diff -Nru cargo-0.25.0/Cargo.toml cargo-0.26.0/Cargo.toml --- cargo-0.25.0/Cargo.toml 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/Cargo.toml 2018-02-26 21:17:55.000000000 +0000 @@ -1,10 +1,10 @@ [package] name = "cargo" -version = "0.25.0" +version = "0.26.0" authors = ["Yehuda Katz ", "Carl Lerche ", "Alex Crichton "] -license = "MIT/Apache-2.0" +license = "MIT OR Apache-2.0" homepage = "https://crates.io" repository = "https://github.com/rust-lang/cargo" documentation = "https://docs.rs/cargo" @@ -18,30 +18,31 @@ [dependencies] atty = "0.2" -crates-io = { path = "src/crates-io", version = "0.14" } +crates-io = { path = "src/crates-io", version = "0.15" } crossbeam = "0.3" crypto-hash = "0.3" curl = "0.4.6" docopt = "0.8.1" -env_logger = "0.4" +env_logger = "0.5" failure = "0.1.1" filetime = "0.1" flate2 = "1.0" fs2 = "0.4" -git2 = "0.6" +git2 = "0.6.11" git2-curl = "0.7" glob = "0.2" -hex = "0.2" +hex = "0.3" home = "0.3" -ignore = "^0.2.2" -jobserver = "0.1.6" +ignore = "0.4" +jobserver = "0.1.9" +lazycell = "0.6" libc = "0.2" libgit2-sys = "0.6" -log = "0.3" +log = "0.4" num_cpus = "1.0" -same-file = "0.1" +same-file = "1" scoped-tls = "0.1" -semver = { version = "0.8.0", features = ["serde"] } +semver = { version = "0.9.0", features = ["serde"] } serde = "1.0" serde_derive = "1.0" serde_ignored = "0.0.4" @@ -54,17 +55,32 @@ url = "1.1" [target.'cfg(target_os = "macos")'.dependencies] -core-foundation = { version = "0.4.4", features = ["mac_os_10_7_support"] } +core-foundation = { version = "0.5.1", features = ["mac_os_10_7_support"] } [target.'cfg(windows)'.dependencies] -kernel32-sys = "0.2" -miow = "0.2" -psapi-sys = "0.1" -winapi = "0.2" +miow = "0.3" + +[target.'cfg(windows)'.dependencies.winapi] +version = "0.3" +features = [ + "handleapi", + "jobapi", + "jobapi2", + "minwindef", + "ntdef", + "processenv", + "processthreadsapi", + "psapi", + "synchapi", + "winerror", + "winbase", + "wincon", + "winnt", +] [dev-dependencies] bufstream = "0.1" -cargotest = { path = "tests/cargotest" } +cargotest = { path = "tests/cargotest", version = "0.1" } filetime = "0.1" hamcrest = "=0.1.1" diff -Nru cargo-0.25.0/debian/changelog cargo-0.26.0/debian/changelog --- cargo-0.25.0/debian/changelog 2018-03-19 18:02:48.000000000 +0000 +++ cargo-0.26.0/debian/changelog 2018-04-13 17:52:29.000000000 +0000 @@ -1,3 +1,24 @@ +cargo (0.26.0-0ubuntu1) bionic; urgency=medium + + * New upstream release (0.26.0) + + * Refresh patches + - update debian/patches/2004_clean-cargo-deps.patch + * Drop patches that are no longer needed or fixed upstream + - remove debian/patches/2003_local-jquery.patch + - remove debian/patches/1002_fix_typo_cargo_search.patch + - remove debian/patches/2005_dont_run_mdbook.patch + - remove debian/patches/2006_disable_wasm32_tests.patch + - update debian/patches/series + * Drop an extra step which is no longer needed when building the + documentation now + - update debian/rules + * Drop the unneeded dependency on libjs-jquery from cargo-doc + - update debian/control + - update debian/rules + + -- Chris Coulson Fri, 13 Apr 2018 18:52:29 +0100 + cargo (0.25.0-1ubuntu1) bionic; urgency=medium [ Rico Tzschichholz ] diff -Nru cargo-0.25.0/debian/control cargo-0.26.0/debian/control --- cargo-0.25.0/debian/control 2018-03-19 18:02:48.000000000 +0000 +++ cargo-0.26.0/debian/control 2018-04-13 17:52:29.000000000 +0000 @@ -58,7 +58,7 @@ Section: doc Architecture: all Build-Profiles: -Depends: ${misc:Depends}, libjs-jquery +Depends: ${misc:Depends} Description: Rust package manager, documentation Cargo is a tool that allows Rust projects to declare their various dependencies, and ensure that you'll always get a repeatable build. diff -Nru cargo-0.25.0/debian/patches/1002_fix_typo_cargo_search.patch cargo-0.26.0/debian/patches/1002_fix_typo_cargo_search.patch --- cargo-0.25.0/debian/patches/1002_fix_typo_cargo_search.patch 2018-03-09 15:39:38.000000000 +0000 +++ cargo-0.26.0/debian/patches/1002_fix_typo_cargo_search.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -Description: Fix typo in cargo search subcommand. - Since the search subcommand where typo happened is - also used in test fix the typo in test also. -Author: Vasudev Kamath -Last-Update: 2017-10-29 - ---- a/src/bin/search.rs -+++ b/src/bin/search.rs -@@ -69,7 +69,7 @@ - let msg = "The flag '--host' is no longer valid. - - Previous versions of Cargo accepted this flag, but it is being --depricated. The flag is being renamed to 'index', as the flag -+deprecated. The flag is being renamed to 'index', as the flag - wants the location of the index in which to search. Please - use '--index' instead. - ---- a/tests/search.rs -+++ b/tests/search.rs -@@ -140,7 +140,7 @@ - [WARNING] The flag '--host' is no longer valid. - - Previous versions of Cargo accepted this flag, but it is being --depricated. The flag is being renamed to 'index', as the flag -+deprecated. The flag is being renamed to 'index', as the flag - wants the location of the index in which to search. Please - use '--index' instead. - -@@ -207,7 +207,7 @@ - [WARNING] The flag '--host' is no longer valid. - - Previous versions of Cargo accepted this flag, but it is being --depricated. The flag is being renamed to 'index', as the flag -+deprecated. The flag is being renamed to 'index', as the flag - wants the location of the index in which to search. Please - use '--index' instead. - diff -Nru cargo-0.25.0/debian/patches/2003_local-jquery.patch cargo-0.26.0/debian/patches/2003_local-jquery.patch --- cargo-0.25.0/debian/patches/2003_local-jquery.patch 2018-03-09 15:39:38.000000000 +0000 +++ cargo-0.26.0/debian/patches/2003_local-jquery.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -Description: Remove remote jquery references -From: Luca Bruno -Forwarded: no ---- -This patch header follows DEP-3: http://dep.debian.net/deps/dep3/ ---- a/src/doc/html-headers.html -+++ b/src/doc/html-headers.html -@@ -1,2 +1,2 @@ -- -+ - diff -Nru cargo-0.25.0/debian/patches/2004_clean-cargo-deps.patch cargo-0.26.0/debian/patches/2004_clean-cargo-deps.patch --- cargo-0.25.0/debian/patches/2004_clean-cargo-deps.patch 2018-03-09 15:39:38.000000000 +0000 +++ cargo-0.26.0/debian/patches/2004_clean-cargo-deps.patch 2018-04-13 17:50:51.000000000 +0000 @@ -11,20 +11,14 @@ This patch header follows DEP-3: http://dep.debian.net/deps/dep3/ --- a/Cargo.toml +++ b/Cargo.toml -@@ -56,11 +56,11 @@ +@@ -57,8 +57,8 @@ url = "1.1" [target.'cfg(target_os = "macos")'.dependencies] - core-foundation = { version = "0.4.4", features = ["mac_os_10_7_support"] } + core-foundation = { version = "0.5.1", features = ["mac_os_10_7_support"] } -[target.'cfg(windows)'.dependencies] --kernel32-sys = "0.2" --miow = "0.2" --psapi-sys = "0.1" --winapi = "0.2" +-miow = "0.3" +#[target.'cfg(windows)'.dependencies] -+#kernel32-sys = "0.2" -+#miow = "0.2" -+#psapi-sys = "0.1" -+#winapi = "0.2" ++#miow = "0.3" - [dev-dependencies] - bufstream = "0.1" + [target.'cfg(windows)'.dependencies.winapi] + version = "0.3" diff -Nru cargo-0.25.0/debian/patches/2005_dont_run_mdbook.patch cargo-0.26.0/debian/patches/2005_dont_run_mdbook.patch --- cargo-0.25.0/debian/patches/2005_dont_run_mdbook.patch 2018-03-09 15:39:38.000000000 +0000 +++ cargo-0.26.0/debian/patches/2005_dont_run_mdbook.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -Description: Don't run mdBook for book preview - Upstream script tries to show preview of generated document - the tool needed is missing and step is not needed during - package build. -Author: Vasudev Kamath -Last-Update: 2017-12-03 - ---- cargo-0.23.0.orig/src/ci/dox.sh -+++ cargo-0.23.0/src/ci/dox.sh -@@ -28,6 +28,6 @@ for doc in $DOCS; do - done - - # Temporary preview for mdBook docs --cd src/doc/book --$HOME/.cargo/bin/mdbook build --no-create --dest-dir ../../../target/doc/book --cd ../../../ -+#cd src/doc/book -+#$HOME/.cargo/bin/mdbook build --no-create --dest-dir ../../../target/doc/book -+#cd ../../../ diff -Nru cargo-0.25.0/debian/patches/2006_disable_wasm32_tests.patch cargo-0.26.0/debian/patches/2006_disable_wasm32_tests.patch --- cargo-0.25.0/debian/patches/2006_disable_wasm32_tests.patch 2018-03-09 15:39:38.000000000 +0000 +++ cargo-0.26.0/debian/patches/2006_disable_wasm32_tests.patch 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -Description: Disable wasm32_final_outputs test - This test depends on emscripten built using fastcomp - a fork of LLVM and is not available in Debian. -Author: Vasudev Kamath -Last-Update: 2017-12-05 - ---- cargo-0.23.0.orig/tests/build.rs -+++ cargo-0.23.0/tests/build.rs -@@ -3479,7 +3479,6 @@ fn cdylib_final_outputs() { - } - } - --#[test] - fn wasm32_final_outputs() { - use cargo::core::{Shell, Target, Workspace}; - use cargo::ops::{self, BuildConfig, Context, CompileMode, CompileOptions, Kind, Unit}; diff -Nru cargo-0.25.0/debian/patches/series cargo-0.26.0/debian/patches/series --- cargo-0.25.0/debian/patches/series 2018-03-09 15:39:38.000000000 +0000 +++ cargo-0.26.0/debian/patches/series 2018-04-13 17:52:29.000000000 +0000 @@ -1,7 +1,3 @@ 2004_clean-cargo-deps.patch -2003_local-jquery.patch 2001_use-system-libgit2.patch 2002_disable-net-tests.patch -1002_fix_typo_cargo_search.patch -2005_dont_run_mdbook.patch -2006_disable_wasm32_tests.patch diff -Nru cargo-0.25.0/debian/rules cargo-0.26.0/debian/rules --- cargo-0.25.0/debian/rules 2018-03-19 18:02:44.000000000 +0000 +++ cargo-0.26.0/debian/rules 2018-04-13 17:52:29.000000000 +0000 @@ -63,10 +63,6 @@ override_dh_auto_build-indep: ifeq (,$(findstring nodoc,$(DEB_BUILD_PROFILES))) $(CARGO) doc $(CARGOFLAGS) - # Extra instructions from README.md, unfortunately not done by "cargo doc" - sh src/ci/dox.sh - # Post-processing for Debian - cd target/doc/ && rm -f jquery.js && ln -s /usr/share/javascript/jquery/jquery.js endif RUN_TESTS = \ diff -Nru cargo-0.25.0/README.md cargo-0.26.0/README.md --- cargo-0.25.0/README.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/README.md 2018-02-26 21:17:55.000000000 +0000 @@ -2,13 +2,15 @@ Cargo downloads your Rust project’s dependencies and compiles your project. -Learn more at http://doc.crates.io/ +Learn more at https://doc.rust-lang.org/cargo/ ## Code Status [![Build Status](https://travis-ci.org/rust-lang/cargo.svg?branch=master)](https://travis-ci.org/rust-lang/cargo) [![Build Status](https://ci.appveyor.com/api/projects/status/github/rust-lang/cargo?branch=master&svg=true)](https://ci.appveyor.com/project/rust-lang-libs/cargo) +Code documentation: https://docs.rs/cargo/ + ## Installing Cargo Cargo is distributed by default with Rust, so if you've got `rustc` installed diff -Nru cargo-0.25.0/src/bin/bench.rs cargo-0.26.0/src/bin/bench.rs --- cargo-0.25.0/src/bin/bench.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/bin/bench.rs 2018-02-26 21:17:55.000000000 +0000 @@ -37,15 +37,18 @@ flag_exclude: Vec, #[serde(rename = "flag_Z")] flag_z: Vec, + #[serde(rename = "arg_BENCHNAME")] + arg_benchname: Option, } pub const USAGE: &'static str = " Execute all benchmarks of a local package Usage: - cargo bench [options] [--] [...] + cargo bench [options] [BENCHNAME] [--] [...] Options: + BENCHNAME If specified, only run benches containing this string in their names -h, --help Print this message --lib Benchmark only this package's library --bin NAME ... Benchmark only the specified binary @@ -95,7 +98,7 @@ Compilation can be customized with the `bench` profile in the manifest. "; -pub fn execute(options: Options, config: &mut Config) -> CliResult { +pub fn execute(mut options: Options, config: &mut Config) -> CliResult { debug!("executing; cmd=cargo-bench; args={:?}", env::args().collect::>()); @@ -139,6 +142,10 @@ }, }; + if let Some(test) = options.arg_benchname.take() { + options.arg_args.insert(0, test); + } + let err = ops::run_benches(&ws, &ops, &options.arg_args)?; match err { None => Ok(()), diff -Nru cargo-0.25.0/src/bin/cargo.rs cargo-0.26.0/src/bin/cargo.rs --- cargo-0.25.0/src/bin/cargo.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/bin/cargo.rs 2018-02-26 21:17:55.000000000 +0000 @@ -75,7 +75,7 @@ "; fn main() { - env_logger::init().unwrap(); + env_logger::init(); let mut config = match Config::default() { Ok(cfg) => cfg, diff -Nru cargo-0.25.0/src/bin/init.rs cargo-0.26.0/src/bin/init.rs --- cargo-0.25.0/src/bin/init.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/bin/init.rs 2018-02-26 21:17:55.000000000 +0000 @@ -32,8 +32,8 @@ control system (git, hg, pijul, or fossil) or do not initialize any version control at all (none), overriding a global configuration. - --bin Use a binary (application) template - --lib Use a library template [default] + --bin Use a binary (application) template [default] + --lib Use a library template --name NAME Set the resulting package name -v, --verbose ... Use verbose output (-vv very verbose/build.rs output) -q, --quiet No output printed to stdout @@ -56,17 +56,14 @@ let path = &arg_path.unwrap_or_else(|| String::from(".")); let opts = ops::NewOptions::new(flag_vcs, - flag_bin, - flag_lib, - path, - flag_name.as_ref().map(|s| s.as_ref())); + flag_bin, + flag_lib, + path, + flag_name.as_ref().map(|s| s.as_ref()))?; - let opts_lib = opts.lib; ops::init(&opts, config)?; - config.shell().status("Created", format!("{} project", - if opts_lib { "library" } - else {"binary (application)"}))?; + config.shell().status("Created", format!("{} project", opts.kind))?; Ok(()) } diff -Nru cargo-0.25.0/src/bin/new.rs cargo-0.26.0/src/bin/new.rs --- cargo-0.25.0/src/bin/new.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/bin/new.rs 2018-02-26 21:17:55.000000000 +0000 @@ -32,8 +32,8 @@ control system (git, hg, pijul, or fossil) or do not initialize any version control at all (none), overriding a global configuration. - --bin Use a binary (application) template - --lib Use a library template [default] + --bin Use a binary (application) template [default] + --lib Use a library template --name NAME Set the resulting package name, defaults to the value of -v, --verbose ... Use verbose output (-vv very verbose/build.rs output) -q, --quiet No output printed to stdout @@ -58,15 +58,11 @@ flag_bin, flag_lib, &arg_path, - flag_name.as_ref().map(|s| s.as_ref())); + flag_name.as_ref().map(|s| s.as_ref()))?; - let opts_lib = opts.lib; ops::new(&opts, config)?; - config.shell().status("Created", format!("{} `{}` project", - if opts_lib { "library" } - else {"binary (application)"}, - arg_path))?; + config.shell().status("Created", format!("{} `{}` project", opts.kind, arg_path))?; Ok(()) } diff -Nru cargo-0.25.0/src/bin/search.rs cargo-0.26.0/src/bin/search.rs --- cargo-0.25.0/src/bin/search.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/bin/search.rs 2018-02-26 21:17:55.000000000 +0000 @@ -6,7 +6,7 @@ #[derive(Deserialize)] pub struct Options { flag_index: Option, - flag_host: Option, // TODO: Depricated, remove + flag_host: Option, // TODO: Deprecated, remove flag_verbose: u32, flag_quiet: Option, flag_color: Option, @@ -49,7 +49,7 @@ &options.flag_z)?; let Options { flag_index: index, - flag_host: host, // TODO: Depricated, remove + flag_host: host, // TODO: Deprecated, remove flag_limit: limit, arg_query: query, flag_registry: registry, @@ -61,7 +61,7 @@ requires -Zunstable-options to use.").into()) } - // TODO: Depricated + // TODO: Deprecated // remove once it has been decided --host can be safely removed // We may instead want to repurpose the host flag, as // mentioned in this issue @@ -70,7 +70,7 @@ let msg = "The flag '--host' is no longer valid. Previous versions of Cargo accepted this flag, but it is being -depricated. The flag is being renamed to 'index', as the flag +deprecated. The flag is being renamed to 'index', as the flag wants the location of the index in which to search. Please use '--index' instead. diff -Nru cargo-0.25.0/src/bin/test.rs cargo-0.26.0/src/bin/test.rs --- cargo-0.25.0/src/bin/test.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/bin/test.rs 2018-02-26 21:17:55.000000000 +0000 @@ -39,15 +39,18 @@ flag_exclude: Vec, #[serde(rename = "flag_Z")] flag_z: Vec, + #[serde(rename = "arg_TESTNAME")] + arg_testname: Option, } pub const USAGE: &'static str = " Execute all unit and integration tests of a local package Usage: - cargo test [options] [--] [...] + cargo test [options] [TESTNAME] [--] [...] Options: + TESTNAME If specified, only run tests containing this string in their names -h, --help Print this message --lib Test only this package's library --doc Test only this library's documentation @@ -116,7 +119,7 @@ cargo test -- --help "; -pub fn execute(options: Options, config: &mut Config) -> CliResult { +pub fn execute(mut options: Options, config: &mut Config) -> CliResult { debug!("executing; cmd=cargo-test; args={:?}", env::args().collect::>()); @@ -172,6 +175,12 @@ }, }; + // TESTNAME is actually an argument of the test binary, but it's + // important so we explicitly mention it and reconfigure + if let Some(test) = options.arg_testname.take() { + options.arg_args.insert(0, test); + } + let err = ops::run_tests(&ws, &ops, &options.arg_args)?; match err { None => Ok(()), diff -Nru cargo-0.25.0/src/cargo/core/dependency.rs cargo-0.26.0/src/cargo/core/dependency.rs --- cargo-0.25.0/src/cargo/core/dependency.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/core/dependency.rs 2018-02-26 21:17:55.000000000 +0000 @@ -22,6 +22,7 @@ struct Inner { name: String, source_id: SourceId, + registry_id: Option, req: VersionReq, specified_req: bool, kind: Kind, @@ -172,6 +173,7 @@ inner: Rc::new(Inner { name: name.to_string(), source_id: source_id.clone(), + registry_id: None, req: VersionReq::any(), kind: Kind::Normal, only_match_name: true, @@ -196,6 +198,15 @@ &self.inner.source_id } + pub fn registry_id(&self) -> Option<&SourceId> { + self.inner.registry_id.as_ref() + } + + pub fn set_registry_id(&mut self, registry_id: &SourceId) -> &mut Dependency { + Rc::make_mut(&mut self.inner).registry_id = Some(registry_id.clone()); + self + } + pub fn kind(&self) -> Kind { self.inner.kind } @@ -254,6 +265,11 @@ pub fn lock_to(&mut self, id: &PackageId) -> &mut Dependency { assert_eq!(self.inner.source_id, *id.source_id()); assert!(self.inner.req.matches(id.version())); + trace!("locking dep from `{}` with `{}` at {} to {}", + self.name(), + self.version_req(), + self.source_id(), + id); self.set_version_req(VersionReq::exact(id.version())) .set_source_id(id.source_id().clone()) } diff -Nru cargo-0.25.0/src/cargo/core/features.rs cargo-0.26.0/src/cargo/core/features.rs --- cargo-0.25.0/src/cargo/core/features.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/core/features.rs 2018-02-26 21:17:55.000000000 +0000 @@ -40,9 +40,40 @@ //! we'll be sure to update this documentation! use std::env; +use std::fmt; +use std::str::FromStr; use util::errors::CargoResult; +/// The epoch of the compiler (RFC 2052) +#[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, Eq, PartialEq)] +#[derive(Serialize, Deserialize)] +pub enum Epoch { + /// The 2015 epoch + Epoch2015, + /// The 2018 epoch + Epoch2018, +} + +impl fmt::Display for Epoch { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Epoch::Epoch2015 => f.write_str("2015"), + Epoch::Epoch2018 => f.write_str("2018"), + } + } +} +impl FromStr for Epoch { + type Err = (); + fn from_str(s: &str) -> Result { + match s { + "2015" => Ok(Epoch::Epoch2015), + "2018" => Ok(Epoch::Epoch2018), + _ => Err(()) + } + } +} + enum Status { Stable, Unstable, @@ -125,6 +156,9 @@ // Downloading packages from alternative registry indexes. [unstable] alternative_registries: bool, + + // Using epochs + [unstable] epoch: bool, } } @@ -201,6 +235,10 @@ bail!("{}", msg); } } + + pub fn is_enabled(&self, feature: &Feature) -> bool { + feature.is_enabled(self) + } } /// A parsed representation of all unstable flags that Cargo accepts. @@ -232,6 +270,8 @@ pub struct CliUnstable { pub print_im_a_teapot: bool, pub unstable_options: bool, + pub offline: bool, + pub no_index_update: bool, } impl CliUnstable { @@ -262,6 +302,8 @@ match k { "print-im-a-teapot" => self.print_im_a_teapot = parse_bool(v)?, "unstable-options" => self.unstable_options = true, + "offline" => self.offline = true, + "no-index-update" => self.no_index_update = true, _ => bail!("unknown `-Z` flag specified: {}", k), } diff -Nru cargo-0.25.0/src/cargo/core/manifest.rs cargo-0.26.0/src/cargo/core/manifest.rs --- cargo-0.25.0/src/cargo/core/manifest.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/core/manifest.rs 2018-02-26 21:17:55.000000000 +0000 @@ -9,7 +9,7 @@ use url::Url; use core::{Dependency, PackageId, Summary, SourceId, PackageIdSpec}; -use core::{WorkspaceConfig, Features, Feature}; +use core::{WorkspaceConfig, Epoch, Features, Feature}; use util::Config; use util::toml::TomlManifest; use util::errors::*; @@ -36,6 +36,7 @@ workspace: WorkspaceConfig, original: Rc, features: Features, + epoch: Epoch, im_a_teapot: Option, } @@ -156,7 +157,7 @@ pub struct Profile { pub opt_level: String, #[serde(skip_serializing)] - pub lto: bool, + pub lto: Lto, #[serde(skip_serializing)] pub codegen_units: Option, // None = use rustc default #[serde(skip_serializing)] @@ -181,6 +182,12 @@ pub incremental: bool, } +#[derive(Clone, PartialEq, Eq, Debug, Hash)] +pub enum Lto { + Bool(bool), + Named(String), +} + #[derive(Default, Clone, Debug, PartialEq, Eq)] pub struct Profiles { pub release: Profile, @@ -233,7 +240,7 @@ /// Serialized as a list of strings for historical reasons. kind: &'a TargetKind, /// Corresponds to `--crate-type` compiler attribute. - /// See https://doc.rust-lang.org/reference.html#linkage + /// See https://doc.rust-lang.org/reference/linkage.html crate_types: Vec<&'a str>, name: &'a str, src_path: &'a PathBuf, @@ -263,6 +270,7 @@ patch: HashMap>, workspace: WorkspaceConfig, features: Features, + epoch: Epoch, im_a_teapot: Option, original: Rc) -> Manifest { Manifest { @@ -279,6 +287,7 @@ patch: patch, workspace: workspace, features: features, + epoch: epoch, original: original, im_a_teapot: im_a_teapot, } @@ -350,6 +359,10 @@ } } } + + pub fn epoch(&self) -> Epoch { + self.epoch + } } impl VirtualManifest { @@ -702,7 +715,7 @@ fn default() -> Profile { Profile { opt_level: "0".to_string(), - lto: false, + lto: Lto::Bool(false), codegen_units: None, rustc_args: None, rustdoc_args: None, diff -Nru cargo-0.25.0/src/cargo/core/mod.rs cargo-0.26.0/src/cargo/core/mod.rs --- cargo-0.25.0/src/cargo/core/mod.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/core/mod.rs 2018-02-26 21:17:55.000000000 +0000 @@ -1,5 +1,5 @@ pub use self::dependency::Dependency; -pub use self::features::{Features, Feature, CliUnstable}; +pub use self::features::{Epoch, Features, Feature, CliUnstable}; pub use self::manifest::{EitherManifest, VirtualManifest}; pub use self::manifest::{Manifest, Target, TargetKind, Profile, LibKind, Profiles}; pub use self::package::{Package, PackageSet}; diff -Nru cargo-0.25.0/src/cargo/core/package.rs cargo-0.26.0/src/cargo/core/package.rs --- cargo-0.25.0/src/cargo/core/package.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/core/package.rs 2018-02-26 21:17:55.000000000 +0000 @@ -7,11 +7,12 @@ use semver::Version; use serde::ser; use toml; +use lazycell::LazyCell; use core::{Dependency, Manifest, PackageId, SourceId, Target}; use core::{Summary, SourceMap}; use ops; -use util::{Config, LazyCell, internal, lev_distance}; +use util::{Config, internal, lev_distance}; use util::errors::{CargoResult, CargoResultExt}; /// Information about a package that is available somewhere in the file system. @@ -95,7 +96,7 @@ pub fn manifest_path(&self) -> &Path { &self.manifest_path } /// Get the name of the package pub fn name(&self) -> &str { self.package_id().name() } - /// Get the PackageId object for the package (fully defines a packge) + /// Get the PackageId object for the package (fully defines a package) pub fn package_id(&self) -> &PackageId { self.manifest.package_id() } /// Get the root folder of the package pub fn root(&self) -> &Path { self.manifest_path.parent().unwrap() } @@ -134,8 +135,8 @@ } } - pub fn to_registry_toml(&self) -> CargoResult { - let manifest = self.manifest().original().prepare_for_publish(); + pub fn to_registry_toml(&self, config: &Config) -> CargoResult { + let manifest = self.manifest().original().prepare_for_publish(config)?; let toml = toml::to_string(&manifest)?; Ok(format!("\ # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO\n\ diff -Nru cargo-0.25.0/src/cargo/core/registry.rs cargo-0.26.0/src/cargo/core/registry.rs --- cargo-0.25.0/src/cargo/core/registry.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/core/registry.rs 2018-02-26 21:17:55.000000000 +0000 @@ -88,7 +88,10 @@ locked: LockedMap, source_config: SourceConfigMap<'cfg>, + patches: HashMap>, + patches_locked: bool, + patches_available: HashMap>, } type LockedMap = HashMap)>>>; @@ -110,6 +113,8 @@ source_config: source_config, locked: HashMap::new(), patches: HashMap::new(), + patches_locked: false, + patches_available: HashMap::new(), }) } @@ -188,9 +193,50 @@ sub_vec.push((id, deps)); } + /// Insert a `[patch]` section into this registry. + /// + /// This method will insert a `[patch]` section for the `url` specified, + /// with the given list of dependencies. The `url` specified is the URL of + /// the source to patch (for example this is `crates-io` in the manifest). + /// The `deps` is an array of all the entries in the `[patch]` section of + /// the manifest. + /// + /// Here the `deps` will be resolved to a precise version and stored + /// internally for future calls to `query` below. It's expected that `deps` + /// have had `lock_to` call already, if applicable. (e.g. if a lock file was + /// already present). + /// + /// Note that the patch list specified here *will not* be available to + /// `query` until `lock_patches` is called below, which should be called + /// once all patches have been added. pub fn patch(&mut self, url: &Url, deps: &[Dependency]) -> CargoResult<()> { - let deps = deps.iter().map(|dep| { - let mut summaries = self.query_vec(dep)?.into_iter(); + // First up we need to actually resolve each `deps` specification to + // precisely one summary. We're not using the `query` method below as it + // internally uses maps we're building up as part of this method + // (`patches_available` and `patches). Instead we're going straight to + // the source to load information from it. + // + // Remember that each dependency listed in `[patch]` has to resolve to + // precisely one package, so that's why we're just creating a flat list + // of summaries which should be the same length as `deps` above. + let unlocked_summaries = deps.iter().map(|dep| { + debug!("registring a patch for `{}` with `{}`", + url, + dep.name()); + + // Go straight to the source for resolving `dep`. Load it as we + // normally would and then ask it directly for the list of summaries + // corresponding to this `dep`. + self.ensure_loaded(dep.source_id(), Kind::Normal).chain_err(|| { + format_err!("failed to load source for a dependency \ + on `{}`", dep.name()) + })?; + + let mut summaries = self.sources.get_mut(dep.source_id()) + .expect("loaded source not present") + .query_vec(dep)? + .into_iter(); + let summary = match summaries.next() { Some(summary) => summary, None => { @@ -214,11 +260,38 @@ format_err!("failed to resolve patches for `{}`", url) })?; - self.patches.insert(url.clone(), deps); + // Note that we do not use `lock` here to lock summaries! That step + // happens later once `lock_patches` is invoked. In the meantime though + // we want to fill in the `patches_available` map (later used in the + // `lock` method) and otherwise store the unlocked summaries in + // `patches` to get locked in a future call to `lock_patches`. + let ids = unlocked_summaries.iter() + .map(|s| s.package_id()) + .cloned() + .collect(); + self.patches_available.insert(url.clone(), ids); + self.patches.insert(url.clone(), unlocked_summaries); Ok(()) } + /// Lock all patch summaries added via `patch`, making them available to + /// resolution via `query`. + /// + /// This function will internally `lock` each summary added via `patch` + /// above now that the full set of `patch` packages are known. This'll allow + /// us to correctly resolve overridden dependencies between patches + /// hopefully! + pub fn lock_patches(&mut self) { + assert!(!self.patches_locked); + for summaries in self.patches.values_mut() { + for summary in summaries { + *summary = lock(&self.locked, &self.patches_available, summary.clone()); + } + } + self.patches_locked = true; + } + pub fn patches(&self) -> &HashMap> { &self.patches } @@ -271,7 +344,8 @@ /// possible. If we're unable to map a dependency though, we just pass it on /// through. pub fn lock(&self, summary: Summary) -> Summary { - lock(&self.locked, &self.patches, summary) + assert!(self.patches_locked); + lock(&self.locked, &self.patches_available, summary) } fn warn_bad_override(&self, @@ -323,6 +397,7 @@ fn query(&mut self, dep: &Dependency, f: &mut FnMut(Summary)) -> CargoResult<()> { + assert!(self.patches_locked); let (override_summary, n, to_warn) = { // Look for an override and get ready to query the real source. let override_summary = self.query_overrides(dep)?; @@ -357,8 +432,12 @@ } } else { if !patches.is_empty() { - debug!("found {} patches with an unlocked dep, \ - looking at sources", patches.len()); + debug!("found {} patches with an unlocked dep on `{}` at {} \ + with `{}`, \ + looking at sources", patches.len(), + dep.name(), + dep.source_id(), + dep.version_req()); } // Ensure the requested source_id is loaded @@ -387,7 +466,7 @@ // version as something in `patches` that we've // already selected, then we skip this `summary`. let locked = &self.locked; - let all_patches = &self.patches; + let all_patches = &self.patches_available; return source.query(dep, &mut |summary| { for patch in patches.iter() { let patch = patch.package_id().version(); @@ -437,7 +516,7 @@ } fn lock(locked: &LockedMap, - patches: &HashMap>, + patches: &HashMap>, summary: Summary) -> Summary { let pair = locked.get(summary.source_id()).and_then(|map| { map.get(summary.name()) @@ -504,24 +583,24 @@ // this dependency. let v = patches.get(dep.source_id().url()).map(|vec| { let dep2 = dep.clone(); - let mut iter = vec.iter().filter(move |s| { - dep2.name() == s.package_id().name() && - dep2.version_req().matches(s.package_id().version()) + let mut iter = vec.iter().filter(move |p| { + dep2.name() == p.name() && + dep2.version_req().matches(p.version()) }); (iter.next(), iter) }); - if let Some((Some(summary), mut remaining)) = v { + if let Some((Some(patch_id), mut remaining)) = v { assert!(remaining.next().is_none()); - let patch_source = summary.package_id().source_id(); + let patch_source = patch_id.source_id(); let patch_locked = locked.get(patch_source).and_then(|m| { - m.get(summary.package_id().name()) + m.get(patch_id.name()) }).map(|list| { - list.iter().any(|&(ref id, _)| id == summary.package_id()) + list.iter().any(|&(ref id, _)| id == patch_id) }).unwrap_or(false); if patch_locked { - trace!("\tthird hit on {}", summary.package_id()); - let req = VersionReq::exact(summary.package_id().version()); + trace!("\tthird hit on {}", patch_id); + let req = VersionReq::exact(patch_id.version()); let mut dep = dep.clone(); dep.set_version_req(req); return dep diff -Nru cargo-0.25.0/src/cargo/core/resolver/mod.rs cargo-0.26.0/src/cargo/core/resolver/mod.rs --- cargo-0.25.0/src/cargo/core/resolver/mod.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/core/resolver/mod.rs 2018-02-26 21:17:55.000000000 +0000 @@ -118,28 +118,8 @@ impl Resolve { /// Resolves one of the paths from the given dependent package up to /// the root. - pub fn path_to_top<'a>(&'a self, mut pkg: &'a PackageId) -> Vec<&'a PackageId> { - // Note that this implementation isn't the most robust per se, we'll - // likely have to tweak this over time. For now though it works for what - // it's used for! - let mut result = vec![pkg]; - let first_pkg_depending_on = |pkg: &PackageId| { - self.graph.get_nodes() - .iter() - .filter(|&(_node, adjacent)| adjacent.contains(pkg)) - .next() - .map(|p| p.0) - }; - while let Some(p) = first_pkg_depending_on(pkg) { - // Note that we can have "cycles" introduced through dev-dependency - // edges, so make sure we don't loop infinitely. - if result.contains(&p) { - break - } - result.push(p); - pkg = p; - } - result + pub fn path_to_top<'a>(&'a self, pkg: &'a PackageId) -> Vec<&'a PackageId> { + self.graph.path_to_top(pkg) } pub fn register_used_patches(&mut self, patches: &HashMap>) { @@ -620,7 +600,7 @@ // You'll note that a few stacks are maintained on the side, which might // seem odd when this algorithm looks like it could be implemented // recursively. While correct, this is implemented iteratively to avoid - // blowing the stack (the recusion depth is proportional to the size of the + // blowing the stack (the recursion depth is proportional to the size of the // input). // // The general sketch of this loop is to run until there are no dependencies @@ -722,7 +702,7 @@ None => return Err(activation_error(&cx, registry, &parent, &dep, cx.prev_active(&dep), - &candidates)), + &candidates, config)), Some(candidate) => candidate, } } @@ -745,9 +725,16 @@ Ok(cx) } -// Searches up `backtrack_stack` until it finds a dependency with remaining -// candidates. Resets `cx` and `remaining_deps` to that level and returns the +// Looks through the states in `backtrack_stack` for dependencies with +// remaining candidates. For each one, also checks if rolling back +// could change the outcome of the failed resolution that caused backtracking +// in the first place - namely, if we've backtracked past the parent of the +// failed dep, or the previous number of activations of the failed dep has +// changed (possibly relaxing version constraints). If the outcome could differ, +// resets `cx` and `remaining_deps` to that level and returns the // next candidate. If all candidates have been exhausted, returns None. +// Read https://github.com/rust-lang/cargo/pull/4834#issuecomment-362871537 for +// a more detailed explanation of the logic here. fn find_candidate<'a>(backtrack_stack: &mut Vec>, cx: &mut Context<'a>, remaining_deps: &mut BinaryHeap, @@ -755,12 +742,21 @@ cur: &mut usize, dep: &mut Dependency, features: &mut Rc>) -> Option { + let num_dep_prev_active = cx.prev_active(dep).len(); while let Some(mut frame) = backtrack_stack.pop() { let (next, has_another) = { let prev_active = frame.context_backup.prev_active(&frame.dep); (frame.remaining_candidates.next(prev_active), frame.remaining_candidates.clone().next(prev_active).is_some()) }; + let cur_num_dep_prev_active = frame.context_backup.prev_active(dep).len(); + // Activations should monotonically decrease during backtracking + assert!(cur_num_dep_prev_active <= num_dep_prev_active); + let maychange = !frame.context_backup.is_active(parent) || + cur_num_dep_prev_active != num_dep_prev_active; + if !maychange { + continue + } if let Some(candidate) = next { *cur = frame.cur; if has_another { @@ -788,31 +784,30 @@ parent: &Summary, dep: &Dependency, prev_active: &[Summary], - candidates: &[Candidate]) -> CargoError { + candidates: &[Candidate], + config: Option<&Config>) -> CargoError { + let graph = cx.graph(); + let describe_path = |pkgid: &PackageId| -> String { + use std::fmt::Write; + let dep_path = graph.path_to_top(pkgid); + let mut dep_path_desc = format!("package `{}`", dep_path[0]); + for dep in dep_path.iter().skip(1) { + write!(dep_path_desc, + "\n ... which is depended on by `{}`", + dep).unwrap(); + } + dep_path_desc + }; if !candidates.is_empty() { - let mut msg = format!("failed to select a version for `{}` \ - (required by `{}`):\n\ + let mut msg = format!("failed to select a version for `{0}`\n\ all possible versions conflict with \ - previously selected versions of `{}`", - dep.name(), parent.name(), + previously selected versions of `{0}`\n", dep.name()); - let graph = cx.graph(); - 'outer: for v in prev_active.iter() { - for node in graph.iter() { - let edges = match graph.edges(node) { - Some(edges) => edges, - None => continue, - }; - for edge in edges { - if edge != v.package_id() { continue } - - msg.push_str(&format!("\n version {} in use by {}", - v.version(), edge)); - continue 'outer; - } - } - msg.push_str(&format!("\n version {} in use by ??", - v.version())); + msg.push_str("required by "); + msg.push_str(&describe_path(parent.package_id())); + for v in prev_active.iter() { + msg.push_str("\n previously selected "); + msg.push_str(&describe_path(v.package_id())); } msg.push_str(&format!("\n possible versions to select: {}", @@ -843,7 +838,7 @@ b.version().cmp(a.version()) }); - let msg = if !candidates.is_empty() { + let mut msg = if !candidates.is_empty() { let versions = { let mut versions = candidates.iter().take(3).map(|cand| { cand.version().to_string() @@ -856,15 +851,15 @@ versions.join(", ") }; - let mut msg = format!("no matching version `{}` found for package `{}` \ - (required by `{}`)\n\ + let mut msg = format!("no matching version `{}` found for package `{}`\n\ location searched: {}\n\ - versions found: {}", + versions found: {}\n", dep.version_req(), dep.name(), - parent.name(), dep.source_id(), versions); + msg.push_str("required by "); + msg.push_str(&describe_path(parent.package_id())); // If we have a path dependency with a locked version, then this may // indicate that we updated a sub-package and forgot to run `cargo @@ -877,15 +872,24 @@ msg } else { - format!("no matching package named `{}` found \ - (required by `{}`)\n\ - location searched: {}\n\ - version required: {}", - dep.name(), parent.name(), - dep.source_id(), - dep.version_req()) + let mut msg = format!("no matching package named `{}` found\n\ + location searched: {}\n", + dep.name(), dep.source_id()); + msg.push_str("required by "); + msg.push_str(&describe_path(parent.package_id())); + + msg }; + if let Some(config) = config { + if config.cli_unstable().offline { + msg.push_str("\nAs a reminder, you're using offline mode (-Z offline) \ + which can sometimes cause surprising resolution failures, \ + if this error is too confusing you may with to retry \ + without the offline flag."); + } + } + format_err!("{}", msg) } @@ -1063,7 +1067,7 @@ registry: &mut Registry, candidate: &Summary, method: &Method) -> CargoResult> { - // First, figure out our set of dependencies based on the requsted set + // First, figure out our set of dependencies based on the requested set // of features. This also calculates what features we're going to enable // for our own dependencies. let deps = self.resolve_features(candidate, method)?; @@ -1168,6 +1172,14 @@ .unwrap_or(&[]) } + fn is_active(&mut self, summary: &Summary) -> bool { + let id = summary.package_id(); + self.activations.get(id.name()) + .and_then(|v| v.get(id.source_id())) + .map(|v| v.iter().any(|s| s == summary)) + .unwrap_or(false) + } + /// Return all dependencies and the features we want from them. fn resolve_features<'b>(&mut self, s: &'b Summary, diff -Nru cargo-0.25.0/src/cargo/core/shell.rs cargo-0.26.0/src/cargo/core/shell.rs --- cargo-0.25.0/src/cargo/core/shell.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/core/shell.rs 2018-02-26 21:17:55.000000000 +0000 @@ -317,16 +317,18 @@ #[cfg(windows)] mod imp { - use std::mem; - extern crate winapi; - extern crate kernel32; + + use std::mem; + use self::winapi::um::processenv::*; + use self::winapi::um::winbase::*; + use self::winapi::um::wincon::*; pub fn stderr_width() -> Option { unsafe { - let stdout = kernel32::GetStdHandle(winapi::STD_ERROR_HANDLE); - let mut csbi: winapi::CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed(); - if kernel32::GetConsoleScreenBufferInfo(stdout, &mut csbi) == 0 { + let stdout = GetStdHandle(STD_ERROR_HANDLE); + let mut csbi: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed(); + if GetConsoleScreenBufferInfo(stdout, &mut csbi) == 0 { return None } Some((csbi.srWindow.Right - csbi.srWindow.Left) as usize) diff -Nru cargo-0.25.0/src/cargo/core/summary.rs cargo-0.26.0/src/cargo/core/summary.rs --- cargo-0.25.0/src/cargo/core/summary.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/core/summary.rs 2018-02-26 21:17:55.000000000 +0000 @@ -7,7 +7,7 @@ use util::CargoResult; -/// Subset of a `Manifest`. Contains only the most important informations about +/// Subset of a `Manifest`. Contains only the most important information about /// a package. /// /// Summaries are cloned, and should not be mutated after creation diff -Nru cargo-0.25.0/src/cargo/lib.rs cargo-0.26.0/src/cargo/lib.rs --- cargo-0.25.0/src/cargo/lib.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/lib.rs 2018-02-26 21:17:55.000000000 +0000 @@ -21,6 +21,7 @@ extern crate home; extern crate ignore; extern crate jobserver; +extern crate lazycell; extern crate libc; extern crate libgit2_sys; extern crate num_cpus; @@ -142,7 +143,7 @@ } else if fatal { drop(shell.error(&error)) } else { - drop(writeln!(shell.err(), "{}", error)) + println!("{}", error); } if !handle_cause(&error, shell) || hide { diff -Nru cargo-0.25.0/src/cargo/ops/cargo_doc.rs cargo-0.26.0/src/cargo/ops/cargo_doc.rs --- cargo-0.25.0/src/cargo/ops/cargo_doc.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/ops/cargo_doc.rs 2018-02-26 21:17:55.000000000 +0000 @@ -59,7 +59,10 @@ if options.open_result { let name = if pkgs.len() > 1 { - bail!("Passing multiple packages and `open` is not supported") + bail!("Passing multiple packages and `open` is not supported.\n\ + Please re-run this command with `-p ` where `` \ + is one of the following:\n {}", + pkgs.iter().map(|p| p.name()).collect::>().join("\n ")); } else if pkgs.len() == 1 { pkgs[0].name().replace("-", "_") } else { diff -Nru cargo-0.25.0/src/cargo/ops/cargo_generate_lockfile.rs cargo-0.26.0/src/cargo/ops/cargo_generate_lockfile.rs --- cargo-0.25.0/src/cargo/ops/cargo_generate_lockfile.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/ops/cargo_generate_lockfile.rs 2018-02-26 21:17:55.000000000 +0000 @@ -19,9 +19,14 @@ pub fn generate_lockfile(ws: &Workspace) -> CargoResult<()> { let mut registry = PackageRegistry::new(ws.config())?; - let resolve = ops::resolve_with_previous(&mut registry, ws, + let resolve = ops::resolve_with_previous(&mut registry, + ws, Method::Everything, - None, None, &[], true)?; + None, + None, + &[], + true, + true)?; ops::write_pkg_lockfile(ws, &resolve)?; Ok(()) } @@ -37,6 +42,10 @@ bail!("you can't generate a lockfile for an empty workspace.") } + if opts.config.cli_unstable().offline { + bail!("you can't update in the offline mode"); + } + let previous_resolve = match ops::load_pkg_lockfile(ws)? { Some(resolve) => resolve, None => return generate_lockfile(ws), @@ -77,12 +86,13 @@ } let resolve = ops::resolve_with_previous(&mut registry, - ws, - Method::Everything, - Some(&previous_resolve), - Some(&to_avoid), - &[], - true)?; + ws, + Method::Everything, + Some(&previous_resolve), + Some(&to_avoid), + &[], + true, + true)?; // Summarize what is changing for the user. let print_change = |status: &str, msg: String, color: Color| { diff -Nru cargo-0.25.0/src/cargo/ops/cargo_new.rs cargo-0.26.0/src/cargo/ops/cargo_new.rs --- cargo-0.25.0/src/cargo/ops/cargo_new.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/ops/cargo_new.rs 2018-02-26 21:17:55.000000000 +0000 @@ -1,6 +1,7 @@ use std::collections::BTreeMap; use std::env; use std::fs; +use std::fmt; use std::path::Path; use serde::{Deserialize, Deserializer}; @@ -20,14 +21,35 @@ #[derive(Clone, Copy, Debug, PartialEq)] pub enum VersionControl { Git, Hg, Pijul, Fossil, NoVcs } +#[derive(Debug)] pub struct NewOptions<'a> { pub version_control: Option, - pub bin: bool, - pub lib: bool, + pub kind: NewProjectKind, pub path: &'a str, pub name: Option<&'a str>, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NewProjectKind { + Bin, + Lib, +} + +impl NewProjectKind { + fn is_bin(&self) -> bool { + *self == NewProjectKind::Bin + } +} + +impl fmt::Display for NewProjectKind { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + NewProjectKind::Bin => "binary (application)", + NewProjectKind::Lib => "library", + }.fmt(f) + } +} + struct SourceFileInformation { relative_path: String, target_name: String, @@ -61,26 +83,21 @@ impl<'a> NewOptions<'a> { pub fn new(version_control: Option, - bin: bool, - lib: bool, - path: &'a str, - name: Option<&'a str>) -> NewOptions<'a> { - - // default to lib - let is_lib = if !bin { - true - } - else { - lib + bin: bool, + lib: bool, + path: &'a str, + name: Option<&'a str>) -> CargoResult> { + + let kind = match (bin, lib) { + (true, true) => bail!("can't specify both lib and binary outputs"), + (true, false) => NewProjectKind::Bin, + (false, true) => NewProjectKind::Lib, + // default to bin + (false, false) => NewProjectKind::Bin, }; - NewOptions { - version_control: version_control, - bin: bin, - lib: is_lib, - path: path, - name: name, - } + let opts = NewOptions { version_control, kind, path, name }; + Ok(opts) } } @@ -90,35 +107,28 @@ version_control: Option, } -fn get_name<'a>(path: &'a Path, opts: &'a NewOptions, config: &Config) -> CargoResult<&'a str> { +fn get_name<'a>(path: &'a Path, opts: &'a NewOptions) -> CargoResult<&'a str> { if let Some(name) = opts.name { return Ok(name); } - if path.file_name().is_none() { - bail!("cannot auto-detect project name from path {:?} ; use --name to override", - path.as_os_str()); - } - - let dir_name = path.file_name().and_then(|s| s.to_str()).ok_or_else(|| { - format_err!("cannot create a project with a non-unicode name: {:?}", - path.file_name().unwrap()) + let file_name = path.file_name().ok_or_else(|| { + format_err!("cannot auto-detect project name from path {:?} ; use --name to override", path.as_os_str()) })?; - if opts.bin { - Ok(dir_name) - } else { - let new_name = strip_rust_affixes(dir_name); - if new_name != dir_name { - writeln!(config.shell().err(), - "note: package will be named `{}`; use --name to override", - new_name)?; - } - Ok(new_name) - } + file_name.to_str().ok_or_else(|| { + format_err!("cannot create project with a non-unicode name: {:?}", file_name) + }) } -fn check_name(name: &str, is_bin: bool) -> CargoResult<()> { +fn check_name(name: &str, opts: &NewOptions) -> CargoResult<()> { + + // If --name is already used to override, no point in suggesting it + // again as a fix. + let name_help = match opts.name { + Some(_) => "", + None => "\nuse --name to override crate name", + }; // Ban keywords + test list found at // https://doc.rust-lang.org/grammar.html#keywords @@ -133,25 +143,26 @@ "super", "test", "trait", "true", "type", "typeof", "unsafe", "unsized", "use", "virtual", "where", "while", "yield"]; - if blacklist.contains(&name) || (is_bin && is_bad_artifact_name(name)) { - bail!("The name `{}` cannot be used as a crate name\n\ - use --name to override crate name", - name) + if blacklist.contains(&name) || (opts.kind.is_bin() && is_bad_artifact_name(name)) { + bail!("The name `{}` cannot be used as a crate name{}", + name, + name_help) } if let Some(ref c) = name.chars().nth(0) { if c.is_digit(10) { - bail!("Package names starting with a digit cannot be used as a crate name\n\ - use --name to override crate name") + bail!("Package names starting with a digit cannot be used as a crate name{}", + name_help) } } for c in name.chars() { if c.is_alphanumeric() { continue } if c == '_' || c == '-' { continue } - bail!("Invalid character `{}` in crate name: `{}`\n\ - use --name to override crate name", - c, name) + bail!("Invalid character `{}` in crate name: `{}`{}", + c, + name, + name_help) } Ok(()) } @@ -274,19 +285,15 @@ ) } - if opts.lib && opts.bin { - bail!("can't specify both lib and binary outputs") - } - - let name = get_name(&path, opts, config)?; - check_name(name, opts.bin)?; + let name = get_name(&path, opts)?; + check_name(name, opts)?; let mkopts = MkOptions { version_control: opts.version_control, path: &path, name: name, - source_files: vec![plan_new_source_file(opts.bin, name.to_string())], - bin: opts.bin, + source_files: vec![plan_new_source_file(opts.kind.is_bin(), name.to_string())], + bin: opts.kind.is_bin(), }; mk(config, &mkopts).chain_err(|| { @@ -304,19 +311,15 @@ bail!("`cargo init` cannot be run on existing Cargo projects") } - if opts.lib && opts.bin { - bail!("can't specify both lib and binary outputs"); - } - - let name = get_name(&path, opts, config)?; - check_name(name, opts.bin)?; + let name = get_name(&path, opts)?; + check_name(name, opts)?; let mut src_paths_types = vec![]; detect_source_paths_and_types(&path, name, &mut src_paths_types)?; if src_paths_types.is_empty() { - src_paths_types.push(plan_new_source_file(opts.bin, name.to_string())); + src_paths_types.push(plan_new_source_file(opts.kind.is_bin(), name.to_string())); } else { // --bin option may be ignored if lib.rs or src/lib.rs present // Maybe when doing `cargo init --bin` inside a library project stub, @@ -358,9 +361,9 @@ } let mkopts = MkOptions { - version_control: version_control, + version_control, path: &path, - name: name, + name, bin: src_paths_types.iter().any(|x|x.bin), source_files: src_paths_types, }; @@ -372,20 +375,6 @@ Ok(()) } -fn strip_rust_affixes(name: &str) -> &str { - for &prefix in &["rust-", "rust_", "rs-", "rs_"] { - if name.starts_with(prefix) { - return &name[prefix.len()..]; - } - } - for &suffix in &["-rust", "_rust", "-rs", "_rs"] { - if name.ends_with(suffix) { - return &name[..name.len()-suffix.len()]; - } - } - name -} - fn existing_vcs_repo(path: &Path, cwd: &Path) -> bool { GitRepo::discover(path, cwd).is_ok() || HgRepo::discover(path, cwd).is_ok() } @@ -395,7 +384,7 @@ let name = opts.name; let cfg = global_config(config)?; // Please ensure that ignore and hgignore are in sync. - let ignore = ["\n", "/target/\n", "**/*.rs.bk\n", + let ignore = ["\n", "/target\n", "**/*.rs.bk\n", if !opts.bin { "Cargo.lock\n" } else { "" }] .concat(); // Mercurial glob ignores can't be rooted, so just sticking a 'syntax: glob' at the top of the @@ -581,6 +570,7 @@ let vcs = match vcs.as_ref().map(|p| (&p.val[..], &p.definition)) { Some(("git", _)) => Some(VersionControl::Git), Some(("hg", _)) => Some(VersionControl::Hg), + Some(("pijul", _)) => Some(VersionControl::Pijul), Some(("none", _)) => Some(VersionControl::NoVcs), Some((s, p)) => { return Err(internal(format!("invalid configuration for key \ @@ -595,20 +585,3 @@ version_control: vcs, }) } - -#[cfg(test)] -mod tests { - use super::strip_rust_affixes; - - #[test] - fn affixes_stripped() { - assert_eq!(strip_rust_affixes("rust-foo"), "foo"); - assert_eq!(strip_rust_affixes("foo-rs"), "foo"); - assert_eq!(strip_rust_affixes("rs_foo"), "foo"); - // Only one affix is stripped - assert_eq!(strip_rust_affixes("rs-foo-rs"), "foo-rs"); - assert_eq!(strip_rust_affixes("foo-rs-rs"), "foo-rs"); - // It shouldn't touch the middle - assert_eq!(strip_rust_affixes("some-rust-crate"), "some-rust-crate"); - } -} diff -Nru cargo-0.25.0/src/cargo/ops/cargo_package.rs cargo-0.26.0/src/cargo/ops/cargo_package.rs --- cargo-0.25.0/src/cargo/ops/cargo_package.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/ops/cargo_package.rs 2018-02-26 21:17:55.000000000 +0000 @@ -31,12 +31,6 @@ let pkg = ws.current()?; let config = ws.config(); - // Allow packaging if a registry has been provided, or if there are no nightly - // features enabled. - if opts.registry.is_none() && !pkg.manifest().features().activated().is_empty() { - bail!("cannot package or publish crates which activate nightly-only \ - cargo features") - } let mut src = PathSource::new(pkg.root(), pkg.package_id().source_id(), config); @@ -255,7 +249,7 @@ })?; let mut header = Header::new_ustar(); - let toml = pkg.to_registry_toml()?; + let toml = pkg.to_registry_toml(ws.config())?; header.set_path(&path)?; header.set_entry_type(EntryType::file()); header.set_mode(0o644); diff -Nru cargo-0.25.0/src/cargo/ops/cargo_rustc/compilation.rs cargo-0.26.0/src/cargo/ops/cargo_rustc/compilation.rs --- cargo-0.25.0/src/cargo/ops/cargo_rustc/compilation.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/ops/cargo_rustc/compilation.rs 2018-02-26 21:17:55.000000000 +0000 @@ -1,10 +1,12 @@ -use std::collections::{HashMap, HashSet}; +use std::collections::{HashMap, HashSet, BTreeSet}; use std::ffi::OsStr; use std::path::PathBuf; + use semver::Version; +use lazycell::LazyCell; use core::{PackageId, Package, Target, TargetKind}; -use util::{self, CargoResult, Config, LazyCell, ProcessBuilder, process, join_paths}; +use util::{self, CargoResult, Config, ProcessBuilder, process, join_paths}; /// A structure returning the result of a compilation. pub struct Compilation<'cfg> { @@ -22,8 +24,10 @@ /// /// This is currently used to drive some entries which are added to the /// LD_LIBRARY_PATH as appropriate. + /// + /// The order should be deterministic. // TODO: deprecated, remove - pub native_dirs: HashSet, + pub native_dirs: BTreeSet, /// Root output directory (for the local package's artifacts) pub root_output: PathBuf, @@ -64,7 +68,7 @@ pub fn new(config: &'cfg Config) -> Compilation<'cfg> { Compilation { libraries: HashMap::new(), - native_dirs: HashSet::new(), // TODO: deprecated, remove + native_dirs: BTreeSet::new(), // TODO: deprecated, remove root_output: PathBuf::from("/"), deps_output: PathBuf::from("/"), host_deps_output: PathBuf::from("/"), @@ -99,7 +103,7 @@ } fn target_runner(&self) -> CargoResult<&Option<(PathBuf, Vec)>> { - self.target_runner.get_or_try_init(|| { + self.target_runner.try_borrow_with(|| { let key = format!("target.{}.runner", self.target); Ok(self.config.get_path_and_args(&key)?.map(|v| v.val)) }) diff -Nru cargo-0.25.0/src/cargo/ops/cargo_rustc/context.rs cargo-0.26.0/src/cargo/ops/cargo_rustc/context.rs --- cargo-0.25.0/src/cargo/ops/cargo_rustc/context.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/ops/cargo_rustc/context.rs 2018-02-26 21:17:55.000000000 +0000 @@ -41,7 +41,7 @@ /// all that out. #[derive(Clone, Copy, Eq, PartialEq, Hash)] pub struct Unit<'a> { - /// Information about avaiable targets, which files to include/exclude, etc. Basically stuff in + /// Information about available targets, which files to include/exclude, etc. Basically stuff in /// `Cargo.toml`. pub pkg: &'a Package, /// Information about the specific target to build, out of the possible targets in `pkg`. Not @@ -940,7 +940,7 @@ ret.push(Unit { pkg: dep, target: lib, - profile: self.lib_profile(), + profile: self.lib_or_check_profile(unit, lib), kind: unit.kind.for_target(lib), }); if self.build_config.doc_all { @@ -1055,11 +1055,12 @@ } pub fn lib_or_check_profile(&self, unit: &Unit, target: &Target) -> &'a Profile { - if unit.profile.check && !target.is_custom_build() && !target.for_host() { - &self.profiles.check - } else { - self.lib_profile() + if !target.is_custom_build() && !target.for_host() { + if unit.profile.check || (unit.profile.doc && !unit.profile.test) { + return &self.profiles.check + } } + self.lib_profile() } pub fn build_script_profile(&self, _pkg: &PackageId) -> &'a Profile { @@ -1221,6 +1222,16 @@ None } }); + + // Note that we may have multiple matching `[target]` sections and + // because we're passing flags to the compiler this can affect + // cargo's caching and whether it rebuilds. Ensure a deterministic + // ordering through sorting for now. We may perhaps one day wish to + // ensure a deterministic ordering via the order keys were defined + // in files perhaps. + let mut cfgs = cfgs.collect::>(); + cfgs.sort(); + for n in cfgs { let key = format!("target.{}.{}", n, name); if let Some(args) = config.get_list_or_split_string(&key)? { diff -Nru cargo-0.25.0/src/cargo/ops/cargo_rustc/fingerprint.rs cargo-0.26.0/src/cargo/ops/cargo_rustc/fingerprint.rs --- cargo-0.25.0/src/cargo/ops/cargo_rustc/fingerprint.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/ops/cargo_rustc/fingerprint.rs 2018-02-26 21:17:55.000000000 +0000 @@ -9,7 +9,7 @@ use serde::de::{self, Deserialize}; use serde_json; -use core::{Package, TargetKind}; +use core::{Epoch, Package, TargetKind}; use util; use util::{Fresh, Dirty, Freshness, internal, profile}; use util::errors::{CargoResult, CargoResultExt}; @@ -145,6 +145,7 @@ #[serde(skip_serializing, skip_deserializing)] memoized_hash: Mutex>, rustflags: Vec, + epoch: Epoch, } fn serialize_deps(deps: &[(String, Arc)], ser: S) @@ -170,6 +171,7 @@ features: String::new(), deps: Vec::new(), memoized_hash: Mutex::new(Some(hash)), + epoch: Epoch::Epoch2015, rustflags: Vec::new(), })) }).collect()) @@ -252,6 +254,9 @@ if self.local.len() != old.local.len() { bail!("local lens changed"); } + if self.epoch != old.epoch { + bail!("epoch changed") + } for (new, old) in self.local.iter().zip(&old.local) { match (new, old) { (&LocalFingerprint::Precalculated(ref a), @@ -315,9 +320,10 @@ ref deps, ref local, memoized_hash: _, + epoch, ref rustflags, } = *self; - (rustc, features, target, path, profile, local, rustflags).hash(h); + (rustc, features, target, path, profile, local, epoch, rustflags).hash(h); h.write_usize(deps.len()); for &(ref name, ref fingerprint) in deps { @@ -416,6 +422,7 @@ deps: deps, local: vec![local], memoized_hash: Mutex::new(None), + epoch: unit.pkg.manifest().epoch(), rustflags: extra_flags, }); cx.fingerprints.insert(*unit, Arc::clone(&fingerprint)); @@ -468,6 +475,7 @@ deps: Vec::new(), local: local, memoized_hash: Mutex::new(None), + epoch: Epoch::Epoch2015, rustflags: Vec::new(), }; let compare = compare_old_fingerprint(&loc, &fingerprint); diff -Nru cargo-0.25.0/src/cargo/ops/cargo_rustc/mod.rs cargo-0.26.0/src/cargo/ops/cargo_rustc/mod.rs --- cargo-0.25.0/src/cargo/ops/cargo_rustc/mod.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/ops/cargo_rustc/mod.rs 2018-02-26 21:17:55.000000000 +0000 @@ -9,8 +9,9 @@ use same_file::is_same_file; use serde_json; -use core::{Package, PackageId, PackageSet, Target, Resolve}; +use core::{Feature, Package, PackageId, PackageSet, Target, Resolve}; use core::{Profile, Profiles, Workspace}; +use core::manifest::Lto; use core::shell::ColorChoice; use util::{self, ProcessBuilder, machine_message}; use util::{Config, internal, profile, join_paths}; @@ -744,7 +745,7 @@ unit: &Unit<'a>, crate_types: &[&str]) -> CargoResult<()> { let Profile { - ref opt_level, lto, codegen_units, ref rustc_args, debuginfo, + ref opt_level, ref lto, codegen_units, ref rustc_args, debuginfo, debug_assertions, overflow_checks, rpath, test, doc: _doc, run_custom_build, ref panic, rustdoc_args: _, check, incremental: _, } = *unit.profile; @@ -803,12 +804,27 @@ cmd.arg("-C").arg(format!("panic={}", panic)); } } + let manifest = unit.pkg.manifest(); + + if manifest.features().is_enabled(Feature::epoch()) { + cmd.arg(format!("-Zepoch={}", manifest.epoch())); + } // Disable LTO for host builds as prefer_dynamic and it are mutually // exclusive. - if unit.target.can_lto() && lto && !unit.target.for_host() { - cmd.args(&["-C", "lto"]); - } else if let Some(n) = codegen_units { + if unit.target.can_lto() && !unit.target.for_host() { + match *lto { + Lto::Bool(false) => {} + Lto::Bool(true) => { + cmd.args(&["-C", "lto"]); + } + Lto::Named(ref s) => { + cmd.arg("-C").arg(format!("lto={}", s)); + } + } + } + + if let Some(n) = codegen_units { // There are some restrictions with LTO and codegen-units, so we // only add codegen units when LTO is not used. cmd.arg("-C").arg(&format!("codegen-units={}", n)); diff -Nru cargo-0.25.0/src/cargo/ops/lockfile.rs cargo-0.26.0/src/cargo/ops/lockfile.rs --- cargo-0.25.0/src/cargo/ops/lockfile.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/ops/lockfile.rs 2018-02-26 21:17:55.000000000 +0000 @@ -76,6 +76,10 @@ } if !ws.config().lock_update_allowed() { + if ws.config().cli_unstable().offline { + bail!("can't update in the offline mode"); + } + let flag = if ws.config().network_allowed() {"--locked"} else {"--frozen"}; bail!("the lock file needs to be updated but {} was passed to \ prevent this", flag); diff -Nru cargo-0.25.0/src/cargo/ops/registry.rs cargo-0.26.0/src/cargo/ops/registry.rs --- cargo-0.25.0/src/cargo/ops/registry.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/ops/registry.rs 2018-02-26 21:17:55.000000000 +0000 @@ -42,6 +42,12 @@ pub fn publish(ws: &Workspace, opts: &PublishOpts) -> CargoResult<()> { let pkg = ws.current()?; + // Allow publishing if a registry has been provided, or if there are no nightly + // features enabled. + if opts.registry.is_none() && !pkg.manifest().features().activated().is_empty() { + bail!("cannot publish crates which activate nightly-only cargo features to crates.io") + } + if let &Some(ref allowed_registries) = pkg.publish() { if !match opts.registry { Some(ref registry) => allowed_registries.contains(registry), @@ -124,13 +130,17 @@ // If the dependency is from a different registry, then include the // registry in the dependency. - let dep_registry = if dep.source_id() != registry_id { - Some(dep.source_id().url().to_string()) + let dep_registry_id = match dep.registry_id() { + Some(id) => id, + None => bail!("dependency missing registry ID"), + }; + let dep_registry = if dep_registry_id != registry_id { + Some(dep_registry_id.url().to_string()) } else { None }; - NewCrateDependency { + Ok(NewCrateDependency { optional: dep.is_optional(), default_features: dep.uses_default_features(), name: dep.name().to_string(), @@ -143,8 +153,8 @@ Kind::Development => "dev", }.to_string(), registry: dep_registry, - } - }).collect::>(); + }) + }).collect::>>()?; let manifest = pkg.manifest(); let ManifestMetadata { ref authors, ref description, ref homepage, ref documentation, @@ -210,7 +220,7 @@ Ok(()) }, - Err(e) => Err(e.into()), + Err(e) => Err(e), } } @@ -220,7 +230,7 @@ let (index, token) = match registry { Some(registry) => { (Some(config.get_registry_index(®istry)?.to_string()), - config.get_string(&format!("registry.{}.token", registry))?.map(|p| p.val)) + config.get_string(&format!("registries.{}.token", registry))?.map(|p| p.val)) } None => { // Checking out for default index and token @@ -263,10 +273,13 @@ /// Create a new HTTP handle with appropriate global configuration for cargo. pub fn http_handle(config: &Config) -> CargoResult { - if !config.network_allowed() { + if config.frozen() { bail!("attempting to make an HTTP request, but --frozen was \ specified") } + if !config.network_allowed() { + bail!("can't make HTTP request in the offline mode") + } // The timeout option for libcurl by default times out the entire transfer, // but we probably don't want this. Instead we only set timeouts for the @@ -424,7 +437,7 @@ (Some(name), Some(email)) => println!(" ({} <{}>)", name, email), (Some(s), None) | (None, Some(s)) => println!(" ({})", s), - (None, None) => println!(""), + (None, None) => println!(), } } } diff -Nru cargo-0.25.0/src/cargo/ops/resolve.rs cargo-0.26.0/src/cargo/ops/resolve.rs --- cargo-0.25.0/src/cargo/ops/resolve.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/ops/resolve.rs 2018-02-26 21:17:55.000000000 +0000 @@ -40,11 +40,13 @@ if let Some(source) = source { registry.add_preloaded(source); } + let mut add_patches = true; let resolve = if ws.require_optional_deps() { // First, resolve the root_package's *listed* dependencies, as well as // downloading and updating all remotes and such. let resolve = resolve_with_registry(ws, &mut registry, false)?; + add_patches = false; // Second, resolve with precisely what we're doing. Filter out // transitive dependencies if necessary, specify features, handle @@ -77,9 +79,14 @@ }; let resolved_with_overrides = - ops::resolve_with_previous(&mut registry, ws, - method, resolve.as_ref(), None, - specs, true)?; + ops::resolve_with_previous(&mut registry, + ws, + method, + resolve.as_ref(), + None, + specs, + add_patches, + true)?; let packages = get_resolved_packages(&resolved_with_overrides, registry); @@ -89,9 +96,14 @@ fn resolve_with_registry(ws: &Workspace, registry: &mut PackageRegistry, warn: bool) -> CargoResult { let prev = ops::load_pkg_lockfile(ws)?; - let resolve = resolve_with_previous(registry, ws, + let resolve = resolve_with_previous(registry, + ws, Method::Everything, - prev.as_ref(), None, &[], warn)?; + prev.as_ref(), + None, + &[], + true, + warn)?; if !ws.is_ephemeral() { ops::write_pkg_lockfile(ws, &resolve)?; @@ -115,6 +127,7 @@ previous: Option<&'a Resolve>, to_avoid: Option<&HashSet<&'a PackageId>>, specs: &[PackageIdSpec], + register_patches: bool, warn: bool) -> CargoResult { // Here we place an artificial limitation that all non-registry sources @@ -169,27 +182,31 @@ } } - for (url, patches) in ws.root_patch() { - let previous = match previous { - Some(r) => r, - None => { - registry.patch(url, patches)?; - continue - } - }; - let patches = patches.iter().map(|dep| { - let unused = previous.unused_patches(); - let candidates = previous.iter().chain(unused); - match candidates.filter(keep).find(|id| dep.matches_id(id)) { - Some(id) => { - let mut dep = dep.clone(); - dep.lock_to(id); - dep + if register_patches { + for (url, patches) in ws.root_patch() { + let previous = match previous { + Some(r) => r, + None => { + registry.patch(url, patches)?; + continue } - None => dep.clone(), - } - }).collect::>(); - registry.patch(url, &patches)?; + }; + let patches = patches.iter().map(|dep| { + let unused = previous.unused_patches(); + let candidates = previous.iter().chain(unused); + match candidates.filter(keep).find(|id| dep.matches_id(id)) { + Some(id) => { + let mut dep = dep.clone(); + dep.lock_to(id); + dep + } + None => dep.clone(), + } + }).collect::>(); + registry.patch(url, &patches)?; + } + + registry.lock_patches(); } let mut summaries = Vec::new(); diff -Nru cargo-0.25.0/src/cargo/sources/directory.rs cargo-0.26.0/src/cargo/sources/directory.rs --- cargo-0.25.0/src/cargo/sources/directory.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/sources/directory.rs 2018-02-26 21:17:55.000000000 +0000 @@ -4,7 +4,7 @@ use std::io::Read; use std::path::{Path, PathBuf}; -use hex::ToHex; +use hex; use serde_json; @@ -97,23 +97,16 @@ // when a dir is removed from a different checkout. Sometimes a // mostly-empty dir is left behind. // - // To help Cargo work by default in more cases we try to handle this - // case by default. If the directory looks like it only has dotfiles - // in it (or no files at all) then we skip it. + // Additionally vendor directories are sometimes accompanied with + // readme files and other auxiliary information not too interesting + // to Cargo. // - // In general we don't want to skip completely malformed directories - // to help with debugging, so we don't just ignore errors in - // `update` below. - let mut only_dotfile = true; - for entry in path.read_dir()?.filter_map(|e| e.ok()) { - if let Some(s) = entry.file_name().to_str() { - if s.starts_with('.') { - continue - } - } - only_dotfile = false; - } - if only_dotfile { + // To help handle all this we only try processing folders with a + // `Cargo.toml` in them. This has the upside of being pretty + // flexible with the contents of vendor directories but has the + // downside of accidentally misconfigured vendor directories + // silently returning less crates. + if !path.join("Cargo.toml").exists() { continue } @@ -184,7 +177,7 @@ file.display()) })?; - let actual = h.finish().to_hex(); + let actual = hex::encode(h.finish()); if &*actual != cksum { bail!("\ the listed checksum of `{}` has changed:\n\ diff -Nru cargo-0.25.0/src/cargo/sources/git/source.rs cargo-0.26.0/src/cargo/sources/git/source.rs --- cargo-0.25.0/src/cargo/sources/git/source.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/sources/git/source.rs 2018-02-26 21:17:55.000000000 +0000 @@ -151,6 +151,11 @@ let db_path = lock.parent().join("db").join(&self.ident); + if self.config.cli_unstable().offline && !db_path.exists() { + bail!("can't checkout from '{}': you are in the offline mode (-Z offline)", + self.remote.url()); + } + // Resolve our reference to an actual revision, and check if the // database already has that revision. If it does, we just load a // database pinned at that revision, and if we don't we issue an update @@ -159,7 +164,7 @@ let should_update = actual_rev.is_err() || self.source_id.precise().is_none(); - let (repo, actual_rev) = if should_update { + let (db, actual_rev) = if should_update && !self.config.cli_unstable().offline { self.config.shell().status("Updating", format!("git repository `{}`", self.remote.url()))?; @@ -175,7 +180,7 @@ // Don’t use the full hash, // to contribute less to reaching the path length limit on Windows: // https://github.com/servo/servo/pull/14397 - let short_id = repo.to_short_id(actual_rev.clone()).unwrap(); + let short_id = db.to_short_id(actual_rev.clone()).unwrap(); let checkout_path = lock.parent().join("checkouts") .join(&self.ident).join(short_id.as_str()); @@ -185,7 +190,7 @@ // in scope so the destructors here won't tamper with too much. // Checkout is immutable, so we don't need to protect it with a lock once // it is created. - repo.copy_to(actual_rev.clone(), &checkout_path, self.config)?; + db.copy_to(actual_rev.clone(), &checkout_path, self.config)?; let source_id = self.source_id.with_precise(Some(actual_rev.to_string())); let path_source = PathSource::new_recursive(&checkout_path, diff -Nru cargo-0.25.0/src/cargo/sources/git/utils.rs cargo-0.26.0/src/cargo/sources/git/utils.rs --- cargo-0.25.0/src/cargo/sources/git/utils.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/sources/git/utils.rs 2018-02-26 21:17:55.000000000 +0000 @@ -12,7 +12,7 @@ use core::GitReference; use util::{ToUrl, internal, Config, network, Progress}; -use util::errors::{CargoResult, CargoResultExt, CargoError, Internal}; +use util::errors::{CargoResult, CargoResultExt, Internal}; #[derive(PartialEq, Clone, Debug)] pub struct GitRevision(git2::Oid); @@ -226,14 +226,43 @@ fs::create_dir_all(&dirname).chain_err(|| { format!("Couldn't mkdir {}", dirname.display()) })?; - if fs::metadata(&into).is_ok() { + if into.exists() { fs::remove_dir_all(into).chain_err(|| { format!("Couldn't rmdir {}", into.display()) })?; } - let repo = git2::Repository::init(into)?; - let mut checkout = GitCheckout::new(into, database, revision, repo); - checkout.fetch(config)?; + + // we're doing a local filesystem-to-filesystem clone so there should + // be no need to respect global configuration options, so pass in + // an empty instance of `git2::Config` below. + let git_config = git2::Config::new()?; + + // Clone the repository, but make sure we use the "local" option in + // libgit2 which will attempt to use hardlinks to set up the database. + // This should speed up the clone operation quite a bit if it works. + // + // Note that we still use the same fetch options because while we don't + // need authentication information we may want progress bars and such. + let url = database.path.to_url()?; + let mut repo = None; + with_fetch_options(&git_config, &url, config, &mut |fopts| { + let mut checkout = git2::build::CheckoutBuilder::new(); + checkout.dry_run(); // we'll do this below during a `reset` + + let r = git2::build::RepoBuilder::new() + // use hard links and/or copy the database, we're doing a + // filesystem clone so this'll speed things up quite a bit. + .clone_local(git2::build::CloneLocal::Local) + .with_checkout(checkout) + .fetch_options(fopts) + // .remote_create(|repo, _name, url| repo.remote_anonymous(url)) + .clone(url.as_str(), into)?; + repo = Some(r); + Ok(()) + })?; + let repo = repo.unwrap(); + + let checkout = GitCheckout::new(into, database, revision, repo); checkout.reset(config)?; Ok(checkout) } @@ -242,7 +271,7 @@ match self.repo.revparse_single("HEAD") { Ok(ref head) if head.id() == self.revision.0 => { // See comments in reset() for why we check this - fs::metadata(self.location.join(".cargo-ok")).is_ok() + self.location.join(".cargo-ok").exists() } _ => false, } @@ -555,14 +584,44 @@ Ok(()) } +pub fn with_fetch_options(git_config: &git2::Config, + url: &Url, + config: &Config, + cb: &mut FnMut(git2::FetchOptions) -> CargoResult<()>) + -> CargoResult<()> +{ + let mut progress = Progress::new("Fetch", config); + network::with_retry(config, url, || { + with_authentication(url.as_str(), git_config, |f| { + let mut rcb = git2::RemoteCallbacks::new(); + rcb.credentials(f); + + rcb.transfer_progress(|stats| { + progress.tick(stats.indexed_objects(), stats.total_objects()).is_ok() + }); + + // Create a local anonymous remote in the repository to fetch the + // url + let mut opts = git2::FetchOptions::new(); + opts.remote_callbacks(rcb) + .download_tags(git2::AutotagOption::All); + cb(opts) + })?; + Ok(()) + }) +} + pub fn fetch(repo: &mut git2::Repository, url: &Url, refspec: &str, config: &Config) -> CargoResult<()> { - if !config.network_allowed() { + if config.frozen() { bail!("attempting to update a git repository, but --frozen \ was specified") } + if !config.network_allowed() { + bail!("can't update a git repository in the offline mode") + } // If we're fetching from github, attempt github's special fast path for // testing if we've already got an up-to-date copy of the repository @@ -585,26 +644,10 @@ maybe_gc_repo(repo)?; debug!("doing a fetch for {}", url); - let mut progress = Progress::new("Fetch", config); - with_authentication(url.as_str(), &repo.config()?, |f| { - let mut cb = git2::RemoteCallbacks::new(); - cb.credentials(f); - - cb.transfer_progress(|stats| { - progress.tick(stats.indexed_objects(), stats.total_objects()).is_ok() - }); - - // Create a local anonymous remote in the repository to fetch the url + with_fetch_options(&repo.config()?, url, config, &mut |mut opts| { + debug!("initiating fetch of {} from {}", refspec, url); let mut remote = repo.remote_anonymous(url.as_str())?; - let mut opts = git2::FetchOptions::new(); - opts.remote_callbacks(cb) - .download_tags(git2::AutotagOption::All); - - network::with_retry(config, || { - debug!("initiating fetch of {} from {}", refspec, url); - remote.fetch(&[refspec], Some(&mut opts), None) - .map_err(CargoError::from) - })?; + remote.fetch(&[refspec], Some(&mut opts), None)?; Ok(()) }) } diff -Nru cargo-0.25.0/src/cargo/sources/path.rs cargo-0.26.0/src/cargo/sources/path.rs --- cargo-0.25.0/src/cargo/sources/path.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/sources/path.rs 2018-02-26 21:17:55.000000000 +0000 @@ -97,10 +97,10 @@ /// 1) Only warn users about the future change iff their matching rules are /// affected. (CURRENT STAGE) /// - /// 2) Switch to the new strategy and upate documents. Still keep warning + /// 2) Switch to the new strategy and update documents. Still keep warning /// affected users. /// - /// 3) Drop the old strategy and no mor warnings. + /// 3) Drop the old strategy and no more warnings. /// /// See for more info. pub fn list_files(&self, pkg: &Package) -> CargoResult> { diff -Nru cargo-0.25.0/src/cargo/sources/registry/index.rs cargo-0.26.0/src/cargo/sources/registry/index.rs --- cargo-0.25.0/src/cargo/sources/registry/index.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/sources/registry/index.rs 2018-02-26 21:17:55.000000000 +0000 @@ -110,13 +110,20 @@ .map(|s| s.trim()) .filter(|l| !l.is_empty()); + let online = !self.config.cli_unstable().offline; // Attempt forwards-compatibility on the index by ignoring // everything that we ourselves don't understand, that should // allow future cargo implementations to break the // interpretation of each line here and older cargo will simply // ignore the new lines. ret.extend(lines.filter_map(|line| { - self.parse_registry_package(line).ok() + self.parse_registry_package(line).ok().and_then(|v|{ + if online || load.is_crate_downloaded(v.0.package_id()) { + Some(v) + } else { + None + } + }) })); Ok(()) @@ -170,7 +177,7 @@ // Handle `cargo update --precise` here. If specified, our own source // will have a precise version listed of the form `=` where // `` is the name of a crate on this source and `` is the - // version requested (agument to `--precise`). + // version requested (argument to `--precise`). let summaries = summaries.filter(|s| { match source_id.precise() { Some(p) if p.starts_with(dep.name()) && diff -Nru cargo-0.25.0/src/cargo/sources/registry/local.rs cargo-0.26.0/src/cargo/sources/registry/local.rs --- cargo-0.25.0/src/cargo/sources/registry/local.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/sources/registry/local.rs 2018-02-26 21:17:55.000000000 +0000 @@ -3,7 +3,7 @@ use std::path::Path; use core::PackageId; -use hex::ToHex; +use hex; use sources::registry::{RegistryData, RegistryConfig}; use util::FileLock; use util::paths; @@ -94,7 +94,7 @@ } state.update(&buf[..n]); } - if state.finish().to_hex() != checksum { + if hex::encode(state.finish()) != checksum { bail!("failed to verify the checksum of `{}`", pkg) } diff -Nru cargo-0.25.0/src/cargo/sources/registry/mod.rs cargo-0.26.0/src/cargo/sources/registry/mod.rs --- cargo-0.25.0/src/cargo/sources/registry/mod.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/sources/registry/mod.rs 2018-02-26 21:17:55.000000000 +0000 @@ -249,6 +249,8 @@ fn download(&mut self, pkg: &PackageId, checksum: &str) -> CargoResult; + + fn is_crate_downloaded(&self, _pkg: &PackageId) -> bool { true } } mod index; diff -Nru cargo-0.25.0/src/cargo/sources/registry/remote.rs cargo-0.26.0/src/cargo/sources/registry/remote.rs --- cargo-0.25.0/src/cargo/sources/registry/remote.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/sources/registry/remote.rs 2018-02-26 21:17:55.000000000 +0000 @@ -7,14 +7,15 @@ use std::str; use git2; -use hex::ToHex; +use hex; use serde_json; +use lazycell::LazyCell; use core::{PackageId, SourceId}; use sources::git; use sources::registry::{RegistryData, RegistryConfig, INDEX_LOCK, CRATE_TEMPLATE, VERSION_TEMPLATE}; use util::network; -use util::{FileLock, Filesystem, LazyCell}; +use util::{FileLock, Filesystem}; use util::{Config, Sha256, ToUrl, Progress}; use util::errors::{CargoResult, CargoResultExt, HttpNot200}; @@ -43,7 +44,7 @@ } fn repo(&self) -> CargoResult<&git2::Repository> { - self.repo.get_or_try_init(|| { + self.repo.try_borrow_with(|| { let path = self.index_path.clone().into_path_unlocked(); // Fast path without a lock @@ -153,6 +154,13 @@ } fn update_index(&mut self) -> CargoResult<()> { + if self.config.cli_unstable().offline { + return Ok(()); + } + if self.config.cli_unstable().no_index_update { + return Ok(()); + } + // Ensure that we'll actually be able to acquire an HTTP handle later on // once we start trying to download crates. This will weed out any // problems with `.cargo/config` configuration related to HTTP. @@ -216,14 +224,13 @@ // TODO: don't download into memory, but ensure that if we ctrl-c a // download we should resume either from the start or the middle // on the next time - let url = url.to_string(); let mut handle = self.config.http()?.borrow_mut(); handle.get(true)?; - handle.url(&url)?; + handle.url(&url.to_string())?; handle.follow_location(true)?; let mut state = Sha256::new(); let mut body = Vec::new(); - network::with_retry(self.config, || { + network::with_retry(self.config, &url, || { state = Sha256::new(); body = Vec::new(); let mut pb = Progress::new("Fetch", self.config); @@ -242,15 +249,17 @@ } let code = handle.response_code()?; if code != 200 && code != 0 { - let url = handle.effective_url()?.unwrap_or(&url); - Err(HttpNot200 { code, url: url.to_string() }.into()) + let url = handle.effective_url()? + .map(|url| url.to_string()) + .unwrap_or_else(|| url.to_string()); + Err(HttpNot200 { code, url }.into()) } else { Ok(()) } })?; // Verify what we just downloaded - if state.finish().to_hex() != checksum { + if hex::encode(state.finish()) != checksum { bail!("failed to verify the checksum of `{}`", pkg) } @@ -258,6 +267,20 @@ dst.seek(SeekFrom::Start(0))?; Ok(dst) } + + + fn is_crate_downloaded(&self, pkg: &PackageId) -> bool { + let filename = format!("{}-{}.crate", pkg.name(), pkg.version()); + let path = Path::new(&filename); + + if let Ok(dst) = self.cache_path.open_ro(path, self.config, &filename) { + if let Ok(meta) = dst.file().metadata(){ + return meta.len() > 0; + } + } + false + } + } impl<'cfg> Drop for RemoteRegistry<'cfg> { diff -Nru cargo-0.25.0/src/cargo/util/config.rs cargo-0.26.0/src/cargo/util/config.rs --- cargo-0.25.0/src/cargo/util/config.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/util/config.rs 2018-02-26 21:17:55.000000000 +0000 @@ -16,6 +16,7 @@ use jobserver; use serde::{Serialize, Serializer}; use toml; +use lazycell::LazyCell; use core::shell::Verbosity; use core::{Shell, CliUnstable}; @@ -26,7 +27,7 @@ use util::errors::{CargoResult, CargoResultExt, CargoError, internal}; use util::paths; use util::toml as cargo_toml; -use util::{Filesystem, LazyCell}; +use util::Filesystem; use self::ConfigValue as CV; @@ -144,18 +145,18 @@ /// Get the path to the `rustdoc` executable pub fn rustdoc(&self) -> CargoResult<&Path> { - self.rustdoc.get_or_try_init(|| self.get_tool("rustdoc")).map(AsRef::as_ref) + self.rustdoc.try_borrow_with(|| self.get_tool("rustdoc")).map(AsRef::as_ref) } /// Get the path to the `rustc` executable pub fn rustc(&self) -> CargoResult<&Rustc> { - self.rustc.get_or_try_init(|| Rustc::new(self.get_tool("rustc")?, + self.rustc.try_borrow_with(|| Rustc::new(self.get_tool("rustc")?, self.maybe_get_tool("rustc_wrapper")?)) } /// Get the path to the `cargo` executable pub fn cargo_exe(&self) -> CargoResult<&Path> { - self.cargo_exe.get_or_try_init(|| { + self.cargo_exe.try_borrow_with(|| { fn from_current_exe() -> CargoResult { // Try fetching the path to `cargo` using env::current_exe(). // The method varies per operating system and might fail; in particular, @@ -207,7 +208,7 @@ } pub fn values(&self) -> CargoResult<&HashMap> { - self.values.get_or_try_init(|| self.load_values()) + self.values.try_borrow_with(|| self.load_values()) } pub fn set_values(&self, values: HashMap) -> CargoResult<()> { @@ -504,7 +505,11 @@ } pub fn network_allowed(&self) -> bool { - !self.frozen + !self.frozen() && !self.cli_unstable().offline + } + + pub fn frozen(&self) -> bool { + self.frozen } pub fn lock_update_allowed(&self) -> bool { @@ -548,7 +553,13 @@ /// Gets the index for a registry. pub fn get_registry_index(&self, registry: &str) -> CargoResult { Ok(match self.get_string(&format!("registries.{}.index", registry))? { - Some(index) => index.val.to_url()?, + Some(index) => { + let url = index.val.to_url()?; + if url.username() != "" || url.password().is_some() { + bail!("Registry URLs may not contain credentials"); + } + url + } None => bail!("No index found for registry: `{}`", registry), }) } @@ -573,30 +584,31 @@ format!("could not parse TOML configuration in `{}`", credentials.display()) })?; - let value = CV::from_toml(&credentials, toml).chain_err(|| { + let mut value = CV::from_toml(&credentials, toml).chain_err(|| { format!("failed to load TOML configuration from `{}`", credentials.display()) })?; - let cfg = match *cfg { - CV::Table(ref mut map, _) => map, - _ => unreachable!(), - }; - - let registry = cfg.entry("registry".into()) - .or_insert_with(|| CV::Table(HashMap::new(), PathBuf::from("."))); + // backwards compatibility for old .cargo/credentials layout + { + let value = match value { + CV::Table(ref mut value, _) => value, + _ => unreachable!(), + }; - match (registry, value) { - (&mut CV::Table(ref mut old, _), CV::Table(ref mut new, _)) => { - // Take ownership of `new` by swapping it with an empty hashmap, so we can move - // into an iterator. - let new = mem::replace(new, HashMap::new()); - for (key, value) in new { - old.insert(key, value); + if let Some(token) = value.remove("token") { + if let Vacant(entry) = value.entry("registry".into()) { + let mut map = HashMap::new(); + map.insert("token".into(), token); + let table = CV::Table(map, PathBuf::from(".")); + entry.insert(table); } } - _ => unreachable!(), } + // we want value to override cfg, so swap these + mem::swap(cfg, &mut value); + cfg.merge(value)?; + Ok(()) } @@ -637,7 +649,7 @@ } pub fn http(&self) -> CargoResult<&RefCell> { - let http = self.easy.get_or_try_init(|| { + let http = self.easy.try_borrow_with(|| { ops::http_handle(self).map(RefCell::new) })?; { @@ -919,13 +931,16 @@ let (key, value) = { let key = "token".to_string(); let value = ConfigValue::String(token, file.path().to_path_buf()); + let mut map = HashMap::new(); + map.insert(key, value); + let table = CV::Table(map, file.path().to_path_buf()); if let Some(registry) = registry { let mut map = HashMap::new(); - map.insert(key, value); - (registry, CV::Table(map, file.path().to_path_buf())) + map.insert(registry, table); + ("registries".into(), CV::Table(map, file.path().to_path_buf())) } else { - (key, value) + ("registry".into(), table) } }; @@ -935,6 +950,14 @@ })?; let mut toml = cargo_toml::parse(&contents, file.path(), cfg)?; + + // move the old token location to the new one + if let Some(token) = toml.as_table_mut().unwrap().remove("token") { + let mut map = HashMap::new(); + map.insert("token".to_string(), token); + toml.as_table_mut().unwrap().insert("registry".into(), map.into()); + } + toml.as_table_mut() .unwrap() .insert(key, value.into_toml()); diff -Nru cargo-0.25.0/src/cargo/util/graph.rs cargo-0.26.0/src/cargo/util/graph.rs --- cargo-0.25.0/src/cargo/util/graph.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/util/graph.rs 2018-02-26 21:17:55.000000000 +0000 @@ -67,6 +67,30 @@ pub fn iter(&self) -> Nodes { self.nodes.keys() } + + /// Resolves one of the paths from the given dependent package up to + /// the root. + pub fn path_to_top<'a>(&'a self, mut pkg: &'a N) -> Vec<&'a N> { + // Note that this implementation isn't the most robust per se, we'll + // likely have to tweak this over time. For now though it works for what + // it's used for! + let mut result = vec![pkg]; + let first_pkg_depending_on = |pkg: &N, res: &[&N]| { + self.get_nodes() + .iter() + .filter(|&(_node, adjacent)| adjacent.contains(pkg)) + // Note that we can have "cycles" introduced through dev-dependency + // edges, so make sure we don't loop infinitely. + .filter(|&(_node, _)| !res.contains(&_node)) + .next() + .map(|p| p.0) + }; + while let Some(p) = first_pkg_depending_on(pkg, &result) { + result.push(p); + pkg = p; + } + result + } } impl Default for Graph { diff -Nru cargo-0.25.0/src/cargo/util/hex.rs cargo-0.26.0/src/cargo/util/hex.rs --- cargo-0.25.0/src/cargo/util/hex.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/util/hex.rs 2018-02-26 21:17:55.000000000 +0000 @@ -1,10 +1,10 @@ #![allow(deprecated)] -use hex::ToHex; +use hex; use std::hash::{Hasher, Hash, SipHasher}; pub fn to_hex(num: u64) -> String { - [ + hex::encode(&[ (num >> 0) as u8, (num >> 8) as u8, (num >> 16) as u8, @@ -13,7 +13,7 @@ (num >> 40) as u8, (num >> 48) as u8, (num >> 56) as u8, - ].to_hex() + ]) } pub fn hash_u64(hashable: &H) -> u64 { diff -Nru cargo-0.25.0/src/cargo/util/job.rs cargo-0.26.0/src/cargo/util/job.rs --- cargo-0.25.0/src/cargo/util/job.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/util/job.rs 2018-02-26 21:17:55.000000000 +0000 @@ -42,21 +42,32 @@ #[cfg(windows)] mod imp { - extern crate kernel32; extern crate winapi; - extern crate psapi; use std::ffi::OsString; use std::io; use std::mem; use std::os::windows::prelude::*; + use self::winapi::shared::basetsd::*; + use self::winapi::shared::minwindef::*; + use self::winapi::shared::minwindef::{FALSE, TRUE}; + use self::winapi::um::handleapi::*; + use self::winapi::um::jobapi2::*; + use self::winapi::um::jobapi::*; + use self::winapi::um::processthreadsapi::*; + use self::winapi::um::psapi::*; + use self::winapi::um::synchapi::*; + use self::winapi::um::winbase::*; + use self::winapi::um::winnt::*; + use self::winapi::um::winnt::HANDLE; + pub struct Setup { job: Handle, } pub struct Handle { - inner: winapi::HANDLE, + inner: HANDLE, } fn last_err() -> io::Error { @@ -73,7 +84,7 @@ // use job objects, so we instead just ignore errors and assume that // we're otherwise part of someone else's job object in this case. - let job = kernel32::CreateJobObjectW(0 as *mut _, 0 as *const _); + let job = CreateJobObjectW(0 as *mut _, 0 as *const _); if job.is_null() { return None } @@ -83,22 +94,22 @@ // process in the object should be killed. Note that this includes our // entire process tree by default because we've added ourselves and and // our children will reside in the job once we spawn a process. - let mut info: winapi::JOBOBJECT_EXTENDED_LIMIT_INFORMATION; + let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION; info = mem::zeroed(); info.BasicLimitInformation.LimitFlags = - winapi::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; - let r = kernel32::SetInformationJobObject(job.inner, - winapi::JobObjectExtendedLimitInformation, - &mut info as *mut _ as winapi::LPVOID, - mem::size_of_val(&info) as winapi::DWORD); + JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + let r = SetInformationJobObject(job.inner, + JobObjectExtendedLimitInformation, + &mut info as *mut _ as LPVOID, + mem::size_of_val(&info) as DWORD); if r == 0 { return None } // Assign our process to this job object, meaning that our children will // now live or die based on our existence. - let me = kernel32::GetCurrentProcess(); - let r = kernel32::AssignProcessToJobObject(job.inner, me); + let me = GetCurrentProcess(); + let r = AssignProcessToJobObject(job.inner, me); if r == 0 { return None } @@ -126,13 +137,13 @@ info!("killed some, going for more"); } - let mut info: winapi::JOBOBJECT_EXTENDED_LIMIT_INFORMATION; + let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION; info = mem::zeroed(); - let r = kernel32::SetInformationJobObject( + let r = SetInformationJobObject( self.job.inner, - winapi::JobObjectExtendedLimitInformation, - &mut info as *mut _ as winapi::LPVOID, - mem::size_of_val(&info) as winapi::DWORD); + JobObjectExtendedLimitInformation, + &mut info as *mut _ as LPVOID, + mem::size_of_val(&info) as DWORD); if r == 0 { info!("failed to configure job object to defaults: {}", last_err()); @@ -145,16 +156,16 @@ unsafe fn kill_remaining(&mut self) -> bool { #[repr(C)] struct Jobs { - header: winapi::JOBOBJECT_BASIC_PROCESS_ID_LIST, - list: [winapi::ULONG_PTR; 1024], + header: JOBOBJECT_BASIC_PROCESS_ID_LIST, + list: [ULONG_PTR; 1024], } let mut jobs: Jobs = mem::zeroed(); - let r = kernel32::QueryInformationJobObject( + let r = QueryInformationJobObject( self.job.inner, - winapi::JobObjectBasicProcessIdList, - &mut jobs as *mut _ as winapi::LPVOID, - mem::size_of_val(&jobs) as winapi::DWORD, + JobObjectBasicProcessIdList, + &mut jobs as *mut _ as LPVOID, + mem::size_of_val(&jobs) as DWORD, 0 as *mut _); if r == 0 { info!("failed to query job object: {}", last_err()); @@ -168,17 +179,15 @@ let list = list.iter().filter(|&&id| { // let's not kill ourselves - id as winapi::DWORD != kernel32::GetCurrentProcessId() + id as DWORD != GetCurrentProcessId() }).filter_map(|&id| { // Open the process with the necessary rights, and if this // fails then we probably raced with the process exiting so we // ignore the problem. - let flags = winapi::PROCESS_QUERY_INFORMATION | - winapi::PROCESS_TERMINATE | - winapi::SYNCHRONIZE; - let p = kernel32::OpenProcess(flags, - winapi::FALSE, - id as winapi::DWORD); + let flags = PROCESS_QUERY_INFORMATION | + PROCESS_TERMINATE | + SYNCHRONIZE; + let p = OpenProcess(flags, FALSE, id as DWORD); if p.is_null() { None } else { @@ -189,12 +198,12 @@ // If it's not then we likely raced with something else // recycling this PID, so we just skip this step. let mut res = 0; - let r = kernel32::IsProcessInJob(p.inner, self.job.inner, &mut res); + let r = IsProcessInJob(p.inner, self.job.inner, &mut res); if r == 0 { info!("failed to test is process in job: {}", last_err()); return false } - res == winapi::TRUE + res == TRUE }); @@ -202,9 +211,9 @@ // Load the file which this process was spawned from. We then // later use this for identification purposes. let mut buf = [0; 1024]; - let r = psapi::GetProcessImageFileNameW(p.inner, - buf.as_mut_ptr(), - buf.len() as winapi::DWORD); + let r = GetProcessImageFileNameW(p.inner, + buf.as_mut_ptr(), + buf.len() as DWORD); if r == 0 { info!("failed to get image name: {}", last_err()); continue @@ -233,14 +242,14 @@ // Ok, this isn't mspdbsrv, let's kill the process. After we // kill it we wait on it to ensure that the next time around in // this function we're not going to see it again. - let r = kernel32::TerminateProcess(p.inner, 1); + let r = TerminateProcess(p.inner, 1); if r == 0 { info!("\tfailed to kill subprocess: {}", last_err()); info!("\tassuming subprocess is dead..."); } else { info!("\tterminated subprocess"); } - let r = kernel32::WaitForSingleObject(p.inner, winapi::INFINITE); + let r = WaitForSingleObject(p.inner, INFINITE); if r != 0 { info!("failed to wait for process to die: {}", last_err()); return false @@ -254,7 +263,7 @@ impl Drop for Handle { fn drop(&mut self) { - unsafe { kernel32::CloseHandle(self.inner); } + unsafe { CloseHandle(self.inner); } } } } diff -Nru cargo-0.25.0/src/cargo/util/lazy_cell.rs cargo-0.26.0/src/cargo/util/lazy_cell.rs --- cargo-0.25.0/src/cargo/util/lazy_cell.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/util/lazy_cell.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,74 +0,0 @@ -//! A lazily fill Cell, but with frozen contents. -//! -//! With a `RefCell`, the inner contents cannot be borrowed for the lifetime of -//! the entire object, but only of the borrows returned. A `LazyCell` is a -//! variation on `RefCell` which allows borrows tied to the lifetime of the -//! outer object. -//! -//! The limitation of a `LazyCell` is that after initialized, it can never be -//! modified unless you've otherwise got a `&mut` reference - -use std::cell::UnsafeCell; - -#[derive(Debug)] -pub struct LazyCell { - inner: UnsafeCell>, -} - -impl LazyCell { - /// Creates a new empty lazy cell. - pub fn new() -> LazyCell { - LazyCell { inner: UnsafeCell::new(None) } - } - - /// Put a value into this cell. - /// - /// This function will fail if the cell has already been filled. - pub fn fill(&self, t: T) -> Result<(), T> { - unsafe { - let slot = self.inner.get(); - if (*slot).is_none() { - *slot = Some(t); - Ok(()) - } else { - Err(t) - } - } - } - - /// Borrows the contents of this lazy cell for the duration of the cell - /// itself. - /// - /// This function will return `Some` if the cell has been previously - /// initialized, and `None` if it has not yet been initialized. - pub fn borrow(&self) -> Option<&T> { - unsafe { - (*self.inner.get()).as_ref() - } - } - - /// Same as `borrow`, but the mutable version - pub fn borrow_mut(&mut self) -> Option<&mut T> { - unsafe { - (*self.inner.get()).as_mut() - } - } - - /// Consumes this `LazyCell`, returning the underlying value. - #[allow(unused_unsafe)] - pub fn into_inner(self) -> Option { - unsafe { - self.inner.into_inner() - } - } - - /// Borrows the contents of this lazy cell, initializing it if necessary. - pub fn get_or_try_init(&self, init: F) -> Result<&T, Error> - where F: FnOnce() -> Result - { - if self.borrow().is_none() && self.fill(init()?).is_err() { - unreachable!(); - } - Ok(self.borrow().unwrap()) - } -} diff -Nru cargo-0.25.0/src/cargo/util/mod.rs cargo-0.26.0/src/cargo/util/mod.rs --- cargo-0.25.0/src/cargo/util/mod.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/util/mod.rs 2018-02-26 21:17:55.000000000 +0000 @@ -7,7 +7,6 @@ pub use self::flock::{FileLock, Filesystem}; pub use self::graph::Graph; pub use self::hex::{to_hex, short_hash, hash_u64}; -pub use self::lazy_cell::LazyCell; pub use self::lev_distance::{lev_distance}; pub use self::paths::{join_paths, path2bytes, bytes2path, dylib_path}; pub use self::paths::{normalize_path, dylib_path_envvar, without_prefix}; @@ -40,7 +39,6 @@ mod rustc; mod sha256; mod vcs; -mod lazy_cell; mod flock; mod read2; mod progress; diff -Nru cargo-0.25.0/src/cargo/util/network.rs cargo-0.26.0/src/cargo/util/network.rs --- cargo-0.25.0/src/cargo/util/network.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/util/network.rs 2018-02-26 21:17:55.000000000 +0000 @@ -1,5 +1,6 @@ use curl; use git2; +use url::Url; use failure::Error; @@ -33,6 +34,35 @@ false } + +/// Suggest the user to update their windows 7 to support modern TLS versions. +/// See https://github.com/rust-lang/cargo/issues/5066 for details. +#[cfg(windows)] +fn should_warn_about_old_tls_for_win7(url: &Url, err: &Error) -> bool { + let is_github = url.host_str() == Some("github.com"); + let is_cert_error = err.causes() + .filter_map(|e| e.downcast_ref::()) + .find(|e| e.class() == git2::ErrorClass::Net && e.code() == git2::ErrorCode::Certificate) + .is_some(); + is_github && is_cert_error +} + +#[cfg(not(windows))] +fn should_warn_about_old_tls_for_win7(_url: &Url, _err: &Error) -> bool { + false +} + +const WIN7_TLS_WARNING: &str = "\ +Certificate check failure might be caused by outdated TLS on older versions of Windows. +If you are using Windows 7, Windows Server 2008 R2 or Windows Server 2012, +please follow these instructions to enable more secure TLS: + + https://support.microsoft.com/en-us/help/3140245/ + +See https://github.com/rust-lang/cargo/issues/5066 for details. +"; + + /// Wrapper method for network call retry logic. /// /// Retry counts provided by Config object `net.retry`. Config shell outputs @@ -44,9 +74,9 @@ /// /// ```ignore /// use util::network; -/// cargo_result = network.with_retry(&config, || something.download()); +/// cargo_result = network::with_retry(&config, || something.download()); /// ``` -pub fn with_retry(config: &Config, mut callback: F) -> CargoResult +pub fn with_retry(config: &Config, url: &Url, mut callback: F) -> CargoResult where F: FnMut() -> CargoResult { let mut remaining = config.net_retry()?; @@ -54,9 +84,14 @@ match callback() { Ok(ret) => return Ok(ret), Err(ref e) if maybe_spurious(e) && remaining > 0 => { - let msg = format!("spurious network error ({} tries \ - remaining): {}", remaining, e); - config.shell().warn(msg)?; + config.shell().warn( + format!("spurious network error ({} tries remaining): {}", remaining, e) + )?; + + if should_warn_about_old_tls_for_win7(url, e) { + config.shell().warn(WIN7_TLS_WARNING)?; + } + remaining -= 1; } //todo impl from @@ -71,7 +106,8 @@ let error2 = HttpNot200 { code: 502, url: "Uri".to_string() }.into(); let mut results: Vec> = vec![Ok(()), Err(error1), Err(error2)]; let config = Config::default().unwrap(); - let result = with_retry(&config, || results.pop().unwrap()); + let url = "http://example.com".parse().unwrap(); + let result = with_retry(&config, &url, || results.pop().unwrap()); assert_eq!(result.unwrap(), ()) } @@ -87,6 +123,7 @@ let error2 = CargoError::from(error2.context("A second chained error")); let mut results: Vec> = vec![Ok(()), Err(error1), Err(error2)]; let config = Config::default().unwrap(); - let result = with_retry(&config, || results.pop().unwrap()); + let url = "http://example.com".parse().unwrap(); + let result = with_retry(&config, &url, || results.pop().unwrap()); assert_eq!(result.unwrap(), ()) } diff -Nru cargo-0.25.0/src/cargo/util/read2.rs cargo-0.26.0/src/cargo/util/read2.rs --- cargo-0.25.0/src/cargo/util/read2.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/util/read2.rs 2018-02-26 21:17:55.000000000 +0000 @@ -27,9 +27,12 @@ fds[0].events = libc::POLLIN; fds[1].fd = err_pipe.as_raw_fd(); fds[1].events = libc::POLLIN; - loop { + let mut nfds = 2; + let mut errfd = 1; + + while nfds > 0 { // wait for either pipe to become readable using `select` - let r = unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) }; + let r = unsafe { libc::poll(fds.as_mut_ptr(), nfds, -1) }; if r == -1 { let err = io::Error::last_os_error(); if err.kind() == io::ErrorKind::Interrupted { @@ -55,19 +58,20 @@ } } }; - if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? { - out_done = true; - } - data(true, &mut out, out_done); - if !err_done && fds[1].revents != 0 && handle(err_pipe.read_to_end(&mut err))? { + if !err_done && fds[errfd].revents != 0 && handle(err_pipe.read_to_end(&mut err))? { err_done = true; + nfds -= 1; } data(false, &mut err, err_done); - - if out_done && err_done { - return Ok(()) + if !out_done && fds[0].revents != 0 && handle(out_pipe.read_to_end(&mut out))? { + out_done = true; + fds[0].fd = err_pipe.as_raw_fd(); + errfd = 0; + nfds -= 1; } + data(true, &mut out, out_done); } + Ok(()) } } @@ -84,7 +88,7 @@ use self::miow::iocp::{CompletionPort, CompletionStatus}; use self::miow::pipe::NamedPipe; use self::miow::Overlapped; - use self::winapi::ERROR_BROKEN_PIPE; + use self::winapi::shared::winerror::ERROR_BROKEN_PIPE; struct Pipe<'a> { dst: &'a mut Vec, diff -Nru cargo-0.25.0/src/cargo/util/toml/mod.rs cargo-0.26.0/src/cargo/util/toml/mod.rs --- cargo-0.25.0/src/cargo/util/toml/mod.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/cargo/util/toml/mod.rs 2018-02-26 21:17:55.000000000 +0000 @@ -14,9 +14,9 @@ use core::{SourceId, Profiles, PackageIdSpec, GitReference, WorkspaceConfig, WorkspaceRootConfig}; use core::{Summary, Manifest, Target, Dependency, PackageId}; -use core::{EitherManifest, VirtualManifest, Features, Feature}; +use core::{EitherManifest, Epoch, VirtualManifest, Features, Feature}; use core::dependency::{Kind, Platform}; -use core::manifest::{LibKind, Profile, ManifestMetadata}; +use core::manifest::{LibKind, Profile, ManifestMetadata, Lto}; use sources::CRATES_IO; use util::paths; use util::{self, ToUrl, Config}; @@ -178,9 +178,11 @@ } #[derive(Deserialize, Serialize, Clone, Debug, Default)] +#[serde(rename_all = "kebab-case")] pub struct DetailedTomlDependency { version: Option, registry: Option, + registry_index: Option, path: Option, git: Option, branch: Option, @@ -188,15 +190,14 @@ rev: Option, features: Option>, optional: Option, - #[serde(rename = "default-features")] default_features: Option, #[serde(rename = "default_features")] default_features2: Option, } #[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "kebab-case")] pub struct TomlManifest { - #[serde(rename = "cargo-features")] cargo_features: Option>, package: Option>, project: Option>, @@ -207,11 +208,9 @@ test: Option>, bench: Option>, dependencies: Option>, - #[serde(rename = "dev-dependencies")] dev_dependencies: Option>, #[serde(rename = "dev_dependencies")] dev_dependencies2: Option>, - #[serde(rename = "build-dependencies")] build_dependencies: Option>, #[serde(rename = "build_dependencies")] build_dependencies2: Option>, @@ -328,7 +327,7 @@ pub struct TomlProfile { #[serde(rename = "opt-level")] opt_level: Option, - lto: Option, + lto: Option, #[serde(rename = "codegen-units")] codegen_units: Option, debug: Option, @@ -442,6 +441,7 @@ license_file: Option, repository: Option, metadata: Option, + rust: Option, } #[derive(Debug, Deserialize, Serialize)] @@ -471,13 +471,13 @@ } impl TomlManifest { - pub fn prepare_for_publish(&self) -> TomlManifest { + pub fn prepare_for_publish(&self, config: &Config) -> CargoResult { let mut package = self.package.as_ref() .or_else(|| self.project.as_ref()) .unwrap() .clone(); package.workspace = None; - return TomlManifest { + return Ok(TomlManifest { package: Some(package), project: None, profile: self.profile.clone(), @@ -486,56 +486,68 @@ example: self.example.clone(), test: self.test.clone(), bench: self.bench.clone(), - dependencies: map_deps(self.dependencies.as_ref()), - dev_dependencies: map_deps(self.dev_dependencies.as_ref() - .or_else(|| self.dev_dependencies2.as_ref())), + dependencies: map_deps(config, self.dependencies.as_ref())?, + dev_dependencies: map_deps(config, self.dev_dependencies.as_ref() + .or_else(|| self.dev_dependencies2.as_ref()))?, dev_dependencies2: None, - build_dependencies: map_deps(self.build_dependencies.as_ref() - .or_else(|| self.build_dependencies2.as_ref())), + build_dependencies: map_deps(config, self.build_dependencies.as_ref() + .or_else(|| self.build_dependencies2.as_ref()))?, build_dependencies2: None, features: self.features.clone(), - target: self.target.as_ref().map(|target_map| { + target: match self.target.as_ref().map(|target_map| { target_map.iter().map(|(k, v)| { - (k.clone(), TomlPlatform { - dependencies: map_deps(v.dependencies.as_ref()), - dev_dependencies: map_deps(v.dev_dependencies.as_ref() - .or_else(|| v.dev_dependencies2.as_ref())), + Ok((k.clone(), TomlPlatform { + dependencies: map_deps(config, v.dependencies.as_ref())?, + dev_dependencies: map_deps(config, v.dev_dependencies.as_ref() + .or_else(|| v.dev_dependencies2.as_ref()))?, dev_dependencies2: None, - build_dependencies: map_deps(v.build_dependencies.as_ref() - .or_else(|| v.build_dependencies2.as_ref())), + build_dependencies: map_deps(config, v.build_dependencies.as_ref() + .or_else(|| v.build_dependencies2.as_ref()))?, build_dependencies2: None, - }) + })) }).collect() - }), + }) { + Some(Ok(v)) => Some(v), + Some(Err(e)) => return Err(e), + None => None, + }, replace: None, patch: None, workspace: None, badges: self.badges.clone(), cargo_features: self.cargo_features.clone(), - }; + }); - fn map_deps(deps: Option<&BTreeMap>) - -> Option> + fn map_deps(config: &Config, deps: Option<&BTreeMap>) + -> CargoResult>> { let deps = match deps { Some(deps) => deps, - None => return None + None => return Ok(None), }; - Some(deps.iter().map(|(k, v)| (k.clone(), map_dependency(v))).collect()) + let deps = deps.iter() + .map(|(k, v)| Ok((k.clone(), map_dependency(config, v)?))) + .collect::>>()?; + Ok(Some(deps)) } - fn map_dependency(dep: &TomlDependency) -> TomlDependency { + fn map_dependency(config: &Config, dep: &TomlDependency) -> CargoResult { match *dep { TomlDependency::Detailed(ref d) => { let mut d = d.clone(); d.path.take(); // path dependencies become crates.io deps - TomlDependency::Detailed(d) + // registry specifications are elaborated to the index URL + if let Some(registry) = d.registry.take() { + let src = SourceId::alt_registry(config, ®istry)?; + d.registry_index = Some(src.url().to_string()); + } + Ok(TomlDependency::Detailed(d)) } TomlDependency::Simple(ref s) => { - TomlDependency::Detailed(DetailedTomlDependency { + Ok(TomlDependency::Detailed(DetailedTomlDependency { version: Some(s.clone()), ..Default::default() - }) + })) } } } @@ -704,6 +716,19 @@ Some(VecStringOrBool::Bool(false)) => Some(vec![]), None | Some(VecStringOrBool::Bool(true)) => None, }; + + let epoch = if let Some(ref epoch) = project.rust { + features.require(Feature::epoch()).chain_err(|| { + "epoches are unstable" + })?; + if let Ok(epoch) = epoch.parse() { + epoch + } else { + bail!("the `rust` key must be one of: `2015`, `2018`") + } + } else { + Epoch::Epoch2015 + }; let mut manifest = Manifest::new(summary, targets, exclude, @@ -716,6 +741,7 @@ patch, workspace_config, features, + epoch, project.im_a_teapot, Rc::clone(me)); if project.license_file.is_some() && project.license.is_some() { @@ -925,12 +951,26 @@ } } - let new_source_id = match (details.git.as_ref(), details.path.as_ref(), details.registry.as_ref()) { - (Some(_), _, Some(_)) => bail!("dependency ({}) specification is ambiguous. \ + let registry_id = match details.registry { + Some(ref registry) => { + cx.features.require(Feature::alternative_registries())?; + SourceId::alt_registry(cx.config, registry)? + } + None => SourceId::crates_io(cx.config)? + }; + + let new_source_id = match ( + details.git.as_ref(), + details.path.as_ref(), + details.registry.as_ref(), + details.registry_index.as_ref(), + ) { + (Some(_), _, Some(_), _) | + (Some(_), _, _, Some(_))=> bail!("dependency ({}) specification is ambiguous. \ Only one of `git` or `registry` is allowed.", name), - (_, Some(_), Some(_)) => bail!("dependency ({}) specification is ambiguous. \ - Only one of `path` or `registry` is allowed.", name), - (Some(git), maybe_path, _) => { + (_, _, Some(_), Some(_)) => bail!("dependency ({}) specification is ambiguous. \ + Only one of `registry` or `registry-index` is allowed.", name), + (Some(git), maybe_path, _, _) => { if maybe_path.is_some() { let msg = format!("dependency ({}) specification is ambiguous. \ Only one of `git` or `path` is allowed. \ @@ -957,7 +997,7 @@ let loc = git.to_url()?; SourceId::for_git(&loc, reference)? }, - (None, Some(path), _) => { + (None, Some(path), _, _) => { cx.nested_paths.push(PathBuf::from(path)); // If the source id for the package we're parsing is a path // source, then we normalize the path here to get rid of @@ -975,11 +1015,12 @@ cx.source_id.clone() } }, - (None, None, Some(registry)) => { - cx.features.require(Feature::alternative_registries())?; - SourceId::alt_registry(cx.config, registry)? + (None, None, Some(registry), None) => SourceId::alt_registry(cx.config, registry)?, + (None, None, None, Some(registry_index)) => { + let url = registry_index.to_url()?; + SourceId::for_registry(&url)? } - (None, None, None) => SourceId::crates_io(cx.config)?, + (None, None, None, None) => SourceId::crates_io(cx.config)?, }; let version = details.version.as_ref().map(|v| &v[..]); @@ -995,7 +1036,8 @@ .or(details.default_features2) .unwrap_or(true)) .set_optional(details.optional.unwrap_or(false)) - .set_platform(cx.platform.clone()); + .set_platform(cx.platform.clone()) + .set_registry_id(®istry_id); if let Some(kind) = kind { dep.set_kind(kind); } @@ -1123,7 +1165,7 @@ fn merge(profile: Profile, toml: Option<&TomlProfile>) -> Profile { let &TomlProfile { - ref opt_level, lto, codegen_units, ref debug, debug_assertions, rpath, + ref opt_level, ref lto, codegen_units, ref debug, debug_assertions, rpath, ref panic, ref overflow_checks, ref incremental, } = match toml { Some(toml) => toml, @@ -1137,7 +1179,11 @@ }; Profile { opt_level: opt_level.clone().unwrap_or(TomlOptLevel(profile.opt_level)).0, - lto: lto.unwrap_or(profile.lto), + lto: match *lto { + Some(StringOrBool::Bool(b)) => Lto::Bool(b), + Some(StringOrBool::String(ref n)) => Lto::Named(n.clone()), + None => profile.lto, + }, codegen_units: codegen_units, rustc_args: None, rustdoc_args: None, diff -Nru cargo-0.25.0/src/ci/dox.sh cargo-0.26.0/src/ci/dox.sh --- cargo-0.25.0/src/ci/dox.sh 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/ci/dox.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -set -ex - -DOCS="index faq config guide manifest build-script pkgid-spec crates-io \ - environment-variables specifying-dependencies source-replacement \ - external-tools" -ASSETS="CNAME images/noise.png images/forkme.png images/Cargo-Logo-Small.png \ - stylesheets/all.css stylesheets/normalize.css javascripts/prism.js \ - javascripts/all.js stylesheets/prism.css images/circle-with-i.png \ - images/search.png images/org-level-acl.png images/auth-level-acl.png \ - favicon.ico policies.html" - -for asset in $ASSETS; do - mkdir -p `dirname target/doc/$asset` - cp src/doc/$asset target/doc/$asset -done - -for doc in $DOCS; do - rustdoc \ - --markdown-no-toc \ - --markdown-css stylesheets/normalize.css \ - --markdown-css stylesheets/all.css \ - --markdown-css stylesheets/prism.css \ - --html-in-header src/doc/html-headers.html \ - --html-before-content src/doc/header.html \ - --html-after-content src/doc/footer.html \ - -o target/doc \ - src/doc/$doc.md -done - -# Temporary preview for mdBook docs -cd src/doc/book -$HOME/.cargo/bin/mdbook build --no-create --dest-dir ../../../target/doc/book -cd ../../../ diff -Nru cargo-0.25.0/src/crates-io/Cargo.toml cargo-0.26.0/src/crates-io/Cargo.toml --- cargo-0.25.0/src/crates-io/Cargo.toml 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/crates-io/Cargo.toml 2018-02-26 21:17:55.000000000 +0000 @@ -1,8 +1,8 @@ [package] name = "crates-io" -version = "0.14.0" +version = "0.15.0" authors = ["Alex Crichton "] -license = "MIT/Apache-2.0" +license = "MIT OR Apache-2.0" repository = "https://github.com/rust-lang/cargo" description = """ Helpers for interacting with crates.io diff -Nru cargo-0.25.0/src/crates-io/LICENSE-APACHE cargo-0.26.0/src/crates-io/LICENSE-APACHE --- cargo-0.25.0/src/crates-io/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/crates-io/LICENSE-APACHE 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/src/crates-io/LICENSE-MIT cargo-0.26.0/src/crates-io/LICENSE-MIT --- cargo-0.25.0/src/crates-io/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/crates-io/LICENSE-MIT 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,23 @@ +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. diff -Nru cargo-0.25.0/src/doc/book/book.toml cargo-0.26.0/src/doc/book/book.toml --- cargo-0.25.0/src/doc/book/book.toml 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/book.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -title = "The Cargo Book" -author = "Alex Crichton, Steve Klabnik and Carol Nichols, with Contributions from the Rust Community" diff -Nru cargo-0.25.0/src/doc/book/.gitignore cargo-0.26.0/src/doc/book/.gitignore --- cargo-0.25.0/src/doc/book/.gitignore 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/.gitignore 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -/book diff -Nru cargo-0.25.0/src/doc/book/README.md cargo-0.26.0/src/doc/book/README.md --- cargo-0.25.0/src/doc/book/README.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -# The Cargo Book - - -### Requirements - -Building the book requires [mdBook]. To get it: - -[mdBook]: https://github.com/azerupi/mdBook - -```shell -$ cargo install mdbook -``` - -### Building - -To build the book: - -```shell -$ mdbook build -``` - -The output will be in the `book` subdirectory. To check it out, open it in -your web browser. - -_Firefox:_ -```shell -$ firefox book/index.html # Linux -$ open -a "Firefox" book/index.html # OS X -$ Start-Process "firefox.exe" .\book\index.html # Windows (PowerShell) -$ start firefox.exe .\book\index.html # Windows (Cmd) -``` - -_Chrome:_ -```shell -$ google-chrome book/index.html # Linux -$ open -a "Google Chrome" book/index.html # OS X -$ Start-Process "chrome.exe" .\book\index.html # Windows (PowerShell) -$ start chrome.exe .\book\index.html # Windows (Cmd) -``` - - -## Contributing - -Given that the book is still in a draft state, we'd love your help! Please feel free to open -issues about anything, and send in PRs for things you'd like to fix or change. If your change is -large, please open an issue first, so we can make sure that it's something we'd accept before you -go through the work of getting a PR together. diff -Nru cargo-0.25.0/src/doc/book/src/faq.md cargo-0.26.0/src/doc/book/src/faq.md --- cargo-0.25.0/src/doc/book/src/faq.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/faq.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,193 +0,0 @@ -## Frequently Asked Questions - -### Is the plan to use GitHub as a package repository? - -No. The plan for Cargo is to use [crates.io], like npm or Rubygems do with -npmjs.org and rubygems.org. - -We plan to support git repositories as a source of packages forever, -because they can be used for early development and temporary patches, -even when people use the registry as the primary source of packages. - -### Why build crates.io rather than use GitHub as a registry? - -We think that it’s very important to support multiple ways to download -packages, including downloading from GitHub and copying packages into -your project itself. - -That said, we think that [crates.io] offers a number of important benefits, and -will likely become the primary way that people download packages in Cargo. - -For precedent, both Node.js’s [npm][1] and Ruby’s [bundler][2] support both a -central registry model as well as a Git-based model, and most packages -are downloaded through the registry in those ecosystems, with an -important minority of packages making use of git-based packages. - -[1]: https://www.npmjs.org -[2]: https://bundler.io - -Some of the advantages that make a central registry popular in other -languages include: - -* **Discoverability**. A central registry provides an easy place to look - for existing packages. Combined with tagging, this also makes it - possible for a registry to provide ecosystem-wide information, such as a - list of the most popular or most-depended-on packages. -* **Speed**. A central registry makes it possible to easily fetch just - the metadata for packages quickly and efficiently, and then to - efficiently download just the published package, and not other bloat - that happens to exist in the repository. This adds up to a significant - improvement in the speed of dependency resolution and fetching. As - dependency graphs scale up, downloading all of the git repositories bogs - down fast. Also remember that not everybody has a high-speed, - low-latency Internet connection. - -### Will Cargo work with C code (or other languages)? - -Yes! - -Cargo handles compiling Rust code, but we know that many Rust projects -link against C code. We also know that there are decades of tooling -built up around compiling languages other than Rust. - -Our solution: Cargo allows a package to [specify a script](reference/build-scripts.html) -(written in Rust) to run before invoking `rustc`. Rust is leveraged to -implement platform-specific configuration and refactor out common build -functionality among packages. - -### Can Cargo be used inside of `make` (or `ninja`, or ...) - -Indeed. While we intend Cargo to be useful as a standalone way to -compile Rust projects at the top-level, we know that some people will -want to invoke Cargo from other build tools. - -We have designed Cargo to work well in those contexts, paying attention -to things like error codes and machine-readable output modes. We still -have some work to do on those fronts, but using Cargo in the context of -conventional scripts is something we designed for from the beginning and -will continue to prioritize. - -### Does Cargo handle multi-platform projects or cross-compilation? - -Rust itself provides facilities for configuring sections of code based -on the platform. Cargo also supports [platform-specific -dependencies][target-deps], and we plan to support more per-platform -configuration in `Cargo.toml` in the future. - -[target-deps]: reference/specifying-dependencies.html#platform-specific-dependencies - -In the longer-term, we’re looking at ways to conveniently cross-compile -projects using Cargo. - -### Does Cargo support environments, like `production` or `test`? - -We support environments through the use of [profiles][profile] to support: - -[profile]: reference/manifest.html#the-profile-sections - -* environment-specific flags (like `-g --opt-level=0` for development - and `--opt-level=3` for production). -* environment-specific dependencies (like `hamcrest` for test assertions). -* environment-specific `#[cfg]` -* a `cargo test` command - -### Does Cargo work on Windows? - -Yes! - -All commits to Cargo are required to pass the local test suite on Windows. -If, however, you find a Windows issue, we consider it a bug, so [please file an -issue][3]. - -[3]: https://github.com/rust-lang/cargo/issues - -### Why do binaries have `Cargo.lock` in version control, but not libraries? - -The purpose of a `Cargo.lock` is to describe the state of the world at the time -of a successful build. It is then used to provide deterministic builds across -whatever machine is building the project by ensuring that the exact same -dependencies are being compiled. - -This property is most desirable from applications and projects which are at the -very end of the dependency chain (binaries). As a result, it is recommended that -all binaries check in their `Cargo.lock`. - -For libraries the situation is somewhat different. A library is not only used by -the library developers, but also any downstream consumers of the library. Users -dependent on the library will not inspect the library’s `Cargo.lock` (even if it -exists). This is precisely because a library should **not** be deterministically -recompiled for all users of the library. - -If a library ends up being used transitively by several dependencies, it’s -likely that just a single copy of the library is desired (based on semver -compatibility). If all libraries were to check in their `Cargo.lock`, then -multiple copies of the library would be used, and perhaps even a version -conflict. - -In other words, libraries specify semver requirements for their dependencies but -cannot see the full picture. Only end products like binaries have a full -picture to decide what versions of dependencies should be used. - -### Can libraries use `*` as a version for their dependencies? - -**As of January 22nd, 2016, [crates.io] rejects all packages (not just libraries) -with wildcard dependency constraints.** - -While libraries _can_, strictly speaking, they should not. A version requirement -of `*` says “This will work with every version ever,” which is never going -to be true. Libraries should always specify the range that they do work with, -even if it’s something as general as “every 1.x.y version.” - -### Why `Cargo.toml`? - -As one of the most frequent interactions with Cargo, the question of why the -configuration file is named `Cargo.toml` arises from time to time. The leading -capital-`C` was chosen to ensure that the manifest was grouped with other -similar configuration files in directory listings. Sorting files often puts -capital letters before lowercase letters, ensuring files like `Makefile` and -`Cargo.toml` are placed together. The trailing `.toml` was chosen to emphasize -the fact that the file is in the [TOML configuration -format](https://github.com/toml-lang/toml). - -Cargo does not allow other names such as `cargo.toml` or `Cargofile` to -emphasize the ease of how a Cargo repository can be identified. An option of -many possible names has historically led to confusion where one case was handled -but others were accidentally forgotten. - -[crates.io]: https://crates.io/ - -### How can Cargo work offline? - -Cargo is often used in situations with limited or no network access such as -airplanes, CI environments, or embedded in large production deployments. Users -are often surprised when Cargo attempts to fetch resources from the network, and -hence the request for Cargo to work offline comes up frequently. - -Cargo, at its heart, will not attempt to access the network unless told to do -so. That is, if no crates comes from crates.io, a git repository, or some other -network location, Cargo will never attempt to make a network connection. As a -result, if Cargo attempts to touch the network, then it's because it needs to -fetch a required resource. - -Cargo is also quite aggressive about caching information to minimize the amount -of network activity. It will guarantee, for example, that if `cargo build` (or -an equivalent) is run to completion then the next `cargo build` is guaranteed to -not touch the network so long as `Cargo.toml` has not been modified in the -meantime. This avoidance of the network boils down to a `Cargo.lock` existing -and a populated cache of the crates reflected in the lock file. If either of -these components are missing, then they're required for the build to succeed and -must be fetched remotely. - -As of Rust 1.11.0 Cargo understands a new flag, `--frozen`, which is an -assertion that it shouldn't touch the network. When passed, Cargo will -immediately return an error if it would otherwise attempt a network request. -The error should include contextual information about why the network request is -being made in the first place to help debug as well. Note that this flag *does -not change the behavior of Cargo*, it simply asserts that Cargo shouldn't touch -the network as a previous command has been run to ensure that network activity -shouldn't be necessary. - -For more information about vendoring, see documentation on [source -replacement][replace]. - -[replace]: reference/source-replacement.html diff -Nru cargo-0.25.0/src/doc/book/src/getting-started/first-steps.md cargo-0.26.0/src/doc/book/src/getting-started/first-steps.md --- cargo-0.25.0/src/doc/book/src/getting-started/first-steps.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/getting-started/first-steps.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,70 +0,0 @@ -## First Steps with Cargo - -To start a new project with Cargo, use `cargo new`: - -```shell -$ cargo new hello_world --bin -``` - -We’re passing `--bin` because we’re making a binary program: if we -were making a library, we’d leave it off. - -Let’s check out what Cargo has generated for us: - -```shell -$ cd hello_world -$ tree . -. -├── Cargo.toml -└── src - └── main.rs - -1 directory, 2 files -``` - -This is all we need to get started. First, let’s check out `Cargo.toml`: - -```toml -[package] -name = "hello_world" -version = "0.1.0" -authors = ["Your Name "] -``` - -This is called a **manifest**, and it contains all of the metadata that Cargo -needs to compile your project. - -Here’s what’s in `src/main.rs`: - -```rust -fn main() { - println!("Hello, world!"); -} -``` - -Cargo generated a “hello world” for us. Let’s compile it: - -```shell -$ cargo build - Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) -``` - -And then run it: - -```shell -$ ./target/debug/hello_world -Hello, world! -``` - -We can also use `cargo run` to compile and then run it, all in one step: - -```shell -$ cargo run - Fresh hello_world v0.1.0 (file:///path/to/project/hello_world) - Running `target/hello_world` -Hello, world! -``` - -### Going further - -For more details on using Cargo, check out the [Cargo Guide](guide/index.html) diff -Nru cargo-0.25.0/src/doc/book/src/getting-started/index.md cargo-0.26.0/src/doc/book/src/getting-started/index.md --- cargo-0.25.0/src/doc/book/src/getting-started/index.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/getting-started/index.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -## Getting Started - -To get started with Cargo, install Cargo (and Rust) and set up your first crate. - -* [Installation](getting-started/installation.html) -* [First steps with Cargo](getting-started/first-steps.html) diff -Nru cargo-0.25.0/src/doc/book/src/getting-started/installation.md cargo-0.26.0/src/doc/book/src/getting-started/installation.md --- cargo-0.25.0/src/doc/book/src/getting-started/installation.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/getting-started/installation.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -## Installation - -### Install Stable Rust and Cargo - -The easiest way to get Cargo is to get the current stable release of [Rust] by -using the `rustup` script: - -```shell -$ curl -sSf https://static.rust-lang.org/rustup.sh | sh -``` - -After this, you can use the `rustup` command to also install `beta` or `nightly` -channels for Rust and Cargo. - -### Install Nightly Cargo - -To install just Cargo, the current recommended installation method is through -the official nightly builds. Note that Cargo will also require that [Rust] is -already installed on the system. - -| Platform | 64-bit | 32-bit | -|------------------|-------------------|-------------------| -| Linux binaries | [tar.gz][linux64] | [tar.gz][linux32] | -| MacOS binaries | [tar.gz][mac64] | [tar.gz][mac32] | -| Windows binaries | [tar.gz][win64] | [tar.gz][win32] | - -### Build and Install Cargo from Source - -Alternatively, you can [build Cargo from source][compiling-from-source]. - -[rust]: https://www.rust-lang.org/ -[linux64]: https://static.rust-lang.org/cargo-dist/cargo-nightly-x86_64-unknown-linux-gnu.tar.gz -[linux32]: https://static.rust-lang.org/cargo-dist/cargo-nightly-i686-unknown-linux-gnu.tar.gz -[mac64]: https://static.rust-lang.org/cargo-dist/cargo-nightly-x86_64-apple-darwin.tar.gz -[mac32]: https://static.rust-lang.org/cargo-dist/cargo-nightly-i686-apple-darwin.tar.gz -[win64]: https://static.rust-lang.org/cargo-dist/cargo-nightly-x86_64-pc-windows-gnu.tar.gz -[win32]: https://static.rust-lang.org/cargo-dist/cargo-nightly-i686-pc-windows-gnu.tar.gz -[compiling-from-source]: https://github.com/rust-lang/cargo#compiling-from-source diff -Nru cargo-0.25.0/src/doc/book/src/guide/cargo-toml-vs-cargo-lock.md cargo-0.26.0/src/doc/book/src/guide/cargo-toml-vs-cargo-lock.md --- cargo-0.25.0/src/doc/book/src/guide/cargo-toml-vs-cargo-lock.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/guide/cargo-toml-vs-cargo-lock.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -## Cargo.toml vs Cargo.lock - -`Cargo.toml` and `Cargo.lock` serve two different purposes. Before we talk -about them, here’s a summary: - -* `Cargo.toml` is about describing your dependencies in a broad sense, and is - written by you. -* `Cargo.lock` contains exact information about your dependencies. It is - maintained by Cargo and should not be manually edited. - -If you’re building a library that other projects will depend on, put -`Cargo.lock` in your `.gitignore`. If you’re building an executable like a -command-line tool or an application, check `Cargo.lock` into `git`. If you're -curious about why that is, see ["Why do binaries have `Cargo.lock` in version -control, but not libraries?" in the -FAQ](faq.html#why-do-binaries-have-cargolock-in-version-control-but-not-libraries). - -Let’s dig in a little bit more. - -`Cargo.toml` is a **manifest** file in which we can specify a bunch of -different metadata about our project. For example, we can say that we depend -on another project: - -```toml -[package] -name = "hello_world" -version = "0.1.0" -authors = ["Your Name "] - -[dependencies] -rand = { git = "https://github.com/rust-lang-nursery/rand.git" } -``` - -This project has a single dependency, on the `rand` library. We’ve stated in -this case that we’re relying on a particular Git repository that lives on -GitHub. Since we haven’t specified any other information, Cargo assumes that -we intend to use the latest commit on the `master` branch to build our project. - -Sound good? Well, there’s one problem: If you build this project today, and -then you send a copy to me, and I build this project tomorrow, something bad -could happen. There could be more commits to `rand` in the meantime, and my -build would include new commits while yours would not. Therefore, we would -get different builds. This would be bad because we want reproducible builds. - -We could fix this problem by putting a `rev` line in our `Cargo.toml`: - -```toml -[dependencies] -rand = { git = "https://github.com/rust-lang-nursery/rand.git", rev = "9f35b8e" } -``` - -Now our builds will be the same. But there’s a big drawback: now we have to -manually think about SHA-1s every time we want to update our library. This is -both tedious and error prone. - -Enter the `Cargo.lock`. Because of its existence, we don’t need to manually -keep track of the exact revisions: Cargo will do it for us. When we have a -manifest like this: - -```toml -[package] -name = "hello_world" -version = "0.1.0" -authors = ["Your Name "] - -[dependencies] -rand = { git = "https://github.com/rust-lang-nursery/rand.git" } -``` - -Cargo will take the latest commit and write that information out into our -`Cargo.lock` when we build for the first time. That file will look like this: - -```toml -[[package]] -name = "hello_world" -version = "0.1.0" -dependencies = [ - "rand 0.1.0 (git+https://github.com/rust-lang-nursery/rand.git#9f35b8e439eeedd60b9414c58f389bdc6a3284f9)", -] - -[[package]] -name = "rand" -version = "0.1.0" -source = "git+https://github.com/rust-lang-nursery/rand.git#9f35b8e439eeedd60b9414c58f389bdc6a3284f9" -``` - -You can see that there’s a lot more information here, including the exact -revision we used to build. Now when you give your project to someone else, -they’ll use the exact same SHA, even though we didn’t specify it in our -`Cargo.toml`. - -When we’re ready to opt in to a new version of the library, Cargo can -re-calculate the dependencies and update things for us: - -```shell -$ cargo update # updates all dependencies -$ cargo update -p rand # updates just “rand” -``` - -This will write out a new `Cargo.lock` with the new version information. Note -that the argument to `cargo update` is actually a -[Package ID Specification](reference/pkgid-spec.html) and `rand` is just a short -specification. diff -Nru cargo-0.25.0/src/doc/book/src/guide/continuous-integration.md cargo-0.26.0/src/doc/book/src/guide/continuous-integration.md --- cargo-0.25.0/src/doc/book/src/guide/continuous-integration.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/guide/continuous-integration.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -## Continuous Integration - -### Travis CI - -To test your project on Travis CI, here is a sample `.travis.yml` file: - -```yaml -language: rust -rust: - - stable - - beta - - nightly -matrix: - allow_failures: - - rust: nightly -``` - -This will test all three release channels, but any breakage in nightly -will not fail your overall build. Please see the [Travis CI Rust -documentation](https://docs.travis-ci.com/user/languages/rust/) for more -information. diff -Nru cargo-0.25.0/src/doc/book/src/guide/creating-a-new-project.md cargo-0.26.0/src/doc/book/src/guide/creating-a-new-project.md --- cargo-0.25.0/src/doc/book/src/guide/creating-a-new-project.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/guide/creating-a-new-project.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,89 +0,0 @@ -## Creating a New Project - -To start a new project with Cargo, use `cargo new`: - -```shell -$ cargo new hello_world --bin -``` - -We’re passing `--bin` because we’re making a binary program: if we -were making a library, we’d leave it off. This also initializes a new `git` -repository by default. If you don't want it to do that, pass `--vcs none`. - -Let’s check out what Cargo has generated for us: - -```shell -$ cd hello_world -$ tree . -. -├── Cargo.toml -└── src - └── main.rs - -1 directory, 2 files -``` - -If we had just used `cargo new hello_world` without the `--bin` flag, then -we would have a `lib.rs` instead of a `main.rs`. For now, however, this is all -we need to get started. First, let’s check out `Cargo.toml`: - -```toml -[package] -name = "hello_world" -version = "0.1.0" -authors = ["Your Name "] -``` - -This is called a **manifest**, and it contains all of the metadata that Cargo -needs to compile your project. - -Here’s what’s in `src/main.rs`: - -```rust -fn main() { - println!("Hello, world!"); -} -``` - -Cargo generated a “hello world” for us. Let’s compile it: - -```shell -$ cargo build - Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) -``` - -And then run it: - -```shell -$ ./target/debug/hello_world -Hello, world! -``` - -We can also use `cargo run` to compile and then run it, all in one step (You -won't see the `Compiling` line if you have not made any changes since you last -compiled): - -```shell -$ cargo run - Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) - Running `target/debug/hello_world` -Hello, world! -``` - -You’ll now notice a new file, `Cargo.lock`. It contains information about our -dependencies. Since we don’t have any yet, it’s not very interesting. - -Once you’re ready for release, you can use `cargo build --release` to compile -your files with optimizations turned on: - -```shell -$ cargo build --release - Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) -``` - -`cargo build --release` puts the resulting binary in `target/release` instead of -`target/debug`. - -Compiling in debug mode is the default for development-- compilation time is -shorter since the compiler doesn't do optimizations, but the code will run -slower. Release mode takes longer to compile, but the code will run faster. diff -Nru cargo-0.25.0/src/doc/book/src/guide/dependencies.md cargo-0.26.0/src/doc/book/src/guide/dependencies.md --- cargo-0.25.0/src/doc/book/src/guide/dependencies.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/guide/dependencies.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,90 +0,0 @@ -## Dependencies - -[crates.io] is the Rust community's central package registry that serves as a -location to discover and download packages. `cargo` is configured to use it by -default to find requested packages. - -To depend on a library hosted on [crates.io], add it to your `Cargo.toml`. - -[crates.io]: https://crates.io/ - -### Adding a dependency - -If your `Cargo.toml` doesn't already have a `[dependencies]` section, add that, -then list the crate name and version that you would like to use. This example -adds a dependency of the `time` crate: - -```toml -[dependencies] -time = "0.1.12" -``` - -The version string is a [semver] version requirement. The [specifying -dependencies](reference/specifying-dependencies.html) docs have more information about -the options you have here. - -[semver]: https://github.com/steveklabnik/semver#requirements - -If we also wanted to add a dependency on the `regex` crate, we would not need -to add `[dependencies]` for each crate listed. Here's what your whole -`Cargo.toml` file would look like with dependencies on the `time` and `regex` -crates: - -```toml -[package] -name = "hello_world" -version = "0.1.0" -authors = ["Your Name "] - -[dependencies] -time = "0.1.12" -regex = "0.1.41" -``` - -Re-run `cargo build`, and Cargo will fetch the new dependencies and all of -their dependencies, compile them all, and update the `Cargo.lock`: - -```shell -$ cargo build - Updating registry `https://github.com/rust-lang/crates.io-index` - Downloading memchr v0.1.5 - Downloading libc v0.1.10 - Downloading regex-syntax v0.2.1 - Downloading memchr v0.1.5 - Downloading aho-corasick v0.3.0 - Downloading regex v0.1.41 - Compiling memchr v0.1.5 - Compiling libc v0.1.10 - Compiling regex-syntax v0.2.1 - Compiling memchr v0.1.5 - Compiling aho-corasick v0.3.0 - Compiling regex v0.1.41 - Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) -``` - -Our `Cargo.lock` contains the exact information about which revision of all of -these dependencies we used. - -Now, if `regex` gets updated, we will still build with the same revision until -we choose to `cargo update`. - -You can now use the `regex` library using `extern crate` in `main.rs`. - -``` -extern crate regex; - -use regex::Regex; - -fn main() { - let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); - println!("Did our date match? {}", re.is_match("2014-01-01")); -} -``` - -Running it will show: - -```shell -$ cargo run - Running `target/hello_world` -Did our date match? true -``` diff -Nru cargo-0.25.0/src/doc/book/src/guide/index.md cargo-0.26.0/src/doc/book/src/guide/index.md --- cargo-0.25.0/src/doc/book/src/guide/index.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/guide/index.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -## Cargo Guide - -This guide will give you all that you need to know about how to use Cargo to -develop Rust projects. - -* [Why Cargo Exists](guide/why-cargo-exists.html) -* [Creating a New Project](guide/creating-a-new-project.html) -* [Working on an Existing Cargo Project](guide/working-on-an-existing-project.html) -* [Dependencies](guide/dependencies.html) -* [Project Layout](guide/project-layout.html) -* [Cargo.toml vs Cargo.lock](guide/cargo-toml-vs-cargo-lock.html) -* [Tests](guide/tests.html) -* [Continuous Integration](guide/continuous-integration.html) diff -Nru cargo-0.25.0/src/doc/book/src/guide/project-layout.md cargo-0.26.0/src/doc/book/src/guide/project-layout.md --- cargo-0.25.0/src/doc/book/src/guide/project-layout.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/guide/project-layout.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,35 +0,0 @@ -## Project Layout - -Cargo uses conventions for file placement to make it easy to dive into a new -Cargo project: - -```shell -. -├── Cargo.lock -├── Cargo.toml -├── benches -│   └── large-input.rs -├── examples -│   └── simple.rs -├── src -│   ├── bin -│   │   └── another_executable.rs -│   ├── lib.rs -│   └── main.rs -└── tests - └── some-integration-tests.rs -``` - -* `Cargo.toml` and `Cargo.lock` are stored in the root of your project (*package - root*). -* Source code goes in the `src` directory. -* The default library file is `src/lib.rs`. -* The default executable file is `src/main.rs`. -* Other executables can be placed in `src/bin/*.rs`. -* Integration tests go in the `tests` directory (unit tests go in each file - they're testing). -* Examples go in the `examples` directory. -* Benchmarks go in the `benches` directory. - -These are explained in more detail in the [manifest -description](reference/manifest.html#the-project-layout). diff -Nru cargo-0.25.0/src/doc/book/src/guide/tests.md cargo-0.26.0/src/doc/book/src/guide/tests.md --- cargo-0.25.0/src/doc/book/src/guide/tests.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/guide/tests.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -## Tests - -Cargo can run your tests with the `cargo test` command. Cargo looks for tests -to run in two places: in each of your `src` files and any tests in `tests/`. -Tests in your `src` files should be unit tests, and tests in `tests/` should be -integration-style tests. As such, you’ll need to import your crates into -the files in `tests`. - -Here's an example of running `cargo test` in our project, which currently has -no tests: - -```shell -$ cargo test - Compiling rand v0.1.0 (https://github.com/rust-lang-nursery/rand.git#9f35b8e) - Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) - Running target/test/hello_world-9c2b65bbb79eabce - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -If our project had tests, we would see more output with the correct number of -tests. - -You can also run a specific test by passing a filter: - -```shell -$ cargo test foo -``` - -This will run any test with `foo` in its name. - -`cargo test` runs additional checks as well. For example, it will compile any -examples you’ve included and will also test the examples in your -documentation. Please see the [testing guide][testing] in the Rust -documentation for more details. - -[testing]: https://doc.rust-lang.org/book/testing.html diff -Nru cargo-0.25.0/src/doc/book/src/guide/why-cargo-exists.md cargo-0.26.0/src/doc/book/src/guide/why-cargo-exists.md --- cargo-0.25.0/src/doc/book/src/guide/why-cargo-exists.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/guide/why-cargo-exists.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -## Why Cargo Exists - -Cargo is a tool that allows Rust projects to declare their various -dependencies and ensure that you’ll always get a repeatable build. - -To accomplish this goal, Cargo does four things: - -* Introduces two metadata files with various bits of project information. -* Fetches and builds your project’s dependencies. -* Invokes `rustc` or another build tool with the correct parameters to build - your project. -* Introduces conventions to make working with Rust projects easier. diff -Nru cargo-0.25.0/src/doc/book/src/guide/working-on-an-existing-project.md cargo-0.26.0/src/doc/book/src/guide/working-on-an-existing-project.md --- cargo-0.25.0/src/doc/book/src/guide/working-on-an-existing-project.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/guide/working-on-an-existing-project.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -## Working on an Existing Cargo Project - -If you download an existing project that uses Cargo, it’s really easy -to get going. - -First, get the project from somewhere. In this example, we’ll use `rand` -cloned from its repository on GitHub: - -```shell -$ git clone https://github.com/rust-lang-nursery/rand.git -$ cd rand -``` - -To build, use `cargo build`: - -```shell -$ cargo build - Compiling rand v0.1.0 (file:///path/to/project/rand) -``` - -This will fetch all of the dependencies and then build them, along with the -project. Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/book/src/images/auth-level-acl.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/book/src/images/auth-level-acl.png differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/book/src/images/Cargo-Logo-Small.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/book/src/images/Cargo-Logo-Small.png differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/book/src/images/org-level-acl.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/book/src/images/org-level-acl.png differ diff -Nru cargo-0.25.0/src/doc/book/src/index.md cargo-0.26.0/src/doc/book/src/index.md --- cargo-0.25.0/src/doc/book/src/index.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/index.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -# The Cargo Book - -![Cargo Logo](images/Cargo-Logo-Small.png) - -Cargo is the [Rust] *package manager*. Cargo downloads your Rust project’s -dependencies, compiles your project, makes packages, and upload them to -[crates.io], the Rust community’s *package registry*. - - -### Sections - -**[Getting Started](getting-started/index.html)** - -To get started with Cargo, install Cargo (and Rust) and set up your first crate. - -**[Cargo Guide](guide/index.html)** - -The guide will give you all you need to know about how to use Cargo to develop -Rust projects. - -**[Cargo Reference](reference/index.html)** - -The reference covers the details of various areas of Cargo. - -**[Frequently Asked Questions](faq.html)** - -[rust]: https://www.rust-lang.org/ -[crates.io]: https://crates.io/ diff -Nru cargo-0.25.0/src/doc/book/src/reference/build-scripts.md cargo-0.26.0/src/doc/book/src/reference/build-scripts.md --- cargo-0.25.0/src/doc/book/src/reference/build-scripts.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/reference/build-scripts.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,557 +0,0 @@ -## Build Scripts - -Some packages need to compile third-party non-Rust code, for example C -libraries. Other packages need to link to C libraries which can either be -located on the system or possibly need to be built from source. Others still -need facilities for functionality such as code generation before building (think -parser generators). - -Cargo does not aim to replace other tools that are well-optimized for -these tasks, but it does integrate with them with the `build` configuration -option. - -```toml -[package] -# ... -build = "build.rs" -``` - -The Rust file designated by the `build` command (relative to the package root) -will be compiled and invoked before anything else is compiled in the package, -allowing your Rust code to depend on the built or generated artifacts. -By default Cargo looks up for `"build.rs"` file in a package root (even if you -do not specify a value for `build`). Use `build = "custom_build_name.rs"` to specify -a custom build name or `build = false` to disable automatic detection of the build script. - -Some example use cases of the build command are: - -* Building a bundled C library. -* Finding a C library on the host system. -* Generating a Rust module from a specification. -* Performing any platform-specific configuration needed for the crate. - -Each of these use cases will be detailed in full below to give examples of how -the build command works. - -### Inputs to the Build Script - -When the build script is run, there are a number of inputs to the build script, -all passed in the form of [environment variables][env]. - -In addition to environment variables, the build script’s current directory is -the source directory of the build script’s package. - -[env]: reference/environment-variables.html - -### Outputs of the Build Script - -All the lines printed to stdout by a build script are written to a file like -`target/debug/build//output` (the precise location may depend on your -configuration). Any line that starts with `cargo:` is interpreted directly by -Cargo. This line must be of the form `cargo:key=value`, like the examples below: - -```shell -# specially recognized by Cargo -cargo:rustc-link-lib=static=foo -cargo:rustc-link-search=native=/path/to/foo -cargo:rustc-cfg=foo -cargo:rustc-env=FOO=bar -# arbitrary user-defined metadata -cargo:root=/path/to/foo -cargo:libdir=/path/to/foo/lib -cargo:include=/path/to/foo/include -``` - -On the other hand, lines printed to stderr are written to a file like -`target/debug/build//stderr` but are not interpreted by cargo. - -There are a few special keys that Cargo recognizes, some affecting how the -crate is built: - -* `rustc-link-lib=[KIND=]NAME` indicates that the specified value is a library - name and should be passed to the compiler as a `-l` flag. The optional `KIND` - can be one of `static`, `dylib` (the default), or `framework`, see - `rustc --help` for more details. -* `rustc-link-search=[KIND=]PATH` indicates the specified value is a library - search path and should be passed to the compiler as a `-L` flag. The optional - `KIND` can be one of `dependency`, `crate`, `native`, `framework` or `all` - (the default), see `rustc --help` for more details. -* `rustc-flags=FLAGS` is a set of flags passed to the compiler, only `-l` and - `-L` flags are supported. -* `rustc-cfg=FEATURE` indicates that the specified feature will be passed as a - `--cfg` flag to the compiler. This is often useful for performing compile-time - detection of various features. -* `rustc-env=VAR=VALUE` indicates that the specified environment variable - will be added to the environment which the compiler is run within. - The value can be then retrieved by the `env!` macro in the compiled crate. - This is useful for embedding additional metadata in crate's code, - such as the hash of Git HEAD or the unique identifier of a continuous - integration server. -* `rerun-if-changed=PATH` is a path to a file or directory which indicates that - the build script should be re-run if it changes (detected by a more-recent - last-modified timestamp on the file). Normally build scripts are re-run if - any file inside the crate root changes, but this can be used to scope changes - to just a small set of files. (If this path points to a directory the entire - directory will not be traversed for changes -- only changes to the timestamp - of the directory itself (which corresponds to some types of changes within the - directory, depending on platform) will trigger a rebuild. To request a re-run - on any changes within an entire directory, print a line for the directory and - another line for everything inside it, recursively.) - Note that if the build script itself (or one of its dependencies) changes, - then it's rebuilt and rerun unconditionally, so - `cargo:rerun-if-changed=build.rs` is almost always redundant (unless you - want to ignore changes in all other files except for `build.rs`). -* `rerun-if-env-changed=VAR` is the name of an environment variable which - indicates that if the environment variable's value changes the build script - should be rerun. This basically behaves the same as `rerun-if-changed` except - that it works with environment variables instead. Note that the environment - variables here are intended for global environment variables like `CC` and - such, it's not necessary to use this for env vars like `TARGET` that Cargo - sets. Also note that if `rerun-if-env-changed` is printed out then Cargo will - *only* rerun the build script if those environment variables change or if - files printed out by `rerun-if-changed` change. - -* `warning=MESSAGE` is a message that will be printed to the main console after - a build script has finished running. Warnings are only shown for path - dependencies (that is, those you're working on locally), so for example - warnings printed out in crates.io crates are not emitted by default. - -Any other element is a user-defined metadata that will be passed to -dependents. More information about this can be found in the [`links`][links] -section. - -[links]: #the-links-manifest-key - -### Build Dependencies - -Build scripts are also allowed to have dependencies on other Cargo-based crates. -Dependencies are declared through the `build-dependencies` section of the -manifest. - -```toml -[build-dependencies] -foo = { git = "https://github.com/your-packages/foo" } -``` - -The build script **does not** have access to the dependencies listed in the -`dependencies` or `dev-dependencies` section (they’re not built yet!). All build -dependencies will also not be available to the package itself unless explicitly -stated as so. - -### The `links` Manifest Key - -In addition to the manifest key `build`, Cargo also supports a `links` manifest -key to declare the name of a native library that is being linked to: - -```toml -[package] -# ... -links = "foo" -build = "build.rs" -``` - -This manifest states that the package links to the `libfoo` native library, and -it also has a build script for locating and/or building the library. Cargo -requires that a `build` command is specified if a `links` entry is also -specified. - -The purpose of this manifest key is to give Cargo an understanding about the set -of native dependencies that a package has, as well as providing a principled -system of passing metadata between package build scripts. - -Primarily, Cargo requires that there is at most one package per `links` value. -In other words, it’s forbidden to have two packages link to the same native -library. Note, however, that there are [conventions in place][star-sys] to -alleviate this. - -[star-sys]: #-sys-packages - -As mentioned above in the output format, each build script can generate an -arbitrary set of metadata in the form of key-value pairs. This metadata is -passed to the build scripts of **dependent** packages. For example, if `libbar` -depends on `libfoo`, then if `libfoo` generates `key=value` as part of its -metadata, then the build script of `libbar` will have the environment variables -`DEP_FOO_KEY=value`. - -Note that metadata is only passed to immediate dependents, not transitive -dependents. The motivation for this metadata passing is outlined in the linking -to system libraries case study below. - -### Overriding Build Scripts - -If a manifest contains a `links` key, then Cargo supports overriding the build -script specified with a custom library. The purpose of this functionality is to -prevent running the build script in question altogether and instead supply the -metadata ahead of time. - -To override a build script, place the following configuration in any acceptable -Cargo [configuration location](reference/config.html). - -```toml -[target.x86_64-unknown-linux-gnu.foo] -rustc-link-search = ["/path/to/foo"] -rustc-link-lib = ["foo"] -root = "/path/to/foo" -key = "value" -``` - -This section states that for the target `x86_64-unknown-linux-gnu` the library -named `foo` has the metadata specified. This metadata is the same as the -metadata generated as if the build script had run, providing a number of -key/value pairs where the `rustc-flags`, `rustc-link-search`, and -`rustc-link-lib` keys are slightly special. - -With this configuration, if a package declares that it links to `foo` then the -build script will **not** be compiled or run, and the metadata specified will -instead be used. - -### Case study: Code generation - -Some Cargo packages need to have code generated just before they are compiled -for various reasons. Here we’ll walk through a simple example which generates a -library call as part of the build script. - -First, let’s take a look at the directory structure of this package: - -```shell -. -├── Cargo.toml -├── build.rs -└── src - └── main.rs - -1 directory, 3 files -``` - -Here we can see that we have a `build.rs` build script and our binary in -`main.rs`. Next, let’s take a look at the manifest: - -```toml -# Cargo.toml - -[package] -name = "hello-from-generated-code" -version = "0.1.0" -authors = ["you@example.com"] -build = "build.rs" -``` - -Here we can see we’ve got a build script specified which we’ll use to generate -some code. Let’s see what’s inside the build script: - -```rust,no_run -// build.rs - -use std::env; -use std::fs::File; -use std::io::Write; -use std::path::Path; - -fn main() { - let out_dir = env::var("OUT_DIR").unwrap(); - let dest_path = Path::new(&out_dir).join("hello.rs"); - let mut f = File::create(&dest_path).unwrap(); - - f.write_all(b" - pub fn message() -> &'static str { - \"Hello, World!\" - } - ").unwrap(); -} -``` - -There’s a couple of points of note here: - -* The script uses the `OUT_DIR` environment variable to discover where the - output files should be located. It can use the process’ current working - directory to find where the input files should be located, but in this case we - don’t have any input files. -* This script is relatively simple as it just writes out a small generated file. - One could imagine that other more fanciful operations could take place such as - generating a Rust module from a C header file or another language definition, - for example. - -Next, let’s peek at the library itself: - -```rust,ignore -// src/main.rs - -include!(concat!(env!("OUT_DIR"), "/hello.rs")); - -fn main() { - println!("{}", message()); -} -``` - -This is where the real magic happens. The library is using the rustc-defined -`include!` macro in combination with the `concat!` and `env!` macros to include -the generated file (`hello.rs`) into the crate’s compilation. - -Using the structure shown here, crates can include any number of generated files -from the build script itself. - -### Case study: Building some native code - -Sometimes it’s necessary to build some native C or C++ code as part of a -package. This is another excellent use case of leveraging the build script to -build a native library before the Rust crate itself. As an example, we’ll create -a Rust library which calls into C to print “Hello, World!”. - -Like above, let’s first take a look at the project layout: - -```shell -. -├── Cargo.toml -├── build.rs -└── src - ├── hello.c - └── main.rs - -1 directory, 4 files -``` - -Pretty similar to before! Next, the manifest: - -```toml -# Cargo.toml - -[package] -name = "hello-world-from-c" -version = "0.1.0" -authors = ["you@example.com"] -build = "build.rs" -``` - -For now we’re not going to use any build dependencies, so let’s take a look at -the build script now: - -```rust,no_run -// build.rs - -use std::process::Command; -use std::env; -use std::path::Path; - -fn main() { - let out_dir = env::var("OUT_DIR").unwrap(); - - // note that there are a number of downsides to this approach, the comments - // below detail how to improve the portability of these commands. - Command::new("gcc").args(&["src/hello.c", "-c", "-fPIC", "-o"]) - .arg(&format!("{}/hello.o", out_dir)) - .status().unwrap(); - Command::new("ar").args(&["crus", "libhello.a", "hello.o"]) - .current_dir(&Path::new(&out_dir)) - .status().unwrap(); - - println!("cargo:rustc-link-search=native={}", out_dir); - println!("cargo:rustc-link-lib=static=hello"); -} -``` - -This build script starts out by compiling our C file into an object file (by -invoking `gcc`) and then converting this object file into a static library (by -invoking `ar`). The final step is feedback to Cargo itself to say that our -output was in `out_dir` and the compiler should link the crate to `libhello.a` -statically via the `-l static=hello` flag. - -Note that there are a number of drawbacks to this hardcoded approach: - -* The `gcc` command itself is not portable across platforms. For example it’s - unlikely that Windows platforms have `gcc`, and not even all Unix platforms - may have `gcc`. The `ar` command is also in a similar situation. -* These commands do not take cross-compilation into account. If we’re cross - compiling for a platform such as Android it’s unlikely that `gcc` will produce - an ARM executable. - -Not to fear, though, this is where a `build-dependencies` entry would help! The -Cargo ecosystem has a number of packages to make this sort of task much easier, -portable, and standardized. For example, the build script could be written as: - -```rust,ignore -// build.rs - -// Bring in a dependency on an externally maintained `gcc` package which manages -// invoking the C compiler. -extern crate gcc; - -fn main() { - gcc::compile_library("libhello.a", &["src/hello.c"]); -} -``` - -Add a build time dependency on the `gcc` crate with the following addition to -your `Cargo.toml`: - -```toml -[build-dependencies] -gcc = "0.3" -``` - -The [`gcc` crate](https://crates.io/crates/gcc) abstracts a range of build -script requirements for C code: - -* It invokes the appropriate compiler (MSVC for windows, `gcc` for MinGW, `cc` - for Unix platforms, etc.). -* It takes the `TARGET` variable into account by passing appropriate flags to - the compiler being used. -* Other environment variables, such as `OPT_LEVEL`, `DEBUG`, etc., are all - handled automatically. -* The stdout output and `OUT_DIR` locations are also handled by the `gcc` - library. - -Here we can start to see some of the major benefits of farming as much -functionality as possible out to common build dependencies rather than -duplicating logic across all build scripts! - -Back to the case study though, let’s take a quick look at the contents of the -`src` directory: - -```c -// src/hello.c - -#include - -void hello() { - printf("Hello, World!\n"); -} -``` - -```rust,ignore -// src/main.rs - -// Note the lack of the `#[link]` attribute. We’re delegating the responsibility -// of selecting what to link to over to the build script rather than hardcoding -// it in the source file. -extern { fn hello(); } - -fn main() { - unsafe { hello(); } -} -``` - -And there we go! This should complete our example of building some C code from a -Cargo package using the build script itself. This also shows why using a build -dependency can be crucial in many situations and even much more concise! - -We’ve also seen a brief example of how a build script can use a crate as a -dependency purely for the build process and not for the crate itself at runtime. - -### Case study: Linking to system libraries - -The final case study here will be investigating how a Cargo library links to a -system library and how the build script is leveraged to support this use case. - -Quite frequently a Rust crate wants to link to a native library often provided -on the system to bind its functionality or just use it as part of an -implementation detail. This is quite a nuanced problem when it comes to -performing this in a platform-agnostic fashion, and the purpose of a build -script is again to farm out as much of this as possible to make this as easy as -possible for consumers. - -As an example to follow, let’s take a look at one of [Cargo’s own -dependencies][git2-rs], [libgit2][libgit2]. The C library has a number of -constraints: - -[git2-rs]: https://github.com/alexcrichton/git2-rs/tree/master/libgit2-sys -[libgit2]: https://github.com/libgit2/libgit2 - -* It has an optional dependency on OpenSSL on Unix to implement the https - transport. -* It has an optional dependency on libssh2 on all platforms to implement the ssh - transport. -* It is often not installed on all systems by default. -* It can be built from source using `cmake`. - -To visualize what’s going on here, let’s take a look at the manifest for the -relevant Cargo package that links to the native C library. - -```toml -[package] -name = "libgit2-sys" -version = "0.1.0" -authors = ["..."] -links = "git2" -build = "build.rs" - -[dependencies] -libssh2-sys = { git = "https://github.com/alexcrichton/ssh2-rs" } - -[target.'cfg(unix)'.dependencies] -openssl-sys = { git = "https://github.com/alexcrichton/openssl-sys" } - -# ... -``` - -As the above manifests show, we’ve got a `build` script specified, but it’s -worth noting that this example has a `links` entry which indicates that the -crate (`libgit2-sys`) links to the `git2` native library. - -Here we also see that we chose to have the Rust crate have an unconditional -dependency on `libssh2` via the `libssh2-sys` crate, as well as a -platform-specific dependency on `openssl-sys` for \*nix (other variants elided -for now). It may seem a little counterintuitive to express *C dependencies* in -the *Cargo manifest*, but this is actually using one of Cargo’s conventions in -this space. - -### `*-sys` Packages - -To alleviate linking to system libraries, Cargo has a *convention* of package -naming and functionality. Any package named `foo-sys` will provide two major -pieces of functionality: - -* The library crate will link to the native library `libfoo`. This will often - probe the current system for `libfoo` before resorting to building from - source. -* The library crate will provide **declarations** for functions in `libfoo`, - but it does **not** provide bindings or higher-level abstractions. - -The set of `*-sys` packages provides a common set of dependencies for linking -to native libraries. There are a number of benefits earned from having this -convention of native-library-related packages: - -* Common dependencies on `foo-sys` alleviates the above rule about one package - per value of `links`. -* A common dependency allows centralizing logic on discovering `libfoo` itself - (or building it from source). -* These dependencies are easily overridable. - -### Building libgit2 - -Now that we’ve got libgit2’s dependencies sorted out, we need to actually write -the build script. We’re not going to look at specific snippets of code here and -instead only take a look at the high-level details of the build script of -`libgit2-sys`. This is not recommending all packages follow this strategy, but -rather just outlining one specific strategy. - -The first step of the build script should do is to query whether libgit2 is -already installed on the host system. To do this we’ll leverage the preexisting -tool `pkg-config` (when its available). We’ll also use a `build-dependencies` -section to refactor out all the `pkg-config` related code (or someone’s already -done that!). - -If `pkg-config` failed to find libgit2, or if `pkg-config` just wasn’t -installed, the next step is to build libgit2 from bundled source code -(distributed as part of `libgit2-sys` itself). There are a few nuances when -doing so that we need to take into account, however: - -* The build system of libgit2, `cmake`, needs to be able to find libgit2’s - optional dependency of libssh2. We’re sure we’ve already built it (it’s a - Cargo dependency), we just need to communicate this information. To do this - we leverage the metadata format to communicate information between build - scripts. In this example the libssh2 package printed out `cargo:root=...` to - tell us where libssh2 is installed at, and we can then pass this along to - cmake with the `CMAKE_PREFIX_PATH` environment variable. - -* We’ll need to handle some `CFLAGS` values when compiling C code (and tell - `cmake` about this). Some flags we may want to pass are `-m64` for 64-bit - code, `-m32` for 32-bit code, or `-fPIC` for 64-bit code as well. - -* Finally, we’ll invoke `cmake` to place all output into the `OUT_DIR` - environment variable, and then we’ll print the necessary metadata to instruct - rustc how to link to libgit2. - -Most of the functionality of this build script is easily refactorable into -common dependencies, so our build script isn’t quite as intimidating as this -descriptions! In reality it’s expected that build scripts are quite succinct by -farming logic such as above to build dependencies. diff -Nru cargo-0.25.0/src/doc/book/src/reference/config.md cargo-0.26.0/src/doc/book/src/reference/config.md --- cargo-0.25.0/src/doc/book/src/reference/config.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/reference/config.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,139 +0,0 @@ -## Configuration - -This document will explain how Cargo’s configuration system works, as well as -available keys or configuration. For configuration of a project through its -manifest, see the [manifest format](reference/manifest.html). - -### Hierarchical structure - - -Cargo allows local configuration for a particular project as well as global -configuration, like git. Cargo extends this to a hierarchical strategy. -If, for example, Cargo were invoked in `/projects/foo/bar/baz`, then the -following configuration files would be probed for and unified in this order: - -* `/projects/foo/bar/baz/.cargo/config` -* `/projects/foo/bar/.cargo/config` -* `/projects/foo/.cargo/config` -* `/projects/.cargo/config` -* `/.cargo/config` -* `$HOME/.cargo/config` - -With this structure, you can specify configuration per-project, and even -possibly check it into version control. You can also specify personal defaults -with a configuration file in your home directory. - -### Configuration format - -All configuration is currently in the [TOML format][toml] (like the manifest), -with simple key-value pairs inside of sections (tables) which all get merged -together. - -[toml]: https://github.com/toml-lang/toml - -### Configuration keys - -All of the following keys are optional, and their defaults are listed as their -value unless otherwise noted. - -Key values that specify a tool may be given as an absolute path, a relative path -or as a pathless tool name. Absolute paths and pathless tool names are used as -given. Relative paths are resolved relative to the parent directory of the -`.cargo` directory of the config file that the value resides within. - -```toml -# An array of paths to local repositories which are to be used as overrides for -# dependencies. For more information see the Specifying Dependencies guide. -paths = ["/path/to/override"] - -[cargo-new] -# This is your name/email to place in the `authors` section of a new Cargo.toml -# that is generated. If not present, then `git` will be probed, and if that is -# not present then `$USER` and `$EMAIL` will be used. -name = "..." -email = "..." - -# By default `cargo new` will initialize a new Git repository. This key can be -# set to `hg` to create a Mercurial repository, or `none` to disable this -# behavior. -vcs = "none" - -# For the following sections, $triple refers to any valid target triple, not the -# literal string "$triple", and it will apply whenever that target triple is -# being compiled to. 'cfg(...)' refers to the Rust-like `#[cfg]` syntax for -# conditional compilation. -[target.$triple] -# This is the linker which is passed to rustc (via `-C linker=`) when the `$triple` -# is being compiled for. By default this flag is not passed to the compiler. -linker = ".." -# Same but for the library archiver which is passed to rustc via `-C ar=`. -ar = ".." -# If a runner is provided, compiled targets for the `$triple` will be executed -# by invoking the specified runner executable with actual target as first argument. -# This applies to `cargo run`, `cargo test` and `cargo bench` commands. -# By default compiled targets are executed directly. -runner = ".." -# custom flags to pass to all compiler invocations that target $triple -# this value overrides build.rustflags when both are present -rustflags = ["..", ".."] - -[target.'cfg(...)'] -# Similar for the $triple configuration, but using the `cfg` syntax. -# If several `cfg` and $triple targets are candidates, then the rustflags -# are concatenated. The `cfg` syntax only applies to rustflags, and not to -# linker. -rustflags = ["..", ".."] - -# Configuration keys related to the registry -[registry] -index = "..." # URL of the registry index (defaults to the central repository) -token = "..." # Access token (found on the central repo’s website) - -[http] -proxy = "host:port" # HTTP proxy to use for HTTP requests (defaults to none) - # in libcurl format, e.g. "socks5h://host:port" -timeout = 60000 # Timeout for each HTTP request, in milliseconds -cainfo = "cert.pem" # Path to Certificate Authority (CA) bundle (optional) -check-revoke = true # Indicates whether SSL certs are checked for revocation - -[build] -jobs = 1 # number of parallel jobs, defaults to # of CPUs -rustc = "rustc" # the rust compiler tool -rustdoc = "rustdoc" # the doc generator tool -target = "triple" # build for the target triple -target-dir = "target" # path of where to place all generated artifacts -rustflags = ["..", ".."] # custom flags to pass to all compiler invocations - -[term] -verbose = false # whether cargo provides verbose output -color = 'auto' # whether cargo colorizes output - -# Network configuration -[net] -retry = 2 # number of times a network call will automatically retried - -# Alias cargo commands. The first 3 aliases are built in. If your -# command requires grouped whitespace use the list format. -[alias] -b = "build" -t = "test" -r = "run" -rr = "run --release" -space_example = ["run", "--release", "--", "\"command list\""] -``` - -### Environment variables - -Cargo can also be configured through environment variables in addition to the -TOML syntax above. For each configuration key above of the form `foo.bar` the -environment variable `CARGO_FOO_BAR` can also be used to define the value. For -example the `build.jobs` key can also be defined by `CARGO_BUILD_JOBS`. - -Environment variables will take precedent over TOML configuration, and currently -only integer, boolean, and string keys are supported to be defined by -environment variables. - -In addition to the system above, Cargo recognizes a few other specific -[environment variables][env]. - -[env]: reference/environment-variables.html diff -Nru cargo-0.25.0/src/doc/book/src/reference/environment-variables.md cargo-0.26.0/src/doc/book/src/reference/environment-variables.md --- cargo-0.25.0/src/doc/book/src/reference/environment-variables.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/reference/environment-variables.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,131 +0,0 @@ -## Environment Variables - -Cargo sets and reads a number of environment variables which your code can detect -or override. Here is a list of the variables Cargo sets, organized by when it interacts -with them: - -### Environment variables Cargo reads - -You can override these environment variables to change Cargo's behavior on your -system: - -* `CARGO_HOME` - Cargo maintains a local cache of the registry index and of git - checkouts of crates. By default these are stored under `$HOME/.cargo`, but - this variable overrides the location of this directory. Once a crate is cached - it is not removed by the clean command. -* `CARGO_TARGET_DIR` - Location of where to place all generated artifacts, - relative to the current working directory. -* `RUSTC` - Instead of running `rustc`, Cargo will execute this specified - compiler instead. -* `RUSTC_WRAPPER` - Instead of simply running `rustc`, Cargo will execute this - specified wrapper instead, passing as its commandline arguments the rustc - invocation, with the first argument being rustc. -* `RUSTDOC` - Instead of running `rustdoc`, Cargo will execute this specified - `rustdoc` instance instead. -* `RUSTDOCFLAGS` - A space-separated list of custom flags to pass to all `rustdoc` - invocations that Cargo performs. In contrast with `cargo rustdoc`, this is - useful for passing a flag to *all* `rustdoc` instances. -* `RUSTFLAGS` - A space-separated list of custom flags to pass to all compiler - invocations that Cargo performs. In contrast with `cargo rustc`, this is - useful for passing a flag to *all* compiler instances. - -Note that Cargo will also read environment variables for `.cargo/config` -configuration values, as described in [that documentation][config-env] - -[config-env]: reference/config.html#environment-variables - -### Environment variables Cargo sets for crates - -Cargo exposes these environment variables to your crate when it is compiled. -Note that this applies for test binaries as well. -To get the value of any of these variables in a Rust program, do this: - -```rust -let version = env!("CARGO_PKG_VERSION"); -``` - -`version` will now contain the value of `CARGO_PKG_VERSION`. - -* `CARGO` - Path to the `cargo` binary performing the build. -* `CARGO_MANIFEST_DIR` - The directory containing the manifest of your package. -* `CARGO_PKG_VERSION` - The full version of your package. -* `CARGO_PKG_VERSION_MAJOR` - The major version of your package. -* `CARGO_PKG_VERSION_MINOR` - The minor version of your package. -* `CARGO_PKG_VERSION_PATCH` - The patch version of your package. -* `CARGO_PKG_VERSION_PRE` - The pre-release version of your package. -* `CARGO_PKG_AUTHORS` - Colon separated list of authors from the manifest of your package. -* `CARGO_PKG_NAME` - The name of your package. -* `CARGO_PKG_DESCRIPTION` - The description of your package. -* `CARGO_PKG_HOMEPAGE` - The home page of your package. -* `OUT_DIR` - If the package has a build script, this is set to the folder where the build - script should place its output. See below for more information. - -### Environment variables Cargo sets for build scripts - -Cargo sets several environment variables when build scripts are run. Because these variables -are not yet set when the build script is compiled, the above example using `env!` won't work -and instead you'll need to retrieve the values when the build script is run: - -```rust -use std::env; -let out_dir = env::var("OUT_DIR").unwrap(); -``` - -`out_dir` will now contain the value of `OUT_DIR`. - -* `CARGO` - Path to the `cargo` binary performing the build. -* `CARGO_MANIFEST_DIR` - The directory containing the manifest for the package - being built (the package containing the build - script). Also note that this is the value of the - current working directory of the build script when it - starts. -* `CARGO_MANIFEST_LINKS` - the manifest `links` value. -* `CARGO_FEATURE_` - For each activated feature of the package being - built, this environment variable will be present - where `` is the name of the feature uppercased - and having `-` translated to `_`. -* `CARGO_CFG_` - For each [configuration option][configuration] of the - package being built, this environment variable will - contain the value of the configuration, where `` is - the name of the configuration uppercased and having `-` - translated to `_`. - Boolean configurations are present if they are set, and - not present otherwise. - Configurations with multiple values are joined to a - single variable with the values delimited by `,`. -* `OUT_DIR` - the folder in which all output should be placed. This folder is - inside the build directory for the package being built, and it is - unique for the package in question. -* `TARGET` - the target triple that is being compiled for. Native code should be - compiled for this triple. Some more information about target - triples can be found in [clang’s own documentation][clang]. -* `HOST` - the host triple of the rust compiler. -* `NUM_JOBS` - the parallelism specified as the top-level parallelism. This can - be useful to pass a `-j` parameter to a system like `make`. Note - that care should be taken when interpreting this environment - variable. For historical purposes this is still provided but - recent versions of Cargo, for example, do not need to run `make - -j` as it'll automatically happen. Cargo implements its own - [jobserver] and will allow build scripts to inherit this - information, so programs compatible with GNU make jobservers will - already have appropriately configured parallelism. -* `OPT_LEVEL`, `DEBUG` - values of the corresponding variables for the - profile currently being built. -* `PROFILE` - `release` for release builds, `debug` for other builds. -* `DEP__` - For more information about this set of environment - variables, see build script documentation about [`links`][links]. -* `RUSTC`, `RUSTDOC` - the compiler and documentation generator that Cargo has - resolved to use, passed to the build script so it might - use it as well. - -[links]: reference/build-scripts.html#the-links-manifest-key -[profile]: reference/manifest.html#the-profile-sections -[configuration]: https://doc.rust-lang.org/reference/attributes.html#conditional-compilation -[clang]:http://clang.llvm.org/docs/CrossCompilation.html#target-triple - -### Environment variables Cargo sets for 3rd party subcommands - -Cargo exposes this environment variable to 3rd party subcommands -(ie. programs named `cargo-foobar` placed in `$PATH`): - -* `CARGO` - Path to the `cargo` binary performing the build. diff -Nru cargo-0.25.0/src/doc/book/src/reference/external-tools.md cargo-0.26.0/src/doc/book/src/reference/external-tools.md --- cargo-0.25.0/src/doc/book/src/reference/external-tools.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/reference/external-tools.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -## External tools - -One of the goals of Cargo is simple integration with third-party tools, like -IDEs and other build systems. To make integration easier, Cargo has several -facilities: - -* a `cargo metadata` command, which outputs project structure and dependencies - information in JSON, - -* a `--message-format` flag, which outputs information about a particular build, - and - -* support for custom subcommands. - - -### Information about project structure - -You can use `cargo metadata` command to get information about project structure -and dependencies. The output of the command looks like this: - -```text -{ - // Integer version number of the format. - "version": integer, - - // List of packages for this workspace, including dependencies. - "packages": [ - { - // Opaque package identifier. - "id": PackageId, - - "name": string, - - "version": string, - - "source": SourceId, - - // A list of declared dependencies, see `resolve` field for actual dependencies. - "dependencies": [ Dependency ], - - "targets: [ Target ], - - // Path to Cargo.toml - "manifest_path": string, - } - ], - - "workspace_members": [ PackageId ], - - // Dependencies graph. - "resolve": { - "nodes": [ - { - "id": PackageId, - "dependencies": [ PackageId ] - } - ] - } -} -``` - -The format is stable and versioned. When calling `cargo metadata`, you should -pass `--format-version` flag explicitly to avoid forward incompatibility -hazard. - -If you are using Rust, there is [cargo_metadata] crate. - -[cargo_metadata]: https://crates.io/crates/cargo_metadata - - -### Information about build - -When passing `--message-format=json`, Cargo will output the following -information during the build: - -* compiler errors and warnings, - -* produced artifacts, - -* results of the build scripts (for example, native dependencies). - -The output goes to stdout in the JSON object per line format. The `reason` field -distinguishes different kinds of messages. - -Information about dependencies in the Makefile-compatible format is stored in -the `.d` files alongside the artifacts. - - -### Custom subcommands - -Cargo is designed to be extensible with new subcommands without having to modify -Cargo itself. This is achieved by translating a cargo invocation of the form -cargo `(?[^ ]+)` into an invocation of an external tool -`cargo-${command}` that then needs to be present in one of the user's `$PATH` -directories. - -Custom subcommand may use `CARGO` environment variable to call back to -Cargo. Alternatively, it can link to `cargo` crate as a library, but this -approach has drawbacks: - -* Cargo as a library is unstable, API changes without deprecation, - -* versions of Cargo library and Cargo binary may be different. diff -Nru cargo-0.25.0/src/doc/book/src/reference/index.md cargo-0.26.0/src/doc/book/src/reference/index.md --- cargo-0.25.0/src/doc/book/src/reference/index.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/reference/index.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -## Cargo Reference - -Now that you have an overview of how to use Cargo and have created your first -crate, you may be interested in more details in the following areas. - -The reference covers the details of various areas of Cargo. - -* [Specifying Dependencies](reference/specifying-dependencies.html) -* [The Manifest Format](reference/manifest.html) -* [Configuration](reference/config.html) -* [Environment Variables](reference/environment-variables.html) -* [Build Scripts](reference/build-scripts.html) -* [Publishing on crates.io](reference/publishing.html) -* [Package ID Specifications](reference/pkgid-spec.html) -* [Source Replacement](reference/source-replacement.html) -* [External Tools](reference/external-tools.html) diff -Nru cargo-0.25.0/src/doc/book/src/reference/manifest.md cargo-0.26.0/src/doc/book/src/reference/manifest.md --- cargo-0.25.0/src/doc/book/src/reference/manifest.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/reference/manifest.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,763 +0,0 @@ -## The Manifest Format - -The `Cargo.toml` file for each package is called its *manifest*. Every manifest -file consists of one or more sections. - -### The `[package]` section - -The first section in a `Cargo.toml` is `[package]`. - -```toml -[package] -name = "hello_world" # the name of the package -version = "0.1.0" # the current version, obeying semver -authors = ["you@example.com"] -``` - -All three of these fields are mandatory. - -#### The `version` field - -Cargo bakes in the concept of [Semantic -Versioning](http://semver.org/), so make sure you follow some basic rules: - -* Before you reach 1.0.0, anything goes, but if you make breaking changes, - increment the minor version. In Rust, breaking changes include adding fields to - structs or variants to enums. -* After 1.0.0, only make breaking changes when you increment the major version. - Don’t break the build. -* After 1.0.0, don’t add any new public API (no new `pub` anything) in tiny - versions. Always increment the minor version if you add any new `pub` structs, - traits, fields, types, functions, methods or anything else. -* Use version numbers with three numeric parts such as 1.0.0 rather than 1.0. - -#### The `build` field (optional) - -This field specifies a file in the project root which is a [build script][1] for -building native code. More information can be found in the build script -[guide][1]. - -[1]: reference/build-scripts.html - -```toml -[package] -# ... -build = "build.rs" -``` - -#### The `documentation` field (optional) - -This field specifies a URL to a website hosting the crate's documentation. -If no URL is specified in the manifest file, [crates.io][cratesio] will -automatically link your crate to the corresponding [docs.rs][docsrs] page. - -Documentation links from specific hosts are blacklisted. Hosts are added -to the blacklist if they are known to not be hosting documentation and are -possibly of malicious intent e.g. ad tracking networks. URLs from the -following hosts are blacklisted: - -* rust-ci.org - -Documentation URLs from blacklisted hosts will not appear on crates.io, and -may be replaced by docs.rs links. - -[docsrs]: https://docs.rs/ -[cratesio]: https://crates.io/ - -#### The `exclude` and `include` fields (optional) - -You can explicitly specify to Cargo that a set of [globs][globs] should be -ignored or included for the purposes of packaging and rebuilding a package. The -globs specified in the `exclude` field identify a set of files that are not -included when a package is published as well as ignored for the purposes of -detecting when to rebuild a package, and the globs in `include` specify files -that are explicitly included. - -If a VCS is being used for a package, the `exclude` field will be seeded with -the VCS’ ignore settings (`.gitignore` for git for example). - -```toml -[package] -# ... -exclude = ["build/**/*.o", "doc/**/*.html"] -``` - -```toml -[package] -# ... -include = ["src/**/*", "Cargo.toml"] -``` - -The options are mutually exclusive: setting `include` will override an -`exclude`. Note that `include` must be an exhaustive list of files as otherwise -necessary source files may not be included. - -[globs]: http://doc.rust-lang.org/glob/glob/struct.Pattern.html - -#### Migrating to `gitignore`-like pattern matching - -The current interpretation of these configs is based on UNIX Globs, as -implemented in the [`glob` crate](https://crates.io/crates/glob). We want -Cargo's `include` and `exclude` configs to work as similar to `gitignore` as -possible. [The `gitignore` specification](https://git-scm.com/docs/gitignore) is -also based on Globs, but has a bunch of additional features that enable easier -pattern writing and more control. Therefore, we are migrating the interpretation -for the rules of these configs to use the [`ignore` -crate](https://crates.io/crates/ignore), and treat them each rule as a single -line in a `gitignore` file. See [the tracking -issue](https://github.com/rust-lang/cargo/issues/4268) for more details on the -migration. - -#### The `publish` field (optional) - -The `publish` field can be used to prevent a package from being published to a -package registry (like *crates.io*) by mistake. - -```toml -[package] -# ... -publish = false -``` - -#### The `workspace` field (optional) - -The `workspace` field can be used to configure the workspace that this package -will be a member of. If not specified this will be inferred as the first -Cargo.toml with `[workspace]` upwards in the filesystem. - -```toml -[package] -# ... -workspace = "path/to/workspace/root" -``` - -For more information, see the documentation for the workspace table below. - -#### Package metadata - -There are a number of optional metadata fields also accepted under the -`[package]` section: - -```toml -[package] -# ... - -# A short blurb about the package. This is not rendered in any format when -# uploaded to crates.io (aka this is not markdown). -description = "..." - -# These URLs point to more information about the package. These are -# intended to be webviews of the relevant data, not necessarily compatible -# with VCS tools and the like. -documentation = "..." -homepage = "..." -repository = "..." - -# This points to a file under the package root (relative to this `Cargo.toml`). -# The contents of this file are stored and indexed in the registry. -# crates.io will render this file and place the result on the crate's page. -readme = "..." - -# This is a list of up to five keywords that describe this crate. Keywords -# are searchable on crates.io, and you may choose any words that would -# help someone find this crate. -keywords = ["...", "..."] - -# This is a list of up to five categories where this crate would fit. -# Categories are a fixed list available at crates.io/category_slugs, and -# they must match exactly. -categories = ["...", "..."] - -# This is a string description of the license for this package. Currently -# crates.io will validate the license provided against a whitelist of known -# license identifiers from http://spdx.org/licenses/. Multiple licenses can be -# separated with a `/`. -license = "..." - -# If a project is using a nonstandard license, then this key may be specified in -# lieu of the above key and must point to a file relative to this manifest -# (similar to the readme key). -license-file = "..." - -# Optional specification of badges to be displayed on crates.io. -# -# - The badges pertaining to build status that are currently available are -# Appveyor, CircleCI, GitLab, and TravisCI. -# - Available badges pertaining to code test coverage are Codecov and -# Coveralls. -# - There are also maintenance-related badges basesed on isitmaintained.com -# which state the issue resolution time, percent of open issues, and future -# maintenance intentions. -# -# If a `repository` key is required, this refers to a repository in -# `user/repo` format. -[badges] - -# Appveyor: `repository` is required. `branch` is optional; default is `master` -# `service` is optional; valid values are `github` (default), `bitbucket`, and -# `gitlab`. -appveyor = { repository = "...", branch = "master", service = "github" } - -# Circle CI: `repository` is required. `branch` is optional; default is `master` -circle-ci = { repository = "...", branch = "master" } - -# GitLab: `repository` is required. `branch` is optional; default is `master` -gitlab = { repository = "...", branch = "master" } - -# Travis CI: `repository` in format "/" is required. -# `branch` is optional; default is `master` -travis-ci = { repository = "...", branch = "master" } - -# Codecov: `repository` is required. `branch` is optional; default is `master` -# `service` is optional; valid values are `github` (default), `bitbucket`, and -# `gitlab`. -codecov = { repository = "...", branch = "master", service = "github" } - -# Coveralls: `repository` is required. `branch` is optional; default is `master` -# `service` is optional; valid values are `github` (default) and `bitbucket`. -coveralls = { repository = "...", branch = "master", service = "github" } - -# Is it maintained resolution time: `repository` is required. -is-it-maintained-issue-resolution = { repository = "..." } - -# Is it maintained percentage of open issues: `repository` is required. -is-it-maintained-open-issues = { repository = "..." } - -# Maintenance: `status` is required Available options are `actively-developed`, -# `passively-maintained`, `as-is`, `none`, `experimental`, `looking-for-maintainer` -# and `deprecated`. -maintenance = { status = "..." } -``` - -The [crates.io](https://crates.io) registry will render the description, display -the license, link to the three URLs and categorize by the keywords. These keys -provide useful information to users of the registry and also influence the -search ranking of a crate. It is highly discouraged to omit everything in a -published crate. - -#### The `metadata` table (optional) - -Cargo by default will warn about unused keys in `Cargo.toml` to assist in -detecting typos and such. The `package.metadata` table, however, is completely -ignored by Cargo and will not be warned about. This section can be used for -tools which would like to store project configuration in `Cargo.toml`. For -example: - -```toml -[package] -name = "..." -# ... - -# Metadata used when generating an Android APK, for example. -[package.metadata.android] -package-name = "my-awesome-android-app" -assets = "path/to/static" -``` - -### Dependency sections - -See the [specifying dependencies page](reference/specifying-dependencies.html) for -information on the `[dependencies]`, `[dev-dependencies]`, -`[build-dependencies]`, and target-specific `[target.*.dependencies]` sections. - -### The `[profile.*]` sections - -Cargo supports custom configuration of how rustc is invoked through profiles at -the top level. Any manifest may declare a profile, but only the top level -project’s profiles are actually read. All dependencies’ profiles will be -overridden. This is done so the top-level project has control over how its -dependencies are compiled. - -There are five currently supported profile names, all of which have the same -configuration available to them. Listed below is the configuration available, -along with the defaults for each profile. - -```toml -# The development profile, used for `cargo build`. -[profile.dev] -opt-level = 0 # controls the `--opt-level` the compiler builds with. - # 0-1 is good for debugging. 2 is well-optimized. Max is 3. -debug = true # include debug information (debug symbols). Equivalent to - # `-C debuginfo=2` compiler flag. -rpath = false # controls whether compiler should set loader paths. - # If true, passes `-C rpath` flag to the compiler. -lto = false # Link Time Optimization usually reduces size of binaries - # and static libraries. Increases compilation time. - # If true, passes `-C lto` flag to the compiler. -debug-assertions = true # controls whether debug assertions are enabled - # (e.g. debug_assert!() and arithmetic overflow checks) -codegen-units = 1 # if > 1 enables parallel code generation which improves - # compile times, but prevents some optimizations. - # Passes `-C codegen-units`. Ignored when `lto = true`. -panic = 'unwind' # panic strategy (`-C panic=...`), can also be 'abort' - -# The release profile, used for `cargo build --release`. -[profile.release] -opt-level = 3 -debug = false -rpath = false -lto = false -debug-assertions = false -codegen-units = 1 -panic = 'unwind' - -# The testing profile, used for `cargo test`. -[profile.test] -opt-level = 0 -debug = 2 -rpath = false -lto = false -debug-assertions = true -codegen-units = 1 -panic = 'unwind' - -# The benchmarking profile, used for `cargo bench` and `cargo test --release`. -[profile.bench] -opt-level = 3 -debug = false -rpath = false -lto = false -debug-assertions = false -codegen-units = 1 -panic = 'unwind' - -# The documentation profile, used for `cargo doc`. -[profile.doc] -opt-level = 0 -debug = 2 -rpath = false -lto = false -debug-assertions = true -codegen-units = 1 -panic = 'unwind' -``` - -### The `[features]` section - -Cargo supports features to allow expression of: - -* conditional compilation options (usable through `cfg` attributes); -* optional dependencies, which enhance a package, but are not required; and -* clusters of optional dependencies, such as `postgres`, that would include the - `postgres` package, the `postgres-macros` package, and possibly other packages - (such as development-time mocking libraries, debugging tools, etc.). - -A feature of a package is either an optional dependency, or a set of other -features. The format for specifying features is: - -```toml -[package] -name = "awesome" - -[features] -# The default set of optional packages. Most people will want to use these -# packages, but they are strictly optional. Note that `session` is not a package -# but rather another feature listed in this manifest. -default = ["jquery", "uglifier", "session"] - -# A feature with no dependencies is used mainly for conditional compilation, -# like `#[cfg(feature = "go-faster")]`. -go-faster = [] - -# The `secure-password` feature depends on the bcrypt package. This aliasing -# will allow people to talk about the feature in a higher-level way and allow -# this package to add more requirements to the feature in the future. -secure-password = ["bcrypt"] - -# Features can be used to reexport features of other packages. The `session` -# feature of package `awesome` will ensure that the `session` feature of the -# package `cookie` is also enabled. -session = ["cookie/session"] - -[dependencies] -# These packages are mandatory and form the core of this package’s distribution. -cookie = "1.2.0" -oauth = "1.1.0" -route-recognizer = "=2.1.0" - -# A list of all of the optional dependencies, some of which are included in the -# above `features`. They can be opted into by apps. -jquery = { version = "1.0.2", optional = true } -uglifier = { version = "1.5.3", optional = true } -bcrypt = { version = "*", optional = true } -civet = { version = "*", optional = true } -``` - -To use the package `awesome`: - -```toml -[dependencies.awesome] -version = "1.3.5" -default-features = false # do not include the default features, and optionally - # cherry-pick individual features -features = ["secure-password", "civet"] -``` - -#### Rules - -The usage of features is subject to a few rules: - -* Feature names must not conflict with other package names in the manifest. This - is because they are opted into via `features = [...]`, which only has a single - namespace. -* With the exception of the `default` feature, all features are opt-in. To opt - out of the default feature, use `default-features = false` and cherry-pick - individual features. -* Feature groups are not allowed to cyclically depend on one another. -* Dev-dependencies cannot be optional. -* Features groups can only reference optional dependencies. -* When a feature is selected, Cargo will call `rustc` with `--cfg - feature="${feature_name}"`. If a feature group is included, it and all of its - individual features will be included. This can be tested in code via - `#[cfg(feature = "foo")]`. - -Note that it is explicitly allowed for features to not actually activate any -optional dependencies. This allows packages to internally enable/disable -features without requiring a new dependency. - -#### Usage in end products - -One major use-case for this feature is specifying optional features in -end-products. For example, the Servo project may want to include optional -features that people can enable or disable when they build it. - -In that case, Servo will describe features in its `Cargo.toml` and they can be -enabled using command-line flags: - -```shell -$ cargo build --release --features "shumway pdf" -``` - -Default features could be excluded using `--no-default-features`. - -#### Usage in packages - -In most cases, the concept of *optional dependency* in a library is best -expressed as a separate package that the top-level application depends on. - -However, high-level packages, like Iron or Piston, may want the ability to -curate a number of packages for easy installation. The current Cargo system -allows them to curate a number of mandatory dependencies into a single package -for easy installation. - -In some cases, packages may want to provide additional curation for optional -dependencies: - -* grouping a number of low-level optional dependencies together into a single - high-level feature; -* specifying packages that are recommended (or suggested) to be included by - users of the package; and -* including a feature (like `secure-password` in the motivating example) that - will only work if an optional dependency is available, and would be difficult - to implement as a separate package (for example, it may be overly difficult to - design an IO package to be completely decoupled from OpenSSL, with opt-in via - the inclusion of a separate package). - -In almost all cases, it is an antipattern to use these features outside of -high-level packages that are designed for curation. If a feature is optional, it -can almost certainly be expressed as a separate package. - -### The `[workspace]` section - -Projects can define a workspace which is a set of crates that will all share the -same `Cargo.lock` and output directory. The `[workspace]` table can be defined -as: - -```toml -[workspace] - -# Optional key, inferred if not present -members = ["path/to/member1", "path/to/member2", "path/to/member3/*"] - -# Optional key, empty if not present -exclude = ["path1", "path/to/dir2"] -``` - -Workspaces were added to Cargo as part of [RFC 1525] and have a number of -properties: - -* A workspace can contain multiple crates where one of them is the *root crate*. -* The *root crate*'s `Cargo.toml` contains the `[workspace]` table, but is not - required to have other configuration. -* Whenever any crate in the workspace is compiled, output is placed in the - *workspace root*. i.e. next to the *root crate*'s `Cargo.toml`. -* The lock file for all crates in the workspace resides in the *workspace root*. -* The `[patch]` and `[replace]` sections in `Cargo.toml` are only recognized - in the *root crate*'s manifest, and ignored in member crates' manifests. - -[RFC 1525]: https://github.com/rust-lang/rfcs/blob/master/text/1525-cargo-workspace.md - -The *root crate* of a workspace, indicated by the presence of `[workspace]` in -its manifest, is responsible for defining the entire workspace. All `path` -dependencies residing in the workspace directory become members. You can add -additional packages to the workspace by listing them in the `members` key. Note -that members of the workspaces listed explicitly will also have their path -dependencies included in the workspace. Sometimes a project may have a lot of -workspace members and it can be onerous to keep up to date. The path dependency -can also use [globs][globs] to match multiple paths. Finally, the `exclude` -key can be used to blacklist paths from being included in a workspace. This can -be useful if some path dependencies aren't desired to be in the workspace at -all. - -The `package.workspace` manifest key (described above) is used in member crates -to point at a workspace's root crate. If this key is omitted then it is inferred -to be the first crate whose manifest contains `[workspace]` upwards in the -filesystem. - -A crate may either specify `package.workspace` or specify `[workspace]`. That -is, a crate cannot both be a root crate in a workspace (contain `[workspace]`) -and also be a member crate of another workspace (contain `package.workspace`). - -Most of the time workspaces will not need to be dealt with as `cargo new` and -`cargo init` will handle workspace configuration automatically. - -#### Virtual Manifest - -In workspace manifests, if the `package` table is present, the workspace root -crate will be treated as a normal package, as well as a worksapce. If the -`package` table is not present in a worksapce manifest, it is called a *virtual -manifest*. - -When working with *virtual manifests*, package-related cargo commands, like -`cargo build`, won't be available anymore. But, most of such commands support -the `--all` option, will execute the command for all the non-virtual manifest in -the workspace. - -#TODO: move this to a more appropriate place -### The project layout - -If your project is an executable, name the main source file `src/main.rs`. If it -is a library, name the main source file `src/lib.rs`. - -Cargo will also treat any files located in `src/bin/*.rs` as executables. If your -executable consists of more than just one source file, you might also use a directory -inside `src/bin` containing a `main.rs` file which will be treated as an executable -with a name of the parent directory. -Do note, however, once you add a `[[bin]]` section ([see -below](#configuring-a-target)), Cargo will no longer automatically build files -located in `src/bin/*.rs`. Instead you must create a `[[bin]]` section for -each file you want to build. - -Your project can optionally contain folders named `examples`, `tests`, and -`benches`, which Cargo will treat as containing examples, -integration tests, and benchmarks respectively. - -```shell -▾ src/ # directory containing source files - lib.rs # the main entry point for libraries and packages - main.rs # the main entry point for projects producing executables - ▾ bin/ # (optional) directory containing additional executables - *.rs - ▾ */ # (optional) directories containing multi-file executables - main.rs -▾ examples/ # (optional) examples - *.rs -▾ tests/ # (optional) integration tests - *.rs -▾ benches/ # (optional) benchmarks - *.rs -``` - -To structure your code after you've created the files and folders for your -project, you should remember to use Rust's module system, which you can read -about in [the book](https://doc.rust-lang.org/book/crates-and-modules.html). - -### Examples - -Files located under `examples` are example uses of the functionality provided by -the library. When compiled, they are placed in the `target/examples` directory. - -They can compile either as executables (with a `main()` function) or libraries -and pull in the library by using `extern crate `. They are -compiled when you run your tests to protect them from bitrotting. - -You can run individual executable examples with the command `cargo run --example -`. - -Specify `crate-type` to make an example be compiled as a library: - -```toml -[[example]] -name = "foo" -crate-type = ["staticlib"] -``` - -You can build individual library examples with the command `cargo build ---example `. - -### Tests - -When you run `cargo test`, Cargo will: - -* compile and run your library’s unit tests, which are in the files reachable - from `lib.rs` (naturally, any sections marked with `#[cfg(test)]` will be - considered at this stage); -* compile and run your library’s documentation tests, which are embedded inside - of documentation blocks; -* compile and run your library’s [integration tests](#integration-tests); and -* compile your library’s examples. - -#### Integration tests - -Each file in `tests/*.rs` is an integration test. When you run `cargo test`, -Cargo will compile each of these files as a separate crate. The crate can link -to your library by using `extern crate `, like any other code that -depends on it. - -Cargo will not automatically compile files inside subdirectories of `tests`, but -an integration test can import modules from these directories as usual. For -example, if you want several integration tests to share some code, you can put -the shared code in `tests/common/mod.rs` and then put `mod common;` in each of -the test files. - -### Configuring a target - -All of the `[[bin]]`, `[lib]`, `[[bench]]`, `[[test]]`, and `[[example]]` -sections support similar configuration for specifying how a target should be -built. The double-bracket sections like `[[bin]]` are array-of-table of -[TOML](https://github.com/toml-lang/toml#array-of-tables), which means you can -write more than one `[[bin]]` section to make several executables in your crate. - -The example below uses `[lib]`, but it also applies to all other sections -as well. All values listed are the defaults for that option unless otherwise -specified. - -```toml -[package] -# ... - -[lib] -# The name of a target is the name of the library that will be generated. This -# is defaulted to the name of the package or project, with any dashes replaced -# with underscores. (Rust `extern crate` declarations reference this name; -# therefore the value must be a valid Rust identifier to be usable.) -name = "foo" - -# This field points at where the crate is located, relative to the `Cargo.toml`. -path = "src/lib.rs" - -# A flag for enabling unit tests for this target. This is used by `cargo test`. -test = true - -# A flag for enabling documentation tests for this target. This is only relevant -# for libraries, it has no effect on other sections. This is used by -# `cargo test`. -doctest = true - -# A flag for enabling benchmarks for this target. This is used by `cargo bench`. -bench = true - -# A flag for enabling documentation of this target. This is used by `cargo doc`. -doc = true - -# If the target is meant to be a compiler plugin, this field must be set to true -# for Cargo to correctly compile it and make it available for all dependencies. -plugin = false - -# If the target is meant to be a "macros 1.1" procedural macro, this field must -# be set to true. -proc-macro = false - -# If set to false, `cargo test` will omit the `--test` flag to rustc, which -# stops it from generating a test harness. This is useful when the binary being -# built manages the test runner itself. -harness = true -``` - -#### The `required-features` field (optional) - -The `required-features` field specifies which features the target needs in order -to be built. If any of the required features are not selected, the target will -be skipped. This is only relevant for the `[[bin]]`, `[[bench]]`, `[[test]]`, -and `[[example]]` sections, it has no effect on `[lib]`. - -```toml -[features] -# ... -postgres = [] -sqlite = [] -tools = [] - -[[bin]] -# ... -required-features = ["postgres", "tools"] -``` - -#### Building dynamic or static libraries - -If your project produces a library, you can specify which kind of library to -build by explicitly listing the library in your `Cargo.toml`: - -```toml -# ... - -[lib] -name = "..." -crate-type = ["dylib"] # could be `staticlib` as well -``` - -The available options are `dylib`, `rlib`, `staticlib`, `cdylib`, and -`proc-macro`. You should only use this option in a project. Cargo will always -compile packages (dependencies) based on the requirements of the project that -includes them. - -You can read more about the different crate types in the -[Rust Reference Manual](https://doc.rust-lang.org/reference/linkage.html) - -### The `[patch]` Section - -This section of Cargo.toml can be used to [override dependencies][replace] with -other copies. The syntax is similar to the `[dependencies]` section: - -```toml -[patch.crates-io] -foo = { git = 'https://github.com/example/foo' } -bar = { path = 'my/local/bar' } -``` - -The `[patch]` table is made of dependency-like sub-tables. Each key after -`[patch]` is a URL of the source that's being patched, or `crates-io` if -you're modifying the https://crates.io registry. In the example above -`crates-io` could be replaced with a git URL such as -`https://github.com/rust-lang-nursery/log`. - -Each entry in these tables is a normal dependency specification, the same as -found in the `[dependencies]` section of the manifest. The dependencies listed -in the `[patch]` section are resolved and used to patch the source at the -URL specified. The above manifest snippet patches the `crates-io` source (e.g. -crates.io itself) with the `foo` crate and `bar` crate. - -Sources can be patched with versions of crates that do not exist, and they can -also be patched with versions of crates that already exist. If a source is -patched with a crate version that already exists in the source, then the -source's original crate is replaced. - -More information about overriding dependencies can be found in the [overriding -dependencies][replace] section of the documentation and [RFC 1969] for the -technical specification of this feature. (Note that the `[patch]` feature will -first become available in Rust 1.21, set to be released on 2017-10-12.) - -[RFC 1969]: https://github.com/rust-lang/rfcs/pull/1969 -[replace]: reference/specifying-dependencies.html#overriding-dependencies - -### The `[replace]` Section - -This section of Cargo.toml can be used to [override dependencies][replace] with -other copies. The syntax is similar to the `[dependencies]` section: - -```toml -[replace] -"foo:0.1.0" = { git = 'https://github.com/example/foo' } -"bar:1.0.2" = { path = 'my/local/bar' } -``` - -Each key in the `[replace]` table is a [package id -specification](reference/pkgid-spec.html) which allows arbitrarily choosing a node in the -dependency graph to override. The value of each key is the same as the -`[dependencies]` syntax for specifying dependencies, except that you can't -specify features. Note that when a crate is overridden the copy it's overridden -with must have both the same name and version, but it can come from a different -source (e.g. git or a local path). - -More information about overriding dependencies can be found in the [overriding -dependencies][replace] section of the documentation. diff -Nru cargo-0.25.0/src/doc/book/src/reference/pkgid-spec.md cargo-0.26.0/src/doc/book/src/reference/pkgid-spec.md --- cargo-0.25.0/src/doc/book/src/reference/pkgid-spec.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/reference/pkgid-spec.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -## Package ID Specifications - -### Package ID specifications - -Subcommands of Cargo frequently need to refer to a particular package within a -dependency graph for various operations like updating, cleaning, building, etc. -To solve this problem, Cargo supports Package ID Specifications. A specification -is a string which is used to uniquely refer to one package within a graph of -packages. - -#### Specification grammar - -The formal grammar for a Package Id Specification is: - -```notrust -pkgid := pkgname - | [ proto "://" ] hostname-and-path [ "#" ( pkgname | semver ) ] -pkgname := name [ ":" semver ] - -proto := "http" | "git" | ... -``` - -Here, brackets indicate that the contents are optional. - -#### Example specifications - -These could all be references to a package `foo` version `1.2.3` from the -registry at `crates.io` - -| pkgid | name | version | url | -|:-----------------------------|:-----:|:-------:|:----------------------:| -| `foo` | `foo` | `*` | `*` | -| `foo:1.2.3` | `foo` | `1.2.3` | `*` | -| `crates.io/foo` | `foo` | `*` | `*://crates.io/foo` | -| `crates.io/foo#1.2.3` | `foo` | `1.2.3` | `*://crates.io/foo` | -| `crates.io/bar#foo:1.2.3` | `foo` | `1.2.3` | `*://crates.io/bar` | -| `http://crates.io/foo#1.2.3` | `foo` | `1.2.3` | `http://crates.io/foo` | - -#### Brevity of specifications - -The goal of this is to enable both succinct and exhaustive syntaxes for -referring to packages in a dependency graph. Ambiguous references may refer to -one or more packages. Most commands generate an error if more than one package -could be referred to with the same specification. diff -Nru cargo-0.25.0/src/doc/book/src/reference/publishing.md cargo-0.26.0/src/doc/book/src/reference/publishing.md --- cargo-0.25.0/src/doc/book/src/reference/publishing.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/reference/publishing.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,222 +0,0 @@ -## Publishing on crates.io - -Once you've got a library that you'd like to share with the world, it's time to -publish it on [crates.io]! Publishing a crate is when a specific -version is uploaded to be hosted on [crates.io]. - -Take care when publishing a crate, because a publish is **permanent**. The -version can never be overwritten, and the code cannot be deleted. There is no -limit to the number of versions which can be published, however. - -### Before your first publish - -First thing’s first, you’ll need an account on [crates.io] to acquire -an API token. To do so, [visit the home page][crates.io] and log in via a GitHub -account (required for now). After this, visit your [Account -Settings](https://crates.io/me) page and run the `cargo login` command -specified. - -```shell -$ cargo login abcdefghijklmnopqrstuvwxyz012345 -``` - -This command will inform Cargo of your API token and store it locally in your -`~/.cargo/credentials` (previously it was `~/.cargo/config`). Note that this -token is a **secret** and should not be shared with anyone else. If it leaks for -any reason, you should regenerate it immediately. - -### Before publishing a new crate - -Keep in mind that crate names on [crates.io] are allocated on a first-come-first- -serve basis. Once a crate name is taken, it cannot be used for another crate. - -#### Packaging a crate - -The next step is to package up your crate into a format that can be uploaded to -[crates.io]. For this we’ll use the `cargo package` subcommand. This will take -our entire crate and package it all up into a `*.crate` file in the -`target/package` directory. - -```shell -$ cargo package -``` - -As an added bonus, the `*.crate` will be verified independently of the current -source tree. After the `*.crate` is created, it’s unpacked into -`target/package` and then built from scratch to ensure that all necessary files -are there for the build to succeed. This behavior can be disabled with the -`--no-verify` flag. - -Now’s a good time to take a look at the `*.crate` file to make sure you didn’t -accidentally package up that 2GB video asset, or large data files used for code -generation, integration tests, or benchmarking. There is currently a 10MB -upload size limit on `*.crate` files. So, if the size of `tests` and `benches` -directories and their dependencies are up to a couple of MBs, you can keep them -in your package; otherwsie, better to exclude them. - -Cargo will automatically ignore files ignored by your version control system -when packaging, but if you want to specify an extra set of files to ignore you -can use the `exclude` key in the manifest: - -```toml -[package] -# ... -exclude = [ - "public/assets/*", - "videos/*", -] -``` - -The syntax of each element in this array is what -[rust-lang/glob](https://github.com/rust-lang/glob) accepts. If you’d rather -roll with a whitelist instead of a blacklist, Cargo also supports an `include` -key, which if set, overrides the `exclude` key: - -```toml -[package] -# ... -include = [ - "**/*.rs", - "Cargo.toml", -] -``` - -### Uploading the crate - -Now that we’ve got a `*.crate` file ready to go, it can be uploaded to -[crates.io] with the `cargo publish` command. And that’s it, you’ve now published -your first crate! - -```shell -$ cargo publish -``` - -If you’d like to skip the `cargo package` step, the `cargo publish` subcommand -will automatically package up the local crate if a copy isn’t found already. - -Be sure to check out the [metadata you can -specify](reference/manifest.html#package-metadata) to ensure your crate can be -discovered more easily! - -### Publishing a new version of an existing crate - -In order to release a new version, change the `version` value specified in your -`Cargo.toml` manifest. Keep in mind [the semver -rules](reference/manifest.html#the-version-field). Then optionally run `cargo package` if -you want to inspect the `*.crate` file for the new version before publishing, -and run `cargo publish` to upload the new version. - -### Managing a crates.io-based crate - -Management of crates is primarily done through the command line `cargo` tool -rather than the [crates.io] web interface. For this, there are a few subcommands -to manage a crate. - -#### `cargo yank` - -Occasions may arise where you publish a version of a crate that actually ends up -being broken for one reason or another (syntax error, forgot to include a file, -etc.). For situations such as this, Cargo supports a “yank” of a version of a -crate. - -```shell -$ cargo yank --vers 1.0.1 -$ cargo yank --vers 1.0.1 --undo -``` - -A yank **does not** delete any code. This feature is not intended for deleting -accidentally uploaded secrets, for example. If that happens, you must reset -those secrets immediately. - -The semantics of a yanked version are that no new dependencies can be created -against that version, but all existing dependencies continue to work. One of the -major goals of [crates.io] is to act as a permanent archive of crates that does -not change over time, and allowing deletion of a version would go against this -goal. Essentially a yank means that all projects with a `Cargo.lock` will not -break, while any future `Cargo.lock` files generated will not list the yanked -version. - -#### `cargo owner` - -A crate is often developed by more than one person, or the primary maintainer -may change over time! The owner of a crate is the only person allowed to publish -new versions of the crate, but an owner may designate additional owners. - -```shell -$ cargo owner --add my-buddy -$ cargo owner --remove my-buddy -$ cargo owner --add github:rust-lang:owners -$ cargo owner --remove github:rust-lang:owners -``` - -The owner IDs given to these commands must be GitHub user names or GitHub teams. - -If a user name is given to `--add`, that user becomes a “named” owner, with -full rights to the crate. In addition to being able to publish or yank versions -of the crate, they have the ability to add or remove owners, *including* the -owner that made *them* an owner. Needless to say, you shouldn’t make people you -don’t fully trust into a named owner. In order to become a named owner, a user -must have logged into [crates.io] previously. - -If a team name is given to `--add`, that team becomes a “team” owner, with -restricted right to the crate. While they have permission to publish or yank -versions of the crate, they *do not* have the ability to add or remove owners. -In addition to being more convenient for managing groups of owners, teams are -just a bit more secure against owners becoming malicious. - -The syntax for teams is currently `github:org:team` (see examples above). -In order to add a team as an owner one must be a member of that team. No -such restriction applies to removing a team as an owner. - -### GitHub permissions - -Team membership is not something GitHub provides simple public access to, and it -is likely for you to encounter the following message when working with them: - -> It looks like you don’t have permission to query a necessary property from -GitHub to complete this request. You may need to re-authenticate on [crates.io] -to grant permission to read GitHub org memberships. Just go to -https://crates.io/login - -This is basically a catch-all for “you tried to query a team, and one of the -five levels of membership access control denied this”. That is not an -exaggeration. GitHub’s support for team access control is Enterprise Grade. - -The most likely cause of this is simply that you last logged in before this -feature was added. We originally requested *no* permissions from GitHub when -authenticating users, because we didn’t actually ever use the user’s token for -anything other than logging them in. However to query team membership on your -behalf, we now require -[the `read:org` scope](https://developer.github.com/v3/oauth/#scopes). - -You are free to deny us this scope, and everything that worked before teams -were introduced will keep working. However you will never be able to add a team -as an owner, or publish a crate as a team owner. If you ever attempt to do this, -you will get the error above. You may also see this error if you ever try to -publish a crate that you don’t own at all, but otherwise happens to have a team. - -If you ever change your mind, or just aren’t sure if [crates.io] has sufficient -permission, you can always go to https://crates.io/login, which will prompt you -for permission if [crates.io] doesn’t have all the scopes it would like to. - -An additional barrier to querying GitHub is that the organization may be -actively denying third party access. To check this, you can go to: - - https://github.com/organizations/:org/settings/oauth_application_policy - -where `:org` is the name of the organization (e.g. rust-lang). You may see -something like: - -![Organization Access Control](images/org-level-acl.png) - -Where you may choose to explicitly remove [crates.io] from your organization’s -blacklist, or simply press the “Remove Restrictions” button to allow all third -party applications to access this data. - -Alternatively, when [crates.io] requested the `read:org` scope, you could have -explicitly whitelisted [crates.io] querying the org in question by pressing -the “Grant Access” button next to its name: - -![Authentication Access Control](images/auth-level-acl.png) - -[crates.io]: https://crates.io/ diff -Nru cargo-0.25.0/src/doc/book/src/reference/source-replacement.md cargo-0.26.0/src/doc/book/src/reference/source-replacement.md --- cargo-0.25.0/src/doc/book/src/reference/source-replacement.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/reference/source-replacement.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,128 +0,0 @@ -## Source Replacement - -Cargo supports the ability to **replace one source with another** to express -strategies along the lines of mirrors or vendoring dependencies. Configuration -is currently done through the [`.cargo/config` configuration][config] mechanism, -like so: - -[config]: reference/config.html - -```toml -# The `source` table is where all keys related to source-replacement -# are stored. -[source] - -# Under the `source` table are a number of other tables whose keys are a -# name for the relevant source. For example this section defines a new -# source, called `my-awesome-source`, which comes from a directory -# located at `vendor` relative to the directory containing this `.cargo/config` -# file -[source.my-awesome-source] -directory = "vendor" - -# The crates.io default source for crates is available under the name -# "crates-io", and here we use the `replace-with` key to indicate that it's -# replaced with our source above. -[source.crates-io] -replace-with = "my-awesome-source" -``` - -With this configuration Cargo attempts to look up all crates in the directory -"vendor" rather than querying the online registry at crates.io. Using source -replacement Cargo can express: - -* Vendoring - custom sources can be defined which represent crates on the local - filesystem. These sources are subsets of the source that they're replacing and - can be checked into projects if necessary. - -* Mirroring - sources can be replaced with an equivalent version which acts as a - cache for crates.io itself. - -Cargo has a core assumption about source replacement that the source code is -exactly the same from both sources. In our above example Cargo assumes that all -of the crates coming from `my-awesome-source` are the exact same as the copies -from `crates-io`. Note that this also means that `my-awesome-source` is not -allowed to have crates which are not present in the `crates-io` source. - -As a consequence, source replacement is not appropriate for situations such as -patching a dependency or a private registry. Cargo supports patching -dependencies through the usage of [the `[replace]` key][replace-section], and -private registry support is planned for a future version of Cargo. - -[replace-section]: reference/manifest.html#the-replace-section - -### Configuration - -Configuration of replacement sources is done through [`.cargo/config`][config] -and the full set of available keys are: - -```toml -# Each source has its own table where the key is the name of the source -[source.the-source-name] - -# Indicate that `the-source-name` will be replaced with `another-source`, -# defined elsewhere -replace-with = "another-source" - -# Available kinds of sources that can be specified (described below) -registry = "https://example.com/path/to/index" -local-registry = "path/to/registry" -directory = "path/to/vendor" -``` - -The `crates-io` represents the crates.io online registry (default source of -crates) and can be replaced with: - -```toml -[source.crates-io] -replace-with = 'another-source' -``` - -### Registry Sources - -A "registry source" is one that is the same as crates.io itself. That is, it has -an index served in a git repository which matches the format of the -[crates.io index](https://github.com/rust-lang/crates.io-index). That repository -then has configuration indicating where to download crates from. - -Currently there is not an already-available project for setting up a mirror of -crates.io. Stay tuned though! - -### Local Registry Sources - -A "local registry source" is intended to be a subset of another registry -source, but available on the local filesystem (aka vendoring). Local registries -are downloaded ahead of time, typically sync'd with a `Cargo.lock`, and are -made up of a set of `*.crate` files and an index like the normal registry is. - -The primary way to manage and crate local registry sources is through the -[`cargo-local-registry`][cargo-local-registry] subcommand, available on -crates.io and can be installed with `cargo install cargo-local-registry`. - -[cargo-local-registry]: https://crates.io/crates/cargo-local-registry - -Local registries are contained within one directory and contain a number of -`*.crate` files downloaded from crates.io as well as an `index` directory with -the same format as the crates.io-index project (populated with just entries for -the crates that are present). - -### Directory Sources - -A "directory source" is similar to a local registry source where it contains a -number of crates available on the local filesystem, suitable for vendoring -dependencies. Also like local registries, directory sources can primarily be -managed by an external subcommand, [`cargo-vendor`][cargo-vendor], which can be -installed with `cargo install cargo-vendor`. - -[cargo-vendor]: https://crates.io/crates/cargo-vendor - -Directory sources are distinct from local registries though in that they contain -the unpacked version of `*.crate` files, making it more suitable in some -situations to check everything into source control. A directory source is just a -directory containing a number of other directories which contain the source code -for crates (the unpacked version of `*.crate` files). Currently no restriction -is placed on the name of each directory. - -Each crate in a directory source also has an associated metadata file indicating -the checksum of each file in the crate to protect against accidental -modifications. diff -Nru cargo-0.25.0/src/doc/book/src/reference/specifying-dependencies.md cargo-0.26.0/src/doc/book/src/reference/specifying-dependencies.md --- cargo-0.25.0/src/doc/book/src/reference/specifying-dependencies.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/reference/specifying-dependencies.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,524 +0,0 @@ -## Specifying Dependencies - -Your crates can depend on other libraries from [crates.io], `git` repositories, or -subdirectories on your local file system. You can also temporarily override the -location of a dependency— for example, to be able to test out a bug fix in the -dependency that you are working on locally. You can have different -dependencies for different platforms, and dependencies that are only used during -development. Let's take a look at how to do each of these. - -### Specifying dependencies from crates.io - -Cargo is configured to look for dependencies on [crates.io] by default. Only -the name and a version string are required in this case. In [the cargo -guide](guide/index.html), we specified a dependency on the `time` crate: - -```toml -[dependencies] -time = "0.1.12" -``` - -The string `"0.1.12"` is a [semver] version requirement. Since this -string does not have any operators in it, it is interpreted the same way as -if we had specified `"^0.1.12"`, which is called a caret requirement. - -[semver]: https://github.com/steveklabnik/semver#requirements - -### Caret requirements - -**Caret requirements** allow SemVer compatible updates to a specified version. -An update is allowed if the new version number does not modify the left-most -non-zero digit in the major, minor, patch grouping. In this case, if we ran -`cargo update -p time`, cargo would update us to version `0.1.13` if it was -available, but would not update us to `0.2.0`. If instead we had specified the -version string as `^1.0`, cargo would update to `1.1` but not `2.0`. The version -`0.0.x` is not considered compatible with any other version. - -Here are some more examples of caret requirements and the versions that would -be allowed with them: - -```notrust -^1.2.3 := >=1.2.3 <2.0.0 -^1.2 := >=1.2.0 <2.0.0 -^1 := >=1.0.0 <2.0.0 -^0.2.3 := >=0.2.3 <0.3.0 -^0.0.3 := >=0.0.3 <0.0.4 -^0.0 := >=0.0.0 <0.1.0 -^0 := >=0.0.0 <1.0.0 -``` - -This compatibility convention is different from SemVer in the way it treats -versions before 1.0.0. While SemVer says there is no compatibility before -1.0.0, Cargo considers `0.x.y` to be compatible with `0.x.z`, where `y ≥ z` -and `x > 0`. - -### Tilde requirements - -**Tilde requirements** specify a minimal version with some ability to update. -If you specify a major, minor, and patch version or only a major and minor -version, only patch-level changes are allowed. If you only specify a major -version, then minor- and patch-level changes are allowed. - -`~1.2.3` is an example of a tilde requirement. - -```notrust -~1.2.3 := >=1.2.3 <1.3.0 -~1.2 := >=1.2.0 <1.3.0 -~1 := >=1.0.0 <2.0.0 -``` - -### Wildcard requirements - -**Wildcard requirements** allow for any version where the wildcard is -positioned. - -`*`, `1.*` and `1.2.*` are examples of wildcard requirements. - -```notrust -* := >=0.0.0 -1.* := >=1.0.0 <2.0.0 -1.2.* := >=1.2.0 <1.3.0 -``` - -### Inequality requirements - -**Inequality requirements** allow manually specifying a version range or an -exact version to depend on. - -Here are some examples of inequality requirements: - -```notrust ->= 1.2.0 -> 1 -< 2 -= 1.2.3 -``` - -### Multiple requirements - -Multiple version requirements can also be separated with a comma, e.g. `>= 1.2, -< 1.5`. - -### Specifying dependencies from `git` repositories - -To depend on a library located in a `git` repository, the minimum information -you need to specify is the location of the repository with the `git` key: - -```toml -[dependencies] -rand = { git = "https://github.com/rust-lang-nursery/rand" } -``` - -Cargo will fetch the `git` repository at this location then look for a -`Cargo.toml` for the requested crate anywhere inside the `git` repository -(not necessarily at the root). - -Since we haven’t specified any other information, Cargo assumes that -we intend to use the latest commit on the `master` branch to build our project. -You can combine the `git` key with the `rev`, `tag`, or `branch` keys to -specify something else. Here's an example of specifying that you want to use -the latest commit on a branch named `next`: - -```toml -[dependencies] -rand = { git = "https://github.com/rust-lang-nursery/rand", branch = "next" } -``` - -### Specifying path dependencies - -Over time, our `hello_world` project from [the guide](guide/index.html) has -grown significantly in size! It’s gotten to the point that we probably want to -split out a separate crate for others to use. To do this Cargo supports **path -dependencies** which are typically sub-crates that live within one repository. -Let’s start off by making a new crate inside of our `hello_world` project: - -```shell -# inside of hello_world/ -$ cargo new hello_utils -``` - -This will create a new folder `hello_utils` inside of which a `Cargo.toml` and -`src` folder are ready to be configured. In order to tell Cargo about this, open -up `hello_world/Cargo.toml` and add `hello_utils` to your dependencies: - -```toml -[dependencies] -hello_utils = { path = "hello_utils" } -``` - -This tells Cargo that we depend on a crate called `hello_utils` which is found -in the `hello_utils` folder (relative to the `Cargo.toml` it’s written in). - -And that’s it! The next `cargo build` will automatically build `hello_utils` and -all of its own dependencies, and others can also start using the crate as well. -However, crates that use dependencies specified with only a path are not -permitted on [crates.io]. If we wanted to publish our `hello_world` crate, we -would need to publish a version of `hello_utils` to [crates.io](https://crates.io) -and specify its version in the dependencies line as well: - -```toml -[dependencies] -hello_utils = { path = "hello_utils", version = "0.1.0" } -``` - -### Overriding dependencies - -There are a number of methods in Cargo to support overriding dependencies and -otherwise controlling the dependency graph. These options are typically, though, -only available at the workspace level and aren't propagated through -dependencies. In other words, "applications" have the ability to override -dependencies but "libraries" do not. - -The desire to override a dependency or otherwise alter some dependencies can -arise through a number of scenarios. Most of them, however, boil down to the -ability to work with a crate before it's been published to crates.io. For -example: - -* A crate you're working on is also used in a much larger application you're - working on, and you'd like to test a bug fix to the library inside of the - larger application. -* An upstream crate you don't work on has a new feature or a bug fix on the - master branch of its git repository which you'd like to test out. -* You're about to publish a new major version of your crate, but you'd like to - do integration testing across an entire project to ensure the new major - version works. -* You've submitted a fix to an upstream crate for a bug you found, but you'd - like to immediately have your application start depending on the fixed version - of the crate to avoid blocking on the bug fix getting merged. - -These scenarios are currently all solved with the [`[patch]` manifest -section][patch-section]. Note that the `[patch]` feature is not yet currently -stable and will be released on 2017-08-31. Historically some of these scenarios -have been solved with [the `[replace]` section][replace-section], but we'll -document the `[patch]` section here. - -[patch-section]: reference/manifest.html#the-patch-section -[replace-section]: reference/manifest.html#the-replace-section - -### Testing a bugfix - -Let's say you're working with the [`uuid`] crate but while you're working on it -you discover a bug. You are, however, quite enterprising so you decide to also -try out to fix the bug! Originally your manifest will look like: - -[`uuid`](https://crates.io/crates/uuid) - -```toml -[package] -name = "my-library" -version = "0.1.0" -authors = ["..."] - -[dependencies] -uuid = "1.0" -``` - -First thing we'll do is to clone the [`uuid` repository][uuid-repository] -locally via: - -```shell -$ git clone https://github.com/rust-lang-nursery/uuid -``` - -Next we'll edit the manifest of `my-library` to contain: - -```toml -[patch.crates-io] -uuid = { path = "../path/to/uuid" } -``` - -Here we declare that we're *patching* the source `crates-io` with a new -dependency. This will effectively add the local checked out version of `uuid` to -the crates.io registry for our local project. - -Next up we need to ensure that our lock file is updated to use this new version -of `uuid` so our project uses the locally checked out copy instead of one from -crates.io. The way `[patch]` works is that it'll load the dependency at -`../path/to/uuid` and then whenever crates.io is queried for versions of `uuid` -it'll *also* return the local version. - -This means that the version number of the local checkout is significant and will -affect whether the patch is used. Our manifest declared `uuid = "1.0"` which -means we'll only resolve to `>= 1.0.0, < 2.0.0`, and Cargo's greedy resolution -algorithm also means that we'll resolve to the maximum version within that -range. Typically this doesn't matter as the version of the git repository will -already be greater or match the maximum version published on crates.io, but it's -important to keep this in mind! - -In any case, typically all you need to do now is: - -```shell -$ cargo build - Compiling uuid v1.0.0 (file://.../uuid) - Compiling my-library v0.1.0 (file://.../my-library) - Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs -``` - -And that's it! You're now building with the local version of `uuid` (note the -`file://` in the build output). If you don't see the `file://` version getting -built then you may need to run `cargo update -p uuid --precise $version` where -`$version` is the version of the locally checked out copy of `uuid`. - -Once you've fixed the bug you originally found the next thing you'll want to do -is to likely submit that as a pull request to the `uuid` crate itself. Once -you've done this then you can also update the `[patch]` section. The listing -inside of `[patch]` is just like the `[dependencies]` section, so once your pull -request is merged you could change your `path` dependency to: - -```toml -[patch.crates-io] -uuid = { git = 'https://github.com/rust-lang-nursery/uuid' } -``` - -[uuid-repository]: https://github.com/rust-lang-nursery/uuid - -### Working with an unpublished minor version - -Let's now shift gears a bit from bug fixes to adding features. While working on -`my-library` you discover that a whole new feature is needed in the `uuid` -crate. You've implemented this feature, tested it locally above with `[patch]`, -and submitted a pull request. Let's go over how you continue to use and test it -before it's actually published. - -Let's also say that the current version of `uuid` on crates.io is `1.0.0`, but -since then the master branch of the git repository has updated to `1.0.1`. This -branch includes your new feature you submitted previously. To use this -repository we'll edit our `Cargo.toml` to look like - -```toml -[package] -name = "my-library" -version = "0.1.0" -authors = ["..."] - -[dependencies] -uuid = "1.0.1" - -[patch.crates-io] -uuid = { git = 'https://github.com/rust-lang-nursery/uuid' } -``` - -Note that our local dependency on `uuid` has been updated to `1.0.1` as it's -what we'll actually require once the crate is published. This version doesn't -exist on crates.io, though, so we provide it with the `[patch]` section of the -manifest. - -Now when our library is built it'll fetch `uuid` from the git repository and -resolve to 1.0.1 inside the repository instead of trying to download a version -from crates.io. Once 1.0.1 is published on crates.io the `[patch]` section can -be deleted. - -It's also worth nothing that `[patch]` applies *transitively*. Let's say you use -`my-library` in a larger project, such as: - -```toml -[package] -name = "my-binary" -version = "0.1.0" -authors = ["..."] - -[dependencies] -my-library = { git = 'https://example.com/git/my-library' } -uuid = "1.0" - -[patch.crates-io] -uuid = { git = 'https://github.com/rust-lang-nursery/uuid' } -``` - -Remember that `[patch]` is only applicable at the *top level* so we consumers of -`my-library` have to repeat the `[patch]` section if necessary. Here, though, -the new `uuid` crate applies to *both* our dependency on `uuid` and the -`my-library -> uuid` dependency. The `uuid` crate will be resolved to one -version for this entire crate graph, 1.0.1, and it'll be pulled from the git -repository. - -### Prepublishing a breaking change - -As a final scenario, let's take a look at working with a new major version of a -crate, typically accompanied with breaking changes. Sticking with our previous -crates, this means that we're going to be creating version 2.0.0 of the `uuid` -crate. After we've submitted all changes upstream we can update our manifest for -`my-library` to look like: - -```toml -[dependencies] -uuid = "2.0" - -[patch.crates-io] -uuid = { git = "https://github.com/rust-lang-nursery/uuid", branch = "2.0.0" } -``` - -And that's it! Like with the previous example the 2.0.0 version doesn't actually -exist on crates.io but we can still put it in through a git dependency through -the usage of the `[patch]` section. As a thought exercise let's take another -look at the `my-binary` manifest from above again as well: - -```toml -[package] -name = "my-binary" -version = "0.1.0" -authors = ["..."] - -[dependencies] -my-library = { git = 'https://example.com/git/my-library' } -uuid = "1.0" - -[patch.crates-io] -uuid = { git = 'https://github.com/rust-lang-nursery/uuid', version = '2.0.0' } -``` - -Note that this will actually resolve to two versions of the `uuid` crate. The -`my-binary` crate will continue to use the 1.x.y series of the `uuid` crate but -the `my-library` crate will use the 2.0.0 version of `uuid`. This will allow you -to gradually roll out breaking changes to a crate through a dependency graph -without being force to update everything all at once. - -### Overriding with local dependencies - -Sometimes you're only temporarily working on a crate and you don't want to have -to modify `Cargo.toml` like with the `[patch]` section above. For this use -case Cargo offers a much more limited version of overrides called **path -overrides**. - -Path overrides are specified through `.cargo/config` instead of `Cargo.toml`, -and you can find [more documentation about this configuration][config-docs]. -Inside of `.cargo/config` you'll specify a key called `paths`: - -[config-docs]: reference/config.html - -```toml -paths = ["/path/to/uuid"] -``` - -This array should be filled with directories that contain a `Cargo.toml`. In -this instance, we’re just adding `uuid`, so it will be the only one that’s -overridden. This path can be either absolute or relative to the directory that -contains the `.cargo` folder. - -Path overrides are more restricted than the `[patch]` section, however, in -that they cannot change the structure of the dependency graph. When a -path replacement is used then the previous set of dependencies -must all match exactly to the new `Cargo.toml` specification. For example this -means that path overrides cannot be used to test out adding a dependency to a -crate, instead `[patch]` must be used in that situation. As a result usage of a -path override is typically isolated to quick bug fixes rather than larger -changes. - -Note: using a local configuration to override paths will only work for crates -that have been published to [crates.io]. You cannot use this feature to tell -Cargo how to find local unpublished crates. - -### Platform specific dependencies - - -Platform-specific dependencies take the same format, but are listed under a -`target` section. Normally Rust-like `#[cfg]` syntax will be used to define -these sections: - -```toml -[target.'cfg(windows)'.dependencies] -winhttp = "0.4.0" - -[target.'cfg(unix)'.dependencies] -openssl = "1.0.1" - -[target.'cfg(target_arch = "x86")'.dependencies] -native = { path = "native/i686" } - -[target.'cfg(target_arch = "x86_64")'.dependencies] -native = { path = "native/x86_64" } -``` - -Like with Rust, the syntax here supports the `not`, `any`, and `all` operators -to combine various cfg name/value pairs. Note that the `cfg` syntax has only -been available since Cargo 0.9.0 (Rust 1.8.0). - -In addition to `#[cfg]` syntax, Cargo also supports listing out the full target -the dependencies would apply to: - -```toml -[target.x86_64-pc-windows-gnu.dependencies] -winhttp = "0.4.0" - -[target.i686-unknown-linux-gnu.dependencies] -openssl = "1.0.1" -``` - -If you’re using a custom target specification, quote the full path and file -name: - -```toml -[target."x86_64/windows.json".dependencies] -winhttp = "0.4.0" - -[target."i686/linux.json".dependencies] -openssl = "1.0.1" -native = { path = "native/i686" } - -[target."x86_64/linux.json".dependencies] -openssl = "1.0.1" -native = { path = "native/x86_64" } -``` - -### Development dependencies - -You can add a `[dev-dependencies]` section to your `Cargo.toml` whose format -is equivalent to `[dependencies]`: - -```toml -[dev-dependencies] -tempdir = "0.3" -``` - -Dev-dependencies are not used when compiling -a package for building, but are used for compiling tests, examples, and -benchmarks. - -These dependencies are *not* propagated to other packages which depend on this -package. - -You can also have target-specific development dependencies by using -`dev-dependencies` in the target section header instead of `dependencies`. For -example: - -```toml -[target.'cfg(unix)'.dev-dependencies] -mio = "0.0.1" -``` - -[crates.io]: https://crates.io/ - -### Build dependencies - -You can depend on other Cargo-based crates for use in your build scripts. -Dependencies are declared through the `build-dependencies` section of the -manifest: - -```toml -[build-dependencies] -gcc = "0.3" -``` - -The build script **does not** have access to the dependencies listed -in the `dependencies` or `dev-dependencies` section. Build -dependencies will likewise not be available to the package itself -unless listed under the `dependencies` section as well. A package -itself and its build script are built separately, so their -dependencies need not coincide. Cargo is kept simpler and cleaner by -using independent dependencies for independent purposes. - -### Choosing features - -If a package you depend on offers conditional features, you can -specify which to use: - -```toml -[dependencies.awesome] -version = "1.3.5" -default-features = false # do not include the default features, and optionally - # cherry-pick individual features -features = ["secure-password", "civet"] -``` - -More information about features can be found in the -[manifest documentation](reference/manifest.html#the-features-section). diff -Nru cargo-0.25.0/src/doc/book/src/SUMMARY.md cargo-0.26.0/src/doc/book/src/SUMMARY.md --- cargo-0.25.0/src/doc/book/src/SUMMARY.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/book/src/SUMMARY.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -# Summary - -[Introduction](index.md) - -* [Getting Started](getting-started/index.md) - * [Installation](getting-started/installation.md) - * [First Steps with Cargo](getting-started/first-steps.md) - -* [Cargo Guide](guide/index.md) - * [Why Cargo Exists](guide/why-cargo-exists.md) - * [Creating a New Project](guide/creating-a-new-project.md) - * [Working on an Existing Project](guide/working-on-an-existing-project.md) - * [Dependencies](guide/dependencies.md) - * [Project Layout](guide/project-layout.md) - * [Cargo.toml vs Cargo.lock](guide/cargo-toml-vs-cargo-lock.md) - * [Tests](guide/tests.md) - * [Continuous Integration](guide/continuous-integration.md) - -* [Cargo Reference](reference/index.md) - * [Specifying Dependencies](reference/specifying-dependencies.md) - * [The Manifest Format](reference/manifest.md) - * [Configuration](reference/config.md) - * [Environment Variables](reference/environment-variables.md) - * [Build Scripts](reference/build-scripts.md) - * [Publishing on crates.io](reference/publishing.md) - * [Package ID Specifications](reference/pkgid-spec.md) - * [Source Replacement](reference/source-replacement.md) - * [External Tools](reference/external-tools.md) - -* [FAQ](faq.md) Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/book/theme/favicon.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/book/theme/favicon.png differ diff -Nru cargo-0.25.0/src/doc/book.toml cargo-0.26.0/src/doc/book.toml --- cargo-0.25.0/src/doc/book.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/book.toml 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,2 @@ +title = "The Cargo Book" +author = "Alex Crichton, Steve Klabnik and Carol Nichols, with Contributions from the Rust Community" diff -Nru cargo-0.25.0/src/doc/build-script.md cargo-0.26.0/src/doc/build-script.md --- cargo-0.25.0/src/doc/build-script.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/build-script.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,564 +0,0 @@ -% Build Script Support - -Some packages need to compile third-party non-Rust code, for example C -libraries. Other packages need to link to C libraries which can either be -located on the system or possibly need to be built from source. Others still -need facilities for functionality such as code generation before building (think -parser generators). - -Cargo does not aim to replace other tools that are well-optimized for -these tasks, but it does integrate with them with the `build` configuration -option. - -```toml -[package] -# ... -build = "build.rs" -``` - -The Rust file designated by the `build` command (relative to the package root) -will be compiled and invoked before anything else is compiled in the package, -allowing your Rust code to depend on the built or generated artifacts. Note that -if you do not specify a value for `build` but your package root does contains a -`"build.rs"` file, Cargo will compile and invoke this file for you. - -Some example use cases of the build command are: - -* Building a bundled C library. -* Finding a C library on the host system. -* Generating a Rust module from a specification. -* Performing any platform-specific configuration needed for the crate. - -Each of these use cases will be detailed in full below to give examples of how -the build command works. - -## Inputs to the Build Script - -When the build script is run, there are a number of inputs to the build script, -all passed in the form of [environment variables][env]. - -In addition to environment variables, the build script’s current directory is -the source directory of the build script’s package. - -[env]: environment-variables.html - -## Outputs of the Build Script - -All the lines printed to stdout by a build script are written to a file like -`target/debug/build//output` (the precise location may depend on your -configuration). If you would like to see such output directly in your terminal, -invoke cargo as 'very verbose' with the `-vv` flag. Note that if neither the -build script nor project source files are modified, subsequent calls to -cargo with the `-vv` will **not** print output to the terminal because a -new build is not executed. Run `cargo clean` before each cargo invokation -if you want to ensure that output is always displayed on your terminal. -Any line that starts with `cargo:` is interpreted directly by Cargo. -This line must be of the form `cargo:key=value`, like the examples below: - -```notrust -# specially recognized by Cargo -cargo:rustc-link-lib=static=foo -cargo:rustc-link-search=native=/path/to/foo -cargo:rustc-cfg=foo -cargo:rustc-env=FOO=bar -# arbitrary user-defined metadata -cargo:root=/path/to/foo -cargo:libdir=/path/to/foo/lib -cargo:include=/path/to/foo/include -``` - -On the other hand, lines printed to stderr are written to a file like -`target/debug/build//stderr` but are not interpreted by cargo. - -There are a few special keys that Cargo recognizes, some affecting how the -crate is built: - -* `rustc-link-lib=[KIND=]NAME` indicates that the specified value is a library - name and should be passed to the compiler as a `-l` flag. The optional `KIND` - can be one of `static`, `dylib` (the default), or `framework`, see - `rustc --help` for more details. -* `rustc-link-search=[KIND=]PATH` indicates the specified value is a library - search path and should be passed to the compiler as a `-L` flag. The optional - `KIND` can be one of `dependency`, `crate`, `native`, `framework` or `all` - (the default), see `rustc --help` for more details. -* `rustc-flags=FLAGS` is a set of flags passed to the compiler, only `-l` and - `-L` flags are supported. -* `rustc-cfg=FEATURE` indicates that the specified feature will be passed as a - `--cfg` flag to the compiler. This is often useful for performing compile-time - detection of various features. -* `rustc-env=VAR=VALUE` indicates that the specified environment variable - will be added to the environment which the compiler is run within. - The value can be then retrieved by the `env!` macro in the compiled crate. - This is useful for embedding additional metadata in crate's code, - such as the hash of Git HEAD or the unique identifier of a continuous - integration server. -* `rerun-if-changed=PATH` is a path to a file or directory which indicates that - the build script should be re-run if it changes (detected by a more-recent - last-modified timestamp on the file). Normally build scripts are re-run if - any file inside the crate root changes, but this can be used to scope changes - to just a small set of files. (If this path points to a directory the entire - directory will not be traversed for changes -- only changes to the timestamp - of the directory itself (which corresponds to some types of changes within the - directory, depending on platform) will trigger a rebuild. To request a re-run - on any changes within an entire directory, print a line for the directory and - another line for everything inside it, recursively.) - Note that if the build script itself (or one of its dependencies) changes, - then it's rebuilt and rerun unconditionally, so - `cargo:rerun-if-changed=build.rs` is almost always redundant (unless you - want to ignore changes in all other files except for `build.rs`). -* `rerun-if-env-changed=VAR` is the name of an environment variable which - indicates that if the environment variable's value changes the build script - should be rerun. This basically behaves the same as `rerun-if-changed` except - that it works with environment variables instead. Note that the environment - variables here are intended for global environment variables like `CC` and - such, it's not necessary to use this for env vars like `TARGET` that Cargo - sets. Also note that if `rerun-if-env-changed` is printed out then Cargo will - *only* rerun the build script if those environment variables change or if - files printed out by `rerun-if-changed` change. - -* `warning=MESSAGE` is a message that will be printed to the main console after - a build script has finished running. Warnings are only shown for path - dependencies (that is, those you're working on locally), so for example - warnings printed out in crates.io crates are not emitted by default. - -Any other element is a user-defined metadata that will be passed to -dependents. More information about this can be found in the [`links`][links] -section. - -[links]: #the-links-manifest-key - -## Build Dependencies - -Build scripts are also allowed to have dependencies on other Cargo-based crates. -Dependencies are declared through the `build-dependencies` section of the -manifest. - -```toml -[build-dependencies] -foo = { git = "https://github.com/your-packages/foo" } -``` - -The build script **does not** have access to the dependencies listed in the -`dependencies` or `dev-dependencies` section (they’re not built yet!). All build -dependencies will also not be available to the package itself unless explicitly -stated as so. - -## The `links` Manifest Key - -In addition to the manifest key `build`, Cargo also supports a `links` manifest -key to declare the name of a native library that is being linked to: - -```toml -[package] -# ... -links = "foo" -build = "build.rs" -``` - -This manifest states that the package links to the `libfoo` native library, and -it also has a build script for locating and/or building the library. Cargo -requires that a `build` command is specified if a `links` entry is also -specified. - -The purpose of this manifest key is to give Cargo an understanding about the set -of native dependencies that a package has, as well as providing a principled -system of passing metadata between package build scripts. - -Primarily, Cargo requires that there is at most one package per `links` value. -In other words, it’s forbidden to have two packages link to the same native -library. Note, however, that there are [conventions in place][star-sys] to -alleviate this. - -[star-sys]: #-sys-packages - -As mentioned above in the output format, each build script can generate an -arbitrary set of metadata in the form of key-value pairs. This metadata is -passed to the build scripts of **dependent** packages. For example, if `libbar` -depends on `libfoo`, then if `libfoo` generates `key=value` as part of its -metadata, then the build script of `libbar` will have the environment variables -`DEP_FOO_KEY=value`. - -Note that metadata is only passed to immediate dependents, not transitive -dependents. The motivation for this metadata passing is outlined in the linking -to system libraries case study below. - -## Overriding Build Scripts - -If a manifest contains a `links` key, then Cargo supports overriding the build -script specified with a custom library. The purpose of this functionality is to -prevent running the build script in question altogether and instead supply the -metadata ahead of time. - -To override a build script, place the following configuration in any acceptable -Cargo [configuration location](config.html). - -```toml -[target.x86_64-unknown-linux-gnu.foo] -rustc-link-search = ["/path/to/foo"] -rustc-link-lib = ["foo"] -root = "/path/to/foo" -key = "value" -``` - -This section states that for the target `x86_64-unknown-linux-gnu` the library -named `foo` has the metadata specified. This metadata is the same as the -metadata generated as if the build script had run, providing a number of -key/value pairs where the `rustc-flags`, `rustc-link-search`, and -`rustc-link-lib` keys are slightly special. - -With this configuration, if a package declares that it links to `foo` then the -build script will **not** be compiled or run, and the metadata specified will -instead be used. - -# Case study: Code generation - -Some Cargo packages need to have code generated just before they are compiled -for various reasons. Here we’ll walk through a simple example which generates a -library call as part of the build script. - -First, let’s take a look at the directory structure of this package: - -```notrust -. -├── Cargo.toml -├── build.rs -└── src - └── main.rs - -1 directory, 3 files -``` - -Here we can see that we have a `build.rs` build script and our binary in -`main.rs`. Next, let’s take a look at the manifest: - -```toml -# Cargo.toml - -[package] -name = "hello-from-generated-code" -version = "0.1.0" -authors = ["you@example.com"] -build = "build.rs" -``` - -Here we can see we’ve got a build script specified which we’ll use to generate -some code. Let’s see what’s inside the build script: - -```rust,no_run -// build.rs - -use std::env; -use std::fs::File; -use std::io::Write; -use std::path::Path; - -fn main() { - let out_dir = env::var("OUT_DIR").unwrap(); - let dest_path = Path::new(&out_dir).join("hello.rs"); - let mut f = File::create(&dest_path).unwrap(); - - f.write_all(b" - pub fn message() -> &'static str { - \"Hello, World!\" - } - ").unwrap(); -} -``` - -There’s a couple of points of note here: - -* The script uses the `OUT_DIR` environment variable to discover where the - output files should be located. It can use the process’ current working - directory to find where the input files should be located, but in this case we - don’t have any input files. -* This script is relatively simple as it just writes out a small generated file. - One could imagine that other more fanciful operations could take place such as - generating a Rust module from a C header file or another language definition, - for example. - -Next, let’s peek at the library itself: - -```rust,ignore -// src/main.rs - -include!(concat!(env!("OUT_DIR"), "/hello.rs")); - -fn main() { - println!("{}", message()); -} -``` - -This is where the real magic happens. The library is using the rustc-defined -`include!` macro in combination with the `concat!` and `env!` macros to include -the generated file (`hello.rs`) into the crate’s compilation. - -Using the structure shown here, crates can include any number of generated files -from the build script itself. - -# Case study: Building some native code - -Sometimes it’s necessary to build some native C or C++ code as part of a -package. This is another excellent use case of leveraging the build script to -build a native library before the Rust crate itself. As an example, we’ll create -a Rust library which calls into C to print “Hello, World!”. - -Like above, let’s first take a look at the project layout: - -```notrust -. -├── Cargo.toml -├── build.rs -└── src - ├── hello.c - └── main.rs - -1 directory, 4 files -``` - -Pretty similar to before! Next, the manifest: - -```toml -# Cargo.toml - -[package] -name = "hello-world-from-c" -version = "0.1.0" -authors = ["you@example.com"] -build = "build.rs" -``` - -For now we’re not going to use any build dependencies, so let’s take a look at -the build script now: - -```rust,no_run -// build.rs - -use std::process::Command; -use std::env; -use std::path::Path; - -fn main() { - let out_dir = env::var("OUT_DIR").unwrap(); - - // note that there are a number of downsides to this approach, the comments - // below detail how to improve the portability of these commands. - Command::new("gcc").args(&["src/hello.c", "-c", "-fPIC", "-o"]) - .arg(&format!("{}/hello.o", out_dir)) - .status().unwrap(); - Command::new("ar").args(&["crus", "libhello.a", "hello.o"]) - .current_dir(&Path::new(&out_dir)) - .status().unwrap(); - - println!("cargo:rustc-link-search=native={}", out_dir); - println!("cargo:rustc-link-lib=static=hello"); -} -``` - -This build script starts out by compiling our C file into an object file (by -invoking `gcc`) and then converting this object file into a static library (by -invoking `ar`). The final step is feedback to Cargo itself to say that our -output was in `out_dir` and the compiler should link the crate to `libhello.a` -statically via the `-l static=hello` flag. - -Note that there are a number of drawbacks to this hardcoded approach: - -* The `gcc` command itself is not portable across platforms. For example it’s - unlikely that Windows platforms have `gcc`, and not even all Unix platforms - may have `gcc`. The `ar` command is also in a similar situation. -* These commands do not take cross-compilation into account. If we’re cross - compiling for a platform such as Android it’s unlikely that `gcc` will produce - an ARM executable. - -Not to fear, though, this is where a `build-dependencies` entry would help! The -Cargo ecosystem has a number of packages to make this sort of task much easier, -portable, and standardized. For example, the build script could be written as: - -```rust,ignore -// build.rs - -// Bring in a dependency on an externally maintained `cc` package which manages -// invoking the C compiler. -extern crate cc; - -fn main() { - cc::Build::new() - .file("src/hello.c") - .compile("hello"); -} -``` - -Add a build time dependency on the `cc` crate with the following addition to -your `Cargo.toml`: - -```toml -[build-dependencies] -cc = "1.0" -``` - -The [`cc` crate](https://crates.io/crates/cc) abstracts a range of build -script requirements for C code: - -* It invokes the appropriate compiler (MSVC for windows, `gcc` for MinGW, `cc` - for Unix platforms, etc.). -* It takes the `TARGET` variable into account by passing appropriate flags to - the compiler being used. -* Other environment variables, such as `OPT_LEVEL`, `DEBUG`, etc., are all - handled automatically. -* The stdout output and `OUT_DIR` locations are also handled by the `cc` - library. - -Here we can start to see some of the major benefits of farming as much -functionality as possible out to common build dependencies rather than -duplicating logic across all build scripts! - -Back to the case study though, let’s take a quick look at the contents of the -`src` directory: - -```c -// src/hello.c - -#include - -void hello() { - printf("Hello, World!\n"); -} -``` - -```rust,ignore -// src/main.rs - -// Note the lack of the `#[link]` attribute. We’re delegating the responsibility -// of selecting what to link to over to the build script rather than hardcoding -// it in the source file. -extern { fn hello(); } - -fn main() { - unsafe { hello(); } -} -``` - -And there we go! This should complete our example of building some C code from a -Cargo package using the build script itself. This also shows why using a build -dependency can be crucial in many situations and even much more concise! - -We’ve also seen a brief example of how a build script can use a crate as a -dependency purely for the build process and not for the crate itself at runtime. - -# Case study: Linking to system libraries - -The final case study here will be investigating how a Cargo library links to a -system library and how the build script is leveraged to support this use case. - -Quite frequently a Rust crate wants to link to a native library often provided -on the system to bind its functionality or just use it as part of an -implementation detail. This is quite a nuanced problem when it comes to -performing this in a platform-agnostic fashion, and the purpose of a build -script is again to farm out as much of this as possible to make this as easy as -possible for consumers. - -As an example to follow, let’s take a look at one of [Cargo’s own -dependencies][git2-rs], [libgit2][libgit2]. The C library has a number of -constraints: - -[git2-rs]: https://github.com/alexcrichton/git2-rs/tree/master/libgit2-sys -[libgit2]: https://github.com/libgit2/libgit2 - -* It has an optional dependency on OpenSSL on Unix to implement the https - transport. -* It has an optional dependency on libssh2 on all platforms to implement the ssh - transport. -* It is often not installed on all systems by default. -* It can be built from source using `cmake`. - -To visualize what’s going on here, let’s take a look at the manifest for the -relevant Cargo package that links to the native C library. - -```toml -[package] -name = "libgit2-sys" -version = "0.1.0" -authors = ["..."] -links = "git2" -build = "build.rs" - -[dependencies] -libssh2-sys = { git = "https://github.com/alexcrichton/ssh2-rs" } - -[target.'cfg(unix)'.dependencies] -openssl-sys = { git = "https://github.com/alexcrichton/openssl-sys" } - -# ... -``` - -As the above manifests show, we’ve got a `build` script specified, but it’s -worth noting that this example has a `links` entry which indicates that the -crate (`libgit2-sys`) links to the `git2` native library. - -Here we also see that we chose to have the Rust crate have an unconditional -dependency on `libssh2` via the `libssh2-sys` crate, as well as a -platform-specific dependency on `openssl-sys` for \*nix (other variants elided -for now). It may seem a little counterintuitive to express *C dependencies* in -the *Cargo manifest*, but this is actually using one of Cargo’s conventions in -this space. - -## `*-sys` Packages - -To alleviate linking to system libraries, Cargo has a *convention* of package -naming and functionality. Any package named `foo-sys` will provide two major -pieces of functionality: - -* The library crate will link to the native library `libfoo`. This will often - probe the current system for `libfoo` before resorting to building from - source. -* The library crate will provide **declarations** for functions in `libfoo`, - but it does **not** provide bindings or higher-level abstractions. - -The set of `*-sys` packages provides a common set of dependencies for linking -to native libraries. There are a number of benefits earned from having this -convention of native-library-related packages: - -* Common dependencies on `foo-sys` alleviates the above rule about one package - per value of `links`. -* A common dependency allows centralizing logic on discovering `libfoo` itself - (or building it from source). -* These dependencies are easily overridable. - -## Building libgit2 - -Now that we’ve got libgit2’s dependencies sorted out, we need to actually write -the build script. We’re not going to look at specific snippets of code here and -instead only take a look at the high-level details of the build script of -`libgit2-sys`. This is not recommending all packages follow this strategy, but -rather just outlining one specific strategy. - -The first step of the build script should do is to query whether libgit2 is -already installed on the host system. To do this we’ll leverage the preexisting -tool `pkg-config` (when its available). We’ll also use a `build-dependencies` -section to refactor out all the `pkg-config` related code (or someone’s already -done that!). - -If `pkg-config` failed to find libgit2, or if `pkg-config` just wasn’t -installed, the next step is to build libgit2 from bundled source code -(distributed as part of `libgit2-sys` itself). There are a few nuances when -doing so that we need to take into account, however: - -* The build system of libgit2, `cmake`, needs to be able to find libgit2’s - optional dependency of libssh2. We’re sure we’ve already built it (it’s a - Cargo dependency), we just need to communicate this information. To do this - we leverage the metadata format to communicate information between build - scripts. In this example the libssh2 package printed out `cargo:root=...` to - tell us where libssh2 is installed at, and we can then pass this along to - cmake with the `CMAKE_PREFIX_PATH` environment variable. - -* We’ll need to handle some `CFLAGS` values when compiling C code (and tell - `cmake` about this). Some flags we may want to pass are `-m64` for 64-bit - code, `-m32` for 32-bit code, or `-fPIC` for 64-bit code as well. - -* Finally, we’ll invoke `cmake` to place all output into the `OUT_DIR` - environment variable, and then we’ll print the necessary metadata to instruct - rustc how to link to libgit2. - -Most of the functionality of this build script is easily refactorable into -common dependencies, so our build script isn’t quite as intimidating as this -descriptions! In reality it’s expected that build scripts are quite succinct by -farming logic such as above to build dependencies. diff -Nru cargo-0.25.0/src/doc/CNAME cargo-0.26.0/src/doc/CNAME --- cargo-0.25.0/src/doc/CNAME 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/CNAME 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -doc.crates.io diff -Nru cargo-0.25.0/src/doc/config.md cargo-0.26.0/src/doc/config.md --- cargo-0.25.0/src/doc/config.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/config.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,139 +0,0 @@ -% Configuration - -This document will explain how Cargo’s configuration system works, as well as -available keys or configuration. For configuration of a project through its -manifest, see the [manifest format](manifest.html). - -# Hierarchical structure - -Cargo allows local configuration for a particular project as well as global -configuration, like git. Cargo extends this to a hierarchical strategy. -If, for example, Cargo were invoked in `/projects/foo/bar/baz`, then the -following configuration files would be probed for and unified in this order: - -* `/projects/foo/bar/baz/.cargo/config` -* `/projects/foo/bar/.cargo/config` -* `/projects/foo/.cargo/config` -* `/projects/.cargo/config` -* `/.cargo/config` -* `$HOME/.cargo/config` - -With this structure, you can specify configuration per-project, and even -possibly check it into version control. You can also specify personal defaults -with a configuration file in your home directory. - -# Configuration format - -All configuration is currently in the [TOML format][toml] (like the manifest), -with simple key-value pairs inside of sections (tables) which all get merged -together. - -[toml]: https://github.com/toml-lang/toml - -# Configuration keys - -All of the following keys are optional, and their defaults are listed as their -value unless otherwise noted. - -Key values that specify a tool may be given as an absolute path, a relative path -or as a pathless tool name. Absolute paths and pathless tool names are used as -given. Relative paths are resolved relative to the parent directory of the -`.cargo` directory of the config file that the value resides within. - -```toml -# An array of paths to local repositories which are to be used as overrides for -# dependencies. For more information see the Specifying Dependencies guide. -paths = ["/path/to/override"] - -[cargo-new] -# This is your name/email to place in the `authors` section of a new Cargo.toml -# that is generated. If not present, then `git` will be probed, and if that is -# not present then `$USER` and `$EMAIL` will be used. -name = "..." -email = "..." - -# By default `cargo new` will initialize a new Git repository. This key can be -# set to `hg` to create a Mercurial repository, or `none` to disable this -# behavior. -vcs = "none" - -# For the following sections, $triple refers to any valid target triple, not the -# literal string "$triple", and it will apply whenever that target triple is -# being compiled to. 'cfg(...)' refers to the Rust-like `#[cfg]` syntax for -# conditional compilation. -[target.$triple] -# This is the linker which is passed to rustc (via `-C linker=`) when the `$triple` -# is being compiled for. By default this flag is not passed to the compiler. -linker = ".." -# Same but for the library archiver which is passed to rustc via `-C ar=`. -ar = ".." -# If a runner is provided, compiled targets for the `$triple` will be executed -# by invoking the specified runner executable with actual target as first argument. -# This applies to `cargo run`, `cargo test` and `cargo bench` commands. -# By default compiled targets are executed directly. -runner = ".." -# custom flags to pass to all compiler invocations that target $triple -# this value overrides build.rustflags when both are present -rustflags = ["..", ".."] - -[target.'cfg(...)'] -# Similar for the $triple configuration, but using the `cfg` syntax. -# If several `cfg` and $triple targets are candidates, then the rustflags -# are concatenated. The `cfg` syntax only applies to rustflags, and not to -# linker. -rustflags = ["..", ".."] - -# Configuration keys related to the registry -[registry] -index = "..." # URL of the registry index (defaults to the central repository) -token = "..." # Access token (found on the central repo’s website) - -[http] -proxy = "host:port" # HTTP proxy to use for HTTP requests (defaults to none) - # in libcurl format, e.g. "socks5h://host:port" -timeout = 60000 # Timeout for each HTTP request, in milliseconds -cainfo = "cert.pem" # Path to Certificate Authority (CA) bundle (optional) -check-revoke = true # Indicates whether SSL certs are checked for revocation - -[build] -jobs = 1 # number of parallel jobs, defaults to # of CPUs -rustc = "rustc" # the rust compiler tool -rustdoc = "rustdoc" # the doc generator tool -target = "triple" # build for the target triple -target-dir = "target" # path of where to place all generated artifacts -rustflags = ["..", ".."] # custom flags to pass to all compiler invocations -incremental = true # whether or not to enable incremental compilation - -[term] -verbose = false # whether cargo provides verbose output -color = 'auto' # whether cargo colorizes output - -# Network configuration -[net] -retry = 2 # number of times a network call will automatically retried - -# Alias cargo commands. The first 3 aliases are built in. If your -# command requires grouped whitespace use the list format. -[alias] -b = "build" -t = "test" -r = "run" -rr = "run --release" -space_example = ["run", "--release", "--", "\"command list\""] -``` - -# Environment variables - -Cargo can also be configured through environment variables in addition to the -TOML syntax above. For each configuration key above of the form `foo.bar` the -environment variable `CARGO_FOO_BAR` can also be used to define the value. For -example the `build.jobs` key can also be defined by `CARGO_BUILD_JOBS`. - -Environment variables will take precedent over TOML configuration, and currently -only integer, boolean, and string keys are supported to be defined by -environment variables. - -In addition to the system above, Cargo recognizes a few other specific -[environment variables][env]. - -[env]: environment-variables.html diff -Nru cargo-0.25.0/src/doc/crates-io.md cargo-0.26.0/src/doc/crates-io.md --- cargo-0.25.0/src/doc/crates-io.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/crates-io.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,222 +0,0 @@ -% Publishing on crates.io - -Once you've got a library that you'd like to share with the world, it's time to -publish it on [crates.io]! Publishing a crate is when a specific -version is uploaded to be hosted on [crates.io]. - -Take care when publishing a crate, because a publish is **permanent**. The -version can never be overwritten, and the code cannot be deleted. There is no -limit to the number of versions which can be published, however. - -# Before your first publish - -First thing’s first, you’ll need an account on [crates.io] to acquire -an API token. To do so, [visit the home page][crates.io] and log in via a GitHub -account (required for now). After this, visit your [Account -Settings](https://crates.io/me) page and run the `cargo login` command -specified. - -```notrust -$ cargo login abcdefghijklmnopqrstuvwxyz012345 -``` - -This command will inform Cargo of your API token and store it locally in your -`~/.cargo/credentials` (previously it was `~/.cargo/config`). Note that this -token is a **secret** and should not be shared with anyone else. If it leaks for -any reason, you should regenerate it immediately. - -# Before publishing a new crate - -Keep in mind that crate names on [crates.io] are allocated on a first-come-first- -serve basis. Once a crate name is taken, it cannot be used for another crate. - -## Packaging a crate - -The next step is to package up your crate into a format that can be uploaded to -[crates.io]. For this we’ll use the `cargo package` subcommand. This will take -our entire crate and package it all up into a `*.crate` file in the -`target/package` directory. - -```notrust -$ cargo package -``` - -As an added bonus, the `*.crate` will be verified independently of the current -source tree. After the `*.crate` is created, it’s unpacked into -`target/package` and then built from scratch to ensure that all necessary files -are there for the build to succeed. This behavior can be disabled with the -`--no-verify` flag. - -Now’s a good time to take a look at the `*.crate` file to make sure you didn’t -accidentally package up that 2GB video asset, or large data files used for code -generation, integration tests, or benchmarking. There is currently a 10MB -upload size limit on `*.crate` files. So, if the size of `tests` and `benches` -directories and their dependencies are up to a couple of MBs, you can keep them -in your package; otherwise, better to exclude them. - -Cargo will automatically ignore files ignored by your version control system -when packaging, but if you want to specify an extra set of files to ignore you -can use the `exclude` key in the manifest: - -```toml -[package] -# ... -exclude = [ - "public/assets/*", - "videos/*", -] -``` - -The syntax of each element in this array is what -[rust-lang/glob](https://github.com/rust-lang/glob) accepts. If you’d rather -roll with a whitelist instead of a blacklist, Cargo also supports an `include` -key, which if set, overrides the `exclude` key: - -```toml -[package] -# ... -include = [ - "**/*.rs", - "Cargo.toml", -] -``` - -## Uploading the crate - -Now that we’ve got a `*.crate` file ready to go, it can be uploaded to -[crates.io] with the `cargo publish` command. And that’s it, you’ve now published -your first crate! - -```notrust -$ cargo publish -``` - -If you’d like to skip the `cargo package` step, the `cargo publish` subcommand -will automatically package up the local crate if a copy isn’t found already. - -Be sure to check out the [metadata you can -specify](manifest.html#package-metadata) to ensure your crate can be discovered -more easily! - -# Publishing a new version of an existing crate - -In order to release a new version, change the `version` value specified in your -`Cargo.toml` manifest. Keep in mind [the semver -rules](manifest.html#the-version-field). Then optionally run `cargo package` if -you want to inspect the `*.crate` file for the new version before publishing, -and run `cargo publish` to upload the new version. - -# Managing a crates.io-based crate - -Management of crates is primarily done through the command line `cargo` tool -rather than the [crates.io] web interface. For this, there are a few subcommands -to manage a crate. - -## `cargo yank` - -Occasions may arise where you publish a version of a crate that actually ends up -being broken for one reason or another (syntax error, forgot to include a file, -etc.). For situations such as this, Cargo supports a “yank” of a version of a -crate. - -```notrust -$ cargo yank --vers 1.0.1 -$ cargo yank --vers 1.0.1 --undo -``` - -A yank **does not** delete any code. This feature is not intended for deleting -accidentally uploaded secrets, for example. If that happens, you must reset -those secrets immediately. - -The semantics of a yanked version are that no new dependencies can be created -against that version, but all existing dependencies continue to work. One of the -major goals of [crates.io] is to act as a permanent archive of crates that does -not change over time, and allowing deletion of a version would go against this -goal. Essentially a yank means that all projects with a `Cargo.lock` will not -break, while any future `Cargo.lock` files generated will not list the yanked -version. - -## `cargo owner` - -A crate is often developed by more than one person, or the primary maintainer -may change over time! The owner of a crate is the only person allowed to publish -new versions of the crate, but an owner may designate additional owners. - -```notrust -$ cargo owner --add my-buddy -$ cargo owner --remove my-buddy -$ cargo owner --add github:rust-lang:owners -$ cargo owner --remove github:rust-lang:owners -``` - -The owner IDs given to these commands must be GitHub user names or GitHub teams. - -If a user name is given to `--add`, that user becomes a “named” owner, with -full rights to the crate. In addition to being able to publish or yank versions -of the crate, they have the ability to add or remove owners, *including* the -owner that made *them* an owner. Needless to say, you shouldn’t make people you -don’t fully trust into a named owner. In order to become a named owner, a user -must have logged into [crates.io] previously. - -If a team name is given to `--add`, that team becomes a “team” owner, with -restricted right to the crate. While they have permission to publish or yank -versions of the crate, they *do not* have the ability to add or remove owners. -In addition to being more convenient for managing groups of owners, teams are -just a bit more secure against owners becoming malicious. - -The syntax for teams is currently `github:org:team` (see examples above). -In order to add a team as an owner one must be a member of that team. No -such restriction applies to removing a team as an owner. - -## GitHub permissions - -Team membership is not something GitHub provides simple public access to, and it -is likely for you to encounter the following message when working with them: - -> It looks like you don’t have permission to query a necessary property from -GitHub to complete this request. You may need to re-authenticate on [crates.io] -to grant permission to read GitHub org memberships. Just go to -https://crates.io/login - -This is basically a catch-all for “you tried to query a team, and one of the -five levels of membership access control denied this”. That is not an -exaggeration. GitHub’s support for team access control is Enterprise Grade. - -The most likely cause of this is simply that you last logged in before this -feature was added. We originally requested *no* permissions from GitHub when -authenticating users, because we didn’t actually ever use the user’s token for -anything other than logging them in. However to query team membership on your -behalf, we now require -[the `read:org` scope](https://developer.github.com/v3/oauth/#scopes). - -You are free to deny us this scope, and everything that worked before teams -were introduced will keep working. However you will never be able to add a team -as an owner, or publish a crate as a team owner. If you ever attempt to do this, -you will get the error above. You may also see this error if you ever try to -publish a crate that you don’t own at all, but otherwise happens to have a team. - -If you ever change your mind, or just aren’t sure if [crates.io] has sufficient -permission, you can always go to https://crates.io/login, which will prompt you -for permission if [crates.io] doesn’t have all the scopes it would like to. - -An additional barrier to querying GitHub is that the organization may be -actively denying third party access. To check this, you can go to: - - https://github.com/organizations/:org/settings/oauth_application_policy - -where `:org` is the name of the organization (e.g. rust-lang). You may see -something like: - -![Organization Access Control](images/org-level-acl.png) - -Where you may choose to explicitly remove [crates.io] from your organization’s -blacklist, or simply press the “Remove Restrictions” button to allow all third -party applications to access this data. - -Alternatively, when [crates.io] requested the `read:org` scope, you could have -explicitly whitelisted [crates.io] querying the org in question by pressing -the “Grant Access” button next to its name: - -![Authentication Access Control](images/auth-level-acl.png) - -[crates.io]: https://crates.io/ diff -Nru cargo-0.25.0/src/doc/environment-variables.md cargo-0.26.0/src/doc/environment-variables.md --- cargo-0.25.0/src/doc/environment-variables.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/environment-variables.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,136 +0,0 @@ -% Environment Variables - -Cargo sets and reads a number of environment variables which your code can detect -or override. Here is a list of the variables Cargo sets, organized by when it interacts -with them: - -# Environment variables Cargo reads - -You can override these environment variables to change Cargo's behavior on your -system: - -* `CARGO_HOME` - Cargo maintains a local cache of the registry index and of git - checkouts of crates. By default these are stored under `$HOME/.cargo`, but - this variable overrides the location of this directory. Once a crate is cached - it is not removed by the clean command. -* `CARGO_TARGET_DIR` - Location of where to place all generated artifacts, - relative to the current working directory. -* `RUSTC` - Instead of running `rustc`, Cargo will execute this specified - compiler instead. -* `RUSTC_WRAPPER` - Instead of simply running `rustc`, Cargo will execute this - specified wrapper instead, passing as its commandline arguments the rustc - invocation, with the first argument being rustc. -* `RUSTDOC` - Instead of running `rustdoc`, Cargo will execute this specified - `rustdoc` instance instead. -* `RUSTDOCFLAGS` - A space-separated list of custom flags to pass to all `rustdoc` - invocations that Cargo performs. In contrast with `cargo rustdoc`, this is - useful for passing a flag to *all* `rustdoc` instances. -* `RUSTFLAGS` - A space-separated list of custom flags to pass to all compiler - invocations that Cargo performs. In contrast with `cargo rustc`, this is - useful for passing a flag to *all* compiler instances. -* `CARGO_INCREMENTAL` - If this is set to 1 then Cargo will force incremental - compilation to be enabled for the current compilation, and when set to 0 it - will force disabling it. If this env var isn't present then Cargo's defaults - will otherwise be used. - -Note that Cargo will also read environment variables for `.cargo/config` -configuration values, as described in [that documentation][config-env] - -[config-env]: config.html#environment-variables - -# Environment variables Cargo sets for crates - -Cargo exposes these environment variables to your crate when it is compiled. -Note that this applies for test binaries as well. -To get the value of any of these variables in a Rust program, do this: - -``` -let version = env!("CARGO_PKG_VERSION"); -``` - -`version` will now contain the value of `CARGO_PKG_VERSION`. - -* `CARGO` - Path to the `cargo` binary performing the build. -* `CARGO_MANIFEST_DIR` - The directory containing the manifest of your package. -* `CARGO_PKG_VERSION` - The full version of your package. -* `CARGO_PKG_VERSION_MAJOR` - The major version of your package. -* `CARGO_PKG_VERSION_MINOR` - The minor version of your package. -* `CARGO_PKG_VERSION_PATCH` - The patch version of your package. -* `CARGO_PKG_VERSION_PRE` - The pre-release version of your package. -* `CARGO_PKG_AUTHORS` - Colon separated list of authors from the manifest of your package. -* `CARGO_PKG_NAME` - The name of your package. -* `CARGO_PKG_DESCRIPTION` - The description of your package. -* `CARGO_PKG_HOMEPAGE` - The home page of your package. -* `OUT_DIR` - If the package has a build script, this is set to the folder where the build - script should place its output. See below for more information. - -# Environment variables Cargo sets for build scripts - -Cargo sets several environment variables when build scripts are run. Because these variables -are not yet set when the build script is compiled, the above example using `env!` won't work -and instead you'll need to retrieve the values when the build script is run: - -``` -use std::env; -let out_dir = env::var("OUT_DIR").unwrap(); -``` - -`out_dir` will now contain the value of `OUT_DIR`. - -* `CARGO` - Path to the `cargo` binary performing the build. -* `CARGO_MANIFEST_DIR` - The directory containing the manifest for the package - being built (the package containing the build - script). Also note that this is the value of the - current working directory of the build script when it - starts. -* `CARGO_MANIFEST_LINKS` - the manifest `links` value. -* `CARGO_FEATURE_` - For each activated feature of the package being - built, this environment variable will be present - where `` is the name of the feature uppercased - and having `-` translated to `_`. -* `CARGO_CFG_` - For each [configuration option][configuration] of the - package being built, this environment variable will - contain the value of the configuration, where `` is - the name of the configuration uppercased and having `-` - translated to `_`. - Boolean configurations are present if they are set, and - not present otherwise. - Configurations with multiple values are joined to a - single variable with the values delimited by `,`. -* `OUT_DIR` - the folder in which all output should be placed. This folder is - inside the build directory for the package being built, and it is - unique for the package in question. -* `TARGET` - the target triple that is being compiled for. Native code should be - compiled for this triple. Some more information about target - triples can be found in [clang’s own documentation][clang]. -* `HOST` - the host triple of the rust compiler. -* `NUM_JOBS` - the parallelism specified as the top-level parallelism. This can - be useful to pass a `-j` parameter to a system like `make`. Note - that care should be taken when interpreting this environment - variable. For historical purposes this is still provided but - recent versions of Cargo, for example, do not need to run `make - -j` as it'll automatically happen. Cargo implements its own - [jobserver] and will allow build scripts to inherit this - information, so programs compatible with GNU make jobservers will - already have appropriately configured parallelism. -* `OPT_LEVEL`, `DEBUG` - values of the corresponding variables for the - profile currently being built. -* `PROFILE` - `release` for release builds, `debug` for other builds. -* `DEP__` - For more information about this set of environment - variables, see build script documentation about [`links`][links]. -* `RUSTC`, `RUSTDOC` - the compiler and documentation generator that Cargo has - resolved to use, passed to the build script so it might - use it as well. - -[links]: build-script.html#the-links-manifest-key -[profile]: manifest.html#the-profile-sections -[configuration]: https://doc.rust-lang.org/reference/attributes.html#conditional-compilation -[clang]:http://clang.llvm.org/docs/CrossCompilation.html#target-triple -[jobserver]: http://make.mad-scientist.net/papers/jobserver-implementation/ - -# Environment variables Cargo sets for 3rd party subcommands - -Cargo exposes this environment variable to 3rd party subcommands -(ie. programs named `cargo-foobar` placed in `$PATH`): - -* `CARGO` - Path to the `cargo` binary performing the build. diff -Nru cargo-0.25.0/src/doc/external-tools.md cargo-0.26.0/src/doc/external-tools.md --- cargo-0.25.0/src/doc/external-tools.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/external-tools.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -% External tools - -One of the goals of Cargo is simple integration with third-party tools, like -IDEs and other build systems. To make integration easier, Cargo has several -facilities: - -* a `cargo metadata` command, which outputs project structure and dependencies - information in JSON, - -* a `--message-format` flag, which outputs information about a particular build, - and - -* support for custom subcommands. - - -# Information about project structure - -You can use `cargo metadata` command to get information about project structure -and dependencies. The output of the command looks like this: - -```text -{ - // Integer version number of the format. - "version": integer, - - // List of packages for this workspace, including dependencies. - "packages": [ - { - // Opaque package identifier. - "id": PackageId, - - "name": string, - - "version": string, - - "source": SourceId, - - // A list of declared dependencies, see `resolve` field for actual dependencies. - "dependencies": [ Dependency ], - - "targets: [ Target ], - - // Path to Cargo.toml - "manifest_path": string, - } - ], - - "workspace_members": [ PackageId ], - - // Dependencies graph. - "resolve": { - "nodes": [ - { - "id": PackageId, - "dependencies": [ PackageId ] - } - ] - } -} -``` - -The format is stable and versioned. When calling `cargo metadata`, you should -pass `--format-version` flag explicitly to avoid forward incompatibility -hazard. - -If you are using Rust, there is [cargo_metadata] crate. - -[cargo_metadata]: https://crates.io/crates/cargo_metadata - - -# Information about build - -When passing `--message-format=json`, Cargo will output the following -information during the build: - -* compiler errors and warnings, - -* produced artifacts, - -* results of the build scripts (for example, native dependencies). - -The output goes to stdout in the JSON object per line format. The `reason` field -distinguishes different kinds of messages. - -Information about dependencies in the Makefile-compatible format is stored in -the `.d` files alongside the artifacts. - - -# Custom subcommands - -Cargo is designed to be extensible with new subcommands without having to modify -Cargo itself. This is achieved by translating a cargo invocation of the form -cargo `(?[^ ]+)` into an invocation of an external tool -`cargo-${command}` that then needs to be present in one of the user's `$PATH` -directories. - -Custom subcommand may use `CARGO` environment variable to call back to -Cargo. Alternatively, it can link to `cargo` crate as a library, but this -approach has drawbacks: - -* Cargo as a library is unstable, API changes without deprecation, - -* versions of Cargo library and Cargo binary may be different. diff -Nru cargo-0.25.0/src/doc/faq.md cargo-0.26.0/src/doc/faq.md --- cargo-0.25.0/src/doc/faq.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/faq.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,193 +0,0 @@ -% Frequently Asked Questions - -# Is the plan to use GitHub as a package repository? - -No. The plan for Cargo is to use [crates.io], like npm or Rubygems do with -npmjs.org and rubygems.org. - -We plan to support git repositories as a source of packages forever, -because they can be used for early development and temporary patches, -even when people use the registry as the primary source of packages. - -# Why build crates.io rather than use GitHub as a registry? - -We think that it’s very important to support multiple ways to download -packages, including downloading from GitHub and copying packages into -your project itself. - -That said, we think that [crates.io] offers a number of important benefits, and -will likely become the primary way that people download packages in Cargo. - -For precedent, both Node.js’s [npm][1] and Ruby’s [bundler][2] support both a -central registry model as well as a Git-based model, and most packages -are downloaded through the registry in those ecosystems, with an -important minority of packages making use of git-based packages. - -[1]: https://www.npmjs.org -[2]: https://bundler.io - -Some of the advantages that make a central registry popular in other -languages include: - -* **Discoverability**. A central registry provides an easy place to look - for existing packages. Combined with tagging, this also makes it - possible for a registry to provide ecosystem-wide information, such as a - list of the most popular or most-depended-on packages. -* **Speed**. A central registry makes it possible to easily fetch just - the metadata for packages quickly and efficiently, and then to - efficiently download just the published package, and not other bloat - that happens to exist in the repository. This adds up to a significant - improvement in the speed of dependency resolution and fetching. As - dependency graphs scale up, downloading all of the git repositories bogs - down fast. Also remember that not everybody has a high-speed, - low-latency Internet connection. - -# Will Cargo work with C code (or other languages)? - -Yes! - -Cargo handles compiling Rust code, but we know that many Rust projects -link against C code. We also know that there are decades of tooling -built up around compiling languages other than Rust. - -Our solution: Cargo allows a package to [specify a script](build-script.html) -(written in Rust) to run before invoking `rustc`. Rust is leveraged to -implement platform-specific configuration and refactor out common build -functionality among packages. - -# Can Cargo be used inside of `make` (or `ninja`, or ...) - -Indeed. While we intend Cargo to be useful as a standalone way to -compile Rust projects at the top-level, we know that some people will -want to invoke Cargo from other build tools. - -We have designed Cargo to work well in those contexts, paying attention -to things like error codes and machine-readable output modes. We still -have some work to do on those fronts, but using Cargo in the context of -conventional scripts is something we designed for from the beginning and -will continue to prioritize. - -# Does Cargo handle multi-platform projects or cross-compilation? - -Rust itself provides facilities for configuring sections of code based -on the platform. Cargo also supports [platform-specific -dependencies][target-deps], and we plan to support more per-platform -configuration in `Cargo.toml` in the future. - -[target-deps]: manifest.html#the-dependencies-section - -In the longer-term, we’re looking at ways to conveniently cross-compile -projects using Cargo. - -# Does Cargo support environments, like `production` or `test`? - -We support environments through the use of [profiles][profile] to support: - -[profile]: manifest.html#the-profile-sections - -* environment-specific flags (like `-g --opt-level=0` for development - and `--opt-level=3` for production). -* environment-specific dependencies (like `hamcrest` for test assertions). -* environment-specific `#[cfg]` -* a `cargo test` command - -# Does Cargo work on Windows? - -Yes! - -All commits to Cargo are required to pass the local test suite on Windows. -If, however, you find a Windows issue, we consider it a bug, so [please file an -issue][3]. - -[3]: https://github.com/rust-lang/cargo/issues - -# Why do binaries have `Cargo.lock` in version control, but not libraries? - -The purpose of a `Cargo.lock` is to describe the state of the world at the time -of a successful build. It is then used to provide deterministic builds across -whatever machine is building the project by ensuring that the exact same -dependencies are being compiled. - -This property is most desirable from applications and projects which are at the -very end of the dependency chain (binaries). As a result, it is recommended that -all binaries check in their `Cargo.lock`. - -For libraries the situation is somewhat different. A library is not only used by -the library developers, but also any downstream consumers of the library. Users -dependent on the library will not inspect the library’s `Cargo.lock` (even if it -exists). This is precisely because a library should **not** be deterministically -recompiled for all users of the library. - -If a library ends up being used transitively by several dependencies, it’s -likely that just a single copy of the library is desired (based on semver -compatibility). If all libraries were to check in their `Cargo.lock`, then -multiple copies of the library would be used, and perhaps even a version -conflict. - -In other words, libraries specify semver requirements for their dependencies but -cannot see the full picture. Only end products like binaries have a full -picture to decide what versions of dependencies should be used. - -# Can libraries use `*` as a version for their dependencies? - -**As of January 22nd, 2016, [crates.io] rejects all packages (not just libraries) -with wildcard dependency constraints.** - -While libraries _can_, strictly speaking, they should not. A version requirement -of `*` says “This will work with every version ever,” which is never going -to be true. Libraries should always specify the range that they do work with, -even if it’s something as general as “every 1.x.y version.” - -# Why `Cargo.toml`? - -As one of the most frequent interactions with Cargo, the question of why the -configuration file is named `Cargo.toml` arises from time to time. The leading -capital-`C` was chosen to ensure that the manifest was grouped with other -similar configuration files in directory listings. Sorting files often puts -capital letters before lowercase letters, ensuring files like `Makefile` and -`Cargo.toml` are placed together. The trailing `.toml` was chosen to emphasize -the fact that the file is in the [TOML configuration -format](https://github.com/toml-lang/toml). - -Cargo does not allow other names such as `cargo.toml` or `Cargofile` to -emphasize the ease of how a Cargo repository can be identified. An option of -many possible names has historically led to confusion where one case was handled -but others were accidentally forgotten. - -[crates.io]: https://crates.io/ - -# How can Cargo work offline? - -Cargo is often used in situations with limited or no network access such as -airplanes, CI environments, or embedded in large production deployments. Users -are often surprised when Cargo attempts to fetch resources from the network, and -hence the request for Cargo to work offline comes up frequently. - -Cargo, at its heart, will not attempt to access the network unless told to do -so. That is, if no crates comes from crates.io, a git repository, or some other -network location, Cargo will never attempt to make a network connection. As a -result, if Cargo attempts to touch the network, then it's because it needs to -fetch a required resource. - -Cargo is also quite aggressive about caching information to minimize the amount -of network activity. It will guarantee, for example, that if `cargo build` (or -an equivalent) is run to completion then the next `cargo build` is guaranteed to -not touch the network so long as `Cargo.toml` has not been modified in the -meantime. This avoidance of the network boils down to a `Cargo.lock` existing -and a populated cache of the crates reflected in the lock file. If either of -these components are missing, then they're required for the build to succeed and -must be fetched remotely. - -As of Rust 1.11.0 Cargo understands a new flag, `--frozen`, which is an -assertion that it shouldn't touch the network. When passed, Cargo will -immediately return an error if it would otherwise attempt a network request. -The error should include contextual information about why the network request is -being made in the first place to help debug as well. Note that this flag *does -not change the behavior of Cargo*, it simply asserts that Cargo shouldn't touch -the network as a previous command has been run to ensure that network activity -shouldn't be necessary. - -For more information about vendoring, see documentation on [source -replacement][replace]. - -[replace]: source-replacement.html Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/favicon.ico and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/favicon.ico differ diff -Nru cargo-0.25.0/src/doc/footer.html cargo-0.26.0/src/doc/footer.html --- cargo-0.25.0/src/doc/footer.html 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/footer.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ - - - - - diff -Nru cargo-0.25.0/src/doc/guide.md cargo-0.26.0/src/doc/guide.md --- cargo-0.25.0/src/doc/guide.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/guide.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,446 +0,0 @@ -% Cargo Guide - -Welcome to the Cargo guide. This guide will give you all that you need to know -about how to use Cargo to develop Rust projects. - -# Why Cargo exists - -Cargo is a tool that allows Rust projects to declare their various -dependencies and ensure that you’ll always get a repeatable build. - -To accomplish this goal, Cargo does four things: - -* Introduces two metadata files with various bits of project information. -* Fetches and builds your project’s dependencies. -* Invokes `rustc` or another build tool with the correct parameters to build - your project. -* Introduces conventions to make working with Rust projects easier. - -# Creating a new project - -To start a new project with Cargo, use `cargo new`: - -```shell -$ cargo new hello_world --bin -``` - -We’re passing `--bin` because we’re making a binary program: if we -were making a library, we’d leave it off. This also initializes a new `git` -repository by default. If you don't want it to do that, pass `--vcs none`. - -Let’s check out what Cargo has generated for us: - -```shell -$ cd hello_world -$ tree . -. -├── Cargo.toml -└── src - └── main.rs - -1 directory, 2 files -``` - -If we had just used `cargo new hello_world` without the `--bin` flag, then -we would have a `lib.rs` instead of a `main.rs`. For now, however, this is all -we need to get started. First, let’s check out `Cargo.toml`: - -```toml -[package] -name = "hello_world" -version = "0.1.0" -authors = ["Your Name "] -``` - -This is called a **manifest**, and it contains all of the metadata that Cargo -needs to compile your project. - -Here’s what’s in `src/main.rs`: - -```rust -fn main() { - println!("Hello, world!"); -} -``` - -Cargo generated a “hello world” for us. Let’s compile it: - -```shell -$ cargo build - Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) -``` - -And then run it: - -```shell -$ ./target/debug/hello_world -Hello, world! -``` - -We can also use `cargo run` to compile and then run it, all in one step (You -won't see the `Compiling` line if you have not made any changes since you last -compiled): - -```shell -$ cargo run - Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) - Running `target/debug/hello_world` -Hello, world! -``` - -You’ll now notice a new file, `Cargo.lock`. It contains information about our -dependencies. Since we don’t have any yet, it’s not very interesting. - -Once you’re ready for release, you can use `cargo build --release` to compile -your files with optimizations turned on: - -```shell -$ cargo build --release - Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) -``` - -`cargo build --release` puts the resulting binary in `target/release` instead of -`target/debug`. - -Compiling in debug mode is the default for development-- compilation time is -shorter since the compiler doesn't do optimizations, but the code will run -slower. Release mode takes longer to compile, but the code will run faster. - -# Working on an existing Cargo project - -If you download an existing project that uses Cargo, it’s really easy -to get going. - -First, get the project from somewhere. In this example, we’ll use `rand` -cloned from its repository on GitHub: - -```shell -$ git clone https://github.com/rust-lang-nursery/rand.git -$ cd rand -``` - -To build, use `cargo build`: - -```shell -$ cargo build - Compiling rand v0.1.0 (file:///path/to/project/rand) -``` - -This will fetch all of the dependencies and then build them, along with the -project. - -# Adding dependencies from crates.io - -[crates.io] is the Rust community's central package registry that serves as a -location to discover and download packages. `cargo` is configured to use it by -default to find requested packages. - -To depend on a library hosted on [crates.io], add it to your `Cargo.toml`. - -[crates.io]: https://crates.io/ - -## Adding a dependency - -If your `Cargo.toml` doesn't already have a `[dependencies]` section, add that, -then list the crate name and version that you would like to use. This example -adds a dependency of the `time` crate: - -```toml -[dependencies] -time = "0.1.12" -``` - -The version string is a [semver] version requirement. The [specifying -dependencies](specifying-dependencies.html) docs have more information about -the options you have here. - -[semver]: https://github.com/steveklabnik/semver#requirements - -If we also wanted to add a dependency on the `regex` crate, we would not need -to add `[dependencies]` for each crate listed. Here's what your whole -`Cargo.toml` file would look like with dependencies on the `time` and `regex` -crates: - -```toml -[package] -name = "hello_world" -version = "0.1.0" -authors = ["Your Name "] - -[dependencies] -time = "0.1.12" -regex = "0.1.41" -``` - -Re-run `cargo build`, and Cargo will fetch the new dependencies and all of -their dependencies, compile them all, and update the `Cargo.lock`: - -```shell -$ cargo build - Updating registry `https://github.com/rust-lang/crates.io-index` - Downloading memchr v0.1.5 - Downloading libc v0.1.10 - Downloading regex-syntax v0.2.1 - Downloading memchr v0.1.5 - Downloading aho-corasick v0.3.0 - Downloading regex v0.1.41 - Compiling memchr v0.1.5 - Compiling libc v0.1.10 - Compiling regex-syntax v0.2.1 - Compiling memchr v0.1.5 - Compiling aho-corasick v0.3.0 - Compiling regex v0.1.41 - Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) -``` - -Our `Cargo.lock` contains the exact information about which revision of all of -these dependencies we used. - -Now, if `regex` gets updated, we will still build with the same revision until -we choose to `cargo update`. - -You can now use the `regex` library using `extern crate` in `main.rs`. - -```rust -extern crate regex; - -use regex::Regex; - -fn main() { - let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); - println!("Did our date match? {}", re.is_match("2014-01-01")); -} -``` - -Running it will show: - -```shell -$ cargo run - Running `target/hello_world` -Did our date match? true -``` -# Project layout - -Cargo uses conventions for file placement to make it easy to dive into a new -Cargo project: - -```shell -. -├── Cargo.lock -├── Cargo.toml -├── benches -│   └── large-input.rs -├── examples -│   └── simple.rs -├── src -│   ├── bin -│   │   └── another_executable.rs -│   ├── lib.rs -│   └── main.rs -└── tests - └── some-integration-tests.rs -``` - -* `Cargo.toml` and `Cargo.lock` are stored in the root of your project (*package - root*). -* Source code goes in the `src` directory. -* The default library file is `src/lib.rs`. -* The default executable file is `src/main.rs`. -* Other executables can be placed in `src/bin/*.rs`. -* Integration tests go in the `tests` directory (unit tests go in each file - they're testing). -* Examples go in the `examples` directory. -* Benchmarks go in the `benches` directory. - -These are explained in more detail in the [manifest -description](manifest.html#the-project-layout). - -# Cargo.toml vs Cargo.lock - -`Cargo.toml` and `Cargo.lock` serve two different purposes. Before we talk -about them, here’s a summary: - -* `Cargo.toml` is about describing your dependencies in a broad sense, and is - written by you. -* `Cargo.lock` contains exact information about your dependencies. It is - maintained by Cargo and should not be manually edited. - -If you’re building a library that other projects will depend on, put -`Cargo.lock` in your `.gitignore`. If you’re building an executable like a -command-line tool or an application, check `Cargo.lock` into `git`. If you're -curious about why that is, see ["Why do binaries have `Cargo.lock` in version -control, but not libraries?" in the -FAQ](faq.html#why-do-binaries-have-cargolock-in-version-control-but-not-libraries). - -Let’s dig in a little bit more. - -`Cargo.toml` is a **manifest** file in which we can specify a bunch of -different metadata about our project. For example, we can say that we depend -on another project: - -```toml -[package] -name = "hello_world" -version = "0.1.0" -authors = ["Your Name "] - -[dependencies] -rand = { git = "https://github.com/rust-lang-nursery/rand.git" } -``` - -This project has a single dependency, on the `rand` library. We’ve stated in -this case that we’re relying on a particular Git repository that lives on -GitHub. Since we haven’t specified any other information, Cargo assumes that -we intend to use the latest commit on the `master` branch to build our project. - -Sound good? Well, there’s one problem: If you build this project today, and -then you send a copy to me, and I build this project tomorrow, something bad -could happen. There could be more commits to `rand` in the meantime, and my -build would include new commits while yours would not. Therefore, we would -get different builds. This would be bad because we want reproducible builds. - -We could fix this problem by putting a `rev` line in our `Cargo.toml`: - -```toml -[dependencies] -rand = { git = "https://github.com/rust-lang-nursery/rand.git", rev = "9f35b8e" } -``` - -Now our builds will be the same. But there’s a big drawback: now we have to -manually think about SHA-1s every time we want to update our library. This is -both tedious and error prone. - -Enter the `Cargo.lock`. Because of its existence, we don’t need to manually -keep track of the exact revisions: Cargo will do it for us. When we have a -manifest like this: - -```toml -[package] -name = "hello_world" -version = "0.1.0" -authors = ["Your Name "] - -[dependencies] -rand = { git = "https://github.com/rust-lang-nursery/rand.git" } -``` - -Cargo will take the latest commit and write that information out into our -`Cargo.lock` when we build for the first time. That file will look like this: - -```toml -[[package]] -name = "hello_world" -version = "0.1.0" -dependencies = [ - "rand 0.1.0 (git+https://github.com/rust-lang-nursery/rand.git#9f35b8e439eeedd60b9414c58f389bdc6a3284f9)", -] - -[[package]] -name = "rand" -version = "0.1.0" -source = "git+https://github.com/rust-lang-nursery/rand.git#9f35b8e439eeedd60b9414c58f389bdc6a3284f9" -``` - -You can see that there’s a lot more information here, including the exact -revision we used to build. Now when you give your project to someone else, -they’ll use the exact same SHA, even though we didn’t specify it in our -`Cargo.toml`. - -When we’re ready to opt in to a new version of the library, Cargo can -re-calculate the dependencies and update things for us: - -```shell -$ cargo update # updates all dependencies -$ cargo update -p rand # updates just “rand” -``` - -This will write out a new `Cargo.lock` with the new version information. Note -that the argument to `cargo update` is actually a -[Package ID Specification](pkgid-spec.html) and `rand` is just a short -specification. - -# Tests - -Cargo can run your tests with the `cargo test` command. Cargo looks for tests -to run in two places: in each of your `src` files and any tests in `tests/`. -Tests in your `src` files should be unit tests, and tests in `tests/` should be -integration-style tests. As such, you’ll need to import your crates into -the files in `tests`. - -Here's an example of running `cargo test` in our project, which currently has -no tests: - -```shell -$ cargo test - Compiling rand v0.1.0 (https://github.com/rust-lang-nursery/rand.git#9f35b8e) - Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) - Running target/test/hello_world-9c2b65bbb79eabce - -running 0 tests - -test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out -``` - -If our project had tests, we would see more output with the correct number of -tests. - -You can also run a specific test by passing a filter: - -```shell -$ cargo test foo -``` - -This will run any test with `foo` in its name. - -`cargo test` runs additional checks as well. For example, it will compile any -examples you’ve included and will also test the examples in your -documentation. Please see the [testing guide][testing] in the Rust -documentation for more details. - -[testing]: https://doc.rust-lang.org/book/testing.html - -## Travis CI - -To test your project on Travis CI, here is a sample `.travis.yml` file: - -```yaml -language: rust -rust: - - stable - - beta - - nightly -matrix: - allow_failures: - - rust: nightly -``` - -This will test all three release channels, but any breakage in nightly -will not fail your overall build. Please see the [Travis CI Rust -documentation](https://docs.travis-ci.com/user/languages/rust/) for more -information. - - -## Build cache - -Cargo shares build artifacts among all the packages of a single workspace. -Today, Cargo does not share build results across different workspaces, but -a similar result can be achieved by using a third party tool, [sccache]. - -To setup `sccache`, install it with `cargo install sccache` and set -`RUSTC_WRAPPER` environmental variable to `sccache` before invoking Cargo. -If you use bash, it makes sense to add `export RUSTC_WRAPPER=sccache` to -`.bashrc`. Refer to sccache documentation for more details. - -[sccache]: https://github.com/mozilla/sccache - - -# Further reading - -Now that you have an overview of how to use cargo and have created your first -crate, you may be interested in: - -* [Publishing your crate on crates.io](crates-io.html) -* [Reading about all the possible ways of specifying dependencies](specifying-dependencies.html) -* [Learning more details about what you can specify in your `Cargo.toml` manifest](manifest.html) - -Even more topics are available in the Docs menu at the top! diff -Nru cargo-0.25.0/src/doc/header.html cargo-0.26.0/src/doc/header.html --- cargo-0.25.0/src/doc/header.html 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/header.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,52 +0,0 @@ - - - - - - -
diff -Nru cargo-0.25.0/src/doc/html-headers.html cargo-0.26.0/src/doc/html-headers.html --- cargo-0.25.0/src/doc/html-headers.html 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/html-headers.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ - - Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/images/auth-level-acl.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/images/auth-level-acl.png differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/images/Cargo-Logo-Small.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/images/Cargo-Logo-Small.png differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/images/circle-with-i.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/images/circle-with-i.png differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/images/forkme.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/images/forkme.png differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/images/noise.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/images/noise.png differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/images/org-level-acl.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/images/org-level-acl.png differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/images/search.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/images/search.png differ diff -Nru cargo-0.25.0/src/doc/index.md cargo-0.26.0/src/doc/index.md --- cargo-0.25.0/src/doc/index.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/index.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,111 +0,0 @@ -% Cargo, Rust’s Package Manager - -# Installing - -### Install Stable Rust and Cargo - -The easiest way to get Cargo is to get the current stable release of [Rust] by -using the `rustup` script: - -```shell -$ curl -sSf https://static.rust-lang.org/rustup.sh | sh -``` - -After this, you can use the `rustup` command to also install `beta` or `nightly` -channels for Rust and Cargo. - -### Install Nightly Cargo - -To install just Cargo, the current recommended installation method is through -the official nightly builds. Note that Cargo will also require that [Rust] is -already installed on the system. - -| Platform | 64-bit | 32-bit | -|------------------|-------------------|-------------------| -| Linux binaries | [tar.gz][linux64] | [tar.gz][linux32] | -| MacOS binaries | [tar.gz][mac64] | [tar.gz][mac32] | -| Windows binaries | [tar.gz][win64] | [tar.gz][win32] | - -### Build and Install Cargo from Source - -Alternatively, you can [build Cargo from source][compiling-from-source]. - -[rust]: https://www.rust-lang.org/ -[linux64]: https://static.rust-lang.org/cargo-dist/cargo-nightly-x86_64-unknown-linux-gnu.tar.gz -[linux32]: https://static.rust-lang.org/cargo-dist/cargo-nightly-i686-unknown-linux-gnu.tar.gz -[mac64]: https://static.rust-lang.org/cargo-dist/cargo-nightly-x86_64-apple-darwin.tar.gz -[mac32]: https://static.rust-lang.org/cargo-dist/cargo-nightly-i686-apple-darwin.tar.gz -[win64]: https://static.rust-lang.org/cargo-dist/cargo-nightly-x86_64-pc-windows-gnu.tar.gz -[win32]: https://static.rust-lang.org/cargo-dist/cargo-nightly-i686-pc-windows-gnu.tar.gz -[compiling-from-source]: https://github.com/rust-lang/cargo#compiling-from-source - -# Let’s get started - -To start a new project with Cargo, use `cargo new`: - -```shell -$ cargo new hello_world --bin -``` - -We’re passing `--bin` because we’re making a binary program: if we -were making a library, we’d leave it off. - -Let’s check out what Cargo has generated for us: - -```shell -$ cd hello_world -$ tree . -. -├── Cargo.toml -└── src - └── main.rs - -1 directory, 2 files -``` - -This is all we need to get started. First, let’s check out `Cargo.toml`: - -```toml -[package] -name = "hello_world" -version = "0.1.0" -authors = ["Your Name "] -``` - -This is called a **manifest**, and it contains all of the metadata that Cargo -needs to compile your project. - -Here’s what’s in `src/main.rs`: - -``` -fn main() { - println!("Hello, world!"); -} -``` - -Cargo generated a “hello world” for us. Let’s compile it: - -```shell -$ cargo build - Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) -``` - -And then run it: - -```shell -$ ./target/debug/hello_world -Hello, world! -``` - -We can also use `cargo run` to compile and then run it, all in one step: - -```shell -$ cargo run - Fresh hello_world v0.1.0 (file:///path/to/project/hello_world) - Running `target/hello_world` -Hello, world! -``` - -# Going further - -For more details on using Cargo, check out the [Cargo Guide](guide.html) diff -Nru cargo-0.25.0/src/doc/javascripts/all.js cargo-0.26.0/src/doc/javascripts/all.js --- cargo-0.25.0/src/doc/javascripts/all.js 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/javascripts/all.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -//= require_tree . - -Prism.languages.toml = { - // https://github.com/LeaVerou/prism/issues/307 - 'comment': [{ - pattern: /(^[^"]*?("[^"]*?"[^"]*?)*?[^"\\]*?)(\/\*[\w\W]*?\*\/|(^|[^:])#.*?(\r?\n|$))/g, - lookbehind: true - }], - 'string': /("|')(\\?.)*?\1/g, - 'number': /\d+/, - 'boolean': /true|false/, - 'toml-section': /\[.*\]/, - 'toml-key': /[\w-]+/ -}; - -$(function() { - var pres = document.querySelectorAll('pre.rust'); - for (var i = 0; i < pres.length; i++) { - pres[i].className += ' language-rust'; - } - - // Toggles docs menu - $('button.dropdown, a.dropdown').click(function(el, e) { - $(this).toggleClass('active').siblings('ul').toggleClass('open'); - - return false; - }); - - // A click in the page anywhere but in the menu will turn the menu off - $(document).on('click', function(e) { - // Checks to make sure the click did not come from inside dropdown menu - // if it doesn't we close the menu - // else, we do nothing and just follow the link - if (!$(e.target).closest('ul.dropdown').length) { - var toggles = $('button.dropdown.active, a.dropdown.active'); - toggles.toggleClass('active').siblings('ul').toggleClass('open'); - - } - }); -}); diff -Nru cargo-0.25.0/src/doc/javascripts/prism.js cargo-0.26.0/src/doc/javascripts/prism.js --- cargo-0.25.0/src/doc/javascripts/prism.js 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/javascripts/prism.js 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -/* http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript */ -self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{};var Prism=function(){var e=/\blang(?:uage)?-(?!\*)(\w+)\b/i,t=self.Prism={util:{encode:function(e){return e instanceof n?new n(e.type,t.util.encode(e.content),e.alias):"Array"===t.util.type(e)?e.map(t.util.encode):e.replace(/&/g,"&").replace(/e.length)break e;if(!(d instanceof a)){c.lastIndex=0;var m=c.exec(d);if(m){u&&(f=m[1].length);var y=m.index-1+f,m=m[0].slice(f),v=m.length,k=y+v,b=d.slice(0,y+1),w=d.slice(k+1),N=[p,1];b&&N.push(b);var O=new a(l,g?t.tokenize(m,g):m,h);N.push(O),w&&N.push(w),Array.prototype.splice.apply(r,N)}}}}}return r},hooks:{all:{},add:function(e,n){var a=t.hooks.all;a[e]=a[e]||[],a[e].push(n)},run:function(e,n){var a=t.hooks.all[e];if(a&&a.length)for(var r,i=0;r=a[i++];)r(n)}}},n=t.Token=function(e,t,n){this.type=e,this.content=t,this.alias=n};if(n.stringify=function(e,a,r){if("string"==typeof e)return e;if("[object Array]"==Object.prototype.toString.call(e))return e.map(function(t){return n.stringify(t,a,e)}).join("");var i={type:e.type,content:n.stringify(e.content,a,r),tag:"span",classes:["token",e.type],attributes:{},language:a,parent:r};if("comment"==i.type&&(i.attributes.spellcheck="true"),e.alias){var l="Array"===t.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(i.classes,l)}t.hooks.run("wrap",i);var o="";for(var s in i.attributes)o+=s+'="'+(i.attributes[s]||"")+'"';return"<"+i.tag+' class="'+i.classes.join(" ")+'" '+o+">"+i.content+""},!self.document)return self.addEventListener?(self.addEventListener("message",function(e){var n=JSON.parse(e.data),a=n.language,r=n.code;self.postMessage(JSON.stringify(t.util.encode(t.tokenize(r,t.languages[a])))),self.close()},!1),self.Prism):self.Prism;var a=document.getElementsByTagName("script");return a=a[a.length-1],a&&(t.filename=a.src,document.addEventListener&&!a.hasAttribute("data-manual")&&document.addEventListener("DOMContentLoaded",t.highlightAll)),self.Prism}();"undefined"!=typeof module&&module.exports&&(module.exports=Prism);; -Prism.languages.markup={comment://g,prolog:/<\?.+?\?>/,doctype://,cdata://i,tag:{pattern:/<\/?[\w:-]+\s*(?:\s+[\w:-]+(?:=(?:("|')(\\?[\w\W])*?\1|[^\s'">=]+))?\s*)*\/?>/gi,inside:{tag:{pattern:/^<\/?[\w:-]+/i,inside:{punctuation:/^<\/?/,namespace:/^[\w-]+?:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/gi,inside:{punctuation:/=|>|"/g}},punctuation:/\/?>/g,"attr-name":{pattern:/[\w:-]+/g,inside:{namespace:/^[\w-]+?:/}}}},entity:/\&#?[\da-z]{1,8};/gi},Prism.hooks.add("wrap",function(t){"entity"===t.type&&(t.attributes.title=t.content.replace(/&/,"&"))});; -Prism.languages.css={comment:/\/\*[\w\W]*?\*\//g,atrule:{pattern:/@[\w-]+?.*?(;|(?=\s*{))/gi,inside:{punctuation:/[;:]/g}},url:/url\((["']?).*?\1\)/gi,selector:/[^\{\}\s][^\{\};]*(?=\s*\{)/g,property:/(\b|\B)[\w-]+(?=\s*:)/gi,string:/("|')(\\?.)*?\1/g,important:/\B!important\b/gi,punctuation:/[\{\};:]/g,"function":/[-a-z0-9]+(?=\()/gi},Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{style:{pattern:/[\w\W]*?<\/style>/gi,inside:{tag:{pattern:/|<\/style>/gi,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.css}}});; -Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\w\W]*?\*\//g,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*?(\r?\n|$)/g,lookbehind:!0}],string:/("|')(\\?.)*?\1/g,"class-name":{pattern:/((?:(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/gi,lookbehind:!0,inside:{punctuation:/(\.|\\)/}},keyword:/\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/g,"boolean":/\b(true|false)\b/g,"function":{pattern:/[a-z0-9_]+\(/gi,inside:{punctuation:/\(/}},number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?)\b/g,operator:/[-+]{1,2}|!|<=?|>=?|={1,3}|&{1,2}|\|?\||\?|\*|\/|\~|\^|\%/g,ignore:/&(lt|gt|amp);/gi,punctuation:/[{}[\];(),.:]/g};; -Prism.languages.javascript=Prism.languages.extend("clike",{keyword:/\b(break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|function|get|if|implements|import|in|instanceof|interface|let|new|null|package|private|protected|public|return|set|static|super|switch|this|throw|true|try|typeof|var|void|while|with|yield)\b/g,number:/\b-?(0x[\dA-Fa-f]+|\d*\.?\d+([Ee]-?\d+)?|NaN|-?Infinity)\b/g}),Prism.languages.insertBefore("javascript","keyword",{regex:{pattern:/(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,lookbehind:!0}}),Prism.languages.markup&&Prism.languages.insertBefore("markup","tag",{script:{pattern:/[\w\W]*?<\/script>/gi,inside:{tag:{pattern:/|<\/script>/gi,inside:Prism.languages.markup.tag.inside},rest:Prism.languages.javascript}}});; diff -Nru cargo-0.25.0/src/doc/manifest.md cargo-0.26.0/src/doc/manifest.md --- cargo-0.25.0/src/doc/manifest.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/manifest.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,797 +0,0 @@ -% The Manifest Format - -# The `[package]` section - -The first section in a `Cargo.toml` is `[package]`. - -```toml -[package] -name = "hello_world" # the name of the package -version = "0.1.0" # the current version, obeying semver -authors = ["you@example.com"] -``` - -All three of these fields are mandatory. - -## The `version` field - -Cargo bakes in the concept of [Semantic -Versioning](http://semver.org/), so make sure you follow some basic rules: - -* Before you reach 1.0.0, anything goes, but if you make breaking changes, - increment the minor version. In Rust, breaking changes include adding fields to - structs or variants to enums. -* After 1.0.0, only make breaking changes when you increment the major version. - Don’t break the build. -* After 1.0.0, don’t add any new public API (no new `pub` anything) in tiny - versions. Always increment the minor version if you add any new `pub` structs, - traits, fields, types, functions, methods or anything else. -* Use version numbers with three numeric parts such as 1.0.0 rather than 1.0. - -## The `build` field (optional) - -This field specifies a file in the project root which is a [build script][1] for -building native code. More information can be found in the build script -[guide][1]. - -[1]: build-script.html - -```toml -[package] -# ... -build = "build.rs" -``` - -## The `documentation` field (optional) - -This field specifies a URL to a website hosting the crate's documentation. -If no URL is specified in the manifest file, [crates.io][cratesio] will -automatically link your crate to the corresponding [docs.rs][docsrs] page. - -Documentation links from specific hosts are blacklisted. Hosts are added -to the blacklist if they are known to not be hosting documentation and are -possibly of malicious intent e.g. ad tracking networks. URLs from the -following hosts are blacklisted: - -* rust-ci.org - -Documentation URLs from blacklisted hosts will not appear on crates.io, and -may be replaced by docs.rs links. - -[docsrs]: https://docs.rs/ -[cratesio]: https://crates.io/ - -## The `exclude` and `include` fields (optional) - -You can explicitly specify to Cargo that a set of [globs][globs] should be -ignored or included for the purposes of packaging and rebuilding a package. The -globs specified in the `exclude` field identify a set of files that are not -included when a package is published as well as ignored for the purposes of -detecting when to rebuild a package, and the globs in `include` specify files -that are explicitly included. - -If a VCS is being used for a package, the `exclude` field will be seeded with -the VCS’ ignore settings (`.gitignore` for git for example). - -```toml -[package] -# ... -exclude = ["build/**/*.o", "doc/**/*.html"] -``` - -```toml -[package] -# ... -include = ["src/**/*", "Cargo.toml"] -``` - -The options are mutually exclusive: setting `include` will override an -`exclude`. Note that `include` must be an exhaustive list of files as otherwise -necessary source files may not be included. - -[globs]: http://doc.rust-lang.org/glob/glob/struct.Pattern.html - -### Migrating to `gitignore`-like pattern matching - -The current interpretation of these configs is based on UNIX Globs, as -implemented in the [`glob` crate](https://crates.io/crates/glob). We want -Cargo's `include` and `exclude` configs to work as similar to `gitignore` as -possible. [The `gitignore` specification](https://git-scm.com/docs/gitignore) is -also based on Globs, but has a bunch of additional features that enable easier -pattern writing and more control. Therefore, we are migrating the interpretation -for the rules of these configs to use the [`ignore` -crate](https://crates.io/crates/ignore), and treat them each rule as a single -line in a `gitignore` file. See [the tracking -issue](https://github.com/rust-lang/cargo/issues/4268) for more details on the -migration. - -## The `publish` field (optional) - -The `publish` field can be used to prevent a package from being published to a -package registry (like *crates.io*) by mistake. - -```toml -[package] -# ... -publish = false -``` - -## The `workspace` field (optional) - -The `workspace` field can be used to configure the workspace that this package -will be a member of. If not specified this will be inferred as the first -Cargo.toml with `[workspace]` upwards in the filesystem. - -```toml -[package] -# ... -workspace = "path/to/workspace/root" -``` - -For more information, see the documentation for the workspace table below. - -## Package metadata - -There are a number of optional metadata fields also accepted under the -`[package]` section: - -```toml -[package] -# ... - -# A short blurb about the package. This is not rendered in any format when -# uploaded to crates.io (aka this is not markdown). -description = "..." - -# These URLs point to more information about the package. These are -# intended to be webviews of the relevant data, not necessarily compatible -# with VCS tools and the like. -documentation = "..." -homepage = "..." -repository = "..." - -# This points to a file under the package root (relative to this `Cargo.toml`). -# The contents of this file are stored and indexed in the registry. -# crates.io will render this file and place the result on the crate's page. -readme = "..." - -# This is a list of up to five keywords that describe this crate. Keywords -# are searchable on crates.io, and you may choose any words that would -# help someone find this crate. -keywords = ["...", "..."] - -# This is a list of up to five categories where this crate would fit. -# Categories are a fixed list available at crates.io/category_slugs, and -# they must match exactly. -categories = ["...", "..."] - -# This is a string description of the license for this package. Currently -# crates.io will validate the license provided against a whitelist of known -# license identifiers from http://spdx.org/licenses/. Multiple licenses can be -# separated with a `/`. -license = "..." - -# If a project is using a nonstandard license, then this key may be specified in -# lieu of the above key and must point to a file relative to this manifest -# (similar to the readme key). -license-file = "..." - -# Optional specification of badges to be displayed on crates.io. -# -# - The badges pertaining to build status that are currently available are -# Appveyor, CircleCI, GitLab, and TravisCI. -# - Available badges pertaining to code test coverage are Codecov and -# Coveralls. -# - There are also maintenance-related badges basesed on isitmaintained.com -# which state the issue resolution time, percent of open issues, and future -# maintenance intentions. -# -# If a `repository` key is required, this refers to a repository in -# `user/repo` format. -[badges] - -# Appveyor: `repository` is required. `branch` is optional; default is `master` -# `service` is optional; valid values are `github` (default), `bitbucket`, and -# `gitlab`; `id` is optional; you can specify the appveyor project id if you -# want to use that instead. `project_name` is optional; use when the repository -# name differs from the appveyor project name. -appveyor = { repository = "...", branch = "master", service = "github" } - -# Circle CI: `repository` is required. `branch` is optional; default is `master` -circle-ci = { repository = "...", branch = "master" } - -# GitLab: `repository` is required. `branch` is optional; default is `master` -gitlab = { repository = "...", branch = "master" } - -# Travis CI: `repository` in format "/" is required. -# `branch` is optional; default is `master` -travis-ci = { repository = "...", branch = "master" } - -# Codecov: `repository` is required. `branch` is optional; default is `master` -# `service` is optional; valid values are `github` (default), `bitbucket`, and -# `gitlab`. -codecov = { repository = "...", branch = "master", service = "github" } - -# Coveralls: `repository` is required. `branch` is optional; default is `master` -# `service` is optional; valid values are `github` (default) and `bitbucket`. -coveralls = { repository = "...", branch = "master", service = "github" } - -# Is it maintained resolution time: `repository` is required. -is-it-maintained-issue-resolution = { repository = "..." } - -# Is it maintained percentage of open issues: `repository` is required. -is-it-maintained-open-issues = { repository = "..." } - -# Maintenance: `status` is required Available options are `actively-developed`, -# `passively-maintained`, `as-is`, `none`, `experimental`, `looking-for-maintainer` -# and `deprecated`. -maintenance = { status = "..." } -``` - -The [crates.io](https://crates.io) registry will render the description, display -the license, link to the three URLs and categorize by the keywords. These keys -provide useful information to users of the registry and also influence the -search ranking of a crate. It is highly discouraged to omit everything in a -published crate. - -## The `metadata` table (optional) - -Cargo by default will warn about unused keys in `Cargo.toml` to assist in -detecting typos and such. The `package.metadata` table, however, is completely -ignored by Cargo and will not be warned about. This section can be used for -tools which would like to store project configuration in `Cargo.toml`. For -example: - -```toml -[package] -name = "..." -# ... - -# Metadata used when generating an Android APK, for example. -[package.metadata.android] -package-name = "my-awesome-android-app" -assets = "path/to/static" -``` - -# Dependency sections - -See the [specifying dependencies page](specifying-dependencies.html) for -information on the `[dependencies]`, `[dev-dependencies]`, -`[build-dependencies]`, and target-specific `[target.*.dependencies]` sections. - -# The `[profile.*]` sections - -Cargo supports custom configuration of how rustc is invoked through profiles at -the top level. Any manifest may declare a profile, but only the top level -project’s profiles are actually read. All dependencies’ profiles will be -overridden. This is done so the top-level project has control over how its -dependencies are compiled. - -There are five currently supported profile names, all of which have the same -configuration available to them. Listed below is the configuration available, -along with the defaults for each profile. - -```toml -# The development profile, used for `cargo build`. -[profile.dev] -opt-level = 0 # controls the `--opt-level` the compiler builds with. - # 0-1 is good for debugging. 2 is well-optimized. Max is 3. -debug = true # include debug information (debug symbols). Equivalent to - # `-C debuginfo=2` compiler flag. -rpath = false # controls whether compiler should set loader paths. - # If true, passes `-C rpath` flag to the compiler. -lto = false # Link Time Optimization usually reduces size of binaries - # and static libraries. Increases compilation time. - # If true, passes `-C lto` flag to the compiler. -debug-assertions = true # controls whether debug assertions are enabled - # (e.g. debug_assert!() and arithmetic overflow checks) -codegen-units = 1 # if > 1 enables parallel code generation which improves - # compile times, but prevents some optimizations. - # Passes `-C codegen-units`. Ignored when `lto = true`. -panic = 'unwind' # panic strategy (`-C panic=...`), can also be 'abort' -incremental = true # whether or not incremental compilation is enabled - -# The release profile, used for `cargo build --release`. -[profile.release] -opt-level = 3 -debug = false -rpath = false -lto = false -debug-assertions = false -codegen-units = 1 -panic = 'unwind' -incremental = false - -# The testing profile, used for `cargo test`. -[profile.test] -opt-level = 0 -debug = 2 -rpath = false -lto = false -debug-assertions = true -codegen-units = 1 -panic = 'unwind' -incremental = true - -# The benchmarking profile, used for `cargo bench` and `cargo test --release`. -[profile.bench] -opt-level = 3 -debug = false -rpath = false -lto = false -debug-assertions = false -codegen-units = 1 -panic = 'unwind' -incremental = false - -# The documentation profile, used for `cargo doc`. -[profile.doc] -opt-level = 0 -debug = 2 -rpath = false -lto = false -debug-assertions = true -codegen-units = 1 -panic = 'unwind' -incremental = true -``` - -# The `[features]` section - -Cargo supports features to allow expression of: - -* conditional compilation options (usable through `cfg` attributes); -* optional dependencies, which enhance a package, but are not required; and -* clusters of optional dependencies, such as `postgres`, that would include the - `postgres` package, the `postgres-macros` package, and possibly other packages - (such as development-time mocking libraries, debugging tools, etc.). - -A feature of a package is either an optional dependency, or a set of other -features. The format for specifying features is: - -```toml -[package] -name = "awesome" - -[features] -# The default set of optional packages. Most people will want to use these -# packages, but they are strictly optional. Note that `session` is not a package -# but rather another feature listed in this manifest. -default = ["jquery", "uglifier", "session"] - -# A feature with no dependencies is used mainly for conditional compilation, -# like `#[cfg(feature = "go-faster")]`. -go-faster = [] - -# The `secure-password` feature depends on the bcrypt package. This aliasing -# will allow people to talk about the feature in a higher-level way and allow -# this package to add more requirements to the feature in the future. -secure-password = ["bcrypt"] - -# Features can be used to reexport features of other packages. The `session` -# feature of package `awesome` will ensure that the `session` feature of the -# package `cookie` is also enabled. -session = ["cookie/session"] - -[dependencies] -# These packages are mandatory and form the core of this package’s distribution. -cookie = "1.2.0" -oauth = "1.1.0" -route-recognizer = "=2.1.0" - -# A list of all of the optional dependencies, some of which are included in the -# above `features`. They can be opted into by apps. -jquery = { version = "1.0.2", optional = true } -uglifier = { version = "1.5.3", optional = true } -bcrypt = { version = "*", optional = true } -civet = { version = "*", optional = true } -``` - -To use the package `awesome`: - -```toml -[dependencies.awesome] -version = "1.3.5" -default-features = false # do not include the default features, and optionally - # cherry-pick individual features -features = ["secure-password", "civet"] -``` - -## Rules - -The usage of features is subject to a few rules: - -* Feature names must not conflict with other package names in the manifest. This - is because they are opted into via `features = [...]`, which only has a single - namespace. -* With the exception of the `default` feature, all features are opt-in. To opt - out of the default feature, use `default-features = false` and cherry-pick - individual features. -* Feature groups are not allowed to cyclically depend on one another. -* Dev-dependencies cannot be optional. -* Features groups can only reference optional dependencies. -* When a feature is selected, Cargo will call `rustc` with `--cfg - feature="${feature_name}"`. If a feature group is included, it and all of its - individual features will be included. This can be tested in code via - `#[cfg(feature = "foo")]`. - -Note that it is explicitly allowed for features to not actually activate any -optional dependencies. This allows packages to internally enable/disable -features without requiring a new dependency. - -## Usage in end products - -One major use-case for this feature is specifying optional features in -end-products. For example, the Servo project may want to include optional -features that people can enable or disable when they build it. - -In that case, Servo will describe features in its `Cargo.toml` and they can be -enabled using command-line flags: - -``` -$ cargo build --release --features "shumway pdf" -``` - -Default features could be excluded using `--no-default-features`. - -## Usage in packages - -In most cases, the concept of *optional dependency* in a library is best -expressed as a separate package that the top-level application depends on. - -However, high-level packages, like Iron or Piston, may want the ability to -curate a number of packages for easy installation. The current Cargo system -allows them to curate a number of mandatory dependencies into a single package -for easy installation. - -In some cases, packages may want to provide additional curation for optional -dependencies: - -* grouping a number of low-level optional dependencies together into a single - high-level feature; -* specifying packages that are recommended (or suggested) to be included by - users of the package; and -* including a feature (like `secure-password` in the motivating example) that - will only work if an optional dependency is available, and would be difficult - to implement as a separate package (for example, it may be overly difficult to - design an IO package to be completely decoupled from OpenSSL, with opt-in via - the inclusion of a separate package). - -In almost all cases, it is an antipattern to use these features outside of -high-level packages that are designed for curation. If a feature is optional, it -can almost certainly be expressed as a separate package. - -# The `[workspace]` section - -Projects can define a workspace which is a set of crates that will all share the -same `Cargo.lock` and output directory. The `[workspace]` table can be defined -as: - -```toml -[workspace] - -# Optional key, inferred from path dependencies if not present. -# Additional non-path dependencies that should be included must be given here. -# In particular, for a virtual manifest, all members have to be listed. -members = ["path/to/member1", "path/to/member2", "path/to/member3/*"] - -# Optional key, empty if not present. -exclude = ["path1", "path/to/dir2"] -``` - -Workspaces were added to Cargo as part of [RFC 1525] and have a number of -properties: - -* A workspace can contain multiple crates where one of them is the *root crate*. -* The *root crate*'s `Cargo.toml` contains the `[workspace]` table, but is not - required to have other configuration. -* Whenever any crate in the workspace is compiled, output is placed in the - *workspace root*. i.e. next to the *root crate*'s `Cargo.toml`. -* The lock file for all crates in the workspace resides in the *workspace root*. -* The `[patch]` and `[replace]` sections in `Cargo.toml` are only recognized - in the *root crate*'s manifest, and ignored in member crates' manifests. - -[RFC 1525]: https://github.com/rust-lang/rfcs/blob/master/text/1525-cargo-workspace.md - -The *root crate* of a workspace, indicated by the presence of `[workspace]` in -its manifest, is responsible for defining the entire workspace. All `path` -dependencies residing in the workspace directory become members. You can add -additional packages to the workspace by listing them in the `members` key. Note -that members of the workspaces listed explicitly will also have their path -dependencies included in the workspace. Sometimes a project may have a lot of -workspace members and it can be onerous to keep up to date. The path dependency -can also use [globs][globs] to match multiple paths. Finally, the `exclude` -key can be used to blacklist paths from being included in a workspace. This can -be useful if some path dependencies aren't desired to be in the workspace at -all. - -The `package.workspace` manifest key (described above) is used in member crates -to point at a workspace's root crate. If this key is omitted then it is inferred -to be the first crate whose manifest contains `[workspace]` upwards in the -filesystem. - -A crate may either specify `package.workspace` or specify `[workspace]`. That -is, a crate cannot both be a root crate in a workspace (contain `[workspace]`) -and also be a member crate of another workspace (contain `package.workspace`). - -Most of the time workspaces will not need to be dealt with as `cargo new` and -`cargo init` will handle workspace configuration automatically. - -## Virtual Manifest - -In workspace manifests, if the `package` table is present, the workspace root -crate will be treated as a normal package, as well as a workspace. If the -`package` table is not present in a workspace manifest, it is called a *virtual -manifest*. - -## Package selection - -In a workspace, package-related cargo commands like `cargo build` apply to -packages selected by `-p` / `--package` or `--all` command-line parameters. -When neither is specified, the optional `default-members` configuration is used: - -```toml -[workspace] -members = ["path/to/member1", "path/to/member2", "path/to/member3/*"] -default-members = ["path/to/member2", "path/to/member3/foo"] -``` - -When specified, `default-members` must expand to a subset of `members`. - -When `default-members` is not specified, the default is the root manifest -if it is a package, or every member manifest (as if `--all` were specified -on the command-line) for virtual workspaces. - -# The project layout - -If your project is an executable, name the main source file `src/main.rs`. If it -is a library, name the main source file `src/lib.rs`. - -Cargo will also treat any files located in `src/bin/*.rs` as executables. If your -executable consists of more than just one source file, you might also use a directory -inside `src/bin` containing a `main.rs` file which will be treated as an executable -with a name of the parent directory. -Do note, however, once you add a `[[bin]]` section ([see -below](#configuring-a-target)), Cargo will no longer automatically build files -located in `src/bin/*.rs`. Instead you must create a `[[bin]]` section for -each file you want to build. - -Your project can optionally contain folders named `examples`, `tests`, and -`benches`, which Cargo will treat as containing examples, -integration tests, and benchmarks respectively. Analogous to `bin` targets, they -may be composed of single files or directories with a `main.rs` file. - -```notrust -▾ src/ # directory containing source files - lib.rs # the main entry point for libraries and packages - main.rs # the main entry point for projects producing executables - ▾ bin/ # (optional) directory containing additional executables - *.rs - ▾ */ # (optional) directories containing multi-file executables - main.rs -▾ examples/ # (optional) examples - *.rs - ▾ */ # (optional) directories containing multi-file examples - main.rs -▾ tests/ # (optional) integration tests - *.rs - ▾ */ # (optional) directories containing multi-file tests - main.rs -▾ benches/ # (optional) benchmarks - *.rs - ▾ */ # (optional) directories containing multi-file benchmarks - main.rs -``` - -To structure your code after you've created the files and folders for your -project, you should remember to use Rust's module system, which you can read -about in [the book](https://doc.rust-lang.org/book/crates-and-modules.html). - -# Examples - -Files located under `examples` are example uses of the functionality provided by -the library. When compiled, they are placed in the `target/examples` directory. - -They can compile either as executables (with a `main()` function) or libraries -and pull in the library by using `extern crate `. They are -compiled when you run your tests to protect them from bitrotting. - -You can run individual executable examples with the command `cargo run --example -`. - -Specify `crate-type` to make an example be compiled as a library: - -```toml -[[example]] -name = "foo" -crate-type = ["staticlib"] -``` - -You can build individual library examples with the command `cargo build ---example `. - -# Tests - -When you run `cargo test`, Cargo will: - -* compile and run your library’s unit tests, which are in the files reachable - from `lib.rs` (naturally, any sections marked with `#[cfg(test)]` will be - considered at this stage); -* compile and run your library’s documentation tests, which are embedded inside - of documentation blocks; -* compile and run your library’s [integration tests](#integration-tests); and -* compile your library’s examples. - -## Integration tests - -Each file in `tests/*.rs` is an integration test. When you run `cargo test`, -Cargo will compile each of these files as a separate crate. The crate can link -to your library by using `extern crate `, like any other code that -depends on it. - -Cargo will not automatically compile files inside subdirectories of `tests`, but -an integration test can import modules from these directories as usual. For -example, if you want several integration tests to share some code, you can put -the shared code in `tests/common/mod.rs` and then put `mod common;` in each of -the test files. - -# Configuring a target - -All of the `[[bin]]`, `[lib]`, `[[bench]]`, `[[test]]`, and `[[example]]` -sections support similar configuration for specifying how a target should be -built. The double-bracket sections like `[[bin]]` are array-of-table of -[TOML](https://github.com/toml-lang/toml#array-of-tables), which means you can -write more than one `[[bin]]` section to make several executables in your crate. - -The example below uses `[lib]`, but it also applies to all other sections -as well. All values listed are the defaults for that option unless otherwise -specified. - -```toml -[package] -# ... - -[lib] -# The name of a target is the name of the library that will be generated. This -# is defaulted to the name of the package or project, with any dashes replaced -# with underscores. (Rust `extern crate` declarations reference this name; -# therefore the value must be a valid Rust identifier to be usable.) -name = "foo" - -# This field points at where the crate is located, relative to the `Cargo.toml`. -path = "src/lib.rs" - -# A flag for enabling unit tests for this target. This is used by `cargo test`. -test = true - -# A flag for enabling documentation tests for this target. This is only relevant -# for libraries, it has no effect on other sections. This is used by -# `cargo test`. -doctest = true - -# A flag for enabling benchmarks for this target. This is used by `cargo bench`. -bench = true - -# A flag for enabling documentation of this target. This is used by `cargo doc`. -doc = true - -# If the target is meant to be a compiler plugin, this field must be set to true -# for Cargo to correctly compile it and make it available for all dependencies. -plugin = false - -# If the target is meant to be a "macros 1.1" procedural macro, this field must -# be set to true. -proc-macro = false - -# If set to false, `cargo test` will omit the `--test` flag to rustc, which -# stops it from generating a test harness. This is useful when the binary being -# built manages the test runner itself. -harness = true -``` - -## The `required-features` field (optional) - -The `required-features` field specifies which features the target needs in order -to be built. If any of the required features are not selected, the target will -be skipped. This is only relevant for the `[[bin]]`, `[[bench]]`, `[[test]]`, -and `[[example]]` sections, it has no effect on `[lib]`. - -```toml -[features] -# ... -postgres = [] -sqlite = [] -tools = [] - -[[bin]] -# ... -required-features = ["postgres", "tools"] -``` - -# Building dynamic or static libraries - -If your project produces a library, you can specify which kind of library to -build by explicitly listing the library in your `Cargo.toml`: - -```toml -# ... - -[lib] -name = "..." -crate-type = ["dylib"] # could be `staticlib` as well -``` - -The available options are `dylib`, `rlib`, `staticlib`, `cdylib`, and -`proc-macro`. You should only use this option in a project. Cargo will always -compile packages (dependencies) based on the requirements of the project that -includes them. - -You can read more about the different crate types in the -[Rust Reference Manual](https://doc.rust-lang.org/reference/linkage.html) - -# The `[patch]` Section - -This section of Cargo.toml can be used to [override dependencies][replace] with -other copies. The syntax is similar to the `[dependencies]` section: - -```toml -[patch.crates-io] -foo = { git = 'https://github.com/example/foo' } -bar = { path = 'my/local/bar' } - -[dependencies.baz] -git = 'https://github.com/example/baz' - -[patch.'https://github.com/example/baz'] -baz = { git = 'https://github.com/example/patched-baz', branch = 'my-branch' } -``` - -The `[patch]` table is made of dependency-like sub-tables. Each key after -`[patch]` is a URL of the source that's being patched, or `crates-io` if -you're modifying the https://crates.io registry. In the example above -`crates-io` could be replaced with a git URL such as -`https://github.com/rust-lang-nursery/log`; the second `[patch]` -section in the example uses this to specify a source called `baz`. - -Each entry in these tables is a normal dependency specification, the same as -found in the `[dependencies]` section of the manifest. The dependencies listed -in the `[patch]` section are resolved and used to patch the source at the -URL specified. The above manifest snippet patches the `crates-io` source (e.g. -crates.io itself) with the `foo` crate and `bar` crate. It also -patches the `https://github.com/example/baz` source with a `my-branch` that -comes from elsewhere. - -Sources can be patched with versions of crates that do not exist, and they can -also be patched with versions of crates that already exist. If a source is -patched with a crate version that already exists in the source, then the -source's original crate is replaced. - -More information about overriding dependencies can be found in the [overriding -dependencies][replace] section of the documentation and [RFC 1969] for the -technical specification of this feature. Note that the `[patch]` feature will -first become available in Rust 1.21, set to be released on 2017-10-12. - -[RFC 1969]: https://github.com/rust-lang/rfcs/pull/1969 -[replace]: specifying-dependencies.html#overriding-dependencies - -# The `[replace]` Section - -This section of Cargo.toml can be used to [override dependencies][replace] with -other copies. The syntax is similar to the `[dependencies]` section: - -```toml -[replace] -"foo:0.1.0" = { git = 'https://github.com/example/foo' } -"bar:1.0.2" = { path = 'my/local/bar' } -``` - -Each key in the `[replace]` table is a [package id -specification](pkgid-spec.html) which allows arbitrarily choosing a node in the -dependency graph to override. The value of each key is the same as the -`[dependencies]` syntax for specifying dependencies, except that you can't -specify features. Note that when a crate is overridden the copy it's overridden -with must have both the same name and version, but it can come from a different -source (e.g. git or a local path). - -More information about overriding dependencies can be found in the [overriding -dependencies][replace] section of the documentation. diff -Nru cargo-0.25.0/src/doc/MIGRATION_MAP cargo-0.26.0/src/doc/MIGRATION_MAP --- cargo-0.25.0/src/doc/MIGRATION_MAP 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/MIGRATION_MAP 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -index.md book/src/index.md book/src/getting-started/index.md book/src/getting-started/*.md -guide.md book/src/guide/index.md book/src/guide/*.md -build-script.md book/src/reference/build-scripts.md -config.md book/src/reference/config.md -crates-io.md book/src/reference/publishing.md -environment-variables.md book/src/reference/environment-variables.md -external-tools.md book/src/reference/external-tools.md -manifest.md book/src/reference/manifest.md -pkgid-spec.md book/src/reference/pkgid-spec.md -source-replacement.md book/src/reference/source-replacement.md -specifying-dependencies.md book/src/reference/specifying-dependencies.md -faq.md book/src/faq.md diff -Nru cargo-0.25.0/src/doc/pkgid-spec.md cargo-0.26.0/src/doc/pkgid-spec.md --- cargo-0.25.0/src/doc/pkgid-spec.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/pkgid-spec.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -% Package ID Specifications - -# Package ID specifications - -Subcommands of Cargo frequently need to refer to a particular package within a -dependency graph for various operations like updating, cleaning, building, etc. -To solve this problem, Cargo supports Package ID Specifications. A specification -is a string which is used to uniquely refer to one package within a graph of -packages. - -## Specification grammar - -The formal grammar for a Package Id Specification is: - -```notrust -pkgid := pkgname - | [ proto "://" ] hostname-and-path [ "#" ( pkgname | semver ) ] -pkgname := name [ ":" semver ] - -proto := "http" | "git" | ... -``` - -Here, brackets indicate that the contents are optional. - -## Example specifications - -These could all be references to a package `foo` version `1.2.3` from the -registry at `crates.io` - -| pkgid | name | version | url | -|:-----------------------------|:-----:|:-------:|:----------------------:| -| `foo` | `foo` | `*` | `*` | -| `foo:1.2.3` | `foo` | `1.2.3` | `*` | -| `crates.io/foo` | `foo` | `*` | `*://crates.io/foo` | -| `crates.io/foo#1.2.3` | `foo` | `1.2.3` | `*://crates.io/foo` | -| `crates.io/bar#foo:1.2.3` | `foo` | `1.2.3` | `*://crates.io/bar` | -| `http://crates.io/foo#1.2.3` | `foo` | `1.2.3` | `http://crates.io/foo` | - -## Brevity of specifications - -The goal of this is to enable both succinct and exhaustive syntaxes for -referring to packages in a dependency graph. Ambiguous references may refer to -one or more packages. Most commands generate an error if more than one package -could be referred to with the same specification. diff -Nru cargo-0.25.0/src/doc/policies.html cargo-0.26.0/src/doc/policies.html --- cargo-0.25.0/src/doc/policies.html 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/policies.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ - - - - - - - - Redirecting to https://crates.io/policies... - - diff -Nru cargo-0.25.0/src/doc/README.md cargo-0.26.0/src/doc/README.md --- cargo-0.25.0/src/doc/README.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/README.md 2018-02-26 21:17:55.000000000 +0000 @@ -1,6 +1,47 @@ -# Cargo Documentation +# The Cargo Book -NOTE: Cargo documentation is under migration to mdBook-based structure. All the -`*.md` files here shall be kept in sync with the `*.md` files under `book/src/`. -See `MIGRATION_MAP` file here and -for details. + +### Requirements + +Building the book requires [mdBook]. To get it: + +[mdBook]: https://github.com/azerupi/mdBook + +```console +$ cargo install mdbook +``` + +### Building + +To build the book: + +```console +$ mdbook build +``` + +The output will be in the `book` subdirectory. To check it out, open it in +your web browser. + +_Firefox:_ +```console +$ firefox book/index.html # Linux +$ open -a "Firefox" book/index.html # OS X +$ Start-Process "firefox.exe" .\book\index.html # Windows (PowerShell) +$ start firefox.exe .\book\index.html # Windows (Cmd) +``` + +_Chrome:_ +```console +$ google-chrome book/index.html # Linux +$ open -a "Google Chrome" book/index.html # OS X +$ Start-Process "chrome.exe" .\book\index.html # Windows (PowerShell) +$ start chrome.exe .\book\index.html # Windows (Cmd) +``` + + +## Contributing + +Given that the book is still in a draft state, we'd love your help! Please feel free to open +issues about anything, and send in PRs for things you'd like to fix or change. If your change is +large, please open an issue first, so we can make sure that it's something we'd accept before you +go through the work of getting a PR together. diff -Nru cargo-0.25.0/src/doc/source-replacement.md cargo-0.26.0/src/doc/source-replacement.md --- cargo-0.25.0/src/doc/source-replacement.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/source-replacement.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,134 +0,0 @@ -% Replacing sources - -Cargo supports the ability to **replace one source with another** to express -strategies along the lines of mirrors or vendoring dependencies. Configuration -is currently done through the [`.cargo/config` configuration][config] mechanism, -like so: - -[config]: config.html - -```toml -# The `source` table is where all keys related to source-replacement -# are stored. -[source] - -# Under the `source` table are a number of other tables whose keys are a -# name for the relevant source. For example this section defines a new -# source, called `my-awesome-source`, which comes from a directory -# located at `vendor` relative to the directory containing this `.cargo/config` -# file -[source.my-awesome-source] -directory = "vendor" - -# The crates.io default source for crates is available under the name -# "crates-io", and here we use the `replace-with` key to indicate that it's -# replaced with our source above. -[source.crates-io] -replace-with = "my-awesome-source" -``` - -With this configuration Cargo attempts to look up all crates in the directory -"vendor" rather than querying the online registry at crates.io. Using source -replacement Cargo can express: - -* Vendoring - custom sources can be defined which represent crates on the local - filesystem. These sources are subsets of the source that they're replacing and - can be checked into projects if necessary. - -* Mirroring - sources can be replaced with an equivalent version which acts as a - cache for crates.io itself. - -Cargo has a core assumption about source replacement that the source code is -exactly the same from both sources. In our above example Cargo assumes that all -of the crates coming from `my-awesome-source` are the exact same as the copies -from `crates-io`. Note that this also means that `my-awesome-source` is not -allowed to have crates which are not present in the `crates-io` source. - -As a consequence, source replacement is not appropriate for situations such as -patching a dependency or a private registry. Cargo supports patching -dependencies through the usage of [the `[replace]` key][replace-section], and -private registry support is planned for a future version of Cargo. - -[replace-section]: manifest.html#the-replace-section - -## Configuration - -Configuration of replacement sources is done through [`.cargo/config`][config] -and the full set of available keys are: - -```toml -# Each source has its own table where the key is the name of the source -[source.the-source-name] - -# Indicate that `the-source-name` will be replaced with `another-source`, -# defined elsewhere -replace-with = "another-source" - -# Available kinds of sources that can be specified (described below) -registry = "https://example.com/path/to/index" -local-registry = "path/to/registry" -directory = "path/to/vendor" - -# Git sources can optionally specify a branch/tag/rev as well -git = "https://example.com/path/to/repo" -# branch = "master" -# tag = "v1.0.1" -# rev = "313f44e8" -``` - -The `crates-io` represents the crates.io online registry (default source of -crates) and can be replaced with: - -```toml -[source.crates-io] -replace-with = 'another-source' -``` - -## Registry Sources - -A "registry source" is one that is the same as crates.io itself. That is, it has -an index served in a git repository which matches the format of the -[crates.io index](https://github.com/rust-lang/crates.io-index). That repository -then has configuration indicating where to download crates from. - -Currently there is not an already-available project for setting up a mirror of -crates.io. Stay tuned though! - -## Local Registry Sources - -A "local registry source" is intended to be a subset of another registry -source, but available on the local filesystem (aka vendoring). Local registries -are downloaded ahead of time, typically sync'd with a `Cargo.lock`, and are -made up of a set of `*.crate` files and an index like the normal registry is. - -The primary way to manage and crate local registry sources is through the -[`cargo-local-registry`][cargo-local-registry] subcommand, available on -crates.io and can be installed with `cargo install cargo-local-registry`. - -[cargo-local-registry]: https://crates.io/crates/cargo-local-registry - -Local registries are contained within one directory and contain a number of -`*.crate` files downloaded from crates.io as well as an `index` directory with -the same format as the crates.io-index project (populated with just entries for -the crates that are present). - -## Directory Sources - -A "directory source" is similar to a local registry source where it contains a -number of crates available on the local filesystem, suitable for vendoring -dependencies. Also like local registries, directory sources can primarily be -managed by an external subcommand, [`cargo-vendor`][cargo-vendor], which can be -installed with `cargo install cargo-vendor`. - -[cargo-vendor]: https://crates.io/crates/cargo-vendor - -Directory sources are distinct from local registries though in that they contain -the unpacked version of `*.crate` files, making it more suitable in some -situations to check everything into source control. A directory source is just a -directory containing a number of other directories which contain the source code -for crates (the unpacked version of `*.crate` files). Currently no restriction -is placed on the name of each directory. - -Each crate in a directory source also has an associated metadata file indicating -the checksum of each file in the crate to protect against accidental -modifications. diff -Nru cargo-0.25.0/src/doc/specifying-dependencies.md cargo-0.26.0/src/doc/specifying-dependencies.md --- cargo-0.25.0/src/doc/specifying-dependencies.md 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/specifying-dependencies.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,525 +0,0 @@ -% Specifying Dependencies - -Your crates can depend on other libraries from [crates.io], `git` repositories, or -subdirectories on your local file system. You can also temporarily override the -location of a dependency— for example, to be able to test out a bug fix in the -dependency that you are working on locally. You can have different -dependencies for different platforms, and dependencies that are only used during -development. Let's take a look at how to do each of these. - -# Specifying dependencies from crates.io - -Cargo is configured to look for dependencies on [crates.io] by default. Only -the name and a version string are required in this case. In [the cargo -guide](guide.html), we specified a dependency on the `time` crate: - -```toml -[dependencies] -time = "0.1.12" -``` - -The string `"0.1.12"` is a [semver] version requirement. Since this -string does not have any operators in it, it is interpreted the same way as -if we had specified `"^0.1.12"`, which is called a caret requirement. - -[semver]: https://github.com/steveklabnik/semver#requirements - -## Caret requirements - -**Caret requirements** allow SemVer compatible updates to a specified version. -An update is allowed if the new version number does not modify the left-most -non-zero digit in the major, minor, patch grouping. In this case, if we ran -`cargo update -p time`, cargo would update us to version `0.1.13` if it was -available, but would not update us to `0.2.0`. If instead we had specified the -version string as `^1.0`, cargo would update to `1.1` but not `2.0`. `0.0.x` is -not considered compatible with any other version. - -Here are some more examples of caret requirements and the versions that would -be allowed with them: - -```notrust -^1.2.3 := >=1.2.3 <2.0.0 -^1.2 := >=1.2.0 <2.0.0 -^1 := >=1.0.0 <2.0.0 -^0.2.3 := >=0.2.3 <0.3.0 -^0.0.3 := >=0.0.3 <0.0.4 -^0.0 := >=0.0.0 <0.1.0 -^0 := >=0.0.0 <1.0.0 -``` - -This compatibility convention is different from SemVer in the way it treats -versions before 1.0.0. While SemVer says there is no compatibility before -1.0.0, Cargo considers `0.x.y` to be compatible with `0.x.z`, where `y ≥ z` -and `x > 0`. - -## Tilde requirements - -**Tilde requirements** specify a minimal version with some ability to update. -If you specify a major, minor, and patch version or only a major and minor -version, only patch-level changes are allowed. If you only specify a major -version, then minor- and patch-level changes are allowed. - -`~1.2.3` is an example of a tilde requirement. - -```notrust -~1.2.3 := >=1.2.3 <1.3.0 -~1.2 := >=1.2.0 <1.3.0 -~1 := >=1.0.0 <2.0.0 -``` - -## Wildcard requirements - -**Wildcard requirements** allow for any version where the wildcard is -positioned. - -`*`, `1.*` and `1.2.*` are examples of wildcard requirements. - -```notrust -* := >=0.0.0 -1.* := >=1.0.0 <2.0.0 -1.2.* := >=1.2.0 <1.3.0 -``` - -## Inequality requirements - -**Inequality requirements** allow manually specifying a version range or an -exact version to depend on. - -Here are some examples of inequality requirements: - -```notrust ->= 1.2.0 -> 1 -< 2 -= 1.2.3 -``` - -## Multiple requirements - -Multiple version requirements can also be separated with a comma, e.g. `>= 1.2, -< 1.5`. - -# Specifying dependencies from `git` repositories - -To depend on a library located in a `git` repository, the minimum information -you need to specify is the location of the repository with the `git` key: - -```toml -[dependencies] -rand = { git = "https://github.com/rust-lang-nursery/rand" } -``` - -Cargo will fetch the `git` repository at this location then look for a -`Cargo.toml` for the requested crate anywhere inside the `git` repository -(not necessarily at the root). - -Since we haven’t specified any other information, Cargo assumes that -we intend to use the latest commit on the `master` branch to build our project. -You can combine the `git` key with the `rev`, `tag`, or `branch` keys to -specify something else. Here's an example of specifying that you want to use -the latest commit on a branch named `next`: - -```toml -[dependencies] -rand = { git = "https://github.com/rust-lang-nursery/rand", branch = "next" } -``` - -# Specifying path dependencies - -Over time, our `hello_world` project from [the guide](guide.html) has grown -significantly in size! It’s gotten to the point that we probably want to -split out a separate crate for others to use. To do this Cargo supports -**path dependencies** which are typically sub-crates that live within one -repository. Let’s start off by making a new crate inside of our `hello_world` -project: - -```shell -# inside of hello_world/ -$ cargo new hello_utils -``` - -This will create a new folder `hello_utils` inside of which a `Cargo.toml` and -`src` folder are ready to be configured. In order to tell Cargo about this, open -up `hello_world/Cargo.toml` and add `hello_utils` to your dependencies: - -```toml -[dependencies] -hello_utils = { path = "hello_utils" } -``` - -This tells Cargo that we depend on a crate called `hello_utils` which is found -in the `hello_utils` folder (relative to the `Cargo.toml` it’s written in). - -And that’s it! The next `cargo build` will automatically build `hello_utils` and -all of its own dependencies, and others can also start using the crate as well. -However, crates that use dependencies specified with only a path are not -permitted on [crates.io]. If we wanted to publish our `hello_world` crate, we -would need to publish a version of `hello_utils` to [crates.io](https://crates.io) -and specify its version in the dependencies line as well: - -```toml -[dependencies] -hello_utils = { path = "hello_utils", version = "0.1.0" } -``` - -# Overriding dependencies - -There are a number of methods in Cargo to support overriding dependencies and -otherwise controlling the dependency graph. These options are typically, though, -only available at the workspace level and aren't propagated through -dependencies. In other words, "applications" have the ability to override -dependencies but "libraries" do not. - -The desire to override a dependency or otherwise alter some dependencies can -arise through a number of scenarios. Most of them, however, boil down to the -ability to work with a crate before it's been published to crates.io. For -example: - -* A crate you're working on is also used in a much larger application you're - working on, and you'd like to test a bug fix to the library inside of the - larger application. -* An upstream crate you don't work on has a new feature or a bug fix on the - master branch of its git repository which you'd like to test out. -* You're about to publish a new major version of your crate, but you'd like to - do integration testing across an entire project to ensure the new major - version works. -* You've submitted a fix to an upstream crate for a bug you found, but you'd - like to immediately have your application start depending on the fixed version - of the crate to avoid blocking on the bug fix getting merged. - -These scenarios are currently all solved with the [`[patch]` manifest -section][patch-section]. (Note that the `[patch]` feature will first become -available in Rust 1.21, set to be released on 2017-10-12.) Historically some of -these scenarios have been solved with [the `[replace]` section][replace-section], -but we'll document the `[patch]` section here. - -[patch-section]: manifest.html#the-patch-section -[replace-section]: manifest.html#the-replace-section - -### Testing a bugfix - -Let's say you're working with the [`uuid`] crate but while you're working on it -you discover a bug. You are, however, quite enterprising so you decide to also -try out to fix the bug! Originally your manifest will look like: - -[`uuid`](https://crates.io/crates/uuid) - -```toml -[package] -name = "my-library" -version = "0.1.0" -authors = ["..."] - -[dependencies] -uuid = "1.0" -``` - -First thing we'll do is to clone the [`uuid` repository][uuid-repository] -locally via: - -```shell -$ git clone https://github.com/rust-lang-nursery/uuid -``` - -Next we'll edit the manifest of `my-library` to contain: - -```toml -[patch.crates-io] -uuid = { path = "../path/to/uuid" } -``` - -Here we declare that we're *patching* the source `crates-io` with a new -dependency. This will effectively add the local checked out version of `uuid` to -the crates.io registry for our local project. - -Next up we need to ensure that our lock file is updated to use this new version -of `uuid` so our project uses the locally checked out copy instead of one from -crates.io. The way `[patch]` works is that it'll load the dependency at -`../path/to/uuid` and then whenever crates.io is queried for versions of `uuid` -it'll *also* return the local version. - -This means that the version number of the local checkout is significant and will -affect whether the patch is used. Our manifest declared `uuid = "1.0"` which -means we'll only resolve to `>= 1.0.0, < 2.0.0`, and Cargo's greedy resolution -algorithm also means that we'll resolve to the maximum version within that -range. Typically this doesn't matter as the version of the git repository will -already be greater or match the maximum version published on crates.io, but it's -important to keep this in mind! - -In any case, typically all you need to do now is: - -```shell -$ cargo build - Compiling uuid v1.0.0 (file://.../uuid) - Compiling my-library v0.1.0 (file://.../my-library) - Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs -``` - -And that's it! You're now building with the local version of `uuid` (note the -`file://` in the build output). If you don't see the `file://` version getting -built then you may need to run `cargo update -p uuid --precise $version` where -`$version` is the version of the locally checked out copy of `uuid`. - -Once you've fixed the bug you originally found the next thing you'll want to do -is to likely submit that as a pull request to the `uuid` crate itself. Once -you've done this then you can also update the `[patch]` section. The listing -inside of `[patch]` is just like the `[dependencies]` section, so once your pull -request is merged you could change your `path` dependency to: - -```toml -[patch.crates-io] -uuid = { git = 'https://github.com/rust-lang-nursery/uuid' } -``` - -[uuid-repository]: https://github.com/rust-lang-nursery/uuid - -### Working with an unpublished minor version - -Let's now shift gears a bit from bug fixes to adding features. While working on -`my-library` you discover that a whole new feature is needed in the `uuid` -crate. You've implemented this feature, tested it locally above with `[patch]`, -and submitted a pull request. Let's go over how you continue to use and test it -before it's actually published. - -Let's also say that the current version of `uuid` on crates.io is `1.0.0`, but -since then the master branch of the git repository has updated to `1.0.1`. This -branch includes your new feature you submitted previously. To use this -repository we'll edit our `Cargo.toml` to look like - -```toml -[package] -name = "my-library" -version = "0.1.0" -authors = ["..."] - -[dependencies] -uuid = "1.0.1" - -[patch.crates-io] -uuid = { git = 'https://github.com/rust-lang-nursery/uuid' } -``` - -Note that our local dependency on `uuid` has been updated to `1.0.1` as it's -what we'll actually require once the crate is published. This version doesn't -exist on crates.io, though, so we provide it with the `[patch]` section of the -manifest. - -Now when our library is built it'll fetch `uuid` from the git repository and -resolve to 1.0.1 inside the repository instead of trying to download a version -from crates.io. Once 1.0.1 is published on crates.io the `[patch]` section can -be deleted. - -It's also worth nothing that `[patch]` applies *transitively*. Let's say you use -`my-library` in a larger project, such as: - -```toml -[package] -name = "my-binary" -version = "0.1.0" -authors = ["..."] - -[dependencies] -my-library = { git = 'https://example.com/git/my-library' } -uuid = "1.0" - -[patch.crates-io] -uuid = { git = 'https://github.com/rust-lang-nursery/uuid' } -``` - -Remember that `[patch]` is only applicable at the *top level* so we consumers of -`my-library` have to repeat the `[patch]` section if necessary. Here, though, -the new `uuid` crate applies to *both* our dependency on `uuid` and the -`my-library -> uuid` dependency. The `uuid` crate will be resolved to one -version for this entire crate graph, 1.0.1, and it'll be pulled from the git -repository. - -### Prepublishing a breaking change - -As a final scenario, let's take a look at working with a new major version of a -crate, typically accompanied with breaking changes. Sticking with our previous -crates, this means that we're going to be creating version 2.0.0 of the `uuid` -crate. After we've submitted all changes upstream we can update our manifest for -`my-library` to look like: - -```toml -[dependencies] -uuid = "2.0" - -[patch.crates-io] -uuid = { git = "https://github.com/rust-lang-nursery/uuid", branch = "2.0.0" } -``` - -And that's it! Like with the previous example the 2.0.0 version doesn't actually -exist on crates.io but we can still put it in through a git dependency through -the usage of the `[patch]` section. As a thought exercise let's take another -look at the `my-binary` manifest from above again as well: - -```toml -[package] -name = "my-binary" -version = "0.1.0" -authors = ["..."] - -[dependencies] -my-library = { git = 'https://example.com/git/my-library' } -uuid = "1.0" - -[patch.crates-io] -uuid = { git = 'https://github.com/rust-lang-nursery/uuid', version = '2.0.0' } -``` - -Note that this will actually resolve to two versions of the `uuid` crate. The -`my-binary` crate will continue to use the 1.x.y series of the `uuid` crate but -the `my-library` crate will use the 2.0.0 version of `uuid`. This will allow you -to gradually roll out breaking changes to a crate through a dependency graph -without being force to update everything all at once. - -### Overriding with local dependencies - -Sometimes you're only temporarily working on a crate and you don't want to have -to modify `Cargo.toml` like with the `[patch]` section above. For this use -case Cargo offers a much more limited version of overrides called **path -overrides**. - -Path overrides are specified through `.cargo/config` instead of `Cargo.toml`, -and you can find [more documentation about this configuration][config-docs]. -Inside of `.cargo/config` you'll specify a key called `paths`: - -[config-docs]: config.html - -```toml -paths = ["/path/to/uuid"] -``` - -This array should be filled with directories that contain a `Cargo.toml`. In -this instance, we’re just adding `uuid`, so it will be the only one that’s -overridden. This path can be either absolute or relative to the directory that -contains the `.cargo` folder. - -Path overrides are more restricted than the `[patch]` section, however, in -that they cannot change the structure of the dependency graph. When a -path replacement is used then the previous set of dependencies -must all match exactly to the new `Cargo.toml` specification. For example this -means that path overrides cannot be used to test out adding a dependency to a -crate, instead `[patch]` must be used in that situation. As a result usage of a -path override is typically isolated to quick bug fixes rather than larger -changes. - -Note: using a local configuration to override paths will only work for crates -that have been published to [crates.io]. You cannot use this feature to tell -Cargo how to find local unpublished crates. - -# Platform specific dependencies - - -Platform-specific dependencies take the same format, but are listed under a -`target` section. Normally Rust-like `#[cfg]` syntax will be used to define -these sections: - -```toml -[target.'cfg(windows)'.dependencies] -winhttp = "0.4.0" - -[target.'cfg(unix)'.dependencies] -openssl = "1.0.1" - -[target.'cfg(target_arch = "x86")'.dependencies] -native = { path = "native/i686" } - -[target.'cfg(target_arch = "x86_64")'.dependencies] -native = { path = "native/x86_64" } -``` - -Like with Rust, the syntax here supports the `not`, `any`, and `all` operators -to combine various cfg name/value pairs. Note that the `cfg` syntax has only -been available since Cargo 0.9.0 (Rust 1.8.0). - -In addition to `#[cfg]` syntax, Cargo also supports listing out the full target -the dependencies would apply to: - -```toml -[target.x86_64-pc-windows-gnu.dependencies] -winhttp = "0.4.0" - -[target.i686-unknown-linux-gnu.dependencies] -openssl = "1.0.1" -``` - -If you’re using a custom target specification, quote the full path and file -name: - -```toml -[target."x86_64/windows.json".dependencies] -winhttp = "0.4.0" - -[target."i686/linux.json".dependencies] -openssl = "1.0.1" -native = { path = "native/i686" } - -[target."x86_64/linux.json".dependencies] -openssl = "1.0.1" -native = { path = "native/x86_64" } -``` - -# Development dependencies - -You can add a `[dev-dependencies]` section to your `Cargo.toml` whose format -is equivalent to `[dependencies]`: - -```toml -[dev-dependencies] -tempdir = "0.3" -``` - -Dev-dependencies are not used when compiling -a package for building, but are used for compiling tests, examples, and -benchmarks. - -These dependencies are *not* propagated to other packages which depend on this -package. - -You can also have target-specific development dependencies by using -`dev-dependencies` in the target section header instead of `dependencies`. For -example: - -```toml -[target.'cfg(unix)'.dev-dependencies] -mio = "0.0.1" -``` - -[crates.io]: https://crates.io/ - -# Build dependencies - -You can depend on other Cargo-based crates for use in your build scripts. -Dependencies are declared through the `build-dependencies` section of the -manifest: - -```toml -[build-dependencies] -gcc = "0.3" -``` - -The build script **does not** have access to the dependencies listed -in the `dependencies` or `dev-dependencies` section. Build -dependencies will likewise not be available to the package itself -unless listed under the `dependencies` section as well. A package -itself and its build script are built separately, so their -dependencies need not coincide. Cargo is kept simpler and cleaner by -using independent dependencies for independent purposes. - -# Choosing features - -If a package you depend on offers conditional features, you can -specify which to use: - -```toml -[dependencies.awesome] -version = "1.3.5" -default-features = false # do not include the default features, and optionally - # cherry-pick individual features -features = ["secure-password", "civet"] -``` - -More information about features can be found in the -[manifest documentation](manifest.html#the-features-section). diff -Nru cargo-0.25.0/src/doc/src/faq.md cargo-0.26.0/src/doc/src/faq.md --- cargo-0.25.0/src/doc/src/faq.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/faq.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,193 @@ +## Frequently Asked Questions + +### Is the plan to use GitHub as a package repository? + +No. The plan for Cargo is to use [crates.io], like npm or Rubygems do with +npmjs.org and rubygems.org. + +We plan to support git repositories as a source of packages forever, +because they can be used for early development and temporary patches, +even when people use the registry as the primary source of packages. + +### Why build crates.io rather than use GitHub as a registry? + +We think that it’s very important to support multiple ways to download +packages, including downloading from GitHub and copying packages into +your project itself. + +That said, we think that [crates.io] offers a number of important benefits, and +will likely become the primary way that people download packages in Cargo. + +For precedent, both Node.js’s [npm][1] and Ruby’s [bundler][2] support both a +central registry model as well as a Git-based model, and most packages +are downloaded through the registry in those ecosystems, with an +important minority of packages making use of git-based packages. + +[1]: https://www.npmjs.org +[2]: https://bundler.io + +Some of the advantages that make a central registry popular in other +languages include: + +* **Discoverability**. A central registry provides an easy place to look + for existing packages. Combined with tagging, this also makes it + possible for a registry to provide ecosystem-wide information, such as a + list of the most popular or most-depended-on packages. +* **Speed**. A central registry makes it possible to easily fetch just + the metadata for packages quickly and efficiently, and then to + efficiently download just the published package, and not other bloat + that happens to exist in the repository. This adds up to a significant + improvement in the speed of dependency resolution and fetching. As + dependency graphs scale up, downloading all of the git repositories bogs + down fast. Also remember that not everybody has a high-speed, + low-latency Internet connection. + +### Will Cargo work with C code (or other languages)? + +Yes! + +Cargo handles compiling Rust code, but we know that many Rust projects +link against C code. We also know that there are decades of tooling +built up around compiling languages other than Rust. + +Our solution: Cargo allows a package to [specify a script](reference/build-scripts.html) +(written in Rust) to run before invoking `rustc`. Rust is leveraged to +implement platform-specific configuration and refactor out common build +functionality among packages. + +### Can Cargo be used inside of `make` (or `ninja`, or ...) + +Indeed. While we intend Cargo to be useful as a standalone way to +compile Rust projects at the top-level, we know that some people will +want to invoke Cargo from other build tools. + +We have designed Cargo to work well in those contexts, paying attention +to things like error codes and machine-readable output modes. We still +have some work to do on those fronts, but using Cargo in the context of +conventional scripts is something we designed for from the beginning and +will continue to prioritize. + +### Does Cargo handle multi-platform projects or cross-compilation? + +Rust itself provides facilities for configuring sections of code based +on the platform. Cargo also supports [platform-specific +dependencies][target-deps], and we plan to support more per-platform +configuration in `Cargo.toml` in the future. + +[target-deps]: reference/specifying-dependencies.html#platform-specific-dependencies + +In the longer-term, we’re looking at ways to conveniently cross-compile +projects using Cargo. + +### Does Cargo support environments, like `production` or `test`? + +We support environments through the use of [profiles][profile] to support: + +[profile]: reference/manifest.html#the-profile-sections + +* environment-specific flags (like `-g --opt-level=0` for development + and `--opt-level=3` for production). +* environment-specific dependencies (like `hamcrest` for test assertions). +* environment-specific `#[cfg]` +* a `cargo test` command + +### Does Cargo work on Windows? + +Yes! + +All commits to Cargo are required to pass the local test suite on Windows. +If, however, you find a Windows issue, we consider it a bug, so [please file an +issue][3]. + +[3]: https://github.com/rust-lang/cargo/issues + +### Why do binaries have `Cargo.lock` in version control, but not libraries? + +The purpose of a `Cargo.lock` is to describe the state of the world at the time +of a successful build. It is then used to provide deterministic builds across +whatever machine is building the project by ensuring that the exact same +dependencies are being compiled. + +This property is most desirable from applications and projects which are at the +very end of the dependency chain (binaries). As a result, it is recommended that +all binaries check in their `Cargo.lock`. + +For libraries the situation is somewhat different. A library is not only used by +the library developers, but also any downstream consumers of the library. Users +dependent on the library will not inspect the library’s `Cargo.lock` (even if it +exists). This is precisely because a library should **not** be deterministically +recompiled for all users of the library. + +If a library ends up being used transitively by several dependencies, it’s +likely that just a single copy of the library is desired (based on semver +compatibility). If all libraries were to check in their `Cargo.lock`, then +multiple copies of the library would be used, and perhaps even a version +conflict. + +In other words, libraries specify semver requirements for their dependencies but +cannot see the full picture. Only end products like binaries have a full +picture to decide what versions of dependencies should be used. + +### Can libraries use `*` as a version for their dependencies? + +**As of January 22nd, 2016, [crates.io] rejects all packages (not just libraries) +with wildcard dependency constraints.** + +While libraries _can_, strictly speaking, they should not. A version requirement +of `*` says “This will work with every version ever,” which is never going +to be true. Libraries should always specify the range that they do work with, +even if it’s something as general as “every 1.x.y version.” + +### Why `Cargo.toml`? + +As one of the most frequent interactions with Cargo, the question of why the +configuration file is named `Cargo.toml` arises from time to time. The leading +capital-`C` was chosen to ensure that the manifest was grouped with other +similar configuration files in directory listings. Sorting files often puts +capital letters before lowercase letters, ensuring files like `Makefile` and +`Cargo.toml` are placed together. The trailing `.toml` was chosen to emphasize +the fact that the file is in the [TOML configuration +format](https://github.com/toml-lang/toml). + +Cargo does not allow other names such as `cargo.toml` or `Cargofile` to +emphasize the ease of how a Cargo repository can be identified. An option of +many possible names has historically led to confusion where one case was handled +but others were accidentally forgotten. + +[crates.io]: https://crates.io/ + +### How can Cargo work offline? + +Cargo is often used in situations with limited or no network access such as +airplanes, CI environments, or embedded in large production deployments. Users +are often surprised when Cargo attempts to fetch resources from the network, and +hence the request for Cargo to work offline comes up frequently. + +Cargo, at its heart, will not attempt to access the network unless told to do +so. That is, if no crates comes from crates.io, a git repository, or some other +network location, Cargo will never attempt to make a network connection. As a +result, if Cargo attempts to touch the network, then it's because it needs to +fetch a required resource. + +Cargo is also quite aggressive about caching information to minimize the amount +of network activity. It will guarantee, for example, that if `cargo build` (or +an equivalent) is run to completion then the next `cargo build` is guaranteed to +not touch the network so long as `Cargo.toml` has not been modified in the +meantime. This avoidance of the network boils down to a `Cargo.lock` existing +and a populated cache of the crates reflected in the lock file. If either of +these components are missing, then they're required for the build to succeed and +must be fetched remotely. + +As of Rust 1.11.0 Cargo understands a new flag, `--frozen`, which is an +assertion that it shouldn't touch the network. When passed, Cargo will +immediately return an error if it would otherwise attempt a network request. +The error should include contextual information about why the network request is +being made in the first place to help debug as well. Note that this flag *does +not change the behavior of Cargo*, it simply asserts that Cargo shouldn't touch +the network as a previous command has been run to ensure that network activity +shouldn't be necessary. + +For more information about vendoring, see documentation on [source +replacement][replace]. + +[replace]: reference/source-replacement.html diff -Nru cargo-0.25.0/src/doc/src/getting-started/first-steps.md cargo-0.26.0/src/doc/src/getting-started/first-steps.md --- cargo-0.25.0/src/doc/src/getting-started/first-steps.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/getting-started/first-steps.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,70 @@ +## First Steps with Cargo + +To start a new project with Cargo, use `cargo new`: + +```console +$ cargo new hello_world --bin +``` + +We’re passing `--bin` because we’re making a binary program: if we +were making a library, we’d pass `--lib`. + +Let’s check out what Cargo has generated for us: + +```console +$ cd hello_world +$ tree . +. +├── Cargo.toml +└── src + └── main.rs + +1 directory, 2 files +``` + +This is all we need to get started. First, let’s check out `Cargo.toml`: + +```toml +[package] +name = "hello_world" +version = "0.1.0" +authors = ["Your Name "] +``` + +This is called a **manifest**, and it contains all of the metadata that Cargo +needs to compile your project. + +Here’s what’s in `src/main.rs`: + +```rust +fn main() { + println!("Hello, world!"); +} +``` + +Cargo generated a “hello world” for us. Let’s compile it: + +```console +$ cargo build + Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) +``` + +And then run it: + +```console +$ ./target/debug/hello_world +Hello, world! +``` + +We can also use `cargo run` to compile and then run it, all in one step: + +```console +$ cargo run + Fresh hello_world v0.1.0 (file:///path/to/project/hello_world) + Running `target/hello_world` +Hello, world! +``` + +### Going further + +For more details on using Cargo, check out the [Cargo Guide](guide/index.html) diff -Nru cargo-0.25.0/src/doc/src/getting-started/index.md cargo-0.26.0/src/doc/src/getting-started/index.md --- cargo-0.25.0/src/doc/src/getting-started/index.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/getting-started/index.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,6 @@ +## Getting Started + +To get started with Cargo, install Cargo (and Rust) and set up your first crate. + +* [Installation](getting-started/installation.html) +* [First steps with Cargo](getting-started/first-steps.html) diff -Nru cargo-0.25.0/src/doc/src/getting-started/installation.md cargo-0.26.0/src/doc/src/getting-started/installation.md --- cargo-0.25.0/src/doc/src/getting-started/installation.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/getting-started/installation.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,38 @@ +## Installation + +### Install Stable Rust and Cargo + +The easiest way to get Cargo is to get the current stable release of [Rust] by +using the `rustup` script: + +```console +$ curl -sSf https://static.rust-lang.org/rustup.sh | sh +``` + +After this, you can use the `rustup` command to also install `beta` or `nightly` +channels for Rust and Cargo. + +### Install Nightly Cargo + +To install just Cargo, the current recommended installation method is through +the official nightly builds. Note that Cargo will also require that [Rust] is +already installed on the system. + +| Platform | 64-bit | 32-bit | +|------------------|-------------------|-------------------| +| Linux binaries | [tar.gz][linux64] | [tar.gz][linux32] | +| MacOS binaries | [tar.gz][mac64] | [tar.gz][mac32] | +| Windows binaries | [tar.gz][win64] | [tar.gz][win32] | + +### Build and Install Cargo from Source + +Alternatively, you can [build Cargo from source][compiling-from-source]. + +[rust]: https://www.rust-lang.org/ +[linux64]: https://static.rust-lang.org/cargo-dist/cargo-nightly-x86_64-unknown-linux-gnu.tar.gz +[linux32]: https://static.rust-lang.org/cargo-dist/cargo-nightly-i686-unknown-linux-gnu.tar.gz +[mac64]: https://static.rust-lang.org/cargo-dist/cargo-nightly-x86_64-apple-darwin.tar.gz +[mac32]: https://static.rust-lang.org/cargo-dist/cargo-nightly-i686-apple-darwin.tar.gz +[win64]: https://static.rust-lang.org/cargo-dist/cargo-nightly-x86_64-pc-windows-gnu.tar.gz +[win32]: https://static.rust-lang.org/cargo-dist/cargo-nightly-i686-pc-windows-gnu.tar.gz +[compiling-from-source]: https://github.com/rust-lang/cargo#compiling-from-source diff -Nru cargo-0.25.0/src/doc/src/guide/build-cache.md cargo-0.26.0/src/doc/src/guide/build-cache.md --- cargo-0.25.0/src/doc/src/guide/build-cache.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/guide/build-cache.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,14 @@ +## Build cache + +Cargo shares build artifacts among all the packages of a single workspace. +Today, Cargo does not share build results across different workspaces, but +a similar result can be achieved by using a third party tool, [sccache]. + +To setup `sccache`, install it with `cargo install sccache` and set +`RUSTC_WRAPPER` environmental variable to `sccache` before invoking Cargo. +If you use bash, it makes sense to add `export RUSTC_WRAPPER=sccache` to +`.bashrc`. Refer to sccache documentation for more details. + +[sccache]: https://github.com/mozilla/sccache + + diff -Nru cargo-0.25.0/src/doc/src/guide/cargo-toml-vs-cargo-lock.md cargo-0.26.0/src/doc/src/guide/cargo-toml-vs-cargo-lock.md --- cargo-0.25.0/src/doc/src/guide/cargo-toml-vs-cargo-lock.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/guide/cargo-toml-vs-cargo-lock.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,103 @@ +## Cargo.toml vs Cargo.lock + +`Cargo.toml` and `Cargo.lock` serve two different purposes. Before we talk +about them, here’s a summary: + +* `Cargo.toml` is about describing your dependencies in a broad sense, and is + written by you. +* `Cargo.lock` contains exact information about your dependencies. It is + maintained by Cargo and should not be manually edited. + +If you’re building a library that other projects will depend on, put +`Cargo.lock` in your `.gitignore`. If you’re building an executable like a +command-line tool or an application, check `Cargo.lock` into `git`. If you're +curious about why that is, see ["Why do binaries have `Cargo.lock` in version +control, but not libraries?" in the +FAQ](faq.html#why-do-binaries-have-cargolock-in-version-control-but-not-libraries). + +Let’s dig in a little bit more. + +`Cargo.toml` is a **manifest** file in which we can specify a bunch of +different metadata about our project. For example, we can say that we depend +on another project: + +```toml +[package] +name = "hello_world" +version = "0.1.0" +authors = ["Your Name "] + +[dependencies] +rand = { git = "https://github.com/rust-lang-nursery/rand.git" } +``` + +This project has a single dependency, on the `rand` library. We’ve stated in +this case that we’re relying on a particular Git repository that lives on +GitHub. Since we haven’t specified any other information, Cargo assumes that +we intend to use the latest commit on the `master` branch to build our project. + +Sound good? Well, there’s one problem: If you build this project today, and +then you send a copy to me, and I build this project tomorrow, something bad +could happen. There could be more commits to `rand` in the meantime, and my +build would include new commits while yours would not. Therefore, we would +get different builds. This would be bad because we want reproducible builds. + +We could fix this problem by putting a `rev` line in our `Cargo.toml`: + +```toml +[dependencies] +rand = { git = "https://github.com/rust-lang-nursery/rand.git", rev = "9f35b8e" } +``` + +Now our builds will be the same. But there’s a big drawback: now we have to +manually think about SHA-1s every time we want to update our library. This is +both tedious and error prone. + +Enter the `Cargo.lock`. Because of its existence, we don’t need to manually +keep track of the exact revisions: Cargo will do it for us. When we have a +manifest like this: + +```toml +[package] +name = "hello_world" +version = "0.1.0" +authors = ["Your Name "] + +[dependencies] +rand = { git = "https://github.com/rust-lang-nursery/rand.git" } +``` + +Cargo will take the latest commit and write that information out into our +`Cargo.lock` when we build for the first time. That file will look like this: + +```toml +[[package]] +name = "hello_world" +version = "0.1.0" +dependencies = [ + "rand 0.1.0 (git+https://github.com/rust-lang-nursery/rand.git#9f35b8e439eeedd60b9414c58f389bdc6a3284f9)", +] + +[[package]] +name = "rand" +version = "0.1.0" +source = "git+https://github.com/rust-lang-nursery/rand.git#9f35b8e439eeedd60b9414c58f389bdc6a3284f9" +``` + +You can see that there’s a lot more information here, including the exact +revision we used to build. Now when you give your project to someone else, +they’ll use the exact same SHA, even though we didn’t specify it in our +`Cargo.toml`. + +When we’re ready to opt in to a new version of the library, Cargo can +re-calculate the dependencies and update things for us: + +```console +$ cargo update # updates all dependencies +$ cargo update -p rand # updates just “rand” +``` + +This will write out a new `Cargo.lock` with the new version information. Note +that the argument to `cargo update` is actually a +[Package ID Specification](reference/pkgid-spec.html) and `rand` is just a short +specification. diff -Nru cargo-0.25.0/src/doc/src/guide/continuous-integration.md cargo-0.26.0/src/doc/src/guide/continuous-integration.md --- cargo-0.25.0/src/doc/src/guide/continuous-integration.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/guide/continuous-integration.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,21 @@ +## Continuous Integration + +### Travis CI + +To test your project on Travis CI, here is a sample `.travis.yml` file: + +```yaml +language: rust +rust: + - stable + - beta + - nightly +matrix: + allow_failures: + - rust: nightly +``` + +This will test all three release channels, but any breakage in nightly +will not fail your overall build. Please see the [Travis CI Rust +documentation](https://docs.travis-ci.com/user/languages/rust/) for more +information. diff -Nru cargo-0.25.0/src/doc/src/guide/creating-a-new-project.md cargo-0.26.0/src/doc/src/guide/creating-a-new-project.md --- cargo-0.25.0/src/doc/src/guide/creating-a-new-project.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/guide/creating-a-new-project.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,87 @@ +## Creating a New Project + +To start a new project with Cargo, use `cargo new`: + +```console +$ cargo new hello_world --bin +``` + +We’re passing `--bin` because we’re making a binary program: if we +were making a library, we’d pass `--lib`. This also initializes a new `git` +repository by default. If you don't want it to do that, pass `--vcs none`. + +Let’s check out what Cargo has generated for us: + +```console +$ cd hello_world +$ tree . +. +├── Cargo.toml +└── src + └── main.rs + +1 directory, 2 files +``` + +Let’s take a closer look at `Cargo.toml`: + +```toml +[package] +name = "hello_world" +version = "0.1.0" +authors = ["Your Name "] +``` + +This is called a **manifest**, and it contains all of the metadata that Cargo +needs to compile your project. + +Here’s what’s in `src/main.rs`: + +```rust +fn main() { + println!("Hello, world!"); +} +``` + +Cargo generated a “hello world” for us. Let’s compile it: + +```console +$ cargo build + Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) +``` + +And then run it: + +```console +$ ./target/debug/hello_world +Hello, world! +``` + +We can also use `cargo run` to compile and then run it, all in one step (You +won't see the `Compiling` line if you have not made any changes since you last +compiled): + +```console +$ cargo run + Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) + Running `target/debug/hello_world` +Hello, world! +``` + +You’ll now notice a new file, `Cargo.lock`. It contains information about our +dependencies. Since we don’t have any yet, it’s not very interesting. + +Once you’re ready for release, you can use `cargo build --release` to compile +your files with optimizations turned on: + +```console +$ cargo build --release + Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) +``` + +`cargo build --release` puts the resulting binary in `target/release` instead of +`target/debug`. + +Compiling in debug mode is the default for development-- compilation time is +shorter since the compiler doesn't do optimizations, but the code will run +slower. Release mode takes longer to compile, but the code will run faster. diff -Nru cargo-0.25.0/src/doc/src/guide/dependencies.md cargo-0.26.0/src/doc/src/guide/dependencies.md --- cargo-0.25.0/src/doc/src/guide/dependencies.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/guide/dependencies.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,90 @@ +## Dependencies + +[crates.io] is the Rust community's central package registry that serves as a +location to discover and download packages. `cargo` is configured to use it by +default to find requested packages. + +To depend on a library hosted on [crates.io], add it to your `Cargo.toml`. + +[crates.io]: https://crates.io/ + +### Adding a dependency + +If your `Cargo.toml` doesn't already have a `[dependencies]` section, add that, +then list the crate name and version that you would like to use. This example +adds a dependency of the `time` crate: + +```toml +[dependencies] +time = "0.1.12" +``` + +The version string is a [semver] version requirement. The [specifying +dependencies](reference/specifying-dependencies.html) docs have more information about +the options you have here. + +[semver]: https://github.com/steveklabnik/semver#requirements + +If we also wanted to add a dependency on the `regex` crate, we would not need +to add `[dependencies]` for each crate listed. Here's what your whole +`Cargo.toml` file would look like with dependencies on the `time` and `regex` +crates: + +```toml +[package] +name = "hello_world" +version = "0.1.0" +authors = ["Your Name "] + +[dependencies] +time = "0.1.12" +regex = "0.1.41" +``` + +Re-run `cargo build`, and Cargo will fetch the new dependencies and all of +their dependencies, compile them all, and update the `Cargo.lock`: + +```console +$ cargo build + Updating registry `https://github.com/rust-lang/crates.io-index` + Downloading memchr v0.1.5 + Downloading libc v0.1.10 + Downloading regex-syntax v0.2.1 + Downloading memchr v0.1.5 + Downloading aho-corasick v0.3.0 + Downloading regex v0.1.41 + Compiling memchr v0.1.5 + Compiling libc v0.1.10 + Compiling regex-syntax v0.2.1 + Compiling memchr v0.1.5 + Compiling aho-corasick v0.3.0 + Compiling regex v0.1.41 + Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) +``` + +Our `Cargo.lock` contains the exact information about which revision of all of +these dependencies we used. + +Now, if `regex` gets updated, we will still build with the same revision until +we choose to `cargo update`. + +You can now use the `regex` library using `extern crate` in `main.rs`. + +```rust +extern crate regex; + +use regex::Regex; + +fn main() { + let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); + println!("Did our date match? {}", re.is_match("2014-01-01")); +} +``` + +Running it will show: + +```console +$ cargo run + Running `target/hello_world` +Did our date match? true +``` diff -Nru cargo-0.25.0/src/doc/src/guide/index.md cargo-0.26.0/src/doc/src/guide/index.md --- cargo-0.25.0/src/doc/src/guide/index.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/guide/index.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,14 @@ +## Cargo Guide + +This guide will give you all that you need to know about how to use Cargo to +develop Rust projects. + +* [Why Cargo Exists](guide/why-cargo-exists.html) +* [Creating a New Project](guide/creating-a-new-project.html) +* [Working on an Existing Cargo Project](guide/working-on-an-existing-project.html) +* [Dependencies](guide/dependencies.html) +* [Project Layout](guide/project-layout.html) +* [Cargo.toml vs Cargo.lock](guide/cargo-toml-vs-cargo-lock.html) +* [Tests](guide/tests.html) +* [Continuous Integration](guide/continuous-integration.html) +* [Build Cache](guide/build-cache.html) diff -Nru cargo-0.25.0/src/doc/src/guide/project-layout.md cargo-0.26.0/src/doc/src/guide/project-layout.md --- cargo-0.25.0/src/doc/src/guide/project-layout.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/guide/project-layout.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,35 @@ +## Project Layout + +Cargo uses conventions for file placement to make it easy to dive into a new +Cargo project: + +``` +. +├── Cargo.lock +├── Cargo.toml +├── benches +│   └── large-input.rs +├── examples +│   └── simple.rs +├── src +│   ├── bin +│   │   └── another_executable.rs +│   ├── lib.rs +│   └── main.rs +└── tests + └── some-integration-tests.rs +``` + +* `Cargo.toml` and `Cargo.lock` are stored in the root of your project (*package + root*). +* Source code goes in the `src` directory. +* The default library file is `src/lib.rs`. +* The default executable file is `src/main.rs`. +* Other executables can be placed in `src/bin/*.rs`. +* Integration tests go in the `tests` directory (unit tests go in each file + they're testing). +* Examples go in the `examples` directory. +* Benchmarks go in the `benches` directory. + +These are explained in more detail in the [manifest +description](reference/manifest.html#the-project-layout). diff -Nru cargo-0.25.0/src/doc/src/guide/tests.md cargo-0.26.0/src/doc/src/guide/tests.md --- cargo-0.25.0/src/doc/src/guide/tests.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/guide/tests.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,39 @@ +## Tests + +Cargo can run your tests with the `cargo test` command. Cargo looks for tests +to run in two places: in each of your `src` files and any tests in `tests/`. +Tests in your `src` files should be unit tests, and tests in `tests/` should be +integration-style tests. As such, you’ll need to import your crates into +the files in `tests`. + +Here's an example of running `cargo test` in our project, which currently has +no tests: + +```console +$ cargo test + Compiling rand v0.1.0 (https://github.com/rust-lang-nursery/rand.git#9f35b8e) + Compiling hello_world v0.1.0 (file:///path/to/project/hello_world) + Running target/test/hello_world-9c2b65bbb79eabce + +running 0 tests + +test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out +``` + +If our project had tests, we would see more output with the correct number of +tests. + +You can also run a specific test by passing a filter: + +```console +$ cargo test foo +``` + +This will run any test with `foo` in its name. + +`cargo test` runs additional checks as well. For example, it will compile any +examples you’ve included and will also test the examples in your +documentation. Please see the [testing guide][testing] in the Rust +documentation for more details. + +[testing]: https://doc.rust-lang.org/book/testing.html diff -Nru cargo-0.25.0/src/doc/src/guide/why-cargo-exists.md cargo-0.26.0/src/doc/src/guide/why-cargo-exists.md --- cargo-0.25.0/src/doc/src/guide/why-cargo-exists.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/guide/why-cargo-exists.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,12 @@ +## Why Cargo Exists + +Cargo is a tool that allows Rust projects to declare their various +dependencies and ensure that you’ll always get a repeatable build. + +To accomplish this goal, Cargo does four things: + +* Introduces two metadata files with various bits of project information. +* Fetches and builds your project’s dependencies. +* Invokes `rustc` or another build tool with the correct parameters to build + your project. +* Introduces conventions to make working with Rust projects easier. diff -Nru cargo-0.25.0/src/doc/src/guide/working-on-an-existing-project.md cargo-0.26.0/src/doc/src/guide/working-on-an-existing-project.md --- cargo-0.25.0/src/doc/src/guide/working-on-an-existing-project.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/guide/working-on-an-existing-project.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,22 @@ +## Working on an Existing Cargo Project + +If you download an existing project that uses Cargo, it’s really easy +to get going. + +First, get the project from somewhere. In this example, we’ll use `rand` +cloned from its repository on GitHub: + +```console +$ git clone https://github.com/rust-lang-nursery/rand.git +$ cd rand +``` + +To build, use `cargo build`: + +```console +$ cargo build + Compiling rand v0.1.0 (file:///path/to/project/rand) +``` + +This will fetch all of the dependencies and then build them, along with the +project. Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/src/images/auth-level-acl.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/src/images/auth-level-acl.png differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/src/images/Cargo-Logo-Small.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/src/images/Cargo-Logo-Small.png differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/src/images/org-level-acl.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/src/images/org-level-acl.png differ diff -Nru cargo-0.25.0/src/doc/src/index.md cargo-0.26.0/src/doc/src/index.md --- cargo-0.25.0/src/doc/src/index.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/index.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,28 @@ +# The Cargo Book + +![Cargo Logo](images/Cargo-Logo-Small.png) + +Cargo is the [Rust] *package manager*. Cargo downloads your Rust project’s +dependencies, compiles your project, makes packages, and upload them to +[crates.io], the Rust community’s *package registry*. + + +### Sections + +**[Getting Started](getting-started/index.html)** + +To get started with Cargo, install Cargo (and Rust) and set up your first crate. + +**[Cargo Guide](guide/index.html)** + +The guide will give you all you need to know about how to use Cargo to develop +Rust projects. + +**[Cargo Reference](reference/index.html)** + +The reference covers the details of various areas of Cargo. + +**[Frequently Asked Questions](faq.html)** + +[rust]: https://www.rust-lang.org/ +[crates.io]: https://crates.io/ diff -Nru cargo-0.25.0/src/doc/src/reference/build-scripts.md cargo-0.26.0/src/doc/src/reference/build-scripts.md --- cargo-0.25.0/src/doc/src/reference/build-scripts.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/reference/build-scripts.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,565 @@ +## Build Scripts + +Some packages need to compile third-party non-Rust code, for example C +libraries. Other packages need to link to C libraries which can either be +located on the system or possibly need to be built from source. Others still +need facilities for functionality such as code generation before building (think +parser generators). + +Cargo does not aim to replace other tools that are well-optimized for +these tasks, but it does integrate with them with the `build` configuration +option. + +```toml +[package] +# ... +build = "build.rs" +``` + +The Rust file designated by the `build` command (relative to the package root) +will be compiled and invoked before anything else is compiled in the package, +allowing your Rust code to depend on the built or generated artifacts. +By default Cargo looks up for `"build.rs"` file in a package root (even if you +do not specify a value for `build`). Use `build = "custom_build_name.rs"` to specify +a custom build name or `build = false` to disable automatic detection of the build script. + +Some example use cases of the build command are: + +* Building a bundled C library. +* Finding a C library on the host system. +* Generating a Rust module from a specification. +* Performing any platform-specific configuration needed for the crate. + +Each of these use cases will be detailed in full below to give examples of how +the build command works. + +### Inputs to the Build Script + +When the build script is run, there are a number of inputs to the build script, +all passed in the form of [environment variables][env]. + +In addition to environment variables, the build script’s current directory is +the source directory of the build script’s package. + +[env]: reference/environment-variables.html + +### Outputs of the Build Script + +All the lines printed to stdout by a build script are written to a file like +`target/debug/build//output` (the precise location may depend on your +configuration). If you would like to see such output directly in your terminal, +invoke cargo as 'very verbose' with the `-vv` flag. Note that if neither the +build script nor project source files are modified, subsequent calls to +cargo with `-vv` will **not** print output to the terminal because a +new build is not executed. Run `cargo clean` before each cargo invocation +if you want to ensure that output is always displayed on your terminal. +Any line that starts with `cargo:` is interpreted directly by Cargo. +This line must be of the form `cargo:key=value`, like the examples below: + +``` +# specially recognized by Cargo +cargo:rustc-link-lib=static=foo +cargo:rustc-link-search=native=/path/to/foo +cargo:rustc-cfg=foo +cargo:rustc-env=FOO=bar +# arbitrary user-defined metadata +cargo:root=/path/to/foo +cargo:libdir=/path/to/foo/lib +cargo:include=/path/to/foo/include +``` + +On the other hand, lines printed to stderr are written to a file like +`target/debug/build//stderr` but are not interpreted by cargo. + +There are a few special keys that Cargo recognizes, some affecting how the +crate is built: + +* `rustc-link-lib=[KIND=]NAME` indicates that the specified value is a library + name and should be passed to the compiler as a `-l` flag. The optional `KIND` + can be one of `static`, `dylib` (the default), or `framework`, see + `rustc --help` for more details. +* `rustc-link-search=[KIND=]PATH` indicates the specified value is a library + search path and should be passed to the compiler as a `-L` flag. The optional + `KIND` can be one of `dependency`, `crate`, `native`, `framework` or `all` + (the default), see `rustc --help` for more details. +* `rustc-flags=FLAGS` is a set of flags passed to the compiler, only `-l` and + `-L` flags are supported. +* `rustc-cfg=FEATURE` indicates that the specified feature will be passed as a + `--cfg` flag to the compiler. This is often useful for performing compile-time + detection of various features. +* `rustc-env=VAR=VALUE` indicates that the specified environment variable + will be added to the environment which the compiler is run within. + The value can be then retrieved by the `env!` macro in the compiled crate. + This is useful for embedding additional metadata in crate's code, + such as the hash of Git HEAD or the unique identifier of a continuous + integration server. +* `rerun-if-changed=PATH` is a path to a file or directory which indicates that + the build script should be re-run if it changes (detected by a more-recent + last-modified timestamp on the file). Normally build scripts are re-run if + any file inside the crate root changes, but this can be used to scope changes + to just a small set of files. (If this path points to a directory the entire + directory will not be traversed for changes -- only changes to the timestamp + of the directory itself (which corresponds to some types of changes within the + directory, depending on platform) will trigger a rebuild. To request a re-run + on any changes within an entire directory, print a line for the directory and + another line for everything inside it, recursively.) + Note that if the build script itself (or one of its dependencies) changes, + then it's rebuilt and rerun unconditionally, so + `cargo:rerun-if-changed=build.rs` is almost always redundant (unless you + want to ignore changes in all other files except for `build.rs`). +* `rerun-if-env-changed=VAR` is the name of an environment variable which + indicates that if the environment variable's value changes the build script + should be rerun. This basically behaves the same as `rerun-if-changed` except + that it works with environment variables instead. Note that the environment + variables here are intended for global environment variables like `CC` and + such, it's not necessary to use this for env vars like `TARGET` that Cargo + sets. Also note that if `rerun-if-env-changed` is printed out then Cargo will + *only* rerun the build script if those environment variables change or if + files printed out by `rerun-if-changed` change. + +* `warning=MESSAGE` is a message that will be printed to the main console after + a build script has finished running. Warnings are only shown for path + dependencies (that is, those you're working on locally), so for example + warnings printed out in crates.io crates are not emitted by default. + +Any other element is a user-defined metadata that will be passed to +dependents. More information about this can be found in the [`links`][links] +section. + +[links]: #the-links-manifest-key + +### Build Dependencies + +Build scripts are also allowed to have dependencies on other Cargo-based crates. +Dependencies are declared through the `build-dependencies` section of the +manifest. + +```toml +[build-dependencies] +foo = { git = "https://github.com/your-packages/foo" } +``` + +The build script **does not** have access to the dependencies listed in the +`dependencies` or `dev-dependencies` section (they’re not built yet!). All build +dependencies will also not be available to the package itself unless explicitly +stated as so. + +### The `links` Manifest Key + +In addition to the manifest key `build`, Cargo also supports a `links` manifest +key to declare the name of a native library that is being linked to: + +```toml +[package] +# ... +links = "foo" +build = "build.rs" +``` + +This manifest states that the package links to the `libfoo` native library, and +it also has a build script for locating and/or building the library. Cargo +requires that a `build` command is specified if a `links` entry is also +specified. + +The purpose of this manifest key is to give Cargo an understanding about the set +of native dependencies that a package has, as well as providing a principled +system of passing metadata between package build scripts. + +Primarily, Cargo requires that there is at most one package per `links` value. +In other words, it’s forbidden to have two packages link to the same native +library. Note, however, that there are [conventions in place][star-sys] to +alleviate this. + +[star-sys]: #-sys-packages + +As mentioned above in the output format, each build script can generate an +arbitrary set of metadata in the form of key-value pairs. This metadata is +passed to the build scripts of **dependent** packages. For example, if `libbar` +depends on `libfoo`, then if `libfoo` generates `key=value` as part of its +metadata, then the build script of `libbar` will have the environment variables +`DEP_FOO_KEY=value`. + +Note that metadata is only passed to immediate dependents, not transitive +dependents. The motivation for this metadata passing is outlined in the linking +to system libraries case study below. + +### Overriding Build Scripts + +If a manifest contains a `links` key, then Cargo supports overriding the build +script specified with a custom library. The purpose of this functionality is to +prevent running the build script in question altogether and instead supply the +metadata ahead of time. + +To override a build script, place the following configuration in any acceptable +Cargo [configuration location](reference/config.html). + +```toml +[target.x86_64-unknown-linux-gnu.foo] +rustc-link-search = ["/path/to/foo"] +rustc-link-lib = ["foo"] +root = "/path/to/foo" +key = "value" +``` + +This section states that for the target `x86_64-unknown-linux-gnu` the library +named `foo` has the metadata specified. This metadata is the same as the +metadata generated as if the build script had run, providing a number of +key/value pairs where the `rustc-flags`, `rustc-link-search`, and +`rustc-link-lib` keys are slightly special. + +With this configuration, if a package declares that it links to `foo` then the +build script will **not** be compiled or run, and the metadata specified will +instead be used. + +### Case study: Code generation + +Some Cargo packages need to have code generated just before they are compiled +for various reasons. Here we’ll walk through a simple example which generates a +library call as part of the build script. + +First, let’s take a look at the directory structure of this package: + +``` +. +├── Cargo.toml +├── build.rs +└── src + └── main.rs + +1 directory, 3 files +``` + +Here we can see that we have a `build.rs` build script and our binary in +`main.rs`. Next, let’s take a look at the manifest: + +```toml +# Cargo.toml + +[package] +name = "hello-from-generated-code" +version = "0.1.0" +authors = ["you@example.com"] +build = "build.rs" +``` + +Here we can see we’ve got a build script specified which we’ll use to generate +some code. Let’s see what’s inside the build script: + +```rust,no_run +// build.rs + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::Path; + +fn main() { + let out_dir = env::var("OUT_DIR").unwrap(); + let dest_path = Path::new(&out_dir).join("hello.rs"); + let mut f = File::create(&dest_path).unwrap(); + + f.write_all(b" + pub fn message() -> &'static str { + \"Hello, World!\" + } + ").unwrap(); +} +``` + +There’s a couple of points of note here: + +* The script uses the `OUT_DIR` environment variable to discover where the + output files should be located. It can use the process’ current working + directory to find where the input files should be located, but in this case we + don’t have any input files. +* This script is relatively simple as it just writes out a small generated file. + One could imagine that other more fanciful operations could take place such as + generating a Rust module from a C header file or another language definition, + for example. + +Next, let’s peek at the library itself: + +```rust,ignore +// src/main.rs + +include!(concat!(env!("OUT_DIR"), "/hello.rs")); + +fn main() { + println!("{}", message()); +} +``` + +This is where the real magic happens. The library is using the rustc-defined +`include!` macro in combination with the `concat!` and `env!` macros to include +the generated file (`hello.rs`) into the crate’s compilation. + +Using the structure shown here, crates can include any number of generated files +from the build script itself. + +### Case study: Building some native code + +Sometimes it’s necessary to build some native C or C++ code as part of a +package. This is another excellent use case of leveraging the build script to +build a native library before the Rust crate itself. As an example, we’ll create +a Rust library which calls into C to print “Hello, World!”. + +Like above, let’s first take a look at the project layout: + +``` +. +├── Cargo.toml +├── build.rs +└── src + ├── hello.c + └── main.rs + +1 directory, 4 files +``` + +Pretty similar to before! Next, the manifest: + +```toml +# Cargo.toml + +[package] +name = "hello-world-from-c" +version = "0.1.0" +authors = ["you@example.com"] +build = "build.rs" +``` + +For now we’re not going to use any build dependencies, so let’s take a look at +the build script now: + +```rust,no_run +// build.rs + +use std::process::Command; +use std::env; +use std::path::Path; + +fn main() { + let out_dir = env::var("OUT_DIR").unwrap(); + + // note that there are a number of downsides to this approach, the comments + // below detail how to improve the portability of these commands. + Command::new("gcc").args(&["src/hello.c", "-c", "-fPIC", "-o"]) + .arg(&format!("{}/hello.o", out_dir)) + .status().unwrap(); + Command::new("ar").args(&["crus", "libhello.a", "hello.o"]) + .current_dir(&Path::new(&out_dir)) + .status().unwrap(); + + println!("cargo:rustc-link-search=native={}", out_dir); + println!("cargo:rustc-link-lib=static=hello"); +} +``` + +This build script starts out by compiling our C file into an object file (by +invoking `gcc`) and then converting this object file into a static library (by +invoking `ar`). The final step is feedback to Cargo itself to say that our +output was in `out_dir` and the compiler should link the crate to `libhello.a` +statically via the `-l static=hello` flag. + +Note that there are a number of drawbacks to this hardcoded approach: + +* The `gcc` command itself is not portable across platforms. For example it’s + unlikely that Windows platforms have `gcc`, and not even all Unix platforms + may have `gcc`. The `ar` command is also in a similar situation. +* These commands do not take cross-compilation into account. If we’re cross + compiling for a platform such as Android it’s unlikely that `gcc` will produce + an ARM executable. + +Not to fear, though, this is where a `build-dependencies` entry would help! The +Cargo ecosystem has a number of packages to make this sort of task much easier, +portable, and standardized. For example, the build script could be written as: + +```rust,ignore +// build.rs + +// Bring in a dependency on an externally maintained `cc` package which manages +// invoking the C compiler. +extern crate cc; + +fn main() { + cc::Build::new() + .file("src/hello.c") + .compile("hello"); +} +``` + +Add a build time dependency on the `cc` crate with the following addition to +your `Cargo.toml`: + +```toml +[build-dependencies] +gcc = "1.0" +``` + +The [`cc` crate](https://crates.io/crates/cc) abstracts a range of build +script requirements for C code: + +* It invokes the appropriate compiler (MSVC for windows, `gcc` for MinGW, `cc` + for Unix platforms, etc.). +* It takes the `TARGET` variable into account by passing appropriate flags to + the compiler being used. +* Other environment variables, such as `OPT_LEVEL`, `DEBUG`, etc., are all + handled automatically. +* The stdout output and `OUT_DIR` locations are also handled by the `cc` + library. + +Here we can start to see some of the major benefits of farming as much +functionality as possible out to common build dependencies rather than +duplicating logic across all build scripts! + +Back to the case study though, let’s take a quick look at the contents of the +`src` directory: + +```c +// src/hello.c + +#include + +void hello() { + printf("Hello, World!\n"); +} +``` + +```rust,ignore +// src/main.rs + +// Note the lack of the `#[link]` attribute. We’re delegating the responsibility +// of selecting what to link to over to the build script rather than hardcoding +// it in the source file. +extern { fn hello(); } + +fn main() { + unsafe { hello(); } +} +``` + +And there we go! This should complete our example of building some C code from a +Cargo package using the build script itself. This also shows why using a build +dependency can be crucial in many situations and even much more concise! + +We’ve also seen a brief example of how a build script can use a crate as a +dependency purely for the build process and not for the crate itself at runtime. + +### Case study: Linking to system libraries + +The final case study here will be investigating how a Cargo library links to a +system library and how the build script is leveraged to support this use case. + +Quite frequently a Rust crate wants to link to a native library often provided +on the system to bind its functionality or just use it as part of an +implementation detail. This is quite a nuanced problem when it comes to +performing this in a platform-agnostic fashion, and the purpose of a build +script is again to farm out as much of this as possible to make this as easy as +possible for consumers. + +As an example to follow, let’s take a look at one of [Cargo’s own +dependencies][git2-rs], [libgit2][libgit2]. The C library has a number of +constraints: + +[git2-rs]: https://github.com/alexcrichton/git2-rs/tree/master/libgit2-sys +[libgit2]: https://github.com/libgit2/libgit2 + +* It has an optional dependency on OpenSSL on Unix to implement the https + transport. +* It has an optional dependency on libssh2 on all platforms to implement the ssh + transport. +* It is often not installed on all systems by default. +* It can be built from source using `cmake`. + +To visualize what’s going on here, let’s take a look at the manifest for the +relevant Cargo package that links to the native C library. + +```toml +[package] +name = "libgit2-sys" +version = "0.1.0" +authors = ["..."] +links = "git2" +build = "build.rs" + +[dependencies] +libssh2-sys = { git = "https://github.com/alexcrichton/ssh2-rs" } + +[target.'cfg(unix)'.dependencies] +openssl-sys = { git = "https://github.com/alexcrichton/openssl-sys" } + +# ... +``` + +As the above manifests show, we’ve got a `build` script specified, but it’s +worth noting that this example has a `links` entry which indicates that the +crate (`libgit2-sys`) links to the `git2` native library. + +Here we also see that we chose to have the Rust crate have an unconditional +dependency on `libssh2` via the `libssh2-sys` crate, as well as a +platform-specific dependency on `openssl-sys` for \*nix (other variants elided +for now). It may seem a little counterintuitive to express *C dependencies* in +the *Cargo manifest*, but this is actually using one of Cargo’s conventions in +this space. + +### `*-sys` Packages + +To alleviate linking to system libraries, Cargo has a *convention* of package +naming and functionality. Any package named `foo-sys` will provide two major +pieces of functionality: + +* The library crate will link to the native library `libfoo`. This will often + probe the current system for `libfoo` before resorting to building from + source. +* The library crate will provide **declarations** for functions in `libfoo`, + but it does **not** provide bindings or higher-level abstractions. + +The set of `*-sys` packages provides a common set of dependencies for linking +to native libraries. There are a number of benefits earned from having this +convention of native-library-related packages: + +* Common dependencies on `foo-sys` alleviates the above rule about one package + per value of `links`. +* A common dependency allows centralizing logic on discovering `libfoo` itself + (or building it from source). +* These dependencies are easily overridable. + +### Building libgit2 + +Now that we’ve got libgit2’s dependencies sorted out, we need to actually write +the build script. We’re not going to look at specific snippets of code here and +instead only take a look at the high-level details of the build script of +`libgit2-sys`. This is not recommending all packages follow this strategy, but +rather just outlining one specific strategy. + +The first step of the build script should do is to query whether libgit2 is +already installed on the host system. To do this we’ll leverage the preexisting +tool `pkg-config` (when its available). We’ll also use a `build-dependencies` +section to refactor out all the `pkg-config` related code (or someone’s already +done that!). + +If `pkg-config` failed to find libgit2, or if `pkg-config` just wasn’t +installed, the next step is to build libgit2 from bundled source code +(distributed as part of `libgit2-sys` itself). There are a few nuances when +doing so that we need to take into account, however: + +* The build system of libgit2, `cmake`, needs to be able to find libgit2’s + optional dependency of libssh2. We’re sure we’ve already built it (it’s a + Cargo dependency), we just need to communicate this information. To do this + we leverage the metadata format to communicate information between build + scripts. In this example the libssh2 package printed out `cargo:root=...` to + tell us where libssh2 is installed at, and we can then pass this along to + cmake with the `CMAKE_PREFIX_PATH` environment variable. + +* We’ll need to handle some `CFLAGS` values when compiling C code (and tell + `cmake` about this). Some flags we may want to pass are `-m64` for 64-bit + code, `-m32` for 32-bit code, or `-fPIC` for 64-bit code as well. + +* Finally, we’ll invoke `cmake` to place all output into the `OUT_DIR` + environment variable, and then we’ll print the necessary metadata to instruct + rustc how to link to libgit2. + +Most of the functionality of this build script is easily refactorable into +common dependencies, so our build script isn’t quite as intimidating as this +descriptions! In reality it’s expected that build scripts are quite succinct by +farming logic such as above to build dependencies. diff -Nru cargo-0.25.0/src/doc/src/reference/config.md cargo-0.26.0/src/doc/src/reference/config.md --- cargo-0.25.0/src/doc/src/reference/config.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/reference/config.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,141 @@ +## Configuration + +This document will explain how Cargo’s configuration system works, as well as +available keys or configuration. For configuration of a project through its +manifest, see the [manifest format](reference/manifest.html). + +### Hierarchical structure + + +Cargo allows local configuration for a particular project as well as global +configuration, like git. Cargo extends this to a hierarchical strategy. +If, for example, Cargo were invoked in `/projects/foo/bar/baz`, then the +following configuration files would be probed for and unified in this order: + +* `/projects/foo/bar/baz/.cargo/config` +* `/projects/foo/bar/.cargo/config` +* `/projects/foo/.cargo/config` +* `/projects/.cargo/config` +* `/.cargo/config` +* `$HOME/.cargo/config` + +With this structure, you can specify configuration per-project, and even +possibly check it into version control. You can also specify personal defaults +with a configuration file in your home directory. + +### Configuration format + +All configuration is currently in the [TOML format][toml] (like the manifest), +with simple key-value pairs inside of sections (tables) which all get merged +together. + +[toml]: https://github.com/toml-lang/toml + +### Configuration keys + +All of the following keys are optional, and their defaults are listed as their +value unless otherwise noted. + +Key values that specify a tool may be given as an absolute path, a relative path +or as a pathless tool name. Absolute paths and pathless tool names are used as +given. Relative paths are resolved relative to the parent directory of the +`.cargo` directory of the config file that the value resides within. + +```toml +# An array of paths to local repositories which are to be used as overrides for +# dependencies. For more information see the Specifying Dependencies guide. +paths = ["/path/to/override"] + +[cargo-new] +# This is your name/email to place in the `authors` section of a new Cargo.toml +# that is generated. If not present, then `git` will be probed, and if that is +# not present then `$USER` and `$EMAIL` will be used. +name = "..." +email = "..." + +# By default `cargo new` will initialize a new Git repository. This key can be +# set to `hg` to create a Mercurial repository, or `none` to disable this +# behavior. +vcs = "none" + +# For the following sections, $triple refers to any valid target triple, not the +# literal string "$triple", and it will apply whenever that target triple is +# being compiled to. 'cfg(...)' refers to the Rust-like `#[cfg]` syntax for +# conditional compilation. +[target.$triple] +# This is the linker which is passed to rustc (via `-C linker=`) when the `$triple` +# is being compiled for. By default this flag is not passed to the compiler. +linker = ".." +# Same but for the library archiver which is passed to rustc via `-C ar=`. +ar = ".." +# If a runner is provided, compiled targets for the `$triple` will be executed +# by invoking the specified runner executable with actual target as first argument. +# This applies to `cargo run`, `cargo test` and `cargo bench` commands. +# By default compiled targets are executed directly. +runner = ".." +# custom flags to pass to all compiler invocations that target $triple +# this value overrides build.rustflags when both are present +rustflags = ["..", ".."] +# Whether or not to enable incremental compilation +incremental = true + +[target.'cfg(...)'] +# Similar for the $triple configuration, but using the `cfg` syntax. +# If several `cfg` and $triple targets are candidates, then the rustflags +# are concatenated. The `cfg` syntax only applies to rustflags, and not to +# linker. +rustflags = ["..", ".."] + +# Configuration keys related to the registry +[registry] +index = "..." # URL of the registry index (defaults to the central repository) +token = "..." # Access token (found on the central repo’s website) + +[http] +proxy = "host:port" # HTTP proxy to use for HTTP requests (defaults to none) + # in libcurl format, e.g. "socks5h://host:port" +timeout = 60000 # Timeout for each HTTP request, in milliseconds +cainfo = "cert.pem" # Path to Certificate Authority (CA) bundle (optional) +check-revoke = true # Indicates whether SSL certs are checked for revocation + +[build] +jobs = 1 # number of parallel jobs, defaults to # of CPUs +rustc = "rustc" # the rust compiler tool +rustdoc = "rustdoc" # the doc generator tool +target = "triple" # build for the target triple +target-dir = "target" # path of where to place all generated artifacts +rustflags = ["..", ".."] # custom flags to pass to all compiler invocations + +[term] +verbose = false # whether cargo provides verbose output +color = 'auto' # whether cargo colorizes output + +# Network configuration +[net] +retry = 2 # number of times a network call will automatically retried + +# Alias cargo commands. The first 3 aliases are built in. If your +# command requires grouped whitespace use the list format. +[alias] +b = "build" +t = "test" +r = "run" +rr = "run --release" +space_example = ["run", "--release", "--", "\"command list\""] +``` + +### Environment variables + +Cargo can also be configured through environment variables in addition to the +TOML syntax above. For each configuration key above of the form `foo.bar` the +environment variable `CARGO_FOO_BAR` can also be used to define the value. For +example the `build.jobs` key can also be defined by `CARGO_BUILD_JOBS`. + +Environment variables will take precedent over TOML configuration, and currently +only integer, boolean, and string keys are supported to be defined by +environment variables. + +In addition to the system above, Cargo recognizes a few other specific +[environment variables][env]. + +[env]: reference/environment-variables.html diff -Nru cargo-0.25.0/src/doc/src/reference/environment-variables.md cargo-0.26.0/src/doc/src/reference/environment-variables.md --- cargo-0.25.0/src/doc/src/reference/environment-variables.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/reference/environment-variables.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,136 @@ +## Environment Variables + +Cargo sets and reads a number of environment variables which your code can detect +or override. Here is a list of the variables Cargo sets, organized by when it interacts +with them: + +### Environment variables Cargo reads + +You can override these environment variables to change Cargo's behavior on your +system: + +* `CARGO_HOME` - Cargo maintains a local cache of the registry index and of git + checkouts of crates. By default these are stored under `$HOME/.cargo`, but + this variable overrides the location of this directory. Once a crate is cached + it is not removed by the clean command. +* `CARGO_TARGET_DIR` - Location of where to place all generated artifacts, + relative to the current working directory. +* `RUSTC` - Instead of running `rustc`, Cargo will execute this specified + compiler instead. +* `RUSTC_WRAPPER` - Instead of simply running `rustc`, Cargo will execute this + specified wrapper instead, passing as its commandline arguments the rustc + invocation, with the first argument being rustc. +* `RUSTDOC` - Instead of running `rustdoc`, Cargo will execute this specified + `rustdoc` instance instead. +* `RUSTDOCFLAGS` - A space-separated list of custom flags to pass to all `rustdoc` + invocations that Cargo performs. In contrast with `cargo rustdoc`, this is + useful for passing a flag to *all* `rustdoc` instances. +* `RUSTFLAGS` - A space-separated list of custom flags to pass to all compiler + invocations that Cargo performs. In contrast with `cargo rustc`, this is + useful for passing a flag to *all* compiler instances. +* `CARGO_INCREMENTAL` - If this is set to 1 then Cargo will force incremental + compilation to be enabled for the current compilation, and when set to 0 it + will force disabling it. If this env var isn't present then cargo's defaults + will otherwise be used. + +Note that Cargo will also read environment variables for `.cargo/config` +configuration values, as described in [that documentation][config-env] + +[config-env]: reference/config.html#environment-variables + +### Environment variables Cargo sets for crates + +Cargo exposes these environment variables to your crate when it is compiled. +Note that this applies for test binaries as well. +To get the value of any of these variables in a Rust program, do this: + +```rust +let version = env!("CARGO_PKG_VERSION"); +``` + +`version` will now contain the value of `CARGO_PKG_VERSION`. + +* `CARGO` - Path to the `cargo` binary performing the build. +* `CARGO_MANIFEST_DIR` - The directory containing the manifest of your package. +* `CARGO_PKG_VERSION` - The full version of your package. +* `CARGO_PKG_VERSION_MAJOR` - The major version of your package. +* `CARGO_PKG_VERSION_MINOR` - The minor version of your package. +* `CARGO_PKG_VERSION_PATCH` - The patch version of your package. +* `CARGO_PKG_VERSION_PRE` - The pre-release version of your package. +* `CARGO_PKG_AUTHORS` - Colon separated list of authors from the manifest of your package. +* `CARGO_PKG_NAME` - The name of your package. +* `CARGO_PKG_DESCRIPTION` - The description of your package. +* `CARGO_PKG_HOMEPAGE` - The home page of your package. +* `OUT_DIR` - If the package has a build script, this is set to the folder where the build + script should place its output. See below for more information. + +### Environment variables Cargo sets for build scripts + +Cargo sets several environment variables when build scripts are run. Because these variables +are not yet set when the build script is compiled, the above example using `env!` won't work +and instead you'll need to retrieve the values when the build script is run: + +```rust +use std::env; +let out_dir = env::var("OUT_DIR").unwrap(); +``` + +`out_dir` will now contain the value of `OUT_DIR`. + +* `CARGO` - Path to the `cargo` binary performing the build. +* `CARGO_MANIFEST_DIR` - The directory containing the manifest for the package + being built (the package containing the build + script). Also note that this is the value of the + current working directory of the build script when it + starts. +* `CARGO_MANIFEST_LINKS` - the manifest `links` value. +* `CARGO_FEATURE_` - For each activated feature of the package being + built, this environment variable will be present + where `` is the name of the feature uppercased + and having `-` translated to `_`. +* `CARGO_CFG_` - For each [configuration option][configuration] of the + package being built, this environment variable will + contain the value of the configuration, where `` is + the name of the configuration uppercased and having `-` + translated to `_`. + Boolean configurations are present if they are set, and + not present otherwise. + Configurations with multiple values are joined to a + single variable with the values delimited by `,`. +* `OUT_DIR` - the folder in which all output should be placed. This folder is + inside the build directory for the package being built, and it is + unique for the package in question. +* `TARGET` - the target triple that is being compiled for. Native code should be + compiled for this triple. Some more information about target + triples can be found in [clang’s own documentation][clang]. +* `HOST` - the host triple of the rust compiler. +* `NUM_JOBS` - the parallelism specified as the top-level parallelism. This can + be useful to pass a `-j` parameter to a system like `make`. Note + that care should be taken when interpreting this environment + variable. For historical purposes this is still provided but + recent versions of Cargo, for example, do not need to run `make + -j` as it'll automatically happen. Cargo implements its own + [jobserver] and will allow build scripts to inherit this + information, so programs compatible with GNU make jobservers will + already have appropriately configured parallelism. +* `OPT_LEVEL`, `DEBUG` - values of the corresponding variables for the + profile currently being built. +* `PROFILE` - `release` for release builds, `debug` for other builds. +* `DEP__` - For more information about this set of environment + variables, see build script documentation about [`links`][links]. +* `RUSTC`, `RUSTDOC` - the compiler and documentation generator that Cargo has + resolved to use, passed to the build script so it might + use it as well. + +[links]: reference/build-scripts.html#the-links-manifest-key +[profile]: reference/manifest.html#the-profile-sections +[configuration]: https://doc.rust-lang.org/reference/attributes.html#conditional-compilation +[clang]: http://clang.llvm.org/docs/CrossCompilation.html#target-triple +[jobserver]: https://www.gnu.org/software/make/manual/html_node/Job-Slots.html + +### Environment variables Cargo sets for 3rd party subcommands + +Cargo exposes this environment variable to 3rd party subcommands +(ie. programs named `cargo-foobar` placed in `$PATH`): + +* `CARGO` - Path to the `cargo` binary performing the build. diff -Nru cargo-0.25.0/src/doc/src/reference/external-tools.md cargo-0.26.0/src/doc/src/reference/external-tools.md --- cargo-0.25.0/src/doc/src/reference/external-tools.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/reference/external-tools.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,103 @@ +## External tools + +One of the goals of Cargo is simple integration with third-party tools, like +IDEs and other build systems. To make integration easier, Cargo has several +facilities: + +* a `cargo metadata` command, which outputs project structure and dependencies + information in JSON, + +* a `--message-format` flag, which outputs information about a particular build, + and + +* support for custom subcommands. + + +### Information about project structure + +You can use `cargo metadata` command to get information about project structure +and dependencies. The output of the command looks like this: + +```text +{ + // Integer version number of the format. + "version": integer, + + // List of packages for this workspace, including dependencies. + "packages": [ + { + // Opaque package identifier. + "id": PackageId, + + "name": string, + + "version": string, + + "source": SourceId, + + // A list of declared dependencies, see `resolve` field for actual dependencies. + "dependencies": [ Dependency ], + + "targets: [ Target ], + + // Path to Cargo.toml + "manifest_path": string, + } + ], + + "workspace_members": [ PackageId ], + + // Dependencies graph. + "resolve": { + "nodes": [ + { + "id": PackageId, + "dependencies": [ PackageId ] + } + ] + } +} +``` + +The format is stable and versioned. When calling `cargo metadata`, you should +pass `--format-version` flag explicitly to avoid forward incompatibility +hazard. + +If you are using Rust, there is [cargo_metadata] crate. + +[cargo_metadata]: https://crates.io/crates/cargo_metadata + + +### Information about build + +When passing `--message-format=json`, Cargo will output the following +information during the build: + +* compiler errors and warnings, + +* produced artifacts, + +* results of the build scripts (for example, native dependencies). + +The output goes to stdout in the JSON object per line format. The `reason` field +distinguishes different kinds of messages. + +Information about dependencies in the Makefile-compatible format is stored in +the `.d` files alongside the artifacts. + + +### Custom subcommands + +Cargo is designed to be extensible with new subcommands without having to modify +Cargo itself. This is achieved by translating a cargo invocation of the form +cargo `(?[^ ]+)` into an invocation of an external tool +`cargo-${command}` that then needs to be present in one of the user's `$PATH` +directories. + +Custom subcommand may use `CARGO` environment variable to call back to +Cargo. Alternatively, it can link to `cargo` crate as a library, but this +approach has drawbacks: + +* Cargo as a library is unstable, API changes without deprecation, + +* versions of Cargo library and Cargo binary may be different. diff -Nru cargo-0.25.0/src/doc/src/reference/index.md cargo-0.26.0/src/doc/src/reference/index.md --- cargo-0.25.0/src/doc/src/reference/index.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/reference/index.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,13 @@ +## Cargo Reference + +The reference covers the details of various areas of Cargo. + +* [Specifying Dependencies](reference/specifying-dependencies.html) +* [The Manifest Format](reference/manifest.html) +* [Configuration](reference/config.html) +* [Environment Variables](reference/environment-variables.html) +* [Build Scripts](reference/build-scripts.html) +* [Publishing on crates.io](reference/publishing.html) +* [Package ID Specifications](reference/pkgid-spec.html) +* [Source Replacement](reference/source-replacement.html) +* [External Tools](reference/external-tools.html) diff -Nru cargo-0.25.0/src/doc/src/reference/manifest.md cargo-0.26.0/src/doc/src/reference/manifest.md --- cargo-0.25.0/src/doc/src/reference/manifest.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/reference/manifest.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,825 @@ +## The Manifest Format + +The `Cargo.toml` file for each package is called its *manifest*. Every manifest +file consists of one or more sections. + +### The `[package]` section + +The first section in a `Cargo.toml` is `[package]`. + +```toml +[package] +name = "hello_world" # the name of the package +version = "0.1.0" # the current version, obeying semver +authors = ["you@example.com"] +``` + +All three of these fields are mandatory. + +#### The `version` field + +Cargo bakes in the concept of [Semantic +Versioning](http://semver.org/), so make sure you follow some basic rules: + +* Before you reach 1.0.0, anything goes, but if you make breaking changes, + increment the minor version. In Rust, breaking changes include adding fields to + structs or variants to enums. +* After 1.0.0, only make breaking changes when you increment the major version. + Don’t break the build. +* After 1.0.0, don’t add any new public API (no new `pub` anything) in tiny + versions. Always increment the minor version if you add any new `pub` structs, + traits, fields, types, functions, methods or anything else. +* Use version numbers with three numeric parts such as 1.0.0 rather than 1.0. + +#### The `build` field (optional) + +This field specifies a file in the project root which is a [build script][1] for +building native code. More information can be found in the build script +[guide][1]. + +[1]: reference/build-scripts.html + +```toml +[package] +# ... +build = "build.rs" +``` + +#### The `documentation` field (optional) + +This field specifies a URL to a website hosting the crate's documentation. +If no URL is specified in the manifest file, [crates.io][cratesio] will +automatically link your crate to the corresponding [docs.rs][docsrs] page. + +Documentation links from specific hosts are blacklisted. Hosts are added +to the blacklist if they are known to not be hosting documentation and are +possibly of malicious intent e.g. ad tracking networks. URLs from the +following hosts are blacklisted: + +* rust-ci.org + +Documentation URLs from blacklisted hosts will not appear on crates.io, and +may be replaced by docs.rs links. + +[docsrs]: https://docs.rs/ +[cratesio]: https://crates.io/ + +#### The `exclude` and `include` fields (optional) + +You can explicitly specify to Cargo that a set of [globs][globs] should be +ignored or included for the purposes of packaging and rebuilding a package. The +globs specified in the `exclude` field identify a set of files that are not +included when a package is published as well as ignored for the purposes of +detecting when to rebuild a package, and the globs in `include` specify files +that are explicitly included. + +If a VCS is being used for a package, the `exclude` field will be seeded with +the VCS’ ignore settings (`.gitignore` for git for example). + +```toml +[package] +# ... +exclude = ["build/**/*.o", "doc/**/*.html"] +``` + +```toml +[package] +# ... +include = ["src/**/*", "Cargo.toml"] +``` + +The options are mutually exclusive: setting `include` will override an +`exclude`. Note that `include` must be an exhaustive list of files as otherwise +necessary source files may not be included. + +[globs]: http://doc.rust-lang.org/glob/glob/struct.Pattern.html + +#### Migrating to `gitignore`-like pattern matching + +The current interpretation of these configs is based on UNIX Globs, as +implemented in the [`glob` crate](https://crates.io/crates/glob). We want +Cargo's `include` and `exclude` configs to work as similar to `gitignore` as +possible. [The `gitignore` specification](https://git-scm.com/docs/gitignore) is +also based on Globs, but has a bunch of additional features that enable easier +pattern writing and more control. Therefore, we are migrating the interpretation +for the rules of these configs to use the [`ignore` +crate](https://crates.io/crates/ignore), and treat them each rule as a single +line in a `gitignore` file. See [the tracking +issue](https://github.com/rust-lang/cargo/issues/4268) for more details on the +migration. + +#### The `publish` field (optional) + +The `publish` field can be used to prevent a package from being published to a +package registry (like *crates.io*) by mistake. + +```toml +[package] +# ... +publish = false +``` + +#### The `workspace` field (optional) + +The `workspace` field can be used to configure the workspace that this package +will be a member of. If not specified this will be inferred as the first +Cargo.toml with `[workspace]` upwards in the filesystem. + +```toml +[package] +# ... +workspace = "path/to/workspace/root" +``` + +For more information, see the documentation for the workspace table below. + +#### Package metadata + +There are a number of optional metadata fields also accepted under the +`[package]` section: + +```toml +[package] +# ... + +# A short blurb about the package. This is not rendered in any format when +# uploaded to crates.io (aka this is not markdown). +description = "..." + +# These URLs point to more information about the package. These are +# intended to be webviews of the relevant data, not necessarily compatible +# with VCS tools and the like. +documentation = "..." +homepage = "..." +repository = "..." + +# This points to a file under the package root (relative to this `Cargo.toml`). +# The contents of this file are stored and indexed in the registry. +# crates.io will render this file and place the result on the crate's page. +readme = "..." + +# This is a list of up to five keywords that describe this crate. Keywords +# are searchable on crates.io, and you may choose any words that would +# help someone find this crate. +keywords = ["...", "..."] + +# This is a list of up to five categories where this crate would fit. +# Categories are a fixed list available at crates.io/category_slugs, and +# they must match exactly. +categories = ["...", "..."] + +# This is an SPDX 2.1 license expression for this package. Currently +# crates.io will validate the license provided against a whitelist of +# known license and exception identifiers from the SPDX license list +# 2.4. Parentheses are not currently supported. +# +# Multiple licenses can be separated with a `/`, although that usage +# is deprecated. Instead, use a license expression with AND and OR +# operators to get more explicit semantics. +license = "..." + +# If a project is using a nonstandard license, then this key may be specified in +# lieu of the above key and must point to a file relative to this manifest +# (similar to the readme key). +license-file = "..." + +# Optional specification of badges to be displayed on crates.io. +# +# - The badges pertaining to build status that are currently available are +# Appveyor, CircleCI, GitLab, and TravisCI. +# - Available badges pertaining to code test coverage are Codecov and +# Coveralls. +# - There are also maintenance-related badges based on isitmaintained.com +# which state the issue resolution time, percent of open issues, and future +# maintenance intentions. +# +# If a `repository` key is required, this refers to a repository in +# `user/repo` format. +[badges] + +# Appveyor: `repository` is required. `branch` is optional; default is `master` +# `service` is optional; valid values are `github` (default), `bitbucket`, and +# `gitlab`; `id` is optional; you can specify the appveyor project id if you +# want to use that instead. `project_name` is optional; use when the repository +# name differs from the appveyor project name. +appveyor = { repository = "...", branch = "master", service = "github" } + +# Circle CI: `repository` is required. `branch` is optional; default is `master` +circle-ci = { repository = "...", branch = "master" } + +# GitLab: `repository` is required. `branch` is optional; default is `master` +gitlab = { repository = "...", branch = "master" } + +# Travis CI: `repository` in format "/" is required. +# `branch` is optional; default is `master` +travis-ci = { repository = "...", branch = "master" } + +# Codecov: `repository` is required. `branch` is optional; default is `master` +# `service` is optional; valid values are `github` (default), `bitbucket`, and +# `gitlab`. +codecov = { repository = "...", branch = "master", service = "github" } + +# Coveralls: `repository` is required. `branch` is optional; default is `master` +# `service` is optional; valid values are `github` (default) and `bitbucket`. +coveralls = { repository = "...", branch = "master", service = "github" } + +# Is it maintained resolution time: `repository` is required. +is-it-maintained-issue-resolution = { repository = "..." } + +# Is it maintained percentage of open issues: `repository` is required. +is-it-maintained-open-issues = { repository = "..." } + +# Maintenance: `status` is required Available options are `actively-developed`, +# `passively-maintained`, `as-is`, `none`, `experimental`, `looking-for-maintainer` +# and `deprecated`. +maintenance = { status = "..." } +``` + +The [crates.io](https://crates.io) registry will render the description, display +the license, link to the three URLs and categorize by the keywords. These keys +provide useful information to users of the registry and also influence the +search ranking of a crate. It is highly discouraged to omit everything in a +published crate. + +SPDX 2.1 license expressions are documented +[here][spdx-2.1-license-expressions]. The current version of the +license list is available [here][spdx-license-list], and version 2.4 +is available [here][spdx-license-list-2.4]. + +#### The `metadata` table (optional) + +Cargo by default will warn about unused keys in `Cargo.toml` to assist in +detecting typos and such. The `package.metadata` table, however, is completely +ignored by Cargo and will not be warned about. This section can be used for +tools which would like to store project configuration in `Cargo.toml`. For +example: + +```toml +[package] +name = "..." +# ... + +# Metadata used when generating an Android APK, for example. +[package.metadata.android] +package-name = "my-awesome-android-app" +assets = "path/to/static" +``` + +### Dependency sections + +See the [specifying dependencies page](reference/specifying-dependencies.html) for +information on the `[dependencies]`, `[dev-dependencies]`, +`[build-dependencies]`, and target-specific `[target.*.dependencies]` sections. + +### The `[profile.*]` sections + +Cargo supports custom configuration of how rustc is invoked through profiles at +the top level. Any manifest may declare a profile, but only the top level +project’s profiles are actually read. All dependencies’ profiles will be +overridden. This is done so the top-level project has control over how its +dependencies are compiled. + +There are five currently supported profile names, all of which have the same +configuration available to them. Listed below is the configuration available, +along with the defaults for each profile. + +```toml +# The development profile, used for `cargo build`. +[profile.dev] +opt-level = 0 # controls the `--opt-level` the compiler builds with. + # 0-1 is good for debugging. 2 is well-optimized. Max is 3. +debug = true # include debug information (debug symbols). Equivalent to + # `-C debuginfo=2` compiler flag. +rpath = false # controls whether compiler should set loader paths. + # If true, passes `-C rpath` flag to the compiler. +lto = false # Link Time Optimization usually reduces size of binaries + # and static libraries. Increases compilation time. + # If true, passes `-C lto` flag to the compiler, and if a + # string is specified like 'thin' then `-C lto=thin` will + # be passed +debug-assertions = true # controls whether debug assertions are enabled + # (e.g. debug_assert!() and arithmetic overflow checks) +codegen-units = 1 # if > 1 enables parallel code generation which improves + # compile times, but prevents some optimizations. + # Passes `-C codegen-units`. +panic = 'unwind' # panic strategy (`-C panic=...`), can also be 'abort' +incremental = true # whether or not incremental compilation is enabled +overflow-checks = true # use overflow checks for integer arithmetic. + # Passes the `-C overflow-checks=...` flag to the compiler. + +# The release profile, used for `cargo build --release`. +[profile.release] +opt-level = 3 +debug = false +rpath = false +lto = false +debug-assertions = false +codegen-units = 1 +panic = 'unwind' +incremental = false +overflow-checks = false + +# The testing profile, used for `cargo test`. +[profile.test] +opt-level = 0 +debug = 2 +rpath = false +lto = false +debug-assertions = true +codegen-units = 1 +panic = 'unwind' +incremental = true +overflow-checks = true + +# The benchmarking profile, used for `cargo bench` and `cargo test --release`. +[profile.bench] +opt-level = 3 +debug = false +rpath = false +lto = false +debug-assertions = false +codegen-units = 1 +panic = 'unwind' +incremental = false +overflow-checks = false + +# The documentation profile, used for `cargo doc`. +[profile.doc] +opt-level = 0 +debug = 2 +rpath = false +lto = false +debug-assertions = true +codegen-units = 1 +panic = 'unwind' +incremental = true +overflow-checks = true +``` + +### The `[features]` section + +Cargo supports features to allow expression of: + +* conditional compilation options (usable through `cfg` attributes); +* optional dependencies, which enhance a package, but are not required; and +* clusters of optional dependencies, such as `postgres`, that would include the + `postgres` package, the `postgres-macros` package, and possibly other packages + (such as development-time mocking libraries, debugging tools, etc.). + +A feature of a package is either an optional dependency, or a set of other +features. The format for specifying features is: + +```toml +[package] +name = "awesome" + +[features] +# The default set of optional packages. Most people will want to use these +# packages, but they are strictly optional. Note that `session` is not a package +# but rather another feature listed in this manifest. +default = ["jquery", "uglifier", "session"] + +# A feature with no dependencies is used mainly for conditional compilation, +# like `#[cfg(feature = "go-faster")]`. +go-faster = [] + +# The `secure-password` feature depends on the bcrypt package. This aliasing +# will allow people to talk about the feature in a higher-level way and allow +# this package to add more requirements to the feature in the future. +secure-password = ["bcrypt"] + +# Features can be used to reexport features of other packages. The `session` +# feature of package `awesome` will ensure that the `session` feature of the +# package `cookie` is also enabled. +session = ["cookie/session"] + +[dependencies] +# These packages are mandatory and form the core of this package’s distribution. +cookie = "1.2.0" +oauth = "1.1.0" +route-recognizer = "=2.1.0" + +# A list of all of the optional dependencies, some of which are included in the +# above `features`. They can be opted into by apps. +jquery = { version = "1.0.2", optional = true } +uglifier = { version = "1.5.3", optional = true } +bcrypt = { version = "*", optional = true } +civet = { version = "*", optional = true } +``` + +To use the package `awesome`: + +```toml +[dependencies.awesome] +version = "1.3.5" +default-features = false # do not include the default features, and optionally + # cherry-pick individual features +features = ["secure-password", "civet"] +``` + +#### Rules + +The usage of features is subject to a few rules: + +* Feature names must not conflict with other package names in the manifest. This + is because they are opted into via `features = [...]`, which only has a single + namespace. +* With the exception of the `default` feature, all features are opt-in. To opt + out of the default feature, use `default-features = false` and cherry-pick + individual features. +* Feature groups are not allowed to cyclically depend on one another. +* Dev-dependencies cannot be optional. +* Features groups can only reference optional dependencies. +* When a feature is selected, Cargo will call `rustc` with `--cfg + feature="${feature_name}"`. If a feature group is included, it and all of its + individual features will be included. This can be tested in code via + `#[cfg(feature = "foo")]`. + +Note that it is explicitly allowed for features to not actually activate any +optional dependencies. This allows packages to internally enable/disable +features without requiring a new dependency. + +#### Usage in end products + +One major use-case for this feature is specifying optional features in +end-products. For example, the Servo project may want to include optional +features that people can enable or disable when they build it. + +In that case, Servo will describe features in its `Cargo.toml` and they can be +enabled using command-line flags: + +```console +$ cargo build --release --features "shumway pdf" +``` + +Default features could be excluded using `--no-default-features`. + +#### Usage in packages + +In most cases, the concept of *optional dependency* in a library is best +expressed as a separate package that the top-level application depends on. + +However, high-level packages, like Iron or Piston, may want the ability to +curate a number of packages for easy installation. The current Cargo system +allows them to curate a number of mandatory dependencies into a single package +for easy installation. + +In some cases, packages may want to provide additional curation for optional +dependencies: + +* grouping a number of low-level optional dependencies together into a single + high-level feature; +* specifying packages that are recommended (or suggested) to be included by + users of the package; and +* including a feature (like `secure-password` in the motivating example) that + will only work if an optional dependency is available, and would be difficult + to implement as a separate package (for example, it may be overly difficult to + design an IO package to be completely decoupled from OpenSSL, with opt-in via + the inclusion of a separate package). + +In almost all cases, it is an antipattern to use these features outside of +high-level packages that are designed for curation. If a feature is optional, it +can almost certainly be expressed as a separate package. + +### The `[workspace]` section + +Projects can define a workspace which is a set of crates that will all share the +same `Cargo.lock` and output directory. The `[workspace]` table can be defined +as: + +```toml +[workspace] + +# Optional key, inferred from path dependencies if not present. +# Additional non-path dependencies that should be included must be given here. +# In particular, for a virtual manifest, all members have to be listed. +members = ["path/to/member1", "path/to/member2", "path/to/member3/*"] + +# Optional key, empty if not present. +exclude = ["path1", "path/to/dir2"] +``` + +Workspaces were added to Cargo as part of [RFC 1525] and have a number of +properties: + +* A workspace can contain multiple crates where one of them is the *root crate*. +* The *root crate*'s `Cargo.toml` contains the `[workspace]` table, but is not + required to have other configuration. +* Whenever any crate in the workspace is compiled, output is placed in the + *workspace root*. i.e. next to the *root crate*'s `Cargo.toml`. +* The lock file for all crates in the workspace resides in the *workspace root*. +* The `[patch]`, `[replace]` and `[profile.*]` sections in `Cargo.toml` + are only recognized + in the *root crate*'s manifest, and ignored in member crates' manifests. + +[RFC 1525]: https://github.com/rust-lang/rfcs/blob/master/text/1525-cargo-workspace.md + +The *root crate* of a workspace, indicated by the presence of `[workspace]` in +its manifest, is responsible for defining the entire workspace. All `path` +dependencies residing in the workspace directory become members. You can add +additional packages to the workspace by listing them in the `members` key. Note +that members of the workspaces listed explicitly will also have their path +dependencies included in the workspace. Sometimes a project may have a lot of +workspace members and it can be onerous to keep up to date. The path dependency +can also use [globs][globs] to match multiple paths. Finally, the `exclude` +key can be used to blacklist paths from being included in a workspace. This can +be useful if some path dependencies aren't desired to be in the workspace at +all. + +The `package.workspace` manifest key (described above) is used in member crates +to point at a workspace's root crate. If this key is omitted then it is inferred +to be the first crate whose manifest contains `[workspace]` upwards in the +filesystem. + +A crate may either specify `package.workspace` or specify `[workspace]`. That +is, a crate cannot both be a root crate in a workspace (contain `[workspace]`) +and also be a member crate of another workspace (contain `package.workspace`). + +Most of the time workspaces will not need to be dealt with as `cargo new` and +`cargo init` will handle workspace configuration automatically. + +#### Virtual Manifest + +In workspace manifests, if the `package` table is present, the workspace root +crate will be treated as a normal package, as well as a workspace. If the +`package` table is not present in a workspace manifest, it is called a *virtual +manifest*. + +#### Package selection + +In a workspace, package-related cargo commands like `cargo build` apply to +packages selected by `-p` / `--package` or `--all` command-line parameters. +When neither is specified, the optional `default-members` configuration is used: + +```toml +[workspace] +members = ["path/to/member1", "path/to/member2", "path/to/member3/*"] +default-members = ["path/to/member2", "path/to/member3/foo"] +``` + +When specified, `default-members` must expand to a subset of `members`. + +When `default-members` is not specified, the default is the root manifest +if it is a package, or every member manifest (as if `--all` were specified +on the command-line) for virtual workspaces. + +#TODO: move this to a more appropriate place +### The project layout + +If your project is an executable, name the main source file `src/main.rs`. If it +is a library, name the main source file `src/lib.rs`. + +Cargo will also treat any files located in `src/bin/*.rs` as executables. If your +executable consists of more than just one source file, you might also use a directory +inside `src/bin` containing a `main.rs` file which will be treated as an executable +with a name of the parent directory. +Do note, however, once you add a `[[bin]]` section ([see +below](#configuring-a-target)), Cargo will no longer automatically build files +located in `src/bin/*.rs`. Instead you must create a `[[bin]]` section for +each file you want to build. + +Your project can optionally contain folders named `examples`, `tests`, and +`benches`, which Cargo will treat as containing examples, +integration tests, and benchmarks respectively. Analogous to `bin` targets, they +may be composed of single files or directories with a `main.rs` file. + +``` +▾ src/ # directory containing source files + lib.rs # the main entry point for libraries and packages + main.rs # the main entry point for projects producing executables + ▾ bin/ # (optional) directory containing additional executables + *.rs + ▾ */ # (optional) directories containing multi-file executables + main.rs +▾ examples/ # (optional) examples + *.rs +▾ */ # (optional) directories containing multi-file examples + main.rs +▾ tests/ # (optional) integration tests + *.rs +▾ */ # (optional) directories containing multi-file tests + main.rs +▾ benches/ # (optional) benchmarks + *.rs +▾ */ # (optional) directories containing multi-file benchmarks + main.rs +``` + +To structure your code after you've created the files and folders for your +project, you should remember to use Rust's module system, which you can read +about in [the book](https://doc.rust-lang.org/book/crates-and-modules.html). + +### Examples + +Files located under `examples` are example uses of the functionality provided by +the library. When compiled, they are placed in the `target/examples` directory. + +They can compile either as executables (with a `main()` function) or libraries +and pull in the library by using `extern crate `. They are +compiled when you run your tests to protect them from bitrotting. + +You can run individual executable examples with the command `cargo run --example +`. + +Specify `crate-type` to make an example be compiled as a library (additional +information about crate types is available in +[the Cargo reference](https://doc.rust-lang.org/reference/linkage.html)): + +```toml +[[example]] +name = "foo" +crate-type = ["staticlib"] +``` + +You can build individual library examples with the command `cargo build +--example `. + +### Tests + +When you run `cargo test`, Cargo will: + +* compile and run your library’s unit tests, which are in the files reachable + from `lib.rs` (naturally, any sections marked with `#[cfg(test)]` will be + considered at this stage); +* compile and run your library’s documentation tests, which are embedded inside + of documentation blocks; +* compile and run your library’s [integration tests](#integration-tests); and +* compile your library’s examples. + +#### Integration tests + +Each file in `tests/*.rs` is an integration test. When you run `cargo test`, +Cargo will compile each of these files as a separate crate. The crate can link +to your library by using `extern crate `, like any other code that +depends on it. + +Cargo will not automatically compile files inside subdirectories of `tests`, but +an integration test can import modules from these directories as usual. For +example, if you want several integration tests to share some code, you can put +the shared code in `tests/common/mod.rs` and then put `mod common;` in each of +the test files. + +### Configuring a target + +All of the `[[bin]]`, `[lib]`, `[[bench]]`, `[[test]]`, and `[[example]]` +sections support similar configuration for specifying how a target should be +built. The double-bracket sections like `[[bin]]` are array-of-table of +[TOML](https://github.com/toml-lang/toml#array-of-tables), which means you can +write more than one `[[bin]]` section to make several executables in your crate. + +The example below uses `[lib]`, but it also applies to all other sections +as well. All values listed are the defaults for that option unless otherwise +specified. + +```toml +[package] +# ... + +[lib] +# The name of a target is the name of the library that will be generated. This +# is defaulted to the name of the package or project, with any dashes replaced +# with underscores. (Rust `extern crate` declarations reference this name; +# therefore the value must be a valid Rust identifier to be usable.) +name = "foo" + +# This field points at where the crate is located, relative to the `Cargo.toml`. +path = "src/lib.rs" + +# A flag for enabling unit tests for this target. This is used by `cargo test`. +test = true + +# A flag for enabling documentation tests for this target. This is only relevant +# for libraries, it has no effect on other sections. This is used by +# `cargo test`. +doctest = true + +# A flag for enabling benchmarks for this target. This is used by `cargo bench`. +bench = true + +# A flag for enabling documentation of this target. This is used by `cargo doc`. +doc = true + +# If the target is meant to be a compiler plugin, this field must be set to true +# for Cargo to correctly compile it and make it available for all dependencies. +plugin = false + +# If the target is meant to be a "macros 1.1" procedural macro, this field must +# be set to true. +proc-macro = false + +# If set to false, `cargo test` will omit the `--test` flag to rustc, which +# stops it from generating a test harness. This is useful when the binary being +# built manages the test runner itself. +harness = true +``` + +#### The `required-features` field (optional) + +The `required-features` field specifies which features the target needs in order +to be built. If any of the required features are not selected, the target will +be skipped. This is only relevant for the `[[bin]]`, `[[bench]]`, `[[test]]`, +and `[[example]]` sections, it has no effect on `[lib]`. + +```toml +[features] +# ... +postgres = [] +sqlite = [] +tools = [] + +[[bin]] +# ... +required-features = ["postgres", "tools"] +``` + +#### Building dynamic or static libraries + +If your project produces a library, you can specify which kind of library to +build by explicitly listing the library in your `Cargo.toml`: + +```toml +# ... + +[lib] +name = "..." +crate-type = ["dylib"] # could be `staticlib` as well +``` + +The available options are `dylib`, `rlib`, `staticlib`, `cdylib`, and +`proc-macro`. You should only use this option in a project. Cargo will always +compile packages (dependencies) based on the requirements of the project that +includes them. + +You can read more about the different crate types in the +[Rust Reference Manual](https://doc.rust-lang.org/reference/linkage.html) + +### The `[patch]` Section + +This section of Cargo.toml can be used to [override dependencies][replace] with +other copies. The syntax is similar to the `[dependencies]` section: + +```toml +[patch.crates-io] +foo = { git = 'https://github.com/example/foo' } +bar = { path = 'my/local/bar' } + +[dependencies.baz] +git = 'https://github.com/example/baz' + +[patch.'https://github.com/example/baz'] +baz = { git = 'https://github.com/example/patched-baz', branch = 'my-branch' } +``` + +The `[patch]` table is made of dependency-like sub-tables. Each key after +`[patch]` is a URL of the source that's being patched, or `crates-io` if +you're modifying the https://crates.io registry. In the example above +`crates-io` could be replaced with a git URL such as +`https://github.com/rust-lang-nursery/log`; the second `[patch]` +section in the example uses this to specify a source called `baz`. + +Each entry in these tables is a normal dependency specification, the same as +found in the `[dependencies]` section of the manifest. The dependencies listed +in the `[patch]` section are resolved and used to patch the source at the +URL specified. The above manifest snippet patches the `crates-io` source (e.g. +crates.io itself) with the `foo` crate and `bar` crate. It also +patches the `https://github.com/example/baz` source with a `my-branch` that +comes from elsewhere. + +Sources can be patched with versions of crates that do not exist, and they can +also be patched with versions of crates that already exist. If a source is +patched with a crate version that already exists in the source, then the +source's original crate is replaced. + +More information about overriding dependencies can be found in the [overriding +dependencies][replace] section of the documentation and [RFC 1969] for the +technical specification of this feature. (Note that the `[patch]` feature will +first become available in Rust 1.21, set to be released on 2017-10-12.) + +[RFC 1969]: https://github.com/rust-lang/rfcs/pull/1969 +[replace]: reference/specifying-dependencies.html#overriding-dependencies + +### The `[replace]` Section + +This section of Cargo.toml can be used to [override dependencies][replace] with +other copies. The syntax is similar to the `[dependencies]` section: + +```toml +[replace] +"foo:0.1.0" = { git = 'https://github.com/example/foo' } +"bar:1.0.2" = { path = 'my/local/bar' } +``` + +Each key in the `[replace]` table is a [package id +specification](reference/pkgid-spec.html) which allows arbitrarily choosing a node in the +dependency graph to override. The value of each key is the same as the +`[dependencies]` syntax for specifying dependencies, except that you can't +specify features. Note that when a crate is overridden the copy it's overridden +with must have both the same name and version, but it can come from a different +source (e.g. git or a local path). + +More information about overriding dependencies can be found in the [overriding +dependencies][replace] section of the documentation. + +[spdx-2.1-license-expressions]: https://spdx.org/spdx-specification-21-web-version#h.jxpfx0ykyb60 +[spdx-license-list]: https://spdx.org/licenses/ +[spdx-license-list-2.4]: https://github.com/spdx/license-list-data/tree/v2.4 diff -Nru cargo-0.25.0/src/doc/src/reference/pkgid-spec.md cargo-0.26.0/src/doc/src/reference/pkgid-spec.md --- cargo-0.25.0/src/doc/src/reference/pkgid-spec.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/reference/pkgid-spec.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,44 @@ +## Package ID Specifications + +### Package ID specifications + +Subcommands of Cargo frequently need to refer to a particular package within a +dependency graph for various operations like updating, cleaning, building, etc. +To solve this problem, Cargo supports Package ID Specifications. A specification +is a string which is used to uniquely refer to one package within a graph of +packages. + +#### Specification grammar + +The formal grammar for a Package Id Specification is: + +```notrust +pkgid := pkgname + | [ proto "://" ] hostname-and-path [ "#" ( pkgname | semver ) ] +pkgname := name [ ":" semver ] + +proto := "http" | "git" | ... +``` + +Here, brackets indicate that the contents are optional. + +#### Example specifications + +These could all be references to a package `foo` version `1.2.3` from the +registry at `crates.io` + +| pkgid | name | version | url | +|:-----------------------------|:-----:|:-------:|:----------------------:| +| `foo` | `foo` | `*` | `*` | +| `foo:1.2.3` | `foo` | `1.2.3` | `*` | +| `crates.io/foo` | `foo` | `*` | `*://crates.io/foo` | +| `crates.io/foo#1.2.3` | `foo` | `1.2.3` | `*://crates.io/foo` | +| `crates.io/bar#foo:1.2.3` | `foo` | `1.2.3` | `*://crates.io/bar` | +| `http://crates.io/foo#1.2.3` | `foo` | `1.2.3` | `http://crates.io/foo` | + +#### Brevity of specifications + +The goal of this is to enable both succinct and exhaustive syntaxes for +referring to packages in a dependency graph. Ambiguous references may refer to +one or more packages. Most commands generate an error if more than one package +could be referred to with the same specification. diff -Nru cargo-0.25.0/src/doc/src/reference/publishing.md cargo-0.26.0/src/doc/src/reference/publishing.md --- cargo-0.25.0/src/doc/src/reference/publishing.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/reference/publishing.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,222 @@ +## Publishing on crates.io + +Once you've got a library that you'd like to share with the world, it's time to +publish it on [crates.io]! Publishing a crate is when a specific +version is uploaded to be hosted on [crates.io]. + +Take care when publishing a crate, because a publish is **permanent**. The +version can never be overwritten, and the code cannot be deleted. There is no +limit to the number of versions which can be published, however. + +### Before your first publish + +First thing’s first, you’ll need an account on [crates.io] to acquire +an API token. To do so, [visit the home page][crates.io] and log in via a GitHub +account (required for now). After this, visit your [Account +Settings](https://crates.io/me) page and run the `cargo login` command +specified. + +```console +$ cargo login abcdefghijklmnopqrstuvwxyz012345 +``` + +This command will inform Cargo of your API token and store it locally in your +`~/.cargo/credentials` (previously it was `~/.cargo/config`). Note that this +token is a **secret** and should not be shared with anyone else. If it leaks for +any reason, you should regenerate it immediately. + +### Before publishing a new crate + +Keep in mind that crate names on [crates.io] are allocated on a first-come-first- +serve basis. Once a crate name is taken, it cannot be used for another crate. + +#### Packaging a crate + +The next step is to package up your crate into a format that can be uploaded to +[crates.io]. For this we’ll use the `cargo package` subcommand. This will take +our entire crate and package it all up into a `*.crate` file in the +`target/package` directory. + +```console +$ cargo package +``` + +As an added bonus, the `*.crate` will be verified independently of the current +source tree. After the `*.crate` is created, it’s unpacked into +`target/package` and then built from scratch to ensure that all necessary files +are there for the build to succeed. This behavior can be disabled with the +`--no-verify` flag. + +Now’s a good time to take a look at the `*.crate` file to make sure you didn’t +accidentally package up that 2GB video asset, or large data files used for code +generation, integration tests, or benchmarking. There is currently a 10MB +upload size limit on `*.crate` files. So, if the size of `tests` and `benches` +directories and their dependencies are up to a couple of MBs, you can keep them +in your package; otherwise, better to exclude them. + +Cargo will automatically ignore files ignored by your version control system +when packaging, but if you want to specify an extra set of files to ignore you +can use the `exclude` key in the manifest: + +```toml +[package] +# ... +exclude = [ + "public/assets/*", + "videos/*", +] +``` + +The syntax of each element in this array is what +[rust-lang/glob](https://github.com/rust-lang/glob) accepts. If you’d rather +roll with a whitelist instead of a blacklist, Cargo also supports an `include` +key, which if set, overrides the `exclude` key: + +```toml +[package] +# ... +include = [ + "**/*.rs", + "Cargo.toml", +] +``` + +### Uploading the crate + +Now that we’ve got a `*.crate` file ready to go, it can be uploaded to +[crates.io] with the `cargo publish` command. And that’s it, you’ve now published +your first crate! + +```console +$ cargo publish +``` + +If you’d like to skip the `cargo package` step, the `cargo publish` subcommand +will automatically package up the local crate if a copy isn’t found already. + +Be sure to check out the [metadata you can +specify](reference/manifest.html#package-metadata) to ensure your crate can be +discovered more easily! + +### Publishing a new version of an existing crate + +In order to release a new version, change the `version` value specified in your +`Cargo.toml` manifest. Keep in mind [the semver +rules](reference/manifest.html#the-version-field). Then optionally run `cargo package` if +you want to inspect the `*.crate` file for the new version before publishing, +and run `cargo publish` to upload the new version. + +### Managing a crates.io-based crate + +Management of crates is primarily done through the command line `cargo` tool +rather than the [crates.io] web interface. For this, there are a few subcommands +to manage a crate. + +#### `cargo yank` + +Occasions may arise where you publish a version of a crate that actually ends up +being broken for one reason or another (syntax error, forgot to include a file, +etc.). For situations such as this, Cargo supports a “yank” of a version of a +crate. + +```console +$ cargo yank --vers 1.0.1 +$ cargo yank --vers 1.0.1 --undo +``` + +A yank **does not** delete any code. This feature is not intended for deleting +accidentally uploaded secrets, for example. If that happens, you must reset +those secrets immediately. + +The semantics of a yanked version are that no new dependencies can be created +against that version, but all existing dependencies continue to work. One of the +major goals of [crates.io] is to act as a permanent archive of crates that does +not change over time, and allowing deletion of a version would go against this +goal. Essentially a yank means that all projects with a `Cargo.lock` will not +break, while any future `Cargo.lock` files generated will not list the yanked +version. + +#### `cargo owner` + +A crate is often developed by more than one person, or the primary maintainer +may change over time! The owner of a crate is the only person allowed to publish +new versions of the crate, but an owner may designate additional owners. + +```console +$ cargo owner --add my-buddy +$ cargo owner --remove my-buddy +$ cargo owner --add github:rust-lang:owners +$ cargo owner --remove github:rust-lang:owners +``` + +The owner IDs given to these commands must be GitHub user names or GitHub teams. + +If a user name is given to `--add`, that user becomes a “named” owner, with +full rights to the crate. In addition to being able to publish or yank versions +of the crate, they have the ability to add or remove owners, *including* the +owner that made *them* an owner. Needless to say, you shouldn’t make people you +don’t fully trust into a named owner. In order to become a named owner, a user +must have logged into [crates.io] previously. + +If a team name is given to `--add`, that team becomes a “team” owner, with +restricted right to the crate. While they have permission to publish or yank +versions of the crate, they *do not* have the ability to add or remove owners. +In addition to being more convenient for managing groups of owners, teams are +just a bit more secure against owners becoming malicious. + +The syntax for teams is currently `github:org:team` (see examples above). +In order to add a team as an owner one must be a member of that team. No +such restriction applies to removing a team as an owner. + +### GitHub permissions + +Team membership is not something GitHub provides simple public access to, and it +is likely for you to encounter the following message when working with them: + +> It looks like you don’t have permission to query a necessary property from +GitHub to complete this request. You may need to re-authenticate on [crates.io] +to grant permission to read GitHub org memberships. Just go to +https://crates.io/login + +This is basically a catch-all for “you tried to query a team, and one of the +five levels of membership access control denied this”. That is not an +exaggeration. GitHub’s support for team access control is Enterprise Grade. + +The most likely cause of this is simply that you last logged in before this +feature was added. We originally requested *no* permissions from GitHub when +authenticating users, because we didn’t actually ever use the user’s token for +anything other than logging them in. However to query team membership on your +behalf, we now require +[the `read:org` scope](https://developer.github.com/v3/oauth/#scopes). + +You are free to deny us this scope, and everything that worked before teams +were introduced will keep working. However you will never be able to add a team +as an owner, or publish a crate as a team owner. If you ever attempt to do this, +you will get the error above. You may also see this error if you ever try to +publish a crate that you don’t own at all, but otherwise happens to have a team. + +If you ever change your mind, or just aren’t sure if [crates.io] has sufficient +permission, you can always go to https://crates.io/login, which will prompt you +for permission if [crates.io] doesn’t have all the scopes it would like to. + +An additional barrier to querying GitHub is that the organization may be +actively denying third party access. To check this, you can go to: + + https://github.com/organizations/:org/settings/oauth_application_policy + +where `:org` is the name of the organization (e.g. rust-lang). You may see +something like: + +![Organization Access Control](images/org-level-acl.png) + +Where you may choose to explicitly remove [crates.io] from your organization’s +blacklist, or simply press the “Remove Restrictions” button to allow all third +party applications to access this data. + +Alternatively, when [crates.io] requested the `read:org` scope, you could have +explicitly whitelisted [crates.io] querying the org in question by pressing +the “Grant Access” button next to its name: + +![Authentication Access Control](images/auth-level-acl.png) + +[crates.io]: https://crates.io/ diff -Nru cargo-0.25.0/src/doc/src/reference/source-replacement.md cargo-0.26.0/src/doc/src/reference/source-replacement.md --- cargo-0.25.0/src/doc/src/reference/source-replacement.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/reference/source-replacement.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,134 @@ +## Source Replacement + +Cargo supports the ability to **replace one source with another** to express +strategies along the lines of mirrors or vendoring dependencies. Configuration +is currently done through the [`.cargo/config` configuration][config] mechanism, +like so: + +[config]: reference/config.html + +```toml +# The `source` table is where all keys related to source-replacement +# are stored. +[source] + +# Under the `source` table are a number of other tables whose keys are a +# name for the relevant source. For example this section defines a new +# source, called `my-awesome-source`, which comes from a directory +# located at `vendor` relative to the directory containing this `.cargo/config` +# file +[source.my-awesome-source] +directory = "vendor" + +# Git sources can optionally specify a branch/tag/rev as well +git = "https://example.com/path/to/repo" +# branch = "master" +# tag = "v1.0.1" +# rev = "313f44e8" + +# The crates.io default source for crates is available under the name +# "crates-io", and here we use the `replace-with` key to indicate that it's +# replaced with our source above. +[source.crates-io] +replace-with = "my-awesome-source" +``` + +With this configuration Cargo attempts to look up all crates in the directory +"vendor" rather than querying the online registry at crates.io. Using source +replacement Cargo can express: + +* Vendoring - custom sources can be defined which represent crates on the local + filesystem. These sources are subsets of the source that they're replacing and + can be checked into projects if necessary. + +* Mirroring - sources can be replaced with an equivalent version which acts as a + cache for crates.io itself. + +Cargo has a core assumption about source replacement that the source code is +exactly the same from both sources. In our above example Cargo assumes that all +of the crates coming from `my-awesome-source` are the exact same as the copies +from `crates-io`. Note that this also means that `my-awesome-source` is not +allowed to have crates which are not present in the `crates-io` source. + +As a consequence, source replacement is not appropriate for situations such as +patching a dependency or a private registry. Cargo supports patching +dependencies through the usage of [the `[replace]` key][replace-section], and +private registry support is planned for a future version of Cargo. + +[replace-section]: reference/manifest.html#the-replace-section + +### Configuration + +Configuration of replacement sources is done through [`.cargo/config`][config] +and the full set of available keys are: + +```toml +# Each source has its own table where the key is the name of the source +[source.the-source-name] + +# Indicate that `the-source-name` will be replaced with `another-source`, +# defined elsewhere +replace-with = "another-source" + +# Available kinds of sources that can be specified (described below) +registry = "https://example.com/path/to/index" +local-registry = "path/to/registry" +directory = "path/to/vendor" +``` + +The `crates-io` represents the crates.io online registry (default source of +crates) and can be replaced with: + +```toml +[source.crates-io] +replace-with = 'another-source' +``` + +### Registry Sources + +A "registry source" is one that is the same as crates.io itself. That is, it has +an index served in a git repository which matches the format of the +[crates.io index](https://github.com/rust-lang/crates.io-index). That repository +then has configuration indicating where to download crates from. + +Currently there is not an already-available project for setting up a mirror of +crates.io. Stay tuned though! + +### Local Registry Sources + +A "local registry source" is intended to be a subset of another registry +source, but available on the local filesystem (aka vendoring). Local registries +are downloaded ahead of time, typically sync'd with a `Cargo.lock`, and are +made up of a set of `*.crate` files and an index like the normal registry is. + +The primary way to manage and crate local registry sources is through the +[`cargo-local-registry`][cargo-local-registry] subcommand, available on +crates.io and can be installed with `cargo install cargo-local-registry`. + +[cargo-local-registry]: https://crates.io/crates/cargo-local-registry + +Local registries are contained within one directory and contain a number of +`*.crate` files downloaded from crates.io as well as an `index` directory with +the same format as the crates.io-index project (populated with just entries for +the crates that are present). + +### Directory Sources + +A "directory source" is similar to a local registry source where it contains a +number of crates available on the local filesystem, suitable for vendoring +dependencies. Also like local registries, directory sources can primarily be +managed by an external subcommand, [`cargo-vendor`][cargo-vendor], which can be +installed with `cargo install cargo-vendor`. + +[cargo-vendor]: https://crates.io/crates/cargo-vendor + +Directory sources are distinct from local registries though in that they contain +the unpacked version of `*.crate` files, making it more suitable in some +situations to check everything into source control. A directory source is just a +directory containing a number of other directories which contain the source code +for crates (the unpacked version of `*.crate` files). Currently no restriction +is placed on the name of each directory. + +Each crate in a directory source also has an associated metadata file indicating +the checksum of each file in the crate to protect against accidental +modifications. diff -Nru cargo-0.25.0/src/doc/src/reference/specifying-dependencies.md cargo-0.26.0/src/doc/src/reference/specifying-dependencies.md --- cargo-0.25.0/src/doc/src/reference/specifying-dependencies.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/reference/specifying-dependencies.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,534 @@ +## Specifying Dependencies + +Your crates can depend on other libraries from [crates.io], `git` repositories, or +subdirectories on your local file system. You can also temporarily override the +location of a dependency— for example, to be able to test out a bug fix in the +dependency that you are working on locally. You can have different +dependencies for different platforms, and dependencies that are only used during +development. Let's take a look at how to do each of these. + +### Specifying dependencies from crates.io + +Cargo is configured to look for dependencies on [crates.io] by default. Only +the name and a version string are required in this case. In [the cargo +guide](guide/index.html), we specified a dependency on the `time` crate: + +```toml +[dependencies] +time = "0.1.12" +``` + +The string `"0.1.12"` is a [semver] version requirement. Since this +string does not have any operators in it, it is interpreted the same way as +if we had specified `"^0.1.12"`, which is called a caret requirement. + +[semver]: https://github.com/steveklabnik/semver#requirements + +### Caret requirements + +**Caret requirements** allow SemVer compatible updates to a specified version. +An update is allowed if the new version number does not modify the left-most +non-zero digit in the major, minor, patch grouping. In this case, if we ran +`cargo update -p time`, cargo would update us to version `0.1.13` if it was +available, but would not update us to `0.2.0`. If instead we had specified the +version string as `^1.0`, cargo would update to `1.1` but not `2.0`. The version +`0.0.x` is not considered compatible with any other version. + +Here are some more examples of caret requirements and the versions that would +be allowed with them: + +```notrust +^1.2.3 := >=1.2.3 <2.0.0 +^1.2 := >=1.2.0 <2.0.0 +^1 := >=1.0.0 <2.0.0 +^0.2.3 := >=0.2.3 <0.3.0 +^0.0.3 := >=0.0.3 <0.0.4 +^0.0 := >=0.0.0 <0.1.0 +^0 := >=0.0.0 <1.0.0 +``` + +This compatibility convention is different from SemVer in the way it treats +versions before 1.0.0. While SemVer says there is no compatibility before +1.0.0, Cargo considers `0.x.y` to be compatible with `0.x.z`, where `y ≥ z` +and `x > 0`. + +### Tilde requirements + +**Tilde requirements** specify a minimal version with some ability to update. +If you specify a major, minor, and patch version or only a major and minor +version, only patch-level changes are allowed. If you only specify a major +version, then minor- and patch-level changes are allowed. + +`~1.2.3` is an example of a tilde requirement. + +```notrust +~1.2.3 := >=1.2.3 <1.3.0 +~1.2 := >=1.2.0 <1.3.0 +~1 := >=1.0.0 <2.0.0 +``` + +### Wildcard requirements + +**Wildcard requirements** allow for any version where the wildcard is +positioned. + +`*`, `1.*` and `1.2.*` are examples of wildcard requirements. + +```notrust +* := >=0.0.0 +1.* := >=1.0.0 <2.0.0 +1.2.* := >=1.2.0 <1.3.0 +``` + +### Inequality requirements + +**Inequality requirements** allow manually specifying a version range or an +exact version to depend on. + +Here are some examples of inequality requirements: + +```notrust +>= 1.2.0 +> 1 +< 2 += 1.2.3 +``` + +### Multiple requirements + +Multiple version requirements can also be separated with a comma, e.g. `>= 1.2, +< 1.5`. + +### Specifying dependencies from `git` repositories + +To depend on a library located in a `git` repository, the minimum information +you need to specify is the location of the repository with the `git` key: + +```toml +[dependencies] +rand = { git = "https://github.com/rust-lang-nursery/rand" } +``` + +Cargo will fetch the `git` repository at this location then look for a +`Cargo.toml` for the requested crate anywhere inside the `git` repository +(not necessarily at the root). + +Since we haven’t specified any other information, Cargo assumes that +we intend to use the latest commit on the `master` branch to build our project. +You can combine the `git` key with the `rev`, `tag`, or `branch` keys to +specify something else. Here's an example of specifying that you want to use +the latest commit on a branch named `next`: + +```toml +[dependencies] +rand = { git = "https://github.com/rust-lang-nursery/rand", branch = "next" } +``` + +### Specifying path dependencies + +Over time, our `hello_world` project from [the guide](guide/index.html) has +grown significantly in size! It’s gotten to the point that we probably want to +split out a separate crate for others to use. To do this Cargo supports **path +dependencies** which are typically sub-crates that live within one repository. +Let’s start off by making a new crate inside of our `hello_world` project: + +```console +# inside of hello_world/ +$ cargo new hello_utils +``` + +This will create a new folder `hello_utils` inside of which a `Cargo.toml` and +`src` folder are ready to be configured. In order to tell Cargo about this, open +up `hello_world/Cargo.toml` and add `hello_utils` to your dependencies: + +```toml +[dependencies] +hello_utils = { path = "hello_utils" } +``` + +This tells Cargo that we depend on a crate called `hello_utils` which is found +in the `hello_utils` folder (relative to the `Cargo.toml` it’s written in). + +And that’s it! The next `cargo build` will automatically build `hello_utils` and +all of its own dependencies, and others can also start using the crate as well. +However, crates that use dependencies specified with only a path are not +permitted on [crates.io]. If we wanted to publish our `hello_world` crate, we +would need to publish a version of `hello_utils` to [crates.io](https://crates.io) +and specify its version in the dependencies line as well: + +```toml +[dependencies] +hello_utils = { path = "hello_utils", version = "0.1.0" } +``` + +### Overriding dependencies + +There are a number of methods in Cargo to support overriding dependencies and +otherwise controlling the dependency graph. These options are typically, though, +only available at the workspace level and aren't propagated through +dependencies. In other words, "applications" have the ability to override +dependencies but "libraries" do not. + +The desire to override a dependency or otherwise alter some dependencies can +arise through a number of scenarios. Most of them, however, boil down to the +ability to work with a crate before it's been published to crates.io. For +example: + +* A crate you're working on is also used in a much larger application you're + working on, and you'd like to test a bug fix to the library inside of the + larger application. +* An upstream crate you don't work on has a new feature or a bug fix on the + master branch of its git repository which you'd like to test out. +* You're about to publish a new major version of your crate, but you'd like to + do integration testing across an entire project to ensure the new major + version works. +* You've submitted a fix to an upstream crate for a bug you found, but you'd + like to immediately have your application start depending on the fixed version + of the crate to avoid blocking on the bug fix getting merged. + +These scenarios are currently all solved with the [`[patch]` manifest +section][patch-section]. Historically some of these scenarios have been solved +with [the `[replace]` section][replace-section], but we'll document the `[patch]` +section here. + +[patch-section]: reference/manifest.html#the-patch-section +[replace-section]: reference/manifest.html#the-replace-section + +### Testing a bugfix + +Let's say you're working with the [`uuid`] crate but while you're working on it +you discover a bug. You are, however, quite enterprising so you decide to also +try out to fix the bug! Originally your manifest will look like: + +[`uuid`](https://crates.io/crates/uuid) + +```toml +[package] +name = "my-library" +version = "0.1.0" +authors = ["..."] + +[dependencies] +uuid = "1.0" +``` + +First thing we'll do is to clone the [`uuid` repository][uuid-repository] +locally via: + +```console +$ git clone https://github.com/rust-lang-nursery/uuid +``` + +Next we'll edit the manifest of `my-library` to contain: + +```toml +[patch.crates-io] +uuid = { path = "../path/to/uuid" } +``` + +Here we declare that we're *patching* the source `crates-io` with a new +dependency. This will effectively add the local checked out version of `uuid` to +the crates.io registry for our local project. + +Next up we need to ensure that our lock file is updated to use this new version +of `uuid` so our project uses the locally checked out copy instead of one from +crates.io. The way `[patch]` works is that it'll load the dependency at +`../path/to/uuid` and then whenever crates.io is queried for versions of `uuid` +it'll *also* return the local version. + +This means that the version number of the local checkout is significant and will +affect whether the patch is used. Our manifest declared `uuid = "1.0"` which +means we'll only resolve to `>= 1.0.0, < 2.0.0`, and Cargo's greedy resolution +algorithm also means that we'll resolve to the maximum version within that +range. Typically this doesn't matter as the version of the git repository will +already be greater or match the maximum version published on crates.io, but it's +important to keep this in mind! + +In any case, typically all you need to do now is: + +```console +$ cargo build + Compiling uuid v1.0.0 (file://.../uuid) + Compiling my-library v0.1.0 (file://.../my-library) + Finished dev [unoptimized + debuginfo] target(s) in 0.32 secs +``` + +And that's it! You're now building with the local version of `uuid` (note the +`file://` in the build output). If you don't see the `file://` version getting +built then you may need to run `cargo update -p uuid --precise $version` where +`$version` is the version of the locally checked out copy of `uuid`. + +Once you've fixed the bug you originally found the next thing you'll want to do +is to likely submit that as a pull request to the `uuid` crate itself. Once +you've done this then you can also update the `[patch]` section. The listing +inside of `[patch]` is just like the `[dependencies]` section, so once your pull +request is merged you could change your `path` dependency to: + +```toml +[patch.crates-io] +uuid = { git = 'https://github.com/rust-lang-nursery/uuid' } +``` + +[uuid-repository]: https://github.com/rust-lang-nursery/uuid + +### Working with an unpublished minor version + +Let's now shift gears a bit from bug fixes to adding features. While working on +`my-library` you discover that a whole new feature is needed in the `uuid` +crate. You've implemented this feature, tested it locally above with `[patch]`, +and submitted a pull request. Let's go over how you continue to use and test it +before it's actually published. + +Let's also say that the current version of `uuid` on crates.io is `1.0.0`, but +since then the master branch of the git repository has updated to `1.0.1`. This +branch includes your new feature you submitted previously. To use this +repository we'll edit our `Cargo.toml` to look like + +```toml +[package] +name = "my-library" +version = "0.1.0" +authors = ["..."] + +[dependencies] +uuid = "1.0.1" + +[patch.crates-io] +uuid = { git = 'https://github.com/rust-lang-nursery/uuid' } +``` + +Note that our local dependency on `uuid` has been updated to `1.0.1` as it's +what we'll actually require once the crate is published. This version doesn't +exist on crates.io, though, so we provide it with the `[patch]` section of the +manifest. + +Now when our library is built it'll fetch `uuid` from the git repository and +resolve to 1.0.1 inside the repository instead of trying to download a version +from crates.io. Once 1.0.1 is published on crates.io the `[patch]` section can +be deleted. + +It's also worth nothing that `[patch]` applies *transitively*. Let's say you use +`my-library` in a larger project, such as: + +```toml +[package] +name = "my-binary" +version = "0.1.0" +authors = ["..."] + +[dependencies] +my-library = { git = 'https://example.com/git/my-library' } +uuid = "1.0" + +[patch.crates-io] +uuid = { git = 'https://github.com/rust-lang-nursery/uuid' } +``` + +Remember that `[patch]` is applicable *transitively* but can only be defined at +the *top level* so we consumers of `my-library` have to repeat the `[patch]` section +if necessary. Here, though, the new `uuid` crate applies to *both* our dependency on +`uuid` and the `my-library -> uuid` dependency. The `uuid` crate will be resolved to +one version for this entire crate graph, 1.0.1, and it'll be pulled from the git +repository. + +#### Overriding repository URL + +In case the dependency you want to override isn't loaded from `crates.io`, you'll have to change a bit how you use `[patch]`: + +```toml +[patch."https://github.com/your/repository"] +my-library = { path = "../my-library/path" } +``` + +And that's it! + +### Prepublishing a breaking change + +As a final scenario, let's take a look at working with a new major version of a +crate, typically accompanied with breaking changes. Sticking with our previous +crates, this means that we're going to be creating version 2.0.0 of the `uuid` +crate. After we've submitted all changes upstream we can update our manifest for +`my-library` to look like: + +```toml +[dependencies] +uuid = "2.0" + +[patch.crates-io] +uuid = { git = "https://github.com/rust-lang-nursery/uuid", branch = "2.0.0" } +``` + +And that's it! Like with the previous example the 2.0.0 version doesn't actually +exist on crates.io but we can still put it in through a git dependency through +the usage of the `[patch]` section. As a thought exercise let's take another +look at the `my-binary` manifest from above again as well: + +```toml +[package] +name = "my-binary" +version = "0.1.0" +authors = ["..."] + +[dependencies] +my-library = { git = 'https://example.com/git/my-library' } +uuid = "1.0" + +[patch.crates-io] +uuid = { git = 'https://github.com/rust-lang-nursery/uuid', version = '2.0.0' } +``` + +Note that this will actually resolve to two versions of the `uuid` crate. The +`my-binary` crate will continue to use the 1.x.y series of the `uuid` crate but +the `my-library` crate will use the 2.0.0 version of `uuid`. This will allow you +to gradually roll out breaking changes to a crate through a dependency graph +without being force to update everything all at once. + +### Overriding with local dependencies + +Sometimes you're only temporarily working on a crate and you don't want to have +to modify `Cargo.toml` like with the `[patch]` section above. For this use +case Cargo offers a much more limited version of overrides called **path +overrides**. + +Path overrides are specified through `.cargo/config` instead of `Cargo.toml`, +and you can find [more documentation about this configuration][config-docs]. +Inside of `.cargo/config` you'll specify a key called `paths`: + +[config-docs]: reference/config.html + +```toml +paths = ["/path/to/uuid"] +``` + +This array should be filled with directories that contain a `Cargo.toml`. In +this instance, we’re just adding `uuid`, so it will be the only one that’s +overridden. This path can be either absolute or relative to the directory that +contains the `.cargo` folder. + +Path overrides are more restricted than the `[patch]` section, however, in +that they cannot change the structure of the dependency graph. When a +path replacement is used then the previous set of dependencies +must all match exactly to the new `Cargo.toml` specification. For example this +means that path overrides cannot be used to test out adding a dependency to a +crate, instead `[patch]` must be used in that situation. As a result usage of a +path override is typically isolated to quick bug fixes rather than larger +changes. + +Note: using a local configuration to override paths will only work for crates +that have been published to [crates.io]. You cannot use this feature to tell +Cargo how to find local unpublished crates. + +### Platform specific dependencies + + +Platform-specific dependencies take the same format, but are listed under a +`target` section. Normally Rust-like `#[cfg]` syntax will be used to define +these sections: + +```toml +[target.'cfg(windows)'.dependencies] +winhttp = "0.4.0" + +[target.'cfg(unix)'.dependencies] +openssl = "1.0.1" + +[target.'cfg(target_arch = "x86")'.dependencies] +native = { path = "native/i686" } + +[target.'cfg(target_arch = "x86_64")'.dependencies] +native = { path = "native/x86_64" } +``` + +Like with Rust, the syntax here supports the `not`, `any`, and `all` operators +to combine various cfg name/value pairs. Note that the `cfg` syntax has only +been available since Cargo 0.9.0 (Rust 1.8.0). + +In addition to `#[cfg]` syntax, Cargo also supports listing out the full target +the dependencies would apply to: + +```toml +[target.x86_64-pc-windows-gnu.dependencies] +winhttp = "0.4.0" + +[target.i686-unknown-linux-gnu.dependencies] +openssl = "1.0.1" +``` + +If you’re using a custom target specification, quote the full path and file +name: + +```toml +[target."x86_64/windows.json".dependencies] +winhttp = "0.4.0" + +[target."i686/linux.json".dependencies] +openssl = "1.0.1" +native = { path = "native/i686" } + +[target."x86_64/linux.json".dependencies] +openssl = "1.0.1" +native = { path = "native/x86_64" } +``` + +### Development dependencies + +You can add a `[dev-dependencies]` section to your `Cargo.toml` whose format +is equivalent to `[dependencies]`: + +```toml +[dev-dependencies] +tempdir = "0.3" +``` + +Dev-dependencies are not used when compiling +a package for building, but are used for compiling tests, examples, and +benchmarks. + +These dependencies are *not* propagated to other packages which depend on this +package. + +You can also have target-specific development dependencies by using +`dev-dependencies` in the target section header instead of `dependencies`. For +example: + +```toml +[target.'cfg(unix)'.dev-dependencies] +mio = "0.0.1" +``` + +[crates.io]: https://crates.io/ + +### Build dependencies + +You can depend on other Cargo-based crates for use in your build scripts. +Dependencies are declared through the `build-dependencies` section of the +manifest: + +```toml +[build-dependencies] +gcc = "0.3" +``` + +The build script **does not** have access to the dependencies listed +in the `dependencies` or `dev-dependencies` section. Build +dependencies will likewise not be available to the package itself +unless listed under the `dependencies` section as well. A package +itself and its build script are built separately, so their +dependencies need not coincide. Cargo is kept simpler and cleaner by +using independent dependencies for independent purposes. + +### Choosing features + +If a package you depend on offers conditional features, you can +specify which to use: + +```toml +[dependencies.awesome] +version = "1.3.5" +default-features = false # do not include the default features, and optionally + # cherry-pick individual features +features = ["secure-password", "civet"] +``` + +More information about features can be found in the +[manifest documentation](reference/manifest.html#the-features-section). diff -Nru cargo-0.25.0/src/doc/src/SUMMARY.md cargo-0.26.0/src/doc/src/SUMMARY.md --- cargo-0.25.0/src/doc/src/SUMMARY.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/src/doc/src/SUMMARY.md 2018-02-26 21:17:55.000000000 +0000 @@ -0,0 +1,31 @@ +# Summary + +[Introduction](index.md) + +* [Getting Started](getting-started/index.md) + * [Installation](getting-started/installation.md) + * [First Steps with Cargo](getting-started/first-steps.md) + +* [Cargo Guide](guide/index.md) + * [Why Cargo Exists](guide/why-cargo-exists.md) + * [Creating a New Project](guide/creating-a-new-project.md) + * [Working on an Existing Project](guide/working-on-an-existing-project.md) + * [Dependencies](guide/dependencies.md) + * [Project Layout](guide/project-layout.md) + * [Cargo.toml vs Cargo.lock](guide/cargo-toml-vs-cargo-lock.md) + * [Tests](guide/tests.md) + * [Continuous Integration](guide/continuous-integration.md) + * [Build Cache](guide/build-cache.md) + +* [Cargo Reference](reference/index.md) + * [Specifying Dependencies](reference/specifying-dependencies.md) + * [The Manifest Format](reference/manifest.md) + * [Configuration](reference/config.md) + * [Environment Variables](reference/environment-variables.md) + * [Build Scripts](reference/build-scripts.md) + * [Publishing on crates.io](reference/publishing.md) + * [Package ID Specifications](reference/pkgid-spec.md) + * [Source Replacement](reference/source-replacement.md) + * [External Tools](reference/external-tools.md) + +* [FAQ](faq.md) diff -Nru cargo-0.25.0/src/doc/stylesheets/all.css cargo-0.26.0/src/doc/stylesheets/all.css --- cargo-0.25.0/src/doc/stylesheets/all.css 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/stylesheets/all.css 1970-01-01 00:00:00.000000000 +0000 @@ -1,291 +0,0 @@ -html { - background: url("../images/noise.png"); - background-color: #3b6837; -} - -main, #header { width: 900px; } - -* { - box-sizing: border-box; -} - -body { - display: -webkit-flex; - display: flex; - -webkit-flex-direction: column; - flex-direction: column; - -webkit-align-items: center; - align-items: center; - font-family: sans-serif; - font-size: 16px; -} - -a { color: #00ac5b; text-decoration: none; } -a:hover { color: #00793f; } - -h1 { - font-size: 24px; - margin: 20px 0 10px 0; - font-weight: bold; - color: #b64790; -} - -h1 code:not(.highlight) { - color: #d9a700; - vertical-align: bottom; -} -h1 a, h2 a { color: #b64790; text-decoration: none; } -h1:hover a, h2:hover a { color: #A03D7E; } -h1:hover a:after, -h2:hover a:after { content: '\2002\00a7\2002'; } -:target { background: rgba(239, 242, 178, 1); padding: 5px; } - -h1.title { /* style rustdoc-generated title */ - width: 100%; - padding: 40px 20px 40px 60px; - background-color: #edebdd; - margin-bottom: 20px; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - -ms-border-radius: 5px; - border-radius: 5px; - margin: 0; - color: #383838; - font-size: 2em; - background-image: url(../images/circle-with-i.png); - background-repeat: no-repeat; - background-position: 20px center; -} - -h2 { - font-size: 18px; - margin: 15px 0 5px 0; - color: #b64790; - font-weight: bold; -} - -h2 code:not(.highlight) { color: #d9a700; } - -code:not(.highlight) { - font-family: monospace; - color: #b64790; -} - -main { - display: -webkit-flex; - display: flex; - -webkit-flex-direction: column; - flex-direction: column; - - width: 100%; - max-width: 900px; - margin-bottom: 10px; - - background-color: #f9f7ec; - padding: 15px; - - -webkit-border-radius: 10px; - -moz-border-radius: 10px; - -ms-border-radius: 10px; - border-radius: 10px; - box-shadow: 0px 0px 5px 2px #3b6837; - border: 5px solid #62865f; - color: #383838; -} - -main > p:first-child { - font-weight: 500; - margin-top: 3px; - padding-bottom: 15px; - border-bottom: 1px solid #62865f; - text-align: center; -} - -main p:first-child a { color: #3b6837; } -main p:first-child a:hover { color: #62865f; } - -main p, main ul { - /* color: #3b6837; */ - margin: 10px 0; - line-height: 150%; -} - -main ul { margin-left: 20px; } -main li { list-style-type: disc; } -main strong { font-weight: bold; } - -img.logo { - align-self: center; - margin-bottom: 10px; -} - -pre { - padding: 10px; - margin: 10px 0; - /* border: 1px solid #cad0d0; */ - border-radius: 4px; - max-width: calc(100vw - 45px); - overflow-x: auto; - - background: #383838 !important; - color: white; - padding: 20px; - - /* override prism.js styles */ - font-size: 1em !important; - border: none !important; - box-shadow: none !important; - text-shadow: none !important; -} - -pre code { - text-shadow: none !important; -} - -footer { - padding: 40px; - width: 900px; -} -footer a { - color: white; -} -footer a:hover { - color: #e6e6e6; -} -footer .sep, #header .sep { color: #284725; } -footer .sep { margin: 0 10px; } -#header .sep { margin-left: 10px; } - -.headerlink { - display: none; - text-decoration: none; -} -.fork-me { - position:absolute; - top:0; - right:0; -} - -.token.toml-section { color: #CB4B16; } -.token.toml-key { color: #268BD2; } - -/* Rust code highlighting */ -pre.rust .kw { color: #8959A8; } -pre.rust .kw-2, pre.rust .prelude-ty { color: #4271AE; } -pre.rust .number, pre.rust .string { color: #718C00; } -pre.rust .self, pre.rust .boolval, pre.rust .prelude-val, -pre.rust .attribute, pre.rust .attribute .ident { color: #C82829; } -pre.rust .comment { color: #8E908C; } -pre.rust .doccomment { color: #4D4D4C; } -pre.rust .macro, pre.rust .macro-nonterminal { color: #3E999F; } -pre.rust .lifetime { color: #B76514; } -code span.s1 { color: #2AA198; } - -table th { border-bottom: 1px solid black; } -table td, table th { padding: 5px 10px; } - -#header { - color: white; - position: relative; - height: 100px; - display: -webkit-flex; - display: flex; - -webkit-align-items: center; - align-items: center; -} -#header h1 { font-size: 2em; } -#header a, #header h1 { color: white; text-decoration: none; } -#header a:hover { color: #d9d9d9; } - -#header input.search { - border: none; - color: black; - outline: 0; - margin-left: 30px; - padding: 5px 5px 5px 25px; - background-image: url(../images/search.png); - background-repeat: no-repeat; - background-position: 6px 6px; - -webkit-border-radius: 15px; - -moz-border-radius: 15px; - -ms-border-radius: 15px; - border-radius: 15px; -} - -#header .nav { - -webkit-flex-grow: 2; - flex-grow: 2; - text-align: right; -} - -button.dropdown, a.dropdown { cursor: pointer; } -button.dropdown .arrow, a.dropdown .arrow { - font-size: 50%; display: inline-block; vertical-align: middle; -} -button.dropdown .arrow::after, a.dropdown .arrow::after { content: "▼"; } -button.active.dropdown .arrow::after, a.active.dropdown .arrow::after { - content: "▲"; -} - -button { - background: none; - outline: 0; - border: 0; - padding: 10px; - color: white; -} - -button.active { - background:#2a4f27; - box-shadow:inset -2px 2px 4px 0 #243d26 -} - -ul.dropdown { - display: none; - visibility: none; - position: absolute; - top: 100%; - right: 0; - width: 100%; - min-width: 150px; - opacity: 0; - margin: 0; - text-align: left; - padding: 0; - background: white; - border: 1px solid #d5d3cb; - list-style: none; - z-index: 10; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - -ms-border-radius: 5px; - border-radius: 5px; -} - -ul.dropdown li a { - font-size: 90%; - width: 100%; - display: inline-block; - padding: 8px 10px; - text-decoration: none; - color: #383838 !important; -} - -ul.dropdown li a:hover { - background: #5e5e5e; - color: white !important; -} -ul.dropdown li.last { border-top: 1px solid #d5d3cb; } -ul.dropdown.open { - display: block; - visibility: visible; - opacity: 1; -} -.dropdown-container { - display: inline-block; - position: relative; -} - -p > img { - max-width: 100%; -} diff -Nru cargo-0.25.0/src/doc/stylesheets/normalize.css cargo-0.26.0/src/doc/stylesheets/normalize.css --- cargo-0.25.0/src/doc/stylesheets/normalize.css 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/stylesheets/normalize.css 1970-01-01 00:00:00.000000000 +0000 @@ -1,375 +0,0 @@ -/*! normalize.css v2.0.1 | MIT License | git.io/normalize */ - -/* ========================================================================== - HTML5 display definitions - ========================================================================== */ - -/* - * Corrects `block` display not defined in IE 8/9. - */ - -article, -aside, -details, -figcaption, -figure, -footer, -header, -hgroup, -nav, -section, -summary { - display: block; -} - -/* - * Corrects `inline-block` display not defined in IE 8/9. - */ - -audio, -canvas, -video { - display: inline-block; -} - -/* - * Prevents modern browsers from displaying `audio` without controls. - * Remove excess height in iOS 5 devices. - */ - -audio:not([controls]) { - display: none; - height: 0; -} - -/* - * Addresses styling for `hidden` attribute not present in IE 8/9. - */ - -[hidden] { - display: none; -} - -/* ========================================================================== - Base - ========================================================================== */ - -/* - * 1. Sets default font family to sans-serif. - * 2. Prevents iOS text size adjust after orientation change, without disabling - * user zoom. - */ - -html { - font-family: sans-serif; /* 1 */ - -webkit-text-size-adjust: 100%; /* 2 */ - -ms-text-size-adjust: 100%; /* 2 */ -} - -/* - * Removes default margin. - */ - -body { - margin: 0; -} - -/* ========================================================================== - Links - ========================================================================== */ - -/* - * Addresses `outline` inconsistency between Chrome and other browsers. - */ - -a:focus { - outline: thin dotted; -} - -/* - * Improves readability when focused and also mouse hovered in all browsers. - */ - -a:active, -a:hover { - outline: 0; -} - -/* ========================================================================== - Typography - ========================================================================== */ - -/* - * Addresses `h1` font sizes within `section` and `article` in Firefox 4+, - * Safari 5, and Chrome. - */ - -h1 { - font-size: 2em; -} - -/* - * Addresses styling not present in IE 8/9, Safari 5, and Chrome. - */ - -abbr[title] { - border-bottom: 1px dotted; -} - -/* - * Addresses style set to `bolder` in Firefox 4+, Safari 5, and Chrome. - */ - -b, -strong { - font-weight: bold; -} - -/* - * Addresses styling not present in Safari 5 and Chrome. - */ - -dfn { - font-style: italic; -} - -/* - * Addresses styling not present in IE 8/9. - */ - -mark { - background: #ff0; - color: #000; -} - - -/* - * Corrects font family set oddly in Safari 5 and Chrome. - */ - -code, -kbd, -pre, -samp { - font-family: monospace, serif; - font-size: 1em; -} - -/* - * Improves readability of pre-formatted text in all browsers. - */ - -pre { - white-space: pre; - white-space: pre-wrap; - word-wrap: break-word; -} - -/* - * Sets consistent quote types. - */ - -q { - quotes: "\201C" "\201D" "\2018" "\2019"; -} - -/* - * Addresses inconsistent and variable font size in all browsers. - */ - -small { - font-size: 80%; -} - -/* - * Prevents `sub` and `sup` affecting `line-height` in all browsers. - */ - -sub, -sup { - font-size: 75%; - line-height: 0; - position: relative; - vertical-align: baseline; -} - -sup { - top: -0.5em; -} - -sub { - bottom: -0.25em; -} - -/* ========================================================================== - Embedded content - ========================================================================== */ - -/* - * Removes border when inside `a` element in IE 8/9. - */ - -img { - border: 0; -} - -/* - * Corrects overflow displayed oddly in IE 9. - */ - -svg:not(:root) { - overflow: hidden; -} - -/* ========================================================================== - Figures - ========================================================================== */ - -/* - * Addresses margin not present in IE 8/9 and Safari 5. - */ - -figure { - margin: 0; -} - -/* ========================================================================== - Forms - ========================================================================== */ - -/* - * Define consistent border, margin, and padding. - */ - -fieldset { - border: 1px solid #c0c0c0; - margin: 0 2px; - padding: 0.35em 0.625em 0.75em; -} - -/* - * 1. Corrects color not being inherited in IE 8/9. - * 2. Remove padding so people aren't caught out if they zero out fieldsets. - */ - -legend { - border: 0; /* 1 */ - padding: 0; /* 2 */ -} - -/* - * 1. Corrects font family not being inherited in all browsers. - * 2. Corrects font size not being inherited in all browsers. - * 3. Addresses margins set differently in Firefox 4+, Safari 5, and Chrome - */ - -button, -input, -select, -textarea { - font-family: inherit; /* 1 */ - font-size: 100%; /* 2 */ - margin: 0; /* 3 */ -} - -/* - * Addresses Firefox 4+ setting `line-height` on `input` using `!important` in - * the UA stylesheet. - */ - -button, -input { - line-height: normal; -} - -/* - * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` - * and `video` controls. - * 2. Corrects inability to style clickable `input` types in iOS. - * 3. Improves usability and consistency of cursor style between image-type - * `input` and others. - */ - -button, -html input[type="button"], /* 1 */ -input[type="reset"], -input[type="submit"] { - -webkit-appearance: button; /* 2 */ - cursor: pointer; /* 3 */ -} - -/* - * Re-set default cursor for disabled elements. - */ - -button[disabled], -input[disabled] { - cursor: default; -} - -/* - * 1. Addresses box sizing set to `content-box` in IE 8/9. - * 2. Removes excess padding in IE 8/9. - */ - -input[type="checkbox"], -input[type="radio"] { - box-sizing: border-box; /* 1 */ - padding: 0; /* 2 */ -} - -/* - * 1. Addresses `appearance` set to `searchfield` in Safari 5 and Chrome. - * 2. Addresses `box-sizing` set to `border-box` in Safari 5 and Chrome - * (include `-moz` to future-proof). - */ - -input[type="search"] { - -webkit-appearance: textfield; /* 1 */ - -moz-box-sizing: content-box; - -webkit-box-sizing: content-box; /* 2 */ - box-sizing: content-box; -} - -/* - * Removes inner padding and search cancel button in Safari 5 and Chrome - * on OS X. - */ - -input[type="search"]::-webkit-search-cancel-button, -input[type="search"]::-webkit-search-decoration { - -webkit-appearance: none; -} - -/* - * Removes inner padding and border in Firefox 4+. - */ - -button::-moz-focus-inner, -input::-moz-focus-inner { - border: 0; - padding: 0; -} - -/* - * 1. Removes default vertical scrollbar in IE 8/9. - * 2. Improves readability and alignment in all browsers. - */ - -textarea { - overflow: auto; /* 1 */ - vertical-align: top; /* 2 */ -} - -/* ========================================================================== - Tables - ========================================================================== */ - -/* - * Remove most spacing between table cells. - */ - -table { - border-collapse: collapse; - border-spacing: 0; -} \ No newline at end of file diff -Nru cargo-0.25.0/src/doc/stylesheets/prism.css cargo-0.26.0/src/doc/stylesheets/prism.css --- cargo-0.25.0/src/doc/stylesheets/prism.css 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/doc/stylesheets/prism.css 1970-01-01 00:00:00.000000000 +0000 @@ -1,197 +0,0 @@ -/* http://prismjs.com/download.html?themes=prism-twilight&languages=markup+css+clike+javascript */ -/** - * prism.js Twilight theme - * Based (more or less) on the Twilight theme originally of Textmate fame. - * @author Remy Bach - */ -code[class*="language-"], -pre[class*="language-"] { - color: white; - direction: ltr; - font-family: Consolas, Monaco, 'Andale Mono', monospace; - text-align: left; - text-shadow: 0 -.1em .2em black; - white-space: pre; - word-spacing: normal; - word-break: normal; - line-height: 1.5; - - -moz-tab-size: 4; - -o-tab-size: 4; - tab-size: 4; - - -webkit-hyphens: none; - -moz-hyphens: none; - -ms-hyphens: none; - hyphens: none; -} - -pre[class*="language-"], -:not(pre) > code[class*="language-"] { - background: hsl(0, 0%, 8%); /* #141414 */ -} - -/* Code blocks */ -pre[class*="language-"] { - border-radius: .5em; - border: .3em solid hsl(0, 0%, 33%); /* #282A2B */ - box-shadow: 1px 1px .5em black inset; - margin: .5em 0; - overflow: auto; - padding: 1em; -} - -pre[class*="language-"]::selection { - /* Safari */ - background: hsl(200, 4%, 16%); /* #282A2B */ -} - -pre[class*="language-"]::selection { - /* Firefox */ - background: hsl(200, 4%, 16%); /* #282A2B */ -} - -/* Text Selection colour */ -pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection, -code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection { - text-shadow: none; - background: hsla(0, 0%, 93%, 0.15); /* #EDEDED */ -} - -pre[class*="language-"]::selection, pre[class*="language-"] ::selection, -code[class*="language-"]::selection, code[class*="language-"] ::selection { - text-shadow: none; - background: hsla(0, 0%, 93%, 0.15); /* #EDEDED */ -} - -/* Inline code */ -:not(pre) > code[class*="language-"] { - border-radius: .3em; - border: .13em solid hsl(0, 0%, 33%); /* #545454 */ - box-shadow: 1px 1px .3em -.1em black inset; - padding: .15em .2em .05em; -} - -.token.comment, -.token.prolog, -.token.doctype, -.token.cdata { - color: hsl(0, 0%, 47%); /* #777777 */ -} - -.token.punctuation { - opacity: .7; -} - -.namespace { - opacity: .7; -} - -.token.tag, -.token.boolean, -.token.number, -.token.deleted { - color: hsl(14, 58%, 55%); /* #CF6A4C */ -} - -.token.keyword, -.token.property, -.token.selector, -.token.constant, -.token.symbol, -.token.builtin { - color: hsl(53, 89%, 79%); /* #F9EE98 */ -} - -.token.attr-name, -.token.attr-value, -.token.string, -.token.char, -.token.operator, -.token.entity, -.token.url, -.language-css .token.string, -.style .token.string, -.token.variable, -.token.inserted { - color: hsl(76, 21%, 52%); /* #8F9D6A */ -} - -.token.atrule { - color: hsl(218, 22%, 55%); /* #7587A6 */ -} - -.token.regex, -.token.important { - color: hsl(42, 75%, 65%); /* #E9C062 */ -} - -.token.important { - font-weight: bold; -} - -.token.entity { - cursor: help; -} - -pre[data-line] { - padding: 1em 0 1em 3em; - position: relative; -} - -/* Markup */ -.language-markup .token.tag, -.language-markup .token.attr-name, -.language-markup .token.punctuation { - color: hsl(33, 33%, 52%); /* #AC885B */ -} - -/* Make the tokens sit above the line highlight so the colours don't look faded. */ -.token { - position: relative; - z-index: 1; -} - -.line-highlight { - background: -moz-linear-gradient(left, hsla(0, 0%, 33%, .1) 70%, hsla(0, 0%, 33%, 0)); /* #545454 */ - background: -o-linear-gradient(left, hsla(0, 0%, 33%, .1) 70%, hsla(0, 0%, 33%, 0)); /* #545454 */ - background: -webkit-linear-gradient(left, hsla(0, 0%, 33%, .1) 70%, hsla(0, 0%, 33%, 0)); /* #545454 */ - background: hsla(0, 0%, 33%, 0.25); /* #545454 */ - background: linear-gradient(left, hsla(0, 0%, 33%, .1) 70%, hsla(0, 0%, 33%, 0)); /* #545454 */ - border-bottom: 1px dashed hsl(0, 0%, 33%); /* #545454 */ - border-top: 1px dashed hsl(0, 0%, 33%); /* #545454 */ - left: 0; - line-height: inherit; - margin-top: 0.75em; /* Same as .prism’s padding-top */ - padding: inherit 0; - pointer-events: none; - position: absolute; - right: 0; - white-space: pre; - z-index: 0; -} - -.line-highlight:before, -.line-highlight[data-end]:after { - background-color: hsl(215, 15%, 59%); /* #8794A6 */ - border-radius: 999px; - box-shadow: 0 1px white; - color: hsl(24, 20%, 95%); /* #F5F2F0 */ - content: attr(data-start); - font: bold 65%/1.5 sans-serif; - left: .6em; - min-width: 1em; - padding: 0 .5em; - position: absolute; - text-align: center; - text-shadow: none; - top: .4em; - vertical-align: .3em; -} - -.line-highlight[data-end]:after { - bottom: .4em; - content: attr(data-end); - top: auto; -} - Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/src/doc/theme/favicon.png and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/src/doc/theme/favicon.png differ diff -Nru cargo-0.25.0/src/etc/_cargo cargo-0.26.0/src/etc/_cargo --- cargo-0.25.0/src/etc/_cargo 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/src/etc/_cargo 2018-02-26 21:17:55.000000000 +0000 @@ -136,7 +136,7 @@ git-checkout) _arguments \ '(-h, --help)'{-h,--help}'[show help message]' \ - 'q(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ + '(-q, --quiet)'{-q,--quiet}'[no output printed to stdout]' \ '--reference=[REF]' \ '--url=[URL]' \ '(-v, --verbose)'{-v,--verbose}'[use verbose output]' \ diff -Nru cargo-0.25.0/tests/alt-registry.rs cargo-0.26.0/tests/alt-registry.rs --- cargo-0.25.0/tests/alt-registry.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/alt-registry.rs 2018-02-26 21:17:55.000000000 +0000 @@ -3,8 +3,10 @@ use cargotest::ChannelChanger; use cargotest::support::registry::{self, Package, alt_api_path}; -use cargotest::support::{project, execs}; +use cargotest::support::{paths, project, execs}; use hamcrest::assert_that; +use std::fs::File; +use std::io::Write; #[test] fn is_feature_gated() { @@ -180,7 +182,9 @@ } #[test] -fn registry_incompatible_with_path() { +fn registry_and_path_dep_works() { + registry::init(); + let p = project("foo") .file("Cargo.toml", r#" cargo-features = ["alternative-registries"] @@ -191,19 +195,33 @@ authors = [] [dependencies.bar] - path = "" + path = "bar" registry = "alternative" "#) .file("src/main.rs", "fn main() {}") + .file("bar/Cargo.toml", r#" + [project] + name = "bar" + version = "0.0.1" + authors = [] + "#) + .file("bar/src/lib.rs", "") .build(); assert_that(p.cargo("build").masquerade_as_nightly_cargo(), - execs().with_status(101) - .with_stderr_contains(" dependency (bar) specification is ambiguous. Only one of `path` or `registry` is allowed.")); + execs().with_status(0) + .with_stderr(&format!("\ +[COMPILING] bar v0.0.1 ({dir}/bar) +[COMPILING] foo v0.0.1 ({dir}) +[FINISHED] dev [unoptimized + debuginfo] target(s) in [..] secs +", + dir = p.url()))); } #[test] fn registry_incompatible_with_git() { + registry::init(); + let p = project("foo") .file("Cargo.toml", r#" cargo-features = ["alternative-registries"] @@ -407,3 +425,35 @@ .arg("--registry").arg("alternative").arg("-Zunstable-options"), execs().with_status(0)); } + +#[test] +fn credentials_in_url_forbidden() { + registry::init(); + + let config = paths::home().join(".cargo/config"); + + File::create(config) + .unwrap() + .write_all(br#" + [registries.alternative] + index = "ssh://git:secret@foobar.com" + "#) + .unwrap(); + + let p = project("foo") + .file("Cargo.toml", r#" + cargo-features = ["alternative-registries"] + + [project] + name = "foo" + version = "0.0.1" + authors = [] + "#) + .file("src/main.rs", "fn main() {}") + .build(); + + assert_that(p.cargo("publish").masquerade_as_nightly_cargo() + .arg("--registry").arg("alternative").arg("-Zunstable-options"), + execs().with_status(101) + .with_stderr_contains("error: Registry URLs may not contain credentials")); +} diff -Nru cargo-0.25.0/tests/bench.rs cargo-0.26.0/tests/bench.rs --- cargo-0.25.0/tests/bench.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/bench.rs 2018-02-26 21:17:55.000000000 +0000 @@ -257,7 +257,6 @@ } #[test] -#[ignore] // unignored on the master branch of cargo fn cargo_bench_failing_test() { if !is_nightly() { return } @@ -287,17 +286,17 @@ assert_that(process(&p.bin("foo")), execs().with_stdout("hello\n")); - assert_that(p.cargo("bench"), - execs().with_stdout_contains("test bench_hello ... ") + // Force libtest into serial execution so that the test header will be printed. + assert_that(p.cargo("bench").arg("--").arg("--test-threads=1"), + execs().with_stdout_contains("test bench_hello ...[..]") .with_stderr_contains(format!("\ -[COMPILING] foo v0.5.0 ({}) +[COMPILING] foo v0.5.0 ({})[..] [FINISHED] release [optimized] target(s) in [..] -[RUNNING] target[/]release[/]deps[/]foo-[..][EXE] -thread '[..]' panicked at 'assertion failed: \ - `(left == right)`[..]", p.url())) - .with_stderr_contains("[..]left: `\"hello\"`[..]") - .with_stderr_contains("[..]right: `\"nope\"`[..]") - .with_stderr_contains("[..]src[/]main.rs:15[..]") +[RUNNING] target[/]release[/]deps[/]foo-[..][EXE]", p.url())) + .with_either_contains("[..]thread '[..]' panicked at 'assertion failed: `(left == right)`[..]") + .with_either_contains("[..]left: `\"hello\"`[..]") + .with_either_contains("[..]right: `\"nope\"`[..]") + .with_either_contains("[..]src[/]main.rs:15[..]") .with_status(101)); } @@ -994,7 +993,7 @@ }"#) .build(); - assert_that(p.cargo("bench").arg("--no-fail-fast"), + assert_that(p.cargo("bench").arg("--no-fail-fast").arg("--").arg("--test-threads=1"), execs().with_status(101) .with_stderr_contains("\ [RUNNING] target[/]release[/]deps[/]foo-[..][EXE]") diff -Nru cargo-0.25.0/tests/build.rs cargo-0.26.0/tests/build.rs --- cargo-0.25.0/tests/build.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/build.rs 2018-02-26 21:17:55.000000000 +0000 @@ -15,6 +15,7 @@ use cargotest::support::{ProjectBuilder}; use cargotest::support::{project, execs, main_file, basic_bin_manifest}; use cargotest::support::registry::Package; +use cargotest::ChannelChanger; use hamcrest::{assert_that, existing_file, existing_dir, is_not}; use tempdir::TempDir; @@ -783,9 +784,9 @@ assert_that(p.cargo("build"), execs().with_status(101).with_stderr(&format!( -r#"[ERROR] no matching package named `notquitebar` found (required by `foo`) +r#"error: no matching package named `notquitebar` found location searched: {proj_dir}/bar -version required: * +required by package `foo v0.0.1 ({proj_dir})` "#, proj_dir = p.url()))); } @@ -830,6 +831,260 @@ } #[test] +fn cargo_compile_path_with_offline() { + let p = project("foo") + .file("Cargo.toml", r#" + [package] + name = "foo" + version = "0.0.1" + authors = [] + + [dependencies.bar] + path = "bar" + "#) + .file("src/lib.rs", "") + .file("bar/Cargo.toml", r#" + [package] + name = "bar" + version = "0.0.1" + authors = [] + "#) + .file("bar/src/lib.rs", "") + .build(); + + assert_that(p.cargo("build").masquerade_as_nightly_cargo().arg("-Zoffline"), + execs().with_status(0)); +} + +#[test] +fn cargo_compile_with_downloaded_dependency_with_offline() { + Package::new("present_dep", "1.2.3") + .file("Cargo.toml", r#" + [project] + name = "present_dep" + version = "1.2.3" + "#) + .file("src/lib.rs", "") + .publish(); + + { + // make package downloaded + let p = project("foo") + .file("Cargo.toml", r#" + [project] + name = "foo" + version = "0.1.0" + + [dependencies] + present_dep = "1.2.3" + "#) + .file("src/lib.rs", "") + .build(); + assert_that(p.cargo("build"),execs().with_status(0)); + } + + let p2 = project("bar") + .file("Cargo.toml", r#" + [project] + name = "bar" + version = "0.1.0" + + [dependencies] + present_dep = "1.2.3" + "#) + .file("src/lib.rs", "") + .build(); + + assert_that(p2.cargo("build").masquerade_as_nightly_cargo().arg("-Zoffline"), + execs().with_status(0) + .with_stderr(format!("\ +[COMPILING] present_dep v1.2.3 +[COMPILING] bar v0.1.0 ([..]) +[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]"))); + +} + +#[test] +fn cargo_compile_offline_not_try_update() { + let p = project("bar") + .file("Cargo.toml", r#" + [project] + name = "bar" + version = "0.1.0" + + [dependencies] + not_cached_dep = "1.2.5" + "#) + .file("src/lib.rs", "") + .build(); + + assert_that(p.cargo("build").masquerade_as_nightly_cargo().arg("-Zoffline"), + execs().with_status(101) + .with_stderr("\ +error: no matching package named `not_cached_dep` found +location searched: registry `[..]` +required by package `bar v0.1.0 ([..])` +As a reminder, you're using offline mode (-Z offline) \ +which can sometimes cause surprising resolution failures, \ +if this error is too confusing you may with to retry \ +without the offline flag.")); +} + +#[test] +fn compile_offline_without_maxvers_cached(){ + Package::new("present_dep", "1.2.1").publish(); + Package::new("present_dep", "1.2.2").publish(); + + Package::new("present_dep", "1.2.3") + .file("Cargo.toml", r#" + [project] + name = "present_dep" + version = "1.2.3" + "#) + .file("src/lib.rs", r#"pub fn get_version()->&'static str {"1.2.3"}"#) + .publish(); + + Package::new("present_dep", "1.2.5") + .file("Cargo.toml", r#" + [project] + name = "present_dep" + version = "1.2.5" + "#) + .file("src/lib.rs", r#"pub fn get_version(){"1.2.5"}"#) + .publish(); + + { + // make package cached + let p = project("foo") + .file("Cargo.toml", r#" + [project] + name = "foo" + version = "0.1.0" + + [dependencies] + present_dep = "=1.2.3" + "#) + .file("src/lib.rs", "") + .build(); + assert_that(p.cargo("build"),execs().with_status(0)); + } + + let p2 = project("foo") + .file("Cargo.toml", r#" + [project] + name = "foo" + version = "0.1.0" + + [dependencies] + present_dep = "1.2" + "#) + .file("src/main.rs", "\ +extern crate present_dep; +fn main(){ + println!(\"{}\", present_dep::get_version()); +}") + .build(); + + assert_that(p2.cargo("run").masquerade_as_nightly_cargo().arg("-Zoffline"), + execs().with_status(0) + .with_stderr(format!("\ +[COMPILING] present_dep v1.2.3 +[COMPILING] foo v0.1.0 ({url}) +[FINISHED] dev [unoptimized + debuginfo] target(s) in [..] + Running `[..]`", url = p2.url())) + .with_stdout("1.2.3") + ); +} + +#[test] +fn incompatible_dependencies() { + Package::new("bad", "0.1.0").publish(); + Package::new("bad", "1.0.0").publish(); + Package::new("bad", "1.0.1").publish(); + Package::new("bad", "1.0.2").publish(); + Package::new("foo", "0.1.0").dep("bad", "0.1.0").publish(); + Package::new("bar", "0.1.1").dep("bad", "=1.0.0").publish(); + Package::new("bar", "0.1.0").dep("bad", "=1.0.0").publish(); + Package::new("baz", "0.1.2").dep("bad", ">=1.0.1").publish(); + Package::new("baz", "0.1.1").dep("bad", ">=1.0.1").publish(); + Package::new("baz", "0.1.0").dep("bad", ">=1.0.1").publish(); + + let p = project("transitive_load_test") + .file("Cargo.toml", r#" + [project] + name = "incompatible_dependencies" + version = "0.0.1" + + [dependencies] + foo = "0.1.0" + bar = "0.1.0" + baz = "0.1.0" + "#) + .file("src/main.rs", "fn main(){}") + .build(); + + assert_that(p.cargo("build"), + execs().with_status(101) + .with_stderr_contains("\ +error: failed to select a version for `bad` +all possible versions conflict with previously selected versions of `bad` +required by package `baz v0.1.0` + ... which is depended on by `incompatible_dependencies v0.0.1 ([..])` + previously selected package `bad v0.1.0` + ... which is depended on by `foo v0.1.0` + ... which is depended on by `incompatible_dependencies v0.0.1 ([..])` + previously selected package `bad v1.0.0` + ... which is depended on by `bar v0.1.0` + ... which is depended on by `incompatible_dependencies v0.0.1 ([..])` + possible versions to select: 1.0.2, 1.0.1")); +} + +#[test] +fn compile_offline_while_transitive_dep_not_cached() { + let bar = Package::new("bar", "1.0.0"); + let bar_path = bar.archive_dst(); + bar.publish(); + + let mut content = Vec::new(); + + let mut file = File::open(bar_path.clone()).ok().unwrap(); + let _ok = file.read_to_end(&mut content).ok().unwrap(); + drop(file); + drop(File::create(bar_path.clone()).ok().unwrap() ); + + Package::new("foo", "0.1.0").dep("bar", "1.0.0").publish(); + + let p = project("transitive_load_test") + .file("Cargo.toml", r#" + [project] + name = "transitive_load_test" + version = "0.0.1" + + [dependencies] + foo = "0.1.0" + "#) + .file("src/main.rs", "fn main(){}") + .build(); + + // simulate download foo, but fail to download bar + let _out = p.cargo("build").exec_with_output(); + + drop( File::create(bar_path).ok().unwrap().write_all(&content) ); + + assert_that(p.cargo("build").masquerade_as_nightly_cargo().arg("-Zoffline"), + execs().with_status(101) + .with_stderr("\ +error: no matching package named `bar` found +location searched: registry `[..]` +required by package `foo v0.1.0` + ... which is depended on by `transitive_load_test v0.0.1 ([..]/transitive_load_test)` +As a reminder, you're using offline mode (-Z offline) \ +which can sometimes cause surprising resolution failures, \ +if this error is too confusing you may with to retry \ +without the offline flag.")); +} + +#[test] fn compile_path_dep_then_change_version() { let p = project("foo") .file("Cargo.toml", r#" @@ -862,9 +1117,10 @@ assert_that(p.cargo("build"), execs().with_status(101).with_stderr("\ -[ERROR] no matching version `= 0.0.1` found for package `bar` (required by `foo`) +error: no matching version `= 0.0.1` found for package `bar` location searched: [..] versions found: 0.0.2 +required by package `foo v0.0.1 ([..]/foo)` consider running `cargo update` to update a path dependency's locked version ")); } @@ -3553,107 +3809,6 @@ } } -#[test] -fn wasm32_final_outputs() { - use cargo::core::{Shell, Target, Workspace}; - use cargo::ops::{self, BuildConfig, Context, CompileMode, CompileOptions, Kind, Unit}; - use cargo::util::Config; - use cargo::util::important_paths::find_root_manifest_for_wd; - - let target_triple = "wasm32-unknown-emscripten"; - - let p = project("foo") - .file("Cargo.toml", r#" - [project] - name = "foo-bar" - authors = [] - version = "0.1.0" - "#) - .file("src/main.rs", "fn main() {}") - .build(); - - // We can't cross-compile the project to wasm target unless we have emscripten installed. - // So here we will not run `cargo build`, but just create cargo_rustc::Context and ask it - // what the target file names would be. - - // Create various stuff required to build cargo_rustc::Context. - let shell = Shell::new(); - let config = Config::new(shell, p.root(), p.root()); - let root = find_root_manifest_for_wd(None, config.cwd()).expect("Can't find the root manifest"); - let ws = Workspace::new(&root, &config).expect("Can't create workspace"); - - let opts = CompileOptions { - target: Some(target_triple), - .. CompileOptions::default(&config, CompileMode::Build) - }; - - let specs = opts.spec.into_package_id_specs(&ws).expect("Can't create specs"); - - let (packages, resolve) = ops::resolve_ws_precisely( - &ws, - None, - opts.features, - opts.all_features, - opts.no_default_features, - &specs, - ).expect("Can't create resolve"); - - let build_config = BuildConfig { - requested_target: Some(target_triple.to_string()), - jobs: 1, - .. BuildConfig::default() - }; - - let pkgid = packages - .package_ids() - .filter(|id| id.name() == "foo-bar") - .collect::>(); - let pkg = packages.get(pkgid[0]).expect("Can't get package"); - - let target = Target::bin_target("foo-bar", p.root().join("src/main.rs"), None); - - let unit = Unit { - pkg: &pkg, - target: &target, - profile: &ws.profiles().dev, - kind: Kind::Target, - }; - let units = vec![unit]; - - // Finally, create the cargo_rustc::Context. - let mut ctx = Context::new( - &ws, - &resolve, - &packages, - &config, - build_config, - ws.profiles(), - ).expect("Can't create context"); - - // Ask the context to resolve target file names. - ctx.probe_target_info(&units).expect("Can't probe target info"); - let target_filenames = ctx.target_filenames(&unit).expect("Can't get target file names"); - - // Verify the result. - let mut expected = vec!["debug/foo-bar.js", "debug/foo_bar.wasm"]; - - assert_eq!(target_filenames.len(), expected.len()); - - let mut target_filenames = target_filenames - .iter() - .map(|&(_, ref link_dst, _)| link_dst.clone().unwrap()) - .collect::>(); - target_filenames.sort(); - expected.sort(); - - for (expected, actual) in expected.iter().zip(target_filenames.iter()) { - assert!( - actual.ends_with(expected), - format!("{:?} does not end with {}", actual, expected) - ); - } -} - #[test] fn deterministic_cfg_flags() { // This bug is non-deterministic diff -Nru cargo-0.25.0/tests/cargo-features.rs cargo-0.26.0/tests/cargo-features.rs --- cargo-0.25.0/tests/cargo-features.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/cargo-features.rs 2018-02-26 21:17:55.000000000 +0000 @@ -264,10 +264,10 @@ "#) .file("src/lib.rs", "") .build(); - assert_that(p.cargo("package") + assert_that(p.cargo("publish") .masquerade_as_nightly_cargo(), execs().with_status(101) .with_stderr("\ -error: cannot package or publish crates which activate nightly-only cargo features +error: cannot publish crates which activate nightly-only cargo features to crates.io ")); } diff -Nru cargo-0.25.0/tests/cargotest/Cargo.toml cargo-0.26.0/tests/cargotest/Cargo.toml --- cargo-0.25.0/tests/cargotest/Cargo.toml 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/cargotest/Cargo.toml 2018-02-26 21:17:55.000000000 +0000 @@ -12,8 +12,8 @@ flate2 = "1.0" git2 = { version = "0.6", default-features = false } hamcrest = "=0.1.1" -hex = "0.2" -log = "0.3" +hex = "0.3" +log = "0.4" serde_json = "1.0" tar = { version = "0.4", default-features = false } url = "1.1" diff -Nru cargo-0.25.0/tests/cargotest/lib.rs cargo-0.26.0/tests/cargotest/lib.rs --- cargo-0.25.0/tests/cargotest/lib.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/cargotest/lib.rs 2018-02-26 21:17:55.000000000 +0000 @@ -46,8 +46,8 @@ .env("__CARGO_TEST_ROOT", support::paths::root()) // Force cargo to think it's on the stable channel for all tests, this - // should hopefully not suprise us as we add cargo features over time and - // cargo rides the trains + // should hopefully not surprise us as we add cargo features over time and + // cargo rides the trains. .env("__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS", "stable") // For now disable incremental by default as support hasn't ridden to the diff -Nru cargo-0.25.0/tests/cargotest/support/mod.rs cargo-0.26.0/tests/cargotest/support/mod.rs --- cargo-0.25.0/tests/cargotest/support/mod.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/cargotest/support/mod.rs 2018-02-26 21:17:55.000000000 +0000 @@ -348,9 +348,11 @@ expect_exit_code: Option, expect_stdout_contains: Vec, expect_stderr_contains: Vec, + expect_either_contains: Vec, expect_stdout_contains_n: Vec<(String, usize)>, expect_stdout_not_contains: Vec, expect_stderr_not_contains: Vec, + expect_neither_contains: Vec, expect_json: Option>, } @@ -384,6 +386,11 @@ self } + pub fn with_either_contains(mut self, expected: S) -> Execs { + self.expect_either_contains.push(expected.to_string()); + self + } + pub fn with_stdout_contains_n(mut self, expected: S, number: usize) -> Execs { self.expect_stdout_contains_n.push((expected.to_string(), number)); self @@ -399,6 +406,11 @@ self } + pub fn with_neither_contains(mut self, expected: S) -> Execs { + self.expect_neither_contains.push(expected.to_string()); + self + } + pub fn with_json(mut self, expected: &str) -> Execs { self.expect_json = Some(expected.split("\n\n").map(|obj| { obj.parse().unwrap() @@ -449,6 +461,26 @@ self.match_std(Some(expect), &actual.stderr, "stderr", &actual.stdout, MatchKind::NotPresent)?; } + for expect in self.expect_neither_contains.iter() { + self.match_std(Some(expect), &actual.stdout, "stdout", + &actual.stdout, MatchKind::NotPresent)?; + + self.match_std(Some(expect), &actual.stderr, "stderr", + &actual.stderr, MatchKind::NotPresent)?; + } + + for expect in self.expect_either_contains.iter() { + let match_std = self.match_std(Some(expect), &actual.stdout, "stdout", + &actual.stdout, MatchKind::Partial); + let match_err = self.match_std(Some(expect), &actual.stderr, "stderr", + &actual.stderr, MatchKind::Partial); + + if let (Err(_), Err(_)) = (match_std, match_err) { + Err(format!("expected to find:\n\ + {}\n\n\ + did not find in either output.", expect))?; + } + } if let Some(ref objects) = self.expect_json { let stdout = str::from_utf8(&actual.stdout) @@ -531,7 +563,7 @@ } {} ham::expect(matches == number, - format!("expected to find {} occurences:\n\ + format!("expected to find {} occurrences:\n\ {}\n\n\ did not find in output:\n\ {}", number, out, @@ -762,9 +794,11 @@ expect_exit_code: None, expect_stdout_contains: Vec::new(), expect_stderr_contains: Vec::new(), + expect_either_contains: Vec::new(), expect_stdout_contains_n: Vec::new(), expect_stdout_not_contains: Vec::new(), expect_stderr_not_contains: Vec::new(), + expect_neither_contains: Vec::new(), expect_json: None, } } diff -Nru cargo-0.25.0/tests/cargotest/support/publish.rs cargo-0.26.0/tests/cargotest/support/publish.rs --- cargo-0.25.0/tests/cargotest/support/publish.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/cargotest/support/publish.rs 2018-02-26 21:17:55.000000000 +0000 @@ -12,7 +12,7 @@ t!(fs::create_dir_all(config.parent().unwrap())); t!(t!(File::create(&config)).write_all(format!(r#" [registry] - token = "api-token" + token = "api-token" [registries.alternative] index = "{registry}" @@ -21,7 +21,7 @@ let credentials = paths::root().join("home/.cargo/credentials"); t!(fs::create_dir_all(credentials.parent().unwrap())); t!(t!(File::create(&credentials)).write_all(br#" - [alternative] + [registries.alternative] token = "api-token" "#)); diff -Nru cargo-0.25.0/tests/cargotest/support/registry.rs cargo-0.26.0/tests/cargotest/support/registry.rs --- cargo-0.25.0/tests/cargotest/support/registry.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/cargotest/support/registry.rs 2018-02-26 21:17:55.000000000 +0000 @@ -6,7 +6,7 @@ use flate2::Compression; use flate2::write::GzEncoder; use git2; -use hex::ToHex; +use hex; use tar::{Builder, Header}; use url::Url; @@ -320,5 +320,5 @@ pub fn cksum(s: &[u8]) -> String { let mut sha = Sha256::new(); sha.update(s); - sha.finish().to_hex() + hex::encode(&sha.finish()) } diff -Nru cargo-0.25.0/tests/death.rs cargo-0.26.0/tests/death.rs --- cargo-0.25.0/tests/death.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/death.rs 2018-02-26 21:17:55.000000000 +0000 @@ -1,5 +1,7 @@ extern crate cargotest; extern crate libc; +#[cfg(windows)] +extern crate winapi; use std::fs; use std::io::{self, Read}; @@ -15,7 +17,7 @@ true } -// On Windows suport for these tests is only enabled through the usage of job +// On Windows support for these tests is only enabled through the usage of job // objects. Support for nested job objects, however, was added in recent-ish // versions of Windows, so this test may not always be able to succeed. // @@ -23,16 +25,16 @@ // can succeed or not. #[cfg(windows)] fn enabled() -> bool { - extern crate kernel32; - extern crate winapi; + use winapi::um::{handleapi, jobapi, jobapi2, processthreadsapi}; + unsafe { // If we're not currently in a job, then we can definitely run these // tests. - let me = kernel32::GetCurrentProcess(); + let me = processthreadsapi::GetCurrentProcess(); let mut ret = 0; - let r = kernel32::IsProcessInJob(me, 0 as *mut _, &mut ret); + let r = jobapi::IsProcessInJob(me, 0 as *mut _, &mut ret); assert!(r != 0); - if ret == winapi::FALSE { + if ret == winapi::shared::minwindef::FALSE { return true } @@ -42,10 +44,10 @@ // // If we can't be added to a nested job, then these tests will // definitely fail, and there's not much we can do about that. - let job = kernel32::CreateJobObjectW(0 as *mut _, 0 as *const _); + let job = jobapi2::CreateJobObjectW(0 as *mut _, 0 as *const _); assert!(!job.is_null()); - let r = kernel32::AssignProcessToJobObject(job, me); - kernel32::CloseHandle(job); + let r = jobapi2::AssignProcessToJobObject(job, me); + handleapi::CloseHandle(job); r != 0 } } diff -Nru cargo-0.25.0/tests/directory.rs cargo-0.26.0/tests/directory.rs --- cargo-0.25.0/tests/directory.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/directory.rs 2018-02-26 21:17:55.000000000 +0000 @@ -195,9 +195,9 @@ error: failed to compile `bar v0.1.0`, intermediate artifacts can be found at `[..]` Caused by: - no matching package named `baz` found (required by `bar`) + no matching package named `baz` found location searched: registry `https://github.com/rust-lang/crates.io-index` -version required: ^9.8.7 +required by package `bar v0.1.0` ")); } @@ -276,9 +276,9 @@ assert_that(p.cargo("build"), execs().with_status(101).with_stderr("\ -error: no matching package named `foo` found (required by `bar`) +error: no matching package named `foo` found location searched: [..] -version required: ^0.1.0 +required by package `bar v0.1.0 ([..])` ")); } @@ -496,6 +496,40 @@ .build(); let p = project("bar") + .file("Cargo.toml", r#" + [package] + name = "bar" + version = "0.1.0" + authors = [] + + [dependencies] + foo = "0.1.0" + "#) + .file("src/lib.rs", "") + .build(); + + assert_that(p.cargo("build"), execs().with_status(0)); +} + +#[test] +fn random_files_ok() { + setup(); + + VendorPackage::new("foo") + .file("Cargo.toml", r#" + [package] + name = "foo" + version = "0.1.0" + authors = [] + "#) + .file("src/lib.rs", "") + .build(); + VendorPackage::new("bar") + .file("foo", "") + .file("../test", "") + .build(); + + let p = project("bar") .file("Cargo.toml", r#" [package] name = "bar" diff -Nru cargo-0.25.0/tests/doc.rs cargo-0.26.0/tests/doc.rs --- cargo-0.25.0/tests/doc.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/doc.rs 2018-02-26 21:17:55.000000000 +0000 @@ -1034,3 +1034,37 @@ .with_stderr_contains("[..] Updating registry `[..]`") .with_stderr_contains("[..] Documenting a v0.1.0 ([..])")); } + +#[test] +fn doc_workspace_open_help_message() { + let p = project("foo") + .file("Cargo.toml", r#" + [workspace] + members = ["foo", "bar"] + "#) + .file("foo/Cargo.toml", r#" + [package] + name = "foo" + version = "0.1.0" + "#) + .file("foo/src/lib.rs", "") + .file("bar/Cargo.toml", r#" + [package] + name = "bar" + version = "0.1.0" + "#) + .file("bar/src/lib.rs", "") + .build(); + + // The order in which bar is compiled or documented is not deterministic + assert_that(p.cargo("doc") + .arg("--all") + .arg("--open"), + execs().with_status(101) + .with_stderr_contains("[..] Documenting bar v0.1.0 ([..])") + .with_stderr_contains("[..] Documenting foo v0.1.0 ([..])") + .with_stderr_contains("error: Passing multiple packages and `open` is not supported.") + .with_stderr_contains("Please re-run this command with `-p ` where `` is one of the following:") + .with_stderr_contains(" foo") + .with_stderr_contains(" bar")); +} diff -Nru cargo-0.25.0/tests/generate-lockfile.rs cargo-0.26.0/tests/generate-lockfile.rs --- cargo-0.25.0/tests/generate-lockfile.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/generate-lockfile.rs 2018-02-26 21:17:55.000000000 +0000 @@ -75,6 +75,31 @@ } #[test] +fn no_index_update() { + use cargotest::ChannelChanger; + let p = project("foo") + .file("Cargo.toml", r#" + [package] + name = "foo" + authors = [] + version = "0.0.1" + + [dependencies] + serde = "1.0" + "#) + .file("src/main.rs", "fn main() {}") + .build(); + + assert_that(p.cargo("generate-lockfile"), + execs().with_status(0).with_stdout("") + .with_stderr_contains(" Updating registry `https://github.com/rust-lang/crates.io-index`")); + + assert_that(p.cargo("generate-lockfile").masquerade_as_nightly_cargo().arg("-Zno-index-update"), + execs().with_status(0).with_stdout("") + .with_stderr_does_not_contain(" Updating registry `https://github.com/rust-lang/crates.io-index`")); +} + +#[test] fn preserve_metadata() { let p = project("foo") .file("Cargo.toml", r#" diff -Nru cargo-0.25.0/tests/git.rs cargo-0.26.0/tests/git.rs --- cargo-0.25.0/tests/git.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/git.rs 2018-02-26 21:17:55.000000000 +0000 @@ -15,6 +15,7 @@ use cargotest::sleep_ms; use cargotest::support::paths::{self, CargoPathExt}; use cargotest::support::{git, project, execs, main_file, path2url}; +use cargotest::ChannelChanger; use hamcrest::{assert_that,existing_file}; #[test] @@ -76,6 +77,141 @@ } #[test] +fn cargo_compile_forbird_git_httpsrepo_offline() { + + let p = project("need_remote_repo") + .file("Cargo.toml", r#" + + [project] + name = "need_remote_repo" + version = "0.5.0" + authors = ["chabapok@example.com"] + + [dependencies.dep1] + git = 'https://github.com/some_user/dep1.git' + "#) + .file("src/main.rs", "") + .build(); + + + assert_that(p.cargo("build").masquerade_as_nightly_cargo().arg("-Zoffline"), + execs().with_status(101). + with_stderr("\ +error: failed to load source for a dependency on `dep1` + +Caused by: + Unable to update https://github.com/some_user/dep1.git + +Caused by: + can't checkout from 'https://github.com/some_user/dep1.git': you are in the offline mode (-Z offline)")); +} + + +#[test] +fn cargo_compile_offline_with_cached_git_dep() { + let git_project = git::new("dep1", |project| { + project + .file("Cargo.toml", r#" + [project] + name = "dep1" + version = "0.5.0" + authors = ["chabapok@example.com"] + + [lib] + name = "dep1""#) + .file("src/lib.rs", r#" + pub static COOL_STR:&str = "cached git repo rev1"; + "#) + }).unwrap(); + + let repo = git2::Repository::open(&git_project.root()).unwrap(); + let rev1 = repo.revparse_single("HEAD").unwrap().id(); + + // Commit the changes and make sure we trigger a recompile + File::create(&git_project.root().join("src/lib.rs")).unwrap().write_all(br#" + pub static COOL_STR:&str = "cached git repo rev2"; + "#).unwrap(); + git::add(&repo); + let rev2 = git::commit(&repo); + + { + // cache to regisrty rev1 and rev2 + let prj = project("cache_git_dep") + .file("Cargo.toml", &format!(r#" + [project] + name = "cache_git_dep" + version = "0.5.0" + + [dependencies.dep1] + git = '{}' + rev = "{}" + "#, git_project.url(), rev1.clone())) + .file("src/main.rs", "fn main(){}") + .build(); + assert_that(prj.cargo("build"), execs().with_status(0)); + + File::create(&prj.root().join("Cargo.toml")).unwrap().write_all( + &format!(r#" + [project] + name = "cache_git_dep" + version = "0.5.0" + + [dependencies.dep1] + git = '{}' + rev = "{}" + "#, git_project.url(), rev2.clone()).as_bytes() + ).unwrap(); + assert_that(prj.cargo("build"), execs().with_status(0)); + } + + let project = project("foo") + .file("Cargo.toml", &format!(r#" + [project] + name = "foo" + version = "0.5.0" + + [dependencies.dep1] + git = '{}' + "#, git_project.url())) + .file("src/main.rs", &main_file(r#""hello from {}", dep1::COOL_STR"#, &["dep1"])) + .build(); + + let root = project.root(); + let git_root = git_project.root(); + + assert_that(project.cargo("build").masquerade_as_nightly_cargo().arg("-Zoffline"), + execs().with_stderr(format!("\ +[COMPILING] dep1 v0.5.0 ({}#[..]) +[COMPILING] foo v0.5.0 ({}) +[FINISHED] dev [unoptimized + debuginfo] target(s) in [..]", + path2url(git_root), + path2url(root) + ))); + + assert_that(&project.bin("foo"), existing_file()); + + assert_that(process(&project.bin("foo")), + execs().with_stdout("hello from cached git repo rev2\n")); + + drop( File::create(&project.root().join("Cargo.toml")).unwrap() + .write_all(&format!(r#" + [project] + name = "foo" + version = "0.5.0" + + [dependencies.dep1] + git = '{}' + rev = "{}" + "#, git_project.url(), rev1).as_bytes()).unwrap() ); + + let _out = project.cargo("build").masquerade_as_nightly_cargo() + .arg("-Zoffline").exec_with_output(); + assert_that(process(&project.bin("foo")), + execs().with_stdout("hello from cached git repo rev1\n")); +} + + +#[test] fn cargo_compile_git_dep_branch() { let project = project("foo"); let git_project = git::new("dep1", |project| { diff -Nru cargo-0.25.0/tests/login.rs cargo-0.26.0/tests/login.rs --- cargo-0.25.0/tests/login.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/login.rs 2018-02-26 21:17:55.000000000 +0000 @@ -53,7 +53,9 @@ // A registry has been provided, so check that the token exists in a // table for the registry. (Some(registry), toml::Value::Table(table)) => { - table.get(registry).and_then(|registry_table| { + table.get("registries") + .and_then(|registries_table| registries_table.get(registry)) + .and_then(|registry_table| { match registry_table.get("token") { Some(&toml::Value::String(ref token)) => Some(token.as_str().to_string()), _ => None, @@ -62,7 +64,9 @@ }, // There is no registry provided, so check the global token instead. (None, toml::Value::Table(table)) => { - table.get("token").and_then(|v| { + table.get("registry") + .and_then(|registry_table| registry_table.get("token")) + .and_then(|v| { match v { &toml::Value::String(ref token) => Some(token.as_str().to_string()), _ => None, diff -Nru cargo-0.25.0/tests/new.rs cargo-0.26.0/tests/new.rs --- cargo-0.25.0/tests/new.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/new.rs 2018-02-26 21:17:55.000000000 +0000 @@ -164,37 +164,6 @@ } #[test] -fn rust_prefix_stripped() { - assert_that(cargo_process("new").arg("--lib").arg("rust-foo").env("USER", "foo"), - execs().with_status(0) - .with_stderr_contains("note: package will be named `foo`; use --name to override")); - let toml = paths::root().join("rust-foo/Cargo.toml"); - let mut contents = String::new(); - File::open(&toml).unwrap().read_to_string(&mut contents).unwrap(); - assert!(contents.contains(r#"name = "foo""#)); -} - -#[test] -fn bin_disables_stripping() { - assert_that(cargo_process("new").arg("rust-foo").arg("--bin").env("USER", "foo"), - execs().with_status(0)); - let toml = paths::root().join("rust-foo/Cargo.toml"); - let mut contents = String::new(); - File::open(&toml).unwrap().read_to_string(&mut contents).unwrap(); - assert!(contents.contains(r#"name = "rust-foo""#)); -} - -#[test] -fn explicit_name_not_stripped() { - assert_that(cargo_process("new").arg("foo").arg("--name").arg("rust-bar").env("USER", "foo"), - execs().with_status(0)); - let toml = paths::root().join("foo/Cargo.toml"); - let mut contents = String::new(); - File::open(&toml).unwrap().read_to_string(&mut contents).unwrap(); - assert!(contents.contains(r#"name = "rust-bar""#)); -} - -#[test] fn finds_author_user() { create_empty_gitconfig(); assert_that(cargo_process("new").arg("foo").env("USER", "foo"), @@ -416,3 +385,11 @@ cargo new [..] ")); } + +#[test] +fn explicit_invalid_name_not_suggested() { + assert_that(cargo_process("new").arg("--name").arg("10-invalid").arg("a"), + execs().with_status(101) + .with_stderr("\ +[ERROR] Package names starting with a digit cannot be used as a crate name")); +} diff -Nru cargo-0.25.0/tests/package.rs cargo-0.26.0/tests/package.rs --- cargo-0.25.0/tests/package.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/package.rs 2018-02-26 21:17:55.000000000 +0000 @@ -9,8 +9,8 @@ use std::io::prelude::*; use std::path::{Path, PathBuf}; -use cargotest::{cargo_process, process}; -use cargotest::support::{project, execs, paths, git, path2url, cargo_exe}; +use cargotest::{cargo_process, process, ChannelChanger}; +use cargotest::support::{project, execs, paths, git, path2url, cargo_exe, registry}; use cargotest::support::registry::Package; use flate2::read::GzDecoder; use hamcrest::{assert_that, existing_file, contains, equal_to}; @@ -330,10 +330,6 @@ See [..] [WARNING] [..] file `some_dir[/]dir_deep_3[/]some_dir[/]file` WILL be excluded [..] See [..] -[WARNING] [..] file `some_dir[/]dir_deep_4[/]some_dir[/]file` WILL be excluded [..] -See [..] -[WARNING] [..] file `some_dir[/]dir_deep_5[/]some_dir[/]file` WILL be excluded [..] -See [..] [WARNING] [..] file `some_dir[/]file_deep_1` WILL be excluded [..] See [..] [ARCHIVING] [..] @@ -715,6 +711,8 @@ Package::new("ghi", "1.0.0").publish(); let p = project("foo") .file("Cargo.toml", r#" + cargo-features = ["alternative-registries"] + [project] name = "foo" version = "0.0.1" @@ -730,7 +728,7 @@ [dependencies] bar = { path = "bar", version = "0.1" } - def = "1.0" + def = { version = "1.0", registry = "alternative" } ghi = "1.0" abc = "1.0" "#) @@ -744,7 +742,9 @@ .file("bar/src/lib.rs", "") .build(); - assert_that(p.cargo("package").arg("--no-verify"), + assert_that(p.cargo("package") + .masquerade_as_nightly_cargo() + .arg("--no-verify"), execs().with_status(0)); let f = File::open(&p.root().join("target/package/foo-0.0.1.crate")).unwrap(); @@ -761,6 +761,7 @@ // BTreeMap makes the order of dependencies in the generated file deterministic // by sorting alphabetically assert_that(&contents[..], equal_to( +&*format!( r#"# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically @@ -773,6 +774,8 @@ # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) +cargo-features = ["alternative-registries"] + [package] name = "foo" version = "0.0.1" @@ -791,10 +794,12 @@ [dependencies.def] version = "1.0" +registry-index = "{}" [dependencies.ghi] version = "1.0" -"#)); +"#, + registry::alt_registry()))); } #[test] @@ -878,3 +883,120 @@ assert_that(p.cargo("package").arg("--no-verify"), execs().with_status(0)); } + +#[test] +fn test_epoch() { + let p = project("foo") + .file("Cargo.toml", r#" + cargo-features = ["epoch"] + [package] + name = "foo" + version = "0.0.1" + authors = [] + rust = "2018" + "#) + .file("src/lib.rs", r#" "#) + .build(); + + assert_that(p.cargo("build").arg("-v") + .masquerade_as_nightly_cargo(), + execs() + // -Zepoch is still in flux and we're not passing -Zunstable-options + // from Cargo so it will probably error. Only partially match the output + // until stuff stabilizes + .with_stderr_contains(format!("\ +[COMPILING] foo v0.0.1 ({url}) +[RUNNING] `rustc --crate-name foo src[/]lib.rs --crate-type lib \ + --emit=dep-info,link -Zepoch=2018 -C debuginfo=2 \ + -C metadata=[..] \ + --out-dir [..] \ + -L dependency={dir}[/]target[/]debug[/]deps` +", dir = p.root().display(), url = p.url()))); +} + +#[test] +fn test_epoch_missing() { + // no epoch = 2015 + let p = project("foo") + .file("Cargo.toml", r#" + cargo-features = ["epoch"] + [package] + name = "foo" + version = "0.0.1" + authors = [] + "#) + .file("src/lib.rs", r#" "#) + .build(); + + assert_that(p.cargo("build").arg("-v") + .masquerade_as_nightly_cargo(), + execs() + // -Zepoch is still in flux and we're not passing -Zunstable-options + // from Cargo so it will probably error. Only partially match the output + // until stuff stabilizes + .with_stderr_contains(format!("\ +[COMPILING] foo v0.0.1 ({url}) +[RUNNING] `rustc --crate-name foo src[/]lib.rs --crate-type lib \ + --emit=dep-info,link -Zepoch=2015 -C debuginfo=2 \ + -C metadata=[..] \ + --out-dir [..] \ + -L dependency={dir}[/]target[/]debug[/]deps` +", dir = p.root().display(), url = p.url()))); +} + +#[test] +fn test_epoch_malformed() { + let p = project("foo") + .file("Cargo.toml", r#" + cargo-features = ["epoch"] + [package] + name = "foo" + version = "0.0.1" + authors = [] + rust = "chicken" + "#) + .file("src/lib.rs", r#" "#) + .build(); + + assert_that(p.cargo("build").arg("-v") + .masquerade_as_nightly_cargo(), + execs() + .with_status(101) + .with_stderr(format!("\ +error: failed to parse manifest at `[..]` + +Caused by: + the `rust` key must be one of: `2015`, `2018` +"))); +} + + +#[test] +fn test_epoch_nightly() { + let p = project("foo") + .file("Cargo.toml", r#" + [package] + name = "foo" + version = "0.0.1" + authors = [] + rust = "2015" + "#) + .file("src/lib.rs", r#" "#) + .build(); + + assert_that(p.cargo("build").arg("-v") + .masquerade_as_nightly_cargo(), + execs() + .with_status(101) + .with_stderr(format!("\ +error: failed to parse manifest at `[..]` + +Caused by: + epoches are unstable + +Caused by: + feature `epoch` is required + +consider adding `cargo-features = [\"epoch\"]` to the manifest +"))); +} diff -Nru cargo-0.25.0/tests/patch.rs cargo-0.26.0/tests/patch.rs --- cargo-0.25.0/tests/patch.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/patch.rs 2018-02-26 21:17:55.000000000 +0000 @@ -796,3 +796,59 @@ [FINISHED] [..] ")); } + +#[test] +fn patch_depends_on_another_patch() { + Package::new("foo", "0.1.0") + .file("src/lib.rs", "broken code") + .publish(); + + Package::new("bar", "0.1.0") + .dep("foo", "0.1") + .file("src/lib.rs", "broken code") + .publish(); + + let p = project("p") + .file("Cargo.toml", r#" + [package] + name = "p" + authors = [] + version = "0.1.0" + + [dependencies] + foo = "0.1" + bar = "0.1" + + [patch.crates-io] + foo = { path = "foo" } + bar = { path = "bar" } + "#) + .file("src/lib.rs", "") + .file("foo/Cargo.toml", r#" + [package] + name = "foo" + version = "0.1.1" + authors = [] + "#) + .file("foo/src/lib.rs", r#""#) + .file("bar/Cargo.toml", r#" + [package] + name = "bar" + version = "0.1.1" + authors = [] + + [dependencies] + foo = "0.1" + "#) + .file("bar/src/lib.rs", r#""#) + .build(); + + assert_that(p.cargo("build"), + execs().with_status(0)); + + // Nothing should be rebuilt, no registry should be updated. + assert_that(p.cargo("build"), + execs().with_status(0).with_stderr("\ +[FINISHED] [..] +")); +} diff -Nru cargo-0.25.0/tests/path.rs cargo-0.26.0/tests/path.rs --- cargo-0.25.0/tests/path.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/path.rs 2018-02-26 21:17:55.000000000 +0000 @@ -950,9 +950,9 @@ assert_that(p.cargo("build"), execs().with_status(101) .with_stderr("\ -error: no matching package named `bar` found (required by `foo`) +error: no matching package named `bar` found location searched: [..] -version required: * +required by package `foo v0.5.0 ([..])` ")); } @@ -986,3 +986,29 @@ assert_that(&p.root().join("target/debug/libfoo.rlib"), existing_file()); } + +#[test] +fn thin_lto_works() { + if !cargotest::is_nightly() { + return + } + let p = project("foo") + .file("Cargo.toml", r#" + [project] + name = "top" + version = "0.5.0" + authors = [] + + [profile.release] + lto = 'thin' + "#) + .file("src/main.rs", "fn main() {}") + .build(); + + assert_that(p.cargo("build").arg("--release").arg("-v"), + execs().with_stderr("\ +[COMPILING] top [..] +[RUNNING] `rustc [..] -C lto=thin [..]` +[FINISHED] [..] +")); +} diff -Nru cargo-0.25.0/tests/publish.rs cargo-0.26.0/tests/publish.rs --- cargo-0.25.0/tests/publish.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/publish.rs 2018-02-26 21:17:55.000000000 +0000 @@ -4,7 +4,7 @@ extern crate tar; use std::io::prelude::*; -use std::fs::File; +use std::fs::{self, File}; use std::io::SeekFrom; use cargotest::ChannelChanger; @@ -70,6 +70,72 @@ } } +#[test] +fn old_token_location() { + publish::setup(); + + // publish::setup puts a token in this file. + fs::remove_file(paths::root().join(".cargo/config")).unwrap(); + + let credentials = paths::root().join("home/.cargo/credentials"); + File::create(credentials) + .unwrap() + .write_all(br#" + token = "api-token" + "#) + .unwrap(); + + let p = project("foo") + .file("Cargo.toml", r#" + [project] + name = "foo" + version = "0.0.1" + authors = [] + license = "MIT" + description = "foo" + "#) + .file("src/main.rs", "fn main() {}") + .build(); + + assert_that(p.cargo("publish").arg("--no-verify") + .arg("--index").arg(publish::registry().to_string()), + execs().with_status(0).with_stderr(&format!("\ +[UPDATING] registry `{reg}` +[WARNING] manifest has no documentation, [..] +See [..] +[PACKAGING] foo v0.0.1 ({dir}) +[UPLOADING] foo v0.0.1 ({dir}) +", + dir = p.url(), + reg = publish::registry()))); + + let mut f = File::open(&publish::upload_path().join("api/v1/crates/new")).unwrap(); + // Skip the metadata payload and the size of the tarball + let mut sz = [0; 4]; + assert_eq!(f.read(&mut sz).unwrap(), 4); + let sz = ((sz[0] as u32) << 0) | + ((sz[1] as u32) << 8) | + ((sz[2] as u32) << 16) | + ((sz[3] as u32) << 24); + f.seek(SeekFrom::Current(sz as i64 + 4)).unwrap(); + + // Verify the tarball + let mut rdr = GzDecoder::new(f); + assert_eq!(rdr.header().unwrap().filename().unwrap(), b"foo-0.0.1.crate"); + let mut contents = Vec::new(); + rdr.read_to_end(&mut contents).unwrap(); + let mut ar = Archive::new(&contents[..]); + for file in ar.entries().unwrap() { + let file = file.unwrap(); + let fname = file.header().path_bytes(); + let fname = &*fname; + assert!(fname == b"foo-0.0.1/Cargo.toml" || + fname == b"foo-0.0.1/Cargo.toml.orig" || + fname == b"foo-0.0.1/src/main.rs", + "unexpected filename: {:?}", file.header().path()); + } +} + // TODO: Deprecated // remove once it has been decided --host can be removed #[test] @@ -640,7 +706,8 @@ .build(); assert_that(p.cargo("publish").masquerade_as_nightly_cargo() - .arg("--index").arg(publish::registry().to_string()), + .arg("--registry").arg("alternative") + .arg("-Zunstable-options"), execs().with_status(101).with_stderr("\ [ERROR] some crates cannot be published. `foo` is marked as unpublishable diff -Nru cargo-0.25.0/tests/registry.rs cargo-0.26.0/tests/registry.rs --- cargo-0.25.0/tests/registry.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/registry.rs 2018-02-26 21:17:55.000000000 +0000 @@ -110,9 +110,9 @@ assert_that(p.cargo("build"), execs().with_status(101).with_stderr("\ [UPDATING] registry [..] -[ERROR] no matching package named `nonexistent` found (required by `foo`) +error: no matching package named `nonexistent` found location searched: registry [..] -version required: >= 0.0.0 +required by package `foo v0.0.1 ([..])` ")); } @@ -136,9 +136,10 @@ assert_that(p.cargo("build"), execs().with_status(101).with_stderr_contains("\ -[ERROR] no matching version `>= 1.0.0` found for package `foo` (required by `foo`) +error: no matching version `>= 1.0.0` found for package `foo` location searched: registry [..] versions found: 0.0.2, 0.0.1 +required by package `foo v0.0.1 ([..])` ")); Package::new("foo", "0.0.3").publish(); @@ -146,9 +147,10 @@ assert_that(p.cargo("build"), execs().with_status(101).with_stderr_contains("\ -[ERROR] no matching version `>= 1.0.0` found for package `foo` (required by `foo`) +error: no matching version `>= 1.0.0` found for package `foo` location searched: registry [..] versions found: 0.0.4, 0.0.3, 0.0.2, ... +required by package `foo v0.0.1 ([..])` ")); } @@ -204,9 +206,9 @@ assert_that(p.cargo("build"), execs().with_status(101).with_stderr_contains("\ -[ERROR] no matching package named `notyet` found (required by `foo`) -location searched: registry [..] -version required: >= 0.0.0 +error: no matching package named `notyet` found +location searched: registry `[..]` +required by package `foo v0.0.1 ([..])` ")); Package::new("notyet", "0.0.1").publish(); @@ -256,9 +258,9 @@ [ERROR] failed to verify package tarball Caused by: - no matching package named `notyet` found (required by `foo`) + no matching package named `notyet` found location searched: registry [..] -version required: ^0.0.1 +required by package `foo v0.0.1 ([..])` ")); Package::new("notyet", "0.0.1").publish(); @@ -401,9 +403,10 @@ assert_that(p.cargo("build"), execs().with_status(101).with_stderr_contains("\ -[ERROR] no matching version `= 0.0.2` found for package `baz` (required by `bar`) -location searched: registry [..] +error: no matching version `= 0.0.2` found for package `baz` +location searched: registry `[..]` versions found: 0.0.1 +required by package `bar v0.0.1` ")); } @@ -436,9 +439,9 @@ assert_that(p.cargo("update"), execs().with_status(101).with_stderr_contains("\ -[ERROR] no matching package named `bar` found (required by `foo`) +error: no matching package named `bar` found location searched: registry [..] -version required: * +required by package `foo v0.0.1 ([..])` ")); } @@ -553,6 +556,26 @@ } #[test] +fn update_offline(){ + use cargotest::ChannelChanger; + let p = project("foo") + .file("Cargo.toml", r#" + [project] + name = "foo" + version = "0.0.1" + authors = [] + + [dependencies] + bar = "*" + "#) + .file("src/main.rs", "fn main() {}") + .build(); + assert_that(p.cargo("update").masquerade_as_nightly_cargo().arg("-Zoffline"), + execs().with_status(101). + with_stderr("error: you can't update in the offline mode[..]")); +} + +#[test] fn dev_dependency_not_used() { let p = project("foo") .file("Cargo.toml", r#" diff -Nru cargo-0.25.0/tests/resolve.rs cargo-0.26.0/tests/resolve.rs --- cargo-0.25.0/tests/resolve.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/resolve.rs 2018-02-26 21:17:55.000000000 +0000 @@ -74,6 +74,13 @@ } } +impl ToPkgId for (&'static str, String) { + fn to_pkgid(&self) -> PackageId { + let (name, ref vers) = *self; + PackageId::new(name, vers, ®istry_loc()).unwrap() + } +} + macro_rules! pkg { ($pkgid:expr => [$($deps:expr),+]) => ({ let d: Vec = vec![$($deps.to_dep()),+]; @@ -365,6 +372,137 @@ } #[test] +fn resolving_with_constrained_sibling_backtrack_parent() { + // There is no point in considering all of the backtrack_trap{1,2} + // candidates since they can't change the result of failing to + // resolve 'constrained'. Cargo should (ideally) skip past them and resume + // resolution once the activation of the parent, 'bar', is rolled back. + // Note that the traps are slightly more constrained to make sure they + // get picked first. + let mut reglist = vec![ + pkg!(("foo", "1.0.0") => [dep_req("bar", "1.0"), + dep_req("constrained", "=1.0.0")]), + + pkg!(("bar", "1.0.0") => [dep_req("backtrack_trap1", "1.0.2"), + dep_req("backtrack_trap2", "1.0.2"), + dep_req("constrained", "1.0.0")]), + pkg!(("constrained", "1.0.0")), + pkg!(("backtrack_trap1", "1.0.0")), + pkg!(("backtrack_trap2", "1.0.0")), + ]; + // Bump this to make the test harder - it adds more versions of bar that will + // fail to resolve, and more versions of the traps to consider. + const NUM_BARS_AND_TRAPS: usize = 50; // minimum 2 + for i in 1..NUM_BARS_AND_TRAPS { + let vsn = format!("1.0.{}", i); + reglist.push(pkg!(("bar", vsn.clone()) => [dep_req("backtrack_trap1", "1.0.2"), + dep_req("backtrack_trap2", "1.0.2"), + dep_req("constrained", "1.0.1")])); + reglist.push(pkg!(("backtrack_trap1", vsn.clone()))); + reglist.push(pkg!(("backtrack_trap2", vsn.clone()))); + reglist.push(pkg!(("constrained", vsn.clone()))); + } + let reg = registry(reglist); + + let res = resolve(&pkg_id("root"), vec![ + dep_req("foo", "1"), + ], ®).unwrap(); + + assert_that(&res, contains(names(&[("root", "1.0.0"), + ("foo", "1.0.0"), + ("bar", "1.0.0"), + ("constrained", "1.0.0")]))); +} + +#[test] +fn resolving_with_constrained_sibling_backtrack_activation() { + // It makes sense to resolve most-constrained deps first, but + // with that logic the backtrack traps here come between the two + // attempted resolutions of 'constrained'. When backtracking, + // cargo should skip past them and resume resolution once the + // number of activations for 'constrained' changes. + let mut reglist = vec![ + pkg!(("foo", "1.0.0") => [dep_req("bar", "=1.0.0"), + dep_req("backtrack_trap1", "1.0"), + dep_req("backtrack_trap2", "1.0"), + dep_req("constrained", "<=1.0.60")]), + pkg!(("bar", "1.0.0") => [dep_req("constrained", ">=1.0.60")]), + ]; + // Bump these to make the test harder, but you'll also need to + // change the version constraints on `constrained` above. To correctly + // exercise Cargo, the relationship between the values is: + // NUM_CONSTRAINED - vsn < NUM_TRAPS < vsn + // to make sure the traps are resolved between `constrained`. + const NUM_TRAPS: usize = 45; // min 1 + const NUM_CONSTRAINED: usize = 100; // min 1 + for i in 0..NUM_TRAPS { + let vsn = format!("1.0.{}", i); + reglist.push(pkg!(("backtrack_trap1", vsn.clone()))); + reglist.push(pkg!(("backtrack_trap2", vsn.clone()))); + } + for i in 0..NUM_CONSTRAINED { + let vsn = format!("1.0.{}", i); + reglist.push(pkg!(("constrained", vsn.clone()))); + } + let reg = registry(reglist); + + let res = resolve(&pkg_id("root"), vec![ + dep_req("foo", "1"), + ], ®).unwrap(); + + assert_that(&res, contains(names(&[("root", "1.0.0"), + ("foo", "1.0.0"), + ("bar", "1.0.0"), + ("constrained", "1.0.60")]))); +} + +#[test] +fn resolving_with_constrained_sibling_transitive_dep_effects() { + // When backtracking due to a failed dependency, if Cargo is + // trying to be clever and skip irrelevant dependencies, care must + // be taken to not miss the transitive effects of alternatives. E.g. + // in the right-to-left resolution of the graph below, B may + // affect whether D is successfully resolved. + // + // A + // / | \ + // B C D + // | | + // C D + let reg = registry(vec![ + pkg!(("A", "1.0.0") => [dep_req("B", "1.0"), + dep_req("C", "1.0"), + dep_req("D", "1.0.100")]), + + pkg!(("B", "1.0.0") => [dep_req("C", ">=1.0.0")]), + pkg!(("B", "1.0.1") => [dep_req("C", ">=1.0.1")]), + + pkg!(("C", "1.0.0") => [dep_req("D", "1.0.0")]), + pkg!(("C", "1.0.1") => [dep_req("D", ">=1.0.1,<1.0.100")]), + pkg!(("C", "1.0.2") => [dep_req("D", ">=1.0.2,<1.0.100")]), + + pkg!(("D", "1.0.0")), + pkg!(("D", "1.0.1")), + pkg!(("D", "1.0.2")), + pkg!(("D", "1.0.100")), + pkg!(("D", "1.0.101")), + pkg!(("D", "1.0.102")), + pkg!(("D", "1.0.103")), + pkg!(("D", "1.0.104")), + pkg!(("D", "1.0.105")), + ]); + + let res = resolve(&pkg_id("root"), vec![ + dep_req("A", "1"), + ], ®).unwrap(); + + assert_that(&res, contains(names(&[("A", "1.0.0"), + ("B", "1.0.0"), + ("C", "1.0.0"), + ("D", "1.0.105")]))); +} + +#[test] fn resolving_but_no_exists() { let reg = registry(vec![ ]); @@ -375,9 +513,9 @@ assert!(res.is_err()); assert_eq!(res.err().unwrap().to_string(), "\ -no matching package named `foo` found (required by `root`) -location searched: registry `http://example.com/` -version required: ^1\ +no matching package named `foo` found\n\ +location searched: registry `http://example.com/`\n\ +required by package `root v1.0.0 (registry `http://example.com/`)`\ "); } diff -Nru cargo-0.25.0/tests/run.rs cargo-0.26.0/tests/run.rs --- cargo-0.25.0/tests/run.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/run.rs 2018-02-26 21:17:55.000000000 +0000 @@ -785,6 +785,49 @@ } #[test] +fn library_paths_sorted_alphabetically() { + let p = project("foo"); + + let mut dir1 = p.target_debug_dir(); + dir1.push("zzzzzzz"); + + let mut dir2 = p.target_debug_dir(); + dir2.push("BBBBBBB"); + + let mut dir3 = p.target_debug_dir(); + dir3.push("aaaaaaa"); + + let p = p + .file("Cargo.toml", r#" + [project] + name = "foo" + version = "0.0.1" + authors = [] + build = "build.rs" + "#) + .file("build.rs", &format!(r##" + fn main() {{ + println!(r#"cargo:rustc-link-search=native={}"#); + println!(r#"cargo:rustc-link-search=native={}"#); + println!(r#"cargo:rustc-link-search=native={}"#); + }} + "##, dir1.display(), dir2.display(), dir3.display())) + .file("src/main.rs", &format!(r##" + fn main() {{ + let search_path = std::env::var_os("{}").unwrap(); + let paths = std::env::split_paths(&search_path).collect::>(); + // ASCII case-sensitive sort + assert_eq!("BBBBBBB", paths[0].file_name().unwrap().to_string_lossy()); + assert_eq!("aaaaaaa", paths[1].file_name().unwrap().to_string_lossy()); + assert_eq!("zzzzzzz", paths[2].file_name().unwrap().to_string_lossy()); + }} + "##, dylib_path_envvar())) + .build(); + + assert_that(p.cargo("run"), execs().with_status(0)); +} + +#[test] fn fail_no_extra_verbose() { let p = project("foo") .file("Cargo.toml", r#" diff -Nru cargo-0.25.0/tests/rustflags.rs cargo-0.26.0/tests/rustflags.rs --- cargo-0.25.0/tests/rustflags.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/rustflags.rs 2018-02-26 21:17:55.000000000 +0000 @@ -974,21 +974,21 @@ [RUNNING] `rustc [..] --cfg bar[..]` [FINISHED] dev [unoptimized + debuginfo] target(s) in [..] ")); - + assert_that(p.cargo("build").arg("--bin=a").arg("-v"), execs().with_status(0).with_stderr("\ [COMPILING] foo v0.0.1 ([..]) [RUNNING] `rustc [..] --cfg bar[..]` [FINISHED] dev [unoptimized + debuginfo] target(s) in [..] ")); - + assert_that(p.cargo("build").arg("--example=b").arg("-v"), execs().with_status(0).with_stderr("\ [COMPILING] foo v0.0.1 ([..]) [RUNNING] `rustc [..] --cfg bar[..]` [FINISHED] dev [unoptimized + debuginfo] target(s) in [..] ")); - + assert_that(p.cargo("test").arg("--no-run").arg("-v"), execs().with_status(0).with_stderr("\ [COMPILING] foo v0.0.1 ([..]) @@ -997,7 +997,7 @@ [RUNNING] `rustc [..] --cfg bar[..]` [FINISHED] dev [unoptimized + debuginfo] target(s) in [..] ")); - + assert_that(p.cargo("bench").arg("--no-run").arg("-v"), execs().with_status(0).with_stderr("\ [COMPILING] foo v0.0.1 ([..]) @@ -1006,7 +1006,7 @@ [RUNNING] `rustc [..] --cfg bar[..]` [FINISHED] release [optimized] target(s) in [..] ")); - + } // target.'cfg(...)'.rustflags takes precedence over build.rustflags @@ -1069,7 +1069,7 @@ [RUNNING] `rustc [..] --cfg bar[..]` [FINISHED] release [optimized] target(s) in [..] ")); - + } #[test] @@ -1157,5 +1157,42 @@ [RUNNING] `rustc [..] --cfg foo[..]` [FINISHED] dev [unoptimized + debuginfo] target(s) in [..] ")); +} +#[test] +fn two_matching_in_config() { + let p1 = project("foo") + .file("Cargo.toml", r#" + [package] + name = "foo" + version = "0.0.1" + "#) + .file(".cargo/config", r#" + [target.'cfg(unix)'] + rustflags = ["--cfg", 'foo="a"'] + [target.'cfg(windows)'] + rustflags = ["--cfg", 'foo="a"'] + [target.'cfg(target_pointer_width = "32")'] + rustflags = ["--cfg", 'foo="b"'] + [target.'cfg(target_pointer_width = "64")'] + rustflags = ["--cfg", 'foo="b"'] + "#) + .file("src/main.rs", r#" + fn main() { + if cfg!(foo = "a") { + println!("a"); + } else if cfg!(foo = "b") { + println!("b"); + } else { + panic!() + } + } + "#) + .build(); + + assert_that(p1.cargo("run"), execs().with_status(0)); + assert_that(p1.cargo("build"), + execs().with_status(0).with_stderr("\ +[FINISHED] [..] +")); } diff -Nru cargo-0.25.0/tests/search.rs cargo-0.26.0/tests/search.rs --- cargo-0.25.0/tests/search.rs 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/tests/search.rs 2018-02-26 21:17:55.000000000 +0000 @@ -88,7 +88,7 @@ hoare = \"0.1.1\" # Design by contract style assertions for Rust")); } -// TODO: Depricated +// TODO: Deprecated // remove once it has been decided '--host' can be safely removed #[test] fn simple_with_host() { @@ -140,7 +140,7 @@ [WARNING] The flag '--host' is no longer valid. Previous versions of Cargo accepted this flag, but it is being -depricated. The flag is being renamed to 'index', as the flag +deprecated. The flag is being renamed to 'index', as the flag wants the location of the index in which to search. Please use '--index' instead. @@ -154,7 +154,7 @@ hoare = \"0.1.1\" # Design by contract style assertions for Rust")); } -// TODO: Depricated +// TODO: Deprecated // remove once it has been decided '--host' can be safely removed #[test] fn simple_with_index_and_host() { @@ -207,7 +207,7 @@ [WARNING] The flag '--host' is no longer valid. Previous versions of Cargo accepted this flag, but it is being -depricated. The flag is being renamed to 'index', as the flag +deprecated. The flag is being renamed to 'index', as the flag wants the location of the index in which to search. Please use '--index' instead. @@ -277,4 +277,9 @@ execs().with_status(0)); assert_that(cargo_process("help").arg("search"), execs().with_status(0)); + // Ensure that help output goes to stdout, not stderr. + assert_that(cargo_process("search").arg("--help"), + execs().with_stderr("")); + assert_that(cargo_process("search").arg("--help"), + execs().with_stdout_contains("[..] --frozen [..]")); } diff -Nru cargo-0.25.0/.travis.yml cargo-0.26.0/.travis.yml --- cargo-0.25.0/.travis.yml 2018-02-01 21:15:01.000000000 +0000 +++ cargo-0.26.0/.travis.yml 2018-02-26 21:17:55.000000000 +0000 @@ -34,14 +34,7 @@ script: - cargo test - cargo doc --no-deps - - sh src/ci/dox.sh - after_success: | - [ $TRAVIS_BRANCH = master ] && - [ $TRAVIS_PULL_REQUEST = false ] && - [ $(uname -s) = Linux ] && - pip install ghp-import --user && - $HOME/.local/bin/ghp-import -n target/doc && - git push -qf https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages 2>&1 >/dev/null + - (cd src/doc && mdbook build --no-create --dest-dir ../../target/doc) exclude: - rust: stable @@ -51,13 +44,10 @@ script: - cargo test -env: - global: - - secure: "hWheSLilMM4DXChfSy2XsDlLw338X2o+fw8bE590xxU2TzngFW8GUfq7lGfZEp/l4SNNIS6ROU/igyttCZtxZMANZ4aMQZR5E8Fp4yPOyE1pZLDH/LdQVXnROsfburQJeq+GIYIbZ01Abzh5ClpgLg5KX0H627uj063zZ7Ljo/w=" - notifications: email: on_success: never + addons: apt: packages: diff -Nru cargo-0.25.0/vendor/advapi32-sys-0.2.0/build.rs cargo-0.26.0/vendor/advapi32-sys-0.2.0/build.rs --- cargo-0.25.0/vendor/advapi32-sys-0.2.0/build.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/advapi32-sys-0.2.0/build.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -// Copyright © 2015, Peter Atashian -// Licensed under the MIT License -extern crate build; -fn main() { - build::link("advapi32", false) -} diff -Nru cargo-0.25.0/vendor/advapi32-sys-0.2.0/.cargo-checksum.json cargo-0.26.0/vendor/advapi32-sys-0.2.0/.cargo-checksum.json --- cargo-0.25.0/vendor/advapi32-sys-0.2.0/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/advapi32-sys-0.2.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"e06588080cb19d0acb6739808aafa5f26bfb2ca015b2b6370028b44cf7cb8a9a"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/advapi32-sys-0.2.0/Cargo.toml cargo-0.26.0/vendor/advapi32-sys-0.2.0/Cargo.toml --- cargo-0.25.0/vendor/advapi32-sys-0.2.0/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/advapi32-sys-0.2.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -[package] -name = "advapi32-sys" -version = "0.2.0" -authors = ["Peter Atashian "] -description = "Contains function definitions for the Windows API library advapi32. See winapi for types and constants." -documentation = "https://retep998.github.io/doc/advapi32/" -repository = "https://github.com/retep998/winapi-rs" -readme = "README.md" -keywords = ["windows", "ffi", "win32"] -license = "MIT" -build = "build.rs" -[lib] -name = "advapi32" -[dependencies] -winapi = { version = "0.2.5", path = "../.." } -[build-dependencies] -winapi-build = { version = "0.1.1", path = "../../build" } diff -Nru cargo-0.25.0/vendor/advapi32-sys-0.2.0/README.md cargo-0.26.0/vendor/advapi32-sys-0.2.0/README.md --- cargo-0.25.0/vendor/advapi32-sys-0.2.0/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/advapi32-sys-0.2.0/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -# advapi32 # -Contains function definitions for the Windows API library advapi32. See winapi for types and constants. - -```toml -[dependencies] -advapi32-sys = "0.1.2" -``` - -```rust -extern crate advapi32; -``` - -[Documentation](https://retep998.github.io/doc/advapi32/) diff -Nru cargo-0.25.0/vendor/advapi32-sys-0.2.0/src/lib.rs cargo-0.26.0/vendor/advapi32-sys-0.2.0/src/lib.rs --- cargo-0.25.0/vendor/advapi32-sys-0.2.0/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/advapi32-sys-0.2.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1005 +0,0 @@ -// Copyright © 2015, Peter Atashian -// Licensed under the MIT License -//! FFI bindings to advapi32. -#![cfg(windows)] -extern crate winapi; -use winapi::*; -extern "system" { - pub fn AbortSystemShutdownA(lpMachineName: LPCSTR) -> BOOL; - pub fn AbortSystemShutdownW(lpMachineName: LPWSTR) -> BOOL; - // pub fn AccessCheck(); - // pub fn AccessCheckAndAuditAlarmA(); - // pub fn AccessCheckAndAuditAlarmW(); - // pub fn AccessCheckByType(); - // pub fn AccessCheckByTypeAndAuditAlarmA(); - // pub fn AccessCheckByTypeAndAuditAlarmW(); - // pub fn AccessCheckByTypeResultList(); - // pub fn AccessCheckByTypeResultListAndAuditAlarmA(); - // pub fn AccessCheckByTypeResultListAndAuditAlarmByHandleA(); - // pub fn AccessCheckByTypeResultListAndAuditAlarmByHandleW(); - // pub fn AccessCheckByTypeResultListAndAuditAlarmW(); - // pub fn AddAccessAllowedAce(); - // pub fn AddAccessAllowedAceEx(); - // pub fn AddAccessAllowedObjectAce(); - // pub fn AddAccessDeniedAce(); - // pub fn AddAccessDeniedAceEx(); - // pub fn AddAccessDeniedObjectAce(); - // pub fn AddAce(); - // pub fn AddAuditAccessAce(); - // pub fn AddAuditAccessAceEx(); - // pub fn AddAuditAccessObjectAce(); - // pub fn AddConditionalAce(); - // pub fn AddMandatoryAce(); - // pub fn AddUsersToEncryptedFile(); - // pub fn AddUsersToEncryptedFileEx(); - // pub fn AdjustTokenGroups(); - pub fn AdjustTokenPrivileges( - TokenHandle: HANDLE, DisableAllPrivileges: BOOL, NewState: PTOKEN_PRIVILEGES, - BufferLength: DWORD, PreviousState: PTOKEN_PRIVILEGES, ReturnLength: PDWORD, - ) -> BOOL; - // pub fn AllocateAndInitializeSid(); - pub fn AllocateLocallyUniqueId(Luid: PLUID) -> BOOL; - pub fn AreAllAccessesGranted(GrantedAccess: DWORD, DesiredAccess: DWORD) -> BOOL; - pub fn AreAnyAccessesGranted(GrantedAccess: DWORD, DesiredAccess: DWORD) -> BOOL; - // pub fn AuditComputeEffectivePolicyBySid(); - // pub fn AuditComputeEffectivePolicyByToken(); - // pub fn AuditEnumerateCategories(); - // pub fn AuditEnumeratePerUserPolicy(); - // pub fn AuditEnumerateSubCategories(); - pub fn AuditFree(Buffer: PVOID); - // pub fn AuditLookupCategoryGuidFromCategoryId(); - // pub fn AuditLookupCategoryIdFromCategoryGuid(); - // pub fn AuditLookupCategoryNameA(); - // pub fn AuditLookupCategoryNameW(); - // pub fn AuditLookupSubCategoryNameA(); - // pub fn AuditLookupSubCategoryNameW(); - // pub fn AuditQueryGlobalSaclA(); - // pub fn AuditQueryGlobalSaclW(); - // pub fn AuditQueryPerUserPolicy(); - // pub fn AuditQuerySecurity(); - // pub fn AuditQuerySystemPolicy(); - // pub fn AuditSetGlobalSaclA(); - // pub fn AuditSetGlobalSaclW(); - // pub fn AuditSetPerUserPolicy(); - // pub fn AuditSetSecurity(); - // pub fn AuditSetSystemPolicy(); - // pub fn BackupEventLogA(); - // pub fn BackupEventLogW(); - // pub fn BaseRegCloseKey(); - // pub fn BaseRegCreateKey(); - // pub fn BaseRegDeleteKeyEx(); - // pub fn BaseRegDeleteValue(); - // pub fn BaseRegFlushKey(); - // pub fn BaseRegGetVersion(); - // pub fn BaseRegLoadKey(); - // pub fn BaseRegOpenKey(); - // pub fn BaseRegRestoreKey(); - // pub fn BaseRegSaveKeyEx(); - // pub fn BaseRegSetKeySecurity(); - // pub fn BaseRegSetValue(); - // pub fn BaseRegUnLoadKey(); - // pub fn BuildExplicitAccessWithNameA(); - // pub fn BuildExplicitAccessWithNameW(); - // pub fn BuildImpersonateExplicitAccessWithNameA(); - // pub fn BuildImpersonateExplicitAccessWithNameW(); - // pub fn BuildImpersonateTrusteeA(); - // pub fn BuildImpersonateTrusteeW(); - // pub fn BuildSecurityDescriptorA(); - // pub fn BuildSecurityDescriptorW(); - // pub fn BuildTrusteeWithNameA(); - // pub fn BuildTrusteeWithNameW(); - // pub fn BuildTrusteeWithObjectsAndNameA(); - // pub fn BuildTrusteeWithObjectsAndNameW(); - // pub fn BuildTrusteeWithObjectsAndSidA(); - // pub fn BuildTrusteeWithObjectsAndSidW(); - // pub fn BuildTrusteeWithSidA(); - // pub fn BuildTrusteeWithSidW(); - // pub fn CancelOverlappedAccess(); - // pub fn ChangeServiceConfig2A(); - // pub fn ChangeServiceConfig2W(); - // pub fn ChangeServiceConfigA(); - // pub fn ChangeServiceConfigW(); - // pub fn CheckForHiberboot(); - // pub fn CheckTokenMembership(); - // pub fn ClearEventLogA(); - // pub fn ClearEventLogW(); - // pub fn CloseCodeAuthzLevel(); - // pub fn CloseEncryptedFileRaw(); - // pub fn CloseEventLog(); - pub fn CloseServiceHandle(hSCObject: SC_HANDLE) -> BOOL; - // pub fn CloseThreadWaitChainSession(); - // pub fn CloseTrace(); - // pub fn CommandLineFromMsiDescriptor(); - // pub fn ComputeAccessTokenFromCodeAuthzLevel(); - pub fn ControlService( - hService: SC_HANDLE, dwControl: DWORD, lpServiceStatus: LPSERVICE_STATUS, - ) -> BOOL; - // pub fn ControlServiceExA(); - // pub fn ControlServiceExW(); - // pub fn ControlTraceA(); - // pub fn ControlTraceW(); - // pub fn ConvertAccessToSecurityDescriptorA(); - // pub fn ConvertAccessToSecurityDescriptorW(); - // pub fn ConvertSDToStringSDDomainW(); - // pub fn ConvertSDToStringSDRootDomainA(); - // pub fn ConvertSDToStringSDRootDomainW(); - // pub fn ConvertSecurityDescriptorToAccessA(); - // pub fn ConvertSecurityDescriptorToAccessNamedA(); - // pub fn ConvertSecurityDescriptorToAccessNamedW(); - // pub fn ConvertSecurityDescriptorToAccessW(); - // pub fn ConvertSecurityDescriptorToStringSecurityDescriptorA(); - // pub fn ConvertSecurityDescriptorToStringSecurityDescriptorW(); - // pub fn ConvertSidToStringSidA(); - // pub fn ConvertSidToStringSidW(); - // pub fn ConvertStringSDToSDDomainA(); - // pub fn ConvertStringSDToSDDomainW(); - // pub fn ConvertStringSDToSDRootDomainA(); - // pub fn ConvertStringSDToSDRootDomainW(); - // pub fn ConvertStringSecurityDescriptorToSecurityDescriptorA(); - // pub fn ConvertStringSecurityDescriptorToSecurityDescriptorW(); - // pub fn ConvertStringSidToSidA(); - // pub fn ConvertStringSidToSidW(); - // pub fn ConvertToAutoInheritPrivateObjectSecurity(); - // pub fn CopySid(); - // pub fn CreateCodeAuthzLevel(); - // pub fn CreatePrivateObjectSecurity(); - // pub fn CreatePrivateObjectSecurityEx(); - // pub fn CreatePrivateObjectSecurityWithMultipleInheritance(); - // pub fn CreateProcessAsUserA(); - // pub fn CreateProcessAsUserW(); - // pub fn CreateProcessWithLogonW(); - // pub fn CreateProcessWithTokenW(); - // pub fn CreateRestrictedToken(); - pub fn CreateServiceA( - hSCManager: SC_HANDLE, lpServiceName: LPCSTR, lpDisplayName: LPCSTR, - dwDesiredAccess: DWORD, dwServiceType: DWORD, dwStartType: DWORD, dwErrorControl: DWORD, - lpBinaryPathName: LPCSTR, lpLoadOrderGroup: LPCSTR, lpdwTagId: LPDWORD, - lpDependencies: LPCSTR, lpServiceStartName: LPCSTR, lpPassword: LPCSTR, - ) -> SC_HANDLE; - pub fn CreateServiceW( - hSCManager: SC_HANDLE, lpServiceName: LPCWSTR, lpDisplayName: LPCWSTR, - dwDesiredAccess: DWORD, dwServiceType: DWORD, dwStartType: DWORD, dwErrorControl: DWORD, - lpBinaryPathName: LPCWSTR, lpLoadOrderGroup: LPCWSTR, lpdwTagId: LPDWORD, - lpDependencies: LPCWSTR, lpServiceStartName: LPCWSTR, lpPassword: LPCWSTR, - ) -> SC_HANDLE; - // pub fn CreateTraceInstanceId(); - // pub fn CreateWellKnownSid(); - pub fn CredDeleteA(TargetName: LPCSTR, Type: DWORD, Flags: DWORD) -> BOOL; - pub fn CredDeleteW(TargetName: LPCWSTR, Type: DWORD, Flags: DWORD) -> BOOL; - // pub fn CredEnumerateA(); - // pub fn CredEnumerateW(); - // pub fn CredFindBestCredentialA(); - // pub fn CredFindBestCredentialW(); - pub fn CredFree(Buffer: PVOID); - // pub fn CredGetSessionTypes(); - // pub fn CredGetTargetInfoA(); - // pub fn CredGetTargetInfoW(); - // pub fn CredIsMarshaledCredentialA(); - // pub fn CredIsMarshaledCredentialW(); - // pub fn CredIsProtectedA(); - // pub fn CredIsProtectedW(); - // pub fn CredMarshalCredentialA(); - // pub fn CredMarshalCredentialW(); - // pub fn CredProtectA(); - // pub fn CredProtectW(); - pub fn CredReadA( - TargetName: LPCSTR, Type: DWORD, Flags: DWORD, Credential: *mut PCREDENTIALA, - ) -> BOOL; - // pub fn CredReadDomainCredentialsA(); - // pub fn CredReadDomainCredentialsW(); - pub fn CredReadW( - TargetName: LPCWSTR, Type: DWORD, Flags: DWORD, Credential: *mut PCREDENTIALW, - ) -> BOOL; - // pub fn CredRenameA(); - // pub fn CredRenameW(); - // pub fn CredUnmarshalCredentialA(); - // pub fn CredUnmarshalCredentialW(); - // pub fn CredUnprotectA(); - // pub fn CredUnprotectW(); - pub fn CredWriteA(Credential: PCREDENTIALA, Flags: DWORD) -> BOOL; - // pub fn CredWriteDomainCredentialsA(); - // pub fn CredWriteDomainCredentialsW(); - pub fn CredWriteW(Credential: PCREDENTIALW, Flags: DWORD) -> BOOL; - pub fn CryptAcquireContextA( - phProv: *mut HCRYPTPROV, szContainer: LPCSTR, szProvider: LPCSTR, dwProvType: DWORD, - dwFlags: DWORD, - ) -> BOOL; - pub fn CryptAcquireContextW( - phProv: *mut HCRYPTPROV, szContainer: LPCWSTR, szProvider: LPCWSTR, dwProvType: DWORD, - dwFlags: DWORD, - ) -> BOOL; - pub fn CryptContextAddRef(hProv: HCRYPTPROV, pdwReserved: *mut DWORD, dwFlags: DWORD) -> BOOL; - pub fn CryptCreateHash( - hProv: HCRYPTPROV, Algid: ALG_ID, hKey: HCRYPTKEY, dwFlags: DWORD, phHash: *mut HCRYPTHASH, - ) -> BOOL; - pub fn CryptDecrypt( - hKey: HCRYPTKEY, hHash: HCRYPTHASH, Final: BOOL, dwFlags: DWORD, pbData: *mut BYTE, - pdwDataLen: *mut DWORD, - ) -> BOOL; - pub fn CryptDeriveKey( - hProv: HCRYPTPROV, Algid: ALG_ID, hBaseData: HCRYPTHASH, dwFlags: DWORD, - phKey: *mut HCRYPTKEY, - ) -> BOOL; - pub fn CryptDestroyHash(hHash: HCRYPTHASH) -> BOOL; - pub fn CryptDestroyKey(hKey: HCRYPTKEY) -> BOOL; - pub fn CryptDuplicateHash( - hHash: HCRYPTHASH, pdwReserved: *mut DWORD, dwFlags: DWORD, phHash: *mut HCRYPTHASH, - ) -> BOOL; - pub fn CryptDuplicateKey( - hKey: HCRYPTKEY, pdwReserved: *mut DWORD, dwFlags: DWORD, phKey: *mut HCRYPTKEY, - ) -> BOOL; - pub fn CryptEncrypt( - hKey: HCRYPTKEY, hHash: HCRYPTHASH, Final: BOOL, dwFlags: DWORD, pbData: *mut BYTE, - pdwDataLen: *mut DWORD, dwBufLen: DWORD, - ) -> BOOL; - pub fn CryptEnumProviderTypesA( - dwIndex: DWORD, pdwReserved: *mut DWORD, dwFlags: DWORD, pdwProvType: *mut DWORD, - szTypeName: LPSTR, pcbTypeName: *mut DWORD, - ) -> BOOL; - pub fn CryptEnumProviderTypesW( - dwIndex: DWORD, pdwReserved: *mut DWORD, dwFlags: DWORD, pdwProvType: *mut DWORD, - szTypeName: LPWSTR, pcbTypeName: *mut DWORD, - ) -> BOOL; - pub fn CryptEnumProvidersA( - dwIndex: DWORD, pdwReserved: *mut DWORD, dwFlags: DWORD, pdwProvType: *mut DWORD, - szProvName: LPSTR, pcbProvName: *mut DWORD, - ) -> BOOL; - pub fn CryptEnumProvidersW( - dwIndex: DWORD, pdwReserved: *mut DWORD, dwFlags: DWORD, pdwProvType: *mut DWORD, - szProvName: LPWSTR, pcbProvName: *mut DWORD, - ) -> BOOL; - pub fn CryptExportKey( - hKey: HCRYPTKEY, hExpKey: HCRYPTKEY, dwBlobType: DWORD, dwFlags: DWORD, pbData: *mut BYTE, - pdwDataLen: *mut DWORD, - ) -> BOOL; - pub fn CryptGenKey( - hProv: HCRYPTPROV, Algid: ALG_ID, dwFlags: DWORD, phKey: *mut HCRYPTKEY, - ) -> BOOL; - pub fn CryptGenRandom(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: *mut BYTE) -> BOOL; - pub fn CryptGetDefaultProviderA( - dwProvType: DWORD, pdwReserved: *mut DWORD, dwFlags: DWORD, pszProvName: LPSTR, - pcbProvName: *mut DWORD, - ) -> BOOL; - pub fn CryptGetDefaultProviderW( - dwProvType: DWORD, pdwReserved: *mut DWORD, dwFlags: DWORD, pszProvName: LPWSTR, - pcbProvName: *mut DWORD, - ) -> BOOL; - pub fn CryptGetHashParam( - hHash: HCRYPTHASH, dwParam: DWORD, pbData: *mut BYTE, pdwDataLen: *mut DWORD, - dwFlags: DWORD, - ) -> BOOL; - pub fn CryptGetKeyParam( - hKey: HCRYPTKEY, dwParam: DWORD, pbData: *mut BYTE, pdwDataLen: *mut DWORD, dwFlags: DWORD, - ) -> BOOL; - pub fn CryptGetProvParam( - hProv: HCRYPTPROV, dwParam: DWORD, pbData: *mut BYTE, pdwDataLen: *mut DWORD, - dwFlags: DWORD, - ) -> BOOL; - pub fn CryptGetUserKey(hProv: HCRYPTPROV, dwKeySpec: DWORD, phUserKey: *mut HCRYPTKEY) -> BOOL; - pub fn CryptHashData( - hHash: HCRYPTHASH, pbData: *const BYTE, dwDataLen: DWORD, dwFlags: DWORD, - ) -> BOOL; - pub fn CryptHashSessionKey(hHash: HCRYPTHASH, hKey: HCRYPTKEY, dwFlags: DWORD) -> BOOL; - pub fn CryptImportKey( - hProv: HCRYPTPROV, pbData: *const BYTE, dwDataLen: DWORD, hPubKey: HCRYPTKEY, - dwFlags: DWORD, phKey: *mut HCRYPTKEY, - ) -> BOOL; - pub fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL; - pub fn CryptSetHashParam( - hHash: HCRYPTHASH, dwParam: DWORD, pbData: *const BYTE, dwFlags: DWORD, - ) -> BOOL; - pub fn CryptSetKeyParam( - hKey: HCRYPTKEY, dwParam: DWORD, pbData: *const BYTE, dwFlags: DWORD, - ) -> BOOL; - pub fn CryptSetProvParam( - hProv: HCRYPTPROV, dwParam: DWORD, pbData: *const BYTE, dwFlags: DWORD, - ) -> BOOL; - pub fn CryptSetProviderA(pszProvName: LPCSTR, dwProvType: DWORD) -> BOOL; - pub fn CryptSetProviderExA( - pszProvName: LPCSTR, dwProvType: DWORD, pdwReserved: *mut DWORD, dwFlags: DWORD, - ) -> BOOL; - pub fn CryptSetProviderExW( - pszProvName: LPCWSTR, dwProvType: DWORD, pdwReserved: *mut DWORD, dwFlags: DWORD, - ) -> BOOL; - pub fn CryptSetProviderW(pszProvName: LPCWSTR, dwProvType: DWORD) -> BOOL; - pub fn CryptSignHashA( - hHash: HCRYPTHASH, dwKeySpec: DWORD, szDescription: LPCSTR, dwFlags: DWORD, - pbSignature: *mut BYTE, pdwSigLen: *mut DWORD, - ) -> BOOL; - pub fn CryptSignHashW( - hHash: HCRYPTHASH, dwKeySpec: DWORD, szDescription: LPCWSTR, dwFlags: DWORD, - pbSignature: *mut BYTE, pdwSigLen: *mut DWORD, - ) -> BOOL; - pub fn CryptVerifySignatureA( - hHash: HCRYPTHASH, pbSignature: *const BYTE, dwSigLen: DWORD, hPubKey: HCRYPTKEY, - szDescription: LPCSTR, dwFlags: DWORD, - ) -> BOOL; - pub fn CryptVerifySignatureW( - hHash: HCRYPTHASH, pbSignature: *const BYTE, dwSigLen: DWORD, hPubKey: HCRYPTKEY, - szDescription: LPCWSTR, dwFlags: DWORD, - ) -> BOOL; - // pub fn DecryptFileA(); - // pub fn DecryptFileW(); - // pub fn DeleteAce(); - pub fn DeleteService(hService: SC_HANDLE) -> BOOL; - // pub fn DeregisterEventSource(); - // pub fn DestroyPrivateObjectSecurity(); - // pub fn DuplicateEncryptionInfoFile(); - // pub fn DuplicateToken(); - // pub fn DuplicateTokenEx(); - // pub fn ElfBackupEventLogFileA(); - // pub fn ElfBackupEventLogFileW(); - // pub fn ElfChangeNotify(); - // pub fn ElfClearEventLogFileA(); - // pub fn ElfClearEventLogFileW(); - // pub fn ElfCloseEventLog(); - // pub fn ElfDeregisterEventSource(); - // pub fn ElfFlushEventLog(); - // pub fn ElfNumberOfRecords(); - // pub fn ElfOldestRecord(); - // pub fn ElfOpenBackupEventLogA(); - // pub fn ElfOpenBackupEventLogW(); - // pub fn ElfOpenEventLogA(); - // pub fn ElfOpenEventLogW(); - // pub fn ElfReadEventLogA(); - // pub fn ElfReadEventLogW(); - // pub fn ElfRegisterEventSourceA(); - // pub fn ElfRegisterEventSourceW(); - // pub fn ElfReportEventA(); - // pub fn ElfReportEventAndSourceW(); - // pub fn ElfReportEventW(); - // pub fn EnableTrace(); - // pub fn EnableTraceEx(); - // pub fn EnableTraceEx2(); - // pub fn EncryptFileA(); - // pub fn EncryptFileW(); - // pub fn EncryptedFileKeyInfo(); - // pub fn EncryptionDisable(); - // pub fn EnumDependentServicesA(); - // pub fn EnumDependentServicesW(); - // pub fn EnumDynamicTimeZoneInformation(); - // pub fn EnumServiceGroupW(); - // pub fn EnumServicesStatusA(); - // pub fn EnumServicesStatusExA(); - // pub fn EnumServicesStatusExW(); - // pub fn EnumServicesStatusW(); - // pub fn EnumerateTraceGuids(); - // pub fn EnumerateTraceGuidsEx(); - // pub fn EqualDomainSid(); - // pub fn EqualPrefixSid(); - // pub fn EqualSid(); - // pub fn EtwLogSysConfigExtension(); - // pub fn EventAccessControl(); - // pub fn EventAccessQuery(); - // pub fn EventAccessRemove(); - // pub fn EventActivityIdControl(); - // pub fn EventEnabled(); - // pub fn EventProviderEnabled(); - // pub fn EventRegister(); - // pub fn EventSetInformation(); - // pub fn EventUnregister(); - // pub fn EventWrite(); - // pub fn EventWriteEndScenario(); - // pub fn EventWriteEx(); - // pub fn EventWriteStartScenario(); - // pub fn EventWriteString(); - // pub fn EventWriteTransfer(); - // pub fn FileEncryptionStatusA(); - // pub fn FileEncryptionStatusW(); - // pub fn FindFirstFreeAce(); - // pub fn FlushEfsCache(); - // pub fn FlushTraceA(); - // pub fn FlushTraceW(); - // pub fn FreeEncryptedFileKeyInfo(); - // pub fn FreeEncryptedFileMetadata(); - // pub fn FreeEncryptionCertificateHashList(); - // pub fn FreeInheritedFromArray(); - // pub fn FreeSid(); - // pub fn GetAccessPermissionsForObjectA(); - // pub fn GetAccessPermissionsForObjectW(); - // pub fn GetAce(); - // pub fn GetAclInformation(); - // pub fn GetAuditedPermissionsFromAclA(); - // pub fn GetAuditedPermissionsFromAclW(); - pub fn GetCurrentHwProfileA(lpHwProfileInfo: LPHW_PROFILE_INFOA) -> BOOL; - pub fn GetCurrentHwProfileW(lpHwProfileInfo: LPHW_PROFILE_INFOW) -> BOOL; - // pub fn GetDynamicTimeZoneInformationEffectiveYears(); - // pub fn GetEffectiveRightsFromAclA(); - // pub fn GetEffectiveRightsFromAclW(); - // pub fn GetEncryptedFileMetadata(); - // pub fn GetEventLogInformation(); - // pub fn GetExplicitEntriesFromAclA(); - // pub fn GetExplicitEntriesFromAclW(); - // pub fn GetFileSecurityA(); - // pub fn GetFileSecurityW(); - // pub fn GetInformationCodeAuthzLevelW(); - // pub fn GetInformationCodeAuthzPolicyW(); - // pub fn GetInheritanceSourceA(); - // pub fn GetInheritanceSourceW(); - // pub fn GetKernelObjectSecurity(); - // pub fn GetLengthSid(); - // pub fn GetLocalManagedApplicationData(); - // pub fn GetLocalManagedApplications(); - // pub fn GetManagedApplicationCategories(); - // pub fn GetManagedApplications(); - // pub fn GetMultipleTrusteeA(); - // pub fn GetMultipleTrusteeOperationA(); - // pub fn GetMultipleTrusteeOperationW(); - // pub fn GetMultipleTrusteeW(); - // pub fn GetNamedSecurityInfoA(); - // pub fn GetNamedSecurityInfoExA(); - // pub fn GetNamedSecurityInfoExW(); - // pub fn GetNamedSecurityInfoW(); - // pub fn GetNumberOfEventLogRecords(); - // pub fn GetOldestEventLogRecord(); - // pub fn GetOverlappedAccessResults(); - // pub fn GetPrivateObjectSecurity(); - // pub fn GetSecurityDescriptorControl(); - // pub fn GetSecurityDescriptorDacl(); - // pub fn GetSecurityDescriptorGroup(); - // pub fn GetSecurityDescriptorLength(); - // pub fn GetSecurityDescriptorOwner(); - // pub fn GetSecurityDescriptorRMControl(); - // pub fn GetSecurityDescriptorSacl(); - // pub fn GetSecurityInfo(); - // pub fn GetSecurityInfoExA(); - // pub fn GetSecurityInfoExW(); - // pub fn GetServiceDisplayNameA(); - // pub fn GetServiceDisplayNameW(); - // pub fn GetServiceKeyNameA(); - // pub fn GetServiceKeyNameW(); - // pub fn GetSidIdentifierAuthority(); - // pub fn GetSidLengthRequired(); - // pub fn GetSidSubAuthority(); - // pub fn GetSidSubAuthorityCount(); - // pub fn GetStringConditionFromBinary(); - // pub fn GetThreadWaitChain(); - // pub fn GetTokenInformation(); - // pub fn GetTraceEnableFlags(); - // pub fn GetTraceEnableLevel(); - // pub fn GetTraceLoggerHandle(); - // pub fn GetTrusteeFormA(); - // pub fn GetTrusteeFormW(); - // pub fn GetTrusteeNameA(); - // pub fn GetTrusteeNameW(); - // pub fn GetTrusteeTypeA(); - // pub fn GetTrusteeTypeW(); - pub fn GetUserNameA(lpBuffer: LPSTR, pcbBuffer: LPDWORD) -> BOOL; - pub fn GetUserNameW(lpBuffer: LPWSTR, pcbBuffer: LPDWORD) -> BOOL; - // pub fn GetWindowsAccountDomainSid(); - // pub fn I_ScSetServiceBitsA(); - // pub fn I_ScSetServiceBitsW(); - // pub fn IdentifyCodeAuthzLevelW(); - // pub fn ImpersonateAnonymousToken(); - // pub fn ImpersonateLoggedOnUser(); - // pub fn ImpersonateNamedPipeClient(); - // pub fn ImpersonateSelf(); - // pub fn InitializeAcl(); - // pub fn InitializeSecurityDescriptor(); - // pub fn InitializeSid(); - // pub fn InitiateShutdownA(); - // pub fn InitiateShutdownW(); - // pub fn InitiateSystemShutdownA(); - // pub fn InitiateSystemShutdownExA(); - // pub fn InitiateSystemShutdownExW(); - // pub fn InitiateSystemShutdownW(); - // pub fn InstallApplication(); - // pub fn IsTextUnicode(); - // pub fn IsTokenRestricted(); - // pub fn IsTokenUntrusted(); - // pub fn IsValidAcl(); - // pub fn IsValidRelativeSecurityDescriptor(); - // pub fn IsValidSecurityDescriptor(); - // pub fn IsValidSid(); - // pub fn IsWellKnownSid(); - // pub fn LockServiceDatabase(); - // pub fn LogonUserA(); - // pub fn LogonUserExA(); - // pub fn LogonUserExExW(); - // pub fn LogonUserExW(); - // pub fn LogonUserW(); - // pub fn LookupAccountNameA(); - // pub fn LookupAccountNameW(); - // pub fn LookupAccountSidA(); - // pub fn LookupAccountSidW(); - // pub fn LookupPrivilegeDisplayNameA(); - // pub fn LookupPrivilegeDisplayNameW(); - pub fn LookupPrivilegeNameA( - lpSystemName: LPCSTR, lpLuid: PLUID, lpName: LPSTR, cchName: LPDWORD, - ) -> BOOL; - pub fn LookupPrivilegeNameW( - lpSystemName: LPCWSTR, lpLuid: PLUID, lpName: LPWSTR, cchName: LPDWORD, - ) -> BOOL; - pub fn LookupPrivilegeValueA( - lpSystemName: LPCSTR, lpName: LPCSTR, lpLuid: PLUID, - ) -> BOOL; - pub fn LookupPrivilegeValueW( - lpSystemName: LPCWSTR, lpName: LPCWSTR, lpLuid: PLUID, - ) -> BOOL; - // pub fn LookupSecurityDescriptorPartsA(); - // pub fn LookupSecurityDescriptorPartsW(); - // pub fn LsaAddAccountRights(); - // pub fn LsaAddPrivilegesToAccount(); - // pub fn LsaClearAuditLog(); - // pub fn LsaClose(); - // pub fn LsaCreateAccount(); - // pub fn LsaCreateSecret(); - // pub fn LsaCreateTrustedDomain(); - // pub fn LsaCreateTrustedDomainEx(); - // pub fn LsaDelete(); - // pub fn LsaDeleteTrustedDomain(); - // pub fn LsaEnumerateAccountRights(); - // pub fn LsaEnumerateAccounts(); - // pub fn LsaEnumerateAccountsWithUserRight(); - // pub fn LsaEnumeratePrivileges(); - // pub fn LsaEnumeratePrivilegesOfAccount(); - // pub fn LsaEnumerateTrustedDomains(); - // pub fn LsaEnumerateTrustedDomainsEx(); - // pub fn LsaFreeMemory(); - // pub fn LsaGetAppliedCAPIDs(); - // pub fn LsaGetQuotasForAccount(); - // pub fn LsaGetRemoteUserName(); - // pub fn LsaGetSystemAccessAccount(); - // pub fn LsaGetUserName(); - // pub fn LsaICLookupNames(); - // pub fn LsaICLookupNamesWithCreds(); - // pub fn LsaICLookupSids(); - // pub fn LsaICLookupSidsWithCreds(); - // pub fn LsaLookupNames(); - // pub fn LsaLookupNames2(); - // pub fn LsaLookupPrivilegeDisplayName(); - // pub fn LsaLookupPrivilegeName(); - // pub fn LsaLookupPrivilegeValue(); - // pub fn LsaLookupSids(); - // pub fn LsaLookupSids2(); - // pub fn LsaManageSidNameMapping(); - // pub fn LsaNtStatusToWinError(); - // pub fn LsaOpenAccount(); - // pub fn LsaOpenPolicy(); - // pub fn LsaOpenPolicySce(); - // pub fn LsaOpenSecret(); - // pub fn LsaOpenTrustedDomain(); - // pub fn LsaOpenTrustedDomainByName(); - // pub fn LsaQueryCAPs(); - // pub fn LsaQueryDomainInformationPolicy(); - // pub fn LsaQueryForestTrustInformation(); - // pub fn LsaQueryInfoTrustedDomain(); - // pub fn LsaQueryInformationPolicy(); - // pub fn LsaQuerySecret(); - // pub fn LsaQuerySecurityObject(); - // pub fn LsaQueryTrustedDomainInfo(); - // pub fn LsaQueryTrustedDomainInfoByName(); - // pub fn LsaRemoveAccountRights(); - // pub fn LsaRemovePrivilegesFromAccount(); - // pub fn LsaRetrievePrivateData(); - // pub fn LsaSetCAPs(); - // pub fn LsaSetDomainInformationPolicy(); - // pub fn LsaSetForestTrustInformation(); - // pub fn LsaSetInformationPolicy(); - // pub fn LsaSetInformationTrustedDomain(); - // pub fn LsaSetQuotasForAccount(); - // pub fn LsaSetSecret(); - // pub fn LsaSetSecurityObject(); - // pub fn LsaSetSystemAccessAccount(); - // pub fn LsaSetTrustedDomainInfoByName(); - // pub fn LsaSetTrustedDomainInformation(); - // pub fn LsaStorePrivateData(); - // pub fn MIDL_user_free_Ext(); - // pub fn MSChapSrvChangePassword(); - // pub fn MSChapSrvChangePassword2(); - // pub fn MakeAbsoluteSD(); - // pub fn MakeAbsoluteSD2(); - // pub fn MakeSelfRelativeSD(); - // pub fn MapGenericMask(); - // pub fn NotifyBootConfigStatus(); - // pub fn NotifyChangeEventLog(); - // pub fn NotifyServiceStatusChange(); - // pub fn NotifyServiceStatusChangeA(); - // pub fn NotifyServiceStatusChangeW(); - // pub fn ObjectCloseAuditAlarmA(); - // pub fn ObjectCloseAuditAlarmW(); - // pub fn ObjectDeleteAuditAlarmA(); - // pub fn ObjectDeleteAuditAlarmW(); - // pub fn ObjectOpenAuditAlarmA(); - // pub fn ObjectOpenAuditAlarmW(); - // pub fn ObjectPrivilegeAuditAlarmA(); - // pub fn ObjectPrivilegeAuditAlarmW(); - // pub fn OpenBackupEventLogA(); - // pub fn OpenBackupEventLogW(); - // pub fn OpenEncryptedFileRawA(); - // pub fn OpenEncryptedFileRawW(); - // pub fn OpenEventLogA(); - // pub fn OpenEventLogW(); - pub fn OpenProcessToken( - ProcessHandle: HANDLE, DesiredAccess: DWORD, TokenHandle: PHANDLE, - ) -> BOOL; - pub fn OpenSCManagerA( - lpMachineName: LPCSTR, lpDatabaseName: LPCSTR, dwDesiredAccess: DWORD, - ) -> SC_HANDLE; - pub fn OpenSCManagerW( - lpMachineName: LPCWSTR, lpDatabaseName: LPCWSTR, dwDesiredAccess: DWORD, - ) -> SC_HANDLE; - pub fn OpenServiceA( - hSCManager: SC_HANDLE, lpServiceName: LPCSTR, dwDesiredAccess: DWORD, - ) -> SC_HANDLE; - pub fn OpenServiceW( - hSCManager: SC_HANDLE, lpServiceName: LPCWSTR, dwDesiredAccess: DWORD, - ) -> SC_HANDLE; - // pub fn OpenThreadToken(); - // pub fn OpenThreadWaitChainSession(); - // pub fn OpenTraceA(); - // pub fn OpenTraceW(); - // pub fn OperationEnd(); - // pub fn OperationStart(); - // pub fn PerfAddCounters(); - // pub fn PerfCloseQueryHandle(); - // pub fn PerfCreateInstance(); - // pub fn PerfDecrementULongCounterValue(); - // pub fn PerfDecrementULongLongCounterValue(); - // pub fn PerfDeleteCounters(); - // pub fn PerfDeleteInstance(); - // pub fn PerfEnumerateCounterSet(); - // pub fn PerfEnumerateCounterSetInstances(); - // pub fn PerfIncrementULongCounterValue(); - // pub fn PerfIncrementULongLongCounterValue(); - // pub fn PerfOpenQueryHandle(); - // pub fn PerfQueryCounterData(); - // pub fn PerfQueryCounterInfo(); - // pub fn PerfQueryCounterSetRegistrationInfo(); - // pub fn PerfQueryInstance(); - // pub fn PerfRegCloseKey(); - // pub fn PerfRegEnumKey(); - // pub fn PerfRegEnumValue(); - // pub fn PerfRegQueryInfoKey(); - // pub fn PerfRegQueryValue(); - // pub fn PerfRegSetValue(); - // pub fn PerfSetCounterRefValue(); - // pub fn PerfSetCounterSetInfo(); - // pub fn PerfSetULongCounterValue(); - // pub fn PerfSetULongLongCounterValue(); - // pub fn PerfStartProvider(); - // pub fn PerfStartProviderEx(); - // pub fn PerfStopProvider(); - // pub fn PrivilegeCheck(); - // pub fn PrivilegedServiceAuditAlarmA(); - // pub fn PrivilegedServiceAuditAlarmW(); - // pub fn ProcessTrace(); - // pub fn QueryAllTracesA(); - // pub fn QueryAllTracesW(); - // pub fn QueryRecoveryAgentsOnEncryptedFile(); - // pub fn QuerySecurityAccessMask(); - // pub fn QueryServiceConfig2A(); - // pub fn QueryServiceConfig2W(); - // pub fn QueryServiceConfigA(); - // pub fn QueryServiceConfigW(); - // pub fn QueryServiceDynamicInformation(); - // pub fn QueryServiceLockStatusA(); - // pub fn QueryServiceLockStatusW(); - // pub fn QueryServiceObjectSecurity(); - pub fn QueryServiceStatus(hService: SC_HANDLE, lpServiceStatus: LPSERVICE_STATUS) -> BOOL; - pub fn QueryServiceStatusEx( - hService: SC_HANDLE, InfoLevel: SC_STATUS_TYPE, lpBuffer: LPBYTE, cbBufSize: DWORD, - pcbBytesNeeded: LPDWORD, - ) -> BOOL; - // pub fn QueryTraceA(); - // pub fn QueryTraceW(); - // pub fn QueryUsersOnEncryptedFile(); - // pub fn ReadEncryptedFileRaw(); - // pub fn ReadEventLogA(); - // pub fn ReadEventLogW(); - pub fn RegCloseKey(hKey: HKEY) -> LONG; - pub fn RegConnectRegistryA(lpMachineName: LPCSTR, hKey: HKEY, phkResult: PHKEY) -> LONG; - // pub fn RegConnectRegistryExA(); - // pub fn RegConnectRegistryExW(); - pub fn RegConnectRegistryW(lpMachineName: LPCWSTR, hKey: HKEY, phkResult: PHKEY) -> LONG; - pub fn RegCopyTreeA(hKeySrc: HKEY, lpSubKey: LPCSTR, hKeyDest: HKEY) -> LONG; - pub fn RegCopyTreeW(hKeySrc: HKEY, lpSubKey: LPCWSTR, hKeyDest: HKEY) -> LONG; - // pub fn RegCreateKeyA(); - pub fn RegCreateKeyExA( - hKey: HKEY, lpSubKey: LPCSTR, Reserved: DWORD, lpClass: LPSTR, dwOptions: DWORD, - samDesired: REGSAM, lpSecurityAttributes: LPSECURITY_ATTRIBUTES, phkResult: PHKEY, - lpdwDisposition: LPDWORD, - ) -> LONG; - pub fn RegCreateKeyExW( - hKey: HKEY, lpSubKey: LPCWSTR, Reserved: DWORD, lpClass: LPWSTR, dwOptions: DWORD, - samDesired: REGSAM, lpSecurityAttributes: LPSECURITY_ATTRIBUTES, phkResult: PHKEY, - lpdwDisposition: LPDWORD, - ) -> LONG; - pub fn RegCreateKeyTransactedA( - hKey: HKEY, lpSubKey: LPCSTR, Reserved: DWORD, lpClass: LPSTR, dwOptions: DWORD, - samDesired: REGSAM, lpSecurityAttributes: LPSECURITY_ATTRIBUTES, phkResult: PHKEY, - lpdwDisposition: LPDWORD, hTransaction: HANDLE, pExtendedParemeter: PVOID, - ) -> LONG; - pub fn RegCreateKeyTransactedW( - hKey: HKEY, lpSubKey: LPCWSTR, Reserved: DWORD, lpClass: LPWSTR, dwOptions: DWORD, - samDesired: REGSAM, lpSecurityAttributes: LPSECURITY_ATTRIBUTES, phkResult: PHKEY, - lpdwDisposition: LPDWORD, hTransaction: HANDLE, pExtendedParemeter: PVOID, - ) -> LONG; - // pub fn RegCreateKeyW(); - pub fn RegDeleteKeyA(hKey: HKEY, lpSubKey: LPCSTR) -> LONG; - pub fn RegDeleteKeyExA( - hKey: HKEY, lpSubKey: LPCSTR, samDesired: REGSAM, Reserved: DWORD, - ) -> LONG; - pub fn RegDeleteKeyExW( - hKey: HKEY, lpSubKey: LPCWSTR, samDesired: REGSAM, Reserved: DWORD, - ) -> LONG; - pub fn RegDeleteKeyTransactedA( - hKey: HKEY, lpSubKey: LPCSTR, samDesired: REGSAM, Reserved: DWORD, - hTransaction: HANDLE, pExtendedParemeter: PVOID, - ) -> LONG; - pub fn RegDeleteKeyTransactedW( - hKey: HKEY, lpSubKey: LPCWSTR, samDesired: REGSAM, Reserved: DWORD, - hTransaction: HANDLE, pExtendedParemeter: PVOID, - ) -> LONG; - pub fn RegDeleteKeyValueA(hKey: HKEY, lpSubKey: LPCSTR, lpValueName: LPCSTR) -> LONG; - pub fn RegDeleteKeyValueW(hKey: HKEY, lpSubKey: LPCWSTR, lpValueName: LPCWSTR) -> LONG; - pub fn RegDeleteKeyW(hKey: HKEY, lpSubKey: LPCWSTR) -> LONG; - pub fn RegDeleteTreeA(hKey: HKEY, lpSubKey: LPCSTR) -> LONG; - pub fn RegDeleteTreeW(hKey: HKEY, lpSubKey: LPCWSTR) -> LONG; - pub fn RegDeleteValueA(hKey: HKEY, lpValueName: LPCSTR) -> LONG; - pub fn RegDeleteValueW(hKey: HKEY, lpValueName: LPCWSTR) -> LONG; - pub fn RegDisablePredefinedCache() -> LONG; - pub fn RegDisablePredefinedCacheEx() -> LONG; - pub fn RegDisableReflectionKey(hBase: HKEY) -> LONG; - pub fn RegEnableReflectionKey(hBase: HKEY) -> LONG; - // pub fn RegEnumKeyA(); - pub fn RegEnumKeyExA( - hKey: HKEY, dwIndex: DWORD, lpName: LPSTR, lpcName: LPDWORD, lpReserved: LPDWORD, - lpClass: LPSTR, lpcClass: LPDWORD, lpftLastWriteTime: PFILETIME, - ) -> LONG; - pub fn RegEnumKeyExW( - hKey: HKEY, dwIndex: DWORD, lpName: LPWSTR, lpcName: LPDWORD, lpReserved: LPDWORD, - lpClass: LPWSTR, lpcClass: LPDWORD, lpftLastWriteTime: PFILETIME, - ) -> LONG; - // pub fn RegEnumKeyW(); - pub fn RegEnumValueA( - hKey: HKEY, dwIndex: DWORD, lpValueName: LPSTR, lpcchValueName: LPDWORD, - lpReserved: LPDWORD, lpType: LPDWORD, lpData: LPBYTE, lpcbData: LPDWORD, - ) -> LONG; - pub fn RegEnumValueW( - hKey: HKEY, dwIndex: DWORD, lpValueName: LPWSTR, lpcchValueName: LPDWORD, - lpReserved: LPDWORD, lpType: LPDWORD, lpData: LPBYTE, lpcbData: LPDWORD, - ) -> LONG; - pub fn RegFlushKey(hKey: HKEY) -> LONG; - // pub fn RegGetKeySecurity(); - pub fn RegGetValueA( - hkey: HKEY, lpSubKey: LPCSTR, lpValue: LPCSTR, dwFlags: DWORD, pdwType: LPDWORD, - pvData: PVOID, pcbData: LPDWORD, - ) -> LONG; - pub fn RegGetValueW( - hkey: HKEY, lpSubKey: LPCWSTR, lpValue: LPCWSTR, dwFlags: DWORD, pdwType: LPDWORD, - pvData: PVOID, pcbData: LPDWORD, - ) -> LONG; - // pub fn RegLoadAppKeyA(); - // pub fn RegLoadAppKeyW(); - // pub fn RegLoadKeyA(); - // pub fn RegLoadKeyW(); - // pub fn RegLoadMUIStringA(); - pub fn RegLoadMUIStringW( - hKey: HKEY, pszValue: LPCWSTR, pszOutBuf: LPWSTR, cbOutBuf: DWORD, pcbData: LPDWORD, - Flags: DWORD, pszDirectory: LPCWSTR, - ) -> LONG; - pub fn RegNotifyChangeKeyValue( - hKey: HKEY, bWatchSubtree: BOOL, dwNotifyFilter: DWORD, hEvent: HANDLE, - fAsynchronous: BOOL, - ) -> LONG; - pub fn RegOpenCurrentUser(samDesired: REGSAM, phkResult: PHKEY) -> LONG; - // pub fn RegOpenKeyA(); - pub fn RegOpenKeyExA( - hKey: HKEY, lpSubKey: LPCSTR, ulOptions: DWORD, samDesired: REGSAM, phkResult: PHKEY, - ) -> LONG; - pub fn RegOpenKeyExW( - hKey: HKEY, lpSubKey: LPCWSTR, ulOptions: DWORD, samDesired: REGSAM, phkResult: PHKEY, - ) -> LONG; - pub fn RegOpenKeyTransactedA( - hKey: HKEY, lpSubKey: LPCSTR, ulOptions: DWORD, samDesired: REGSAM, phkResult: PHKEY, - hTransaction: HANDLE, pExtendedParemeter: PVOID, - ) -> LONG; - pub fn RegOpenKeyTransactedW( - hKey: HKEY, lpSubKey: LPCWSTR, ulOptions: DWORD, samDesired: REGSAM, phkResult: PHKEY, - hTransaction: HANDLE, pExtendedParemeter: PVOID, - ) -> LONG; - // pub fn RegOpenKeyW(); - pub fn RegOpenUserClassesRoot( - hToken: HANDLE, dwOptions: DWORD, samDesired: REGSAM, phkResult: PHKEY, - ) -> LONG; - pub fn RegOverridePredefKey(hKey: HKEY, hNewHKey: HKEY) -> LONG; - pub fn RegQueryInfoKeyA( - hKey: HKEY, lpClass: LPSTR, lpcClass: LPDWORD, lpReserved: LPDWORD, lpcSubKeys: LPDWORD, - lpcMaxSubKeyLen: LPDWORD, lpcMaxClassLen: LPDWORD, lpcValues: LPDWORD, - lpcMaxValueNameLen: LPDWORD, lpcMaxValueLen: LPDWORD, lpcbSecurityDescriptor: LPDWORD, - lpftLastWriteTime: PFILETIME, - ) -> LONG; - pub fn RegQueryInfoKeyW( - hKey: HKEY, lpClass: LPWSTR, lpcClass: LPDWORD, lpReserved: LPDWORD, lpcSubKeys: LPDWORD, - lpcMaxSubKeyLen: LPDWORD, lpcMaxClassLen: LPDWORD, lpcValues: LPDWORD, - lpcMaxValueNameLen: LPDWORD, lpcMaxValueLen: LPDWORD, lpcbSecurityDescriptor: LPDWORD, - lpftLastWriteTime: PFILETIME, - ) -> LONG; - pub fn RegQueryMultipleValuesA( - hKey: HKEY, val_list: PVALENTA, num_vals: DWORD, lpValueBuf: LPSTR, ldwTotsize: LPDWORD, - ) -> LONG; - pub fn RegQueryMultipleValuesW( - hKey: HKEY, val_list: PVALENTW, num_vals: DWORD, lpValueBuf: LPWSTR, ldwTotsize: LPDWORD, - ) -> LONG; - pub fn RegQueryReflectionKey(hBase: HKEY, bIsReflectionDisabled: PBOOL) -> LONG; - pub fn RegQueryValueExA( - hKey: HKEY, lpValueName: LPCSTR, lpReserved: LPDWORD, lpType: LPDWORD, lpData: LPBYTE, - lpcbData: LPDWORD, - ) -> LONG; - pub fn RegQueryValueExW( - hKey: HKEY, lpValueName: LPCWSTR, lpReserved: LPDWORD, lpType: LPDWORD, lpData: LPBYTE, - lpcbData: LPDWORD, - ) -> LONG; - // pub fn RegQueryValueW(); - // pub fn RegRenameKey(); - // pub fn RegReplaceKeyA(); - // pub fn RegReplaceKeyW(); - // pub fn RegRestoreKeyA(); - // pub fn RegRestoreKeyW(); - // pub fn RegSaveKeyA(); - // pub fn RegSaveKeyExA(); - // pub fn RegSaveKeyExW(); - // pub fn RegSaveKeyW(); - // pub fn RegSetKeySecurity(); - pub fn RegSetKeyValueA( - hKey: HKEY, lpSubKey: LPCSTR, lpValueName: LPCSTR, dwType: DWORD, lpData: LPCVOID, - cbData: DWORD, - ) -> LONG; - pub fn RegSetValueExA( - hKey: HKEY, lpValueName: LPCSTR, Reserved: DWORD, dwType: DWORD, lpData: *const BYTE, - cbData: DWORD, - ) -> LONG; - pub fn RegSetValueExW( - hKey: HKEY, lpValueName: LPCWSTR, Reserved: DWORD, dwType: DWORD, lpData: *const BYTE, - cbData: DWORD, - ) -> LONG; - pub fn RegSetKeyValueW( - hKey: HKEY, lpSubKey: LPCWSTR, lpValueName: LPCWSTR, dwType: DWORD, lpData: LPCVOID, - cbData: DWORD, - ) -> LONG; - // pub fn RegUnLoadKeyA(); - // pub fn RegUnLoadKeyW(); - // pub fn RegisterEventSourceA(); - // pub fn RegisterEventSourceW(); - pub fn RegisterServiceCtrlHandlerA( - lpServiceName: LPCSTR, lpHandlerProc: LPHANDLER_FUNCTION, - ) -> SERVICE_STATUS_HANDLE; - pub fn RegisterServiceCtrlHandlerExA( - lpServiceName: LPCSTR, lpHandlerProc: LPHANDLER_FUNCTION_EX, lpContext: LPVOID, - ) -> SERVICE_STATUS_HANDLE; - pub fn RegisterServiceCtrlHandlerExW( - lpServiceName: LPCWSTR, lpHandlerProc: LPHANDLER_FUNCTION_EX, lpContext: LPVOID, - ) -> SERVICE_STATUS_HANDLE; - pub fn RegisterServiceCtrlHandlerW( - lpServiceName: LPCWSTR, lpHandlerProc: LPHANDLER_FUNCTION, - ) -> SERVICE_STATUS_HANDLE; - // pub fn RegisterTraceGuidsA(); - // pub fn RegisterTraceGuidsW(); - // pub fn RegisterWaitChainCOMCallback(); - // pub fn RemoteRegEnumKeyWrapper(); - // pub fn RemoteRegEnumValueWrapper(); - // pub fn RemoteRegQueryInfoKeyWrapper(); - // pub fn RemoteRegQueryValueWrapper(); - // pub fn RemoveTraceCallback(); - // pub fn RemoveUsersFromEncryptedFile(); - // pub fn ReportEventA(); - // pub fn ReportEventW(); - // pub fn RevertToSelf(); - // pub fn SafeBaseRegGetKeySecurity(); - // pub fn SaferCloseLevel(); - // pub fn SaferComputeTokenFromLevel(); - // pub fn SaferCreateLevel(); - // pub fn SaferGetLevelInformation(); - // pub fn SaferGetPolicyInformation(); - // pub fn SaferIdentifyLevel(); - // pub fn SaferRecordEventLogEntry(); - // pub fn SaferSetLevelInformation(); - // pub fn SaferSetPolicyInformation(); - // pub fn SaferiIsExecutableFileType(); - // pub fn SetAclInformation(); - // pub fn SetEncryptedFileMetadata(); - // pub fn SetEntriesInAccessListA(); - // pub fn SetEntriesInAccessListW(); - // pub fn SetEntriesInAclA(); - // pub fn SetEntriesInAclW(); - // pub fn SetEntriesInAuditListA(); - // pub fn SetEntriesInAuditListW(); - // pub fn SetFileSecurityA(); - // pub fn SetFileSecurityW(); - // pub fn SetInformationCodeAuthzLevelW(); - // pub fn SetInformationCodeAuthzPolicyW(); - // pub fn SetKernelObjectSecurity(); - // pub fn SetNamedSecurityInfoA(); - // pub fn SetNamedSecurityInfoExA(); - // pub fn SetNamedSecurityInfoExW(); - // pub fn SetNamedSecurityInfoW(); - // pub fn SetPrivateObjectSecurity(); - // pub fn SetPrivateObjectSecurityEx(); - // pub fn SetSecurityAccessMask(); - // pub fn SetSecurityDescriptorControl(); - // pub fn SetSecurityDescriptorDacl(); - // pub fn SetSecurityDescriptorGroup(); - // pub fn SetSecurityDescriptorOwner(); - // pub fn SetSecurityDescriptorRMControl(); - // pub fn SetSecurityDescriptorSacl(); - // pub fn SetSecurityInfo(); - // pub fn SetSecurityInfoExA(); - // pub fn SetSecurityInfoExW(); - // pub fn SetServiceBits(); - // pub fn SetServiceObjectSecurity(); - pub fn SetServiceStatus( - hServiceStatus: SERVICE_STATUS_HANDLE, lpServiceStatus: LPSERVICE_STATUS, - ) -> BOOL; - // pub fn SetThreadToken(); - // pub fn SetTokenInformation(); - // pub fn SetTraceCallback(); - // pub fn SetUserFileEncryptionKey(); - // pub fn SetUserFileEncryptionKeyEx(); - // pub fn StartServiceA(); - pub fn StartServiceCtrlDispatcherA(lpServiceStartTable: *const SERVICE_TABLE_ENTRYA) -> BOOL; - pub fn StartServiceCtrlDispatcherW(lpServiceStartTable: *const SERVICE_TABLE_ENTRYW) -> BOOL; - // pub fn StartServiceW(); - // pub fn StartTraceA(); - // pub fn StartTraceW(); - // pub fn StopTraceA(); - // pub fn StopTraceW(); - // pub fn SystemFunction001(); - // pub fn SystemFunction002(); - // pub fn SystemFunction003(); - // pub fn SystemFunction004(); - // pub fn SystemFunction005(); - // pub fn SystemFunction006(); - // pub fn SystemFunction007(); - // pub fn SystemFunction008(); - // pub fn SystemFunction009(); - // pub fn SystemFunction010(); - // pub fn SystemFunction011(); - // pub fn SystemFunction012(); - // pub fn SystemFunction013(); - // pub fn SystemFunction014(); - // pub fn SystemFunction015(); - // pub fn SystemFunction016(); - // pub fn SystemFunction017(); - // pub fn SystemFunction018(); - // pub fn SystemFunction019(); - // pub fn SystemFunction020(); - // pub fn SystemFunction021(); - // pub fn SystemFunction022(); - // pub fn SystemFunction023(); - // pub fn SystemFunction024(); - // pub fn SystemFunction025(); - // pub fn SystemFunction026(); - // pub fn SystemFunction027(); - // pub fn SystemFunction028(); - // pub fn SystemFunction029(); - // pub fn SystemFunction030(); - // pub fn SystemFunction031(); - // pub fn SystemFunction032(); - // pub fn SystemFunction033(); - // pub fn SystemFunction034(); - // pub fn SystemFunction036(); - // pub fn SystemFunction040(); - // pub fn SystemFunction041(); - // pub fn TraceEvent(); - // pub fn TraceEventInstance(); - // pub fn TraceMessage(); - // pub fn TraceMessageVa(); - // pub fn TraceQueryInformation(); - // pub fn TraceSetInformation(); - // pub fn TreeResetNamedSecurityInfoA(); - // pub fn TreeResetNamedSecurityInfoW(); - // pub fn TreeSetNamedSecurityInfoA(); - // pub fn TreeSetNamedSecurityInfoW(); - // pub fn TrusteeAccessToObjectA(); - // pub fn TrusteeAccessToObjectW(); - // pub fn UninstallApplication(); - // pub fn UnlockServiceDatabase(); - // pub fn UnregisterTraceGuids(); - // pub fn UpdateTraceA(); - // pub fn UpdateTraceW(); - // pub fn UsePinForEncryptedFilesA(); - // pub fn UsePinForEncryptedFilesW(); - // pub fn WaitServiceState(); - // pub fn WriteEncryptedFileRaw(); -} diff -Nru cargo-0.25.0/vendor/atty-0.2.6/appveyor.yml cargo-0.26.0/vendor/atty-0.2.6/appveyor.yml --- cargo-0.25.0/vendor/atty-0.2.6/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.6/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -environment: - matrix: - - TARGET: nightly-x86_64-pc-windows-msvc - - TARGET: nightly-i686-pc-windows-msvc - - TARGET: nightly-x86_64-pc-windows-gnu - - TARGET: nightly-i686-pc-windows-gnu -install: - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:TARGET}.exe" -FileName "rust-install.exe" - - ps: .\rust-install.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null - - ps: $env:PATH="$env:PATH;C:\rust\bin" - - call "%VCVARS%" || ver>nul - - rustc -vV - - cargo -vV -build: false -test_script: - - cargo build diff -Nru cargo-0.25.0/vendor/atty-0.2.6/.cargo-checksum.json cargo-0.26.0/vendor/atty-0.2.6/.cargo-checksum.json --- cargo-0.25.0/vendor/atty-0.2.6/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.6/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"8352656fd42c30a0c3c89d26dea01e3b77c0ab2af18230835c15e2e13cd51859"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/atty-0.2.6/Cargo.toml cargo-0.26.0/vendor/atty-0.2.6/Cargo.toml --- cargo-0.25.0/vendor/atty-0.2.6/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.6/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "atty" -version = "0.2.6" -authors = ["softprops "] -description = "A simple interface for querying atty" -homepage = "https://github.com/softprops/atty" -documentation = "http://softprops.github.io/atty" -readme = "README.md" -keywords = ["terminal", "tty"] -license = "MIT" -repository = "https://github.com/softprops/atty" -[target."cfg(windows)".dependencies.winapi] -version = "0.3" -features = ["consoleapi", "processenv", "minwinbase", "minwindef", "winbase"] -[target."cfg(unix)".dependencies.libc] -version = "0.2" -default-features = false -[target."cfg(target_os = \"redox\")".dependencies.termion] -version = "1.5" -[badges.travis-ci] -repository = "softprops/atty" diff -Nru cargo-0.25.0/vendor/atty-0.2.6/CHANGELOG.md cargo-0.26.0/vendor/atty-0.2.6/CHANGELOG.md --- cargo-0.25.0/vendor/atty-0.2.6/CHANGELOG.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.6/CHANGELOG.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -# 0.2.6 - -* updated winapi dependency to [0.3](https://retep998.github.io/blog/winapi-0.3/) [#18](https://github.com/softprops/atty/pull/18) - -# 0.2.5 - -* added support for Wasm compile targets [#17](https://github.com/softprops/atty/pull/17) - -# 0.2.4 - -* added support for Wasm compile targets [#17](https://github.com/softprops/atty/pull/17) - -# 0.2.3 - -* added support for Redox OS [#14](https://github.com/softprops/atty/pull/14) - -# 0.2.2 - -* use target specific dependencies [#11](https://github.com/softprops/atty/pull/11) -* Add tty detection for MSYS terminals [#12](https://github.com/softprops/atty/pull/12) - -# 0.2.1 - -* fix windows bug - -# 0.2.0 - -* support for various stream types - -# 0.1.2 - -* windows support (with automated testing) -* automated code coverage - -# 0.1.1 - -* bumped libc dep from `0.1` to `0.2` - -# 0.1.0 - -* initial release diff -Nru cargo-0.25.0/vendor/atty-0.2.6/examples/atty.rs cargo-0.26.0/vendor/atty-0.2.6/examples/atty.rs --- cargo-0.25.0/vendor/atty-0.2.6/examples/atty.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.6/examples/atty.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ -extern crate atty; - -use atty::{is, Stream}; - -fn main() { - println!("stdout? {}", is(Stream::Stdout)); - println!("stderr? {}", is(Stream::Stderr)); - println!("stdin? {}", is(Stream::Stdin)); -} diff -Nru cargo-0.25.0/vendor/atty-0.2.6/LICENSE cargo-0.26.0/vendor/atty-0.2.6/LICENSE --- cargo-0.25.0/vendor/atty-0.2.6/LICENSE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.6/LICENSE 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -Copyright (c) 2015-2017 Doug Tangren - -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. diff -Nru cargo-0.25.0/vendor/atty-0.2.6/README.md cargo-0.26.0/vendor/atty-0.2.6/README.md --- cargo-0.25.0/vendor/atty-0.2.6/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.6/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -# atty - -[![Build Status](https://travis-ci.org/softprops/atty.svg?branch=master)](https://travis-ci.org/softprops/atty) [![Build status](https://ci.appveyor.com/api/projects/status/geggrsnsjsuse8cv?svg=true)](https://ci.appveyor.com/project/softprops/atty) [![Coverage Status](https://coveralls.io/repos/softprops/atty/badge.svg?branch=master&service=github)](https://coveralls.io/github/softprops/atty?branch=master) [![crates.io](http://meritbadge.herokuapp.com/atty)](https://crates.io/crates/atty) - -> are you or are you not a tty? - - -[Documentation](http://softprops.github.io/atty) - -## install - -Add the following to your `Cargo.toml` - -```toml -[dependencies] -atty = "0.2" -``` - -## usage - -```rust -extern crate atty; - -use atty::Stream; - -fn main() { - if atty::is(Stream::Stdout) { - println!("I'm a terminal"); - } else { - println!("I'm not"); - } -} -``` - -## testing - -This library has been unit tested on both unix and windows platforms (via appveyor). - - -A simple example program is provided in this repo to test various tty's. By default. - -It prints - -```bash -$ cargo run --example atty -stdout? true -stderr? true -stdin? true -``` - -To test std in, pipe some text to the program - -```bash -$ echo "test" | cargo run --example atty -stdout? true -stderr? true -stdin? false -``` - -To test std out, pipe the program to something - -```bash -$ cargo run --example atty | grep std -stdout? false -stderr? true -stdin? true -``` - -To test std err, pipe the program to something redirecting std err - -```bash -$ cargo run --example atty 2>&1 | grep std -stdout? false -stderr? false -stdin? true -``` - -Doug Tangren (softprops) 2015-2017 diff -Nru cargo-0.25.0/vendor/atty-0.2.6/rustfmt.toml cargo-0.26.0/vendor/atty-0.2.6/rustfmt.toml --- cargo-0.25.0/vendor/atty-0.2.6/rustfmt.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.6/rustfmt.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ -# keep imports tidy -reorder_imported_names = true -reorder_imports = true -reorder_imports_in_group = true -# there is no try! -use_try_shorthand = true -# don't create rustfmt artifacts -write_mode = "Replace" -# reduce wide load -max_width = 80 \ No newline at end of file diff -Nru cargo-0.25.0/vendor/atty-0.2.6/src/lib.rs cargo-0.26.0/vendor/atty-0.2.6/src/lib.rs --- cargo-0.25.0/vendor/atty-0.2.6/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.6/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,210 +0,0 @@ -//! atty is a simple utility that answers one question -//! > is this a tty? -//! -//! usage is just as simple -//! -//! ``` -//! if atty::is(atty::Stream::Stdout) { -//! println!("i'm a tty") -//! } -//! ``` -//! -//! ``` -//! if atty::isnt(atty::Stream::Stdout) { -//! println!("i'm not a tty") -//! } -//! ``` - -#![cfg_attr(unix, no_std)] - -#[cfg(unix)] -extern crate libc; -#[cfg(windows)] -extern crate winapi; -#[cfg(target_os = "redox")] -extern crate termion; - -#[cfg(windows)] -use winapi::shared::minwindef::DWORD; - -/// possible stream sources -#[derive(Clone, Copy, Debug)] -pub enum Stream { - Stdout, - Stderr, - Stdin, -} - -/// returns true if this is a tty -#[cfg(unix)] -pub fn is(stream: Stream) -> bool { - extern crate libc; - - let fd = match stream { - Stream::Stdout => libc::STDOUT_FILENO, - Stream::Stderr => libc::STDERR_FILENO, - Stream::Stdin => libc::STDIN_FILENO, - }; - unsafe { libc::isatty(fd) != 0 } -} - -/// returns true if this is a tty -#[cfg(windows)] -pub fn is(stream: Stream) -> bool { - use winapi::um::winbase::{STD_ERROR_HANDLE as STD_ERROR, STD_INPUT_HANDLE as STD_INPUT, - STD_OUTPUT_HANDLE as STD_OUTPUT}; - - let (fd, others) = match stream { - Stream::Stdin => (STD_INPUT, [STD_ERROR, STD_OUTPUT]), - Stream::Stderr => (STD_ERROR, [STD_INPUT, STD_OUTPUT]), - Stream::Stdout => (STD_OUTPUT, [STD_INPUT, STD_ERROR]), - }; - if unsafe { console_on_any(&[fd]) } { - // False positives aren't possible. If we got a console then - // we definitely have a tty on stdin. - return true; - } - - // At this point, we *could* have a false negative. We can determine that - // this is true negative if we can detect the presence of a console on - // any of the other streams. If another stream has a console, then we know - // we're in a Windows console and can therefore trust the negative. - if unsafe { console_on_any(&others) } { - return false; - } - - // Otherwise, we fall back to a very strange msys hack to see if we can - // sneakily detect the presence of a tty. - unsafe { msys_tty_on(fd) } -} - -/// returns true if this is _not_ a tty -pub fn isnt(stream: Stream) -> bool { - !is(stream) -} - -/// Returns true if any of the given fds are on a console. -#[cfg(windows)] -unsafe fn console_on_any(fds: &[DWORD]) -> bool { - use winapi::um::consoleapi::GetConsoleMode; - use winapi::um::processenv::GetStdHandle; - - for &fd in fds { - let mut out = 0; - let handle = GetStdHandle(fd); - if GetConsoleMode(handle, &mut out) != 0 { - return true; - } - } - false -} - -/// Returns true if there is an MSYS tty on the given handle. -#[cfg(windows)] -unsafe fn msys_tty_on(fd: DWORD) -> bool { - use std::ffi::OsString; - use std::mem; - use std::os::windows::ffi::OsStringExt; - use std::slice; - - use winapi::ctypes::c_void; - use winapi::um::winbase::GetFileInformationByHandleEx; - use winapi::um::fileapi::FILE_NAME_INFO; - use winapi::um::minwinbase::FileNameInfo; - use winapi::um::processenv::GetStdHandle; - use winapi::shared::minwindef::MAX_PATH; - - let size = mem::size_of::(); - let mut name_info_bytes = vec![0u8; size + MAX_PATH]; - let res = GetFileInformationByHandleEx( - GetStdHandle(fd), - FileNameInfo, - &mut *name_info_bytes as *mut _ as *mut c_void, - name_info_bytes.len() as u32, - ); - if res == 0 { - return true; - } - let name_info: FILE_NAME_INFO = *(name_info_bytes[0..size].as_ptr() as - *const FILE_NAME_INFO); - let name_bytes = - &name_info_bytes[size..size + name_info.FileNameLength as usize]; - let name_u16 = slice::from_raw_parts( - name_bytes.as_ptr() as *const u16, - name_bytes.len() / 2, - ); - let name = OsString::from_wide(name_u16) - .as_os_str() - .to_string_lossy() - .into_owned(); - name.contains("msys-") || name.contains("-pty") -} - -/// returns true if this is a tty -#[cfg(target_os = "redox")] -pub fn is(stream: Stream) -> bool { - use std::io; - use termion::is_tty; - - match stream { - Stream::Stdin => is_tty(&io::stdin()), - Stream::Stdout => is_tty(&io::stdout()), - Stream::Stderr => is_tty(&io::stderr()), - } -} - -/// returns true if this is a tty -#[cfg(target_arch = "wasm32")] -pub fn is(_stream: Stream) -> bool { - false -} - -#[cfg(test)] -mod tests { - use super::{Stream, is}; - - #[test] - #[cfg(windows)] - fn is_err() { - // appveyor pipes its output - assert!(!is(Stream::Stderr)) - } - - #[test] - #[cfg(windows)] - fn is_out() { - // appveyor pipes its output - assert!(!is(Stream::Stdout)) - } - - #[test] - #[cfg(windows)] - fn is_in() { - assert!(is(Stream::Stdin)) - } - - #[test] - #[cfg(unix)] - fn is_err() { - assert!(is(Stream::Stderr)) - } - - #[test] - #[cfg(unix)] - fn is_out() { - assert!(is(Stream::Stdout)) - } - - #[test] - #[cfg(target_os = "macos")] - fn is_in() { - // macos on travis seems to pipe its input - assert!(is(Stream::Stdin)) - } - - #[test] - #[cfg(all(not(target_os = "macos"), unix))] - fn is_in() { - assert!(is(Stream::Stdin)) - } -} diff -Nru cargo-0.25.0/vendor/atty-0.2.6/.travis.yml cargo-0.26.0/vendor/atty-0.2.6/.travis.yml --- cargo-0.25.0/vendor/atty-0.2.6/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.6/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -sudo: false -language: rust -matrix: - fast_finish: true - include: - - rust: nightly - - rust: nightly - os: osx - - rust: beta - - rust: beta - os: osx - - rust: stable - - rust: stable - os: osx - allow_failures: - - rust: nightly - -before_cache: - # Travis can't cache files that are not readable by "others" - - chmod -R a+r $HOME/.cargo - -before_install: - # install kcov - - > - if [ ! -d "$HOME/.kcov/bin" ]; then - wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && - tar xzf master.tar.gz && mkdir kcov-master/build && cd kcov-master/build && - cmake -DCMAKE_INSTALL_PREFIX:PATH=$HOME/.kcov .. && make && make install && cd ../.. - fi - - export PATH=$HOME/.kcov/bin:$PATH - -script: - - cargo build - -cache: - cargo: true - apt: true - directories: - - target/debug/deps - - target/debug/build - -addons: - apt: - packages: - - libcurl4-openssl-dev - - libelf-dev - - libdw-dev - - binutils-dev - - libiberty-dev - -after_success: - - '[ $TRAVIS_RUST_VERSION = stable ] && - [ $TRAVIS_BRANCH = master ] && - [ $TRAVIS_PULL_REQUEST = false ] && - (ls target/debug && - RUSTFLAGS="-C link-dead-code" cargo test --no-run && - for file in target/debug/atty-*; do - if [[ "${file: -2}" != ".d" ]]; then - mkdir -p "target/cov/$(basename $file)"; - kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; - fi; - done && - kcov --coveralls-id=$COVERALLS_REPO_TOKEN --merge target/cov target/cov/* && - echo "covered") || true' - - '[ $TRAVIS_RUST_VERSION = stable ] && - [ $TRAVIS_BRANCH = master ] && - [ $TRAVIS_PULL_REQUEST = false ] - && cargo doc --no-deps && - echo "" > target/doc/index.html && - pip install --user ghp-import && - /home/travis/.local/bin/ghp-import -n target/doc && - git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages && - echo "documented"' \ No newline at end of file diff -Nru cargo-0.25.0/vendor/atty-0.2.8/appveyor.yml cargo-0.26.0/vendor/atty-0.2.8/appveyor.yml --- cargo-0.25.0/vendor/atty-0.2.8/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.8/appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,16 @@ +environment: + matrix: + - TARGET: nightly-x86_64-pc-windows-msvc + - TARGET: nightly-i686-pc-windows-msvc + - TARGET: nightly-x86_64-pc-windows-gnu + - TARGET: nightly-i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:TARGET}.exe" -FileName "rust-install.exe" + - ps: .\rust-install.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null + - ps: $env:PATH="$env:PATH;C:\rust\bin" + - call "%VCVARS%" || ver>nul + - rustc -vV + - cargo -vV +build: false +test_script: + - cargo build diff -Nru cargo-0.25.0/vendor/atty-0.2.8/.cargo-checksum.json cargo-0.26.0/vendor/atty-0.2.8/.cargo-checksum.json --- cargo-0.25.0/vendor/atty-0.2.8/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.8/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"af80143d6f7608d746df1520709e5d141c96f240b0e62b0aa41bdfb53374d9d4"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/atty-0.2.8/Cargo.toml cargo-0.26.0/vendor/atty-0.2.8/Cargo.toml --- cargo-0.25.0/vendor/atty-0.2.8/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.8/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,33 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "atty" +version = "0.2.8" +authors = ["softprops "] +description = "A simple interface for querying atty" +homepage = "https://github.com/softprops/atty" +documentation = "http://softprops.github.io/atty" +readme = "README.md" +keywords = ["terminal", "tty"] +license = "MIT" +repository = "https://github.com/softprops/atty" +[target."cfg(target_os = \"redox\")".dependencies.termion] +version = "1.5" +[target."cfg(unix)".dependencies.libc] +version = "0.2" +default-features = false +[target."cfg(windows)".dependencies.winapi] +version = "0.3" +features = ["consoleapi", "processenv", "minwinbase", "minwindef", "winbase"] +[badges.travis-ci] +repository = "softprops/atty" diff -Nru cargo-0.25.0/vendor/atty-0.2.8/CHANGELOG.md cargo-0.26.0/vendor/atty-0.2.8/CHANGELOG.md --- cargo-0.25.0/vendor/atty-0.2.8/CHANGELOG.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.8/CHANGELOG.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,49 @@ +# 0.2.8 + +* Fix an inverted condition on MinGW [#22](https://github.com/softprops/atty/pull/22) + +# 0.2.7 + +* Change `||` to `&&` for whether MSYS is a tty [#24](https://github.com/softprops/atty/pull/24/) + +# 0.2.6 + +* updated winapi dependency to [0.3](https://retep998.github.io/blog/winapi-0.3/) [#18](https://github.com/softprops/atty/pull/18) + +# 0.2.5 + +* added support for Wasm compile targets [#17](https://github.com/softprops/atty/pull/17) + +# 0.2.4 + +* added support for Wasm compile targets [#17](https://github.com/softprops/atty/pull/17) + +# 0.2.3 + +* added support for Redox OS [#14](https://github.com/softprops/atty/pull/14) + +# 0.2.2 + +* use target specific dependencies [#11](https://github.com/softprops/atty/pull/11) +* Add tty detection for MSYS terminals [#12](https://github.com/softprops/atty/pull/12) + +# 0.2.1 + +* fix windows bug + +# 0.2.0 + +* support for various stream types + +# 0.1.2 + +* windows support (with automated testing) +* automated code coverage + +# 0.1.1 + +* bumped libc dep from `0.1` to `0.2` + +# 0.1.0 + +* initial release diff -Nru cargo-0.25.0/vendor/atty-0.2.8/examples/atty.rs cargo-0.26.0/vendor/atty-0.2.8/examples/atty.rs --- cargo-0.25.0/vendor/atty-0.2.8/examples/atty.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.8/examples/atty.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,9 @@ +extern crate atty; + +use atty::{is, Stream}; + +fn main() { + println!("stdout? {}", is(Stream::Stdout)); + println!("stderr? {}", is(Stream::Stderr)); + println!("stdin? {}", is(Stream::Stdin)); +} diff -Nru cargo-0.25.0/vendor/atty-0.2.8/LICENSE cargo-0.26.0/vendor/atty-0.2.8/LICENSE --- cargo-0.25.0/vendor/atty-0.2.8/LICENSE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.8/LICENSE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +Copyright (c) 2015-2017 Doug Tangren + +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. diff -Nru cargo-0.25.0/vendor/atty-0.2.8/README.md cargo-0.26.0/vendor/atty-0.2.8/README.md --- cargo-0.25.0/vendor/atty-0.2.8/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.8/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,78 @@ +# atty + +[![Build Status](https://travis-ci.org/softprops/atty.svg?branch=master)](https://travis-ci.org/softprops/atty) [![Build status](https://ci.appveyor.com/api/projects/status/geggrsnsjsuse8cv?svg=true)](https://ci.appveyor.com/project/softprops/atty) [![Coverage Status](https://coveralls.io/repos/softprops/atty/badge.svg?branch=master&service=github)](https://coveralls.io/github/softprops/atty?branch=master) [![crates.io](http://meritbadge.herokuapp.com/atty)](https://crates.io/crates/atty) + +> are you or are you not a tty? + + +[Documentation](http://softprops.github.io/atty) + +## install + +Add the following to your `Cargo.toml` + +```toml +[dependencies] +atty = "0.2" +``` + +## usage + +```rust +extern crate atty; + +use atty::Stream; + +fn main() { + if atty::is(Stream::Stdout) { + println!("I'm a terminal"); + } else { + println!("I'm not"); + } +} +``` + +## testing + +This library has been unit tested on both unix and windows platforms (via appveyor). + + +A simple example program is provided in this repo to test various tty's. By default. + +It prints + +```bash +$ cargo run --example atty +stdout? true +stderr? true +stdin? true +``` + +To test std in, pipe some text to the program + +```bash +$ echo "test" | cargo run --example atty +stdout? true +stderr? true +stdin? false +``` + +To test std out, pipe the program to something + +```bash +$ cargo run --example atty | grep std +stdout? false +stderr? true +stdin? true +``` + +To test std err, pipe the program to something redirecting std err + +```bash +$ cargo run --example atty 2>&1 | grep std +stdout? false +stderr? false +stdin? true +``` + +Doug Tangren (softprops) 2015-2017 diff -Nru cargo-0.25.0/vendor/atty-0.2.8/rustfmt.toml cargo-0.26.0/vendor/atty-0.2.8/rustfmt.toml --- cargo-0.25.0/vendor/atty-0.2.8/rustfmt.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.8/rustfmt.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,10 @@ +# keep imports tidy +reorder_imported_names = true +reorder_imports = true +reorder_imports_in_group = true +# there is no try! +use_try_shorthand = true +# don't create rustfmt artifacts +write_mode = "Replace" +# reduce wide load +max_width = 80 \ No newline at end of file diff -Nru cargo-0.25.0/vendor/atty-0.2.8/src/lib.rs cargo-0.26.0/vendor/atty-0.2.8/src/lib.rs --- cargo-0.25.0/vendor/atty-0.2.8/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.8/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,210 @@ +//! atty is a simple utility that answers one question +//! > is this a tty? +//! +//! usage is just as simple +//! +//! ``` +//! if atty::is(atty::Stream::Stdout) { +//! println!("i'm a tty") +//! } +//! ``` +//! +//! ``` +//! if atty::isnt(atty::Stream::Stdout) { +//! println!("i'm not a tty") +//! } +//! ``` + +#![cfg_attr(unix, no_std)] + +#[cfg(unix)] +extern crate libc; +#[cfg(windows)] +extern crate winapi; +#[cfg(target_os = "redox")] +extern crate termion; + +#[cfg(windows)] +use winapi::shared::minwindef::DWORD; + +/// possible stream sources +#[derive(Clone, Copy, Debug)] +pub enum Stream { + Stdout, + Stderr, + Stdin, +} + +/// returns true if this is a tty +#[cfg(unix)] +pub fn is(stream: Stream) -> bool { + extern crate libc; + + let fd = match stream { + Stream::Stdout => libc::STDOUT_FILENO, + Stream::Stderr => libc::STDERR_FILENO, + Stream::Stdin => libc::STDIN_FILENO, + }; + unsafe { libc::isatty(fd) != 0 } +} + +/// returns true if this is a tty +#[cfg(windows)] +pub fn is(stream: Stream) -> bool { + use winapi::um::winbase::{STD_ERROR_HANDLE as STD_ERROR, STD_INPUT_HANDLE as STD_INPUT, + STD_OUTPUT_HANDLE as STD_OUTPUT}; + + let (fd, others) = match stream { + Stream::Stdin => (STD_INPUT, [STD_ERROR, STD_OUTPUT]), + Stream::Stderr => (STD_ERROR, [STD_INPUT, STD_OUTPUT]), + Stream::Stdout => (STD_OUTPUT, [STD_INPUT, STD_ERROR]), + }; + if unsafe { console_on_any(&[fd]) } { + // False positives aren't possible. If we got a console then + // we definitely have a tty on stdin. + return true; + } + + // At this point, we *could* have a false negative. We can determine that + // this is true negative if we can detect the presence of a console on + // any of the other streams. If another stream has a console, then we know + // we're in a Windows console and can therefore trust the negative. + if unsafe { console_on_any(&others) } { + return false; + } + + // Otherwise, we fall back to a very strange msys hack to see if we can + // sneakily detect the presence of a tty. + unsafe { msys_tty_on(fd) } +} + +/// returns true if this is _not_ a tty +pub fn isnt(stream: Stream) -> bool { + !is(stream) +} + +/// Returns true if any of the given fds are on a console. +#[cfg(windows)] +unsafe fn console_on_any(fds: &[DWORD]) -> bool { + use winapi::um::consoleapi::GetConsoleMode; + use winapi::um::processenv::GetStdHandle; + + for &fd in fds { + let mut out = 0; + let handle = GetStdHandle(fd); + if GetConsoleMode(handle, &mut out) != 0 { + return true; + } + } + false +} + +/// Returns true if there is an MSYS tty on the given handle. +#[cfg(windows)] +unsafe fn msys_tty_on(fd: DWORD) -> bool { + use std::ffi::OsString; + use std::mem; + use std::os::windows::ffi::OsStringExt; + use std::slice; + + use winapi::ctypes::c_void; + use winapi::um::winbase::GetFileInformationByHandleEx; + use winapi::um::fileapi::FILE_NAME_INFO; + use winapi::um::minwinbase::FileNameInfo; + use winapi::um::processenv::GetStdHandle; + use winapi::shared::minwindef::MAX_PATH; + + let size = mem::size_of::(); + let mut name_info_bytes = vec![0u8; size + MAX_PATH]; + let res = GetFileInformationByHandleEx( + GetStdHandle(fd), + FileNameInfo, + &mut *name_info_bytes as *mut _ as *mut c_void, + name_info_bytes.len() as u32, + ); + if res == 0 { + return false; + } + let name_info: FILE_NAME_INFO = *(name_info_bytes[0..size].as_ptr() as + *const FILE_NAME_INFO); + let name_bytes = + &name_info_bytes[size..size + name_info.FileNameLength as usize]; + let name_u16 = slice::from_raw_parts( + name_bytes.as_ptr() as *const u16, + name_bytes.len() / 2, + ); + let name = OsString::from_wide(name_u16) + .as_os_str() + .to_string_lossy() + .into_owned(); + name.contains("msys-") && name.contains("-pty") +} + +/// returns true if this is a tty +#[cfg(target_os = "redox")] +pub fn is(stream: Stream) -> bool { + use std::io; + use termion::is_tty; + + match stream { + Stream::Stdin => is_tty(&io::stdin()), + Stream::Stdout => is_tty(&io::stdout()), + Stream::Stderr => is_tty(&io::stderr()), + } +} + +/// returns true if this is a tty +#[cfg(target_arch = "wasm32")] +pub fn is(_stream: Stream) -> bool { + false +} + +#[cfg(test)] +mod tests { + use super::{Stream, is}; + + #[test] + #[cfg(windows)] + fn is_err() { + // appveyor pipes its output + assert!(!is(Stream::Stderr)) + } + + #[test] + #[cfg(windows)] + fn is_out() { + // appveyor pipes its output + assert!(!is(Stream::Stdout)) + } + + #[test] + #[cfg(windows)] + fn is_in() { + assert!(is(Stream::Stdin)) + } + + #[test] + #[cfg(unix)] + fn is_err() { + assert!(is(Stream::Stderr)) + } + + #[test] + #[cfg(unix)] + fn is_out() { + assert!(is(Stream::Stdout)) + } + + #[test] + #[cfg(target_os = "macos")] + fn is_in() { + // macos on travis seems to pipe its input + assert!(is(Stream::Stdin)) + } + + #[test] + #[cfg(all(not(target_os = "macos"), unix))] + fn is_in() { + assert!(is(Stream::Stdin)) + } +} diff -Nru cargo-0.25.0/vendor/atty-0.2.8/.travis.yml cargo-0.26.0/vendor/atty-0.2.8/.travis.yml --- cargo-0.25.0/vendor/atty-0.2.8/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/atty-0.2.8/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,73 @@ +sudo: false +language: rust +matrix: + fast_finish: true + include: + - rust: nightly + - rust: nightly + os: osx + - rust: beta + - rust: beta + os: osx + - rust: stable + - rust: stable + os: osx + allow_failures: + - rust: nightly + +before_cache: + # Travis can't cache files that are not readable by "others" + - chmod -R a+r $HOME/.cargo + +before_install: + # install kcov + - > + if [ ! -d "$HOME/.kcov/bin" ]; then + wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz && + tar xzf master.tar.gz && mkdir kcov-master/build && cd kcov-master/build && + cmake -DCMAKE_INSTALL_PREFIX:PATH=$HOME/.kcov .. && make && make install && cd ../.. + fi + - export PATH=$HOME/.kcov/bin:$PATH + +script: + - cargo build + +cache: + cargo: true + apt: true + directories: + - target/debug/deps + - target/debug/build + +addons: + apt: + packages: + - libcurl4-openssl-dev + - libelf-dev + - libdw-dev + - binutils-dev + - libiberty-dev + +after_success: + - '[ $TRAVIS_RUST_VERSION = stable ] && + [ $TRAVIS_BRANCH = master ] && + [ $TRAVIS_PULL_REQUEST = false ] && + (ls target/debug && + RUSTFLAGS="-C link-dead-code" cargo test --no-run && + for file in target/debug/atty-*; do + if [[ "${file: -2}" != ".d" ]]; then + mkdir -p "target/cov/$(basename $file)"; + kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; + fi; + done && + kcov --coveralls-id=$COVERALLS_REPO_TOKEN --merge target/cov target/cov/* && + echo "covered") || true' + - '[ $TRAVIS_RUST_VERSION = stable ] && + [ $TRAVIS_BRANCH = master ] && + [ $TRAVIS_PULL_REQUEST = false ] + && cargo doc --no-deps && + echo "" > target/doc/index.html && + pip install --user ghp-import && + /home/travis/.local/bin/ghp-import -n target/doc && + git push -fq https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages && + echo "documented"' \ No newline at end of file diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/appveyor.yml cargo-0.26.0/vendor/backtrace-0.3.5/appveyor.yml --- cargo-0.25.0/vendor/backtrace-0.3.5/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -environment: - matrix: - - TARGET: x86_64-pc-windows-gnu - MSYS_BITS: 64 - - TARGET: i686-pc-windows-gnu - MSYS_BITS: 32 - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc -install: - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" - - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - - set PATH=%PATH%;C:\Program Files (x86)\Rust\bin - - if defined MSYS_BITS set PATH=%PATH%;C:\msys64\mingw%MSYS_BITS%\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test --target %TARGET% diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/.cargo-checksum.json cargo-0.26.0/vendor/backtrace-0.3.5/.cargo-checksum.json --- cargo-0.25.0/vendor/backtrace-0.3.5/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"ebbbf59b1c43eefa8c3ede390fcc36820b4999f7914104015be25025e0d62af2"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/Cargo.toml cargo-0.26.0/vendor/backtrace-0.3.5/Cargo.toml --- cargo-0.25.0/vendor/backtrace-0.3.5/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,74 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "backtrace" -version = "0.3.5" -authors = ["Alex Crichton ", "The Rust Project Developers"] -description = "A library to acquire a stack trace (backtrace) at runtime in a Rust program.\n" -homepage = "https://github.com/alexcrichton/backtrace-rs" -documentation = "http://alexcrichton.com/backtrace-rs" -readme = "README.md" -license = "MIT/Apache-2.0" -repository = "https://github.com/alexcrichton/backtrace-rs" -[dependencies.addr2line] -version = "0.5.0" -optional = true - -[dependencies.cfg-if] -version = "0.1" - -[dependencies.cpp_demangle] -version = "0.2.3" -optional = true -default-features = false - -[dependencies.findshlibs] -version = "0.3.3" -optional = true - -[dependencies.rustc-demangle] -version = "0.1.4" - -[dependencies.rustc-serialize] -version = "0.3" -optional = true - -[dependencies.serde] -version = "1.0" -optional = true - -[dependencies.serde_derive] -version = "1.0" -optional = true - -[features] -coresymbolication = [] -dbghelp = ["winapi"] -default = ["libunwind", "libbacktrace", "coresymbolication", "dladdr", "dbghelp"] -dladdr = [] -gimli-symbolize = ["addr2line", "findshlibs"] -kernel32 = [] -libbacktrace = ["backtrace-sys"] -libunwind = [] -serialize-rustc = ["rustc-serialize"] -serialize-serde = ["serde", "serde_derive"] -unix-backtrace = [] -[target."cfg(all(unix, not(target_os = \"fuchsia\"), not(target_os = \"emscripten\"), not(target_os = \"macos\"), not(target_os = \"ios\")))".dependencies.backtrace-sys] -version = "0.1.3" -optional = true -[target."cfg(unix)".dependencies.libc] -version = "0.2" -[target."cfg(windows)".dependencies.winapi] -version = "0.3.3" -features = ["std", "dbghelp", "processthreadsapi", "winnt", "minwindef"] -optional = true diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/examples/backtrace.rs cargo-0.26.0/vendor/backtrace-0.3.5/examples/backtrace.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/examples/backtrace.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/examples/backtrace.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -extern crate backtrace; - -use backtrace::Backtrace; - -fn main() { - println!("{:?}", Backtrace::new()); -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/examples/raw.rs cargo-0.26.0/vendor/backtrace-0.3.5/examples/raw.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/examples/raw.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/examples/raw.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -extern crate backtrace; - -fn main() { - foo(); -} - -fn foo() { bar() } -fn bar() { baz() } -fn baz() { print() } - -#[cfg(target_pointer_width = "32")] const HEX_WIDTH: usize = 10; -#[cfg(target_pointer_width = "64")] const HEX_WIDTH: usize = 20; - -fn print() { - let mut cnt = 0; - backtrace::trace(|frame| { - let ip = frame.ip(); - print!("frame #{:<2} - {:#02$x}", cnt, ip as usize, HEX_WIDTH); - cnt += 1; - - let mut resolved = false; - backtrace::resolve(frame.ip(), |symbol| { - if !resolved { - resolved = true; - } else { - print!("{}", vec![" "; 7 + 2 + 3 + HEX_WIDTH].join("")); - } - - if let Some(name) = symbol.name() { - print!(" - {}", name); - } else { - print!(" - "); - } - if let Some(file) = symbol.filename() { - if let Some(l) = symbol.lineno() { - print!("\n{:13}{:4$}@ {}:{}", "", "", file.display(), l, - HEX_WIDTH); - } - } - println!(""); - - }); - if !resolved { - println!(" - "); - } - true // keep going - }); -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/LICENSE-APACHE cargo-0.26.0/vendor/backtrace-0.3.5/LICENSE-APACHE --- cargo-0.25.0/vendor/backtrace-0.3.5/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/LICENSE-MIT cargo-0.26.0/vendor/backtrace-0.3.5/LICENSE-MIT --- cargo-0.25.0/vendor/backtrace-0.3.5/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 Alex Crichton - -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. diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/README.md cargo-0.26.0/vendor/backtrace-0.3.5/README.md --- cargo-0.25.0/vendor/backtrace-0.3.5/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,91 +0,0 @@ -# backtrace-rs - -[![Build Status](https://travis-ci.org/alexcrichton/backtrace-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/backtrace-rs) -[![Build status](https://ci.appveyor.com/api/projects/status/v4l9oj4aqbbgyx44?svg=true)](https://ci.appveyor.com/project/alexcrichton/backtrace-rs) - -[Documentation](http://alexcrichton.com/backtrace-rs) - -A library for acquiring backtraces at runtime for Rust. This library aims to -enhance the support given by the standard library at `std::rt` by providing a -more stable and programmatic interface. - -## Install - -```toml -[dependencies] -backtrace = "0.3" -``` - -```rust -extern crate backtrace; -``` - -Note that this crate requires `make`, `objcopy`, and `ar` to be present on Linux -systems. - -## Usage - -To simply capture a backtrace and defer dealing with it until a later time, -you can use the top-level `Backtrace` type. - -```rust -extern crate backtrace; - -use backtrace::Backtrace; - -fn main() { - let bt = Backtrace::new(); - - // do_some_work(); - - println!("{:?}", bt); -} -``` - -If, however, you'd like more raw access to the actual tracing functionality, you -can use the `trace` and `resolve` functions directly. - -```rust -extern crate backtrace; - -fn main() { - backtrace::trace(|frame| { - let ip = frame.ip(); - let symbol_address = frame.symbol_address(); - - // Resolve this instruction pointer to a symbol name - backtrace::resolve(ip, |symbol| { - if let Some(name) = symbol.name() { - // ... - } - if let Some(filename) = symbol.filename() { - // ... - } - }); - - true // keep going to the next frame - }); -} -``` - -## Platform Support - -This library currently supports OSX, Linux, and Windows. Support for other -platforms is always welcome! - -# License - -This project is 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 backtrace-rs by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/backtrace/dbghelp.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/backtrace/dbghelp.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/backtrace/dbghelp.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/backtrace/dbghelp.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(bad_style)] - -use std::mem; -use winapi::ctypes::*; -use winapi::shared::minwindef::*; -use winapi::um::processthreadsapi; -use winapi::um::winnt::{self, CONTEXT}; -use winapi::um::dbghelp; -use winapi::um::dbghelp::*; - -pub struct Frame { - inner: STACKFRAME64, -} - -impl Frame { - pub fn ip(&self) -> *mut c_void { - self.inner.AddrPC.Offset as *mut _ - } - - pub fn symbol_address(&self) -> *mut c_void { - self.ip() - } -} - -#[inline(always)] -pub fn trace(cb: &mut FnMut(&super::Frame) -> bool) { - // According to windows documentation, all dbghelp functions are - // single-threaded. - let _g = ::lock::lock(); - - unsafe { - // Allocate necessary structures for doing the stack walk - let process = processthreadsapi::GetCurrentProcess(); - let thread = processthreadsapi::GetCurrentThread(); - - // The CONTEXT structure needs to be aligned on a 16-byte boundary for - // 64-bit Windows, but currently we don't have a way to express that in - // Rust. Allocations are generally aligned to 16-bytes, though, so we - // box this up. - let mut context = Box::new(mem::zeroed::()); - winnt::RtlCaptureContext(&mut *context); - let mut frame = super::Frame { - inner: Frame { inner: mem::zeroed() }, - }; - let image = init_frame(&mut frame.inner.inner, &context); - - // Initialize this process's symbols - let _c = ::dbghelp_init(); - - // And now that we're done with all the setup, do the stack walking! - while dbghelp::StackWalk64(image as DWORD, - process, - thread, - &mut frame.inner.inner, - &mut *context as *mut _ as *mut _, - None, - Some(dbghelp::SymFunctionTableAccess64), - Some(dbghelp::SymGetModuleBase64), - None) == TRUE { - if frame.inner.inner.AddrPC.Offset == frame.inner.inner.AddrReturn.Offset || - frame.inner.inner.AddrPC.Offset == 0 || - frame.inner.inner.AddrReturn.Offset == 0 { - break - } - - if !cb(&frame) { - break - } - } - } -} - -#[cfg(target_arch = "x86_64")] -fn init_frame(frame: &mut STACKFRAME64, ctx: &CONTEXT) -> WORD { - frame.AddrPC.Offset = ctx.Rip as u64; - frame.AddrPC.Mode = AddrModeFlat; - frame.AddrStack.Offset = ctx.Rsp as u64; - frame.AddrStack.Mode = AddrModeFlat; - frame.AddrFrame.Offset = ctx.Rbp as u64; - frame.AddrFrame.Mode = AddrModeFlat; - winnt::IMAGE_FILE_MACHINE_AMD64 -} - -#[cfg(target_arch = "x86")] -fn init_frame(frame: &mut STACKFRAME64, ctx: &CONTEXT) -> WORD { - frame.AddrPC.Offset = ctx.Eip as u64; - frame.AddrPC.Mode = AddrModeFlat; - frame.AddrStack.Offset = ctx.Esp as u64; - frame.AddrStack.Mode = AddrModeFlat; - frame.AddrFrame.Offset = ctx.Ebp as u64; - frame.AddrFrame.Mode = AddrModeFlat; - winnt::IMAGE_FILE_MACHINE_I386 -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/backtrace/libunwind.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/backtrace/libunwind.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/backtrace/libunwind.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/backtrace/libunwind.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,200 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::os::raw::c_void; - -pub struct Frame { - ctx: *mut uw::_Unwind_Context, -} - -impl Frame { - pub fn ip(&self) -> *mut c_void { - let mut ip_before_insn = 0; - let mut ip = unsafe { - uw::_Unwind_GetIPInfo(self.ctx, &mut ip_before_insn) as *mut c_void - }; - if !ip.is_null() && ip_before_insn == 0 { - // this is a non-signaling frame, so `ip` refers to the address - // after the calling instruction. account for that. - ip = (ip as usize - 1) as *mut _; - } - return ip - } - - pub fn symbol_address(&self) -> *mut c_void { - // dladdr() on osx gets whiny when we use FindEnclosingFunction, and - // it appears to work fine without it, so we only use - // FindEnclosingFunction on non-osx platforms. In doing so, we get a - // slightly more accurate stack trace in the process. - // - // This is often because panic involves the last instruction of a - // function being "call std::rt::begin_unwind", with no ret - // instructions after it. This means that the return instruction - // pointer points *outside* of the calling function, and by - // unwinding it we go back to the original function. - if cfg!(target_os = "macos") || cfg!(target_os = "ios") { - self.ip() - } else { - unsafe { uw::_Unwind_FindEnclosingFunction(self.ip()) } - } - } -} - -#[inline(always)] -pub fn trace(mut cb: &mut FnMut(&super::Frame) -> bool) { - unsafe { - uw::_Unwind_Backtrace(trace_fn, &mut cb as *mut _ as *mut _); - } - - extern fn trace_fn(ctx: *mut uw::_Unwind_Context, - arg: *mut c_void) -> uw::_Unwind_Reason_Code { - let cb = unsafe { &mut *(arg as *mut &mut FnMut(&super::Frame) -> bool) }; - let cx = super::Frame { - inner: Frame { ctx: ctx }, - }; - - let mut bomb = ::Bomb { enabled: true }; - let keep_going = cb(&cx); - bomb.enabled = false; - - if keep_going { - uw::_URC_NO_REASON - } else { - uw::_URC_FAILURE - } - } -} - -/// Unwind library interface used for backtraces -/// -/// Note that dead code is allowed as here are just bindings -/// iOS doesn't use all of them it but adding more -/// platform-specific configs pollutes the code too much -#[allow(non_camel_case_types)] -#[allow(non_snake_case)] -#[allow(dead_code)] -mod uw { - pub use self::_Unwind_Reason_Code::*; - - use libc; - use std::os::raw::{c_int, c_void}; - - #[repr(C)] - pub enum _Unwind_Reason_Code { - _URC_NO_REASON = 0, - _URC_FOREIGN_EXCEPTION_CAUGHT = 1, - _URC_FATAL_PHASE2_ERROR = 2, - _URC_FATAL_PHASE1_ERROR = 3, - _URC_NORMAL_STOP = 4, - _URC_END_OF_STACK = 5, - _URC_HANDLER_FOUND = 6, - _URC_INSTALL_CONTEXT = 7, - _URC_CONTINUE_UNWIND = 8, - _URC_FAILURE = 9, // used only by ARM EABI - } - - pub enum _Unwind_Context {} - - pub type _Unwind_Trace_Fn = - extern fn(ctx: *mut _Unwind_Context, - arg: *mut c_void) -> _Unwind_Reason_Code; - - extern { - // No native _Unwind_Backtrace on iOS - #[cfg(not(all(target_os = "ios", target_arch = "arm")))] - pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn, - trace_argument: *mut c_void) - -> _Unwind_Reason_Code; - - // available since GCC 4.2.0, should be fine for our purpose - #[cfg(all(not(all(target_os = "android", target_arch = "arm")), - not(all(target_os = "linux", target_arch = "arm"))))] - pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context, - ip_before_insn: *mut c_int) - -> libc::uintptr_t; - - #[cfg(all(not(target_os = "android"), - not(all(target_os = "linux", target_arch = "arm"))))] - pub fn _Unwind_FindEnclosingFunction(pc: *mut c_void) - -> *mut c_void; - } - - // On android, the function _Unwind_GetIP is a macro, and this is the - // expansion of the macro. This is all copy/pasted directly from the - // header file with the definition of _Unwind_GetIP. - #[cfg(any(all(target_os = "android", target_arch = "arm"), - all(target_os = "linux", target_arch = "arm")))] - pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t { - #[repr(C)] - enum _Unwind_VRS_Result { - _UVRSR_OK = 0, - _UVRSR_NOT_IMPLEMENTED = 1, - _UVRSR_FAILED = 2, - } - #[repr(C)] - enum _Unwind_VRS_RegClass { - _UVRSC_CORE = 0, - _UVRSC_VFP = 1, - _UVRSC_FPA = 2, - _UVRSC_WMMXD = 3, - _UVRSC_WMMXC = 4, - } - #[repr(C)] - enum _Unwind_VRS_DataRepresentation { - _UVRSD_UINT32 = 0, - _UVRSD_VFPX = 1, - _UVRSD_FPAX = 2, - _UVRSD_UINT64 = 3, - _UVRSD_FLOAT = 4, - _UVRSD_DOUBLE = 5, - } - - type _Unwind_Word = libc::c_uint; - extern { - fn _Unwind_VRS_Get(ctx: *mut _Unwind_Context, - klass: _Unwind_VRS_RegClass, - word: _Unwind_Word, - repr: _Unwind_VRS_DataRepresentation, - data: *mut c_void) - -> _Unwind_VRS_Result; - } - - let mut val: _Unwind_Word = 0; - let ptr = &mut val as *mut _Unwind_Word; - let _ = _Unwind_VRS_Get(ctx, _Unwind_VRS_RegClass::_UVRSC_CORE, 15, - _Unwind_VRS_DataRepresentation::_UVRSD_UINT32, - ptr as *mut c_void); - (val & !1) as libc::uintptr_t - } - - // This function doesn't exist on Android or ARM/Linux, so make it same - // to _Unwind_GetIP - #[cfg(any(all(target_os = "android", target_arch = "arm"), - all(target_os = "linux", target_arch = "arm")))] - pub unsafe fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context, - ip_before_insn: *mut c_int) - -> libc::uintptr_t - { - *ip_before_insn = 0; - _Unwind_GetIP(ctx) - } - - // This function also doesn't exist on Android or ARM/Linux, so make it - // a no-op - #[cfg(any(target_os = "android", - all(target_os = "linux", target_arch = "arm")))] - pub unsafe fn _Unwind_FindEnclosingFunction(pc: *mut c_void) - -> *mut c_void - { - pc - } -} - - diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/backtrace/mod.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/backtrace/mod.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/backtrace/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/backtrace/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,113 +0,0 @@ -use std::fmt; - -use std::os::raw::c_void; - -/// Inspects the current call-stack, passing all active frames into the closure -/// provided to calculate a stack trace. -/// -/// This function is the workhorse of this library in calculating the stack -/// traces for a program. The given closure `cb` is yielded instances of a -/// `Frame` which represent information about that call frame on the stack. The -/// closure is yielded frames in a top-down fashion (most recently called -/// functions first). -/// -/// The closure's return value is an indication of whether the backtrace should -/// continue. A return value of `false` will terminate the backtrace and return -/// immediately. -/// -/// Once a `Frame` is acquired you will likely want to call `backtrace::resolve` -/// to convert the `ip` (instruction pointer) or symbol address to a `Symbol` -/// through which the name and/or filename/line number can be learned. -/// -/// Note that this is a relatively low-level function and if you'd like to, for -/// example, capture a backtrace to be inspected later, then the `Backtrace` -/// type may be more appropriate. -/// -/// # Example -/// -/// ``` -/// extern crate backtrace; -/// -/// fn main() { -/// backtrace::trace(|frame| { -/// // ... -/// -/// true // continue the backtrace -/// }); -/// } -/// ``` -#[inline(never)] // if this is never inlined then the first frame can be known - // to be skipped -pub fn trace bool>(mut cb: F) { - trace_imp(&mut cb) -} - -/// A trait representing one frame of a backtrace, yielded to the `trace` -/// function of this crate. -/// -/// The tracing function's closure will be yielded frames, and the frame is -/// virtually dispatched as the underlying implementation is not always known -/// until runtime. -pub struct Frame { - inner: FrameImp, -} - -impl Frame { - /// Returns the current instruction pointer of this frame. - /// - /// This is normally the next instruction to execute in the frame, but not - /// all implementations list this with 100% accuracy (but it's generally - /// pretty close). - /// - /// It is recommended to pass this value to `backtrace::resolve` to turn it - /// into a symbol name. - pub fn ip(&self) -> *mut c_void { - self.inner.ip() - } - - /// Returns the starting symbol address of the frame of this function. - /// - /// This will attempt to rewind the instruction pointer returned by `ip` to - /// the start of the function, returning that value. In some cases, however, - /// backends will just return `ip` from this function. - /// - /// The returned value can sometimes be used if `backtrace::resolve` failed - /// on the `ip` given above. - pub fn symbol_address(&self) -> *mut c_void { - self.inner.symbol_address() - } -} - -impl fmt::Debug for Frame { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Frame") - .field("ip", &self.ip()) - .field("symbol_address", &self.symbol_address()) - .finish() - } -} - -cfg_if! { - if #[cfg(all(unix, - not(target_os = "emscripten"), - not(all(target_os = "ios", target_arch = "arm")), - feature = "libunwind"))] { - mod libunwind; - use self::libunwind::trace as trace_imp; - use self::libunwind::Frame as FrameImp; - } else if #[cfg(all(unix, - not(target_os = "emscripten"), - feature = "unix-backtrace"))] { - mod unix_backtrace; - use self::unix_backtrace::trace as trace_imp; - use self::unix_backtrace::Frame as FrameImp; - } else if #[cfg(all(windows, feature = "dbghelp"))] { - mod dbghelp; - use self::dbghelp::trace as trace_imp; - use self::dbghelp::Frame as FrameImp; - } else { - mod noop; - use self::noop::trace as trace_imp; - use self::noop::Frame as FrameImp; - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/backtrace/noop.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/backtrace/noop.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/backtrace/noop.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/backtrace/noop.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -use std::os::raw::c_void; - -#[inline(always)] -pub fn trace(_cb: &mut FnMut(&super::Frame) -> bool) {} - -pub struct Frame; - -impl Frame { - pub fn ip(&self) -> *mut c_void { - 0 as *mut _ - } - - pub fn symbol_address(&self) -> *mut c_void { - 0 as *mut _ - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/backtrace/unix_backtrace.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/backtrace/unix_backtrace.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/backtrace/unix_backtrace.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/backtrace/unix_backtrace.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::mem; -use std::os::raw::{c_void, c_int}; - -pub struct Frame { - addr: *mut c_void, -} - -impl Frame { - pub fn ip(&self) -> *mut c_void { self.addr } - pub fn symbol_address(&self) -> *mut c_void { self.addr } -} - -extern { - fn backtrace(buf: *mut *mut c_void, sz: c_int) -> c_int; -} - -#[inline(always)] -pub fn trace(cb: &mut FnMut(&super::Frame) -> bool) { - const SIZE: usize = 100; - - let mut buf: [*mut c_void; SIZE]; - let cnt; - unsafe { - buf = mem::zeroed(); - cnt = backtrace(buf.as_mut_ptr(), SIZE as c_int); - } - - for addr in buf[..cnt as usize].iter() { - let cx = super::Frame { - inner: Frame { addr: *addr }, - }; - if !cb(&cx) { - return - } - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/capture.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/capture.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/capture.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/capture.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,237 +0,0 @@ -use std::fmt; -use std::mem; -use std::os::raw::c_void; -use std::path::{Path, PathBuf}; - -use {trace, resolve, SymbolName}; - -/// Representation of an owned and self-contained backtrace. -/// -/// This structure can be used to capture a backtrace at various points in a -/// program and later used to inspect what the backtrace was at that time. -#[derive(Clone)] -#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))] -#[cfg_attr(feature = "serialize-serde", derive(Deserialize, Serialize))] -pub struct Backtrace { - frames: Vec, -} - -/// Captured version of a frame in a backtrace. -/// -/// This type is returned as a list from `Backtrace::frames` and represents one -/// stack frame in a captured backtrace. -#[derive(Clone)] -#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))] -#[cfg_attr(feature = "serialize-serde", derive(Deserialize, Serialize))] -pub struct BacktraceFrame { - ip: usize, - symbol_address: usize, - symbols: Option>, -} - -/// Captured version of a symbol in a backtrace. -/// -/// This type is returned as a list from `BacktraceFrame::symbols` and -/// represents the metadata for a symbol in a backtrace. -#[derive(Clone)] -#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))] -#[cfg_attr(feature = "serialize-serde", derive(Deserialize, Serialize))] -pub struct BacktraceSymbol { - name: Option>, - addr: Option, - filename: Option, - lineno: Option, -} - -impl Backtrace { - /// Captures a backtrace at the callsite of this function, returning an - /// owned representation. - /// - /// This function is useful for representing a backtrace as an object in - /// Rust. This returned value can be sent across threads and printed - /// elsewhere, and the purpose of this value is to be entirely self - /// contained. - /// - /// # Examples - /// - /// ``` - /// use backtrace::Backtrace; - /// - /// let current_backtrace = Backtrace::new(); - /// ``` - pub fn new() -> Backtrace { - let mut bt = Backtrace::new_unresolved(); - bt.resolve(); - return bt - } - - /// Similar to `new` except that this does not resolve any symbols, this - /// simply captures the backtrace as a list of addresses. - /// - /// At a later time the `resolve` function can be called to resolve this - /// backtrace's symbols into readable names. This function exists because - /// the resolution process can sometimes take a significant amount of time - /// whereas any one backtrace may only be rarely printed. - /// - /// # Examples - /// - /// ``` - /// use backtrace::Backtrace; - /// - /// let mut current_backtrace = Backtrace::new_unresolved(); - /// println!("{:?}", current_backtrace); // no symbol names - /// current_backtrace.resolve(); - /// println!("{:?}", current_backtrace); // symbol names now present - /// ``` - pub fn new_unresolved() -> Backtrace { - let mut frames = Vec::new(); - trace(|frame| { - frames.push(BacktraceFrame { - ip: frame.ip() as usize, - symbol_address: frame.symbol_address() as usize, - symbols: None, - }); - true - }); - - Backtrace { frames: frames } - } - - /// Returns the frames from when this backtrace was captured. - /// - /// The first entry of this slice is likely the function `Backtrace::new`, - /// and the last frame is likely something about how this thread or the main - /// function started. - pub fn frames(&self) -> &[BacktraceFrame] { - &self.frames - } - - /// If this backtrace was created from `new_unresolved` then this function - /// will resolve all addresses in the backtrace to their symbolic names. - /// - /// If this backtrace has been previously resolved or was created through - /// `new`, this function does nothing. - pub fn resolve(&mut self) { - for frame in self.frames.iter_mut().filter(|f| f.symbols.is_none()) { - let mut symbols = Vec::new(); - resolve(frame.ip as *mut _, |symbol| { - symbols.push(BacktraceSymbol { - name: symbol.name().map(|m| m.as_bytes().to_vec()), - addr: symbol.addr().map(|a| a as usize), - filename: symbol.filename().map(|m| m.to_path_buf()), - lineno: symbol.lineno(), - }); - }); - frame.symbols = Some(symbols); - } - } -} - -impl From> for Backtrace { - fn from(frames: Vec) -> Self { - Backtrace { - frames: frames - } - } -} - -impl Into> for Backtrace { - fn into(self) -> Vec { - self.frames - } -} - -impl BacktraceFrame { - /// Same as `Frame::ip` - pub fn ip(&self) -> *mut c_void { - self.ip as *mut c_void - } - - /// Same as `Frame::symbol_address` - pub fn symbol_address(&self) -> *mut c_void { - self.symbol_address as *mut c_void - } - - /// Returns the list of symbols that this frame corresponds to. - /// - /// Normally there is only one symbol per frame, but sometimes if a number - /// of functions are inlined into one frame then multiple symbols will be - /// returned. The first symbol listed is the "innermost function", whereas - /// the last symbol is the outermost (last caller). - /// - /// Note that if this frame came from an unresolved backtrace then this will - /// return an empty list. - pub fn symbols(&self) -> &[BacktraceSymbol] { - self.symbols.as_ref().map(|s| &s[..]).unwrap_or(&[]) - } -} - -impl BacktraceSymbol { - /// Same as `Symbol::name` - pub fn name(&self) -> Option { - self.name.as_ref().map(|s| SymbolName::new(s)) - } - - /// Same as `Symbol::addr` - pub fn addr(&self) -> Option<*mut c_void> { - self.addr.map(|s| s as *mut c_void) - } - - /// Same as `Symbol::filename` - pub fn filename(&self) -> Option<&Path> { - self.filename.as_ref().map(|p| &**p) - } - - /// Same as `Symbol::lineno` - pub fn lineno(&self) -> Option { - self.lineno - } -} - -impl fmt::Debug for Backtrace { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - let hex_width = mem::size_of::() * 2 + 2; - - try!(write!(fmt, "stack backtrace:")); - - for (idx, frame) in self.frames().iter().enumerate() { - let ip = frame.ip(); - try!(write!(fmt, "\n{:4}: {:2$?}", idx, ip, hex_width)); - - let symbols = match frame.symbols { - Some(ref s) => s, - None => { - try!(write!(fmt, " - ")); - continue - } - }; - if symbols.len() == 0 { - try!(write!(fmt, " - ")); - } - - for (idx, symbol) in symbols.iter().enumerate() { - if idx != 0 { - try!(write!(fmt, "\n {:1$}", "", hex_width)); - } - - if let Some(name) = symbol.name() { - try!(write!(fmt, " - {}", name)); - } else { - try!(write!(fmt, " - ")); - } - - if let (Some(file), Some(line)) = (symbol.filename(), symbol.lineno()) { - try!(write!(fmt, "\n {:3$}at {}:{}", "", file.display(), line, hex_width)); - } - } - } - - Ok(()) - } -} - -impl Default for Backtrace { - fn default() -> Backtrace { - Backtrace::new() - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/dylib.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/dylib.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/dylib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/dylib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,70 +0,0 @@ -use std::ffi::CString; -use std::marker; -use std::mem; -use std::sync::atomic::{AtomicUsize, Ordering}; - -use libc::{self, c_char, c_void}; - -pub struct Dylib { - pub init: AtomicUsize, -} - -pub struct Symbol { - pub name: &'static str, - pub addr: AtomicUsize, - pub _marker: marker::PhantomData, -} - -impl Dylib { - pub unsafe fn get<'a, T>(&self, sym: &'a Symbol) -> Option<&'a T> { - self.load().and_then(|handle| { - sym.get(handle) - }) - } - - pub unsafe fn init(&self, path: &str) -> bool { - if self.init.load(Ordering::SeqCst) != 0 { - return true - } - let name = CString::new(path).unwrap(); - let ptr = libc::dlopen(name.as_ptr() as *const c_char, libc::RTLD_LAZY); - if ptr.is_null() { - return false - } - match self.init.compare_and_swap(0, ptr as usize, Ordering::SeqCst) { - 0 => {} - _ => { libc::dlclose(ptr); } - } - return true - } - - unsafe fn load(&self) -> Option<*mut c_void> { - match self.init.load(Ordering::SeqCst) { - 0 => None, - n => Some(n as *mut c_void), - } - } -} - -impl Symbol { - unsafe fn get(&self, handle: *mut c_void) -> Option<&T> { - assert_eq!(mem::size_of::(), mem::size_of_val(&self.addr)); - if self.addr.load(Ordering::SeqCst) == 0 { - self.addr.store(fetch(handle, self.name.as_ptr()), Ordering::SeqCst) - } - if self.addr.load(Ordering::SeqCst) == 1 { - None - } else { - mem::transmute::<&AtomicUsize, Option<&T>>(&self.addr) - } - } -} - -unsafe fn fetch(handle: *mut c_void, name: *const u8) -> usize { - let ptr = libc::dlsym(handle, name as *const _); - if ptr.is_null() { - 1 - } else { - ptr as usize - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/lib.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/lib.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,177 +0,0 @@ -//! A library for acquiring a backtrace at runtime -//! -//! This library is meant to supplement the `RUST_BACKTRACE=1` support of the -//! standard library by allowing an acquisition of a backtrace at runtime -//! programmatically. The backtraces generated by this library do not need to be -//! parsed, for example, and expose the functionality of multiple backend -//! implementations. -//! -//! # Implementation -//! -//! This library makes use of a number of strategies for actually acquiring a -//! backtrace. For example unix uses libgcc's libunwind bindings by default to -//! acquire a backtrace, but coresymbolication or dladdr is used on OSX to -//! acquire symbol names while linux uses gcc's libbacktrace. -//! -//! When using the default feature set of this library the "most reasonable" set -//! of defaults is chosen for the current platform, but the features activated -//! can also be controlled at a finer granularity. -//! -//! # Platform Support -//! -//! Currently this library is verified to work on Linux, OSX, and Windows, but -//! it may work on other platforms as well. Note that the quality of the -//! backtrace may vary across platforms. -//! -//! # API Principles -//! -//! This library attempts to be as flexible as possible to accommodate different -//! backend implementations of acquiring a backtrace. Consequently the currently -//! exported functions are closure-based as opposed to the likely expected -//! iterator-based versions. This is done due to limitations of the underlying -//! APIs used from the system. -//! -//! # Usage -//! -//! First, add this to your Cargo.toml -//! -//! ```toml -//! [dependencies] -//! backtrace = "0.2" -//! ``` -//! -//! Next: -//! -//! ``` -//! extern crate backtrace; -//! -//! fn main() { -//! backtrace::trace(|frame| { -//! let ip = frame.ip(); -//! let symbol_address = frame.symbol_address(); -//! -//! // Resolve this instruction pointer to a symbol name -//! backtrace::resolve(ip, |symbol| { -//! if let Some(name) = symbol.name() { -//! // ... -//! } -//! if let Some(filename) = symbol.filename() { -//! // ... -//! } -//! }); -//! -//! true // keep going to the next frame -//! }); -//! } -//! ``` - -#![doc(html_root_url = "http://alexcrichton.com/backtrace-rs")] -#![deny(missing_docs)] -#![deny(warnings)] - -#[cfg(unix)] -extern crate libc; -#[cfg(all(windows, feature = "winapi"))] extern crate winapi; - -#[cfg(feature = "serde_derive")] -#[cfg_attr(feature = "serde_derive", macro_use)] -extern crate serde_derive; - -#[cfg(feature = "rustc-serialize")] -extern crate rustc_serialize; - -#[macro_use] -extern crate cfg_if; - -extern crate rustc_demangle; - -#[cfg(feature = "cpp_demangle")] -extern crate cpp_demangle; - -#[cfg(all(feature = "gimli-symbolize", - unix, - target_os = "linux"))] -extern crate addr2line; -#[cfg(all(feature = "gimli-symbolize", - unix, - target_os = "linux"))] -extern crate findshlibs; - -#[allow(dead_code)] // not used everywhere -#[cfg(unix)] -#[macro_use] -mod dylib; - -pub use backtrace::{trace, Frame}; -mod backtrace; - -pub use symbolize::{resolve, Symbol, SymbolName}; -mod symbolize; - -pub use capture::{Backtrace, BacktraceFrame, BacktraceSymbol}; -mod capture; - -#[allow(dead_code)] -struct Bomb { - enabled: bool, -} - -#[allow(dead_code)] -impl Drop for Bomb { - fn drop(&mut self) { - if self.enabled { - panic!("cannot panic during the backtrace function"); - } - } -} - -#[allow(dead_code)] -mod lock { - use std::cell::Cell; - use std::mem; - use std::sync::{Once, Mutex, MutexGuard, ONCE_INIT}; - - pub struct LockGuard(MutexGuard<'static, ()>); - - static mut LOCK: *mut Mutex<()> = 0 as *mut _; - static INIT: Once = ONCE_INIT; - thread_local!(static LOCK_HELD: Cell = Cell::new(false)); - - impl Drop for LockGuard { - fn drop(&mut self) { - LOCK_HELD.with(|slot| { - assert!(slot.get()); - slot.set(false); - }); - } - } - - pub fn lock() -> Option { - if LOCK_HELD.with(|l| l.get()) { - return None - } - LOCK_HELD.with(|s| s.set(true)); - unsafe { - INIT.call_once(|| { - LOCK = mem::transmute(Box::new(Mutex::new(()))); - }); - Some(LockGuard((*LOCK).lock().unwrap())) - } - } -} - -// requires external synchronization -#[cfg(all(windows, feature = "dbghelp"))] -unsafe fn dbghelp_init() { - use winapi::shared::minwindef; - use winapi::um::{dbghelp, processthreadsapi}; - - static mut INITIALIZED: bool = false; - - if !INITIALIZED { - dbghelp::SymInitializeW(processthreadsapi::GetCurrentProcess(), - 0 as *mut _, - minwindef::TRUE); - INITIALIZED = true; - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/coresymbolication.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/coresymbolication.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/coresymbolication.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/coresymbolication.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,192 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(bad_style)] - -use std::ffi::{CStr, OsStr}; -use std::mem; -use std::os::raw::{c_void, c_char, c_int}; -use std::os::unix::prelude::*; -use std::path::Path; -use std::ptr; -use std::sync::atomic::ATOMIC_USIZE_INIT; - -use libc::{self, Dl_info}; - -use SymbolName; -use dylib::Dylib; -use dylib::Symbol as DylibSymbol; - -#[repr(C)] -#[derive(Copy, Clone, PartialEq)] -pub struct CSTypeRef { - cpp_data: *const c_void, - cpp_obj: *const c_void -} - -const CS_NOW: u64 = 0x80000000; -const CSREF_NULL: CSTypeRef = CSTypeRef { - cpp_data: 0 as *const c_void, - cpp_obj: 0 as *const c_void, -}; - -pub enum Symbol { - Core { - path: *const c_char, - lineno: u32, - name: *const c_char, - addr: *mut c_void, - }, - Dladdr(Dl_info), -} - -impl Symbol { - pub fn name(&self) -> Option { - let name = match *self { - Symbol::Core { name, .. } => name, - Symbol::Dladdr(ref info) => info.dli_sname, - }; - if name.is_null() { - None - } else { - Some(SymbolName::new(unsafe { - CStr::from_ptr(name).to_bytes() - })) - } - } - - pub fn addr(&self) -> Option<*mut c_void> { - match *self { - Symbol::Core { addr, .. } => Some(addr), - Symbol::Dladdr(ref info) => Some(info.dli_saddr as *mut _), - } - } - - pub fn filename(&self) -> Option<&Path> { - match *self { - Symbol::Core { path, .. } => { - if path.is_null() { - None - } else { - Some(Path::new(OsStr::from_bytes(unsafe { - CStr::from_ptr(path).to_bytes() - }))) - } - } - Symbol::Dladdr(_) => None, - } - } - - pub fn lineno(&self) -> Option { - match *self { - Symbol::Core { lineno: 0, .. } => None, - Symbol::Core { lineno, .. } => Some(lineno), - Symbol::Dladdr(_) => None, - } - } -} - -static CORESYMBOLICATION: Dylib = Dylib { init: ATOMIC_USIZE_INIT }; - -macro_rules! dlsym { - (extern { - $(fn $name:ident($($arg:ident: $t:ty),*) -> $ret:ty;)* - }) => ($( - static $name: ::dylib::Symbol $ret> = - ::dylib::Symbol { - name: concat!(stringify!($name), "\0"), - addr: ::std::sync::atomic::ATOMIC_USIZE_INIT, - _marker: ::std::marker::PhantomData, - }; - )*) -} - -dlsym! { - extern { - fn CSSymbolicatorCreateWithPid(pid: c_int) -> CSTypeRef; - fn CSRelease(rf: CSTypeRef) -> c_void; - fn CSSymbolicatorGetSymbolWithAddressAtTime( - cs: CSTypeRef, addr: *const c_void, time: u64) -> CSTypeRef; - fn CSSymbolicatorGetSourceInfoWithAddressAtTime( - cs: CSTypeRef, addr: *const c_void, time: u64) -> CSTypeRef; - fn CSSourceInfoGetLineNumber(info: CSTypeRef) -> c_int; - fn CSSourceInfoGetPath(info: CSTypeRef) -> *const c_char; - fn CSSourceInfoGetSymbol(info: CSTypeRef) -> CSTypeRef; - fn CSSymbolGetName(sym: CSTypeRef) -> *const c_char; - fn CSSymbolGetSymbolOwner(sym: CSTypeRef) -> CSTypeRef; - fn CSSymbolOwnerGetBaseAddress(symowner: CSTypeRef) -> *mut c_void; - } -} - -unsafe fn get(sym: &DylibSymbol) -> &T { - CORESYMBOLICATION.get(sym).unwrap() -} - -unsafe fn try_resolve(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) -> bool { - let path = "/System/Library/PrivateFrameworks/CoreSymbolication.framework\ - /Versions/A/CoreSymbolication"; - if !CORESYMBOLICATION.init(path) { - return false; - } - - let cs = get(&CSSymbolicatorCreateWithPid)(libc::getpid()); - if cs == CSREF_NULL { - return false - } - - let info = get(&CSSymbolicatorGetSourceInfoWithAddressAtTime)( - cs, addr, CS_NOW); - let sym = if info == CSREF_NULL { - get(&CSSymbolicatorGetSymbolWithAddressAtTime)(cs, addr, CS_NOW) - } else { - get(&CSSourceInfoGetSymbol)(info) - }; - - let mut rv = false; - if sym != CSREF_NULL { - let owner = get(&CSSymbolGetSymbolOwner)(sym); - if owner != CSREF_NULL { - cb(&super::Symbol { - inner: Symbol::Core { - path: if info != CSREF_NULL { - get(&CSSourceInfoGetPath)(info) - } else { - ptr::null() - }, - lineno: if info != CSREF_NULL { - get(&CSSourceInfoGetLineNumber)(info) as u32 - } else { - 0 - }, - name: get(&CSSymbolGetName)(sym), - addr: get(&CSSymbolOwnerGetBaseAddress)(owner), - }, - }); - rv = true; - } - } - get(&CSRelease)(cs); - - rv -} - -pub fn resolve(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) { - unsafe { - if try_resolve(addr, cb) { - return - } - let mut info: Dl_info = mem::zeroed(); - if libc::dladdr(addr as *mut _, &mut info) != 0 { - cb(&super::Symbol { - inner: Symbol::Dladdr(info), - }); - } - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/dbghelp.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/dbghelp.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/dbghelp.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/dbghelp.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,118 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(bad_style)] - -use std::ffi::OsString; -use std::mem; -use std::path::Path; -use std::os::windows::prelude::*; -use std::slice; -use winapi::ctypes::*; -use winapi::shared::basetsd::*; -use winapi::shared::minwindef::*; -use winapi::um::processthreadsapi; -use winapi::um::dbghelp; -use winapi::um::dbghelp::*; - -use SymbolName; - -pub struct Symbol { - name: OsString, - addr: *mut c_void, - line: Option, - filename: Option, -} - -impl Symbol { - pub fn name(&self) -> Option { - self.name.to_str().map(|s| SymbolName::new(s.as_bytes())) - } - - pub fn addr(&self) -> Option<*mut c_void> { - Some(self.addr as *mut _) - } - - pub fn filename(&self) -> Option<&Path> { - self.filename.as_ref().map(Path::new) - } - - pub fn lineno(&self) -> Option { - self.line - } -} - -pub fn resolve(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) { - // According to windows documentation, all dbghelp functions are - // single-threaded. - let _g = ::lock::lock(); - - unsafe { - let size = 2 * MAX_SYM_NAME + mem::size_of::(); - let mut data = vec![0u8; size]; - let info = &mut *(data.as_mut_ptr() as *mut SYMBOL_INFOW); - info.MaxNameLen = MAX_SYM_NAME as ULONG; - // the struct size in C. the value is different to - // `size_of::() - MAX_SYM_NAME + 1` (== 81) - // due to struct alignment. - info.SizeOfStruct = 88; - - let _c = ::dbghelp_init(); - - let mut displacement = 0u64; - let ret = dbghelp::SymFromAddrW(processthreadsapi::GetCurrentProcess(), - addr as DWORD64, - &mut displacement, - info); - if ret != TRUE { - return - } - - // If the symbol name is greater than MaxNameLen, SymFromAddrW will - // give a buffer of (MaxNameLen - 1) characters and set NameLen to - // the real value. - let name_len = ::std::cmp::min(info.NameLen as usize, - info.MaxNameLen as usize - 1); - - let name = slice::from_raw_parts(info.Name.as_ptr() as *const u16, - name_len); - let name = OsString::from_wide(name); - - let mut line = mem::zeroed::(); - line.SizeOfStruct = mem::size_of::() as DWORD; - let mut displacement = 0; - let ret = dbghelp::SymGetLineFromAddrW64(processthreadsapi::GetCurrentProcess(), - addr as DWORD64, - &mut displacement, - &mut line); - let mut filename = None; - let mut lineno = None; - if ret == TRUE { - lineno = Some(line.LineNumber as u32); - - let base = line.FileName; - let mut len = 0; - while *base.offset(len) != 0 { - len += 1; - } - let name = slice::from_raw_parts(base, len as usize); - filename = Some(OsString::from_wide(name)); - } - - cb(&super::Symbol { - inner: Symbol { - name: name, - addr: info.Address as *mut _, - line: lineno, - filename: filename, - }, - }) - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/dladdr.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/dladdr.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/dladdr.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/dladdr.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::ffi::CStr; -use std::mem; -use std::os::raw::c_void; -use std::path::Path; - -use libc::{self, Dl_info}; - -use SymbolName; - -pub struct Symbol { - inner: Dl_info, -} - -impl Symbol { - pub fn name(&self) -> Option { - if self.inner.dli_sname.is_null() { - None - } else { - Some(SymbolName::new(unsafe { - CStr::from_ptr(self.inner.dli_sname).to_bytes() - })) - } - } - - pub fn addr(&self) -> Option<*mut c_void> { - Some(self.inner.dli_saddr as *mut _) - } - - pub fn filename(&self) -> Option<&Path> { - None - } - - pub fn lineno(&self) -> Option { - None - } -} - -pub fn resolve(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) { - unsafe { - let mut info: super::Symbol = super::Symbol { - inner: Symbol { - inner: mem::zeroed(), - }, - }; - if libc::dladdr(addr as *mut _, &mut info.inner.inner) != 0 { - cb(&info) - } - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/gimli.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/gimli.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/gimli.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/gimli.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,170 +0,0 @@ -use addr2line; -use findshlibs::{self, Segment, SharedLibrary}; -use std::cell::RefCell; -use std::env; -use std::os::raw::c_void; -use std::path::{Path, PathBuf}; -use std::u32; - -use SymbolName; - -const MAPPINGS_CACHE_SIZE: usize = 4; - -thread_local! { - // A very small, very simple LRU cache for debug info mappings. - // - // The hit rate should be very high, since the typical stack doesn't cross - // between many shared libraries. - // - // The `addr2line::Mapping` structures are pretty expensive to create. Its - // cost is expected to be amortized by subsequent `locate` queries, which - // leverage the structures built when constructing `addr2line::Mapping`s to - // get nice speedups. If we didn't have this cache, that amortization would - // never happen, and symbolicating backtraces would be ssssllllooooowwww. - static MAPPINGS_CACHE: RefCell> - = RefCell::new(Vec::with_capacity(MAPPINGS_CACHE_SIZE)); -} - -fn with_mapping_for_path(path: PathBuf, mut f: F) -where - F: FnMut(&mut addr2line::Mapping) -{ - MAPPINGS_CACHE.with(|cache| { - let mut cache = cache.borrow_mut(); - - let idx = cache.iter().position(|&(ref p, _)| p == &path); - - // Invariant: after this conditional completes without early returning - // from an error, the cache entry for this path is at index 0. - - if let Some(idx) = idx { - // When the mapping is already in the cache, move it to the front. - if idx != 0 { - let entry = cache.remove(idx); - cache.insert(0, entry); - } - } else { - // When the mapping is not in the cache, create a new mapping, - // insert it into the front of the cache, and evict the oldest cache - // entry if necessary. - let opts = addr2line::Options::default() - .with_functions(); - - let mapping = match opts.build(&path) { - Err(_) => return, - Ok(m) => m, - }; - - if cache.len() == MAPPINGS_CACHE_SIZE { - cache.pop(); - } - - cache.insert(0, (path, mapping)); - } - - f(&mut cache[0].1); - }); -} - -pub fn resolve(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) { - // First, find the file containing the segment that the given AVMA (after - // relocation) address falls within. Use the containing segment to compute - // the SVMA (before relocation) address. - // - // Note that the OS APIs that `SharedLibrary::each` is implemented with hold - // a lock for the duration of the `each` call, so we want to keep this - // section as short as possible to avoid contention with other threads - // capturing backtraces. - let addr = findshlibs::Avma(addr as *mut u8 as *const u8); - let mut so_info = None; - findshlibs::TargetSharedLibrary::each(|so| { - use findshlibs::IterationControl::*; - - for segment in so.segments() { - if segment.contains_avma(so, addr) { - let addr = so.avma_to_svma(addr); - let path = so.name().to_string_lossy(); - so_info = Some((addr, path.to_string())); - return Break; - } - } - - Continue - }); - let (addr, path) = match so_info { - None => return, - Some((a, p)) => (a, p), - }; - - // Second, fixup the path. Empty path means that this address falls within - // the main executable, not a shared library. - let path = if path.is_empty() { - match env::current_exe() { - Err(_) => return, - Ok(p) => p, - } - } else { - PathBuf::from(path) - }; - - // Finally, get a cached mapping or create a new mapping for this file, and - // evaluate the DWARF info to find the file/line/name for this address. - with_mapping_for_path(path, |mapping| { - let (file, line, func) = match mapping.locate(addr.0 as u64) { - Ok(None) | Err(_) => return, - Ok(Some((file, line, func))) => (file, line, func), - }; - - let sym = super::Symbol { - inner: Symbol::new(addr.0 as usize, - file, - line, - func.map(|f| f.to_string())) - }; - - cb(&sym); - }); -} - -pub struct Symbol { - addr: usize, - file: PathBuf, - line: Option, - name: Option, -} - -impl Symbol { - fn new(addr: usize, - file: PathBuf, - line: Option, - name: Option) - -> Symbol { - Symbol { - addr, - file, - line, - name, - } - } - - pub fn name(&self) -> Option { - self.name.as_ref().map(|s| SymbolName::new(s.as_bytes())) - } - - pub fn addr(&self) -> Option<*mut c_void> { - Some(self.addr as *mut c_void) - } - - pub fn filename(&self) -> Option<&Path> { - Some(self.file.as_ref()) - } - - pub fn lineno(&self) -> Option { - self.line - .and_then(|l| if l > (u32::MAX as u64) { - None - } else { - Some(l as u32) - }) - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/libbacktrace.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/libbacktrace.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/libbacktrace.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/libbacktrace.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,180 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(bad_style)] - -extern crate backtrace_sys as bt; - -use libc::uintptr_t; -use std::ffi::{CStr, OsStr}; -use std::os::raw::{c_void, c_char, c_int}; -use std::os::unix::prelude::*; -use std::path::Path; -use std::ptr; -use std::sync::{ONCE_INIT, Once}; - -use SymbolName; - -pub enum Symbol { - Syminfo { - pc: uintptr_t, - symname: *const c_char, - }, - Pcinfo { - pc: uintptr_t, - filename: *const c_char, - lineno: c_int, - function: *const c_char, - }, -} - -impl Symbol { - pub fn name(&self) -> Option { - let ptr = match *self { - Symbol::Syminfo { symname, .. } => symname, - Symbol::Pcinfo { function, .. } => function, - }; - if ptr.is_null() { - None - } else { - Some(SymbolName::new(unsafe { CStr::from_ptr(ptr).to_bytes() })) - } - } - - pub fn addr(&self) -> Option<*mut c_void> { - let pc = match *self { - Symbol::Syminfo { pc, .. } => pc, - Symbol::Pcinfo { pc, .. } => pc, - }; - if pc == 0 {None} else {Some(pc as *mut _)} - } - - pub fn filename(&self) -> Option<&Path> { - match *self { - Symbol::Syminfo { .. } => None, - Symbol::Pcinfo { filename, .. } => { - Some(Path::new(OsStr::from_bytes(unsafe { - CStr::from_ptr(filename).to_bytes() - }))) - } - } - } - - pub fn lineno(&self) -> Option { - match *self { - Symbol::Syminfo { .. } => None, - Symbol::Pcinfo { lineno, .. } => Some(lineno as u32), - } - } -} - -extern fn error_cb(_data: *mut c_void, _msg: *const c_char, - _errnum: c_int) { - // do nothing for now -} - -extern fn syminfo_cb(data: *mut c_void, - pc: uintptr_t, - symname: *const c_char, - _symval: uintptr_t, - _symsize: uintptr_t) { - unsafe { - call(data, &super::Symbol { - inner: Symbol::Syminfo { - pc: pc, - symname: symname, - }, - }); - } -} - -extern fn pcinfo_cb(data: *mut c_void, - pc: uintptr_t, - filename: *const c_char, - lineno: c_int, - function: *const c_char) -> c_int { - unsafe { - if filename.is_null() || function.is_null() { - return -1 - } - call(data, &super::Symbol { - inner: Symbol::Pcinfo { - pc: pc, - filename: filename, - lineno: lineno, - function: function, - }, - }); - return 0 - } -} - -unsafe fn call(data: *mut c_void, sym: &super::Symbol) { - let cb = data as *mut &mut FnMut(&super::Symbol); - let mut bomb = ::Bomb { enabled: true }; - (*cb)(sym); - bomb.enabled = false; -} - -// The libbacktrace API supports creating a state, but it does not -// support destroying a state. I personally take this to mean that a -// state is meant to be created and then live forever. -// -// I would love to register an at_exit() handler which cleans up this -// state, but libbacktrace provides no way to do so. -// -// With these constraints, this function has a statically cached state -// that is calculated the first time this is requested. Remember that -// backtracing all happens serially (one global lock). -// -// Things don't work so well on not-Linux since libbacktrace can't track down -// that executable this is. We at one point used env::current_exe but it turns -// out that there are some serious security issues with that approach. -// -// Specifically, on certain platforms like BSDs, a malicious actor can cause an -// arbitrary file to be placed at the path returned by current_exe. libbacktrace -// does not behave defensively in the presence of ill-formed DWARF information, -// and has been demonstrated to segfault in at least one case. There is no -// evidence at the moment to suggest that a more carefully constructed file -// can't cause arbitrary code execution. As a result of all of this, we don't -// hint libbacktrace with the path to the current process. -unsafe fn init_state() -> *mut bt::backtrace_state { - static mut STATE: *mut bt::backtrace_state = 0 as *mut _; - static INIT: Once = ONCE_INIT; - INIT.call_once(|| { - // Our libbacktrace may not have multithreading support, so - // set `threaded = 0` and synchronize ourselves. - STATE = bt::backtrace_create_state(ptr::null(), 0, error_cb, - ptr::null_mut()); - }); - - STATE -} - -pub fn resolve(symaddr: *mut c_void, mut cb: &mut FnMut(&super::Symbol)) { - let _guard = ::lock::lock(); - - // backtrace errors are currently swept under the rug - unsafe { - let state = init_state(); - if state.is_null() { - return - } - - let ret = bt::backtrace_pcinfo(state, symaddr as uintptr_t, - pcinfo_cb, error_cb, - &mut cb as *mut _ as *mut _); - if ret != 0 { - bt::backtrace_syminfo(state, symaddr as uintptr_t, - syminfo_cb, error_cb, - &mut cb as *mut _ as *mut _); - } - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/mod.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/mod.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,290 +0,0 @@ -use std::fmt; -#[cfg(not(feature = "cpp_demangle"))] -use std::marker::PhantomData; -use std::os::raw::c_void; -use std::path::Path; -use std::str; -use rustc_demangle::{try_demangle, Demangle}; - -/// Resolve an address to a symbol, passing the symbol to the specified -/// closure. -/// -/// This function will look up the given address in areas such as the local -/// symbol table, dynamic symbol table, or DWARF debug info (depending on the -/// activated implementation) to find symbols to yield. -/// -/// The closure may not be called if resolution could not be performed, and it -/// also may be called more than once in the case of inlined functions. -/// -/// Symbols yielded represent the execution at the specified `addr`, returning -/// file/line pairs for that address (if available). -/// -/// # Example -/// -/// ``` -/// extern crate backtrace; -/// -/// fn main() { -/// backtrace::trace(|frame| { -/// let ip = frame.ip(); -/// -/// backtrace::resolve(ip, |symbol| { -/// // ... -/// }); -/// -/// false // only look at the top frame -/// }); -/// } -/// ``` -pub fn resolve(addr: *mut c_void, mut cb: F) { - resolve_imp(addr, &mut cb) -} - -/// A trait representing the resolution of a symbol in a file. -/// -/// This trait is yielded as a trait object to the closure given to the -/// `backtrace::resolve` function, and it is virtually dispatched as it's -/// unknown which implementation is behind it. -/// -/// A symbol can give contextual information about a function, for example the -/// name, filename, line number, precise address, etc. Not all information is -/// always available in a symbol, however, so all methods return an `Option`. -pub struct Symbol { - inner: SymbolImp, -} - -impl Symbol { - /// Returns the name of this function. - /// - /// The returned structure can be used to query various properties about the - /// symbol name: - /// - /// * The `Display` implementation will print out the demangled symbol. - /// * The raw `str` value of the symbol can be accessed (if it's valid - /// utf-8). - /// * The raw bytes for the symbol name can be accessed. - pub fn name(&self) -> Option { - self.inner.name() - } - - /// Returns the starting address of this function. - pub fn addr(&self) -> Option<*mut c_void> { - self.inner.addr() - } - - /// Returns the file name where this function was defined. - /// - /// This is currently only available when libbacktrace is being used (e.g. - /// unix platforms other than OSX) and when a binary is compiled with - /// debuginfo. If neither of these conditions is met then this will likely - /// return `None`. - pub fn filename(&self) -> Option<&Path> { - self.inner.filename() - } - - /// Returns the line number for where this symbol is currently executing. - /// - /// This return value is typically `Some` if `filename` returns `Some`, and - /// is consequently subject to similar caveats. - pub fn lineno(&self) -> Option { - self.inner.lineno() - } -} - -impl fmt::Debug for Symbol { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut d = f.debug_struct("Symbol"); - if let Some(name) = self.name() { - d.field("name", &name); - } - if let Some(addr) = self.addr() { - d.field("addr", &addr); - } - if let Some(filename) = self.filename() { - d.field("filename", &filename); - } - if let Some(lineno) = self.lineno() { - d.field("lineno", &lineno); - } - d.finish() - } -} - - -cfg_if! { - if #[cfg(feature = "cpp_demangle")] { - // Maybe a parsed C++ symbol, if parsing the mangled symbol as Rust - // failed. - struct OptionCppSymbol<'a>(Option<::cpp_demangle::BorrowedSymbol<'a>>); - - impl<'a> OptionCppSymbol<'a> { - fn parse(input: &'a [u8]) -> OptionCppSymbol<'a> { - OptionCppSymbol(::cpp_demangle::BorrowedSymbol::new(input).ok()) - } - - fn none() -> OptionCppSymbol<'a> { - OptionCppSymbol(None) - } - } - } else { - // Make sure to keep this zero-sized, so that the `cpp_demangle` feature - // has no cost when disabled. - struct OptionCppSymbol<'a>(PhantomData<&'a ()>); - - impl<'a> OptionCppSymbol<'a> { - fn parse(_: &'a [u8]) -> OptionCppSymbol<'a> { - OptionCppSymbol(PhantomData) - } - - fn none() -> OptionCppSymbol<'a> { - OptionCppSymbol(PhantomData) - } - } - } -} - -/// A wrapper around a symbol name to provide ergonomic accessors to the -/// demangled name, the raw bytes, the raw string, etc. -// Allow dead code for when the `cpp_demangle` feature is not enabled. -#[allow(dead_code)] -pub struct SymbolName<'a> { - bytes: &'a [u8], - demangled: Option>, - cpp_demangled: OptionCppSymbol<'a>, -} - -impl<'a> SymbolName<'a> { - /// Creates a new symbol name from the raw underlying bytes. - pub fn new(bytes: &'a [u8]) -> SymbolName<'a> { - let str_bytes = str::from_utf8(bytes).ok(); - let demangled = str_bytes.and_then(|s| try_demangle(s).ok()); - - let cpp = if demangled.is_none() { - OptionCppSymbol::parse(bytes) - } else { - OptionCppSymbol::none() - }; - - SymbolName { - bytes: bytes, - demangled: demangled, - cpp_demangled: cpp, - } - } - - /// Returns the raw symbol name as a `str` if the symbols is valid utf-8. - pub fn as_str(&self) -> Option<&'a str> { - self.demangled - .as_ref() - .map(|s| s.as_str()) - .or_else(|| { - str::from_utf8(self.bytes).ok() - }) - } - - /// Returns the raw symbol name as a list of bytes - pub fn as_bytes(&self) -> &'a [u8] { - self.bytes - } -} - -cfg_if! { - if #[cfg(feature = "cpp_demangle")] { - impl<'a> fmt::Display for SymbolName<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if let Some(ref s) = self.demangled { - s.fmt(f) - } else if let Some(ref cpp) = self.cpp_demangled.0 { - cpp.fmt(f) - } else { - String::from_utf8_lossy(self.bytes).fmt(f) - } - } - } - } else { - impl<'a> fmt::Display for SymbolName<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if let Some(ref s) = self.demangled { - s.fmt(f) - } else { - String::from_utf8_lossy(self.bytes).fmt(f) - } - } - } - } -} - -cfg_if! { - if #[cfg(feature = "cpp_demangle")] { - impl<'a> fmt::Debug for SymbolName<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use std::fmt::Write; - - if let Some(ref s) = self.demangled { - return s.fmt(f) - } - - // This may to print if the demangled symbol isn't actually - // valid, so handle the error here gracefully by not propagating - // it outwards. - if let Some(ref cpp) = self.cpp_demangled.0 { - let mut s = String::new(); - if write!(s, "{}", cpp).is_ok() { - return s.fmt(f) - } - } - - String::from_utf8_lossy(self.bytes).fmt(f) - } - } - } else { - impl<'a> fmt::Debug for SymbolName<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if let Some(ref s) = self.demangled { - s.fmt(f) - } else { - String::from_utf8_lossy(self.bytes).fmt(f) - } - } - } - } -} - -cfg_if! { - if #[cfg(all(windows, feature = "dbghelp"))] { - mod dbghelp; - use self::dbghelp::resolve as resolve_imp; - use self::dbghelp::Symbol as SymbolImp; - } else if #[cfg(all(feature = "gimli-symbolize", - unix, - target_os = "linux"))] { - mod gimli; - use self::gimli::resolve as resolve_imp; - use self::gimli::Symbol as SymbolImp; - } else if #[cfg(all(feature = "libbacktrace", - unix, - not(target_os = "fuchsia"), - not(target_os = "emscripten"), - not(target_os = "macos"), - not(target_os = "ios")))] { - mod libbacktrace; - use self::libbacktrace::resolve as resolve_imp; - use self::libbacktrace::Symbol as SymbolImp; - } else if #[cfg(all(feature = "coresymbolication", - any(target_os = "macos", - target_os = "ios")))] { - mod coresymbolication; - use self::coresymbolication::resolve as resolve_imp; - use self::coresymbolication::Symbol as SymbolImp; - } else if #[cfg(all(unix, - not(target_os = "emscripten"), - feature = "dladdr"))] { - mod dladdr; - use self::dladdr::resolve as resolve_imp; - use self::dladdr::Symbol as SymbolImp; - } else { - mod noop; - use self::noop::resolve as resolve_imp; - use self::noop::Symbol as SymbolImp; - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/noop.rs cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/noop.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/src/symbolize/noop.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/src/symbolize/noop.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -use std::path::Path; -use std::os::raw::c_void; - -use SymbolName; - -pub fn resolve(_addr: *mut c_void, _cb: &mut FnMut(&super::Symbol)) { -} - -pub struct Symbol; - -impl Symbol { - pub fn name(&self) -> Option { - None - } - - pub fn addr(&self) -> Option<*mut c_void> { - None - } - - pub fn filename(&self) -> Option<&Path> { - None - } - - pub fn lineno(&self) -> Option { - None - } -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/tests/long_fn_name.rs cargo-0.26.0/vendor/backtrace-0.3.5/tests/long_fn_name.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/tests/long_fn_name.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/tests/long_fn_name.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -extern crate backtrace; - -#[cfg(all(windows, feature = "dbghelp"))] -extern crate winapi; - -use backtrace::Backtrace; - -// 50-character module name -mod _234567890_234567890_234567890_234567890_234567890 { - // 50-character struct name - #[allow(non_camel_case_types)] - pub struct _234567890_234567890_234567890_234567890_234567890(T); - impl _234567890_234567890_234567890_234567890_234567890 { - #[allow(dead_code)] - pub fn new() -> ::Backtrace { - ::Backtrace::new() - } - } -} - -// Long function names must be truncated to (MAX_SYM_NAME - 1) characters. -// Only run this test for msvc, since gnu prints "" for all frames. -#[test] -#[cfg(all(windows, feature = "dbghelp", target_env = "msvc"))] -fn test_long_fn_name() { - use winapi::um::dbghelp; - use _234567890_234567890_234567890_234567890_234567890:: - _234567890_234567890_234567890_234567890_234567890 as S; - - // 10 repetitions of struct name, so fully qualified function name is - // atleast 10 * (50 + 50) * 2 = 2000 characters long. - // It's actually longer since it also includes `::`, `<>` and the - // name of the current module - let bt = S::>>>>>>>>>::new(); - println!("{:?}", bt); - - let mut found_long_name_frame = false; - - for frame in bt.frames() { - let symbols = frame.symbols(); - if symbols.is_empty() { - continue; - } - - if let Some(function_name) = symbols[0].name() { - let function_name = function_name.as_str().unwrap(); - if function_name.contains( - "::_234567890_234567890_234567890_234567890_234567890") - { - found_long_name_frame = true; - assert_eq!(function_name.len(), dbghelp::MAX_SYM_NAME - 1); - } - } - } - - assert!(found_long_name_frame); -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/tests/smoke.rs cargo-0.26.0/vendor/backtrace-0.3.5/tests/smoke.rs --- cargo-0.25.0/vendor/backtrace-0.3.5/tests/smoke.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/tests/smoke.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,171 +0,0 @@ -extern crate backtrace; - -use std::os::raw::c_void; -use std::thread; - -static LIBUNWIND: bool = cfg!(all(unix, feature = "libunwind")); -static UNIX_BACKTRACE: bool = cfg!(all(unix, feature = "unix-backtrace")); -static LIBBACKTRACE: bool = cfg!(all(unix, feature = "libbacktrace")) && - !cfg!(target_os = "fuchsia") && !cfg!(target_os = "macos") && - !cfg!(target_os = "ios"); -static CORESYMBOLICATION: bool = cfg!(all(any(target_os = "macos", target_os = "ios"), - feature = "coresymbolication")); -static DLADDR: bool = cfg!(all(unix, feature = "dladdr")) && !cfg!(target_os = "fuchsia"); -static DBGHELP: bool = cfg!(all(windows, feature = "dbghelp")); -static MSVC: bool = cfg!(target_env = "msvc"); -static GIMLI_SYMBOLIZE: bool = cfg!(all(feature = "gimli-symbolize", - unix, - target_os = "linux")); - -#[test] -fn smoke_test_frames() { - frame_1(line!()); - #[inline(never)] fn frame_1(start_line: u32) { frame_2(start_line) } - #[inline(never)] fn frame_2(start_line: u32) { frame_3(start_line) } - #[inline(never)] fn frame_3(start_line: u32) { frame_4(start_line) } - #[inline(never)] fn frame_4(start_line: u32) { - let mut v = Vec::new(); - backtrace::trace(|cx| { - v.push((cx.ip(), cx.symbol_address())); - true - }); - - if v.len() < 5 { - assert!(!LIBUNWIND); - assert!(!UNIX_BACKTRACE); - assert!(!DBGHELP); - return - } - - // On 32-bit windows apparently the first frame isn't our backtrace - // frame but it's actually this frame. I'm not entirely sure why, but at - // least it seems consistent? - let o = if cfg!(all(windows, target_pointer_width = "32")) {1} else {0}; - // frame offset 0 is the `backtrace::trace` function, but that's generic - assert_frame(&v, o, 1, frame_4 as usize, "frame_4", - "tests/smoke.rs", start_line + 6); - assert_frame(&v, o, 2, frame_3 as usize, "frame_3", "tests/smoke.rs", - start_line + 3); - assert_frame(&v, o, 3, frame_2 as usize, "frame_2", "tests/smoke.rs", - start_line + 2); - assert_frame(&v, o, 4, frame_1 as usize, "frame_1", "tests/smoke.rs", - start_line + 1); - assert_frame(&v, o, 5, smoke_test_frames as usize, - "smoke_test_frames", "", 0); - } - - fn assert_frame(syms: &[(*mut c_void, *mut c_void)], - offset: usize, - idx: usize, - actual_fn_pointer: usize, - expected_name: &str, - expected_file: &str, - expected_line: u32) { - if offset > idx { return } - let (ip, sym) = syms[idx - offset]; - let ip = ip as usize; - let sym = sym as usize; - assert!(ip >= sym); - assert!(sym >= actual_fn_pointer); - - // windows dbghelp is *quite* liberal (and wrong) in many of its reports - // right now... - if !DBGHELP { - assert!(sym - actual_fn_pointer < 1024); - } - - let mut resolved = 0; - let can_resolve = DLADDR || LIBBACKTRACE || CORESYMBOLICATION || DBGHELP || GIMLI_SYMBOLIZE; - - let mut name = None; - let mut addr = None; - let mut line = None; - let mut file = None; - backtrace::resolve(ip as *mut c_void, |sym| { - resolved += 1; - name = sym.name().map(|v| v.to_string()); - addr = sym.addr(); - line = sym.lineno(); - file = sym.filename().map(|v| v.to_path_buf()); - }); - - // dbghelp doesn't always resolve symbols right now - match resolved { - 0 => return assert!(!can_resolve || DBGHELP), - _ => {} - } - - // * linux dladdr doesn't work (only consults local symbol table) - // * windows dbghelp isn't great for GNU - if can_resolve && - !(cfg!(target_os = "linux") && DLADDR) && - !(DBGHELP && !MSVC) - { - let name = name.expect("didn't find a name"); - assert!(name.contains(expected_name), - "didn't find `{}` in `{}`", expected_name, name); - } - - if can_resolve { - addr.expect("didn't find a symbol"); - } - - if (LIBBACKTRACE || CORESYMBOLICATION || (DBGHELP && MSVC)) && cfg!(debug_assertions) { - let line = line.expect("didn't find a line number"); - let file = file.expect("didn't find a line number"); - if !expected_file.is_empty() { - assert!(file.ends_with(expected_file), - "{:?} didn't end with {:?}", file, expected_file); - } - if expected_line != 0 { - assert!(line == expected_line, - "bad line number on frame for `{}`: {} != {}", - expected_name, line, expected_line); - } - } - } -} - -#[test] -fn many_threads() { - let threads = (0..16).map(|_| { - thread::spawn(|| { - for _ in 0..16 { - backtrace::trace(|frame| { - backtrace::resolve(frame.ip(), |symbol| { - let _s = symbol.name().map(|s| s.to_string()); - }); - true - }); - } - }) - }).collect::>(); - - for t in threads { - t.join().unwrap() - } -} - -#[test] -#[cfg(feature = "rustc-serialize")] -fn is_rustc_serialize() { - extern crate rustc_serialize; - - fn is_encode() {} - fn is_decode() {} - - is_encode::(); - is_decode::(); -} - -#[test] -#[cfg(feature = "serde")] -fn is_serde() { - extern crate serde; - - fn is_serialize() {} - fn is_deserialize() {} - - is_serialize::(); - is_deserialize::(); -} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.5/.travis.yml cargo-0.26.0/vendor/backtrace-0.3.5/.travis.yml --- cargo-0.25.0/vendor/backtrace-0.3.5/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.5/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -language: rust -sudo: false - -matrix: - include: - - rust: 1.21.0 - - rust: stable - - os: osx - - rust: beta - - rust: nightly - - - rust: nightly - before_script: - - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH - script: - - cargo doc --no-deps --all-features - after_success: - - travis-cargo --only nightly doc-upload - -dist: trusty - -addons: - sources: - # Provides clang-3.9 - - llvm-toolchain-trusty-3.9 - apt: - packages: - # Required for `bindgen`, which is required by `findshlibs`, which is - # required by the `gimli` feature. - - clang-3.9 - -script: - - cargo test - - cargo test --no-default-features - - cargo test --no-default-features --features 'libunwind' - - cargo test --no-default-features --features 'libunwind dladdr' - - cargo test --no-default-features --features 'libunwind libbacktrace' - - cargo test --no-default-features --features 'unix-backtrace' - - cargo test --no-default-features --features 'unix-backtrace dladdr' - - cargo test --no-default-features --features 'unix-backtrace libbacktrace' - - cargo test --no-default-features --features 'serialize-serde' - - cargo test --no-default-features --features 'serialize-rustc' - - cargo test --no-default-features --features 'serialize-rustc serialize-serde' - - cargo test --no-default-features --features 'cpp_demangle' - - cargo test --no-default-features --features 'gimli-symbolize' - - cd ./cpp_smoke_test && cargo test && cd .. - - cargo clean && cargo build - -notifications: - email: - on_success: never - -after_success: - - travis-cargo --only nightly doc-upload - -env: - global: - # serde-codegen has historically needed a large stack to expand - - RUST_MIN_STACK=16777216 - - secure: "Kuf3j6gC3MhR+F7g8/5J4+3tu+FXJP/SqKjsUVVjs/qjniIVX3MwZPhtP/pVtdRvYjW0NzLw5Nufb4o1cyY4uKwR8BHHNuEUE/h3mPShjWHqzLyn5QiBumPozsFCa32H4gconRmp3+s0YrBT7nLoGvUZZS0dkldMkpvvrPL/yUKXLS8HEP4L1GO5iMQQYG6i3sbWTbHikE6ZQogW/iZommyqUkVB/s/SQvdH9SXu89ttNXlm/F+EIsgsgyzpbULp5sD34GRDPJe+H1m+sgA1kTRrzmuBGNmz9mx6GyIKaqACTm1gRcb06nFjTPVTQioJBNnoV7TEqZCvjuSsUjcGmP4Aeissafo93ADzV+bd0uoWIScE9ltSVS+RgCDV+sd0GHz5U6FjhgZp0amaVl3d6hPp8lbTfK/gfj1i9ktQfKZbG7rB4tfIU1KeQRkyE9vb/TaKp8nwBbc4SVQ4EKFOlRbE1S1FooaKZweW8w57d2u+sMMMVJbO28/Ap8tk9xDSOl4shPaT0iM0U9/heF8FmCZB1OKXLKn6TAaNFnaMTvdTHl+Tjrf6Vzd/oPXJ7GuaB6eLxXYjXvZHuKiLkSZriOzhL7PbijNILbSgZt7+Fa0vcnXP8zgD4dmupx/CoIHLN9NP4o9cGXuBcaJ/iFryJ4i5LKGFNEUHtXkavDrcgcA=" diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/appveyor.yml cargo-0.26.0/vendor/backtrace-0.3.6/appveyor.yml --- cargo-0.25.0/vendor/backtrace-0.3.6/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-gnu + MSYS_BITS: 64 + - TARGET: i686-pc-windows-gnu + MSYS_BITS: 32 + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - set PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - if defined MSYS_BITS set PATH=%PATH%;C:\msys64\mingw%MSYS_BITS%\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --target %TARGET% diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/.cargo-checksum.json cargo-0.26.0/vendor/backtrace-0.3.6/.cargo-checksum.json --- cargo-0.25.0/vendor/backtrace-0.3.6/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"ebbe525f66f42d207968308ee86bc2dd60aa5fab535b22e616323a173d097d8e"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/Cargo.toml cargo-0.26.0/vendor/backtrace-0.3.6/Cargo.toml --- cargo-0.25.0/vendor/backtrace-0.3.6/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,86 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "backtrace" +version = "0.3.6" +authors = ["Alex Crichton ", "The Rust Project Developers"] +description = "A library to acquire a stack trace (backtrace) at runtime in a Rust program.\n" +homepage = "https://github.com/alexcrichton/backtrace-rs" +documentation = "http://alexcrichton.com/backtrace-rs" +readme = "README.md" +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/backtrace-rs" +[dependencies.addr2line] +version = "0.6.0" +optional = true + +[dependencies.cfg-if] +version = "0.1" + +[dependencies.cpp_demangle] +version = "0.2.3" +optional = true +default-features = false + +[dependencies.findshlibs] +version = "0.3.3" +optional = true + +[dependencies.gimli] +version = "0.15.0" +optional = true + +[dependencies.memmap] +version = "0.6.2" +optional = true + +[dependencies.object] +version = "0.7.0" +optional = true + +[dependencies.rustc-demangle] +version = "0.1.4" + +[dependencies.rustc-serialize] +version = "0.3" +optional = true + +[dependencies.serde] +version = "1.0" +optional = true + +[dependencies.serde_derive] +version = "1.0" +optional = true + +[features] +coresymbolication = [] +dbghelp = ["winapi"] +default = ["libunwind", "libbacktrace", "coresymbolication", "dladdr", "dbghelp"] +dladdr = [] +gimli-symbolize = ["addr2line", "findshlibs", "gimli", "memmap", "object"] +kernel32 = [] +libbacktrace = ["backtrace-sys"] +libunwind = [] +serialize-rustc = ["rustc-serialize"] +serialize-serde = ["serde", "serde_derive"] +unix-backtrace = [] +[target."cfg(all(unix, not(target_os = \"fuchsia\"), not(target_os = \"emscripten\"), not(target_os = \"macos\"), not(target_os = \"ios\")))".dependencies.backtrace-sys] +version = "0.1.3" +optional = true +[target."cfg(unix)".dependencies.libc] +version = "0.2" +[target."cfg(windows)".dependencies.winapi] +version = "0.3.3" +features = ["std", "dbghelp", "processthreadsapi", "winnt", "minwindef"] +optional = true diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/examples/backtrace.rs cargo-0.26.0/vendor/backtrace-0.3.6/examples/backtrace.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/examples/backtrace.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/examples/backtrace.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,7 @@ +extern crate backtrace; + +use backtrace::Backtrace; + +fn main() { + println!("{:?}", Backtrace::new()); +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/examples/raw.rs cargo-0.26.0/vendor/backtrace-0.3.6/examples/raw.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/examples/raw.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/examples/raw.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,48 @@ +extern crate backtrace; + +fn main() { + foo(); +} + +fn foo() { bar() } +fn bar() { baz() } +fn baz() { print() } + +#[cfg(target_pointer_width = "32")] const HEX_WIDTH: usize = 10; +#[cfg(target_pointer_width = "64")] const HEX_WIDTH: usize = 20; + +fn print() { + let mut cnt = 0; + backtrace::trace(|frame| { + let ip = frame.ip(); + print!("frame #{:<2} - {:#02$x}", cnt, ip as usize, HEX_WIDTH); + cnt += 1; + + let mut resolved = false; + backtrace::resolve(frame.ip(), |symbol| { + if !resolved { + resolved = true; + } else { + print!("{}", vec![" "; 7 + 2 + 3 + HEX_WIDTH].join("")); + } + + if let Some(name) = symbol.name() { + print!(" - {}", name); + } else { + print!(" - "); + } + if let Some(file) = symbol.filename() { + if let Some(l) = symbol.lineno() { + print!("\n{:13}{:4$}@ {}:{}", "", "", file.display(), l, + HEX_WIDTH); + } + } + println!(""); + + }); + if !resolved { + println!(" - "); + } + true // keep going + }); +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/LICENSE-APACHE cargo-0.26.0/vendor/backtrace-0.3.6/LICENSE-APACHE --- cargo-0.25.0/vendor/backtrace-0.3.6/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/LICENSE-MIT cargo-0.26.0/vendor/backtrace-0.3.6/LICENSE-MIT --- cargo-0.25.0/vendor/backtrace-0.3.6/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +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. diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/README.md cargo-0.26.0/vendor/backtrace-0.3.6/README.md --- cargo-0.25.0/vendor/backtrace-0.3.6/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,91 @@ +# backtrace-rs + +[![Build Status](https://travis-ci.org/alexcrichton/backtrace-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/backtrace-rs) +[![Build status](https://ci.appveyor.com/api/projects/status/v4l9oj4aqbbgyx44?svg=true)](https://ci.appveyor.com/project/alexcrichton/backtrace-rs) + +[Documentation](http://alexcrichton.com/backtrace-rs) + +A library for acquiring backtraces at runtime for Rust. This library aims to +enhance the support given by the standard library at `std::rt` by providing a +more stable and programmatic interface. + +## Install + +```toml +[dependencies] +backtrace = "0.3" +``` + +```rust +extern crate backtrace; +``` + +Note that this crate requires `make`, `objcopy`, and `ar` to be present on Linux +systems. + +## Usage + +To simply capture a backtrace and defer dealing with it until a later time, +you can use the top-level `Backtrace` type. + +```rust +extern crate backtrace; + +use backtrace::Backtrace; + +fn main() { + let bt = Backtrace::new(); + + // do_some_work(); + + println!("{:?}", bt); +} +``` + +If, however, you'd like more raw access to the actual tracing functionality, you +can use the `trace` and `resolve` functions directly. + +```rust +extern crate backtrace; + +fn main() { + backtrace::trace(|frame| { + let ip = frame.ip(); + let symbol_address = frame.symbol_address(); + + // Resolve this instruction pointer to a symbol name + backtrace::resolve(ip, |symbol| { + if let Some(name) = symbol.name() { + // ... + } + if let Some(filename) = symbol.filename() { + // ... + } + }); + + true // keep going to the next frame + }); +} +``` + +## Platform Support + +This library currently supports OSX, Linux, and Windows. Support for other +platforms is always welcome! + +# License + +This project is 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 backtrace-rs by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/backtrace/dbghelp.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/backtrace/dbghelp.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/backtrace/dbghelp.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/backtrace/dbghelp.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,103 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(bad_style)] + +use std::mem; +use winapi::ctypes::*; +use winapi::shared::minwindef::*; +use winapi::um::processthreadsapi; +use winapi::um::winnt::{self, CONTEXT}; +use winapi::um::dbghelp; +use winapi::um::dbghelp::*; + +pub struct Frame { + inner: STACKFRAME64, +} + +impl Frame { + pub fn ip(&self) -> *mut c_void { + self.inner.AddrPC.Offset as *mut _ + } + + pub fn symbol_address(&self) -> *mut c_void { + self.ip() + } +} + +#[inline(always)] +pub fn trace(cb: &mut FnMut(&super::Frame) -> bool) { + // According to windows documentation, all dbghelp functions are + // single-threaded. + let _g = ::lock::lock(); + + unsafe { + // Allocate necessary structures for doing the stack walk + let process = processthreadsapi::GetCurrentProcess(); + let thread = processthreadsapi::GetCurrentThread(); + + // The CONTEXT structure needs to be aligned on a 16-byte boundary for + // 64-bit Windows, but currently we don't have a way to express that in + // Rust. Allocations are generally aligned to 16-bytes, though, so we + // box this up. + let mut context = Box::new(mem::zeroed::()); + winnt::RtlCaptureContext(&mut *context); + let mut frame = super::Frame { + inner: Frame { inner: mem::zeroed() }, + }; + let image = init_frame(&mut frame.inner.inner, &context); + + // Initialize this process's symbols + let _c = ::dbghelp_init(); + + // And now that we're done with all the setup, do the stack walking! + while dbghelp::StackWalk64(image as DWORD, + process, + thread, + &mut frame.inner.inner, + &mut *context as *mut _ as *mut _, + None, + Some(dbghelp::SymFunctionTableAccess64), + Some(dbghelp::SymGetModuleBase64), + None) == TRUE { + if frame.inner.inner.AddrPC.Offset == frame.inner.inner.AddrReturn.Offset || + frame.inner.inner.AddrPC.Offset == 0 || + frame.inner.inner.AddrReturn.Offset == 0 { + break + } + + if !cb(&frame) { + break + } + } + } +} + +#[cfg(target_arch = "x86_64")] +fn init_frame(frame: &mut STACKFRAME64, ctx: &CONTEXT) -> WORD { + frame.AddrPC.Offset = ctx.Rip as u64; + frame.AddrPC.Mode = AddrModeFlat; + frame.AddrStack.Offset = ctx.Rsp as u64; + frame.AddrStack.Mode = AddrModeFlat; + frame.AddrFrame.Offset = ctx.Rbp as u64; + frame.AddrFrame.Mode = AddrModeFlat; + winnt::IMAGE_FILE_MACHINE_AMD64 +} + +#[cfg(target_arch = "x86")] +fn init_frame(frame: &mut STACKFRAME64, ctx: &CONTEXT) -> WORD { + frame.AddrPC.Offset = ctx.Eip as u64; + frame.AddrPC.Mode = AddrModeFlat; + frame.AddrStack.Offset = ctx.Esp as u64; + frame.AddrStack.Mode = AddrModeFlat; + frame.AddrFrame.Offset = ctx.Ebp as u64; + frame.AddrFrame.Mode = AddrModeFlat; + winnt::IMAGE_FILE_MACHINE_I386 +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/backtrace/libunwind.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/backtrace/libunwind.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/backtrace/libunwind.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/backtrace/libunwind.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,200 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::os::raw::c_void; + +pub struct Frame { + ctx: *mut uw::_Unwind_Context, +} + +impl Frame { + pub fn ip(&self) -> *mut c_void { + let mut ip_before_insn = 0; + let mut ip = unsafe { + uw::_Unwind_GetIPInfo(self.ctx, &mut ip_before_insn) as *mut c_void + }; + if !ip.is_null() && ip_before_insn == 0 { + // this is a non-signaling frame, so `ip` refers to the address + // after the calling instruction. account for that. + ip = (ip as usize - 1) as *mut _; + } + return ip + } + + pub fn symbol_address(&self) -> *mut c_void { + // dladdr() on osx gets whiny when we use FindEnclosingFunction, and + // it appears to work fine without it, so we only use + // FindEnclosingFunction on non-osx platforms. In doing so, we get a + // slightly more accurate stack trace in the process. + // + // This is often because panic involves the last instruction of a + // function being "call std::rt::begin_unwind", with no ret + // instructions after it. This means that the return instruction + // pointer points *outside* of the calling function, and by + // unwinding it we go back to the original function. + if cfg!(target_os = "macos") || cfg!(target_os = "ios") { + self.ip() + } else { + unsafe { uw::_Unwind_FindEnclosingFunction(self.ip()) } + } + } +} + +#[inline(always)] +pub fn trace(mut cb: &mut FnMut(&super::Frame) -> bool) { + unsafe { + uw::_Unwind_Backtrace(trace_fn, &mut cb as *mut _ as *mut _); + } + + extern fn trace_fn(ctx: *mut uw::_Unwind_Context, + arg: *mut c_void) -> uw::_Unwind_Reason_Code { + let cb = unsafe { &mut *(arg as *mut &mut FnMut(&super::Frame) -> bool) }; + let cx = super::Frame { + inner: Frame { ctx: ctx }, + }; + + let mut bomb = ::Bomb { enabled: true }; + let keep_going = cb(&cx); + bomb.enabled = false; + + if keep_going { + uw::_URC_NO_REASON + } else { + uw::_URC_FAILURE + } + } +} + +/// Unwind library interface used for backtraces +/// +/// Note that dead code is allowed as here are just bindings +/// iOS doesn't use all of them it but adding more +/// platform-specific configs pollutes the code too much +#[allow(non_camel_case_types)] +#[allow(non_snake_case)] +#[allow(dead_code)] +mod uw { + pub use self::_Unwind_Reason_Code::*; + + use libc; + use std::os::raw::{c_int, c_void}; + + #[repr(C)] + pub enum _Unwind_Reason_Code { + _URC_NO_REASON = 0, + _URC_FOREIGN_EXCEPTION_CAUGHT = 1, + _URC_FATAL_PHASE2_ERROR = 2, + _URC_FATAL_PHASE1_ERROR = 3, + _URC_NORMAL_STOP = 4, + _URC_END_OF_STACK = 5, + _URC_HANDLER_FOUND = 6, + _URC_INSTALL_CONTEXT = 7, + _URC_CONTINUE_UNWIND = 8, + _URC_FAILURE = 9, // used only by ARM EABI + } + + pub enum _Unwind_Context {} + + pub type _Unwind_Trace_Fn = + extern fn(ctx: *mut _Unwind_Context, + arg: *mut c_void) -> _Unwind_Reason_Code; + + extern { + // No native _Unwind_Backtrace on iOS + #[cfg(not(all(target_os = "ios", target_arch = "arm")))] + pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn, + trace_argument: *mut c_void) + -> _Unwind_Reason_Code; + + // available since GCC 4.2.0, should be fine for our purpose + #[cfg(all(not(all(target_os = "android", target_arch = "arm")), + not(all(target_os = "linux", target_arch = "arm"))))] + pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context, + ip_before_insn: *mut c_int) + -> libc::uintptr_t; + + #[cfg(all(not(target_os = "android"), + not(all(target_os = "linux", target_arch = "arm"))))] + pub fn _Unwind_FindEnclosingFunction(pc: *mut c_void) + -> *mut c_void; + } + + // On android, the function _Unwind_GetIP is a macro, and this is the + // expansion of the macro. This is all copy/pasted directly from the + // header file with the definition of _Unwind_GetIP. + #[cfg(any(all(target_os = "android", target_arch = "arm"), + all(target_os = "linux", target_arch = "arm")))] + pub unsafe fn _Unwind_GetIP(ctx: *mut _Unwind_Context) -> libc::uintptr_t { + #[repr(C)] + enum _Unwind_VRS_Result { + _UVRSR_OK = 0, + _UVRSR_NOT_IMPLEMENTED = 1, + _UVRSR_FAILED = 2, + } + #[repr(C)] + enum _Unwind_VRS_RegClass { + _UVRSC_CORE = 0, + _UVRSC_VFP = 1, + _UVRSC_FPA = 2, + _UVRSC_WMMXD = 3, + _UVRSC_WMMXC = 4, + } + #[repr(C)] + enum _Unwind_VRS_DataRepresentation { + _UVRSD_UINT32 = 0, + _UVRSD_VFPX = 1, + _UVRSD_FPAX = 2, + _UVRSD_UINT64 = 3, + _UVRSD_FLOAT = 4, + _UVRSD_DOUBLE = 5, + } + + type _Unwind_Word = libc::c_uint; + extern { + fn _Unwind_VRS_Get(ctx: *mut _Unwind_Context, + klass: _Unwind_VRS_RegClass, + word: _Unwind_Word, + repr: _Unwind_VRS_DataRepresentation, + data: *mut c_void) + -> _Unwind_VRS_Result; + } + + let mut val: _Unwind_Word = 0; + let ptr = &mut val as *mut _Unwind_Word; + let _ = _Unwind_VRS_Get(ctx, _Unwind_VRS_RegClass::_UVRSC_CORE, 15, + _Unwind_VRS_DataRepresentation::_UVRSD_UINT32, + ptr as *mut c_void); + (val & !1) as libc::uintptr_t + } + + // This function doesn't exist on Android or ARM/Linux, so make it same + // to _Unwind_GetIP + #[cfg(any(all(target_os = "android", target_arch = "arm"), + all(target_os = "linux", target_arch = "arm")))] + pub unsafe fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context, + ip_before_insn: *mut c_int) + -> libc::uintptr_t + { + *ip_before_insn = 0; + _Unwind_GetIP(ctx) + } + + // This function also doesn't exist on Android or ARM/Linux, so make it + // a no-op + #[cfg(any(target_os = "android", + all(target_os = "linux", target_arch = "arm")))] + pub unsafe fn _Unwind_FindEnclosingFunction(pc: *mut c_void) + -> *mut c_void + { + pc + } +} + + diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/backtrace/mod.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/backtrace/mod.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/backtrace/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/backtrace/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,113 @@ +use std::fmt; + +use std::os::raw::c_void; + +/// Inspects the current call-stack, passing all active frames into the closure +/// provided to calculate a stack trace. +/// +/// This function is the workhorse of this library in calculating the stack +/// traces for a program. The given closure `cb` is yielded instances of a +/// `Frame` which represent information about that call frame on the stack. The +/// closure is yielded frames in a top-down fashion (most recently called +/// functions first). +/// +/// The closure's return value is an indication of whether the backtrace should +/// continue. A return value of `false` will terminate the backtrace and return +/// immediately. +/// +/// Once a `Frame` is acquired you will likely want to call `backtrace::resolve` +/// to convert the `ip` (instruction pointer) or symbol address to a `Symbol` +/// through which the name and/or filename/line number can be learned. +/// +/// Note that this is a relatively low-level function and if you'd like to, for +/// example, capture a backtrace to be inspected later, then the `Backtrace` +/// type may be more appropriate. +/// +/// # Example +/// +/// ``` +/// extern crate backtrace; +/// +/// fn main() { +/// backtrace::trace(|frame| { +/// // ... +/// +/// true // continue the backtrace +/// }); +/// } +/// ``` +#[inline(never)] // if this is never inlined then the first frame can be known + // to be skipped +pub fn trace bool>(mut cb: F) { + trace_imp(&mut cb) +} + +/// A trait representing one frame of a backtrace, yielded to the `trace` +/// function of this crate. +/// +/// The tracing function's closure will be yielded frames, and the frame is +/// virtually dispatched as the underlying implementation is not always known +/// until runtime. +pub struct Frame { + inner: FrameImp, +} + +impl Frame { + /// Returns the current instruction pointer of this frame. + /// + /// This is normally the next instruction to execute in the frame, but not + /// all implementations list this with 100% accuracy (but it's generally + /// pretty close). + /// + /// It is recommended to pass this value to `backtrace::resolve` to turn it + /// into a symbol name. + pub fn ip(&self) -> *mut c_void { + self.inner.ip() + } + + /// Returns the starting symbol address of the frame of this function. + /// + /// This will attempt to rewind the instruction pointer returned by `ip` to + /// the start of the function, returning that value. In some cases, however, + /// backends will just return `ip` from this function. + /// + /// The returned value can sometimes be used if `backtrace::resolve` failed + /// on the `ip` given above. + pub fn symbol_address(&self) -> *mut c_void { + self.inner.symbol_address() + } +} + +impl fmt::Debug for Frame { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Frame") + .field("ip", &self.ip()) + .field("symbol_address", &self.symbol_address()) + .finish() + } +} + +cfg_if! { + if #[cfg(all(unix, + not(target_os = "emscripten"), + not(all(target_os = "ios", target_arch = "arm")), + feature = "libunwind"))] { + mod libunwind; + use self::libunwind::trace as trace_imp; + use self::libunwind::Frame as FrameImp; + } else if #[cfg(all(unix, + not(target_os = "emscripten"), + feature = "unix-backtrace"))] { + mod unix_backtrace; + use self::unix_backtrace::trace as trace_imp; + use self::unix_backtrace::Frame as FrameImp; + } else if #[cfg(all(windows, feature = "dbghelp"))] { + mod dbghelp; + use self::dbghelp::trace as trace_imp; + use self::dbghelp::Frame as FrameImp; + } else { + mod noop; + use self::noop::trace as trace_imp; + use self::noop::Frame as FrameImp; + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/backtrace/noop.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/backtrace/noop.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/backtrace/noop.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/backtrace/noop.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,16 @@ +use std::os::raw::c_void; + +#[inline(always)] +pub fn trace(_cb: &mut FnMut(&super::Frame) -> bool) {} + +pub struct Frame; + +impl Frame { + pub fn ip(&self) -> *mut c_void { + 0 as *mut _ + } + + pub fn symbol_address(&self) -> *mut c_void { + 0 as *mut _ + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/backtrace/unix_backtrace.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/backtrace/unix_backtrace.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/backtrace/unix_backtrace.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/backtrace/unix_backtrace.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,46 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::mem; +use std::os::raw::{c_void, c_int}; + +pub struct Frame { + addr: *mut c_void, +} + +impl Frame { + pub fn ip(&self) -> *mut c_void { self.addr } + pub fn symbol_address(&self) -> *mut c_void { self.addr } +} + +extern { + fn backtrace(buf: *mut *mut c_void, sz: c_int) -> c_int; +} + +#[inline(always)] +pub fn trace(cb: &mut FnMut(&super::Frame) -> bool) { + const SIZE: usize = 100; + + let mut buf: [*mut c_void; SIZE]; + let cnt; + unsafe { + buf = mem::zeroed(); + cnt = backtrace(buf.as_mut_ptr(), SIZE as c_int); + } + + for addr in buf[..cnt as usize].iter() { + let cx = super::Frame { + inner: Frame { addr: *addr }, + }; + if !cb(&cx) { + return + } + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/capture.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/capture.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/capture.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/capture.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,237 @@ +use std::fmt; +use std::mem; +use std::os::raw::c_void; +use std::path::{Path, PathBuf}; + +use {trace, resolve, SymbolName}; + +/// Representation of an owned and self-contained backtrace. +/// +/// This structure can be used to capture a backtrace at various points in a +/// program and later used to inspect what the backtrace was at that time. +#[derive(Clone)] +#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))] +#[cfg_attr(feature = "serialize-serde", derive(Deserialize, Serialize))] +pub struct Backtrace { + frames: Vec, +} + +/// Captured version of a frame in a backtrace. +/// +/// This type is returned as a list from `Backtrace::frames` and represents one +/// stack frame in a captured backtrace. +#[derive(Clone)] +#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))] +#[cfg_attr(feature = "serialize-serde", derive(Deserialize, Serialize))] +pub struct BacktraceFrame { + ip: usize, + symbol_address: usize, + symbols: Option>, +} + +/// Captured version of a symbol in a backtrace. +/// +/// This type is returned as a list from `BacktraceFrame::symbols` and +/// represents the metadata for a symbol in a backtrace. +#[derive(Clone)] +#[cfg_attr(feature = "serialize-rustc", derive(RustcDecodable, RustcEncodable))] +#[cfg_attr(feature = "serialize-serde", derive(Deserialize, Serialize))] +pub struct BacktraceSymbol { + name: Option>, + addr: Option, + filename: Option, + lineno: Option, +} + +impl Backtrace { + /// Captures a backtrace at the callsite of this function, returning an + /// owned representation. + /// + /// This function is useful for representing a backtrace as an object in + /// Rust. This returned value can be sent across threads and printed + /// elsewhere, and the purpose of this value is to be entirely self + /// contained. + /// + /// # Examples + /// + /// ``` + /// use backtrace::Backtrace; + /// + /// let current_backtrace = Backtrace::new(); + /// ``` + pub fn new() -> Backtrace { + let mut bt = Backtrace::new_unresolved(); + bt.resolve(); + return bt + } + + /// Similar to `new` except that this does not resolve any symbols, this + /// simply captures the backtrace as a list of addresses. + /// + /// At a later time the `resolve` function can be called to resolve this + /// backtrace's symbols into readable names. This function exists because + /// the resolution process can sometimes take a significant amount of time + /// whereas any one backtrace may only be rarely printed. + /// + /// # Examples + /// + /// ``` + /// use backtrace::Backtrace; + /// + /// let mut current_backtrace = Backtrace::new_unresolved(); + /// println!("{:?}", current_backtrace); // no symbol names + /// current_backtrace.resolve(); + /// println!("{:?}", current_backtrace); // symbol names now present + /// ``` + pub fn new_unresolved() -> Backtrace { + let mut frames = Vec::new(); + trace(|frame| { + frames.push(BacktraceFrame { + ip: frame.ip() as usize, + symbol_address: frame.symbol_address() as usize, + symbols: None, + }); + true + }); + + Backtrace { frames: frames } + } + + /// Returns the frames from when this backtrace was captured. + /// + /// The first entry of this slice is likely the function `Backtrace::new`, + /// and the last frame is likely something about how this thread or the main + /// function started. + pub fn frames(&self) -> &[BacktraceFrame] { + &self.frames + } + + /// If this backtrace was created from `new_unresolved` then this function + /// will resolve all addresses in the backtrace to their symbolic names. + /// + /// If this backtrace has been previously resolved or was created through + /// `new`, this function does nothing. + pub fn resolve(&mut self) { + for frame in self.frames.iter_mut().filter(|f| f.symbols.is_none()) { + let mut symbols = Vec::new(); + resolve(frame.ip as *mut _, |symbol| { + symbols.push(BacktraceSymbol { + name: symbol.name().map(|m| m.as_bytes().to_vec()), + addr: symbol.addr().map(|a| a as usize), + filename: symbol.filename().map(|m| m.to_path_buf()), + lineno: symbol.lineno(), + }); + }); + frame.symbols = Some(symbols); + } + } +} + +impl From> for Backtrace { + fn from(frames: Vec) -> Self { + Backtrace { + frames: frames + } + } +} + +impl Into> for Backtrace { + fn into(self) -> Vec { + self.frames + } +} + +impl BacktraceFrame { + /// Same as `Frame::ip` + pub fn ip(&self) -> *mut c_void { + self.ip as *mut c_void + } + + /// Same as `Frame::symbol_address` + pub fn symbol_address(&self) -> *mut c_void { + self.symbol_address as *mut c_void + } + + /// Returns the list of symbols that this frame corresponds to. + /// + /// Normally there is only one symbol per frame, but sometimes if a number + /// of functions are inlined into one frame then multiple symbols will be + /// returned. The first symbol listed is the "innermost function", whereas + /// the last symbol is the outermost (last caller). + /// + /// Note that if this frame came from an unresolved backtrace then this will + /// return an empty list. + pub fn symbols(&self) -> &[BacktraceSymbol] { + self.symbols.as_ref().map(|s| &s[..]).unwrap_or(&[]) + } +} + +impl BacktraceSymbol { + /// Same as `Symbol::name` + pub fn name(&self) -> Option { + self.name.as_ref().map(|s| SymbolName::new(s)) + } + + /// Same as `Symbol::addr` + pub fn addr(&self) -> Option<*mut c_void> { + self.addr.map(|s| s as *mut c_void) + } + + /// Same as `Symbol::filename` + pub fn filename(&self) -> Option<&Path> { + self.filename.as_ref().map(|p| &**p) + } + + /// Same as `Symbol::lineno` + pub fn lineno(&self) -> Option { + self.lineno + } +} + +impl fmt::Debug for Backtrace { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + let hex_width = mem::size_of::() * 2 + 2; + + try!(write!(fmt, "stack backtrace:")); + + for (idx, frame) in self.frames().iter().enumerate() { + let ip = frame.ip(); + try!(write!(fmt, "\n{:4}: {:2$?}", idx, ip, hex_width)); + + let symbols = match frame.symbols { + Some(ref s) => s, + None => { + try!(write!(fmt, " - ")); + continue + } + }; + if symbols.len() == 0 { + try!(write!(fmt, " - ")); + } + + for (idx, symbol) in symbols.iter().enumerate() { + if idx != 0 { + try!(write!(fmt, "\n {:1$}", "", hex_width)); + } + + if let Some(name) = symbol.name() { + try!(write!(fmt, " - {}", name)); + } else { + try!(write!(fmt, " - ")); + } + + if let (Some(file), Some(line)) = (symbol.filename(), symbol.lineno()) { + try!(write!(fmt, "\n {:3$}at {}:{}", "", file.display(), line, hex_width)); + } + } + } + + Ok(()) + } +} + +impl Default for Backtrace { + fn default() -> Backtrace { + Backtrace::new() + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/dylib.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/dylib.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/dylib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/dylib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,70 @@ +use std::ffi::CString; +use std::marker; +use std::mem; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use libc::{self, c_char, c_void}; + +pub struct Dylib { + pub init: AtomicUsize, +} + +pub struct Symbol { + pub name: &'static str, + pub addr: AtomicUsize, + pub _marker: marker::PhantomData, +} + +impl Dylib { + pub unsafe fn get<'a, T>(&self, sym: &'a Symbol) -> Option<&'a T> { + self.load().and_then(|handle| { + sym.get(handle) + }) + } + + pub unsafe fn init(&self, path: &str) -> bool { + if self.init.load(Ordering::SeqCst) != 0 { + return true + } + let name = CString::new(path).unwrap(); + let ptr = libc::dlopen(name.as_ptr() as *const c_char, libc::RTLD_LAZY); + if ptr.is_null() { + return false + } + match self.init.compare_and_swap(0, ptr as usize, Ordering::SeqCst) { + 0 => {} + _ => { libc::dlclose(ptr); } + } + return true + } + + unsafe fn load(&self) -> Option<*mut c_void> { + match self.init.load(Ordering::SeqCst) { + 0 => None, + n => Some(n as *mut c_void), + } + } +} + +impl Symbol { + unsafe fn get(&self, handle: *mut c_void) -> Option<&T> { + assert_eq!(mem::size_of::(), mem::size_of_val(&self.addr)); + if self.addr.load(Ordering::SeqCst) == 0 { + self.addr.store(fetch(handle, self.name.as_ptr()), Ordering::SeqCst) + } + if self.addr.load(Ordering::SeqCst) == 1 { + None + } else { + mem::transmute::<&AtomicUsize, Option<&T>>(&self.addr) + } + } +} + +unsafe fn fetch(handle: *mut c_void, name: *const u8) -> usize { + let ptr = libc::dlsym(handle, name as *const _); + if ptr.is_null() { + 1 + } else { + ptr as usize + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/lib.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/lib.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,178 @@ +//! A library for acquiring a backtrace at runtime +//! +//! This library is meant to supplement the `RUST_BACKTRACE=1` support of the +//! standard library by allowing an acquisition of a backtrace at runtime +//! programmatically. The backtraces generated by this library do not need to be +//! parsed, for example, and expose the functionality of multiple backend +//! implementations. +//! +//! # Implementation +//! +//! This library makes use of a number of strategies for actually acquiring a +//! backtrace. For example unix uses libgcc's libunwind bindings by default to +//! acquire a backtrace, but coresymbolication or dladdr is used on OSX to +//! acquire symbol names while linux uses gcc's libbacktrace. +//! +//! When using the default feature set of this library the "most reasonable" set +//! of defaults is chosen for the current platform, but the features activated +//! can also be controlled at a finer granularity. +//! +//! # Platform Support +//! +//! Currently this library is verified to work on Linux, OSX, and Windows, but +//! it may work on other platforms as well. Note that the quality of the +//! backtrace may vary across platforms. +//! +//! # API Principles +//! +//! This library attempts to be as flexible as possible to accommodate different +//! backend implementations of acquiring a backtrace. Consequently the currently +//! exported functions are closure-based as opposed to the likely expected +//! iterator-based versions. This is done due to limitations of the underlying +//! APIs used from the system. +//! +//! # Usage +//! +//! First, add this to your Cargo.toml +//! +//! ```toml +//! [dependencies] +//! backtrace = "0.2" +//! ``` +//! +//! Next: +//! +//! ``` +//! extern crate backtrace; +//! +//! fn main() { +//! backtrace::trace(|frame| { +//! let ip = frame.ip(); +//! let symbol_address = frame.symbol_address(); +//! +//! // Resolve this instruction pointer to a symbol name +//! backtrace::resolve(ip, |symbol| { +//! if let Some(name) = symbol.name() { +//! // ... +//! } +//! if let Some(filename) = symbol.filename() { +//! // ... +//! } +//! }); +//! +//! true // keep going to the next frame +//! }); +//! } +//! ``` + +#![doc(html_root_url = "http://alexcrichton.com/backtrace-rs")] +#![deny(missing_docs)] +#![deny(warnings)] + +#[cfg(unix)] +extern crate libc; +#[cfg(all(windows, feature = "winapi"))] extern crate winapi; + +#[cfg(feature = "serde_derive")] +#[cfg_attr(feature = "serde_derive", macro_use)] +extern crate serde_derive; + +#[cfg(feature = "rustc-serialize")] +extern crate rustc_serialize; + +#[macro_use] +extern crate cfg_if; + +extern crate rustc_demangle; + +#[cfg(feature = "cpp_demangle")] +extern crate cpp_demangle; + +cfg_if! { + if #[cfg(all(feature = "gimli-symbolize", unix, target_os = "linux"))] { + extern crate addr2line; + extern crate findshlibs; + extern crate gimli; + extern crate memmap; + extern crate object; + } +} + +#[allow(dead_code)] // not used everywhere +#[cfg(unix)] +#[macro_use] +mod dylib; + +pub use backtrace::{trace, Frame}; +mod backtrace; + +pub use symbolize::{resolve, Symbol, SymbolName}; +mod symbolize; + +pub use capture::{Backtrace, BacktraceFrame, BacktraceSymbol}; +mod capture; + +#[allow(dead_code)] +struct Bomb { + enabled: bool, +} + +#[allow(dead_code)] +impl Drop for Bomb { + fn drop(&mut self) { + if self.enabled { + panic!("cannot panic during the backtrace function"); + } + } +} + +#[allow(dead_code)] +mod lock { + use std::cell::Cell; + use std::mem; + use std::sync::{Once, Mutex, MutexGuard, ONCE_INIT}; + + pub struct LockGuard(MutexGuard<'static, ()>); + + static mut LOCK: *mut Mutex<()> = 0 as *mut _; + static INIT: Once = ONCE_INIT; + thread_local!(static LOCK_HELD: Cell = Cell::new(false)); + + impl Drop for LockGuard { + fn drop(&mut self) { + LOCK_HELD.with(|slot| { + assert!(slot.get()); + slot.set(false); + }); + } + } + + pub fn lock() -> Option { + if LOCK_HELD.with(|l| l.get()) { + return None + } + LOCK_HELD.with(|s| s.set(true)); + unsafe { + INIT.call_once(|| { + LOCK = mem::transmute(Box::new(Mutex::new(()))); + }); + Some(LockGuard((*LOCK).lock().unwrap())) + } + } +} + +// requires external synchronization +#[cfg(all(windows, feature = "dbghelp"))] +unsafe fn dbghelp_init() { + use winapi::shared::minwindef; + use winapi::um::{dbghelp, processthreadsapi}; + + static mut INITIALIZED: bool = false; + + if !INITIALIZED { + dbghelp::SymInitializeW(processthreadsapi::GetCurrentProcess(), + 0 as *mut _, + minwindef::TRUE); + INITIALIZED = true; + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/coresymbolication.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/coresymbolication.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/coresymbolication.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/coresymbolication.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,192 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(bad_style)] + +use std::ffi::{CStr, OsStr}; +use std::mem; +use std::os::raw::{c_void, c_char, c_int}; +use std::os::unix::prelude::*; +use std::path::Path; +use std::ptr; +use std::sync::atomic::ATOMIC_USIZE_INIT; + +use libc::{self, Dl_info}; + +use SymbolName; +use dylib::Dylib; +use dylib::Symbol as DylibSymbol; + +#[repr(C)] +#[derive(Copy, Clone, PartialEq)] +pub struct CSTypeRef { + cpp_data: *const c_void, + cpp_obj: *const c_void +} + +const CS_NOW: u64 = 0x80000000; +const CSREF_NULL: CSTypeRef = CSTypeRef { + cpp_data: 0 as *const c_void, + cpp_obj: 0 as *const c_void, +}; + +pub enum Symbol { + Core { + path: *const c_char, + lineno: u32, + name: *const c_char, + addr: *mut c_void, + }, + Dladdr(Dl_info), +} + +impl Symbol { + pub fn name(&self) -> Option { + let name = match *self { + Symbol::Core { name, .. } => name, + Symbol::Dladdr(ref info) => info.dli_sname, + }; + if name.is_null() { + None + } else { + Some(SymbolName::new(unsafe { + CStr::from_ptr(name).to_bytes() + })) + } + } + + pub fn addr(&self) -> Option<*mut c_void> { + match *self { + Symbol::Core { addr, .. } => Some(addr), + Symbol::Dladdr(ref info) => Some(info.dli_saddr as *mut _), + } + } + + pub fn filename(&self) -> Option<&Path> { + match *self { + Symbol::Core { path, .. } => { + if path.is_null() { + None + } else { + Some(Path::new(OsStr::from_bytes(unsafe { + CStr::from_ptr(path).to_bytes() + }))) + } + } + Symbol::Dladdr(_) => None, + } + } + + pub fn lineno(&self) -> Option { + match *self { + Symbol::Core { lineno: 0, .. } => None, + Symbol::Core { lineno, .. } => Some(lineno), + Symbol::Dladdr(_) => None, + } + } +} + +static CORESYMBOLICATION: Dylib = Dylib { init: ATOMIC_USIZE_INIT }; + +macro_rules! dlsym { + (extern { + $(fn $name:ident($($arg:ident: $t:ty),*) -> $ret:ty;)* + }) => ($( + static $name: ::dylib::Symbol $ret> = + ::dylib::Symbol { + name: concat!(stringify!($name), "\0"), + addr: ::std::sync::atomic::ATOMIC_USIZE_INIT, + _marker: ::std::marker::PhantomData, + }; + )*) +} + +dlsym! { + extern { + fn CSSymbolicatorCreateWithPid(pid: c_int) -> CSTypeRef; + fn CSRelease(rf: CSTypeRef) -> c_void; + fn CSSymbolicatorGetSymbolWithAddressAtTime( + cs: CSTypeRef, addr: *const c_void, time: u64) -> CSTypeRef; + fn CSSymbolicatorGetSourceInfoWithAddressAtTime( + cs: CSTypeRef, addr: *const c_void, time: u64) -> CSTypeRef; + fn CSSourceInfoGetLineNumber(info: CSTypeRef) -> c_int; + fn CSSourceInfoGetPath(info: CSTypeRef) -> *const c_char; + fn CSSourceInfoGetSymbol(info: CSTypeRef) -> CSTypeRef; + fn CSSymbolGetName(sym: CSTypeRef) -> *const c_char; + fn CSSymbolGetSymbolOwner(sym: CSTypeRef) -> CSTypeRef; + fn CSSymbolOwnerGetBaseAddress(symowner: CSTypeRef) -> *mut c_void; + } +} + +unsafe fn get(sym: &DylibSymbol) -> &T { + CORESYMBOLICATION.get(sym).unwrap() +} + +unsafe fn try_resolve(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) -> bool { + let path = "/System/Library/PrivateFrameworks/CoreSymbolication.framework\ + /Versions/A/CoreSymbolication"; + if !CORESYMBOLICATION.init(path) { + return false; + } + + let cs = get(&CSSymbolicatorCreateWithPid)(libc::getpid()); + if cs == CSREF_NULL { + return false + } + + let info = get(&CSSymbolicatorGetSourceInfoWithAddressAtTime)( + cs, addr, CS_NOW); + let sym = if info == CSREF_NULL { + get(&CSSymbolicatorGetSymbolWithAddressAtTime)(cs, addr, CS_NOW) + } else { + get(&CSSourceInfoGetSymbol)(info) + }; + + let mut rv = false; + if sym != CSREF_NULL { + let owner = get(&CSSymbolGetSymbolOwner)(sym); + if owner != CSREF_NULL { + cb(&super::Symbol { + inner: Symbol::Core { + path: if info != CSREF_NULL { + get(&CSSourceInfoGetPath)(info) + } else { + ptr::null() + }, + lineno: if info != CSREF_NULL { + get(&CSSourceInfoGetLineNumber)(info) as u32 + } else { + 0 + }, + name: get(&CSSymbolGetName)(sym), + addr: get(&CSSymbolOwnerGetBaseAddress)(owner), + }, + }); + rv = true; + } + } + get(&CSRelease)(cs); + + rv +} + +pub fn resolve(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) { + unsafe { + if try_resolve(addr, cb) { + return + } + let mut info: Dl_info = mem::zeroed(); + if libc::dladdr(addr as *mut _, &mut info) != 0 { + cb(&super::Symbol { + inner: Symbol::Dladdr(info), + }); + } + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/dbghelp.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/dbghelp.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/dbghelp.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/dbghelp.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,118 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(bad_style)] + +use std::ffi::OsString; +use std::mem; +use std::path::Path; +use std::os::windows::prelude::*; +use std::slice; +use winapi::ctypes::*; +use winapi::shared::basetsd::*; +use winapi::shared::minwindef::*; +use winapi::um::processthreadsapi; +use winapi::um::dbghelp; +use winapi::um::dbghelp::*; + +use SymbolName; + +pub struct Symbol { + name: OsString, + addr: *mut c_void, + line: Option, + filename: Option, +} + +impl Symbol { + pub fn name(&self) -> Option { + self.name.to_str().map(|s| SymbolName::new(s.as_bytes())) + } + + pub fn addr(&self) -> Option<*mut c_void> { + Some(self.addr as *mut _) + } + + pub fn filename(&self) -> Option<&Path> { + self.filename.as_ref().map(Path::new) + } + + pub fn lineno(&self) -> Option { + self.line + } +} + +pub fn resolve(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) { + // According to windows documentation, all dbghelp functions are + // single-threaded. + let _g = ::lock::lock(); + + unsafe { + let size = 2 * MAX_SYM_NAME + mem::size_of::(); + let mut data = vec![0u8; size]; + let info = &mut *(data.as_mut_ptr() as *mut SYMBOL_INFOW); + info.MaxNameLen = MAX_SYM_NAME as ULONG; + // the struct size in C. the value is different to + // `size_of::() - MAX_SYM_NAME + 1` (== 81) + // due to struct alignment. + info.SizeOfStruct = 88; + + let _c = ::dbghelp_init(); + + let mut displacement = 0u64; + let ret = dbghelp::SymFromAddrW(processthreadsapi::GetCurrentProcess(), + addr as DWORD64, + &mut displacement, + info); + if ret != TRUE { + return + } + + // If the symbol name is greater than MaxNameLen, SymFromAddrW will + // give a buffer of (MaxNameLen - 1) characters and set NameLen to + // the real value. + let name_len = ::std::cmp::min(info.NameLen as usize, + info.MaxNameLen as usize - 1); + + let name = slice::from_raw_parts(info.Name.as_ptr() as *const u16, + name_len); + let name = OsString::from_wide(name); + + let mut line = mem::zeroed::(); + line.SizeOfStruct = mem::size_of::() as DWORD; + let mut displacement = 0; + let ret = dbghelp::SymGetLineFromAddrW64(processthreadsapi::GetCurrentProcess(), + addr as DWORD64, + &mut displacement, + &mut line); + let mut filename = None; + let mut lineno = None; + if ret == TRUE { + lineno = Some(line.LineNumber as u32); + + let base = line.FileName; + let mut len = 0; + while *base.offset(len) != 0 { + len += 1; + } + let name = slice::from_raw_parts(base, len as usize); + filename = Some(OsString::from_wide(name)); + } + + cb(&super::Symbol { + inner: Symbol { + name: name, + addr: info.Address as *mut _, + line: lineno, + filename: filename, + }, + }) + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/dladdr.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/dladdr.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/dladdr.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/dladdr.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,59 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::ffi::CStr; +use std::mem; +use std::os::raw::c_void; +use std::path::Path; + +use libc::{self, Dl_info}; + +use SymbolName; + +pub struct Symbol { + inner: Dl_info, +} + +impl Symbol { + pub fn name(&self) -> Option { + if self.inner.dli_sname.is_null() { + None + } else { + Some(SymbolName::new(unsafe { + CStr::from_ptr(self.inner.dli_sname).to_bytes() + })) + } + } + + pub fn addr(&self) -> Option<*mut c_void> { + Some(self.inner.dli_saddr as *mut _) + } + + pub fn filename(&self) -> Option<&Path> { + None + } + + pub fn lineno(&self) -> Option { + None + } +} + +pub fn resolve(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) { + unsafe { + let mut info: super::Symbol = super::Symbol { + inner: Symbol { + inner: mem::zeroed(), + }, + }; + if libc::dladdr(addr as *mut _, &mut info.inner.inner) != 0 { + cb(&info) + } + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/gimli.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/gimli.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/gimli.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/gimli.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,224 @@ +use addr2line; +use findshlibs::{self, Segment, SharedLibrary}; +use gimli; +use memmap::Mmap; +use object::{self, Object}; +use std::cell::RefCell; +use std::env; +use std::fs::File; +use std::mem; +use std::os::raw::c_void; +use std::path::{Path, PathBuf}; +use std::u32; + +use SymbolName; + +const MAPPINGS_CACHE_SIZE: usize = 4; + +type Dwarf<'map> = addr2line::Context>; +type Symbols<'map> = object::SymbolMap<'map>; + +struct Mapping { + // 'static lifetime is a lie to hack around lack of support for self-referential structs. + dwarf: Dwarf<'static>, + symbols: Symbols<'static>, + _map: Mmap, +} + +impl Mapping { + fn new(path: &PathBuf) -> Option { + let file = File::open(path).ok()?; + // TODO: not completely safe, see https://github.com/danburkert/memmap-rs/issues/25 + let map = unsafe { Mmap::map(&file).ok()? }; + let (dwarf, symbols) = { + let object = object::File::parse(&*map).ok()?; + let dwarf = addr2line::Context::new(&object).ok()?; + let symbols = object.symbol_map(); + // Convert to 'static lifetimes. + unsafe { (mem::transmute(dwarf), mem::transmute(symbols)) } + }; + Some(Mapping { + dwarf, + symbols, + _map: map, + }) + } + + // Ensure the 'static lifetimes don't leak. + fn rent(&self, mut f: F) + where + F: FnMut(&Dwarf, &Symbols), + { + f(&self.dwarf, &self.symbols) + } +} + +thread_local! { + // A very small, very simple LRU cache for debug info mappings. + // + // The hit rate should be very high, since the typical stack doesn't cross + // between many shared libraries. + // + // The `addr2line::Context` structures are pretty expensive to create. Its + // cost is expected to be amortized by subsequent `locate` queries, which + // leverage the structures built when constructing `addr2line::Context`s to + // get nice speedups. If we didn't have this cache, that amortization would + // never happen, and symbolicating backtraces would be ssssllllooooowwww. + static MAPPINGS_CACHE: RefCell> + = RefCell::new(Vec::with_capacity(MAPPINGS_CACHE_SIZE)); +} + +fn with_mapping_for_path(path: PathBuf, f: F) +where + F: FnMut(&Dwarf, &Symbols), +{ + MAPPINGS_CACHE.with(|cache| { + let mut cache = cache.borrow_mut(); + + let idx = cache.iter().position(|&(ref p, _)| p == &path); + + // Invariant: after this conditional completes without early returning + // from an error, the cache entry for this path is at index 0. + + if let Some(idx) = idx { + // When the mapping is already in the cache, move it to the front. + if idx != 0 { + let entry = cache.remove(idx); + cache.insert(0, entry); + } + } else { + // When the mapping is not in the cache, create a new mapping, + // insert it into the front of the cache, and evict the oldest cache + // entry if necessary. + let mapping = match Mapping::new(&path) { + None => return, + Some(m) => m, + }; + + if cache.len() == MAPPINGS_CACHE_SIZE { + cache.pop(); + } + + cache.insert(0, (path, mapping)); + } + + cache[0].1.rent(f); + }); +} + +pub fn resolve(addr: *mut c_void, cb: &mut FnMut(&super::Symbol)) { + // First, find the file containing the segment that the given AVMA (after + // relocation) address falls within. Use the containing segment to compute + // the SVMA (before relocation) address. + // + // Note that the OS APIs that `SharedLibrary::each` is implemented with hold + // a lock for the duration of the `each` call, so we want to keep this + // section as short as possible to avoid contention with other threads + // capturing backtraces. + let addr = findshlibs::Avma(addr as *mut u8 as *const u8); + let mut so_info = None; + findshlibs::TargetSharedLibrary::each(|so| { + use findshlibs::IterationControl::*; + + for segment in so.segments() { + if segment.contains_avma(so, addr) { + let addr = so.avma_to_svma(addr); + let path = so.name().to_string_lossy(); + so_info = Some((addr, path.to_string())); + return Break; + } + } + + Continue + }); + let (addr, path) = match so_info { + None => return, + Some((a, p)) => (a, p), + }; + + // Second, fixup the path. Empty path means that this address falls within + // the main executable, not a shared library. + let path = if path.is_empty() { + match env::current_exe() { + Err(_) => return, + Ok(p) => p, + } + } else { + PathBuf::from(path) + }; + + // Finally, get a cached mapping or create a new mapping for this file, and + // evaluate the DWARF info to find the file/line/name for this address. + with_mapping_for_path(path, |dwarf, symbols| { + let mut found_sym = false; + if let Ok(mut frames) = dwarf.find_frames(addr.0 as u64) { + while let Ok(Some(frame)) = frames.next() { + let (file, line) = frame + .location + .map(|l| (l.file, l.line)) + .unwrap_or((None, None)); + let name = frame + .function + .and_then(|f| f.raw_name().ok().map(|f| f.to_string())); + let sym = super::Symbol { + inner: Symbol::new(addr.0 as usize, file, line, name), + }; + cb(&sym); + found_sym = true; + } + } + + // No DWARF info found, so fallback to the symbol table. + if !found_sym { + if let Some(name) = symbols.get(addr.0 as u64).and_then(|x| x.name()) { + let sym = super::Symbol { + inner: Symbol::new(addr.0 as usize, None, None, Some(name.to_string())), + }; + cb(&sym); + } + } + }); +} + +pub struct Symbol { + addr: usize, + file: Option, + line: Option, + name: Option, +} + +impl Symbol { + fn new(addr: usize, + file: Option, + line: Option, + name: Option) + -> Symbol { + Symbol { + addr, + file, + line, + name, + } + } + + pub fn name(&self) -> Option { + self.name.as_ref().map(|s| SymbolName::new(s.as_bytes())) + } + + pub fn addr(&self) -> Option<*mut c_void> { + Some(self.addr as *mut c_void) + } + + pub fn filename(&self) -> Option<&Path> { + self.file.as_ref().map(|f| f.as_ref()) + } + + pub fn lineno(&self) -> Option { + self.line + .and_then(|l| if l > (u32::MAX as u64) { + None + } else { + Some(l as u32) + }) + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/libbacktrace.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/libbacktrace.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/libbacktrace.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/libbacktrace.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,180 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(bad_style)] + +extern crate backtrace_sys as bt; + +use libc::uintptr_t; +use std::ffi::{CStr, OsStr}; +use std::os::raw::{c_void, c_char, c_int}; +use std::os::unix::prelude::*; +use std::path::Path; +use std::ptr; +use std::sync::{ONCE_INIT, Once}; + +use SymbolName; + +pub enum Symbol { + Syminfo { + pc: uintptr_t, + symname: *const c_char, + }, + Pcinfo { + pc: uintptr_t, + filename: *const c_char, + lineno: c_int, + function: *const c_char, + }, +} + +impl Symbol { + pub fn name(&self) -> Option { + let ptr = match *self { + Symbol::Syminfo { symname, .. } => symname, + Symbol::Pcinfo { function, .. } => function, + }; + if ptr.is_null() { + None + } else { + Some(SymbolName::new(unsafe { CStr::from_ptr(ptr).to_bytes() })) + } + } + + pub fn addr(&self) -> Option<*mut c_void> { + let pc = match *self { + Symbol::Syminfo { pc, .. } => pc, + Symbol::Pcinfo { pc, .. } => pc, + }; + if pc == 0 {None} else {Some(pc as *mut _)} + } + + pub fn filename(&self) -> Option<&Path> { + match *self { + Symbol::Syminfo { .. } => None, + Symbol::Pcinfo { filename, .. } => { + Some(Path::new(OsStr::from_bytes(unsafe { + CStr::from_ptr(filename).to_bytes() + }))) + } + } + } + + pub fn lineno(&self) -> Option { + match *self { + Symbol::Syminfo { .. } => None, + Symbol::Pcinfo { lineno, .. } => Some(lineno as u32), + } + } +} + +extern fn error_cb(_data: *mut c_void, _msg: *const c_char, + _errnum: c_int) { + // do nothing for now +} + +extern fn syminfo_cb(data: *mut c_void, + pc: uintptr_t, + symname: *const c_char, + _symval: uintptr_t, + _symsize: uintptr_t) { + unsafe { + call(data, &super::Symbol { + inner: Symbol::Syminfo { + pc: pc, + symname: symname, + }, + }); + } +} + +extern fn pcinfo_cb(data: *mut c_void, + pc: uintptr_t, + filename: *const c_char, + lineno: c_int, + function: *const c_char) -> c_int { + unsafe { + if filename.is_null() || function.is_null() { + return -1 + } + call(data, &super::Symbol { + inner: Symbol::Pcinfo { + pc: pc, + filename: filename, + lineno: lineno, + function: function, + }, + }); + return 0 + } +} + +unsafe fn call(data: *mut c_void, sym: &super::Symbol) { + let cb = data as *mut &mut FnMut(&super::Symbol); + let mut bomb = ::Bomb { enabled: true }; + (*cb)(sym); + bomb.enabled = false; +} + +// The libbacktrace API supports creating a state, but it does not +// support destroying a state. I personally take this to mean that a +// state is meant to be created and then live forever. +// +// I would love to register an at_exit() handler which cleans up this +// state, but libbacktrace provides no way to do so. +// +// With these constraints, this function has a statically cached state +// that is calculated the first time this is requested. Remember that +// backtracing all happens serially (one global lock). +// +// Things don't work so well on not-Linux since libbacktrace can't track down +// that executable this is. We at one point used env::current_exe but it turns +// out that there are some serious security issues with that approach. +// +// Specifically, on certain platforms like BSDs, a malicious actor can cause an +// arbitrary file to be placed at the path returned by current_exe. libbacktrace +// does not behave defensively in the presence of ill-formed DWARF information, +// and has been demonstrated to segfault in at least one case. There is no +// evidence at the moment to suggest that a more carefully constructed file +// can't cause arbitrary code execution. As a result of all of this, we don't +// hint libbacktrace with the path to the current process. +unsafe fn init_state() -> *mut bt::backtrace_state { + static mut STATE: *mut bt::backtrace_state = 0 as *mut _; + static INIT: Once = ONCE_INIT; + INIT.call_once(|| { + // Our libbacktrace may not have multithreading support, so + // set `threaded = 0` and synchronize ourselves. + STATE = bt::backtrace_create_state(ptr::null(), 0, error_cb, + ptr::null_mut()); + }); + + STATE +} + +pub fn resolve(symaddr: *mut c_void, mut cb: &mut FnMut(&super::Symbol)) { + let _guard = ::lock::lock(); + + // backtrace errors are currently swept under the rug + unsafe { + let state = init_state(); + if state.is_null() { + return + } + + let ret = bt::backtrace_pcinfo(state, symaddr as uintptr_t, + pcinfo_cb, error_cb, + &mut cb as *mut _ as *mut _); + if ret != 0 { + bt::backtrace_syminfo(state, symaddr as uintptr_t, + syminfo_cb, error_cb, + &mut cb as *mut _ as *mut _); + } + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/mod.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/mod.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,294 @@ +use std::fmt; +#[cfg(not(feature = "cpp_demangle"))] +use std::marker::PhantomData; +use std::os::raw::c_void; +use std::path::Path; +use std::str; +use rustc_demangle::{try_demangle, Demangle}; + +/// Resolve an address to a symbol, passing the symbol to the specified +/// closure. +/// +/// This function will look up the given address in areas such as the local +/// symbol table, dynamic symbol table, or DWARF debug info (depending on the +/// activated implementation) to find symbols to yield. +/// +/// The closure may not be called if resolution could not be performed, and it +/// also may be called more than once in the case of inlined functions. +/// +/// Symbols yielded represent the execution at the specified `addr`, returning +/// file/line pairs for that address (if available). +/// +/// # Example +/// +/// ``` +/// extern crate backtrace; +/// +/// fn main() { +/// backtrace::trace(|frame| { +/// let ip = frame.ip(); +/// +/// backtrace::resolve(ip, |symbol| { +/// // ... +/// }); +/// +/// false // only look at the top frame +/// }); +/// } +/// ``` +pub fn resolve(addr: *mut c_void, mut cb: F) { + resolve_imp(addr, &mut cb) +} + +/// A trait representing the resolution of a symbol in a file. +/// +/// This trait is yielded as a trait object to the closure given to the +/// `backtrace::resolve` function, and it is virtually dispatched as it's +/// unknown which implementation is behind it. +/// +/// A symbol can give contextual information about a function, for example the +/// name, filename, line number, precise address, etc. Not all information is +/// always available in a symbol, however, so all methods return an `Option`. +pub struct Symbol { + inner: SymbolImp, +} + +impl Symbol { + /// Returns the name of this function. + /// + /// The returned structure can be used to query various properties about the + /// symbol name: + /// + /// * The `Display` implementation will print out the demangled symbol. + /// * The raw `str` value of the symbol can be accessed (if it's valid + /// utf-8). + /// * The raw bytes for the symbol name can be accessed. + pub fn name(&self) -> Option { + self.inner.name() + } + + /// Returns the starting address of this function. + pub fn addr(&self) -> Option<*mut c_void> { + self.inner.addr() + } + + /// Returns the file name where this function was defined. + /// + /// This is currently only available when libbacktrace is being used (e.g. + /// unix platforms other than OSX) and when a binary is compiled with + /// debuginfo. If neither of these conditions is met then this will likely + /// return `None`. + pub fn filename(&self) -> Option<&Path> { + self.inner.filename() + } + + /// Returns the line number for where this symbol is currently executing. + /// + /// This return value is typically `Some` if `filename` returns `Some`, and + /// is consequently subject to similar caveats. + pub fn lineno(&self) -> Option { + self.inner.lineno() + } +} + +impl fmt::Debug for Symbol { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut d = f.debug_struct("Symbol"); + if let Some(name) = self.name() { + d.field("name", &name); + } + if let Some(addr) = self.addr() { + d.field("addr", &addr); + } + if let Some(filename) = self.filename() { + d.field("filename", &filename); + } + if let Some(lineno) = self.lineno() { + d.field("lineno", &lineno); + } + d.finish() + } +} + + +cfg_if! { + if #[cfg(feature = "cpp_demangle")] { + // Maybe a parsed C++ symbol, if parsing the mangled symbol as Rust + // failed. + struct OptionCppSymbol<'a>(Option<::cpp_demangle::BorrowedSymbol<'a>>); + + impl<'a> OptionCppSymbol<'a> { + fn parse(input: &'a [u8]) -> OptionCppSymbol<'a> { + OptionCppSymbol(::cpp_demangle::BorrowedSymbol::new(input).ok()) + } + + fn none() -> OptionCppSymbol<'a> { + OptionCppSymbol(None) + } + } + } else { + // Make sure to keep this zero-sized, so that the `cpp_demangle` feature + // has no cost when disabled. + struct OptionCppSymbol<'a>(PhantomData<&'a ()>); + + impl<'a> OptionCppSymbol<'a> { + fn parse(_: &'a [u8]) -> OptionCppSymbol<'a> { + OptionCppSymbol(PhantomData) + } + + fn none() -> OptionCppSymbol<'a> { + OptionCppSymbol(PhantomData) + } + } + } +} + +/// A wrapper around a symbol name to provide ergonomic accessors to the +/// demangled name, the raw bytes, the raw string, etc. +// Allow dead code for when the `cpp_demangle` feature is not enabled. +#[allow(dead_code)] +pub struct SymbolName<'a> { + bytes: &'a [u8], + demangled: Option>, + cpp_demangled: OptionCppSymbol<'a>, +} + +impl<'a> SymbolName<'a> { + /// Creates a new symbol name from the raw underlying bytes. + pub fn new(bytes: &'a [u8]) -> SymbolName<'a> { + let str_bytes = str::from_utf8(bytes).ok(); + let demangled = str_bytes.and_then(|s| try_demangle(s).ok()); + + let cpp = if demangled.is_none() { + OptionCppSymbol::parse(bytes) + } else { + OptionCppSymbol::none() + }; + + SymbolName { + bytes: bytes, + demangled: demangled, + cpp_demangled: cpp, + } + } + + /// Returns the raw symbol name as a `str` if the symbols is valid utf-8. + pub fn as_str(&self) -> Option<&'a str> { + self.demangled + .as_ref() + .map(|s| s.as_str()) + .or_else(|| { + str::from_utf8(self.bytes).ok() + }) + } + + /// Returns the raw symbol name as a list of bytes + pub fn as_bytes(&self) -> &'a [u8] { + self.bytes + } +} + +cfg_if! { + if #[cfg(feature = "cpp_demangle")] { + impl<'a> fmt::Display for SymbolName<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if let Some(ref s) = self.demangled { + s.fmt(f) + } else if let Some(ref cpp) = self.cpp_demangled.0 { + cpp.fmt(f) + } else { + String::from_utf8_lossy(self.bytes).fmt(f) + } + } + } + } else { + impl<'a> fmt::Display for SymbolName<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if let Some(ref s) = self.demangled { + s.fmt(f) + } else { + String::from_utf8_lossy(self.bytes).fmt(f) + } + } + } + } +} + +cfg_if! { + if #[cfg(feature = "cpp_demangle")] { + impl<'a> fmt::Debug for SymbolName<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use std::fmt::Write; + + if let Some(ref s) = self.demangled { + return s.fmt(f) + } + + // This may to print if the demangled symbol isn't actually + // valid, so handle the error here gracefully by not propagating + // it outwards. + if let Some(ref cpp) = self.cpp_demangled.0 { + let mut s = String::new(); + if write!(s, "{}", cpp).is_ok() { + return s.fmt(f) + } + } + + String::from_utf8_lossy(self.bytes).fmt(f) + } + } + } else { + impl<'a> fmt::Debug for SymbolName<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if let Some(ref s) = self.demangled { + s.fmt(f) + } else { + String::from_utf8_lossy(self.bytes).fmt(f) + } + } + } + } +} + +cfg_if! { + if #[cfg(all(windows, feature = "dbghelp"))] { + mod dbghelp; + use self::dbghelp::resolve as resolve_imp; + use self::dbghelp::Symbol as SymbolImp; + } else if #[cfg(all(feature = "gimli-symbolize", + unix, + target_os = "linux"))] { + mod gimli; + use self::gimli::resolve as resolve_imp; + use self::gimli::Symbol as SymbolImp; + } else if #[cfg(all(feature = "libbacktrace", + unix, + not(target_os = "fuchsia"), + not(target_os = "emscripten"), + not(target_os = "macos"), + not(target_os = "ios")))] { + mod libbacktrace; + use self::libbacktrace::resolve as resolve_imp; + use self::libbacktrace::Symbol as SymbolImp; + + // Note that we only enable coresymbolication on iOS when debug assertions + // are enabled because it's helpful in debug mode but it looks like apps get + // rejected from the app store if they use this API, see #92 for more info + } else if #[cfg(all(feature = "coresymbolication", + any(target_os = "macos", + all(target_os = "ios", debug_assertions))))] { + mod coresymbolication; + use self::coresymbolication::resolve as resolve_imp; + use self::coresymbolication::Symbol as SymbolImp; + } else if #[cfg(all(unix, + not(target_os = "emscripten"), + feature = "dladdr"))] { + mod dladdr; + use self::dladdr::resolve as resolve_imp; + use self::dladdr::Symbol as SymbolImp; + } else { + mod noop; + use self::noop::resolve as resolve_imp; + use self::noop::Symbol as SymbolImp; + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/noop.rs cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/noop.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/src/symbolize/noop.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/src/symbolize/noop.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,27 @@ +use std::path::Path; +use std::os::raw::c_void; + +use SymbolName; + +pub fn resolve(_addr: *mut c_void, _cb: &mut FnMut(&super::Symbol)) { +} + +pub struct Symbol; + +impl Symbol { + pub fn name(&self) -> Option { + None + } + + pub fn addr(&self) -> Option<*mut c_void> { + None + } + + pub fn filename(&self) -> Option<&Path> { + None + } + + pub fn lineno(&self) -> Option { + None + } +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/tests/long_fn_name.rs cargo-0.26.0/vendor/backtrace-0.3.6/tests/long_fn_name.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/tests/long_fn_name.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/tests/long_fn_name.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,57 @@ +extern crate backtrace; + +#[cfg(all(windows, feature = "dbghelp"))] +extern crate winapi; + +use backtrace::Backtrace; + +// 50-character module name +mod _234567890_234567890_234567890_234567890_234567890 { + // 50-character struct name + #[allow(non_camel_case_types)] + pub struct _234567890_234567890_234567890_234567890_234567890(T); + impl _234567890_234567890_234567890_234567890_234567890 { + #[allow(dead_code)] + pub fn new() -> ::Backtrace { + ::Backtrace::new() + } + } +} + +// Long function names must be truncated to (MAX_SYM_NAME - 1) characters. +// Only run this test for msvc, since gnu prints "" for all frames. +#[test] +#[cfg(all(windows, feature = "dbghelp", target_env = "msvc"))] +fn test_long_fn_name() { + use winapi::um::dbghelp; + use _234567890_234567890_234567890_234567890_234567890:: + _234567890_234567890_234567890_234567890_234567890 as S; + + // 10 repetitions of struct name, so fully qualified function name is + // atleast 10 * (50 + 50) * 2 = 2000 characters long. + // It's actually longer since it also includes `::`, `<>` and the + // name of the current module + let bt = S::>>>>>>>>>::new(); + println!("{:?}", bt); + + let mut found_long_name_frame = false; + + for frame in bt.frames() { + let symbols = frame.symbols(); + if symbols.is_empty() { + continue; + } + + if let Some(function_name) = symbols[0].name() { + let function_name = function_name.as_str().unwrap(); + if function_name.contains( + "::_234567890_234567890_234567890_234567890_234567890") + { + found_long_name_frame = true; + assert_eq!(function_name.len(), dbghelp::MAX_SYM_NAME - 1); + } + } + } + + assert!(found_long_name_frame); +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/tests/smoke.rs cargo-0.26.0/vendor/backtrace-0.3.6/tests/smoke.rs --- cargo-0.25.0/vendor/backtrace-0.3.6/tests/smoke.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/tests/smoke.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,171 @@ +extern crate backtrace; + +use std::os::raw::c_void; +use std::thread; + +static LIBUNWIND: bool = cfg!(all(unix, feature = "libunwind")); +static UNIX_BACKTRACE: bool = cfg!(all(unix, feature = "unix-backtrace")); +static LIBBACKTRACE: bool = cfg!(all(unix, feature = "libbacktrace")) && + !cfg!(target_os = "fuchsia") && !cfg!(target_os = "macos") && + !cfg!(target_os = "ios"); +static CORESYMBOLICATION: bool = cfg!(all(any(target_os = "macos", target_os = "ios"), + feature = "coresymbolication")); +static DLADDR: bool = cfg!(all(unix, feature = "dladdr")) && !cfg!(target_os = "fuchsia"); +static DBGHELP: bool = cfg!(all(windows, feature = "dbghelp")); +static MSVC: bool = cfg!(target_env = "msvc"); +static GIMLI_SYMBOLIZE: bool = cfg!(all(feature = "gimli-symbolize", + unix, + target_os = "linux")); + +#[test] +fn smoke_test_frames() { + frame_1(line!()); + #[inline(never)] fn frame_1(start_line: u32) { frame_2(start_line) } + #[inline(never)] fn frame_2(start_line: u32) { frame_3(start_line) } + #[inline(never)] fn frame_3(start_line: u32) { frame_4(start_line) } + #[inline(never)] fn frame_4(start_line: u32) { + let mut v = Vec::new(); + backtrace::trace(|cx| { + v.push((cx.ip(), cx.symbol_address())); + true + }); + + if v.len() < 5 { + assert!(!LIBUNWIND); + assert!(!UNIX_BACKTRACE); + assert!(!DBGHELP); + return + } + + // On 32-bit windows apparently the first frame isn't our backtrace + // frame but it's actually this frame. I'm not entirely sure why, but at + // least it seems consistent? + let o = if cfg!(all(windows, target_pointer_width = "32")) {1} else {0}; + // frame offset 0 is the `backtrace::trace` function, but that's generic + assert_frame(&v, o, 1, frame_4 as usize, "frame_4", + "tests/smoke.rs", start_line + 6); + assert_frame(&v, o, 2, frame_3 as usize, "frame_3", "tests/smoke.rs", + start_line + 3); + assert_frame(&v, o, 3, frame_2 as usize, "frame_2", "tests/smoke.rs", + start_line + 2); + assert_frame(&v, o, 4, frame_1 as usize, "frame_1", "tests/smoke.rs", + start_line + 1); + assert_frame(&v, o, 5, smoke_test_frames as usize, + "smoke_test_frames", "", 0); + } + + fn assert_frame(syms: &[(*mut c_void, *mut c_void)], + offset: usize, + idx: usize, + actual_fn_pointer: usize, + expected_name: &str, + expected_file: &str, + expected_line: u32) { + if offset > idx { return } + let (ip, sym) = syms[idx - offset]; + let ip = ip as usize; + let sym = sym as usize; + assert!(ip >= sym); + assert!(sym >= actual_fn_pointer); + + // windows dbghelp is *quite* liberal (and wrong) in many of its reports + // right now... + if !DBGHELP { + assert!(sym - actual_fn_pointer < 1024); + } + + let mut resolved = 0; + let can_resolve = DLADDR || LIBBACKTRACE || CORESYMBOLICATION || DBGHELP || GIMLI_SYMBOLIZE; + + let mut name = None; + let mut addr = None; + let mut line = None; + let mut file = None; + backtrace::resolve(ip as *mut c_void, |sym| { + resolved += 1; + name = sym.name().map(|v| v.to_string()); + addr = sym.addr(); + line = sym.lineno(); + file = sym.filename().map(|v| v.to_path_buf()); + }); + + // dbghelp doesn't always resolve symbols right now + match resolved { + 0 => return assert!(!can_resolve || DBGHELP), + _ => {} + } + + // * linux dladdr doesn't work (only consults local symbol table) + // * windows dbghelp isn't great for GNU + if can_resolve && + !(cfg!(target_os = "linux") && DLADDR) && + !(DBGHELP && !MSVC) + { + let name = name.expect("didn't find a name"); + assert!(name.contains(expected_name), + "didn't find `{}` in `{}`", expected_name, name); + } + + if can_resolve { + addr.expect("didn't find a symbol"); + } + + if (LIBBACKTRACE || CORESYMBOLICATION || (DBGHELP && MSVC)) && cfg!(debug_assertions) { + let line = line.expect("didn't find a line number"); + let file = file.expect("didn't find a line number"); + if !expected_file.is_empty() { + assert!(file.ends_with(expected_file), + "{:?} didn't end with {:?}", file, expected_file); + } + if expected_line != 0 { + assert!(line == expected_line, + "bad line number on frame for `{}`: {} != {}", + expected_name, line, expected_line); + } + } + } +} + +#[test] +fn many_threads() { + let threads = (0..16).map(|_| { + thread::spawn(|| { + for _ in 0..16 { + backtrace::trace(|frame| { + backtrace::resolve(frame.ip(), |symbol| { + let _s = symbol.name().map(|s| s.to_string()); + }); + true + }); + } + }) + }).collect::>(); + + for t in threads { + t.join().unwrap() + } +} + +#[test] +#[cfg(feature = "rustc-serialize")] +fn is_rustc_serialize() { + extern crate rustc_serialize; + + fn is_encode() {} + fn is_decode() {} + + is_encode::(); + is_decode::(); +} + +#[test] +#[cfg(feature = "serde")] +fn is_serde() { + extern crate serde; + + fn is_serialize() {} + fn is_deserialize() {} + + is_serialize::(); + is_deserialize::(); +} diff -Nru cargo-0.25.0/vendor/backtrace-0.3.6/.travis.yml cargo-0.26.0/vendor/backtrace-0.3.6/.travis.yml --- cargo-0.25.0/vendor/backtrace-0.3.6/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/backtrace-0.3.6/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,60 @@ +language: rust +sudo: false + +matrix: + include: + - rust: 1.21.0 + - rust: stable + - os: osx + - rust: beta + - rust: nightly + + - rust: nightly + before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH + script: + - cargo doc --no-deps --all-features + after_success: + - travis-cargo --only nightly doc-upload + +dist: trusty + +addons: + sources: + # Provides clang-3.9 + - llvm-toolchain-trusty-3.9 + apt: + packages: + # Required for `bindgen`, which is required by `findshlibs`, which is + # required by the `gimli` feature. + - clang-3.9 + +script: + - cargo test + - cargo test --no-default-features + - cargo test --no-default-features --features 'libunwind' + - cargo test --no-default-features --features 'libunwind dladdr' + - cargo test --no-default-features --features 'libunwind libbacktrace' + - cargo test --no-default-features --features 'unix-backtrace' + - cargo test --no-default-features --features 'unix-backtrace dladdr' + - cargo test --no-default-features --features 'unix-backtrace libbacktrace' + - cargo test --no-default-features --features 'serialize-serde' + - cargo test --no-default-features --features 'serialize-rustc' + - cargo test --no-default-features --features 'serialize-rustc serialize-serde' + - cargo test --no-default-features --features 'cpp_demangle' + - cargo test --no-default-features --features 'gimli-symbolize' + - cd ./cpp_smoke_test && cargo test && cd .. + - cargo clean && cargo build + +notifications: + email: + on_success: never + +after_success: + - travis-cargo --only nightly doc-upload + +env: + global: + # serde-codegen has historically needed a large stack to expand + - RUST_MIN_STACK=16777216 + - secure: "Kuf3j6gC3MhR+F7g8/5J4+3tu+FXJP/SqKjsUVVjs/qjniIVX3MwZPhtP/pVtdRvYjW0NzLw5Nufb4o1cyY4uKwR8BHHNuEUE/h3mPShjWHqzLyn5QiBumPozsFCa32H4gconRmp3+s0YrBT7nLoGvUZZS0dkldMkpvvrPL/yUKXLS8HEP4L1GO5iMQQYG6i3sbWTbHikE6ZQogW/iZommyqUkVB/s/SQvdH9SXu89ttNXlm/F+EIsgsgyzpbULp5sD34GRDPJe+H1m+sgA1kTRrzmuBGNmz9mx6GyIKaqACTm1gRcb06nFjTPVTQioJBNnoV7TEqZCvjuSsUjcGmP4Aeissafo93ADzV+bd0uoWIScE9ltSVS+RgCDV+sd0GHz5U6FjhgZp0amaVl3d6hPp8lbTfK/gfj1i9ktQfKZbG7rB4tfIU1KeQRkyE9vb/TaKp8nwBbc4SVQ4EKFOlRbE1S1FooaKZweW8w57d2u+sMMMVJbO28/Ap8tk9xDSOl4shPaT0iM0U9/heF8FmCZB1OKXLKn6TAaNFnaMTvdTHl+Tjrf6Vzd/oPXJ7GuaB6eLxXYjXvZHuKiLkSZriOzhL7PbijNILbSgZt7+Fa0vcnXP8zgD4dmupx/CoIHLN9NP4o9cGXuBcaJ/iFryJ4i5LKGFNEUHtXkavDrcgcA=" diff -Nru cargo-0.25.0/vendor/cc-1.0.10/appveyor.yml cargo-0.26.0/vendor/cc-1.0.10/appveyor.yml --- cargo-0.25.0/vendor/cc-1.0.10/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,55 @@ +environment: + + # At the time this was added AppVeyor was having troubles with checking + # revocation of SSL certificates of sites like static.rust-lang.org and what + # we think is crates.io. The libcurl HTTP client by default checks for + # revocation on Windows and according to a mailing list [1] this can be + # disabled. + # + # The `CARGO_HTTP_CHECK_REVOKE` env var here tells cargo to disable SSL + # revocation checking on Windows in libcurl. Note, though, that rustup, which + # we're using to download Rust here, also uses libcurl as the default backend. + # Unlike Cargo, however, rustup doesn't have a mechanism to disable revocation + # checking. To get rustup working we set `RUSTUP_USE_HYPER` which forces it to + # use the Hyper instead of libcurl backend. Both Hyper and libcurl use + # schannel on Windows but it appears that Hyper configures it slightly + # differently such that revocation checking isn't turned on by default. + # + # [1]: https://curl.haxx.se/mail/lib-2016-03/0202.html + RUSTUP_USE_HYPER: 1 + CARGO_HTTP_CHECK_REVOKE: false + + matrix: + - TARGET: x86_64-pc-windows-msvc + ARCH: amd64 + VS: C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat + - TARGET: x86_64-pc-windows-msvc + ARCH: amd64 + VS: C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat + - TARGET: i686-pc-windows-msvc + ARCH: x86 + VS: C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat + - TARGET: i686-pc-windows-msvc + ARCH: x86 + VS: C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat + - TARGET: x86_64-pc-windows-gnu + MSYS_BITS: 64 + - TARGET: i686-pc-windows-gnu + MSYS_BITS: 32 +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - if defined VS call "%VS%" %ARCH% + - set PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - if defined MSYS_BITS set PATH=%PATH%;C:\msys64\mingw%MSYS_BITS%\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --target %TARGET% + - cargo test --features parallel --target %TARGET% + - cargo test --manifest-path cc-test/Cargo.toml --target %TARGET% + - cargo test --manifest-path cc-test/Cargo.toml --features parallel --target %TARGET% + - cargo test --manifest-path cc-test/Cargo.toml --release --target %TARGET% diff -Nru cargo-0.25.0/vendor/cc-1.0.10/.cargo-checksum.json cargo-0.26.0/vendor/cc-1.0.10/.cargo-checksum.json --- cargo-0.25.0/vendor/cc-1.0.10/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"8b9d2900f78631a5876dc5d6c9033ede027253efcd33dd36b1309fc6cab97ee0"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/cc-1.0.10/Cargo.toml cargo-0.26.0/vendor/cc-1.0.10/Cargo.toml --- cargo-0.25.0/vendor/cc-1.0.10/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,37 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "cc" +version = "1.0.10" +authors = ["Alex Crichton "] +description = "A build-time dependency for Cargo build scripts to assist in invoking the native\nC compiler to compile native C code into a static archive to be linked into Rust\ncode.\n" +homepage = "https://github.com/alexcrichton/cc-rs" +documentation = "https://docs.rs/cc" +readme = "README.md" +keywords = ["build-dependencies"] +categories = ["development-tools"] +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/cc-rs" +[dependencies.rayon] +version = "1.0" +optional = true +[dev-dependencies.tempdir] +version = "0.3" + +[features] +parallel = ["rayon"] +[badges.appveyor] +repository = "alexcrichton/cc-rs" + +[badges.travis-ci] +repository = "alexcrichton/cc-rs" diff -Nru cargo-0.25.0/vendor/cc-1.0.10/LICENSE-APACHE cargo-0.26.0/vendor/cc-1.0.10/LICENSE-APACHE --- cargo-0.25.0/vendor/cc-1.0.10/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/cc-1.0.10/LICENSE-MIT cargo-0.26.0/vendor/cc-1.0.10/LICENSE-MIT --- cargo-0.25.0/vendor/cc-1.0.10/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +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. diff -Nru cargo-0.25.0/vendor/cc-1.0.10/README.md cargo-0.26.0/vendor/cc-1.0.10/README.md --- cargo-0.25.0/vendor/cc-1.0.10/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,202 @@ +# cc-rs + +A library to compile C/C++/assembly into a Rust library/application. + +[![Build Status](https://travis-ci.org/alexcrichton/cc-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/cc-rs) +[![Build status](https://ci.appveyor.com/api/projects/status/onu270iw98h81nwv?svg=true)](https://ci.appveyor.com/project/alexcrichton/cc-rs) + +[Documentation](https://docs.rs/cc) + +A simple library meant to be used as a build dependency with Cargo packages in +order to build a set of C/C++ files into a static archive. This crate calls out +to the most relevant compiler for a platform, for example using `cl` on MSVC. + +> **Note**: this crate was recently renamed from the `gcc` crate, so if you're +> looking for the `gcc` crate you're in the right spot! + +## Using cc-rs + +First, you'll want to both add a build script for your crate (`build.rs`) and +also add this crate to your `Cargo.toml` via: + +```toml +[build-dependencies] +cc = "1.0" +``` + +Next up, you'll want to write a build script like so: + +```rust,no_run +// build.rs + +extern crate cc; + +fn main() { + cc::Build::new() + .file("foo.c") + .file("bar.c") + .compile("foo"); +} +``` + +And that's it! Running `cargo build` should take care of the rest and your Rust +application will now have the C files `foo.c` and `bar.c` compiled into a file +named libfoo.a. You can call the functions in Rust by declaring functions in +your Rust code like so: + +``` +extern { + fn foo_function(); + fn bar_function(); +} + +pub fn call() { + unsafe { + foo_function(); + bar_function(); + } +} + +fn main() { + // ... +} +``` + +## External configuration via environment variables + +To control the programs and flags used for building, the builder can set a +number of different environment variables. + +* `CFLAGS` - a series of space separated flags passed to compilers. Note that + individual flags cannot currently contain spaces, so doing + something like: "-L=foo\ bar" is not possible. +* `CC` - the actual C compiler used. Note that this is used as an exact + executable name, so (for example) no extra flags can be passed inside + this variable, and the builder must ensure that there aren't any + trailing spaces. This compiler must understand the `-c` flag. For + certain `TARGET`s, it also is assumed to know about other flags (most + common is `-fPIC`). +* `AR` - the `ar` (archiver) executable to use to build the static library. + +Each of these variables can also be supplied with certain prefixes and suffixes, +in the following prioritized order: + +1. `_` - for example, `CC_x86_64-unknown-linux-gnu` +2. `_` - for example, `CC_x86_64_unknown_linux_gnu` +3. `_` - for example, `HOST_CC` or `TARGET_CFLAGS` +4. `` - a plain `CC`, `AR` as above. + +If none of these variables exist, cc-rs uses built-in defaults + +In addition to the the above optional environment variables, `cc-rs` has some +functions with hard requirements on some variables supplied by [cargo's +build-script driver][cargo] that it has the `TARGET`, `OUT_DIR`, `OPT_LEVEL`, +and `HOST` variables. + +[cargo]: http://doc.crates.io/build-script.html#inputs-to-the-build-script + +## Optional features + +### Parallel + +Currently cc-rs supports parallel compilation (think `make -jN`) but this +feature is turned off by default. To enable cc-rs to compile C/C++ in parallel, +you can change your dependency to: + +```toml +[build-dependencies] +cc = { version = "1.0", features = ["parallel"] } +``` + +By default cc-rs will limit parallelism to `$NUM_JOBS`, or if not present it +will limit it to the number of cpus on the machine. If you are using cargo, +use `-jN` option of `build`, `test` and `run` commands as `$NUM_JOBS` +is supplied by cargo. + +## Compile-time Requirements + +To work properly this crate needs access to a C compiler when the build script +is being run. This crate does not ship a C compiler with it. The compiler +required varies per platform, but there are three broad categories: + +* Unix platforms require `cc` to be the C compiler. This can be found by + installing cc/clang on Linux distributions and Xcode on OSX, for example. +* Windows platforms targeting MSVC (e.g. your target triple ends in `-msvc`) + require `cl.exe` to be available and in `PATH`. This is typically found in + standard Visual Studio installations and the `PATH` can be set up by running + the appropriate developer tools shell. +* Windows platforms targeting MinGW (e.g. your target triple ends in `-gnu`) + require `cc` to be available in `PATH`. We recommend the + [MinGW-w64](http://mingw-w64.org) distribution, which is using the + [Win-builds](http://win-builds.org) installation system. + You may also acquire it via + [MSYS2](http://msys2.github.io), as explained [here][msys2-help]. Make sure + to install the appropriate architecture corresponding to your installation of + rustc. GCC from older [MinGW](http://www.mingw.org) project is compatible + only with 32-bit rust compiler. + +[msys2-help]: http://github.com/rust-lang/rust#building-on-windows + +## C++ support + +`cc-rs` supports C++ libraries compilation by using the `cpp` method on +`Build`: + +```rust,no_run +extern crate cc; + +fn main() { + cc::Build::new() + .cpp(true) // Switch to C++ library compilation. + .file("foo.cpp") + .compile("libfoo.a"); +} +``` + +When using C++ library compilation switch, the `CXX` and `CXXFLAGS` env +variables are used instead of `CC` and `CFLAGS` and the C++ standard library is +linked to the crate target. + +## CUDA C++ support + +`cc-rs` also supports compiling CUDA C++ libraries by using the `cuda` method +on `Build` (currently for GNU/Clang toolchains only): + +```rust,no_run +extern crate cc; + +fn main() { + cc::Build::new() + // Switch to CUDA C++ library compilation using NVCC. + .cuda(true) + // Generate code for Maxwell (GTX 970, 980, 980 Ti, Titan X). + .flag("-gencode").flag("arch=compute_52,code=sm_52") + // Generate code for Maxwell (Jetson TX1). + .flag("-gencode").flag("arch=compute_53,code=sm_53") + // Generate code for Pascal (GTX 1070, 1080, 1080 Ti, Titan Xp). + .flag("-gencode").flag("arch=compute_61,code=sm_61") + // Generate code for Pascal (Tesla P100). + .flag("-gencode").flag("arch=compute_60,code=sm_60") + // Generate code for Pascal (Jetson TX2). + .flag("-gencode").flag("arch=compute_62,code=sm_62") + .file("bar.cu") + .compile("libbar.a"); +} +``` + +## License + +This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/cc-1.0.10/src/bin/gcc-shim.rs cargo-0.26.0/vendor/cc-1.0.10/src/bin/gcc-shim.rs --- cargo-0.25.0/vendor/cc-1.0.10/src/bin/gcc-shim.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/src/bin/gcc-shim.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,23 @@ +#![cfg_attr(test, allow(dead_code))] + +use std::env; +use std::fs::File; +use std::io::prelude::*; +use std::path::PathBuf; + +fn main() { + let out_dir = PathBuf::from(env::var_os("GCCTEST_OUT_DIR").unwrap()); + for i in 0.. { + let candidate = out_dir.join(format!("out{}", i)); + if candidate.exists() { + continue; + } + let mut f = File::create(candidate).unwrap(); + for arg in env::args().skip(1) { + writeln!(f, "{}", arg).unwrap(); + } + + File::create(out_dir.join("libfoo.a")).unwrap(); + break; + } +} diff -Nru cargo-0.25.0/vendor/cc-1.0.10/src/com.rs cargo-0.26.0/vendor/cc-1.0.10/src/com.rs --- cargo-0.25.0/vendor/cc-1.0.10/src/com.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/src/com.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,155 @@ +// Copyright © 2017 winapi-rs developers +// Licensed under the Apache License, Version 2.0 +// or the MIT license +// , at your option. +// All files in the project carrying such notice may not be copied, modified, or distributed +// except according to those terms. + +#![allow(unused)] + +use std::ffi::{OsStr, OsString}; +use std::mem::forget; +use std::ops::Deref; +use std::os::windows::ffi::{OsStrExt, OsStringExt}; +use std::ptr::null_mut; +use std::slice::from_raw_parts; +use winapi::Interface; +use winapi::BSTR; +use winapi::CoInitializeEx; +use winapi::COINIT_MULTITHREADED; +use winapi::{SysFreeString, SysStringLen}; +use winapi::IUnknown; +use winapi::{HRESULT, S_FALSE, S_OK}; + +pub fn initialize() -> Result<(), HRESULT> { + let err = unsafe { CoInitializeEx(null_mut(), COINIT_MULTITHREADED) }; + if err != S_OK && err != S_FALSE { + // S_FALSE just means COM is already initialized + return Err(err); + } + Ok(()) +} + +pub struct ComPtr(*mut T) +where + T: Interface; +impl ComPtr +where + T: Interface, +{ + /// Creates a `ComPtr` to wrap a raw pointer. + /// It takes ownership over the pointer which means it does __not__ call `AddRef`. + /// `T` __must__ be a COM interface that inherits from `IUnknown`. + pub unsafe fn from_raw(ptr: *mut T) -> ComPtr { + assert!(!ptr.is_null()); + ComPtr(ptr) + } + /// Casts up the inheritance chain + pub fn up(self) -> ComPtr + where + T: Deref, + U: Interface, + { + ComPtr(self.into_raw() as *mut U) + } + /// Extracts the raw pointer. + /// You are now responsible for releasing it yourself. + pub fn into_raw(self) -> *mut T { + let p = self.0; + forget(self); + p + } + /// For internal use only. + fn as_unknown(&self) -> &IUnknown { + unsafe { &*(self.0 as *mut IUnknown) } + } + /// Performs QueryInterface fun. + pub fn cast(&self) -> Result, i32> + where + U: Interface, + { + let mut obj = null_mut(); + let err = unsafe { self.as_unknown().QueryInterface(&U::uuidof(), &mut obj) }; + if err < 0 { + return Err(err); + } + Ok(unsafe { ComPtr::from_raw(obj as *mut U) }) + } +} +impl Deref for ComPtr +where + T: Interface, +{ + type Target = T; + fn deref(&self) -> &T { + unsafe { &*self.0 } + } +} +impl Clone for ComPtr +where + T: Interface, +{ + fn clone(&self) -> Self { + unsafe { + self.as_unknown().AddRef(); + ComPtr::from_raw(self.0) + } + } +} +impl Drop for ComPtr +where + T: Interface, +{ + fn drop(&mut self) { + unsafe { + self.as_unknown().Release(); + } + } +} +pub struct BStr(BSTR); +impl BStr { + pub unsafe fn from_raw(s: BSTR) -> BStr { + BStr(s) + } + pub fn to_osstring(&self) -> OsString { + let len = unsafe { SysStringLen(self.0) }; + let slice = unsafe { from_raw_parts(self.0, len as usize) }; + OsStringExt::from_wide(slice) + } +} +impl Drop for BStr { + fn drop(&mut self) { + unsafe { SysFreeString(self.0) }; + } +} + +pub trait ToWide { + fn to_wide(&self) -> Vec; + fn to_wide_null(&self) -> Vec; +} +impl ToWide for T +where + T: AsRef, +{ + fn to_wide(&self) -> Vec { + self.as_ref().encode_wide().collect() + } + fn to_wide_null(&self) -> Vec { + self.as_ref().encode_wide().chain(Some(0)).collect() + } +} +pub trait FromWide +where + Self: Sized, +{ + fn from_wide(wide: &[u16]) -> Self; + fn from_wide_null(wide: &[u16]) -> Self { + let len = wide.iter().take_while(|&&c| c != 0).count(); + Self::from_wide(&wide[..len]) + } +} +impl FromWide for OsString { + fn from_wide(wide: &[u16]) -> OsString { + OsStringExt::from_wide(wide) + } +} diff -Nru cargo-0.25.0/vendor/cc-1.0.10/src/lib.rs cargo-0.26.0/vendor/cc-1.0.10/src/lib.rs --- cargo-0.25.0/vendor/cc-1.0.10/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2098 @@ +//! A library for build scripts to compile custom C code +//! +//! This library is intended to be used as a `build-dependencies` entry in +//! `Cargo.toml`: +//! +//! ```toml +//! [build-dependencies] +//! cc = "1.0" +//! ``` +//! +//! The purpose of this crate is to provide the utility functions necessary to +//! compile C code into a static archive which is then linked into a Rust crate. +//! Configuration is available through the `Build` struct. +//! +//! This crate will automatically detect situations such as cross compilation or +//! other environment variables set by Cargo and will build code appropriately. +//! +//! The crate is not limited to C code, it can accept any source code that can +//! be passed to a C or C++ compiler. As such, assembly files with extensions +//! `.s` (gcc/clang) and `.asm` (MSVC) can also be compiled. +//! +//! [`Build`]: struct.Build.html +//! +//! # Parallelism +//! +//! To parallelize computation, enable the `parallel` feature for the crate. +//! +//! ```toml +//! [build-dependencies] +//! cc = { version = "1.0", features = ["parallel"] } +//! ``` +//! To specify the max number of concurrent compilation jobs, set the `NUM_JOBS` +//! environment variable to the desired amount. +//! +//! Cargo will also set this environment variable when executed with the `-jN` flag. +//! +//! If `NUM_JOBS` is not set, the `RAYON_NUM_THREADS` environment variable can +//! also specify the build paralellism. +//! +//! # Examples +//! +//! Use the `Build` struct to compile `src/foo.c`: +//! +//! ```no_run +//! extern crate cc; +//! +//! fn main() { +//! cc::Build::new() +//! .file("src/foo.c") +//! .define("FOO", Some("bar")) +//! .include("src") +//! .compile("foo"); +//! } +//! ``` + +#![doc(html_root_url = "https://docs.rs/cc/1.0")] +#![cfg_attr(test, deny(warnings))] +#![deny(missing_docs)] + +#[cfg(feature = "parallel")] +extern crate rayon; + +use std::env; +use std::ffi::{OsStr, OsString}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::thread::{self, JoinHandle}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +// These modules are all glue to support reading the MSVC version from +// the registry and from COM interfaces +#[cfg(windows)] +mod registry; +#[cfg(windows)] +#[macro_use] +mod winapi; +#[cfg(windows)] +mod com; +#[cfg(windows)] +mod setup_config; + +pub mod windows_registry; + +/// A builder for compilation of a native static library. +/// +/// A `Build` is the main type of the `cc` crate and is used to control all the +/// various configuration options and such of a compile. You'll find more +/// documentation on each method itself. +#[derive(Clone, Debug)] +pub struct Build { + include_directories: Vec, + definitions: Vec<(String, Option)>, + objects: Vec, + flags: Vec, + flags_supported: Vec, + known_flag_support_status: Arc>>, + files: Vec, + cpp: bool, + cpp_link_stdlib: Option>, + cpp_set_stdlib: Option, + cuda: bool, + target: Option, + host: Option, + out_dir: Option, + opt_level: Option, + debug: Option, + env: Vec<(OsString, OsString)>, + compiler: Option, + archiver: Option, + cargo_metadata: bool, + pic: Option, + static_crt: Option, + shared_flag: Option, + static_flag: Option, + warnings_into_errors: bool, + warnings: bool, +} + +/// Represents the types of errors that may occur while using cc-rs. +#[derive(Clone, Debug)] +enum ErrorKind { + /// Error occurred while performing I/O. + IOError, + /// Invalid architecture supplied. + ArchitectureInvalid, + /// Environment variable not found, with the var in question as extra info. + EnvVarNotFound, + /// Error occurred while using external tools (ie: invocation of compiler). + ToolExecError, + /// Error occurred due to missing external tools. + ToolNotFound, +} + +/// Represents an internal error that occurred, with an explanation. +#[derive(Clone, Debug)] +pub struct Error { + /// Describes the kind of error that occurred. + kind: ErrorKind, + /// More explanation of error that occurred. + message: String, +} + +impl Error { + fn new(kind: ErrorKind, message: &str) -> Error { + Error { + kind: kind, + message: message.to_owned(), + } + } +} + +impl From for Error { + fn from(e: io::Error) -> Error { + Error::new(ErrorKind::IOError, &format!("{}", e)) + } +} + +/// Configuration used to represent an invocation of a C compiler. +/// +/// This can be used to figure out what compiler is in use, what the arguments +/// to it are, and what the environment variables look like for the compiler. +/// This can be used to further configure other build systems (e.g. forward +/// along CC and/or CFLAGS) or the `to_command` method can be used to run the +/// compiler itself. +#[derive(Clone, Debug)] +pub struct Tool { + path: PathBuf, + cc_wrapper_path: Option, + cc_wrapper_args: Vec, + args: Vec, + env: Vec<(OsString, OsString)>, + family: ToolFamily, + cuda: bool, +} + +/// Represents the family of tools this tool belongs to. +/// +/// Each family of tools differs in how and what arguments they accept. +/// +/// Detection of a family is done on best-effort basis and may not accurately reflect the tool. +#[derive(Copy, Clone, Debug, PartialEq)] +enum ToolFamily { + /// Tool is GNU Compiler Collection-like. + Gnu, + /// Tool is Clang-like. It differs from the GCC in a sense that it accepts superset of flags + /// and its cross-compilation approach is different. + Clang, + /// Tool is the MSVC cl.exe. + Msvc, +} + +impl ToolFamily { + /// What the flag to request debug info for this family of tools look like + fn debug_flag(&self) -> &'static str { + match *self { + ToolFamily::Msvc => "/Z7", + ToolFamily::Gnu | ToolFamily::Clang => "-g", + } + } + + /// What the flag to include directories into header search path looks like + fn include_flag(&self) -> &'static str { + match *self { + ToolFamily::Msvc => "/I", + ToolFamily::Gnu | ToolFamily::Clang => "-I", + } + } + + /// What the flag to request macro-expanded source output looks like + fn expand_flag(&self) -> &'static str { + match *self { + ToolFamily::Msvc => "/E", + ToolFamily::Gnu | ToolFamily::Clang => "-E", + } + } + + /// What the flags to enable all warnings + fn warnings_flags(&self) -> &'static [&'static str] { + static MSVC_FLAGS: &'static [&'static str] = &["/W4"]; + static GNU_CLANG_FLAGS: &'static [&'static str] = &["-Wall", "-Wextra"]; + + match *self { + ToolFamily::Msvc => &MSVC_FLAGS, + ToolFamily::Gnu | ToolFamily::Clang => &GNU_CLANG_FLAGS, + } + } + + /// What the flag to turn warning into errors + fn warnings_to_errors_flag(&self) -> &'static str { + match *self { + ToolFamily::Msvc => "/WX", + ToolFamily::Gnu | ToolFamily::Clang => "-Werror", + } + } + + /// NVCC-specific. Device code debug info flag. This is separate from the + /// debug info flag passed to the C++ compiler. + fn nvcc_debug_flag(&self) -> &'static str { + match *self { + ToolFamily::Msvc => unimplemented!(), + ToolFamily::Gnu | ToolFamily::Clang => "-G", + } + } + + /// NVCC-specific. Redirect the following flag to the underlying C++ + /// compiler. + fn nvcc_redirect_flag(&self) -> &'static str { + match *self { + ToolFamily::Msvc => unimplemented!(), + ToolFamily::Gnu | ToolFamily::Clang => "-Xcompiler", + } + } +} + +/// Represents an object. +/// +/// This is a source file -> object file pair. +#[derive(Clone, Debug)] +struct Object { + src: PathBuf, + dst: PathBuf, +} + +impl Object { + /// Create a new source file -> object file pair. + fn new(src: PathBuf, dst: PathBuf) -> Object { + Object { src: src, dst: dst } + } +} + +impl Build { + /// Construct a new instance of a blank set of configuration. + /// + /// This builder is finished with the [`compile`] function. + /// + /// [`compile`]: struct.Build.html#method.compile + pub fn new() -> Build { + Build { + include_directories: Vec::new(), + definitions: Vec::new(), + objects: Vec::new(), + flags: Vec::new(), + flags_supported: Vec::new(), + known_flag_support_status: Arc::new(Mutex::new(HashMap::new())), + files: Vec::new(), + shared_flag: None, + static_flag: None, + cpp: false, + cpp_link_stdlib: None, + cpp_set_stdlib: None, + cuda: false, + target: None, + host: None, + out_dir: None, + opt_level: None, + debug: None, + env: Vec::new(), + compiler: None, + archiver: None, + cargo_metadata: true, + pic: None, + static_crt: None, + warnings: true, + warnings_into_errors: false, + } + } + + /// Add a directory to the `-I` or include path for headers + /// + /// # Example + /// + /// ```no_run + /// use std::path::Path; + /// + /// let library_path = Path::new("/path/to/library"); + /// + /// cc::Build::new() + /// .file("src/foo.c") + /// .include(library_path) + /// .include("src") + /// .compile("foo"); + /// ``` + pub fn include>(&mut self, dir: P) -> &mut Build { + self.include_directories.push(dir.as_ref().to_path_buf()); + self + } + + /// Specify a `-D` variable with an optional value. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .define("FOO", "BAR") + /// .define("BAZ", None) + /// .compile("foo"); + /// ``` + pub fn define<'a, V: Into>>(&mut self, var: &str, val: V) -> &mut Build { + self.definitions + .push((var.to_string(), val.into().map(|s| s.to_string()))); + self + } + + /// Add an arbitrary object file to link in + pub fn object>(&mut self, obj: P) -> &mut Build { + self.objects.push(obj.as_ref().to_path_buf()); + self + } + + /// Add an arbitrary flag to the invocation of the compiler + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .flag("-ffunction-sections") + /// .compile("foo"); + /// ``` + pub fn flag(&mut self, flag: &str) -> &mut Build { + self.flags.push(flag.to_string()); + self + } + + fn ensure_check_file(&self) -> Result { + let out_dir = self.get_out_dir()?; + let src = if self.cuda { + assert!(self.cpp); + out_dir.join("flag_check.cu") + } else if self.cpp { + out_dir.join("flag_check.cpp") + } else { + out_dir.join("flag_check.c") + }; + + if !src.exists() { + let mut f = fs::File::create(&src)?; + write!(f, "int main(void) {{ return 0; }}")?; + } + + Ok(src) + } + + /// Run the compiler to test if it accepts the given flag. + /// + /// For a convenience method for setting flags conditionally, + /// see `flag_if_supported()`. + /// + /// It may return error if it's unable to run the compilier with a test file + /// (e.g. the compiler is missing or a write to the `out_dir` failed). + /// + /// Note: Once computed, the result of this call is stored in the + /// `known_flag_support` field. If `is_flag_supported(flag)` + /// is called again, the result will be read from the hash table. + pub fn is_flag_supported(&self, flag: &str) -> Result { + let mut known_status = self.known_flag_support_status.lock().unwrap(); + if let Some(is_supported) = known_status.get(flag).cloned() { + return Ok(is_supported); + } + + let out_dir = self.get_out_dir()?; + let src = self.ensure_check_file()?; + let obj = out_dir.join("flag_check"); + let target = self.get_target()?; + let mut cfg = Build::new(); + cfg.flag(flag) + .target(&target) + .opt_level(0) + .host(&target) + .debug(false) + .cpp(self.cpp) + .cuda(self.cuda); + let compiler = cfg.try_get_compiler()?; + let mut cmd = compiler.to_command(); + let is_arm = target.contains("aarch64") || target.contains("arm"); + command_add_output_file(&mut cmd, &obj, target.contains("msvc"), false, is_arm); + + // We need to explicitly tell msvc not to link and create an exe + // in the root directory of the crate + if target.contains("msvc") { + cmd.arg("/c"); + } + + cmd.arg(&src); + + let output = cmd.output()?; + let is_supported = output.stderr.is_empty(); + + known_status.insert(flag.to_owned(), is_supported); + Ok(is_supported) + } + + /// Add an arbitrary flag to the invocation of the compiler if it supports it + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .flag_if_supported("-Wlogical-op") // only supported by GCC + /// .flag_if_supported("-Wunreachable-code") // only supported by clang + /// .compile("foo"); + /// ``` + pub fn flag_if_supported(&mut self, flag: &str) -> &mut Build { + self.flags_supported.push(flag.to_string()); + self + } + + /// Set the `-shared` flag. + /// + /// When enabled, the compiler will produce a shared object which can + /// then be linked with other objects to form an executable. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .shared_flag(true) + /// .compile("libfoo.so"); + /// ``` + + pub fn shared_flag(&mut self, shared_flag: bool) -> &mut Build { + self.shared_flag = Some(shared_flag); + self + } + + /// Set the `-static` flag. + /// + /// When enabled on systems that support dynamic linking, this prevents + /// linking with the shared libraries. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .shared_flag(true) + /// .static_flag(true) + /// .compile("foo"); + /// ``` + pub fn static_flag(&mut self, static_flag: bool) -> &mut Build { + self.static_flag = Some(static_flag); + self + } + + /// Add a file which will be compiled + pub fn file>(&mut self, p: P) -> &mut Build { + self.files.push(p.as_ref().to_path_buf()); + self + } + + /// Add files which will be compiled + pub fn files

(&mut self, p: P) -> &mut Build + where + P: IntoIterator, + P::Item: AsRef, + { + for file in p.into_iter() { + self.file(file); + } + self + } + + /// Set C++ support. + /// + /// The other `cpp_*` options will only become active if this is set to + /// `true`. + pub fn cpp(&mut self, cpp: bool) -> &mut Build { + self.cpp = cpp; + self + } + + /// Set CUDA C++ support. + /// + /// Enabling CUDA will pass the detected C/C++ toolchain as an argument to + /// the CUDA compiler, NVCC. NVCC itself accepts some limited GNU-like args; + /// any other arguments for the C/C++ toolchain will be redirected using + /// "-Xcompiler" flags. + /// + /// If enabled, this also implicitly enables C++ support. + pub fn cuda(&mut self, cuda: bool) -> &mut Build { + self.cuda = cuda; + if cuda { + self.cpp = true; + } + self + } + + /// Set warnings into errors flag. + /// + /// Disabled by default. + /// + /// Warning: turning warnings into errors only make sense + /// if you are a developer of the crate using cc-rs. + /// Some warnings only appear on some architecture or + /// specific version of the compiler. Any user of this crate, + /// or any other crate depending on it, could fail during + /// compile time. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .warnings_into_errors(true) + /// .compile("libfoo.a"); + /// ``` + pub fn warnings_into_errors(&mut self, warnings_into_errors: bool) -> &mut Build { + self.warnings_into_errors = warnings_into_errors; + self + } + + /// Set warnings flags. + /// + /// Adds some flags: + /// - "/Wall" for MSVC. + /// - "-Wall", "-Wextra" for GNU and Clang. + /// + /// Enabled by default. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .warnings(false) + /// .compile("libfoo.a"); + /// ``` + pub fn warnings(&mut self, warnings: bool) -> &mut Build { + self.warnings = warnings; + self + } + + /// Set the standard library to link against when compiling with C++ + /// support. + /// + /// The default value of this property depends on the current target: On + /// OS X `Some("c++")` is used, when compiling for a Visual Studio based + /// target `None` is used and for other targets `Some("stdc++")` is used. + /// If the `CXXSTDLIB` environment variable is set, its value will + /// override the default value. + /// + /// A value of `None` indicates that no automatic linking should happen, + /// otherwise cargo will link against the specified library. + /// + /// The given library name must not contain the `lib` prefix. + /// + /// Common values: + /// - `stdc++` for GNU + /// - `c++` for Clang + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .shared_flag(true) + /// .cpp_link_stdlib("stdc++") + /// .compile("libfoo.so"); + /// ``` + pub fn cpp_link_stdlib<'a, V: Into>>( + &mut self, + cpp_link_stdlib: V, + ) -> &mut Build { + self.cpp_link_stdlib = Some(cpp_link_stdlib.into().map(|s| s.into())); + self + } + + /// Force the C++ compiler to use the specified standard library. + /// + /// Setting this option will automatically set `cpp_link_stdlib` to the same + /// value. + /// + /// The default value of this option is always `None`. + /// + /// This option has no effect when compiling for a Visual Studio based + /// target. + /// + /// This option sets the `-stdlib` flag, which is only supported by some + /// compilers (clang, icc) but not by others (gcc). The library will not + /// detect which compiler is used, as such it is the responsibility of the + /// caller to ensure that this option is only used in conjuction with a + /// compiler which supports the `-stdlib` flag. + /// + /// A value of `None` indicates that no specific C++ standard library should + /// be used, otherwise `-stdlib` is added to the compile invocation. + /// + /// The given library name must not contain the `lib` prefix. + /// + /// Common values: + /// - `stdc++` for GNU + /// - `c++` for Clang + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .cpp_set_stdlib("c++") + /// .compile("libfoo.a"); + /// ``` + pub fn cpp_set_stdlib<'a, V: Into>>( + &mut self, + cpp_set_stdlib: V, + ) -> &mut Build { + let cpp_set_stdlib = cpp_set_stdlib.into(); + self.cpp_set_stdlib = cpp_set_stdlib.map(|s| s.into()); + self.cpp_link_stdlib(cpp_set_stdlib); + self + } + + /// Configures the target this configuration will be compiling for. + /// + /// This option is automatically scraped from the `TARGET` environment + /// variable by build scripts, so it's not required to call this function. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .target("aarch64-linux-android") + /// .compile("foo"); + /// ``` + pub fn target(&mut self, target: &str) -> &mut Build { + self.target = Some(target.to_string()); + self + } + + /// Configures the host assumed by this configuration. + /// + /// This option is automatically scraped from the `HOST` environment + /// variable by build scripts, so it's not required to call this function. + /// + /// # Example + /// + /// ```no_run + /// cc::Build::new() + /// .file("src/foo.c") + /// .host("arm-linux-gnueabihf") + /// .compile("foo"); + /// ``` + pub fn host(&mut self, host: &str) -> &mut Build { + self.host = Some(host.to_string()); + self + } + + /// Configures the optimization level of the generated object files. + /// + /// This option is automatically scraped from the `OPT_LEVEL` environment + /// variable by build scripts, so it's not required to call this function. + pub fn opt_level(&mut self, opt_level: u32) -> &mut Build { + self.opt_level = Some(opt_level.to_string()); + self + } + + /// Configures the optimization level of the generated object files. + /// + /// This option is automatically scraped from the `OPT_LEVEL` environment + /// variable by build scripts, so it's not required to call this function. + pub fn opt_level_str(&mut self, opt_level: &str) -> &mut Build { + self.opt_level = Some(opt_level.to_string()); + self + } + + /// Configures whether the compiler will emit debug information when + /// generating object files. + /// + /// This option is automatically scraped from the `PROFILE` environment + /// variable by build scripts (only enabled when the profile is "debug"), so + /// it's not required to call this function. + pub fn debug(&mut self, debug: bool) -> &mut Build { + self.debug = Some(debug); + self + } + + /// Configures the output directory where all object files and static + /// libraries will be located. + /// + /// This option is automatically scraped from the `OUT_DIR` environment + /// variable by build scripts, so it's not required to call this function. + pub fn out_dir>(&mut self, out_dir: P) -> &mut Build { + self.out_dir = Some(out_dir.as_ref().to_owned()); + self + } + + /// Configures the compiler to be used to produce output. + /// + /// This option is automatically determined from the target platform or a + /// number of environment variables, so it's not required to call this + /// function. + pub fn compiler>(&mut self, compiler: P) -> &mut Build { + self.compiler = Some(compiler.as_ref().to_owned()); + self + } + + /// Configures the tool used to assemble archives. + /// + /// This option is automatically determined from the target platform or a + /// number of environment variables, so it's not required to call this + /// function. + pub fn archiver>(&mut self, archiver: P) -> &mut Build { + self.archiver = Some(archiver.as_ref().to_owned()); + self + } + /// Define whether metadata should be emitted for cargo allowing it to + /// automatically link the binary. Defaults to `true`. + /// + /// The emitted metadata is: + /// + /// - `rustc-link-lib=static=`*compiled lib* + /// - `rustc-link-search=native=`*target folder* + /// - When target is MSVC, the ATL-MFC libs are added via `rustc-link-search=native=` + /// - When C++ is enabled, the C++ stdlib is added via `rustc-link-lib` + /// + pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Build { + self.cargo_metadata = cargo_metadata; + self + } + + /// Configures whether the compiler will emit position independent code. + /// + /// This option defaults to `false` for `windows-gnu` targets and + /// to `true` for all other targets. + pub fn pic(&mut self, pic: bool) -> &mut Build { + self.pic = Some(pic); + self + } + + /// Configures whether the /MT flag or the /MD flag will be passed to msvc build tools. + /// + /// This option defaults to `false`, and affect only msvc targets. + pub fn static_crt(&mut self, static_crt: bool) -> &mut Build { + self.static_crt = Some(static_crt); + self + } + + #[doc(hidden)] + pub fn __set_env(&mut self, a: A, b: B) -> &mut Build + where + A: AsRef, + B: AsRef, + { + self.env + .push((a.as_ref().to_owned(), b.as_ref().to_owned())); + self + } + + /// Run the compiler, generating the file `output` + /// + /// This will return a result instead of panicing; see compile() for the complete description. + pub fn try_compile(&self, output: &str) -> Result<(), Error> { + let (lib_name, gnu_lib_name) = if output.starts_with("lib") && output.ends_with(".a") { + (&output[3..output.len() - 2], output.to_owned()) + } else { + let mut gnu = String::with_capacity(5 + output.len()); + gnu.push_str("lib"); + gnu.push_str(&output); + gnu.push_str(".a"); + (output, gnu) + }; + let dst = self.get_out_dir()?; + + let mut objects = Vec::new(); + for file in self.files.iter() { + let obj = dst.join(file).with_extension("o"); + let obj = if !obj.starts_with(&dst) { + dst.join(obj.file_name().ok_or_else(|| { + Error::new(ErrorKind::IOError, "Getting object file details failed.") + })?) + } else { + obj + }; + + match obj.parent() { + Some(s) => fs::create_dir_all(s)?, + None => { + return Err(Error::new( + ErrorKind::IOError, + "Getting object file details failed.", + )) + } + }; + + objects.push(Object::new(file.to_path_buf(), obj)); + } + self.compile_objects(&objects)?; + self.assemble(lib_name, &dst.join(gnu_lib_name), &objects)?; + + if self.get_target()?.contains("msvc") { + let compiler = self.get_base_compiler()?; + let atlmfc_lib = compiler + .env() + .iter() + .find(|&&(ref var, _)| var.as_os_str() == OsStr::new("LIB")) + .and_then(|&(_, ref lib_paths)| { + env::split_paths(lib_paths).find(|path| { + let sub = Path::new("atlmfc/lib"); + path.ends_with(sub) || path.parent().map_or(false, |p| p.ends_with(sub)) + }) + }); + + if let Some(atlmfc_lib) = atlmfc_lib { + self.print(&format!( + "cargo:rustc-link-search=native={}", + atlmfc_lib.display() + )); + } + } + + self.print(&format!("cargo:rustc-link-lib=static={}", lib_name)); + self.print(&format!("cargo:rustc-link-search=native={}", dst.display())); + + // Add specific C++ libraries, if enabled. + if self.cpp { + if let Some(stdlib) = self.get_cpp_link_stdlib()? { + self.print(&format!("cargo:rustc-link-lib={}", stdlib)); + } + } + + Ok(()) + } + + /// Run the compiler, generating the file `output` + /// + /// The name `output` should be the name of the library. For backwards compatibility, + /// the `output` may start with `lib` and end with `.a`. The Rust compilier will create + /// the assembly with the lib prefix and .a extension. MSVC will create a file without prefix, + /// ending with `.lib`. + /// + /// # Panics + /// + /// Panics if `output` is not formatted correctly or if one of the underlying + /// compiler commands fails. It can also panic if it fails reading file names + /// or creating directories. + pub fn compile(&self, output: &str) { + if let Err(e) = self.try_compile(output) { + fail(&e.message); + } + } + + #[cfg(feature = "parallel")] + fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> { + use self::rayon::prelude::*; + + if let Ok(amt) = env::var("NUM_JOBS") { + if let Ok(amt) = amt.parse() { + let _ = rayon::ThreadPoolBuilder::new() + .num_threads(amt) + .build_global(); + } + } + + // Check for any errors and return the first one found. + objs.par_iter() + .with_max_len(1) + .map(|obj| self.compile_object(obj)) + .collect() + } + + #[cfg(not(feature = "parallel"))] + fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> { + for obj in objs { + self.compile_object(obj)?; + } + Ok(()) + } + + fn compile_object(&self, obj: &Object) -> Result<(), Error> { + let is_asm = obj.src.extension().and_then(|s| s.to_str()) == Some("asm"); + let target = self.get_target()?; + let msvc = target.contains("msvc"); + let (mut cmd, name) = if msvc && is_asm { + self.msvc_macro_assembler()? + } else { + let compiler = self.try_get_compiler()?; + let mut cmd = compiler.to_command(); + for &(ref a, ref b) in self.env.iter() { + cmd.env(a, b); + } + ( + cmd, + compiler + .path + .file_name() + .ok_or_else(|| Error::new(ErrorKind::IOError, "Failed to get compiler path."))? + .to_string_lossy() + .into_owned(), + ) + }; + let is_arm = target.contains("aarch64") || target.contains("arm"); + command_add_output_file(&mut cmd, &obj.dst, msvc, is_asm, is_arm); + // armasm and armasm64 don't requrie -c option + if !msvc || !is_asm || !is_arm { + cmd.arg(if msvc { "/c" } else { "-c" }); + } + cmd.arg(&obj.src); + + run(&mut cmd, &name)?; + Ok(()) + } + + /// This will return a result instead of panicing; see expand() for the complete description. + pub fn try_expand(&self) -> Result, Error> { + let compiler = self.try_get_compiler()?; + let mut cmd = compiler.to_command(); + for &(ref a, ref b) in self.env.iter() { + cmd.env(a, b); + } + cmd.arg(compiler.family.expand_flag()); + + assert!( + self.files.len() <= 1, + "Expand may only be called for a single file" + ); + + for file in self.files.iter() { + cmd.arg(file); + } + + let name = compiler + .path + .file_name() + .ok_or_else(|| Error::new(ErrorKind::IOError, "Failed to get compiler path."))? + .to_string_lossy() + .into_owned(); + + Ok(run_output(&mut cmd, &name)?) + } + + /// Run the compiler, returning the macro-expanded version of the input files. + /// + /// This is only relevant for C and C++ files. + /// + /// # Panics + /// Panics if more than one file is present in the config, or if compiler + /// path has an invalid file name. + /// + /// # Example + /// ```no_run + /// let out = cc::Build::new().file("src/foo.c").expand(); + /// ``` + pub fn expand(&self) -> Vec { + match self.try_expand() { + Err(e) => fail(&e.message), + Ok(v) => v, + } + } + + /// Get the compiler that's in use for this configuration. + /// + /// This function will return a `Tool` which represents the culmination + /// of this configuration at a snapshot in time. The returned compiler can + /// be inspected (e.g. the path, arguments, environment) to forward along to + /// other tools, or the `to_command` method can be used to invoke the + /// compiler itself. + /// + /// This method will take into account all configuration such as debug + /// information, optimization level, include directories, defines, etc. + /// Additionally, the compiler binary in use follows the standard + /// conventions for this path, e.g. looking at the explicitly set compiler, + /// environment variables (a number of which are inspected here), and then + /// falling back to the default configuration. + /// + /// # Panics + /// + /// Panics if an error occurred while determining the architecture. + pub fn get_compiler(&self) -> Tool { + match self.try_get_compiler() { + Ok(tool) => tool, + Err(e) => fail(&e.message), + } + } + + /// Get the compiler that's in use for this configuration. + /// + /// This will return a result instead of panicing; see get_compiler() for the complete description. + pub fn try_get_compiler(&self) -> Result { + let opt_level = self.get_opt_level()?; + let target = self.get_target()?; + + let mut cmd = self.get_base_compiler()?; + + // Non-target flags + // If the flag is not conditioned on target variable, it belongs here :) + match cmd.family { + ToolFamily::Msvc => { + assert!(!self.cuda, + "CUDA C++ compilation not supported for MSVC, yet... but you are welcome to implement it :)"); + + cmd.args.push("/nologo".into()); + + let crt_flag = match self.static_crt { + Some(true) => "/MT", + Some(false) => "/MD", + None => { + let features = + env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or(String::new()); + if features.contains("crt-static") { + "/MT" + } else { + "/MD" + } + } + }; + cmd.args.push(crt_flag.into()); + + match &opt_level[..] { + // Msvc uses /O1 to enable all optimizations that minimize code size. + "z" | "s" | "1" => cmd.args.push("/O1".into()), + // -O3 is a valid value for gcc and clang compilers, but not msvc. Cap to /O2. + "2" | "3" => cmd.args.push("/O2".into()), + _ => {} + } + } + ToolFamily::Gnu | ToolFamily::Clang => { + // arm-linux-androideabi-gcc 4.8 shipped with Android NDK does + // not support '-Oz' + if opt_level == "z" && cmd.family != ToolFamily::Clang { + cmd.args.push("-Os".into()); + } else { + cmd.args.push(format!("-O{}", opt_level).into()); + } + + if !target.contains("-ios") { + cmd.push_cc_arg("-ffunction-sections".into()); + cmd.push_cc_arg("-fdata-sections".into()); + } + if self.pic.unwrap_or(!target.contains("windows-gnu")) { + cmd.push_cc_arg("-fPIC".into()); + } + } + } + for arg in self.envflags(if self.cpp { "CXXFLAGS" } else { "CFLAGS" }) { + cmd.args.push(arg.into()); + } + + if self.get_debug() { + if self.cuda { + let nvcc_debug_flag = cmd.family.nvcc_debug_flag().into(); + cmd.args.push(nvcc_debug_flag); + } + let debug_flag = cmd.family.debug_flag().into(); + cmd.push_cc_arg(debug_flag); + } + + // Target flags + match cmd.family { + ToolFamily::Clang => { + cmd.args.push(format!("--target={}", target).into()); + } + ToolFamily::Msvc => { + if target.contains("i586") { + cmd.args.push("/ARCH:IA32".into()); + } + } + ToolFamily::Gnu => { + if target.contains("i686") || target.contains("i586") { + cmd.args.push("-m32".into()); + } else if target == "x86_64-unknown-linux-gnux32" { + cmd.args.push("-mx32".into()); + } else if target.contains("x86_64") || target.contains("powerpc64") { + cmd.args.push("-m64".into()); + } + + if self.static_flag.is_none() { + let features = env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or(String::new()); + if features.contains("crt-static") { + cmd.args.push("-static".into()); + } + } + + // armv7 targets get to use armv7 instructions + if target.starts_with("armv7-") && target.contains("-linux-") { + cmd.args.push("-march=armv7-a".into()); + } + + // On android we can guarantee some extra float instructions + // (specified in the android spec online) + if target.starts_with("armv7-linux-androideabi") { + cmd.args.push("-march=armv7-a".into()); + cmd.args.push("-mthumb".into()); + cmd.args.push("-mfpu=vfpv3-d16".into()); + cmd.args.push("-mfloat-abi=softfp".into()); + } + + if target.starts_with("armv4t-unknown-linux-") { + cmd.args.push("-march=armv4t".into()); + cmd.args.push("-marm".into()); + cmd.args.push("-mfloat-abi=soft".into()); + } + + if target.starts_with("armv5te-unknown-linux-") { + cmd.args.push("-march=armv5te".into()); + cmd.args.push("-marm".into()); + cmd.args.push("-mfloat-abi=soft".into()); + } + + // For us arm == armv6 by default + if target.starts_with("arm-unknown-linux-") { + cmd.args.push("-march=armv6".into()); + cmd.args.push("-marm".into()); + } + + // We can guarantee some settings for FRC + if target.starts_with("arm-frc-") { + cmd.args.push("-march=armv7-a".into()); + cmd.args.push("-mcpu=cortex-a9".into()); + cmd.args.push("-mfpu=vfpv3".into()); + cmd.args.push("-mfloat-abi=softfp".into()); + cmd.args.push("-marm".into()); + } + + // Turn codegen down on i586 to avoid some instructions. + if target.starts_with("i586-unknown-linux-") { + cmd.args.push("-march=pentium".into()); + } + + // Set codegen level for i686 correctly + if target.starts_with("i686-unknown-linux-") { + cmd.args.push("-march=i686".into()); + } + + // Looks like `musl-gcc` makes is hard for `-m32` to make its way + // all the way to the linker, so we need to actually instruct the + // linker that we're generating 32-bit executables as well. This'll + // typically only be used for build scripts which transitively use + // these flags that try to compile executables. + if target == "i686-unknown-linux-musl" || target == "i586-unknown-linux-musl" { + cmd.args.push("-Wl,-melf_i386".into()); + } + + if target.starts_with("thumb") { + cmd.args.push("-mthumb".into()); + + if target.ends_with("eabihf") { + cmd.args.push("-mfloat-abi=hard".into()) + } + } + if target.starts_with("thumbv6m") { + cmd.args.push("-march=armv6s-m".into()); + } + if target.starts_with("thumbv7em") { + cmd.args.push("-march=armv7e-m".into()); + + if target.ends_with("eabihf") { + cmd.args.push("-mfpu=fpv4-sp-d16".into()) + } + } + if target.starts_with("thumbv7m") { + cmd.args.push("-march=armv7-m".into()); + } + } + } + + if target.contains("-ios") { + // FIXME: potential bug. iOS is always compiled with Clang, but Gcc compiler may be + // detected instead. + self.ios_flags(&mut cmd)?; + } + + if self.static_flag.unwrap_or(false) { + cmd.args.push("-static".into()); + } + if self.shared_flag.unwrap_or(false) { + cmd.args.push("-shared".into()); + } + + if self.cpp { + match (self.cpp_set_stdlib.as_ref(), cmd.family) { + (None, _) => {} + (Some(stdlib), ToolFamily::Gnu) | (Some(stdlib), ToolFamily::Clang) => { + cmd.push_cc_arg(format!("-stdlib=lib{}", stdlib).into()); + } + _ => { + println!( + "cargo:warning=cpp_set_stdlib is specified, but the {:?} compiler \ + does not support this option, ignored", + cmd.family + ); + } + } + } + + for directory in self.include_directories.iter() { + cmd.args.push(cmd.family.include_flag().into()); + cmd.args.push(directory.into()); + } + + if self.warnings { + for flag in cmd.family.warnings_flags().iter() { + cmd.push_cc_arg(flag.into()); + } + } + + for flag in self.flags.iter() { + cmd.args.push(flag.into()); + } + + for flag in self.flags_supported.iter() { + if self.is_flag_supported(flag).unwrap_or(false) { + cmd.push_cc_arg(flag.into()); + } + } + + for &(ref key, ref value) in self.definitions.iter() { + let lead = if let ToolFamily::Msvc = cmd.family { + "/" + } else { + "-" + }; + if let Some(ref value) = *value { + cmd.args.push(format!("{}D{}={}", lead, key, value).into()); + } else { + cmd.args.push(format!("{}D{}", lead, key).into()); + } + } + + if self.warnings_into_errors { + let warnings_to_errors_flag = cmd.family.warnings_to_errors_flag().into(); + cmd.push_cc_arg(warnings_to_errors_flag); + } + + Ok(cmd) + } + + fn msvc_macro_assembler(&self) -> Result<(Command, String), Error> { + let target = self.get_target()?; + let tool = if target.contains("x86_64") { + "ml64.exe" + } else if target.contains("arm") { + "armasm.exe" + } else if target.contains("aarch64") { + "armasm64.exe" + } else { + "ml.exe" + }; + let mut cmd = windows_registry::find(&target, tool).unwrap_or_else(|| self.cmd(tool)); + for directory in self.include_directories.iter() { + cmd.arg("/I").arg(directory); + } + for &(ref key, ref value) in self.definitions.iter() { + if let Some(ref value) = *value { + cmd.arg(&format!("/D{}={}", key, value)); + } else { + cmd.arg(&format!("/D{}", key)); + } + } + + if target.contains("i686") || target.contains("i586") { + cmd.arg("/safeseh"); + } + for flag in self.flags.iter() { + cmd.arg(flag); + } + + Ok((cmd, tool.to_string())) + } + + fn assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error> { + // Delete the destination if it exists as the `ar` tool at least on Unix + // appends to it, which we don't want. + let _ = fs::remove_file(&dst); + + let objects: Vec<_> = objs.iter().map(|obj| obj.dst.clone()).collect(); + let target = self.get_target()?; + if target.contains("msvc") { + let mut cmd = match self.archiver { + Some(ref s) => self.cmd(s), + None => windows_registry::find(&target, "lib.exe") + .unwrap_or_else(|| self.cmd("lib.exe")), + }; + + let mut out = OsString::from("/OUT:"); + out.push(dst); + cmd.arg(out).arg("/nologo"); + + // Similar to https://github.com/rust-lang/rust/pull/47507 + // and https://github.com/rust-lang/rust/pull/48548 + let estimated_command_line_len = objects + .iter() + .chain(&self.objects) + .map(|a| a.as_os_str().len()) + .sum::(); + if estimated_command_line_len > 1024 * 6 { + let mut args = String::from("\u{FEFF}"); // BOM + for arg in objects.iter().chain(&self.objects) { + args.push('"'); + for c in arg.to_str().unwrap().chars() { + if c == '"' { + args.push('\\') + } + args.push(c) + } + args.push('"'); + args.push('\n'); + } + + let mut utf16le = Vec::new(); + for code_unit in args.encode_utf16() { + utf16le.push(code_unit as u8); + utf16le.push((code_unit >> 8) as u8); + } + + let mut args_file = OsString::from(dst); + args_file.push(".args"); + fs::File::create(&args_file) + .unwrap() + .write_all(&utf16le) + .unwrap(); + + let mut args_file_arg = OsString::from("@"); + args_file_arg.push(args_file); + cmd.arg(args_file_arg); + } else { + cmd.args(&objects).args(&self.objects); + } + run(&mut cmd, "lib.exe")?; + + // The Rust compiler will look for libfoo.a and foo.lib, but the + // MSVC linker will also be passed foo.lib, so be sure that both + // exist for now. + let lib_dst = dst.with_file_name(format!("{}.lib", lib_name)); + let _ = fs::remove_file(&lib_dst); + match fs::hard_link(&dst, &lib_dst).or_else(|_| { + // if hard-link fails, just copy (ignoring the number of bytes written) + fs::copy(&dst, &lib_dst).map(|_| ()) + }) { + Ok(_) => (), + Err(_) => { + return Err(Error::new( + ErrorKind::IOError, + "Could not copy or create a hard-link to the generated lib file.", + )) + } + }; + } else { + let (mut ar, cmd) = self.get_ar()?; + run( + ar.arg("crs").arg(dst).args(&objects).args(&self.objects), + &cmd, + )?; + } + + Ok(()) + } + + fn ios_flags(&self, cmd: &mut Tool) -> Result<(), Error> { + enum ArchSpec { + Device(&'static str), + Simulator(&'static str), + } + + let target = self.get_target()?; + let arch = target.split('-').nth(0).ok_or_else(|| { + Error::new( + ErrorKind::ArchitectureInvalid, + "Unknown architecture for iOS target.", + ) + })?; + let arch = match arch { + "arm" | "armv7" | "thumbv7" => ArchSpec::Device("armv7"), + "armv7s" | "thumbv7s" => ArchSpec::Device("armv7s"), + "arm64" | "aarch64" => ArchSpec::Device("arm64"), + "i386" | "i686" => ArchSpec::Simulator("-m32"), + "x86_64" => ArchSpec::Simulator("-m64"), + _ => { + return Err(Error::new( + ErrorKind::ArchitectureInvalid, + "Unknown architecture for iOS target.", + )) + } + }; + + let sdk = match arch { + ArchSpec::Device(arch) => { + cmd.args.push("-arch".into()); + cmd.args.push(arch.into()); + cmd.args.push("-miphoneos-version-min=7.0".into()); + "iphoneos" + } + ArchSpec::Simulator(arch) => { + cmd.args.push(arch.into()); + cmd.args.push("-mios-simulator-version-min=7.0".into()); + "iphonesimulator" + } + }; + + self.print(&format!("Detecting iOS SDK path for {}", sdk)); + let sdk_path = self.cmd("xcrun") + .arg("--show-sdk-path") + .arg("--sdk") + .arg(sdk) + .stderr(Stdio::inherit()) + .output()? + .stdout; + + let sdk_path = match String::from_utf8(sdk_path) { + Ok(p) => p, + Err(_) => { + return Err(Error::new( + ErrorKind::IOError, + "Unable to determine iOS SDK path.", + )) + } + }; + + cmd.args.push("-isysroot".into()); + cmd.args.push(sdk_path.trim().into()); + cmd.args.push("-fembed-bitcode".into()); + /* + * TODO we probably ultimatedly want the -fembed-bitcode-marker flag + * but can't have it now because of an issue in LLVM: + * https://github.com/alexcrichton/cc-rs/issues/301 + * https://github.com/rust-lang/rust/pull/48896#comment-372192660 + */ + /* + if self.get_opt_level()? == "0" { + cmd.args.push("-fembed-bitcode-marker".into()); + } + */ + + Ok(()) + } + + fn cmd>(&self, prog: P) -> Command { + let mut cmd = Command::new(prog); + for &(ref a, ref b) in self.env.iter() { + cmd.env(a, b); + } + cmd + } + + fn get_base_compiler(&self) -> Result { + if let Some(ref c) = self.compiler { + return Ok(Tool::new(c.clone())); + } + let host = self.get_host()?; + let target = self.get_target()?; + let (env, msvc, gnu, traditional) = if self.cpp { + ("CXX", "cl.exe", "g++", "c++") + } else { + ("CC", "cl.exe", "gcc", "cc") + }; + + // On Solaris, c++/cc unlikely to exist or be correct. + let default = if host.contains("solaris") { + gnu + } else { + traditional + }; + + let tool_opt: Option = self.env_tool(env) + .map(|(tool, cc, args)| { + // chop off leading/trailing whitespace to work around + // semi-buggy build scripts which are shared in + // makefiles/configure scripts (where spaces are far more + // lenient) + let mut t = Tool::new(PathBuf::from(tool.trim())); + if let Some(cc) = cc { + t.cc_wrapper_path = Some(PathBuf::from(cc)); + } + for arg in args { + t.cc_wrapper_args.push(arg.into()); + } + t + }) + .or_else(|| { + if target.contains("emscripten") { + let tool = if self.cpp { "em++" } else { "emcc" }; + // Windows uses bat file so we have to be a bit more specific + if cfg!(windows) { + let mut t = Tool::new(PathBuf::from("cmd")); + t.args.push("/c".into()); + t.args.push(format!("{}.bat", tool).into()); + Some(t) + } else { + Some(Tool::new(PathBuf::from(tool))) + } + } else { + None + } + }) + .or_else(|| windows_registry::find_tool(&target, "cl.exe")); + + let tool = match tool_opt { + Some(t) => t, + None => { + let compiler = if host.contains("windows") && target.contains("windows") { + if target.contains("msvc") { + msvc.to_string() + } else { + format!("{}.exe", gnu) + } + } else if target.contains("android") { + format!("{}-{}", target.replace("armv7", "arm"), gnu) + } else if target.contains("cloudabi") { + format!("{}-{}", target, traditional) + } else if self.get_host()? != target { + // CROSS_COMPILE is of the form: "arm-linux-gnueabi-" + let cc_env = self.getenv("CROSS_COMPILE"); + let cross_compile = cc_env.as_ref().map(|s| s.trim_right_matches('-')); + let prefix = cross_compile.or(match &target[..] { + "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu"), + "aarch64-unknown-linux-musl" => Some("aarch64-linux-musl"), + "arm-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"), + "armv4t-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"), + "armv5te-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"), + "arm-frc-linux-gnueabi" => Some("arm-frc-linux-gnueabi"), + "arm-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"), + "arm-unknown-linux-musleabi" => Some("arm-linux-musleabi"), + "arm-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"), + "arm-unknown-netbsd-eabi" => Some("arm--netbsdelf-eabi"), + "armv6-unknown-netbsd-eabihf" => Some("armv6--netbsdelf-eabihf"), + "armv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"), + "armv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"), + "armv7-unknown-netbsd-eabihf" => Some("armv7--netbsdelf-eabihf"), + "i586-unknown-linux-musl" => Some("musl"), + "i686-pc-windows-gnu" => Some("i686-w64-mingw32"), + "i686-unknown-linux-musl" => Some("musl"), + "i686-unknown-netbsd" => Some("i486--netbsdelf"), + "mips-unknown-linux-gnu" => Some("mips-linux-gnu"), + "mipsel-unknown-linux-gnu" => Some("mipsel-linux-gnu"), + "mips64-unknown-linux-gnuabi64" => Some("mips64-linux-gnuabi64"), + "mips64el-unknown-linux-gnuabi64" => Some("mips64el-linux-gnuabi64"), + "powerpc-unknown-linux-gnu" => Some("powerpc-linux-gnu"), + "powerpc-unknown-linux-gnuspe" => Some("powerpc-linux-gnuspe"), + "powerpc-unknown-netbsd" => Some("powerpc--netbsd"), + "powerpc64-unknown-linux-gnu" => Some("powerpc-linux-gnu"), + "powerpc64le-unknown-linux-gnu" => Some("powerpc64le-linux-gnu"), + "s390x-unknown-linux-gnu" => Some("s390x-linux-gnu"), + "sparc-unknown-linux-gnu" => Some("sparc-linux-gnu"), + "sparc64-unknown-linux-gnu" => Some("sparc64-linux-gnu"), + "sparc64-unknown-netbsd" => Some("sparc64--netbsd"), + "sparcv9-sun-solaris" => Some("sparcv9-sun-solaris"), + "thumbv6m-none-eabi" => Some("arm-none-eabi"), + "thumbv7em-none-eabi" => Some("arm-none-eabi"), + "thumbv7em-none-eabihf" => Some("arm-none-eabi"), + "thumbv7m-none-eabi" => Some("arm-none-eabi"), + "x86_64-pc-windows-gnu" => Some("x86_64-w64-mingw32"), + "x86_64-rumprun-netbsd" => Some("x86_64-rumprun-netbsd"), + "x86_64-unknown-linux-musl" => Some("musl"), + "x86_64-unknown-netbsd" => Some("x86_64--netbsd"), + _ => None, + }); + match prefix { + Some(prefix) => format!("{}-{}", prefix, gnu), + None => default.to_string(), + } + } else { + default.to_string() + }; + Tool::new(PathBuf::from(compiler)) + } + }; + + let tool = if self.cuda { + assert!( + tool.args.is_empty(), + "CUDA compilation currently assumes empty pre-existing args" + ); + let nvcc = match self.get_var("NVCC") { + Err(_) => "nvcc".into(), + Ok(nvcc) => nvcc, + }; + let mut nvcc_tool = Tool::with_features(PathBuf::from(nvcc), self.cuda); + nvcc_tool + .args + .push(format!("-ccbin={}", tool.path.display()).into()); + nvcc_tool + } else { + tool + }; + + Ok(tool) + } + + fn get_var(&self, var_base: &str) -> Result { + let target = self.get_target()?; + let host = self.get_host()?; + let kind = if host == target { "HOST" } else { "TARGET" }; + let target_u = target.replace("-", "_"); + let res = self.getenv(&format!("{}_{}", var_base, target)) + .or_else(|| self.getenv(&format!("{}_{}", var_base, target_u))) + .or_else(|| self.getenv(&format!("{}_{}", kind, var_base))) + .or_else(|| self.getenv(var_base)); + + match res { + Some(res) => Ok(res), + None => Err(Error::new( + ErrorKind::EnvVarNotFound, + &format!("Could not find environment variable {}.", var_base), + )), + } + } + + fn envflags(&self, name: &str) -> Vec { + self.get_var(name) + .unwrap_or(String::new()) + .split(|c: char| c.is_whitespace()) + .filter(|s| !s.is_empty()) + .map(|s| s.to_string()) + .collect() + } + + /// Returns compiler path, optional modifier name from whitelist, and arguments vec + fn env_tool(&self, name: &str) -> Option<(String, Option, Vec)> { + let tool = match self.get_var(name) { + Ok(tool) => tool, + Err(_) => return None, + }; + + // If this is an exact path on the filesystem we don't want to do any + // interpretation at all, just pass it on through. This'll hopefully get + // us to support spaces-in-paths. + if Path::new(&tool).exists() { + return Some((tool, None, Vec::new())); + } + + // Ok now we want to handle a couple of scenarios. We'll assume from + // here on out that spaces are splitting separate arguments. Two major + // features we want to support are: + // + // CC='sccache cc' + // + // aka using `sccache` or any other wrapper/caching-like-thing for + // compilations. We want to know what the actual compiler is still, + // though, because our `Tool` API support introspection of it to see + // what compiler is in use. + // + // additionally we want to support + // + // CC='cc -flag' + // + // where the CC env var is used to also pass default flags to the C + // compiler. + // + // It's true that everything here is a bit of a pain, but apparently if + // you're not literally make or bash then you get a lot of bug reports. + let known_wrappers = ["ccache", "distcc", "sccache", "icecc"]; + + let mut parts = tool.split_whitespace(); + let maybe_wrapper = match parts.next() { + Some(s) => s, + None => return None, + }; + + let file_stem = Path::new(maybe_wrapper) + .file_stem() + .unwrap() + .to_str() + .unwrap(); + if known_wrappers.contains(&file_stem) { + if let Some(compiler) = parts.next() { + return Some(( + compiler.to_string(), + Some(maybe_wrapper.to_string()), + parts.map(|s| s.to_string()).collect(), + )); + } + } + + Some(( + maybe_wrapper.to_string(), + None, + parts.map(|s| s.to_string()).collect(), + )) + } + + /// Returns the default C++ standard library for the current target: `libc++` + /// for OS X and `libstdc++` for anything else. + fn get_cpp_link_stdlib(&self) -> Result, Error> { + match self.cpp_link_stdlib.clone() { + Some(s) => Ok(s), + None => { + if let Ok(stdlib) = self.get_var("CXXSTDLIB") { + if stdlib.is_empty() { + Ok(None) + } else { + Ok(Some(stdlib)) + } + } else { + let target = self.get_target()?; + if target.contains("msvc") { + Ok(None) + } else if target.contains("apple") { + Ok(Some("c++".to_string())) + } else if target.contains("freebsd") { + Ok(Some("c++".to_string())) + } else if target.contains("openbsd") { + Ok(Some("c++".to_string())) + } else { + Ok(Some("stdc++".to_string())) + } + } + } + } + } + + fn get_ar(&self) -> Result<(Command, String), Error> { + if let Some(ref p) = self.archiver { + let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("ar"); + return Ok((self.cmd(p), name.to_string())); + } + if let Ok(p) = self.get_var("AR") { + return Ok((self.cmd(&p), p)); + } + let program = if self.get_target()?.contains("android") { + format!("{}-ar", self.get_target()?.replace("armv7", "arm")) + } else if self.get_target()?.contains("emscripten") { + // Windows use bat files so we have to be a bit more specific + if cfg!(windows) { + let mut cmd = self.cmd("cmd"); + cmd.arg("/c").arg("emar.bat"); + return Ok((cmd, "emar.bat".to_string())); + } + + "emar".to_string() + } else { + "ar".to_string() + }; + Ok((self.cmd(&program), program)) + } + + fn get_target(&self) -> Result { + match self.target.clone() { + Some(t) => Ok(t), + None => Ok(self.getenv_unwrap("TARGET")?), + } + } + + fn get_host(&self) -> Result { + match self.host.clone() { + Some(h) => Ok(h), + None => Ok(self.getenv_unwrap("HOST")?), + } + } + + fn get_opt_level(&self) -> Result { + match self.opt_level.as_ref().cloned() { + Some(ol) => Ok(ol), + None => Ok(self.getenv_unwrap("OPT_LEVEL")?), + } + } + + fn get_debug(&self) -> bool { + self.debug.unwrap_or_else(|| match self.getenv("DEBUG") { + Some(s) => s != "false", + None => false, + }) + } + + fn get_out_dir(&self) -> Result { + match self.out_dir.clone() { + Some(p) => Ok(p), + None => Ok(env::var_os("OUT_DIR").map(PathBuf::from).ok_or_else(|| { + Error::new( + ErrorKind::EnvVarNotFound, + "Environment variable OUT_DIR not defined.", + ) + })?), + } + } + + fn getenv(&self, v: &str) -> Option { + let r = env::var(v).ok(); + self.print(&format!("{} = {:?}", v, r)); + r + } + + fn getenv_unwrap(&self, v: &str) -> Result { + match self.getenv(v) { + Some(s) => Ok(s), + None => Err(Error::new( + ErrorKind::EnvVarNotFound, + &format!("Environment variable {} not defined.", v.to_string()), + )), + } + } + + fn print(&self, s: &str) { + if self.cargo_metadata { + println!("{}", s); + } + } +} + +impl Default for Build { + fn default() -> Build { + Build::new() + } +} + +impl Tool { + fn new(path: PathBuf) -> Tool { + Tool::with_features(path, false) + } + + fn with_features(path: PathBuf, cuda: bool) -> Tool { + // Try to detect family of the tool from its name, falling back to Gnu. + let family = if let Some(fname) = path.file_name().and_then(|p| p.to_str()) { + if fname.contains("clang") { + ToolFamily::Clang + } else if fname.contains("cl") && !fname.contains("cloudabi") + && !fname.contains("uclibc") + { + ToolFamily::Msvc + } else { + ToolFamily::Gnu + } + } else { + ToolFamily::Gnu + }; + Tool { + path: path, + cc_wrapper_path: None, + cc_wrapper_args: Vec::new(), + args: Vec::new(), + env: Vec::new(), + family: family, + cuda: cuda, + } + } + + /// Add a flag, and optionally prepend the NVCC wrapper flag "-Xcompiler". + /// + /// Currently this is only used for compiling CUDA sources, since NVCC only + /// accepts a limited set of GNU-like flags, and the rest must be prefixed + /// with a "-Xcompiler" flag to get passed to the underlying C++ compiler. + fn push_cc_arg(&mut self, flag: OsString) { + if self.cuda { + self.args.push(self.family.nvcc_redirect_flag().into()); + } + self.args.push(flag); + } + + /// Converts this compiler into a `Command` that's ready to be run. + /// + /// This is useful for when the compiler needs to be executed and the + /// command returned will already have the initial arguments and environment + /// variables configured. + pub fn to_command(&self) -> Command { + let mut cmd = match self.cc_wrapper_path { + Some(ref cc_wrapper_path) => { + let mut cmd = Command::new(&cc_wrapper_path); + cmd.arg(&self.path); + cmd.args(&self.cc_wrapper_args); + cmd + } + None => Command::new(&self.path), + }; + cmd.args(&self.args); + for &(ref k, ref v) in self.env.iter() { + cmd.env(k, v); + } + cmd + } + + /// Returns the path for this compiler. + /// + /// Note that this may not be a path to a file on the filesystem, e.g. "cc", + /// but rather something which will be resolved when a process is spawned. + pub fn path(&self) -> &Path { + &self.path + } + + /// Returns the default set of arguments to the compiler needed to produce + /// executables for the target this compiler generates. + pub fn args(&self) -> &[OsString] { + &self.args + } + + /// Returns the set of environment variables needed for this compiler to + /// operate. + /// + /// This is typically only used for MSVC compilers currently. + pub fn env(&self) -> &[(OsString, OsString)] { + &self.env + } + + /// Returns the compiler command in format of CC environment variable. + /// Or empty string if CC env was not present + /// + /// This is typically used by configure script + pub fn cc_env(&self) -> OsString { + match self.cc_wrapper_path { + Some(ref cc_wrapper_path) => { + let mut cc_env = cc_wrapper_path.as_os_str().to_owned(); + cc_env.push(" "); + cc_env.push(self.path.to_path_buf().into_os_string()); + for arg in self.cc_wrapper_args.iter() { + cc_env.push(" "); + cc_env.push(arg); + } + cc_env + } + None => OsString::from(""), + } + } + + /// Returns the compiler flags in format of CFLAGS environment variable. + /// Important here - this will not be CFLAGS from env, its internal gcc's flags to use as CFLAGS + /// This is typically used by configure script + pub fn cflags_env(&self) -> OsString { + let mut flags = OsString::new(); + for (i, arg) in self.args.iter().enumerate() { + if i > 0 { + flags.push(" "); + } + flags.push(arg); + } + flags + } + + /// Whether the tool is GNU Compiler Collection-like. + pub fn is_like_gnu(&self) -> bool { + self.family == ToolFamily::Gnu + } + + /// Whether the tool is Clang-like. + pub fn is_like_clang(&self) -> bool { + self.family == ToolFamily::Clang + } + + /// Whether the tool is MSVC-like. + pub fn is_like_msvc(&self) -> bool { + self.family == ToolFamily::Msvc + } +} + +fn run(cmd: &mut Command, program: &str) -> Result<(), Error> { + let (mut child, print) = spawn(cmd, program)?; + let status = match child.wait() { + Ok(s) => s, + Err(_) => { + return Err(Error::new( + ErrorKind::ToolExecError, + &format!( + "Failed to wait on spawned child process, command {:?} with args {:?}.", + cmd, program + ), + )) + } + }; + print.join().unwrap(); + println!("{}", status); + + if status.success() { + Ok(()) + } else { + Err(Error::new( + ErrorKind::ToolExecError, + &format!( + "Command {:?} with args {:?} did not execute successfully (status code {}).", + cmd, program, status + ), + )) + } +} + +fn run_output(cmd: &mut Command, program: &str) -> Result, Error> { + cmd.stdout(Stdio::piped()); + let (mut child, print) = spawn(cmd, program)?; + let mut stdout = vec![]; + child + .stdout + .take() + .unwrap() + .read_to_end(&mut stdout) + .unwrap(); + let status = match child.wait() { + Ok(s) => s, + Err(_) => { + return Err(Error::new( + ErrorKind::ToolExecError, + &format!( + "Failed to wait on spawned child process, command {:?} with args {:?}.", + cmd, program + ), + )) + } + }; + print.join().unwrap(); + println!("{}", status); + + if status.success() { + Ok(stdout) + } else { + Err(Error::new( + ErrorKind::ToolExecError, + &format!( + "Command {:?} with args {:?} did not execute successfully (status code {}).", + cmd, program, status + ), + )) + } +} + +fn spawn(cmd: &mut Command, program: &str) -> Result<(Child, JoinHandle<()>), Error> { + println!("running: {:?}", cmd); + + // Capture the standard error coming from these programs, and write it out + // with cargo:warning= prefixes. Note that this is a bit wonky to avoid + // requiring the output to be UTF-8, we instead just ship bytes from one + // location to another. + match cmd.stderr(Stdio::piped()).spawn() { + Ok(mut child) => { + let stderr = BufReader::new(child.stderr.take().unwrap()); + let print = thread::spawn(move || { + for line in stderr.split(b'\n').filter_map(|l| l.ok()) { + print!("cargo:warning="); + std::io::stdout().write_all(&line).unwrap(); + println!(""); + } + }); + Ok((child, print)) + } + Err(ref e) if e.kind() == io::ErrorKind::NotFound => { + let extra = if cfg!(windows) { + " (see https://github.com/alexcrichton/cc-rs#compile-time-requirements \ + for help)" + } else { + "" + }; + Err(Error::new( + ErrorKind::ToolNotFound, + &format!("Failed to find tool. Is `{}` installed?{}", program, extra), + )) + } + Err(_) => Err(Error::new( + ErrorKind::ToolExecError, + &format!("Command {:?} with args {:?} failed to start.", cmd, program), + )), + } +} + +fn fail(s: &str) -> ! { + panic!("\n\nInternal error occurred: {}\n\n", s) +} + +fn command_add_output_file(cmd: &mut Command, dst: &Path, msvc: bool, is_asm: bool, is_arm: bool) { + if msvc && is_asm && is_arm { + cmd.arg("-o").arg(&dst); + } else if msvc && is_asm { + cmd.arg("/Fo").arg(dst); + } else if msvc { + let mut s = OsString::from("/Fo"); + s.push(&dst); + cmd.arg(s); + } else { + cmd.arg("-o").arg(&dst); + } +} diff -Nru cargo-0.25.0/vendor/cc-1.0.10/src/registry.rs cargo-0.26.0/vendor/cc-1.0.10/src/registry.rs --- cargo-0.25.0/vendor/cc-1.0.10/src/registry.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/src/registry.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,204 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::ffi::{OsStr, OsString}; +use std::io; +use std::ops::RangeFrom; +use std::os::raw; +use std::os::windows::prelude::*; + +pub struct RegistryKey(Repr); + +type HKEY = *mut u8; +type DWORD = u32; +type LPDWORD = *mut DWORD; +type LPCWSTR = *const u16; +type LPWSTR = *mut u16; +type LONG = raw::c_long; +type PHKEY = *mut HKEY; +type PFILETIME = *mut u8; +type LPBYTE = *mut u8; +type REGSAM = u32; + +const ERROR_SUCCESS: DWORD = 0; +const ERROR_NO_MORE_ITEMS: DWORD = 259; +const HKEY_LOCAL_MACHINE: HKEY = 0x80000002 as HKEY; +const REG_SZ: DWORD = 1; +const KEY_READ: DWORD = 0x20019; +const KEY_WOW64_32KEY: DWORD = 0x200; + +#[link(name = "advapi32")] +extern "system" { + fn RegOpenKeyExW( + key: HKEY, + lpSubKey: LPCWSTR, + ulOptions: DWORD, + samDesired: REGSAM, + phkResult: PHKEY, + ) -> LONG; + fn RegEnumKeyExW( + key: HKEY, + dwIndex: DWORD, + lpName: LPWSTR, + lpcName: LPDWORD, + lpReserved: LPDWORD, + lpClass: LPWSTR, + lpcClass: LPDWORD, + lpftLastWriteTime: PFILETIME, + ) -> LONG; + fn RegQueryValueExW( + hKey: HKEY, + lpValueName: LPCWSTR, + lpReserved: LPDWORD, + lpType: LPDWORD, + lpData: LPBYTE, + lpcbData: LPDWORD, + ) -> LONG; + fn RegCloseKey(hKey: HKEY) -> LONG; +} + +struct OwnedKey(HKEY); + +enum Repr { + Const(HKEY), + Owned(OwnedKey), +} + +pub struct Iter<'a> { + idx: RangeFrom, + key: &'a RegistryKey, +} + +unsafe impl Sync for Repr {} +unsafe impl Send for Repr {} + +pub static LOCAL_MACHINE: RegistryKey = RegistryKey(Repr::Const(HKEY_LOCAL_MACHINE)); + +impl RegistryKey { + fn raw(&self) -> HKEY { + match self.0 { + Repr::Const(val) => val, + Repr::Owned(ref val) => val.0, + } + } + + pub fn open(&self, key: &OsStr) -> io::Result { + let key = key.encode_wide().chain(Some(0)).collect::>(); + let mut ret = 0 as *mut _; + let err = unsafe { + RegOpenKeyExW( + self.raw(), + key.as_ptr(), + 0, + KEY_READ | KEY_WOW64_32KEY, + &mut ret, + ) + }; + if err == ERROR_SUCCESS as LONG { + Ok(RegistryKey(Repr::Owned(OwnedKey(ret)))) + } else { + Err(io::Error::from_raw_os_error(err as i32)) + } + } + + pub fn iter(&self) -> Iter { + Iter { + idx: 0.., + key: self, + } + } + + pub fn query_str(&self, name: &str) -> io::Result { + let name: &OsStr = name.as_ref(); + let name = name.encode_wide().chain(Some(0)).collect::>(); + let mut len = 0; + let mut kind = 0; + unsafe { + let err = RegQueryValueExW( + self.raw(), + name.as_ptr(), + 0 as *mut _, + &mut kind, + 0 as *mut _, + &mut len, + ); + if err != ERROR_SUCCESS as LONG { + return Err(io::Error::from_raw_os_error(err as i32)); + } + if kind != REG_SZ { + return Err(io::Error::new( + io::ErrorKind::Other, + "registry key wasn't a string", + )); + } + + // The length here is the length in bytes, but we're using wide + // characters so we need to be sure to halve it for the capacity + // passed in. + let mut v = Vec::with_capacity(len as usize / 2); + let err = RegQueryValueExW( + self.raw(), + name.as_ptr(), + 0 as *mut _, + 0 as *mut _, + v.as_mut_ptr() as *mut _, + &mut len, + ); + if err != ERROR_SUCCESS as LONG { + return Err(io::Error::from_raw_os_error(err as i32)); + } + v.set_len(len as usize / 2); + + // Some registry keys may have a terminating nul character, but + // we're not interested in that, so chop it off if it's there. + if v[v.len() - 1] == 0 { + v.pop(); + } + Ok(OsString::from_wide(&v)) + } + } +} + +impl Drop for OwnedKey { + fn drop(&mut self) { + unsafe { + RegCloseKey(self.0); + } + } +} + +impl<'a> Iterator for Iter<'a> { + type Item = io::Result; + + fn next(&mut self) -> Option> { + self.idx.next().and_then(|i| unsafe { + let mut v = Vec::with_capacity(256); + let mut len = v.capacity() as DWORD; + let ret = RegEnumKeyExW( + self.key.raw(), + i, + v.as_mut_ptr(), + &mut len, + 0 as *mut _, + 0 as *mut _, + 0 as *mut _, + 0 as *mut _, + ); + if ret == ERROR_NO_MORE_ITEMS as LONG { + None + } else if ret != ERROR_SUCCESS as LONG { + Some(Err(io::Error::from_raw_os_error(ret as i32))) + } else { + v.set_len(len as usize); + Some(Ok(OsString::from_wide(&v))) + } + }) + } +} diff -Nru cargo-0.25.0/vendor/cc-1.0.10/src/setup_config.rs cargo-0.26.0/vendor/cc-1.0.10/src/setup_config.rs --- cargo-0.25.0/vendor/cc-1.0.10/src/setup_config.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/src/setup_config.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,283 @@ +// Copyright © 2017 winapi-rs developers +// Licensed under the Apache License, Version 2.0 +// or the MIT license +// , at your option. +// All files in the project carrying such notice may not be copied, modified, or distributed +// except according to those terms. + +#![allow(bad_style)] +#![allow(unused)] + +use std::ffi::OsString; +use std::ptr::null_mut; +use winapi::Interface; +use winapi::{LPFILETIME, ULONG}; +use winapi::S_FALSE; +use winapi::BSTR; +use winapi::LPCOLESTR; +use winapi::{CoCreateInstance, CLSCTX_ALL}; +use winapi::LPSAFEARRAY; +use winapi::{IUnknown, IUnknownVtbl}; +use winapi::{HRESULT, LCID, LPCWSTR, PULONGLONG}; + +use com::{BStr, ComPtr}; + +// Bindings to the Setup.Configuration stuff +pub type InstanceState = u32; + +pub const eNone: InstanceState = 0; +pub const eLocal: InstanceState = 1; +pub const eRegistered: InstanceState = 2; +pub const eNoRebootRequired: InstanceState = 4; +pub const eComplete: InstanceState = -1i32 as u32; + +RIDL!{#[uuid(0xb41463c3, 0x8866, 0x43b5, 0xbc, 0x33, 0x2b, 0x06, 0x76, 0xf7, 0xf4, 0x2e)] +interface ISetupInstance(ISetupInstanceVtbl): IUnknown(IUnknownVtbl) { + fn GetInstanceId( + pbstrInstanceId: *mut BSTR, + ) -> HRESULT, + fn GetInstallDate( + pInstallDate: LPFILETIME, + ) -> HRESULT, + fn GetInstallationName( + pbstrInstallationName: *mut BSTR, + ) -> HRESULT, + fn GetInstallationPath( + pbstrInstallationPath: *mut BSTR, + ) -> HRESULT, + fn GetInstallationVersion( + pbstrInstallationVersion: *mut BSTR, + ) -> HRESULT, + fn GetDisplayName( + lcid: LCID, + pbstrDisplayName: *mut BSTR, + ) -> HRESULT, + fn GetDescription( + lcid: LCID, + pbstrDescription: *mut BSTR, + ) -> HRESULT, + fn ResolvePath( + pwszRelativePath: LPCOLESTR, + pbstrAbsolutePath: *mut BSTR, + ) -> HRESULT, +}} + +RIDL!{#[uuid(0x89143c9a, 0x05af, 0x49b0, 0xb7, 0x17, 0x72, 0xe2, 0x18, 0xa2, 0x18, 0x5c)] +interface ISetupInstance2(ISetupInstance2Vtbl): ISetupInstance(ISetupInstanceVtbl) { + fn GetState( + pState: *mut InstanceState, + ) -> HRESULT, + fn GetPackages( + ppsaPackages: *mut LPSAFEARRAY, + ) -> HRESULT, + fn GetProduct( + ppPackage: *mut *mut ISetupPackageReference, + ) -> HRESULT, + fn GetProductPath( + pbstrProductPath: *mut BSTR, + ) -> HRESULT, +}} + +RIDL!{#[uuid(0x6380bcff, 0x41d3, 0x4b2e, 0x8b, 0x2e, 0xbf, 0x8a, 0x68, 0x10, 0xc8, 0x48)] +interface IEnumSetupInstances(IEnumSetupInstancesVtbl): IUnknown(IUnknownVtbl) { + fn Next( + celt: ULONG, + rgelt: *mut *mut ISetupInstance, + pceltFetched: *mut ULONG, + ) -> HRESULT, + fn Skip( + celt: ULONG, + ) -> HRESULT, + fn Reset() -> HRESULT, + fn Clone( + ppenum: *mut *mut IEnumSetupInstances, + ) -> HRESULT, +}} + +RIDL!{#[uuid(0x42843719, 0xdb4c, 0x46c2, 0x8e, 0x7c, 0x64, 0xf1, 0x81, 0x6e, 0xfd, 0x5b)] +interface ISetupConfiguration(ISetupConfigurationVtbl): IUnknown(IUnknownVtbl) { + fn EnumInstances( + ppEnumInstances: *mut *mut IEnumSetupInstances, + ) -> HRESULT, + fn GetInstanceForCurrentProcess( + ppInstance: *mut *mut ISetupInstance, + ) -> HRESULT, + fn GetInstanceForPath( + wzPath: LPCWSTR, + ppInstance: *mut *mut ISetupInstance, + ) -> HRESULT, +}} + +RIDL!{#[uuid(0x26aab78c, 0x4a60, 0x49d6, 0xaf, 0x3b, 0x3c, 0x35, 0xbc, 0x93, 0x36, 0x5d)] +interface ISetupConfiguration2(ISetupConfiguration2Vtbl): + ISetupConfiguration(ISetupConfigurationVtbl) { + fn EnumAllInstances( + ppEnumInstances: *mut *mut IEnumSetupInstances, + ) -> HRESULT, +}} + +RIDL!{#[uuid(0xda8d8a16, 0xb2b6, 0x4487, 0xa2, 0xf1, 0x59, 0x4c, 0xcc, 0xcd, 0x6b, 0xf5)] +interface ISetupPackageReference(ISetupPackageReferenceVtbl): IUnknown(IUnknownVtbl) { + fn GetId( + pbstrId: *mut BSTR, + ) -> HRESULT, + fn GetVersion( + pbstrVersion: *mut BSTR, + ) -> HRESULT, + fn GetChip( + pbstrChip: *mut BSTR, + ) -> HRESULT, + fn GetLanguage( + pbstrLanguage: *mut BSTR, + ) -> HRESULT, + fn GetBranch( + pbstrBranch: *mut BSTR, + ) -> HRESULT, + fn GetType( + pbstrType: *mut BSTR, + ) -> HRESULT, + fn GetUniqueId( + pbstrUniqueId: *mut BSTR, + ) -> HRESULT, +}} + +RIDL!{#[uuid(0x42b21b78, 0x6192, 0x463e, 0x87, 0xbf, 0xd5, 0x77, 0x83, 0x8f, 0x1d, 0x5c)] +interface ISetupHelper(ISetupHelperVtbl): IUnknown(IUnknownVtbl) { + fn ParseVersion( + pwszVersion: LPCOLESTR, + pullVersion: PULONGLONG, + ) -> HRESULT, + fn ParseVersionRange( + pwszVersionRange: LPCOLESTR, + pullMinVersion: PULONGLONG, + pullMaxVersion: PULONGLONG, + ) -> HRESULT, +}} + +DEFINE_GUID!{CLSID_SetupConfiguration, +0x177f0c4a, 0x1cd3, 0x4de7, 0xa3, 0x2c, 0x71, 0xdb, 0xbb, 0x9f, 0xa3, 0x6d} + +// Safe wrapper around the COM interfaces +pub struct SetupConfiguration(ComPtr); + +impl SetupConfiguration { + pub fn new() -> Result { + let mut obj = null_mut(); + let err = unsafe { + CoCreateInstance( + &CLSID_SetupConfiguration, + null_mut(), + CLSCTX_ALL, + &ISetupConfiguration::uuidof(), + &mut obj, + ) + }; + if err < 0 { + return Err(err); + } + let obj = unsafe { ComPtr::from_raw(obj as *mut ISetupConfiguration) }; + Ok(SetupConfiguration(obj)) + } + pub fn get_instance_for_current_process(&self) -> Result { + let mut obj = null_mut(); + let err = unsafe { self.0.GetInstanceForCurrentProcess(&mut obj) }; + if err < 0 { + return Err(err); + } + Ok(unsafe { SetupInstance::from_raw(obj) }) + } + pub fn enum_instances(&self) -> Result { + let mut obj = null_mut(); + let err = unsafe { self.0.EnumInstances(&mut obj) }; + if err < 0 { + return Err(err); + } + Ok(unsafe { EnumSetupInstances::from_raw(obj) }) + } + pub fn enum_all_instances(&self) -> Result { + let mut obj = null_mut(); + let this = try!(self.0.cast::()); + let err = unsafe { this.EnumAllInstances(&mut obj) }; + if err < 0 { + return Err(err); + } + Ok(unsafe { EnumSetupInstances::from_raw(obj) }) + } +} + +pub struct SetupInstance(ComPtr); + +impl SetupInstance { + pub unsafe fn from_raw(obj: *mut ISetupInstance) -> SetupInstance { + SetupInstance(ComPtr::from_raw(obj)) + } + pub fn instance_id(&self) -> Result { + let mut s = null_mut(); + let err = unsafe { self.0.GetInstanceId(&mut s) }; + let bstr = unsafe { BStr::from_raw(s) }; + if err < 0 { + return Err(err); + } + Ok(bstr.to_osstring()) + } + pub fn installation_name(&self) -> Result { + let mut s = null_mut(); + let err = unsafe { self.0.GetInstallationName(&mut s) }; + let bstr = unsafe { BStr::from_raw(s) }; + if err < 0 { + return Err(err); + } + Ok(bstr.to_osstring()) + } + pub fn installation_path(&self) -> Result { + let mut s = null_mut(); + let err = unsafe { self.0.GetInstallationPath(&mut s) }; + let bstr = unsafe { BStr::from_raw(s) }; + if err < 0 { + return Err(err); + } + Ok(bstr.to_osstring()) + } + pub fn installation_version(&self) -> Result { + let mut s = null_mut(); + let err = unsafe { self.0.GetInstallationVersion(&mut s) }; + let bstr = unsafe { BStr::from_raw(s) }; + if err < 0 { + return Err(err); + } + Ok(bstr.to_osstring()) + } + pub fn product_path(&self) -> Result { + let mut s = null_mut(); + let this = try!(self.0.cast::()); + let err = unsafe { this.GetProductPath(&mut s) }; + let bstr = unsafe { BStr::from_raw(s) }; + if err < 0 { + return Err(err); + } + Ok(bstr.to_osstring()) + } +} + +pub struct EnumSetupInstances(ComPtr); + +impl EnumSetupInstances { + pub unsafe fn from_raw(obj: *mut IEnumSetupInstances) -> EnumSetupInstances { + EnumSetupInstances(ComPtr::from_raw(obj)) + } +} + +impl Iterator for EnumSetupInstances { + type Item = Result; + fn next(&mut self) -> Option> { + let mut obj = null_mut(); + let err = unsafe { self.0.Next(1, &mut obj, null_mut()) }; + if err < 0 { + return Some(Err(err)); + } + if err == S_FALSE { + return None; + } + Some(Ok(unsafe { SetupInstance::from_raw(obj) })) + } +} diff -Nru cargo-0.25.0/vendor/cc-1.0.10/src/winapi.rs cargo-0.26.0/vendor/cc-1.0.10/src/winapi.rs --- cargo-0.25.0/vendor/cc-1.0.10/src/winapi.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/src/winapi.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,218 @@ +// Copyright © 2015-2017 winapi-rs developers +// Licensed under the Apache License, Version 2.0 +// or the MIT license +// , at your option. +// All files in the project carrying such notice may not be copied, modified, or distributed +// except according to those terms. + +#![allow(bad_style)] + +use std::os::raw; + +pub type wchar_t = u16; + +pub type UINT = raw::c_uint; +pub type LPUNKNOWN = *mut IUnknown; +pub type REFIID = *const IID; +pub type IID = GUID; +pub type REFCLSID = *const IID; +pub type PVOID = *mut raw::c_void; +pub type USHORT = raw::c_ushort; +pub type ULONG = raw::c_ulong; +pub type LONG = raw::c_long; +pub type DWORD = u32; +pub type LPVOID = *mut raw::c_void; +pub type HRESULT = raw::c_long; +pub type LPFILETIME = *mut FILETIME; +pub type BSTR = *mut OLECHAR; +pub type OLECHAR = WCHAR; +pub type WCHAR = wchar_t; +pub type LPCOLESTR = *const OLECHAR; +pub type LCID = DWORD; +pub type LPCWSTR = *const WCHAR; +pub type PULONGLONG = *mut ULONGLONG; +pub type ULONGLONG = u64; + +pub const S_OK: HRESULT = 0; +pub const S_FALSE: HRESULT = 1; +pub const COINIT_MULTITHREADED: u32 = 0x0; + +pub type CLSCTX = u32; + +pub const CLSCTX_INPROC_SERVER: CLSCTX = 0x1; +pub const CLSCTX_INPROC_HANDLER: CLSCTX = 0x2; +pub const CLSCTX_LOCAL_SERVER: CLSCTX = 0x4; +pub const CLSCTX_REMOTE_SERVER: CLSCTX = 0x10; + +pub const CLSCTX_ALL: CLSCTX = + CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER; + +#[repr(C)] +#[derive(Copy, Clone)] +pub struct GUID { + pub Data1: raw::c_ulong, + pub Data2: raw::c_ushort, + pub Data3: raw::c_ushort, + pub Data4: [raw::c_uchar; 8], +} + +#[repr(C)] +#[derive(Copy, Clone)] +pub struct FILETIME { + pub dwLowDateTime: DWORD, + pub dwHighDateTime: DWORD, +} + +pub trait Interface { + fn uuidof() -> GUID; +} + +#[link(name = "ole32")] +#[link(name = "oleaut32")] +extern "C" {} + +extern "system" { + pub fn CoInitializeEx(pvReserved: LPVOID, dwCoInit: DWORD) -> HRESULT; + pub fn CoCreateInstance( + rclsid: REFCLSID, + pUnkOuter: LPUNKNOWN, + dwClsContext: DWORD, + riid: REFIID, + ppv: *mut LPVOID, + ) -> HRESULT; + pub fn SysFreeString(bstrString: BSTR); + pub fn SysStringLen(pbstr: BSTR) -> UINT; +} + +#[repr(C)] +#[derive(Copy, Clone)] +pub struct SAFEARRAYBOUND { + pub cElements: ULONG, + pub lLbound: LONG, +} + +#[repr(C)] +#[derive(Copy, Clone)] +pub struct SAFEARRAY { + pub cDims: USHORT, + pub fFeatures: USHORT, + pub cbElements: ULONG, + pub cLocks: ULONG, + pub pvData: PVOID, + pub rgsabound: [SAFEARRAYBOUND; 1], +} + +pub type LPSAFEARRAY = *mut SAFEARRAY; + +macro_rules! DEFINE_GUID { + ( + $name:ident, $l:expr, $w1:expr, $w2:expr, + $b1:expr, $b2:expr, $b3:expr, $b4:expr, $b5:expr, $b6:expr, $b7:expr, $b8:expr + ) => { + pub const $name: $crate::winapi::GUID = $crate::winapi::GUID { + Data1: $l, + Data2: $w1, + Data3: $w2, + Data4: [$b1, $b2, $b3, $b4, $b5, $b6, $b7, $b8], + }; + } +} + +macro_rules! RIDL { + (#[uuid($($uuid:expr),+)] + interface $interface:ident ($vtbl:ident) {$( + fn $method:ident($($p:ident : $t:ty,)*) -> $rtr:ty, + )+}) => ( + #[repr(C)] + pub struct $vtbl { + $(pub $method: unsafe extern "system" fn( + This: *mut $interface, + $($p: $t),* + ) -> $rtr,)+ + } + #[repr(C)] + pub struct $interface { + pub lpVtbl: *const $vtbl, + } + RIDL!{@impl $interface {$(fn $method($($p: $t,)*) -> $rtr,)+}} + RIDL!{@uuid $interface $($uuid),+} + ); + (#[uuid($($uuid:expr),+)] + interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident) { + }) => ( + #[repr(C)] + pub struct $vtbl { + pub parent: $pvtbl, + } + #[repr(C)] + pub struct $interface { + pub lpVtbl: *const $vtbl, + } + RIDL!{@deref $interface $pinterface} + RIDL!{@uuid $interface $($uuid),+} + ); + (#[uuid($($uuid:expr),+)] + interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident) {$( + fn $method:ident($($p:ident : $t:ty,)*) -> $rtr:ty, + )+}) => ( + #[repr(C)] + pub struct $vtbl { + pub parent: $pvtbl, + $(pub $method: unsafe extern "system" fn( + This: *mut $interface, + $($p: $t,)* + ) -> $rtr,)+ + } + #[repr(C)] + pub struct $interface { + pub lpVtbl: *const $vtbl, + } + RIDL!{@impl $interface {$(fn $method($($p: $t,)*) -> $rtr,)+}} + RIDL!{@deref $interface $pinterface} + RIDL!{@uuid $interface $($uuid),+} + ); + (@deref $interface:ident $pinterface:ident) => ( + impl ::std::ops::Deref for $interface { + type Target = $pinterface; + #[inline] + fn deref(&self) -> &$pinterface { + unsafe { &*(self as *const $interface as *const $pinterface) } + } + } + ); + (@impl $interface:ident {$( + fn $method:ident($($p:ident : $t:ty,)*) -> $rtr:ty, + )+}) => ( + impl $interface { + $(#[inline] pub unsafe fn $method(&self, $($p: $t,)*) -> $rtr { + ((*self.lpVtbl).$method)(self as *const _ as *mut _, $($p,)*) + })+ + } + ); + (@uuid $interface:ident + $l:expr, $w1:expr, $w2:expr, + $b1:expr, $b2:expr, $b3:expr, $b4:expr, $b5:expr, $b6:expr, $b7:expr, $b8:expr + ) => ( + impl $crate::winapi::Interface for $interface { + #[inline] + fn uuidof() -> $crate::winapi::GUID { + $crate::winapi::GUID { + Data1: $l, + Data2: $w1, + Data3: $w2, + Data4: [$b1, $b2, $b3, $b4, $b5, $b6, $b7, $b8], + } + } + } + ); +} + +RIDL!{#[uuid(0x00000000, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46)] +interface IUnknown(IUnknownVtbl) { + fn QueryInterface( + riid: REFIID, + ppvObject: *mut *mut raw::c_void, + ) -> HRESULT, + fn AddRef() -> ULONG, + fn Release() -> ULONG, +}} diff -Nru cargo-0.25.0/vendor/cc-1.0.10/src/windows_registry.rs cargo-0.26.0/vendor/cc-1.0.10/src/windows_registry.rs --- cargo-0.25.0/vendor/cc-1.0.10/src/windows_registry.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/src/windows_registry.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,671 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A helper module to probe the Windows Registry when looking for +//! windows-specific tools. + +use std::process::Command; + +use Tool; + +#[cfg(windows)] +macro_rules! otry { + ($expr:expr) => (match $expr { + Some(val) => val, + None => return None, + }) +} + +/// Attempts to find a tool within an MSVC installation using the Windows +/// registry as a point to search from. +/// +/// The `target` argument is the target that the tool should work for (e.g. +/// compile or link for) and the `tool` argument is the tool to find (e.g. +/// `cl.exe` or `link.exe`). +/// +/// This function will return `None` if the tool could not be found, or it will +/// return `Some(cmd)` which represents a command that's ready to execute the +/// tool with the appropriate environment variables set. +/// +/// Note that this function always returns `None` for non-MSVC targets. +pub fn find(target: &str, tool: &str) -> Option { + find_tool(target, tool).map(|c| c.to_command()) +} + +/// Similar to the `find` function above, this function will attempt the same +/// operation (finding a MSVC tool in a local install) but instead returns a +/// `Tool` which may be introspected. +#[cfg(not(windows))] +pub fn find_tool(_target: &str, _tool: &str) -> Option { + None +} + +/// Documented above. +#[cfg(windows)] +pub fn find_tool(target: &str, tool: &str) -> Option { + use std::env; + + // This logic is all tailored for MSVC, if we're not that then bail out + // early. + if !target.contains("msvc") { + return None; + } + + // Looks like msbuild isn't located in the same location as other tools like + // cl.exe and lib.exe. To handle this we probe for it manually with + // dedicated registry keys. + if tool.contains("msbuild") { + return impl_::find_msbuild(target); + } + + // If VCINSTALLDIR is set, then someone's probably already run vcvars and we + // should just find whatever that indicates. + if env::var_os("VCINSTALLDIR").is_some() { + return env::var_os("PATH") + .and_then(|path| { + env::split_paths(&path) + .map(|p| p.join(tool)) + .find(|p| p.exists()) + }) + .map(|path| Tool::new(path.into())); + } + + // Ok, if we're here, now comes the fun part of the probing. Default shells + // or shells like MSYS aren't really configured to execute `cl.exe` and the + // various compiler tools shipped as part of Visual Studio. Here we try to + // first find the relevant tool, then we also have to be sure to fill in + // environment variables like `LIB`, `INCLUDE`, and `PATH` to ensure that + // the tool is actually usable. + + return impl_::find_msvc_15(tool, target) + .or_else(|| impl_::find_msvc_14(tool, target)) + .or_else(|| impl_::find_msvc_12(tool, target)) + .or_else(|| impl_::find_msvc_11(tool, target)); +} + +/// A version of Visual Studio +#[derive(Debug, PartialEq, Eq, Copy, Clone)] +pub enum VsVers { + /// Visual Studio 12 (2013) + Vs12, + /// Visual Studio 14 (2015) + Vs14, + /// Visual Studio 15 (2017) + Vs15, + + /// Hidden variant that should not be matched on. Callers that want to + /// handle an enumeration of `VsVers` instances should always have a default + /// case meaning that it's a VS version they don't understand. + #[doc(hidden)] + #[allow(bad_style)] + __Nonexhaustive_do_not_match_this_or_your_code_will_break, +} + +/// Find the most recent installed version of Visual Studio +/// +/// This is used by the cmake crate to figure out the correct +/// generator. +#[cfg(not(windows))] +pub fn find_vs_version() -> Result { + Err(format!("not windows")) +} + +/// Documented above +#[cfg(windows)] +pub fn find_vs_version() -> Result { + use std::env; + + match env::var("VisualStudioVersion") { + Ok(version) => match &version[..] { + "15.0" => Ok(VsVers::Vs15), + "14.0" => Ok(VsVers::Vs14), + "12.0" => Ok(VsVers::Vs12), + vers => Err(format!( + "\n\n\ + unsupported or unknown VisualStudio version: {}\n\ + if another version is installed consider running \ + the appropriate vcvars script before building this \ + crate\n\ + ", + vers + )), + }, + _ => { + // Check for the presense of a specific registry key + // that indicates visual studio is installed. + if impl_::has_msbuild_version("15.0") { + Ok(VsVers::Vs15) + } else if impl_::has_msbuild_version("14.0") { + Ok(VsVers::Vs14) + } else if impl_::has_msbuild_version("12.0") { + Ok(VsVers::Vs12) + } else { + Err(format!( + "\n\n\ + couldn't determine visual studio generator\n\ + if VisualStudio is installed, however, consider \ + running the appropriate vcvars script before building \ + this crate\n\ + " + )) + } + } + } +} + +#[cfg(windows)] +mod impl_ { + use std::env; + use std::ffi::OsString; + use std::mem; + use std::path::{Path, PathBuf}; + use std::fs::File; + use std::io::Read; + use registry::{RegistryKey, LOCAL_MACHINE}; + use com; + use setup_config::{SetupConfiguration, SetupInstance}; + + use Tool; + + struct MsvcTool { + tool: PathBuf, + libs: Vec, + path: Vec, + include: Vec, + } + + impl MsvcTool { + fn new(tool: PathBuf) -> MsvcTool { + MsvcTool { + tool: tool, + libs: Vec::new(), + path: Vec::new(), + include: Vec::new(), + } + } + + fn into_tool(self) -> Tool { + let MsvcTool { + tool, + libs, + path, + include, + } = self; + let mut tool = Tool::new(tool.into()); + add_env(&mut tool, "LIB", libs); + add_env(&mut tool, "PATH", path); + add_env(&mut tool, "INCLUDE", include); + tool + } + } + + // In MSVC 15 (2017) MS once again changed the scheme for locating + // the tooling. Now we must go through some COM interfaces, which + // is super fun for Rust. + // + // Note that much of this logic can be found [online] wrt paths, COM, etc. + // + // [online]: https://blogs.msdn.microsoft.com/vcblog/2017/03/06/finding-the-visual-c-compiler-tools-in-visual-studio-2017/ + pub fn find_msvc_15(tool: &str, target: &str) -> Option { + otry!(com::initialize().ok()); + + let config = otry!(SetupConfiguration::new().ok()); + let iter = otry!(config.enum_all_instances().ok()); + for instance in iter { + let instance = otry!(instance.ok()); + let tool = tool_from_vs15_instance(tool, target, &instance); + if tool.is_some() { + return tool; + } + } + + None + } + + fn tool_from_vs15_instance(tool: &str, target: &str, instance: &SetupInstance) -> Option { + let (bin_path, host_dylib_path, lib_path, include_path) = + otry!(vs15_vc_paths(target, instance)); + let tool_path = bin_path.join(tool); + if !tool_path.exists() { + return None; + }; + + let mut tool = MsvcTool::new(tool_path); + tool.path.push(host_dylib_path); + tool.libs.push(lib_path); + tool.include.push(include_path); + + if let Some((atl_lib_path, atl_include_path)) = atl_paths(target, &bin_path) { + tool.libs.push(atl_lib_path); + tool.include.push(atl_include_path); + } + + otry!(add_sdks(&mut tool, target)); + + Some(tool.into_tool()) + } + + fn vs15_vc_paths( + target: &str, + instance: &SetupInstance, + ) -> Option<(PathBuf, PathBuf, PathBuf, PathBuf)> { + let instance_path: PathBuf = otry!(instance.installation_path().ok()).into(); + let version_path = + instance_path.join(r"VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt"); + let mut version_file = otry!(File::open(version_path).ok()); + let mut version = String::new(); + otry!(version_file.read_to_string(&mut version).ok()); + let version = version.trim(); + let host = match host_arch() { + X86 => "X86", + X86_64 => "X64", + _ => return None, + }; + let target = otry!(lib_subdir(target)); + // The directory layout here is MSVC/bin/Host$host/$target/ + let path = instance_path.join(r"VC\Tools\MSVC").join(version); + // This is the path to the toolchain for a particular target, running + // on a given host + let bin_path = path.join("bin") + .join(&format!("Host{}", host)) + .join(&target); + // But! we also need PATH to contain the target directory for the host + // architecture, because it contains dlls like mspdb140.dll compiled for + // the host architecture. + let host_dylib_path = path.join("bin") + .join(&format!("Host{}", host)) + .join(&host.to_lowercase()); + let lib_path = path.join("lib").join(&target); + let include_path = path.join("include"); + Some((bin_path, host_dylib_path, lib_path, include_path)) + } + + fn atl_paths(target: &str, path: &Path) -> Option<(PathBuf, PathBuf)> { + let atl_path = path.join("atlfmc"); + let sub = otry!(lib_subdir(target)); + if atl_path.exists() { + Some((atl_path.join("lib").join(sub), atl_path.join("include"))) + } else { + None + } + } + + // For MSVC 14 we need to find the Universal CRT as well as either + // the Windows 10 SDK or Windows 8.1 SDK. + pub fn find_msvc_14(tool: &str, target: &str) -> Option { + let vcdir = otry!(get_vc_dir("14.0")); + let mut tool = otry!(get_tool(tool, &vcdir, target)); + otry!(add_sdks(&mut tool, target)); + Some(tool.into_tool()) + } + + fn add_sdks(tool: &mut MsvcTool, target: &str) -> Option<()> { + let sub = otry!(lib_subdir(target)); + let (ucrt, ucrt_version) = otry!(get_ucrt_dir()); + + tool.path + .push(ucrt.join("bin").join(&ucrt_version).join(sub)); + + let ucrt_include = ucrt.join("include").join(&ucrt_version); + tool.include.push(ucrt_include.join("ucrt")); + + let ucrt_lib = ucrt.join("lib").join(&ucrt_version); + tool.libs.push(ucrt_lib.join("ucrt").join(sub)); + + if let Some((sdk, version)) = get_sdk10_dir() { + tool.path.push(sdk.join("bin").join(sub)); + let sdk_lib = sdk.join("lib").join(&version); + tool.libs.push(sdk_lib.join("um").join(sub)); + let sdk_include = sdk.join("include").join(&version); + tool.include.push(sdk_include.join("um")); + tool.include.push(sdk_include.join("winrt")); + tool.include.push(sdk_include.join("shared")); + } else if let Some(sdk) = get_sdk81_dir() { + tool.path.push(sdk.join("bin").join(sub)); + let sdk_lib = sdk.join("lib").join("winv6.3"); + tool.libs.push(sdk_lib.join("um").join(sub)); + let sdk_include = sdk.join("include"); + tool.include.push(sdk_include.join("um")); + tool.include.push(sdk_include.join("winrt")); + tool.include.push(sdk_include.join("shared")); + } + + Some(()) + } + + // For MSVC 12 we need to find the Windows 8.1 SDK. + pub fn find_msvc_12(tool: &str, target: &str) -> Option { + let vcdir = otry!(get_vc_dir("12.0")); + let mut tool = otry!(get_tool(tool, &vcdir, target)); + let sub = otry!(lib_subdir(target)); + let sdk81 = otry!(get_sdk81_dir()); + tool.path.push(sdk81.join("bin").join(sub)); + let sdk_lib = sdk81.join("lib").join("winv6.3"); + tool.libs.push(sdk_lib.join("um").join(sub)); + let sdk_include = sdk81.join("include"); + tool.include.push(sdk_include.join("shared")); + tool.include.push(sdk_include.join("um")); + tool.include.push(sdk_include.join("winrt")); + Some(tool.into_tool()) + } + + // For MSVC 11 we need to find the Windows 8 SDK. + pub fn find_msvc_11(tool: &str, target: &str) -> Option { + let vcdir = otry!(get_vc_dir("11.0")); + let mut tool = otry!(get_tool(tool, &vcdir, target)); + let sub = otry!(lib_subdir(target)); + let sdk8 = otry!(get_sdk8_dir()); + tool.path.push(sdk8.join("bin").join(sub)); + let sdk_lib = sdk8.join("lib").join("win8"); + tool.libs.push(sdk_lib.join("um").join(sub)); + let sdk_include = sdk8.join("include"); + tool.include.push(sdk_include.join("shared")); + tool.include.push(sdk_include.join("um")); + tool.include.push(sdk_include.join("winrt")); + Some(tool.into_tool()) + } + + fn add_env(tool: &mut Tool, env: &str, paths: Vec) { + let prev = env::var_os(env).unwrap_or(OsString::new()); + let prev = env::split_paths(&prev); + let new = paths.into_iter().chain(prev); + tool.env + .push((env.to_string().into(), env::join_paths(new).unwrap())); + } + + // Given a possible MSVC installation directory, we look for the linker and + // then add the MSVC library path. + fn get_tool(tool: &str, path: &Path, target: &str) -> Option { + bin_subdir(target) + .into_iter() + .map(|(sub, host)| { + ( + path.join("bin").join(sub).join(tool), + path.join("bin").join(host), + ) + }) + .filter(|&(ref path, _)| path.is_file()) + .map(|(path, host)| { + let mut tool = MsvcTool::new(path); + tool.path.push(host); + tool + }) + .filter_map(|mut tool| { + let sub = otry!(vc_lib_subdir(target)); + tool.libs.push(path.join("lib").join(sub)); + tool.include.push(path.join("include")); + let atlmfc_path = path.join("atlmfc"); + if atlmfc_path.exists() { + tool.libs.push(atlmfc_path.join("lib").join(sub)); + tool.include.push(atlmfc_path.join("include")); + } + Some(tool) + }) + .next() + } + + // To find MSVC we look in a specific registry key for the version we are + // trying to find. + fn get_vc_dir(ver: &str) -> Option { + let key = r"SOFTWARE\Microsoft\VisualStudio\SxS\VC7"; + let key = otry!(LOCAL_MACHINE.open(key.as_ref()).ok()); + let path = otry!(key.query_str(ver).ok()); + Some(path.into()) + } + + // To find the Universal CRT we look in a specific registry key for where + // all the Universal CRTs are located and then sort them asciibetically to + // find the newest version. While this sort of sorting isn't ideal, it is + // what vcvars does so that's good enough for us. + // + // Returns a pair of (root, version) for the ucrt dir if found + fn get_ucrt_dir() -> Option<(PathBuf, String)> { + let key = r"SOFTWARE\Microsoft\Windows Kits\Installed Roots"; + let key = otry!(LOCAL_MACHINE.open(key.as_ref()).ok()); + let root = otry!(key.query_str("KitsRoot10").ok()); + let readdir = otry!(Path::new(&root).join("lib").read_dir().ok()); + let max_libdir = otry!( + readdir + .filter_map(|dir| dir.ok()) + .map(|dir| dir.path()) + .filter(|dir| dir.components() + .last() + .and_then(|c| c.as_os_str().to_str()) + .map(|c| c.starts_with("10.") && dir.join("ucrt").is_dir()) + .unwrap_or(false)) + .max() + ); + let version = max_libdir.components().last().unwrap(); + let version = version.as_os_str().to_str().unwrap().to_string(); + Some((root.into(), version)) + } + + // Vcvars finds the correct version of the Windows 10 SDK by looking + // for the include `um\Windows.h` because sometimes a given version will + // only have UCRT bits without the rest of the SDK. Since we only care about + // libraries and not includes, we instead look for `um\x64\kernel32.lib`. + // Since the 32-bit and 64-bit libraries are always installed together we + // only need to bother checking x64, making this code a tiny bit simpler. + // Like we do for the Universal CRT, we sort the possibilities + // asciibetically to find the newest one as that is what vcvars does. + fn get_sdk10_dir() -> Option<(PathBuf, String)> { + let key = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v10.0"; + let key = otry!(LOCAL_MACHINE.open(key.as_ref()).ok()); + let root = otry!(key.query_str("InstallationFolder").ok()); + let readdir = otry!(Path::new(&root).join("lib").read_dir().ok()); + let mut dirs = readdir + .filter_map(|dir| dir.ok()) + .map(|dir| dir.path()) + .collect::>(); + dirs.sort(); + let dir = otry!( + dirs.into_iter() + .rev() + .filter(|dir| dir.join("um").join("x64").join("kernel32.lib").is_file()) + .next() + ); + let version = dir.components().last().unwrap(); + let version = version.as_os_str().to_str().unwrap().to_string(); + Some((root.into(), version)) + } + + // Interestingly there are several subdirectories, `win7` `win8` and + // `winv6.3`. Vcvars seems to only care about `winv6.3` though, so the same + // applies to us. Note that if we were targetting kernel mode drivers + // instead of user mode applications, we would care. + fn get_sdk81_dir() -> Option { + let key = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.1"; + let key = otry!(LOCAL_MACHINE.open(key.as_ref()).ok()); + let root = otry!(key.query_str("InstallationFolder").ok()); + Some(root.into()) + } + + fn get_sdk8_dir() -> Option { + let key = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.0"; + let key = otry!(LOCAL_MACHINE.open(key.as_ref()).ok()); + let root = otry!(key.query_str("InstallationFolder").ok()); + Some(root.into()) + } + + const PROCESSOR_ARCHITECTURE_INTEL: u16 = 0; + const PROCESSOR_ARCHITECTURE_AMD64: u16 = 9; + const X86: u16 = PROCESSOR_ARCHITECTURE_INTEL; + const X86_64: u16 = PROCESSOR_ARCHITECTURE_AMD64; + + // When choosing the tool to use, we have to choose the one which matches + // the target architecture. Otherwise we end up in situations where someone + // on 32-bit Windows is trying to cross compile to 64-bit and it tries to + // invoke the native 64-bit compiler which won't work. + // + // For the return value of this function, the first member of the tuple is + // the folder of the tool we will be invoking, while the second member is + // the folder of the host toolchain for that tool which is essential when + // using a cross linker. We return a Vec since on x64 there are often two + // linkers that can target the architecture we desire. The 64-bit host + // linker is preferred, and hence first, due to 64-bit allowing it more + // address space to work with and potentially being faster. + fn bin_subdir(target: &str) -> Vec<(&'static str, &'static str)> { + let arch = target.split('-').next().unwrap(); + match (arch, host_arch()) { + ("i586", X86) | ("i686", X86) => vec![("", "")], + ("i586", X86_64) | ("i686", X86_64) => vec![("amd64_x86", "amd64"), ("", "")], + ("x86_64", X86) => vec![("x86_amd64", "")], + ("x86_64", X86_64) => vec![("amd64", "amd64"), ("x86_amd64", "")], + ("arm", X86) => vec![("x86_arm", "")], + ("arm", X86_64) => vec![("amd64_arm", "amd64"), ("x86_arm", "")], + _ => vec![], + } + } + + fn lib_subdir(target: &str) -> Option<&'static str> { + let arch = target.split('-').next().unwrap(); + match arch { + "i586" | "i686" => Some("x86"), + "x86_64" => Some("x64"), + "arm" => Some("arm"), + "aarch64" => Some("arm64"), + _ => None, + } + } + + // MSVC's x86 libraries are not in a subfolder + fn vc_lib_subdir(target: &str) -> Option<&'static str> { + let arch = target.split('-').next().unwrap(); + match arch { + "i586" | "i686" => Some(""), + "x86_64" => Some("amd64"), + "arm" => Some("arm"), + "aarch64" => Some("arm64"), + _ => None, + } + } + + #[allow(bad_style)] + fn host_arch() -> u16 { + type DWORD = u32; + type WORD = u16; + type LPVOID = *mut u8; + type DWORD_PTR = usize; + + #[repr(C)] + struct SYSTEM_INFO { + wProcessorArchitecture: WORD, + _wReserved: WORD, + _dwPageSize: DWORD, + _lpMinimumApplicationAddress: LPVOID, + _lpMaximumApplicationAddress: LPVOID, + _dwActiveProcessorMask: DWORD_PTR, + _dwNumberOfProcessors: DWORD, + _dwProcessorType: DWORD, + _dwAllocationGranularity: DWORD, + _wProcessorLevel: WORD, + _wProcessorRevision: WORD, + } + + extern "system" { + fn GetNativeSystemInfo(lpSystemInfo: *mut SYSTEM_INFO); + } + + unsafe { + let mut info = mem::zeroed(); + GetNativeSystemInfo(&mut info); + info.wProcessorArchitecture + } + } + + // Given a registry key, look at all the sub keys and find the one which has + // the maximal numeric value. + // + // Returns the name of the maximal key as well as the opened maximal key. + fn max_version(key: &RegistryKey) -> Option<(OsString, RegistryKey)> { + let mut max_vers = 0; + let mut max_key = None; + for subkey in key.iter().filter_map(|k| k.ok()) { + let val = subkey + .to_str() + .and_then(|s| s.trim_left_matches("v").replace(".", "").parse().ok()); + let val = match val { + Some(s) => s, + None => continue, + }; + if val > max_vers { + if let Ok(k) = key.open(&subkey) { + max_vers = val; + max_key = Some((subkey, k)); + } + } + } + max_key + } + + pub fn has_msbuild_version(version: &str) -> bool { + match version { + "15.0" => { + find_msbuild_vs15("x86_64-pc-windows-msvc").is_some() + || find_msbuild_vs15("i686-pc-windows-msvc").is_some() + } + "12.0" | "14.0" => LOCAL_MACHINE + .open(&OsString::from(format!( + "SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\{}", + version + ))) + .is_ok(), + _ => false, + } + } + + // see http://stackoverflow.com/questions/328017/path-to-msbuild + pub fn find_msbuild(target: &str) -> Option { + // VS 15 (2017) changed how to locate msbuild + if let Some(r) = find_msbuild_vs15(target) { + return Some(r); + } else { + find_old_msbuild(target) + } + } + + fn find_msbuild_vs15(target: &str) -> Option { + // Seems like this could also go through SetupConfiguration, + // or that find_msvc_15 could just use this registry key + // instead of the COM interface. + let key = r"SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7"; + LOCAL_MACHINE + .open(key.as_ref()) + .ok() + .and_then(|key| key.query_str("15.0").ok()) + .map(|path| { + let path = PathBuf::from(path).join(r"MSBuild\15.0\Bin\MSBuild.exe"); + let mut tool = Tool::new(path); + if target.contains("x86_64") { + tool.env.push(("Platform".into(), "X64".into())); + } + tool + }) + } + + fn find_old_msbuild(target: &str) -> Option { + let key = r"SOFTWARE\Microsoft\MSBuild\ToolsVersions"; + LOCAL_MACHINE + .open(key.as_ref()) + .ok() + .and_then(|key| { + max_version(&key).and_then(|(_vers, key)| key.query_str("MSBuildToolsPath").ok()) + }) + .map(|path| { + let mut path = PathBuf::from(path); + path.push("MSBuild.exe"); + let mut tool = Tool::new(path); + if target.contains("x86_64") { + tool.env.push(("Platform".into(), "X64".into())); + } + tool + }) + } +} diff -Nru cargo-0.25.0/vendor/cc-1.0.10/tests/cc_env.rs cargo-0.26.0/vendor/cc-1.0.10/tests/cc_env.rs --- cargo-0.25.0/vendor/cc-1.0.10/tests/cc_env.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/tests/cc_env.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,119 @@ +extern crate cc; +extern crate tempdir; + +use std::env; +use std::path::Path; +use std::ffi::OsString; + +mod support; +use support::Test; + +#[test] +fn main() { + ccache(); + distcc(); + ccache_spaces(); + ccache_env_flags(); + leading_spaces(); + extra_flags(); + path_to_ccache(); + more_spaces(); +} + +fn ccache() { + let test = Test::gnu(); + + env::set_var("CC", "ccache cc"); + let compiler = test.gcc().file("foo.c").get_compiler(); + + assert_eq!(compiler.path(), Path::new("cc")); +} + +fn ccache_spaces() { + let test = Test::gnu(); + test.shim("ccache"); + + env::set_var("CC", "ccache cc"); + let compiler = test.gcc().file("foo.c").get_compiler(); + assert_eq!(compiler.path(), Path::new("cc")); +} + +fn distcc() { + let test = Test::gnu(); + test.shim("distcc"); + + env::set_var("CC", "distcc cc"); + let compiler = test.gcc().file("foo.c").get_compiler(); + assert_eq!(compiler.path(), Path::new("cc")); +} + +fn ccache_env_flags() { + let test = Test::gnu(); + test.shim("ccache"); + + env::set_var("CC", "ccache lol-this-is-not-a-compiler"); + let compiler = test.gcc().file("foo.c").get_compiler(); + assert_eq!(compiler.path(), Path::new("lol-this-is-not-a-compiler")); + assert_eq!( + compiler.cc_env(), + OsString::from("ccache lol-this-is-not-a-compiler") + ); + assert!( + compiler + .cflags_env() + .into_string() + .unwrap() + .contains("ccache") == false + ); + assert!( + compiler + .cflags_env() + .into_string() + .unwrap() + .contains(" lol-this-is-not-a-compiler") == false + ); + + env::set_var("CC", ""); +} + +fn leading_spaces() { + let test = Test::gnu(); + test.shim("ccache"); + + env::set_var("CC", " test "); + let compiler = test.gcc().file("foo.c").get_compiler(); + assert_eq!(compiler.path(), Path::new("test")); + + env::set_var("CC", ""); +} + +fn extra_flags() { + let test = Test::gnu(); + test.shim("ccache"); + + env::set_var("CC", "ccache cc -m32"); + let compiler = test.gcc().file("foo.c").get_compiler(); + assert_eq!(compiler.path(), Path::new("cc")); +} + +fn path_to_ccache() { + let test = Test::gnu(); + test.shim("ccache"); + + env::set_var("CC", "/path/to/ccache.exe cc -m32"); + let compiler = test.gcc().file("foo.c").get_compiler(); + assert_eq!(compiler.path(), Path::new("cc")); + assert_eq!( + compiler.cc_env(), + OsString::from("/path/to/ccache.exe cc -m32"), + ); +} + +fn more_spaces() { + let test = Test::gnu(); + test.shim("ccache"); + + env::set_var("CC", "cc -m32"); + let compiler = test.gcc().file("foo.c").get_compiler(); + assert_eq!(compiler.path(), Path::new("cc")); +} diff -Nru cargo-0.25.0/vendor/cc-1.0.10/tests/support/mod.rs cargo-0.26.0/vendor/cc-1.0.10/tests/support/mod.rs --- cargo-0.25.0/vendor/cc-1.0.10/tests/support/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/tests/support/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,131 @@ +#![allow(dead_code)] + +use std::env; +use std::ffi::OsStr; +use std::fs::{self, File}; +use std::io::prelude::*; +use std::path::PathBuf; + +use cc; +use tempdir::TempDir; + +pub struct Test { + pub td: TempDir, + pub gcc: PathBuf, + pub msvc: bool, +} + +pub struct Execution { + args: Vec, +} + +impl Test { + pub fn new() -> Test { + let mut gcc = PathBuf::from(env::current_exe().unwrap()); + gcc.pop(); + if gcc.ends_with("deps") { + gcc.pop(); + } + gcc.push(format!("gcc-shim{}", env::consts::EXE_SUFFIX)); + Test { + td: TempDir::new("gcc-test").unwrap(), + gcc: gcc, + msvc: false, + } + } + + pub fn gnu() -> Test { + let t = Test::new(); + t.shim("cc").shim("c++").shim("ar"); + t + } + + pub fn msvc() -> Test { + let mut t = Test::new(); + t.shim("cl").shim("lib.exe"); + t.msvc = true; + t + } + + pub fn shim(&self, name: &str) -> &Test { + let fname = format!("{}{}", name, env::consts::EXE_SUFFIX); + fs::hard_link(&self.gcc, self.td.path().join(&fname)) + .or_else(|_| fs::copy(&self.gcc, self.td.path().join(&fname)).map(|_| ())) + .unwrap(); + self + } + + pub fn gcc(&self) -> cc::Build { + let mut cfg = cc::Build::new(); + let mut path = env::split_paths(&env::var_os("PATH").unwrap()).collect::>(); + path.insert(0, self.td.path().to_owned()); + let target = if self.msvc { + "x86_64-pc-windows-msvc" + } else { + "x86_64-unknown-linux-gnu" + }; + + cfg.target(target) + .host(target) + .opt_level(2) + .debug(false) + .out_dir(self.td.path()) + .__set_env("PATH", env::join_paths(path).unwrap()) + .__set_env("GCCTEST_OUT_DIR", self.td.path()); + if self.msvc { + cfg.compiler(self.td.path().join("cl")); + cfg.archiver(self.td.path().join("lib.exe")); + } + cfg + } + + pub fn cmd(&self, i: u32) -> Execution { + let mut s = String::new(); + File::open(self.td.path().join(format!("out{}", i))) + .unwrap() + .read_to_string(&mut s) + .unwrap(); + Execution { + args: s.lines().map(|s| s.to_string()).collect(), + } + } +} + +impl Execution { + pub fn must_have>(&self, p: P) -> &Execution { + if !self.has(p.as_ref()) { + panic!("didn't find {:?} in {:?}", p.as_ref(), self.args); + } else { + self + } + } + + pub fn must_not_have>(&self, p: P) -> &Execution { + if self.has(p.as_ref()) { + panic!("found {:?}", p.as_ref()); + } else { + self + } + } + + pub fn has(&self, p: &OsStr) -> bool { + self.args.iter().any(|arg| OsStr::new(arg) == p) + } + + pub fn must_have_in_order(&self, before: &str, after: &str) -> &Execution { + let before_position = self.args + .iter() + .rposition(|x| OsStr::new(x) == OsStr::new(before)); + let after_position = self.args + .iter() + .rposition(|x| OsStr::new(x) == OsStr::new(after)); + match (before_position, after_position) { + (Some(b), Some(a)) if b < a => {} + (b, a) => panic!( + "{:?} (last position: {:?}) did not appear before {:?} (last position: {:?})", + before, b, after, a + ), + }; + self + } +} diff -Nru cargo-0.25.0/vendor/cc-1.0.10/tests/test.rs cargo-0.26.0/vendor/cc-1.0.10/tests/test.rs --- cargo-0.25.0/vendor/cc-1.0.10/tests/test.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/tests/test.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,308 @@ +extern crate cc; +extern crate tempdir; + +use support::Test; + +mod support; + +#[test] +fn gnu_smoke() { + let test = Test::gnu(); + test.gcc().file("foo.c").compile("foo"); + + test.cmd(0) + .must_have("-O2") + .must_have("foo.c") + .must_not_have("-g") + .must_have("-c") + .must_have("-ffunction-sections") + .must_have("-fdata-sections"); + test.cmd(1).must_have(test.td.path().join("foo.o")); +} + +#[test] +fn gnu_opt_level_1() { + let test = Test::gnu(); + test.gcc().opt_level(1).file("foo.c").compile("foo"); + + test.cmd(0).must_have("-O1").must_not_have("-O2"); +} + +#[test] +fn gnu_opt_level_s() { + let test = Test::gnu(); + test.gcc().opt_level_str("s").file("foo.c").compile("foo"); + + test.cmd(0) + .must_have("-Os") + .must_not_have("-O1") + .must_not_have("-O2") + .must_not_have("-O3") + .must_not_have("-Oz"); +} + +#[test] +fn gnu_debug() { + let test = Test::gnu(); + test.gcc().debug(true).file("foo.c").compile("foo"); + test.cmd(0).must_have("-g"); +} + +#[test] +fn gnu_warnings_into_errors() { + let test = Test::gnu(); + test.gcc() + .warnings_into_errors(true) + .file("foo.c") + .compile("foo"); + + test.cmd(0).must_have("-Werror"); +} + +#[test] +fn gnu_warnings() { + let test = Test::gnu(); + test.gcc() + .warnings(true) + .flag("-Wno-missing-field-initializers") + .file("foo.c") + .compile("foo"); + + test.cmd(0).must_have("-Wall").must_have("-Wextra"); +} + +#[test] +fn gnu_warnings_overridable() { + let test = Test::gnu(); + test.gcc() + .warnings(true) + .flag("-Wno-missing-field-initializers") + .file("foo.c") + .compile("foo"); + + test.cmd(0) + .must_have_in_order("-Wall", "-Wno-missing-field-initializers"); +} + +#[test] +fn gnu_x86_64() { + for vendor in &["unknown-linux-gnu", "apple-darwin"] { + let target = format!("x86_64-{}", vendor); + let test = Test::gnu(); + test.gcc() + .target(&target) + .host(&target) + .file("foo.c") + .compile("foo"); + + test.cmd(0).must_have("-fPIC").must_have("-m64"); + } +} + +#[test] +fn gnu_x86_64_no_pic() { + for vendor in &["unknown-linux-gnu", "apple-darwin"] { + let target = format!("x86_64-{}", vendor); + let test = Test::gnu(); + test.gcc() + .pic(false) + .target(&target) + .host(&target) + .file("foo.c") + .compile("foo"); + + test.cmd(0).must_not_have("-fPIC"); + } +} + +#[test] +fn gnu_i686() { + for vendor in &["unknown-linux-gnu", "apple-darwin"] { + let target = format!("i686-{}", vendor); + let test = Test::gnu(); + test.gcc() + .target(&target) + .host(&target) + .file("foo.c") + .compile("foo"); + + test.cmd(0).must_have("-m32"); + } +} + +#[test] +fn gnu_i686_pic() { + for vendor in &["unknown-linux-gnu", "apple-darwin"] { + let target = format!("i686-{}", vendor); + let test = Test::gnu(); + test.gcc() + .pic(true) + .target(&target) + .host(&target) + .file("foo.c") + .compile("foo"); + + test.cmd(0).must_have("-fPIC"); + } +} + +#[test] +fn gnu_set_stdlib() { + let test = Test::gnu(); + test.gcc() + .cpp_set_stdlib(Some("foo")) + .file("foo.c") + .compile("foo"); + + test.cmd(0).must_not_have("-stdlib=foo"); +} + +#[test] +fn gnu_include() { + let test = Test::gnu(); + test.gcc().include("foo/bar").file("foo.c").compile("foo"); + + test.cmd(0).must_have("-I").must_have("foo/bar"); +} + +#[test] +fn gnu_define() { + let test = Test::gnu(); + test.gcc() + .define("FOO", "bar") + .define("BAR", None) + .file("foo.c") + .compile("foo"); + + test.cmd(0).must_have("-DFOO=bar").must_have("-DBAR"); +} + +#[test] +fn gnu_compile_assembly() { + let test = Test::gnu(); + test.gcc().file("foo.S").compile("foo"); + test.cmd(0).must_have("foo.S"); +} + +#[test] +fn gnu_shared() { + let test = Test::gnu(); + test.gcc() + .file("foo.c") + .shared_flag(true) + .static_flag(false) + .compile("foo"); + + test.cmd(0).must_have("-shared").must_not_have("-static"); +} + +#[test] +fn gnu_flag_if_supported() { + if cfg!(windows) { + return; + } + let test = Test::gnu(); + test.gcc() + .file("foo.c") + .flag_if_supported("-Wall") + .flag_if_supported("-Wflag-does-not-exist") + .flag_if_supported("-std=c++11") + .compile("foo"); + + test.cmd(0) + .must_have("-Wall") + .must_not_have("-Wflag-does-not-exist") + .must_not_have("-std=c++11"); +} + +#[test] +fn gnu_flag_if_supported_cpp() { + if cfg!(windows) { + return; + } + let test = Test::gnu(); + test.gcc() + .cpp(true) + .file("foo.cpp") + .flag_if_supported("-std=c++11") + .compile("foo"); + + test.cmd(0).must_have("-std=c++11"); +} + +#[test] +fn gnu_static() { + let test = Test::gnu(); + test.gcc() + .file("foo.c") + .shared_flag(false) + .static_flag(true) + .compile("foo"); + + test.cmd(0).must_have("-static").must_not_have("-shared"); +} + +#[test] +fn msvc_smoke() { + let test = Test::msvc(); + test.gcc().file("foo.c").compile("foo"); + + test.cmd(0) + .must_have("/O2") + .must_have("foo.c") + .must_not_have("/Z7") + .must_have("/c") + .must_have("/MD"); + test.cmd(1).must_have(test.td.path().join("foo.o")); +} + +#[test] +fn msvc_opt_level_0() { + let test = Test::msvc(); + test.gcc().opt_level(0).file("foo.c").compile("foo"); + + test.cmd(0).must_not_have("/O2"); +} + +#[test] +fn msvc_debug() { + let test = Test::msvc(); + test.gcc().debug(true).file("foo.c").compile("foo"); + test.cmd(0).must_have("/Z7"); +} + +#[test] +fn msvc_include() { + let test = Test::msvc(); + test.gcc().include("foo/bar").file("foo.c").compile("foo"); + + test.cmd(0).must_have("/I").must_have("foo/bar"); +} + +#[test] +fn msvc_define() { + let test = Test::msvc(); + test.gcc() + .define("FOO", "bar") + .define("BAR", None) + .file("foo.c") + .compile("foo"); + + test.cmd(0).must_have("/DFOO=bar").must_have("/DBAR"); +} + +#[test] +fn msvc_static_crt() { + let test = Test::msvc(); + test.gcc().static_crt(true).file("foo.c").compile("foo"); + + test.cmd(0).must_have("/MT"); +} + +#[test] +fn msvc_no_static_crt() { + let test = Test::msvc(); + test.gcc().static_crt(false).file("foo.c").compile("foo"); + + test.cmd(0).must_have("/MD"); +} diff -Nru cargo-0.25.0/vendor/cc-1.0.10/.travis.yml cargo-0.26.0/vendor/cc-1.0.10/.travis.yml --- cargo-0.25.0/vendor/cc-1.0.10/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.10/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,59 @@ +language: rust +sudo: false + +matrix: + include: + - rust: 1.13.0 + install: + script: cargo build + - rust: stable + env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 + - rust: stable + env: TARGET=i686-unknown-linux-gnu + - os: osx + env: TARGET=x86_64-apple-darwin NO_ADD=1 + - os: osx + env: TARGET=aarch64-apple-ios NO_RUN=--no-run TARGET_SYSROOT=$(xcrun -sdk iphoneos --show-sdk-path) + - rust: beta + env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 + - rust: nightly + env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 + - install: rustup component add rustfmt-preview + script: + - cargo fmt -- --write-mode diff + - (cd cc-test && cargo fmt -- --write-mode diff) + + - rust: nightly + before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH + install: + script: + - cargo doc --no-deps --all-features + after_success: + - travis-cargo --only nightly doc-upload + +install: + - if [ -z "$NO_ADD" ]; then rustup target add $TARGET; fi + +script: + - cargo build --verbose + - cargo test --verbose $NO_RUN + - cargo test --verbose --features parallel $NO_RUN + - cargo test --manifest-path cc-test/Cargo.toml --target $TARGET $NO_RUN + - cargo test --manifest-path cc-test/Cargo.toml --target $TARGET --features parallel $NO_RUN + - cargo test --manifest-path cc-test/Cargo.toml --target $TARGET --release $NO_RUN + - cargo doc + - cargo clean && cargo build + - rustdoc --test README.md -L target/debug -L target/debug/deps + +env: + global: + secure: "CBtqrudgE0PS8x3kTr44jKbC2D4nfnmdYVecooNm0qnER4B4TSvZpZSQoCgKK6k4BYQuOSyFTOwYx6M79w39ZMOgyCP9ytB+tyMWL0/+ZuUQL04yVg4M5vd3oJMkOaXbvG56ncgPyFrseY+FPDg+mXAzvJk/nily37YXjkQj2D0=" + +notifications: + email: + on_success: never +addons: + apt: + packages: + - g++-multilib diff -Nru cargo-0.25.0/vendor/cc-1.0.4/appveyor.yml cargo-0.26.0/vendor/cc-1.0.4/appveyor.yml --- cargo-0.25.0/vendor/cc-1.0.4/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ -environment: - - # At the time this was added AppVeyor was having troubles with checking - # revocation of SSL certificates of sites like static.rust-lang.org and what - # we think is crates.io. The libcurl HTTP client by default checks for - # revocation on Windows and according to a mailing list [1] this can be - # disabled. - # - # The `CARGO_HTTP_CHECK_REVOKE` env var here tells cargo to disable SSL - # revocation checking on Windows in libcurl. Note, though, that rustup, which - # we're using to download Rust here, also uses libcurl as the default backend. - # Unlike Cargo, however, rustup doesn't have a mechanism to disable revocation - # checking. To get rustup working we set `RUSTUP_USE_HYPER` which forces it to - # use the Hyper instead of libcurl backend. Both Hyper and libcurl use - # schannel on Windows but it appears that Hyper configures it slightly - # differently such that revocation checking isn't turned on by default. - # - # [1]: https://curl.haxx.se/mail/lib-2016-03/0202.html - RUSTUP_USE_HYPER: 1 - CARGO_HTTP_CHECK_REVOKE: false - - matrix: - - TARGET: x86_64-pc-windows-msvc - ARCH: amd64 - VS: C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat - - TARGET: x86_64-pc-windows-msvc - ARCH: amd64 - VS: C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat - - TARGET: i686-pc-windows-msvc - ARCH: x86 - VS: C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat - - TARGET: i686-pc-windows-msvc - ARCH: x86 - VS: C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat - - TARGET: x86_64-pc-windows-gnu - MSYS_BITS: 64 - - TARGET: i686-pc-windows-gnu - MSYS_BITS: 32 -install: - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" - - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - - if defined VS call "%VS%" %ARCH% - - set PATH=%PATH%;C:\Program Files (x86)\Rust\bin - - if defined MSYS_BITS set PATH=%PATH%;C:\msys64\mingw%MSYS_BITS%\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test --target %TARGET% - - cargo test --features parallel --target %TARGET% - - cargo test --manifest-path cc-test/Cargo.toml --target %TARGET% - - cargo test --manifest-path cc-test/Cargo.toml --features parallel --target %TARGET% - - cargo test --manifest-path cc-test/Cargo.toml --release --target %TARGET% diff -Nru cargo-0.25.0/vendor/cc-1.0.4/.cargo-checksum.json cargo-0.26.0/vendor/cc-1.0.4/.cargo-checksum.json --- cargo-0.25.0/vendor/cc-1.0.4/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"deaf9ec656256bb25b404c51ef50097207b9cbb29c933d31f92cae5a8a0ffee0"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/cc-1.0.4/Cargo.toml cargo-0.26.0/vendor/cc-1.0.4/Cargo.toml --- cargo-0.25.0/vendor/cc-1.0.4/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "cc" -version = "1.0.4" -authors = ["Alex Crichton "] -description = "A build-time dependency for Cargo build scripts to assist in invoking the native\nC compiler to compile native C code into a static archive to be linked into Rust\ncode.\n" -homepage = "https://github.com/alexcrichton/cc-rs" -documentation = "https://docs.rs/cc" -readme = "README.md" -keywords = ["build-dependencies"] -categories = ["development-tools"] -license = "MIT/Apache-2.0" -repository = "https://github.com/alexcrichton/cc-rs" -[dependencies.rayon] -version = "0.9" -optional = true -[dev-dependencies.tempdir] -version = "0.3" - -[features] -parallel = ["rayon"] -[badges.appveyor] -repository = "alexcrichton/cc-rs" - -[badges.travis-ci] -repository = "alexcrichton/cc-rs" diff -Nru cargo-0.25.0/vendor/cc-1.0.4/LICENSE-APACHE cargo-0.26.0/vendor/cc-1.0.4/LICENSE-APACHE --- cargo-0.25.0/vendor/cc-1.0.4/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/cc-1.0.4/LICENSE-MIT cargo-0.26.0/vendor/cc-1.0.4/LICENSE-MIT --- cargo-0.25.0/vendor/cc-1.0.4/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 Alex Crichton - -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. diff -Nru cargo-0.25.0/vendor/cc-1.0.4/README.md cargo-0.26.0/vendor/cc-1.0.4/README.md --- cargo-0.25.0/vendor/cc-1.0.4/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,202 +0,0 @@ -# cc-rs - -A library to compile C/C++/assembly into a Rust library/application. - -[![Build Status](https://travis-ci.org/alexcrichton/cc-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/cc-rs) -[![Build status](https://ci.appveyor.com/api/projects/status/onu270iw98h81nwv?svg=true)](https://ci.appveyor.com/project/alexcrichton/cc-rs) - -[Documentation](https://docs.rs/cc) - -A simple library meant to be used as a build dependency with Cargo packages in -order to build a set of C/C++ files into a static archive. This crate calls out -to the most relevant compiler for a platform, for example using `cl` on MSVC. - -> **Note**: this crate was recently renamed from the `gcc` crate, so if you're -> looking for the `gcc` crate you're in the right spot! - -## Using cc-rs - -First, you'll want to both add a build script for your crate (`build.rs`) and -also add this crate to your `Cargo.toml` via: - -```toml -[build-dependencies] -cc = "1.0" -``` - -Next up, you'll want to write a build script like so: - -```rust,no_run -// build.rs - -extern crate cc; - -fn main() { - cc::Build::new() - .file("foo.c") - .file("bar.c") - .compile("foo"); -} -``` - -And that's it! Running `cargo build` should take care of the rest and your Rust -application will now have the C files `foo.c` and `bar.c` compiled into a file -named libfoo.a. You can call the functions in Rust by declaring functions in -your Rust code like so: - -``` -extern { - fn foo_function(); - fn bar_function(); -} - -pub fn call() { - unsafe { - foo_function(); - bar_function(); - } -} - -fn main() { - // ... -} -``` - -## External configuration via environment variables - -To control the programs and flags used for building, the builder can set a -number of different environment variables. - -* `CFLAGS` - a series of space separated flags passed to compilers. Note that - individual flags cannot currently contain spaces, so doing - something like: "-L=foo\ bar" is not possible. -* `CC` - the actual C compiler used. Note that this is used as an exact - executable name, so (for example) no extra flags can be passed inside - this variable, and the builder must ensure that there aren't any - trailing spaces. This compiler must understand the `-c` flag. For - certain `TARGET`s, it also is assumed to know about other flags (most - common is `-fPIC`). -* `AR` - the `ar` (archiver) executable to use to build the static library. - -Each of these variables can also be supplied with certain prefixes and suffixes, -in the following prioritized order: - -1. `_` - for example, `CC_x86_64-unknown-linux-gnu` -2. `_` - for example, `CC_x86_64_unknown_linux_gnu` -3. `_` - for example, `HOST_CC` or `TARGET_CFLAGS` -4. `` - a plain `CC`, `AR` as above. - -If none of these variables exist, cc-rs uses built-in defaults - -In addition to the the above optional environment variables, `cc-rs` has some -functions with hard requirements on some variables supplied by [cargo's -build-script driver][cargo] that it has the `TARGET`, `OUT_DIR`, `OPT_LEVEL`, -and `HOST` variables. - -[cargo]: http://doc.crates.io/build-script.html#inputs-to-the-build-script - -## Optional features - -### Parallel - -Currently cc-rs supports parallel compilation (think `make -jN`) but this -feature is turned off by default. To enable cc-rs to compile C/C++ in parallel, -you can change your dependency to: - -```toml -[build-dependencies] -cc = { version = "1.0", features = ["parallel"] } -``` - -By default cc-rs will limit parallelism to `$NUM_JOBS`, or if not present it -will limit it to the number of cpus on the machine. If you are using cargo, -use `-jN` option of `build`, `test` and `run` commands as `$NUM_JOBS` -is supplied by cargo. - -## Compile-time Requirements - -To work properly this crate needs access to a C compiler when the build script -is being run. This crate does not ship a C compiler with it. The compiler -required varies per platform, but there are three broad categories: - -* Unix platforms require `cc` to be the C compiler. This can be found by - installing cc/clang on Linux distributions and Xcode on OSX, for example. -* Windows platforms targeting MSVC (e.g. your target triple ends in `-msvc`) - require `cl.exe` to be available and in `PATH`. This is typically found in - standard Visual Studio installations and the `PATH` can be set up by running - the appropriate developer tools shell. -* Windows platforms targeting MinGW (e.g. your target triple ends in `-gnu`) - require `cc` to be available in `PATH`. We recommend the - [MinGW-w64](http://mingw-w64.org) distribution, which is using the - [Win-builds](http://win-builds.org) installation system. - You may also acquire it via - [MSYS2](http://msys2.github.io), as explained [here][msys2-help]. Make sure - to install the appropriate architecture corresponding to your installation of - rustc. GCC from older [MinGW](http://www.mingw.org) project is compatible - only with 32-bit rust compiler. - -[msys2-help]: http://github.com/rust-lang/rust#building-on-windows - -## C++ support - -`cc-rs` supports C++ libraries compilation by using the `cpp` method on -`Build`: - -```rust,no_run -extern crate cc; - -fn main() { - cc::Build::new() - .cpp(true) // Switch to C++ library compilation. - .file("foo.cpp") - .compile("libfoo.a"); -} -``` - -When using C++ library compilation switch, the `CXX` and `CXXFLAGS` env -variables are used instead of `CC` and `CFLAGS` and the C++ standard library is -linked to the crate target. - -## CUDA C++ support - -`cc-rs` also supports compiling CUDA C++ libraries by using the `cuda` method -on `Build` (currently for GNU/Clang toolchains only): - -```rust,no_run -extern crate cc; - -fn main() { - cc::Build::new() - // Switch to CUDA C++ library compilation using NVCC. - .cuda(true) - // Generate code for Maxwell (GTX 970, 980, 980 Ti, Titan X). - .flag("-gencode").flag("arch=compute_52,code=sm_52") - // Generate code for Maxwell (Jetson TX1). - .flag("-gencode").flag("arch=compute_53,code=sm_53") - // Generate code for Pascal (GTX 1070, 1080, 1080 Ti, Titan Xp). - .flag("-gencode").flag("arch=compute_61,code=sm_61") - // Generate code for Pascal (Tesla P100). - .flag("-gencode").flag("arch=compute_60,code=sm_60") - // Generate code for Pascal (Jetson TX2). - .flag("-gencode").flag("arch=compute_62,code=sm_62") - .file("bar.cu") - .compile("libbar.a"); -} -``` - -## License - -This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/cc-1.0.4/src/bin/gcc-shim.rs cargo-0.26.0/vendor/cc-1.0.4/src/bin/gcc-shim.rs --- cargo-0.25.0/vendor/cc-1.0.4/src/bin/gcc-shim.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/src/bin/gcc-shim.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -#![cfg_attr(test, allow(dead_code))] - -use std::env; -use std::fs::File; -use std::io::prelude::*; -use std::path::PathBuf; - -fn main() { - let out_dir = PathBuf::from(env::var_os("GCCTEST_OUT_DIR").unwrap()); - for i in 0.. { - let candidate = out_dir.join(format!("out{}", i)); - if candidate.exists() { - continue; - } - let mut f = File::create(candidate).unwrap(); - for arg in env::args().skip(1) { - writeln!(f, "{}", arg).unwrap(); - } - - File::create(out_dir.join("libfoo.a")).unwrap(); - break; - } -} diff -Nru cargo-0.25.0/vendor/cc-1.0.4/src/com.rs cargo-0.26.0/vendor/cc-1.0.4/src/com.rs --- cargo-0.25.0/vendor/cc-1.0.4/src/com.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/src/com.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,125 +0,0 @@ -// Copyright © 2017 winapi-rs developers -// Licensed under the Apache License, Version 2.0 -// or the MIT license -// , at your option. -// All files in the project carrying such notice may not be copied, modified, or distributed -// except according to those terms. - -#![allow(unused)] - -use std::ffi::{OsStr, OsString}; -use std::mem::forget; -use std::ops::Deref; -use std::os::windows::ffi::{OsStrExt, OsStringExt}; -use std::ptr::null_mut; -use std::slice::from_raw_parts; -use winapi::Interface; -use winapi::BSTR; -use winapi::CoInitializeEx; -use winapi::COINIT_MULTITHREADED; -use winapi::{SysFreeString, SysStringLen}; -use winapi::IUnknown; -use winapi::{S_OK, S_FALSE, HRESULT}; - -pub fn initialize() -> Result<(), HRESULT> { - let err = unsafe { CoInitializeEx(null_mut(), COINIT_MULTITHREADED) }; - if err != S_OK && err != S_FALSE { - // S_FALSE just means COM is already initialized - return Err(err); - } - Ok(()) -} - -pub struct ComPtr(*mut T) where T: Interface; -impl ComPtr where T: Interface { - /// Creates a `ComPtr` to wrap a raw pointer. - /// It takes ownership over the pointer which means it does __not__ call `AddRef`. - /// `T` __must__ be a COM interface that inherits from `IUnknown`. - pub unsafe fn from_raw(ptr: *mut T) -> ComPtr { - assert!(!ptr.is_null()); - ComPtr(ptr) - } - /// Casts up the inheritance chain - pub fn up(self) -> ComPtr where T: Deref, U: Interface { - ComPtr(self.into_raw() as *mut U) - } - /// Extracts the raw pointer. - /// You are now responsible for releasing it yourself. - pub fn into_raw(self) -> *mut T { - let p = self.0; - forget(self); - p - } - /// For internal use only. - fn as_unknown(&self) -> &IUnknown { - unsafe { &*(self.0 as *mut IUnknown) } - } - /// Performs QueryInterface fun. - pub fn cast(&self) -> Result, i32> where U: Interface { - let mut obj = null_mut(); - let err = unsafe { self.as_unknown().QueryInterface(&U::uuidof(), &mut obj) }; - if err < 0 { return Err(err); } - Ok(unsafe { ComPtr::from_raw(obj as *mut U) }) - } -} -impl Deref for ComPtr where T: Interface { - type Target = T; - fn deref(&self) -> &T { - unsafe { &*self.0 } - } -} -impl Clone for ComPtr where T: Interface { - fn clone(&self) -> Self { - unsafe { - self.as_unknown().AddRef(); - ComPtr::from_raw(self.0) - } - } -} -impl Drop for ComPtr where T: Interface { - fn drop(&mut self) { - unsafe { self.as_unknown().Release(); } - } -} -pub struct BStr(BSTR); -impl BStr { - pub unsafe fn from_raw(s: BSTR) -> BStr { - BStr(s) - } - pub fn to_osstring(&self) -> OsString { - let len = unsafe { SysStringLen(self.0) }; - let slice = unsafe { from_raw_parts(self.0, len as usize) }; - OsStringExt::from_wide(slice) - } -} -impl Drop for BStr { - fn drop(&mut self) { - unsafe { SysFreeString(self.0) }; - } -} - -pub trait ToWide { - fn to_wide(&self) -> Vec; - fn to_wide_null(&self) -> Vec; -} -impl ToWide for T where T: AsRef { - fn to_wide(&self) -> Vec { - self.as_ref().encode_wide().collect() - } - fn to_wide_null(&self) -> Vec { - self.as_ref().encode_wide().chain(Some(0)).collect() - } -} -pub trait FromWide where Self: Sized { - fn from_wide(wide: &[u16]) -> Self; - fn from_wide_null(wide: &[u16]) -> Self { - let len = wide.iter().take_while(|&&c| c != 0).count(); - Self::from_wide(&wide[..len]) - } -} -impl FromWide for OsString { - fn from_wide(wide: &[u16]) -> OsString { - OsStringExt::from_wide(wide) - } -} - diff -Nru cargo-0.25.0/vendor/cc-1.0.4/src/lib.rs cargo-0.26.0/vendor/cc-1.0.4/src/lib.rs --- cargo-0.25.0/vendor/cc-1.0.4/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1998 +0,0 @@ -//! A library for build scripts to compile custom C code -//! -//! This library is intended to be used as a `build-dependencies` entry in -//! `Cargo.toml`: -//! -//! ```toml -//! [build-dependencies] -//! cc = "1.0" -//! ``` -//! -//! The purpose of this crate is to provide the utility functions necessary to -//! compile C code into a static archive which is then linked into a Rust crate. -//! Configuration is available through the `Build` struct. -//! -//! This crate will automatically detect situations such as cross compilation or -//! other environment variables set by Cargo and will build code appropriately. -//! -//! The crate is not limited to C code, it can accept any source code that can -//! be passed to a C or C++ compiler. As such, assembly files with extensions -//! `.s` (gcc/clang) and `.asm` (MSVC) can also be compiled. -//! -//! [`Build`]: struct.Build.html -//! -//! # Parallelism -//! -//! To parallelize computation, enable the `parallel` feature for the crate. -//! -//! ```toml -//! [build-dependencies] -//! cc = { version = "1.0", features = ["parallel"] } -//! ``` -//! To specify the max number of concurrent compilation jobs, set the `NUM_JOBS` -//! environment variable to the desired amount. -//! -//! Cargo will also set this environment variable when executed with the `-jN` flag. -//! -//! If `NUM_JOBS` is not set, the `RAYON_NUM_THREADS` environment variable can -//! also specify the build paralellism. -//! -//! # Examples -//! -//! Use the `Build` struct to compile `src/foo.c`: -//! -//! ```no_run -//! extern crate cc; -//! -//! fn main() { -//! cc::Build::new() -//! .file("src/foo.c") -//! .define("FOO", Some("bar")) -//! .include("src") -//! .compile("foo"); -//! } -//! ``` - -#![doc(html_root_url = "https://docs.rs/cc/1.0")] -#![cfg_attr(test, deny(warnings))] -#![deny(missing_docs)] - -#[cfg(feature = "parallel")] -extern crate rayon; - -use std::env; -use std::ffi::{OsString, OsStr}; -use std::fs; -use std::path::{PathBuf, Path}; -use std::process::{Command, Stdio, Child}; -use std::io::{self, BufReader, BufRead, Read, Write}; -use std::thread::{self, JoinHandle}; - -#[cfg(feature = "parallel")] -use std::sync::Mutex; - -// These modules are all glue to support reading the MSVC version from -// the registry and from COM interfaces -#[cfg(windows)] -mod registry; -#[cfg(windows)] -#[macro_use] -mod winapi; -#[cfg(windows)] -mod com; -#[cfg(windows)] -mod setup_config; - -pub mod windows_registry; - -/// A builder for compilation of a native static library. -/// -/// A `Build` is the main type of the `cc` crate and is used to control all the -/// various configuration options and such of a compile. You'll find more -/// documentation on each method itself. -#[derive(Clone, Debug)] -pub struct Build { - include_directories: Vec, - definitions: Vec<(String, Option)>, - objects: Vec, - flags: Vec, - flags_supported: Vec, - files: Vec, - cpp: bool, - cpp_link_stdlib: Option>, - cpp_set_stdlib: Option, - cuda: bool, - target: Option, - host: Option, - out_dir: Option, - opt_level: Option, - debug: Option, - env: Vec<(OsString, OsString)>, - compiler: Option, - archiver: Option, - cargo_metadata: bool, - pic: Option, - static_crt: Option, - shared_flag: Option, - static_flag: Option, - warnings_into_errors: bool, - warnings: bool, -} - -/// Represents the types of errors that may occur while using cc-rs. -#[derive(Clone, Debug)] -enum ErrorKind { - /// Error occurred while performing I/O. - IOError, - /// Invalid architecture supplied. - ArchitectureInvalid, - /// Environment variable not found, with the var in question as extra info. - EnvVarNotFound, - /// Error occurred while using external tools (ie: invocation of compiler). - ToolExecError, - /// Error occurred due to missing external tools. - ToolNotFound, -} - -/// Represents an internal error that occurred, with an explanation. -#[derive(Clone, Debug)] -pub struct Error { - /// Describes the kind of error that occurred. - kind: ErrorKind, - /// More explanation of error that occurred. - message: String, -} - -impl Error { - fn new(kind: ErrorKind, message: &str) -> Error { - Error { - kind: kind, - message: message.to_owned(), - } - } -} - -impl From for Error { - fn from(e: io::Error) -> Error { - Error::new(ErrorKind::IOError, &format!("{}", e)) - } -} - -/// Configuration used to represent an invocation of a C compiler. -/// -/// This can be used to figure out what compiler is in use, what the arguments -/// to it are, and what the environment variables look like for the compiler. -/// This can be used to further configure other build systems (e.g. forward -/// along CC and/or CFLAGS) or the `to_command` method can be used to run the -/// compiler itself. -#[derive(Clone, Debug)] -pub struct Tool { - path: PathBuf, - cc_wrapper_path: Option, - cc_wrapper_args: Vec, - args: Vec, - env: Vec<(OsString, OsString)>, - family: ToolFamily, - cuda: bool, -} - -/// Represents the family of tools this tool belongs to. -/// -/// Each family of tools differs in how and what arguments they accept. -/// -/// Detection of a family is done on best-effort basis and may not accurately reflect the tool. -#[derive(Copy, Clone, Debug, PartialEq)] -enum ToolFamily { - /// Tool is GNU Compiler Collection-like. - Gnu, - /// Tool is Clang-like. It differs from the GCC in a sense that it accepts superset of flags - /// and its cross-compilation approach is different. - Clang, - /// Tool is the MSVC cl.exe. - Msvc, -} - -impl ToolFamily { - /// What the flag to request debug info for this family of tools look like - fn debug_flag(&self) -> &'static str { - match *self { - ToolFamily::Msvc => "/Z7", - ToolFamily::Gnu | ToolFamily::Clang => "-g", - } - } - - /// What the flag to include directories into header search path looks like - fn include_flag(&self) -> &'static str { - match *self { - ToolFamily::Msvc => "/I", - ToolFamily::Gnu | ToolFamily::Clang => "-I", - } - } - - /// What the flag to request macro-expanded source output looks like - fn expand_flag(&self) -> &'static str { - match *self { - ToolFamily::Msvc => "/E", - ToolFamily::Gnu | ToolFamily::Clang => "-E", - } - } - - /// What the flags to enable all warnings - fn warnings_flags(&self) -> &'static [&'static str] { - static MSVC_FLAGS: &'static [&'static str] = &["/W4"]; - static GNU_CLANG_FLAGS: &'static [&'static str] = &["-Wall", "-Wextra"]; - - match *self { - ToolFamily::Msvc => &MSVC_FLAGS, - ToolFamily::Gnu | ToolFamily::Clang => &GNU_CLANG_FLAGS, - } - } - - /// What the flag to turn warning into errors - fn warnings_to_errors_flag(&self) -> &'static str { - match *self { - ToolFamily::Msvc => "/WX", - ToolFamily::Gnu | ToolFamily::Clang => "-Werror", - } - } - - /// NVCC-specific. Device code debug info flag. This is separate from the - /// debug info flag passed to the C++ compiler. - fn nvcc_debug_flag(&self) -> &'static str { - match *self { - ToolFamily::Msvc => unimplemented!(), - ToolFamily::Gnu | - ToolFamily::Clang => "-G", - } - } - - /// NVCC-specific. Redirect the following flag to the underlying C++ - /// compiler. - fn nvcc_redirect_flag(&self) -> &'static str { - match *self { - ToolFamily::Msvc => unimplemented!(), - ToolFamily::Gnu | - ToolFamily::Clang => "-Xcompiler", - } - } -} - -/// Represents an object. -/// -/// This is a source file -> object file pair. -#[derive(Clone, Debug)] -struct Object { - src: PathBuf, - dst: PathBuf, -} - -impl Object { - /// Create a new source file -> object file pair. - fn new(src: PathBuf, dst: PathBuf) -> Object { - Object { - src: src, - dst: dst, - } - } -} - -impl Build { - /// Construct a new instance of a blank set of configuration. - /// - /// This builder is finished with the [`compile`] function. - /// - /// [`compile`]: struct.Build.html#method.compile - pub fn new() -> Build { - Build { - include_directories: Vec::new(), - definitions: Vec::new(), - objects: Vec::new(), - flags: Vec::new(), - flags_supported: Vec::new(), - files: Vec::new(), - shared_flag: None, - static_flag: None, - cpp: false, - cpp_link_stdlib: None, - cpp_set_stdlib: None, - cuda: false, - target: None, - host: None, - out_dir: None, - opt_level: None, - debug: None, - env: Vec::new(), - compiler: None, - archiver: None, - cargo_metadata: true, - pic: None, - static_crt: None, - warnings: true, - warnings_into_errors: false, - } - } - - /// Add a directory to the `-I` or include path for headers - /// - /// # Example - /// - /// ```no_run - /// use std::path::Path; - /// - /// let library_path = Path::new("/path/to/library"); - /// - /// cc::Build::new() - /// .file("src/foo.c") - /// .include(library_path) - /// .include("src") - /// .compile("foo"); - /// ``` - pub fn include>(&mut self, dir: P) -> &mut Build { - self.include_directories.push(dir.as_ref().to_path_buf()); - self - } - - /// Specify a `-D` variable with an optional value. - /// - /// # Example - /// - /// ```no_run - /// cc::Build::new() - /// .file("src/foo.c") - /// .define("FOO", "BAR") - /// .define("BAZ", None) - /// .compile("foo"); - /// ``` - pub fn define<'a, V: Into>>(&mut self, var: &str, val: V) -> &mut Build { - self.definitions.push(( - var.to_string(), - val.into().map(|s| s.to_string()), - )); - self - } - - /// Add an arbitrary object file to link in - pub fn object>(&mut self, obj: P) -> &mut Build { - self.objects.push(obj.as_ref().to_path_buf()); - self - } - - /// Add an arbitrary flag to the invocation of the compiler - /// - /// # Example - /// - /// ```no_run - /// cc::Build::new() - /// .file("src/foo.c") - /// .flag("-ffunction-sections") - /// .compile("foo"); - /// ``` - pub fn flag(&mut self, flag: &str) -> &mut Build { - self.flags.push(flag.to_string()); - self - } - - fn ensure_check_file(&self) -> Result { - let out_dir = self.get_out_dir()?; - let src = if self.cuda { - assert!(self.cpp); - out_dir.join("flag_check.cu") - } else if self.cpp { - out_dir.join("flag_check.cpp") - } else { - out_dir.join("flag_check.c") - }; - - if !src.exists() { - let mut f = fs::File::create(&src)?; - write!(f, "int main(void) {{ return 0; }}")?; - } - - Ok(src) - } - - /// Run the compiler to test if it accepts the given flag. - /// - /// For a convenience method for setting flags conditionally, - /// see `flag_if_supported()`. - /// - /// It may return error if it's unable to run the compilier with a test file - /// (e.g. the compiler is missing or a write to the `out_dir` failed). - pub fn is_flag_supported(&self, flag: &str) -> Result { - let out_dir = self.get_out_dir()?; - let src = self.ensure_check_file()?; - let obj = out_dir.join("flag_check"); - let target = self.get_target()?; - let mut cfg = Build::new(); - cfg.flag(flag) - .target(&target) - .opt_level(0) - .host(&target) - .debug(false) - .cpp(self.cpp) - .cuda(self.cuda); - let compiler = cfg.try_get_compiler()?; - let mut cmd = compiler.to_command(); - command_add_output_file(&mut cmd, &obj, target.contains("msvc"), false); - - // We need to explicitly tell msvc not to link and create an exe - // in the root directory of the crate - if target.contains("msvc") { - cmd.arg("/c"); - } - - cmd.arg(&src); - - let output = cmd.output()?; - Ok(output.stderr.is_empty()) - } - - /// Add an arbitrary flag to the invocation of the compiler if it supports it - /// - /// # Example - /// - /// ```no_run - /// cc::Build::new() - /// .file("src/foo.c") - /// .flag_if_supported("-Wlogical-op") // only supported by GCC - /// .flag_if_supported("-Wunreachable-code") // only supported by clang - /// .compile("foo"); - /// ``` - pub fn flag_if_supported(&mut self, flag: &str) -> &mut Build { - self.flags_supported.push(flag.to_string()); - self - } - - /// Set the `-shared` flag. - /// - /// When enabled, the compiler will produce a shared object which can - /// then be linked with other objects to form an executable. - /// - /// # Example - /// - /// ```no_run - /// cc::Build::new() - /// .file("src/foo.c") - /// .shared_flag(true) - /// .compile("libfoo.so"); - /// ``` - - pub fn shared_flag(&mut self, shared_flag: bool) -> &mut Build { - self.shared_flag = Some(shared_flag); - self - } - - /// Set the `-static` flag. - /// - /// When enabled on systems that support dynamic linking, this prevents - /// linking with the shared libraries. - /// - /// # Example - /// - /// ```no_run - /// cc::Build::new() - /// .file("src/foo.c") - /// .shared_flag(true) - /// .static_flag(true) - /// .compile("foo"); - /// ``` - pub fn static_flag(&mut self, static_flag: bool) -> &mut Build { - self.static_flag = Some(static_flag); - self - } - - /// Add a file which will be compiled - pub fn file>(&mut self, p: P) -> &mut Build { - self.files.push(p.as_ref().to_path_buf()); - self - } - - /// Add files which will be compiled - pub fn files

(&mut self, p: P) -> &mut Build - where - P: IntoIterator, - P::Item: AsRef, - { - for file in p.into_iter() { - self.file(file); - } - self - } - - /// Set C++ support. - /// - /// The other `cpp_*` options will only become active if this is set to - /// `true`. - pub fn cpp(&mut self, cpp: bool) -> &mut Build { - self.cpp = cpp; - self - } - - /// Set CUDA C++ support. - /// - /// Enabling CUDA will pass the detected C/C++ toolchain as an argument to - /// the CUDA compiler, NVCC. NVCC itself accepts some limited GNU-like args; - /// any other arguments for the C/C++ toolchain will be redirected using - /// "-Xcompiler" flags. - /// - /// If enabled, this also implicitly enables C++ support. - pub fn cuda(&mut self, cuda: bool) -> &mut Build { - self.cuda = cuda; - if cuda { - self.cpp = true; - } - self - } - - /// Set warnings into errors flag. - /// - /// Disabled by default. - /// - /// Warning: turning warnings into errors only make sense - /// if you are a developer of the crate using cc-rs. - /// Some warnings only appear on some architecture or - /// specific version of the compiler. Any user of this crate, - /// or any other crate depending on it, could fail during - /// compile time. - /// - /// # Example - /// - /// ```no_run - /// cc::Build::new() - /// .file("src/foo.c") - /// .warnings_into_errors(true) - /// .compile("libfoo.a"); - /// ``` - pub fn warnings_into_errors(&mut self, warnings_into_errors: bool) -> &mut Build { - self.warnings_into_errors = warnings_into_errors; - self - } - - /// Set warnings flags. - /// - /// Adds some flags: - /// - "/Wall" for MSVC. - /// - "-Wall", "-Wextra" for GNU and Clang. - /// - /// Enabled by default. - /// - /// # Example - /// - /// ```no_run - /// cc::Build::new() - /// .file("src/foo.c") - /// .warnings(false) - /// .compile("libfoo.a"); - /// ``` - pub fn warnings(&mut self, warnings: bool) -> &mut Build { - self.warnings = warnings; - self - } - - /// Set the standard library to link against when compiling with C++ - /// support. - /// - /// The default value of this property depends on the current target: On - /// OS X `Some("c++")` is used, when compiling for a Visual Studio based - /// target `None` is used and for other targets `Some("stdc++")` is used. - /// - /// A value of `None` indicates that no automatic linking should happen, - /// otherwise cargo will link against the specified library. - /// - /// The given library name must not contain the `lib` prefix. - /// - /// Common values: - /// - `stdc++` for GNU - /// - `c++` for Clang - /// - /// # Example - /// - /// ```no_run - /// cc::Build::new() - /// .file("src/foo.c") - /// .shared_flag(true) - /// .cpp_link_stdlib("stdc++") - /// .compile("libfoo.so"); - /// ``` - pub fn cpp_link_stdlib<'a, V: Into>>( - &mut self, - cpp_link_stdlib: V, - ) -> &mut Build { - self.cpp_link_stdlib = Some(cpp_link_stdlib.into().map(|s| s.into())); - self - } - - /// Force the C++ compiler to use the specified standard library. - /// - /// Setting this option will automatically set `cpp_link_stdlib` to the same - /// value. - /// - /// The default value of this option is always `None`. - /// - /// This option has no effect when compiling for a Visual Studio based - /// target. - /// - /// This option sets the `-stdlib` flag, which is only supported by some - /// compilers (clang, icc) but not by others (gcc). The library will not - /// detect which compiler is used, as such it is the responsibility of the - /// caller to ensure that this option is only used in conjuction with a - /// compiler which supports the `-stdlib` flag. - /// - /// A value of `None` indicates that no specific C++ standard library should - /// be used, otherwise `-stdlib` is added to the compile invocation. - /// - /// The given library name must not contain the `lib` prefix. - /// - /// Common values: - /// - `stdc++` for GNU - /// - `c++` for Clang - /// - /// # Example - /// - /// ```no_run - /// cc::Build::new() - /// .file("src/foo.c") - /// .cpp_set_stdlib("c++") - /// .compile("libfoo.a"); - /// ``` - pub fn cpp_set_stdlib<'a, V: Into>>( - &mut self, - cpp_set_stdlib: V, - ) -> &mut Build { - let cpp_set_stdlib = cpp_set_stdlib.into(); - self.cpp_set_stdlib = cpp_set_stdlib.map(|s| s.into()); - self.cpp_link_stdlib(cpp_set_stdlib); - self - } - - /// Configures the target this configuration will be compiling for. - /// - /// This option is automatically scraped from the `TARGET` environment - /// variable by build scripts, so it's not required to call this function. - /// - /// # Example - /// - /// ```no_run - /// cc::Build::new() - /// .file("src/foo.c") - /// .target("aarch64-linux-android") - /// .compile("foo"); - /// ``` - pub fn target(&mut self, target: &str) -> &mut Build { - self.target = Some(target.to_string()); - self - } - - /// Configures the host assumed by this configuration. - /// - /// This option is automatically scraped from the `HOST` environment - /// variable by build scripts, so it's not required to call this function. - /// - /// # Example - /// - /// ```no_run - /// cc::Build::new() - /// .file("src/foo.c") - /// .host("arm-linux-gnueabihf") - /// .compile("foo"); - /// ``` - pub fn host(&mut self, host: &str) -> &mut Build { - self.host = Some(host.to_string()); - self - } - - /// Configures the optimization level of the generated object files. - /// - /// This option is automatically scraped from the `OPT_LEVEL` environment - /// variable by build scripts, so it's not required to call this function. - pub fn opt_level(&mut self, opt_level: u32) -> &mut Build { - self.opt_level = Some(opt_level.to_string()); - self - } - - /// Configures the optimization level of the generated object files. - /// - /// This option is automatically scraped from the `OPT_LEVEL` environment - /// variable by build scripts, so it's not required to call this function. - pub fn opt_level_str(&mut self, opt_level: &str) -> &mut Build { - self.opt_level = Some(opt_level.to_string()); - self - } - - /// Configures whether the compiler will emit debug information when - /// generating object files. - /// - /// This option is automatically scraped from the `PROFILE` environment - /// variable by build scripts (only enabled when the profile is "debug"), so - /// it's not required to call this function. - pub fn debug(&mut self, debug: bool) -> &mut Build { - self.debug = Some(debug); - self - } - - /// Configures the output directory where all object files and static - /// libraries will be located. - /// - /// This option is automatically scraped from the `OUT_DIR` environment - /// variable by build scripts, so it's not required to call this function. - pub fn out_dir>(&mut self, out_dir: P) -> &mut Build { - self.out_dir = Some(out_dir.as_ref().to_owned()); - self - } - - /// Configures the compiler to be used to produce output. - /// - /// This option is automatically determined from the target platform or a - /// number of environment variables, so it's not required to call this - /// function. - pub fn compiler>(&mut self, compiler: P) -> &mut Build { - self.compiler = Some(compiler.as_ref().to_owned()); - self - } - - /// Configures the tool used to assemble archives. - /// - /// This option is automatically determined from the target platform or a - /// number of environment variables, so it's not required to call this - /// function. - pub fn archiver>(&mut self, archiver: P) -> &mut Build { - self.archiver = Some(archiver.as_ref().to_owned()); - self - } - /// Define whether metadata should be emitted for cargo allowing it to - /// automatically link the binary. Defaults to `true`. - /// - /// The emitted metadata is: - /// - /// - `rustc-link-lib=static=`*compiled lib* - /// - `rustc-link-search=native=`*target folder* - /// - When target is MSVC, the ATL-MFC libs are added via `rustc-link-search=native=` - /// - When C++ is enabled, the C++ stdlib is added via `rustc-link-lib` - /// - pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Build { - self.cargo_metadata = cargo_metadata; - self - } - - /// Configures whether the compiler will emit position independent code. - /// - /// This option defaults to `false` for `windows-gnu` targets and - /// to `true` for all other targets. - pub fn pic(&mut self, pic: bool) -> &mut Build { - self.pic = Some(pic); - self - } - - /// Configures whether the /MT flag or the /MD flag will be passed to msvc build tools. - /// - /// This option defaults to `false`, and affect only msvc targets. - pub fn static_crt(&mut self, static_crt: bool) -> &mut Build { - self.static_crt = Some(static_crt); - self - } - - #[doc(hidden)] - pub fn __set_env(&mut self, a: A, b: B) -> &mut Build - where - A: AsRef, - B: AsRef, - { - self.env.push( - (a.as_ref().to_owned(), b.as_ref().to_owned()), - ); - self - } - - /// Run the compiler, generating the file `output` - /// - /// This will return a result instead of panicing; see compile() for the complete description. - pub fn try_compile(&self, output: &str) -> Result<(), Error> { - let (lib_name, gnu_lib_name) = if output.starts_with("lib") && output.ends_with(".a") { - (&output[3..output.len() - 2], output.to_owned()) - } else { - let mut gnu = String::with_capacity(5 + output.len()); - gnu.push_str("lib"); - gnu.push_str(&output); - gnu.push_str(".a"); - (output, gnu) - }; - let dst = self.get_out_dir()?; - - let mut objects = Vec::new(); - for file in self.files.iter() { - let obj = dst.join(file).with_extension("o"); - let obj = if !obj.starts_with(&dst) { - dst.join(obj.file_name().ok_or_else(|| { - Error::new(ErrorKind::IOError, "Getting object file details failed.") - })?) - } else { - obj - }; - - match obj.parent() { - Some(s) => fs::create_dir_all(s)?, - None => { - return Err(Error::new( - ErrorKind::IOError, - "Getting object file details failed.", - )) - } - }; - - objects.push(Object::new(file.to_path_buf(), obj)); - } - self.compile_objects(&objects)?; - self.assemble(lib_name, &dst.join(gnu_lib_name), &objects)?; - - if self.get_target()?.contains("msvc") { - let compiler = self.get_base_compiler()?; - let atlmfc_lib = compiler - .env() - .iter() - .find(|&&(ref var, _)| var.as_os_str() == OsStr::new("LIB")) - .and_then(|&(_, ref lib_paths)| { - env::split_paths(lib_paths).find(|path| { - let sub = Path::new("atlmfc/lib"); - path.ends_with(sub) || path.parent().map_or(false, |p| p.ends_with(sub)) - }) - }); - - if let Some(atlmfc_lib) = atlmfc_lib { - self.print(&format!( - "cargo:rustc-link-search=native={}", - atlmfc_lib.display() - )); - } - } - - self.print(&format!("cargo:rustc-link-lib=static={}", lib_name)); - self.print(&format!("cargo:rustc-link-search=native={}", dst.display())); - - // Add specific C++ libraries, if enabled. - if self.cpp { - if let Some(stdlib) = self.get_cpp_link_stdlib()? { - self.print(&format!("cargo:rustc-link-lib={}", stdlib)); - } - } - - Ok(()) - } - - /// Run the compiler, generating the file `output` - /// - /// The name `output` should be the name of the library. For backwards compatibility, - /// the `output` may start with `lib` and end with `.a`. The Rust compilier will create - /// the assembly with the lib prefix and .a extension. MSVC will create a file without prefix, - /// ending with `.lib`. - /// - /// # Panics - /// - /// Panics if `output` is not formatted correctly or if one of the underlying - /// compiler commands fails. It can also panic if it fails reading file names - /// or creating directories. - pub fn compile(&self, output: &str) { - if let Err(e) = self.try_compile(output) { - fail(&e.message); - } - } - - #[cfg(feature = "parallel")] - fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> { - use self::rayon::prelude::*; - - let mut cfg = rayon::Configuration::new(); - if let Ok(amt) = env::var("NUM_JOBS") { - if let Ok(amt) = amt.parse() { - cfg = cfg.num_threads(amt); - } - } - drop(rayon::initialize(cfg)); - - let results: Mutex>> = Mutex::new(Vec::new()); - - objs.par_iter().with_max_len(1).for_each( - |obj| { - let res = self.compile_object(obj); - results.lock().unwrap().push(res) - }, - ); - - // Check for any errors and return the first one found. - for result in results.into_inner().unwrap().iter() { - if result.is_err() { - return result.clone(); - } - } - - Ok(()) - } - - #[cfg(not(feature = "parallel"))] - fn compile_objects(&self, objs: &[Object]) -> Result<(), Error> { - for obj in objs { - self.compile_object(obj)?; - } - Ok(()) - } - - fn compile_object(&self, obj: &Object) -> Result<(), Error> { - let is_asm = obj.src.extension().and_then(|s| s.to_str()) == Some("asm"); - let msvc = self.get_target()?.contains("msvc"); - let (mut cmd, name) = if msvc && is_asm { - self.msvc_macro_assembler()? - } else { - let compiler = self.try_get_compiler()?; - let mut cmd = compiler.to_command(); - for &(ref a, ref b) in self.env.iter() { - cmd.env(a, b); - } - ( - cmd, - compiler - .path - .file_name() - .ok_or_else(|| { - Error::new(ErrorKind::IOError, "Failed to get compiler path.") - })? - .to_string_lossy() - .into_owned(), - ) - }; - command_add_output_file(&mut cmd, &obj.dst, msvc, is_asm); - cmd.arg(if msvc { "/c" } else { "-c" }); - cmd.arg(&obj.src); - - run(&mut cmd, &name)?; - Ok(()) - } - - /// This will return a result instead of panicing; see expand() for the complete description. - pub fn try_expand(&self) -> Result, Error> { - let compiler = self.try_get_compiler()?; - let mut cmd = compiler.to_command(); - for &(ref a, ref b) in self.env.iter() { - cmd.env(a, b); - } - cmd.arg(compiler.family.expand_flag()); - - assert!( - self.files.len() <= 1, - "Expand may only be called for a single file" - ); - - for file in self.files.iter() { - cmd.arg(file); - } - - let name = compiler - .path - .file_name() - .ok_or_else(|| { - Error::new(ErrorKind::IOError, "Failed to get compiler path.") - })? - .to_string_lossy() - .into_owned(); - - Ok(run_output(&mut cmd, &name)?) - } - - /// Run the compiler, returning the macro-expanded version of the input files. - /// - /// This is only relevant for C and C++ files. - /// - /// # Panics - /// Panics if more than one file is present in the config, or if compiler - /// path has an invalid file name. - /// - /// # Example - /// ```no_run - /// let out = cc::Build::new().file("src/foo.c").expand(); - /// ``` - pub fn expand(&self) -> Vec { - match self.try_expand() { - Err(e) => fail(&e.message), - Ok(v) => v, - } - } - - /// Get the compiler that's in use for this configuration. - /// - /// This function will return a `Tool` which represents the culmination - /// of this configuration at a snapshot in time. The returned compiler can - /// be inspected (e.g. the path, arguments, environment) to forward along to - /// other tools, or the `to_command` method can be used to invoke the - /// compiler itself. - /// - /// This method will take into account all configuration such as debug - /// information, optimization level, include directories, defines, etc. - /// Additionally, the compiler binary in use follows the standard - /// conventions for this path, e.g. looking at the explicitly set compiler, - /// environment variables (a number of which are inspected here), and then - /// falling back to the default configuration. - /// - /// # Panics - /// - /// Panics if an error occurred while determining the architecture. - pub fn get_compiler(&self) -> Tool { - match self.try_get_compiler() { - Ok(tool) => tool, - Err(e) => fail(&e.message), - } - } - - /// Get the compiler that's in use for this configuration. - /// - /// This will return a result instead of panicing; see get_compiler() for the complete description. - pub fn try_get_compiler(&self) -> Result { - let opt_level = self.get_opt_level()?; - let target = self.get_target()?; - - let mut cmd = self.get_base_compiler()?; - - // Non-target flags - // If the flag is not conditioned on target variable, it belongs here :) - match cmd.family { - ToolFamily::Msvc => { - assert!(!self.cuda, - "CUDA C++ compilation not supported for MSVC, yet... but you are welcome to implement it :)"); - - cmd.args.push("/nologo".into()); - - let crt_flag = match self.static_crt { - Some(true) => "/MT", - Some(false) => "/MD", - None => { - let features = - env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or(String::new()); - if features.contains("crt-static") { - "/MT" - } else { - "/MD" - } - } - }; - cmd.args.push(crt_flag.into()); - - match &opt_level[..] { - "z" | "s" => cmd.args.push("/Os".into()), - "1" => cmd.args.push("/O1".into()), - // -O3 is a valid value for gcc and clang compilers, but not msvc. Cap to /O2. - "2" | "3" => cmd.args.push("/O2".into()), - _ => {} - } - } - ToolFamily::Gnu | ToolFamily::Clang => { - // arm-linux-androideabi-gcc 4.8 shipped with Android NDK does - // not support '-Oz' - if opt_level == "z" && cmd.family != ToolFamily::Clang { - cmd.args.push("-Os".into()); - } else { - cmd.args.push(format!("-O{}", opt_level).into()); - } - - cmd.push_cc_arg("-ffunction-sections".into()); - cmd.push_cc_arg("-fdata-sections".into()); - if self.pic.unwrap_or(!target.contains("windows-gnu")) { - cmd.push_cc_arg("-fPIC".into()); - } - } - } - for arg in self.envflags(if self.cpp { "CXXFLAGS" } else { "CFLAGS" }) { - cmd.args.push(arg.into()); - } - - if self.get_debug() { - if self.cuda { - let nvcc_debug_flag = cmd.family.nvcc_debug_flag().into(); - cmd.args.push(nvcc_debug_flag); - } - let debug_flag = cmd.family.debug_flag().into(); - cmd.push_cc_arg(debug_flag); - } - - // Target flags - match cmd.family { - ToolFamily::Clang => { - cmd.args.push(format!("--target={}", target).into()); - } - ToolFamily::Msvc => { - if target.contains("i586") { - cmd.args.push("/ARCH:IA32".into()); - } - } - ToolFamily::Gnu => { - if target.contains("i686") || target.contains("i586") { - cmd.args.push("-m32".into()); - } else if target == "x86_64-unknown-linux-gnux32" { - cmd.args.push("-mx32".into()); - } else if target.contains("x86_64") || target.contains("powerpc64") { - cmd.args.push("-m64".into()); - } - - if self.static_flag.is_none() && target.contains("musl") { - cmd.args.push("-static".into()); - } - - // armv7 targets get to use armv7 instructions - if target.starts_with("armv7-") && target.contains("-linux-") { - cmd.args.push("-march=armv7-a".into()); - } - - // On android we can guarantee some extra float instructions - // (specified in the android spec online) - if target.starts_with("armv7-linux-androideabi") { - cmd.args.push("-march=armv7-a".into()); - cmd.args.push("-mthumb".into()); - cmd.args.push("-mfpu=vfpv3-d16".into()); - cmd.args.push("-mfloat-abi=softfp".into()); - } - - if target.starts_with("armv4t-unknown-linux-") { - cmd.args.push("-march=armv4t".into()); - cmd.args.push("-marm".into()); - cmd.args.push("-mfloat-abi=soft".into()); - } - - if target.starts_with("armv5te-unknown-linux-") { - cmd.args.push("-march=armv5te".into()); - cmd.args.push("-marm".into()); - cmd.args.push("-mfloat-abi=soft".into()); - } - - // For us arm == armv6 by default - if target.starts_with("arm-unknown-linux-") { - cmd.args.push("-march=armv6".into()); - cmd.args.push("-marm".into()); - } - - // We can guarantee some settings for FRC - if target.starts_with("arm-frc-") { - cmd.args.push("-march=armv7-a".into()); - cmd.args.push("-mcpu=cortex-a9".into()); - cmd.args.push("-mfpu=vfpv3".into()); - cmd.args.push("-mfloat-abi=softfp".into()); - cmd.args.push("-marm".into()); - } - - // Turn codegen down on i586 to avoid some instructions. - if target.starts_with("i586-unknown-linux-") { - cmd.args.push("-march=pentium".into()); - } - - // Set codegen level for i686 correctly - if target.starts_with("i686-unknown-linux-") { - cmd.args.push("-march=i686".into()); - } - - // Looks like `musl-gcc` makes is hard for `-m32` to make its way - // all the way to the linker, so we need to actually instruct the - // linker that we're generating 32-bit executables as well. This'll - // typically only be used for build scripts which transitively use - // these flags that try to compile executables. - if target == "i686-unknown-linux-musl" { - cmd.args.push("-Wl,-melf_i386".into()); - } - - if target.starts_with("thumb") { - cmd.args.push("-mthumb".into()); - - if target.ends_with("eabihf") { - cmd.args.push("-mfloat-abi=hard".into()) - } - } - if target.starts_with("thumbv6m") { - cmd.args.push("-march=armv6s-m".into()); - } - if target.starts_with("thumbv7em") { - cmd.args.push("-march=armv7e-m".into()); - - if target.ends_with("eabihf") { - cmd.args.push("-mfpu=fpv4-sp-d16".into()) - } - } - if target.starts_with("thumbv7m") { - cmd.args.push("-march=armv7-m".into()); - } - } - } - - if target.contains("-ios") { - // FIXME: potential bug. iOS is always compiled with Clang, but Gcc compiler may be - // detected instead. - self.ios_flags(&mut cmd)?; - } - - if self.static_flag.unwrap_or(false) { - cmd.args.push("-static".into()); - } - if self.shared_flag.unwrap_or(false) { - cmd.args.push("-shared".into()); - } - - if self.cpp { - match (self.cpp_set_stdlib.as_ref(), cmd.family) { - (None, _) => {} - (Some(stdlib), ToolFamily::Gnu) | - (Some(stdlib), ToolFamily::Clang) => { - cmd.push_cc_arg(format!("-stdlib=lib{}", stdlib).into()); - } - _ => { - println!( - "cargo:warning=cpp_set_stdlib is specified, but the {:?} compiler \ - does not support this option, ignored", - cmd.family - ); - } - } - } - - for directory in self.include_directories.iter() { - cmd.args.push(cmd.family.include_flag().into()); - cmd.args.push(directory.into()); - } - - if self.warnings { - for flag in cmd.family.warnings_flags().iter() { - cmd.push_cc_arg(flag.into()); - } - } - - for flag in self.flags.iter() { - cmd.args.push(flag.into()); - } - - for flag in self.flags_supported.iter() { - if self.is_flag_supported(flag).unwrap_or(false) { - cmd.push_cc_arg(flag.into()); - } - } - - for &(ref key, ref value) in self.definitions.iter() { - let lead = if let ToolFamily::Msvc = cmd.family { - "/" - } else { - "-" - }; - if let Some(ref value) = *value { - cmd.args.push(format!("{}D{}={}", lead, key, value).into()); - } else { - cmd.args.push(format!("{}D{}", lead, key).into()); - } - } - - if self.warnings_into_errors { - let warnings_to_errors_flag = cmd.family.warnings_to_errors_flag().into(); - cmd.push_cc_arg(warnings_to_errors_flag); - } - - Ok(cmd) - } - - fn msvc_macro_assembler(&self) -> Result<(Command, String), Error> { - let target = self.get_target()?; - let tool = if target.contains("x86_64") { - "ml64.exe" - } else { - "ml.exe" - }; - let mut cmd = windows_registry::find(&target, tool).unwrap_or_else(|| self.cmd(tool)); - for directory in self.include_directories.iter() { - cmd.arg("/I").arg(directory); - } - for &(ref key, ref value) in self.definitions.iter() { - if let Some(ref value) = *value { - cmd.arg(&format!("/D{}={}", key, value)); - } else { - cmd.arg(&format!("/D{}", key)); - } - } - - if target.contains("i686") || target.contains("i586") { - cmd.arg("/safeseh"); - } - for flag in self.flags.iter() { - cmd.arg(flag); - } - - Ok((cmd, tool.to_string())) - } - - fn assemble(&self, lib_name: &str, dst: &Path, objs: &[Object]) -> Result<(), Error> { - // Delete the destination if it exists as the `ar` tool at least on Unix - // appends to it, which we don't want. - let _ = fs::remove_file(&dst); - - let objects: Vec<_> = objs.iter().map(|obj| obj.dst.clone()).collect(); - let target = self.get_target()?; - if target.contains("msvc") { - let mut cmd = match self.archiver { - Some(ref s) => self.cmd(s), - None => { - windows_registry::find(&target, "lib.exe").unwrap_or_else( - || { - self.cmd("lib.exe") - }, - ) - } - }; - let mut out = OsString::from("/OUT:"); - out.push(dst); - run( - cmd.arg(out).arg("/nologo").args(&objects).args(&self.objects), - "lib.exe", - )?; - - // The Rust compiler will look for libfoo.a and foo.lib, but the - // MSVC linker will also be passed foo.lib, so be sure that both - // exist for now. - let lib_dst = dst.with_file_name(format!("{}.lib", lib_name)); - let _ = fs::remove_file(&lib_dst); - match fs::hard_link(&dst, &lib_dst).or_else(|_| { - // if hard-link fails, just copy (ignoring the number of bytes written) - fs::copy(&dst, &lib_dst).map(|_| ()) - }) { - Ok(_) => (), - Err(_) => { - return Err(Error::new( - ErrorKind::IOError, - "Could not copy or create a hard-link to the generated lib file.", - )) - } - }; - } else { - let (mut ar, cmd) = self.get_ar()?; - run( - ar.arg("crs").arg(dst).args(&objects).args(&self.objects), - &cmd, - )?; - } - - Ok(()) - } - - fn ios_flags(&self, cmd: &mut Tool) -> Result<(), Error> { - enum ArchSpec { - Device(&'static str), - Simulator(&'static str), - } - - let target = self.get_target()?; - let arch = target.split('-').nth(0).ok_or_else(|| { - Error::new( - ErrorKind::ArchitectureInvalid, - "Unknown architecture for iOS target.", - ) - })?; - let arch = match arch { - "arm" | "armv7" | "thumbv7" => ArchSpec::Device("armv7"), - "armv7s" | "thumbv7s" => ArchSpec::Device("armv7s"), - "arm64" | "aarch64" => ArchSpec::Device("arm64"), - "i386" | "i686" => ArchSpec::Simulator("-m32"), - "x86_64" => ArchSpec::Simulator("-m64"), - _ => { - return Err(Error::new( - ErrorKind::ArchitectureInvalid, - "Unknown architecture for iOS target.", - )) - } - }; - - let sdk = match arch { - ArchSpec::Device(arch) => { - cmd.args.push("-arch".into()); - cmd.args.push(arch.into()); - cmd.args.push("-miphoneos-version-min=7.0".into()); - "iphoneos" - } - ArchSpec::Simulator(arch) => { - cmd.args.push(arch.into()); - cmd.args.push("-mios-simulator-version-min=7.0".into()); - "iphonesimulator" - } - }; - - self.print(&format!("Detecting iOS SDK path for {}", sdk)); - let sdk_path = self.cmd("xcrun") - .arg("--show-sdk-path") - .arg("--sdk") - .arg(sdk) - .stderr(Stdio::inherit()) - .output()? - .stdout; - - let sdk_path = match String::from_utf8(sdk_path) { - Ok(p) => p, - Err(_) => { - return Err(Error::new( - ErrorKind::IOError, - "Unable to determine iOS SDK path.", - )) - } - }; - - cmd.args.push("-isysroot".into()); - cmd.args.push(sdk_path.trim().into()); - - Ok(()) - } - - fn cmd>(&self, prog: P) -> Command { - let mut cmd = Command::new(prog); - for &(ref a, ref b) in self.env.iter() { - cmd.env(a, b); - } - cmd - } - - fn get_base_compiler(&self) -> Result { - if let Some(ref c) = self.compiler { - return Ok(Tool::new(c.clone())); - } - let host = self.get_host()?; - let target = self.get_target()?; - let (env, msvc, gnu, traditional) = if self.cpp { - ("CXX", "cl.exe", "g++", "c++") - } else { - ("CC", "cl.exe", "gcc", "cc") - }; - - // On Solaris, c++/cc unlikely to exist or be correct. - let default = if host.contains("solaris") { gnu } else { traditional }; - - let tool_opt: Option = - self.env_tool(env) - .map(|(tool, cc, args)| { - let mut t = Tool::new(PathBuf::from(tool)); - if let Some(cc) = cc { - t.cc_wrapper_path = Some(PathBuf::from(cc)); - } - for arg in args { - t.cc_wrapper_args.push(arg.into()); - } - t - }) - .or_else(|| { - if target.contains("emscripten") { - let tool = if self.cpp { "em++" } else { "emcc" }; - // Windows uses bat file so we have to be a bit more specific - if cfg!(windows) { - let mut t = Tool::new(PathBuf::from("cmd")); - t.args.push("/c".into()); - t.args.push(format!("{}.bat", tool).into()); - Some(t) - } else { - Some(Tool::new(PathBuf::from(tool))) - } - } else { - None - } - }) - .or_else(|| windows_registry::find_tool(&target, "cl.exe")); - - let tool = match tool_opt { - Some(t) => t, - None => { - let compiler = if host.contains("windows") && target.contains("windows") { - if target.contains("msvc") { - msvc.to_string() - } else { - format!("{}.exe", gnu) - } - } else if target.contains("android") { - format!("{}-{}", target.replace("armv7", "arm"), gnu) - } else if target.contains("cloudabi") { - format!("{}-{}", target, traditional) - } else if self.get_host()? != target { - // CROSS_COMPILE is of the form: "arm-linux-gnueabi-" - let cc_env = self.getenv("CROSS_COMPILE"); - let cross_compile = cc_env.as_ref().map(|s| s.trim_right_matches('-')); - let prefix = cross_compile.or(match &target[..] { - "aarch64-unknown-linux-gnu" => Some("aarch64-linux-gnu"), - "aarch64-unknown-linux-musl" => Some("aarch64-linux-musl"), - "arm-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"), - "armv4t-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"), - "armv5te-unknown-linux-gnueabi" => Some("arm-linux-gnueabi"), - "arm-frc-linux-gnueabi" => Some("arm-frc-linux-gnueabi"), - "arm-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"), - "arm-unknown-linux-musleabi" => Some("arm-linux-musleabi"), - "arm-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"), - "arm-unknown-netbsd-eabi" => Some("arm--netbsdelf-eabi"), - "armv6-unknown-netbsd-eabihf" => Some("armv6--netbsdelf-eabihf"), - "armv7-unknown-linux-gnueabihf" => Some("arm-linux-gnueabihf"), - "armv7-unknown-linux-musleabihf" => Some("arm-linux-musleabihf"), - "armv7-unknown-netbsd-eabihf" => Some("armv7--netbsdelf-eabihf"), - "i686-pc-windows-gnu" => Some("i686-w64-mingw32"), - "i686-unknown-linux-musl" => Some("musl"), - "i686-unknown-netbsd" => Some("i486--netbsdelf"), - "mips-unknown-linux-gnu" => Some("mips-linux-gnu"), - "mipsel-unknown-linux-gnu" => Some("mipsel-linux-gnu"), - "mips64-unknown-linux-gnuabi64" => Some("mips64-linux-gnuabi64"), - "mips64el-unknown-linux-gnuabi64" => Some("mips64el-linux-gnuabi64"), - "powerpc-unknown-linux-gnu" => Some("powerpc-linux-gnu"), - "powerpc-unknown-netbsd" => Some("powerpc--netbsd"), - "powerpc64-unknown-linux-gnu" => Some("powerpc-linux-gnu"), - "powerpc64le-unknown-linux-gnu" => Some("powerpc64le-linux-gnu"), - "s390x-unknown-linux-gnu" => Some("s390x-linux-gnu"), - "sparc64-unknown-linux-gnu" => Some("sparc64-linux-gnu"), - "sparc64-unknown-netbsd" => Some("sparc64--netbsd"), - "sparcv9-sun-solaris" => Some("sparcv9-sun-solaris"), - "thumbv6m-none-eabi" => Some("arm-none-eabi"), - "thumbv7em-none-eabi" => Some("arm-none-eabi"), - "thumbv7em-none-eabihf" => Some("arm-none-eabi"), - "thumbv7m-none-eabi" => Some("arm-none-eabi"), - "x86_64-pc-windows-gnu" => Some("x86_64-w64-mingw32"), - "x86_64-rumprun-netbsd" => Some("x86_64-rumprun-netbsd"), - "x86_64-unknown-linux-musl" => Some("musl"), - "x86_64-unknown-netbsd" => Some("x86_64--netbsd"), - _ => None, - }); - match prefix { - Some(prefix) => format!("{}-{}", prefix, gnu), - None => default.to_string(), - } - } else { - default.to_string() - }; - Tool::new(PathBuf::from(compiler)) - } - }; - - let tool = if self.cuda { - assert!(tool.args.is_empty(), - "CUDA compilation currently assumes empty pre-existing args"); - let nvcc = match self.get_var("NVCC") { - Err(_) => "nvcc".into(), - Ok(nvcc) => nvcc, - }; - let mut nvcc_tool = Tool::with_features(PathBuf::from(nvcc), self.cuda); - nvcc_tool.args.push(format!("-ccbin={}", tool.path.display()).into()); - nvcc_tool - } else { - tool - }; - - Ok(tool) - } - - fn get_var(&self, var_base: &str) -> Result { - let target = self.get_target()?; - let host = self.get_host()?; - let kind = if host == target { "HOST" } else { "TARGET" }; - let target_u = target.replace("-", "_"); - let res = self.getenv(&format!("{}_{}", var_base, target)) - .or_else(|| self.getenv(&format!("{}_{}", var_base, target_u))) - .or_else(|| self.getenv(&format!("{}_{}", kind, var_base))) - .or_else(|| self.getenv(var_base)); - - match res { - Some(res) => Ok(res), - None => Err(Error::new( - ErrorKind::EnvVarNotFound, - &format!( - "Could not find environment variable {}.", - var_base - ), - )), - } - } - - fn envflags(&self, name: &str) -> Vec { - self.get_var(name) - .unwrap_or(String::new()) - .split(|c: char| c.is_whitespace()) - .filter(|s| !s.is_empty()) - .map(|s| s.to_string()) - .collect() - } - - - /// Returns compiler path, optional modifier name from whitelist, and arguments vec - fn env_tool(&self, name: &str) -> Option<(String, Option, Vec)> { - self.get_var(name).ok().map(|tool| { - let whitelist = ["ccache", "distcc", "sccache"]; - - for t in whitelist.iter() { - if tool.starts_with(t) && tool[t.len()..].starts_with(' ') { - let args = tool.split_whitespace().collect::>(); - - return (args[1].to_string(), Some(t.to_string()), args[2..].iter().map(|s| s.to_string()).collect()); - } - } - (tool, None, Vec::new()) - }) - } - - /// Returns the default C++ standard library for the current target: `libc++` - /// for OS X and `libstdc++` for anything else. - fn get_cpp_link_stdlib(&self) -> Result, Error> { - match self.cpp_link_stdlib.clone() { - Some(s) => Ok(s), - None => { - let target = self.get_target()?; - if target.contains("msvc") { - Ok(None) - } else if target.contains("darwin") { - Ok(Some("c++".to_string())) - } else if target.contains("freebsd") { - Ok(Some("c++".to_string())) - } else if target.contains("openbsd") { - Ok(Some("c++".to_string())) - } else { - Ok(Some("stdc++".to_string())) - } - } - } - } - - fn get_ar(&self) -> Result<(Command, String), Error> { - if let Some(ref p) = self.archiver { - let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("ar"); - return Ok((self.cmd(p), name.to_string())); - } - if let Ok(p) = self.get_var("AR") { - return Ok((self.cmd(&p), p)); - } - let program = if self.get_target()?.contains("android") { - format!("{}-ar", self.get_target()?.replace("armv7", "arm")) - } else if self.get_target()?.contains("emscripten") { - // Windows use bat files so we have to be a bit more specific - if cfg!(windows) { - let mut cmd = self.cmd("cmd"); - cmd.arg("/c").arg("emar.bat"); - return Ok((cmd, "emar.bat".to_string())); - } - - "emar".to_string() - } else { - "ar".to_string() - }; - Ok((self.cmd(&program), program)) - } - - fn get_target(&self) -> Result { - match self.target.clone() { - Some(t) => Ok(t), - None => Ok(self.getenv_unwrap("TARGET")?), - } - } - - fn get_host(&self) -> Result { - match self.host.clone() { - Some(h) => Ok(h), - None => Ok(self.getenv_unwrap("HOST")?), - } - } - - fn get_opt_level(&self) -> Result { - match self.opt_level.as_ref().cloned() { - Some(ol) => Ok(ol), - None => Ok(self.getenv_unwrap("OPT_LEVEL")?), - } - } - - fn get_debug(&self) -> bool { - self.debug.unwrap_or_else(|| match self.getenv("DEBUG") { - Some(s) => s != "false", - None => false, - }) - } - - fn get_out_dir(&self) -> Result { - match self.out_dir.clone() { - Some(p) => Ok(p), - None => Ok(env::var_os("OUT_DIR").map(PathBuf::from).ok_or_else(|| { - Error::new( - ErrorKind::EnvVarNotFound, - "Environment variable OUT_DIR not defined.", - ) - })?), - } - } - - fn getenv(&self, v: &str) -> Option { - let r = env::var(v).ok(); - self.print(&format!("{} = {:?}", v, r)); - r - } - - fn getenv_unwrap(&self, v: &str) -> Result { - match self.getenv(v) { - Some(s) => Ok(s), - None => Err(Error::new( - ErrorKind::EnvVarNotFound, - &format!( - "Environment variable {} not defined.", - v.to_string() - ), - )), - } - } - - fn print(&self, s: &str) { - if self.cargo_metadata { - println!("{}", s); - } - } -} - -impl Default for Build { - fn default() -> Build { - Build::new() - } -} - -impl Tool { - fn new(path: PathBuf) -> Tool { - Tool::with_features(path, false) - } - - fn with_features(path: PathBuf, cuda: bool) -> Tool { - // Try to detect family of the tool from its name, falling back to Gnu. - let family = if let Some(fname) = path.file_name().and_then(|p| p.to_str()) { - if fname.contains("clang") { - ToolFamily::Clang - } else if fname.contains("cl") && !fname.contains("cloudabi") && - !fname.contains("uclibc") { - ToolFamily::Msvc - } else { - ToolFamily::Gnu - } - } else { - ToolFamily::Gnu - }; - Tool { - path: path, - cc_wrapper_path: None, - cc_wrapper_args: Vec::new(), - args: Vec::new(), - env: Vec::new(), - family: family, - cuda: cuda, - } - } - - /// Add a flag, and optionally prepend the NVCC wrapper flag "-Xcompiler". - /// - /// Currently this is only used for compiling CUDA sources, since NVCC only - /// accepts a limited set of GNU-like flags, and the rest must be prefixed - /// with a "-Xcompiler" flag to get passed to the underlying C++ compiler. - fn push_cc_arg(&mut self, flag: OsString) { - if self.cuda { - self.args.push(self.family.nvcc_redirect_flag().into()); - } - self.args.push(flag); - } - - /// Converts this compiler into a `Command` that's ready to be run. - /// - /// This is useful for when the compiler needs to be executed and the - /// command returned will already have the initial arguments and environment - /// variables configured. - pub fn to_command(&self) -> Command { - let mut cmd = match self.cc_wrapper_path { - Some(ref cc_wrapper_path) => { - let mut cmd = Command::new(&cc_wrapper_path); - cmd.arg(&self.path); - cmd.args(&self.cc_wrapper_args); - cmd - }, - None => Command::new(&self.path) - }; - cmd.args(&self.args); - for &(ref k, ref v) in self.env.iter() { - cmd.env(k, v); - } - cmd - } - - /// Returns the path for this compiler. - /// - /// Note that this may not be a path to a file on the filesystem, e.g. "cc", - /// but rather something which will be resolved when a process is spawned. - pub fn path(&self) -> &Path { - &self.path - } - - /// Returns the default set of arguments to the compiler needed to produce - /// executables for the target this compiler generates. - pub fn args(&self) -> &[OsString] { - &self.args - } - - /// Returns the set of environment variables needed for this compiler to - /// operate. - /// - /// This is typically only used for MSVC compilers currently. - pub fn env(&self) -> &[(OsString, OsString)] { - &self.env - } - - /// Returns the compiler command in format of CC environment variable. - /// Or empty string if CC env was not present - /// - /// This is typically used by configure script - pub fn cc_env(&self) -> OsString { - match self.cc_wrapper_path { - Some(ref cc_wrapper_path) => { - let mut cc_env = cc_wrapper_path.as_os_str().to_owned(); - cc_env.push(" "); - cc_env.push(self.path.to_path_buf().into_os_string()); - for arg in self.cc_wrapper_args.iter() { - cc_env.push(" "); - cc_env.push(arg); - } - cc_env - }, - None => { - OsString::from("") - } - } - } - - /// Returns the compiler flags in format of CFLAGS environment variable. - /// Important here - this will not be CFLAGS from env, its internal gcc's flags to use as CFLAGS - /// This is typically used by configure script - pub fn cflags_env(&self) -> OsString { - let mut flags = OsString::new(); - for (i, arg) in self.args.iter().enumerate() { - if i > 0 { - flags.push(" "); - } - flags.push(arg); - } - flags - } - - /// Whether the tool is GNU Compiler Collection-like. - pub fn is_like_gnu(&self) -> bool { - self.family == ToolFamily::Gnu - } - - /// Whether the tool is Clang-like. - pub fn is_like_clang(&self) -> bool { - self.family == ToolFamily::Clang - } - - /// Whether the tool is MSVC-like. - pub fn is_like_msvc(&self) -> bool { - self.family == ToolFamily::Msvc - } -} - -fn run(cmd: &mut Command, program: &str) -> Result<(), Error> { - let (mut child, print) = spawn(cmd, program)?; - let status = match child.wait() { - Ok(s) => s, - Err(_) => { - return Err(Error::new( - ErrorKind::ToolExecError, - &format!( - "Failed to wait on spawned child process, command {:?} with args {:?}.", - cmd, - program - ), - )) - } - }; - print.join().unwrap(); - println!("{}", status); - - if status.success() { - Ok(()) - } else { - Err(Error::new( - ErrorKind::ToolExecError, - &format!( - "Command {:?} with args {:?} did not execute successfully (status code {}).", - cmd, - program, - status - ), - )) - } -} - -fn run_output(cmd: &mut Command, program: &str) -> Result, Error> { - cmd.stdout(Stdio::piped()); - let (mut child, print) = spawn(cmd, program)?; - let mut stdout = vec![]; - child - .stdout - .take() - .unwrap() - .read_to_end(&mut stdout) - .unwrap(); - let status = match child.wait() { - Ok(s) => s, - Err(_) => { - return Err(Error::new( - ErrorKind::ToolExecError, - &format!( - "Failed to wait on spawned child process, command {:?} with args {:?}.", - cmd, - program - ), - )) - } - }; - print.join().unwrap(); - println!("{}", status); - - if status.success() { - Ok(stdout) - } else { - Err(Error::new( - ErrorKind::ToolExecError, - &format!( - "Command {:?} with args {:?} did not execute successfully (status code {}).", - cmd, - program, - status - ), - )) - } -} - -fn spawn(cmd: &mut Command, program: &str) -> Result<(Child, JoinHandle<()>), Error> { - println!("running: {:?}", cmd); - - // Capture the standard error coming from these programs, and write it out - // with cargo:warning= prefixes. Note that this is a bit wonky to avoid - // requiring the output to be UTF-8, we instead just ship bytes from one - // location to another. - match cmd.stderr(Stdio::piped()).spawn() { - Ok(mut child) => { - let stderr = BufReader::new(child.stderr.take().unwrap()); - let print = thread::spawn(move || for line in stderr.split(b'\n').filter_map( - |l| l.ok(), - ) - { - print!("cargo:warning="); - std::io::stdout().write_all(&line).unwrap(); - println!(""); - }); - Ok((child, print)) - } - Err(ref e) if e.kind() == io::ErrorKind::NotFound => { - let extra = if cfg!(windows) { - " (see https://github.com/alexcrichton/cc-rs#compile-time-requirements \ - for help)" - } else { - "" - }; - Err(Error::new( - ErrorKind::ToolNotFound, - &format!( - "Failed to find tool. Is `{}` installed?{}", - program, - extra - ), - )) - } - Err(_) => Err(Error::new( - ErrorKind::ToolExecError, - &format!( - "Command {:?} with args {:?} failed to start.", - cmd, - program - ), - )), - } -} - -fn fail(s: &str) -> ! { - panic!("\n\nInternal error occurred: {}\n\n", s) -} - - -fn command_add_output_file(cmd: &mut Command, dst: &Path, msvc: bool, is_asm: bool) { - if msvc && is_asm { - cmd.arg("/Fo").arg(dst); - } else if msvc { - let mut s = OsString::from("/Fo"); - s.push(&dst); - cmd.arg(s); - } else { - cmd.arg("-o").arg(&dst); - } -} diff -Nru cargo-0.25.0/vendor/cc-1.0.4/src/registry.rs cargo-0.26.0/vendor/cc-1.0.4/src/registry.rs --- cargo-0.25.0/vendor/cc-1.0.4/src/registry.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/src/registry.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,190 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::ffi::{OsString, OsStr}; -use std::io; -use std::ops::RangeFrom; -use std::os::raw; -use std::os::windows::prelude::*; - -pub struct RegistryKey(Repr); - -type HKEY = *mut u8; -type DWORD = u32; -type LPDWORD = *mut DWORD; -type LPCWSTR = *const u16; -type LPWSTR = *mut u16; -type LONG = raw::c_long; -type PHKEY = *mut HKEY; -type PFILETIME = *mut u8; -type LPBYTE = *mut u8; -type REGSAM = u32; - -const ERROR_SUCCESS: DWORD = 0; -const ERROR_NO_MORE_ITEMS: DWORD = 259; -const HKEY_LOCAL_MACHINE: HKEY = 0x80000002 as HKEY; -const REG_SZ: DWORD = 1; -const KEY_READ: DWORD = 0x20019; -const KEY_WOW64_32KEY: DWORD = 0x200; - -#[link(name = "advapi32")] -extern "system" { - fn RegOpenKeyExW(key: HKEY, - lpSubKey: LPCWSTR, - ulOptions: DWORD, - samDesired: REGSAM, - phkResult: PHKEY) - -> LONG; - fn RegEnumKeyExW(key: HKEY, - dwIndex: DWORD, - lpName: LPWSTR, - lpcName: LPDWORD, - lpReserved: LPDWORD, - lpClass: LPWSTR, - lpcClass: LPDWORD, - lpftLastWriteTime: PFILETIME) - -> LONG; - fn RegQueryValueExW(hKey: HKEY, - lpValueName: LPCWSTR, - lpReserved: LPDWORD, - lpType: LPDWORD, - lpData: LPBYTE, - lpcbData: LPDWORD) - -> LONG; - fn RegCloseKey(hKey: HKEY) -> LONG; -} - -struct OwnedKey(HKEY); - -enum Repr { - Const(HKEY), - Owned(OwnedKey), -} - -pub struct Iter<'a> { - idx: RangeFrom, - key: &'a RegistryKey, -} - -unsafe impl Sync for Repr {} -unsafe impl Send for Repr {} - -pub static LOCAL_MACHINE: RegistryKey = RegistryKey(Repr::Const(HKEY_LOCAL_MACHINE)); - -impl RegistryKey { - fn raw(&self) -> HKEY { - match self.0 { - Repr::Const(val) => val, - Repr::Owned(ref val) => val.0, - } - } - - pub fn open(&self, key: &OsStr) -> io::Result { - let key = key.encode_wide().chain(Some(0)).collect::>(); - let mut ret = 0 as *mut _; - let err = unsafe { - RegOpenKeyExW(self.raw(), - key.as_ptr(), - 0, - KEY_READ | KEY_WOW64_32KEY, - &mut ret) - }; - if err == ERROR_SUCCESS as LONG { - Ok(RegistryKey(Repr::Owned(OwnedKey(ret)))) - } else { - Err(io::Error::from_raw_os_error(err as i32)) - } - } - - pub fn iter(&self) -> Iter { - Iter { - idx: 0.., - key: self, - } - } - - pub fn query_str(&self, name: &str) -> io::Result { - let name: &OsStr = name.as_ref(); - let name = name.encode_wide().chain(Some(0)).collect::>(); - let mut len = 0; - let mut kind = 0; - unsafe { - let err = RegQueryValueExW(self.raw(), - name.as_ptr(), - 0 as *mut _, - &mut kind, - 0 as *mut _, - &mut len); - if err != ERROR_SUCCESS as LONG { - return Err(io::Error::from_raw_os_error(err as i32)); - } - if kind != REG_SZ { - return Err(io::Error::new(io::ErrorKind::Other, "registry key wasn't a string")); - } - - // The length here is the length in bytes, but we're using wide - // characters so we need to be sure to halve it for the capacity - // passed in. - let mut v = Vec::with_capacity(len as usize / 2); - let err = RegQueryValueExW(self.raw(), - name.as_ptr(), - 0 as *mut _, - 0 as *mut _, - v.as_mut_ptr() as *mut _, - &mut len); - if err != ERROR_SUCCESS as LONG { - return Err(io::Error::from_raw_os_error(err as i32)); - } - v.set_len(len as usize / 2); - - // Some registry keys may have a terminating nul character, but - // we're not interested in that, so chop it off if it's there. - if v[v.len() - 1] == 0 { - v.pop(); - } - Ok(OsString::from_wide(&v)) - } - } -} - -impl Drop for OwnedKey { - fn drop(&mut self) { - unsafe { - RegCloseKey(self.0); - } - } -} - -impl<'a> Iterator for Iter<'a> { - type Item = io::Result; - - fn next(&mut self) -> Option> { - self.idx.next().and_then(|i| unsafe { - let mut v = Vec::with_capacity(256); - let mut len = v.capacity() as DWORD; - let ret = RegEnumKeyExW(self.key.raw(), - i, - v.as_mut_ptr(), - &mut len, - 0 as *mut _, - 0 as *mut _, - 0 as *mut _, - 0 as *mut _); - if ret == ERROR_NO_MORE_ITEMS as LONG { - None - } else if ret != ERROR_SUCCESS as LONG { - Some(Err(io::Error::from_raw_os_error(ret as i32))) - } else { - v.set_len(len as usize); - Some(Ok(OsString::from_wide(&v))) - } - }) - } -} diff -Nru cargo-0.25.0/vendor/cc-1.0.4/src/setup_config.rs cargo-0.26.0/vendor/cc-1.0.4/src/setup_config.rs --- cargo-0.25.0/vendor/cc-1.0.4/src/setup_config.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/src/setup_config.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,257 +0,0 @@ -// Copyright © 2017 winapi-rs developers -// Licensed under the Apache License, Version 2.0 -// or the MIT license -// , at your option. -// All files in the project carrying such notice may not be copied, modified, or distributed -// except according to those terms. - -#![allow(bad_style)] -#![allow(unused)] - -use std::ffi::OsString; -use std::ptr::null_mut; -use winapi::Interface; -use winapi::{LPFILETIME, ULONG}; -use winapi::S_FALSE; -use winapi::BSTR; -use winapi::LPCOLESTR; -use winapi::{CLSCTX_ALL, CoCreateInstance}; -use winapi::LPSAFEARRAY; -use winapi::{IUnknown, IUnknownVtbl}; -use winapi::{HRESULT, LCID, LPCWSTR, PULONGLONG}; - -use com::{BStr, ComPtr}; - -// Bindings to the Setup.Configuration stuff -pub type InstanceState = u32; - -pub const eNone: InstanceState = 0; -pub const eLocal: InstanceState = 1; -pub const eRegistered: InstanceState = 2; -pub const eNoRebootRequired: InstanceState = 4; -pub const eComplete: InstanceState = -1i32 as u32; - -RIDL!{#[uuid(0xb41463c3, 0x8866, 0x43b5, 0xbc, 0x33, 0x2b, 0x06, 0x76, 0xf7, 0xf4, 0x2e)] -interface ISetupInstance(ISetupInstanceVtbl): IUnknown(IUnknownVtbl) { - fn GetInstanceId( - pbstrInstanceId: *mut BSTR, - ) -> HRESULT, - fn GetInstallDate( - pInstallDate: LPFILETIME, - ) -> HRESULT, - fn GetInstallationName( - pbstrInstallationName: *mut BSTR, - ) -> HRESULT, - fn GetInstallationPath( - pbstrInstallationPath: *mut BSTR, - ) -> HRESULT, - fn GetInstallationVersion( - pbstrInstallationVersion: *mut BSTR, - ) -> HRESULT, - fn GetDisplayName( - lcid: LCID, - pbstrDisplayName: *mut BSTR, - ) -> HRESULT, - fn GetDescription( - lcid: LCID, - pbstrDescription: *mut BSTR, - ) -> HRESULT, - fn ResolvePath( - pwszRelativePath: LPCOLESTR, - pbstrAbsolutePath: *mut BSTR, - ) -> HRESULT, -}} - -RIDL!{#[uuid(0x89143c9a, 0x05af, 0x49b0, 0xb7, 0x17, 0x72, 0xe2, 0x18, 0xa2, 0x18, 0x5c)] -interface ISetupInstance2(ISetupInstance2Vtbl): ISetupInstance(ISetupInstanceVtbl) { - fn GetState( - pState: *mut InstanceState, - ) -> HRESULT, - fn GetPackages( - ppsaPackages: *mut LPSAFEARRAY, - ) -> HRESULT, - fn GetProduct( - ppPackage: *mut *mut ISetupPackageReference, - ) -> HRESULT, - fn GetProductPath( - pbstrProductPath: *mut BSTR, - ) -> HRESULT, -}} - -RIDL!{#[uuid(0x6380bcff, 0x41d3, 0x4b2e, 0x8b, 0x2e, 0xbf, 0x8a, 0x68, 0x10, 0xc8, 0x48)] -interface IEnumSetupInstances(IEnumSetupInstancesVtbl): IUnknown(IUnknownVtbl) { - fn Next( - celt: ULONG, - rgelt: *mut *mut ISetupInstance, - pceltFetched: *mut ULONG, - ) -> HRESULT, - fn Skip( - celt: ULONG, - ) -> HRESULT, - fn Reset() -> HRESULT, - fn Clone( - ppenum: *mut *mut IEnumSetupInstances, - ) -> HRESULT, -}} - -RIDL!{#[uuid(0x42843719, 0xdb4c, 0x46c2, 0x8e, 0x7c, 0x64, 0xf1, 0x81, 0x6e, 0xfd, 0x5b)] -interface ISetupConfiguration(ISetupConfigurationVtbl): IUnknown(IUnknownVtbl) { - fn EnumInstances( - ppEnumInstances: *mut *mut IEnumSetupInstances, - ) -> HRESULT, - fn GetInstanceForCurrentProcess( - ppInstance: *mut *mut ISetupInstance, - ) -> HRESULT, - fn GetInstanceForPath( - wzPath: LPCWSTR, - ppInstance: *mut *mut ISetupInstance, - ) -> HRESULT, -}} - -RIDL!{#[uuid(0x26aab78c, 0x4a60, 0x49d6, 0xaf, 0x3b, 0x3c, 0x35, 0xbc, 0x93, 0x36, 0x5d)] -interface ISetupConfiguration2(ISetupConfiguration2Vtbl): - ISetupConfiguration(ISetupConfigurationVtbl) { - fn EnumAllInstances( - ppEnumInstances: *mut *mut IEnumSetupInstances, - ) -> HRESULT, -}} - -RIDL!{#[uuid(0xda8d8a16, 0xb2b6, 0x4487, 0xa2, 0xf1, 0x59, 0x4c, 0xcc, 0xcd, 0x6b, 0xf5)] -interface ISetupPackageReference(ISetupPackageReferenceVtbl): IUnknown(IUnknownVtbl) { - fn GetId( - pbstrId: *mut BSTR, - ) -> HRESULT, - fn GetVersion( - pbstrVersion: *mut BSTR, - ) -> HRESULT, - fn GetChip( - pbstrChip: *mut BSTR, - ) -> HRESULT, - fn GetLanguage( - pbstrLanguage: *mut BSTR, - ) -> HRESULT, - fn GetBranch( - pbstrBranch: *mut BSTR, - ) -> HRESULT, - fn GetType( - pbstrType: *mut BSTR, - ) -> HRESULT, - fn GetUniqueId( - pbstrUniqueId: *mut BSTR, - ) -> HRESULT, -}} - -RIDL!{#[uuid(0x42b21b78, 0x6192, 0x463e, 0x87, 0xbf, 0xd5, 0x77, 0x83, 0x8f, 0x1d, 0x5c)] -interface ISetupHelper(ISetupHelperVtbl): IUnknown(IUnknownVtbl) { - fn ParseVersion( - pwszVersion: LPCOLESTR, - pullVersion: PULONGLONG, - ) -> HRESULT, - fn ParseVersionRange( - pwszVersionRange: LPCOLESTR, - pullMinVersion: PULONGLONG, - pullMaxVersion: PULONGLONG, - ) -> HRESULT, -}} - -DEFINE_GUID!{CLSID_SetupConfiguration, - 0x177f0c4a, 0x1cd3, 0x4de7, 0xa3, 0x2c, 0x71, 0xdb, 0xbb, 0x9f, 0xa3, 0x6d} - -// Safe wrapper around the COM interfaces -pub struct SetupConfiguration(ComPtr); - -impl SetupConfiguration { - pub fn new() -> Result { - let mut obj = null_mut(); - let err = unsafe { CoCreateInstance( - &CLSID_SetupConfiguration, null_mut(), CLSCTX_ALL, - &ISetupConfiguration::uuidof(), &mut obj, - ) }; - if err < 0 { return Err(err); } - let obj = unsafe { ComPtr::from_raw(obj as *mut ISetupConfiguration) }; - Ok(SetupConfiguration(obj)) - } - pub fn get_instance_for_current_process(&self) -> Result { - let mut obj = null_mut(); - let err = unsafe { self.0.GetInstanceForCurrentProcess(&mut obj) }; - if err < 0 { return Err(err); } - Ok(unsafe { SetupInstance::from_raw(obj) }) - } - pub fn enum_instances(&self) -> Result { - let mut obj = null_mut(); - let err = unsafe { self.0.EnumInstances(&mut obj) }; - if err < 0 { return Err(err); } - Ok(unsafe { EnumSetupInstances::from_raw(obj) }) - } - pub fn enum_all_instances(&self) -> Result { - let mut obj = null_mut(); - let this = try!(self.0.cast::()); - let err = unsafe { this.EnumAllInstances(&mut obj) }; - if err < 0 { return Err(err); } - Ok(unsafe { EnumSetupInstances::from_raw(obj) }) - } -} - -pub struct SetupInstance(ComPtr); - -impl SetupInstance { - pub unsafe fn from_raw(obj: *mut ISetupInstance) -> SetupInstance { - SetupInstance(ComPtr::from_raw(obj)) - } - pub fn instance_id(&self) -> Result { - let mut s = null_mut(); - let err = unsafe { self.0.GetInstanceId(&mut s) }; - let bstr = unsafe { BStr::from_raw(s) }; - if err < 0 { return Err(err); } - Ok(bstr.to_osstring()) - } - pub fn installation_name(&self) -> Result { - let mut s = null_mut(); - let err = unsafe { self.0.GetInstallationName(&mut s) }; - let bstr = unsafe { BStr::from_raw(s) }; - if err < 0 { return Err(err); } - Ok(bstr.to_osstring()) - } - pub fn installation_path(&self) -> Result { - let mut s = null_mut(); - let err = unsafe { self.0.GetInstallationPath(&mut s) }; - let bstr = unsafe { BStr::from_raw(s) }; - if err < 0 { return Err(err); } - Ok(bstr.to_osstring()) - } - pub fn installation_version(&self) -> Result { - let mut s = null_mut(); - let err = unsafe { self.0.GetInstallationVersion(&mut s) }; - let bstr = unsafe { BStr::from_raw(s) }; - if err < 0 { return Err(err); } - Ok(bstr.to_osstring()) - } - pub fn product_path(&self) -> Result { - let mut s = null_mut(); - let this = try!(self.0.cast::()); - let err = unsafe { this.GetProductPath(&mut s) }; - let bstr = unsafe { BStr::from_raw(s) }; - if err < 0 { return Err(err); } - Ok(bstr.to_osstring()) - } -} - -pub struct EnumSetupInstances(ComPtr); - -impl EnumSetupInstances { - pub unsafe fn from_raw(obj: *mut IEnumSetupInstances) -> EnumSetupInstances { - EnumSetupInstances(ComPtr::from_raw(obj)) - } -} - -impl Iterator for EnumSetupInstances { - type Item = Result; - fn next(&mut self) -> Option> { - let mut obj = null_mut(); - let err = unsafe { self.0.Next(1, &mut obj, null_mut()) }; - if err < 0 { return Some(Err(err)); } - if err == S_FALSE { return None; } - Some(Ok(unsafe { SetupInstance::from_raw(obj) })) - } -} - diff -Nru cargo-0.25.0/vendor/cc-1.0.4/src/winapi.rs cargo-0.26.0/vendor/cc-1.0.4/src/winapi.rs --- cargo-0.25.0/vendor/cc-1.0.4/src/winapi.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/src/winapi.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,214 +0,0 @@ -// Copyright © 2015-2017 winapi-rs developers -// Licensed under the Apache License, Version 2.0 -// or the MIT license -// , at your option. -// All files in the project carrying such notice may not be copied, modified, or distributed -// except according to those terms. - -#![allow(bad_style)] - -use std::os::raw; - -pub type wchar_t = u16; - -pub type UINT = raw::c_uint; -pub type LPUNKNOWN = *mut IUnknown; -pub type REFIID = *const IID; -pub type IID = GUID; -pub type REFCLSID = *const IID; -pub type PVOID = *mut raw::c_void; -pub type USHORT = raw::c_ushort; -pub type ULONG = raw::c_ulong; -pub type LONG = raw::c_long; -pub type DWORD = u32; -pub type LPVOID = *mut raw::c_void; -pub type HRESULT = raw::c_long; -pub type LPFILETIME = *mut FILETIME; -pub type BSTR = *mut OLECHAR; -pub type OLECHAR = WCHAR; -pub type WCHAR = wchar_t; -pub type LPCOLESTR = *const OLECHAR; -pub type LCID = DWORD; -pub type LPCWSTR = *const WCHAR; -pub type PULONGLONG = *mut ULONGLONG; -pub type ULONGLONG = u64; - -pub const S_OK: HRESULT = 0; -pub const S_FALSE: HRESULT = 1; -pub const COINIT_MULTITHREADED: u32 = 0x0; - -pub type CLSCTX = u32; - -pub const CLSCTX_INPROC_SERVER: CLSCTX = 0x1; -pub const CLSCTX_INPROC_HANDLER: CLSCTX = 0x2; -pub const CLSCTX_LOCAL_SERVER: CLSCTX = 0x4; -pub const CLSCTX_REMOTE_SERVER: CLSCTX = 0x10; - -pub const CLSCTX_ALL: CLSCTX = CLSCTX_INPROC_SERVER | - CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER; - -#[repr(C)] -#[derive(Copy, Clone)] -pub struct GUID { - pub Data1: raw::c_ulong, - pub Data2: raw::c_ushort, - pub Data3: raw::c_ushort, - pub Data4: [raw::c_uchar; 8], -} - -#[repr(C)] -#[derive(Copy, Clone)] -pub struct FILETIME { - pub dwLowDateTime: DWORD, - pub dwHighDateTime: DWORD, -} - -pub trait Interface { - fn uuidof() -> GUID; -} - -#[link(name = "ole32")] -#[link(name = "oleaut32")] -extern { } - -extern "system" { - pub fn CoInitializeEx(pvReserved: LPVOID, dwCoInit: DWORD) -> HRESULT; - pub fn CoCreateInstance(rclsid: REFCLSID, pUnkOuter: LPUNKNOWN, - dwClsContext: DWORD, riid: REFIID, - ppv: *mut LPVOID) -> HRESULT; - pub fn SysFreeString(bstrString: BSTR); - pub fn SysStringLen(pbstr: BSTR) -> UINT; -} - -#[repr(C)] -#[derive(Copy, Clone)] -pub struct SAFEARRAYBOUND { - pub cElements: ULONG, - pub lLbound: LONG, -} - -#[repr(C)] -#[derive(Copy, Clone)] -pub struct SAFEARRAY { - pub cDims: USHORT, - pub fFeatures: USHORT, - pub cbElements: ULONG, - pub cLocks: ULONG, - pub pvData: PVOID, - pub rgsabound: [SAFEARRAYBOUND; 1], -} - -pub type LPSAFEARRAY = *mut SAFEARRAY; - -macro_rules! DEFINE_GUID { - ( - $name:ident, $l:expr, $w1:expr, $w2:expr, - $b1:expr, $b2:expr, $b3:expr, $b4:expr, $b5:expr, $b6:expr, $b7:expr, $b8:expr - ) => { - pub const $name: $crate::winapi::GUID = $crate::winapi::GUID { - Data1: $l, - Data2: $w1, - Data3: $w2, - Data4: [$b1, $b2, $b3, $b4, $b5, $b6, $b7, $b8], - }; - } -} - -macro_rules! RIDL { - (#[uuid($($uuid:expr),+)] - interface $interface:ident ($vtbl:ident) {$( - fn $method:ident($($p:ident : $t:ty,)*) -> $rtr:ty, - )+}) => ( - #[repr(C)] - pub struct $vtbl { - $(pub $method: unsafe extern "system" fn( - This: *mut $interface, - $($p: $t),* - ) -> $rtr,)+ - } - #[repr(C)] - pub struct $interface { - pub lpVtbl: *const $vtbl, - } - RIDL!{@impl $interface {$(fn $method($($p: $t,)*) -> $rtr,)+}} - RIDL!{@uuid $interface $($uuid),+} - ); - (#[uuid($($uuid:expr),+)] - interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident) { - }) => ( - #[repr(C)] - pub struct $vtbl { - pub parent: $pvtbl, - } - #[repr(C)] - pub struct $interface { - pub lpVtbl: *const $vtbl, - } - RIDL!{@deref $interface $pinterface} - RIDL!{@uuid $interface $($uuid),+} - ); - (#[uuid($($uuid:expr),+)] - interface $interface:ident ($vtbl:ident) : $pinterface:ident ($pvtbl:ident) {$( - fn $method:ident($($p:ident : $t:ty,)*) -> $rtr:ty, - )+}) => ( - #[repr(C)] - pub struct $vtbl { - pub parent: $pvtbl, - $(pub $method: unsafe extern "system" fn( - This: *mut $interface, - $($p: $t,)* - ) -> $rtr,)+ - } - #[repr(C)] - pub struct $interface { - pub lpVtbl: *const $vtbl, - } - RIDL!{@impl $interface {$(fn $method($($p: $t,)*) -> $rtr,)+}} - RIDL!{@deref $interface $pinterface} - RIDL!{@uuid $interface $($uuid),+} - ); - (@deref $interface:ident $pinterface:ident) => ( - impl ::std::ops::Deref for $interface { - type Target = $pinterface; - #[inline] - fn deref(&self) -> &$pinterface { - unsafe { &*(self as *const $interface as *const $pinterface) } - } - } - ); - (@impl $interface:ident {$( - fn $method:ident($($p:ident : $t:ty,)*) -> $rtr:ty, - )+}) => ( - impl $interface { - $(#[inline] pub unsafe fn $method(&self, $($p: $t,)*) -> $rtr { - ((*self.lpVtbl).$method)(self as *const _ as *mut _, $($p,)*) - })+ - } - ); - (@uuid $interface:ident - $l:expr, $w1:expr, $w2:expr, - $b1:expr, $b2:expr, $b3:expr, $b4:expr, $b5:expr, $b6:expr, $b7:expr, $b8:expr - ) => ( - impl $crate::winapi::Interface for $interface { - #[inline] - fn uuidof() -> $crate::winapi::GUID { - $crate::winapi::GUID { - Data1: $l, - Data2: $w1, - Data3: $w2, - Data4: [$b1, $b2, $b3, $b4, $b5, $b6, $b7, $b8], - } - } - } - ); -} - -RIDL!{#[uuid(0x00000000, 0x0000, 0x0000, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46)] -interface IUnknown(IUnknownVtbl) { - fn QueryInterface( - riid: REFIID, - ppvObject: *mut *mut raw::c_void, - ) -> HRESULT, - fn AddRef() -> ULONG, - fn Release() -> ULONG, -}} diff -Nru cargo-0.25.0/vendor/cc-1.0.4/src/windows_registry.rs cargo-0.26.0/vendor/cc-1.0.4/src/windows_registry.rs --- cargo-0.25.0/vendor/cc-1.0.4/src/windows_registry.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/src/windows_registry.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,634 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A helper module to probe the Windows Registry when looking for -//! windows-specific tools. - -use std::process::Command; - -use Tool; - -#[cfg(windows)] -macro_rules! otry { - ($expr:expr) => (match $expr { - Some(val) => val, - None => return None, - }) -} - -/// Attempts to find a tool within an MSVC installation using the Windows -/// registry as a point to search from. -/// -/// The `target` argument is the target that the tool should work for (e.g. -/// compile or link for) and the `tool` argument is the tool to find (e.g. -/// `cl.exe` or `link.exe`). -/// -/// This function will return `None` if the tool could not be found, or it will -/// return `Some(cmd)` which represents a command that's ready to execute the -/// tool with the appropriate environment variables set. -/// -/// Note that this function always returns `None` for non-MSVC targets. -pub fn find(target: &str, tool: &str) -> Option { - find_tool(target, tool).map(|c| c.to_command()) -} - -/// Similar to the `find` function above, this function will attempt the same -/// operation (finding a MSVC tool in a local install) but instead returns a -/// `Tool` which may be introspected. -#[cfg(not(windows))] -pub fn find_tool(_target: &str, _tool: &str) -> Option { - None -} - -/// Documented above. -#[cfg(windows)] -pub fn find_tool(target: &str, tool: &str) -> Option { - use std::env; - - // This logic is all tailored for MSVC, if we're not that then bail out - // early. - if !target.contains("msvc") { - return None; - } - - // Looks like msbuild isn't located in the same location as other tools like - // cl.exe and lib.exe. To handle this we probe for it manually with - // dedicated registry keys. - if tool.contains("msbuild") { - return impl_::find_msbuild(target); - } - - // If VCINSTALLDIR is set, then someone's probably already run vcvars and we - // should just find whatever that indicates. - if env::var_os("VCINSTALLDIR").is_some() { - return env::var_os("PATH") - .and_then(|path| env::split_paths(&path).map(|p| p.join(tool)).find(|p| p.exists())) - .map(|path| Tool::new(path.into())); - } - - // Ok, if we're here, now comes the fun part of the probing. Default shells - // or shells like MSYS aren't really configured to execute `cl.exe` and the - // various compiler tools shipped as part of Visual Studio. Here we try to - // first find the relevant tool, then we also have to be sure to fill in - // environment variables like `LIB`, `INCLUDE`, and `PATH` to ensure that - // the tool is actually usable. - - return impl_::find_msvc_15(tool, target) - .or_else(|| impl_::find_msvc_14(tool, target)) - .or_else(|| impl_::find_msvc_12(tool, target)) - .or_else(|| impl_::find_msvc_11(tool, target)); -} - -/// A version of Visual Studio -#[derive(Debug, PartialEq, Eq, Copy, Clone)] -pub enum VsVers { - /// Visual Studio 12 (2013) - Vs12, - /// Visual Studio 14 (2015) - Vs14, - /// Visual Studio 15 (2017) - Vs15, - - /// Hidden variant that should not be matched on. Callers that want to - /// handle an enumeration of `VsVers` instances should always have a default - /// case meaning that it's a VS version they don't understand. - #[doc(hidden)] - #[allow(bad_style)] - __Nonexhaustive_do_not_match_this_or_your_code_will_break, -} - -/// Find the most recent installed version of Visual Studio -/// -/// This is used by the cmake crate to figure out the correct -/// generator. -#[cfg(not(windows))] -pub fn find_vs_version() -> Result { - Err(format!("not windows")) -} - -/// Documented above -#[cfg(windows)] -pub fn find_vs_version() -> Result { - use std::env; - - match env::var("VisualStudioVersion") { - Ok(version) => { - match &version[..] { - "15.0" => Ok(VsVers::Vs15), - "14.0" => Ok(VsVers::Vs14), - "12.0" => Ok(VsVers::Vs12), - vers => Err(format!("\n\n\ - unsupported or unknown VisualStudio version: {}\n\ - if another version is installed consider running \ - the appropriate vcvars script before building this \ - crate\n\ - ", vers)), - } - } - _ => { - // Check for the presense of a specific registry key - // that indicates visual studio is installed. - if impl_::has_msbuild_version("15.0") { - Ok(VsVers::Vs15) - } else if impl_::has_msbuild_version("14.0") { - Ok(VsVers::Vs14) - } else if impl_::has_msbuild_version("12.0") { - Ok(VsVers::Vs12) - } else { - Err(format!("\n\n\ - couldn't determine visual studio generator\n\ - if VisualStudio is installed, however, consider \ - running the appropriate vcvars script before building \ - this crate\n\ - ")) - } - } - } -} - -#[cfg(windows)] -mod impl_ { - use std::env; - use std::ffi::OsString; - use std::mem; - use std::path::{Path, PathBuf}; - use std::fs::File; - use std::io::Read; - use registry::{RegistryKey, LOCAL_MACHINE}; - use com; - use setup_config::{SetupConfiguration, SetupInstance}; - - use Tool; - - struct MsvcTool { - tool: PathBuf, - libs: Vec, - path: Vec, - include: Vec, - } - - impl MsvcTool { - fn new(tool: PathBuf) -> MsvcTool { - MsvcTool { - tool: tool, - libs: Vec::new(), - path: Vec::new(), - include: Vec::new(), - } - } - - fn into_tool(self) -> Tool { - let MsvcTool { tool, libs, path, include } = self; - let mut tool = Tool::new(tool.into()); - add_env(&mut tool, "LIB", libs); - add_env(&mut tool, "PATH", path); - add_env(&mut tool, "INCLUDE", include); - tool - } - } - - // In MSVC 15 (2017) MS once again changed the scheme for locating - // the tooling. Now we must go through some COM interfaces, which - // is super fun for Rust. - // - // Note that much of this logic can be found [online] wrt paths, COM, etc. - // - // [online]: https://blogs.msdn.microsoft.com/vcblog/2017/03/06/finding-the-visual-c-compiler-tools-in-visual-studio-2017/ - pub fn find_msvc_15(tool: &str, target: &str) -> Option { - otry!(com::initialize().ok()); - - let config = otry!(SetupConfiguration::new().ok()); - let iter = otry!(config.enum_all_instances().ok()); - for instance in iter { - let instance = otry!(instance.ok()); - let tool = tool_from_vs15_instance(tool, target, &instance); - if tool.is_some() { - return tool; - } - } - - None - } - - fn tool_from_vs15_instance(tool: &str, target: &str, - instance: &SetupInstance) -> Option { - let (bin_path, host_dylib_path, lib_path, include_path) = otry!(vs15_vc_paths(target, instance)); - let tool_path = bin_path.join(tool); - if !tool_path.exists() { return None }; - - let mut tool = MsvcTool::new(tool_path); - tool.path.push(host_dylib_path); - tool.libs.push(lib_path); - tool.include.push(include_path); - - if let Some((atl_lib_path, atl_include_path)) = atl_paths(target, &bin_path) { - tool.libs.push(atl_lib_path); - tool.include.push(atl_include_path); - } - - otry!(add_sdks(&mut tool, target)); - - Some(tool.into_tool()) - } - - fn vs15_vc_paths(target: &str, instance: &SetupInstance) -> Option<(PathBuf, PathBuf, PathBuf, PathBuf)> { - let instance_path: PathBuf = otry!(instance.installation_path().ok()).into(); - let version_path = instance_path.join(r"VC\Auxiliary\Build\Microsoft.VCToolsVersion.default.txt"); - let mut version_file = otry!(File::open(version_path).ok()); - let mut version = String::new(); - otry!(version_file.read_to_string(&mut version).ok()); - let version = version.trim(); - let host = match host_arch() { - X86 => "X86", - X86_64 => "X64", - _ => return None, - }; - let target = otry!(lib_subdir(target)); - // The directory layout here is MSVC/bin/Host$host/$target/ - let path = instance_path.join(r"VC\Tools\MSVC").join(version); - // This is the path to the toolchain for a particular target, running - // on a given host - let bin_path = path.join("bin").join(&format!("Host{}", host)).join(&target); - // But! we also need PATH to contain the target directory for the host - // architecture, because it contains dlls like mspdb140.dll compiled for - // the host architecture. - let host_dylib_path = path.join("bin").join(&format!("Host{}", host)).join(&host.to_lowercase()); - let lib_path = path.join("lib").join(&target); - let include_path = path.join("include"); - Some((bin_path, host_dylib_path, lib_path, include_path)) - } - - fn atl_paths(target: &str, path: &Path) -> Option<(PathBuf, PathBuf)> { - let atl_path = path.join("atlfmc"); - let sub = otry!(lib_subdir(target)); - if atl_path.exists() { - Some((atl_path.join("lib").join(sub), atl_path.join("include"))) - } else { - None - } - } - - // For MSVC 14 we need to find the Universal CRT as well as either - // the Windows 10 SDK or Windows 8.1 SDK. - pub fn find_msvc_14(tool: &str, target: &str) -> Option { - let vcdir = otry!(get_vc_dir("14.0")); - let mut tool = otry!(get_tool(tool, &vcdir, target)); - otry!(add_sdks(&mut tool, target)); - Some(tool.into_tool()) - } - - fn add_sdks(tool: &mut MsvcTool, target: &str) -> Option<()> { - let sub = otry!(lib_subdir(target)); - let (ucrt, ucrt_version) = otry!(get_ucrt_dir()); - - tool.path.push(ucrt.join("bin").join(&ucrt_version).join(sub)); - - let ucrt_include = ucrt.join("include").join(&ucrt_version); - tool.include.push(ucrt_include.join("ucrt")); - - let ucrt_lib = ucrt.join("lib").join(&ucrt_version); - tool.libs.push(ucrt_lib.join("ucrt").join(sub)); - - if let Some((sdk, version)) = get_sdk10_dir() { - tool.path.push(sdk.join("bin").join(sub)); - let sdk_lib = sdk.join("lib").join(&version); - tool.libs.push(sdk_lib.join("um").join(sub)); - let sdk_include = sdk.join("include").join(&version); - tool.include.push(sdk_include.join("um")); - tool.include.push(sdk_include.join("winrt")); - tool.include.push(sdk_include.join("shared")); - } else if let Some(sdk) = get_sdk81_dir() { - tool.path.push(sdk.join("bin").join(sub)); - let sdk_lib = sdk.join("lib").join("winv6.3"); - tool.libs.push(sdk_lib.join("um").join(sub)); - let sdk_include = sdk.join("include"); - tool.include.push(sdk_include.join("um")); - tool.include.push(sdk_include.join("winrt")); - tool.include.push(sdk_include.join("shared")); - } - - Some(()) - } - - // For MSVC 12 we need to find the Windows 8.1 SDK. - pub fn find_msvc_12(tool: &str, target: &str) -> Option { - let vcdir = otry!(get_vc_dir("12.0")); - let mut tool = otry!(get_tool(tool, &vcdir, target)); - let sub = otry!(lib_subdir(target)); - let sdk81 = otry!(get_sdk81_dir()); - tool.path.push(sdk81.join("bin").join(sub)); - let sdk_lib = sdk81.join("lib").join("winv6.3"); - tool.libs.push(sdk_lib.join("um").join(sub)); - let sdk_include = sdk81.join("include"); - tool.include.push(sdk_include.join("shared")); - tool.include.push(sdk_include.join("um")); - tool.include.push(sdk_include.join("winrt")); - Some(tool.into_tool()) - } - - // For MSVC 11 we need to find the Windows 8 SDK. - pub fn find_msvc_11(tool: &str, target: &str) -> Option { - let vcdir = otry!(get_vc_dir("11.0")); - let mut tool = otry!(get_tool(tool, &vcdir, target)); - let sub = otry!(lib_subdir(target)); - let sdk8 = otry!(get_sdk8_dir()); - tool.path.push(sdk8.join("bin").join(sub)); - let sdk_lib = sdk8.join("lib").join("win8"); - tool.libs.push(sdk_lib.join("um").join(sub)); - let sdk_include = sdk8.join("include"); - tool.include.push(sdk_include.join("shared")); - tool.include.push(sdk_include.join("um")); - tool.include.push(sdk_include.join("winrt")); - Some(tool.into_tool()) - } - - fn add_env(tool: &mut Tool, env: &str, paths: Vec) { - let prev = env::var_os(env).unwrap_or(OsString::new()); - let prev = env::split_paths(&prev); - let new = paths.into_iter().chain(prev); - tool.env.push((env.to_string().into(), env::join_paths(new).unwrap())); - } - - // Given a possible MSVC installation directory, we look for the linker and - // then add the MSVC library path. - fn get_tool(tool: &str, path: &Path, target: &str) -> Option { - bin_subdir(target) - .into_iter() - .map(|(sub, host)| (path.join("bin").join(sub).join(tool), path.join("bin").join(host))) - .filter(|&(ref path, _)| path.is_file()) - .map(|(path, host)| { - let mut tool = MsvcTool::new(path); - tool.path.push(host); - tool - }) - .filter_map(|mut tool| { - let sub = otry!(vc_lib_subdir(target)); - tool.libs.push(path.join("lib").join(sub)); - tool.include.push(path.join("include")); - let atlmfc_path = path.join("atlmfc"); - if atlmfc_path.exists() { - tool.libs.push(atlmfc_path.join("lib").join(sub)); - tool.include.push(atlmfc_path.join("include")); - } - Some(tool) - }) - .next() - } - - // To find MSVC we look in a specific registry key for the version we are - // trying to find. - fn get_vc_dir(ver: &str) -> Option { - let key = r"SOFTWARE\Microsoft\VisualStudio\SxS\VC7"; - let key = otry!(LOCAL_MACHINE.open(key.as_ref()).ok()); - let path = otry!(key.query_str(ver).ok()); - Some(path.into()) - } - - // To find the Universal CRT we look in a specific registry key for where - // all the Universal CRTs are located and then sort them asciibetically to - // find the newest version. While this sort of sorting isn't ideal, it is - // what vcvars does so that's good enough for us. - // - // Returns a pair of (root, version) for the ucrt dir if found - fn get_ucrt_dir() -> Option<(PathBuf, String)> { - let key = r"SOFTWARE\Microsoft\Windows Kits\Installed Roots"; - let key = otry!(LOCAL_MACHINE.open(key.as_ref()).ok()); - let root = otry!(key.query_str("KitsRoot10").ok()); - let readdir = otry!(Path::new(&root).join("lib").read_dir().ok()); - let max_libdir = otry!(readdir.filter_map(|dir| dir.ok()) - .map(|dir| dir.path()) - .filter(|dir| { - dir.components() - .last() - .and_then(|c| c.as_os_str().to_str()) - .map(|c| c.starts_with("10.") && dir.join("ucrt").is_dir()) - .unwrap_or(false) - }) - .max()); - let version = max_libdir.components().last().unwrap(); - let version = version.as_os_str().to_str().unwrap().to_string(); - Some((root.into(), version)) - } - - // Vcvars finds the correct version of the Windows 10 SDK by looking - // for the include `um\Windows.h` because sometimes a given version will - // only have UCRT bits without the rest of the SDK. Since we only care about - // libraries and not includes, we instead look for `um\x64\kernel32.lib`. - // Since the 32-bit and 64-bit libraries are always installed together we - // only need to bother checking x64, making this code a tiny bit simpler. - // Like we do for the Universal CRT, we sort the possibilities - // asciibetically to find the newest one as that is what vcvars does. - fn get_sdk10_dir() -> Option<(PathBuf, String)> { - let key = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v10.0"; - let key = otry!(LOCAL_MACHINE.open(key.as_ref()).ok()); - let root = otry!(key.query_str("InstallationFolder").ok()); - let readdir = otry!(Path::new(&root).join("lib").read_dir().ok()); - let mut dirs = readdir.filter_map(|dir| dir.ok()) - .map(|dir| dir.path()) - .collect::>(); - dirs.sort(); - let dir = otry!(dirs.into_iter() - .rev() - .filter(|dir| dir.join("um").join("x64").join("kernel32.lib").is_file()) - .next()); - let version = dir.components().last().unwrap(); - let version = version.as_os_str().to_str().unwrap().to_string(); - Some((root.into(), version)) - } - - // Interestingly there are several subdirectories, `win7` `win8` and - // `winv6.3`. Vcvars seems to only care about `winv6.3` though, so the same - // applies to us. Note that if we were targetting kernel mode drivers - // instead of user mode applications, we would care. - fn get_sdk81_dir() -> Option { - let key = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.1"; - let key = otry!(LOCAL_MACHINE.open(key.as_ref()).ok()); - let root = otry!(key.query_str("InstallationFolder").ok()); - Some(root.into()) - } - - fn get_sdk8_dir() -> Option { - let key = r"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.0"; - let key = otry!(LOCAL_MACHINE.open(key.as_ref()).ok()); - let root = otry!(key.query_str("InstallationFolder").ok()); - Some(root.into()) - } - - const PROCESSOR_ARCHITECTURE_INTEL: u16 = 0; - const PROCESSOR_ARCHITECTURE_AMD64: u16 = 9; - const X86: u16 = PROCESSOR_ARCHITECTURE_INTEL; - const X86_64: u16 = PROCESSOR_ARCHITECTURE_AMD64; - - // When choosing the tool to use, we have to choose the one which matches - // the target architecture. Otherwise we end up in situations where someone - // on 32-bit Windows is trying to cross compile to 64-bit and it tries to - // invoke the native 64-bit compiler which won't work. - // - // For the return value of this function, the first member of the tuple is - // the folder of the tool we will be invoking, while the second member is - // the folder of the host toolchain for that tool which is essential when - // using a cross linker. We return a Vec since on x64 there are often two - // linkers that can target the architecture we desire. The 64-bit host - // linker is preferred, and hence first, due to 64-bit allowing it more - // address space to work with and potentially being faster. - fn bin_subdir(target: &str) -> Vec<(&'static str, &'static str)> { - let arch = target.split('-').next().unwrap(); - match (arch, host_arch()) { - ("i586", X86) | ("i686", X86) => vec![("", "")], - ("i586", X86_64) | ("i686", X86_64) => vec![("amd64_x86", "amd64"), ("", "")], - ("x86_64", X86) => vec![("x86_amd64", "")], - ("x86_64", X86_64) => vec![("amd64", "amd64"), ("x86_amd64", "")], - ("arm", X86) => vec![("x86_arm", "")], - ("arm", X86_64) => vec![("amd64_arm", "amd64"), ("x86_arm", "")], - _ => vec![], - } - } - - fn lib_subdir(target: &str) -> Option<&'static str> { - let arch = target.split('-').next().unwrap(); - match arch { - "i586" | "i686" => Some("x86"), - "x86_64" => Some("x64"), - "arm" => Some("arm"), - _ => None, - } - } - - // MSVC's x86 libraries are not in a subfolder - fn vc_lib_subdir(target: &str) -> Option<&'static str> { - let arch = target.split('-').next().unwrap(); - match arch { - "i586" | "i686" => Some(""), - "x86_64" => Some("amd64"), - "arm" => Some("arm"), - _ => None, - } - } - - #[allow(bad_style)] - fn host_arch() -> u16 { - type DWORD = u32; - type WORD = u16; - type LPVOID = *mut u8; - type DWORD_PTR = usize; - - #[repr(C)] - struct SYSTEM_INFO { - wProcessorArchitecture: WORD, - _wReserved: WORD, - _dwPageSize: DWORD, - _lpMinimumApplicationAddress: LPVOID, - _lpMaximumApplicationAddress: LPVOID, - _dwActiveProcessorMask: DWORD_PTR, - _dwNumberOfProcessors: DWORD, - _dwProcessorType: DWORD, - _dwAllocationGranularity: DWORD, - _wProcessorLevel: WORD, - _wProcessorRevision: WORD, - } - - extern "system" { - fn GetNativeSystemInfo(lpSystemInfo: *mut SYSTEM_INFO); - } - - unsafe { - let mut info = mem::zeroed(); - GetNativeSystemInfo(&mut info); - info.wProcessorArchitecture - } - } - - // Given a registry key, look at all the sub keys and find the one which has - // the maximal numeric value. - // - // Returns the name of the maximal key as well as the opened maximal key. - fn max_version(key: &RegistryKey) -> Option<(OsString, RegistryKey)> { - let mut max_vers = 0; - let mut max_key = None; - for subkey in key.iter().filter_map(|k| k.ok()) { - let val = subkey.to_str() - .and_then(|s| s.trim_left_matches("v").replace(".", "").parse().ok()); - let val = match val { - Some(s) => s, - None => continue, - }; - if val > max_vers { - if let Ok(k) = key.open(&subkey) { - max_vers = val; - max_key = Some((subkey, k)); - } - } - } - max_key - } - - pub fn has_msbuild_version(version: &str) -> bool { - match version { - "15.0" => { - find_msbuild_vs15("x86_64-pc-windows-msvc").is_some() || - find_msbuild_vs15("i686-pc-windows-msvc").is_some() - } - "12.0" | "14.0" => { - LOCAL_MACHINE.open( - &OsString::from(format!("SOFTWARE\\Microsoft\\MSBuild\\ToolsVersions\\{}", - version))).is_ok() - } - _ => false - } - } - - // see http://stackoverflow.com/questions/328017/path-to-msbuild - pub fn find_msbuild(target: &str) -> Option { - // VS 15 (2017) changed how to locate msbuild - if let Some(r) = find_msbuild_vs15(target) { - return Some(r); - } else { - find_old_msbuild(target) - } - } - - fn find_msbuild_vs15(target: &str) -> Option { - // Seems like this could also go through SetupConfiguration, - // or that find_msvc_15 could just use this registry key - // instead of the COM interface. - let key = r"SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7"; - LOCAL_MACHINE.open(key.as_ref()) - .ok() - .and_then(|key| { - key.query_str("15.0").ok() - }) - .map(|path| { - let path = PathBuf::from(path).join(r"MSBuild\15.0\Bin\MSBuild.exe"); - let mut tool = Tool::new(path); - if target.contains("x86_64") { - tool.env.push(("Platform".into(), "X64".into())); - } - tool - }) - } - - fn find_old_msbuild(target: &str) -> Option { - let key = r"SOFTWARE\Microsoft\MSBuild\ToolsVersions"; - LOCAL_MACHINE.open(key.as_ref()) - .ok() - .and_then(|key| { - max_version(&key).and_then(|(_vers, key)| key.query_str("MSBuildToolsPath").ok()) - }) - .map(|path| { - let mut path = PathBuf::from(path); - path.push("MSBuild.exe"); - let mut tool = Tool::new(path); - if target.contains("x86_64") { - tool.env.push(("Platform".into(), "X64".into())); - } - tool - }) - } -} diff -Nru cargo-0.25.0/vendor/cc-1.0.4/tests/cc_env.rs cargo-0.26.0/vendor/cc-1.0.4/tests/cc_env.rs --- cargo-0.25.0/vendor/cc-1.0.4/tests/cc_env.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/tests/cc_env.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -extern crate cc; -extern crate tempdir; - -use std::env; -use std::path::Path; -use std::ffi::OsString; - -mod support; -use support::Test; - -#[test] -fn main() { - ccache(); - distcc(); - ccache_spaces(); - ccache_env_flags(); -} - -fn ccache() { - let test = Test::gnu(); - - env::set_var("CC", "ccache cc"); - let compiler = test.gcc().file("foo.c").get_compiler(); - - assert_eq!(compiler.path(), Path::new("cc")); -} - -fn ccache_spaces() { - let test = Test::gnu(); - test.shim("ccache"); - - env::set_var("CC", "ccache cc"); - let compiler = test.gcc().file("foo.c").get_compiler(); - assert_eq!(compiler.path(), Path::new("cc")); -} - -fn distcc() { - let test = Test::gnu(); - test.shim("distcc"); - - env::set_var("CC", "distcc cc"); - let compiler = test.gcc().file("foo.c").get_compiler(); - assert_eq!(compiler.path(), Path::new("cc")); -} - -fn ccache_env_flags() { - let test = Test::gnu(); - test.shim("ccache"); - - env::set_var("CC", "ccache lol-this-is-not-a-compiler"); - let compiler = test.gcc().file("foo.c").get_compiler(); - assert_eq!(compiler.path(), Path::new("lol-this-is-not-a-compiler")); - assert_eq!( - compiler.cc_env(), - OsString::from("ccache lol-this-is-not-a-compiler") - ); - assert!( - compiler - .cflags_env() - .into_string() - .unwrap() - .contains("ccache") == false - ); - assert!( - compiler - .cflags_env() - .into_string() - .unwrap() - .contains(" lol-this-is-not-a-compiler") == false - ); - - env::set_var("CC", ""); -} diff -Nru cargo-0.25.0/vendor/cc-1.0.4/tests/support/mod.rs cargo-0.26.0/vendor/cc-1.0.4/tests/support/mod.rs --- cargo-0.25.0/vendor/cc-1.0.4/tests/support/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/tests/support/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,122 +0,0 @@ -#![allow(dead_code)] - -use std::env; -use std::ffi::OsStr; -use std::fs::{self, File}; -use std::io::prelude::*; -use std::path::PathBuf; - -use cc; -use tempdir::TempDir; - -pub struct Test { - pub td: TempDir, - pub gcc: PathBuf, - pub msvc: bool, -} - -pub struct Execution { - args: Vec, -} - -impl Test { - pub fn new() -> Test { - let mut gcc = PathBuf::from(env::current_exe().unwrap()); - gcc.pop(); - if gcc.ends_with("deps") { - gcc.pop(); - } - gcc.push(format!("gcc-shim{}", env::consts::EXE_SUFFIX)); - Test { - td: TempDir::new("gcc-test").unwrap(), - gcc: gcc, - msvc: false, - } - } - - pub fn gnu() -> Test { - let t = Test::new(); - t.shim("cc").shim("c++").shim("ar"); - t - } - - pub fn msvc() -> Test { - let mut t = Test::new(); - t.shim("cl").shim("lib.exe"); - t.msvc = true; - t - } - - pub fn shim(&self, name: &str) -> &Test { - let fname = format!("{}{}", name, env::consts::EXE_SUFFIX); - fs::hard_link(&self.gcc, self.td.path().join(&fname)) - .or_else(|_| fs::copy(&self.gcc, self.td.path().join(&fname)).map(|_| ())) - .unwrap(); - self - } - - pub fn gcc(&self) -> cc::Build { - let mut cfg = cc::Build::new(); - let mut path = env::split_paths(&env::var_os("PATH").unwrap()).collect::>(); - path.insert(0, self.td.path().to_owned()); - let target = if self.msvc { - "x86_64-pc-windows-msvc" - } else { - "x86_64-unknown-linux-gnu" - }; - - cfg.target(target) - .host(target) - .opt_level(2) - .debug(false) - .out_dir(self.td.path()) - .__set_env("PATH", env::join_paths(path).unwrap()) - .__set_env("GCCTEST_OUT_DIR", self.td.path()); - if self.msvc { - cfg.compiler(self.td.path().join("cl")); - cfg.archiver(self.td.path().join("lib.exe")); - } - cfg - } - - pub fn cmd(&self, i: u32) -> Execution { - let mut s = String::new(); - File::open(self.td.path().join(format!("out{}", i))) - .unwrap() - .read_to_string(&mut s) - .unwrap(); - Execution { args: s.lines().map(|s| s.to_string()).collect() } - } -} - -impl Execution { - pub fn must_have>(&self, p: P) -> &Execution { - if !self.has(p.as_ref()) { - panic!("didn't find {:?} in {:?}", p.as_ref(), self.args); - } else { - self - } - } - - pub fn must_not_have>(&self, p: P) -> &Execution { - if self.has(p.as_ref()) { - panic!("found {:?}", p.as_ref()); - } else { - self - } - } - - pub fn has(&self, p: &OsStr) -> bool { - self.args.iter().any(|arg| OsStr::new(arg) == p) - } - - pub fn must_have_in_order(&self, before: &str, after: &str) -> &Execution { - let before_position = self.args.iter().rposition(|x| OsStr::new(x) == OsStr::new(before)); - let after_position = self.args.iter().rposition(|x| OsStr::new(x) == OsStr::new(after)); - match (before_position, after_position) { - (Some(b), Some(a)) if b < a => {}, - (b, a) => { panic!("{:?} (last position: {:?}) did not appear before {:?} (last position: {:?})", before, b, after, a) }, - }; - self - } -} diff -Nru cargo-0.25.0/vendor/cc-1.0.4/tests/test.rs cargo-0.26.0/vendor/cc-1.0.4/tests/test.rs --- cargo-0.25.0/vendor/cc-1.0.4/tests/test.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/tests/test.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,351 +0,0 @@ -extern crate cc; -extern crate tempdir; - -use support::Test; - -mod support; - -#[test] -fn gnu_smoke() { - let test = Test::gnu(); - test.gcc() - .file("foo.c") - .compile("foo"); - - test.cmd(0) - .must_have("-O2") - .must_have("foo.c") - .must_not_have("-g") - .must_have("-c") - .must_have("-ffunction-sections") - .must_have("-fdata-sections"); - test.cmd(1).must_have(test.td.path().join("foo.o")); -} - -#[test] -fn gnu_opt_level_1() { - let test = Test::gnu(); - test.gcc() - .opt_level(1) - .file("foo.c") - .compile("foo"); - - test.cmd(0) - .must_have("-O1") - .must_not_have("-O2"); -} - -#[test] -fn gnu_opt_level_s() { - let test = Test::gnu(); - test.gcc() - .opt_level_str("s") - .file("foo.c") - .compile("foo"); - - test.cmd(0) - .must_have("-Os") - .must_not_have("-O1") - .must_not_have("-O2") - .must_not_have("-O3") - .must_not_have("-Oz"); -} - -#[test] -fn gnu_debug() { - let test = Test::gnu(); - test.gcc() - .debug(true) - .file("foo.c") - .compile("foo"); - test.cmd(0).must_have("-g"); -} - -#[test] -fn gnu_warnings_into_errors() { - let test = Test::gnu(); - test.gcc() - .warnings_into_errors(true) - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_have("-Werror"); -} - -#[test] -fn gnu_warnings() { - let test = Test::gnu(); - test.gcc() - .warnings(true) - .flag("-Wno-missing-field-initializers") - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_have("-Wall") - .must_have("-Wextra"); -} - -#[test] -fn gnu_warnings_overridable() { - let test = Test::gnu(); - test.gcc() - .warnings(true) - .flag("-Wno-missing-field-initializers") - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_have_in_order("-Wall", "-Wno-missing-field-initializers"); -} - -#[test] -fn gnu_x86_64() { - for vendor in &["unknown-linux-gnu", "apple-darwin"] { - let target = format!("x86_64-{}", vendor); - let test = Test::gnu(); - test.gcc() - .target(&target) - .host(&target) - .file("foo.c") - .compile("foo"); - - test.cmd(0) - .must_have("-fPIC") - .must_have("-m64"); - } -} - -#[test] -fn gnu_x86_64_no_pic() { - for vendor in &["unknown-linux-gnu", "apple-darwin"] { - let target = format!("x86_64-{}", vendor); - let test = Test::gnu(); - test.gcc() - .pic(false) - .target(&target) - .host(&target) - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_not_have("-fPIC"); - } -} - -#[test] -fn gnu_i686() { - for vendor in &["unknown-linux-gnu", "apple-darwin"] { - let target = format!("i686-{}", vendor); - let test = Test::gnu(); - test.gcc() - .target(&target) - .host(&target) - .file("foo.c") - .compile("foo"); - - test.cmd(0) - .must_have("-m32"); - } -} - -#[test] -fn gnu_i686_pic() { - for vendor in &["unknown-linux-gnu", "apple-darwin"] { - let target = format!("i686-{}", vendor); - let test = Test::gnu(); - test.gcc() - .pic(true) - .target(&target) - .host(&target) - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_have("-fPIC"); - } -} - -#[test] -fn gnu_set_stdlib() { - let test = Test::gnu(); - test.gcc() - .cpp_set_stdlib(Some("foo")) - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_not_have("-stdlib=foo"); -} - -#[test] -fn gnu_include() { - let test = Test::gnu(); - test.gcc() - .include("foo/bar") - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_have("-I").must_have("foo/bar"); -} - -#[test] -fn gnu_define() { - let test = Test::gnu(); - test.gcc() - .define("FOO", "bar") - .define("BAR", None) - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_have("-DFOO=bar").must_have("-DBAR"); -} - -#[test] -fn gnu_compile_assembly() { - let test = Test::gnu(); - test.gcc() - .file("foo.S") - .compile("foo"); - test.cmd(0).must_have("foo.S"); -} - -#[test] -fn gnu_shared() { - let test = Test::gnu(); - test.gcc() - .file("foo.c") - .shared_flag(true) - .static_flag(false) - .compile("foo"); - - test.cmd(0) - .must_have("-shared") - .must_not_have("-static"); -} - -#[test] -fn gnu_flag_if_supported() { - if cfg!(windows) { - return - } - let test = Test::gnu(); - test.gcc() - .file("foo.c") - .flag_if_supported("-Wall") - .flag_if_supported("-Wflag-does-not-exist") - .flag_if_supported("-std=c++11") - .compile("foo"); - - test.cmd(0) - .must_have("-Wall") - .must_not_have("-Wflag-does-not-exist") - .must_not_have("-std=c++11"); -} - -#[test] -fn gnu_flag_if_supported_cpp() { - if cfg!(windows) { - return - } - let test = Test::gnu(); - test.gcc() - .cpp(true) - .file("foo.cpp") - .flag_if_supported("-std=c++11") - .compile("foo"); - - test.cmd(0) - .must_have("-std=c++11"); -} - -#[test] -fn gnu_static() { - let test = Test::gnu(); - test.gcc() - .file("foo.c") - .shared_flag(false) - .static_flag(true) - .compile("foo"); - - test.cmd(0) - .must_have("-static") - .must_not_have("-shared"); -} - -#[test] -fn msvc_smoke() { - let test = Test::msvc(); - test.gcc() - .file("foo.c") - .compile("foo"); - - test.cmd(0) - .must_have("/O2") - .must_have("foo.c") - .must_not_have("/Z7") - .must_have("/c") - .must_have("/MD"); - test.cmd(1).must_have(test.td.path().join("foo.o")); -} - -#[test] -fn msvc_opt_level_0() { - let test = Test::msvc(); - test.gcc() - .opt_level(0) - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_not_have("/O2"); -} - -#[test] -fn msvc_debug() { - let test = Test::msvc(); - test.gcc() - .debug(true) - .file("foo.c") - .compile("foo"); - test.cmd(0).must_have("/Z7"); -} - -#[test] -fn msvc_include() { - let test = Test::msvc(); - test.gcc() - .include("foo/bar") - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_have("/I").must_have("foo/bar"); -} - -#[test] -fn msvc_define() { - let test = Test::msvc(); - test.gcc() - .define("FOO", "bar") - .define("BAR", None) - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_have("/DFOO=bar").must_have("/DBAR"); -} - -#[test] -fn msvc_static_crt() { - let test = Test::msvc(); - test.gcc() - .static_crt(true) - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_have("/MT"); -} - -#[test] -fn msvc_no_static_crt() { - let test = Test::msvc(); - test.gcc() - .static_crt(false) - .file("foo.c") - .compile("foo"); - - test.cmd(0).must_have("/MD"); -} diff -Nru cargo-0.25.0/vendor/cc-1.0.4/.travis.yml cargo-0.26.0/vendor/cc-1.0.4/.travis.yml --- cargo-0.25.0/vendor/cc-1.0.4/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cc-1.0.4/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,53 +0,0 @@ -language: rust -sudo: false - -matrix: - include: - - rust: 1.13.0 - install: - script: cargo build - - rust: stable - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 - - rust: stable - env: TARGET=i686-unknown-linux-gnu - - os: osx - env: TARGET=x86_64-apple-darwin NO_ADD=1 - - rust: beta - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 - - rust: nightly - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 - - - rust: nightly - before_script: - - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH - install: - script: - - cargo doc --no-deps --all-features - after_success: - - travis-cargo --only nightly doc-upload - -install: - - if [ -z "$NO_ADD" ]; then rustup target add $TARGET; fi - -script: - - cargo build --verbose - - cargo test --verbose - - cargo test --verbose --features parallel - - cargo test --manifest-path cc-test/Cargo.toml --target $TARGET - - cargo test --manifest-path cc-test/Cargo.toml --target $TARGET --features parallel - - cargo test --manifest-path cc-test/Cargo.toml --target $TARGET --release - - cargo doc - - cargo clean && cargo build - - rustdoc --test README.md -L target/debug -L target/debug/deps - -env: - global: - secure: "CBtqrudgE0PS8x3kTr44jKbC2D4nfnmdYVecooNm0qnER4B4TSvZpZSQoCgKK6k4BYQuOSyFTOwYx6M79w39ZMOgyCP9ytB+tyMWL0/+ZuUQL04yVg4M5vd3oJMkOaXbvG56ncgPyFrseY+FPDg+mXAzvJk/nily37YXjkQj2D0=" - -notifications: - email: - on_success: never -addons: - apt: - packages: - - g++-multilib diff -Nru cargo-0.25.0/vendor/cmake-0.1.29/.cargo-checksum.json cargo-0.26.0/vendor/cmake-0.1.29/.cargo-checksum.json --- cargo-0.25.0/vendor/cmake-0.1.29/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.29/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"56d741ea7a69e577f6d06b36b7dff4738f680593dc27a701ffa8506b73ce28bb"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/cmake-0.1.29/Cargo.toml cargo-0.26.0/vendor/cmake-0.1.29/Cargo.toml --- cargo-0.25.0/vendor/cmake-0.1.29/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.29/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "cmake" -version = "0.1.29" -authors = ["Alex Crichton "] -description = "A build dependency for running `cmake` to build a native library\n" -homepage = "https://github.com/alexcrichton/cmake-rs" -documentation = "http://alexcrichton.com/cmake-rs" -readme = "README.md" -keywords = ["build-dependencies"] -license = "MIT/Apache-2.0" -repository = "https://github.com/alexcrichton/cmake-rs" -[dependencies.cc] -version = "1.0" diff -Nru cargo-0.25.0/vendor/cmake-0.1.29/LICENSE-APACHE cargo-0.26.0/vendor/cmake-0.1.29/LICENSE-APACHE --- cargo-0.25.0/vendor/cmake-0.1.29/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.29/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/cmake-0.1.29/LICENSE-MIT cargo-0.26.0/vendor/cmake-0.1.29/LICENSE-MIT --- cargo-0.25.0/vendor/cmake-0.1.29/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.29/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 Alex Crichton - -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. diff -Nru cargo-0.25.0/vendor/cmake-0.1.29/README.md cargo-0.26.0/vendor/cmake-0.1.29/README.md --- cargo-0.25.0/vendor/cmake-0.1.29/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.29/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -# cmake - -[![Build Status](https://travis-ci.org/alexcrichton/cmake-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/cmake-rs) - -[Documentation](http://alexcrichton.com/cmake-rs) - -A build dependency for running the `cmake` build tool to compile a native -library. - -```toml -# Cargo.toml -[build-dependencies] -cmake = "0.2" -``` - -The CMake executable is assumed to be `cmake` unless the `CMAKE` -environmental variable is set. - -# License - -This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/cmake-0.1.29/src/lib.rs cargo-0.26.0/vendor/cmake-0.1.29/src/lib.rs --- cargo-0.25.0/vendor/cmake-0.1.29/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.29/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,633 +0,0 @@ -//! A build dependency for running `cmake` to build a native library -//! -//! This crate provides some necessary boilerplate and shim support for running -//! the system `cmake` command to build a native library. It will add -//! appropriate cflags for building code to link into Rust, handle cross -//! compilation, and use the necessary generator for the platform being -//! targeted. -//! -//! The builder-style configuration allows for various variables and such to be -//! passed down into the build as well. -//! -//! ## Installation -//! -//! Add this to your `Cargo.toml`: -//! -//! ```toml -//! [build-dependencies] -//! cmake = "0.1" -//! ``` -//! -//! ## Examples -//! -//! ```no_run -//! use cmake; -//! -//! // Builds the project in the directory located in `libfoo`, installing it -//! // into $OUT_DIR -//! let dst = cmake::build("libfoo"); -//! -//! println!("cargo:rustc-link-search=native={}", dst.display()); -//! println!("cargo:rustc-link-lib=static=foo"); -//! ``` -//! -//! ```no_run -//! use cmake::Config; -//! -//! let dst = Config::new("libfoo") -//! .define("FOO", "BAR") -//! .cflag("-foo") -//! .build(); -//! println!("cargo:rustc-link-search=native={}", dst.display()); -//! println!("cargo:rustc-link-lib=static=foo"); -//! ``` - -#![deny(missing_docs)] - -extern crate cc; - -use std::env; -use std::ffi::{OsString, OsStr}; -use std::fs::{self, File}; -use std::io::ErrorKind; -use std::io::prelude::*; -use std::path::{Path, PathBuf}; -use std::process::Command; - -/// Builder style configuration for a pending CMake build. -pub struct Config { - path: PathBuf, - generator: Option, - cflags: OsString, - cxxflags: OsString, - defines: Vec<(OsString, OsString)>, - deps: Vec, - target: Option, - host: Option, - out_dir: Option, - profile: Option, - build_args: Vec, - cmake_target: Option, - env: Vec<(OsString, OsString)>, - static_crt: Option, - uses_cxx11: bool, -} - -/// Builds the native library rooted at `path` with the default cmake options. -/// This will return the directory in which the library was installed. -/// -/// # Examples -/// -/// ```no_run -/// use cmake; -/// -/// // Builds the project in the directory located in `libfoo`, installing it -/// // into $OUT_DIR -/// let dst = cmake::build("libfoo"); -/// -/// println!("cargo:rustc-link-search=native={}", dst.display()); -/// println!("cargo:rustc-link-lib=static=foo"); -/// ``` -/// -pub fn build>(path: P) -> PathBuf { - Config::new(path.as_ref()).build() -} - -impl Config { - /// Creates a new blank set of configuration to build the project specified - /// at the path `path`. - pub fn new>(path: P) -> Config { - Config { - path: env::current_dir().unwrap().join(path), - generator: None, - cflags: OsString::new(), - cxxflags: OsString::new(), - defines: Vec::new(), - deps: Vec::new(), - profile: None, - out_dir: None, - target: None, - host: None, - build_args: Vec::new(), - cmake_target: None, - env: Vec::new(), - static_crt: None, - uses_cxx11: false - } - } - - /// Sets the build-tool generator (`-G`) for this compilation. - pub fn generator>(&mut self, generator: T) -> &mut Config { - self.generator = Some(generator.as_ref().to_owned()); - self - } - - /// Adds a custom flag to pass down to the C compiler, supplementing those - /// that this library already passes. - pub fn cflag>(&mut self, flag: P) -> &mut Config { - self.cflags.push(" "); - self.cflags.push(flag.as_ref()); - self - } - - /// Adds a custom flag to pass down to the C++ compiler, supplementing those - /// that this library already passes. - pub fn cxxflag>(&mut self, flag: P) -> &mut Config { - self.cxxflags.push(" "); - self.cxxflags.push(flag.as_ref()); - self - } - - /// Adds a new `-D` flag to pass to cmake during the generation step. - pub fn define(&mut self, k: K, v: V) -> &mut Config - where K: AsRef, V: AsRef - { - self.defines.push((k.as_ref().to_owned(), v.as_ref().to_owned())); - self - } - - /// Registers a dependency for this compilation on the native library built - /// by Cargo previously. - /// - /// This registration will modify the `CMAKE_PREFIX_PATH` environment - /// variable for the build system generation step. - pub fn register_dep(&mut self, dep: &str) -> &mut Config { - self.deps.push(dep.to_string()); - self - } - - /// Sets the target triple for this compilation. - /// - /// This is automatically scraped from `$TARGET` which is set for Cargo - /// build scripts so it's not necessary to call this from a build script. - pub fn target(&mut self, target: &str) -> &mut Config { - self.target = Some(target.to_string()); - self - } - - /// Sets the host triple for this compilation. - /// - /// This is automatically scraped from `$HOST` which is set for Cargo - /// build scripts so it's not necessary to call this from a build script. - pub fn host(&mut self, host: &str) -> &mut Config { - self.host = Some(host.to_string()); - self - } - - /// Sets the output directory for this compilation. - /// - /// This is automatically scraped from `$OUT_DIR` which is set for Cargo - /// build scripts so it's not necessary to call this from a build script. - pub fn out_dir>(&mut self, out: P) -> &mut Config { - self.out_dir = Some(out.as_ref().to_path_buf()); - self - } - - /// Sets the profile for this compilation. - /// - /// This is automatically scraped from `$PROFILE` which is set for Cargo - /// build scripts so it's not necessary to call this from a build script. - pub fn profile(&mut self, profile: &str) -> &mut Config { - self.profile = Some(profile.to_string()); - self - } - - /// Configures whether the /MT flag or the /MD flag will be passed to msvc build tools. - /// - /// This option defaults to `false`, and affect only msvc targets. - pub fn static_crt(&mut self, static_crt: bool) -> &mut Config { - self.static_crt = Some(static_crt); - self - } - - /// Add an argument to the final `cmake` build step - pub fn build_arg>(&mut self, arg: A) -> &mut Config { - self.build_args.push(arg.as_ref().to_owned()); - self - } - - /// Configure an environment variable for the `cmake` processes spawned by - /// this crate in the `build` step. - pub fn env(&mut self, key: K, value: V) -> &mut Config - where K: AsRef, - V: AsRef, - { - self.env.push((key.as_ref().to_owned(), value.as_ref().to_owned())); - self - } - - /// Sets the build target for the final `cmake` build step, this will - /// default to "install" if not specified. - pub fn build_target(&mut self, target: &str) -> &mut Config { - self.cmake_target = Some(target.to_string()); - self - } - - /// Alters the default target triple on OSX to ensure that c++11 is - /// available. Does not change the target triple if it is explicitly - /// specified. - /// - /// This does not otherwise affect any CXX flags, i.e. it does not set - /// -std=c++11 or -stdlib=libc++. - pub fn uses_cxx11(&mut self) -> &mut Config { - self.uses_cxx11 = true; - self - } - - /// Run this configuration, compiling the library with all the configured - /// options. - /// - /// This will run both the build system generator command as well as the - /// command to build the library. - pub fn build(&mut self) -> PathBuf { - let target = match self.target.clone() { - Some(t) => t, - None => { - let mut t = getenv_unwrap("TARGET"); - if t.ends_with("-darwin") && self.uses_cxx11 { - t = t + "11" - } - t - } - }; - let host = self.host.clone().unwrap_or_else(|| { - getenv_unwrap("HOST") - }); - let msvc = target.contains("msvc"); - let mut c_cfg = cc::Build::new(); - c_cfg.cargo_metadata(false) - .opt_level(0) - .debug(false) - .target(&target) - .warnings(false) - .host(&host); - let mut cxx_cfg = cc::Build::new(); - cxx_cfg.cargo_metadata(false) - .cpp(true) - .opt_level(0) - .debug(false) - .target(&target) - .warnings(false) - .host(&host); - if let Some(static_crt) = self.static_crt { - c_cfg.static_crt(static_crt); - cxx_cfg.static_crt(static_crt); - } - let c_compiler = c_cfg.get_compiler(); - let cxx_compiler = cxx_cfg.get_compiler(); - - let dst = self.out_dir.clone().unwrap_or_else(|| { - PathBuf::from(getenv_unwrap("OUT_DIR")) - }); - let build = dst.join("build"); - self.maybe_clear(&build); - let _ = fs::create_dir(&build); - - // Add all our dependencies to our cmake paths - let mut cmake_prefix_path = Vec::new(); - for dep in &self.deps { - if let Some(root) = env::var_os(&format!("DEP_{}_ROOT", dep)) { - cmake_prefix_path.push(PathBuf::from(root)); - } - } - let system_prefix = env::var_os("CMAKE_PREFIX_PATH") - .unwrap_or(OsString::new()); - cmake_prefix_path.extend(env::split_paths(&system_prefix) - .map(|s| s.to_owned())); - let cmake_prefix_path = env::join_paths(&cmake_prefix_path).unwrap(); - - // Build up the first cmake command to build the build system. - let executable = env::var("CMAKE").unwrap_or("cmake".to_owned()); - let mut cmd = Command::new(executable); - cmd.arg(&self.path) - .current_dir(&build); - if target.contains("windows-gnu") { - if host.contains("windows") { - // On MinGW we need to coerce cmake to not generate a visual - // studio build system but instead use makefiles that MinGW can - // use to build. - if self.generator.is_none() { - cmd.arg("-G").arg("MSYS Makefiles"); - } - } else { - // If we're cross compiling onto windows, then set some - // variables which will hopefully get things to succeed. Some - // systems may need the `windres` or `dlltool` variables set, so - // set them if possible. - if !self.defined("CMAKE_SYSTEM_NAME") { - cmd.arg("-DCMAKE_SYSTEM_NAME=Windows"); - } - if !self.defined("CMAKE_RC_COMPILER") { - let exe = find_exe(c_compiler.path()); - if let Some(name) = exe.file_name().unwrap().to_str() { - let name = name.replace("gcc", "windres"); - let windres = exe.with_file_name(name); - if windres.is_file() { - let mut arg = OsString::from("-DCMAKE_RC_COMPILER="); - arg.push(&windres); - cmd.arg(arg); - } - } - } - } - } else if msvc { - // If we're on MSVC we need to be sure to use the right generator or - // otherwise we won't get 32/64 bit correct automatically. - // This also guarantees that NMake generator isn't chosen implicitly. - if self.generator.is_none() { - cmd.arg("-G").arg(self.visual_studio_generator(&target)); - } - } else if target.contains("redox") { - if !self.defined("CMAKE_SYSTEM_NAME") { - cmd.arg("-DCMAKE_SYSTEM_NAME=Generic"); - } - } - let mut is_ninja = false; - if let Some(ref generator) = self.generator { - cmd.arg("-G").arg(generator); - is_ninja = generator.to_string_lossy().contains("Ninja"); - } - let profile = self.profile.clone().unwrap_or_else(|| { - match &getenv_unwrap("PROFILE")[..] { - "bench" | "release" => "Release", - _ => "Debug", - }.to_string() - }); - for &(ref k, ref v) in &self.defines { - let mut os = OsString::from("-D"); - os.push(k); - os.push("="); - os.push(v); - cmd.arg(os); - } - - if !self.defined("CMAKE_INSTALL_PREFIX") { - let mut dstflag = OsString::from("-DCMAKE_INSTALL_PREFIX="); - dstflag.push(&dst); - cmd.arg(dstflag); - } - - let build_type = self.defines.iter().find(|&&(ref a, _)| { - a == "CMAKE_BUILD_TYPE" - }).map(|x| x.1.to_str().unwrap()).unwrap_or(&profile); - let build_type_upcase = build_type.chars() - .flat_map(|c| c.to_uppercase()) - .collect::(); - - { - // let cmake deal with optimization/debuginfo - let skip_arg = |arg: &OsStr| { - match arg.to_str() { - Some(s) => { - s.starts_with("-O") || s.starts_with("/O") || s == "-g" - } - None => false, - } - }; - let mut set_compiler = |kind: &str, - compiler: &cc::Tool, - extra: &OsString| { - let flag_var = format!("CMAKE_{}_FLAGS", kind); - let tool_var = format!("CMAKE_{}_COMPILER", kind); - if !self.defined(&flag_var) { - let mut flagsflag = OsString::from("-D"); - flagsflag.push(&flag_var); - flagsflag.push("="); - flagsflag.push(extra); - for arg in compiler.args() { - if skip_arg(arg) { - continue - } - flagsflag.push(" "); - flagsflag.push(arg); - } - cmd.arg(flagsflag); - } - - // The visual studio generator apparently doesn't respect - // `CMAKE_C_FLAGS` but does respect `CMAKE_C_FLAGS_RELEASE` and - // such. We need to communicate /MD vs /MT, so set those vars - // here. - // - // Note that for other generators, though, this *overrides* - // things like the optimization flags, which is bad. - if self.generator.is_none() && msvc { - let flag_var_alt = format!("CMAKE_{}_FLAGS_{}", kind, - build_type_upcase); - if !self.defined(&flag_var_alt) { - let mut flagsflag = OsString::from("-D"); - flagsflag.push(&flag_var_alt); - flagsflag.push("="); - flagsflag.push(extra); - for arg in compiler.args() { - if skip_arg(arg) { - continue - } - flagsflag.push(" "); - flagsflag.push(arg); - } - cmd.arg(flagsflag); - } - } - - // Apparently cmake likes to have an absolute path to the - // compiler as otherwise it sometimes thinks that this variable - // changed as it thinks the found compiler, /usr/bin/cc, - // differs from the specified compiler, cc. Not entirely sure - // what's up, but at least this means cmake doesn't get - // confused? - // - // Also specify this on Windows only if we use MSVC with Ninja, - // as it's not needed for MSVC with Visual Studio generators and - // for MinGW it doesn't really vary. - if !self.defined("CMAKE_TOOLCHAIN_FILE") - && !self.defined(&tool_var) - && (env::consts::FAMILY != "windows" || (msvc && is_ninja)) { - let mut ccompiler = OsString::from("-D"); - ccompiler.push(&tool_var); - ccompiler.push("="); - ccompiler.push(find_exe(compiler.path())); - #[cfg(windows)] { - // CMake doesn't like unescaped `\`s in compiler paths - // so we either have to escape them or replace with `/`s. - use std::os::windows::ffi::{OsStrExt, OsStringExt}; - let wchars = ccompiler.encode_wide().map(|wchar| { - if wchar == b'\\' as u16 { '/' as u16 } else { wchar } - }).collect::>(); - ccompiler = OsString::from_wide(&wchars); - } - cmd.arg(ccompiler); - } - }; - - set_compiler("C", &c_compiler, &self.cflags); - set_compiler("CXX", &cxx_compiler, &self.cxxflags); - } - - if !self.defined("CMAKE_BUILD_TYPE") { - cmd.arg(&format!("-DCMAKE_BUILD_TYPE={}", profile)); - } - - if !self.defined("CMAKE_TOOLCHAIN_FILE") { - if let Ok(s) = env::var("CMAKE_TOOLCHAIN_FILE") { - cmd.arg(&format!("-DCMAKE_TOOLCHAIN_FILE={}", s)); - } - } - - for &(ref k, ref v) in c_compiler.env().iter().chain(&self.env) { - cmd.env(k, v); - } - - run(cmd.env("CMAKE_PREFIX_PATH", cmake_prefix_path), "cmake"); - - let mut makeflags = None; - let mut parallel_args = Vec::new(); - if let Ok(s) = env::var("NUM_JOBS") { - match self.generator.as_ref().map(|g| g.to_string_lossy()) { - Some(ref g) if g.contains("Ninja") => { - parallel_args.push(format!("-j{}", s)); - } - Some(ref g) if g.contains("Visual Studio") => { - parallel_args.push(format!("/m:{}", s)); - } - Some(ref g) if g.contains("NMake") => { - // NMake creates `Makefile`s, but doesn't understand `-jN`. - } - _ if fs::metadata(&dst.join("build/Makefile")).is_ok() => { - match env::var_os("CARGO_MAKEFLAGS") { - // Only do this on non-windows as we could actually be - // invoking make instead of mingw32-make which doesn't - // work with our jobserver - Some(ref s) if !cfg!(windows) => makeflags = Some(s.clone()), - - // This looks like `make`, let's hope it understands `-jN`. - _ => parallel_args.push(format!("-j{}", s)), - } - } - _ => {} - } - } - - // And build! - let target = self.cmake_target.clone().unwrap_or("install".to_string()); - let mut cmd = Command::new("cmake"); - for &(ref k, ref v) in c_compiler.env().iter().chain(&self.env) { - cmd.env(k, v); - } - if let Some(flags) = makeflags { - cmd.env("MAKEFLAGS", flags); - } - run(cmd.arg("--build").arg(".") - .arg("--target").arg(target) - .arg("--config").arg(&profile) - .arg("--").args(&self.build_args) - .args(¶llel_args) - .current_dir(&build), "cmake"); - - println!("cargo:root={}", dst.display()); - return dst - } - - fn visual_studio_generator(&self, target: &str) -> String { - use cc::windows_registry::{find_vs_version, VsVers}; - - let base = match find_vs_version() { - Ok(VsVers::Vs15) => "Visual Studio 15 2017", - Ok(VsVers::Vs14) => "Visual Studio 14 2015", - Ok(VsVers::Vs12) => "Visual Studio 12 2013", - Ok(_) => panic!("Visual studio version detected but this crate \ - doesn't know how to generate cmake files for it, \ - can the `cmake` crate be updated?"), - Err(msg) => panic!(msg), - }; - if target.contains("i686") { - base.to_string() - } else if target.contains("x86_64") { - format!("{} Win64", base) - } else { - panic!("unsupported msvc target: {}", target); - } - } - - fn defined(&self, var: &str) -> bool { - self.defines.iter().any(|&(ref a, _)| a == var) - } - - // If a cmake project has previously been built (e.g. CMakeCache.txt already - // exists), then cmake will choke if the source directory for the original - // project being built has changed. Detect this situation through the - // `CMAKE_HOME_DIRECTORY` variable that cmake emits and if it doesn't match - // we blow away the build directory and start from scratch (the recommended - // solution apparently [1]). - // - // [1]: https://cmake.org/pipermail/cmake/2012-August/051545.html - fn maybe_clear(&self, dir: &Path) { - // CMake will apparently store canonicalized paths which normally - // isn't relevant to us but we canonicalize it here to ensure - // we're both checking the same thing. - let path = fs::canonicalize(&self.path).unwrap_or(self.path.clone()); - let mut f = match File::open(dir.join("CMakeCache.txt")) { - Ok(f) => f, - Err(..) => return, - }; - let mut u8contents = Vec::new(); - match f.read_to_end(&mut u8contents) { - Ok(f) => f, - Err(..) => return, - }; - let contents = String::from_utf8_lossy(&u8contents); - drop(f); - for line in contents.lines() { - if line.starts_with("CMAKE_HOME_DIRECTORY") { - let needs_cleanup = match line.split('=').next_back() { - Some(cmake_home) => { - fs::canonicalize(cmake_home) - .ok() - .map(|cmake_home| cmake_home != path) - .unwrap_or(true) - }, - None => true - }; - if needs_cleanup { - println!("detected home dir change, cleaning out entire build \ - directory"); - fs::remove_dir_all(dir).unwrap(); - } - break - } - } - } -} - -fn run(cmd: &mut Command, program: &str) { - println!("running: {:?}", cmd); - let status = match cmd.status() { - Ok(status) => status, - Err(ref e) if e.kind() == ErrorKind::NotFound => { - fail(&format!("failed to execute command: {}\nis `{}` not installed?", - e, program)); - } - Err(e) => fail(&format!("failed to execute command: {}", e)), - }; - if !status.success() { - fail(&format!("command did not execute successfully, got: {}", status)); - } -} - -fn find_exe(path: &Path) -> PathBuf { - env::split_paths(&env::var_os("PATH").unwrap_or(OsString::new())) - .map(|p| p.join(path)) - .find(|p| fs::metadata(p).is_ok()) - .unwrap_or(path.to_owned()) -} - -fn getenv_unwrap(v: &str) -> String { - match env::var(v) { - Ok(s) => s, - Err(..) => fail(&format!("environment variable `{}` not defined", v)), - } -} - -fn fail(s: &str) -> ! { - panic!("\n{}\n\nbuild script failed, must exit now", s) -} diff -Nru cargo-0.25.0/vendor/cmake-0.1.29/.travis.yml cargo-0.26.0/vendor/cmake-0.1.29/.travis.yml --- cargo-0.25.0/vendor/cmake-0.1.29/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.29/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -language: rust -rust: - - stable - - beta - - nightly -sudo: false -before_script: - - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH -script: - - cargo test --verbose - - cargo doc --no-deps -after_success: - - travis-cargo --only nightly doc-upload -env: - global: - secure: "IA467qqr1j0BpyTqG6hO8Kpt+EUDEjO1pBVhu4+L76/dygkQIwROgqdT7uXZqBPMjU6Rbi0wzGXXHJjbCWVTCjh7U/Q0bK2svtR8DKtM0o1Un/YftSUFt2p/WoiJ9PrkUjKh1rHuoyijpUqAls0JfIz8OdC45egT2SWDufljo+s=" - -notifications: - email: - on_success: never diff -Nru cargo-0.25.0/vendor/cmake-0.1.30/.cargo-checksum.json cargo-0.26.0/vendor/cmake-0.1.30/.cargo-checksum.json --- cargo-0.25.0/vendor/cmake-0.1.30/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.30/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"5cf678ceebedde428000cb3a34465cf3606d1a48da17014948a916deac39da7c"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/cmake-0.1.30/Cargo.toml cargo-0.26.0/vendor/cmake-0.1.30/Cargo.toml --- cargo-0.25.0/vendor/cmake-0.1.30/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.30/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "cmake" +version = "0.1.30" +authors = ["Alex Crichton "] +description = "A build dependency for running `cmake` to build a native library\n" +homepage = "https://github.com/alexcrichton/cmake-rs" +documentation = "http://alexcrichton.com/cmake-rs" +readme = "README.md" +keywords = ["build-dependencies"] +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/cmake-rs" +[dependencies.cc] +version = "1.0" diff -Nru cargo-0.25.0/vendor/cmake-0.1.30/LICENSE-APACHE cargo-0.26.0/vendor/cmake-0.1.30/LICENSE-APACHE --- cargo-0.25.0/vendor/cmake-0.1.30/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.30/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/cmake-0.1.30/LICENSE-MIT cargo-0.26.0/vendor/cmake-0.1.30/LICENSE-MIT --- cargo-0.25.0/vendor/cmake-0.1.30/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.30/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +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. diff -Nru cargo-0.25.0/vendor/cmake-0.1.30/README.md cargo-0.26.0/vendor/cmake-0.1.30/README.md --- cargo-0.25.0/vendor/cmake-0.1.30/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.30/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,34 @@ +# cmake + +[![Build Status](https://travis-ci.org/alexcrichton/cmake-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/cmake-rs) + +[Documentation](http://alexcrichton.com/cmake-rs) + +A build dependency for running the `cmake` build tool to compile a native +library. + +```toml +# Cargo.toml +[build-dependencies] +cmake = "0.2" +``` + +The CMake executable is assumed to be `cmake` unless the `CMAKE` +environmental variable is set. + +# License + +This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/cmake-0.1.30/src/lib.rs cargo-0.26.0/vendor/cmake-0.1.30/src/lib.rs --- cargo-0.25.0/vendor/cmake-0.1.30/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.30/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,644 @@ +//! A build dependency for running `cmake` to build a native library +//! +//! This crate provides some necessary boilerplate and shim support for running +//! the system `cmake` command to build a native library. It will add +//! appropriate cflags for building code to link into Rust, handle cross +//! compilation, and use the necessary generator for the platform being +//! targeted. +//! +//! The builder-style configuration allows for various variables and such to be +//! passed down into the build as well. +//! +//! ## Installation +//! +//! Add this to your `Cargo.toml`: +//! +//! ```toml +//! [build-dependencies] +//! cmake = "0.1" +//! ``` +//! +//! ## Examples +//! +//! ```no_run +//! use cmake; +//! +//! // Builds the project in the directory located in `libfoo`, installing it +//! // into $OUT_DIR +//! let dst = cmake::build("libfoo"); +//! +//! println!("cargo:rustc-link-search=native={}", dst.display()); +//! println!("cargo:rustc-link-lib=static=foo"); +//! ``` +//! +//! ```no_run +//! use cmake::Config; +//! +//! let dst = Config::new("libfoo") +//! .define("FOO", "BAR") +//! .cflag("-foo") +//! .build(); +//! println!("cargo:rustc-link-search=native={}", dst.display()); +//! println!("cargo:rustc-link-lib=static=foo"); +//! ``` + +#![deny(missing_docs)] + +extern crate cc; + +use std::env; +use std::ffi::{OsString, OsStr}; +use std::fs::{self, File}; +use std::io::ErrorKind; +use std::io::prelude::*; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Builder style configuration for a pending CMake build. +pub struct Config { + path: PathBuf, + generator: Option, + cflags: OsString, + cxxflags: OsString, + defines: Vec<(OsString, OsString)>, + deps: Vec, + target: Option, + host: Option, + out_dir: Option, + profile: Option, + build_args: Vec, + cmake_target: Option, + env: Vec<(OsString, OsString)>, + static_crt: Option, + uses_cxx11: bool, +} + +/// Builds the native library rooted at `path` with the default cmake options. +/// This will return the directory in which the library was installed. +/// +/// # Examples +/// +/// ```no_run +/// use cmake; +/// +/// // Builds the project in the directory located in `libfoo`, installing it +/// // into $OUT_DIR +/// let dst = cmake::build("libfoo"); +/// +/// println!("cargo:rustc-link-search=native={}", dst.display()); +/// println!("cargo:rustc-link-lib=static=foo"); +/// ``` +/// +pub fn build>(path: P) -> PathBuf { + Config::new(path.as_ref()).build() +} + +impl Config { + /// Creates a new blank set of configuration to build the project specified + /// at the path `path`. + pub fn new>(path: P) -> Config { + Config { + path: env::current_dir().unwrap().join(path), + generator: None, + cflags: OsString::new(), + cxxflags: OsString::new(), + defines: Vec::new(), + deps: Vec::new(), + profile: None, + out_dir: None, + target: None, + host: None, + build_args: Vec::new(), + cmake_target: None, + env: Vec::new(), + static_crt: None, + uses_cxx11: false + } + } + + /// Sets the build-tool generator (`-G`) for this compilation. + pub fn generator>(&mut self, generator: T) -> &mut Config { + self.generator = Some(generator.as_ref().to_owned()); + self + } + + /// Adds a custom flag to pass down to the C compiler, supplementing those + /// that this library already passes. + pub fn cflag>(&mut self, flag: P) -> &mut Config { + self.cflags.push(" "); + self.cflags.push(flag.as_ref()); + self + } + + /// Adds a custom flag to pass down to the C++ compiler, supplementing those + /// that this library already passes. + pub fn cxxflag>(&mut self, flag: P) -> &mut Config { + self.cxxflags.push(" "); + self.cxxflags.push(flag.as_ref()); + self + } + + /// Adds a new `-D` flag to pass to cmake during the generation step. + pub fn define(&mut self, k: K, v: V) -> &mut Config + where K: AsRef, V: AsRef + { + self.defines.push((k.as_ref().to_owned(), v.as_ref().to_owned())); + self + } + + /// Registers a dependency for this compilation on the native library built + /// by Cargo previously. + /// + /// This registration will modify the `CMAKE_PREFIX_PATH` environment + /// variable for the build system generation step. + pub fn register_dep(&mut self, dep: &str) -> &mut Config { + self.deps.push(dep.to_string()); + self + } + + /// Sets the target triple for this compilation. + /// + /// This is automatically scraped from `$TARGET` which is set for Cargo + /// build scripts so it's not necessary to call this from a build script. + pub fn target(&mut self, target: &str) -> &mut Config { + self.target = Some(target.to_string()); + self + } + + /// Sets the host triple for this compilation. + /// + /// This is automatically scraped from `$HOST` which is set for Cargo + /// build scripts so it's not necessary to call this from a build script. + pub fn host(&mut self, host: &str) -> &mut Config { + self.host = Some(host.to_string()); + self + } + + /// Sets the output directory for this compilation. + /// + /// This is automatically scraped from `$OUT_DIR` which is set for Cargo + /// build scripts so it's not necessary to call this from a build script. + pub fn out_dir>(&mut self, out: P) -> &mut Config { + self.out_dir = Some(out.as_ref().to_path_buf()); + self + } + + /// Sets the profile for this compilation. + /// + /// This is automatically scraped from `$PROFILE` which is set for Cargo + /// build scripts so it's not necessary to call this from a build script. + pub fn profile(&mut self, profile: &str) -> &mut Config { + self.profile = Some(profile.to_string()); + self + } + + /// Configures whether the /MT flag or the /MD flag will be passed to msvc build tools. + /// + /// This option defaults to `false`, and affect only msvc targets. + pub fn static_crt(&mut self, static_crt: bool) -> &mut Config { + self.static_crt = Some(static_crt); + self + } + + /// Add an argument to the final `cmake` build step + pub fn build_arg>(&mut self, arg: A) -> &mut Config { + self.build_args.push(arg.as_ref().to_owned()); + self + } + + /// Configure an environment variable for the `cmake` processes spawned by + /// this crate in the `build` step. + pub fn env(&mut self, key: K, value: V) -> &mut Config + where K: AsRef, + V: AsRef, + { + self.env.push((key.as_ref().to_owned(), value.as_ref().to_owned())); + self + } + + /// Sets the build target for the final `cmake` build step, this will + /// default to "install" if not specified. + pub fn build_target(&mut self, target: &str) -> &mut Config { + self.cmake_target = Some(target.to_string()); + self + } + + /// Alters the default target triple on OSX to ensure that c++11 is + /// available. Does not change the target triple if it is explicitly + /// specified. + /// + /// This does not otherwise affect any CXX flags, i.e. it does not set + /// -std=c++11 or -stdlib=libc++. + pub fn uses_cxx11(&mut self) -> &mut Config { + self.uses_cxx11 = true; + self + } + + /// Run this configuration, compiling the library with all the configured + /// options. + /// + /// This will run both the build system generator command as well as the + /// command to build the library. + pub fn build(&mut self) -> PathBuf { + let target = match self.target.clone() { + Some(t) => t, + None => { + let mut t = getenv_unwrap("TARGET"); + if t.ends_with("-darwin") && self.uses_cxx11 { + t = t + "11" + } + t + } + }; + let host = self.host.clone().unwrap_or_else(|| { + getenv_unwrap("HOST") + }); + let msvc = target.contains("msvc"); + let mut c_cfg = cc::Build::new(); + c_cfg.cargo_metadata(false) + .opt_level(0) + .debug(false) + .target(&target) + .warnings(false) + .host(&host); + let mut cxx_cfg = cc::Build::new(); + cxx_cfg.cargo_metadata(false) + .cpp(true) + .opt_level(0) + .debug(false) + .target(&target) + .warnings(false) + .host(&host); + if let Some(static_crt) = self.static_crt { + c_cfg.static_crt(static_crt); + cxx_cfg.static_crt(static_crt); + } + let c_compiler = c_cfg.get_compiler(); + let cxx_compiler = cxx_cfg.get_compiler(); + + let dst = self.out_dir.clone().unwrap_or_else(|| { + PathBuf::from(getenv_unwrap("OUT_DIR")) + }); + let build = dst.join("build"); + self.maybe_clear(&build); + let _ = fs::create_dir(&build); + + // Add all our dependencies to our cmake paths + let mut cmake_prefix_path = Vec::new(); + for dep in &self.deps { + if let Some(root) = env::var_os(&format!("DEP_{}_ROOT", dep)) { + cmake_prefix_path.push(PathBuf::from(root)); + } + } + let system_prefix = env::var_os("CMAKE_PREFIX_PATH") + .unwrap_or(OsString::new()); + cmake_prefix_path.extend(env::split_paths(&system_prefix) + .map(|s| s.to_owned())); + let cmake_prefix_path = env::join_paths(&cmake_prefix_path).unwrap(); + + // Build up the first cmake command to build the build system. + let executable = env::var("CMAKE").unwrap_or("cmake".to_owned()); + let mut cmd = Command::new(executable); + cmd.arg(&self.path) + .current_dir(&build); + if target.contains("windows-gnu") { + if host.contains("windows") { + // On MinGW we need to coerce cmake to not generate a visual + // studio build system but instead use makefiles that MinGW can + // use to build. + if self.generator.is_none() { + cmd.arg("-G").arg("MSYS Makefiles"); + } + } else { + // If we're cross compiling onto windows, then set some + // variables which will hopefully get things to succeed. Some + // systems may need the `windres` or `dlltool` variables set, so + // set them if possible. + if !self.defined("CMAKE_SYSTEM_NAME") { + cmd.arg("-DCMAKE_SYSTEM_NAME=Windows"); + } + if !self.defined("CMAKE_RC_COMPILER") { + let exe = find_exe(c_compiler.path()); + if let Some(name) = exe.file_name().unwrap().to_str() { + let name = name.replace("gcc", "windres"); + let windres = exe.with_file_name(name); + if windres.is_file() { + let mut arg = OsString::from("-DCMAKE_RC_COMPILER="); + arg.push(&windres); + cmd.arg(arg); + } + } + } + } + } else if msvc { + // If we're on MSVC we need to be sure to use the right generator or + // otherwise we won't get 32/64 bit correct automatically. + // This also guarantees that NMake generator isn't chosen implicitly. + if self.generator.is_none() { + cmd.arg("-G").arg(self.visual_studio_generator(&target)); + } + } else if target.contains("redox") { + if !self.defined("CMAKE_SYSTEM_NAME") { + cmd.arg("-DCMAKE_SYSTEM_NAME=Generic"); + } + } else if target.contains("solaris") { + if !self.defined("CMAKE_SYSTEM_NAME") { + cmd.arg("-DCMAKE_SYSTEM_NAME=SunOS"); + } + } + let mut is_ninja = false; + if let Some(ref generator) = self.generator { + cmd.arg("-G").arg(generator); + is_ninja = generator.to_string_lossy().contains("Ninja"); + } + let profile = self.profile.clone().unwrap_or_else(|| { + match &getenv_unwrap("PROFILE")[..] { + "bench" | "release" => "Release", + _ => "Debug", + }.to_string() + }); + for &(ref k, ref v) in &self.defines { + let mut os = OsString::from("-D"); + os.push(k); + os.push("="); + os.push(v); + cmd.arg(os); + } + + if !self.defined("CMAKE_INSTALL_PREFIX") { + let mut dstflag = OsString::from("-DCMAKE_INSTALL_PREFIX="); + dstflag.push(&dst); + cmd.arg(dstflag); + } + + let build_type = self.defines.iter().find(|&&(ref a, _)| { + a == "CMAKE_BUILD_TYPE" + }).map(|x| x.1.to_str().unwrap()).unwrap_or(&profile); + let build_type_upcase = build_type.chars() + .flat_map(|c| c.to_uppercase()) + .collect::(); + + { + // let cmake deal with optimization/debuginfo + let skip_arg = |arg: &OsStr| { + match arg.to_str() { + Some(s) => { + s.starts_with("-O") || s.starts_with("/O") || s == "-g" + } + None => false, + } + }; + let mut set_compiler = |kind: &str, + compiler: &cc::Tool, + extra: &OsString| { + let flag_var = format!("CMAKE_{}_FLAGS", kind); + let tool_var = format!("CMAKE_{}_COMPILER", kind); + if !self.defined(&flag_var) { + let mut flagsflag = OsString::from("-D"); + flagsflag.push(&flag_var); + flagsflag.push("="); + flagsflag.push(extra); + for arg in compiler.args() { + if skip_arg(arg) { + continue + } + flagsflag.push(" "); + flagsflag.push(arg); + } + cmd.arg(flagsflag); + } + + // The visual studio generator apparently doesn't respect + // `CMAKE_C_FLAGS` but does respect `CMAKE_C_FLAGS_RELEASE` and + // such. We need to communicate /MD vs /MT, so set those vars + // here. + // + // Note that for other generators, though, this *overrides* + // things like the optimization flags, which is bad. + if self.generator.is_none() && msvc { + let flag_var_alt = format!("CMAKE_{}_FLAGS_{}", kind, + build_type_upcase); + if !self.defined(&flag_var_alt) { + let mut flagsflag = OsString::from("-D"); + flagsflag.push(&flag_var_alt); + flagsflag.push("="); + flagsflag.push(extra); + for arg in compiler.args() { + if skip_arg(arg) { + continue + } + flagsflag.push(" "); + flagsflag.push(arg); + } + cmd.arg(flagsflag); + } + } + + // Apparently cmake likes to have an absolute path to the + // compiler as otherwise it sometimes thinks that this variable + // changed as it thinks the found compiler, /usr/bin/cc, + // differs from the specified compiler, cc. Not entirely sure + // what's up, but at least this means cmake doesn't get + // confused? + // + // Also specify this on Windows only if we use MSVC with Ninja, + // as it's not needed for MSVC with Visual Studio generators and + // for MinGW it doesn't really vary. + if !self.defined("CMAKE_TOOLCHAIN_FILE") + && !self.defined(&tool_var) + && (env::consts::FAMILY != "windows" || (msvc && is_ninja)) { + let mut ccompiler = OsString::from("-D"); + ccompiler.push(&tool_var); + ccompiler.push("="); + ccompiler.push(find_exe(compiler.path())); + #[cfg(windows)] { + // CMake doesn't like unescaped `\`s in compiler paths + // so we either have to escape them or replace with `/`s. + use std::os::windows::ffi::{OsStrExt, OsStringExt}; + let wchars = ccompiler.encode_wide().map(|wchar| { + if wchar == b'\\' as u16 { '/' as u16 } else { wchar } + }).collect::>(); + ccompiler = OsString::from_wide(&wchars); + } + cmd.arg(ccompiler); + } + }; + + set_compiler("C", &c_compiler, &self.cflags); + set_compiler("CXX", &cxx_compiler, &self.cxxflags); + } + + if !self.defined("CMAKE_BUILD_TYPE") { + cmd.arg(&format!("-DCMAKE_BUILD_TYPE={}", profile)); + } + + if !self.defined("CMAKE_TOOLCHAIN_FILE") { + if let Ok(s) = env::var("CMAKE_TOOLCHAIN_FILE") { + cmd.arg(&format!("-DCMAKE_TOOLCHAIN_FILE={}", s)); + } + } + + for &(ref k, ref v) in c_compiler.env().iter().chain(&self.env) { + cmd.env(k, v); + } + + run(cmd.env("CMAKE_PREFIX_PATH", cmake_prefix_path), "cmake"); + + let mut makeflags = None; + let mut parallel_args = Vec::new(); + if let Ok(s) = env::var("NUM_JOBS") { + match self.generator.as_ref().map(|g| g.to_string_lossy()) { + Some(ref g) if g.contains("Ninja") => { + parallel_args.push(format!("-j{}", s)); + } + Some(ref g) if g.contains("Visual Studio") => { + parallel_args.push(format!("/m:{}", s)); + } + Some(ref g) if g.contains("NMake") => { + // NMake creates `Makefile`s, but doesn't understand `-jN`. + } + _ if fs::metadata(&dst.join("build/Makefile")).is_ok() => { + match env::var_os("CARGO_MAKEFLAGS") { + // Only do this on non-windows and non-bsd + // On Windows, we could be invoking make instead of + // mingw32-make which doesn't work with our jobserver + // bsdmake also does not work with our job server + Some(ref s) if !(cfg!(windows) || + cfg!(target_os = "openbsd") || + cfg!(target_os = "netbsd") || + cfg!(target_os = "freebsd") || + cfg!(target_os = "bitrig") || + cfg!(target_os = "dragonflybsd") + ) => makeflags = Some(s.clone()), + + // This looks like `make`, let's hope it understands `-jN`. + _ => parallel_args.push(format!("-j{}", s)), + } + } + _ => {} + } + } + + // And build! + let target = self.cmake_target.clone().unwrap_or("install".to_string()); + let mut cmd = Command::new("cmake"); + for &(ref k, ref v) in c_compiler.env().iter().chain(&self.env) { + cmd.env(k, v); + } + if let Some(flags) = makeflags { + cmd.env("MAKEFLAGS", flags); + } + run(cmd.arg("--build").arg(".") + .arg("--target").arg(target) + .arg("--config").arg(&profile) + .arg("--").args(&self.build_args) + .args(¶llel_args) + .current_dir(&build), "cmake"); + + println!("cargo:root={}", dst.display()); + return dst + } + + fn visual_studio_generator(&self, target: &str) -> String { + use cc::windows_registry::{find_vs_version, VsVers}; + + let base = match find_vs_version() { + Ok(VsVers::Vs15) => "Visual Studio 15 2017", + Ok(VsVers::Vs14) => "Visual Studio 14 2015", + Ok(VsVers::Vs12) => "Visual Studio 12 2013", + Ok(_) => panic!("Visual studio version detected but this crate \ + doesn't know how to generate cmake files for it, \ + can the `cmake` crate be updated?"), + Err(msg) => panic!(msg), + }; + if target.contains("i686") { + base.to_string() + } else if target.contains("x86_64") { + format!("{} Win64", base) + } else { + panic!("unsupported msvc target: {}", target); + } + } + + fn defined(&self, var: &str) -> bool { + self.defines.iter().any(|&(ref a, _)| a == var) + } + + // If a cmake project has previously been built (e.g. CMakeCache.txt already + // exists), then cmake will choke if the source directory for the original + // project being built has changed. Detect this situation through the + // `CMAKE_HOME_DIRECTORY` variable that cmake emits and if it doesn't match + // we blow away the build directory and start from scratch (the recommended + // solution apparently [1]). + // + // [1]: https://cmake.org/pipermail/cmake/2012-August/051545.html + fn maybe_clear(&self, dir: &Path) { + // CMake will apparently store canonicalized paths which normally + // isn't relevant to us but we canonicalize it here to ensure + // we're both checking the same thing. + let path = fs::canonicalize(&self.path).unwrap_or(self.path.clone()); + let mut f = match File::open(dir.join("CMakeCache.txt")) { + Ok(f) => f, + Err(..) => return, + }; + let mut u8contents = Vec::new(); + match f.read_to_end(&mut u8contents) { + Ok(f) => f, + Err(..) => return, + }; + let contents = String::from_utf8_lossy(&u8contents); + drop(f); + for line in contents.lines() { + if line.starts_with("CMAKE_HOME_DIRECTORY") { + let needs_cleanup = match line.split('=').next_back() { + Some(cmake_home) => { + fs::canonicalize(cmake_home) + .ok() + .map(|cmake_home| cmake_home != path) + .unwrap_or(true) + }, + None => true + }; + if needs_cleanup { + println!("detected home dir change, cleaning out entire build \ + directory"); + fs::remove_dir_all(dir).unwrap(); + } + break + } + } + } +} + +fn run(cmd: &mut Command, program: &str) { + println!("running: {:?}", cmd); + let status = match cmd.status() { + Ok(status) => status, + Err(ref e) if e.kind() == ErrorKind::NotFound => { + fail(&format!("failed to execute command: {}\nis `{}` not installed?", + e, program)); + } + Err(e) => fail(&format!("failed to execute command: {}", e)), + }; + if !status.success() { + fail(&format!("command did not execute successfully, got: {}", status)); + } +} + +fn find_exe(path: &Path) -> PathBuf { + env::split_paths(&env::var_os("PATH").unwrap_or(OsString::new())) + .map(|p| p.join(path)) + .find(|p| fs::metadata(p).is_ok()) + .unwrap_or(path.to_owned()) +} + +fn getenv_unwrap(v: &str) -> String { + match env::var(v) { + Ok(s) => s, + Err(..) => fail(&format!("environment variable `{}` not defined", v)), + } +} + +fn fail(s: &str) -> ! { + panic!("\n{}\n\nbuild script failed, must exit now", s) +} diff -Nru cargo-0.25.0/vendor/cmake-0.1.30/.travis.yml cargo-0.26.0/vendor/cmake-0.1.30/.travis.yml --- cargo-0.25.0/vendor/cmake-0.1.30/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/cmake-0.1.30/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +language: rust +rust: + - stable + - beta + - nightly +sudo: false +before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH +script: + - cargo test --verbose + - cargo doc --no-deps +after_success: + - travis-cargo --only nightly doc-upload +env: + global: + secure: "IA467qqr1j0BpyTqG6hO8Kpt+EUDEjO1pBVhu4+L76/dygkQIwROgqdT7uXZqBPMjU6Rbi0wzGXXHJjbCWVTCjh7U/Q0bK2svtR8DKtM0o1Un/YftSUFt2p/WoiJ9PrkUjKh1rHuoyijpUqAls0JfIz8OdC45egT2SWDufljo+s=" + +notifications: + email: + on_success: never diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/.cargo-checksum.json cargo-0.26.0/vendor/core-foundation-0.4.6/.cargo-checksum.json --- cargo-0.25.0/vendor/core-foundation-0.4.6/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"8047f547cd6856d45b1cdd75ef8d2f21f3d0e4bf1dab0a0041b0ae9a5dda9c0e"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/Cargo.toml cargo-0.26.0/vendor/core-foundation-0.4.6/Cargo.toml --- cargo-0.25.0/vendor/core-foundation-0.4.6/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "core-foundation" -version = "0.4.6" -authors = ["The Servo Project Developers"] -description = "Bindings to Core Foundation for OS X" -homepage = "https://github.com/servo/core-foundation-rs" -license = "MIT / Apache-2.0" -repository = "https://github.com/servo/core-foundation-rs" -[dependencies.chrono] -version = "0.4" -optional = true - -[dependencies.core-foundation-sys] -version = "0.4.6" - -[dependencies.libc] -version = "0.2" - -[dependencies.uuid] -version = "0.5" -optional = true - -[features] -mac_os_10_7_support = ["core-foundation-sys/mac_os_10_7_support"] -mac_os_10_8_features = ["core-foundation-sys/mac_os_10_8_features"] -with-chrono = ["chrono"] -with-uuid = ["uuid"] diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/array.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/array.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/array.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/array.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,235 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Heterogeneous immutable arrays. - -pub use core_foundation_sys::array::*; -pub use core_foundation_sys::base::{CFIndex, CFRelease}; -use core_foundation_sys::base::{CFTypeRef, kCFAllocatorDefault}; -use base::CFType; -use libc::c_void; -use std::mem; -use std::marker::PhantomData; - -use base::{CFIndexConvertible, TCFType, CFRange}; - -/// A heterogeneous immutable array. -pub struct CFArray(CFArrayRef, PhantomData); - -/// A trait describing how to convert from the stored *const c_void to the desired T -pub unsafe trait FromVoid { - unsafe fn from_void(x: *const c_void) -> Self; -} - -unsafe impl FromVoid for u32 { - unsafe fn from_void(x: *const c_void) -> u32 { - x as usize as u32 - } -} - -unsafe impl FromVoid for *const c_void { - unsafe fn from_void(x: *const c_void) -> *const c_void { - x - } -} - -unsafe impl FromVoid for CFType { - unsafe fn from_void(x: *const c_void) -> CFType { - TCFType::wrap_under_get_rule(mem::transmute(x)) - } -} - -impl Drop for CFArray { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -pub struct CFArrayIterator<'a, T: 'a> { - array: &'a CFArray, - index: CFIndex, -} - -impl<'a, T: FromVoid> Iterator for CFArrayIterator<'a, T> { - type Item = T; - - fn next(&mut self) -> Option { - if self.index >= self.array.len() { - None - } else { - let value = self.array.get(self.index); - self.index += 1; - Some(value) - } - } -} - -impl<'a, T: FromVoid> ExactSizeIterator for CFArrayIterator<'a, T> { - fn len(&self) -> usize { - (self.array.len() - self.index) as usize - } -} - -impl_TCFTypeGeneric!(CFArray, CFArrayRef, CFArrayGetTypeID); -impl_CFTypeDescriptionGeneric!(CFArray); - -impl CFArray { - /// Creates a new `CFArray` with the given elements, which must be `CFType` objects. - pub fn from_CFTypes(elems: &[T]) -> CFArray where T: TCFType { - unsafe { - let elems: Vec = elems.iter().map(|elem| elem.as_CFTypeRef()).collect(); - let array_ref = CFArrayCreate(kCFAllocatorDefault, - mem::transmute(elems.as_ptr()), - elems.len().to_CFIndex(), - &kCFTypeArrayCallBacks); - TCFType::wrap_under_create_rule(array_ref) - } - } - - #[deprecated(note = "please use `as_untyped` instead")] - pub fn to_untyped(self) -> CFArray { - unsafe { CFArray::wrap_under_get_rule(self.0) } - } - - pub fn as_untyped(&self) -> CFArray { - unsafe { CFArray::wrap_under_get_rule(self.0) } - } - - /// Iterates over the elements of this `CFArray`. - /// - /// Careful; the loop body must wrap the reference properly. Generally, when array elements are - /// Core Foundation objects (not always true), they need to be wrapped with - /// `TCFType::wrap_under_get_rule()`. - #[inline] - pub fn iter<'a>(&'a self) -> CFArrayIterator<'a, T> { - CFArrayIterator { - array: self, - index: 0 - } - } - - #[inline] - pub fn len(&self) -> CFIndex { - unsafe { - CFArrayGetCount(self.0) - } - } - - #[inline] - pub fn get(&self, index: CFIndex) -> T where T: FromVoid { - assert!(index < self.len()); - unsafe { T::from_void(CFArrayGetValueAtIndex(self.0, index)) } - } - - pub fn get_values(&self, range: CFRange) -> Vec<*const c_void> { - let mut vec = Vec::with_capacity(range.length as usize); - unsafe { - CFArrayGetValues(self.0, range, vec.as_mut_ptr()); - vec.set_len(range.length as usize); - vec - } - } - - pub fn get_all_values(&self) -> Vec<*const c_void> { - self.get_values(CFRange { - location: 0, - length: self.len() - }) - } -} - -impl<'a, T: FromVoid> IntoIterator for &'a CFArray { - type Item = T; - type IntoIter = CFArrayIterator<'a, T>; - - fn into_iter(self) -> CFArrayIterator<'a, T> { - self.iter() - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::mem; - - #[test] - fn to_untyped_correct_retain_count() { - let array = CFArray::::from_CFTypes(&[]); - assert_eq!(array.retain_count(), 1); - - let untyped_array = array.to_untyped(); - assert_eq!(untyped_array.retain_count(), 1); - } - - #[test] - fn as_untyped_correct_retain_count() { - let array = CFArray::::from_CFTypes(&[]); - assert_eq!(array.retain_count(), 1); - - let untyped_array = array.as_untyped(); - assert_eq!(array.retain_count(), 2); - assert_eq!(untyped_array.retain_count(), 2); - - mem::drop(array); - assert_eq!(untyped_array.retain_count(), 1); - } - - #[test] - fn should_box_and_unbox() { - use number::CFNumber; - - let n0 = CFNumber::from(0); - let n1 = CFNumber::from(1); - let n2 = CFNumber::from(2); - let n3 = CFNumber::from(3); - let n4 = CFNumber::from(4); - let n5 = CFNumber::from(5); - - let arr = CFArray::from_CFTypes(&[ - n0.as_CFType(), - n1.as_CFType(), - n2.as_CFType(), - n3.as_CFType(), - n4.as_CFType(), - n5.as_CFType(), - ]); - - assert!(arr.get_all_values() == &[n0.as_CFTypeRef(), - n1.as_CFTypeRef(), - n2.as_CFTypeRef(), - n3.as_CFTypeRef(), - n4.as_CFTypeRef(), - n5.as_CFTypeRef()]); - - unsafe { - let mut sum = 0; - - let mut iter = arr.iter(); - assert_eq!(iter.len(), 6); - assert!(iter.next().is_some()); - assert_eq!(iter.len(), 5); - - for elem in iter { - let number: CFNumber = TCFType::wrap_under_get_rule(mem::transmute(elem)); - sum += number.to_i64().unwrap() - } - - assert!(sum == 15); - - for elem in arr.iter() { - let number: CFNumber = TCFType::wrap_under_get_rule(mem::transmute(elem)); - sum += number.to_i64().unwrap() - } - - assert!(sum == 30); - } - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/base.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/base.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/base.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/base.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,197 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::fmt; - -pub use core_foundation_sys::base::*; - -use string::CFString; - -pub trait CFIndexConvertible { - /// Always use this method to construct a `CFIndex` value. It performs bounds checking to - /// ensure the value is in range. - fn to_CFIndex(self) -> CFIndex; -} - -impl CFIndexConvertible for usize { - #[inline] - fn to_CFIndex(self) -> CFIndex { - let max_CFIndex = CFIndex::max_value(); - if self > (max_CFIndex as usize) { - panic!("value out of range") - } - self as CFIndex - } -} - -/// Superclass of all Core Foundation objects. -pub struct CFType(CFTypeRef); - -impl fmt::Debug for CFType { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let desc = unsafe { - CFString::wrap_under_create_rule(CFCopyDescription(self.0)) - }; - desc.fmt(f) - } -} - -impl Clone for CFType { - #[inline] - fn clone(&self) -> CFType { - unsafe { - TCFType::wrap_under_get_rule(self.0) - } - } -} - -impl PartialEq for CFType { - #[inline] - fn eq(&self, other: &CFType) -> bool { - unsafe { - CFEqual(self.as_CFTypeRef(), other.as_CFTypeRef()) != 0 - } - } -} - -impl Drop for CFType { - fn drop(&mut self) { - unsafe { - CFRelease(self.0) - } - } -} - -/// An allocator for Core Foundation objects. -pub struct CFAllocator(CFAllocatorRef); - -impl Drop for CFAllocator { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFAllocator, CFAllocatorRef, CFAllocatorGetTypeID); - -impl CFAllocator { - #[inline] - pub fn new(mut context: CFAllocatorContext) -> CFAllocator { - unsafe { - let allocator_ref = CFAllocatorCreate(kCFAllocatorDefault, &mut context); - TCFType::wrap_under_create_rule(allocator_ref) - } - } -} - -/// All Core Foundation types implement this trait. The type parameter `TypeRef` specifies the -/// associated Core Foundation type: e.g. for `CFType` this is `CFTypeRef`; for `CFArray` this is -/// `CFArrayRef`. -pub trait TCFType { - /// Returns the object as its concrete TypeRef. - fn as_concrete_TypeRef(&self) -> ConcreteTypeRef; - - /// Returns an instance of the object, wrapping the underlying `CFTypeRef` subclass. Use this - /// when following Core Foundation's "Create Rule". The reference count is *not* bumped. - unsafe fn wrap_under_create_rule(obj: ConcreteTypeRef) -> Self; - - /// Returns the type ID for this class. - fn type_id() -> CFTypeID; - - /// Returns the object as a wrapped `CFType`. The reference count is incremented by one. - #[inline] - fn as_CFType(&self) -> CFType { - unsafe { - TCFType::wrap_under_get_rule(self.as_CFTypeRef()) - } - } - - /// Returns the object as a raw `CFTypeRef`. The reference count is not adjusted. - fn as_CFTypeRef(&self) -> CFTypeRef; - - /// Returns an instance of the object, wrapping the underlying `CFTypeRef` subclass. Use this - /// when following Core Foundation's "Get Rule". The reference count *is* bumped. - unsafe fn wrap_under_get_rule(reference: ConcreteTypeRef) -> Self; - - /// Returns the reference count of the object. It is unwise to do anything other than test - /// whether the return value of this method is greater than zero. - #[inline] - fn retain_count(&self) -> CFIndex { - unsafe { - CFGetRetainCount(self.as_CFTypeRef()) - } - } - - /// Returns the type ID of this object. - #[inline] - fn type_of(&self) -> CFTypeID { - unsafe { - CFGetTypeID(self.as_CFTypeRef()) - } - } - - /// Writes a debugging version of this object on standard error. - fn show(&self) { - unsafe { - CFShow(self.as_CFTypeRef()) - } - } - - /// Returns true if this value is an instance of another type. - #[inline] - fn instance_of>(&self) -> bool { - self.type_of() == >::type_id() - } -} - -impl TCFType for CFType { - #[inline] - fn as_concrete_TypeRef(&self) -> CFTypeRef { - self.0 - } - - #[inline] - unsafe fn wrap_under_get_rule(reference: CFTypeRef) -> CFType { - let reference: CFTypeRef = CFRetain(reference); - TCFType::wrap_under_create_rule(reference) - } - - #[inline] - fn as_CFTypeRef(&self) -> CFTypeRef { - self.as_concrete_TypeRef() - } - - #[inline] - unsafe fn wrap_under_create_rule(obj: CFTypeRef) -> CFType { - CFType(obj) - } - - #[inline] - fn type_id() -> CFTypeID { - // FIXME(pcwalton): Is this right? - 0 - } -} - - -#[cfg(test)] -mod tests { - use super::*; - use boolean::CFBoolean; - - #[test] - fn cftype_instance_of() { - let string = CFString::from_static_string("foo"); - let cftype = string.as_CFType(); - - assert!(cftype.instance_of::<_, CFString>()); - assert!(!cftype.instance_of::<_, CFBoolean>()); - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/boolean.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/boolean.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/boolean.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/boolean.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A Boolean type. - -use core_foundation_sys::base::{CFRelease}; -pub use core_foundation_sys::number::{CFBooleanRef, CFBooleanGetTypeID, kCFBooleanTrue, kCFBooleanFalse}; - -use base::TCFType; - -/// A Boolean type. -/// -/// FIXME(pcwalton): Should be a newtype struct, but that fails due to a Rust compiler bug. -pub struct CFBoolean(CFBooleanRef); - -impl Drop for CFBoolean { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFBoolean, CFBooleanRef, CFBooleanGetTypeID); -impl_CFTypeDescription!(CFBoolean); - -impl CFBoolean { - pub fn true_value() -> CFBoolean { - unsafe { - TCFType::wrap_under_get_rule(kCFBooleanTrue) - } - } - - pub fn false_value() -> CFBoolean { - unsafe { - TCFType::wrap_under_get_rule(kCFBooleanFalse) - } - } -} - -impl From for CFBoolean { - fn from(value: bool) -> CFBoolean { - if value { - CFBoolean::true_value() - } else { - CFBoolean::false_value() - } - } -} - -impl From for bool { - fn from(value: CFBoolean) -> bool { - value.0 == unsafe { kCFBooleanTrue } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn to_and_from_bool() { - let b_false = CFBoolean::from(false); - let b_true = CFBoolean::from(true); - assert_ne!(b_false, b_true); - assert_eq!(b_false, CFBoolean::false_value()); - assert_eq!(b_true, CFBoolean::true_value()); - assert!(!bool::from(b_false)); - assert!(bool::from(b_true)); - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/bundle.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/bundle.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/bundle.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/bundle.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,127 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Core Foundation Bundle Type - -pub use core_foundation_sys::bundle::*; -use core_foundation_sys::base::{CFRelease, kCFAllocatorDefault}; - -use base::TCFType; -use url::CFURL; -use dictionary::CFDictionary; - -/// A Bundle type. -pub struct CFBundle(CFBundleRef); - -impl Drop for CFBundle { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl CFBundle { - pub fn new(bundleURL: CFURL) -> Option { - unsafe { - let bundle_ref = CFBundleCreate(kCFAllocatorDefault, bundleURL.as_concrete_TypeRef()); - if bundle_ref.is_null() { - None - } else { - Some(TCFType::wrap_under_create_rule(bundle_ref)) - } - } - } - - pub fn main_bundle() -> CFBundle { - unsafe { - let bundle_ref = CFBundleGetMainBundle(); - TCFType::wrap_under_get_rule(bundle_ref) - } - } - - pub fn info_dictionary(&self) -> CFDictionary { - unsafe { - let info_dictionary = CFBundleGetInfoDictionary(self.0); - TCFType::wrap_under_get_rule(info_dictionary) - } - } - - pub fn executable_url(&self) -> Option { - unsafe { - let exe_url = CFBundleCopyExecutableURL(self.0); - if exe_url.is_null() { - None - } else { - Some(TCFType::wrap_under_create_rule(exe_url)) - } - } - } - - pub fn private_frameworks_url(&self) -> Option { - unsafe { - let fw_url = CFBundleCopyPrivateFrameworksURL(self.0); - if fw_url.is_null() { - None - } else { - Some(TCFType::wrap_under_create_rule(fw_url)) - } - } - } -} - -impl_TCFType!(CFBundle, CFBundleRef, CFBundleGetTypeID); - -#[test] -fn safari_executable_url() { - use string::CFString; - use url::{CFURL, kCFURLPOSIXPathStyle}; - - let cfstr_path = CFString::from_static_string("/Applications/Safari.app"); - let cfurl_path = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); - let cfurl_executable = CFBundle::new(cfurl_path) - .expect("Safari not present") - .executable_url(); - assert!(cfurl_executable.is_some()); - assert_eq!(cfurl_executable - .unwrap() - .absolute() - .get_file_system_path(kCFURLPOSIXPathStyle) - .to_string(), - "/Applications/Safari.app/Contents/MacOS/Safari"); -} - -#[test] -fn safari_private_frameworks_url() { - use string::CFString; - use url::{CFURL, kCFURLPOSIXPathStyle}; - - let cfstr_path = CFString::from_static_string("/Applications/Safari.app"); - let cfurl_path = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); - let cfurl_executable = CFBundle::new(cfurl_path) - .expect("Safari not present") - .private_frameworks_url(); - assert!(cfurl_executable.is_some()); - assert_eq!(cfurl_executable - .unwrap() - .absolute() - .get_file_system_path(kCFURLPOSIXPathStyle) - .to_string(), - "/Applications/Safari.app/Contents/Frameworks"); -} - -#[test] -fn non_existant_bundle() { - use string::CFString; - use url::{CFURL, kCFURLPOSIXPathStyle}; - - let cfstr_path = CFString::from_static_string("/usr/local/foo"); - let cfurl_path = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); - assert!(CFBundle::new(cfurl_path).is_none()); -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/data.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/data.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/data.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/data.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Core Foundation byte buffers. - -pub use core_foundation_sys::data::*; -use core_foundation_sys::base::{CFIndex, CFRelease}; -use core_foundation_sys::base::{kCFAllocatorDefault}; -use std::ops::Deref; -use std::slice; - -use base::{CFIndexConvertible, TCFType}; - -/// A byte buffer. -pub struct CFData(CFDataRef); - -impl Drop for CFData { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFData, CFDataRef, CFDataGetTypeID); -impl_CFTypeDescription!(CFData); - -impl CFData { - pub fn from_buffer(buffer: &[u8]) -> CFData { - unsafe { - let data_ref = CFDataCreate(kCFAllocatorDefault, - buffer.as_ptr(), - buffer.len().to_CFIndex()); - TCFType::wrap_under_create_rule(data_ref) - } - } - - /// Returns a pointer to the underlying bytes in this data. Note that this byte buffer is - /// read-only. - #[inline] - pub fn bytes<'a>(&'a self) -> &'a [u8] { - unsafe { - slice::from_raw_parts(CFDataGetBytePtr(self.0), self.len() as usize) - } - } - - /// Returns the length of this byte buffer. - #[inline] - pub fn len(&self) -> CFIndex { - unsafe { - CFDataGetLength(self.0) - } - } -} - -impl Deref for CFData { - type Target = [u8]; - - #[inline] - fn deref(&self) -> &[u8] { - self.bytes() - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/date.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/date.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/date.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/date.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,136 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Core Foundation date objects. - -pub use core_foundation_sys::date::*; -use core_foundation_sys::base::{CFRelease, kCFAllocatorDefault}; - -use base::TCFType; - -#[cfg(feature = "with-chrono")] -use chrono::NaiveDateTime; - -/// A date. -pub struct CFDate(CFDateRef); - -impl Drop for CFDate { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFDate, CFDateRef, CFDateGetTypeID); -impl_CFTypeDescription!(CFDate); -impl_CFComparison!(CFDate, CFDateCompare); - -impl CFDate { - #[inline] - pub fn new(time: CFAbsoluteTime) -> CFDate { - unsafe { - let date_ref = CFDateCreate(kCFAllocatorDefault, time); - TCFType::wrap_under_create_rule(date_ref) - } - } - - #[inline] - pub fn now() -> CFDate { - CFDate::new(unsafe { CFAbsoluteTimeGetCurrent() }) - } - - #[inline] - pub fn abs_time(&self) -> CFAbsoluteTime { - unsafe { - CFDateGetAbsoluteTime(self.0) - } - } - - #[cfg(feature = "with-chrono")] - pub fn naive_utc(&self) -> NaiveDateTime { - let ts = unsafe { - self.abs_time() + kCFAbsoluteTimeIntervalSince1970 - }; - let (secs, nanos) = if ts.is_sign_positive() { - (ts.trunc() as i64, ts.fract()) - } else { - // nanoseconds can't be negative in NaiveDateTime - (ts.trunc() as i64 - 1, 1.0 - ts.fract().abs()) - }; - NaiveDateTime::from_timestamp(secs, (nanos * 1e9).floor() as u32) - } - - #[cfg(feature = "with-chrono")] - pub fn from_naive_utc(time: NaiveDateTime) -> CFDate { - let secs = time.timestamp(); - let nanos = time.timestamp_subsec_nanos(); - let ts = unsafe { - secs as f64 + (nanos as f64 / 1e9) - kCFAbsoluteTimeIntervalSince1970 - }; - CFDate::new(ts) - } -} - -#[cfg(test)] -mod test { - use super::CFDate; - use std::cmp::Ordering; - - #[cfg(feature = "with-chrono")] - use chrono::NaiveDateTime; - - #[cfg(feature = "with-chrono")] - fn approx_eq(a: f64, b: f64) -> bool { - use std::f64; - - let same_sign = a.is_sign_positive() == b.is_sign_positive(); - let equal = ((a - b).abs() / f64::min(a.abs() + b.abs(), f64::MAX)) < f64::EPSILON; - (same_sign && equal) - } - - #[test] - fn date_comparison() { - let now = CFDate::now(); - let past = CFDate::new(now.abs_time() - 1.0); - assert_eq!(now.cmp(&past), Ordering::Greater); - assert_eq!(now.cmp(&now), Ordering::Equal); - assert_eq!(past.cmp(&now), Ordering::Less); - } - - #[test] - fn date_equality() { - let now = CFDate::now(); - let same_time = CFDate::new(now.abs_time()); - assert_eq!(now, same_time); - } - - #[test] - #[cfg(feature = "with-chrono")] - fn date_chrono_conversion_positive() { - let date = CFDate::now(); - let datetime = date.naive_utc(); - let converted = CFDate::from_naive_utc(datetime); - assert!(approx_eq(date.abs_time(), converted.abs_time())); - } - - #[test] - #[cfg(feature = "with-chrono")] - fn date_chrono_conversion_negative() { - use super::kCFAbsoluteTimeIntervalSince1970; - - let ts = unsafe { - kCFAbsoluteTimeIntervalSince1970 - 420.0 - }; - let date = CFDate::new(ts); - let datetime: NaiveDateTime = date.naive_utc(); - let converted = CFDate::from_naive_utc(datetime); - assert!(approx_eq(date.abs_time(), converted.abs_time())); - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/dictionary.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/dictionary.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/dictionary.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/dictionary.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,133 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Dictionaries of key-value pairs. - -pub use core_foundation_sys::dictionary::*; -use core_foundation_sys::base::CFRelease; -use core_foundation_sys::base::{CFTypeRef, kCFAllocatorDefault}; -use libc::c_void; -use std::mem; -use std::ptr; - -use base::{CFType, CFIndexConvertible, TCFType}; - -/// An immutable dictionary of key-value pairs. -pub struct CFDictionary(CFDictionaryRef); - -impl Drop for CFDictionary { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFDictionary, CFDictionaryRef, CFDictionaryGetTypeID); -impl_CFTypeDescription!(CFDictionary); - -impl CFDictionary { - pub fn from_CFType_pairs(pairs: &[(K, V)]) -> CFDictionary - where K: TCFType, V: TCFType { - let (keys, values): (Vec,Vec) = - pairs.iter() - .map(|&(ref key, ref value)| (key.as_CFTypeRef(), value.as_CFTypeRef())) - .unzip(); - - unsafe { - let dictionary_ref = CFDictionaryCreate(kCFAllocatorDefault, - mem::transmute(keys.as_ptr()), - mem::transmute(values.as_ptr()), - keys.len().to_CFIndex(), - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); - TCFType::wrap_under_create_rule(dictionary_ref) - } - } - - #[inline] - pub fn len(&self) -> usize { - unsafe { - CFDictionaryGetCount(self.0) as usize - } - } - - #[inline] - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - #[inline] - pub fn contains_key(&self, key: *const c_void) -> bool { - unsafe { - CFDictionaryContainsKey(self.0, key) != 0 - } - } - - /// Similar to `contains_key` but acts on a higher level, automatically converting from any - /// `TCFType` to the raw pointer of its concrete TypeRef. - #[inline] - pub fn contains_key2>(&self, key: &K) -> bool { - self.contains_key(key.as_concrete_TypeRef() as *const c_void) - } - - #[inline] - pub fn find(&self, key: *const c_void) -> Option<*const c_void> { - unsafe { - let mut value: *const c_void = ptr::null(); - if CFDictionaryGetValueIfPresent(self.0, key, &mut value) != 0 { - Some(value) - } else { - None - } - } - } - - /// Similar to `find` but acts on a higher level, automatically converting from any `TCFType` - /// to the raw pointer of its concrete TypeRef. - #[inline] - pub fn find2>(&self, key: &K) -> Option<*const c_void> { - self.find(key.as_concrete_TypeRef() as *const c_void) - } - - /// # Panics - /// - /// Panics if the key is not present in the dictionary. Use `find` to get an `Option` instead - /// of panicking. - #[inline] - pub fn get(&self, key: *const c_void) -> *const c_void { - self.find(key).expect(&format!("No entry found for key {:p}", key)) - } - - /// A convenience function to retrieve `CFType` instances. - #[inline] - pub unsafe fn get_CFType(&self, key: *const c_void) -> CFType { - let value: CFTypeRef = mem::transmute(self.get(key)); - TCFType::wrap_under_get_rule(value) - } - - #[inline] - pub unsafe fn set_value(&self, key: *const c_void, value: *const c_void) { - CFDictionarySetValue(self.0, key, value) - } - - pub fn get_keys_and_values(&self) -> (Vec<*const c_void>, Vec<*const c_void>) { - let length = self.len(); - let mut keys = Vec::with_capacity(length); - let mut values = Vec::with_capacity(length); - - unsafe { - CFDictionaryGetKeysAndValues(self.0, keys.as_mut_ptr(), values.as_mut_ptr()); - keys.set_len(length); - values.set_len(length); - } - - (keys, values) - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/error.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/error.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/error.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/error.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -// Copyright 2016 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Core Foundation errors. - -use core_foundation_sys::error::*; -use core_foundation_sys::base::CFRelease; -use std::error::Error; -use std::fmt; - -use base::{CFIndex, TCFType}; -use string::CFString; - -/// An error value. -pub struct CFError(CFErrorRef); - -impl Drop for CFError { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFError, CFErrorRef, CFErrorGetTypeID); - -impl fmt::Debug for CFError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("CFError") - .field("domain", &self.domain()) - .field("code", &self.code()) - .field("description", &self.description()) - .finish() - } -} - -impl fmt::Display for CFError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!(fmt, "{}", self.description()) - } -} - -impl Error for CFError { - fn description(&self) -> &str { - "a Core Foundation error" - } -} - -impl CFError { - /// Returns a string identifying the domain with which this error is - /// associated. - pub fn domain(&self) -> CFString { - unsafe { - let s = CFErrorGetDomain(self.0); - CFString::wrap_under_get_rule(s) - } - } - - /// Returns the code identifying this type of error. - pub fn code(&self) -> CFIndex { - unsafe { CFErrorGetCode(self.0) } - } - - /// Returns a human-presentable description of the error. - pub fn description(&self) -> CFString { - unsafe { - let s = CFErrorCopyDescription(self.0); - CFString::wrap_under_create_rule(s) - } - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/lib.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/lib.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,222 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -#![allow(non_snake_case)] - -extern crate core_foundation_sys; -extern crate libc; - -#[cfg(feature = "with-chrono")] -extern crate chrono; - -#[macro_export] -macro_rules! impl_TCFType { - ($ty:ident, $raw:ident, $ty_id:ident) => { - impl $crate::base::TCFType<$raw> for $ty { - #[inline] - fn as_concrete_TypeRef(&self) -> $raw { - self.0 - } - - #[inline] - unsafe fn wrap_under_get_rule(reference: $raw) -> $ty { - let reference = ::std::mem::transmute(::core_foundation_sys::base::CFRetain(::std::mem::transmute(reference))); - $crate::base::TCFType::wrap_under_create_rule(reference) - } - - #[inline] - fn as_CFTypeRef(&self) -> ::core_foundation_sys::base::CFTypeRef { - unsafe { - ::std::mem::transmute(self.as_concrete_TypeRef()) - } - } - - #[inline] - unsafe fn wrap_under_create_rule(obj: $raw) -> $ty { - $ty(obj) - } - - #[inline] - fn type_id() -> ::core_foundation_sys::base::CFTypeID { - unsafe { - $ty_id() - } - } - } - - impl Clone for $ty { - #[inline] - fn clone(&self) -> $ty { - unsafe { - $ty::wrap_under_get_rule(self.0) - } - } - } - - impl PartialEq for $ty { - #[inline] - fn eq(&self, other: &$ty) -> bool { - self.as_CFType().eq(&other.as_CFType()) - } - } - - impl Eq for $ty { } - } -} - -// This is basically identical to the implementation above. I can't -// think of a clean way to have them share code -#[macro_export] -macro_rules! impl_TCFTypeGeneric { - ($ty:ident, $raw:ident, $ty_id:ident) => { - impl $crate::base::TCFType<$raw> for $ty { - #[inline] - fn as_concrete_TypeRef(&self) -> $raw { - self.0 - } - - #[inline] - unsafe fn wrap_under_get_rule(reference: $raw) -> $ty { - let reference = ::std::mem::transmute(::core_foundation_sys::base::CFRetain(::std::mem::transmute(reference))); - $crate::base::TCFType::wrap_under_create_rule(reference) - } - - #[inline] - fn as_CFTypeRef(&self) -> ::core_foundation_sys::base::CFTypeRef { - unsafe { - ::std::mem::transmute(self.as_concrete_TypeRef()) - } - } - - #[inline] - unsafe fn wrap_under_create_rule(obj: $raw) -> $ty { - $ty(obj, PhantomData) - } - - #[inline] - fn type_id() -> ::core_foundation_sys::base::CFTypeID { - unsafe { - $ty_id() - } - } - } - - impl Clone for $ty { - #[inline] - fn clone(&self) -> $ty { - unsafe { - $ty::wrap_under_get_rule(self.0) - } - } - } - - impl PartialEq for $ty { - #[inline] - fn eq(&self, other: &$ty) -> bool { - self.as_CFType().eq(&other.as_CFType()) - } - } - - impl Eq for $ty { } - } -} - -#[macro_export] -macro_rules! impl_CFTypeDescription { - ($ty:ident) => { - impl ::std::fmt::Debug for $ty { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - self.as_CFType().fmt(f) - } - } - } -} - -// The same as impl_CFTypeDescription but with a type parameter -#[macro_export] -macro_rules! impl_CFTypeDescriptionGeneric { - ($ty:ident) => { - impl ::std::fmt::Debug for $ty { - fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - self.as_CFType().fmt(f) - } - } - } -} - -#[macro_export] -macro_rules! impl_CFComparison { - ($ty:ident, $compare:ident) => { - impl PartialOrd for $ty { - #[inline] - fn partial_cmp(&self, other: &$ty) -> Option<::std::cmp::Ordering> { - unsafe { - Some($compare(self.as_concrete_TypeRef(), other.as_concrete_TypeRef(), ::std::ptr::null_mut()).into()) - } - } - } - - impl Ord for $ty { - #[inline] - fn cmp(&self, other: &$ty) -> ::std::cmp::Ordering { - self.partial_cmp(other).unwrap() - } - } - } -} - -pub mod array; -pub mod base; -pub mod boolean; -pub mod data; -pub mod date; -pub mod dictionary; -pub mod error; -pub mod number; -pub mod set; -pub mod string; -pub mod url; -pub mod bundle; -pub mod propertylist; -pub mod runloop; -pub mod timezone; -pub mod uuid; - -#[cfg(test)] -pub mod test { - #[test] - fn test_stuff() { - use base::TCFType; - use boolean::CFBoolean; - use number::CFNumber; - use dictionary::CFDictionary; - use string::CFString; - - /*let n = CFNumber::new_number(42 as i32); - io::println(format!("%d", (&n).retain_count() as int)); - (&n).show();*/ - - let bar = CFString::from_static_string("Bar"); - let baz = CFString::from_static_string("Baz"); - let boo = CFString::from_static_string("Boo"); - let foo = CFString::from_static_string("Foo"); - let tru = CFBoolean::true_value(); - let n42 = CFNumber::from(42); - - let d = CFDictionary::from_CFType_pairs(&[ - (bar.as_CFType(), boo.as_CFType()), - (baz.as_CFType(), tru.as_CFType()), - (foo.as_CFType(), n42.as_CFType()), - ]); - - let (v1, v2) = d.get_keys_and_values(); - - assert!(v1 == &[bar.as_CFTypeRef(), baz.as_CFTypeRef(), foo.as_CFTypeRef()]); - assert!(v2 == &[boo.as_CFTypeRef(), tru.as_CFTypeRef(), n42.as_CFTypeRef()]); - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/number.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/number.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/number.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/number.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,146 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Immutable numbers. - -use core_foundation_sys::base::{CFRelease, kCFAllocatorDefault}; -pub use core_foundation_sys::number::*; -use std::mem; - -use base::{TCFType}; - -/// An immutable numeric value. -pub struct CFNumber(CFNumberRef); - -impl Drop for CFNumber { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFNumber, CFNumberRef, CFNumberGetTypeID); -impl_CFTypeDescription!(CFNumber); -impl_CFComparison!(CFNumber, CFNumberCompare); - -impl CFNumber { - #[inline] - pub fn to_i64(&self) -> Option { - unsafe { - let mut value: i64 = 0; - let ok = CFNumberGetValue(self.0, kCFNumberSInt64Type, mem::transmute(&mut value)); - if ok { Some(value) } else { None } - } - } - - #[inline] - pub fn to_f32(&self) -> Option { - unsafe { - let mut value: f32 = 0.0; - let ok = CFNumberGetValue(self.0, kCFNumberFloat32Type, mem::transmute(&mut value)); - if ok { Some(value) } else { None } - } - } - - #[inline] - pub fn to_f64(&self) -> Option { - unsafe { - let mut value: f64 = 0.0; - let ok = CFNumberGetValue(self.0, kCFNumberFloat64Type, mem::transmute(&mut value)); - if ok { Some(value) } else { None } - } - } - - #[deprecated(note = "please use `CFNumber::from` instead")] - #[inline] - pub fn from_i32(value: i32) -> CFNumber { - CFNumber::from(value) - } - - #[deprecated(note = "please use `CFNumber::from` instead")] - #[inline] - pub fn from_i64(value: i64) -> CFNumber { - Self::from(value) - } - - #[deprecated(note = "please use `CFNumber::from` instead")] - #[inline] - pub fn from_f32(value: f32) -> CFNumber { - Self::from(value) - } - - #[deprecated(note = "please use `CFNumber::from` instead")] - #[inline] - pub fn from_f64(value: f64) -> CFNumber { - Self::from(value) - } -} - -impl From for CFNumber { - #[inline] - fn from(value: i32) -> Self { - unsafe { - let number_ref = CFNumberCreate( - kCFAllocatorDefault, - kCFNumberSInt32Type, - mem::transmute(&value), - ); - TCFType::wrap_under_create_rule(number_ref) - } - } -} - -impl From for CFNumber { - #[inline] - fn from(value: i64) -> Self { - unsafe { - let number_ref = CFNumberCreate( - kCFAllocatorDefault, - kCFNumberSInt64Type, - mem::transmute(&value), - ); - TCFType::wrap_under_create_rule(number_ref) - } - } -} - -impl From for CFNumber { - #[inline] - fn from(value: f32) -> Self { - unsafe { - let number_ref = CFNumberCreate( - kCFAllocatorDefault, - kCFNumberFloat32Type, - mem::transmute(&value), - ); - TCFType::wrap_under_create_rule(number_ref) - } - } -} - -impl From for CFNumber { - #[inline] - fn from(value: f64) -> Self { - unsafe { - let number_ref = CFNumberCreate( - kCFAllocatorDefault, - kCFNumberFloat64Type, - mem::transmute(&value), - ); - TCFType::wrap_under_create_rule(number_ref) - } - } -} - -/// A convenience function to create CFNumbers. -#[deprecated(note = "please use `CFNumber::from` instead")] -pub fn number(value: i64) -> CFNumber { - CFNumber::from(value) -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/propertylist.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/propertylist.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/propertylist.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/propertylist.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,255 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Core Foundation property lists - -use std::ptr; -use std::mem; - -use libc::c_void; - -use error::CFError; -use data::CFData; -use base::{CFType, TCFType}; - -pub use core_foundation_sys::propertylist::*; -use core_foundation_sys::error::CFErrorRef; -use core_foundation_sys::base::{CFGetRetainCount, CFGetTypeID, CFIndex, CFRelease, CFRetain, - CFShow, CFTypeID, kCFAllocatorDefault}; - -pub fn create_with_data(data: CFData, - options: CFPropertyListMutabilityOptions) - -> Result<(*const c_void, CFPropertyListFormat), CFError> { - unsafe { - let mut error: CFErrorRef = ptr::null_mut(); - let mut format: CFPropertyListFormat = 0; - let property_list = CFPropertyListCreateWithData(kCFAllocatorDefault, - data.as_concrete_TypeRef(), - options, - &mut format, - &mut error); - if property_list.is_null() { - Err(TCFType::wrap_under_create_rule(error)) - } else { - Ok((property_list, format)) - } - } -} - -pub fn create_data(property_list: *const c_void, format: CFPropertyListFormat) -> Result { - unsafe { - let mut error: CFErrorRef = ptr::null_mut(); - let data_ref = CFPropertyListCreateData(kCFAllocatorDefault, - property_list, - format, - 0, - &mut error); - if data_ref.is_null() { - Err(TCFType::wrap_under_create_rule(error)) - } else { - Ok(TCFType::wrap_under_create_rule(data_ref)) - } - } -} - - -/// Trait for all subclasses of [`CFPropertyList`]. -/// -/// [`CFPropertyList`]: struct.CFPropertyList.html -pub trait CFPropertyListSubClass: TCFType<*const Raw> { - /// Create an instance of the superclass type [`CFPropertyList`] for this instance. - /// - /// [`CFPropertyList`]: struct.CFPropertyList.html - fn to_CFPropertyList(&self) -> CFPropertyList { - unsafe { CFPropertyList::wrap_under_get_rule(self.as_concrete_TypeRef() as *const c_void) } - } -} - -impl CFPropertyListSubClass<::data::__CFData> for ::data::CFData {} -impl CFPropertyListSubClass<::string::__CFString> for ::string::CFString {} -impl CFPropertyListSubClass<::array::__CFArray> for ::array::CFArray {} -impl CFPropertyListSubClass<::dictionary::__CFDictionary> for ::dictionary::CFDictionary {} -impl CFPropertyListSubClass<::date::__CFDate> for ::date::CFDate {} -impl CFPropertyListSubClass<::number::__CFBoolean> for ::boolean::CFBoolean {} -impl CFPropertyListSubClass<::number::__CFNumber> for ::number::CFNumber {} - -/// A CFPropertyList struct. This is superclass to [`CFData`], [`CFString`], [`CFArray`], -/// [`CFDictionary`], [`CFDate`], [`CFBoolean`], and [`CFNumber`]. -/// -/// This superclass type does not have its own `CFTypeID`, instead each instance has the `CFTypeID` -/// of the subclass it is an instance of. Thus, this type cannot implement the [`TCFType`] trait, -/// since it cannot implement the static [`TCFType::type_id()`] method. -/// -/// [`CFData`]: ../data/struct.CFData.html -/// [`CFString`]: ../string/struct.CFString.html -/// [`CFArray`]: ../array/struct.CFArray.html -/// [`CFDictionary`]: ../dictionary/struct.CFDictionary.html -/// [`CFDate`]: ../date/struct.CFDate.html -/// [`CFBoolean`]: ../boolean/struct.CFBoolean.html -/// [`CFNumber`]: ../number/struct.CFNumber.html -/// [`TCFType`]: ../base/trait.TCFType.html -/// [`TCFType::type_id()`]: ../base/trait.TCFType.html#method.type_of -pub struct CFPropertyList(CFPropertyListRef); - -impl Drop for CFPropertyList { - fn drop(&mut self) { - unsafe { CFRelease(self.as_CFTypeRef()) } - } -} - -impl CFPropertyList { - #[inline] - pub fn as_concrete_TypeRef(&self) -> CFPropertyListRef { - self.0 - } - - #[inline] - pub unsafe fn wrap_under_get_rule(reference: CFPropertyListRef) -> CFPropertyList { - let reference = mem::transmute(CFRetain(mem::transmute(reference))); - CFPropertyList(reference) - } - - #[inline] - pub fn as_CFType(&self) -> CFType { - unsafe { CFType::wrap_under_get_rule(self.as_CFTypeRef()) } - } - - #[inline] - pub fn as_CFTypeRef(&self) -> ::core_foundation_sys::base::CFTypeRef { - unsafe { mem::transmute(self.as_concrete_TypeRef()) } - } - - #[inline] - pub unsafe fn wrap_under_create_rule(obj: CFPropertyListRef) -> CFPropertyList { - CFPropertyList(obj) - } - - /// Returns the reference count of the object. It is unwise to do anything other than test - /// whether the return value of this method is greater than zero. - #[inline] - pub fn retain_count(&self) -> CFIndex { - unsafe { CFGetRetainCount(self.as_CFTypeRef()) } - } - - /// Returns the type ID of this object. Will be one of CFData, CFString, CFArray, CFDictionary, - /// CFDate, CFBoolean, or CFNumber. - #[inline] - pub fn type_of(&self) -> CFTypeID { - unsafe { CFGetTypeID(self.as_CFTypeRef()) } - } - - /// Writes a debugging version of this object on standard error. - pub fn show(&self) { - unsafe { CFShow(self.as_CFTypeRef()) } - } - - /// Returns true if this value is an instance of another type. - #[inline] - pub fn instance_of>( - &self, - ) -> bool { - self.type_of() == >::type_id() - } -} - -impl Clone for CFPropertyList { - #[inline] - fn clone(&self) -> CFPropertyList { - unsafe { CFPropertyList::wrap_under_get_rule(self.0) } - } -} - -impl PartialEq for CFPropertyList { - #[inline] - fn eq(&self, other: &CFPropertyList) -> bool { - self.as_CFType().eq(&other.as_CFType()) - } -} - -impl Eq for CFPropertyList {} - -impl CFPropertyList { - /// Try to downcast the [`CFPropertyList`] to a subclass. Checking if the instance is the correct - /// subclass happens at runtime and an error is returned if it is not the correct type. - /// Works similar to [`Box::downcast`]. - /// - /// # Examples - /// - /// ``` - /// # use core_foundation::string::CFString; - /// # use core_foundation::propertylist::{CFPropertyList, CFPropertyListSubClass}; - /// # - /// // Create a string. - /// let string: CFString = CFString::from_static_string("FooBar"); - /// // Cast it up to a property list. - /// let propertylist: CFPropertyList = string.to_CFPropertyList(); - /// // Cast it down again. - /// assert!(propertylist.downcast::<_, CFString>().unwrap().to_string() == "FooBar"); - /// ``` - /// - /// [`CFPropertyList`]: struct.CFPropertyList.html - /// [`Box::downcast`]: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.downcast - pub fn downcast>(&self) -> Option { - if self.instance_of::<_, T>() { - Some(unsafe { T::wrap_under_get_rule(self.0 as *const Raw) }) - } else { - None - } - } -} - - - -#[cfg(test)] -pub mod test { - use super::*; - use string::CFString; - use boolean::CFBoolean; - - #[test] - fn test_property_list_serialization() { - use base::{TCFType, CFEqual}; - use boolean::CFBoolean; - use number::CFNumber; - use dictionary::CFDictionary; - use string::CFString; - use super::*; - - let bar = CFString::from_static_string("Bar"); - let baz = CFString::from_static_string("Baz"); - let boo = CFString::from_static_string("Boo"); - let foo = CFString::from_static_string("Foo"); - let tru = CFBoolean::true_value(); - let n42 = CFNumber::from(42); - - let dict1 = CFDictionary::from_CFType_pairs(&[(bar.as_CFType(), boo.as_CFType()), - (baz.as_CFType(), tru.as_CFType()), - (foo.as_CFType(), n42.as_CFType())]); - - let data = create_data(dict1.as_CFTypeRef(), kCFPropertyListXMLFormat_v1_0).unwrap(); - let (dict2, _) = create_with_data(data, kCFPropertyListImmutable).unwrap(); - unsafe { - assert!(CFEqual(dict1.as_CFTypeRef(), dict2) == 1); - } - } - - #[test] - fn downcast_string() { - let propertylist = CFString::from_static_string("Bar").to_CFPropertyList(); - assert!(propertylist.downcast::<_, CFString>().unwrap().to_string() == "Bar"); - assert!(propertylist.downcast::<_, CFBoolean>().is_none()); - } - - #[test] - fn downcast_boolean() { - let propertylist = CFBoolean::true_value().to_CFPropertyList(); - assert!(propertylist.downcast::<_, CFBoolean>().is_some()); - assert!(propertylist.downcast::<_, CFString>().is_none()); - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/runloop.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/runloop.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/runloop.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/runloop.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,212 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(non_upper_case_globals)] - -pub use core_foundation_sys::runloop::*; -use core_foundation_sys::base::{CFIndex, CFRelease}; -use core_foundation_sys::base::{kCFAllocatorDefault, CFOptionFlags}; -use core_foundation_sys::string::CFStringRef; - -use base::{TCFType}; -use date::{CFAbsoluteTime, CFTimeInterval}; -use string::{CFString}; - -pub type CFRunLoopMode = CFStringRef; - -pub struct CFRunLoop(CFRunLoopRef); - -impl Drop for CFRunLoop { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFRunLoop, CFRunLoopRef, CFRunLoopGetTypeID); -impl_CFTypeDescription!(CFRunLoop); - -impl CFRunLoop { - pub fn get_current() -> CFRunLoop { - unsafe { - let run_loop_ref = CFRunLoopGetCurrent(); - TCFType::wrap_under_get_rule(run_loop_ref) - } - } - - pub fn get_main() -> CFRunLoop { - unsafe { - let run_loop_ref = CFRunLoopGetMain(); - TCFType::wrap_under_get_rule(run_loop_ref) - } - } - - pub fn run_current() { - unsafe { - CFRunLoopRun(); - } - } - - pub fn stop(&self) { - unsafe { - CFRunLoopStop(self.0); - } - } - - pub fn current_mode(&self) -> Option { - unsafe { - let string_ref = CFRunLoopCopyCurrentMode(self.0); - if string_ref.is_null() { - return None; - } - - let cf_string: CFString = TCFType::wrap_under_create_rule(string_ref); - Some(cf_string.to_string()) - } - } - - pub fn contains_timer(&self, timer: &CFRunLoopTimer, mode: CFRunLoopMode) -> bool { - unsafe { - CFRunLoopContainsTimer(self.0, timer.0, mode) != 0 - } - } - - pub fn add_timer(&self, timer: &CFRunLoopTimer, mode: CFRunLoopMode) { - unsafe { - CFRunLoopAddTimer(self.0, timer.0, mode); - } - } - - pub fn remove_timer(&self, timer: &CFRunLoopTimer, mode: CFRunLoopMode) { - unsafe { - CFRunLoopRemoveTimer(self.0, timer.0, mode); - } - } - - pub fn contains_source(&self, source: &CFRunLoopSource, mode: CFRunLoopMode) -> bool { - unsafe { - CFRunLoopContainsSource(self.0, source.0, mode) != 0 - } - } - - pub fn add_source(&self, source: &CFRunLoopSource, mode: CFRunLoopMode) { - unsafe { - CFRunLoopAddSource(self.0, source.0, mode); - } - } - - pub fn remove_source(&self, source: &CFRunLoopSource, mode: CFRunLoopMode) { - unsafe { - CFRunLoopRemoveSource(self.0, source.0, mode); - } - } - - pub fn contains_observer(&self, observer: &CFRunLoopObserver, mode: CFRunLoopMode) -> bool { - unsafe { - CFRunLoopContainsObserver(self.0, observer.0, mode) != 0 - } - } - - pub fn add_observer(&self, observer: &CFRunLoopObserver, mode: CFRunLoopMode) { - unsafe { - CFRunLoopAddObserver(self.0, observer.0, mode); - } - } - - pub fn remove_observer(&self, observer: &CFRunLoopObserver, mode: CFRunLoopMode) { - unsafe { - CFRunLoopRemoveObserver(self.0, observer.0, mode); - } - } - -} - -pub struct CFRunLoopTimer(CFRunLoopTimerRef); - -impl Drop for CFRunLoopTimer { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFRunLoopTimer, CFRunLoopTimerRef, CFRunLoopTimerGetTypeID); - -impl CFRunLoopTimer { - pub fn new(fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, callout: CFRunLoopTimerCallBack, context: *mut CFRunLoopTimerContext) -> CFRunLoopTimer { - unsafe { - let timer_ref = CFRunLoopTimerCreate(kCFAllocatorDefault, fireDate, interval, flags, order, callout, context); - TCFType::wrap_under_create_rule(timer_ref) - } - } -} - - -pub struct CFRunLoopSource(CFRunLoopSourceRef); - -impl Drop for CFRunLoopSource { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFRunLoopSource, CFRunLoopSourceRef, CFRunLoopSourceGetTypeID); - - -pub struct CFRunLoopObserver(CFRunLoopObserverRef); - -impl Drop for CFRunLoopObserver { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFRunLoopObserver, CFRunLoopObserverRef, CFRunLoopObserverGetTypeID); - -#[cfg(test)] -mod test { - use super::*; - use date::{CFDate, CFAbsoluteTime}; - use std::mem; - use libc::c_void; - - #[test] - fn wait_200_milliseconds() { - let run_loop = CFRunLoop::get_current(); - let mut now = CFDate::now().abs_time(); - let mut context = unsafe { CFRunLoopTimerContext { - version: 0, - info: mem::transmute(&mut now), - retain: mem::zeroed(), - release: mem::zeroed(), - copyDescription: mem::zeroed(), - } }; - - - let run_loop_timer = CFRunLoopTimer::new(now + 0.20f64, 0f64, 0, 0, timer_popped, &mut context); - unsafe { - run_loop.add_timer(&run_loop_timer, kCFRunLoopDefaultMode); - } - CFRunLoop::run_current(); - } - - extern "C" fn timer_popped(_timer: CFRunLoopTimerRef, info: *mut c_void) { - let previous_now_ptr: *const CFAbsoluteTime = unsafe { mem::transmute(info) }; - let previous_now = unsafe { *previous_now_ptr }; - let now = CFDate::now().abs_time(); - assert!(now - previous_now > 0.19 && now - previous_now < 0.21); - CFRunLoop::get_current().stop(); - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/set.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/set.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/set.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/set.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! An immutable bag of elements. - -pub use core_foundation_sys::set::*; -use core_foundation_sys::base::CFRelease; -use core_foundation_sys::base::{CFTypeRef, kCFAllocatorDefault}; - -use base::{CFIndexConvertible, TCFType}; - -use std::mem; - -/// An immutable bag of elements. -pub struct CFSet(CFSetRef); - -impl Drop for CFSet { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFSet, CFSetRef, CFSetGetTypeID); -impl_CFTypeDescription!(CFSet); - -impl CFSet { - /// Creates a new set from a list of `CFType` instances. - pub fn from_slice(elems: &[T]) -> CFSet where T: TCFType { - unsafe { - let elems: Vec = elems.iter().map(|elem| elem.as_CFTypeRef()).collect(); - let set_ref = CFSetCreate(kCFAllocatorDefault, - mem::transmute(elems.as_ptr()), - elems.len().to_CFIndex(), - &kCFTypeSetCallBacks); - TCFType::wrap_under_create_rule(set_ref) - } - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/string.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/string.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/string.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/string.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,149 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Immutable strings. - -pub use core_foundation_sys::string::*; - -use base::{CFIndexConvertible, TCFType}; - -use core_foundation_sys::base::{Boolean, CFIndex, CFRange, CFRelease}; -use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull}; -use std::fmt; -use std::str::{self, FromStr}; -use std::ptr; -use std::ffi::CStr; - -/// An immutable string in one of a variety of encodings. -pub struct CFString(CFStringRef); - -impl Drop for CFString { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFString, CFStringRef, CFStringGetTypeID); - -impl FromStr for CFString { - type Err = (); - - /// See also CFString::new for a variant of this which does not return a Result - #[inline] - fn from_str(string: &str) -> Result { - Ok(CFString::new(string)) - } -} - -impl<'a> From<&'a str> for CFString { - #[inline] - fn from(string: &'a str) -> CFString { - CFString::new(string) - } -} - -impl fmt::Display for CFString { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - unsafe { - // Do this without allocating if we can get away with it - let c_string = CFStringGetCStringPtr(self.0, kCFStringEncodingUTF8); - if c_string != ptr::null() { - let c_str = CStr::from_ptr(c_string); - fmt.write_str(str::from_utf8_unchecked(c_str.to_bytes())) - } else { - let char_len = self.char_len(); - - // First, ask how big the buffer ought to be. - let mut bytes_required: CFIndex = 0; - CFStringGetBytes(self.0, - CFRange { location: 0, length: char_len }, - kCFStringEncodingUTF8, - 0, - false as Boolean, - ptr::null_mut(), - 0, - &mut bytes_required); - - // Then, allocate the buffer and actually copy. - let mut buffer = vec![b'\x00'; bytes_required as usize]; - - let mut bytes_used: CFIndex = 0; - let chars_written = CFStringGetBytes(self.0, - CFRange { location: 0, length: char_len }, - kCFStringEncodingUTF8, - 0, - false as Boolean, - buffer.as_mut_ptr(), - buffer.len().to_CFIndex(), - &mut bytes_used) as usize; - assert!(chars_written.to_CFIndex() == char_len); - - // This is dangerous; we over-allocate and null-terminate the string (during - // initialization). - assert!(bytes_used == buffer.len().to_CFIndex()); - fmt.write_str(str::from_utf8_unchecked(&buffer)) - } - } - } -} - -impl fmt::Debug for CFString { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "\"{}\"", self) - } -} - - -impl CFString { - /// Creates a new `CFString` instance from a Rust string. - #[inline] - pub fn new(string: &str) -> CFString { - unsafe { - let string_ref = CFStringCreateWithBytes(kCFAllocatorDefault, - string.as_ptr(), - string.len().to_CFIndex(), - kCFStringEncodingUTF8, - false as Boolean); - CFString::wrap_under_create_rule(string_ref) - } - } - - /// Like `CFString::new`, but references a string that can be used as a backing store - /// by virtue of being statically allocated. - #[inline] - pub fn from_static_string(string: &'static str) -> CFString { - unsafe { - let string_ref = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, - string.as_ptr(), - string.len().to_CFIndex(), - kCFStringEncodingUTF8, - false as Boolean, - kCFAllocatorNull); - TCFType::wrap_under_create_rule(string_ref) - } - } - - /// Returns the number of characters in the string. - #[inline] - pub fn char_len(&self) -> CFIndex { - unsafe { - CFStringGetLength(self.0) - } - } -} - -#[test] -fn string_and_back() { - let original = "The quick brown fox jumped over the slow lazy dog."; - let cfstr = CFString::from_static_string(original); - let converted = cfstr.to_string(); - assert!(converted == original); -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/timezone.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/timezone.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/timezone.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/timezone.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,101 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Core Foundation time zone objects. - -pub use core_foundation_sys::timezone::*; -use core_foundation_sys::base::{CFRelease, kCFAllocatorDefault}; - -use base::TCFType; -use date::{CFDate, CFTimeInterval}; - -#[cfg(feature = "with-chrono")] -use chrono::{FixedOffset, NaiveDateTime}; - -/// A time zone. -pub struct CFTimeZone(CFTimeZoneRef); - -impl Drop for CFTimeZone { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFTimeZone, CFTimeZoneRef, CFTimeZoneGetTypeID); -impl_CFTypeDescription!(CFTimeZone); - -impl Default for CFTimeZone { - fn default() -> CFTimeZone { - unsafe { - let tz_ref = CFTimeZoneCopyDefault(); - TCFType::wrap_under_create_rule(tz_ref) - } - } -} - -impl CFTimeZone { - #[inline] - pub fn new(interval: CFTimeInterval) -> CFTimeZone { - unsafe { - let tz_ref = CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorDefault, interval); - TCFType::wrap_under_create_rule(tz_ref) - } - } - - #[inline] - pub fn system() -> CFTimeZone { - unsafe { - let tz_ref = CFTimeZoneCopySystem(); - TCFType::wrap_under_create_rule(tz_ref) - } - } - - pub fn seconds_from_gmt(&self, date: CFDate) -> CFTimeInterval { - unsafe { - CFTimeZoneGetSecondsFromGMT(self.0, date.abs_time()) - } - } - - #[cfg(feature = "with-chrono")] - pub fn offset_at_date(&self, date: NaiveDateTime) -> FixedOffset { - let date = CFDate::from_naive_utc(date); - FixedOffset::east(self.seconds_from_gmt(date) as i32) - } - - #[cfg(feature = "with-chrono")] - pub fn from_offset(offset: FixedOffset) -> CFTimeZone { - CFTimeZone::new(offset.local_minus_utc() as f64) - } -} - -#[cfg(test)] -mod test { - use super::CFTimeZone; - - #[cfg(feature = "with-chrono")] - use chrono::{NaiveDateTime, FixedOffset}; - - #[test] - fn timezone_comparison() { - let system = CFTimeZone::system(); - let default = CFTimeZone::default(); - assert_eq!(system, default); - } - - #[test] - #[cfg(feature = "with-chrono")] - fn timezone_chrono_conversion() { - let offset = FixedOffset::west(28800); - let tz = CFTimeZone::from_offset(offset); - let converted = tz.offset_at_date(NaiveDateTime::from_timestamp(0, 0)); - assert_eq!(offset, converted); - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/url.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/url.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/url.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/url.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,164 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A URL type for Core Foundation. - -pub use core_foundation_sys::url::*; - -use base::{TCFType, CFIndex}; -use string::{CFString}; - -use core_foundation_sys::base::{kCFAllocatorDefault, CFRelease, Boolean}; -use std::fmt; -use std::ptr; -use std::path::{Path, PathBuf}; -use std::mem; - -use libc::{strlen, PATH_MAX}; - -#[cfg(unix)] -use std::os::unix::ffi::OsStrExt; -#[cfg(unix)] -use std::ffi::OsStr; - -pub struct CFURL(CFURLRef); - -impl Drop for CFURL { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFURL, CFURLRef, CFURLGetTypeID); - -impl fmt::Debug for CFURL { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - unsafe { - let string: CFString = TCFType::wrap_under_get_rule(CFURLGetString(self.0)); - write!(f, "{}", string.to_string()) - } - } -} - -impl CFURL { - pub fn from_path>(path: P, isDirectory: bool) -> Option { - let path_bytes; - #[cfg(unix)] - { - path_bytes = path.as_ref().as_os_str().as_bytes() - } - #[cfg(not(unix))] - { - // XXX: Getting non-valid UTF8 paths into CoreFoundation on Windows is going to be unpleasant - // CFURLGetWideFileSystemRepresentation might help - path_bytes = match path.as_ref().to_str() { - Some(path) => path, - None => return None, - } - } - - unsafe { - let url_ref = CFURLCreateFromFileSystemRepresentation(ptr::null_mut(), path_bytes.as_ptr(), path_bytes.len() as CFIndex, isDirectory as u8); - if url_ref.is_null() { - return None; - } - Some(TCFType::wrap_under_create_rule(url_ref)) - } - } - - pub fn from_file_system_path(filePath: CFString, pathStyle: CFURLPathStyle, isDirectory: bool) -> CFURL { - unsafe { - let url_ref = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, filePath.as_concrete_TypeRef(), pathStyle, isDirectory as u8); - TCFType::wrap_under_create_rule(url_ref) - } - } - - #[cfg(unix)] - pub fn to_path(&self) -> Option { - // implementing this on Windows is more complicated because of the different OsStr representation - unsafe { - let mut buf: [u8; PATH_MAX as usize] = mem::uninitialized(); - let result = CFURLGetFileSystemRepresentation(self.0, true as Boolean, buf.as_mut_ptr(), buf.len() as CFIndex); - if result == false as Boolean { - return None; - } - let len = strlen(buf.as_ptr() as *const i8); - let path = OsStr::from_bytes(&buf[0..len]); - Some(PathBuf::from(path)) - } - } - - pub fn get_string(&self) -> CFString { - unsafe { - TCFType::wrap_under_get_rule(CFURLGetString(self.0)) - } - } - - pub fn get_file_system_path(&self, pathStyle: CFURLPathStyle) -> CFString { - unsafe { - TCFType::wrap_under_create_rule(CFURLCopyFileSystemPath(self.as_concrete_TypeRef(), pathStyle)) - } - } - - pub fn absolute(&self) -> CFURL { - unsafe { - TCFType::wrap_under_create_rule(CFURLCopyAbsoluteURL(self.as_concrete_TypeRef())) - } - } -} - -#[test] -fn file_url_from_path() { - let path = "/usr/local/foo/"; - let cfstr_path = CFString::from_static_string(path); - let cfurl = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); - assert_eq!(cfurl.get_string().to_string(), "file:///usr/local/foo/"); -} - -#[cfg(unix)] -#[test] -fn non_utf8() { - use std::ffi::OsStr; - let path = Path::new(OsStr::from_bytes(b"/\xC0/blame")); - let cfurl = CFURL::from_path(path, false).unwrap(); - assert_eq!(cfurl.to_path().unwrap(), path); - let len = unsafe { CFURLGetBytes(cfurl.as_concrete_TypeRef(), ptr::null_mut(), 0) }; - assert_eq!(len, 17); -} - -#[test] -fn absolute_file_url() { - use core_foundation_sys::url::CFURLCreateWithFileSystemPathRelativeToBase; - use std::path::PathBuf; - - let path = "/usr/local/foo"; - let file = "bar"; - - let cfstr_path = CFString::from_static_string(path); - let cfstr_file = CFString::from_static_string(file); - let cfurl_base = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); - let cfurl_relative: CFURL = unsafe { - let url_ref = CFURLCreateWithFileSystemPathRelativeToBase(kCFAllocatorDefault, - cfstr_file.as_concrete_TypeRef(), - kCFURLPOSIXPathStyle, - false as u8, - cfurl_base.as_concrete_TypeRef()); - TCFType::wrap_under_create_rule(url_ref) - }; - - let mut absolute_path = PathBuf::from(path); - absolute_path.push(file); - - assert_eq!(cfurl_relative.get_file_system_path(kCFURLPOSIXPathStyle).to_string(), file); - assert_eq!(cfurl_relative.absolute().get_file_system_path(kCFURLPOSIXPathStyle).to_string(), - absolute_path.to_str().unwrap()); -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.4.6/src/uuid.rs cargo-0.26.0/vendor/core-foundation-0.4.6/src/uuid.rs --- cargo-0.25.0/vendor/core-foundation-0.4.6/src/uuid.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.4.6/src/uuid.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,118 +0,0 @@ -// Copyright 2013 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Core Foundation UUID objects. - -#[cfg(feature = "with-uuid")] -extern crate uuid; - -pub use core_foundation_sys::uuid::*; -use core_foundation_sys::base::{CFRelease, kCFAllocatorDefault}; - -use base::TCFType; - -#[cfg(feature = "with-uuid")] -use self::uuid::Uuid; - -/// A UUID. -pub struct CFUUID(CFUUIDRef); - -impl Drop for CFUUID { - fn drop(&mut self) { - unsafe { - CFRelease(self.as_CFTypeRef()) - } - } -} - -impl_TCFType!(CFUUID, CFUUIDRef, CFUUIDGetTypeID); -impl_CFTypeDescription!(CFUUID); - -impl CFUUID { - #[inline] - pub fn new() -> CFUUID { - unsafe { - let uuid_ref = CFUUIDCreate(kCFAllocatorDefault); - TCFType::wrap_under_create_rule(uuid_ref) - } - } -} - -#[cfg(feature = "with-uuid")] -impl Into for CFUUID { - fn into(self) -> Uuid { - let b = unsafe { - CFUUIDGetUUIDBytes(self.0) - }; - let bytes = [ - b.byte0, - b.byte1, - b.byte2, - b.byte3, - b.byte4, - b.byte5, - b.byte6, - b.byte7, - b.byte8, - b.byte9, - b.byte10, - b.byte11, - b.byte12, - b.byte13, - b.byte14, - b.byte15, - ]; - Uuid::from_bytes(&bytes).unwrap() - } -} - -#[cfg(feature = "with-uuid")] -impl From for CFUUID { - fn from(uuid: Uuid) -> CFUUID { - let b = uuid.as_bytes(); - let bytes = CFUUIDBytes { - byte0: b[0], - byte1: b[1], - byte2: b[2], - byte3: b[3], - byte4: b[4], - byte5: b[5], - byte6: b[6], - byte7: b[7], - byte8: b[8], - byte9: b[9], - byte10: b[10], - byte11: b[11], - byte12: b[12], - byte13: b[13], - byte14: b[14], - byte15: b[15], - }; - unsafe { - let uuid_ref = CFUUIDCreateFromUUIDBytes(kCFAllocatorDefault, bytes); - TCFType::wrap_under_create_rule(uuid_ref) - } - } -} - - -#[cfg(test)] -#[cfg(feature = "with-uuid")] -mod test { - use super::CFUUID; - use uuid::Uuid; - - #[test] - fn uuid_conversion() { - let cf_uuid = CFUUID::new(); - let uuid: Uuid = cf_uuid.clone().into(); - let converted = CFUUID::from(uuid); - assert!(cf_uuid == converted); - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/.cargo-checksum.json cargo-0.26.0/vendor/core-foundation-0.5.1/.cargo-checksum.json --- cargo-0.25.0/vendor/core-foundation-0.5.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"286e0b41c3a20da26536c6000a280585d519fd07b3956b43aed8a79e9edce980"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/Cargo.toml cargo-0.26.0/vendor/core-foundation-0.5.1/Cargo.toml --- cargo-0.25.0/vendor/core-foundation-0.5.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,39 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "core-foundation" +version = "0.5.1" +authors = ["The Servo Project Developers"] +description = "Bindings to Core Foundation for OS X" +homepage = "https://github.com/servo/core-foundation-rs" +license = "MIT / Apache-2.0" +repository = "https://github.com/servo/core-foundation-rs" +[dependencies.chrono] +version = "0.4" +optional = true + +[dependencies.core-foundation-sys] +version = "0.5.1" + +[dependencies.libc] +version = "0.2" + +[dependencies.uuid] +version = "0.5" +optional = true + +[features] +mac_os_10_7_support = ["core-foundation-sys/mac_os_10_7_support"] +mac_os_10_8_features = ["core-foundation-sys/mac_os_10_8_features"] +with-chrono = ["chrono"] +with-uuid = ["uuid"] diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/LICENSE-APACHE cargo-0.26.0/vendor/core-foundation-0.5.1/LICENSE-APACHE --- cargo-0.25.0/vendor/core-foundation-0.5.1/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/LICENSE-MIT cargo-0.26.0/vendor/core-foundation-0.5.1/LICENSE-MIT --- cargo-0.25.0/vendor/core-foundation-0.5.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2012-2013 Mozilla Foundation + +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. diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/array.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/array.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/array.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/array.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,289 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Heterogeneous immutable arrays. + +pub use core_foundation_sys::array::*; +pub use core_foundation_sys::base::CFIndex; +use core_foundation_sys::base::{CFTypeRef, CFRelease, kCFAllocatorDefault}; +use libc::c_void; +use std::mem; +use std::mem::ManuallyDrop; +use std::marker::PhantomData; +use std; +use std::ops::Deref; +use std::fmt::{Debug, Formatter}; + +use base::{CFIndexConvertible, TCFType, TCFTypeRef, CFRange}; + +/// A heterogeneous immutable array. +pub struct CFArray(CFArrayRef, PhantomData); + +/// A reference to an element inside the array +pub struct ItemRef<'a, T: 'a>(ManuallyDrop, PhantomData<&'a T>); + +impl<'a, T> Deref for ItemRef<'a, T> { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +impl<'a, T: Debug> Debug for ItemRef<'a, T> { + fn fmt(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> { + self.0.fmt(f) + } +} + +/// A trait describing how to convert from the stored *const c_void to the desired T +pub unsafe trait FromVoid { + unsafe fn from_void<'a>(x: *const c_void) -> ItemRef<'a, Self> where Self: std::marker::Sized; +} + +unsafe impl FromVoid for u32 { + unsafe fn from_void<'a>(x: *const c_void) -> ItemRef<'a, Self> { + // Functions like CGFontCopyTableTags treat the void*'s as u32's + // so we convert by casting directly + ItemRef(ManuallyDrop::new(x as u32), PhantomData) + } +} + +unsafe impl FromVoid for T { + unsafe fn from_void<'a>(x: *const c_void) -> ItemRef<'a, Self> { + ItemRef(ManuallyDrop::new(TCFType::wrap_under_create_rule(T::Ref::from_void_ptr(x))), PhantomData) + } +} + +impl Drop for CFArray { + fn drop(&mut self) { + unsafe { CFRelease(self.as_CFTypeRef()) } + } +} + +pub struct CFArrayIterator<'a, T: 'a> { + array: &'a CFArray, + index: CFIndex, + len: CFIndex, +} + +impl<'a, T: FromVoid> Iterator for CFArrayIterator<'a, T> { + type Item = ItemRef<'a, T>; + + fn next(&mut self) -> Option> { + if self.index >= self.len { + None + } else { + let value = unsafe { self.array.get_unchecked(self.index) }; + self.index += 1; + Some(value) + } + } +} + +impl<'a, T: FromVoid> ExactSizeIterator for CFArrayIterator<'a, T> { + fn len(&self) -> usize { + (self.array.len() - self.index) as usize + } +} + +impl_TCFTypeGeneric!(CFArray, CFArrayRef, CFArrayGetTypeID); +impl_CFTypeDescriptionGeneric!(CFArray); + +impl CFArray { + /// Creates a new `CFArray` with the given elements, which must be `CFType` objects. + pub fn from_CFTypes(elems: &[T]) -> CFArray where T: TCFType { + unsafe { + let elems: Vec = elems.iter().map(|elem| elem.as_CFTypeRef()).collect(); + let array_ref = CFArrayCreate(kCFAllocatorDefault, + mem::transmute(elems.as_ptr()), + elems.len().to_CFIndex(), + &kCFTypeArrayCallBacks); + TCFType::wrap_under_create_rule(array_ref) + } + } + + #[inline] + pub fn to_untyped(&self) -> CFArray { + unsafe { CFArray::wrap_under_get_rule(self.0) } + } + + /// Returns the same array, but with the type reset to void pointers. + /// Equal to `to_untyped`, but is faster since it does not increment the retain count. + #[inline] + pub fn into_untyped(self) -> CFArray { + let reference = self.0; + mem::forget(self); + unsafe { CFArray::wrap_under_create_rule(reference) } + } + + /// Iterates over the elements of this `CFArray`. + /// + /// Careful; the loop body must wrap the reference properly. Generally, when array elements are + /// Core Foundation objects (not always true), they need to be wrapped with + /// `TCFType::wrap_under_get_rule()`. + #[inline] + pub fn iter<'a>(&'a self) -> CFArrayIterator<'a, T> { + CFArrayIterator { + array: self, + index: 0, + len: self.len(), + } + } + + #[inline] + pub fn len(&self) -> CFIndex { + unsafe { + CFArrayGetCount(self.0) + } + } + + #[inline] + pub unsafe fn get_unchecked<'a>(&'a self, index: CFIndex) -> ItemRef<'a, T> where T: FromVoid { + T::from_void(CFArrayGetValueAtIndex(self.0, index)) + } + + #[inline] + pub fn get<'a>(&'a self, index: CFIndex) -> Option> where T: FromVoid { + if index < self.len() { + Some(unsafe { T::from_void(CFArrayGetValueAtIndex(self.0, index)) } ) + } else { + None + } + } + + pub fn get_values(&self, range: CFRange) -> Vec<*const c_void> { + let mut vec = Vec::with_capacity(range.length as usize); + unsafe { + CFArrayGetValues(self.0, range, vec.as_mut_ptr()); + vec.set_len(range.length as usize); + vec + } + } + + pub fn get_all_values(&self) -> Vec<*const c_void> { + self.get_values(CFRange { + location: 0, + length: self.len() + }) + } +} + +impl<'a, T: FromVoid> IntoIterator for &'a CFArray { + type Item = ItemRef<'a, T>; + type IntoIter = CFArrayIterator<'a, T>; + + fn into_iter(self) -> CFArrayIterator<'a, T> { + self.iter() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::mem; + use base::CFType; + + #[test] + fn to_untyped_correct_retain_count() { + let array = CFArray::::from_CFTypes(&[]); + assert_eq!(array.retain_count(), 1); + + let untyped_array = array.to_untyped(); + assert_eq!(array.retain_count(), 2); + assert_eq!(untyped_array.retain_count(), 2); + + mem::drop(array); + assert_eq!(untyped_array.retain_count(), 1); + } + + #[test] + fn into_untyped() { + let array = CFArray::::from_CFTypes(&[]); + let array2 = array.to_untyped(); + assert_eq!(array.retain_count(), 2); + + let untyped_array = array.into_untyped(); + assert_eq!(untyped_array.retain_count(), 2); + + mem::drop(array2); + assert_eq!(untyped_array.retain_count(), 1); + } + + #[test] + fn borrow() { + use string::CFString; + + let string = CFString::from_static_string("bar"); + assert_eq!(string.retain_count(), 1); + let x; + { + let arr: CFArray = CFArray::from_CFTypes(&[string]); + { + let p = arr.get(0).unwrap(); + assert_eq!(p.retain_count(), 1); + } + { + x = arr.get(0).unwrap().clone(); + assert_eq!(x.retain_count(), 2); + assert_eq!(x.to_string(), "bar"); + } + } + assert_eq!(x.retain_count(), 1); + } + + #[test] + fn should_box_and_unbox() { + use number::CFNumber; + + let n0 = CFNumber::from(0); + let n1 = CFNumber::from(1); + let n2 = CFNumber::from(2); + let n3 = CFNumber::from(3); + let n4 = CFNumber::from(4); + let n5 = CFNumber::from(5); + + let arr = CFArray::from_CFTypes(&[ + n0.as_CFType(), + n1.as_CFType(), + n2.as_CFType(), + n3.as_CFType(), + n4.as_CFType(), + n5.as_CFType(), + ]); + + assert!(arr.get_all_values() == &[n0.as_CFTypeRef(), + n1.as_CFTypeRef(), + n2.as_CFTypeRef(), + n3.as_CFTypeRef(), + n4.as_CFTypeRef(), + n5.as_CFTypeRef()]); + + let mut sum = 0; + + let mut iter = arr.iter(); + assert_eq!(iter.len(), 6); + assert!(iter.next().is_some()); + assert_eq!(iter.len(), 5); + + for elem in iter { + let number: CFNumber = elem.downcast::().unwrap(); + sum += number.to_i64().unwrap() + } + + assert!(sum == 15); + + for elem in arr.iter() { + let number: CFNumber = elem.downcast::().unwrap(); + sum += number.to_i64().unwrap() + } + + assert!(sum == 30); + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/base.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/base.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/base.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/base.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,293 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::fmt; +use std::mem; + +pub use core_foundation_sys::base::*; + +use string::CFString; + +pub trait CFIndexConvertible { + /// Always use this method to construct a `CFIndex` value. It performs bounds checking to + /// ensure the value is in range. + fn to_CFIndex(self) -> CFIndex; +} + +impl CFIndexConvertible for usize { + #[inline] + fn to_CFIndex(self) -> CFIndex { + let max_CFIndex = CFIndex::max_value(); + if self > (max_CFIndex as usize) { + panic!("value out of range") + } + self as CFIndex + } +} + +declare_TCFType!{ + /// Superclass of all Core Foundation objects. + CFType, CFTypeRef +} + +impl CFType { + /// Try to downcast the `CFType` to a subclass. Checking if the instance is the + /// correct subclass happens at runtime and `None` is returned if it is not the correct type. + /// Works similar to [`Box::downcast`] and [`CFPropertyList::downcast`]. + /// + /// # Examples + /// + /// ``` + /// # use core_foundation::string::CFString; + /// # use core_foundation::boolean::CFBoolean; + /// # use core_foundation::base::{CFType, TCFType}; + /// # + /// // Create a string. + /// let string: CFString = CFString::from_static_string("FooBar"); + /// // Cast it up to a CFType. + /// let cf_type: CFType = string.as_CFType(); + /// // Cast it down again. + /// assert!(cf_type.downcast::().unwrap().to_string() == "FooBar"); + /// // Casting it to some other type will yield `None` + /// assert!(cf_type.downcast::().is_none()); + /// ``` + /// + /// [`Box::downcast`]: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.downcast + /// [`CFPropertyList::downcast`]: ../propertylist/struct.CFPropertyList.html#method.downcast + #[inline] + pub fn downcast(&self) -> Option { + if self.instance_of::() { + unsafe { + let reference = T::Ref::from_void_ptr(self.0); + Some(T::wrap_under_get_rule(reference)) + } + } else { + None + } + } + + /// Similar to [`downcast`], but consumes self and can thus avoid touching the retain count. + /// + /// [`downcast`]: #method.downcast + #[inline] + pub fn downcast_into(self) -> Option { + if self.instance_of::() { + unsafe { + let reference = T::Ref::from_void_ptr(self.0); + mem::forget(self); + Some(T::wrap_under_create_rule(reference)) + } + } else { + None + } + } +} + +impl fmt::Debug for CFType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let desc = unsafe { + CFString::wrap_under_create_rule(CFCopyDescription(self.0)) + }; + desc.fmt(f) + } +} + +impl Clone for CFType { + #[inline] + fn clone(&self) -> CFType { + unsafe { + TCFType::wrap_under_get_rule(self.0) + } + } +} + +impl PartialEq for CFType { + #[inline] + fn eq(&self, other: &CFType) -> bool { + unsafe { + CFEqual(self.as_CFTypeRef(), other.as_CFTypeRef()) != 0 + } + } +} + +declare_TCFType!(CFAllocator, CFAllocatorRef); +impl_TCFType!(CFAllocator, CFAllocatorRef, CFAllocatorGetTypeID); + +impl CFAllocator { + #[inline] + pub fn new(mut context: CFAllocatorContext) -> CFAllocator { + unsafe { + let allocator_ref = CFAllocatorCreate(kCFAllocatorDefault, &mut context); + TCFType::wrap_under_create_rule(allocator_ref) + } + } +} + + +/// All Core Foundation types implement this trait. The associated type `Ref` specifies the +/// associated Core Foundation type: e.g. for `CFType` this is `CFTypeRef`; for `CFArray` this is +/// `CFArrayRef`. +pub trait TCFType { + /// The reference type wrapped inside this type. + type Ref: TCFTypeRef; + + /// Returns the object as its concrete TypeRef. + fn as_concrete_TypeRef(&self) -> Self::Ref; + + /// Returns an instance of the object, wrapping the underlying `CFTypeRef` subclass. Use this + /// when following Core Foundation's "Create Rule". The reference count is *not* bumped. + unsafe fn wrap_under_create_rule(obj: Self::Ref) -> Self; + + /// Returns the type ID for this class. + fn type_id() -> CFTypeID; + + /// Returns the object as a wrapped `CFType`. The reference count is incremented by one. + #[inline] + fn as_CFType(&self) -> CFType { + unsafe { + TCFType::wrap_under_get_rule(self.as_CFTypeRef()) + } + } + + /// Returns the object as a wrapped `CFType`. Consumes self and avoids changing the reference + /// count. + #[inline] + fn into_CFType(self) -> CFType + where + Self: Sized, + { + let reference = self.as_CFTypeRef(); + mem::forget(self); + unsafe { TCFType::wrap_under_create_rule(reference) } + } + + /// Returns the object as a raw `CFTypeRef`. The reference count is not adjusted. + fn as_CFTypeRef(&self) -> CFTypeRef; + + /// Returns an instance of the object, wrapping the underlying `CFTypeRef` subclass. Use this + /// when following Core Foundation's "Get Rule". The reference count *is* bumped. + unsafe fn wrap_under_get_rule(reference: Self::Ref) -> Self; + + /// Returns the reference count of the object. It is unwise to do anything other than test + /// whether the return value of this method is greater than zero. + #[inline] + fn retain_count(&self) -> CFIndex { + unsafe { + CFGetRetainCount(self.as_CFTypeRef()) + } + } + + /// Returns the type ID of this object. + #[inline] + fn type_of(&self) -> CFTypeID { + unsafe { + CFGetTypeID(self.as_CFTypeRef()) + } + } + + /// Writes a debugging version of this object on standard error. + fn show(&self) { + unsafe { + CFShow(self.as_CFTypeRef()) + } + } + + /// Returns true if this value is an instance of another type. + #[inline] + fn instance_of(&self) -> bool { + self.type_of() == OtherCFType::type_id() + } +} + +impl TCFType for CFType { + type Ref = CFTypeRef; + + #[inline] + fn as_concrete_TypeRef(&self) -> CFTypeRef { + self.0 + } + + #[inline] + unsafe fn wrap_under_get_rule(reference: CFTypeRef) -> CFType { + let reference: CFTypeRef = CFRetain(reference); + TCFType::wrap_under_create_rule(reference) + } + + #[inline] + fn as_CFTypeRef(&self) -> CFTypeRef { + self.as_concrete_TypeRef() + } + + #[inline] + unsafe fn wrap_under_create_rule(obj: CFTypeRef) -> CFType { + CFType(obj) + } + + #[inline] + fn type_id() -> CFTypeID { + // FIXME(pcwalton): Is this right? + 0 + } +} + + +#[cfg(test)] +mod tests { + use super::*; + use std::mem; + use boolean::CFBoolean; + + #[test] + fn cftype_instance_of() { + let string = CFString::from_static_string("foo"); + let cftype = string.as_CFType(); + + assert!(cftype.instance_of::()); + assert!(!cftype.instance_of::()); + } + + #[test] + fn as_cftype_retain_count() { + let string = CFString::from_static_string("bar"); + assert_eq!(string.retain_count(), 1); + let cftype = string.as_CFType(); + assert_eq!(cftype.retain_count(), 2); + mem::drop(string); + assert_eq!(cftype.retain_count(), 1); + } + + #[test] + fn into_cftype_retain_count() { + let string = CFString::from_static_string("bar"); + assert_eq!(string.retain_count(), 1); + let cftype = string.into_CFType(); + assert_eq!(cftype.retain_count(), 1); + } + + #[test] + fn as_cftype_and_downcast() { + let string = CFString::from_static_string("bar"); + let cftype = string.as_CFType(); + let string2 = cftype.downcast::().unwrap(); + assert_eq!(string2.to_string(), "bar"); + + assert_eq!(string.retain_count(), 3); + assert_eq!(cftype.retain_count(), 3); + assert_eq!(string2.retain_count(), 3); + } + + #[test] + fn into_cftype_and_downcast_into() { + let string = CFString::from_static_string("bar"); + let cftype = string.into_CFType(); + let string2 = cftype.downcast_into::().unwrap(); + assert_eq!(string2.to_string(), "bar"); + assert_eq!(string2.retain_count(), 1); + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/boolean.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/boolean.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/boolean.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/boolean.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,70 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A Boolean type. + +pub use core_foundation_sys::number::{CFBooleanRef, CFBooleanGetTypeID, kCFBooleanTrue, kCFBooleanFalse}; + +use base::TCFType; + + +declare_TCFType!{ + /// A Boolean type. + /// + /// FIXME(pcwalton): Should be a newtype struct, but that fails due to a Rust compiler bug. + CFBoolean, CFBooleanRef +} +impl_TCFType!(CFBoolean, CFBooleanRef, CFBooleanGetTypeID); +impl_CFTypeDescription!(CFBoolean); + +impl CFBoolean { + pub fn true_value() -> CFBoolean { + unsafe { + TCFType::wrap_under_get_rule(kCFBooleanTrue) + } + } + + pub fn false_value() -> CFBoolean { + unsafe { + TCFType::wrap_under_get_rule(kCFBooleanFalse) + } + } +} + +impl From for CFBoolean { + fn from(value: bool) -> CFBoolean { + if value { + CFBoolean::true_value() + } else { + CFBoolean::false_value() + } + } +} + +impl From for bool { + fn from(value: CFBoolean) -> bool { + value.0 == unsafe { kCFBooleanTrue } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn to_and_from_bool() { + let b_false = CFBoolean::from(false); + let b_true = CFBoolean::from(true); + assert_ne!(b_false, b_true); + assert_eq!(b_false, CFBoolean::false_value()); + assert_eq!(b_true, CFBoolean::true_value()); + assert!(!bool::from(b_false)); + assert!(bool::from(b_true)); + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/bundle.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/bundle.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/bundle.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/bundle.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,122 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation Bundle Type + +pub use core_foundation_sys::bundle::*; +use core_foundation_sys::base::kCFAllocatorDefault; + +use base::TCFType; +use url::CFURL; +use dictionary::CFDictionary; + + +declare_TCFType!{ + /// A Bundle type. + CFBundle, CFBundleRef +} +impl_TCFType!(CFBundle, CFBundleRef, CFBundleGetTypeID); + +impl CFBundle { + pub fn new(bundleURL: CFURL) -> Option { + unsafe { + let bundle_ref = CFBundleCreate(kCFAllocatorDefault, bundleURL.as_concrete_TypeRef()); + if bundle_ref.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(bundle_ref)) + } + } + } + + pub fn main_bundle() -> CFBundle { + unsafe { + let bundle_ref = CFBundleGetMainBundle(); + TCFType::wrap_under_get_rule(bundle_ref) + } + } + + pub fn info_dictionary(&self) -> CFDictionary { + unsafe { + let info_dictionary = CFBundleGetInfoDictionary(self.0); + TCFType::wrap_under_get_rule(info_dictionary) + } + } + + pub fn executable_url(&self) -> Option { + unsafe { + let exe_url = CFBundleCopyExecutableURL(self.0); + if exe_url.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(exe_url)) + } + } + } + + pub fn private_frameworks_url(&self) -> Option { + unsafe { + let fw_url = CFBundleCopyPrivateFrameworksURL(self.0); + if fw_url.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(fw_url)) + } + } + } +} + + +#[test] +fn safari_executable_url() { + use string::CFString; + use url::{CFURL, kCFURLPOSIXPathStyle}; + + let cfstr_path = CFString::from_static_string("/Applications/Safari.app"); + let cfurl_path = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); + let cfurl_executable = CFBundle::new(cfurl_path) + .expect("Safari not present") + .executable_url(); + assert!(cfurl_executable.is_some()); + assert_eq!(cfurl_executable + .unwrap() + .absolute() + .get_file_system_path(kCFURLPOSIXPathStyle) + .to_string(), + "/Applications/Safari.app/Contents/MacOS/Safari"); +} + +#[test] +fn safari_private_frameworks_url() { + use string::CFString; + use url::{CFURL, kCFURLPOSIXPathStyle}; + + let cfstr_path = CFString::from_static_string("/Applications/Safari.app"); + let cfurl_path = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); + let cfurl_executable = CFBundle::new(cfurl_path) + .expect("Safari not present") + .private_frameworks_url(); + assert!(cfurl_executable.is_some()); + assert_eq!(cfurl_executable + .unwrap() + .absolute() + .get_file_system_path(kCFURLPOSIXPathStyle) + .to_string(), + "/Applications/Safari.app/Contents/Frameworks"); +} + +#[test] +fn non_existant_bundle() { + use string::CFString; + use url::{CFURL, kCFURLPOSIXPathStyle}; + + let cfstr_path = CFString::from_static_string("/usr/local/foo"); + let cfurl_path = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); + assert!(CFBundle::new(cfurl_path).is_none()); +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/data.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/data.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/data.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/data.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,63 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation byte buffers. + +pub use core_foundation_sys::data::*; +use core_foundation_sys::base::CFIndex; +use core_foundation_sys::base::{kCFAllocatorDefault}; +use std::ops::Deref; +use std::slice; + +use base::{CFIndexConvertible, TCFType}; + + +declare_TCFType!{ + /// A byte buffer. + CFData, CFDataRef +} +impl_TCFType!(CFData, CFDataRef, CFDataGetTypeID); +impl_CFTypeDescription!(CFData); + +impl CFData { + pub fn from_buffer(buffer: &[u8]) -> CFData { + unsafe { + let data_ref = CFDataCreate(kCFAllocatorDefault, + buffer.as_ptr(), + buffer.len().to_CFIndex()); + TCFType::wrap_under_create_rule(data_ref) + } + } + + /// Returns a pointer to the underlying bytes in this data. Note that this byte buffer is + /// read-only. + #[inline] + pub fn bytes<'a>(&'a self) -> &'a [u8] { + unsafe { + slice::from_raw_parts(CFDataGetBytePtr(self.0), self.len() as usize) + } + } + + /// Returns the length of this byte buffer. + #[inline] + pub fn len(&self) -> CFIndex { + unsafe { + CFDataGetLength(self.0) + } + } +} + +impl Deref for CFData { + type Target = [u8]; + + #[inline] + fn deref(&self) -> &[u8] { + self.bytes() + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/date.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/date.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/date.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/date.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,130 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation date objects. + +pub use core_foundation_sys::date::*; +use core_foundation_sys::base::kCFAllocatorDefault; + +use base::TCFType; + +#[cfg(feature = "with-chrono")] +use chrono::NaiveDateTime; + + +declare_TCFType!{ + /// A date. + CFDate, CFDateRef +} +impl_TCFType!(CFDate, CFDateRef, CFDateGetTypeID); +impl_CFTypeDescription!(CFDate); +impl_CFComparison!(CFDate, CFDateCompare); + +impl CFDate { + #[inline] + pub fn new(time: CFAbsoluteTime) -> CFDate { + unsafe { + let date_ref = CFDateCreate(kCFAllocatorDefault, time); + TCFType::wrap_under_create_rule(date_ref) + } + } + + #[inline] + pub fn now() -> CFDate { + CFDate::new(unsafe { CFAbsoluteTimeGetCurrent() }) + } + + #[inline] + pub fn abs_time(&self) -> CFAbsoluteTime { + unsafe { + CFDateGetAbsoluteTime(self.0) + } + } + + #[cfg(feature = "with-chrono")] + pub fn naive_utc(&self) -> NaiveDateTime { + let ts = unsafe { + self.abs_time() + kCFAbsoluteTimeIntervalSince1970 + }; + let (secs, nanos) = if ts.is_sign_positive() { + (ts.trunc() as i64, ts.fract()) + } else { + // nanoseconds can't be negative in NaiveDateTime + (ts.trunc() as i64 - 1, 1.0 - ts.fract().abs()) + }; + NaiveDateTime::from_timestamp(secs, (nanos * 1e9).floor() as u32) + } + + #[cfg(feature = "with-chrono")] + pub fn from_naive_utc(time: NaiveDateTime) -> CFDate { + let secs = time.timestamp(); + let nanos = time.timestamp_subsec_nanos(); + let ts = unsafe { + secs as f64 + (nanos as f64 / 1e9) - kCFAbsoluteTimeIntervalSince1970 + }; + CFDate::new(ts) + } +} + +#[cfg(test)] +mod test { + use super::CFDate; + use std::cmp::Ordering; + + #[cfg(feature = "with-chrono")] + use chrono::NaiveDateTime; + + #[cfg(feature = "with-chrono")] + fn approx_eq(a: f64, b: f64) -> bool { + use std::f64; + + let same_sign = a.is_sign_positive() == b.is_sign_positive(); + let equal = ((a - b).abs() / f64::min(a.abs() + b.abs(), f64::MAX)) < f64::EPSILON; + (same_sign && equal) + } + + #[test] + fn date_comparison() { + let now = CFDate::now(); + let past = CFDate::new(now.abs_time() - 1.0); + assert_eq!(now.cmp(&past), Ordering::Greater); + assert_eq!(now.cmp(&now), Ordering::Equal); + assert_eq!(past.cmp(&now), Ordering::Less); + } + + #[test] + fn date_equality() { + let now = CFDate::now(); + let same_time = CFDate::new(now.abs_time()); + assert_eq!(now, same_time); + } + + #[test] + #[cfg(feature = "with-chrono")] + fn date_chrono_conversion_positive() { + let date = CFDate::now(); + let datetime = date.naive_utc(); + let converted = CFDate::from_naive_utc(datetime); + assert!(approx_eq(date.abs_time(), converted.abs_time())); + } + + #[test] + #[cfg(feature = "with-chrono")] + fn date_chrono_conversion_negative() { + use super::kCFAbsoluteTimeIntervalSince1970; + + let ts = unsafe { + kCFAbsoluteTimeIntervalSince1970 - 420.0 + }; + let date = CFDate::new(ts); + let datetime: NaiveDateTime = date.naive_utc(); + let converted = CFDate::from_naive_utc(datetime); + assert!(approx_eq(date.abs_time(), converted.abs_time())); + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/dictionary.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/dictionary.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/dictionary.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/dictionary.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,391 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Dictionaries of key-value pairs. + +pub use core_foundation_sys::dictionary::*; + +use core_foundation_sys::base::{CFTypeRef, kCFAllocatorDefault}; +use libc::c_void; +use std::mem; +use std::ptr; + +use base::{CFType, CFIndexConvertible, TCFType, TCFTypeRef}; + + +declare_TCFType!{ + /// An immutable dictionary of key-value pairs. + CFDictionary, CFDictionaryRef +} +impl_TCFType!(CFDictionary, CFDictionaryRef, CFDictionaryGetTypeID); +impl_CFTypeDescription!(CFDictionary); + +impl CFDictionary { + pub fn from_CFType_pairs(pairs: &[(K, V)]) -> CFDictionary { + let (keys, values): (Vec, Vec) = pairs + .iter() + .map(|&(ref key, ref value)| (key.as_CFTypeRef(), value.as_CFTypeRef())) + .unzip(); + + unsafe { + let dictionary_ref = CFDictionaryCreate(kCFAllocatorDefault, + mem::transmute(keys.as_ptr()), + mem::transmute(values.as_ptr()), + keys.len().to_CFIndex(), + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + TCFType::wrap_under_create_rule(dictionary_ref) + } + } + + #[inline] + pub fn len(&self) -> usize { + unsafe { + CFDictionaryGetCount(self.0) as usize + } + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + #[inline] + pub fn contains_key(&self, key: *const c_void) -> bool { + unsafe { CFDictionaryContainsKey(self.0, key) != 0 } + } + + /// Similar to `contains_key` but acts on a higher level, automatically converting from any + /// `TCFType` to the raw pointer of its concrete TypeRef. + #[inline] + pub fn contains_key2(&self, key: &K) -> bool { + self.contains_key(key.as_concrete_TypeRef().as_void_ptr()) + } + + #[inline] + pub fn find(&self, key: *const c_void) -> Option<*const c_void> { + unsafe { + let mut value: *const c_void = ptr::null(); + if CFDictionaryGetValueIfPresent(self.0, key, &mut value) != 0 { + Some(value) + } else { + None + } + } + } + + /// Similar to `find` but acts on a higher level, automatically converting from any `TCFType` + /// to the raw pointer of its concrete TypeRef. + #[inline] + pub fn find2(&self, key: &K) -> Option<*const c_void> { + self.find(key.as_concrete_TypeRef().as_void_ptr()) + } + + /// # Panics + /// + /// Panics if the key is not present in the dictionary. Use `find` to get an `Option` instead + /// of panicking. + #[inline] + pub fn get(&self, key: *const c_void) -> *const c_void { + self.find(key).expect(&format!("No entry found for key {:p}", key)) + } + + /// A convenience function to retrieve `CFType` instances. + #[inline] + pub unsafe fn get_CFType(&self, key: *const c_void) -> CFType { + let value: CFTypeRef = mem::transmute(self.get(key)); + TCFType::wrap_under_get_rule(value) + } + + pub fn get_keys_and_values(&self) -> (Vec<*const c_void>, Vec<*const c_void>) { + let length = self.len(); + let mut keys = Vec::with_capacity(length); + let mut values = Vec::with_capacity(length); + + unsafe { + CFDictionaryGetKeysAndValues(self.0, keys.as_mut_ptr(), values.as_mut_ptr()); + keys.set_len(length); + values.set_len(length); + } + + (keys, values) + } +} + +declare_TCFType!{ + /// An mutable dictionary of key-value pairs. + CFMutableDictionary, CFMutableDictionaryRef +} + +impl_TCFType!(CFMutableDictionary, CFMutableDictionaryRef, CFDictionaryGetTypeID); +impl_CFTypeDescription!(CFMutableDictionary); + +impl CFMutableDictionary { + pub fn new() -> Self { + Self::with_capacity(0) + } + + pub fn with_capacity(capacity: isize) -> Self { + unsafe { + let dictionary_ref = CFDictionaryCreateMutable(kCFAllocatorDefault, + capacity as _, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + TCFType::wrap_under_create_rule(dictionary_ref) + } + } + + pub fn copy_with_capacity(&self, capacity: isize) -> Self { + unsafe { + let dictionary_ref = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, capacity as _, self.0); + TCFType::wrap_under_get_rule(dictionary_ref) + } + } + + pub fn from_CFType_pairs(pairs: &[(K, V)]) -> CFMutableDictionary { + let result = Self::with_capacity(pairs.len() as _); + unsafe { + for &(ref key, ref value) in pairs { + result.add(key.as_CFTypeRef(), value.as_CFTypeRef()); + } + } + result + } + + // Immutable interface + + #[inline] + pub fn len(&self) -> usize { + unsafe { + CFDictionaryGetCount(self.0) as usize + } + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + #[inline] + pub fn contains_key(&self, key: *const c_void) -> bool { + unsafe { + CFDictionaryContainsKey(self.0, key) != 0 + } + } + + /// Similar to `contains_key` but acts on a higher level, automatically converting from any + /// `TCFType` to the raw pointer of its concrete TypeRef. + #[inline] + pub fn contains_key2(&self, key: &K) -> bool { + self.contains_key(key.as_concrete_TypeRef().as_void_ptr()) + } + + #[inline] + pub fn find(&self, key: *const c_void) -> Option<*const c_void> { + unsafe { + let mut value: *const c_void = ptr::null(); + if CFDictionaryGetValueIfPresent(self.0, key, &mut value) != 0 { + Some(value) + } else { + None + } + } + } + + /// Similar to `find` but acts on a higher level, automatically converting from any `TCFType` + /// to the raw pointer of its concrete TypeRef. + #[inline] + pub fn find2(&self, key: &K) -> Option<*const c_void> { + self.find(key.as_concrete_TypeRef().as_void_ptr()) + } + + /// # Panics + /// + /// Panics if the key is not present in the dictionary. Use `find` to get an `Option` instead + /// of panicking. + #[inline] + pub fn get(&self, key: *const c_void) -> *const c_void { + self.find(key).expect(&format!("No entry found for key {:p}", key)) + } + + /// A convenience function to retrieve `CFType` instances. + #[inline] + pub unsafe fn get_CFType(&self, key: *const c_void) -> CFType { + let value: CFTypeRef = mem::transmute(self.get(key)); + TCFType::wrap_under_get_rule(value) + } + + pub fn get_keys_and_values(&self) -> (Vec<*const c_void>, Vec<*const c_void>) { + let length = self.len(); + let mut keys = Vec::with_capacity(length); + let mut values = Vec::with_capacity(length); + + unsafe { + CFDictionaryGetKeysAndValues(self.0, keys.as_mut_ptr(), values.as_mut_ptr()); + keys.set_len(length); + values.set_len(length); + } + + (keys, values) + } + + // Mutable interface + + /// Adds the key-value pair to the dictionary if no such key already exist. + #[inline] + pub unsafe fn add(&self, key: *const c_void, value: *const c_void) { + CFDictionaryAddValue(self.0, key, value) + } + + /// Similar to `add` but acts on a higher level, automatically converting from any `TCFType` + /// to the raw pointer of its concrete TypeRef. + #[inline] + pub fn add2(&self, key: &K, value: &V) { + unsafe { + self.add( + key.as_concrete_TypeRef().as_void_ptr(), + value.as_concrete_TypeRef().as_void_ptr(), + ) + } + } + + /// Sets the value of the key in the dictionary. + #[inline] + pub unsafe fn set(&self, key: *const c_void, value: *const c_void) { + CFDictionarySetValue(self.0, key, value) + } + + /// Similar to `set` but acts on a higher level, automatically converting from any `TCFType` + /// to the raw pointer of its concrete TypeRef. + #[inline] + pub fn set2(&self, key: &K, value: &V) { + unsafe { + self.set( + key.as_concrete_TypeRef().as_void_ptr(), + value.as_concrete_TypeRef().as_void_ptr(), + ) + } + } + + /// Replaces the value of the key in the dictionary. + #[inline] + pub unsafe fn replace(&self, key: *const c_void, value: *const c_void) { + CFDictionaryReplaceValue(self.0, key, value) + } + + /// Similar to `replace` but acts on a higher level, automatically converting from any `TCFType` + /// to the raw pointer of its concrete TypeRef. + #[inline] + pub fn replace2(&self, key: &K, value: &V) { + unsafe { + self.replace( + key.as_concrete_TypeRef().as_void_ptr(), + value.as_concrete_TypeRef().as_void_ptr(), + ) + } + } + + /// Removes the value of the key from the dictionary. + #[inline] + pub unsafe fn remove(&self, key: *const c_void) { + CFDictionaryRemoveValue(self.0, key); + } + + /// Similar to `remove` but acts on a higher level, automatically converting from any `TCFType` + /// to the raw pointer of its concrete TypeRef. + #[inline] + pub fn remove2(&self, key: &K) { + unsafe { self.remove(key.as_concrete_TypeRef().as_void_ptr()) } + } + + #[inline] + pub fn remove_all(&self) { + unsafe { CFDictionaryRemoveAllValues(self.0) } + } +} + + +#[cfg(test)] +pub mod test { + use super::*; + use base::TCFType; + use boolean::{CFBoolean, CFBooleanRef}; + use number::CFNumber; + use string::CFString; + + + #[test] + fn dictionary() { + let bar = CFString::from_static_string("Bar"); + let baz = CFString::from_static_string("Baz"); + let boo = CFString::from_static_string("Boo"); + let foo = CFString::from_static_string("Foo"); + let tru = CFBoolean::true_value(); + let n42 = CFNumber::from(42); + + let d = CFDictionary::from_CFType_pairs(&[ + (bar.as_CFType(), boo.as_CFType()), + (baz.as_CFType(), tru.as_CFType()), + (foo.as_CFType(), n42.as_CFType()), + ]); + + let (v1, v2) = d.get_keys_and_values(); + assert!(v1 == &[bar.as_CFTypeRef(), baz.as_CFTypeRef(), foo.as_CFTypeRef()]); + assert!(v2 == &[boo.as_CFTypeRef(), tru.as_CFTypeRef(), n42.as_CFTypeRef()]); + } + + #[test] + fn mutable_dictionary() { + let bar = CFString::from_static_string("Bar"); + let baz = CFString::from_static_string("Baz"); + let boo = CFString::from_static_string("Boo"); + let foo = CFString::from_static_string("Foo"); + let tru = CFBoolean::true_value(); + let n42 = CFNumber::from(42); + + let d = CFMutableDictionary::new(); + d.add2(&bar, &boo); + d.add2(&baz, &tru); + d.add2(&foo, &n42); + assert_eq!(d.len(), 3); + + let (v1, v2) = d.get_keys_and_values(); + assert!(v1 == &[bar.as_CFTypeRef(), baz.as_CFTypeRef(), foo.as_CFTypeRef()]); + assert!(v2 == &[boo.as_CFTypeRef(), tru.as_CFTypeRef(), n42.as_CFTypeRef()]); + + d.remove2(&baz); + assert_eq!(d.len(), 2); + + let (v1, v2) = d.get_keys_and_values(); + assert!(v1 == &[bar.as_CFTypeRef(), foo.as_CFTypeRef()]); + assert!(v2 == &[boo.as_CFTypeRef(), n42.as_CFTypeRef()]); + + d.remove_all(); + assert_eq!(d.len(), 0) + } + + #[test] + fn dict_find2_and_contains_key2() { + let dict = CFDictionary::from_CFType_pairs(&[ + ( + CFString::from_static_string("hello"), + CFBoolean::true_value(), + ), + ]); + let key = CFString::from_static_string("hello"); + let invalid_key = CFString::from_static_string("foobar"); + + assert!(dict.contains_key2(&key)); + assert!(!dict.contains_key2(&invalid_key)); + + let value = unsafe { CFBoolean::wrap_under_get_rule(dict.find2(&key).unwrap() as CFBooleanRef) }; + assert_eq!(value, CFBoolean::true_value()); + assert_eq!(dict.find2(&invalid_key), None); + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/error.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/error.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/error.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/error.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,71 @@ +// Copyright 2016 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation errors. + +pub use core_foundation_sys::error::*; + +use std::error::Error; +use std::fmt; + +use base::{CFIndex, TCFType}; +use string::CFString; + + +declare_TCFType!{ + /// An error value. + CFError, CFErrorRef +} +impl_TCFType!(CFError, CFErrorRef, CFErrorGetTypeID); + +impl fmt::Debug for CFError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("CFError") + .field("domain", &self.domain()) + .field("code", &self.code()) + .field("description", &self.description()) + .finish() + } +} + +impl fmt::Display for CFError { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "{}", self.description()) + } +} + +impl Error for CFError { + fn description(&self) -> &str { + "a Core Foundation error" + } +} + +impl CFError { + /// Returns a string identifying the domain with which this error is + /// associated. + pub fn domain(&self) -> CFString { + unsafe { + let s = CFErrorGetDomain(self.0); + CFString::wrap_under_get_rule(s) + } + } + + /// Returns the code identifying this type of error. + pub fn code(&self) -> CFIndex { + unsafe { CFErrorGetCode(self.0) } + } + + /// Returns a human-presentable description of the error. + pub fn description(&self) -> CFString { + unsafe { + let s = CFErrorCopyDescription(self.0); + CFString::wrap_under_create_rule(s) + } + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/filedescriptor.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/filedescriptor.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/filedescriptor.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/filedescriptor.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,200 @@ +pub use core_foundation_sys::filedescriptor::*; + +use core_foundation_sys::base::{Boolean, CFIndex}; +use core_foundation_sys::base::{kCFAllocatorDefault, CFOptionFlags}; + +use base::TCFType; +use runloop::CFRunLoopSource; + +use std::mem; +use std::os::unix::io::{AsRawFd, RawFd}; +use std::ptr; + +declare_TCFType!{ + CFFileDescriptor, CFFileDescriptorRef +} +impl_TCFType!(CFFileDescriptor, CFFileDescriptorRef, CFFileDescriptorGetTypeID); + +impl CFFileDescriptor { + pub fn new(fd: RawFd, + closeOnInvalidate: bool, + callout: CFFileDescriptorCallBack, + context: Option<&CFFileDescriptorContext>) -> Option { + let context = context.map_or(ptr::null(), |c| c as *const _); + unsafe { + let fd_ref = CFFileDescriptorCreate(kCFAllocatorDefault, + fd, + closeOnInvalidate as Boolean, + callout, + context); + if fd_ref.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(fd_ref)) + } + } + } + + pub fn context(&self) -> CFFileDescriptorContext { + unsafe { + let mut context: CFFileDescriptorContext = mem::uninitialized(); + CFFileDescriptorGetContext(self.0, &mut context); + context + } + } + + pub fn enable_callbacks(&self, callback_types: CFOptionFlags) { + unsafe { + CFFileDescriptorEnableCallBacks(self.0, callback_types) + } + } + + pub fn disable_callbacks(&self, callback_types: CFOptionFlags) { + unsafe { + CFFileDescriptorDisableCallBacks(self.0, callback_types) + } + } + + pub fn valid(&self) -> bool { + unsafe { + CFFileDescriptorIsValid(self.0) != 0 + } + } + + pub fn invalidate(&self) { + unsafe { + CFFileDescriptorInvalidate(self.0) + } + } + + pub fn to_run_loop_source(&self, order: CFIndex) -> Option { + unsafe { + let source_ref = CFFileDescriptorCreateRunLoopSource( + kCFAllocatorDefault, + self.0, + order + ); + if source_ref.is_null() { + None + } else { + Some(TCFType::wrap_under_create_rule(source_ref)) + } + } + } +} + +impl AsRawFd for CFFileDescriptor { + fn as_raw_fd(&self) -> RawFd { + unsafe { + CFFileDescriptorGetNativeDescriptor(self.0) + } + } +} + + +#[cfg(test)] +mod test { + extern crate libc; + + use super::*; + use std::ffi::CString; + use libc::{c_void, O_RDWR}; + use core_foundation_sys::base::{CFOptionFlags}; + use core_foundation_sys::runloop::{kCFRunLoopDefaultMode}; + use runloop::{CFRunLoop}; + + #[test] + fn test_consumed() { + let path = CString::new("/dev/null").unwrap(); + let raw_fd = unsafe { libc::open(path.as_ptr(), O_RDWR, 0) }; + let cf_fd = CFFileDescriptor::new(raw_fd, true, never_callback, None); + assert!(cf_fd.is_some()); + let cf_fd = cf_fd.unwrap(); + + assert!(cf_fd.valid()); + cf_fd.invalidate(); + assert!(!cf_fd.valid()); + + // close() should fail + assert_eq!(unsafe { libc::close(raw_fd) }, -1); + } + + #[test] + fn test_unconsumed() { + let path = CString::new("/dev/null").unwrap(); + let raw_fd = unsafe { libc::open(path.as_ptr(), O_RDWR, 0) }; + let cf_fd = CFFileDescriptor::new(raw_fd, false, never_callback, None); + assert!(cf_fd.is_some()); + let cf_fd = cf_fd.unwrap(); + + assert!(cf_fd.valid()); + cf_fd.invalidate(); + assert!(!cf_fd.valid()); + + // close() should succeed + assert_eq!(unsafe { libc::close(raw_fd) }, 0); + } + + extern "C" fn never_callback(_f: CFFileDescriptorRef, + _callback_types: CFOptionFlags, + _info_ptr: *mut c_void) { + unreachable!(); + } + + struct TestInfo { + value: CFOptionFlags + } + + #[test] + fn test_callback() { + let mut info = TestInfo { value: 0 }; + let context = CFFileDescriptorContext { + version: 0, + info: &mut info as *mut _ as *mut c_void, + retain: None, + release: None, + copyDescription: None + }; + + let path = CString::new("/dev/null").unwrap(); + let raw_fd = unsafe { libc::open(path.as_ptr(), O_RDWR, 0) }; + let cf_fd = CFFileDescriptor::new(raw_fd, true, callback, Some(&context)); + assert!(cf_fd.is_some()); + let cf_fd = cf_fd.unwrap(); + + assert!(cf_fd.valid()); + + let run_loop = CFRunLoop::get_current(); + let source = CFRunLoopSource::from_file_descriptor(&cf_fd, 0); + assert!(source.is_some()); + unsafe { + run_loop.add_source(&source.unwrap(), kCFRunLoopDefaultMode); + } + + info.value = 0; + cf_fd.enable_callbacks(kCFFileDescriptorReadCallBack); + CFRunLoop::run_current(); + assert_eq!(info.value, kCFFileDescriptorReadCallBack); + + info.value = 0; + cf_fd.enable_callbacks(kCFFileDescriptorWriteCallBack); + CFRunLoop::run_current(); + assert_eq!(info.value, kCFFileDescriptorWriteCallBack); + + info.value = 0; + cf_fd.disable_callbacks(kCFFileDescriptorReadCallBack | kCFFileDescriptorWriteCallBack); + + cf_fd.invalidate(); + assert!(!cf_fd.valid()); + } + + extern "C" fn callback(_f: CFFileDescriptorRef, callback_types: CFOptionFlags, info_ptr: *mut c_void) { + assert!(!info_ptr.is_null()); + + let info: *mut TestInfo = info_ptr as *mut TestInfo; + + unsafe { (*info).value = callback_types }; + + CFRunLoop::get_current().stop(); + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/lib.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/lib.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,212 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +#![allow(non_snake_case)] + +extern crate core_foundation_sys; +extern crate libc; + +#[cfg(feature = "with-chrono")] +extern crate chrono; + +#[macro_export] +macro_rules! declare_TCFType { + ( + $(#[$doc:meta])* + $ty:ident, $raw:ident + ) => { + $(#[$doc])* + pub struct $ty($raw); + + impl Drop for $ty { + fn drop(&mut self) { + unsafe { $crate::base::CFRelease(self.as_CFTypeRef()) } + } + } + } +} + +#[macro_export] +macro_rules! impl_TCFType { + ($ty:ident, $ty_ref:ident, $ty_id:ident) => { + impl $crate::base::TCFType for $ty { + type Ref = $ty_ref; + + #[inline] + fn as_concrete_TypeRef(&self) -> $ty_ref { + self.0 + } + + #[inline] + unsafe fn wrap_under_get_rule(reference: $ty_ref) -> $ty { + use std::mem; + let reference = mem::transmute($crate::base::CFRetain(mem::transmute(reference))); + $crate::base::TCFType::wrap_under_create_rule(reference) + } + + #[inline] + fn as_CFTypeRef(&self) -> $crate::base::CFTypeRef { + unsafe { + ::std::mem::transmute(self.as_concrete_TypeRef()) + } + } + + #[inline] + unsafe fn wrap_under_create_rule(reference: $ty_ref) -> $ty { + $ty(reference) + } + + #[inline] + fn type_id() -> $crate::base::CFTypeID { + unsafe { + $ty_id() + } + } + } + + impl Clone for $ty { + #[inline] + fn clone(&self) -> $ty { + unsafe { + $ty::wrap_under_get_rule(self.0) + } + } + } + + impl PartialEq for $ty { + #[inline] + fn eq(&self, other: &$ty) -> bool { + self.as_CFType().eq(&other.as_CFType()) + } + } + + impl Eq for $ty { } + } +} + +// This is basically identical to the implementation above. I can't +// think of a clean way to have them share code +#[macro_export] +macro_rules! impl_TCFTypeGeneric { + ($ty:ident, $ty_ref:ident, $ty_id:ident) => { + impl $crate::base::TCFType for $ty { + type Ref = $ty_ref; + + #[inline] + fn as_concrete_TypeRef(&self) -> $ty_ref { + self.0 + } + + #[inline] + unsafe fn wrap_under_get_rule(reference: $ty_ref) -> $ty { + use std::mem; + let reference = mem::transmute($crate::base::CFRetain(mem::transmute(reference))); + $crate::base::TCFType::wrap_under_create_rule(reference) + } + + #[inline] + fn as_CFTypeRef(&self) -> ::core_foundation_sys::base::CFTypeRef { + unsafe { + ::std::mem::transmute(self.as_concrete_TypeRef()) + } + } + + #[inline] + unsafe fn wrap_under_create_rule(obj: $ty_ref) -> $ty { + $ty(obj, PhantomData) + } + + #[inline] + fn type_id() -> ::core_foundation_sys::base::CFTypeID { + unsafe { + $ty_id() + } + } + } + + impl Clone for $ty { + #[inline] + fn clone(&self) -> $ty { + unsafe { + $ty::wrap_under_get_rule(self.0) + } + } + } + + impl PartialEq for $ty { + #[inline] + fn eq(&self, other: &$ty) -> bool { + self.as_CFType().eq(&other.as_CFType()) + } + } + + impl Eq for $ty { } + } +} + +#[macro_export] +macro_rules! impl_CFTypeDescription { + ($ty:ident) => { + impl ::std::fmt::Debug for $ty { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + self.as_CFType().fmt(f) + } + } + } +} + +// The same as impl_CFTypeDescription but with a type parameter +#[macro_export] +macro_rules! impl_CFTypeDescriptionGeneric { + ($ty:ident) => { + impl ::std::fmt::Debug for $ty { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + self.as_CFType().fmt(f) + } + } + } +} + +#[macro_export] +macro_rules! impl_CFComparison { + ($ty:ident, $compare:ident) => { + impl PartialOrd for $ty { + #[inline] + fn partial_cmp(&self, other: &$ty) -> Option<::std::cmp::Ordering> { + unsafe { + Some($compare(self.as_concrete_TypeRef(), other.as_concrete_TypeRef(), ::std::ptr::null_mut()).into()) + } + } + } + + impl Ord for $ty { + #[inline] + fn cmp(&self, other: &$ty) -> ::std::cmp::Ordering { + self.partial_cmp(other).unwrap() + } + } + } +} + +pub mod array; +pub mod base; +pub mod boolean; +pub mod data; +pub mod date; +pub mod dictionary; +pub mod error; +pub mod filedescriptor; +pub mod number; +pub mod set; +pub mod string; +pub mod url; +pub mod bundle; +pub mod propertylist; +pub mod runloop; +pub mod timezone; +pub mod uuid; diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/number.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/number.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/number.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/number.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,110 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Immutable numbers. + +use core_foundation_sys::base::kCFAllocatorDefault; +pub use core_foundation_sys::number::*; +use std::mem; + +use base::TCFType; + + +declare_TCFType!{ + /// An immutable numeric value. + CFNumber, CFNumberRef +} +impl_TCFType!(CFNumber, CFNumberRef, CFNumberGetTypeID); +impl_CFTypeDescription!(CFNumber); +impl_CFComparison!(CFNumber, CFNumberCompare); + +impl CFNumber { + #[inline] + pub fn to_i64(&self) -> Option { + unsafe { + let mut value: i64 = 0; + let ok = CFNumberGetValue(self.0, kCFNumberSInt64Type, mem::transmute(&mut value)); + if ok { Some(value) } else { None } + } + } + + #[inline] + pub fn to_f32(&self) -> Option { + unsafe { + let mut value: f32 = 0.0; + let ok = CFNumberGetValue(self.0, kCFNumberFloat32Type, mem::transmute(&mut value)); + if ok { Some(value) } else { None } + } + } + + #[inline] + pub fn to_f64(&self) -> Option { + unsafe { + let mut value: f64 = 0.0; + let ok = CFNumberGetValue(self.0, kCFNumberFloat64Type, mem::transmute(&mut value)); + if ok { Some(value) } else { None } + } + } +} + +impl From for CFNumber { + #[inline] + fn from(value: i32) -> Self { + unsafe { + let number_ref = CFNumberCreate( + kCFAllocatorDefault, + kCFNumberSInt32Type, + mem::transmute(&value), + ); + TCFType::wrap_under_create_rule(number_ref) + } + } +} + +impl From for CFNumber { + #[inline] + fn from(value: i64) -> Self { + unsafe { + let number_ref = CFNumberCreate( + kCFAllocatorDefault, + kCFNumberSInt64Type, + mem::transmute(&value), + ); + TCFType::wrap_under_create_rule(number_ref) + } + } +} + +impl From for CFNumber { + #[inline] + fn from(value: f32) -> Self { + unsafe { + let number_ref = CFNumberCreate( + kCFAllocatorDefault, + kCFNumberFloat32Type, + mem::transmute(&value), + ); + TCFType::wrap_under_create_rule(number_ref) + } + } +} + +impl From for CFNumber { + #[inline] + fn from(value: f64) -> Self { + unsafe { + let number_ref = CFNumberCreate( + kCFAllocatorDefault, + kCFNumberFloat64Type, + mem::transmute(&value), + ); + TCFType::wrap_under_create_rule(number_ref) + } + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/propertylist.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/propertylist.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/propertylist.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/propertylist.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,326 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation property lists + +use std::ptr; +use std::mem; + +use libc::c_void; + +use error::CFError; +use data::CFData; +use base::{CFType, TCFType, TCFTypeRef}; + +pub use core_foundation_sys::propertylist::*; +use core_foundation_sys::error::CFErrorRef; +use core_foundation_sys::base::{CFGetRetainCount, CFGetTypeID, CFIndex, CFRetain, + CFShow, CFTypeID, kCFAllocatorDefault}; + +pub fn create_with_data(data: CFData, + options: CFPropertyListMutabilityOptions) + -> Result<(*const c_void, CFPropertyListFormat), CFError> { + unsafe { + let mut error: CFErrorRef = ptr::null_mut(); + let mut format: CFPropertyListFormat = 0; + let property_list = CFPropertyListCreateWithData(kCFAllocatorDefault, + data.as_concrete_TypeRef(), + options, + &mut format, + &mut error); + if property_list.is_null() { + Err(TCFType::wrap_under_create_rule(error)) + } else { + Ok((property_list, format)) + } + } +} + +pub fn create_data(property_list: *const c_void, format: CFPropertyListFormat) -> Result { + unsafe { + let mut error: CFErrorRef = ptr::null_mut(); + let data_ref = CFPropertyListCreateData(kCFAllocatorDefault, + property_list, + format, + 0, + &mut error); + if data_ref.is_null() { + Err(TCFType::wrap_under_create_rule(error)) + } else { + Ok(TCFType::wrap_under_create_rule(data_ref)) + } + } +} + + +/// Trait for all subclasses of [`CFPropertyList`]. +/// +/// [`CFPropertyList`]: struct.CFPropertyList.html +pub trait CFPropertyListSubClass: TCFType { + /// Create an instance of the superclass type [`CFPropertyList`] for this instance. + /// + /// [`CFPropertyList`]: struct.CFPropertyList.html + #[inline] + fn to_CFPropertyList(&self) -> CFPropertyList { + unsafe { CFPropertyList::wrap_under_get_rule(self.as_concrete_TypeRef().as_void_ptr()) } + } + + /// Equal to [`to_CFPropertyList`], but consumes self and avoids changing the reference count. + /// + /// [`to_CFPropertyList`]: #method.to_CFPropertyList + #[inline] + fn into_CFPropertyList(self) -> CFPropertyList + where + Self: Sized, + { + let reference = self.as_concrete_TypeRef().as_void_ptr(); + mem::forget(self); + unsafe { CFPropertyList::wrap_under_create_rule(reference) } + } +} + +impl CFPropertyListSubClass for ::data::CFData {} +impl CFPropertyListSubClass for ::string::CFString {} +impl CFPropertyListSubClass for ::array::CFArray {} +impl CFPropertyListSubClass for ::dictionary::CFDictionary {} +impl CFPropertyListSubClass for ::date::CFDate {} +impl CFPropertyListSubClass for ::boolean::CFBoolean {} +impl CFPropertyListSubClass for ::number::CFNumber {} + + +declare_TCFType!{ + /// A CFPropertyList struct. This is superclass to [`CFData`], [`CFString`], [`CFArray`], + /// [`CFDictionary`], [`CFDate`], [`CFBoolean`], and [`CFNumber`]. + /// + /// This superclass type does not have its own `CFTypeID`, instead each instance has the `CFTypeID` + /// of the subclass it is an instance of. Thus, this type cannot implement the [`TCFType`] trait, + /// since it cannot implement the static [`TCFType::type_id()`] method. + /// + /// [`CFData`]: ../data/struct.CFData.html + /// [`CFString`]: ../string/struct.CFString.html + /// [`CFArray`]: ../array/struct.CFArray.html + /// [`CFDictionary`]: ../dictionary/struct.CFDictionary.html + /// [`CFDate`]: ../date/struct.CFDate.html + /// [`CFBoolean`]: ../boolean/struct.CFBoolean.html + /// [`CFNumber`]: ../number/struct.CFNumber.html + /// [`TCFType`]: ../base/trait.TCFType.html + /// [`TCFType::type_id()`]: ../base/trait.TCFType.html#method.type_of + CFPropertyList, CFPropertyListRef +} + +impl CFPropertyList { + #[inline] + pub fn as_concrete_TypeRef(&self) -> CFPropertyListRef { + self.0 + } + + #[inline] + pub unsafe fn wrap_under_get_rule(reference: CFPropertyListRef) -> CFPropertyList { + let reference = mem::transmute(CFRetain(mem::transmute(reference))); + CFPropertyList(reference) + } + + #[inline] + pub fn as_CFType(&self) -> CFType { + unsafe { CFType::wrap_under_get_rule(self.as_CFTypeRef()) } + } + + #[inline] + pub fn into_CFType(self) -> CFType + where + Self: Sized, + { + let reference = self.as_CFTypeRef(); + mem::forget(self); + unsafe { TCFType::wrap_under_create_rule(reference) } + } + + #[inline] + pub fn as_CFTypeRef(&self) -> ::core_foundation_sys::base::CFTypeRef { + unsafe { mem::transmute(self.as_concrete_TypeRef()) } + } + + #[inline] + pub unsafe fn wrap_under_create_rule(obj: CFPropertyListRef) -> CFPropertyList { + CFPropertyList(obj) + } + + /// Returns the reference count of the object. It is unwise to do anything other than test + /// whether the return value of this method is greater than zero. + #[inline] + pub fn retain_count(&self) -> CFIndex { + unsafe { CFGetRetainCount(self.as_CFTypeRef()) } + } + + /// Returns the type ID of this object. Will be one of CFData, CFString, CFArray, CFDictionary, + /// CFDate, CFBoolean, or CFNumber. + #[inline] + pub fn type_of(&self) -> CFTypeID { + unsafe { CFGetTypeID(self.as_CFTypeRef()) } + } + + /// Writes a debugging version of this object on standard error. + pub fn show(&self) { + unsafe { CFShow(self.as_CFTypeRef()) } + } + + /// Returns true if this value is an instance of another type. + #[inline] + pub fn instance_of(&self) -> bool { + self.type_of() == OtherCFType::type_id() + } +} + +impl Clone for CFPropertyList { + #[inline] + fn clone(&self) -> CFPropertyList { + unsafe { CFPropertyList::wrap_under_get_rule(self.0) } + } +} + +impl PartialEq for CFPropertyList { + #[inline] + fn eq(&self, other: &CFPropertyList) -> bool { + self.as_CFType().eq(&other.as_CFType()) + } +} + +impl Eq for CFPropertyList {} + +impl CFPropertyList { + /// Try to downcast the [`CFPropertyList`] to a subclass. Checking if the instance is the + /// correct subclass happens at runtime and `None` is returned if it is not the correct type. + /// Works similar to [`Box::downcast`] and [`CFType::downcast`]. + /// + /// # Examples + /// + /// ``` + /// # use core_foundation::string::CFString; + /// # use core_foundation::propertylist::{CFPropertyList, CFPropertyListSubClass}; + /// # + /// // Create a string. + /// let string: CFString = CFString::from_static_string("FooBar"); + /// // Cast it up to a property list. + /// let propertylist: CFPropertyList = string.to_CFPropertyList(); + /// // Cast it down again. + /// assert!(propertylist.downcast::().unwrap().to_string() == "FooBar"); + /// ``` + /// + /// [`CFPropertyList`]: struct.CFPropertyList.html + /// [`Box::downcast`]: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.downcast + pub fn downcast(&self) -> Option { + if self.instance_of::() { + unsafe { + let subclass_ref = T::Ref::from_void_ptr(self.0); + Some(T::wrap_under_get_rule(subclass_ref)) + } + } else { + None + } + } + + /// Similar to [`downcast`], but consumes self and can thus avoid touching the retain count. + /// + /// [`downcast`]: #method.downcast + pub fn downcast_into(self) -> Option { + if self.instance_of::() { + unsafe { + let subclass_ref = T::Ref::from_void_ptr(self.0); + mem::forget(self); + Some(T::wrap_under_create_rule(subclass_ref)) + } + } else { + None + } + } +} + + + +#[cfg(test)] +pub mod test { + use super::*; + use string::CFString; + use boolean::CFBoolean; + + #[test] + fn test_property_list_serialization() { + use base::{TCFType, CFEqual}; + use boolean::CFBoolean; + use number::CFNumber; + use dictionary::CFDictionary; + use string::CFString; + use super::*; + + let bar = CFString::from_static_string("Bar"); + let baz = CFString::from_static_string("Baz"); + let boo = CFString::from_static_string("Boo"); + let foo = CFString::from_static_string("Foo"); + let tru = CFBoolean::true_value(); + let n42 = CFNumber::from(42); + + let dict1 = CFDictionary::from_CFType_pairs(&[(bar.as_CFType(), boo.as_CFType()), + (baz.as_CFType(), tru.as_CFType()), + (foo.as_CFType(), n42.as_CFType())]); + + let data = create_data(dict1.as_CFTypeRef(), kCFPropertyListXMLFormat_v1_0).unwrap(); + let (dict2, _) = create_with_data(data, kCFPropertyListImmutable).unwrap(); + unsafe { + assert!(CFEqual(dict1.as_CFTypeRef(), dict2) == 1); + } + } + + #[test] + fn to_propertylist_retain_count() { + let string = CFString::from_static_string("Bar"); + assert_eq!(string.retain_count(), 1); + + let propertylist = string.to_CFPropertyList(); + assert_eq!(string.retain_count(), 2); + assert_eq!(propertylist.retain_count(), 2); + + mem::drop(string); + assert_eq!(propertylist.retain_count(), 1); + } + + #[test] + fn downcast_string() { + let propertylist = CFString::from_static_string("Bar").to_CFPropertyList(); + assert!(propertylist.downcast::().unwrap().to_string() == "Bar"); + assert!(propertylist.downcast::().is_none()); + } + + #[test] + fn downcast_boolean() { + let propertylist = CFBoolean::true_value().to_CFPropertyList(); + assert!(propertylist.downcast::().is_some()); + assert!(propertylist.downcast::().is_none()); + } + + #[test] + fn downcast_into_fail() { + let string = CFString::from_static_string("Bar"); + let propertylist = string.to_CFPropertyList(); + assert_eq!(string.retain_count(), 2); + + assert!(propertylist.downcast_into::().is_none()); + assert_eq!(string.retain_count(), 1); + } + + #[test] + fn downcast_into() { + let string = CFString::from_static_string("Bar"); + let propertylist = string.to_CFPropertyList(); + assert_eq!(string.retain_count(), 2); + + let string2 = propertylist.downcast_into::().unwrap(); + assert!(string2.to_string() == "Bar"); + assert_eq!(string2.retain_count(), 2); + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/runloop.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/runloop.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/runloop.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/runloop.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,199 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_upper_case_globals)] + +pub use core_foundation_sys::runloop::*; +use core_foundation_sys::base::CFIndex; +use core_foundation_sys::base::{kCFAllocatorDefault, CFOptionFlags}; +use core_foundation_sys::string::CFStringRef; + +use base::{TCFType}; +use date::{CFAbsoluteTime, CFTimeInterval}; +use filedescriptor::CFFileDescriptor; +use string::{CFString}; + +pub type CFRunLoopMode = CFStringRef; + + +declare_TCFType!(CFRunLoop, CFRunLoopRef); +impl_TCFType!(CFRunLoop, CFRunLoopRef, CFRunLoopGetTypeID); +impl_CFTypeDescription!(CFRunLoop); + +impl CFRunLoop { + pub fn get_current() -> CFRunLoop { + unsafe { + let run_loop_ref = CFRunLoopGetCurrent(); + TCFType::wrap_under_get_rule(run_loop_ref) + } + } + + pub fn get_main() -> CFRunLoop { + unsafe { + let run_loop_ref = CFRunLoopGetMain(); + TCFType::wrap_under_get_rule(run_loop_ref) + } + } + + pub fn run_current() { + unsafe { + CFRunLoopRun(); + } + } + + pub fn stop(&self) { + unsafe { + CFRunLoopStop(self.0); + } + } + + pub fn current_mode(&self) -> Option { + unsafe { + let string_ref = CFRunLoopCopyCurrentMode(self.0); + if string_ref.is_null() { + return None; + } + + let cf_string: CFString = TCFType::wrap_under_create_rule(string_ref); + Some(cf_string.to_string()) + } + } + + pub fn contains_timer(&self, timer: &CFRunLoopTimer, mode: CFRunLoopMode) -> bool { + unsafe { + CFRunLoopContainsTimer(self.0, timer.0, mode) != 0 + } + } + + pub fn add_timer(&self, timer: &CFRunLoopTimer, mode: CFRunLoopMode) { + unsafe { + CFRunLoopAddTimer(self.0, timer.0, mode); + } + } + + pub fn remove_timer(&self, timer: &CFRunLoopTimer, mode: CFRunLoopMode) { + unsafe { + CFRunLoopRemoveTimer(self.0, timer.0, mode); + } + } + + pub fn contains_source(&self, source: &CFRunLoopSource, mode: CFRunLoopMode) -> bool { + unsafe { + CFRunLoopContainsSource(self.0, source.0, mode) != 0 + } + } + + pub fn add_source(&self, source: &CFRunLoopSource, mode: CFRunLoopMode) { + unsafe { + CFRunLoopAddSource(self.0, source.0, mode); + } + } + + pub fn remove_source(&self, source: &CFRunLoopSource, mode: CFRunLoopMode) { + unsafe { + CFRunLoopRemoveSource(self.0, source.0, mode); + } + } + + pub fn contains_observer(&self, observer: &CFRunLoopObserver, mode: CFRunLoopMode) -> bool { + unsafe { + CFRunLoopContainsObserver(self.0, observer.0, mode) != 0 + } + } + + pub fn add_observer(&self, observer: &CFRunLoopObserver, mode: CFRunLoopMode) { + unsafe { + CFRunLoopAddObserver(self.0, observer.0, mode); + } + } + + pub fn remove_observer(&self, observer: &CFRunLoopObserver, mode: CFRunLoopMode) { + unsafe { + CFRunLoopRemoveObserver(self.0, observer.0, mode); + } + } + +} + + +declare_TCFType!(CFRunLoopTimer, CFRunLoopTimerRef); +impl_TCFType!(CFRunLoopTimer, CFRunLoopTimerRef, CFRunLoopTimerGetTypeID); + +impl CFRunLoopTimer { + pub fn new(fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, callout: CFRunLoopTimerCallBack, context: *mut CFRunLoopTimerContext) -> CFRunLoopTimer { + unsafe { + let timer_ref = CFRunLoopTimerCreate(kCFAllocatorDefault, fireDate, interval, flags, order, callout, context); + TCFType::wrap_under_create_rule(timer_ref) + } + } +} + + +declare_TCFType!(CFRunLoopSource, CFRunLoopSourceRef); +impl_TCFType!(CFRunLoopSource, CFRunLoopSourceRef, CFRunLoopSourceGetTypeID); + +impl CFRunLoopSource { + pub fn from_file_descriptor(fd: &CFFileDescriptor, order: CFIndex) -> Option { + fd.to_run_loop_source(order) + } +} + +declare_TCFType!(CFRunLoopObserver, CFRunLoopObserverRef); +impl_TCFType!(CFRunLoopObserver, CFRunLoopObserverRef, CFRunLoopObserverGetTypeID); + +#[cfg(test)] +mod test { + use super::*; + use date::{CFDate, CFAbsoluteTime}; + use std::mem; + use libc::c_void; + use std::sync::mpsc; + + #[test] + fn wait_200_milliseconds() { + let run_loop = CFRunLoop::get_current(); + + let now = CFDate::now().abs_time(); + let (elapsed_tx, elapsed_rx) = mpsc::channel(); + let mut info = Info { + start_time: now, + elapsed_tx, + }; + let mut context = unsafe { CFRunLoopTimerContext { + version: 0, + info: &mut info as *mut _ as *mut c_void, + retain: mem::zeroed(), + release: mem::zeroed(), + copyDescription: mem::zeroed(), + } }; + + + let run_loop_timer = CFRunLoopTimer::new(now + 0.20f64, 0f64, 0, 0, timer_popped, &mut context); + unsafe { + run_loop.add_timer(&run_loop_timer, kCFRunLoopDefaultMode); + } + CFRunLoop::run_current(); + let elapsed = elapsed_rx.try_recv().unwrap(); + println!("wait_200_milliseconds, elapsed: {}", elapsed); + assert!(elapsed > 0.19 && elapsed < 0.30); + } + + struct Info { + start_time: CFAbsoluteTime, + elapsed_tx: mpsc::Sender, + } + + extern "C" fn timer_popped(_timer: CFRunLoopTimerRef, raw_info: *mut c_void) { + let info: *mut Info = unsafe { mem::transmute(raw_info) }; + let now = CFDate::now().abs_time(); + let elapsed = now - unsafe { (*info).start_time }; + let _ = unsafe { (*info).elapsed_tx.send(elapsed) }; + CFRunLoop::get_current().stop(); + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/set.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/set.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/set.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/set.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,39 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! An immutable bag of elements. + +pub use core_foundation_sys::set::*; +use core_foundation_sys::base::{CFTypeRef, kCFAllocatorDefault}; + +use base::{CFIndexConvertible, TCFType}; + +use std::mem; + + +declare_TCFType!{ + /// An immutable bag of elements. + CFSet, CFSetRef +} +impl_TCFType!(CFSet, CFSetRef, CFSetGetTypeID); +impl_CFTypeDescription!(CFSet); + +impl CFSet { + /// Creates a new set from a list of `CFType` instances. + pub fn from_slice(elems: &[T]) -> CFSet where T: TCFType { + unsafe { + let elems: Vec = elems.iter().map(|elem| elem.as_CFTypeRef()).collect(); + let set_ref = CFSetCreate(kCFAllocatorDefault, + mem::transmute(elems.as_ptr()), + elems.len().to_CFIndex(), + &kCFTypeSetCallBacks); + TCFType::wrap_under_create_rule(set_ref) + } + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/string.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/string.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/string.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/string.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,143 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Immutable strings. + +pub use core_foundation_sys::string::*; + +use base::{CFIndexConvertible, TCFType}; + +use core_foundation_sys::base::{Boolean, CFIndex, CFRange}; +use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull}; +use std::fmt; +use std::str::{self, FromStr}; +use std::ptr; +use std::ffi::CStr; + + +declare_TCFType!{ + /// An immutable string in one of a variety of encodings. + CFString, CFStringRef +} +impl_TCFType!(CFString, CFStringRef, CFStringGetTypeID); + +impl FromStr for CFString { + type Err = (); + + /// See also CFString::new for a variant of this which does not return a Result + #[inline] + fn from_str(string: &str) -> Result { + Ok(CFString::new(string)) + } +} + +impl<'a> From<&'a str> for CFString { + #[inline] + fn from(string: &'a str) -> CFString { + CFString::new(string) + } +} + +impl fmt::Display for CFString { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + unsafe { + // Do this without allocating if we can get away with it + let c_string = CFStringGetCStringPtr(self.0, kCFStringEncodingUTF8); + if c_string != ptr::null() { + let c_str = CStr::from_ptr(c_string); + fmt.write_str(str::from_utf8_unchecked(c_str.to_bytes())) + } else { + let char_len = self.char_len(); + + // First, ask how big the buffer ought to be. + let mut bytes_required: CFIndex = 0; + CFStringGetBytes(self.0, + CFRange { location: 0, length: char_len }, + kCFStringEncodingUTF8, + 0, + false as Boolean, + ptr::null_mut(), + 0, + &mut bytes_required); + + // Then, allocate the buffer and actually copy. + let mut buffer = vec![b'\x00'; bytes_required as usize]; + + let mut bytes_used: CFIndex = 0; + let chars_written = CFStringGetBytes(self.0, + CFRange { location: 0, length: char_len }, + kCFStringEncodingUTF8, + 0, + false as Boolean, + buffer.as_mut_ptr(), + buffer.len().to_CFIndex(), + &mut bytes_used) as usize; + assert!(chars_written.to_CFIndex() == char_len); + + // This is dangerous; we over-allocate and null-terminate the string (during + // initialization). + assert!(bytes_used == buffer.len().to_CFIndex()); + fmt.write_str(str::from_utf8_unchecked(&buffer)) + } + } + } +} + +impl fmt::Debug for CFString { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "\"{}\"", self) + } +} + + +impl CFString { + /// Creates a new `CFString` instance from a Rust string. + #[inline] + pub fn new(string: &str) -> CFString { + unsafe { + let string_ref = CFStringCreateWithBytes(kCFAllocatorDefault, + string.as_ptr(), + string.len().to_CFIndex(), + kCFStringEncodingUTF8, + false as Boolean); + CFString::wrap_under_create_rule(string_ref) + } + } + + /// Like `CFString::new`, but references a string that can be used as a backing store + /// by virtue of being statically allocated. + #[inline] + pub fn from_static_string(string: &'static str) -> CFString { + unsafe { + let string_ref = CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, + string.as_ptr(), + string.len().to_CFIndex(), + kCFStringEncodingUTF8, + false as Boolean, + kCFAllocatorNull); + TCFType::wrap_under_create_rule(string_ref) + } + } + + /// Returns the number of characters in the string. + #[inline] + pub fn char_len(&self) -> CFIndex { + unsafe { + CFStringGetLength(self.0) + } + } +} + +#[test] +fn string_and_back() { + let original = "The quick brown fox jumped over the slow lazy dog."; + let cfstr = CFString::from_static_string(original); + let converted = cfstr.to_string(); + assert!(converted == original); +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/timezone.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/timezone.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/timezone.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/timezone.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,95 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation time zone objects. + +pub use core_foundation_sys::timezone::*; +use core_foundation_sys::base::kCFAllocatorDefault; + +use base::TCFType; +use date::{CFDate, CFTimeInterval}; + +#[cfg(feature = "with-chrono")] +use chrono::{FixedOffset, NaiveDateTime}; + + +declare_TCFType!{ + /// A time zone. + CFTimeZone, CFTimeZoneRef +} +impl_TCFType!(CFTimeZone, CFTimeZoneRef, CFTimeZoneGetTypeID); +impl_CFTypeDescription!(CFTimeZone); + +impl Default for CFTimeZone { + fn default() -> CFTimeZone { + unsafe { + let tz_ref = CFTimeZoneCopyDefault(); + TCFType::wrap_under_create_rule(tz_ref) + } + } +} + +impl CFTimeZone { + #[inline] + pub fn new(interval: CFTimeInterval) -> CFTimeZone { + unsafe { + let tz_ref = CFTimeZoneCreateWithTimeIntervalFromGMT(kCFAllocatorDefault, interval); + TCFType::wrap_under_create_rule(tz_ref) + } + } + + #[inline] + pub fn system() -> CFTimeZone { + unsafe { + let tz_ref = CFTimeZoneCopySystem(); + TCFType::wrap_under_create_rule(tz_ref) + } + } + + pub fn seconds_from_gmt(&self, date: CFDate) -> CFTimeInterval { + unsafe { + CFTimeZoneGetSecondsFromGMT(self.0, date.abs_time()) + } + } + + #[cfg(feature = "with-chrono")] + pub fn offset_at_date(&self, date: NaiveDateTime) -> FixedOffset { + let date = CFDate::from_naive_utc(date); + FixedOffset::east(self.seconds_from_gmt(date) as i32) + } + + #[cfg(feature = "with-chrono")] + pub fn from_offset(offset: FixedOffset) -> CFTimeZone { + CFTimeZone::new(offset.local_minus_utc() as f64) + } +} + +#[cfg(test)] +mod test { + use super::CFTimeZone; + + #[cfg(feature = "with-chrono")] + use chrono::{NaiveDateTime, FixedOffset}; + + #[test] + fn timezone_comparison() { + let system = CFTimeZone::system(); + let default = CFTimeZone::default(); + assert_eq!(system, default); + } + + #[test] + #[cfg(feature = "with-chrono")] + fn timezone_chrono_conversion() { + let offset = FixedOffset::west(28800); + let tz = CFTimeZone::from_offset(offset); + let converted = tz.offset_at_date(NaiveDateTime::from_timestamp(0, 0)); + assert_eq!(offset, converted); + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/url.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/url.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/url.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/url.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,156 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A URL type for Core Foundation. + +pub use core_foundation_sys::url::*; + +use base::{TCFType, CFIndex}; +use string::{CFString}; + +use core_foundation_sys::base::{kCFAllocatorDefault, Boolean}; +use std::fmt; +use std::ptr; +use std::path::{Path, PathBuf}; +use std::mem; + +use libc::{strlen, PATH_MAX}; + +#[cfg(unix)] +use std::os::unix::ffi::OsStrExt; +#[cfg(unix)] +use std::ffi::OsStr; + + +declare_TCFType!(CFURL, CFURLRef); +impl_TCFType!(CFURL, CFURLRef, CFURLGetTypeID); + +impl fmt::Debug for CFURL { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + unsafe { + let string: CFString = TCFType::wrap_under_get_rule(CFURLGetString(self.0)); + write!(f, "{}", string.to_string()) + } + } +} + +impl CFURL { + pub fn from_path>(path: P, isDirectory: bool) -> Option { + let path_bytes; + #[cfg(unix)] + { + path_bytes = path.as_ref().as_os_str().as_bytes() + } + #[cfg(not(unix))] + { + // XXX: Getting non-valid UTF8 paths into CoreFoundation on Windows is going to be unpleasant + // CFURLGetWideFileSystemRepresentation might help + path_bytes = match path.as_ref().to_str() { + Some(path) => path, + None => return None, + } + } + + unsafe { + let url_ref = CFURLCreateFromFileSystemRepresentation(ptr::null_mut(), path_bytes.as_ptr(), path_bytes.len() as CFIndex, isDirectory as u8); + if url_ref.is_null() { + return None; + } + Some(TCFType::wrap_under_create_rule(url_ref)) + } + } + + pub fn from_file_system_path(filePath: CFString, pathStyle: CFURLPathStyle, isDirectory: bool) -> CFURL { + unsafe { + let url_ref = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, filePath.as_concrete_TypeRef(), pathStyle, isDirectory as u8); + TCFType::wrap_under_create_rule(url_ref) + } + } + + #[cfg(unix)] + pub fn to_path(&self) -> Option { + // implementing this on Windows is more complicated because of the different OsStr representation + unsafe { + let mut buf: [u8; PATH_MAX as usize] = mem::uninitialized(); + let result = CFURLGetFileSystemRepresentation(self.0, true as Boolean, buf.as_mut_ptr(), buf.len() as CFIndex); + if result == false as Boolean { + return None; + } + let len = strlen(buf.as_ptr() as *const i8); + let path = OsStr::from_bytes(&buf[0..len]); + Some(PathBuf::from(path)) + } + } + + pub fn get_string(&self) -> CFString { + unsafe { + TCFType::wrap_under_get_rule(CFURLGetString(self.0)) + } + } + + pub fn get_file_system_path(&self, pathStyle: CFURLPathStyle) -> CFString { + unsafe { + TCFType::wrap_under_create_rule(CFURLCopyFileSystemPath(self.as_concrete_TypeRef(), pathStyle)) + } + } + + pub fn absolute(&self) -> CFURL { + unsafe { + TCFType::wrap_under_create_rule(CFURLCopyAbsoluteURL(self.as_concrete_TypeRef())) + } + } +} + +#[test] +fn file_url_from_path() { + let path = "/usr/local/foo/"; + let cfstr_path = CFString::from_static_string(path); + let cfurl = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); + assert_eq!(cfurl.get_string().to_string(), "file:///usr/local/foo/"); +} + +#[cfg(unix)] +#[test] +fn non_utf8() { + use std::ffi::OsStr; + let path = Path::new(OsStr::from_bytes(b"/\xC0/blame")); + let cfurl = CFURL::from_path(path, false).unwrap(); + assert_eq!(cfurl.to_path().unwrap(), path); + let len = unsafe { CFURLGetBytes(cfurl.as_concrete_TypeRef(), ptr::null_mut(), 0) }; + assert_eq!(len, 17); +} + +#[test] +fn absolute_file_url() { + use core_foundation_sys::url::CFURLCreateWithFileSystemPathRelativeToBase; + use std::path::PathBuf; + + let path = "/usr/local/foo"; + let file = "bar"; + + let cfstr_path = CFString::from_static_string(path); + let cfstr_file = CFString::from_static_string(file); + let cfurl_base = CFURL::from_file_system_path(cfstr_path, kCFURLPOSIXPathStyle, true); + let cfurl_relative: CFURL = unsafe { + let url_ref = CFURLCreateWithFileSystemPathRelativeToBase(kCFAllocatorDefault, + cfstr_file.as_concrete_TypeRef(), + kCFURLPOSIXPathStyle, + false as u8, + cfurl_base.as_concrete_TypeRef()); + TCFType::wrap_under_create_rule(url_ref) + }; + + let mut absolute_path = PathBuf::from(path); + absolute_path.push(file); + + assert_eq!(cfurl_relative.get_file_system_path(kCFURLPOSIXPathStyle).to_string(), file); + assert_eq!(cfurl_relative.absolute().get_file_system_path(kCFURLPOSIXPathStyle).to_string(), + absolute_path.to_str().unwrap()); +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/src/uuid.rs cargo-0.26.0/vendor/core-foundation-0.5.1/src/uuid.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/src/uuid.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/src/uuid.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,112 @@ +// Copyright 2013 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Core Foundation UUID objects. + +#[cfg(feature = "with-uuid")] +extern crate uuid; + +pub use core_foundation_sys::uuid::*; +use core_foundation_sys::base::kCFAllocatorDefault; + +use base::TCFType; + +#[cfg(feature = "with-uuid")] +use self::uuid::Uuid; + + +declare_TCFType! { + /// A UUID. + CFUUID, CFUUIDRef +} +impl_TCFType!(CFUUID, CFUUIDRef, CFUUIDGetTypeID); +impl_CFTypeDescription!(CFUUID); + +impl CFUUID { + #[inline] + pub fn new() -> CFUUID { + unsafe { + let uuid_ref = CFUUIDCreate(kCFAllocatorDefault); + TCFType::wrap_under_create_rule(uuid_ref) + } + } +} + +#[cfg(feature = "with-uuid")] +impl Into for CFUUID { + fn into(self) -> Uuid { + let b = unsafe { + CFUUIDGetUUIDBytes(self.0) + }; + let bytes = [ + b.byte0, + b.byte1, + b.byte2, + b.byte3, + b.byte4, + b.byte5, + b.byte6, + b.byte7, + b.byte8, + b.byte9, + b.byte10, + b.byte11, + b.byte12, + b.byte13, + b.byte14, + b.byte15, + ]; + Uuid::from_bytes(&bytes).unwrap() + } +} + +#[cfg(feature = "with-uuid")] +impl From for CFUUID { + fn from(uuid: Uuid) -> CFUUID { + let b = uuid.as_bytes(); + let bytes = CFUUIDBytes { + byte0: b[0], + byte1: b[1], + byte2: b[2], + byte3: b[3], + byte4: b[4], + byte5: b[5], + byte6: b[6], + byte7: b[7], + byte8: b[8], + byte9: b[9], + byte10: b[10], + byte11: b[11], + byte12: b[12], + byte13: b[13], + byte14: b[14], + byte15: b[15], + }; + unsafe { + let uuid_ref = CFUUIDCreateFromUUIDBytes(kCFAllocatorDefault, bytes); + TCFType::wrap_under_create_rule(uuid_ref) + } + } +} + + +#[cfg(test)] +#[cfg(feature = "with-uuid")] +mod test { + use super::CFUUID; + use uuid::Uuid; + + #[test] + fn uuid_conversion() { + let cf_uuid = CFUUID::new(); + let uuid: Uuid = cf_uuid.clone().into(); + let converted = CFUUID::from(uuid); + assert!(cf_uuid == converted); + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-0.5.1/tests/use_macro_outside_crate.rs cargo-0.26.0/vendor/core-foundation-0.5.1/tests/use_macro_outside_crate.rs --- cargo-0.25.0/vendor/core-foundation-0.5.1/tests/use_macro_outside_crate.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-0.5.1/tests/use_macro_outside_crate.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,29 @@ +#[macro_use] +extern crate core_foundation; +extern crate libc; + +use core_foundation::base::{CFComparisonResult, TCFType}; +use libc::c_void; + +// sys equivalent stuff that must be declared + +#[repr(C)] +pub struct __CFFooBar(c_void); + +pub type CFFooBarRef = *const __CFFooBar; + +extern "C" { + pub fn CFFooBarGetTypeID() -> core_foundation::base::CFTypeID; + pub fn fake_compare( + this: CFFooBarRef, + other: CFFooBarRef, + context: *mut c_void, + ) -> CFComparisonResult; +} + +// Try to use the macros outside of the crate + +declare_TCFType!(CFFooBar, CFFooBarRef); +impl_TCFType!(CFFooBar, CFFooBarRef, CFFooBarGetTypeID); +impl_CFTypeDescription!(CFFooBar); +impl_CFComparison!(CFFooBar, fake_compare); diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/build.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/build.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/build.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/build.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -fn main() { - if std::env::var("TARGET").unwrap().contains("-apple") { - println!("cargo:rustc-link-lib=framework=CoreFoundation"); - } -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/.cargo-checksum.json cargo-0.26.0/vendor/core-foundation-sys-0.4.6/.cargo-checksum.json --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"152195421a2e6497a8179195672e9d4ee8e45ed8c465b626f1606d27a08ebcd5"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/Cargo.toml cargo-0.26.0/vendor/core-foundation-sys-0.4.6/Cargo.toml --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "core-foundation-sys" -version = "0.4.6" -authors = ["The Servo Project Developers"] -build = "build.rs" -description = "Bindings to Core Foundation for OS X" -homepage = "https://github.com/servo/core-foundation-rs" -license = "MIT / Apache-2.0" -repository = "https://github.com/servo/core-foundation-rs" -[dependencies.libc] -version = "0.2" - -[features] -mac_os_10_7_support = [] -mac_os_10_8_features = [] diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/array.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/array.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/array.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/array.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use libc::c_void; - -use base::{CFRange, CFIndex, CFAllocatorRef, CFTypeID, Boolean}; -use string::CFStringRef; - -pub type CFArrayRetainCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; -pub type CFArrayReleaseCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void); -pub type CFArrayCopyDescriptionCallBack = extern "C" fn(value: *const c_void) -> CFStringRef; -pub type CFArrayEqualCallBack = extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; - -#[repr(C)] -#[derive(Clone, Copy)] -pub struct CFArrayCallBacks { - pub version: CFIndex, - pub retain: CFArrayRetainCallBack, - pub release: CFArrayReleaseCallBack, - pub copyDescription: CFArrayCopyDescriptionCallBack, - pub equal: CFArrayEqualCallBack, -} - -#[repr(C)] -pub struct __CFArray(c_void); - -pub type CFArrayRef = *const __CFArray; - -extern { - /* - * CFArray.h - */ - pub static kCFTypeArrayCallBacks: CFArrayCallBacks; - - pub fn CFArrayCreate(allocator: CFAllocatorRef, values: *const *const c_void, - numValues: CFIndex, callBacks: *const CFArrayCallBacks) -> CFArrayRef; - pub fn CFArrayCreateCopy(allocator: CFAllocatorRef , theArray: CFArrayRef) -> CFArrayRef; - - // CFArrayBSearchValues - // CFArrayContainsValue - pub fn CFArrayGetCount(theArray: CFArrayRef) -> CFIndex; - // CFArrayGetCountOfValue - // CFArrayGetFirstIndexOfValue - // CFArrayGetLastIndexOfValue - pub fn CFArrayGetValues(theArray: CFArrayRef, range: CFRange, values: *mut *const c_void); - pub fn CFArrayGetValueAtIndex(theArray: CFArrayRef, idx: CFIndex) -> *const c_void; - // CFArrayApplyFunction - pub fn CFArrayGetTypeID() -> CFTypeID; -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/base.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/base.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/base.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/base.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,127 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::cmp::Ordering; -use libc::{c_uint, c_long, c_ulong, c_void, c_int}; -use string::CFStringRef; - -pub type Boolean = u8; -pub type CFIndex = c_long; -pub type mach_port_t = c_uint; -pub type CFAllocatorRef = *const c_void; -pub type CFNullRef = *const c_void; -pub type CFHashCode = c_ulong; -pub type CFTypeID = c_ulong; -pub type CFTypeRef = *const c_void; -pub type CFOptionFlags = u32; -pub type OSStatus = i32; -pub type SInt32 = c_int; - -#[repr(i64)] -#[derive(Clone, Copy)] -pub enum CFComparisonResult { - LessThan = -1, - EqualTo = 0, - GreaterThan = 1, -} - -impl Into for CFComparisonResult { - fn into(self) -> Ordering { - match self { - CFComparisonResult::LessThan => Ordering::Less, - CFComparisonResult::EqualTo => Ordering::Equal, - CFComparisonResult::GreaterThan => Ordering::Greater - } - } -} - -#[repr(C)] -#[derive(Clone, Copy)] -pub struct CFRange { - pub location: CFIndex, - pub length: CFIndex -} - -// for back-compat -impl CFRange { - pub fn init(location: CFIndex, length: CFIndex) -> CFRange { - CFRange { - location: location, - length: length, - } - } -} - -pub type CFAllocatorRetainCallBack = extern "C" fn(info: *mut c_void) -> *mut c_void; -pub type CFAllocatorReleaseCallBack = extern "C" fn(info: *mut c_void); -pub type CFAllocatorCopyDescriptionCallBack = extern "C" fn(info: *mut c_void) -> CFStringRef; -pub type CFAllocatorAllocateCallBack = extern "C" fn(allocSize: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> *mut c_void; -pub type CFAllocatorReallocateCallBack = extern "C" fn(ptr: *mut c_void, newsize: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> *mut c_void; -pub type CFAllocatorDeallocateCallBack = extern "C" fn(ptr: *mut c_void, info: *mut c_void); -pub type CFAllocatorPreferredSizeCallBack = extern "C" fn(size: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> CFIndex; - -#[repr(C)] -#[derive(Clone, Copy)] -pub struct CFAllocatorContext { - pub version: CFIndex, - pub info: *mut c_void, - pub retain: CFAllocatorRetainCallBack, - pub release: CFAllocatorReleaseCallBack, - pub copyDescription: CFAllocatorCopyDescriptionCallBack, - pub allocate: CFAllocatorAllocateCallBack, - pub reallocate: CFAllocatorReallocateCallBack, - pub deallocate: CFAllocatorDeallocateCallBack, - pub preferredSize: CFAllocatorPreferredSizeCallBack -} - -extern { - /* - * CFBase.h - */ - - /* CFAllocator Reference */ - - pub static kCFAllocatorDefault: CFAllocatorRef; - pub static kCFAllocatorSystemDefault: CFAllocatorRef; - pub static kCFAllocatorMalloc: CFAllocatorRef; - pub static kCFAllocatorMallocZone: CFAllocatorRef; - pub static kCFAllocatorNull: CFAllocatorRef; - pub static kCFAllocatorUseContext: CFAllocatorRef; - - pub fn CFAllocatorCreate(allocator: CFAllocatorRef, context: *mut CFAllocatorContext) -> CFAllocatorRef; - pub fn CFAllocatorAllocate(allocator: CFAllocatorRef, size: CFIndex, hint: CFOptionFlags) -> *mut c_void; - pub fn CFAllocatorDeallocate(allocator: CFAllocatorRef, ptr: *mut c_void); - pub fn CFAllocatorGetPreferredSizeForSize(allocator: CFAllocatorRef, size: CFIndex, hint: CFOptionFlags) -> CFIndex; - pub fn CFAllocatorReallocate(allocator: CFAllocatorRef, ptr: *mut c_void, newsize: CFIndex, hint: CFOptionFlags) -> *mut c_void; - pub fn CFAllocatorGetDefault() -> CFAllocatorRef; - pub fn CFAllocatorSetDefault(allocator: CFAllocatorRef); - pub fn CFAllocatorGetContext(allocator: CFAllocatorRef, context: *mut CFAllocatorContext); - pub fn CFAllocatorGetTypeID() -> CFTypeID; - - /* CFNull Reference */ - - pub static kCFNull: CFNullRef; - - /* CFType Reference */ - - //fn CFCopyTypeIDDescription - //fn CFGetAllocator - pub fn CFCopyDescription(cf: CFTypeRef) -> CFStringRef; - pub fn CFEqual(cf1: CFTypeRef, cf2: CFTypeRef) -> Boolean; - pub fn CFGetRetainCount(cf: CFTypeRef) -> CFIndex; - pub fn CFGetTypeID(cf: CFTypeRef) -> CFTypeID; - pub fn CFHash(cf: CFTypeRef) -> CFHashCode; - //fn CFMakeCollectable - pub fn CFRelease(cf: CFTypeRef); - pub fn CFRetain(cf: CFTypeRef) -> CFTypeRef; - pub fn CFShow(obj: CFTypeRef); - - /* Base Utilities Reference */ - // N.B. Some things missing here. -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/bundle.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/bundle.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/bundle.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/bundle.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use libc::c_void; - -use base::{CFTypeID, CFAllocatorRef}; -use url::CFURLRef; -use dictionary::CFDictionaryRef; -use string::CFStringRef; - -#[repr(C)] -pub struct __CFBundle(c_void); - -pub type CFBundleRef = *const __CFBundle; - -extern { - /* - * CFBundle.h - */ - pub fn CFBundleCreate(allocator: CFAllocatorRef, bundleURL: CFURLRef) -> CFBundleRef; - - pub fn CFBundleGetBundleWithIdentifier(bundleID: CFStringRef) -> CFBundleRef; - pub fn CFBundleGetFunctionPointerForName(bundle: CFBundleRef, function_name: CFStringRef) -> *const c_void; - pub fn CFBundleGetMainBundle() -> CFBundleRef; - pub fn CFBundleGetInfoDictionary(bundle: CFBundleRef) -> CFDictionaryRef; - - pub fn CFBundleGetTypeID() -> CFTypeID; - pub fn CFBundleCopyExecutableURL(bundle: CFBundleRef) -> CFURLRef; - pub fn CFBundleCopyPrivateFrameworksURL(bundle: CFBundleRef) -> CFURLRef; -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/data.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/data.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/data.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/data.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -use libc::c_void; - -use base::{CFAllocatorRef, CFTypeID, CFIndex}; - -#[repr(C)] -pub struct __CFData(c_void); - -pub type CFDataRef = *const __CFData; - -extern { - /* - * CFData.h - */ - - pub fn CFDataCreate(allocator: CFAllocatorRef, - bytes: *const u8, length: CFIndex) -> CFDataRef; - //fn CFDataFind - pub fn CFDataGetBytePtr(theData: CFDataRef) -> *const u8; - pub fn CFDataGetLength(theData: CFDataRef) -> CFIndex; - - pub fn CFDataGetTypeID() -> CFTypeID; -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/date.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/date.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/date.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/date.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use libc::c_void; - -use base::{CFAllocatorRef, CFComparisonResult, CFTypeID}; - -#[repr(C)] -pub struct __CFDate(c_void); - -pub type CFDateRef = *const __CFDate; - -pub type CFTimeInterval = f64; -pub type CFAbsoluteTime = CFTimeInterval; - -extern { - pub static kCFAbsoluteTimeIntervalSince1904: CFTimeInterval; - pub static kCFAbsoluteTimeIntervalSince1970: CFTimeInterval; - - pub fn CFAbsoluteTimeGetCurrent() -> CFAbsoluteTime; - - pub fn CFDateCreate(allocator: CFAllocatorRef, at: CFAbsoluteTime) -> CFDateRef; - pub fn CFDateGetAbsoluteTime(date: CFDateRef) -> CFAbsoluteTime; - pub fn CFDateGetTimeIntervalSinceDate(date: CFDateRef, other: CFDateRef) -> CFTimeInterval; - pub fn CFDateCompare(date: CFDateRef, other: CFDateRef, context: *mut c_void) -> CFComparisonResult; - - pub fn CFDateGetTypeID() -> CFTypeID; -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/dictionary.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/dictionary.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/dictionary.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/dictionary.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use libc::{c_void}; - -use base::{CFAllocatorRef, CFHashCode, CFIndex, CFTypeID, Boolean}; -use string::CFStringRef; - -pub type CFDictionaryApplierFunction = extern "C" fn(key: *const c_void, value: *const c_void, context: *mut c_void); - -pub type CFDictionaryRetainCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; -pub type CFDictionaryReleaseCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void); -pub type CFDictionaryCopyDescriptionCallBack = extern "C" fn(value: *const c_void) -> CFStringRef; -pub type CFDictionaryEqualCallBack = extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; -pub type CFDictionaryHashCallBack = extern "C" fn(value: *const c_void) -> CFHashCode; - -#[repr(C)] -#[derive(Clone, Copy)] -pub struct CFDictionaryKeyCallBacks { - pub version: CFIndex, - pub retain: CFDictionaryRetainCallBack, - pub release: CFDictionaryReleaseCallBack, - pub copyDescription: CFDictionaryCopyDescriptionCallBack, - pub equal: CFDictionaryEqualCallBack, - pub hash: CFDictionaryHashCallBack -} - -#[repr(C)] -#[derive(Clone, Copy)] -pub struct CFDictionaryValueCallBacks { - pub version: CFIndex, - pub retain: CFDictionaryRetainCallBack, - pub release: CFDictionaryReleaseCallBack, - pub copyDescription: CFDictionaryCopyDescriptionCallBack, - pub equal: CFDictionaryEqualCallBack -} - -#[repr(C)] -pub struct __CFDictionary(c_void); - -pub type CFDictionaryRef = *const __CFDictionary; -pub type CFMutableDictionaryRef = *const __CFDictionary; - -extern { - /* - * CFDictionary.h - */ - - pub static kCFTypeDictionaryKeyCallBacks: CFDictionaryKeyCallBacks; - pub static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks; - - pub fn CFDictionaryContainsKey(theDict: CFDictionaryRef, key: *const c_void) -> Boolean; - pub fn CFDictionaryCreate(allocator: CFAllocatorRef, keys: *const *const c_void, values: *const *const c_void, - numValues: CFIndex, keyCallBacks: *const CFDictionaryKeyCallBacks, - valueCallBacks: *const CFDictionaryValueCallBacks) - -> CFDictionaryRef; - pub fn CFDictionaryGetCount(theDict: CFDictionaryRef) -> CFIndex; - pub fn CFDictionaryGetTypeID() -> CFTypeID; - pub fn CFDictionaryGetValueIfPresent(theDict: CFDictionaryRef, key: *const c_void, value: *mut *const c_void) - -> Boolean; - pub fn CFDictionaryApplyFunction(theDict: CFDictionaryRef, - applier: CFDictionaryApplierFunction, - context: *mut c_void); - pub fn CFDictionarySetValue(theDict: CFMutableDictionaryRef, - key: *const c_void, - value: *const c_void); - pub fn CFDictionaryGetKeysAndValues(theDict: CFDictionaryRef, - keys: *mut *const c_void, - values: *mut *const c_void); - -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/error.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/error.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/error.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/error.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -// Copyright 2016 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use libc::c_void; - -use base::{CFTypeID, CFIndex}; -use string::CFStringRef; - -#[repr(C)] -pub struct __CFError(c_void); - -pub type CFErrorRef = *mut __CFError; - -extern "C" { - pub fn CFErrorGetTypeID() -> CFTypeID; - - pub static kCFErrorDomainPOSIX: CFStringRef; - pub static kCFErrorDomainOSStatus: CFStringRef; - pub static kCFErrorDomainMach: CFStringRef; - pub static kCFErrorDomainCocoa: CFStringRef; - - pub fn CFErrorGetDomain(err: CFErrorRef) -> CFStringRef; - pub fn CFErrorGetCode(err: CFErrorRef) -> CFIndex; - - pub fn CFErrorCopyDescription(err: CFErrorRef) -> CFStringRef; -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/lib.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/lib.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, improper_ctypes)] - -#![cfg_attr(all(feature="mac_os_10_7_support", feature="mac_os_10_8_features"), feature(linkage))] // back-compat requires weak linkage - -extern crate libc; - -pub mod array; -pub mod base; -pub mod bundle; -pub mod data; -pub mod date; -pub mod dictionary; -pub mod error; -pub mod messageport; -pub mod number; -pub mod propertylist; -pub mod runloop; -pub mod set; -pub mod string; -pub mod timezone; -pub mod url; -pub mod uuid; diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/messageport.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/messageport.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/messageport.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/messageport.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use libc::c_void; - -use base::{CFAllocatorRef, CFIndex, CFTypeID, Boolean}; -use data::CFDataRef; -use date::CFTimeInterval; -use runloop::CFRunLoopSourceRef; -use string::CFStringRef; - -#[repr(C)] -#[derive(Copy, Clone)] -#[derive(Debug)] -pub struct CFMessagePortContext { - pub version: CFIndex, - pub info: *mut c_void, - pub retain: Option *const c_void>, - pub release: Option, - pub copyDescription: Option CFStringRef>, -} - -pub type CFMessagePortCallBack = Option< - unsafe extern fn(local: CFMessagePortRef, - msgid: i32, - data: CFDataRef, - info: *mut c_void) -> CFDataRef>; - -pub type CFMessagePortInvalidationCallBack = Option< - unsafe extern "C" fn(ms: CFMessagePortRef, info: *mut c_void)>; - -#[repr(C)] -pub struct __CFMessagePort(c_void); -pub type CFMessagePortRef = *const __CFMessagePort; - -extern { - /* - * CFMessagePort.h - */ - pub fn CFMessagePortGetTypeID() -> CFTypeID; - pub fn CFMessagePortCreateLocal(allocator: CFAllocatorRef, - name: CFStringRef, - callout: CFMessagePortCallBack, - context: *const CFMessagePortContext, - shouldFreeInfo: *mut Boolean) - -> CFMessagePortRef; - pub fn CFMessagePortCreateRemote(allocator: CFAllocatorRef, - name: CFStringRef) -> CFMessagePortRef; - pub fn CFMessagePortIsRemote(ms: CFMessagePortRef) -> Boolean; - pub fn CFMessagePortGetName(ms: CFMessagePortRef) -> CFStringRef; - pub fn CFMessagePortSetName(ms: CFMessagePortRef, newName: CFStringRef) - -> Boolean; - pub fn CFMessagePortGetContext(ms: CFMessagePortRef, - context: *mut CFMessagePortContext); - pub fn CFMessagePortInvalidate(ms: CFMessagePortRef); - pub fn CFMessagePortIsValid(ms: CFMessagePortRef) -> Boolean; - pub fn CFMessagePortGetInvalidationCallBack(ms: CFMessagePortRef) - -> CFMessagePortInvalidationCallBack; - pub fn CFMessagePortSetInvalidationCallBack(ms: CFMessagePortRef, - callout: CFMessagePortInvalidationCallBack); - pub fn CFMessagePortSendRequest(remote: CFMessagePortRef, msgid: i32, - data: CFDataRef, - sendTimeout: CFTimeInterval, - rcvTimeout: CFTimeInterval, - replyMode: CFStringRef, - returnData: *mut CFDataRef) -> i32; - pub fn CFMessagePortCreateRunLoopSource(allocator: CFAllocatorRef, - local: CFMessagePortRef, - order: CFIndex) - -> CFRunLoopSourceRef; - // CFMessagePortSetDispatchQueue -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/number.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/number.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/number.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/number.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use libc::c_void; - -use base::{CFAllocatorRef, CFTypeID, CFComparisonResult}; - -#[repr(C)] -pub struct __CFBoolean(c_void); - -pub type CFBooleanRef = *const __CFBoolean; - -pub type CFNumberType = u32; - -// members of enum CFNumberType -// static kCFNumberSInt8Type: CFNumberType = 1; -// static kCFNumberSInt16Type: CFNumberType = 2; -pub static kCFNumberSInt32Type: CFNumberType = 3; -pub static kCFNumberSInt64Type: CFNumberType = 4; -pub static kCFNumberFloat32Type: CFNumberType = 5; -pub static kCFNumberFloat64Type: CFNumberType = 6; -// static kCFNumberCharType: CFNumberType = 7; -// static kCFNumberShortType: CFNumberType = 8; -// static kCFNumberIntType: CFNumberType = 9; -// static kCFNumberLongType: CFNumberType = 10; -// static kCFNumberLongLongType: CFNumberType = 11; -// static kCFNumberFloatType: CFNumberType = 12; -// static kCFNumberDoubleType: CFNumberType = 13; -// static kCFNumberCFIndexType: CFNumberType = 14; -// static kCFNumberNSIntegerType: CFNumberType = 15; -// static kCFNumberCGFloatType: CFNumberType = 16; -// static kCFNumberMaxType: CFNumberType = 16; - -// This is an enum due to zero-sized types warnings. -// For more details see https://github.com/rust-lang/rust/issues/27303 -pub enum __CFNumber {} - -pub type CFNumberRef = *const __CFNumber; - -extern { - /* - * CFNumber.h - */ - pub static kCFBooleanTrue: CFBooleanRef; - pub static kCFBooleanFalse: CFBooleanRef; - - pub fn CFBooleanGetTypeID() -> CFTypeID; - pub fn CFNumberCreate(allocator: CFAllocatorRef, theType: CFNumberType, valuePtr: *const c_void) - -> CFNumberRef; - //fn CFNumberGetByteSize - pub fn CFNumberGetValue(number: CFNumberRef, theType: CFNumberType, valuePtr: *mut c_void) -> bool; - pub fn CFNumberCompare(date: CFNumberRef, other: CFNumberRef, context: *mut c_void) -> CFComparisonResult; - pub fn CFNumberGetTypeID() -> CFTypeID; -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/propertylist.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/propertylist.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/propertylist.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/propertylist.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -use base::{CFAllocatorRef, CFIndex, CFOptionFlags, CFTypeRef}; -use data::CFDataRef; -use error::CFErrorRef; - -pub type CFPropertyListRef = CFTypeRef; - -pub type CFPropertyListFormat = CFIndex; -pub const kCFPropertyListOpenStepFormat: CFPropertyListFormat = 1; -pub const kCFPropertyListXMLFormat_v1_0: CFPropertyListFormat = 100; -pub const kCFPropertyListBinaryFormat_v1_0: CFPropertyListFormat = 200; - -pub type CFPropertyListMutabilityOptions = CFOptionFlags; -pub const kCFPropertyListImmutable: CFPropertyListMutabilityOptions = 0; -pub const kCFPropertyListMutableContainers: CFPropertyListMutabilityOptions = 1; -pub const kCFPropertyListMutableContainersAndLeaves: CFPropertyListMutabilityOptions = 2; - -extern "C" { - // CFPropertyList.h - // - - // fn CFPropertyListCreateDeepCopy - // fn CFPropertyListIsValid - pub fn CFPropertyListCreateWithData(allocator: CFAllocatorRef, - data: CFDataRef, - options: CFPropertyListMutabilityOptions, - format: *mut CFPropertyListFormat, - error: *mut CFErrorRef) - -> CFPropertyListRef; - // fn CFPropertyListCreateWithStream - // fn CFPropertyListWrite - pub fn CFPropertyListCreateData(allocator: CFAllocatorRef, - propertyList: CFPropertyListRef, - format: CFPropertyListFormat, - options: CFOptionFlags, - error: *mut CFErrorRef) - -> CFDataRef; -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/runloop.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/runloop.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/runloop.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/runloop.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,164 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use libc::c_void; - -use array::CFArrayRef; -use base::{Boolean, CFIndex, CFTypeID, CFAllocatorRef, CFOptionFlags, CFHashCode, mach_port_t}; -use date::{CFAbsoluteTime, CFTimeInterval}; -use string::CFStringRef; - -#[repr(C)] -pub struct __CFRunLoop(c_void); - -pub type CFRunLoopRef = *const __CFRunLoop; - -#[repr(C)] -pub struct __CFRunLoopSource(c_void); - -pub type CFRunLoopSourceRef = *const __CFRunLoopSource; - -#[repr(C)] -pub struct __CFRunLoopObserver(c_void); - -pub type CFRunLoopObserverRef = *const __CFRunLoopObserver; - -// Reasons for CFRunLoopRunInMode() to Return -pub const kCFRunLoopRunFinished: i32 = 1; -pub const kCFRunLoopRunStopped: i32 = 2; -pub const kCFRunLoopRunTimedOut: i32 = 3; -pub const kCFRunLoopRunHandledSource: i32 = 4; - -// Run Loop Observer Activities -//typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) { -pub type CFRunLoopActivity = CFOptionFlags; -pub const kCFRunLoopEntry: CFOptionFlags = 1 << 0; -pub const kCFRunLoopBeforeTimers: CFOptionFlags = 1 << 1; -pub const kCFRunLoopBeforeSources: CFOptionFlags = 1 << 2; -pub const kCFRunLoopBeforeWaiting: CFOptionFlags = 1 << 5; -pub const kCFRunLoopAfterWaiting: CFOptionFlags = 1 << 6; -pub const kCFRunLoopExit: CFOptionFlags = 1 << 7; -pub const kCFRunLoopAllActivities: CFOptionFlags = 0x0FFFFFFF; - -#[repr(C)] -pub struct CFRunLoopSourceContext { - pub version: CFIndex, - pub info: *mut c_void, - pub retain: extern "C" fn (info: *const c_void) -> *const c_void, - pub release: extern "C" fn (info: *const c_void), - pub copyDescription: extern "C" fn (info: *const c_void) -> CFStringRef, - pub equal: extern "C" fn (info1: *const c_void, info2: *const c_void) -> Boolean, - pub hash: extern "C" fn (info: *const c_void) -> CFHashCode, - pub schedule: extern "C" fn (info: *const c_void, rl: CFRunLoopRef, mode: CFStringRef), - pub cancel: extern "C" fn (info: *const c_void, rl: CFRunLoopRef, mode: CFStringRef), - pub perform: extern "C" fn (info: *const c_void), -} - -#[repr(C)] -pub struct CFRunLoopSourceContext1 { - pub version: CFIndex, - pub info: *mut c_void, - pub retain: extern "C" fn (info: *const c_void) -> *const c_void, - pub release: extern "C" fn (info: *const c_void), - pub copyDescription: extern "C" fn (info: *const c_void) -> CFStringRef, - pub equal: extern "C" fn (info1: *const c_void, info2: *const c_void) -> Boolean, - pub hash: extern "C" fn (info: *const c_void) -> CFHashCode, - // note that the following two fields are platform dependent in the C header, the ones here are for OS X - pub getPort: extern "C" fn (info: *mut c_void) -> mach_port_t, - pub perform: extern "C" fn (msg: *mut c_void, size: CFIndex, allocator: CFAllocatorRef, info: *mut c_void) -> *mut c_void, -} - -#[repr(C)] -pub struct CFRunLoopObserverContext { - pub version: CFIndex, - pub info: *mut c_void, - pub retain: extern "C" fn (info: *const c_void) -> *const c_void, - pub release: extern "C" fn (info: *const c_void), - pub copyDescription: extern "C" fn (info: *const c_void) -> CFStringRef, -} - -pub type CFRunLoopObserverCallBack = extern "C" fn (observer: CFRunLoopObserverRef, activity: CFRunLoopActivity, info: *mut c_void); - -#[repr(C)] -pub struct CFRunLoopTimerContext { - pub version: CFIndex, - pub info: *mut c_void, - pub retain: extern "C" fn (info: *const c_void) -> *const c_void, - pub release: extern "C" fn (info: *const c_void), - pub copyDescription: extern "C" fn (info: *const c_void) -> CFStringRef, -} - -pub type CFRunLoopTimerCallBack = extern "C" fn (timer: CFRunLoopTimerRef, info: *mut c_void); - -#[repr(C)] -pub struct __CFRunLoopTimer; - -pub type CFRunLoopTimerRef = *const __CFRunLoopTimer; - -extern { - /* - * CFRunLoop.h - */ - pub static kCFRunLoopDefaultMode: CFStringRef; - pub static kCFRunLoopCommonModes: CFStringRef; - pub fn CFRunLoopGetTypeID() -> CFTypeID; - pub fn CFRunLoopGetCurrent() -> CFRunLoopRef; - pub fn CFRunLoopGetMain() -> CFRunLoopRef; - pub fn CFRunLoopCopyCurrentMode(rl: CFRunLoopRef) -> CFStringRef; - pub fn CFRunLoopCopyAllModes(rl: CFRunLoopRef) -> CFArrayRef; - pub fn CFRunLoopAddCommonMode(rl: CFRunLoopRef, mode: CFStringRef); - pub fn CFRunLoopGetNextTimerFireDate(rl: CFRunLoopRef, mode: CFStringRef) -> CFAbsoluteTime; - pub fn CFRunLoopRun(); - pub fn CFRunLoopRunInMode(mode: CFStringRef, seconds: CFTimeInterval, returnAfterSourceHandled: Boolean) -> i32; - pub fn CFRunLoopIsWaiting(rl: CFRunLoopRef) -> Boolean; - pub fn CFRunLoopWakeUp(rl: CFRunLoopRef); - pub fn CFRunLoopStop(rl: CFRunLoopRef); - // fn CFRunLoopPerformBlock(rl: CFRunLoopRef, mode: CFTypeRef, block: void (^)(void)); - pub fn CFRunLoopContainsSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef) -> Boolean; - pub fn CFRunLoopAddSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef); - pub fn CFRunLoopRemoveSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef); - pub fn CFRunLoopContainsObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef) -> Boolean; - pub fn CFRunLoopAddObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef); - pub fn CFRunLoopRemoveObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef); - pub fn CFRunLoopContainsTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef) -> Boolean; - pub fn CFRunLoopAddTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef); - pub fn CFRunLoopRemoveTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef); - - pub fn CFRunLoopSourceGetTypeID() -> CFTypeID; - pub fn CFRunLoopSourceCreate(allocator: CFAllocatorRef, order: CFIndex, context: *mut CFRunLoopSourceContext) -> CFRunLoopSourceRef; - pub fn CFRunLoopSourceGetOrder(source: CFRunLoopSourceRef) -> CFIndex; - pub fn CFRunLoopSourceInvalidate(source: CFRunLoopSourceRef); - pub fn CFRunLoopSourceIsValid(source: CFRunLoopSourceRef) -> Boolean; - pub fn CFRunLoopSourceGetContext(source: CFRunLoopSourceRef, context: *mut CFRunLoopSourceContext); - pub fn CFRunLoopSourceSignal(source: CFRunLoopSourceRef); - - pub fn CFRunLoopObserverGetTypeID() -> CFTypeID; - pub fn CFRunLoopObserverCreate(allocator: CFAllocatorRef, activities: CFOptionFlags, repeats: Boolean, order: CFIndex, callout: CFRunLoopObserverCallBack, context: *mut CFRunLoopObserverContext) -> CFRunLoopObserverRef; - // fn CFRunLoopObserverCreateWithHandler(allocator: CFAllocatorRef, activities: CFOptionFlags, repeats: Boolean, order: CFIndex, block: void (^) (CFRunLoopObserverRef observer, CFRunLoopActivity activity)) -> CFRunLoopObserverRef; - pub fn CFRunLoopObserverGetActivities(observer: CFRunLoopObserverRef) -> CFOptionFlags; - pub fn CFRunLoopObserverDoesRepeat(observer: CFRunLoopObserverRef) -> Boolean; - pub fn CFRunLoopObserverGetOrder(observer: CFRunLoopObserverRef) -> CFIndex; - pub fn CFRunLoopObserverInvalidate(observer: CFRunLoopObserverRef); - pub fn CFRunLoopObserverIsValid(observer: CFRunLoopObserverRef) -> Boolean; - pub fn CFRunLoopObserverGetContext(observer: CFRunLoopObserverRef, context: *mut CFRunLoopObserverContext); - - pub fn CFRunLoopTimerGetTypeID() -> CFTypeID; - pub fn CFRunLoopTimerCreate(allocator: CFAllocatorRef, fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, callout: CFRunLoopTimerCallBack, context: *mut CFRunLoopTimerContext) -> CFRunLoopTimerRef; - // fn CFRunLoopTimerCreateWithHandler(allocator: CFAllocatorRef, fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, block: void (^) (CFRunLoopTimerRef timer)) -> CFRunLoopTimerRef; - pub fn CFRunLoopTimerGetNextFireDate(timer: CFRunLoopTimerRef) -> CFAbsoluteTime; - pub fn CFRunLoopTimerSetNextFireDate(timer: CFRunLoopTimerRef, fireDate: CFAbsoluteTime); - pub fn CFRunLoopTimerGetInterval(timer: CFRunLoopTimerRef) -> CFTimeInterval; - pub fn CFRunLoopTimerDoesRepeat(timer: CFRunLoopTimerRef) -> Boolean; - pub fn CFRunLoopTimerGetOrder(timer: CFRunLoopTimerRef) -> CFIndex; - pub fn CFRunLoopTimerInvalidate(timer: CFRunLoopTimerRef); - pub fn CFRunLoopTimerIsValid(timer: CFRunLoopTimerRef) -> Boolean; - pub fn CFRunLoopTimerGetContext(timer: CFRunLoopTimerRef, context: *mut CFRunLoopTimerContext); - pub fn CFRunLoopTimerGetTolerance(timer: CFRunLoopTimerRef) -> CFTimeInterval; - pub fn CFRunLoopTimerSetTolerance(timer: CFRunLoopTimerRef, tolerance: CFTimeInterval); -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/set.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/set.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/set.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/set.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use libc::c_void; - -use base::{CFAllocatorRef, CFIndex, CFTypeID}; - -pub type CFSetApplierFunction = extern "C" fn (value: *const c_void, - context: *const c_void); -pub type CFSetRetainCallBack = *const u8; -pub type CFSetReleaseCallBack = *const u8; -pub type CFSetCopyDescriptionCallBack = *const u8; -pub type CFSetEqualCallBack = *const u8; -pub type CFSetHashCallBack = *const u8; - -#[repr(C)] -#[derive(Clone, Copy)] -pub struct CFSetCallBacks { - pub version: CFIndex, - pub retain: CFSetRetainCallBack, - pub release: CFSetReleaseCallBack, - pub copyDescription: CFSetCopyDescriptionCallBack, - pub equal: CFSetEqualCallBack, - pub hash: CFSetHashCallBack, -} - -#[repr(C)] -pub struct __CFSet(c_void); - -pub type CFSetRef = *const __CFSet; - -extern { - /* - * CFSet.h - */ - - pub static kCFTypeSetCallBacks: CFSetCallBacks; - - /* Creating Sets */ - pub fn CFSetCreate(allocator: CFAllocatorRef, values: *const *const c_void, numValues: CFIndex, - callBacks: *const CFSetCallBacks) -> CFSetRef; - - /* Applying a Function to Set Members */ - pub fn CFSetApplyFunction(theSet: CFSetRef, - applier: CFSetApplierFunction, - context: *const c_void); - - pub fn CFSetGetCount(theSet: CFSetRef) -> CFIndex; - - pub fn CFSetGetTypeID() -> CFTypeID; -} - diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/string.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/string.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/string.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/string.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,319 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use libc::{c_char, c_ushort, c_void}; - -use base::{Boolean, CFOptionFlags, CFIndex, CFAllocatorRef, CFRange, CFTypeID}; - -pub type UniChar = c_ushort; - -// CFString.h - -pub type CFStringCompareFlags = CFOptionFlags; -//static kCFCompareCaseInsensitive: CFStringCompareFlags = 1; -//static kCFCompareBackwards: CFStringCompareFlags = 4; -//static kCFCompareAnchored: CFStringCompareFlags = 8; -//static kCFCompareNonliteral: CFStringCompareFlags = 16; -//static kCFCompareLocalized: CFStringCompareFlags = 32; -//static kCFCompareNumerically: CFStringCompareFlags = 64; -//static kCFCompareDiacriticInsensitive: CFStringCompareFlags = 128; -//static kCFCompareWidthInsensitive: CFStringCompareFlags = 256; -//static kCFCompareForcedOrdering: CFStringCompareFlags = 512; - -pub type CFStringEncoding = u32; - -// OS X built-in encodings. - -//static kCFStringEncodingMacRoman: CFStringEncoding = 0; -//static kCFStringEncodingWindowsLatin1: CFStringEncoding = 0x0500; -//static kCFStringEncodingISOLatin1: CFStringEncoding = 0x0201; -//static kCFStringEncodingNextStepLatin: CFStringEncoding = 0x0B01; -//static kCFStringEncodingASCII: CFStringEncoding = 0x0600; -//static kCFStringEncodingUnicode: CFStringEncoding = 0x0100; -pub static kCFStringEncodingUTF8: CFStringEncoding = 0x08000100; -//static kCFStringEncodingNonLossyASCII: CFStringEncoding = 0x0BFF; - -//static kCFStringEncodingUTF16: CFStringEncoding = 0x0100; -//static kCFStringEncodingUTF16BE: CFStringEncoding = 0x10000100; -//static kCFStringEncodingUTF16LE: CFStringEncoding = 0x14000100; -//static kCFStringEncodingUTF32: CFStringEncoding = 0x0c000100; -//static kCFStringEncodingUTF32BE: CFStringEncoding = 0x18000100; -//static kCFStringEncodingUTF32LE: CFStringEncoding = 0x1c000100; - - -// CFStringEncodingExt.h - -pub type CFStringEncodings = CFIndex; - -// External encodings, except those defined above. -// Defined above: kCFStringEncodingMacRoman = 0 -//static kCFStringEncodingMacJapanese: CFStringEncoding = 1; -//static kCFStringEncodingMacChineseTrad: CFStringEncoding = 2; -//static kCFStringEncodingMacKorean: CFStringEncoding = 3; -//static kCFStringEncodingMacArabic: CFStringEncoding = 4; -//static kCFStringEncodingMacHebrew: CFStringEncoding = 5; -//static kCFStringEncodingMacGreek: CFStringEncoding = 6; -//static kCFStringEncodingMacCyrillic: CFStringEncoding = 7; -//static kCFStringEncodingMacDevanagari: CFStringEncoding = 9; -//static kCFStringEncodingMacGurmukhi: CFStringEncoding = 10; -//static kCFStringEncodingMacGujarati: CFStringEncoding = 11; -//static kCFStringEncodingMacOriya: CFStringEncoding = 12; -//static kCFStringEncodingMacBengali: CFStringEncoding = 13; -//static kCFStringEncodingMacTamil: CFStringEncoding = 14; -//static kCFStringEncodingMacTelugu: CFStringEncoding = 15; -//static kCFStringEncodingMacKannada: CFStringEncoding = 16; -//static kCFStringEncodingMacMalayalam: CFStringEncoding = 17; -//static kCFStringEncodingMacSinhalese: CFStringEncoding = 18; -//static kCFStringEncodingMacBurmese: CFStringEncoding = 19; -//static kCFStringEncodingMacKhmer: CFStringEncoding = 20; -//static kCFStringEncodingMacThai: CFStringEncoding = 21; -//static kCFStringEncodingMacLaotian: CFStringEncoding = 22; -//static kCFStringEncodingMacGeorgian: CFStringEncoding = 23; -//static kCFStringEncodingMacArmenian: CFStringEncoding = 24; -//static kCFStringEncodingMacChineseSimp: CFStringEncoding = 25; -//static kCFStringEncodingMacTibetan: CFStringEncoding = 26; -//static kCFStringEncodingMacMongolian: CFStringEncoding = 27; -//static kCFStringEncodingMacEthiopic: CFStringEncoding = 28; -//static kCFStringEncodingMacCentralEurRoman: CFStringEncoding = 29; -//static kCFStringEncodingMacVietnamese: CFStringEncoding = 30; -//static kCFStringEncodingMacExtArabic: CFStringEncoding = 31; -//static kCFStringEncodingMacSymbol: CFStringEncoding = 33; -//static kCFStringEncodingMacDingbats: CFStringEncoding = 34; -//static kCFStringEncodingMacTurkish: CFStringEncoding = 35; -//static kCFStringEncodingMacCroatian: CFStringEncoding = 36; -//static kCFStringEncodingMacIcelandic: CFStringEncoding = 37; -//static kCFStringEncodingMacRomanian: CFStringEncoding = 38; -//static kCFStringEncodingMacCeltic: CFStringEncoding = 39; -//static kCFStringEncodingMacGaelic: CFStringEncoding = 40; -//static kCFStringEncodingMacFarsi: CFStringEncoding = 0x8C; -//static kCFStringEncodingMacUkrainian: CFStringEncoding = 0x98; -//static kCFStringEncodingMacInuit: CFStringEncoding = 0xEC; -//static kCFStringEncodingMacVT100: CFStringEncoding = 0xFC; -//static kCFStringEncodingMacHFS: CFStringEncoding = 0xFF; -// Defined above: kCFStringEncodingISOLatin1 = 0x0201 -//static kCFStringEncodingISOLatin2: CFStringEncoding = 0x0202; -//static kCFStringEncodingISOLatin3: CFStringEncoding = 0x0203; -//static kCFStringEncodingISOLatin4: CFStringEncoding = 0x0204; -//static kCFStringEncodingISOLatinCyrillic: CFStringEncoding = 0x0205; -//static kCFStringEncodingISOLatinArabic: CFStringEncoding = 0x0206; -//static kCFStringEncodingISOLatinGreek: CFStringEncoding = 0x0207; -//static kCFStringEncodingISOLatinHebrew: CFStringEncoding = 0x0208; -//static kCFStringEncodingISOLatin5: CFStringEncoding = 0x0209; -//static kCFStringEncodingISOLatin6: CFStringEncoding = 0x020A; -//static kCFStringEncodingISOLatinThai: CFStringEncoding = 0x020B; -//static kCFStringEncodingISOLatin7: CFStringEncoding = 0x020D; -//static kCFStringEncodingISOLatin8: CFStringEncoding = 0x020E; -//static kCFStringEncodingISOLatin9: CFStringEncoding = 0x020F; -//static kCFStringEncodingISOLatin10: CFStringEncoding = 0x0210; -//static kCFStringEncodingDOSLatinUS: CFStringEncoding = 0x0400; -//static kCFStringEncodingDOSGreek: CFStringEncoding = 0x0405; -//static kCFStringEncodingDOSBalticRim: CFStringEncoding = 0x0406; -//static kCFStringEncodingDOSLatin1: CFStringEncoding = 0x0410; -//static kCFStringEncodingDOSGreek1: CFStringEncoding = 0x0411; -//static kCFStringEncodingDOSLatin2: CFStringEncoding = 0x0412; -//static kCFStringEncodingDOSCyrillic: CFStringEncoding = 0x0413; -//static kCFStringEncodingDOSTurkish: CFStringEncoding = 0x0414; -//static kCFStringEncodingDOSPortuguese: CFStringEncoding = 0x0415; -//static kCFStringEncodingDOSIcelandic: CFStringEncoding = 0x0416; -//static kCFStringEncodingDOSHebrew: CFStringEncoding = 0x0417; -//static kCFStringEncodingDOSCanadianFrench: CFStringEncoding = 0x0418; -//static kCFStringEncodingDOSArabic: CFStringEncoding = 0x0419; -//static kCFStringEncodingDOSNordic: CFStringEncoding = 0x041A; -//static kCFStringEncodingDOSRussian: CFStringEncoding = 0x041B; -//static kCFStringEncodingDOSGreek2: CFStringEncoding = 0x041C; -//static kCFStringEncodingDOSThai: CFStringEncoding = 0x041D; -//static kCFStringEncodingDOSJapanese: CFStringEncoding = 0x0420; -//static kCFStringEncodingDOSChineseSimplif: CFStringEncoding = 0x0421; -//static kCFStringEncodingDOSKorean: CFStringEncoding = 0x0422; -//static kCFStringEncodingDOSChineseTrad: CFStringEncoding = 0x0423; -// Defined above: kCFStringEncodingWindowsLatin1 = 0x0500 -//static kCFStringEncodingWindowsLatin2: CFStringEncoding = 0x0501; -//static kCFStringEncodingWindowsCyrillic: CFStringEncoding = 0x0502; -//static kCFStringEncodingWindowsGreek: CFStringEncoding = 0x0503; -//static kCFStringEncodingWindowsLatin5: CFStringEncoding = 0x0504; -//static kCFStringEncodingWindowsHebrew: CFStringEncoding = 0x0505; -//static kCFStringEncodingWindowsArabic: CFStringEncoding = 0x0506; -//static kCFStringEncodingWindowsBalticRim: CFStringEncoding = 0x0507; -//static kCFStringEncodingWindowsVietnamese: CFStringEncoding = 0x0508; -//static kCFStringEncodingWindowsKoreanJohab: CFStringEncoding = 0x0510; -// Defined above: kCFStringEncodingASCII = 0x0600 -//static kCFStringEncodingANSEL: CFStringEncoding = 0x0601; -//static kCFStringEncodingJIS_X0201_76: CFStringEncoding = 0x0620; -//static kCFStringEncodingJIS_X0208_83: CFStringEncoding = 0x0621; -//static kCFStringEncodingJIS_X0208_90: CFStringEncoding = 0x0622; -//static kCFStringEncodingJIS_X0212_90: CFStringEncoding = 0x0623; -//static kCFStringEncodingJIS_C6226_78: CFStringEncoding = 0x0624; -//static kCFStringEncodingShiftJIS_X0213: CFStringEncoding = 0x0628; -//static kCFStringEncodingShiftJIS_X0213_MenKuTen: CFStringEncoding = 0x0629; -//static kCFStringEncodingGB_2312_80: CFStringEncoding = 0x0630; -//static kCFStringEncodingGBK_95: CFStringEncoding = 0x0631; -//static kCFStringEncodingGB_18030_2000: CFStringEncoding = 0x0632; -//static kCFStringEncodingKSC_5601_87: CFStringEncoding = 0x0640; -//static kCFStringEncodingKSC_5601_92_Johab: CFStringEncoding = 0x0641; -//static kCFStringEncodingCNS_11643_92_P1: CFStringEncoding = 0x0651; -//static kCFStringEncodingCNS_11643_92_P2: CFStringEncoding = 0x0652; -//static kCFStringEncodingCNS_11643_92_P3: CFStringEncoding = 0x0653; -//static kCFStringEncodingISO_2022_JP: CFStringEncoding = 0x0820; -//static kCFStringEncodingISO_2022_JP_2: CFStringEncoding = 0x0821; -//static kCFStringEncodingISO_2022_JP_1: CFStringEncoding = 0x0822; -//static kCFStringEncodingISO_2022_JP_3: CFStringEncoding = 0x0823; -//static kCFStringEncodingISO_2022_CN: CFStringEncoding = 0x0830; -//static kCFStringEncodingISO_2022_CN_EXT: CFStringEncoding = 0x0831; -//static kCFStringEncodingISO_2022_KR: CFStringEncoding = 0x0840; -//static kCFStringEncodingEUC_JP: CFStringEncoding = 0x0920; -//static kCFStringEncodingEUC_CN: CFStringEncoding = 0x0930; -//static kCFStringEncodingEUC_TW: CFStringEncoding = 0x0931; -//static kCFStringEncodingEUC_KR: CFStringEncoding = 0x0940; -//static kCFStringEncodingShiftJIS: CFStringEncoding = 0x0A01; -//static kCFStringEncodingKOI8_R: CFStringEncoding = 0x0A02; -//static kCFStringEncodingBig5: CFStringEncoding = 0x0A03; -//static kCFStringEncodingMacRomanLatin1: CFStringEncoding = 0x0A04; -//static kCFStringEncodingHZ_GB_2312: CFStringEncoding = 0x0A05; -//static kCFStringEncodingBig5_HKSCS_1999: CFStringEncoding = 0x0A06; -//static kCFStringEncodingVISCII: CFStringEncoding = 0x0A07; -//static kCFStringEncodingKOI8_U: CFStringEncoding = 0x0A08; -//static kCFStringEncodingBig5_E: CFStringEncoding = 0x0A09; -// Defined above: kCFStringEncodingNextStepLatin = 0x0B01 -//static kCFStringEncodingNextStepJapanese: CFStringEncoding = 0x0B02; -//static kCFStringEncodingEBCDIC_US: CFStringEncoding = 0x0C01; -//static kCFStringEncodingEBCDIC_CP037: CFStringEncoding = 0x0C02; -//static kCFStringEncodingUTF7: CFStringEncoding = 0x04000100; -//static kCFStringEncodingUTF7_IMAP: CFStringEncoding = 0x0A10; -//static kCFStringEncodingShiftJIS_X0213_00: CFStringEncoding = 0x0628; /* Deprecated */ - -#[repr(C)] -pub struct __CFString(c_void); - -pub type CFStringRef = *const __CFString; - -extern { - /* - * CFString.h - */ - - // N.B. organized according to "Functions by task" in docs - - /* Creating a CFString */ - //fn CFSTR - //fn CFStringCreateArrayBySeparatingStrings - //fn CFStringCreateByCombiningStrings - //fn CFStringCreateCopy - //fn CFStringCreateFromExternalRepresentation - pub fn CFStringCreateWithBytes(alloc: CFAllocatorRef, - bytes: *const u8, - numBytes: CFIndex, - encoding: CFStringEncoding, - isExternalRepresentation: Boolean) - -> CFStringRef; - pub fn CFStringCreateWithBytesNoCopy(alloc: CFAllocatorRef, - bytes: *const u8, - numBytes: CFIndex, - encoding: CFStringEncoding, - isExternalRepresentation: Boolean, - contentsDeallocator: CFAllocatorRef) - -> CFStringRef; - //fn CFStringCreateWithCharacters - //fn CFStringCreateWithCharactersNoCopy - pub fn CFStringCreateWithCString(alloc: CFAllocatorRef, - cStr: *const c_char, - encoding: CFStringEncoding) - -> CFStringRef; - //fn CFStringCreateWithCStringNoCopy - //fn CFStringCreateWithFormat - //fn CFStringCreateWithFormatAndArguments - //fn CFStringCreateWithPascalString - //fn CFStringCreateWithPascalStringNoCopy - //fn CFStringCreateWithSubstring - - /* Searching Strings */ - //fn CFStringCreateArrayWithFindResults - //fn CFStringFind - //fn CFStringFindCharacterFromSet - //fn CFStringFindWithOptions - //fn CFStringFindWithOptionsAndLocale - //fn CFStringGetLineBounds - - /* Comparing Strings */ - //fn CFStringCompare - //fn CFStringCompareWithOptions - //fn CFStringCompareWithOptionsAndLocale - //fn CFStringHasPrefix - //fn CFStringHasSuffix - - /* Accessing Characters */ - //fn CFStringCreateExternalRepresentation - pub fn CFStringGetBytes(theString: CFStringRef, - range: CFRange, - encoding: CFStringEncoding, - lossByte: u8, - isExternalRepresentation: Boolean, - buffer: *mut u8, - maxBufLen: CFIndex, - usedBufLen: *mut CFIndex) - -> CFIndex; - //fn CFStringGetCharacterAtIndex - //fn CFStringGetCharacters - //fn CFStringGetCharactersPtr - //fn CFStringGetCharacterFromInlineBuffer - pub fn CFStringGetCString(theString: CFStringRef, - buffer: *mut c_char, - bufferSize: CFIndex, - encoding: CFStringEncoding) - -> Boolean; - pub fn CFStringGetCStringPtr(theString: CFStringRef, - encoding: CFStringEncoding) - -> *const c_char; - pub fn CFStringGetLength(theString: CFStringRef) -> CFIndex; - //fn CFStringGetPascalString - //fn CFStringGetPascalStringPtr - //fn CFStringGetRangeOfComposedCharactersAtIndex - //fn CFStringInitInlineBuffer - - /* Working With Hyphenation */ - //fn CFStringGetHyphenationLocationBeforeIndex - //fn CFStringIsHyphenationAvailableForLocale - - /* Working With Encodings */ - //fn CFStringConvertEncodingToIANACharSetName - //fn CFStringConvertEncodingToNSStringEncoding - //fn CFStringConvertEncodingToWindowsCodepage - //fn CFStringConvertIANACharSetNameToEncoding - //fn CFStringConvertNSStringEncodingToEncoding - //fn CFStringConvertWindowsCodepageToEncoding - //fn CFStringGetFastestEncoding - //fn CFStringGetListOfAvailableEncodings - //fn CFStringGetMaximumSizeForEncoding - //fn CFStringGetMostCompatibleMacStringEncoding - //fn CFStringGetNameOfEncoding - //fn CFStringGetSmallestEncoding - //fn CFStringGetSystemEncoding - //fn CFStringIsEncodingAvailable - - /* Getting Numeric Values */ - //fn CFStringGetDoubleValue - //fn CFStringGetIntValue - - /* Getting String Properties */ - //fn CFShowStr - pub fn CFStringGetTypeID() -> CFTypeID; - - /* String File System Representations */ - //fn CFStringCreateWithFileSystemRepresentation - //fn CFStringGetFileSystemRepresentation - //fn CFStringGetMaximumSizeOfFileSystemRepresentation - - /* Getting Paragraph Bounds */ - //fn CFStringGetParagraphBounds - - /* Managing Surrogates */ - //fn CFStringGetLongCharacterForSurrogatePair - //fn CFStringGetSurrogatePairForLongCharacter - //fn CFStringIsSurrogateHighCharacter - //fn CFStringIsSurrogateLowCharacter -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/timezone.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/timezone.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/timezone.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/timezone.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use libc::c_void; - -use base::{CFAllocatorRef, CFTypeID}; -use date::{CFTimeInterval, CFAbsoluteTime}; - -#[repr(C)] -pub struct __CFTimeZone(c_void); - -pub type CFTimeZoneRef = *const __CFTimeZone; - -extern { - pub fn CFTimeZoneCopySystem() -> CFTimeZoneRef; - pub fn CFTimeZoneCopyDefault() -> CFTimeZoneRef; - pub fn CFTimeZoneCreateWithTimeIntervalFromGMT(allocator: CFAllocatorRef, interval: CFTimeInterval) -> CFTimeZoneRef; - pub fn CFTimeZoneGetSecondsFromGMT(tz: CFTimeZoneRef, time: CFAbsoluteTime) -> CFTimeInterval; - - pub fn CFTimeZoneGetTypeID() -> CFTypeID; -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/url.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/url.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/url.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/url.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,163 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -use libc::c_void; - -use base::{CFOptionFlags, CFIndex, CFAllocatorRef, Boolean, CFTypeID, CFTypeRef, SInt32}; -use string::{CFStringRef, CFStringEncoding}; -use error::CFErrorRef; - -#[repr(C)] -pub struct __CFURL(c_void); - -pub type CFURLRef = *const __CFURL; - -pub type CFURLBookmarkCreationOptions = CFOptionFlags; - -pub type CFURLPathStyle = CFIndex; - -/* typedef CF_ENUM(CFIndex, CFURLPathStyle) */ -pub const kCFURLPOSIXPathStyle: CFURLPathStyle = 0; -pub const kCFURLHFSPathStyle: CFURLPathStyle = 1; -pub const kCFURLWindowsPathStyle: CFURLPathStyle = 2; - -// static kCFURLBookmarkCreationPreferFileIDResolutionMask: CFURLBookmarkCreationOptions = -// (1 << 8) as u32; -// static kCFURLBookmarkCreationMinimalBookmarkMask: CFURLBookmarkCreationOptions = -// (1 << 9) as u32; -// static kCFURLBookmarkCreationSuitableForBookmarkFile: CFURLBookmarkCreationOptions = -// (1 << 10) as u32; -// static kCFURLBookmarkCreationWithSecurityScope: CFURLBookmarkCreationOptions = -// (1 << 11) as u32; -// static kCFURLBookmarkCreationSecurityScopeAllowOnlyReadAccess: CFURLBookmarkCreationOptions = -// (1 << 12) as u32; - -// TODO: there are a lot of missing keys and constants. Add if you are bored or need them. - -extern { - /* - * CFURL.h - */ - - /* Common File System Resource Keys */ - pub static kCFURLAttributeModificationDateKey: CFStringRef; - pub static kCFURLContentAccessDateKey: CFStringRef; - pub static kCFURLContentModificationDateKey: CFStringRef; - pub static kCFURLCreationDateKey: CFStringRef; - pub static kCFURLFileResourceIdentifierKey: CFStringRef; - pub static kCFURLFileSecurityKey: CFStringRef; - pub static kCFURLHasHiddenExtensionKey: CFStringRef; - pub static kCFURLIsDirectoryKey: CFStringRef; - pub static kCFURLIsExecutableKey: CFStringRef; - pub static kCFURLIsHiddenKey: CFStringRef; - pub static kCFURLIsPackageKey: CFStringRef; - pub static kCFURLIsReadableKey: CFStringRef; - pub static kCFURLIsRegularFileKey: CFStringRef; - pub static kCFURLIsSymbolicLinkKey: CFStringRef; - pub static kCFURLIsSystemImmutableKey: CFStringRef; - pub static kCFURLIsUserImmutableKey: CFStringRef; - pub static kCFURLIsVolumeKey: CFStringRef; - pub static kCFURLIsWritableKey: CFStringRef; - pub static kCFURLLabelNumberKey: CFStringRef; - pub static kCFURLLinkCountKey: CFStringRef; - pub static kCFURLLocalizedLabelKey: CFStringRef; - pub static kCFURLLocalizedNameKey: CFStringRef; - pub static kCFURLLocalizedTypeDescriptionKey: CFStringRef; - pub static kCFURLNameKey: CFStringRef; - pub static kCFURLParentDirectoryURLKey: CFStringRef; - pub static kCFURLPreferredIOBlockSizeKey: CFStringRef; - pub static kCFURLTypeIdentifierKey: CFStringRef; - pub static kCFURLVolumeIdentifierKey: CFStringRef; - pub static kCFURLVolumeURLKey: CFStringRef; - - #[cfg(feature="mac_os_10_8_features")] - #[cfg_attr(feature = "mac_os_10_7_support", linkage = "extern_weak")] - pub static kCFURLIsExcludedFromBackupKey: CFStringRef; - pub static kCFURLFileResourceTypeKey: CFStringRef; - - /* Creating a CFURL */ - pub fn CFURLCopyAbsoluteURL(anURL: CFURLRef) -> CFURLRef; - //fn CFURLCreateAbsoluteURLWithBytes - //fn CFURLCreateByResolvingBookmarkData - //fn CFURLCreateCopyAppendingPathComponent - //fn CFURLCreateCopyAppendingPathExtension - //fn CFURLCreateCopyDeletingLastPathComponent - //fn CFURLCreateCopyDeletingPathExtension - pub fn CFURLCreateFilePathURL(allocator: CFAllocatorRef, url: CFURLRef, error: *mut CFErrorRef) -> CFURLRef; - //fn CFURLCreateFileReferenceURL - pub fn CFURLCreateFromFileSystemRepresentation(allocator: CFAllocatorRef, buffer: *const u8, bufLen: CFIndex, isDirectory: Boolean) -> CFURLRef; - //fn CFURLCreateFromFileSystemRepresentationRelativeToBase - //fn CFURLCreateFromFSRef - pub fn CFURLCreateWithBytes(allocator: CFAllocatorRef, URLBytes: *const u8, length: CFIndex, encoding: CFStringEncoding, baseURL: CFURLRef) -> CFURLRef; - pub fn CFURLCreateWithFileSystemPath(allocator: CFAllocatorRef, filePath: CFStringRef, pathStyle: CFURLPathStyle, isDirectory: Boolean) -> CFURLRef; - pub fn CFURLCreateWithFileSystemPathRelativeToBase(allocator: CFAllocatorRef, filePath: CFStringRef, pathStyle: CFURLPathStyle, isDirectory: Boolean, baseURL: CFURLRef) -> CFURLRef; - //fn CFURLCreateWithString(allocator: CFAllocatorRef, urlString: CFStringRef, - // baseURL: CFURLRef) -> CFURLRef; - - /* Accessing the Parts of a URL */ - pub fn CFURLCanBeDecomposed(anURL: CFURLRef) -> Boolean; - pub fn CFURLCopyFileSystemPath(anURL: CFURLRef, pathStyle: CFURLPathStyle) -> CFStringRef; - pub fn CFURLCopyFragment(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; - pub fn CFURLCopyHostName(anURL: CFURLRef) -> CFStringRef; - pub fn CFURLCopyLastPathComponent(anURL: CFURLRef) -> CFStringRef; - pub fn CFURLCopyNetLocation(anURL: CFURLRef) -> CFStringRef; - pub fn CFURLCopyParameterString(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; - pub fn CFURLCopyPassword(anURL: CFURLRef) -> CFStringRef; - pub fn CFURLCopyPath(anURL: CFURLRef) -> CFStringRef; - pub fn CFURLCopyPathExtension(anURL: CFURLRef) -> CFStringRef; - pub fn CFURLCopyQueryString(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; - pub fn CFURLCopyResourceSpecifier(anURL: CFURLRef) -> CFStringRef; - pub fn CFURLCopyScheme(anURL: CFURLRef) -> CFStringRef; - pub fn CFURLCopyStrictPath(anURL: CFURLRef, isAbsolute: *mut Boolean) -> CFStringRef; - pub fn CFURLCopyUserName(anURL: CFURLRef) -> CFStringRef; - pub fn CFURLGetPortNumber(anURL: CFURLRef) -> SInt32; - pub fn CFURLHasDirectoryPath(anURL: CFURLRef) -> Boolean; - - /* Converting URLs to Other Representations */ - //fn CFURLCreateData(allocator: CFAllocatorRef, url: CFURLRef, - // encoding: CFStringEncoding, escapeWhitespace: bool) -> CFDataRef; - //fn CFURLCreateStringByAddingPercentEscapes - //fn CFURLCreateStringByReplacingPercentEscapes - //fn CFURLCreateStringByReplacingPercentEscapesUsingEncoding - pub fn CFURLGetFileSystemRepresentation(anURL: CFURLRef, resolveAgainstBase: Boolean, buffer: *mut u8, maxBufLen: CFIndex) -> Boolean; - - //fn CFURLGetFSRef - pub fn CFURLGetString(anURL: CFURLRef) -> CFStringRef; - - /* Getting URL Properties */ - //fn CFURLGetBaseURL(anURL: CFURLRef) -> CFURLRef; - pub fn CFURLGetBytes(anURL: CFURLRef, buffer: *mut u8, bufferLength: CFIndex) -> CFIndex; - //fn CFURLGetByteRangeForComponent - pub fn CFURLGetTypeID() -> CFTypeID; - //fn CFURLResourceIsReachable - - /* Getting and Setting File System Resource Properties */ - pub fn CFURLClearResourcePropertyCache(url: CFURLRef); - //fn CFURLClearResourcePropertyCacheForKey - //fn CFURLCopyResourcePropertiesForKeys - //fn CFURLCopyResourcePropertyForKey - //fn CFURLCreateResourcePropertiesForKeysFromBookmarkData - //fn CFURLCreateResourcePropertyForKeyFromBookmarkData - //fn CFURLSetResourcePropertiesForKeys - pub fn CFURLSetResourcePropertyForKey(url: CFURLRef, key: CFStringRef, value: CFTypeRef, error: *mut CFErrorRef) -> Boolean; - //fn CFURLSetTemporaryResourcePropertyForKey - - /* Working with Bookmark Data */ - //fn CFURLCreateBookmarkData - //fn CFURLCreateBookmarkDataFromAliasRecord - //fn CFURLCreateBookmarkDataFromFile - //fn CFURLWriteBookmarkDataToFile - //fn CFURLStartAccessingSecurityScopedResource - //fn CFURLStopAccessingSecurityScopedResource -} - -#[test] -#[cfg(feature="mac_os_10_8_features")] -fn can_see_excluded_from_backup_key() { - let _ = unsafe { kCFURLIsExcludedFromBackupKey }; -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/uuid.rs cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/uuid.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.4.6/src/uuid.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.4.6/src/uuid.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -use libc::c_void; - -use base::{CFAllocatorRef, CFTypeID}; - -#[repr(C)] -pub struct __CFUUID(c_void); - -pub type CFUUIDRef = *const __CFUUID; - -#[repr(C)] -#[derive(Clone, Copy, Default)] -pub struct CFUUIDBytes { - pub byte0: u8, - pub byte1: u8, - pub byte2: u8, - pub byte3: u8, - pub byte4: u8, - pub byte5: u8, - pub byte6: u8, - pub byte7: u8, - pub byte8: u8, - pub byte9: u8, - pub byte10: u8, - pub byte11: u8, - pub byte12: u8, - pub byte13: u8, - pub byte14: u8, - pub byte15: u8 -} - -extern { - /* - * CFUUID.h - */ - pub fn CFUUIDCreate(allocator: CFAllocatorRef) -> CFUUIDRef; - pub fn CFUUIDCreateFromUUIDBytes(allocator: CFAllocatorRef, bytes: CFUUIDBytes) -> CFUUIDRef; - pub fn CFUUIDGetUUIDBytes(uuid: CFUUIDRef) -> CFUUIDBytes; - - pub fn CFUUIDGetTypeID() -> CFTypeID; -} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/build.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/build.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/build.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/build.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,14 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +fn main() { + if std::env::var("TARGET").unwrap().contains("-apple") { + println!("cargo:rustc-link-lib=framework=CoreFoundation"); + } +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/.cargo-checksum.json cargo-0.26.0/vendor/core-foundation-sys-0.5.1/.cargo-checksum.json --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"716c271e8613ace48344f723b60b900a93150271e5be206212d052bbc0883efa"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/Cargo.toml cargo-0.26.0/vendor/core-foundation-sys-0.5.1/Cargo.toml --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,27 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "core-foundation-sys" +version = "0.5.1" +authors = ["The Servo Project Developers"] +build = "build.rs" +description = "Bindings to Core Foundation for OS X" +homepage = "https://github.com/servo/core-foundation-rs" +license = "MIT / Apache-2.0" +repository = "https://github.com/servo/core-foundation-rs" +[dependencies.libc] +version = "0.2" + +[features] +mac_os_10_7_support = [] +mac_os_10_8_features = [] diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/LICENSE-APACHE cargo-0.26.0/vendor/core-foundation-sys-0.5.1/LICENSE-APACHE --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/LICENSE-MIT cargo-0.26.0/vendor/core-foundation-sys-0.5.1/LICENSE-MIT --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2012-2013 Mozilla Foundation + +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. diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/array.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/array.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/array.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/array.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,55 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use libc::c_void; + +use base::{CFRange, CFIndex, CFAllocatorRef, CFTypeID, Boolean}; +use string::CFStringRef; + +pub type CFArrayRetainCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; +pub type CFArrayReleaseCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void); +pub type CFArrayCopyDescriptionCallBack = extern "C" fn(value: *const c_void) -> CFStringRef; +pub type CFArrayEqualCallBack = extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFArrayCallBacks { + pub version: CFIndex, + pub retain: CFArrayRetainCallBack, + pub release: CFArrayReleaseCallBack, + pub copyDescription: CFArrayCopyDescriptionCallBack, + pub equal: CFArrayEqualCallBack, +} + +#[repr(C)] +pub struct __CFArray(c_void); + +pub type CFArrayRef = *const __CFArray; + +extern { + /* + * CFArray.h + */ + pub static kCFTypeArrayCallBacks: CFArrayCallBacks; + + pub fn CFArrayCreate(allocator: CFAllocatorRef, values: *const *const c_void, + numValues: CFIndex, callBacks: *const CFArrayCallBacks) -> CFArrayRef; + pub fn CFArrayCreateCopy(allocator: CFAllocatorRef , theArray: CFArrayRef) -> CFArrayRef; + + // CFArrayBSearchValues + // CFArrayContainsValue + pub fn CFArrayGetCount(theArray: CFArrayRef) -> CFIndex; + // CFArrayGetCountOfValue + // CFArrayGetFirstIndexOfValue + // CFArrayGetLastIndexOfValue + pub fn CFArrayGetValues(theArray: CFArrayRef, range: CFRange, values: *mut *const c_void); + pub fn CFArrayGetValueAtIndex(theArray: CFArrayRef, idx: CFIndex) -> *const c_void; + // CFArrayApplyFunction + pub fn CFArrayGetTypeID() -> CFTypeID; +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/base.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/base.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/base.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/base.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,154 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cmp::Ordering; +use libc::{c_uint, c_long, c_ulong, c_void, c_int}; +use string::CFStringRef; + +pub type Boolean = u8; +pub type CFIndex = c_long; +pub type mach_port_t = c_uint; +pub type CFAllocatorRef = *const c_void; +pub type CFNullRef = *const c_void; +pub type CFHashCode = c_ulong; +pub type CFTypeID = c_ulong; +pub type CFTypeRef = *const c_void; +pub type CFOptionFlags = u32; +pub type OSStatus = i32; +pub type SInt32 = c_int; + +#[repr(i64)] +#[derive(Clone, Copy)] +pub enum CFComparisonResult { + LessThan = -1, + EqualTo = 0, + GreaterThan = 1, +} + +impl Into for CFComparisonResult { + fn into(self) -> Ordering { + match self { + CFComparisonResult::LessThan => Ordering::Less, + CFComparisonResult::EqualTo => Ordering::Equal, + CFComparisonResult::GreaterThan => Ordering::Greater + } + } +} + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFRange { + pub location: CFIndex, + pub length: CFIndex +} + +// for back-compat +impl CFRange { + pub fn init(location: CFIndex, length: CFIndex) -> CFRange { + CFRange { + location: location, + length: length, + } + } +} + +pub type CFAllocatorRetainCallBack = extern "C" fn(info: *mut c_void) -> *mut c_void; +pub type CFAllocatorReleaseCallBack = extern "C" fn(info: *mut c_void); +pub type CFAllocatorCopyDescriptionCallBack = extern "C" fn(info: *mut c_void) -> CFStringRef; +pub type CFAllocatorAllocateCallBack = extern "C" fn(allocSize: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> *mut c_void; +pub type CFAllocatorReallocateCallBack = extern "C" fn(ptr: *mut c_void, newsize: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> *mut c_void; +pub type CFAllocatorDeallocateCallBack = extern "C" fn(ptr: *mut c_void, info: *mut c_void); +pub type CFAllocatorPreferredSizeCallBack = extern "C" fn(size: CFIndex, hint: CFOptionFlags, info: *mut c_void) -> CFIndex; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFAllocatorContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: CFAllocatorRetainCallBack, + pub release: CFAllocatorReleaseCallBack, + pub copyDescription: CFAllocatorCopyDescriptionCallBack, + pub allocate: CFAllocatorAllocateCallBack, + pub reallocate: CFAllocatorReallocateCallBack, + pub deallocate: CFAllocatorDeallocateCallBack, + pub preferredSize: CFAllocatorPreferredSizeCallBack +} + +/// Trait for all types which are Core Foundation reference types. +pub trait TCFTypeRef { + fn as_void_ptr(&self) -> *const c_void; + + unsafe fn from_void_ptr(ptr: *const c_void) -> Self; +} + +impl TCFTypeRef for *const T { + fn as_void_ptr(&self) -> *const c_void { + (*self) as *const c_void + } + + unsafe fn from_void_ptr(ptr: *const c_void) -> Self { + ptr as *const T + } +} + +impl TCFTypeRef for *mut T { + fn as_void_ptr(&self) -> *const c_void { + (*self) as *const T as *const c_void + } + + unsafe fn from_void_ptr(ptr: *const c_void) -> Self { + ptr as *const T as *mut T + } +} + +extern { + /* + * CFBase.h + */ + + /* CFAllocator Reference */ + + pub static kCFAllocatorDefault: CFAllocatorRef; + pub static kCFAllocatorSystemDefault: CFAllocatorRef; + pub static kCFAllocatorMalloc: CFAllocatorRef; + pub static kCFAllocatorMallocZone: CFAllocatorRef; + pub static kCFAllocatorNull: CFAllocatorRef; + pub static kCFAllocatorUseContext: CFAllocatorRef; + + pub fn CFAllocatorCreate(allocator: CFAllocatorRef, context: *mut CFAllocatorContext) -> CFAllocatorRef; + pub fn CFAllocatorAllocate(allocator: CFAllocatorRef, size: CFIndex, hint: CFOptionFlags) -> *mut c_void; + pub fn CFAllocatorDeallocate(allocator: CFAllocatorRef, ptr: *mut c_void); + pub fn CFAllocatorGetPreferredSizeForSize(allocator: CFAllocatorRef, size: CFIndex, hint: CFOptionFlags) -> CFIndex; + pub fn CFAllocatorReallocate(allocator: CFAllocatorRef, ptr: *mut c_void, newsize: CFIndex, hint: CFOptionFlags) -> *mut c_void; + pub fn CFAllocatorGetDefault() -> CFAllocatorRef; + pub fn CFAllocatorSetDefault(allocator: CFAllocatorRef); + pub fn CFAllocatorGetContext(allocator: CFAllocatorRef, context: *mut CFAllocatorContext); + pub fn CFAllocatorGetTypeID() -> CFTypeID; + + /* CFNull Reference */ + + pub static kCFNull: CFNullRef; + + /* CFType Reference */ + + //fn CFCopyTypeIDDescription + //fn CFGetAllocator + pub fn CFCopyDescription(cf: CFTypeRef) -> CFStringRef; + pub fn CFEqual(cf1: CFTypeRef, cf2: CFTypeRef) -> Boolean; + pub fn CFGetRetainCount(cf: CFTypeRef) -> CFIndex; + pub fn CFGetTypeID(cf: CFTypeRef) -> CFTypeID; + pub fn CFHash(cf: CFTypeRef) -> CFHashCode; + //fn CFMakeCollectable + pub fn CFRelease(cf: CFTypeRef); + pub fn CFRetain(cf: CFTypeRef) -> CFTypeRef; + pub fn CFShow(obj: CFTypeRef); + + /* Base Utilities Reference */ + // N.B. Some things missing here. +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/bundle.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/bundle.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/bundle.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/bundle.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,36 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use libc::c_void; + +use base::{CFTypeID, CFAllocatorRef}; +use url::CFURLRef; +use dictionary::CFDictionaryRef; +use string::CFStringRef; + +#[repr(C)] +pub struct __CFBundle(c_void); + +pub type CFBundleRef = *mut __CFBundle; + +extern { + /* + * CFBundle.h + */ + pub fn CFBundleCreate(allocator: CFAllocatorRef, bundleURL: CFURLRef) -> CFBundleRef; + + pub fn CFBundleGetBundleWithIdentifier(bundleID: CFStringRef) -> CFBundleRef; + pub fn CFBundleGetFunctionPointerForName(bundle: CFBundleRef, function_name: CFStringRef) -> *const c_void; + pub fn CFBundleGetMainBundle() -> CFBundleRef; + pub fn CFBundleGetInfoDictionary(bundle: CFBundleRef) -> CFDictionaryRef; + + pub fn CFBundleGetTypeID() -> CFTypeID; + pub fn CFBundleCopyExecutableURL(bundle: CFBundleRef) -> CFURLRef; + pub fn CFBundleCopyPrivateFrameworksURL(bundle: CFBundleRef) -> CFURLRef; +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/data.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/data.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/data.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/data.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,22 @@ +use libc::c_void; + +use base::{CFAllocatorRef, CFTypeID, CFIndex}; + +#[repr(C)] +pub struct __CFData(c_void); + +pub type CFDataRef = *const __CFData; + +extern { + /* + * CFData.h + */ + + pub fn CFDataCreate(allocator: CFAllocatorRef, + bytes: *const u8, length: CFIndex) -> CFDataRef; + //fn CFDataFind + pub fn CFDataGetBytePtr(theData: CFDataRef) -> *const u8; + pub fn CFDataGetLength(theData: CFDataRef) -> CFIndex; + + pub fn CFDataGetTypeID() -> CFTypeID; +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/date.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/date.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/date.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/date.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,34 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use libc::c_void; + +use base::{CFAllocatorRef, CFComparisonResult, CFTypeID}; + +#[repr(C)] +pub struct __CFDate(c_void); + +pub type CFDateRef = *const __CFDate; + +pub type CFTimeInterval = f64; +pub type CFAbsoluteTime = CFTimeInterval; + +extern { + pub static kCFAbsoluteTimeIntervalSince1904: CFTimeInterval; + pub static kCFAbsoluteTimeIntervalSince1970: CFTimeInterval; + + pub fn CFAbsoluteTimeGetCurrent() -> CFAbsoluteTime; + + pub fn CFDateCreate(allocator: CFAllocatorRef, at: CFAbsoluteTime) -> CFDateRef; + pub fn CFDateGetAbsoluteTime(date: CFDateRef) -> CFAbsoluteTime; + pub fn CFDateGetTimeIntervalSinceDate(date: CFDateRef, other: CFDateRef) -> CFTimeInterval; + pub fn CFDateCompare(date: CFDateRef, other: CFDateRef, context: *mut c_void) -> CFComparisonResult; + + pub fn CFDateGetTypeID() -> CFTypeID; +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/dictionary.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/dictionary.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/dictionary.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/dictionary.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,91 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use libc::{c_void}; + +use base::{CFAllocatorRef, CFHashCode, CFIndex, CFTypeID, Boolean}; +use string::CFStringRef; + +pub type CFDictionaryApplierFunction = extern "C" fn(key: *const c_void, value: *const c_void, context: *mut c_void); + +pub type CFDictionaryRetainCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void) -> *const c_void; +pub type CFDictionaryReleaseCallBack = extern "C" fn(allocator: CFAllocatorRef, value: *const c_void); +pub type CFDictionaryCopyDescriptionCallBack = extern "C" fn(value: *const c_void) -> CFStringRef; +pub type CFDictionaryEqualCallBack = extern "C" fn(value1: *const c_void, value2: *const c_void) -> Boolean; +pub type CFDictionaryHashCallBack = extern "C" fn(value: *const c_void) -> CFHashCode; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFDictionaryKeyCallBacks { + pub version: CFIndex, + pub retain: CFDictionaryRetainCallBack, + pub release: CFDictionaryReleaseCallBack, + pub copyDescription: CFDictionaryCopyDescriptionCallBack, + pub equal: CFDictionaryEqualCallBack, + pub hash: CFDictionaryHashCallBack +} + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFDictionaryValueCallBacks { + pub version: CFIndex, + pub retain: CFDictionaryRetainCallBack, + pub release: CFDictionaryReleaseCallBack, + pub copyDescription: CFDictionaryCopyDescriptionCallBack, + pub equal: CFDictionaryEqualCallBack +} + +#[repr(C)] +pub struct __CFDictionary(c_void); + +pub type CFDictionaryRef = *const __CFDictionary; +pub type CFMutableDictionaryRef = *mut __CFDictionary; + +extern { + /* + * CFDictionary.h + */ + + pub static kCFTypeDictionaryKeyCallBacks: CFDictionaryKeyCallBacks; + pub static kCFTypeDictionaryValueCallBacks: CFDictionaryValueCallBacks; + + pub fn CFDictionaryContainsKey(theDict: CFDictionaryRef, key: *const c_void) -> Boolean; + pub fn CFDictionaryCreate(allocator: CFAllocatorRef, keys: *const *const c_void, values: *const *const c_void, + numValues: CFIndex, keyCallBacks: *const CFDictionaryKeyCallBacks, + valueCallBacks: *const CFDictionaryValueCallBacks) + -> CFDictionaryRef; + pub fn CFDictionaryGetCount(theDict: CFDictionaryRef) -> CFIndex; + pub fn CFDictionaryGetTypeID() -> CFTypeID; + pub fn CFDictionaryGetValueIfPresent(theDict: CFDictionaryRef, key: *const c_void, value: *mut *const c_void) + -> Boolean; + pub fn CFDictionaryApplyFunction(theDict: CFDictionaryRef, + applier: CFDictionaryApplierFunction, + context: *mut c_void); + pub fn CFDictionaryGetKeysAndValues(theDict: CFDictionaryRef, + keys: *mut *const c_void, + values: *mut *const c_void); + + pub fn CFDictionaryCreateMutable(allocator: CFAllocatorRef, capacity: CFIndex, + keyCallbacks: *const CFDictionaryKeyCallBacks, + valueCallbacks: *const CFDictionaryValueCallBacks) -> CFMutableDictionaryRef; + pub fn CFDictionaryCreateMutableCopy(allocator: CFAllocatorRef, capacity: CFIndex, + theDict: CFDictionaryRef) -> CFMutableDictionaryRef; + pub fn CFDictionaryAddValue(theDict: CFMutableDictionaryRef, + key: *const c_void, + value: *const c_void); + pub fn CFDictionarySetValue(theDict: CFMutableDictionaryRef, + key: *const c_void, + value: *const c_void); + pub fn CFDictionaryReplaceValue(theDict: CFMutableDictionaryRef, + key: *const c_void, + value: *const c_void); + pub fn CFDictionaryRemoveValue(theDict: CFMutableDictionaryRef, + key: *const c_void); + pub fn CFDictionaryRemoveAllValues(theDict: CFMutableDictionaryRef); +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/error.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/error.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/error.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/error.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,32 @@ +// Copyright 2016 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use libc::c_void; + +use base::{CFTypeID, CFIndex}; +use string::CFStringRef; + +#[repr(C)] +pub struct __CFError(c_void); + +pub type CFErrorRef = *mut __CFError; + +extern "C" { + pub fn CFErrorGetTypeID() -> CFTypeID; + + pub static kCFErrorDomainPOSIX: CFStringRef; + pub static kCFErrorDomainOSStatus: CFStringRef; + pub static kCFErrorDomainMach: CFStringRef; + pub static kCFErrorDomainCocoa: CFStringRef; + + pub fn CFErrorGetDomain(err: CFErrorRef) -> CFStringRef; + pub fn CFErrorGetCode(err: CFErrorRef) -> CFIndex; + + pub fn CFErrorCopyDescription(err: CFErrorRef) -> CFStringRef; +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/filedescriptor.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/filedescriptor.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/filedescriptor.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/filedescriptor.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,48 @@ +use libc::{c_void, c_int}; +use base::{Boolean, CFIndex, CFTypeID, CFOptionFlags, CFAllocatorRef}; +use string::CFStringRef; +use runloop::CFRunLoopSourceRef; + +pub type CFFileDescriptorNativeDescriptor = c_int; + +#[repr(C)] +pub struct __CFFileDescriptor(c_void); + +pub type CFFileDescriptorRef = *mut __CFFileDescriptor; + +/* Callback Reason Types */ +pub const kCFFileDescriptorReadCallBack: CFOptionFlags = 1 << 0; +pub const kCFFileDescriptorWriteCallBack: CFOptionFlags = 1 << 1; + +pub type CFFileDescriptorCallBack = extern "C" fn (f: CFFileDescriptorRef, callBackTypes: CFOptionFlags, info: *mut c_void); + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFFileDescriptorContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, +} + +extern { + /* + * CFFileDescriptor.h + */ + pub fn CFFileDescriptorGetTypeID() -> CFTypeID; + + pub fn CFFileDescriptorCreate(allocator: CFAllocatorRef, fd: CFFileDescriptorNativeDescriptor, closeOnInvalidate: Boolean, callout: CFFileDescriptorCallBack, context: *const CFFileDescriptorContext) -> CFFileDescriptorRef; + + pub fn CFFileDescriptorGetNativeDescriptor(f: CFFileDescriptorRef) -> CFFileDescriptorNativeDescriptor; + + pub fn CFFileDescriptorGetContext(f: CFFileDescriptorRef, context: *mut CFFileDescriptorContext); + + pub fn CFFileDescriptorEnableCallBacks(f: CFFileDescriptorRef, callBackTypes: CFOptionFlags); + pub fn CFFileDescriptorDisableCallBacks(f: CFFileDescriptorRef, callBackTypes: CFOptionFlags); + + pub fn CFFileDescriptorInvalidate(f: CFFileDescriptorRef); + pub fn CFFileDescriptorIsValid(f: CFFileDescriptorRef) -> Boolean; + + pub fn CFFileDescriptorCreateRunLoopSource(allocator: CFAllocatorRef, f: CFFileDescriptorRef, order: CFIndex) -> CFRunLoopSourceRef; +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/lib.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/lib.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,31 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, improper_ctypes)] + +#![cfg_attr(all(feature="mac_os_10_7_support", feature="mac_os_10_8_features"), feature(linkage))] // back-compat requires weak linkage + +extern crate libc; + +pub mod array; +pub mod base; +pub mod bundle; +pub mod data; +pub mod date; +pub mod dictionary; +pub mod error; +pub mod filedescriptor; +pub mod messageport; +pub mod number; +pub mod propertylist; +pub mod runloop; +pub mod set; +pub mod string; +pub mod timezone; +pub mod url; +pub mod uuid; diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/messageport.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/messageport.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/messageport.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/messageport.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,79 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use libc::c_void; + +use base::{CFAllocatorRef, CFIndex, CFTypeID, Boolean}; +use data::CFDataRef; +use date::CFTimeInterval; +use runloop::CFRunLoopSourceRef; +use string::CFStringRef; + +#[repr(C)] +#[derive(Copy, Clone)] +#[derive(Debug)] +pub struct CFMessagePortContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: Option *const c_void>, + pub release: Option, + pub copyDescription: Option CFStringRef>, +} + +pub type CFMessagePortCallBack = Option< + unsafe extern fn(local: CFMessagePortRef, + msgid: i32, + data: CFDataRef, + info: *mut c_void) -> CFDataRef>; + +pub type CFMessagePortInvalidationCallBack = Option< + unsafe extern "C" fn(ms: CFMessagePortRef, info: *mut c_void)>; + +#[repr(C)] +pub struct __CFMessagePort(c_void); +pub type CFMessagePortRef = *mut __CFMessagePort; + +extern { + /* + * CFMessagePort.h + */ + pub fn CFMessagePortGetTypeID() -> CFTypeID; + pub fn CFMessagePortCreateLocal(allocator: CFAllocatorRef, + name: CFStringRef, + callout: CFMessagePortCallBack, + context: *const CFMessagePortContext, + shouldFreeInfo: *mut Boolean) + -> CFMessagePortRef; + pub fn CFMessagePortCreateRemote(allocator: CFAllocatorRef, + name: CFStringRef) -> CFMessagePortRef; + pub fn CFMessagePortIsRemote(ms: CFMessagePortRef) -> Boolean; + pub fn CFMessagePortGetName(ms: CFMessagePortRef) -> CFStringRef; + pub fn CFMessagePortSetName(ms: CFMessagePortRef, newName: CFStringRef) + -> Boolean; + pub fn CFMessagePortGetContext(ms: CFMessagePortRef, + context: *mut CFMessagePortContext); + pub fn CFMessagePortInvalidate(ms: CFMessagePortRef); + pub fn CFMessagePortIsValid(ms: CFMessagePortRef) -> Boolean; + pub fn CFMessagePortGetInvalidationCallBack(ms: CFMessagePortRef) + -> CFMessagePortInvalidationCallBack; + pub fn CFMessagePortSetInvalidationCallBack(ms: CFMessagePortRef, + callout: CFMessagePortInvalidationCallBack); + pub fn CFMessagePortSendRequest(remote: CFMessagePortRef, msgid: i32, + data: CFDataRef, + sendTimeout: CFTimeInterval, + rcvTimeout: CFTimeInterval, + replyMode: CFStringRef, + returnData: *mut CFDataRef) -> i32; + pub fn CFMessagePortCreateRunLoopSource(allocator: CFAllocatorRef, + local: CFMessagePortRef, + order: CFIndex) + -> CFRunLoopSourceRef; + // CFMessagePortSetDispatchQueue +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/number.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/number.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/number.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/number.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,60 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use libc::c_void; + +use base::{CFAllocatorRef, CFTypeID, CFComparisonResult}; + +#[repr(C)] +pub struct __CFBoolean(c_void); + +pub type CFBooleanRef = *const __CFBoolean; + +pub type CFNumberType = u32; + +// members of enum CFNumberType +// static kCFNumberSInt8Type: CFNumberType = 1; +// static kCFNumberSInt16Type: CFNumberType = 2; +pub static kCFNumberSInt32Type: CFNumberType = 3; +pub static kCFNumberSInt64Type: CFNumberType = 4; +pub static kCFNumberFloat32Type: CFNumberType = 5; +pub static kCFNumberFloat64Type: CFNumberType = 6; +// static kCFNumberCharType: CFNumberType = 7; +// static kCFNumberShortType: CFNumberType = 8; +// static kCFNumberIntType: CFNumberType = 9; +// static kCFNumberLongType: CFNumberType = 10; +// static kCFNumberLongLongType: CFNumberType = 11; +// static kCFNumberFloatType: CFNumberType = 12; +// static kCFNumberDoubleType: CFNumberType = 13; +// static kCFNumberCFIndexType: CFNumberType = 14; +// static kCFNumberNSIntegerType: CFNumberType = 15; +// static kCFNumberCGFloatType: CFNumberType = 16; +// static kCFNumberMaxType: CFNumberType = 16; + +// This is an enum due to zero-sized types warnings. +// For more details see https://github.com/rust-lang/rust/issues/27303 +pub enum __CFNumber {} + +pub type CFNumberRef = *const __CFNumber; + +extern { + /* + * CFNumber.h + */ + pub static kCFBooleanTrue: CFBooleanRef; + pub static kCFBooleanFalse: CFBooleanRef; + + pub fn CFBooleanGetTypeID() -> CFTypeID; + pub fn CFNumberCreate(allocator: CFAllocatorRef, theType: CFNumberType, valuePtr: *const c_void) + -> CFNumberRef; + //fn CFNumberGetByteSize + pub fn CFNumberGetValue(number: CFNumberRef, theType: CFNumberType, valuePtr: *mut c_void) -> bool; + pub fn CFNumberCompare(date: CFNumberRef, other: CFNumberRef, context: *mut c_void) -> CFComparisonResult; + pub fn CFNumberGetTypeID() -> CFTypeID; +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/propertylist.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/propertylist.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/propertylist.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/propertylist.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,37 @@ +use base::{CFAllocatorRef, CFIndex, CFOptionFlags, CFTypeRef}; +use data::CFDataRef; +use error::CFErrorRef; + +pub type CFPropertyListRef = CFTypeRef; + +pub type CFPropertyListFormat = CFIndex; +pub const kCFPropertyListOpenStepFormat: CFPropertyListFormat = 1; +pub const kCFPropertyListXMLFormat_v1_0: CFPropertyListFormat = 100; +pub const kCFPropertyListBinaryFormat_v1_0: CFPropertyListFormat = 200; + +pub type CFPropertyListMutabilityOptions = CFOptionFlags; +pub const kCFPropertyListImmutable: CFPropertyListMutabilityOptions = 0; +pub const kCFPropertyListMutableContainers: CFPropertyListMutabilityOptions = 1; +pub const kCFPropertyListMutableContainersAndLeaves: CFPropertyListMutabilityOptions = 2; + +extern "C" { + // CFPropertyList.h + // + + // fn CFPropertyListCreateDeepCopy + // fn CFPropertyListIsValid + pub fn CFPropertyListCreateWithData(allocator: CFAllocatorRef, + data: CFDataRef, + options: CFPropertyListMutabilityOptions, + format: *mut CFPropertyListFormat, + error: *mut CFErrorRef) + -> CFPropertyListRef; + // fn CFPropertyListCreateWithStream + // fn CFPropertyListWrite + pub fn CFPropertyListCreateData(allocator: CFAllocatorRef, + propertyList: CFPropertyListRef, + format: CFPropertyListFormat, + options: CFOptionFlags, + error: *mut CFErrorRef) + -> CFDataRef; +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/runloop.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/runloop.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/runloop.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/runloop.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,164 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use libc::c_void; + +use array::CFArrayRef; +use base::{Boolean, CFIndex, CFTypeID, CFAllocatorRef, CFOptionFlags, CFHashCode, mach_port_t}; +use date::{CFAbsoluteTime, CFTimeInterval}; +use string::CFStringRef; + +#[repr(C)] +pub struct __CFRunLoop(c_void); + +pub type CFRunLoopRef = *mut __CFRunLoop; + +#[repr(C)] +pub struct __CFRunLoopSource(c_void); + +pub type CFRunLoopSourceRef = *mut __CFRunLoopSource; + +#[repr(C)] +pub struct __CFRunLoopObserver(c_void); + +pub type CFRunLoopObserverRef = *mut __CFRunLoopObserver; + +// Reasons for CFRunLoopRunInMode() to Return +pub const kCFRunLoopRunFinished: i32 = 1; +pub const kCFRunLoopRunStopped: i32 = 2; +pub const kCFRunLoopRunTimedOut: i32 = 3; +pub const kCFRunLoopRunHandledSource: i32 = 4; + +// Run Loop Observer Activities +//typedef CF_OPTIONS(CFOptionFlags, CFRunLoopActivity) { +pub type CFRunLoopActivity = CFOptionFlags; +pub const kCFRunLoopEntry: CFOptionFlags = 1 << 0; +pub const kCFRunLoopBeforeTimers: CFOptionFlags = 1 << 1; +pub const kCFRunLoopBeforeSources: CFOptionFlags = 1 << 2; +pub const kCFRunLoopBeforeWaiting: CFOptionFlags = 1 << 5; +pub const kCFRunLoopAfterWaiting: CFOptionFlags = 1 << 6; +pub const kCFRunLoopExit: CFOptionFlags = 1 << 7; +pub const kCFRunLoopAllActivities: CFOptionFlags = 0x0FFFFFFF; + +#[repr(C)] +pub struct CFRunLoopSourceContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: extern "C" fn (info: *const c_void) -> *const c_void, + pub release: extern "C" fn (info: *const c_void), + pub copyDescription: extern "C" fn (info: *const c_void) -> CFStringRef, + pub equal: extern "C" fn (info1: *const c_void, info2: *const c_void) -> Boolean, + pub hash: extern "C" fn (info: *const c_void) -> CFHashCode, + pub schedule: extern "C" fn (info: *const c_void, rl: CFRunLoopRef, mode: CFStringRef), + pub cancel: extern "C" fn (info: *const c_void, rl: CFRunLoopRef, mode: CFStringRef), + pub perform: extern "C" fn (info: *const c_void), +} + +#[repr(C)] +pub struct CFRunLoopSourceContext1 { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: extern "C" fn (info: *const c_void) -> *const c_void, + pub release: extern "C" fn (info: *const c_void), + pub copyDescription: extern "C" fn (info: *const c_void) -> CFStringRef, + pub equal: extern "C" fn (info1: *const c_void, info2: *const c_void) -> Boolean, + pub hash: extern "C" fn (info: *const c_void) -> CFHashCode, + // note that the following two fields are platform dependent in the C header, the ones here are for OS X + pub getPort: extern "C" fn (info: *mut c_void) -> mach_port_t, + pub perform: extern "C" fn (msg: *mut c_void, size: CFIndex, allocator: CFAllocatorRef, info: *mut c_void) -> *mut c_void, +} + +#[repr(C)] +pub struct CFRunLoopObserverContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: extern "C" fn (info: *const c_void) -> *const c_void, + pub release: extern "C" fn (info: *const c_void), + pub copyDescription: extern "C" fn (info: *const c_void) -> CFStringRef, +} + +pub type CFRunLoopObserverCallBack = extern "C" fn (observer: CFRunLoopObserverRef, activity: CFRunLoopActivity, info: *mut c_void); + +#[repr(C)] +pub struct CFRunLoopTimerContext { + pub version: CFIndex, + pub info: *mut c_void, + pub retain: extern "C" fn (info: *const c_void) -> *const c_void, + pub release: extern "C" fn (info: *const c_void), + pub copyDescription: extern "C" fn (info: *const c_void) -> CFStringRef, +} + +pub type CFRunLoopTimerCallBack = extern "C" fn (timer: CFRunLoopTimerRef, info: *mut c_void); + +#[repr(C)] +pub struct __CFRunLoopTimer; + +pub type CFRunLoopTimerRef = *mut __CFRunLoopTimer; + +extern { + /* + * CFRunLoop.h + */ + pub static kCFRunLoopDefaultMode: CFStringRef; + pub static kCFRunLoopCommonModes: CFStringRef; + pub fn CFRunLoopGetTypeID() -> CFTypeID; + pub fn CFRunLoopGetCurrent() -> CFRunLoopRef; + pub fn CFRunLoopGetMain() -> CFRunLoopRef; + pub fn CFRunLoopCopyCurrentMode(rl: CFRunLoopRef) -> CFStringRef; + pub fn CFRunLoopCopyAllModes(rl: CFRunLoopRef) -> CFArrayRef; + pub fn CFRunLoopAddCommonMode(rl: CFRunLoopRef, mode: CFStringRef); + pub fn CFRunLoopGetNextTimerFireDate(rl: CFRunLoopRef, mode: CFStringRef) -> CFAbsoluteTime; + pub fn CFRunLoopRun(); + pub fn CFRunLoopRunInMode(mode: CFStringRef, seconds: CFTimeInterval, returnAfterSourceHandled: Boolean) -> i32; + pub fn CFRunLoopIsWaiting(rl: CFRunLoopRef) -> Boolean; + pub fn CFRunLoopWakeUp(rl: CFRunLoopRef); + pub fn CFRunLoopStop(rl: CFRunLoopRef); + // fn CFRunLoopPerformBlock(rl: CFRunLoopRef, mode: CFTypeRef, block: void (^)(void)); + pub fn CFRunLoopContainsSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef) -> Boolean; + pub fn CFRunLoopAddSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef); + pub fn CFRunLoopRemoveSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFStringRef); + pub fn CFRunLoopContainsObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef) -> Boolean; + pub fn CFRunLoopAddObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef); + pub fn CFRunLoopRemoveObserver(rl: CFRunLoopRef, observer: CFRunLoopObserverRef, mode: CFStringRef); + pub fn CFRunLoopContainsTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef) -> Boolean; + pub fn CFRunLoopAddTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef); + pub fn CFRunLoopRemoveTimer(rl: CFRunLoopRef, timer: CFRunLoopTimerRef, mode: CFStringRef); + + pub fn CFRunLoopSourceGetTypeID() -> CFTypeID; + pub fn CFRunLoopSourceCreate(allocator: CFAllocatorRef, order: CFIndex, context: *mut CFRunLoopSourceContext) -> CFRunLoopSourceRef; + pub fn CFRunLoopSourceGetOrder(source: CFRunLoopSourceRef) -> CFIndex; + pub fn CFRunLoopSourceInvalidate(source: CFRunLoopSourceRef); + pub fn CFRunLoopSourceIsValid(source: CFRunLoopSourceRef) -> Boolean; + pub fn CFRunLoopSourceGetContext(source: CFRunLoopSourceRef, context: *mut CFRunLoopSourceContext); + pub fn CFRunLoopSourceSignal(source: CFRunLoopSourceRef); + + pub fn CFRunLoopObserverGetTypeID() -> CFTypeID; + pub fn CFRunLoopObserverCreate(allocator: CFAllocatorRef, activities: CFOptionFlags, repeats: Boolean, order: CFIndex, callout: CFRunLoopObserverCallBack, context: *mut CFRunLoopObserverContext) -> CFRunLoopObserverRef; + // fn CFRunLoopObserverCreateWithHandler(allocator: CFAllocatorRef, activities: CFOptionFlags, repeats: Boolean, order: CFIndex, block: void (^) (CFRunLoopObserverRef observer, CFRunLoopActivity activity)) -> CFRunLoopObserverRef; + pub fn CFRunLoopObserverGetActivities(observer: CFRunLoopObserverRef) -> CFOptionFlags; + pub fn CFRunLoopObserverDoesRepeat(observer: CFRunLoopObserverRef) -> Boolean; + pub fn CFRunLoopObserverGetOrder(observer: CFRunLoopObserverRef) -> CFIndex; + pub fn CFRunLoopObserverInvalidate(observer: CFRunLoopObserverRef); + pub fn CFRunLoopObserverIsValid(observer: CFRunLoopObserverRef) -> Boolean; + pub fn CFRunLoopObserverGetContext(observer: CFRunLoopObserverRef, context: *mut CFRunLoopObserverContext); + + pub fn CFRunLoopTimerGetTypeID() -> CFTypeID; + pub fn CFRunLoopTimerCreate(allocator: CFAllocatorRef, fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, callout: CFRunLoopTimerCallBack, context: *mut CFRunLoopTimerContext) -> CFRunLoopTimerRef; + // fn CFRunLoopTimerCreateWithHandler(allocator: CFAllocatorRef, fireDate: CFAbsoluteTime, interval: CFTimeInterval, flags: CFOptionFlags, order: CFIndex, block: void (^) (CFRunLoopTimerRef timer)) -> CFRunLoopTimerRef; + pub fn CFRunLoopTimerGetNextFireDate(timer: CFRunLoopTimerRef) -> CFAbsoluteTime; + pub fn CFRunLoopTimerSetNextFireDate(timer: CFRunLoopTimerRef, fireDate: CFAbsoluteTime); + pub fn CFRunLoopTimerGetInterval(timer: CFRunLoopTimerRef) -> CFTimeInterval; + pub fn CFRunLoopTimerDoesRepeat(timer: CFRunLoopTimerRef) -> Boolean; + pub fn CFRunLoopTimerGetOrder(timer: CFRunLoopTimerRef) -> CFIndex; + pub fn CFRunLoopTimerInvalidate(timer: CFRunLoopTimerRef); + pub fn CFRunLoopTimerIsValid(timer: CFRunLoopTimerRef) -> Boolean; + pub fn CFRunLoopTimerGetContext(timer: CFRunLoopTimerRef, context: *mut CFRunLoopTimerContext); + pub fn CFRunLoopTimerGetTolerance(timer: CFRunLoopTimerRef) -> CFTimeInterval; + pub fn CFRunLoopTimerSetTolerance(timer: CFRunLoopTimerRef, tolerance: CFTimeInterval); +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/set.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/set.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/set.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/set.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,58 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use libc::c_void; + +use base::{CFAllocatorRef, CFIndex, CFTypeID}; + +pub type CFSetApplierFunction = extern "C" fn (value: *const c_void, + context: *const c_void); +pub type CFSetRetainCallBack = *const u8; +pub type CFSetReleaseCallBack = *const u8; +pub type CFSetCopyDescriptionCallBack = *const u8; +pub type CFSetEqualCallBack = *const u8; +pub type CFSetHashCallBack = *const u8; + +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFSetCallBacks { + pub version: CFIndex, + pub retain: CFSetRetainCallBack, + pub release: CFSetReleaseCallBack, + pub copyDescription: CFSetCopyDescriptionCallBack, + pub equal: CFSetEqualCallBack, + pub hash: CFSetHashCallBack, +} + +#[repr(C)] +pub struct __CFSet(c_void); + +pub type CFSetRef = *const __CFSet; + +extern { + /* + * CFSet.h + */ + + pub static kCFTypeSetCallBacks: CFSetCallBacks; + + /* Creating Sets */ + pub fn CFSetCreate(allocator: CFAllocatorRef, values: *const *const c_void, numValues: CFIndex, + callBacks: *const CFSetCallBacks) -> CFSetRef; + + /* Applying a Function to Set Members */ + pub fn CFSetApplyFunction(theSet: CFSetRef, + applier: CFSetApplierFunction, + context: *const c_void); + + pub fn CFSetGetCount(theSet: CFSetRef) -> CFIndex; + + pub fn CFSetGetTypeID() -> CFTypeID; +} + diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/string.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/string.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/string.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/string.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,319 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use libc::{c_char, c_ushort, c_void}; + +use base::{Boolean, CFOptionFlags, CFIndex, CFAllocatorRef, CFRange, CFTypeID}; + +pub type UniChar = c_ushort; + +// CFString.h + +pub type CFStringCompareFlags = CFOptionFlags; +//static kCFCompareCaseInsensitive: CFStringCompareFlags = 1; +//static kCFCompareBackwards: CFStringCompareFlags = 4; +//static kCFCompareAnchored: CFStringCompareFlags = 8; +//static kCFCompareNonliteral: CFStringCompareFlags = 16; +//static kCFCompareLocalized: CFStringCompareFlags = 32; +//static kCFCompareNumerically: CFStringCompareFlags = 64; +//static kCFCompareDiacriticInsensitive: CFStringCompareFlags = 128; +//static kCFCompareWidthInsensitive: CFStringCompareFlags = 256; +//static kCFCompareForcedOrdering: CFStringCompareFlags = 512; + +pub type CFStringEncoding = u32; + +// OS X built-in encodings. + +//static kCFStringEncodingMacRoman: CFStringEncoding = 0; +//static kCFStringEncodingWindowsLatin1: CFStringEncoding = 0x0500; +//static kCFStringEncodingISOLatin1: CFStringEncoding = 0x0201; +//static kCFStringEncodingNextStepLatin: CFStringEncoding = 0x0B01; +//static kCFStringEncodingASCII: CFStringEncoding = 0x0600; +//static kCFStringEncodingUnicode: CFStringEncoding = 0x0100; +pub static kCFStringEncodingUTF8: CFStringEncoding = 0x08000100; +//static kCFStringEncodingNonLossyASCII: CFStringEncoding = 0x0BFF; + +//static kCFStringEncodingUTF16: CFStringEncoding = 0x0100; +//static kCFStringEncodingUTF16BE: CFStringEncoding = 0x10000100; +//static kCFStringEncodingUTF16LE: CFStringEncoding = 0x14000100; +//static kCFStringEncodingUTF32: CFStringEncoding = 0x0c000100; +//static kCFStringEncodingUTF32BE: CFStringEncoding = 0x18000100; +//static kCFStringEncodingUTF32LE: CFStringEncoding = 0x1c000100; + + +// CFStringEncodingExt.h + +pub type CFStringEncodings = CFIndex; + +// External encodings, except those defined above. +// Defined above: kCFStringEncodingMacRoman = 0 +//static kCFStringEncodingMacJapanese: CFStringEncoding = 1; +//static kCFStringEncodingMacChineseTrad: CFStringEncoding = 2; +//static kCFStringEncodingMacKorean: CFStringEncoding = 3; +//static kCFStringEncodingMacArabic: CFStringEncoding = 4; +//static kCFStringEncodingMacHebrew: CFStringEncoding = 5; +//static kCFStringEncodingMacGreek: CFStringEncoding = 6; +//static kCFStringEncodingMacCyrillic: CFStringEncoding = 7; +//static kCFStringEncodingMacDevanagari: CFStringEncoding = 9; +//static kCFStringEncodingMacGurmukhi: CFStringEncoding = 10; +//static kCFStringEncodingMacGujarati: CFStringEncoding = 11; +//static kCFStringEncodingMacOriya: CFStringEncoding = 12; +//static kCFStringEncodingMacBengali: CFStringEncoding = 13; +//static kCFStringEncodingMacTamil: CFStringEncoding = 14; +//static kCFStringEncodingMacTelugu: CFStringEncoding = 15; +//static kCFStringEncodingMacKannada: CFStringEncoding = 16; +//static kCFStringEncodingMacMalayalam: CFStringEncoding = 17; +//static kCFStringEncodingMacSinhalese: CFStringEncoding = 18; +//static kCFStringEncodingMacBurmese: CFStringEncoding = 19; +//static kCFStringEncodingMacKhmer: CFStringEncoding = 20; +//static kCFStringEncodingMacThai: CFStringEncoding = 21; +//static kCFStringEncodingMacLaotian: CFStringEncoding = 22; +//static kCFStringEncodingMacGeorgian: CFStringEncoding = 23; +//static kCFStringEncodingMacArmenian: CFStringEncoding = 24; +//static kCFStringEncodingMacChineseSimp: CFStringEncoding = 25; +//static kCFStringEncodingMacTibetan: CFStringEncoding = 26; +//static kCFStringEncodingMacMongolian: CFStringEncoding = 27; +//static kCFStringEncodingMacEthiopic: CFStringEncoding = 28; +//static kCFStringEncodingMacCentralEurRoman: CFStringEncoding = 29; +//static kCFStringEncodingMacVietnamese: CFStringEncoding = 30; +//static kCFStringEncodingMacExtArabic: CFStringEncoding = 31; +//static kCFStringEncodingMacSymbol: CFStringEncoding = 33; +//static kCFStringEncodingMacDingbats: CFStringEncoding = 34; +//static kCFStringEncodingMacTurkish: CFStringEncoding = 35; +//static kCFStringEncodingMacCroatian: CFStringEncoding = 36; +//static kCFStringEncodingMacIcelandic: CFStringEncoding = 37; +//static kCFStringEncodingMacRomanian: CFStringEncoding = 38; +//static kCFStringEncodingMacCeltic: CFStringEncoding = 39; +//static kCFStringEncodingMacGaelic: CFStringEncoding = 40; +//static kCFStringEncodingMacFarsi: CFStringEncoding = 0x8C; +//static kCFStringEncodingMacUkrainian: CFStringEncoding = 0x98; +//static kCFStringEncodingMacInuit: CFStringEncoding = 0xEC; +//static kCFStringEncodingMacVT100: CFStringEncoding = 0xFC; +//static kCFStringEncodingMacHFS: CFStringEncoding = 0xFF; +// Defined above: kCFStringEncodingISOLatin1 = 0x0201 +//static kCFStringEncodingISOLatin2: CFStringEncoding = 0x0202; +//static kCFStringEncodingISOLatin3: CFStringEncoding = 0x0203; +//static kCFStringEncodingISOLatin4: CFStringEncoding = 0x0204; +//static kCFStringEncodingISOLatinCyrillic: CFStringEncoding = 0x0205; +//static kCFStringEncodingISOLatinArabic: CFStringEncoding = 0x0206; +//static kCFStringEncodingISOLatinGreek: CFStringEncoding = 0x0207; +//static kCFStringEncodingISOLatinHebrew: CFStringEncoding = 0x0208; +//static kCFStringEncodingISOLatin5: CFStringEncoding = 0x0209; +//static kCFStringEncodingISOLatin6: CFStringEncoding = 0x020A; +//static kCFStringEncodingISOLatinThai: CFStringEncoding = 0x020B; +//static kCFStringEncodingISOLatin7: CFStringEncoding = 0x020D; +//static kCFStringEncodingISOLatin8: CFStringEncoding = 0x020E; +//static kCFStringEncodingISOLatin9: CFStringEncoding = 0x020F; +//static kCFStringEncodingISOLatin10: CFStringEncoding = 0x0210; +//static kCFStringEncodingDOSLatinUS: CFStringEncoding = 0x0400; +//static kCFStringEncodingDOSGreek: CFStringEncoding = 0x0405; +//static kCFStringEncodingDOSBalticRim: CFStringEncoding = 0x0406; +//static kCFStringEncodingDOSLatin1: CFStringEncoding = 0x0410; +//static kCFStringEncodingDOSGreek1: CFStringEncoding = 0x0411; +//static kCFStringEncodingDOSLatin2: CFStringEncoding = 0x0412; +//static kCFStringEncodingDOSCyrillic: CFStringEncoding = 0x0413; +//static kCFStringEncodingDOSTurkish: CFStringEncoding = 0x0414; +//static kCFStringEncodingDOSPortuguese: CFStringEncoding = 0x0415; +//static kCFStringEncodingDOSIcelandic: CFStringEncoding = 0x0416; +//static kCFStringEncodingDOSHebrew: CFStringEncoding = 0x0417; +//static kCFStringEncodingDOSCanadianFrench: CFStringEncoding = 0x0418; +//static kCFStringEncodingDOSArabic: CFStringEncoding = 0x0419; +//static kCFStringEncodingDOSNordic: CFStringEncoding = 0x041A; +//static kCFStringEncodingDOSRussian: CFStringEncoding = 0x041B; +//static kCFStringEncodingDOSGreek2: CFStringEncoding = 0x041C; +//static kCFStringEncodingDOSThai: CFStringEncoding = 0x041D; +//static kCFStringEncodingDOSJapanese: CFStringEncoding = 0x0420; +//static kCFStringEncodingDOSChineseSimplif: CFStringEncoding = 0x0421; +//static kCFStringEncodingDOSKorean: CFStringEncoding = 0x0422; +//static kCFStringEncodingDOSChineseTrad: CFStringEncoding = 0x0423; +// Defined above: kCFStringEncodingWindowsLatin1 = 0x0500 +//static kCFStringEncodingWindowsLatin2: CFStringEncoding = 0x0501; +//static kCFStringEncodingWindowsCyrillic: CFStringEncoding = 0x0502; +//static kCFStringEncodingWindowsGreek: CFStringEncoding = 0x0503; +//static kCFStringEncodingWindowsLatin5: CFStringEncoding = 0x0504; +//static kCFStringEncodingWindowsHebrew: CFStringEncoding = 0x0505; +//static kCFStringEncodingWindowsArabic: CFStringEncoding = 0x0506; +//static kCFStringEncodingWindowsBalticRim: CFStringEncoding = 0x0507; +//static kCFStringEncodingWindowsVietnamese: CFStringEncoding = 0x0508; +//static kCFStringEncodingWindowsKoreanJohab: CFStringEncoding = 0x0510; +// Defined above: kCFStringEncodingASCII = 0x0600 +//static kCFStringEncodingANSEL: CFStringEncoding = 0x0601; +//static kCFStringEncodingJIS_X0201_76: CFStringEncoding = 0x0620; +//static kCFStringEncodingJIS_X0208_83: CFStringEncoding = 0x0621; +//static kCFStringEncodingJIS_X0208_90: CFStringEncoding = 0x0622; +//static kCFStringEncodingJIS_X0212_90: CFStringEncoding = 0x0623; +//static kCFStringEncodingJIS_C6226_78: CFStringEncoding = 0x0624; +//static kCFStringEncodingShiftJIS_X0213: CFStringEncoding = 0x0628; +//static kCFStringEncodingShiftJIS_X0213_MenKuTen: CFStringEncoding = 0x0629; +//static kCFStringEncodingGB_2312_80: CFStringEncoding = 0x0630; +//static kCFStringEncodingGBK_95: CFStringEncoding = 0x0631; +//static kCFStringEncodingGB_18030_2000: CFStringEncoding = 0x0632; +//static kCFStringEncodingKSC_5601_87: CFStringEncoding = 0x0640; +//static kCFStringEncodingKSC_5601_92_Johab: CFStringEncoding = 0x0641; +//static kCFStringEncodingCNS_11643_92_P1: CFStringEncoding = 0x0651; +//static kCFStringEncodingCNS_11643_92_P2: CFStringEncoding = 0x0652; +//static kCFStringEncodingCNS_11643_92_P3: CFStringEncoding = 0x0653; +//static kCFStringEncodingISO_2022_JP: CFStringEncoding = 0x0820; +//static kCFStringEncodingISO_2022_JP_2: CFStringEncoding = 0x0821; +//static kCFStringEncodingISO_2022_JP_1: CFStringEncoding = 0x0822; +//static kCFStringEncodingISO_2022_JP_3: CFStringEncoding = 0x0823; +//static kCFStringEncodingISO_2022_CN: CFStringEncoding = 0x0830; +//static kCFStringEncodingISO_2022_CN_EXT: CFStringEncoding = 0x0831; +//static kCFStringEncodingISO_2022_KR: CFStringEncoding = 0x0840; +//static kCFStringEncodingEUC_JP: CFStringEncoding = 0x0920; +//static kCFStringEncodingEUC_CN: CFStringEncoding = 0x0930; +//static kCFStringEncodingEUC_TW: CFStringEncoding = 0x0931; +//static kCFStringEncodingEUC_KR: CFStringEncoding = 0x0940; +//static kCFStringEncodingShiftJIS: CFStringEncoding = 0x0A01; +//static kCFStringEncodingKOI8_R: CFStringEncoding = 0x0A02; +//static kCFStringEncodingBig5: CFStringEncoding = 0x0A03; +//static kCFStringEncodingMacRomanLatin1: CFStringEncoding = 0x0A04; +//static kCFStringEncodingHZ_GB_2312: CFStringEncoding = 0x0A05; +//static kCFStringEncodingBig5_HKSCS_1999: CFStringEncoding = 0x0A06; +//static kCFStringEncodingVISCII: CFStringEncoding = 0x0A07; +//static kCFStringEncodingKOI8_U: CFStringEncoding = 0x0A08; +//static kCFStringEncodingBig5_E: CFStringEncoding = 0x0A09; +// Defined above: kCFStringEncodingNextStepLatin = 0x0B01 +//static kCFStringEncodingNextStepJapanese: CFStringEncoding = 0x0B02; +//static kCFStringEncodingEBCDIC_US: CFStringEncoding = 0x0C01; +//static kCFStringEncodingEBCDIC_CP037: CFStringEncoding = 0x0C02; +//static kCFStringEncodingUTF7: CFStringEncoding = 0x04000100; +//static kCFStringEncodingUTF7_IMAP: CFStringEncoding = 0x0A10; +//static kCFStringEncodingShiftJIS_X0213_00: CFStringEncoding = 0x0628; /* Deprecated */ + +#[repr(C)] +pub struct __CFString(c_void); + +pub type CFStringRef = *const __CFString; + +extern { + /* + * CFString.h + */ + + // N.B. organized according to "Functions by task" in docs + + /* Creating a CFString */ + //fn CFSTR + //fn CFStringCreateArrayBySeparatingStrings + //fn CFStringCreateByCombiningStrings + //fn CFStringCreateCopy + //fn CFStringCreateFromExternalRepresentation + pub fn CFStringCreateWithBytes(alloc: CFAllocatorRef, + bytes: *const u8, + numBytes: CFIndex, + encoding: CFStringEncoding, + isExternalRepresentation: Boolean) + -> CFStringRef; + pub fn CFStringCreateWithBytesNoCopy(alloc: CFAllocatorRef, + bytes: *const u8, + numBytes: CFIndex, + encoding: CFStringEncoding, + isExternalRepresentation: Boolean, + contentsDeallocator: CFAllocatorRef) + -> CFStringRef; + //fn CFStringCreateWithCharacters + //fn CFStringCreateWithCharactersNoCopy + pub fn CFStringCreateWithCString(alloc: CFAllocatorRef, + cStr: *const c_char, + encoding: CFStringEncoding) + -> CFStringRef; + //fn CFStringCreateWithCStringNoCopy + //fn CFStringCreateWithFormat + //fn CFStringCreateWithFormatAndArguments + //fn CFStringCreateWithPascalString + //fn CFStringCreateWithPascalStringNoCopy + //fn CFStringCreateWithSubstring + + /* Searching Strings */ + //fn CFStringCreateArrayWithFindResults + //fn CFStringFind + //fn CFStringFindCharacterFromSet + //fn CFStringFindWithOptions + //fn CFStringFindWithOptionsAndLocale + //fn CFStringGetLineBounds + + /* Comparing Strings */ + //fn CFStringCompare + //fn CFStringCompareWithOptions + //fn CFStringCompareWithOptionsAndLocale + //fn CFStringHasPrefix + //fn CFStringHasSuffix + + /* Accessing Characters */ + //fn CFStringCreateExternalRepresentation + pub fn CFStringGetBytes(theString: CFStringRef, + range: CFRange, + encoding: CFStringEncoding, + lossByte: u8, + isExternalRepresentation: Boolean, + buffer: *mut u8, + maxBufLen: CFIndex, + usedBufLen: *mut CFIndex) + -> CFIndex; + //fn CFStringGetCharacterAtIndex + //fn CFStringGetCharacters + //fn CFStringGetCharactersPtr + //fn CFStringGetCharacterFromInlineBuffer + pub fn CFStringGetCString(theString: CFStringRef, + buffer: *mut c_char, + bufferSize: CFIndex, + encoding: CFStringEncoding) + -> Boolean; + pub fn CFStringGetCStringPtr(theString: CFStringRef, + encoding: CFStringEncoding) + -> *const c_char; + pub fn CFStringGetLength(theString: CFStringRef) -> CFIndex; + //fn CFStringGetPascalString + //fn CFStringGetPascalStringPtr + //fn CFStringGetRangeOfComposedCharactersAtIndex + //fn CFStringInitInlineBuffer + + /* Working With Hyphenation */ + //fn CFStringGetHyphenationLocationBeforeIndex + //fn CFStringIsHyphenationAvailableForLocale + + /* Working With Encodings */ + //fn CFStringConvertEncodingToIANACharSetName + //fn CFStringConvertEncodingToNSStringEncoding + //fn CFStringConvertEncodingToWindowsCodepage + //fn CFStringConvertIANACharSetNameToEncoding + //fn CFStringConvertNSStringEncodingToEncoding + //fn CFStringConvertWindowsCodepageToEncoding + //fn CFStringGetFastestEncoding + //fn CFStringGetListOfAvailableEncodings + //fn CFStringGetMaximumSizeForEncoding + //fn CFStringGetMostCompatibleMacStringEncoding + //fn CFStringGetNameOfEncoding + //fn CFStringGetSmallestEncoding + //fn CFStringGetSystemEncoding + //fn CFStringIsEncodingAvailable + + /* Getting Numeric Values */ + //fn CFStringGetDoubleValue + //fn CFStringGetIntValue + + /* Getting String Properties */ + //fn CFShowStr + pub fn CFStringGetTypeID() -> CFTypeID; + + /* String File System Representations */ + //fn CFStringCreateWithFileSystemRepresentation + //fn CFStringGetFileSystemRepresentation + //fn CFStringGetMaximumSizeOfFileSystemRepresentation + + /* Getting Paragraph Bounds */ + //fn CFStringGetParagraphBounds + + /* Managing Surrogates */ + //fn CFStringGetLongCharacterForSurrogatePair + //fn CFStringGetSurrogatePairForLongCharacter + //fn CFStringIsSurrogateHighCharacter + //fn CFStringIsSurrogateLowCharacter +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/timezone.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/timezone.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/timezone.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/timezone.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,27 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use libc::c_void; + +use base::{CFAllocatorRef, CFTypeID}; +use date::{CFTimeInterval, CFAbsoluteTime}; + +#[repr(C)] +pub struct __CFTimeZone(c_void); + +pub type CFTimeZoneRef = *const __CFTimeZone; + +extern { + pub fn CFTimeZoneCopySystem() -> CFTimeZoneRef; + pub fn CFTimeZoneCopyDefault() -> CFTimeZoneRef; + pub fn CFTimeZoneCreateWithTimeIntervalFromGMT(allocator: CFAllocatorRef, interval: CFTimeInterval) -> CFTimeZoneRef; + pub fn CFTimeZoneGetSecondsFromGMT(tz: CFTimeZoneRef, time: CFAbsoluteTime) -> CFTimeInterval; + + pub fn CFTimeZoneGetTypeID() -> CFTypeID; +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/url.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/url.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/url.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/url.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,163 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +use libc::c_void; + +use base::{CFOptionFlags, CFIndex, CFAllocatorRef, Boolean, CFTypeID, CFTypeRef, SInt32}; +use string::{CFStringRef, CFStringEncoding}; +use error::CFErrorRef; + +#[repr(C)] +pub struct __CFURL(c_void); + +pub type CFURLRef = *const __CFURL; + +pub type CFURLBookmarkCreationOptions = CFOptionFlags; + +pub type CFURLPathStyle = CFIndex; + +/* typedef CF_ENUM(CFIndex, CFURLPathStyle) */ +pub const kCFURLPOSIXPathStyle: CFURLPathStyle = 0; +pub const kCFURLHFSPathStyle: CFURLPathStyle = 1; +pub const kCFURLWindowsPathStyle: CFURLPathStyle = 2; + +// static kCFURLBookmarkCreationPreferFileIDResolutionMask: CFURLBookmarkCreationOptions = +// (1 << 8) as u32; +// static kCFURLBookmarkCreationMinimalBookmarkMask: CFURLBookmarkCreationOptions = +// (1 << 9) as u32; +// static kCFURLBookmarkCreationSuitableForBookmarkFile: CFURLBookmarkCreationOptions = +// (1 << 10) as u32; +// static kCFURLBookmarkCreationWithSecurityScope: CFURLBookmarkCreationOptions = +// (1 << 11) as u32; +// static kCFURLBookmarkCreationSecurityScopeAllowOnlyReadAccess: CFURLBookmarkCreationOptions = +// (1 << 12) as u32; + +// TODO: there are a lot of missing keys and constants. Add if you are bored or need them. + +extern { + /* + * CFURL.h + */ + + /* Common File System Resource Keys */ + pub static kCFURLAttributeModificationDateKey: CFStringRef; + pub static kCFURLContentAccessDateKey: CFStringRef; + pub static kCFURLContentModificationDateKey: CFStringRef; + pub static kCFURLCreationDateKey: CFStringRef; + pub static kCFURLFileResourceIdentifierKey: CFStringRef; + pub static kCFURLFileSecurityKey: CFStringRef; + pub static kCFURLHasHiddenExtensionKey: CFStringRef; + pub static kCFURLIsDirectoryKey: CFStringRef; + pub static kCFURLIsExecutableKey: CFStringRef; + pub static kCFURLIsHiddenKey: CFStringRef; + pub static kCFURLIsPackageKey: CFStringRef; + pub static kCFURLIsReadableKey: CFStringRef; + pub static kCFURLIsRegularFileKey: CFStringRef; + pub static kCFURLIsSymbolicLinkKey: CFStringRef; + pub static kCFURLIsSystemImmutableKey: CFStringRef; + pub static kCFURLIsUserImmutableKey: CFStringRef; + pub static kCFURLIsVolumeKey: CFStringRef; + pub static kCFURLIsWritableKey: CFStringRef; + pub static kCFURLLabelNumberKey: CFStringRef; + pub static kCFURLLinkCountKey: CFStringRef; + pub static kCFURLLocalizedLabelKey: CFStringRef; + pub static kCFURLLocalizedNameKey: CFStringRef; + pub static kCFURLLocalizedTypeDescriptionKey: CFStringRef; + pub static kCFURLNameKey: CFStringRef; + pub static kCFURLParentDirectoryURLKey: CFStringRef; + pub static kCFURLPreferredIOBlockSizeKey: CFStringRef; + pub static kCFURLTypeIdentifierKey: CFStringRef; + pub static kCFURLVolumeIdentifierKey: CFStringRef; + pub static kCFURLVolumeURLKey: CFStringRef; + + #[cfg(feature="mac_os_10_8_features")] + #[cfg_attr(feature = "mac_os_10_7_support", linkage = "extern_weak")] + pub static kCFURLIsExcludedFromBackupKey: CFStringRef; + pub static kCFURLFileResourceTypeKey: CFStringRef; + + /* Creating a CFURL */ + pub fn CFURLCopyAbsoluteURL(anURL: CFURLRef) -> CFURLRef; + //fn CFURLCreateAbsoluteURLWithBytes + //fn CFURLCreateByResolvingBookmarkData + //fn CFURLCreateCopyAppendingPathComponent + //fn CFURLCreateCopyAppendingPathExtension + //fn CFURLCreateCopyDeletingLastPathComponent + //fn CFURLCreateCopyDeletingPathExtension + pub fn CFURLCreateFilePathURL(allocator: CFAllocatorRef, url: CFURLRef, error: *mut CFErrorRef) -> CFURLRef; + //fn CFURLCreateFileReferenceURL + pub fn CFURLCreateFromFileSystemRepresentation(allocator: CFAllocatorRef, buffer: *const u8, bufLen: CFIndex, isDirectory: Boolean) -> CFURLRef; + //fn CFURLCreateFromFileSystemRepresentationRelativeToBase + //fn CFURLCreateFromFSRef + pub fn CFURLCreateWithBytes(allocator: CFAllocatorRef, URLBytes: *const u8, length: CFIndex, encoding: CFStringEncoding, baseURL: CFURLRef) -> CFURLRef; + pub fn CFURLCreateWithFileSystemPath(allocator: CFAllocatorRef, filePath: CFStringRef, pathStyle: CFURLPathStyle, isDirectory: Boolean) -> CFURLRef; + pub fn CFURLCreateWithFileSystemPathRelativeToBase(allocator: CFAllocatorRef, filePath: CFStringRef, pathStyle: CFURLPathStyle, isDirectory: Boolean, baseURL: CFURLRef) -> CFURLRef; + //fn CFURLCreateWithString(allocator: CFAllocatorRef, urlString: CFStringRef, + // baseURL: CFURLRef) -> CFURLRef; + + /* Accessing the Parts of a URL */ + pub fn CFURLCanBeDecomposed(anURL: CFURLRef) -> Boolean; + pub fn CFURLCopyFileSystemPath(anURL: CFURLRef, pathStyle: CFURLPathStyle) -> CFStringRef; + pub fn CFURLCopyFragment(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; + pub fn CFURLCopyHostName(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyLastPathComponent(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyNetLocation(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyParameterString(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; + pub fn CFURLCopyPassword(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyPath(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyPathExtension(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyQueryString(anURL: CFURLRef, charactersToLeaveEscaped: CFStringRef) -> CFStringRef; + pub fn CFURLCopyResourceSpecifier(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyScheme(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLCopyStrictPath(anURL: CFURLRef, isAbsolute: *mut Boolean) -> CFStringRef; + pub fn CFURLCopyUserName(anURL: CFURLRef) -> CFStringRef; + pub fn CFURLGetPortNumber(anURL: CFURLRef) -> SInt32; + pub fn CFURLHasDirectoryPath(anURL: CFURLRef) -> Boolean; + + /* Converting URLs to Other Representations */ + //fn CFURLCreateData(allocator: CFAllocatorRef, url: CFURLRef, + // encoding: CFStringEncoding, escapeWhitespace: bool) -> CFDataRef; + //fn CFURLCreateStringByAddingPercentEscapes + //fn CFURLCreateStringByReplacingPercentEscapes + //fn CFURLCreateStringByReplacingPercentEscapesUsingEncoding + pub fn CFURLGetFileSystemRepresentation(anURL: CFURLRef, resolveAgainstBase: Boolean, buffer: *mut u8, maxBufLen: CFIndex) -> Boolean; + + //fn CFURLGetFSRef + pub fn CFURLGetString(anURL: CFURLRef) -> CFStringRef; + + /* Getting URL Properties */ + //fn CFURLGetBaseURL(anURL: CFURLRef) -> CFURLRef; + pub fn CFURLGetBytes(anURL: CFURLRef, buffer: *mut u8, bufferLength: CFIndex) -> CFIndex; + //fn CFURLGetByteRangeForComponent + pub fn CFURLGetTypeID() -> CFTypeID; + //fn CFURLResourceIsReachable + + /* Getting and Setting File System Resource Properties */ + pub fn CFURLClearResourcePropertyCache(url: CFURLRef); + //fn CFURLClearResourcePropertyCacheForKey + //fn CFURLCopyResourcePropertiesForKeys + //fn CFURLCopyResourcePropertyForKey + //fn CFURLCreateResourcePropertiesForKeysFromBookmarkData + //fn CFURLCreateResourcePropertyForKeyFromBookmarkData + //fn CFURLSetResourcePropertiesForKeys + pub fn CFURLSetResourcePropertyForKey(url: CFURLRef, key: CFStringRef, value: CFTypeRef, error: *mut CFErrorRef) -> Boolean; + //fn CFURLSetTemporaryResourcePropertyForKey + + /* Working with Bookmark Data */ + //fn CFURLCreateBookmarkData + //fn CFURLCreateBookmarkDataFromAliasRecord + //fn CFURLCreateBookmarkDataFromFile + //fn CFURLWriteBookmarkDataToFile + //fn CFURLStartAccessingSecurityScopedResource + //fn CFURLStopAccessingSecurityScopedResource +} + +#[test] +#[cfg(feature="mac_os_10_8_features")] +fn can_see_excluded_from_backup_key() { + let _ = unsafe { kCFURLIsExcludedFromBackupKey }; +} diff -Nru cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/uuid.rs cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/uuid.rs --- cargo-0.25.0/vendor/core-foundation-sys-0.5.1/src/uuid.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/core-foundation-sys-0.5.1/src/uuid.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,48 @@ +// Copyright 2013-2015 The Servo Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +use libc::c_void; + +use base::{CFAllocatorRef, CFTypeID}; + +#[repr(C)] +pub struct __CFUUID(c_void); + +pub type CFUUIDRef = *const __CFUUID; + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub struct CFUUIDBytes { + pub byte0: u8, + pub byte1: u8, + pub byte2: u8, + pub byte3: u8, + pub byte4: u8, + pub byte5: u8, + pub byte6: u8, + pub byte7: u8, + pub byte8: u8, + pub byte9: u8, + pub byte10: u8, + pub byte11: u8, + pub byte12: u8, + pub byte13: u8, + pub byte14: u8, + pub byte15: u8 +} + +extern { + /* + * CFUUID.h + */ + pub fn CFUUIDCreate(allocator: CFAllocatorRef) -> CFUUIDRef; + pub fn CFUUIDCreateFromUUIDBytes(allocator: CFAllocatorRef, bytes: CFUUIDBytes) -> CFUUIDRef; + pub fn CFUUIDGetUUIDBytes(uuid: CFUUIDRef) -> CFUUIDBytes; + + pub fn CFUUIDGetTypeID() -> CFTypeID; +} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/.cargo-checksum.json cargo-0.26.0/vendor/crossbeam-0.2.12/.cargo-checksum.json --- cargo-0.25.0/vendor/crossbeam-0.2.12/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"bd66663db5a988098a89599d4857919b3acf7f61402e61365acfd3919857b9be"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/Cargo.toml cargo-0.26.0/vendor/crossbeam-0.2.12/Cargo.toml --- cargo-0.25.0/vendor/crossbeam-0.2.12/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "crossbeam" -version = "0.2.12" -authors = ["Aaron Turon "] -description = "Support for lock-free data structures, synchronizers, and parallel programming" -documentation = "http://aturon.github.io/crossbeam-doc/crossbeam/" -readme = "README.md" -license = "Apache-2.0/MIT" -repository = "https://github.com/aturon/crossbeam" -[dev-dependencies.rand] -version = "0.3" - -[features] -nightly = [] diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/CHANGELOG.md cargo-0.26.0/vendor/crossbeam-0.2.12/CHANGELOG.md --- cargo-0.25.0/vendor/crossbeam-0.2.12/CHANGELOG.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/CHANGELOG.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -# Version 0.2 - -- Changed existing non-blocking `pop` methods to `try_pop` -- Added blocking `pop` support to Michael-Scott queue -- Added Chase-Lev work-stealing deque - -# Version 0.1 - -- Added [epoch-based memory management](http://aturon.github.io/blog/2015/08/27/epoch/) -- Added Michael-Scott queue -- Added Segmented array queue diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/LICENSE-APACHE cargo-0.26.0/vendor/crossbeam-0.2.12/LICENSE-APACHE --- cargo-0.25.0/vendor/crossbeam-0.2.12/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/LICENSE-MIT cargo-0.26.0/vendor/crossbeam-0.2.12/LICENSE-MIT --- cargo-0.25.0/vendor/crossbeam-0.2.12/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2015 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/README.md cargo-0.26.0/vendor/crossbeam-0.2.12/README.md --- cargo-0.25.0/vendor/crossbeam-0.2.12/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -# Crossbeam: support for concurrent and parallel programming - -[![Build Status](https://travis-ci.org/aturon/crossbeam.svg?branch=master)](https://travis-ci.org/aturon/crossbeam) - -This crate is an early work in progress. The focus for the moment is -concurrency: - -- **Non-blocking data structures**. These data structures allow for high -performance, highly-concurrent access, much superior to wrapping with a -`Mutex`. Ultimately the goal is to include stacks, queues, deques, bags, sets -and maps. - -- **Memory management**. Because non-blocking data structures avoid global -synchronization, it is not easy to tell when internal data can be safely -freed. The `mem` module provides generic, easy to use, and high-performance APIs -for managing memory in these cases. - -- **Synchronization**. The standard library provides a few synchronization -primitives (locks, semaphores, barriers, etc) but this crate seeks to expand -that set to include more advanced/niche primitives, as well as userspace -alternatives. - -- **Scoped thread API**. Finally, the crate provides a "scoped" thread API, -making it possible to spawn threads that share stack data with their parents. - -# Usage - -To use Crossbeam, add this to your `Cargo.toml`: - -```toml -[dependencies] -crossbeam = "0.2" -``` - -For examples of what Crossbeam is capable of, see the -[documentation][docs]. - -[docs]: http://aturon.github.io/crossbeam-doc/crossbeam/ diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/scala-bench/bench.scala cargo-0.26.0/vendor/crossbeam-0.2.12/scala-bench/bench.scala --- cargo-0.25.0/vendor/crossbeam-0.2.12/scala-bench/bench.scala 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/scala-bench/bench.scala 1970-01-01 00:00:00.000000000 +0000 @@ -1,195 +0,0 @@ -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent._ -import scala.concurrent.duration._ -import java.util.concurrent.ConcurrentLinkedQueue -import java.util.concurrent.atomic._ -import java.util.Stack - -import scala.annotation.tailrec - -final class MSQueue[A](a: A) { - private abstract class Q - private final case class Node(data: A, next: AtomicReference[Q] = new AtomicReference(Emp)) extends Q - private final case object Emp extends Q - private val head = new AtomicReference(Node(a)) - private val tail = new AtomicReference(head.get()) - - def enq(a: A) { - val newNode = new Node(a) - while (true) { - val curTail = tail.get() - curTail.next.get()match { - case n@Node(_,_) => tail.compareAndSet(curTail, n) - case Emp => { - if (curTail.next.compareAndSet(Emp, newNode)) { - tail.compareAndSet(curTail, newNode) - return - } - } - } - } - } - - def deq(): Option[A] = { - while (true) { - val cur_head = head.get() - cur_head.next.get() match { - case Emp => return None - case n@Node(data, _) => { - if (head.compareAndSet(cur_head, n)) { - return Some(data) - } - } - } - } - None - } -} - -abstract class MyBool -final case class MyTrue() extends MyBool -final case class MyFalse() extends MyBool - -object Bench { - def time(block: => Unit): Long = { - val t0 = System.nanoTime() - val result = block // call-by-name - val t1 = System.nanoTime() - t1 - t0 - } - - def do_linked(threads: Int, count: Int) { - val q: ConcurrentLinkedQueue[MyBool] = new ConcurrentLinkedQueue(); - - val t = time { - var s = new Stack[Future[Unit]] - for (i <- 1 to threads) { - s.push(Future { - for (i <- 1 to count+1) { - //if (i % 100000 == 0) { println(q.size()) } - q.offer(MyTrue()) - } - }) - } - - var rn = 0 - while (rn < count) { - if (q.poll() != null) { - rn += 1 - } - } - - while (!s.empty()) { - Await.ready(s.pop(), Duration.Inf) - } - } - - println("Linked: " + t / (count * threads)) - } - - def do_linked_mpmc(threads: Int, count: Int) { - val q = new ConcurrentLinkedQueue[MyBool]; - val prod = new AtomicInteger(); - - val t = time { - var s = new Stack[Future[Unit]] - for (i <- 1 to threads) { - s.push(Future { - for (i <- 1 to count+1) { - q.offer(MyTrue()) - //if (i % 100000 == 0) { println(q.size()) } - } - if (prod.incrementAndGet() == threads) { - for (i <- 0 to threads) { q.offer(MyFalse()) } - } - }) - s.push(Future { - var done = false; - while (!done) { - q.poll() match { - case MyFalse() => done = true - case _ => {} - } - } - }) - } - - while (!s.empty()) { - Await.ready(s.pop(), Duration.Inf) - } - } - - println("Linked mpmc: " + t / (count * threads) + " (" + t / 1000000000 + ")") - } - - - def do_msq(threads: Int, count: Int) { - val q = new MSQueue[Int](0); - - val t = time { - var s = new Stack[Future[Unit]] - for (i <- 1 to threads) { - s.push(Future { for (i <- 1 to count+1) { q.enq(i) } }) - } - - var rn = 0 - while (rn < count) { - if (q.deq() != None) { - rn += 1 - } - } - - while (!s.empty()) { - Await.ready(s.pop(), Duration.Inf) - } - } - - println("MSQ: " + t / (count * threads) + " (" + t / 1000000000 + ")") - } - - def do_msq_mpmc(threads: Int, count: Int) { - val q = new MSQueue[Boolean](true); - val prod = new AtomicInteger(); - - val t = time { - var s = new Stack[Future[Unit]] - for (i <- 1 to threads) { - s.push(Future { - for (i <- 1 to count+1) { q.enq(true) } - if (prod.incrementAndGet() == threads) { - for (i <- 1 to threads) { q.enq(false) } - } - }) - s.push(Future { - var done = false; - while (!done) { - q.deq() match { - case Some(false) => done = true - case _ => {} - } - } - }) - } - - while (!s.empty()) { - Await.ready(s.pop(), Duration.Inf) - } - } - - println("MSQ mpmc: " + t / (count * threads) + " (" + t / 1000000000 + ")") - } - - def main(args: Array[String]) { - do_linked(2, 1000000) - do_linked(2, 10000000) - - do_msq(2, 1000000) - do_msq(2, 10000000) - - do_linked_mpmc(2, 1000000) - do_linked_mpmc(2, 10000000) - - do_msq_mpmc(2, 1000000) - do_msq_mpmc(2, 10000000) - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/bin/bench.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/bin/bench.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/bin/bench.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/bin/bench.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,165 +0,0 @@ -extern crate crossbeam; - -use std::collections::VecDeque; -use std::sync::Mutex; -use std::sync::mpsc::channel; -use std::time::Duration; - -use crossbeam::scope; -use crossbeam::sync::MsQueue; -use crossbeam::sync::SegQueue; - -use extra_impls::mpsc_queue::Queue as MpscQueue; - -mod extra_impls; - -const COUNT: u64 = 10000000; -const THREADS: u64 = 2; - -#[cfg(feature = "nightly")] -fn time(f: F) -> Duration { - let start = ::std::time::Instant::now(); - f(); - start.elapsed() -} - -#[cfg(not(feature = "nightly"))] -fn time(_f: F) -> Duration { - Duration::new(0, 0) -} - -fn nanos(d: Duration) -> f64 { - d.as_secs() as f64 * 1000000000f64 + (d.subsec_nanos() as f64) -} - -trait Queue { - fn push(&self, T); - fn try_pop(&self) -> Option; -} - -impl Queue for MsQueue { - fn push(&self, t: T) { self.push(t) } - fn try_pop(&self) -> Option { self.try_pop() } -} - -impl Queue for SegQueue { - fn push(&self, t: T) { self.push(t) } - fn try_pop(&self) -> Option { self.try_pop() } -} - -impl Queue for MpscQueue { - fn push(&self, t: T) { self.push(t) } - fn try_pop(&self) -> Option { - use extra_impls::mpsc_queue::*; - - loop { - match self.pop() { - Data(t) => return Some(t), - Empty => return None, - Inconsistent => (), - } - } - } -} - -impl Queue for Mutex> { - fn push(&self, t: T) { self.lock().unwrap().push_back(t) } - fn try_pop(&self) -> Option { self.lock().unwrap().pop_front() } -} - -fn bench_queue_mpsc + Sync>(q: Q) -> f64 { - let d = time(|| { - scope(|scope| { - for _i in 0..THREADS { - let qr = &q; - scope.spawn(move || { - for x in 0..COUNT { - let _ = qr.push(x); - } - }); - } - - let mut count = 0; - while count < COUNT*THREADS { - if q.try_pop().is_some() { - count += 1; - } - } - }); - }); - - nanos(d) / ((COUNT * THREADS) as f64) -} - -fn bench_queue_mpmc + Sync>(q: Q) -> f64 { - use std::sync::atomic::AtomicUsize; - use std::sync::atomic::Ordering::Relaxed; - - let prod_count = AtomicUsize::new(0); - - let d = time(|| { - scope(|scope| { - for _i in 0..THREADS { - let qr = &q; - let pcr = &prod_count; - scope.spawn(move || { - for _x in 0..COUNT { - qr.push(true); - } - if pcr.fetch_add(1, Relaxed) == (THREADS as usize) - 1 { - for _x in 0..THREADS { - qr.push(false) - } - } - }); - scope.spawn(move || { - loop { - if let Some(false) = qr.try_pop() { break } - } - }); - } - - - }); - }); - - nanos(d) / ((COUNT * THREADS) as f64) -} - -fn bench_chan_mpsc() -> f64 { - let (tx, rx) = channel(); - - let d = time(|| { - scope(|scope| { - for _i in 0..THREADS { - let my_tx = tx.clone(); - - scope.spawn(move || { - for x in 0..COUNT { - let _ = my_tx.send(x); - } - }); - } - - for _i in 0..COUNT*THREADS { - let _ = rx.recv().unwrap(); - } - }); - }); - - nanos(d) / ((COUNT * THREADS) as f64) -} - -fn main() { - println!("MSQ mpsc: {}", bench_queue_mpsc(MsQueue::new())); - println!("chan mpsc: {}", bench_chan_mpsc()); - println!("mpsc mpsc: {}", bench_queue_mpsc(MpscQueue::new())); - println!("Seg mpsc: {}", bench_queue_mpsc(SegQueue::new())); - - println!("MSQ mpmc: {}", bench_queue_mpmc(MsQueue::new())); - println!("Seg mpmc: {}", bench_queue_mpmc(SegQueue::new())); - -// println!("queue_mpsc: {}", bench_queue_mpsc()); -// println!("queue_mpmc: {}", bench_queue_mpmc()); -// println!("mutex_mpmc: {}", bench_mutex_mpmc()); -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/bin/extra_impls/mod.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/bin/extra_impls/mod.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/bin/extra_impls/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/bin/extra_impls/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -pub mod mpsc_queue; diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/bin/extra_impls/mpsc_queue.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/bin/extra_impls/mpsc_queue.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/bin/extra_impls/mpsc_queue.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/bin/extra_impls/mpsc_queue.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,155 +0,0 @@ -/* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "AS IS" AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT - * SHALL DMITRY VYUKOV OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation are - * those of the authors and should not be interpreted as representing official - * policies, either expressed or implied, of Dmitry Vyukov. - */ - -//! A mostly lock-free multi-producer, single consumer queue. -//! -//! This module contains an implementation of a concurrent MPSC queue. This -//! queue can be used to share data between threads, and is also used as the -//! building block of channels in rust. -//! -//! Note that the current implementation of this queue has a caveat of the `pop` -//! method, and see the method for more information about it. Due to this -//! caveat, this queue may not be appropriate for all use-cases. - -// http://www.1024cores.net/home/lock-free-algorithms -// /queues/non-intrusive-mpsc-node-based-queue - -pub use self::PopResult::*; - -use std::fmt; -use std::ptr; -use std::cell::UnsafeCell; - -use std::sync::atomic::{AtomicPtr, Ordering}; - -/// A result of the `pop` function. -#[derive(Debug)] -pub enum PopResult { - /// Some data has been popped - Data(T), - /// The queue is empty - Empty, - /// The queue is in an inconsistent state. Popping data should succeed, but - /// some pushers have yet to make enough progress in order allow a pop to - /// succeed. It is recommended that a pop() occur "in the near future" in - /// order to see if the sender has made progress or not - Inconsistent, -} - -#[derive(Debug)] -struct Node { - next: AtomicPtr>, - value: Option, -} - -/// The multi-producer single-consumer structure. This is not cloneable, but it -/// may be safely shared so long as it is guaranteed that there is only one -/// popper at a time (many pushers are allowed). -pub struct Queue { - head: AtomicPtr>, - tail: UnsafeCell<*mut Node>, -} - -impl fmt::Debug for Queue { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Queue {{ ... }}") - } -} - -unsafe impl Send for Queue { } -unsafe impl Sync for Queue { } - -impl Node { - unsafe fn new(v: Option) -> *mut Node { - Box::into_raw(Box::new(Node { - next: AtomicPtr::new(ptr::null_mut()), - value: v, - })) - } -} - -impl Queue { - /// Creates a new queue that is safe to share among multiple producers and - /// one consumer. - pub fn new() -> Queue { - let stub = unsafe { Node::new(None) }; - Queue { - head: AtomicPtr::new(stub), - tail: UnsafeCell::new(stub), - } - } - - /// Pushes a new value onto this queue. - pub fn push(&self, t: T) { - unsafe { - let n = Node::new(Some(t)); - let prev = self.head.swap(n, Ordering::AcqRel); - (*prev).next.store(n, Ordering::Release); - } - } - - /// Pops some data from this queue. - /// - /// Note that the current implementation means that this function cannot - /// return `Option`. It is possible for this queue to be in an - /// inconsistent state where many pushes have succeeded and completely - /// finished, but pops cannot return `Some(t)`. This inconsistent state - /// happens when a pusher is pre-empted at an inopportune moment. - /// - /// This inconsistent state means that this queue does indeed have data, but - /// it does not currently have access to it at this time. - pub fn pop(&self) -> PopResult { - unsafe { - let tail = *self.tail.get(); - let next = (*tail).next.load(Ordering::Acquire); - - if !next.is_null() { - *self.tail.get() = next; - assert!((*tail).value.is_none()); - assert!((*next).value.is_some()); - let ret = (*next).value.take().unwrap(); - let _ = Box::from_raw(tail); - return Data(ret); - } - - if self.head.load(Ordering::Acquire) == tail {Empty} else {Inconsistent} - } - } -} - -impl Drop for Queue { - fn drop(&mut self) { - unsafe { - let mut cur = *self.tail.get(); - while !cur.is_null() { - let next = (*cur).next.load(Ordering::Relaxed); - let _ = Box::from_raw(cur); - cur = next; - } - } - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/bin/stress-msq.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/bin/stress-msq.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/bin/stress-msq.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/bin/stress-msq.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -extern crate crossbeam; - -use crossbeam::sync::MsQueue; -use crossbeam::scope; - -use std::sync::Arc; - -const DUP: usize = 4; -const THREADS: u32 = 2; -const COUNT: u64 = 100000; - -fn main() { - scope(|s| { - for _i in 0..DUP { - let q = Arc::new(MsQueue::new()); - let qs = q.clone(); - - s.spawn(move || { - for i in 1..COUNT { qs.push(i) } - }); - - for _i in 0..THREADS { - let qr = q.clone(); - s.spawn(move || { - let mut cur: u64 = 0; - for _j in 0..COUNT { - if let Some(new) = qr.try_pop() { - assert!(new > cur); - cur = new; - } - } - }); - } - } - }); -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/lib.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/lib.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -//! Support for concurrent and parallel programming. -//! -//! This crate is an early work in progress. The focus for the moment is -//! concurrency: -//! -//! - **Non-blocking data structures**. These data structures allow for high -//! performance, highly-concurrent access, much superior to wrapping with a -//! `Mutex`. Ultimately the goal is to include stacks, queues, deques, bags, -//! sets and maps. These live in the `sync` module. -//! -//! - **Memory management**. Because non-blocking data structures avoid global -//! synchronization, it is not easy to tell when internal data can be safely -//! freed. The `mem` module provides generic, easy to use, and high-performance -//! APIs for managing memory in these cases. These live in the `mem` module. -//! -//! - **Synchronization**. The standard library provides a few synchronization -//! primitives (locks, semaphores, barriers, etc) but this crate seeks to expand -//! that set to include more advanced/niche primitives, as well as userspace -//! alternatives. These live in the `sync` module. -//! -//! - **Scoped thread API**. Finally, the crate provides a "scoped" thread API, -//! making it possible to spawn threads that share stack data with their -//! parents. This functionality is exported at the top-level. - -//#![deny(missing_docs)] - -#![cfg_attr(feature = "nightly", - feature(const_fn, repr_simd, optin_builtin_traits))] - -use std::thread; - -pub use scoped::{scope, Scope, ScopedJoinHandle}; - -pub mod mem; -pub mod sync; -mod scoped; - -#[doc(hidden)] -trait FnBox { - fn call_box(self: Box); -} - -impl FnBox for F { - fn call_box(self: Box) { (*self)() } -} - -/// Like `std::thread::spawn`, but without the closure bounds. -pub unsafe fn spawn_unsafe<'a, F>(f: F) -> thread::JoinHandle<()> where F: FnOnce() + Send + 'a { - use std::mem; - - let closure: Box = Box::new(f); - let closure: Box = mem::transmute(closure); - thread::spawn(move || closure.call_box()) -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/cache_padded.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/cache_padded.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/cache_padded.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/cache_padded.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,164 +0,0 @@ -use std::marker; -use std::cell::UnsafeCell; -use std::fmt; -use std::mem; -use std::ptr; -use std::ops::{Deref, DerefMut}; - -// For now, treat this as an arch-independent constant. -const CACHE_LINE: usize = 32; - -#[cfg_attr(feature = "nightly", - repr(simd))] -#[derive(Debug)] -struct Padding(u64, u64, u64, u64); - -/// Pad `T` to the length of a cacheline. -/// -/// Sometimes concurrent programming requires a piece of data to be padded out -/// to the size of a cacheline to avoid "false sharing": cachelines being -/// invalidated due to unrelated concurrent activity. Use the `CachePadded` type -/// when you want to *avoid* cache locality. -/// -/// At the moment, cache lines are assumed to be 32 * sizeof(usize) on all -/// architectures. -/// -/// **Warning**: the wrapped data is never dropped; move out using `ptr::read` -/// if you need to run dtors. -pub struct CachePadded { - data: UnsafeCell<[usize; CACHE_LINE]>, - _marker: ([Padding; 0], marker::PhantomData), -} - -impl fmt::Debug for CachePadded { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "CachePadded {{ ... }}") - } -} - -unsafe impl Send for CachePadded {} -unsafe impl Sync for CachePadded {} - -#[cfg(not(feature = "nightly"))] -macro_rules! declare_zeros_valid { - () => { - /// Types for which mem::zeroed() is safe. - /// - /// If a type `T: ZerosValid`, then a sequence of zeros the size of `T` must be - /// a valid member of the type `T`. - pub unsafe trait ZerosValid {} - } -} - -#[cfg(feature = "nightly")] -macro_rules! declare_zeros_valid { - () => { - /// Types for which mem::zeroed() is safe. - /// - /// If a type `T: ZerosValid`, then a sequence of zeros the size of `T` must be - /// a valid member of the type `T`. - pub unsafe auto trait ZerosValid {} - } -} - -declare_zeros_valid!(); - -macro_rules! zeros_valid { ($( $T:ty )*) => ($( - unsafe impl ZerosValid for $T {} -)*)} - -zeros_valid!(u8 u16 u32 u64 usize); -zeros_valid!(i8 i16 i32 i64 isize); - -unsafe impl ZerosValid for ::std::sync::atomic::AtomicUsize {} -unsafe impl ZerosValid for ::std::sync::atomic::AtomicPtr {} - -impl CachePadded { - /// A const fn equivalent to mem::zeroed(). - #[cfg(not(feature = "nightly"))] - pub fn zeroed() -> CachePadded { - CachePadded { - data: UnsafeCell::new(([0; CACHE_LINE])), - _marker: ([], marker::PhantomData), - } - } - - /// A const fn equivalent to mem::zeroed(). - #[cfg(feature = "nightly")] - pub const fn zeroed() -> CachePadded { - CachePadded { - data: UnsafeCell::new(([0; CACHE_LINE])), - _marker: ([], marker::PhantomData), - } - } -} - -#[inline] -/// Assert that the size and alignment of `T` are consistent with `CachePadded`. -fn assert_valid() { - assert!(mem::size_of::() <= mem::size_of::>()); - assert!(mem::align_of::() <= mem::align_of::>()); -} - -impl CachePadded { - /// Wrap `t` with cacheline padding. - /// - /// **Warning**: the wrapped data is never dropped; move out using - /// `ptr:read` if you need to run dtors. - pub fn new(t: T) -> CachePadded { - assert_valid::(); - let ret = CachePadded { - data: UnsafeCell::new(([0; CACHE_LINE])), - _marker: ([], marker::PhantomData), - }; - unsafe { - let p: *mut T = mem::transmute(&ret.data); - ptr::write(p, t); - } - ret - } -} - -impl Deref for CachePadded { - type Target = T; - fn deref(&self) -> &T { - assert_valid::(); - unsafe { mem::transmute(&self.data) } - } -} - -impl DerefMut for CachePadded { - fn deref_mut(&mut self) -> &mut T { - assert_valid::(); - unsafe { mem::transmute(&mut self.data) } - } -} - -// FIXME: support Drop by pulling out a version usable for statics -/* -impl Drop for CachePadded { - fn drop(&mut self) { - assert_valid::(); - let p: *mut T = mem::transmute(&self.data); - mem::drop(ptr::read(p)); - } -} -*/ - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn cache_padded_store_u64() { - let x: CachePadded = CachePadded::new(17); - assert_eq!(*x, 17); - } - - #[test] - fn cache_padded_store_pair() { - let x: CachePadded<(u64, u64)> = CachePadded::new((17, 37)); - assert_eq!(x.0, 17); - assert_eq!(x.1, 37); - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/atomic.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/atomic.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/atomic.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/atomic.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,181 +0,0 @@ -use std::marker::PhantomData; -use std::mem; -use std::ptr; -use std::sync::atomic::{self, Ordering}; - -use super::{Owned, Shared, Guard}; - -/// Like `std::sync::atomic::AtomicPtr`. -/// -/// Provides atomic access to a (nullable) pointer of type `T`, interfacing with -/// the `Owned` and `Shared` types. -#[derive(Debug)] -pub struct Atomic { - ptr: atomic::AtomicPtr, - _marker: PhantomData<*const ()>, -} - -unsafe impl Send for Atomic {} -unsafe impl Sync for Atomic {} - -fn opt_shared_into_raw(val: Option>) -> *mut T { - val.map(|p| p.as_raw()).unwrap_or(ptr::null_mut()) -} - -fn opt_owned_as_raw(val: &Option>) -> *mut T { - val.as_ref().map(Owned::as_raw).unwrap_or(ptr::null_mut()) -} - -fn opt_owned_into_raw(val: Option>) -> *mut T { - let ptr = val.as_ref().map(Owned::as_raw).unwrap_or(ptr::null_mut()); - mem::forget(val); - ptr -} - -impl Atomic { - /// Create a new, null atomic pointer. - #[cfg(feature = "nightly")] - pub const fn null() -> Atomic { - Atomic { - ptr: atomic::AtomicPtr::new(0 as *mut _), - _marker: PhantomData - } - } - - #[cfg(not(feature = "nightly"))] - pub fn null() -> Atomic { - Atomic { - ptr: atomic::AtomicPtr::new(0 as *mut _), - _marker: PhantomData - } - } - - /// Create a new atomic pointer - pub fn new(data: T) -> Atomic { - Atomic { - ptr: atomic::AtomicPtr::new(Box::into_raw(Box::new(data))), - _marker: PhantomData - } - } - - /// Do an atomic load with the given memory ordering. - /// - /// In order to perform the load, we must pass in a borrow of a - /// `Guard`. This is a way of guaranteeing that the thread has pinned the - /// epoch for the entire lifetime `'a`. In return, you get an optional - /// `Shared` pointer back (`None` if the `Atomic` is currently null), with - /// lifetime tied to the guard. - /// - /// # Panics - /// - /// Panics if `ord` is `Release` or `AcqRel`. - pub fn load<'a>(&self, ord: Ordering, _: &'a Guard) -> Option> { - unsafe { Shared::from_raw(self.ptr.load(ord)) } - } - - /// Do an atomic store with the given memory ordering. - /// - /// Transfers ownership of the given `Owned` pointer, if any. Since no - /// lifetime information is acquired, no `Guard` value is needed. - /// - /// # Panics - /// - /// Panics if `ord` is `Acquire` or `AcqRel`. - pub fn store(&self, val: Option>, ord: Ordering) { - self.ptr.store(opt_owned_into_raw(val), ord) - } - - /// Do an atomic store with the given memory ordering, immediately yielding - /// a shared reference to the pointer that was stored. - /// - /// Transfers ownership of the given `Owned` pointer, yielding a `Shared` - /// reference to it. Since the reference is valid only for the curent epoch, - /// it's lifetime is tied to a `Guard` value. - /// - /// # Panics - /// - /// Panics if `ord` is `Acquire` or `AcqRel`. - pub fn store_and_ref<'a>(&self, val: Owned, ord: Ordering, _: &'a Guard) - -> Shared<'a, T> - { - unsafe { - let shared = Shared::from_owned(val); - self.store_shared(Some(shared), ord); - shared - } - } - - /// Do an atomic store of a `Shared` pointer with the given memory ordering. - /// - /// This operation does not require a guard, because it does not yield any - /// new information about the lifetime of a pointer. - /// - /// # Panics - /// - /// Panics if `ord` is `Acquire` or `AcqRel`. - pub fn store_shared(&self, val: Option>, ord: Ordering) { - self.ptr.store(opt_shared_into_raw(val), ord) - } - - /// Do a compare-and-set from a `Shared` to an `Owned` pointer with the - /// given memory ordering. - /// - /// As with `store`, this operation does not require a guard; it produces no new - /// lifetime information. The `Result` indicates whether the CAS succeeded; if - /// not, ownership of the `new` pointer is returned to the caller. - pub fn cas(&self, old: Option>, new: Option>, ord: Ordering) - -> Result<(), Option>> - { - if self.ptr.compare_and_swap(opt_shared_into_raw(old), - opt_owned_as_raw(&new), - ord) == opt_shared_into_raw(old) - { - mem::forget(new); - Ok(()) - } else { - Err(new) - } - } - - /// Do a compare-and-set from a `Shared` to an `Owned` pointer with the - /// given memory ordering, immediatley acquiring a new `Shared` reference to - /// the previously-owned pointer if successful. - /// - /// This operation is analogous to `store_and_ref`. - pub fn cas_and_ref<'a>(&self, old: Option>, new: Owned, - ord: Ordering, _: &'a Guard) - -> Result, Owned> - { - if self.ptr.compare_and_swap(opt_shared_into_raw(old), new.as_raw(), ord) - == opt_shared_into_raw(old) - { - Ok(unsafe { Shared::from_owned(new) }) - } else { - Err(new) - } - } - - /// Do a compare-and-set from a `Shared` to another `Shared` pointer with - /// the given memory ordering. - /// - /// The boolean return value is `true` when the CAS is successful. - pub fn cas_shared(&self, old: Option>, new: Option>, ord: Ordering) - -> bool - { - self.ptr.compare_and_swap(opt_shared_into_raw(old), - opt_shared_into_raw(new), - ord) == opt_shared_into_raw(old) - } - - /// Do an atomic swap with an `Owned` pointer with the given memory ordering. - pub fn swap<'a>(&self, new: Option>, ord: Ordering, _: &'a Guard) - -> Option> { - unsafe { Shared::from_raw(self.ptr.swap(opt_owned_into_raw(new), ord)) } - } - - /// Do an atomic swap with a `Shared` pointer with the given memory ordering. - pub fn swap_shared<'a>(&self, new: Option>, ord: Ordering, _: &'a Guard) - -> Option> { - unsafe { Shared::from_raw(self.ptr.swap(opt_shared_into_raw(new), ord)) } - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/garbage.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/garbage.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/garbage.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/garbage.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,144 +0,0 @@ -// Data structures for storing garbage to be freed later (once the -// epochs have sufficiently advanced). -// -// In general, we try to manage the garbage thread locally whenever -// possible. Each thread keep track of three bags of garbage. But if a -// thread is exiting, these bags must be moved into the global garbage -// bags. - -use std::ptr; -use std::mem; -use std::sync::atomic::AtomicPtr; -use std::sync::atomic::Ordering::{Relaxed, Release, Acquire}; - -use mem::ZerosValid; - -/// One item of garbage. -/// -/// Stores enough information to do a deallocation. -#[derive(Debug)] -struct Item { - ptr: *mut u8, - free: unsafe fn(*mut u8), -} - -/// A single, thread-local bag of garbage. -#[derive(Debug)] -pub struct Bag(Vec); - -impl Bag { - fn new() -> Bag { - Bag(vec![]) - } - - fn insert(&mut self, elem: *mut T) { - let size = mem::size_of::(); - if size > 0 { - self.0.push(Item { - ptr: elem as *mut u8, - free: free::, - }) - } - unsafe fn free(t: *mut u8) { - drop(Vec::from_raw_parts(t as *mut T, 0, 1)); - } - } - - fn len(&self) -> usize { - self.0.len() - } - - /// Deallocate all garbage in the bag - pub unsafe fn collect(&mut self) { - let mut data = mem::replace(&mut self.0, Vec::new()); - for item in data.iter() { - (item.free)(item.ptr); - } - data.truncate(0); - self.0 = data; - } -} - -// needed because the bags store raw pointers. -unsafe impl Send for Bag {} -unsafe impl Sync for Bag {} - -/// A thread-local set of garbage bags. -#[derive(Debug)] -pub struct Local { - /// Garbage added at least one epoch behind the current local epoch - pub old: Bag, - /// Garbage added in the current local epoch or earlier - pub cur: Bag, - /// Garbage added in the current *global* epoch - pub new: Bag, -} - -impl Local { - pub fn new() -> Local { - Local { - old: Bag::new(), - cur: Bag::new(), - new: Bag::new(), - } - } - - pub fn insert(&mut self, elem: *mut T) { - self.new.insert(elem) - } - - /// Collect one epoch of garbage, rotating the local garbage bags. - pub unsafe fn collect(&mut self) { - let ret = self.old.collect(); - mem::swap(&mut self.old, &mut self.cur); - mem::swap(&mut self.cur, &mut self.new); - ret - } - - pub fn size(&self) -> usize { - self.old.len() + self.cur.len() + self.new.len() - } -} - -/// A concurrent garbage bag, currently based on Treiber's stack. -/// -/// The elements are themselves owned `Bag`s. -#[derive(Debug)] -pub struct ConcBag { - head: AtomicPtr, -} - -unsafe impl ZerosValid for ConcBag {} - -#[derive(Debug)] -struct Node { - data: Bag, - next: AtomicPtr, -} - -impl ConcBag { - pub fn insert(&self, t: Bag){ - let n = Box::into_raw(Box::new( - Node { data: t, next: AtomicPtr::new(ptr::null_mut()) })); - loop { - let head = self.head.load(Acquire); - unsafe { (*n).next.store(head, Relaxed) }; - if self.head.compare_and_swap(head, n, Release) == head { break } - } - } - - pub unsafe fn collect(&self) { - // check to avoid xchg instruction - // when no garbage exists - let mut head = self.head.load(Relaxed); - if head != ptr::null_mut() { - head = self.head.swap(ptr::null_mut(), Acquire); - - while head != ptr::null_mut() { - let mut n = Box::from_raw(head); - n.data.collect(); - head = n.next.load(Relaxed); - } - } - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/global.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/global.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/global.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/global.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,95 +0,0 @@ -// Definition of global epoch state. The `get` function is the way to -// access this data externally (until const fn is stabilized...). - -use std::sync::atomic::AtomicUsize; - -use mem::CachePadded; -use mem::epoch::garbage; -use mem::epoch::participants::Participants; - -/// Global epoch state -#[derive(Debug)] -pub struct EpochState { - /// Current global epoch - pub epoch: CachePadded, - - // FIXME: move this into the `garbage` module, rationalize API - /// Global garbage bags - pub garbage: [CachePadded; 3], - - /// Participant list - pub participants: Participants, -} - -unsafe impl Send for EpochState {} -unsafe impl Sync for EpochState {} - -pub use self::imp::get; - -#[cfg(not(feature = "nightly"))] -mod imp { - use std::mem; - use std::sync::atomic::{self, AtomicUsize}; - use std::sync::atomic::Ordering::Relaxed; - - use super::EpochState; - use mem::CachePadded; - use mem::epoch::participants::Participants; - - impl EpochState { - fn new() -> EpochState { - EpochState { - epoch: CachePadded::zeroed(), - garbage: [CachePadded::zeroed(), - CachePadded::zeroed(), - CachePadded::zeroed()], - participants: Participants::new(), - } - } - } - - static EPOCH: AtomicUsize = atomic::ATOMIC_USIZE_INIT; - - pub fn get() -> &'static EpochState { - let mut addr = EPOCH.load(Relaxed); - - if addr == 0 { - let boxed = Box::new(EpochState::new()); - let raw = Box::into_raw(boxed); - - addr = EPOCH.compare_and_swap(0, raw as usize, Relaxed); - if addr != 0 { - let boxed = unsafe { Box::from_raw(raw) }; - mem::drop(boxed); - } else { - addr = raw as usize; - } - } - - unsafe { - &*(addr as *mut EpochState) - } - } -} - -#[cfg(feature = "nightly")] -mod imp { - use super::EpochState; - use mem::CachePadded; - use mem::epoch::participants::Participants; - - impl EpochState { - const fn new() -> EpochState { - EpochState { - epoch: CachePadded::zeroed(), - garbage: [CachePadded::zeroed(), - CachePadded::zeroed(), - CachePadded::zeroed()], - participants: Participants::new(), - } - } - } - - static EPOCH: EpochState = EpochState::new(); - pub fn get() -> &'static EpochState { &EPOCH } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/guard.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/guard.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/guard.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/guard.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -use std::marker; - -use super::{local, Shared}; - -/// An RAII-style guard for pinning the current epoch. -/// -/// A guard must be acquired before most operations on an `Atomic` pointer. On -/// destruction, it unpins the epoch. -#[must_use] -#[derive(Debug)] -pub struct Guard { - _marker: marker::PhantomData<*mut ()>, // !Send and !Sync -} - -/// Pin the current epoch. -/// -/// Threads generally pin before interacting with a lock-free data -/// structure. Pinning requires a full memory barrier, so is somewhat -/// expensive. It is rentrant -- you can safely acquire nested guards, and only -/// the first guard requires a barrier. Thus, in cases where you expect to -/// perform several lock-free operations in quick succession, you may consider -/// pinning around the entire set of operations. -pub fn pin() -> Guard { - local::with_participant(|p| { - p.enter(); - - let g = Guard { - _marker: marker::PhantomData, - }; - - if p.should_gc() { - p.try_collect(&g); - } - - g - }) -} - -impl Guard { - /// Assert that the value is no longer reachable from a lock-free data - /// structure and should be collected when sufficient epochs have passed. - pub unsafe fn unlinked(&self, val: Shared) { - local::with_participant(|p| p.reclaim(val.as_raw())) - } - - /// Move the thread-local garbage into the global set of garbage. - pub fn migrate_garbage(&self) { - local::with_participant(|p| p.migrate_garbage()) - } -} - -impl Drop for Guard { - fn drop(&mut self) { - local::with_participant(|p| p.exit()); - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/local.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/local.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/local.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/local.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// Manage the thread-local state, providing access to a `Participant` record. - -use std::sync::atomic::Ordering::Relaxed; - -use mem::epoch::participant::Participant; -use mem::epoch::global; - -#[derive(Debug)] -struct LocalEpoch { - participant: *const Participant, -} - -impl LocalEpoch { - fn new() -> LocalEpoch { - LocalEpoch { participant: global::get().participants.enroll() } - } - - fn get(&self) -> &Participant { - unsafe { &*self.participant } - } -} - -// FIXME: avoid leaking when all threads have exited -impl Drop for LocalEpoch { - fn drop(&mut self) { - let p = self.get(); - p.enter(); - p.migrate_garbage(); - p.exit(); - p.active.store(false, Relaxed); - } -} - -thread_local!(static LOCAL_EPOCH: LocalEpoch = LocalEpoch::new() ); - -pub fn with_participant(f: F) -> T where F: FnOnce(&Participant) -> T { - LOCAL_EPOCH.with(|e| f(e.get())) -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/mod.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/mod.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,265 +0,0 @@ -//! Epoch-based memory management -//! -//! This module provides fast, easy to use memory management for lock free data -//! structures. It's inspired by [Keir Fraser's *epoch-based -//! reclamation*](https://www.cl.cam.ac.uk/techreports/UCAM-CL-TR-579.pdf). -//! -//! The basic problem this is solving is the fact that when one thread has -//! removed a node from a data structure, other threads may still have pointers -//! to that node (in the form of snapshots that will be validated through things -//! like compare-and-swap), so the memory cannot be immediately freed. Put differently: -//! -//! 1. There are two sources of reachability at play -- the data structure, and -//! the snapshots in threads accessing it. Before we delete a node, we need to know -//! that it cannot be reached in either of these ways. -//! -//! 2. Once a node has been unliked from the data structure, no *new* snapshots -//! reaching it will be created. -//! -//! Using the epoch scheme is fairly straightforward, and does not require -//! understanding any of the implementation details: -//! -//! - When operating on a shared data structure, a thread must "pin the current -//! epoch", which is done by calling `pin()`. This function returns a `Guard` -//! which unpins the epoch when destroyed. -//! -//! - When the thread subsequently reads from a lock-free data structure, the -//! pointers it extracts act like references with lifetime tied to the -//! `Guard`. This allows threads to safely read from snapshotted data, being -//! guaranteed that the data will remain allocated until they exit the epoch. -//! -//! To put the `Guard` to use, Crossbeam provides a set of three pointer types meant to work together: -//! -//! - `Owned`, akin to `Box`, which points to uniquely-owned data that has -//! not yet been published in a concurrent data structure. -//! -//! - `Shared<'a, T>`, akin to `&'a T`, which points to shared data that may or may -//! not be reachable from a data structure, but it guaranteed not to be freed -//! during lifetime `'a`. -//! -//! - `Atomic`, akin to `std::sync::atomic::AtomicPtr`, which provides atomic -//! updates to a pointer using the `Owned` and `Shared` types, and connects them -//! to a `Guard`. -//! -//! Each of these types provides further documentation on usage. -//! -//! # Example -//! -//! ``` -//! use std::sync::atomic::Ordering::{Acquire, Release, Relaxed}; -//! use std::ptr; -//! -//! use crossbeam::mem::epoch::{self, Atomic, Owned}; -//! -//! struct TreiberStack { -//! head: Atomic>, -//! } -//! -//! struct Node { -//! data: T, -//! next: Atomic>, -//! } -//! -//! impl TreiberStack { -//! fn new() -> TreiberStack { -//! TreiberStack { -//! head: Atomic::null() -//! } -//! } -//! -//! fn push(&self, t: T) { -//! // allocate the node via Owned -//! let mut n = Owned::new(Node { -//! data: t, -//! next: Atomic::null(), -//! }); -//! -//! // become active -//! let guard = epoch::pin(); -//! -//! loop { -//! // snapshot current head -//! let head = self.head.load(Relaxed, &guard); -//! -//! // update `next` pointer with snapshot -//! n.next.store_shared(head, Relaxed); -//! -//! // if snapshot is still good, link in the new node -//! match self.head.cas_and_ref(head, n, Release, &guard) { -//! Ok(_) => return, -//! Err(owned) => n = owned, -//! } -//! } -//! } -//! -//! fn pop(&self) -> Option { -//! // become active -//! let guard = epoch::pin(); -//! -//! loop { -//! // take a snapshot -//! match self.head.load(Acquire, &guard) { -//! // the stack is non-empty -//! Some(head) => { -//! // read through the snapshot, *safely*! -//! let next = head.next.load(Relaxed, &guard); -//! -//! // if snapshot is still good, update from `head` to `next` -//! if self.head.cas_shared(Some(head), next, Release) { -//! unsafe { -//! // mark the node as unlinked -//! guard.unlinked(head); -//! -//! // extract out the data from the now-unlinked node -//! return Some(ptr::read(&(*head).data)) -//! } -//! } -//! } -//! -//! // we observed the stack empty -//! None => return None -//! } -//! } -//! } -//! } -//! ``` - -// FIXME: document implementation details - -mod atomic; -mod garbage; -mod global; -mod guard; -mod local; -mod participant; -mod participants; - -pub use self::atomic::Atomic; -pub use self::guard::{pin, Guard}; - -use std::ops::{Deref, DerefMut}; -use std::ptr; -use std::mem; - -/// Like `Box`: an owned, heap-allocated data value of type `T`. -#[derive(Debug)] -pub struct Owned { - data: Box, -} - -impl Owned { - /// Move `t` to a new heap allocation. - pub fn new(t: T) -> Owned { - Owned { data: Box::new(t) } - } - - fn as_raw(&self) -> *mut T { - self.deref() as *const _ as *mut _ - } - - /// Move data out of the owned box, deallocating the box. - pub fn into_inner(self) -> T { - *self.data - } -} - -impl Deref for Owned { - type Target = T; - fn deref(&self) -> &T { - &self.data - } -} - -impl DerefMut for Owned { - fn deref_mut(&mut self) -> &mut T { - &mut self.data - } -} - -#[derive(PartialEq, Eq)] -/// Like `&'a T`: a shared reference valid for lifetime `'a`. -#[derive(Debug)] -pub struct Shared<'a, T: 'a> { - data: &'a T, -} - -impl<'a, T> Copy for Shared<'a, T> {} -impl<'a, T> Clone for Shared<'a, T> { - fn clone(&self) -> Shared<'a, T> { - Shared { data: self.data } - } -} - -impl<'a, T> Deref for Shared<'a, T> { - type Target = &'a T; - fn deref(&self) -> &&'a T { - &self.data - } -} - -impl<'a, T> Shared<'a, T> { - unsafe fn from_raw(raw: *mut T) -> Option> { - if raw == ptr::null_mut() { None } - else { - Some(Shared { - data: mem::transmute::<*mut T, &T>(raw) - }) - } - } - - unsafe fn from_ref(r: &T) -> Shared<'a, T> { - Shared { data: mem::transmute(r) } - } - - unsafe fn from_owned(owned: Owned) -> Shared<'a, T> { - let ret = Shared::from_ref(owned.deref()); - mem::forget(owned); - ret - } - - pub fn as_raw(&self) -> *mut T { - self.data as *const _ as *mut _ - } -} - - -#[cfg(test)] -mod test { - use std::sync::atomic::Ordering; - use super::*; - use mem::epoch; - - #[test] - fn test_no_drop() { - static mut DROPS: i32 = 0; - struct Test; - impl Drop for Test { - fn drop(&mut self) { - unsafe { - DROPS += 1; - } - } - } - let g = pin(); - - let x = Atomic::null(); - x.store(Some(Owned::new(Test)), Ordering::Relaxed); - x.store_and_ref(Owned::new(Test), Ordering::Relaxed, &g); - let y = x.load(Ordering::Relaxed, &g); - let z = x.cas_and_ref(y, Owned::new(Test), Ordering::Relaxed, &g).ok(); - let _ = x.cas(z, Some(Owned::new(Test)), Ordering::Relaxed); - x.swap(Some(Owned::new(Test)), Ordering::Relaxed, &g); - - unsafe { - assert_eq!(DROPS, 0); - } - } - - #[test] - fn test_new() { - let guard = epoch::pin(); - let my_atomic = Atomic::new(42); - - assert_eq!(**my_atomic.load(Ordering::Relaxed, &guard).unwrap(), 42); - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/participant.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/participant.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/participant.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/participant.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,133 +0,0 @@ -// Manages a single participant in the epoch scheme. This is where all -// of the actual epoch management logic happens! - -use std::mem; -use std::cell::UnsafeCell; -use std::fmt; -use std::sync::atomic::{self, AtomicUsize, AtomicBool}; -use std::sync::atomic::Ordering::{Relaxed, Acquire, Release, SeqCst}; - -use mem::epoch::{Atomic, Guard, garbage, global}; -use mem::epoch::participants::ParticipantNode; - -/// Thread-local data for epoch participation. -pub struct Participant { - /// The local epoch. - epoch: AtomicUsize, - - /// Number of pending uses of `epoch::pin()`; keeping a count allows for - /// reentrant use of epoch management. - in_critical: AtomicUsize, - - /// Thread-local garbage tracking - garbage: UnsafeCell, - - /// Is the thread still active? Becomes `false` when the thread exits. This - /// is ultimately used to free `Participant` records. - pub active: AtomicBool, - - /// The participant list is coded intrusively; here's the `next` pointer. - pub next: Atomic, -} - -impl fmt::Debug for Participant { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Participant {{ ... }}") - } -} - -unsafe impl Sync for Participant {} - -const GC_THRESH: usize = 32; - -impl Participant { - pub fn new() -> Participant { - Participant { - epoch: AtomicUsize::new(0), - in_critical: AtomicUsize::new(0), - active: AtomicBool::new(true), - garbage: UnsafeCell::new(garbage::Local::new()), - next: Atomic::null(), - } - } - - /// Enter a critical section. - /// - /// This method is reentrant, allowing for nested critical sections. - /// - /// Returns `true` is this is the first entry on the stack (as opposed to a - /// re-entrant call). - pub fn enter(&self) -> bool { - let new_count = self.in_critical.load(Relaxed) + 1; - self.in_critical.store(new_count, Relaxed); - if new_count > 1 { return false } - - atomic::fence(SeqCst); - - let global_epoch = global::get().epoch.load(Relaxed); - if global_epoch != self.epoch.load(Relaxed) { - self.epoch.store(global_epoch, Relaxed); - unsafe { (*self.garbage.get()).collect(); } - } - - true - } - - /// Exit the current (nested) critical section. - pub fn exit(&self) { - let new_count = self.in_critical.load(Relaxed) - 1; - self.in_critical.store( - new_count, - if new_count > 0 { Relaxed } else { Release }); - } - - /// Begin the reclamation process for a piece of data. - pub unsafe fn reclaim(&self, data: *mut T) { - (*self.garbage.get()).insert(data); - } - - /// Attempt to collect garbage by moving the global epoch forward. - /// - /// Returns `true` on success. - pub fn try_collect(&self, guard: &Guard) -> bool { - let cur_epoch = global::get().epoch.load(SeqCst); - - for p in global::get().participants.iter(guard) { - if p.in_critical.load(Relaxed) > 0 && p.epoch.load(Relaxed) != cur_epoch { - return false - } - } - - let new_epoch = cur_epoch.wrapping_add(1); - atomic::fence(Acquire); - if global::get().epoch.compare_and_swap(cur_epoch, new_epoch, SeqCst) != cur_epoch { - return false - } - - unsafe { - (*self.garbage.get()).collect(); - global::get().garbage[new_epoch.wrapping_add(1) % 3].collect(); - } - self.epoch.store(new_epoch, Release); - - true - } - - /// Move the current thread-local garbage into the global garbage bags. - pub fn migrate_garbage(&self) { - let cur_epoch = self.epoch.load(Relaxed); - let local = unsafe { mem::replace(&mut *self.garbage.get(), garbage::Local::new()) }; - global::get().garbage[cur_epoch.wrapping_sub(1) % 3].insert(local.old); - global::get().garbage[cur_epoch % 3].insert(local.cur); - global::get().garbage[global::get().epoch.load(Relaxed) % 3].insert(local.new); - } - - /// How much garbage is this participant currently storing? - pub fn garbage_size(&self) -> usize { - unsafe { (*self.garbage.get()).size() } - } - /// Is this participant past its local GC threshhold? - pub fn should_gc(&self) -> bool { - self.garbage_size() >= GC_THRESH - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/participants.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/participants.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/epoch/participants.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/epoch/participants.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,120 +0,0 @@ -// Manages the global participant list, which is an intrustive list in -// which items are lazily removed on traversal (after being -// "logically" deleted by becoming inactive.) - -use std::mem; -use std::ops::{Deref, DerefMut}; -use std::sync::atomic::Ordering::{Relaxed, Acquire, Release}; - -use mem::epoch::{Atomic, Owned, Guard}; -use mem::epoch::participant::Participant; -use mem::CachePadded; - -/// Global, threadsafe list of threads participating in epoch management. -#[derive(Debug)] -pub struct Participants { - head: Atomic -} - -#[derive(Debug)] -pub struct ParticipantNode(CachePadded); - -impl ParticipantNode { - pub fn new() -> ParticipantNode { - ParticipantNode(CachePadded::new(Participant::new())) - } -} - -impl Deref for ParticipantNode { - type Target = Participant; - fn deref(&self) -> &Participant { - &self.0 - } -} - -impl DerefMut for ParticipantNode { - fn deref_mut(&mut self) -> &mut Participant { - &mut self.0 - } -} - -impl Participants { - #[cfg(not(feature = "nightly"))] - pub fn new() -> Participants { - Participants { head: Atomic::null() } - } - - #[cfg(feature = "nightly")] - pub const fn new() -> Participants { - Participants { head: Atomic::null() } - } - - /// Enroll a new thread in epoch management by adding a new `Particpant` - /// record to the global list. - pub fn enroll(&self) -> *const Participant { - let mut participant = Owned::new(ParticipantNode::new()); - - // we ultimately use epoch tracking to free Participant nodes, but we - // can't actually enter an epoch here, so fake it; we know the node - // can't be removed until marked inactive anyway. - let fake_guard = (); - let g: &'static Guard = unsafe { mem::transmute(&fake_guard) }; - loop { - let head = self.head.load(Relaxed, g); - participant.next.store_shared(head, Relaxed); - match self.head.cas_and_ref(head, participant, Release, g) { - Ok(shared) => { - let shared: &Participant = &shared; - return shared; - } - Err(owned) => { - participant = owned; - } - } - } - } - - pub fn iter<'a>(&'a self, g: &'a Guard) -> Iter<'a> { - Iter { - guard: g, - next: &self.head, - needs_acq: true, - } - } -} - -#[derive(Debug)] -pub struct Iter<'a> { - // pin to an epoch so that we can free inactive nodes - guard: &'a Guard, - next: &'a Atomic, - - // an Acquire read is needed only for the first read, due to release - // sequences - needs_acq: bool, -} - -impl<'a> Iterator for Iter<'a> { - type Item = &'a Participant; - fn next(&mut self) -> Option<&'a Participant> { - let mut cur = if self.needs_acq { - self.needs_acq = false; - self.next.load(Acquire, self.guard) - } else { - self.next.load(Relaxed, self.guard) - }; - - while let Some(n) = cur { - // attempt to clean up inactive nodes - if !n.active.load(Relaxed) { - cur = n.next.load(Relaxed, self.guard); - // TODO: actually reclaim inactive participants! - } else { - self.next = &n.next; - return Some(&n) - } - } - - None - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/mod.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/mod.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/mem/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/mem/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ -//! Memory management for concurrent data structures -//! -//! At the moment, the only memory management scheme is epoch-based reclamation, -//! found in the `epoch` submodule. - -pub use self::cache_padded::{CachePadded, ZerosValid}; - -pub mod epoch; -mod cache_padded; diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/scoped.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/scoped.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/scoped.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/scoped.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,275 +0,0 @@ -use std::cell::RefCell; -use std::fmt; -use std::mem; -use std::rc::Rc; -use std::sync::atomic::Ordering; -use std::sync::Arc; -use std::thread; - -use {spawn_unsafe, FnBox}; -use sync::AtomicOption; - -pub struct Scope<'a> { - dtors: RefCell>> -} - -struct DtorChain<'a> { - dtor: Box, - next: Option>> -} - -enum JoinState { - Running(thread::JoinHandle<()>), - Joined, -} - -impl JoinState { - fn join(&mut self) { - let mut state = JoinState::Joined; - mem::swap(self, &mut state); - if let JoinState::Running(handle) = state { - let res = handle.join(); - - if !thread::panicking() { res.unwrap(); } - } - } -} - -/// A handle to a scoped thread -pub struct ScopedJoinHandle { - inner: Rc>, - packet: Arc>, - thread: thread::Thread, -} - -/// Create a new `scope`, for deferred destructors. -/// -/// Scopes, in particular, support [*scoped thread spawning*](struct.Scope.html#method.spawn). -/// -/// # Examples -/// -/// Creating and using a scope: -/// -/// ``` -/// crossbeam::scope(|scope| { -/// scope.defer(|| println!("Exiting scope")); -/// scope.spawn(|| println!("Running child thread in scope")) -/// }); -/// // Prints messages in the reverse order written -/// ``` -pub fn scope<'a, F, R>(f: F) -> R where F: FnOnce(&Scope<'a>) -> R { - let mut scope = Scope { dtors: RefCell::new(None) }; - let ret = f(&scope); - scope.drop_all(); - ret -} - -impl<'a> fmt::Debug for Scope<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Scope {{ ... }}") - } -} - -impl fmt::Debug for ScopedJoinHandle { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "ScopedJoinHandle {{ ... }}") - } -} - -impl<'a> Scope<'a> { - // This method is carefully written in a transactional style, so - // that it can be called directly and, if any dtor panics, can be - // resumed in the unwinding this causes. By initially running the - // method outside of any destructor, we avoid any leakage problems - // due to @rust-lang/rust#14875. - fn drop_all(&mut self) { - loop { - // use a separate scope to ensure that the RefCell borrow - // is relinquishe before running `dtor` - let dtor = { - let mut dtors = self.dtors.borrow_mut(); - if let Some(mut node) = dtors.take() { - *dtors = node.next.take().map(|b| *b); - node.dtor - } else { - return - } - }; - dtor.call_box() - } - } - - /// Schedule code to be executed when exiting the scope. - /// - /// This is akin to having a destructor on the stack, except that it is - /// *guaranteed* to be run. - pub fn defer(&self, f: F) where F: FnOnce() + 'a { - let mut dtors = self.dtors.borrow_mut(); - *dtors = Some(DtorChain { - dtor: Box::new(f), - next: dtors.take().map(Box::new) - }); - } - - /// Create a scoped thread. - /// - /// `spawn` is similar to the [`spawn`][spawn] function in Rust's standard library. The - /// difference is that this thread is scoped, meaning that it's guaranteed to terminate - /// before the current stack frame goes away, allowing you to reference the parent stack frame - /// directly. This is ensured by having the parent thread join on the child thread before the - /// scope exits. - /// - /// [spawn]: http://doc.rust-lang.org/std/thread/fn.spawn.html - /// - /// # Examples - /// - /// A basic scoped thread: - /// - /// ``` - /// crossbeam::scope(|scope| { - /// scope.spawn(|| { - /// println!("Hello from a scoped thread!"); - /// }); - /// }); - /// ``` - /// - /// When writing concurrent Rust programs, you'll sometimes see a pattern like this, using - /// [`std::thread::spawn`][spawn]: - /// - /// ```ignore - /// let array = [1, 2, 3]; - /// let mut guards = vec![]; - /// - /// for i in &array { - /// let guard = std::thread::spawn(move || { - /// println!("element: {}", i); - /// }); - /// - /// guards.push(guard); - /// } - /// - /// for guard in guards { - /// guard.join().unwrap(); - /// } - /// ``` - /// - /// The basic pattern is: - /// - /// 1. Iterate over some collection. - /// 2. Spin up a thread to operate on each part of the collection. - /// 3. Join all the threads. - /// - /// However, this code actually gives an error: - /// - /// ```text - /// error: `array` does not live long enough - /// for i in &array { - /// ^~~~~ - /// in expansion of for loop expansion - /// note: expansion site - /// note: reference must be valid for the static lifetime... - /// note: ...but borrowed value is only valid for the block suffix following statement 0 at ... - /// let array = [1, 2, 3]; - /// let mut guards = vec![]; - /// - /// for i in &array { - /// let guard = std::thread::spawn(move || { - /// println!("element: {}", i); - /// ... - /// error: aborting due to previous error - /// ``` - /// - /// Because [`std::thread::spawn`][spawn] doesn't know about this scope, it requires a - /// `'static` lifetime. One way of giving it a proper lifetime is to use an [`Arc`][arc]: - /// - /// [arc]: http://doc.rust-lang.org/stable/std/sync/struct.Arc.html - /// - /// ``` - /// use std::sync::Arc; - /// - /// let array = Arc::new([1, 2, 3]); - /// let mut guards = vec![]; - /// - /// for i in (0..array.len()) { - /// let a = array.clone(); - /// - /// let guard = std::thread::spawn(move || { - /// println!("element: {}", a[i]); - /// }); - /// - /// guards.push(guard); - /// } - /// - /// for guard in guards { - /// guard.join().unwrap(); - /// } - /// ``` - /// - /// But this introduces unnecessary allocation, as `Arc` puts its data on the heap, and we - /// also end up dealing with reference counts. We know that we're joining the threads before - /// our function returns, so just taking a reference _should_ be safe. Rust can't know that, - /// though. - /// - /// Enter scoped threads. Here's our original example, using `spawn` from crossbeam rather - /// than from `std::thread`: - /// - /// ``` - /// let array = [1, 2, 3]; - /// - /// crossbeam::scope(|scope| { - /// for i in &array { - /// scope.spawn(move || { - /// println!("element: {}", i); - /// }); - /// } - /// }); - /// ``` - /// - /// Much more straightforward. - pub fn spawn(&self, f: F) -> ScopedJoinHandle where - F: FnOnce() -> T + Send + 'a, T: Send + 'a - { - let their_packet = Arc::new(AtomicOption::new()); - let my_packet = their_packet.clone(); - - let join_handle = unsafe { - spawn_unsafe(move || { - their_packet.swap(f(), Ordering::Relaxed); - }) - }; - - let thread = join_handle.thread().clone(); - let deferred_handle = Rc::new(RefCell::new(JoinState::Running(join_handle))); - let my_handle = deferred_handle.clone(); - - self.defer(move || { - let mut state = deferred_handle.borrow_mut(); - state.join(); - }); - - ScopedJoinHandle { - inner: my_handle, - packet: my_packet, - thread: thread, - } - } -} - -impl ScopedJoinHandle { - /// Join the scoped thread, returning the result it produced. - pub fn join(self) -> T { - self.inner.borrow_mut().join(); - self.packet.take(Ordering::Relaxed).unwrap() - } - - /// Get the underlying thread handle. - pub fn thread(&self) -> &thread::Thread { - &self.thread - } -} - -impl<'a> Drop for Scope<'a> { - fn drop(&mut self) { - self.drop_all() - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/arc_cell.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/arc_cell.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/arc_cell.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/arc_cell.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,90 +0,0 @@ -use std::marker::PhantomData; -use std::mem; -use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; - -/// A type providing atomic storage and retrieval of an `Arc`. -#[derive(Debug)] -pub struct ArcCell(AtomicUsize, PhantomData>); - -impl Drop for ArcCell { - fn drop(&mut self) { - self.take(); - } -} - -impl ArcCell { - /// Creates a new `ArcCell`. - pub fn new(t: Arc) -> ArcCell { - ArcCell(AtomicUsize::new(unsafe { mem::transmute(t) }), PhantomData) - } - - fn take(&self) -> Arc { - loop { - match self.0.swap(0, Ordering::Acquire) { - 0 => {} - n => return unsafe { mem::transmute(n) } - } - } - } - - fn put(&self, t: Arc) { - debug_assert_eq!(self.0.load(Ordering::SeqCst), 0); - self.0.store(unsafe { mem::transmute(t) }, Ordering::Release); - } - - /// Stores a new value in the `ArcCell`, returning the previous - /// value. - pub fn set(&self, t: Arc) -> Arc { - let old = self.take(); - self.put(t); - old - } - - /// Returns a copy of the value stored by the `ArcCell`. - pub fn get(&self) -> Arc { - let t = self.take(); - // NB: correctness here depends on Arc's clone impl not panicking - let out = t.clone(); - self.put(t); - out - } -} - -#[cfg(test)] -mod test { - use std::sync::Arc; - use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; - - use super::*; - - #[test] - fn basic() { - let r = ArcCell::new(Arc::new(0)); - assert_eq!(*r.get(), 0); - assert_eq!(*r.set(Arc::new(1)), 0); - assert_eq!(*r.get(), 1); - } - - #[test] - fn drop_runs() { - static DROPS: AtomicUsize = ATOMIC_USIZE_INIT; - - struct Foo; - - impl Drop for Foo { - fn drop(&mut self) { - DROPS.fetch_add(1, Ordering::SeqCst); - } - } - - let r = ArcCell::new(Arc::new(Foo)); - let _f = r.get(); - r.get(); - r.set(Arc::new(Foo)); - drop(_f); - assert_eq!(DROPS.load(Ordering::SeqCst), 1); - drop(r); - assert_eq!(DROPS.load(Ordering::SeqCst), 2); - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/atomic_option.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/atomic_option.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/atomic_option.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/atomic_option.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -use std::sync::atomic::{AtomicPtr, Ordering}; -use std::ptr; - -unsafe impl Send for AtomicOption {} -unsafe impl Sync for AtomicOption {} - -#[derive(Debug)] -pub struct AtomicOption { - inner: AtomicPtr, -} - -impl AtomicOption { - pub fn new() -> AtomicOption { - AtomicOption { inner: AtomicPtr::new(ptr::null_mut()) } - } - - fn swap_inner(&self, ptr: *mut T, order: Ordering) -> Option> { - let old = self.inner.swap(ptr, order); - if old.is_null() { - None - } else { - Some(unsafe { Box::from_raw(old) }) - } - } - - // allows re-use of allocation - pub fn swap_box(&self, t: Box, order: Ordering) -> Option> { - self.swap_inner(Box::into_raw(t), order) - } - - pub fn swap(&self, t: T, order: Ordering) -> Option { - self.swap_box(Box::new(t), order).map(|old| *old) - } - - pub fn take(&self, order: Ordering) -> Option { - self.swap_inner(ptr::null_mut(), order).map(|old| *old) - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/chase_lev.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/chase_lev.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/chase_lev.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/chase_lev.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,602 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A lock-free concurrent work-stealing deque -//! -//! This module contains a hybrid implementation of the Chase-Lev work stealing deque -//! described in ["Dynamic Circular Work-Stealing Deque"][chase_lev] and the improved version -//! described in ["Correct and Efficient Work-Stealing for Weak Memory Models"][weak_chase_lev]. -//! The implementation is heavily based on the pseudocode found in the papers. -//! -//! # Example -//! -//! ``` -//! use crossbeam::sync::chase_lev; -//! let (mut worker, stealer) = chase_lev::deque(); -//! -//! // Only the worker may push/try_pop -//! worker.push(1); -//! worker.try_pop(); -//! -//! // Stealers take data from the other end of the deque -//! worker.push(1); -//! stealer.steal(); -//! -//! // Stealers can be cloned to have many stealers stealing in parallel -//! worker.push(1); -//! let stealer2 = stealer.clone(); -//! stealer2.steal(); -//! ``` -//! -//! [chase_lev]: http://neteril.org/~jeremie/Dynamic_Circular_Work_Queue.pdf -//! [weak_chase_lev]: http://www.di.ens.fr/~zappa/readings/ppopp13.pdf - -use std::cell::UnsafeCell; -use std::fmt; -use std::mem; -use std::ptr; -use std::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst}; -use std::sync::atomic::{AtomicIsize, fence}; -use std::sync::Arc; - -use mem::epoch::{self, Atomic, Shared, Owned}; - -// Once the queue is less than 1/K full, then it will be downsized. Note that -// the deque requires that this number be less than 2. -const K: isize = 4; - -// Minimum number of bits that a buffer size should be. No buffer will resize to -// under this value, and all deques will initially contain a buffer of this -// size. -// -// The size in question is 1 << MIN_BITS -const MIN_BITS: u32 = 7; - -#[derive(Debug)] -struct Deque { - bottom: AtomicIsize, - top: AtomicIsize, - array: Atomic>, -} - -// FIXME: can these constraints be relaxed? -unsafe impl Send for Deque {} -unsafe impl Sync for Deque {} - -/// Worker half of the work-stealing deque. This worker has exclusive access to -/// one side of the deque, and uses `push` and `try_pop` method to manipulate it. -/// -/// There may only be one worker per deque, and operations on the worker -/// require mutable access to the worker itself. -#[derive(Debug)] -pub struct Worker { - deque: Arc>, -} - -/// The stealing half of the work-stealing deque. Stealers have access to the -/// opposite end of the deque from the worker, and they only have access to the -/// `steal` method. -/// -/// Stealers can be cloned to have more than one handle active at a time. -#[derive(Debug)] -pub struct Stealer { - deque: Arc>, -} - -/// When stealing some data, this is an enumeration of the possible outcomes. -#[derive(PartialEq, Eq, Debug)] -pub enum Steal { - /// The deque was empty at the time of stealing - Empty, - /// The stealer lost the race for stealing data, and a retry may return more - /// data. - Abort, - /// The stealer has successfully stolen some data. - Data(T), -} - -// An internal buffer used by the chase-lev deque. This structure is actually -// implemented as a circular buffer, and is used as the intermediate storage of -// the data in the deque. -// -// This Vec always has a length of 0, the backing buffer is just used by the -// code below. -struct Buffer { - storage: UnsafeCell>, - log_size: u32, -} - -impl fmt::Debug for Buffer { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Buffer {{ ... }}") - } -} - -impl Worker { - /// Pushes data onto the front of this work queue. - pub fn push(&mut self, t: T) { - unsafe { self.deque.push(t) } - } - - /// Pops data off the front of the work queue, returning `None` on an empty - /// queue. - pub fn try_pop(&mut self) -> Option { - unsafe { self.deque.try_pop() } - } -} - -impl Stealer { - /// Steals work off the end of the queue (opposite of the worker's end) - pub fn steal(&self) -> Steal { - self.deque.steal() - } -} - -impl Clone for Stealer { - fn clone(&self) -> Stealer { - Stealer { deque: self.deque.clone() } - } -} - -/// Creates a new empty deque -pub fn deque() -> (Worker, Stealer) { - let a = Arc::new(Deque::new()); - let b = a.clone(); - (Worker { deque: a }, Stealer { deque: b }) -} - -// Almost all of this code can be found directly in the paper so I'm not -// personally going to heavily comment what's going on here. - -impl Deque { - fn new() -> Deque { - let array = Atomic::null(); - array.store(Some(Owned::new(Buffer::new(MIN_BITS))), SeqCst); - Deque { - bottom: AtomicIsize::new(0), - top: AtomicIsize::new(0), - array: array, - } - } - - unsafe fn push(&self, data: T) { - let guard = epoch::pin(); - - let mut b = self.bottom.load(Relaxed); - let t = self.top.load(Acquire); - let mut a = self.array.load(Relaxed, &guard).unwrap(); - - let size = b - t; - if size >= (a.size() as isize) - 1 { - // You won't find this code in the chase-lev deque paper. This is - // alluded to in a small footnote, however. We always free a buffer - // when growing in order to prevent leaks. - a = self.swap_buffer(a, a.resize(b, t, 1), &guard); - - // reload the bottom counter, since swap_buffer modifies it. - b = self.bottom.load(Relaxed); - } - a.put(b, data); - fence(Release); - self.bottom.store(b + 1, Relaxed); - } - - unsafe fn try_pop(&self) -> Option { - let guard = epoch::pin(); - - let b = self.bottom.load(Relaxed) - 1; - let a = self.array.load(Relaxed, &guard).unwrap(); - self.bottom.store(b, Relaxed); - fence(SeqCst); // the store to bottom must occur before loading top. - let t = self.top.load(Relaxed); - - let size = b - t; - if size >= 0 { - // non-empty case - let mut data = Some(a.get(b)); - if size == 0 { - // last element in queue, check for races. - if self.top.compare_and_swap(t, t + 1, SeqCst) != t { - // lost the race. - mem::forget(data.take()); - } - - // set the queue to a canonically empty state. - self.bottom.store(b + 1, Relaxed); - } else { - self.maybe_shrink(b, t, &guard); - } - data - } else { - // empty queue. revert the decrement of "b" and try to shrink. - // - // the original chase_lev paper uses "t" here, but the new one uses "b + 1". - // don't worry, they're the same thing: pop and steal operations will never leave - // the top counter greater than the bottom counter. After we decrement "b" at - // the beginning of this function, the lowest possible value it could hold here is "t - 1". - // That's also the only value that could cause this branch to be taken. - self.bottom.store(b + 1, Relaxed); - None - } - } - - fn steal(&self) -> Steal { - let guard = epoch::pin(); - - let t = self.top.load(Acquire); - fence(SeqCst); // top must be loaded before bottom. - let b = self.bottom.load(Acquire); - - let size = b - t; - if size <= 0 { - return Steal::Empty - } - - unsafe { - // while the paper uses a "consume" ordering here, the closest thing we have - // available is Acquire, which is strictly stronger. - let a = self.array.load(Acquire, &guard).unwrap(); - let data = a.get(t); - // we may be racing against other steals and a pop. - if self.top.compare_and_swap(t, t + 1, SeqCst) == t { - Steal::Data(data) - } else { - mem::forget(data); // someone else stole this value - Steal::Abort - } - } - } - - // potentially shrink the array. This can be called only from the worker. - unsafe fn maybe_shrink(&self, b: isize, t: isize, guard: &epoch::Guard) { - let a = self.array.load(SeqCst, guard).unwrap(); - let size = b - t; - if size < (a.size() as isize) / K && size > (1 << MIN_BITS) { - self.swap_buffer(a, a.resize(b, t, -1), guard); - } - } - - // Helper routine not mentioned in the paper which is used in growing and - // shrinking buffers to swap in a new buffer into place. - // - // As a bit of a recap, stealers can continue using buffers after this - // method has called 'unlinked' on it. The continued usage is simply a read - // followed by a forget, but we must make sure that the memory can continue - // to be read after we flag this buffer for reclamation. All stealers, - // however, have their own epoch pinned during this time so the buffer will - // just naturally be free'd once all concurrent stealers have exited. - // - // This method may only be called safely from the workers due to the way it modifies - // the array pointer. - unsafe fn swap_buffer<'a>(&self, - old: Shared<'a, Buffer>, - buf: Buffer, - guard: &'a epoch::Guard) - -> Shared<'a, Buffer> { - let newbuf = Owned::new(buf); - let newbuf = self.array.store_and_ref(newbuf, Release, &guard); - guard.unlinked(old); - - newbuf - } -} - - -impl Drop for Deque { - fn drop(&mut self) { - let guard = epoch::pin(); - - // Arc enforces that we have truly exclusive access here. - - let t = self.top.load(Relaxed); - let b = self.bottom.load(Relaxed); - let a = self.array.swap(None, Relaxed, &guard).unwrap(); - // Free whatever is leftover in the dequeue, then free the backing - // memory itself - unsafe { - for i in t..b { - drop(a.get(i)); - } - guard.unlinked(a); - } - } -} - -impl Buffer { - fn new(log_size: u32) -> Buffer { - Buffer { - storage: UnsafeCell::new(Vec::with_capacity(1 << log_size)), - log_size: log_size, - } - } - - fn size(&self) -> usize { - unsafe { (*self.storage.get()).capacity() } - } - - fn mask(&self) -> isize { - unsafe { - ((*self.storage.get()).capacity() - 1) as isize - } - } - - unsafe fn elem(&self, i: isize) -> *mut T { - (*self.storage.get()).as_mut_ptr().offset(i & self.mask()) - } - - // This does not protect against loading duplicate values of the same cell, - // nor does this clear out the contents contained within. Hence, this is a - // very unsafe method which the caller needs to treat specially in case a - // race is lost. - unsafe fn get(&self, i: isize) -> T { - ptr::read(self.elem(i)) - } - - // Unsafe because this unsafely overwrites possibly uninitialized or - // initialized data. - unsafe fn put(&self, i: isize, t: T) { - ptr::write(self.elem(i), t); - } - - // Again, unsafe because this has incredibly dubious ownership violations. - // It is assumed that this buffer is immediately dropped. - unsafe fn resize(&self, b: isize, t: isize, delta: i32) -> Buffer { - let buf = Buffer::new(((self.log_size as i32) + delta) as u32); - for i in t..b { - buf.put(i, self.get(i)); - } - return buf; - } -} - -#[cfg(test)] -mod tests { - extern crate rand; - - use super::{deque, Worker, Stealer, Steal}; - - use std::thread; - use std::sync::Arc; - use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, - AtomicUsize, ATOMIC_USIZE_INIT}; - use std::sync::atomic::Ordering::SeqCst; - - use self::rand::Rng; - - #[test] - fn smoke() { - let (mut w, s) = deque(); - assert_eq!(w.try_pop(), None); - assert_eq!(s.steal(), Steal::Empty); - w.push(1); - assert_eq!(w.try_pop(), Some(1)); - w.push(1); - assert_eq!(s.steal(), Steal::Data(1)); - w.push(1); - assert_eq!(s.clone().steal(), Steal::Data(1)); - } - - #[test] - fn stealpush() { - static AMT: isize = 100000; - let (mut w, s) = deque(); - let t = thread::spawn(move || { - let mut left = AMT; - while left > 0 { - match s.steal() { - Steal::Data(i) => { - assert_eq!(i, 1); - left -= 1; - } - Steal::Abort | Steal::Empty => {} - } - } - }); - - for _ in 0..AMT { - w.push(1); - } - - t.join().unwrap(); - } - - #[test] - fn stealpush_large() { - static AMT: isize = 100000; - let (mut w, s) = deque(); - let t = thread::spawn(move || { - let mut left = AMT; - while left > 0 { - match s.steal() { - Steal::Data((1, 10)) => { left -= 1; } - Steal::Data(..) => panic!(), - Steal::Abort | Steal::Empty => {} - } - } - }); - - for _ in 0..AMT { - w.push((1, 10)); - } - - t.join().unwrap(); - } - - fn stampede(mut w: Worker>, - s: Stealer>, - nthreads: isize, - amt: usize) { - for _ in 0..amt { - w.push(Box::new(20)); - } - let remaining = Arc::new(AtomicUsize::new(amt)); - - let threads = (0..nthreads).map(|_| { - let remaining = remaining.clone(); - let s = s.clone(); - thread::spawn(move || { - while remaining.load(SeqCst) > 0 { - match s.steal() { - Steal::Data(val) => { - if *val == 20 { - remaining.fetch_sub(1, SeqCst); - } else { - panic!() - } - } - Steal::Abort | Steal::Empty => {} - } - } - }) - }).collect::>(); - - while remaining.load(SeqCst) > 0 { - if let Some(val) = w.try_pop() { - if *val == 20 { - remaining.fetch_sub(1, SeqCst); - } else { - panic!() - } - } - } - - for thread in threads.into_iter() { - thread.join().unwrap(); - } - } - - #[test] - fn run_stampede() { - let (w, s) = deque(); - stampede(w, s, 8, 10000); - } - - #[test] - fn many_stampede() { - static AMT: usize = 4; - let threads = (0..AMT).map(|_| { - let (w, s) = deque(); - thread::spawn(|| { - stampede(w, s, 4, 10000); - }) - }).collect::>(); - - for thread in threads.into_iter() { - thread.join().unwrap(); - } - } - - #[test] - fn stress() { - static AMT: isize = 100000; - static NTHREADS: isize = 8; - static DONE: AtomicBool = ATOMIC_BOOL_INIT; - static HITS: AtomicUsize = ATOMIC_USIZE_INIT; - let (mut w, s) = deque(); - - let threads = (0..NTHREADS).map(|_| { - let s = s.clone(); - thread::spawn(move || { - loop { - match s.steal() { - Steal::Data(2) => { HITS.fetch_add(1, SeqCst); } - Steal::Data(..) => panic!(), - _ if DONE.load(SeqCst) => break, - _ => {} - } - } - }) - }).collect::>(); - - let mut rng = rand::thread_rng(); - let mut expected = 0; - while expected < AMT { - if rng.gen_range(0, 3) == 2 { - match w.try_pop() { - None => {} - Some(2) => { HITS.fetch_add(1, SeqCst); }, - Some(_) => panic!(), - } - } else { - expected += 1; - w.push(2); - } - } - - while HITS.load(SeqCst) < AMT as usize { - match w.try_pop() { - None => {} - Some(2) => { HITS.fetch_add(1, SeqCst); }, - Some(_) => panic!(), - } - } - DONE.store(true, SeqCst); - - for thread in threads.into_iter() { - thread.join().unwrap(); - } - - assert_eq!(HITS.load(SeqCst), expected as usize); - } - - #[test] - fn no_starvation() { - static AMT: isize = 10000; - static NTHREADS: isize = 4; - static DONE: AtomicBool = ATOMIC_BOOL_INIT; - let (mut w, s) = deque(); - - let (threads, hits): (Vec<_>, Vec<_>) = (0..NTHREADS).map(|_| { - let s = s.clone(); - let ctr = Arc::new(AtomicUsize::new(0)); - let ctr2 = ctr.clone(); - (thread::spawn(move || { - loop { - match s.steal() { - Steal::Data((1, 2)) => { ctr.fetch_add(1, SeqCst); } - Steal::Data(..) => panic!(), - _ if DONE.load(SeqCst) => break, - _ => {} - } - } - }), ctr2) - }).unzip(); - - let mut rng = rand::thread_rng(); - let mut myhit = false; - 'outer: loop { - for _ in 0..rng.gen_range(0, AMT) { - if !myhit && rng.gen_range(0, 3) == 2 { - match w.try_pop() { - None => {} - Some((1, 2)) => myhit = true, - Some(_) => panic!(), - } - } else { - w.push((1, 2)); - } - } - - for slot in hits.iter() { - let amt = slot.load(SeqCst); - if amt == 0 { continue 'outer; } - } - if myhit { - break - } - } - - DONE.store(true, SeqCst); - - for thread in threads.into_iter() { - thread.join().unwrap(); - } - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/mod.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/mod.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -//! Synchronization primitives. - -pub use self::ms_queue::MsQueue; -pub use self::atomic_option::AtomicOption; -pub use self::treiber_stack::TreiberStack; -pub use self::seg_queue::SegQueue; -pub use self::arc_cell::ArcCell; - -mod atomic_option; -mod ms_queue; -mod treiber_stack; -mod seg_queue; -pub mod chase_lev; -mod arc_cell; diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/ms_queue.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/ms_queue.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/ms_queue.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/ms_queue.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,511 +0,0 @@ -use std::sync::atomic::Ordering::{Acquire, Release, Relaxed}; -use std::sync::atomic::AtomicBool; -use std::{ptr, mem}; -use std::thread::{self, Thread}; - -use mem::epoch::{self, Atomic, Owned, Shared}; -use mem::CachePadded; - -/// A Michael-Scott lock-free queue, with support for blocking `pop`s. -/// -/// Usable with any number of producers and consumers. -// The representation here is a singly-linked list, with a sentinel -// node at the front. In general the `tail` pointer may lag behind the -// actual tail. Non-sentinal nodes are either all `Data` or all -// `Blocked` (requests for data from blocked threads). -#[derive(Debug)] -pub struct MsQueue { - head: CachePadded>>, - tail: CachePadded>>, -} - -#[derive(Debug)] -struct Node { - payload: Payload, - next: Atomic>, -} - -#[derive(Debug)] -enum Payload { - /// A node with actual data that can be popped. - Data(T), - /// A node representing a blocked request for data. - Blocked(*mut Signal), -} - -/// A blocked request for data, which includes a slot to write the data. -#[derive(Debug)] -struct Signal { - /// Thread to unpark when data is ready. - thread: Thread, - /// The actual data, when available. - data: Option, - /// Is the data ready? Needed to cope with spurious wakeups. - ready: AtomicBool, -} - -impl Node { - fn is_data(&self) -> bool { - if let Payload::Data(_) = self.payload { true } else { false } - } -} - -// Any particular `T` should never accessed concurrently, so no need -// for Sync. -unsafe impl Sync for MsQueue {} -unsafe impl Send for MsQueue {} - -impl MsQueue { - /// Create a new, empty queue. - pub fn new() -> MsQueue { - let q = MsQueue { - head: CachePadded::new(Atomic::null()), - tail: CachePadded::new(Atomic::null()), - }; - let sentinel = Owned::new(Node { - payload: Payload::Data(unsafe { mem::uninitialized() }), - next: Atomic::null(), - }); - let guard = epoch::pin(); - let sentinel = q.head.store_and_ref(sentinel, Relaxed, &guard); - q.tail.store_shared(Some(sentinel), Relaxed); - q - } - - #[inline(always)] - /// Attempt to atomically place `n` into the `next` pointer of `onto`. - /// - /// If unsuccessful, returns ownership of `n`, possibly updating - /// the queue's `tail` pointer. - fn push_internal(&self, - guard: &epoch::Guard, - onto: Shared>, - n: Owned>) - -> Result<(), Owned>> - { - // is `onto` the actual tail? - if let Some(next) = onto.next.load(Acquire, guard) { - // if not, try to "help" by moving the tail pointer forward - self.tail.cas_shared(Some(onto), Some(next), Release); - Err(n) - } else { - // looks like the actual tail; attempt to link in `n` - onto.next.cas_and_ref(None, n, Release, guard).map(|shared| { - // try to move the tail pointer forward - self.tail.cas_shared(Some(onto), Some(shared), Release); - }) - } - } - - /// Add `t` to the back of the queue, possibly waking up threads - /// blocked on `pop`. - pub fn push(&self, t: T) { - /// We may or may not need to allocate a node; once we do, - /// we cache that allocation. - enum Cache { - Data(T), - Node(Owned>), - } - - impl Cache { - /// Extract the node if cached, or allocate if not. - fn into_node(self) -> Owned> { - match self { - Cache::Data(t) => { - Owned::new(Node { - payload: Payload::Data(t), - next: Atomic::null() - }) - } - Cache::Node(n) => n - } - } - - /// Extract the data from the cache, deallocating any cached node. - fn into_data(self) -> T { - match self { - Cache::Data(t) => t, - Cache::Node(node) => { - match node.into_inner().payload { - Payload::Data(t) => t, - _ => unreachable!(), - } - } - } - } - } - - let mut cache = Cache::Data(t); // don't allocate up front - let guard = epoch::pin(); - - loop { - // We push onto the tail, so we'll start optimistically by looking - // there first. - let tail = self.tail.load(Acquire, &guard).unwrap(); - - // Is the queue in Data mode (empty queues can be viewed as either mode)? - if tail.is_data() || - self.head.load(Relaxed, &guard).unwrap().as_raw() == tail.as_raw() - { - // Attempt to push onto the `tail` snapshot; fails if - // `tail.next` has changed, which will always be the case if the - // queue has transitioned to blocking mode. - match self.push_internal(&guard, tail, cache.into_node()) { - Ok(_) => return, - Err(n) => { - // replace the cache, retry whole thing - cache = Cache::Node(n) - } - } - } else { - // Queue is in blocking mode. Attempt to unblock a thread. - let head = self.head.load(Acquire, &guard).unwrap(); - // Get a handle on the first blocked node. Racy, so queue might - // be empty or in data mode by the time we see it. - let request = head.next.load(Acquire, &guard).and_then(|next| { - match next.payload { - Payload::Blocked(signal) => Some((next, signal)), - Payload::Data(_) => None, - } - }); - if let Some((blocked_node, signal)) = request { - // race to dequeue the node - if self.head.cas_shared(Some(head), Some(blocked_node), Release) { - unsafe { - // signal the thread - (*signal).data = Some(cache.into_data()); - (*signal).ready.store(true, Relaxed); - (*signal).thread.unpark(); - guard.unlinked(head); - return; - } - } - } - } - } - } - - #[inline(always)] - // Attempt to pop a data node. `Ok(None)` if queue is empty or in blocking - // mode; `Err(())` if lost race to pop. - fn pop_internal(&self, guard: &epoch::Guard) -> Result, ()> { - let head = self.head.load(Acquire, guard).unwrap(); - if let Some(next) = head.next.load(Acquire, guard) { - if let Payload::Data(ref t) = next.payload { - unsafe { - if self.head.cas_shared(Some(head), Some(next), Release) { - guard.unlinked(head); - Ok(Some(ptr::read(t))) - } else { - Err(()) - } - } - } else { - Ok(None) - } - } else { - Ok(None) - } - } - - /// Check if this queue is empty. - pub fn is_empty(&self) -> bool { - let guard = epoch::pin(); - let head = self.head.load(Acquire, &guard).unwrap(); - - if let Some(next) = head.next.load(Acquire, &guard) { - if let Payload::Data(_) = next.payload { - false - } else { - true - } - } else { - true - } - } - - /// Attempt to dequeue from the front. - /// - /// Returns `None` if the queue is observed to be empty. - pub fn try_pop(&self) -> Option { - let guard = epoch::pin(); - loop { - if let Ok(r) = self.pop_internal(&guard) { - return r; - } - } - } - - /// Dequeue an element from the front of the queue, blocking if the queue is - /// empty. - pub fn pop(&self) -> T { - let guard = epoch::pin(); - - // Fast path: keep retrying until we observe that the queue has no data, - // avoiding the allocation of a blocked node. - loop { - match self.pop_internal(&guard) { - Ok(Some(r)) => { - return r; - } - Ok(None) => { - break; - } - Err(()) => {} - } - } - - // The signal gets to live on the stack, since this stack frame will be - // blocked until receiving the signal. - let mut signal = Signal { - thread: thread::current(), - data: None, - ready: AtomicBool::new(false), - }; - - // Go ahead and allocate the blocked node; chances are, we'll need it. - let mut node = Owned::new(Node { - payload: Payload::Blocked(&mut signal), - next: Atomic::null(), - }); - - loop { - // try a normal pop - if let Ok(Some(r)) = self.pop_internal(&guard) { - return r; - } - - // At this point, we believe the queue is empty/blocked. - // Snapshot the tail, onto which we want to push a blocked node. - let tail = self.tail.load(Relaxed, &guard).unwrap(); - - // Double-check that we're in blocking mode - if tail.is_data() { - // The current tail is in data mode, so we probably need to abort. - // BUT, it might be the sentinel, so check for that first. - let head = self.head.load(Relaxed, &guard).unwrap(); - if tail.is_data() && tail.as_raw() != head.as_raw() { continue; } - } - - // At this point, the tail snapshot is either a blocked node deep in - // the queue, the sentinel, or no longer accessible from the queue. - // In *ALL* of these cases, if we succeed in pushing onto the - // snapshot, we know we are maintaining the core invariant: all - // reachable, non-sentinel nodes have the same payload mode, in this - // case, blocked. - match self.push_internal(&guard, tail, node) { - Ok(()) => { - while !signal.ready.load(Relaxed) { - thread::park(); - } - return signal.data.unwrap(); - } - Err(n) => { - node = n; - } - } - } - } -} - -#[cfg(test)] -mod test { - const CONC_COUNT: i64 = 1000000; - - use scope; - use super::*; - - #[test] - fn push_try_pop_1() { - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - q.push(37); - assert!(!q.is_empty()); - assert_eq!(q.try_pop(), Some(37)); - assert!(q.is_empty()); - } - - #[test] - fn push_try_pop_2() { - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - q.push(37); - q.push(48); - assert_eq!(q.try_pop(), Some(37)); - assert!(!q.is_empty()); - assert_eq!(q.try_pop(), Some(48)); - assert!(q.is_empty()); - } - - #[test] - fn push_try_pop_many_seq() { - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - for i in 0..200 { - q.push(i) - } - assert!(!q.is_empty()); - for i in 0..200 { - assert_eq!(q.try_pop(), Some(i)); - } - assert!(q.is_empty()); - } - - #[test] - fn push_pop_1() { - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - q.push(37); - assert!(!q.is_empty()); - assert_eq!(q.pop(), 37); - assert!(q.is_empty()); - } - - #[test] - fn push_pop_2() { - let q: MsQueue = MsQueue::new(); - q.push(37); - q.push(48); - assert_eq!(q.pop(), 37); - assert_eq!(q.pop(), 48); - } - - #[test] - fn push_pop_many_seq() { - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - for i in 0..200 { - q.push(i) - } - assert!(!q.is_empty()); - for i in 0..200 { - assert_eq!(q.pop(), i); - } - assert!(q.is_empty()); - } - - #[test] - fn push_try_pop_many_spsc() { - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - - scope(|scope| { - scope.spawn(|| { - let mut next = 0; - - while next < CONC_COUNT { - if let Some(elem) = q.try_pop() { - assert_eq!(elem, next); - next += 1; - } - } - }); - - for i in 0..CONC_COUNT { - q.push(i) - } - }); - } - - #[test] - fn push_try_pop_many_spmc() { - fn recv(_t: i32, q: &MsQueue) { - let mut cur = -1; - for _i in 0..CONC_COUNT { - if let Some(elem) = q.try_pop() { - assert!(elem > cur); - cur = elem; - - if cur == CONC_COUNT - 1 { break } - } - } - } - - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - let qr = &q; - scope(|scope| { - for i in 0..3 { - scope.spawn(move || recv(i, qr)); - } - - scope.spawn(|| { - for i in 0..CONC_COUNT { - q.push(i); - } - }) - }); - } - - #[test] - fn push_try_pop_many_mpmc() { - enum LR { Left(i64), Right(i64) } - - let q: MsQueue = MsQueue::new(); - assert!(q.is_empty()); - - scope(|scope| { - for _t in 0..2 { - scope.spawn(|| { - for i in CONC_COUNT-1..CONC_COUNT { - q.push(LR::Left(i)) - } - }); - scope.spawn(|| { - for i in CONC_COUNT-1..CONC_COUNT { - q.push(LR::Right(i)) - } - }); - scope.spawn(|| { - let mut vl = vec![]; - let mut vr = vec![]; - for _i in 0..CONC_COUNT { - match q.try_pop() { - Some(LR::Left(x)) => vl.push(x), - Some(LR::Right(x)) => vr.push(x), - _ => {} - } - } - - let mut vl2 = vl.clone(); - let mut vr2 = vr.clone(); - vl2.sort(); - vr2.sort(); - - assert_eq!(vl, vl2); - assert_eq!(vr, vr2); - }); - } - }); - } - - #[test] - fn push_pop_many_spsc() { - let q: MsQueue = MsQueue::new(); - - scope(|scope| { - scope.spawn(|| { - let mut next = 0; - while next < CONC_COUNT { - assert_eq!(q.pop(), next); - next += 1; - } - }); - - for i in 0..CONC_COUNT { - q.push(i) - } - }); - assert!(q.is_empty()); - } - - #[test] - fn is_empty_dont_pop() { - let q: MsQueue = MsQueue::new(); - q.push(20); - q.push(20); - assert!(!q.is_empty()); - assert!(!q.is_empty()); - assert!(q.try_pop().is_some()); - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/seg_queue.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/seg_queue.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/seg_queue.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/seg_queue.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,251 +0,0 @@ -use std::sync::atomic::Ordering::{Acquire, Release, Relaxed}; -use std::sync::atomic::{AtomicBool, AtomicUsize}; -use std::fmt; -use std::{ptr, mem}; -use std::cmp; -use std::cell::UnsafeCell; - -use mem::epoch::{self, Atomic, Owned}; - -const SEG_SIZE: usize = 32; - -/// A Michael-Scott queue that allocates "segments" (arrays of nodes) -/// for efficiency. -/// -/// Usable with any number of producers and consumers. -#[derive(Debug)] -pub struct SegQueue { - head: Atomic>, - tail: Atomic>, -} - -struct Segment { - low: AtomicUsize, - data: [UnsafeCell<(T, AtomicBool)>; SEG_SIZE], - high: AtomicUsize, - next: Atomic>, -} - -impl fmt::Debug for Segment { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Segment {{ ... }}") - } -} - -unsafe impl Sync for Segment {} - -impl Segment { - fn new() -> Segment { - let rqueue = Segment { - data: unsafe { mem::uninitialized() }, - low: AtomicUsize::new(0), - high: AtomicUsize::new(0), - next: Atomic::null(), - }; - for val in rqueue.data.iter() { - unsafe { - (*val.get()).1 = AtomicBool::new(false); - } - } - rqueue - } -} - -impl SegQueue { - /// Create a new, empty queue. - pub fn new() -> SegQueue { - let q = SegQueue { - head: Atomic::null(), - tail: Atomic::null(), - }; - let sentinel = Owned::new(Segment::new()); - let guard = epoch::pin(); - let sentinel = q.head.store_and_ref(sentinel, Relaxed, &guard); - q.tail.store_shared(Some(sentinel), Relaxed); - q - } - - /// Add `t` to the back of the queue. - pub fn push(&self, t: T) { - let guard = epoch::pin(); - loop { - let tail = self.tail.load(Acquire, &guard).unwrap(); - if tail.high.load(Relaxed) >= SEG_SIZE { continue } - let i = tail.high.fetch_add(1, Relaxed); - unsafe { - if i < SEG_SIZE { - let cell = (*tail).data.get_unchecked(i).get(); - ptr::write(&mut (*cell).0, t); - (*cell).1.store(true, Release); - - if i + 1 == SEG_SIZE { - let tail = tail.next.store_and_ref(Owned::new(Segment::new()), Release, &guard); - self.tail.store_shared(Some(tail), Release); - } - - return - } - } - } - } - - /// Attempt to dequeue from the front. - /// - /// Returns `None` if the queue is observed to be empty. - pub fn try_pop(&self) -> Option { - let guard = epoch::pin(); - loop { - let head = self.head.load(Acquire, &guard).unwrap(); - loop { - let low = head.low.load(Relaxed); - if low >= cmp::min(head.high.load(Relaxed), SEG_SIZE) { break } - if head.low.compare_and_swap(low, low+1, Relaxed) == low { - unsafe { - let cell = (*head).data.get_unchecked(low).get(); - loop { - if (*cell).1.load(Acquire) { break } - } - if low + 1 == SEG_SIZE { - loop { - if let Some(next) = head.next.load(Acquire, &guard) { - self.head.store_shared(Some(next), Release); - guard.unlinked(head); - break - } - } - } - return Some(ptr::read(&(*cell).0)) - } - } - } - if head.next.load(Relaxed, &guard).is_none() { return None } - } - } -} - -#[cfg(test)] -mod test { - const CONC_COUNT: i64 = 1000000; - - use scope; - use super::*; - - #[test] - fn push_pop_1() { - let q: SegQueue = SegQueue::new(); - q.push(37); - assert_eq!(q.try_pop(), Some(37)); - } - - #[test] - fn push_pop_2() { - let q: SegQueue = SegQueue::new(); - q.push(37); - q.push(48); - assert_eq!(q.try_pop(), Some(37)); - assert_eq!(q.try_pop(), Some(48)); - } - - #[test] - fn push_pop_many_seq() { - let q: SegQueue = SegQueue::new(); - for i in 0..200 { - q.push(i) - } - for i in 0..200 { - assert_eq!(q.try_pop(), Some(i)); - } - } - - #[test] - fn push_pop_many_spsc() { - let q: SegQueue = SegQueue::new(); - - scope(|scope| { - scope.spawn(|| { - let mut next = 0; - - while next < CONC_COUNT { - if let Some(elem) = q.try_pop() { - assert_eq!(elem, next); - next += 1; - } - } - }); - - for i in 0..CONC_COUNT { - q.push(i) - } - }); - } - - #[test] - fn push_pop_many_spmc() { - fn recv(_t: i32, q: &SegQueue) { - let mut cur = -1; - for _i in 0..CONC_COUNT { - if let Some(elem) = q.try_pop() { - assert!(elem > cur); - cur = elem; - - if cur == CONC_COUNT - 1 { break } - } - } - } - - let q: SegQueue = SegQueue::new(); - let qr = &q; - scope(|scope| { - for i in 0..3 { - scope.spawn(move || recv(i, qr)); - } - - scope.spawn(|| { - for i in 0..CONC_COUNT { - q.push(i); - } - }) - }); - } - - #[test] - fn push_pop_many_mpmc() { - enum LR { Left(i64), Right(i64) } - - let q: SegQueue = SegQueue::new(); - - scope(|scope| { - for _t in 0..2 { - scope.spawn(|| { - for i in CONC_COUNT-1..CONC_COUNT { - q.push(LR::Left(i)) - } - }); - scope.spawn(|| { - for i in CONC_COUNT-1..CONC_COUNT { - q.push(LR::Right(i)) - } - }); - scope.spawn(|| { - let mut vl = vec![]; - let mut vr = vec![]; - for _i in 0..CONC_COUNT { - match q.try_pop() { - Some(LR::Left(x)) => vl.push(x), - Some(LR::Right(x)) => vr.push(x), - _ => {} - } - } - - let mut vl2 = vl.clone(); - let mut vr2 = vr.clone(); - vl2.sort(); - vr2.sort(); - - assert_eq!(vl, vl2); - assert_eq!(vr, vr2); - }); - } - }); - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/treiber_stack.rs cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/treiber_stack.rs --- cargo-0.25.0/vendor/crossbeam-0.2.12/src/sync/treiber_stack.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/src/sync/treiber_stack.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,98 +0,0 @@ -use std::sync::atomic::Ordering::{Acquire, Release, Relaxed}; -use std::ptr; - -use mem::epoch::{self, Atomic, Owned}; - -/// Treiber's lock-free stack. -/// -/// Usable with any number of producers and consumers. -#[derive(Debug)] -pub struct TreiberStack { - head: Atomic>, -} - -#[derive(Debug)] -struct Node { - data: T, - next: Atomic>, -} - -impl TreiberStack { - /// Create a new, empty stack. - pub fn new() -> TreiberStack { - TreiberStack { head: Atomic::null() } - } - - /// Push `t` on top of the stack. - pub fn push(&self, t: T) { - let mut n = Owned::new(Node { - data: t, - next: Atomic::null(), - }); - let guard = epoch::pin(); - loop { - let head = self.head.load(Relaxed, &guard); - n.next.store_shared(head, Relaxed); - match self.head.cas_and_ref(head, n, Release, &guard) { - Ok(_) => break, - Err(owned) => n = owned, - } - } - } - - /// Attempt to pop the top element of the stack. - /// **Deprecated method**, use try_pop - /// - /// Returns `None` if the stack is observed to be empty. - #[cfg_attr(any(feature="beta", feature="nightly"), deprecated(note="The pop method has been renamed to try_pop for consistency with other collections."))] - pub fn pop(&self) -> Option { - self.try_pop() - } - - /// Attempt to pop the top element of the stack. - /// - /// Returns `None` if the stack is observed to be empty. - pub fn try_pop(&self) -> Option { - let guard = epoch::pin(); - loop { - match self.head.load(Acquire, &guard) { - Some(head) => { - let next = head.next.load(Relaxed, &guard); - if self.head.cas_shared(Some(head), next, Release) { - unsafe { - guard.unlinked(head); - return Some(ptr::read(&(*head).data)); - } - } - } - None => return None, - } - } - } - - /// Check if this queue is empty. - pub fn is_empty(&self) -> bool { - let guard = epoch::pin(); - self.head.load(Acquire, &guard).is_none() - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn is_empty() { - let q: TreiberStack = TreiberStack::new(); - assert!(q.is_empty()); - q.push(20); - q.push(20); - assert!(!q.is_empty()); - assert!(!q.is_empty()); - assert!(q.try_pop().is_some()); - assert!(q.try_pop().is_some()); - assert!(q.is_empty()); - q.push(25); - assert!(!q.is_empty()); - } -} diff -Nru cargo-0.25.0/vendor/crossbeam-0.2.12/.travis.yml cargo-0.26.0/vendor/crossbeam-0.2.12/.travis.yml --- cargo-0.25.0/vendor/crossbeam-0.2.12/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crossbeam-0.2.12/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -language: rust -# necessary for `travis-cargo coveralls --no-sudo` -addons: - apt: - packages: - - libcurl4-openssl-dev - - libelf-dev - - libdw-dev - -# run builds for all the trains (and more) -rust: - - nightly - - beta - - stable - -# load travis-cargo -before_script: - - | - pip install 'travis-cargo<0.2' --user && - export PATH=$HOME/.local/bin:$PATH - -# the main build -script: - - | - travis-cargo build && - travis-cargo test && - travis-cargo test -- --release && - travis-cargo run -- --bin bench --release && - travis-cargo --only stable doc -env: - global: - # override the default `--features unstable` used for the nightly branch (optional) - - TRAVIS_CARGO_NIGHTLY_FEATURE=nightly -notifications: - email: - on_success: never diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.0/.cargo-checksum.json cargo-0.26.0/vendor/crypto-hash-0.3.0/.cargo-checksum.json --- cargo-0.25.0/vendor/crypto-hash-0.3.0/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"34903878eec1694faf53cae8473a088df333181de421d4d3d48061d6559fe602"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.0/Cargo.toml cargo-0.26.0/vendor/crypto-hash-0.3.0/Cargo.toml --- cargo-0.25.0/vendor/crypto-hash-0.3.0/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -[package] -name = "crypto-hash" -version = "0.3.0" -authors = ["Mark Lee"] -description = "A wrapper for OS-level cryptographic hash functions" -documentation = "https://docs.rs/crypto-hash" -repository = "https://github.com/malept/crypto-hash" -readme = "README.md" -keywords = ["crypto", "hash", "digest"] -license = "MIT" -exclude = [ - ".*.yml", - "ci/*" -] - -[badges] -travis-ci = { repository = "malept/crypto-hash" } -appveyor = { repository = "malept/crypto-hash" } - -[dependencies] -hex = "0.2" - -[target.'cfg(target_os = "macos")'.dependencies] -commoncrypto = "0.2" - -[target.'cfg(target_os = "windows")'.dependencies] -advapi32-sys = "0.2" -winapi = "0.2" - -[target.'cfg(not(any(target_os = "windows", target_os = "macos")))'.dependencies] -openssl = "0.9" diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.0/CONTRIBUTING.md cargo-0.26.0/vendor/crypto-hash-0.3.0/CONTRIBUTING.md --- cargo-0.25.0/vendor/crypto-hash-0.3.0/CONTRIBUTING.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.0/CONTRIBUTING.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -# Contributing to `crypto-hash` - -`crypto-hash` is a part of the Rust ecosystem. As such, all contributions to this project follow the -[Rust language's code of conduct](https://www.rust-lang.org/conduct.html) where appropriate. - -This project is hosted at [GitHub](https://github.com/malept/crypto-hash). Both pull requests and -issues of many different kinds are accepted. - -## Filing Issues - -Issues include bugs, questions, feedback, and feature requests. Before you file a new issue, please -make sure that your issue has not already been filed by someone else. - -### Filing Bugs - -When filing a bug, please include the following information: - -* Operating system and version. If on Linux, please also include the distribution name. -* System architecture. Examples include: x86-64, x86, and ARMv7. -* Rust version that compiled `crypto-hash`. -* The version (and/or git revision) of `crypto-hash`. -* A detailed list of steps to reproduce the bug. A minimal testcase would be very helpful, - if possible. -* If there any any error messages in the console, copying them in the bug summary will be - very helpful. - -## Adding a new implementation - -If you are requesting or adding a new library source for hash algorithms, please make sure that it -supports all of the existing algorithms. For example, while the creator of this project supports the -efforts of the team writing LibreSSL, it does not support the MD5 algorithm. - -## Adding a new hash algorithm - -If you are requesting or adding a wrapper for a new hash algorithm, please make sure that it is -available in all of the supported implementations listed in the README. - -## Filing Pull Requests - -Here are some things to keep in mind as you file a pull request to fix a bug, add a new feature, -etc.: - -* Travis CI (for Linux and OS X) and AppVeyor (for Windows) are used to make sure that the project - builds as expected on the supported platforms, using the current stable and beta versions of Rust. - Make sure the testsuite passes locally by running `cargo test`. -* Unless it's impractical, please write tests for your changes. This will help spot regressions - much easier. -* If your PR changes the behavior of an existing feature, or adds a new feature, please add/edit - the `rustdoc` inline documentation. -* Please ensure that your changes follow the [rustfmt](https://github.com/rust-lang-nursery/rustfmt) - coding standard, and do not produce any warnings when running the - [clippy](https://github.com/Manishearth/rust-clippy) linter. -* If you are contributing a nontrivial change, please add an entry to `NEWS.md`. The format is - similar to the one described at [Keep a Changelog](http://keepachangelog.com/). -* Please make sure your commits are rebased onto the latest commit in the master branch, and that - you limit/squash the number of commits created to a "feature"-level. For instance: - -bad: - -``` -commit 1: add foo algorithm -commit 2: run rustfmt -commit 3: add test -commit 4: add docs -commit 5: add bar -commit 6: add test + docs -``` - -good: - -``` -commit 1: add foo algorithm -commit 2: add bar -``` - -If you are continuing the work of another person's PR and need to rebase/squash, please retain the -attribution of the original author(s) and continue the work in subsequent commits. diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.0/LICENSE cargo-0.26.0/vendor/crypto-hash-0.3.0/LICENSE --- cargo-0.25.0/vendor/crypto-hash-0.3.0/LICENSE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.0/LICENSE 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -Copyright (c) 2015, 2016 Mark Lee - -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. diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.0/Makefile cargo-0.26.0/vendor/crypto-hash-0.3.0/Makefile --- cargo-0.25.0/vendor/crypto-hash-0.3.0/Makefile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.0/Makefile 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -CARGO ?= cargo -CARGO_BUILD_TEST = $(CARGO) test --no-run -KCOV ?= kcov -TEST_APP = debug/crypto_hash-* -WIN_TARGET = x86_64-pc-windows-gnu - -build-test: - $(CARGO_BUILD_TEST) - -check-i686: - PKG_CONFIG_LIBDIR=/usr/lib/i386-linux-gnu/pkgconfig \ - PKG_CONFIG_ALLOW_CROSS=1 \ - $(CARGO) test --target i686-unknown-linux-gnu --verbose - -check-wine64: - $(CARGO_BUILD_TEST) --target $(WIN_TARGET) - WINEPREFIX=$(HOME)/.local/share/wineprefixes/wine64 wine64 target/$(WIN_TARGET)/$(TEST_APP) - -cov: build-test - $(KCOV) --exclude-pattern=/.multirust,test.rs target/cov target/$(TEST_APP) - -debug: build-test - rust-gdb target/$(TEST_APP) - -fmt: - $(CARGO) fmt - -lint: - $(CARGO) clippy --features=lint -- -Wclippy-pedantic diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.0/NEWS.md cargo-0.26.0/vendor/crypto-hash-0.3.0/NEWS.md --- cargo-0.25.0/vendor/crypto-hash-0.3.0/NEWS.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.0/NEWS.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -# Changes by Version - -## Unreleased - -## [0.3.0] - 2017-06-18 - -### Changed - -* Upgrade to `commoncrypto` 0.2.x -* Function signatures for `digest` and `hex_digest` changed to use `&[u8]`, per Clippy - -## [0.2.1] - 2016-12-12 - -### Changed - -* Move CommonCrypto implementation to its own crate - -## [0.2.0] - 2016-11-06 - -### Added - -* SHA-1 algorithm - -### Changed - -* Upgrade rust-openssl to 0.9 - -## [0.1.0] - 2016-06-26 - -This release signifies the minimum amount of algorithms and implementations necessary for -[HTTP digest authentication](https://tools.ietf.org/html/rfc7616). - -### Added - -Algorithms: - -* MD5 -* SHA256 -* SHA512 - -Implementations: - -* CommonCrypto (OS X) -* CryptoAPI (Windows) -* OpenSSL (Linux/BSD/etc.) - -[0.2.1]: https://github.com/malept/crypto-hash/compare/v0.2.0...v0.2.1 -[0.2.0]: https://github.com/malept/crypto-hash/compare/v0.1.0...v0.2.0 -[0.1.0]: https://github.com/malept/crypto-hash/releases/tag/v0.1.0 diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.0/README.md cargo-0.26.0/vendor/crypto-hash-0.3.0/README.md --- cargo-0.25.0/vendor/crypto-hash-0.3.0/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.0/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -# `crypto-hash` - -[![Linux/OS X Status](https://travis-ci.org/malept/crypto-hash.svg?branch=master)](https://travis-ci.org/malept/crypto-hash) -[![Windows status](https://ci.appveyor.com/api/projects/status/xwc9nb4633b5n67r?svg=true)](https://ci.appveyor.com/project/malept/crypto-hash) -[![Crates.io](https://img.shields.io/crates/v/crypto-hash.svg?maxAge=2592000)](https://crates.io/crates/crypto-hash) - -`crypto-hash` is a Rust wrapper around OS-level implementations of cryptographic hash functions. - -The purpose of this crate is to provide access to hash algorithms with as few dependencies as -possible. This means that when possible, the library uses the hashing functions that are provided by -the given operating system's bundled cryptographic libraries. - -## Supported Implementations - -By operating system: - -* Windows: CryptoAPI -* OS X: [CommonCrypto](https://crates.io/crates/commoncrypto) -* Linux/BSD/etc.: [OpenSSL](https://crates.io/crates/openssl) - -## Supported Algorithms - -* MD5 -* SHA1 -* SHA256 -* SHA512 - -## Usage - -Add `crypto-hash` to your project's `Cargo.toml`. For more details, consult the -[Cargo guide](http://doc.crates.io/guide.html#adding-dependencies). - -Example: - -```rust -use crypto_hash::{Algorithm, hex_digest}; - -let digest = hex_digest(Algorithm::SHA256, b"crypto-hash".to_vec()); -``` - -For more examples, consult the [documentation](https://malept.github.io/crypto-hash/). - -## [Release Notes](https://github.com/malept/crypto-hash/blob/master/NEWS.md) - -## [Contributing](https://github.com/malept/crypto-hash/blob/master/CONTRIBUTING.md) - -## Acknowledgements - -This crate was inspired by [rust-native-tls](https://github.com/sfackler/rust-native-tls) and -[crypto-bench](https://github.com/briansmith/crypto-bench). - -## Legal - -`crypto-hash` is copyrighted under the terms of the MIT license. See LICENSE for details. diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.0/src/imp/commoncrypto.rs cargo-0.26.0/vendor/crypto-hash-0.3.0/src/imp/commoncrypto.rs --- cargo-0.25.0/vendor/crypto-hash-0.3.0/src/imp/commoncrypto.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.0/src/imp/commoncrypto.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,81 +0,0 @@ -// Copyright (c) 2016 Mark Lee -// -// 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. - -//! A cryptographic hash generator dependent upon OSX's `CommonCrypto`. - -use commoncrypto::hash; -use std::io; -use super::Algorithm; - -/// Generator of digests using a cryptographic hash function. -/// -/// # Examples -/// -/// ```rust -/// use crypto_hash::{Algorithm, Hasher}; -/// use std::io::Write; -/// -/// let mut hasher = Hasher::new(Algorithm::SHA256); -/// hasher.write_all(b"crypto"); -/// hasher.write_all(b"-"); -/// hasher.write_all(b"hash"); -/// let result = hasher.finish(); -/// let expected = -/// b"\xfd\x1a\xfb`\"\xcdMG\xc8\x90\x96\x1cS9(\xea\xcf\xe8!\x9f\x1b%$\xf7\xfb*a\x84}\xdf\x8c'" -/// .to_vec(); -/// assert_eq!(expected, result) -/// ``` -#[derive(Debug)] -pub struct Hasher(hash::Hasher); - -impl Hasher { - /// Create a new `Hasher` for the given `Algorithm`. - pub fn new(algorithm: Algorithm) -> Hasher { - let cc_algorithm = match algorithm { - Algorithm::MD5 => hash::CCDigestAlgorithm::kCCDigestMD5, - Algorithm::SHA1 => hash::CCDigestAlgorithm::kCCDigestSHA1, - Algorithm::SHA256 => hash::CCDigestAlgorithm::kCCDigestSHA256, - Algorithm::SHA512 => hash::CCDigestAlgorithm::kCCDigestSHA512, - }; - - Hasher(hash::Hasher::new(cc_algorithm)) - } - - /// Generate a digest from the data written to the `Hasher`. - pub fn finish(&mut self) -> Vec { - let Hasher(ref mut hasher) = *self; - match hasher.finish() { - Ok(digest) => digest, - Err(error) => panic!("CommonCrypto error: {}", error), - } - } -} - -impl io::Write for Hasher { - fn write(&mut self, buf: &[u8]) -> io::Result { - let Hasher(ref mut hasher) = *self; - hasher.write(buf) - } - - fn flush(&mut self) -> io::Result<()> { - let Hasher(ref mut hasher) = *self; - hasher.flush() - } -} diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.0/src/imp/cryptoapi.rs cargo-0.26.0/vendor/crypto-hash-0.3.0/src/imp/cryptoapi.rs --- cargo-0.25.0/vendor/crypto-hash-0.3.0/src/imp/cryptoapi.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.0/src/imp/cryptoapi.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,154 +0,0 @@ -// Copyright (c) 2016 Mark Lee -// -// 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. - -//! A cryptographic hash generator dependent upon Windows's `CryptoAPI`. -//! -//! Originally based on: -//! https://github.com/rust-lang/cargo/blob/0.10.0/src/cargo/util/sha256.rs -//! which is copyright (c) 2014 The Rust Project Developers under the MIT license. - -use advapi32::{CryptAcquireContextW, CryptCreateHash, CryptDestroyHash, CryptGetHashParam, - CryptHashData, CryptReleaseContext}; -use std::io; -use std::ptr; -use super::Algorithm; -use winapi::{CALG_MD5, CALG_SHA1, CALG_SHA_256, CALG_SHA_512, CRYPT_SILENT, CRYPT_VERIFYCONTEXT, - DWORD, HCRYPTHASH, HCRYPTPROV, HP_HASHVAL, PROV_RSA_AES}; - -macro_rules! call { - ($e: expr) => ({ - if $e == 0 { - panic!("failed {}: {}", stringify!($e), io::Error::last_os_error()) - } - }) -} - -macro_rules! finish_algorithm { - ($func_name: ident, $size: ident) => { - fn $func_name(&mut self) -> Vec { - let mut len = $size as u32; - let mut hash = [0u8; $size]; - call!(unsafe { - CryptGetHashParam(self.hcrypthash, HP_HASHVAL, hash.as_mut_ptr(), &mut len, 0) - }); - assert_eq!(len as usize, hash.len()); - hash.to_vec() - } - } -} - -const MD5_LENGTH: usize = 16; -const SHA1_LENGTH: usize = 20; -const SHA256_LENGTH: usize = 32; -const SHA512_LENGTH: usize = 64; - -/// Generator of digests using a cryptographic hash function. -/// -/// # Examples -/// -/// ```rust -/// use crypto_hash::{Algorithm, Hasher}; -/// use std::io::Write; -/// -/// let mut hasher = Hasher::new(Algorithm::SHA256); -/// hasher.write_all(b"crypto"); -/// hasher.write_all(b"-"); -/// hasher.write_all(b"hash"); -/// let result = hasher.finish(); -/// let expected = -/// b"\xfd\x1a\xfb`\"\xcdMG\xc8\x90\x96\x1cS9(\xea\xcf\xe8!\x9f\x1b%$\xf7\xfb*a\x84}\xdf\x8c'" -/// .to_vec(); -/// assert_eq!(expected, result) -/// ``` -pub struct Hasher { - algorithm: Algorithm, - hcryptprov: HCRYPTPROV, - hcrypthash: HCRYPTHASH, -} - -impl Hasher { - /// Create a new `Hasher` for the given `Algorithm`. - pub fn new(algorithm: Algorithm) -> Hasher { - let mut hcp = 0; - call!(unsafe { - CryptAcquireContextW(&mut hcp, - ptr::null(), - ptr::null(), - PROV_RSA_AES, - CRYPT_VERIFYCONTEXT | CRYPT_SILENT) - }); - - let hash_type = match algorithm { - Algorithm::MD5 => CALG_MD5, - Algorithm::SHA1 => CALG_SHA1, - Algorithm::SHA256 => CALG_SHA_256, - Algorithm::SHA512 => CALG_SHA_512, - }; - - let mut ret = Hasher { - algorithm: algorithm, - hcryptprov: hcp, - hcrypthash: 0, - }; - - call!(unsafe { CryptCreateHash(ret.hcryptprov, hash_type, 0, 0, &mut ret.hcrypthash) }); - ret - } - - /// Generate a digest from the data written to the `Hasher`. - pub fn finish(&mut self) -> Vec { - match self.algorithm { - Algorithm::MD5 => self.finish_md5(), - Algorithm::SHA1 => self.finish_sha1(), - Algorithm::SHA256 => self.finish_sha256(), - Algorithm::SHA512 => self.finish_sha512(), - } - } - - finish_algorithm!(finish_md5, MD5_LENGTH); - finish_algorithm!(finish_sha1, SHA1_LENGTH); - finish_algorithm!(finish_sha256, SHA256_LENGTH); - finish_algorithm!(finish_sha512, SHA512_LENGTH); -} - -impl io::Write for Hasher { - fn write(&mut self, buf: &[u8]) -> io::Result { - call!(unsafe { - CryptHashData(self.hcrypthash, - buf.as_ptr() as *mut _, - buf.len() as DWORD, - 0) - }); - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -impl Drop for Hasher { - fn drop(&mut self) { - if self.hcrypthash != 0 { - call!(unsafe { CryptDestroyHash(self.hcrypthash) }); - } - call!(unsafe { CryptReleaseContext(self.hcryptprov, 0) }); - } -} diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.0/src/imp/openssl.rs cargo-0.26.0/vendor/crypto-hash-0.3.0/src/imp/openssl.rs --- cargo-0.25.0/vendor/crypto-hash-0.3.0/src/imp/openssl.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.0/src/imp/openssl.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,85 +0,0 @@ -// Copyright (c) 2015, 2016 Mark Lee -// -// 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. - -//! A cryptographic hash digest generator dependent upon `OpenSSL`. - -#![warn(missing_docs)] - -use openssl::hash; -use std::io; -use super::Algorithm; - -/// Generator of digests using a cryptographic hash function. -/// -/// # Examples -/// -/// ```rust -/// use crypto_hash::{Algorithm, Hasher}; -/// use std::io::Write; -/// -/// let mut hasher = Hasher::new(Algorithm::SHA256); -/// hasher.write_all(b"crypto"); -/// hasher.write_all(b"-"); -/// hasher.write_all(b"hash"); -/// let result = hasher.finish(); -/// let expected = -/// b"\xfd\x1a\xfb`\"\xcdMG\xc8\x90\x96\x1cS9(\xea\xcf\xe8!\x9f\x1b%$\xf7\xfb*a\x84}\xdf\x8c'" -/// .to_vec(); -/// assert_eq!(expected, result) -/// ``` -pub struct Hasher(hash::Hasher); - -impl Hasher { - /// Create a new `Hasher` for the given `Algorithm`. - pub fn new(algorithm: Algorithm) -> Hasher { - let hash_type = match algorithm { - Algorithm::MD5 => hash::MessageDigest::md5(), - Algorithm::SHA1 => hash::MessageDigest::sha1(), - Algorithm::SHA256 => hash::MessageDigest::sha256(), - Algorithm::SHA512 => hash::MessageDigest::sha512(), - }; - - match hash::Hasher::new(hash_type) { - Ok(hasher) => Hasher(hasher), - Err(error_stack) => panic!("OpenSSL error(s): {}", error_stack), - } - } - - /// Generate a digest from the data written to the `Hasher`. - pub fn finish(&mut self) -> Vec { - let Hasher(ref mut hasher) = *self; - match hasher.finish2() { - Ok(digest) => digest.to_vec(), - Err(error_stack) => panic!("OpenSSL error(s): {}", error_stack), - } - } -} - -impl io::Write for Hasher { - fn write(&mut self, buf: &[u8]) -> io::Result { - let Hasher(ref mut hasher) = *self; - hasher.write(buf) - } - - fn flush(&mut self) -> io::Result<()> { - let Hasher(ref mut hasher) = *self; - hasher.flush() - } -} diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.0/src/lib.rs cargo-0.26.0/vendor/crypto-hash-0.3.0/src/lib.rs --- cargo-0.25.0/vendor/crypto-hash-0.3.0/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,122 +0,0 @@ -// Copyright (c) 2015, 2016, 2017 Mark Lee -// -// 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. - -//! A set of [cryptographic hash -//! functions](https://en.wikipedia.org/wiki/Cryptographic_hash_function) provided by the operating -//! system, when available. -//! -//! The purpose of this crate is to provide access to hash algorithms with as few dependencies as -//! possible. This means that when possible, the library uses the hashing functions that are -//! provided by the given operating system's bundled cryptographic libraries. -//! -//! # Supported Implementations -//! -//! By operating system: -//! -//! * Windows: `CryptoAPI` -//! * Mac OS X: `CommonCrypto` -//! * Linux/BSD/etc.: `OpenSSL` -//! -//! # Supported Algorithms -//! -//! * MD5 -//! * SHA1 -//! * SHA256 -//! * SHA512 - -#![warn(missing_docs)] - -#[cfg(target_os = "windows")] -extern crate advapi32; -#[cfg(target_os = "macos")] -extern crate commoncrypto; -extern crate hex; -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -extern crate openssl; -#[cfg(target_os = "windows")] -extern crate winapi; - -use hex::ToHex; -use std::io::Write; - -#[cfg(target_os = "macos")] -#[path = "imp/commoncrypto.rs"] -mod imp; -#[cfg(target_os = "windows")] -#[path = "imp/cryptoapi.rs"] -mod imp; -#[cfg(not(any(target_os = "macos", target_os = "windows")))] -#[path = "imp/openssl.rs"] -mod imp; - -mod test; - -pub use imp::Hasher; - -/// Available cryptographic hash functions. -#[derive(Clone, Debug)] -pub enum Algorithm { - /// Popular message digest algorithm, only available for backwards compatibility purposes. - MD5, - /// SHA-1 algorithm from NIST FIPS, only available for backwards compatibility purposes. - SHA1, - /// SHA-2 family algorithm (256 bits). - SHA256, - /// SHA-2 family algorithm (512 bits). - SHA512, -} - -/// Helper function for `Hasher` which generates a cryptographic digest from the given -/// data and algorithm. -/// -/// # Examples -/// -/// ```rust -/// use crypto_hash::{Algorithm, digest}; -/// -/// let data = b"crypto-hash"; -/// let result = digest(Algorithm::SHA256, data); -/// let expected = -/// b"\xfd\x1a\xfb`\"\xcdMG\xc8\x90\x96\x1cS9(\xea\xcf\xe8!\x9f\x1b%$\xf7\xfb*a\x84}\xdf\x8c'" -/// .to_vec(); -/// assert_eq!(expected, result) -/// ``` -pub fn digest(algorithm: Algorithm, data: &[u8]) -> Vec { - let mut hasher = imp::Hasher::new(algorithm); - hasher.write_all(data).expect("Could not write hash data"); - hasher.finish() -} - -/// Helper function for `Hasher` which generates a cryptographic digest serialized in -/// hexadecimal from the given data and algorithm. -/// -/// # Examples -/// -/// ```rust -/// use crypto_hash::{Algorithm, hex_digest}; -/// -/// let data = b"crypto-hash"; -/// let result = hex_digest(Algorithm::SHA256, data); -/// let expected = "fd1afb6022cd4d47c890961c533928eacfe8219f1b2524f7fb2a61847ddf8c27"; -/// assert_eq!(expected, result) -/// ``` -pub fn hex_digest(algorithm: Algorithm, data: &[u8]) -> String { - digest(algorithm, data).to_hex() -} diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.0/src/test.rs cargo-0.26.0/vendor/crypto-hash-0.3.0/src/test.rs --- cargo-0.25.0/vendor/crypto-hash-0.3.0/src/test.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.0/src/test.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -// Copyright (c) 2016, 2017 Mark Lee -// -// 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. - -#![cfg(test)] - -use hex::ToHex; -use std::io::Write; -use super::{Algorithm, Hasher, hex_digest}; - -// From Wikipedia -const MD5_EMPTY_STRING: &'static str = "d41d8cd98f00b204e9800998ecf8427e"; -const SHA1_EMPTY_STRING: &'static str = "da39a3ee5e6b4b0d3255bfef95601890afd80709"; -const SHA256_EMPTY_STRING: &'static str = concat!("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649", - "b934ca495991b7852b855"); -const SHA512_EMPTY_STRING: &'static str = concat!("cf83e1357eefb8bdf1542850d66d8007d620e4050b5", - "715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318", - "d2877eec2f63b931bd47417a81a538327af927da3e"); -const TO_HASH: &'static str = "The quick brown fox jumps over the lazy dog"; -const TO_HASH_MD5: &'static str = "9e107d9d372bb6826bd81d3542a419d6"; - -#[test] -fn md5_empty_string() { - assert_hex_hashed_empty_string(Algorithm::MD5, MD5_EMPTY_STRING) -} - -#[test] -fn sha1_empty_string() { - assert_hex_hashed_empty_string(Algorithm::SHA1, SHA1_EMPTY_STRING) -} - -#[test] -fn sha256_empty_string() { - // From Wikipedia - assert_hex_hashed_empty_string(Algorithm::SHA256, SHA256_EMPTY_STRING) -} - -#[test] -fn sha512_empty_string() { - assert_hex_hashed_empty_string(Algorithm::SHA512, SHA512_EMPTY_STRING) -} - -#[test] -fn hasher_sans_write() { - let mut hasher = Hasher::new(Algorithm::MD5); - let actual = hasher.finish().to_hex(); - assert_eq!(MD5_EMPTY_STRING, actual) -} - -#[test] -fn hasher_with_write() { - let mut hasher = Hasher::new(Algorithm::MD5); - hasher - .write_all(TO_HASH.as_bytes()) - .expect("Could not write to hasher"); - let actual = hasher.finish().to_hex(); - assert_eq!(TO_HASH_MD5, actual) -} - -fn assert_hex_hashed_empty_string(algorithm: Algorithm, expected: &str) { - let vec = vec![]; - assert_eq!(expected, hex_digest(algorithm, vec.as_slice()).as_str()) -} diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.1/.cargo-checksum.json cargo-0.26.0/vendor/crypto-hash-0.3.1/.cargo-checksum.json --- cargo-0.25.0/vendor/crypto-hash-0.3.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.1/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"09de9ee0fc255ace04c7fa0763c9395a945c37c8292bb554f8d48361d1dcf1b4"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.1/Cargo.toml cargo-0.26.0/vendor/crypto-hash-0.3.1/Cargo.toml --- cargo-0.25.0/vendor/crypto-hash-0.3.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.1/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,37 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "crypto-hash" +version = "0.3.1" +authors = ["Mark Lee"] +exclude = [".*.yml", "ci/*"] +description = "A wrapper for OS-level cryptographic hash functions" +documentation = "https://docs.rs/crypto-hash" +readme = "README.md" +keywords = ["crypto", "hash", "digest"] +license = "MIT" +repository = "https://github.com/malept/crypto-hash" +[dependencies.hex] +version = "0.3" +[target."cfg(not(any(target_os = \"windows\", target_os = \"macos\")))".dependencies.openssl] +version = "0.10" +[target."cfg(target_os = \"macos\")".dependencies.commoncrypto] +version = "0.2" +[target."cfg(target_os = \"windows\")".dependencies.winapi] +version = "0.3" +features = ["minwindef", "wincrypt"] +[badges.appveyor] +repository = "malept/crypto-hash" + +[badges.travis-ci] +repository = "malept/crypto-hash" diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.1/CONTRIBUTING.md cargo-0.26.0/vendor/crypto-hash-0.3.1/CONTRIBUTING.md --- cargo-0.25.0/vendor/crypto-hash-0.3.1/CONTRIBUTING.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.1/CONTRIBUTING.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,77 @@ +# Contributing to `crypto-hash` + +`crypto-hash` is a part of the Rust ecosystem. As such, all contributions to this project follow the +[Rust language's code of conduct](https://www.rust-lang.org/conduct.html) where appropriate. + +This project is hosted at [GitHub](https://github.com/malept/crypto-hash). Both pull requests and +issues of many different kinds are accepted. + +## Filing Issues + +Issues include bugs, questions, feedback, and feature requests. Before you file a new issue, please +make sure that your issue has not already been filed by someone else. + +### Filing Bugs + +When filing a bug, please include the following information: + +* Operating system and version. If on Linux, please also include the distribution name. +* System architecture. Examples include: x86-64, x86, and ARMv7. +* Rust version that compiled `crypto-hash`. +* The version (and/or git revision) of `crypto-hash`. +* A detailed list of steps to reproduce the bug. A minimal testcase would be very helpful, + if possible. +* If there any any error messages in the console, copying them in the bug summary will be + very helpful. + +## Adding a new implementation + +If you are requesting or adding a new library source for hash algorithms, please make sure that it +supports all of the existing algorithms. For example, while the creator of this project supports the +efforts of the team writing LibreSSL, it does not support the MD5 algorithm. + +## Adding a new hash algorithm + +If you are requesting or adding a wrapper for a new hash algorithm, please make sure that it is +available in all of the supported implementations listed in the README. + +## Filing Pull Requests + +Here are some things to keep in mind as you file a pull request to fix a bug, add a new feature, +etc.: + +* Travis CI (for Linux and OS X) and AppVeyor (for Windows) are used to make sure that the project + builds as expected on the supported platforms, using the current stable and beta versions of Rust. + Make sure the testsuite passes locally by running `cargo test`. +* Unless it's impractical, please write tests for your changes. This will help spot regressions + much easier. +* If your PR changes the behavior of an existing feature, or adds a new feature, please add/edit + the `rustdoc` inline documentation. +* Please ensure that your changes follow the [rustfmt](https://github.com/rust-lang-nursery/rustfmt) + coding standard, and do not produce any warnings when running the + [clippy](https://github.com/Manishearth/rust-clippy) linter. +* If you are contributing a nontrivial change, please add an entry to `NEWS.md`. The format is + similar to the one described at [Keep a Changelog](http://keepachangelog.com/). +* Please make sure your commits are rebased onto the latest commit in the master branch, and that + you limit/squash the number of commits created to a "feature"-level. For instance: + +bad: + +``` +commit 1: add foo algorithm +commit 2: run rustfmt +commit 3: add test +commit 4: add docs +commit 5: add bar +commit 6: add test + docs +``` + +good: + +``` +commit 1: add foo algorithm +commit 2: add bar +``` + +If you are continuing the work of another person's PR and need to rebase/squash, please retain the +attribution of the original author(s) and continue the work in subsequent commits. diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.1/LICENSE cargo-0.26.0/vendor/crypto-hash-0.3.1/LICENSE --- cargo-0.25.0/vendor/crypto-hash-0.3.1/LICENSE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.1/LICENSE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,19 @@ +Copyright (c) 2015, 2016 Mark Lee + +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. diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.1/Makefile cargo-0.26.0/vendor/crypto-hash-0.3.1/Makefile --- cargo-0.25.0/vendor/crypto-hash-0.3.1/Makefile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.1/Makefile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,29 @@ +CARGO ?= cargo +CARGO_BUILD_TEST = $(CARGO) test --no-run +KCOV ?= kcov +TEST_APP = debug/crypto_hash-*.exe +WIN_TARGET = x86_64-pc-windows-gnu + +build-test: + $(CARGO_BUILD_TEST) + +check-i686: + PKG_CONFIG_LIBDIR=/usr/lib/i386-linux-gnu/pkgconfig \ + PKG_CONFIG_ALLOW_CROSS=1 \ + $(CARGO) test --target i686-unknown-linux-gnu --verbose + +check-wine64: + $(CARGO_BUILD_TEST) --target $(WIN_TARGET) + WINEPREFIX=$(HOME)/.local/share/wineprefixes/wine64 wine64 target/$(WIN_TARGET)/$(TEST_APP) + +cov: build-test + $(KCOV) --exclude-pattern=/.multirust,test.rs target/cov target/$(TEST_APP) + +debug: build-test + rust-gdb target/$(TEST_APP) + +fmt: + $(CARGO) fmt + +lint: + $(CARGO) +nightly clippy -- --allow clippy-pedantic diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.1/NEWS.md cargo-0.26.0/vendor/crypto-hash-0.3.1/NEWS.md --- cargo-0.25.0/vendor/crypto-hash-0.3.1/NEWS.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.1/NEWS.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,62 @@ +# Changes by Version + +## Unreleased + +## [0.3.1] - 2018-02-14 + +[0.3.1]: https://github.com/malept/crypto-hash/compare/v0.3.0...v0.3.1 + +### Changed + +* Upgrade to `openssl` 0.10.x (#1) +* Upgrade to `winapi` 0.3.x + +## [0.3.0] - 2017-06-18 + +[0.3.0]: https://github.com/malept/crypto-hash/compare/v0.2.1...v0.3.0 + +### Changed + +* Upgrade to `commoncrypto` 0.2.x +* Function signatures for `digest` and `hex_digest` changed to use `&[u8]`, per Clippy + +## [0.2.1] - 2016-12-12 + +[0.2.1]: https://github.com/malept/crypto-hash/compare/v0.2.0...v0.2.1 + +### Changed + +* Move CommonCrypto implementation to its own crate + +## [0.2.0] - 2016-11-06 + +[0.2.0]: https://github.com/malept/crypto-hash/compare/v0.1.0...v0.2.0 + +### Added + +* SHA-1 algorithm + +### Changed + +* Upgrade rust-openssl to 0.9 + +## [0.1.0] - 2016-06-26 + +[0.1.0]: https://github.com/malept/crypto-hash/releases/tag/v0.1.0 + +This release signifies the minimum amount of algorithms and implementations necessary for +[HTTP digest authentication](https://tools.ietf.org/html/rfc7616). + +### Added + +Algorithms: + +* MD5 +* SHA256 +* SHA512 + +Implementations: + +* CommonCrypto (OS X) +* CryptoAPI (Windows) +* OpenSSL (Linux/BSD/etc.) diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.1/README.md cargo-0.26.0/vendor/crypto-hash-0.3.1/README.md --- cargo-0.25.0/vendor/crypto-hash-0.3.1/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.1/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,54 @@ +# `crypto-hash` + +[![Linux/OS X Status](https://travis-ci.org/malept/crypto-hash.svg?branch=master)](https://travis-ci.org/malept/crypto-hash) +[![Windows status](https://ci.appveyor.com/api/projects/status/xwc9nb4633b5n67r/branch/master?svg=true)](https://ci.appveyor.com/project/malept/crypto-hash) +[![Crates.io](https://img.shields.io/crates/v/crypto-hash.svg?maxAge=2592000)](https://crates.io/crates/crypto-hash) + +`crypto-hash` is a Rust wrapper around OS-level implementations of cryptographic hash functions. + +The purpose of this crate is to provide access to hash algorithms with as few dependencies as +possible. This means that when possible, the library uses the hashing functions that are provided by +the given operating system's bundled cryptographic libraries. + +## Supported Implementations + +By operating system: + +* Windows: CryptoAPI +* OS X: [CommonCrypto](https://crates.io/crates/commoncrypto) +* Linux/BSD/etc.: [OpenSSL](https://crates.io/crates/openssl) + +## Supported Algorithms + +* MD5 +* SHA1 +* SHA256 +* SHA512 + +## Usage + +Add `crypto-hash` to your project's `Cargo.toml`. For more details, consult the +[Cargo guide](http://doc.crates.io/guide.html#adding-dependencies). + +Example: + +```rust +use crypto_hash::{Algorithm, hex_digest}; + +let digest = hex_digest(Algorithm::SHA256, b"crypto-hash"); +``` + +For more examples, consult the [documentation](https://malept.github.io/crypto-hash/). + +## [Release Notes](https://github.com/malept/crypto-hash/blob/master/NEWS.md) + +## [Contributing](https://github.com/malept/crypto-hash/blob/master/CONTRIBUTING.md) + +## Acknowledgements + +This crate was inspired by [rust-native-tls](https://github.com/sfackler/rust-native-tls) and +[crypto-bench](https://github.com/briansmith/crypto-bench). + +## Legal + +`crypto-hash` is copyrighted under the terms of the MIT license. See LICENSE for details. diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.1/src/imp/commoncrypto.rs cargo-0.26.0/vendor/crypto-hash-0.3.1/src/imp/commoncrypto.rs --- cargo-0.25.0/vendor/crypto-hash-0.3.1/src/imp/commoncrypto.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.1/src/imp/commoncrypto.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,81 @@ +// Copyright (c) 2016 Mark Lee +// +// 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. + +//! A cryptographic hash generator dependent upon OSX's `CommonCrypto`. + +use commoncrypto::hash; +use std::io; +use super::Algorithm; + +/// Generator of digests using a cryptographic hash function. +/// +/// # Examples +/// +/// ```rust +/// use crypto_hash::{Algorithm, Hasher}; +/// use std::io::Write; +/// +/// let mut hasher = Hasher::new(Algorithm::SHA256); +/// hasher.write_all(b"crypto"); +/// hasher.write_all(b"-"); +/// hasher.write_all(b"hash"); +/// let result = hasher.finish(); +/// let expected = +/// b"\xfd\x1a\xfb`\"\xcdMG\xc8\x90\x96\x1cS9(\xea\xcf\xe8!\x9f\x1b%$\xf7\xfb*a\x84}\xdf\x8c'" +/// .to_vec(); +/// assert_eq!(expected, result) +/// ``` +#[derive(Debug)] +pub struct Hasher(hash::Hasher); + +impl Hasher { + /// Create a new `Hasher` for the given `Algorithm`. + pub fn new(algorithm: Algorithm) -> Hasher { + let cc_algorithm = match algorithm { + Algorithm::MD5 => hash::CCDigestAlgorithm::kCCDigestMD5, + Algorithm::SHA1 => hash::CCDigestAlgorithm::kCCDigestSHA1, + Algorithm::SHA256 => hash::CCDigestAlgorithm::kCCDigestSHA256, + Algorithm::SHA512 => hash::CCDigestAlgorithm::kCCDigestSHA512, + }; + + Hasher(hash::Hasher::new(cc_algorithm)) + } + + /// Generate a digest from the data written to the `Hasher`. + pub fn finish(&mut self) -> Vec { + let Hasher(ref mut hasher) = *self; + match hasher.finish() { + Ok(digest) => digest, + Err(error) => panic!("CommonCrypto error: {}", error), + } + } +} + +impl io::Write for Hasher { + fn write(&mut self, buf: &[u8]) -> io::Result { + let Hasher(ref mut hasher) = *self; + hasher.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + let Hasher(ref mut hasher) = *self; + hasher.flush() + } +} diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.1/src/imp/cryptoapi.rs cargo-0.26.0/vendor/crypto-hash-0.3.1/src/imp/cryptoapi.rs --- cargo-0.25.0/vendor/crypto-hash-0.3.1/src/imp/cryptoapi.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.1/src/imp/cryptoapi.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,159 @@ +// Copyright (c) 2016 Mark Lee +// +// 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. + +//! A cryptographic hash generator dependent upon Windows's `CryptoAPI`. +//! +//! Originally based on: +//! https://github.com/rust-lang/cargo/blob/0.10.0/src/cargo/util/sha256.rs +//! which is copyright (c) 2014 The Rust Project Developers under the MIT license. + +use std::io; +use std::ptr; +use super::Algorithm; +use winapi::shared::minwindef::DWORD; +use winapi::um::wincrypt::{CALG_MD5, CALG_SHA1, CALG_SHA_256, CALG_SHA_512, CryptAcquireContextW, + CryptCreateHash, CryptDestroyHash, CryptGetHashParam, CryptHashData, + CryptReleaseContext, CRYPT_SILENT, CRYPT_VERIFYCONTEXT, HCRYPTHASH, + HCRYPTPROV, HP_HASHVAL, PROV_RSA_AES}; + +macro_rules! call { + ($e: expr) => ({ + if $e == 0 { + panic!("failed {}: {}", stringify!($e), io::Error::last_os_error()) + } + }) +} + +macro_rules! finish_algorithm { + ($func_name: ident, $size: ident) => { + fn $func_name(&mut self) -> Vec { + let mut len = $size as u32; + let mut hash = [0u8; $size]; + call!(unsafe { + CryptGetHashParam(self.hcrypthash, HP_HASHVAL, hash.as_mut_ptr(), &mut len, 0) + }); + assert_eq!(len as usize, hash.len()); + hash.to_vec() + } + } +} + +const MD5_LENGTH: usize = 16; +const SHA1_LENGTH: usize = 20; +const SHA256_LENGTH: usize = 32; +const SHA512_LENGTH: usize = 64; + +/// Generator of digests using a cryptographic hash function. +/// +/// # Examples +/// +/// ```rust +/// use crypto_hash::{Algorithm, Hasher}; +/// use std::io::Write; +/// +/// let mut hasher = Hasher::new(Algorithm::SHA256); +/// hasher.write_all(b"crypto"); +/// hasher.write_all(b"-"); +/// hasher.write_all(b"hash"); +/// let result = hasher.finish(); +/// let expected = +/// b"\xfd\x1a\xfb`\"\xcdMG\xc8\x90\x96\x1cS9(\xea\xcf\xe8!\x9f\x1b%$\xf7\xfb*a\x84}\xdf\x8c'" +/// .to_vec(); +/// assert_eq!(expected, result) +/// ``` +pub struct Hasher { + algorithm: Algorithm, + hcryptprov: HCRYPTPROV, + hcrypthash: HCRYPTHASH, +} + +impl Hasher { + /// Create a new `Hasher` for the given `Algorithm`. + pub fn new(algorithm: Algorithm) -> Hasher { + let mut hcp = 0; + call!(unsafe { + CryptAcquireContextW( + &mut hcp, + ptr::null(), + ptr::null(), + PROV_RSA_AES, + CRYPT_VERIFYCONTEXT | CRYPT_SILENT, + ) + }); + + let hash_type = match algorithm { + Algorithm::MD5 => CALG_MD5, + Algorithm::SHA1 => CALG_SHA1, + Algorithm::SHA256 => CALG_SHA_256, + Algorithm::SHA512 => CALG_SHA_512, + }; + + let mut ret = Hasher { + algorithm: algorithm, + hcryptprov: hcp, + hcrypthash: 0, + }; + + call!(unsafe { CryptCreateHash(ret.hcryptprov, hash_type, 0, 0, &mut ret.hcrypthash) }); + ret + } + + /// Generate a digest from the data written to the `Hasher`. + pub fn finish(&mut self) -> Vec { + match self.algorithm { + Algorithm::MD5 => self.finish_md5(), + Algorithm::SHA1 => self.finish_sha1(), + Algorithm::SHA256 => self.finish_sha256(), + Algorithm::SHA512 => self.finish_sha512(), + } + } + + finish_algorithm!(finish_md5, MD5_LENGTH); + finish_algorithm!(finish_sha1, SHA1_LENGTH); + finish_algorithm!(finish_sha256, SHA256_LENGTH); + finish_algorithm!(finish_sha512, SHA512_LENGTH); +} + +impl io::Write for Hasher { + fn write(&mut self, buf: &[u8]) -> io::Result { + call!(unsafe { + CryptHashData( + self.hcrypthash, + buf.as_ptr() as *mut _, + buf.len() as DWORD, + 0, + ) + }); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl Drop for Hasher { + fn drop(&mut self) { + if self.hcrypthash != 0 { + call!(unsafe { CryptDestroyHash(self.hcrypthash) }); + } + call!(unsafe { CryptReleaseContext(self.hcryptprov, 0) }); + } +} diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.1/src/imp/openssl.rs cargo-0.26.0/vendor/crypto-hash-0.3.1/src/imp/openssl.rs --- cargo-0.25.0/vendor/crypto-hash-0.3.1/src/imp/openssl.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.1/src/imp/openssl.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,85 @@ +// Copyright (c) 2015, 2016 Mark Lee +// +// 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. + +//! A cryptographic hash digest generator dependent upon `OpenSSL`. + +#![warn(missing_docs)] + +use openssl::hash; +use std::io; +use super::Algorithm; + +/// Generator of digests using a cryptographic hash function. +/// +/// # Examples +/// +/// ```rust +/// use crypto_hash::{Algorithm, Hasher}; +/// use std::io::Write; +/// +/// let mut hasher = Hasher::new(Algorithm::SHA256); +/// hasher.write_all(b"crypto"); +/// hasher.write_all(b"-"); +/// hasher.write_all(b"hash"); +/// let result = hasher.finish(); +/// let expected = +/// b"\xfd\x1a\xfb`\"\xcdMG\xc8\x90\x96\x1cS9(\xea\xcf\xe8!\x9f\x1b%$\xf7\xfb*a\x84}\xdf\x8c'" +/// .to_vec(); +/// assert_eq!(expected, result) +/// ``` +pub struct Hasher(hash::Hasher); + +impl Hasher { + /// Create a new `Hasher` for the given `Algorithm`. + pub fn new(algorithm: Algorithm) -> Hasher { + let hash_type = match algorithm { + Algorithm::MD5 => hash::MessageDigest::md5(), + Algorithm::SHA1 => hash::MessageDigest::sha1(), + Algorithm::SHA256 => hash::MessageDigest::sha256(), + Algorithm::SHA512 => hash::MessageDigest::sha512(), + }; + + match hash::Hasher::new(hash_type) { + Ok(hasher) => Hasher(hasher), + Err(error_stack) => panic!("OpenSSL error(s): {}", error_stack), + } + } + + /// Generate a digest from the data written to the `Hasher`. + pub fn finish(&mut self) -> Vec { + let Hasher(ref mut hasher) = *self; + match hasher.finish() { + Ok(digest) => digest.to_vec(), + Err(error_stack) => panic!("OpenSSL error(s): {}", error_stack), + } + } +} + +impl io::Write for Hasher { + fn write(&mut self, buf: &[u8]) -> io::Result { + let Hasher(ref mut hasher) = *self; + hasher.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + let Hasher(ref mut hasher) = *self; + hasher.flush() + } +} diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.1/src/lib.rs cargo-0.26.0/vendor/crypto-hash-0.3.1/src/lib.rs --- cargo-0.25.0/vendor/crypto-hash-0.3.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.1/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,119 @@ +// Copyright (c) 2015, 2016, 2017 Mark Lee +// +// 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. + +//! A set of [cryptographic hash +//! functions](https://en.wikipedia.org/wiki/Cryptographic_hash_function) provided by the operating +//! system, when available. +//! +//! The purpose of this crate is to provide access to hash algorithms with as few dependencies as +//! possible. This means that when possible, the library uses the hashing functions that are +//! provided by the given operating system's bundled cryptographic libraries. +//! +//! # Supported Implementations +//! +//! By operating system: +//! +//! * Windows: `CryptoAPI` +//! * Mac OS X: `CommonCrypto` +//! * Linux/BSD/etc.: `OpenSSL` +//! +//! # Supported Algorithms +//! +//! * MD5 +//! * SHA1 +//! * SHA256 +//! * SHA512 + +#![warn(missing_docs)] + +#[cfg(target_os = "macos")] +extern crate commoncrypto; +extern crate hex; +#[cfg(not(any(target_os = "macos", target_os = "windows")))] +extern crate openssl; +#[cfg(target_os = "windows")] +extern crate winapi; + +use std::io::Write; + +#[cfg(target_os = "macos")] +#[path = "imp/commoncrypto.rs"] +mod imp; +#[cfg(target_os = "windows")] +#[path = "imp/cryptoapi.rs"] +mod imp; +#[cfg(not(any(target_os = "macos", target_os = "windows")))] +#[path = "imp/openssl.rs"] +mod imp; + +mod test; + +pub use imp::Hasher; + +/// Available cryptographic hash functions. +#[derive(Clone, Debug)] +pub enum Algorithm { + /// Popular message digest algorithm, only available for backwards compatibility purposes. + MD5, + /// SHA-1 algorithm from NIST FIPS, only available for backwards compatibility purposes. + SHA1, + /// SHA-2 family algorithm (256 bits). + SHA256, + /// SHA-2 family algorithm (512 bits). + SHA512, +} + +/// Helper function for `Hasher` which generates a cryptographic digest from the given +/// data and algorithm. +/// +/// # Examples +/// +/// ```rust +/// use crypto_hash::{Algorithm, digest}; +/// +/// let data = b"crypto-hash"; +/// let result = digest(Algorithm::SHA256, data); +/// let expected = +/// b"\xfd\x1a\xfb`\"\xcdMG\xc8\x90\x96\x1cS9(\xea\xcf\xe8!\x9f\x1b%$\xf7\xfb*a\x84}\xdf\x8c'" +/// .to_vec(); +/// assert_eq!(expected, result) +/// ``` +pub fn digest(algorithm: Algorithm, data: &[u8]) -> Vec { + let mut hasher = imp::Hasher::new(algorithm); + hasher.write_all(data).expect("Could not write hash data"); + hasher.finish() +} + +/// Helper function for `Hasher` which generates a cryptographic digest serialized in +/// hexadecimal from the given data and algorithm. +/// +/// # Examples +/// +/// ```rust +/// use crypto_hash::{Algorithm, hex_digest}; +/// +/// let data = b"crypto-hash"; +/// let result = hex_digest(Algorithm::SHA256, data); +/// let expected = "fd1afb6022cd4d47c890961c533928eacfe8219f1b2524f7fb2a61847ddf8c27"; +/// assert_eq!(expected, result) +/// ``` +pub fn hex_digest(algorithm: Algorithm, data: &[u8]) -> String { + hex::encode(digest(algorithm, data)) +} diff -Nru cargo-0.25.0/vendor/crypto-hash-0.3.1/src/test.rs cargo-0.26.0/vendor/crypto-hash-0.3.1/src/test.rs --- cargo-0.25.0/vendor/crypto-hash-0.3.1/src/test.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/crypto-hash-0.3.1/src/test.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,83 @@ +// Copyright (c) 2016, 2017 Mark Lee +// +// 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. + +#![cfg(test)] + +use hex; +use std::io::Write; +use super::{hex_digest, Algorithm, Hasher}; + +// From Wikipedia +const MD5_EMPTY_STRING: &'static str = "d41d8cd98f00b204e9800998ecf8427e"; +const SHA1_EMPTY_STRING: &'static str = "da39a3ee5e6b4b0d3255bfef95601890afd80709"; +const SHA256_EMPTY_STRING: &'static str = concat!( + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649", + "b934ca495991b7852b855" +); +const SHA512_EMPTY_STRING: &'static str = concat!( + "cf83e1357eefb8bdf1542850d66d8007d620e4050b5", + "715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318", + "d2877eec2f63b931bd47417a81a538327af927da3e" +); +const TO_HASH: &'static str = "The quick brown fox jumps over the lazy dog"; +const TO_HASH_MD5: &'static str = "9e107d9d372bb6826bd81d3542a419d6"; + +#[test] +fn md5_empty_string() { + assert_hex_hashed_empty_string(Algorithm::MD5, MD5_EMPTY_STRING) +} + +#[test] +fn sha1_empty_string() { + assert_hex_hashed_empty_string(Algorithm::SHA1, SHA1_EMPTY_STRING) +} + +#[test] +fn sha256_empty_string() { + // From Wikipedia + assert_hex_hashed_empty_string(Algorithm::SHA256, SHA256_EMPTY_STRING) +} + +#[test] +fn sha512_empty_string() { + assert_hex_hashed_empty_string(Algorithm::SHA512, SHA512_EMPTY_STRING) +} + +#[test] +fn hasher_sans_write() { + let mut hasher = Hasher::new(Algorithm::MD5); + let actual = hex::encode(hasher.finish()); + assert_eq!(MD5_EMPTY_STRING, actual) +} + +#[test] +fn hasher_with_write() { + let mut hasher = Hasher::new(Algorithm::MD5); + hasher + .write_all(TO_HASH.as_bytes()) + .expect("Could not write to hasher"); + let actual = hex::encode(hasher.finish()); + assert_eq!(TO_HASH_MD5, actual) +} + +fn assert_hex_hashed_empty_string(algorithm: Algorithm, expected: &str) { + let vec = vec![]; + assert_eq!(expected, hex_digest(algorithm, vec.as_slice()).as_str()) +} diff -Nru cargo-0.25.0/vendor/env_logger-0.4.3/.cargo-checksum.json cargo-0.26.0/vendor/env_logger-0.4.3/.cargo-checksum.json --- cargo-0.25.0/vendor/env_logger-0.4.3/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.4.3/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"3ddf21e73e016298f5cb37d6ef8e8da8e39f91f9ec8b0df44b7deb16a9f8cd5b"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/env_logger-0.4.3/Cargo.toml cargo-0.26.0/vendor/env_logger-0.4.3/Cargo.toml --- cargo-0.25.0/vendor/env_logger-0.4.3/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.4.3/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,35 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "env_logger" -version = "0.4.3" -authors = ["The Rust Project Developers"] -description = "A logging implementation for `log` which is configured via an environment\nvariable.\n" -homepage = "https://github.com/rust-lang/log" -documentation = "http://doc.rust-lang.org/log/env_logger" -categories = ["development-tools::debugging"] -license = "MIT/Apache-2.0" -repository = "https://github.com/rust-lang/log" - -[[test]] -name = "regexp_filter" -harness = false -[dependencies.regex] -version = "0.2" -optional = true - -[dependencies.log] -version = "0.3" - -[features] -default = ["regex"] diff -Nru cargo-0.25.0/vendor/env_logger-0.4.3/LICENSE-APACHE cargo-0.26.0/vendor/env_logger-0.4.3/LICENSE-APACHE --- cargo-0.25.0/vendor/env_logger-0.4.3/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.4.3/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/env_logger-0.4.3/LICENSE-MIT cargo-0.26.0/vendor/env_logger-0.4.3/LICENSE-MIT --- cargo-0.25.0/vendor/env_logger-0.4.3/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.4.3/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/env_logger-0.4.3/src/lib.rs cargo-0.26.0/vendor/env_logger-0.4.3/src/lib.rs --- cargo-0.25.0/vendor/env_logger-0.4.3/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.4.3/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,652 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A logger configured via an environment variable which writes to standard -//! error. -//! -//! ## Example -//! -//! ``` -//! #[macro_use] extern crate log; -//! extern crate env_logger; -//! -//! use log::LogLevel; -//! -//! fn main() { -//! env_logger::init().unwrap(); -//! -//! debug!("this is a debug {}", "message"); -//! error!("this is printed by default"); -//! -//! if log_enabled!(LogLevel::Info) { -//! let x = 3 * 4; // expensive computation -//! info!("the answer was: {}", x); -//! } -//! } -//! ``` -//! -//! Assumes the binary is `main`: -//! -//! ```{.bash} -//! $ RUST_LOG=error ./main -//! ERROR:main: this is printed by default -//! ``` -//! -//! ```{.bash} -//! $ RUST_LOG=info ./main -//! ERROR:main: this is printed by default -//! INFO:main: the answer was: 12 -//! ``` -//! -//! ```{.bash} -//! $ RUST_LOG=debug ./main -//! DEBUG:main: this is a debug message -//! ERROR:main: this is printed by default -//! INFO:main: the answer was: 12 -//! ``` -//! -//! You can also set the log level on a per module basis: -//! -//! ```{.bash} -//! $ RUST_LOG=main=info ./main -//! ERROR:main: this is printed by default -//! INFO:main: the answer was: 12 -//! ``` -//! -//! And enable all logging: -//! -//! ```{.bash} -//! $ RUST_LOG=main ./main -//! DEBUG:main: this is a debug message -//! ERROR:main: this is printed by default -//! INFO:main: the answer was: 12 -//! ``` -//! -//! See the documentation for the log crate for more information about its API. -//! -//! ## Enabling logging -//! -//! Log levels are controlled on a per-module basis, and by default all logging -//! is disabled except for `error!`. Logging is controlled via the `RUST_LOG` -//! environment variable. The value of this environment variable is a -//! comma-separated list of logging directives. A logging directive is of the -//! form: -//! -//! ```text -//! path::to::module=log_level -//! ``` -//! -//! The path to the module is rooted in the name of the crate it was compiled -//! for, so if your program is contained in a file `hello.rs`, for example, to -//! turn on logging for this file you would use a value of `RUST_LOG=hello`. -//! Furthermore, this path is a prefix-search, so all modules nested in the -//! specified module will also have logging enabled. -//! -//! The actual `log_level` is optional to specify. If omitted, all logging will -//! be enabled. If specified, it must be one of the strings `debug`, `error`, -//! `info`, `warn`, or `trace`. -//! -//! As the log level for a module is optional, the module to enable logging for -//! is also optional. If only a `log_level` is provided, then the global log -//! level for all modules is set to this value. -//! -//! Some examples of valid values of `RUST_LOG` are: -//! -//! * `hello` turns on all logging for the 'hello' module -//! * `info` turns on all info logging -//! * `hello=debug` turns on debug logging for 'hello' -//! * `hello,std::option` turns on hello, and std's option logging -//! * `error,hello=warn` turn on global error logging and also warn for hello -//! -//! ## Filtering results -//! -//! A RUST_LOG directive may include a regex filter. The syntax is to append `/` -//! followed by a regex. Each message is checked against the regex, and is only -//! logged if it matches. Note that the matching is done after formatting the -//! log string but before adding any logging meta-data. There is a single filter -//! for all modules. -//! -//! Some examples: -//! -//! * `hello/foo` turns on all logging for the 'hello' module where the log -//! message includes 'foo'. -//! * `info/f.o` turns on all info logging where the log message includes 'foo', -//! 'f1o', 'fao', etc. -//! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log -//! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc. -//! * `error,hello=warn/[0-9] scopes` turn on global error logging and also -//! warn for hello. In both cases the log message must include a single digit -//! number followed by 'scopes'. - -#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", - html_favicon_url = "http://www.rust-lang.org/favicon.ico", - html_root_url = "http://doc.rust-lang.org/env_logger/")] -#![cfg_attr(test, deny(warnings))] - -// When compiled for the rustc compiler itself we want to make sure that this is -// an unstable crate -#![cfg_attr(rustbuild, feature(staged_api, rustc_private))] -#![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))] - -extern crate log; - -use std::env; -use std::io::prelude::*; -use std::io; -use std::mem; - -use log::{Log, LogLevel, LogLevelFilter, LogRecord, SetLoggerError, LogMetadata}; - -#[cfg(feature = "regex")] -#[path = "regex.rs"] -mod filter; - -#[cfg(not(feature = "regex"))] -#[path = "string.rs"] -mod filter; - -/// Log target, either stdout or stderr. -#[derive(Debug)] -pub enum LogTarget { - Stdout, - Stderr, -} - -/// The logger. -pub struct Logger { - directives: Vec, - filter: Option, - format: Box String + Sync + Send>, - target: LogTarget, -} - -/// LogBuilder acts as builder for initializing the Logger. -/// It can be used to customize the log format, change the enviromental variable used -/// to provide the logging directives and also set the default log level filter. -/// -/// ## Example -/// -/// ``` -/// #[macro_use] -/// extern crate log; -/// extern crate env_logger; -/// -/// use std::env; -/// use log::{LogRecord, LogLevelFilter}; -/// use env_logger::LogBuilder; -/// -/// fn main() { -/// let format = |record: &LogRecord| { -/// format!("{} - {}", record.level(), record.args()) -/// }; -/// -/// let mut builder = LogBuilder::new(); -/// builder.format(format).filter(None, LogLevelFilter::Info); -/// -/// if env::var("RUST_LOG").is_ok() { -/// builder.parse(&env::var("RUST_LOG").unwrap()); -/// } -/// -/// builder.init().unwrap(); -/// -/// error!("error message"); -/// info!("info message"); -/// } -/// ``` -pub struct LogBuilder { - directives: Vec, - filter: Option, - format: Box String + Sync + Send>, - target: LogTarget, -} - -impl LogBuilder { - /// Initializes the log builder with defaults - pub fn new() -> LogBuilder { - LogBuilder { - directives: Vec::new(), - filter: None, - format: Box::new(|record: &LogRecord| { - format!("{}:{}: {}", record.level(), - record.location().module_path(), record.args()) - }), - target: LogTarget::Stderr, - } - } - - /// Adds filters to the logger - /// - /// The given module (if any) will log at most the specified level provided. - /// If no module is provided then the filter will apply to all log messages. - pub fn filter(&mut self, - module: Option<&str>, - level: LogLevelFilter) -> &mut Self { - self.directives.push(LogDirective { - name: module.map(|s| s.to_string()), - level: level, - }); - self - } - - /// Sets the format function for formatting the log output. - /// - /// This function is called on each record logged to produce a string which - /// is actually printed out. - pub fn format(&mut self, format: F) -> &mut Self - where F: Fn(&LogRecord) -> String + Sync + Send - { - self.format = Box::new(format); - self - } - - /// Sets the target for the log output. - /// - /// Env logger can log to either stdout or stderr. The default is stderr. - pub fn target(&mut self, target: LogTarget) -> &mut Self { - self.target = target; - self - } - - /// Parses the directives string in the same form as the RUST_LOG - /// environment variable. - /// - /// See the module documentation for more details. - pub fn parse(&mut self, filters: &str) -> &mut Self { - let (directives, filter) = parse_logging_spec(filters); - - self.filter = filter; - - for directive in directives { - self.directives.push(directive); - } - self - } - - /// Initializes the global logger with an env logger. - /// - /// This should be called early in the execution of a Rust program, and the - /// global logger may only be initialized once. Future initialization - /// attempts will return an error. - pub fn init(&mut self) -> Result<(), SetLoggerError> { - log::set_logger(|max_level| { - let logger = self.build(); - max_level.set(logger.filter()); - Box::new(logger) - }) - } - - /// Build an env logger. - pub fn build(&mut self) -> Logger { - if self.directives.is_empty() { - // Adds the default filter if none exist - self.directives.push(LogDirective { - name: None, - level: LogLevelFilter::Error, - }); - } else { - // Sort the directives by length of their name, this allows a - // little more efficient lookup at runtime. - self.directives.sort_by(|a, b| { - let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0); - let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0); - alen.cmp(&blen) - }); - } - - Logger { - directives: mem::replace(&mut self.directives, Vec::new()), - filter: mem::replace(&mut self.filter, None), - format: mem::replace(&mut self.format, Box::new(|_| String::new())), - target: mem::replace(&mut self.target, LogTarget::Stderr), - } - } -} - -impl Logger { - pub fn new() -> Logger { - let mut builder = LogBuilder::new(); - - if let Ok(s) = env::var("RUST_LOG") { - builder.parse(&s); - } - - builder.build() - } - - pub fn filter(&self) -> LogLevelFilter { - self.directives.iter() - .map(|d| d.level).max() - .unwrap_or(LogLevelFilter::Off) - } - - fn enabled(&self, level: LogLevel, target: &str) -> bool { - // Search for the longest match, the vector is assumed to be pre-sorted. - for directive in self.directives.iter().rev() { - match directive.name { - Some(ref name) if !target.starts_with(&**name) => {}, - Some(..) | None => { - return level <= directive.level - } - } - } - false - } -} - -impl Log for Logger { - fn enabled(&self, metadata: &LogMetadata) -> bool { - self.enabled(metadata.level(), metadata.target()) - } - - fn log(&self, record: &LogRecord) { - if !Log::enabled(self, record.metadata()) { - return; - } - - if let Some(filter) = self.filter.as_ref() { - if !filter.is_match(&*record.args().to_string()) { - return; - } - } - - match self.target { - LogTarget::Stdout => println!("{}", (self.format)(record)), - LogTarget::Stderr => { - let _ = writeln!(&mut io::stderr(), "{}", (self.format)(record)); - }, - }; - } -} - -struct LogDirective { - name: Option, - level: LogLevelFilter, -} - -/// Initializes the global logger with an env logger. -/// -/// This should be called early in the execution of a Rust program, and the -/// global logger may only be initialized once. Future initialization attempts -/// will return an error. -pub fn init() -> Result<(), SetLoggerError> { - let mut builder = LogBuilder::new(); - - if let Ok(s) = env::var("RUST_LOG") { - builder.parse(&s); - } - - builder.init() -} - -/// Parse a logging specification string (e.g: "crate1,crate2::mod3,crate3::x=error/foo") -/// and return a vector with log directives. -fn parse_logging_spec(spec: &str) -> (Vec, Option) { - let mut dirs = Vec::new(); - - let mut parts = spec.split('/'); - let mods = parts.next(); - let filter = parts.next(); - if parts.next().is_some() { - println!("warning: invalid logging spec '{}', \ - ignoring it (too many '/'s)", spec); - return (dirs, None); - } - mods.map(|m| { for s in m.split(',') { - if s.len() == 0 { continue } - let mut parts = s.split('='); - let (log_level, name) = match (parts.next(), parts.next().map(|s| s.trim()), parts.next()) { - (Some(part0), None, None) => { - // if the single argument is a log-level string or number, - // treat that as a global fallback - match part0.parse() { - Ok(num) => (num, None), - Err(_) => (LogLevelFilter::max(), Some(part0)), - } - } - (Some(part0), Some(""), None) => (LogLevelFilter::max(), Some(part0)), - (Some(part0), Some(part1), None) => { - match part1.parse() { - Ok(num) => (num, Some(part0)), - _ => { - println!("warning: invalid logging spec '{}', \ - ignoring it", part1); - continue - } - } - }, - _ => { - println!("warning: invalid logging spec '{}', \ - ignoring it", s); - continue - } - }; - dirs.push(LogDirective { - name: name.map(|s| s.to_string()), - level: log_level, - }); - }}); - - let filter = filter.map_or(None, |filter| { - match filter::Filter::new(filter) { - Ok(re) => Some(re), - Err(e) => { - println!("warning: invalid regex filter - {}", e); - None - } - } - }); - - return (dirs, filter); -} - -#[cfg(test)] -mod tests { - use log::{LogLevel, LogLevelFilter}; - - use super::{LogBuilder, Logger, LogDirective, parse_logging_spec}; - - fn make_logger(dirs: Vec) -> Logger { - let mut logger = LogBuilder::new().build(); - logger.directives = dirs; - logger - } - - #[test] - fn filter_info() { - let logger = LogBuilder::new().filter(None, LogLevelFilter::Info).build(); - assert!(logger.enabled(LogLevel::Info, "crate1")); - assert!(!logger.enabled(LogLevel::Debug, "crate1")); - } - - #[test] - fn filter_beginning_longest_match() { - let logger = LogBuilder::new() - .filter(Some("crate2"), LogLevelFilter::Info) - .filter(Some("crate2::mod"), LogLevelFilter::Debug) - .filter(Some("crate1::mod1"), LogLevelFilter::Warn) - .build(); - assert!(logger.enabled(LogLevel::Debug, "crate2::mod1")); - assert!(!logger.enabled(LogLevel::Debug, "crate2")); - } - - #[test] - fn parse_default() { - let logger = LogBuilder::new().parse("info,crate1::mod1=warn").build(); - assert!(logger.enabled(LogLevel::Warn, "crate1::mod1")); - assert!(logger.enabled(LogLevel::Info, "crate2::mod2")); - } - - #[test] - fn match_full_path() { - let logger = make_logger(vec![ - LogDirective { - name: Some("crate2".to_string()), - level: LogLevelFilter::Info - }, - LogDirective { - name: Some("crate1::mod1".to_string()), - level: LogLevelFilter::Warn - } - ]); - assert!(logger.enabled(LogLevel::Warn, "crate1::mod1")); - assert!(!logger.enabled(LogLevel::Info, "crate1::mod1")); - assert!(logger.enabled(LogLevel::Info, "crate2")); - assert!(!logger.enabled(LogLevel::Debug, "crate2")); - } - - #[test] - fn no_match() { - let logger = make_logger(vec![ - LogDirective { name: Some("crate2".to_string()), level: LogLevelFilter::Info }, - LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn } - ]); - assert!(!logger.enabled(LogLevel::Warn, "crate3")); - } - - #[test] - fn match_beginning() { - let logger = make_logger(vec![ - LogDirective { name: Some("crate2".to_string()), level: LogLevelFilter::Info }, - LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn } - ]); - assert!(logger.enabled(LogLevel::Info, "crate2::mod1")); - } - - #[test] - fn match_beginning_longest_match() { - let logger = make_logger(vec![ - LogDirective { name: Some("crate2".to_string()), level: LogLevelFilter::Info }, - LogDirective { name: Some("crate2::mod".to_string()), level: LogLevelFilter::Debug }, - LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn } - ]); - assert!(logger.enabled(LogLevel::Debug, "crate2::mod1")); - assert!(!logger.enabled(LogLevel::Debug, "crate2")); - } - - #[test] - fn match_default() { - let logger = make_logger(vec![ - LogDirective { name: None, level: LogLevelFilter::Info }, - LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Warn } - ]); - assert!(logger.enabled(LogLevel::Warn, "crate1::mod1")); - assert!(logger.enabled(LogLevel::Info, "crate2::mod2")); - } - - #[test] - fn zero_level() { - let logger = make_logger(vec![ - LogDirective { name: None, level: LogLevelFilter::Info }, - LogDirective { name: Some("crate1::mod1".to_string()), level: LogLevelFilter::Off } - ]); - assert!(!logger.enabled(LogLevel::Error, "crate1::mod1")); - assert!(logger.enabled(LogLevel::Info, "crate2::mod2")); - } - - #[test] - fn parse_logging_spec_valid() { - let (dirs, filter) = parse_logging_spec("crate1::mod1=error,crate1::mod2,crate2=debug"); - assert_eq!(dirs.len(), 3); - assert_eq!(dirs[0].name, Some("crate1::mod1".to_string())); - assert_eq!(dirs[0].level, LogLevelFilter::Error); - - assert_eq!(dirs[1].name, Some("crate1::mod2".to_string())); - assert_eq!(dirs[1].level, LogLevelFilter::max()); - - assert_eq!(dirs[2].name, Some("crate2".to_string())); - assert_eq!(dirs[2].level, LogLevelFilter::Debug); - assert!(filter.is_none()); - } - - #[test] - fn parse_logging_spec_invalid_crate() { - // test parse_logging_spec with multiple = in specification - let (dirs, filter) = parse_logging_spec("crate1::mod1=warn=info,crate2=debug"); - assert_eq!(dirs.len(), 1); - assert_eq!(dirs[0].name, Some("crate2".to_string())); - assert_eq!(dirs[0].level, LogLevelFilter::Debug); - assert!(filter.is_none()); - } - - #[test] - fn parse_logging_spec_invalid_log_level() { - // test parse_logging_spec with 'noNumber' as log level - let (dirs, filter) = parse_logging_spec("crate1::mod1=noNumber,crate2=debug"); - assert_eq!(dirs.len(), 1); - assert_eq!(dirs[0].name, Some("crate2".to_string())); - assert_eq!(dirs[0].level, LogLevelFilter::Debug); - assert!(filter.is_none()); - } - - #[test] - fn parse_logging_spec_string_log_level() { - // test parse_logging_spec with 'warn' as log level - let (dirs, filter) = parse_logging_spec("crate1::mod1=wrong,crate2=warn"); - assert_eq!(dirs.len(), 1); - assert_eq!(dirs[0].name, Some("crate2".to_string())); - assert_eq!(dirs[0].level, LogLevelFilter::Warn); - assert!(filter.is_none()); - } - - #[test] - fn parse_logging_spec_empty_log_level() { - // test parse_logging_spec with '' as log level - let (dirs, filter) = parse_logging_spec("crate1::mod1=wrong,crate2="); - assert_eq!(dirs.len(), 1); - assert_eq!(dirs[0].name, Some("crate2".to_string())); - assert_eq!(dirs[0].level, LogLevelFilter::max()); - assert!(filter.is_none()); - } - - #[test] - fn parse_logging_spec_global() { - // test parse_logging_spec with no crate - let (dirs, filter) = parse_logging_spec("warn,crate2=debug"); - assert_eq!(dirs.len(), 2); - assert_eq!(dirs[0].name, None); - assert_eq!(dirs[0].level, LogLevelFilter::Warn); - assert_eq!(dirs[1].name, Some("crate2".to_string())); - assert_eq!(dirs[1].level, LogLevelFilter::Debug); - assert!(filter.is_none()); - } - - #[test] - fn parse_logging_spec_valid_filter() { - let (dirs, filter) = parse_logging_spec("crate1::mod1=error,crate1::mod2,crate2=debug/abc"); - assert_eq!(dirs.len(), 3); - assert_eq!(dirs[0].name, Some("crate1::mod1".to_string())); - assert_eq!(dirs[0].level, LogLevelFilter::Error); - - assert_eq!(dirs[1].name, Some("crate1::mod2".to_string())); - assert_eq!(dirs[1].level, LogLevelFilter::max()); - - assert_eq!(dirs[2].name, Some("crate2".to_string())); - assert_eq!(dirs[2].level, LogLevelFilter::Debug); - assert!(filter.is_some() && filter.unwrap().to_string() == "abc"); - } - - #[test] - fn parse_logging_spec_invalid_crate_filter() { - let (dirs, filter) = parse_logging_spec("crate1::mod1=error=warn,crate2=debug/a.c"); - assert_eq!(dirs.len(), 1); - assert_eq!(dirs[0].name, Some("crate2".to_string())); - assert_eq!(dirs[0].level, LogLevelFilter::Debug); - assert!(filter.is_some() && filter.unwrap().to_string() == "a.c"); - } - - #[test] - fn parse_logging_spec_empty_with_filter() { - let (dirs, filter) = parse_logging_spec("crate1/a*c"); - assert_eq!(dirs.len(), 1); - assert_eq!(dirs[0].name, Some("crate1".to_string())); - assert_eq!(dirs[0].level, LogLevelFilter::max()); - assert!(filter.is_some() && filter.unwrap().to_string() == "a*c"); - } -} diff -Nru cargo-0.25.0/vendor/env_logger-0.4.3/src/regex.rs cargo-0.26.0/vendor/env_logger-0.4.3/src/regex.rs --- cargo-0.25.0/vendor/env_logger-0.4.3/src/regex.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.4.3/src/regex.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -extern crate regex; - -use std::fmt; - -use self::regex::Regex; - -pub struct Filter { - inner: Regex, -} - -impl Filter { - pub fn new(spec: &str) -> Result { - match Regex::new(spec){ - Ok(r) => Ok(Filter { inner: r }), - Err(e) => Err(e.to_string()), - } - } - - pub fn is_match(&self, s: &str) -> bool { - self.inner.is_match(s) - } -} - -impl fmt::Display for Filter { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.inner.fmt(f) - } -} diff -Nru cargo-0.25.0/vendor/env_logger-0.4.3/src/string.rs cargo-0.26.0/vendor/env_logger-0.4.3/src/string.rs --- cargo-0.25.0/vendor/env_logger-0.4.3/src/string.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.4.3/src/string.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -use std::fmt; - -pub struct Filter { - inner: String, -} - -impl Filter { - pub fn new(spec: &str) -> Result { - Ok(Filter { inner: spec.to_string() }) - } - - pub fn is_match(&self, s: &str) -> bool { - s.contains(&self.inner) - } -} - -impl fmt::Display for Filter { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.inner.fmt(f) - } -} diff -Nru cargo-0.25.0/vendor/env_logger-0.4.3/tests/regexp_filter.rs cargo-0.26.0/vendor/env_logger-0.4.3/tests/regexp_filter.rs --- cargo-0.25.0/vendor/env_logger-0.4.3/tests/regexp_filter.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.4.3/tests/regexp_filter.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -#[macro_use] extern crate log; -extern crate env_logger; - -use std::process; -use std::env; -use std::str; - -fn main() { - if env::var("LOG_REGEXP_TEST").ok() == Some(String::from("1")) { - child_main(); - } else { - parent_main() - } -} - -fn child_main() { - env_logger::init().unwrap(); - info!("XYZ Message"); -} - -fn run_child(rust_log: String) -> bool { - let exe = env::current_exe().unwrap(); - let out = process::Command::new(exe) - .env("LOG_REGEXP_TEST", "1") - .env("RUST_LOG", rust_log) - .output() - .unwrap_or_else(|e| panic!("Unable to start child process: {}", e)); - str::from_utf8(out.stderr.as_ref()).unwrap().contains("XYZ Message") -} - -fn assert_message_printed(rust_log: &str) { - if !run_child(rust_log.to_string()) { - panic!("RUST_LOG={} should allow the test log message", rust_log) - } -} - -fn assert_message_not_printed(rust_log: &str) { - if run_child(rust_log.to_string()) { - panic!("RUST_LOG={} should not allow the test log message", rust_log) - } -} - -fn parent_main() { - // test normal log severity levels - assert_message_printed("info"); - assert_message_not_printed("warn"); - - // test of regular expression filters - assert_message_printed("info/XYZ"); - assert_message_not_printed("info/XXX"); -} diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/.cargo-checksum.json cargo-0.26.0/vendor/env_logger-0.5.7/.cargo-checksum.json --- cargo-0.25.0/vendor/env_logger-0.5.7/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"0f475037312b91d34dbc3142a1ad3980ef0d070c7a855ce238afdd5e987cfecc"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/Cargo.toml cargo-0.26.0/vendor/env_logger-0.5.7/Cargo.toml --- cargo-0.25.0/vendor/env_logger-0.5.7/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,50 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "env_logger" +version = "0.5.7" +authors = ["The Rust Project Developers"] +description = "A logging implementation for `log` which is configured via an environment\nvariable.\n" +documentation = "https://docs.rs/env_logger" +readme = "README.md" +keywords = ["logging", "log", "logger"] +categories = ["development-tools::debugging"] +license = "MIT/Apache-2.0" +repository = "https://github.com/sebasmagri/env_logger/" + +[[test]] +name = "regexp_filter" +harness = false + +[[test]] +name = "log-in-log" +harness = false +[dependencies.atty] +version = "0.2" + +[dependencies.humantime] +version = "1.1.0" + +[dependencies.log] +version = "0.4.0" +features = ["std"] + +[dependencies.regex] +version = "0.2" +optional = true + +[dependencies.termcolor] +version = "0.3" + +[features] +default = ["regex"] diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/examples/custom_default_format.rs cargo-0.26.0/vendor/env_logger-0.5.7/examples/custom_default_format.rs --- cargo-0.25.0/vendor/env_logger-0.5.7/examples/custom_default_format.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/examples/custom_default_format.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,44 @@ +/*! +Disabling parts of the default format. + +Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: + +```no_run,shell +$ export MY_LOG_LEVEL='info' +``` + +Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors +or `auto` to enable them: + +```no_run,shell +$ export MY_LOG_STYLE=never +``` + +If you want to control the logging output completely, see the `custom_logger` example. +*/ + +#[macro_use] +extern crate log; +extern crate env_logger; + +use env_logger::{Env, Builder}; + +fn init_logger() { + let env = Env::default() + .filter("MY_LOG_LEVEL") + .write_style("MY_LOG_STYLE"); + + let mut builder = Builder::from_env(env); + + builder + .default_format_level(false) + .default_format_timestamp(false); + + builder.init(); +} + +fn main() { + init_logger(); + + info!("a log from `MyLogger`"); +} diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/examples/custom_format.rs cargo-0.26.0/vendor/env_logger-0.5.7/examples/custom_format.rs --- cargo-0.25.0/vendor/env_logger-0.5.7/examples/custom_format.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/examples/custom_format.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,52 @@ +/*! +Changing the default logging format. + +Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: + +```no_run,shell +$ export MY_LOG_LEVEL='info' +``` + +Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors +or `auto` to enable them: + +```no_run,shell +$ export MY_LOG_STYLE=never +``` + +If you want to control the logging output completely, see the `custom_logger` example. +*/ + +#[macro_use] +extern crate log; +extern crate env_logger; + +use std::io::Write; + +use env_logger::{Env, Builder, fmt}; + +fn init_logger() { + let env = Env::default() + .filter("MY_LOG_LEVEL") + .write_style("MY_LOG_STYLE"); + + let mut builder = Builder::from_env(env); + + // Use a different format for writing log records + builder.format(|buf, record| { + let mut style = buf.style(); + style.set_bg(fmt::Color::Yellow).set_bold(true); + + let timestamp = buf.timestamp(); + + writeln!(buf, "My formatted log ({}): {}", timestamp, style.value(record.args())) + }); + + builder.init(); +} + +fn main() { + init_logger(); + + info!("a log from `MyLogger`"); +} diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/examples/custom_logger.rs cargo-0.26.0/vendor/env_logger-0.5.7/examples/custom_logger.rs --- cargo-0.25.0/vendor/env_logger-0.5.7/examples/custom_logger.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/examples/custom_logger.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,60 @@ +/*! +Using `env_logger` to drive a custom logger. + +Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: + +```no_run,shell +$ export MY_LOG_LEVEL='info' +``` + +If you only want to change the way logs are formatted, look at the `custom_format` example. +*/ + +#[macro_use] +extern crate log; +extern crate env_logger; +use env_logger::filter::Filter; +use log::{Log, Metadata, Record, SetLoggerError}; + +struct MyLogger { + inner: Filter +} + +impl MyLogger { + fn new() -> MyLogger { + use env_logger::filter::Builder; + let mut builder = Builder::from_env("MY_LOG_LEVEL"); + + MyLogger { + inner: builder.build() + } + } + + fn init() -> Result<(), SetLoggerError> { + let logger = Self::new(); + + log::set_max_level(logger.inner.filter()); + log::set_boxed_logger(Box::new(logger)) + } +} + +impl Log for MyLogger { + fn enabled(&self, metadata: &Metadata) -> bool { + self.inner.enabled(metadata) + } + + fn log(&self, record: &Record) { + // Check if the record is matched by the logger before logging + if self.inner.matches(record) { + println!("{} - {}", record.level(), record.args()); + } + } + + fn flush(&self) { } +} + +fn main() { + MyLogger::init().unwrap(); + + info!("a log from `MyLogger`"); +} diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/examples/default.rs cargo-0.26.0/vendor/env_logger-0.5.7/examples/default.rs --- cargo-0.25.0/vendor/env_logger-0.5.7/examples/default.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/examples/default.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,36 @@ +/*! +Using `env_logger`. + +Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: + +```no_run,shell +$ export MY_LOG_LEVEL='info' +``` + +Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors +or `auto` to enable them: + +```no_run,shell +$ export MY_LOG_STYLE=never +``` +*/ + +#[macro_use] +extern crate log; +extern crate env_logger; + +use env_logger::Env; + +fn main() { + let env = Env::default() + .filter("MY_LOG_LEVEL") + .write_style("MY_LOG_STYLE"); + + env_logger::init_from_env(env); + + trace!("some trace log"); + debug!("some debug log"); + info!("some information log"); + warn!("some warning log"); + error!("some error log"); +} diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/examples/direct_logger.rs cargo-0.26.0/vendor/env_logger-0.5.7/examples/direct_logger.rs --- cargo-0.25.0/vendor/env_logger-0.5.7/examples/direct_logger.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/examples/direct_logger.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,40 @@ +/*! +Using `env_logger::Logger` and the `log::Log` trait directly. + +This example doesn't rely on environment variables, or having a static logger installed. +*/ + +extern crate log; +extern crate env_logger; + +fn record() -> log::Record<'static> { + let error_metadata = log::MetadataBuilder::new() + .target("myApp") + .level(log::Level::Error) + .build(); + + log::Record::builder() + .metadata(error_metadata) + .args(format_args!("Error!")) + .line(Some(433)) + .file(Some("app.rs")) + .module_path(Some("server")) + .build() +} + +fn main() { + use log::Log; + + let stylish_logger = env_logger::Builder::new() + .filter(None, log::LevelFilter::Error) + .write_style(env_logger::WriteStyle::Always) + .build(); + + let unstylish_logger = env_logger::Builder::new() + .filter(None, log::LevelFilter::Error) + .write_style(env_logger::WriteStyle::Never) + .build(); + + stylish_logger.log(&record()); + unstylish_logger.log(&record()); +} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/LICENSE-APACHE cargo-0.26.0/vendor/env_logger-0.5.7/LICENSE-APACHE --- cargo-0.25.0/vendor/env_logger-0.5.7/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/LICENSE-MIT cargo-0.26.0/vendor/env_logger-0.5.7/LICENSE-MIT --- cargo-0.25.0/vendor/env_logger-0.5.7/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/README.md cargo-0.26.0/vendor/env_logger-0.5.7/README.md --- cargo-0.25.0/vendor/env_logger-0.5.7/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,142 @@ +env_logger [![Build Status](https://travis-ci.org/sebasmagri/env_logger.svg?branch=master)](https://travis-ci.org/sebasmagri/env_logger) +========== + +Implements a logger that can be configured via an environment variable. + +* [`env_logger` documentation](https://docs.rs/env_logger) + +## Usage + +### In libraries + +`env_logger` makes sense when used in executables (binary projects). Libraries should use the [`log`](https://doc.rust-lang.org/log) crate instead. + +### In executables + +It must be added along with `log` to the project dependencies: + +```toml +[dependencies] +log = "0.4.0" +env_logger = "0.5.7" +``` + +`env_logger` must be initialized as early as possible in the project. After it's initialized, you can use the `log` macros to do actual logging. + +```rust +#[macro_use] +extern crate log; +extern crate env_logger; + +fn main() { + env_logger::init(); + + info!("starting up"); + + // ... +} +``` + +Then when running the executable, specify a value for the `RUST_LOG` +environment variable that corresponds with the log messages you want to show. + +```bash +$ RUST_LOG=info ./main +INFO: 2017-11-09T02:12:24Z: main: starting up +``` + +### In tests + +Tests can use the `env_logger` crate to see log messages generated during that test: + +```toml +[dependencies] +log = "0.4.0" + +[dev-dependencies] +env_logger = "0.5.7" +``` + +```rust +#[macro_use] +extern crate log; + +fn add_one(num: i32) -> i32 { + info!("add_one called with {}", num); + num + 1 +} + +#[cfg(test)] +mod tests { + use super::*; + extern crate env_logger; + + #[test] + fn it_adds_one() { + let _ = env_logger::try_init(); + info!("can log from the test too"); + assert_eq!(3, add_one(2)); + } + + #[test] + fn it_handles_negative_numbers() { + let _ = env_logger::try_init(); + info!("logging from another test"); + assert_eq!(-7, add_one(-8)); + } +} +``` + +Assuming the module under test is called `my_lib`, running the tests with the +`RUST_LOG` filtering to info messages from this module looks like: + +```bash +$ RUST_LOG=my_lib=info cargo test + Running target/debug/my_lib-... + +running 2 tests +INFO: 2017-11-09T02:12:24Z: my_lib::tests: logging from another test +INFO: 2017-11-09T02:12:24Z: my_lib: add_one called with -8 +test tests::it_handles_negative_numbers ... ok +INFO: 2017-11-09T02:12:24Z: my_lib::tests: can log from the test too +INFO: 2017-11-09T02:12:24Z: my_lib: add_one called with 2 +test tests::it_adds_one ... ok + +test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured +``` + +Note that `env_logger::try_init()` needs to be called in each test in which you +want to enable logging. Additionally, the default behavior of tests to +run in parallel means that logging output may be interleaved with test output. +Either run tests in a single thread by specifying `RUST_TEST_THREADS=1` or by +running one test by specifying its name as an argument to the test binaries as +directed by the `cargo test` help docs: + +```bash +$ RUST_LOG=my_lib=info cargo test it_adds_one + Running target/debug/my_lib-... + +running 1 test +INFO: 2017-11-09T02:12:24Z: my_lib::tests: can log from the test too +INFO: 2017-11-09T02:12:24Z: my_lib: add_one called with 2 +test tests::it_adds_one ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured +``` + +## Configuring log target + +By default, `env_logger` logs to stderr. If you want to log to stdout instead, +you can use the `Builder` to change the log target: + +```rust +use std::env; +use env_logger::{Builder, Target}; + +let mut builder = Builder::new(); +builder.target(Target::Stdout); +if env::var("RUST_LOG").is_ok() { + builder.parse(&env::var("RUST_LOG").unwrap()); +} +builder.init(); +``` diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/src/filter/mod.rs cargo-0.26.0/vendor/env_logger-0.5.7/src/filter/mod.rs --- cargo-0.25.0/vendor/env_logger-0.5.7/src/filter/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/src/filter/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,558 @@ +//! Filtering for log records. +//! +//! This module contains the log filtering used by `env_logger` to match records. +//! You can use the `Filter` type in your own logger implementation to use the same +//! filter parsing and matching as `env_logger`. For more details about the format +//! for directive strings see [Enabling Logging]. +//! +//! ## Using `env_logger` in your own logger +//! +//! You can use `env_logger`'s filtering functionality with your own logger. +//! Call [`Builder::parse`] to parse directives from a string when constructing +//! your logger. Call [`Filter::matches`] to check whether a record should be +//! logged based on the parsed filters when log records are received. +//! +//! ``` +//! extern crate log; +//! extern crate env_logger; +//! use env_logger::filter::Filter; +//! use log::{Log, Metadata, Record}; +//! +//! struct MyLogger { +//! filter: Filter +//! } +//! +//! impl MyLogger { +//! fn new() -> MyLogger { +//! use env_logger::filter::Builder; +//! let mut builder = Builder::new(); +//! +//! // Parse a directives string from an environment variable +//! if let Ok(ref filter) = std::env::var("MY_LOG_LEVEL") { +//! builder.parse(filter); +//! } +//! +//! MyLogger { +//! filter: builder.build() +//! } +//! } +//! } +//! +//! impl Log for MyLogger { +//! fn enabled(&self, metadata: &Metadata) -> bool { +//! self.filter.enabled(metadata) +//! } +//! +//! fn log(&self, record: &Record) { +//! // Check if the record is matched by the filter +//! if self.filter.matches(record) { +//! println!("{:?}", record); +//! } +//! } +//! +//! fn flush(&self) {} +//! } +//! # fn main() {} +//! ``` +//! +//! [Enabling Logging]: ../index.html#enabling-logging +//! [`Builder::parse`]: struct.Builder.html#method.parse +//! [`Filter::matches`]: struct.Filter.html#method.matches + +use std::env; +use std::mem; +use std::fmt; +use log::{Level, LevelFilter, Record, Metadata}; + +#[cfg(feature = "regex")] +#[path = "regex.rs"] +mod inner; + +#[cfg(not(feature = "regex"))] +#[path = "string.rs"] +mod inner; + +/// A log filter. +/// +/// This struct can be used to determine whether or not a log record +/// should be written to the output. +/// Use the [`Builder`] type to parse and construct a `Filter`. +/// +/// [`Builder`]: struct.Builder.html +pub struct Filter { + directives: Vec, + filter: Option, +} + +/// A builder for a log filter. +/// +/// It can be used to parse a set of directives from a string before building +/// a [`Filter`] instance. +/// +/// ## Example +/// +/// ``` +/// #[macro_use] +/// extern crate log; +/// extern crate env_logger; +/// +/// use std::env; +/// use std::io; +/// use env_logger::filter::Builder; +/// +/// fn main() { +/// let mut builder = Builder::new(); +/// +/// // Parse a logging filter from an environment variable. +/// if let Ok(rust_log) = env::var("RUST_LOG") { +/// builder.parse(&rust_log); +/// } +/// +/// let filter = builder.build(); +/// } +/// ``` +/// +/// [`Filter`]: struct.Filter.html +pub struct Builder { + directives: Vec, + filter: Option, +} + +#[derive(Debug)] +struct Directive { + name: Option, + level: LevelFilter, +} + +impl Filter { + /// Returns the maximum `LevelFilter` that this filter instance is + /// configured to output. + /// + /// # Example + /// + /// ```rust + /// extern crate log; + /// extern crate env_logger; + /// + /// use log::LevelFilter; + /// use env_logger::filter::Builder; + /// + /// fn main() { + /// let mut builder = Builder::new(); + /// builder.filter(Some("module1"), LevelFilter::Info); + /// builder.filter(Some("module2"), LevelFilter::Error); + /// + /// let filter = builder.build(); + /// assert_eq!(filter.filter(), LevelFilter::Info); + /// } + /// ``` + pub fn filter(&self) -> LevelFilter { + self.directives.iter() + .map(|d| d.level) + .max() + .unwrap_or(LevelFilter::Off) + } + + /// Checks if this record matches the configured filter. + pub fn matches(&self, record: &Record) -> bool { + if !self.enabled(record.metadata()) { + return false; + } + + if let Some(filter) = self.filter.as_ref() { + if !filter.is_match(&*record.args().to_string()) { + return false; + } + } + + true + } + + /// Determines if a log message with the specified metadata would be logged. + pub fn enabled(&self, metadata: &Metadata) -> bool { + let level = metadata.level(); + let target = metadata.target(); + + enabled(&self.directives, level, target) + } +} + +impl Builder { + /// Initializes the filter builder with defaults. + pub fn new() -> Builder { + Builder { + directives: Vec::new(), + filter: None, + } + } + + /// Initializes the filter builder from an environment. + pub fn from_env(env: &str) -> Builder { + let mut builder = Builder::new(); + + if let Ok(s) = env::var(env) { + builder.parse(&s); + } + + builder + } + + /// Adds a directive to the filter. + /// + /// The given module (if any) will log at most the specified level provided. + /// If no module is provided then the filter will apply to all log messages. + pub fn filter(&mut self, + module: Option<&str>, + level: LevelFilter) -> &mut Self { + self.directives.push(Directive { + name: module.map(|s| s.to_string()), + level: level, + }); + self + } + + /// Parses the directives string. + /// + /// See the [Enabling Logging] section for more details. + /// + /// [Enabling Logging]: ../index.html#enabling-logging + pub fn parse(&mut self, filters: &str) -> &mut Self { + let (directives, filter) = parse_spec(filters); + + self.filter = filter; + + for directive in directives { + self.directives.push(directive); + } + self + } + + /// Build a log filter. + pub fn build(&mut self) -> Filter { + if self.directives.is_empty() { + // Adds the default filter if none exist + self.directives.push(Directive { + name: None, + level: LevelFilter::Error, + }); + } else { + // Sort the directives by length of their name, this allows a + // little more efficient lookup at runtime. + self.directives.sort_by(|a, b| { + let alen = a.name.as_ref().map(|a| a.len()).unwrap_or(0); + let blen = b.name.as_ref().map(|b| b.len()).unwrap_or(0); + alen.cmp(&blen) + }); + } + + Filter { + directives: mem::replace(&mut self.directives, Vec::new()), + filter: mem::replace(&mut self.filter, None), + } + } +} + +impl Default for Builder { + fn default() -> Self { + Builder::new() + } +} + +impl fmt::Debug for Filter { + fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result { + f.debug_struct("Filter") + .field("filter", &self.filter) + .field("directives", &self.directives) + .finish() + } +} + +impl fmt::Debug for Builder { + fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result { + f.debug_struct("Filter") + .field("filter", &self.filter) + .field("directives", &self.directives) + .finish() + } +} + +/// Parse a logging specification string (e.g: "crate1,crate2::mod3,crate3::x=error/foo") +/// and return a vector with log directives. +fn parse_spec(spec: &str) -> (Vec, Option) { + let mut dirs = Vec::new(); + + let mut parts = spec.split('/'); + let mods = parts.next(); + let filter = parts.next(); + if parts.next().is_some() { + println!("warning: invalid logging spec '{}', \ + ignoring it (too many '/'s)", spec); + return (dirs, None); + } + mods.map(|m| { for s in m.split(',') { + if s.len() == 0 { continue } + let mut parts = s.split('='); + let (log_level, name) = match (parts.next(), parts.next().map(|s| s.trim()), parts.next()) { + (Some(part0), None, None) => { + // if the single argument is a log-level string or number, + // treat that as a global fallback + match part0.parse() { + Ok(num) => (num, None), + Err(_) => (LevelFilter::max(), Some(part0)), + } + } + (Some(part0), Some(""), None) => (LevelFilter::max(), Some(part0)), + (Some(part0), Some(part1), None) => { + match part1.parse() { + Ok(num) => (num, Some(part0)), + _ => { + println!("warning: invalid logging spec '{}', \ + ignoring it", part1); + continue + } + } + }, + _ => { + println!("warning: invalid logging spec '{}', \ + ignoring it", s); + continue + } + }; + dirs.push(Directive { + name: name.map(|s| s.to_string()), + level: log_level, + }); + }}); + + let filter = filter.map_or(None, |filter| { + match inner::Filter::new(filter) { + Ok(re) => Some(re), + Err(e) => { + println!("warning: invalid regex filter - {}", e); + None + } + } + }); + + return (dirs, filter); +} + + +// Check whether a level and target are enabled by the set of directives. +fn enabled(directives: &[Directive], level: Level, target: &str) -> bool { + // Search for the longest match, the vector is assumed to be pre-sorted. + for directive in directives.iter().rev() { + match directive.name { + Some(ref name) if !target.starts_with(&**name) => {}, + Some(..) | None => { + return level <= directive.level + } + } + } + false +} + +#[cfg(test)] +mod tests { + use log::{Level, LevelFilter}; + + use super::{Builder, Filter, Directive, parse_spec, enabled}; + + fn make_logger_filter(dirs: Vec) -> Filter { + let mut logger = Builder::new().build(); + logger.directives = dirs; + logger + } + + #[test] + fn filter_info() { + let logger = Builder::new().filter(None, LevelFilter::Info).build(); + assert!(enabled(&logger.directives, Level::Info, "crate1")); + assert!(!enabled(&logger.directives, Level::Debug, "crate1")); + } + + #[test] + fn filter_beginning_longest_match() { + let logger = Builder::new() + .filter(Some("crate2"), LevelFilter::Info) + .filter(Some("crate2::mod"), LevelFilter::Debug) + .filter(Some("crate1::mod1"), LevelFilter::Warn) + .build(); + assert!(enabled(&logger.directives, Level::Debug, "crate2::mod1")); + assert!(!enabled(&logger.directives, Level::Debug, "crate2")); + } + + #[test] + fn parse_default() { + let logger = Builder::new().parse("info,crate1::mod1=warn").build(); + assert!(enabled(&logger.directives, Level::Warn, "crate1::mod1")); + assert!(enabled(&logger.directives, Level::Info, "crate2::mod2")); + } + + #[test] + fn match_full_path() { + let logger = make_logger_filter(vec![ + Directive { + name: Some("crate2".to_string()), + level: LevelFilter::Info + }, + Directive { + name: Some("crate1::mod1".to_string()), + level: LevelFilter::Warn + } + ]); + assert!(enabled(&logger.directives, Level::Warn, "crate1::mod1")); + assert!(!enabled(&logger.directives, Level::Info, "crate1::mod1")); + assert!(enabled(&logger.directives, Level::Info, "crate2")); + assert!(!enabled(&logger.directives, Level::Debug, "crate2")); + } + + #[test] + fn no_match() { + let logger = make_logger_filter(vec![ + Directive { name: Some("crate2".to_string()), level: LevelFilter::Info }, + Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn } + ]); + assert!(!enabled(&logger.directives, Level::Warn, "crate3")); + } + + #[test] + fn match_beginning() { + let logger = make_logger_filter(vec![ + Directive { name: Some("crate2".to_string()), level: LevelFilter::Info }, + Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn } + ]); + assert!(enabled(&logger.directives, Level::Info, "crate2::mod1")); + } + + #[test] + fn match_beginning_longest_match() { + let logger = make_logger_filter(vec![ + Directive { name: Some("crate2".to_string()), level: LevelFilter::Info }, + Directive { name: Some("crate2::mod".to_string()), level: LevelFilter::Debug }, + Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn } + ]); + assert!(enabled(&logger.directives, Level::Debug, "crate2::mod1")); + assert!(!enabled(&logger.directives, Level::Debug, "crate2")); + } + + #[test] + fn match_default() { + let logger = make_logger_filter(vec![ + Directive { name: None, level: LevelFilter::Info }, + Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Warn } + ]); + assert!(enabled(&logger.directives, Level::Warn, "crate1::mod1")); + assert!(enabled(&logger.directives, Level::Info, "crate2::mod2")); + } + + #[test] + fn zero_level() { + let logger = make_logger_filter(vec![ + Directive { name: None, level: LevelFilter::Info }, + Directive { name: Some("crate1::mod1".to_string()), level: LevelFilter::Off } + ]); + assert!(!enabled(&logger.directives, Level::Error, "crate1::mod1")); + assert!(enabled(&logger.directives, Level::Info, "crate2::mod2")); + } + + #[test] + fn parse_spec_valid() { + let (dirs, filter) = parse_spec("crate1::mod1=error,crate1::mod2,crate2=debug"); + assert_eq!(dirs.len(), 3); + assert_eq!(dirs[0].name, Some("crate1::mod1".to_string())); + assert_eq!(dirs[0].level, LevelFilter::Error); + + assert_eq!(dirs[1].name, Some("crate1::mod2".to_string())); + assert_eq!(dirs[1].level, LevelFilter::max()); + + assert_eq!(dirs[2].name, Some("crate2".to_string())); + assert_eq!(dirs[2].level, LevelFilter::Debug); + assert!(filter.is_none()); + } + + #[test] + fn parse_spec_invalid_crate() { + // test parse_spec with multiple = in specification + let (dirs, filter) = parse_spec("crate1::mod1=warn=info,crate2=debug"); + assert_eq!(dirs.len(), 1); + assert_eq!(dirs[0].name, Some("crate2".to_string())); + assert_eq!(dirs[0].level, LevelFilter::Debug); + assert!(filter.is_none()); + } + + #[test] + fn parse_spec_invalid_level() { + // test parse_spec with 'noNumber' as log level + let (dirs, filter) = parse_spec("crate1::mod1=noNumber,crate2=debug"); + assert_eq!(dirs.len(), 1); + assert_eq!(dirs[0].name, Some("crate2".to_string())); + assert_eq!(dirs[0].level, LevelFilter::Debug); + assert!(filter.is_none()); + } + + #[test] + fn parse_spec_string_level() { + // test parse_spec with 'warn' as log level + let (dirs, filter) = parse_spec("crate1::mod1=wrong,crate2=warn"); + assert_eq!(dirs.len(), 1); + assert_eq!(dirs[0].name, Some("crate2".to_string())); + assert_eq!(dirs[0].level, LevelFilter::Warn); + assert!(filter.is_none()); + } + + #[test] + fn parse_spec_empty_level() { + // test parse_spec with '' as log level + let (dirs, filter) = parse_spec("crate1::mod1=wrong,crate2="); + assert_eq!(dirs.len(), 1); + assert_eq!(dirs[0].name, Some("crate2".to_string())); + assert_eq!(dirs[0].level, LevelFilter::max()); + assert!(filter.is_none()); + } + + #[test] + fn parse_spec_global() { + // test parse_spec with no crate + let (dirs, filter) = parse_spec("warn,crate2=debug"); + assert_eq!(dirs.len(), 2); + assert_eq!(dirs[0].name, None); + assert_eq!(dirs[0].level, LevelFilter::Warn); + assert_eq!(dirs[1].name, Some("crate2".to_string())); + assert_eq!(dirs[1].level, LevelFilter::Debug); + assert!(filter.is_none()); + } + + #[test] + fn parse_spec_valid_filter() { + let (dirs, filter) = parse_spec("crate1::mod1=error,crate1::mod2,crate2=debug/abc"); + assert_eq!(dirs.len(), 3); + assert_eq!(dirs[0].name, Some("crate1::mod1".to_string())); + assert_eq!(dirs[0].level, LevelFilter::Error); + + assert_eq!(dirs[1].name, Some("crate1::mod2".to_string())); + assert_eq!(dirs[1].level, LevelFilter::max()); + + assert_eq!(dirs[2].name, Some("crate2".to_string())); + assert_eq!(dirs[2].level, LevelFilter::Debug); + assert!(filter.is_some() && filter.unwrap().to_string() == "abc"); + } + + #[test] + fn parse_spec_invalid_crate_filter() { + let (dirs, filter) = parse_spec("crate1::mod1=error=warn,crate2=debug/a.c"); + assert_eq!(dirs.len(), 1); + assert_eq!(dirs[0].name, Some("crate2".to_string())); + assert_eq!(dirs[0].level, LevelFilter::Debug); + assert!(filter.is_some() && filter.unwrap().to_string() == "a.c"); + } + + #[test] + fn parse_spec_empty_with_filter() { + let (dirs, filter) = parse_spec("crate1/a*c"); + assert_eq!(dirs.len(), 1); + assert_eq!(dirs[0].name, Some("crate1".to_string())); + assert_eq!(dirs[0].level, LevelFilter::max()); + assert!(filter.is_some() && filter.unwrap().to_string() == "a*c"); + } +} diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/src/filter/regex.rs cargo-0.26.0/vendor/env_logger-0.5.7/src/filter/regex.rs --- cargo-0.25.0/vendor/env_logger-0.5.7/src/filter/regex.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/src/filter/regex.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,29 @@ +extern crate regex; + +use std::fmt; + +use self::regex::Regex; + +#[derive(Debug)] +pub struct Filter { + inner: Regex, +} + +impl Filter { + pub fn new(spec: &str) -> Result { + match Regex::new(spec){ + Ok(r) => Ok(Filter { inner: r }), + Err(e) => Err(e.to_string()), + } + } + + pub fn is_match(&self, s: &str) -> bool { + self.inner.is_match(s) + } +} + +impl fmt::Display for Filter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/src/filter/string.rs cargo-0.26.0/vendor/env_logger-0.5.7/src/filter/string.rs --- cargo-0.25.0/vendor/env_logger-0.5.7/src/filter/string.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/src/filter/string.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,22 @@ +use std::fmt; + +#[derive(Debug)] +pub struct Filter { + inner: String, +} + +impl Filter { + pub fn new(spec: &str) -> Result { + Ok(Filter { inner: spec.to_string() }) + } + + pub fn is_match(&self, s: &str) -> bool { + s.contains(&self.inner) + } +} + +impl fmt::Display for Filter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/src/fmt.rs cargo-0.26.0/vendor/env_logger-0.5.7/src/fmt.rs --- cargo-0.25.0/vendor/env_logger-0.5.7/src/fmt.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/src/fmt.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,815 @@ +//! Formatting for log records. +//! +//! This module contains a [`Formatter`] that can be used to format log records +//! into without needing temporary allocations. Usually you won't need to worry +//! about the contents of this module and can use the `Formatter` like an ordinary +//! [`Write`]. +//! +//! # Formatting log records +//! +//! The format used to print log records can be customised using the [`Builder::format`] +//! method. +//! Custom formats can apply different color and weight to printed values using +//! [`Style`] builders. +//! +//! ``` +//! use std::io::Write; +//! use env_logger::fmt::Color; +//! +//! let mut builder = env_logger::Builder::new(); +//! +//! builder.format(|buf, record| { +//! let mut level_style = buf.style(); +//! +//! level_style.set_color(Color::Red).set_bold(true); +//! +//! writeln!(buf, "{}: {}", +//! level_style.value(record.level()), +//! record.args()) +//! }); +//! ``` +//! +//! [`Formatter`]: struct.Formatter.html +//! [`Style`]: struct.Style.html +//! [`Builder::format`]: ../struct.Builder.html#method.format +//! [`Write`]: https://doc.rust-lang.org/stable/std/io/trait.Write.html + +use std::io::prelude::*; +use std::{io, fmt}; +use std::rc::Rc; +use std::str::FromStr; +use std::error::Error; +use std::cell::RefCell; +use std::time::SystemTime; + +use termcolor::{self, ColorSpec, ColorChoice, Buffer, BufferWriter, WriteColor}; +use atty; +use humantime::format_rfc3339_seconds; + +/// A formatter to write logs into. +/// +/// `Formatter` implements the standard [`Write`] trait for writing log records. +/// It also supports terminal colors, through the [`style`] method. +/// +/// # Examples +/// +/// Use the [`writeln`] macro to easily format a log record: +/// +/// ``` +/// use std::io::Write; +/// +/// let mut builder = env_logger::Builder::new(); +/// +/// builder.format(|buf, record| writeln!(buf, "{}: {}", record.level(), record.args())); +/// ``` +/// +/// [`Write`]: https://doc.rust-lang.org/stable/std/io/trait.Write.html +/// [`writeln`]: https://doc.rust-lang.org/stable/std/macro.writeln.html +/// [`style`]: #method.style +pub struct Formatter { + buf: Rc>, + write_style: WriteStyle, +} + +/// A set of styles to apply to the terminal output. +/// +/// Call [`Formatter::style`] to get a `Style` and use the builder methods to +/// set styling properties, like [color] and [weight]. +/// To print a value using the style, wrap it in a call to [`value`] when the log +/// record is formatted. +/// +/// # Examples +/// +/// Create a bold, red colored style and use it to print the log level: +/// +/// ``` +/// use std::io::Write; +/// use env_logger::fmt::Color; +/// +/// let mut builder = env_logger::Builder::new(); +/// +/// builder.format(|buf, record| { +/// let mut level_style = buf.style(); +/// +/// level_style.set_color(Color::Red).set_bold(true); +/// +/// writeln!(buf, "{}: {}", +/// level_style.value(record.level()), +/// record.args()) +/// }); +/// ``` +/// +/// Styles can be re-used to output multiple values: +/// +/// ``` +/// use std::io::Write; +/// use env_logger::fmt::Color; +/// +/// let mut builder = env_logger::Builder::new(); +/// +/// builder.format(|buf, record| { +/// let mut bold = buf.style(); +/// +/// bold.set_bold(true); +/// +/// writeln!(buf, "{}: {} {}", +/// bold.value(record.level()), +/// bold.value("some bold text"), +/// record.args()) +/// }); +/// ``` +/// +/// [`Formatter::style`]: struct.Formatter.html#method.style +/// [color]: #method.set_color +/// [weight]: #method.set_bold +/// [`value`]: #method.value +#[derive(Clone)] +pub struct Style { + buf: Rc>, + spec: ColorSpec, +} + +/// A value that can be printed using the given styles. +/// +/// It is the result of calling [`Style::value`]. +/// +/// [`Style::value`]: struct.Style.html#method.value +pub struct StyledValue<'a, T> { + style: &'a Style, + value: T, +} + +/// An [RFC3339] formatted timestamp. +/// +/// The timestamp implements [`Display`] and can be written to a [`Formatter`]. +/// +/// [RFC3339]: https://www.ietf.org/rfc/rfc3339.txt +/// [`Display`]: https://doc.rust-lang.org/stable/std/fmt/trait.Display.html +/// [`Formatter`]: struct.Formatter.html +pub struct Timestamp(SystemTime); + +/// Log target, either `stdout` or `stderr`. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum Target { + /// Logs will be sent to standard output. + Stdout, + /// Logs will be sent to standard error. + Stderr, +} + +impl Default for Target { + fn default() -> Self { + Target::Stderr + } +} + +/// Whether or not to print styles to the target. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum WriteStyle { + /// Try to print styles, but don't force the issue. + Auto, + /// Try very hard to print styles. + Always, + /// Never print styles. + Never, +} + +impl Default for WriteStyle { + fn default() -> Self { + WriteStyle::Auto + } +} + +/// A terminal target with color awareness. +pub(crate) struct Writer { + inner: BufferWriter, + write_style: WriteStyle, +} + +impl Writer { + pub(crate) fn write_style(&self) -> WriteStyle { + self.write_style + } +} + +/// A builder for a terminal writer. +/// +/// The target and style choice can be configured before building. +pub(crate) struct Builder { + target: Target, + write_style: WriteStyle, +} + +impl Builder { + /// Initialize the writer builder with defaults. + pub fn new() -> Self { + Builder { + target: Default::default(), + write_style: Default::default(), + } + } + + /// Set the target to write to. + pub fn target(&mut self, target: Target) -> &mut Self { + self.target = target; + self + } + + /// Parses a style choice string. + /// + /// See the [Disabling colors] section for more details. + /// + /// [Disabling colors]: ../index.html#disabling-colors + pub fn parse(&mut self, write_style: &str) -> &mut Self { + self.write_style(parse_write_style(write_style)) + } + + /// Whether or not to print style characters when writing. + pub fn write_style(&mut self, write_style: WriteStyle) -> &mut Self { + self.write_style = write_style; + self + } + + /// Build a terminal writer. + pub fn build(&mut self) -> Writer { + let color_choice = match self.write_style { + WriteStyle::Auto => { + if atty::is(match self.target { + Target::Stderr => atty::Stream::Stderr, + Target::Stdout => atty::Stream::Stdout, + }) { + ColorChoice::Auto + } else { + ColorChoice::Never + } + }, + WriteStyle::Always => ColorChoice::Always, + WriteStyle::Never => ColorChoice::Never, + }; + + let writer = match self.target { + Target::Stderr => BufferWriter::stderr(color_choice), + Target::Stdout => BufferWriter::stdout(color_choice), + }; + + Writer { + inner: writer, + write_style: self.write_style, + } + } +} + +impl Default for Builder { + fn default() -> Self { + Builder::new() + } +} + +impl Style { + /// Set the text color. + /// + /// # Examples + /// + /// Create a style with red text: + /// + /// ``` + /// use std::io::Write; + /// use env_logger::fmt::Color; + /// + /// let mut builder = env_logger::Builder::new(); + /// + /// builder.format(|buf, record| { + /// let mut style = buf.style(); + /// + /// style.set_color(Color::Red); + /// + /// writeln!(buf, "{}", style.value(record.args())) + /// }); + /// ``` + pub fn set_color(&mut self, color: Color) -> &mut Style { + self.spec.set_fg(color.to_termcolor()); + self + } + + /// Set the text weight. + /// + /// If `yes` is true then text will be written in bold. + /// If `yes` is false then text will be written in the default weight. + /// + /// # Examples + /// + /// Create a style with bold text: + /// + /// ``` + /// use std::io::Write; + /// + /// let mut builder = env_logger::Builder::new(); + /// + /// builder.format(|buf, record| { + /// let mut style = buf.style(); + /// + /// style.set_bold(true); + /// + /// writeln!(buf, "{}", style.value(record.args())) + /// }); + /// ``` + pub fn set_bold(&mut self, yes: bool) -> &mut Style { + self.spec.set_bold(yes); + self + } + + /// Set the text intensity. + /// + /// If `yes` is true then text will be written in a brighter color. + /// If `yes` is false then text will be written in the default color. + /// + /// # Examples + /// + /// Create a style with intense text: + /// + /// ``` + /// use std::io::Write; + /// + /// let mut builder = env_logger::Builder::new(); + /// + /// builder.format(|buf, record| { + /// let mut style = buf.style(); + /// + /// style.set_intense(true); + /// + /// writeln!(buf, "{}", style.value(record.args())) + /// }); + /// ``` + pub fn set_intense(&mut self, yes: bool) -> &mut Style { + self.spec.set_intense(yes); + self + } + + /// Set the background color. + /// + /// # Examples + /// + /// Create a style with a yellow background: + /// + /// ``` + /// use std::io::Write; + /// use env_logger::fmt::Color; + /// + /// let mut builder = env_logger::Builder::new(); + /// + /// builder.format(|buf, record| { + /// let mut style = buf.style(); + /// + /// style.set_bg(Color::Yellow); + /// + /// writeln!(buf, "{}", style.value(record.args())) + /// }); + /// ``` + pub fn set_bg(&mut self, color: Color) -> &mut Style { + self.spec.set_bg(color.to_termcolor()); + self + } + + /// Wrap a value in the style. + /// + /// The same `Style` can be used to print multiple different values. + /// + /// # Examples + /// + /// Create a bold, red colored style and use it to print the log level: + /// + /// ``` + /// use std::io::Write; + /// use env_logger::fmt::Color; + /// + /// let mut builder = env_logger::Builder::new(); + /// + /// builder.format(|buf, record| { + /// let mut style = buf.style(); + /// + /// style.set_color(Color::Red).set_bold(true); + /// + /// writeln!(buf, "{}: {}", + /// style.value(record.level()), + /// record.args()) + /// }); + /// ``` + pub fn value(&self, value: T) -> StyledValue { + StyledValue { + style: &self, + value + } + } +} + +impl Formatter { + pub(crate) fn new(writer: &Writer) -> Self { + Formatter { + buf: Rc::new(RefCell::new(writer.inner.buffer())), + write_style: writer.write_style(), + } + } + + pub(crate) fn write_style(&self) -> WriteStyle { + self.write_style + } + + /// Begin a new [`Style`]. + /// + /// # Examples + /// + /// Create a bold, red colored style and use it to print the log level: + /// + /// ``` + /// use std::io::Write; + /// use env_logger::fmt::Color; + /// + /// let mut builder = env_logger::Builder::new(); + /// + /// builder.format(|buf, record| { + /// let mut level_style = buf.style(); + /// + /// level_style.set_color(Color::Red).set_bold(true); + /// + /// writeln!(buf, "{}: {}", + /// level_style.value(record.level()), + /// record.args()) + /// }); + /// ``` + /// + /// [`Style`]: struct.Style.html + pub fn style(&self) -> Style { + Style { + buf: self.buf.clone(), + spec: ColorSpec::new(), + } + } + + /// Get a [`Timestamp`] for the current date and time in UTC. + /// + /// # Examples + /// + /// Include the current timestamp with the log record: + /// + /// ``` + /// use std::io::Write; + /// + /// let mut builder = env_logger::Builder::new(); + /// + /// builder.format(|buf, record| { + /// let ts = buf.timestamp(); + /// + /// writeln!(buf, "{}: {}: {}", ts, record.level(), record.args()) + /// }); + /// ``` + /// + /// [`Timestamp`]: struct.Timestamp.html + pub fn timestamp(&self) -> Timestamp { + Timestamp(SystemTime::now()) + } + + pub(crate) fn print(&self, writer: &Writer) -> io::Result<()> { + writer.inner.print(&self.buf.borrow()) + } + + pub(crate) fn clear(&mut self) { + self.buf.borrow_mut().clear() + } +} + +impl Write for Formatter { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.buf.borrow_mut().write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.buf.borrow_mut().flush() + } +} + +impl<'a, T> StyledValue<'a, T> { + fn write_fmt(&self, f: F) -> fmt::Result + where + F: FnOnce() -> fmt::Result, + { + self.style.buf.borrow_mut().set_color(&self.style.spec).map_err(|_| fmt::Error)?; + + // Always try to reset the terminal style, even if writing failed + let write = f(); + let reset = self.style.buf.borrow_mut().reset().map_err(|_| fmt::Error); + + write.and(reset) + } +} + +impl fmt::Debug for Timestamp { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + /// A `Debug` wrapper for `Timestamp` that uses the `Display` implementation. + struct TimestampValue<'a>(&'a Timestamp); + + impl<'a> fmt::Debug for TimestampValue<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self.0, f) + } + } + + f.debug_tuple("Timestamp") + .field(&TimestampValue(&self)) + .finish() + } +} + +impl fmt::Debug for Writer { + fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result { + f.debug_struct("Writer").finish() + } +} + +impl fmt::Debug for Formatter { + fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result { + f.debug_struct("Formatter").finish() + } +} + +impl fmt::Debug for Builder { + fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result { + f.debug_struct("Logger") + .field("target", &self.target) + .field("write_style", &self.write_style) + .finish() + } +} + +impl fmt::Debug for Style { + fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result { + f.debug_struct("Style").field("spec", &self.spec).finish() + } +} + +macro_rules! impl_styled_value_fmt { + ($($fmt_trait:path),*) => { + $( + impl<'a, T: $fmt_trait> $fmt_trait for StyledValue<'a, T> { + fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result { + self.write_fmt(|| T::fmt(&self.value, f)) + } + } + )* + }; +} + +impl_styled_value_fmt!( + fmt::Debug, + fmt::Display, + fmt::Pointer, + fmt::Octal, + fmt::Binary, + fmt::UpperHex, + fmt::LowerHex, + fmt::UpperExp, + fmt::LowerExp); + +impl fmt::Display for Timestamp { + fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result { + format_rfc3339_seconds(self.0).fmt(f) + } +} + +// The `Color` type is copied from https://github.com/BurntSushi/ripgrep/tree/master/termcolor + +/// The set of available colors for the terminal foreground/background. +/// +/// The `Ansi256` and `Rgb` colors will only output the correct codes when +/// paired with the `Ansi` `WriteColor` implementation. +/// +/// The `Ansi256` and `Rgb` color types are not supported when writing colors +/// on Windows using the console. If they are used on Windows, then they are +/// silently ignored and no colors will be emitted. +/// +/// This set may expand over time. +/// +/// This type has a `FromStr` impl that can parse colors from their human +/// readable form. The format is as follows: +/// +/// 1. Any of the explicitly listed colors in English. They are matched +/// case insensitively. +/// 2. A single 8-bit integer, in either decimal or hexadecimal format. +/// 3. A triple of 8-bit integers separated by a comma, where each integer is +/// in decimal or hexadecimal format. +/// +/// Hexadecimal numbers are written with a `0x` prefix. +#[allow(missing_docs)] +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Color { + Black, + Blue, + Green, + Red, + Cyan, + Magenta, + Yellow, + White, + Ansi256(u8), + Rgb(u8, u8, u8), + #[doc(hidden)] + __Nonexhaustive, +} + +/// An error from parsing an invalid color specification. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ParseColorError(ParseColorErrorKind); + +#[derive(Clone, Debug, Eq, PartialEq)] +enum ParseColorErrorKind { + /// An error originating from `termcolor`. + TermColor(termcolor::ParseColorError), + /// An error converting the `termcolor` color to a `env_logger::Color`. + /// + /// This variant should only get reached if a user uses a new spec that's + /// valid for `termcolor`, but not recognised in `env_logger` yet. + Unrecognized { + given: String, + } +} + +impl ParseColorError { + fn termcolor(err: termcolor::ParseColorError) -> Self { + ParseColorError(ParseColorErrorKind::TermColor(err)) + } + + fn unrecognized(given: String) -> Self { + ParseColorError(ParseColorErrorKind::Unrecognized { given }) + } + + /// Return the string that couldn't be parsed as a valid color. + pub fn invalid(&self) -> &str { + match self.0 { + ParseColorErrorKind::TermColor(ref err) => err.invalid(), + ParseColorErrorKind::Unrecognized { ref given, .. } => given, + } + } +} + +impl Error for ParseColorError { + fn description(&self) -> &str { + match self.0 { + ParseColorErrorKind::TermColor(ref err) => err.description(), + ParseColorErrorKind::Unrecognized { .. } => "unrecognized color value", + } + } +} + +impl fmt::Display for ParseColorError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.0 { + ParseColorErrorKind::TermColor(ref err) => fmt::Display::fmt(err, f), + ParseColorErrorKind::Unrecognized { ref given, .. } => { + write!(f, "unrecognized color value '{}'", given) + } + } + } +} + +impl Color { + fn to_termcolor(self) -> Option { + match self { + Color::Black => Some(termcolor::Color::Black), + Color::Blue => Some(termcolor::Color::Blue), + Color::Green => Some(termcolor::Color::Green), + Color::Red => Some(termcolor::Color::Red), + Color::Cyan => Some(termcolor::Color::Cyan), + Color::Magenta => Some(termcolor::Color::Magenta), + Color::Yellow => Some(termcolor::Color::Yellow), + Color::White => Some(termcolor::Color::White), + Color::Ansi256(value) => Some(termcolor::Color::Ansi256(value)), + Color::Rgb(r, g, b) => Some(termcolor::Color::Rgb(r, g, b)), + _ => None, + } + } + + fn from_termcolor(color: termcolor::Color) -> Option { + match color { + termcolor::Color::Black => Some(Color::Black), + termcolor::Color::Blue => Some(Color::Blue), + termcolor::Color::Green => Some(Color::Green), + termcolor::Color::Red => Some(Color::Red), + termcolor::Color::Cyan => Some(Color::Cyan), + termcolor::Color::Magenta => Some(Color::Magenta), + termcolor::Color::Yellow => Some(Color::Yellow), + termcolor::Color::White => Some(Color::White), + termcolor::Color::Ansi256(value) => Some(Color::Ansi256(value)), + termcolor::Color::Rgb(r, g, b) => Some(Color::Rgb(r, g, b)), + _ => None, + } + } +} + +impl FromStr for Color { + type Err = ParseColorError; + + fn from_str(s: &str) -> Result { + let tc = termcolor::Color::from_str(s).map_err(ParseColorError::termcolor)?; + Color::from_termcolor(tc).ok_or(ParseColorError::unrecognized(s.to_owned())) + } +} + +fn parse_write_style(spec: &str) -> WriteStyle { + match spec { + "auto" => WriteStyle::Auto, + "always" => WriteStyle::Always, + "never" => WriteStyle::Never, + _ => Default::default(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_write_style_valid() { + let inputs = vec![ + ("auto", WriteStyle::Auto), + ("always", WriteStyle::Always), + ("never", WriteStyle::Never), + ]; + + for (input, expected) in inputs { + assert_eq!(expected, parse_write_style(input)); + } + } + + #[test] + fn parse_write_style_invalid() { + let inputs = vec![ + "", + "true", + "false", + "NEVER!!" + ]; + + for input in inputs { + assert_eq!(WriteStyle::Auto, parse_write_style(input)); + } + } + + #[test] + fn parse_color_name_valid() { + let inputs = vec![ + "black", + "blue", + "green", + "red", + "cyan", + "magenta", + "yellow", + "white", + ]; + + for input in inputs { + assert!(Color::from_str(input).is_ok()); + } + } + + #[test] + fn parse_color_ansi_valid() { + let inputs = vec![ + "7", + "32", + "0xFF", + ]; + + for input in inputs { + assert!(Color::from_str(input).is_ok()); + } + } + + #[test] + fn parse_color_rgb_valid() { + let inputs = vec![ + "0,0,0", + "0,128,255", + "0x0,0x0,0x0", + "0x33,0x66,0xFF", + ]; + + for input in inputs { + assert!(Color::from_str(input).is_ok()); + } + } + + #[test] + fn parse_color_invalid() { + let inputs = vec![ + "not_a_color", + "256", + "0,0", + "0,0,256", + ]; + + for input in inputs { + let err = Color::from_str(input).unwrap_err(); + assert_eq!(input, err.invalid()); + } + } +} diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/src/lib.rs cargo-0.26.0/vendor/env_logger-0.5.7/src/lib.rs --- cargo-0.25.0/vendor/env_logger-0.5.7/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,944 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A simple logger configured via environment variables which writes +//! to stdout or stderr, for use with the logging facade exposed by the +//! [`log` crate][log-crate-url]. +//! +//! ## Example +//! +//! ``` +//! #[macro_use] extern crate log; +//! extern crate env_logger; +//! +//! use log::Level; +//! +//! fn main() { +//! env_logger::init(); +//! +//! debug!("this is a debug {}", "message"); +//! error!("this is printed by default"); +//! +//! if log_enabled!(Level::Info) { +//! let x = 3 * 4; // expensive computation +//! info!("the answer was: {}", x); +//! } +//! } +//! ``` +//! +//! Assumes the binary is `main`: +//! +//! ```{.bash} +//! $ RUST_LOG=error ./main +//! ERROR: 2017-11-09T02:12:24Z: main: this is printed by default +//! ``` +//! +//! ```{.bash} +//! $ RUST_LOG=info ./main +//! ERROR: 2017-11-09T02:12:24Z: main: this is printed by default +//! INFO: 2017-11-09T02:12:24Z: main: the answer was: 12 +//! ``` +//! +//! ```{.bash} +//! $ RUST_LOG=debug ./main +//! DEBUG: 2017-11-09T02:12:24Z: main: this is a debug message +//! ERROR: 2017-11-09T02:12:24Z: main: this is printed by default +//! INFO: 2017-11-09T02:12:24Z: main: the answer was: 12 +//! ``` +//! +//! You can also set the log level on a per module basis: +//! +//! ```{.bash} +//! $ RUST_LOG=main=info ./main +//! ERROR: 2017-11-09T02:12:24Z: main: this is printed by default +//! INFO: 2017-11-09T02:12:24Z: main: the answer was: 12 +//! ``` +//! +//! And enable all logging: +//! +//! ```{.bash} +//! $ RUST_LOG=main ./main +//! DEBUG: 2017-11-09T02:12:24Z: main: this is a debug message +//! ERROR: 2017-11-09T02:12:24Z: main: this is printed by default +//! INFO: 2017-11-09T02:12:24Z: main: the answer was: 12 +//! ``` +//! +//! If the binary name contains hyphens, you will need to replace +//! them with underscores: +//! +//! ```{.bash} +//! $ RUST_LOG=my_app ./my-app +//! DEBUG: 2017-11-09T02:12:24Z: my_app: this is a debug message +//! ERROR: 2017-11-09T02:12:24Z: my_app: this is printed by default +//! INFO: 2017-11-09T02:12:24Z: my_app: the answer was: 12 +//! ``` +//! +//! This is because Rust modules and crates cannot contain hyphens +//! in their name, although `cargo` continues to accept them. +//! +//! See the documentation for the [`log` crate][log-crate-url] for more +//! information about its API. +//! +//! ## Enabling logging +//! +//! Log levels are controlled on a per-module basis, and by default all logging +//! is disabled except for `error!`. Logging is controlled via the `RUST_LOG` +//! environment variable. The value of this environment variable is a +//! comma-separated list of logging directives. A logging directive is of the +//! form: +//! +//! ```text +//! path::to::module=level +//! ``` +//! +//! The path to the module is rooted in the name of the crate it was compiled +//! for, so if your program is contained in a file `hello.rs`, for example, to +//! turn on logging for this file you would use a value of `RUST_LOG=hello`. +//! Furthermore, this path is a prefix-search, so all modules nested in the +//! specified module will also have logging enabled. +//! +//! The actual `level` is optional to specify. If omitted, all logging will +//! be enabled. If specified, it must be one of the strings `debug`, `error`, +//! `info`, `warn`, or `trace`. +//! +//! As the log level for a module is optional, the module to enable logging for +//! is also optional. If only a `level` is provided, then the global log +//! level for all modules is set to this value. +//! +//! Some examples of valid values of `RUST_LOG` are: +//! +//! * `hello` turns on all logging for the 'hello' module +//! * `info` turns on all info logging +//! * `hello=debug` turns on debug logging for 'hello' +//! * `hello,std::option` turns on hello, and std's option logging +//! * `error,hello=warn` turn on global error logging and also warn for hello +//! +//! ## Filtering results +//! +//! A `RUST_LOG` directive may include a regex filter. The syntax is to append `/` +//! followed by a regex. Each message is checked against the regex, and is only +//! logged if it matches. Note that the matching is done after formatting the +//! log string but before adding any logging meta-data. There is a single filter +//! for all modules. +//! +//! Some examples: +//! +//! * `hello/foo` turns on all logging for the 'hello' module where the log +//! message includes 'foo'. +//! * `info/f.o` turns on all info logging where the log message includes 'foo', +//! 'f1o', 'fao', etc. +//! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log +//! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc. +//! * `error,hello=warn/[0-9]scopes` turn on global error logging and also +//! warn for hello. In both cases the log message must include a single digit +//! number followed by 'scopes'. +//! +//! ## Disabling colors +//! +//! Colors and other styles can be configured with the `RUST_LOG_STYLE` +//! environment variable. It accepts the following values: +//! +//! * `auto` (default) will attempt to print style characters, but don't force the issue. +//! If the console isn't available on Windows, or if TERM=dumb, for example, then don't print colors. +//! * `always` will always print style characters even if they aren't supported by the terminal. +//! This includes emitting ANSI colors on Windows if the console API is unavailable. +//! * `never` will never print style characters. +//! +//! ## Tweaking the default format +//! +//! Parts of the default format can be excluded from the log output using the [`Builder`]. +//! The following example excluding the timestamp from the log output: +//! +//! ``` +//! #[macro_use] extern crate log; +//! extern crate env_logger; +//! +//! use log::Level; +//! +//! fn main() { +//! env_logger::Builder::from_default_env() +//! .default_format_timestamp(false) +//! .init(); +//! +//! debug!("this is a debug {}", "message"); +//! error!("this is printed by default"); +//! +//! if log_enabled!(Level::Info) { +//! let x = 3 * 4; // expensive computation +//! info!("the answer was: {}", x); +//! } +//! } +//! ``` +//! +//! [log-crate-url]: https://docs.rs/log/ +//! [`Builder`]: struct.Builder.html + +#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "http://www.rust-lang.org/favicon.ico", + html_root_url = "https://docs.rs/env_logger/0.5.7")] +#![cfg_attr(test, deny(warnings))] + +// When compiled for the rustc compiler itself we want to make sure that this is +// an unstable crate +#![cfg_attr(rustbuild, feature(staged_api, rustc_private))] +#![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))] + +#![deny(missing_debug_implementations, missing_docs, warnings)] + +extern crate log; +extern crate termcolor; +extern crate humantime; +extern crate atty; + +use std::env; +use std::borrow::Cow; +use std::io::prelude::*; +use std::io; +use std::mem; +use std::cell::RefCell; + +use log::{Log, LevelFilter, Level, Record, SetLoggerError, Metadata}; + +pub mod filter; +pub mod fmt; + +pub use self::fmt::{Target, WriteStyle, Color, Formatter}; + +const DEFAULT_FILTER_ENV: &'static str = "RUST_LOG"; +const DEFAULT_WRITE_STYLE_ENV: &'static str = "RUST_LOG_STYLE"; + +/// Set of environment variables to configure from. +/// +/// # Default environment variables +/// +/// By default, the `Env` will read the following environment variables: +/// +/// - `RUST_LOG`: the level filter +/// - `RUST_LOG_STYLE`: whether or not to print styles with records. +/// +/// These sources can be configured using the builder methods on `Env`. +#[derive(Debug)] +pub struct Env<'a> { + filter: Cow<'a, str>, + write_style: Cow<'a, str>, +} + +/// The env logger. +/// +/// This struct implements the `Log` trait from the [`log` crate][log-crate-url], +/// which allows it to act as a logger. +/// +/// The [`init()`], [`try_init()`], [`Builder::init()`] and [`Builder::try_init()`] +/// methods will each construct a `Logger` and immediately initialize it as the +/// default global logger. +/// +/// If you'd instead need access to the constructed `Logger`, you can use +/// the associated [`Builder`] and install it with the +/// [`log` crate][log-crate-url] directly. +/// +/// [log-crate-url]: https://docs.rs/log/ +/// [`init()`]: fn.init.html +/// [`try_init()`]: fn.try_init.html +/// [`Builder::init()`]: struct.Builder.html#method.init +/// [`Builder::try_init()`]: struct.Builder.html#method.try_init +/// [`Builder`]: struct.Builder.html +pub struct Logger { + writer: fmt::Writer, + filter: filter::Filter, + format: Box io::Result<()> + Sync + Send>, +} + +struct Format { + default_format_timestamp: bool, + default_format_module_path: bool, + default_format_level: bool, + custom_format: Option io::Result<()> + Sync + Send>>, +} + +impl Default for Format { + fn default() -> Self { + Format { + default_format_timestamp: true, + default_format_module_path: true, + default_format_level: true, + custom_format: None, + } + } +} + +impl Format { + /// Convert the format into a callable function. + /// + /// If the `custom_format` is `Some`, then any `default_format` switches are ignored. + /// If the `custom_format` is `None`, then a default format is returned. + /// Any `default_format` switches set to `false` won't be written by the format. + fn into_boxed_fn(self) -> Box io::Result<()> + Sync + Send> { + if let Some(fmt) = self.custom_format { + fmt + } + else { + Box::new(move |buf, record| { + let write_level = if self.default_format_level { + let level = record.level(); + let mut level_style = buf.style(); + + match level { + Level::Trace => level_style.set_color(Color::White), + Level::Debug => level_style.set_color(Color::Blue), + Level::Info => level_style.set_color(Color::Green), + Level::Warn => level_style.set_color(Color::Yellow), + Level::Error => level_style.set_color(Color::Red).set_bold(true), + }; + + write!(buf, "{:>5} ", level_style.value(level)) + } else { + Ok(()) + }; + + let write_ts = if self.default_format_timestamp { + let ts = buf.timestamp(); + write!(buf, "{}: ", ts) + } else { + Ok(()) + }; + + let default_format_module_path = (self.default_format_module_path, record.module_path()); + let write_module_path = if let (true, Some(module_path)) = default_format_module_path { + write!(buf, "{}: ", module_path) + } else { + Ok(()) + }; + + let write_args = writeln!(buf, "{}", record.args()); + + write_level.and(write_ts).and(write_module_path).and(write_args) + }) + } + } +} + +/// `Builder` acts as builder for initializing a `Logger`. +/// +/// It can be used to customize the log format, change the environment variable used +/// to provide the logging directives and also set the default log level filter. +/// +/// # Examples +/// +/// ``` +/// #[macro_use] +/// extern crate log; +/// extern crate env_logger; +/// +/// use std::env; +/// use std::io::Write; +/// use log::LevelFilter; +/// use env_logger::Builder; +/// +/// fn main() { +/// let mut builder = Builder::from_default_env(); +/// +/// builder.format(|buf, record| writeln!(buf, "{} - {}", record.level(), record.args())) +/// .filter(None, LevelFilter::Info) +/// .init(); +/// +/// error!("error message"); +/// info!("info message"); +/// } +/// ``` +#[derive(Default)] +pub struct Builder { + filter: filter::Builder, + writer: fmt::Builder, + format: Format, +} + +impl Builder { + /// Initializes the log builder with defaults. + /// + /// **NOTE:** This method won't read from any environment variables. + /// Use the [`filter`] and [`write_style`] methods to configure the builder + /// or use [`from_env`] or [`from_default_env`] instead. + /// + /// # Examples + /// + /// Create a new builder and configure filters and style: + /// + /// ``` + /// # extern crate log; + /// # extern crate env_logger; + /// # fn main() { + /// use log::LevelFilter; + /// use env_logger::{Builder, WriteStyle}; + /// + /// let mut builder = Builder::new(); + /// + /// builder.filter(None, LevelFilter::Info) + /// .write_style(WriteStyle::Always) + /// .init(); + /// # } + /// ``` + /// + /// [`filter`]: #method.filter + /// [`write_style`]: #method.write_style + /// [`from_env`]: #method.from_env + /// [`from_default_env`]: #method.from_default_env + pub fn new() -> Builder { + Default::default() + } + + /// Initializes the log builder from the environment. + /// + /// The variables used to read configuration from can be tweaked before + /// passing in. + /// + /// # Examples + /// + /// Initialise a logger reading the log filter from an environment variable + /// called `MY_LOG`: + /// + /// ``` + /// use env_logger::Builder; + /// + /// let mut builder = Builder::from_env("MY_LOG"); + /// builder.init(); + /// ``` + /// + /// Initialise a logger using the `MY_LOG` variable for filtering and + /// `MY_LOG_STYLE` for whether or not to write styles: + /// + /// ``` + /// use env_logger::{Builder, Env}; + /// + /// let env = Env::new().filter("MY_LOG").write_style("MY_LOG_STYLE"); + /// + /// let mut builder = Builder::from_env(env); + /// builder.init(); + /// ``` + pub fn from_env<'a, E>(env: E) -> Self + where + E: Into> + { + let mut builder = Builder::new(); + let env = env.into(); + + if let Some(s) = env.get_filter() { + builder.parse(&s); + } + + if let Some(s) = env.get_write_style() { + builder.parse_write_style(&s); + } + + builder + } + + /// Initializes the log builder from the environment using default variable names. + /// + /// This method is a convenient way to call `from_env(Env::default())` without + /// having to use the `Env` type explicitly. The builder will use the + /// [default environment variables]. + /// + /// # Examples + /// + /// Initialise a logger using the default environment variables: + /// + /// ``` + /// use env_logger::Builder; + /// + /// let mut builder = Builder::from_default_env(); + /// builder.init(); + /// ``` + /// + /// [default environment variables]: struct.Env.html#default-environment-variables + pub fn from_default_env() -> Self { + Self::from_env(Env::default()) + } + + /// Sets the format function for formatting the log output. + /// + /// This function is called on each record logged and should format the + /// log record and output it to the given [`Formatter`]. + /// + /// The format function is expected to output the string directly to the + /// `Formatter` so that implementations can use the [`std::fmt`] macros + /// to format and output without intermediate heap allocations. The default + /// `env_logger` formatter takes advantage of this. + /// + /// # Examples + /// + /// Use a custom format to write only the log message: + /// + /// ``` + /// use std::io::Write; + /// use env_logger::Builder; + /// + /// let mut builder = Builder::new(); + /// + /// builder.format(|buf, record| write!(buf, "{}", record.args())); + /// ``` + /// + /// [`Formatter`]: fmt/struct.Formatter.html + /// [`String`]: https://doc.rust-lang.org/stable/std/string/struct.String.html + /// [`std::fmt`]: https://doc.rust-lang.org/std/fmt/index.html + pub fn format(&mut self, format: F) -> &mut Self + where F: Fn(&mut Formatter, &Record) -> io::Result<()> + Sync + Send + { + self.format.custom_format = Some(Box::new(format)); + self + } + + /// Use the default format. + /// + /// This method will clear any custom format set on the builder. + pub fn default_format(&mut self) -> &mut Self { + self.format.custom_format = None; + self + } + + /// Whether or not to write the level in the default format. + pub fn default_format_level(&mut self, write: bool) -> &mut Self { + self.format.default_format_level = write; + self + } + + /// Whether or not to write the module path in the default format. + pub fn default_format_module_path(&mut self, write: bool) -> &mut Self { + self.format.default_format_module_path = write; + self + } + + /// Whether or not to write the timestamp in the default format. + pub fn default_format_timestamp(&mut self, write: bool) -> &mut Self { + self.format.default_format_timestamp = write; + self + } + + /// Adds filters to the logger. + /// + /// The given module (if any) will log at most the specified level provided. + /// If no module is provided then the filter will apply to all log messages. + /// + /// # Examples + /// + /// Only include messages for warning and above for logs in `path::to::module`: + /// + /// ``` + /// # extern crate log; + /// # extern crate env_logger; + /// # fn main() { + /// use log::LevelFilter; + /// use env_logger::Builder; + /// + /// let mut builder = Builder::new(); + /// + /// builder.filter(Some("path::to::module"), LevelFilter::Info); + /// # } + /// ``` + pub fn filter(&mut self, + module: Option<&str>, + level: LevelFilter) -> &mut Self { + self.filter.filter(module, level); + self + } + + /// Parses the directives string in the same form as the `RUST_LOG` + /// environment variable. + /// + /// See the module documentation for more details. + pub fn parse(&mut self, filters: &str) -> &mut Self { + self.filter.parse(filters); + self + } + + /// Sets the target for the log output. + /// + /// Env logger can log to either stdout or stderr. The default is stderr. + /// + /// # Examples + /// + /// Write log message to `stdout`: + /// + /// ``` + /// use env_logger::{Builder, Target}; + /// + /// let mut builder = Builder::new(); + /// + /// builder.target(Target::Stdout); + /// ``` + pub fn target(&mut self, target: fmt::Target) -> &mut Self { + self.writer.target(target); + self + } + + /// Sets whether or not styles will be written. + /// + /// This can be useful in environments that don't support control characters + /// for setting colors. + /// + /// # Examples + /// + /// Never attempt to write styles: + /// + /// ``` + /// use env_logger::{Builder, WriteStyle}; + /// + /// let mut builder = Builder::new(); + /// + /// builder.write_style(WriteStyle::Never); + /// ``` + pub fn write_style(&mut self, write_style: fmt::WriteStyle) -> &mut Self { + self.writer.write_style(write_style); + self + } + + /// Parses whether or not to write styles in the same form as the `RUST_LOG_STYLE` + /// environment variable. + /// + /// See the module documentation for more details. + pub fn parse_write_style(&mut self, write_style: &str) -> &mut Self { + self.writer.parse(write_style); + self + } + + /// Initializes the global logger with the built env logger. + /// + /// This should be called early in the execution of a Rust program. Any log + /// events that occur before initialization will be ignored. + /// + /// # Errors + /// + /// This function will fail if it is called more than once, or if another + /// library has already initialized a global logger. + pub fn try_init(&mut self) -> Result<(), SetLoggerError> { + let logger = self.build(); + + log::set_max_level(logger.filter()); + log::set_boxed_logger(Box::new(logger)) + } + + /// Initializes the global logger with the built env logger. + /// + /// This should be called early in the execution of a Rust program. Any log + /// events that occur before initialization will be ignored. + /// + /// # Panics + /// + /// This function will panic if it is called more than once, or if another + /// library has already initialized a global logger. + pub fn init(&mut self) { + self.try_init().expect("Builder::init should not be called after logger initialized"); + } + + /// Build an env logger. + /// + /// The returned logger implements the `Log` trait and can be installed manually + /// or nested within another logger. + pub fn build(&mut self) -> Logger { + Logger { + writer: self.writer.build(), + filter: self.filter.build(), + format: mem::replace(&mut self.format, Default::default()).into_boxed_fn(), + } + } +} + +impl Logger { + /// Creates the logger from the environment. + /// + /// The variables used to read configuration from can be tweaked before + /// passing in. + /// + /// # Examples + /// + /// Create a logger reading the log filter from an environment variable + /// called `MY_LOG`: + /// + /// ``` + /// use env_logger::Logger; + /// + /// let logger = Logger::from_env("MY_LOG"); + /// ``` + /// + /// Create a logger using the `MY_LOG` variable for filtering and + /// `MY_LOG_STYLE` for whether or not to write styles: + /// + /// ``` + /// use env_logger::{Logger, Env}; + /// + /// let env = Env::new().filter("MY_LOG").write_style("MY_LOG_STYLE"); + /// + /// let logger = Logger::from_env(env); + /// ``` + pub fn from_env<'a, E>(env: E) -> Self + where + E: Into> + { + Builder::from_env(env).build() + } + + /// Creates the logger from the environment using default variable names. + /// + /// This method is a convenient way to call `from_env(Env::default())` without + /// having to use the `Env` type explicitly. The logger will use the + /// [default environment variables]. + /// + /// # Examples + /// + /// Creates a logger using the default environment variables: + /// + /// ``` + /// use env_logger::Logger; + /// + /// let logger = Logger::from_default_env(); + /// ``` + /// + /// [default environment variables]: struct.Env.html#default-environment-variables + pub fn from_default_env() -> Self { + Builder::from_default_env().build() + } + + /// Returns the maximum `LevelFilter` that this env logger instance is + /// configured to output. + pub fn filter(&self) -> LevelFilter { + self.filter.filter() + } + + /// Checks if this record matches the configured filter. + pub fn matches(&self, record: &Record) -> bool { + self.filter.matches(record) + } +} + +impl Log for Logger { + fn enabled(&self, metadata: &Metadata) -> bool { + self.filter.enabled(metadata) + } + + fn log(&self, record: &Record) { + if self.matches(record) { + // Log records are written to a thread-local buffer before being printed + // to the terminal. We clear these buffers afterwards, but they aren't shrinked + // so will always at least have capacity for the largest log record formatted + // on that thread. + // + // If multiple `Logger`s are used by the same threads then the thread-local + // formatter might have different color support. If this is the case the + // formatter and its buffer are discarded and recreated. + + thread_local! { + static FORMATTER: RefCell> = RefCell::new(None); + } + + FORMATTER.with(|tl_buf| { + // It's possible for implementations to sometimes + // log-while-logging (e.g. a `std::fmt` implementation logs + // internally) but it's super rare. If this happens make sure we + // at least don't panic and ship some output to the screen. + let mut a; + let mut b = None; + let tl_buf = match tl_buf.try_borrow_mut() { + Ok(f) => { + a = f; + &mut *a + } + Err(_) => &mut b, + }; + + // Check the buffer style. If it's different from the logger's + // style then drop the buffer and recreate it. + match *tl_buf { + Some(ref mut formatter) => { + if formatter.write_style() != self.writer.write_style() { + *formatter = Formatter::new(&self.writer) + } + }, + ref mut tl_buf => *tl_buf = Some(Formatter::new(&self.writer)) + } + + // The format is guaranteed to be `Some` by this point + let mut formatter = tl_buf.as_mut().unwrap(); + + let _ = (self.format)(&mut formatter, record).and_then(|_| formatter.print(&self.writer)); + + // Always clear the buffer afterwards + formatter.clear(); + }); + } + } + + fn flush(&self) {} +} + +impl<'a> Env<'a> { + /// Get a default set of environment variables. + pub fn new() -> Self { + Self::default() + } + + /// Specify an environment variable to read the filter from. + pub fn filter(mut self, filter_env: E) -> Self + where + E: Into> + { + self.filter = filter_env.into(); + self + } + + fn get_filter(&self) -> Option { + env::var(&*self.filter).ok() + } + + /// Specify an environment variable to read the style from. + pub fn write_style(mut self, write_style_env: E) -> Self + where + E: Into> + { + self.write_style = write_style_env.into(); + self + } + + fn get_write_style(&self) -> Option { + env::var(&*self.write_style).ok() + } +} + +impl<'a, T> From for Env<'a> +where + T: Into> +{ + fn from(filter_env: T) -> Self { + Env::default().filter(filter_env.into()) + } +} + +impl<'a> Default for Env<'a> { + fn default() -> Self { + Env { + filter: DEFAULT_FILTER_ENV.into(), + write_style: DEFAULT_WRITE_STYLE_ENV.into() + } + } +} + +mod std_fmt_impls { + use std::fmt; + use super::*; + + impl fmt::Debug for Logger{ + fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result { + f.debug_struct("Logger") + .field("filter", &self.filter) + .finish() + } + } + + impl fmt::Debug for Builder{ + fn fmt(&self, f: &mut fmt::Formatter)->fmt::Result { + f.debug_struct("Logger") + .field("filter", &self.filter) + .field("writer", &self.writer) + .finish() + } + } +} + +/// Attempts to initialize the global logger with an env logger. +/// +/// This should be called early in the execution of a Rust program. Any log +/// events that occur before initialization will be ignored. +/// +/// # Errors +/// +/// This function will fail if it is called more than once, or if another +/// library has already initialized a global logger. +pub fn try_init() -> Result<(), SetLoggerError> { + try_init_from_env(Env::default()) +} + +/// Initializes the global logger with an env logger. +/// +/// This should be called early in the execution of a Rust program. Any log +/// events that occur before initialization will be ignored. +/// +/// # Panics +/// +/// This function will panic if it is called more than once, or if another +/// library has already initialized a global logger. +pub fn init() { + try_init().expect("env_logger::init should not be called after logger initialized"); +} + +/// Attempts to initialize the global logger with an env logger from the given +/// environment variables. +/// +/// This should be called early in the execution of a Rust program. Any log +/// events that occur before initialization will be ignored. +/// +/// # Examples +/// +/// Initialise a logger using the `MY_LOG` environment variable for filters +/// and `MY_LOG_STYLE` for writing colors: +/// +/// ``` +/// # extern crate env_logger; +/// use env_logger::{Builder, Env}; +/// +/// # fn run() -> Result<(), Box<::std::error::Error>> { +/// let env = Env::new().filter("MY_LOG").write_style("MY_LOG_STYLE"); +/// +/// env_logger::try_init_from_env(env)?; +/// +/// Ok(()) +/// # } +/// # fn main() { run().unwrap(); } +/// ``` +/// +/// # Errors +/// +/// This function will fail if it is called more than once, or if another +/// library has already initialized a global logger. +pub fn try_init_from_env<'a, E>(env: E) -> Result<(), SetLoggerError> +where + E: Into> +{ + let mut builder = Builder::from_env(env); + + builder.try_init() +} + +/// Initializes the global logger with an env logger from the given environment +/// variables. +/// +/// This should be called early in the execution of a Rust program. Any log +/// events that occur before initialization will be ignored. +/// +/// # Examples +/// +/// Initialise a logger using the `MY_LOG` environment variable for filters +/// and `MY_LOG_STYLE` for writing colors: +/// +/// ``` +/// use env_logger::{Builder, Env}; +/// +/// let env = Env::new().filter("MY_LOG").write_style("MY_LOG_STYLE"); +/// +/// env_logger::init_from_env(env); +/// ``` +/// +/// # Panics +/// +/// This function will panic if it is called more than once, or if another +/// library has already initialized a global logger. +pub fn init_from_env<'a, E>(env: E) +where + E: Into> +{ + try_init_from_env(env).expect("env_logger::init_from_env should not be called after logger initialized"); +} diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/tests/log-in-log.rs cargo-0.26.0/vendor/env_logger-0.5.7/tests/log-in-log.rs --- cargo-0.25.0/vendor/env_logger-0.5.7/tests/log-in-log.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/tests/log-in-log.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,38 @@ +#[macro_use] extern crate log; +extern crate env_logger; + +use std::process; +use std::fmt; +use std::env; +use std::str; + +struct Foo; + +impl fmt::Display for Foo { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + info!("test"); + f.write_str("bar") + } +} + +fn main() { + env_logger::init(); + if env::var("YOU_ARE_TESTING_NOW").is_ok() { + return info!("{}", Foo); + } + + let exe = env::current_exe().unwrap(); + let out = process::Command::new(exe) + .env("YOU_ARE_TESTING_NOW", "1") + .env("RUST_LOG", "debug") + .output() + .unwrap_or_else(|e| panic!("Unable to start child process: {}", e)); + if out.status.success() { + return + } + + println!("test failed: {}", out.status); + println!("--- stdout\n{}", str::from_utf8(&out.stdout).unwrap()); + println!("--- stderr\n{}", str::from_utf8(&out.stderr).unwrap()); + process::exit(1); +} diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/tests/regexp_filter.rs cargo-0.26.0/vendor/env_logger-0.5.7/tests/regexp_filter.rs --- cargo-0.25.0/vendor/env_logger-0.5.7/tests/regexp_filter.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/tests/regexp_filter.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,51 @@ +#[macro_use] extern crate log; +extern crate env_logger; + +use std::process; +use std::env; +use std::str; + +fn main() { + if env::var("LOG_REGEXP_TEST").ok() == Some(String::from("1")) { + child_main(); + } else { + parent_main() + } +} + +fn child_main() { + env_logger::init(); + info!("XYZ Message"); +} + +fn run_child(rust_log: String) -> bool { + let exe = env::current_exe().unwrap(); + let out = process::Command::new(exe) + .env("LOG_REGEXP_TEST", "1") + .env("RUST_LOG", rust_log) + .output() + .unwrap_or_else(|e| panic!("Unable to start child process: {}", e)); + str::from_utf8(out.stderr.as_ref()).unwrap().contains("XYZ Message") +} + +fn assert_message_printed(rust_log: &str) { + if !run_child(rust_log.to_string()) { + panic!("RUST_LOG={} should allow the test log message", rust_log) + } +} + +fn assert_message_not_printed(rust_log: &str) { + if run_child(rust_log.to_string()) { + panic!("RUST_LOG={} should not allow the test log message", rust_log) + } +} + +fn parent_main() { + // test normal log severity levels + assert_message_printed("info"); + assert_message_not_printed("warn"); + + // test of regular expression filters + assert_message_printed("info/XYZ"); + assert_message_not_printed("info/XXX"); +} diff -Nru cargo-0.25.0/vendor/env_logger-0.5.7/.travis.yml cargo-0.26.0/vendor/env_logger-0.5.7/.travis.yml --- cargo-0.25.0/vendor/env_logger-0.5.7/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/env_logger-0.5.7/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +language: rust +sudo: false +rust: + - 1.18.0 + - stable + - beta + - nightly +before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH +script: + - cargo build --verbose + - cargo build --verbose --no-default-features + - cargo test --verbose + - cargo test --verbose --no-default-features +after_success: + - travis-cargo --only nightly doc-upload + +notifications: + email: +on_success: never diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/appveyor.yml cargo-0.26.0/vendor/filetime-0.2.0/appveyor.yml --- cargo-0.25.0/vendor/filetime-0.2.0/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,17 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --verbose --target %TARGET% diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/.cargo-checksum.json cargo-0.26.0/vendor/filetime-0.2.0/.cargo-checksum.json --- cargo-0.25.0/vendor/filetime-0.2.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"08530a39af0bd442c40aabb9e854f442a83bd2403feb1ed58fbe982dec2385f3"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/Cargo.toml cargo-0.26.0/vendor/filetime-0.2.0/Cargo.toml --- cargo-0.25.0/vendor/filetime-0.2.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,31 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "filetime" +version = "0.2.0" +authors = ["Alex Crichton "] +description = "Platform-agnostic accessors of timestamps in File metadata\n" +homepage = "https://github.com/alexcrichton/filetime" +documentation = "http://alexcrichton.com/filetime" +readme = "README.md" +keywords = ["timestamp", "mtime"] +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/filetime" +[dependencies.cfg-if] +version = "0.1" +[dev-dependencies.tempdir] +version = "0.3" +[target."cfg(target_os = \"redox\")".dependencies.redox_syscall] +version = "0.1" +[target."cfg(unix)".dependencies.libc] +version = "0.2" diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/LICENSE-APACHE cargo-0.26.0/vendor/filetime-0.2.0/LICENSE-APACHE --- cargo-0.25.0/vendor/filetime-0.2.0/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/LICENSE-MIT cargo-0.26.0/vendor/filetime-0.2.0/LICENSE-MIT --- cargo-0.25.0/vendor/filetime-0.2.0/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +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. diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/README.md cargo-0.26.0/vendor/filetime-0.2.0/README.md --- cargo-0.25.0/vendor/filetime-0.2.0/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,34 @@ +# filetime + +[![Build Status](https://travis-ci.org/alexcrichton/filetime.svg?branch=master)](https://travis-ci.org/alexcrichton/filetime) +[![Build status](https://ci.appveyor.com/api/projects/status/9tatexq47i3ee13k?svg=true)](https://ci.appveyor.com/project/alexcrichton/filetime) + +[Documentation](http://alexcrichton.com/filetime/filetime/index.html) + +A helper library for inspecting the various timestamps of files in Rust. This +library takes into account cross-platform differences in terms of where the +timestamps are located, what they are called, and how to convert them into a +platform-independent representation. + +```toml +# Cargo.toml +[dependencies] +filetime = "0.2" +``` + +# License + +This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/src/lib.rs cargo-0.26.0/vendor/filetime-0.2.0/src/lib.rs --- cargo-0.25.0/vendor/filetime-0.2.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,429 @@ +//! Timestamps for files in Rust +//! +//! This library provides platform-agnostic inspection of the various timestamps +//! present in the standard `fs::Metadata` structure. +//! +//! # Installation +//! +//! Add this to your `Cargo.toml`: +//! +//! ```toml +//! [dependencies] +//! filetime = "0.1" +//! ``` +//! +//! # Usage +//! +//! ```no_run +//! use std::fs; +//! use filetime::FileTime; +//! +//! let metadata = fs::metadata("foo.txt").unwrap(); +//! +//! let mtime = FileTime::from_last_modification_time(&metadata); +//! println!("{}", mtime); +//! +//! let atime = FileTime::from_last_access_time(&metadata); +//! assert!(mtime < atime); +//! +//! // Inspect values that can be interpreted across platforms +//! println!("{}", mtime.unix_seconds()); +//! println!("{}", mtime.nanoseconds()); +//! +//! // Print the platform-specific value of seconds +//! println!("{}", mtime.seconds()); +//! ``` + +#[macro_use] +extern crate cfg_if; + +use std::fmt; +use std::fs; +use std::io; +use std::path::Path; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +cfg_if! { + if #[cfg(target_os = "redox")] { + #[path = "redox.rs"] + mod imp; + } else if #[cfg(windows)] { + #[path = "windows.rs"] + mod imp; + } else { + #[path = "unix/mod.rs"] + mod imp; + } +} + +/// A helper structure to represent a timestamp for a file. +/// +/// The actual value contined within is platform-specific and does not have the +/// same meaning across platforms, but comparisons and stringification can be +/// significant among the same platform. +#[derive(Eq, PartialEq, Ord, PartialOrd, Debug, Copy, Clone, Hash)] +pub struct FileTime { + seconds: i64, + nanos: u32, +} + +impl FileTime { + /// Creates a new timestamp representing a 0 time. + /// + /// Useful for creating the base of a cmp::max chain of times. + pub fn zero() -> FileTime { + FileTime { seconds: 0, nanos: 0 } + } + + /// Creates a new instance of `FileTime` with a number of seconds and + /// nanoseconds relative to the Unix epoch, 1970-01-01T00:00:00Z. + /// + /// Negative seconds represent times before the Unix epoch, and positive + /// values represent times after it. Nanos always count forwards in time. + /// + /// Note that this is typically the relative point that Unix time stamps are + /// from, but on Windows the native time stamp is relative to January 1, + /// 1601 so the return value of `seconds` from the returned `FileTime` + /// instance may not be the same as that passed in. + pub fn from_unix_time(seconds: i64, nanos: u32) -> FileTime { + FileTime { + seconds: seconds + if cfg!(windows) {11644473600} else {0}, + nanos, + } + } + + /// Creates a new timestamp from the last modification time listed in the + /// specified metadata. + /// + /// The returned value corresponds to the `mtime` field of `stat` on Unix + /// platforms and the `ftLastWriteTime` field on Windows platforms. + pub fn from_last_modification_time(meta: &fs::Metadata) -> FileTime { + imp::from_last_modification_time(meta) + } + + /// Creates a new timestamp from the last access time listed in the + /// specified metadata. + /// + /// The returned value corresponds to the `atime` field of `stat` on Unix + /// platforms and the `ftLastAccessTime` field on Windows platforms. + pub fn from_last_access_time(meta: &fs::Metadata) -> FileTime { + imp::from_last_access_time(meta) + } + + /// Creates a new timestamp from the creation time listed in the specified + /// metadata. + /// + /// The returned value corresponds to the `birthtime` field of `stat` on + /// Unix platforms and the `ftCreationTime` field on Windows platforms. Note + /// that not all Unix platforms have this field available and may return + /// `None` in some circumstances. + pub fn from_creation_time(meta: &fs::Metadata) -> Option { + imp::from_creation_time(meta) + } + + /// Creates a new timestamp from the given SystemTime. + /// + /// Windows counts file times since 1601-01-01T00:00:00Z, and cannot + /// represent times before this, but it's possible to create a SystemTime + /// that does. This function will error if passed such a SystemTime. + pub fn from_system_time(time: SystemTime) -> FileTime { + let epoch = if cfg!(windows) { + UNIX_EPOCH - Duration::from_secs(11644473600) + } else { + UNIX_EPOCH + }; + + time.duration_since(epoch).map(|d| FileTime { + seconds: d.as_secs() as i64, + nanos: d.subsec_nanos() + }) + .unwrap_or_else(|e| { + let until_epoch = e.duration(); + let (sec_offset, nanos) = if until_epoch.subsec_nanos() == 0 { + (0, 0) + } else { + (-1, 1_000_000_000 - until_epoch.subsec_nanos()) + }; + + FileTime { + seconds: -1 * until_epoch.as_secs() as i64 + sec_offset, + nanos + } + }) + } + + /// Returns the whole number of seconds represented by this timestamp. + /// + /// Note that this value's meaning is **platform specific**. On Unix + /// platform time stamps are typically relative to January 1, 1970, but on + /// Windows platforms time stamps are relative to January 1, 1601. + pub fn seconds(&self) -> i64 { self.seconds } + + /// Returns the whole number of seconds represented by this timestamp, + /// relative to the Unix epoch start of January 1, 1970. + /// + /// Note that this does not return the same value as `seconds` for Windows + /// platforms as seconds are relative to a different date there. + pub fn unix_seconds(&self) -> i64 { + self.seconds - if cfg!(windows) {11644473600} else {0} + } + + /// Returns the nanosecond precision of this timestamp. + /// + /// The returned value is always less than one billion and represents a + /// portion of a second forward from the seconds returned by the `seconds` + /// method. + pub fn nanoseconds(&self) -> u32 { self.nanos } +} + +impl fmt::Display for FileTime { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}.{:09}s", self.seconds, self.nanos) + } +} + +/// Set the last access and modification times for a file on the filesystem. +/// +/// This function will set the `atime` and `mtime` metadata fields for a file +/// on the local filesystem, returning any error encountered. +pub fn set_file_times

(p: P, atime: FileTime, mtime: FileTime) + -> io::Result<()> + where P: AsRef +{ + imp::set_file_times(p.as_ref(), atime, mtime) +} + +/// Set the last access and modification times for a file on the filesystem. +/// This function does not follow symlink. +/// +/// This function will set the `atime` and `mtime` metadata fields for a file +/// on the local filesystem, returning any error encountered. +pub fn set_symlink_file_times

(p: P, atime: FileTime, mtime: FileTime) + -> io::Result<()> + where P: AsRef +{ + imp::set_symlink_file_times(p.as_ref(), atime, mtime) +} + +#[cfg(test)] +mod tests { + extern crate tempdir; + + use std::io; + use std::path::Path; + use std::fs::{self, File}; + use self::tempdir::TempDir; + use super::{FileTime, set_file_times, set_symlink_file_times}; + use std::time::{Duration, UNIX_EPOCH}; + + #[cfg(unix)] + fn make_symlink(src: P, dst: Q) -> io::Result<()> + where P: AsRef, + Q: AsRef, + { + use std::os::unix::fs::symlink; + symlink(src, dst) + } + + #[cfg(windows)] + fn make_symlink(src: P, dst: Q) -> io::Result<()> + where P: AsRef, + Q: AsRef, + { + use std::os::windows::fs::symlink_file; + symlink_file(src, dst) + } + + #[test] + #[cfg(windows)] + fn from_unix_time_test() { + let time = FileTime::from_unix_time(10, 100_000_000); + assert_eq!(11644473610, time.seconds); + assert_eq!(100_000_000, time.nanos); + + let time = FileTime::from_unix_time(-10, 100_000_000); + assert_eq!(11644473590, time.seconds); + assert_eq!(100_000_000, time.nanos); + + let time = FileTime::from_unix_time(-12_000_000_000, 0); + assert_eq!(-355526400, time.seconds); + assert_eq!(0, time.nanos); + } + + #[test] + #[cfg(not(windows))] + fn from_unix_time_test() { + let time = FileTime::from_unix_time(10, 100_000_000); + assert_eq!(10, time.seconds); + assert_eq!(100_000_000, time.nanos); + + let time = FileTime::from_unix_time(-10, 100_000_000); + assert_eq!(-10, time.seconds); + assert_eq!(100_000_000, time.nanos); + + let time = FileTime::from_unix_time(-12_000_000_000, 0); + assert_eq!(-12_000_000_000, time.seconds); + assert_eq!(0, time.nanos); + } + + #[test] + #[cfg(windows)] + fn from_system_time_test() { + let time = FileTime::from_system_time(UNIX_EPOCH + Duration::from_secs(10)); + assert_eq!(11644473610, time.seconds); + assert_eq!(0, time.nanos); + + let time = FileTime::from_system_time(UNIX_EPOCH - Duration::from_secs(10)); + assert_eq!(11644473590, time.seconds); + assert_eq!(0, time.nanos); + + let time = FileTime::from_system_time(UNIX_EPOCH - Duration::from_millis(1100)); + assert_eq!(11644473598, time.seconds); + assert_eq!(900_000_000, time.nanos); + + let time = FileTime::from_system_time(UNIX_EPOCH - Duration::from_secs(12_000_000_000)); + assert_eq!(-355526400, time.seconds); + assert_eq!(0, time.nanos); + } + + #[test] + #[cfg(not(windows))] + fn from_system_time_test() { + let time = FileTime::from_system_time(UNIX_EPOCH + Duration::from_secs(10)); + assert_eq!(10, time.seconds); + assert_eq!(0, time.nanos); + + let time = FileTime::from_system_time(UNIX_EPOCH - Duration::from_secs(10)); + assert_eq!(-10, time.seconds); + assert_eq!(0, time.nanos); + + let time = FileTime::from_system_time(UNIX_EPOCH - Duration::from_millis(1100)); + assert_eq!(-2, time.seconds); + assert_eq!(900_000_000, time.nanos); + + let time = FileTime::from_system_time(UNIX_EPOCH - Duration::from_secs(12_000_000_000)); + assert_eq!(-12_000_000_000, time.seconds); + assert_eq!(0, time.nanos); + } + + #[test] + fn set_file_times_test() { + let td = TempDir::new("filetime").unwrap(); + let path = td.path().join("foo.txt"); + File::create(&path).unwrap(); + + let metadata = fs::metadata(&path).unwrap(); + let mtime = FileTime::from_last_modification_time(&metadata); + let atime = FileTime::from_last_access_time(&metadata); + set_file_times(&path, atime, mtime).unwrap(); + + let new_mtime = FileTime::from_unix_time(10_000, 0); + set_file_times(&path, atime, new_mtime).unwrap(); + + let metadata = fs::metadata(&path).unwrap(); + let mtime = FileTime::from_last_modification_time(&metadata); + assert_eq!(mtime, new_mtime); + + let spath = td.path().join("bar.txt"); + make_symlink(&path, &spath).unwrap(); + let metadata = fs::symlink_metadata(&spath).unwrap(); + let smtime = FileTime::from_last_modification_time(&metadata); + + set_file_times(&spath, atime, mtime).unwrap(); + + let metadata = fs::metadata(&path).unwrap(); + let cur_mtime = FileTime::from_last_modification_time(&metadata); + assert_eq!(mtime, cur_mtime); + + let metadata = fs::symlink_metadata(&spath).unwrap(); + let cur_mtime = FileTime::from_last_modification_time(&metadata); + assert_eq!(smtime, cur_mtime); + + set_file_times(&spath, atime, new_mtime).unwrap(); + + let metadata = fs::metadata(&path).unwrap(); + let mtime = FileTime::from_last_modification_time(&metadata); + assert_eq!(mtime, new_mtime); + + let metadata = fs::symlink_metadata(&spath).unwrap(); + let mtime = FileTime::from_last_modification_time(&metadata); + assert_eq!(mtime, smtime); + } + + #[test] + fn set_file_times_pre_unix_epoch_test() { + let td = TempDir::new("filetime").unwrap(); + let path = td.path().join("foo.txt"); + File::create(&path).unwrap(); + + let metadata = fs::metadata(&path).unwrap(); + let mtime = FileTime::from_last_modification_time(&metadata); + let atime = FileTime::from_last_access_time(&metadata); + set_file_times(&path, atime, mtime).unwrap(); + + let new_mtime = FileTime::from_unix_time(-10_000, 0); + set_file_times(&path, atime, new_mtime).unwrap(); + + let metadata = fs::metadata(&path).unwrap(); + let mtime = FileTime::from_last_modification_time(&metadata); + assert_eq!(mtime, new_mtime); + } + + #[test] + #[cfg(windows)] + fn set_file_times_pre_windows_epoch_test() { + let td = TempDir::new("filetime").unwrap(); + let path = td.path().join("foo.txt"); + File::create(&path).unwrap(); + + let metadata = fs::metadata(&path).unwrap(); + let mtime = FileTime::from_last_modification_time(&metadata); + let atime = FileTime::from_last_access_time(&metadata); + set_file_times(&path, atime, mtime).unwrap(); + + let new_mtime = FileTime::from_unix_time(-12_000_000_000, 0); + assert!(set_file_times(&path, atime, new_mtime).is_err()); + } + + #[test] + fn set_symlink_file_times_test() { + let td = TempDir::new("filetime").unwrap(); + let path = td.path().join("foo.txt"); + File::create(&path).unwrap(); + + let metadata = fs::metadata(&path).unwrap(); + let mtime = FileTime::from_last_modification_time(&metadata); + let atime = FileTime::from_last_access_time(&metadata); + set_symlink_file_times(&path, atime, mtime).unwrap(); + + let new_mtime = FileTime::from_unix_time(10_000, 0); + set_symlink_file_times(&path, atime, new_mtime).unwrap(); + + let metadata = fs::metadata(&path).unwrap(); + let mtime = FileTime::from_last_modification_time(&metadata); + assert_eq!(mtime, new_mtime); + + let spath = td.path().join("bar.txt"); + make_symlink(&path, &spath).unwrap(); + + let metadata = fs::symlink_metadata(&spath).unwrap(); + let smtime = FileTime::from_last_modification_time(&metadata); + let satime = FileTime::from_last_access_time(&metadata); + set_symlink_file_times(&spath, smtime, satime).unwrap(); + + let metadata = fs::metadata(&path).unwrap(); + let mtime = FileTime::from_last_modification_time(&metadata); + assert_eq!(mtime, new_mtime); + + let new_smtime = FileTime::from_unix_time(20_000, 0); + set_symlink_file_times(&spath, atime, new_smtime).unwrap(); + + let metadata = fs::metadata(&spath).unwrap(); + let mtime = FileTime::from_last_modification_time(&metadata); + assert_eq!(mtime, new_mtime); + + let metadata = fs::symlink_metadata(&spath).unwrap(); + let mtime = FileTime::from_last_modification_time(&metadata); + assert_eq!(mtime, new_smtime); + } +} diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/src/redox.rs cargo-0.26.0/vendor/filetime-0.2.0/src/redox.rs --- cargo-0.25.0/vendor/filetime-0.2.0/src/redox.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/src/redox.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,57 @@ +extern crate syscall; + +use std::fs; +use std::io; +use std::os::unix::prelude::*; +use std::path::Path; + +use FileTime; + +pub fn set_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { + let fd = syscall::open(p.as_os_str().as_bytes(), 0) + .map_err(|err| io::Error::from_raw_os_error(err.errno))?; + set_file_times_redox(fd, atime, mtime) +} + +pub fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { + let fd = syscall::open(p.as_os_str().as_bytes(), syscall::O_NOFOLLOW) + .map_err(|err| io::Error::from_raw_os_error(err.errno))?; + set_file_times_redox(fd, atime, mtime) +} + +fn set_file_times_redox(fd: usize, atime: FileTime, mtime: FileTime) -> io::Result<()> { + use self::syscall::TimeSpec; + + fn to_timespec(ft: &FileTime) -> TimeSpec { + TimeSpec { + tv_sec: ft.seconds(), + tv_nsec: ft.nanoseconds() as i32 + } + } + + let times = [to_timespec(&atime), to_timespec(&mtime)]; + let res = syscall::futimens(fd, ×); + let _ = syscall::close(fd); + match res { + Ok(_) => Ok(()), + Err(err) => Err(io::Error::from_raw_os_error(err.errno)) + } +} + +pub fn from_last_modification_time(meta: &fs::Metadata) -> FileTime { + FileTime { + seconds: meta.mtime(), + nanos: meta.mtime_nsec() as u32, + } +} + +pub fn from_last_access_time(meta: &fs::Metadata) -> FileTime { + FileTime { + seconds: meta.atime(), + nanos: meta.atime_nsec() as u32, + } +} + +pub fn from_creation_time(_meta: &fs::Metadata) -> Option { + None +} diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/src/unix/linux.rs cargo-0.26.0/vendor/filetime-0.2.0/src/unix/linux.rs --- cargo-0.25.0/vendor/filetime-0.2.0/src/unix/linux.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/src/unix/linux.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,62 @@ +//! On Linux we try to use the more accurate `utimensat` syscall but this isn't +//! always available so we also fall back to `utimes` if we couldn't find +//! `utimensat` at runtime. + +use std::io; +use std::mem; +use std::path::Path; +use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; +use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT}; + +use FileTime; +use super::libc::{self, c_int, c_char, timespec}; + +pub fn set_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { + set_times(p, atime, mtime, false) +} + +pub fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { + set_times(p, atime, mtime, true) +} + +fn set_times(p: &Path, atime: FileTime, mtime: FileTime, symlink: bool) -> io::Result<()> { + let flags = if symlink { libc::AT_SYMLINK_NOFOLLOW } else { 0 }; + let utimes = if symlink { libc::lutimes } else { libc::utimes }; + + // Try to use the more-accurate `utimensat` when possible. + static INVALID: AtomicBool = ATOMIC_BOOL_INIT; + if !INVALID.load(Ordering::SeqCst) { + if let Some(f) = utimensat() { + // Even when libc has `utimensat`, the kernel may return `ENOSYS`, + // and then we'll need to use the `utimes` fallback instead. + match super::utimensat(p, atime, mtime, f, flags) { + Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => { + INVALID.store(true, Ordering::SeqCst); + } + valid => return valid, + } + } + } + + super::utimes(p, atime, mtime, utimes) +} + +fn utimensat() -> Option c_int> { + static ADDR: AtomicUsize = ATOMIC_USIZE_INIT; + unsafe { + match ADDR.load(Ordering::SeqCst) { + 0 => {} + 1 => return None, + n => return Some(mem::transmute(n)), + } + let name = b"utimensat\0"; + let sym = libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _); + let (val, ret) = if sym.is_null() { + (1, None) + } else { + (sym as usize, Some(mem::transmute(sym))) + }; + ADDR.store(val, Ordering::SeqCst); + return ret + } +} diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/src/unix/mod.rs cargo-0.26.0/vendor/filetime-0.2.0/src/unix/mod.rs --- cargo-0.25.0/vendor/filetime-0.2.0/src/unix/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/src/unix/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,125 @@ +extern crate libc; + +use std::ffi::CString; +use std::fs; +use std::io; +use std::os::unix::prelude::*; +use std::path::Path; + +use self::libc::{c_int, c_char, timeval, time_t, suseconds_t}; +use self::libc::{timespec}; + +use FileTime; + +cfg_if! { + if #[cfg(target_os = "linux")] { + mod linux; + pub use self::linux::*; + } else if #[cfg(any(target_os = "android", + target_os = "solaris", + target_os = "netbsd", + target_os = "openbsd"))] { + mod utimensat; + pub use self::utimensat::*; + } else { + mod utimes; + pub use self::utimes::*; + } +} + +#[allow(dead_code)] +fn utimes(p: &Path, + atime: FileTime, + mtime: FileTime, + utimes: unsafe extern fn(*const c_char, *const timeval) -> c_int) + -> io::Result<()> +{ + let times = [to_timeval(&atime), to_timeval(&mtime)]; + let p = try!(CString::new(p.as_os_str().as_bytes())); + return if unsafe { utimes(p.as_ptr() as *const _, times.as_ptr()) == 0 } { + Ok(()) + } else { + Err(io::Error::last_os_error()) + }; + + fn to_timeval(ft: &FileTime) -> timeval { + timeval { + tv_sec: ft.seconds() as time_t, + tv_usec: (ft.nanoseconds() / 1000) as suseconds_t, + } + } +} + +#[allow(dead_code)] +fn utimensat(p: &Path, + atime: FileTime, + mtime: FileTime, + f: unsafe extern fn(c_int, *const c_char, *const timespec, c_int) -> c_int, + flags: c_int) + -> io::Result<()> +{ + let times = [to_timespec(&atime), to_timespec(&mtime)]; + let p = try!(CString::new(p.as_os_str().as_bytes())); + let rc = unsafe { + f(libc::AT_FDCWD, p.as_ptr() as *const _, times.as_ptr(), flags) + }; + return if rc == 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + }; + + fn to_timespec(ft: &FileTime) -> timespec { + timespec { + tv_sec: ft.seconds() as time_t, + tv_nsec: ft.nanoseconds() as _, + } + } +} + +pub fn from_last_modification_time(meta: &fs::Metadata) -> FileTime { + FileTime { + seconds: meta.mtime(), + nanos: meta.mtime_nsec() as u32, + } +} + +pub fn from_last_access_time(meta: &fs::Metadata) -> FileTime { + FileTime { + seconds: meta.atime(), + nanos: meta.atime_nsec() as u32, + } +} + +pub fn from_creation_time(meta: &fs::Metadata) -> Option { + macro_rules! birthtim { + ($(($e:expr, $i:ident)),*) => { + #[cfg(any($(target_os = $e),*))] + fn imp(meta: &fs::Metadata) -> Option { + $( + #[cfg(target_os = $e)] + use std::os::$i::fs::MetadataExt; + )* + Some(FileTime { + seconds: meta.st_birthtime(), + nanos: meta.st_birthtime_nsec() as u32, + }) + } + + #[cfg(all($(not(target_os = $e)),*))] + fn imp(_meta: &fs::Metadata) -> Option { + None + } + } + } + + birthtim! { + ("bitrig", bitrig), + ("freebsd", freebsd), + ("ios", ios), + ("macos", macos), + ("openbsd", openbsd) + } + + imp(meta) +} diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/src/unix/utimensat.rs cargo-0.26.0/vendor/filetime-0.2.0/src/unix/utimensat.rs --- cargo-0.25.0/vendor/filetime-0.2.0/src/unix/utimensat.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/src/unix/utimensat.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,13 @@ +use std::path::Path; +use std::io; + +use FileTime; +use super::libc; + +pub fn set_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { + super::utimensat(p, atime, mtime, libc::utimensat, 0) +} + +pub fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { + super::utimensat(p, atime, mtime, libc::utimensat, libc::AT_SYMLINK_NOFOLLOW) +} diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/src/unix/utimes.rs cargo-0.26.0/vendor/filetime-0.2.0/src/unix/utimes.rs --- cargo-0.25.0/vendor/filetime-0.2.0/src/unix/utimes.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/src/unix/utimes.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,13 @@ +use std::path::Path; +use std::io; + +use FileTime; +use super::libc; + +pub fn set_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { + super::utimes(p, atime, mtime, libc::utimes) +} + +pub fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { + super::utimes(p, atime, mtime, libc::lutimes) +} diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/src/windows.rs cargo-0.26.0/vendor/filetime-0.2.0/src/windows.rs --- cargo-0.25.0/vendor/filetime-0.2.0/src/windows.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/src/windows.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,87 @@ +#![allow(bad_style)] + +use std::fs::{self, OpenOptions}; +use std::io; +use std::os::windows::prelude::*; +use std::path::Path; + +use FileTime; + +pub fn set_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { + set_file_times_w(p, atime, mtime, OpenOptions::new()) +} + +pub fn set_symlink_file_times(p: &Path, atime: FileTime, mtime: FileTime) -> io::Result<()> { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x00200000; + + let mut options = OpenOptions::new(); + options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT); + set_file_times_w(p, atime, mtime, options) +} + +pub fn set_file_times_w(p: &Path, + atime: FileTime, + mtime: FileTime, + mut options: OpenOptions) -> io::Result<()> { + type BOOL = i32; + type HANDLE = *mut u8; + type DWORD = u32; + + #[repr(C)] + struct FILETIME { + dwLowDateTime: u32, + dwHighDateTime: u32, + } + + extern "system" { + fn SetFileTime(hFile: HANDLE, + lpCreationTime: *const FILETIME, + lpLastAccessTime: *const FILETIME, + lpLastWriteTime: *const FILETIME) -> BOOL; + } + + let f = try!(options.write(true).open(p)); + let atime = to_filetime(&atime); + let mtime = to_filetime(&mtime); + return unsafe { + let ret = SetFileTime(f.as_raw_handle() as *mut _, + 0 as *const _, + &atime, &mtime); + if ret != 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + }; + + fn to_filetime(ft: &FileTime) -> FILETIME { + let intervals = ft.seconds() * (1_000_000_000 / 100) + + ((ft.nanoseconds() as i64) / 100); + FILETIME { + dwLowDateTime: intervals as DWORD, + dwHighDateTime: (intervals >> 32) as DWORD, + } + } +} + +pub fn from_last_modification_time(meta: &fs::Metadata) -> FileTime { + from_intervals(meta.last_write_time()) +} + +pub fn from_last_access_time(meta: &fs::Metadata) -> FileTime { + from_intervals(meta.last_access_time()) +} + +pub fn from_creation_time(meta: &fs::Metadata) -> Option { + Some(from_intervals(meta.creation_time())) +} + +fn from_intervals(ticks: u64) -> FileTime { + // Windows write times are in 100ns intervals, so do a little math to + // get it into the right representation. + FileTime { + seconds: (ticks / (1_000_000_000 / 100)) as i64, + nanos: ((ticks % (1_000_000_000 / 100)) * 100) as u32, + } +} diff -Nru cargo-0.25.0/vendor/filetime-0.2.0/.travis.yml cargo-0.26.0/vendor/filetime-0.2.0/.travis.yml --- cargo-0.25.0/vendor/filetime-0.2.0/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/filetime-0.2.0/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,29 @@ +language: rust +sudo: false + +matrix: + include: + - rust: 1.21.0 + - rust: stable + - os: osx + - rust: beta + - rust: nightly + + - rust: nightly + before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH + script: + - cargo doc --no-deps --all-features + after_success: + - travis-cargo --only nightly doc-upload + +script: + - cargo test + +env: + global: + secure: "MIaQyJIgy7VUoYHY7KbYtxpN/t+a2eWk8PihYctz+F+1PANgD6KbgbF9JW4ip5MYaehk7UWs++kPkHiAvJFKWo2BnQswc4digTUa9Vc2n8/C0d0Ec2zn1EUXH4fkeaMvIffn8QQUPwuNdE6khifSfG8Y42siqJF4zkuPKwaLrUo=" + +notifications: + email: + on_success: never diff -Nru cargo-0.25.0/vendor/globset-0.2.1/benches/bench.rs cargo-0.26.0/vendor/globset-0.2.1/benches/bench.rs --- cargo-0.25.0/vendor/globset-0.2.1/benches/bench.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.2.1/benches/bench.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,121 +0,0 @@ -/*! -This module benchmarks the glob implementation. For benchmarks on the ripgrep -tool itself, see the benchsuite directory. -*/ -#![feature(test)] - -extern crate glob; -extern crate globset; -#[macro_use] -extern crate lazy_static; -extern crate regex; -extern crate test; - -use std::ffi::OsStr; -use std::path::Path; - -use globset::{Candidate, Glob, GlobMatcher, GlobSet, GlobSetBuilder}; - -const EXT: &'static str = "some/a/bigger/path/to/the/crazy/needle.txt"; -const EXT_PAT: &'static str = "*.txt"; - -const SHORT: &'static str = "some/needle.txt"; -const SHORT_PAT: &'static str = "some/**/needle.txt"; - -const LONG: &'static str = "some/a/bigger/path/to/the/crazy/needle.txt"; -const LONG_PAT: &'static str = "some/**/needle.txt"; - -fn new_glob(pat: &str) -> glob::Pattern { - glob::Pattern::new(pat).unwrap() -} - -fn new_reglob(pat: &str) -> GlobMatcher { - Glob::new(pat).unwrap().compile_matcher() -} - -fn new_reglob_many(pats: &[&str]) -> GlobSet { - let mut builder = GlobSetBuilder::new(); - for pat in pats { - builder.add(Glob::new(pat).unwrap()); - } - builder.build().unwrap() -} - -#[bench] -fn ext_glob(b: &mut test::Bencher) { - let pat = new_glob(EXT_PAT); - b.iter(|| assert!(pat.matches(EXT))); -} - -#[bench] -fn ext_regex(b: &mut test::Bencher) { - let set = new_reglob(EXT_PAT); - let cand = Candidate::new(EXT); - b.iter(|| assert!(set.is_match_candidate(&cand))); -} - -#[bench] -fn short_glob(b: &mut test::Bencher) { - let pat = new_glob(SHORT_PAT); - b.iter(|| assert!(pat.matches(SHORT))); -} - -#[bench] -fn short_regex(b: &mut test::Bencher) { - let set = new_reglob(SHORT_PAT); - let cand = Candidate::new(SHORT); - b.iter(|| assert!(set.is_match_candidate(&cand))); -} - -#[bench] -fn long_glob(b: &mut test::Bencher) { - let pat = new_glob(LONG_PAT); - b.iter(|| assert!(pat.matches(LONG))); -} - -#[bench] -fn long_regex(b: &mut test::Bencher) { - let set = new_reglob(LONG_PAT); - let cand = Candidate::new(LONG); - b.iter(|| assert!(set.is_match_candidate(&cand))); -} - -const MANY_SHORT_GLOBS: &'static [&'static str] = &[ - // Taken from a random .gitignore on my system. - ".*.swp", - "tags", - "target", - "*.lock", - "tmp", - "*.csv", - "*.fst", - "*-got", - "*.csv.idx", - "words", - "98m*", - "dict", - "test", - "months", -]; - -const MANY_SHORT_SEARCH: &'static str = "98m-blah.csv.idx"; - -#[bench] -fn many_short_glob(b: &mut test::Bencher) { - let pats: Vec<_> = MANY_SHORT_GLOBS.iter().map(|&s| new_glob(s)).collect(); - b.iter(|| { - let mut count = 0; - for pat in &pats { - if pat.matches(MANY_SHORT_SEARCH) { - count += 1; - } - } - assert_eq!(2, count); - }) -} - -#[bench] -fn many_short_regex_set(b: &mut test::Bencher) { - let set = new_reglob_many(MANY_SHORT_GLOBS); - b.iter(|| assert_eq!(2, set.matches(MANY_SHORT_SEARCH).iter().count())); -} diff -Nru cargo-0.25.0/vendor/globset-0.2.1/.cargo-checksum.json cargo-0.26.0/vendor/globset-0.2.1/.cargo-checksum.json --- cargo-0.25.0/vendor/globset-0.2.1/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.2.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"464627f948c3190ae3d04b1bc6d7dca2f785bda0ac01278e6db129ad383dbeb6"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/globset-0.2.1/Cargo.toml cargo-0.26.0/vendor/globset-0.2.1/Cargo.toml --- cargo-0.25.0/vendor/globset-0.2.1/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.2.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "globset" -version = "0.2.1" -authors = ["Andrew Gallant "] -description = "Cross platform single glob and glob set matching. Glob set matching is the\nprocess of matching one or more glob patterns against a single candidate path\nsimultaneously, and returning all of the globs that matched.\n" -homepage = "https://github.com/BurntSushi/ripgrep/tree/master/globset" -documentation = "https://docs.rs/globset" -readme = "README.md" -keywords = ["regex", "glob", "multiple", "set", "pattern"] -license = "Unlicense/MIT" -repository = "https://github.com/BurntSushi/ripgrep/tree/master/globset" - -[lib] -name = "globset" -bench = false -[dependencies.aho-corasick] -version = "0.6.0" - -[dependencies.regex] -version = "0.2.1" - -[dependencies.memchr] -version = "2" - -[dependencies.log] -version = "0.3" - -[dependencies.fnv] -version = "1.0" -[dev-dependencies.glob] -version = "0.2" - -[features] -simd-accel = ["regex/simd-accel"] diff -Nru cargo-0.25.0/vendor/globset-0.2.1/COPYING cargo-0.26.0/vendor/globset-0.2.1/COPYING --- cargo-0.25.0/vendor/globset-0.2.1/COPYING 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.2.1/COPYING 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -This project is dual-licensed under the Unlicense and MIT licenses. - -You may use this code under the terms of either license. diff -Nru cargo-0.25.0/vendor/globset-0.2.1/LICENSE-MIT cargo-0.26.0/vendor/globset-0.2.1/LICENSE-MIT --- cargo-0.25.0/vendor/globset-0.2.1/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.2.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Andrew Gallant - -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. diff -Nru cargo-0.25.0/vendor/globset-0.2.1/README.md cargo-0.26.0/vendor/globset-0.2.1/README.md --- cargo-0.25.0/vendor/globset-0.2.1/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.2.1/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,122 +0,0 @@ -globset -======= -Cross platform single glob and glob set matching. Glob set matching is the -process of matching one or more glob patterns against a single candidate path -simultaneously, and returning all of the globs that matched. - -[![Linux build status](https://api.travis-ci.org/BurntSushi/ripgrep.png)](https://travis-ci.org/BurntSushi/ripgrep) -[![Windows build status](https://ci.appveyor.com/api/projects/status/github/BurntSushi/ripgrep?svg=true)](https://ci.appveyor.com/project/BurntSushi/ripgrep) -[![](https://img.shields.io/crates/v/globset.svg)](https://crates.io/crates/globset) - -Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). - -### Documentation - -[https://docs.rs/globset](https://docs.rs/globset) - -### Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -globset = "0.2" -``` - -and this to your crate root: - -```rust -extern crate globset; -``` - -### Example: one glob - -This example shows how to match a single glob against a single file path. - -```rust -use globset::Glob; - -let glob = try!(Glob::new("*.rs")).compile_matcher(); - -assert!(glob.is_match("foo.rs")); -assert!(glob.is_match("foo/bar.rs")); -assert!(!glob.is_match("Cargo.toml")); -``` - -### Example: configuring a glob matcher - -This example shows how to use a `GlobBuilder` to configure aspects of match -semantics. In this example, we prevent wildcards from matching path separators. - -```rust -use globset::GlobBuilder; - -let glob = try!(GlobBuilder::new("*.rs") - .literal_separator(true).build()).compile_matcher(); - -assert!(glob.is_match("foo.rs")); -assert!(!glob.is_match("foo/bar.rs")); // no longer matches -assert!(!glob.is_match("Cargo.toml")); -``` - -### Example: match multiple globs at once - -This example shows how to match multiple glob patterns at once. - -```rust -use globset::{Glob, GlobSetBuilder}; - -let mut builder = GlobSetBuilder::new(); -// A GlobBuilder can be used to configure each glob's match semantics -// independently. -builder.add(try!(Glob::new("*.rs"))); -builder.add(try!(Glob::new("src/lib.rs"))); -builder.add(try!(Glob::new("src/**/foo.rs"))); -let set = try!(builder.build()); - -assert_eq!(set.matches("src/bar/baz/foo.rs"), vec![0, 2]); -``` - -### Performance - -This crate implements globs by converting them to regular expressions, and -executing them with the -[`regex`](https://github.com/rust-lang-nursery/regex) -crate. - -For single glob matching, performance of this crate should be roughly on par -with the performance of the -[`glob`](https://github.com/rust-lang-nursery/glob) -crate. (`*_regex` correspond to benchmarks for this library while `*_glob` -correspond to benchmarks for the `glob` library.) -Optimizations in the `regex` crate may propel this library past `glob`, -particularly when matching longer paths. - -``` -test ext_glob ... bench: 425 ns/iter (+/- 21) -test ext_regex ... bench: 175 ns/iter (+/- 10) -test long_glob ... bench: 182 ns/iter (+/- 11) -test long_regex ... bench: 173 ns/iter (+/- 10) -test short_glob ... bench: 69 ns/iter (+/- 4) -test short_regex ... bench: 83 ns/iter (+/- 2) -``` - -The primary performance advantage of this crate is when matching multiple -globs against a single path. With the `glob` crate, one must match each glob -synchronously, one after the other. In this crate, many can be matched -simultaneously. For example: - -``` -test many_short_glob ... bench: 1,063 ns/iter (+/- 47) -test many_short_regex_set ... bench: 186 ns/iter (+/- 11) -``` - -### Comparison with the [`glob`](https://github.com/rust-lang-nursery/glob) crate - -* Supports alternate "or" globs, e.g., `*.{foo,bar}`. -* Can match non-UTF-8 file paths correctly. -* Supports matching multiple globs at once. -* Doesn't provide a recursive directory iterator of matching file paths, - although I believe this crate should grow one eventually. -* Supports case insensitive and require-literal-separator match options, but - **doesn't** support the require-literal-leading-dot option. diff -Nru cargo-0.25.0/vendor/globset-0.2.1/src/glob.rs cargo-0.26.0/vendor/globset-0.2.1/src/glob.rs --- cargo-0.25.0/vendor/globset-0.2.1/src/glob.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.2.1/src/glob.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1340 +0,0 @@ -use std::ffi::{OsStr, OsString}; -use std::fmt; -use std::hash; -use std::iter; -use std::ops::{Deref, DerefMut}; -use std::path::{Path, is_separator}; -use std::str; - -use regex; -use regex::bytes::Regex; - -use {Candidate, Error, ErrorKind, new_regex}; - -/// Describes a matching strategy for a particular pattern. -/// -/// This provides a way to more quickly determine whether a pattern matches -/// a particular file path in a way that scales with a large number of -/// patterns. For example, if many patterns are of the form `*.ext`, then it's -/// possible to test whether any of those patterns matches by looking up a -/// file path's extension in a hash table. -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum MatchStrategy { - /// A pattern matches if and only if the entire file path matches this - /// literal string. - Literal(String), - /// A pattern matches if and only if the file path's basename matches this - /// literal string. - BasenameLiteral(String), - /// A pattern matches if and only if the file path's extension matches this - /// literal string. - Extension(OsString), - /// A pattern matches if and only if this prefix literal is a prefix of the - /// candidate file path. - Prefix(String), - /// A pattern matches if and only if this prefix literal is a prefix of the - /// candidate file path. - /// - /// An exception: if `component` is true, then `suffix` must appear at the - /// beginning of a file path or immediately following a `/`. - Suffix { - /// The actual suffix. - suffix: String, - /// Whether this must start at the beginning of a path component. - component: bool, - }, - /// A pattern matches only if the given extension matches the file path's - /// extension. Note that this is a necessary but NOT sufficient criterion. - /// Namely, if the extension matches, then a full regex search is still - /// required. - RequiredExtension(OsString), - /// A regex needs to be used for matching. - Regex, -} - -impl MatchStrategy { - /// Returns a matching strategy for the given pattern. - pub fn new(pat: &Glob) -> MatchStrategy { - if let Some(lit) = pat.basename_literal() { - MatchStrategy::BasenameLiteral(lit) - } else if let Some(lit) = pat.literal() { - MatchStrategy::Literal(lit) - } else if let Some(ext) = pat.ext() { - MatchStrategy::Extension(ext) - } else if let Some(prefix) = pat.prefix() { - MatchStrategy::Prefix(prefix) - } else if let Some((suffix, component)) = pat.suffix() { - MatchStrategy::Suffix { suffix: suffix, component: component } - } else if let Some(ext) = pat.required_ext() { - MatchStrategy::RequiredExtension(ext) - } else { - MatchStrategy::Regex - } - } -} - -/// Glob represents a successfully parsed shell glob pattern. -/// -/// It cannot be used directly to match file paths, but it can be converted -/// to a regular expression string or a matcher. -#[derive(Clone, Debug, Eq)] -pub struct Glob { - glob: String, - re: String, - opts: GlobOptions, - tokens: Tokens, -} - -impl PartialEq for Glob { - fn eq(&self, other: &Glob) -> bool { - self.glob == other.glob && self.opts == other.opts - } -} - -impl hash::Hash for Glob { - fn hash(&self, state: &mut H) { - self.glob.hash(state); - self.opts.hash(state); - } -} - -impl fmt::Display for Glob { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.glob.fmt(f) - } -} - -/// A matcher for a single pattern. -#[derive(Clone, Debug)] -pub struct GlobMatcher { - /// The underlying pattern. - pat: Glob, - /// The pattern, as a compiled regex. - re: Regex, -} - -impl GlobMatcher { - /// Tests whether the given path matches this pattern or not. - pub fn is_match>(&self, path: P) -> bool { - self.is_match_candidate(&Candidate::new(path.as_ref())) - } - - /// Tests whether the given path matches this pattern or not. - pub fn is_match_candidate(&self, path: &Candidate) -> bool { - self.re.is_match(&path.path) - } -} - -/// A strategic matcher for a single pattern. -#[cfg(test)] -#[derive(Clone, Debug)] -struct GlobStrategic { - /// The match strategy to use. - strategy: MatchStrategy, - /// The underlying pattern. - pat: Glob, - /// The pattern, as a compiled regex. - re: Regex, -} - -#[cfg(test)] -impl GlobStrategic { - /// Tests whether the given path matches this pattern or not. - fn is_match>(&self, path: P) -> bool { - self.is_match_candidate(&Candidate::new(path.as_ref())) - } - - /// Tests whether the given path matches this pattern or not. - fn is_match_candidate(&self, candidate: &Candidate) -> bool { - let byte_path = &*candidate.path; - - match self.strategy { - MatchStrategy::Literal(ref lit) => lit.as_bytes() == byte_path, - MatchStrategy::BasenameLiteral(ref lit) => { - lit.as_bytes() == &*candidate.basename - } - MatchStrategy::Extension(ref ext) => { - candidate.ext == ext - } - MatchStrategy::Prefix(ref pre) => { - starts_with(pre.as_bytes(), byte_path) - } - MatchStrategy::Suffix { ref suffix, component } => { - if component && byte_path == &suffix.as_bytes()[1..] { - return true; - } - ends_with(suffix.as_bytes(), byte_path) - } - MatchStrategy::RequiredExtension(ref ext) => { - candidate.ext == ext && self.re.is_match(byte_path) - } - MatchStrategy::Regex => self.re.is_match(byte_path), - } - } -} - -/// A builder for a pattern. -/// -/// This builder enables configuring the match semantics of a pattern. For -/// example, one can make matching case insensitive. -/// -/// The lifetime `'a` refers to the lifetime of the pattern string. -#[derive(Clone, Debug)] -pub struct GlobBuilder<'a> { - /// The glob pattern to compile. - glob: &'a str, - /// Options for the pattern. - opts: GlobOptions, -} - -#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] -struct GlobOptions { - /// Whether to match case insensitively. - case_insensitive: bool, - /// Whether to require a literal separator to match a separator in a file - /// path. e.g., when enabled, `*` won't match `/`. - literal_separator: bool, -} - -#[derive(Clone, Debug, Default, Eq, PartialEq)] -struct Tokens(Vec); - -impl Deref for Tokens { - type Target = Vec; - fn deref(&self) -> &Vec { &self.0 } -} - -impl DerefMut for Tokens { - fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } -} - -#[derive(Clone, Debug, Eq, PartialEq)] -enum Token { - Literal(char), - Any, - ZeroOrMore, - RecursivePrefix, - RecursiveSuffix, - RecursiveZeroOrMore, - Class { - negated: bool, - ranges: Vec<(char, char)>, - }, - Alternates(Vec), -} - -impl Glob { - /// Builds a new pattern with default options. - pub fn new(glob: &str) -> Result { - GlobBuilder::new(glob).build() - } - - /// Returns a matcher for this pattern. - pub fn compile_matcher(&self) -> GlobMatcher { - let re = new_regex(&self.re) - .expect("regex compilation shouldn't fail"); - GlobMatcher { - pat: self.clone(), - re: re, - } - } - - /// Returns a strategic matcher. - /// - /// This isn't exposed because it's not clear whether it's actually - /// faster than just running a regex for a *single* pattern. If it - /// is faster, then GlobMatcher should do it automatically. - #[cfg(test)] - fn compile_strategic_matcher(&self) -> GlobStrategic { - let strategy = MatchStrategy::new(self); - let re = new_regex(&self.re) - .expect("regex compilation shouldn't fail"); - GlobStrategic { - strategy: strategy, - pat: self.clone(), - re: re, - } - } - - /// Returns the original glob pattern used to build this pattern. - pub fn glob(&self) -> &str { - &self.glob - } - - /// Returns the regular expression string for this glob. - pub fn regex(&self) -> &str { - &self.re - } - - /// Returns the pattern as a literal if and only if the pattern must match - /// an entire path exactly. - /// - /// The basic format of these patterns is `{literal}`. - fn literal(&self) -> Option { - if self.opts.case_insensitive { - return None; - } - let mut lit = String::new(); - for t in &*self.tokens { - match *t { - Token::Literal(c) => lit.push(c), - _ => return None, - } - } - if lit.is_empty() { - None - } else { - Some(lit) - } - } - - /// Returns an extension if this pattern matches a file path if and only - /// if the file path has the extension returned. - /// - /// Note that this extension returned differs from the extension that - /// std::path::Path::extension returns. Namely, this extension includes - /// the '.'. Also, paths like `.rs` are considered to have an extension - /// of `.rs`. - fn ext(&self) -> Option { - if self.opts.case_insensitive { - return None; - } - let start = match self.tokens.get(0) { - Some(&Token::RecursivePrefix) => 1, - Some(_) => 0, - _ => return None, - }; - match self.tokens.get(start) { - Some(&Token::ZeroOrMore) => { - // If there was no recursive prefix, then we only permit - // `*` if `*` can match a `/`. For example, if `*` can't - // match `/`, then `*.c` doesn't match `foo/bar.c`. - if start == 0 && self.opts.literal_separator { - return None; - } - } - _ => return None, - } - match self.tokens.get(start + 1) { - Some(&Token::Literal('.')) => {} - _ => return None, - } - let mut lit = OsStr::new(".").to_os_string(); - for t in self.tokens[start + 2..].iter() { - match *t { - Token::Literal('.') | Token::Literal('/') => return None, - Token::Literal(c) => lit.push(c.to_string()), - _ => return None, - } - } - if lit.is_empty() { - None - } else { - Some(lit) - } - } - - /// This is like `ext`, but returns an extension even if it isn't sufficent - /// to imply a match. Namely, if an extension is returned, then it is - /// necessary but not sufficient for a match. - fn required_ext(&self) -> Option { - if self.opts.case_insensitive { - return None; - } - // We don't care at all about the beginning of this pattern. All we - // need to check for is if it ends with a literal of the form `.ext`. - let mut ext: Vec = vec![]; // built in reverse - for t in self.tokens.iter().rev() { - match *t { - Token::Literal('/') => return None, - Token::Literal(c) => { - ext.push(c); - if c == '.' { - break; - } - } - _ => return None, - } - } - if ext.last() != Some(&'.') { - None - } else { - ext.reverse(); - Some(OsString::from(ext.into_iter().collect::())) - } - } - - /// Returns a literal prefix of this pattern if the entire pattern matches - /// if the literal prefix matches. - fn prefix(&self) -> Option { - if self.opts.case_insensitive { - return None; - } - let end = match self.tokens.last() { - Some(&Token::ZeroOrMore) => { - if self.opts.literal_separator { - // If a trailing `*` can't match a `/`, then we can't - // assume a match of the prefix corresponds to a match - // of the overall pattern. e.g., `foo/*` with - // `literal_separator` enabled matches `foo/bar` but not - // `foo/bar/baz`, even though `foo/bar/baz` has a `foo/` - // literal prefix. - return None; - } - self.tokens.len() - 1 - } - _ => self.tokens.len(), - }; - let mut lit = String::new(); - for t in &self.tokens[0..end] { - match *t { - Token::Literal(c) => lit.push(c), - _ => return None, - } - } - if lit.is_empty() { - None - } else { - Some(lit) - } - } - - /// Returns a literal suffix of this pattern if the entire pattern matches - /// if the literal suffix matches. - /// - /// If a literal suffix is returned and it must match either the entire - /// file path or be preceded by a `/`, then also return true. This happens - /// with a pattern like `**/foo/bar`. Namely, this pattern matches - /// `foo/bar` and `baz/foo/bar`, but not `foofoo/bar`. In this case, the - /// suffix returned is `/foo/bar` (but should match the entire path - /// `foo/bar`). - /// - /// When this returns true, the suffix literal is guaranteed to start with - /// a `/`. - fn suffix(&self) -> Option<(String, bool)> { - if self.opts.case_insensitive { - return None; - } - let mut lit = String::new(); - let (start, entire) = match self.tokens.get(0) { - Some(&Token::RecursivePrefix) => { - // We only care if this follows a path component if the next - // token is a literal. - if let Some(&Token::Literal(_)) = self.tokens.get(1) { - lit.push('/'); - (1, true) - } else { - (1, false) - } - } - _ => (0, false), - }; - let start = match self.tokens.get(start) { - Some(&Token::ZeroOrMore) => { - // If literal_separator is enabled, then a `*` can't - // necessarily match everything, so reporting a suffix match - // as a match of the pattern would be a false positive. - if self.opts.literal_separator { - return None; - } - start + 1 - } - _ => start, - }; - for t in &self.tokens[start..] { - match *t { - Token::Literal(c) => lit.push(c), - _ => return None, - } - } - if lit.is_empty() || lit == "/" { - None - } else { - Some((lit, entire)) - } - } - - /// If this pattern only needs to inspect the basename of a file path, - /// then the tokens corresponding to only the basename match are returned. - /// - /// For example, given a pattern of `**/*.foo`, only the tokens - /// corresponding to `*.foo` are returned. - /// - /// Note that this will return None if any match of the basename tokens - /// doesn't correspond to a match of the entire pattern. For example, the - /// glob `foo` only matches when a file path has a basename of `foo`, but - /// doesn't *always* match when a file path has a basename of `foo`. e.g., - /// `foo` doesn't match `abc/foo`. - fn basename_tokens(&self) -> Option<&[Token]> { - if self.opts.case_insensitive { - return None; - } - let start = match self.tokens.get(0) { - Some(&Token::RecursivePrefix) => 1, - _ => { - // With nothing to gobble up the parent portion of a path, - // we can't assume that matching on only the basename is - // correct. - return None; - } - }; - if self.tokens[start..].is_empty() { - return None; - } - for t in &self.tokens[start..] { - match *t { - Token::Literal('/') => return None, - Token::Literal(_) => {} // OK - Token::Any | Token::ZeroOrMore => { - if !self.opts.literal_separator { - // In this case, `*` and `?` can match a path - // separator, which means this could reach outside - // the basename. - return None; - } - } - Token::RecursivePrefix - | Token::RecursiveSuffix - | Token::RecursiveZeroOrMore => { - return None; - } - Token::Class{..} | Token::Alternates(..) => { - // We *could* be a little smarter here, but either one - // of these is going to prevent our literal optimizations - // anyway, so give up. - return None; - } - } - } - Some(&self.tokens[start..]) - } - - /// Returns the pattern as a literal if and only if the pattern exclusiely - /// matches the basename of a file path *and* is a literal. - /// - /// The basic format of these patterns is `**/{literal}`, where `{literal}` - /// does not contain a path separator. - fn basename_literal(&self) -> Option { - let tokens = match self.basename_tokens() { - None => return None, - Some(tokens) => tokens, - }; - let mut lit = String::new(); - for t in tokens { - match *t { - Token::Literal(c) => lit.push(c), - _ => return None, - } - } - Some(lit) - } -} - -impl<'a> GlobBuilder<'a> { - /// Create a new builder for the pattern given. - /// - /// The pattern is not compiled until `build` is called. - pub fn new(glob: &'a str) -> GlobBuilder<'a> { - GlobBuilder { - glob: glob, - opts: GlobOptions::default(), - } - } - - /// Parses and builds the pattern. - pub fn build(&self) -> Result { - let mut p = Parser { - glob: &self.glob, - stack: vec![Tokens::default()], - chars: self.glob.chars().peekable(), - prev: None, - cur: None, - }; - try!(p.parse()); - if p.stack.is_empty() { - Err(Error { - glob: Some(self.glob.to_string()), - kind: ErrorKind::UnopenedAlternates, - }) - } else if p.stack.len() > 1 { - Err(Error { - glob: Some(self.glob.to_string()), - kind: ErrorKind::UnclosedAlternates, - }) - } else { - let tokens = p.stack.pop().unwrap(); - Ok(Glob { - glob: self.glob.to_string(), - re: tokens.to_regex_with(&self.opts), - opts: self.opts, - tokens: tokens, - }) - } - } - - /// Toggle whether the pattern matches case insensitively or not. - /// - /// This is disabled by default. - pub fn case_insensitive(&mut self, yes: bool) -> &mut GlobBuilder<'a> { - self.opts.case_insensitive = yes; - self - } - - /// Toggle whether a literal `/` is required to match a path separator. - pub fn literal_separator(&mut self, yes: bool) -> &mut GlobBuilder<'a> { - self.opts.literal_separator = yes; - self - } -} - -impl Tokens { - /// Convert this pattern to a string that is guaranteed to be a valid - /// regular expression and will represent the matching semantics of this - /// glob pattern and the options given. - fn to_regex_with(&self, options: &GlobOptions) -> String { - let mut re = String::new(); - re.push_str("(?-u)"); - if options.case_insensitive { - re.push_str("(?i)"); - } - re.push('^'); - // Special case. If the entire glob is just `**`, then it should match - // everything. - if self.len() == 1 && self[0] == Token::RecursivePrefix { - re.push_str(".*"); - re.push('$'); - return re; - } - self.tokens_to_regex(options, &self, &mut re); - re.push('$'); - re - } - - fn tokens_to_regex( - &self, - options: &GlobOptions, - tokens: &[Token], - re: &mut String, - ) { - for tok in tokens { - match *tok { - Token::Literal(c) => { - re.push_str(&char_to_escaped_literal(c)); - } - Token::Any => { - if options.literal_separator { - re.push_str("[^/]"); - } else { - re.push_str("."); - } - } - Token::ZeroOrMore => { - if options.literal_separator { - re.push_str("[^/]*"); - } else { - re.push_str(".*"); - } - } - Token::RecursivePrefix => { - re.push_str("(?:/?|.*/)"); - } - Token::RecursiveSuffix => { - re.push_str("(?:/?|/.*)"); - } - Token::RecursiveZeroOrMore => { - re.push_str("(?:/|/.*/)"); - } - Token::Class { negated, ref ranges } => { - re.push('['); - if negated { - re.push('^'); - } - for r in ranges { - if r.0 == r.1 { - // Not strictly necessary, but nicer to look at. - re.push_str(&char_to_escaped_literal(r.0)); - } else { - re.push_str(&char_to_escaped_literal(r.0)); - re.push('-'); - re.push_str(&char_to_escaped_literal(r.1)); - } - } - re.push(']'); - } - Token::Alternates(ref patterns) => { - let mut parts = vec![]; - for pat in patterns { - let mut altre = String::new(); - self.tokens_to_regex(options, &pat, &mut altre); - if !altre.is_empty() { - parts.push(altre); - } - } - - // It is possible to have an empty set in which case the - // resulting alternation '()' would be an error. - if !parts.is_empty() { - re.push('('); - re.push_str(&parts.join("|")); - re.push(')'); - } - } - } - } - } -} - -/// Convert a Unicode scalar value to an escaped string suitable for use as -/// a literal in a non-Unicode regex. -fn char_to_escaped_literal(c: char) -> String { - bytes_to_escaped_literal(&c.to_string().into_bytes()) -} - -/// Converts an arbitrary sequence of bytes to a UTF-8 string. All non-ASCII -/// code units are converted to their escaped form. -fn bytes_to_escaped_literal(bs: &[u8]) -> String { - let mut s = String::with_capacity(bs.len()); - for &b in bs { - if b <= 0x7F { - s.push_str(®ex::escape(&(b as char).to_string())); - } else { - s.push_str(&format!("\\x{:02x}", b)); - } - } - s -} - -struct Parser<'a> { - glob: &'a str, - stack: Vec, - chars: iter::Peekable>, - prev: Option, - cur: Option, -} - -impl<'a> Parser<'a> { - fn error(&self, kind: ErrorKind) -> Error { - Error { glob: Some(self.glob.to_string()), kind: kind } - } - - fn parse(&mut self) -> Result<(), Error> { - while let Some(c) = self.bump() { - match c { - '?' => try!(self.push_token(Token::Any)), - '*' => try!(self.parse_star()), - '[' => try!(self.parse_class()), - '{' => try!(self.push_alternate()), - '}' => try!(self.pop_alternate()), - ',' => try!(self.parse_comma()), - c => { - if is_separator(c) { - // Normalize all patterns to use / as a separator. - try!(self.push_token(Token::Literal('/'))) - } else { - try!(self.push_token(Token::Literal(c))) - } - } - } - } - Ok(()) - } - - fn push_alternate(&mut self) -> Result<(), Error> { - if self.stack.len() > 1 { - return Err(self.error(ErrorKind::NestedAlternates)); - } - Ok(self.stack.push(Tokens::default())) - } - - fn pop_alternate(&mut self) -> Result<(), Error> { - let mut alts = vec![]; - while self.stack.len() >= 2 { - alts.push(self.stack.pop().unwrap()); - } - self.push_token(Token::Alternates(alts)) - } - - fn push_token(&mut self, tok: Token) -> Result<(), Error> { - if let Some(ref mut pat) = self.stack.last_mut() { - return Ok(pat.push(tok)); - } - Err(self.error(ErrorKind::UnopenedAlternates)) - } - - fn pop_token(&mut self) -> Result { - if let Some(ref mut pat) = self.stack.last_mut() { - return Ok(pat.pop().unwrap()); - } - Err(self.error(ErrorKind::UnopenedAlternates)) - } - - fn have_tokens(&self) -> Result { - match self.stack.last() { - None => Err(self.error(ErrorKind::UnopenedAlternates)), - Some(ref pat) => Ok(!pat.is_empty()), - } - } - - fn parse_comma(&mut self) -> Result<(), Error> { - // If we aren't inside a group alternation, then don't - // treat commas specially. Otherwise, we need to start - // a new alternate. - if self.stack.len() <= 1 { - self.push_token(Token::Literal(',')) - } else { - Ok(self.stack.push(Tokens::default())) - } - } - - fn parse_star(&mut self) -> Result<(), Error> { - let prev = self.prev; - if self.chars.peek() != Some(&'*') { - try!(self.push_token(Token::ZeroOrMore)); - return Ok(()); - } - assert!(self.bump() == Some('*')); - if !try!(self.have_tokens()) { - try!(self.push_token(Token::RecursivePrefix)); - let next = self.bump(); - if !next.map(is_separator).unwrap_or(true) { - return Err(self.error(ErrorKind::InvalidRecursive)); - } - return Ok(()); - } - try!(self.pop_token()); - if !prev.map(is_separator).unwrap_or(false) { - if self.stack.len() <= 1 - || (prev != Some(',') && prev != Some('{')) { - return Err(self.error(ErrorKind::InvalidRecursive)); - } - } - match self.chars.peek() { - None => { - assert!(self.bump().is_none()); - self.push_token(Token::RecursiveSuffix) - } - Some(&',') | Some(&'}') if self.stack.len() >= 2 => { - self.push_token(Token::RecursiveSuffix) - } - Some(&c) if is_separator(c) => { - assert!(self.bump().map(is_separator).unwrap_or(false)); - self.push_token(Token::RecursiveZeroOrMore) - } - _ => Err(self.error(ErrorKind::InvalidRecursive)), - } - } - - fn parse_class(&mut self) -> Result<(), Error> { - fn add_to_last_range( - glob: &str, - r: &mut (char, char), - add: char, - ) -> Result<(), Error> { - r.1 = add; - if r.1 < r.0 { - Err(Error { - glob: Some(glob.to_string()), - kind: ErrorKind::InvalidRange(r.0, r.1), - }) - } else { - Ok(()) - } - } - let mut negated = false; - let mut ranges = vec![]; - if self.chars.peek() == Some(&'!') { - assert!(self.bump() == Some('!')); - negated = true; - } - let mut first = true; - let mut in_range = false; - loop { - let c = match self.bump() { - Some(c) => c, - // The only way to successfully break this loop is to observe - // a ']'. - None => return Err(self.error(ErrorKind::UnclosedClass)), - }; - match c { - ']' => { - if first { - ranges.push((']', ']')); - } else { - break; - } - } - '-' => { - if first { - ranges.push(('-', '-')); - } else if in_range { - // invariant: in_range is only set when there is - // already at least one character seen. - let r = ranges.last_mut().unwrap(); - try!(add_to_last_range(&self.glob, r, '-')); - in_range = false; - } else { - assert!(!ranges.is_empty()); - in_range = true; - } - } - c => { - if in_range { - // invariant: in_range is only set when there is - // already at least one character seen. - try!(add_to_last_range( - &self.glob, ranges.last_mut().unwrap(), c)); - } else { - ranges.push((c, c)); - } - in_range = false; - } - } - first = false; - } - if in_range { - // Means that the last character in the class was a '-', so add - // it as a literal. - ranges.push(('-', '-')); - } - self.push_token(Token::Class { - negated: negated, - ranges: ranges, - }) - } - - fn bump(&mut self) -> Option { - self.prev = self.cur; - self.cur = self.chars.next(); - self.cur - } -} - -#[cfg(test)] -fn starts_with(needle: &[u8], haystack: &[u8]) -> bool { - needle.len() <= haystack.len() && needle == &haystack[..needle.len()] -} - -#[cfg(test)] -fn ends_with(needle: &[u8], haystack: &[u8]) -> bool { - if needle.len() > haystack.len() { - return false; - } - needle == &haystack[haystack.len() - needle.len()..] -} - -#[cfg(test)] -mod tests { - use std::ffi::{OsStr, OsString}; - - use {GlobSetBuilder, ErrorKind}; - use super::{Glob, GlobBuilder, Token}; - use super::Token::*; - - #[derive(Clone, Copy, Debug, Default)] - struct Options { - casei: bool, - litsep: bool, - } - - macro_rules! syntax { - ($name:ident, $pat:expr, $tokens:expr) => { - #[test] - fn $name() { - let pat = Glob::new($pat).unwrap(); - assert_eq!($tokens, pat.tokens.0); - } - } - } - - macro_rules! syntaxerr { - ($name:ident, $pat:expr, $err:expr) => { - #[test] - fn $name() { - let err = Glob::new($pat).unwrap_err(); - assert_eq!(&$err, err.kind()); - } - } - } - - macro_rules! toregex { - ($name:ident, $pat:expr, $re:expr) => { - toregex!($name, $pat, $re, Options::default()); - }; - ($name:ident, $pat:expr, $re:expr, $options:expr) => { - #[test] - fn $name() { - let pat = GlobBuilder::new($pat) - .case_insensitive($options.casei) - .literal_separator($options.litsep) - .build() - .unwrap(); - assert_eq!(format!("(?-u){}", $re), pat.regex()); - } - }; - } - - macro_rules! matches { - ($name:ident, $pat:expr, $path:expr) => { - matches!($name, $pat, $path, Options::default()); - }; - ($name:ident, $pat:expr, $path:expr, $options:expr) => { - #[test] - fn $name() { - let pat = GlobBuilder::new($pat) - .case_insensitive($options.casei) - .literal_separator($options.litsep) - .build() - .unwrap(); - let matcher = pat.compile_matcher(); - let strategic = pat.compile_strategic_matcher(); - let set = GlobSetBuilder::new().add(pat).build().unwrap(); - assert!(matcher.is_match($path)); - assert!(strategic.is_match($path)); - assert!(set.is_match($path)); - } - }; - } - - macro_rules! nmatches { - ($name:ident, $pat:expr, $path:expr) => { - nmatches!($name, $pat, $path, Options::default()); - }; - ($name:ident, $pat:expr, $path:expr, $options:expr) => { - #[test] - fn $name() { - let pat = GlobBuilder::new($pat) - .case_insensitive($options.casei) - .literal_separator($options.litsep) - .build() - .unwrap(); - let matcher = pat.compile_matcher(); - let strategic = pat.compile_strategic_matcher(); - let set = GlobSetBuilder::new().add(pat).build().unwrap(); - assert!(!matcher.is_match($path)); - assert!(!strategic.is_match($path)); - assert!(!set.is_match($path)); - } - }; - } - - fn s(string: &str) -> String { string.to_string() } - fn os(string: &str) -> OsString { OsStr::new(string).to_os_string() } - - fn class(s: char, e: char) -> Token { - Class { negated: false, ranges: vec![(s, e)] } - } - - fn classn(s: char, e: char) -> Token { - Class { negated: true, ranges: vec![(s, e)] } - } - - fn rclass(ranges: &[(char, char)]) -> Token { - Class { negated: false, ranges: ranges.to_vec() } - } - - fn rclassn(ranges: &[(char, char)]) -> Token { - Class { negated: true, ranges: ranges.to_vec() } - } - - syntax!(literal1, "a", vec![Literal('a')]); - syntax!(literal2, "ab", vec![Literal('a'), Literal('b')]); - syntax!(any1, "?", vec![Any]); - syntax!(any2, "a?b", vec![Literal('a'), Any, Literal('b')]); - syntax!(seq1, "*", vec![ZeroOrMore]); - syntax!(seq2, "a*b", vec![Literal('a'), ZeroOrMore, Literal('b')]); - syntax!(seq3, "*a*b*", vec![ - ZeroOrMore, Literal('a'), ZeroOrMore, Literal('b'), ZeroOrMore, - ]); - syntax!(rseq1, "**", vec![RecursivePrefix]); - syntax!(rseq2, "**/", vec![RecursivePrefix]); - syntax!(rseq3, "/**", vec![RecursiveSuffix]); - syntax!(rseq4, "/**/", vec![RecursiveZeroOrMore]); - syntax!(rseq5, "a/**/b", vec![ - Literal('a'), RecursiveZeroOrMore, Literal('b'), - ]); - syntax!(cls1, "[a]", vec![class('a', 'a')]); - syntax!(cls2, "[!a]", vec![classn('a', 'a')]); - syntax!(cls3, "[a-z]", vec![class('a', 'z')]); - syntax!(cls4, "[!a-z]", vec![classn('a', 'z')]); - syntax!(cls5, "[-]", vec![class('-', '-')]); - syntax!(cls6, "[]]", vec![class(']', ']')]); - syntax!(cls7, "[*]", vec![class('*', '*')]); - syntax!(cls8, "[!!]", vec![classn('!', '!')]); - syntax!(cls9, "[a-]", vec![rclass(&[('a', 'a'), ('-', '-')])]); - syntax!(cls10, "[-a-z]", vec![rclass(&[('-', '-'), ('a', 'z')])]); - syntax!(cls11, "[a-z-]", vec![rclass(&[('a', 'z'), ('-', '-')])]); - syntax!(cls12, "[-a-z-]", vec![ - rclass(&[('-', '-'), ('a', 'z'), ('-', '-')]), - ]); - syntax!(cls13, "[]-z]", vec![class(']', 'z')]); - syntax!(cls14, "[--z]", vec![class('-', 'z')]); - syntax!(cls15, "[ --]", vec![class(' ', '-')]); - syntax!(cls16, "[0-9a-z]", vec![rclass(&[('0', '9'), ('a', 'z')])]); - syntax!(cls17, "[a-z0-9]", vec![rclass(&[('a', 'z'), ('0', '9')])]); - syntax!(cls18, "[!0-9a-z]", vec![rclassn(&[('0', '9'), ('a', 'z')])]); - syntax!(cls19, "[!a-z0-9]", vec![rclassn(&[('a', 'z'), ('0', '9')])]); - - syntaxerr!(err_rseq1, "a**", ErrorKind::InvalidRecursive); - syntaxerr!(err_rseq2, "**a", ErrorKind::InvalidRecursive); - syntaxerr!(err_rseq3, "a**b", ErrorKind::InvalidRecursive); - syntaxerr!(err_rseq4, "***", ErrorKind::InvalidRecursive); - syntaxerr!(err_rseq5, "/a**", ErrorKind::InvalidRecursive); - syntaxerr!(err_rseq6, "/**a", ErrorKind::InvalidRecursive); - syntaxerr!(err_rseq7, "/a**b", ErrorKind::InvalidRecursive); - syntaxerr!(err_unclosed1, "[", ErrorKind::UnclosedClass); - syntaxerr!(err_unclosed2, "[]", ErrorKind::UnclosedClass); - syntaxerr!(err_unclosed3, "[!", ErrorKind::UnclosedClass); - syntaxerr!(err_unclosed4, "[!]", ErrorKind::UnclosedClass); - syntaxerr!(err_range1, "[z-a]", ErrorKind::InvalidRange('z', 'a')); - syntaxerr!(err_range2, "[z--]", ErrorKind::InvalidRange('z', '-')); - - const CASEI: Options = Options { - casei: true, - litsep: false, - }; - const SLASHLIT: Options = Options { - casei: false, - litsep: true, - }; - - toregex!(re_casei, "a", "(?i)^a$", &CASEI); - - toregex!(re_slash1, "?", r"^[^/]$", SLASHLIT); - toregex!(re_slash2, "*", r"^[^/]*$", SLASHLIT); - - toregex!(re1, "a", "^a$"); - toregex!(re2, "?", "^.$"); - toregex!(re3, "*", "^.*$"); - toregex!(re4, "a?", "^a.$"); - toregex!(re5, "?a", "^.a$"); - toregex!(re6, "a*", "^a.*$"); - toregex!(re7, "*a", "^.*a$"); - toregex!(re8, "[*]", r"^[\*]$"); - toregex!(re9, "[+]", r"^[\+]$"); - toregex!(re10, "+", r"^\+$"); - toregex!(re11, "**", r"^.*$"); - toregex!(re12, "☃", r"^\xe2\x98\x83$"); - - matches!(match1, "a", "a"); - matches!(match2, "a*b", "a_b"); - matches!(match3, "a*b*c", "abc"); - matches!(match4, "a*b*c", "a_b_c"); - matches!(match5, "a*b*c", "a___b___c"); - matches!(match6, "abc*abc*abc", "abcabcabcabcabcabcabc"); - matches!(match7, "a*a*a*a*a*a*a*a*a", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); - matches!(match8, "a*b[xyz]c*d", "abxcdbxcddd"); - matches!(match9, "*.rs", ".rs"); - matches!(match10, "☃", "☃"); - - matches!(matchrec1, "some/**/needle.txt", "some/needle.txt"); - matches!(matchrec2, "some/**/needle.txt", "some/one/needle.txt"); - matches!(matchrec3, "some/**/needle.txt", "some/one/two/needle.txt"); - matches!(matchrec4, "some/**/needle.txt", "some/other/needle.txt"); - matches!(matchrec5, "**", "abcde"); - matches!(matchrec6, "**", ""); - matches!(matchrec7, "**", ".asdf"); - matches!(matchrec8, "**", "/x/.asdf"); - matches!(matchrec9, "some/**/**/needle.txt", "some/needle.txt"); - matches!(matchrec10, "some/**/**/needle.txt", "some/one/needle.txt"); - matches!(matchrec11, "some/**/**/needle.txt", "some/one/two/needle.txt"); - matches!(matchrec12, "some/**/**/needle.txt", "some/other/needle.txt"); - matches!(matchrec13, "**/test", "one/two/test"); - matches!(matchrec14, "**/test", "one/test"); - matches!(matchrec15, "**/test", "test"); - matches!(matchrec16, "/**/test", "/one/two/test"); - matches!(matchrec17, "/**/test", "/one/test"); - matches!(matchrec18, "/**/test", "/test"); - matches!(matchrec19, "**/.*", ".abc"); - matches!(matchrec20, "**/.*", "abc/.abc"); - matches!(matchrec21, ".*/**", ".abc"); - matches!(matchrec22, ".*/**", ".abc/abc"); - matches!(matchrec23, "foo/**", "foo"); - matches!(matchrec24, "**/foo/bar", "foo/bar"); - - matches!(matchrange1, "a[0-9]b", "a0b"); - matches!(matchrange2, "a[0-9]b", "a9b"); - matches!(matchrange3, "a[!0-9]b", "a_b"); - matches!(matchrange4, "[a-z123]", "1"); - matches!(matchrange5, "[1a-z23]", "1"); - matches!(matchrange6, "[123a-z]", "1"); - matches!(matchrange7, "[abc-]", "-"); - matches!(matchrange8, "[-abc]", "-"); - matches!(matchrange9, "[-a-c]", "b"); - matches!(matchrange10, "[a-c-]", "b"); - matches!(matchrange11, "[-]", "-"); - - matches!(matchpat1, "*hello.txt", "hello.txt"); - matches!(matchpat2, "*hello.txt", "gareth_says_hello.txt"); - matches!(matchpat3, "*hello.txt", "some/path/to/hello.txt"); - matches!(matchpat4, "*hello.txt", "some\\path\\to\\hello.txt"); - matches!(matchpat5, "*hello.txt", "/an/absolute/path/to/hello.txt"); - matches!(matchpat6, "*some/path/to/hello.txt", "some/path/to/hello.txt"); - matches!(matchpat7, "*some/path/to/hello.txt", - "a/bigger/some/path/to/hello.txt"); - - matches!(matchescape, "_[[]_[]]_[?]_[*]_!_", "_[_]_?_*_!_"); - - matches!(matchcasei1, "aBcDeFg", "aBcDeFg", CASEI); - matches!(matchcasei2, "aBcDeFg", "abcdefg", CASEI); - matches!(matchcasei3, "aBcDeFg", "ABCDEFG", CASEI); - matches!(matchcasei4, "aBcDeFg", "AbCdEfG", CASEI); - - matches!(matchalt1, "a,b", "a,b"); - matches!(matchalt2, ",", ","); - matches!(matchalt3, "{a,b}", "a"); - matches!(matchalt4, "{a,b}", "b"); - matches!(matchalt5, "{**/src/**,foo}", "abc/src/bar"); - matches!(matchalt6, "{**/src/**,foo}", "foo"); - matches!(matchalt7, "{[}],foo}", "}"); - matches!(matchalt8, "{foo}", "foo"); - matches!(matchalt9, "{}", ""); - matches!(matchalt10, "{,}", ""); - matches!(matchalt11, "{*.foo,*.bar,*.wat}", "test.foo"); - matches!(matchalt12, "{*.foo,*.bar,*.wat}", "test.bar"); - matches!(matchalt13, "{*.foo,*.bar,*.wat}", "test.wat"); - - matches!(matchslash1, "abc/def", "abc/def", SLASHLIT); - #[cfg(unix)] - nmatches!(matchslash2, "abc?def", "abc/def", SLASHLIT); - #[cfg(not(unix))] - nmatches!(matchslash2, "abc?def", "abc\\def", SLASHLIT); - nmatches!(matchslash3, "abc*def", "abc/def", SLASHLIT); - matches!(matchslash4, "abc[/]def", "abc/def", SLASHLIT); // differs - #[cfg(unix)] - nmatches!(matchslash5, "abc\\def", "abc/def", SLASHLIT); - #[cfg(not(unix))] - matches!(matchslash5, "abc\\def", "abc/def", SLASHLIT); - - nmatches!(matchnot1, "a*b*c", "abcd"); - nmatches!(matchnot2, "abc*abc*abc", "abcabcabcabcabcabcabca"); - nmatches!(matchnot3, "some/**/needle.txt", "some/other/notthis.txt"); - nmatches!(matchnot4, "some/**/**/needle.txt", "some/other/notthis.txt"); - nmatches!(matchnot5, "/**/test", "test"); - nmatches!(matchnot6, "/**/test", "/one/notthis"); - nmatches!(matchnot7, "/**/test", "/notthis"); - nmatches!(matchnot8, "**/.*", "ab.c"); - nmatches!(matchnot9, "**/.*", "abc/ab.c"); - nmatches!(matchnot10, ".*/**", "a.bc"); - nmatches!(matchnot11, ".*/**", "abc/a.bc"); - nmatches!(matchnot12, "a[0-9]b", "a_b"); - nmatches!(matchnot13, "a[!0-9]b", "a0b"); - nmatches!(matchnot14, "a[!0-9]b", "a9b"); - nmatches!(matchnot15, "[!-]", "-"); - nmatches!(matchnot16, "*hello.txt", "hello.txt-and-then-some"); - nmatches!(matchnot17, "*hello.txt", "goodbye.txt"); - nmatches!(matchnot18, "*some/path/to/hello.txt", - "some/path/to/hello.txt-and-then-some"); - nmatches!(matchnot19, "*some/path/to/hello.txt", - "some/other/path/to/hello.txt"); - nmatches!(matchnot20, "a", "foo/a"); - nmatches!(matchnot21, "./foo", "foo"); - nmatches!(matchnot22, "**/foo", "foofoo"); - nmatches!(matchnot23, "**/foo/bar", "foofoo/bar"); - nmatches!(matchnot24, "/*.c", "mozilla-sha1/sha1.c"); - nmatches!(matchnot25, "*.c", "mozilla-sha1/sha1.c", SLASHLIT); - nmatches!(matchnot26, "**/m4/ltoptions.m4", - "csharp/src/packages/repositories.config", SLASHLIT); - - macro_rules! extract { - ($which:ident, $name:ident, $pat:expr, $expect:expr) => { - extract!($which, $name, $pat, $expect, Options::default()); - }; - ($which:ident, $name:ident, $pat:expr, $expect:expr, $opts:expr) => { - #[test] - fn $name() { - let pat = GlobBuilder::new($pat) - .case_insensitive($opts.casei) - .literal_separator($opts.litsep) - .build().unwrap(); - assert_eq!($expect, pat.$which()); - } - }; - } - - macro_rules! literal { - ($($tt:tt)*) => { extract!(literal, $($tt)*); } - } - - macro_rules! basetokens { - ($($tt:tt)*) => { extract!(basename_tokens, $($tt)*); } - } - - macro_rules! ext { - ($($tt:tt)*) => { extract!(ext, $($tt)*); } - } - - macro_rules! required_ext { - ($($tt:tt)*) => { extract!(required_ext, $($tt)*); } - } - - macro_rules! prefix { - ($($tt:tt)*) => { extract!(prefix, $($tt)*); } - } - - macro_rules! suffix { - ($($tt:tt)*) => { extract!(suffix, $($tt)*); } - } - - macro_rules! baseliteral { - ($($tt:tt)*) => { extract!(basename_literal, $($tt)*); } - } - - literal!(extract_lit1, "foo", Some(s("foo"))); - literal!(extract_lit2, "foo", None, CASEI); - literal!(extract_lit3, "/foo", Some(s("/foo"))); - literal!(extract_lit4, "/foo/", Some(s("/foo/"))); - literal!(extract_lit5, "/foo/bar", Some(s("/foo/bar"))); - literal!(extract_lit6, "*.foo", None); - literal!(extract_lit7, "foo/bar", Some(s("foo/bar"))); - literal!(extract_lit8, "**/foo/bar", None); - - basetokens!(extract_basetoks1, "**/foo", Some(&*vec![ - Literal('f'), Literal('o'), Literal('o'), - ])); - basetokens!(extract_basetoks2, "**/foo", None, CASEI); - basetokens!(extract_basetoks3, "**/foo", Some(&*vec![ - Literal('f'), Literal('o'), Literal('o'), - ]), SLASHLIT); - basetokens!(extract_basetoks4, "*foo", None, SLASHLIT); - basetokens!(extract_basetoks5, "*foo", None); - basetokens!(extract_basetoks6, "**/fo*o", None); - basetokens!(extract_basetoks7, "**/fo*o", Some(&*vec![ - Literal('f'), Literal('o'), ZeroOrMore, Literal('o'), - ]), SLASHLIT); - - ext!(extract_ext1, "**/*.rs", Some(os(".rs"))); - ext!(extract_ext2, "**/*.rs.bak", None); - ext!(extract_ext3, "*.rs", Some(os(".rs"))); - ext!(extract_ext4, "a*.rs", None); - ext!(extract_ext5, "/*.c", None); - ext!(extract_ext6, "*.c", None, SLASHLIT); - ext!(extract_ext7, "*.c", Some(os(".c"))); - - required_ext!(extract_req_ext1, "*.rs", Some(os(".rs"))); - required_ext!(extract_req_ext2, "/foo/bar/*.rs", Some(os(".rs"))); - required_ext!(extract_req_ext3, "/foo/bar/*.rs", Some(os(".rs"))); - required_ext!(extract_req_ext4, "/foo/bar/.rs", Some(os(".rs"))); - required_ext!(extract_req_ext5, ".rs", Some(os(".rs"))); - required_ext!(extract_req_ext6, "./rs", None); - required_ext!(extract_req_ext7, "foo", None); - required_ext!(extract_req_ext8, ".foo/", None); - required_ext!(extract_req_ext9, "foo/", None); - - prefix!(extract_prefix1, "/foo", Some(s("/foo"))); - prefix!(extract_prefix2, "/foo/*", Some(s("/foo/"))); - prefix!(extract_prefix3, "**/foo", None); - prefix!(extract_prefix4, "foo/**", None); - - suffix!(extract_suffix1, "**/foo/bar", Some((s("/foo/bar"), true))); - suffix!(extract_suffix2, "*/foo/bar", Some((s("/foo/bar"), false))); - suffix!(extract_suffix3, "*/foo/bar", None, SLASHLIT); - suffix!(extract_suffix4, "foo/bar", Some((s("foo/bar"), false))); - suffix!(extract_suffix5, "*.foo", Some((s(".foo"), false))); - suffix!(extract_suffix6, "*.foo", None, SLASHLIT); - suffix!(extract_suffix7, "**/*_test", Some((s("_test"), false))); - - baseliteral!(extract_baselit1, "**/foo", Some(s("foo"))); - baseliteral!(extract_baselit2, "foo", None); - baseliteral!(extract_baselit3, "*foo", None); - baseliteral!(extract_baselit4, "*/foo", None); -} diff -Nru cargo-0.25.0/vendor/globset-0.2.1/src/lib.rs cargo-0.26.0/vendor/globset-0.2.1/src/lib.rs --- cargo-0.25.0/vendor/globset-0.2.1/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.2.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,835 +0,0 @@ -/*! -The globset crate provides cross platform single glob and glob set matching. - -Glob set matching is the process of matching one or more glob patterns against -a single candidate path simultaneously, and returning all of the globs that -matched. For example, given this set of globs: - -```ignore -*.rs -src/lib.rs -src/**/foo.rs -``` - -and a path `src/bar/baz/foo.rs`, then the set would report the first and third -globs as matching. - -# Example: one glob - -This example shows how to match a single glob against a single file path. - -``` -# fn example() -> Result<(), globset::Error> { -use globset::Glob; - -let glob = try!(Glob::new("*.rs")).compile_matcher(); - -assert!(glob.is_match("foo.rs")); -assert!(glob.is_match("foo/bar.rs")); -assert!(!glob.is_match("Cargo.toml")); -# Ok(()) } example().unwrap(); -``` - -# Example: configuring a glob matcher - -This example shows how to use a `GlobBuilder` to configure aspects of match -semantics. In this example, we prevent wildcards from matching path separators. - -``` -# fn example() -> Result<(), globset::Error> { -use globset::GlobBuilder; - -let glob = try!(GlobBuilder::new("*.rs") - .literal_separator(true).build()).compile_matcher(); - -assert!(glob.is_match("foo.rs")); -assert!(!glob.is_match("foo/bar.rs")); // no longer matches -assert!(!glob.is_match("Cargo.toml")); -# Ok(()) } example().unwrap(); -``` - -# Example: match multiple globs at once - -This example shows how to match multiple glob patterns at once. - -``` -# fn example() -> Result<(), globset::Error> { -use globset::{Glob, GlobSetBuilder}; - -let mut builder = GlobSetBuilder::new(); -// A GlobBuilder can be used to configure each glob's match semantics -// independently. -builder.add(try!(Glob::new("*.rs"))); -builder.add(try!(Glob::new("src/lib.rs"))); -builder.add(try!(Glob::new("src/**/foo.rs"))); -let set = try!(builder.build()); - -assert_eq!(set.matches("src/bar/baz/foo.rs"), vec![0, 2]); -# Ok(()) } example().unwrap(); -``` - -# Syntax - -Standard Unix-style glob syntax is supported: - -* `?` matches any single character. (If the `literal_separator` option is - enabled, then `?` can never match a path separator.) -* `*` matches zero or more characters. (If the `literal_separator` option is - enabled, then `*` can never match a path separator.) -* `**` recursively matches directories but are only legal in three situations. - First, if the glob starts with \*\*/, then it matches - all directories. For example, \*\*/foo matches `foo` - and `bar/foo` but not `foo/bar`. Secondly, if the glob ends with - /\*\*, then it matches all sub-entries. For example, - foo/\*\* matches `foo/a` and `foo/a/b`, but not `foo`. - Thirdly, if the glob contains /\*\*/ anywhere within - the pattern, then it matches zero or more directories. Using `**` anywhere - else is illegal (N.B. the glob `**` is allowed and means "match everything"). -* `{a,b}` matches `a` or `b` where `a` and `b` are arbitrary glob patterns. - (N.B. Nesting `{...}` is not currently allowed.) -* `[ab]` matches `a` or `b` where `a` and `b` are characters. Use - `[!ab]` to match any character except for `a` and `b`. -* Metacharacters such as `*` and `?` can be escaped with character class - notation. e.g., `[*]` matches `*`. - -A `GlobBuilder` can be used to prevent wildcards from matching path separators, -or to enable case insensitive matching. -*/ - -#![deny(missing_docs)] - -extern crate aho_corasick; -extern crate fnv; -#[macro_use] -extern crate log; -extern crate memchr; -extern crate regex; - -use std::borrow::Cow; -use std::collections::{BTreeMap, HashMap}; -use std::error::Error as StdError; -use std::ffi::{OsStr, OsString}; -use std::fmt; -use std::hash; -use std::path::Path; -use std::str; - -use aho_corasick::{Automaton, AcAutomaton, FullAcAutomaton}; -use regex::bytes::{Regex, RegexBuilder, RegexSet}; - -use pathutil::{ - file_name, file_name_ext, normalize_path, os_str_bytes, path_bytes, -}; -use glob::MatchStrategy; -pub use glob::{Glob, GlobBuilder, GlobMatcher}; - -mod glob; -mod pathutil; - -/// Represents an error that can occur when parsing a glob pattern. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct Error { - /// The original glob provided by the caller. - glob: Option, - /// The kind of error. - kind: ErrorKind, -} - -/// The kind of error that can occur when parsing a glob pattern. -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum ErrorKind { - /// Occurs when a use of `**` is invalid. Namely, `**` can only appear - /// adjacent to a path separator, or the beginning/end of a glob. - InvalidRecursive, - /// Occurs when a character class (e.g., `[abc]`) is not closed. - UnclosedClass, - /// Occurs when a range in a character (e.g., `[a-z]`) is invalid. For - /// example, if the range starts with a lexicographically larger character - /// than it ends with. - InvalidRange(char, char), - /// Occurs when a `}` is found without a matching `{`. - UnopenedAlternates, - /// Occurs when a `{` is found without a matching `}`. - UnclosedAlternates, - /// Occurs when an alternating group is nested inside another alternating - /// group, e.g., `{{a,b},{c,d}}`. - NestedAlternates, - /// An error associated with parsing or compiling a regex. - Regex(String), -} - -impl StdError for Error { - fn description(&self) -> &str { - self.kind.description() - } -} - -impl Error { - /// Return the glob that caused this error, if one exists. - pub fn glob(&self) -> Option<&str> { - self.glob.as_ref().map(|s| &**s) - } - - /// Return the kind of this error. - pub fn kind(&self) -> &ErrorKind { - &self.kind - } -} - -impl ErrorKind { - fn description(&self) -> &str { - match *self { - ErrorKind::InvalidRecursive => { - "invalid use of **; must be one path component" - } - ErrorKind::UnclosedClass => { - "unclosed character class; missing ']'" - } - ErrorKind::InvalidRange(_, _) => { - "invalid character range" - } - ErrorKind::UnopenedAlternates => { - "unopened alternate group; missing '{' \ - (maybe escape '}' with '[}]'?)" - } - ErrorKind::UnclosedAlternates => { - "unclosed alternate group; missing '}' \ - (maybe escape '{' with '[{]'?)" - } - ErrorKind::NestedAlternates => { - "nested alternate groups are not allowed" - } - ErrorKind::Regex(ref err) => err, - } - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.glob { - None => self.kind.fmt(f), - Some(ref glob) => { - write!(f, "error parsing glob '{}': {}", glob, self.kind) - } - } - } -} - -impl fmt::Display for ErrorKind { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - ErrorKind::InvalidRecursive - | ErrorKind::UnclosedClass - | ErrorKind::UnopenedAlternates - | ErrorKind::UnclosedAlternates - | ErrorKind::NestedAlternates - | ErrorKind::Regex(_) => { - write!(f, "{}", self.description()) - } - ErrorKind::InvalidRange(s, e) => { - write!(f, "invalid range; '{}' > '{}'", s, e) - } - } - } -} - -fn new_regex(pat: &str) -> Result { - RegexBuilder::new(pat) - .dot_matches_new_line(true) - .size_limit(10 * (1 << 20)) - .dfa_size_limit(10 * (1 << 20)) - .build() - .map_err(|err| { - Error { - glob: Some(pat.to_string()), - kind: ErrorKind::Regex(err.to_string()), - } - }) -} - -fn new_regex_set(pats: I) -> Result - where S: AsRef, I: IntoIterator { - RegexSet::new(pats).map_err(|err| { - Error { - glob: None, - kind: ErrorKind::Regex(err.to_string()), - } - }) -} - -type Fnv = hash::BuildHasherDefault; - -/// GlobSet represents a group of globs that can be matched together in a -/// single pass. -#[derive(Clone, Debug)] -pub struct GlobSet { - len: usize, - strats: Vec, -} - -impl GlobSet { - /// Returns true if this set is empty, and therefore matches nothing. - pub fn is_empty(&self) -> bool { - self.len == 0 - } - - /// Returns the number of globs in this set. - pub fn len(&self) -> usize { - self.len - } - - /// Returns true if any glob in this set matches the path given. - pub fn is_match>(&self, path: P) -> bool { - self.is_match_candidate(&Candidate::new(path.as_ref())) - } - - /// Returns true if any glob in this set matches the path given. - /// - /// This takes a Candidate as input, which can be used to amortize the - /// cost of preparing a path for matching. - pub fn is_match_candidate(&self, path: &Candidate) -> bool { - if self.is_empty() { - return false; - } - for strat in &self.strats { - if strat.is_match(path) { - return true; - } - } - false - } - - /// Returns the sequence number of every glob pattern that matches the - /// given path. - pub fn matches>(&self, path: P) -> Vec { - self.matches_candidate(&Candidate::new(path.as_ref())) - } - - /// Returns the sequence number of every glob pattern that matches the - /// given path. - /// - /// This takes a Candidate as input, which can be used to amortize the - /// cost of preparing a path for matching. - pub fn matches_candidate(&self, path: &Candidate) -> Vec { - let mut into = vec![]; - if self.is_empty() { - return into; - } - self.matches_candidate_into(path, &mut into); - into - } - - /// Adds the sequence number of every glob pattern that matches the given - /// path to the vec given. - /// - /// `into` is is cleared before matching begins, and contains the set of - /// sequence numbers (in ascending order) after matching ends. If no globs - /// were matched, then `into` will be empty. - pub fn matches_into>( - &self, - path: P, - into: &mut Vec, - ) { - self.matches_candidate_into(&Candidate::new(path.as_ref()), into); - } - - /// Adds the sequence number of every glob pattern that matches the given - /// path to the vec given. - /// - /// `into` is is cleared before matching begins, and contains the set of - /// sequence numbers (in ascending order) after matching ends. If no globs - /// were matched, then `into` will be empty. - /// - /// This takes a Candidate as input, which can be used to amortize the - /// cost of preparing a path for matching. - pub fn matches_candidate_into( - &self, - path: &Candidate, - into: &mut Vec, - ) { - into.clear(); - if self.is_empty() { - return; - } - for strat in &self.strats { - strat.matches_into(path, into); - } - into.sort(); - into.dedup(); - } - - fn new(pats: &[Glob]) -> Result { - if pats.is_empty() { - return Ok(GlobSet { len: 0, strats: vec![] }); - } - let mut lits = LiteralStrategy::new(); - let mut base_lits = BasenameLiteralStrategy::new(); - let mut exts = ExtensionStrategy::new(); - let mut prefixes = MultiStrategyBuilder::new(); - let mut suffixes = MultiStrategyBuilder::new(); - let mut required_exts = RequiredExtensionStrategyBuilder::new(); - let mut regexes = MultiStrategyBuilder::new(); - for (i, p) in pats.iter().enumerate() { - match MatchStrategy::new(p) { - MatchStrategy::Literal(lit) => { - lits.add(i, lit); - } - MatchStrategy::BasenameLiteral(lit) => { - base_lits.add(i, lit); - } - MatchStrategy::Extension(ext) => { - exts.add(i, ext); - } - MatchStrategy::Prefix(prefix) => { - prefixes.add(i, prefix); - } - MatchStrategy::Suffix { suffix, component } => { - if component { - lits.add(i, suffix[1..].to_string()); - } - suffixes.add(i, suffix); - } - MatchStrategy::RequiredExtension(ext) => { - required_exts.add(i, ext, p.regex().to_owned()); - } - MatchStrategy::Regex => { - debug!("glob converted to regex: {:?}", p); - regexes.add(i, p.regex().to_owned()); - } - } - } - debug!("built glob set; {} literals, {} basenames, {} extensions, \ - {} prefixes, {} suffixes, {} required extensions, {} regexes", - lits.0.len(), base_lits.0.len(), exts.0.len(), - prefixes.literals.len(), suffixes.literals.len(), - required_exts.0.len(), regexes.literals.len()); - Ok(GlobSet { - len: pats.len(), - strats: vec![ - GlobSetMatchStrategy::Extension(exts), - GlobSetMatchStrategy::BasenameLiteral(base_lits), - GlobSetMatchStrategy::Literal(lits), - GlobSetMatchStrategy::Suffix(suffixes.suffix()), - GlobSetMatchStrategy::Prefix(prefixes.prefix()), - GlobSetMatchStrategy::RequiredExtension( - try!(required_exts.build())), - GlobSetMatchStrategy::Regex(try!(regexes.regex_set())), - ], - }) - } -} - -/// GlobSetBuilder builds a group of patterns that can be used to -/// simultaneously match a file path. -pub struct GlobSetBuilder { - pats: Vec, -} - -impl GlobSetBuilder { - /// Create a new GlobSetBuilder. A GlobSetBuilder can be used to add new - /// patterns. Once all patterns have been added, `build` should be called - /// to produce a `GlobSet`, which can then be used for matching. - pub fn new() -> GlobSetBuilder { - GlobSetBuilder { pats: vec![] } - } - - /// Builds a new matcher from all of the glob patterns added so far. - /// - /// Once a matcher is built, no new patterns can be added to it. - pub fn build(&self) -> Result { - GlobSet::new(&self.pats) - } - - /// Add a new pattern to this set. - #[allow(dead_code)] - pub fn add(&mut self, pat: Glob) -> &mut GlobSetBuilder { - self.pats.push(pat); - self - } -} - -/// A candidate path for matching. -/// -/// All glob matching in this crate operates on `Candidate` values. -/// Constructing candidates has a very small cost associated with it, so -/// callers may find it beneficial to amortize that cost when matching a single -/// path against multiple globs or sets of globs. -#[derive(Clone, Debug)] -pub struct Candidate<'a> { - path: Cow<'a, [u8]>, - basename: Cow<'a, [u8]>, - ext: &'a OsStr, -} - -impl<'a> Candidate<'a> { - /// Create a new candidate for matching from the given path. - pub fn new + ?Sized>(path: &'a P) -> Candidate<'a> { - let path = path.as_ref(); - let basename = file_name(path).unwrap_or(OsStr::new("")); - Candidate { - path: normalize_path(path_bytes(path)), - basename: os_str_bytes(basename), - ext: file_name_ext(basename).unwrap_or(OsStr::new("")), - } - } - - fn path_prefix(&self, max: usize) -> &[u8] { - if self.path.len() <= max { - &*self.path - } else { - &self.path[..max] - } - } - - fn path_suffix(&self, max: usize) -> &[u8] { - if self.path.len() <= max { - &*self.path - } else { - &self.path[self.path.len() - max..] - } - } -} - -#[derive(Clone, Debug)] -enum GlobSetMatchStrategy { - Literal(LiteralStrategy), - BasenameLiteral(BasenameLiteralStrategy), - Extension(ExtensionStrategy), - Prefix(PrefixStrategy), - Suffix(SuffixStrategy), - RequiredExtension(RequiredExtensionStrategy), - Regex(RegexSetStrategy), -} - -impl GlobSetMatchStrategy { - fn is_match(&self, candidate: &Candidate) -> bool { - use self::GlobSetMatchStrategy::*; - match *self { - Literal(ref s) => s.is_match(candidate), - BasenameLiteral(ref s) => s.is_match(candidate), - Extension(ref s) => s.is_match(candidate), - Prefix(ref s) => s.is_match(candidate), - Suffix(ref s) => s.is_match(candidate), - RequiredExtension(ref s) => s.is_match(candidate), - Regex(ref s) => s.is_match(candidate), - } - } - - fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { - use self::GlobSetMatchStrategy::*; - match *self { - Literal(ref s) => s.matches_into(candidate, matches), - BasenameLiteral(ref s) => s.matches_into(candidate, matches), - Extension(ref s) => s.matches_into(candidate, matches), - Prefix(ref s) => s.matches_into(candidate, matches), - Suffix(ref s) => s.matches_into(candidate, matches), - RequiredExtension(ref s) => s.matches_into(candidate, matches), - Regex(ref s) => s.matches_into(candidate, matches), - } - } -} - -#[derive(Clone, Debug)] -struct LiteralStrategy(BTreeMap, Vec>); - -impl LiteralStrategy { - fn new() -> LiteralStrategy { - LiteralStrategy(BTreeMap::new()) - } - - fn add(&mut self, global_index: usize, lit: String) { - self.0.entry(lit.into_bytes()).or_insert(vec![]).push(global_index); - } - - fn is_match(&self, candidate: &Candidate) -> bool { - self.0.contains_key(&*candidate.path) - } - - #[inline(never)] - fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { - if let Some(hits) = self.0.get(&*candidate.path) { - matches.extend(hits); - } - } -} - -#[derive(Clone, Debug)] -struct BasenameLiteralStrategy(BTreeMap, Vec>); - -impl BasenameLiteralStrategy { - fn new() -> BasenameLiteralStrategy { - BasenameLiteralStrategy(BTreeMap::new()) - } - - fn add(&mut self, global_index: usize, lit: String) { - self.0.entry(lit.into_bytes()).or_insert(vec![]).push(global_index); - } - - fn is_match(&self, candidate: &Candidate) -> bool { - if candidate.basename.is_empty() { - return false; - } - self.0.contains_key(&*candidate.basename) - } - - #[inline(never)] - fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { - if candidate.basename.is_empty() { - return; - } - if let Some(hits) = self.0.get(&*candidate.basename) { - matches.extend(hits); - } - } -} - -#[derive(Clone, Debug)] -struct ExtensionStrategy(HashMap, Fnv>); - -impl ExtensionStrategy { - fn new() -> ExtensionStrategy { - ExtensionStrategy(HashMap::with_hasher(Fnv::default())) - } - - fn add(&mut self, global_index: usize, ext: OsString) { - self.0.entry(ext).or_insert(vec![]).push(global_index); - } - - fn is_match(&self, candidate: &Candidate) -> bool { - if candidate.ext.is_empty() { - return false; - } - self.0.contains_key(candidate.ext) - } - - #[inline(never)] - fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { - if candidate.ext.is_empty() { - return; - } - if let Some(hits) = self.0.get(candidate.ext) { - matches.extend(hits); - } - } -} - -#[derive(Clone, Debug)] -struct PrefixStrategy { - matcher: FullAcAutomaton>, - map: Vec, - longest: usize, -} - -impl PrefixStrategy { - fn is_match(&self, candidate: &Candidate) -> bool { - let path = candidate.path_prefix(self.longest); - for m in self.matcher.find_overlapping(path) { - if m.start == 0 { - return true; - } - } - false - } - - fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { - let path = candidate.path_prefix(self.longest); - for m in self.matcher.find_overlapping(path) { - if m.start == 0 { - matches.push(self.map[m.pati]); - } - } - } -} - -#[derive(Clone, Debug)] -struct SuffixStrategy { - matcher: FullAcAutomaton>, - map: Vec, - longest: usize, -} - -impl SuffixStrategy { - fn is_match(&self, candidate: &Candidate) -> bool { - let path = candidate.path_suffix(self.longest); - for m in self.matcher.find_overlapping(path) { - if m.end == path.len() { - return true; - } - } - false - } - - fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { - let path = candidate.path_suffix(self.longest); - for m in self.matcher.find_overlapping(path) { - if m.end == path.len() { - matches.push(self.map[m.pati]); - } - } - } -} - -#[derive(Clone, Debug)] -struct RequiredExtensionStrategy(HashMap, Fnv>); - -impl RequiredExtensionStrategy { - fn is_match(&self, candidate: &Candidate) -> bool { - if candidate.ext.is_empty() { - return false; - } - match self.0.get(candidate.ext) { - None => false, - Some(regexes) => { - for &(_, ref re) in regexes { - if re.is_match(&*candidate.path) { - return true; - } - } - false - } - } - } - - #[inline(never)] - fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { - if candidate.ext.is_empty() { - return; - } - if let Some(regexes) = self.0.get(candidate.ext) { - for &(global_index, ref re) in regexes { - if re.is_match(&*candidate.path) { - matches.push(global_index); - } - } - } - } -} - -#[derive(Clone, Debug)] -struct RegexSetStrategy { - matcher: RegexSet, - map: Vec, -} - -impl RegexSetStrategy { - fn is_match(&self, candidate: &Candidate) -> bool { - self.matcher.is_match(&*candidate.path) - } - - fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { - for i in self.matcher.matches(&*candidate.path) { - matches.push(self.map[i]); - } - } -} - -#[derive(Clone, Debug)] -struct MultiStrategyBuilder { - literals: Vec, - map: Vec, - longest: usize, -} - -impl MultiStrategyBuilder { - fn new() -> MultiStrategyBuilder { - MultiStrategyBuilder { - literals: vec![], - map: vec![], - longest: 0, - } - } - - fn add(&mut self, global_index: usize, literal: String) { - if literal.len() > self.longest { - self.longest = literal.len(); - } - self.map.push(global_index); - self.literals.push(literal); - } - - fn prefix(self) -> PrefixStrategy { - let it = self.literals.into_iter().map(|s| s.into_bytes()); - PrefixStrategy { - matcher: AcAutomaton::new(it).into_full(), - map: self.map, - longest: self.longest, - } - } - - fn suffix(self) -> SuffixStrategy { - let it = self.literals.into_iter().map(|s| s.into_bytes()); - SuffixStrategy { - matcher: AcAutomaton::new(it).into_full(), - map: self.map, - longest: self.longest, - } - } - - fn regex_set(self) -> Result { - Ok(RegexSetStrategy { - matcher: try!(new_regex_set(self.literals)), - map: self.map, - }) - } -} - -#[derive(Clone, Debug)] -struct RequiredExtensionStrategyBuilder( - HashMap>, -); - -impl RequiredExtensionStrategyBuilder { - fn new() -> RequiredExtensionStrategyBuilder { - RequiredExtensionStrategyBuilder(HashMap::new()) - } - - fn add(&mut self, global_index: usize, ext: OsString, regex: String) { - self.0.entry(ext).or_insert(vec![]).push((global_index, regex)); - } - - fn build(self) -> Result { - let mut exts = HashMap::with_hasher(Fnv::default()); - for (ext, regexes) in self.0.into_iter() { - exts.insert(ext.clone(), vec![]); - for (global_index, regex) in regexes { - let compiled = try!(new_regex(®ex)); - exts.get_mut(&ext).unwrap().push((global_index, compiled)); - } - } - Ok(RequiredExtensionStrategy(exts)) - } -} - -#[cfg(test)] -mod tests { - use super::GlobSetBuilder; - use glob::Glob; - - #[test] - fn set_works() { - let mut builder = GlobSetBuilder::new(); - builder.add(Glob::new("src/**/*.rs").unwrap()); - builder.add(Glob::new("*.c").unwrap()); - builder.add(Glob::new("src/lib.rs").unwrap()); - let set = builder.build().unwrap(); - - assert!(set.is_match("foo.c")); - assert!(set.is_match("src/foo.c")); - assert!(!set.is_match("foo.rs")); - assert!(!set.is_match("tests/foo.rs")); - assert!(set.is_match("src/foo.rs")); - assert!(set.is_match("src/grep/src/main.rs")); - - let matches = set.matches("src/lib.rs"); - assert_eq!(2, matches.len()); - assert_eq!(0, matches[0]); - assert_eq!(2, matches[1]); - } - - #[test] - fn empty_set_works() { - let set = GlobSetBuilder::new().build().unwrap(); - assert!(!set.is_match("")); - assert!(!set.is_match("a")); - } -} diff -Nru cargo-0.25.0/vendor/globset-0.2.1/src/pathutil.rs cargo-0.26.0/vendor/globset-0.2.1/src/pathutil.rs --- cargo-0.25.0/vendor/globset-0.2.1/src/pathutil.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.2.1/src/pathutil.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,178 +0,0 @@ -use std::borrow::Cow; -use std::ffi::OsStr; -use std::path::Path; - -/// The final component of the path, if it is a normal file. -/// -/// If the path terminates in ., .., or consists solely of a root of prefix, -/// file_name will return None. -#[cfg(unix)] -pub fn file_name<'a, P: AsRef + ?Sized>( - path: &'a P, -) -> Option<&'a OsStr> { - use std::os::unix::ffi::OsStrExt; - use memchr::memrchr; - - let path = path.as_ref().as_os_str().as_bytes(); - if path.is_empty() { - return None; - } else if path.len() == 1 && path[0] == b'.' { - return None; - } else if path.last() == Some(&b'.') { - return None; - } else if path.len() >= 2 && &path[path.len() - 2..] == &b".."[..] { - return None; - } - let last_slash = memrchr(b'/', path).map(|i| i + 1).unwrap_or(0); - Some(OsStr::from_bytes(&path[last_slash..])) -} - -/// The final component of the path, if it is a normal file. -/// -/// If the path terminates in ., .., or consists solely of a root of prefix, -/// file_name will return None. -#[cfg(not(unix))] -pub fn file_name<'a, P: AsRef + ?Sized>( - path: &'a P, -) -> Option<&'a OsStr> { - path.as_ref().file_name() -} - -/// Return a file extension given a path's file name. -/// -/// Note that this does NOT match the semantics of std::path::Path::extension. -/// Namely, the extension includes the `.` and matching is otherwise more -/// liberal. Specifically, the extenion is: -/// -/// * None, if the file name given is empty; -/// * None, if there is no embedded `.`; -/// * Otherwise, the portion of the file name starting with the final `.`. -/// -/// e.g., A file name of `.rs` has an extension `.rs`. -/// -/// N.B. This is done to make certain glob match optimizations easier. Namely, -/// a pattern like `*.rs` is obviously trying to match files with a `rs` -/// extension, but it also matches files like `.rs`, which doesn't have an -/// extension according to std::path::Path::extension. -pub fn file_name_ext(name: &OsStr) -> Option<&OsStr> { - // Yes, these functions are awful, and yes, we are completely violating - // the abstraction barrier of std::ffi. The barrier we're violating is - // that an OsStr's encoding is *ASCII compatible*. While this is obviously - // true on Unix systems, it's also true on Windows because an OsStr uses - // WTF-8 internally: https://simonsapin.github.io/wtf-8/ - // - // We should consider doing the same for the other path utility functions. - // Right now, we don't break any barriers, but Windows users are paying - // for it. - // - // Got any better ideas that don't cost anything? Hit me up. ---AG - unsafe fn os_str_as_u8_slice(s: &OsStr) -> &[u8] { - ::std::mem::transmute(s) - } - unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr { - ::std::mem::transmute(s) - } - if name.is_empty() { - return None; - } - let name = unsafe { os_str_as_u8_slice(name) }; - for (i, &b) in name.iter().enumerate().rev() { - if b == b'.' { - return Some(unsafe { u8_slice_as_os_str(&name[i..]) }); - } - } - None -} - -/// Return raw bytes of a path, transcoded to UTF-8 if necessary. -pub fn path_bytes(path: &Path) -> Cow<[u8]> { - os_str_bytes(path.as_os_str()) -} - -/// Return the raw bytes of the given OS string, possibly transcoded to UTF-8. -#[cfg(unix)] -pub fn os_str_bytes(s: &OsStr) -> Cow<[u8]> { - use std::os::unix::ffi::OsStrExt; - Cow::Borrowed(s.as_bytes()) -} - -/// Return the raw bytes of the given OS string, possibly transcoded to UTF-8. -#[cfg(not(unix))] -pub fn os_str_bytes(s: &OsStr) -> Cow<[u8]> { - // TODO(burntsushi): On Windows, OS strings are WTF-8, which is a superset - // of UTF-8, so even if we could get at the raw bytes, they wouldn't - // be useful. We *must* convert to UTF-8 before doing path matching. - // Unfortunate, but necessary. - match s.to_string_lossy() { - Cow::Owned(s) => Cow::Owned(s.into_bytes()), - Cow::Borrowed(s) => Cow::Borrowed(s.as_bytes()), - } -} - -/// Normalizes a path to use `/` as a separator everywhere, even on platforms -/// that recognize other characters as separators. -#[cfg(unix)] -pub fn normalize_path(path: Cow<[u8]>) -> Cow<[u8]> { - // UNIX only uses /, so we're good. - path -} - -/// Normalizes a path to use `/` as a separator everywhere, even on platforms -/// that recognize other characters as separators. -#[cfg(not(unix))] -pub fn normalize_path(mut path: Cow<[u8]>) -> Cow<[u8]> { - use std::path::is_separator; - - for i in 0..path.len() { - if path[i] == b'/' || !is_separator(path[i] as char) { - continue; - } - path.to_mut()[i] = b'/'; - } - path -} - -#[cfg(test)] -mod tests { - use std::borrow::Cow; - use std::ffi::OsStr; - - use super::{file_name_ext, normalize_path}; - - macro_rules! ext { - ($name:ident, $file_name:expr, $ext:expr) => { - #[test] - fn $name() { - let got = file_name_ext(OsStr::new($file_name)); - assert_eq!($ext.map(OsStr::new), got); - } - }; - } - - ext!(ext1, "foo.rs", Some(".rs")); - ext!(ext2, ".rs", Some(".rs")); - ext!(ext3, "..rs", Some(".rs")); - ext!(ext4, "", None::<&str>); - ext!(ext5, "foo", None::<&str>); - - macro_rules! normalize { - ($name:ident, $path:expr, $expected:expr) => { - #[test] - fn $name() { - let got = normalize_path(Cow::Owned($path.to_vec())); - assert_eq!($expected.to_vec(), got.into_owned()); - } - }; - } - - normalize!(normal1, b"foo", b"foo"); - normalize!(normal2, b"foo/bar", b"foo/bar"); - #[cfg(unix)] - normalize!(normal3, b"foo\\bar", b"foo\\bar"); - #[cfg(not(unix))] - normalize!(normal3, b"foo\\bar", b"foo/bar"); - #[cfg(unix)] - normalize!(normal4, b"foo\\bar/baz", b"foo\\bar/baz"); - #[cfg(not(unix))] - normalize!(normal4, b"foo\\bar/baz", b"foo/bar/baz"); -} diff -Nru cargo-0.25.0/vendor/globset-0.2.1/UNLICENSE cargo-0.26.0/vendor/globset-0.2.1/UNLICENSE --- cargo-0.25.0/vendor/globset-0.2.1/UNLICENSE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.2.1/UNLICENSE 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -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 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. - -For more information, please refer to diff -Nru cargo-0.25.0/vendor/globset-0.3.0/benches/bench.rs cargo-0.26.0/vendor/globset-0.3.0/benches/bench.rs --- cargo-0.25.0/vendor/globset-0.3.0/benches/bench.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.3.0/benches/bench.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,121 @@ +/*! +This module benchmarks the glob implementation. For benchmarks on the ripgrep +tool itself, see the benchsuite directory. +*/ +#![feature(test)] + +extern crate glob; +extern crate globset; +#[macro_use] +extern crate lazy_static; +extern crate regex; +extern crate test; + +use std::ffi::OsStr; +use std::path::Path; + +use globset::{Candidate, Glob, GlobMatcher, GlobSet, GlobSetBuilder}; + +const EXT: &'static str = "some/a/bigger/path/to/the/crazy/needle.txt"; +const EXT_PAT: &'static str = "*.txt"; + +const SHORT: &'static str = "some/needle.txt"; +const SHORT_PAT: &'static str = "some/**/needle.txt"; + +const LONG: &'static str = "some/a/bigger/path/to/the/crazy/needle.txt"; +const LONG_PAT: &'static str = "some/**/needle.txt"; + +fn new_glob(pat: &str) -> glob::Pattern { + glob::Pattern::new(pat).unwrap() +} + +fn new_reglob(pat: &str) -> GlobMatcher { + Glob::new(pat).unwrap().compile_matcher() +} + +fn new_reglob_many(pats: &[&str]) -> GlobSet { + let mut builder = GlobSetBuilder::new(); + for pat in pats { + builder.add(Glob::new(pat).unwrap()); + } + builder.build().unwrap() +} + +#[bench] +fn ext_glob(b: &mut test::Bencher) { + let pat = new_glob(EXT_PAT); + b.iter(|| assert!(pat.matches(EXT))); +} + +#[bench] +fn ext_regex(b: &mut test::Bencher) { + let set = new_reglob(EXT_PAT); + let cand = Candidate::new(EXT); + b.iter(|| assert!(set.is_match_candidate(&cand))); +} + +#[bench] +fn short_glob(b: &mut test::Bencher) { + let pat = new_glob(SHORT_PAT); + b.iter(|| assert!(pat.matches(SHORT))); +} + +#[bench] +fn short_regex(b: &mut test::Bencher) { + let set = new_reglob(SHORT_PAT); + let cand = Candidate::new(SHORT); + b.iter(|| assert!(set.is_match_candidate(&cand))); +} + +#[bench] +fn long_glob(b: &mut test::Bencher) { + let pat = new_glob(LONG_PAT); + b.iter(|| assert!(pat.matches(LONG))); +} + +#[bench] +fn long_regex(b: &mut test::Bencher) { + let set = new_reglob(LONG_PAT); + let cand = Candidate::new(LONG); + b.iter(|| assert!(set.is_match_candidate(&cand))); +} + +const MANY_SHORT_GLOBS: &'static [&'static str] = &[ + // Taken from a random .gitignore on my system. + ".*.swp", + "tags", + "target", + "*.lock", + "tmp", + "*.csv", + "*.fst", + "*-got", + "*.csv.idx", + "words", + "98m*", + "dict", + "test", + "months", +]; + +const MANY_SHORT_SEARCH: &'static str = "98m-blah.csv.idx"; + +#[bench] +fn many_short_glob(b: &mut test::Bencher) { + let pats: Vec<_> = MANY_SHORT_GLOBS.iter().map(|&s| new_glob(s)).collect(); + b.iter(|| { + let mut count = 0; + for pat in &pats { + if pat.matches(MANY_SHORT_SEARCH) { + count += 1; + } + } + assert_eq!(2, count); + }) +} + +#[bench] +fn many_short_regex_set(b: &mut test::Bencher) { + let set = new_reglob_many(MANY_SHORT_GLOBS); + b.iter(|| assert_eq!(2, set.matches(MANY_SHORT_SEARCH).iter().count())); +} diff -Nru cargo-0.25.0/vendor/globset-0.3.0/.cargo-checksum.json cargo-0.26.0/vendor/globset-0.3.0/.cargo-checksum.json --- cargo-0.25.0/vendor/globset-0.3.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.3.0/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"1e96ab92362c06811385ae9a34d2698e8a1160745e0c78fbb434a44c8de3fabc"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/globset-0.3.0/Cargo.toml cargo-0.26.0/vendor/globset-0.3.0/Cargo.toml --- cargo-0.25.0/vendor/globset-0.3.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.3.0/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,46 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "globset" +version = "0.3.0" +authors = ["Andrew Gallant "] +description = "Cross platform single glob and glob set matching. Glob set matching is the\nprocess of matching one or more glob patterns against a single candidate path\nsimultaneously, and returning all of the globs that matched.\n" +homepage = "https://github.com/BurntSushi/ripgrep/tree/master/globset" +documentation = "https://docs.rs/globset" +readme = "README.md" +keywords = ["regex", "glob", "multiple", "set", "pattern"] +license = "Unlicense/MIT" +repository = "https://github.com/BurntSushi/ripgrep/tree/master/globset" + +[lib] +name = "globset" +bench = false +[dependencies.aho-corasick] +version = "0.6.0" + +[dependencies.fnv] +version = "1.0" + +[dependencies.log] +version = "0.4" + +[dependencies.memchr] +version = "2" + +[dependencies.regex] +version = "0.2.1" +[dev-dependencies.glob] +version = "0.2" + +[features] +simd-accel = ["regex/simd-accel"] diff -Nru cargo-0.25.0/vendor/globset-0.3.0/COPYING cargo-0.26.0/vendor/globset-0.3.0/COPYING --- cargo-0.25.0/vendor/globset-0.3.0/COPYING 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.3.0/COPYING 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3 @@ +This project is dual-licensed under the Unlicense and MIT licenses. + +You may use this code under the terms of either license. diff -Nru cargo-0.25.0/vendor/globset-0.3.0/LICENSE-MIT cargo-0.26.0/vendor/globset-0.3.0/LICENSE-MIT --- cargo-0.25.0/vendor/globset-0.3.0/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.3.0/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +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. diff -Nru cargo-0.25.0/vendor/globset-0.3.0/README.md cargo-0.26.0/vendor/globset-0.3.0/README.md --- cargo-0.25.0/vendor/globset-0.3.0/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.3.0/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,122 @@ +globset +======= +Cross platform single glob and glob set matching. Glob set matching is the +process of matching one or more glob patterns against a single candidate path +simultaneously, and returning all of the globs that matched. + +[![Linux build status](https://api.travis-ci.org/BurntSushi/ripgrep.png)](https://travis-ci.org/BurntSushi/ripgrep) +[![Windows build status](https://ci.appveyor.com/api/projects/status/github/BurntSushi/ripgrep?svg=true)](https://ci.appveyor.com/project/BurntSushi/ripgrep) +[![](https://img.shields.io/crates/v/globset.svg)](https://crates.io/crates/globset) + +Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). + +### Documentation + +[https://docs.rs/globset](https://docs.rs/globset) + +### Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +globset = "0.2" +``` + +and this to your crate root: + +```rust +extern crate globset; +``` + +### Example: one glob + +This example shows how to match a single glob against a single file path. + +```rust +use globset::Glob; + +let glob = Glob::new("*.rs")?.compile_matcher(); + +assert!(glob.is_match("foo.rs")); +assert!(glob.is_match("foo/bar.rs")); +assert!(!glob.is_match("Cargo.toml")); +``` + +### Example: configuring a glob matcher + +This example shows how to use a `GlobBuilder` to configure aspects of match +semantics. In this example, we prevent wildcards from matching path separators. + +```rust +use globset::GlobBuilder; + +let glob = GlobBuilder::new("*.rs") + .literal_separator(true).build()?.compile_matcher(); + +assert!(glob.is_match("foo.rs")); +assert!(!glob.is_match("foo/bar.rs")); // no longer matches +assert!(!glob.is_match("Cargo.toml")); +``` + +### Example: match multiple globs at once + +This example shows how to match multiple glob patterns at once. + +```rust +use globset::{Glob, GlobSetBuilder}; + +let mut builder = GlobSetBuilder::new(); +// A GlobBuilder can be used to configure each glob's match semantics +// independently. +builder.add(Glob::new("*.rs")?); +builder.add(Glob::new("src/lib.rs")?); +builder.add(Glob::new("src/**/foo.rs")?); +let set = builder.build()?; + +assert_eq!(set.matches("src/bar/baz/foo.rs"), vec![0, 2]); +``` + +### Performance + +This crate implements globs by converting them to regular expressions, and +executing them with the +[`regex`](https://github.com/rust-lang-nursery/regex) +crate. + +For single glob matching, performance of this crate should be roughly on par +with the performance of the +[`glob`](https://github.com/rust-lang-nursery/glob) +crate. (`*_regex` correspond to benchmarks for this library while `*_glob` +correspond to benchmarks for the `glob` library.) +Optimizations in the `regex` crate may propel this library past `glob`, +particularly when matching longer paths. + +``` +test ext_glob ... bench: 425 ns/iter (+/- 21) +test ext_regex ... bench: 175 ns/iter (+/- 10) +test long_glob ... bench: 182 ns/iter (+/- 11) +test long_regex ... bench: 173 ns/iter (+/- 10) +test short_glob ... bench: 69 ns/iter (+/- 4) +test short_regex ... bench: 83 ns/iter (+/- 2) +``` + +The primary performance advantage of this crate is when matching multiple +globs against a single path. With the `glob` crate, one must match each glob +synchronously, one after the other. In this crate, many can be matched +simultaneously. For example: + +``` +test many_short_glob ... bench: 1,063 ns/iter (+/- 47) +test many_short_regex_set ... bench: 186 ns/iter (+/- 11) +``` + +### Comparison with the [`glob`](https://github.com/rust-lang-nursery/glob) crate + +* Supports alternate "or" globs, e.g., `*.{foo,bar}`. +* Can match non-UTF-8 file paths correctly. +* Supports matching multiple globs at once. +* Doesn't provide a recursive directory iterator of matching file paths, + although I believe this crate should grow one eventually. +* Supports case insensitive and require-literal-separator match options, but + **doesn't** support the require-literal-leading-dot option. diff -Nru cargo-0.25.0/vendor/globset-0.3.0/src/glob.rs cargo-0.26.0/vendor/globset-0.3.0/src/glob.rs --- cargo-0.25.0/vendor/globset-0.3.0/src/glob.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.3.0/src/glob.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1354 @@ +use std::fmt; +use std::hash; +use std::iter; +use std::ops::{Deref, DerefMut}; +use std::path::{Path, is_separator}; +use std::str; + +use regex; +use regex::bytes::Regex; + +use {Candidate, Error, ErrorKind, new_regex}; + +/// Describes a matching strategy for a particular pattern. +/// +/// This provides a way to more quickly determine whether a pattern matches +/// a particular file path in a way that scales with a large number of +/// patterns. For example, if many patterns are of the form `*.ext`, then it's +/// possible to test whether any of those patterns matches by looking up a +/// file path's extension in a hash table. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum MatchStrategy { + /// A pattern matches if and only if the entire file path matches this + /// literal string. + Literal(String), + /// A pattern matches if and only if the file path's basename matches this + /// literal string. + BasenameLiteral(String), + /// A pattern matches if and only if the file path's extension matches this + /// literal string. + Extension(String), + /// A pattern matches if and only if this prefix literal is a prefix of the + /// candidate file path. + Prefix(String), + /// A pattern matches if and only if this prefix literal is a prefix of the + /// candidate file path. + /// + /// An exception: if `component` is true, then `suffix` must appear at the + /// beginning of a file path or immediately following a `/`. + Suffix { + /// The actual suffix. + suffix: String, + /// Whether this must start at the beginning of a path component. + component: bool, + }, + /// A pattern matches only if the given extension matches the file path's + /// extension. Note that this is a necessary but NOT sufficient criterion. + /// Namely, if the extension matches, then a full regex search is still + /// required. + RequiredExtension(String), + /// A regex needs to be used for matching. + Regex, +} + +impl MatchStrategy { + /// Returns a matching strategy for the given pattern. + pub fn new(pat: &Glob) -> MatchStrategy { + if let Some(lit) = pat.basename_literal() { + MatchStrategy::BasenameLiteral(lit) + } else if let Some(lit) = pat.literal() { + MatchStrategy::Literal(lit) + } else if let Some(ext) = pat.ext() { + MatchStrategy::Extension(ext) + } else if let Some(prefix) = pat.prefix() { + MatchStrategy::Prefix(prefix) + } else if let Some((suffix, component)) = pat.suffix() { + MatchStrategy::Suffix { suffix: suffix, component: component } + } else if let Some(ext) = pat.required_ext() { + MatchStrategy::RequiredExtension(ext) + } else { + MatchStrategy::Regex + } + } +} + +/// Glob represents a successfully parsed shell glob pattern. +/// +/// It cannot be used directly to match file paths, but it can be converted +/// to a regular expression string or a matcher. +#[derive(Clone, Debug, Eq)] +pub struct Glob { + glob: String, + re: String, + opts: GlobOptions, + tokens: Tokens, +} + +impl PartialEq for Glob { + fn eq(&self, other: &Glob) -> bool { + self.glob == other.glob && self.opts == other.opts + } +} + +impl hash::Hash for Glob { + fn hash(&self, state: &mut H) { + self.glob.hash(state); + self.opts.hash(state); + } +} + +impl fmt::Display for Glob { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.glob.fmt(f) + } +} + +/// A matcher for a single pattern. +#[derive(Clone, Debug)] +pub struct GlobMatcher { + /// The underlying pattern. + pat: Glob, + /// The pattern, as a compiled regex. + re: Regex, +} + +impl GlobMatcher { + /// Tests whether the given path matches this pattern or not. + pub fn is_match>(&self, path: P) -> bool { + self.is_match_candidate(&Candidate::new(path.as_ref())) + } + + /// Tests whether the given path matches this pattern or not. + pub fn is_match_candidate(&self, path: &Candidate) -> bool { + self.re.is_match(&path.path) + } +} + +/// A strategic matcher for a single pattern. +#[cfg(test)] +#[derive(Clone, Debug)] +struct GlobStrategic { + /// The match strategy to use. + strategy: MatchStrategy, + /// The underlying pattern. + pat: Glob, + /// The pattern, as a compiled regex. + re: Regex, +} + +#[cfg(test)] +impl GlobStrategic { + /// Tests whether the given path matches this pattern or not. + fn is_match>(&self, path: P) -> bool { + self.is_match_candidate(&Candidate::new(path.as_ref())) + } + + /// Tests whether the given path matches this pattern or not. + fn is_match_candidate(&self, candidate: &Candidate) -> bool { + let byte_path = &*candidate.path; + + match self.strategy { + MatchStrategy::Literal(ref lit) => lit.as_bytes() == byte_path, + MatchStrategy::BasenameLiteral(ref lit) => { + lit.as_bytes() == &*candidate.basename + } + MatchStrategy::Extension(ref ext) => { + ext.as_bytes() == &*candidate.ext + } + MatchStrategy::Prefix(ref pre) => { + starts_with(pre.as_bytes(), byte_path) + } + MatchStrategy::Suffix { ref suffix, component } => { + if component && byte_path == &suffix.as_bytes()[1..] { + return true; + } + ends_with(suffix.as_bytes(), byte_path) + } + MatchStrategy::RequiredExtension(ref ext) => { + let ext = ext.as_bytes(); + &*candidate.ext == ext && self.re.is_match(byte_path) + } + MatchStrategy::Regex => self.re.is_match(byte_path), + } + } +} + +/// A builder for a pattern. +/// +/// This builder enables configuring the match semantics of a pattern. For +/// example, one can make matching case insensitive. +/// +/// The lifetime `'a` refers to the lifetime of the pattern string. +#[derive(Clone, Debug)] +pub struct GlobBuilder<'a> { + /// The glob pattern to compile. + glob: &'a str, + /// Options for the pattern. + opts: GlobOptions, +} + +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] +struct GlobOptions { + /// Whether to match case insensitively. + case_insensitive: bool, + /// Whether to require a literal separator to match a separator in a file + /// path. e.g., when enabled, `*` won't match `/`. + literal_separator: bool, +} + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +struct Tokens(Vec); + +impl Deref for Tokens { + type Target = Vec; + fn deref(&self) -> &Vec { &self.0 } +} + +impl DerefMut for Tokens { + fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +enum Token { + Literal(char), + Any, + ZeroOrMore, + RecursivePrefix, + RecursiveSuffix, + RecursiveZeroOrMore, + Class { + negated: bool, + ranges: Vec<(char, char)>, + }, + Alternates(Vec), +} + +impl Glob { + /// Builds a new pattern with default options. + pub fn new(glob: &str) -> Result { + GlobBuilder::new(glob).build() + } + + /// Returns a matcher for this pattern. + pub fn compile_matcher(&self) -> GlobMatcher { + let re = new_regex(&self.re) + .expect("regex compilation shouldn't fail"); + GlobMatcher { + pat: self.clone(), + re: re, + } + } + + /// Returns a strategic matcher. + /// + /// This isn't exposed because it's not clear whether it's actually + /// faster than just running a regex for a *single* pattern. If it + /// is faster, then GlobMatcher should do it automatically. + #[cfg(test)] + fn compile_strategic_matcher(&self) -> GlobStrategic { + let strategy = MatchStrategy::new(self); + let re = new_regex(&self.re) + .expect("regex compilation shouldn't fail"); + GlobStrategic { + strategy: strategy, + pat: self.clone(), + re: re, + } + } + + /// Returns the original glob pattern used to build this pattern. + pub fn glob(&self) -> &str { + &self.glob + } + + /// Returns the regular expression string for this glob. + pub fn regex(&self) -> &str { + &self.re + } + + /// Returns the pattern as a literal if and only if the pattern must match + /// an entire path exactly. + /// + /// The basic format of these patterns is `{literal}`. + fn literal(&self) -> Option { + if self.opts.case_insensitive { + return None; + } + let mut lit = String::new(); + for t in &*self.tokens { + match *t { + Token::Literal(c) => lit.push(c), + _ => return None, + } + } + if lit.is_empty() { + None + } else { + Some(lit) + } + } + + /// Returns an extension if this pattern matches a file path if and only + /// if the file path has the extension returned. + /// + /// Note that this extension returned differs from the extension that + /// std::path::Path::extension returns. Namely, this extension includes + /// the '.'. Also, paths like `.rs` are considered to have an extension + /// of `.rs`. + fn ext(&self) -> Option { + if self.opts.case_insensitive { + return None; + } + let start = match self.tokens.get(0) { + Some(&Token::RecursivePrefix) => 1, + Some(_) => 0, + _ => return None, + }; + match self.tokens.get(start) { + Some(&Token::ZeroOrMore) => { + // If there was no recursive prefix, then we only permit + // `*` if `*` can match a `/`. For example, if `*` can't + // match `/`, then `*.c` doesn't match `foo/bar.c`. + if start == 0 && self.opts.literal_separator { + return None; + } + } + _ => return None, + } + match self.tokens.get(start + 1) { + Some(&Token::Literal('.')) => {} + _ => return None, + } + let mut lit = ".".to_string(); + for t in self.tokens[start + 2..].iter() { + match *t { + Token::Literal('.') | Token::Literal('/') => return None, + Token::Literal(c) => lit.push(c), + _ => return None, + } + } + if lit.is_empty() { + None + } else { + Some(lit) + } + } + + /// This is like `ext`, but returns an extension even if it isn't sufficent + /// to imply a match. Namely, if an extension is returned, then it is + /// necessary but not sufficient for a match. + fn required_ext(&self) -> Option { + if self.opts.case_insensitive { + return None; + } + // We don't care at all about the beginning of this pattern. All we + // need to check for is if it ends with a literal of the form `.ext`. + let mut ext: Vec = vec![]; // built in reverse + for t in self.tokens.iter().rev() { + match *t { + Token::Literal('/') => return None, + Token::Literal(c) => { + ext.push(c); + if c == '.' { + break; + } + } + _ => return None, + } + } + if ext.last() != Some(&'.') { + None + } else { + ext.reverse(); + Some(ext.into_iter().collect()) + } + } + + /// Returns a literal prefix of this pattern if the entire pattern matches + /// if the literal prefix matches. + fn prefix(&self) -> Option { + if self.opts.case_insensitive { + return None; + } + let end = match self.tokens.last() { + Some(&Token::ZeroOrMore) => { + if self.opts.literal_separator { + // If a trailing `*` can't match a `/`, then we can't + // assume a match of the prefix corresponds to a match + // of the overall pattern. e.g., `foo/*` with + // `literal_separator` enabled matches `foo/bar` but not + // `foo/bar/baz`, even though `foo/bar/baz` has a `foo/` + // literal prefix. + return None; + } + self.tokens.len() - 1 + } + _ => self.tokens.len(), + }; + let mut lit = String::new(); + for t in &self.tokens[0..end] { + match *t { + Token::Literal(c) => lit.push(c), + _ => return None, + } + } + if lit.is_empty() { + None + } else { + Some(lit) + } + } + + /// Returns a literal suffix of this pattern if the entire pattern matches + /// if the literal suffix matches. + /// + /// If a literal suffix is returned and it must match either the entire + /// file path or be preceded by a `/`, then also return true. This happens + /// with a pattern like `**/foo/bar`. Namely, this pattern matches + /// `foo/bar` and `baz/foo/bar`, but not `foofoo/bar`. In this case, the + /// suffix returned is `/foo/bar` (but should match the entire path + /// `foo/bar`). + /// + /// When this returns true, the suffix literal is guaranteed to start with + /// a `/`. + fn suffix(&self) -> Option<(String, bool)> { + if self.opts.case_insensitive { + return None; + } + let mut lit = String::new(); + let (start, entire) = match self.tokens.get(0) { + Some(&Token::RecursivePrefix) => { + // We only care if this follows a path component if the next + // token is a literal. + if let Some(&Token::Literal(_)) = self.tokens.get(1) { + lit.push('/'); + (1, true) + } else { + (1, false) + } + } + _ => (0, false), + }; + let start = match self.tokens.get(start) { + Some(&Token::ZeroOrMore) => { + // If literal_separator is enabled, then a `*` can't + // necessarily match everything, so reporting a suffix match + // as a match of the pattern would be a false positive. + if self.opts.literal_separator { + return None; + } + start + 1 + } + _ => start, + }; + for t in &self.tokens[start..] { + match *t { + Token::Literal(c) => lit.push(c), + _ => return None, + } + } + if lit.is_empty() || lit == "/" { + None + } else { + Some((lit, entire)) + } + } + + /// If this pattern only needs to inspect the basename of a file path, + /// then the tokens corresponding to only the basename match are returned. + /// + /// For example, given a pattern of `**/*.foo`, only the tokens + /// corresponding to `*.foo` are returned. + /// + /// Note that this will return None if any match of the basename tokens + /// doesn't correspond to a match of the entire pattern. For example, the + /// glob `foo` only matches when a file path has a basename of `foo`, but + /// doesn't *always* match when a file path has a basename of `foo`. e.g., + /// `foo` doesn't match `abc/foo`. + fn basename_tokens(&self) -> Option<&[Token]> { + if self.opts.case_insensitive { + return None; + } + let start = match self.tokens.get(0) { + Some(&Token::RecursivePrefix) => 1, + _ => { + // With nothing to gobble up the parent portion of a path, + // we can't assume that matching on only the basename is + // correct. + return None; + } + }; + if self.tokens[start..].is_empty() { + return None; + } + for t in &self.tokens[start..] { + match *t { + Token::Literal('/') => return None, + Token::Literal(_) => {} // OK + Token::Any | Token::ZeroOrMore => { + if !self.opts.literal_separator { + // In this case, `*` and `?` can match a path + // separator, which means this could reach outside + // the basename. + return None; + } + } + Token::RecursivePrefix + | Token::RecursiveSuffix + | Token::RecursiveZeroOrMore => { + return None; + } + Token::Class{..} | Token::Alternates(..) => { + // We *could* be a little smarter here, but either one + // of these is going to prevent our literal optimizations + // anyway, so give up. + return None; + } + } + } + Some(&self.tokens[start..]) + } + + /// Returns the pattern as a literal if and only if the pattern exclusively + /// matches the basename of a file path *and* is a literal. + /// + /// The basic format of these patterns is `**/{literal}`, where `{literal}` + /// does not contain a path separator. + fn basename_literal(&self) -> Option { + let tokens = match self.basename_tokens() { + None => return None, + Some(tokens) => tokens, + }; + let mut lit = String::new(); + for t in tokens { + match *t { + Token::Literal(c) => lit.push(c), + _ => return None, + } + } + Some(lit) + } +} + +impl<'a> GlobBuilder<'a> { + /// Create a new builder for the pattern given. + /// + /// The pattern is not compiled until `build` is called. + pub fn new(glob: &'a str) -> GlobBuilder<'a> { + GlobBuilder { + glob: glob, + opts: GlobOptions::default(), + } + } + + /// Parses and builds the pattern. + pub fn build(&self) -> Result { + let mut p = Parser { + glob: &self.glob, + stack: vec![Tokens::default()], + chars: self.glob.chars().peekable(), + prev: None, + cur: None, + }; + p.parse()?; + if p.stack.is_empty() { + Err(Error { + glob: Some(self.glob.to_string()), + kind: ErrorKind::UnopenedAlternates, + }) + } else if p.stack.len() > 1 { + Err(Error { + glob: Some(self.glob.to_string()), + kind: ErrorKind::UnclosedAlternates, + }) + } else { + let tokens = p.stack.pop().unwrap(); + Ok(Glob { + glob: self.glob.to_string(), + re: tokens.to_regex_with(&self.opts), + opts: self.opts, + tokens: tokens, + }) + } + } + + /// Toggle whether the pattern matches case insensitively or not. + /// + /// This is disabled by default. + pub fn case_insensitive(&mut self, yes: bool) -> &mut GlobBuilder<'a> { + self.opts.case_insensitive = yes; + self + } + + /// Toggle whether a literal `/` is required to match a path separator. + pub fn literal_separator(&mut self, yes: bool) -> &mut GlobBuilder<'a> { + self.opts.literal_separator = yes; + self + } +} + +impl Tokens { + /// Convert this pattern to a string that is guaranteed to be a valid + /// regular expression and will represent the matching semantics of this + /// glob pattern and the options given. + fn to_regex_with(&self, options: &GlobOptions) -> String { + let mut re = String::new(); + re.push_str("(?-u)"); + if options.case_insensitive { + re.push_str("(?i)"); + } + re.push('^'); + // Special case. If the entire glob is just `**`, then it should match + // everything. + if self.len() == 1 && self[0] == Token::RecursivePrefix { + re.push_str(".*"); + re.push('$'); + return re; + } + self.tokens_to_regex(options, &self, &mut re); + re.push('$'); + re + } + + fn tokens_to_regex( + &self, + options: &GlobOptions, + tokens: &[Token], + re: &mut String, + ) { + for tok in tokens { + match *tok { + Token::Literal(c) => { + re.push_str(&char_to_escaped_literal(c)); + } + Token::Any => { + if options.literal_separator { + re.push_str("[^/]"); + } else { + re.push_str("."); + } + } + Token::ZeroOrMore => { + if options.literal_separator { + re.push_str("[^/]*"); + } else { + re.push_str(".*"); + } + } + Token::RecursivePrefix => { + re.push_str("(?:/?|.*/)"); + } + Token::RecursiveSuffix => { + re.push_str("(?:/?|/.*)"); + } + Token::RecursiveZeroOrMore => { + re.push_str("(?:/|/.*/)"); + } + Token::Class { negated, ref ranges } => { + re.push('['); + if negated { + re.push('^'); + } + for r in ranges { + if r.0 == r.1 { + // Not strictly necessary, but nicer to look at. + re.push_str(&char_to_escaped_literal(r.0)); + } else { + re.push_str(&char_to_escaped_literal(r.0)); + re.push('-'); + re.push_str(&char_to_escaped_literal(r.1)); + } + } + re.push(']'); + } + Token::Alternates(ref patterns) => { + let mut parts = vec![]; + for pat in patterns { + let mut altre = String::new(); + self.tokens_to_regex(options, &pat, &mut altre); + if !altre.is_empty() { + parts.push(altre); + } + } + + // It is possible to have an empty set in which case the + // resulting alternation '()' would be an error. + if !parts.is_empty() { + re.push('('); + re.push_str(&parts.join("|")); + re.push(')'); + } + } + } + } + } +} + +/// Convert a Unicode scalar value to an escaped string suitable for use as +/// a literal in a non-Unicode regex. +fn char_to_escaped_literal(c: char) -> String { + bytes_to_escaped_literal(&c.to_string().into_bytes()) +} + +/// Converts an arbitrary sequence of bytes to a UTF-8 string. All non-ASCII +/// code units are converted to their escaped form. +fn bytes_to_escaped_literal(bs: &[u8]) -> String { + let mut s = String::with_capacity(bs.len()); + for &b in bs { + if b <= 0x7F { + s.push_str(®ex::escape(&(b as char).to_string())); + } else { + s.push_str(&format!("\\x{:02x}", b)); + } + } + s +} + +struct Parser<'a> { + glob: &'a str, + stack: Vec, + chars: iter::Peekable>, + prev: Option, + cur: Option, +} + +impl<'a> Parser<'a> { + fn error(&self, kind: ErrorKind) -> Error { + Error { glob: Some(self.glob.to_string()), kind: kind } + } + + fn parse(&mut self) -> Result<(), Error> { + while let Some(c) = self.bump() { + match c { + '?' => self.push_token(Token::Any)?, + '*' => self.parse_star()?, + '[' => self.parse_class()?, + '{' => self.push_alternate()?, + '}' => self.pop_alternate()?, + ',' => self.parse_comma()?, + c => { + if is_separator(c) { + // Normalize all patterns to use / as a separator. + self.push_token(Token::Literal('/'))? + } else { + self.push_token(Token::Literal(c))? + } + } + } + } + Ok(()) + } + + fn push_alternate(&mut self) -> Result<(), Error> { + if self.stack.len() > 1 { + return Err(self.error(ErrorKind::NestedAlternates)); + } + Ok(self.stack.push(Tokens::default())) + } + + fn pop_alternate(&mut self) -> Result<(), Error> { + let mut alts = vec![]; + while self.stack.len() >= 2 { + alts.push(self.stack.pop().unwrap()); + } + self.push_token(Token::Alternates(alts)) + } + + fn push_token(&mut self, tok: Token) -> Result<(), Error> { + if let Some(ref mut pat) = self.stack.last_mut() { + return Ok(pat.push(tok)); + } + Err(self.error(ErrorKind::UnopenedAlternates)) + } + + fn pop_token(&mut self) -> Result { + if let Some(ref mut pat) = self.stack.last_mut() { + return Ok(pat.pop().unwrap()); + } + Err(self.error(ErrorKind::UnopenedAlternates)) + } + + fn have_tokens(&self) -> Result { + match self.stack.last() { + None => Err(self.error(ErrorKind::UnopenedAlternates)), + Some(ref pat) => Ok(!pat.is_empty()), + } + } + + fn parse_comma(&mut self) -> Result<(), Error> { + // If we aren't inside a group alternation, then don't + // treat commas specially. Otherwise, we need to start + // a new alternate. + if self.stack.len() <= 1 { + self.push_token(Token::Literal(',')) + } else { + Ok(self.stack.push(Tokens::default())) + } + } + + fn parse_star(&mut self) -> Result<(), Error> { + let prev = self.prev; + if self.chars.peek() != Some(&'*') { + self.push_token(Token::ZeroOrMore)?; + return Ok(()); + } + assert!(self.bump() == Some('*')); + if !self.have_tokens()? { + self.push_token(Token::RecursivePrefix)?; + let next = self.bump(); + if !next.map(is_separator).unwrap_or(true) { + return Err(self.error(ErrorKind::InvalidRecursive)); + } + return Ok(()); + } + self.pop_token()?; + if !prev.map(is_separator).unwrap_or(false) { + if self.stack.len() <= 1 + || (prev != Some(',') && prev != Some('{')) { + return Err(self.error(ErrorKind::InvalidRecursive)); + } + } + match self.chars.peek() { + None => { + assert!(self.bump().is_none()); + self.push_token(Token::RecursiveSuffix) + } + Some(&',') | Some(&'}') if self.stack.len() >= 2 => { + self.push_token(Token::RecursiveSuffix) + } + Some(&c) if is_separator(c) => { + assert!(self.bump().map(is_separator).unwrap_or(false)); + self.push_token(Token::RecursiveZeroOrMore) + } + _ => Err(self.error(ErrorKind::InvalidRecursive)), + } + } + + fn parse_class(&mut self) -> Result<(), Error> { + fn add_to_last_range( + glob: &str, + r: &mut (char, char), + add: char, + ) -> Result<(), Error> { + r.1 = add; + if r.1 < r.0 { + Err(Error { + glob: Some(glob.to_string()), + kind: ErrorKind::InvalidRange(r.0, r.1), + }) + } else { + Ok(()) + } + } + let mut ranges = vec![]; + let negated = match self.chars.peek() { + Some(&'!') | Some(&'^') => { + let bump = self.bump(); + assert!(bump == Some('!') || bump == Some('^')); + true + } + _ => false, + }; + let mut first = true; + let mut in_range = false; + loop { + let c = match self.bump() { + Some(c) => c, + // The only way to successfully break this loop is to observe + // a ']'. + None => return Err(self.error(ErrorKind::UnclosedClass)), + }; + match c { + ']' => { + if first { + ranges.push((']', ']')); + } else { + break; + } + } + '-' => { + if first { + ranges.push(('-', '-')); + } else if in_range { + // invariant: in_range is only set when there is + // already at least one character seen. + let r = ranges.last_mut().unwrap(); + add_to_last_range(&self.glob, r, '-')?; + in_range = false; + } else { + assert!(!ranges.is_empty()); + in_range = true; + } + } + c => { + if in_range { + // invariant: in_range is only set when there is + // already at least one character seen. + add_to_last_range( + &self.glob, ranges.last_mut().unwrap(), c)?; + } else { + ranges.push((c, c)); + } + in_range = false; + } + } + first = false; + } + if in_range { + // Means that the last character in the class was a '-', so add + // it as a literal. + ranges.push(('-', '-')); + } + self.push_token(Token::Class { + negated: negated, + ranges: ranges, + }) + } + + fn bump(&mut self) -> Option { + self.prev = self.cur; + self.cur = self.chars.next(); + self.cur + } +} + +#[cfg(test)] +fn starts_with(needle: &[u8], haystack: &[u8]) -> bool { + needle.len() <= haystack.len() && needle == &haystack[..needle.len()] +} + +#[cfg(test)] +fn ends_with(needle: &[u8], haystack: &[u8]) -> bool { + if needle.len() > haystack.len() { + return false; + } + needle == &haystack[haystack.len() - needle.len()..] +} + +#[cfg(test)] +mod tests { + use {GlobSetBuilder, ErrorKind}; + use super::{Glob, GlobBuilder, Token}; + use super::Token::*; + + #[derive(Clone, Copy, Debug, Default)] + struct Options { + casei: bool, + litsep: bool, + } + + macro_rules! syntax { + ($name:ident, $pat:expr, $tokens:expr) => { + #[test] + fn $name() { + let pat = Glob::new($pat).unwrap(); + assert_eq!($tokens, pat.tokens.0); + } + } + } + + macro_rules! syntaxerr { + ($name:ident, $pat:expr, $err:expr) => { + #[test] + fn $name() { + let err = Glob::new($pat).unwrap_err(); + assert_eq!(&$err, err.kind()); + } + } + } + + macro_rules! toregex { + ($name:ident, $pat:expr, $re:expr) => { + toregex!($name, $pat, $re, Options::default()); + }; + ($name:ident, $pat:expr, $re:expr, $options:expr) => { + #[test] + fn $name() { + let pat = GlobBuilder::new($pat) + .case_insensitive($options.casei) + .literal_separator($options.litsep) + .build() + .unwrap(); + assert_eq!(format!("(?-u){}", $re), pat.regex()); + } + }; + } + + macro_rules! matches { + ($name:ident, $pat:expr, $path:expr) => { + matches!($name, $pat, $path, Options::default()); + }; + ($name:ident, $pat:expr, $path:expr, $options:expr) => { + #[test] + fn $name() { + let pat = GlobBuilder::new($pat) + .case_insensitive($options.casei) + .literal_separator($options.litsep) + .build() + .unwrap(); + let matcher = pat.compile_matcher(); + let strategic = pat.compile_strategic_matcher(); + let set = GlobSetBuilder::new().add(pat).build().unwrap(); + assert!(matcher.is_match($path)); + assert!(strategic.is_match($path)); + assert!(set.is_match($path)); + } + }; + } + + macro_rules! nmatches { + ($name:ident, $pat:expr, $path:expr) => { + nmatches!($name, $pat, $path, Options::default()); + }; + ($name:ident, $pat:expr, $path:expr, $options:expr) => { + #[test] + fn $name() { + let pat = GlobBuilder::new($pat) + .case_insensitive($options.casei) + .literal_separator($options.litsep) + .build() + .unwrap(); + let matcher = pat.compile_matcher(); + let strategic = pat.compile_strategic_matcher(); + let set = GlobSetBuilder::new().add(pat).build().unwrap(); + assert!(!matcher.is_match($path)); + assert!(!strategic.is_match($path)); + assert!(!set.is_match($path)); + } + }; + } + + fn s(string: &str) -> String { string.to_string() } + + fn class(s: char, e: char) -> Token { + Class { negated: false, ranges: vec![(s, e)] } + } + + fn classn(s: char, e: char) -> Token { + Class { negated: true, ranges: vec![(s, e)] } + } + + fn rclass(ranges: &[(char, char)]) -> Token { + Class { negated: false, ranges: ranges.to_vec() } + } + + fn rclassn(ranges: &[(char, char)]) -> Token { + Class { negated: true, ranges: ranges.to_vec() } + } + + syntax!(literal1, "a", vec![Literal('a')]); + syntax!(literal2, "ab", vec![Literal('a'), Literal('b')]); + syntax!(any1, "?", vec![Any]); + syntax!(any2, "a?b", vec![Literal('a'), Any, Literal('b')]); + syntax!(seq1, "*", vec![ZeroOrMore]); + syntax!(seq2, "a*b", vec![Literal('a'), ZeroOrMore, Literal('b')]); + syntax!(seq3, "*a*b*", vec![ + ZeroOrMore, Literal('a'), ZeroOrMore, Literal('b'), ZeroOrMore, + ]); + syntax!(rseq1, "**", vec![RecursivePrefix]); + syntax!(rseq2, "**/", vec![RecursivePrefix]); + syntax!(rseq3, "/**", vec![RecursiveSuffix]); + syntax!(rseq4, "/**/", vec![RecursiveZeroOrMore]); + syntax!(rseq5, "a/**/b", vec![ + Literal('a'), RecursiveZeroOrMore, Literal('b'), + ]); + syntax!(cls1, "[a]", vec![class('a', 'a')]); + syntax!(cls2, "[!a]", vec![classn('a', 'a')]); + syntax!(cls3, "[a-z]", vec![class('a', 'z')]); + syntax!(cls4, "[!a-z]", vec![classn('a', 'z')]); + syntax!(cls5, "[-]", vec![class('-', '-')]); + syntax!(cls6, "[]]", vec![class(']', ']')]); + syntax!(cls7, "[*]", vec![class('*', '*')]); + syntax!(cls8, "[!!]", vec![classn('!', '!')]); + syntax!(cls9, "[a-]", vec![rclass(&[('a', 'a'), ('-', '-')])]); + syntax!(cls10, "[-a-z]", vec![rclass(&[('-', '-'), ('a', 'z')])]); + syntax!(cls11, "[a-z-]", vec![rclass(&[('a', 'z'), ('-', '-')])]); + syntax!(cls12, "[-a-z-]", vec![ + rclass(&[('-', '-'), ('a', 'z'), ('-', '-')]), + ]); + syntax!(cls13, "[]-z]", vec![class(']', 'z')]); + syntax!(cls14, "[--z]", vec![class('-', 'z')]); + syntax!(cls15, "[ --]", vec![class(' ', '-')]); + syntax!(cls16, "[0-9a-z]", vec![rclass(&[('0', '9'), ('a', 'z')])]); + syntax!(cls17, "[a-z0-9]", vec![rclass(&[('a', 'z'), ('0', '9')])]); + syntax!(cls18, "[!0-9a-z]", vec![rclassn(&[('0', '9'), ('a', 'z')])]); + syntax!(cls19, "[!a-z0-9]", vec![rclassn(&[('a', 'z'), ('0', '9')])]); + syntax!(cls20, "[^a]", vec![classn('a', 'a')]); + syntax!(cls21, "[^a-z]", vec![classn('a', 'z')]); + + syntaxerr!(err_rseq1, "a**", ErrorKind::InvalidRecursive); + syntaxerr!(err_rseq2, "**a", ErrorKind::InvalidRecursive); + syntaxerr!(err_rseq3, "a**b", ErrorKind::InvalidRecursive); + syntaxerr!(err_rseq4, "***", ErrorKind::InvalidRecursive); + syntaxerr!(err_rseq5, "/a**", ErrorKind::InvalidRecursive); + syntaxerr!(err_rseq6, "/**a", ErrorKind::InvalidRecursive); + syntaxerr!(err_rseq7, "/a**b", ErrorKind::InvalidRecursive); + syntaxerr!(err_unclosed1, "[", ErrorKind::UnclosedClass); + syntaxerr!(err_unclosed2, "[]", ErrorKind::UnclosedClass); + syntaxerr!(err_unclosed3, "[!", ErrorKind::UnclosedClass); + syntaxerr!(err_unclosed4, "[!]", ErrorKind::UnclosedClass); + syntaxerr!(err_range1, "[z-a]", ErrorKind::InvalidRange('z', 'a')); + syntaxerr!(err_range2, "[z--]", ErrorKind::InvalidRange('z', '-')); + + const CASEI: Options = Options { + casei: true, + litsep: false, + }; + const SLASHLIT: Options = Options { + casei: false, + litsep: true, + }; + + toregex!(re_casei, "a", "(?i)^a$", &CASEI); + + toregex!(re_slash1, "?", r"^[^/]$", SLASHLIT); + toregex!(re_slash2, "*", r"^[^/]*$", SLASHLIT); + + toregex!(re1, "a", "^a$"); + toregex!(re2, "?", "^.$"); + toregex!(re3, "*", "^.*$"); + toregex!(re4, "a?", "^a.$"); + toregex!(re5, "?a", "^.a$"); + toregex!(re6, "a*", "^a.*$"); + toregex!(re7, "*a", "^.*a$"); + toregex!(re8, "[*]", r"^[\*]$"); + toregex!(re9, "[+]", r"^[\+]$"); + toregex!(re10, "+", r"^\+$"); + toregex!(re11, "**", r"^.*$"); + toregex!(re12, "☃", r"^\xe2\x98\x83$"); + + matches!(match1, "a", "a"); + matches!(match2, "a*b", "a_b"); + matches!(match3, "a*b*c", "abc"); + matches!(match4, "a*b*c", "a_b_c"); + matches!(match5, "a*b*c", "a___b___c"); + matches!(match6, "abc*abc*abc", "abcabcabcabcabcabcabc"); + matches!(match7, "a*a*a*a*a*a*a*a*a", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + matches!(match8, "a*b[xyz]c*d", "abxcdbxcddd"); + matches!(match9, "*.rs", ".rs"); + matches!(match10, "☃", "☃"); + + matches!(matchrec1, "some/**/needle.txt", "some/needle.txt"); + matches!(matchrec2, "some/**/needle.txt", "some/one/needle.txt"); + matches!(matchrec3, "some/**/needle.txt", "some/one/two/needle.txt"); + matches!(matchrec4, "some/**/needle.txt", "some/other/needle.txt"); + matches!(matchrec5, "**", "abcde"); + matches!(matchrec6, "**", ""); + matches!(matchrec7, "**", ".asdf"); + matches!(matchrec8, "**", "/x/.asdf"); + matches!(matchrec9, "some/**/**/needle.txt", "some/needle.txt"); + matches!(matchrec10, "some/**/**/needle.txt", "some/one/needle.txt"); + matches!(matchrec11, "some/**/**/needle.txt", "some/one/two/needle.txt"); + matches!(matchrec12, "some/**/**/needle.txt", "some/other/needle.txt"); + matches!(matchrec13, "**/test", "one/two/test"); + matches!(matchrec14, "**/test", "one/test"); + matches!(matchrec15, "**/test", "test"); + matches!(matchrec16, "/**/test", "/one/two/test"); + matches!(matchrec17, "/**/test", "/one/test"); + matches!(matchrec18, "/**/test", "/test"); + matches!(matchrec19, "**/.*", ".abc"); + matches!(matchrec20, "**/.*", "abc/.abc"); + matches!(matchrec21, ".*/**", ".abc"); + matches!(matchrec22, ".*/**", ".abc/abc"); + matches!(matchrec23, "foo/**", "foo"); + matches!(matchrec24, "**/foo/bar", "foo/bar"); + matches!(matchrec25, "some/*/needle.txt", "some/one/needle.txt"); + + matches!(matchrange1, "a[0-9]b", "a0b"); + matches!(matchrange2, "a[0-9]b", "a9b"); + matches!(matchrange3, "a[!0-9]b", "a_b"); + matches!(matchrange4, "[a-z123]", "1"); + matches!(matchrange5, "[1a-z23]", "1"); + matches!(matchrange6, "[123a-z]", "1"); + matches!(matchrange7, "[abc-]", "-"); + matches!(matchrange8, "[-abc]", "-"); + matches!(matchrange9, "[-a-c]", "b"); + matches!(matchrange10, "[a-c-]", "b"); + matches!(matchrange11, "[-]", "-"); + matches!(matchrange12, "a[^0-9]b", "a_b"); + + matches!(matchpat1, "*hello.txt", "hello.txt"); + matches!(matchpat2, "*hello.txt", "gareth_says_hello.txt"); + matches!(matchpat3, "*hello.txt", "some/path/to/hello.txt"); + matches!(matchpat4, "*hello.txt", "some\\path\\to\\hello.txt"); + matches!(matchpat5, "*hello.txt", "/an/absolute/path/to/hello.txt"); + matches!(matchpat6, "*some/path/to/hello.txt", "some/path/to/hello.txt"); + matches!(matchpat7, "*some/path/to/hello.txt", + "a/bigger/some/path/to/hello.txt"); + + matches!(matchescape, "_[[]_[]]_[?]_[*]_!_", "_[_]_?_*_!_"); + + matches!(matchcasei1, "aBcDeFg", "aBcDeFg", CASEI); + matches!(matchcasei2, "aBcDeFg", "abcdefg", CASEI); + matches!(matchcasei3, "aBcDeFg", "ABCDEFG", CASEI); + matches!(matchcasei4, "aBcDeFg", "AbCdEfG", CASEI); + + matches!(matchalt1, "a,b", "a,b"); + matches!(matchalt2, ",", ","); + matches!(matchalt3, "{a,b}", "a"); + matches!(matchalt4, "{a,b}", "b"); + matches!(matchalt5, "{**/src/**,foo}", "abc/src/bar"); + matches!(matchalt6, "{**/src/**,foo}", "foo"); + matches!(matchalt7, "{[}],foo}", "}"); + matches!(matchalt8, "{foo}", "foo"); + matches!(matchalt9, "{}", ""); + matches!(matchalt10, "{,}", ""); + matches!(matchalt11, "{*.foo,*.bar,*.wat}", "test.foo"); + matches!(matchalt12, "{*.foo,*.bar,*.wat}", "test.bar"); + matches!(matchalt13, "{*.foo,*.bar,*.wat}", "test.wat"); + + matches!(matchslash1, "abc/def", "abc/def", SLASHLIT); + #[cfg(unix)] + nmatches!(matchslash2, "abc?def", "abc/def", SLASHLIT); + #[cfg(not(unix))] + nmatches!(matchslash2, "abc?def", "abc\\def", SLASHLIT); + nmatches!(matchslash3, "abc*def", "abc/def", SLASHLIT); + matches!(matchslash4, "abc[/]def", "abc/def", SLASHLIT); // differs + #[cfg(unix)] + nmatches!(matchslash5, "abc\\def", "abc/def", SLASHLIT); + #[cfg(not(unix))] + matches!(matchslash5, "abc\\def", "abc/def", SLASHLIT); + + nmatches!(matchnot1, "a*b*c", "abcd"); + nmatches!(matchnot2, "abc*abc*abc", "abcabcabcabcabcabcabca"); + nmatches!(matchnot3, "some/**/needle.txt", "some/other/notthis.txt"); + nmatches!(matchnot4, "some/**/**/needle.txt", "some/other/notthis.txt"); + nmatches!(matchnot5, "/**/test", "test"); + nmatches!(matchnot6, "/**/test", "/one/notthis"); + nmatches!(matchnot7, "/**/test", "/notthis"); + nmatches!(matchnot8, "**/.*", "ab.c"); + nmatches!(matchnot9, "**/.*", "abc/ab.c"); + nmatches!(matchnot10, ".*/**", "a.bc"); + nmatches!(matchnot11, ".*/**", "abc/a.bc"); + nmatches!(matchnot12, "a[0-9]b", "a_b"); + nmatches!(matchnot13, "a[!0-9]b", "a0b"); + nmatches!(matchnot14, "a[!0-9]b", "a9b"); + nmatches!(matchnot15, "[!-]", "-"); + nmatches!(matchnot16, "*hello.txt", "hello.txt-and-then-some"); + nmatches!(matchnot17, "*hello.txt", "goodbye.txt"); + nmatches!(matchnot18, "*some/path/to/hello.txt", + "some/path/to/hello.txt-and-then-some"); + nmatches!(matchnot19, "*some/path/to/hello.txt", + "some/other/path/to/hello.txt"); + nmatches!(matchnot20, "a", "foo/a"); + nmatches!(matchnot21, "./foo", "foo"); + nmatches!(matchnot22, "**/foo", "foofoo"); + nmatches!(matchnot23, "**/foo/bar", "foofoo/bar"); + nmatches!(matchnot24, "/*.c", "mozilla-sha1/sha1.c"); + nmatches!(matchnot25, "*.c", "mozilla-sha1/sha1.c", SLASHLIT); + nmatches!(matchnot26, "**/m4/ltoptions.m4", + "csharp/src/packages/repositories.config", SLASHLIT); + nmatches!(matchnot27, "a[^0-9]b", "a0b"); + nmatches!(matchnot28, "a[^0-9]b", "a9b"); + nmatches!(matchnot29, "[^-]", "-"); + nmatches!(matchnot30, "some/*/needle.txt", "some/needle.txt"); + nmatches!( + matchrec31, + "some/*/needle.txt", "some/one/two/needle.txt", SLASHLIT); + nmatches!( + matchrec32, + "some/*/needle.txt", "some/one/two/three/needle.txt", SLASHLIT); + + macro_rules! extract { + ($which:ident, $name:ident, $pat:expr, $expect:expr) => { + extract!($which, $name, $pat, $expect, Options::default()); + }; + ($which:ident, $name:ident, $pat:expr, $expect:expr, $opts:expr) => { + #[test] + fn $name() { + let pat = GlobBuilder::new($pat) + .case_insensitive($opts.casei) + .literal_separator($opts.litsep) + .build().unwrap(); + assert_eq!($expect, pat.$which()); + } + }; + } + + macro_rules! literal { + ($($tt:tt)*) => { extract!(literal, $($tt)*); } + } + + macro_rules! basetokens { + ($($tt:tt)*) => { extract!(basename_tokens, $($tt)*); } + } + + macro_rules! ext { + ($($tt:tt)*) => { extract!(ext, $($tt)*); } + } + + macro_rules! required_ext { + ($($tt:tt)*) => { extract!(required_ext, $($tt)*); } + } + + macro_rules! prefix { + ($($tt:tt)*) => { extract!(prefix, $($tt)*); } + } + + macro_rules! suffix { + ($($tt:tt)*) => { extract!(suffix, $($tt)*); } + } + + macro_rules! baseliteral { + ($($tt:tt)*) => { extract!(basename_literal, $($tt)*); } + } + + literal!(extract_lit1, "foo", Some(s("foo"))); + literal!(extract_lit2, "foo", None, CASEI); + literal!(extract_lit3, "/foo", Some(s("/foo"))); + literal!(extract_lit4, "/foo/", Some(s("/foo/"))); + literal!(extract_lit5, "/foo/bar", Some(s("/foo/bar"))); + literal!(extract_lit6, "*.foo", None); + literal!(extract_lit7, "foo/bar", Some(s("foo/bar"))); + literal!(extract_lit8, "**/foo/bar", None); + + basetokens!(extract_basetoks1, "**/foo", Some(&*vec![ + Literal('f'), Literal('o'), Literal('o'), + ])); + basetokens!(extract_basetoks2, "**/foo", None, CASEI); + basetokens!(extract_basetoks3, "**/foo", Some(&*vec![ + Literal('f'), Literal('o'), Literal('o'), + ]), SLASHLIT); + basetokens!(extract_basetoks4, "*foo", None, SLASHLIT); + basetokens!(extract_basetoks5, "*foo", None); + basetokens!(extract_basetoks6, "**/fo*o", None); + basetokens!(extract_basetoks7, "**/fo*o", Some(&*vec![ + Literal('f'), Literal('o'), ZeroOrMore, Literal('o'), + ]), SLASHLIT); + + ext!(extract_ext1, "**/*.rs", Some(s(".rs"))); + ext!(extract_ext2, "**/*.rs.bak", None); + ext!(extract_ext3, "*.rs", Some(s(".rs"))); + ext!(extract_ext4, "a*.rs", None); + ext!(extract_ext5, "/*.c", None); + ext!(extract_ext6, "*.c", None, SLASHLIT); + ext!(extract_ext7, "*.c", Some(s(".c"))); + + required_ext!(extract_req_ext1, "*.rs", Some(s(".rs"))); + required_ext!(extract_req_ext2, "/foo/bar/*.rs", Some(s(".rs"))); + required_ext!(extract_req_ext3, "/foo/bar/*.rs", Some(s(".rs"))); + required_ext!(extract_req_ext4, "/foo/bar/.rs", Some(s(".rs"))); + required_ext!(extract_req_ext5, ".rs", Some(s(".rs"))); + required_ext!(extract_req_ext6, "./rs", None); + required_ext!(extract_req_ext7, "foo", None); + required_ext!(extract_req_ext8, ".foo/", None); + required_ext!(extract_req_ext9, "foo/", None); + + prefix!(extract_prefix1, "/foo", Some(s("/foo"))); + prefix!(extract_prefix2, "/foo/*", Some(s("/foo/"))); + prefix!(extract_prefix3, "**/foo", None); + prefix!(extract_prefix4, "foo/**", None); + + suffix!(extract_suffix1, "**/foo/bar", Some((s("/foo/bar"), true))); + suffix!(extract_suffix2, "*/foo/bar", Some((s("/foo/bar"), false))); + suffix!(extract_suffix3, "*/foo/bar", None, SLASHLIT); + suffix!(extract_suffix4, "foo/bar", Some((s("foo/bar"), false))); + suffix!(extract_suffix5, "*.foo", Some((s(".foo"), false))); + suffix!(extract_suffix6, "*.foo", None, SLASHLIT); + suffix!(extract_suffix7, "**/*_test", Some((s("_test"), false))); + + baseliteral!(extract_baselit1, "**/foo", Some(s("foo"))); + baseliteral!(extract_baselit2, "foo", None); + baseliteral!(extract_baselit3, "*foo", None); + baseliteral!(extract_baselit4, "*/foo", None); +} diff -Nru cargo-0.25.0/vendor/globset-0.3.0/src/lib.rs cargo-0.26.0/vendor/globset-0.3.0/src/lib.rs --- cargo-0.25.0/vendor/globset-0.3.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.3.0/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,838 @@ +/*! +The globset crate provides cross platform single glob and glob set matching. + +Glob set matching is the process of matching one or more glob patterns against +a single candidate path simultaneously, and returning all of the globs that +matched. For example, given this set of globs: + +```ignore +*.rs +src/lib.rs +src/**/foo.rs +``` + +and a path `src/bar/baz/foo.rs`, then the set would report the first and third +globs as matching. + +# Example: one glob + +This example shows how to match a single glob against a single file path. + +``` +# fn example() -> Result<(), globset::Error> { +use globset::Glob; + +let glob = Glob::new("*.rs")?.compile_matcher(); + +assert!(glob.is_match("foo.rs")); +assert!(glob.is_match("foo/bar.rs")); +assert!(!glob.is_match("Cargo.toml")); +# Ok(()) } example().unwrap(); +``` + +# Example: configuring a glob matcher + +This example shows how to use a `GlobBuilder` to configure aspects of match +semantics. In this example, we prevent wildcards from matching path separators. + +``` +# fn example() -> Result<(), globset::Error> { +use globset::GlobBuilder; + +let glob = GlobBuilder::new("*.rs") + .literal_separator(true).build()?.compile_matcher(); + +assert!(glob.is_match("foo.rs")); +assert!(!glob.is_match("foo/bar.rs")); // no longer matches +assert!(!glob.is_match("Cargo.toml")); +# Ok(()) } example().unwrap(); +``` + +# Example: match multiple globs at once + +This example shows how to match multiple glob patterns at once. + +``` +# fn example() -> Result<(), globset::Error> { +use globset::{Glob, GlobSetBuilder}; + +let mut builder = GlobSetBuilder::new(); +// A GlobBuilder can be used to configure each glob's match semantics +// independently. +builder.add(Glob::new("*.rs")?); +builder.add(Glob::new("src/lib.rs")?); +builder.add(Glob::new("src/**/foo.rs")?); +let set = builder.build()?; + +assert_eq!(set.matches("src/bar/baz/foo.rs"), vec![0, 2]); +# Ok(()) } example().unwrap(); +``` + +# Syntax + +Standard Unix-style glob syntax is supported: + +* `?` matches any single character. (If the `literal_separator` option is + enabled, then `?` can never match a path separator.) +* `*` matches zero or more characters. (If the `literal_separator` option is + enabled, then `*` can never match a path separator.) +* `**` recursively matches directories but are only legal in three situations. + First, if the glob starts with \*\*/, then it matches + all directories. For example, \*\*/foo matches `foo` + and `bar/foo` but not `foo/bar`. Secondly, if the glob ends with + /\*\*, then it matches all sub-entries. For example, + foo/\*\* matches `foo/a` and `foo/a/b`, but not `foo`. + Thirdly, if the glob contains /\*\*/ anywhere within + the pattern, then it matches zero or more directories. Using `**` anywhere + else is illegal (N.B. the glob `**` is allowed and means "match everything"). +* `{a,b}` matches `a` or `b` where `a` and `b` are arbitrary glob patterns. + (N.B. Nesting `{...}` is not currently allowed.) +* `[ab]` matches `a` or `b` where `a` and `b` are characters. Use + `[!ab]` to match any character except for `a` and `b`. +* Metacharacters such as `*` and `?` can be escaped with character class + notation. e.g., `[*]` matches `*`. + +A `GlobBuilder` can be used to prevent wildcards from matching path separators, +or to enable case insensitive matching. +*/ + +#![deny(missing_docs)] + +extern crate aho_corasick; +extern crate fnv; +#[macro_use] +extern crate log; +extern crate memchr; +extern crate regex; + +use std::borrow::Cow; +use std::collections::{BTreeMap, HashMap}; +use std::error::Error as StdError; +use std::ffi::OsStr; +use std::fmt; +use std::hash; +use std::path::Path; +use std::str; + +use aho_corasick::{Automaton, AcAutomaton, FullAcAutomaton}; +use regex::bytes::{Regex, RegexBuilder, RegexSet}; + +use pathutil::{ + file_name, file_name_ext, normalize_path, os_str_bytes, path_bytes, +}; +use glob::MatchStrategy; +pub use glob::{Glob, GlobBuilder, GlobMatcher}; + +mod glob; +mod pathutil; + +/// Represents an error that can occur when parsing a glob pattern. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Error { + /// The original glob provided by the caller. + glob: Option, + /// The kind of error. + kind: ErrorKind, +} + +/// The kind of error that can occur when parsing a glob pattern. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ErrorKind { + /// Occurs when a use of `**` is invalid. Namely, `**` can only appear + /// adjacent to a path separator, or the beginning/end of a glob. + InvalidRecursive, + /// Occurs when a character class (e.g., `[abc]`) is not closed. + UnclosedClass, + /// Occurs when a range in a character (e.g., `[a-z]`) is invalid. For + /// example, if the range starts with a lexicographically larger character + /// than it ends with. + InvalidRange(char, char), + /// Occurs when a `}` is found without a matching `{`. + UnopenedAlternates, + /// Occurs when a `{` is found without a matching `}`. + UnclosedAlternates, + /// Occurs when an alternating group is nested inside another alternating + /// group, e.g., `{{a,b},{c,d}}`. + NestedAlternates, + /// An error associated with parsing or compiling a regex. + Regex(String), +} + +impl StdError for Error { + fn description(&self) -> &str { + self.kind.description() + } +} + +impl Error { + /// Return the glob that caused this error, if one exists. + pub fn glob(&self) -> Option<&str> { + self.glob.as_ref().map(|s| &**s) + } + + /// Return the kind of this error. + pub fn kind(&self) -> &ErrorKind { + &self.kind + } +} + +impl ErrorKind { + fn description(&self) -> &str { + match *self { + ErrorKind::InvalidRecursive => { + "invalid use of **; must be one path component" + } + ErrorKind::UnclosedClass => { + "unclosed character class; missing ']'" + } + ErrorKind::InvalidRange(_, _) => { + "invalid character range" + } + ErrorKind::UnopenedAlternates => { + "unopened alternate group; missing '{' \ + (maybe escape '}' with '[}]'?)" + } + ErrorKind::UnclosedAlternates => { + "unclosed alternate group; missing '}' \ + (maybe escape '{' with '[{]'?)" + } + ErrorKind::NestedAlternates => { + "nested alternate groups are not allowed" + } + ErrorKind::Regex(ref err) => err, + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.glob { + None => self.kind.fmt(f), + Some(ref glob) => { + write!(f, "error parsing glob '{}': {}", glob, self.kind) + } + } + } +} + +impl fmt::Display for ErrorKind { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + ErrorKind::InvalidRecursive + | ErrorKind::UnclosedClass + | ErrorKind::UnopenedAlternates + | ErrorKind::UnclosedAlternates + | ErrorKind::NestedAlternates + | ErrorKind::Regex(_) => { + write!(f, "{}", self.description()) + } + ErrorKind::InvalidRange(s, e) => { + write!(f, "invalid range; '{}' > '{}'", s, e) + } + } + } +} + +fn new_regex(pat: &str) -> Result { + RegexBuilder::new(pat) + .dot_matches_new_line(true) + .size_limit(10 * (1 << 20)) + .dfa_size_limit(10 * (1 << 20)) + .build() + .map_err(|err| { + Error { + glob: Some(pat.to_string()), + kind: ErrorKind::Regex(err.to_string()), + } + }) +} + +fn new_regex_set(pats: I) -> Result + where S: AsRef, I: IntoIterator { + RegexSet::new(pats).map_err(|err| { + Error { + glob: None, + kind: ErrorKind::Regex(err.to_string()), + } + }) +} + +type Fnv = hash::BuildHasherDefault; + +/// GlobSet represents a group of globs that can be matched together in a +/// single pass. +#[derive(Clone, Debug)] +pub struct GlobSet { + len: usize, + strats: Vec, +} + +impl GlobSet { + /// Returns true if this set is empty, and therefore matches nothing. + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Returns the number of globs in this set. + pub fn len(&self) -> usize { + self.len + } + + /// Returns true if any glob in this set matches the path given. + pub fn is_match>(&self, path: P) -> bool { + self.is_match_candidate(&Candidate::new(path.as_ref())) + } + + /// Returns true if any glob in this set matches the path given. + /// + /// This takes a Candidate as input, which can be used to amortize the + /// cost of preparing a path for matching. + pub fn is_match_candidate(&self, path: &Candidate) -> bool { + if self.is_empty() { + return false; + } + for strat in &self.strats { + if strat.is_match(path) { + return true; + } + } + false + } + + /// Returns the sequence number of every glob pattern that matches the + /// given path. + pub fn matches>(&self, path: P) -> Vec { + self.matches_candidate(&Candidate::new(path.as_ref())) + } + + /// Returns the sequence number of every glob pattern that matches the + /// given path. + /// + /// This takes a Candidate as input, which can be used to amortize the + /// cost of preparing a path for matching. + pub fn matches_candidate(&self, path: &Candidate) -> Vec { + let mut into = vec![]; + if self.is_empty() { + return into; + } + self.matches_candidate_into(path, &mut into); + into + } + + /// Adds the sequence number of every glob pattern that matches the given + /// path to the vec given. + /// + /// `into` is is cleared before matching begins, and contains the set of + /// sequence numbers (in ascending order) after matching ends. If no globs + /// were matched, then `into` will be empty. + pub fn matches_into>( + &self, + path: P, + into: &mut Vec, + ) { + self.matches_candidate_into(&Candidate::new(path.as_ref()), into); + } + + /// Adds the sequence number of every glob pattern that matches the given + /// path to the vec given. + /// + /// `into` is is cleared before matching begins, and contains the set of + /// sequence numbers (in ascending order) after matching ends. If no globs + /// were matched, then `into` will be empty. + /// + /// This takes a Candidate as input, which can be used to amortize the + /// cost of preparing a path for matching. + pub fn matches_candidate_into( + &self, + path: &Candidate, + into: &mut Vec, + ) { + into.clear(); + if self.is_empty() { + return; + } + for strat in &self.strats { + strat.matches_into(path, into); + } + into.sort(); + into.dedup(); + } + + fn new(pats: &[Glob]) -> Result { + if pats.is_empty() { + return Ok(GlobSet { len: 0, strats: vec![] }); + } + let mut lits = LiteralStrategy::new(); + let mut base_lits = BasenameLiteralStrategy::new(); + let mut exts = ExtensionStrategy::new(); + let mut prefixes = MultiStrategyBuilder::new(); + let mut suffixes = MultiStrategyBuilder::new(); + let mut required_exts = RequiredExtensionStrategyBuilder::new(); + let mut regexes = MultiStrategyBuilder::new(); + for (i, p) in pats.iter().enumerate() { + match MatchStrategy::new(p) { + MatchStrategy::Literal(lit) => { + lits.add(i, lit); + } + MatchStrategy::BasenameLiteral(lit) => { + base_lits.add(i, lit); + } + MatchStrategy::Extension(ext) => { + exts.add(i, ext); + } + MatchStrategy::Prefix(prefix) => { + prefixes.add(i, prefix); + } + MatchStrategy::Suffix { suffix, component } => { + if component { + lits.add(i, suffix[1..].to_string()); + } + suffixes.add(i, suffix); + } + MatchStrategy::RequiredExtension(ext) => { + required_exts.add(i, ext, p.regex().to_owned()); + } + MatchStrategy::Regex => { + debug!("glob converted to regex: {:?}", p); + regexes.add(i, p.regex().to_owned()); + } + } + } + debug!("built glob set; {} literals, {} basenames, {} extensions, \ + {} prefixes, {} suffixes, {} required extensions, {} regexes", + lits.0.len(), base_lits.0.len(), exts.0.len(), + prefixes.literals.len(), suffixes.literals.len(), + required_exts.0.len(), regexes.literals.len()); + Ok(GlobSet { + len: pats.len(), + strats: vec![ + GlobSetMatchStrategy::Extension(exts), + GlobSetMatchStrategy::BasenameLiteral(base_lits), + GlobSetMatchStrategy::Literal(lits), + GlobSetMatchStrategy::Suffix(suffixes.suffix()), + GlobSetMatchStrategy::Prefix(prefixes.prefix()), + GlobSetMatchStrategy::RequiredExtension( + required_exts.build()?), + GlobSetMatchStrategy::Regex(regexes.regex_set()?), + ], + }) + } +} + +/// GlobSetBuilder builds a group of patterns that can be used to +/// simultaneously match a file path. +pub struct GlobSetBuilder { + pats: Vec, +} + +impl GlobSetBuilder { + /// Create a new GlobSetBuilder. A GlobSetBuilder can be used to add new + /// patterns. Once all patterns have been added, `build` should be called + /// to produce a `GlobSet`, which can then be used for matching. + pub fn new() -> GlobSetBuilder { + GlobSetBuilder { pats: vec![] } + } + + /// Builds a new matcher from all of the glob patterns added so far. + /// + /// Once a matcher is built, no new patterns can be added to it. + pub fn build(&self) -> Result { + GlobSet::new(&self.pats) + } + + /// Add a new pattern to this set. + #[allow(dead_code)] + pub fn add(&mut self, pat: Glob) -> &mut GlobSetBuilder { + self.pats.push(pat); + self + } +} + +/// A candidate path for matching. +/// +/// All glob matching in this crate operates on `Candidate` values. +/// Constructing candidates has a very small cost associated with it, so +/// callers may find it beneficial to amortize that cost when matching a single +/// path against multiple globs or sets of globs. +#[derive(Clone, Debug)] +pub struct Candidate<'a> { + path: Cow<'a, [u8]>, + basename: Cow<'a, [u8]>, + ext: Cow<'a, [u8]>, +} + +impl<'a> Candidate<'a> { + /// Create a new candidate for matching from the given path. + pub fn new + ?Sized>(path: &'a P) -> Candidate<'a> { + let path = path.as_ref(); + let basename = file_name(path).unwrap_or(OsStr::new("")); + Candidate { + path: normalize_path(path_bytes(path)), + basename: os_str_bytes(basename), + ext: file_name_ext(basename).unwrap_or(Cow::Borrowed(b"")), + } + } + + fn path_prefix(&self, max: usize) -> &[u8] { + if self.path.len() <= max { + &*self.path + } else { + &self.path[..max] + } + } + + fn path_suffix(&self, max: usize) -> &[u8] { + if self.path.len() <= max { + &*self.path + } else { + &self.path[self.path.len() - max..] + } + } +} + +#[derive(Clone, Debug)] +enum GlobSetMatchStrategy { + Literal(LiteralStrategy), + BasenameLiteral(BasenameLiteralStrategy), + Extension(ExtensionStrategy), + Prefix(PrefixStrategy), + Suffix(SuffixStrategy), + RequiredExtension(RequiredExtensionStrategy), + Regex(RegexSetStrategy), +} + +impl GlobSetMatchStrategy { + fn is_match(&self, candidate: &Candidate) -> bool { + use self::GlobSetMatchStrategy::*; + match *self { + Literal(ref s) => s.is_match(candidate), + BasenameLiteral(ref s) => s.is_match(candidate), + Extension(ref s) => s.is_match(candidate), + Prefix(ref s) => s.is_match(candidate), + Suffix(ref s) => s.is_match(candidate), + RequiredExtension(ref s) => s.is_match(candidate), + Regex(ref s) => s.is_match(candidate), + } + } + + fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { + use self::GlobSetMatchStrategy::*; + match *self { + Literal(ref s) => s.matches_into(candidate, matches), + BasenameLiteral(ref s) => s.matches_into(candidate, matches), + Extension(ref s) => s.matches_into(candidate, matches), + Prefix(ref s) => s.matches_into(candidate, matches), + Suffix(ref s) => s.matches_into(candidate, matches), + RequiredExtension(ref s) => s.matches_into(candidate, matches), + Regex(ref s) => s.matches_into(candidate, matches), + } + } +} + +#[derive(Clone, Debug)] +struct LiteralStrategy(BTreeMap, Vec>); + +impl LiteralStrategy { + fn new() -> LiteralStrategy { + LiteralStrategy(BTreeMap::new()) + } + + fn add(&mut self, global_index: usize, lit: String) { + self.0.entry(lit.into_bytes()).or_insert(vec![]).push(global_index); + } + + fn is_match(&self, candidate: &Candidate) -> bool { + self.0.contains_key(&*candidate.path) + } + + #[inline(never)] + fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { + if let Some(hits) = self.0.get(&*candidate.path) { + matches.extend(hits); + } + } +} + +#[derive(Clone, Debug)] +struct BasenameLiteralStrategy(BTreeMap, Vec>); + +impl BasenameLiteralStrategy { + fn new() -> BasenameLiteralStrategy { + BasenameLiteralStrategy(BTreeMap::new()) + } + + fn add(&mut self, global_index: usize, lit: String) { + self.0.entry(lit.into_bytes()).or_insert(vec![]).push(global_index); + } + + fn is_match(&self, candidate: &Candidate) -> bool { + if candidate.basename.is_empty() { + return false; + } + self.0.contains_key(&*candidate.basename) + } + + #[inline(never)] + fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { + if candidate.basename.is_empty() { + return; + } + if let Some(hits) = self.0.get(&*candidate.basename) { + matches.extend(hits); + } + } +} + +#[derive(Clone, Debug)] +struct ExtensionStrategy(HashMap, Vec, Fnv>); + +impl ExtensionStrategy { + fn new() -> ExtensionStrategy { + ExtensionStrategy(HashMap::with_hasher(Fnv::default())) + } + + fn add(&mut self, global_index: usize, ext: String) { + self.0.entry(ext.into_bytes()).or_insert(vec![]).push(global_index); + } + + fn is_match(&self, candidate: &Candidate) -> bool { + if candidate.ext.is_empty() { + return false; + } + self.0.contains_key(&*candidate.ext) + } + + #[inline(never)] + fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { + if candidate.ext.is_empty() { + return; + } + if let Some(hits) = self.0.get(&*candidate.ext) { + matches.extend(hits); + } + } +} + +#[derive(Clone, Debug)] +struct PrefixStrategy { + matcher: FullAcAutomaton>, + map: Vec, + longest: usize, +} + +impl PrefixStrategy { + fn is_match(&self, candidate: &Candidate) -> bool { + let path = candidate.path_prefix(self.longest); + for m in self.matcher.find_overlapping(path) { + if m.start == 0 { + return true; + } + } + false + } + + fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { + let path = candidate.path_prefix(self.longest); + for m in self.matcher.find_overlapping(path) { + if m.start == 0 { + matches.push(self.map[m.pati]); + } + } + } +} + +#[derive(Clone, Debug)] +struct SuffixStrategy { + matcher: FullAcAutomaton>, + map: Vec, + longest: usize, +} + +impl SuffixStrategy { + fn is_match(&self, candidate: &Candidate) -> bool { + let path = candidate.path_suffix(self.longest); + for m in self.matcher.find_overlapping(path) { + if m.end == path.len() { + return true; + } + } + false + } + + fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { + let path = candidate.path_suffix(self.longest); + for m in self.matcher.find_overlapping(path) { + if m.end == path.len() { + matches.push(self.map[m.pati]); + } + } + } +} + +#[derive(Clone, Debug)] +struct RequiredExtensionStrategy(HashMap, Vec<(usize, Regex)>, Fnv>); + +impl RequiredExtensionStrategy { + fn is_match(&self, candidate: &Candidate) -> bool { + if candidate.ext.is_empty() { + return false; + } + match self.0.get(&*candidate.ext) { + None => false, + Some(regexes) => { + for &(_, ref re) in regexes { + if re.is_match(&*candidate.path) { + return true; + } + } + false + } + } + } + + #[inline(never)] + fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { + if candidate.ext.is_empty() { + return; + } + if let Some(regexes) = self.0.get(&*candidate.ext) { + for &(global_index, ref re) in regexes { + if re.is_match(&*candidate.path) { + matches.push(global_index); + } + } + } + } +} + +#[derive(Clone, Debug)] +struct RegexSetStrategy { + matcher: RegexSet, + map: Vec, +} + +impl RegexSetStrategy { + fn is_match(&self, candidate: &Candidate) -> bool { + self.matcher.is_match(&*candidate.path) + } + + fn matches_into(&self, candidate: &Candidate, matches: &mut Vec) { + for i in self.matcher.matches(&*candidate.path) { + matches.push(self.map[i]); + } + } +} + +#[derive(Clone, Debug)] +struct MultiStrategyBuilder { + literals: Vec, + map: Vec, + longest: usize, +} + +impl MultiStrategyBuilder { + fn new() -> MultiStrategyBuilder { + MultiStrategyBuilder { + literals: vec![], + map: vec![], + longest: 0, + } + } + + fn add(&mut self, global_index: usize, literal: String) { + if literal.len() > self.longest { + self.longest = literal.len(); + } + self.map.push(global_index); + self.literals.push(literal); + } + + fn prefix(self) -> PrefixStrategy { + let it = self.literals.into_iter().map(|s| s.into_bytes()); + PrefixStrategy { + matcher: AcAutomaton::new(it).into_full(), + map: self.map, + longest: self.longest, + } + } + + fn suffix(self) -> SuffixStrategy { + let it = self.literals.into_iter().map(|s| s.into_bytes()); + SuffixStrategy { + matcher: AcAutomaton::new(it).into_full(), + map: self.map, + longest: self.longest, + } + } + + fn regex_set(self) -> Result { + Ok(RegexSetStrategy { + matcher: new_regex_set(self.literals)?, + map: self.map, + }) + } +} + +#[derive(Clone, Debug)] +struct RequiredExtensionStrategyBuilder( + HashMap, Vec<(usize, String)>>, +); + +impl RequiredExtensionStrategyBuilder { + fn new() -> RequiredExtensionStrategyBuilder { + RequiredExtensionStrategyBuilder(HashMap::new()) + } + + fn add(&mut self, global_index: usize, ext: String, regex: String) { + self.0 + .entry(ext.into_bytes()) + .or_insert(vec![]) + .push((global_index, regex)); + } + + fn build(self) -> Result { + let mut exts = HashMap::with_hasher(Fnv::default()); + for (ext, regexes) in self.0.into_iter() { + exts.insert(ext.clone(), vec![]); + for (global_index, regex) in regexes { + let compiled = new_regex(®ex)?; + exts.get_mut(&ext).unwrap().push((global_index, compiled)); + } + } + Ok(RequiredExtensionStrategy(exts)) + } +} + +#[cfg(test)] +mod tests { + use super::GlobSetBuilder; + use glob::Glob; + + #[test] + fn set_works() { + let mut builder = GlobSetBuilder::new(); + builder.add(Glob::new("src/**/*.rs").unwrap()); + builder.add(Glob::new("*.c").unwrap()); + builder.add(Glob::new("src/lib.rs").unwrap()); + let set = builder.build().unwrap(); + + assert!(set.is_match("foo.c")); + assert!(set.is_match("src/foo.c")); + assert!(!set.is_match("foo.rs")); + assert!(!set.is_match("tests/foo.rs")); + assert!(set.is_match("src/foo.rs")); + assert!(set.is_match("src/grep/src/main.rs")); + + let matches = set.matches("src/lib.rs"); + assert_eq!(2, matches.len()); + assert_eq!(0, matches[0]); + assert_eq!(2, matches[1]); + } + + #[test] + fn empty_set_works() { + let set = GlobSetBuilder::new().build().unwrap(); + assert!(!set.is_match("")); + assert!(!set.is_match("a")); + } +} diff -Nru cargo-0.25.0/vendor/globset-0.3.0/src/pathutil.rs cargo-0.26.0/vendor/globset-0.3.0/src/pathutil.rs --- cargo-0.25.0/vendor/globset-0.3.0/src/pathutil.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.3.0/src/pathutil.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,172 @@ +use std::borrow::Cow; +use std::ffi::OsStr; +use std::path::Path; + +/// The final component of the path, if it is a normal file. +/// +/// If the path terminates in ., .., or consists solely of a root of prefix, +/// file_name will return None. +#[cfg(unix)] +pub fn file_name<'a, P: AsRef + ?Sized>( + path: &'a P, +) -> Option<&'a OsStr> { + use std::os::unix::ffi::OsStrExt; + use memchr::memrchr; + + let path = path.as_ref().as_os_str().as_bytes(); + if path.is_empty() { + return None; + } else if path.len() == 1 && path[0] == b'.' { + return None; + } else if path.last() == Some(&b'.') { + return None; + } else if path.len() >= 2 && &path[path.len() - 2..] == &b".."[..] { + return None; + } + let last_slash = memrchr(b'/', path).map(|i| i + 1).unwrap_or(0); + Some(OsStr::from_bytes(&path[last_slash..])) +} + +/// The final component of the path, if it is a normal file. +/// +/// If the path terminates in ., .., or consists solely of a root of prefix, +/// file_name will return None. +#[cfg(not(unix))] +pub fn file_name<'a, P: AsRef + ?Sized>( + path: &'a P, +) -> Option<&'a OsStr> { + path.as_ref().file_name() +} + +/// Return a file extension given a path's file name. +/// +/// Note that this does NOT match the semantics of std::path::Path::extension. +/// Namely, the extension includes the `.` and matching is otherwise more +/// liberal. Specifically, the extenion is: +/// +/// * None, if the file name given is empty; +/// * None, if there is no embedded `.`; +/// * Otherwise, the portion of the file name starting with the final `.`. +/// +/// e.g., A file name of `.rs` has an extension `.rs`. +/// +/// N.B. This is done to make certain glob match optimizations easier. Namely, +/// a pattern like `*.rs` is obviously trying to match files with a `rs` +/// extension, but it also matches files like `.rs`, which doesn't have an +/// extension according to std::path::Path::extension. +pub fn file_name_ext(name: &OsStr) -> Option> { + if name.is_empty() { + return None; + } + let name = os_str_bytes(name); + let last_dot_at = { + let result = name + .iter().enumerate().rev() + .find(|&(_, &b)| b == b'.') + .map(|(i, _)| i); + match result { + None => return None, + Some(i) => i, + } + }; + Some(match name { + Cow::Borrowed(name) => Cow::Borrowed(&name[last_dot_at..]), + Cow::Owned(mut name) => { + name.drain(..last_dot_at); + Cow::Owned(name) + } + }) +} + +/// Return raw bytes of a path, transcoded to UTF-8 if necessary. +pub fn path_bytes(path: &Path) -> Cow<[u8]> { + os_str_bytes(path.as_os_str()) +} + +/// Return the raw bytes of the given OS string, possibly transcoded to UTF-8. +#[cfg(unix)] +pub fn os_str_bytes(s: &OsStr) -> Cow<[u8]> { + use std::os::unix::ffi::OsStrExt; + Cow::Borrowed(s.as_bytes()) +} + +/// Return the raw bytes of the given OS string, possibly transcoded to UTF-8. +#[cfg(not(unix))] +pub fn os_str_bytes(s: &OsStr) -> Cow<[u8]> { + // TODO(burntsushi): On Windows, OS strings are WTF-8, which is a superset + // of UTF-8, so even if we could get at the raw bytes, they wouldn't + // be useful. We *must* convert to UTF-8 before doing path matching. + // Unfortunate, but necessary. + match s.to_string_lossy() { + Cow::Owned(s) => Cow::Owned(s.into_bytes()), + Cow::Borrowed(s) => Cow::Borrowed(s.as_bytes()), + } +} + +/// Normalizes a path to use `/` as a separator everywhere, even on platforms +/// that recognize other characters as separators. +#[cfg(unix)] +pub fn normalize_path(path: Cow<[u8]>) -> Cow<[u8]> { + // UNIX only uses /, so we're good. + path +} + +/// Normalizes a path to use `/` as a separator everywhere, even on platforms +/// that recognize other characters as separators. +#[cfg(not(unix))] +pub fn normalize_path(mut path: Cow<[u8]>) -> Cow<[u8]> { + use std::path::is_separator; + + for i in 0..path.len() { + if path[i] == b'/' || !is_separator(path[i] as char) { + continue; + } + path.to_mut()[i] = b'/'; + } + path +} + +#[cfg(test)] +mod tests { + use std::borrow::Cow; + use std::ffi::OsStr; + + use super::{file_name_ext, normalize_path}; + + macro_rules! ext { + ($name:ident, $file_name:expr, $ext:expr) => { + #[test] + fn $name() { + let got = file_name_ext(OsStr::new($file_name)); + assert_eq!($ext.map(|s| Cow::Borrowed(s.as_bytes())), got); + } + }; + } + + ext!(ext1, "foo.rs", Some(".rs")); + ext!(ext2, ".rs", Some(".rs")); + ext!(ext3, "..rs", Some(".rs")); + ext!(ext4, "", None::<&str>); + ext!(ext5, "foo", None::<&str>); + + macro_rules! normalize { + ($name:ident, $path:expr, $expected:expr) => { + #[test] + fn $name() { + let got = normalize_path(Cow::Owned($path.to_vec())); + assert_eq!($expected.to_vec(), got.into_owned()); + } + }; + } + + normalize!(normal1, b"foo", b"foo"); + normalize!(normal2, b"foo/bar", b"foo/bar"); + #[cfg(unix)] + normalize!(normal3, b"foo\\bar", b"foo\\bar"); + #[cfg(not(unix))] + normalize!(normal3, b"foo\\bar", b"foo/bar"); + #[cfg(unix)] + normalize!(normal4, b"foo\\bar/baz", b"foo\\bar/baz"); + #[cfg(not(unix))] + normalize!(normal4, b"foo\\bar/baz", b"foo/bar/baz"); +} diff -Nru cargo-0.25.0/vendor/globset-0.3.0/UNLICENSE cargo-0.26.0/vendor/globset-0.3.0/UNLICENSE --- cargo-0.25.0/vendor/globset-0.3.0/UNLICENSE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/globset-0.3.0/UNLICENSE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +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 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. + +For more information, please refer to diff -Nru cargo-0.25.0/vendor/hex-0.2.0/.cargo-checksum.json cargo-0.26.0/vendor/hex-0.2.0/.cargo-checksum.json --- cargo-0.25.0/vendor/hex-0.2.0/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.2.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"d6a22814455d41612f41161581c2883c0c6a1c41852729b17d5ed88f01e153aa"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/hex-0.2.0/Cargo.toml cargo-0.26.0/vendor/hex-0.2.0/Cargo.toml --- cargo-0.25.0/vendor/hex-0.2.0/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.2.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ -[package] -name = "hex" -version = "0.2.0" -authors = ["KokaKiwi "] -description = "A basic crate to encode values to hexadecimal representation." -license = "MIT OR Apache-2.0" -homepage = "https://github.com/KokaKiwi/rust-hex" -documentation = "https://kokakiwi.github.io/rust-hex/hex/" -repository = "https://github.com/KokaKiwi/rust-hex" diff -Nru cargo-0.25.0/vendor/hex-0.2.0/LICENSE-APACHE cargo-0.26.0/vendor/hex-0.2.0/LICENSE-APACHE --- cargo-0.25.0/vendor/hex-0.2.0/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.2.0/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,202 +0,0 @@ - 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. - diff -Nru cargo-0.25.0/vendor/hex-0.2.0/LICENSE-MIT cargo-0.26.0/vendor/hex-0.2.0/LICENSE-MIT --- cargo-0.25.0/vendor/hex-0.2.0/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.2.0/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -Copyright (c) 2015 The rust-hex 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. diff -Nru cargo-0.25.0/vendor/hex-0.2.0/README.md cargo-0.26.0/vendor/hex-0.2.0/README.md --- cargo-0.25.0/vendor/hex-0.2.0/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.2.0/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -Documentation: https://kokakiwi.github.io/rust-hex/hex/ - -## 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. diff -Nru cargo-0.25.0/vendor/hex-0.2.0/rust-hex.sublime-project cargo-0.26.0/vendor/hex-0.2.0/rust-hex.sublime-project --- cargo-0.25.0/vendor/hex-0.2.0/rust-hex.sublime-project 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.2.0/rust-hex.sublime-project 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -{ - "folders": - [ - { - "path": "." - } - ] -} diff -Nru cargo-0.25.0/vendor/hex-0.2.0/src/lib.rs cargo-0.26.0/vendor/hex-0.2.0/src/lib.rs --- cargo-0.25.0/vendor/hex-0.2.0/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.2.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,157 +0,0 @@ -use std::error; -use std::fmt; - -pub trait ToHex { - fn to_hex(&self) -> String; - - fn write_hex(&self, w: &mut W) -> fmt::Result { - w.write_str(&self.to_hex()) - } -} - -impl> ToHex for T { - fn to_hex(&self) -> String { - static CHARS: &'static [u8] = b"0123456789abcdef"; - - let bytes = self.as_ref(); - let mut v = Vec::with_capacity(bytes.len() * 2); - for &byte in bytes.iter() { - v.push(CHARS[(byte >> 4) as usize]); - v.push(CHARS[(byte & 0xf) as usize]); - } - - unsafe { - String::from_utf8_unchecked(v) - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq)] -pub enum FromHexError { - InvalidHexCharacter { - c: char, - index: usize, - }, - InvalidHexLength, -} - -impl error::Error for FromHexError { - fn description(&self) -> &str { - match *self { - FromHexError::InvalidHexCharacter{ .. } => "invalid character", - FromHexError::InvalidHexLength => "invalid length", - } - } -} - -impl fmt::Display for FromHexError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - FromHexError::InvalidHexCharacter { c, index } => - write!(f, "Invalid character '{}' at position {}", c, index), - FromHexError::InvalidHexLength => - write!(f, "Invalid string length"), - } - } -} - -pub trait FromHex: Sized { - type Error; - - fn from_hex>(s: T) -> Result; -} - -impl FromHex for Vec { - type Error = FromHexError; - - fn from_hex>(s: T) -> Result { - let bytes = s.as_ref(); - let mut b = Vec::with_capacity(bytes.len() / 2); - let mut modulus = 0; - let mut buf = 08; - - for (idx, byte) in bytes.iter().enumerate() { - buf <<= 4; - - match *byte { - b'A'...b'F' => buf |= byte - b'A' + 10, - b'a'...b'f' => buf |= byte - b'a' + 10, - b'0'...b'9' => buf |= byte - b'0', - _ => { - return Err(FromHexError::InvalidHexCharacter { - c: bytes[idx] as char, - index: idx, - }) - } - } - - modulus += 1; - if modulus == 2 { - modulus = 0; - b.push(buf); - } - } - - match modulus { - 0 => Ok(b.into_iter().collect()), - _ => Err(FromHexError::InvalidHexLength), - } - } -} - -#[cfg(test)] -mod test { - use super::{FromHex, FromHexError, ToHex}; - - #[test] - fn test_to_hex() { - assert_eq!("foobar".to_hex(), "666f6f626172"); - } - - #[test] - pub fn test_from_hex_okay_str() { - assert_eq!(Vec::from_hex("666f6f626172").unwrap(), - b"foobar"); - assert_eq!(Vec::from_hex("666F6F626172").unwrap(), - b"foobar"); - } - - #[test] - pub fn test_from_hex_okay_bytes() { - assert_eq!(Vec::from_hex(b"666f6f626172").unwrap(), - b"foobar"); - assert_eq!(Vec::from_hex(b"666F6F626172").unwrap(), - b"foobar"); - } - - #[test] - pub fn test_invalid_length() { - assert_eq!(Vec::from_hex("1").unwrap_err(), - FromHexError::InvalidHexLength); - assert_eq!(Vec::from_hex("666f6f6261721").unwrap_err(), - FromHexError::InvalidHexLength); - } - - #[test] - pub fn test_invalid_char() { - assert_eq!(Vec::from_hex("66ag").unwrap_err(), - FromHexError::InvalidHexCharacter { - c: 'g', - index: 3 - }); - } - - #[test] - pub fn test_empty() { - assert_eq!(Vec::from_hex("").unwrap(), b""); - } - - #[test] - pub fn test_from_hex_whitespace() { - assert_eq!(Vec::from_hex("666f 6f626172").unwrap_err(), - FromHexError::InvalidHexCharacter { - c: ' ', - index: 4 - }); - } -} diff -Nru cargo-0.25.0/vendor/hex-0.2.0/toto.rs cargo-0.26.0/vendor/hex-0.2.0/toto.rs --- cargo-0.25.0/vendor/hex-0.2.0/toto.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.2.0/toto.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,209 +0,0 @@ -// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -// -// ignore-lexer-test FIXME #15679 - -//! Hex binary-to-text encoding - -pub use self::FromHexError::*; - -use std::fmt; -use std::error; - -/// A trait for converting a value to hexadecimal encoding -pub trait ToHex { - /// Converts the value of `self` to a hex value, returning the owned - /// string. - fn to_hex(&self) -> String; -} - -static CHARS: &'static[u8] = b"0123456789abcdef"; - -impl ToHex for [u8] { - /// Turn a vector of `u8` bytes into a hexadecimal string. - /// - /// # Example - /// - /// ```rust - /// extern crate rustc_serialize; - /// use rustc_serialize::hex::ToHex; - /// - /// fn main () { - /// let str = [52,32].to_hex(); - /// println!("{}", str); - /// } - /// ``` - fn to_hex(&self) -> String { - let mut v = Vec::with_capacity(self.len() * 2); - for &byte in self.iter() { - v.push(CHARS[(byte >> 4) as usize]); - v.push(CHARS[(byte & 0xf) as usize]); - } - - unsafe { - String::from_utf8_unchecked(v) - } - } -} - -/// A trait for converting hexadecimal encoded values -pub trait FromHex { - /// Converts the value of `self`, interpreted as hexadecimal encoded data, - /// into an owned vector of bytes, returning the vector. - fn from_hex(&self) -> Result, FromHexError>; -} - -/// Errors that can occur when decoding a hex encoded string -#[derive(Clone, Copy)] -pub enum FromHexError { - /// The input contained a character not part of the hex format - InvalidHexCharacter(char, usize), - /// The input had an invalid length - InvalidHexLength, -} - -impl fmt::Debug for FromHexError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - InvalidHexCharacter(ch, idx) => - write!(f, "Invalid character '{}' at position {}", ch, idx), - InvalidHexLength => write!(f, "Invalid input length"), - } - } -} - -impl error::Error for FromHexError { - fn description(&self) -> &str { - match *self { - InvalidHexCharacter(_, _) => "invalid character", - InvalidHexLength => "invalid length", - } - } -} - -impl fmt::Display for FromHexError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(&self, f) - } -} - -impl FromHex for str { - /// Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`) - /// to the byte values it encodes. - /// - /// You can use the `String::from_utf8` function to turn a - /// `Vec` into a string with characters corresponding to those values. - /// - /// # Example - /// - /// This converts a string literal to hexadecimal and back. - /// - /// ```rust - /// extern crate rustc_serialize; - /// use rustc_serialize::hex::{FromHex, ToHex}; - /// - /// fn main () { - /// let hello_str = "Hello, World".as_bytes().to_hex(); - /// println!("{}", hello_str); - /// let bytes = hello_str.from_hex().unwrap(); - /// println!("{:?}", bytes); - /// let result_str = String::from_utf8(bytes).unwrap(); - /// println!("{}", result_str); - /// } - /// ``` - fn from_hex(&self) -> Result, FromHexError> { - // This may be an overestimate if there is any whitespace - let mut b = Vec::with_capacity(self.len() / 2); - let mut modulus = 0; - let mut buf = 08; - - for (idx, byte) in self.bytes().enumerate() { - buf <<= 4; - - match byte { - b'A'...b'F' => buf |= byte - b'A' + 10, - b'a'...b'f' => buf |= byte - b'a' + 10, - b'0'...b'9' => buf |= byte - b'0', - b' '|b'\r'|b'\n'|b'\t' => { - buf >>= 4; - continue - } - _ => { - let ch = self[idx..].chars().next().unwrap(); - return Err(InvalidHexCharacter(ch, idx)) - } - } - - modulus += 1; - if modulus == 2 { - modulus = 0; - b.push(buf); - } - } - - match modulus { - 0 => Ok(b.into_iter().collect()), - _ => Err(InvalidHexLength), - } - } -} - -#[cfg(test)] -mod tests { - use hex::{FromHex, ToHex}; - - #[test] - pub fn test_to_hex() { - assert_eq!("foobar".as_bytes().to_hex(), "666f6f626172"); - } - - #[test] - pub fn test_from_hex_okay() { - assert_eq!("666f6f626172".from_hex().unwrap(), - b"foobar"); - assert_eq!("666F6F626172".from_hex().unwrap(), - b"foobar"); - } - - #[test] - pub fn test_from_hex_odd_len() { - assert!("666".from_hex().is_err()); - assert!("66 6".from_hex().is_err()); - } - - #[test] - pub fn test_from_hex_invalid_char() { - assert!("66y6".from_hex().is_err()); - } - - #[test] - pub fn test_from_hex_ignores_whitespace() { - assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(), - b"foobar"); - } - - #[test] - pub fn test_to_hex_all_bytes() { - for i in 0..256 { - assert_eq!([i as u8].to_hex(), format!("{:02x}", i)); - } - } - - #[test] - pub fn test_from_hex_all_bytes() { - for i in 0..256 { - let ii: &[u8] = &[i as u8]; - assert_eq!(format!("{:02x}", i).from_hex().unwrap(), - ii); - assert_eq!(format!("{:02X}", i).from_hex().unwrap(), - ii); - } - } -} diff -Nru cargo-0.25.0/vendor/hex-0.2.0/.travis.yml cargo-0.26.0/vendor/hex-0.2.0/.travis.yml --- cargo-0.25.0/vendor/hex-0.2.0/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.2.0/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -language: rust -rust: - - stable - - beta - - nightly -matrix: - allow_failures: - - rust: nightly diff -Nru cargo-0.25.0/vendor/hex-0.3.1/.cargo-checksum.json cargo-0.26.0/vendor/hex-0.3.1/.cargo-checksum.json --- cargo-0.25.0/vendor/hex-0.3.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.3.1/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"459d3cf58137bb02ad4adeef5036377ff59f066dbb82517b7192e3a5462a2abc"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/hex-0.3.1/Cargo.toml cargo-0.26.0/vendor/hex-0.3.1/Cargo.toml --- cargo-0.25.0/vendor/hex-0.3.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.3.1/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "hex" +version = "0.3.1" +authors = ["KokaKiwi "] +description = "Encoding and decoding data into/from hexadecimal representation." +documentation = "https://docs.rs/hex/" +license = "MIT OR Apache-2.0" +repository = "https://github.com/KokaKiwi/rust-hex" diff -Nru cargo-0.25.0/vendor/hex-0.3.1/LICENSE-APACHE cargo-0.26.0/vendor/hex-0.3.1/LICENSE-APACHE --- cargo-0.25.0/vendor/hex-0.3.1/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.3.1/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -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. + diff -Nru cargo-0.25.0/vendor/hex-0.3.1/LICENSE-MIT cargo-0.26.0/vendor/hex-0.3.1/LICENSE-MIT --- cargo-0.25.0/vendor/hex-0.3.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.3.1/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +Copyright (c) 2013-2014 The Rust Project Developers. +Copyright (c) 2015-2016 The rust-hex 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. diff -Nru cargo-0.25.0/vendor/hex-0.3.1/README.md cargo-0.26.0/vendor/hex-0.3.1/README.md --- cargo-0.25.0/vendor/hex-0.3.1/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.3.1/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,17 @@ +Documentation: https://docs.rs/hex + +## 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. diff -Nru cargo-0.25.0/vendor/hex-0.3.1/src/lib.rs cargo-0.26.0/vendor/hex-0.3.1/src/lib.rs --- cargo-0.25.0/vendor/hex-0.3.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.3.1/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,385 @@ +// Copyright (c) 2013-2014 The Rust Project Developers. +// Copyright (c) 2015-2017 The rust-hex Developers. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +//! Encoding and decoding hex strings. +//! +//! For most cases, you can simply use the `decode()`, `encode()` and +//! `encode_upper()` functions. If you need a bit more control, use the traits +//! `ToHex` and `FromHex` instead. +//! +//! # Example +//! +//! ``` +//! extern crate hex; +//! +//! fn main() { +//! let hex_string = hex::encode("Hello world!"); +//! println!("{}", hex_string); // Prints '48656c6c6f20776f726c6421' +//! } +//! ``` + +use std::error; +use std::fmt; + +/// Encoding values as hex string. +/// +/// This trait is implemented for all `T` which implement `AsRef<[u8]>`. This +/// includes `String`, `str`, `Vec` and `[u8]`. +/// +/// # Example +/// +/// ``` +/// use hex::ToHex; +/// +/// let mut s = String::new(); +/// "Hello world!".write_hex(&mut s).unwrap(); +/// println!("{}", s); +/// ``` +/// +/// *Note*: instead of using this trait, you might want to use `encode()`. +pub trait ToHex { + /// Writes the hex string representing `self` into `w`. Lower case letters + /// are used (e.g. `f9b4ca`). + fn write_hex(&self, w: &mut W) -> fmt::Result; + + /// Writes the hex string representing `self` into `w`. Upper case letters + /// are used (e.g. `F9B4CA`). + fn write_hex_upper(&self, w: &mut W) -> fmt::Result; +} + + +impl> ToHex for T { + fn write_hex(&self, w: &mut W) -> fmt::Result { + static CHARS: &'static [u8] = b"0123456789abcdef"; + + for &byte in self.as_ref().iter() { + w.write_char(CHARS[(byte >> 4) as usize].into())?; + w.write_char(CHARS[(byte & 0xf) as usize].into())?; + } + + Ok(()) + } + + fn write_hex_upper(&self, w: &mut W) -> fmt::Result { + static CHARS: &'static [u8] = b"0123456789ABCDEF"; + + for &byte in self.as_ref().iter() { + w.write_char(CHARS[(byte >> 4) as usize].into())?; + w.write_char(CHARS[(byte & 0xf) as usize].into())?; + } + + Ok(()) + } +} + +/// The error type for decoding a hex string into `Vec` or `[u8; N]`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum FromHexError { + /// An invalid character was found. Valid ones are: `0...9`, `a...f` + /// or `A...F`. + InvalidHexCharacter { + c: char, + index: usize, + }, + + /// A hex string's length needs to be even, as two digits correspond to + /// one byte. + OddLength, + + /// If the hex string is decoded into a fixed sized container, such as an + /// array, the hex string's length * 2 has to match the container's + /// length. + InvalidStringLength, +} + +impl error::Error for FromHexError { + fn description(&self) -> &str { + match *self { + FromHexError::InvalidHexCharacter { .. } => "invalid character", + FromHexError::OddLength => "odd number of digits", + FromHexError::InvalidStringLength => "invalid string length", + + } + } +} + +impl fmt::Display for FromHexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + FromHexError::InvalidHexCharacter { c, index } => + write!(f, "Invalid character '{}' at position {}", c, index), + FromHexError::OddLength => + write!(f, "Odd number of digits"), + FromHexError::InvalidStringLength => + write!(f, "Invalid string length"), + } + } +} + +/// Types that can be decoded from a hex string. +/// +/// This trait is implemented for `Vec` and small `u8`-arrays. +/// +/// # Example +/// +/// ``` +/// use hex::FromHex; +/// +/// match Vec::from_hex("48656c6c6f20776f726c6421") { +/// Ok(vec) => { +/// for b in vec { +/// println!("{}", b as char); +/// } +/// } +/// Err(e) => { +/// // Deal with the error ... +/// } +/// } +/// ``` +pub trait FromHex: Sized { + type Error; + + /// Creates an instance of type `Self` from the given hex string, or fails + /// with a custom error type. + /// + /// Both, upper and lower case characters are valid and can even be + /// mixed (e.g. `f9b4ca`, `F9B4CA` and `f9B4Ca` are all valid strings). + fn from_hex>(hex: T) -> Result; +} + +fn val(c: u8, idx: usize) -> Result { + match c { + b'A'...b'F' => Ok(c - b'A' + 10), + b'a'...b'f' => Ok(c - b'a' + 10), + b'0'...b'9' => Ok(c - b'0'), + _ => { + Err(FromHexError::InvalidHexCharacter { + c: c as char, + index: idx, + }) + } + } +} + +impl FromHex for Vec { + type Error = FromHexError; + + fn from_hex>(hex: T) -> Result { + let hex = hex.as_ref(); + if hex.len() % 2 != 0 { + return Err(FromHexError::OddLength); + } + + hex.chunks(2).enumerate().map(|(i, pair)| { + Ok(val(pair[0], 2 * i)? << 4 | val(pair[1], 2 * i + 1)?) + }).collect() + } +} + +// Helper macro to implement the trait for a few fixed sized arrays. Once Rust +// has type level integers, this should be removed. +macro_rules! impl_from_hex_for_array { + ($len:expr) => { + impl FromHex for [u8; $len] { + type Error = FromHexError; + + fn from_hex>(hex: T) -> Result { + let hex = hex.as_ref(); + if hex.len() % 2 != 0 { + return Err(FromHexError::OddLength); + } + if hex.len() / 2 != $len { + return Err(FromHexError::InvalidStringLength); + } + + let mut out = [0; $len]; + for (i, byte) in out.iter_mut().enumerate() { + *byte = val(hex[2 * i], 2 * i)? << 4 + | val(hex[2 * i + 1], 2 * i + 1)?; + } + + Ok(out) + } + } + } +} + +impl_from_hex_for_array!(1); +impl_from_hex_for_array!(2); +impl_from_hex_for_array!(3); +impl_from_hex_for_array!(4); +impl_from_hex_for_array!(5); +impl_from_hex_for_array!(6); +impl_from_hex_for_array!(7); +impl_from_hex_for_array!(8); +impl_from_hex_for_array!(9); +impl_from_hex_for_array!(10); +impl_from_hex_for_array!(11); +impl_from_hex_for_array!(12); +impl_from_hex_for_array!(13); +impl_from_hex_for_array!(14); +impl_from_hex_for_array!(15); +impl_from_hex_for_array!(16); + +// Throw in some multiples of 8 which may be useful. +impl_from_hex_for_array!(24); +impl_from_hex_for_array!(32); +impl_from_hex_for_array!(40); +impl_from_hex_for_array!(48); +impl_from_hex_for_array!(56); +impl_from_hex_for_array!(64); + +/// Encodes `data` as hex string using lowercase characters. +/// +/// Lowercase characters are used (e.g. `f9b4ca`). The resulting string's +/// length is always even, each byte in `data` is always encoded using two hex +/// digits. Thus, the resulting string contains exactly twice as many bytes as +/// the input data. +/// +/// # Example +/// +/// ``` +/// assert_eq!(hex::encode("Hello world!"), "48656c6c6f20776f726c6421"); +/// assert_eq!(hex::encode(vec![1, 2, 3, 15, 16]), "0102030f10"); +/// ``` +pub fn encode>(data: T) -> String { + let mut s = String::with_capacity(data.as_ref().len() * 2); + + // Writing to a string never errors, so we can unwrap here. + data.write_hex(&mut s).unwrap(); + s +} + +/// Encodes `data` as hex string using uppercase characters. +/// +/// Apart from the characters' casing, this works exactly like `encode()`. +/// +/// # Example +/// +/// ``` +/// assert_eq!(hex::encode_upper("Hello world!"), "48656C6C6F20776F726C6421"); +/// assert_eq!(hex::encode_upper(vec![1, 2, 3, 15, 16]), "0102030F10"); +/// ``` +pub fn encode_upper>(data: T) -> String { + let mut s = String::with_capacity(data.as_ref().len() * 2); + + // Writing to a string never errors, so we can unwrap here. + data.write_hex_upper(&mut s).unwrap(); + s +} + +/// Decodes a hex string into raw bytes. +/// +/// Both, upper and lower case characters are valid in the input string and can +/// even be mixed (e.g. `f9b4ca`, `F9B4CA` and `f9B4Ca` are all valid strings). +/// +/// # Example +/// ``` +/// assert_eq!( +/// hex::decode("48656c6c6f20776f726c6421"), +/// Ok("Hello world!".to_owned().into_bytes()) +/// ); +/// +/// assert_eq!(hex::decode("123"), Err(hex::FromHexError::OddLength)); +/// assert!(hex::decode("foo").is_err()); +/// ``` +pub fn decode>(data: T) -> Result, FromHexError> { + FromHex::from_hex(data) +} + + +#[cfg(test)] +mod test { + use super::{encode, decode, FromHex, FromHexError}; + + #[test] + fn test_encode() { + assert_eq!(encode("foobar"), "666f6f626172"); + } + + #[test] + fn test_decode() { + assert_eq!(decode("666f6f626172"), Ok("foobar".to_owned().into_bytes())); + } + + #[test] + pub fn test_from_hex_okay_str() { + assert_eq!( + Vec::from_hex("666f6f626172").unwrap(), + b"foobar" + ); + assert_eq!( + Vec::from_hex("666F6F626172").unwrap(), + b"foobar" + ); + } + + #[test] + pub fn test_from_hex_okay_bytes() { + assert_eq!( + Vec::from_hex(b"666f6f626172").unwrap(), + b"foobar" + ); + assert_eq!( + Vec::from_hex(b"666F6F626172").unwrap(), + b"foobar" + ); + } + + #[test] + pub fn test_invalid_length() { + assert_eq!( + Vec::from_hex("1").unwrap_err(), + FromHexError::OddLength + ); + assert_eq!( + Vec::from_hex("666f6f6261721").unwrap_err(), + FromHexError::OddLength + ); + } + + #[test] + pub fn test_invalid_char() { + assert_eq!( + Vec::from_hex("66ag").unwrap_err(), + FromHexError::InvalidHexCharacter { + c: 'g', + index: 3 + } + ); + } + + #[test] + pub fn test_empty() { + assert_eq!(Vec::from_hex("").unwrap(), b""); + } + + #[test] + pub fn test_from_hex_whitespace() { + assert_eq!( + Vec::from_hex("666f 6f62617").unwrap_err(), + FromHexError::InvalidHexCharacter { + c: ' ', + index: 4 + } + ); + } + + #[test] + pub fn test_from_hex_array() { + assert_eq!( + <[u8; 6] as FromHex>::from_hex("666f6f626172"), + Ok([0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72]) + ); + + assert_eq!( + <[u8; 5] as FromHex>::from_hex("666f6f626172"), + Err(FromHexError::InvalidStringLength) + ); + } +} diff -Nru cargo-0.25.0/vendor/hex-0.3.1/.travis.yml cargo-0.26.0/vendor/hex-0.3.1/.travis.yml --- cargo-0.25.0/vendor/hex-0.3.1/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/hex-0.3.1/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,8 @@ +language: rust +rust: + - stable + - beta + - nightly +matrix: + allow_failures: + - rust: nightly diff -Nru cargo-0.25.0/vendor/home-0.3.0/.cargo-checksum.json cargo-0.26.0/vendor/home-0.3.0/.cargo-checksum.json --- cargo-0.25.0/vendor/home-0.3.0/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/home-0.3.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"9f25ae61099d8f3fee8b483df0bd4ecccf4b2731897aad40d50eca1b641fe6db"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/home-0.3.0/Cargo.toml cargo-0.26.0/vendor/home-0.3.0/Cargo.toml --- cargo-0.25.0/vendor/home-0.3.0/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/home-0.3.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "home" -version = "0.3.0" -authors = ["Brian Anderson "] -description = "Shared definitions of home directories" -documentation = "https://docs.rs/home" -license = "MIT/Apache-2.0" -repository = "https://github.com/brson/home" -[target."cfg(windows)".dependencies.winapi] -version = "0.2.8" - -[target."cfg(windows)".dependencies.kernel32-sys] -version = "0.2.1" - -[target."cfg(windows)".dependencies.scopeguard] -version = "0.1.2" - -[target."cfg(windows)".dependencies.userenv-sys] -version = "0.2.0" - -[target."cfg(windows)".dependencies.advapi32-sys] -version = "0.2.0" diff -Nru cargo-0.25.0/vendor/home-0.3.0/README.md cargo-0.26.0/vendor/home-0.3.0/README.md --- cargo-0.25.0/vendor/home-0.3.0/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/home-0.3.0/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -Canonical definitions of `home_dir`, `cargo_home`, and `rustup_home`. - -This provides the definition of `home_dir` used by Cargo and rustup, -as well functions to find the correct value of `CARGO_HOME` and -`RUSTUP_HOME`. - -The definition of `home_dir` provided by the standard library is -incorrect because it considers the `HOME` environment variable on -Windows. This causes surprising situations where a Rust program will -behave differently depending on whether it is run under a Unix -emulation environment like Cygwin or MinGW. Neither Cargo nor rustup -use the standard libraries definition - they use the definition here. - -This crate further provides two functions, `cargo_home` and -`rustup_home`, which are the canonical way to determine the location -that Cargo and rustup store their data. - -See [rust-lang/rust#43321]. - -[rust-lang/rust#43321]: https://github.com/rust-lang/rust/issues/43321 - -## License - -MIT/Apache-2.0 diff -Nru cargo-0.25.0/vendor/home-0.3.0/src/lib.rs cargo-0.26.0/vendor/home-0.3.0/src/lib.rs --- cargo-0.25.0/vendor/home-0.3.0/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/home-0.3.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,302 +0,0 @@ -/// Canonical definitions of `home_dir`, `cargo_home`, and `rustup_home`. -/// -/// This provides the definition of `home_dir` used by Cargo and -/// rustup, as well functions to find the correct value of -/// `CARGO_HOME` and `RUSTUP_HOME`. -/// -/// The definition of `home_dir` provided by the standard library is -/// incorrect because it considers the `HOME` environment variable on -/// Windows. This causes surprising situations where a Rust program -/// will behave differently depending on whether it is run under a -/// Unix emulation environment like Cygwin or MinGW. Neither Cargo nor -/// rustup use the standard libraries definition - they use the -/// definition here. -/// -/// This crate further provides two functions, `cargo_home` and -/// `rustup_home`, which are the canonical way to determine the -/// location that Cargo and rustup store their data. -/// -/// See [rust-lang/rust#43321]. -/// -/// [rust-lang/rust#43321]: https://github.com/rust-lang/rust/issues/43321 - -#[cfg(windows)] -extern crate scopeguard; -#[cfg(windows)] -extern crate winapi; -#[cfg(windows)] -extern crate kernel32; -#[cfg(windows)] -extern crate advapi32; -#[cfg(windows)] -extern crate userenv; - -#[cfg(windows)] -use winapi::DWORD; -use std::path::{PathBuf, Path}; -use std::io; -use std::env; - -/// Returns the path of the current user's home directory if known. -/// -/// # Unix -/// -/// Returns the value of the 'HOME' environment variable if it is set -/// and not equal to the empty string. Otherwise, it tries to determine the -/// home directory by invoking the `getpwuid_r` function on the UID of the -/// current user. -/// -/// # Windows -/// -/// Returns the value of the 'USERPROFILE' environment variable if it -/// is set and not equal to the empty string. If both do not exist, -/// [`GetUserProfileDirectory`][msdn] is used to return the -/// appropriate path. -/// -/// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762280(v=vs.85).aspx -/// -/// # Examples -/// -/// ``` -/// use std::env; -/// -/// match env::home_dir() { -/// Some(path) => println!("{}", path.display()), -/// None => println!("Impossible to get your home dir!"), -/// } -/// ``` -pub fn home_dir() -> Option { - home_dir_() -} - -#[cfg(windows)] -fn home_dir_() -> Option { - use std::ptr; - use kernel32::{GetCurrentProcess, GetLastError, CloseHandle}; - use advapi32::OpenProcessToken; - use userenv::GetUserProfileDirectoryW; - use winapi::ERROR_INSUFFICIENT_BUFFER; - use winapi::winnt::TOKEN_READ; - use scopeguard; - - ::std::env::var_os("USERPROFILE").map(PathBuf::from).or_else(|| unsafe { - let me = GetCurrentProcess(); - let mut token = ptr::null_mut(); - if OpenProcessToken(me, TOKEN_READ, &mut token) == 0 { - return None; - } - let _g = scopeguard::guard(token, |h| { let _ = CloseHandle(*h); }); - fill_utf16_buf(|buf, mut sz| { - match GetUserProfileDirectoryW(token, buf, &mut sz) { - 0 if GetLastError() != ERROR_INSUFFICIENT_BUFFER => 0, - 0 => sz, - _ => sz - 1, // sz includes the null terminator - } - }, os2path).ok() - }) -} - -#[cfg(windows)] -fn os2path(s: &[u16]) -> PathBuf { - use std::ffi::OsString; - use std::os::windows::ffi::OsStringExt; - PathBuf::from(OsString::from_wide(s)) -} - -#[cfg(windows)] -fn fill_utf16_buf(mut f1: F1, f2: F2) -> io::Result - where F1: FnMut(*mut u16, DWORD) -> DWORD, - F2: FnOnce(&[u16]) -> T -{ - use kernel32::{GetLastError, SetLastError}; - use winapi::{ERROR_INSUFFICIENT_BUFFER}; - - // Start off with a stack buf but then spill over to the heap if we end up - // needing more space. - let mut stack_buf = [0u16; 512]; - let mut heap_buf = Vec::new(); - unsafe { - let mut n = stack_buf.len(); - loop { - let buf = if n <= stack_buf.len() { - &mut stack_buf[..] - } else { - let extra = n - heap_buf.len(); - heap_buf.reserve(extra); - heap_buf.set_len(n); - &mut heap_buf[..] - }; - - // This function is typically called on windows API functions which - // will return the correct length of the string, but these functions - // also return the `0` on error. In some cases, however, the - // returned "correct length" may actually be 0! - // - // To handle this case we call `SetLastError` to reset it to 0 and - // then check it again if we get the "0 error value". If the "last - // error" is still 0 then we interpret it as a 0 length buffer and - // not an actual error. - SetLastError(0); - let k = match f1(buf.as_mut_ptr(), n as DWORD) { - 0 if GetLastError() == 0 => 0, - 0 => return Err(io::Error::last_os_error()), - n => n, - } as usize; - if k == n && GetLastError() == ERROR_INSUFFICIENT_BUFFER { - n *= 2; - } else if k >= n { - n = k; - } else { - return Ok(f2(&buf[..k])) - } - } - } -} - -#[cfg(unix)] -fn home_dir_() -> Option { - ::std::env::home_dir() -} - -/// Returns the storage directory used by Cargo, often knowns as -/// `.cargo` or `CARGO_HOME`. -/// -/// It returns one of the following values, in this order of -/// preference: -/// -/// - The value of the `CARGO_HOME` environment variable, if it is -/// an absolute path. -/// - The value of the current working directory joined with the value -/// of the `CARGO_HOME` environment variable, if `CARGO_HOME` is a -/// relative directory. -/// - The `.cargo` directory in the user's home directory, as reported -/// by the `home_dir` function. -/// -/// # Errors -/// -/// This function fails if it fails to retrieve the current directory, -/// or if the home directory cannot be determined. -pub fn cargo_home() -> io::Result { - let cwd = env::current_dir()?; - cargo_home_with_cwd(&cwd) -} - -pub fn cargo_home_with_cwd(cwd: &Path) -> io::Result { - let env_var = env::var_os("CARGO_HOME"); - - // NB: During the multirust-rs -> rustup transition the install - // dir changed from ~/.multirust/bin to ~/.cargo/bin. Because - // multirust used to explicitly set CARGO_HOME it's possible to - // get here when e.g. installing under `cargo run` and decide to - // install to the wrong place. This check is to make the - // multirust-rs to rustup upgrade seamless. - let env_var = if let Some(v) = env_var { - let vv = v.to_string_lossy().to_string(); - if vv.contains(".multirust/cargo") || - vv.contains(r".multirust\cargo") || - vv.trim().is_empty() { - None - } else { - Some(v) - } - } else { - None - }; - - let env_cargo_home = env_var.map(|home| cwd.join(home)); - let home_dir = home_dir() - .ok_or(io::Error::new(io::ErrorKind::Other, "couldn't find home dir")); - let user_home = home_dir.map(|p| p.join(".cargo")); - - // Compatibility with old cargo that used the std definition of home_dir - let compat_home_dir = ::std::env::home_dir(); - let compat_user_home = compat_home_dir.map(|p| p.join(".cargo")); - - if let Some(p) = env_cargo_home { - Ok(p) - } else { - if let Some(d) = compat_user_home { - if d.exists() { - Ok(d) - } else { - user_home - } - } else { - user_home - } - } -} - -/// Returns the storage directory used by rustup, often knowns as -/// `.rustup` or `RUSTUP_HOME`. -/// -/// It returns one of the following values, in this order of -/// preference: -/// -/// - The value of the `RUSTUP_HOME` environment variable, if it is -/// an absolute path. -/// - The value of the current working directory joined with the value -/// of the `RUSTUP_HOME` environment variable, if `RUSTUP_HOME` is a -/// relative directory. -/// - The `.rustup` directory in the user's home directory, as reported -/// by the `home_dir` function. -/// -/// As a matter of backwards compatibility, this function _may_ return -/// the `.multirust` directory in the user's home directory, only if -/// it determines that the user is running an old version of rustup -/// where that is necessary. -/// -/// # Errors -/// -/// This function fails if it fails to retrieve the current directory, -/// or if the home directory cannot be determined. -pub fn rustup_home() -> io::Result { - let cwd = env::current_dir()?; - rustup_home_with_cwd(&cwd) -} - -pub fn rustup_home_with_cwd(cwd: &Path) -> io::Result { - let env_var = env::var_os("RUSTUP_HOME"); - let env_rustup_home = env_var.map(|home| cwd.join(home)); - let home_dir = home_dir() - .ok_or(io::Error::new(io::ErrorKind::Other, "couldn't find home dir")); - - let user_home = if use_rustup_dir() { - home_dir.map(|d| d.join(".rustup")) - } else { - home_dir.map(|d| d.join(".multirust")) - }; - - if let Some(p) = env_rustup_home { - Ok(p) - } else { - user_home - } -} - -fn use_rustup_dir() -> bool { - fn rustup_dir() -> Option { - home_dir().map(|p| p.join(".rustup")) - } - - fn multirust_dir() -> Option { - home_dir().map(|p| p.join(".multirust")) - } - - fn rustup_dir_exists() -> bool { - rustup_dir().map(|p| p.exists()).unwrap_or(false) - } - - fn multirust_dir_exists() -> bool { - multirust_dir().map(|p| p.exists()).unwrap_or(false) - } - - fn rustup_old_version_exists() -> bool { - rustup_dir() - .map(|p| p.join("rustup-version").exists()) - .unwrap_or(false) - } - - !rustup_old_version_exists() - && (rustup_dir_exists() || !multirust_dir_exists()) -} diff -Nru cargo-0.25.0/vendor/home-0.3.2/.cargo-checksum.json cargo-0.26.0/vendor/home-0.3.2/.cargo-checksum.json --- cargo-0.25.0/vendor/home-0.3.2/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/home-0.3.2/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"8f94f6fbdc000a6eba0c8cf08632b2091bb59141d36ac321a2a96d6365e5e4dc"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/home-0.3.2/Cargo.toml cargo-0.26.0/vendor/home-0.3.2/Cargo.toml --- cargo-0.25.0/vendor/home-0.3.2/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/home-0.3.2/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,29 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "home" +version = "0.3.2" +authors = ["Brian Anderson "] +description = "Shared definitions of home directories" +documentation = "https://docs.rs/home" +license = "MIT/Apache-2.0" +repository = "https://github.com/brson/home" +[target."cfg(windows)".dependencies.scopeguard] +version = "0.3" + +[target."cfg(windows)".dependencies.userenv-sys] +version = "0.2.0" + +[target."cfg(windows)".dependencies.winapi] +version = "0.3" +features = ["errhandlingapi", "handleapi", "processthreadsapi", "std", "winerror", "winnt"] diff -Nru cargo-0.25.0/vendor/home-0.3.2/README.md cargo-0.26.0/vendor/home-0.3.2/README.md --- cargo-0.25.0/vendor/home-0.3.2/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/home-0.3.2/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,24 @@ +Canonical definitions of `home_dir`, `cargo_home`, and `rustup_home`. + +This provides the definition of `home_dir` used by Cargo and rustup, +as well functions to find the correct value of `CARGO_HOME` and +`RUSTUP_HOME`. + +The definition of `home_dir` provided by the standard library is +incorrect because it considers the `HOME` environment variable on +Windows. This causes surprising situations where a Rust program will +behave differently depending on whether it is run under a Unix +emulation environment like Cygwin or MinGW. Neither Cargo nor rustup +use the standard libraries definition - they use the definition here. + +This crate further provides two functions, `cargo_home` and +`rustup_home`, which are the canonical way to determine the location +that Cargo and rustup store their data. + +See [rust-lang/rust#43321]. + +[rust-lang/rust#43321]: https://github.com/rust-lang/rust/issues/43321 + +## License + +MIT/Apache-2.0 diff -Nru cargo-0.25.0/vendor/home-0.3.2/src/lib.rs cargo-0.26.0/vendor/home-0.3.2/src/lib.rs --- cargo-0.25.0/vendor/home-0.3.2/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/home-0.3.2/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,299 @@ +/// Canonical definitions of `home_dir`, `cargo_home`, and `rustup_home`. +/// +/// This provides the definition of `home_dir` used by Cargo and +/// rustup, as well functions to find the correct value of +/// `CARGO_HOME` and `RUSTUP_HOME`. +/// +/// The definition of `home_dir` provided by the standard library is +/// incorrect because it considers the `HOME` environment variable on +/// Windows. This causes surprising situations where a Rust program +/// will behave differently depending on whether it is run under a +/// Unix emulation environment like Cygwin or MinGW. Neither Cargo nor +/// rustup use the standard libraries definition - they use the +/// definition here. +/// +/// This crate further provides two functions, `cargo_home` and +/// `rustup_home`, which are the canonical way to determine the +/// location that Cargo and rustup store their data. +/// +/// See [rust-lang/rust#43321]. +/// +/// [rust-lang/rust#43321]: https://github.com/rust-lang/rust/issues/43321 + +#[cfg(windows)] +extern crate scopeguard; +#[cfg(windows)] +extern crate winapi; +#[cfg(windows)] +extern crate userenv; + +#[cfg(windows)] +use winapi::shared::minwindef::DWORD; +use std::path::{PathBuf, Path}; +use std::io; +use std::env; + +/// Returns the path of the current user's home directory if known. +/// +/// # Unix +/// +/// Returns the value of the 'HOME' environment variable if it is set +/// and not equal to the empty string. Otherwise, it tries to determine the +/// home directory by invoking the `getpwuid_r` function on the UID of the +/// current user. +/// +/// # Windows +/// +/// Returns the value of the 'USERPROFILE' environment variable if it +/// is set and not equal to the empty string. If both do not exist, +/// [`GetUserProfileDirectory`][msdn] is used to return the +/// appropriate path. +/// +/// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762280(v=vs.85).aspx +/// +/// # Examples +/// +/// ``` +/// use std::env; +/// +/// match env::home_dir() { +/// Some(path) => println!("{}", path.display()), +/// None => println!("Impossible to get your home dir!"), +/// } +/// ``` +pub fn home_dir() -> Option { + home_dir_() +} + +#[cfg(windows)] +fn home_dir_() -> Option { + use std::ptr; + use userenv::GetUserProfileDirectoryW; + use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER; + use winapi::um::errhandlingapi::GetLastError; + use winapi::um::handleapi::CloseHandle; + use winapi::um::processthreadsapi::{GetCurrentProcess, OpenProcessToken}; + use winapi::um::winnt::TOKEN_READ; + use scopeguard; + + ::std::env::var_os("USERPROFILE").map(PathBuf::from).or_else(|| unsafe { + let me = GetCurrentProcess(); + let mut token = ptr::null_mut(); + if OpenProcessToken(me, TOKEN_READ, &mut token) == 0 { + return None; + } + let _g = scopeguard::guard(token, |h| { let _ = CloseHandle(*h); }); + fill_utf16_buf(|buf, mut sz| { + match GetUserProfileDirectoryW(token, buf, &mut sz) { + 0 if GetLastError() != ERROR_INSUFFICIENT_BUFFER => 0, + 0 => sz, + _ => sz - 1, // sz includes the null terminator + } + }, os2path).ok() + }) +} + +#[cfg(windows)] +fn os2path(s: &[u16]) -> PathBuf { + use std::ffi::OsString; + use std::os::windows::ffi::OsStringExt; + PathBuf::from(OsString::from_wide(s)) +} + +#[cfg(windows)] +fn fill_utf16_buf(mut f1: F1, f2: F2) -> io::Result + where F1: FnMut(*mut u16, DWORD) -> DWORD, + F2: FnOnce(&[u16]) -> T +{ + use winapi::um::errhandlingapi::{GetLastError, SetLastError}; + use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER; + + // Start off with a stack buf but then spill over to the heap if we end up + // needing more space. + let mut stack_buf = [0u16; 512]; + let mut heap_buf = Vec::new(); + unsafe { + let mut n = stack_buf.len(); + loop { + let buf = if n <= stack_buf.len() { + &mut stack_buf[..] + } else { + let extra = n - heap_buf.len(); + heap_buf.reserve(extra); + heap_buf.set_len(n); + &mut heap_buf[..] + }; + + // This function is typically called on windows API functions which + // will return the correct length of the string, but these functions + // also return the `0` on error. In some cases, however, the + // returned "correct length" may actually be 0! + // + // To handle this case we call `SetLastError` to reset it to 0 and + // then check it again if we get the "0 error value". If the "last + // error" is still 0 then we interpret it as a 0 length buffer and + // not an actual error. + SetLastError(0); + let k = match f1(buf.as_mut_ptr(), n as DWORD) { + 0 if GetLastError() == 0 => 0, + 0 => return Err(io::Error::last_os_error()), + n => n, + } as usize; + if k == n && GetLastError() == ERROR_INSUFFICIENT_BUFFER { + n *= 2; + } else if k >= n { + n = k; + } else { + return Ok(f2(&buf[..k])) + } + } + } +} + +#[cfg(unix)] +fn home_dir_() -> Option { + ::std::env::home_dir() +} + +/// Returns the storage directory used by Cargo, often knowns as +/// `.cargo` or `CARGO_HOME`. +/// +/// It returns one of the following values, in this order of +/// preference: +/// +/// - The value of the `CARGO_HOME` environment variable, if it is +/// an absolute path. +/// - The value of the current working directory joined with the value +/// of the `CARGO_HOME` environment variable, if `CARGO_HOME` is a +/// relative directory. +/// - The `.cargo` directory in the user's home directory, as reported +/// by the `home_dir` function. +/// +/// # Errors +/// +/// This function fails if it fails to retrieve the current directory, +/// or if the home directory cannot be determined. +pub fn cargo_home() -> io::Result { + let cwd = env::current_dir()?; + cargo_home_with_cwd(&cwd) +} + +pub fn cargo_home_with_cwd(cwd: &Path) -> io::Result { + let env_var = env::var_os("CARGO_HOME"); + + // NB: During the multirust-rs -> rustup transition the install + // dir changed from ~/.multirust/bin to ~/.cargo/bin. Because + // multirust used to explicitly set CARGO_HOME it's possible to + // get here when e.g. installing under `cargo run` and decide to + // install to the wrong place. This check is to make the + // multirust-rs to rustup upgrade seamless. + let env_var = if let Some(v) = env_var { + let vv = v.to_string_lossy().to_string(); + if vv.contains(".multirust/cargo") || + vv.contains(r".multirust\cargo") || + vv.trim().is_empty() { + None + } else { + Some(v) + } + } else { + None + }; + + let env_cargo_home = env_var.map(|home| cwd.join(home)); + let home_dir = home_dir() + .ok_or(io::Error::new(io::ErrorKind::Other, "couldn't find home dir")); + let user_home = home_dir.map(|p| p.join(".cargo")); + + // Compatibility with old cargo that used the std definition of home_dir + let compat_home_dir = ::std::env::home_dir(); + let compat_user_home = compat_home_dir.map(|p| p.join(".cargo")); + + if let Some(p) = env_cargo_home { + Ok(p) + } else { + if let Some(d) = compat_user_home { + if d.exists() { + Ok(d) + } else { + user_home + } + } else { + user_home + } + } +} + +/// Returns the storage directory used by rustup, often knowns as +/// `.rustup` or `RUSTUP_HOME`. +/// +/// It returns one of the following values, in this order of +/// preference: +/// +/// - The value of the `RUSTUP_HOME` environment variable, if it is +/// an absolute path. +/// - The value of the current working directory joined with the value +/// of the `RUSTUP_HOME` environment variable, if `RUSTUP_HOME` is a +/// relative directory. +/// - The `.rustup` directory in the user's home directory, as reported +/// by the `home_dir` function. +/// +/// As a matter of backwards compatibility, this function _may_ return +/// the `.multirust` directory in the user's home directory, only if +/// it determines that the user is running an old version of rustup +/// where that is necessary. +/// +/// # Errors +/// +/// This function fails if it fails to retrieve the current directory, +/// or if the home directory cannot be determined. +pub fn rustup_home() -> io::Result { + let cwd = env::current_dir()?; + rustup_home_with_cwd(&cwd) +} + +pub fn rustup_home_with_cwd(cwd: &Path) -> io::Result { + let env_var = env::var_os("RUSTUP_HOME"); + let env_rustup_home = env_var.map(|home| cwd.join(home)); + let home_dir = home_dir() + .ok_or(io::Error::new(io::ErrorKind::Other, "couldn't find home dir")); + + let user_home = if use_rustup_dir() { + home_dir.map(|d| d.join(".rustup")) + } else { + home_dir.map(|d| d.join(".multirust")) + }; + + if let Some(p) = env_rustup_home { + Ok(p) + } else { + user_home + } +} + +fn use_rustup_dir() -> bool { + fn rustup_dir() -> Option { + home_dir().map(|p| p.join(".rustup")) + } + + fn multirust_dir() -> Option { + home_dir().map(|p| p.join(".multirust")) + } + + fn rustup_dir_exists() -> bool { + rustup_dir().map(|p| p.exists()).unwrap_or(false) + } + + fn multirust_dir_exists() -> bool { + multirust_dir().map(|p| p.exists()).unwrap_or(false) + } + + fn rustup_old_version_exists() -> bool { + rustup_dir() + .map(|p| p.join("rustup-version").exists()) + .unwrap_or(false) + } + + !rustup_old_version_exists() + && (rustup_dir_exists() || !multirust_dir_exists()) +} diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/benches/datetime_format.rs cargo-0.26.0/vendor/humantime-1.1.1/benches/datetime_format.rs --- cargo-0.25.0/vendor/humantime-1.1.1/benches/datetime_format.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/benches/datetime_format.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,58 @@ +#![feature(test)] +extern crate chrono; +extern crate humantime; +extern crate test; + +use std::io::Write; +use std::time::{Duration, UNIX_EPOCH}; +use humantime::format_rfc3339; + + +#[bench] +fn rfc3339_humantime_seconds(b: &mut test::Bencher) { + let time = UNIX_EPOCH + Duration::new(1483228799, 0); + let mut buf = Vec::with_capacity(100); + b.iter(|| { + buf.truncate(0); + write!(&mut buf, "{}", format_rfc3339(time)).unwrap() + }); +} + +#[bench] +fn rfc3339_chrono(b: &mut test::Bencher) { + use chrono::{DateTime, NaiveDateTime, Utc}; + use chrono::format::Item; + use chrono::format::Item::*; + use chrono::format::Numeric::*; + use chrono::format::Fixed::*; + use chrono::format::Pad::*; + + let time = DateTime::::from_utc( + NaiveDateTime::from_timestamp(1483228799, 0), Utc); + let mut buf = Vec::with_capacity(100); + + // formatting code from env_logger + const ITEMS: &'static [Item<'static>] = { + &[ + Numeric(Year, Zero), + Literal("-"), + Numeric(Month, Zero), + Literal("-"), + Numeric(Day, Zero), + Literal("T"), + Numeric(Hour, Zero), + Literal(":"), + Numeric(Minute, Zero), + Literal(":"), + Numeric(Second, Zero), + Fixed(TimezoneOffsetZ), + ] + }; + + + b.iter(|| { + buf.truncate(0); + write!(&mut buf, "{}", time.format_with_items(ITEMS.iter().cloned())) + .unwrap() + }); +} diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/benches/datetime_parse.rs cargo-0.26.0/vendor/humantime-1.1.1/benches/datetime_parse.rs --- cargo-0.25.0/vendor/humantime-1.1.1/benches/datetime_parse.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/benches/datetime_parse.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,50 @@ +#![feature(test)] +extern crate chrono; +extern crate humantime; +extern crate test; + +use chrono::{DateTime}; +use humantime::parse_rfc3339; + + +#[bench] +fn rfc3339_humantime_seconds(b: &mut test::Bencher) { + b.iter(|| { + parse_rfc3339("2018-02-13T23:08:32Z").unwrap() + }); +} + +#[bench] +fn datetime_utc_parse_seconds(b: &mut test::Bencher) { + b.iter(|| { + DateTime::parse_from_rfc3339("2018-02-13T23:08:32Z").unwrap() + }); +} + +#[bench] +fn rfc3339_humantime_millis(b: &mut test::Bencher) { + b.iter(|| { + parse_rfc3339("2018-02-13T23:08:32.123Z").unwrap() + }); +} + +#[bench] +fn datetime_utc_parse_millis(b: &mut test::Bencher) { + b.iter(|| { + DateTime::parse_from_rfc3339("2018-02-13T23:08:32.123Z").unwrap() + }); +} + +#[bench] +fn rfc3339_humantime_nanos(b: &mut test::Bencher) { + b.iter(|| { + parse_rfc3339("2018-02-13T23:08:32.123456983Z").unwrap() + }); +} + +#[bench] +fn datetime_utc_parse_nanos(b: &mut test::Bencher) { + b.iter(|| { + DateTime::parse_from_rfc3339("2018-02-13T23:08:32.123456983Z").unwrap() + }); +} diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/bulk.yaml cargo-0.26.0/vendor/humantime-1.1.1/bulk.yaml --- cargo-0.25.0/vendor/humantime-1.1.1/bulk.yaml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/bulk.yaml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,8 @@ +minimum-bulk: v0.4.5 + +versions: + +- file: Cargo.toml + block-start: ^\[package\] + block-end: ^\[.*\] + regex: ^version\s*=\s*"(\S+)" diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/.cargo-checksum.json cargo-0.26.0/vendor/humantime-1.1.1/.cargo-checksum.json --- cargo-0.25.0/vendor/humantime-1.1.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"0484fda3e7007f2a4a0d9c3a703ca38c71c54c55602ce4660c419fd32e188c9e"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/Cargo.toml cargo-0.26.0/vendor/humantime-1.1.1/Cargo.toml --- cargo-0.25.0/vendor/humantime-1.1.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,37 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "humantime" +version = "1.1.1" +authors = ["Paul Colomiets "] +description = " A parser and formatter for std::time::{Duration, SystemTime}\n" +homepage = "https://github.com/tailhook/humantime" +documentation = "https://docs.rs/humantime" +readme = "README.md" +keywords = ["time", "human", "human-friendly", "parser", "duration"] +categories = ["date-and-time"] +license = "MIT/Apache-2.0" + +[lib] +name = "humantime" +path = "src/lib.rs" +[dependencies.quick-error] +version = "1.0.0" +[dev-dependencies.chrono] +version = "0.4.0" + +[dev-dependencies.rand] +version = "0.4.2" + +[dev-dependencies.time] +version = "0.1.39" diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/LICENSE-APACHE cargo-0.26.0/vendor/humantime-1.1.1/LICENSE-APACHE --- cargo-0.25.0/vendor/humantime-1.1.1/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -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. + diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/LICENSE-MIT cargo-0.26.0/vendor/humantime-1.1.1/LICENSE-MIT --- cargo-0.25.0/vendor/humantime-1.1.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,26 @@ +Copyright (c) 2016 The humantime Developers + +Includes parts of http date with the following copyright: +Copyright (c) 2016 Pyfisch + +Includes portions of musl libc with the following copyright: +Copyright © 2005-2013 Rich Felker + + +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. diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/README.md cargo-0.26.0/vendor/humantime-1.1.1/README.md --- cargo-0.25.0/vendor/humantime-1.1.1/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,67 @@ +Human Time +========== + +**Status: stable** + +[Documentation](https://docs.rs/humantime) | +[Github](https://github.com/tailhook/humantime) | +[Crate](https://crates.io/crates/humantime) + + +Features: + +* Parses durations in free form like `15days 2min 2s` +* Formats durations in similar form `2years 2min 12us` +* Parses and formats timestamp in `rfc3339` format: `2018-01-01T12:53:00Z` +* Parses timestamps in a weaker format: `2018-01-01 12:53:00` + +Timestamp parsing/formatting is super-fast because format is basically +fixed. + +Here are some micro-benchmarks: + +``` +test result: ok. 0 passed; 0 failed; 26 ignored; 0 measured; 0 filtered out + + Running target/release/deps/datetime_format-8facb4ac832d9770 + +running 2 tests +test rfc3339_chrono ... bench: 737 ns/iter (+/- 37) +test rfc3339_humantime_seconds ... bench: 73 ns/iter (+/- 2) + +test result: ok. 0 passed; 0 failed; 0 ignored; 2 measured; 0 filtered out + + Running target/release/deps/datetime_parse-342628f877d7867c + +running 6 tests +test datetime_utc_parse_millis ... bench: 228 ns/iter (+/- 11) +test datetime_utc_parse_nanos ... bench: 236 ns/iter (+/- 10) +test datetime_utc_parse_seconds ... bench: 204 ns/iter (+/- 18) +test rfc3339_humantime_millis ... bench: 28 ns/iter (+/- 1) +test rfc3339_humantime_nanos ... bench: 36 ns/iter (+/- 2) +test rfc3339_humantime_seconds ... bench: 24 ns/iter (+/- 1) + +test result: ok. 0 passed; 0 failed; 0 ignored; 6 measured; 0 filtered out +``` + +See [serde-humantime] for serde integration. + +[serde-humantime]: https://docs.rs/serde-humantime/0.1.1/serde_humantime/ + +License +======= + +Licensed under either of + +* Apache License, Version 2.0, (./LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) +* MIT license (./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. diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/src/date.rs cargo-0.26.0/vendor/humantime-1.1.1/src/date.rs --- cargo-0.25.0/vendor/humantime-1.1.1/src/date.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/src/date.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,530 @@ +use std::fmt; +use std::str; +use std::time::{SystemTime, Duration, UNIX_EPOCH}; + +#[cfg(target_os="cloudabi")] +mod max { + pub const SECONDS: u64 = ::std::u64::MAX / 1_000_000_000; + #[allow(unused)] + pub const TIMESTAMP: &'static str = "2554-07-21T23:34:33Z"; +} +#[cfg(all( + target_pointer_width="32", + not(target_os="cloudabi"), + not(target_os="windows"), + not(all(target_arch="wasm32", not(target_os="emscripten"))) +))] +mod max { + pub const SECONDS: u64 = ::std::i32::MAX as u64; + #[allow(unused)] + pub const TIMESTAMP: &'static str = "2038-01-19T03:14:07Z"; +} + +#[cfg(any( + target_pointer_width="64", + target_os="windows", + all(target_arch="wasm32", not(target_os="emscripten")), +))] +mod max { + pub const SECONDS: u64 = 253402300800-1; // last second of year 9999 + #[allow(unused)] + pub const TIMESTAMP: &'static str = "9999-12-31T23:59:59Z"; +} + +quick_error! { + /// Error parsing datetime (timestamp) + #[derive(Debug, PartialEq, Clone, Copy)] + pub enum Error { + /// Numeric component is out of range + OutOfRange { + display("numeric component is out of range") + } + /// Bad character where digit is expected + InvalidDigit { + display("bad character where digit is expected") + } + /// Other formatting errors + InvalidFormat { + display("timestamp format is invalid") + } + } +} + +#[derive(Debug, PartialEq, Eq)] +enum Precision { + Smart, + Seconds, + Nanos, +} + +/// A wrapper type that allows you to Display a SystemTime +#[derive(Debug)] +pub struct Rfc3339Timestamp(SystemTime, Precision); + +#[inline] +fn two_digits(b1: u8, b2: u8) -> Result { + if b1 < b'0' || b2 < b'0' || b1 > b'9' || b2 > b'9' { + return Err(Error::InvalidDigit); + } + Ok(((b1 - b'0')*10 + (b2 - b'0')) as u64) +} + +/// Parse RFC3339 timestamp `2018-02-14T00:28:07Z` +/// +/// Supported feature: any precision of fractional +/// digits `2018-02-14T00:28:07.133Z`. +/// +/// Unsupported feature: localized timestamps. Only UTC is supported. +pub fn parse_rfc3339(s: &str) -> Result { + if s.len() < "2018-02-14T00:28:07Z".len() { + return Err(Error::InvalidFormat); + } + let b = s.as_bytes(); + if b[10] != b'T' || b[b.len()-1] != b'Z' { + return Err(Error::InvalidFormat); + } + return parse_rfc3339_weak(s); +} + +/// Parse RFC3339-like timestamp `2018-02-14 00:28:07` +/// +/// Supported features: +/// +/// 1. Any precision of fractional digits `2018-02-14 00:28:07.133`. +/// 2. Supports timestamp with or without either of `T` or `Z` +/// 3. Anything valid for `parse_3339` is valid for this function +/// +/// Unsupported feature: localized timestamps. Only UTC is supported, even if +/// `Z` is not specified. +/// +/// This function is intended to use for parsing human input. Whereas +/// `parse_rfc3339` is for strings generated programmatically. +pub fn parse_rfc3339_weak(s: &str) -> Result { + if s.len() < "2018-02-14T00:28:07".len() { + return Err(Error::InvalidFormat); + } + let b = s.as_bytes(); // for careless slicing + if b[4] != b'-' || b[7] != b'-' || (b[10] != b'T' && b[10] != b' ') || + b[13] != b':' || b[16] != b':' + { + return Err(Error::InvalidFormat); + } + let year = two_digits(b[0], b[1])? * 100 + two_digits(b[2], b[3])?; + let month = two_digits(b[5], b[6])?; + let day = two_digits(b[8], b[9])?; + let hour = two_digits(b[11], b[12])?; + let minute = two_digits(b[14], b[15])?; + let mut second = two_digits(b[17], b[18])?; + + if year < 1970 || hour > 23 || minute > 59 || second > 60 { + return Err(Error::OutOfRange); + } + // TODO(tailhook) should we check that leaps second is only on midnight ? + if second == 60 { + second = 59 + }; + let leap_years = ((year - 1) - 1968) / 4 - ((year - 1) - 1900) / 100 + + ((year - 1) - 1600) / 400; + let leap = is_leap_year(year); + let (mut ydays, mdays) = match month { + 1 => (0, 31), + 2 if leap => (31, 29), + 2 => (31, 28), + 3 => (59, 31), + 4 => (90, 30), + 5 => (120, 31), + 6 => (151, 30), + 7 => (181, 31), + 8 => (212, 31), + 9 => (243, 30), + 10 => (273, 31), + 11 => (304, 30), + 12 => (334, 31), + _ => return Err(Error::OutOfRange), + }; + if day > mdays || day == 0 { + return Err(Error::OutOfRange); + } + ydays += day - 1; + if leap && month > 2 { + ydays += 1; + } + let days = (year - 1970) * 365 + leap_years + ydays; + + let time = second + minute * 60 + hour * 3600; + + let mut nanos = 0; + let mut mult = 100_000_000; + if b.get(19) == Some(&b'.') { + for idx in 20..b.len() { + if b[idx] == b'Z' { + if idx == b.len()-1 { + break; + } else { + return Err(Error::InvalidDigit); + } + } + if b[idx] < b'0' || b[idx] > b'9' { + return Err(Error::InvalidDigit); + } + nanos += mult * (b[idx] - b'0') as u32; + mult /= 10; + } + } else { + if b.len() != 19 && (b.len() > 20 || b[19] != b'Z') { + return Err(Error::InvalidFormat); + } + } + + let total_seconds = time + days * 86400; + if total_seconds > max::SECONDS { + return Err(Error::OutOfRange); + } + + return Ok(UNIX_EPOCH + Duration::new(total_seconds, nanos)); +} + +fn is_leap_year(y: u64) -> bool { + y % 4 == 0 && (!(y % 100 == 0) || y % 400 == 0) +} + +/// Format an RFC3339 timestamp `2018-02-14T00:28:07Z` +/// +/// This function formats timestamp with smart precision: i.e. if it has no +/// fractional seconds, they aren't written at all. And up to nine digits if +/// they are. +/// +/// The value is always UTC and ignores system timezone. +pub fn format_rfc3339(system_time: SystemTime) -> Rfc3339Timestamp { + return Rfc3339Timestamp(system_time, Precision::Smart); +} + +/// Format an RFC3339 timestamp `2018-02-14T00:28:07Z` +/// +/// This format always shows timestamp without fractional seconds. +/// +/// The value is always UTC and ignores system timezone. +pub fn format_rfc3339_seconds(system_time: SystemTime) -> Rfc3339Timestamp { + return Rfc3339Timestamp(system_time, Precision::Seconds); +} + +/// Format an RFC3339 timestamp `2018-02-14T00:28:07.000000000Z` +/// +/// This format always shows nanoseconds even if nanosecond value is zero. +/// +/// The value is always UTC and ignores system timezone. +pub fn format_rfc3339_nanos(system_time: SystemTime) -> Rfc3339Timestamp { + return Rfc3339Timestamp(system_time, Precision::Nanos); +} + +impl fmt::Display for Rfc3339Timestamp { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Precision::*; + + let dur = self.0.duration_since(UNIX_EPOCH) + .expect("all times should be after the epoch"); + let secs_since_epoch = dur.as_secs(); + let nanos = dur.subsec_nanos(); + + if secs_since_epoch >= 253402300800 { // year 9999 + return Err(fmt::Error); + } + + /* 2000-03-01 (mod 400 year, immediately after feb29 */ + const LEAPOCH: i64 = 11017; + const DAYS_PER_400Y: i64 = 365*400 + 97; + const DAYS_PER_100Y: i64 = 365*100 + 24; + const DAYS_PER_4Y: i64 = 365*4 + 1; + + let days = (secs_since_epoch / 86400) as i64 - LEAPOCH; + let secs_of_day = secs_since_epoch % 86400; + + let mut qc_cycles = days / DAYS_PER_400Y; + let mut remdays = days % DAYS_PER_400Y; + + if remdays < 0 { + remdays += DAYS_PER_400Y; + qc_cycles -= 1; + } + + let mut c_cycles = remdays / DAYS_PER_100Y; + if c_cycles == 4 { c_cycles -= 1; } + remdays -= c_cycles * DAYS_PER_100Y; + + let mut q_cycles = remdays / DAYS_PER_4Y; + if q_cycles == 25 { q_cycles -= 1; } + remdays -= q_cycles * DAYS_PER_4Y; + + let mut remyears = remdays / 365; + if remyears == 4 { remyears -= 1; } + remdays -= remyears * 365; + + let mut year = 2000 + + remyears + 4*q_cycles + 100*c_cycles + 400*qc_cycles; + + let months = [31,30,31,30,31,31,30,31,30,31,31,29]; + let mut mon = 0; + for mon_len in months.iter() { + mon += 1; + if remdays < *mon_len { + break; + } + remdays -= *mon_len; + } + let mday = remdays+1; + let mon = if mon + 2 > 12 { + year += 1; + mon - 10 + } else { + mon + 2 + }; + + let mut buf: [u8; 30] = [ + // Too long to write as: b"0000-00-00T00:00:00.000000000Z" + b'0', b'0', b'0', b'0', b'-', b'0', b'0', b'-', b'0', b'0', b'T', + b'0', b'0', b':', b'0', b'0', b':', b'0', b'0', + b'.', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'0', b'Z', + ]; + buf[0] = b'0' + (year / 1000) as u8; + buf[1] = b'0' + (year / 100 % 10) as u8; + buf[2] = b'0' + (year / 10 % 10) as u8; + buf[3] = b'0' + (year % 10) as u8; + buf[5] = b'0' + (mon / 10) as u8; + buf[6] = b'0' + (mon % 10) as u8; + buf[8] = b'0' + (mday / 10) as u8; + buf[9] = b'0' + (mday % 10) as u8; + buf[11] = b'0' + (secs_of_day / 3600 / 10) as u8; + buf[12] = b'0' + (secs_of_day / 3600 % 10) as u8; + buf[14] = b'0' + (secs_of_day / 60 / 10 % 6) as u8; + buf[15] = b'0' + (secs_of_day / 60 % 10) as u8; + buf[17] = b'0' + (secs_of_day / 10 % 6) as u8; + buf[18] = b'0' + (secs_of_day % 10) as u8; + + if self.1 == Seconds || nanos == 0 && self.1 == Smart { + buf[19] = b'Z'; + f.write_str(unsafe { str::from_utf8_unchecked(&buf[..20]) }) + } else { + buf[20] = b'0' + (nanos / 100_000_000) as u8; + buf[21] = b'0' + (nanos / 10_000_000 % 10) as u8; + buf[22] = b'0' + (nanos / 1_000_000 % 10) as u8; + buf[23] = b'0' + (nanos / 100_000 % 10) as u8; + buf[24] = b'0' + (nanos / 10_000 % 10) as u8; + buf[25] = b'0' + (nanos / 1_000 % 10) as u8; + buf[26] = b'0' + (nanos / 100 % 10) as u8; + buf[27] = b'0' + (nanos / 10 % 10) as u8; + buf[28] = b'0' + (nanos / 1 % 10) as u8; + // we know our chars are all ascii + f.write_str(unsafe { str::from_utf8_unchecked(&buf[..]) }) + } + } +} + +#[cfg(test)] +mod test { + extern crate time; + extern crate rand; + + use std::str::from_utf8; + use self::rand::Rng; + use std::time::{UNIX_EPOCH, SystemTime, Duration}; + use super::{parse_rfc3339, parse_rfc3339_weak, format_rfc3339}; + use super::max; + + fn from_sec(sec: u64) -> (String, SystemTime) { + let s = time::at_utc(time::Timespec { sec: sec as i64, nsec: 0 }) + .rfc3339().to_string(); + let time = UNIX_EPOCH + Duration::new(sec, 0); + return (s, time) + } + + #[test] + #[cfg(all(target_pointer_width="32", target_os="linux"))] + fn year_after_2038_fails_gracefully() { + // next second + assert_eq!(parse_rfc3339("2038-01-19T03:14:08Z").unwrap_err(), + super::Error::OutOfRange); + assert_eq!(parse_rfc3339("9999-12-31T23:59:59Z").unwrap_err(), + super::Error::OutOfRange); + } + + #[test] + fn smoke_tests_parse() { + assert_eq!(parse_rfc3339("1970-01-01T00:00:00Z").unwrap(), + UNIX_EPOCH + Duration::new(0, 0)); + assert_eq!(parse_rfc3339("1970-01-01T00:00:01Z").unwrap(), + UNIX_EPOCH + Duration::new(1, 0)); + assert_eq!(parse_rfc3339("2018-02-13T23:08:32Z").unwrap(), + UNIX_EPOCH + Duration::new(1518563312, 0)); + assert_eq!(parse_rfc3339("2012-01-01T00:00:00Z").unwrap(), + UNIX_EPOCH + Duration::new(1325376000, 0)); + } + + #[test] + fn smoke_tests_format() { + assert_eq!( + format_rfc3339(UNIX_EPOCH + Duration::new(0, 0)).to_string(), + "1970-01-01T00:00:00Z"); + assert_eq!( + format_rfc3339(UNIX_EPOCH + Duration::new(1, 0)).to_string(), + "1970-01-01T00:00:01Z"); + assert_eq!( + format_rfc3339(UNIX_EPOCH + Duration::new(1518563312, 0)).to_string(), + "2018-02-13T23:08:32Z"); + assert_eq!( + format_rfc3339(UNIX_EPOCH + Duration::new(1325376000, 0)).to_string(), + "2012-01-01T00:00:00Z"); + } + + #[test] + fn upper_bound() { + let max = UNIX_EPOCH + Duration::new(max::SECONDS, 0); + assert_eq!(parse_rfc3339(&max::TIMESTAMP).unwrap(), max); + assert_eq!(format_rfc3339(max).to_string(), max::TIMESTAMP); + } + + #[test] + fn leap_second() { + assert_eq!(parse_rfc3339("2016-12-31T23:59:60Z").unwrap(), + UNIX_EPOCH + Duration::new(1483228799, 0)); + } + + #[test] + fn first_731_days() { + let year_start = 0; // 1970 + for day in 0.. (365 * 2 + 1) { // scan leap year and non-leap year + let (s, time) = from_sec(year_start + day * 86400); + assert_eq!(parse_rfc3339(&s).unwrap(), time); + assert_eq!(format_rfc3339(time).to_string(), s); + } + } + + #[test] + fn the_731_consecutive_days() { + let year_start = 1325376000; // 2012 + for day in 0.. (365 * 2 + 1) { // scan leap year and non-leap year + let (s, time) = from_sec(year_start + day * 86400); + assert_eq!(parse_rfc3339(&s).unwrap(), time); + assert_eq!(format_rfc3339(time).to_string(), s); + } + } + + #[test] + fn all_86400_seconds() { + let day_start = 1325376000; + for second in 0..86400 { // scan leap year and non-leap year + let (s, time) = from_sec(day_start + second); + assert_eq!(parse_rfc3339(&s).unwrap(), time); + assert_eq!(format_rfc3339(time).to_string(), s); + } + } + + #[test] + fn random_past() { + let upper = SystemTime::now().duration_since(UNIX_EPOCH).unwrap() + .as_secs(); + for _ in 0..10000 { + let sec = rand::thread_rng().gen_range(0, upper); + let (s, time) = from_sec(sec); + assert_eq!(parse_rfc3339(&s).unwrap(), time); + assert_eq!(format_rfc3339(time).to_string(), s); + } + } + + #[test] + fn random_wide_range() { + for _ in 0..100000 { + let sec = rand::thread_rng().gen_range(0, max::SECONDS); + let (s, time) = from_sec(sec); + assert_eq!(parse_rfc3339(&s).unwrap(), time); + assert_eq!(format_rfc3339(time).to_string(), s); + } + } + + #[test] + fn milliseconds() { + assert_eq!(parse_rfc3339("1970-01-01T00:00:00.123Z").unwrap(), + UNIX_EPOCH + Duration::new(0, 123000000)); + assert_eq!(format_rfc3339(UNIX_EPOCH + Duration::new(0, 123000000)) + .to_string(), "1970-01-01T00:00:00.123000000Z"); + } + + #[test] + #[should_panic(expected="OutOfRange")] + fn zero_month() { + parse_rfc3339("1970-00-01T00:00:00Z").unwrap(); + } + + #[test] + #[should_panic(expected="OutOfRange")] + fn big_month() { + parse_rfc3339("1970-32-01T00:00:00Z").unwrap(); + } + + #[test] + #[should_panic(expected="OutOfRange")] + fn zero_day() { + parse_rfc3339("1970-01-00T00:00:00Z").unwrap(); + } + + #[test] + #[should_panic(expected="OutOfRange")] + fn big_day() { + parse_rfc3339("1970-12-35T00:00:00Z").unwrap(); + } + + #[test] + #[should_panic(expected="OutOfRange")] + fn big_day2() { + parse_rfc3339("1970-02-30T00:00:00Z").unwrap(); + } + + #[test] + #[should_panic(expected="OutOfRange")] + fn big_second() { + parse_rfc3339("1970-12-30T00:00:78Z").unwrap(); + } + + #[test] + #[should_panic(expected="OutOfRange")] + fn big_minute() { + parse_rfc3339("1970-12-30T00:78:00Z").unwrap(); + } + + #[test] + #[should_panic(expected="OutOfRange")] + fn big_hour() { + parse_rfc3339("1970-12-30T24:00:00Z").unwrap(); + } + + #[test] + fn break_data() { + for pos in 0.."2016-12-31T23:59:60Z".len() { + let mut s = b"2016-12-31T23:59:60Z".to_vec(); + s[pos] = b'x'; + parse_rfc3339(from_utf8(&s).unwrap()).unwrap_err(); + } + } + + #[test] + fn weak_smoke_tests() { + assert_eq!(parse_rfc3339_weak("1970-01-01 00:00:00").unwrap(), + UNIX_EPOCH + Duration::new(0, 0)); + parse_rfc3339("1970-01-01 00:00:00").unwrap_err(); + + assert_eq!(parse_rfc3339_weak("1970-01-01 00:00:00.000123").unwrap(), + UNIX_EPOCH + Duration::new(0, 123000)); + parse_rfc3339("1970-01-01 00:00:00.000123").unwrap_err(); + + assert_eq!(parse_rfc3339_weak("1970-01-01T00:00:00.000123").unwrap(), + UNIX_EPOCH + Duration::new(0, 123000)); + parse_rfc3339("1970-01-01T00:00:00.000123").unwrap_err(); + + assert_eq!(parse_rfc3339_weak("1970-01-01 00:00:00.000123Z").unwrap(), + UNIX_EPOCH + Duration::new(0, 123000)); + parse_rfc3339("1970-01-01 00:00:00.000123Z").unwrap_err(); + + assert_eq!(parse_rfc3339_weak("1970-01-01 00:00:00Z").unwrap(), + UNIX_EPOCH + Duration::new(0, 0)); + parse_rfc3339("1970-01-01 00:00:00Z").unwrap_err(); + } +} diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/src/duration.rs cargo-0.26.0/vendor/humantime-1.1.1/src/duration.rs --- cargo-0.25.0/vendor/humantime-1.1.1/src/duration.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/src/duration.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,411 @@ +use std::fmt; +use std::str::Chars; +use std::time::Duration; +use std::error::Error as StdError; + +quick_error! { + /// Error parsing human-friendly duration + #[derive(Debug, PartialEq, Clone, Copy)] + pub enum Error { + /// Invalid character during parsing + /// + /// More specifically anything that is not alphanumeric is prohibited + /// + /// The field is an byte offset of the character in the string. + InvalidCharacter(offset: usize) { + display("invalid character at {}", offset) + description("invalid character") + } + /// Non-numeric value where number is expected + /// + /// This usually means that either time unit is broken into words, + /// e.g. `m sec` instead of `msec`, or just number is omitted, + /// for example `2 hours min` instead of `2 hours 1 min` + /// + /// The field is an byte offset of the errorneous character + /// in the string. + NumberExpected(offset: usize) { + display("expected number at {}", offset) + description("expected number") + } + /// Unit in the number is not one of allowed units + /// + /// See documentation of `parse_duration` for the list of supported + /// time units. + /// + /// The two fields are start and end (exclusive) of the slice from + /// the original string, containing errorneous value + UnknownUnit(start: usize, end: usize) { + display("unknown unit at {}-{}", start, end) + description("unknown unit") + } + /// The numeric value is too large + /// + /// Usually this means value is too large to be useful. If user writes + /// data in subsecond units, then the maximum is about 3k years. When + /// using seconds, or larger units, the limit is even larger. + NumberOverflow { + display(self_) -> ("{}", self_.description()) + description("number is too large") + } + /// The value was an empty string (or consists only whitespace) + Empty { + display(self_) -> ("{}", self_.description()) + description("value was empty") + } + } + +} + +/// A wrapper type that allows you to Display a Duration +#[derive(Debug)] +pub struct FormattedDuration(Duration); + +trait OverflowOp: Sized { + fn mul(self, other: Self) -> Result; + fn add(self, other: Self) -> Result; +} + +impl OverflowOp for u64 { + fn mul(self, other: Self) -> Result { + self.checked_mul(other).ok_or(Error::NumberOverflow) + } + fn add(self, other: Self) -> Result { + self.checked_add(other).ok_or(Error::NumberOverflow) + } +} + +struct Parser<'a> { + iter: Chars<'a>, + src: &'a str, + current: (u64, u64), +} + +impl<'a> Parser<'a> { + fn off(&self) -> usize { + self.src.len() - self.iter.as_str().len() + } + + fn parse_first_char(&mut self) -> Result, Error> { + let off = self.off(); + for c in self.iter.by_ref() { + match c { + '0'...'9' => { + return Ok(Some(c as u64 - '0' as u64)); + } + c if c.is_whitespace() => continue, + _ => { + return Err(Error::NumberExpected(off)); + } + } + } + return Ok(None); + } + fn parse_unit(&mut self, n: u64, start: usize, end: usize) + -> Result<(), Error> + { + let (mut sec, nsec) = match &self.src[start..end] { + "nanos" | "nsec" | "ns" => (0u64, n), + "usec" | "us" => (0u64, try!(n.mul(1000))), + "millis" | "msec" | "ms" => (0u64, try!(n.mul(1000_000))), + "seconds" | "second" | "secs" | "sec" | "s" => (n, 0), + "minutes" | "minute" | "min" | "mins" | "m" + => (try!(n.mul(60)), 0), + "hours" | "hour" | "hr" | "hrs" | "h" => (try!(n.mul(3600)), 0), + "days" | "day" | "d" => (try!(n.mul(86400)), 0), + "weeks" | "week" | "w" => (try!(n.mul(86400*7)), 0), + "months" | "month" | "M" => (try!(n.mul(2630016)), 0), // 30.44d + "years" | "year" | "y" => (try!(n.mul(31557600)), 0), // 365.25d + _ => return Err(Error::UnknownUnit(start, end)), + }; + let mut nsec = try!(self.current.1.add(nsec)); + if nsec > 1000_000_000 { + sec = try!(sec.add(nsec / 1000_000_000)); + nsec %= 1000_000_000; + } + sec = try!(self.current.0.add(sec)); + self.current = (sec, nsec); + Ok(()) + } + + fn parse(mut self) -> Result { + let mut n = try!(try!(self.parse_first_char()).ok_or(Error::Empty)); + 'outer: loop { + let mut off = self.off(); + while let Some(c) = self.iter.next() { + match c { + '0'...'9' => { + n = try!(n.checked_mul(10) + .and_then(|x| x.checked_add(c as u64 - '0' as u64)) + .ok_or(Error::NumberOverflow)); + } + c if c.is_whitespace() => {} + 'a'...'z' | 'A'...'Z' => { + break; + } + _ => { + return Err(Error::InvalidCharacter(off)); + } + } + off = self.off(); + } + let start = off; + let mut off = self.off(); + while let Some(c) = self.iter.next() { + match c { + '0'...'9' => { + try!(self.parse_unit(n, start, off)); + n = c as u64 - '0' as u64; + continue 'outer; + } + c if c.is_whitespace() => break, + 'a'...'z' | 'A'...'Z' => {} + _ => { + return Err(Error::InvalidCharacter(off)); + } + } + off = self.off(); + } + try!(self.parse_unit(n, start, off)); + n = match try!(self.parse_first_char()) { + Some(n) => n, + None => return Ok( + Duration::new(self.current.0, self.current.1 as u32)), + }; + } + } + +} + +/// Parse duration object `1hour 12min 5s` +/// +/// The duration object is a concatenation of time spans. Where each time +/// span is an integer number and a suffix. Supported suffixes: +/// +/// * `nsec`, `ns` -- microseconds +/// * `usec`, `us` -- microseconds +/// * `msec`, `ms` -- milliseconds +/// * `seconds`, `second`, `sec`, `s` +/// * `minutes`, `minute`, `min`, `m` +/// * `hours`, `hour`, `hr`, `h` +/// * `days`, `day`, `d` +/// * `weeks`, `week`, `w` +/// * `months`, `month`, `M` -- defined as 30.44 days +/// * `years`, `year`, `y` -- defined as 365.25 days +/// +/// # Examples +/// +/// ``` +/// use std::time::Duration; +/// use humantime::parse_duration; +/// +/// assert_eq!(parse_duration("2h 37min"), Ok(Duration::new(9420, 0))); +/// assert_eq!(parse_duration("32ms"), Ok(Duration::new(0, 32_000_000))); +/// ``` +pub fn parse_duration(s: &str) -> Result { + Parser { + iter: s.chars(), + src: s, + current: (0, 0), + }.parse() +} + +/// Formats duration into a human-readable string +/// +/// Note: this format is guaranteed to have same value when using +/// parse_duration, but we can change some details of the exact composition +/// of the value. +/// +/// # Examples +/// +/// ``` +/// use std::time::Duration; +/// use humantime::format_duration; +/// +/// let val1 = Duration::new(9420, 0); +/// assert_eq!(format_duration(val1).to_string(), "2h 37m"); +/// let val2 = Duration::new(0, 32_000_000); +/// assert_eq!(format_duration(val2).to_string(), "32ms"); +/// ``` +pub fn format_duration(val: Duration) -> FormattedDuration { + FormattedDuration(val) +} + +fn item_plural(f: &mut fmt::Formatter, started: &mut bool, + name: &str, value: u64) + -> fmt::Result +{ + if value > 0 { + if *started { + f.write_str(" ")?; + } + write!(f, "{}{}", value, name)?; + if value > 1 { + f.write_str("s")?; + } + *started = true; + } + Ok(()) +} +fn item(f: &mut fmt::Formatter, started: &mut bool, name: &str, value: u32) + -> fmt::Result +{ + if value > 0 { + if *started { + f.write_str(" ")?; + } + write!(f, "{}{}", value, name)?; + *started = true; + } + Ok(()) +} + +impl fmt::Display for FormattedDuration { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let secs = self.0.as_secs(); + let nanos = self.0.subsec_nanos(); + + if secs == 0 && nanos == 0 { + f.write_str("0s")?; + return Ok(()); + } + + let years = secs / 31557600; // 365.25d + let ydays = secs % 31557600; + let months = ydays / 2630016; // 30.44d + let mdays = ydays % 2630016; + let days = mdays / 86400; + let day_secs = mdays % 86400; + let hours = day_secs / 3600; + let minutes = day_secs % 3600 / 60; + let seconds = day_secs % 60; + + let millis = nanos / 1_000_000; + let micros = nanos / 1000 % 1000; + let nanosec = nanos % 1000; + + let ref mut started = false; + item_plural(f, started, "year", years)?; + item_plural(f, started, "month", months)?; + item_plural(f, started, "day", days)?; + item(f, started, "h", hours as u32)?; + item(f, started, "m", minutes as u32)?; + item(f, started, "s", seconds as u32)?; + item(f, started, "ms", millis)?; + item(f, started, "us", micros)?; + item(f, started, "ns", nanosec)?; + Ok(()) + } +} + +#[cfg(test)] +mod test { + extern crate rand; + + use std::time::Duration; + use self::rand::Rng; + use super::{parse_duration, format_duration}; + use super::Error; + + #[test] + fn test_units() { + assert_eq!(parse_duration("17nsec"), Ok(Duration::new(0, 17))); + assert_eq!(parse_duration("17nanos"), Ok(Duration::new(0, 17))); + assert_eq!(parse_duration("33ns"), Ok(Duration::new(0, 33))); + assert_eq!(parse_duration("3usec"), Ok(Duration::new(0, 3000))); + assert_eq!(parse_duration("78us"), Ok(Duration::new(0, 78000))); + assert_eq!(parse_duration("31msec"), Ok(Duration::new(0, 31000000))); + assert_eq!(parse_duration("31millis"), Ok(Duration::new(0, 31000000))); + assert_eq!(parse_duration("6ms"), Ok(Duration::new(0, 6000000))); + assert_eq!(parse_duration("3000s"), Ok(Duration::new(3000, 0))); + assert_eq!(parse_duration("300sec"), Ok(Duration::new(300, 0))); + assert_eq!(parse_duration("300secs"), Ok(Duration::new(300, 0))); + assert_eq!(parse_duration("50seconds"), Ok(Duration::new(50, 0))); + assert_eq!(parse_duration("1second"), Ok(Duration::new(1, 0))); + assert_eq!(parse_duration("100m"), Ok(Duration::new(6000, 0))); + assert_eq!(parse_duration("12min"), Ok(Duration::new(720, 0))); + assert_eq!(parse_duration("12mins"), Ok(Duration::new(720, 0))); + assert_eq!(parse_duration("1minute"), Ok(Duration::new(60, 0))); + assert_eq!(parse_duration("7minutes"), Ok(Duration::new(420, 0))); + assert_eq!(parse_duration("2h"), Ok(Duration::new(7200, 0))); + assert_eq!(parse_duration("7hr"), Ok(Duration::new(25200, 0))); + assert_eq!(parse_duration("7hrs"), Ok(Duration::new(25200, 0))); + assert_eq!(parse_duration("1hour"), Ok(Duration::new(3600, 0))); + assert_eq!(parse_duration("24hours"), Ok(Duration::new(86400, 0))); + assert_eq!(parse_duration("1day"), Ok(Duration::new(86400, 0))); + assert_eq!(parse_duration("2days"), Ok(Duration::new(172800, 0))); + assert_eq!(parse_duration("365d"), Ok(Duration::new(31536000, 0))); + assert_eq!(parse_duration("1week"), Ok(Duration::new(604800, 0))); + assert_eq!(parse_duration("7weeks"), Ok(Duration::new(4233600, 0))); + assert_eq!(parse_duration("52w"), Ok(Duration::new(31449600, 0))); + assert_eq!(parse_duration("1month"), Ok(Duration::new(2630016, 0))); + assert_eq!(parse_duration("3months"), Ok(Duration::new(3*2630016, 0))); + assert_eq!(parse_duration("12M"), Ok(Duration::new(31560192, 0))); + assert_eq!(parse_duration("1year"), Ok(Duration::new(31557600, 0))); + assert_eq!(parse_duration("7years"), Ok(Duration::new(7*31557600, 0))); + assert_eq!(parse_duration("17y"), Ok(Duration::new(536479200, 0))); + } + + #[test] + fn test_combo() { + assert_eq!(parse_duration("20 min 17 nsec "), Ok(Duration::new(1200, 17))); + assert_eq!(parse_duration("2h 15m"), Ok(Duration::new(8100, 0))); + } + + #[test] + fn all_86400_seconds() { + for second in 0..86400 { // scan leap year and non-leap year + let d = Duration::new(second, 0); + assert_eq!(d, + parse_duration(&format_duration(d).to_string()).unwrap()); + } + } + + #[test] + fn random_second() { + for _ in 0..10000 { + let sec = rand::thread_rng().gen_range(0, 253370764800); + let d = Duration::new(sec, 0); + assert_eq!(d, + parse_duration(&format_duration(d).to_string()).unwrap()); + } + } + + #[test] + fn random_any() { + for _ in 0..10000 { + let sec = rand::thread_rng().gen_range(0, 253370764800); + let nanos = rand::thread_rng().gen_range(0, 1_000_000_000); + let d = Duration::new(sec, nanos); + assert_eq!(d, + parse_duration(&format_duration(d).to_string()).unwrap()); + } + } + + #[test] + fn test_overlow() { + // Overflow on subseconds is earlier because of how we do conversion + // we could fix it, but I don't see any good reason for this + assert_eq!(parse_duration("100000000000000000000ns"), + Err(Error::NumberOverflow)); + assert_eq!(parse_duration("100000000000000000us"), + Err(Error::NumberOverflow)); + assert_eq!(parse_duration("100000000000000ms"), + Err(Error::NumberOverflow)); + + assert_eq!(parse_duration("100000000000000000000s"), + Err(Error::NumberOverflow)); + assert_eq!(parse_duration("10000000000000000000m"), + Err(Error::NumberOverflow)); + assert_eq!(parse_duration("1000000000000000000h"), + Err(Error::NumberOverflow)); + assert_eq!(parse_duration("100000000000000000d"), + Err(Error::NumberOverflow)); + assert_eq!(parse_duration("10000000000000000w"), + Err(Error::NumberOverflow)); + assert_eq!(parse_duration("1000000000000000M"), + Err(Error::NumberOverflow)); + assert_eq!(parse_duration("10000000000000y"), + Err(Error::NumberOverflow)); + } +} diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/src/lib.rs cargo-0.26.0/vendor/humantime-1.1.1/src/lib.rs --- cargo-0.25.0/vendor/humantime-1.1.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,30 @@ +//! Human-friendly time parser and formatter +//! +//! Features: +//! +//! * Parses durations in free form like `15days 2min 2s` +//! * Formats durations in similar form `2years 2min 12us` +//! * Parses and formats timestamp in `rfc3339` format: `2018-01-01T12:53:00Z` +//! * Parses timestamps in a weaker format: `2018-01-01 12:53:00` +//! +//! Timestamp parsing/formatting is super-fast because format is basically +//! fixed. +//! +//! See [serde-humantime] for serde integration. +//! +//! [serde-humantime]: https://docs.rs/serde-humantime/0.1.1/serde_humantime/ +#![warn(missing_debug_implementations)] +#![warn(missing_docs)] + +#[macro_use] extern crate quick_error; + +mod duration; +mod wrapper; +mod date; + +pub use duration::{parse_duration, Error as DurationError}; +pub use duration::{format_duration, FormattedDuration}; +pub use wrapper::{Duration, Timestamp}; +pub use date::{parse_rfc3339, parse_rfc3339_weak, Error as TimestampError}; +pub use date::{format_rfc3339, format_rfc3339_seconds, format_rfc3339_nanos}; +pub use date::{Rfc3339Timestamp}; diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/src/wrapper.rs cargo-0.26.0/vendor/humantime-1.1.1/src/wrapper.rs --- cargo-0.25.0/vendor/humantime-1.1.1/src/wrapper.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/src/wrapper.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,107 @@ +use std::str::FromStr; +use std::ops::Deref; +use std::fmt; +use std::time::{Duration as StdDuration, SystemTime}; + +use duration::{self, parse_duration, format_duration}; +use date::{self, parse_rfc3339_weak, format_rfc3339}; + +/// A wrapper for duration that has `FromStr` implementation +/// +/// This is useful if you want to use it somewhere where `FromStr` is +/// expected. +/// +/// See `parse_duration` for the description of the format. +/// +/// # Example +/// +/// ``` +/// use std::time::Duration; +/// let x: Duration; +/// x = "12h 5min 2ns".parse::().unwrap().into(); +/// assert_eq!(x, Duration::new(12*3600 + 5*60, 2)) +/// ``` +/// +#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)] +pub struct Duration(StdDuration); + +/// A wrapper for SystemTime that has `FromStr` implementation +/// +/// This is useful if you want to use it somewhere where `FromStr` is +/// expected. +/// +/// See `parse_rfc3339_weak` for the description of the format. The "weak" +/// format is used as it's more pemissive for human input as this is the +/// expected use of the type (e.g. command-line parsing). +/// +/// # Example +/// +/// ``` +/// use std::time::SystemTime; +/// let x: SystemTime; +/// x = "2018-02-16T00:31:37Z".parse::().unwrap().into(); +/// assert_eq!(humantime::format_rfc3339(x).to_string(), "2018-02-16T00:31:37Z"); +/// ``` +/// +#[derive(Debug, PartialEq, Eq, Clone)] +pub struct Timestamp(SystemTime); + +impl AsRef for Duration { + fn as_ref(&self) -> &StdDuration { &self.0 } +} + +impl Deref for Duration { + type Target = StdDuration; + fn deref(&self) -> &StdDuration { &self.0 } +} + +impl Into for Duration { + fn into(self) -> StdDuration { self.0 } +} + +impl From for Duration { + fn from(dur: StdDuration) -> Duration { Duration(dur) } +} + +impl FromStr for Duration { + type Err = duration::Error; + fn from_str(s: &str) -> Result { + parse_duration(s).map(Duration) + } +} + +impl fmt::Display for Duration { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + format_duration(self.0).fmt(f) + } +} + +impl AsRef for Timestamp { + fn as_ref(&self) -> &SystemTime { &self.0 } +} + +impl Deref for Timestamp { + type Target = SystemTime; + fn deref(&self) -> &SystemTime { &self.0 } +} + +impl Into for Timestamp { + fn into(self) -> SystemTime { self.0 } +} + +impl From for Timestamp { + fn from(dur: SystemTime) -> Timestamp { Timestamp(dur) } +} + +impl FromStr for Timestamp { + type Err = date::Error; + fn from_str(s: &str) -> Result { + parse_rfc3339_weak(s).map(Timestamp) + } +} + +impl fmt::Display for Timestamp { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + format_rfc3339(self.0).fmt(f) + } +} diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/.travis.yml cargo-0.26.0/vendor/humantime-1.1.1/.travis.yml --- cargo-0.25.0/vendor/humantime-1.1.1/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,36 @@ +sudo: false +dist: trusty +language: rust + +cache: +- cargo + +before_cache: +- rm -r $TRAVIS_BUILD_DIR/target/debug + +jobs: + include: + - os: linux + rust: 1.18.0 + - os: linux + rust: stable + - os: linux + rust: beta + - os: linux + rust: nightly + + # deploy + - stage: publish + os: linux + rust: stable + env: + # CARGO_TOKEN + - secure: "OLR1+9BgqV6eQB2el9rJAGyN1blKH77RcqMWZc1UAtBoT9/iiWCrsEVbD78Qgvei37QCqoa9f4BaQ20Eo4gaodo2f7NoqAYubxRoCNnDN1Mn7GA66YcPTwajhI41KEGXI2lE35zcNbCuJR9cSax2Lb+Gu6Et0tIhT5Vi2Rem5g7Id/v/sqD6FRpP/oTMKT1YcZTt81lvRPsOJHjImDKYWwTcxDmK6/FPPqrLVnXRdZeArAIgfE37KAZQPjrySC1JxESdQ0OhSkg84lC1mxFk83w4MFIY14Pi59tzN5ukI1nhNNIuvkjErKI+/rpp7obJ1do9/pesh2kVeiaR2XXdB4T6SR+oJo3VAfe+LmmBjBLTUXHM7Iwg6vc8Xors7HCsgyvxY0S0ppjwh/PQa9yjx5eKRw2tB26HjCS/pom8ffTyjTh1//+4rVvMs/qp3cpfYyYVLGaGNRMtXCsYdiURCAZwTtKKbk9P4dWHX9ceVpi/Ikbqu0C18FueerBEbAc+Rum2bhEkf0smUC4LTPXQgsb2l2DDCFnTAvfeGz+7rJ26g7UAG+ua4KDeVU+R3VUUNjBwU5GeWy08/bEQz64KX+pTcRxEpxWVs55CeOQPTVEjoyhUvK0BYvRCovri+3YSqznf4Vm42QluJ6H90uyQTmfI030fQLnabmZn4M9Um+U=" + install: true + script: true + + deploy: + - provider: script + script: 'cargo publish --verbose --token=$CARGO_TOKEN' + on: + tags: true diff -Nru cargo-0.25.0/vendor/humantime-1.1.1/vagga.yaml cargo-0.26.0/vendor/humantime-1.1.1/vagga.yaml --- cargo-0.25.0/vendor/humantime-1.1.1/vagga.yaml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/humantime-1.1.1/vagga.yaml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,92 @@ +commands: + + cargo: !Command + description: Run any cargo command + container: ubuntu + run: [cargo] + + make: !Command + description: Build the library + container: ubuntu + run: [cargo, build] + + test64: !Command + description: Test the 64bit library + container: ubuntu + environ: { RUST_BACKTRACE: 1 } + run: [cargo, test] + + test32: !Command + description: Test the 32bit library + container: ubuntu32 + environ: { RUST_BACKTRACE: 1 } + run: [cargo, test] + + test: !Command + description: Test the 64bit library + container: ubuntu + environ: { RUST_BACKTRACE: 1 } + prerequisites: [test64, test32] + run: [echo, okay] + + bench: !Command + description: Run benchmarks + container: bench + environ: { RUST_BACKTRACE: 1 } + run: [cargo, bench] + + _bulk: !Command + description: Run `bulk` command (for version bookkeeping) + container: ubuntu + run: [bulk] + +containers: + + ubuntu: + setup: + - !Ubuntu xenial + - !UbuntuUniverse + - !Install [ca-certificates, build-essential, vim] + + - !TarInstall + url: "https://static.rust-lang.org/dist/rust-1.24.0-x86_64-unknown-linux-gnu.tar.gz" + script: "./install.sh --prefix=/usr \ + --components=rustc,rust-std-x86_64-unknown-linux-gnu,cargo" + - &bulk !Tar + url: "https://github.com/tailhook/bulk/releases/download/v0.4.10/bulk-v0.4.10.tar.gz" + sha256: 481513f8a0306a9857d045497fb5b50b50a51e9ff748909ecf7d2bda1de275ab + path: / + + environ: + HOME: /work/target + USER: pc + + ubuntu32: + setup: + - !UbuntuRelease + codename: xenial + arch: i386 + - !UbuntuUniverse + - !Install [ca-certificates, build-essential, vim] + + - !TarInstall + url: "https://static.rust-lang.org/dist/rust-1.24.0-i686-unknown-linux-gnu.tar.gz" + script: "./install.sh --prefix=/usr \ + --components=rustc,rust-std-i686-unknown-linux-gnu,cargo" + + environ: + HOME: /work/target + USER: pc + + bench: + setup: + - !Ubuntu xenial + - !Install [ca-certificates, wget, build-essential] + - !TarInstall + url: https://static.rust-lang.org/dist/rust-nightly-x86_64-unknown-linux-gnu.tar.gz + script: | + ./install.sh --prefix=/usr \ + --components=rustc,rust-std-x86_64-unknown-linux-gnu,cargo + environ: + HOME: /work/target + USER: pc diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/.cargo-checksum.json cargo-0.26.0/vendor/ignore-0.2.2/.cargo-checksum.json --- cargo-0.25.0/vendor/ignore-0.2.2/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"b3fcaf2365eb14b28ec7603c98c06cc531f19de9eb283d89a3dff8417c8c99f5"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/Cargo.toml cargo-0.26.0/vendor/ignore-0.2.2/Cargo.toml --- cargo-0.25.0/vendor/ignore-0.2.2/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,57 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "ignore" -version = "0.2.2" -authors = ["Andrew Gallant "] -description = "A fast library for efficiently matching ignore files such as `.gitignore`\nagainst file paths.\n" -homepage = "https://github.com/BurntSushi/ripgrep/tree/master/ignore" -documentation = "https://docs.rs/ignore" -readme = "README.md" -keywords = ["glob", "ignore", "gitignore", "pattern", "file"] -license = "Unlicense/MIT" -repository = "https://github.com/BurntSushi/ripgrep/tree/master/ignore" -[profile.release] -debug = true - -[lib] -name = "ignore" -bench = false -[dependencies.memchr] -version = "1" - -[dependencies.walkdir] -version = "1.0.7" - -[dependencies.crossbeam] -version = "0.2" - -[dependencies.log] -version = "0.3" - -[dependencies.regex] -version = "0.2.1" - -[dependencies.thread_local] -version = "0.3.2" - -[dependencies.globset] -version = "0.2.0" - -[dependencies.lazy_static] -version = "0.2" -[dev-dependencies.tempdir] -version = "0.3.5" - -[features] -simd-accel = ["globset/simd-accel"] diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/COPYING cargo-0.26.0/vendor/ignore-0.2.2/COPYING --- cargo-0.25.0/vendor/ignore-0.2.2/COPYING 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/COPYING 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -This project is dual-licensed under the Unlicense and MIT licenses. - -You may use this code under the terms of either license. diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/examples/walk.rs cargo-0.26.0/vendor/ignore-0.2.2/examples/walk.rs --- cargo-0.25.0/vendor/ignore-0.2.2/examples/walk.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/examples/walk.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,92 +0,0 @@ -#![allow(dead_code, unused_imports, unused_mut, unused_variables)] - -extern crate crossbeam; -extern crate ignore; -extern crate walkdir; - -use std::env; -use std::io::{self, Write}; -use std::path::Path; -use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::thread; - -use crossbeam::sync::MsQueue; -use ignore::WalkBuilder; -use walkdir::WalkDir; - -fn main() { - let mut path = env::args().nth(1).unwrap(); - let mut parallel = false; - let mut simple = false; - let queue: Arc>> = Arc::new(MsQueue::new()); - if path == "parallel" { - path = env::args().nth(2).unwrap(); - parallel = true; - } else if path == "walkdir" { - path = env::args().nth(2).unwrap(); - simple = true; - } - - let stdout_queue = queue.clone(); - let stdout_thread = thread::spawn(move || { - let mut stdout = io::BufWriter::new(io::stdout()); - while let Some(dent) = stdout_queue.pop() { - write_path(&mut stdout, dent.path()); - } - }); - - if parallel { - let walker = WalkBuilder::new(path).threads(6).build_parallel(); - walker.run(|| { - let queue = queue.clone(); - Box::new(move |result| { - use ignore::WalkState::*; - - queue.push(Some(DirEntry::Y(result.unwrap()))); - Continue - }) - }); - } else if simple { - let mut stdout = io::BufWriter::new(io::stdout()); - let walker = WalkDir::new(path); - for result in walker { - queue.push(Some(DirEntry::X(result.unwrap()))); - } - } else { - let mut stdout = io::BufWriter::new(io::stdout()); - let walker = WalkBuilder::new(path).build(); - for result in walker { - queue.push(Some(DirEntry::Y(result.unwrap()))); - } - } - queue.push(None); - stdout_thread.join().unwrap(); -} - -enum DirEntry { - X(walkdir::DirEntry), - Y(ignore::DirEntry), -} - -impl DirEntry { - fn path(&self) -> &Path { - match *self { - DirEntry::X(ref x) => x.path(), - DirEntry::Y(ref y) => y.path(), - } - } -} - -#[cfg(unix)] -fn write_path(mut wtr: W, path: &Path) { - use std::os::unix::ffi::OsStrExt; - wtr.write(path.as_os_str().as_bytes()).unwrap(); - wtr.write(b"\n").unwrap(); -} - -#[cfg(not(unix))] -fn write_path(mut wtr: W, path: &Path) { - wtr.write(path.to_string_lossy().as_bytes()).unwrap(); - wtr.write(b"\n").unwrap(); -} diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/LICENSE-MIT cargo-0.26.0/vendor/ignore-0.2.2/LICENSE-MIT --- cargo-0.25.0/vendor/ignore-0.2.2/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Andrew Gallant - -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. diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/README.md cargo-0.26.0/vendor/ignore-0.2.2/README.md --- cargo-0.25.0/vendor/ignore-0.2.2/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,66 +0,0 @@ -ignore -====== -The ignore crate provides a fast recursive directory iterator that respects -various filters such as globs, file types and `.gitignore` files. This crate -also provides lower level direct access to gitignore and file type matchers. - -[![Linux build status](https://api.travis-ci.org/BurntSushi/ripgrep.png)](https://travis-ci.org/BurntSushi/ripgrep) -[![Windows build status](https://ci.appveyor.com/api/projects/status/github/BurntSushi/ripgrep?svg=true)](https://ci.appveyor.com/project/BurntSushi/ripgrep) -[![](https://img.shields.io/crates/v/ignore.svg)](https://crates.io/crates/ignore) - -Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). - -### Documentation - -[https://docs.rs/ignore](https://docs.rs/ignore) - -### Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -ignore = "0.2" -``` - -and this to your crate root: - -```rust -extern crate ignore; -``` - -### Example - -This example shows the most basic usage of this crate. This code will -recursively traverse the current directory while automatically filtering out -files and directories according to ignore globs found in files like -`.ignore` and `.gitignore`: - - -```rust,no_run -use ignore::Walk; - -for result in Walk::new("./") { - // Each item yielded by the iterator is either a directory entry or an - // error, so either print the path or the error. - match result { - Ok(entry) => println!("{}", entry.path().display()), - Err(err) => println!("ERROR: {}", err), - } -} -``` - -### Example: advanced - -By default, the recursive directory iterator will ignore hidden files and -directories. This can be disabled by building the iterator with `WalkBuilder`: - -```rust,no_run -use ignore::WalkBuilder; - -for result in WalkBuilder::new("./").hidden(false).build() { - println!("{:?}", result); -} -``` - -See the documentation for `WalkBuilder` for many other options. diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/src/dir.rs cargo-0.26.0/vendor/ignore-0.2.2/src/dir.rs --- cargo-0.25.0/vendor/ignore-0.2.2/src/dir.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/src/dir.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,800 +0,0 @@ -// This module provides a data structure, `Ignore`, that connects "directory -// traversal" with "ignore matchers." Specifically, it knows about gitignore -// semantics and precedence, and is organized based on directory hierarchy. -// Namely, every matcher logically corresponds to ignore rules from a single -// directory, and points to the matcher for its corresponding parent directory. -// In this sense, `Ignore` is a *persistent* data structure. -// -// This design was specifically chosen to make it possible to use this data -// structure in a parallel directory iterator. -// -// My initial intention was to expose this module as part of this crate's -// public API, but I think the data structure's public API is too complicated -// with non-obvious failure modes. Alas, such things haven't been documented -// well. - -use std::collections::HashMap; -use std::ffi::OsString; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, RwLock}; - -use gitignore::{self, Gitignore, GitignoreBuilder}; -use pathutil::{is_hidden, strip_prefix}; -use overrides::{self, Override}; -use types::{self, Types}; -use {Error, Match, PartialErrorBuilder}; - -/// IgnoreMatch represents information about where a match came from when using -/// the `Ignore` matcher. -#[derive(Clone, Debug)] -pub struct IgnoreMatch<'a>(IgnoreMatchInner<'a>); - -/// IgnoreMatchInner describes precisely where the match information came from. -/// This is private to allow expansion to more matchers in the future. -#[derive(Clone, Debug)] -enum IgnoreMatchInner<'a> { - Override(overrides::Glob<'a>), - Gitignore(&'a gitignore::Glob), - Types(types::Glob<'a>), - Hidden, -} - -impl<'a> IgnoreMatch<'a> { - fn overrides(x: overrides::Glob<'a>) -> IgnoreMatch<'a> { - IgnoreMatch(IgnoreMatchInner::Override(x)) - } - - fn gitignore(x: &'a gitignore::Glob) -> IgnoreMatch<'a> { - IgnoreMatch(IgnoreMatchInner::Gitignore(x)) - } - - fn types(x: types::Glob<'a>) -> IgnoreMatch<'a> { - IgnoreMatch(IgnoreMatchInner::Types(x)) - } - - fn hidden() -> IgnoreMatch<'static> { - IgnoreMatch(IgnoreMatchInner::Hidden) - } -} - -/// Options for the ignore matcher, shared between the matcher itself and the -/// builder. -#[derive(Clone, Copy, Debug)] -struct IgnoreOptions { - /// Whether to ignore hidden file paths or not. - hidden: bool, - /// Whether to read .ignore files. - ignore: bool, - /// Whether to read git's global gitignore file. - git_global: bool, - /// Whether to read .gitignore files. - git_ignore: bool, - /// Whether to read .git/info/exclude files. - git_exclude: bool, -} - -impl IgnoreOptions { - /// Returns true if at least one type of ignore rules should be matched. - fn has_any_ignore_options(&self) -> bool { - self.ignore || self.git_global || self.git_ignore || self.git_exclude - } -} - -/// Ignore is a matcher useful for recursively walking one or more directories. -#[derive(Clone, Debug)] -pub struct Ignore(Arc); - -#[derive(Clone, Debug)] -struct IgnoreInner { - /// A map of all existing directories that have already been - /// compiled into matchers. - /// - /// Note that this is never used during matching, only when adding new - /// parent directory matchers. This avoids needing to rebuild glob sets for - /// parent directories if many paths are being searched. - compiled: Arc>>, - /// The path to the directory that this matcher was built from. - dir: PathBuf, - /// An override matcher (default is empty). - overrides: Arc, - /// A file type matcher. - types: Arc, - /// The parent directory to match next. - /// - /// If this is the root directory or there are otherwise no more - /// directories to match, then `parent` is `None`. - parent: Option, - /// Whether this is an absolute parent matcher, as added by add_parent. - is_absolute_parent: bool, - /// The absolute base path of this matcher. Populated only if parent - /// directories are added. - absolute_base: Option>, - /// Explicit ignore matchers specified by the caller. - explicit_ignores: Arc>, - /// The matcher for .ignore files. - ignore_matcher: Gitignore, - /// A global gitignore matcher, usually from $XDG_CONFIG_HOME/git/ignore. - git_global_matcher: Arc, - /// The matcher for .gitignore files. - git_ignore_matcher: Gitignore, - /// Special matcher for `.git/info/exclude` files. - git_exclude_matcher: Gitignore, - /// Whether this directory contains a .git sub-directory. - has_git: bool, - /// Ignore config. - opts: IgnoreOptions, -} - -impl Ignore { - /// Return the directory path of this matcher. - #[allow(dead_code)] - pub fn path(&self) -> &Path { - &self.0.dir - } - - /// Return true if this matcher has no parent. - pub fn is_root(&self) -> bool { - self.0.parent.is_none() - } - - /// Returns true if this matcher was added via the `add_parents` method. - pub fn is_absolute_parent(&self) -> bool { - self.0.is_absolute_parent - } - - /// Return this matcher's parent, if one exists. - pub fn parent(&self) -> Option { - self.0.parent.clone() - } - - /// Create a new `Ignore` matcher with the parent directories of `dir`. - /// - /// Note that this can only be called on an `Ignore` matcher with no - /// parents (i.e., `is_root` returns `true`). This will panic otherwise. - pub fn add_parents>( - &self, - path: P, - ) -> (Ignore, Option) { - if !self.is_root() { - panic!("Ignore::add_parents called on non-root matcher"); - } - let absolute_base = match path.as_ref().canonicalize() { - Ok(path) => Arc::new(path), - Err(_) => { - // There's not much we can do here, so just return our - // existing matcher. We drop the error to be consistent - // with our general pattern of ignoring I/O errors when - // processing ignore files. - return (self.clone(), None); - } - }; - // List of parents, from child to root. - let mut parents = vec![]; - let mut path = &**absolute_base; - while let Some(parent) = path.parent() { - parents.push(parent); - path = parent; - } - let mut errs = PartialErrorBuilder::default(); - let mut ig = self.clone(); - for parent in parents.into_iter().rev() { - let mut compiled = self.0.compiled.write().unwrap(); - if let Some(prebuilt) = compiled.get(parent.as_os_str()) { - ig = prebuilt.clone(); - continue; - } - let (mut igtmp, err) = ig.add_child_path(parent); - errs.maybe_push(err); - igtmp.is_absolute_parent = true; - igtmp.absolute_base = Some(absolute_base.clone()); - ig = Ignore(Arc::new(igtmp)); - compiled.insert(parent.as_os_str().to_os_string(), ig.clone()); - } - (ig, errs.into_error_option()) - } - - /// Create a new `Ignore` matcher for the given child directory. - /// - /// Since building the matcher may require reading from multiple - /// files, it's possible that this method partially succeeds. Therefore, - /// a matcher is always returned (which may match nothing) and an error is - /// returned if it exists. - /// - /// Note that all I/O errors are completely ignored. - pub fn add_child>( - &self, - dir: P, - ) -> (Ignore, Option) { - let (ig, err) = self.add_child_path(dir.as_ref()); - (Ignore(Arc::new(ig)), err) - } - - /// Like add_child, but takes a full path and returns an IgnoreInner. - fn add_child_path(&self, dir: &Path) -> (IgnoreInner, Option) { - static IG_NAMES: &'static [&'static str] = &[".rgignore", ".ignore"]; - - let mut errs = PartialErrorBuilder::default(); - let ig_matcher = - if !self.0.opts.ignore { - Gitignore::empty() - } else { - let (m, err) = create_gitignore(&dir, IG_NAMES); - errs.maybe_push(err); - m - }; - let gi_matcher = - if !self.0.opts.git_ignore { - Gitignore::empty() - } else { - let (m, err) = create_gitignore(&dir, &[".gitignore"]); - errs.maybe_push(err); - m - }; - let gi_exclude_matcher = - if !self.0.opts.git_exclude { - Gitignore::empty() - } else { - let (m, err) = create_gitignore(&dir, &[".git/info/exclude"]); - errs.maybe_push(err); - m - }; - let ig = IgnoreInner { - compiled: self.0.compiled.clone(), - dir: dir.to_path_buf(), - overrides: self.0.overrides.clone(), - types: self.0.types.clone(), - parent: Some(self.clone()), - is_absolute_parent: false, - absolute_base: self.0.absolute_base.clone(), - explicit_ignores: self.0.explicit_ignores.clone(), - ignore_matcher: ig_matcher, - git_global_matcher: self.0.git_global_matcher.clone(), - git_ignore_matcher: gi_matcher, - git_exclude_matcher: gi_exclude_matcher, - has_git: dir.join(".git").is_dir(), - opts: self.0.opts, - }; - (ig, errs.into_error_option()) - } - - /// Returns a match indicating whether the given file path should be - /// ignored or not. - /// - /// The match contains information about its origin. - pub fn matched<'a, P: AsRef>( - &'a self, - path: P, - is_dir: bool, - ) -> Match> { - // We need to be careful with our path. If it has a leading ./, then - // strip it because it causes nothing but trouble. - let mut path = path.as_ref(); - if let Some(p) = strip_prefix("./", path) { - path = p; - } - // Match against the override patterns. If an override matches - // regardless of whether it's whitelist/ignore, then we quit and - // return that result immediately. Overrides have the highest - // precedence. - if !self.0.overrides.is_empty() { - let mat = - self.0.overrides.matched(path, is_dir) - .map(IgnoreMatch::overrides); - if !mat.is_none() { - return mat; - } - } - let mut whitelisted = Match::None; - if self.0.opts.has_any_ignore_options() { - let mat = self.matched_ignore(path, is_dir); - if mat.is_ignore() { - return mat; - } else if mat.is_whitelist() { - whitelisted = mat; - } - } - if !self.0.types.is_empty() { - let mat = - self.0.types.matched(path, is_dir).map(IgnoreMatch::types); - if mat.is_ignore() { - return mat; - } else if mat.is_whitelist() { - whitelisted = mat; - } - } - if whitelisted.is_none() && self.0.opts.hidden && is_hidden(path) { - return Match::Ignore(IgnoreMatch::hidden()); - } - whitelisted - } - - /// Performs matching only on the ignore files for this directory and - /// all parent directories. - fn matched_ignore<'a>( - &'a self, - path: &Path, - is_dir: bool, - ) -> Match> { - let (mut m_ignore, mut m_gi, mut m_gi_exclude, mut m_explicit) = - (Match::None, Match::None, Match::None, Match::None); - let mut saw_git = false; - for ig in self.parents().take_while(|ig| !ig.0.is_absolute_parent) { - if m_ignore.is_none() { - m_ignore = - ig.0.ignore_matcher.matched(path, is_dir) - .map(IgnoreMatch::gitignore); - } - if !saw_git && m_gi.is_none() { - m_gi = - ig.0.git_ignore_matcher.matched(path, is_dir) - .map(IgnoreMatch::gitignore); - } - if !saw_git && m_gi_exclude.is_none() { - m_gi_exclude = - ig.0.git_exclude_matcher.matched(path, is_dir) - .map(IgnoreMatch::gitignore); - } - saw_git = saw_git || ig.0.has_git; - } - if let Some(abs_parent_path) = self.absolute_base() { - let path = abs_parent_path.join(path); - for ig in self.parents().skip_while(|ig|!ig.0.is_absolute_parent) { - if m_ignore.is_none() { - m_ignore = - ig.0.ignore_matcher.matched(&path, is_dir) - .map(IgnoreMatch::gitignore); - } - if !saw_git && m_gi.is_none() { - m_gi = - ig.0.git_ignore_matcher.matched(&path, is_dir) - .map(IgnoreMatch::gitignore); - } - if !saw_git && m_gi_exclude.is_none() { - m_gi_exclude = - ig.0.git_exclude_matcher.matched(&path, is_dir) - .map(IgnoreMatch::gitignore); - } - saw_git = saw_git || ig.0.has_git; - } - } - for gi in self.0.explicit_ignores.iter().rev() { - if !m_explicit.is_none() { - break; - } - m_explicit = gi.matched(&path, is_dir).map(IgnoreMatch::gitignore); - } - let m_global = self.0.git_global_matcher.matched(&path, is_dir) - .map(IgnoreMatch::gitignore); - - m_ignore.or(m_gi).or(m_gi_exclude).or(m_global).or(m_explicit) - } - - /// Returns an iterator over parent ignore matchers, including this one. - pub fn parents(&self) -> Parents { - Parents(Some(self)) - } - - /// Returns the first absolute path of the first absolute parent, if - /// one exists. - fn absolute_base(&self) -> Option<&Path> { - self.0.absolute_base.as_ref().map(|p| &***p) - } -} - -/// An iterator over all parents of an ignore matcher, including itself. -/// -/// The lifetime `'a` refers to the lifetime of the initial `Ignore` matcher. -pub struct Parents<'a>(Option<&'a Ignore>); - -impl<'a> Iterator for Parents<'a> { - type Item = &'a Ignore; - - fn next(&mut self) -> Option<&'a Ignore> { - match self.0.take() { - None => None, - Some(ig) => { - self.0 = ig.0.parent.as_ref(); - Some(ig) - } - } - } -} - -/// A builder for creating an Ignore matcher. -#[derive(Clone, Debug)] -pub struct IgnoreBuilder { - /// The root directory path for this ignore matcher. - dir: PathBuf, - /// An override matcher (default is empty). - overrides: Arc, - /// A type matcher (default is empty). - types: Arc, - /// Explicit ignore matchers. - explicit_ignores: Vec, - /// Ignore config. - opts: IgnoreOptions, -} - -impl IgnoreBuilder { - /// Create a new builder for an `Ignore` matcher. - /// - /// All relative file paths are resolved with respect to the current - /// working directory. - pub fn new() -> IgnoreBuilder { - IgnoreBuilder { - dir: Path::new("").to_path_buf(), - overrides: Arc::new(Override::empty()), - types: Arc::new(Types::empty()), - explicit_ignores: vec![], - opts: IgnoreOptions { - hidden: true, - ignore: true, - git_global: true, - git_ignore: true, - git_exclude: true, - }, - } - } - - /// Builds a new `Ignore` matcher. - /// - /// The matcher returned won't match anything until ignore rules from - /// directories are added to it. - pub fn build(&self) -> Ignore { - let git_global_matcher = - if !self.opts.git_global { - Gitignore::empty() - } else { - let (gi, err) = Gitignore::global(); - if let Some(err) = err { - debug!("{}", err); - } - gi - }; - Ignore(Arc::new(IgnoreInner { - compiled: Arc::new(RwLock::new(HashMap::new())), - dir: self.dir.clone(), - overrides: self.overrides.clone(), - types: self.types.clone(), - parent: None, - is_absolute_parent: true, - absolute_base: None, - explicit_ignores: Arc::new(self.explicit_ignores.clone()), - ignore_matcher: Gitignore::empty(), - git_global_matcher: Arc::new(git_global_matcher), - git_ignore_matcher: Gitignore::empty(), - git_exclude_matcher: Gitignore::empty(), - has_git: false, - opts: self.opts, - })) - } - - /// Add an override matcher. - /// - /// By default, no override matcher is used. - /// - /// This overrides any previous setting. - pub fn overrides(&mut self, overrides: Override) -> &mut IgnoreBuilder { - self.overrides = Arc::new(overrides); - self - } - - /// Add a file type matcher. - /// - /// By default, no file type matcher is used. - /// - /// This overrides any previous setting. - pub fn types(&mut self, types: Types) -> &mut IgnoreBuilder { - self.types = Arc::new(types); - self - } - - /// Adds a new global ignore matcher from the ignore file path given. - pub fn add_ignore(&mut self, ig: Gitignore) -> &mut IgnoreBuilder { - self.explicit_ignores.push(ig); - self - } - - /// Enables ignoring hidden files. - /// - /// This is enabled by default. - pub fn hidden(&mut self, yes: bool) -> &mut IgnoreBuilder { - self.opts.hidden = yes; - self - } - - /// Enables reading `.ignore` files. - /// - /// `.ignore` files have the same semantics as `gitignore` files and are - /// supported by search tools such as ripgrep and The Silver Searcher. - /// - /// This is enabled by default. - pub fn ignore(&mut self, yes: bool) -> &mut IgnoreBuilder { - self.opts.ignore = yes; - self - } - - /// Add a global gitignore matcher. - /// - /// Its precedence is lower than both normal `.gitignore` files and - /// `.git/info/exclude` files. - /// - /// This overwrites any previous global gitignore setting. - /// - /// This is enabled by default. - pub fn git_global(&mut self, yes: bool) -> &mut IgnoreBuilder { - self.opts.git_global = yes; - self - } - - /// Enables reading `.gitignore` files. - /// - /// `.gitignore` files have match semantics as described in the `gitignore` - /// man page. - /// - /// This is enabled by default. - pub fn git_ignore(&mut self, yes: bool) -> &mut IgnoreBuilder { - self.opts.git_ignore = yes; - self - } - - /// Enables reading `.git/info/exclude` files. - /// - /// `.git/info/exclude` files have match semantics as described in the - /// `gitignore` man page. - /// - /// This is enabled by default. - pub fn git_exclude(&mut self, yes: bool) -> &mut IgnoreBuilder { - self.opts.git_exclude = yes; - self - } -} - -/// Creates a new gitignore matcher for the directory given. -/// -/// Ignore globs are extracted from each of the file names in `dir` in the -/// order given (earlier names have lower precedence than later names). -/// -/// I/O errors are ignored. -pub fn create_gitignore( - dir: &Path, - names: &[&str], -) -> (Gitignore, Option) { - let mut builder = GitignoreBuilder::new(dir); - let mut errs = PartialErrorBuilder::default(); - for name in names { - let gipath = dir.join(name); - errs.maybe_push_ignore_io(builder.add(gipath)); - } - let gi = match builder.build() { - Ok(gi) => gi, - Err(err) => { - errs.push(err); - GitignoreBuilder::new(dir).build().unwrap() - } - }; - (gi, errs.into_error_option()) -} - -#[cfg(test)] -mod tests { - use std::fs::{self, File}; - use std::io::Write; - use std::path::Path; - - use tempdir::TempDir; - - use dir::IgnoreBuilder; - use gitignore::Gitignore; - use Error; - - fn wfile>(path: P, contents: &str) { - let mut file = File::create(path).unwrap(); - file.write_all(contents.as_bytes()).unwrap(); - } - - fn mkdirp>(path: P) { - fs::create_dir_all(path).unwrap(); - } - - fn partial(err: Error) -> Vec { - match err { - Error::Partial(errs) => errs, - _ => panic!("expected partial error but got {:?}", err), - } - } - - #[test] - fn explicit_ignore() { - let td = TempDir::new("ignore-test-").unwrap(); - wfile(td.path().join("not-an-ignore"), "foo\n!bar"); - - let (gi, err) = Gitignore::new(td.path().join("not-an-ignore")); - assert!(err.is_none()); - let (ig, err) = IgnoreBuilder::new() - .add_ignore(gi).build().add_child(td.path()); - assert!(err.is_none()); - assert!(ig.matched("foo", false).is_ignore()); - assert!(ig.matched("bar", false).is_whitelist()); - assert!(ig.matched("baz", false).is_none()); - } - - #[test] - fn git_exclude() { - let td = TempDir::new("ignore-test-").unwrap(); - mkdirp(td.path().join(".git/info")); - wfile(td.path().join(".git/info/exclude"), "foo\n!bar"); - - let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); - assert!(err.is_none()); - assert!(ig.matched("foo", false).is_ignore()); - assert!(ig.matched("bar", false).is_whitelist()); - assert!(ig.matched("baz", false).is_none()); - } - - #[test] - fn gitignore() { - let td = TempDir::new("ignore-test-").unwrap(); - wfile(td.path().join(".gitignore"), "foo\n!bar"); - - let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); - assert!(err.is_none()); - assert!(ig.matched("foo", false).is_ignore()); - assert!(ig.matched("bar", false).is_whitelist()); - assert!(ig.matched("baz", false).is_none()); - } - - #[test] - fn ignore() { - let td = TempDir::new("ignore-test-").unwrap(); - wfile(td.path().join(".ignore"), "foo\n!bar"); - - let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); - assert!(err.is_none()); - assert!(ig.matched("foo", false).is_ignore()); - assert!(ig.matched("bar", false).is_whitelist()); - assert!(ig.matched("baz", false).is_none()); - } - - // Tests that an .ignore will override a .gitignore. - #[test] - fn ignore_over_gitignore() { - let td = TempDir::new("ignore-test-").unwrap(); - wfile(td.path().join(".gitignore"), "foo"); - wfile(td.path().join(".ignore"), "!foo"); - - let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); - assert!(err.is_none()); - assert!(ig.matched("foo", false).is_whitelist()); - } - - // Tests that exclude has lower precedent than both .ignore and .gitignore. - #[test] - fn exclude_lowest() { - let td = TempDir::new("ignore-test-").unwrap(); - wfile(td.path().join(".gitignore"), "!foo"); - wfile(td.path().join(".ignore"), "!bar"); - mkdirp(td.path().join(".git/info")); - wfile(td.path().join(".git/info/exclude"), "foo\nbar\nbaz"); - - let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); - assert!(err.is_none()); - assert!(ig.matched("baz", false).is_ignore()); - assert!(ig.matched("foo", false).is_whitelist()); - assert!(ig.matched("bar", false).is_whitelist()); - } - - #[test] - fn errored() { - let td = TempDir::new("ignore-test-").unwrap(); - wfile(td.path().join(".gitignore"), "f**oo"); - - let (_, err) = IgnoreBuilder::new().build().add_child(td.path()); - assert!(err.is_some()); - } - - #[test] - fn errored_both() { - let td = TempDir::new("ignore-test-").unwrap(); - wfile(td.path().join(".gitignore"), "f**oo"); - wfile(td.path().join(".ignore"), "fo**o"); - - let (_, err) = IgnoreBuilder::new().build().add_child(td.path()); - assert_eq!(2, partial(err.expect("an error")).len()); - } - - #[test] - fn errored_partial() { - let td = TempDir::new("ignore-test-").unwrap(); - wfile(td.path().join(".gitignore"), "f**oo\nbar"); - - let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); - assert!(err.is_some()); - assert!(ig.matched("bar", false).is_ignore()); - } - - #[test] - fn errored_partial_and_ignore() { - let td = TempDir::new("ignore-test-").unwrap(); - wfile(td.path().join(".gitignore"), "f**oo\nbar"); - wfile(td.path().join(".ignore"), "!bar"); - - let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); - assert!(err.is_some()); - assert!(ig.matched("bar", false).is_whitelist()); - } - - #[test] - fn not_present_empty() { - let td = TempDir::new("ignore-test-").unwrap(); - - let (_, err) = IgnoreBuilder::new().build().add_child(td.path()); - assert!(err.is_none()); - } - - #[test] - fn stops_at_git_dir() { - // This tests that .gitignore files beyond a .git barrier aren't - // matched, but .ignore files are. - let td = TempDir::new("ignore-test-").unwrap(); - mkdirp(td.path().join(".git")); - mkdirp(td.path().join("foo/.git")); - wfile(td.path().join(".gitignore"), "foo"); - wfile(td.path().join(".ignore"), "bar"); - - let ig0 = IgnoreBuilder::new().build(); - let (ig1, err) = ig0.add_child(td.path()); - assert!(err.is_none()); - let (ig2, err) = ig1.add_child(ig1.path().join("foo")); - assert!(err.is_none()); - - assert!(ig1.matched("foo", false).is_ignore()); - assert!(ig2.matched("foo", false).is_none()); - - assert!(ig1.matched("bar", false).is_ignore()); - assert!(ig2.matched("bar", false).is_ignore()); - } - - #[test] - fn absolute_parent() { - let td = TempDir::new("ignore-test-").unwrap(); - mkdirp(td.path().join(".git")); - mkdirp(td.path().join("foo")); - wfile(td.path().join(".gitignore"), "bar"); - - // First, check that the parent gitignore file isn't detected if the - // parent isn't added. This establishes a baseline. - let ig0 = IgnoreBuilder::new().build(); - let (ig1, err) = ig0.add_child(td.path().join("foo")); - assert!(err.is_none()); - assert!(ig1.matched("bar", false).is_none()); - - // Second, check that adding a parent directory actually works. - let ig0 = IgnoreBuilder::new().build(); - let (ig1, err) = ig0.add_parents(td.path().join("foo")); - assert!(err.is_none()); - let (ig2, err) = ig1.add_child(td.path().join("foo")); - assert!(err.is_none()); - assert!(ig2.matched("bar", false).is_ignore()); - } - - #[test] - fn absolute_parent_anchored() { - let td = TempDir::new("ignore-test-").unwrap(); - mkdirp(td.path().join(".git")); - mkdirp(td.path().join("src/llvm")); - wfile(td.path().join(".gitignore"), "/llvm/\nfoo"); - - let ig0 = IgnoreBuilder::new().build(); - let (ig1, err) = ig0.add_parents(td.path().join("src")); - assert!(err.is_none()); - let (ig2, err) = ig1.add_child("src"); - assert!(err.is_none()); - - assert!(ig1.matched("llvm", true).is_none()); - assert!(ig2.matched("llvm", true).is_none()); - assert!(ig2.matched("src/llvm", true).is_none()); - assert!(ig2.matched("foo", false).is_ignore()); - assert!(ig2.matched("src/foo", false).is_ignore()); - } -} diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/src/gitignore.rs cargo-0.26.0/vendor/ignore-0.2.2/src/gitignore.rs --- cargo-0.25.0/vendor/ignore-0.2.2/src/gitignore.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/src/gitignore.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,692 +0,0 @@ -/*! -The gitignore module provides a way to match globs from a gitignore file -against file paths. - -Note that this module implements the specification as described in the -`gitignore` man page from scratch. That is, this module does *not* shell out to -the `git` command line tool. -*/ - -use std::cell::RefCell; -use std::env; -use std::fs::File; -use std::io::{self, BufRead, Read}; -use std::path::{Path, PathBuf}; -use std::str; -use std::sync::Arc; - -use globset::{Candidate, GlobBuilder, GlobSet, GlobSetBuilder}; -use regex::bytes::Regex; -use thread_local::ThreadLocal; - -use pathutil::{is_file_name, strip_prefix}; -use {Error, Match, PartialErrorBuilder}; - -/// Glob represents a single glob in a gitignore file. -/// -/// This is used to report information about the highest precedent glob that -/// matched in one or more gitignore files. -#[derive(Clone, Debug)] -pub struct Glob { - /// The file path that this glob was extracted from. - from: Option, - /// The original glob string. - original: String, - /// The actual glob string used to convert to a regex. - actual: String, - /// Whether this is a whitelisted glob or not. - is_whitelist: bool, - /// Whether this glob should only match directories or not. - is_only_dir: bool, -} - -impl Glob { - /// Returns the file path that defined this glob. - pub fn from(&self) -> Option<&Path> { - self.from.as_ref().map(|p| &**p) - } - - /// The original glob as it was defined in a gitignore file. - pub fn original(&self) -> &str { - &self.original - } - - /// The actual glob that was compiled to respect gitignore - /// semantics. - pub fn actual(&self) -> &str { - &self.actual - } - - /// Whether this was a whitelisted glob or not. - pub fn is_whitelist(&self) -> bool { - self.is_whitelist - } - - /// Whether this glob must match a directory or not. - pub fn is_only_dir(&self) -> bool { - self.is_only_dir - } -} - -/// Gitignore is a matcher for the globs in one or more gitignore files -/// in the same directory. -#[derive(Clone, Debug)] -pub struct Gitignore { - set: GlobSet, - root: PathBuf, - globs: Vec, - num_ignores: u64, - num_whitelists: u64, - matches: Arc>>>, -} - -impl Gitignore { - /// Creates a new gitignore matcher from the gitignore file path given. - /// - /// If it's desirable to include multiple gitignore files in a single - /// matcher, or read gitignore globs from a different source, then - /// use `GitignoreBuilder`. - /// - /// This always returns a valid matcher, even if it's empty. In particular, - /// a Gitignore file can be partially valid, e.g., when one glob is invalid - /// but the rest aren't. - /// - /// Note that I/O errors are ignored. For more granular control over - /// errors, use `GitignoreBuilder`. - pub fn new>( - gitignore_path: P, - ) -> (Gitignore, Option) { - let path = gitignore_path.as_ref(); - let parent = path.parent().unwrap_or(Path::new("/")); - let mut builder = GitignoreBuilder::new(parent); - let mut errs = PartialErrorBuilder::default(); - errs.maybe_push_ignore_io(builder.add(path)); - match builder.build() { - Ok(gi) => (gi, errs.into_error_option()), - Err(err) => { - errs.push(err); - (Gitignore::empty(), errs.into_error_option()) - } - } - } - - /// Creates a new gitignore matcher from the global ignore file, if one - /// exists. - /// - /// The global config file path is specified by git's `core.excludesFile` - /// config option. - /// - /// Git's config file location is `$HOME/.gitconfig`. If `$HOME/.gitconfig` - /// does not exist or does not specify `core.excludesFile`, then - /// `$XDG_CONFIG_HOME/git/ignore` is read. If `$XDG_CONFIG_HOME` is not - /// set or is empty, then `$HOME/.config/git/ignore` is used instead. - pub fn global() -> (Gitignore, Option) { - match gitconfig_excludes_path() { - None => (Gitignore::empty(), None), - Some(path) => { - if !path.is_file() { - (Gitignore::empty(), None) - } else { - Gitignore::new(path) - } - } - } - } - - /// Creates a new empty gitignore matcher that never matches anything. - /// - /// Its path is empty. - pub fn empty() -> Gitignore { - GitignoreBuilder::new("").build().unwrap() - } - - /// Returns the directory containing this gitignore matcher. - /// - /// All matches are done relative to this path. - pub fn path(&self) -> &Path { - &*self.root - } - - /// Returns true if and only if this gitignore has zero globs, and - /// therefore never matches any file path. - pub fn is_empty(&self) -> bool { - self.set.is_empty() - } - - /// Returns the total number of globs, which should be equivalent to - /// `num_ignores + num_whitelists`. - pub fn len(&self) -> usize { - self.set.len() - } - - /// Returns the total number of ignore globs. - pub fn num_ignores(&self) -> u64 { - self.num_ignores - } - - /// Returns the total number of whitelisted globs. - pub fn num_whitelists(&self) -> u64 { - self.num_whitelists - } - - /// Returns whether the given path (file or directory) matched a pattern in - /// this gitignore matcher. - /// - /// `is_dir` should be true if the path refers to a directory and false - /// otherwise. - /// - /// The given path is matched relative to the path given when building - /// the matcher. Specifically, before matching `path`, its prefix (as - /// determined by a common suffix of the directory containing this - /// gitignore) is stripped. If there is no common suffix/prefix overlap, - /// then `path` is assumed to be relative to this matcher. - pub fn matched>( - &self, - path: P, - is_dir: bool, - ) -> Match<&Glob> { - if self.is_empty() { - return Match::None; - } - self.matched_stripped(self.strip(path.as_ref()), is_dir) - } - - /// Returns whether the given path (file or directory, and expected to be - /// under the root) or any of its parent directories (up to the root) - /// matched a pattern in this gitignore matcher. - /// - /// NOTE: This method is more expensive than walking the directory hierarchy - /// top-to-bottom and matching the entries. But, is easier to use in cases - /// when a list of paths are available without a hierarchy. - /// - /// `is_dir` should be true if the path refers to a directory and false - /// otherwise. - /// - /// The given path is matched relative to the path given when building - /// the matcher. Specifically, before matching `path`, its prefix (as - /// determined by a common suffix of the directory containing this - /// gitignore) is stripped. If there is no common suffix/prefix overlap, - /// then `path` is assumed to be relative to this matcher. - pub fn matched_path_or_any_parents>( - &self, - path: P, - is_dir: bool, - ) -> Match<&Glob> { - if self.is_empty() { - return Match::None; - } - let mut path = self.strip(path.as_ref()); - debug_assert!( - !path.has_root(), - "path is expect to be under the root" - ); - match self.matched_stripped(path, is_dir) { - Match::None => (), // walk up - a_match => return a_match, - } - while let Some(parent) = path.parent() { - match self.matched_stripped(parent, /* is_dir */ true) { - Match::None => path = parent, // walk up - a_match => return a_match, - } - } - Match::None - } - - /// Like matched, but takes a path that has already been stripped. - fn matched_stripped>( - &self, - path: P, - is_dir: bool, - ) -> Match<&Glob> { - if self.is_empty() { - return Match::None; - } - let path = path.as_ref(); - let _matches = self.matches.get_default(); - let mut matches = _matches.borrow_mut(); - let candidate = Candidate::new(path); - self.set.matches_candidate_into(&candidate, &mut *matches); - for &i in matches.iter().rev() { - let glob = &self.globs[i]; - if !glob.is_only_dir() || is_dir { - return if glob.is_whitelist() { - Match::Whitelist(glob) - } else { - Match::Ignore(glob) - }; - } - } - Match::None - } - - /// Strips the given path such that it's suitable for matching with this - /// gitignore matcher. - fn strip<'a, P: 'a + AsRef + ?Sized>( - &'a self, - path: &'a P, - ) -> &'a Path { - let mut path = path.as_ref(); - // A leading ./ is completely superfluous. We also strip it from - // our gitignore root path, so we need to strip it from our candidate - // path too. - if let Some(p) = strip_prefix("./", path) { - path = p; - } - // Strip any common prefix between the candidate path and the root - // of the gitignore, to make sure we get relative matching right. - // BUT, a file name might not have any directory components to it, - // in which case, we don't want to accidentally strip any part of the - // file name. - if !is_file_name(path) { - if let Some(p) = strip_prefix(&self.root, path) { - path = p; - // If we're left with a leading slash, get rid of it. - if let Some(p) = strip_prefix("/", path) { - path = p; - } - } - } - path - } -} - -/// Builds a matcher for a single set of globs from a .gitignore file. -pub struct GitignoreBuilder { - builder: GlobSetBuilder, - root: PathBuf, - globs: Vec, - case_insensitive: bool, -} - -impl GitignoreBuilder { - /// Create a new builder for a gitignore file. - /// - /// The path given should be the path at which the globs for this gitignore - /// file should be matched. Note that paths are always matched relative - /// to the root path given here. Generally, the root path should correspond - /// to the *directory* containing a `.gitignore` file. - pub fn new>(root: P) -> GitignoreBuilder { - let root = root.as_ref(); - GitignoreBuilder { - builder: GlobSetBuilder::new(), - root: strip_prefix("./", root).unwrap_or(root).to_path_buf(), - globs: vec![], - case_insensitive: false, - } - } - - /// Builds a new matcher from the globs added so far. - /// - /// Once a matcher is built, no new globs can be added to it. - pub fn build(&self) -> Result { - let nignore = self.globs.iter().filter(|g| !g.is_whitelist()).count(); - let nwhite = self.globs.iter().filter(|g| g.is_whitelist()).count(); - let set = try!( - self.builder.build().map_err(|err| { - Error::Glob { - glob: None, - err: err.to_string(), - } - })); - Ok(Gitignore { - set: set, - root: self.root.clone(), - globs: self.globs.clone(), - num_ignores: nignore as u64, - num_whitelists: nwhite as u64, - matches: Arc::new(ThreadLocal::default()), - }) - } - - /// Add each glob from the file path given. - /// - /// The file given should be formatted as a `gitignore` file. - /// - /// Note that partial errors can be returned. For example, if there was - /// a problem adding one glob, an error for that will be returned, but - /// all other valid globs will still be added. - pub fn add>(&mut self, path: P) -> Option { - let path = path.as_ref(); - let file = match File::open(path) { - Err(err) => return Some(Error::Io(err).with_path(path)), - Ok(file) => file, - }; - let rdr = io::BufReader::new(file); - let mut errs = PartialErrorBuilder::default(); - for (i, line) in rdr.lines().enumerate() { - let lineno = (i + 1) as u64; - let line = match line { - Ok(line) => line, - Err(err) => { - errs.push(Error::Io(err).tagged(path, lineno)); - break; - } - }; - if let Err(err) = self.add_line(Some(path.to_path_buf()), &line) { - errs.push(err.tagged(path, lineno)); - } - } - errs.into_error_option() - } - - /// Add each glob line from the string given. - /// - /// If this string came from a particular `gitignore` file, then its path - /// should be provided here. - /// - /// The string given should be formatted as a `gitignore` file. - #[cfg(test)] - fn add_str( - &mut self, - from: Option, - gitignore: &str, - ) -> Result<&mut GitignoreBuilder, Error> { - for line in gitignore.lines() { - try!(self.add_line(from.clone(), line)); - } - Ok(self) - } - - /// Add a line from a gitignore file to this builder. - /// - /// If this line came from a particular `gitignore` file, then its path - /// should be provided here. - /// - /// If the line could not be parsed as a glob, then an error is returned. - pub fn add_line( - &mut self, - from: Option, - mut line: &str, - ) -> Result<&mut GitignoreBuilder, Error> { - if line.starts_with("#") { - return Ok(self); - } - if !line.ends_with("\\ ") { - line = line.trim_right(); - } - if line.is_empty() { - return Ok(self); - } - let mut glob = Glob { - from: from, - original: line.to_string(), - actual: String::new(), - is_whitelist: false, - is_only_dir: false, - }; - let mut literal_separator = false; - let has_slash = line.chars().any(|c| c == '/'); - let mut is_absolute = false; - if line.starts_with("\\!") || line.starts_with("\\#") { - line = &line[1..]; - is_absolute = line.chars().nth(0) == Some('/'); - } else { - if line.starts_with("!") { - glob.is_whitelist = true; - line = &line[1..]; - } - if line.starts_with("/") { - // `man gitignore` says that if a glob starts with a slash, - // then the glob can only match the beginning of a path - // (relative to the location of gitignore). We achieve this by - // simply banning wildcards from matching /. - literal_separator = true; - line = &line[1..]; - is_absolute = true; - } - } - // If it ends with a slash, then this should only match directories, - // but the slash should otherwise not be used while globbing. - if let Some((i, c)) = line.char_indices().rev().nth(0) { - if c == '/' { - glob.is_only_dir = true; - line = &line[..i]; - } - } - // If there is a literal slash, then we note that so that globbing - // doesn't let wildcards match slashes. - glob.actual = line.to_string(); - if has_slash { - literal_separator = true; - } - // If there was a leading slash, then this is a glob that must - // match the entire path name. Otherwise, we should let it match - // anywhere, so use a **/ prefix. - if !is_absolute { - // ... but only if we don't already have a **/ prefix. - if !glob.actual.starts_with("**/") { - glob.actual = format!("**/{}", glob.actual); - } - } - // If the glob ends with `/**`, then we should only match everything - // inside a directory, but not the directory itself. Standard globs - // will match the directory. So we add `/*` to force the issue. - if glob.actual.ends_with("/**") { - glob.actual = format!("{}/*", glob.actual); - } - let parsed = try!( - GlobBuilder::new(&glob.actual) - .literal_separator(literal_separator) - .case_insensitive(self.case_insensitive) - .build() - .map_err(|err| { - Error::Glob { - glob: Some(glob.original.clone()), - err: err.kind().to_string(), - } - })); - self.builder.add(parsed); - self.globs.push(glob); - Ok(self) - } - - /// Toggle whether the globs should be matched case insensitively or not. - /// - /// This is disabled by default. - pub fn case_insensitive( - &mut self, yes: bool - ) -> Result<&mut GitignoreBuilder, Error> { - self.case_insensitive = yes; - Ok(self) - } -} - -/// Return the file path of the current environment's global gitignore file. -/// -/// Note that the file path returned may not exist. -fn gitconfig_excludes_path() -> Option { - gitconfig_contents() - .and_then(|data| parse_excludes_file(&data)) - .or_else(excludes_file_default) -} - -/// Returns the file contents of git's global config file, if one exists. -fn gitconfig_contents() -> Option> { - let home = match env::var_os("HOME") { - None => return None, - Some(home) => PathBuf::from(home), - }; - let mut file = match File::open(home.join(".gitconfig")) { - Err(_) => return None, - Ok(file) => io::BufReader::new(file), - }; - let mut contents = vec![]; - file.read_to_end(&mut contents).ok().map(|_| contents) -} - -/// Returns the default file path for a global .gitignore file. -/// -/// Specifically, this respects XDG_CONFIG_HOME. -fn excludes_file_default() -> Option { - env::var_os("XDG_CONFIG_HOME") - .and_then(|x| if x.is_empty() { None } else { Some(PathBuf::from(x)) }) - .or_else(|| env::home_dir().map(|p| p.join(".config"))) - .map(|x| x.join("git/ignore")) -} - -/// Extract git's `core.excludesfile` config setting from the raw file contents -/// given. -fn parse_excludes_file(data: &[u8]) -> Option { - // N.B. This is the lazy approach, and isn't technically correct, but - // probably works in more circumstances. I guess we would ideally have - // a full INI parser. Yuck. - lazy_static! { - static ref RE: Regex = Regex::new( - r"(?ium)^\s*excludesfile\s*=\s*(.+)\s*$").unwrap(); - }; - let caps = match RE.captures(data) { - None => return None, - Some(caps) => caps, - }; - str::from_utf8(&caps[1]).ok().map(|s| PathBuf::from(expand_tilde(s))) -} - -/// Expands ~ in file paths to the value of $HOME. -fn expand_tilde(path: &str) -> String { - let home = match env::var("HOME") { - Err(_) => return path.to_string(), - Ok(home) => home, - }; - path.replace("~", &home) -} - -#[cfg(test)] -mod tests { - use std::path::Path; - use super::{Gitignore, GitignoreBuilder}; - - fn gi_from_str>(root: P, s: &str) -> Gitignore { - let mut builder = GitignoreBuilder::new(root); - builder.add_str(None, s).unwrap(); - builder.build().unwrap() - } - - macro_rules! ignored { - ($name:ident, $root:expr, $gi:expr, $path:expr) => { - ignored!($name, $root, $gi, $path, false); - }; - ($name:ident, $root:expr, $gi:expr, $path:expr, $is_dir:expr) => { - #[test] - fn $name() { - let gi = gi_from_str($root, $gi); - assert!(gi.matched($path, $is_dir).is_ignore()); - } - }; - } - - macro_rules! not_ignored { - ($name:ident, $root:expr, $gi:expr, $path:expr) => { - not_ignored!($name, $root, $gi, $path, false); - }; - ($name:ident, $root:expr, $gi:expr, $path:expr, $is_dir:expr) => { - #[test] - fn $name() { - let gi = gi_from_str($root, $gi); - assert!(!gi.matched($path, $is_dir).is_ignore()); - } - }; - } - - const ROOT: &'static str = "/home/foobar/rust/rg"; - - ignored!(ig1, ROOT, "months", "months"); - ignored!(ig2, ROOT, "*.lock", "Cargo.lock"); - ignored!(ig3, ROOT, "*.rs", "src/main.rs"); - ignored!(ig4, ROOT, "src/*.rs", "src/main.rs"); - ignored!(ig5, ROOT, "/*.c", "cat-file.c"); - ignored!(ig6, ROOT, "/src/*.rs", "src/main.rs"); - ignored!(ig7, ROOT, "!src/main.rs\n*.rs", "src/main.rs"); - ignored!(ig8, ROOT, "foo/", "foo", true); - ignored!(ig9, ROOT, "**/foo", "foo"); - ignored!(ig10, ROOT, "**/foo", "src/foo"); - ignored!(ig11, ROOT, "**/foo/**", "src/foo/bar"); - ignored!(ig12, ROOT, "**/foo/**", "wat/src/foo/bar/baz"); - ignored!(ig13, ROOT, "**/foo/bar", "foo/bar"); - ignored!(ig14, ROOT, "**/foo/bar", "src/foo/bar"); - ignored!(ig15, ROOT, "abc/**", "abc/x"); - ignored!(ig16, ROOT, "abc/**", "abc/x/y"); - ignored!(ig17, ROOT, "abc/**", "abc/x/y/z"); - ignored!(ig18, ROOT, "a/**/b", "a/b"); - ignored!(ig19, ROOT, "a/**/b", "a/x/b"); - ignored!(ig20, ROOT, "a/**/b", "a/x/y/b"); - ignored!(ig21, ROOT, r"\!xy", "!xy"); - ignored!(ig22, ROOT, r"\#foo", "#foo"); - ignored!(ig23, ROOT, "foo", "./foo"); - ignored!(ig24, ROOT, "target", "grep/target"); - ignored!(ig25, ROOT, "Cargo.lock", "./tabwriter-bin/Cargo.lock"); - ignored!(ig26, ROOT, "/foo/bar/baz", "./foo/bar/baz"); - ignored!(ig27, ROOT, "foo/", "xyz/foo", true); - ignored!(ig28, ROOT, "src/*.rs", "src/grep/src/main.rs"); - ignored!(ig29, "./src", "/llvm/", "./src/llvm", true); - ignored!(ig30, ROOT, "node_modules/ ", "node_modules", true); - - not_ignored!(ignot1, ROOT, "amonths", "months"); - not_ignored!(ignot2, ROOT, "monthsa", "months"); - not_ignored!(ignot3, ROOT, "/src/*.rs", "src/grep/src/main.rs"); - not_ignored!(ignot4, ROOT, "/*.c", "mozilla-sha1/sha1.c"); - not_ignored!(ignot5, ROOT, "/src/*.rs", "src/grep/src/main.rs"); - not_ignored!(ignot6, ROOT, "*.rs\n!src/main.rs", "src/main.rs"); - not_ignored!(ignot7, ROOT, "foo/", "foo", false); - not_ignored!(ignot8, ROOT, "**/foo/**", "wat/src/afoo/bar/baz"); - not_ignored!(ignot9, ROOT, "**/foo/**", "wat/src/fooa/bar/baz"); - not_ignored!(ignot10, ROOT, "**/foo/bar", "foo/src/bar"); - not_ignored!(ignot11, ROOT, "#foo", "#foo"); - not_ignored!(ignot12, ROOT, "\n\n\n", "foo"); - not_ignored!(ignot13, ROOT, "foo/**", "foo", true); - not_ignored!( - ignot14, "./third_party/protobuf", "m4/ltoptions.m4", - "./third_party/protobuf/csharp/src/packages/repositories.config"); - not_ignored!(ignot15, ROOT, "!/bar", "foo/bar"); - - fn bytes(s: &str) -> Vec { - s.to_string().into_bytes() - } - - fn path_string>(path: P) -> String { - path.as_ref().to_str().unwrap().to_string() - } - - #[test] - fn parse_excludes_file1() { - let data = bytes("[core]\nexcludesFile = /foo/bar"); - let got = super::parse_excludes_file(&data).unwrap(); - assert_eq!(path_string(got), "/foo/bar"); - } - - #[test] - fn parse_excludes_file2() { - let data = bytes("[core]\nexcludesFile = ~/foo/bar"); - let got = super::parse_excludes_file(&data).unwrap(); - assert_eq!(path_string(got), super::expand_tilde("~/foo/bar")); - } - - #[test] - fn parse_excludes_file3() { - let data = bytes("[core]\nexcludeFile = /foo/bar"); - assert!(super::parse_excludes_file(&data).is_none()); - } - - // See: https://github.com/BurntSushi/ripgrep/issues/106 - #[test] - fn regression_106() { - gi_from_str("/", " "); - } - - #[test] - fn case_insensitive() { - let gi = GitignoreBuilder::new(ROOT) - .case_insensitive(true).unwrap() - .add_str(None, "*.html").unwrap() - .build().unwrap(); - assert!(gi.matched("foo.html", false).is_ignore()); - assert!(gi.matched("foo.HTML", false).is_ignore()); - assert!(!gi.matched("foo.htm", false).is_ignore()); - assert!(!gi.matched("foo.HTM", false).is_ignore()); - } - - ignored!(cs1, ROOT, "*.html", "foo.html"); - not_ignored!(cs2, ROOT, "*.html", "foo.HTML"); - not_ignored!(cs3, ROOT, "*.html", "foo.htm"); - not_ignored!(cs4, ROOT, "*.html", "foo.HTM"); -} diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/src/lib.rs cargo-0.26.0/vendor/ignore-0.2.2/src/lib.rs --- cargo-0.25.0/vendor/ignore-0.2.2/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,404 +0,0 @@ -/*! -The ignore crate provides a fast recursive directory iterator that respects -various filters such as globs, file types and `.gitignore` files. The precise -matching rules and precedence is explained in the documentation for -`WalkBuilder`. - -Secondarily, this crate exposes gitignore and file type matchers for use cases -that demand more fine-grained control. - -# Example - -This example shows the most basic usage of this crate. This code will -recursively traverse the current directory while automatically filtering out -files and directories according to ignore globs found in files like -`.ignore` and `.gitignore`: - - -```rust,no_run -use ignore::Walk; - -for result in Walk::new("./") { - // Each item yielded by the iterator is either a directory entry or an - // error, so either print the path or the error. - match result { - Ok(entry) => println!("{}", entry.path().display()), - Err(err) => println!("ERROR: {}", err), - } -} -``` - -# Example: advanced - -By default, the recursive directory iterator will ignore hidden files and -directories. This can be disabled by building the iterator with `WalkBuilder`: - -```rust,no_run -use ignore::WalkBuilder; - -for result in WalkBuilder::new("./").hidden(false).build() { - println!("{:?}", result); -} -``` - -See the documentation for `WalkBuilder` for many other options. -*/ - -#![deny(missing_docs)] - -extern crate crossbeam; -extern crate globset; -#[macro_use] -extern crate lazy_static; -#[macro_use] -extern crate log; -extern crate memchr; -extern crate regex; -#[cfg(test)] -extern crate tempdir; -extern crate thread_local; -extern crate walkdir; - -use std::error; -use std::fmt; -use std::io; -use std::path::{Path, PathBuf}; - -pub use walk::{DirEntry, Walk, WalkBuilder, WalkParallel, WalkState}; - -mod dir; -pub mod gitignore; -mod pathutil; -pub mod overrides; -pub mod types; -mod walk; - -/// Represents an error that can occur when parsing a gitignore file. -#[derive(Debug)] -pub enum Error { - /// A collection of "soft" errors. These occur when adding an ignore - /// file partially succeeded. - Partial(Vec), - /// An error associated with a specific line number. - WithLineNumber { - /// The line number. - line: u64, - /// The underlying error. - err: Box, - }, - /// An error associated with a particular file path. - WithPath { - /// The file path. - path: PathBuf, - /// The underlying error. - err: Box, - }, - /// An error associated with a particular directory depth when recursively - /// walking a directory. - WithDepth { - /// The directory depth. - depth: usize, - /// The underlying error. - err: Box, - }, - /// An error that occurs when a file loop is detected when traversing - /// symbolic links. - Loop { - /// The ancestor file path in the loop. - ancestor: PathBuf, - /// The child file path in the loop. - child: PathBuf, - }, - /// An error that occurs when doing I/O, such as reading an ignore file. - Io(io::Error), - /// An error that occurs when trying to parse a glob. - Glob { - /// The original glob that caused this error. This glob, when - /// available, always corresponds to the glob provided by an end user. - /// e.g., It is the glob as writtein in a `.gitignore` file. - /// - /// (This glob may be distinct from the glob that is actually - /// compiled, after accounting for `gitignore` semantics.) - glob: Option, - /// The underlying glob error as a string. - err: String, - }, - /// A type selection for a file type that is not defined. - UnrecognizedFileType(String), - /// A user specified file type definition could not be parsed. - InvalidDefinition, -} - -impl Error { - /// Returns true if this is a partial error. - /// - /// A partial error occurs when only some operations failed while others - /// may have succeeded. For example, an ignore file may contain an invalid - /// glob among otherwise valid globs. - pub fn is_partial(&self) -> bool { - match *self { - Error::Partial(_) => true, - Error::WithLineNumber { ref err, .. } => err.is_partial(), - Error::WithPath { ref err, .. } => err.is_partial(), - Error::WithDepth { ref err, .. } => err.is_partial(), - _ => false, - } - } - - /// Returns true if this error is exclusively an I/O error. - pub fn is_io(&self) -> bool { - match *self { - Error::Partial(ref errs) => errs.len() == 1 && errs[0].is_io(), - Error::WithLineNumber { ref err, .. } => err.is_io(), - Error::WithPath { ref err, .. } => err.is_io(), - Error::WithDepth { ref err, .. } => err.is_io(), - Error::Loop { .. } => false, - Error::Io(_) => true, - Error::Glob { .. } => false, - Error::UnrecognizedFileType(_) => false, - Error::InvalidDefinition => false, - } - } - - /// Returns a depth associated with recursively walking a directory (if - /// this error was generated from a recursive directory iterator). - pub fn depth(&self) -> Option { - match *self { - Error::WithPath { ref err, .. } => err.depth(), - Error::WithDepth { depth, .. } => Some(depth), - _ => None, - } - } - - /// Turn an error into a tagged error with the given file path. - fn with_path>(self, path: P) -> Error { - Error::WithPath { - path: path.as_ref().to_path_buf(), - err: Box::new(self), - } - } - - /// Turn an error into a tagged error with the given depth. - fn with_depth(self, depth: usize) -> Error { - Error::WithDepth { - depth: depth, - err: Box::new(self), - } - } - - /// Turn an error into a tagged error with the given file path and line - /// number. If path is empty, then it is omitted from the error. - fn tagged>(self, path: P, lineno: u64) -> Error { - let errline = Error::WithLineNumber { - line: lineno, - err: Box::new(self), - }; - if path.as_ref().as_os_str().is_empty() { - return errline; - } - errline.with_path(path) - } -} - -impl error::Error for Error { - fn description(&self) -> &str { - match *self { - Error::Partial(_) => "partial error", - Error::WithLineNumber { ref err, .. } => err.description(), - Error::WithPath { ref err, .. } => err.description(), - Error::WithDepth { ref err, .. } => err.description(), - Error::Loop { .. } => "file system loop found", - Error::Io(ref err) => err.description(), - Error::Glob { ref err, .. } => err, - Error::UnrecognizedFileType(_) => "unrecognized file type", - Error::InvalidDefinition => "invalid definition", - } - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Error::Partial(ref errs) => { - let msgs: Vec = - errs.iter().map(|err| err.to_string()).collect(); - write!(f, "{}", msgs.join("\n")) - } - Error::WithLineNumber { line, ref err } => { - write!(f, "line {}: {}", line, err) - } - Error::WithPath { ref path, ref err } => { - write!(f, "{}: {}", path.display(), err) - } - Error::WithDepth { ref err, .. } => err.fmt(f), - Error::Loop { ref ancestor, ref child } => { - write!(f, "File system loop found: \ - {} points to an ancestor {}", - child.display(), ancestor.display()) - } - Error::Io(ref err) => err.fmt(f), - Error::Glob { glob: None, ref err } => write!(f, "{}", err), - Error::Glob { glob: Some(ref glob), ref err } => { - write!(f, "error parsing glob '{}': {}", glob, err) - } - Error::UnrecognizedFileType(ref ty) => { - write!(f, "unrecognized file type: {}", ty) - } - Error::InvalidDefinition => { - write!(f, "invalid definition (format is type:glob, e.g., \ - html:*.html)") - } - } - } -} - -impl From for Error { - fn from(err: io::Error) -> Error { - Error::Io(err) - } -} - -impl From for Error { - fn from(err: walkdir::Error) -> Error { - let depth = err.depth(); - if let (Some(anc), Some(child)) = (err.loop_ancestor(), err.path()) { - return Error::WithDepth { - depth: depth, - err: Box::new(Error::Loop { - ancestor: anc.to_path_buf(), - child: child.to_path_buf(), - }), - }; - } - let path = err.path().map(|p| p.to_path_buf()); - let mut ig_err = Error::Io(io::Error::from(err)); - if let Some(path) = path { - ig_err = Error::WithPath { - path: path, - err: Box::new(ig_err), - }; - } - ig_err - } -} - -#[derive(Debug, Default)] -struct PartialErrorBuilder(Vec); - -impl PartialErrorBuilder { - fn push(&mut self, err: Error) { - self.0.push(err); - } - - fn push_ignore_io(&mut self, err: Error) { - if !err.is_io() { - self.push(err); - } - } - - fn maybe_push(&mut self, err: Option) { - if let Some(err) = err { - self.push(err); - } - } - - fn maybe_push_ignore_io(&mut self, err: Option) { - if let Some(err) = err { - self.push_ignore_io(err); - } - } - - fn into_error_option(mut self) -> Option { - if self.0.is_empty() { - None - } else if self.0.len() == 1 { - Some(self.0.pop().unwrap()) - } else { - Some(Error::Partial(self.0)) - } - } -} - -/// The result of a glob match. -/// -/// The type parameter `T` typically refers to a type that provides more -/// information about a particular match. For example, it might identify -/// the specific gitignore file and the specific glob pattern that caused -/// the match. -#[derive(Clone, Debug)] -pub enum Match { - /// The path didn't match any glob. - None, - /// The highest precedent glob matched indicates the path should be - /// ignored. - Ignore(T), - /// The highest precedent glob matched indicates the path should be - /// whitelisted. - Whitelist(T), -} - -impl Match { - /// Returns true if the match result didn't match any globs. - pub fn is_none(&self) -> bool { - match *self { - Match::None => true, - Match::Ignore(_) | Match::Whitelist(_) => false, - } - } - - /// Returns true if the match result implies the path should be ignored. - pub fn is_ignore(&self) -> bool { - match *self { - Match::Ignore(_) => true, - Match::None | Match::Whitelist(_) => false, - } - } - - /// Returns true if the match result implies the path should be - /// whitelisted. - pub fn is_whitelist(&self) -> bool { - match *self { - Match::Whitelist(_) => true, - Match::None | Match::Ignore(_) => false, - } - } - - /// Inverts the match so that `Ignore` becomes `Whitelist` and - /// `Whitelist` becomes `Ignore`. A non-match remains the same. - pub fn invert(self) -> Match { - match self { - Match::None => Match::None, - Match::Ignore(t) => Match::Whitelist(t), - Match::Whitelist(t) => Match::Ignore(t), - } - } - - /// Return the value inside this match if it exists. - pub fn inner(&self) -> Option<&T> { - match *self { - Match::None => None, - Match::Ignore(ref t) => Some(t), - Match::Whitelist(ref t) => Some(t), - } - } - - /// Apply the given function to the value inside this match. - /// - /// If the match has no value, then return the match unchanged. - pub fn map U>(self, f: F) -> Match { - match self { - Match::None => Match::None, - Match::Ignore(t) => Match::Ignore(f(t)), - Match::Whitelist(t) => Match::Whitelist(f(t)), - } - } - - /// Return the match if it is not none. Otherwise, return other. - pub fn or(self, other: Self) -> Self { - if self.is_none() { - other - } else { - self - } - } -} diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/src/overrides.rs cargo-0.26.0/vendor/ignore-0.2.2/src/overrides.rs --- cargo-0.25.0/vendor/ignore-0.2.2/src/overrides.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/src/overrides.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,256 +0,0 @@ -/*! -The overrides module provides a way to specify a set of override globs. -This provides functionality similar to `--include` or `--exclude` in command -line tools. -*/ - -use std::path::Path; - -use gitignore::{self, Gitignore, GitignoreBuilder}; -use {Error, Match}; - -/// Glob represents a single glob in an override matcher. -/// -/// This is used to report information about the highest precedent glob -/// that matched. -/// -/// Note that not all matches necessarily correspond to a specific glob. For -/// example, if there are one or more whitelist globs and a file path doesn't -/// match any glob in the set, then the file path is considered to be ignored. -/// -/// The lifetime `'a` refers to the lifetime of the matcher that produced -/// this glob. -#[derive(Clone, Debug)] -pub struct Glob<'a>(GlobInner<'a>); - -#[derive(Clone, Debug)] -enum GlobInner<'a> { - /// No glob matched, but the file path should still be ignored. - UnmatchedIgnore, - /// A glob matched. - Matched(&'a gitignore::Glob), -} - -impl<'a> Glob<'a> { - fn unmatched() -> Glob<'a> { - Glob(GlobInner::UnmatchedIgnore) - } -} - -/// Manages a set of overrides provided explicitly by the end user. -#[derive(Clone, Debug)] -pub struct Override(Gitignore); - -impl Override { - /// Returns an empty matcher that never matches any file path. - pub fn empty() -> Override { - Override(Gitignore::empty()) - } - - /// Returns the directory of this override set. - /// - /// All matches are done relative to this path. - pub fn path(&self) -> &Path { - self.0.path() - } - - /// Returns true if and only if this matcher is empty. - /// - /// When a matcher is empty, it will never match any file path. - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } - - /// Returns the total number of ignore globs. - pub fn num_ignores(&self) -> u64 { - self.0.num_whitelists() - } - - /// Returns the total number of whitelisted globs. - pub fn num_whitelists(&self) -> u64 { - self.0.num_ignores() - } - - /// Returns whether the given file path matched a pattern in this override - /// matcher. - /// - /// `is_dir` should be true if the path refers to a directory and false - /// otherwise. - /// - /// If there are no overrides, then this always returns `Match::None`. - /// - /// If there is at least one whitelist override and `is_dir` is false, then - /// this never returns `Match::None`, since non-matches are interpreted as - /// ignored. - /// - /// The given path is matched to the globs relative to the path given - /// when building the override matcher. Specifically, before matching - /// `path`, its prefix (as determined by a common suffix of the directory - /// given) is stripped. If there is no common suffix/prefix overlap, then - /// `path` is assumed to reside in the same directory as the root path for - /// this set of overrides. - pub fn matched<'a, P: AsRef>( - &'a self, - path: P, - is_dir: bool, - ) -> Match> { - if self.is_empty() { - return Match::None; - } - let mat = self.0.matched(path, is_dir).invert(); - if mat.is_none() && self.num_whitelists() > 0 && !is_dir { - return Match::Ignore(Glob::unmatched()); - } - mat.map(move |giglob| Glob(GlobInner::Matched(giglob))) - } -} - -/// Builds a matcher for a set of glob overrides. -pub struct OverrideBuilder { - builder: GitignoreBuilder, -} - -impl OverrideBuilder { - /// Create a new override builder. - /// - /// Matching is done relative to the directory path provided. - pub fn new>(path: P) -> OverrideBuilder { - OverrideBuilder { - builder: GitignoreBuilder::new(path), - } - } - - /// Builds a new override matcher from the globs added so far. - /// - /// Once a matcher is built, no new globs can be added to it. - pub fn build(&self) -> Result { - Ok(Override(try!(self.builder.build()))) - } - - /// Add a glob to the set of overrides. - /// - /// Globs provided here have precisely the same semantics as a single - /// line in a `gitignore` file, where the meaning of `!` is inverted: - /// namely, `!` at the beginning of a glob will ignore a file. Without `!`, - /// all matches of the glob provided are treated as whitelist matches. - pub fn add(&mut self, glob: &str) -> Result<&mut OverrideBuilder, Error> { - try!(self.builder.add_line(None, glob)); - Ok(self) - } - - /// Toggle whether the globs should be matched case insensitively or not. - /// - /// This is disabled by default. - pub fn case_insensitive( - &mut self, yes: bool - ) -> Result<&mut OverrideBuilder, Error> { - try!(self.builder.case_insensitive(yes)); - Ok(self) - } -} - -#[cfg(test)] -mod tests { - use super::{Override, OverrideBuilder}; - - const ROOT: &'static str = "/home/andrew/foo"; - - fn ov(globs: &[&str]) -> Override { - let mut builder = OverrideBuilder::new(ROOT); - for glob in globs { - builder.add(glob).unwrap(); - } - builder.build().unwrap() - } - - #[test] - fn empty() { - let ov = ov(&[]); - assert!(ov.matched("a.foo", false).is_none()); - assert!(ov.matched("a", false).is_none()); - assert!(ov.matched("", false).is_none()); - } - - #[test] - fn simple() { - let ov = ov(&["*.foo", "!*.bar"]); - assert!(ov.matched("a.foo", false).is_whitelist()); - assert!(ov.matched("a.foo", true).is_whitelist()); - assert!(ov.matched("a.rs", false).is_ignore()); - assert!(ov.matched("a.rs", true).is_none()); - assert!(ov.matched("a.bar", false).is_ignore()); - assert!(ov.matched("a.bar", true).is_ignore()); - } - - #[test] - fn only_ignores() { - let ov = ov(&["!*.bar"]); - assert!(ov.matched("a.rs", false).is_none()); - assert!(ov.matched("a.rs", true).is_none()); - assert!(ov.matched("a.bar", false).is_ignore()); - assert!(ov.matched("a.bar", true).is_ignore()); - } - - #[test] - fn precedence() { - let ov = ov(&["*.foo", "!*.bar.foo"]); - assert!(ov.matched("a.foo", false).is_whitelist()); - assert!(ov.matched("a.baz", false).is_ignore()); - assert!(ov.matched("a.bar.foo", false).is_ignore()); - } - - #[test] - fn gitignore() { - let ov = ov(&["/foo", "bar/*.rs", "baz/**"]); - assert!(ov.matched("bar/wat/lib.rs", false).is_ignore()); - assert!(ov.matched("wat/bar/lib.rs", false).is_whitelist()); - assert!(ov.matched("foo", false).is_whitelist()); - assert!(ov.matched("wat/foo", false).is_ignore()); - assert!(ov.matched("baz", false).is_ignore()); - assert!(ov.matched("baz/a", false).is_whitelist()); - assert!(ov.matched("baz/a/b", false).is_whitelist()); - } - - #[test] - fn allow_directories() { - // This tests that directories are NOT ignored when they are unmatched. - let ov = ov(&["*.rs"]); - assert!(ov.matched("foo.rs", false).is_whitelist()); - assert!(ov.matched("foo.c", false).is_ignore()); - assert!(ov.matched("foo", false).is_ignore()); - assert!(ov.matched("foo", true).is_none()); - assert!(ov.matched("src/foo.rs", false).is_whitelist()); - assert!(ov.matched("src/foo.c", false).is_ignore()); - assert!(ov.matched("src/foo", false).is_ignore()); - assert!(ov.matched("src/foo", true).is_none()); - } - - #[test] - fn absolute_path() { - let ov = ov(&["!/bar"]); - assert!(ov.matched("./foo/bar", false).is_none()); - } - - #[test] - fn case_insensitive() { - let ov = OverrideBuilder::new(ROOT) - .case_insensitive(true).unwrap() - .add("*.html").unwrap() - .build().unwrap(); - assert!(ov.matched("foo.html", false).is_whitelist()); - assert!(ov.matched("foo.HTML", false).is_whitelist()); - assert!(ov.matched("foo.htm", false).is_ignore()); - assert!(ov.matched("foo.HTM", false).is_ignore()); - } - - #[test] - fn default_case_sensitive() { - let ov = OverrideBuilder::new(ROOT) - .add("*.html").unwrap() - .build().unwrap(); - assert!(ov.matched("foo.html", false).is_whitelist()); - assert!(ov.matched("foo.HTML", false).is_ignore()); - assert!(ov.matched("foo.htm", false).is_ignore()); - assert!(ov.matched("foo.HTM", false).is_ignore()); - } -} diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/src/pathutil.rs cargo-0.26.0/vendor/ignore-0.2.2/src/pathutil.rs --- cargo-0.25.0/vendor/ignore-0.2.2/src/pathutil.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/src/pathutil.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,108 +0,0 @@ -use std::ffi::OsStr; -use std::path::Path; - -/// Returns true if and only if this file path is considered to be hidden. -#[cfg(unix)] -pub fn is_hidden>(path: P) -> bool { - use std::os::unix::ffi::OsStrExt; - - if let Some(name) = file_name(path.as_ref()) { - name.as_bytes().get(0) == Some(&b'.') - } else { - false - } -} - -/// Returns true if and only if this file path is considered to be hidden. -#[cfg(not(unix))] -pub fn is_hidden>(path: P) -> bool { - if let Some(name) = file_name(path.as_ref()) { - name.to_str().map(|s| s.starts_with(".")).unwrap_or(false) - } else { - false - } -} - -/// Strip `prefix` from the `path` and return the remainder. -/// -/// If `path` doesn't have a prefix `prefix`, then return `None`. -#[cfg(unix)] -pub fn strip_prefix<'a, P: AsRef + ?Sized>( - prefix: &'a P, - path: &'a Path, -) -> Option<&'a Path> { - use std::os::unix::ffi::OsStrExt; - - let prefix = prefix.as_ref().as_os_str().as_bytes(); - let path = path.as_os_str().as_bytes(); - if prefix.len() > path.len() || prefix != &path[0..prefix.len()] { - None - } else { - Some(&Path::new(OsStr::from_bytes(&path[prefix.len()..]))) - } -} - -/// Strip `prefix` from the `path` and return the remainder. -/// -/// If `path` doesn't have a prefix `prefix`, then return `None`. -#[cfg(not(unix))] -pub fn strip_prefix<'a, P: AsRef + ?Sized>( - prefix: &'a P, - path: &'a Path, -) -> Option<&'a Path> { - path.strip_prefix(prefix).ok() -} - -/// Returns true if this file path is just a file name. i.e., Its parent is -/// the empty string. -#[cfg(unix)] -pub fn is_file_name>(path: P) -> bool { - use std::os::unix::ffi::OsStrExt; - use memchr::memchr; - - let path = path.as_ref().as_os_str().as_bytes(); - memchr(b'/', path).is_none() -} - -/// Returns true if this file path is just a file name. i.e., Its parent is -/// the empty string. -#[cfg(not(unix))] -pub fn is_file_name>(path: P) -> bool { - path.as_ref().parent().map(|p| p.as_os_str().is_empty()).unwrap_or(false) -} - -/// The final component of the path, if it is a normal file. -/// -/// If the path terminates in ., .., or consists solely of a root of prefix, -/// file_name will return None. -#[cfg(unix)] -pub fn file_name<'a, P: AsRef + ?Sized>( - path: &'a P, -) -> Option<&'a OsStr> { - use std::os::unix::ffi::OsStrExt; - use memchr::memrchr; - - let path = path.as_ref().as_os_str().as_bytes(); - if path.is_empty() { - return None; - } else if path.len() == 1 && path[0] == b'.' { - return None; - } else if path.last() == Some(&b'.') { - return None; - } else if path.len() >= 2 && &path[path.len() - 2..] == &b".."[..] { - return None; - } - let last_slash = memrchr(b'/', path).map(|i| i + 1).unwrap_or(0); - Some(OsStr::from_bytes(&path[last_slash..])) -} - -/// The final component of the path, if it is a normal file. -/// -/// If the path terminates in ., .., or consists solely of a root of prefix, -/// file_name will return None. -#[cfg(not(unix))] -pub fn file_name<'a, P: AsRef + ?Sized>( - path: &'a P, -) -> Option<&'a OsStr> { - path.as_ref().file_name() -} diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/src/types.rs cargo-0.26.0/vendor/ignore-0.2.2/src/types.rs --- cargo-0.25.0/vendor/ignore-0.2.2/src/types.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/src/types.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,686 +0,0 @@ -/*! -The types module provides a way of associating globs on file names to file -types. - -This can be used to match specific types of files. For example, among -the default file types provided, the Rust file type is defined to be `*.rs` -with name `rust`. Similarly, the C file type is defined to be `*.{c,h}` with -name `c`. - -Note that the set of default types may change over time. - -# Example - -This shows how to create and use a simple file type matcher using the default -file types defined in this crate. - -``` -use ignore::types::TypesBuilder; - -let mut builder = TypesBuilder::new(); -builder.add_defaults(); -builder.select("rust"); -let matcher = builder.build().unwrap(); - -assert!(matcher.matched("foo.rs", false).is_whitelist()); -assert!(matcher.matched("foo.c", false).is_ignore()); -``` - -# Example: negation - -This is like the previous example, but shows how negating a file type works. -That is, this will let us match file paths that *don't* correspond to a -particular file type. - -``` -use ignore::types::TypesBuilder; - -let mut builder = TypesBuilder::new(); -builder.add_defaults(); -builder.negate("c"); -let matcher = builder.build().unwrap(); - -assert!(matcher.matched("foo.rs", false).is_none()); -assert!(matcher.matched("foo.c", false).is_ignore()); -``` - -# Example: custom file type definitions - -This shows how to extend this library default file type definitions with -your own. - -``` -use ignore::types::TypesBuilder; - -let mut builder = TypesBuilder::new(); -builder.add_defaults(); -builder.add("foo", "*.foo"); -// Another way of adding a file type definition. -// This is useful when accepting input from an end user. -builder.add_def("bar:*.bar"); -// Note: we only select `foo`, not `bar`. -builder.select("foo"); -let matcher = builder.build().unwrap(); - -assert!(matcher.matched("x.foo", false).is_whitelist()); -// This is ignored because we only selected the `foo` file type. -assert!(matcher.matched("x.bar", false).is_ignore()); -``` - -We can also add file type definitions based on other definitions. - -``` -use ignore::types::TypesBuilder; - -let mut builder = TypesBuilder::new(); -builder.add_defaults(); -builder.add("foo", "*.foo"); -builder.add_def("bar:include:foo,cpp"); -builder.select("bar"); -let matcher = builder.build().unwrap(); - -assert!(matcher.matched("x.foo", false).is_whitelist()); -assert!(matcher.matched("y.cpp", false).is_whitelist()); -``` -*/ - -use std::cell::RefCell; -use std::collections::HashMap; -use std::path::Path; -use std::sync::Arc; - -use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; -use regex::Regex; -use thread_local::ThreadLocal; - -use pathutil::file_name; -use {Error, Match}; - -const DEFAULT_TYPES: &'static [(&'static str, &'static [&'static str])] = &[ - ("agda", &["*.agda", "*.lagda"]), - ("asciidoc", &["*.adoc", "*.asc", "*.asciidoc"]), - ("asm", &["*.asm", "*.s", "*.S"]), - ("awk", &["*.awk"]), - ("c", &["*.c", "*.h", "*.H"]), - ("cabal", &["*.cabal"]), - ("cbor", &["*.cbor"]), - ("ceylon", &["*.ceylon"]), - ("clojure", &["*.clj", "*.cljc", "*.cljs", "*.cljx"]), - ("cmake", &["*.cmake", "CMakeLists.txt"]), - ("coffeescript", &["*.coffee"]), - ("creole", &["*.creole"]), - ("config", &["*.config"]), - ("cpp", &[ - "*.C", "*.cc", "*.cpp", "*.cxx", - "*.h", "*.H", "*.hh", "*.hpp", "*.inl", - ]), - ("crystal", &["Projectfile", "*.cr"]), - ("cs", &["*.cs"]), - ("csharp", &["*.cs"]), - ("cshtml", &["*.cshtml"]), - ("css", &["*.css", "*.scss"]), - ("cython", &["*.pyx"]), - ("dart", &["*.dart"]), - ("d", &["*.d"]), - ("elisp", &["*.el"]), - ("elixir", &["*.ex", "*.eex", "*.exs"]), - ("erlang", &["*.erl", "*.hrl"]), - ("fish", &["*.fish"]), - ("fortran", &[ - "*.f", "*.F", "*.f77", "*.F77", "*.pfo", - "*.f90", "*.F90", "*.f95", "*.F95", - ]), - ("fsharp", &["*.fs", "*.fsx", "*.fsi"]), - ("go", &["*.go"]), - ("groovy", &["*.groovy", "*.gradle"]), - ("h", &["*.h", "*.hpp"]), - ("hbs", &["*.hbs"]), - ("haskell", &["*.hs", "*.lhs"]), - ("html", &["*.htm", "*.html", "*.ejs"]), - ("java", &["*.java"]), - ("jinja", &["*.jinja", "*.jinja2"]), - ("js", &[ - "*.js", "*.jsx", "*.vue", - ]), - ("json", &["*.json"]), - ("jsonl", &["*.jsonl"]), - ("julia", &["*.jl"]), - ("kotlin", &["*.kt", "*.kts"]), - ("less", &["*.less"]), - ("lisp", &["*.el", "*.jl", "*.lisp", "*.lsp", "*.sc", "*.scm"]), - ("log", &["*.log"]), - ("lua", &["*.lua"]), - ("m4", &["*.ac", "*.m4"]), - ("make", &["gnumakefile", "Gnumakefile", "makefile", "Makefile", "*.mk", "*.mak"]), - ("markdown", &["*.markdown", "*.md", "*.mdown", "*.mkdn"]), - ("md", &["*.markdown", "*.md", "*.mdown", "*.mkdn"]), - ("matlab", &["*.m"]), - ("mk", &["mkfile"]), - ("ml", &["*.ml"]), - ("msbuild", &["*.csproj", "*.fsproj", "*.vcxproj", "*.proj", "*.props", "*.targets"]), - ("nim", &["*.nim"]), - ("nix", &["*.nix"]), - ("objc", &["*.h", "*.m"]), - ("objcpp", &["*.h", "*.mm"]), - ("ocaml", &["*.ml", "*.mli", "*.mll", "*.mly"]), - ("org", &["*.org"]), - ("perl", &["*.perl", "*.pl", "*.PL", "*.plh", "*.plx", "*.pm", "*.t"]), - ("pdf", &["*.pdf"]), - ("php", &["*.php", "*.php3", "*.php4", "*.php5", "*.phtml"]), - ("pod", &["*.pod"]), - ("ps", &["*.cdxml", "*.ps1", "*.ps1xml", "*.psd1", "*.psm1"]), - ("py", &["*.py"]), - ("qmake", &["*.pro", "*.pri"]), - ("readme", &["README*", "*README"]), - ("r", &["*.R", "*.r", "*.Rmd", "*.Rnw"]), - ("rdoc", &["*.rdoc"]), - ("rst", &["*.rst"]), - ("ruby", &["Gemfile", "*.gemspec", ".irbrc", "Rakefile", "*.rb"]), - ("rust", &["*.rs"]), - ("sass", &["*.sass", "*.scss"]), - ("scala", &["*.scala"]), - ("sh", &["*.bash", "*.csh", "*.ksh", "*.sh", "*.tcsh"]), - ("spark", &["*.spark"]), - ("stylus", &["*.styl"]), - ("sql", &["*.sql"]), - ("sv", &["*.v", "*.vg", "*.sv", "*.svh", "*.h"]), - ("svg", &["*.svg"]), - ("swift", &["*.swift"]), - ("swig", &["*.def", "*.i"]), - ("taskpaper", &["*.taskpaper"]), - ("tcl", &["*.tcl"]), - ("tex", &["*.tex", "*.ltx", "*.cls", "*.sty", "*.bib"]), - ("textile", &["*.textile"]), - ("ts", &["*.ts", "*.tsx"]), - ("txt", &["*.txt"]), - ("toml", &["*.toml", "Cargo.lock"]), - ("twig", &["*.twig"]), - ("vala", &["*.vala"]), - ("vb", &["*.vb"]), - ("vim", &["*.vim"]), - ("vimscript", &["*.vim"]), - ("wiki", &["*.mediawiki", "*.wiki"]), - ("xml", &["*.xml"]), - ("yacc", &["*.y"]), - ("yaml", &["*.yaml", "*.yml"]), - ("yocto", &["*.bb", "*.bbappend", "*.bbclass"]), - ("zsh", &["zshenv", ".zshenv", "zprofile", ".zprofile", "zshrc", ".zshrc", "zlogin", ".zlogin", "zlogout", ".zlogout", "*.zsh"]), -]; - -/// Glob represents a single glob in a set of file type definitions. -/// -/// There may be more than one glob for a particular file type. -/// -/// This is used to report information about the highest precedent glob -/// that matched. -/// -/// Note that not all matches necessarily correspond to a specific glob. -/// For example, if there are one or more selections and a file path doesn't -/// match any of those selections, then the file path is considered to be -/// ignored. -/// -/// The lifetime `'a` refers to the lifetime of the underlying file type -/// definition, which corresponds to the lifetime of the file type matcher. -#[derive(Clone, Debug)] -pub struct Glob<'a>(GlobInner<'a>); - -#[derive(Clone, Debug)] -enum GlobInner<'a> { - /// No glob matched, but the file path should still be ignored. - UnmatchedIgnore, - /// A glob matched. - Matched { - /// The file type definition which provided the glob. - def: &'a FileTypeDef, - /// The index of the glob that matched inside the file type definition. - which: usize, - /// Whether the selection was negated or not. - negated: bool, - } -} - -impl<'a> Glob<'a> { - fn unmatched() -> Glob<'a> { - Glob(GlobInner::UnmatchedIgnore) - } -} - -/// A single file type definition. -/// -/// File type definitions can be retrieved in aggregate from a file type -/// matcher. File type definitions are also reported when its responsible -/// for a match. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct FileTypeDef { - name: String, - globs: Vec, -} - -impl FileTypeDef { - /// Return the name of this file type. - pub fn name(&self) -> &str { - &self.name - } - - /// Return the globs used to recognize this file type. - pub fn globs(&self) -> &[String] { - &self.globs - } -} - -/// Types is a file type matcher. -#[derive(Clone, Debug)] -pub struct Types { - /// All of the file type definitions, sorted lexicographically by name. - defs: Vec, - /// All of the selections made by the user. - selections: Vec>, - /// Whether there is at least one Selection::Select in our selections. - /// When this is true, a Match::None is converted to Match::Ignore. - has_selected: bool, - /// A mapping from glob index in the set to two indices. The first is an - /// index into `selections` and the second is an index into the - /// corresponding file type definition's list of globs. - glob_to_selection: Vec<(usize, usize)>, - /// The set of all glob selections, used for actual matching. - set: GlobSet, - /// Temporary storage for globs that match. - matches: Arc>>>, -} - -/// Indicates the type of a selection for a particular file type. -#[derive(Clone, Debug)] -enum Selection { - Select(String, T), - Negate(String, T), -} - -impl Selection { - fn is_negated(&self) -> bool { - match *self { - Selection::Select(..) => false, - Selection::Negate(..) => true, - } - } - - fn name(&self) -> &str { - match *self { - Selection::Select(ref name, _) => name, - Selection::Negate(ref name, _) => name, - } - } - - fn map U>(self, f: F) -> Selection { - match self { - Selection::Select(name, inner) => { - Selection::Select(name, f(inner)) - } - Selection::Negate(name, inner) => { - Selection::Negate(name, f(inner)) - } - } - } - - fn inner(&self) -> &T { - match *self { - Selection::Select(_, ref inner) => inner, - Selection::Negate(_, ref inner) => inner, - } - } -} - -impl Types { - /// Creates a new file type matcher that never matches any path and - /// contains no file type definitions. - pub fn empty() -> Types { - Types { - defs: vec![], - selections: vec![], - has_selected: false, - glob_to_selection: vec![], - set: GlobSetBuilder::new().build().unwrap(), - matches: Arc::new(ThreadLocal::default()), - } - } - - /// Returns true if and only if this matcher has zero selections. - pub fn is_empty(&self) -> bool { - self.selections.is_empty() - } - - /// Returns the number of selections used in this matcher. - pub fn len(&self) -> usize { - self.selections.len() - } - - /// Return the set of current file type definitions. - /// - /// Definitions and globs are sorted. - pub fn definitions(&self) -> &[FileTypeDef] { - &self.defs - } - - /// Returns a match for the given path against this file type matcher. - /// - /// The path is considered whitelisted if it matches a selected file type. - /// The path is considered ignored if it matches a negated file type. - /// If at least one file type is selected and `path` doesn't match, then - /// the path is also considered ignored. - pub fn matched<'a, P: AsRef>( - &'a self, - path: P, - is_dir: bool, - ) -> Match> { - // File types don't apply to directories, and we can't do anything - // if our glob set is empty. - if is_dir || self.set.is_empty() { - return Match::None; - } - // We only want to match against the file name, so extract it. - // If one doesn't exist, then we can't match it. - let name = match file_name(path.as_ref()) { - Some(name) => name, - None if self.has_selected => { - return Match::Ignore(Glob::unmatched()); - } - None => { - return Match::None; - } - }; - let mut matches = self.matches.get_default().borrow_mut(); - self.set.matches_into(name, &mut *matches); - // The highest precedent match is the last one. - if let Some(&i) = matches.last() { - let (isel, iglob) = self.glob_to_selection[i]; - let sel = &self.selections[isel]; - let glob = Glob(GlobInner::Matched { - def: sel.inner(), - which: iglob, - negated: sel.is_negated(), - }); - return if sel.is_negated() { - Match::Ignore(glob) - } else { - Match::Whitelist(glob) - }; - } - if self.has_selected { - Match::Ignore(Glob::unmatched()) - } else { - Match::None - } - } -} - -/// TypesBuilder builds a type matcher from a set of file type definitions and -/// a set of file type selections. -pub struct TypesBuilder { - types: HashMap, - selections: Vec>, -} - -impl TypesBuilder { - /// Create a new builder for a file type matcher. - /// - /// The builder contains *no* type definitions to start with. A set - /// of default type definitions can be added with `add_defaults`, and - /// additional type definitions can be added with `select` and `negate`. - pub fn new() -> TypesBuilder { - TypesBuilder { - types: HashMap::new(), - selections: vec![], - } - } - - /// Build the current set of file type definitions *and* selections into - /// a file type matcher. - pub fn build(&self) -> Result { - let defs = self.definitions(); - let has_selected = self.selections.iter().any(|s| !s.is_negated()); - - let mut selections = vec![]; - let mut glob_to_selection = vec![]; - let mut build_set = GlobSetBuilder::new(); - for (isel, selection) in self.selections.iter().enumerate() { - let def = match self.types.get(selection.name()) { - Some(def) => def.clone(), - None => { - let name = selection.name().to_string(); - return Err(Error::UnrecognizedFileType(name)); - } - }; - for (iglob, glob) in def.globs.iter().enumerate() { - build_set.add(try!( - GlobBuilder::new(glob) - .literal_separator(true) - .build() - .map_err(|err| { - Error::Glob { - glob: Some(glob.to_string()), - err: err.kind().to_string(), - } - }))); - glob_to_selection.push((isel, iglob)); - } - selections.push(selection.clone().map(move |_| def)); - } - let set = try!(build_set.build().map_err(|err| { - Error::Glob { glob: None, err: err.to_string() } - })); - Ok(Types { - defs: defs, - selections: selections, - has_selected: has_selected, - glob_to_selection: glob_to_selection, - set: set, - matches: Arc::new(ThreadLocal::default()), - }) - } - - /// Return the set of current file type definitions. - /// - /// Definitions and globs are sorted. - pub fn definitions(&self) -> Vec { - let mut defs = vec![]; - for def in self.types.values() { - let mut def = def.clone(); - def.globs.sort(); - defs.push(def); - } - defs.sort_by(|def1, def2| def1.name().cmp(def2.name())); - defs - } - - /// Select the file type given by `name`. - /// - /// If `name` is `all`, then all file types currently defined are selected. - pub fn select(&mut self, name: &str) -> &mut TypesBuilder { - if name == "all" { - for name in self.types.keys() { - self.selections.push(Selection::Select(name.to_string(), ())); - } - } else { - self.selections.push(Selection::Select(name.to_string(), ())); - } - self - } - - /// Ignore the file type given by `name`. - /// - /// If `name` is `all`, then all file types currently defined are negated. - pub fn negate(&mut self, name: &str) -> &mut TypesBuilder { - if name == "all" { - for name in self.types.keys() { - self.selections.push(Selection::Negate(name.to_string(), ())); - } - } else { - self.selections.push(Selection::Negate(name.to_string(), ())); - } - self - } - - /// Clear any file type definitions for the type name given. - pub fn clear(&mut self, name: &str) -> &mut TypesBuilder { - self.types.remove(name); - self - } - - /// Add a new file type definition. `name` can be arbitrary and `pat` - /// should be a glob recognizing file paths belonging to the `name` type. - /// - /// If `name` is `all` or otherwise contains any character that is not a - /// Unicode letter or number, then an error is returned. - pub fn add(&mut self, name: &str, glob: &str) -> Result<(), Error> { - lazy_static! { - static ref RE: Regex = Regex::new(r"^[\pL\pN]+$").unwrap(); - }; - if name == "all" || !RE.is_match(name) { - return Err(Error::InvalidDefinition); - } - let (key, glob) = (name.to_string(), glob.to_string()); - self.types.entry(key).or_insert_with(|| { - FileTypeDef { name: name.to_string(), globs: vec![] } - }).globs.push(glob); - Ok(()) - } - - /// Add a new file type definition specified in string form. There are two - /// valid formats: - /// 1. `{name}:{glob}`. This defines a 'root' definition that associates the - /// given name with the given glob. - /// 2. `{name}:include:{comma-separated list of already defined names}. - /// This defines an 'include' definition that associates the given name - /// with the definitions of the given existing types. - /// Names may not include any characters that are not - /// Unicode letters or numbers. - pub fn add_def(&mut self, def: &str) -> Result<(), Error> { - let parts: Vec<&str> = def.split(':').collect(); - match parts.len() { - 2 => { - let name = parts[0]; - let glob = parts[1]; - if name.is_empty() || glob.is_empty() { - return Err(Error::InvalidDefinition); - } - self.add(name, glob) - } - 3 => { - let name = parts[0]; - let types_string = parts[2]; - if name.is_empty() || parts[1] != "include" || types_string.is_empty() { - return Err(Error::InvalidDefinition); - } - let types = types_string.split(','); - // Check ahead of time to ensure that all types specified are - // present and fail fast if not. - if types.clone().any(|t| !self.types.contains_key(t)) { - return Err(Error::InvalidDefinition); - } - for type_name in types { - let globs = self.types.get(type_name).unwrap().globs.clone(); - for glob in globs { - try!(self.add(name, &glob)); - } - } - Ok(()) - } - _ => Err(Error::InvalidDefinition) - } - } - - /// Add a set of default file type definitions. - pub fn add_defaults(&mut self) -> &mut TypesBuilder { - static MSG: &'static str = "adding a default type should never fail"; - for &(name, exts) in DEFAULT_TYPES { - for ext in exts { - self.add(name, ext).expect(MSG); - } - } - self - } -} - -#[cfg(test)] -mod tests { - use super::TypesBuilder; - - macro_rules! matched { - ($name:ident, $types:expr, $sel:expr, $selnot:expr, - $path:expr) => { - matched!($name, $types, $sel, $selnot, $path, true); - }; - (not, $name:ident, $types:expr, $sel:expr, $selnot:expr, - $path:expr) => { - matched!($name, $types, $sel, $selnot, $path, false); - }; - ($name:ident, $types:expr, $sel:expr, $selnot:expr, - $path:expr, $matched:expr) => { - #[test] - fn $name() { - let mut btypes = TypesBuilder::new(); - for tydef in $types { - btypes.add_def(tydef).unwrap(); - } - for sel in $sel { - btypes.select(sel); - } - for selnot in $selnot { - btypes.negate(selnot); - } - let types = btypes.build().unwrap(); - let mat = types.matched($path, false); - assert_eq!($matched, !mat.is_ignore()); - } - }; - } - - fn types() -> Vec<&'static str> { - vec![ - "html:*.html", - "html:*.htm", - "rust:*.rs", - "js:*.js", - "foo:*.{rs,foo}", - "combo:include:html,rust" - ] - } - - matched!(match1, types(), vec!["rust"], vec![], "lib.rs"); - matched!(match2, types(), vec!["html"], vec![], "index.html"); - matched!(match3, types(), vec!["html"], vec![], "index.htm"); - matched!(match4, types(), vec!["html", "rust"], vec![], "main.rs"); - matched!(match5, types(), vec![], vec![], "index.html"); - matched!(match6, types(), vec![], vec!["rust"], "index.html"); - matched!(match7, types(), vec!["foo"], vec!["rust"], "main.foo"); - matched!(match8, types(), vec!["combo"], vec![], "index.html"); - matched!(match9, types(), vec!["combo"], vec![], "lib.rs"); - - matched!(not, matchnot1, types(), vec!["rust"], vec![], "index.html"); - matched!(not, matchnot2, types(), vec![], vec!["rust"], "main.rs"); - matched!(not, matchnot3, types(), vec!["foo"], vec!["rust"], "main.rs"); - matched!(not, matchnot4, types(), vec!["rust"], vec!["foo"], "main.rs"); - matched!(not, matchnot5, types(), vec!["rust"], vec!["foo"], "main.foo"); - matched!(not, matchnot6, types(), vec!["combo"], vec![], "leftpad.js"); - - #[test] - fn test_invalid_defs() { - let mut btypes = TypesBuilder::new(); - for tydef in types() { - btypes.add_def(tydef).unwrap(); - } - // Preserve the original definitions for later comparison. - let original_defs = btypes.definitions(); - let bad_defs = vec![ - // Reference to type that does not exist - "combo:include:html,python", - // Bad format - "combo:foobar:html,rust", - "" - ]; - for def in bad_defs { - assert!(btypes.add_def(def).is_err()); - // Ensure that nothing changed, even if some of the includes were valid. - assert_eq!(btypes.definitions(), original_defs); - } - } -} diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/src/walk.rs cargo-0.26.0/vendor/ignore-0.2.2/src/walk.rs --- cargo-0.25.0/vendor/ignore-0.2.2/src/walk.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/src/walk.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1565 +0,0 @@ -use std::cmp; -use std::ffi::{OsStr, OsString}; -use std::fmt; -use std::fs::{self, FileType, Metadata}; -use std::io; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::thread; -use std::time::Duration; -use std::vec; - -use crossbeam::sync::MsQueue; -use walkdir::{self, WalkDir, WalkDirIterator, is_same_file}; - -use dir::{Ignore, IgnoreBuilder}; -use gitignore::GitignoreBuilder; -use overrides::Override; -use types::Types; -use {Error, PartialErrorBuilder}; - -/// A directory entry with a possible error attached. -/// -/// The error typically refers to a problem parsing ignore files in a -/// particular directory. -#[derive(Debug)] -pub struct DirEntry { - dent: DirEntryInner, - err: Option, -} - -impl DirEntry { - /// The full path that this entry represents. - pub fn path(&self) -> &Path { - self.dent.path() - } - - /// Whether this entry corresponds to a symbolic link or not. - pub fn path_is_symbolic_link(&self) -> bool { - self.dent.path_is_symbolic_link() - } - - /// Returns true if and only if this entry corresponds to stdin. - /// - /// i.e., The entry has depth 0 and its file name is `-`. - pub fn is_stdin(&self) -> bool { - self.dent.is_stdin() - } - - /// Return the metadata for the file that this entry points to. - pub fn metadata(&self) -> Result { - self.dent.metadata() - } - - /// Return the file type for the file that this entry points to. - /// - /// This entry doesn't have a file type if it corresponds to stdin. - pub fn file_type(&self) -> Option { - self.dent.file_type() - } - - /// Return the file name of this entry. - /// - /// If this entry has no file name (e.g., `/`), then the full path is - /// returned. - pub fn file_name(&self) -> &OsStr { - self.dent.file_name() - } - - /// Returns the depth at which this entry was created relative to the root. - pub fn depth(&self) -> usize { - self.dent.depth() - } - - /// Returns the underlying inode number if one exists. - /// - /// If this entry doesn't have an inode number, then `None` is returned. - #[cfg(unix)] - pub fn ino(&self) -> Option { - self.dent.ino() - } - - /// Returns an error, if one exists, associated with processing this entry. - /// - /// An example of an error is one that occurred while parsing an ignore - /// file. - pub fn error(&self) -> Option<&Error> { - self.err.as_ref() - } - - fn new_stdin() -> DirEntry { - DirEntry { - dent: DirEntryInner::Stdin, - err: None, - } - } - - fn new_walkdir(dent: walkdir::DirEntry, err: Option) -> DirEntry { - DirEntry { - dent: DirEntryInner::Walkdir(dent), - err: err, - } - } - - fn new_raw(dent: DirEntryRaw, err: Option) -> DirEntry { - DirEntry { - dent: DirEntryInner::Raw(dent), - err: err, - } - } -} - -/// DirEntryInner is the implementation of DirEntry. -/// -/// It specifically represents three distinct sources of directory entries: -/// -/// 1. From the walkdir crate. -/// 2. Special entries that represent things like stdin. -/// 3. From a path. -/// -/// Specifically, (3) has to essentially re-create the DirEntry implementation -/// from WalkDir. -#[derive(Debug)] -enum DirEntryInner { - Stdin, - Walkdir(walkdir::DirEntry), - Raw(DirEntryRaw), -} - -impl DirEntryInner { - fn path(&self) -> &Path { - use self::DirEntryInner::*; - match *self { - Stdin => Path::new(""), - Walkdir(ref x) => x.path(), - Raw(ref x) => x.path(), - } - } - - fn path_is_symbolic_link(&self) -> bool { - use self::DirEntryInner::*; - match *self { - Stdin => false, - Walkdir(ref x) => x.path_is_symbolic_link(), - Raw(ref x) => x.path_is_symbolic_link(), - } - } - - fn is_stdin(&self) -> bool { - match *self { - DirEntryInner::Stdin => true, - _ => false, - } - } - - fn metadata(&self) -> Result { - use self::DirEntryInner::*; - match *self { - Stdin => { - let err = Error::Io(io::Error::new( - io::ErrorKind::Other, " has no metadata")); - Err(err.with_path("")) - } - Walkdir(ref x) => { - x.metadata().map_err(|err| { - Error::Io(io::Error::from(err)).with_path(x.path()) - }) - } - Raw(ref x) => x.metadata(), - } - } - - fn file_type(&self) -> Option { - use self::DirEntryInner::*; - match *self { - Stdin => None, - Walkdir(ref x) => Some(x.file_type()), - Raw(ref x) => Some(x.file_type()), - } - } - - fn file_name(&self) -> &OsStr { - use self::DirEntryInner::*; - match *self { - Stdin => OsStr::new(""), - Walkdir(ref x) => x.file_name(), - Raw(ref x) => x.file_name(), - } - } - - fn depth(&self) -> usize { - use self::DirEntryInner::*; - match *self { - Stdin => 0, - Walkdir(ref x) => x.depth(), - Raw(ref x) => x.depth(), - } - } - - #[cfg(unix)] - fn ino(&self) -> Option { - use self::DirEntryInner::*; - match *self { - Stdin => None, - Walkdir(ref x) => Some(x.ino()), - Raw(ref x) => Some(x.ino()), - } - } -} - -/// DirEntryRaw is essentially copied from the walkdir crate so that we can -/// build `DirEntry`s from whole cloth in the parallel iterator. -struct DirEntryRaw { - /// The path as reported by the `fs::ReadDir` iterator (even if it's a - /// symbolic link). - path: PathBuf, - /// The file type. Necessary for recursive iteration, so store it. - ty: FileType, - /// Is set when this entry was created from a symbolic link and the user - /// expects the iterator to follow symbolic links. - follow_link: bool, - /// The depth at which this entry was generated relative to the root. - depth: usize, - /// The underlying inode number (Unix only). - #[cfg(unix)] - ino: u64, -} - -impl fmt::Debug for DirEntryRaw { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Leaving out FileType because it doesn't have a debug impl - // in Rust 1.9. We could add it if we really wanted to by manually - // querying each possibly file type. Meh. ---AG - f.debug_struct("DirEntryRaw") - .field("path", &self.path) - .field("follow_link", &self.follow_link) - .field("depth", &self.depth) - .finish() - } -} - -impl DirEntryRaw { - fn path(&self) -> &Path { - &self.path - } - - fn path_is_symbolic_link(&self) -> bool { - self.ty.is_symlink() || self.follow_link - } - - fn metadata(&self) -> Result { - if self.follow_link { - fs::metadata(&self.path) - } else { - fs::symlink_metadata(&self.path) - }.map_err(|err| Error::Io(io::Error::from(err)).with_path(&self.path)) - } - - fn file_type(&self) -> FileType { - self.ty - } - - fn file_name(&self) -> &OsStr { - self.path.file_name().unwrap_or_else(|| self.path.as_os_str()) - } - - fn depth(&self) -> usize { - self.depth - } - - #[cfg(unix)] - fn ino(&self) -> u64 { - self.ino - } - - fn from_entry( - depth: usize, - ent: &fs::DirEntry, - ) -> Result { - let ty = try!(ent.file_type().map_err(|err| { - let err = Error::Io(io::Error::from(err)).with_path(ent.path()); - Error::WithDepth { - depth: depth, - err: Box::new(err), - } - })); - Ok(DirEntryRaw::from_entry_os(depth, ent, ty)) - } - - #[cfg(not(unix))] - fn from_entry_os( - depth: usize, - ent: &fs::DirEntry, - ty: fs::FileType, - ) -> DirEntryRaw { - DirEntryRaw { - path: ent.path(), - ty: ty, - follow_link: false, - depth: depth, - } - } - - #[cfg(unix)] - fn from_entry_os( - depth: usize, - ent: &fs::DirEntry, - ty: fs::FileType, - ) -> DirEntryRaw { - use std::os::unix::fs::DirEntryExt; - - DirEntryRaw { - path: ent.path(), - ty: ty, - follow_link: false, - depth: depth, - ino: ent.ino(), - } - } - - #[cfg(not(unix))] - fn from_link(depth: usize, pb: PathBuf) -> Result { - let md = try!(fs::metadata(&pb).map_err(|err| { - Error::Io(err).with_path(&pb) - })); - Ok(DirEntryRaw { - path: pb, - ty: md.file_type(), - follow_link: true, - depth: depth, - }) - } - - #[cfg(unix)] - fn from_link(depth: usize, pb: PathBuf) -> Result { - use std::os::unix::fs::MetadataExt; - - let md = try!(fs::metadata(&pb).map_err(|err| { - Error::Io(err).with_path(&pb) - })); - Ok(DirEntryRaw { - path: pb, - ty: md.file_type(), - follow_link: true, - depth: depth, - ino: md.ino(), - }) - } -} - -/// WalkBuilder builds a recursive directory iterator. -/// -/// The builder supports a large number of configurable options. This includes -/// specific glob overrides, file type matching, toggling whether hidden -/// files are ignored or not, and of course, support for respecting gitignore -/// files. -/// -/// By default, all ignore files found are respected. This includes `.ignore`, -/// `.gitignore`, `.git/info/exclude` and even your global gitignore -/// globs, usually found in `$XDG_CONFIG_HOME/git/ignore`. -/// -/// Some standard recursive directory options are also supported, such as -/// limiting the recursive depth or whether to follow symbolic links (disabled -/// by default). -/// -/// # Ignore rules -/// -/// There are many rules that influence whether a particular file or directory -/// is skipped by this iterator. Those rules are documented here. Note that -/// the rules assume a default configuration. -/// -/// * First, glob overrides are checked. If a path matches a glob override, -/// then matching stops. The path is then only skipped if the glob that matched -/// the path is an ignore glob. (An override glob is a whitelist glob unless it -/// starts with a `!`, in which case it is an ignore glob.) -/// * Second, ignore files are checked. Ignore files currently only come from -/// git ignore files (`.gitignore`, `.git/info/exclude` and the configured -/// global gitignore file), plain `.ignore` files, which have the same format -/// as gitignore files, or explicitly added ignore files. The precedence order -/// is: `.ignore`, `.gitignore`, `.git/info/exclude`, global gitignore and -/// finally explicitly added ignore files. Note that precedence between -/// different types of ignore files is not impacted by the directory hierarchy; -/// any `.ignore` file overrides all `.gitignore` files. Within each precedence -/// level, more nested ignore files have a higher precedence than less nested -/// ignore files. -/// * Third, if the previous step yields an ignore match, then all matching -/// is stopped and the path is skipped. If it yields a whitelist match, then -/// matching continues. A whitelist match can be overridden by a later matcher. -/// * Fourth, unless the path is a directory, the file type matcher is run on -/// the path. As above, if it yields an ignore match, then all matching is -/// stopped and the path is skipped. If it yields a whitelist match, then -/// matching continues. -/// * Fifth, if the path hasn't been whitelisted and it is hidden, then the -/// path is skipped. -/// * Sixth, unless the path is a directory, the size of the file is compared -/// against the max filesize limit. If it exceeds the limit, it is skipped. -/// * Seventh, if the path has made it this far then it is yielded in the -/// iterator. -#[derive(Clone)] -pub struct WalkBuilder { - paths: Vec, - ig_builder: IgnoreBuilder, - parents: bool, - max_depth: Option, - max_filesize: Option, - follow_links: bool, - sorter: Option cmp::Ordering + 'static>>, - threads: usize, -} - -impl fmt::Debug for WalkBuilder { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("WalkBuilder") - .field("paths", &self.paths) - .field("ig_builder", &self.ig_builder) - .field("parents", &self.parents) - .field("max_depth", &self.max_depth) - .field("max_filesize", &self.max_filesize) - .field("follow_links", &self.follow_links) - .field("threads", &self.threads) - .finish() - } -} - -impl WalkBuilder { - /// Create a new builder for a recursive directory iterator for the - /// directory given. - /// - /// Note that if you want to traverse multiple different directories, it - /// is better to call `add` on this builder than to create multiple - /// `Walk` values. - pub fn new>(path: P) -> WalkBuilder { - WalkBuilder { - paths: vec![path.as_ref().to_path_buf()], - ig_builder: IgnoreBuilder::new(), - parents: true, - max_depth: None, - max_filesize: None, - follow_links: false, - sorter: None, - threads: 0, - } - } - - /// Build a new `Walk` iterator. - pub fn build(&self) -> Walk { - let follow_links = self.follow_links; - let max_depth = self.max_depth; - let cmp = self.sorter.clone(); - let its = self.paths.iter().map(move |p| { - if p == Path::new("-") { - (p.to_path_buf(), None) - } else { - let mut wd = WalkDir::new(p); - wd = wd.follow_links(follow_links || p.is_file()); - if let Some(max_depth) = max_depth { - wd = wd.max_depth(max_depth); - } - if let Some(ref cmp) = cmp { - let cmp = cmp.clone(); - wd = wd.sort_by(move |a, b| cmp(a, b)); - } - (p.to_path_buf(), Some(WalkEventIter::from(wd))) - } - }).collect::>().into_iter(); - let ig_root = self.ig_builder.build(); - Walk { - its: its, - it: None, - ig_root: ig_root.clone(), - ig: ig_root.clone(), - max_filesize: self.max_filesize, - parents: self.parents, - } - } - - /// Build a new `WalkParallel` iterator. - /// - /// Note that this *doesn't* return something that implements `Iterator`. - /// Instead, the returned value must be run with a closure. e.g., - /// `builder.build_parallel().run(|| |path| println!("{:?}", path))`. - pub fn build_parallel(&self) -> WalkParallel { - WalkParallel { - paths: self.paths.clone().into_iter(), - ig_root: self.ig_builder.build(), - max_depth: self.max_depth, - max_filesize: self.max_filesize, - follow_links: self.follow_links, - parents: self.parents, - threads: self.threads, - } - } - - /// Add a file path to the iterator. - /// - /// Each additional file path added is traversed recursively. This should - /// be preferred over building multiple `Walk` iterators since this - /// enables reusing resources across iteration. - pub fn add>(&mut self, path: P) -> &mut WalkBuilder { - self.paths.push(path.as_ref().to_path_buf()); - self - } - - /// The maximum depth to recurse. - /// - /// The default, `None`, imposes no depth restriction. - pub fn max_depth(&mut self, depth: Option) -> &mut WalkBuilder { - self.max_depth = depth; - self - } - - /// Whether to follow symbolic links or not. - pub fn follow_links(&mut self, yes: bool) -> &mut WalkBuilder { - self.follow_links = yes; - self - } - - /// Whether to ignore files above the specified limit. - pub fn max_filesize(&mut self, filesize: Option) -> &mut WalkBuilder { - self.max_filesize = filesize; - self - } - - /// The number of threads to use for traversal. - /// - /// Note that this only has an effect when using `build_parallel`. - /// - /// The default setting is `0`, which chooses the number of threads - /// automatically using heuristics. - pub fn threads(&mut self, n: usize) -> &mut WalkBuilder { - self.threads = n; - self - } - - /// Add an ignore file to the matcher. - /// - /// This has lower precedence than all other sources of ignore rules. - /// - /// If there was a problem adding the ignore file, then an error is - /// returned. Note that the error may indicate *partial* failure. For - /// example, if an ignore file contains an invalid glob, all other globs - /// are still applied. - pub fn add_ignore>(&mut self, path: P) -> Option { - let mut builder = GitignoreBuilder::new(""); - let mut errs = PartialErrorBuilder::default(); - errs.maybe_push(builder.add(path)); - match builder.build() { - Ok(gi) => { self.ig_builder.add_ignore(gi); } - Err(err) => { errs.push(err); } - } - errs.into_error_option() - } - - /// Add an override matcher. - /// - /// By default, no override matcher is used. - /// - /// This overrides any previous setting. - pub fn overrides(&mut self, overrides: Override) -> &mut WalkBuilder { - self.ig_builder.overrides(overrides); - self - } - - /// Add a file type matcher. - /// - /// By default, no file type matcher is used. - /// - /// This overrides any previous setting. - pub fn types(&mut self, types: Types) -> &mut WalkBuilder { - self.ig_builder.types(types); - self - } - - /// Enables ignoring hidden files. - /// - /// This is enabled by default. - pub fn hidden(&mut self, yes: bool) -> &mut WalkBuilder { - self.ig_builder.hidden(yes); - self - } - - /// Enables reading ignore files from parent directories. - /// - /// If this is enabled, then the parent directories of each file path given - /// are traversed for ignore files (subject to the ignore settings on - /// this builder). Note that file paths are canonicalized with respect to - /// the current working directory in order to determine parent directories. - /// - /// This is enabled by default. - pub fn parents(&mut self, yes: bool) -> &mut WalkBuilder { - self.parents = yes; - self - } - - /// Enables reading `.ignore` files. - /// - /// `.ignore` files have the same semantics as `gitignore` files and are - /// supported by search tools such as ripgrep and The Silver Searcher. - /// - /// This is enabled by default. - pub fn ignore(&mut self, yes: bool) -> &mut WalkBuilder { - self.ig_builder.ignore(yes); - self - } - - /// Enables reading a global gitignore file, whose path is specified in - /// git's `core.excludesFile` config option. - /// - /// Git's config file location is `$HOME/.gitconfig`. If `$HOME/.gitconfig` - /// does not exist or does not specify `core.excludesFile`, then - /// `$XDG_CONFIG_HOME/git/ignore` is read. If `$XDG_CONFIG_HOME` is not - /// set or is empty, then `$HOME/.config/git/ignore` is used instead. - pub fn git_global(&mut self, yes: bool) -> &mut WalkBuilder { - self.ig_builder.git_global(yes); - self - } - - /// Enables reading `.gitignore` files. - /// - /// `.gitignore` files have match semantics as described in the `gitignore` - /// man page. - /// - /// This is enabled by default. - pub fn git_ignore(&mut self, yes: bool) -> &mut WalkBuilder { - self.ig_builder.git_ignore(yes); - self - } - - /// Enables reading `.git/info/exclude` files. - /// - /// `.git/info/exclude` files have match semantics as described in the - /// `gitignore` man page. - /// - /// This is enabled by default. - pub fn git_exclude(&mut self, yes: bool) -> &mut WalkBuilder { - self.ig_builder.git_exclude(yes); - self - } - - /// Set a function for sorting directory entries. - /// - /// If a compare function is set, the resulting iterator will return all - /// paths in sorted order. The compare function will be called to compare - /// names from entries from the same directory using only the name of the - /// entry. - /// - /// Note that this is not used in the parallel iterator. - pub fn sort_by(&mut self, cmp: F) -> &mut WalkBuilder - where F: Fn(&OsString, &OsString) -> cmp::Ordering + 'static { - self.sorter = Some(Arc::new(cmp)); - self - } -} - -/// Walk is a recursive directory iterator over file paths in one or more -/// directories. -/// -/// Only file and directory paths matching the rules are returned. By default, -/// ignore files like `.gitignore` are respected. The precise matching rules -/// and precedence is explained in the documentation for `WalkBuilder`. -pub struct Walk { - its: vec::IntoIter<(PathBuf, Option)>, - it: Option, - ig_root: Ignore, - ig: Ignore, - max_filesize: Option, - parents: bool, -} - -impl Walk { - /// Creates a new recursive directory iterator for the file path given. - /// - /// Note that this uses default settings, which include respecting - /// `.gitignore` files. To configure the iterator, use `WalkBuilder` - /// instead. - pub fn new>(path: P) -> Walk { - WalkBuilder::new(path).build() - } - - fn skip_entry(&self, ent: &walkdir::DirEntry) -> bool { - if ent.depth() == 0 { - return false; - } - - let is_dir = ent.file_type().is_dir(); - let max_size = self.max_filesize; - let should_skip_path = skip_path(&self.ig, ent.path(), is_dir); - let should_skip_filesize = if !is_dir && max_size.is_some() { - skip_filesize(max_size.unwrap(), ent.path(), &ent.metadata().ok()) - } else { - false - }; - - should_skip_path || should_skip_filesize - } -} - -impl Iterator for Walk { - type Item = Result; - - #[inline(always)] - fn next(&mut self) -> Option> { - loop { - let ev = match self.it.as_mut().and_then(|it| it.next()) { - Some(ev) => ev, - None => { - match self.its.next() { - None => return None, - Some((_, None)) => { - return Some(Ok(DirEntry::new_stdin())); - } - Some((path, Some(it))) => { - self.it = Some(it); - if self.parents && path.is_dir() { - let (ig, err) = self.ig_root.add_parents(path); - self.ig = ig; - if let Some(err) = err { - return Some(Err(err)); - } - } else { - self.ig = self.ig_root.clone(); - } - } - } - continue; - } - }; - match ev { - Err(err) => { - return Some(Err(Error::from(err))); - } - Ok(WalkEvent::Exit) => { - self.ig = self.ig.parent().unwrap(); - } - Ok(WalkEvent::Dir(ent)) => { - if self.skip_entry(&ent) { - self.it.as_mut().unwrap().it.skip_current_dir(); - // Still need to push this on the stack because - // we'll get a WalkEvent::Exit event for this dir. - // We don't care if it errors though. - let (igtmp, _) = self.ig.add_child(ent.path()); - self.ig = igtmp; - continue; - } - let (igtmp, err) = self.ig.add_child(ent.path()); - self.ig = igtmp; - return Some(Ok(DirEntry::new_walkdir(ent, err))); - } - Ok(WalkEvent::File(ent)) => { - if self.skip_entry(&ent) { - continue; - } - return Some(Ok(DirEntry::new_walkdir(ent, None))); - } - } - } - } -} - -/// WalkEventIter transforms a WalkDir iterator into an iterator that more -/// accurately describes the directory tree. Namely, it emits events that are -/// one of three types: directory, file or "exit." An "exit" event means that -/// the entire contents of a directory have been enumerated. -struct WalkEventIter { - depth: usize, - it: walkdir::Iter, - next: Option>, -} - -#[derive(Debug)] -enum WalkEvent { - Dir(walkdir::DirEntry), - File(walkdir::DirEntry), - Exit, -} - -impl From for WalkEventIter { - fn from(it: WalkDir) -> WalkEventIter { - WalkEventIter { depth: 0, it: it.into_iter(), next: None } - } -} - -impl Iterator for WalkEventIter { - type Item = walkdir::Result; - - #[inline(always)] - fn next(&mut self) -> Option> { - let dent = self.next.take().or_else(|| self.it.next()); - let depth = match dent { - None => 0, - Some(Ok(ref dent)) => dent.depth(), - Some(Err(ref err)) => err.depth(), - }; - if depth < self.depth { - self.depth -= 1; - self.next = dent; - return Some(Ok(WalkEvent::Exit)); - } - self.depth = depth; - match dent { - None => None, - Some(Err(err)) => Some(Err(err)), - Some(Ok(dent)) => { - if dent.file_type().is_dir() { - self.depth += 1; - Some(Ok(WalkEvent::Dir(dent))) - } else { - Some(Ok(WalkEvent::File(dent))) - } - } - } - } -} - -/// WalkState is used in the parallel recursive directory iterator to indicate -/// whether walking should continue as normal, skip descending into a -/// particular directory or quit the walk entirely. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum WalkState { - /// Continue walking as normal. - Continue, - /// If the directory entry given is a directory, don't descend into it. - /// In all other cases, this has no effect. - Skip, - /// Quit the entire iterator as soon as possible. - /// - /// Note that this is an inherently asynchronous action. It is possible - /// for more entries to be yielded even after instructing the iterator - /// to quit. - Quit, -} - -impl WalkState { - fn is_quit(&self) -> bool { - *self == WalkState::Quit - } -} - -/// WalkParallel is a parallel recursive directory iterator over files paths -/// in one or more directories. -/// -/// Only file and directory paths matching the rules are returned. By default, -/// ignore files like `.gitignore` are respected. The precise matching rules -/// and precedence is explained in the documentation for `WalkBuilder`. -/// -/// Unlike `Walk`, this uses multiple threads for traversing a directory. -pub struct WalkParallel { - paths: vec::IntoIter, - ig_root: Ignore, - parents: bool, - max_filesize: Option, - max_depth: Option, - follow_links: bool, - threads: usize, -} - -impl WalkParallel { - /// Execute the parallel recursive directory iterator. `mkf` is called - /// for each thread used for iteration. The function produced by `mkf` - /// is then in turn called for each visited file path. - pub fn run( - self, - mut mkf: F, - ) where F: FnMut() -> Box) -> WalkState + Send + 'static> { - let mut f = mkf(); - let threads = self.threads(); - let queue = Arc::new(MsQueue::new()); - let mut any_work = false; - // Send the initial set of root paths to the pool of workers. - // Note that we only send directories. For files, we send to them the - // callback directly. - for path in self.paths { - let dent = - if path == Path::new("-") { - DirEntry::new_stdin() - } else { - match DirEntryRaw::from_link(0, path) { - Ok(dent) => DirEntry::new_raw(dent, None), - Err(err) => { - if f(Err(err)).is_quit() { - return; - } - continue; - } - } - }; - queue.push(Message::Work(Work { - dent: dent, - ignore: self.ig_root.clone(), - })); - any_work = true; - } - // ... but there's no need to start workers if we don't need them. - if !any_work { - return; - } - // Create the workers and then wait for them to finish. - let num_waiting = Arc::new(AtomicUsize::new(0)); - let num_quitting = Arc::new(AtomicUsize::new(0)); - let quit_now = Arc::new(AtomicBool::new(false)); - let mut handles = vec![]; - for _ in 0..threads { - let worker = Worker { - f: mkf(), - queue: queue.clone(), - quit_now: quit_now.clone(), - is_waiting: false, - is_quitting: false, - num_waiting: num_waiting.clone(), - num_quitting: num_quitting.clone(), - threads: threads, - parents: self.parents, - max_depth: self.max_depth, - max_filesize: self.max_filesize, - follow_links: self.follow_links, - }; - handles.push(thread::spawn(|| worker.run())); - } - for handle in handles { - handle.join().unwrap(); - } - } - - fn threads(&self) -> usize { - if self.threads == 0 { - 2 - } else { - self.threads - } - } -} - -/// Message is the set of instructions that a worker knows how to process. -enum Message { - /// A work item corresponds to a directory that should be descended into. - /// Work items for entries that should be skipped or ignored should not - /// be produced. - Work(Work), - /// This instruction indicates that the worker should start quitting. - Quit, -} - -/// A unit of work for each worker to process. -/// -/// Each unit of work corresponds to a directory that should be descended -/// into. -struct Work { - /// The directory entry. - dent: DirEntry, - /// Any ignore matchers that have been built for this directory's parents. - ignore: Ignore, -} - -impl Work { - /// Returns true if and only if this work item is a directory. - fn is_dir(&self) -> bool { - self.dent.file_type().map_or(false, |t| t.is_dir()) - } - - /// Adds ignore rules for parent directories. - /// - /// Note that this only applies to entries at depth 0. On all other - /// entries, this is a no-op. - fn add_parents(&mut self) -> Option { - if self.dent.depth() > 0 { - return None; - } - // At depth 0, the path of this entry is a root path, so we can - // use it directly to add parent ignore rules. - let (ig, err) = self.ignore.add_parents(self.dent.path()); - self.ignore = ig; - err - } - - /// Reads the directory contents of this work item and adds ignore - /// rules for this directory. - /// - /// If there was a problem with reading the directory contents, then - /// an error is returned. If there was a problem reading the ignore - /// rules for this directory, then the error is attached to this - /// work item's directory entry. - fn read_dir(&mut self) -> Result { - let readdir = match fs::read_dir(self.dent.path()) { - Ok(readdir) => readdir, - Err(err) => { - let err = Error::from(err) - .with_path(self.dent.path()) - .with_depth(self.dent.depth()); - return Err(err); - } - }; - let (ig, err) = self.ignore.add_child(self.dent.path()); - self.ignore = ig; - self.dent.err = err; - Ok(readdir) - } -} - -/// A worker is responsible for descending into directories, updating the -/// ignore matchers, producing new work and invoking the caller's callback. -/// -/// Note that a worker is *both* a producer and a consumer. -struct Worker { - /// The caller's callback. - f: Box) -> WalkState + Send + 'static>, - /// A queue of work items. This is multi-producer and multi-consumer. - queue: Arc>, - /// Whether all workers should quit at the next opportunity. Note that - /// this is distinct from quitting because of exhausting the contents of - /// a directory. Instead, this is used when the caller's callback indicates - /// that the iterator should quit immediately. - quit_now: Arc, - /// Whether this worker is waiting for more work. - is_waiting: bool, - /// Whether this worker has started to quit. - is_quitting: bool, - /// The number of workers waiting for more work. - num_waiting: Arc, - /// The number of workers waiting to quit. - num_quitting: Arc, - /// The total number of workers. - threads: usize, - /// Whether to create ignore matchers for parents of caller specified - /// directories. - parents: bool, - /// The maximum depth of directories to descend. A value of `0` means no - /// descension at all. - max_depth: Option, - /// The maximum size a searched file can be (in bytes). If a file exceeds - /// this size it will be skipped. - max_filesize: Option, - /// Whether to follow symbolic links or not. When this is enabled, loop - /// detection is performed. - follow_links: bool, -} - -impl Worker { - /// Runs this worker until there is no more work left to do. - /// - /// The worker will call the caller's callback for all entries that aren't - /// skipped by the ignore matcher. - fn run(mut self) { - while let Some(mut work) = self.get_work() { - // If the work is not a directory, then we can just execute the - // caller's callback immediately and move on. - if !work.is_dir() { - if (self.f)(Ok(work.dent)).is_quit() { - self.quit_now(); - return; - } - continue; - } - if self.parents { - if let Some(err) = work.add_parents() { - if (self.f)(Err(err)).is_quit() { - self.quit_now(); - return; - } - } - } - let readdir = match work.read_dir() { - Ok(readdir) => readdir, - Err(err) => { - if (self.f)(Err(err)).is_quit() { - self.quit_now(); - return; - } - continue; - } - }; - let depth = work.dent.depth(); - match (self.f)(Ok(work.dent)) { - WalkState::Continue => {} - WalkState::Skip => continue, - WalkState::Quit => { - self.quit_now(); - return; - } - } - if self.max_depth.map_or(false, |max| depth >= max) { - continue; - } - for result in readdir { - if self.run_one(&work.ignore, depth + 1, result).is_quit() { - self.quit_now(); - return; - } - } - } - } - - /// Runs the worker on a single entry from a directory iterator. - /// - /// If the entry is a path that should be ignored, then this is a no-op. - /// Otherwise, the entry is pushed on to the queue. (The actual execution - /// of the callback happens in `run`.) - /// - /// If an error occurs while reading the entry, then it is sent to the - /// caller's callback. - /// - /// `ig` is the `Ignore` matcher for the parent directory. `depth` should - /// be the depth of this entry. `result` should be the item yielded by - /// a directory iterator. - fn run_one( - &mut self, - ig: &Ignore, - depth: usize, - result: Result, - ) -> WalkState { - let fs_dent = match result { - Ok(fs_dent) => fs_dent, - Err(err) => { - return (self.f)(Err(Error::from(err).with_depth(depth))); - } - }; - let mut dent = match DirEntryRaw::from_entry(depth, &fs_dent) { - Ok(dent) => DirEntry::new_raw(dent, None), - Err(err) => { - return (self.f)(Err(err)); - } - }; - let is_symlink = dent.file_type().map_or(false, |ft| ft.is_symlink()); - if self.follow_links && is_symlink { - let path = dent.path().to_path_buf(); - dent = match DirEntryRaw::from_link(depth, path) { - Ok(dent) => DirEntry::new_raw(dent, None), - Err(err) => { - return (self.f)(Err(err)); - } - }; - if dent.file_type().map_or(false, |ft| ft.is_dir()) { - if let Err(err) = check_symlink_loop(ig, dent.path(), depth) { - return (self.f)(Err(err)); - } - } - } - let is_dir = dent.file_type().map_or(false, |ft| ft.is_dir()); - let max_size = self.max_filesize; - let should_skip_path = skip_path(ig, dent.path(), is_dir); - let should_skip_filesize = if !is_dir && max_size.is_some() { - skip_filesize(max_size.unwrap(), dent.path(), &dent.metadata().ok()) - } else { - false - }; - - if !should_skip_path && !should_skip_filesize { - self.queue.push(Message::Work(Work { - dent: dent, - ignore: ig.clone(), - })); - } - WalkState::Continue - } - - /// Returns the next directory to descend into. - /// - /// If all work has been exhausted, then this returns None. The worker - /// should then subsequently quit. - fn get_work(&mut self) -> Option { - loop { - if self.is_quit_now() { - return None; - } - match self.queue.try_pop() { - Some(Message::Work(work)) => { - self.waiting(false); - self.quitting(false); - return Some(work); - } - Some(Message::Quit) => { - // We can't just quit because a Message::Quit could be - // spurious. For example, it's possible to observe that - // all workers are waiting even if there's more work to - // be done. - // - // Therefore, we do a bit of a dance to wait until all - // workers have signaled that they're ready to quit before - // actually quitting. - // - // If the Quit message turns out to be spurious, then the - // loop below will break and we'll go back to looking for - // more work. - self.waiting(true); - self.quitting(true); - while !self.is_quit_now() { - let nwait = self.num_waiting(); - let nquit = self.num_quitting(); - // If the number of waiting workers dropped, then - // abort our attempt to quit. - if nwait < self.threads { - break; - } - // If all workers are in this quit loop, then we - // can stop. - if nquit == self.threads { - return None; - } - // Otherwise, spin. - } - } - None => { - self.waiting(true); - self.quitting(false); - if self.num_waiting() == self.threads { - for _ in 0..self.threads { - self.queue.push(Message::Quit); - } - } else { - // You're right to consider this suspicious, but it's - // a useful heuristic to permit producers to catch up - // to consumers without burning the CPU. It is also - // useful as a means to prevent burning the CPU if only - // one worker is left doing actual work. It's not - // perfect and it doesn't leave the CPU completely - // idle, but it's not clear what else we can do. :-/ - thread::sleep(Duration::from_millis(1)); - } - } - } - } - } - - /// Indicates that all workers should quit immediately. - fn quit_now(&self) { - self.quit_now.store(true, Ordering::SeqCst); - } - - /// Returns true if this worker should quit immediately. - fn is_quit_now(&self) -> bool { - self.quit_now.load(Ordering::SeqCst) - } - - /// Returns the total number of workers waiting for work. - fn num_waiting(&self) -> usize { - self.num_waiting.load(Ordering::SeqCst) - } - - /// Returns the total number of workers ready to quit. - fn num_quitting(&self) -> usize { - self.num_quitting.load(Ordering::SeqCst) - } - - /// Sets this worker's "quitting" state to the value of `yes`. - fn quitting(&mut self, yes: bool) { - if yes { - if !self.is_quitting { - self.is_quitting = true; - self.num_quitting.fetch_add(1, Ordering::SeqCst); - } - } else { - if self.is_quitting { - self.is_quitting = false; - self.num_quitting.fetch_sub(1, Ordering::SeqCst); - } - } - } - - /// Sets this worker's "waiting" state to the value of `yes`. - fn waiting(&mut self, yes: bool) { - if yes { - if !self.is_waiting { - self.is_waiting = true; - self.num_waiting.fetch_add(1, Ordering::SeqCst); - } - } else { - if self.is_waiting { - self.is_waiting = false; - self.num_waiting.fetch_sub(1, Ordering::SeqCst); - } - } - } -} - -fn check_symlink_loop( - ig_parent: &Ignore, - child_path: &Path, - child_depth: usize, -) -> Result<(), Error> { - for ig in ig_parent.parents().take_while(|ig| !ig.is_absolute_parent()) { - let same = try!(is_same_file(ig.path(), child_path).map_err(|err| { - Error::from(err).with_path(child_path).with_depth(child_depth) - })); - if same { - return Err(Error::Loop { - ancestor: ig.path().to_path_buf(), - child: child_path.to_path_buf(), - }.with_depth(child_depth)); - } - } - Ok(()) -} - -// Before calling this function, make sure that you ensure that is really -// necessary as the arguments imply a file stat. -fn skip_filesize( - max_filesize: u64, - path: &Path, - ent: &Option -) -> bool { - let filesize = match *ent { - Some(ref md) => Some(md.len()), - None => None - }; - - if let Some(fs) = filesize { - if fs > max_filesize { - debug!("ignoring {}: {} bytes", path.display(), fs); - true - } else { - false - } - } else { - false - } -} - -fn skip_path(ig: &Ignore, path: &Path, is_dir: bool) -> bool { - let m = ig.matched(path, is_dir); - if m.is_ignore() { - debug!("ignoring {}: {:?}", path.display(), m); - true - } else if m.is_whitelist() { - debug!("whitelisting {}: {:?}", path.display(), m); - false - } else { - false - } -} - -#[cfg(test)] -mod tests { - use std::fs::{self, File}; - use std::io::Write; - use std::path::Path; - use std::sync::{Arc, Mutex}; - - use tempdir::TempDir; - - use super::{WalkBuilder, WalkState}; - - fn wfile>(path: P, contents: &str) { - let mut file = File::create(path).unwrap(); - file.write_all(contents.as_bytes()).unwrap(); - } - - fn wfile_size>(path: P, size: u64) { - let file = File::create(path).unwrap(); - file.set_len(size).unwrap(); - } - - #[cfg(unix)] - fn symlink, Q: AsRef>(src: P, dst: Q) { - use std::os::unix::fs::symlink; - symlink(src, dst).unwrap(); - } - - fn mkdirp>(path: P) { - fs::create_dir_all(path).unwrap(); - } - - fn normal_path(unix: &str) -> String { - if cfg!(windows) { - unix.replace("\\", "/") - } else { - unix.to_string() - } - } - - fn walk_collect(prefix: &Path, builder: &WalkBuilder) -> Vec { - let mut paths = vec![]; - for result in builder.build() { - let dent = match result { - Err(_) => continue, - Ok(dent) => dent, - }; - let path = dent.path().strip_prefix(prefix).unwrap(); - if path.as_os_str().is_empty() { - continue; - } - paths.push(normal_path(path.to_str().unwrap())); - } - paths.sort(); - paths - } - - fn walk_collect_parallel( - prefix: &Path, - builder: &WalkBuilder, - ) -> Vec { - let paths = Arc::new(Mutex::new(vec![])); - let prefix = Arc::new(prefix.to_path_buf()); - builder.build_parallel().run(|| { - let paths = paths.clone(); - let prefix = prefix.clone(); - Box::new(move |result| { - let dent = match result { - Err(_) => return WalkState::Continue, - Ok(dent) => dent, - }; - let path = dent.path().strip_prefix(&**prefix).unwrap(); - if path.as_os_str().is_empty() { - return WalkState::Continue; - } - let mut paths = paths.lock().unwrap(); - paths.push(normal_path(path.to_str().unwrap())); - WalkState::Continue - }) - }); - let mut paths = paths.lock().unwrap(); - paths.sort(); - paths.to_vec() - } - - fn mkpaths(paths: &[&str]) -> Vec { - let mut paths: Vec<_> = paths.iter().map(|s| s.to_string()).collect(); - paths.sort(); - paths - } - - fn assert_paths( - prefix: &Path, - builder: &WalkBuilder, - expected: &[&str], - ) { - let got = walk_collect(prefix, builder); - assert_eq!(got, mkpaths(expected)); - let got = walk_collect_parallel(prefix, builder); - assert_eq!(got, mkpaths(expected)); - } - - #[test] - fn no_ignores() { - let td = TempDir::new("walk-test-").unwrap(); - mkdirp(td.path().join("a/b/c")); - mkdirp(td.path().join("x/y")); - wfile(td.path().join("a/b/foo"), ""); - wfile(td.path().join("x/y/foo"), ""); - - assert_paths(td.path(), &WalkBuilder::new(td.path()), &[ - "x", "x/y", "x/y/foo", "a", "a/b", "a/b/foo", "a/b/c", - ]); - } - - #[test] - fn gitignore() { - let td = TempDir::new("walk-test-").unwrap(); - mkdirp(td.path().join("a")); - wfile(td.path().join(".gitignore"), "foo"); - wfile(td.path().join("foo"), ""); - wfile(td.path().join("a/foo"), ""); - wfile(td.path().join("bar"), ""); - wfile(td.path().join("a/bar"), ""); - - assert_paths(td.path(), &WalkBuilder::new(td.path()), &[ - "bar", "a", "a/bar", - ]); - } - - #[test] - fn explicit_ignore() { - let td = TempDir::new("walk-test-").unwrap(); - let igpath = td.path().join(".not-an-ignore"); - mkdirp(td.path().join("a")); - wfile(&igpath, "foo"); - wfile(td.path().join("foo"), ""); - wfile(td.path().join("a/foo"), ""); - wfile(td.path().join("bar"), ""); - wfile(td.path().join("a/bar"), ""); - - let mut builder = WalkBuilder::new(td.path()); - assert!(builder.add_ignore(&igpath).is_none()); - assert_paths(td.path(), &builder, &["bar", "a", "a/bar"]); - } - - #[test] - fn gitignore_parent() { - let td = TempDir::new("walk-test-").unwrap(); - mkdirp(td.path().join("a")); - wfile(td.path().join(".gitignore"), "foo"); - wfile(td.path().join("a/foo"), ""); - wfile(td.path().join("a/bar"), ""); - - let root = td.path().join("a"); - assert_paths(&root, &WalkBuilder::new(&root), &["bar"]); - } - - #[test] - fn max_depth() { - let td = TempDir::new("walk-test-").unwrap(); - mkdirp(td.path().join("a/b/c")); - wfile(td.path().join("foo"), ""); - wfile(td.path().join("a/foo"), ""); - wfile(td.path().join("a/b/foo"), ""); - wfile(td.path().join("a/b/c/foo"), ""); - - let mut builder = WalkBuilder::new(td.path()); - assert_paths(td.path(), &builder, &[ - "a", "a/b", "a/b/c", "foo", "a/foo", "a/b/foo", "a/b/c/foo", - ]); - assert_paths(td.path(), builder.max_depth(Some(0)), &[]); - assert_paths(td.path(), builder.max_depth(Some(1)), &["a", "foo"]); - assert_paths(td.path(), builder.max_depth(Some(2)), &[ - "a", "a/b", "foo", "a/foo", - ]); - } - - #[test] - fn max_filesize() { - let td = TempDir::new("walk-test-").unwrap(); - mkdirp(td.path().join("a/b")); - wfile_size(td.path().join("foo"), 0); - wfile_size(td.path().join("bar"), 400); - wfile_size(td.path().join("baz"), 600); - wfile_size(td.path().join("a/foo"), 600); - wfile_size(td.path().join("a/bar"), 500); - wfile_size(td.path().join("a/baz"), 200); - - let mut builder = WalkBuilder::new(td.path()); - assert_paths(td.path(), &builder, &[ - "a", "a/b", "foo", "bar", "baz", "a/foo", "a/bar", "a/baz", - ]); - assert_paths(td.path(), builder.max_filesize(Some(0)), &[ - "a", "a/b", "foo" - ]); - assert_paths(td.path(), builder.max_filesize(Some(500)), &[ - "a", "a/b", "foo", "bar", "a/bar", "a/baz" - ]); - assert_paths(td.path(), builder.max_filesize(Some(50000)), &[ - "a", "a/b", "foo", "bar", "baz", "a/foo", "a/bar", "a/baz", - ]); - } - - #[cfg(unix)] // because symlinks on windows are weird - #[test] - fn symlinks() { - let td = TempDir::new("walk-test-").unwrap(); - mkdirp(td.path().join("a/b")); - symlink(td.path().join("a/b"), td.path().join("z")); - wfile(td.path().join("a/b/foo"), ""); - - let mut builder = WalkBuilder::new(td.path()); - assert_paths(td.path(), &builder, &[ - "a", "a/b", "a/b/foo", "z", - ]); - assert_paths(td.path(), &builder.follow_links(true), &[ - "a", "a/b", "a/b/foo", "z", "z/foo", - ]); - } - - #[cfg(unix)] // because symlinks on windows are weird - #[test] - fn symlink_loop() { - let td = TempDir::new("walk-test-").unwrap(); - mkdirp(td.path().join("a/b")); - symlink(td.path().join("a"), td.path().join("a/b/c")); - - let mut builder = WalkBuilder::new(td.path()); - assert_paths(td.path(), &builder, &[ - "a", "a/b", "a/b/c", - ]); - assert_paths(td.path(), &builder.follow_links(true), &[ - "a", "a/b", - ]); - } -} diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/tests/gitignore_matched_path_or_any_parents_tests.gitignore cargo-0.26.0/vendor/ignore-0.2.2/tests/gitignore_matched_path_or_any_parents_tests.gitignore --- cargo-0.25.0/vendor/ignore-0.2.2/tests/gitignore_matched_path_or_any_parents_tests.gitignore 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/tests/gitignore_matched_path_or_any_parents_tests.gitignore 1970-01-01 00:00:00.000000000 +0000 @@ -1,216 +0,0 @@ -# Based on https://github.com/behnam/gitignore-test/blob/master/.gitignore - -### file in root - -# MATCH /file_root_1 -file_root_00 - -# NO_MATCH -file_root_01/ - -# NO_MATCH -file_root_02/* - -# NO_MATCH -file_root_03/** - - -# MATCH /file_root_10 -/file_root_10 - -# NO_MATCH -/file_root_11/ - -# NO_MATCH -/file_root_12/* - -# NO_MATCH -/file_root_13/** - - -# NO_MATCH -*/file_root_20 - -# NO_MATCH -*/file_root_21/ - -# NO_MATCH -*/file_root_22/* - -# NO_MATCH -*/file_root_23/** - - -# MATCH /file_root_30 -**/file_root_30 - -# NO_MATCH -**/file_root_31/ - -# NO_MATCH -**/file_root_32/* - -# NO_MATCH -**/file_root_33/** - - -### file in sub-dir - -# MATCH /parent_dir/file_deep_1 -file_deep_00 - -# NO_MATCH -file_deep_01/ - -# NO_MATCH -file_deep_02/* - -# NO_MATCH -file_deep_03/** - - -# NO_MATCH -/file_deep_10 - -# NO_MATCH -/file_deep_11/ - -# NO_MATCH -/file_deep_12/* - -# NO_MATCH -/file_deep_13/** - - -# MATCH /parent_dir/file_deep_20 -*/file_deep_20 - -# NO_MATCH -*/file_deep_21/ - -# NO_MATCH -*/file_deep_22/* - -# NO_MATCH -*/file_deep_23/** - - -# MATCH /parent_dir/file_deep_30 -**/file_deep_30 - -# NO_MATCH -**/file_deep_31/ - -# NO_MATCH -**/file_deep_32/* - -# NO_MATCH -**/file_deep_33/** - - -### dir in root - -# MATCH /dir_root_00 -dir_root_00 - -# MATCH /dir_root_01 -dir_root_01/ - -# MATCH /dir_root_02 -dir_root_02/* - -# MATCH /dir_root_03 -dir_root_03/** - - -# MATCH /dir_root_10 -/dir_root_10 - -# MATCH /dir_root_11 -/dir_root_11/ - -# MATCH /dir_root_12 -/dir_root_12/* - -# MATCH /dir_root_13 -/dir_root_13/** - - -# NO_MATCH -*/dir_root_20 - -# NO_MATCH -*/dir_root_21/ - -# NO_MATCH -*/dir_root_22/* - -# NO_MATCH -*/dir_root_23/** - - -# MATCH /dir_root_30 -**/dir_root_30 - -# MATCH /dir_root_31 -**/dir_root_31/ - -# MATCH /dir_root_32 -**/dir_root_32/* - -# MATCH /dir_root_33 -**/dir_root_33/** - - -### dir in sub-dir - -# MATCH /parent_dir/dir_deep_00 -dir_deep_00 - -# MATCH /parent_dir/dir_deep_01 -dir_deep_01/ - -# NO_MATCH -dir_deep_02/* - -# NO_MATCH -dir_deep_03/** - - -# NO_MATCH -/dir_deep_10 - -# NO_MATCH -/dir_deep_11/ - -# NO_MATCH -/dir_deep_12/* - -# NO_MATCH -/dir_deep_13/** - - -# MATCH /parent_dir/dir_deep_20 -*/dir_deep_20 - -# MATCH /parent_dir/dir_deep_21 -*/dir_deep_21/ - -# MATCH /parent_dir/dir_deep_22 -*/dir_deep_22/* - -# MATCH /parent_dir/dir_deep_23 -*/dir_deep_23/** - - -# MATCH /parent_dir/dir_deep_30 -**/dir_deep_30 - -# MATCH /parent_dir/dir_deep_31 -**/dir_deep_31/ - -# MATCH /parent_dir/dir_deep_32 -**/dir_deep_32/* - -# MATCH /parent_dir/dir_deep_33 -**/dir_deep_33/** diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/tests/gitignore_matched_path_or_any_parents_tests.rs cargo-0.26.0/vendor/ignore-0.2.2/tests/gitignore_matched_path_or_any_parents_tests.rs --- cargo-0.25.0/vendor/ignore-0.2.2/tests/gitignore_matched_path_or_any_parents_tests.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/tests/gitignore_matched_path_or_any_parents_tests.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,297 +0,0 @@ -extern crate ignore; - - -use std::path::Path; - -use ignore::gitignore::{Gitignore, GitignoreBuilder}; - - -const IGNORE_FILE: &'static str = "tests/gitignore_matched_path_or_any_parents_tests.gitignore"; - - -fn get_gitignore() -> Gitignore { - let mut builder = GitignoreBuilder::new("ROOT"); - let error = builder.add(IGNORE_FILE); - assert!(error.is_none(), "failed to open gitignore file"); - builder.build().unwrap() -} - - -#[test] -#[should_panic(expected = "path is expect to be under the root")] -fn test_path_should_be_under_root() { - let gitignore = get_gitignore(); - let path = "/tmp/some_file"; - gitignore.matched_path_or_any_parents(Path::new(path), false); - assert!(false); -} - - -#[test] -fn test_files_in_root() { - let gitignore = get_gitignore(); - let m = |path: &str| gitignore.matched_path_or_any_parents(Path::new(path), false); - - // 0x - assert!(m("ROOT/file_root_00").is_ignore()); - assert!(m("ROOT/file_root_01").is_none()); - assert!(m("ROOT/file_root_02").is_none()); - assert!(m("ROOT/file_root_03").is_none()); - - // 1x - assert!(m("ROOT/file_root_10").is_ignore()); - assert!(m("ROOT/file_root_11").is_none()); - assert!(m("ROOT/file_root_12").is_none()); - assert!(m("ROOT/file_root_13").is_none()); - - // 2x - assert!(m("ROOT/file_root_20").is_none()); - assert!(m("ROOT/file_root_21").is_none()); - assert!(m("ROOT/file_root_22").is_none()); - assert!(m("ROOT/file_root_23").is_none()); - - // 3x - assert!(m("ROOT/file_root_30").is_ignore()); - assert!(m("ROOT/file_root_31").is_none()); - assert!(m("ROOT/file_root_32").is_none()); - assert!(m("ROOT/file_root_33").is_none()); -} - - -#[test] -fn test_files_in_deep() { - let gitignore = get_gitignore(); - let m = |path: &str| gitignore.matched_path_or_any_parents(Path::new(path), false); - - // 0x - assert!(m("ROOT/parent_dir/file_deep_00").is_ignore()); - assert!(m("ROOT/parent_dir/file_deep_01").is_none()); - assert!(m("ROOT/parent_dir/file_deep_02").is_none()); - assert!(m("ROOT/parent_dir/file_deep_03").is_none()); - - // 1x - assert!(m("ROOT/parent_dir/file_deep_10").is_none()); - assert!(m("ROOT/parent_dir/file_deep_11").is_none()); - assert!(m("ROOT/parent_dir/file_deep_12").is_none()); - assert!(m("ROOT/parent_dir/file_deep_13").is_none()); - - // 2x - assert!(m("ROOT/parent_dir/file_deep_20").is_ignore()); - assert!(m("ROOT/parent_dir/file_deep_21").is_none()); - assert!(m("ROOT/parent_dir/file_deep_22").is_none()); - assert!(m("ROOT/parent_dir/file_deep_23").is_none()); - - // 3x - assert!(m("ROOT/parent_dir/file_deep_30").is_ignore()); - assert!(m("ROOT/parent_dir/file_deep_31").is_none()); - assert!(m("ROOT/parent_dir/file_deep_32").is_none()); - assert!(m("ROOT/parent_dir/file_deep_33").is_none()); -} - - -#[test] -fn test_dirs_in_root() { - let gitignore = get_gitignore(); - let m = - |path: &str, is_dir: bool| gitignore.matched_path_or_any_parents(Path::new(path), is_dir); - - // 00 - assert!(m("ROOT/dir_root_00", true).is_ignore()); - assert!(m("ROOT/dir_root_00/file", false).is_ignore()); - assert!(m("ROOT/dir_root_00/child_dir", true).is_ignore()); - assert!(m("ROOT/dir_root_00/child_dir/file", false).is_ignore()); - - // 01 - assert!(m("ROOT/dir_root_01", true).is_ignore()); - assert!(m("ROOT/dir_root_01/file", false).is_ignore()); - assert!(m("ROOT/dir_root_01/child_dir", true).is_ignore()); - assert!(m("ROOT/dir_root_01/child_dir/file", false).is_ignore()); - - // 02 - assert!(m("ROOT/dir_root_02", true).is_none()); // dir itself doesn't match - assert!(m("ROOT/dir_root_02/file", false).is_ignore()); - assert!(m("ROOT/dir_root_02/child_dir", true).is_ignore()); - assert!(m("ROOT/dir_root_02/child_dir/file", false).is_ignore()); - - // 03 - assert!(m("ROOT/dir_root_03", true).is_none()); // dir itself doesn't match - assert!(m("ROOT/dir_root_03/file", false).is_ignore()); - assert!(m("ROOT/dir_root_03/child_dir", true).is_ignore()); - assert!(m("ROOT/dir_root_03/child_dir/file", false).is_ignore()); - - // 10 - assert!(m("ROOT/dir_root_10", true).is_ignore()); - assert!(m("ROOT/dir_root_10/file", false).is_ignore()); - assert!(m("ROOT/dir_root_10/child_dir", true).is_ignore()); - assert!(m("ROOT/dir_root_10/child_dir/file", false).is_ignore()); - - // 11 - assert!(m("ROOT/dir_root_11", true).is_ignore()); - assert!(m("ROOT/dir_root_11/file", false).is_ignore()); - assert!(m("ROOT/dir_root_11/child_dir", true).is_ignore()); - assert!(m("ROOT/dir_root_11/child_dir/file", false).is_ignore()); - - // 12 - assert!(m("ROOT/dir_root_12", true).is_none()); // dir itself doesn't match - assert!(m("ROOT/dir_root_12/file", false).is_ignore()); - assert!(m("ROOT/dir_root_12/child_dir", true).is_ignore()); - assert!(m("ROOT/dir_root_12/child_dir/file", false).is_ignore()); - - // 13 - assert!(m("ROOT/dir_root_13", true).is_none()); - assert!(m("ROOT/dir_root_13/file", false).is_ignore()); - assert!(m("ROOT/dir_root_13/child_dir", true).is_ignore()); - assert!(m("ROOT/dir_root_13/child_dir/file", false).is_ignore()); - - // 20 - assert!(m("ROOT/dir_root_20", true).is_none()); - assert!(m("ROOT/dir_root_20/file", false).is_none()); - assert!(m("ROOT/dir_root_20/child_dir", true).is_none()); - assert!(m("ROOT/dir_root_20/child_dir/file", false).is_none()); - - // 21 - assert!(m("ROOT/dir_root_21", true).is_none()); - assert!(m("ROOT/dir_root_21/file", false).is_none()); - assert!(m("ROOT/dir_root_21/child_dir", true).is_none()); - assert!(m("ROOT/dir_root_21/child_dir/file", false).is_none()); - - // 22 - assert!(m("ROOT/dir_root_22", true).is_none()); - assert!(m("ROOT/dir_root_22/file", false).is_none()); - assert!(m("ROOT/dir_root_22/child_dir", true).is_none()); - assert!(m("ROOT/dir_root_22/child_dir/file", false).is_none()); - - // 23 - assert!(m("ROOT/dir_root_23", true).is_none()); - assert!(m("ROOT/dir_root_23/file", false).is_none()); - assert!(m("ROOT/dir_root_23/child_dir", true).is_none()); - assert!(m("ROOT/dir_root_23/child_dir/file", false).is_none()); - - // 30 - assert!(m("ROOT/dir_root_30", true).is_ignore()); - assert!(m("ROOT/dir_root_30/file", false).is_ignore()); - assert!(m("ROOT/dir_root_30/child_dir", true).is_ignore()); - assert!(m("ROOT/dir_root_30/child_dir/file", false).is_ignore()); - - // 31 - assert!(m("ROOT/dir_root_31", true).is_ignore()); - assert!(m("ROOT/dir_root_31/file", false).is_ignore()); - assert!(m("ROOT/dir_root_31/child_dir", true).is_ignore()); - assert!(m("ROOT/dir_root_31/child_dir/file", false).is_ignore()); - - // 32 - assert!(m("ROOT/dir_root_32", true).is_none()); // dir itself doesn't match - assert!(m("ROOT/dir_root_32/file", false).is_ignore()); - assert!(m("ROOT/dir_root_32/child_dir", true).is_ignore()); - assert!(m("ROOT/dir_root_32/child_dir/file", false).is_ignore()); - - // 33 - assert!(m("ROOT/dir_root_33", true).is_none()); // dir itself doesn't match - assert!(m("ROOT/dir_root_33/file", false).is_ignore()); - assert!(m("ROOT/dir_root_33/child_dir", true).is_ignore()); - assert!(m("ROOT/dir_root_33/child_dir/file", false).is_ignore()); -} - - -#[test] -fn test_dirs_in_deep() { - let gitignore = get_gitignore(); - let m = - |path: &str, is_dir: bool| gitignore.matched_path_or_any_parents(Path::new(path), is_dir); - - // 00 - assert!(m("ROOT/parent_dir/dir_deep_00", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_00/file", false).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_00/child_dir", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_00/child_dir/file", false).is_ignore()); - - // 01 - assert!(m("ROOT/parent_dir/dir_deep_01", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_01/file", false).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_01/child_dir", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_01/child_dir/file", false).is_ignore()); - - // 02 - assert!(m("ROOT/parent_dir/dir_deep_02", true).is_none()); // dir itself doesn't match - assert!(m("ROOT/parent_dir/dir_deep_02/file", false).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_02/child_dir", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_02/child_dir/file", false).is_ignore()); - - // 03 - assert!(m("ROOT/parent_dir/dir_deep_03", true).is_none()); // dir itself doesn't match - assert!(m("ROOT/parent_dir/dir_deep_03/file", false).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_03/child_dir", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_03/child_dir/file", false).is_ignore()); - - // 10 - assert!(m("ROOT/parent_dir/dir_deep_10", true).is_none()); - assert!(m("ROOT/parent_dir/dir_deep_10/file", false).is_none()); - assert!(m("ROOT/parent_dir/dir_deep_10/child_dir", true).is_none()); - assert!(m("ROOT/parent_dir/dir_deep_10/child_dir/file", false).is_none()); - - // 11 - assert!(m("ROOT/parent_dir/dir_deep_11", true).is_none()); - assert!(m("ROOT/parent_dir/dir_deep_11/file", false).is_none()); - assert!(m("ROOT/parent_dir/dir_deep_11/child_dir", true).is_none()); - assert!(m("ROOT/parent_dir/dir_deep_11/child_dir/file", false).is_none()); - - // 12 - assert!(m("ROOT/parent_dir/dir_deep_12", true).is_none()); - assert!(m("ROOT/parent_dir/dir_deep_12/file", false).is_none()); - assert!(m("ROOT/parent_dir/dir_deep_12/child_dir", true).is_none()); - assert!(m("ROOT/parent_dir/dir_deep_12/child_dir/file", false).is_none()); - - // 13 - assert!(m("ROOT/parent_dir/dir_deep_13", true).is_none()); - assert!(m("ROOT/parent_dir/dir_deep_13/file", false).is_none()); - assert!(m("ROOT/parent_dir/dir_deep_13/child_dir", true).is_none()); - assert!(m("ROOT/parent_dir/dir_deep_13/child_dir/file", false).is_none()); - - // 20 - assert!(m("ROOT/parent_dir/dir_deep_20", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_20/file", false).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_20/child_dir", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_20/child_dir/file", false).is_ignore()); - - // 21 - assert!(m("ROOT/parent_dir/dir_deep_21", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_21/file", false).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_21/child_dir", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_21/child_dir/file", false).is_ignore()); - - // 22 - assert!(m("ROOT/parent_dir/dir_deep_22", true).is_none()); // dir itself doesn't match - assert!(m("ROOT/parent_dir/dir_deep_22/file", false).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_22/child_dir", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_22/child_dir/file", false).is_ignore()); - - // 23 - assert!(m("ROOT/parent_dir/dir_deep_23", true).is_none()); // dir itself doesn't match - assert!(m("ROOT/parent_dir/dir_deep_23/file", false).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_23/child_dir", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_23/child_dir/file", false).is_ignore()); - - // 30 - assert!(m("ROOT/parent_dir/dir_deep_30", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_30/file", false).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_30/child_dir", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_30/child_dir/file", false).is_ignore()); - - // 31 - assert!(m("ROOT/parent_dir/dir_deep_31", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_31/file", false).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_31/child_dir", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_31/child_dir/file", false).is_ignore()); - - // 32 - assert!(m("ROOT/parent_dir/dir_deep_32", true).is_none()); // dir itself doesn't match - assert!(m("ROOT/parent_dir/dir_deep_32/file", false).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_32/child_dir", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_32/child_dir/file", false).is_ignore()); - - // 33 - assert!(m("ROOT/parent_dir/dir_deep_33", true).is_none()); // dir itself doesn't match - assert!(m("ROOT/parent_dir/dir_deep_33/file", false).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_33/child_dir", true).is_ignore()); - assert!(m("ROOT/parent_dir/dir_deep_33/child_dir/file", false).is_ignore()); -} diff -Nru cargo-0.25.0/vendor/ignore-0.2.2/UNLICENSE cargo-0.26.0/vendor/ignore-0.2.2/UNLICENSE --- cargo-0.25.0/vendor/ignore-0.2.2/UNLICENSE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.2.2/UNLICENSE 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -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 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. - -For more information, please refer to diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/.cargo-checksum.json cargo-0.26.0/vendor/ignore-0.4.1/.cargo-checksum.json --- cargo-0.25.0/vendor/ignore-0.4.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"245bea0ba52531a3739cb8ba99f8689eda13d7faf8c36b6a73ce4421aab42588"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/Cargo.toml cargo-0.26.0/vendor/ignore-0.4.1/Cargo.toml --- cargo-0.25.0/vendor/ignore-0.4.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,61 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "ignore" +version = "0.4.1" +authors = ["Andrew Gallant "] +description = "A fast library for efficiently matching ignore files such as `.gitignore`\nagainst file paths.\n" +homepage = "https://github.com/BurntSushi/ripgrep/tree/master/ignore" +documentation = "https://docs.rs/ignore" +readme = "README.md" +keywords = ["glob", "ignore", "gitignore", "pattern", "file"] +license = "Unlicense/MIT" +repository = "https://github.com/BurntSushi/ripgrep/tree/master/ignore" + +[lib] +name = "ignore" +bench = false +[dependencies.crossbeam] +version = "0.3" + +[dependencies.globset] +version = "0.3.0" + +[dependencies.lazy_static] +version = "1" + +[dependencies.log] +version = "0.4" + +[dependencies.memchr] +version = "2" + +[dependencies.regex] +version = "0.2.1" + +[dependencies.same-file] +version = "1" + +[dependencies.thread_local] +version = "0.3.2" + +[dependencies.walkdir] +version = "2" +[dev-dependencies.tempdir] +version = "0.3.5" + +[features] +simd-accel = ["globset/simd-accel"] +[target."cfg(windows)".dependencies.winapi] +version = "0.3" +features = ["std", "winnt"] diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/COPYING cargo-0.26.0/vendor/ignore-0.4.1/COPYING --- cargo-0.25.0/vendor/ignore-0.4.1/COPYING 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/COPYING 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3 @@ +This project is dual-licensed under the Unlicense and MIT licenses. + +You may use this code under the terms of either license. diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/examples/walk.rs cargo-0.26.0/vendor/ignore-0.4.1/examples/walk.rs --- cargo-0.25.0/vendor/ignore-0.4.1/examples/walk.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/examples/walk.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,92 @@ +#![allow(dead_code, unused_imports, unused_mut, unused_variables)] + +extern crate crossbeam; +extern crate ignore; +extern crate walkdir; + +use std::env; +use std::io::{self, Write}; +use std::path::Path; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::thread; + +use crossbeam::sync::MsQueue; +use ignore::WalkBuilder; +use walkdir::WalkDir; + +fn main() { + let mut path = env::args().nth(1).unwrap(); + let mut parallel = false; + let mut simple = false; + let queue: Arc>> = Arc::new(MsQueue::new()); + if path == "parallel" { + path = env::args().nth(2).unwrap(); + parallel = true; + } else if path == "walkdir" { + path = env::args().nth(2).unwrap(); + simple = true; + } + + let stdout_queue = queue.clone(); + let stdout_thread = thread::spawn(move || { + let mut stdout = io::BufWriter::new(io::stdout()); + while let Some(dent) = stdout_queue.pop() { + write_path(&mut stdout, dent.path()); + } + }); + + if parallel { + let walker = WalkBuilder::new(path).threads(6).build_parallel(); + walker.run(|| { + let queue = queue.clone(); + Box::new(move |result| { + use ignore::WalkState::*; + + queue.push(Some(DirEntry::Y(result.unwrap()))); + Continue + }) + }); + } else if simple { + let mut stdout = io::BufWriter::new(io::stdout()); + let walker = WalkDir::new(path); + for result in walker { + queue.push(Some(DirEntry::X(result.unwrap()))); + } + } else { + let mut stdout = io::BufWriter::new(io::stdout()); + let walker = WalkBuilder::new(path).build(); + for result in walker { + queue.push(Some(DirEntry::Y(result.unwrap()))); + } + } + queue.push(None); + stdout_thread.join().unwrap(); +} + +enum DirEntry { + X(walkdir::DirEntry), + Y(ignore::DirEntry), +} + +impl DirEntry { + fn path(&self) -> &Path { + match *self { + DirEntry::X(ref x) => x.path(), + DirEntry::Y(ref y) => y.path(), + } + } +} + +#[cfg(unix)] +fn write_path(mut wtr: W, path: &Path) { + use std::os::unix::ffi::OsStrExt; + wtr.write(path.as_os_str().as_bytes()).unwrap(); + wtr.write(b"\n").unwrap(); +} + +#[cfg(not(unix))] +fn write_path(mut wtr: W, path: &Path) { + wtr.write(path.to_string_lossy().as_bytes()).unwrap(); + wtr.write(b"\n").unwrap(); +} diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/LICENSE-MIT cargo-0.26.0/vendor/ignore-0.4.1/LICENSE-MIT --- cargo-0.25.0/vendor/ignore-0.4.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +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. diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/README.md cargo-0.26.0/vendor/ignore-0.4.1/README.md --- cargo-0.25.0/vendor/ignore-0.4.1/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,66 @@ +ignore +====== +The ignore crate provides a fast recursive directory iterator that respects +various filters such as globs, file types and `.gitignore` files. This crate +also provides lower level direct access to gitignore and file type matchers. + +[![Linux build status](https://api.travis-ci.org/BurntSushi/ripgrep.png)](https://travis-ci.org/BurntSushi/ripgrep) +[![Windows build status](https://ci.appveyor.com/api/projects/status/github/BurntSushi/ripgrep?svg=true)](https://ci.appveyor.com/project/BurntSushi/ripgrep) +[![](https://img.shields.io/crates/v/ignore.svg)](https://crates.io/crates/ignore) + +Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). + +### Documentation + +[https://docs.rs/ignore](https://docs.rs/ignore) + +### Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +ignore = "0.3" +``` + +and this to your crate root: + +```rust +extern crate ignore; +``` + +### Example + +This example shows the most basic usage of this crate. This code will +recursively traverse the current directory while automatically filtering out +files and directories according to ignore globs found in files like +`.ignore` and `.gitignore`: + + +```rust,no_run +use ignore::Walk; + +for result in Walk::new("./") { + // Each item yielded by the iterator is either a directory entry or an + // error, so either print the path or the error. + match result { + Ok(entry) => println!("{}", entry.path().display()), + Err(err) => println!("ERROR: {}", err), + } +} +``` + +### Example: advanced + +By default, the recursive directory iterator will ignore hidden files and +directories. This can be disabled by building the iterator with `WalkBuilder`: + +```rust,no_run +use ignore::WalkBuilder; + +for result in WalkBuilder::new("./").hidden(false).build() { + println!("{:?}", result); +} +``` + +See the documentation for `WalkBuilder` for many other options. diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/src/dir.rs cargo-0.26.0/vendor/ignore-0.4.1/src/dir.rs --- cargo-0.25.0/vendor/ignore-0.4.1/src/dir.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/src/dir.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,889 @@ +// This module provides a data structure, `Ignore`, that connects "directory +// traversal" with "ignore matchers." Specifically, it knows about gitignore +// semantics and precedence, and is organized based on directory hierarchy. +// Namely, every matcher logically corresponds to ignore rules from a single +// directory, and points to the matcher for its corresponding parent directory. +// In this sense, `Ignore` is a *persistent* data structure. +// +// This design was specifically chosen to make it possible to use this data +// structure in a parallel directory iterator. +// +// My initial intention was to expose this module as part of this crate's +// public API, but I think the data structure's public API is too complicated +// with non-obvious failure modes. Alas, such things haven't been documented +// well. + +use std::collections::HashMap; +use std::ffi::{OsString, OsStr}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock}; + +use gitignore::{self, Gitignore, GitignoreBuilder}; +use pathutil::{is_hidden, strip_prefix}; +use overrides::{self, Override}; +use types::{self, Types}; +use {Error, Match, PartialErrorBuilder}; + +/// IgnoreMatch represents information about where a match came from when using +/// the `Ignore` matcher. +#[derive(Clone, Debug)] +pub struct IgnoreMatch<'a>(IgnoreMatchInner<'a>); + +/// IgnoreMatchInner describes precisely where the match information came from. +/// This is private to allow expansion to more matchers in the future. +#[derive(Clone, Debug)] +enum IgnoreMatchInner<'a> { + Override(overrides::Glob<'a>), + Gitignore(&'a gitignore::Glob), + Types(types::Glob<'a>), + Hidden, +} + +impl<'a> IgnoreMatch<'a> { + fn overrides(x: overrides::Glob<'a>) -> IgnoreMatch<'a> { + IgnoreMatch(IgnoreMatchInner::Override(x)) + } + + fn gitignore(x: &'a gitignore::Glob) -> IgnoreMatch<'a> { + IgnoreMatch(IgnoreMatchInner::Gitignore(x)) + } + + fn types(x: types::Glob<'a>) -> IgnoreMatch<'a> { + IgnoreMatch(IgnoreMatchInner::Types(x)) + } + + fn hidden() -> IgnoreMatch<'static> { + IgnoreMatch(IgnoreMatchInner::Hidden) + } +} + +/// Options for the ignore matcher, shared between the matcher itself and the +/// builder. +#[derive(Clone, Copy, Debug)] +struct IgnoreOptions { + /// Whether to ignore hidden file paths or not. + hidden: bool, + /// Whether to read .ignore files. + ignore: bool, + /// Whether to read git's global gitignore file. + git_global: bool, + /// Whether to read .gitignore files. + git_ignore: bool, + /// Whether to read .git/info/exclude files. + git_exclude: bool, +} + +/// Ignore is a matcher useful for recursively walking one or more directories. +#[derive(Clone, Debug)] +pub struct Ignore(Arc); + +#[derive(Clone, Debug)] +struct IgnoreInner { + /// A map of all existing directories that have already been + /// compiled into matchers. + /// + /// Note that this is never used during matching, only when adding new + /// parent directory matchers. This avoids needing to rebuild glob sets for + /// parent directories if many paths are being searched. + compiled: Arc>>, + /// The path to the directory that this matcher was built from. + dir: PathBuf, + /// An override matcher (default is empty). + overrides: Arc, + /// A file type matcher. + types: Arc, + /// The parent directory to match next. + /// + /// If this is the root directory or there are otherwise no more + /// directories to match, then `parent` is `None`. + parent: Option, + /// Whether this is an absolute parent matcher, as added by add_parent. + is_absolute_parent: bool, + /// The absolute base path of this matcher. Populated only if parent + /// directories are added. + absolute_base: Option>, + /// Explicit global ignore matchers specified by the caller. + explicit_ignores: Arc>, + /// Ignore files used in addition to `.ignore` + custom_ignore_filenames: Arc>, + /// The matcher for custom ignore files + custom_ignore_matcher: Gitignore, + /// The matcher for .ignore files. + ignore_matcher: Gitignore, + /// A global gitignore matcher, usually from $XDG_CONFIG_HOME/git/ignore. + git_global_matcher: Arc, + /// The matcher for .gitignore files. + git_ignore_matcher: Gitignore, + /// Special matcher for `.git/info/exclude` files. + git_exclude_matcher: Gitignore, + /// Whether this directory contains a .git sub-directory. + has_git: bool, + /// Ignore config. + opts: IgnoreOptions, +} + +impl Ignore { + /// Return the directory path of this matcher. + pub fn path(&self) -> &Path { + &self.0.dir + } + + /// Return true if this matcher has no parent. + pub fn is_root(&self) -> bool { + self.0.parent.is_none() + } + + /// Returns true if this matcher was added via the `add_parents` method. + pub fn is_absolute_parent(&self) -> bool { + self.0.is_absolute_parent + } + + /// Return this matcher's parent, if one exists. + pub fn parent(&self) -> Option { + self.0.parent.clone() + } + + /// Create a new `Ignore` matcher with the parent directories of `dir`. + /// + /// Note that this can only be called on an `Ignore` matcher with no + /// parents (i.e., `is_root` returns `true`). This will panic otherwise. + pub fn add_parents>( + &self, + path: P, + ) -> (Ignore, Option) { + if !self.is_root() { + panic!("Ignore::add_parents called on non-root matcher"); + } + let absolute_base = match path.as_ref().canonicalize() { + Ok(path) => Arc::new(path), + Err(_) => { + // There's not much we can do here, so just return our + // existing matcher. We drop the error to be consistent + // with our general pattern of ignoring I/O errors when + // processing ignore files. + return (self.clone(), None); + } + }; + // List of parents, from child to root. + let mut parents = vec![]; + let mut path = &**absolute_base; + while let Some(parent) = path.parent() { + parents.push(parent); + path = parent; + } + let mut errs = PartialErrorBuilder::default(); + let mut ig = self.clone(); + for parent in parents.into_iter().rev() { + let mut compiled = self.0.compiled.write().unwrap(); + if let Some(prebuilt) = compiled.get(parent.as_os_str()) { + ig = prebuilt.clone(); + continue; + } + let (mut igtmp, err) = ig.add_child_path(parent); + errs.maybe_push(err); + igtmp.is_absolute_parent = true; + igtmp.absolute_base = Some(absolute_base.clone()); + ig = Ignore(Arc::new(igtmp)); + compiled.insert(parent.as_os_str().to_os_string(), ig.clone()); + } + (ig, errs.into_error_option()) + } + + /// Create a new `Ignore` matcher for the given child directory. + /// + /// Since building the matcher may require reading from multiple + /// files, it's possible that this method partially succeeds. Therefore, + /// a matcher is always returned (which may match nothing) and an error is + /// returned if it exists. + /// + /// Note that all I/O errors are completely ignored. + pub fn add_child>( + &self, + dir: P, + ) -> (Ignore, Option) { + let (ig, err) = self.add_child_path(dir.as_ref()); + (Ignore(Arc::new(ig)), err) + } + + /// Like add_child, but takes a full path and returns an IgnoreInner. + fn add_child_path(&self, dir: &Path) -> (IgnoreInner, Option) { + let mut errs = PartialErrorBuilder::default(); + let custom_ig_matcher = + { + let (m, err) = + create_gitignore(&dir, &self.0.custom_ignore_filenames); + errs.maybe_push(err); + m + }; + let ig_matcher = + if !self.0.opts.ignore { + Gitignore::empty() + } else { + let (m, err) = create_gitignore(&dir, &[".ignore"]); + errs.maybe_push(err); + m + }; + let gi_matcher = + if !self.0.opts.git_ignore { + Gitignore::empty() + } else { + let (m, err) = create_gitignore(&dir, &[".gitignore"]); + errs.maybe_push(err); + m + }; + let gi_exclude_matcher = + if !self.0.opts.git_exclude { + Gitignore::empty() + } else { + let (m, err) = create_gitignore(&dir, &[".git/info/exclude"]); + errs.maybe_push(err); + m + }; + let ig = IgnoreInner { + compiled: self.0.compiled.clone(), + dir: dir.to_path_buf(), + overrides: self.0.overrides.clone(), + types: self.0.types.clone(), + parent: Some(self.clone()), + is_absolute_parent: false, + absolute_base: self.0.absolute_base.clone(), + explicit_ignores: self.0.explicit_ignores.clone(), + custom_ignore_filenames: self.0.custom_ignore_filenames.clone(), + custom_ignore_matcher: custom_ig_matcher, + ignore_matcher: ig_matcher, + git_global_matcher: self.0.git_global_matcher.clone(), + git_ignore_matcher: gi_matcher, + git_exclude_matcher: gi_exclude_matcher, + has_git: dir.join(".git").is_dir(), + opts: self.0.opts, + }; + (ig, errs.into_error_option()) + } + + /// Returns true if at least one type of ignore rule should be matched. + fn has_any_ignore_rules(&self) -> bool { + let opts = self.0.opts; + let has_custom_ignore_files = !self.0.custom_ignore_filenames.is_empty(); + + opts.ignore || opts.git_global || opts.git_ignore + || opts.git_exclude || has_custom_ignore_files + } + + /// Returns a match indicating whether the given file path should be + /// ignored or not. + /// + /// The match contains information about its origin. + pub fn matched<'a, P: AsRef>( + &'a self, + path: P, + is_dir: bool, + ) -> Match> { + // We need to be careful with our path. If it has a leading ./, then + // strip it because it causes nothing but trouble. + let mut path = path.as_ref(); + if let Some(p) = strip_prefix("./", path) { + path = p; + } + // Match against the override patterns. If an override matches + // regardless of whether it's whitelist/ignore, then we quit and + // return that result immediately. Overrides have the highest + // precedence. + if !self.0.overrides.is_empty() { + let mat = + self.0.overrides.matched(path, is_dir) + .map(IgnoreMatch::overrides); + if !mat.is_none() { + return mat; + } + } + let mut whitelisted = Match::None; + if self.has_any_ignore_rules() { + let mat = self.matched_ignore(path, is_dir); + if mat.is_ignore() { + return mat; + } else if mat.is_whitelist() { + whitelisted = mat; + } + } + if !self.0.types.is_empty() { + let mat = + self.0.types.matched(path, is_dir).map(IgnoreMatch::types); + if mat.is_ignore() { + return mat; + } else if mat.is_whitelist() { + whitelisted = mat; + } + } + if whitelisted.is_none() && self.0.opts.hidden && is_hidden(path) { + return Match::Ignore(IgnoreMatch::hidden()); + } + whitelisted + } + + /// Performs matching only on the ignore files for this directory and + /// all parent directories. + fn matched_ignore<'a>( + &'a self, + path: &Path, + is_dir: bool, + ) -> Match> { + let (mut m_custom_ignore, mut m_ignore, mut m_gi, mut m_gi_exclude, mut m_explicit) = + (Match::None, Match::None, Match::None, Match::None, Match::None); + let mut saw_git = false; + for ig in self.parents().take_while(|ig| !ig.0.is_absolute_parent) { + if m_custom_ignore.is_none() { + m_custom_ignore = + ig.0.custom_ignore_matcher.matched(path, is_dir) + .map(IgnoreMatch::gitignore); + } + if m_ignore.is_none() { + m_ignore = + ig.0.ignore_matcher.matched(path, is_dir) + .map(IgnoreMatch::gitignore); + } + if !saw_git && m_gi.is_none() { + m_gi = + ig.0.git_ignore_matcher.matched(path, is_dir) + .map(IgnoreMatch::gitignore); + } + if !saw_git && m_gi_exclude.is_none() { + m_gi_exclude = + ig.0.git_exclude_matcher.matched(path, is_dir) + .map(IgnoreMatch::gitignore); + } + saw_git = saw_git || ig.0.has_git; + } + if let Some(abs_parent_path) = self.absolute_base() { + let path = abs_parent_path.join(path); + for ig in self.parents().skip_while(|ig|!ig.0.is_absolute_parent) { + if m_custom_ignore.is_none() { + m_custom_ignore = + ig.0.custom_ignore_matcher.matched(&path, is_dir) + .map(IgnoreMatch::gitignore); + } + if m_ignore.is_none() { + m_ignore = + ig.0.ignore_matcher.matched(&path, is_dir) + .map(IgnoreMatch::gitignore); + } + if !saw_git && m_gi.is_none() { + m_gi = + ig.0.git_ignore_matcher.matched(&path, is_dir) + .map(IgnoreMatch::gitignore); + } + if !saw_git && m_gi_exclude.is_none() { + m_gi_exclude = + ig.0.git_exclude_matcher.matched(&path, is_dir) + .map(IgnoreMatch::gitignore); + } + saw_git = saw_git || ig.0.has_git; + } + } + for gi in self.0.explicit_ignores.iter().rev() { + if !m_explicit.is_none() { + break; + } + m_explicit = gi.matched(&path, is_dir).map(IgnoreMatch::gitignore); + } + let m_global = self.0.git_global_matcher.matched(&path, is_dir) + .map(IgnoreMatch::gitignore); + + m_custom_ignore.or(m_ignore).or(m_gi).or(m_gi_exclude).or(m_global).or(m_explicit) + } + + /// Returns an iterator over parent ignore matchers, including this one. + pub fn parents(&self) -> Parents { + Parents(Some(self)) + } + + /// Returns the first absolute path of the first absolute parent, if + /// one exists. + fn absolute_base(&self) -> Option<&Path> { + self.0.absolute_base.as_ref().map(|p| &***p) + } +} + +/// An iterator over all parents of an ignore matcher, including itself. +/// +/// The lifetime `'a` refers to the lifetime of the initial `Ignore` matcher. +pub struct Parents<'a>(Option<&'a Ignore>); + +impl<'a> Iterator for Parents<'a> { + type Item = &'a Ignore; + + fn next(&mut self) -> Option<&'a Ignore> { + match self.0.take() { + None => None, + Some(ig) => { + self.0 = ig.0.parent.as_ref(); + Some(ig) + } + } + } +} + +/// A builder for creating an Ignore matcher. +#[derive(Clone, Debug)] +pub struct IgnoreBuilder { + /// The root directory path for this ignore matcher. + dir: PathBuf, + /// An override matcher (default is empty). + overrides: Arc, + /// A type matcher (default is empty). + types: Arc, + /// Explicit global ignore matchers. + explicit_ignores: Vec, + /// Ignore files in addition to .ignore. + custom_ignore_filenames: Vec, + /// Ignore config. + opts: IgnoreOptions, +} + +impl IgnoreBuilder { + /// Create a new builder for an `Ignore` matcher. + /// + /// All relative file paths are resolved with respect to the current + /// working directory. + pub fn new() -> IgnoreBuilder { + IgnoreBuilder { + dir: Path::new("").to_path_buf(), + overrides: Arc::new(Override::empty()), + types: Arc::new(Types::empty()), + explicit_ignores: vec![], + custom_ignore_filenames: vec![], + opts: IgnoreOptions { + hidden: true, + ignore: true, + git_global: true, + git_ignore: true, + git_exclude: true, + }, + } + } + + /// Builds a new `Ignore` matcher. + /// + /// The matcher returned won't match anything until ignore rules from + /// directories are added to it. + pub fn build(&self) -> Ignore { + let git_global_matcher = + if !self.opts.git_global { + Gitignore::empty() + } else { + let (gi, err) = Gitignore::global(); + if let Some(err) = err { + debug!("{}", err); + } + gi + }; + + Ignore(Arc::new(IgnoreInner { + compiled: Arc::new(RwLock::new(HashMap::new())), + dir: self.dir.clone(), + overrides: self.overrides.clone(), + types: self.types.clone(), + parent: None, + is_absolute_parent: true, + absolute_base: None, + explicit_ignores: Arc::new(self.explicit_ignores.clone()), + custom_ignore_filenames: Arc::new(self.custom_ignore_filenames.clone()), + custom_ignore_matcher: Gitignore::empty(), + ignore_matcher: Gitignore::empty(), + git_global_matcher: Arc::new(git_global_matcher), + git_ignore_matcher: Gitignore::empty(), + git_exclude_matcher: Gitignore::empty(), + has_git: false, + opts: self.opts, + })) + } + + /// Add an override matcher. + /// + /// By default, no override matcher is used. + /// + /// This overrides any previous setting. + pub fn overrides(&mut self, overrides: Override) -> &mut IgnoreBuilder { + self.overrides = Arc::new(overrides); + self + } + + /// Add a file type matcher. + /// + /// By default, no file type matcher is used. + /// + /// This overrides any previous setting. + pub fn types(&mut self, types: Types) -> &mut IgnoreBuilder { + self.types = Arc::new(types); + self + } + + /// Adds a new global ignore matcher from the ignore file path given. + pub fn add_ignore(&mut self, ig: Gitignore) -> &mut IgnoreBuilder { + self.explicit_ignores.push(ig); + self + } + + /// Add a custom ignore file name + /// + /// These ignore files have higher precedence than all other ignore files. + /// + /// When specifying multiple names, earlier names have lower precedence than + /// later names. + pub fn add_custom_ignore_filename>( + &mut self, + file_name: S + ) -> &mut IgnoreBuilder { + self.custom_ignore_filenames.push(file_name.as_ref().to_os_string()); + self + } + + /// Enables ignoring hidden files. + /// + /// This is enabled by default. + pub fn hidden(&mut self, yes: bool) -> &mut IgnoreBuilder { + self.opts.hidden = yes; + self + } + + /// Enables reading `.ignore` files. + /// + /// `.ignore` files have the same semantics as `gitignore` files and are + /// supported by search tools such as ripgrep and The Silver Searcher. + /// + /// This is enabled by default. + pub fn ignore(&mut self, yes: bool) -> &mut IgnoreBuilder { + self.opts.ignore = yes; + self + } + + /// Add a global gitignore matcher. + /// + /// Its precedence is lower than both normal `.gitignore` files and + /// `.git/info/exclude` files. + /// + /// This overwrites any previous global gitignore setting. + /// + /// This is enabled by default. + pub fn git_global(&mut self, yes: bool) -> &mut IgnoreBuilder { + self.opts.git_global = yes; + self + } + + /// Enables reading `.gitignore` files. + /// + /// `.gitignore` files have match semantics as described in the `gitignore` + /// man page. + /// + /// This is enabled by default. + pub fn git_ignore(&mut self, yes: bool) -> &mut IgnoreBuilder { + self.opts.git_ignore = yes; + self + } + + /// Enables reading `.git/info/exclude` files. + /// + /// `.git/info/exclude` files have match semantics as described in the + /// `gitignore` man page. + /// + /// This is enabled by default. + pub fn git_exclude(&mut self, yes: bool) -> &mut IgnoreBuilder { + self.opts.git_exclude = yes; + self + } +} + +/// Creates a new gitignore matcher for the directory given. +/// +/// Ignore globs are extracted from each of the file names in `dir` in the +/// order given (earlier names have lower precedence than later names). +/// +/// I/O errors are ignored. +pub fn create_gitignore>( + dir: &Path, + names: &[T], +) -> (Gitignore, Option) { + let mut builder = GitignoreBuilder::new(dir); + let mut errs = PartialErrorBuilder::default(); + for name in names { + let gipath = dir.join(name.as_ref()); + errs.maybe_push_ignore_io(builder.add(gipath)); + } + let gi = match builder.build() { + Ok(gi) => gi, + Err(err) => { + errs.push(err); + GitignoreBuilder::new(dir).build().unwrap() + } + }; + (gi, errs.into_error_option()) +} + +#[cfg(test)] +mod tests { + use std::fs::{self, File}; + use std::io::Write; + use std::path::Path; + + use tempdir::TempDir; + + use dir::IgnoreBuilder; + use gitignore::Gitignore; + use Error; + + fn wfile>(path: P, contents: &str) { + let mut file = File::create(path).unwrap(); + file.write_all(contents.as_bytes()).unwrap(); + } + + fn mkdirp>(path: P) { + fs::create_dir_all(path).unwrap(); + } + + fn partial(err: Error) -> Vec { + match err { + Error::Partial(errs) => errs, + _ => panic!("expected partial error but got {:?}", err), + } + } + + #[test] + fn explicit_ignore() { + let td = TempDir::new("ignore-test-").unwrap(); + wfile(td.path().join("not-an-ignore"), "foo\n!bar"); + + let (gi, err) = Gitignore::new(td.path().join("not-an-ignore")); + assert!(err.is_none()); + let (ig, err) = IgnoreBuilder::new() + .add_ignore(gi).build().add_child(td.path()); + assert!(err.is_none()); + assert!(ig.matched("foo", false).is_ignore()); + assert!(ig.matched("bar", false).is_whitelist()); + assert!(ig.matched("baz", false).is_none()); + } + + #[test] + fn git_exclude() { + let td = TempDir::new("ignore-test-").unwrap(); + mkdirp(td.path().join(".git/info")); + wfile(td.path().join(".git/info/exclude"), "foo\n!bar"); + + let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); + assert!(err.is_none()); + assert!(ig.matched("foo", false).is_ignore()); + assert!(ig.matched("bar", false).is_whitelist()); + assert!(ig.matched("baz", false).is_none()); + } + + #[test] + fn gitignore() { + let td = TempDir::new("ignore-test-").unwrap(); + wfile(td.path().join(".gitignore"), "foo\n!bar"); + + let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); + assert!(err.is_none()); + assert!(ig.matched("foo", false).is_ignore()); + assert!(ig.matched("bar", false).is_whitelist()); + assert!(ig.matched("baz", false).is_none()); + } + + #[test] + fn ignore() { + let td = TempDir::new("ignore-test-").unwrap(); + wfile(td.path().join(".ignore"), "foo\n!bar"); + + let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); + assert!(err.is_none()); + assert!(ig.matched("foo", false).is_ignore()); + assert!(ig.matched("bar", false).is_whitelist()); + assert!(ig.matched("baz", false).is_none()); + } + + #[test] + fn custom_ignore() { + let td = TempDir::new("ignore-test-").unwrap(); + let custom_ignore = ".customignore"; + wfile(td.path().join(custom_ignore), "foo\n!bar"); + + let (ig, err) = IgnoreBuilder::new() + .add_custom_ignore_filename(custom_ignore) + .build().add_child(td.path()); + assert!(err.is_none()); + assert!(ig.matched("foo", false).is_ignore()); + assert!(ig.matched("bar", false).is_whitelist()); + assert!(ig.matched("baz", false).is_none()); + } + + // Tests that a custom ignore file will override an .ignore. + #[test] + fn custom_ignore_over_ignore() { + let td = TempDir::new("ignore-test-").unwrap(); + let custom_ignore = ".customignore"; + wfile(td.path().join(".ignore"), "foo"); + wfile(td.path().join(custom_ignore), "!foo"); + + let (ig, err) = IgnoreBuilder::new() + .add_custom_ignore_filename(custom_ignore) + .build().add_child(td.path()); + assert!(err.is_none()); + assert!(ig.matched("foo", false).is_whitelist()); + } + + // Tests that earlier custom ignore files have lower precedence than later. + #[test] + fn custom_ignore_precedence() { + let td = TempDir::new("ignore-test-").unwrap(); + let custom_ignore1 = ".customignore1"; + let custom_ignore2 = ".customignore2"; + wfile(td.path().join(custom_ignore1), "foo"); + wfile(td.path().join(custom_ignore2), "!foo"); + + let (ig, err) = IgnoreBuilder::new() + .add_custom_ignore_filename(custom_ignore1) + .add_custom_ignore_filename(custom_ignore2) + .build().add_child(td.path()); + assert!(err.is_none()); + assert!(ig.matched("foo", false).is_whitelist()); + } + + // Tests that an .ignore will override a .gitignore. + #[test] + fn ignore_over_gitignore() { + let td = TempDir::new("ignore-test-").unwrap(); + wfile(td.path().join(".gitignore"), "foo"); + wfile(td.path().join(".ignore"), "!foo"); + + let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); + assert!(err.is_none()); + assert!(ig.matched("foo", false).is_whitelist()); + } + + // Tests that exclude has lower precedent than both .ignore and .gitignore. + #[test] + fn exclude_lowest() { + let td = TempDir::new("ignore-test-").unwrap(); + wfile(td.path().join(".gitignore"), "!foo"); + wfile(td.path().join(".ignore"), "!bar"); + mkdirp(td.path().join(".git/info")); + wfile(td.path().join(".git/info/exclude"), "foo\nbar\nbaz"); + + let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); + assert!(err.is_none()); + assert!(ig.matched("baz", false).is_ignore()); + assert!(ig.matched("foo", false).is_whitelist()); + assert!(ig.matched("bar", false).is_whitelist()); + } + + #[test] + fn errored() { + let td = TempDir::new("ignore-test-").unwrap(); + wfile(td.path().join(".gitignore"), "f**oo"); + + let (_, err) = IgnoreBuilder::new().build().add_child(td.path()); + assert!(err.is_some()); + } + + #[test] + fn errored_both() { + let td = TempDir::new("ignore-test-").unwrap(); + wfile(td.path().join(".gitignore"), "f**oo"); + wfile(td.path().join(".ignore"), "fo**o"); + + let (_, err) = IgnoreBuilder::new().build().add_child(td.path()); + assert_eq!(2, partial(err.expect("an error")).len()); + } + + #[test] + fn errored_partial() { + let td = TempDir::new("ignore-test-").unwrap(); + wfile(td.path().join(".gitignore"), "f**oo\nbar"); + + let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); + assert!(err.is_some()); + assert!(ig.matched("bar", false).is_ignore()); + } + + #[test] + fn errored_partial_and_ignore() { + let td = TempDir::new("ignore-test-").unwrap(); + wfile(td.path().join(".gitignore"), "f**oo\nbar"); + wfile(td.path().join(".ignore"), "!bar"); + + let (ig, err) = IgnoreBuilder::new().build().add_child(td.path()); + assert!(err.is_some()); + assert!(ig.matched("bar", false).is_whitelist()); + } + + #[test] + fn not_present_empty() { + let td = TempDir::new("ignore-test-").unwrap(); + + let (_, err) = IgnoreBuilder::new().build().add_child(td.path()); + assert!(err.is_none()); + } + + #[test] + fn stops_at_git_dir() { + // This tests that .gitignore files beyond a .git barrier aren't + // matched, but .ignore files are. + let td = TempDir::new("ignore-test-").unwrap(); + mkdirp(td.path().join(".git")); + mkdirp(td.path().join("foo/.git")); + wfile(td.path().join(".gitignore"), "foo"); + wfile(td.path().join(".ignore"), "bar"); + + let ig0 = IgnoreBuilder::new().build(); + let (ig1, err) = ig0.add_child(td.path()); + assert!(err.is_none()); + let (ig2, err) = ig1.add_child(ig1.path().join("foo")); + assert!(err.is_none()); + + assert!(ig1.matched("foo", false).is_ignore()); + assert!(ig2.matched("foo", false).is_none()); + + assert!(ig1.matched("bar", false).is_ignore()); + assert!(ig2.matched("bar", false).is_ignore()); + } + + #[test] + fn absolute_parent() { + let td = TempDir::new("ignore-test-").unwrap(); + mkdirp(td.path().join(".git")); + mkdirp(td.path().join("foo")); + wfile(td.path().join(".gitignore"), "bar"); + + // First, check that the parent gitignore file isn't detected if the + // parent isn't added. This establishes a baseline. + let ig0 = IgnoreBuilder::new().build(); + let (ig1, err) = ig0.add_child(td.path().join("foo")); + assert!(err.is_none()); + assert!(ig1.matched("bar", false).is_none()); + + // Second, check that adding a parent directory actually works. + let ig0 = IgnoreBuilder::new().build(); + let (ig1, err) = ig0.add_parents(td.path().join("foo")); + assert!(err.is_none()); + let (ig2, err) = ig1.add_child(td.path().join("foo")); + assert!(err.is_none()); + assert!(ig2.matched("bar", false).is_ignore()); + } + + #[test] + fn absolute_parent_anchored() { + let td = TempDir::new("ignore-test-").unwrap(); + mkdirp(td.path().join(".git")); + mkdirp(td.path().join("src/llvm")); + wfile(td.path().join(".gitignore"), "/llvm/\nfoo"); + + let ig0 = IgnoreBuilder::new().build(); + let (ig1, err) = ig0.add_parents(td.path().join("src")); + assert!(err.is_none()); + let (ig2, err) = ig1.add_child("src"); + assert!(err.is_none()); + + assert!(ig1.matched("llvm", true).is_none()); + assert!(ig2.matched("llvm", true).is_none()); + assert!(ig2.matched("src/llvm", true).is_none()); + assert!(ig2.matched("foo", false).is_ignore()); + assert!(ig2.matched("src/foo", false).is_ignore()); + } +} diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/src/gitignore.rs cargo-0.26.0/vendor/ignore-0.4.1/src/gitignore.rs --- cargo-0.25.0/vendor/ignore-0.4.1/src/gitignore.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/src/gitignore.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,710 @@ +/*! +The gitignore module provides a way to match globs from a gitignore file +against file paths. + +Note that this module implements the specification as described in the +`gitignore` man page from scratch. That is, this module does *not* shell out to +the `git` command line tool. +*/ + +use std::cell::RefCell; +use std::env; +use std::fs::File; +use std::io::{self, BufRead, Read}; +use std::path::{Path, PathBuf}; +use std::str; +use std::sync::Arc; + +use globset::{Candidate, GlobBuilder, GlobSet, GlobSetBuilder}; +use regex::bytes::Regex; +use thread_local::ThreadLocal; + +use pathutil::{is_file_name, strip_prefix}; +use {Error, Match, PartialErrorBuilder}; + +/// Glob represents a single glob in a gitignore file. +/// +/// This is used to report information about the highest precedent glob that +/// matched in one or more gitignore files. +#[derive(Clone, Debug)] +pub struct Glob { + /// The file path that this glob was extracted from. + from: Option, + /// The original glob string. + original: String, + /// The actual glob string used to convert to a regex. + actual: String, + /// Whether this is a whitelisted glob or not. + is_whitelist: bool, + /// Whether this glob should only match directories or not. + is_only_dir: bool, +} + +impl Glob { + /// Returns the file path that defined this glob. + pub fn from(&self) -> Option<&Path> { + self.from.as_ref().map(|p| &**p) + } + + /// The original glob as it was defined in a gitignore file. + pub fn original(&self) -> &str { + &self.original + } + + /// The actual glob that was compiled to respect gitignore + /// semantics. + pub fn actual(&self) -> &str { + &self.actual + } + + /// Whether this was a whitelisted glob or not. + pub fn is_whitelist(&self) -> bool { + self.is_whitelist + } + + /// Whether this glob must match a directory or not. + pub fn is_only_dir(&self) -> bool { + self.is_only_dir + } + + /// Returns true if and only if this glob has a `**/` prefix. + fn has_doublestar_prefix(&self) -> bool { + self.actual.starts_with("**/") + || (self.actual == "**" && self.is_only_dir) + } +} + +/// Gitignore is a matcher for the globs in one or more gitignore files +/// in the same directory. +#[derive(Clone, Debug)] +pub struct Gitignore { + set: GlobSet, + root: PathBuf, + globs: Vec, + num_ignores: u64, + num_whitelists: u64, + matches: Arc>>>, +} + +impl Gitignore { + /// Creates a new gitignore matcher from the gitignore file path given. + /// + /// If it's desirable to include multiple gitignore files in a single + /// matcher, or read gitignore globs from a different source, then + /// use `GitignoreBuilder`. + /// + /// This always returns a valid matcher, even if it's empty. In particular, + /// a Gitignore file can be partially valid, e.g., when one glob is invalid + /// but the rest aren't. + /// + /// Note that I/O errors are ignored. For more granular control over + /// errors, use `GitignoreBuilder`. + pub fn new>( + gitignore_path: P, + ) -> (Gitignore, Option) { + let path = gitignore_path.as_ref(); + let parent = path.parent().unwrap_or(Path::new("/")); + let mut builder = GitignoreBuilder::new(parent); + let mut errs = PartialErrorBuilder::default(); + errs.maybe_push_ignore_io(builder.add(path)); + match builder.build() { + Ok(gi) => (gi, errs.into_error_option()), + Err(err) => { + errs.push(err); + (Gitignore::empty(), errs.into_error_option()) + } + } + } + + /// Creates a new gitignore matcher from the global ignore file, if one + /// exists. + /// + /// The global config file path is specified by git's `core.excludesFile` + /// config option. + /// + /// Git's config file location is `$HOME/.gitconfig`. If `$HOME/.gitconfig` + /// does not exist or does not specify `core.excludesFile`, then + /// `$XDG_CONFIG_HOME/git/ignore` is read. If `$XDG_CONFIG_HOME` is not + /// set or is empty, then `$HOME/.config/git/ignore` is used instead. + pub fn global() -> (Gitignore, Option) { + match gitconfig_excludes_path() { + None => (Gitignore::empty(), None), + Some(path) => { + if !path.is_file() { + (Gitignore::empty(), None) + } else { + Gitignore::new(path) + } + } + } + } + + /// Creates a new empty gitignore matcher that never matches anything. + /// + /// Its path is empty. + pub fn empty() -> Gitignore { + GitignoreBuilder::new("").build().unwrap() + } + + /// Returns the directory containing this gitignore matcher. + /// + /// All matches are done relative to this path. + pub fn path(&self) -> &Path { + &*self.root + } + + /// Returns true if and only if this gitignore has zero globs, and + /// therefore never matches any file path. + pub fn is_empty(&self) -> bool { + self.set.is_empty() + } + + /// Returns the total number of globs, which should be equivalent to + /// `num_ignores + num_whitelists`. + pub fn len(&self) -> usize { + self.set.len() + } + + /// Returns the total number of ignore globs. + pub fn num_ignores(&self) -> u64 { + self.num_ignores + } + + /// Returns the total number of whitelisted globs. + pub fn num_whitelists(&self) -> u64 { + self.num_whitelists + } + + /// Returns whether the given path (file or directory) matched a pattern in + /// this gitignore matcher. + /// + /// `is_dir` should be true if the path refers to a directory and false + /// otherwise. + /// + /// The given path is matched relative to the path given when building + /// the matcher. Specifically, before matching `path`, its prefix (as + /// determined by a common suffix of the directory containing this + /// gitignore) is stripped. If there is no common suffix/prefix overlap, + /// then `path` is assumed to be relative to this matcher. + pub fn matched>( + &self, + path: P, + is_dir: bool, + ) -> Match<&Glob> { + if self.is_empty() { + return Match::None; + } + self.matched_stripped(self.strip(path.as_ref()), is_dir) + } + + /// Returns whether the given path (file or directory, and expected to be + /// under the root) or any of its parent directories (up to the root) + /// matched a pattern in this gitignore matcher. + /// + /// NOTE: This method is more expensive than walking the directory hierarchy + /// top-to-bottom and matching the entries. But, is easier to use in cases + /// when a list of paths are available without a hierarchy. + /// + /// `is_dir` should be true if the path refers to a directory and false + /// otherwise. + /// + /// The given path is matched relative to the path given when building + /// the matcher. Specifically, before matching `path`, its prefix (as + /// determined by a common suffix of the directory containing this + /// gitignore) is stripped. If there is no common suffix/prefix overlap, + /// then `path` is assumed to be relative to this matcher. + pub fn matched_path_or_any_parents>( + &self, + path: P, + is_dir: bool, + ) -> Match<&Glob> { + if self.is_empty() { + return Match::None; + } + let mut path = self.strip(path.as_ref()); + debug_assert!( + !path.has_root(), + "path is expect to be under the root" + ); + match self.matched_stripped(path, is_dir) { + Match::None => (), // walk up + a_match => return a_match, + } + while let Some(parent) = path.parent() { + match self.matched_stripped(parent, /* is_dir */ true) { + Match::None => path = parent, // walk up + a_match => return a_match, + } + } + Match::None + } + + /// Like matched, but takes a path that has already been stripped. + fn matched_stripped>( + &self, + path: P, + is_dir: bool, + ) -> Match<&Glob> { + if self.is_empty() { + return Match::None; + } + let path = path.as_ref(); + let _matches = self.matches.get_default(); + let mut matches = _matches.borrow_mut(); + let candidate = Candidate::new(path); + self.set.matches_candidate_into(&candidate, &mut *matches); + for &i in matches.iter().rev() { + let glob = &self.globs[i]; + if !glob.is_only_dir() || is_dir { + return if glob.is_whitelist() { + Match::Whitelist(glob) + } else { + Match::Ignore(glob) + }; + } + } + Match::None + } + + /// Strips the given path such that it's suitable for matching with this + /// gitignore matcher. + fn strip<'a, P: 'a + AsRef + ?Sized>( + &'a self, + path: &'a P, + ) -> &'a Path { + let mut path = path.as_ref(); + // A leading ./ is completely superfluous. We also strip it from + // our gitignore root path, so we need to strip it from our candidate + // path too. + if let Some(p) = strip_prefix("./", path) { + path = p; + } + // Strip any common prefix between the candidate path and the root + // of the gitignore, to make sure we get relative matching right. + // BUT, a file name might not have any directory components to it, + // in which case, we don't want to accidentally strip any part of the + // file name. + // + // As an additional special case, if the root is just `.`, then we + // shouldn't try to strip anything, e.g., when path begins with a `.`. + if self.root != Path::new(".") && !is_file_name(path) { + if let Some(p) = strip_prefix(&self.root, path) { + path = p; + // If we're left with a leading slash, get rid of it. + if let Some(p) = strip_prefix("/", path) { + path = p; + } + } + } + path + } +} + +/// Builds a matcher for a single set of globs from a .gitignore file. +pub struct GitignoreBuilder { + builder: GlobSetBuilder, + root: PathBuf, + globs: Vec, + case_insensitive: bool, +} + +impl GitignoreBuilder { + /// Create a new builder for a gitignore file. + /// + /// The path given should be the path at which the globs for this gitignore + /// file should be matched. Note that paths are always matched relative + /// to the root path given here. Generally, the root path should correspond + /// to the *directory* containing a `.gitignore` file. + pub fn new>(root: P) -> GitignoreBuilder { + let root = root.as_ref(); + GitignoreBuilder { + builder: GlobSetBuilder::new(), + root: strip_prefix("./", root).unwrap_or(root).to_path_buf(), + globs: vec![], + case_insensitive: false, + } + } + + /// Builds a new matcher from the globs added so far. + /// + /// Once a matcher is built, no new globs can be added to it. + pub fn build(&self) -> Result { + let nignore = self.globs.iter().filter(|g| !g.is_whitelist()).count(); + let nwhite = self.globs.iter().filter(|g| g.is_whitelist()).count(); + let set = + self.builder.build().map_err(|err| { + Error::Glob { + glob: None, + err: err.to_string(), + } + })?; + Ok(Gitignore { + set: set, + root: self.root.clone(), + globs: self.globs.clone(), + num_ignores: nignore as u64, + num_whitelists: nwhite as u64, + matches: Arc::new(ThreadLocal::default()), + }) + } + + /// Add each glob from the file path given. + /// + /// The file given should be formatted as a `gitignore` file. + /// + /// Note that partial errors can be returned. For example, if there was + /// a problem adding one glob, an error for that will be returned, but + /// all other valid globs will still be added. + pub fn add>(&mut self, path: P) -> Option { + let path = path.as_ref(); + let file = match File::open(path) { + Err(err) => return Some(Error::Io(err).with_path(path)), + Ok(file) => file, + }; + let rdr = io::BufReader::new(file); + let mut errs = PartialErrorBuilder::default(); + for (i, line) in rdr.lines().enumerate() { + let lineno = (i + 1) as u64; + let line = match line { + Ok(line) => line, + Err(err) => { + errs.push(Error::Io(err).tagged(path, lineno)); + break; + } + }; + if let Err(err) = self.add_line(Some(path.to_path_buf()), &line) { + errs.push(err.tagged(path, lineno)); + } + } + errs.into_error_option() + } + + /// Add each glob line from the string given. + /// + /// If this string came from a particular `gitignore` file, then its path + /// should be provided here. + /// + /// The string given should be formatted as a `gitignore` file. + #[cfg(test)] + fn add_str( + &mut self, + from: Option, + gitignore: &str, + ) -> Result<&mut GitignoreBuilder, Error> { + for line in gitignore.lines() { + self.add_line(from.clone(), line)?; + } + Ok(self) + } + + /// Add a line from a gitignore file to this builder. + /// + /// If this line came from a particular `gitignore` file, then its path + /// should be provided here. + /// + /// If the line could not be parsed as a glob, then an error is returned. + pub fn add_line( + &mut self, + from: Option, + mut line: &str, + ) -> Result<&mut GitignoreBuilder, Error> { + if line.starts_with("#") { + return Ok(self); + } + if !line.ends_with("\\ ") { + line = line.trim_right(); + } + if line.is_empty() { + return Ok(self); + } + let mut glob = Glob { + from: from, + original: line.to_string(), + actual: String::new(), + is_whitelist: false, + is_only_dir: false, + }; + let mut literal_separator = false; + let mut is_absolute = false; + if line.starts_with("\\!") || line.starts_with("\\#") { + line = &line[1..]; + is_absolute = line.chars().nth(0) == Some('/'); + } else { + if line.starts_with("!") { + glob.is_whitelist = true; + line = &line[1..]; + } + if line.starts_with("/") { + // `man gitignore` says that if a glob starts with a slash, + // then the glob can only match the beginning of a path + // (relative to the location of gitignore). We achieve this by + // simply banning wildcards from matching /. + literal_separator = true; + line = &line[1..]; + is_absolute = true; + } + } + // If it ends with a slash, then this should only match directories, + // but the slash should otherwise not be used while globbing. + if let Some((i, c)) = line.char_indices().rev().nth(0) { + if c == '/' { + glob.is_only_dir = true; + line = &line[..i]; + } + } + // If there is a literal slash, then we note that so that globbing + // doesn't let wildcards match slashes. + glob.actual = line.to_string(); + if is_absolute || line.chars().any(|c| c == '/') { + literal_separator = true; + } + // If there was a slash, then this is a glob that must match the entire + // path name. Otherwise, we should let it match anywhere, so use a **/ + // prefix. + if !literal_separator { + // ... but only if we don't already have a **/ prefix. + if !glob.has_doublestar_prefix() { + glob.actual = format!("**/{}", glob.actual); + } + } + // If the glob ends with `/**`, then we should only match everything + // inside a directory, but not the directory itself. Standard globs + // will match the directory. So we add `/*` to force the issue. + if glob.actual.ends_with("/**") { + glob.actual = format!("{}/*", glob.actual); + } + let parsed = + GlobBuilder::new(&glob.actual) + .literal_separator(literal_separator) + .case_insensitive(self.case_insensitive) + .build() + .map_err(|err| { + Error::Glob { + glob: Some(glob.original.clone()), + err: err.kind().to_string(), + } + })?; + self.builder.add(parsed); + self.globs.push(glob); + Ok(self) + } + + /// Toggle whether the globs should be matched case insensitively or not. + /// + /// This is disabled by default. + pub fn case_insensitive( + &mut self, yes: bool + ) -> Result<&mut GitignoreBuilder, Error> { + self.case_insensitive = yes; + Ok(self) + } +} + +/// Return the file path of the current environment's global gitignore file. +/// +/// Note that the file path returned may not exist. +fn gitconfig_excludes_path() -> Option { + gitconfig_contents() + .and_then(|data| parse_excludes_file(&data)) + .or_else(excludes_file_default) +} + +/// Returns the file contents of git's global config file, if one exists. +fn gitconfig_contents() -> Option> { + let home = match env::var_os("HOME") { + None => return None, + Some(home) => PathBuf::from(home), + }; + let mut file = match File::open(home.join(".gitconfig")) { + Err(_) => return None, + Ok(file) => io::BufReader::new(file), + }; + let mut contents = vec![]; + file.read_to_end(&mut contents).ok().map(|_| contents) +} + +/// Returns the default file path for a global .gitignore file. +/// +/// Specifically, this respects XDG_CONFIG_HOME. +fn excludes_file_default() -> Option { + env::var_os("XDG_CONFIG_HOME") + .and_then(|x| if x.is_empty() { None } else { Some(PathBuf::from(x)) }) + .or_else(|| env::home_dir().map(|p| p.join(".config"))) + .map(|x| x.join("git/ignore")) +} + +/// Extract git's `core.excludesfile` config setting from the raw file contents +/// given. +fn parse_excludes_file(data: &[u8]) -> Option { + // N.B. This is the lazy approach, and isn't technically correct, but + // probably works in more circumstances. I guess we would ideally have + // a full INI parser. Yuck. + lazy_static! { + static ref RE: Regex = Regex::new( + r"(?ium)^\s*excludesfile\s*=\s*(.+)\s*$").unwrap(); + }; + let caps = match RE.captures(data) { + None => return None, + Some(caps) => caps, + }; + str::from_utf8(&caps[1]).ok().map(|s| PathBuf::from(expand_tilde(s))) +} + +/// Expands ~ in file paths to the value of $HOME. +fn expand_tilde(path: &str) -> String { + let home = match env::var("HOME") { + Err(_) => return path.to_string(), + Ok(home) => home, + }; + path.replace("~", &home) +} + +#[cfg(test)] +mod tests { + use std::path::Path; + use super::{Gitignore, GitignoreBuilder}; + + fn gi_from_str>(root: P, s: &str) -> Gitignore { + let mut builder = GitignoreBuilder::new(root); + builder.add_str(None, s).unwrap(); + builder.build().unwrap() + } + + macro_rules! ignored { + ($name:ident, $root:expr, $gi:expr, $path:expr) => { + ignored!($name, $root, $gi, $path, false); + }; + ($name:ident, $root:expr, $gi:expr, $path:expr, $is_dir:expr) => { + #[test] + fn $name() { + let gi = gi_from_str($root, $gi); + assert!(gi.matched($path, $is_dir).is_ignore()); + } + }; + } + + macro_rules! not_ignored { + ($name:ident, $root:expr, $gi:expr, $path:expr) => { + not_ignored!($name, $root, $gi, $path, false); + }; + ($name:ident, $root:expr, $gi:expr, $path:expr, $is_dir:expr) => { + #[test] + fn $name() { + let gi = gi_from_str($root, $gi); + assert!(!gi.matched($path, $is_dir).is_ignore()); + } + }; + } + + const ROOT: &'static str = "/home/foobar/rust/rg"; + + ignored!(ig1, ROOT, "months", "months"); + ignored!(ig2, ROOT, "*.lock", "Cargo.lock"); + ignored!(ig3, ROOT, "*.rs", "src/main.rs"); + ignored!(ig4, ROOT, "src/*.rs", "src/main.rs"); + ignored!(ig5, ROOT, "/*.c", "cat-file.c"); + ignored!(ig6, ROOT, "/src/*.rs", "src/main.rs"); + ignored!(ig7, ROOT, "!src/main.rs\n*.rs", "src/main.rs"); + ignored!(ig8, ROOT, "foo/", "foo", true); + ignored!(ig9, ROOT, "**/foo", "foo"); + ignored!(ig10, ROOT, "**/foo", "src/foo"); + ignored!(ig11, ROOT, "**/foo/**", "src/foo/bar"); + ignored!(ig12, ROOT, "**/foo/**", "wat/src/foo/bar/baz"); + ignored!(ig13, ROOT, "**/foo/bar", "foo/bar"); + ignored!(ig14, ROOT, "**/foo/bar", "src/foo/bar"); + ignored!(ig15, ROOT, "abc/**", "abc/x"); + ignored!(ig16, ROOT, "abc/**", "abc/x/y"); + ignored!(ig17, ROOT, "abc/**", "abc/x/y/z"); + ignored!(ig18, ROOT, "a/**/b", "a/b"); + ignored!(ig19, ROOT, "a/**/b", "a/x/b"); + ignored!(ig20, ROOT, "a/**/b", "a/x/y/b"); + ignored!(ig21, ROOT, r"\!xy", "!xy"); + ignored!(ig22, ROOT, r"\#foo", "#foo"); + ignored!(ig23, ROOT, "foo", "./foo"); + ignored!(ig24, ROOT, "target", "grep/target"); + ignored!(ig25, ROOT, "Cargo.lock", "./tabwriter-bin/Cargo.lock"); + ignored!(ig26, ROOT, "/foo/bar/baz", "./foo/bar/baz"); + ignored!(ig27, ROOT, "foo/", "xyz/foo", true); + ignored!(ig28, "./src", "/llvm/", "./src/llvm", true); + ignored!(ig29, ROOT, "node_modules/ ", "node_modules", true); + ignored!(ig30, ROOT, "**/", "foo/bar", true); + ignored!(ig31, ROOT, "path1/*", "path1/foo"); + ignored!(ig32, ROOT, ".a/b", ".a/b"); + ignored!(ig33, "./", ".a/b", ".a/b"); + ignored!(ig34, ".", ".a/b", ".a/b"); + ignored!(ig35, "./.", ".a/b", ".a/b"); + ignored!(ig36, "././", ".a/b", ".a/b"); + ignored!(ig37, "././.", ".a/b", ".a/b"); + + not_ignored!(ignot1, ROOT, "amonths", "months"); + not_ignored!(ignot2, ROOT, "monthsa", "months"); + not_ignored!(ignot3, ROOT, "/src/*.rs", "src/grep/src/main.rs"); + not_ignored!(ignot4, ROOT, "/*.c", "mozilla-sha1/sha1.c"); + not_ignored!(ignot5, ROOT, "/src/*.rs", "src/grep/src/main.rs"); + not_ignored!(ignot6, ROOT, "*.rs\n!src/main.rs", "src/main.rs"); + not_ignored!(ignot7, ROOT, "foo/", "foo", false); + not_ignored!(ignot8, ROOT, "**/foo/**", "wat/src/afoo/bar/baz"); + not_ignored!(ignot9, ROOT, "**/foo/**", "wat/src/fooa/bar/baz"); + not_ignored!(ignot10, ROOT, "**/foo/bar", "foo/src/bar"); + not_ignored!(ignot11, ROOT, "#foo", "#foo"); + not_ignored!(ignot12, ROOT, "\n\n\n", "foo"); + not_ignored!(ignot13, ROOT, "foo/**", "foo", true); + not_ignored!( + ignot14, "./third_party/protobuf", "m4/ltoptions.m4", + "./third_party/protobuf/csharp/src/packages/repositories.config"); + not_ignored!(ignot15, ROOT, "!/bar", "foo/bar"); + not_ignored!(ignot16, ROOT, "*\n!**/", "foo", true); + not_ignored!(ignot17, ROOT, "src/*.rs", "src/grep/src/main.rs"); + not_ignored!(ignot18, ROOT, "path1/*", "path2/path1/foo"); + + fn bytes(s: &str) -> Vec { + s.to_string().into_bytes() + } + + fn path_string>(path: P) -> String { + path.as_ref().to_str().unwrap().to_string() + } + + #[test] + fn parse_excludes_file1() { + let data = bytes("[core]\nexcludesFile = /foo/bar"); + let got = super::parse_excludes_file(&data).unwrap(); + assert_eq!(path_string(got), "/foo/bar"); + } + + #[test] + fn parse_excludes_file2() { + let data = bytes("[core]\nexcludesFile = ~/foo/bar"); + let got = super::parse_excludes_file(&data).unwrap(); + assert_eq!(path_string(got), super::expand_tilde("~/foo/bar")); + } + + #[test] + fn parse_excludes_file3() { + let data = bytes("[core]\nexcludeFile = /foo/bar"); + assert!(super::parse_excludes_file(&data).is_none()); + } + + // See: https://github.com/BurntSushi/ripgrep/issues/106 + #[test] + fn regression_106() { + gi_from_str("/", " "); + } + + #[test] + fn case_insensitive() { + let gi = GitignoreBuilder::new(ROOT) + .case_insensitive(true).unwrap() + .add_str(None, "*.html").unwrap() + .build().unwrap(); + assert!(gi.matched("foo.html", false).is_ignore()); + assert!(gi.matched("foo.HTML", false).is_ignore()); + assert!(!gi.matched("foo.htm", false).is_ignore()); + assert!(!gi.matched("foo.HTM", false).is_ignore()); + } + + ignored!(cs1, ROOT, "*.html", "foo.html"); + not_ignored!(cs2, ROOT, "*.html", "foo.HTML"); + not_ignored!(cs3, ROOT, "*.html", "foo.htm"); + not_ignored!(cs4, ROOT, "*.html", "foo.HTM"); +} diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/src/lib.rs cargo-0.26.0/vendor/ignore-0.4.1/src/lib.rs --- cargo-0.25.0/vendor/ignore-0.4.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,406 @@ +/*! +The ignore crate provides a fast recursive directory iterator that respects +various filters such as globs, file types and `.gitignore` files. The precise +matching rules and precedence is explained in the documentation for +`WalkBuilder`. + +Secondarily, this crate exposes gitignore and file type matchers for use cases +that demand more fine-grained control. + +# Example + +This example shows the most basic usage of this crate. This code will +recursively traverse the current directory while automatically filtering out +files and directories according to ignore globs found in files like +`.ignore` and `.gitignore`: + + +```rust,no_run +use ignore::Walk; + +for result in Walk::new("./") { + // Each item yielded by the iterator is either a directory entry or an + // error, so either print the path or the error. + match result { + Ok(entry) => println!("{}", entry.path().display()), + Err(err) => println!("ERROR: {}", err), + } +} +``` + +# Example: advanced + +By default, the recursive directory iterator will ignore hidden files and +directories. This can be disabled by building the iterator with `WalkBuilder`: + +```rust,no_run +use ignore::WalkBuilder; + +for result in WalkBuilder::new("./").hidden(false).build() { + println!("{:?}", result); +} +``` + +See the documentation for `WalkBuilder` for many other options. +*/ + +#![deny(missing_docs)] + +extern crate crossbeam; +extern crate globset; +#[macro_use] +extern crate lazy_static; +#[macro_use] +extern crate log; +extern crate memchr; +extern crate regex; +extern crate same_file; +#[cfg(test)] +extern crate tempdir; +extern crate thread_local; +extern crate walkdir; +#[cfg(windows)] +extern crate winapi; + +use std::error; +use std::fmt; +use std::io; +use std::path::{Path, PathBuf}; + +pub use walk::{DirEntry, Walk, WalkBuilder, WalkParallel, WalkState}; + +mod dir; +pub mod gitignore; +mod pathutil; +pub mod overrides; +pub mod types; +mod walk; + +/// Represents an error that can occur when parsing a gitignore file. +#[derive(Debug)] +pub enum Error { + /// A collection of "soft" errors. These occur when adding an ignore + /// file partially succeeded. + Partial(Vec), + /// An error associated with a specific line number. + WithLineNumber { + /// The line number. + line: u64, + /// The underlying error. + err: Box, + }, + /// An error associated with a particular file path. + WithPath { + /// The file path. + path: PathBuf, + /// The underlying error. + err: Box, + }, + /// An error associated with a particular directory depth when recursively + /// walking a directory. + WithDepth { + /// The directory depth. + depth: usize, + /// The underlying error. + err: Box, + }, + /// An error that occurs when a file loop is detected when traversing + /// symbolic links. + Loop { + /// The ancestor file path in the loop. + ancestor: PathBuf, + /// The child file path in the loop. + child: PathBuf, + }, + /// An error that occurs when doing I/O, such as reading an ignore file. + Io(io::Error), + /// An error that occurs when trying to parse a glob. + Glob { + /// The original glob that caused this error. This glob, when + /// available, always corresponds to the glob provided by an end user. + /// e.g., It is the glob as written in a `.gitignore` file. + /// + /// (This glob may be distinct from the glob that is actually + /// compiled, after accounting for `gitignore` semantics.) + glob: Option, + /// The underlying glob error as a string. + err: String, + }, + /// A type selection for a file type that is not defined. + UnrecognizedFileType(String), + /// A user specified file type definition could not be parsed. + InvalidDefinition, +} + +impl Error { + /// Returns true if this is a partial error. + /// + /// A partial error occurs when only some operations failed while others + /// may have succeeded. For example, an ignore file may contain an invalid + /// glob among otherwise valid globs. + pub fn is_partial(&self) -> bool { + match *self { + Error::Partial(_) => true, + Error::WithLineNumber { ref err, .. } => err.is_partial(), + Error::WithPath { ref err, .. } => err.is_partial(), + Error::WithDepth { ref err, .. } => err.is_partial(), + _ => false, + } + } + + /// Returns true if this error is exclusively an I/O error. + pub fn is_io(&self) -> bool { + match *self { + Error::Partial(ref errs) => errs.len() == 1 && errs[0].is_io(), + Error::WithLineNumber { ref err, .. } => err.is_io(), + Error::WithPath { ref err, .. } => err.is_io(), + Error::WithDepth { ref err, .. } => err.is_io(), + Error::Loop { .. } => false, + Error::Io(_) => true, + Error::Glob { .. } => false, + Error::UnrecognizedFileType(_) => false, + Error::InvalidDefinition => false, + } + } + + /// Returns a depth associated with recursively walking a directory (if + /// this error was generated from a recursive directory iterator). + pub fn depth(&self) -> Option { + match *self { + Error::WithPath { ref err, .. } => err.depth(), + Error::WithDepth { depth, .. } => Some(depth), + _ => None, + } + } + + /// Turn an error into a tagged error with the given file path. + fn with_path>(self, path: P) -> Error { + Error::WithPath { + path: path.as_ref().to_path_buf(), + err: Box::new(self), + } + } + + /// Turn an error into a tagged error with the given depth. + fn with_depth(self, depth: usize) -> Error { + Error::WithDepth { + depth: depth, + err: Box::new(self), + } + } + + /// Turn an error into a tagged error with the given file path and line + /// number. If path is empty, then it is omitted from the error. + fn tagged>(self, path: P, lineno: u64) -> Error { + let errline = Error::WithLineNumber { + line: lineno, + err: Box::new(self), + }; + if path.as_ref().as_os_str().is_empty() { + return errline; + } + errline.with_path(path) + } + + /// Build an error from a walkdir error. + fn from_walkdir(err: walkdir::Error) -> Error { + let depth = err.depth(); + if let (Some(anc), Some(child)) = (err.loop_ancestor(), err.path()) { + return Error::WithDepth { + depth: depth, + err: Box::new(Error::Loop { + ancestor: anc.to_path_buf(), + child: child.to_path_buf(), + }), + }; + } + let path = err.path().map(|p| p.to_path_buf()); + let mut ig_err = Error::Io(io::Error::from(err)); + if let Some(path) = path { + ig_err = Error::WithPath { + path: path, + err: Box::new(ig_err), + }; + } + ig_err + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::Partial(_) => "partial error", + Error::WithLineNumber { ref err, .. } => err.description(), + Error::WithPath { ref err, .. } => err.description(), + Error::WithDepth { ref err, .. } => err.description(), + Error::Loop { .. } => "file system loop found", + Error::Io(ref err) => err.description(), + Error::Glob { ref err, .. } => err, + Error::UnrecognizedFileType(_) => "unrecognized file type", + Error::InvalidDefinition => "invalid definition", + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::Partial(ref errs) => { + let msgs: Vec = + errs.iter().map(|err| err.to_string()).collect(); + write!(f, "{}", msgs.join("\n")) + } + Error::WithLineNumber { line, ref err } => { + write!(f, "line {}: {}", line, err) + } + Error::WithPath { ref path, ref err } => { + write!(f, "{}: {}", path.display(), err) + } + Error::WithDepth { ref err, .. } => err.fmt(f), + Error::Loop { ref ancestor, ref child } => { + write!(f, "File system loop found: \ + {} points to an ancestor {}", + child.display(), ancestor.display()) + } + Error::Io(ref err) => err.fmt(f), + Error::Glob { glob: None, ref err } => write!(f, "{}", err), + Error::Glob { glob: Some(ref glob), ref err } => { + write!(f, "error parsing glob '{}': {}", glob, err) + } + Error::UnrecognizedFileType(ref ty) => { + write!(f, "unrecognized file type: {}", ty) + } + Error::InvalidDefinition => { + write!(f, "invalid definition (format is type:glob, e.g., \ + html:*.html)") + } + } + } +} + +impl From for Error { + fn from(err: io::Error) -> Error { + Error::Io(err) + } +} + +#[derive(Debug, Default)] +struct PartialErrorBuilder(Vec); + +impl PartialErrorBuilder { + fn push(&mut self, err: Error) { + self.0.push(err); + } + + fn push_ignore_io(&mut self, err: Error) { + if !err.is_io() { + self.push(err); + } + } + + fn maybe_push(&mut self, err: Option) { + if let Some(err) = err { + self.push(err); + } + } + + fn maybe_push_ignore_io(&mut self, err: Option) { + if let Some(err) = err { + self.push_ignore_io(err); + } + } + + fn into_error_option(mut self) -> Option { + if self.0.is_empty() { + None + } else if self.0.len() == 1 { + Some(self.0.pop().unwrap()) + } else { + Some(Error::Partial(self.0)) + } + } +} + +/// The result of a glob match. +/// +/// The type parameter `T` typically refers to a type that provides more +/// information about a particular match. For example, it might identify +/// the specific gitignore file and the specific glob pattern that caused +/// the match. +#[derive(Clone, Debug)] +pub enum Match { + /// The path didn't match any glob. + None, + /// The highest precedent glob matched indicates the path should be + /// ignored. + Ignore(T), + /// The highest precedent glob matched indicates the path should be + /// whitelisted. + Whitelist(T), +} + +impl Match { + /// Returns true if the match result didn't match any globs. + pub fn is_none(&self) -> bool { + match *self { + Match::None => true, + Match::Ignore(_) | Match::Whitelist(_) => false, + } + } + + /// Returns true if the match result implies the path should be ignored. + pub fn is_ignore(&self) -> bool { + match *self { + Match::Ignore(_) => true, + Match::None | Match::Whitelist(_) => false, + } + } + + /// Returns true if the match result implies the path should be + /// whitelisted. + pub fn is_whitelist(&self) -> bool { + match *self { + Match::Whitelist(_) => true, + Match::None | Match::Ignore(_) => false, + } + } + + /// Inverts the match so that `Ignore` becomes `Whitelist` and + /// `Whitelist` becomes `Ignore`. A non-match remains the same. + pub fn invert(self) -> Match { + match self { + Match::None => Match::None, + Match::Ignore(t) => Match::Whitelist(t), + Match::Whitelist(t) => Match::Ignore(t), + } + } + + /// Return the value inside this match if it exists. + pub fn inner(&self) -> Option<&T> { + match *self { + Match::None => None, + Match::Ignore(ref t) => Some(t), + Match::Whitelist(ref t) => Some(t), + } + } + + /// Apply the given function to the value inside this match. + /// + /// If the match has no value, then return the match unchanged. + pub fn map U>(self, f: F) -> Match { + match self { + Match::None => Match::None, + Match::Ignore(t) => Match::Ignore(f(t)), + Match::Whitelist(t) => Match::Whitelist(f(t)), + } + } + + /// Return the match if it is not none. Otherwise, return other. + pub fn or(self, other: Self) -> Self { + if self.is_none() { + other + } else { + self + } + } +} diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/src/overrides.rs cargo-0.26.0/vendor/ignore-0.4.1/src/overrides.rs --- cargo-0.25.0/vendor/ignore-0.4.1/src/overrides.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/src/overrides.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,257 @@ +/*! +The overrides module provides a way to specify a set of override globs. +This provides functionality similar to `--include` or `--exclude` in command +line tools. +*/ + +use std::path::Path; + +use gitignore::{self, Gitignore, GitignoreBuilder}; +use {Error, Match}; + +/// Glob represents a single glob in an override matcher. +/// +/// This is used to report information about the highest precedent glob +/// that matched. +/// +/// Note that not all matches necessarily correspond to a specific glob. For +/// example, if there are one or more whitelist globs and a file path doesn't +/// match any glob in the set, then the file path is considered to be ignored. +/// +/// The lifetime `'a` refers to the lifetime of the matcher that produced +/// this glob. +#[derive(Clone, Debug)] +pub struct Glob<'a>(GlobInner<'a>); + +#[derive(Clone, Debug)] +enum GlobInner<'a> { + /// No glob matched, but the file path should still be ignored. + UnmatchedIgnore, + /// A glob matched. + Matched(&'a gitignore::Glob), +} + +impl<'a> Glob<'a> { + fn unmatched() -> Glob<'a> { + Glob(GlobInner::UnmatchedIgnore) + } +} + +/// Manages a set of overrides provided explicitly by the end user. +#[derive(Clone, Debug)] +pub struct Override(Gitignore); + +impl Override { + /// Returns an empty matcher that never matches any file path. + pub fn empty() -> Override { + Override(Gitignore::empty()) + } + + /// Returns the directory of this override set. + /// + /// All matches are done relative to this path. + pub fn path(&self) -> &Path { + self.0.path() + } + + /// Returns true if and only if this matcher is empty. + /// + /// When a matcher is empty, it will never match any file path. + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + /// Returns the total number of ignore globs. + pub fn num_ignores(&self) -> u64 { + self.0.num_whitelists() + } + + /// Returns the total number of whitelisted globs. + pub fn num_whitelists(&self) -> u64 { + self.0.num_ignores() + } + + /// Returns whether the given file path matched a pattern in this override + /// matcher. + /// + /// `is_dir` should be true if the path refers to a directory and false + /// otherwise. + /// + /// If there are no overrides, then this always returns `Match::None`. + /// + /// If there is at least one whitelist override and `is_dir` is false, then + /// this never returns `Match::None`, since non-matches are interpreted as + /// ignored. + /// + /// The given path is matched to the globs relative to the path given + /// when building the override matcher. Specifically, before matching + /// `path`, its prefix (as determined by a common suffix of the directory + /// given) is stripped. If there is no common suffix/prefix overlap, then + /// `path` is assumed to reside in the same directory as the root path for + /// this set of overrides. + pub fn matched<'a, P: AsRef>( + &'a self, + path: P, + is_dir: bool, + ) -> Match> { + if self.is_empty() { + return Match::None; + } + let mat = self.0.matched(path, is_dir).invert(); + if mat.is_none() && self.num_whitelists() > 0 && !is_dir { + return Match::Ignore(Glob::unmatched()); + } + mat.map(move |giglob| Glob(GlobInner::Matched(giglob))) + } +} + +/// Builds a matcher for a set of glob overrides. +pub struct OverrideBuilder { + builder: GitignoreBuilder, +} + +impl OverrideBuilder { + /// Create a new override builder. + /// + /// Matching is done relative to the directory path provided. + pub fn new>(path: P) -> OverrideBuilder { + OverrideBuilder { + builder: GitignoreBuilder::new(path), + } + } + + /// Builds a new override matcher from the globs added so far. + /// + /// Once a matcher is built, no new globs can be added to it. + pub fn build(&self) -> Result { + Ok(Override(self.builder.build()?)) + } + + /// Add a glob to the set of overrides. + /// + /// Globs provided here have precisely the same semantics as a single + /// line in a `gitignore` file, where the meaning of `!` is inverted: + /// namely, `!` at the beginning of a glob will ignore a file. Without `!`, + /// all matches of the glob provided are treated as whitelist matches. + pub fn add(&mut self, glob: &str) -> Result<&mut OverrideBuilder, Error> { + self.builder.add_line(None, glob)?; + Ok(self) + } + + /// Toggle whether the globs should be matched case insensitively or not. + /// + /// This is disabled by default. + pub fn case_insensitive( + &mut self, yes: bool + ) -> Result<&mut OverrideBuilder, Error> { + self.builder.case_insensitive(yes)?; + Ok(self) + } +} + +#[cfg(test)] +mod tests { + use super::{Override, OverrideBuilder}; + + const ROOT: &'static str = "/home/andrew/foo"; + + fn ov(globs: &[&str]) -> Override { + let mut builder = OverrideBuilder::new(ROOT); + for glob in globs { + builder.add(glob).unwrap(); + } + builder.build().unwrap() + } + + #[test] + fn empty() { + let ov = ov(&[]); + assert!(ov.matched("a.foo", false).is_none()); + assert!(ov.matched("a", false).is_none()); + assert!(ov.matched("", false).is_none()); + } + + #[test] + fn simple() { + let ov = ov(&["*.foo", "!*.bar"]); + assert!(ov.matched("a.foo", false).is_whitelist()); + assert!(ov.matched("a.foo", true).is_whitelist()); + assert!(ov.matched("a.rs", false).is_ignore()); + assert!(ov.matched("a.rs", true).is_none()); + assert!(ov.matched("a.bar", false).is_ignore()); + assert!(ov.matched("a.bar", true).is_ignore()); + } + + #[test] + fn only_ignores() { + let ov = ov(&["!*.bar"]); + assert!(ov.matched("a.rs", false).is_none()); + assert!(ov.matched("a.rs", true).is_none()); + assert!(ov.matched("a.bar", false).is_ignore()); + assert!(ov.matched("a.bar", true).is_ignore()); + } + + #[test] + fn precedence() { + let ov = ov(&["*.foo", "!*.bar.foo"]); + assert!(ov.matched("a.foo", false).is_whitelist()); + assert!(ov.matched("a.baz", false).is_ignore()); + assert!(ov.matched("a.bar.foo", false).is_ignore()); + } + + #[test] + fn gitignore() { + let ov = ov(&["/foo", "bar/*.rs", "baz/**"]); + assert!(ov.matched("bar/lib.rs", false).is_whitelist()); + assert!(ov.matched("bar/wat/lib.rs", false).is_ignore()); + assert!(ov.matched("wat/bar/lib.rs", false).is_ignore()); + assert!(ov.matched("foo", false).is_whitelist()); + assert!(ov.matched("wat/foo", false).is_ignore()); + assert!(ov.matched("baz", false).is_ignore()); + assert!(ov.matched("baz/a", false).is_whitelist()); + assert!(ov.matched("baz/a/b", false).is_whitelist()); + } + + #[test] + fn allow_directories() { + // This tests that directories are NOT ignored when they are unmatched. + let ov = ov(&["*.rs"]); + assert!(ov.matched("foo.rs", false).is_whitelist()); + assert!(ov.matched("foo.c", false).is_ignore()); + assert!(ov.matched("foo", false).is_ignore()); + assert!(ov.matched("foo", true).is_none()); + assert!(ov.matched("src/foo.rs", false).is_whitelist()); + assert!(ov.matched("src/foo.c", false).is_ignore()); + assert!(ov.matched("src/foo", false).is_ignore()); + assert!(ov.matched("src/foo", true).is_none()); + } + + #[test] + fn absolute_path() { + let ov = ov(&["!/bar"]); + assert!(ov.matched("./foo/bar", false).is_none()); + } + + #[test] + fn case_insensitive() { + let ov = OverrideBuilder::new(ROOT) + .case_insensitive(true).unwrap() + .add("*.html").unwrap() + .build().unwrap(); + assert!(ov.matched("foo.html", false).is_whitelist()); + assert!(ov.matched("foo.HTML", false).is_whitelist()); + assert!(ov.matched("foo.htm", false).is_ignore()); + assert!(ov.matched("foo.HTM", false).is_ignore()); + } + + #[test] + fn default_case_sensitive() { + let ov = OverrideBuilder::new(ROOT) + .add("*.html").unwrap() + .build().unwrap(); + assert!(ov.matched("foo.html", false).is_whitelist()); + assert!(ov.matched("foo.HTML", false).is_ignore()); + assert!(ov.matched("foo.htm", false).is_ignore()); + assert!(ov.matched("foo.HTM", false).is_ignore()); + } +} diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/src/pathutil.rs cargo-0.26.0/vendor/ignore-0.4.1/src/pathutil.rs --- cargo-0.25.0/vendor/ignore-0.4.1/src/pathutil.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/src/pathutil.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,108 @@ +use std::ffi::OsStr; +use std::path::Path; + +/// Returns true if and only if this file path is considered to be hidden. +#[cfg(unix)] +pub fn is_hidden>(path: P) -> bool { + use std::os::unix::ffi::OsStrExt; + + if let Some(name) = file_name(path.as_ref()) { + name.as_bytes().get(0) == Some(&b'.') + } else { + false + } +} + +/// Returns true if and only if this file path is considered to be hidden. +#[cfg(not(unix))] +pub fn is_hidden>(path: P) -> bool { + if let Some(name) = file_name(path.as_ref()) { + name.to_str().map(|s| s.starts_with(".")).unwrap_or(false) + } else { + false + } +} + +/// Strip `prefix` from the `path` and return the remainder. +/// +/// If `path` doesn't have a prefix `prefix`, then return `None`. +#[cfg(unix)] +pub fn strip_prefix<'a, P: AsRef + ?Sized>( + prefix: &'a P, + path: &'a Path, +) -> Option<&'a Path> { + use std::os::unix::ffi::OsStrExt; + + let prefix = prefix.as_ref().as_os_str().as_bytes(); + let path = path.as_os_str().as_bytes(); + if prefix.len() > path.len() || prefix != &path[0..prefix.len()] { + None + } else { + Some(&Path::new(OsStr::from_bytes(&path[prefix.len()..]))) + } +} + +/// Strip `prefix` from the `path` and return the remainder. +/// +/// If `path` doesn't have a prefix `prefix`, then return `None`. +#[cfg(not(unix))] +pub fn strip_prefix<'a, P: AsRef + ?Sized>( + prefix: &'a P, + path: &'a Path, +) -> Option<&'a Path> { + path.strip_prefix(prefix).ok() +} + +/// Returns true if this file path is just a file name. i.e., Its parent is +/// the empty string. +#[cfg(unix)] +pub fn is_file_name>(path: P) -> bool { + use std::os::unix::ffi::OsStrExt; + use memchr::memchr; + + let path = path.as_ref().as_os_str().as_bytes(); + memchr(b'/', path).is_none() +} + +/// Returns true if this file path is just a file name. i.e., Its parent is +/// the empty string. +#[cfg(not(unix))] +pub fn is_file_name>(path: P) -> bool { + path.as_ref().parent().map(|p| p.as_os_str().is_empty()).unwrap_or(false) +} + +/// The final component of the path, if it is a normal file. +/// +/// If the path terminates in ., .., or consists solely of a root of prefix, +/// file_name will return None. +#[cfg(unix)] +pub fn file_name<'a, P: AsRef + ?Sized>( + path: &'a P, +) -> Option<&'a OsStr> { + use std::os::unix::ffi::OsStrExt; + use memchr::memrchr; + + let path = path.as_ref().as_os_str().as_bytes(); + if path.is_empty() { + return None; + } else if path.len() == 1 && path[0] == b'.' { + return None; + } else if path.last() == Some(&b'.') { + return None; + } else if path.len() >= 2 && &path[path.len() - 2..] == &b".."[..] { + return None; + } + let last_slash = memrchr(b'/', path).map(|i| i + 1).unwrap_or(0); + Some(OsStr::from_bytes(&path[last_slash..])) +} + +/// The final component of the path, if it is a normal file. +/// +/// If the path terminates in ., .., or consists solely of a root of prefix, +/// file_name will return None. +#[cfg(not(unix))] +pub fn file_name<'a, P: AsRef + ?Sized>( + path: &'a P, +) -> Option<&'a OsStr> { + path.as_ref().file_name() +} diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/src/types.rs cargo-0.26.0/vendor/ignore-0.4.1/src/types.rs --- cargo-0.25.0/vendor/ignore-0.4.1/src/types.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/src/types.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,773 @@ +/*! +The types module provides a way of associating globs on file names to file +types. + +This can be used to match specific types of files. For example, among +the default file types provided, the Rust file type is defined to be `*.rs` +with name `rust`. Similarly, the C file type is defined to be `*.{c,h}` with +name `c`. + +Note that the set of default types may change over time. + +# Example + +This shows how to create and use a simple file type matcher using the default +file types defined in this crate. + +``` +use ignore::types::TypesBuilder; + +let mut builder = TypesBuilder::new(); +builder.add_defaults(); +builder.select("rust"); +let matcher = builder.build().unwrap(); + +assert!(matcher.matched("foo.rs", false).is_whitelist()); +assert!(matcher.matched("foo.c", false).is_ignore()); +``` + +# Example: negation + +This is like the previous example, but shows how negating a file type works. +That is, this will let us match file paths that *don't* correspond to a +particular file type. + +``` +use ignore::types::TypesBuilder; + +let mut builder = TypesBuilder::new(); +builder.add_defaults(); +builder.negate("c"); +let matcher = builder.build().unwrap(); + +assert!(matcher.matched("foo.rs", false).is_none()); +assert!(matcher.matched("foo.c", false).is_ignore()); +``` + +# Example: custom file type definitions + +This shows how to extend this library default file type definitions with +your own. + +``` +use ignore::types::TypesBuilder; + +let mut builder = TypesBuilder::new(); +builder.add_defaults(); +builder.add("foo", "*.foo"); +// Another way of adding a file type definition. +// This is useful when accepting input from an end user. +builder.add_def("bar:*.bar"); +// Note: we only select `foo`, not `bar`. +builder.select("foo"); +let matcher = builder.build().unwrap(); + +assert!(matcher.matched("x.foo", false).is_whitelist()); +// This is ignored because we only selected the `foo` file type. +assert!(matcher.matched("x.bar", false).is_ignore()); +``` + +We can also add file type definitions based on other definitions. + +``` +use ignore::types::TypesBuilder; + +let mut builder = TypesBuilder::new(); +builder.add_defaults(); +builder.add("foo", "*.foo"); +builder.add_def("bar:include:foo,cpp"); +builder.select("bar"); +let matcher = builder.build().unwrap(); + +assert!(matcher.matched("x.foo", false).is_whitelist()); +assert!(matcher.matched("y.cpp", false).is_whitelist()); +``` +*/ + +use std::cell::RefCell; +use std::collections::HashMap; +use std::path::Path; +use std::sync::Arc; + +use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; +use regex::Regex; +use thread_local::ThreadLocal; + +use pathutil::file_name; +use {Error, Match}; + +const DEFAULT_TYPES: &'static [(&'static str, &'static [&'static str])] = &[ + ("agda", &["*.agda", "*.lagda"]), + ("asciidoc", &["*.adoc", "*.asc", "*.asciidoc"]), + ("asm", &["*.asm", "*.s", "*.S"]), + ("avro", &["*.avdl", "*.avpr", "*.avsc"]), + ("awk", &["*.awk"]), + ("bitbake", &["*.bb", "*.bbappend", "*.bbclass", "*.conf", "*.inc"]), + ("bzip2", &["*.bz2"]), + ("c", &["*.c", "*.h", "*.H"]), + ("cabal", &["*.cabal"]), + ("cbor", &["*.cbor"]), + ("ceylon", &["*.ceylon"]), + ("clojure", &["*.clj", "*.cljc", "*.cljs", "*.cljx"]), + ("cmake", &["*.cmake", "CMakeLists.txt"]), + ("coffeescript", &["*.coffee"]), + ("creole", &["*.creole"]), + ("config", &["*.cfg", "*.conf", "*.config", "*.ini"]), + ("cpp", &[ + "*.C", "*.cc", "*.cpp", "*.cxx", + "*.h", "*.H", "*.hh", "*.hpp", "*.hxx", "*.inl", + ]), + ("crystal", &["Projectfile", "*.cr"]), + ("cs", &["*.cs"]), + ("csharp", &["*.cs"]), + ("cshtml", &["*.cshtml"]), + ("css", &["*.css", "*.scss"]), + ("csv", &["*.csv"]), + ("cython", &["*.pyx"]), + ("dart", &["*.dart"]), + ("d", &["*.d"]), + ("docker", &["*Dockerfile*"]), + ("elisp", &["*.el"]), + ("elixir", &["*.ex", "*.eex", "*.exs"]), + ("elm", &["*.elm"]), + ("erlang", &["*.erl", "*.hrl"]), + ("fish", &["*.fish"]), + ("fortran", &[ + "*.f", "*.F", "*.f77", "*.F77", "*.pfo", + "*.f90", "*.F90", "*.f95", "*.F95", + ]), + ("fsharp", &["*.fs", "*.fsx", "*.fsi"]), + ("gn", &["*.gn", "*.gni"]), + ("go", &["*.go"]), + ("gzip", &["*.gz"]), + ("groovy", &["*.groovy", "*.gradle"]), + ("h", &["*.h", "*.hpp"]), + ("hbs", &["*.hbs"]), + ("haskell", &["*.hs", "*.lhs"]), + ("html", &["*.htm", "*.html", "*.ejs"]), + ("java", &["*.java"]), + ("jinja", &["*.j2", "*.jinja", "*.jinja2"]), + ("js", &[ + "*.js", "*.jsx", "*.vue", + ]), + ("json", &["*.json", "composer.lock"]), + ("jsonl", &["*.jsonl"]), + ("julia", &["*.jl"]), + ("jupyter", &["*.ipynb", "*.jpynb"]), + ("jl", &["*.jl"]), + ("kotlin", &["*.kt", "*.kts"]), + ("less", &["*.less"]), + ("license", &[ + // General + "COPYING", "COPYING[.-]*", + "COPYRIGHT", "COPYRIGHT[.-]*", + "EULA", "EULA[.-]*", + "licen[cs]e", "licen[cs]e.*", + "LICEN[CS]E", "LICEN[CS]E[.-]*", "*[.-]LICEN[CS]E*", + "NOTICE", "NOTICE[.-]*", + "PATENTS", "PATENTS[.-]*", + "UNLICEN[CS]E", "UNLICEN[CS]E[.-]*", + // GPL (gpl.txt, etc.) + "agpl[.-]*", + "gpl[.-]*", + "lgpl[.-]*", + // Other license-specific (APACHE-2.0.txt, etc.) + "AGPL-*[0-9]*", + "APACHE-*[0-9]*", + "BSD-*[0-9]*", + "CC-BY-*", + "GFDL-*[0-9]*", + "GNU-*[0-9]*", + "GPL-*[0-9]*", + "LGPL-*[0-9]*", + "MIT-*[0-9]*", + "MPL-*[0-9]*", + "OFL-*[0-9]*", + ]), + ("lisp", &["*.el", "*.jl", "*.lisp", "*.lsp", "*.sc", "*.scm"]), + ("log", &["*.log"]), + ("lua", &["*.lua"]), + ("lzma", &["*.lzma"]), + ("m4", &["*.ac", "*.m4"]), + ("make", &[ + "gnumakefile", "Gnumakefile", "GNUmakefile", + "makefile", "Makefile", + "*.mk", "*.mak" + ]), + ("markdown", &["*.markdown", "*.md", "*.mdown", "*.mkdn"]), + ("md", &["*.markdown", "*.md", "*.mdown", "*.mkdn"]), + ("man", &["*.[0-9lnpx]", "*.[0-9][cEFMmpSx]"]), + ("matlab", &["*.m"]), + ("mk", &["mkfile"]), + ("ml", &["*.ml"]), + ("msbuild", &[ + "*.csproj", "*.fsproj", "*.vcxproj", "*.proj", "*.props", "*.targets" + ]), + ("nim", &["*.nim"]), + ("nix", &["*.nix"]), + ("objc", &["*.h", "*.m"]), + ("objcpp", &["*.h", "*.mm"]), + ("ocaml", &["*.ml", "*.mli", "*.mll", "*.mly"]), + ("org", &["*.org"]), + ("perl", &["*.perl", "*.pl", "*.PL", "*.plh", "*.plx", "*.pm", "*.t"]), + ("pdf", &["*.pdf"]), + ("php", &["*.php", "*.php3", "*.php4", "*.php5", "*.phtml"]), + ("pod", &["*.pod"]), + ("protobuf", &["*.proto"]), + ("ps", &["*.cdxml", "*.ps1", "*.ps1xml", "*.psd1", "*.psm1"]), + ("purs", &["*.purs"]), + ("py", &["*.py"]), + ("qmake", &["*.pro", "*.pri", "*.prf"]), + ("readme", &["README*", "*README"]), + ("r", &["*.R", "*.r", "*.Rmd", "*.Rnw"]), + ("rdoc", &["*.rdoc"]), + ("rst", &["*.rst"]), + ("ruby", &["Gemfile", "*.gemspec", ".irbrc", "Rakefile", "*.rb"]), + ("rust", &["*.rs"]), + ("sass", &["*.sass", "*.scss"]), + ("scala", &["*.scala"]), + ("sh", &[ + // Portable/misc. init files + ".login", ".logout", ".profile", "profile", + // bash-specific init files + ".bash_login", "bash_login", + ".bash_logout", "bash_logout", + ".bash_profile", "bash_profile", + ".bashrc", "bashrc", "*.bashrc", + // csh-specific init files + ".cshrc", "*.cshrc", + // ksh-specific init files + ".kshrc", "*.kshrc", + // tcsh-specific init files + ".tcshrc", + // zsh-specific init files + ".zshenv", "zshenv", + ".zlogin", "zlogin", + ".zlogout", "zlogout", + ".zprofile", "zprofile", + ".zshrc", "zshrc", + // Extensions + "*.bash", "*.csh", "*.ksh", "*.sh", "*.tcsh", "*.zsh", + ]), + ("smarty", &["*.tpl"]), + ("sml", &["*.sml", "*.sig"]), + ("soy", &["*.soy"]), + ("spark", &["*.spark"]), + ("sql", &["*.sql", "*.psql"]), + ("stylus", &["*.styl"]), + ("sv", &["*.v", "*.vg", "*.sv", "*.svh", "*.h"]), + ("svg", &["*.svg"]), + ("swift", &["*.swift"]), + ("swig", &["*.def", "*.i"]), + ("systemd", &[ + "*.automount", "*.conf", "*.device", "*.link", "*.mount", "*.path", + "*.scope", "*.service", "*.slice", "*.socket", "*.swap", "*.target", + "*.timer", + ]), + ("taskpaper", &["*.taskpaper"]), + ("tcl", &["*.tcl"]), + ("tex", &["*.tex", "*.ltx", "*.cls", "*.sty", "*.bib"]), + ("textile", &["*.textile"]), + ("tf", &["*.tf"]), + ("ts", &["*.ts", "*.tsx"]), + ("txt", &["*.txt"]), + ("toml", &["*.toml", "Cargo.lock"]), + ("twig", &["*.twig"]), + ("vala", &["*.vala"]), + ("vb", &["*.vb"]), + ("vhdl", &["*.vhd", "*.vhdl"]), + ("vim", &["*.vim"]), + ("vimscript", &["*.vim"]), + ("wiki", &["*.mediawiki", "*.wiki"]), + ("webidl", &["*.idl", "*.webidl", "*.widl"]), + ("xml", &["*.xml", "*.xml.dist"]), + ("xz", &["*.xz"]), + ("yacc", &["*.y"]), + ("yaml", &["*.yaml", "*.yml"]), + ("zsh", &[ + ".zshenv", "zshenv", + ".zlogin", "zlogin", + ".zlogout", "zlogout", + ".zprofile", "zprofile", + ".zshrc", "zshrc", + "*.zsh", + ]), +]; + +/// Glob represents a single glob in a set of file type definitions. +/// +/// There may be more than one glob for a particular file type. +/// +/// This is used to report information about the highest precedent glob +/// that matched. +/// +/// Note that not all matches necessarily correspond to a specific glob. +/// For example, if there are one or more selections and a file path doesn't +/// match any of those selections, then the file path is considered to be +/// ignored. +/// +/// The lifetime `'a` refers to the lifetime of the underlying file type +/// definition, which corresponds to the lifetime of the file type matcher. +#[derive(Clone, Debug)] +pub struct Glob<'a>(GlobInner<'a>); + +#[derive(Clone, Debug)] +enum GlobInner<'a> { + /// No glob matched, but the file path should still be ignored. + UnmatchedIgnore, + /// A glob matched. + Matched { + /// The file type definition which provided the glob. + def: &'a FileTypeDef, + /// The index of the glob that matched inside the file type definition. + which: usize, + /// Whether the selection was negated or not. + negated: bool, + } +} + +impl<'a> Glob<'a> { + fn unmatched() -> Glob<'a> { + Glob(GlobInner::UnmatchedIgnore) + } +} + +/// A single file type definition. +/// +/// File type definitions can be retrieved in aggregate from a file type +/// matcher. File type definitions are also reported when its responsible +/// for a match. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct FileTypeDef { + name: String, + globs: Vec, +} + +impl FileTypeDef { + /// Return the name of this file type. + pub fn name(&self) -> &str { + &self.name + } + + /// Return the globs used to recognize this file type. + pub fn globs(&self) -> &[String] { + &self.globs + } +} + +/// Types is a file type matcher. +#[derive(Clone, Debug)] +pub struct Types { + /// All of the file type definitions, sorted lexicographically by name. + defs: Vec, + /// All of the selections made by the user. + selections: Vec>, + /// Whether there is at least one Selection::Select in our selections. + /// When this is true, a Match::None is converted to Match::Ignore. + has_selected: bool, + /// A mapping from glob index in the set to two indices. The first is an + /// index into `selections` and the second is an index into the + /// corresponding file type definition's list of globs. + glob_to_selection: Vec<(usize, usize)>, + /// The set of all glob selections, used for actual matching. + set: GlobSet, + /// Temporary storage for globs that match. + matches: Arc>>>, +} + +/// Indicates the type of a selection for a particular file type. +#[derive(Clone, Debug)] +enum Selection { + Select(String, T), + Negate(String, T), +} + +impl Selection { + fn is_negated(&self) -> bool { + match *self { + Selection::Select(..) => false, + Selection::Negate(..) => true, + } + } + + fn name(&self) -> &str { + match *self { + Selection::Select(ref name, _) => name, + Selection::Negate(ref name, _) => name, + } + } + + fn map U>(self, f: F) -> Selection { + match self { + Selection::Select(name, inner) => { + Selection::Select(name, f(inner)) + } + Selection::Negate(name, inner) => { + Selection::Negate(name, f(inner)) + } + } + } + + fn inner(&self) -> &T { + match *self { + Selection::Select(_, ref inner) => inner, + Selection::Negate(_, ref inner) => inner, + } + } +} + +impl Types { + /// Creates a new file type matcher that never matches any path and + /// contains no file type definitions. + pub fn empty() -> Types { + Types { + defs: vec![], + selections: vec![], + has_selected: false, + glob_to_selection: vec![], + set: GlobSetBuilder::new().build().unwrap(), + matches: Arc::new(ThreadLocal::default()), + } + } + + /// Returns true if and only if this matcher has zero selections. + pub fn is_empty(&self) -> bool { + self.selections.is_empty() + } + + /// Returns the number of selections used in this matcher. + pub fn len(&self) -> usize { + self.selections.len() + } + + /// Return the set of current file type definitions. + /// + /// Definitions and globs are sorted. + pub fn definitions(&self) -> &[FileTypeDef] { + &self.defs + } + + /// Returns a match for the given path against this file type matcher. + /// + /// The path is considered whitelisted if it matches a selected file type. + /// The path is considered ignored if it matches a negated file type. + /// If at least one file type is selected and `path` doesn't match, then + /// the path is also considered ignored. + pub fn matched<'a, P: AsRef>( + &'a self, + path: P, + is_dir: bool, + ) -> Match> { + // File types don't apply to directories, and we can't do anything + // if our glob set is empty. + if is_dir || self.set.is_empty() { + return Match::None; + } + // We only want to match against the file name, so extract it. + // If one doesn't exist, then we can't match it. + let name = match file_name(path.as_ref()) { + Some(name) => name, + None if self.has_selected => { + return Match::Ignore(Glob::unmatched()); + } + None => { + return Match::None; + } + }; + let mut matches = self.matches.get_default().borrow_mut(); + self.set.matches_into(name, &mut *matches); + // The highest precedent match is the last one. + if let Some(&i) = matches.last() { + let (isel, iglob) = self.glob_to_selection[i]; + let sel = &self.selections[isel]; + let glob = Glob(GlobInner::Matched { + def: sel.inner(), + which: iglob, + negated: sel.is_negated(), + }); + return if sel.is_negated() { + Match::Ignore(glob) + } else { + Match::Whitelist(glob) + }; + } + if self.has_selected { + Match::Ignore(Glob::unmatched()) + } else { + Match::None + } + } +} + +/// TypesBuilder builds a type matcher from a set of file type definitions and +/// a set of file type selections. +pub struct TypesBuilder { + types: HashMap, + selections: Vec>, +} + +impl TypesBuilder { + /// Create a new builder for a file type matcher. + /// + /// The builder contains *no* type definitions to start with. A set + /// of default type definitions can be added with `add_defaults`, and + /// additional type definitions can be added with `select` and `negate`. + pub fn new() -> TypesBuilder { + TypesBuilder { + types: HashMap::new(), + selections: vec![], + } + } + + /// Build the current set of file type definitions *and* selections into + /// a file type matcher. + pub fn build(&self) -> Result { + let defs = self.definitions(); + let has_selected = self.selections.iter().any(|s| !s.is_negated()); + + let mut selections = vec![]; + let mut glob_to_selection = vec![]; + let mut build_set = GlobSetBuilder::new(); + for (isel, selection) in self.selections.iter().enumerate() { + let def = match self.types.get(selection.name()) { + Some(def) => def.clone(), + None => { + let name = selection.name().to_string(); + return Err(Error::UnrecognizedFileType(name)); + } + }; + for (iglob, glob) in def.globs.iter().enumerate() { + build_set.add( + GlobBuilder::new(glob) + .literal_separator(true) + .build() + .map_err(|err| { + Error::Glob { + glob: Some(glob.to_string()), + err: err.kind().to_string(), + } + })?); + glob_to_selection.push((isel, iglob)); + } + selections.push(selection.clone().map(move |_| def)); + } + let set = build_set.build().map_err(|err| { + Error::Glob { glob: None, err: err.to_string() } + })?; + Ok(Types { + defs: defs, + selections: selections, + has_selected: has_selected, + glob_to_selection: glob_to_selection, + set: set, + matches: Arc::new(ThreadLocal::default()), + }) + } + + /// Return the set of current file type definitions. + /// + /// Definitions and globs are sorted. + pub fn definitions(&self) -> Vec { + let mut defs = vec![]; + for def in self.types.values() { + let mut def = def.clone(); + def.globs.sort(); + defs.push(def); + } + defs.sort_by(|def1, def2| def1.name().cmp(def2.name())); + defs + } + + /// Select the file type given by `name`. + /// + /// If `name` is `all`, then all file types currently defined are selected. + pub fn select(&mut self, name: &str) -> &mut TypesBuilder { + if name == "all" { + for name in self.types.keys() { + self.selections.push(Selection::Select(name.to_string(), ())); + } + } else { + self.selections.push(Selection::Select(name.to_string(), ())); + } + self + } + + /// Ignore the file type given by `name`. + /// + /// If `name` is `all`, then all file types currently defined are negated. + pub fn negate(&mut self, name: &str) -> &mut TypesBuilder { + if name == "all" { + for name in self.types.keys() { + self.selections.push(Selection::Negate(name.to_string(), ())); + } + } else { + self.selections.push(Selection::Negate(name.to_string(), ())); + } + self + } + + /// Clear any file type definitions for the type name given. + pub fn clear(&mut self, name: &str) -> &mut TypesBuilder { + self.types.remove(name); + self + } + + /// Add a new file type definition. `name` can be arbitrary and `pat` + /// should be a glob recognizing file paths belonging to the `name` type. + /// + /// If `name` is `all` or otherwise contains any character that is not a + /// Unicode letter or number, then an error is returned. + pub fn add(&mut self, name: &str, glob: &str) -> Result<(), Error> { + lazy_static! { + static ref RE: Regex = Regex::new(r"^[\pL\pN]+$").unwrap(); + }; + if name == "all" || !RE.is_match(name) { + return Err(Error::InvalidDefinition); + } + let (key, glob) = (name.to_string(), glob.to_string()); + self.types.entry(key).or_insert_with(|| { + FileTypeDef { name: name.to_string(), globs: vec![] } + }).globs.push(glob); + Ok(()) + } + + /// Add a new file type definition specified in string form. There are two + /// valid formats: + /// 1. `{name}:{glob}`. This defines a 'root' definition that associates the + /// given name with the given glob. + /// 2. `{name}:include:{comma-separated list of already defined names}. + /// This defines an 'include' definition that associates the given name + /// with the definitions of the given existing types. + /// Names may not include any characters that are not + /// Unicode letters or numbers. + pub fn add_def(&mut self, def: &str) -> Result<(), Error> { + let parts: Vec<&str> = def.split(':').collect(); + match parts.len() { + 2 => { + let name = parts[0]; + let glob = parts[1]; + if name.is_empty() || glob.is_empty() { + return Err(Error::InvalidDefinition); + } + self.add(name, glob) + } + 3 => { + let name = parts[0]; + let types_string = parts[2]; + if name.is_empty() || parts[1] != "include" || types_string.is_empty() { + return Err(Error::InvalidDefinition); + } + let types = types_string.split(','); + // Check ahead of time to ensure that all types specified are + // present and fail fast if not. + if types.clone().any(|t| !self.types.contains_key(t)) { + return Err(Error::InvalidDefinition); + } + for type_name in types { + let globs = self.types.get(type_name).unwrap().globs.clone(); + for glob in globs { + self.add(name, &glob)?; + } + } + Ok(()) + } + _ => Err(Error::InvalidDefinition) + } + } + + /// Add a set of default file type definitions. + pub fn add_defaults(&mut self) -> &mut TypesBuilder { + static MSG: &'static str = "adding a default type should never fail"; + for &(name, exts) in DEFAULT_TYPES { + for ext in exts { + self.add(name, ext).expect(MSG); + } + } + self + } +} + +#[cfg(test)] +mod tests { + use super::TypesBuilder; + + macro_rules! matched { + ($name:ident, $types:expr, $sel:expr, $selnot:expr, + $path:expr) => { + matched!($name, $types, $sel, $selnot, $path, true); + }; + (not, $name:ident, $types:expr, $sel:expr, $selnot:expr, + $path:expr) => { + matched!($name, $types, $sel, $selnot, $path, false); + }; + ($name:ident, $types:expr, $sel:expr, $selnot:expr, + $path:expr, $matched:expr) => { + #[test] + fn $name() { + let mut btypes = TypesBuilder::new(); + for tydef in $types { + btypes.add_def(tydef).unwrap(); + } + for sel in $sel { + btypes.select(sel); + } + for selnot in $selnot { + btypes.negate(selnot); + } + let types = btypes.build().unwrap(); + let mat = types.matched($path, false); + assert_eq!($matched, !mat.is_ignore()); + } + }; + } + + fn types() -> Vec<&'static str> { + vec![ + "html:*.html", + "html:*.htm", + "rust:*.rs", + "js:*.js", + "foo:*.{rs,foo}", + "combo:include:html,rust" + ] + } + + matched!(match1, types(), vec!["rust"], vec![], "lib.rs"); + matched!(match2, types(), vec!["html"], vec![], "index.html"); + matched!(match3, types(), vec!["html"], vec![], "index.htm"); + matched!(match4, types(), vec!["html", "rust"], vec![], "main.rs"); + matched!(match5, types(), vec![], vec![], "index.html"); + matched!(match6, types(), vec![], vec!["rust"], "index.html"); + matched!(match7, types(), vec!["foo"], vec!["rust"], "main.foo"); + matched!(match8, types(), vec!["combo"], vec![], "index.html"); + matched!(match9, types(), vec!["combo"], vec![], "lib.rs"); + + matched!(not, matchnot1, types(), vec!["rust"], vec![], "index.html"); + matched!(not, matchnot2, types(), vec![], vec!["rust"], "main.rs"); + matched!(not, matchnot3, types(), vec!["foo"], vec!["rust"], "main.rs"); + matched!(not, matchnot4, types(), vec!["rust"], vec!["foo"], "main.rs"); + matched!(not, matchnot5, types(), vec!["rust"], vec!["foo"], "main.foo"); + matched!(not, matchnot6, types(), vec!["combo"], vec![], "leftpad.js"); + + #[test] + fn test_invalid_defs() { + let mut btypes = TypesBuilder::new(); + for tydef in types() { + btypes.add_def(tydef).unwrap(); + } + // Preserve the original definitions for later comparison. + let original_defs = btypes.definitions(); + let bad_defs = vec![ + // Reference to type that does not exist + "combo:include:html,python", + // Bad format + "combo:foobar:html,rust", + "" + ]; + for def in bad_defs { + assert!(btypes.add_def(def).is_err()); + // Ensure that nothing changed, even if some of the includes were valid. + assert_eq!(btypes.definitions(), original_defs); + } + } +} diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/src/walk.rs cargo-0.26.0/vendor/ignore-0.4.1/src/walk.rs --- cargo-0.25.0/vendor/ignore-0.4.1/src/walk.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/src/walk.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1765 @@ +use std::cmp; +use std::ffi::OsStr; +use std::fmt; +use std::fs::{self, FileType, Metadata}; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::thread; +use std::time::Duration; +use std::vec; + +use crossbeam::sync::MsQueue; +use same_file::Handle; +use walkdir::{self, WalkDir}; + +use dir::{Ignore, IgnoreBuilder}; +use gitignore::GitignoreBuilder; +use overrides::Override; +use types::Types; +use {Error, PartialErrorBuilder}; + +/// A directory entry with a possible error attached. +/// +/// The error typically refers to a problem parsing ignore files in a +/// particular directory. +#[derive(Debug)] +pub struct DirEntry { + dent: DirEntryInner, + err: Option, +} + +impl DirEntry { + /// The full path that this entry represents. + pub fn path(&self) -> &Path { + self.dent.path() + } + + /// Whether this entry corresponds to a symbolic link or not. + pub fn path_is_symlink(&self) -> bool { + self.dent.path_is_symlink() + } + + /// Returns true if and only if this entry corresponds to stdin. + /// + /// i.e., The entry has depth 0 and its file name is `-`. + pub fn is_stdin(&self) -> bool { + self.dent.is_stdin() + } + + /// Return the metadata for the file that this entry points to. + pub fn metadata(&self) -> Result { + self.dent.metadata() + } + + /// Return the file type for the file that this entry points to. + /// + /// This entry doesn't have a file type if it corresponds to stdin. + pub fn file_type(&self) -> Option { + self.dent.file_type() + } + + /// Return the file name of this entry. + /// + /// If this entry has no file name (e.g., `/`), then the full path is + /// returned. + pub fn file_name(&self) -> &OsStr { + self.dent.file_name() + } + + /// Returns the depth at which this entry was created relative to the root. + pub fn depth(&self) -> usize { + self.dent.depth() + } + + /// Returns the underlying inode number if one exists. + /// + /// If this entry doesn't have an inode number, then `None` is returned. + #[cfg(unix)] + pub fn ino(&self) -> Option { + self.dent.ino() + } + + /// Returns an error, if one exists, associated with processing this entry. + /// + /// An example of an error is one that occurred while parsing an ignore + /// file. + pub fn error(&self) -> Option<&Error> { + self.err.as_ref() + } + + /// Returns true if and only if this entry points to a directory. + fn is_dir(&self) -> bool { + self.dent.is_dir() + } + + fn new_stdin() -> DirEntry { + DirEntry { + dent: DirEntryInner::Stdin, + err: None, + } + } + + fn new_walkdir(dent: walkdir::DirEntry, err: Option) -> DirEntry { + DirEntry { + dent: DirEntryInner::Walkdir(dent), + err: err, + } + } + + fn new_raw(dent: DirEntryRaw, err: Option) -> DirEntry { + DirEntry { + dent: DirEntryInner::Raw(dent), + err: err, + } + } +} + +/// DirEntryInner is the implementation of DirEntry. +/// +/// It specifically represents three distinct sources of directory entries: +/// +/// 1. From the walkdir crate. +/// 2. Special entries that represent things like stdin. +/// 3. From a path. +/// +/// Specifically, (3) has to essentially re-create the DirEntry implementation +/// from WalkDir. +#[derive(Debug)] +enum DirEntryInner { + Stdin, + Walkdir(walkdir::DirEntry), + Raw(DirEntryRaw), +} + +impl DirEntryInner { + fn path(&self) -> &Path { + use self::DirEntryInner::*; + match *self { + Stdin => Path::new(""), + Walkdir(ref x) => x.path(), + Raw(ref x) => x.path(), + } + } + + fn path_is_symlink(&self) -> bool { + use self::DirEntryInner::*; + match *self { + Stdin => false, + Walkdir(ref x) => x.path_is_symlink(), + Raw(ref x) => x.path_is_symlink(), + } + } + + fn is_stdin(&self) -> bool { + match *self { + DirEntryInner::Stdin => true, + _ => false, + } + } + + fn metadata(&self) -> Result { + use self::DirEntryInner::*; + match *self { + Stdin => { + let err = Error::Io(io::Error::new( + io::ErrorKind::Other, " has no metadata")); + Err(err.with_path("")) + } + Walkdir(ref x) => { + x.metadata().map_err(|err| { + Error::Io(io::Error::from(err)).with_path(x.path()) + }) + } + Raw(ref x) => x.metadata(), + } + } + + fn file_type(&self) -> Option { + use self::DirEntryInner::*; + match *self { + Stdin => None, + Walkdir(ref x) => Some(x.file_type()), + Raw(ref x) => Some(x.file_type()), + } + } + + fn file_name(&self) -> &OsStr { + use self::DirEntryInner::*; + match *self { + Stdin => OsStr::new(""), + Walkdir(ref x) => x.file_name(), + Raw(ref x) => x.file_name(), + } + } + + fn depth(&self) -> usize { + use self::DirEntryInner::*; + match *self { + Stdin => 0, + Walkdir(ref x) => x.depth(), + Raw(ref x) => x.depth(), + } + } + + #[cfg(unix)] + fn ino(&self) -> Option { + use walkdir::DirEntryExt; + use self::DirEntryInner::*; + match *self { + Stdin => None, + Walkdir(ref x) => Some(x.ino()), + Raw(ref x) => Some(x.ino()), + } + } + + /// Returns true if and only if this entry points to a directory. + /// + /// This works around a bug in Rust's standard library: + /// https://github.com/rust-lang/rust/issues/46484 + #[cfg(windows)] + fn is_dir(&self) -> bool { + self.metadata().map(|md| metadata_is_dir(&md)).unwrap_or(false) + } + + /// Returns true if and only if this entry points to a directory. + /// + /// This works around a bug in Rust's standard library: + /// https://github.com/rust-lang/rust/issues/46484 + #[cfg(not(windows))] + fn is_dir(&self) -> bool { + self.file_type().map(|ft| ft.is_dir()).unwrap_or(false) + } +} + +/// DirEntryRaw is essentially copied from the walkdir crate so that we can +/// build `DirEntry`s from whole cloth in the parallel iterator. +struct DirEntryRaw { + /// The path as reported by the `fs::ReadDir` iterator (even if it's a + /// symbolic link). + path: PathBuf, + /// The file type. Necessary for recursive iteration, so store it. + ty: FileType, + /// Is set when this entry was created from a symbolic link and the user + /// expects the iterator to follow symbolic links. + follow_link: bool, + /// The depth at which this entry was generated relative to the root. + depth: usize, + /// The underlying inode number (Unix only). + #[cfg(unix)] + ino: u64, + /// The underlying metadata (Windows only). We store this on Windows + /// because this comes for free while reading a directory. + /// + /// We use this to determine whether an entry is a directory or not, which + /// works around a bug in Rust's standard library: + /// https://github.com/rust-lang/rust/issues/46484 + #[cfg(windows)] + metadata: fs::Metadata, +} + +impl fmt::Debug for DirEntryRaw { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Leaving out FileType because it doesn't have a debug impl + // in Rust 1.9. We could add it if we really wanted to by manually + // querying each possibly file type. Meh. ---AG + f.debug_struct("DirEntryRaw") + .field("path", &self.path) + .field("follow_link", &self.follow_link) + .field("depth", &self.depth) + .finish() + } +} + +impl DirEntryRaw { + fn path(&self) -> &Path { + &self.path + } + + fn path_is_symlink(&self) -> bool { + self.ty.is_symlink() || self.follow_link + } + + fn metadata(&self) -> Result { + self.metadata_internal() + } + + #[cfg(windows)] + fn metadata_internal(&self) -> Result { + if self.follow_link { + fs::metadata(&self.path) + } else { + Ok(self.metadata.clone()) + }.map_err(|err| Error::Io(io::Error::from(err)).with_path(&self.path)) + } + + #[cfg(not(windows))] + fn metadata_internal(&self) -> Result { + if self.follow_link { + fs::metadata(&self.path) + } else { + fs::symlink_metadata(&self.path) + }.map_err(|err| Error::Io(io::Error::from(err)).with_path(&self.path)) + } + + fn file_type(&self) -> FileType { + self.ty + } + + fn file_name(&self) -> &OsStr { + self.path.file_name().unwrap_or_else(|| self.path.as_os_str()) + } + + fn depth(&self) -> usize { + self.depth + } + + #[cfg(unix)] + fn ino(&self) -> u64 { + self.ino + } + + fn from_entry( + depth: usize, + ent: &fs::DirEntry, + ) -> Result { + let ty = ent.file_type().map_err(|err| { + let err = Error::Io(io::Error::from(err)).with_path(ent.path()); + Error::WithDepth { + depth: depth, + err: Box::new(err), + } + })?; + DirEntryRaw::from_entry_os(depth, ent, ty) + } + + #[cfg(windows)] + fn from_entry_os( + depth: usize, + ent: &fs::DirEntry, + ty: fs::FileType, + ) -> Result { + let md = ent.metadata().map_err(|err| { + let err = Error::Io(io::Error::from(err)).with_path(ent.path()); + Error::WithDepth { + depth: depth, + err: Box::new(err), + } + })?; + Ok(DirEntryRaw { + path: ent.path(), + ty: ty, + follow_link: false, + depth: depth, + metadata: md, + }) + } + + #[cfg(unix)] + fn from_entry_os( + depth: usize, + ent: &fs::DirEntry, + ty: fs::FileType, + ) -> Result { + use std::os::unix::fs::DirEntryExt; + + Ok(DirEntryRaw { + path: ent.path(), + ty: ty, + follow_link: false, + depth: depth, + ino: ent.ino(), + }) + } + + #[cfg(not(unix))] + fn from_link(depth: usize, pb: PathBuf) -> Result { + let md = fs::metadata(&pb).map_err(|err| { + Error::Io(err).with_path(&pb) + })?; + Ok(DirEntryRaw { + path: pb, + ty: md.file_type(), + follow_link: true, + depth: depth, + metadata: md, + }) + } + + #[cfg(unix)] + fn from_link(depth: usize, pb: PathBuf) -> Result { + use std::os::unix::fs::MetadataExt; + + let md = fs::metadata(&pb).map_err(|err| { + Error::Io(err).with_path(&pb) + })?; + Ok(DirEntryRaw { + path: pb, + ty: md.file_type(), + follow_link: true, + depth: depth, + ino: md.ino(), + }) + } +} + +/// WalkBuilder builds a recursive directory iterator. +/// +/// The builder supports a large number of configurable options. This includes +/// specific glob overrides, file type matching, toggling whether hidden +/// files are ignored or not, and of course, support for respecting gitignore +/// files. +/// +/// By default, all ignore files found are respected. This includes `.ignore`, +/// `.gitignore`, `.git/info/exclude` and even your global gitignore +/// globs, usually found in `$XDG_CONFIG_HOME/git/ignore`. +/// +/// Some standard recursive directory options are also supported, such as +/// limiting the recursive depth or whether to follow symbolic links (disabled +/// by default). +/// +/// # Ignore rules +/// +/// There are many rules that influence whether a particular file or directory +/// is skipped by this iterator. Those rules are documented here. Note that +/// the rules assume a default configuration. +/// +/// * First, glob overrides are checked. If a path matches a glob override, +/// then matching stops. The path is then only skipped if the glob that matched +/// the path is an ignore glob. (An override glob is a whitelist glob unless it +/// starts with a `!`, in which case it is an ignore glob.) +/// * Second, ignore files are checked. Ignore files currently only come from +/// git ignore files (`.gitignore`, `.git/info/exclude` and the configured +/// global gitignore file), plain `.ignore` files, which have the same format +/// as gitignore files, or explicitly added ignore files. The precedence order +/// is: `.ignore`, `.gitignore`, `.git/info/exclude`, global gitignore and +/// finally explicitly added ignore files. Note that precedence between +/// different types of ignore files is not impacted by the directory hierarchy; +/// any `.ignore` file overrides all `.gitignore` files. Within each precedence +/// level, more nested ignore files have a higher precedence than less nested +/// ignore files. +/// * Third, if the previous step yields an ignore match, then all matching +/// is stopped and the path is skipped. If it yields a whitelist match, then +/// matching continues. A whitelist match can be overridden by a later matcher. +/// * Fourth, unless the path is a directory, the file type matcher is run on +/// the path. As above, if it yields an ignore match, then all matching is +/// stopped and the path is skipped. If it yields a whitelist match, then +/// matching continues. +/// * Fifth, if the path hasn't been whitelisted and it is hidden, then the +/// path is skipped. +/// * Sixth, unless the path is a directory, the size of the file is compared +/// against the max filesize limit. If it exceeds the limit, it is skipped. +/// * Seventh, if the path has made it this far then it is yielded in the +/// iterator. +#[derive(Clone)] +pub struct WalkBuilder { + paths: Vec, + ig_builder: IgnoreBuilder, + parents: bool, + max_depth: Option, + max_filesize: Option, + follow_links: bool, + sorter: Option cmp::Ordering + Send + Sync + 'static + >>, + threads: usize, +} + +impl fmt::Debug for WalkBuilder { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("WalkBuilder") + .field("paths", &self.paths) + .field("ig_builder", &self.ig_builder) + .field("parents", &self.parents) + .field("max_depth", &self.max_depth) + .field("max_filesize", &self.max_filesize) + .field("follow_links", &self.follow_links) + .field("threads", &self.threads) + .finish() + } +} + +impl WalkBuilder { + /// Create a new builder for a recursive directory iterator for the + /// directory given. + /// + /// Note that if you want to traverse multiple different directories, it + /// is better to call `add` on this builder than to create multiple + /// `Walk` values. + pub fn new>(path: P) -> WalkBuilder { + WalkBuilder { + paths: vec![path.as_ref().to_path_buf()], + ig_builder: IgnoreBuilder::new(), + parents: true, + max_depth: None, + max_filesize: None, + follow_links: false, + sorter: None, + threads: 0, + } + } + + /// Build a new `Walk` iterator. + pub fn build(&self) -> Walk { + let follow_links = self.follow_links; + let max_depth = self.max_depth; + let cmp = self.sorter.clone(); + let its = self.paths.iter().map(move |p| { + if p == Path::new("-") { + (p.to_path_buf(), None) + } else { + let mut wd = WalkDir::new(p); + wd = wd.follow_links(follow_links || path_is_file(p)); + if let Some(max_depth) = max_depth { + wd = wd.max_depth(max_depth); + } + if let Some(ref cmp) = cmp { + let cmp = cmp.clone(); + wd = wd.sort_by(move |a, b| { + cmp(a.file_name(), b.file_name()) + }); + } + (p.to_path_buf(), Some(WalkEventIter::from(wd))) + } + }).collect::>().into_iter(); + let ig_root = self.ig_builder.build(); + Walk { + its: its, + it: None, + ig_root: ig_root.clone(), + ig: ig_root.clone(), + max_filesize: self.max_filesize, + parents: self.parents, + } + } + + /// Build a new `WalkParallel` iterator. + /// + /// Note that this *doesn't* return something that implements `Iterator`. + /// Instead, the returned value must be run with a closure. e.g., + /// `builder.build_parallel().run(|| |path| println!("{:?}", path))`. + pub fn build_parallel(&self) -> WalkParallel { + WalkParallel { + paths: self.paths.clone().into_iter(), + ig_root: self.ig_builder.build(), + max_depth: self.max_depth, + max_filesize: self.max_filesize, + follow_links: self.follow_links, + parents: self.parents, + threads: self.threads, + } + } + + /// Add a file path to the iterator. + /// + /// Each additional file path added is traversed recursively. This should + /// be preferred over building multiple `Walk` iterators since this + /// enables reusing resources across iteration. + pub fn add>(&mut self, path: P) -> &mut WalkBuilder { + self.paths.push(path.as_ref().to_path_buf()); + self + } + + /// The maximum depth to recurse. + /// + /// The default, `None`, imposes no depth restriction. + pub fn max_depth(&mut self, depth: Option) -> &mut WalkBuilder { + self.max_depth = depth; + self + } + + /// Whether to follow symbolic links or not. + pub fn follow_links(&mut self, yes: bool) -> &mut WalkBuilder { + self.follow_links = yes; + self + } + + /// Whether to ignore files above the specified limit. + pub fn max_filesize(&mut self, filesize: Option) -> &mut WalkBuilder { + self.max_filesize = filesize; + self + } + + /// The number of threads to use for traversal. + /// + /// Note that this only has an effect when using `build_parallel`. + /// + /// The default setting is `0`, which chooses the number of threads + /// automatically using heuristics. + pub fn threads(&mut self, n: usize) -> &mut WalkBuilder { + self.threads = n; + self + } + + /// Add a global ignore file to the matcher. + /// + /// This has lower precedence than all other sources of ignore rules. + /// + /// If there was a problem adding the ignore file, then an error is + /// returned. Note that the error may indicate *partial* failure. For + /// example, if an ignore file contains an invalid glob, all other globs + /// are still applied. + pub fn add_ignore>(&mut self, path: P) -> Option { + let mut builder = GitignoreBuilder::new(""); + let mut errs = PartialErrorBuilder::default(); + errs.maybe_push(builder.add(path)); + match builder.build() { + Ok(gi) => { self.ig_builder.add_ignore(gi); } + Err(err) => { errs.push(err); } + } + errs.into_error_option() + } + + /// Add a custom ignore file name + /// + /// These ignore files have higher precedence than all other ignore files. + /// + /// When specifying multiple names, earlier names have lower precedence than + /// later names. + pub fn add_custom_ignore_filename>( + &mut self, + file_name: S + ) -> &mut WalkBuilder { + self.ig_builder.add_custom_ignore_filename(file_name); + self + } + + /// Add an override matcher. + /// + /// By default, no override matcher is used. + /// + /// This overrides any previous setting. + pub fn overrides(&mut self, overrides: Override) -> &mut WalkBuilder { + self.ig_builder.overrides(overrides); + self + } + + /// Add a file type matcher. + /// + /// By default, no file type matcher is used. + /// + /// This overrides any previous setting. + pub fn types(&mut self, types: Types) -> &mut WalkBuilder { + self.ig_builder.types(types); + self + } + + /// Enables all the standard ignore filters. + /// + /// This toggles, as a group, all the filters that are enabled by default: + /// + /// - [hidden()](#method.hidden) + /// - [parents()](#method.parents) + /// - [ignore()](#method.ignore) + /// - [git_ignore()](#method.git_ignore) + /// - [git_global()](#method.git_global) + /// - [git_exclude()](#method.git_exclude) + /// + /// They may still be toggled individually after calling this function. + /// + /// This is (by definition) enabled by default. + pub fn standard_filters(&mut self, yes: bool) -> &mut WalkBuilder { + self.hidden(yes) + .parents(yes) + .ignore(yes) + .git_ignore(yes) + .git_global(yes) + .git_exclude(yes) + } + + /// Enables ignoring hidden files. + /// + /// This is enabled by default. + pub fn hidden(&mut self, yes: bool) -> &mut WalkBuilder { + self.ig_builder.hidden(yes); + self + } + + /// Enables reading ignore files from parent directories. + /// + /// If this is enabled, then the parent directories of each file path given + /// are traversed for ignore files (subject to the ignore settings on + /// this builder). Note that file paths are canonicalized with respect to + /// the current working directory in order to determine parent directories. + /// + /// This is enabled by default. + pub fn parents(&mut self, yes: bool) -> &mut WalkBuilder { + self.parents = yes; + self + } + + /// Enables reading `.ignore` files. + /// + /// `.ignore` files have the same semantics as `gitignore` files and are + /// supported by search tools such as ripgrep and The Silver Searcher. + /// + /// This is enabled by default. + pub fn ignore(&mut self, yes: bool) -> &mut WalkBuilder { + self.ig_builder.ignore(yes); + self + } + + /// Enables reading a global gitignore file, whose path is specified in + /// git's `core.excludesFile` config option. + /// + /// Git's config file location is `$HOME/.gitconfig`. If `$HOME/.gitconfig` + /// does not exist or does not specify `core.excludesFile`, then + /// `$XDG_CONFIG_HOME/git/ignore` is read. If `$XDG_CONFIG_HOME` is not + /// set or is empty, then `$HOME/.config/git/ignore` is used instead. + /// + /// This is enabled by default. + pub fn git_global(&mut self, yes: bool) -> &mut WalkBuilder { + self.ig_builder.git_global(yes); + self + } + + /// Enables reading `.gitignore` files. + /// + /// `.gitignore` files have match semantics as described in the `gitignore` + /// man page. + /// + /// This is enabled by default. + pub fn git_ignore(&mut self, yes: bool) -> &mut WalkBuilder { + self.ig_builder.git_ignore(yes); + self + } + + /// Enables reading `.git/info/exclude` files. + /// + /// `.git/info/exclude` files have match semantics as described in the + /// `gitignore` man page. + /// + /// This is enabled by default. + pub fn git_exclude(&mut self, yes: bool) -> &mut WalkBuilder { + self.ig_builder.git_exclude(yes); + self + } + + /// Set a function for sorting directory entries by file name. + /// + /// If a compare function is set, the resulting iterator will return all + /// paths in sorted order. The compare function will be called to compare + /// names from entries from the same directory using only the name of the + /// entry. + /// + /// Note that this is not used in the parallel iterator. + pub fn sort_by_file_name(&mut self, cmp: F) -> &mut WalkBuilder + where F: Fn(&OsStr, &OsStr) -> cmp::Ordering + Send + Sync + 'static + { + self.sorter = Some(Arc::new(cmp)); + self + } +} + +/// Walk is a recursive directory iterator over file paths in one or more +/// directories. +/// +/// Only file and directory paths matching the rules are returned. By default, +/// ignore files like `.gitignore` are respected. The precise matching rules +/// and precedence is explained in the documentation for `WalkBuilder`. +pub struct Walk { + its: vec::IntoIter<(PathBuf, Option)>, + it: Option, + ig_root: Ignore, + ig: Ignore, + max_filesize: Option, + parents: bool, +} + +impl Walk { + /// Creates a new recursive directory iterator for the file path given. + /// + /// Note that this uses default settings, which include respecting + /// `.gitignore` files. To configure the iterator, use `WalkBuilder` + /// instead. + pub fn new>(path: P) -> Walk { + WalkBuilder::new(path).build() + } + + fn skip_entry(&self, ent: &walkdir::DirEntry) -> bool { + if ent.depth() == 0 { + return false; + } + + let is_dir = walkdir_entry_is_dir(ent); + let max_size = self.max_filesize; + let should_skip_path = skip_path(&self.ig, ent.path(), is_dir); + let should_skip_filesize = if !is_dir && max_size.is_some() { + skip_filesize(max_size.unwrap(), ent.path(), &ent.metadata().ok()) + } else { + false + }; + + should_skip_path || should_skip_filesize + } +} + +impl Iterator for Walk { + type Item = Result; + + #[inline(always)] + fn next(&mut self) -> Option> { + loop { + let ev = match self.it.as_mut().and_then(|it| it.next()) { + Some(ev) => ev, + None => { + match self.its.next() { + None => return None, + Some((_, None)) => { + return Some(Ok(DirEntry::new_stdin())); + } + Some((path, Some(it))) => { + self.it = Some(it); + if self.parents && path_is_dir(&path) { + let (ig, err) = self.ig_root.add_parents(path); + self.ig = ig; + if let Some(err) = err { + return Some(Err(err)); + } + } else { + self.ig = self.ig_root.clone(); + } + } + } + continue; + } + }; + match ev { + Err(err) => { + return Some(Err(Error::from_walkdir(err))); + } + Ok(WalkEvent::Exit) => { + self.ig = self.ig.parent().unwrap(); + } + Ok(WalkEvent::Dir(ent)) => { + if self.skip_entry(&ent) { + self.it.as_mut().unwrap().it.skip_current_dir(); + // Still need to push this on the stack because + // we'll get a WalkEvent::Exit event for this dir. + // We don't care if it errors though. + let (igtmp, _) = self.ig.add_child(ent.path()); + self.ig = igtmp; + continue; + } + let (igtmp, err) = self.ig.add_child(ent.path()); + self.ig = igtmp; + return Some(Ok(DirEntry::new_walkdir(ent, err))); + } + Ok(WalkEvent::File(ent)) => { + if self.skip_entry(&ent) { + continue; + } + return Some(Ok(DirEntry::new_walkdir(ent, None))); + } + } + } + } +} + +/// WalkEventIter transforms a WalkDir iterator into an iterator that more +/// accurately describes the directory tree. Namely, it emits events that are +/// one of three types: directory, file or "exit." An "exit" event means that +/// the entire contents of a directory have been enumerated. +struct WalkEventIter { + depth: usize, + it: walkdir::IntoIter, + next: Option>, +} + +#[derive(Debug)] +enum WalkEvent { + Dir(walkdir::DirEntry), + File(walkdir::DirEntry), + Exit, +} + +impl From for WalkEventIter { + fn from(it: WalkDir) -> WalkEventIter { + WalkEventIter { depth: 0, it: it.into_iter(), next: None } + } +} + +impl Iterator for WalkEventIter { + type Item = walkdir::Result; + + #[inline(always)] + fn next(&mut self) -> Option> { + let dent = self.next.take().or_else(|| self.it.next()); + let depth = match dent { + None => 0, + Some(Ok(ref dent)) => dent.depth(), + Some(Err(ref err)) => err.depth(), + }; + if depth < self.depth { + self.depth -= 1; + self.next = dent; + return Some(Ok(WalkEvent::Exit)); + } + self.depth = depth; + match dent { + None => None, + Some(Err(err)) => Some(Err(err)), + Some(Ok(dent)) => { + if walkdir_entry_is_dir(&dent) { + self.depth += 1; + Some(Ok(WalkEvent::Dir(dent))) + } else { + Some(Ok(WalkEvent::File(dent))) + } + } + } + } +} + +/// WalkState is used in the parallel recursive directory iterator to indicate +/// whether walking should continue as normal, skip descending into a +/// particular directory or quit the walk entirely. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum WalkState { + /// Continue walking as normal. + Continue, + /// If the directory entry given is a directory, don't descend into it. + /// In all other cases, this has no effect. + Skip, + /// Quit the entire iterator as soon as possible. + /// + /// Note that this is an inherently asynchronous action. It is possible + /// for more entries to be yielded even after instructing the iterator + /// to quit. + Quit, +} + +impl WalkState { + fn is_quit(&self) -> bool { + *self == WalkState::Quit + } +} + +/// WalkParallel is a parallel recursive directory iterator over files paths +/// in one or more directories. +/// +/// Only file and directory paths matching the rules are returned. By default, +/// ignore files like `.gitignore` are respected. The precise matching rules +/// and precedence is explained in the documentation for `WalkBuilder`. +/// +/// Unlike `Walk`, this uses multiple threads for traversing a directory. +pub struct WalkParallel { + paths: vec::IntoIter, + ig_root: Ignore, + parents: bool, + max_filesize: Option, + max_depth: Option, + follow_links: bool, + threads: usize, +} + +impl WalkParallel { + /// Execute the parallel recursive directory iterator. `mkf` is called + /// for each thread used for iteration. The function produced by `mkf` + /// is then in turn called for each visited file path. + pub fn run( + self, + mut mkf: F, + ) where F: FnMut() -> Box) -> WalkState + Send + 'static> { + let mut f = mkf(); + let threads = self.threads(); + let queue = Arc::new(MsQueue::new()); + let mut any_work = false; + // Send the initial set of root paths to the pool of workers. + // Note that we only send directories. For files, we send to them the + // callback directly. + for path in self.paths { + let dent = + if path == Path::new("-") { + DirEntry::new_stdin() + } else { + match DirEntryRaw::from_link(0, path) { + Ok(dent) => DirEntry::new_raw(dent, None), + Err(err) => { + if f(Err(err)).is_quit() { + return; + } + continue; + } + } + }; + queue.push(Message::Work(Work { + dent: dent, + ignore: self.ig_root.clone(), + })); + any_work = true; + } + // ... but there's no need to start workers if we don't need them. + if !any_work { + return; + } + // Create the workers and then wait for them to finish. + let num_waiting = Arc::new(AtomicUsize::new(0)); + let num_quitting = Arc::new(AtomicUsize::new(0)); + let quit_now = Arc::new(AtomicBool::new(false)); + let mut handles = vec![]; + for _ in 0..threads { + let worker = Worker { + f: mkf(), + queue: queue.clone(), + quit_now: quit_now.clone(), + is_waiting: false, + is_quitting: false, + num_waiting: num_waiting.clone(), + num_quitting: num_quitting.clone(), + threads: threads, + parents: self.parents, + max_depth: self.max_depth, + max_filesize: self.max_filesize, + follow_links: self.follow_links, + }; + handles.push(thread::spawn(|| worker.run())); + } + for handle in handles { + handle.join().unwrap(); + } + } + + fn threads(&self) -> usize { + if self.threads == 0 { + 2 + } else { + self.threads + } + } +} + +/// Message is the set of instructions that a worker knows how to process. +enum Message { + /// A work item corresponds to a directory that should be descended into. + /// Work items for entries that should be skipped or ignored should not + /// be produced. + Work(Work), + /// This instruction indicates that the worker should start quitting. + Quit, +} + +/// A unit of work for each worker to process. +/// +/// Each unit of work corresponds to a directory that should be descended +/// into. +struct Work { + /// The directory entry. + dent: DirEntry, + /// Any ignore matchers that have been built for this directory's parents. + ignore: Ignore, +} + +impl Work { + /// Returns true if and only if this work item is a directory. + fn is_dir(&self) -> bool { + self.dent.is_dir() + } + + /// Returns true if and only if this work item is a symlink. + fn is_symlink(&self) -> bool { + self.dent.file_type().map_or(false, |ft| ft.is_symlink()) + } + + /// Adds ignore rules for parent directories. + /// + /// Note that this only applies to entries at depth 0. On all other + /// entries, this is a no-op. + fn add_parents(&mut self) -> Option { + if self.dent.depth() > 0 { + return None; + } + // At depth 0, the path of this entry is a root path, so we can + // use it directly to add parent ignore rules. + let (ig, err) = self.ignore.add_parents(self.dent.path()); + self.ignore = ig; + err + } + + /// Reads the directory contents of this work item and adds ignore + /// rules for this directory. + /// + /// If there was a problem with reading the directory contents, then + /// an error is returned. If there was a problem reading the ignore + /// rules for this directory, then the error is attached to this + /// work item's directory entry. + fn read_dir(&mut self) -> Result { + let readdir = match fs::read_dir(self.dent.path()) { + Ok(readdir) => readdir, + Err(err) => { + let err = Error::from(err) + .with_path(self.dent.path()) + .with_depth(self.dent.depth()); + return Err(err); + } + }; + let (ig, err) = self.ignore.add_child(self.dent.path()); + self.ignore = ig; + self.dent.err = err; + Ok(readdir) + } +} + +/// A worker is responsible for descending into directories, updating the +/// ignore matchers, producing new work and invoking the caller's callback. +/// +/// Note that a worker is *both* a producer and a consumer. +struct Worker { + /// The caller's callback. + f: Box) -> WalkState + Send + 'static>, + /// A queue of work items. This is multi-producer and multi-consumer. + queue: Arc>, + /// Whether all workers should quit at the next opportunity. Note that + /// this is distinct from quitting because of exhausting the contents of + /// a directory. Instead, this is used when the caller's callback indicates + /// that the iterator should quit immediately. + quit_now: Arc, + /// Whether this worker is waiting for more work. + is_waiting: bool, + /// Whether this worker has started to quit. + is_quitting: bool, + /// The number of workers waiting for more work. + num_waiting: Arc, + /// The number of workers waiting to quit. + num_quitting: Arc, + /// The total number of workers. + threads: usize, + /// Whether to create ignore matchers for parents of caller specified + /// directories. + parents: bool, + /// The maximum depth of directories to descend. A value of `0` means no + /// descension at all. + max_depth: Option, + /// The maximum size a searched file can be (in bytes). If a file exceeds + /// this size it will be skipped. + max_filesize: Option, + /// Whether to follow symbolic links or not. When this is enabled, loop + /// detection is performed. + follow_links: bool, +} + +impl Worker { + /// Runs this worker until there is no more work left to do. + /// + /// The worker will call the caller's callback for all entries that aren't + /// skipped by the ignore matcher. + fn run(mut self) { + while let Some(mut work) = self.get_work() { + // If the work is not a directory, then we can just execute the + // caller's callback immediately and move on. + if work.is_symlink() || !work.is_dir() { + if (self.f)(Ok(work.dent)).is_quit() { + self.quit_now(); + return; + } + continue; + } + if self.parents { + if let Some(err) = work.add_parents() { + if (self.f)(Err(err)).is_quit() { + self.quit_now(); + return; + } + } + } + let readdir = match work.read_dir() { + Ok(readdir) => readdir, + Err(err) => { + if (self.f)(Err(err)).is_quit() { + self.quit_now(); + return; + } + continue; + } + }; + let depth = work.dent.depth(); + match (self.f)(Ok(work.dent)) { + WalkState::Continue => {} + WalkState::Skip => continue, + WalkState::Quit => { + self.quit_now(); + return; + } + } + if self.max_depth.map_or(false, |max| depth >= max) { + continue; + } + for result in readdir { + if self.run_one(&work.ignore, depth + 1, result).is_quit() { + self.quit_now(); + return; + } + } + } + } + + /// Runs the worker on a single entry from a directory iterator. + /// + /// If the entry is a path that should be ignored, then this is a no-op. + /// Otherwise, the entry is pushed on to the queue. (The actual execution + /// of the callback happens in `run`.) + /// + /// If an error occurs while reading the entry, then it is sent to the + /// caller's callback. + /// + /// `ig` is the `Ignore` matcher for the parent directory. `depth` should + /// be the depth of this entry. `result` should be the item yielded by + /// a directory iterator. + fn run_one( + &mut self, + ig: &Ignore, + depth: usize, + result: Result, + ) -> WalkState { + let fs_dent = match result { + Ok(fs_dent) => fs_dent, + Err(err) => { + return (self.f)(Err(Error::from(err).with_depth(depth))); + } + }; + let mut dent = match DirEntryRaw::from_entry(depth, &fs_dent) { + Ok(dent) => DirEntry::new_raw(dent, None), + Err(err) => { + return (self.f)(Err(err)); + } + }; + let is_symlink = dent.file_type().map_or(false, |ft| ft.is_symlink()); + if self.follow_links && is_symlink { + let path = dent.path().to_path_buf(); + dent = match DirEntryRaw::from_link(depth, path) { + Ok(dent) => DirEntry::new_raw(dent, None), + Err(err) => { + return (self.f)(Err(err)); + } + }; + if dent.is_dir() { + if let Err(err) = check_symlink_loop(ig, dent.path(), depth) { + return (self.f)(Err(err)); + } + } + } + let is_dir = dent.is_dir(); + let max_size = self.max_filesize; + let should_skip_path = skip_path(ig, dent.path(), is_dir); + let should_skip_filesize = if !is_dir && max_size.is_some() { + skip_filesize(max_size.unwrap(), dent.path(), &dent.metadata().ok()) + } else { + false + }; + + if !should_skip_path && !should_skip_filesize { + self.queue.push(Message::Work(Work { + dent: dent, + ignore: ig.clone(), + })); + } + WalkState::Continue + } + + /// Returns the next directory to descend into. + /// + /// If all work has been exhausted, then this returns None. The worker + /// should then subsequently quit. + fn get_work(&mut self) -> Option { + loop { + if self.is_quit_now() { + return None; + } + match self.queue.try_pop() { + Some(Message::Work(work)) => { + self.waiting(false); + self.quitting(false); + return Some(work); + } + Some(Message::Quit) => { + // We can't just quit because a Message::Quit could be + // spurious. For example, it's possible to observe that + // all workers are waiting even if there's more work to + // be done. + // + // Therefore, we do a bit of a dance to wait until all + // workers have signaled that they're ready to quit before + // actually quitting. + // + // If the Quit message turns out to be spurious, then the + // loop below will break and we'll go back to looking for + // more work. + self.waiting(true); + self.quitting(true); + while !self.is_quit_now() { + let nwait = self.num_waiting(); + let nquit = self.num_quitting(); + // If the number of waiting workers dropped, then + // abort our attempt to quit. + if nwait < self.threads { + break; + } + // If all workers are in this quit loop, then we + // can stop. + if nquit == self.threads { + return None; + } + // Otherwise, spin. + } + } + None => { + self.waiting(true); + self.quitting(false); + if self.num_waiting() == self.threads { + for _ in 0..self.threads { + self.queue.push(Message::Quit); + } + } else { + // You're right to consider this suspicious, but it's + // a useful heuristic to permit producers to catch up + // to consumers without burning the CPU. It is also + // useful as a means to prevent burning the CPU if only + // one worker is left doing actual work. It's not + // perfect and it doesn't leave the CPU completely + // idle, but it's not clear what else we can do. :-/ + thread::sleep(Duration::from_millis(1)); + } + } + } + } + } + + /// Indicates that all workers should quit immediately. + fn quit_now(&self) { + self.quit_now.store(true, Ordering::SeqCst); + } + + /// Returns true if this worker should quit immediately. + fn is_quit_now(&self) -> bool { + self.quit_now.load(Ordering::SeqCst) + } + + /// Returns the total number of workers waiting for work. + fn num_waiting(&self) -> usize { + self.num_waiting.load(Ordering::SeqCst) + } + + /// Returns the total number of workers ready to quit. + fn num_quitting(&self) -> usize { + self.num_quitting.load(Ordering::SeqCst) + } + + /// Sets this worker's "quitting" state to the value of `yes`. + fn quitting(&mut self, yes: bool) { + if yes { + if !self.is_quitting { + self.is_quitting = true; + self.num_quitting.fetch_add(1, Ordering::SeqCst); + } + } else { + if self.is_quitting { + self.is_quitting = false; + self.num_quitting.fetch_sub(1, Ordering::SeqCst); + } + } + } + + /// Sets this worker's "waiting" state to the value of `yes`. + fn waiting(&mut self, yes: bool) { + if yes { + if !self.is_waiting { + self.is_waiting = true; + self.num_waiting.fetch_add(1, Ordering::SeqCst); + } + } else { + if self.is_waiting { + self.is_waiting = false; + self.num_waiting.fetch_sub(1, Ordering::SeqCst); + } + } + } +} + +fn check_symlink_loop( + ig_parent: &Ignore, + child_path: &Path, + child_depth: usize, +) -> Result<(), Error> { + let hchild = Handle::from_path(child_path).map_err(|err| { + Error::from(err).with_path(child_path).with_depth(child_depth) + })?; + for ig in ig_parent.parents().take_while(|ig| !ig.is_absolute_parent()) { + let h = Handle::from_path(ig.path()).map_err(|err| { + Error::from(err).with_path(child_path).with_depth(child_depth) + })?; + if hchild == h { + return Err(Error::Loop { + ancestor: ig.path().to_path_buf(), + child: child_path.to_path_buf(), + }.with_depth(child_depth)); + } + } + Ok(()) +} + +// Before calling this function, make sure that you ensure that is really +// necessary as the arguments imply a file stat. +fn skip_filesize( + max_filesize: u64, + path: &Path, + ent: &Option +) -> bool { + let filesize = match *ent { + Some(ref md) => Some(md.len()), + None => None + }; + + if let Some(fs) = filesize { + if fs > max_filesize { + debug!("ignoring {}: {} bytes", path.display(), fs); + true + } else { + false + } + } else { + false + } +} + +fn skip_path(ig: &Ignore, path: &Path, is_dir: bool) -> bool { + let m = ig.matched(path, is_dir); + if m.is_ignore() { + debug!("ignoring {}: {:?}", path.display(), m); + true + } else if m.is_whitelist() { + debug!("whitelisting {}: {:?}", path.display(), m); + false + } else { + false + } +} + +/// Returns true if and only if this path points to a directory. +/// +/// This works around a bug in Rust's standard library: +/// https://github.com/rust-lang/rust/issues/46484 +#[cfg(windows)] +fn path_is_dir(path: &Path) -> bool { + fs::metadata(path).map(|md| metadata_is_dir(&md)).unwrap_or(false) +} + +/// Returns true if and only if this entry points to a directory. +#[cfg(not(windows))] +fn path_is_dir(path: &Path) -> bool { + path.is_dir() +} + +/// Returns true if and only if this path points to a file. +/// +/// This works around a bug in Rust's standard library: +/// https://github.com/rust-lang/rust/issues/46484 +#[cfg(windows)] +fn path_is_file(path: &Path) -> bool { + !path_is_dir(path) +} + +/// Returns true if and only if this entry points to a directory. +#[cfg(not(windows))] +fn path_is_file(path: &Path) -> bool { + path.is_file() +} + +/// Returns true if and only if the given walkdir entry points to a directory. +/// +/// This works around a bug in Rust's standard library: +/// https://github.com/rust-lang/rust/issues/46484 +#[cfg(windows)] +fn walkdir_entry_is_dir(dent: &walkdir::DirEntry) -> bool { + dent.metadata().map(|md| metadata_is_dir(&md)).unwrap_or(false) +} + +/// Returns true if and only if the given walkdir entry points to a directory. +#[cfg(not(windows))] +fn walkdir_entry_is_dir(dent: &walkdir::DirEntry) -> bool { + dent.file_type().is_dir() +} + +/// Returns true if and only if the given metadata points to a directory. +/// +/// This works around a bug in Rust's standard library: +/// https://github.com/rust-lang/rust/issues/46484 +#[cfg(windows)] +fn metadata_is_dir(md: &fs::Metadata) -> bool { + use std::os::windows::fs::MetadataExt; + use winapi::um::winnt::FILE_ATTRIBUTE_DIRECTORY; + md.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 +} + +#[cfg(test)] +mod tests { + use std::fs::{self, File}; + use std::io::Write; + use std::path::Path; + use std::sync::{Arc, Mutex}; + + use tempdir::TempDir; + + use super::{WalkBuilder, WalkState}; + + fn wfile>(path: P, contents: &str) { + let mut file = File::create(path).unwrap(); + file.write_all(contents.as_bytes()).unwrap(); + } + + fn wfile_size>(path: P, size: u64) { + let file = File::create(path).unwrap(); + file.set_len(size).unwrap(); + } + + #[cfg(unix)] + fn symlink, Q: AsRef>(src: P, dst: Q) { + use std::os::unix::fs::symlink; + symlink(src, dst).unwrap(); + } + + fn mkdirp>(path: P) { + fs::create_dir_all(path).unwrap(); + } + + fn normal_path(unix: &str) -> String { + if cfg!(windows) { + unix.replace("\\", "/") + } else { + unix.to_string() + } + } + + fn walk_collect(prefix: &Path, builder: &WalkBuilder) -> Vec { + let mut paths = vec![]; + for result in builder.build() { + let dent = match result { + Err(_) => continue, + Ok(dent) => dent, + }; + let path = dent.path().strip_prefix(prefix).unwrap(); + if path.as_os_str().is_empty() { + continue; + } + paths.push(normal_path(path.to_str().unwrap())); + } + paths.sort(); + paths + } + + fn walk_collect_parallel( + prefix: &Path, + builder: &WalkBuilder, + ) -> Vec { + let paths = Arc::new(Mutex::new(vec![])); + let prefix = Arc::new(prefix.to_path_buf()); + builder.build_parallel().run(|| { + let paths = paths.clone(); + let prefix = prefix.clone(); + Box::new(move |result| { + let dent = match result { + Err(_) => return WalkState::Continue, + Ok(dent) => dent, + }; + let path = dent.path().strip_prefix(&**prefix).unwrap(); + if path.as_os_str().is_empty() { + return WalkState::Continue; + } + let mut paths = paths.lock().unwrap(); + paths.push(normal_path(path.to_str().unwrap())); + WalkState::Continue + }) + }); + let mut paths = paths.lock().unwrap(); + paths.sort(); + paths.to_vec() + } + + fn mkpaths(paths: &[&str]) -> Vec { + let mut paths: Vec<_> = paths.iter().map(|s| s.to_string()).collect(); + paths.sort(); + paths + } + + fn assert_paths( + prefix: &Path, + builder: &WalkBuilder, + expected: &[&str], + ) { + let got = walk_collect(prefix, builder); + assert_eq!(got, mkpaths(expected)); + let got = walk_collect_parallel(prefix, builder); + assert_eq!(got, mkpaths(expected)); + } + + #[test] + fn no_ignores() { + let td = TempDir::new("walk-test-").unwrap(); + mkdirp(td.path().join("a/b/c")); + mkdirp(td.path().join("x/y")); + wfile(td.path().join("a/b/foo"), ""); + wfile(td.path().join("x/y/foo"), ""); + + assert_paths(td.path(), &WalkBuilder::new(td.path()), &[ + "x", "x/y", "x/y/foo", "a", "a/b", "a/b/foo", "a/b/c", + ]); + } + + #[test] + fn custom_ignore() { + let td = TempDir::new("walk-test-").unwrap(); + let custom_ignore = ".customignore"; + mkdirp(td.path().join("a")); + wfile(td.path().join(custom_ignore), "foo"); + wfile(td.path().join("foo"), ""); + wfile(td.path().join("a/foo"), ""); + wfile(td.path().join("bar"), ""); + wfile(td.path().join("a/bar"), ""); + + let mut builder = WalkBuilder::new(td.path()); + builder.add_custom_ignore_filename(&custom_ignore); + assert_paths(td.path(), &builder, &["bar", "a", "a/bar"]); + } + + #[test] + fn custom_ignore_exclusive_use() { + let td = TempDir::new("walk-test-").unwrap(); + let custom_ignore = ".customignore"; + mkdirp(td.path().join("a")); + wfile(td.path().join(custom_ignore), "foo"); + wfile(td.path().join("foo"), ""); + wfile(td.path().join("a/foo"), ""); + wfile(td.path().join("bar"), ""); + wfile(td.path().join("a/bar"), ""); + + let mut builder = WalkBuilder::new(td.path()); + builder.ignore(false); + builder.git_ignore(false); + builder.git_global(false); + builder.git_exclude(false); + builder.add_custom_ignore_filename(&custom_ignore); + assert_paths(td.path(), &builder, &["bar", "a", "a/bar"]); + } + + #[test] + fn gitignore() { + let td = TempDir::new("walk-test-").unwrap(); + mkdirp(td.path().join("a")); + wfile(td.path().join(".gitignore"), "foo"); + wfile(td.path().join("foo"), ""); + wfile(td.path().join("a/foo"), ""); + wfile(td.path().join("bar"), ""); + wfile(td.path().join("a/bar"), ""); + + assert_paths(td.path(), &WalkBuilder::new(td.path()), &[ + "bar", "a", "a/bar", + ]); + } + + #[test] + fn explicit_ignore() { + let td = TempDir::new("walk-test-").unwrap(); + let igpath = td.path().join(".not-an-ignore"); + mkdirp(td.path().join("a")); + wfile(&igpath, "foo"); + wfile(td.path().join("foo"), ""); + wfile(td.path().join("a/foo"), ""); + wfile(td.path().join("bar"), ""); + wfile(td.path().join("a/bar"), ""); + + let mut builder = WalkBuilder::new(td.path()); + assert!(builder.add_ignore(&igpath).is_none()); + assert_paths(td.path(), &builder, &["bar", "a", "a/bar"]); + } + + #[test] + fn gitignore_parent() { + let td = TempDir::new("walk-test-").unwrap(); + mkdirp(td.path().join("a")); + wfile(td.path().join(".gitignore"), "foo"); + wfile(td.path().join("a/foo"), ""); + wfile(td.path().join("a/bar"), ""); + + let root = td.path().join("a"); + assert_paths(&root, &WalkBuilder::new(&root), &["bar"]); + } + + #[test] + fn max_depth() { + let td = TempDir::new("walk-test-").unwrap(); + mkdirp(td.path().join("a/b/c")); + wfile(td.path().join("foo"), ""); + wfile(td.path().join("a/foo"), ""); + wfile(td.path().join("a/b/foo"), ""); + wfile(td.path().join("a/b/c/foo"), ""); + + let mut builder = WalkBuilder::new(td.path()); + assert_paths(td.path(), &builder, &[ + "a", "a/b", "a/b/c", "foo", "a/foo", "a/b/foo", "a/b/c/foo", + ]); + assert_paths(td.path(), builder.max_depth(Some(0)), &[]); + assert_paths(td.path(), builder.max_depth(Some(1)), &["a", "foo"]); + assert_paths(td.path(), builder.max_depth(Some(2)), &[ + "a", "a/b", "foo", "a/foo", + ]); + } + + #[test] + fn max_filesize() { + let td = TempDir::new("walk-test-").unwrap(); + mkdirp(td.path().join("a/b")); + wfile_size(td.path().join("foo"), 0); + wfile_size(td.path().join("bar"), 400); + wfile_size(td.path().join("baz"), 600); + wfile_size(td.path().join("a/foo"), 600); + wfile_size(td.path().join("a/bar"), 500); + wfile_size(td.path().join("a/baz"), 200); + + let mut builder = WalkBuilder::new(td.path()); + assert_paths(td.path(), &builder, &[ + "a", "a/b", "foo", "bar", "baz", "a/foo", "a/bar", "a/baz", + ]); + assert_paths(td.path(), builder.max_filesize(Some(0)), &[ + "a", "a/b", "foo" + ]); + assert_paths(td.path(), builder.max_filesize(Some(500)), &[ + "a", "a/b", "foo", "bar", "a/bar", "a/baz" + ]); + assert_paths(td.path(), builder.max_filesize(Some(50000)), &[ + "a", "a/b", "foo", "bar", "baz", "a/foo", "a/bar", "a/baz", + ]); + } + + #[cfg(unix)] // because symlinks on windows are weird + #[test] + fn symlinks() { + let td = TempDir::new("walk-test-").unwrap(); + mkdirp(td.path().join("a/b")); + symlink(td.path().join("a/b"), td.path().join("z")); + wfile(td.path().join("a/b/foo"), ""); + + let mut builder = WalkBuilder::new(td.path()); + assert_paths(td.path(), &builder, &[ + "a", "a/b", "a/b/foo", "z", + ]); + assert_paths(td.path(), &builder.follow_links(true), &[ + "a", "a/b", "a/b/foo", "z", "z/foo", + ]); + } + + #[cfg(unix)] // because symlinks on windows are weird + #[test] + fn symlink_loop() { + let td = TempDir::new("walk-test-").unwrap(); + mkdirp(td.path().join("a/b")); + symlink(td.path().join("a"), td.path().join("a/b/c")); + + let mut builder = WalkBuilder::new(td.path()); + assert_paths(td.path(), &builder, &[ + "a", "a/b", "a/b/c", + ]); + assert_paths(td.path(), &builder.follow_links(true), &[ + "a", "a/b", + ]); + } +} diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/tests/gitignore_matched_path_or_any_parents_tests.gitignore cargo-0.26.0/vendor/ignore-0.4.1/tests/gitignore_matched_path_or_any_parents_tests.gitignore --- cargo-0.25.0/vendor/ignore-0.4.1/tests/gitignore_matched_path_or_any_parents_tests.gitignore 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/tests/gitignore_matched_path_or_any_parents_tests.gitignore 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,216 @@ +# Based on https://github.com/behnam/gitignore-test/blob/master/.gitignore + +### file in root + +# MATCH /file_root_1 +file_root_00 + +# NO_MATCH +file_root_01/ + +# NO_MATCH +file_root_02/* + +# NO_MATCH +file_root_03/** + + +# MATCH /file_root_10 +/file_root_10 + +# NO_MATCH +/file_root_11/ + +# NO_MATCH +/file_root_12/* + +# NO_MATCH +/file_root_13/** + + +# NO_MATCH +*/file_root_20 + +# NO_MATCH +*/file_root_21/ + +# NO_MATCH +*/file_root_22/* + +# NO_MATCH +*/file_root_23/** + + +# MATCH /file_root_30 +**/file_root_30 + +# NO_MATCH +**/file_root_31/ + +# NO_MATCH +**/file_root_32/* + +# NO_MATCH +**/file_root_33/** + + +### file in sub-dir + +# MATCH /parent_dir/file_deep_1 +file_deep_00 + +# NO_MATCH +file_deep_01/ + +# NO_MATCH +file_deep_02/* + +# NO_MATCH +file_deep_03/** + + +# NO_MATCH +/file_deep_10 + +# NO_MATCH +/file_deep_11/ + +# NO_MATCH +/file_deep_12/* + +# NO_MATCH +/file_deep_13/** + + +# MATCH /parent_dir/file_deep_20 +*/file_deep_20 + +# NO_MATCH +*/file_deep_21/ + +# NO_MATCH +*/file_deep_22/* + +# NO_MATCH +*/file_deep_23/** + + +# MATCH /parent_dir/file_deep_30 +**/file_deep_30 + +# NO_MATCH +**/file_deep_31/ + +# NO_MATCH +**/file_deep_32/* + +# NO_MATCH +**/file_deep_33/** + + +### dir in root + +# MATCH /dir_root_00 +dir_root_00 + +# MATCH /dir_root_01 +dir_root_01/ + +# MATCH /dir_root_02 +dir_root_02/* + +# MATCH /dir_root_03 +dir_root_03/** + + +# MATCH /dir_root_10 +/dir_root_10 + +# MATCH /dir_root_11 +/dir_root_11/ + +# MATCH /dir_root_12 +/dir_root_12/* + +# MATCH /dir_root_13 +/dir_root_13/** + + +# NO_MATCH +*/dir_root_20 + +# NO_MATCH +*/dir_root_21/ + +# NO_MATCH +*/dir_root_22/* + +# NO_MATCH +*/dir_root_23/** + + +# MATCH /dir_root_30 +**/dir_root_30 + +# MATCH /dir_root_31 +**/dir_root_31/ + +# MATCH /dir_root_32 +**/dir_root_32/* + +# MATCH /dir_root_33 +**/dir_root_33/** + + +### dir in sub-dir + +# MATCH /parent_dir/dir_deep_00 +dir_deep_00 + +# MATCH /parent_dir/dir_deep_01 +dir_deep_01/ + +# NO_MATCH +dir_deep_02/* + +# NO_MATCH +dir_deep_03/** + + +# NO_MATCH +/dir_deep_10 + +# NO_MATCH +/dir_deep_11/ + +# NO_MATCH +/dir_deep_12/* + +# NO_MATCH +/dir_deep_13/** + + +# MATCH /parent_dir/dir_deep_20 +*/dir_deep_20 + +# MATCH /parent_dir/dir_deep_21 +*/dir_deep_21/ + +# MATCH /parent_dir/dir_deep_22 +*/dir_deep_22/* + +# MATCH /parent_dir/dir_deep_23 +*/dir_deep_23/** + + +# MATCH /parent_dir/dir_deep_30 +**/dir_deep_30 + +# MATCH /parent_dir/dir_deep_31 +**/dir_deep_31/ + +# MATCH /parent_dir/dir_deep_32 +**/dir_deep_32/* + +# MATCH /parent_dir/dir_deep_33 +**/dir_deep_33/** diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/tests/gitignore_matched_path_or_any_parents_tests.rs cargo-0.26.0/vendor/ignore-0.4.1/tests/gitignore_matched_path_or_any_parents_tests.rs --- cargo-0.25.0/vendor/ignore-0.4.1/tests/gitignore_matched_path_or_any_parents_tests.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/tests/gitignore_matched_path_or_any_parents_tests.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,297 @@ +extern crate ignore; + + +use std::path::Path; + +use ignore::gitignore::{Gitignore, GitignoreBuilder}; + + +const IGNORE_FILE: &'static str = "tests/gitignore_matched_path_or_any_parents_tests.gitignore"; + + +fn get_gitignore() -> Gitignore { + let mut builder = GitignoreBuilder::new("ROOT"); + let error = builder.add(IGNORE_FILE); + assert!(error.is_none(), "failed to open gitignore file"); + builder.build().unwrap() +} + + +#[test] +#[should_panic(expected = "path is expect to be under the root")] +fn test_path_should_be_under_root() { + let gitignore = get_gitignore(); + let path = "/tmp/some_file"; + gitignore.matched_path_or_any_parents(Path::new(path), false); + assert!(false); +} + + +#[test] +fn test_files_in_root() { + let gitignore = get_gitignore(); + let m = |path: &str| gitignore.matched_path_or_any_parents(Path::new(path), false); + + // 0x + assert!(m("ROOT/file_root_00").is_ignore()); + assert!(m("ROOT/file_root_01").is_none()); + assert!(m("ROOT/file_root_02").is_none()); + assert!(m("ROOT/file_root_03").is_none()); + + // 1x + assert!(m("ROOT/file_root_10").is_ignore()); + assert!(m("ROOT/file_root_11").is_none()); + assert!(m("ROOT/file_root_12").is_none()); + assert!(m("ROOT/file_root_13").is_none()); + + // 2x + assert!(m("ROOT/file_root_20").is_none()); + assert!(m("ROOT/file_root_21").is_none()); + assert!(m("ROOT/file_root_22").is_none()); + assert!(m("ROOT/file_root_23").is_none()); + + // 3x + assert!(m("ROOT/file_root_30").is_ignore()); + assert!(m("ROOT/file_root_31").is_none()); + assert!(m("ROOT/file_root_32").is_none()); + assert!(m("ROOT/file_root_33").is_none()); +} + + +#[test] +fn test_files_in_deep() { + let gitignore = get_gitignore(); + let m = |path: &str| gitignore.matched_path_or_any_parents(Path::new(path), false); + + // 0x + assert!(m("ROOT/parent_dir/file_deep_00").is_ignore()); + assert!(m("ROOT/parent_dir/file_deep_01").is_none()); + assert!(m("ROOT/parent_dir/file_deep_02").is_none()); + assert!(m("ROOT/parent_dir/file_deep_03").is_none()); + + // 1x + assert!(m("ROOT/parent_dir/file_deep_10").is_none()); + assert!(m("ROOT/parent_dir/file_deep_11").is_none()); + assert!(m("ROOT/parent_dir/file_deep_12").is_none()); + assert!(m("ROOT/parent_dir/file_deep_13").is_none()); + + // 2x + assert!(m("ROOT/parent_dir/file_deep_20").is_ignore()); + assert!(m("ROOT/parent_dir/file_deep_21").is_none()); + assert!(m("ROOT/parent_dir/file_deep_22").is_none()); + assert!(m("ROOT/parent_dir/file_deep_23").is_none()); + + // 3x + assert!(m("ROOT/parent_dir/file_deep_30").is_ignore()); + assert!(m("ROOT/parent_dir/file_deep_31").is_none()); + assert!(m("ROOT/parent_dir/file_deep_32").is_none()); + assert!(m("ROOT/parent_dir/file_deep_33").is_none()); +} + + +#[test] +fn test_dirs_in_root() { + let gitignore = get_gitignore(); + let m = + |path: &str, is_dir: bool| gitignore.matched_path_or_any_parents(Path::new(path), is_dir); + + // 00 + assert!(m("ROOT/dir_root_00", true).is_ignore()); + assert!(m("ROOT/dir_root_00/file", false).is_ignore()); + assert!(m("ROOT/dir_root_00/child_dir", true).is_ignore()); + assert!(m("ROOT/dir_root_00/child_dir/file", false).is_ignore()); + + // 01 + assert!(m("ROOT/dir_root_01", true).is_ignore()); + assert!(m("ROOT/dir_root_01/file", false).is_ignore()); + assert!(m("ROOT/dir_root_01/child_dir", true).is_ignore()); + assert!(m("ROOT/dir_root_01/child_dir/file", false).is_ignore()); + + // 02 + assert!(m("ROOT/dir_root_02", true).is_none()); // dir itself doesn't match + assert!(m("ROOT/dir_root_02/file", false).is_ignore()); + assert!(m("ROOT/dir_root_02/child_dir", true).is_ignore()); + assert!(m("ROOT/dir_root_02/child_dir/file", false).is_ignore()); + + // 03 + assert!(m("ROOT/dir_root_03", true).is_none()); // dir itself doesn't match + assert!(m("ROOT/dir_root_03/file", false).is_ignore()); + assert!(m("ROOT/dir_root_03/child_dir", true).is_ignore()); + assert!(m("ROOT/dir_root_03/child_dir/file", false).is_ignore()); + + // 10 + assert!(m("ROOT/dir_root_10", true).is_ignore()); + assert!(m("ROOT/dir_root_10/file", false).is_ignore()); + assert!(m("ROOT/dir_root_10/child_dir", true).is_ignore()); + assert!(m("ROOT/dir_root_10/child_dir/file", false).is_ignore()); + + // 11 + assert!(m("ROOT/dir_root_11", true).is_ignore()); + assert!(m("ROOT/dir_root_11/file", false).is_ignore()); + assert!(m("ROOT/dir_root_11/child_dir", true).is_ignore()); + assert!(m("ROOT/dir_root_11/child_dir/file", false).is_ignore()); + + // 12 + assert!(m("ROOT/dir_root_12", true).is_none()); // dir itself doesn't match + assert!(m("ROOT/dir_root_12/file", false).is_ignore()); + assert!(m("ROOT/dir_root_12/child_dir", true).is_ignore()); + assert!(m("ROOT/dir_root_12/child_dir/file", false).is_ignore()); + + // 13 + assert!(m("ROOT/dir_root_13", true).is_none()); + assert!(m("ROOT/dir_root_13/file", false).is_ignore()); + assert!(m("ROOT/dir_root_13/child_dir", true).is_ignore()); + assert!(m("ROOT/dir_root_13/child_dir/file", false).is_ignore()); + + // 20 + assert!(m("ROOT/dir_root_20", true).is_none()); + assert!(m("ROOT/dir_root_20/file", false).is_none()); + assert!(m("ROOT/dir_root_20/child_dir", true).is_none()); + assert!(m("ROOT/dir_root_20/child_dir/file", false).is_none()); + + // 21 + assert!(m("ROOT/dir_root_21", true).is_none()); + assert!(m("ROOT/dir_root_21/file", false).is_none()); + assert!(m("ROOT/dir_root_21/child_dir", true).is_none()); + assert!(m("ROOT/dir_root_21/child_dir/file", false).is_none()); + + // 22 + assert!(m("ROOT/dir_root_22", true).is_none()); + assert!(m("ROOT/dir_root_22/file", false).is_none()); + assert!(m("ROOT/dir_root_22/child_dir", true).is_none()); + assert!(m("ROOT/dir_root_22/child_dir/file", false).is_none()); + + // 23 + assert!(m("ROOT/dir_root_23", true).is_none()); + assert!(m("ROOT/dir_root_23/file", false).is_none()); + assert!(m("ROOT/dir_root_23/child_dir", true).is_none()); + assert!(m("ROOT/dir_root_23/child_dir/file", false).is_none()); + + // 30 + assert!(m("ROOT/dir_root_30", true).is_ignore()); + assert!(m("ROOT/dir_root_30/file", false).is_ignore()); + assert!(m("ROOT/dir_root_30/child_dir", true).is_ignore()); + assert!(m("ROOT/dir_root_30/child_dir/file", false).is_ignore()); + + // 31 + assert!(m("ROOT/dir_root_31", true).is_ignore()); + assert!(m("ROOT/dir_root_31/file", false).is_ignore()); + assert!(m("ROOT/dir_root_31/child_dir", true).is_ignore()); + assert!(m("ROOT/dir_root_31/child_dir/file", false).is_ignore()); + + // 32 + assert!(m("ROOT/dir_root_32", true).is_none()); // dir itself doesn't match + assert!(m("ROOT/dir_root_32/file", false).is_ignore()); + assert!(m("ROOT/dir_root_32/child_dir", true).is_ignore()); + assert!(m("ROOT/dir_root_32/child_dir/file", false).is_ignore()); + + // 33 + assert!(m("ROOT/dir_root_33", true).is_none()); // dir itself doesn't match + assert!(m("ROOT/dir_root_33/file", false).is_ignore()); + assert!(m("ROOT/dir_root_33/child_dir", true).is_ignore()); + assert!(m("ROOT/dir_root_33/child_dir/file", false).is_ignore()); +} + + +#[test] +fn test_dirs_in_deep() { + let gitignore = get_gitignore(); + let m = + |path: &str, is_dir: bool| gitignore.matched_path_or_any_parents(Path::new(path), is_dir); + + // 00 + assert!(m("ROOT/parent_dir/dir_deep_00", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_00/file", false).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_00/child_dir", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_00/child_dir/file", false).is_ignore()); + + // 01 + assert!(m("ROOT/parent_dir/dir_deep_01", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_01/file", false).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_01/child_dir", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_01/child_dir/file", false).is_ignore()); + + // 02 + assert!(m("ROOT/parent_dir/dir_deep_02", true).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_02/file", false).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_02/child_dir", true).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_02/child_dir/file", false).is_none()); + + // 03 + assert!(m("ROOT/parent_dir/dir_deep_03", true).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_03/file", false).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_03/child_dir", true).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_03/child_dir/file", false).is_none()); + + // 10 + assert!(m("ROOT/parent_dir/dir_deep_10", true).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_10/file", false).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_10/child_dir", true).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_10/child_dir/file", false).is_none()); + + // 11 + assert!(m("ROOT/parent_dir/dir_deep_11", true).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_11/file", false).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_11/child_dir", true).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_11/child_dir/file", false).is_none()); + + // 12 + assert!(m("ROOT/parent_dir/dir_deep_12", true).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_12/file", false).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_12/child_dir", true).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_12/child_dir/file", false).is_none()); + + // 13 + assert!(m("ROOT/parent_dir/dir_deep_13", true).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_13/file", false).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_13/child_dir", true).is_none()); + assert!(m("ROOT/parent_dir/dir_deep_13/child_dir/file", false).is_none()); + + // 20 + assert!(m("ROOT/parent_dir/dir_deep_20", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_20/file", false).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_20/child_dir", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_20/child_dir/file", false).is_ignore()); + + // 21 + assert!(m("ROOT/parent_dir/dir_deep_21", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_21/file", false).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_21/child_dir", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_21/child_dir/file", false).is_ignore()); + + // 22 + assert!(m("ROOT/parent_dir/dir_deep_22", true).is_none()); // dir itself doesn't match + assert!(m("ROOT/parent_dir/dir_deep_22/file", false).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_22/child_dir", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_22/child_dir/file", false).is_ignore()); + + // 23 + assert!(m("ROOT/parent_dir/dir_deep_23", true).is_none()); // dir itself doesn't match + assert!(m("ROOT/parent_dir/dir_deep_23/file", false).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_23/child_dir", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_23/child_dir/file", false).is_ignore()); + + // 30 + assert!(m("ROOT/parent_dir/dir_deep_30", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_30/file", false).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_30/child_dir", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_30/child_dir/file", false).is_ignore()); + + // 31 + assert!(m("ROOT/parent_dir/dir_deep_31", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_31/file", false).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_31/child_dir", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_31/child_dir/file", false).is_ignore()); + + // 32 + assert!(m("ROOT/parent_dir/dir_deep_32", true).is_none()); // dir itself doesn't match + assert!(m("ROOT/parent_dir/dir_deep_32/file", false).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_32/child_dir", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_32/child_dir/file", false).is_ignore()); + + // 33 + assert!(m("ROOT/parent_dir/dir_deep_33", true).is_none()); // dir itself doesn't match + assert!(m("ROOT/parent_dir/dir_deep_33/file", false).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_33/child_dir", true).is_ignore()); + assert!(m("ROOT/parent_dir/dir_deep_33/child_dir/file", false).is_ignore()); +} diff -Nru cargo-0.25.0/vendor/ignore-0.4.1/UNLICENSE cargo-0.26.0/vendor/ignore-0.4.1/UNLICENSE --- cargo-0.25.0/vendor/ignore-0.4.1/UNLICENSE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ignore-0.4.1/UNLICENSE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +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 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. + +For more information, please refer to diff -Nru cargo-0.25.0/vendor/itoa-0.3.4/benches/bench.rs cargo-0.26.0/vendor/itoa-0.3.4/benches/bench.rs --- cargo-0.25.0/vendor/itoa-0.3.4/benches/bench.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.3.4/benches/bench.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -#![cfg_attr(feature = "i128", feature(i128_type, i128))] - -#![cfg_attr(feature = "cargo-clippy", allow(cast_lossless))] - -#![feature(test)] -#![allow(non_snake_case)] - -extern crate itoa; -extern crate test; - -macro_rules! benches { - ( - $( - $(#[$attr:meta])* - $name:ident($value:expr) - ),* - ) => { - mod bench_itoa { - use test::{Bencher, black_box}; - $( - $(#[$attr])* - #[bench] - fn $name(b: &mut Bencher) { - use itoa; - - let mut buf = Vec::with_capacity(40); - - b.iter(|| { - buf.clear(); - itoa::write(&mut buf, black_box($value)).unwrap() - }); - } - )* - } - - mod bench_fmt { - use test::{Bencher, black_box}; - $( - $(#[$attr])* - #[bench] - fn $name(b: &mut Bencher) { - use std::io::Write; - - let mut buf = Vec::with_capacity(40); - - b.iter(|| { - buf.clear(); - write!(&mut buf, "{}", black_box($value)).unwrap() - }); - } - )* - } - } -} - -benches!{ - bench_u64_0(0u64), - bench_u64_half(::max_value() as u64), - bench_u64_max(::max_value()), - - bench_i16_0(0i16), - bench_i16_min(::min_value()), - - #[cfg(feature = "i128")] - bench_u128_0(0u128), - #[cfg(feature = "i128")] - bench_u128_max(::max_value()) -} diff -Nru cargo-0.25.0/vendor/itoa-0.3.4/.cargo-checksum.json cargo-0.26.0/vendor/itoa-0.3.4/.cargo-checksum.json --- cargo-0.25.0/vendor/itoa-0.3.4/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.3.4/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"8324a32baf01e2ae060e9de58ed0bc2320c9a2833491ee36cd3b4c414de4db8c"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/itoa-0.3.4/Cargo.toml cargo-0.26.0/vendor/itoa-0.3.4/Cargo.toml --- cargo-0.25.0/vendor/itoa-0.3.4/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.3.4/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "itoa" -version = "0.3.4" -authors = ["David Tolnay "] -exclude = ["performance.png"] -description = "Fast functions for printing integer primitives to an io::Write" -documentation = "https://github.com/dtolnay/itoa" -readme = "README.md" -categories = ["value-formatting"] -license = "MIT/Apache-2.0" -repository = "https://github.com/dtolnay/itoa" - -[features] -i128 = [] diff -Nru cargo-0.25.0/vendor/itoa-0.3.4/LICENSE-APACHE cargo-0.26.0/vendor/itoa-0.3.4/LICENSE-APACHE --- cargo-0.25.0/vendor/itoa-0.3.4/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.3.4/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/itoa-0.3.4/LICENSE-MIT cargo-0.26.0/vendor/itoa-0.3.4/LICENSE-MIT --- cargo-0.25.0/vendor/itoa-0.3.4/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.3.4/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2016 Itoa 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. diff -Nru cargo-0.25.0/vendor/itoa-0.3.4/README.md cargo-0.26.0/vendor/itoa-0.3.4/README.md --- cargo-0.25.0/vendor/itoa-0.3.4/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.3.4/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -itoa -==== - -[![Build Status](https://api.travis-ci.org/dtolnay/itoa.svg?branch=master)](https://travis-ci.org/dtolnay/itoa) -[![Latest Version](https://img.shields.io/crates/v/itoa.svg)](https://crates.io/crates/itoa) - -This crate provides fast functions for printing integer primitives to an -[`io::Write`](https://doc.rust-lang.org/std/io/trait.Write.html). The -implementation comes straight from -[libcore](https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L201-L254) -but avoids the performance penalty of going through -[`fmt::Formatter`](https://doc.rust-lang.org/std/fmt/struct.Formatter.html). - -See also [`dtoa`](https://github.com/dtolnay/dtoa) for printing floating point -primitives. - -## Performance (lower is better) - -![performance](https://raw.githubusercontent.com/dtolnay/itoa/master/performance.png) - -## Functions - -```rust -extern crate itoa; - -// write to a vector or other io::Write -let mut buf = Vec::new(); -itoa::write(&mut buf, 128u64)?; -println!("{:?}", buf); - -// write to a stack buffer -let mut bytes = [b'\0'; 20]; -let n = itoa::write(&mut bytes[..], 128u64)?; -println!("{:?}", &bytes[..n]); -``` - -The function signature is: - -```rust -fn write(writer: W, value: V) -> io::Result -``` - -where `itoa::Integer` is implemented for `i8`, `u8`, `i16`, `u16`, `i32`, `u32`, -`i64`, `u64`, `i128`, `u128`, `isize` and `usize`. 128-bit integer support is -only available with the nightly compiler when the `i128` feature is enabled for -this crate. The return value gives the number of bytes written. - -## Dependency - -Itoa is available on [crates.io](https://crates.io/crates/itoa). Use the -following in `Cargo.toml`: - -```toml -[dependencies] -itoa = "0.3" -``` - -## 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 itoa by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/itoa-0.3.4/src/lib.rs cargo-0.26.0/vendor/itoa-0.3.4/src/lib.rs --- cargo-0.25.0/vendor/itoa-0.3.4/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.3.4/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,196 +0,0 @@ -// Copyright 2016 Itoa Developers -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![doc(html_root_url = "https://docs.rs/itoa/0.3.4")] - -#![cfg_attr(feature = "i128", feature(i128_type, i128))] - -#![cfg_attr(feature = "cargo-clippy", allow(cast_lossless, unreadable_literal))] - -#[cfg(feature = "i128")] -mod udiv128; - -use std::{io, mem, ptr, slice}; - -#[inline] -pub fn write(wr: W, value: V) -> io::Result { - value.write(wr) -} - -pub trait Integer { - fn write(self, W) -> io::Result; -} - -trait IntegerPrivate { - fn write_to(self, buf: &mut [u8; MAX_LEN]) -> &[u8]; -} - -const DEC_DIGITS_LUT: &'static[u8] = - b"0001020304050607080910111213141516171819\ - 2021222324252627282930313233343536373839\ - 4041424344454647484950515253545556575859\ - 6061626364656667686970717273747576777879\ - 8081828384858687888990919293949596979899"; - -const MAX_LEN: usize = 40; // i128::MIN (including minus sign) - -// Adaptation of the original implementation at -// https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L188-L266 -macro_rules! impl_Integer { - ($($t:ident),* as $conv_fn:ident) => {$( - impl Integer for $t { - fn write(self, mut wr: W) -> io::Result { - let mut buf = unsafe { mem::uninitialized() }; - let bytes = self.write_to(&mut buf); - try!(wr.write_all(bytes)); - Ok(bytes.len()) - } - } - - impl IntegerPrivate for $t { - #[allow(unused_comparisons)] - fn write_to(self, buf: &mut [u8; MAX_LEN]) -> &[u8] { - let is_nonnegative = self >= 0; - let mut n = if is_nonnegative { - self as $conv_fn - } else { - // convert the negative num to positive by summing 1 to it's 2 complement - (!(self as $conv_fn)).wrapping_add(1) - }; - let mut curr = buf.len() as isize; - let buf_ptr = buf.as_mut_ptr(); - let lut_ptr = DEC_DIGITS_LUT.as_ptr(); - - unsafe { - // need at least 16 bits for the 4-characters-at-a-time to work. - if mem::size_of::<$t>() >= 2 { - // eagerly decode 4 characters at a time - while n >= 10000 { - let rem = (n % 10000) as isize; - n /= 10000; - - let d1 = (rem / 100) << 1; - let d2 = (rem % 100) << 1; - curr -= 4; - ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); - ptr::copy_nonoverlapping(lut_ptr.offset(d2), buf_ptr.offset(curr + 2), 2); - } - } - - // if we reach here numbers are <= 9999, so at most 4 chars long - let mut n = n as isize; // possibly reduce 64bit math - - // decode 2 more chars, if > 2 chars - if n >= 100 { - let d1 = (n % 100) << 1; - n /= 100; - curr -= 2; - ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); - } - - // decode last 1 or 2 chars - if n < 10 { - curr -= 1; - *buf_ptr.offset(curr) = (n as u8) + b'0'; - } else { - let d1 = n << 1; - curr -= 2; - ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); - } - - if !is_nonnegative { - curr -= 1; - *buf_ptr.offset(curr) = b'-'; - } - } - - let len = buf.len() - curr as usize; - unsafe { slice::from_raw_parts(buf_ptr.offset(curr), len) } - } - } - )*}; -} - -impl_Integer!(i8, u8, i16, u16, i32, u32 as u32); -impl_Integer!(i64, u64 as u64); -#[cfg(target_pointer_width = "16")] -impl_Integer!(isize, usize as u16); -#[cfg(target_pointer_width = "32")] -impl_Integer!(isize, usize as u32); -#[cfg(target_pointer_width = "64")] -impl_Integer!(isize, usize as u64); - -#[cfg(all(feature = "i128"))] -macro_rules! impl_Integer128 { - ($($t:ident),*) => {$( - impl Integer for $t { - fn write(self, mut wr: W) -> io::Result { - let mut buf = unsafe { mem::uninitialized() }; - let bytes = self.write_to(&mut buf); - try!(wr.write_all(bytes)); - Ok(bytes.len()) - } - } - - impl IntegerPrivate for $t { - #[allow(unused_comparisons)] - fn write_to(self, buf: &mut [u8; MAX_LEN]) -> &[u8] { - let is_nonnegative = self >= 0; - let n = if is_nonnegative { - self as u128 - } else { - // convert the negative num to positive by summing 1 to it's 2 complement - (!(self as u128)).wrapping_add(1) - }; - let mut curr = buf.len() as isize; - let buf_ptr = buf.as_mut_ptr(); - - unsafe { - // Divide by 10^19 which is the highest power less than 2^64. - let (n, rem) = udiv128::udivmod_1e19(n); - curr -= rem.write_to(buf).len() as isize; - - if n != 0 { - // Memset the base10 leading zeros of rem. - let target = buf.len() as isize - 19; - ptr::write_bytes(buf_ptr.offset(target), b'0', (curr - target) as usize); - curr = target; - - // Divide by 10^19 again. - let (n, rem) = udiv128::udivmod_1e19(n); - let buf2 = buf_ptr.offset(curr - buf.len() as isize) as *mut _; - curr -= rem.write_to(&mut *buf2).len() as isize; - - if n != 0 { - // Memset the leading zeros. - let target = buf.len() as isize - 38; - ptr::write_bytes(buf_ptr.offset(target), b'0', (curr - target) as usize); - curr = target; - - // There is at most one digit left - // because u128::max / 10^19 / 10^19 is 3. - curr -= 1; - *buf_ptr.offset(curr) = (n as u8) + b'0'; - } - } - - if !is_nonnegative { - curr -= 1; - *buf_ptr.offset(curr) = b'-'; - } - - let len = buf.len() - curr as usize; - slice::from_raw_parts(buf_ptr.offset(curr), len) - } - } - } - )*}; -} - -#[cfg(all(feature = "i128"))] -impl_Integer128!(i128, u128); diff -Nru cargo-0.25.0/vendor/itoa-0.3.4/src/udiv128.rs cargo-0.26.0/vendor/itoa-0.3.4/src/udiv128.rs --- cargo-0.25.0/vendor/itoa-0.3.4/src/udiv128.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.3.4/src/udiv128.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -// Copyright 2009-2016 compiler-builtins Developers -// -// The compiler-builtins crate is dual licensed under both the University of -// Illinois "BSD-Like" license and the MIT license. As a user of this code you may -// choose to use it under either license. As a contributor, you agree to allow -// your code to be used under both. -// -// Full text of the relevant licenses is found here: -// https://github.com/rust-lang-nursery/compiler-builtins/blob/master/LICENSE.TXT -// -// -// -// The following code is based on Rust’s [compiler-builtins crate] -// (https://github.com/rust-lang-nursery/compiler-builtins) which -// provides runtime functions for the Rust programs. The Rust -// compiler will automatically link your programs against this crate. -// -// We copied the implementation of '__udivmodti4()' which is an intrinsic -// implementing division with remainder for architectures without 128-bit integer support. -// We have done this two reasons, to work around [bad optimization by LLVM] -// (https://github.com/rust-lang/rust/issues/44545) and to allow function -// inlining which doesn’t happen with the intrinsic. - -pub fn udivmod_1e19(n: u128) -> (u128, u64) { - let d = 10_000_000_000_000_000_000_u64; // 10^19 - - let high = (n >> 64) as u64; - if high == 0 { - let low = n as u64; - return ((low / d) as u128, low % d); - } - - let sr = 65 - high.leading_zeros(); - - // 2 <= sr <= 65 - let mut q: u128 = n << (128 - sr); - let mut r: u128 = n >> sr; - let mut carry: u64 = 0; - - // Don't use a range because they may generate references to memcpy in unoptimized code - // - // Loop invariants: r < d; carry is 0 or 1 - let mut i = 0; - while i < sr { - i += 1; - - // r:q = ((r:q) << 1) | carry - r = (r << 1) | (q >> 127); - q = (q << 1) | carry as u128; - - // carry = 0 - // if r >= d { - // r -= d; - // carry = 1; - // } - let s = (d as u128).wrapping_sub(r).wrapping_sub(1) as i128 >> 127; - carry = (s & 1) as u64; - r -= (d as u128) & s as u128; - } - - ((q << 1) | carry as u128, r as u64) -} diff -Nru cargo-0.25.0/vendor/itoa-0.3.4/tests/test.rs cargo-0.26.0/vendor/itoa-0.3.4/tests/test.rs --- cargo-0.25.0/vendor/itoa-0.3.4/tests/test.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.3.4/tests/test.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,43 +0,0 @@ -#![cfg_attr(feature = "i128", feature(i128_type, i128))] - -#![cfg_attr(feature = "cargo-clippy", allow(cast_lossless, string_lit_as_bytes))] - -#![allow(non_snake_case)] - -extern crate itoa; - -macro_rules! test { - ( - $( - $(#[$attr:meta])* - $name:ident($value:expr, $expected:expr) - ),* - ) => { - $( - $(#[$attr])* - #[test] - fn $name() { - let mut buf = [b'\0'; 40]; - let len = itoa::write(&mut buf[..], $value).unwrap(); - assert_eq!(&buf[0..len], $expected.as_bytes()); - } - )* - } -} - -test!{ - test_u64_0(0u64, "0"), - test_u64_half(::max_value() as u64, "4294967295"), - test_u64_max(::max_value(), "18446744073709551615"), - test_i64_min(::min_value(), "-9223372036854775808"), - - test_i16_0(0i16, "0"), - test_i16_min(::min_value(), "-32768"), - - #[cfg(feature = "i128")] - test_u128_0(0u128, "0"), - #[cfg(feature = "i128")] - test_u128_max(::max_value(), "340282366920938463463374607431768211455"), - #[cfg(feature = "i128")] - test_i128_min(::min_value(), "-170141183460469231731687303715884105728") -} diff -Nru cargo-0.25.0/vendor/itoa-0.3.4/.travis.yml cargo-0.26.0/vendor/itoa-0.3.4/.travis.yml --- cargo-0.25.0/vendor/itoa-0.3.4/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.3.4/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -sudo: false -language: rust - -matrix: - include: - - rust: stable - - rust: beta - - rust: nightly - env: - - FEATURES="i128" - - BUILD_BENCH="true" - -script: - - cargo build --verbose --features "$FEATURES" - - cargo test --verbose --features "$FEATURES" - - if [ "$BUILD_BENCH" == "true" ]; then cargo bench --verbose --no-run --features "$FEATURES"; fi - diff -Nru cargo-0.25.0/vendor/itoa-0.4.1/benches/bench.rs cargo-0.26.0/vendor/itoa-0.4.1/benches/bench.rs --- cargo-0.25.0/vendor/itoa-0.4.1/benches/bench.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.4.1/benches/bench.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,86 @@ +#![cfg_attr(feature = "i128", feature(i128_type, i128))] + +#![cfg_attr(feature = "cargo-clippy", allow(cast_lossless))] + +#![feature(test)] +#![allow(non_snake_case)] + +extern crate itoa; +extern crate test; + +macro_rules! benches { + ( + $( + $(#[$attr:meta])* + $name:ident($value:expr) + ),* + ) => { + mod bench_itoa_write { + use test::{Bencher, black_box}; + $( + $(#[$attr])* + #[bench] + fn $name(b: &mut Bencher) { + use itoa; + + let mut buf = Vec::with_capacity(40); + + b.iter(|| { + buf.clear(); + itoa::write(&mut buf, black_box($value)).unwrap() + }); + } + )* + } + + mod bench_itoa_fmt { + use test::{Bencher, black_box}; + $( + $(#[$attr])* + #[bench] + fn $name(b: &mut Bencher) { + use itoa; + + let mut buf = String::with_capacity(40); + + b.iter(|| { + buf.clear(); + itoa::fmt(&mut buf, black_box($value)).unwrap() + }); + } + )* + } + + mod bench_std_fmt { + use test::{Bencher, black_box}; + $( + $(#[$attr])* + #[bench] + fn $name(b: &mut Bencher) { + use std::io::Write; + + let mut buf = Vec::with_capacity(40); + + b.iter(|| { + buf.clear(); + write!(&mut buf, "{}", black_box($value)).unwrap() + }); + } + )* + } + } +} + +benches!{ + bench_u64_0(0u64), + bench_u64_half(::max_value() as u64), + bench_u64_max(::max_value()), + + bench_i16_0(0i16), + bench_i16_min(::min_value()), + + #[cfg(feature = "i128")] + bench_u128_0(0u128), + #[cfg(feature = "i128")] + bench_u128_max(::max_value()) +} diff -Nru cargo-0.25.0/vendor/itoa-0.4.1/.cargo-checksum.json cargo-0.26.0/vendor/itoa-0.4.1/.cargo-checksum.json --- cargo-0.25.0/vendor/itoa-0.4.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.4.1/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"c069bbec61e1ca5a596166e55dfe4773ff745c3d16b700013bcaff9a6df2c682"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/itoa-0.4.1/Cargo.toml cargo-0.26.0/vendor/itoa-0.4.1/Cargo.toml --- cargo-0.25.0/vendor/itoa-0.4.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.4.1/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "itoa" +version = "0.4.1" +authors = ["David Tolnay "] +exclude = ["performance.png"] +description = "Fast functions for printing integer primitives to an io::Write" +documentation = "https://github.com/dtolnay/itoa" +readme = "README.md" +categories = ["value-formatting"] +license = "MIT/Apache-2.0" +repository = "https://github.com/dtolnay/itoa" + +[features] +default = ["std"] +i128 = [] +std = [] diff -Nru cargo-0.25.0/vendor/itoa-0.4.1/LICENSE-APACHE cargo-0.26.0/vendor/itoa-0.4.1/LICENSE-APACHE --- cargo-0.25.0/vendor/itoa-0.4.1/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.4.1/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/itoa-0.4.1/LICENSE-MIT cargo-0.26.0/vendor/itoa-0.4.1/LICENSE-MIT --- cargo-0.25.0/vendor/itoa-0.4.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.4.1/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2016 Itoa 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. diff -Nru cargo-0.25.0/vendor/itoa-0.4.1/README.md cargo-0.26.0/vendor/itoa-0.4.1/README.md --- cargo-0.25.0/vendor/itoa-0.4.1/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.4.1/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,82 @@ +itoa +==== + +[![Build Status](https://api.travis-ci.org/dtolnay/itoa.svg?branch=master)](https://travis-ci.org/dtolnay/itoa) +[![Latest Version](https://img.shields.io/crates/v/itoa.svg)](https://crates.io/crates/itoa) + +This crate provides fast functions for printing integer primitives to an +[`io::Write`](https://doc.rust-lang.org/std/io/trait.Write.html) or a +[`fmt::Write`](https://doc.rust-lang.org/core/fmt/trait.Write.html). The +implementation comes straight from +[libcore](https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L201-L254) +but avoids the performance penalty of going through +[`fmt::Formatter`](https://doc.rust-lang.org/std/fmt/struct.Formatter.html). + +See also [`dtoa`](https://github.com/dtolnay/dtoa) for printing floating point +primitives. + +## Performance (lower is better) + +![performance](https://raw.githubusercontent.com/dtolnay/itoa/master/performance.png) + +## Functions + +```rust +extern crate itoa; + +// write to a vector or other io::Write +let mut buf = Vec::new(); +itoa::write(&mut buf, 128u64)?; +println!("{:?}", buf); + +// write to a stack buffer +let mut bytes = [b'\0'; 20]; +let n = itoa::write(&mut bytes[..], 128u64)?; +println!("{:?}", &bytes[..n]); + +// write to a String +let mut s = String::new(); +itoa::fmt(&mut s, 128u64)?; +println!("{}", s); +``` + +The function signatures are: + +```rust +fn write(writer: W, value: V) -> io::Result; + +fn fmt(writer: W, value: V) -> fmt::Result; +``` + +where `itoa::Integer` is implemented for `i8`, `u8`, `i16`, `u16`, `i32`, `u32`, +`i64`, `u64`, `i128`, `u128`, `isize` and `usize`. 128-bit integer support is +only available with the nightly compiler when the `i128` feature is enabled for +this crate. The return value gives the number of bytes written. + +The `write` function is only available when the `std` feature is enabled +(default is enabled). + +## Dependency + +Itoa is available on [crates.io](https://crates.io/crates/itoa). Use the +following in `Cargo.toml`: + +```toml +[dependencies] +itoa = "0.4" +``` + +## 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 itoa by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/itoa-0.4.1/src/lib.rs cargo-0.26.0/vendor/itoa-0.4.1/src/lib.rs --- cargo-0.25.0/vendor/itoa-0.4.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.4.1/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,261 @@ +// Copyright 2016 Itoa Developers +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![doc(html_root_url = "https://docs.rs/itoa/0.4.1")] + +#![cfg_attr(not(feature = "std"), no_std)] + +#![cfg_attr(feature = "i128", feature(i128_type, i128))] + +#![cfg_attr(feature = "cargo-clippy", allow(cast_lossless, unreadable_literal))] + +#[cfg(feature = "i128")] +mod udiv128; + +#[cfg(feature = "std")] +use std::{fmt, io, mem, ptr, slice, str}; + +#[cfg(not(feature = "std"))] +use core::{fmt, mem, ptr, slice, str}; + +/// Write integer to an `io::Write`. +#[cfg(feature = "std")] +#[inline] +pub fn write(wr: W, value: V) -> io::Result { + value.write(wr) +} + +/// Write integer to an `fmt::Write`. +#[inline] +pub fn fmt(wr: W, value: V) -> fmt::Result { + value.fmt(wr) +} + +// Seal to prevent downstream implementations of the Integer trait. +mod private { + pub trait Sealed {} +} + +/// An integer that can be formatted by `itoa::write` and `itoa::fmt`. +/// +/// This trait is sealed and cannot be implemented for types outside of itoa. +pub trait Integer: private::Sealed { + // Not public API. + #[doc(hidden)] + #[cfg(feature = "std")] + fn write(self, W) -> io::Result; + + // Not public API. + #[doc(hidden)] + fn fmt(self, W) -> fmt::Result; +} + +trait IntegerPrivate { + fn write_to(self, buf: &mut B) -> &[u8]; +} + +const DEC_DIGITS_LUT: &'static[u8] = + b"0001020304050607080910111213141516171819\ + 2021222324252627282930313233343536373839\ + 4041424344454647484950515253545556575859\ + 6061626364656667686970717273747576777879\ + 8081828384858687888990919293949596979899"; + +// Adaptation of the original implementation at +// https://github.com/rust-lang/rust/blob/b8214dc6c6fc20d0a660fb5700dca9ebf51ebe89/src/libcore/fmt/num.rs#L188-L266 +macro_rules! impl_IntegerCommon { + ($max_len:expr, $t:ident) => { + impl Integer for $t { + #[cfg(feature = "std")] + #[inline] + fn write(self, mut wr: W) -> io::Result { + let mut buf: [u8; $max_len] = unsafe { mem::uninitialized() }; + let bytes = self.write_to(&mut buf); + try!(wr.write_all(bytes)); + Ok(bytes.len()) + } + + #[inline] + fn fmt(self, mut wr: W) -> fmt::Result { + let mut buf: [u8; $max_len] = unsafe { mem::uninitialized() }; + let bytes = self.write_to(&mut buf); + wr.write_str(unsafe { str::from_utf8_unchecked(bytes) }) + } + } + + impl private::Sealed for $t {} + }; +} + +macro_rules! impl_Integer { + ($($max_len:expr => $t:ident),* as $conv_fn:ident) => {$( + impl_IntegerCommon!($max_len, $t); + + impl IntegerPrivate<[u8; $max_len]> for $t { + #[allow(unused_comparisons)] + #[inline] + fn write_to(self, buf: &mut [u8; $max_len]) -> &[u8] { + let is_nonnegative = self >= 0; + let mut n = if is_nonnegative { + self as $conv_fn + } else { + // convert the negative num to positive by summing 1 to it's 2 complement + (!(self as $conv_fn)).wrapping_add(1) + }; + let mut curr = buf.len() as isize; + let buf_ptr = buf.as_mut_ptr(); + let lut_ptr = DEC_DIGITS_LUT.as_ptr(); + + unsafe { + // need at least 16 bits for the 4-characters-at-a-time to work. + if mem::size_of::<$t>() >= 2 { + // eagerly decode 4 characters at a time + while n >= 10000 { + let rem = (n % 10000) as isize; + n /= 10000; + + let d1 = (rem / 100) << 1; + let d2 = (rem % 100) << 1; + curr -= 4; + ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); + ptr::copy_nonoverlapping(lut_ptr.offset(d2), buf_ptr.offset(curr + 2), 2); + } + } + + // if we reach here numbers are <= 9999, so at most 4 chars long + let mut n = n as isize; // possibly reduce 64bit math + + // decode 2 more chars, if > 2 chars + if n >= 100 { + let d1 = (n % 100) << 1; + n /= 100; + curr -= 2; + ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); + } + + // decode last 1 or 2 chars + if n < 10 { + curr -= 1; + *buf_ptr.offset(curr) = (n as u8) + b'0'; + } else { + let d1 = n << 1; + curr -= 2; + ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr.offset(curr), 2); + } + + if !is_nonnegative { + curr -= 1; + *buf_ptr.offset(curr) = b'-'; + } + } + + let len = buf.len() - curr as usize; + unsafe { slice::from_raw_parts(buf_ptr.offset(curr), len) } + } + } + )*}; +} + +const I8_MAX_LEN: usize = 4; +const U8_MAX_LEN: usize = 3; +const I16_MAX_LEN: usize = 6; +const U16_MAX_LEN: usize = 5; +const I32_MAX_LEN: usize = 11; +const U32_MAX_LEN: usize = 10; +const I64_MAX_LEN: usize = 20; +const U64_MAX_LEN: usize = 20; + +impl_Integer!( + I8_MAX_LEN => i8, + U8_MAX_LEN => u8, + I16_MAX_LEN => i16, + U16_MAX_LEN => u16, + I32_MAX_LEN => i32, + U32_MAX_LEN => u32 + as u32); + +impl_Integer!(I64_MAX_LEN => i64, U64_MAX_LEN => u64 as u64); + +#[cfg(target_pointer_width = "16")] +impl_Integer!(I16_MAX_LEN => isize, U16_MAX_LEN => usize as u16); + +#[cfg(target_pointer_width = "32")] +impl_Integer!(I32_MAX_LEN => isize, U32_MAX_LEN => usize as u32); + +#[cfg(target_pointer_width = "64")] +impl_Integer!(I64_MAX_LEN => isize, U64_MAX_LEN => usize as u64); + +#[cfg(all(feature = "i128"))] +macro_rules! impl_Integer128 { + ($($max_len:expr => $t:ident),*) => {$( + impl_IntegerCommon!($max_len, $t); + + impl IntegerPrivate<[u8; $max_len]> for $t { + #[allow(unused_comparisons)] + #[inline] + fn write_to(self, buf: &mut [u8; $max_len]) -> &[u8] { + let is_nonnegative = self >= 0; + let n = if is_nonnegative { + self as u128 + } else { + // convert the negative num to positive by summing 1 to it's 2 complement + (!(self as u128)).wrapping_add(1) + }; + let mut curr = buf.len() as isize; + let buf_ptr = buf.as_mut_ptr(); + + unsafe { + // Divide by 10^19 which is the highest power less than 2^64. + let (n, rem) = udiv128::udivmod_1e19(n); + let buf1 = buf_ptr.offset(curr - U64_MAX_LEN as isize) as *mut [u8; U64_MAX_LEN]; + curr -= rem.write_to(&mut *buf1).len() as isize; + + if n != 0 { + // Memset the base10 leading zeros of rem. + let target = buf.len() as isize - 19; + ptr::write_bytes(buf_ptr.offset(target), b'0', (curr - target) as usize); + curr = target; + + // Divide by 10^19 again. + let (n, rem) = udiv128::udivmod_1e19(n); + let buf2 = buf_ptr.offset(curr - U64_MAX_LEN as isize) as *mut [u8; U64_MAX_LEN]; + curr -= rem.write_to(&mut *buf2).len() as isize; + + if n != 0 { + // Memset the leading zeros. + let target = buf.len() as isize - 38; + ptr::write_bytes(buf_ptr.offset(target), b'0', (curr - target) as usize); + curr = target; + + // There is at most one digit left + // because u128::max / 10^19 / 10^19 is 3. + curr -= 1; + *buf_ptr.offset(curr) = (n as u8) + b'0'; + } + } + + if !is_nonnegative { + curr -= 1; + *buf_ptr.offset(curr) = b'-'; + } + + let len = buf.len() - curr as usize; + slice::from_raw_parts(buf_ptr.offset(curr), len) + } + } + } + )*}; +} + +#[cfg(all(feature = "i128"))] +const U128_MAX_LEN: usize = 39; +#[cfg(all(feature = "i128"))] +const I128_MAX_LEN: usize = 40; + +#[cfg(all(feature = "i128"))] +impl_Integer128!(I128_MAX_LEN => i128, U128_MAX_LEN => u128); diff -Nru cargo-0.25.0/vendor/itoa-0.4.1/src/udiv128.rs cargo-0.26.0/vendor/itoa-0.4.1/src/udiv128.rs --- cargo-0.25.0/vendor/itoa-0.4.1/src/udiv128.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.4.1/src/udiv128.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,63 @@ +// Copyright 2009-2016 compiler-builtins Developers +// +// The compiler-builtins crate is dual licensed under both the University of +// Illinois "BSD-Like" license and the MIT license. As a user of this code you may +// choose to use it under either license. As a contributor, you agree to allow +// your code to be used under both. +// +// Full text of the relevant licenses is found here: +// https://github.com/rust-lang-nursery/compiler-builtins/blob/master/LICENSE.TXT +// +// +// +// The following code is based on Rust’s [compiler-builtins crate] +// (https://github.com/rust-lang-nursery/compiler-builtins) which +// provides runtime functions for the Rust programs. The Rust +// compiler will automatically link your programs against this crate. +// +// We copied the implementation of '__udivmodti4()' which is an intrinsic +// implementing division with remainder for architectures without 128-bit integer support. +// We have done this two reasons, to work around [bad optimization by LLVM] +// (https://github.com/rust-lang/rust/issues/44545) and to allow function +// inlining which doesn’t happen with the intrinsic. + +#[inline] +pub fn udivmod_1e19(n: u128) -> (u128, u64) { + let d = 10_000_000_000_000_000_000_u64; // 10^19 + + let high = (n >> 64) as u64; + if high == 0 { + let low = n as u64; + return ((low / d) as u128, low % d); + } + + let sr = 65 - high.leading_zeros(); + + // 2 <= sr <= 65 + let mut q: u128 = n << (128 - sr); + let mut r: u128 = n >> sr; + let mut carry: u64 = 0; + + // Don't use a range because they may generate references to memcpy in unoptimized code + // + // Loop invariants: r < d; carry is 0 or 1 + let mut i = 0; + while i < sr { + i += 1; + + // r:q = ((r:q) << 1) | carry + r = (r << 1) | (q >> 127); + q = (q << 1) | carry as u128; + + // carry = 0 + // if r >= d { + // r -= d; + // carry = 1; + // } + let s = (d as u128).wrapping_sub(r).wrapping_sub(1) as i128 >> 127; + carry = (s & 1) as u64; + r -= (d as u128) & s as u128; + } + + ((q << 1) | carry as u128, r as u64) +} diff -Nru cargo-0.25.0/vendor/itoa-0.4.1/tests/test.rs cargo-0.26.0/vendor/itoa-0.4.1/tests/test.rs --- cargo-0.25.0/vendor/itoa-0.4.1/tests/test.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.4.1/tests/test.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,50 @@ +#![cfg_attr(feature = "i128", feature(i128_type, i128))] + +#![cfg_attr(feature = "cargo-clippy", allow(cast_lossless, string_lit_as_bytes))] + +#![allow(non_snake_case)] + +extern crate itoa; + +macro_rules! test { + ( + $( + $(#[$attr:meta])* + $name:ident($value:expr, $expected:expr) + ),* + ) => { + $( + $(#[$attr])* + #[test] + fn $name() { + #[cfg(feature = "std")] + { + let mut buf = [b'\0'; 40]; + let len = itoa::write(&mut buf[..], $value).unwrap(); + assert_eq!(&buf[0..len], $expected.as_bytes()); + } + + let mut s = String::new(); + itoa::fmt(&mut s, $value).unwrap(); + assert_eq!(s, $expected); + } + )* + } +} + +test!{ + test_u64_0(0u64, "0"), + test_u64_half(::max_value() as u64, "4294967295"), + test_u64_max(::max_value(), "18446744073709551615"), + test_i64_min(::min_value(), "-9223372036854775808"), + + test_i16_0(0i16, "0"), + test_i16_min(::min_value(), "-32768"), + + #[cfg(feature = "i128")] + test_u128_0(0u128, "0"), + #[cfg(feature = "i128")] + test_u128_max(::max_value(), "340282366920938463463374607431768211455"), + #[cfg(feature = "i128")] + test_i128_min(::min_value(), "-170141183460469231731687303715884105728") +} diff -Nru cargo-0.25.0/vendor/itoa-0.4.1/.travis.yml cargo-0.26.0/vendor/itoa-0.4.1/.travis.yml --- cargo-0.25.0/vendor/itoa-0.4.1/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/itoa-0.4.1/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,19 @@ +sudo: false +language: rust + +matrix: + include: + - rust: stable + - rust: beta + - rust: nightly + env: + - FEATURES="i128" + - BUILD_BENCH="true" + +script: + - cargo build --verbose --features "$FEATURES" + - cargo test --verbose --features "$FEATURES" + - cargo build --verbose --no-default-features --features "$FEATURES" + - cargo test --verbose --no-default-features --features "$FEATURES" + - if [ "$BUILD_BENCH" == "true" ]; then cargo bench --verbose --no-run --features "$FEATURES"; fi + diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/.appveyor.yml cargo-0.26.0/vendor/jobserver-0.1.11/.appveyor.yml --- cargo-0.25.0/vendor/jobserver-0.1.11/.appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/.appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,18 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + MAKE: mingw32-make + +install: + # Install rust, x86_64-pc-windows-msvc host + - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe + - rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain nightly + - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin + - set PATH=C:\msys64\mingw64\bin;C:\msys64\usr\bin;%PATH% + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/.cargo-checksum.json cargo-0.26.0/vendor/jobserver-0.1.11/.cargo-checksum.json --- cargo-0.25.0/vendor/jobserver-0.1.11/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"60af5f849e1981434e4a31d3d782c4774ae9b434ce55b101a96ecfd09147e8be"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/Cargo.toml cargo-0.26.0/vendor/jobserver-0.1.11/Cargo.toml --- cargo-0.25.0/vendor/jobserver-0.1.11/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,64 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "jobserver" +version = "0.1.11" +authors = ["Alex Crichton "] +description = "An implementation of the GNU make jobserver for Rust\n" +homepage = "https://github.com/alexcrichton/jobserver-rs" +documentation = "https://docs.rs/jobserver" +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/jobserver-rs" + +[[test]] +name = "client" +path = "tests/client.rs" +harness = false + +[[test]] +name = "server" +path = "tests/server.rs" + +[[test]] +name = "client-of-myself" +path = "tests/client-of-myself.rs" +harness = false + +[[test]] +name = "make-as-a-client" +path = "tests/make-as-a-client.rs" +harness = false + +[[test]] +name = "helper" +path = "tests/helper.rs" +[dependencies.log] +version = "0.4" +[dev-dependencies.futures] +version = "0.1" + +[dev-dependencies.num_cpus] +version = "1.0" + +[dev-dependencies.tempdir] +version = "0.3" + +[dev-dependencies.tokio-core] +version = "0.1" + +[dev-dependencies.tokio-process] +version = "0.1" +[target."cfg(unix)".dependencies.libc] +version = "0.2" +[target."cfg(windows)".dependencies.rand] +version = "0.4" diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/LICENSE-APACHE cargo-0.26.0/vendor/jobserver-0.1.11/LICENSE-APACHE --- cargo-0.25.0/vendor/jobserver-0.1.11/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/LICENSE-MIT cargo-0.26.0/vendor/jobserver-0.1.11/LICENSE-MIT --- cargo-0.25.0/vendor/jobserver-0.1.11/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +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. diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/README.md cargo-0.26.0/vendor/jobserver-0.1.11/README.md --- cargo-0.25.0/vendor/jobserver-0.1.11/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,41 @@ +# jobserver-rs + +An implementation of the GNU make jobserver for Rust + +[![Build Status](https://travis-ci.org/alexcrichton/jobserver-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/jobserver-rs) +[![Build status](https://ci.appveyor.com/api/projects/status/h5jc30hohp7ejd9c/branch/master?svg=true)](https://ci.appveyor.com/project/alexcrichton/jobserver-rs/branch/master) +[![Crates.io](https://img.shields.io/crates/v/jobserver.svg?maxAge=2592000)](https://crates.io/crates/jobserver) + +[Documentation](https://docs.rs/jobserver) + +## Usage + +First, add this to your `Cargo.toml`: + +```toml +[dependencies] +jobserver = "0.1" +``` + +Next, add this to your crate: + +```rust +extern crate jobserver; +``` + +# License + +This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/src/lib.rs cargo-0.26.0/vendor/jobserver-0.1.11/src/lib.rs --- cargo-0.25.0/vendor/jobserver-0.1.11/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,942 @@ +//! An implementation of the GNU make jobserver. +//! +//! This crate is an implementation, in Rust, of the GNU `make` jobserver for +//! CLI tools that are interoperating with make or otherwise require some form +//! of parallelism limiting across process boundaries. This was originally +//! written for usage in Cargo to both (a) work when `cargo` is invoked from +//! `make` (using `make`'s jobserver) and (b) work when `cargo` invokes build +//! scripts, exporting a jobserver implementation for `make` processes to +//! transitively use. +//! +//! The jobserver implementation can be found in [detail online][docs] but +//! basically boils down to a cross-process semaphore. On Unix this is +//! implemented with the `pipe` syscall and read/write ends of a pipe and on +//! Windows this is implemented literally with IPC semaphores. +//! +//! The jobserver protocol in `make` also dictates when tokens are acquire to +//! run child work, and clients using this crate should take care to implement +//! such details to ensure correct interoperation with `make` itself. +//! +//! ## Examples +//! +//! Connect to a jobserver that was set up by `make` or a different process: +//! +//! ```no_run +//! use jobserver::Client; +//! +//! // See API documentation for why this is `unsafe` +//! let client = match unsafe { Client::from_env() } { +//! Some(client) => client, +//! None => panic!("client not configured"), +//! }; +//! ``` +//! +//! Acquire and release token from a jobserver: +//! +//! ```no_run +//! use jobserver::Client; +//! +//! let client = unsafe { Client::from_env().unwrap() }; +//! let token = client.acquire().unwrap(); // blocks until it is available +//! drop(token); // releases the token when the work is done +//! ``` +//! +//! Create a new jobserver and configure a child process to have access: +//! +//! ``` +//! use std::process::Command; +//! use jobserver::Client; +//! +//! let client = Client::new(4).expect("failed to create jobserver"); +//! let mut cmd = Command::new("make"); +//! client.configure(&mut cmd); +//! ``` +//! +//! ## Caveats +//! +//! This crate makes no attempt to release tokens back to a jobserver on +//! abnormal exit of a process. If a process which acquires a token is killed +//! with ctrl-c or some similar signal then tokens will not be released and the +//! jobserver may be in a corrupt state. +//! +//! Note that this is typically ok as ctrl-c means that an entire build process +//! is being torn down, but it's worth being aware of at least! +//! +//! ## Windows caveats +//! +//! There appear to be two implementations of `make` on Windows. On MSYS2 one +//! typically comes as `mingw32-make` and the other as `make` itself. I'm not +//! personally too familiar with what's going on here, but for jobserver-related +//! information the `mingw32-make` implementation uses Windows semaphores +//! whereas the `make` program does not. The `make` program appears to use file +//! descriptors and I'm not really sure how it works, so this crate is not +//! compatible with `make` on Windows. It is, however, compatible with +//! `mingw32-make`. +//! +//! [docs]: http://make.mad-scientist.net/papers/jobserver-implementation/ + +#![deny(missing_docs, missing_debug_implementations)] +#![doc(html_root_url = "https://docs.rs/jobserver/0.1")] + +#[macro_use] +extern crate log; + +use std::env; +use std::io; +use std::process::Command; +use std::sync::Arc; +use std::sync::mpsc::{self, Sender}; + +/// A client of a jobserver +/// +/// This structure is the main type exposed by this library, and is where +/// interaction to a jobserver is configured through. Clients are either created +/// from scratch in which case the internal semphore is initialied on the spot, +/// or a client is created from the environment to connect to a jobserver +/// already created. +/// +/// Some usage examples can be found in the crate documentation for using a +/// client. +/// +/// Note that a `Client` implements the `Clone` trait, and all instances of a +/// `Client` refer to the same jobserver instance. +#[derive(Clone, Debug)] +pub struct Client { + inner: Arc, +} + +/// An acquired token from a jobserver. +/// +/// This token will be released back to the jobserver when it is dropped and +/// otherwise represents the ability to spawn off another thread of work. +#[derive(Debug)] +pub struct Acquired { + client: Arc, + data: imp::Acquired, +} + +impl Client { + /// Creates a new jobserver initialized with the given parallelism limit. + /// + /// A client to the jobserver created will be returned. This client will + /// allow at most `limit` tokens to be acquired from it in parallel. More + /// calls to `acquire` will cause the calling thread to block. + /// + /// Note that the created `Client` is not automatically inherited into + /// spawned child processes from this program. Manual usage of the + /// `configure` function is required for a child process to have access to a + /// job server. + /// + /// # Examples + /// + /// ``` + /// use jobserver::Client; + /// + /// let client = Client::new(4).expect("failed to create jobserver"); + /// ``` + /// + /// # Errors + /// + /// Returns an error if any I/O error happens when attempting to create the + /// jobserver client. + pub fn new(limit: usize) -> io::Result { + Ok(Client { + inner: Arc::new(imp::Client::new(limit)?), + }) + } + + /// Attempts to connect to the jobserver specified in this process's + /// environment. + /// + /// When the a `make` executable calls a child process it will configure the + /// environment of the child to ensure that it has handles to the jobserver + /// it's passing down. This function will attempt to look for these details + /// and connect to the jobserver. + /// + /// Note that the created `Client` is not automatically inherited into + /// spawned child processes from this program. Manual usage of the + /// `configure` function is required for a child process to have access to a + /// job server. + /// + /// # Return value + /// + /// If a jobserver was found in the environment and it looks correct then + /// `Some` of the connected client will be returned. If no jobserver was + /// found then `None` will be returned. + /// + /// Note that on Unix the `Client` returned **takes ownership of the file + /// descriptors specified in the environment**. Jobservers on Unix are + /// implemented with `pipe` file descriptors, and they're inherited from + /// parent processes. This `Client` returned takes ownership of the file + /// descriptors for this process and will close the file descriptors after + /// this value is dropped. + /// + /// Additionally on Unix this function will configure the file descriptors + /// with `CLOEXEC` so they're not automatically inherited by spawned + /// children. + /// + /// # Unsafety + /// + /// This function is `unsafe` to call on Unix specifically as it + /// transitively requires usage of the `from_raw_fd` function, which is + /// itself unsafe in some circumstances. + /// + /// It's recommended to call this function very early in the lifetime of a + /// program before any other file descriptors are opened. That way you can + /// make sure to take ownership properly of the file descriptors passed + /// down, if any. + /// + /// It's generally unsafe to call this function twice in a program if the + /// previous invocation returned `Some`. + /// + /// Note, though, that on Windows it should be safe to call this function + /// any number of times. + pub unsafe fn from_env() -> Option { + let var = match env::var("CARGO_MAKEFLAGS") + .or(env::var("MAKEFLAGS")) + .or(env::var("MFLAGS")) { + Ok(s) => s, + Err(_) => return None, + }; + let mut arg = "--jobserver-fds="; + let pos = match var.find(arg) { + Some(i) => i, + None => { + arg = "--jobserver-auth="; + match var.find(arg) { + Some(i) => i, + None => return None, + } + } + }; + + let s = var[pos + arg.len()..].split(' ').next().unwrap(); + imp::Client::open(s).map(|c| { + Client { inner: Arc::new(c) } + }) + } + + /// Acquires a token from this jobserver client. + /// + /// This function will block the calling thread until a new token can be + /// acquired from the jobserver. + /// + /// # Return value + /// + /// On successful acquisition of a token an instance of `Acquired` is + /// returned. This structure, when dropped, will release the token back to + /// the jobserver. It's recommended to avoid leaking this value. + /// + /// # Errors + /// + /// If an I/O error happens while acquiring a token then this function will + /// return immediately with the error. If an error is returned then a token + /// was not acquired. + pub fn acquire(&self) -> io::Result { + let data = try!(self.inner.acquire()); + Ok(Acquired { + client: self.inner.clone(), + data: data, + }) + } + + /// Configures a child process to have access to this client's jobserver as + /// well. + /// + /// This function is required to be called to ensure that a jobserver is + /// properly inherited to a child process. If this function is *not* called + /// then this `Client` will not be accessible in the child process. In other + /// words, if not called, then `Client::from_env` will return `None` in the + /// child process (or the equivalent of `Child::from_env` that `make` uses). + /// + /// ## Platform-specific behavior + /// + /// On Unix and Windows this will clobber the `CARGO_MAKEFLAGS` environment + /// variables for the child process, and on Unix this will also allow the + /// two file descriptors for this client to be inherited to the child. + pub fn configure(&self, cmd: &mut Command) { + let arg = self.inner.string_arg(); + // Older implementations of make use `--jobserver-fds` and newer + // implementations use `--jobserver-auth`, pass both to try to catch + // both implementations. + let value = format!("--jobserver-fds={0} --jobserver-auth={0}", arg); + cmd.env("CARGO_MAKEFLAGS", &value); + self.inner.configure(cmd); + } + + /// Converts this `Client` into a helper thread to deal with a blocking + /// `acquire` function a little more easily. + /// + /// The fact that the `acquire` function on `Client` blocks isn't always + /// the easiest to work with. Typically you're using a jobserver to + /// manage running other events in parallel! This means that you need to + /// either (a) wait for an existing job to finish or (b) wait for a + /// new token to become available. + /// + /// Unfortunately the blocking in `acquire` happens at the implementation + /// layer of jobservers. On Unix this requires a blocking call to `read` + /// and on Windows this requires one of the `WaitFor*` functions. Both + /// of these situations aren't the easiest to deal with: + /// + /// * On Unix there's basically only one way to wake up a `read` early, and + /// that's through a signal. This is what the `make` implementation + /// itself uses, relying on `SIGCHLD` to wake up a blocking acquisition + /// of a new job token. Unfortunately nonblocking I/O is not an option + /// here, so it means that "waiting for one of two events" means that + /// the latter event must generate a signal! This is not always the case + /// on unix for all jobservers. + /// + /// * On Windows you'd have to basically use the `WaitForMultipleObjects` + /// which means that you've got to canonicalize all your event sources + /// into a `HANDLE` which also isn't the easiest thing to do + /// unfortunately. + /// + /// This function essentially attempts to ease these limitations by + /// converting this `Client` into a helper thread spawned into this + /// process. The application can then request that the helper thread + /// acquires tokens and the provided closure will be invoked for each token + /// acquired. + /// + /// The intention is that this function can be used to translate the event + /// of a token acquisition into an arbitrary user-defined event. + /// + /// # Arguments + /// + /// This function will consume the `Client` provided to be transferred to + /// the helper thread that is spawned. Additionally a closure `f` is + /// provided to be invoked whenever a token is acquired. + /// + /// This closure is only invoked after calls to + /// `HelperThread::request_token` have been made and a token itself has + /// been acquired. If an error happens while acquiring the token then + /// an error will be yielded to the closure as well. + /// + /// # Return Value + /// + /// This function will return an instance of the `HelperThread` structure + /// which is used to manage the helper thread associated with this client. + /// Through the `HelperThread` you'll request that tokens are acquired. + /// When acquired, the closure provided here is invoked. + /// + /// When the `HelperThread` structure is returned it will be gracefully + /// torn down, and the calling thread will be blocked until the thread is + /// torn down (which should be prompt). + /// + /// # Errors + /// + /// This function may fail due to creation of the helper thread or + /// auxiliary I/O objects to manage the helper thread. In any of these + /// situations the error is propagated upwards. + /// + /// # Platform-specific behavior + /// + /// On Windows this function behaves pretty normally as expected, but on + /// Unix the implementation is... a little heinous. As mentioned above + /// we're forced into blocking I/O for token acquisition, namely a blocking + /// call to `read`. We must be able to unblock this, however, to tear down + /// the helper thread gracefully! + /// + /// Essentially what happens is that we'll send a signal to the helper + /// thread spawned and rely on `EINTR` being returned to wake up the helper + /// thread. This involves installing a global `SIGUSR1` handler that does + /// nothing along with sending signals to that thread. This may cause + /// odd behavior in some applications, so it's recommended to review and + /// test thoroughly before using this. + pub fn into_helper_thread(self, f: F) -> io::Result + where F: FnMut(io::Result) + Send + 'static, + { + let (tx, rx) = mpsc::channel(); + Ok(HelperThread { + inner: Some(imp::spawn_helper(self, rx, Box::new(f))?), + tx: Some(tx), + }) + } +} + +impl Drop for Acquired { + fn drop(&mut self) { + drop(self.client.release(&self.data)); + } +} + +/// Structure returned from `Client::into_helper_thread` to manage the lifetime +/// of the helper thread returned, see those associated docs for more info. +#[derive(Debug)] +pub struct HelperThread { + inner: Option, + tx: Option>, +} + +impl HelperThread { + /// Request that the helper thread acquires a token, eventually calling the + /// original closure with a token when it's available. + /// + /// For more information, see the docs on that function. + pub fn request_token(&self) { + self.tx.as_ref().unwrap().send(()).unwrap(); + } +} + +impl Drop for HelperThread { + fn drop(&mut self) { + drop(self.tx.take()); + self.inner.take().unwrap().join(); + } +} + +#[cfg(unix)] +mod imp { + extern crate libc; + + use std::fs::File; + use std::io::{self, Read, Write}; + use std::mem; + use std::os::unix::prelude::*; + use std::process::Command; + use std::ptr; + use std::sync::atomic::{AtomicBool, AtomicUsize, + ATOMIC_BOOL_INIT, ATOMIC_USIZE_INIT, + Ordering}; + use std::sync::mpsc::{self, Receiver, RecvTimeoutError}; + use std::sync::{Arc, Once, ONCE_INIT}; + use std::thread::{self, JoinHandle, Builder}; + use std::time::Duration; + + use self::libc::c_int; + + #[derive(Debug)] + pub struct Client { + read: File, + write: File, + } + + #[derive(Debug)] + pub struct Acquired { + byte: u8, + } + + impl Client { + pub fn new(limit: usize) -> io::Result { + let client = unsafe { Client::mk()? }; + // I don't think the character written here matters, but I could be + // wrong! + for _ in 0..limit { + (&client.write).write(&[b'|'])?; + } + info!("created a jobserver: {:?}", client); + Ok(client) + } + + unsafe fn mk() -> io::Result { + static INVALID: AtomicBool = ATOMIC_BOOL_INIT; + let mut pipes = [0; 2]; + + // Attempt atomically-create-with-cloexec if we can. Note that even + // when libc has the symbol, `pipe2` might still not be supported on + // the running kernel -> `ENOSYS`, then we need to use the fallback. + if cfg!(target_os = "linux") && !INVALID.load(Ordering::SeqCst) { + if let Some(pipe2) = pipe2() { + match cvt(pipe2(pipes.as_mut_ptr(), libc::O_CLOEXEC)) { + Ok(_) => return Ok(Client::from_fds(pipes[0], pipes[1])), + Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => { + INVALID.store(true, Ordering::SeqCst); + } + Err(e) => return Err(e), + } + } + } + + cvt(libc::pipe(pipes.as_mut_ptr()))?; + drop(set_cloexec(pipes[0], true)); + drop(set_cloexec(pipes[1], true)); + Ok(Client::from_fds(pipes[0], pipes[1])) + } + + pub unsafe fn open(s: &str) -> Option { + let mut parts = s.splitn(2, ','); + let read = parts.next().unwrap(); + let write = match parts.next() { + Some(s) => s, + None => return None, + }; + + let read = match read.parse() { + Ok(n) => n, + Err(_) => return None, + }; + let write = match write.parse() { + Ok(n) => n, + Err(_) => return None, + }; + + // Ok so we've got two integers that look like file descriptors, but + // for extra sanity checking let's see if they actually look like + // instances of a pipe before we return the client. + // + // If we're called from `make` *without* the leading + on our rule + // then we'll have `MAKEFLAGS` env vars but won't actually have + // access to the file descriptors. + if is_valid_fd(read) && is_valid_fd(write) { + info!("using env fds {} and {}", read, write); + drop(set_cloexec(read, true)); + drop(set_cloexec(write, true)); + Some(Client::from_fds(read, write)) + } else { + info!("one of {} or {} isn't a pipe", read, write); + None + } + } + + unsafe fn from_fds(read: c_int, write: c_int) -> Client { + Client { + read: File::from_raw_fd(read), + write: File::from_raw_fd(write), + } + } + + pub fn acquire(&self) -> io::Result { + // We don't actually know if the file descriptor here is set in + // blocking or nonblocking mode. AFAIK all released versions of + // `make` use blocking fds for the jobserver, but the unreleased + // version of `make` doesn't. In the unreleased version jobserver + // fds are set to nonblocking and combined with `pselect` + // internally. + // + // Here we try to be compatible with both strategies. We + // unconditionally expect the file descriptor to be in nonblocking + // mode and if it happens to be in blocking mode then most of this + // won't end up actually being necessary! + // + // We use `poll` here to block this thread waiting for read + // readiness, and then afterwards we perform the `read` itself. If + // the `read` returns that it would block then we start over and try + // again. + // + // Also note that we explicitly don't handle EINTR here. That's used + // to shut us down, so we otherwise punt all errors upwards. + unsafe { + let mut fd: libc::pollfd = mem::zeroed(); + fd.fd = self.read.as_raw_fd(); + fd.events = libc::POLLIN; + loop { + fd.revents = 0; + if libc::poll(&mut fd, 1, -1) == -1 { + return Err(io::Error::last_os_error()) + } + if fd.revents == 0 { + continue + } + let mut buf = [0]; + match (&self.read).read(&mut buf) { + Ok(1) => return Ok(Acquired { byte: buf[0] }), + Ok(_) => { + return Err(io::Error::new(io::ErrorKind::Other, + "early EOF on jobserver pipe")) + } + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {} + Err(e) => return Err(e), + } + } + } + } + + pub fn release(&self, data: &Acquired) -> io::Result<()> { + // Note that the fd may be nonblocking but we're going to go ahead + // and assume that the writes here are always nonblocking (we can + // always quickly release a token). If that turns out to not be the + // case we'll get an error anyway! + match (&self.write).write(&[data.byte])? { + 1 => Ok(()), + _ => Err(io::Error::new(io::ErrorKind::Other, + "failed to write token back to jobserver")), + } + } + + pub fn string_arg(&self) -> String { + format!("{},{} -j", self.read.as_raw_fd(), self.write.as_raw_fd()) + } + + pub fn configure(&self, cmd: &mut Command) { + // Here we basically just want to say that in the child process + // we'll configure the read/write file descriptors to *not* be + // cloexec, so they're inherited across the exec and specified as + // integers through `string_arg` above. + let read = self.read.as_raw_fd(); + let write = self.write.as_raw_fd(); + cmd.before_exec(move || { + set_cloexec(read, false)?; + set_cloexec(write, false)?; + Ok(()) + }); + } + } + + #[derive(Debug)] + pub struct Helper { + thread: JoinHandle<()>, + quitting: Arc, + rx_done: Receiver<()>, + } + + pub fn spawn_helper(client: ::Client, + rx: Receiver<()>, + mut f: Box) + Send>) + -> io::Result + { + static USR1_INIT: Once = ONCE_INIT; + let mut err = None; + USR1_INIT.call_once(|| unsafe { + let mut new: libc::sigaction = mem::zeroed(); + new.sa_sigaction = sigusr1_handler as usize; + new.sa_flags = libc::SA_SIGINFO as _; + if libc::sigaction(libc::SIGUSR1, &new, ptr::null_mut()) != 0 { + err = Some(io::Error::last_os_error()); + } + }); + + if let Some(e) = err.take() { + return Err(e) + } + + let quitting = Arc::new(AtomicBool::new(false)); + let quitting2 = quitting.clone(); + let (tx_done, rx_done) = mpsc::channel(); + let thread = Builder::new().spawn(move || { + 'outer: + for () in rx { + loop { + let res = client.acquire(); + if let Err(ref e) = res { + if e.kind() == io::ErrorKind::Interrupted { + if quitting2.load(Ordering::SeqCst) { + break 'outer + } else { + continue + } + } + } + f(res); + break + } + } + tx_done.send(()).unwrap(); + })?; + + Ok(Helper { + thread: thread, + quitting: quitting, + rx_done: rx_done, + }) + } + + impl Helper { + pub fn join(self) { + self.quitting.store(true, Ordering::SeqCst); + let dur = Duration::from_millis(10); + let mut done = false; + for _ in 0..100 { + unsafe { + // Ignore the return value here of `pthread_kill`, + // apparently on OSX if you kill a dead thread it will + // return an error, but on other platforms it may not. In + // that sense we don't actually know if this will succeed or + // not! + libc::pthread_kill(self.thread.as_pthread_t(), libc::SIGUSR1); + match self.rx_done.recv_timeout(dur) { + Ok(()) | + Err(RecvTimeoutError::Disconnected) => { + done = true; + break + } + Err(RecvTimeoutError::Timeout) => {} + } + } + thread::yield_now(); + } + if done { + drop(self.thread.join()); + } + } + } + + fn is_valid_fd(fd: c_int) -> bool { + unsafe { + return libc::fcntl(fd, libc::F_GETFD) != -1; + } + } + + fn set_cloexec(fd: c_int, set: bool) -> io::Result<()> { + unsafe { + let previous = cvt(libc::fcntl(fd, libc::F_GETFD))?; + let new = if set { + previous | libc::FD_CLOEXEC + } else { + previous & !libc::FD_CLOEXEC + }; + if new != previous { + cvt(libc::fcntl(fd, libc::F_SETFD, new))?; + } + Ok(()) + } + } + + fn cvt(t: c_int) -> io::Result { + if t == -1 { + Err(io::Error::last_os_error()) + } else { + Ok(t) + } + } + + unsafe fn pipe2() -> Option<&'static fn(*mut c_int, c_int) -> c_int> { + static PIPE2: AtomicUsize = ATOMIC_USIZE_INIT; + + if PIPE2.load(Ordering::SeqCst) == 0 { + let name = "pipe2\0"; + let n = match libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _) as usize { + 0 => 1, + n => n, + }; + PIPE2.store(n, Ordering::SeqCst); + } + if PIPE2.load(Ordering::SeqCst) == 1 { + None + } else { + mem::transmute(&PIPE2) + } + } + + extern fn sigusr1_handler(_signum: c_int, + _info: *mut libc::siginfo_t, + _ptr: *mut libc::c_void) { + // nothing to do + } +} + +#[cfg(windows)] +mod imp { + extern crate rand; + + use std::ffi::CString; + use std::io; + use std::process::Command; + use std::ptr; + use std::sync::Arc; + use std::sync::mpsc::Receiver; + use std::thread::{Builder, JoinHandle}; + + #[derive(Debug)] + pub struct Client { + sem: Handle, + name: String, + } + + #[derive(Debug)] + pub struct Acquired; + + type BOOL = i32; + type DWORD = u32; + type HANDLE = *mut u8; + type LONG = i32; + + const ERROR_ALREADY_EXISTS: DWORD = 183; + const FALSE: BOOL = 0; + const INFINITE: DWORD = 0xffffffff; + const SEMAPHORE_MODIFY_STATE: DWORD = 0x2; + const SYNCHRONIZE: DWORD = 0x00100000; + const TRUE: BOOL = 1; + const WAIT_OBJECT_0: DWORD = 0; + + extern "system" { + fn CloseHandle(handle: HANDLE) -> BOOL; + fn SetEvent(hEvent: HANDLE) -> BOOL; + fn WaitForMultipleObjects(ncount: DWORD, + lpHandles: *const HANDLE, + bWaitAll: BOOL, + dwMilliseconds: DWORD) -> DWORD; + fn CreateEventA(lpEventAttributes: *mut u8, + bManualReset: BOOL, + bInitialState: BOOL, + lpName: *const i8) -> HANDLE; + fn ReleaseSemaphore(hSemaphore: HANDLE, + lReleaseCount: LONG, + lpPreviousCount: *mut LONG) -> BOOL; + fn CreateSemaphoreA(lpEventAttributes: *mut u8, + lInitialCount: LONG, + lMaximumCount: LONG, + lpName: *const i8) -> HANDLE; + fn OpenSemaphoreA(dwDesiredAccess: DWORD, + bInheritHandle: BOOL, + lpName: *const i8) -> HANDLE; + fn WaitForSingleObject(hHandle: HANDLE, + dwMilliseconds: DWORD) -> DWORD; + } + + impl Client { + pub fn new(limit: usize) -> io::Result { + // Try a bunch of random semaphore names until we get a unique one, + // but don't try for too long. + // + // Note that `limit == 0` is a valid argument above but Windows + // won't let us create a semaphore with 0 slots available to it. Get + // `limit == 0` working by creating a semaphore instead with one + // slot and then immediately acquire it (without ever releaseing it + // back). + for _ in 0..100 { + let mut name = format!("__rust_jobserver_semaphore_{}\0", + rand::random::()); + unsafe { + let create_limit = if limit == 0 {1} else {limit}; + let r = CreateSemaphoreA(ptr::null_mut(), + create_limit as LONG, + create_limit as LONG, + name.as_ptr() as *const _); + if r.is_null() { + return Err(io::Error::last_os_error()) + } + let handle = Handle(r); + + let err = io::Error::last_os_error(); + if err.raw_os_error() == Some(ERROR_ALREADY_EXISTS as i32) { + continue + } + name.pop(); // chop off the trailing nul + let client = Client { + sem: handle, + name: name, + }; + if create_limit != limit { + client.acquire()?; + } + info!("created jobserver {:?}", client); + return Ok(client) + } + } + + Err(io::Error::new(io::ErrorKind::Other, + "failed to find a unique name for a semaphore")) + } + + pub unsafe fn open(s: &str) -> Option { + let name = match CString::new(s) { + Ok(s) => s, + Err(_) => return None, + }; + + let sem = OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, + FALSE, + name.as_ptr()); + if sem.is_null() { + info!("failed to open environment semaphore {}", s); + None + } else { + info!("opened environment semaphore {}", s); + Some(Client { + sem: Handle(sem), + name: s.to_string(), + }) + } + } + + pub fn acquire(&self) -> io::Result { + unsafe { + let r = WaitForSingleObject(self.sem.0, INFINITE); + if r == WAIT_OBJECT_0 { + Ok(Acquired) + } else { + Err(io::Error::last_os_error()) + } + } + } + + pub fn release(&self, _data: &Acquired) -> io::Result<()> { + unsafe { + let r = ReleaseSemaphore(self.sem.0, 1, ptr::null_mut()); + if r != 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + } + + pub fn string_arg(&self) -> String { + self.name.clone() + } + + pub fn configure(&self, _cmd: &mut Command) { + // nothing to do here, we gave the name of our semaphore to the + // child above + } + } + + #[derive(Debug)] + struct Handle(HANDLE); + // HANDLE is a raw ptr, but we're send/sync + unsafe impl Sync for Handle {} + unsafe impl Send for Handle {} + + impl Drop for Handle { + fn drop(&mut self) { + unsafe { + CloseHandle(self.0); + } + } + } + + #[derive(Debug)] + pub struct Helper { + event: Arc, + thread: JoinHandle<()>, + } + + pub fn spawn_helper(client: ::Client, + rx: Receiver<()>, + mut f: Box) + Send>) + -> io::Result + { + let event = unsafe { + let r = CreateEventA(ptr::null_mut(), TRUE, FALSE, ptr::null()); + if r.is_null() { + return Err(io::Error::last_os_error()) + } else { + Handle(r) + } + }; + let event = Arc::new(event); + let event2 = event.clone(); + let thread = Builder::new().spawn(move || { + let objects = [event2.0, client.inner.sem.0]; + for () in rx { + let r = unsafe { + WaitForMultipleObjects(2, objects.as_ptr(), FALSE, INFINITE) + }; + if r == WAIT_OBJECT_0 { + break + } + if r == WAIT_OBJECT_0 + 1 { + f(Ok(::Acquired { + client: client.inner.clone(), + data: Acquired, + })) + } else { + f(Err(io::Error::last_os_error())) + } + } + })?; + Ok(Helper { + thread: thread, + event: event, + }) + } + + impl Helper { + pub fn join(self) { + let r = unsafe { SetEvent(self.event.0) }; + if r == 0 { + panic!("failed to set event: {}", io::Error::last_os_error()); + } + drop(self.thread.join()); + } + } +} diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/tests/client-of-myself.rs cargo-0.26.0/vendor/jobserver-0.1.11/tests/client-of-myself.rs --- cargo-0.25.0/vendor/jobserver-0.1.11/tests/client-of-myself.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/tests/client-of-myself.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,60 @@ +extern crate jobserver; + +use std::env; +use std::io::BufReader; +use std::io::prelude::*; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use std::thread; + +use jobserver::Client; + +macro_rules! t { + ($e:expr) => (match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {}", stringify!($e), e), + }) +} + +fn main() { + if env::var("I_AM_THE_CLIENT").is_ok() { + client(); + } else { + server(); + } +} + +fn server() { + let me = t!(env::current_exe()); + let client = t!(Client::new(1)); + let mut cmd = Command::new(me); + cmd.env("I_AM_THE_CLIENT", "1") + .stdout(Stdio::piped()); + client.configure(&mut cmd); + let acq = client.acquire().unwrap(); + let mut child = t!(cmd.spawn()); + let stdout = child.stdout.take().unwrap(); + let (tx, rx) = mpsc::channel(); + let t = thread::spawn(move || { + for line in BufReader::new(stdout).lines() { + tx.send(t!(line)).unwrap(); + } + }); + + for _ in 0..100 { + assert!(rx.try_recv().is_err()); + } + + drop(acq); + assert_eq!(rx.recv().unwrap(), "hello!"); + t.join().unwrap(); + assert!(rx.recv().is_err()); + client.acquire().unwrap(); +} + +fn client() { + let client = unsafe { Client::from_env().unwrap() }; + let acq = client.acquire().unwrap(); + println!("hello!"); + drop(acq); +} diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/tests/client.rs cargo-0.26.0/vendor/jobserver-0.1.11/tests/client.rs --- cargo-0.25.0/vendor/jobserver-0.1.11/tests/client.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/tests/client.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,191 @@ +extern crate futures; +extern crate jobserver; +extern crate num_cpus; +extern crate tempdir; +extern crate tokio_core; +extern crate tokio_process; + +use std::env; +use std::fs::File; +use std::io::Write; +use std::process::Command; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::thread; + +use futures::future::{self, Future}; +use futures::stream::{self, Stream}; +use jobserver::Client; +use tempdir::TempDir; +use tokio_core::reactor::Core; +use tokio_process::CommandExt; + +macro_rules! t { + ($e:expr) => (match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {}", stringify!($e), e), + }) +} + +struct Test { + name: &'static str, + f: &'static Fn(), + make_args: &'static [&'static str], + rule: &'static Fn(&str) -> String, +} + +const TESTS: &[Test] = &[ + Test { + name: "no j args", + make_args: &[], + rule: &|me| format!("{}", me), + f: &|| { + assert!(unsafe { Client::from_env().is_none() }); + }, + }, + Test { + name: "no j args with plus", + make_args: &[], + rule: &|me| format!("+{}", me), + f: &|| { + assert!(unsafe { Client::from_env().is_none() }); + }, + }, + Test { + name: "j args with plus", + make_args: &["-j2"], + rule: &|me| format!("+{}", me), + f: &|| { + assert!(unsafe { Client::from_env().is_some() }); + }, + }, + Test { + name: "acquire", + make_args: &["-j2"], + rule: &|me| format!("+{}", me), + f: &|| { + let c = unsafe { Client::from_env().unwrap() }; + drop(c.acquire().unwrap()); + drop(c.acquire().unwrap()); + }, + }, + Test { + name: "acquire3", + make_args: &["-j3"], + rule: &|me| format!("+{}", me), + f: &|| { + let c = unsafe { Client::from_env().unwrap() }; + let a = c.acquire().unwrap(); + let b = c.acquire().unwrap(); + drop((a, b)); + }, + }, + Test { + name: "acquire blocks", + make_args: &["-j2"], + rule: &|me| format!("+{}", me), + f: &|| { + let c = unsafe { Client::from_env().unwrap() }; + let a = c.acquire().unwrap(); + let hit = Arc::new(AtomicBool::new(false)); + let hit2 = hit.clone(); + let (tx, rx) = mpsc::channel(); + let t = thread::spawn(move || { + tx.send(()).unwrap(); + let _b = c.acquire().unwrap(); + hit2.store(true, Ordering::SeqCst); + }); + rx.recv().unwrap(); + assert!(!hit.load(Ordering::SeqCst)); + drop(a); + t.join().unwrap(); + assert!(hit.load(Ordering::SeqCst)); + }, + }, +]; + +fn main() { + if let Ok(test) = env::var("TEST_TO_RUN") { + return (TESTS.iter().find(|t| t.name == test).unwrap().f)() + } + + let me = t!(env::current_exe()); + let me = me.to_str().unwrap(); + let filter = env::args().skip(1).next(); + + let mut core = t!(Core::new()); + let ref handle = core.handle(); + + let futures = TESTS.iter().filter(|test| { + match filter { + Some(ref s) => test.name.contains(s), + None => true, + } + }).map(|test| { + let td = t!(TempDir::new("foo")); + let makefile = format!("\ +all: export TEST_TO_RUN={} +all: +\t{} +", test.name, (test.rule)(me)); + t!(t!(File::create(td.path().join("Makefile"))) + .write_all(makefile.as_bytes())); + let prog = env::var("MAKE").unwrap_or("make".to_string()); + let mut cmd = Command::new(prog); + cmd.args(test.make_args); + cmd.current_dir(td.path()); + future::lazy(move || { + cmd.output_async(&handle).map(move |e| { + drop(td); + (test, e) + }) + }) + }).collect::>(); + + println!("\nrunning {} tests\n", futures.len()); + + let stream = stream::iter(futures.into_iter().map(Ok)) + .buffer_unordered(num_cpus::get()); + + let mut failures = Vec::new(); + t!(core.run(stream.for_each(|(test, output)| { + if output.status.success() { + println!("test {} ... ok", test.name); + } else { + println!("test {} ... FAIL", test.name); + failures.push((test, output)); + } + Ok(()) + }))); + + if failures.len() == 0 { + println!("\ntest result: ok\n"); + return + } + + println!("\n----------- failures"); + + for (test, output) in failures { + println!("test {}", test.name); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + + println!("\texit status: {}", output.status); + if !stdout.is_empty() { + println!("\tstdout ==="); + for line in stdout.lines() { + println!("\t\t{}", line); + } + } + + if !stderr.is_empty() { + println!("\tstderr ==="); + for line in stderr.lines() { + println!("\t\t{}", line); + } + } + } + + std::process::exit(4); +} diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/tests/helper.rs cargo-0.26.0/vendor/jobserver-0.1.11/tests/helper.rs --- cargo-0.25.0/vendor/jobserver-0.1.11/tests/helper.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/tests/helper.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,44 @@ +extern crate jobserver; + +use std::sync::mpsc; + +use jobserver::Client; + +macro_rules! t { + ($e:expr) => (match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {}", stringify!($e), e), + }) +} + +#[test] +fn helper_smoke() { + let client = t!(Client::new(1)); + drop(client.clone().into_helper_thread(|_| ()).unwrap()); + drop(client.clone().into_helper_thread(|_| ()).unwrap()); + drop(client.clone().into_helper_thread(|_| ()).unwrap()); + drop(client.clone().into_helper_thread(|_| ()).unwrap()); + drop(client.clone().into_helper_thread(|_| ()).unwrap()); + drop(client.clone().into_helper_thread(|_| ()).unwrap()); +} + +#[test] +fn acquire() { + let (tx, rx) = mpsc::channel(); + let client = t!(Client::new(1)); + let helper = client.into_helper_thread(move |a| drop(tx.send(a))).unwrap(); + assert!(rx.try_recv().is_err()); + helper.request_token(); + rx.recv().unwrap().unwrap(); + helper.request_token(); + rx.recv().unwrap().unwrap(); + + helper.request_token(); + helper.request_token(); + rx.recv().unwrap().unwrap(); + rx.recv().unwrap().unwrap(); + + helper.request_token(); + helper.request_token(); + drop(helper); +} diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/tests/make-as-a-client.rs cargo-0.26.0/vendor/jobserver-0.1.11/tests/make-as-a-client.rs --- cargo-0.25.0/vendor/jobserver-0.1.11/tests/make-as-a-client.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/tests/make-as-a-client.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,77 @@ +extern crate jobserver; +extern crate tempdir; + +use std::env; +use std::fs::File; +use std::io::prelude::*; +use std::net::{TcpStream, TcpListener}; +use std::process::Command; + +use jobserver::Client; +use tempdir::TempDir; + +macro_rules! t { + ($e:expr) => (match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {}", stringify!($e), e), + }) +} + +fn main() { + if env::var("_DO_THE_TEST").is_ok() { + std::process::exit( + Command::new(env::var_os("MAKE").unwrap()) + .env("MAKEFLAGS", env::var_os("CARGO_MAKEFLAGS").unwrap()) + .env_remove("_DO_THE_TEST") + .args(&env::args_os().skip(1).collect::>()) + .status() + .unwrap() + .code() + .unwrap_or(1) + ); + } + + if let Ok(s) = env::var("TEST_ADDR") { + let mut contents = Vec::new(); + t!(t!(TcpStream::connect(&s)).read_to_end(&mut contents)); + return + } + + let c = t!(Client::new(1)); + let td = TempDir::new("foo").unwrap(); + + let prog = env::var("MAKE").unwrap_or("make".to_string()); + + let me = t!(env::current_exe()); + let me = me.to_str().unwrap(); + + let mut cmd = Command::new(&me); + cmd.current_dir(td.path()); + cmd.env("MAKE", prog); + cmd.env("_DO_THE_TEST", "1"); + + t!(t!(File::create(td.path().join("Makefile"))).write_all(format!("\ +all: foo bar +foo: +\t{0} +bar: +\t{0} +", me).as_bytes())); + + // We're leaking one extra token to `make` sort of violating the makefile + // jobserver protocol. It has the desired effect though. + c.configure(&mut cmd); + + let listener = t!(TcpListener::bind("127.0.0.1:0")); + let addr = t!(listener.local_addr()); + cmd.env("TEST_ADDR", addr.to_string()); + let mut child = t!(cmd.spawn()); + + // We should get both connections as the two programs should be run + // concurrently. + let a = t!(listener.accept()); + let b = t!(listener.accept()); + drop((a, b)); + + assert!(t!(child.wait()).success()); +} diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/tests/server.rs cargo-0.26.0/vendor/jobserver-0.1.11/tests/server.rs --- cargo-0.25.0/vendor/jobserver-0.1.11/tests/server.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/tests/server.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,145 @@ +extern crate jobserver; +extern crate tempdir; + +use std::env; +use std::fs::File; +use std::io::prelude::*; +use std::process::Command; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::thread; + +use jobserver::Client; +use tempdir::TempDir; + +macro_rules! t { + ($e:expr) => (match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {}", stringify!($e), e), + }) +} + +#[test] +fn server_smoke() { + let c = t!(Client::new(1)); + drop(c.acquire().unwrap()); + drop(c.acquire().unwrap()); +} + +#[test] +fn server_multiple() { + let c = t!(Client::new(2)); + let a = c.acquire().unwrap(); + let b = c.acquire().unwrap(); + drop((a, b)); +} + +#[test] +fn server_blocks() { + let c = t!(Client::new(1)); + let a = c.acquire().unwrap(); + let hit = Arc::new(AtomicBool::new(false)); + let hit2 = hit.clone(); + let (tx, rx) = mpsc::channel(); + let t = thread::spawn(move || { + tx.send(()).unwrap(); + let _b = c.acquire().unwrap(); + hit2.store(true, Ordering::SeqCst); + }); + rx.recv().unwrap(); + assert!(!hit.load(Ordering::SeqCst)); + drop(a); + t.join().unwrap(); + assert!(hit.load(Ordering::SeqCst)); +} + +#[test] +fn make_as_a_single_thread_client() { + let c = t!(Client::new(1)); + let td = TempDir::new("foo").unwrap(); + + let prog = env::var("MAKE").unwrap_or("make".to_string()); + let mut cmd = Command::new(prog); + cmd.current_dir(td.path()); + + t!(t!(File::create(td.path().join("Makefile"))).write_all(b" +all: foo bar +foo: +\techo foo +bar: +\techo bar +")); + + // The jobserver protocol means that the `make` process itself "runs with a + // token", so we acquire our one token to drain the jobserver, and this + // should mean that `make` itself never has a second token available to it. + let _a = c.acquire(); + c.configure(&mut cmd); + let output = t!(cmd.output()); + println!("\n\t=== stderr\n\t\t{}", + String::from_utf8_lossy(&output.stderr).replace("\n", "\n\t\t")); + println!("\t=== stdout\n\t\t{}", + String::from_utf8_lossy(&output.stdout).replace("\n", "\n\t\t")); + + assert!(output.status.success()); + assert!(output.stderr.is_empty()); + + let stdout = String::from_utf8_lossy(&output.stdout).replace("\r\n", "\n"); + let a = "\ +echo foo +foo +echo bar +bar +"; + let b = "\ +echo bar +bar +echo foo +foo +"; + + assert!(stdout == a || stdout == b); +} + +#[test] +fn make_as_a_multi_thread_client() { + let c = t!(Client::new(1)); + let td = TempDir::new("foo").unwrap(); + + let prog = env::var("MAKE").unwrap_or("make".to_string()); + let mut cmd = Command::new(prog); + cmd.current_dir(td.path()); + + t!(t!(File::create(td.path().join("Makefile"))).write_all(b" +all: foo bar +foo: +\techo foo +bar: +\techo bar +")); + + // We're leaking one extra token to `make` sort of violating the makefile + // jobserver protocol. It has the desired effect though. + c.configure(&mut cmd); + let output = t!(cmd.output()); + println!("\n\t=== stderr\n\t\t{}", + String::from_utf8_lossy(&output.stderr).replace("\n", "\n\t\t")); + println!("\t=== stdout\n\t\t{}", + String::from_utf8_lossy(&output.stdout).replace("\n", "\n\t\t")); + + assert!(output.status.success()); +} + +#[test] +fn zero_client() { + let client = t!(Client::new(0)); + let (tx, rx) = mpsc::channel(); + let helper = client.into_helper_thread(move |a| drop(tx.send(a))).unwrap(); + helper.request_token(); + helper.request_token(); + + for _ in 0..1000 { + assert!(rx.try_recv().is_err()); + } +} diff -Nru cargo-0.25.0/vendor/jobserver-0.1.11/.travis.yml cargo-0.26.0/vendor/jobserver-0.1.11/.travis.yml --- cargo-0.25.0/vendor/jobserver-0.1.11/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.11/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +language: rust +rust: stable + +matrix: + include: + - os: osx + - rust: stable + - rust: beta + - rust: nightly + before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH + after_success: + - travis-cargo doc-upload + +sudo: false +script: + - cargo test + - cargo doc --no-deps +env: + global: + secure: "u4sfTRgvuqtiwil/a5RMjNFKdUJl0fr8MM73c934I4nDuIPQ+v1ZIj/ehclHXED+vT3M5h0Ois+HWBn/626vVZCuCUBqeC96qB7K+tqJlzpxGgukF9Ps2q7nh14NBxsTQ3HBJbrxdi6qaozAaa3BLPh6pLCBBgfofsbaeikV6ogosI0ZeYDwwEA7dc7yVKWwuMDFnxeqEqkdC9SLc4dsSuFAYWs3w00EU6sukG7ISv1e5fluZtJgNxbMe5RUCa2/lsDtmrWpkHSagcfhbWqb5LZ0ZZE+v6/Z9ASlHEOt462p4ZnkTgVgRw9/QcV75KN/tHI4hrXOU55VkEBzZqlc1Fyr+xeIpghNel8HEnLpde8B+XbCxCzGORPntCjVjfIn++wxK7ce30hslBsT75UJPrTnsBPr5rPahX8i0K6R8Xc2i7qMd5p2NTDs51MWpnjNgAGFj/1WS7t638i+gkia9ficfNRXDlMCNDC8F24r5huB6G4EKWYyCLYdMZHNaKO1XCVMTeRh2EQpLILkT8BFVZN1ttGUZ1BhMsZ1U4pCgta7phRZkBiov7uomPHMUX+fn0rmh58Z2Rodbvdzdx4fVRCebBgqxh25We2ByWRyAHfEF0Cw91A8bs1u1ssdta8UXqrb9d6oKDPCDIO/v+mzd6KXN2d5bTExo0aLs8qMC3Q=" + +notifications: + email: + on_success: never diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/.appveyor.yml cargo-0.26.0/vendor/jobserver-0.1.9/.appveyor.yml --- cargo-0.25.0/vendor/jobserver-0.1.9/.appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/.appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -environment: - matrix: - - TARGET: x86_64-pc-windows-msvc - MAKE: mingw32-make - -install: - # Install rust, x86_64-pc-windows-msvc host - - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe - - rustup-init.exe -y --default-host x86_64-pc-windows-msvc --default-toolchain nightly - - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - - set PATH=C:\msys64\mingw64\bin;C:\msys64\usr\bin;%PATH% - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/.cargo-checksum.json cargo-0.26.0/vendor/jobserver-0.1.9/.cargo-checksum.json --- cargo-0.25.0/vendor/jobserver-0.1.9/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"565f6106bd87b394398f813bea4e5ecad6d6b0f6aa077592d088f882a506481d"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/Cargo.toml cargo-0.26.0/vendor/jobserver-0.1.9/Cargo.toml --- cargo-0.25.0/vendor/jobserver-0.1.9/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "jobserver" -version = "0.1.9" -authors = ["Alex Crichton "] -description = "An implementation of the GNU make jobserver for Rust\n" -homepage = "https://github.com/alexcrichton/jobserver-rs" -documentation = "https://docs.rs/jobserver" -license = "MIT/Apache-2.0" -repository = "https://github.com/alexcrichton/jobserver-rs" - -[[test]] -name = "client" -path = "tests/client.rs" -harness = false - -[[test]] -name = "server" -path = "tests/server.rs" - -[[test]] -name = "client-of-myself" -path = "tests/client-of-myself.rs" -harness = false - -[[test]] -name = "make-as-a-client" -path = "tests/make-as-a-client.rs" -harness = false - -[[test]] -name = "helper" -path = "tests/helper.rs" -[dev-dependencies.futures] -version = "0.1" - -[dev-dependencies.num_cpus] -version = "1.0" - -[dev-dependencies.tempdir] -version = "0.3" - -[dev-dependencies.tokio-core] -version = "0.1" - -[dev-dependencies.tokio-process] -version = "0.1" -[target."cfg(unix)".dependencies.libc] -version = "0.2" -[target."cfg(windows)".dependencies.rand] -version = "0.3" diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/LICENSE-APACHE cargo-0.26.0/vendor/jobserver-0.1.9/LICENSE-APACHE --- cargo-0.25.0/vendor/jobserver-0.1.9/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/LICENSE-MIT cargo-0.26.0/vendor/jobserver-0.1.9/LICENSE-MIT --- cargo-0.25.0/vendor/jobserver-0.1.9/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 Alex Crichton - -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. diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/README.md cargo-0.26.0/vendor/jobserver-0.1.9/README.md --- cargo-0.25.0/vendor/jobserver-0.1.9/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -# jobserver-rs - -An implementation of the GNU make jobserver for Rust - -[![Build Status](https://travis-ci.org/alexcrichton/jobserver-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/jobserver-rs) -[![Build status](https://ci.appveyor.com/api/projects/status/h5jc30hohp7ejd9c/branch/master?svg=true)](https://ci.appveyor.com/project/alexcrichton/jobserver-rs/branch/master) -[![Crates.io](https://img.shields.io/crates/v/jobserver.svg?maxAge=2592000)](https://crates.io/crates/jobserver) - -[Documentation](https://docs.rs/jobserver) - -## Usage - -First, add this to your `Cargo.toml`: - -```toml -[dependencies] -jobserver = "0.1" -``` - -Next, add this to your crate: - -```rust -extern crate jobserver; -``` - -# License - -This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/src/lib.rs cargo-0.26.0/vendor/jobserver-0.1.9/src/lib.rs --- cargo-0.25.0/vendor/jobserver-0.1.9/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,945 +0,0 @@ -//! An implementation of the GNU make jobserver. -//! -//! This crate is an implementation, in Rust, of the GNU `make` jobserver for -//! CLI tools that are interoperating with make or otherwise require some form -//! of parallelism limiting across process boundaries. This was originally -//! written for usage in Cargo to both (a) work when `cargo` is invoked from -//! `make` (using `make`'s jobserver) and (b) work when `cargo` invokes build -//! scripts, exporting a jobserver implementation for `make` processes to -//! transitively use. -//! -//! The jobserver implementation can be found in [detail online][docs] but -//! basically boils down to a cross-process semaphore. On Unix this is -//! implemented with the `pipe` syscall and read/write ends of a pipe and on -//! Windows this is implemented literally with IPC semaphores. -//! -//! The jobserver protocol in `make` also dictates when tokens are acquire to -//! run child work, and clients using this crate should take care to implement -//! such details to ensure correct interoperation with `make` itself. -//! -//! ## Examples -//! -//! Connect to a jobserver that was set up by `make` or a different process: -//! -//! ```no_run -//! use jobserver::Client; -//! -//! // See API documentation for why this is `unsafe` -//! let client = match unsafe { Client::from_env() } { -//! Some(client) => client, -//! None => panic!("client not configured"), -//! }; -//! ``` -//! -//! Acquire and release token from a jobserver: -//! -//! ```no_run -//! use jobserver::Client; -//! -//! let client = unsafe { Client::from_env().unwrap() }; -//! let token = client.acquire().unwrap(); // blocks until it is available -//! drop(token); // releases the token when the work is done -//! ``` -//! -//! Create a new jobserver and configure a child process to have access: -//! -//! ``` -//! use std::process::Command; -//! use jobserver::Client; -//! -//! let client = Client::new(4).expect("failed to create jobserver"); -//! let mut cmd = Command::new("make"); -//! client.configure(&mut cmd); -//! ``` -//! -//! ## Caveats -//! -//! This crate makes no attempt to release tokens back to a jobserver on -//! abnormal exit of a process. If a process which acquires a token is killed -//! with ctrl-c or some similar signal then tokens will not be released and the -//! jobserver may be in a corrupt state. -//! -//! Note that this is typically ok as ctrl-c means that an entire build process -//! is being torn down, but it's worth being aware of at least! -//! -//! ## Windows caveats -//! -//! There appear to be two implementations of `make` on Windows. On MSYS2 one -//! typically comes as `mingw32-make` and the other as `make` itself. I'm not -//! personally too familiar with what's going on here, but for jobserver-related -//! information the `mingw32-make` implementation uses Windows semaphores -//! whereas the `make` program does not. The `make` program appears to use file -//! descriptors and I'm not really sure how it works, so this crate is not -//! compatible with `make` on Windows. It is, however, compatible with -//! `mingw32-make`. -//! -//! [docs]: http://make.mad-scientist.net/papers/jobserver-implementation/ - -#![deny(missing_docs, missing_debug_implementations)] -#![doc(html_root_url = "https://docs.rs/jobserver/0.1")] - -use std::env; -use std::io; -use std::process::Command; -use std::sync::Arc; -use std::sync::mpsc::{self, Sender}; - -/// A client of a jobserver -/// -/// This structure is the main type exposed by this library, and is where -/// interaction to a jobserver is configured through. Clients are either created -/// from scratch in which case the internal semphore is initialied on the spot, -/// or a client is created from the environment to connect to a jobserver -/// already created. -/// -/// Some usage examples can be found in the crate documentation for using a -/// client. -/// -/// Note that a `Client` implements the `Clone` trait, and all instances of a -/// `Client` refer to the same jobserver instance. -#[derive(Clone, Debug)] -pub struct Client { - inner: Arc, -} - -/// An acquired token from a jobserver. -/// -/// This token will be released back to the jobserver when it is dropped and -/// otherwise represents the ability to spawn off another thread of work. -#[derive(Debug)] -pub struct Acquired { - client: Arc, - data: imp::Acquired, -} - -impl Client { - /// Creates a new jobserver initialized with the given parallelism limit. - /// - /// A client to the jobserver created will be returned. This client will - /// allow at most `limit` tokens to be acquired from it in parallel. More - /// calls to `acquire` will cause the calling thread to block. - /// - /// Note that the created `Client` is not automatically inherited into - /// spawned child processes from this program. Manual usage of the - /// `configure` function is required for a child process to have access to a - /// job server. - /// - /// # Examples - /// - /// ``` - /// use jobserver::Client; - /// - /// let client = Client::new(4).expect("failed to create jobserver"); - /// ``` - /// - /// # Errors - /// - /// Returns an error if any I/O error happens when attempting to create the - /// jobserver client. - pub fn new(limit: usize) -> io::Result { - Ok(Client { - inner: Arc::new(imp::Client::new(limit)?), - }) - } - - /// Attempts to connect to the jobserver specified in this process's - /// environment. - /// - /// When the a `make` executable calls a child process it will configure the - /// environment of the child to ensure that it has handles to the jobserver - /// it's passing down. This function will attempt to look for these details - /// and connect to the jobserver. - /// - /// Note that the created `Client` is not automatically inherited into - /// spawned child processes from this program. Manual usage of the - /// `configure` function is required for a child process to have access to a - /// job server. - /// - /// # Return value - /// - /// If a jobserver was found in the environment and it looks correct then - /// `Some` of the connected client will be returned. If no jobserver was - /// found then `None` will be returned. - /// - /// Note that on Unix the `Client` returned **takes ownership of the file - /// descriptors specified in the environment**. Jobservers on Unix are - /// implemented with `pipe` file descriptors, and they're inherited from - /// parent processes. This `Client` returned takes ownership of the file - /// descriptors for this process and will close the file descriptors after - /// this value is dropped. - /// - /// Additionally on Unix this function will configure the file descriptors - /// with `CLOEXEC` so they're not automatically inherited by spawned - /// children. - /// - /// # Unsafety - /// - /// This function is `unsafe` to call on Unix specifically as it - /// transitively requires usage of the `from_raw_fd` function, which is - /// itself unsafe in some circumstances. - /// - /// It's recommended to call this function very early in the lifetime of a - /// program before any other file descriptors are opened. That way you can - /// make sure to take ownership properly of the file descriptors passed - /// down, if any. - /// - /// It's generally unsafe to call this function twice in a program if the - /// previous invocation returned `Some`. - /// - /// Note, though, that on Windows it should be safe to call this function - /// any number of times. - pub unsafe fn from_env() -> Option { - let var = match env::var("CARGO_MAKEFLAGS") - .or(env::var("MAKEFLAGS")) - .or(env::var("MFLAGS")) { - Ok(s) => s, - Err(_) => return None, - }; - let mut arg = "--jobserver-fds="; - let pos = match var.find(arg) { - Some(i) => i, - None => { - arg = "--jobserver-auth="; - match var.find(arg) { - Some(i) => i, - None => return None, - } - } - }; - - let s = var[pos + arg.len()..].split(' ').next().unwrap(); - imp::Client::open(s).map(|c| { - Client { inner: Arc::new(c) } - }) - } - - /// Acquires a token from this jobserver client. - /// - /// This function will block the calling thread until a new token can be - /// acquired from the jobserver. - /// - /// # Return value - /// - /// On successful acquisition of a token an instance of `Acquired` is - /// returned. This structure, when dropped, will release the token back to - /// the jobserver. It's recommended to avoid leaking this value. - /// - /// # Errors - /// - /// If an I/O error happens while acquiring a token then this function will - /// return immediately with the error. If an error is returned then a token - /// was not acquired. - pub fn acquire(&self) -> io::Result { - let data = try!(self.inner.acquire()); - Ok(Acquired { - client: self.inner.clone(), - data: data, - }) - } - - /// Configures a child process to have access to this client's jobserver as - /// well. - /// - /// This function is required to be called to ensure that a jobserver is - /// properly inherited to a child process. If this function is *not* called - /// then this `Client` will not be accessible in the child process. In other - /// words, if not called, then `Client::from_env` will return `None` in the - /// child process (or the equivalent of `Child::from_env` that `make` uses). - /// - /// ## Platform-specific behavior - /// - /// On Unix and Windows this will clobber the `CARGO_MAKEFLAGS` environment - /// variables for the child process, and on Unix this will also allow the - /// two file descriptors for this client to be inherited to the child. - pub fn configure(&self, cmd: &mut Command) { - let arg = self.inner.string_arg(); - // Older implementations of make use `--jobserver-fds` and newer - // implementations use `--jobserver-auth`, pass both to try to catch - // both implementations. - let value = format!("--jobserver-fds={0} --jobserver-auth={0}", arg); - cmd.env("CARGO_MAKEFLAGS", &value); - self.inner.configure(cmd); - } - - /// Converts this `Client` into a helper thread to deal with a blocking - /// `acquire` function a little more easily. - /// - /// The fact that the `acquire` function on `Client` blocks isn't always - /// the easiest to work with. Typically you're using a jobserver to - /// manage running other events in parallel! This means that you need to - /// either (a) wait for an existing job to finish or (b) wait for a - /// new token to become available. - /// - /// Unfortunately the blocking in `acquire` happens at the implementation - /// layer of jobservers. On Unix this requires a blocking call to `read` - /// and on Windows this requires one of the `WaitFor*` functions. Both - /// of these situations aren't the easiest to deal with: - /// - /// * On Unix there's basically only one way to wake up a `read` early, and - /// that's through a signal. This is what the `make` implementation - /// itself uses, relying on `SIGCHLD` to wake up a blocking acquisition - /// of a new job token. Unfortunately nonblocking I/O is not an option - /// here, so it means that "waiting for one of two events" means that - /// the latter event must generate a signal! This is not always the case - /// on unix for all jobservers. - /// - /// * On Windows you'd have to basically use the `WaitForMultipleObjects` - /// which means that you've got to canonicalize all your event sources - /// into a `HANDLE` which also isn't the easiest thing to do - /// unfortunately. - /// - /// This function essentially attempts to ease these limitations by - /// converting this `Client` into a helper thread spawned into this - /// process. The application can then request that the helper thread - /// acquires tokens and the provided closure will be invoked for each token - /// acquired. - /// - /// The intention is that this function can be used to translate the event - /// of a token acquisition into an arbitrary user-defined event. - /// - /// # Arguments - /// - /// This function will consume the `Client` provided to be transferred to - /// the helper thread that is spawned. Additionally a closure `f` is - /// provided to be invoked whenever a token is acquired. - /// - /// This closure is only invoked after calls to - /// `HelperThread::request_token` have been made and a token itself has - /// been acquired. If an error happens while acquiring the token then - /// an error will be yielded to the closure as well. - /// - /// # Return Value - /// - /// This function will return an instance of the `HelperThread` structure - /// which is used to manage the helper thread associated with this client. - /// Through the `HelperThread` you'll request that tokens are acquired. - /// When acquired, the closure provided here is invoked. - /// - /// When the `HelperThread` structure is returned it will be gracefully - /// torn down, and the calling thread will be blocked until the thread is - /// torn down (which should be prompt). - /// - /// # Errors - /// - /// This function may fail due to creation of the helper thread or - /// auxiliary I/O objects to manage the helper thread. In any of these - /// situations the error is propagated upwards. - /// - /// # Platform-specific behavior - /// - /// On Windows this function behaves pretty normally as expected, but on - /// Unix the implementation is... a little heinous. As mentioned above - /// we're forced into blocking I/O for token acquisition, namely a blocking - /// call to `read`. We must be able to unblock this, however, to tear down - /// the helper thread gracefully! - /// - /// Essentially what happens is that we'll send a signal to the helper - /// thread spawned and rely on `EINTR` being returned to wake up the helper - /// thread. This involves installing a global `SIGUSR1` handler that does - /// nothing along with sending signals to that thread. This may cause - /// odd behavior in some applications, so it's recommended to review and - /// test thoroughly before using this. - pub fn into_helper_thread(self, f: F) -> io::Result - where F: FnMut(io::Result) + Send + 'static, - { - let (tx, rx) = mpsc::channel(); - Ok(HelperThread { - inner: Some(imp::spawn_helper(self, rx, Box::new(f))?), - tx: Some(tx), - }) - } -} - -impl Drop for Acquired { - fn drop(&mut self) { - drop(self.client.release(&self.data)); - } -} - -/// Structure returned from `Client::into_helper_thread` to manage the lifetime -/// of the helper thread returned, see those associated docs for more info. -#[derive(Debug)] -pub struct HelperThread { - inner: Option, - tx: Option>, -} - -impl HelperThread { - /// Request that the helper thread acquires a token, eventually calling the - /// original closure with a token when it's available. - /// - /// For more information, see the docs on that function. - pub fn request_token(&self) { - self.tx.as_ref().unwrap().send(()).unwrap(); - } -} - -impl Drop for HelperThread { - fn drop(&mut self) { - drop(self.tx.take()); - self.inner.take().unwrap().join(); - } -} - -#[cfg(unix)] -mod imp { - extern crate libc; - - use std::fs::File; - use std::io::{self, Read, Write}; - use std::mem; - use std::os::unix::prelude::*; - use std::process::Command; - use std::ptr; - use std::sync::atomic::{AtomicBool, AtomicUsize, - ATOMIC_BOOL_INIT, ATOMIC_USIZE_INIT, - Ordering}; - use std::sync::mpsc::{self, Receiver, RecvTimeoutError}; - use std::sync::{Arc, Once, ONCE_INIT}; - use std::thread::{JoinHandle, Builder}; - use std::time::Duration; - - use self::libc::c_int; - - #[derive(Debug)] - pub struct Client { - read: File, - write: File, - } - - #[derive(Debug)] - pub struct Acquired { - byte: u8, - } - - impl Client { - pub fn new(limit: usize) -> io::Result { - let client = unsafe { Client::mk()? }; - // I don't think the character written here matters, but I could be - // wrong! - for _ in 0..limit { - (&client.write).write(&[b'|'])?; - } - Ok(client) - } - - unsafe fn mk() -> io::Result { - static INVALID: AtomicBool = ATOMIC_BOOL_INIT; - let mut pipes = [0; 2]; - - // Attempt atomically-create-with-cloexec if we can. Note that even - // when libc has the symbol, `pipe2` might still not be supported on - // the running kernel -> `ENOSYS`, then we need to use the fallback. - if cfg!(target_os = "linux") && !INVALID.load(Ordering::SeqCst) { - if let Some(pipe2) = pipe2() { - match cvt(pipe2(pipes.as_mut_ptr(), libc::O_CLOEXEC)) { - Ok(_) => return Ok(Client::from_fds(pipes[0], pipes[1])), - Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => { - INVALID.store(true, Ordering::SeqCst); - } - Err(e) => return Err(e), - } - } - } - - cvt(libc::pipe(pipes.as_mut_ptr()))?; - drop(set_cloexec(pipes[0], true)); - drop(set_cloexec(pipes[1], true)); - Ok(Client::from_fds(pipes[0], pipes[1])) - } - - pub unsafe fn open(s: &str) -> Option { - let mut parts = s.splitn(2, ','); - let read = parts.next().unwrap(); - let write = match parts.next() { - Some(s) => s, - None => return None, - }; - - let read = match read.parse() { - Ok(n) => n, - Err(_) => return None, - }; - let write = match write.parse() { - Ok(n) => n, - Err(_) => return None, - }; - - // Ok so we've got two integers that look like file descriptors, but - // for extra sanity checking let's see if they actually look like - // instances of a pipe before we return the client. - // - // If we're called from `make` *without* the leading + on our rule - // then we'll have `MAKEFLAGS` env vars but won't actually have - // access to the file descriptors. - if is_pipe(read) && is_pipe(write) { - drop(set_cloexec(read, true)); - drop(set_cloexec(write, true)); - Some(Client::from_fds(read, write)) - } else { - None - } - } - - unsafe fn from_fds(read: c_int, write: c_int) -> Client { - Client { - read: File::from_raw_fd(read), - write: File::from_raw_fd(write), - } - } - - pub fn acquire(&self) -> io::Result { - // We don't actually know if the file descriptor here is set in - // blocking or nonblocking mode. AFAIK all released versions of - // `make` use blocking fds for the jobserver, but the unreleased - // version of `make` doesn't. In the unreleased version jobserver - // fds are set to nonblocking and combined with `pselect` - // internally. - // - // Here we try to be compatible with both strategies. We - // unconditionally expect the file descriptor to be in nonblocking - // mode and if it happens to be in blocking mode then most of this - // won't end up actually being necessary! - // - // We use `poll` here to block this thread waiting for read - // readiness, and then afterwards we perform the `read` itself. If - // the `read` returns that it would block then we start over and try - // again. - // - // Also note that we explicitly don't handle EINTR here. That's used - // to shut us down, so we otherwise punt all errors upwards. - unsafe { - let mut fd: libc::pollfd = mem::zeroed(); - fd.fd = self.read.as_raw_fd(); - fd.events = libc::POLLIN; - loop { - fd.revents = 0; - if libc::poll(&mut fd, 1, -1) == -1 { - return Err(io::Error::last_os_error()) - } - if fd.revents == 0 { - continue - } - let mut buf = [0]; - match (&self.read).read(&mut buf) { - Ok(1) => return Ok(Acquired { byte: buf[0] }), - Ok(_) => { - return Err(io::Error::new(io::ErrorKind::Other, - "early EOF on jobserver pipe")) - } - Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {} - Err(e) => return Err(e), - } - } - } - } - - pub fn release(&self, data: &Acquired) -> io::Result<()> { - // Note that the fd may be nonblocking but we're going to go ahead - // and assume that the writes here are always nonblocking (we can - // always quickly release a token). If that turns out to not be the - // case we'll get an error anyway! - match (&self.write).write(&[data.byte])? { - 1 => Ok(()), - _ => Err(io::Error::new(io::ErrorKind::Other, - "failed to write token back to jobserver")), - } - } - - pub fn string_arg(&self) -> String { - format!("{},{} -j", self.read.as_raw_fd(), self.write.as_raw_fd()) - } - - pub fn configure(&self, cmd: &mut Command) { - // Here we basically just want to say that in the child process - // we'll configure the read/write file descriptors to *not* be - // cloexec, so they're inherited across the exec and specified as - // integers through `string_arg` above. - let read = self.read.as_raw_fd(); - let write = self.write.as_raw_fd(); - cmd.before_exec(move || { - set_cloexec(read, false)?; - set_cloexec(write, false)?; - Ok(()) - }); - } - } - - #[derive(Debug)] - pub struct Helper { - thread: JoinHandle<()>, - quitting: Arc, - rx_done: Receiver<()>, - } - - pub fn spawn_helper(client: ::Client, - rx: Receiver<()>, - mut f: Box) + Send>) - -> io::Result - { - static USR1_INIT: Once = ONCE_INIT; - let mut err = None; - USR1_INIT.call_once(|| unsafe { - let mut new: libc::sigaction = mem::zeroed(); - new.sa_sigaction = sigusr1_handler as usize; - new.sa_flags = libc::SA_SIGINFO as _; - if libc::sigaction(libc::SIGUSR1, &new, ptr::null_mut()) != 0 { - err = Some(io::Error::last_os_error()); - } - }); - - if let Some(e) = err.take() { - return Err(e) - } - - let quitting = Arc::new(AtomicBool::new(false)); - let quitting2 = quitting.clone(); - let (tx_done, rx_done) = mpsc::channel(); - let thread = Builder::new().spawn(move || { - 'outer: - for () in rx { - loop { - let res = client.acquire(); - if let Err(ref e) = res { - if e.kind() == io::ErrorKind::Interrupted { - if quitting2.load(Ordering::SeqCst) { - break 'outer - } else { - continue - } - } - } - f(res); - break - } - } - tx_done.send(()).unwrap(); - })?; - - Ok(Helper { - thread: thread, - quitting: quitting, - rx_done: rx_done, - }) - } - - impl Helper { - pub fn join(self) { - self.quitting.store(true, Ordering::SeqCst); - let dur = Duration::from_millis(10); - let mut done = false; - for _ in 0..100 { - unsafe { - // Ignore the return value here of `pthread_kill`, - // apparently on OSX if you kill a dead thread it will - // return an error, but on other platforms it may not. In - // that sense we don't actually know if this will succeed or - // not! - libc::pthread_kill(self.thread.as_pthread_t(), libc::SIGUSR1); - match self.rx_done.recv_timeout(dur) { - Ok(()) | - Err(RecvTimeoutError::Disconnected) => { - done = true; - break - } - Err(RecvTimeoutError::Timeout) => {} - } - } - } - if !done { - panic!("failed to shut down worker thread"); - } - drop(self.thread.join()); - } - } - - #[allow(unused_assignments)] - fn is_pipe(fd: c_int) -> bool { - unsafe { - let mut stat = mem::zeroed(); - if libc::fstat(fd, &mut stat) == 0 { - // On android arm and i686 mode_t is u16 and st_mode is u32, - // this generates a type mismatch when S_IFIFO (declared as mode_t) - // is used in operations with st_mode, so we use this workaround - // to get the value of S_IFIFO with the same type of st_mode. - let mut s_ififo = stat.st_mode; - s_ififo = libc::S_IFIFO as _; - stat.st_mode & s_ififo == s_ififo - } else { - false - } - } - } - - fn set_cloexec(fd: c_int, set: bool) -> io::Result<()> { - unsafe { - let previous = cvt(libc::fcntl(fd, libc::F_GETFD))?; - let new = if set { - previous | libc::FD_CLOEXEC - } else { - previous & !libc::FD_CLOEXEC - }; - if new != previous { - cvt(libc::fcntl(fd, libc::F_SETFD, new))?; - } - Ok(()) - } - } - - fn cvt(t: c_int) -> io::Result { - if t == -1 { - Err(io::Error::last_os_error()) - } else { - Ok(t) - } - } - - unsafe fn pipe2() -> Option<&'static fn(*mut c_int, c_int) -> c_int> { - static PIPE2: AtomicUsize = ATOMIC_USIZE_INIT; - - if PIPE2.load(Ordering::SeqCst) == 0 { - let name = "pipe2\0"; - let n = match libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _) as usize { - 0 => 1, - n => n, - }; - PIPE2.store(n, Ordering::SeqCst); - } - if PIPE2.load(Ordering::SeqCst) == 1 { - None - } else { - mem::transmute(&PIPE2) - } - } - - extern fn sigusr1_handler(_signum: c_int, - _info: *mut libc::siginfo_t, - _ptr: *mut libc::c_void) { - // nothing to do - } -} - -#[cfg(windows)] -mod imp { - extern crate rand; - - use std::ffi::CString; - use std::io; - use std::process::Command; - use std::ptr; - use std::sync::Arc; - use std::sync::mpsc::Receiver; - use std::thread::{Builder, JoinHandle}; - - #[derive(Debug)] - pub struct Client { - sem: Handle, - name: String, - } - - #[derive(Debug)] - pub struct Acquired; - - type BOOL = i32; - type DWORD = u32; - type HANDLE = *mut u8; - type LONG = i32; - - const ERROR_ALREADY_EXISTS: DWORD = 183; - const FALSE: BOOL = 0; - const INFINITE: DWORD = 0xffffffff; - const SEMAPHORE_MODIFY_STATE: DWORD = 0x2; - const SYNCHRONIZE: DWORD = 0x00100000; - const TRUE: BOOL = 1; - const WAIT_OBJECT_0: DWORD = 0; - - extern "system" { - fn CloseHandle(handle: HANDLE) -> BOOL; - fn SetEvent(hEvent: HANDLE) -> BOOL; - fn WaitForMultipleObjects(ncount: DWORD, - lpHandles: *const HANDLE, - bWaitAll: BOOL, - dwMilliseconds: DWORD) -> DWORD; - fn CreateEventA(lpEventAttributes: *mut u8, - bManualReset: BOOL, - bInitialState: BOOL, - lpName: *const i8) -> HANDLE; - fn ReleaseSemaphore(hSemaphore: HANDLE, - lReleaseCount: LONG, - lpPreviousCount: *mut LONG) -> BOOL; - fn CreateSemaphoreA(lpEventAttributes: *mut u8, - lInitialCount: LONG, - lMaximumCount: LONG, - lpName: *const i8) -> HANDLE; - fn OpenSemaphoreA(dwDesiredAccess: DWORD, - bInheritHandle: BOOL, - lpName: *const i8) -> HANDLE; - fn WaitForSingleObject(hHandle: HANDLE, - dwMilliseconds: DWORD) -> DWORD; - } - - impl Client { - pub fn new(limit: usize) -> io::Result { - // Try a bunch of random semaphore names until we get a unique one, - // but don't try for too long. - // - // Note that `limit == 0` is a valid argument above but Windows - // won't let us create a semaphore with 0 slots available to it. Get - // `limit == 0` working by creating a semaphore instead with one - // slot and then immediately acquire it (without ever releaseing it - // back). - for _ in 0..100 { - let mut name = format!("__rust_jobserver_semaphore_{}\0", - rand::random::()); - unsafe { - let create_limit = if limit == 0 {1} else {limit}; - let r = CreateSemaphoreA(ptr::null_mut(), - create_limit as LONG, - create_limit as LONG, - name.as_ptr() as *const _); - if r.is_null() { - return Err(io::Error::last_os_error()) - } - let handle = Handle(r); - - let err = io::Error::last_os_error(); - if err.raw_os_error() == Some(ERROR_ALREADY_EXISTS as i32) { - continue - } - name.pop(); // chop off the trailing nul - let client = Client { - sem: handle, - name: name, - }; - if create_limit != limit { - client.acquire()?; - } - return Ok(client) - } - } - - Err(io::Error::new(io::ErrorKind::Other, - "failed to find a unique name for a semaphore")) - } - - pub unsafe fn open(s: &str) -> Option { - let name = match CString::new(s) { - Ok(s) => s, - Err(_) => return None, - }; - - let sem = OpenSemaphoreA(SYNCHRONIZE | SEMAPHORE_MODIFY_STATE, - FALSE, - name.as_ptr()); - if sem.is_null() { - None - } else { - Some(Client { - sem: Handle(sem), - name: s.to_string(), - }) - } - } - - pub fn acquire(&self) -> io::Result { - unsafe { - let r = WaitForSingleObject(self.sem.0, INFINITE); - if r == WAIT_OBJECT_0 { - Ok(Acquired) - } else { - Err(io::Error::last_os_error()) - } - } - } - - pub fn release(&self, _data: &Acquired) -> io::Result<()> { - unsafe { - let r = ReleaseSemaphore(self.sem.0, 1, ptr::null_mut()); - if r != 0 { - Ok(()) - } else { - Err(io::Error::last_os_error()) - } - } - } - - pub fn string_arg(&self) -> String { - self.name.clone() - } - - pub fn configure(&self, _cmd: &mut Command) { - // nothing to do here, we gave the name of our semaphore to the - // child above - } - } - - #[derive(Debug)] - struct Handle(HANDLE); - // HANDLE is a raw ptr, but we're send/sync - unsafe impl Sync for Handle {} - unsafe impl Send for Handle {} - - impl Drop for Handle { - fn drop(&mut self) { - unsafe { - CloseHandle(self.0); - } - } - } - - #[derive(Debug)] - pub struct Helper { - event: Arc, - thread: JoinHandle<()>, - } - - pub fn spawn_helper(client: ::Client, - rx: Receiver<()>, - mut f: Box) + Send>) - -> io::Result - { - let event = unsafe { - let r = CreateEventA(ptr::null_mut(), TRUE, FALSE, ptr::null()); - if r.is_null() { - return Err(io::Error::last_os_error()) - } else { - Handle(r) - } - }; - let event = Arc::new(event); - let event2 = event.clone(); - let thread = Builder::new().spawn(move || { - let objects = [event2.0, client.inner.sem.0]; - for () in rx { - let r = unsafe { - WaitForMultipleObjects(2, objects.as_ptr(), FALSE, INFINITE) - }; - if r == WAIT_OBJECT_0 { - break - } - if r == WAIT_OBJECT_0 + 1 { - f(Ok(::Acquired { - client: client.inner.clone(), - data: Acquired, - })) - } else { - f(Err(io::Error::last_os_error())) - } - } - })?; - Ok(Helper { - thread: thread, - event: event, - }) - } - - impl Helper { - pub fn join(self) { - let r = unsafe { SetEvent(self.event.0) }; - if r == 0 { - panic!("failed to set event: {}", io::Error::last_os_error()); - } - drop(self.thread.join()); - } - } -} diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/tests/client-of-myself.rs cargo-0.26.0/vendor/jobserver-0.1.9/tests/client-of-myself.rs --- cargo-0.25.0/vendor/jobserver-0.1.9/tests/client-of-myself.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/tests/client-of-myself.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -extern crate jobserver; - -use std::env; -use std::io::BufReader; -use std::io::prelude::*; -use std::process::{Command, Stdio}; -use std::sync::mpsc; -use std::thread; - -use jobserver::Client; - -macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {}", stringify!($e), e), - }) -} - -fn main() { - if env::var("I_AM_THE_CLIENT").is_ok() { - client(); - } else { - server(); - } -} - -fn server() { - let me = t!(env::current_exe()); - let client = t!(Client::new(1)); - let mut cmd = Command::new(me); - cmd.env("I_AM_THE_CLIENT", "1") - .stdout(Stdio::piped()); - client.configure(&mut cmd); - let acq = client.acquire().unwrap(); - let mut child = t!(cmd.spawn()); - let stdout = child.stdout.take().unwrap(); - let (tx, rx) = mpsc::channel(); - let t = thread::spawn(move || { - for line in BufReader::new(stdout).lines() { - tx.send(t!(line)).unwrap(); - } - }); - - for _ in 0..100 { - assert!(rx.try_recv().is_err()); - } - - drop(acq); - assert_eq!(rx.recv().unwrap(), "hello!"); - t.join().unwrap(); - assert!(rx.recv().is_err()); - client.acquire().unwrap(); -} - -fn client() { - let client = unsafe { Client::from_env().unwrap() }; - let acq = client.acquire().unwrap(); - println!("hello!"); - drop(acq); -} diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/tests/client.rs cargo-0.26.0/vendor/jobserver-0.1.9/tests/client.rs --- cargo-0.25.0/vendor/jobserver-0.1.9/tests/client.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/tests/client.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,191 +0,0 @@ -extern crate futures; -extern crate jobserver; -extern crate num_cpus; -extern crate tempdir; -extern crate tokio_core; -extern crate tokio_process; - -use std::env; -use std::fs::File; -use std::io::Write; -use std::process::Command; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc; -use std::thread; - -use futures::future::{self, Future}; -use futures::stream::{self, Stream}; -use jobserver::Client; -use tempdir::TempDir; -use tokio_core::reactor::Core; -use tokio_process::CommandExt; - -macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {}", stringify!($e), e), - }) -} - -struct Test { - name: &'static str, - f: &'static Fn(), - make_args: &'static [&'static str], - rule: &'static Fn(&str) -> String, -} - -const TESTS: &[Test] = &[ - Test { - name: "no j args", - make_args: &[], - rule: &|me| format!("{}", me), - f: &|| { - assert!(unsafe { Client::from_env().is_none() }); - }, - }, - Test { - name: "no j args with plus", - make_args: &[], - rule: &|me| format!("+{}", me), - f: &|| { - assert!(unsafe { Client::from_env().is_none() }); - }, - }, - Test { - name: "j args with plus", - make_args: &["-j2"], - rule: &|me| format!("+{}", me), - f: &|| { - assert!(unsafe { Client::from_env().is_some() }); - }, - }, - Test { - name: "acquire", - make_args: &["-j2"], - rule: &|me| format!("+{}", me), - f: &|| { - let c = unsafe { Client::from_env().unwrap() }; - drop(c.acquire().unwrap()); - drop(c.acquire().unwrap()); - }, - }, - Test { - name: "acquire3", - make_args: &["-j3"], - rule: &|me| format!("+{}", me), - f: &|| { - let c = unsafe { Client::from_env().unwrap() }; - let a = c.acquire().unwrap(); - let b = c.acquire().unwrap(); - drop((a, b)); - }, - }, - Test { - name: "acquire blocks", - make_args: &["-j2"], - rule: &|me| format!("+{}", me), - f: &|| { - let c = unsafe { Client::from_env().unwrap() }; - let a = c.acquire().unwrap(); - let hit = Arc::new(AtomicBool::new(false)); - let hit2 = hit.clone(); - let (tx, rx) = mpsc::channel(); - let t = thread::spawn(move || { - tx.send(()).unwrap(); - let _b = c.acquire().unwrap(); - hit2.store(true, Ordering::SeqCst); - }); - rx.recv().unwrap(); - assert!(!hit.load(Ordering::SeqCst)); - drop(a); - t.join().unwrap(); - assert!(hit.load(Ordering::SeqCst)); - }, - }, -]; - -fn main() { - if let Ok(test) = env::var("TEST_TO_RUN") { - return (TESTS.iter().find(|t| t.name == test).unwrap().f)() - } - - let me = t!(env::current_exe()); - let me = me.to_str().unwrap(); - let filter = env::args().skip(1).next(); - - let mut core = t!(Core::new()); - let ref handle = core.handle(); - - let futures = TESTS.iter().filter(|test| { - match filter { - Some(ref s) => test.name.contains(s), - None => true, - } - }).map(|test| { - let td = t!(TempDir::new("foo")); - let makefile = format!("\ -all: export TEST_TO_RUN={} -all: -\t{} -", test.name, (test.rule)(me)); - t!(t!(File::create(td.path().join("Makefile"))) - .write_all(makefile.as_bytes())); - let prog = env::var("MAKE").unwrap_or("make".to_string()); - let mut cmd = Command::new(prog); - cmd.args(test.make_args); - cmd.current_dir(td.path()); - future::lazy(move || { - cmd.output_async(&handle).map(move |e| { - drop(td); - (test, e) - }) - }) - }).collect::>(); - - println!("\nrunning {} tests\n", futures.len()); - - let stream = stream::iter(futures.into_iter().map(Ok)) - .buffer_unordered(num_cpus::get()); - - let mut failures = Vec::new(); - t!(core.run(stream.for_each(|(test, output)| { - if output.status.success() { - println!("test {} ... ok", test.name); - } else { - println!("test {} ... FAIL", test.name); - failures.push((test, output)); - } - Ok(()) - }))); - - if failures.len() == 0 { - println!("\ntest result: ok\n"); - return - } - - println!("\n----------- failures"); - - for (test, output) in failures { - println!("test {}", test.name); - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - - println!("\texit status: {}", output.status); - if !stdout.is_empty() { - println!("\tstdout ==="); - for line in stdout.lines() { - println!("\t\t{}", line); - } - } - - if !stderr.is_empty() { - println!("\tstderr ==="); - for line in stderr.lines() { - println!("\t\t{}", line); - } - } - } - - std::process::exit(4); -} diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/tests/helper.rs cargo-0.26.0/vendor/jobserver-0.1.9/tests/helper.rs --- cargo-0.25.0/vendor/jobserver-0.1.9/tests/helper.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/tests/helper.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -extern crate jobserver; - -use std::sync::mpsc; - -use jobserver::Client; - -macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {}", stringify!($e), e), - }) -} - -#[test] -fn helper_smoke() { - let client = t!(Client::new(1)); - drop(client.clone().into_helper_thread(|_| ()).unwrap()); - drop(client.clone().into_helper_thread(|_| ()).unwrap()); - drop(client.clone().into_helper_thread(|_| ()).unwrap()); - drop(client.clone().into_helper_thread(|_| ()).unwrap()); - drop(client.clone().into_helper_thread(|_| ()).unwrap()); - drop(client.clone().into_helper_thread(|_| ()).unwrap()); -} - -#[test] -fn acquire() { - let (tx, rx) = mpsc::channel(); - let client = t!(Client::new(1)); - let helper = client.into_helper_thread(move |a| drop(tx.send(a))).unwrap(); - assert!(rx.try_recv().is_err()); - helper.request_token(); - rx.recv().unwrap().unwrap(); - helper.request_token(); - rx.recv().unwrap().unwrap(); - - helper.request_token(); - helper.request_token(); - rx.recv().unwrap().unwrap(); - rx.recv().unwrap().unwrap(); - - helper.request_token(); - helper.request_token(); - drop(helper); -} diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/tests/make-as-a-client.rs cargo-0.26.0/vendor/jobserver-0.1.9/tests/make-as-a-client.rs --- cargo-0.25.0/vendor/jobserver-0.1.9/tests/make-as-a-client.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/tests/make-as-a-client.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -extern crate jobserver; -extern crate tempdir; - -use std::env; -use std::fs::File; -use std::io::prelude::*; -use std::net::{TcpStream, TcpListener}; -use std::process::Command; - -use jobserver::Client; -use tempdir::TempDir; - -macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {}", stringify!($e), e), - }) -} - -fn main() { - if env::var("_DO_THE_TEST").is_ok() { - std::process::exit( - Command::new(env::var_os("MAKE").unwrap()) - .env("MAKEFLAGS", env::var_os("CARGO_MAKEFLAGS").unwrap()) - .env_remove("_DO_THE_TEST") - .args(&env::args_os().skip(1).collect::>()) - .status() - .unwrap() - .code() - .unwrap_or(1) - ); - } - - if let Ok(s) = env::var("TEST_ADDR") { - let mut contents = Vec::new(); - t!(t!(TcpStream::connect(&s)).read_to_end(&mut contents)); - return - } - - let c = t!(Client::new(1)); - let td = TempDir::new("foo").unwrap(); - - let prog = env::var("MAKE").unwrap_or("make".to_string()); - - let me = t!(env::current_exe()); - let me = me.to_str().unwrap(); - - let mut cmd = Command::new(&me); - cmd.current_dir(td.path()); - cmd.env("MAKE", prog); - cmd.env("_DO_THE_TEST", "1"); - - t!(t!(File::create(td.path().join("Makefile"))).write_all(format!("\ -all: foo bar -foo: -\t{0} -bar: -\t{0} -", me).as_bytes())); - - // We're leaking one extra token to `make` sort of violating the makefile - // jobserver protocol. It has the desired effect though. - c.configure(&mut cmd); - - let listener = t!(TcpListener::bind("127.0.0.1:0")); - let addr = t!(listener.local_addr()); - cmd.env("TEST_ADDR", addr.to_string()); - let mut child = t!(cmd.spawn()); - - // We should get both connections as the two programs should be run - // concurrently. - let a = t!(listener.accept()); - let b = t!(listener.accept()); - drop((a, b)); - - assert!(t!(child.wait()).success()); -} diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/tests/server.rs cargo-0.26.0/vendor/jobserver-0.1.9/tests/server.rs --- cargo-0.25.0/vendor/jobserver-0.1.9/tests/server.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/tests/server.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,145 +0,0 @@ -extern crate jobserver; -extern crate tempdir; - -use std::env; -use std::fs::File; -use std::io::prelude::*; -use std::process::Command; -use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::mpsc; -use std::thread; - -use jobserver::Client; -use tempdir::TempDir; - -macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {}", stringify!($e), e), - }) -} - -#[test] -fn server_smoke() { - let c = t!(Client::new(1)); - drop(c.acquire().unwrap()); - drop(c.acquire().unwrap()); -} - -#[test] -fn server_multiple() { - let c = t!(Client::new(2)); - let a = c.acquire().unwrap(); - let b = c.acquire().unwrap(); - drop((a, b)); -} - -#[test] -fn server_blocks() { - let c = t!(Client::new(1)); - let a = c.acquire().unwrap(); - let hit = Arc::new(AtomicBool::new(false)); - let hit2 = hit.clone(); - let (tx, rx) = mpsc::channel(); - let t = thread::spawn(move || { - tx.send(()).unwrap(); - let _b = c.acquire().unwrap(); - hit2.store(true, Ordering::SeqCst); - }); - rx.recv().unwrap(); - assert!(!hit.load(Ordering::SeqCst)); - drop(a); - t.join().unwrap(); - assert!(hit.load(Ordering::SeqCst)); -} - -#[test] -fn make_as_a_single_thread_client() { - let c = t!(Client::new(1)); - let td = TempDir::new("foo").unwrap(); - - let prog = env::var("MAKE").unwrap_or("make".to_string()); - let mut cmd = Command::new(prog); - cmd.current_dir(td.path()); - - t!(t!(File::create(td.path().join("Makefile"))).write_all(b" -all: foo bar -foo: -\techo foo -bar: -\techo bar -")); - - // The jobserver protocol means that the `make` process itself "runs with a - // token", so we acquire our one token to drain the jobserver, and this - // should mean that `make` itself never has a second token available to it. - let _a = c.acquire(); - c.configure(&mut cmd); - let output = t!(cmd.output()); - println!("\n\t=== stderr\n\t\t{}", - String::from_utf8_lossy(&output.stderr).replace("\n", "\n\t\t")); - println!("\t=== stdout\n\t\t{}", - String::from_utf8_lossy(&output.stdout).replace("\n", "\n\t\t")); - - assert!(output.status.success()); - assert!(output.stderr.is_empty()); - - let stdout = String::from_utf8_lossy(&output.stdout).replace("\r\n", "\n"); - let a = "\ -echo foo -foo -echo bar -bar -"; - let b = "\ -echo bar -bar -echo foo -foo -"; - - assert!(stdout == a || stdout == b); -} - -#[test] -fn make_as_a_multi_thread_client() { - let c = t!(Client::new(1)); - let td = TempDir::new("foo").unwrap(); - - let prog = env::var("MAKE").unwrap_or("make".to_string()); - let mut cmd = Command::new(prog); - cmd.current_dir(td.path()); - - t!(t!(File::create(td.path().join("Makefile"))).write_all(b" -all: foo bar -foo: -\techo foo -bar: -\techo bar -")); - - // We're leaking one extra token to `make` sort of violating the makefile - // jobserver protocol. It has the desired effect though. - c.configure(&mut cmd); - let output = t!(cmd.output()); - println!("\n\t=== stderr\n\t\t{}", - String::from_utf8_lossy(&output.stderr).replace("\n", "\n\t\t")); - println!("\t=== stdout\n\t\t{}", - String::from_utf8_lossy(&output.stdout).replace("\n", "\n\t\t")); - - assert!(output.status.success()); -} - -#[test] -fn zero_client() { - let client = t!(Client::new(0)); - let (tx, rx) = mpsc::channel(); - let helper = client.into_helper_thread(move |a| drop(tx.send(a))).unwrap(); - helper.request_token(); - helper.request_token(); - - for _ in 0..1000 { - assert!(rx.try_recv().is_err()); - } -} diff -Nru cargo-0.25.0/vendor/jobserver-0.1.9/.travis.yml cargo-0.26.0/vendor/jobserver-0.1.9/.travis.yml --- cargo-0.25.0/vendor/jobserver-0.1.9/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/jobserver-0.1.9/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -language: rust -rust: stable - -matrix: - include: - - os: osx - - rust: stable - - rust: beta - - rust: nightly - before_script: - - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH - after_success: - - travis-cargo doc-upload - -sudo: false -script: - - cargo test - - cargo doc --no-deps -env: - global: - secure: "u4sfTRgvuqtiwil/a5RMjNFKdUJl0fr8MM73c934I4nDuIPQ+v1ZIj/ehclHXED+vT3M5h0Ois+HWBn/626vVZCuCUBqeC96qB7K+tqJlzpxGgukF9Ps2q7nh14NBxsTQ3HBJbrxdi6qaozAaa3BLPh6pLCBBgfofsbaeikV6ogosI0ZeYDwwEA7dc7yVKWwuMDFnxeqEqkdC9SLc4dsSuFAYWs3w00EU6sukG7ISv1e5fluZtJgNxbMe5RUCa2/lsDtmrWpkHSagcfhbWqb5LZ0ZZE+v6/Z9ASlHEOt462p4ZnkTgVgRw9/QcV75KN/tHI4hrXOU55VkEBzZqlc1Fyr+xeIpghNel8HEnLpde8B+XbCxCzGORPntCjVjfIn++wxK7ce30hslBsT75UJPrTnsBPr5rPahX8i0K6R8Xc2i7qMd5p2NTDs51MWpnjNgAGFj/1WS7t638i+gkia9ficfNRXDlMCNDC8F24r5huB6G4EKWYyCLYdMZHNaKO1XCVMTeRh2EQpLILkT8BFVZN1ttGUZ1BhMsZ1U4pCgta7phRZkBiov7uomPHMUX+fn0rmh58Z2Rodbvdzdx4fVRCebBgqxh25We2ByWRyAHfEF0Cw91A8bs1u1ssdta8UXqrb9d6oKDPCDIO/v+mzd6KXN2d5bTExo0aLs8qMC3Q=" - -notifications: - email: - on_success: never diff -Nru cargo-0.25.0/vendor/lazycell-0.6.0/.cargo-checksum.json cargo-0.26.0/vendor/lazycell-0.6.0/.cargo-checksum.json --- cargo-0.25.0/vendor/lazycell-0.6.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/lazycell-0.6.0/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"a6f08839bc70ef4a3fe1d566d5350f519c5912ea86be0df1740a7d247c7fc0ef"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/lazycell-0.6.0/Cargo.toml cargo-0.26.0/vendor/lazycell-0.6.0/Cargo.toml --- cargo-0.25.0/vendor/lazycell-0.6.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/lazycell-0.6.0/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,30 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "lazycell" +version = "0.6.0" +authors = ["Alex Crichton ", "Nikita Pekin "] +include = ["CHANGELOG.md", "Cargo.toml", "LICENSE-MIT", "LICENSE-APACHE", "README.md", "src/**/*.rs"] +description = "A library providing a lazily filled Cell struct" +documentation = "http://indiv0.github.io/lazycell/lazycell/" +readme = "README.md" +keywords = ["lazycell", "lazy", "cell", "library"] +license = "MIT/Apache-2.0" +repository = "https://github.com/indiv0/lazycell" +[dependencies.clippy] +version = "0.0" +optional = true + +[features] +nightly = [] +nightly-testing = ["clippy", "nightly"] diff -Nru cargo-0.25.0/vendor/lazycell-0.6.0/CHANGELOG.md cargo-0.26.0/vendor/lazycell-0.6.0/CHANGELOG.md --- cargo-0.25.0/vendor/lazycell-0.6.0/CHANGELOG.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/lazycell-0.6.0/CHANGELOG.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,132 @@ + +## 0.6.0 (2017-11-25) + + +#### Bug Fixes + +* fix soundness hole in borrow_with ([d1f46bef](https://github.com/indiv0/lazycell/commit/d1f46bef9d1397570aa9c3e87e18e0d16e6d1585)) + +#### Features + +* add Default derives ([71bc5088](https://github.com/indiv0/lazycell/commit/71bc50880cd8e20002038197c9b890f5b76ad096)) +* add LazyCell::try_borrow_with ([bffa4028](https://github.com/indiv0/lazycell/commit/bffa402896670b5c78a9ec050d82a58ee98de6fb)) +* add LazyCell::borrow_mut method ([fd419dea](https://github.com/indiv0/lazycell/commit/fd419dea965ff1ad3853f26f37e8d107c6ca096c)) + +#### Breaking Changes + +* add `T: Send` for `AtomicLazyCell` `Sync` impl ([668bb2fa](https://github.com/indiv0/lazycell/commit/668bb2fa974fd6707c4c7edad292c76a9017d74d), closes [#67](https://github.com/indiv0/lazycell/issues/67)) + +#### Improvements + +* add `T: Send` for `AtomicLazyCell` `Sync` impl ([668bb2fa](https://github.com/indiv0/lazycell/commit/668bb2fa974fd6707c4c7edad292c76a9017d74d), closes [#67](https://github.com/indiv0/lazycell/issues/67)) + + + + +## v0.5.1 (2017-03-24) + + +#### Documentation + +* fix missing backticks ([44bafaaf](https://github.com/indiv0/lazycell/commit/44bafaaf93a91641261f58ee38adadcd4af6458e)) + +#### Improvements + +* derive `Debug` impls ([9da0a5a2](https://github.com/indiv0/lazycell/commit/9da0a5a2ffac1fef03ef02851c2c89d26d67d225)) + +#### Features + +* Add get method for Copy types ([dc8f8209](https://github.com/indiv0/lazycell/commit/dc8f8209888b6eba6d18717eba6a22614629b997)) + + + + +## v0.5.0 (2016-12-08) + + +#### Features + +* add borrow_with to LazyCell ([a15efa35](https://github.com/indiv0/lazycell/commit/a15efa359ea5a31a66ba57fc5b25f90c87b4b0dd)) + + + + +## (2016-08-17) + + +#### Breaking Changes + +* **LazyCell:** return Err(value) on full cell ([68f3415d](https://github.com/indiv0/lazycell/commit/68f3415dd5d6a66ba047a133b7028ebe4f1c5070), breaks [#](https://github.com/indiv0/lazycell/issues/)) + +#### Improvements + +* **LazyCell:** return Err(value) on full cell ([68f3415d](https://github.com/indiv0/lazycell/commit/68f3415dd5d6a66ba047a133b7028ebe4f1c5070), breaks [#](https://github.com/indiv0/lazycell/issues/)) + + + + +## (2016-08-16) + + +#### Features + +* add AtomicLazyCell which is thread-safe ([85afbd36](https://github.com/indiv0/lazycell/commit/85afbd36d8a148e14cc53654b39ddb523980124d)) + +#### Improvements + +* Use UnsafeCell instead of RefCell ([3347a8e9](https://github.com/indiv0/lazycell/commit/3347a8e97d2215a47e25c1e2fc953e8052ad8eb6)) + + + + +## (2016-04-18) + + +#### Documentation + +* put types in between backticks ([607cf939](https://github.com/indiv0/lazycell/commit/607cf939b05e35001ba3070ec7a0b17b064e7be1)) + + + + +## v0.2.0 (2016-03-28) + + +#### Features + +* **lazycell:** + * add tests for `LazyCell` struct ([38f1313d](https://github.com/indiv0/lazycell/commit/38f1313d98542ca8c98b424edfa9ba9c3975f99e), closes [#30](https://github.com/indiv0/lazycell/issues/30)) + * remove unnecessary `Default` impl ([68c16d2d](https://github.com/indiv0/lazycell/commit/68c16d2df4e9d13d5298162c06edf918246fd758)) + +#### Documentation + +* **CHANGELOG:** removed unnecessary sections ([1cc0555d](https://github.com/indiv0/lazycell/commit/1cc0555d875898a01b0832ff967aed6b40e720eb)) +* **README:** add link to documentation ([c8dc33f0](https://github.com/indiv0/lazycell/commit/c8dc33f01f2c0dc187f59ee53a2b73081053012b), closes [#13](https://github.com/indiv0/lazycell/issues/13)) + + + + +## v0.1.0 (2016-03-16) + + +#### Features + +* **lib.rs:** implement Default trait for LazyCell ([150a6304](https://github.com/indiv0/LazyCell/commit/150a6304a230ee1de8424e49c447ec1b2d6578ce)) + + + + +## v0.0.1 (2016-03-16) + + +#### Bug Fixes + +* **Cargo.toml:** loosen restrictions on Clippy version ([84dd8f96](https://github.com/indiv0/LazyCell/commit/84dd8f960000294f9dad47d776a41b98ed812981)) + +#### Features + +* add initial implementation ([4b39764a](https://github.com/indiv0/LazyCell/commit/4b39764a575bcb701dbd8047b966f72720fd18a4)) +* add initial commit ([a80407a9](https://github.com/indiv0/LazyCell/commit/a80407a907ef7c9401f120104663172f6965521a)) + + + diff -Nru cargo-0.25.0/vendor/lazycell-0.6.0/LICENSE-APACHE cargo-0.26.0/vendor/lazycell-0.6.0/LICENSE-APACHE --- cargo-0.25.0/vendor/lazycell-0.6.0/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/lazycell-0.6.0/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/lazycell-0.6.0/LICENSE-MIT cargo-0.26.0/vendor/lazycell-0.6.0/LICENSE-MIT --- cargo-0.25.0/vendor/lazycell-0.6.0/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/lazycell-0.6.0/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,26 @@ +Original work Copyright (c) 2014 The Rust Project Developers +Modified work Copyright (c) 2016-2017 Nikita Pekin and lazycell contributors + +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. diff -Nru cargo-0.25.0/vendor/lazycell-0.6.0/README.md cargo-0.26.0/vendor/lazycell-0.6.0/README.md --- cargo-0.25.0/vendor/lazycell-0.6.0/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/lazycell-0.6.0/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,72 @@ +# lazycell + + + + + + + + + +
Linuxtravis-badge
+ api-docs-badge + crates-io + license-badge + coveralls-badge +
+ +Rust library providing a lazily filled Cell. + +# Table of Contents + +* [Usage](#usage) +* [Contributing](#contributing) +* [Credits](#credits) +* [License](#license) + +## Usage + +Add the following to your `Cargo.toml`: + +```toml +[dependencies] +lazycell = "0.6" +``` + +And in your `lib.rs` or `main.rs`: + +```rust +extern crate lazycell; +``` + +See the [API docs][api-docs] for information on using the crate in your library. + +## Contributing + +Contributions are always welcome! +If you have an idea for something to add (code, documentation, tests, examples, +etc.) feel free to give it a shot. + +Please read [CONTRIBUTING.md][contributing] before you start contributing. + +## Credits + +The LazyCell library is based originally on work by The Rust Project Developers +for the project [crates.io][crates-io-repo]. + +The list of contributors to this project can be found at +[CONTRIBUTORS.md][contributors]. + +## License + +LazyCell is distributed under the terms of both the MIT license and the Apache +License (Version 2.0). + +See [LICENSE-APACHE][license-apache], and [LICENSE-MIT][license-mit] for details. + +[api-docs]: https://indiv0.github.io/lazycell/lazycell +[contributing]: https://github.com/indiv0/lazycell/blob/master/CONTRIBUTING.md "Contribution Guide" +[contributors]: https://github.com/indiv0/lazycell/blob/master/CONTRIBUTORS.md "List of Contributors" +[crates-io-repo]: https://github.com/rust-lang/crates.io "rust-lang/crates.io: Source code for crates.io" +[license-apache]: https://github.com/indiv0/lazycell/blob/master/LICENSE-APACHE "Apache-2.0 License" +[license-mit]: https://github.com/indiv0/lazycell/blob/master/LICENSE-MIT "MIT License" diff -Nru cargo-0.25.0/vendor/lazycell-0.6.0/src/lib.rs cargo-0.26.0/vendor/lazycell-0.6.0/src/lib.rs --- cargo-0.25.0/vendor/lazycell-0.6.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/lazycell-0.6.0/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,414 @@ +// Original work Copyright (c) 2014 The Rust Project Developers +// Modified work Copyright (c) 2016-2017 Nikita Pekin and the lazycell contributors +// See the README.md file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![deny(missing_docs)] +#![cfg_attr(feature = "nightly", feature(plugin))] +#![cfg_attr(feature = "clippy", plugin(clippy))] + +//! This crate provides a `LazyCell` struct which acts as a lazily filled +//! `Cell`, but with frozen contents. +//! +//! With a `RefCell`, the inner contents cannot be borrowed for the lifetime of +//! the entire object, but only of the borrows returned. A `LazyCell` is a +//! variation on `RefCell` which allows borrows to be tied to the lifetime of +//! the outer object. +//! +//! The limitation of a `LazyCell` is that after it is initialized and shared, +//! it can be modified. +//! +//! # Example +//! +//! The following example shows a quick example of the basic functionality of +//! `LazyCell`. +//! +//! ``` +//! use lazycell::LazyCell; +//! +//! let lazycell = LazyCell::new(); +//! +//! assert_eq!(lazycell.borrow(), None); +//! assert!(!lazycell.filled()); +//! lazycell.fill(1).ok(); +//! assert!(lazycell.filled()); +//! assert_eq!(lazycell.borrow(), Some(&1)); +//! assert_eq!(lazycell.into_inner(), Some(1)); +//! ``` +//! +//! `AtomicLazyCell` is a variant that uses an atomic variable to manage +//! coordination in a thread-safe fashion. + +use std::cell::UnsafeCell; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// A lazily filled `Cell`, with frozen contents. +#[derive(Debug, Default)] +pub struct LazyCell { + inner: UnsafeCell>, +} + +impl LazyCell { + /// Creates a new, empty, `LazyCell`. + pub fn new() -> LazyCell { + LazyCell { inner: UnsafeCell::new(None) } + } + + /// Put a value into this cell. + /// + /// This function will return `Err(value)` is the cell is already full. + pub fn fill(&self, value: T) -> Result<(), T> { + let mut slot = unsafe { &mut *self.inner.get() }; + if slot.is_some() { + return Err(value); + } + *slot = Some(value); + + Ok(()) + } + + /// Test whether this cell has been previously filled. + pub fn filled(&self) -> bool { + self.borrow().is_some() + } + + /// Borrows the contents of this lazy cell for the duration of the cell + /// itself. + /// + /// This function will return `Some` if the cell has been previously + /// initialized, and `None` if it has not yet been initialized. + pub fn borrow(&self) -> Option<&T> { + unsafe { &*self.inner.get() }.as_ref() + } + + /// Borrows the contents of this lazy cell mutably for the duration of the cell + /// itself. + /// + /// This function will return `Some` if the cell has been previously + /// initialized, and `None` if it has not yet been initialized. + pub fn borrow_mut(&mut self) -> Option<&mut T> { + unsafe { &mut *self.inner.get() }.as_mut() + } + + /// Borrows the contents of this lazy cell for the duration of the cell + /// itself. + /// + /// If the cell has not yet been filled, the cell is first filled using the + /// function provided. + /// + /// # Panics + /// + /// Panics if the cell becomes filled as a side effect of `f`. + pub fn borrow_with T>(&self, f: F) -> &T { + if let Some(value) = self.borrow() { + return value; + } + let value = f(); + if self.fill(value).is_err() { + panic!("borrow_with: cell was filled by closure") + } + self.borrow().unwrap() + } + + /// Same as `borrow_with`, but allows the initializing function to fail. + /// + /// # Panics + /// + /// Panics if the cell becomes filled as a side effect of `f`. + pub fn try_borrow_with(&self, f: F) -> Result<&T, E> + where F: FnOnce() -> Result + { + if let Some(value) = self.borrow() { + return Ok(value); + } + let value = f()?; + if self.fill(value).is_err() { + panic!("try_borrow_with: cell was filled by closure") + } + Ok(self.borrow().unwrap()) + } + + /// Consumes this `LazyCell`, returning the underlying value. + pub fn into_inner(self) -> Option { + unsafe { self.inner.into_inner() } + } +} + +impl LazyCell { + /// Returns a copy of the contents of the lazy cell. + /// + /// This function will return `Some` if the cell has been previously initialized, + /// and `None` if it has not yet been initialized. + pub fn get(&self) -> Option { + unsafe { *self.inner.get() } + } +} + +// Tracks the AtomicLazyCell inner state +const NONE: usize = 0; +const LOCK: usize = 1; +const SOME: usize = 2; + +/// A lazily filled `Cell`, with frozen contents. +#[derive(Debug, Default)] +pub struct AtomicLazyCell { + inner: UnsafeCell>, + state: AtomicUsize, +} + +impl AtomicLazyCell { + /// Creates a new, empty, `AtomicLazyCell`. + pub fn new() -> AtomicLazyCell { + AtomicLazyCell { + inner: UnsafeCell::new(None), + state: AtomicUsize::new(NONE), + } + } + + /// Put a value into this cell. + /// + /// This function will return `Err(value)` is the cell is already full. + pub fn fill(&self, t: T) -> Result<(), T> { + if NONE != self.state.compare_and_swap(NONE, LOCK, Ordering::Acquire) { + return Err(t); + } + + unsafe { *self.inner.get() = Some(t) }; + + if LOCK != self.state.compare_and_swap(LOCK, SOME, Ordering::Release) { + panic!("unable to release lock"); + } + + Ok(()) + } + + /// Test whether this cell has been previously filled. + pub fn filled(&self) -> bool { + self.state.load(Ordering::Acquire) == SOME + } + + /// Borrows the contents of this lazy cell for the duration of the cell + /// itself. + /// + /// This function will return `Some` if the cell has been previously + /// initialized, and `None` if it has not yet been initialized. + pub fn borrow(&self) -> Option<&T> { + match self.state.load(Ordering::Acquire) { + SOME => unsafe { &*self.inner.get() }.as_ref(), + _ => None, + } + } + + /// Consumes this `LazyCell`, returning the underlying value. + pub fn into_inner(self) -> Option { + unsafe { self.inner.into_inner() } + } +} + +impl AtomicLazyCell { + /// Returns a copy of the contents of the lazy cell. + /// + /// This function will return `Some` if the cell has been previously initialized, + /// and `None` if it has not yet been initialized. + pub fn get(&self) -> Option { + match self.state.load(Ordering::Acquire) { + SOME => unsafe { *self.inner.get() }, + _ => None, + } + } +} + +unsafe impl Sync for AtomicLazyCell {} + +unsafe impl Send for AtomicLazyCell {} + +#[cfg(test)] +mod tests { + use super::{AtomicLazyCell, LazyCell}; + + #[test] + fn test_borrow_from_empty() { + let lazycell: LazyCell = LazyCell::new(); + + let value = lazycell.borrow(); + assert_eq!(value, None); + + let value = lazycell.get(); + assert_eq!(value, None); + } + + #[test] + fn test_fill_and_borrow() { + let lazycell = LazyCell::new(); + + assert!(!lazycell.filled()); + lazycell.fill(1).unwrap(); + assert!(lazycell.filled()); + + let value = lazycell.borrow(); + assert_eq!(value, Some(&1)); + + let value = lazycell.get(); + assert_eq!(value, Some(1)); + } + + #[test] + fn test_borrow_mut() { + let mut lazycell = LazyCell::new(); + assert!(lazycell.borrow_mut().is_none()); + + lazycell.fill(1).unwrap(); + assert_eq!(lazycell.borrow_mut(), Some(&mut 1)); + + *lazycell.borrow_mut().unwrap() = 2; + assert_eq!(lazycell.borrow_mut(), Some(&mut 2)); + + // official way to reset the cell + lazycell = LazyCell::new(); + assert!(lazycell.borrow_mut().is_none()); + } + + #[test] + fn test_already_filled_error() { + let lazycell = LazyCell::new(); + + lazycell.fill(1).unwrap(); + assert_eq!(lazycell.fill(1), Err(1)); + } + + #[test] + fn test_borrow_with() { + let lazycell = LazyCell::new(); + + let value = lazycell.borrow_with(|| 1); + assert_eq!(&1, value); + } + + #[test] + fn test_borrow_with_already_filled() { + let lazycell = LazyCell::new(); + lazycell.fill(1).unwrap(); + + let value = lazycell.borrow_with(|| 1); + assert_eq!(&1, value); + } + + #[test] + fn test_borrow_with_not_called_when_filled() { + let lazycell = LazyCell::new(); + + lazycell.fill(1).unwrap(); + + let value = lazycell.borrow_with(|| 2); + assert_eq!(&1, value); + } + + #[test] + #[should_panic] + fn test_borrow_with_sound_with_reentrancy() { + // Kudos to dbaupp for discovering this issue + // https://www.reddit.com/r/rust/comments/5vs9rt/lazycell_a_rust_library_providing_a_lazilyfilled/de527xm/ + let lazycell: LazyCell> = LazyCell::new(); + + let mut reference: Option<&i32> = None; + + lazycell.borrow_with(|| { + let _ = lazycell.fill(Box::new(1)); + reference = lazycell.borrow().map(|r| &**r); + Box::new(2) + }); + } + + #[test] + fn test_try_borrow_with_ok() { + let lazycell = LazyCell::new(); + let result = lazycell.try_borrow_with::<(), _>(|| Ok(1)); + assert_eq!(result, Ok(&1)); + } + + #[test] + fn test_try_borrow_with_err() { + let lazycell = LazyCell::<()>::new(); + let result = lazycell.try_borrow_with(|| Err(1)); + assert_eq!(result, Err(1)); + } + + #[test] + fn test_try_borrow_with_already_filled() { + let lazycell = LazyCell::new(); + lazycell.fill(1).unwrap(); + let result = lazycell.try_borrow_with::<(), _>(|| unreachable!()); + assert_eq!(result, Ok(&1)); + } + + #[test] + #[should_panic] + fn test_try_borrow_with_sound_with_reentrancy() { + let lazycell: LazyCell> = LazyCell::new(); + + let mut reference: Option<&i32> = None; + + let _ = lazycell.try_borrow_with::<(), _>(|| { + let _ = lazycell.fill(Box::new(1)); + reference = lazycell.borrow().map(|r| &**r); + Ok(Box::new(2)) + }); + } + + #[test] + fn test_into_inner() { + let lazycell = LazyCell::new(); + + lazycell.fill(1).unwrap(); + let value = lazycell.into_inner(); + assert_eq!(value, Some(1)); + } + + #[test] + fn test_atomic_borrow_from_empty() { + let lazycell: AtomicLazyCell = AtomicLazyCell::new(); + + let value = lazycell.borrow(); + assert_eq!(value, None); + + let value = lazycell.get(); + assert_eq!(value, None); + } + + #[test] + fn test_atomic_fill_and_borrow() { + let lazycell = AtomicLazyCell::new(); + + assert!(!lazycell.filled()); + lazycell.fill(1).unwrap(); + assert!(lazycell.filled()); + + let value = lazycell.borrow(); + assert_eq!(value, Some(&1)); + + let value = lazycell.get(); + assert_eq!(value, Some(1)); + } + + #[test] + fn test_atomic_already_filled_panic() { + let lazycell = AtomicLazyCell::new(); + + lazycell.fill(1).unwrap(); + assert_eq!(1, lazycell.fill(1).unwrap_err()); + } + + #[test] + fn test_atomic_into_inner() { + let lazycell = AtomicLazyCell::new(); + + lazycell.fill(1).unwrap(); + let value = lazycell.into_inner(); + assert_eq!(value, Some(1)); + } +} diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/appveyor.yml cargo-0.26.0/vendor/lazy_static-0.2.11/appveyor.yml --- cargo-0.25.0/vendor/lazy_static-0.2.11/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,59 +0,0 @@ -environment: - global: - PROJECT_NAME: lazy_static - # When this was added there were revocation check failures when using the - # libcurl backend as libcurl checks by default, but rustup doesn't provide the - # switch to turn this off. Switch to Hyper which looks to not check for - # revocation by default like libcurl does. - RUSTUP_USE_REQWEST: 1 - CARGO_HTTP_CHECK_REVOKE: false - matrix: - # Stable channel - - TARGET: i686-pc-windows-gnu - CHANNEL: stable - - TARGET: i686-pc-windows-msvc - CHANNEL: stable - - TARGET: x86_64-pc-windows-gnu - CHANNEL: stable - - TARGET: x86_64-pc-windows-msvc - CHANNEL: stable - # Beta channel - - TARGET: i686-pc-windows-gnu - CHANNEL: beta - - TARGET: i686-pc-windows-msvc - CHANNEL: beta - - TARGET: x86_64-pc-windows-gnu - CHANNEL: beta - - TARGET: x86_64-pc-windows-msvc - CHANNEL: beta - # Nightly channel - - TARGET: i686-pc-windows-gnu - CHANNEL: nightly - - TARGET: i686-pc-windows-msvc - CHANNEL: nightly - - TARGET: x86_64-pc-windows-gnu - CHANNEL: nightly - - TARGET: x86_64-pc-windows-msvc - CHANNEL: nightly - -# Install Rust and Cargo -# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml) -install: - - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe - - rustup-init.exe -y --default-toolchain %CHANNEL% --default-host %TARGET% - - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - - if "%TARGET%" == "i686-pc-windows-gnu" set PATH=%PATH%;C:\msys64\mingw32\bin - - if "%TARGET%" == "x86_64-pc-windows-gnu" set PATH=%PATH%;C:\msys64\mingw64\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo build --verbose - - cargo test - - if [%CHANNEL%]==[nightly] ( - cargo clean && - cargo build --verbose --features "compiletest" && - cargo test --features "compiletest" - ) diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/.cargo-checksum.json cargo-0.26.0/vendor/lazy_static-0.2.11/.cargo-checksum.json --- cargo-0.25.0/vendor/lazy_static-0.2.11/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"76f033c7ad61445c5b347c7382dd1237847eb1bce590fe50365dcb33d546be73"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/Cargo.toml cargo-0.26.0/vendor/lazy_static-0.2.11/Cargo.toml --- cargo-0.25.0/vendor/lazy_static-0.2.11/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,43 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "lazy_static" -version = "0.2.11" -authors = ["Marvin Löbel "] -description = "A macro for declaring lazily evaluated statics in Rust." -documentation = "https://docs.rs/lazy_static" -readme = "README.md" -keywords = ["macro", "lazy", "static"] -categories = ["no-std", "rust-patterns", "memory-management"] -license = "MIT/Apache-2.0" -repository = "https://github.com/rust-lang-nursery/lazy-static.rs" -[dependencies.compiletest_rs] -version = "0.3" -optional = true - -[dependencies.spin] -version = "0.4.6" -optional = true - -[features] -compiletest = ["compiletest_rs"] -nightly = [] -spin_no_std = ["nightly", "spin"] -[badges.appveyor] -repository = "rust-lang-nursery/lazy-static.rs" - -[badges.maintenance] -status = "passively-maintained" - -[badges.travis-ci] -repository = "rust-lang-nursery/lazy-static.rs" diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/LICENSE-APACHE cargo-0.26.0/vendor/lazy_static-0.2.11/LICENSE-APACHE --- cargo-0.25.0/vendor/lazy_static-0.2.11/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/LICENSE-MIT cargo-0.26.0/vendor/lazy_static-0.2.11/LICENSE-MIT --- cargo-0.25.0/vendor/lazy_static-0.2.11/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2010 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/README.md cargo-0.26.0/vendor/lazy_static-0.2.11/README.md --- cargo-0.25.0/vendor/lazy_static-0.2.11/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,69 +0,0 @@ -lazy-static.rs -============== - -A macro for declaring lazily evaluated statics in Rust. - -Using this macro, it is possible to have `static`s that require code to be -executed at runtime in order to be initialized. -This includes anything requiring heap allocations, like vectors or hash maps, -as well as anything that requires non-const function calls to be computed. - -[![Travis-CI Status](https://travis-ci.org/rust-lang-nursery/lazy-static.rs.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/lazy-static.rs) - -# Getting Started - -[lazy-static.rs is available on crates.io](https://crates.io/crates/lazy_static). -It is recommended to look there for the newest released version, as well as links to the newest builds of the docs. - -At the point of the last update of this README, the latest published version could be used like this: - -Add the following dependency to your Cargo manifest... - -```toml -[dependencies] -lazy_static = "0.2" -``` - -...and see the [docs](https://docs.rs/lazy_static) for how to use it. - -# Example - -```rust -#[macro_use] -extern crate lazy_static; - -use std::collections::HashMap; - -lazy_static! { - static ref HASHMAP: HashMap = { - let mut m = HashMap::new(); - m.insert(0, "foo"); - m.insert(1, "bar"); - m.insert(2, "baz"); - m - }; -} - -fn main() { - // First access to `HASHMAP` initializes it - println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap()); - - // Any further access to `HASHMAP` just returns the computed value - println!("The entry for `1` is \"{}\".", HASHMAP.get(&1).unwrap()); -} -``` - -## 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. diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/src/core_lazy.rs cargo-0.26.0/vendor/lazy_static-0.2.11/src/core_lazy.rs --- cargo-0.25.0/vendor/lazy_static-0.2.11/src/core_lazy.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/src/core_lazy.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -// Copyright 2016 lazy-static.rs Developers -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -extern crate spin; - -use self::spin::Once; - -pub struct Lazy(Once); - -impl Lazy { - #[inline(always)] - pub const fn new() -> Self { - Lazy(Once::new()) - } - - #[inline(always)] - pub fn get(&'static self, builder: F) -> &T - where F: FnOnce() -> T - { - self.0.call_once(builder) - } -} - -#[macro_export] -macro_rules! __lazy_static_create { - ($NAME:ident, $T:ty) => { - static $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy::new(); - } -} diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/src/lazy.rs cargo-0.26.0/vendor/lazy_static-0.2.11/src/lazy.rs --- cargo-0.25.0/vendor/lazy_static-0.2.11/src/lazy.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/src/lazy.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,39 +0,0 @@ -// Copyright 2016 lazy-static.rs Developers -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -extern crate std; - -use self::std::prelude::v1::*; -use self::std::sync::Once; -pub use self::std::sync::ONCE_INIT; - -pub struct Lazy(pub *const T, pub Once); - -impl Lazy { - #[inline(always)] - pub fn get(&'static mut self, f: F) -> &T - where F: FnOnce() -> T - { - unsafe { - let r = &mut self.0; - self.1.call_once(|| { - *r = Box::into_raw(Box::new(f())); - }); - - &*self.0 - } - } -} - -unsafe impl Sync for Lazy {} - -#[macro_export] -macro_rules! __lazy_static_create { - ($NAME:ident, $T:ty) => { - static mut $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy(0 as *const $T, $crate::lazy::ONCE_INIT); - } -} diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/src/lib.rs cargo-0.26.0/vendor/lazy_static-0.2.11/src/lib.rs --- cargo-0.25.0/vendor/lazy_static-0.2.11/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,212 +0,0 @@ -// Copyright 2016 lazy-static.rs Developers -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -/*! -A macro for declaring lazily evaluated statics. - -Using this macro, it is possible to have `static`s that require code to be -executed at runtime in order to be initialized. -This includes anything requiring heap allocations, like vectors or hash maps, -as well as anything that requires function calls to be computed. - -# Syntax - -```ignore -lazy_static! { - [pub] static ref NAME_1: TYPE_1 = EXPR_1; - [pub] static ref NAME_2: TYPE_2 = EXPR_2; - ... - [pub] static ref NAME_N: TYPE_N = EXPR_N; -} -``` - -Attributes (including doc comments) are supported as well: - -```rust -# #[macro_use] -# extern crate lazy_static; -# fn main() { -lazy_static! { - /// This is an example for using doc comment attributes - static ref EXAMPLE: u8 = 42; -} -# } -``` - -# Semantics - -For a given `static ref NAME: TYPE = EXPR;`, the macro generates a unique type that -implements `Deref` and stores it in a static with name `NAME`. (Attributes end up -attaching to this type.) - -On first deref, `EXPR` gets evaluated and stored internally, such that all further derefs -can return a reference to the same object. Note that this can lead to deadlocks -if you have multiple lazy statics that depend on each other in their initialization. - -Apart from the lazy initialization, the resulting "static ref" variables -have generally the same properties as regular "static" variables: - -- Any type in them needs to fulfill the `Sync` trait. -- If the type has a destructor, then it will not run when the process exits. - -# Example - -Using the macro: - -```rust -#[macro_use] -extern crate lazy_static; - -use std::collections::HashMap; - -lazy_static! { - static ref HASHMAP: HashMap = { - let mut m = HashMap::new(); - m.insert(0, "foo"); - m.insert(1, "bar"); - m.insert(2, "baz"); - m - }; - static ref COUNT: usize = HASHMAP.len(); - static ref NUMBER: u32 = times_two(21); -} - -fn times_two(n: u32) -> u32 { n * 2 } - -fn main() { - println!("The map has {} entries.", *COUNT); - println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap()); - println!("A expensive calculation on a static results in: {}.", *NUMBER); -} -``` - -# Implementation details - -The `Deref` implementation uses a hidden static variable that is guarded by a atomic check on each access. On stable Rust, the macro may need to allocate each static on the heap. - -*/ - -#![cfg_attr(feature="spin_no_std", feature(const_fn))] -#![cfg_attr(feature="nightly", feature(unreachable))] - -#![doc(html_root_url = "https://docs.rs/lazy_static/0.2.11")] -#![no_std] - -#[cfg(not(feature="nightly"))] -#[doc(hidden)] -pub mod lazy; - -#[cfg(all(feature="nightly", not(feature="spin_no_std")))] -#[path="nightly_lazy.rs"] -#[doc(hidden)] -pub mod lazy; - -#[cfg(all(feature="nightly", feature="spin_no_std"))] -#[path="core_lazy.rs"] -#[doc(hidden)] -pub mod lazy; - -#[doc(hidden)] -pub use core::ops::Deref as __Deref; - -#[macro_export] -#[doc(hidden)] -macro_rules! __lazy_static_internal { - // optional visibility restrictions are wrapped in `()` to allow for - // explicitly passing otherwise implicit information about private items - ($(#[$attr:meta])* ($($vis:tt)*) static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { - __lazy_static_internal!(@MAKE TY, $(#[$attr])*, ($($vis)*), $N); - __lazy_static_internal!(@TAIL, $N : $T = $e); - lazy_static!($($t)*); - }; - (@TAIL, $N:ident : $T:ty = $e:expr) => { - impl $crate::__Deref for $N { - type Target = $T; - #[allow(unsafe_code)] - fn deref(&self) -> &$T { - unsafe { - #[inline(always)] - fn __static_ref_initialize() -> $T { $e } - - #[inline(always)] - unsafe fn __stability() -> &'static $T { - __lazy_static_create!(LAZY, $T); - LAZY.get(__static_ref_initialize) - } - __stability() - } - } - } - impl $crate::LazyStatic for $N { - fn initialize(lazy: &Self) { - let _ = &**lazy; - } - } - }; - // `vis` is wrapped in `()` to prevent parsing ambiguity - (@MAKE TY, $(#[$attr:meta])*, ($($vis:tt)*), $N:ident) => { - #[allow(missing_copy_implementations)] - #[allow(non_camel_case_types)] - #[allow(dead_code)] - $(#[$attr])* - $($vis)* struct $N {__private_field: ()} - #[doc(hidden)] - $($vis)* static $N: $N = $N {__private_field: ()}; - }; - () => () -} - -#[macro_export] -macro_rules! lazy_static { - ($(#[$attr:meta])* static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { - // use `()` to explicitly forward the information about private items - __lazy_static_internal!($(#[$attr])* () static ref $N : $T = $e; $($t)*); - }; - ($(#[$attr:meta])* pub static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { - __lazy_static_internal!($(#[$attr])* (pub) static ref $N : $T = $e; $($t)*); - }; - ($(#[$attr:meta])* pub ($($vis:tt)+) static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { - __lazy_static_internal!($(#[$attr])* (pub ($($vis)+)) static ref $N : $T = $e; $($t)*); - }; - () => () -} - -/// Support trait for enabling a few common operation on lazy static values. -/// -/// This is implemented by each defined lazy static, and -/// used by the free functions in this crate. -pub trait LazyStatic { - #[doc(hidden)] - fn initialize(lazy: &Self); -} - -/// Takes a shared reference to a lazy static and initializes -/// it if it has not been already. -/// -/// This can be used to control the initialization point of a lazy static. -/// -/// Example: -/// -/// ```rust -/// #[macro_use] -/// extern crate lazy_static; -/// -/// lazy_static! { -/// static ref BUFFER: Vec = (0..65537).collect(); -/// } -/// -/// fn main() { -/// lazy_static::initialize(&BUFFER); -/// -/// // ... -/// work_with_initialized_data(&BUFFER); -/// } -/// # fn work_with_initialized_data(_: &[u8]) {} -/// ``` -pub fn initialize(lazy: &T) { - LazyStatic::initialize(lazy); -} diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/src/nightly_lazy.rs cargo-0.26.0/vendor/lazy_static-0.2.11/src/nightly_lazy.rs --- cargo-0.25.0/vendor/lazy_static-0.2.11/src/nightly_lazy.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/src/nightly_lazy.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,43 +0,0 @@ -// Copyright 2016 lazy-static.rs Developers -// -// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be -// copied, modified, or distributed except according to those terms. - -extern crate std; - -use self::std::prelude::v1::*; -use self::std::sync::Once; -pub use self::std::sync::ONCE_INIT; - -pub struct Lazy(pub Option, pub Once); - -impl Lazy { - #[inline(always)] - pub fn get(&'static mut self, f: F) -> &T - where F: FnOnce() -> T - { - { - let r = &mut self.0; - self.1.call_once(|| { - *r = Some(f()); - }); - } - unsafe { - match self.0 { - Some(ref x) => x, - None => std::mem::unreachable(), - } - } - } -} - -unsafe impl Sync for Lazy {} - -#[macro_export] -macro_rules! __lazy_static_create { - ($NAME:ident, $T:ty) => { - static mut $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy(None, $crate::lazy::ONCE_INIT); - } -} diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/tests/compile-fail/incorrect_visibility_restriction.rs cargo-0.26.0/vendor/lazy_static-0.2.11/tests/compile-fail/incorrect_visibility_restriction.rs --- cargo-0.25.0/vendor/lazy_static-0.2.11/tests/compile-fail/incorrect_visibility_restriction.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/tests/compile-fail/incorrect_visibility_restriction.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ -// incorrect visibility restriction -#[macro_use] -extern crate lazy_static; - -lazy_static! { - pub(nonsense) static ref WRONG: () = (); - //~^ ERROR incorrect visibility restriction -} - -fn main() { } diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/tests/compile-fail/README.md cargo-0.26.0/vendor/lazy_static-0.2.11/tests/compile-fail/README.md --- cargo-0.25.0/vendor/lazy_static-0.2.11/tests/compile-fail/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/tests/compile-fail/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -This directory contains snippets of code that should yield a -warning/note/help/error at compilation. Syntax of annotations is described in -[rust documentation](https://github.com/rust-lang/rust/blob/master/src/test/COMPILER_TESTS.md). -For more information check out [`compiletest` crate](https://github.com/laumann/compiletest-rs). - -To run compile tests issue `cargo +nightly --test --features compiletest`. - -## Notes on working with `compiletest` crate - -* Currently code that is inside macro should not be annotated, as `compiletest` - crate cannot deal with the fact that macro invocations effectively changes - line numbering. To prevent this add a `// error-pattern:` - on the top of the file and make sure that you set `deny` lint level - if you want to test compiler message different than error. -* `compiletest` crate by default sets `allow(dead_code)` lint level so make sure - that you change it to something suiting your needs even if the warning is - issued prior to any macro invocation. -* If you get a message `error: 0 unexpected errors found, 1 expected errors not found` - despite the fact that some error was bound to occur don't worry - it's a known - issue in the `compiletest` crate and your error was probably not registered - - make sure that your annotations are correct and that you are setting correct - lint levels. diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_private.rs cargo-0.26.0/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_private.rs --- cargo-0.25.0/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_private.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_private.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -#[macro_use] -extern crate lazy_static; - -mod outer { - pub mod inner { - lazy_static! { - pub(in outer) static ref FOO: () = (); - } - } -} - -fn main() { - assert_eq!(*outer::inner::FOO, ()); //~ ERROR static `FOO` is private -} diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_sized.rs cargo-0.26.0/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_sized.rs --- cargo-0.25.0/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_sized.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/tests/compile-fail/static_is_sized.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -// error-pattern:the trait bound `str: std::marker::Sized` is not satisfied -#[macro_use] -extern crate lazy_static; - -lazy_static! { - pub static ref FOO: str = panic!(); -} - - -fn main() { -} diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/tests/compile-fail/static_never_used.rs cargo-0.26.0/vendor/lazy_static-0.2.11/tests/compile-fail/static_never_used.rs --- cargo-0.25.0/vendor/lazy_static-0.2.11/tests/compile-fail/static_never_used.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/tests/compile-fail/static_never_used.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ -// error-pattern:static item is never used: `UNUSED` -#![deny(dead_code)] -#[macro_use] -extern crate lazy_static; - -lazy_static! { - static ref UNUSED: () = (); -} - -fn main() { } diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/tests/compile_tests.rs cargo-0.26.0/vendor/lazy_static-0.2.11/tests/compile_tests.rs --- cargo-0.25.0/vendor/lazy_static-0.2.11/tests/compile_tests.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/tests/compile_tests.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -#![cfg(feature="compiletest")] -extern crate compiletest_rs as compiletest; - -fn run_mode(mode: &'static str) { - let mut config = compiletest::Config::default(); - config.mode = mode.parse().expect("Invalid mode"); - config.src_base = ["tests", mode].iter().collect(); - config.target_rustcflags = Some("-L target/debug/ -L target/debug/deps/".to_owned()); - - config.verbose = true; - - compiletest::run_tests(&config); -} - -#[test] -fn compile_test() { - run_mode("compile-fail"); -} diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/tests/no_std.rs cargo-0.26.0/vendor/lazy_static-0.2.11/tests/no_std.rs --- cargo-0.25.0/vendor/lazy_static-0.2.11/tests/no_std.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/tests/no_std.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -#![cfg(feature="spin_no_std")] -#![feature(const_fn)] - -#![no_std] - -#[macro_use] -extern crate lazy_static; - -lazy_static! { - /// Documentation! - pub static ref NUMBER: u32 = times_two(3); -} - -fn times_two(n: u32) -> u32 { - n * 2 -} - -#[test] -fn test_basic() { - assert_eq!(*NUMBER, 6); -} diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/tests/test.rs cargo-0.26.0/vendor/lazy_static-0.2.11/tests/test.rs --- cargo-0.25.0/vendor/lazy_static-0.2.11/tests/test.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/tests/test.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,164 +0,0 @@ -#![cfg_attr(feature="nightly", feature(const_fn))] - -#[macro_use] -extern crate lazy_static; -use std::collections::HashMap; - -lazy_static! { - /// Documentation! - pub static ref NUMBER: u32 = times_two(3); - - static ref ARRAY_BOXES: [Box; 3] = [Box::new(1), Box::new(2), Box::new(3)]; - - /// More documentation! - #[allow(unused_variables)] - #[derive(Copy, Clone, Debug)] - pub static ref STRING: String = "hello".to_string(); - - static ref HASHMAP: HashMap = { - let mut m = HashMap::new(); - m.insert(0, "abc"); - m.insert(1, "def"); - m.insert(2, "ghi"); - m - }; - - // This should not compile if the unsafe is removed. - static ref UNSAFE: u32 = unsafe { - std::mem::transmute::(-1) - }; -} - -lazy_static! { - static ref S1: &'static str = "a"; - static ref S2: &'static str = "b"; -} -lazy_static! { - static ref S3: String = [*S1, *S2].join(""); -} - -#[test] -fn s3() { - assert_eq!(&*S3, "ab"); -} - -fn times_two(n: u32) -> u32 { - n * 2 -} - -#[test] -fn test_basic() { - assert_eq!(&**STRING, "hello"); - assert_eq!(*NUMBER, 6); - assert!(HASHMAP.get(&1).is_some()); - assert!(HASHMAP.get(&3).is_none()); - assert_eq!(&*ARRAY_BOXES, &[Box::new(1), Box::new(2), Box::new(3)]); - assert_eq!(*UNSAFE, std::u32::MAX); -} - -#[test] -fn test_repeat() { - assert_eq!(*NUMBER, 6); - assert_eq!(*NUMBER, 6); - assert_eq!(*NUMBER, 6); -} - -#[test] -fn test_meta() { - // this would not compile if STRING were not marked #[derive(Copy, Clone)] - let copy_of_string = STRING; - // just to make sure it was copied - assert!(&STRING as *const _ != ©_of_string as *const _); - - // this would not compile if STRING were not marked #[derive(Debug)] - assert_eq!(format!("{:?}", STRING), "STRING { __private_field: () }".to_string()); -} - -mod visibility { - lazy_static! { - pub static ref FOO: Box = Box::new(0); - static ref BAR: Box = Box::new(98); - } - - pub mod inner { - lazy_static! { - pub(in visibility) static ref BAZ: Box = Box::new(42); - pub(crate) static ref BAG: Box = Box::new(37); - } - } - - #[test] - fn sub_test() { - assert_eq!(**FOO, 0); - assert_eq!(**BAR, 98); - assert_eq!(**inner::BAZ, 42); - assert_eq!(**inner::BAG, 37); - } -} - -#[test] -fn test_visibility() { - assert_eq!(*visibility::FOO, Box::new(0)); - assert_eq!(*visibility::inner::BAG, Box::new(37)); -} - -// This should not cause a warning about a missing Copy implementation -lazy_static! { - pub static ref VAR: i32 = { 0 }; -} - -#[derive(Copy, Clone, Debug, PartialEq)] -struct X; -struct Once(X); -const ONCE_INIT: Once = Once(X); -static DATA: X = X; -static ONCE: X = X; -fn require_sync() -> X { X } -fn transmute() -> X { X } -fn __static_ref_initialize() -> X { X } -fn test(_: Vec) -> X { X } - -// All these names should not be shadowed -lazy_static! { - static ref ITEM_NAME_TEST: X = { - test(vec![X, Once(X).0, ONCE_INIT.0, DATA, ONCE, - require_sync(), transmute(), - // Except this, which will sadly be shadowed by internals: - // __static_ref_initialize() - ]) - }; -} - -#[test] -fn item_name_shadowing() { - assert_eq!(*ITEM_NAME_TEST, X); -} - -use std::sync::atomic::AtomicBool; -use std::sync::atomic::ATOMIC_BOOL_INIT; -use std::sync::atomic::Ordering::SeqCst; - -static PRE_INIT_FLAG: AtomicBool = ATOMIC_BOOL_INIT; - -lazy_static! { - static ref PRE_INIT: () = { - PRE_INIT_FLAG.store(true, SeqCst); - () - }; -} - -#[test] -fn pre_init() { - assert_eq!(PRE_INIT_FLAG.load(SeqCst), false); - lazy_static::initialize(&PRE_INIT); - assert_eq!(PRE_INIT_FLAG.load(SeqCst), true); -} - -lazy_static! { - static ref LIFETIME_NAME: for<'a> fn(&'a u8) = { fn f(_: &u8) {} f }; -} - -#[test] -fn lifetime_name() { - let _ = LIFETIME_NAME; -} diff -Nru cargo-0.25.0/vendor/lazy_static-0.2.11/.travis.yml cargo-0.26.0/vendor/lazy_static-0.2.11/.travis.yml --- cargo-0.25.0/vendor/lazy_static-0.2.11/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/lazy_static-0.2.11/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -language: rust -rust: -- nightly -- beta -- stable -before_script: -- | - pip install 'travis-cargo<0.2' --user && - export PATH=`python -m site --user-base`/bin:$PATH -script: -- | - travis-cargo build && - travis-cargo test && - travis-cargo bench && - travis-cargo --only nightly build -- --features spin_no_std && - travis-cargo --only nightly test -- --features spin_no_std && - travis-cargo --only nightly bench -- --features spin_no_std && - travis-cargo --only nightly clean && - travis-cargo --only nightly build -- --features compiletest && - travis-cargo --only nightly test -- --features compiletest && - travis-cargo --only nightly clean && - travis-cargo --only stable doc -after_success: -- travis-cargo --only stable doc-upload -env: - global: - - TRAVIS_CARGO_NIGHTLY_FEATURE=nightly - - secure: YXu24LptjeYirjWYjWGsMT2m3mB7LvQATE6TVo7VEUXv8GYoy2ORIHD83PeImxC93MmZ01QeUezRzuCW51ZcK92VnNSBttlF60SvIX18VsJrV92tsAhievFstqYQ+fB8DIuQ8noU0jPz7GpI+R9dlTRSImAqWOnVIghA+Wzz7Js= -os: - - linux - - osx diff -Nru cargo-0.25.0/vendor/libc-0.2.36/appveyor.yml cargo-0.26.0/vendor/libc-0.2.36/appveyor.yml --- cargo-0.25.0/vendor/libc-0.2.36/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -environment: - # When this was added there were revocation check failures when using the - # libcurl backend as libcurl checks by default, but rustup doesn't provide the - # switch to turn this off. Switch to Hyper which looks to not check for - # revocation by default like libcurl does. - RUSTUP_USE_HYPER: 1 - CARGO_HTTP_CHECK_REVOKE: false - matrix: - - TARGET: x86_64-pc-windows-gnu - MSYS2_BITS: 64 - - TARGET: i686-pc-windows-gnu - MSYS2_BITS: 32 - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc -install: - - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe - - rustup-init.exe -y --default-host %TARGET% - - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - - if defined MSYS2_BITS set PATH=%PATH%;C:\msys64\mingw%MSYS2_BITS%\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test --target %TARGET% - - cargo test --manifest-path libc-test/Cargo.toml --target %TARGET% diff -Nru cargo-0.25.0/vendor/libc-0.2.36/.cargo-checksum.json cargo-0.26.0/vendor/libc-0.2.36/.cargo-checksum.json --- cargo-0.25.0/vendor/libc-0.2.36/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"1e5d97d6708edaa407429faa671b942dc0f2727222fb6b6539bf1db936e4b121"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/libc-0.2.36/Cargo.toml cargo-0.26.0/vendor/libc-0.2.36/Cargo.toml --- cargo-0.25.0/vendor/libc-0.2.36/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "libc" -version = "0.2.36" -authors = ["The Rust Project Developers"] -description = "A library for types and bindings to native C functions often found in libc or\nother common platform libraries.\n" -homepage = "https://github.com/rust-lang/libc" -documentation = "http://doc.rust-lang.org/libc" -readme = "README.md" -license = "MIT/Apache-2.0" -repository = "https://github.com/rust-lang/libc" - -[features] -default = ["use_std"] -use_std = [] -[badges.appveyor] -project_name = "rust-lang-libs/libc" -repository = "rust-lang/libc" - -[badges.travis-ci] -repository = "rust-lang/libc" diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/android-install-ndk.sh cargo-0.26.0/vendor/libc-0.2.36/ci/android-install-ndk.sh --- cargo-0.25.0/vendor/libc-0.2.36/ci/android-install-ndk.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/android-install-ndk.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -#!/bin/sh -# Copyright 2016 The Rust Project Developers. See the COPYRIGHT -# file at the top-level directory of this distribution and at -# http://rust-lang.org/COPYRIGHT. -# -# Licensed under the Apache License, Version 2.0 or the MIT license -# , at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -set -ex - -curl -O https://dl.google.com/android/repository/android-ndk-r15b-linux-x86_64.zip -unzip -q android-ndk-r15b-linux-x86_64.zip - -case "$1" in - aarch64) - arch=arm64 - ;; - - i686) - arch=x86 - ;; - - *) - arch=$1 - ;; -esac; - -android-ndk-r15b/build/tools/make_standalone_toolchain.py \ - --unified-headers \ - --install-dir /android/ndk-$1 \ - --arch $arch \ - --api 24 - -rm -rf ./android-ndk-r15b-linux-x86_64.zip ./android-ndk-r15b diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/android-install-sdk.sh cargo-0.26.0/vendor/libc-0.2.36/ci/android-install-sdk.sh --- cargo-0.25.0/vendor/libc-0.2.36/ci/android-install-sdk.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/android-install-sdk.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -#!/bin/sh -# Copyright 2016 The Rust Project Developers. See the COPYRIGHT -# file at the top-level directory of this distribution and at -# http://rust-lang.org/COPYRIGHT. -# -# Licensed under the Apache License, Version 2.0 or the MIT license -# , at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -set -ex - -# Prep the SDK and emulator -# -# Note that the update process requires that we accept a bunch of licenses, and -# we can't just pipe `yes` into it for some reason, so we take the same strategy -# located in https://github.com/appunite/docker by just wrapping it in a script -# which apparently magically accepts the licenses. - -mkdir sdk -curl https://dl.google.com/android/repository/sdk-tools-linux-3859397.zip -O -unzip -d sdk sdk-tools-linux-3859397.zip - -case "$1" in - arm | armv7) - abi=armeabi-v7a - ;; - - aarch64) - abi=arm64-v8a - ;; - - i686) - abi=x86 - ;; - - x86_64) - abi=x86_64 - ;; - - *) - echo "invalid arch: $1" - exit 1 - ;; -esac; - -# --no_https avoids -# javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found -echo "yes" | \ - ./sdk/tools/bin/sdkmanager --no_https \ - "emulator" \ - "platform-tools" \ - "platforms;android-24" \ - "system-images;android-24;default;$abi" - -echo "no" | - ./sdk/tools/bin/avdmanager create avd \ - --name $1 \ - --package "system-images;android-24;default;$abi" diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/android-sysimage.sh cargo-0.26.0/vendor/libc-0.2.36/ci/android-sysimage.sh --- cargo-0.25.0/vendor/libc-0.2.36/ci/android-sysimage.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/android-sysimage.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,52 +0,0 @@ -# Copyright 2017 The Rust Project Developers. See the COPYRIGHT -# file at the top-level directory of this distribution and at -# http://rust-lang.org/COPYRIGHT. -# -# Licensed under the Apache License, Version 2.0 or the MIT license -# , at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -set -ex - -URL=https://dl.google.com/android/repository/sys-img/android - -main() { - local arch=$1 - local name=$2 - local dest=/system - local td=$(mktemp -d) - - apt-get install --no-install-recommends e2tools - - pushd $td - curl -O $URL/$name - unzip -q $name - - local system=$(find . -name system.img) - mkdir -p $dest/{bin,lib,lib64} - - # Extract android linker and libraries to /system - # This allows android executables to be run directly (or with qemu) - if [ $arch = "x86_64" -o $arch = "arm64" ]; then - e2cp -p $system:/bin/linker64 $dest/bin/ - e2cp -p $system:/lib64/libdl.so $dest/lib64/ - e2cp -p $system:/lib64/libc.so $dest/lib64/ - e2cp -p $system:/lib64/libm.so $dest/lib64/ - else - e2cp -p $system:/bin/linker $dest/bin/ - e2cp -p $system:/lib/libdl.so $dest/lib/ - e2cp -p $system:/lib/libc.so $dest/lib/ - e2cp -p $system:/lib/libm.so $dest/lib/ - fi - - # clean up - apt-get purge --auto-remove -y e2tools - - popd - - rm -rf $td -} - -main "${@}" diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/aarch64-linux-android/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/aarch64-linux-android/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/aarch64-linux-android/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/aarch64-linux-android/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -FROM ubuntu:16.04 - -RUN dpkg --add-architecture i386 && \ - apt-get update && \ - apt-get install -y --no-install-recommends \ - file \ - curl \ - ca-certificates \ - python \ - unzip \ - expect \ - openjdk-9-jre \ - libstdc++6:i386 \ - libpulse0 \ - gcc \ - libc6-dev - -WORKDIR /android/ -COPY android* /android/ - -ENV ANDROID_ARCH=aarch64 -ENV PATH=$PATH:/android/ndk-$ANDROID_ARCH/bin:/android/sdk/tools:/android/sdk/platform-tools - -RUN sh /android/android-install-ndk.sh $ANDROID_ARCH -RUN sh /android/android-install-sdk.sh $ANDROID_ARCH -RUN mv /root/.android /tmp -RUN chmod 777 -R /tmp/.android -RUN chmod 755 /android/sdk/tools/* /android/sdk/emulator/qemu/linux-x86_64/* - -ENV PATH=$PATH:/rust/bin \ - CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER=aarch64-linux-android-gcc \ - CARGO_TARGET_AARCH64_LINUX_ANDROID_RUNNER=/tmp/runtest \ - HOME=/tmp - -ADD runtest-android.rs /tmp/runtest.rs -ENTRYPOINT [ \ - "bash", \ - "-c", \ - # set SHELL so android can detect a 64bits system, see - # http://stackoverflow.com/a/41789144 - "SHELL=/bin/dash /android/sdk/emulator/emulator @aarch64 -no-window & \ - rustc /tmp/runtest.rs -o /tmp/runtest && \ - exec \"$@\"", \ - "--" \ -] diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/aarch64-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/aarch64-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/aarch64-unknown-linux-gnu/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/aarch64-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -FROM ubuntu:17.10 -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc libc6-dev ca-certificates \ - gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user -ENV CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc \ - CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUNNER="qemu-aarch64 -L /usr/aarch64-linux-gnu" \ - PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/aarch64-unknown-linux-musl/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/aarch64-unknown-linux-musl/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/aarch64-unknown-linux-musl/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/aarch64-unknown-linux-musl/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -FROM ubuntu:17.10 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc make libc6-dev git curl ca-certificates \ - gcc-aarch64-linux-gnu qemu-user -RUN curl https://www.musl-libc.org/releases/musl-1.1.16.tar.gz | \ - tar xzf - && \ - cd musl-1.1.16 && \ - CC=aarch64-linux-gnu-gcc \ - ./configure --prefix=/musl-aarch64 --enable-wrapper=yes && \ - make install -j4 && \ - cd .. && \ - rm -rf musl-1.1.16 && \ -# Install linux kernel headers sanitized for use with musl - curl -L https://github.com/sabotage-linux/kernel-headers/archive/v3.12.6-5.tar.gz | \ - tar xzf - && \ - cd kernel-headers-3.12.6-5 && \ - make ARCH=arm64 prefix=/musl-aarch64 install -j4 && \ - cd .. && \ - rm -rf kernel-headers-3.12.6-5 - -# FIXME: shouldn't need the `-lgcc` here, shouldn't that be in libstd? -ENV PATH=$PATH:/musl-aarch64/bin:/rust/bin \ - CC_aarch64_unknown_linux_musl=musl-gcc \ - RUSTFLAGS='-Clink-args=-lgcc' \ - CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=musl-gcc \ - CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUNNER="qemu-aarch64 -L /musl-aarch64" diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/arm-linux-androideabi/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/arm-linux-androideabi/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/arm-linux-androideabi/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/arm-linux-androideabi/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -FROM ubuntu:16.04 - -RUN dpkg --add-architecture i386 && \ - apt-get update && \ - apt-get install -y --no-install-recommends \ - file \ - curl \ - ca-certificates \ - python \ - unzip \ - expect \ - openjdk-9-jre \ - libstdc++6:i386 \ - libpulse0 \ - gcc \ - libc6-dev - -WORKDIR /android/ -COPY android* /android/ - -ENV ANDROID_ARCH=arm -ENV PATH=$PATH:/android/ndk-$ANDROID_ARCH/bin:/android/sdk/tools:/android/sdk/platform-tools - -RUN sh /android/android-install-ndk.sh $ANDROID_ARCH -RUN sh /android/android-install-sdk.sh $ANDROID_ARCH -RUN mv /root/.android /tmp -RUN chmod 777 -R /tmp/.android -RUN chmod 755 /android/sdk/tools/* /android/sdk/emulator/qemu/linux-x86_64/* - -ENV PATH=$PATH:/rust/bin \ - CARGO_TARGET_ARM_LINUX_ANDROIDEABI_LINKER=arm-linux-androideabi-gcc \ - CARGO_TARGET_ARM_LINUX_ANDROIDEABI_RUNNER=/tmp/runtest \ - HOME=/tmp - -ADD runtest-android.rs /tmp/runtest.rs -ENTRYPOINT [ \ - "bash", \ - "-c", \ - # set SHELL so android can detect a 64bits system, see - # http://stackoverflow.com/a/41789144 - "SHELL=/bin/dash /android/sdk/emulator/emulator @arm -no-window & \ - rustc /tmp/runtest.rs -o /tmp/runtest && \ - exec \"$@\"", \ - "--" \ -] diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -FROM ubuntu:17.10 -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc libc6-dev ca-certificates \ - gcc-arm-linux-gnueabihf libc6-dev-armhf-cross qemu-user -ENV CARGO_TARGET_ARM_UNKNOWN_LINUX_GNUEABIHF_LINKER=arm-linux-gnueabihf-gcc \ - CARGO_TARGET_ARM_UNKNOWN_LINUX_GNUEABIHF_RUNNER="qemu-arm -L /usr/arm-linux-gnueabihf" \ - PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/arm-unknown-linux-musleabihf/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/arm-unknown-linux-musleabihf/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/arm-unknown-linux-musleabihf/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/arm-unknown-linux-musleabihf/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -FROM ubuntu:17.10 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc make libc6-dev git curl ca-certificates \ - gcc-arm-linux-gnueabihf qemu-user - -RUN curl https://www.musl-libc.org/releases/musl-1.1.16.tar.gz | tar xzf - -WORKDIR /musl-1.1.16 -RUN CC=arm-linux-gnueabihf-gcc \ - CFLAGS="-march=armv6 -marm" \ - ./configure --prefix=/musl-arm --enable-wrapper=yes -RUN make install -j4 - -# Install linux kernel headers sanitized for use with musl -RUN \ - curl -L https://github.com/sabotage-linux/kernel-headers/archive/v3.12.6-5.tar.gz | \ - tar xzf - && \ - cd kernel-headers-3.12.6-5 && \ - make ARCH=arm prefix=/musl-arm install -j4 && \ - cd .. && \ - rm -rf kernel-headers-3.12.6-5 -ENV PATH=$PATH:/musl-arm/bin:/rust/bin \ - CC_arm_unknown_linux_musleabihf=musl-gcc \ - CARGO_TARGET_ARM_UNKNOWN_LINUX_MUSLEABIHF_LINKER=musl-gcc \ - CARGO_TARGET_ARM_UNKNOWN_LINUX_MUSLEABIHF_RUNNER="qemu-arm -L /musl-arm" diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/asmjs-unknown-emscripten/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/asmjs-unknown-emscripten/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/asmjs-unknown-emscripten/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/asmjs-unknown-emscripten/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -FROM ubuntu:16.04 - -RUN apt-get update && \ - apt-get install -y --no-install-recommends \ - ca-certificates \ - curl \ - gcc \ - git \ - libc6-dev \ - python \ - xz-utils - -COPY emscripten.sh / -RUN bash /emscripten.sh - -ENV PATH=$PATH:/rust/bin \ - CARGO_TARGET_ASMJS_UNKNOWN_EMSCRIPTEN_RUNNER=node - -COPY emscripten-entry.sh / -ENTRYPOINT ["/emscripten-entry.sh"] diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/i686-linux-android/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/i686-linux-android/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/i686-linux-android/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/i686-linux-android/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -FROM ubuntu:16.04 - -RUN dpkg --add-architecture i386 && \ - apt-get update && \ - apt-get install -y --no-install-recommends \ - file \ - curl \ - ca-certificates \ - python \ - unzip \ - expect \ - openjdk-9-jre \ - libstdc++6:i386 \ - libpulse0 \ - gcc \ - libc6-dev - -WORKDIR /android/ -COPY android* /android/ - -ENV ANDROID_ARCH=i686 -ENV PATH=$PATH:/android/ndk-$ANDROID_ARCH/bin:/android/sdk/tools:/android/sdk/platform-tools - -RUN sh /android/android-install-ndk.sh $ANDROID_ARCH -RUN sh /android/android-install-sdk.sh $ANDROID_ARCH -RUN mv /root/.android /tmp -RUN chmod 777 -R /tmp/.android -RUN chmod 755 /android/sdk/tools/* /android/sdk/emulator/qemu/linux-x86_64/* - -ENV PATH=$PATH:/rust/bin \ - CARGO_TARGET_I686_LINUX_ANDROID_LINKER=i686-linux-android-gcc \ - CARGO_TARGET_I686_LINUX_ANDROID_RUNNER=/tmp/runtest \ - HOME=/tmp - -ADD runtest-android.rs /tmp/runtest.rs -ENTRYPOINT [ \ - "bash", \ - "-c", \ - # set SHELL so android can detect a 64bits system, see - # http://stackoverflow.com/a/41789144 - "SHELL=/bin/dash /android/sdk/emulator/emulator @i686 -no-window -no-accel & \ - rustc /tmp/runtest.rs -o /tmp/runtest && \ - exec \"$@\"", \ - "--" \ -] diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/i686-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/i686-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/i686-unknown-linux-gnu/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/i686-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -FROM ubuntu:17.04 -RUN apt-get update -RUN apt-get install -y --no-install-recommends \ - gcc-multilib libc6-dev ca-certificates -ENV PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/i686-unknown-linux-musl/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/i686-unknown-linux-musl/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/i686-unknown-linux-musl/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/i686-unknown-linux-musl/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -FROM ubuntu:17.10 - -RUN dpkg --add-architecture i386 -RUN apt-get update -RUN apt-get install -y --no-install-recommends \ - gcc-multilib make libc6-dev git curl ca-certificates libc6:i386 -# Below we're cross-compiling musl for i686 using the system compiler on an -# x86_64 system. This is an awkward thing to be doing and so we have to jump -# through a couple hoops to get musl to be happy. In particular: -# -# * We specifically pass -m32 in CFLAGS and override CC when running ./configure, -# since otherwise the script will fail to find a compiler. -# * We manually unset CROSS_COMPILE when running make; otherwise the makefile -# will call the non-existent binary 'i686-ar'. -RUN curl https://www.musl-libc.org/releases/musl-1.1.15.tar.gz | \ - tar xzf - && \ - cd musl-1.1.15 && \ - CC=gcc CFLAGS=-m32 ./configure --prefix=/musl-i686 --disable-shared --target=i686 && \ - make CROSS_COMPILE= install -j4 && \ - cd .. && \ - rm -rf musl-1.1.15 && \ -# Install linux kernel headers sanitized for use with musl - curl -L https://github.com/sabotage-linux/kernel-headers/archive/v3.12.6-5.tar.gz | \ - tar xzf - && \ - cd kernel-headers-3.12.6-5 && \ - make ARCH=i386 prefix=/musl-i686 install -j4 && \ - cd .. && \ - rm -rf kernel-headers-3.12.6-5 -ENV PATH=$PATH:/musl-i686/bin:/rust/bin \ - CC_i686_unknown_linux_musl=musl-gcc diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -FROM ubuntu:17.10 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc libc6-dev qemu-user ca-certificates \ - gcc-mips64el-linux-gnuabi64 libc6-dev-mips64el-cross \ - qemu-system-mips64el - -ENV CARGO_TARGET_MIPS64EL_UNKNOWN_LINUX_GNUABI64_LINKER=mips64el-linux-gnuabi64-gcc \ - CARGO_TARGET_MIPS64EL_UNKNOWN_LINUX_GNUABI64_RUNNER="qemu-mips64el -L /usr/mips64el-linux-gnuabi64" \ - CC_mips64el_unknown_linux_gnuabi64=mips64el-linux-gnuabi64-gcc \ - PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -FROM ubuntu:17.10 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc libc6-dev qemu-user ca-certificates \ - gcc-mips64-linux-gnuabi64 libc6-dev-mips64-cross \ - qemu-system-mips64 - -ENV CARGO_TARGET_MIPS64_UNKNOWN_LINUX_GNUABI64_LINKER=mips64-linux-gnuabi64-gcc \ - CARGO_TARGET_MIPS64_UNKNOWN_LINUX_GNUABI64_RUNNER="qemu-mips64 -L /usr/mips64-linux-gnuabi64" \ - CC_mips64_unknown_linux_gnuabi64=mips64-linux-gnuabi64-gcc \ - PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/mipsel-unknown-linux-musl/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/mipsel-unknown-linux-musl/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/mipsel-unknown-linux-musl/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/mipsel-unknown-linux-musl/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -FROM ubuntu:17.10 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc libc6-dev qemu-user ca-certificates qemu-system-mips curl \ - bzip2 - -RUN mkdir /toolchain - -# Note that this originally came from: -# https://downloads.openwrt.org/snapshots/trunk/malta/generic/OpenWrt-Toolchain-malta-le_gcc-5.3.0_musl-1.1.15.Linux-x86_64.tar.bz2 -RUN curl -L https://s3-us-west-1.amazonaws.com/rust-lang-ci2/libc/OpenWrt-Toolchain-malta-le_gcc-5.3.0_musl-1.1.15.Linux-x86_64.tar.bz2 | \ - tar xjf - -C /toolchain --strip-components=2 - -ENV PATH=$PATH:/rust/bin:/toolchain/bin \ - CC_mipsel_unknown_linux_musl=mipsel-openwrt-linux-gcc \ - CARGO_TARGET_MIPSEL_UNKNOWN_LINUX_MUSL_LINKER=mipsel-openwrt-linux-gcc \ - CARGO_TARGET_MIPSEL_UNKNOWN_LINUX_MUSL_RUNNER="qemu-mipsel -L /toolchain" diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/mips-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/mips-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/mips-unknown-linux-gnu/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/mips-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ -FROM ubuntu:17.10 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc libc6-dev qemu-user ca-certificates \ - gcc-mips-linux-gnu libc6-dev-mips-cross \ - qemu-system-mips - -ENV CARGO_TARGET_MIPS_UNKNOWN_LINUX_GNU_LINKER=mips-linux-gnu-gcc \ - CARGO_TARGET_MIPS_UNKNOWN_LINUX_GNU_RUNNER="qemu-mips -L /usr/mips-linux-gnu" \ - PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/mips-unknown-linux-musl/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/mips-unknown-linux-musl/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/mips-unknown-linux-musl/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/mips-unknown-linux-musl/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -FROM ubuntu:17.10 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc libc6-dev qemu-user ca-certificates qemu-system-mips curl \ - bzip2 - -RUN mkdir /toolchain - -# Note that this originally came from: -# https://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/OpenWrt-SDK-ar71xx-generic_gcc-5.3.0_musl-1.1.15.Linux-x86_64.tar.bz2 -RUN curl -L https://s3-us-west-1.amazonaws.com/rust-lang-ci2/libc/OpenWrt-SDK-ar71xx-generic_gcc-5.3.0_musl-1.1.15.Linux-x86_64.tar.bz2 | \ - tar xjf - -C /toolchain --strip-components=1 - -ENV PATH=$PATH:/rust/bin:/toolchain/staging_dir/toolchain-mips_34kc_gcc-5.3.0_musl-1.1.15/bin \ - CC_mips_unknown_linux_musl=mips-openwrt-linux-gcc \ - CARGO_TARGET_MIPS_UNKNOWN_LINUX_MUSL_LINKER=mips-openwrt-linux-gcc \ - CARGO_TARGET_MIPS_UNKNOWN_LINUX_MUSL_RUNNER="qemu-mips -L /toolchain/staging_dir/toolchain-mips_34kc_gcc-5.3.0_musl-1.1.15" diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -FROM ubuntu:17.10 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc libc6-dev qemu-user ca-certificates \ - gcc-powerpc64le-linux-gnu libc6-dev-ppc64el-cross \ - qemu-system-ppc - -ENV CARGO_TARGET_POWERPC64LE_UNKNOWN_LINUX_GNU_LINKER=powerpc64le-linux-gnu-gcc \ - CARGO_TARGET_POWERPC64LE_UNKNOWN_LINUX_GNU_RUNNER="qemu-ppc64le -L /usr/powerpc64le-linux-gnu" \ - CC=powerpc64le-linux-gnu-gcc \ - PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -FROM ubuntu:17.10 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc libc6-dev qemu-user ca-certificates \ - gcc-powerpc64-linux-gnu libc6-dev-ppc64-cross \ - qemu-system-ppc - -ENV CARGO_TARGET_POWERPC64_UNKNOWN_LINUX_GNU_LINKER=powerpc64-linux-gnu-gcc \ - CARGO_TARGET_POWERPC64_UNKNOWN_LINUX_GNU_RUNNER="qemu-ppc64 -L /usr/powerpc64-linux-gnu" \ - CC=powerpc64-linux-gnu-gcc \ - PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/powerpc-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/powerpc-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/powerpc-unknown-linux-gnu/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/powerpc-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ -FROM ubuntu:17.10 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - gcc libc6-dev qemu-user ca-certificates \ - gcc-powerpc-linux-gnu libc6-dev-powerpc-cross \ - qemu-system-ppc - -ENV CARGO_TARGET_POWERPC_UNKNOWN_LINUX_GNU_LINKER=powerpc-linux-gnu-gcc \ - CARGO_TARGET_POWERPC_UNKNOWN_LINUX_GNU_RUNNER="qemu-ppc -L /usr/powerpc-linux-gnu" \ - PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/s390x-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/s390x-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/s390x-unknown-linux-gnu/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/s390x-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -FROM ubuntu:17.10 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - curl ca-certificates \ - gcc libc6-dev \ - gcc-s390x-linux-gnu libc6-dev-s390x-cross \ - qemu-system-s390x \ - cpio - -COPY linux-s390x.sh / -RUN bash /linux-s390x.sh - -COPY test-runner-linux / - -ENV CARGO_TARGET_S390X_UNKNOWN_LINUX_GNU_LINKER=s390x-linux-gnu-gcc \ - CARGO_TARGET_S390X_UNKNOWN_LINUX_GNU_RUNNER="/test-runner-linux s390x" \ - CC_s390x_unknown_linux_gnu=s390x-linux-gnu-gcc \ - PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/sparc64-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/sparc64-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/sparc64-unknown-linux-gnu/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/sparc64-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -# link fails on 17.10 -FROM ubuntu:17.04 - -RUN apt-get update && apt-get install -y --no-install-recommends \ - curl ca-certificates \ - gcc libc6-dev \ - gcc-sparc64-linux-gnu libc6-dev-sparc64-cross \ - qemu-system-sparc64 openbios-sparc seabios ipxe-qemu \ - p7zip-full cpio - -COPY linux-sparc64.sh / -RUN bash /linux-sparc64.sh - -COPY test-runner-linux / - -ENV CARGO_TARGET_SPARC64_UNKNOWN_LINUX_GNU_LINKER=sparc64-linux-gnu-gcc \ - CARGO_TARGET_SPARC64_UNKNOWN_LINUX_GNU_RUNNER="/test-runner-linux sparc64" \ - CC_sparc64_unknown_linux_gnu=sparc64-linux-gnu-gcc \ - PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/wasm32-unknown-emscripten/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/wasm32-unknown-emscripten/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/wasm32-unknown-emscripten/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/wasm32-unknown-emscripten/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -FROM ubuntu:16.04 - -RUN apt-get update && \ - apt-get install -y --no-install-recommends \ - ca-certificates \ - curl \ - gcc \ - git \ - libc6-dev \ - python \ - xz-utils - -COPY emscripten.sh / -RUN bash /emscripten.sh - -ENV PATH=$PATH:/rust/bin \ - CARGO_TARGET_WASM32_UNKNOWN_EMSCRIPTEN_RUNNER=node-wrapper.sh - -COPY emscripten-entry.sh / -COPY docker/wasm32-unknown-emscripten/node-wrapper.sh /usr/local/bin/node-wrapper.sh -ENTRYPOINT ["/emscripten-entry.sh"] diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/wasm32-unknown-emscripten/node-wrapper.sh cargo-0.26.0/vendor/libc-0.2.36/ci/docker/wasm32-unknown-emscripten/node-wrapper.sh --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/wasm32-unknown-emscripten/node-wrapper.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/wasm32-unknown-emscripten/node-wrapper.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -#!/bin/sh - -set -e - -me=$1 -shift -dir=$(dirname $me) -file=$(basename $me) - -if echo $file | grep -q wasm; then - exit 0 # FIXME(rust-lang/cargo#4750) -fi - -cd $dir -exec node $file "$@" diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-linux-android/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-linux-android/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-linux-android/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-linux-android/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -FROM ubuntu:16.04 - -RUN apt-get update && \ - apt-get install -y --no-install-recommends \ - ca-certificates \ - curl \ - gcc \ - libc-dev \ - python \ - unzip - -WORKDIR /android/ -ENV ANDROID_ARCH=x86_64 -COPY android-install-ndk.sh /android/ -RUN sh /android/android-install-ndk.sh $ANDROID_ARCH - -# We do not run x86_64-linux-android tests on an android emulator. -# See ci/android-sysimage.sh for informations about how tests are run. -COPY android-sysimage.sh /android/ -RUN bash /android/android-sysimage.sh x86_64 x86_64-24_r07.zip - -ENV PATH=$PATH:/rust/bin:/android/ndk-$ANDROID_ARCH/bin \ - CARGO_TARGET_X86_64_LINUX_ANDROID_LINKER=x86_64-linux-android-gcc \ - CC_x86_64_linux_android=x86_64-linux-android-gcc \ - CXX_x86_64_linux_android=x86_64-linux-android-g++ \ - HOME=/tmp diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-rumprun-netbsd/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-rumprun-netbsd/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-rumprun-netbsd/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-rumprun-netbsd/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ -FROM mato/rumprun-toolchain-hw-x86_64 -USER root -RUN apt-get update -RUN apt-get install -y --no-install-recommends \ - qemu -ENV PATH=$PATH:/rust/bin \ - CARGO_TARGET_X86_64_RUMPRUN_NETBSD_RUNNER=/tmp/runtest - -ADD docker/x86_64-rumprun-netbsd/runtest.rs /tmp/ -ENTRYPOINT ["sh", "-c", "rustc /tmp/runtest.rs -o /tmp/runtest && exec \"$@\"", "--"] diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-rumprun-netbsd/runtest.rs cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-rumprun-netbsd/runtest.rs --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-rumprun-netbsd/runtest.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-rumprun-netbsd/runtest.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -use std::env; -use std::process::{Command, Stdio}; -use std::sync::mpsc; -use std::thread; -use std::time::Duration; -use std::io::{BufRead, BufReader, Read}; - -fn main() { - assert_eq!(env::args().len(), 2); - - let status = Command::new("rumprun-bake") - .arg("hw_virtio") - .arg("/tmp/libc-test.img") - .arg(env::args().nth(1).unwrap()) - .status() - .expect("failed to run rumprun-bake"); - assert!(status.success()); - - let mut child = Command::new("qemu-system-x86_64") - .arg("-nographic") - .arg("-vga").arg("none") - .arg("-m").arg("64") - .arg("-kernel").arg("/tmp/libc-test.img") - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .expect("failed to spawn qemu"); - - let mut stdout = child.stdout.take().unwrap(); - let mut stderr = child.stderr.take().unwrap(); - let (tx, rx) = mpsc::channel(); - let tx2 = tx.clone(); - let t1 = thread::spawn(move || find_ok(&mut stdout, tx)); - let t2 = thread::spawn(move || find_ok(&mut stderr, tx2)); - - let res = rx.recv_timeout(Duration::new(5, 0)); - child.kill().unwrap(); - t1.join().unwrap(); - t2.join().unwrap(); - - if res.is_err() { - panic!("didn't find success"); - } -} - -fn find_ok(input: &mut Read, tx: mpsc::Sender<()>) { - for line in BufReader::new(input).lines() { - let line = line.unwrap(); - println!("{}", line); - if line.starts_with("PASSED ") && line.contains(" tests") { - tx.send(()).unwrap(); - } - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-freebsd/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-freebsd/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-freebsd/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-freebsd/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -FROM alexcrichton/port-prebuilt-freebsd:2017-09-16 - -RUN apt-get update -RUN apt-get install -y --no-install-recommends \ - qemu genext2fs -RUN apt-get install -y curl ca-certificates gcc - -ENTRYPOINT ["sh"] - -ENV PATH=$PATH:/rust/bin \ - QEMU=2016-11-06/freebsd.qcow2.gz \ - CAN_CROSS=1 \ - CARGO_TARGET_X86_64_UNKNOWN_FREEBSD_LINKER=x86_64-unknown-freebsd10-gcc diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-linux-gnu/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -FROM ubuntu:17.04 -RUN apt-get update -RUN apt-get install -y --no-install-recommends \ - gcc libc6-dev ca-certificates -ENV PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-linux-gnux32/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-linux-gnux32/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-linux-gnux32/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-linux-gnux32/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -FROM ubuntu:17.04 -RUN apt-get update -RUN apt-get install -y --no-install-recommends \ - gcc-multilib libc6-dev ca-certificates -ENV PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-linux-musl/Dockerfile cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-linux-musl/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-linux-musl/Dockerfile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/docker/x86_64-unknown-linux-musl/Dockerfile 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -FROM ubuntu:17.10 - -RUN apt-get update -RUN apt-get install -y --no-install-recommends \ - gcc make libc6-dev git curl ca-certificates -RUN curl https://www.musl-libc.org/releases/musl-1.1.15.tar.gz | \ - tar xzf - && \ - cd musl-1.1.15 && \ - ./configure --prefix=/musl-x86_64 && \ - make install -j4 && \ - cd .. && \ - rm -rf musl-1.1.15 && \ -# Install linux kernel headers sanitized for use with musl - curl -L https://github.com/sabotage-linux/kernel-headers/archive/v3.12.6-5.tar.gz | \ - tar xzf - && \ - cd kernel-headers-3.12.6-5 && \ - make ARCH=x86_64 prefix=/musl-x86_64 install -j4 && \ - cd .. && \ - rm -rf kernel-headers-3.12.6-5 -ENV PATH=$PATH:/musl-x86_64/bin:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/dox.sh cargo-0.26.0/vendor/libc-0.2.36/ci/dox.sh --- cargo-0.25.0/vendor/libc-0.2.36/ci/dox.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/dox.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -#!/bin/sh - -# Builds documentation for all target triples that we have a registered URL for -# in liblibc. This scrapes the list of triples to document from `src/lib.rs` -# which has a bunch of `html_root_url` directives we pick up. - -set -e - -TARGETS=`grep html_root_url src/lib.rs | sed 's/.*".*\/\(.*\)"/\1/'` - -rm -rf target/doc -mkdir -p target/doc - -cp ci/landing-page-head.html target/doc/index.html - -for target in $TARGETS; do - echo documenting $target - - rustdoc -o target/doc/$target --target $target src/lib.rs --cfg dox \ - --crate-name libc - - echo "

  • $target
  • " \ - >> target/doc/index.html -done - -cat ci/landing-page-footer.html >> target/doc/index.html - -# If we're on travis, not a PR, and on the right branch, publish! -if [ "$TRAVIS_PULL_REQUEST" = "false" ] && [ "$TRAVIS_BRANCH" = "master" ]; then - pip install ghp_import --install-option="--prefix=$HOME/.local" - $HOME/.local/bin/ghp-import -n target/doc - git push -qf https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages -fi diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/emscripten-entry.sh cargo-0.26.0/vendor/libc-0.2.36/ci/emscripten-entry.sh --- cargo-0.25.0/vendor/libc-0.2.36/ci/emscripten-entry.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/emscripten-entry.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -#!/usr/bin/env bash -# Copyright 2017 The Rust Project Developers. See the COPYRIGHT -# file at the top-level directory of this distribution and at -# http://rust-lang.org/COPYRIGHT. -# -# Licensed under the Apache License, Version 2.0 or the MIT license -# , at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -set -ex - -source /emsdk-portable/emsdk_env.sh &> /dev/null - -# emsdk-portable provides a node binary, but we need version 8 to run wasm -export PATH="/node-v8.0.0-linux-x64/bin:$PATH" - -exec "$@" diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/emscripten.sh cargo-0.26.0/vendor/libc-0.2.36/ci/emscripten.sh --- cargo-0.25.0/vendor/libc-0.2.36/ci/emscripten.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/emscripten.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -# Copyright 2017 The Rust Project Developers. See the COPYRIGHT -# file at the top-level directory of this distribution and at -# http://rust-lang.org/COPYRIGHT. -# -# Licensed under the Apache License, Version 2.0 or the MIT license -# , at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -set -ex - -hide_output() { - set +x - on_err=" -echo ERROR: An error was encountered with the build. -cat /tmp/build.log -exit 1 -" - trap "$on_err" ERR - bash -c "while true; do sleep 30; echo \$(date) - building ...; done" & - PING_LOOP_PID=$! - $@ &> /tmp/build.log - trap - ERR - kill $PING_LOOP_PID - rm -f /tmp/build.log - set -x -} - -cd / -curl -L https://s3.amazonaws.com/mozilla-games/emscripten/releases/emsdk-portable.tar.gz | \ - tar -xz - -cd /emsdk-portable -./emsdk update -hide_output ./emsdk install sdk-1.37.20-64bit -./emsdk activate sdk-1.37.20-64bit - -# Compile and cache libc -source ./emsdk_env.sh -echo "main(){}" > a.c -HOME=/emsdk-portable/ emcc a.c -HOME=/emsdk-portable/ emcc -s BINARYEN=1 a.c -rm -f a.* - -# Make emsdk usable by any user -cp /root/.emscripten /emsdk-portable -chmod a+rxw -R /emsdk-portable - -# node 8 is required to run wasm -cd / -curl -L https://nodejs.org/dist/v8.0.0/node-v8.0.0-linux-x64.tar.xz | \ - tar -xJ - diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/ios/deploy_and_run_on_ios_simulator.rs cargo-0.26.0/vendor/libc-0.2.36/ci/ios/deploy_and_run_on_ios_simulator.rs --- cargo-0.25.0/vendor/libc-0.2.36/ci/ios/deploy_and_run_on_ios_simulator.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/ios/deploy_and_run_on_ios_simulator.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,171 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// This is a script to deploy and execute a binary on an iOS simulator. -// The primary use of this is to be able to run unit tests on the simulator and -// retrieve the results. -// -// To do this through Cargo instead, use Dinghy -// (https://github.com/snipsco/dinghy): cargo dinghy install, then cargo dinghy -// test. - -use std::env; -use std::fs::{self, File}; -use std::io::Write; -use std::path::Path; -use std::process; -use std::process::Command; - -macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with: {}", stringify!($e), e), - }) -} - -// Step one: Wrap as an app -fn package_as_simulator_app(crate_name: &str, test_binary_path: &Path) { - println!("Packaging simulator app"); - drop(fs::remove_dir_all("ios_simulator_app")); - t!(fs::create_dir("ios_simulator_app")); - t!(fs::copy(test_binary_path, - Path::new("ios_simulator_app").join(crate_name))); - - let mut f = t!(File::create("ios_simulator_app/Info.plist")); - t!(f.write_all(format!(r#" - - - - - CFBundleExecutable - {} - CFBundleIdentifier - com.rust.unittests - - - "#, crate_name).as_bytes())); -} - -// Step two: Start the iOS simulator -fn start_simulator() { - println!("Looking for iOS simulator"); - let output = t!(Command::new("xcrun").arg("simctl").arg("list").output()); - assert!(output.status.success()); - let mut simulator_exists = false; - let mut simulator_booted = false; - let mut found_rust_sim = false; - let stdout = t!(String::from_utf8(output.stdout)); - for line in stdout.lines() { - if line.contains("rust_ios") { - if found_rust_sim { - panic!("Duplicate rust_ios simulators found. Please \ - double-check xcrun simctl list."); - } - simulator_exists = true; - simulator_booted = line.contains("(Booted)"); - found_rust_sim = true; - } - } - - if simulator_exists == false { - println!("Creating iOS simulator"); - Command::new("xcrun") - .arg("simctl") - .arg("create") - .arg("rust_ios") - .arg("com.apple.CoreSimulator.SimDeviceType.iPhone-SE") - .arg("com.apple.CoreSimulator.SimRuntime.iOS-10-2") - .check_status(); - } else if simulator_booted == true { - println!("Shutting down already-booted simulator"); - Command::new("xcrun") - .arg("simctl") - .arg("shutdown") - .arg("rust_ios") - .check_status(); - } - - println!("Starting iOS simulator"); - // We can't uninstall the app (if present) as that will hang if the - // simulator isn't completely booted; just erase the simulator instead. - Command::new("xcrun").arg("simctl").arg("erase").arg("rust_ios").check_status(); - Command::new("xcrun").arg("simctl").arg("boot").arg("rust_ios").check_status(); -} - -// Step three: Install the app -fn install_app_to_simulator() { - println!("Installing app to simulator"); - Command::new("xcrun") - .arg("simctl") - .arg("install") - .arg("booted") - .arg("ios_simulator_app/") - .check_status(); -} - -// Step four: Run the app -fn run_app_on_simulator() { - println!("Running app"); - let output = t!(Command::new("xcrun") - .arg("simctl") - .arg("launch") - .arg("--console") - .arg("booted") - .arg("com.rust.unittests") - .output()); - - println!("stdout --\n{}\n", String::from_utf8_lossy(&output.stdout)); - println!("stderr --\n{}\n", String::from_utf8_lossy(&output.stderr)); - - let stdout = String::from_utf8_lossy(&output.stdout); - let passed = stdout.lines() - .find(|l| l.contains("PASSED")) - .map(|l| l.contains("tests")) - .unwrap_or(false); - - println!("Shutting down simulator"); - Command::new("xcrun") - .arg("simctl") - .arg("shutdown") - .arg("rust_ios") - .check_status(); - if !passed { - panic!("tests didn't pass"); - } -} - -trait CheckStatus { - fn check_status(&mut self); -} - -impl CheckStatus for Command { - fn check_status(&mut self) { - println!("\trunning: {:?}", self); - assert!(t!(self.status()).success()); - } -} - -fn main() { - let args: Vec = env::args().collect(); - if args.len() != 2 { - println!("Usage: {} ", args[0]); - process::exit(-1); - } - - let test_binary_path = Path::new(&args[1]); - let crate_name = test_binary_path.file_name().unwrap(); - - package_as_simulator_app(crate_name.to_str().unwrap(), test_binary_path); - start_simulator(); - install_app_to_simulator(); - run_app_on_simulator(); -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/landing-page-footer.html cargo-0.26.0/vendor/libc-0.2.36/ci/landing-page-footer.html --- cargo-0.25.0/vendor/libc-0.2.36/ci/landing-page-footer.html 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/landing-page-footer.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ - - - diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/landing-page-head.html cargo-0.26.0/vendor/libc-0.2.36/ci/landing-page-head.html --- cargo-0.25.0/vendor/libc-0.2.36/ci/landing-page-head.html 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/landing-page-head.html 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ - - - - - - -
      diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/linux-s390x.sh cargo-0.26.0/vendor/libc-0.2.36/ci/linux-s390x.sh --- cargo-0.25.0/vendor/libc-0.2.36/ci/linux-s390x.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/linux-s390x.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -set -ex - -mkdir -m 777 /qemu -cd /qemu - -curl -LO https://github.com/qemu/qemu/raw/master/pc-bios/s390-ccw.img -curl -LO http://ftp.debian.org/debian/dists/testing/main/installer-s390x/20170828/images/generic/kernel.debian -curl -LO http://ftp.debian.org/debian/dists/testing/main/installer-s390x/20170828/images/generic/initrd.debian - -mv kernel.debian kernel -mv initrd.debian initrd.gz - -mkdir init -cd init -gunzip -c ../initrd.gz | cpio -id -rm ../initrd.gz -cp /usr/s390x-linux-gnu/lib/libgcc_s.so.1 usr/lib/ -chmod a+w . diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/linux-sparc64.sh cargo-0.26.0/vendor/libc-0.2.36/ci/linux-sparc64.sh --- cargo-0.25.0/vendor/libc-0.2.36/ci/linux-sparc64.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/linux-sparc64.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -set -ex - -mkdir -m 777 /qemu -cd /qemu - -curl -LO https://cdimage.debian.org/cdimage/ports/debian-9.0-sparc64-NETINST-1.iso -7z e debian-9.0-sparc64-NETINST-1.iso boot/initrd.gz -7z e debian-9.0-sparc64-NETINST-1.iso boot/sparc64 -mv sparc64 kernel -rm debian-9.0-sparc64-NETINST-1.iso - -mkdir init -cd init -gunzip -c ../initrd.gz | cpio -id -rm ../initrd.gz -cp /usr/sparc64-linux-gnu/lib/libgcc_s.so.1 usr/lib/ -chmod a+w . diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/README.md cargo-0.26.0/vendor/libc-0.2.36/ci/README.md --- cargo-0.25.0/vendor/libc-0.2.36/ci/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,203 +0,0 @@ -The goal of the libc crate is to have CI running everywhere to have the -strongest guarantees about the definitions that this library contains, and as a -result the CI is pretty complicated and also pretty large! Hopefully this can -serve as a guide through the sea of scripts in this directory and elsewhere in -this project. - -# Files - -First up, let's talk about the files in this directory: - -* `run-travis.sh` - a shell script run by all Travis builders, this is - responsible for setting up the rest of the environment such as installing new - packages, downloading Rust target libraries, etc. - -* `run.sh` - the actual script which runs tests for a particular architecture. - Called from the `run-travis.sh` script this will run all tests for the target - specified. - -* `cargo-config` - Cargo configuration of linkers to use copied into place by - the `run-travis.sh` script before builds are run. - -* `dox.sh` - script called from `run-travis.sh` on only the linux 64-bit nightly - Travis bots to build documentation for this crate. - -* `landing-page-*.html` - used by `dox.sh` to generate a landing page for all - architectures' documentation. - -* `run-qemu.sh` - see discussion about QEMU below - -* `mips`, `rumprun` - instructions to build the docker image for each respective - CI target - -# CI Systems - -Currently this repository leverages a combination of Travis CI and AppVeyor for -running tests. The triples tested are: - -* AppVeyor - * `{i686,x86_64}-pc-windows-{msvc,gnu}` -* Travis - * `{i686,x86_64,mips,aarch64}-unknown-linux-gnu` - * `{x86_64,aarch64}-unknown-linux-musl` - * `arm-unknown-linux-gnueabihf` - * `arm-linux-androideabi` - * `{i686,x86_64}-apple-{darwin,ios}` - * `x86_64-rumprun-netbsd` - * `x86_64-unknown-freebsd` - * `x86_64-unknown-openbsd` - -The Windows triples are all pretty standard, they just set up their environment -then run tests, no need for downloading any extra target libs (we just download -the right installer). The Intel Linux/OSX builds are similar in that we just -download the right target libs and run tests. Note that the Intel Linux/OSX -builds are run on stable/beta/nightly, but are the only ones that do so. - -The remaining architectures look like: - -* Android runs in a [docker image][android-docker] with an emulator, the NDK, - and the SDK already set up. The entire build happens within the docker image. -* The MIPS, ARM, and AArch64 builds all use the QEMU userspace emulator to run - the generated binary to actually verify the tests pass. -* The MUSL build just has to download a MUSL compiler and target libraries and - then otherwise runs tests normally. -* iOS builds need an extra linker flag currently, but beyond that they're built - as standard as everything else. -* The rumprun target builds an entire kernel from the test suite and then runs - it inside QEMU using the serial console to test whether it succeeded or - failed. -* The BSD builds, currently OpenBSD and FreeBSD, use QEMU to boot up a system - and compile/run tests. More information on that below. - -[android-docker]: https://github.com/rust-lang/rust-buildbot/blob/master/slaves/android/Dockerfile - -## QEMU - -Lots of the architectures tested here use QEMU in the tests, so it's worth going -over all the crazy capabilities QEMU has and the various flavors in which we use -it! - -First up, QEMU has userspace emulation where it doesn't boot a full kernel, it -just runs a binary from another architecture (using the `qemu-` wrappers). -We provide it the runtime path for the dynamically loaded system libraries, -however. This strategy is used for all Linux architectures that aren't intel. -Note that one downside of this QEMU system is that threads are barely -implemented, so we're careful to not spawn many threads. - -For the rumprun target the only output is a kernel image, so we just use that -plus the `rumpbake` command to create a full kernel image which is then run from -within QEMU. - -Finally, the fun part, the BSDs. Quite a few hoops are jumped through to get CI -working for these platforms, but the gist of it looks like: - -* Cross compiling from Linux to any of the BSDs seems to be quite non-standard. - We may be able to get it working but it might be difficult at that point to - ensure that the libc definitions align with what you'd get on the BSD itself. - As a result, we try to do compiles within the BSD distro. -* On Travis we can't run a VM-in-a-VM, so we resort to userspace emulation - (QEMU). -* Unfortunately on Travis we also can't use KVM, so the emulation is super slow. - -With all that in mind, the way BSD is tested looks like: - -1. Download a pre-prepared image for the OS being tested. -2. Generate the tests for the OS being tested. This involves running the `ctest` - library over libc to generate a Rust file and a C file which will then be - compiled into the final test. -3. Generate a disk image which will later be mounted by the OS being tested. - This image is mostly just the libc directory, but some modifications are made - to compile the generated files from step 2. -4. The kernel is booted in QEMU, and it is configured to detect the libc-test - image being available, run the test script, and then shut down afterwards. -5. Look for whether the tests passed in the serial console output of the kernel. - -There's some pretty specific instructions for setting up each image (detailed -below), but the main gist of this is that we must avoid a vanilla `cargo run` -inside of the `libc-test` directory (which is what it's intended for) because -that would compile `syntex_syntax`, a large library, with userspace emulation. -This invariably times out on Travis, so we can't do that. - -Once all those hoops are jumped through, however, we can be happy that we're -testing almost everything! - -Below are some details of how to set up the initial OS images which are -downloaded. Each image must be enabled have input/output over the serial -console, log in automatically at the serial console, detect if a second drive in -QEMU is available, and if so mount it, run a script (it'll specifically be -`run-qemu.sh` in this folder which is copied into the generated image talked -about above), and then shut down. - -### QEMU setup - FreeBSD - -1. Download CD installer (most minimal is fine) -2. `qemu-img create -f qcow2 foo.qcow2 2G` -3. `qemu -cdrom foo.iso -drive if=virtio,file=foo.qcow2 -net nic,model=virtio -net user` -4. run installer -5. `echo 'console="comconsole"' >> /boot/loader.conf` -6. `echo 'autoboot_delay="0"' >> /boot/loader.conf` -7. look at /etc/ttys, see what getty argument is for ttyu0 -8. edit /etc/gettytab, look for ttyu0 argument, prepend `:al=root` to line - beneath - -(note that the current image has a `freebsd` user, but this isn't really -necessary) - -Once that's done, arrange for this script to run at login: - -``` -#!/bin/sh - -sudo kldload ext2fs -[ -e /dev/vtbd1 ] || exit 0 -sudo mount -t ext2fs /dev/vtbd1 /mnt -sh /mnt/run.sh /mnt -sudo poweroff -``` - -Helpful links - -* https://en.wikibooks.org/wiki/QEMU/Images -* https://blog.nekoconeko.nl/blog/2015/06/04/creating-an-openstack-freebsd-image.html -* https://www.freebsd.org/doc/handbook/serialconsole-setup.html - - -### QEMU setup - OpenBSD - -1. Download CD installer -2. `qemu-img create -f qcow2 foo.qcow2 2G` -3. `qemu -cdrom foo.iso -drive if=virtio,file=foo.qcow2 -net nic,model=virtio -net user` -4. run installer -5. `echo 'set tty com0' >> /etc/boot.conf` -6. `echo 'boot' >> /etc/boot.conf` -7. Modify /etc/ttys, change the `tty00` at the end from 'unknown off' to - 'vt220 on secure' -8. Modify same line in /etc/ttys to have `"/root/foo.sh"` as the shell -9. Add this script to `/root/foo.sh` - -``` -#!/bin/sh -exec 1>/dev/tty00 -exec 2>&1 - -if mount -t ext2fs /dev/sd1c /mnt; then - sh /mnt/run.sh /mnt - shutdown -ph now -fi - -# limited shell... -exec /bin/sh < /dev/tty00 -``` - -10. `chmod +x /root/foo.sh` - -Helpful links: - -* https://en.wikibooks.org/wiki/QEMU/Images -* http://www.openbsd.org/faq/faq7.html#SerCon - -# Questions? - -Hopefully that's at least somewhat of an introduction to everything going on -here, and feel free to ping @alexcrichton with questions! - diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/run-docker.sh cargo-0.26.0/vendor/libc-0.2.36/ci/run-docker.sh --- cargo-0.25.0/vendor/libc-0.2.36/ci/run-docker.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/run-docker.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -# Small script to run tests for a target (or all targets) inside all the -# respective docker images. - -set -ex - -run() { - echo $1 - # use -f so we can use ci/ as build context - docker build -t libc -f ci/docker/$1/Dockerfile ci/ - mkdir -p target - if [ -w /dev/kvm ]; then - kvm="--volume /dev/kvm:/dev/kvm" - fi - docker run \ - --user `id -u`:`id -g` \ - --rm \ - --init \ - --volume $HOME/.cargo:/cargo \ - $kvm \ - --env CARGO_HOME=/cargo \ - --volume `rustc --print sysroot`:/rust:ro \ - --volume `pwd`:/checkout:ro \ - --volume `pwd`/target:/checkout/target \ - --env CARGO_TARGET_DIR=/checkout/target \ - --workdir /checkout \ - libc \ - ci/run.sh $1 -} - -if [ -z "$1" ]; then - for d in `ls ci/docker/`; do - run $d - done -else - run $1 -fi diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/run-qemu.sh cargo-0.26.0/vendor/libc-0.2.36/ci/run-qemu.sh --- cargo-0.25.0/vendor/libc-0.2.36/ci/run-qemu.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/run-qemu.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -# Initial script which is run inside of all qemu images. The first argument to -# this script (as arranged by the qemu image itself) is the path to where the -# libc crate is mounted. -# -# For qemu images we currently need to install Rust manually as this wasn't done -# by the initial run-travis.sh script -# -# FIXME: feels like run-travis.sh should be responsible for downloading the -# compiler. - -set -ex - -ROOT=$1 -cp -r $ROOT/libc /tmp/libc -cd /tmp/libc - -TARGET=$(cat $ROOT/TARGET) -export CARGO_TARGET_DIR=/tmp - -case $TARGET in - *-openbsd) - pkg_add cargo gcc%4.9 rust - export CC=egcc - ;; - - *) - echo "Unknown target: $TARGET" - exit 1 - ;; -esac - -exec sh ci/run.sh $TARGET diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/run.sh cargo-0.26.0/vendor/libc-0.2.36/ci/run.sh --- cargo-0.25.0/vendor/libc-0.2.36/ci/run.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/run.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,82 +0,0 @@ -#!/bin/sh - -# Builds and runs tests for a particular target passed as an argument to this -# script. - -set -ex - -TARGET=$1 - -# If we're going to run tests inside of a qemu image, then we don't need any of -# the scripts below. Instead, download the image, prepare a filesystem which has -# the current state of this repository, and then run the image. -# -# It's assume that all images, when run with two disks, will run the `run.sh` -# script from the second which we place inside. -if [ "$QEMU" != "" ]; then - tmpdir=/tmp/qemu-img-creation - mkdir -p $tmpdir - - if [ -z "${QEMU#*.gz}" ]; then - # image is .gz : download and uncompress it - qemufile=$(echo ${QEMU%.gz} | sed 's/\//__/g') - if [ ! -f $tmpdir/$qemufile ]; then - curl https://s3-us-west-1.amazonaws.com/rust-lang-ci2/libc/$QEMU | \ - gunzip -d > $tmpdir/$qemufile - fi - else - # plain qcow2 image: just download it - qemufile=$(echo ${QEMU} | sed 's/\//__/g') - if [ ! -f $tmpdir/$qemufile ]; then - curl https://s3-us-west-1.amazonaws.com/rust-lang-ci2/libc/$QEMU \ - > $tmpdir/$qemufile - fi - fi - - # Create a mount a fresh new filesystem image that we'll later pass to QEMU. - # This will have a `run.sh` script will which use the artifacts inside to run - # on the host. - rm -f $tmpdir/libc-test.img - mkdir $tmpdir/mount - - # Do the standard rigamarole of cross-compiling an executable and then the - # script to run just executes the binary. - cargo build \ - --manifest-path libc-test/Cargo.toml \ - --target $TARGET \ - --test main - rm $CARGO_TARGET_DIR/$TARGET/debug/main-*.d - cp $CARGO_TARGET_DIR/$TARGET/debug/main-* $tmpdir/mount/libc-test - echo 'exec $1/libc-test' > $tmpdir/mount/run.sh - - du -sh $tmpdir/mount - genext2fs \ - --root $tmpdir/mount \ - --size-in-blocks 100000 \ - $tmpdir/libc-test.img - - # Pass -snapshot to prevent tampering with the disk images, this helps when - # running this script in development. The two drives are then passed next, - # first is the OS and second is the one we just made. Next the network is - # configured to work (I'm not entirely sure how), and then finally we turn off - # graphics and redirect the serial console output to out.log. - qemu-system-x86_64 \ - -m 1024 \ - -snapshot \ - -drive if=virtio,file=$tmpdir/$qemufile \ - -drive if=virtio,file=$tmpdir/libc-test.img \ - -net nic,model=virtio \ - -net user \ - -nographic \ - -vga none 2>&1 | tee $CARGO_TARGET_DIR/out.log - exec grep "^PASSED .* tests" $CARGO_TARGET_DIR/out.log -fi - -# FIXME: x86_64-unknown-linux-gnux32 fail to compile wihout --release -# See https://github.com/rust-lang/rust/issues/45417 -opt= -if [ "$TARGET" = "x86_64-unknown-linux-gnux32" ]; then - opt="--release" -fi - -exec cargo test $opt --manifest-path libc-test/Cargo.toml --target $TARGET diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/runtest-android.rs cargo-0.26.0/vendor/libc-0.2.36/ci/runtest-android.rs --- cargo-0.25.0/vendor/libc-0.2.36/ci/runtest-android.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/runtest-android.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -use std::env; -use std::process::Command; -use std::path::{Path, PathBuf}; - -fn main() { - assert_eq!(env::args_os().len(), 2); - let test = PathBuf::from(env::args_os().nth(1).unwrap()); - let dst = Path::new("/data/local/tmp").join(test.file_name().unwrap()); - - let status = Command::new("adb") - .arg("wait-for-device") - .status() - .expect("failed to run rumprun-bake"); - assert!(status.success()); - - let status = Command::new("adb") - .arg("push") - .arg(&test) - .arg(&dst) - .status() - .expect("failed to run rumprun-bake"); - assert!(status.success()); - - let output = Command::new("adb") - .arg("shell") - .arg(&dst) - .output() - .expect("failed to run rumprun-bake"); - assert!(status.success()); - - println!("status: {}\nstdout ---\n{}\nstderr ---\n{}", - output.status, - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr)); - - let stdout = String::from_utf8_lossy(&output.stdout); - let mut lines = stdout.lines().filter(|l| l.starts_with("PASSED ")); - if !lines.any(|l| l.contains(" tests")) { - panic!("failed to find successful test run"); - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/style.rs cargo-0.26.0/vendor/libc-0.2.36/ci/style.rs --- cargo-0.25.0/vendor/libc-0.2.36/ci/style.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/style.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,204 +0,0 @@ -//! Simple script to verify the coding style of this library -//! -//! ## How to run -//! -//! The first argument to this script is the directory to run on, so running -//! this script should be as simple as: -//! -//! ```notrust -//! rustc ci/style.rs -//! ./style src -//! ``` -//! -//! ## Guidelines -//! -//! The current style is: -//! -//! * No trailing whitespace -//! * No tabs -//! * 80-character lines -//! * `extern` instead of `extern "C"` -//! * Specific module layout: -//! 1. use directives -//! 2. typedefs -//! 3. structs -//! 4. constants -//! 5. f! { ... } functions -//! 6. extern functions -//! 7. modules + pub use -//! -//! Things not verified: -//! -//! * alignment -//! * 4-space tabs -//! * leading colons on paths - -use std::env; -use std::fs; -use std::io::prelude::*; -use std::path::Path; - -macro_rules! t { - ($e:expr) => (match $e { - Ok(e) => e, - Err(e) => panic!("{} failed with {}", stringify!($e), e), - }) -} - -fn main() { - let arg = env::args().skip(1).next().unwrap_or(".".to_string()); - - let mut errors = Errors { errs: false }; - walk(Path::new(&arg), &mut errors); - - if errors.errs { - panic!("found some lint errors"); - } else { - println!("good style!"); - } -} - -fn walk(path: &Path, err: &mut Errors) { - for entry in t!(path.read_dir()).map(|e| t!(e)) { - let path = entry.path(); - if t!(entry.file_type()).is_dir() { - walk(&path, err); - continue - } - - let name = entry.file_name().into_string().unwrap(); - match &name[..] { - n if !n.ends_with(".rs") => continue, - - "dox.rs" | - "lib.rs" | - "macros.rs" => continue, - - _ => {} - } - - let mut contents = String::new(); - t!(t!(fs::File::open(&path)).read_to_string(&mut contents)); - - check_style(&contents, &path, err); - } -} - -struct Errors { - errs: bool, -} - -#[derive(Clone, Copy, PartialEq)] -enum State { - Start, - Imports, - Typedefs, - Structs, - Constants, - FunctionDefinitions, - Functions, - Modules, -} - -fn check_style(file: &str, path: &Path, err: &mut Errors) { - let mut state = State::Start; - let mut s_macros = 0; - let mut f_macros = 0; - let mut prev_blank = false; - - for (i, line) in file.lines().enumerate() { - if line == "" { - if prev_blank { - err.error(path, i, "double blank line"); - } - prev_blank = true; - } else { - prev_blank = false; - } - if line != line.trim_right() { - err.error(path, i, "trailing whitespace"); - } - if line.contains("\t") { - err.error(path, i, "tab character"); - } - if line.len() > 80 { - err.error(path, i, "line longer than 80 chars"); - } - if line.contains("extern \"C\"") { - err.error(path, i, "use `extern` instead of `extern \"C\""); - } - if line.contains("#[cfg(") && !line.contains(" if ") { - if state != State::Structs { - err.error(path, i, "use cfg_if! and submodules \ - instead of #[cfg]"); - } - } - - let line = line.trim_left(); - let is_pub = line.starts_with("pub "); - let line = if is_pub {&line[4..]} else {line}; - - let line_state = if line.starts_with("use ") { - if is_pub { - State::Modules - } else { - State::Imports - } - } else if line.starts_with("const ") { - State::Constants - } else if line.starts_with("type ") { - State::Typedefs - } else if line.starts_with("s! {") { - s_macros += 1; - State::Structs - } else if line.starts_with("f! {") { - f_macros += 1; - State::FunctionDefinitions - } else if line.starts_with("extern ") { - State::Functions - } else if line.starts_with("mod ") { - State::Modules - } else { - continue - }; - - if state as usize > line_state as usize { - err.error(path, i, &format!("{} found after {} when \ - it belongs before", - line_state.desc(), state.desc())); - } - - if f_macros == 2 { - f_macros += 1; - err.error(path, i, "multiple f! macros in one module"); - } - if s_macros == 2 { - s_macros += 1; - err.error(path, i, "multiple s! macros in one module"); - } - - state = line_state; - } -} - -impl State { - fn desc(&self) -> &str { - match *self { - State::Start => "start", - State::Imports => "import", - State::Typedefs => "typedef", - State::Structs => "struct", - State::Constants => "constant", - State::FunctionDefinitions => "function definition", - State::Functions => "extern function", - State::Modules => "module", - } - } -} - -impl Errors { - fn error(&mut self, path: &Path, line: usize, msg: &str) { - self.errs = true; - println!("{}:{} - {}", path.display(), line + 1, msg); - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/ci/test-runner-linux cargo-0.26.0/vendor/libc-0.2.36/ci/test-runner-linux --- cargo-0.25.0/vendor/libc-0.2.36/ci/test-runner-linux 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/ci/test-runner-linux 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -#!/bin/sh - -set -e - -arch=$1 -prog=$2 - -cd /qemu/init -cp -f $2 prog -find . | cpio --create --format='newc' --quiet | gzip > ../initrd.gz -cd .. - -timeout 30s qemu-system-$arch \ - -m 1024 \ - -nographic \ - -kernel kernel \ - -initrd initrd.gz \ - -append init=/prog > output || true - -# remove kernel messages -tr -d '\r' < output | egrep -v '^\[' - -grep PASSED output > /dev/null diff -Nru cargo-0.25.0/vendor/libc-0.2.36/LICENSE-APACHE cargo-0.26.0/vendor/libc-0.2.36/LICENSE-APACHE --- cargo-0.25.0/vendor/libc-0.2.36/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/libc-0.2.36/LICENSE-MIT cargo-0.26.0/vendor/libc-0.2.36/LICENSE-MIT --- cargo-0.25.0/vendor/libc-0.2.36/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/libc-0.2.36/README.md cargo-0.26.0/vendor/libc-0.2.36/README.md --- cargo-0.25.0/vendor/libc-0.2.36/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,159 +0,0 @@ -libc -==== - -A Rust library with native bindings to the types and functions commonly found on -various systems, including libc. - -[![Build Status](https://travis-ci.org/rust-lang/libc.svg?branch=master)](https://travis-ci.org/rust-lang/libc) -[![Build status](https://ci.appveyor.com/api/projects/status/github/rust-lang/libc?svg=true)](https://ci.appveyor.com/project/rust-lang-libs/libc) - -[Documentation](#platforms-and-documentation) - -## Usage - -First, add the following to your `Cargo.toml`: - -```toml -[dependencies] -libc = "0.2" -``` - -Next, add this to your crate root: - -```rust -extern crate libc; -``` - -Currently libc by default links to the standard library, but if you would -instead like to use libc in a `#![no_std]` situation or crate you can request -this via: - -```toml -[dependencies] -libc = { version = "0.2", default-features = false } -``` - -## What is libc? - -The primary purpose of this crate is to provide all of the definitions necessary -to easily interoperate with C code (or "C-like" code) on each of the platforms -that Rust supports. This includes type definitions (e.g. `c_int`), constants -(e.g. `EINVAL`) as well as function headers (e.g. `malloc`). - -This crate does not strive to have any form of compatibility across platforms, -but rather it is simply a straight binding to the system libraries on the -platform in question. - -## Public API - -This crate exports all underlying platform types, functions, and constants under -the crate root, so all items are accessible as `libc::foo`. The types and values -of all the exported APIs match the platform that libc is compiled for. - -More detailed information about the design of this library can be found in its -[associated RFC][rfc]. - -[rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1291-promote-libc.md - -## Adding an API - -Want to use an API which currently isn't bound in `libc`? It's quite easy to add -one! - -The internal structure of this crate is designed to minimize the number of -`#[cfg]` attributes in order to easily be able to add new items which apply -to all platforms in the future. As a result, the crate is organized -hierarchically based on platform. Each module has a number of `#[cfg]`'d -children, but only one is ever actually compiled. Each module then reexports all -the contents of its children. - -This means that for each platform that libc supports, the path from a -leaf module to the root will contain all bindings for the platform in question. -Consequently, this indicates where an API should be added! Adding an API at a -particular level in the hierarchy means that it is supported on all the child -platforms of that level. For example, when adding a Unix API it should be added -to `src/unix/mod.rs`, but when adding a Linux-only API it should be added to -`src/unix/notbsd/linux/mod.rs`. - -If you're not 100% sure at what level of the hierarchy an API should be added -at, fear not! This crate has CI support which tests any binding against all -platforms supported, so you'll see failures if an API is added at the wrong -level or has different signatures across platforms. - -With that in mind, the steps for adding a new API are: - -1. Determine where in the module hierarchy your API should be added. -2. Add the API. -3. Send a PR to this repo. -4. Wait for CI to pass, fixing errors. -5. Wait for a merge! - -### Test before you commit - -We have two automated tests running on [Travis](https://travis-ci.org/rust-lang/libc): - -1. [`libc-test`](https://github.com/alexcrichton/ctest) - - `cd libc-test && cargo test` - - Use the `skip_*()` functions in `build.rs` if you really need a workaround. -2. Style checker - - `rustc ci/style.rs && ./style src` - -### Releasing your change to crates.io - -Now that you've done the amazing job of landing your new API or your new -platform in this crate, the next step is to get that sweet, sweet usage from -crates.io! The only next step is to bump the version of libc and then publish -it. If you'd like to get a release out ASAP you can follow these steps: - -1. Update the version number in `Cargo.toml`, you'll just be bumping the patch - version number. -2. Run `cargo update` to regenerate the lockfile to encode your version bump in - the lock file. You may pull in some other updated dependencies, that's ok. -3. Send a PR to this repository. It should [look like this][example], but it'd - also be nice to fill out the description with a small rationale for the - release (any rationale is ok though!) -4. Once merged the release will be tagged and published by one of the libc crate - maintainers. - -[example]: https://github.com/rust-lang/libc/pull/583 - -## Platforms and Documentation - -The following platforms are currently tested and have documentation available: - -Tested: - * [`i686-pc-windows-msvc`](https://doc.rust-lang.org/libc/i686-pc-windows-msvc/libc/) - * [`x86_64-pc-windows-msvc`](https://doc.rust-lang.org/libc/x86_64-pc-windows-msvc/libc/) - (Windows) - * [`i686-pc-windows-gnu`](https://doc.rust-lang.org/libc/i686-pc-windows-gnu/libc/) - * [`x86_64-pc-windows-gnu`](https://doc.rust-lang.org/libc/x86_64-pc-windows-gnu/libc/) - * [`i686-apple-darwin`](https://doc.rust-lang.org/libc/i686-apple-darwin/libc/) - * [`x86_64-apple-darwin`](https://doc.rust-lang.org/libc/x86_64-apple-darwin/libc/) - (OSX) - * `i386-apple-ios` - * `x86_64-apple-ios` - * [`i686-unknown-linux-gnu`](https://doc.rust-lang.org/libc/i686-unknown-linux-gnu/libc/) - * [`x86_64-unknown-linux-gnu`](https://doc.rust-lang.org/libc/x86_64-unknown-linux-gnu/libc/) - (Linux) - * [`x86_64-unknown-linux-musl`](https://doc.rust-lang.org/libc/x86_64-unknown-linux-musl/libc/) - (Linux MUSL) - * [`aarch64-unknown-linux-gnu`](https://doc.rust-lang.org/libc/aarch64-unknown-linux-gnu/libc/) - (Linux) - * [`aarch64-unknown-linux-musl`](https://doc.rust-lang.org/libc/aarch64-unknown-linux-musl/libc/) - (Linux MUSL) - * [`mips-unknown-linux-gnu`](https://doc.rust-lang.org/libc/mips-unknown-linux-gnu/libc/) - * [`arm-unknown-linux-gnueabihf`](https://doc.rust-lang.org/libc/arm-unknown-linux-gnueabihf/libc/) - * [`arm-linux-androideabi`](https://doc.rust-lang.org/libc/arm-linux-androideabi/libc/) - (Android) - * [`x86_64-unknown-freebsd`](https://doc.rust-lang.org/libc/x86_64-unknown-freebsd/libc/) - * [`x86_64-unknown-openbsd`](https://doc.rust-lang.org/libc/x86_64-unknown-openbsd/libc/) - * [`x86_64-rumprun-netbsd`](https://doc.rust-lang.org/libc/x86_64-unknown-netbsd/libc/) - -The following may be supported, but are not guaranteed to always work: - - * `i686-unknown-freebsd` - * [`x86_64-unknown-bitrig`](https://doc.rust-lang.org/libc/x86_64-unknown-bitrig/libc/) - * [`x86_64-unknown-dragonfly`](https://doc.rust-lang.org/libc/x86_64-unknown-dragonfly/libc/) - * `i686-unknown-haiku` - * `x86_64-unknown-haiku` - * [`x86_64-unknown-netbsd`](https://doc.rust-lang.org/libc/x86_64-unknown-netbsd/libc/) diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/cloudabi/aarch64.rs cargo-0.26.0/vendor/libc-0.2.36/src/cloudabi/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/cloudabi/aarch64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/cloudabi/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -pub type c_char = u8; -pub type c_long = i64; -pub type c_ulong = u64; -pub type wchar_t = u32; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/cloudabi/arm.rs cargo-0.26.0/vendor/libc-0.2.36/src/cloudabi/arm.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/cloudabi/arm.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/cloudabi/arm.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -pub type c_char = u8; -pub type c_long = i32; -pub type c_ulong = u32; -pub type wchar_t = u32; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/cloudabi/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/cloudabi/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/cloudabi/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/cloudabi/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,166 +0,0 @@ -pub type in_addr_t = u32; -pub type in_port_t = u16; -pub type pthread_key_t = usize; -pub type pthread_t = usize; -pub type sa_family_t = u8; -pub type socklen_t = usize; -pub type time_t = i64; - -s! { - pub struct addrinfo { - pub ai_flags: ::c_int, - pub ai_family: ::c_int, - pub ai_socktype: ::c_int, - pub ai_protocol: ::c_int, - pub ai_addrlen: ::socklen_t, - pub ai_addr: *mut ::sockaddr, - pub ai_canonname: *mut ::c_char, - pub ai_next: *mut addrinfo, - } - - pub struct in_addr { - pub s_addr: in_addr_t, - } - - pub struct in6_addr { - pub s6_addr: [u8; 16], - } - - pub struct pthread_attr_t { - __detachstate: ::c_int, - __stacksize: usize, - } - - pub struct sockaddr { - pub sa_family: sa_family_t, - pub sa_data: [::c_char; 0], - } - - pub struct sockaddr_in { - pub sin_family: ::sa_family_t, - pub sin_port: ::in_port_t, - pub sin_addr: ::in_addr, - } - - pub struct sockaddr_in6 { - pub sin6_family: sa_family_t, - pub sin6_port: ::in_port_t, - pub sin6_flowinfo: u32, - pub sin6_addr: ::in6_addr, - pub sin6_scope_id: u32, - } - - pub struct sockaddr_storage { - pub ss_family: ::sa_family_t, - __ss_data: [u8; 32], - } -} - -pub const _SC_NPROCESSORS_ONLN: ::c_int = 52; -pub const _SC_PAGESIZE: ::c_int = 54; - -pub const AF_INET: ::c_int = 1; -pub const AF_INET6: ::c_int = 2; - -pub const EACCES: ::c_int = 2; -pub const EADDRINUSE: ::c_int = 3; -pub const EADDRNOTAVAIL: ::c_int = 4; -pub const EAGAIN: ::c_int = 6; -pub const ECONNABORTED: ::c_int = 13; -pub const ECONNREFUSED: ::c_int = 14; -pub const ECONNRESET: ::c_int = 15; -pub const EEXIST: ::c_int = 20; -pub const EINTR: ::c_int = 27; -pub const EINVAL: ::c_int = 28; -pub const ENOENT: ::c_int = 44; -pub const ENOTCONN: ::c_int = 53; -pub const EPERM: ::c_int = 63; -pub const EPIPE: ::c_int = 64; -pub const ETIMEDOUT: ::c_int = 73; -pub const EWOULDBLOCK: ::c_int = EAGAIN; - -pub const EAI_SYSTEM: ::c_int = 9; - -pub const EXIT_FAILURE: ::c_int = 1; -pub const EXIT_SUCCESS: ::c_int = 0; - -pub const PTHREAD_STACK_MIN: ::size_t = 1024; - -pub const SOCK_DGRAM: ::c_int = 128; -pub const SOCK_STREAM: ::c_int = 130; - -extern { - pub fn arc4random_buf(buf: *const ::c_void, len: ::size_t); - pub fn freeaddrinfo(res: *mut addrinfo); - pub fn gai_strerror(errcode: ::c_int) -> *const ::c_char; - pub fn getaddrinfo( - node: *const c_char, - service: *const c_char, - hints: *const addrinfo, - res: *mut *mut addrinfo, - ) -> ::c_int; - pub fn getsockopt( - sockfd: ::c_int, - level: ::c_int, - optname: ::c_int, - optval: *mut ::c_void, - optlen: *mut ::socklen_t, - ) -> ::c_int; - pub fn posix_memalign( - memptr: *mut *mut ::c_void, - align: ::size_t, - size: ::size_t, - ) -> ::c_int; - pub fn pthread_attr_destroy(attr: *mut ::pthread_attr_t) -> ::c_int; - pub fn pthread_attr_init(attr: *mut ::pthread_attr_t) -> ::c_int; - pub fn pthread_attr_setstacksize( - attr: *mut ::pthread_attr_t, - stack_size: ::size_t, - ) -> ::c_int; - pub fn pthread_create( - native: *mut ::pthread_t, - attr: *const ::pthread_attr_t, - f: extern fn(*mut ::c_void) -> *mut ::c_void, - value: *mut ::c_void, - ) -> ::c_int; - pub fn pthread_detach(thread: ::pthread_t) -> ::c_int; - pub fn pthread_getspecific(key: pthread_key_t) -> *mut ::c_void; - pub fn pthread_join( - native: ::pthread_t, - value: *mut *mut ::c_void, - ) -> ::c_int; - pub fn pthread_key_create( - key: *mut pthread_key_t, - dtor: Option, - ) -> ::c_int; - pub fn pthread_key_delete(key: pthread_key_t) -> ::c_int; - pub fn pthread_setspecific( - key: pthread_key_t, - value: *const ::c_void, - ) -> ::c_int; - pub fn send( - socket: ::c_int, - buf: *const ::c_void, - len: ::size_t, - flags: ::c_int, - ) -> ::ssize_t; - pub fn sysconf(name: ::c_int) -> ::c_long; -} - -cfg_if! { - if #[cfg(target_arch = "aarch64")] { - mod aarch64; - pub use self::aarch64::*; - } else if #[cfg(any(target_arch = "arm"))] { - mod arm; - pub use self::arm::*; - } else if #[cfg(any(target_arch = "x86"))] { - mod x86; - pub use self::x86::*; - } else if #[cfg(any(target_arch = "x86_64"))] { - mod x86_64; - pub use self::x86_64::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/cloudabi/x86_64.rs cargo-0.26.0/vendor/libc-0.2.36/src/cloudabi/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/cloudabi/x86_64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/cloudabi/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -pub type c_char = i8; -pub type c_long = i64; -pub type c_ulong = u64; -pub type wchar_t = i32; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/cloudabi/x86.rs cargo-0.26.0/vendor/libc-0.2.36/src/cloudabi/x86.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/cloudabi/x86.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/cloudabi/x86.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -pub type c_char = i8; -pub type c_long = i32; -pub type c_ulong = u32; -pub type wchar_t = i32; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/dox.rs cargo-0.26.0/vendor/libc-0.2.36/src/dox.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/dox.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/dox.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,151 +0,0 @@ -pub use self::imp::*; - -#[cfg(not(dox))] -mod imp { - pub use core::option::Option; - pub use core::clone::Clone; - pub use core::marker::Copy; - pub use core::mem; -} - -#[cfg(dox)] -mod imp { - pub enum Option { - Some(T), - None, - } - impl Copy for Option {} - impl Clone for Option { - fn clone(&self) -> Option { loop {} } - } - - pub trait Clone { - fn clone(&self) -> Self; - } - - #[lang = "copy"] - pub trait Copy {} - - #[lang = "freeze"] - pub trait Freeze {} - - #[lang = "sync"] - pub trait Sync {} - impl Sync for T {} - - #[lang = "sized"] - pub trait Sized {} - - macro_rules! each_int { - ($mac:ident) => ( - $mac!(u8); - $mac!(u16); - $mac!(u32); - $mac!(u64); - $mac!(usize); - each_signed_int!($mac); - ) - } - - macro_rules! each_signed_int { - ($mac:ident) => ( - $mac!(i8); - $mac!(i16); - $mac!(i32); - $mac!(i64); - $mac!(isize); - ) - } - - #[lang = "div"] - pub trait Div { - type Output; - fn div(self, rhs: RHS) -> Self::Output; - } - - #[lang = "shl"] - pub trait Shl { - type Output; - fn shl(self, rhs: RHS) -> Self::Output; - } - - #[lang = "mul"] - pub trait Mul { - type Output; - fn mul(self, rhs: RHS) -> Self::Output; - } - - #[lang = "sub"] - pub trait Sub { - type Output; - fn sub(self, rhs: RHS) -> Self::Output; - } - - #[lang = "bitor"] - pub trait Bitor { - type Output; - fn bitor(self, rhs: RHS) -> Self::Output; - } - - #[lang = "neg"] - pub trait Neg { - type Output; - fn neg(self) -> Self::Output; - } - - #[lang = "not"] - pub trait Not { - type Output; - fn not(self) -> Self::Output; - } - - #[lang = "add"] - pub trait Add { - type Output; - fn add(self, r: RHS) -> Self::Output; - } - - macro_rules! impl_traits { - ($($i:ident)*) => ($( - impl Div<$i> for $i { - type Output = $i; - fn div(self, rhs: $i) -> $i { self / rhs } - } - impl Shl<$i> for $i { - type Output = $i; - fn shl(self, rhs: $i) -> $i { self << rhs } - } - impl Mul for $i { - type Output = $i; - fn mul(self, rhs: $i) -> $i { self * rhs } - } - - impl Sub for $i { - type Output = $i; - fn sub(self, rhs: $i) -> $i { self - rhs } - } - impl Bitor for $i { - type Output = $i; - fn bitor(self, rhs: $i) -> $i { self | rhs } - } - impl Neg for $i { - type Output = $i; - fn neg(self) -> $i { -self } - } - impl Not for $i { - type Output = $i; - fn not(self) -> $i { !self } - } - impl Add<$i> for $i { - type Output = $i; - fn add(self, other: $i) -> $i { self + other } - } - )*) - } - each_int!(impl_traits); - - pub mod mem { - pub fn size_of_val(_: &T) -> usize { 4 } - pub fn size_of(_: &T) -> usize { 4 } - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/fuchsia/aarch64.rs cargo-0.26.0/vendor/libc-0.2.36/src/fuchsia/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/fuchsia/aarch64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/fuchsia/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,336 +0,0 @@ -pub type c_char = u8; -pub type __u64 = ::c_ulonglong; -pub type wchar_t = u32; -pub type nlink_t = u32; -pub type blksize_t = ::c_int; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad0: ::c_ulong, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - __pad1: ::c_int, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused: [::c_uint; 2], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad0: ::c_ulong, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - __pad1: ::c_int, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused: [::c_uint; 2], - } - - pub struct ipc_perm { - pub __ipc_perm_key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::mode_t, - pub __seq: ::c_ushort, - __unused1: ::c_ulong, - __unused2: ::c_ulong, - } -} - -pub const MINSIGSTKSZ: ::size_t = 6144; -pub const SIGSTKSZ: ::size_t = 12288; - -#[doc(hidden)] -pub const PF_MAX: ::c_int = 43; -#[doc(hidden)] -pub const AF_MAX: ::c_int = PF_MAX; - -pub const SYS_io_setup: ::c_long = 0; -pub const SYS_io_destroy: ::c_long = 1; -pub const SYS_io_submit: ::c_long = 2; -pub const SYS_io_cancel: ::c_long = 3; -pub const SYS_io_getevents: ::c_long = 4; -pub const SYS_setxattr: ::c_long = 5; -pub const SYS_lsetxattr: ::c_long = 6; -pub const SYS_fsetxattr: ::c_long = 7; -pub const SYS_getxattr: ::c_long = 8; -pub const SYS_lgetxattr: ::c_long = 9; -pub const SYS_fgetxattr: ::c_long = 10; -pub const SYS_listxattr: ::c_long = 11; -pub const SYS_llistxattr: ::c_long = 12; -pub const SYS_flistxattr: ::c_long = 13; -pub const SYS_removexattr: ::c_long = 14; -pub const SYS_lremovexattr: ::c_long = 15; -pub const SYS_fremovexattr: ::c_long = 16; -pub const SYS_getcwd: ::c_long = 17; -pub const SYS_lookup_dcookie: ::c_long = 18; -pub const SYS_eventfd2: ::c_long = 19; -pub const SYS_epoll_create1: ::c_long = 20; -pub const SYS_epoll_ctl: ::c_long = 21; -pub const SYS_epoll_pwait: ::c_long = 22; -pub const SYS_dup: ::c_long = 23; -pub const SYS_dup3: ::c_long = 24; -pub const SYS_inotify_init1: ::c_long = 26; -pub const SYS_inotify_add_watch: ::c_long = 27; -pub const SYS_inotify_rm_watch: ::c_long = 28; -pub const SYS_ioctl: ::c_long = 29; -pub const SYS_ioprio_set: ::c_long = 30; -pub const SYS_ioprio_get: ::c_long = 31; -pub const SYS_flock: ::c_long = 32; -pub const SYS_mknodat: ::c_long = 33; -pub const SYS_mkdirat: ::c_long = 34; -pub const SYS_unlinkat: ::c_long = 35; -pub const SYS_symlinkat: ::c_long = 36; -pub const SYS_linkat: ::c_long = 37; -pub const SYS_renameat: ::c_long = 38; -pub const SYS_umount2: ::c_long = 39; -pub const SYS_mount: ::c_long = 40; -pub const SYS_pivot_root: ::c_long = 41; -pub const SYS_nfsservctl: ::c_long = 42; -pub const SYS_fallocate: ::c_long = 47; -pub const SYS_faccessat: ::c_long = 48; -pub const SYS_chdir: ::c_long = 49; -pub const SYS_fchdir: ::c_long = 50; -pub const SYS_chroot: ::c_long = 51; -pub const SYS_fchmod: ::c_long = 52; -pub const SYS_fchmodat: ::c_long = 53; -pub const SYS_fchownat: ::c_long = 54; -pub const SYS_fchown: ::c_long = 55; -pub const SYS_openat: ::c_long = 56; -pub const SYS_close: ::c_long = 57; -pub const SYS_vhangup: ::c_long = 58; -pub const SYS_pipe2: ::c_long = 59; -pub const SYS_quotactl: ::c_long = 60; -pub const SYS_getdents64: ::c_long = 61; -pub const SYS_read: ::c_long = 63; -pub const SYS_write: ::c_long = 64; -pub const SYS_readv: ::c_long = 65; -pub const SYS_writev: ::c_long = 66; -pub const SYS_pread64: ::c_long = 67; -pub const SYS_pwrite64: ::c_long = 68; -pub const SYS_preadv: ::c_long = 69; -pub const SYS_pwritev: ::c_long = 70; -pub const SYS_pselect6: ::c_long = 72; -pub const SYS_ppoll: ::c_long = 73; -pub const SYS_signalfd4: ::c_long = 74; -pub const SYS_vmsplice: ::c_long = 75; -pub const SYS_splice: ::c_long = 76; -pub const SYS_tee: ::c_long = 77; -pub const SYS_readlinkat: ::c_long = 78; -pub const SYS_sync: ::c_long = 81; -pub const SYS_fsync: ::c_long = 82; -pub const SYS_fdatasync: ::c_long = 83; -pub const SYS_sync_file_range: ::c_long = 84; -pub const SYS_timerfd_create: ::c_long = 85; -pub const SYS_timerfd_settime: ::c_long = 86; -pub const SYS_timerfd_gettime: ::c_long = 87; -pub const SYS_utimensat: ::c_long = 88; -pub const SYS_acct: ::c_long = 89; -pub const SYS_capget: ::c_long = 90; -pub const SYS_capset: ::c_long = 91; -pub const SYS_personality: ::c_long = 92; -pub const SYS_exit: ::c_long = 93; -pub const SYS_exit_group: ::c_long = 94; -pub const SYS_waitid: ::c_long = 95; -pub const SYS_set_tid_address: ::c_long = 96; -pub const SYS_unshare: ::c_long = 97; -pub const SYS_futex: ::c_long = 98; -pub const SYS_set_robust_list: ::c_long = 99; -pub const SYS_get_robust_list: ::c_long = 100; -pub const SYS_nanosleep: ::c_long = 101; -pub const SYS_getitimer: ::c_long = 102; -pub const SYS_setitimer: ::c_long = 103; -pub const SYS_kexec_load: ::c_long = 104; -pub const SYS_init_module: ::c_long = 105; -pub const SYS_delete_module: ::c_long = 106; -pub const SYS_timer_create: ::c_long = 107; -pub const SYS_timer_gettime: ::c_long = 108; -pub const SYS_timer_getoverrun: ::c_long = 109; -pub const SYS_timer_settime: ::c_long = 110; -pub const SYS_timer_delete: ::c_long = 111; -pub const SYS_clock_settime: ::c_long = 112; -pub const SYS_clock_gettime: ::c_long = 113; -pub const SYS_clock_getres: ::c_long = 114; -pub const SYS_clock_nanosleep: ::c_long = 115; -pub const SYS_syslog: ::c_long = 116; -pub const SYS_ptrace: ::c_long = 117; -pub const SYS_sched_setparam: ::c_long = 118; -pub const SYS_sched_setscheduler: ::c_long = 119; -pub const SYS_sched_getscheduler: ::c_long = 120; -pub const SYS_sched_getparam: ::c_long = 121; -pub const SYS_sched_setaffinity: ::c_long = 122; -pub const SYS_sched_getaffinity: ::c_long = 123; -pub const SYS_sched_yield: ::c_long = 124; -pub const SYS_sched_get_priority_max: ::c_long = 125; -pub const SYS_sched_get_priority_min: ::c_long = 126; -pub const SYS_sched_rr_get_interval: ::c_long = 127; -pub const SYS_restart_syscall: ::c_long = 128; -pub const SYS_kill: ::c_long = 129; -pub const SYS_tkill: ::c_long = 130; -pub const SYS_tgkill: ::c_long = 131; -pub const SYS_sigaltstack: ::c_long = 132; -pub const SYS_rt_sigsuspend: ::c_long = 133; -pub const SYS_rt_sigaction: ::c_long = 134; -pub const SYS_rt_sigprocmask: ::c_long = 135; -pub const SYS_rt_sigpending: ::c_long = 136; -pub const SYS_rt_sigtimedwait: ::c_long = 137; -pub const SYS_rt_sigqueueinfo: ::c_long = 138; -pub const SYS_rt_sigreturn: ::c_long = 139; -pub const SYS_setpriority: ::c_long = 140; -pub const SYS_getpriority: ::c_long = 141; -pub const SYS_reboot: ::c_long = 142; -pub const SYS_setregid: ::c_long = 143; -pub const SYS_setgid: ::c_long = 144; -pub const SYS_setreuid: ::c_long = 145; -pub const SYS_setuid: ::c_long = 146; -pub const SYS_setresuid: ::c_long = 147; -pub const SYS_getresuid: ::c_long = 148; -pub const SYS_setresgid: ::c_long = 149; -pub const SYS_getresgid: ::c_long = 150; -pub const SYS_setfsuid: ::c_long = 151; -pub const SYS_setfsgid: ::c_long = 152; -pub const SYS_times: ::c_long = 153; -pub const SYS_setpgid: ::c_long = 154; -pub const SYS_getpgid: ::c_long = 155; -pub const SYS_getsid: ::c_long = 156; -pub const SYS_setsid: ::c_long = 157; -pub const SYS_getgroups: ::c_long = 158; -pub const SYS_setgroups: ::c_long = 159; -pub const SYS_uname: ::c_long = 160; -pub const SYS_sethostname: ::c_long = 161; -pub const SYS_setdomainname: ::c_long = 162; -pub const SYS_getrlimit: ::c_long = 163; -pub const SYS_setrlimit: ::c_long = 164; -pub const SYS_getrusage: ::c_long = 165; -pub const SYS_umask: ::c_long = 166; -pub const SYS_prctl: ::c_long = 167; -pub const SYS_getcpu: ::c_long = 168; -pub const SYS_gettimeofday: ::c_long = 169; -pub const SYS_settimeofday: ::c_long = 170; -pub const SYS_adjtimex: ::c_long = 171; -pub const SYS_getpid: ::c_long = 172; -pub const SYS_getppid: ::c_long = 173; -pub const SYS_getuid: ::c_long = 174; -pub const SYS_geteuid: ::c_long = 175; -pub const SYS_getgid: ::c_long = 176; -pub const SYS_getegid: ::c_long = 177; -pub const SYS_gettid: ::c_long = 178; -pub const SYS_sysinfo: ::c_long = 179; -pub const SYS_mq_open: ::c_long = 180; -pub const SYS_mq_unlink: ::c_long = 181; -pub const SYS_mq_timedsend: ::c_long = 182; -pub const SYS_mq_timedreceive: ::c_long = 183; -pub const SYS_mq_notify: ::c_long = 184; -pub const SYS_mq_getsetattr: ::c_long = 185; -pub const SYS_msgget: ::c_long = 186; -pub const SYS_msgctl: ::c_long = 187; -pub const SYS_msgrcv: ::c_long = 188; -pub const SYS_msgsnd: ::c_long = 189; -pub const SYS_semget: ::c_long = 190; -pub const SYS_semctl: ::c_long = 191; -pub const SYS_semtimedop: ::c_long = 192; -pub const SYS_semop: ::c_long = 193; -pub const SYS_shmget: ::c_long = 194; -pub const SYS_shmctl: ::c_long = 195; -pub const SYS_shmat: ::c_long = 196; -pub const SYS_shmdt: ::c_long = 197; -pub const SYS_socket: ::c_long = 198; -pub const SYS_socketpair: ::c_long = 199; -pub const SYS_bind: ::c_long = 200; -pub const SYS_listen: ::c_long = 201; -pub const SYS_accept: ::c_long = 202; -pub const SYS_connect: ::c_long = 203; -pub const SYS_getsockname: ::c_long = 204; -pub const SYS_getpeername: ::c_long = 205; -pub const SYS_sendto: ::c_long = 206; -pub const SYS_recvfrom: ::c_long = 207; -pub const SYS_setsockopt: ::c_long = 208; -pub const SYS_getsockopt: ::c_long = 209; -pub const SYS_shutdown: ::c_long = 210; -pub const SYS_sendmsg: ::c_long = 211; -pub const SYS_recvmsg: ::c_long = 212; -pub const SYS_readahead: ::c_long = 213; -pub const SYS_brk: ::c_long = 214; -pub const SYS_munmap: ::c_long = 215; -pub const SYS_mremap: ::c_long = 216; -pub const SYS_add_key: ::c_long = 217; -pub const SYS_request_key: ::c_long = 218; -pub const SYS_keyctl: ::c_long = 219; -pub const SYS_clone: ::c_long = 220; -pub const SYS_execve: ::c_long = 221; -pub const SYS_swapon: ::c_long = 224; -pub const SYS_swapoff: ::c_long = 225; -pub const SYS_mprotect: ::c_long = 226; -pub const SYS_msync: ::c_long = 227; -pub const SYS_mlock: ::c_long = 228; -pub const SYS_munlock: ::c_long = 229; -pub const SYS_mlockall: ::c_long = 230; -pub const SYS_munlockall: ::c_long = 231; -pub const SYS_mincore: ::c_long = 232; -pub const SYS_madvise: ::c_long = 233; -pub const SYS_remap_file_pages: ::c_long = 234; -pub const SYS_mbind: ::c_long = 235; -pub const SYS_get_mempolicy: ::c_long = 236; -pub const SYS_set_mempolicy: ::c_long = 237; -pub const SYS_migrate_pages: ::c_long = 238; -pub const SYS_move_pages: ::c_long = 239; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 240; -pub const SYS_perf_event_open: ::c_long = 241; -pub const SYS_accept4: ::c_long = 242; -pub const SYS_recvmmsg: ::c_long = 243; -pub const SYS_wait4: ::c_long = 260; -pub const SYS_prlimit64: ::c_long = 261; -pub const SYS_fanotify_init: ::c_long = 262; -pub const SYS_fanotify_mark: ::c_long = 263; -pub const SYS_name_to_handle_at: ::c_long = 264; -pub const SYS_open_by_handle_at: ::c_long = 265; -pub const SYS_clock_adjtime: ::c_long = 266; -pub const SYS_syncfs: ::c_long = 267; -pub const SYS_setns: ::c_long = 268; -pub const SYS_sendmmsg: ::c_long = 269; -pub const SYS_process_vm_readv: ::c_long = 270; -pub const SYS_process_vm_writev: ::c_long = 271; -pub const SYS_kcmp: ::c_long = 272; -pub const SYS_finit_module: ::c_long = 273; -pub const SYS_sched_setattr: ::c_long = 274; -pub const SYS_sched_getattr: ::c_long = 275; -pub const SYS_renameat2: ::c_long = 276; -pub const SYS_seccomp: ::c_long = 277; -pub const SYS_getrandom: ::c_long = 278; -pub const SYS_memfd_create: ::c_long = 279; -pub const SYS_bpf: ::c_long = 280; -pub const SYS_execveat: ::c_long = 281; -pub const SYS_userfaultfd: ::c_long = 282; -pub const SYS_membarrier: ::c_long = 283; -pub const SYS_mlock2: ::c_long = 284; -pub const SYS_copy_file_range: ::c_long = 285; -pub const SYS_preadv2: ::c_long = 286; -pub const SYS_pwritev2: ::c_long = 287; -pub const SYS_pkey_mprotect: ::c_long = 288; -pub const SYS_pkey_alloc: ::c_long = 289; -pub const SYS_pkey_free: ::c_long = 290; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/fuchsia/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/fuchsia/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/fuchsia/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/fuchsia/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,3920 +0,0 @@ -//! Definitions found commonly among almost all Unix derivatives -//! -//! More functions and definitions can be found in the more specific modules -//! according to the platform in question. - -use dox::{mem, Option}; - -// PUB_TYPE - -pub type pid_t = i32; -pub type uid_t = u32; -pub type gid_t = u32; -pub type in_addr_t = u32; -pub type in_port_t = u16; -pub type sighandler_t = ::size_t; -pub type cc_t = ::c_uchar; -pub type sa_family_t = u16; -pub type pthread_key_t = ::c_uint; -pub type speed_t = ::c_uint; -pub type tcflag_t = ::c_uint; -pub type clockid_t = ::c_int; -pub type key_t = ::c_int; -pub type id_t = ::c_uint; -pub type useconds_t = u32; -pub type dev_t = u64; -pub type socklen_t = u32; -pub type pthread_t = c_ulong; -pub type mode_t = u32; -pub type ino64_t = u64; -pub type off64_t = i64; -pub type blkcnt64_t = i64; -pub type rlim64_t = u64; -pub type mqd_t = ::c_int; -pub type nfds_t = ::c_ulong; -pub type nl_item = ::c_int; -pub type idtype_t = ::c_uint; -pub type loff_t = ::c_longlong; - -pub type __u8 = ::c_uchar; -pub type __u16 = ::c_ushort; -pub type __s16 = ::c_short; -pub type __u32 = ::c_uint; -pub type __s32 = ::c_int; - -pub type Elf32_Half = u16; -pub type Elf32_Word = u32; -pub type Elf32_Off = u32; -pub type Elf32_Addr = u32; - -pub type Elf64_Half = u16; -pub type Elf64_Word = u32; -pub type Elf64_Off = u64; -pub type Elf64_Addr = u64; -pub type Elf64_Xword = u64; - -pub type clock_t = c_long; -pub type time_t = c_long; -pub type suseconds_t = c_long; -pub type ino_t = u64; -pub type off_t = i64; -pub type blkcnt_t = i64; - -pub type shmatt_t = ::c_ulong; -pub type msgqnum_t = ::c_ulong; -pub type msglen_t = ::c_ulong; -pub type fsblkcnt_t = ::c_ulonglong; -pub type fsfilcnt_t = ::c_ulonglong; -pub type rlim_t = ::c_ulonglong; - -pub type c_long = i64; -pub type c_ulong = u64; - -// FIXME: why are these uninhabited types? that seems... wrong? -// Presumably these should be `()` or an `extern type` (when that stabilizes). -pub enum timezone {} -pub enum DIR {} -pub enum locale_t {} -pub enum fpos64_t {} // TODO: fill this out with a struct - -// PUB_STRUCT - -s! { - pub struct group { - pub gr_name: *mut ::c_char, - pub gr_passwd: *mut ::c_char, - pub gr_gid: ::gid_t, - pub gr_mem: *mut *mut ::c_char, - } - - pub struct utimbuf { - pub actime: time_t, - pub modtime: time_t, - } - - pub struct timeval { - pub tv_sec: time_t, - pub tv_usec: suseconds_t, - } - - // linux x32 compatibility - // See https://sourceware.org/bugzilla/show_bug.cgi?id=16437 - pub struct timespec { - pub tv_sec: time_t, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - pub tv_nsec: i64, - #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] - pub tv_nsec: ::c_long, - } - - pub struct rlimit { - pub rlim_cur: rlim_t, - pub rlim_max: rlim_t, - } - - pub struct rusage { - pub ru_utime: timeval, - pub ru_stime: timeval, - pub ru_maxrss: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad1: u32, - pub ru_ixrss: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad2: u32, - pub ru_idrss: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad3: u32, - pub ru_isrss: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad4: u32, - pub ru_minflt: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad5: u32, - pub ru_majflt: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad6: u32, - pub ru_nswap: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad7: u32, - pub ru_inblock: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad8: u32, - pub ru_oublock: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad9: u32, - pub ru_msgsnd: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad10: u32, - pub ru_msgrcv: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad11: u32, - pub ru_nsignals: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad12: u32, - pub ru_nvcsw: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad13: u32, - pub ru_nivcsw: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad14: u32, - - #[cfg(any(target_env = "musl", target_os = "emscripten"))] - __reserved: [c_long; 16], - } - - pub struct in_addr { - pub s_addr: in_addr_t, - } - - pub struct in6_addr { - pub s6_addr: [u8; 16], - __align: [u32; 0], - } - - pub struct ip_mreq { - pub imr_multiaddr: in_addr, - pub imr_interface: in_addr, - } - - pub struct ipv6_mreq { - pub ipv6mr_multiaddr: in6_addr, - #[cfg(target_os = "android")] - pub ipv6mr_interface: ::c_int, - #[cfg(not(target_os = "android"))] - pub ipv6mr_interface: ::c_uint, - } - - pub struct hostent { - pub h_name: *mut ::c_char, - pub h_aliases: *mut *mut ::c_char, - pub h_addrtype: ::c_int, - pub h_length: ::c_int, - pub h_addr_list: *mut *mut ::c_char, - } - - pub struct iovec { - pub iov_base: *mut ::c_void, - pub iov_len: ::size_t, - } - - pub struct pollfd { - pub fd: ::c_int, - pub events: ::c_short, - pub revents: ::c_short, - } - - pub struct winsize { - pub ws_row: ::c_ushort, - pub ws_col: ::c_ushort, - pub ws_xpixel: ::c_ushort, - pub ws_ypixel: ::c_ushort, - } - - pub struct linger { - pub l_onoff: ::c_int, - pub l_linger: ::c_int, - } - - pub struct sigval { - // Actually a union of an int and a void* - pub sival_ptr: *mut ::c_void - } - - // - pub struct itimerval { - pub it_interval: ::timeval, - pub it_value: ::timeval, - } - - // - pub struct tms { - pub tms_utime: ::clock_t, - pub tms_stime: ::clock_t, - pub tms_cutime: ::clock_t, - pub tms_cstime: ::clock_t, - } - - pub struct servent { - pub s_name: *mut ::c_char, - pub s_aliases: *mut *mut ::c_char, - pub s_port: ::c_int, - pub s_proto: *mut ::c_char, - } - - pub struct protoent { - pub p_name: *mut ::c_char, - pub p_aliases: *mut *mut ::c_char, - pub p_proto: ::c_int, - } - - pub struct aiocb { - pub aio_fildes: ::c_int, - pub aio_lio_opcode: ::c_int, - pub aio_reqprio: ::c_int, - pub aio_buf: *mut ::c_void, - pub aio_nbytes: ::size_t, - pub aio_sigevent: ::sigevent, - __td: *mut ::c_void, - __lock: [::c_int; 2], - __err: ::c_int, - __ret: ::ssize_t, - pub aio_offset: off_t, - __next: *mut ::c_void, - __prev: *mut ::c_void, - #[cfg(target_pointer_width = "32")] - __dummy4: [::c_char; 24], - #[cfg(target_pointer_width = "64")] - __dummy4: [::c_char; 16], - } - - pub struct sigaction { - pub sa_sigaction: ::sighandler_t, - pub sa_mask: ::sigset_t, - pub sa_flags: ::c_int, - pub sa_restorer: ::dox::Option, - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; ::NCCS], - pub __c_ispeed: ::speed_t, - pub __c_ospeed: ::speed_t, - } - - pub struct flock { - pub l_type: ::c_short, - pub l_whence: ::c_short, - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_pid: ::pid_t, - } - - pub struct sysinfo { - pub uptime: ::c_ulong, - pub loads: [::c_ulong; 3], - pub totalram: ::c_ulong, - pub freeram: ::c_ulong, - pub sharedram: ::c_ulong, - pub bufferram: ::c_ulong, - pub totalswap: ::c_ulong, - pub freeswap: ::c_ulong, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: ::c_ulong, - pub freehigh: ::c_ulong, - pub mem_unit: ::c_uint, - pub __reserved: [::c_char; 256], - } - - pub struct ucred { - pub pid: ::pid_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - } - - pub struct sockaddr { - pub sa_family: sa_family_t, - pub sa_data: [::c_char; 14], - } - - pub struct sockaddr_in { - pub sin_family: sa_family_t, - pub sin_port: ::in_port_t, - pub sin_addr: ::in_addr, - pub sin_zero: [u8; 8], - } - - pub struct sockaddr_in6 { - pub sin6_family: sa_family_t, - pub sin6_port: ::in_port_t, - pub sin6_flowinfo: u32, - pub sin6_addr: ::in6_addr, - pub sin6_scope_id: u32, - } - - pub struct sockaddr_un { - pub sun_family: sa_family_t, - pub sun_path: [::c_char; 108] - } - - pub struct sockaddr_storage { - pub ss_family: sa_family_t, - __ss_align: ::size_t, - __ss_pad2: [u8; 128 - 2 * 8], - } - - pub struct addrinfo { - pub ai_flags: ::c_int, - pub ai_family: ::c_int, - pub ai_socktype: ::c_int, - pub ai_protocol: ::c_int, - pub ai_addrlen: socklen_t, - - pub ai_addr: *mut ::sockaddr, - - pub ai_canonname: *mut c_char, - - pub ai_next: *mut addrinfo, - } - - pub struct sockaddr_nl { - pub nl_family: ::sa_family_t, - nl_pad: ::c_ushort, - pub nl_pid: u32, - pub nl_groups: u32 - } - - pub struct sockaddr_ll { - pub sll_family: ::c_ushort, - pub sll_protocol: ::c_ushort, - pub sll_ifindex: ::c_int, - pub sll_hatype: ::c_ushort, - pub sll_pkttype: ::c_uchar, - pub sll_halen: ::c_uchar, - pub sll_addr: [::c_uchar; 8] - } - - pub struct fd_set { - fds_bits: [::c_ulong; FD_SETSIZE / ULONG_SIZE], - } - - pub struct tm { - pub tm_sec: ::c_int, - pub tm_min: ::c_int, - pub tm_hour: ::c_int, - pub tm_mday: ::c_int, - pub tm_mon: ::c_int, - pub tm_year: ::c_int, - pub tm_wday: ::c_int, - pub tm_yday: ::c_int, - pub tm_isdst: ::c_int, - pub tm_gmtoff: ::c_long, - pub tm_zone: *const ::c_char, - } - - pub struct sched_param { - pub sched_priority: ::c_int, - #[cfg(target_env = "musl")] - pub sched_ss_low_priority: ::c_int, - #[cfg(target_env = "musl")] - pub sched_ss_repl_period: ::timespec, - #[cfg(target_env = "musl")] - pub sched_ss_init_budget: ::timespec, - #[cfg(target_env = "musl")] - pub sched_ss_max_repl: ::c_int, - } - - pub struct Dl_info { - pub dli_fname: *const ::c_char, - pub dli_fbase: *mut ::c_void, - pub dli_sname: *const ::c_char, - pub dli_saddr: *mut ::c_void, - } - - #[cfg_attr(any(all(target_arch = "x86", - not(target_env = "musl"), - not(target_os = "android")), - target_arch = "x86_64"), - repr(packed))] - pub struct epoll_event { - pub events: ::uint32_t, - pub u64: ::uint64_t, - } - - pub struct utsname { - pub sysname: [::c_char; 65], - pub nodename: [::c_char; 65], - pub release: [::c_char; 65], - pub version: [::c_char; 65], - pub machine: [::c_char; 65], - pub domainname: [::c_char; 65] - } - - pub struct lconv { - pub decimal_point: *mut ::c_char, - pub thousands_sep: *mut ::c_char, - pub grouping: *mut ::c_char, - pub int_curr_symbol: *mut ::c_char, - pub currency_symbol: *mut ::c_char, - pub mon_decimal_point: *mut ::c_char, - pub mon_thousands_sep: *mut ::c_char, - pub mon_grouping: *mut ::c_char, - pub positive_sign: *mut ::c_char, - pub negative_sign: *mut ::c_char, - pub int_frac_digits: ::c_char, - pub frac_digits: ::c_char, - pub p_cs_precedes: ::c_char, - pub p_sep_by_space: ::c_char, - pub n_cs_precedes: ::c_char, - pub n_sep_by_space: ::c_char, - pub p_sign_posn: ::c_char, - pub n_sign_posn: ::c_char, - pub int_p_cs_precedes: ::c_char, - pub int_p_sep_by_space: ::c_char, - pub int_n_cs_precedes: ::c_char, - pub int_n_sep_by_space: ::c_char, - pub int_p_sign_posn: ::c_char, - pub int_n_sign_posn: ::c_char, - } - - pub struct sigevent { - pub sigev_value: ::sigval, - pub sigev_signo: ::c_int, - pub sigev_notify: ::c_int, - // Actually a union. We only expose sigev_notify_thread_id because it's - // the most useful member - pub sigev_notify_thread_id: ::c_int, - #[cfg(target_pointer_width = "64")] - __unused1: [::c_int; 11], - #[cfg(target_pointer_width = "32")] - __unused1: [::c_int; 12] - } - - pub struct dirent { - pub d_ino: ::ino_t, - pub d_off: ::off_t, - pub d_reclen: ::c_ushort, - pub d_type: ::c_uchar, - pub d_name: [::c_char; 256], - } - - pub struct dirent64 { - pub d_ino: ::ino64_t, - pub d_off: ::off64_t, - pub d_reclen: ::c_ushort, - pub d_type: ::c_uchar, - pub d_name: [::c_char; 256], - } - - pub struct rlimit64 { - pub rlim_cur: rlim64_t, - pub rlim_max: rlim64_t, - } - - pub struct glob_t { - pub gl_pathc: ::size_t, - pub gl_pathv: *mut *mut c_char, - pub gl_offs: ::size_t, - pub gl_flags: ::c_int, - - __unused1: *mut ::c_void, - __unused2: *mut ::c_void, - __unused3: *mut ::c_void, - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - } - - pub struct ifaddrs { - pub ifa_next: *mut ifaddrs, - pub ifa_name: *mut c_char, - pub ifa_flags: ::c_uint, - pub ifa_addr: *mut ::sockaddr, - pub ifa_netmask: *mut ::sockaddr, - pub ifa_ifu: *mut ::sockaddr, // FIXME This should be a union - pub ifa_data: *mut ::c_void - } - - pub struct pthread_mutex_t { - #[cfg(any(target_arch = "mips", - target_arch = "arm", - target_arch = "powerpc", - all(target_arch = "x86_64", - target_pointer_width = "32")))] - __align: [::c_long; 0], - #[cfg(not(any(target_arch = "mips", - target_arch = "arm", - target_arch = "powerpc", - all(target_arch = "x86_64", - target_pointer_width = "32"))))] - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_MUTEX_T], - } - - pub struct pthread_rwlock_t { - #[cfg(any(target_arch = "mips", - target_arch = "arm", - target_arch = "powerpc", - all(target_arch = "x86_64", - target_pointer_width = "32")))] - __align: [::c_long; 0], - #[cfg(not(any(target_arch = "mips", - target_arch = "arm", - target_arch = "powerpc", - all(target_arch = "x86_64", - target_pointer_width = "32"))))] - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_RWLOCK_T], - } - - pub struct pthread_mutexattr_t { - #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", - target_arch = "mips64", target_arch = "s390x", - target_arch = "sparc64"))] - __align: [::c_int; 0], - #[cfg(not(any(target_arch = "x86_64", target_arch = "powerpc64", - target_arch = "mips64", target_arch = "s390x", - target_arch = "sparc64", target_arch = "aarch64")))] - __align: [::c_long; 0], - #[cfg(all(target_arch = "aarch64", target_env = "gnu"))] - __align: [::c_long; 0], - #[cfg(all(target_arch = "aarch64", target_env = "musl"))] - __align: [::c_int; 0], - size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T], - } - - pub struct pthread_rwlockattr_t { - #[cfg(any(target_env = "musl"))] - __align: [::c_int; 0], - #[cfg(not(any(target_env = "musl")))] - __align: [::c_long; 0], - size: [u8; __SIZEOF_PTHREAD_RWLOCKATTR_T], - } - - pub struct pthread_cond_t { - #[cfg(any(target_env = "musl"))] - __align: [*const ::c_void; 0], - #[cfg(not(any(target_env = "musl")))] - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_COND_T], - } - - pub struct pthread_condattr_t { - __align: [::c_int; 0], - size: [u8; __SIZEOF_PTHREAD_CONDATTR_T], - } - - pub struct passwd { - pub pw_name: *mut ::c_char, - pub pw_passwd: *mut ::c_char, - pub pw_uid: ::uid_t, - pub pw_gid: ::gid_t, - pub pw_gecos: *mut ::c_char, - pub pw_dir: *mut ::c_char, - pub pw_shell: *mut ::c_char, - } - - pub struct spwd { - pub sp_namp: *mut ::c_char, - pub sp_pwdp: *mut ::c_char, - pub sp_lstchg: ::c_long, - pub sp_min: ::c_long, - pub sp_max: ::c_long, - pub sp_warn: ::c_long, - pub sp_inact: ::c_long, - pub sp_expire: ::c_long, - pub sp_flag: ::c_ulong, - } - - pub struct statvfs { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_favail: ::fsfilcnt_t, - #[cfg(target_endian = "little")] - pub f_fsid: ::c_ulong, - #[cfg(all(target_pointer_width = "32", not(target_arch = "x86_64")))] - __f_unused: ::c_int, - #[cfg(target_endian = "big")] - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct dqblk { - pub dqb_bhardlimit: ::uint64_t, - pub dqb_bsoftlimit: ::uint64_t, - pub dqb_curspace: ::uint64_t, - pub dqb_ihardlimit: ::uint64_t, - pub dqb_isoftlimit: ::uint64_t, - pub dqb_curinodes: ::uint64_t, - pub dqb_btime: ::uint64_t, - pub dqb_itime: ::uint64_t, - pub dqb_valid: ::uint32_t, - } - - pub struct signalfd_siginfo { - pub ssi_signo: ::uint32_t, - pub ssi_errno: ::int32_t, - pub ssi_code: ::int32_t, - pub ssi_pid: ::uint32_t, - pub ssi_uid: ::uint32_t, - pub ssi_fd: ::int32_t, - pub ssi_tid: ::uint32_t, - pub ssi_band: ::uint32_t, - pub ssi_overrun: ::uint32_t, - pub ssi_trapno: ::uint32_t, - pub ssi_status: ::int32_t, - pub ssi_int: ::int32_t, - pub ssi_ptr: ::uint64_t, - pub ssi_utime: ::uint64_t, - pub ssi_stime: ::uint64_t, - pub ssi_addr: ::uint64_t, - _pad: [::uint8_t; 48], - } - - pub struct itimerspec { - pub it_interval: ::timespec, - pub it_value: ::timespec, - } - - pub struct fsid_t { - __val: [::c_int; 2], - } - - // x32 compatibility - // See https://sourceware.org/bugzilla/show_bug.cgi?id=21279 - pub struct mq_attr { - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - pub mq_flags: i64, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - pub mq_maxmsg: i64, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - pub mq_msgsize: i64, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - pub mq_curmsgs: i64, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - pad: [i64; 4], - - #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] - pub mq_flags: ::c_long, - #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] - pub mq_maxmsg: ::c_long, - #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] - pub mq_msgsize: ::c_long, - #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] - pub mq_curmsgs: ::c_long, - #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] - pad: [::c_long; 4], - } - - pub struct cpu_set_t { - #[cfg(all(target_pointer_width = "32", - not(target_arch = "x86_64")))] - bits: [u32; 32], - #[cfg(not(all(target_pointer_width = "32", - not(target_arch = "x86_64"))))] - bits: [u64; 16], - } - - pub struct if_nameindex { - pub if_index: ::c_uint, - pub if_name: *mut ::c_char, - } - - // System V IPC - pub struct msginfo { - pub msgpool: ::c_int, - pub msgmap: ::c_int, - pub msgmax: ::c_int, - pub msgmnb: ::c_int, - pub msgmni: ::c_int, - pub msgssz: ::c_int, - pub msgtql: ::c_int, - pub msgseg: ::c_ushort, - } - - pub struct mmsghdr { - pub msg_hdr: ::msghdr, - pub msg_len: ::c_uint, - } - - pub struct sembuf { - pub sem_num: ::c_ushort, - pub sem_op: ::c_short, - pub sem_flg: ::c_short, - } - - pub struct input_event { - pub time: ::timeval, - pub type_: ::__u16, - pub code: ::__u16, - pub value: ::__s32, - } - - pub struct input_id { - pub bustype: ::__u16, - pub vendor: ::__u16, - pub product: ::__u16, - pub version: ::__u16, - } - - pub struct input_absinfo { - pub value: ::__s32, - pub minimum: ::__s32, - pub maximum: ::__s32, - pub fuzz: ::__s32, - pub flat: ::__s32, - pub resolution: ::__s32, - } - - pub struct input_keymap_entry { - pub flags: ::__u8, - pub len: ::__u8, - pub index: ::__u16, - pub keycode: ::__u32, - pub scancode: [::__u8; 32], - } - - pub struct input_mask { - pub type_: ::__u32, - pub codes_size: ::__u32, - pub codes_ptr: ::__u64, - } - - pub struct ff_replay { - pub length: ::__u16, - pub delay: ::__u16, - } - - pub struct ff_trigger { - pub button: ::__u16, - pub interval: ::__u16, - } - - pub struct ff_envelope { - pub attack_length: ::__u16, - pub attack_level: ::__u16, - pub fade_length: ::__u16, - pub fade_level: ::__u16, - } - - pub struct ff_constant_effect { - pub level: ::__s16, - pub envelope: ff_envelope, - } - - pub struct ff_ramp_effect { - pub start_level: ::__s16, - pub end_level: ::__s16, - pub envelope: ff_envelope, - } - - pub struct ff_condition_effect { - pub right_saturation: ::__u16, - pub left_saturation: ::__u16, - - pub right_coeff: ::__s16, - pub left_coeff: ::__s16, - - pub deadband: ::__u16, - pub center: ::__s16, - } - - pub struct ff_periodic_effect { - pub waveform: ::__u16, - pub period: ::__u16, - pub magnitude: ::__s16, - pub offset: ::__s16, - pub phase: ::__u16, - - pub envelope: ff_envelope, - - pub custom_len: ::__u32, - pub custom_data: *mut ::__s16, - } - - pub struct ff_rumble_effect { - pub strong_magnitude: ::__u16, - pub weak_magnitude: ::__u16, - } - - pub struct ff_effect { - pub type_: ::__u16, - pub id: ::__s16, - pub direction: ::__u16, - pub trigger: ff_trigger, - pub replay: ff_replay, - // FIXME this is actually a union - #[cfg(target_pointer_width = "64")] - pub u: [u64; 4], - #[cfg(target_pointer_width = "32")] - pub u: [u32; 7], - } - - pub struct dl_phdr_info { - #[cfg(target_pointer_width = "64")] - pub dlpi_addr: Elf64_Addr, - #[cfg(target_pointer_width = "32")] - pub dlpi_addr: Elf32_Addr, - - pub dlpi_name: *const ::c_char, - - #[cfg(target_pointer_width = "64")] - pub dlpi_phdr: *const Elf64_Phdr, - #[cfg(target_pointer_width = "32")] - pub dlpi_phdr: *const Elf32_Phdr, - - #[cfg(target_pointer_width = "64")] - pub dlpi_phnum: Elf64_Half, - #[cfg(target_pointer_width = "32")] - pub dlpi_phnum: Elf32_Half, - - pub dlpi_adds: ::c_ulonglong, - pub dlpi_subs: ::c_ulonglong, - pub dlpi_tls_modid: ::size_t, - pub dlpi_tls_data: *mut ::c_void, - } - - pub struct Elf32_Phdr { - pub p_type: Elf32_Word, - pub p_offset: Elf32_Off, - pub p_vaddr: Elf32_Addr, - pub p_paddr: Elf32_Addr, - pub p_filesz: Elf32_Word, - pub p_memsz: Elf32_Word, - pub p_flags: Elf32_Word, - pub p_align: Elf32_Word, - } - - pub struct Elf64_Phdr { - pub p_type: Elf64_Word, - pub p_flags: Elf64_Word, - pub p_offset: Elf64_Off, - pub p_vaddr: Elf64_Addr, - pub p_paddr: Elf64_Addr, - pub p_filesz: Elf64_Xword, - pub p_memsz: Elf64_Xword, - pub p_align: Elf64_Xword, - } - - pub struct statfs64 { - pub f_type: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_flags: ::c_ulong, - pub f_spare: [::c_ulong; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_flags: ::c_int, - pub ss_size: ::size_t - } - - pub struct pthread_attr_t { - __size: [u64; 7] - } - - pub struct sigset_t { - __val: [::c_ulong; 16], - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::c_ulong, - __pad1: ::c_ulong, - __pad2: ::c_ulong, - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - pub msg_stime: ::time_t, - pub msg_rtime: ::time_t, - pub msg_ctime: ::time_t, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __pad1: ::c_ulong, - __pad2: ::c_ulong, - } - - pub struct statfs { - pub f_type: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_flags: ::c_ulong, - pub f_spare: [::c_ulong; 4], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::c_int, - __pad1: ::c_int, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::socklen_t, - __pad2: ::socklen_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::socklen_t, - pub __pad1: ::c_int, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct sem_t { - __val: [::c_int; 8], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_errno: ::c_int, - pub si_code: ::c_int, - pub _pad: [::c_int; 29], - _align: [usize; 0], - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 19], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } -} - -// PUB_CONST - -pub const SIG_DFL: sighandler_t = 0 as sighandler_t; -pub const SIG_IGN: sighandler_t = 1 as sighandler_t; -pub const SIG_ERR: sighandler_t = !0 as sighandler_t; - -pub const DT_FIFO: u8 = 1; -pub const DT_CHR: u8 = 2; -pub const DT_DIR: u8 = 4; -pub const DT_BLK: u8 = 6; -pub const DT_REG: u8 = 8; -pub const DT_LNK: u8 = 10; -pub const DT_SOCK: u8 = 12; - -pub const FD_CLOEXEC: ::c_int = 0x1; - -pub const USRQUOTA: ::c_int = 0; -pub const GRPQUOTA: ::c_int = 1; - -pub const SIGIOT: ::c_int = 6; - -pub const S_ISUID: ::c_int = 0x800; -pub const S_ISGID: ::c_int = 0x400; -pub const S_ISVTX: ::c_int = 0x200; - -pub const IF_NAMESIZE: ::size_t = 16; - -pub const LOG_EMERG: ::c_int = 0; -pub const LOG_ALERT: ::c_int = 1; -pub const LOG_CRIT: ::c_int = 2; -pub const LOG_ERR: ::c_int = 3; -pub const LOG_WARNING: ::c_int = 4; -pub const LOG_NOTICE: ::c_int = 5; -pub const LOG_INFO: ::c_int = 6; -pub const LOG_DEBUG: ::c_int = 7; - -pub const LOG_KERN: ::c_int = 0; -pub const LOG_USER: ::c_int = 1 << 3; -pub const LOG_MAIL: ::c_int = 2 << 3; -pub const LOG_DAEMON: ::c_int = 3 << 3; -pub const LOG_AUTH: ::c_int = 4 << 3; -pub const LOG_SYSLOG: ::c_int = 5 << 3; -pub const LOG_LPR: ::c_int = 6 << 3; -pub const LOG_NEWS: ::c_int = 7 << 3; -pub const LOG_UUCP: ::c_int = 8 << 3; -pub const LOG_LOCAL0: ::c_int = 16 << 3; -pub const LOG_LOCAL1: ::c_int = 17 << 3; -pub const LOG_LOCAL2: ::c_int = 18 << 3; -pub const LOG_LOCAL3: ::c_int = 19 << 3; -pub const LOG_LOCAL4: ::c_int = 20 << 3; -pub const LOG_LOCAL5: ::c_int = 21 << 3; -pub const LOG_LOCAL6: ::c_int = 22 << 3; -pub const LOG_LOCAL7: ::c_int = 23 << 3; - -pub const LOG_PID: ::c_int = 0x01; -pub const LOG_CONS: ::c_int = 0x02; -pub const LOG_ODELAY: ::c_int = 0x04; -pub const LOG_NDELAY: ::c_int = 0x08; -pub const LOG_NOWAIT: ::c_int = 0x10; - -pub const LOG_PRIMASK: ::c_int = 7; -pub const LOG_FACMASK: ::c_int = 0x3f8; - -pub const PRIO_PROCESS: ::c_int = 0; -pub const PRIO_PGRP: ::c_int = 1; -pub const PRIO_USER: ::c_int = 2; - -pub const PRIO_MIN: ::c_int = -20; -pub const PRIO_MAX: ::c_int = 20; - -pub const IPPROTO_ICMP: ::c_int = 1; -pub const IPPROTO_ICMPV6: ::c_int = 58; -pub const IPPROTO_TCP: ::c_int = 6; -pub const IPPROTO_UDP: ::c_int = 17; -pub const IPPROTO_IP: ::c_int = 0; -pub const IPPROTO_IPV6: ::c_int = 41; - -pub const INADDR_LOOPBACK: in_addr_t = 2130706433; -pub const INADDR_ANY: in_addr_t = 0; -pub const INADDR_BROADCAST: in_addr_t = 4294967295; -pub const INADDR_NONE: in_addr_t = 4294967295; - -pub const EXIT_FAILURE: ::c_int = 1; -pub const EXIT_SUCCESS: ::c_int = 0; -pub const RAND_MAX: ::c_int = 2147483647; -pub const EOF: ::c_int = -1; -pub const SEEK_SET: ::c_int = 0; -pub const SEEK_CUR: ::c_int = 1; -pub const SEEK_END: ::c_int = 2; -pub const _IOFBF: ::c_int = 0; -pub const _IONBF: ::c_int = 2; -pub const _IOLBF: ::c_int = 1; - -pub const F_DUPFD: ::c_int = 0; -pub const F_GETFD: ::c_int = 1; -pub const F_SETFD: ::c_int = 2; -pub const F_GETFL: ::c_int = 3; -pub const F_SETFL: ::c_int = 4; - -// Linux-specific fcntls -pub const F_SETLEASE: ::c_int = 1024; -pub const F_GETLEASE: ::c_int = 1025; -pub const F_NOTIFY: ::c_int = 1026; -pub const F_CANCELLK: ::c_int = 1029; -pub const F_DUPFD_CLOEXEC: ::c_int = 1030; -pub const F_SETPIPE_SZ: ::c_int = 1031; -pub const F_GETPIPE_SZ: ::c_int = 1032; -pub const F_ADD_SEALS: ::c_int = 1033; -pub const F_GET_SEALS: ::c_int = 1034; - -pub const F_SEAL_SEAL: ::c_int = 0x0001; -pub const F_SEAL_SHRINK: ::c_int = 0x0002; -pub const F_SEAL_GROW: ::c_int = 0x0004; -pub const F_SEAL_WRITE: ::c_int = 0x0008; - -// TODO(#235): Include file sealing fcntls once we have a way to verify them. - -pub const SIGTRAP: ::c_int = 5; - -pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; -pub const PTHREAD_CREATE_DETACHED: ::c_int = 1; - -pub const CLOCK_REALTIME: ::clockid_t = 0; -pub const CLOCK_MONOTONIC: ::clockid_t = 1; -pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 2; -pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 3; -pub const CLOCK_MONOTONIC_RAW: ::clockid_t = 4; -pub const CLOCK_REALTIME_COARSE: ::clockid_t = 5; -pub const CLOCK_MONOTONIC_COARSE: ::clockid_t = 6; -pub const CLOCK_BOOTTIME: ::clockid_t = 7; -pub const CLOCK_REALTIME_ALARM: ::clockid_t = 8; -pub const CLOCK_BOOTTIME_ALARM: ::clockid_t = 9; -// TODO(#247) Someday our Travis shall have glibc 2.21 (released in Sep -// 2014.) See also musl/mod.rs -// pub const CLOCK_SGI_CYCLE: ::clockid_t = 10; -// pub const CLOCK_TAI: ::clockid_t = 11; -pub const TIMER_ABSTIME: ::c_int = 1; - -pub const RLIMIT_CPU: ::c_int = 0; -pub const RLIMIT_FSIZE: ::c_int = 1; -pub const RLIMIT_DATA: ::c_int = 2; -pub const RLIMIT_STACK: ::c_int = 3; -pub const RLIMIT_CORE: ::c_int = 4; -pub const RLIMIT_LOCKS: ::c_int = 10; -pub const RLIMIT_SIGPENDING: ::c_int = 11; -pub const RLIMIT_MSGQUEUE: ::c_int = 12; -pub const RLIMIT_NICE: ::c_int = 13; -pub const RLIMIT_RTPRIO: ::c_int = 14; - -pub const RUSAGE_SELF: ::c_int = 0; - -pub const O_RDONLY: ::c_int = 0; -pub const O_WRONLY: ::c_int = 1; -pub const O_RDWR: ::c_int = 2; - -pub const SOCK_CLOEXEC: ::c_int = O_CLOEXEC; - -pub const S_IFIFO: ::mode_t = 4096; -pub const S_IFCHR: ::mode_t = 8192; -pub const S_IFBLK: ::mode_t = 24576; -pub const S_IFDIR: ::mode_t = 16384; -pub const S_IFREG: ::mode_t = 32768; -pub const S_IFLNK: ::mode_t = 40960; -pub const S_IFSOCK: ::mode_t = 49152; -pub const S_IFMT: ::mode_t = 61440; -pub const S_IRWXU: ::mode_t = 448; -pub const S_IXUSR: ::mode_t = 64; -pub const S_IWUSR: ::mode_t = 128; -pub const S_IRUSR: ::mode_t = 256; -pub const S_IRWXG: ::mode_t = 56; -pub const S_IXGRP: ::mode_t = 8; -pub const S_IWGRP: ::mode_t = 16; -pub const S_IRGRP: ::mode_t = 32; -pub const S_IRWXO: ::mode_t = 7; -pub const S_IXOTH: ::mode_t = 1; -pub const S_IWOTH: ::mode_t = 2; -pub const S_IROTH: ::mode_t = 4; -pub const F_OK: ::c_int = 0; -pub const R_OK: ::c_int = 4; -pub const W_OK: ::c_int = 2; -pub const X_OK: ::c_int = 1; -pub const STDIN_FILENO: ::c_int = 0; -pub const STDOUT_FILENO: ::c_int = 1; -pub const STDERR_FILENO: ::c_int = 2; -pub const SIGHUP: ::c_int = 1; -pub const SIGINT: ::c_int = 2; -pub const SIGQUIT: ::c_int = 3; -pub const SIGILL: ::c_int = 4; -pub const SIGABRT: ::c_int = 6; -pub const SIGFPE: ::c_int = 8; -pub const SIGKILL: ::c_int = 9; -pub const SIGSEGV: ::c_int = 11; -pub const SIGPIPE: ::c_int = 13; -pub const SIGALRM: ::c_int = 14; -pub const SIGTERM: ::c_int = 15; - -pub const PROT_NONE: ::c_int = 0; -pub const PROT_READ: ::c_int = 1; -pub const PROT_WRITE: ::c_int = 2; -pub const PROT_EXEC: ::c_int = 4; - -pub const LC_CTYPE: ::c_int = 0; -pub const LC_NUMERIC: ::c_int = 1; -pub const LC_TIME: ::c_int = 2; -pub const LC_COLLATE: ::c_int = 3; -pub const LC_MONETARY: ::c_int = 4; -pub const LC_MESSAGES: ::c_int = 5; -pub const LC_ALL: ::c_int = 6; -pub const LC_CTYPE_MASK: ::c_int = (1 << LC_CTYPE); -pub const LC_NUMERIC_MASK: ::c_int = (1 << LC_NUMERIC); -pub const LC_TIME_MASK: ::c_int = (1 << LC_TIME); -pub const LC_COLLATE_MASK: ::c_int = (1 << LC_COLLATE); -pub const LC_MONETARY_MASK: ::c_int = (1 << LC_MONETARY); -pub const LC_MESSAGES_MASK: ::c_int = (1 << LC_MESSAGES); -// LC_ALL_MASK defined per platform - -pub const MAP_FILE: ::c_int = 0x0000; -pub const MAP_SHARED: ::c_int = 0x0001; -pub const MAP_PRIVATE: ::c_int = 0x0002; -pub const MAP_FIXED: ::c_int = 0x0010; - -pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; - -// MS_ flags for msync(2) -pub const MS_ASYNC: ::c_int = 0x0001; -pub const MS_INVALIDATE: ::c_int = 0x0002; -pub const MS_SYNC: ::c_int = 0x0004; - -// MS_ flags for mount(2) -pub const MS_RDONLY: ::c_ulong = 0x01; -pub const MS_NOSUID: ::c_ulong = 0x02; -pub const MS_NODEV: ::c_ulong = 0x04; -pub const MS_NOEXEC: ::c_ulong = 0x08; -pub const MS_SYNCHRONOUS: ::c_ulong = 0x10; -pub const MS_REMOUNT: ::c_ulong = 0x20; -pub const MS_MANDLOCK: ::c_ulong = 0x40; -pub const MS_DIRSYNC: ::c_ulong = 0x80; -pub const MS_NOATIME: ::c_ulong = 0x0400; -pub const MS_NODIRATIME: ::c_ulong = 0x0800; -pub const MS_BIND: ::c_ulong = 0x1000; -pub const MS_MOVE: ::c_ulong = 0x2000; -pub const MS_REC: ::c_ulong = 0x4000; -pub const MS_SILENT: ::c_ulong = 0x8000; -pub const MS_POSIXACL: ::c_ulong = 0x010000; -pub const MS_UNBINDABLE: ::c_ulong = 0x020000; -pub const MS_PRIVATE: ::c_ulong = 0x040000; -pub const MS_SLAVE: ::c_ulong = 0x080000; -pub const MS_SHARED: ::c_ulong = 0x100000; -pub const MS_RELATIME: ::c_ulong = 0x200000; -pub const MS_KERNMOUNT: ::c_ulong = 0x400000; -pub const MS_I_VERSION: ::c_ulong = 0x800000; -pub const MS_STRICTATIME: ::c_ulong = 0x1000000; -pub const MS_ACTIVE: ::c_ulong = 0x40000000; -pub const MS_NOUSER: ::c_ulong = 0x80000000; -pub const MS_MGC_VAL: ::c_ulong = 0xc0ed0000; -pub const MS_MGC_MSK: ::c_ulong = 0xffff0000; -pub const MS_RMT_MASK: ::c_ulong = 0x800051; - -pub const EPERM: ::c_int = 1; -pub const ENOENT: ::c_int = 2; -pub const ESRCH: ::c_int = 3; -pub const EINTR: ::c_int = 4; -pub const EIO: ::c_int = 5; -pub const ENXIO: ::c_int = 6; -pub const E2BIG: ::c_int = 7; -pub const ENOEXEC: ::c_int = 8; -pub const EBADF: ::c_int = 9; -pub const ECHILD: ::c_int = 10; -pub const EAGAIN: ::c_int = 11; -pub const ENOMEM: ::c_int = 12; -pub const EACCES: ::c_int = 13; -pub const EFAULT: ::c_int = 14; -pub const ENOTBLK: ::c_int = 15; -pub const EBUSY: ::c_int = 16; -pub const EEXIST: ::c_int = 17; -pub const EXDEV: ::c_int = 18; -pub const ENODEV: ::c_int = 19; -pub const ENOTDIR: ::c_int = 20; -pub const EISDIR: ::c_int = 21; -pub const EINVAL: ::c_int = 22; -pub const ENFILE: ::c_int = 23; -pub const EMFILE: ::c_int = 24; -pub const ENOTTY: ::c_int = 25; -pub const ETXTBSY: ::c_int = 26; -pub const EFBIG: ::c_int = 27; -pub const ENOSPC: ::c_int = 28; -pub const ESPIPE: ::c_int = 29; -pub const EROFS: ::c_int = 30; -pub const EMLINK: ::c_int = 31; -pub const EPIPE: ::c_int = 32; -pub const EDOM: ::c_int = 33; -pub const ERANGE: ::c_int = 34; -pub const EWOULDBLOCK: ::c_int = EAGAIN; - -pub const SCM_RIGHTS: ::c_int = 0x01; -pub const SCM_CREDENTIALS: ::c_int = 0x02; - -pub const PROT_GROWSDOWN: ::c_int = 0x1000000; -pub const PROT_GROWSUP: ::c_int = 0x2000000; - -pub const MAP_TYPE: ::c_int = 0x000f; - -pub const MADV_NORMAL: ::c_int = 0; -pub const MADV_RANDOM: ::c_int = 1; -pub const MADV_SEQUENTIAL: ::c_int = 2; -pub const MADV_WILLNEED: ::c_int = 3; -pub const MADV_DONTNEED: ::c_int = 4; -pub const MADV_FREE: ::c_int = 8; -pub const MADV_REMOVE: ::c_int = 9; -pub const MADV_DONTFORK: ::c_int = 10; -pub const MADV_DOFORK: ::c_int = 11; -pub const MADV_MERGEABLE: ::c_int = 12; -pub const MADV_UNMERGEABLE: ::c_int = 13; -pub const MADV_HUGEPAGE: ::c_int = 14; -pub const MADV_NOHUGEPAGE: ::c_int = 15; -pub const MADV_DONTDUMP: ::c_int = 16; -pub const MADV_DODUMP: ::c_int = 17; -pub const MADV_HWPOISON: ::c_int = 100; -pub const MADV_SOFT_OFFLINE: ::c_int = 101; - -pub const IFF_UP: ::c_int = 0x1; -pub const IFF_BROADCAST: ::c_int = 0x2; -pub const IFF_DEBUG: ::c_int = 0x4; -pub const IFF_LOOPBACK: ::c_int = 0x8; -pub const IFF_POINTOPOINT: ::c_int = 0x10; -pub const IFF_NOTRAILERS: ::c_int = 0x20; -pub const IFF_RUNNING: ::c_int = 0x40; -pub const IFF_NOARP: ::c_int = 0x80; -pub const IFF_PROMISC: ::c_int = 0x100; -pub const IFF_ALLMULTI: ::c_int = 0x200; -pub const IFF_MASTER: ::c_int = 0x400; -pub const IFF_SLAVE: ::c_int = 0x800; -pub const IFF_MULTICAST: ::c_int = 0x1000; -pub const IFF_PORTSEL: ::c_int = 0x2000; -pub const IFF_AUTOMEDIA: ::c_int = 0x4000; -pub const IFF_DYNAMIC: ::c_int = 0x8000; - -pub const SOL_IP: ::c_int = 0; -pub const SOL_TCP: ::c_int = 6; -pub const SOL_UDP: ::c_int = 17; -pub const SOL_IPV6: ::c_int = 41; -pub const SOL_ICMPV6: ::c_int = 58; -pub const SOL_RAW: ::c_int = 255; -pub const SOL_DECNET: ::c_int = 261; -pub const SOL_X25: ::c_int = 262; -pub const SOL_PACKET: ::c_int = 263; -pub const SOL_ATM: ::c_int = 264; -pub const SOL_AAL: ::c_int = 265; -pub const SOL_IRDA: ::c_int = 266; -pub const SOL_NETBEUI: ::c_int = 267; -pub const SOL_LLC: ::c_int = 268; -pub const SOL_DCCP: ::c_int = 269; -pub const SOL_NETLINK: ::c_int = 270; -pub const SOL_TIPC: ::c_int = 271; - -pub const AF_UNSPEC: ::c_int = 0; -pub const AF_UNIX: ::c_int = 1; -pub const AF_LOCAL: ::c_int = 1; -pub const AF_INET: ::c_int = 2; -pub const AF_AX25: ::c_int = 3; -pub const AF_IPX: ::c_int = 4; -pub const AF_APPLETALK: ::c_int = 5; -pub const AF_NETROM: ::c_int = 6; -pub const AF_BRIDGE: ::c_int = 7; -pub const AF_ATMPVC: ::c_int = 8; -pub const AF_X25: ::c_int = 9; -pub const AF_INET6: ::c_int = 10; -pub const AF_ROSE: ::c_int = 11; -pub const AF_DECnet: ::c_int = 12; -pub const AF_NETBEUI: ::c_int = 13; -pub const AF_SECURITY: ::c_int = 14; -pub const AF_KEY: ::c_int = 15; -pub const AF_NETLINK: ::c_int = 16; -pub const AF_ROUTE: ::c_int = AF_NETLINK; -pub const AF_PACKET: ::c_int = 17; -pub const AF_ASH: ::c_int = 18; -pub const AF_ECONET: ::c_int = 19; -pub const AF_ATMSVC: ::c_int = 20; -pub const AF_RDS: ::c_int = 21; -pub const AF_SNA: ::c_int = 22; -pub const AF_IRDA: ::c_int = 23; -pub const AF_PPPOX: ::c_int = 24; -pub const AF_WANPIPE: ::c_int = 25; -pub const AF_LLC: ::c_int = 26; -pub const AF_CAN: ::c_int = 29; -pub const AF_TIPC: ::c_int = 30; -pub const AF_BLUETOOTH: ::c_int = 31; -pub const AF_IUCV: ::c_int = 32; -pub const AF_RXRPC: ::c_int = 33; -pub const AF_ISDN: ::c_int = 34; -pub const AF_PHONET: ::c_int = 35; -pub const AF_IEEE802154: ::c_int = 36; -pub const AF_CAIF: ::c_int = 37; -pub const AF_ALG: ::c_int = 38; - -pub const PF_UNSPEC: ::c_int = AF_UNSPEC; -pub const PF_UNIX: ::c_int = AF_UNIX; -pub const PF_LOCAL: ::c_int = AF_LOCAL; -pub const PF_INET: ::c_int = AF_INET; -pub const PF_AX25: ::c_int = AF_AX25; -pub const PF_IPX: ::c_int = AF_IPX; -pub const PF_APPLETALK: ::c_int = AF_APPLETALK; -pub const PF_NETROM: ::c_int = AF_NETROM; -pub const PF_BRIDGE: ::c_int = AF_BRIDGE; -pub const PF_ATMPVC: ::c_int = AF_ATMPVC; -pub const PF_X25: ::c_int = AF_X25; -pub const PF_INET6: ::c_int = AF_INET6; -pub const PF_ROSE: ::c_int = AF_ROSE; -pub const PF_DECnet: ::c_int = AF_DECnet; -pub const PF_NETBEUI: ::c_int = AF_NETBEUI; -pub const PF_SECURITY: ::c_int = AF_SECURITY; -pub const PF_KEY: ::c_int = AF_KEY; -pub const PF_NETLINK: ::c_int = AF_NETLINK; -pub const PF_ROUTE: ::c_int = AF_ROUTE; -pub const PF_PACKET: ::c_int = AF_PACKET; -pub const PF_ASH: ::c_int = AF_ASH; -pub const PF_ECONET: ::c_int = AF_ECONET; -pub const PF_ATMSVC: ::c_int = AF_ATMSVC; -pub const PF_RDS: ::c_int = AF_RDS; -pub const PF_SNA: ::c_int = AF_SNA; -pub const PF_IRDA: ::c_int = AF_IRDA; -pub const PF_PPPOX: ::c_int = AF_PPPOX; -pub const PF_WANPIPE: ::c_int = AF_WANPIPE; -pub const PF_LLC: ::c_int = AF_LLC; -pub const PF_CAN: ::c_int = AF_CAN; -pub const PF_TIPC: ::c_int = AF_TIPC; -pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; -pub const PF_IUCV: ::c_int = AF_IUCV; -pub const PF_RXRPC: ::c_int = AF_RXRPC; -pub const PF_ISDN: ::c_int = AF_ISDN; -pub const PF_PHONET: ::c_int = AF_PHONET; -pub const PF_IEEE802154: ::c_int = AF_IEEE802154; -pub const PF_CAIF: ::c_int = AF_CAIF; -pub const PF_ALG: ::c_int = AF_ALG; - -pub const SOMAXCONN: ::c_int = 128; - -pub const MSG_OOB: ::c_int = 1; -pub const MSG_PEEK: ::c_int = 2; -pub const MSG_DONTROUTE: ::c_int = 4; -pub const MSG_CTRUNC: ::c_int = 8; -pub const MSG_TRUNC: ::c_int = 0x20; -pub const MSG_DONTWAIT: ::c_int = 0x40; -pub const MSG_EOR: ::c_int = 0x80; -pub const MSG_WAITALL: ::c_int = 0x100; -pub const MSG_FIN: ::c_int = 0x200; -pub const MSG_SYN: ::c_int = 0x400; -pub const MSG_CONFIRM: ::c_int = 0x800; -pub const MSG_RST: ::c_int = 0x1000; -pub const MSG_ERRQUEUE: ::c_int = 0x2000; -pub const MSG_NOSIGNAL: ::c_int = 0x4000; -pub const MSG_MORE: ::c_int = 0x8000; -pub const MSG_WAITFORONE: ::c_int = 0x10000; -pub const MSG_FASTOPEN: ::c_int = 0x20000000; -pub const MSG_CMSG_CLOEXEC: ::c_int = 0x40000000; - -pub const SCM_TIMESTAMP: ::c_int = SO_TIMESTAMP; - -pub const SOCK_RAW: ::c_int = 3; -pub const SOCK_RDM: ::c_int = 4; -pub const IP_MULTICAST_IF: ::c_int = 32; -pub const IP_MULTICAST_TTL: ::c_int = 33; -pub const IP_MULTICAST_LOOP: ::c_int = 34; -pub const IP_TTL: ::c_int = 2; -pub const IP_HDRINCL: ::c_int = 3; -pub const IP_ADD_MEMBERSHIP: ::c_int = 35; -pub const IP_DROP_MEMBERSHIP: ::c_int = 36; -pub const IP_TRANSPARENT: ::c_int = 19; -pub const IPV6_ADD_MEMBERSHIP: ::c_int = 20; -pub const IPV6_DROP_MEMBERSHIP: ::c_int = 21; - -pub const TCP_NODELAY: ::c_int = 1; -pub const TCP_MAXSEG: ::c_int = 2; -pub const TCP_CORK: ::c_int = 3; -pub const TCP_KEEPIDLE: ::c_int = 4; -pub const TCP_KEEPINTVL: ::c_int = 5; -pub const TCP_KEEPCNT: ::c_int = 6; -pub const TCP_SYNCNT: ::c_int = 7; -pub const TCP_LINGER2: ::c_int = 8; -pub const TCP_DEFER_ACCEPT: ::c_int = 9; -pub const TCP_WINDOW_CLAMP: ::c_int = 10; -pub const TCP_INFO: ::c_int = 11; -pub const TCP_QUICKACK: ::c_int = 12; -pub const TCP_CONGESTION: ::c_int = 13; - -pub const IPV6_MULTICAST_LOOP: ::c_int = 19; -pub const IPV6_V6ONLY: ::c_int = 26; - -pub const SO_DEBUG: ::c_int = 1; - -pub const SHUT_RD: ::c_int = 0; -pub const SHUT_WR: ::c_int = 1; -pub const SHUT_RDWR: ::c_int = 2; - -pub const LOCK_SH: ::c_int = 1; -pub const LOCK_EX: ::c_int = 2; -pub const LOCK_NB: ::c_int = 4; -pub const LOCK_UN: ::c_int = 8; - -pub const SS_ONSTACK: ::c_int = 1; -pub const SS_DISABLE: ::c_int = 2; - -pub const PATH_MAX: ::c_int = 4096; - -pub const FD_SETSIZE: usize = 1024; - -pub const EPOLLIN: ::c_int = 0x1; -pub const EPOLLPRI: ::c_int = 0x2; -pub const EPOLLOUT: ::c_int = 0x4; -pub const EPOLLRDNORM: ::c_int = 0x40; -pub const EPOLLRDBAND: ::c_int = 0x80; -pub const EPOLLWRNORM: ::c_int = 0x100; -pub const EPOLLWRBAND: ::c_int = 0x200; -pub const EPOLLMSG: ::c_int = 0x400; -pub const EPOLLERR: ::c_int = 0x8; -pub const EPOLLHUP: ::c_int = 0x10; -pub const EPOLLET: ::c_int = 0x80000000; - -pub const EPOLL_CTL_ADD: ::c_int = 1; -pub const EPOLL_CTL_MOD: ::c_int = 3; -pub const EPOLL_CTL_DEL: ::c_int = 2; - -pub const MNT_DETACH: ::c_int = 0x2; -pub const MNT_EXPIRE: ::c_int = 0x4; - -pub const Q_GETFMT: ::c_int = 0x800004; -pub const Q_GETINFO: ::c_int = 0x800005; -pub const Q_SETINFO: ::c_int = 0x800006; -pub const QIF_BLIMITS: ::uint32_t = 1; -pub const QIF_SPACE: ::uint32_t = 2; -pub const QIF_ILIMITS: ::uint32_t = 4; -pub const QIF_INODES: ::uint32_t = 8; -pub const QIF_BTIME: ::uint32_t = 16; -pub const QIF_ITIME: ::uint32_t = 32; -pub const QIF_LIMITS: ::uint32_t = 5; -pub const QIF_USAGE: ::uint32_t = 10; -pub const QIF_TIMES: ::uint32_t = 48; -pub const QIF_ALL: ::uint32_t = 63; - -pub const MNT_FORCE: ::c_int = 0x1; - -pub const Q_SYNC: ::c_int = 0x800001; -pub const Q_QUOTAON: ::c_int = 0x800002; -pub const Q_QUOTAOFF: ::c_int = 0x800003; -pub const Q_GETQUOTA: ::c_int = 0x800007; -pub const Q_SETQUOTA: ::c_int = 0x800008; - -pub const TCIOFF: ::c_int = 2; -pub const TCION: ::c_int = 3; -pub const TCOOFF: ::c_int = 0; -pub const TCOON: ::c_int = 1; -pub const TCIFLUSH: ::c_int = 0; -pub const TCOFLUSH: ::c_int = 1; -pub const TCIOFLUSH: ::c_int = 2; -pub const NL0: ::c_int = 0x00000000; -pub const NL1: ::c_int = 0x00000100; -pub const TAB0: ::c_int = 0x00000000; -pub const CR0: ::c_int = 0x00000000; -pub const FF0: ::c_int = 0x00000000; -pub const BS0: ::c_int = 0x00000000; -pub const VT0: ::c_int = 0x00000000; -pub const VERASE: usize = 2; -pub const VKILL: usize = 3; -pub const VINTR: usize = 0; -pub const VQUIT: usize = 1; -pub const VLNEXT: usize = 15; -pub const IGNBRK: ::tcflag_t = 0x00000001; -pub const BRKINT: ::tcflag_t = 0x00000002; -pub const IGNPAR: ::tcflag_t = 0x00000004; -pub const PARMRK: ::tcflag_t = 0x00000008; -pub const INPCK: ::tcflag_t = 0x00000010; -pub const ISTRIP: ::tcflag_t = 0x00000020; -pub const INLCR: ::tcflag_t = 0x00000040; -pub const IGNCR: ::tcflag_t = 0x00000080; -pub const ICRNL: ::tcflag_t = 0x00000100; -pub const IXANY: ::tcflag_t = 0x00000800; -pub const IMAXBEL: ::tcflag_t = 0x00002000; -pub const OPOST: ::tcflag_t = 0x1; -pub const CS5: ::tcflag_t = 0x00000000; -pub const CRTSCTS: ::tcflag_t = 0x80000000; -pub const ECHO: ::tcflag_t = 0x00000008; -pub const OCRNL: ::tcflag_t = 0o000010; -pub const ONOCR: ::tcflag_t = 0o000020; -pub const ONLRET: ::tcflag_t = 0o000040; -pub const OFILL: ::tcflag_t = 0o000100; -pub const OFDEL: ::tcflag_t = 0o000200; - -pub const CLONE_VM: ::c_int = 0x100; -pub const CLONE_FS: ::c_int = 0x200; -pub const CLONE_FILES: ::c_int = 0x400; -pub const CLONE_SIGHAND: ::c_int = 0x800; -pub const CLONE_PTRACE: ::c_int = 0x2000; -pub const CLONE_VFORK: ::c_int = 0x4000; -pub const CLONE_PARENT: ::c_int = 0x8000; -pub const CLONE_THREAD: ::c_int = 0x10000; -pub const CLONE_NEWNS: ::c_int = 0x20000; -pub const CLONE_SYSVSEM: ::c_int = 0x40000; -pub const CLONE_SETTLS: ::c_int = 0x80000; -pub const CLONE_PARENT_SETTID: ::c_int = 0x100000; -pub const CLONE_CHILD_CLEARTID: ::c_int = 0x200000; -pub const CLONE_DETACHED: ::c_int = 0x400000; -pub const CLONE_UNTRACED: ::c_int = 0x800000; -pub const CLONE_CHILD_SETTID: ::c_int = 0x01000000; -pub const CLONE_NEWUTS: ::c_int = 0x04000000; -pub const CLONE_NEWIPC: ::c_int = 0x08000000; -pub const CLONE_NEWUSER: ::c_int = 0x10000000; -pub const CLONE_NEWPID: ::c_int = 0x20000000; -pub const CLONE_NEWNET: ::c_int = 0x40000000; -pub const CLONE_IO: ::c_int = 0x80000000; -pub const CLONE_NEWCGROUP: ::c_int = 0x02000000; - -pub const WNOHANG: ::c_int = 0x00000001; -pub const WUNTRACED: ::c_int = 0x00000002; -pub const WSTOPPED: ::c_int = WUNTRACED; -pub const WEXITED: ::c_int = 0x00000004; -pub const WCONTINUED: ::c_int = 0x00000008; -pub const WNOWAIT: ::c_int = 0x01000000; - -// Options set using PTRACE_SETOPTIONS. -pub const PTRACE_O_TRACESYSGOOD: ::c_int = 0x00000001; -pub const PTRACE_O_TRACEFORK: ::c_int = 0x00000002; -pub const PTRACE_O_TRACEVFORK: ::c_int = 0x00000004; -pub const PTRACE_O_TRACECLONE: ::c_int = 0x00000008; -pub const PTRACE_O_TRACEEXEC: ::c_int = 0x00000010; -pub const PTRACE_O_TRACEVFORKDONE: ::c_int = 0x00000020; -pub const PTRACE_O_TRACEEXIT: ::c_int = 0x00000040; -pub const PTRACE_O_TRACESECCOMP: ::c_int = 0x00000080; -pub const PTRACE_O_EXITKILL: ::c_int = 0x00100000; -pub const PTRACE_O_SUSPEND_SECCOMP: ::c_int = 0x00200000; -pub const PTRACE_O_MASK: ::c_int = 0x003000ff; - -// Wait extended result codes for the above trace options. -pub const PTRACE_EVENT_FORK: ::c_int = 1; -pub const PTRACE_EVENT_VFORK: ::c_int = 2; -pub const PTRACE_EVENT_CLONE: ::c_int = 3; -pub const PTRACE_EVENT_EXEC: ::c_int = 4; -pub const PTRACE_EVENT_VFORK_DONE: ::c_int = 5; -pub const PTRACE_EVENT_EXIT: ::c_int = 6; -pub const PTRACE_EVENT_SECCOMP: ::c_int = 7; -// PTRACE_EVENT_STOP was added to glibc in 2.26 -// pub const PTRACE_EVENT_STOP: ::c_int = 128; - -pub const __WNOTHREAD: ::c_int = 0x20000000; -pub const __WALL: ::c_int = 0x40000000; -pub const __WCLONE: ::c_int = 0x80000000; - -pub const SPLICE_F_MOVE: ::c_uint = 0x01; -pub const SPLICE_F_NONBLOCK: ::c_uint = 0x02; -pub const SPLICE_F_MORE: ::c_uint = 0x04; -pub const SPLICE_F_GIFT: ::c_uint = 0x08; - -pub const RTLD_LOCAL: ::c_int = 0; -pub const RTLD_LAZY: ::c_int = 1; - -pub const POSIX_FADV_NORMAL: ::c_int = 0; -pub const POSIX_FADV_RANDOM: ::c_int = 1; -pub const POSIX_FADV_SEQUENTIAL: ::c_int = 2; -pub const POSIX_FADV_WILLNEED: ::c_int = 3; - -pub const AT_FDCWD: ::c_int = -100; -pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x100; -pub const AT_REMOVEDIR: ::c_int = 0x200; -pub const AT_SYMLINK_FOLLOW: ::c_int = 0x400; -pub const AT_NO_AUTOMOUNT: ::c_int = 0x800; -pub const AT_EMPTY_PATH: ::c_int = 0x1000; - -pub const LOG_CRON: ::c_int = 9 << 3; -pub const LOG_AUTHPRIV: ::c_int = 10 << 3; -pub const LOG_FTP: ::c_int = 11 << 3; -pub const LOG_PERROR: ::c_int = 0x20; - -pub const PIPE_BUF: usize = 4096; - -pub const SI_LOAD_SHIFT: ::c_uint = 16; - -pub const SIGEV_SIGNAL: ::c_int = 0; -pub const SIGEV_NONE: ::c_int = 1; -pub const SIGEV_THREAD: ::c_int = 2; - -pub const P_ALL: idtype_t = 0; -pub const P_PID: idtype_t = 1; -pub const P_PGID: idtype_t = 2; - -pub const UTIME_OMIT: c_long = 1073741822; -pub const UTIME_NOW: c_long = 1073741823; - -pub const POLLIN: ::c_short = 0x1; -pub const POLLPRI: ::c_short = 0x2; -pub const POLLOUT: ::c_short = 0x4; -pub const POLLERR: ::c_short = 0x8; -pub const POLLHUP: ::c_short = 0x10; -pub const POLLNVAL: ::c_short = 0x20; -pub const POLLRDNORM: ::c_short = 0x040; -pub const POLLRDBAND: ::c_short = 0x080; - -pub const ABDAY_1: ::nl_item = 0x20000; -pub const ABDAY_2: ::nl_item = 0x20001; -pub const ABDAY_3: ::nl_item = 0x20002; -pub const ABDAY_4: ::nl_item = 0x20003; -pub const ABDAY_5: ::nl_item = 0x20004; -pub const ABDAY_6: ::nl_item = 0x20005; -pub const ABDAY_7: ::nl_item = 0x20006; - -pub const DAY_1: ::nl_item = 0x20007; -pub const DAY_2: ::nl_item = 0x20008; -pub const DAY_3: ::nl_item = 0x20009; -pub const DAY_4: ::nl_item = 0x2000A; -pub const DAY_5: ::nl_item = 0x2000B; -pub const DAY_6: ::nl_item = 0x2000C; -pub const DAY_7: ::nl_item = 0x2000D; - -pub const ABMON_1: ::nl_item = 0x2000E; -pub const ABMON_2: ::nl_item = 0x2000F; -pub const ABMON_3: ::nl_item = 0x20010; -pub const ABMON_4: ::nl_item = 0x20011; -pub const ABMON_5: ::nl_item = 0x20012; -pub const ABMON_6: ::nl_item = 0x20013; -pub const ABMON_7: ::nl_item = 0x20014; -pub const ABMON_8: ::nl_item = 0x20015; -pub const ABMON_9: ::nl_item = 0x20016; -pub const ABMON_10: ::nl_item = 0x20017; -pub const ABMON_11: ::nl_item = 0x20018; -pub const ABMON_12: ::nl_item = 0x20019; - -pub const MON_1: ::nl_item = 0x2001A; -pub const MON_2: ::nl_item = 0x2001B; -pub const MON_3: ::nl_item = 0x2001C; -pub const MON_4: ::nl_item = 0x2001D; -pub const MON_5: ::nl_item = 0x2001E; -pub const MON_6: ::nl_item = 0x2001F; -pub const MON_7: ::nl_item = 0x20020; -pub const MON_8: ::nl_item = 0x20021; -pub const MON_9: ::nl_item = 0x20022; -pub const MON_10: ::nl_item = 0x20023; -pub const MON_11: ::nl_item = 0x20024; -pub const MON_12: ::nl_item = 0x20025; - -pub const AM_STR: ::nl_item = 0x20026; -pub const PM_STR: ::nl_item = 0x20027; - -pub const D_T_FMT: ::nl_item = 0x20028; -pub const D_FMT: ::nl_item = 0x20029; -pub const T_FMT: ::nl_item = 0x2002A; -pub const T_FMT_AMPM: ::nl_item = 0x2002B; - -pub const ERA: ::nl_item = 0x2002C; -pub const ERA_D_FMT: ::nl_item = 0x2002E; -pub const ALT_DIGITS: ::nl_item = 0x2002F; -pub const ERA_D_T_FMT: ::nl_item = 0x20030; -pub const ERA_T_FMT: ::nl_item = 0x20031; - -pub const CODESET: ::nl_item = 14; - -pub const CRNCYSTR: ::nl_item = 0x4000F; - -pub const RUSAGE_THREAD: ::c_int = 1; -pub const RUSAGE_CHILDREN: ::c_int = -1; - -pub const RADIXCHAR: ::nl_item = 0x10000; -pub const THOUSEP: ::nl_item = 0x10001; - -pub const YESEXPR: ::nl_item = 0x50000; -pub const NOEXPR: ::nl_item = 0x50001; -pub const YESSTR: ::nl_item = 0x50002; -pub const NOSTR: ::nl_item = 0x50003; - -pub const FILENAME_MAX: ::c_uint = 4096; -pub const L_tmpnam: ::c_uint = 20; -pub const _PC_LINK_MAX: ::c_int = 0; -pub const _PC_MAX_CANON: ::c_int = 1; -pub const _PC_MAX_INPUT: ::c_int = 2; -pub const _PC_NAME_MAX: ::c_int = 3; -pub const _PC_PATH_MAX: ::c_int = 4; -pub const _PC_PIPE_BUF: ::c_int = 5; -pub const _PC_CHOWN_RESTRICTED: ::c_int = 6; -pub const _PC_NO_TRUNC: ::c_int = 7; -pub const _PC_VDISABLE: ::c_int = 8; -pub const _PC_SYNC_IO: ::c_int = 9; -pub const _PC_ASYNC_IO: ::c_int = 10; -pub const _PC_PRIO_IO: ::c_int = 11; -pub const _PC_SOCK_MAXBUF: ::c_int = 12; -pub const _PC_FILESIZEBITS: ::c_int = 13; -pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 14; -pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 15; -pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 16; -pub const _PC_REC_XFER_ALIGN: ::c_int = 17; -pub const _PC_ALLOC_SIZE_MIN: ::c_int = 18; -pub const _PC_SYMLINK_MAX: ::c_int = 19; -pub const _PC_2_SYMLINKS: ::c_int = 20; - -pub const _SC_ARG_MAX: ::c_int = 0; -pub const _SC_CHILD_MAX: ::c_int = 1; -pub const _SC_CLK_TCK: ::c_int = 2; -pub const _SC_NGROUPS_MAX: ::c_int = 3; -pub const _SC_OPEN_MAX: ::c_int = 4; -pub const _SC_STREAM_MAX: ::c_int = 5; -pub const _SC_TZNAME_MAX: ::c_int = 6; -pub const _SC_JOB_CONTROL: ::c_int = 7; -pub const _SC_SAVED_IDS: ::c_int = 8; -pub const _SC_REALTIME_SIGNALS: ::c_int = 9; -pub const _SC_PRIORITY_SCHEDULING: ::c_int = 10; -pub const _SC_TIMERS: ::c_int = 11; -pub const _SC_ASYNCHRONOUS_IO: ::c_int = 12; -pub const _SC_PRIORITIZED_IO: ::c_int = 13; -pub const _SC_SYNCHRONIZED_IO: ::c_int = 14; -pub const _SC_FSYNC: ::c_int = 15; -pub const _SC_MAPPED_FILES: ::c_int = 16; -pub const _SC_MEMLOCK: ::c_int = 17; -pub const _SC_MEMLOCK_RANGE: ::c_int = 18; -pub const _SC_MEMORY_PROTECTION: ::c_int = 19; -pub const _SC_MESSAGE_PASSING: ::c_int = 20; -pub const _SC_SEMAPHORES: ::c_int = 21; -pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 22; -pub const _SC_AIO_LISTIO_MAX: ::c_int = 23; -pub const _SC_AIO_MAX: ::c_int = 24; -pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 25; -pub const _SC_DELAYTIMER_MAX: ::c_int = 26; -pub const _SC_MQ_OPEN_MAX: ::c_int = 27; -pub const _SC_MQ_PRIO_MAX: ::c_int = 28; -pub const _SC_VERSION: ::c_int = 29; -pub const _SC_PAGESIZE: ::c_int = 30; -pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; -pub const _SC_RTSIG_MAX: ::c_int = 31; -pub const _SC_SEM_NSEMS_MAX: ::c_int = 32; -pub const _SC_SEM_VALUE_MAX: ::c_int = 33; -pub const _SC_SIGQUEUE_MAX: ::c_int = 34; -pub const _SC_TIMER_MAX: ::c_int = 35; -pub const _SC_BC_BASE_MAX: ::c_int = 36; -pub const _SC_BC_DIM_MAX: ::c_int = 37; -pub const _SC_BC_SCALE_MAX: ::c_int = 38; -pub const _SC_BC_STRING_MAX: ::c_int = 39; -pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 40; -pub const _SC_EXPR_NEST_MAX: ::c_int = 42; -pub const _SC_LINE_MAX: ::c_int = 43; -pub const _SC_RE_DUP_MAX: ::c_int = 44; -pub const _SC_2_VERSION: ::c_int = 46; -pub const _SC_2_C_BIND: ::c_int = 47; -pub const _SC_2_C_DEV: ::c_int = 48; -pub const _SC_2_FORT_DEV: ::c_int = 49; -pub const _SC_2_FORT_RUN: ::c_int = 50; -pub const _SC_2_SW_DEV: ::c_int = 51; -pub const _SC_2_LOCALEDEF: ::c_int = 52; -pub const _SC_UIO_MAXIOV: ::c_int = 60; -pub const _SC_IOV_MAX: ::c_int = 60; -pub const _SC_THREADS: ::c_int = 67; -pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 68; -pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 69; -pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 70; -pub const _SC_LOGIN_NAME_MAX: ::c_int = 71; -pub const _SC_TTY_NAME_MAX: ::c_int = 72; -pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 73; -pub const _SC_THREAD_KEYS_MAX: ::c_int = 74; -pub const _SC_THREAD_STACK_MIN: ::c_int = 75; -pub const _SC_THREAD_THREADS_MAX: ::c_int = 76; -pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 77; -pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 78; -pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 79; -pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 80; -pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 81; -pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 82; -pub const _SC_NPROCESSORS_CONF: ::c_int = 83; -pub const _SC_NPROCESSORS_ONLN: ::c_int = 84; -pub const _SC_PHYS_PAGES: ::c_int = 85; -pub const _SC_AVPHYS_PAGES: ::c_int = 86; -pub const _SC_ATEXIT_MAX: ::c_int = 87; -pub const _SC_PASS_MAX: ::c_int = 88; -pub const _SC_XOPEN_VERSION: ::c_int = 89; -pub const _SC_XOPEN_XCU_VERSION: ::c_int = 90; -pub const _SC_XOPEN_UNIX: ::c_int = 91; -pub const _SC_XOPEN_CRYPT: ::c_int = 92; -pub const _SC_XOPEN_ENH_I18N: ::c_int = 93; -pub const _SC_XOPEN_SHM: ::c_int = 94; -pub const _SC_2_CHAR_TERM: ::c_int = 95; -pub const _SC_2_UPE: ::c_int = 97; -pub const _SC_XOPEN_XPG2: ::c_int = 98; -pub const _SC_XOPEN_XPG3: ::c_int = 99; -pub const _SC_XOPEN_XPG4: ::c_int = 100; -pub const _SC_NZERO: ::c_int = 109; -pub const _SC_XBS5_ILP32_OFF32: ::c_int = 125; -pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 126; -pub const _SC_XBS5_LP64_OFF64: ::c_int = 127; -pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 128; -pub const _SC_XOPEN_LEGACY: ::c_int = 129; -pub const _SC_XOPEN_REALTIME: ::c_int = 130; -pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 131; -pub const _SC_ADVISORY_INFO: ::c_int = 132; -pub const _SC_BARRIERS: ::c_int = 133; -pub const _SC_CLOCK_SELECTION: ::c_int = 137; -pub const _SC_CPUTIME: ::c_int = 138; -pub const _SC_THREAD_CPUTIME: ::c_int = 139; -pub const _SC_MONOTONIC_CLOCK: ::c_int = 149; -pub const _SC_READER_WRITER_LOCKS: ::c_int = 153; -pub const _SC_SPIN_LOCKS: ::c_int = 154; -pub const _SC_REGEXP: ::c_int = 155; -pub const _SC_SHELL: ::c_int = 157; -pub const _SC_SPAWN: ::c_int = 159; -pub const _SC_SPORADIC_SERVER: ::c_int = 160; -pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 161; -pub const _SC_TIMEOUTS: ::c_int = 164; -pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 165; -pub const _SC_2_PBS: ::c_int = 168; -pub const _SC_2_PBS_ACCOUNTING: ::c_int = 169; -pub const _SC_2_PBS_LOCATE: ::c_int = 170; -pub const _SC_2_PBS_MESSAGE: ::c_int = 171; -pub const _SC_2_PBS_TRACK: ::c_int = 172; -pub const _SC_SYMLOOP_MAX: ::c_int = 173; -pub const _SC_STREAMS: ::c_int = 174; -pub const _SC_2_PBS_CHECKPOINT: ::c_int = 175; -pub const _SC_V6_ILP32_OFF32: ::c_int = 176; -pub const _SC_V6_ILP32_OFFBIG: ::c_int = 177; -pub const _SC_V6_LP64_OFF64: ::c_int = 178; -pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 179; -pub const _SC_HOST_NAME_MAX: ::c_int = 180; -pub const _SC_TRACE: ::c_int = 181; -pub const _SC_TRACE_EVENT_FILTER: ::c_int = 182; -pub const _SC_TRACE_INHERIT: ::c_int = 183; -pub const _SC_TRACE_LOG: ::c_int = 184; -pub const _SC_IPV6: ::c_int = 235; -pub const _SC_RAW_SOCKETS: ::c_int = 236; -pub const _SC_V7_ILP32_OFF32: ::c_int = 237; -pub const _SC_V7_ILP32_OFFBIG: ::c_int = 238; -pub const _SC_V7_LP64_OFF64: ::c_int = 239; -pub const _SC_V7_LPBIG_OFFBIG: ::c_int = 240; -pub const _SC_SS_REPL_MAX: ::c_int = 241; -pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 242; -pub const _SC_TRACE_NAME_MAX: ::c_int = 243; -pub const _SC_TRACE_SYS_MAX: ::c_int = 244; -pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 245; -pub const _SC_XOPEN_STREAMS: ::c_int = 246; -pub const _SC_THREAD_ROBUST_PRIO_INHERIT: ::c_int = 247; -pub const _SC_THREAD_ROBUST_PRIO_PROTECT: ::c_int = 248; - -pub const RLIM_SAVED_MAX: ::rlim_t = RLIM_INFINITY; -pub const RLIM_SAVED_CUR: ::rlim_t = RLIM_INFINITY; - -pub const GLOB_ERR: ::c_int = 1 << 0; -pub const GLOB_MARK: ::c_int = 1 << 1; -pub const GLOB_NOSORT: ::c_int = 1 << 2; -pub const GLOB_DOOFFS: ::c_int = 1 << 3; -pub const GLOB_NOCHECK: ::c_int = 1 << 4; -pub const GLOB_APPEND: ::c_int = 1 << 5; -pub const GLOB_NOESCAPE: ::c_int = 1 << 6; - -pub const GLOB_NOSPACE: ::c_int = 1; -pub const GLOB_ABORTED: ::c_int = 2; -pub const GLOB_NOMATCH: ::c_int = 3; - -pub const POSIX_MADV_NORMAL: ::c_int = 0; -pub const POSIX_MADV_RANDOM: ::c_int = 1; -pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; -pub const POSIX_MADV_WILLNEED: ::c_int = 3; - -pub const S_IEXEC: mode_t = 64; -pub const S_IWRITE: mode_t = 128; -pub const S_IREAD: mode_t = 256; - -pub const F_LOCK: ::c_int = 1; -pub const F_TEST: ::c_int = 3; -pub const F_TLOCK: ::c_int = 2; -pub const F_ULOCK: ::c_int = 0; - -pub const IFF_LOWER_UP: ::c_int = 0x10000; -pub const IFF_DORMANT: ::c_int = 0x20000; -pub const IFF_ECHO: ::c_int = 0x40000; - -pub const ST_RDONLY: ::c_ulong = 1; -pub const ST_NOSUID: ::c_ulong = 2; -pub const ST_NODEV: ::c_ulong = 4; -pub const ST_NOEXEC: ::c_ulong = 8; -pub const ST_SYNCHRONOUS: ::c_ulong = 16; -pub const ST_MANDLOCK: ::c_ulong = 64; -pub const ST_WRITE: ::c_ulong = 128; -pub const ST_APPEND: ::c_ulong = 256; -pub const ST_IMMUTABLE: ::c_ulong = 512; -pub const ST_NOATIME: ::c_ulong = 1024; -pub const ST_NODIRATIME: ::c_ulong = 2048; - -pub const RTLD_NEXT: *mut ::c_void = -1i64 as *mut ::c_void; -pub const RTLD_DEFAULT: *mut ::c_void = 0i64 as *mut ::c_void; -pub const RTLD_NODELETE: ::c_int = 0x1000; -pub const RTLD_NOW: ::c_int = 0x2; - -pub const TCP_MD5SIG: ::c_int = 14; - -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_MUTEX_T], -}; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_COND_T], -}; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_RWLOCK_T], -}; -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; -pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; -pub const PTHREAD_PROCESS_PRIVATE: ::c_int = 0; -pub const PTHREAD_PROCESS_SHARED: ::c_int = 1; -pub const __SIZEOF_PTHREAD_COND_T: usize = 48; - -pub const RENAME_NOREPLACE: ::c_int = 1; -pub const RENAME_EXCHANGE: ::c_int = 2; -pub const RENAME_WHITEOUT: ::c_int = 4; - -pub const SCHED_OTHER: ::c_int = 0; -pub const SCHED_FIFO: ::c_int = 1; -pub const SCHED_RR: ::c_int = 2; -pub const SCHED_BATCH: ::c_int = 3; -pub const SCHED_IDLE: ::c_int = 5; - -// netinet/in.h -// NOTE: These are in addition to the constants defined in src/unix/mod.rs - -// IPPROTO_IP defined in src/unix/mod.rs -/// Hop-by-hop option header -pub const IPPROTO_HOPOPTS: ::c_int = 0; -// IPPROTO_ICMP defined in src/unix/mod.rs -/// group mgmt protocol -pub const IPPROTO_IGMP: ::c_int = 2; -/// for compatibility -pub const IPPROTO_IPIP: ::c_int = 4; -// IPPROTO_TCP defined in src/unix/mod.rs -/// exterior gateway protocol -pub const IPPROTO_EGP: ::c_int = 8; -/// pup -pub const IPPROTO_PUP: ::c_int = 12; -// IPPROTO_UDP defined in src/unix/mod.rs -/// xns idp -pub const IPPROTO_IDP: ::c_int = 22; -/// tp-4 w/ class negotiation -pub const IPPROTO_TP: ::c_int = 29; -/// DCCP -pub const IPPROTO_DCCP: ::c_int = 33; -// IPPROTO_IPV6 defined in src/unix/mod.rs -/// IP6 routing header -pub const IPPROTO_ROUTING: ::c_int = 43; -/// IP6 fragmentation header -pub const IPPROTO_FRAGMENT: ::c_int = 44; -/// resource reservation -pub const IPPROTO_RSVP: ::c_int = 46; -/// General Routing Encap. -pub const IPPROTO_GRE: ::c_int = 47; -/// IP6 Encap Sec. Payload -pub const IPPROTO_ESP: ::c_int = 50; -/// IP6 Auth Header -pub const IPPROTO_AH: ::c_int = 51; -// IPPROTO_ICMPV6 defined in src/unix/mod.rs -/// IP6 no next header -pub const IPPROTO_NONE: ::c_int = 59; -/// IP6 destination option -pub const IPPROTO_DSTOPTS: ::c_int = 60; -pub const IPPROTO_MTP: ::c_int = 92; -pub const IPPROTO_BEETPH: ::c_int = 94; -/// encapsulation header -pub const IPPROTO_ENCAP: ::c_int = 98; -/// Protocol indep. multicast -pub const IPPROTO_PIM: ::c_int = 103; -/// IP Payload Comp. Protocol -pub const IPPROTO_COMP: ::c_int = 108; -/// SCTP -pub const IPPROTO_SCTP: ::c_int = 132; -pub const IPPROTO_MH: ::c_int = 135; -pub const IPPROTO_UDPLITE: ::c_int = 136; -pub const IPPROTO_MPLS: ::c_int = 137; -/// raw IP packet -pub const IPPROTO_RAW: ::c_int = 255; -pub const IPPROTO_MAX: ::c_int = 256; - -pub const AF_IB: ::c_int = 27; -pub const AF_MPLS: ::c_int = 28; -pub const AF_NFC: ::c_int = 39; -pub const AF_VSOCK: ::c_int = 40; -pub const PF_IB: ::c_int = AF_IB; -pub const PF_MPLS: ::c_int = AF_MPLS; -pub const PF_NFC: ::c_int = AF_NFC; -pub const PF_VSOCK: ::c_int = AF_VSOCK; - -// System V IPC -pub const IPC_PRIVATE: ::key_t = 0; - -pub const IPC_CREAT: ::c_int = 0o1000; -pub const IPC_EXCL: ::c_int = 0o2000; -pub const IPC_NOWAIT: ::c_int = 0o4000; - -pub const IPC_RMID: ::c_int = 0; -pub const IPC_SET: ::c_int = 1; -pub const IPC_STAT: ::c_int = 2; -pub const IPC_INFO: ::c_int = 3; -pub const MSG_STAT: ::c_int = 11; -pub const MSG_INFO: ::c_int = 12; - -pub const MSG_NOERROR: ::c_int = 0o10000; -pub const MSG_EXCEPT: ::c_int = 0o20000; -pub const MSG_COPY: ::c_int = 0o40000; - -pub const SHM_R: ::c_int = 0o400; -pub const SHM_W: ::c_int = 0o200; - -pub const SHM_RDONLY: ::c_int = 0o10000; -pub const SHM_RND: ::c_int = 0o20000; -pub const SHM_REMAP: ::c_int = 0o40000; -pub const SHM_EXEC: ::c_int = 0o100000; - -pub const SHM_LOCK: ::c_int = 11; -pub const SHM_UNLOCK: ::c_int = 12; - -pub const SHM_HUGETLB: ::c_int = 0o4000; -pub const SHM_NORESERVE: ::c_int = 0o10000; - -pub const EPOLLRDHUP: ::c_int = 0x2000; -pub const EPOLLEXCLUSIVE: ::c_int = 0x10000000; -pub const EPOLLONESHOT: ::c_int = 0x40000000; - -pub const QFMT_VFS_OLD: ::c_int = 1; -pub const QFMT_VFS_V0: ::c_int = 2; -pub const QFMT_VFS_V1: ::c_int = 4; - -pub const EFD_SEMAPHORE: ::c_int = 0x1; - -pub const LOG_NFACILITIES: ::c_int = 24; - -pub const SEM_FAILED: *mut ::sem_t = 0 as *mut sem_t; - -pub const RB_AUTOBOOT: ::c_int = 0x01234567u32 as i32; -pub const RB_HALT_SYSTEM: ::c_int = 0xcdef0123u32 as i32; -pub const RB_ENABLE_CAD: ::c_int = 0x89abcdefu32 as i32; -pub const RB_DISABLE_CAD: ::c_int = 0x00000000u32 as i32; -pub const RB_POWER_OFF: ::c_int = 0x4321fedcu32 as i32; -pub const RB_SW_SUSPEND: ::c_int = 0xd000fce2u32 as i32; -pub const RB_KEXEC: ::c_int = 0x45584543u32 as i32; - -pub const AI_PASSIVE: ::c_int = 0x0001; -pub const AI_CANONNAME: ::c_int = 0x0002; -pub const AI_NUMERICHOST: ::c_int = 0x0004; -pub const AI_V4MAPPED: ::c_int = 0x0008; -pub const AI_ALL: ::c_int = 0x0010; -pub const AI_ADDRCONFIG: ::c_int = 0x0020; - -pub const AI_NUMERICSERV: ::c_int = 0x0400; - -pub const EAI_BADFLAGS: ::c_int = -1; -pub const EAI_NONAME: ::c_int = -2; -pub const EAI_AGAIN: ::c_int = -3; -pub const EAI_FAIL: ::c_int = -4; -pub const EAI_FAMILY: ::c_int = -6; -pub const EAI_SOCKTYPE: ::c_int = -7; -pub const EAI_SERVICE: ::c_int = -8; -pub const EAI_MEMORY: ::c_int = -10; -pub const EAI_OVERFLOW: ::c_int = -12; - -pub const NI_NUMERICHOST: ::c_int = 1; -pub const NI_NUMERICSERV: ::c_int = 2; -pub const NI_NOFQDN: ::c_int = 4; -pub const NI_NAMEREQD: ::c_int = 8; -pub const NI_DGRAM: ::c_int = 16; - -pub const SYNC_FILE_RANGE_WAIT_BEFORE: ::c_uint = 1; -pub const SYNC_FILE_RANGE_WRITE: ::c_uint = 2; -pub const SYNC_FILE_RANGE_WAIT_AFTER: ::c_uint = 4; - -pub const EAI_SYSTEM: ::c_int = -11; - -pub const AIO_CANCELED: ::c_int = 0; -pub const AIO_NOTCANCELED: ::c_int = 1; -pub const AIO_ALLDONE: ::c_int = 2; -pub const LIO_READ: ::c_int = 0; -pub const LIO_WRITE: ::c_int = 1; -pub const LIO_NOP: ::c_int = 2; -pub const LIO_WAIT: ::c_int = 0; -pub const LIO_NOWAIT: ::c_int = 1; - -pub const MREMAP_MAYMOVE: ::c_int = 1; -pub const MREMAP_FIXED: ::c_int = 2; - -pub const PR_SET_PDEATHSIG: ::c_int = 1; -pub const PR_GET_PDEATHSIG: ::c_int = 2; - -pub const PR_GET_DUMPABLE: ::c_int = 3; -pub const PR_SET_DUMPABLE: ::c_int = 4; - -pub const PR_GET_UNALIGN: ::c_int = 5; -pub const PR_SET_UNALIGN: ::c_int = 6; -pub const PR_UNALIGN_NOPRINT: ::c_int = 1; -pub const PR_UNALIGN_SIGBUS: ::c_int = 2; - -pub const PR_GET_KEEPCAPS: ::c_int = 7; -pub const PR_SET_KEEPCAPS: ::c_int = 8; - -pub const PR_GET_FPEMU: ::c_int = 9; -pub const PR_SET_FPEMU: ::c_int = 10; -pub const PR_FPEMU_NOPRINT: ::c_int = 1; -pub const PR_FPEMU_SIGFPE: ::c_int = 2; - -pub const PR_GET_FPEXC: ::c_int = 11; -pub const PR_SET_FPEXC: ::c_int = 12; -pub const PR_FP_EXC_SW_ENABLE: ::c_int = 0x80; -pub const PR_FP_EXC_DIV: ::c_int = 0x010000; -pub const PR_FP_EXC_OVF: ::c_int = 0x020000; -pub const PR_FP_EXC_UND: ::c_int = 0x040000; -pub const PR_FP_EXC_RES: ::c_int = 0x080000; -pub const PR_FP_EXC_INV: ::c_int = 0x100000; -pub const PR_FP_EXC_DISABLED: ::c_int = 0; -pub const PR_FP_EXC_NONRECOV: ::c_int = 1; -pub const PR_FP_EXC_ASYNC: ::c_int = 2; -pub const PR_FP_EXC_PRECISE: ::c_int = 3; - -pub const PR_GET_TIMING: ::c_int = 13; -pub const PR_SET_TIMING: ::c_int = 14; -pub const PR_TIMING_STATISTICAL: ::c_int = 0; -pub const PR_TIMING_TIMESTAMP: ::c_int = 1; - -pub const PR_SET_NAME: ::c_int = 15; -pub const PR_GET_NAME: ::c_int = 16; - -pub const PR_GET_ENDIAN: ::c_int = 19; -pub const PR_SET_ENDIAN: ::c_int = 20; -pub const PR_ENDIAN_BIG: ::c_int = 0; -pub const PR_ENDIAN_LITTLE: ::c_int = 1; -pub const PR_ENDIAN_PPC_LITTLE: ::c_int = 2; - -pub const PR_GET_SECCOMP: ::c_int = 21; -pub const PR_SET_SECCOMP: ::c_int = 22; - -pub const PR_CAPBSET_READ: ::c_int = 23; -pub const PR_CAPBSET_DROP: ::c_int = 24; - -pub const PR_GET_TSC: ::c_int = 25; -pub const PR_SET_TSC: ::c_int = 26; -pub const PR_TSC_ENABLE: ::c_int = 1; -pub const PR_TSC_SIGSEGV: ::c_int = 2; - -pub const PR_GET_SECUREBITS: ::c_int = 27; -pub const PR_SET_SECUREBITS: ::c_int = 28; - -pub const PR_SET_TIMERSLACK: ::c_int = 29; -pub const PR_GET_TIMERSLACK: ::c_int = 30; - -pub const PR_TASK_PERF_EVENTS_DISABLE: ::c_int = 31; -pub const PR_TASK_PERF_EVENTS_ENABLE: ::c_int = 32; - -pub const PR_MCE_KILL: ::c_int = 33; -pub const PR_MCE_KILL_CLEAR: ::c_int = 0; -pub const PR_MCE_KILL_SET: ::c_int = 1; - -pub const PR_MCE_KILL_LATE: ::c_int = 0; -pub const PR_MCE_KILL_EARLY: ::c_int = 1; -pub const PR_MCE_KILL_DEFAULT: ::c_int = 2; - -pub const PR_MCE_KILL_GET: ::c_int = 34; - -pub const PR_SET_MM: ::c_int = 35; -pub const PR_SET_MM_START_CODE: ::c_int = 1; -pub const PR_SET_MM_END_CODE: ::c_int = 2; -pub const PR_SET_MM_START_DATA: ::c_int = 3; -pub const PR_SET_MM_END_DATA: ::c_int = 4; -pub const PR_SET_MM_START_STACK: ::c_int = 5; -pub const PR_SET_MM_START_BRK: ::c_int = 6; -pub const PR_SET_MM_BRK: ::c_int = 7; -pub const PR_SET_MM_ARG_START: ::c_int = 8; -pub const PR_SET_MM_ARG_END: ::c_int = 9; -pub const PR_SET_MM_ENV_START: ::c_int = 10; -pub const PR_SET_MM_ENV_END: ::c_int = 11; -pub const PR_SET_MM_AUXV: ::c_int = 12; -pub const PR_SET_MM_EXE_FILE: ::c_int = 13; -pub const PR_SET_MM_MAP: ::c_int = 14; -pub const PR_SET_MM_MAP_SIZE: ::c_int = 15; - -pub const PR_SET_PTRACER: ::c_int = 0x59616d61; - -pub const PR_SET_CHILD_SUBREAPER: ::c_int = 36; -pub const PR_GET_CHILD_SUBREAPER: ::c_int = 37; - -pub const PR_SET_NO_NEW_PRIVS: ::c_int = 38; -pub const PR_GET_NO_NEW_PRIVS: ::c_int = 39; - -pub const PR_GET_TID_ADDRESS: ::c_int = 40; - -pub const PR_SET_THP_DISABLE: ::c_int = 41; -pub const PR_GET_THP_DISABLE: ::c_int = 42; - -pub const PR_MPX_ENABLE_MANAGEMENT: ::c_int = 43; -pub const PR_MPX_DISABLE_MANAGEMENT: ::c_int = 44; - -pub const PR_SET_FP_MODE: ::c_int = 45; -pub const PR_GET_FP_MODE: ::c_int = 46; -pub const PR_FP_MODE_FR: ::c_int = 1 << 0; -pub const PR_FP_MODE_FRE: ::c_int = 1 << 1; - -pub const PR_CAP_AMBIENT: ::c_int = 47; -pub const PR_CAP_AMBIENT_IS_SET: ::c_int = 1; -pub const PR_CAP_AMBIENT_RAISE: ::c_int = 2; -pub const PR_CAP_AMBIENT_LOWER: ::c_int = 3; -pub const PR_CAP_AMBIENT_CLEAR_ALL: ::c_int = 4; - -pub const GRND_NONBLOCK: ::c_uint = 0x0001; -pub const GRND_RANDOM: ::c_uint = 0x0002; - -pub const ITIMER_REAL: ::c_int = 0; -pub const ITIMER_VIRTUAL: ::c_int = 1; -pub const ITIMER_PROF: ::c_int = 2; - -pub const TFD_CLOEXEC: ::c_int = O_CLOEXEC; -pub const TFD_NONBLOCK: ::c_int = O_NONBLOCK; -pub const TFD_TIMER_ABSTIME: ::c_int = 1; - -pub const XATTR_CREATE: ::c_int = 0x1; -pub const XATTR_REPLACE: ::c_int = 0x2; - -pub const _POSIX_VDISABLE: ::cc_t = 0; - -pub const FALLOC_FL_KEEP_SIZE: ::c_int = 0x01; -pub const FALLOC_FL_PUNCH_HOLE: ::c_int = 0x02; -pub const FALLOC_FL_COLLAPSE_RANGE: ::c_int = 0x08; -pub const FALLOC_FL_ZERO_RANGE: ::c_int = 0x10; -pub const FALLOC_FL_INSERT_RANGE: ::c_int = 0x20; -pub const FALLOC_FL_UNSHARE_RANGE: ::c_int = 0x40; - -// On Linux, libc doesn't define this constant, libattr does instead. -// We still define it for Linux as it's defined by libc on other platforms, -// and it's mentioned in the man pages for getxattr and setxattr. -pub const ENOATTR: ::c_int = ::ENODATA; - -pub const SO_ORIGINAL_DST: ::c_int = 80; -pub const IUTF8: ::tcflag_t = 0x00004000; -pub const CMSPAR: ::tcflag_t = 0o10000000000; - -pub const MFD_CLOEXEC: ::c_uint = 0x0001; -pub const MFD_ALLOW_SEALING: ::c_uint = 0x0002; - -// these are used in the p_type field of Elf32_Phdr and Elf64_Phdr, which has -// the type Elf32Word and Elf64Word respectively. Luckily, both of those are u32 -// so we can use that type here to avoid having to cast. -pub const PT_NULL: u32 = 0; -pub const PT_LOAD: u32 = 1; -pub const PT_DYNAMIC: u32 = 2; -pub const PT_INTERP: u32 = 3; -pub const PT_NOTE: u32 = 4; -pub const PT_SHLIB: u32 = 5; -pub const PT_PHDR: u32 = 6; -pub const PT_TLS: u32 = 7; -pub const PT_NUM: u32 = 8; -pub const PT_LOOS: u32 = 0x60000000; -pub const PT_GNU_EH_FRAME: u32 = 0x6474e550; -pub const PT_GNU_STACK: u32 = 0x6474e551; -pub const PT_GNU_RELRO: u32 = 0x6474e552; - -pub const SFD_CLOEXEC: ::c_int = 0x080000; - -pub const NCCS: usize = 32; - -pub const O_TRUNC: ::c_int = 0x00040000; -pub const O_NOATIME: ::c_int = 0x00002000; -pub const O_CLOEXEC: ::c_int = 0x00000100; -pub const O_TMPFILE: ::c_int = 0x00004000; - -pub const EBFONT: ::c_int = 59; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENONET: ::c_int = 64; -pub const ENOPKG: ::c_int = 65; -pub const EREMOTE: ::c_int = 66; -pub const ENOLINK: ::c_int = 67; -pub const EADV: ::c_int = 68; -pub const ESRMNT: ::c_int = 69; -pub const ECOMM: ::c_int = 70; -pub const EPROTO: ::c_int = 71; -pub const EDOTDOT: ::c_int = 73; - -pub const SA_NODEFER: ::c_int = 0x40000000; -pub const SA_RESETHAND: ::c_int = 0x80000000; -pub const SA_RESTART: ::c_int = 0x10000000; -pub const SA_NOCLDSTOP: ::c_int = 0x00000001; - -pub const EPOLL_CLOEXEC: ::c_int = 0x80000; - -pub const EFD_CLOEXEC: ::c_int = 0x80000; - -pub const BUFSIZ: ::c_uint = 1024; -pub const TMP_MAX: ::c_uint = 10000; -pub const FOPEN_MAX: ::c_uint = 1000; -pub const O_PATH: ::c_int = 0x00400000; -pub const O_EXEC: ::c_int = O_PATH; -pub const O_SEARCH: ::c_int = O_PATH; -pub const O_ACCMODE: ::c_int = (03 | O_SEARCH); -pub const O_NDELAY: ::c_int = O_NONBLOCK; -pub const NI_MAXHOST: ::socklen_t = 255; -pub const PTHREAD_STACK_MIN: ::size_t = 2048; -pub const POSIX_FADV_DONTNEED: ::c_int = 4; -pub const POSIX_FADV_NOREUSE: ::c_int = 5; - -pub const POSIX_MADV_DONTNEED: ::c_int = 4; - -pub const RLIM_INFINITY: ::rlim_t = !0; -pub const RLIMIT_RTTIME: ::c_int = 15; -pub const RLIMIT_NLIMITS: ::c_int = 16; - -pub const MAP_ANONYMOUS: ::c_int = MAP_ANON; - -pub const SOCK_DCCP: ::c_int = 6; -pub const SOCK_PACKET: ::c_int = 10; - -pub const TCP_COOKIE_TRANSACTIONS: ::c_int = 15; -pub const TCP_THIN_LINEAR_TIMEOUTS: ::c_int = 16; -pub const TCP_THIN_DUPACK: ::c_int = 17; -pub const TCP_USER_TIMEOUT: ::c_int = 18; -pub const TCP_REPAIR: ::c_int = 19; -pub const TCP_REPAIR_QUEUE: ::c_int = 20; -pub const TCP_QUEUE_SEQ: ::c_int = 21; -pub const TCP_REPAIR_OPTIONS: ::c_int = 22; -pub const TCP_FASTOPEN: ::c_int = 23; -pub const TCP_TIMESTAMP: ::c_int = 24; - -pub const SIGUNUSED: ::c_int = ::SIGSYS; - -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; - -pub const CPU_SETSIZE: ::c_int = 128; - -pub const PTRACE_TRACEME: ::c_int = 0; -pub const PTRACE_PEEKTEXT: ::c_int = 1; -pub const PTRACE_PEEKDATA: ::c_int = 2; -pub const PTRACE_PEEKUSER: ::c_int = 3; -pub const PTRACE_POKETEXT: ::c_int = 4; -pub const PTRACE_POKEDATA: ::c_int = 5; -pub const PTRACE_POKEUSER: ::c_int = 6; -pub const PTRACE_CONT: ::c_int = 7; -pub const PTRACE_KILL: ::c_int = 8; -pub const PTRACE_SINGLESTEP: ::c_int = 9; -pub const PTRACE_GETREGS: ::c_int = 12; -pub const PTRACE_SETREGS: ::c_int = 13; -pub const PTRACE_GETFPREGS: ::c_int = 14; -pub const PTRACE_SETFPREGS: ::c_int = 15; -pub const PTRACE_ATTACH: ::c_int = 16; -pub const PTRACE_DETACH: ::c_int = 17; -pub const PTRACE_GETFPXREGS: ::c_int = 18; -pub const PTRACE_SETFPXREGS: ::c_int = 19; -pub const PTRACE_SYSCALL: ::c_int = 24; -pub const PTRACE_SETOPTIONS: ::c_int = 0x4200; -pub const PTRACE_GETEVENTMSG: ::c_int = 0x4201; -pub const PTRACE_GETSIGINFO: ::c_int = 0x4202; -pub const PTRACE_SETSIGINFO: ::c_int = 0x4203; -pub const PTRACE_GETREGSET: ::c_int = 0x4204; -pub const PTRACE_SETREGSET: ::c_int = 0x4205; -pub const PTRACE_SEIZE: ::c_int = 0x4206; -pub const PTRACE_INTERRUPT: ::c_int = 0x4207; -pub const PTRACE_LISTEN: ::c_int = 0x4208; -pub const PTRACE_PEEKSIGINFO: ::c_int = 0x4209; - -pub const EPOLLWAKEUP: ::c_int = 0x20000000; - -pub const EFD_NONBLOCK: ::c_int = ::O_NONBLOCK; - -pub const SFD_NONBLOCK: ::c_int = ::O_NONBLOCK; - -pub const TCSANOW: ::c_int = 0; -pub const TCSADRAIN: ::c_int = 1; -pub const TCSAFLUSH: ::c_int = 2; - -pub const TIOCINQ: ::c_int = ::FIONREAD; - -pub const RTLD_GLOBAL: ::c_int = 0x100; -pub const RTLD_NOLOAD: ::c_int = 0x4; - -// TODO(#247) Temporarily musl-specific (available since musl 0.9.12 / Linux -// kernel 3.10). See also notbsd/mod.rs -pub const CLOCK_SGI_CYCLE: ::clockid_t = 10; -pub const CLOCK_TAI: ::clockid_t = 11; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const CBAUD: ::tcflag_t = 0o0010017; -pub const TAB1: ::c_int = 0x00000800; -pub const TAB2: ::c_int = 0x00001000; -pub const TAB3: ::c_int = 0x00001800; -pub const CR1: ::c_int = 0x00000200; -pub const CR2: ::c_int = 0x00000400; -pub const CR3: ::c_int = 0x00000600; -pub const FF1: ::c_int = 0x00008000; -pub const BS1: ::c_int = 0x00002000; -pub const VT1: ::c_int = 0x00004000; -pub const VWERASE: usize = 14; -pub const VREPRINT: usize = 12; -pub const VSUSP: usize = 10; -pub const VSTART: usize = 8; -pub const VSTOP: usize = 9; -pub const VDISCARD: usize = 13; -pub const VTIME: usize = 5; -pub const IXON: ::tcflag_t = 0x00000400; -pub const IXOFF: ::tcflag_t = 0x00001000; -pub const ONLCR: ::tcflag_t = 0x4; -pub const CSIZE: ::tcflag_t = 0x00000030; -pub const CS6: ::tcflag_t = 0x00000010; -pub const CS7: ::tcflag_t = 0x00000020; -pub const CS8: ::tcflag_t = 0x00000030; -pub const CSTOPB: ::tcflag_t = 0x00000040; -pub const CREAD: ::tcflag_t = 0x00000080; -pub const PARENB: ::tcflag_t = 0x00000100; -pub const PARODD: ::tcflag_t = 0x00000200; -pub const HUPCL: ::tcflag_t = 0x00000400; -pub const CLOCAL: ::tcflag_t = 0x00000800; -pub const ECHOKE: ::tcflag_t = 0x00000800; -pub const ECHOE: ::tcflag_t = 0x00000010; -pub const ECHOK: ::tcflag_t = 0x00000020; -pub const ECHONL: ::tcflag_t = 0x00000040; -pub const ECHOPRT: ::tcflag_t = 0x00000400; -pub const ECHOCTL: ::tcflag_t = 0x00000200; -pub const ISIG: ::tcflag_t = 0x00000001; -pub const ICANON: ::tcflag_t = 0x00000002; -pub const PENDIN: ::tcflag_t = 0x00004000; -pub const NOFLSH: ::tcflag_t = 0x00000080; -pub const CIBAUD: ::tcflag_t = 0o02003600000; -pub const CBAUDEX: ::tcflag_t = 0o010000; -pub const VSWTC: usize = 7; -pub const OLCUC: ::tcflag_t = 0o000002; -pub const NLDLY: ::tcflag_t = 0o000400; -pub const CRDLY: ::tcflag_t = 0o003000; -pub const TABDLY: ::tcflag_t = 0o014000; -pub const BSDLY: ::tcflag_t = 0o020000; -pub const FFDLY: ::tcflag_t = 0o100000; -pub const VTDLY: ::tcflag_t = 0o040000; -pub const XTABS: ::tcflag_t = 0o014000; - -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const EXTA: ::speed_t = B19200; -pub const EXTB: ::speed_t = B38400; -pub const B57600: ::speed_t = 0o010001; -pub const B115200: ::speed_t = 0o010002; -pub const B230400: ::speed_t = 0o010003; -pub const B460800: ::speed_t = 0o010004; -pub const B500000: ::speed_t = 0o010005; -pub const B576000: ::speed_t = 0o010006; -pub const B921600: ::speed_t = 0o010007; -pub const B1000000: ::speed_t = 0o010010; -pub const B1152000: ::speed_t = 0o010011; -pub const B1500000: ::speed_t = 0o010012; -pub const B2000000: ::speed_t = 0o010013; -pub const B2500000: ::speed_t = 0o010014; -pub const B3000000: ::speed_t = 0o010015; -pub const B3500000: ::speed_t = 0o010016; -pub const B4000000: ::speed_t = 0o010017; - -pub const SO_BINDTODEVICE: ::c_int = 25; -pub const SO_TIMESTAMP: ::c_int = 29; -pub const SO_MARK: ::c_int = 36; -pub const SO_RXQ_OVFL: ::c_int = 40; -pub const SO_PEEK_OFF: ::c_int = 42; -pub const SO_BUSY_POLL: ::c_int = 46; - -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; - -pub const O_ASYNC: ::c_int = 0x00000400; - -pub const FIOCLEX: ::c_int = 0x5451; -pub const FIONBIO: ::c_int = 0x5421; - -pub const RLIMIT_RSS: ::c_int = 5; -pub const RLIMIT_NOFILE: ::c_int = 7; -pub const RLIMIT_AS: ::c_int = 9; -pub const RLIMIT_NPROC: ::c_int = 6; -pub const RLIMIT_MEMLOCK: ::c_int = 8; - -pub const O_APPEND: ::c_int = 0x00100000; -pub const O_CREAT: ::c_int = 0x00010000; -pub const O_EXCL: ::c_int = 0x00020000; -pub const O_NOCTTY: ::c_int = 0x00000200; -pub const O_NONBLOCK: ::c_int = 0x00000010; -pub const O_SYNC: ::c_int = (0x00000040 | O_DSYNC); -pub const O_RSYNC: ::c_int = O_SYNC; -pub const O_DSYNC: ::c_int = 0x00000020; - -pub const SOCK_NONBLOCK: ::c_int = 2048; - -pub const MAP_ANON: ::c_int = 0x0020; -pub const MAP_GROWSDOWN: ::c_int = 0x0100; -pub const MAP_DENYWRITE: ::c_int = 0x0800; -pub const MAP_EXECUTABLE: ::c_int = 0x01000; -pub const MAP_LOCKED: ::c_int = 0x02000; -pub const MAP_NORESERVE: ::c_int = 0x04000; -pub const MAP_POPULATE: ::c_int = 0x08000; -pub const MAP_NONBLOCK: ::c_int = 0x010000; -pub const MAP_STACK: ::c_int = 0x020000; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; -pub const SOCK_SEQPACKET: ::c_int = 5; - -pub const SOL_SOCKET: ::c_int = 1; - -pub const EDEADLK: ::c_int = 35; -pub const ENAMETOOLONG: ::c_int = 36; -pub const ENOLCK: ::c_int = 37; -pub const ENOSYS: ::c_int = 38; -pub const ENOTEMPTY: ::c_int = 39; -pub const ELOOP: ::c_int = 40; -pub const ENOMSG: ::c_int = 42; -pub const EIDRM: ::c_int = 43; -pub const ECHRNG: ::c_int = 44; -pub const EL2NSYNC: ::c_int = 45; -pub const EL3HLT: ::c_int = 46; -pub const EL3RST: ::c_int = 47; -pub const ELNRNG: ::c_int = 48; -pub const EUNATCH: ::c_int = 49; -pub const ENOCSI: ::c_int = 50; -pub const EL2HLT: ::c_int = 51; -pub const EBADE: ::c_int = 52; -pub const EBADR: ::c_int = 53; -pub const EXFULL: ::c_int = 54; -pub const ENOANO: ::c_int = 55; -pub const EBADRQC: ::c_int = 56; -pub const EBADSLT: ::c_int = 57; -pub const EDEADLOCK: ::c_int = EDEADLK; -pub const EMULTIHOP: ::c_int = 72; -pub const EBADMSG: ::c_int = 74; -pub const EOVERFLOW: ::c_int = 75; -pub const ENOTUNIQ: ::c_int = 76; -pub const EBADFD: ::c_int = 77; -pub const EREMCHG: ::c_int = 78; -pub const ELIBACC: ::c_int = 79; -pub const ELIBBAD: ::c_int = 80; -pub const ELIBSCN: ::c_int = 81; -pub const ELIBMAX: ::c_int = 82; -pub const ELIBEXEC: ::c_int = 83; -pub const EILSEQ: ::c_int = 84; -pub const ERESTART: ::c_int = 85; -pub const ESTRPIPE: ::c_int = 86; -pub const EUSERS: ::c_int = 87; -pub const ENOTSOCK: ::c_int = 88; -pub const EDESTADDRREQ: ::c_int = 89; -pub const EMSGSIZE: ::c_int = 90; -pub const EPROTOTYPE: ::c_int = 91; -pub const ENOPROTOOPT: ::c_int = 92; -pub const EPROTONOSUPPORT: ::c_int = 93; -pub const ESOCKTNOSUPPORT: ::c_int = 94; -pub const EOPNOTSUPP: ::c_int = 95; -pub const ENOTSUP: ::c_int = EOPNOTSUPP; -pub const EPFNOSUPPORT: ::c_int = 96; -pub const EAFNOSUPPORT: ::c_int = 97; -pub const EADDRINUSE: ::c_int = 98; -pub const EADDRNOTAVAIL: ::c_int = 99; -pub const ENETDOWN: ::c_int = 100; -pub const ENETUNREACH: ::c_int = 101; -pub const ENETRESET: ::c_int = 102; -pub const ECONNABORTED: ::c_int = 103; -pub const ECONNRESET: ::c_int = 104; -pub const ENOBUFS: ::c_int = 105; -pub const EISCONN: ::c_int = 106; -pub const ENOTCONN: ::c_int = 107; -pub const ESHUTDOWN: ::c_int = 108; -pub const ETOOMANYREFS: ::c_int = 109; -pub const ETIMEDOUT: ::c_int = 110; -pub const ECONNREFUSED: ::c_int = 111; -pub const EHOSTDOWN: ::c_int = 112; -pub const EHOSTUNREACH: ::c_int = 113; -pub const EALREADY: ::c_int = 114; -pub const EINPROGRESS: ::c_int = 115; -pub const ESTALE: ::c_int = 116; -pub const EUCLEAN: ::c_int = 117; -pub const ENOTNAM: ::c_int = 118; -pub const ENAVAIL: ::c_int = 119; -pub const EISNAM: ::c_int = 120; -pub const EREMOTEIO: ::c_int = 121; -pub const EDQUOT: ::c_int = 122; -pub const ENOMEDIUM: ::c_int = 123; -pub const EMEDIUMTYPE: ::c_int = 124; -pub const ECANCELED: ::c_int = 125; -pub const ENOKEY: ::c_int = 126; -pub const EKEYEXPIRED: ::c_int = 127; -pub const EKEYREVOKED: ::c_int = 128; -pub const EKEYREJECTED: ::c_int = 129; -pub const EOWNERDEAD: ::c_int = 130; -pub const ENOTRECOVERABLE: ::c_int = 131; -pub const ERFKILL: ::c_int = 132; -pub const EHWPOISON: ::c_int = 133; - -pub const SO_REUSEADDR: ::c_int = 2; -pub const SO_TYPE: ::c_int = 3; -pub const SO_ERROR: ::c_int = 4; -pub const SO_DONTROUTE: ::c_int = 5; -pub const SO_BROADCAST: ::c_int = 6; -pub const SO_SNDBUF: ::c_int = 7; -pub const SO_RCVBUF: ::c_int = 8; -pub const SO_KEEPALIVE: ::c_int = 9; -pub const SO_OOBINLINE: ::c_int = 10; -pub const SO_NO_CHECK: ::c_int = 11; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_LINGER: ::c_int = 13; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_REUSEPORT: ::c_int = 15; -pub const SO_PASSCRED: ::c_int = 16; -pub const SO_PEERCRED: ::c_int = 17; -pub const SO_RCVLOWAT: ::c_int = 18; -pub const SO_SNDLOWAT: ::c_int = 19; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_SNDTIMEO: ::c_int = 21; -pub const SO_ACCEPTCONN: ::c_int = 30; -pub const SO_SNDBUFFORCE: ::c_int = 32; -pub const SO_RCVBUFFORCE: ::c_int = 33; -pub const SO_PROTOCOL: ::c_int = 38; -pub const SO_DOMAIN: ::c_int = 39; - -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 0x00000004; -pub const SA_NOCLDWAIT: ::c_int = 0x00000002; - -pub const SIGCHLD: ::c_int = 17; -pub const SIGBUS: ::c_int = 7; -pub const SIGTTIN: ::c_int = 21; -pub const SIGTTOU: ::c_int = 22; -pub const SIGXCPU: ::c_int = 24; -pub const SIGXFSZ: ::c_int = 25; -pub const SIGVTALRM: ::c_int = 26; -pub const SIGPROF: ::c_int = 27; -pub const SIGWINCH: ::c_int = 28; -pub const SIGUSR1: ::c_int = 10; -pub const SIGUSR2: ::c_int = 12; -pub const SIGCONT: ::c_int = 18; -pub const SIGSTOP: ::c_int = 19; -pub const SIGTSTP: ::c_int = 20; -pub const SIGURG: ::c_int = 23; -pub const SIGIO: ::c_int = 29; -pub const SIGSYS: ::c_int = 31; -pub const SIGSTKFLT: ::c_int = 16; -pub const SIGPOLL: ::c_int = 29; -pub const SIGPWR: ::c_int = 30; -pub const SIG_SETMASK: ::c_int = 2; -pub const SIG_BLOCK: ::c_int = 0x000000; -pub const SIG_UNBLOCK: ::c_int = 0x01; - -pub const EXTPROC: ::tcflag_t = 0x00010000; - -pub const MAP_HUGETLB: ::c_int = 0x040000; - -pub const F_GETLK: ::c_int = 5; -pub const F_GETOWN: ::c_int = 9; -pub const F_SETLK: ::c_int = 6; -pub const F_SETLKW: ::c_int = 7; -pub const F_SETOWN: ::c_int = 8; - -pub const VEOF: usize = 4; -pub const VEOL: usize = 11; -pub const VEOL2: usize = 16; -pub const VMIN: usize = 6; -pub const IEXTEN: ::tcflag_t = 0x00008000; -pub const TOSTOP: ::tcflag_t = 0x00000100; -pub const FLUSHO: ::tcflag_t = 0x00001000; - -pub const TCGETS: ::c_int = 0x5401; -pub const TCSETS: ::c_int = 0x5402; -pub const TCSETSW: ::c_int = 0x5403; -pub const TCSETSF: ::c_int = 0x5404; -pub const TCGETA: ::c_int = 0x5405; -pub const TCSETA: ::c_int = 0x5406; -pub const TCSETAW: ::c_int = 0x5407; -pub const TCSETAF: ::c_int = 0x5408; -pub const TCSBRK: ::c_int = 0x5409; -pub const TCXONC: ::c_int = 0x540A; -pub const TCFLSH: ::c_int = 0x540B; -pub const TIOCGSOFTCAR: ::c_int = 0x5419; -pub const TIOCSSOFTCAR: ::c_int = 0x541A; -pub const TIOCLINUX: ::c_int = 0x541C; -pub const TIOCGSERIAL: ::c_int = 0x541E; -pub const TIOCEXCL: ::c_int = 0x540C; -pub const TIOCNXCL: ::c_int = 0x540D; -pub const TIOCSCTTY: ::c_int = 0x540E; -pub const TIOCGPGRP: ::c_int = 0x540F; -pub const TIOCSPGRP: ::c_int = 0x5410; -pub const TIOCOUTQ: ::c_int = 0x5411; -pub const TIOCSTI: ::c_int = 0x5412; -pub const TIOCGWINSZ: ::c_int = 0x5413; -pub const TIOCSWINSZ: ::c_int = 0x5414; -pub const TIOCMGET: ::c_int = 0x5415; -pub const TIOCMBIS: ::c_int = 0x5416; -pub const TIOCMBIC: ::c_int = 0x5417; -pub const TIOCMSET: ::c_int = 0x5418; -pub const FIONREAD: ::c_int = 0x541B; -pub const TIOCCONS: ::c_int = 0x541D; - -pub const POLLWRNORM: ::c_short = 0x100; -pub const POLLWRBAND: ::c_short = 0x200; - -pub const TIOCM_LE: ::c_int = 0x001; -pub const TIOCM_DTR: ::c_int = 0x002; -pub const TIOCM_RTS: ::c_int = 0x004; -pub const TIOCM_ST: ::c_int = 0x008; -pub const TIOCM_SR: ::c_int = 0x010; -pub const TIOCM_CTS: ::c_int = 0x020; -pub const TIOCM_CAR: ::c_int = 0x040; -pub const TIOCM_RNG: ::c_int = 0x080; -pub const TIOCM_DSR: ::c_int = 0x100; -pub const TIOCM_CD: ::c_int = TIOCM_CAR; -pub const TIOCM_RI: ::c_int = TIOCM_RNG; - -pub const O_DIRECTORY: ::c_int = 0x00080000; -pub const O_DIRECT: ::c_int = 0x00000800; -pub const O_LARGEFILE: ::c_int = 0x00001000; -pub const O_NOFOLLOW: ::c_int = 0x00000080; - -// intentionally not public, only used for fd_set -cfg_if! { - if #[cfg(target_pointer_width = "32")] { - const ULONG_SIZE: usize = 32; - } else if #[cfg(target_pointer_width = "64")] { - const ULONG_SIZE: usize = 64; - } else { - // Unknown target_pointer_width - } -} - -// END_PUB_CONST - -f! { - pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { - let fd = fd as usize; - let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; - (*set).fds_bits[fd / size] &= !(1 << (fd % size)); - return - } - - pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { - let fd = fd as usize; - let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; - return ((*set).fds_bits[fd / size] & (1 << (fd % size))) != 0 - } - - pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { - let fd = fd as usize; - let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; - (*set).fds_bits[fd / size] |= 1 << (fd % size); - return - } - - pub fn FD_ZERO(set: *mut fd_set) -> () { - for slot in (*set).fds_bits.iter_mut() { - *slot = 0; - } - } - - pub fn WIFSTOPPED(status: ::c_int) -> bool { - (status & 0xff) == 0x7f - } - - pub fn WSTOPSIG(status: ::c_int) -> ::c_int { - (status >> 8) & 0xff - } - - pub fn WIFCONTINUED(status: ::c_int) -> bool { - status == 0xffff - } - - pub fn WIFSIGNALED(status: ::c_int) -> bool { - ((status & 0x7f) + 1) as i8 >= 2 - } - - pub fn WTERMSIG(status: ::c_int) -> ::c_int { - status & 0x7f - } - - pub fn WIFEXITED(status: ::c_int) -> bool { - (status & 0x7f) == 0 - } - - pub fn WEXITSTATUS(status: ::c_int) -> ::c_int { - (status >> 8) & 0xff - } - - pub fn WCOREDUMP(status: ::c_int) -> bool { - (status & 0x80) != 0 - } - - pub fn QCMD(cmd: ::c_int, type_: ::c_int) -> ::c_int { - (cmd << 8) | (type_ & 0x00ff) - } - - pub fn CPU_ZERO(cpuset: &mut cpu_set_t) -> () { - for slot in cpuset.bits.iter_mut() { - *slot = 0; - } - } - - pub fn CPU_SET(cpu: usize, cpuset: &mut cpu_set_t) -> () { - let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc - let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); - cpuset.bits[idx] |= 1 << offset; - () - } - - pub fn CPU_CLR(cpu: usize, cpuset: &mut cpu_set_t) -> () { - let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc - let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); - cpuset.bits[idx] &= !(1 << offset); - () - } - - pub fn CPU_ISSET(cpu: usize, cpuset: &cpu_set_t) -> bool { - let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); - let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); - 0 != (cpuset.bits[idx] & (1 << offset)) - } - - pub fn CPU_EQUAL(set1: &cpu_set_t, set2: &cpu_set_t) -> bool { - set1.bits == set2.bits - } - - pub fn major(dev: ::dev_t) -> ::c_uint { - let mut major = 0; - major |= (dev & 0x00000000000fff00) >> 8; - major |= (dev & 0xfffff00000000000) >> 32; - major as ::c_uint - } - - pub fn minor(dev: ::dev_t) -> ::c_uint { - let mut minor = 0; - minor |= (dev & 0x00000000000000ff) >> 0; - minor |= (dev & 0x00000ffffff00000) >> 12; - minor as ::c_uint - } - - pub fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { - let major = major as ::dev_t; - let minor = minor as ::dev_t; - let mut dev = 0; - dev |= (major & 0x00000fff) << 8; - dev |= (major & 0xfffff000) << 32; - dev |= (minor & 0x000000ff) << 0; - dev |= (minor & 0xffffff00) << 12; - dev - } -} - -// EXTERN_FN - -#[link(name = "c")] -#[link(name = "fdio")] -extern {} - -extern { - pub fn getpwnam(name: *const ::c_char) -> *mut passwd; - pub fn getpwuid(uid: ::uid_t) -> *mut passwd; - - pub fn fprintf(stream: *mut ::FILE, - format: *const ::c_char, ...) -> ::c_int; - pub fn printf(format: *const ::c_char, ...) -> ::c_int; - pub fn snprintf(s: *mut ::c_char, n: ::size_t, - format: *const ::c_char, ...) -> ::c_int; - pub fn sprintf(s: *mut ::c_char, format: *const ::c_char, ...) -> ::c_int; - pub fn fscanf(stream: *mut ::FILE, format: *const ::c_char, ...) -> ::c_int; - pub fn scanf(format: *const ::c_char, ...) -> ::c_int; - pub fn sscanf(s: *const ::c_char, format: *const ::c_char, ...) -> ::c_int; - pub fn getchar_unlocked() -> ::c_int; - pub fn putchar_unlocked(c: ::c_int) -> ::c_int; - - pub fn socket(domain: ::c_int, ty: ::c_int, protocol: ::c_int) -> ::c_int; - pub fn connect(socket: ::c_int, address: *const sockaddr, - len: socklen_t) -> ::c_int; - pub fn listen(socket: ::c_int, backlog: ::c_int) -> ::c_int; - pub fn accept(socket: ::c_int, address: *mut sockaddr, - address_len: *mut socklen_t) -> ::c_int; - pub fn getpeername(socket: ::c_int, address: *mut sockaddr, - address_len: *mut socklen_t) -> ::c_int; - pub fn getsockname(socket: ::c_int, address: *mut sockaddr, - address_len: *mut socklen_t) -> ::c_int; - pub fn setsockopt(socket: ::c_int, level: ::c_int, name: ::c_int, - value: *const ::c_void, - option_len: socklen_t) -> ::c_int; - pub fn socketpair(domain: ::c_int, type_: ::c_int, protocol: ::c_int, - socket_vector: *mut ::c_int) -> ::c_int; - pub fn sendto(socket: ::c_int, buf: *const ::c_void, len: ::size_t, - flags: ::c_int, addr: *const sockaddr, - addrlen: socklen_t) -> ::ssize_t; - pub fn shutdown(socket: ::c_int, how: ::c_int) -> ::c_int; - - pub fn chmod(path: *const c_char, mode: mode_t) -> ::c_int; - pub fn fchmod(fd: ::c_int, mode: mode_t) -> ::c_int; - - pub fn fstat(fildes: ::c_int, buf: *mut stat) -> ::c_int; - - pub fn mkdir(path: *const c_char, mode: mode_t) -> ::c_int; - - pub fn stat(path: *const c_char, buf: *mut stat) -> ::c_int; - - pub fn pclose(stream: *mut ::FILE) -> ::c_int; - pub fn fdopen(fd: ::c_int, mode: *const c_char) -> *mut ::FILE; - pub fn fileno(stream: *mut ::FILE) -> ::c_int; - - pub fn open(path: *const c_char, oflag: ::c_int, ...) -> ::c_int; - pub fn creat(path: *const c_char, mode: mode_t) -> ::c_int; - pub fn fcntl(fd: ::c_int, cmd: ::c_int, ...) -> ::c_int; - - pub fn opendir(dirname: *const c_char) -> *mut ::DIR; - pub fn readdir(dirp: *mut ::DIR) -> *mut ::dirent; - pub fn readdir_r(dirp: *mut ::DIR, entry: *mut ::dirent, - result: *mut *mut ::dirent) -> ::c_int; - pub fn closedir(dirp: *mut ::DIR) -> ::c_int; - pub fn rewinddir(dirp: *mut ::DIR); - - pub fn openat(dirfd: ::c_int, pathname: *const ::c_char, - flags: ::c_int, ...) -> ::c_int; - pub fn fchmodat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t, flags: ::c_int) -> ::c_int; - pub fn fchown(fd: ::c_int, - owner: ::uid_t, - group: ::gid_t) -> ::c_int; - pub fn fchownat(dirfd: ::c_int, pathname: *const ::c_char, - owner: ::uid_t, group: ::gid_t, - flags: ::c_int) -> ::c_int; - pub fn fstatat(dirfd: ::c_int, pathname: *const ::c_char, - buf: *mut stat, flags: ::c_int) -> ::c_int; - pub fn linkat(olddirfd: ::c_int, oldpath: *const ::c_char, - newdirfd: ::c_int, newpath: *const ::c_char, - flags: ::c_int) -> ::c_int; - pub fn mkdirat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t) -> ::c_int; - pub fn readlinkat(dirfd: ::c_int, pathname: *const ::c_char, - buf: *mut ::c_char, bufsiz: ::size_t) -> ::ssize_t; - pub fn renameat(olddirfd: ::c_int, oldpath: *const ::c_char, - newdirfd: ::c_int, newpath: *const ::c_char) - -> ::c_int; - pub fn symlinkat(target: *const ::c_char, newdirfd: ::c_int, - linkpath: *const ::c_char) -> ::c_int; - pub fn unlinkat(dirfd: ::c_int, pathname: *const ::c_char, - flags: ::c_int) -> ::c_int; - - pub fn access(path: *const c_char, amode: ::c_int) -> ::c_int; - pub fn alarm(seconds: ::c_uint) -> ::c_uint; - pub fn chdir(dir: *const c_char) -> ::c_int; - pub fn fchdir(dirfd: ::c_int) -> ::c_int; - pub fn chown(path: *const c_char, uid: uid_t, - gid: gid_t) -> ::c_int; - pub fn lchown(path: *const c_char, uid: uid_t, - gid: gid_t) -> ::c_int; - pub fn close(fd: ::c_int) -> ::c_int; - pub fn dup(fd: ::c_int) -> ::c_int; - pub fn dup2(src: ::c_int, dst: ::c_int) -> ::c_int; - pub fn execl(path: *const c_char, - arg0: *const c_char, ...) -> ::c_int; - pub fn execle(path: *const ::c_char, - arg0: *const ::c_char, ...) -> ::c_int; - pub fn execlp(file: *const ::c_char, - arg0: *const ::c_char, ...) -> ::c_int; - pub fn execv(prog: *const c_char, - argv: *const *const c_char) -> ::c_int; - pub fn execve(prog: *const c_char, argv: *const *const c_char, - envp: *const *const c_char) - -> ::c_int; - pub fn execvp(c: *const c_char, - argv: *const *const c_char) -> ::c_int; - pub fn fork() -> pid_t; - pub fn fpathconf(filedes: ::c_int, name: ::c_int) -> c_long; - pub fn getcwd(buf: *mut c_char, size: ::size_t) -> *mut c_char; - pub fn getegid() -> gid_t; - pub fn geteuid() -> uid_t; - pub fn getgid() -> gid_t; - pub fn getgroups(ngroups_max: ::c_int, groups: *mut gid_t) - -> ::c_int; - pub fn getlogin() -> *mut c_char; - pub fn getopt(argc: ::c_int, argv: *const *mut c_char, - optstr: *const c_char) -> ::c_int; - pub fn getpgid(pid: pid_t) -> pid_t; - pub fn getpgrp() -> pid_t; - pub fn getpid() -> pid_t; - pub fn getppid() -> pid_t; - pub fn getuid() -> uid_t; - pub fn isatty(fd: ::c_int) -> ::c_int; - pub fn link(src: *const c_char, dst: *const c_char) -> ::c_int; - pub fn lseek(fd: ::c_int, offset: off_t, whence: ::c_int) -> off_t; - pub fn pathconf(path: *const c_char, name: ::c_int) -> c_long; - pub fn pause() -> ::c_int; - pub fn pipe(fds: *mut ::c_int) -> ::c_int; - pub fn posix_memalign(memptr: *mut *mut ::c_void, - align: ::size_t, - size: ::size_t) -> ::c_int; - pub fn read(fd: ::c_int, buf: *mut ::c_void, count: ::size_t) - -> ::ssize_t; - pub fn rmdir(path: *const c_char) -> ::c_int; - pub fn seteuid(uid: uid_t) -> ::c_int; - pub fn setgid(gid: gid_t) -> ::c_int; - pub fn setpgid(pid: pid_t, pgid: pid_t) -> ::c_int; - pub fn setsid() -> pid_t; - pub fn setuid(uid: uid_t) -> ::c_int; - pub fn sleep(secs: ::c_uint) -> ::c_uint; - pub fn nanosleep(rqtp: *const timespec, - rmtp: *mut timespec) -> ::c_int; - pub fn tcgetpgrp(fd: ::c_int) -> pid_t; - pub fn tcsetpgrp(fd: ::c_int, pgrp: ::pid_t) -> ::c_int; - pub fn ttyname(fd: ::c_int) -> *mut c_char; - pub fn unlink(c: *const c_char) -> ::c_int; - pub fn wait(status: *mut ::c_int) -> pid_t; - pub fn waitpid(pid: pid_t, status: *mut ::c_int, options: ::c_int) - -> pid_t; - pub fn write(fd: ::c_int, buf: *const ::c_void, count: ::size_t) - -> ::ssize_t; - pub fn pread(fd: ::c_int, buf: *mut ::c_void, count: ::size_t, - offset: off_t) -> ::ssize_t; - pub fn pwrite(fd: ::c_int, buf: *const ::c_void, count: ::size_t, - offset: off_t) -> ::ssize_t; - pub fn umask(mask: mode_t) -> mode_t; - - pub fn utime(file: *const c_char, buf: *const utimbuf) -> ::c_int; - - pub fn kill(pid: pid_t, sig: ::c_int) -> ::c_int; - - pub fn mlock(addr: *const ::c_void, len: ::size_t) -> ::c_int; - pub fn munlock(addr: *const ::c_void, len: ::size_t) -> ::c_int; - pub fn mlockall(flags: ::c_int) -> ::c_int; - pub fn munlockall() -> ::c_int; - - pub fn mmap(addr: *mut ::c_void, - len: ::size_t, - prot: ::c_int, - flags: ::c_int, - fd: ::c_int, - offset: off_t) - -> *mut ::c_void; - pub fn munmap(addr: *mut ::c_void, len: ::size_t) -> ::c_int; - - pub fn if_nametoindex(ifname: *const c_char) -> ::c_uint; - pub fn if_indextoname(ifindex: ::c_uint, - ifname: *mut ::c_char) -> *mut ::c_char; - - pub fn lstat(path: *const c_char, buf: *mut stat) -> ::c_int; - - pub fn fsync(fd: ::c_int) -> ::c_int; - - pub fn setenv(name: *const c_char, val: *const c_char, - overwrite: ::c_int) -> ::c_int; - pub fn unsetenv(name: *const c_char) -> ::c_int; - - pub fn symlink(path1: *const c_char, - path2: *const c_char) -> ::c_int; - - pub fn ftruncate(fd: ::c_int, length: off_t) -> ::c_int; - - pub fn signal(signum: ::c_int, handler: sighandler_t) -> sighandler_t; - - pub fn getrlimit(resource: ::c_int, rlim: *mut rlimit) -> ::c_int; - pub fn setrlimit(resource: ::c_int, rlim: *const rlimit) -> ::c_int; - pub fn getrusage(resource: ::c_int, usage: *mut rusage) -> ::c_int; - - pub fn realpath(pathname: *const ::c_char, resolved: *mut ::c_char) - -> *mut ::c_char; - - pub fn flock(fd: ::c_int, operation: ::c_int) -> ::c_int; - - pub fn gettimeofday(tp: *mut ::timeval, - tz: *mut ::c_void) -> ::c_int; - pub fn times(buf: *mut ::tms) -> ::clock_t; - - pub fn pthread_self() -> ::pthread_t; - pub fn pthread_join(native: ::pthread_t, - value: *mut *mut ::c_void) -> ::c_int; - pub fn pthread_exit(value: *mut ::c_void); - pub fn pthread_attr_init(attr: *mut ::pthread_attr_t) -> ::c_int; - pub fn pthread_attr_destroy(attr: *mut ::pthread_attr_t) -> ::c_int; - pub fn pthread_attr_setstacksize(attr: *mut ::pthread_attr_t, - stack_size: ::size_t) -> ::c_int; - pub fn pthread_attr_setdetachstate(attr: *mut ::pthread_attr_t, - state: ::c_int) -> ::c_int; - pub fn pthread_detach(thread: ::pthread_t) -> ::c_int; - pub fn sched_yield() -> ::c_int; - pub fn pthread_key_create(key: *mut pthread_key_t, - dtor: Option) - -> ::c_int; - pub fn pthread_key_delete(key: pthread_key_t) -> ::c_int; - pub fn pthread_getspecific(key: pthread_key_t) -> *mut ::c_void; - pub fn pthread_setspecific(key: pthread_key_t, value: *const ::c_void) - -> ::c_int; - pub fn pthread_mutex_init(lock: *mut pthread_mutex_t, - attr: *const pthread_mutexattr_t) -> ::c_int; - pub fn pthread_mutex_destroy(lock: *mut pthread_mutex_t) -> ::c_int; - pub fn pthread_mutex_lock(lock: *mut pthread_mutex_t) -> ::c_int; - pub fn pthread_mutex_trylock(lock: *mut pthread_mutex_t) -> ::c_int; - pub fn pthread_mutex_unlock(lock: *mut pthread_mutex_t) -> ::c_int; - - pub fn pthread_mutexattr_init(attr: *mut pthread_mutexattr_t) -> ::c_int; - pub fn pthread_mutexattr_destroy(attr: *mut pthread_mutexattr_t) -> ::c_int; - pub fn pthread_mutexattr_settype(attr: *mut pthread_mutexattr_t, - _type: ::c_int) -> ::c_int; - - pub fn pthread_cond_init(cond: *mut pthread_cond_t, - attr: *const pthread_condattr_t) -> ::c_int; - pub fn pthread_cond_wait(cond: *mut pthread_cond_t, - lock: *mut pthread_mutex_t) -> ::c_int; - pub fn pthread_cond_timedwait(cond: *mut pthread_cond_t, - lock: *mut pthread_mutex_t, - abstime: *const ::timespec) -> ::c_int; - pub fn pthread_cond_signal(cond: *mut pthread_cond_t) -> ::c_int; - pub fn pthread_cond_broadcast(cond: *mut pthread_cond_t) -> ::c_int; - pub fn pthread_cond_destroy(cond: *mut pthread_cond_t) -> ::c_int; - pub fn pthread_condattr_init(attr: *mut pthread_condattr_t) -> ::c_int; - pub fn pthread_condattr_destroy(attr: *mut pthread_condattr_t) -> ::c_int; - pub fn pthread_rwlock_init(lock: *mut pthread_rwlock_t, - attr: *const pthread_rwlockattr_t) -> ::c_int; - pub fn pthread_rwlock_destroy(lock: *mut pthread_rwlock_t) -> ::c_int; - pub fn pthread_rwlock_rdlock(lock: *mut pthread_rwlock_t) -> ::c_int; - pub fn pthread_rwlock_tryrdlock(lock: *mut pthread_rwlock_t) -> ::c_int; - pub fn pthread_rwlock_wrlock(lock: *mut pthread_rwlock_t) -> ::c_int; - pub fn pthread_rwlock_trywrlock(lock: *mut pthread_rwlock_t) -> ::c_int; - pub fn pthread_rwlock_unlock(lock: *mut pthread_rwlock_t) -> ::c_int; - pub fn pthread_rwlockattr_init(attr: *mut pthread_rwlockattr_t) -> ::c_int; - pub fn pthread_rwlockattr_destroy(attr: *mut pthread_rwlockattr_t) - -> ::c_int; - pub fn strerror_r(errnum: ::c_int, buf: *mut c_char, - buflen: ::size_t) -> ::c_int; - - pub fn getsockopt(sockfd: ::c_int, - level: ::c_int, - optname: ::c_int, - optval: *mut ::c_void, - optlen: *mut ::socklen_t) -> ::c_int; - pub fn raise(signum: ::c_int) -> ::c_int; - pub fn sigaction(signum: ::c_int, - act: *const sigaction, - oldact: *mut sigaction) -> ::c_int; - - pub fn utimes(filename: *const ::c_char, - times: *const ::timeval) -> ::c_int; - pub fn dlopen(filename: *const ::c_char, - flag: ::c_int) -> *mut ::c_void; - pub fn dlerror() -> *mut ::c_char; - pub fn dlsym(handle: *mut ::c_void, - symbol: *const ::c_char) -> *mut ::c_void; - pub fn dlclose(handle: *mut ::c_void) -> ::c_int; - pub fn dladdr(addr: *const ::c_void, info: *mut Dl_info) -> ::c_int; - - pub fn getaddrinfo(node: *const c_char, - service: *const c_char, - hints: *const addrinfo, - res: *mut *mut addrinfo) -> ::c_int; - pub fn freeaddrinfo(res: *mut addrinfo); - pub fn gai_strerror(errcode: ::c_int) -> *const ::c_char; - pub fn res_init() -> ::c_int; - - pub fn gmtime_r(time_p: *const time_t, result: *mut tm) -> *mut tm; - pub fn localtime_r(time_p: *const time_t, result: *mut tm) -> *mut tm; - pub fn mktime(tm: *mut tm) -> time_t; - pub fn time(time: *mut time_t) -> time_t; - pub fn gmtime(time_p: *const time_t) -> *mut tm; - pub fn localtime(time_p: *const time_t) -> *mut tm; - - pub fn mknod(pathname: *const ::c_char, mode: ::mode_t, - dev: ::dev_t) -> ::c_int; - pub fn uname(buf: *mut ::utsname) -> ::c_int; - pub fn gethostname(name: *mut ::c_char, len: ::size_t) -> ::c_int; - pub fn getservbyname(name: *const ::c_char, - proto: *const ::c_char) -> *mut servent; - pub fn getprotobyname(name: *const ::c_char) -> *mut protoent; - pub fn getprotobynumber(proto: ::c_int) -> *mut protoent; - pub fn chroot(name: *const ::c_char) -> ::c_int; - pub fn usleep(secs: ::c_uint) -> ::c_int; - pub fn send(socket: ::c_int, buf: *const ::c_void, len: ::size_t, - flags: ::c_int) -> ::ssize_t; - pub fn recv(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, - flags: ::c_int) -> ::ssize_t; - pub fn putenv(string: *mut c_char) -> ::c_int; - pub fn poll(fds: *mut pollfd, nfds: nfds_t, timeout: ::c_int) -> ::c_int; - pub fn select(nfds: ::c_int, - readfs: *mut fd_set, - writefds: *mut fd_set, - errorfds: *mut fd_set, - timeout: *mut timeval) -> ::c_int; - pub fn setlocale(category: ::c_int, - locale: *const ::c_char) -> *mut ::c_char; - pub fn localeconv() -> *mut lconv; - - pub fn sem_destroy(sem: *mut sem_t) -> ::c_int; - pub fn sem_wait(sem: *mut sem_t) -> ::c_int; - pub fn sem_trywait(sem: *mut sem_t) -> ::c_int; - pub fn sem_post(sem: *mut sem_t) -> ::c_int; - pub fn sem_init(sem: *mut sem_t, - pshared: ::c_int, - value: ::c_uint) - -> ::c_int; - pub fn statvfs(path: *const c_char, buf: *mut statvfs) -> ::c_int; - pub fn fstatvfs(fd: ::c_int, buf: *mut statvfs) -> ::c_int; - - pub fn readlink(path: *const c_char, - buf: *mut c_char, - bufsz: ::size_t) - -> ::ssize_t; - - pub fn sigemptyset(set: *mut sigset_t) -> ::c_int; - pub fn sigaddset(set: *mut sigset_t, signum: ::c_int) -> ::c_int; - pub fn sigfillset(set: *mut sigset_t) -> ::c_int; - pub fn sigdelset(set: *mut sigset_t, signum: ::c_int) -> ::c_int; - pub fn sigismember(set: *const sigset_t, signum: ::c_int) -> ::c_int; - - pub fn sigprocmask(how: ::c_int, - set: *const sigset_t, - oldset: *mut sigset_t) - -> ::c_int; - pub fn sigpending(set: *mut sigset_t) -> ::c_int; - - pub fn timegm(tm: *mut ::tm) -> time_t; - - pub fn getsid(pid: pid_t) -> pid_t; - - pub fn sysconf(name: ::c_int) -> ::c_long; - - pub fn mkfifo(path: *const c_char, mode: mode_t) -> ::c_int; - - pub fn pselect(nfds: ::c_int, - readfs: *mut fd_set, - writefds: *mut fd_set, - errorfds: *mut fd_set, - timeout: *const timespec, - sigmask: *const sigset_t) -> ::c_int; - pub fn fseeko(stream: *mut ::FILE, - offset: ::off_t, - whence: ::c_int) -> ::c_int; - pub fn ftello(stream: *mut ::FILE) -> ::off_t; - pub fn tcdrain(fd: ::c_int) -> ::c_int; - pub fn cfgetispeed(termios: *const ::termios) -> ::speed_t; - pub fn cfgetospeed(termios: *const ::termios) -> ::speed_t; - pub fn cfmakeraw(termios: *mut ::termios); - pub fn cfsetispeed(termios: *mut ::termios, speed: ::speed_t) -> ::c_int; - pub fn cfsetospeed(termios: *mut ::termios, speed: ::speed_t) -> ::c_int; - pub fn cfsetspeed(termios: *mut ::termios, speed: ::speed_t) -> ::c_int; - pub fn tcgetattr(fd: ::c_int, termios: *mut ::termios) -> ::c_int; - pub fn tcsetattr(fd: ::c_int, - optional_actions: ::c_int, - termios: *const ::termios) -> ::c_int; - pub fn tcflow(fd: ::c_int, action: ::c_int) -> ::c_int; - pub fn tcflush(fd: ::c_int, action: ::c_int) -> ::c_int; - pub fn tcgetsid(fd: ::c_int) -> ::pid_t; - pub fn tcsendbreak(fd: ::c_int, duration: ::c_int) -> ::c_int; - pub fn mkstemp(template: *mut ::c_char) -> ::c_int; - pub fn mkdtemp(template: *mut ::c_char) -> *mut ::c_char; - - pub fn tmpnam(ptr: *mut ::c_char) -> *mut ::c_char; - - pub fn openlog(ident: *const ::c_char, logopt: ::c_int, facility: ::c_int); - pub fn closelog(); - pub fn setlogmask(maskpri: ::c_int) -> ::c_int; - pub fn syslog(priority: ::c_int, message: *const ::c_char, ...); - pub fn nice(incr: ::c_int) -> ::c_int; - - pub fn grantpt(fd: ::c_int) -> ::c_int; - pub fn posix_openpt(flags: ::c_int) -> ::c_int; - pub fn ptsname(fd: ::c_int) -> *mut ::c_char; - pub fn unlockpt(fd: ::c_int) -> ::c_int; - - pub fn fdatasync(fd: ::c_int) -> ::c_int; - pub fn mincore(addr: *mut ::c_void, len: ::size_t, - vec: *mut ::c_uchar) -> ::c_int; - pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; - pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; - - pub fn pthread_getattr_np(native: ::pthread_t, - attr: *mut ::pthread_attr_t) -> ::c_int; - pub fn pthread_attr_getstack(attr: *const ::pthread_attr_t, - stackaddr: *mut *mut ::c_void, - stacksize: *mut ::size_t) -> ::c_int; - pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; - pub fn setgroups(ngroups: ::size_t, - ptr: *const ::gid_t) -> ::c_int; - pub fn pipe2(fds: *mut ::c_int, flags: ::c_int) -> ::c_int; - pub fn statfs(path: *const ::c_char, buf: *mut statfs) -> ::c_int; - pub fn statfs64(path: *const ::c_char, buf: *mut statfs64) -> ::c_int; - pub fn fstatfs(fd: ::c_int, buf: *mut statfs) -> ::c_int; - pub fn fstatfs64(fd: ::c_int, buf: *mut statfs64) -> ::c_int; - pub fn statvfs64(path: *const ::c_char, buf: *mut statvfs64) -> ::c_int; - pub fn fstatvfs64(fd: ::c_int, buf: *mut statvfs64) -> ::c_int; - pub fn memrchr(cx: *const ::c_void, - c: ::c_int, - n: ::size_t) -> *mut ::c_void; - - pub fn posix_fadvise(fd: ::c_int, offset: ::off_t, len: ::off_t, - advise: ::c_int) -> ::c_int; - pub fn futimens(fd: ::c_int, times: *const ::timespec) -> ::c_int; - pub fn utimensat(dirfd: ::c_int, path: *const ::c_char, - times: *const ::timespec, flag: ::c_int) -> ::c_int; - pub fn duplocale(base: ::locale_t) -> ::locale_t; - pub fn freelocale(loc: ::locale_t); - pub fn newlocale(mask: ::c_int, - locale: *const ::c_char, - base: ::locale_t) -> ::locale_t; - pub fn uselocale(loc: ::locale_t) -> ::locale_t; - pub fn creat64(path: *const c_char, mode: mode_t) -> ::c_int; - pub fn fstat64(fildes: ::c_int, buf: *mut stat64) -> ::c_int; - pub fn fstatat64(dirfd: ::c_int, pathname: *const c_char, - buf: *mut stat64, flags: ::c_int) -> ::c_int; - pub fn ftruncate64(fd: ::c_int, length: off64_t) -> ::c_int; - pub fn getrlimit64(resource: ::c_int, rlim: *mut rlimit64) -> ::c_int; - pub fn lseek64(fd: ::c_int, offset: off64_t, whence: ::c_int) -> off64_t; - pub fn lstat64(path: *const c_char, buf: *mut stat64) -> ::c_int; - pub fn mmap64(addr: *mut ::c_void, - len: ::size_t, - prot: ::c_int, - flags: ::c_int, - fd: ::c_int, - offset: off64_t) - -> *mut ::c_void; - pub fn open64(path: *const c_char, oflag: ::c_int, ...) -> ::c_int; - pub fn openat64(fd: ::c_int, - path: *const c_char, - oflag: ::c_int, ...) -> ::c_int; - pub fn pread64(fd: ::c_int, buf: *mut ::c_void, count: ::size_t, - offset: off64_t) -> ::ssize_t; - pub fn preadv64(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off64_t) -> ::ssize_t; - pub fn pwrite64(fd: ::c_int, buf: *const ::c_void, count: ::size_t, - offset: off64_t) -> ::ssize_t; - pub fn pwritev64(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off64_t) -> ::ssize_t; - pub fn readdir64(dirp: *mut ::DIR) -> *mut ::dirent64; - pub fn readdir64_r(dirp: *mut ::DIR, entry: *mut ::dirent64, - result: *mut *mut ::dirent64) -> ::c_int; - pub fn setrlimit64(resource: ::c_int, rlim: *const rlimit64) -> ::c_int; - pub fn stat64(path: *const c_char, buf: *mut stat64) -> ::c_int; - pub fn truncate64(path: *const c_char, length: off64_t) -> ::c_int; - - pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; - - pub fn mknodat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t, dev: dev_t) -> ::c_int; - pub fn pthread_condattr_getclock(attr: *const pthread_condattr_t, - clock_id: *mut clockid_t) -> ::c_int; - pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, - clock_id: ::clockid_t) -> ::c_int; - pub fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, - pshared: ::c_int) -> ::c_int; - pub fn accept4(fd: ::c_int, addr: *mut ::sockaddr, len: *mut ::socklen_t, - flg: ::c_int) -> ::c_int; - pub fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, - pshared: ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, - val: *mut ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, - val: ::c_int) -> ::c_int; - pub fn ptsname_r(fd: ::c_int, - buf: *mut ::c_char, - buflen: ::size_t) -> ::c_int; - pub fn clearenv() -> ::c_int; - pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, - options: ::c_int) -> ::c_int; - pub fn setreuid(ruid: ::uid_t, euid: ::uid_t) -> ::c_int; - pub fn setregid(rgid: ::gid_t, egid: ::gid_t) -> ::c_int; - pub fn getresuid(ruid: *mut ::uid_t, euid: *mut ::uid_t, - suid: *mut ::uid_t) -> ::c_int; - pub fn getresgid(rgid: *mut ::gid_t, egid: *mut ::gid_t, - sgid: *mut ::gid_t) -> ::c_int; - pub fn acct(filename: *const ::c_char) -> ::c_int; - pub fn brk(addr: *mut ::c_void) -> ::c_int; - pub fn sbrk(increment: ::intptr_t) -> *mut ::c_void; - pub fn vfork() -> ::pid_t; - pub fn setresgid(rgid: ::gid_t, egid: ::gid_t, sgid: ::gid_t) -> ::c_int; - pub fn setresuid(ruid: ::uid_t, euid: ::uid_t, suid: ::uid_t) -> ::c_int; - pub fn wait4(pid: ::pid_t, status: *mut ::c_int, options: ::c_int, - rusage: *mut ::rusage) -> ::pid_t; - pub fn openpty(amaster: *mut ::c_int, - aslave: *mut ::c_int, - name: *mut ::c_char, - termp: *const termios, - winp: *const ::winsize) -> ::c_int; - pub fn execvpe(file: *const ::c_char, argv: *const *const ::c_char, - envp: *const *const ::c_char) -> ::c_int; - pub fn fexecve(fd: ::c_int, argv: *const *const ::c_char, - envp: *const *const ::c_char) - -> ::c_int; - - pub fn ioctl(fd: ::c_int, request: ::c_int, ...) -> ::c_int; - pub fn ptrace(request: ::c_int, ...) -> ::c_long; - pub fn getpriority(which: ::c_int, who: ::id_t) -> ::c_int; - pub fn setpriority(which: ::c_int, who: ::id_t, prio: ::c_int) -> ::c_int; - - pub fn aio_read(aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_write(aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_fsync(op: ::c_int, aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_error(aiocbp: *const aiocb) -> ::c_int; - pub fn aio_return(aiocbp: *mut aiocb) -> ::ssize_t; - pub fn aio_suspend(aiocb_list: *const *const aiocb, nitems: ::c_int, - timeout: *const ::timespec) -> ::c_int; - pub fn aio_cancel(fd: ::c_int, aiocbp: *mut aiocb) -> ::c_int; - pub fn lio_listio(mode: ::c_int, aiocb_list: *const *mut aiocb, - nitems: ::c_int, sevp: *mut ::sigevent) -> ::c_int; - - pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; - - pub fn setpwent(); - pub fn endpwent(); - pub fn getpwent() -> *mut passwd; - pub fn setspent(); - pub fn endspent(); - pub fn getspent() -> *mut spwd; - pub fn getspnam(__name: *const ::c_char) -> *mut spwd; - - pub fn shm_open(name: *const c_char, oflag: ::c_int, - mode: mode_t) -> ::c_int; - - // System V IPC - pub fn shmget(key: ::key_t, size: ::size_t, shmflg: ::c_int) -> ::c_int; - pub fn shmat(shmid: ::c_int, - shmaddr: *const ::c_void, - shmflg: ::c_int) -> *mut ::c_void; - pub fn shmdt(shmaddr: *const ::c_void) -> ::c_int; - pub fn shmctl(shmid: ::c_int, - cmd: ::c_int, - buf: *mut ::shmid_ds) -> ::c_int; - pub fn ftok(pathname: *const ::c_char, proj_id: ::c_int) -> ::key_t; - pub fn semget(key: ::key_t, nsems: ::c_int, semflag: ::c_int) -> ::c_int; - pub fn semop(semid: ::c_int, - sops: *mut ::sembuf, nsops: ::size_t) -> ::c_int; - pub fn semctl(semid: ::c_int, - semnum: ::c_int, cmd: ::c_int, ...) -> ::c_int; - pub fn msgctl(msqid: ::c_int, cmd: ::c_int, buf: *mut msqid_ds) -> ::c_int; - pub fn msgget(key: ::key_t, msgflg: ::c_int) -> ::c_int; - pub fn msgrcv(msqid: ::c_int, msgp: *mut ::c_void, msgsz: ::size_t, - msgtyp: ::c_long, msgflg: ::c_int) -> ::ssize_t; - pub fn msgsnd(msqid: ::c_int, msgp: *const ::c_void, msgsz: ::size_t, - msgflg: ::c_int) -> ::c_int; - - pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) - -> ::c_int; - pub fn __errno_location() -> *mut ::c_int; - - pub fn fopen64(filename: *const c_char, - mode: *const c_char) -> *mut ::FILE; - pub fn freopen64(filename: *const c_char, mode: *const c_char, - file: *mut ::FILE) -> *mut ::FILE; - pub fn tmpfile64() -> *mut ::FILE; - pub fn fgetpos64(stream: *mut ::FILE, ptr: *mut fpos64_t) -> ::c_int; - pub fn fsetpos64(stream: *mut ::FILE, ptr: *const fpos64_t) -> ::c_int; - pub fn fseeko64(stream: *mut ::FILE, - offset: ::off64_t, - whence: ::c_int) -> ::c_int; - pub fn ftello64(stream: *mut ::FILE) -> ::off64_t; - pub fn fallocate(fd: ::c_int, mode: ::c_int, - offset: ::off_t, len: ::off_t) -> ::c_int; - pub fn posix_fallocate(fd: ::c_int, offset: ::off_t, - len: ::off_t) -> ::c_int; - pub fn readahead(fd: ::c_int, offset: ::off64_t, - count: ::size_t) -> ::ssize_t; - pub fn getxattr(path: *const c_char, name: *const c_char, - value: *mut ::c_void, size: ::size_t) -> ::ssize_t; - pub fn lgetxattr(path: *const c_char, name: *const c_char, - value: *mut ::c_void, size: ::size_t) -> ::ssize_t; - pub fn fgetxattr(filedes: ::c_int, name: *const c_char, - value: *mut ::c_void, size: ::size_t) -> ::ssize_t; - pub fn setxattr(path: *const c_char, name: *const c_char, - value: *const ::c_void, size: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn lsetxattr(path: *const c_char, name: *const c_char, - value: *const ::c_void, size: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn fsetxattr(filedes: ::c_int, name: *const c_char, - value: *const ::c_void, size: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn listxattr(path: *const c_char, list: *mut c_char, - size: ::size_t) -> ::ssize_t; - pub fn llistxattr(path: *const c_char, list: *mut c_char, - size: ::size_t) -> ::ssize_t; - pub fn flistxattr(filedes: ::c_int, list: *mut c_char, - size: ::size_t) -> ::ssize_t; - pub fn removexattr(path: *const c_char, name: *const c_char) -> ::c_int; - pub fn lremovexattr(path: *const c_char, name: *const c_char) -> ::c_int; - pub fn fremovexattr(filedes: ::c_int, name: *const c_char) -> ::c_int; - pub fn signalfd(fd: ::c_int, - mask: *const ::sigset_t, - flags: ::c_int) -> ::c_int; - pub fn timerfd_create(clockid: ::c_int, flags: ::c_int) -> ::c_int; - pub fn timerfd_gettime(fd: ::c_int, - curr_value: *mut itimerspec) -> ::c_int; - pub fn timerfd_settime(fd: ::c_int, - flags: ::c_int, - new_value: *const itimerspec, - old_value: *mut itimerspec) -> ::c_int; - pub fn pwritev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off_t) -> ::ssize_t; - pub fn preadv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off_t) -> ::ssize_t; - pub fn quotactl(cmd: ::c_int, - special: *const ::c_char, - id: ::c_int, - data: *mut ::c_char) -> ::c_int; - pub fn mq_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::mqd_t; - pub fn mq_close(mqd: ::mqd_t) -> ::c_int; - pub fn mq_unlink(name: *const ::c_char) -> ::c_int; - pub fn mq_receive(mqd: ::mqd_t, - msg_ptr: *mut ::c_char, - msg_len: ::size_t, - msq_prio: *mut ::c_uint) -> ::ssize_t; - pub fn mq_send(mqd: ::mqd_t, - msg_ptr: *const ::c_char, - msg_len: ::size_t, - msq_prio: ::c_uint) -> ::c_int; - pub fn mq_getattr(mqd: ::mqd_t, attr: *mut ::mq_attr) -> ::c_int; - pub fn mq_setattr(mqd: ::mqd_t, - newattr: *const ::mq_attr, - oldattr: *mut ::mq_attr) -> ::c_int; - pub fn epoll_pwait(epfd: ::c_int, - events: *mut ::epoll_event, - maxevents: ::c_int, - timeout: ::c_int, - sigmask: *const ::sigset_t) -> ::c_int; - pub fn dup3(oldfd: ::c_int, newfd: ::c_int, flags: ::c_int) -> ::c_int; - pub fn mkostemp(template: *mut ::c_char, flags: ::c_int) -> ::c_int; - pub fn mkostemps(template: *mut ::c_char, - suffixlen: ::c_int, - flags: ::c_int) -> ::c_int; - pub fn sigtimedwait(set: *const sigset_t, - info: *mut siginfo_t, - timeout: *const ::timespec) -> ::c_int; - pub fn sigwaitinfo(set: *const sigset_t, - info: *mut siginfo_t) -> ::c_int; - pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; - pub fn getnameinfo(sa: *const ::sockaddr, - salen: ::socklen_t, - host: *mut ::c_char, - hostlen: ::socklen_t, - serv: *mut ::c_char, - sevlen: ::socklen_t, - flags: ::c_int) -> ::c_int; - pub fn pthread_setschedprio(native: ::pthread_t, - priority: ::c_int) -> ::c_int; - pub fn prlimit(pid: ::pid_t, resource: ::c_int, new_limit: *const ::rlimit, - old_limit: *mut ::rlimit) -> ::c_int; - pub fn prlimit64(pid: ::pid_t, - resource: ::c_int, - new_limit: *const ::rlimit64, - old_limit: *mut ::rlimit64) -> ::c_int; - pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int; - pub fn process_vm_readv(pid: ::pid_t, - local_iov: *const ::iovec, - liovcnt: ::c_ulong, - remote_iov: *const ::iovec, - riovcnt: ::c_ulong, - flags: ::c_ulong) -> isize; - pub fn process_vm_writev(pid: ::pid_t, - local_iov: *const ::iovec, - liovcnt: ::c_ulong, - remote_iov: *const ::iovec, - riovcnt: ::c_ulong, - flags: ::c_ulong) -> isize; - pub fn reboot(how_to: ::c_int) -> ::c_int; - pub fn setfsgid(gid: ::gid_t) -> ::c_int; - pub fn setfsuid(uid: ::uid_t) -> ::c_int; - - // Not available now on Android - pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t) -> ::c_int; - pub fn if_nameindex() -> *mut if_nameindex; - pub fn if_freenameindex(ptr: *mut if_nameindex); - pub fn sync_file_range(fd: ::c_int, offset: ::off64_t, - nbytes: ::off64_t, flags: ::c_uint) -> ::c_int; - pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; - pub fn freeifaddrs(ifa: *mut ::ifaddrs); - - pub fn mremap(addr: *mut ::c_void, - len: ::size_t, - new_len: ::size_t, - flags: ::c_int, - ...) -> *mut ::c_void; - - pub fn glob(pattern: *const c_char, - flags: ::c_int, - errfunc: Option ::c_int>, - pglob: *mut ::glob_t) -> ::c_int; - pub fn globfree(pglob: *mut ::glob_t); - - pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - pub fn shm_unlink(name: *const ::c_char) -> ::c_int; - - pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); - - pub fn telldir(dirp: *mut ::DIR) -> ::c_long; - pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; - - pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, - flags: ::c_int, addr: *mut ::sockaddr, - addrlen: *mut ::socklen_t) -> ::ssize_t; - pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; - pub fn futimes(fd: ::c_int, times: *const ::timeval) -> ::c_int; - pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; - - pub fn bind(socket: ::c_int, address: *const ::sockaddr, - address_len: ::socklen_t) -> ::c_int; - - pub fn writev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - pub fn readv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - - pub fn sendmsg(fd: ::c_int, - msg: *const ::msghdr, - flags: ::c_int) -> ::ssize_t; - pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) - -> ::ssize_t; - pub fn getdomainname(name: *mut ::c_char, len: ::size_t) -> ::c_int; - pub fn setdomainname(name: *const ::c_char, len: ::size_t) -> ::c_int; - pub fn vhangup() -> ::c_int; - pub fn sendmmsg(sockfd: ::c_int, msgvec: *mut mmsghdr, vlen: ::c_uint, - flags: ::c_int) -> ::c_int; - pub fn recvmmsg(sockfd: ::c_int, msgvec: *mut mmsghdr, vlen: ::c_uint, - flags: ::c_int, timeout: *mut ::timespec) -> ::c_int; - pub fn sync(); - pub fn syscall(num: ::c_long, ...) -> ::c_long; - pub fn sched_getaffinity(pid: ::pid_t, - cpusetsize: ::size_t, - cpuset: *mut cpu_set_t) -> ::c_int; - pub fn sched_setaffinity(pid: ::pid_t, - cpusetsize: ::size_t, - cpuset: *const cpu_set_t) -> ::c_int; - pub fn epoll_create(size: ::c_int) -> ::c_int; - pub fn epoll_create1(flags: ::c_int) -> ::c_int; - pub fn epoll_wait(epfd: ::c_int, - events: *mut ::epoll_event, - maxevents: ::c_int, - timeout: ::c_int) -> ::c_int; - pub fn epoll_ctl(epfd: ::c_int, - op: ::c_int, - fd: ::c_int, - event: *mut ::epoll_event) -> ::c_int; - pub fn pthread_getschedparam(native: ::pthread_t, - policy: *mut ::c_int, - param: *mut ::sched_param) -> ::c_int; - pub fn unshare(flags: ::c_int) -> ::c_int; - pub fn umount(target: *const ::c_char) -> ::c_int; - pub fn sched_get_priority_max(policy: ::c_int) -> ::c_int; - pub fn tee(fd_in: ::c_int, - fd_out: ::c_int, - len: ::size_t, - flags: ::c_uint) -> ::ssize_t; - pub fn settimeofday(tv: *const ::timeval, tz: *const ::timezone) -> ::c_int; - pub fn splice(fd_in: ::c_int, - off_in: *mut ::loff_t, - fd_out: ::c_int, - off_out: *mut ::loff_t, - len: ::size_t, - flags: ::c_uint) -> ::ssize_t; - pub fn eventfd(init: ::c_uint, flags: ::c_int) -> ::c_int; - pub fn sched_rr_get_interval(pid: ::pid_t, tp: *mut ::timespec) -> ::c_int; - pub fn sem_timedwait(sem: *mut sem_t, - abstime: *const ::timespec) -> ::c_int; - pub fn sched_setparam(pid: ::pid_t, param: *const ::sched_param) -> ::c_int; - pub fn setns(fd: ::c_int, nstype: ::c_int) -> ::c_int; - pub fn swapoff(puath: *const ::c_char) -> ::c_int; - pub fn vmsplice(fd: ::c_int, - iov: *const ::iovec, - nr_segs: ::size_t, - flags: ::c_uint) -> ::ssize_t; - pub fn mount(src: *const ::c_char, - target: *const ::c_char, - fstype: *const ::c_char, - flags: ::c_ulong, - data: *const ::c_void) -> ::c_int; - pub fn personality(persona: ::c_ulong) -> ::c_int; - pub fn prctl(option: ::c_int, ...) -> ::c_int; - pub fn sched_getparam(pid: ::pid_t, param: *mut ::sched_param) -> ::c_int; - pub fn ppoll(fds: *mut ::pollfd, - nfds: nfds_t, - timeout: *const ::timespec, - sigmask: *const sigset_t) -> ::c_int; - pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, - abstime: *const ::timespec) -> ::c_int; - pub fn clone(cb: extern fn(*mut ::c_void) -> ::c_int, - child_stack: *mut ::c_void, - flags: ::c_int, - arg: *mut ::c_void, ...) -> ::c_int; - pub fn sched_getscheduler(pid: ::pid_t) -> ::c_int; - pub fn clock_nanosleep(clk_id: ::clockid_t, - flags: ::c_int, - rqtp: *const ::timespec, - rmtp: *mut ::timespec) -> ::c_int; - pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, - guardsize: *mut ::size_t) -> ::c_int; - pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; - pub fn sched_get_priority_min(policy: ::c_int) -> ::c_int; - pub fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, - pshared: *mut ::c_int) -> ::c_int; - pub fn sysinfo(info: *mut ::sysinfo) -> ::c_int; - pub fn umount2(target: *const ::c_char, flags: ::c_int) -> ::c_int; - pub fn pthread_setschedparam(native: ::pthread_t, - policy: ::c_int, - param: *const ::sched_param) -> ::c_int; - pub fn swapon(path: *const ::c_char, swapflags: ::c_int) -> ::c_int; - pub fn sched_setscheduler(pid: ::pid_t, - policy: ::c_int, - param: *const ::sched_param) -> ::c_int; - pub fn sendfile(out_fd: ::c_int, - in_fd: ::c_int, - offset: *mut off_t, - count: ::size_t) -> ::ssize_t; - pub fn sigsuspend(mask: *const ::sigset_t) -> ::c_int; - pub fn getgrgid_r(uid: ::uid_t, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - pub fn sigaltstack(ss: *const stack_t, - oss: *mut stack_t) -> ::c_int; - pub fn sem_close(sem: *mut sem_t) -> ::c_int; - pub fn getdtablesize() -> ::c_int; - pub fn getgrnam_r(name: *const ::c_char, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - pub fn initgroups(user: *const ::c_char, group: ::gid_t) -> ::c_int; - pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, - oldset: *mut sigset_t) -> ::c_int; - pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; - pub fn getgrnam(name: *const ::c_char) -> *mut ::group; - pub fn pthread_cancel(thread: ::pthread_t) -> ::c_int; - pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; - pub fn sem_unlink(name: *const ::c_char) -> ::c_int; - pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; - pub fn getpwnam_r(name: *const ::c_char, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - pub fn getpwuid_r(uid: ::uid_t, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - pub fn sigwait(set: *const sigset_t, - sig: *mut ::c_int) -> ::c_int; - pub fn pthread_atfork(prepare: Option, - parent: Option, - child: Option) -> ::c_int; - pub fn getgrgid(gid: ::gid_t) -> *mut ::group; - pub fn getgrouplist(user: *const ::c_char, - group: ::gid_t, - groups: *mut ::gid_t, - ngroups: *mut ::c_int) -> ::c_int; - pub fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, - pshared: *mut ::c_int) -> ::c_int; - pub fn popen(command: *const c_char, - mode: *const c_char) -> *mut ::FILE; - pub fn faccessat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::c_int, flags: ::c_int) -> ::c_int; - pub fn pthread_create(native: *mut ::pthread_t, - attr: *const ::pthread_attr_t, - f: extern fn(*mut ::c_void) -> *mut ::c_void, - value: *mut ::c_void) -> ::c_int; - pub fn dl_iterate_phdr( - callback: Option ::c_int>, - data: *mut ::c_void - ) -> ::c_int; -} - -cfg_if! { - if #[cfg(target_arch = "aarch64")] { - mod aarch64; - pub use self::aarch64::*; - } else if #[cfg(any(target_arch = "powerpc64"))] { - mod powerpc64; - pub use self::powerpc64::*; - } else if #[cfg(any(target_arch = "x86_64"))] { - mod x86_64; - pub use self::x86_64::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/fuchsia/powerpc64.rs cargo-0.26.0/vendor/libc-0.2.36/src/fuchsia/powerpc64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/fuchsia/powerpc64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/fuchsia/powerpc64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -pub type c_char = u8; -pub type wchar_t = i32; -pub type __u64 = ::c_ulong; -pub type nlink_t = u64; -pub type blksize_t = ::c_long; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - __pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused: [::c_long; 3], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino64_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - __pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __reserved: [::c_long; 3], - } - - pub struct ipc_perm { - pub __ipc_perm_key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::mode_t, - pub __seq: ::c_int, - __unused1: ::c_long, - __unused2: ::c_long - } -} - -pub const SYS_pivot_root: ::c_long = 203; -pub const SYS_gettid: ::c_long = 207; -pub const SYS_perf_event_open: ::c_long = 319; -pub const SYS_memfd_create: ::c_long = 360; - -pub const MAP_32BIT: ::c_int = 0x0040; - -pub const SIGSTKSZ: ::size_t = 8192; -pub const MINSIGSTKSZ: ::size_t = 2048; - -#[doc(hidden)] -pub const AF_MAX: ::c_int = 42; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; - -// Syscall table -pub const SYS_renameat2: ::c_long = 357; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/fuchsia/x86_64.rs cargo-0.26.0/vendor/libc-0.2.36/src/fuchsia/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/fuchsia/x86_64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/fuchsia/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,447 +0,0 @@ -pub type c_char = i8; -pub type wchar_t = i32; -pub type nlink_t = u64; -pub type blksize_t = ::c_long; -pub type __u64 = ::c_ulonglong; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - __pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused: [::c_long; 3], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino64_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - __pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __reserved: [::c_long; 3], - } - - pub struct mcontext_t { - __private: [u64; 32], - } - - pub struct ucontext_t { - pub uc_flags: ::c_ulong, - pub uc_link: *mut ucontext_t, - pub uc_stack: ::stack_t, - pub uc_mcontext: mcontext_t, - pub uc_sigmask: ::sigset_t, - __private: [u8; 512], - } - - pub struct ipc_perm { - pub __ipc_perm_key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::mode_t, - pub __seq: ::c_int, - __unused1: ::c_long, - __unused2: ::c_long - } -} - -// Syscall table - -pub const SYS_read: ::c_long = 0; -pub const SYS_write: ::c_long = 1; -pub const SYS_open: ::c_long = 2; -pub const SYS_close: ::c_long = 3; -pub const SYS_stat: ::c_long = 4; -pub const SYS_fstat: ::c_long = 5; -pub const SYS_lstat: ::c_long = 6; -pub const SYS_poll: ::c_long = 7; -pub const SYS_lseek: ::c_long = 8; -pub const SYS_mmap: ::c_long = 9; -pub const SYS_mprotect: ::c_long = 10; -pub const SYS_munmap: ::c_long = 11; -pub const SYS_brk: ::c_long = 12; -pub const SYS_rt_sigaction: ::c_long = 13; -pub const SYS_rt_sigprocmask: ::c_long = 14; -pub const SYS_rt_sigreturn: ::c_long = 15; -pub const SYS_ioctl: ::c_long = 16; -pub const SYS_pread64: ::c_long = 17; -pub const SYS_pwrite64: ::c_long = 18; -pub const SYS_readv: ::c_long = 19; -pub const SYS_writev: ::c_long = 20; -pub const SYS_access: ::c_long = 21; -pub const SYS_pipe: ::c_long = 22; -pub const SYS_select: ::c_long = 23; -pub const SYS_sched_yield: ::c_long = 24; -pub const SYS_mremap: ::c_long = 25; -pub const SYS_msync: ::c_long = 26; -pub const SYS_mincore: ::c_long = 27; -pub const SYS_madvise: ::c_long = 28; -pub const SYS_shmget: ::c_long = 29; -pub const SYS_shmat: ::c_long = 30; -pub const SYS_shmctl: ::c_long = 31; -pub const SYS_dup: ::c_long = 32; -pub const SYS_dup2: ::c_long = 33; -pub const SYS_pause: ::c_long = 34; -pub const SYS_nanosleep: ::c_long = 35; -pub const SYS_getitimer: ::c_long = 36; -pub const SYS_alarm: ::c_long = 37; -pub const SYS_setitimer: ::c_long = 38; -pub const SYS_getpid: ::c_long = 39; -pub const SYS_sendfile: ::c_long = 40; -pub const SYS_socket: ::c_long = 41; -pub const SYS_connect: ::c_long = 42; -pub const SYS_accept: ::c_long = 43; -pub const SYS_sendto: ::c_long = 44; -pub const SYS_recvfrom: ::c_long = 45; -pub const SYS_sendmsg: ::c_long = 46; -pub const SYS_recvmsg: ::c_long = 47; -pub const SYS_shutdown: ::c_long = 48; -pub const SYS_bind: ::c_long = 49; -pub const SYS_listen: ::c_long = 50; -pub const SYS_getsockname: ::c_long = 51; -pub const SYS_getpeername: ::c_long = 52; -pub const SYS_socketpair: ::c_long = 53; -pub const SYS_setsockopt: ::c_long = 54; -pub const SYS_getsockopt: ::c_long = 55; -pub const SYS_clone: ::c_long = 56; -pub const SYS_fork: ::c_long = 57; -pub const SYS_vfork: ::c_long = 58; -pub const SYS_execve: ::c_long = 59; -pub const SYS_exit: ::c_long = 60; -pub const SYS_wait4: ::c_long = 61; -pub const SYS_kill: ::c_long = 62; -pub const SYS_uname: ::c_long = 63; -pub const SYS_semget: ::c_long = 64; -pub const SYS_semop: ::c_long = 65; -pub const SYS_semctl: ::c_long = 66; -pub const SYS_shmdt: ::c_long = 67; -pub const SYS_msgget: ::c_long = 68; -pub const SYS_msgsnd: ::c_long = 69; -pub const SYS_msgrcv: ::c_long = 70; -pub const SYS_msgctl: ::c_long = 71; -pub const SYS_fcntl: ::c_long = 72; -pub const SYS_flock: ::c_long = 73; -pub const SYS_fsync: ::c_long = 74; -pub const SYS_fdatasync: ::c_long = 75; -pub const SYS_truncate: ::c_long = 76; -pub const SYS_ftruncate: ::c_long = 77; -pub const SYS_getdents: ::c_long = 78; -pub const SYS_getcwd: ::c_long = 79; -pub const SYS_chdir: ::c_long = 80; -pub const SYS_fchdir: ::c_long = 81; -pub const SYS_rename: ::c_long = 82; -pub const SYS_mkdir: ::c_long = 83; -pub const SYS_rmdir: ::c_long = 84; -pub const SYS_creat: ::c_long = 85; -pub const SYS_link: ::c_long = 86; -pub const SYS_unlink: ::c_long = 87; -pub const SYS_symlink: ::c_long = 88; -pub const SYS_readlink: ::c_long = 89; -pub const SYS_chmod: ::c_long = 90; -pub const SYS_fchmod: ::c_long = 91; -pub const SYS_chown: ::c_long = 92; -pub const SYS_fchown: ::c_long = 93; -pub const SYS_lchown: ::c_long = 94; -pub const SYS_umask: ::c_long = 95; -pub const SYS_gettimeofday: ::c_long = 96; -pub const SYS_getrlimit: ::c_long = 97; -pub const SYS_getrusage: ::c_long = 98; -pub const SYS_sysinfo: ::c_long = 99; -pub const SYS_times: ::c_long = 100; -pub const SYS_ptrace: ::c_long = 101; -pub const SYS_getuid: ::c_long = 102; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_getgid: ::c_long = 104; -pub const SYS_setuid: ::c_long = 105; -pub const SYS_setgid: ::c_long = 106; -pub const SYS_geteuid: ::c_long = 107; -pub const SYS_getegid: ::c_long = 108; -pub const SYS_setpgid: ::c_long = 109; -pub const SYS_getppid: ::c_long = 110; -pub const SYS_getpgrp: ::c_long = 111; -pub const SYS_setsid: ::c_long = 112; -pub const SYS_setreuid: ::c_long = 113; -pub const SYS_setregid: ::c_long = 114; -pub const SYS_getgroups: ::c_long = 115; -pub const SYS_setgroups: ::c_long = 116; -pub const SYS_setresuid: ::c_long = 117; -pub const SYS_getresuid: ::c_long = 118; -pub const SYS_setresgid: ::c_long = 119; -pub const SYS_getresgid: ::c_long = 120; -pub const SYS_getpgid: ::c_long = 121; -pub const SYS_setfsuid: ::c_long = 122; -pub const SYS_setfsgid: ::c_long = 123; -pub const SYS_getsid: ::c_long = 124; -pub const SYS_capget: ::c_long = 125; -pub const SYS_capset: ::c_long = 126; -pub const SYS_rt_sigpending: ::c_long = 127; -pub const SYS_rt_sigtimedwait: ::c_long = 128; -pub const SYS_rt_sigqueueinfo: ::c_long = 129; -pub const SYS_rt_sigsuspend: ::c_long = 130; -pub const SYS_sigaltstack: ::c_long = 131; -pub const SYS_utime: ::c_long = 132; -pub const SYS_mknod: ::c_long = 133; -pub const SYS_uselib: ::c_long = 134; -pub const SYS_personality: ::c_long = 135; -pub const SYS_ustat: ::c_long = 136; -pub const SYS_statfs: ::c_long = 137; -pub const SYS_fstatfs: ::c_long = 138; -pub const SYS_sysfs: ::c_long = 139; -pub const SYS_getpriority: ::c_long = 140; -pub const SYS_setpriority: ::c_long = 141; -pub const SYS_sched_setparam: ::c_long = 142; -pub const SYS_sched_getparam: ::c_long = 143; -pub const SYS_sched_setscheduler: ::c_long = 144; -pub const SYS_sched_getscheduler: ::c_long = 145; -pub const SYS_sched_get_priority_max: ::c_long = 146; -pub const SYS_sched_get_priority_min: ::c_long = 147; -pub const SYS_sched_rr_get_interval: ::c_long = 148; -pub const SYS_mlock: ::c_long = 149; -pub const SYS_munlock: ::c_long = 150; -pub const SYS_mlockall: ::c_long = 151; -pub const SYS_munlockall: ::c_long = 152; -pub const SYS_vhangup: ::c_long = 153; -pub const SYS_modify_ldt: ::c_long = 154; -pub const SYS_pivot_root: ::c_long = 155; -pub const SYS__sysctl: ::c_long = 156; -pub const SYS_prctl: ::c_long = 157; -pub const SYS_arch_prctl: ::c_long = 158; -pub const SYS_adjtimex: ::c_long = 159; -pub const SYS_setrlimit: ::c_long = 160; -pub const SYS_chroot: ::c_long = 161; -pub const SYS_sync: ::c_long = 162; -pub const SYS_acct: ::c_long = 163; -pub const SYS_settimeofday: ::c_long = 164; -pub const SYS_mount: ::c_long = 165; -pub const SYS_umount2: ::c_long = 166; -pub const SYS_swapon: ::c_long = 167; -pub const SYS_swapoff: ::c_long = 168; -pub const SYS_reboot: ::c_long = 169; -pub const SYS_sethostname: ::c_long = 170; -pub const SYS_setdomainname: ::c_long = 171; -pub const SYS_iopl: ::c_long = 172; -pub const SYS_ioperm: ::c_long = 173; -pub const SYS_create_module: ::c_long = 174; -pub const SYS_init_module: ::c_long = 175; -pub const SYS_delete_module: ::c_long = 176; -pub const SYS_get_kernel_syms: ::c_long = 177; -pub const SYS_query_module: ::c_long = 178; -pub const SYS_quotactl: ::c_long = 179; -pub const SYS_nfsservctl: ::c_long = 180; -pub const SYS_getpmsg: ::c_long = 181; -pub const SYS_putpmsg: ::c_long = 182; -pub const SYS_afs_syscall: ::c_long = 183; -pub const SYS_tuxcall: ::c_long = 184; -pub const SYS_security: ::c_long = 185; -pub const SYS_gettid: ::c_long = 186; -pub const SYS_readahead: ::c_long = 187; -pub const SYS_setxattr: ::c_long = 188; -pub const SYS_lsetxattr: ::c_long = 189; -pub const SYS_fsetxattr: ::c_long = 190; -pub const SYS_getxattr: ::c_long = 191; -pub const SYS_lgetxattr: ::c_long = 192; -pub const SYS_fgetxattr: ::c_long = 193; -pub const SYS_listxattr: ::c_long = 194; -pub const SYS_llistxattr: ::c_long = 195; -pub const SYS_flistxattr: ::c_long = 196; -pub const SYS_removexattr: ::c_long = 197; -pub const SYS_lremovexattr: ::c_long = 198; -pub const SYS_fremovexattr: ::c_long = 199; -pub const SYS_tkill: ::c_long = 200; -pub const SYS_time: ::c_long = 201; -pub const SYS_futex: ::c_long = 202; -pub const SYS_sched_setaffinity: ::c_long = 203; -pub const SYS_sched_getaffinity: ::c_long = 204; -pub const SYS_set_thread_area: ::c_long = 205; -pub const SYS_io_setup: ::c_long = 206; -pub const SYS_io_destroy: ::c_long = 207; -pub const SYS_io_getevents: ::c_long = 208; -pub const SYS_io_submit: ::c_long = 209; -pub const SYS_io_cancel: ::c_long = 210; -pub const SYS_get_thread_area: ::c_long = 211; -pub const SYS_lookup_dcookie: ::c_long = 212; -pub const SYS_epoll_create: ::c_long = 213; -pub const SYS_epoll_ctl_old: ::c_long = 214; -pub const SYS_epoll_wait_old: ::c_long = 215; -pub const SYS_remap_file_pages: ::c_long = 216; -pub const SYS_getdents64: ::c_long = 217; -pub const SYS_set_tid_address: ::c_long = 218; -pub const SYS_restart_syscall: ::c_long = 219; -pub const SYS_semtimedop: ::c_long = 220; -pub const SYS_fadvise64: ::c_long = 221; -pub const SYS_timer_create: ::c_long = 222; -pub const SYS_timer_settime: ::c_long = 223; -pub const SYS_timer_gettime: ::c_long = 224; -pub const SYS_timer_getoverrun: ::c_long = 225; -pub const SYS_timer_delete: ::c_long = 226; -pub const SYS_clock_settime: ::c_long = 227; -pub const SYS_clock_gettime: ::c_long = 228; -pub const SYS_clock_getres: ::c_long = 229; -pub const SYS_clock_nanosleep: ::c_long = 230; -pub const SYS_exit_group: ::c_long = 231; -pub const SYS_epoll_wait: ::c_long = 232; -pub const SYS_epoll_ctl: ::c_long = 233; -pub const SYS_tgkill: ::c_long = 234; -pub const SYS_utimes: ::c_long = 235; -pub const SYS_vserver: ::c_long = 236; -pub const SYS_mbind: ::c_long = 237; -pub const SYS_set_mempolicy: ::c_long = 238; -pub const SYS_get_mempolicy: ::c_long = 239; -pub const SYS_mq_open: ::c_long = 240; -pub const SYS_mq_unlink: ::c_long = 241; -pub const SYS_mq_timedsend: ::c_long = 242; -pub const SYS_mq_timedreceive: ::c_long = 243; -pub const SYS_mq_notify: ::c_long = 244; -pub const SYS_mq_getsetattr: ::c_long = 245; -pub const SYS_kexec_load: ::c_long = 246; -pub const SYS_waitid: ::c_long = 247; -pub const SYS_add_key: ::c_long = 248; -pub const SYS_request_key: ::c_long = 249; -pub const SYS_keyctl: ::c_long = 250; -pub const SYS_ioprio_set: ::c_long = 251; -pub const SYS_ioprio_get: ::c_long = 252; -pub const SYS_inotify_init: ::c_long = 253; -pub const SYS_inotify_add_watch: ::c_long = 254; -pub const SYS_inotify_rm_watch: ::c_long = 255; -pub const SYS_migrate_pages: ::c_long = 256; -pub const SYS_openat: ::c_long = 257; -pub const SYS_mkdirat: ::c_long = 258; -pub const SYS_mknodat: ::c_long = 259; -pub const SYS_fchownat: ::c_long = 260; -pub const SYS_futimesat: ::c_long = 261; -pub const SYS_newfstatat: ::c_long = 262; -pub const SYS_unlinkat: ::c_long = 263; -pub const SYS_renameat: ::c_long = 264; -pub const SYS_linkat: ::c_long = 265; -pub const SYS_symlinkat: ::c_long = 266; -pub const SYS_readlinkat: ::c_long = 267; -pub const SYS_fchmodat: ::c_long = 268; -pub const SYS_faccessat: ::c_long = 269; -pub const SYS_pselect6: ::c_long = 270; -pub const SYS_ppoll: ::c_long = 271; -pub const SYS_unshare: ::c_long = 272; -pub const SYS_set_robust_list: ::c_long = 273; -pub const SYS_get_robust_list: ::c_long = 274; -pub const SYS_splice: ::c_long = 275; -pub const SYS_tee: ::c_long = 276; -pub const SYS_sync_file_range: ::c_long = 277; -pub const SYS_vmsplice: ::c_long = 278; -pub const SYS_move_pages: ::c_long = 279; -pub const SYS_utimensat: ::c_long = 280; -pub const SYS_epoll_pwait: ::c_long = 281; -pub const SYS_signalfd: ::c_long = 282; -pub const SYS_timerfd_create: ::c_long = 283; -pub const SYS_eventfd: ::c_long = 284; -pub const SYS_fallocate: ::c_long = 285; -pub const SYS_timerfd_settime: ::c_long = 286; -pub const SYS_timerfd_gettime: ::c_long = 287; -pub const SYS_accept4: ::c_long = 288; -pub const SYS_signalfd4: ::c_long = 289; -pub const SYS_eventfd2: ::c_long = 290; -pub const SYS_epoll_create1: ::c_long = 291; -pub const SYS_dup3: ::c_long = 292; -pub const SYS_pipe2: ::c_long = 293; -pub const SYS_inotify_init1: ::c_long = 294; -pub const SYS_preadv: ::c_long = 295; -pub const SYS_pwritev: ::c_long = 296; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 297; -pub const SYS_perf_event_open: ::c_long = 298; -pub const SYS_recvmmsg: ::c_long = 299; -pub const SYS_fanotify_init: ::c_long = 300; -pub const SYS_fanotify_mark: ::c_long = 301; -pub const SYS_prlimit64: ::c_long = 302; -pub const SYS_name_to_handle_at: ::c_long = 303; -pub const SYS_open_by_handle_at: ::c_long = 304; -pub const SYS_clock_adjtime: ::c_long = 305; -pub const SYS_syncfs: ::c_long = 306; -pub const SYS_sendmmsg: ::c_long = 307; -pub const SYS_setns: ::c_long = 308; -pub const SYS_getcpu: ::c_long = 309; -pub const SYS_process_vm_readv: ::c_long = 310; -pub const SYS_process_vm_writev: ::c_long = 311; -pub const SYS_kcmp: ::c_long = 312; -pub const SYS_finit_module: ::c_long = 313; -pub const SYS_sched_setattr: ::c_long = 314; -pub const SYS_sched_getattr: ::c_long = 315; -pub const SYS_renameat2: ::c_long = 316; -pub const SYS_seccomp: ::c_long = 317; -pub const SYS_getrandom: ::c_long = 318; -pub const SYS_memfd_create: ::c_long = 319; -pub const SYS_kexec_file_load: ::c_long = 320; -pub const SYS_bpf: ::c_long = 321; -pub const SYS_execveat: ::c_long = 322; -pub const SYS_userfaultfd: ::c_long = 323; -pub const SYS_membarrier: ::c_long = 324; -pub const SYS_mlock2: ::c_long = 325; -pub const SYS_copy_file_range: ::c_long = 326; -pub const SYS_preadv2: ::c_long = 327; -pub const SYS_pwritev2: ::c_long = 328; -// FIXME syscalls 329-331 have been added in musl 1.16 -// See discussion https://github.com/rust-lang/libc/pull/699 - -// offsets in user_regs_structs, from sys/reg.h -pub const R15: ::c_int = 0; -pub const R14: ::c_int = 1; -pub const R13: ::c_int = 2; -pub const R12: ::c_int = 3; -pub const RBP: ::c_int = 4; -pub const RBX: ::c_int = 5; -pub const R11: ::c_int = 6; -pub const R10: ::c_int = 7; -pub const R9: ::c_int = 8; -pub const R8: ::c_int = 9; -pub const RAX: ::c_int = 10; -pub const RCX: ::c_int = 11; -pub const RDX: ::c_int = 12; -pub const RSI: ::c_int = 13; -pub const RDI: ::c_int = 14; -pub const ORIG_RAX: ::c_int = 15; -pub const RIP: ::c_int = 16; -pub const CS: ::c_int = 17; -pub const EFLAGS: ::c_int = 18; -pub const RSP: ::c_int = 19; -pub const SS: ::c_int = 20; -pub const FS_BASE: ::c_int = 21; -pub const GS_BASE: ::c_int = 22; -pub const DS: ::c_int = 23; -pub const ES: ::c_int = 24; -pub const FS: ::c_int = 25; -pub const GS: ::c_int = 26; - -pub const MAP_32BIT: ::c_int = 0x0040; - -pub const SIGSTKSZ: ::size_t = 8192; -pub const MINSIGSTKSZ: ::size_t = 2048; - -#[doc(hidden)] -pub const AF_MAX: ::c_int = 42; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/lib.rs cargo-0.26.0/vendor/libc-0.2.36/src/lib.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,301 +0,0 @@ -// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Crate docs - -#![allow(bad_style, overflowing_literals, improper_ctypes)] -#![crate_type = "rlib"] -#![crate_name = "libc"] -#![cfg_attr(dox, feature(no_core, lang_items))] -#![cfg_attr(dox, no_core)] -#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", - html_favicon_url = "https://doc.rust-lang.org/favicon.ico")] - -#![cfg_attr(all(target_os = "linux", target_arch = "x86_64"), doc( - html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-linux-gnu" -))] -#![cfg_attr(all(target_os = "linux", target_arch = "x86"), doc( - html_root_url = "https://doc.rust-lang.org/libc/i686-unknown-linux-gnu" -))] -#![cfg_attr(all(target_os = "linux", target_arch = "arm"), doc( - html_root_url = "https://doc.rust-lang.org/libc/arm-unknown-linux-gnueabihf" -))] -#![cfg_attr(all(target_os = "linux", target_arch = "mips"), doc( - html_root_url = "https://doc.rust-lang.org/libc/mips-unknown-linux-gnu" -))] -#![cfg_attr(all(target_os = "linux", target_arch = "aarch64"), doc( - html_root_url = "https://doc.rust-lang.org/libc/aarch64-unknown-linux-gnu" -))] -#![cfg_attr(all(target_os = "linux", target_env = "musl"), doc( - html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-linux-musl" -))] -#![cfg_attr(all(target_os = "macos", target_arch = "x86_64"), doc( - html_root_url = "https://doc.rust-lang.org/libc/x86_64-apple-darwin" -))] -#![cfg_attr(all(target_os = "macos", target_arch = "x86"), doc( - html_root_url = "https://doc.rust-lang.org/libc/i686-apple-darwin" -))] -#![cfg_attr(all(windows, target_arch = "x86_64", target_env = "gnu"), doc( - html_root_url = "https://doc.rust-lang.org/libc/x86_64-pc-windows-gnu" -))] -#![cfg_attr(all(windows, target_arch = "x86", target_env = "gnu"), doc( - html_root_url = "https://doc.rust-lang.org/libc/i686-pc-windows-gnu" -))] -#![cfg_attr(all(windows, target_arch = "x86_64", target_env = "msvc"), doc( - html_root_url = "https://doc.rust-lang.org/libc/x86_64-pc-windows-msvc" -))] -#![cfg_attr(all(windows, target_arch = "x86", target_env = "msvc"), doc( - html_root_url = "https://doc.rust-lang.org/libc/i686-pc-windows-msvc" -))] -#![cfg_attr(target_os = "android", doc( - html_root_url = "https://doc.rust-lang.org/libc/arm-linux-androideabi" -))] -#![cfg_attr(target_os = "freebsd", doc( - html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-freebsd" -))] -#![cfg_attr(target_os = "openbsd", doc( - html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-openbsd" -))] -#![cfg_attr(target_os = "bitrig", doc( - html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-bitrig" -))] -#![cfg_attr(target_os = "netbsd", doc( - html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-netbsd" -))] -#![cfg_attr(target_os = "dragonfly", doc( - html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-dragonfly" -))] -#![cfg_attr(all(target_os = "emscripten", target_arch = "asmjs"), doc( - html_root_url = "https://doc.rust-lang.org/libc/asmjs-unknown-emscripten" -))] -#![cfg_attr(all(target_os = "emscripten", target_arch = "wasm32"), doc( - html_root_url = "https://doc.rust-lang.org/libc/wasm32-unknown-emscripten" -))] -#![cfg_attr(all(target_os = "linux", target_arch = "xparc64"), doc( - html_root_url = "https://doc.rust-lang.org/libc/sparc64-unknown-linux-gnu" -))] - -// Attributes needed when building as part of the standard library -#![cfg_attr(feature = "stdbuild", feature(no_std, staged_api, custom_attribute, cfg_target_vendor))] -#![cfg_attr(feature = "stdbuild", feature(link_cfg))] -#![cfg_attr(feature = "stdbuild", no_std)] -#![cfg_attr(feature = "stdbuild", staged_api)] -#![cfg_attr(feature = "stdbuild", allow(warnings))] -#![cfg_attr(feature = "stdbuild", unstable(feature = "libc", - reason = "use `libc` from crates.io", - issue = "27783"))] - -#![cfg_attr(not(feature = "use_std"), no_std)] - -#[cfg(all(not(dox), feature = "use_std"))] -extern crate std as core; - -#[macro_use] mod macros; -mod dox; - -cfg_if! { - if #[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))] { - // empty ... - } else { - - // Use repr(u8) as LLVM expects `void*` to be the same as `i8*` to help enable - // more optimization opportunities around it recognizing things like - // malloc/free. - #[repr(u8)] - pub enum c_void { - // Two dummy variants so the #[repr] attribute can be used. - #[doc(hidden)] - __variant1, - #[doc(hidden)] - __variant2, - } - - pub type int8_t = i8; - pub type int16_t = i16; - pub type int32_t = i32; - pub type int64_t = i64; - pub type uint8_t = u8; - pub type uint16_t = u16; - pub type uint32_t = u32; - pub type uint64_t = u64; - - pub type c_schar = i8; - pub type c_uchar = u8; - pub type c_short = i16; - pub type c_ushort = u16; - pub type c_int = i32; - pub type c_uint = u32; - pub type c_float = f32; - pub type c_double = f64; - pub type c_longlong = i64; - pub type c_ulonglong = u64; - pub type intmax_t = i64; - pub type uintmax_t = u64; - - pub type size_t = usize; - pub type ptrdiff_t = isize; - pub type intptr_t = isize; - pub type uintptr_t = usize; - pub type ssize_t = isize; - - pub enum FILE {} - pub enum fpos_t {} // TODO: fill this out with a struct - - extern { - pub fn isalnum(c: c_int) -> c_int; - pub fn isalpha(c: c_int) -> c_int; - pub fn iscntrl(c: c_int) -> c_int; - pub fn isdigit(c: c_int) -> c_int; - pub fn isgraph(c: c_int) -> c_int; - pub fn islower(c: c_int) -> c_int; - pub fn isprint(c: c_int) -> c_int; - pub fn ispunct(c: c_int) -> c_int; - pub fn isspace(c: c_int) -> c_int; - pub fn isupper(c: c_int) -> c_int; - pub fn isxdigit(c: c_int) -> c_int; - pub fn tolower(c: c_int) -> c_int; - pub fn toupper(c: c_int) -> c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "fopen$UNIX2003")] - pub fn fopen(filename: *const c_char, - mode: *const c_char) -> *mut FILE; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "freopen$UNIX2003")] - pub fn freopen(filename: *const c_char, mode: *const c_char, - file: *mut FILE) -> *mut FILE; - pub fn fflush(file: *mut FILE) -> c_int; - pub fn fclose(file: *mut FILE) -> c_int; - pub fn remove(filename: *const c_char) -> c_int; - pub fn rename(oldname: *const c_char, newname: *const c_char) -> c_int; - pub fn tmpfile() -> *mut FILE; - pub fn setvbuf(stream: *mut FILE, - buffer: *mut c_char, - mode: c_int, - size: size_t) -> c_int; - pub fn setbuf(stream: *mut FILE, buf: *mut c_char); - pub fn getchar() -> c_int; - pub fn putchar(c: c_int) -> c_int; - pub fn fgetc(stream: *mut FILE) -> c_int; - pub fn fgets(buf: *mut c_char, n: c_int, stream: *mut FILE) -> *mut c_char; - pub fn fputc(c: c_int, stream: *mut FILE) -> c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "fputs$UNIX2003")] - pub fn fputs(s: *const c_char, stream: *mut FILE)-> c_int; - pub fn puts(s: *const c_char) -> c_int; - pub fn ungetc(c: c_int, stream: *mut FILE) -> c_int; - pub fn fread(ptr: *mut c_void, - size: size_t, - nobj: size_t, - stream: *mut FILE) - -> size_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "fwrite$UNIX2003")] - pub fn fwrite(ptr: *const c_void, - size: size_t, - nobj: size_t, - stream: *mut FILE) - -> size_t; - pub fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) -> c_int; - pub fn ftell(stream: *mut FILE) -> c_long; - pub fn rewind(stream: *mut FILE); - #[cfg_attr(target_os = "netbsd", link_name = "__fgetpos50")] - pub fn fgetpos(stream: *mut FILE, ptr: *mut fpos_t) -> c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__fsetpos50")] - pub fn fsetpos(stream: *mut FILE, ptr: *const fpos_t) -> c_int; - pub fn feof(stream: *mut FILE) -> c_int; - pub fn ferror(stream: *mut FILE) -> c_int; - pub fn perror(s: *const c_char); - pub fn atoi(s: *const c_char) -> c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "strtod$UNIX2003")] - pub fn strtod(s: *const c_char, endp: *mut *mut c_char) -> c_double; - pub fn strtol(s: *const c_char, - endp: *mut *mut c_char, base: c_int) -> c_long; - pub fn strtoul(s: *const c_char, endp: *mut *mut c_char, - base: c_int) -> c_ulong; - pub fn calloc(nobj: size_t, size: size_t) -> *mut c_void; - pub fn malloc(size: size_t) -> *mut c_void; - pub fn realloc(p: *mut c_void, size: size_t) -> *mut c_void; - pub fn free(p: *mut c_void); - pub fn abort() -> !; - pub fn exit(status: c_int) -> !; - pub fn _exit(status: c_int) -> !; - pub fn atexit(cb: extern fn()) -> c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "system$UNIX2003")] - pub fn system(s: *const c_char) -> c_int; - pub fn getenv(s: *const c_char) -> *mut c_char; - - pub fn strcpy(dst: *mut c_char, src: *const c_char) -> *mut c_char; - pub fn strncpy(dst: *mut c_char, src: *const c_char, n: size_t) - -> *mut c_char; - pub fn strcat(s: *mut c_char, ct: *const c_char) -> *mut c_char; - pub fn strncat(s: *mut c_char, ct: *const c_char, n: size_t) -> *mut c_char; - pub fn strcmp(cs: *const c_char, ct: *const c_char) -> c_int; - pub fn strncmp(cs: *const c_char, ct: *const c_char, n: size_t) -> c_int; - pub fn strcoll(cs: *const c_char, ct: *const c_char) -> c_int; - pub fn strchr(cs: *const c_char, c: c_int) -> *mut c_char; - pub fn strrchr(cs: *const c_char, c: c_int) -> *mut c_char; - pub fn strspn(cs: *const c_char, ct: *const c_char) -> size_t; - pub fn strcspn(cs: *const c_char, ct: *const c_char) -> size_t; - pub fn strdup(cs: *const c_char) -> *mut c_char; - pub fn strpbrk(cs: *const c_char, ct: *const c_char) -> *mut c_char; - pub fn strstr(cs: *const c_char, ct: *const c_char) -> *mut c_char; - pub fn strlen(cs: *const c_char) -> size_t; - pub fn strnlen(cs: *const c_char, maxlen: size_t) -> size_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "strerror$UNIX2003")] - pub fn strerror(n: c_int) -> *mut c_char; - pub fn strtok(s: *mut c_char, t: *const c_char) -> *mut c_char; - pub fn strxfrm(s: *mut c_char, ct: *const c_char, n: size_t) -> size_t; - pub fn wcslen(buf: *const wchar_t) -> size_t; - pub fn wcstombs(dest: *mut c_char, src: *const wchar_t, n: size_t) -> ::size_t; - - pub fn memchr(cx: *const c_void, c: c_int, n: size_t) -> *mut c_void; - pub fn memcmp(cx: *const c_void, ct: *const c_void, n: size_t) -> c_int; - pub fn memcpy(dest: *mut c_void, src: *const c_void, n: size_t) -> *mut c_void; - pub fn memmove(dest: *mut c_void, src: *const c_void, n: size_t) -> *mut c_void; - pub fn memset(dest: *mut c_void, c: c_int, n: size_t) -> *mut c_void; - } - - // These are all inline functions on android, so they end up just being entirely - // missing on that platform. - #[cfg(not(target_os = "android"))] - extern { - pub fn abs(i: c_int) -> c_int; - pub fn atof(s: *const c_char) -> c_double; - pub fn labs(i: c_long) -> c_long; - pub fn rand() -> c_int; - pub fn srand(seed: c_uint); - } - } -} - -cfg_if! { - if #[cfg(windows)] { - mod windows; - pub use windows::*; - } else if #[cfg(target_os = "redox")] { - mod redox; - pub use redox::*; - } else if #[cfg(target_os = "cloudabi")] { - mod cloudabi; - pub use cloudabi::*; - } else if #[cfg(target_os = "fuchsia")] { - mod fuchsia; - pub use fuchsia::*; - } else if #[cfg(unix)] { - mod unix; - pub use unix::*; - } else { - // Unknown target_family - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/macros.rs cargo-0.26.0/vendor/libc-0.2.36/src/macros.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/macros.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/macros.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -/// A macro for defining #[cfg] if-else statements. -/// -/// This is similar to the `if/elif` C preprocessor macro by allowing definition -/// of a cascade of `#[cfg]` cases, emitting the implementation which matches -/// first. -/// -/// This allows you to conveniently provide a long list #[cfg]'d blocks of code -/// without having to rewrite each clause multiple times. -macro_rules! cfg_if { - ($( - if #[cfg($($meta:meta),*)] { $($it:item)* } - ) else * else { - $($it2:item)* - }) => { - __cfg_if_items! { - () ; - $( ( ($($meta),*) ($($it)*) ), )* - ( () ($($it2)*) ), - } - } -} - -macro_rules! __cfg_if_items { - (($($not:meta,)*) ; ) => {}; - (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => { - __cfg_if_apply! { cfg(all(not(any($($not),*)), $($m,)*)), $($it)* } - __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* } - } -} - -macro_rules! __cfg_if_apply { - ($m:meta, $($it:item)*) => { - $(#[$m] $it)* - } -} - -macro_rules! s { - ($($(#[$attr:meta])* pub struct $i:ident { $($field:tt)* })*) => ($( - __item! { - #[repr(C)] - $(#[$attr])* - pub struct $i { $($field)* } - } - impl ::dox::Copy for $i {} - impl ::dox::Clone for $i { - fn clone(&self) -> $i { *self } - } - )*) -} - -macro_rules! f { - ($(pub fn $i:ident($($arg:ident: $argty:ty),*) -> $ret:ty { - $($body:stmt);* - })*) => ($( - #[inline] - #[cfg(not(dox))] - pub unsafe extern fn $i($($arg: $argty),*) -> $ret { - $($body);* - } - - #[cfg(dox)] - #[allow(dead_code)] - pub unsafe extern fn $i($($arg: $argty),*) -> $ret { - loop {} - } - )*) -} - -macro_rules! __item { - ($i:item) => ($i) -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/redox/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/redox/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/redox/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/redox/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,104 +0,0 @@ -pub type c_char = i8; -pub type c_long = i64; -pub type c_ulong = u64; - -pub type wchar_t = i16; - -pub type off_t = c_long; -pub type mode_t = u16; -pub type time_t = i64; -pub type pid_t = usize; -pub type gid_t = usize; -pub type uid_t = usize; - -pub type suseconds_t = i64; - -s! { - pub struct timeval { - pub tv_sec: time_t, - pub tv_usec: suseconds_t, - } - - pub struct timespec { - pub tv_sec: time_t, - pub tv_nsec: c_long, - } -} - -pub const STDIN_FILENO: ::c_int = 0; -pub const STDOUT_FILENO: ::c_int = 1; -pub const STDERR_FILENO: ::c_int = 2; - -pub const EXIT_FAILURE: ::c_int = 1; -pub const EXIT_SUCCESS: ::c_int = 0; - -pub const S_ISUID: ::c_int = 0x800; -pub const S_ISGID: ::c_int = 0x400; -pub const S_ISVTX: ::c_int = 0x200; - -pub const S_IFIFO: mode_t = 0x1000; -pub const S_IFCHR: mode_t = 0x2000; -pub const S_IFBLK: mode_t = 0x6000; -pub const S_IFDIR: mode_t = 0x4000; -pub const S_IFREG: mode_t = 0x8000; -pub const S_IFLNK: mode_t = 0xA000; -pub const S_IFSOCK: mode_t = 0xC000; -pub const S_IFMT: mode_t = 0xF000; -pub const S_IEXEC: mode_t = 0x40; -pub const S_IWRITE: mode_t = 0x80; -pub const S_IREAD: mode_t = 0x100; -pub const S_IRWXU: mode_t = 0x1C0; -pub const S_IXUSR: mode_t = 0x40; -pub const S_IWUSR: mode_t = 0x80; -pub const S_IRUSR: mode_t = 0x100; -pub const S_IRWXG: mode_t = 0x38; -pub const S_IXGRP: mode_t = 0x8; -pub const S_IWGRP: mode_t = 0x10; -pub const S_IRGRP: mode_t = 0x20; -pub const S_IRWXO: mode_t = 0x7; -pub const S_IXOTH: mode_t = 0x1; -pub const S_IWOTH: mode_t = 0x2; -pub const S_IROTH: mode_t = 0x4; - -pub const F_DUPFD: ::c_int = 0; -pub const F_GETFD: ::c_int = 1; -pub const F_SETFD: ::c_int = 2; -pub const F_GETFL: ::c_int = 3; -pub const F_SETFL: ::c_int = 4; - -pub const O_RDONLY: ::c_int = 0x0001_0000; -pub const O_WRONLY: ::c_int = 0x0002_0000; -pub const O_RDWR: ::c_int = 0x0003_0000; -pub const O_NONBLOCK: ::c_int = 0x0004_0000; -pub const O_APPEND: ::c_int = 0x0008_0000; -pub const O_SHLOCK: ::c_int = 0x0010_0000; -pub const O_EXLOCK: ::c_int = 0x0020_0000; -pub const O_ASYNC: ::c_int = 0x0040_0000; -pub const O_FSYNC: ::c_int = 0x0080_0000; -pub const O_CLOEXEC: ::c_int = 0x0100_0000; -pub const O_CREAT: ::c_int = 0x0200_0000; -pub const O_TRUNC: ::c_int = 0x0400_0000; -pub const O_EXCL: ::c_int = 0x0800_0000; -pub const O_DIRECTORY: ::c_int = 0x1000_0000; -pub const O_STAT: ::c_int = 0x2000_0000; -pub const O_SYMLINK: ::c_int = 0x4000_0000; -pub const O_NOFOLLOW: ::c_int = 0x8000_0000; -pub const O_ACCMODE: ::c_int = O_RDONLY | O_WRONLY | O_RDWR; - -extern { - pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; - pub fn read(fd: ::c_int, buf: *mut ::c_void, count: ::size_t) - -> ::ssize_t; - pub fn write(fd: ::c_int, buf: *const ::c_void, count: ::size_t) - -> ::ssize_t; - pub fn fcntl(fd: ::c_int, cmd: ::c_int, ...) -> ::c_int; - pub fn close(fd: ::c_int) -> ::c_int; -} - -#[link(name = "c")] -#[link(name = "m")] -extern {} - -pub use self::net::*; - -mod net; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/redox/net.rs cargo-0.26.0/vendor/libc-0.2.36/src/redox/net.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/redox/net.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/redox/net.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,110 +0,0 @@ -pub type in_addr_t = u32; -pub type in_port_t = u16; - -pub type socklen_t = u32; -pub type sa_family_t = u16; - -s! { - pub struct in_addr { - pub s_addr: in_addr_t, - } - - pub struct in6_addr { - pub s6_addr: [u8; 16], - __align: [u32; 0], - } - - pub struct ip_mreq { - pub imr_multiaddr: in_addr, - pub imr_interface: in_addr, - } - - pub struct ipv6_mreq { - pub ipv6mr_multiaddr: in6_addr, - pub ipv6mr_interface: ::c_uint, - } - - pub struct linger { - pub l_onoff: ::c_int, - pub l_linger: ::c_int, - } - - pub struct sockaddr { - pub sa_family: sa_family_t, - pub sa_data: [::c_char; 14], - } - - pub struct sockaddr_in { - pub sin_family: sa_family_t, - pub sin_port: ::in_port_t, - pub sin_addr: ::in_addr, - pub sin_zero: [u8; 8], - } - - pub struct sockaddr_in6 { - pub sin6_family: sa_family_t, - pub sin6_port: in_port_t, - pub sin6_flowinfo: u32, - pub sin6_addr: ::in6_addr, - pub sin6_scope_id: u32, - } - - pub struct sockaddr_storage { - pub ss_family: sa_family_t, - pub __ss_padding: [u8; 26], - } -} - -pub const AF_INET: ::c_int = 2; -pub const AF_INET6: ::c_int = 23; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; - -pub const IPPROTO_TCP: ::c_int = 6; -pub const IPPROTO_IP: ::c_int = 0; -pub const IPPROTO_IPV6: ::c_int = 41; - -pub const TCP_KEEPIDLE: ::c_int = 4; -pub const TCP_NODELAY: ::c_int = 8193; - -pub const IP_TTL: ::c_int = 8; -pub const IP_MULTICAST_LOOP: ::c_int = 9; -pub const IP_MULTICAST_TTL: ::c_int = 10; -pub const IP_ADD_MEMBERSHIP: ::c_int = 11; -pub const IP_DROP_MEMBERSHIP: ::c_int = 12; - -pub const IPV6_MULTICAST_LOOP: ::c_int = 19; -pub const IPV6_ADD_MEMBERSHIP: ::c_int = 20; -pub const IPV6_DROP_MEMBERSHIP: ::c_int = 21; -pub const IPV6_V6ONLY: ::c_int = 26; - -pub const SOL_SOCKET: ::c_int = 65535; - -pub const SO_REUSEADDR: ::c_int = 4; -pub const SO_BROADCAST: ::c_int = 6; -pub const SO_KEEPALIVE: ::c_int = 8; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_SNDTIMEO: ::c_int = 21; -pub const SO_LINGER: ::c_int = 128; -pub const SO_SNDBUF: ::c_int = 4097; -pub const SO_RCVBUF: ::c_int = 4098; -pub const SO_ERROR: ::c_int = 4105; - -extern { - pub fn socket(domain: ::c_int, ty: ::c_int, protocol: ::c_int) -> ::c_int; - pub fn bind(fd: ::c_int, addr: *const sockaddr, len: socklen_t) -> ::c_int; - pub fn connect(socket: ::c_int, address: *const sockaddr, - len: socklen_t) -> ::c_int; - pub fn listen(socket: ::c_int, backlog: ::c_int) -> ::c_int; - pub fn getsockname(socket: ::c_int, address: *mut sockaddr, - address_len: *mut socklen_t) -> ::c_int; - pub fn getsockopt(sockfd: ::c_int, - level: ::c_int, - optname: ::c_int, - optval: *mut ::c_void, - optlen: *mut ::socklen_t) -> ::c_int; - pub fn setsockopt(socket: ::c_int, level: ::c_int, name: ::c_int, - value: *const ::c_void, - option_len: socklen_t) -> ::c_int; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/apple/b32.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/apple/b32.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/apple/b32.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/apple/b32.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -//! 32-bit specific Apple (ios/darwin) definitions - -pub type c_long = i32; -pub type c_ulong = u32; -pub type boolean_t = ::c_int; - -s! { - pub struct pthread_attr_t { - __sig: c_long, - __opaque: [::c_char; 36] - } - - pub struct if_data { - pub ifi_type: ::c_uchar, - pub ifi_typelen: ::c_uchar, - pub ifi_physical: ::c_uchar, - pub ifi_addrlen: ::c_uchar, - pub ifi_hdrlen: ::c_uchar, - pub ifi_recvquota: ::c_uchar, - pub ifi_xmitquota: ::c_uchar, - pub ifi_unused1: ::c_uchar, - pub ifi_mtu: u32, - pub ifi_metric: u32, - pub ifi_baudrate: u32, - pub ifi_ipackets: u32, - pub ifi_ierrors: u32, - pub ifi_opackets: u32, - pub ifi_oerrors: u32, - pub ifi_collisions: u32, - pub ifi_ibytes: u32, - pub ifi_obytes: u32, - pub ifi_imcasts: u32, - pub ifi_omcasts: u32, - pub ifi_iqdrops: u32, - pub ifi_noproto: u32, - pub ifi_recvtiming: u32, - pub ifi_xmittiming: u32, - pub ifi_lastchange: ::timeval, - pub ifi_unused2: u32, - pub ifi_hwassist: u32, - pub ifi_reserved1: u32, - pub ifi_reserved2: u32, - } - - pub struct bpf_hdr { - pub bh_tstamp: ::timeval, - pub bh_caplen: ::uint32_t, - pub bh_datalen: ::uint32_t, - pub bh_hdrlen: ::c_ushort, - } -} - -pub const __PTHREAD_MUTEX_SIZE__: usize = 40; -pub const __PTHREAD_COND_SIZE__: usize = 24; -pub const __PTHREAD_CONDATTR_SIZE__: usize = 4; -pub const __PTHREAD_RWLOCK_SIZE__: usize = 124; -pub const __PTHREAD_RWLOCKATTR_SIZE__: usize = 12; - -pub const TIOCTIMESTAMP: ::c_ulong = 0x40087459; -pub const TIOCDCDTIMESTAMP: ::c_ulong = 0x40087458; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/apple/b64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/apple/b64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/apple/b64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/apple/b64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,67 +0,0 @@ -//! 64-bit specific Apple (ios/darwin) definitions - -pub type c_long = i64; -pub type c_ulong = u64; -pub type boolean_t = ::c_uint; - -s! { - pub struct pthread_attr_t { - __sig: c_long, - __opaque: [::c_char; 56] - } - - pub struct timeval32 { - pub tv_sec: i32, - pub tv_usec: i32, - } - - pub struct if_data { - pub ifi_type: ::c_uchar, - pub ifi_typelen: ::c_uchar, - pub ifi_physical: ::c_uchar, - pub ifi_addrlen: ::c_uchar, - pub ifi_hdrlen: ::c_uchar, - pub ifi_recvquota: ::c_uchar, - pub ifi_xmitquota: ::c_uchar, - pub ifi_unused1: ::c_uchar, - pub ifi_mtu: u32, - pub ifi_metric: u32, - pub ifi_baudrate: u32, - pub ifi_ipackets: u32, - pub ifi_ierrors: u32, - pub ifi_opackets: u32, - pub ifi_oerrors: u32, - pub ifi_collisions: u32, - pub ifi_ibytes: u32, - pub ifi_obytes: u32, - pub ifi_imcasts: u32, - pub ifi_omcasts: u32, - pub ifi_iqdrops: u32, - pub ifi_noproto: u32, - pub ifi_recvtiming: u32, - pub ifi_xmittiming: u32, - pub ifi_lastchange: timeval32, - pub ifi_unused2: u32, - pub ifi_hwassist: u32, - pub ifi_reserved1: u32, - pub ifi_reserved2: u32, - } - - pub struct bpf_hdr { - pub bh_tstamp: ::timeval32, - pub bh_caplen: ::uint32_t, - pub bh_datalen: ::uint32_t, - pub bh_hdrlen: ::c_ushort, - } -} - -pub const __PTHREAD_MUTEX_SIZE__: usize = 56; -pub const __PTHREAD_COND_SIZE__: usize = 40; -pub const __PTHREAD_CONDATTR_SIZE__: usize = 8; -pub const __PTHREAD_RWLOCK_SIZE__: usize = 192; -pub const __PTHREAD_RWLOCKATTR_SIZE__: usize = 16; - -pub const TIOCTIMESTAMP: ::c_ulong = 0x40107459; -pub const TIOCDCDTIMESTAMP: ::c_ulong = 0x40107458; - -pub const FIONREAD: ::c_ulong = 0x4004667f; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/apple/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/apple/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/apple/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/apple/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2397 +0,0 @@ -//! Apple (ios/darwin)-specific definitions -//! -//! This covers *-apple-* triples currently - -pub type c_char = i8; -pub type clock_t = c_ulong; -pub type time_t = c_long; -pub type suseconds_t = i32; -pub type dev_t = i32; -pub type ino_t = u64; -pub type mode_t = u16; -pub type nlink_t = u16; -pub type blksize_t = i32; -pub type rlim_t = u64; -pub type mach_timebase_info_data_t = mach_timebase_info; -pub type pthread_key_t = c_ulong; -pub type sigset_t = u32; -pub type clockid_t = ::c_uint; -pub type fsblkcnt_t = ::c_uint; -pub type fsfilcnt_t = ::c_uint; -pub type speed_t = ::c_ulong; -pub type tcflag_t = ::c_ulong; -pub type nl_item = ::c_int; -pub type id_t = ::c_uint; -pub type sem_t = ::c_int; -pub type idtype_t = ::c_uint; -pub type integer_t = ::c_int; -pub type cpu_type_t = integer_t; -pub type cpu_subtype_t = integer_t; -pub type vm_prot_t = ::c_int; - -pub enum timezone {} - -s! { - pub struct aiocb { - pub aio_fildes: ::c_int, - pub aio_offset: ::off_t, - pub aio_buf: *mut ::c_void, - pub aio_nbytes: ::size_t, - pub aio_reqprio: ::c_int, - pub aio_sigevent: sigevent, - pub aio_lio_opcode: ::c_int - } - - pub struct utmpx { - pub ut_user: [::c_char; _UTX_USERSIZE], - pub ut_id: [::c_char; _UTX_IDSIZE], - pub ut_line: [::c_char; _UTX_LINESIZE], - pub ut_pid: ::pid_t, - pub ut_type: ::c_short, - pub ut_tv: ::timeval, - pub ut_host: [::c_char; _UTX_HOSTSIZE], - ut_pad: [::uint32_t; 16], - } - - pub struct glob_t { - pub gl_pathc: ::size_t, - __unused1: ::c_int, - pub gl_offs: ::size_t, - __unused2: ::c_int, - pub gl_pathv: *mut *mut ::c_char, - - __unused3: *mut ::c_void, - - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - __unused6: *mut ::c_void, - __unused7: *mut ::c_void, - __unused8: *mut ::c_void, - } - - pub struct sockaddr_storage { - pub ss_len: u8, - pub ss_family: ::sa_family_t, - __ss_pad1: [u8; 6], - __ss_align: i64, - __ss_pad2: [u8; 112], - } - - pub struct addrinfo { - pub ai_flags: ::c_int, - pub ai_family: ::c_int, - pub ai_socktype: ::c_int, - pub ai_protocol: ::c_int, - pub ai_addrlen: ::socklen_t, - pub ai_canonname: *mut ::c_char, - pub ai_addr: *mut ::sockaddr, - pub ai_next: *mut addrinfo, - } - - pub struct mach_timebase_info { - pub numer: u32, - pub denom: u32, - } - - pub struct stat { - pub st_dev: dev_t, - pub st_mode: mode_t, - pub st_nlink: nlink_t, - pub st_ino: ino_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: dev_t, - pub st_atime: time_t, - pub st_atime_nsec: c_long, - pub st_mtime: time_t, - pub st_mtime_nsec: c_long, - pub st_ctime: time_t, - pub st_ctime_nsec: c_long, - pub st_birthtime: time_t, - pub st_birthtime_nsec: c_long, - pub st_size: ::off_t, - pub st_blocks: ::blkcnt_t, - pub st_blksize: blksize_t, - pub st_flags: ::uint32_t, - pub st_gen: ::uint32_t, - pub st_lspare: ::int32_t, - pub st_qspare: [::int64_t; 2], - } - - pub struct dirent { - pub d_ino: u64, - pub d_seekoff: u64, - pub d_reclen: u16, - pub d_namlen: u16, - pub d_type: u8, - pub d_name: [::c_char; 1024], - } - - pub struct pthread_mutex_t { - __sig: ::c_long, - __opaque: [u8; __PTHREAD_MUTEX_SIZE__], - } - - pub struct pthread_mutexattr_t { - __sig: ::c_long, - __opaque: [u8; 8], - } - - pub struct pthread_cond_t { - __sig: ::c_long, - __opaque: [u8; __PTHREAD_COND_SIZE__], - } - - pub struct pthread_condattr_t { - __sig: ::c_long, - __opaque: [u8; __PTHREAD_CONDATTR_SIZE__], - } - - pub struct pthread_rwlock_t { - __sig: ::c_long, - __opaque: [u8; __PTHREAD_RWLOCK_SIZE__], - } - - pub struct pthread_rwlockattr_t { - __sig: ::c_long, - __opaque: [u8; __PTHREAD_RWLOCKATTR_SIZE__], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_errno: ::c_int, - pub si_code: ::c_int, - pub si_pid: ::pid_t, - pub si_uid: ::uid_t, - pub si_status: ::c_int, - pub si_addr: *mut ::c_void, - _pad: [usize; 9], - } - - pub struct sigaction { - pub sa_sigaction: ::sighandler_t, - pub sa_mask: sigset_t, - pub sa_flags: ::c_int, - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_size: ::size_t, - pub ss_flags: ::c_int, - } - - pub struct fstore_t { - pub fst_flags: ::c_uint, - pub fst_posmode: ::c_int, - pub fst_offset: ::off_t, - pub fst_length: ::off_t, - pub fst_bytesalloc: ::off_t, - } - - pub struct radvisory { - pub ra_offset: ::off_t, - pub ra_count: ::c_int, - } - - pub struct statvfs { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_favail: ::fsfilcnt_t, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - } - - pub struct Dl_info { - pub dli_fname: *const ::c_char, - pub dli_fbase: *mut ::c_void, - pub dli_sname: *const ::c_char, - pub dli_saddr: *mut ::c_void, - } - - pub struct sockaddr_in { - pub sin_len: u8, - pub sin_family: ::sa_family_t, - pub sin_port: ::in_port_t, - pub sin_addr: ::in_addr, - pub sin_zero: [::c_char; 8], - } - - pub struct statfs { - pub f_bsize: ::uint32_t, - pub f_iosize: ::int32_t, - pub f_blocks: ::uint64_t, - pub f_bfree: ::uint64_t, - pub f_bavail: ::uint64_t, - pub f_files: ::uint64_t, - pub f_ffree: ::uint64_t, - pub f_fsid: ::fsid_t, - pub f_owner: ::uid_t, - pub f_type: ::uint32_t, - pub f_flags: ::uint32_t, - pub f_fssubtype: ::uint32_t, - pub f_fstypename: [::c_char; 16], - pub f_mntonname: [::c_char; 1024], - pub f_mntfromname: [::c_char; 1024], - pub f_reserved: [::uint32_t; 8], - } - - // FIXME: this should have align 4 but it's got align 8 on 64-bit - pub struct kevent { - pub ident: ::uintptr_t, - pub filter: ::int16_t, - pub flags: ::uint16_t, - pub fflags: ::uint32_t, - pub data: ::intptr_t, - pub udata: *mut ::c_void, - } - - pub struct kevent64_s { - pub ident: ::uint64_t, - pub filter: ::int16_t, - pub flags: ::uint16_t, - pub fflags: ::uint32_t, - pub data: ::int64_t, - pub udata: ::uint64_t, - pub ext: [::uint64_t; 2], - } - - pub struct dqblk { - pub dqb_bhardlimit: ::uint64_t, - pub dqb_bsoftlimit: ::uint64_t, - pub dqb_curbytes: ::uint64_t, - pub dqb_ihardlimit: ::uint32_t, - pub dqb_isoftlimit: ::uint32_t, - pub dqb_curinodes: ::uint32_t, - pub dqb_btime: ::uint32_t, - pub dqb_itime: ::uint32_t, - pub dqb_id: ::uint32_t, - pub dqb_spare: [::uint32_t; 4], - } - - pub struct if_msghdr { - pub ifm_msglen: ::c_ushort, - pub ifm_version: ::c_uchar, - pub ifm_type: ::c_uchar, - pub ifm_addrs: ::c_int, - pub ifm_flags: ::c_int, - pub ifm_index: ::c_ushort, - pub ifm_data: if_data, - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_cc: [::cc_t; ::NCCS], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } - - pub struct flock { - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_pid: ::pid_t, - pub l_type: ::c_short, - pub l_whence: ::c_short, - } - - pub struct sf_hdtr { - pub headers: *mut ::iovec, - pub hdr_cnt: ::c_int, - pub trailers: *mut ::iovec, - pub trl_cnt: ::c_int, - } - - pub struct lconv { - pub decimal_point: *mut ::c_char, - pub thousands_sep: *mut ::c_char, - pub grouping: *mut ::c_char, - pub int_curr_symbol: *mut ::c_char, - pub currency_symbol: *mut ::c_char, - pub mon_decimal_point: *mut ::c_char, - pub mon_thousands_sep: *mut ::c_char, - pub mon_grouping: *mut ::c_char, - pub positive_sign: *mut ::c_char, - pub negative_sign: *mut ::c_char, - pub int_frac_digits: ::c_char, - pub frac_digits: ::c_char, - pub p_cs_precedes: ::c_char, - pub p_sep_by_space: ::c_char, - pub n_cs_precedes: ::c_char, - pub n_sep_by_space: ::c_char, - pub p_sign_posn: ::c_char, - pub n_sign_posn: ::c_char, - pub int_p_cs_precedes: ::c_char, - pub int_n_cs_precedes: ::c_char, - pub int_p_sep_by_space: ::c_char, - pub int_n_sep_by_space: ::c_char, - pub int_p_sign_posn: ::c_char, - pub int_n_sign_posn: ::c_char, - } - - pub struct sigevent { - pub sigev_notify: ::c_int, - pub sigev_signo: ::c_int, - pub sigev_value: ::sigval, - __unused1: *mut ::c_void, //actually a function pointer - pub sigev_notify_attributes: *mut ::pthread_attr_t - } - - pub struct proc_taskinfo { - pub pti_virtual_size: u64, - pub pti_resident_size: u64, - pub pti_total_user: u64, - pub pti_total_system: u64, - pub pti_threads_user: u64, - pub pti_threads_system: u64, - pub pti_policy: i32, - pub pti_faults: i32, - pub pti_pageins: i32, - pub pti_cow_faults: i32, - pub pti_messages_sent: i32, - pub pti_messages_received: i32, - pub pti_syscalls_mach: i32, - pub pti_syscalls_unix: i32, - pub pti_csw: i32, - pub pti_threadnum: i32, - pub pti_numrunning: i32, - pub pti_priority: i32, - } - - pub struct proc_bsdinfo { - pub pbi_flags: u32, - pub pbi_status: u32, - pub pbi_xstatus: u32, - pub pbi_pid: u32, - pub pbi_ppid: u32, - pub pbi_uid: ::uid_t, - pub pbi_gid: ::gid_t, - pub pbi_ruid: ::uid_t, - pub pbi_rgid: ::gid_t, - pub pbi_svuid: ::uid_t, - pub pbi_svgid: ::gid_t, - pub rfu_1: u32, - pub pbi_comm: [::c_char; MAXCOMLEN], - pub pbi_name: [::c_char; 32], // MAXCOMLEN * 2, but macro isn't happy... - pub pbi_nfiles: u32, - pub pbi_pgid: u32, - pub pbi_pjobc: u32, - pub e_tdev: u32, - pub e_tpgid: u32, - pub pbi_nice: i32, - pub pbi_start_tvsec: u64, - pub pbi_start_tvusec: u64, - } - - pub struct proc_taskallinfo { - pub pbsd: proc_bsdinfo, - pub ptinfo: proc_taskinfo, - } - - pub struct proc_threadinfo { - pub pth_user_time: u64, - pub pth_system_time: u64, - pub pth_cpu_usage: i32, - pub pth_policy: i32, - pub pth_run_state: i32, - pub pth_flags: i32, - pub pth_sleep_time: i32, - pub pth_curpri: i32, - pub pth_priority: i32, - pub pth_maxpriority: i32, - pub pth_name: [::c_char; MAXTHREADNAMESIZE], - } - - pub struct xsw_usage { - pub xsu_total: u64, - pub xsu_avail: u64, - pub xsu_used: u64, - pub xsu_pagesize: u32, - pub xsu_encrypted: ::boolean_t, - } - - pub struct xucred { - pub cr_version: ::c_uint, - pub cr_uid: ::uid_t, - pub cr_ngroups: ::c_short, - pub cr_groups: [::gid_t;16] - } - - pub struct mach_header { - pub magic: u32, - pub cputype: cpu_type_t, - pub cpusubtype: cpu_subtype_t, - pub filetype: u32, - pub ncmds: u32, - pub sizeofcmds: u32, - pub flags: u32, - } - - pub struct mach_header_64 { - pub magic: u32, - pub cputype: cpu_type_t, - pub cpusubtype: cpu_subtype_t, - pub filetype: u32, - pub ncmds: u32, - pub sizeofcmds: u32, - pub flags: u32, - pub reserved: u32, - } - - pub struct segment_command { - pub cmd: u32, - pub cmdsize: u32, - pub segname: [::c_char; 16], - pub vmaddr: u32, - pub vmsize: u32, - pub fileoff: u32, - pub filesize: u32, - pub maxprot: vm_prot_t, - pub initprot: vm_prot_t, - pub nsects: u32, - pub flags: u32, - } - - pub struct segment_command_64 { - pub cmd: u32, - pub cmdsize: u32, - pub segname: [::c_char; 16], - pub vmaddr: u64, - pub vmsize: u64, - pub fileoff: u64, - pub filesize: u64, - pub maxprot: vm_prot_t, - pub initprot: vm_prot_t, - pub nsects: u32, - pub flags: u32, - } - - pub struct load_command { - pub cmd: u32, - pub cmdsize: u32, - } - - pub struct sockaddr_dl { - pub sdl_len: ::c_uchar, - pub sdl_family: ::c_uchar, - pub sdl_index: ::c_ushort, - pub sdl_type: ::c_uchar, - pub sdl_nlen: ::c_uchar, - pub sdl_alen: ::c_uchar, - pub sdl_slen: ::c_uchar, - pub sdl_data: [::c_char; 12], - } - - pub struct sockaddr_inarp { - pub sin_len: ::c_uchar, - pub sin_family: ::c_uchar, - pub sin_port: ::c_ushort, - pub sin_addr: ::in_addr, - pub sin_srcaddr: ::in_addr, - pub sin_tos: ::c_ushort, - pub sin_other: ::c_ushort, - } -} - -pub const _UTX_USERSIZE: usize = 256; -pub const _UTX_LINESIZE: usize = 32; -pub const _UTX_IDSIZE: usize = 4; -pub const _UTX_HOSTSIZE: usize = 256; - -pub const EMPTY: ::c_short = 0; -pub const RUN_LVL: ::c_short = 1; -pub const BOOT_TIME: ::c_short = 2; -pub const OLD_TIME: ::c_short = 3; -pub const NEW_TIME: ::c_short = 4; -pub const INIT_PROCESS: ::c_short = 5; -pub const LOGIN_PROCESS: ::c_short = 6; -pub const USER_PROCESS: ::c_short = 7; -pub const DEAD_PROCESS: ::c_short = 8; -pub const ACCOUNTING: ::c_short = 9; -pub const SIGNATURE: ::c_short = 10; -pub const SHUTDOWN_TIME: ::c_short = 11; - -pub const LC_COLLATE_MASK: ::c_int = (1 << 0); -pub const LC_CTYPE_MASK: ::c_int = (1 << 1); -pub const LC_MESSAGES_MASK: ::c_int = (1 << 2); -pub const LC_MONETARY_MASK: ::c_int = (1 << 3); -pub const LC_NUMERIC_MASK: ::c_int = (1 << 4); -pub const LC_TIME_MASK: ::c_int = (1 << 5); -pub const LC_ALL_MASK: ::c_int = LC_COLLATE_MASK - | LC_CTYPE_MASK - | LC_MESSAGES_MASK - | LC_MONETARY_MASK - | LC_NUMERIC_MASK - | LC_TIME_MASK; - -pub const CODESET: ::nl_item = 0; -pub const D_T_FMT: ::nl_item = 1; -pub const D_FMT: ::nl_item = 2; -pub const T_FMT: ::nl_item = 3; -pub const T_FMT_AMPM: ::nl_item = 4; -pub const AM_STR: ::nl_item = 5; -pub const PM_STR: ::nl_item = 6; - -pub const DAY_1: ::nl_item = 7; -pub const DAY_2: ::nl_item = 8; -pub const DAY_3: ::nl_item = 9; -pub const DAY_4: ::nl_item = 10; -pub const DAY_5: ::nl_item = 11; -pub const DAY_6: ::nl_item = 12; -pub const DAY_7: ::nl_item = 13; - -pub const ABDAY_1: ::nl_item = 14; -pub const ABDAY_2: ::nl_item = 15; -pub const ABDAY_3: ::nl_item = 16; -pub const ABDAY_4: ::nl_item = 17; -pub const ABDAY_5: ::nl_item = 18; -pub const ABDAY_6: ::nl_item = 19; -pub const ABDAY_7: ::nl_item = 20; - -pub const MON_1: ::nl_item = 21; -pub const MON_2: ::nl_item = 22; -pub const MON_3: ::nl_item = 23; -pub const MON_4: ::nl_item = 24; -pub const MON_5: ::nl_item = 25; -pub const MON_6: ::nl_item = 26; -pub const MON_7: ::nl_item = 27; -pub const MON_8: ::nl_item = 28; -pub const MON_9: ::nl_item = 29; -pub const MON_10: ::nl_item = 30; -pub const MON_11: ::nl_item = 31; -pub const MON_12: ::nl_item = 32; - -pub const ABMON_1: ::nl_item = 33; -pub const ABMON_2: ::nl_item = 34; -pub const ABMON_3: ::nl_item = 35; -pub const ABMON_4: ::nl_item = 36; -pub const ABMON_5: ::nl_item = 37; -pub const ABMON_6: ::nl_item = 38; -pub const ABMON_7: ::nl_item = 39; -pub const ABMON_8: ::nl_item = 40; -pub const ABMON_9: ::nl_item = 41; -pub const ABMON_10: ::nl_item = 42; -pub const ABMON_11: ::nl_item = 43; -pub const ABMON_12: ::nl_item = 44; - -pub const CLOCK_REALTIME: ::clockid_t = 0; -pub const CLOCK_MONOTONIC: ::clockid_t = 6; -pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 12; -pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 16; - -pub const ERA: ::nl_item = 45; -pub const ERA_D_FMT: ::nl_item = 46; -pub const ERA_D_T_FMT: ::nl_item = 47; -pub const ERA_T_FMT: ::nl_item = 48; -pub const ALT_DIGITS: ::nl_item = 49; - -pub const RADIXCHAR: ::nl_item = 50; -pub const THOUSEP: ::nl_item = 51; - -pub const YESEXPR: ::nl_item = 52; -pub const NOEXPR: ::nl_item = 53; - -pub const YESSTR: ::nl_item = 54; -pub const NOSTR: ::nl_item = 55; - -pub const CRNCYSTR: ::nl_item = 56; - -pub const D_MD_ORDER: ::nl_item = 57; - -pub const EXIT_FAILURE: ::c_int = 1; -pub const EXIT_SUCCESS: ::c_int = 0; -pub const RAND_MAX: ::c_int = 2147483647; -pub const EOF: ::c_int = -1; -pub const SEEK_SET: ::c_int = 0; -pub const SEEK_CUR: ::c_int = 1; -pub const SEEK_END: ::c_int = 2; -pub const _IOFBF: ::c_int = 0; -pub const _IONBF: ::c_int = 2; -pub const _IOLBF: ::c_int = 1; -pub const BUFSIZ: ::c_uint = 1024; -pub const FOPEN_MAX: ::c_uint = 20; -pub const FILENAME_MAX: ::c_uint = 1024; -pub const L_tmpnam: ::c_uint = 1024; -pub const TMP_MAX: ::c_uint = 308915776; -pub const _PC_LINK_MAX: ::c_int = 1; -pub const _PC_MAX_CANON: ::c_int = 2; -pub const _PC_MAX_INPUT: ::c_int = 3; -pub const _PC_NAME_MAX: ::c_int = 4; -pub const _PC_PATH_MAX: ::c_int = 5; -pub const _PC_PIPE_BUF: ::c_int = 6; -pub const _PC_CHOWN_RESTRICTED: ::c_int = 7; -pub const _PC_NO_TRUNC: ::c_int = 8; -pub const _PC_VDISABLE: ::c_int = 9; -pub const O_DSYNC: ::c_int = 0x400000; -pub const O_NOCTTY: ::c_int = 0x20000; -pub const O_CLOEXEC: ::c_int = 0x1000000; -pub const O_DIRECTORY: ::c_int = 0x100000; -pub const S_IFIFO: mode_t = 4096; -pub const S_IFCHR: mode_t = 8192; -pub const S_IFBLK: mode_t = 24576; -pub const S_IFDIR: mode_t = 16384; -pub const S_IFREG: mode_t = 32768; -pub const S_IFLNK: mode_t = 40960; -pub const S_IFSOCK: mode_t = 49152; -pub const S_IFMT: mode_t = 61440; -pub const S_IEXEC: mode_t = 64; -pub const S_IWRITE: mode_t = 128; -pub const S_IREAD: mode_t = 256; -pub const S_IRWXU: mode_t = 448; -pub const S_IXUSR: mode_t = 64; -pub const S_IWUSR: mode_t = 128; -pub const S_IRUSR: mode_t = 256; -pub const S_IRWXG: mode_t = 56; -pub const S_IXGRP: mode_t = 8; -pub const S_IWGRP: mode_t = 16; -pub const S_IRGRP: mode_t = 32; -pub const S_IRWXO: mode_t = 7; -pub const S_IXOTH: mode_t = 1; -pub const S_IWOTH: mode_t = 2; -pub const S_IROTH: mode_t = 4; -pub const F_OK: ::c_int = 0; -pub const R_OK: ::c_int = 4; -pub const W_OK: ::c_int = 2; -pub const X_OK: ::c_int = 1; -pub const STDIN_FILENO: ::c_int = 0; -pub const STDOUT_FILENO: ::c_int = 1; -pub const STDERR_FILENO: ::c_int = 2; -pub const F_LOCK: ::c_int = 1; -pub const F_TEST: ::c_int = 3; -pub const F_TLOCK: ::c_int = 2; -pub const F_ULOCK: ::c_int = 0; -pub const F_GETLK: ::c_int = 7; -pub const F_SETLK: ::c_int = 8; -pub const F_SETLKW: ::c_int = 9; -pub const SIGHUP: ::c_int = 1; -pub const SIGINT: ::c_int = 2; -pub const SIGQUIT: ::c_int = 3; -pub const SIGILL: ::c_int = 4; -pub const SIGABRT: ::c_int = 6; -pub const SIGEMT: ::c_int = 7; -pub const SIGFPE: ::c_int = 8; -pub const SIGKILL: ::c_int = 9; -pub const SIGSEGV: ::c_int = 11; -pub const SIGPIPE: ::c_int = 13; -pub const SIGALRM: ::c_int = 14; -pub const SIGTERM: ::c_int = 15; - -pub const PROT_NONE: ::c_int = 0; -pub const PROT_READ: ::c_int = 1; -pub const PROT_WRITE: ::c_int = 2; -pub const PROT_EXEC: ::c_int = 4; - -pub const MAP_FILE: ::c_int = 0x0000; -pub const MAP_SHARED: ::c_int = 0x0001; -pub const MAP_PRIVATE: ::c_int = 0x0002; -pub const MAP_FIXED: ::c_int = 0x0010; -pub const MAP_ANON: ::c_int = 0x1000; - -pub const VM_FLAGS_FIXED: ::c_int = 0x0000; -pub const VM_FLAGS_ANYWHERE: ::c_int = 0x0001; -pub const VM_FLAGS_PURGABLE: ::c_int = 0x0002; -pub const VM_FLAGS_RANDOM_ADDR: ::c_int = 0x0008; -pub const VM_FLAGS_NO_CACHE: ::c_int = 0x0010; -pub const VM_FLAGS_RESILIENT_CODESIGN: ::c_int = 0x0020; -pub const VM_FLAGS_RESILIENT_MEDIA: ::c_int = 0x0040; -pub const VM_FLAGS_OVERWRITE: ::c_int = 0x4000; -pub const VM_FLAGS_SUPERPAGE_MASK: ::c_int = 0x70000; -pub const VM_FLAGS_RETURN_DATA_ADDR: ::c_int = 0x100000; -pub const VM_FLAGS_RETURN_4K_DATA_ADDR: ::c_int = 0x800000; -pub const VM_FLAGS_ALIAS_MASK: ::c_int = 0xFF000000; -pub const VM_FLAGS_USER_ALLOCATE: ::c_int = VM_FLAGS_FIXED | VM_FLAGS_ANYWHERE | - VM_FLAGS_PURGABLE | - VM_FLAGS_RANDOM_ADDR | - VM_FLAGS_NO_CACHE | - VM_FLAGS_OVERWRITE | - VM_FLAGS_SUPERPAGE_MASK | - VM_FLAGS_ALIAS_MASK; -pub const VM_FLAGS_USER_MAP: ::c_int = VM_FLAGS_USER_ALLOCATE | - VM_FLAGS_RETURN_4K_DATA_ADDR | - VM_FLAGS_RETURN_DATA_ADDR; -pub const VM_FLAGS_USER_REMAP: ::c_int = VM_FLAGS_FIXED | VM_FLAGS_ANYWHERE | - VM_FLAGS_RANDOM_ADDR | - VM_FLAGS_OVERWRITE | - VM_FLAGS_RETURN_DATA_ADDR | - VM_FLAGS_RESILIENT_CODESIGN; - -pub const VM_FLAGS_SUPERPAGE_SHIFT: ::c_int = 16; -pub const SUPERPAGE_NONE: ::c_int = 0; -pub const SUPERPAGE_SIZE_ANY: ::c_int = 1; -pub const VM_FLAGS_SUPERPAGE_NONE: ::c_int = SUPERPAGE_NONE << - VM_FLAGS_SUPERPAGE_SHIFT; -pub const VM_FLAGS_SUPERPAGE_SIZE_ANY: ::c_int = SUPERPAGE_SIZE_ANY << - VM_FLAGS_SUPERPAGE_SHIFT; -pub const SUPERPAGE_SIZE_2MB: ::c_int = 2; -pub const VM_FLAGS_SUPERPAGE_SIZE_2MB: ::c_int = SUPERPAGE_SIZE_2MB << - VM_FLAGS_SUPERPAGE_SHIFT; - -pub const VM_MEMORY_MALLOC: ::c_int = 1; -pub const VM_MEMORY_MALLOC_SMALL: ::c_int = 2; -pub const VM_MEMORY_MALLOC_LARGE: ::c_int = 3; -pub const VM_MEMORY_MALLOC_HUGE: ::c_int = 4; -pub const VM_MEMORY_SBRK: ::c_int = 5; -pub const VM_MEMORY_REALLOC: ::c_int = 6; -pub const VM_MEMORY_MALLOC_TINY: ::c_int = 7; -pub const VM_MEMORY_MALLOC_LARGE_REUSABLE: ::c_int = 8; -pub const VM_MEMORY_MALLOC_LARGE_REUSED: ::c_int = 9; -pub const VM_MEMORY_ANALYSIS_TOOL: ::c_int = 10; -pub const VM_MEMORY_MALLOC_NANO: ::c_int = 11; -pub const VM_MEMORY_MACH_MSG: ::c_int = 20; -pub const VM_MEMORY_IOKIT: ::c_int = 21; -pub const VM_MEMORY_STACK: ::c_int = 30; -pub const VM_MEMORY_GUARD: ::c_int = 31; -pub const VM_MEMORY_SHARED_PMAP: ::c_int = 32; -pub const VM_MEMORY_DYLIB: ::c_int = 33; -pub const VM_MEMORY_OBJC_DISPATCHERS: ::c_int = 34; -pub const VM_MEMORY_UNSHARED_PMAP: ::c_int = 35; -pub const VM_MEMORY_APPKIT: ::c_int = 40; -pub const VM_MEMORY_FOUNDATION: ::c_int = 41; -pub const VM_MEMORY_COREGRAPHICS: ::c_int = 42; -pub const VM_MEMORY_CORESERVICES: ::c_int = 43; -pub const VM_MEMORY_CARBON: ::c_int = VM_MEMORY_CORESERVICES; -pub const VM_MEMORY_JAVA: ::c_int = 44; -pub const VM_MEMORY_COREDATA: ::c_int = 45; -pub const VM_MEMORY_COREDATA_OBJECTIDS: ::c_int = 46; -pub const VM_MEMORY_ATS: ::c_int = 50; -pub const VM_MEMORY_LAYERKIT: ::c_int = 51; -pub const VM_MEMORY_CGIMAGE: ::c_int = 52; -pub const VM_MEMORY_TCMALLOC: ::c_int = 53; -pub const VM_MEMORY_COREGRAPHICS_DATA: ::c_int = 54; -pub const VM_MEMORY_COREGRAPHICS_SHARED: ::c_int = 55; -pub const VM_MEMORY_COREGRAPHICS_FRAMEBUFFERS: ::c_int = 56; -pub const VM_MEMORY_COREGRAPHICS_BACKINGSTORES: ::c_int = 57; -pub const VM_MEMORY_COREGRAPHICS_XALLOC: ::c_int = 58; -pub const VM_MEMORY_COREGRAPHICS_MISC: ::c_int = VM_MEMORY_COREGRAPHICS; -pub const VM_MEMORY_DYLD: ::c_int = 60; -pub const VM_MEMORY_DYLD_MALLOC: ::c_int = 61; -pub const VM_MEMORY_SQLITE: ::c_int = 62; -pub const VM_MEMORY_JAVASCRIPT_CORE: ::c_int = 63; -pub const VM_MEMORY_JAVASCRIPT_JIT_EXECUTABLE_ALLOCATOR: ::c_int = 64; -pub const VM_MEMORY_JAVASCRIPT_JIT_REGISTER_FILE: ::c_int = 65; -pub const VM_MEMORY_GLSL: ::c_int = 66; -pub const VM_MEMORY_OPENCL: ::c_int = 67; -pub const VM_MEMORY_COREIMAGE: ::c_int = 68; -pub const VM_MEMORY_WEBCORE_PURGEABLE_BUFFERS: ::c_int = 69; -pub const VM_MEMORY_IMAGEIO: ::c_int = 70; -pub const VM_MEMORY_COREPROFILE: ::c_int = 71; -pub const VM_MEMORY_ASSETSD: ::c_int = 72; -pub const VM_MEMORY_OS_ALLOC_ONCE: ::c_int = 73; -pub const VM_MEMORY_LIBDISPATCH: ::c_int = 74; -pub const VM_MEMORY_ACCELERATE: ::c_int = 75; -pub const VM_MEMORY_COREUI: ::c_int = 76; -pub const VM_MEMORY_COREUIFILE: ::c_int = 77; -pub const VM_MEMORY_GENEALOGY: ::c_int = 78; -pub const VM_MEMORY_RAWCAMERA: ::c_int = 79; -pub const VM_MEMORY_CORPSEINFO: ::c_int = 80; -pub const VM_MEMORY_ASL: ::c_int = 81; -pub const VM_MEMORY_SWIFT_RUNTIME: ::c_int = 82; -pub const VM_MEMORY_SWIFT_METADATA: ::c_int = 83; -pub const VM_MEMORY_DHMM: ::c_int = 84; -pub const VM_MEMORY_SCENEKIT: ::c_int = 86; -pub const VM_MEMORY_SKYWALK: ::c_int = 87; -pub const VM_MEMORY_APPLICATION_SPECIFIC_1: ::c_int = 240; -pub const VM_MEMORY_APPLICATION_SPECIFIC_16: ::c_int = 255; - -pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const MS_ASYNC: ::c_int = 0x0001; -pub const MS_INVALIDATE: ::c_int = 0x0002; -pub const MS_SYNC: ::c_int = 0x0010; - -pub const MS_KILLPAGES: ::c_int = 0x0004; -pub const MS_DEACTIVATE: ::c_int = 0x0008; - -pub const EPERM: ::c_int = 1; -pub const ENOENT: ::c_int = 2; -pub const ESRCH: ::c_int = 3; -pub const EINTR: ::c_int = 4; -pub const EIO: ::c_int = 5; -pub const ENXIO: ::c_int = 6; -pub const E2BIG: ::c_int = 7; -pub const ENOEXEC: ::c_int = 8; -pub const EBADF: ::c_int = 9; -pub const ECHILD: ::c_int = 10; -pub const EDEADLK: ::c_int = 11; -pub const ENOMEM: ::c_int = 12; -pub const EACCES: ::c_int = 13; -pub const EFAULT: ::c_int = 14; -pub const ENOTBLK: ::c_int = 15; -pub const EBUSY: ::c_int = 16; -pub const EEXIST: ::c_int = 17; -pub const EXDEV: ::c_int = 18; -pub const ENODEV: ::c_int = 19; -pub const ENOTDIR: ::c_int = 20; -pub const EISDIR: ::c_int = 21; -pub const EINVAL: ::c_int = 22; -pub const ENFILE: ::c_int = 23; -pub const EMFILE: ::c_int = 24; -pub const ENOTTY: ::c_int = 25; -pub const ETXTBSY: ::c_int = 26; -pub const EFBIG: ::c_int = 27; -pub const ENOSPC: ::c_int = 28; -pub const ESPIPE: ::c_int = 29; -pub const EROFS: ::c_int = 30; -pub const EMLINK: ::c_int = 31; -pub const EPIPE: ::c_int = 32; -pub const EDOM: ::c_int = 33; -pub const ERANGE: ::c_int = 34; -pub const EAGAIN: ::c_int = 35; -pub const EWOULDBLOCK: ::c_int = EAGAIN; -pub const EINPROGRESS: ::c_int = 36; -pub const EALREADY: ::c_int = 37; -pub const ENOTSOCK: ::c_int = 38; -pub const EDESTADDRREQ: ::c_int = 39; -pub const EMSGSIZE: ::c_int = 40; -pub const EPROTOTYPE: ::c_int = 41; -pub const ENOPROTOOPT: ::c_int = 42; -pub const EPROTONOSUPPORT: ::c_int = 43; -pub const ESOCKTNOSUPPORT: ::c_int = 44; -pub const ENOTSUP: ::c_int = 45; -pub const EPFNOSUPPORT: ::c_int = 46; -pub const EAFNOSUPPORT: ::c_int = 47; -pub const EADDRINUSE: ::c_int = 48; -pub const EADDRNOTAVAIL: ::c_int = 49; -pub const ENETDOWN: ::c_int = 50; -pub const ENETUNREACH: ::c_int = 51; -pub const ENETRESET: ::c_int = 52; -pub const ECONNABORTED: ::c_int = 53; -pub const ECONNRESET: ::c_int = 54; -pub const ENOBUFS: ::c_int = 55; -pub const EISCONN: ::c_int = 56; -pub const ENOTCONN: ::c_int = 57; -pub const ESHUTDOWN: ::c_int = 58; -pub const ETOOMANYREFS: ::c_int = 59; -pub const ETIMEDOUT: ::c_int = 60; -pub const ECONNREFUSED: ::c_int = 61; -pub const ELOOP: ::c_int = 62; -pub const ENAMETOOLONG: ::c_int = 63; -pub const EHOSTDOWN: ::c_int = 64; -pub const EHOSTUNREACH: ::c_int = 65; -pub const ENOTEMPTY: ::c_int = 66; -pub const EPROCLIM: ::c_int = 67; -pub const EUSERS: ::c_int = 68; -pub const EDQUOT: ::c_int = 69; -pub const ESTALE: ::c_int = 70; -pub const EREMOTE: ::c_int = 71; -pub const EBADRPC: ::c_int = 72; -pub const ERPCMISMATCH: ::c_int = 73; -pub const EPROGUNAVAIL: ::c_int = 74; -pub const EPROGMISMATCH: ::c_int = 75; -pub const EPROCUNAVAIL: ::c_int = 76; -pub const ENOLCK: ::c_int = 77; -pub const ENOSYS: ::c_int = 78; -pub const EFTYPE: ::c_int = 79; -pub const EAUTH: ::c_int = 80; -pub const ENEEDAUTH: ::c_int = 81; -pub const EPWROFF: ::c_int = 82; -pub const EDEVERR: ::c_int = 83; -pub const EOVERFLOW: ::c_int = 84; -pub const EBADEXEC: ::c_int = 85; -pub const EBADARCH: ::c_int = 86; -pub const ESHLIBVERS: ::c_int = 87; -pub const EBADMACHO: ::c_int = 88; -pub const ECANCELED: ::c_int = 89; -pub const EIDRM: ::c_int = 90; -pub const ENOMSG: ::c_int = 91; -pub const EILSEQ: ::c_int = 92; -pub const ENOATTR: ::c_int = 93; -pub const EBADMSG: ::c_int = 94; -pub const EMULTIHOP: ::c_int = 95; -pub const ENODATA: ::c_int = 96; -pub const ENOLINK: ::c_int = 97; -pub const ENOSR: ::c_int = 98; -pub const ENOSTR: ::c_int = 99; -pub const EPROTO: ::c_int = 100; -pub const ETIME: ::c_int = 101; -pub const EOPNOTSUPP: ::c_int = 102; -pub const ENOPOLICY: ::c_int = 103; -pub const ENOTRECOVERABLE: ::c_int = 104; -pub const EOWNERDEAD: ::c_int = 105; -pub const EQFULL: ::c_int = 106; -pub const ELAST: ::c_int = 106; - -pub const EAI_AGAIN: ::c_int = 2; -pub const EAI_BADFLAGS: ::c_int = 3; -pub const EAI_FAIL: ::c_int = 4; -pub const EAI_FAMILY: ::c_int = 5; -pub const EAI_MEMORY: ::c_int = 6; -pub const EAI_NODATA: ::c_int = 7; -pub const EAI_NONAME: ::c_int = 8; -pub const EAI_SERVICE: ::c_int = 9; -pub const EAI_SOCKTYPE: ::c_int = 10; -pub const EAI_SYSTEM: ::c_int = 11; -pub const EAI_OVERFLOW: ::c_int = 14; - -pub const F_DUPFD: ::c_int = 0; -pub const F_DUPFD_CLOEXEC: ::c_int = 67; -pub const F_GETFD: ::c_int = 1; -pub const F_SETFD: ::c_int = 2; -pub const F_GETFL: ::c_int = 3; -pub const F_SETFL: ::c_int = 4; -pub const F_PREALLOCATE: ::c_int = 42; -pub const F_RDADVISE: ::c_int = 44; -pub const F_RDAHEAD: ::c_int = 45; -pub const F_NOCACHE: ::c_int = 48; -pub const F_GETPATH: ::c_int = 50; -pub const F_FULLFSYNC: ::c_int = 51; -pub const F_FREEZE_FS: ::c_int = 53; -pub const F_THAW_FS: ::c_int = 54; -pub const F_GLOBAL_NOCACHE: ::c_int = 55; -pub const F_NODIRECT: ::c_int = 62; - -pub const F_ALLOCATECONTIG: ::c_uint = 0x02; -pub const F_ALLOCATEALL: ::c_uint = 0x04; - -pub const F_PEOFPOSMODE: ::c_int = 3; -pub const F_VOLPOSMODE: ::c_int = 4; - -pub const AT_FDCWD: ::c_int = -2; -pub const AT_EACCESS: ::c_int = 0x0010; -pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x0020; -pub const AT_SYMLINK_FOLLOW: ::c_int = 0x0040; -pub const AT_REMOVEDIR: ::c_int = 0x0080; - -pub const TIOCMODG: ::c_ulong = 0x40047403; -pub const TIOCMODS: ::c_ulong = 0x80047404; -pub const TIOCM_LE: ::c_int = 0x1; -pub const TIOCM_DTR: ::c_int = 0x2; -pub const TIOCM_RTS: ::c_int = 0x4; -pub const TIOCM_ST: ::c_int = 0x8; -pub const TIOCM_SR: ::c_int = 0x10; -pub const TIOCM_CTS: ::c_int = 0x20; -pub const TIOCM_CAR: ::c_int = 0x40; -pub const TIOCM_CD: ::c_int = 0x40; -pub const TIOCM_RNG: ::c_int = 0x80; -pub const TIOCM_RI: ::c_int = 0x80; -pub const TIOCM_DSR: ::c_int = 0x100; -pub const TIOCEXCL: ::c_int = 0x2000740d; -pub const TIOCNXCL: ::c_int = 0x2000740e; -pub const TIOCFLUSH: ::c_ulong = 0x80047410; -pub const TIOCGETD: ::c_ulong = 0x4004741a; -pub const TIOCSETD: ::c_ulong = 0x8004741b; -pub const TIOCIXON: ::c_uint = 0x20007481; -pub const TIOCIXOFF: ::c_uint = 0x20007480; -pub const TIOCSBRK: ::c_uint = 0x2000747b; -pub const TIOCCBRK: ::c_uint = 0x2000747a; -pub const TIOCSDTR: ::c_uint = 0x20007479; -pub const TIOCCDTR: ::c_uint = 0x20007478; -pub const TIOCGPGRP: ::c_ulong = 0x40047477; -pub const TIOCSPGRP: ::c_ulong = 0x80047476; -pub const TIOCOUTQ: ::c_ulong = 0x40047473; -pub const TIOCSTI: ::c_ulong = 0x80017472; -pub const TIOCNOTTY: ::c_uint = 0x20007471; -pub const TIOCPKT: ::c_ulong = 0x80047470; -pub const TIOCPKT_DATA: ::c_int = 0x0; -pub const TIOCPKT_FLUSHREAD: ::c_int = 0x1; -pub const TIOCPKT_FLUSHWRITE: ::c_int = 0x2; -pub const TIOCPKT_STOP: ::c_int = 0x4; -pub const TIOCPKT_START: ::c_int = 0x8; -pub const TIOCPKT_NOSTOP: ::c_int = 0x10; -pub const TIOCPKT_DOSTOP: ::c_int = 0x20; -pub const TIOCPKT_IOCTL: ::c_int = 0x40; -pub const TIOCSTOP: ::c_uint = 0x2000746f; -pub const TIOCSTART: ::c_uint = 0x2000746e; -pub const TIOCMSET: ::c_ulong = 0x8004746d; -pub const TIOCMBIS: ::c_ulong = 0x8004746c; -pub const TIOCMBIC: ::c_ulong = 0x8004746b; -pub const TIOCMGET: ::c_ulong = 0x4004746a; -pub const TIOCREMOTE: ::c_ulong = 0x80047469; -pub const TIOCGWINSZ: ::c_ulong = 0x40087468; -pub const TIOCSWINSZ: ::c_ulong = 0x80087467; -pub const TIOCUCNTL: ::c_ulong = 0x80047466; -pub const TIOCSTAT: ::c_uint = 0x20007465; -pub const TIOCSCONS: ::c_uint = 0x20007463; -pub const TIOCCONS: ::c_ulong = 0x80047462; -pub const TIOCSCTTY: ::c_uint = 0x20007461; -pub const TIOCEXT: ::c_ulong = 0x80047460; -pub const TIOCSIG: ::c_uint = 0x2000745f; -pub const TIOCDRAIN: ::c_uint = 0x2000745e; -pub const TIOCMSDTRWAIT: ::c_ulong = 0x8004745b; -pub const TIOCMGDTRWAIT: ::c_ulong = 0x4004745a; -pub const TIOCSDRAINWAIT: ::c_ulong = 0x80047457; -pub const TIOCGDRAINWAIT: ::c_ulong = 0x40047456; -pub const TIOCDSIMICROCODE: ::c_uint = 0x20007455; -pub const TIOCPTYGRANT: ::c_uint = 0x20007454; -pub const TIOCPTYGNAME: ::c_uint = 0x40807453; -pub const TIOCPTYUNLK: ::c_uint = 0x20007452; - -pub const B0: speed_t = 0; -pub const B50: speed_t = 50; -pub const B75: speed_t = 75; -pub const B110: speed_t = 110; -pub const B134: speed_t = 134; -pub const B150: speed_t = 150; -pub const B200: speed_t = 200; -pub const B300: speed_t = 300; -pub const B600: speed_t = 600; -pub const B1200: speed_t = 1200; -pub const B1800: speed_t = 1800; -pub const B2400: speed_t = 2400; -pub const B4800: speed_t = 4800; -pub const B9600: speed_t = 9600; -pub const B19200: speed_t = 19200; -pub const B38400: speed_t = 38400; -pub const B7200: speed_t = 7200; -pub const B14400: speed_t = 14400; -pub const B28800: speed_t = 28800; -pub const B57600: speed_t = 57600; -pub const B76800: speed_t = 76800; -pub const B115200: speed_t = 115200; -pub const B230400: speed_t = 230400; -pub const EXTA: speed_t = 19200; -pub const EXTB: speed_t = 38400; - -pub const SIGTRAP: ::c_int = 5; - -pub const GLOB_APPEND : ::c_int = 0x0001; -pub const GLOB_DOOFFS : ::c_int = 0x0002; -pub const GLOB_ERR : ::c_int = 0x0004; -pub const GLOB_MARK : ::c_int = 0x0008; -pub const GLOB_NOCHECK : ::c_int = 0x0010; -pub const GLOB_NOSORT : ::c_int = 0x0020; -pub const GLOB_NOESCAPE: ::c_int = 0x2000; - -pub const GLOB_NOSPACE : ::c_int = -1; -pub const GLOB_ABORTED : ::c_int = -2; -pub const GLOB_NOMATCH : ::c_int = -3; - -pub const POSIX_MADV_NORMAL: ::c_int = 0; -pub const POSIX_MADV_RANDOM: ::c_int = 1; -pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; -pub const POSIX_MADV_WILLNEED: ::c_int = 3; -pub const POSIX_MADV_DONTNEED: ::c_int = 4; - -pub const _SC_IOV_MAX: ::c_int = 56; -pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 70; -pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 71; -pub const _SC_LOGIN_NAME_MAX: ::c_int = 73; -pub const _SC_MQ_PRIO_MAX: ::c_int = 75; -pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 82; -pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 83; -pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 85; -pub const _SC_THREAD_KEYS_MAX: ::c_int = 86; -pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 87; -pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 88; -pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 89; -pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 90; -pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 91; -pub const _SC_THREAD_STACK_MIN: ::c_int = 93; -pub const _SC_THREAD_THREADS_MAX: ::c_int = 94; -pub const _SC_THREADS: ::c_int = 96; -pub const _SC_TTY_NAME_MAX: ::c_int = 101; -pub const _SC_ATEXIT_MAX: ::c_int = 107; -pub const _SC_XOPEN_CRYPT: ::c_int = 108; -pub const _SC_XOPEN_ENH_I18N: ::c_int = 109; -pub const _SC_XOPEN_LEGACY: ::c_int = 110; -pub const _SC_XOPEN_REALTIME: ::c_int = 111; -pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 112; -pub const _SC_XOPEN_SHM: ::c_int = 113; -pub const _SC_XOPEN_UNIX: ::c_int = 115; -pub const _SC_XOPEN_VERSION: ::c_int = 116; -pub const _SC_XOPEN_XCU_VERSION: ::c_int = 121; - -pub const PTHREAD_PROCESS_PRIVATE: ::c_int = 2; -pub const PTHREAD_PROCESS_SHARED: ::c_int = 1; -pub const PTHREAD_CREATE_JOINABLE: ::c_int = 1; -pub const PTHREAD_CREATE_DETACHED: ::c_int = 2; -pub const PTHREAD_STACK_MIN: ::size_t = 8192; - -pub const RLIMIT_CPU: ::c_int = 0; -pub const RLIMIT_FSIZE: ::c_int = 1; -pub const RLIMIT_DATA: ::c_int = 2; -pub const RLIMIT_STACK: ::c_int = 3; -pub const RLIMIT_CORE: ::c_int = 4; -pub const RLIMIT_AS: ::c_int = 5; -pub const RLIMIT_RSS: ::c_int = RLIMIT_AS; -pub const RLIMIT_MEMLOCK: ::c_int = 6; -pub const RLIMIT_NPROC: ::c_int = 7; -pub const RLIMIT_NOFILE: ::c_int = 8; -pub const RLIM_NLIMITS: ::c_int = 9; -pub const _RLIMIT_POSIX_FLAG: ::c_int = 0x1000; - -pub const RLIM_INFINITY: rlim_t = 0x7fff_ffff_ffff_ffff; - -pub const RUSAGE_SELF: ::c_int = 0; -pub const RUSAGE_CHILDREN: ::c_int = -1; - -pub const MADV_NORMAL: ::c_int = 0; -pub const MADV_RANDOM: ::c_int = 1; -pub const MADV_SEQUENTIAL: ::c_int = 2; -pub const MADV_WILLNEED: ::c_int = 3; -pub const MADV_DONTNEED: ::c_int = 4; -pub const MADV_FREE: ::c_int = 5; -pub const MADV_ZERO_WIRED_PAGES: ::c_int = 6; -pub const MADV_FREE_REUSABLE: ::c_int = 7; -pub const MADV_FREE_REUSE: ::c_int = 8; -pub const MADV_CAN_REUSE: ::c_int = 9; - -pub const MINCORE_INCORE: ::c_int = 0x1; -pub const MINCORE_REFERENCED: ::c_int = 0x2; -pub const MINCORE_MODIFIED: ::c_int = 0x4; -pub const MINCORE_REFERENCED_OTHER: ::c_int = 0x8; -pub const MINCORE_MODIFIED_OTHER: ::c_int = 0x10; - -// -// sys/netinet/in.h -// Protocols (RFC 1700) -// NOTE: These are in addition to the constants defined in src/unix/mod.rs - -// IPPROTO_IP defined in src/unix/mod.rs -/// IP6 hop-by-hop options -pub const IPPROTO_HOPOPTS: ::c_int = 0; -// IPPROTO_ICMP defined in src/unix/mod.rs -/// group mgmt protocol -pub const IPPROTO_IGMP: ::c_int = 2; -/// gateway2 (deprecated) -pub const IPPROTO_GGP: ::c_int = 3; -/// for compatibility -pub const IPPROTO_IPIP: ::c_int = 4; -// IPPROTO_TCP defined in src/unix/mod.rs -/// Stream protocol II. -pub const IPPROTO_ST: ::c_int = 7; -/// exterior gateway protocol -pub const IPPROTO_EGP: ::c_int = 8; -/// private interior gateway -pub const IPPROTO_PIGP: ::c_int = 9; -/// BBN RCC Monitoring -pub const IPPROTO_RCCMON: ::c_int = 10; -/// network voice protocol -pub const IPPROTO_NVPII: ::c_int = 11; -/// pup -pub const IPPROTO_PUP: ::c_int = 12; -/// Argus -pub const IPPROTO_ARGUS: ::c_int = 13; -/// EMCON -pub const IPPROTO_EMCON: ::c_int = 14; -/// Cross Net Debugger -pub const IPPROTO_XNET: ::c_int = 15; -/// Chaos -pub const IPPROTO_CHAOS: ::c_int = 16; -// IPPROTO_UDP defined in src/unix/mod.rs -/// Multiplexing -pub const IPPROTO_MUX: ::c_int = 18; -/// DCN Measurement Subsystems -pub const IPPROTO_MEAS: ::c_int = 19; -/// Host Monitoring -pub const IPPROTO_HMP: ::c_int = 20; -/// Packet Radio Measurement -pub const IPPROTO_PRM: ::c_int = 21; -/// xns idp -pub const IPPROTO_IDP: ::c_int = 22; -/// Trunk-1 -pub const IPPROTO_TRUNK1: ::c_int = 23; -/// Trunk-2 -pub const IPPROTO_TRUNK2: ::c_int = 24; -/// Leaf-1 -pub const IPPROTO_LEAF1: ::c_int = 25; -/// Leaf-2 -pub const IPPROTO_LEAF2: ::c_int = 26; -/// Reliable Data -pub const IPPROTO_RDP: ::c_int = 27; -/// Reliable Transaction -pub const IPPROTO_IRTP: ::c_int = 28; -/// tp-4 w/ class negotiation -pub const IPPROTO_TP: ::c_int = 29; -/// Bulk Data Transfer -pub const IPPROTO_BLT: ::c_int = 30; -/// Network Services -pub const IPPROTO_NSP: ::c_int = 31; -/// Merit Internodal -pub const IPPROTO_INP: ::c_int = 32; -/// Sequential Exchange -pub const IPPROTO_SEP: ::c_int = 33; -/// Third Party Connect -pub const IPPROTO_3PC: ::c_int = 34; -/// InterDomain Policy Routing -pub const IPPROTO_IDPR: ::c_int = 35; -/// XTP -pub const IPPROTO_XTP: ::c_int = 36; -/// Datagram Delivery -pub const IPPROTO_DDP: ::c_int = 37; -/// Control Message Transport -pub const IPPROTO_CMTP: ::c_int = 38; -/// TP++ Transport -pub const IPPROTO_TPXX: ::c_int = 39; -/// IL transport protocol -pub const IPPROTO_IL: ::c_int = 40; -// IPPROTO_IPV6 defined in src/unix/mod.rs -/// Source Demand Routing -pub const IPPROTO_SDRP: ::c_int = 42; -/// IP6 routing header -pub const IPPROTO_ROUTING: ::c_int = 43; -/// IP6 fragmentation header -pub const IPPROTO_FRAGMENT: ::c_int = 44; -/// InterDomain Routing -pub const IPPROTO_IDRP: ::c_int = 45; -/// resource reservation -pub const IPPROTO_RSVP: ::c_int = 46; -/// General Routing Encap. -pub const IPPROTO_GRE: ::c_int = 47; -/// Mobile Host Routing -pub const IPPROTO_MHRP: ::c_int = 48; -/// BHA -pub const IPPROTO_BHA: ::c_int = 49; -/// IP6 Encap Sec. Payload -pub const IPPROTO_ESP: ::c_int = 50; -/// IP6 Auth Header -pub const IPPROTO_AH: ::c_int = 51; -/// Integ. Net Layer Security -pub const IPPROTO_INLSP: ::c_int = 52; -/// IP with encryption -pub const IPPROTO_SWIPE: ::c_int = 53; -/// Next Hop Resolution -pub const IPPROTO_NHRP: ::c_int = 54; -/* 55-57: Unassigned */ -// IPPROTO_ICMPV6 defined in src/unix/mod.rs -/// IP6 no next header -pub const IPPROTO_NONE: ::c_int = 59; -/// IP6 destination option -pub const IPPROTO_DSTOPTS: ::c_int = 60; -/// any host internal protocol -pub const IPPROTO_AHIP: ::c_int = 61; -/// CFTP -pub const IPPROTO_CFTP: ::c_int = 62; -/// "hello" routing protocol -pub const IPPROTO_HELLO: ::c_int = 63; -/// SATNET/Backroom EXPAK -pub const IPPROTO_SATEXPAK: ::c_int = 64; -/// Kryptolan -pub const IPPROTO_KRYPTOLAN: ::c_int = 65; -/// Remote Virtual Disk -pub const IPPROTO_RVD: ::c_int = 66; -/// Pluribus Packet Core -pub const IPPROTO_IPPC: ::c_int = 67; -/// Any distributed FS -pub const IPPROTO_ADFS: ::c_int = 68; -/// Satnet Monitoring -pub const IPPROTO_SATMON: ::c_int = 69; -/// VISA Protocol -pub const IPPROTO_VISA: ::c_int = 70; -/// Packet Core Utility -pub const IPPROTO_IPCV: ::c_int = 71; -/// Comp. Prot. Net. Executive -pub const IPPROTO_CPNX: ::c_int = 72; -/// Comp. Prot. HeartBeat -pub const IPPROTO_CPHB: ::c_int = 73; -/// Wang Span Network -pub const IPPROTO_WSN: ::c_int = 74; -/// Packet Video Protocol -pub const IPPROTO_PVP: ::c_int = 75; -/// BackRoom SATNET Monitoring -pub const IPPROTO_BRSATMON: ::c_int = 76; -/// Sun net disk proto (temp.) -pub const IPPROTO_ND: ::c_int = 77; -/// WIDEBAND Monitoring -pub const IPPROTO_WBMON: ::c_int = 78; -/// WIDEBAND EXPAK -pub const IPPROTO_WBEXPAK: ::c_int = 79; -/// ISO cnlp -pub const IPPROTO_EON: ::c_int = 80; -/// VMTP -pub const IPPROTO_VMTP: ::c_int = 81; -/// Secure VMTP -pub const IPPROTO_SVMTP: ::c_int = 82; -/// Banyon VINES -pub const IPPROTO_VINES: ::c_int = 83; -/// TTP -pub const IPPROTO_TTP: ::c_int = 84; -/// NSFNET-IGP -pub const IPPROTO_IGP: ::c_int = 85; -/// dissimilar gateway prot. -pub const IPPROTO_DGP: ::c_int = 86; -/// TCF -pub const IPPROTO_TCF: ::c_int = 87; -/// Cisco/GXS IGRP -pub const IPPROTO_IGRP: ::c_int = 88; -/// OSPFIGP -pub const IPPROTO_OSPFIGP: ::c_int = 89; -/// Strite RPC protocol -pub const IPPROTO_SRPC: ::c_int = 90; -/// Locus Address Resoloution -pub const IPPROTO_LARP: ::c_int = 91; -/// Multicast Transport -pub const IPPROTO_MTP: ::c_int = 92; -/// AX.25 Frames -pub const IPPROTO_AX25: ::c_int = 93; -/// IP encapsulated in IP -pub const IPPROTO_IPEIP: ::c_int = 94; -/// Mobile Int.ing control -pub const IPPROTO_MICP: ::c_int = 95; -/// Semaphore Comm. security -pub const IPPROTO_SCCSP: ::c_int = 96; -/// Ethernet IP encapsulation -pub const IPPROTO_ETHERIP: ::c_int = 97; -/// encapsulation header -pub const IPPROTO_ENCAP: ::c_int = 98; -/// any private encr. scheme -pub const IPPROTO_APES: ::c_int = 99; -/// GMTP -pub const IPPROTO_GMTP: ::c_int = 100; - -/* 101-254: Partly Unassigned */ -/// Protocol Independent Mcast -pub const IPPROTO_PIM: ::c_int = 103; -/// payload compression (IPComp) -pub const IPPROTO_IPCOMP: ::c_int = 108; -/// PGM -pub const IPPROTO_PGM: ::c_int = 113; -/// SCTP -pub const IPPROTO_SCTP: ::c_int = 132; - -/* 255: Reserved */ -/* BSD Private, local use, namespace incursion */ -/// divert pseudo-protocol -pub const IPPROTO_DIVERT: ::c_int = 254; -/// raw IP packet -pub const IPPROTO_RAW: ::c_int = 255; -pub const IPPROTO_MAX: ::c_int = 256; -/// last return value of *_input(), meaning "all job for this pkt is done". -pub const IPPROTO_DONE: ::c_int = 257; - -pub const AF_UNSPEC: ::c_int = 0; -pub const AF_LOCAL: ::c_int = 1; -pub const AF_UNIX: ::c_int = AF_LOCAL; -pub const AF_INET: ::c_int = 2; -pub const AF_IMPLINK: ::c_int = 3; -pub const AF_PUP: ::c_int = 4; -pub const AF_CHAOS: ::c_int = 5; -pub const AF_NS: ::c_int = 6; -pub const AF_ISO: ::c_int = 7; -pub const AF_OSI: ::c_int = AF_ISO; -pub const AF_ECMA: ::c_int = 8; -pub const AF_DATAKIT: ::c_int = 9; -pub const AF_CCITT: ::c_int = 10; -pub const AF_SNA: ::c_int = 11; -pub const AF_DECnet: ::c_int = 12; -pub const AF_DLI: ::c_int = 13; -pub const AF_LAT: ::c_int = 14; -pub const AF_HYLINK: ::c_int = 15; -pub const AF_APPLETALK: ::c_int = 16; -pub const AF_ROUTE: ::c_int = 17; -pub const AF_LINK: ::c_int = 18; -pub const pseudo_AF_XTP: ::c_int = 19; -pub const AF_COIP: ::c_int = 20; -pub const AF_CNT: ::c_int = 21; -pub const pseudo_AF_RTIP: ::c_int = 22; -pub const AF_IPX: ::c_int = 23; -pub const AF_SIP: ::c_int = 24; -pub const pseudo_AF_PIP: ::c_int = 25; -pub const AF_ISDN: ::c_int = 28; -pub const AF_E164: ::c_int = AF_ISDN; -pub const pseudo_AF_KEY: ::c_int = 29; -pub const AF_INET6: ::c_int = 30; -pub const AF_NATM: ::c_int = 31; -pub const AF_SYSTEM: ::c_int = 32; -pub const AF_NETBIOS: ::c_int = 33; -pub const AF_PPP: ::c_int = 34; -pub const pseudo_AF_HDRCMPLT: ::c_int = 35; -#[doc(hidden)] -pub const AF_MAX: ::c_int = 40; -pub const AF_SYS_CONTROL: ::c_int = 2; - -pub const SYSPROTO_EVENT: ::c_int = 1; -pub const SYSPROTO_CONTROL: ::c_int = 2; - -pub const PF_UNSPEC: ::c_int = AF_UNSPEC; -pub const PF_LOCAL: ::c_int = AF_LOCAL; -pub const PF_UNIX: ::c_int = PF_LOCAL; -pub const PF_INET: ::c_int = AF_INET; -pub const PF_IMPLINK: ::c_int = AF_IMPLINK; -pub const PF_PUP: ::c_int = AF_PUP; -pub const PF_CHAOS: ::c_int = AF_CHAOS; -pub const PF_NS: ::c_int = AF_NS; -pub const PF_ISO: ::c_int = AF_ISO; -pub const PF_OSI: ::c_int = AF_ISO; -pub const PF_ECMA: ::c_int = AF_ECMA; -pub const PF_DATAKIT: ::c_int = AF_DATAKIT; -pub const PF_CCITT: ::c_int = AF_CCITT; -pub const PF_SNA: ::c_int = AF_SNA; -pub const PF_DECnet: ::c_int = AF_DECnet; -pub const PF_DLI: ::c_int = AF_DLI; -pub const PF_LAT: ::c_int = AF_LAT; -pub const PF_HYLINK: ::c_int = AF_HYLINK; -pub const PF_APPLETALK: ::c_int = AF_APPLETALK; -pub const PF_ROUTE: ::c_int = AF_ROUTE; -pub const PF_LINK: ::c_int = AF_LINK; -pub const PF_XTP: ::c_int = pseudo_AF_XTP; -pub const PF_COIP: ::c_int = AF_COIP; -pub const PF_CNT: ::c_int = AF_CNT; -pub const PF_SIP: ::c_int = AF_SIP; -pub const PF_IPX: ::c_int = AF_IPX; -pub const PF_RTIP: ::c_int = pseudo_AF_RTIP; -pub const PF_PIP: ::c_int = pseudo_AF_PIP; -pub const PF_ISDN: ::c_int = AF_ISDN; -pub const PF_KEY: ::c_int = pseudo_AF_KEY; -pub const PF_INET6: ::c_int = AF_INET6; -pub const PF_NATM: ::c_int = AF_NATM; -pub const PF_SYSTEM: ::c_int = AF_SYSTEM; -pub const PF_NETBIOS: ::c_int = AF_NETBIOS; -pub const PF_PPP: ::c_int = AF_PPP; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; - -#[doc(hidden)] -pub const NET_MAXID: ::c_int = AF_MAX; - -pub const NET_RT_DUMP: ::c_int = 1; -pub const NET_RT_FLAGS: ::c_int = 2; -pub const NET_RT_IFLIST: ::c_int = 3; -#[doc(hidden)] -pub const NET_RT_MAXID: ::c_int = 10; - -pub const SOMAXCONN: ::c_int = 128; - -pub const SOCK_MAXADDRLEN: ::c_int = 255; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; -pub const SOCK_RAW: ::c_int = 3; -pub const SOCK_RDM: ::c_int = 4; -pub const SOCK_SEQPACKET: ::c_int = 5; -pub const IP_TTL: ::c_int = 4; -pub const IP_HDRINCL: ::c_int = 2; -pub const IP_ADD_MEMBERSHIP: ::c_int = 12; -pub const IP_DROP_MEMBERSHIP: ::c_int = 13; -pub const IPV6_JOIN_GROUP: ::c_int = 12; -pub const IPV6_LEAVE_GROUP: ::c_int = 13; - -pub const TCP_NODELAY: ::c_int = 0x01; -pub const TCP_KEEPALIVE: ::c_int = 0x10; - -pub const SOL_LOCAL: ::c_int = 0; - -pub const LOCAL_PEERCRED: ::c_int = 0x001; -pub const LOCAL_PEERPID: ::c_int = 0x002; -pub const LOCAL_PEEREPID: ::c_int = 0x003; -pub const LOCAL_PEERUUID: ::c_int = 0x004; -pub const LOCAL_PEEREUUID: ::c_int = 0x005; - -pub const SOL_SOCKET: ::c_int = 0xffff; - -pub const SO_DEBUG: ::c_int = 0x01; -pub const SO_ACCEPTCONN: ::c_int = 0x0002; -pub const SO_REUSEADDR: ::c_int = 0x0004; -pub const SO_KEEPALIVE: ::c_int = 0x0008; -pub const SO_DONTROUTE: ::c_int = 0x0010; -pub const SO_BROADCAST: ::c_int = 0x0020; -pub const SO_USELOOPBACK: ::c_int = 0x0040; -pub const SO_LINGER: ::c_int = 0x0080; -pub const SO_OOBINLINE: ::c_int = 0x0100; -pub const SO_REUSEPORT: ::c_int = 0x0200; -pub const SO_TIMESTAMP: ::c_int = 0x0400; -pub const SO_TIMESTAMP_MONOTONIC: ::c_int = 0x0800; -pub const SO_DONTTRUNC: ::c_int = 0x2000; -pub const SO_WANTMORE: ::c_int = 0x4000; -pub const SO_WANTOOBFLAG: ::c_int = 0x8000; -pub const SO_SNDBUF: ::c_int = 0x1001; -pub const SO_RCVBUF: ::c_int = 0x1002; -pub const SO_SNDLOWAT: ::c_int = 0x1003; -pub const SO_RCVLOWAT: ::c_int = 0x1004; -pub const SO_SNDTIMEO: ::c_int = 0x1005; -pub const SO_RCVTIMEO: ::c_int = 0x1006; -pub const SO_ERROR: ::c_int = 0x1007; -pub const SO_TYPE: ::c_int = 0x1008; -pub const SO_LABEL: ::c_int = 0x1010; -pub const SO_PEERLABEL: ::c_int = 0x1011; -pub const SO_NREAD: ::c_int = 0x1020; -pub const SO_NKE: ::c_int = 0x1021; -pub const SO_NOSIGPIPE: ::c_int = 0x1022; -pub const SO_NOADDRERR: ::c_int = 0x1023; -pub const SO_NWRITE: ::c_int = 0x1024; -pub const SO_REUSESHAREUID: ::c_int = 0x1025; -pub const SO_NOTIFYCONFLICT: ::c_int = 0x1026; -pub const SO_RANDOMPORT: ::c_int = 0x1082; -pub const SO_NP_EXTENSIONS: ::c_int = 0x1083; - -pub const MSG_OOB: ::c_int = 0x1; -pub const MSG_PEEK: ::c_int = 0x2; -pub const MSG_DONTROUTE: ::c_int = 0x4; -pub const MSG_EOR: ::c_int = 0x8; -pub const MSG_TRUNC: ::c_int = 0x10; -pub const MSG_CTRUNC: ::c_int = 0x20; -pub const MSG_WAITALL: ::c_int = 0x40; -pub const MSG_DONTWAIT: ::c_int = 0x80; -pub const MSG_EOF: ::c_int = 0x100; -pub const MSG_FLUSH: ::c_int = 0x400; -pub const MSG_HOLD: ::c_int = 0x800; -pub const MSG_SEND: ::c_int = 0x1000; -pub const MSG_HAVEMORE: ::c_int = 0x2000; -pub const MSG_RCVMORE: ::c_int = 0x4000; -// pub const MSG_COMPAT: ::c_int = 0x8000; - -pub const SCM_TIMESTAMP: ::c_int = 0x02; -pub const SCM_CREDS: ::c_int = 0x03; - -// https://github.com/aosm/xnu/blob/master/bsd/net/if.h#L140-L156 -pub const IFF_UP: ::c_int = 0x1; // interface is up -pub const IFF_BROADCAST: ::c_int = 0x2; // broadcast address valid -pub const IFF_DEBUG: ::c_int = 0x4; // turn on debugging -pub const IFF_LOOPBACK: ::c_int = 0x8; // is a loopback net -pub const IFF_POINTOPOINT: ::c_int = 0x10; // interface is point-to-point link -pub const IFF_NOTRAILERS: ::c_int = 0x20; // obsolete: avoid use of trailers -pub const IFF_RUNNING: ::c_int = 0x40; // resources allocated -pub const IFF_NOARP: ::c_int = 0x80; // no address resolution protocol -pub const IFF_PROMISC: ::c_int = 0x100;// receive all packets -pub const IFF_ALLMULTI: ::c_int = 0x200;// receive all multicast packets -pub const IFF_OACTIVE: ::c_int = 0x400;// transmission in progress -pub const IFF_SIMPLEX: ::c_int = 0x800;// can't hear own transmissions -pub const IFF_LINK0: ::c_int = 0x1000;// per link layer defined bit -pub const IFF_LINK1: ::c_int = 0x2000;// per link layer defined bit -pub const IFF_LINK2: ::c_int = 0x4000;// per link layer defined bit -pub const IFF_ALTPHYS: ::c_int = IFF_LINK2;// use alternate physical connection -pub const IFF_MULTICAST: ::c_int = 0x8000;// supports multicast - -pub const SHUT_RD: ::c_int = 0; -pub const SHUT_WR: ::c_int = 1; -pub const SHUT_RDWR: ::c_int = 2; - -pub const LOCK_SH: ::c_int = 1; -pub const LOCK_EX: ::c_int = 2; -pub const LOCK_NB: ::c_int = 4; -pub const LOCK_UN: ::c_int = 8; - -pub const MAP_COPY: ::c_int = 0x0002; -pub const MAP_RENAME: ::c_int = 0x0020; -pub const MAP_NORESERVE: ::c_int = 0x0040; -pub const MAP_NOEXTEND: ::c_int = 0x0100; -pub const MAP_HASSEMAPHORE: ::c_int = 0x0200; -pub const MAP_NOCACHE: ::c_int = 0x0400; -pub const MAP_JIT: ::c_int = 0x0800; - -pub const _SC_ARG_MAX: ::c_int = 1; -pub const _SC_CHILD_MAX: ::c_int = 2; -pub const _SC_CLK_TCK: ::c_int = 3; -pub const _SC_NGROUPS_MAX: ::c_int = 4; -pub const _SC_OPEN_MAX: ::c_int = 5; -pub const _SC_JOB_CONTROL: ::c_int = 6; -pub const _SC_SAVED_IDS: ::c_int = 7; -pub const _SC_VERSION: ::c_int = 8; -pub const _SC_BC_BASE_MAX: ::c_int = 9; -pub const _SC_BC_DIM_MAX: ::c_int = 10; -pub const _SC_BC_SCALE_MAX: ::c_int = 11; -pub const _SC_BC_STRING_MAX: ::c_int = 12; -pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 13; -pub const _SC_EXPR_NEST_MAX: ::c_int = 14; -pub const _SC_LINE_MAX: ::c_int = 15; -pub const _SC_RE_DUP_MAX: ::c_int = 16; -pub const _SC_2_VERSION: ::c_int = 17; -pub const _SC_2_C_BIND: ::c_int = 18; -pub const _SC_2_C_DEV: ::c_int = 19; -pub const _SC_2_CHAR_TERM: ::c_int = 20; -pub const _SC_2_FORT_DEV: ::c_int = 21; -pub const _SC_2_FORT_RUN: ::c_int = 22; -pub const _SC_2_LOCALEDEF: ::c_int = 23; -pub const _SC_2_SW_DEV: ::c_int = 24; -pub const _SC_2_UPE: ::c_int = 25; -pub const _SC_STREAM_MAX: ::c_int = 26; -pub const _SC_TZNAME_MAX: ::c_int = 27; -pub const _SC_ASYNCHRONOUS_IO: ::c_int = 28; -pub const _SC_PAGESIZE: ::c_int = 29; -pub const _SC_MEMLOCK: ::c_int = 30; -pub const _SC_MEMLOCK_RANGE: ::c_int = 31; -pub const _SC_MEMORY_PROTECTION: ::c_int = 32; -pub const _SC_MESSAGE_PASSING: ::c_int = 33; -pub const _SC_PRIORITIZED_IO: ::c_int = 34; -pub const _SC_PRIORITY_SCHEDULING: ::c_int = 35; -pub const _SC_REALTIME_SIGNALS: ::c_int = 36; -pub const _SC_SEMAPHORES: ::c_int = 37; -pub const _SC_FSYNC: ::c_int = 38; -pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 39; -pub const _SC_SYNCHRONIZED_IO: ::c_int = 40; -pub const _SC_TIMERS: ::c_int = 41; -pub const _SC_AIO_LISTIO_MAX: ::c_int = 42; -pub const _SC_AIO_MAX: ::c_int = 43; -pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 44; -pub const _SC_DELAYTIMER_MAX: ::c_int = 45; -pub const _SC_MQ_OPEN_MAX: ::c_int = 46; -pub const _SC_MAPPED_FILES: ::c_int = 47; -pub const _SC_RTSIG_MAX: ::c_int = 48; -pub const _SC_SEM_NSEMS_MAX: ::c_int = 49; -pub const _SC_SEM_VALUE_MAX: ::c_int = 50; -pub const _SC_SIGQUEUE_MAX: ::c_int = 51; -pub const _SC_TIMER_MAX: ::c_int = 52; -pub const _SC_NPROCESSORS_CONF: ::c_int = 57; -pub const _SC_NPROCESSORS_ONLN: ::c_int = 58; -pub const _SC_2_PBS: ::c_int = 59; -pub const _SC_2_PBS_ACCOUNTING: ::c_int = 60; -pub const _SC_2_PBS_CHECKPOINT: ::c_int = 61; -pub const _SC_2_PBS_LOCATE: ::c_int = 62; -pub const _SC_2_PBS_MESSAGE: ::c_int = 63; -pub const _SC_2_PBS_TRACK: ::c_int = 64; -pub const _SC_ADVISORY_INFO: ::c_int = 65; -pub const _SC_BARRIERS: ::c_int = 66; -pub const _SC_CLOCK_SELECTION: ::c_int = 67; -pub const _SC_CPUTIME: ::c_int = 68; -pub const _SC_FILE_LOCKING: ::c_int = 69; -pub const _SC_HOST_NAME_MAX: ::c_int = 72; -pub const _SC_MONOTONIC_CLOCK: ::c_int = 74; -pub const _SC_READER_WRITER_LOCKS: ::c_int = 76; -pub const _SC_REGEXP: ::c_int = 77; -pub const _SC_SHELL: ::c_int = 78; -pub const _SC_SPAWN: ::c_int = 79; -pub const _SC_SPIN_LOCKS: ::c_int = 80; -pub const _SC_SPORADIC_SERVER: ::c_int = 81; -pub const _SC_THREAD_CPUTIME: ::c_int = 84; -pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 92; -pub const _SC_TIMEOUTS: ::c_int = 95; -pub const _SC_TRACE: ::c_int = 97; -pub const _SC_TRACE_EVENT_FILTER: ::c_int = 98; -pub const _SC_TRACE_INHERIT: ::c_int = 99; -pub const _SC_TRACE_LOG: ::c_int = 100; -pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 102; -pub const _SC_V6_ILP32_OFF32: ::c_int = 103; -pub const _SC_V6_ILP32_OFFBIG: ::c_int = 104; -pub const _SC_V6_LP64_OFF64: ::c_int = 105; -pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 106; -pub const _SC_IPV6: ::c_int = 118; -pub const _SC_RAW_SOCKETS: ::c_int = 119; -pub const _SC_SYMLOOP_MAX: ::c_int = 120; -pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; -pub const _SC_XOPEN_STREAMS: ::c_int = 114; -pub const _SC_XBS5_ILP32_OFF32: ::c_int = 122; -pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 123; -pub const _SC_XBS5_LP64_OFF64: ::c_int = 124; -pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 125; -pub const _SC_SS_REPL_MAX: ::c_int = 126; -pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 127; -pub const _SC_TRACE_NAME_MAX: ::c_int = 128; -pub const _SC_TRACE_SYS_MAX: ::c_int = 129; -pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 130; -pub const _SC_PASS_MAX: ::c_int = 131; - -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 1; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 2; -pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; -pub const _PTHREAD_MUTEX_SIG_init: ::c_long = 0x32AAABA7; -pub const _PTHREAD_COND_SIG_init: ::c_long = 0x3CB0B1BB; -pub const _PTHREAD_RWLOCK_SIG_init: ::c_long = 0x2DA8B3B4; -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { - __sig: _PTHREAD_MUTEX_SIG_init, - __opaque: [0; __PTHREAD_MUTEX_SIZE__], -}; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { - __sig: _PTHREAD_COND_SIG_init, - __opaque: [0; __PTHREAD_COND_SIZE__], -}; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { - __sig: _PTHREAD_RWLOCK_SIG_init, - __opaque: [0; __PTHREAD_RWLOCK_SIZE__], -}; - -pub const SIGSTKSZ: ::size_t = 131072; - -pub const FD_SETSIZE: usize = 1024; - -pub const ST_NOSUID: ::c_ulong = 2; - -pub const EVFILT_READ: ::int16_t = -1; -pub const EVFILT_WRITE: ::int16_t = -2; -pub const EVFILT_AIO: ::int16_t = -3; -pub const EVFILT_VNODE: ::int16_t = -4; -pub const EVFILT_PROC: ::int16_t = -5; -pub const EVFILT_SIGNAL: ::int16_t = -6; -pub const EVFILT_TIMER: ::int16_t = -7; -pub const EVFILT_MACHPORT: ::int16_t = -8; -pub const EVFILT_FS: ::int16_t = -9; -pub const EVFILT_USER: ::int16_t = -10; -pub const EVFILT_VM: ::int16_t = -12; - -pub const EV_ADD: ::uint16_t = 0x1; -pub const EV_DELETE: ::uint16_t = 0x2; -pub const EV_ENABLE: ::uint16_t = 0x4; -pub const EV_DISABLE: ::uint16_t = 0x8; -pub const EV_ONESHOT: ::uint16_t = 0x10; -pub const EV_CLEAR: ::uint16_t = 0x20; -pub const EV_RECEIPT: ::uint16_t = 0x40; -pub const EV_DISPATCH: ::uint16_t = 0x80; -pub const EV_FLAG0: ::uint16_t = 0x1000; -pub const EV_POLL: ::uint16_t = 0x1000; -pub const EV_FLAG1: ::uint16_t = 0x2000; -pub const EV_OOBAND: ::uint16_t = 0x2000; -pub const EV_ERROR: ::uint16_t = 0x4000; -pub const EV_EOF: ::uint16_t = 0x8000; -pub const EV_SYSFLAGS: ::uint16_t = 0xf000; - -pub const NOTE_TRIGGER: ::uint32_t = 0x01000000; -pub const NOTE_FFNOP: ::uint32_t = 0x00000000; -pub const NOTE_FFAND: ::uint32_t = 0x40000000; -pub const NOTE_FFOR: ::uint32_t = 0x80000000; -pub const NOTE_FFCOPY: ::uint32_t = 0xc0000000; -pub const NOTE_FFCTRLMASK: ::uint32_t = 0xc0000000; -pub const NOTE_FFLAGSMASK: ::uint32_t = 0x00ffffff; -pub const NOTE_LOWAT: ::uint32_t = 0x00000001; -pub const NOTE_DELETE: ::uint32_t = 0x00000001; -pub const NOTE_WRITE: ::uint32_t = 0x00000002; -pub const NOTE_EXTEND: ::uint32_t = 0x00000004; -pub const NOTE_ATTRIB: ::uint32_t = 0x00000008; -pub const NOTE_LINK: ::uint32_t = 0x00000010; -pub const NOTE_RENAME: ::uint32_t = 0x00000020; -pub const NOTE_REVOKE: ::uint32_t = 0x00000040; -pub const NOTE_NONE: ::uint32_t = 0x00000080; -pub const NOTE_EXIT: ::uint32_t = 0x80000000; -pub const NOTE_FORK: ::uint32_t = 0x40000000; -pub const NOTE_EXEC: ::uint32_t = 0x20000000; -pub const NOTE_REAP: ::uint32_t = 0x10000000; -pub const NOTE_SIGNAL: ::uint32_t = 0x08000000; -pub const NOTE_EXITSTATUS: ::uint32_t = 0x04000000; -pub const NOTE_EXIT_DETAIL: ::uint32_t = 0x02000000; -pub const NOTE_PDATAMASK: ::uint32_t = 0x000fffff; -pub const NOTE_PCTRLMASK: ::uint32_t = 0xfff00000; -pub const NOTE_EXIT_REPARENTED: ::uint32_t = 0x00080000; -pub const NOTE_EXIT_DETAIL_MASK: ::uint32_t = 0x00070000; -pub const NOTE_EXIT_DECRYPTFAIL: ::uint32_t = 0x00010000; -pub const NOTE_EXIT_MEMORY: ::uint32_t = 0x00020000; -pub const NOTE_EXIT_CSERROR: ::uint32_t = 0x00040000; -pub const NOTE_VM_PRESSURE: ::uint32_t = 0x80000000; -pub const NOTE_VM_PRESSURE_TERMINATE: ::uint32_t = 0x40000000; -pub const NOTE_VM_PRESSURE_SUDDEN_TERMINATE: ::uint32_t = 0x20000000; -pub const NOTE_VM_ERROR: ::uint32_t = 0x10000000; -pub const NOTE_SECONDS: ::uint32_t = 0x00000001; -pub const NOTE_USECONDS: ::uint32_t = 0x00000002; -pub const NOTE_NSECONDS: ::uint32_t = 0x00000004; -pub const NOTE_ABSOLUTE: ::uint32_t = 0x00000008; -pub const NOTE_LEEWAY: ::uint32_t = 0x00000010; -pub const NOTE_CRITICAL: ::uint32_t = 0x00000020; -pub const NOTE_BACKGROUND: ::uint32_t = 0x00000040; -pub const NOTE_TRACK: ::uint32_t = 0x00000001; -pub const NOTE_TRACKERR: ::uint32_t = 0x00000002; -pub const NOTE_CHILD: ::uint32_t = 0x00000004; - -pub const OCRNL: ::c_int = 0x00000010; -pub const ONOCR: ::c_int = 0x00000020; -pub const ONLRET: ::c_int = 0x00000040; -pub const OFILL: ::c_int = 0x00000080; -pub const NLDLY: ::c_int = 0x00000300; -pub const TABDLY: ::c_int = 0x00000c04; -pub const CRDLY: ::c_int = 0x00003000; -pub const FFDLY: ::c_int = 0x00004000; -pub const BSDLY: ::c_int = 0x00008000; -pub const VTDLY: ::c_int = 0x00010000; -pub const OFDEL: ::c_int = 0x00020000; - -pub const NL0: ::c_int = 0x00000000; -pub const NL1: ::c_int = 0x00000100; -pub const TAB0: ::c_int = 0x00000000; -pub const TAB1: ::c_int = 0x00000400; -pub const TAB2: ::c_int = 0x00000800; -pub const CR0: ::c_int = 0x00000000; -pub const CR1: ::c_int = 0x00001000; -pub const CR2: ::c_int = 0x00002000; -pub const CR3: ::c_int = 0x00003000; -pub const FF0: ::c_int = 0x00000000; -pub const FF1: ::c_int = 0x00004000; -pub const BS0: ::c_int = 0x00000000; -pub const BS1: ::c_int = 0x00008000; -pub const TAB3: ::c_int = 0x00000004; -pub const VT0: ::c_int = 0x00000000; -pub const VT1: ::c_int = 0x00010000; -pub const IUTF8: ::tcflag_t = 0x00004000; -pub const CRTSCTS: ::tcflag_t = 0x00030000; - -pub const NI_MAXHOST: ::socklen_t = 1025; - -pub const Q_GETQUOTA: ::c_int = 0x300; -pub const Q_SETQUOTA: ::c_int = 0x400; - -pub const RTLD_LOCAL: ::c_int = 0x4; -pub const RTLD_FIRST: ::c_int = 0x100; -pub const RTLD_NODELETE: ::c_int = 0x80; -pub const RTLD_NOLOAD: ::c_int = 0x10; -pub const RTLD_GLOBAL: ::c_int = 0x8; - -pub const _WSTOPPED: ::c_int = 0o177; - -pub const LOG_NETINFO: ::c_int = 12 << 3; -pub const LOG_REMOTEAUTH: ::c_int = 13 << 3; -pub const LOG_INSTALL: ::c_int = 14 << 3; -pub const LOG_RAS: ::c_int = 15 << 3; -pub const LOG_LAUNCHD: ::c_int = 24 << 3; -pub const LOG_NFACILITIES: ::c_int = 25; - -pub const CTLTYPE: ::c_int = 0xf; -pub const CTLTYPE_NODE: ::c_int = 1; -pub const CTLTYPE_INT: ::c_int = 2; -pub const CTLTYPE_STRING: ::c_int = 3; -pub const CTLTYPE_QUAD: ::c_int = 4; -pub const CTLTYPE_OPAQUE: ::c_int = 5; -pub const CTLTYPE_STRUCT: ::c_int = CTLTYPE_OPAQUE; -pub const CTLFLAG_RD: ::c_int = 0x80000000; -pub const CTLFLAG_WR: ::c_int = 0x40000000; -pub const CTLFLAG_RW: ::c_int = CTLFLAG_RD | CTLFLAG_WR; -pub const CTLFLAG_NOLOCK: ::c_int = 0x20000000; -pub const CTLFLAG_ANYBODY: ::c_int = 0x10000000; -pub const CTLFLAG_SECURE: ::c_int = 0x08000000; -pub const CTLFLAG_MASKED: ::c_int = 0x04000000; -pub const CTLFLAG_NOAUTO: ::c_int = 0x02000000; -pub const CTLFLAG_KERN: ::c_int = 0x01000000; -pub const CTLFLAG_LOCKED: ::c_int = 0x00800000; -pub const CTLFLAG_OID2: ::c_int = 0x00400000; -pub const CTL_UNSPEC: ::c_int = 0; -pub const CTL_KERN: ::c_int = 1; -pub const CTL_VM: ::c_int = 2; -pub const CTL_VFS: ::c_int = 3; -pub const CTL_NET: ::c_int = 4; -pub const CTL_DEBUG: ::c_int = 5; -pub const CTL_HW: ::c_int = 6; -pub const CTL_MACHDEP: ::c_int = 7; -pub const CTL_USER: ::c_int = 8; -pub const CTL_MAXID: ::c_int = 9; -pub const KERN_OSTYPE: ::c_int = 1; -pub const KERN_OSRELEASE: ::c_int = 2; -pub const KERN_OSREV: ::c_int = 3; -pub const KERN_VERSION: ::c_int = 4; -pub const KERN_MAXVNODES: ::c_int = 5; -pub const KERN_MAXPROC: ::c_int = 6; -pub const KERN_MAXFILES: ::c_int = 7; -pub const KERN_ARGMAX: ::c_int = 8; -pub const KERN_SECURELVL: ::c_int = 9; -pub const KERN_HOSTNAME: ::c_int = 10; -pub const KERN_HOSTID: ::c_int = 11; -pub const KERN_CLOCKRATE: ::c_int = 12; -pub const KERN_VNODE: ::c_int = 13; -pub const KERN_PROC: ::c_int = 14; -pub const KERN_FILE: ::c_int = 15; -pub const KERN_PROF: ::c_int = 16; -pub const KERN_POSIX1: ::c_int = 17; -pub const KERN_NGROUPS: ::c_int = 18; -pub const KERN_JOB_CONTROL: ::c_int = 19; -pub const KERN_SAVED_IDS: ::c_int = 20; -pub const KERN_BOOTTIME: ::c_int = 21; -pub const KERN_NISDOMAINNAME: ::c_int = 22; -pub const KERN_DOMAINNAME: ::c_int = KERN_NISDOMAINNAME; -pub const KERN_MAXPARTITIONS: ::c_int = 23; -pub const KERN_KDEBUG: ::c_int = 24; -pub const KERN_UPDATEINTERVAL: ::c_int = 25; -pub const KERN_OSRELDATE: ::c_int = 26; -pub const KERN_NTP_PLL: ::c_int = 27; -pub const KERN_BOOTFILE: ::c_int = 28; -pub const KERN_MAXFILESPERPROC: ::c_int = 29; -pub const KERN_MAXPROCPERUID: ::c_int = 30; -pub const KERN_DUMPDEV: ::c_int = 31; -pub const KERN_IPC: ::c_int = 32; -pub const KERN_DUMMY: ::c_int = 33; -pub const KERN_PS_STRINGS: ::c_int = 34; -pub const KERN_USRSTACK32: ::c_int = 35; -pub const KERN_LOGSIGEXIT: ::c_int = 36; -pub const KERN_SYMFILE: ::c_int = 37; -pub const KERN_PROCARGS: ::c_int = 38; -pub const KERN_NETBOOT: ::c_int = 40; -pub const KERN_SYSV: ::c_int = 42; -pub const KERN_AFFINITY: ::c_int = 43; -pub const KERN_TRANSLATE: ::c_int = 44; -pub const KERN_CLASSIC: ::c_int = KERN_TRANSLATE; -pub const KERN_EXEC: ::c_int = 45; -pub const KERN_CLASSICHANDLER: ::c_int = KERN_EXEC; -pub const KERN_AIOMAX: ::c_int = 46; -pub const KERN_AIOPROCMAX: ::c_int = 47; -pub const KERN_AIOTHREADS: ::c_int = 48; -pub const KERN_COREFILE: ::c_int = 50; -pub const KERN_COREDUMP: ::c_int = 51; -pub const KERN_SUGID_COREDUMP: ::c_int = 52; -pub const KERN_PROCDELAYTERM: ::c_int = 53; -pub const KERN_SHREG_PRIVATIZABLE: ::c_int = 54; -pub const KERN_LOW_PRI_WINDOW: ::c_int = 56; -pub const KERN_LOW_PRI_DELAY: ::c_int = 57; -pub const KERN_POSIX: ::c_int = 58; -pub const KERN_USRSTACK64: ::c_int = 59; -pub const KERN_NX_PROTECTION: ::c_int = 60; -pub const KERN_TFP: ::c_int = 61; -pub const KERN_PROCNAME: ::c_int = 62; -pub const KERN_THALTSTACK: ::c_int = 63; -pub const KERN_SPECULATIVE_READS: ::c_int = 64; -pub const KERN_OSVERSION: ::c_int = 65; -pub const KERN_SAFEBOOT: ::c_int = 66; -pub const KERN_RAGEVNODE: ::c_int = 68; -pub const KERN_TTY: ::c_int = 69; -pub const KERN_CHECKOPENEVT: ::c_int = 70; -pub const KERN_THREADNAME: ::c_int = 71; -pub const KERN_MAXID: ::c_int = 72; -pub const KERN_RAGE_PROC: ::c_int = 1; -pub const KERN_RAGE_THREAD: ::c_int = 2; -pub const KERN_UNRAGE_PROC: ::c_int = 3; -pub const KERN_UNRAGE_THREAD: ::c_int = 4; -pub const KERN_OPENEVT_PROC: ::c_int = 1; -pub const KERN_UNOPENEVT_PROC: ::c_int = 2; -pub const KERN_TFP_POLICY: ::c_int = 1; -pub const KERN_TFP_POLICY_DENY: ::c_int = 0; -pub const KERN_TFP_POLICY_DEFAULT: ::c_int = 2; -pub const KERN_KDEFLAGS: ::c_int = 1; -pub const KERN_KDDFLAGS: ::c_int = 2; -pub const KERN_KDENABLE: ::c_int = 3; -pub const KERN_KDSETBUF: ::c_int = 4; -pub const KERN_KDGETBUF: ::c_int = 5; -pub const KERN_KDSETUP: ::c_int = 6; -pub const KERN_KDREMOVE: ::c_int = 7; -pub const KERN_KDSETREG: ::c_int = 8; -pub const KERN_KDGETREG: ::c_int = 9; -pub const KERN_KDREADTR: ::c_int = 10; -pub const KERN_KDPIDTR: ::c_int = 11; -pub const KERN_KDTHRMAP: ::c_int = 12; -pub const KERN_KDPIDEX: ::c_int = 14; -pub const KERN_KDSETRTCDEC: ::c_int = 15; -pub const KERN_KDGETENTROPY: ::c_int = 16; -pub const KERN_KDWRITETR: ::c_int = 17; -pub const KERN_KDWRITEMAP: ::c_int = 18; -pub const KERN_KDENABLE_BG_TRACE: ::c_int = 19; -pub const KERN_KDDISABLE_BG_TRACE: ::c_int = 20; -pub const KERN_KDREADCURTHRMAP: ::c_int = 21; -pub const KERN_KDSET_TYPEFILTER: ::c_int = 22; -pub const KERN_KDBUFWAIT: ::c_int = 23; -pub const KERN_KDCPUMAP: ::c_int = 24; -pub const KERN_PROC_ALL: ::c_int = 0; -pub const KERN_PROC_PID: ::c_int = 1; -pub const KERN_PROC_PGRP: ::c_int = 2; -pub const KERN_PROC_SESSION: ::c_int = 3; -pub const KERN_PROC_TTY: ::c_int = 4; -pub const KERN_PROC_UID: ::c_int = 5; -pub const KERN_PROC_RUID: ::c_int = 6; -pub const KERN_PROC_LCID: ::c_int = 7; -pub const KIPC_MAXSOCKBUF: ::c_int = 1; -pub const KIPC_SOCKBUF_WASTE: ::c_int = 2; -pub const KIPC_SOMAXCONN: ::c_int = 3; -pub const KIPC_MAX_LINKHDR: ::c_int = 4; -pub const KIPC_MAX_PROTOHDR: ::c_int = 5; -pub const KIPC_MAX_HDR: ::c_int = 6; -pub const KIPC_MAX_DATALEN: ::c_int = 7; -pub const KIPC_MBSTAT: ::c_int = 8; -pub const KIPC_NMBCLUSTERS: ::c_int = 9; -pub const KIPC_SOQLIMITCOMPAT: ::c_int = 10; -pub const VM_METER: ::c_int = 1; -pub const VM_LOADAVG: ::c_int = 2; -pub const VM_MACHFACTOR: ::c_int = 4; -pub const VM_SWAPUSAGE: ::c_int = 5; -pub const VM_MAXID: ::c_int = 6; -pub const HW_MACHINE: ::c_int = 1; -pub const HW_MODEL: ::c_int = 2; -pub const HW_NCPU: ::c_int = 3; -pub const HW_BYTEORDER: ::c_int = 4; -pub const HW_PHYSMEM: ::c_int = 5; -pub const HW_USERMEM: ::c_int = 6; -pub const HW_PAGESIZE: ::c_int = 7; -pub const HW_DISKNAMES: ::c_int = 8; -pub const HW_DISKSTATS: ::c_int = 9; -pub const HW_EPOCH: ::c_int = 10; -pub const HW_FLOATINGPT: ::c_int = 11; -pub const HW_MACHINE_ARCH: ::c_int = 12; -pub const HW_VECTORUNIT: ::c_int = 13; -pub const HW_BUS_FREQ: ::c_int = 14; -pub const HW_CPU_FREQ: ::c_int = 15; -pub const HW_CACHELINE: ::c_int = 16; -pub const HW_L1ICACHESIZE: ::c_int = 17; -pub const HW_L1DCACHESIZE: ::c_int = 18; -pub const HW_L2SETTINGS: ::c_int = 19; -pub const HW_L2CACHESIZE: ::c_int = 20; -pub const HW_L3SETTINGS: ::c_int = 21; -pub const HW_L3CACHESIZE: ::c_int = 22; -pub const HW_TB_FREQ: ::c_int = 23; -pub const HW_MEMSIZE: ::c_int = 24; -pub const HW_AVAILCPU: ::c_int = 25; -pub const HW_MAXID: ::c_int = 26; -pub const USER_CS_PATH: ::c_int = 1; -pub const USER_BC_BASE_MAX: ::c_int = 2; -pub const USER_BC_DIM_MAX: ::c_int = 3; -pub const USER_BC_SCALE_MAX: ::c_int = 4; -pub const USER_BC_STRING_MAX: ::c_int = 5; -pub const USER_COLL_WEIGHTS_MAX: ::c_int = 6; -pub const USER_EXPR_NEST_MAX: ::c_int = 7; -pub const USER_LINE_MAX: ::c_int = 8; -pub const USER_RE_DUP_MAX: ::c_int = 9; -pub const USER_POSIX2_VERSION: ::c_int = 10; -pub const USER_POSIX2_C_BIND: ::c_int = 11; -pub const USER_POSIX2_C_DEV: ::c_int = 12; -pub const USER_POSIX2_CHAR_TERM: ::c_int = 13; -pub const USER_POSIX2_FORT_DEV: ::c_int = 14; -pub const USER_POSIX2_FORT_RUN: ::c_int = 15; -pub const USER_POSIX2_LOCALEDEF: ::c_int = 16; -pub const USER_POSIX2_SW_DEV: ::c_int = 17; -pub const USER_POSIX2_UPE: ::c_int = 18; -pub const USER_STREAM_MAX: ::c_int = 19; -pub const USER_TZNAME_MAX: ::c_int = 20; -pub const USER_MAXID: ::c_int = 21; -pub const CTL_DEBUG_NAME: ::c_int = 0; -pub const CTL_DEBUG_VALUE: ::c_int = 1; -pub const CTL_DEBUG_MAXID: ::c_int = 20; - -pub const PRIO_DARWIN_THREAD: ::c_int = 3; -pub const PRIO_DARWIN_PROCESS: ::c_int = 4; -pub const PRIO_DARWIN_BG: ::c_int = 0x1000; -pub const PRIO_DARWIN_NONUI: ::c_int = 0x1001; - -pub const SEM_FAILED: *mut sem_t = -1isize as *mut ::sem_t; - -pub const SIGEV_NONE: ::c_int = 0; -pub const SIGEV_SIGNAL: ::c_int = 1; -pub const SIGEV_THREAD: ::c_int = 3; - -pub const AIO_CANCELED: ::c_int = 2; -pub const AIO_NOTCANCELED: ::c_int = 4; -pub const AIO_ALLDONE: ::c_int = 1; -pub const AIO_LISTIO_MAX: ::c_int = 16; -pub const LIO_NOP: ::c_int = 0; -pub const LIO_WRITE: ::c_int = 2; -pub const LIO_READ: ::c_int = 1; -pub const LIO_WAIT: ::c_int = 2; -pub const LIO_NOWAIT: ::c_int = 1; - -pub const WEXITED: ::c_int = 0x00000004; -pub const WSTOPPED: ::c_int = 0x00000008; -pub const WCONTINUED: ::c_int = 0x00000010; -pub const WNOWAIT: ::c_int = 0x00000020; - -pub const P_ALL: idtype_t = 0; -pub const P_PID: idtype_t = 1; -pub const P_PGID: idtype_t = 2; - -pub const XATTR_NOFOLLOW: ::c_int = 0x0001; -pub const XATTR_CREATE: ::c_int = 0x0002; -pub const XATTR_REPLACE: ::c_int = 0x0004; -pub const XATTR_NOSECURITY: ::c_int = 0x0008; -pub const XATTR_NODEFAULT: ::c_int = 0x0010; -pub const XATTR_SHOWCOMPRESSION: ::c_int = 0x0020; - -pub const NET_RT_IFLIST2: ::c_int = 0x0006; - -// net/route.h -pub const RTF_UP: ::c_int = 0x1; -pub const RTF_GATEWAY: ::c_int = 0x2; -pub const RTF_HOST: ::c_int = 0x4; -pub const RTF_REJECT: ::c_int = 0x8; -pub const RTF_DYNAMIC: ::c_int = 0x10; -pub const RTF_MODIFIED: ::c_int = 0x20; -pub const RTF_DONE: ::c_int = 0x40; -pub const RTF_DELCLONE: ::c_int = 0x80; -pub const RTF_CLONING: ::c_int = 0x100; -pub const RTF_XRESOLVE: ::c_int = 0x200; -pub const RTF_LLINFO: ::c_int = 0x400; -pub const RTF_STATIC: ::c_int = 0x800; -pub const RTF_BLACKHOLE: ::c_int = 0x1000; -pub const RTF_NOIFREF: ::c_int = 0x2000; -pub const RTF_PROTO2: ::c_int = 0x4000; -pub const RTF_PROTO1: ::c_int = 0x8000; -pub const RTF_PRCLONING: ::c_int = 0x10000; -pub const RTF_WASCLONED: ::c_int = 0x20000; -pub const RTF_PROTO3: ::c_int = 0x40000; -pub const RTF_PINNED: ::c_int = 0x100000; -pub const RTF_LOCAL: ::c_int = 0x200000; -pub const RTF_BROADCAST: ::c_int = 0x400000; -pub const RTF_MULTICAST: ::c_int = 0x800000; -pub const RTF_IFSCOPE: ::c_int = 0x1000000; -pub const RTF_CONDEMNED: ::c_int = 0x2000000; -pub const RTF_IFREF: ::c_int = 0x4000000; -pub const RTF_PROXY: ::c_int = 0x8000000; -pub const RTF_ROUTER: ::c_int = 0x10000000; - -pub const RTM_VERSION: ::c_int = 5; - -// Message types -pub const RTM_ADD: ::c_int = 0x1; -pub const RTM_DELETE: ::c_int = 0x2; -pub const RTM_CHANGE: ::c_int = 0x3; -pub const RTM_GET: ::c_int = 0x4; -pub const RTM_LOSING: ::c_int = 0x5; -pub const RTM_REDIRECT: ::c_int = 0x6; -pub const RTM_MISS: ::c_int = 0x7; -pub const RTM_LOCK: ::c_int = 0x8; -pub const RTM_OLDADD: ::c_int = 0x9; -pub const RTM_OLDDEL: ::c_int = 0xa; -pub const RTM_RESOLVE: ::c_int = 0xb; -pub const RTM_NEWADDR: ::c_int = 0xc; -pub const RTM_DELADDR: ::c_int = 0xd; -pub const RTM_IFINFO: ::c_int = 0xe; -pub const RTM_NEWMADDR: ::c_int = 0xf; -pub const RTM_DELMADDR: ::c_int = 0x10; -pub const RTM_IFINFO2: ::c_int = 0x12; -pub const RTM_NEWMADDR2: ::c_int = 0x13; -pub const RTM_GET2: ::c_int = 0x14; - -// Bitmask values for rtm_inits and rmx_locks. -pub const RTV_MTU: ::c_int = 0x1; -pub const RTV_HOPCOUNT: ::c_int = 0x2; -pub const RTV_EXPIRE: ::c_int = 0x4; -pub const RTV_RPIPE: ::c_int = 0x8; -pub const RTV_SPIPE: ::c_int = 0x10; -pub const RTV_SSTHRESH: ::c_int = 0x20; -pub const RTV_RTT: ::c_int = 0x40; -pub const RTV_RTTVAR: ::c_int = 0x80; - -// Bitmask values for rtm_addrs. -pub const RTA_DST: ::c_int = 0x1; -pub const RTA_GATEWAY: ::c_int = 0x2; -pub const RTA_NETMASK: ::c_int = 0x4; -pub const RTA_GENMASK: ::c_int = 0x8; -pub const RTA_IFP: ::c_int = 0x10; -pub const RTA_IFA: ::c_int = 0x20; -pub const RTA_AUTHOR: ::c_int = 0x40; -pub const RTA_BRD: ::c_int = 0x80; - -// Index offsets for sockaddr array for alternate internal encoding. -pub const RTAX_DST: ::c_int = 0; -pub const RTAX_GATEWAY: ::c_int = 1; -pub const RTAX_NETMASK: ::c_int = 2; -pub const RTAX_GENMASK: ::c_int = 3; -pub const RTAX_IFP: ::c_int = 4; -pub const RTAX_IFA: ::c_int = 5; -pub const RTAX_AUTHOR: ::c_int = 6; -pub const RTAX_BRD: ::c_int = 7; -pub const RTAX_MAX: ::c_int = 8; - -pub const KERN_PROCARGS2: ::c_int = 49; - -pub const PROC_PIDTASKALLINFO: ::c_int = 2; -pub const PROC_PIDTASKINFO: ::c_int = 4; -pub const PROC_PIDTHREADINFO: ::c_int = 5; -pub const MAXCOMLEN: usize = 16; -pub const MAXTHREADNAMESIZE: usize = 64; - -pub const XUCRED_VERSION: ::c_uint = 0; - -pub const LC_SEGMENT: u32 = 0x1; -pub const LC_SEGMENT_64: u32 = 0x19; - -pub const MH_MAGIC: u32 = 0xfeedface; -pub const MH_MAGIC_64: u32 = 0xfeedfacf; - -// net/if_utun.h -pub const UTUN_OPT_FLAGS: ::c_int = 1; -pub const UTUN_OPT_IFNAME: ::c_int = 2; - -// net/bpf.h -pub const DLT_NULL: ::c_uint = 0; // no link-layer encapsulation -pub const DLT_EN10MB: ::c_uint = 1; // Ethernet (10Mb) -pub const DLT_EN3MB: ::c_uint = 2; // Experimental Ethernet (3Mb) -pub const DLT_AX25: ::c_uint = 3; // Amateur Radio AX.25 -pub const DLT_PRONET: ::c_uint = 4; // Proteon ProNET Token Ring -pub const DLT_CHAOS: ::c_uint = 5; // Chaos -pub const DLT_IEEE802: ::c_uint = 6; // IEEE 802 Networks -pub const DLT_ARCNET: ::c_uint = 7; // ARCNET -pub const DLT_SLIP: ::c_uint = 8; // Serial Line IP -pub const DLT_PPP: ::c_uint = 9; // Point-to-point Protocol -pub const DLT_FDDI: ::c_uint = 10; // FDDI -pub const DLT_ATM_RFC1483: ::c_uint = 11; // LLC/SNAP encapsulated atm -pub const DLT_RAW: ::c_uint = 12; // raw IP -pub const DLT_LOOP: ::c_uint = 108; - -// https://github.com/apple/darwin-xnu/blob/master/bsd/net/bpf.h#L100 -// sizeof(int32_t) -pub const BPF_ALIGNMENT: ::c_int = 4; - -f! { - pub fn WSTOPSIG(status: ::c_int) -> ::c_int { - status >> 8 - } - - pub fn _WSTATUS(status: ::c_int) -> ::c_int { - status & 0x7f - } - - pub fn WIFCONTINUED(status: ::c_int) -> bool { - _WSTATUS(status) == _WSTOPPED && WSTOPSIG(status) == 0x13 - } - - pub fn WIFSIGNALED(status: ::c_int) -> bool { - _WSTATUS(status) != _WSTOPPED && _WSTATUS(status) != 0 - } - - pub fn WIFSTOPPED(status: ::c_int) -> bool { - _WSTATUS(status) == _WSTOPPED && WSTOPSIG(status) != 0x13 - } -} - -extern { - pub fn aio_read(aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_write(aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_fsync(op: ::c_int, aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_error(aiocbp: *const aiocb) -> ::c_int; - pub fn aio_return(aiocbp: *mut aiocb) -> ::ssize_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "aio_suspend$UNIX2003")] - pub fn aio_suspend(aiocb_list: *const *const aiocb, nitems: ::c_int, - timeout: *const ::timespec) -> ::c_int; - pub fn aio_cancel(fd: ::c_int, aiocbp: *mut aiocb) -> ::c_int; - pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn lio_listio(mode: ::c_int, aiocb_list: *const *mut aiocb, - nitems: ::c_int, sevp: *mut sigevent) -> ::c_int; - - pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; - - pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; - - pub fn getutxent() -> *mut utmpx; - pub fn getutxid(ut: *const utmpx) -> *mut utmpx; - pub fn getutxline(ut: *const utmpx) -> *mut utmpx; - pub fn pututxline(ut: *const utmpx) -> *mut utmpx; - pub fn setutxent(); - pub fn endutxent(); - pub fn utmpxname(file: *const ::c_char) -> ::c_int; - - pub fn getnameinfo(sa: *const ::sockaddr, - salen: ::socklen_t, - host: *mut ::c_char, - hostlen: ::socklen_t, - serv: *mut ::c_char, - sevlen: ::socklen_t, - flags: ::c_int) -> ::c_int; - pub fn mincore(addr: *const ::c_void, len: ::size_t, - vec: *mut ::c_char) -> ::c_int; - pub fn sysctlnametomib(name: *const ::c_char, - mibp: *mut ::c_int, - sizep: *mut ::size_t) - -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "mprotect$UNIX2003")] - pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) - -> ::c_int; - pub fn shm_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::c_int; - pub fn sysctl(name: *mut ::c_int, - namelen: ::c_uint, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *mut ::c_void, - newlen: ::size_t) - -> ::c_int; - pub fn sysctlbyname(name: *const ::c_char, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *mut ::c_void, - newlen: ::size_t) - -> ::c_int; - pub fn mach_absolute_time() -> u64; - pub fn mach_timebase_info(info: *mut ::mach_timebase_info) -> ::c_int; - pub fn pthread_setname_np(name: *const ::c_char) -> ::c_int; - pub fn pthread_get_stackaddr_np(thread: ::pthread_t) -> *mut ::c_void; - pub fn pthread_get_stacksize_np(thread: ::pthread_t) -> ::size_t; - pub fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, - pshared: ::c_int) -> ::c_int; - pub fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, - pshared: *mut ::c_int) -> ::c_int; - pub fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, - pshared: ::c_int) -> ::c_int; - pub fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, - pshared: *mut ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, - val: *mut ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, - val: ::c_int) -> ::c_int; - pub fn __error() -> *mut ::c_int; - pub fn backtrace(buf: *mut *mut ::c_void, - sz: ::c_int) -> ::c_int; - #[cfg_attr(target_os = "macos", link_name = "statfs$INODE64")] - pub fn statfs(path: *const ::c_char, buf: *mut statfs) -> ::c_int; - #[cfg_attr(target_os = "macos", link_name = "fstatfs$INODE64")] - pub fn fstatfs(fd: ::c_int, buf: *mut statfs) -> ::c_int; - pub fn kevent(kq: ::c_int, - changelist: *const ::kevent, - nchanges: ::c_int, - eventlist: *mut ::kevent, - nevents: ::c_int, - timeout: *const ::timespec) -> ::c_int; - pub fn kevent64(kq: ::c_int, - changelist: *const ::kevent64_s, - nchanges: ::c_int, - eventlist: *mut ::kevent64_s, - nevents: ::c_int, - flags: ::c_uint, - timeout: *const ::timespec) -> ::c_int; - pub fn mount(src: *const ::c_char, - target: *const ::c_char, - flags: ::c_int, - data: *mut ::c_void) -> ::c_int; - pub fn ptrace(request: ::c_int, - pid: ::pid_t, - addr: *mut ::c_char, - data: ::c_int) -> ::c_int; - pub fn quotactl(special: *const ::c_char, - cmd: ::c_int, - id: ::c_int, - data: *mut ::c_char) -> ::c_int; - pub fn sethostname(name: *const ::c_char, len: ::c_int) -> ::c_int; - pub fn sendfile(fd: ::c_int, - s: ::c_int, - offset: ::off_t, - len: *mut ::off_t, - hdtr: *mut ::sf_hdtr, - flags: ::c_int) -> ::c_int; - pub fn openpty(amaster: *mut ::c_int, - aslave: *mut ::c_int, - name: *mut ::c_char, - termp: *mut termios, - winp: *mut ::winsize) -> ::c_int; - pub fn forkpty(amaster: *mut ::c_int, - name: *mut ::c_char, - termp: *mut termios, - winp: *mut ::winsize) -> ::pid_t; - pub fn duplocale(base: ::locale_t) -> ::locale_t; - pub fn freelocale(loc: ::locale_t) -> ::c_int; - pub fn localeconv_l(loc: ::locale_t) -> *mut lconv; - pub fn newlocale(mask: ::c_int, - locale: *const ::c_char, - base: ::locale_t) -> ::locale_t; - pub fn uselocale(loc: ::locale_t) -> ::locale_t; - pub fn querylocale(mask: ::c_int, loc: ::locale_t) -> *const ::c_char; - pub fn getpriority(which: ::c_int, who: ::id_t) -> ::c_int; - pub fn setpriority(which: ::c_int, who: ::id_t, prio: ::c_int) -> ::c_int; - - pub fn getxattr(path: *const ::c_char, name: *const ::c_char, - value: *mut ::c_void, size: ::size_t, position: u32, - flags: ::c_int) -> ::ssize_t; - pub fn fgetxattr(filedes: ::c_int, name: *const ::c_char, - value: *mut ::c_void, size: ::size_t, position: u32, - flags: ::c_int) -> ::ssize_t; - pub fn setxattr(path: *const ::c_char, name: *const ::c_char, - value: *const ::c_void, size: ::size_t, position: u32, - flags: ::c_int) -> ::c_int; - pub fn fsetxattr(filedes: ::c_int, name: *const ::c_char, - value: *const ::c_void, size: ::size_t, position: u32, - flags: ::c_int) -> ::c_int; - pub fn listxattr(path: *const ::c_char, list: *mut ::c_char, - size: ::size_t, flags: ::c_int) -> ::ssize_t; - pub fn flistxattr(filedes: ::c_int, list: *mut ::c_char, - size: ::size_t, flags: ::c_int) -> ::ssize_t; - pub fn removexattr(path: *const ::c_char, name: *const ::c_char, - flags: ::c_int) -> ::c_int; - pub fn fremovexattr(filedes: ::c_int, name: *const ::c_char, - flags: ::c_int) -> ::c_int; - - pub fn getgrouplist(name: *const ::c_char, - basegid: ::c_int, - groups: *mut ::c_int, - ngroups: *mut ::c_int) -> ::c_int; - pub fn initgroups(user: *const ::c_char, basegroup: ::c_int) -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "waitid$UNIX2003")] - pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, - options: ::c_int) -> ::c_int; - pub fn brk(addr: *const ::c_void) -> *mut ::c_void; - pub fn sbrk(increment: ::c_int) -> *mut ::c_void; - pub fn settimeofday(tv: *const ::timeval, tz: *const ::timezone) -> ::c_int; - pub fn _dyld_image_count() -> u32; - pub fn _dyld_get_image_header(image_index: u32) -> *const mach_header; - pub fn _dyld_get_image_vmaddr_slide(image_index: u32) -> ::intptr_t; - pub fn _dyld_get_image_name(image_index: u32) -> *const ::c_char; -} - -cfg_if! { - if #[cfg(any(target_arch = "arm", target_arch = "x86"))] { - mod b32; - pub use self::b32::*; - } else if #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] { - mod b64; - pub use self::b64::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/dragonfly/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/dragonfly/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/dragonfly/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/dragonfly/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,753 +0,0 @@ -pub type clock_t = u64; -pub type ino_t = u64; -pub type nlink_t = u32; -pub type blksize_t = i64; -pub type clockid_t = ::c_ulong; - -pub type c_long = i64; -pub type c_ulong = u64; -pub type time_t = i64; -pub type suseconds_t = i64; - -pub type uuid_t = ::uuid; - -pub type fsblkcnt_t = u64; -pub type fsfilcnt_t = u64; - -pub type sem_t = *mut sem; - -pub enum sem {} - -s! { - - pub struct exit_status { - pub e_termination: u16, - pub e_exit: u16 - } - - pub struct utmpx { - pub ut_name: [::c_char; 32], - pub ut_id: [::c_char; 4], - - pub ut_line: [::c_char; 32], - pub ut_host: [::c_char; 256], - - pub ut_unused: [u8; 16], - pub ut_session: u16, - pub ut_type: u16, - pub ut_pid: ::pid_t, - ut_exit: exit_status, - ut_ss: ::sockaddr_storage, - pub ut_tv: ::timeval, - pub ut_unused2: [u8; 16], - } - - pub struct aiocb { - pub aio_fildes: ::c_int, - pub aio_offset: ::off_t, - pub aio_buf: *mut ::c_void, - pub aio_nbytes: ::size_t, - pub aio_sigevent: sigevent, - pub aio_lio_opcode: ::c_int, - pub aio_reqprio: ::c_int, - _aio_val: ::c_int, - _aio_err: ::c_int - } - - pub struct dirent { - pub d_fileno: ::ino_t, - pub d_namlen: u16, - pub d_type: u8, - __unused1: u8, - __unused2: u32, - pub d_name: [::c_char; 256], - } - - pub struct uuid { - pub time_low: u32, - pub time_mid: u16, - pub time_hi_and_version: u16, - pub clock_seq_hi_and_reserved: u8, - pub clock_seq_low: u8, - pub node: [u8; 6], - } - - pub struct mq_attr { - pub mq_flags: ::c_long, - pub mq_maxmsg: ::c_long, - pub mq_msgsize: ::c_long, - pub mq_curmsgs: ::c_long, - } - - pub struct sigevent { - pub sigev_notify: ::c_int, - // The union is 8-byte in size, so it is aligned at a 8-byte offset. - #[cfg(target_pointer_width = "64")] - __unused1: ::c_int, - pub sigev_signo: ::c_int, //actually a union - // pad the union - #[cfg(target_pointer_width = "64")] - __unused2: ::c_int, - pub sigev_value: ::sigval, - __unused3: *mut ::c_void //actually a function pointer - } - - pub struct statvfs { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_favail: ::fsfilcnt_t, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - pub f_owner: ::uid_t, - pub f_type: ::c_uint, - pub f_syncreads: u64, - pub f_syncwrites: u64, - pub f_asyncreads: u64, - pub f_asyncwrites: u64, - pub f_fsid_uuid: ::uuid_t, - pub f_uid_uuid: ::uuid_t, - } - - pub struct stat { - pub st_ino: ::ino_t, - pub st_nlink: ::nlink_t, - pub st_dev: ::dev_t, - pub st_mode: ::mode_t, - pub st_padding1: ::uint16_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_size: ::off_t, - pub st_blocks: ::int64_t, - pub st_blksize: ::uint32_t, - pub st_flags: ::uint32_t, - pub st_gen: ::uint32_t, - pub st_lspare: ::int32_t, - pub st_qspare1: ::int64_t, - pub st_qspare2: ::int64_t, - } - - pub struct if_data { - pub ifi_type: ::c_uchar, - pub ifi_physical: ::c_uchar, - pub ifi_addrlen: ::c_uchar, - pub ifi_hdrlen: ::c_uchar, - pub ifi_recvquota: ::c_uchar, - pub ifi_xmitquota: ::c_uchar, - pub ifi_mtu: ::c_ulong, - pub ifi_metric: ::c_ulong, - pub ifi_link_state: ::c_ulong, - pub ifi_baudrate: u64, - pub ifi_ipackets: ::c_ulong, - pub ifi_ierrors: ::c_ulong, - pub ifi_opackets: ::c_ulong, - pub ifi_oerrors: ::c_ulong, - pub ifi_collisions: ::c_ulong, - pub ifi_ibytes: ::c_ulong, - pub ifi_obytes: ::c_ulong, - pub ifi_imcasts: ::c_ulong, - pub ifi_omcasts: ::c_ulong, - pub ifi_iqdrops: ::c_ulong, - pub ifi_noproto: ::c_ulong, - pub ifi_hwassist: ::c_ulong, - pub ifi_oqdrops: ::c_ulong, - pub ifi_lastchange: ::timeval, - } - - pub struct if_msghdr { - pub ifm_msglen: ::c_ushort, - pub ifm_version: ::c_uchar, - pub ifm_type: ::c_uchar, - pub ifm_addrs: ::c_int, - pub ifm_flags: ::c_int, - pub ifm_index: ::c_ushort, - pub ifm_data: if_data, - } - - pub struct sockaddr_dl { - pub sdl_len: ::c_uchar, - pub sdl_family: ::c_uchar, - pub sdl_index: ::c_ushort, - pub sdl_type: ::c_uchar, - pub sdl_nlen: ::c_uchar, - pub sdl_alen: ::c_uchar, - pub sdl_slen: ::c_uchar, - pub sdl_data: [::c_char; 12], - pub sdl_rcf: ::c_ushort, - pub sdl_route: [::c_ushort; 16], - } -} - -pub const RAND_MAX: ::c_int = 0x7fff_ffff; -pub const PTHREAD_STACK_MIN: ::size_t = 16384; -pub const SIGSTKSZ: ::size_t = 40960; -pub const MADV_INVAL: ::c_int = 10; -pub const MADV_SETMAP: ::c_int = 11; -pub const O_CLOEXEC: ::c_int = 0x00020000; -pub const O_DIRECTORY: ::c_int = 0x08000000; -pub const F_GETLK: ::c_int = 7; -pub const F_SETLK: ::c_int = 8; -pub const F_SETLKW: ::c_int = 9; -pub const ELAST: ::c_int = 99; -pub const RLIMIT_POSIXLOCKS: ::c_int = 11; -pub const RLIM_NLIMITS: ::rlim_t = 12; - -pub const Q_GETQUOTA: ::c_int = 0x300; -pub const Q_SETQUOTA: ::c_int = 0x400; - -pub const CLOCK_REALTIME: ::clockid_t = 0; -pub const CLOCK_VIRTUAL: ::clockid_t = 1; -pub const CLOCK_PROF: ::clockid_t = 2; -pub const CLOCK_MONOTONIC: ::clockid_t = 4; -pub const CLOCK_UPTIME: ::clockid_t = 5; -pub const CLOCK_UPTIME_PRECISE: ::clockid_t = 7; -pub const CLOCK_UPTIME_FAST: ::clockid_t = 8; -pub const CLOCK_REALTIME_PRECISE: ::clockid_t = 9; -pub const CLOCK_REALTIME_FAST: ::clockid_t = 10; -pub const CLOCK_MONOTONIC_PRECISE: ::clockid_t = 11; -pub const CLOCK_MONOTONIC_FAST: ::clockid_t = 12; -pub const CLOCK_SECOND: ::clockid_t = 13; -pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 14; -pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 15; - -pub const CTL_UNSPEC: ::c_int = 0; -pub const CTL_KERN: ::c_int = 1; -pub const CTL_VM: ::c_int = 2; -pub const CTL_VFS: ::c_int = 3; -pub const CTL_NET: ::c_int = 4; -pub const CTL_DEBUG: ::c_int = 5; -pub const CTL_HW: ::c_int = 6; -pub const CTL_MACHDEP: ::c_int = 7; -pub const CTL_USER: ::c_int = 8; -pub const CTL_P1003_1B: ::c_int = 9; -pub const CTL_LWKT: ::c_int = 10; -pub const CTL_MAXID: ::c_int = 11; -pub const KERN_OSTYPE: ::c_int = 1; -pub const KERN_OSRELEASE: ::c_int = 2; -pub const KERN_OSREV: ::c_int = 3; -pub const KERN_VERSION: ::c_int = 4; -pub const KERN_MAXVNODES: ::c_int = 5; -pub const KERN_MAXPROC: ::c_int = 6; -pub const KERN_MAXFILES: ::c_int = 7; -pub const KERN_ARGMAX: ::c_int = 8; -pub const KERN_SECURELVL: ::c_int = 9; -pub const KERN_HOSTNAME: ::c_int = 10; -pub const KERN_HOSTID: ::c_int = 11; -pub const KERN_CLOCKRATE: ::c_int = 12; -pub const KERN_VNODE: ::c_int = 13; -pub const KERN_PROC: ::c_int = 14; -pub const KERN_FILE: ::c_int = 15; -pub const KERN_PROF: ::c_int = 16; -pub const KERN_POSIX1: ::c_int = 17; -pub const KERN_NGROUPS: ::c_int = 18; -pub const KERN_JOB_CONTROL: ::c_int = 19; -pub const KERN_SAVED_IDS: ::c_int = 20; -pub const KERN_BOOTTIME: ::c_int = 21; -pub const KERN_NISDOMAINNAME: ::c_int = 22; -pub const KERN_UPDATEINTERVAL: ::c_int = 23; -pub const KERN_OSRELDATE: ::c_int = 24; -pub const KERN_NTP_PLL: ::c_int = 25; -pub const KERN_BOOTFILE: ::c_int = 26; -pub const KERN_MAXFILESPERPROC: ::c_int = 27; -pub const KERN_MAXPROCPERUID: ::c_int = 28; -pub const KERN_DUMPDEV: ::c_int = 29; -pub const KERN_IPC: ::c_int = 30; -pub const KERN_DUMMY: ::c_int = 31; -pub const KERN_PS_STRINGS: ::c_int = 32; -pub const KERN_USRSTACK: ::c_int = 33; -pub const KERN_LOGSIGEXIT: ::c_int = 34; -pub const KERN_IOV_MAX: ::c_int = 35; -pub const KERN_MAXPOSIXLOCKSPERUID: ::c_int = 36; -pub const KERN_MAXID: ::c_int = 37; -pub const KERN_PROC_ALL: ::c_int = 0; -pub const KERN_PROC_PID: ::c_int = 1; -pub const KERN_PROC_PGRP: ::c_int = 2; -pub const KERN_PROC_SESSION: ::c_int = 3; -pub const KERN_PROC_TTY: ::c_int = 4; -pub const KERN_PROC_UID: ::c_int = 5; -pub const KERN_PROC_RUID: ::c_int = 6; -pub const KERN_PROC_ARGS: ::c_int = 7; -pub const KERN_PROC_CWD: ::c_int = 8; -pub const KERN_PROC_PATHNAME: ::c_int = 9; -pub const KERN_PROC_FLAGMASK: ::c_int = 0x10; -pub const KERN_PROC_FLAG_LWP: ::c_int = 0x10; -pub const KIPC_MAXSOCKBUF: ::c_int = 1; -pub const KIPC_SOCKBUF_WASTE: ::c_int = 2; -pub const KIPC_SOMAXCONN: ::c_int = 3; -pub const KIPC_MAX_LINKHDR: ::c_int = 4; -pub const KIPC_MAX_PROTOHDR: ::c_int = 5; -pub const KIPC_MAX_HDR: ::c_int = 6; -pub const KIPC_MAX_DATALEN: ::c_int = 7; -pub const KIPC_MBSTAT: ::c_int = 8; -pub const KIPC_NMBCLUSTERS: ::c_int = 9; -pub const HW_MACHINE: ::c_int = 1; -pub const HW_MODEL: ::c_int = 2; -pub const HW_NCPU: ::c_int = 3; -pub const HW_BYTEORDER: ::c_int = 4; -pub const HW_PHYSMEM: ::c_int = 5; -pub const HW_USERMEM: ::c_int = 6; -pub const HW_PAGESIZE: ::c_int = 7; -pub const HW_DISKNAMES: ::c_int = 8; -pub const HW_DISKSTATS: ::c_int = 9; -pub const HW_FLOATINGPT: ::c_int = 10; -pub const HW_MACHINE_ARCH: ::c_int = 11; -pub const HW_MACHINE_PLATFORM: ::c_int = 12; -pub const HW_SENSORS: ::c_int = 13; -pub const HW_MAXID: ::c_int = 14; -pub const USER_CS_PATH: ::c_int = 1; -pub const USER_BC_BASE_MAX: ::c_int = 2; -pub const USER_BC_DIM_MAX: ::c_int = 3; -pub const USER_BC_SCALE_MAX: ::c_int = 4; -pub const USER_BC_STRING_MAX: ::c_int = 5; -pub const USER_COLL_WEIGHTS_MAX: ::c_int = 6; -pub const USER_EXPR_NEST_MAX: ::c_int = 7; -pub const USER_LINE_MAX: ::c_int = 8; -pub const USER_RE_DUP_MAX: ::c_int = 9; -pub const USER_POSIX2_VERSION: ::c_int = 10; -pub const USER_POSIX2_C_BIND: ::c_int = 11; -pub const USER_POSIX2_C_DEV: ::c_int = 12; -pub const USER_POSIX2_CHAR_TERM: ::c_int = 13; -pub const USER_POSIX2_FORT_DEV: ::c_int = 14; -pub const USER_POSIX2_FORT_RUN: ::c_int = 15; -pub const USER_POSIX2_LOCALEDEF: ::c_int = 16; -pub const USER_POSIX2_SW_DEV: ::c_int = 17; -pub const USER_POSIX2_UPE: ::c_int = 18; -pub const USER_STREAM_MAX: ::c_int = 19; -pub const USER_TZNAME_MAX: ::c_int = 20; -pub const USER_MAXID: ::c_int = 21; -pub const CTL_P1003_1B_ASYNCHRONOUS_IO: ::c_int = 1; -pub const CTL_P1003_1B_MAPPED_FILES: ::c_int = 2; -pub const CTL_P1003_1B_MEMLOCK: ::c_int = 3; -pub const CTL_P1003_1B_MEMLOCK_RANGE: ::c_int = 4; -pub const CTL_P1003_1B_MEMORY_PROTECTION: ::c_int = 5; -pub const CTL_P1003_1B_MESSAGE_PASSING: ::c_int = 6; -pub const CTL_P1003_1B_PRIORITIZED_IO: ::c_int = 7; -pub const CTL_P1003_1B_PRIORITY_SCHEDULING: ::c_int = 8; -pub const CTL_P1003_1B_REALTIME_SIGNALS: ::c_int = 9; -pub const CTL_P1003_1B_SEMAPHORES: ::c_int = 10; -pub const CTL_P1003_1B_FSYNC: ::c_int = 11; -pub const CTL_P1003_1B_SHARED_MEMORY_OBJECTS: ::c_int = 12; -pub const CTL_P1003_1B_SYNCHRONIZED_IO: ::c_int = 13; -pub const CTL_P1003_1B_TIMERS: ::c_int = 14; -pub const CTL_P1003_1B_AIO_LISTIO_MAX: ::c_int = 15; -pub const CTL_P1003_1B_AIO_MAX: ::c_int = 16; -pub const CTL_P1003_1B_AIO_PRIO_DELTA_MAX: ::c_int = 17; -pub const CTL_P1003_1B_DELAYTIMER_MAX: ::c_int = 18; -pub const CTL_P1003_1B_UNUSED1: ::c_int = 19; -pub const CTL_P1003_1B_PAGESIZE: ::c_int = 20; -pub const CTL_P1003_1B_RTSIG_MAX: ::c_int = 21; -pub const CTL_P1003_1B_SEM_NSEMS_MAX: ::c_int = 22; -pub const CTL_P1003_1B_SEM_VALUE_MAX: ::c_int = 23; -pub const CTL_P1003_1B_SIGQUEUE_MAX: ::c_int = 24; -pub const CTL_P1003_1B_TIMER_MAX: ::c_int = 25; -pub const CTL_P1003_1B_MAXID: ::c_int = 26; - -pub const EVFILT_READ: ::int16_t = -1; -pub const EVFILT_WRITE: ::int16_t = -2; -pub const EVFILT_AIO: ::int16_t = -3; -pub const EVFILT_VNODE: ::int16_t = -4; -pub const EVFILT_PROC: ::int16_t = -5; -pub const EVFILT_SIGNAL: ::int16_t = -6; -pub const EVFILT_TIMER: ::int16_t = -7; -pub const EVFILT_EXCEPT: ::int16_t = -8; -pub const EVFILT_USER: ::int16_t = -9; -pub const EVFILT_FS: ::int16_t = -10; - -pub const EV_ADD: ::uint16_t = 0x1; -pub const EV_DELETE: ::uint16_t = 0x2; -pub const EV_ENABLE: ::uint16_t = 0x4; -pub const EV_DISABLE: ::uint16_t = 0x8; -pub const EV_ONESHOT: ::uint16_t = 0x10; -pub const EV_CLEAR: ::uint16_t = 0x20; -pub const EV_RECEIPT: ::uint16_t = 0x40; -pub const EV_DISPATCH: ::uint16_t = 0x80; -pub const EV_NODATA: ::uint16_t = 0x1000; -pub const EV_FLAG1: ::uint16_t = 0x2000; -pub const EV_ERROR: ::uint16_t = 0x4000; -pub const EV_EOF: ::uint16_t = 0x8000; -pub const EV_SYSFLAGS: ::uint16_t = 0xf000; - -pub const NOTE_TRIGGER: ::uint32_t = 0x01000000; -pub const NOTE_FFNOP: ::uint32_t = 0x00000000; -pub const NOTE_FFAND: ::uint32_t = 0x40000000; -pub const NOTE_FFOR: ::uint32_t = 0x80000000; -pub const NOTE_FFCOPY: ::uint32_t = 0xc0000000; -pub const NOTE_FFCTRLMASK: ::uint32_t = 0xc0000000; -pub const NOTE_FFLAGSMASK: ::uint32_t = 0x00ffffff; -pub const NOTE_LOWAT: ::uint32_t = 0x00000001; -pub const NOTE_OOB: ::uint32_t = 0x00000002; -pub const NOTE_DELETE: ::uint32_t = 0x00000001; -pub const NOTE_WRITE: ::uint32_t = 0x00000002; -pub const NOTE_EXTEND: ::uint32_t = 0x00000004; -pub const NOTE_ATTRIB: ::uint32_t = 0x00000008; -pub const NOTE_LINK: ::uint32_t = 0x00000010; -pub const NOTE_RENAME: ::uint32_t = 0x00000020; -pub const NOTE_REVOKE: ::uint32_t = 0x00000040; -pub const NOTE_EXIT: ::uint32_t = 0x80000000; -pub const NOTE_FORK: ::uint32_t = 0x40000000; -pub const NOTE_EXEC: ::uint32_t = 0x20000000; -pub const NOTE_PDATAMASK: ::uint32_t = 0x000fffff; -pub const NOTE_PCTRLMASK: ::uint32_t = 0xf0000000; -pub const NOTE_TRACK: ::uint32_t = 0x00000001; -pub const NOTE_TRACKERR: ::uint32_t = 0x00000002; -pub const NOTE_CHILD: ::uint32_t = 0x00000004; - -pub const SO_SNDSPACE: ::c_int = 0x100a; -pub const SO_CPUHINT: ::c_int = 0x1030; - -// https://github.com/DragonFlyBSD/DragonFlyBSD/blob/master/sys/net/if.h#L101 -pub const IFF_UP: ::c_int = 0x1; // interface is up -pub const IFF_BROADCAST: ::c_int = 0x2; // broadcast address valid -pub const IFF_DEBUG: ::c_int = 0x4; // turn on debugging -pub const IFF_LOOPBACK: ::c_int = 0x8; // is a loopback net -pub const IFF_POINTOPOINT: ::c_int = 0x10; // interface is point-to-point link -pub const IFF_SMART: ::c_int = 0x20; // interface manages own routes -pub const IFF_RUNNING: ::c_int = 0x40; // resources allocated -pub const IFF_NOARP: ::c_int = 0x80; // no address resolution protocol -pub const IFF_PROMISC: ::c_int = 0x100; // receive all packets -pub const IFF_ALLMULTI: ::c_int = 0x200; // receive all multicast packets -pub const IFF_OACTIVE_COMPAT: ::c_int = 0x400; // was transmission in progress -pub const IFF_SIMPLEX: ::c_int = 0x800; // can't hear own transmissions -pub const IFF_LINK0: ::c_int = 0x1000; // per link layer defined bit -pub const IFF_LINK1: ::c_int = 0x2000; // per link layer defined bit -pub const IFF_LINK2: ::c_int = 0x4000; // per link layer defined bit -pub const IFF_ALTPHYS: ::c_int = IFF_LINK2; // use alternate physical connection -pub const IFF_MULTICAST: ::c_int = 0x8000; // supports multicast -// was interface is in polling mode -pub const IFF_POLLING_COMPAT: ::c_int = 0x10000; -pub const IFF_PPROMISC: ::c_int = 0x20000; // user-requested promisc mode -pub const IFF_MONITOR: ::c_int = 0x40000; // user-requested monitor mode -pub const IFF_STATICARP: ::c_int = 0x80000; // static ARP -pub const IFF_NPOLLING: ::c_int = 0x100000; // interface is in polling mode -pub const IFF_IDIRECT: ::c_int = 0x200000; // direct input - -// -// sys/netinet/in.h -// Protocols (RFC 1700) -// NOTE: These are in addition to the constants defined in src/unix/mod.rs - -// IPPROTO_IP defined in src/unix/mod.rs -/// IP6 hop-by-hop options -pub const IPPROTO_HOPOPTS: ::c_int = 0; -// IPPROTO_ICMP defined in src/unix/mod.rs -/// group mgmt protocol -pub const IPPROTO_IGMP: ::c_int = 2; -/// gateway^2 (deprecated) -pub const IPPROTO_GGP: ::c_int = 3; -/// for compatibility -pub const IPPROTO_IPIP: ::c_int = 4; -// IPPROTO_TCP defined in src/unix/mod.rs -/// Stream protocol II. -pub const IPPROTO_ST: ::c_int = 7; -/// exterior gateway protocol -pub const IPPROTO_EGP: ::c_int = 8; -/// private interior gateway -pub const IPPROTO_PIGP: ::c_int = 9; -/// BBN RCC Monitoring -pub const IPPROTO_RCCMON: ::c_int = 10; -/// network voice protocol -pub const IPPROTO_NVPII: ::c_int = 11; -/// pup -pub const IPPROTO_PUP: ::c_int = 12; -/// Argus -pub const IPPROTO_ARGUS: ::c_int = 13; -/// EMCON -pub const IPPROTO_EMCON: ::c_int = 14; -/// Cross Net Debugger -pub const IPPROTO_XNET: ::c_int = 15; -/// Chaos -pub const IPPROTO_CHAOS: ::c_int = 16; -// IPPROTO_UDP defined in src/unix/mod.rs -/// Multiplexing -pub const IPPROTO_MUX: ::c_int = 18; -/// DCN Measurement Subsystems -pub const IPPROTO_MEAS: ::c_int = 19; -/// Host Monitoring -pub const IPPROTO_HMP: ::c_int = 20; -/// Packet Radio Measurement -pub const IPPROTO_PRM: ::c_int = 21; -/// xns idp -pub const IPPROTO_IDP: ::c_int = 22; -/// Trunk-1 -pub const IPPROTO_TRUNK1: ::c_int = 23; -/// Trunk-2 -pub const IPPROTO_TRUNK2: ::c_int = 24; -/// Leaf-1 -pub const IPPROTO_LEAF1: ::c_int = 25; -/// Leaf-2 -pub const IPPROTO_LEAF2: ::c_int = 26; -/// Reliable Data -pub const IPPROTO_RDP: ::c_int = 27; -/// Reliable Transaction -pub const IPPROTO_IRTP: ::c_int = 28; -/// tp-4 w/ class negotiation -pub const IPPROTO_TP: ::c_int = 29; -/// Bulk Data Transfer -pub const IPPROTO_BLT: ::c_int = 30; -/// Network Services -pub const IPPROTO_NSP: ::c_int = 31; -/// Merit Internodal -pub const IPPROTO_INP: ::c_int = 32; -/// Sequential Exchange -pub const IPPROTO_SEP: ::c_int = 33; -/// Third Party Connect -pub const IPPROTO_3PC: ::c_int = 34; -/// InterDomain Policy Routing -pub const IPPROTO_IDPR: ::c_int = 35; -/// XTP -pub const IPPROTO_XTP: ::c_int = 36; -/// Datagram Delivery -pub const IPPROTO_DDP: ::c_int = 37; -/// Control Message Transport -pub const IPPROTO_CMTP: ::c_int = 38; -/// TP++ Transport -pub const IPPROTO_TPXX: ::c_int = 39; -/// IL transport protocol -pub const IPPROTO_IL: ::c_int = 40; -// IPPROTO_IPV6 defined in src/unix/mod.rs -/// Source Demand Routing -pub const IPPROTO_SDRP: ::c_int = 42; -/// IP6 routing header -pub const IPPROTO_ROUTING: ::c_int = 43; -/// IP6 fragmentation header -pub const IPPROTO_FRAGMENT: ::c_int = 44; -/// InterDomain Routing -pub const IPPROTO_IDRP: ::c_int = 45; -/// resource reservation -pub const IPPROTO_RSVP: ::c_int = 46; -/// General Routing Encap. -pub const IPPROTO_GRE: ::c_int = 47; -/// Mobile Host Routing -pub const IPPROTO_MHRP: ::c_int = 48; -/// BHA -pub const IPPROTO_BHA: ::c_int = 49; -/// IP6 Encap Sec. Payload -pub const IPPROTO_ESP: ::c_int = 50; -/// IP6 Auth Header -pub const IPPROTO_AH: ::c_int = 51; -/// Integ. Net Layer Security -pub const IPPROTO_INLSP: ::c_int = 52; -/// IP with encryption -pub const IPPROTO_SWIPE: ::c_int = 53; -/// Next Hop Resolution -pub const IPPROTO_NHRP: ::c_int = 54; -/// IP Mobility -pub const IPPROTO_MOBILE: ::c_int = 55; -/// Transport Layer Security -pub const IPPROTO_TLSP: ::c_int = 56; -/// SKIP -pub const IPPROTO_SKIP: ::c_int = 57; -// IPPROTO_ICMPV6 defined in src/unix/mod.rs -/// IP6 no next header -pub const IPPROTO_NONE: ::c_int = 59; -/// IP6 destination option -pub const IPPROTO_DSTOPTS: ::c_int = 60; -/// any host internal protocol -pub const IPPROTO_AHIP: ::c_int = 61; -/// CFTP -pub const IPPROTO_CFTP: ::c_int = 62; -/// "hello" routing protocol -pub const IPPROTO_HELLO: ::c_int = 63; -/// SATNET/Backroom EXPAK -pub const IPPROTO_SATEXPAK: ::c_int = 64; -/// Kryptolan -pub const IPPROTO_KRYPTOLAN: ::c_int = 65; -/// Remote Virtual Disk -pub const IPPROTO_RVD: ::c_int = 66; -/// Pluribus Packet Core -pub const IPPROTO_IPPC: ::c_int = 67; -/// Any distributed FS -pub const IPPROTO_ADFS: ::c_int = 68; -/// Satnet Monitoring -pub const IPPROTO_SATMON: ::c_int = 69; -/// VISA Protocol -pub const IPPROTO_VISA: ::c_int = 70; -/// Packet Core Utility -pub const IPPROTO_IPCV: ::c_int = 71; -/// Comp. Prot. Net. Executive -pub const IPPROTO_CPNX: ::c_int = 72; -/// Comp. Prot. HeartBeat -pub const IPPROTO_CPHB: ::c_int = 73; -/// Wang Span Network -pub const IPPROTO_WSN: ::c_int = 74; -/// Packet Video Protocol -pub const IPPROTO_PVP: ::c_int = 75; -/// BackRoom SATNET Monitoring -pub const IPPROTO_BRSATMON: ::c_int = 76; -/// Sun net disk proto (temp.) -pub const IPPROTO_ND: ::c_int = 77; -/// WIDEBAND Monitoring -pub const IPPROTO_WBMON: ::c_int = 78; -/// WIDEBAND EXPAK -pub const IPPROTO_WBEXPAK: ::c_int = 79; -/// ISO cnlp -pub const IPPROTO_EON: ::c_int = 80; -/// VMTP -pub const IPPROTO_VMTP: ::c_int = 81; -/// Secure VMTP -pub const IPPROTO_SVMTP: ::c_int = 82; -/// Banyon VINES -pub const IPPROTO_VINES: ::c_int = 83; -/// TTP -pub const IPPROTO_TTP: ::c_int = 84; -/// NSFNET-IGP -pub const IPPROTO_IGP: ::c_int = 85; -/// dissimilar gateway prot. -pub const IPPROTO_DGP: ::c_int = 86; -/// TCF -pub const IPPROTO_TCF: ::c_int = 87; -/// Cisco/GXS IGRP -pub const IPPROTO_IGRP: ::c_int = 88; -/// OSPFIGP -pub const IPPROTO_OSPFIGP: ::c_int = 89; -/// Strite RPC protocol -pub const IPPROTO_SRPC: ::c_int = 90; -/// Locus Address Resoloution -pub const IPPROTO_LARP: ::c_int = 91; -/// Multicast Transport -pub const IPPROTO_MTP: ::c_int = 92; -/// AX.25 Frames -pub const IPPROTO_AX25: ::c_int = 93; -/// IP encapsulated in IP -pub const IPPROTO_IPEIP: ::c_int = 94; -/// Mobile Int.ing control -pub const IPPROTO_MICP: ::c_int = 95; -/// Semaphore Comm. security -pub const IPPROTO_SCCSP: ::c_int = 96; -/// Ethernet IP encapsulation -pub const IPPROTO_ETHERIP: ::c_int = 97; -/// encapsulation header -pub const IPPROTO_ENCAP: ::c_int = 98; -/// any private encr. scheme -pub const IPPROTO_APES: ::c_int = 99; -/// GMTP -pub const IPPROTO_GMTP: ::c_int = 100; -/// payload compression (IPComp) -pub const IPPROTO_IPCOMP: ::c_int = 108; - -/* 101-254: Partly Unassigned */ -/// Protocol Independent Mcast -pub const IPPROTO_PIM: ::c_int = 103; -/// CARP -pub const IPPROTO_CARP: ::c_int = 112; -/// PGM -pub const IPPROTO_PGM: ::c_int = 113; -/// PFSYNC -pub const IPPROTO_PFSYNC: ::c_int = 240; - -/* 255: Reserved */ -/* BSD Private, local use, namespace incursion, no longer used */ -/// divert pseudo-protocol -pub const IPPROTO_DIVERT: ::c_int = 254; -pub const IPPROTO_MAX: ::c_int = 256; -/// last return value of *_input(), meaning "all job for this pkt is done". -pub const IPPROTO_DONE: ::c_int = 257; - -/// Used by RSS: the layer3 protocol is unknown -pub const IPPROTO_UNKNOWN: ::c_int = 258; - -pub const AF_BLUETOOTH: ::c_int = 33; -pub const AF_MPLS: ::c_int = 34; -pub const AF_IEEE80211: ::c_int = 35; -pub const AF_MAX: ::c_int = 36; - -pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; -pub const PF_MAX: ::c_int = AF_MAX; - -pub const NET_RT_DUMP: ::c_int = 1; -pub const NET_RT_FLAGS: ::c_int = 2; -pub const NET_RT_IFLIST: ::c_int = 3; -pub const NET_RT_MAXID: ::c_int = 4; - -pub const SOMAXOPT_SIZE: ::c_int = 65536; - -#[doc(hidden)] -pub const NET_MAXID: ::c_int = AF_MAX; - -pub const MSG_UNUSED09: ::c_int = 0x00000200; -pub const MSG_NOSIGNAL: ::c_int = 0x00000400; -pub const MSG_SYNC: ::c_int = 0x00000800; -pub const MSG_CMSG_CLOEXEC: ::c_int = 0x00001000; -pub const MSG_FBLOCKING: ::c_int = 0x00010000; -pub const MSG_FNONBLOCKING: ::c_int = 0x00020000; -pub const MSG_FMASK: ::c_int = 0xFFFF0000; - -pub const EMPTY: ::c_short = 0; -pub const RUN_LVL: ::c_short = 1; -pub const BOOT_TIME: ::c_short = 2; -pub const OLD_TIME: ::c_short = 3; -pub const NEW_TIME: ::c_short = 4; -pub const INIT_PROCESS: ::c_short = 5; -pub const LOGIN_PROCESS: ::c_short = 6; -pub const USER_PROCESS: ::c_short = 7; -pub const DEAD_PROCESS: ::c_short = 8; - -pub const LC_COLLATE_MASK: ::c_int = (1 << 0); -pub const LC_CTYPE_MASK: ::c_int = (1 << 1); -pub const LC_MONETARY_MASK: ::c_int = (1 << 2); -pub const LC_NUMERIC_MASK: ::c_int = (1 << 3); -pub const LC_TIME_MASK: ::c_int = (1 << 4); -pub const LC_MESSAGES_MASK: ::c_int = (1 << 5); -pub const LC_ALL_MASK: ::c_int = LC_COLLATE_MASK - | LC_CTYPE_MASK - | LC_MESSAGES_MASK - | LC_MONETARY_MASK - | LC_NUMERIC_MASK - | LC_TIME_MASK; - -pub const TIOCSIG: ::c_uint = 0x2000745f; -pub const BTUARTDISC: ::c_int = 0x7; -pub const TIOCDCDTIMESTAMP: ::c_uint = 0x40107458; -pub const TIOCISPTMASTER: ::c_uint = 0x20007455; -pub const TIOCMODG: ::c_uint = 0x40047403; -pub const TIOCMODS: ::c_ulong = 0x80047404; -pub const TIOCREMOTE: ::c_ulong = 0x80047469; - -// Constants used by "at" family of system calls. -pub const AT_FDCWD: ::c_int = 0xFFFAFDCD; // invalid file descriptor -pub const AT_SYMLINK_NOFOLLOW: ::c_int = 1; -pub const AT_REMOVEDIR: ::c_int = 2; -pub const AT_EACCESS: ::c_int = 4; -pub const AT_SYMLINK_FOLLOW: ::c_int = 8; - -pub const VCHECKPT: usize = 19; - -pub const _PC_2_SYMLINKS: ::c_int = 22; -pub const _PC_TIMESTAMP_RESOLUTION: ::c_int = 23; - -pub const _SC_V7_ILP32_OFF32: ::c_int = 122; -pub const _SC_V7_ILP32_OFFBIG: ::c_int = 123; -pub const _SC_V7_LP64_OFF64: ::c_int = 124; -pub const _SC_V7_LPBIG_OFFBIG: ::c_int = 125; -pub const _SC_THREAD_ROBUST_PRIO_INHERIT: ::c_int = 126; -pub const _SC_THREAD_ROBUST_PRIO_PROTECT: ::c_int = 127; - -pub const WCONTINUED: ::c_int = 4; -pub const WSTOPPED: ::c_int = 0o177; - -extern { - pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) - -> ::c_int; - pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; - - pub fn setutxdb(_type: ::c_uint, file: *mut ::c_char) -> ::c_int; - - pub fn aio_waitcomplete(iocbp: *mut *mut aiocb, - timeout: *mut ::timespec) -> ::c_int; - - pub fn freelocale(loc: ::locale_t); -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/aarch64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/aarch64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -pub type c_long = i64; -pub type c_ulong = u64; -pub type time_t = i64; -pub type suseconds_t = i64; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_size: ::off_t, - pub st_blocks: ::blkcnt_t, - pub st_blksize: ::blksize_t, - pub st_flags: ::fflags_t, - pub st_gen: ::uint32_t, - pub st_lspare: ::int32_t, - pub st_birthtime: ::time_t, - pub st_birthtime_nsec: ::c_long, - } -} - -pub const MAP_32BIT: ::c_int = 0x00080000; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,911 +0,0 @@ -pub type fflags_t = u32; -pub type clock_t = i32; -pub type ino_t = u32; -pub type lwpid_t = i32; -pub type nlink_t = u16; -pub type blksize_t = u32; -pub type clockid_t = ::c_int; -pub type sem_t = _sem; - -pub type fsblkcnt_t = ::uint64_t; -pub type fsfilcnt_t = ::uint64_t; -pub type idtype_t = ::c_uint; - -pub type key_t = ::c_long; -pub type msglen_t = ::c_ulong; -pub type msgqnum_t = ::c_ulong; - -s! { - pub struct utmpx { - pub ut_type: ::c_short, - pub ut_tv: ::timeval, - pub ut_id: [::c_char; 8], - pub ut_pid: ::pid_t, - pub ut_user: [::c_char; 32], - pub ut_line: [::c_char; 16], - pub ut_host: [::c_char; 128], - pub __ut_spare: [::c_char; 64], - } - - pub struct aiocb { - pub aio_fildes: ::c_int, - pub aio_offset: ::off_t, - pub aio_buf: *mut ::c_void, - pub aio_nbytes: ::size_t, - __unused1: [::c_int; 2], - __unused2: *mut ::c_void, - pub aio_lio_opcode: ::c_int, - pub aio_reqprio: ::c_int, - // unused 3 through 5 are the __aiocb_private structure - __unused3: ::c_long, - __unused4: ::c_long, - __unused5: *mut ::c_void, - pub aio_sigevent: sigevent - } - - pub struct dirent { - pub d_fileno: u32, - pub d_reclen: u16, - pub d_type: u8, - pub d_namlen: u8, - pub d_name: [::c_char; 256], - } - - pub struct jail { - pub version: u32, - pub path: *mut ::c_char, - pub hostname: *mut ::c_char, - pub jailname: *mut ::c_char, - pub ip4s: ::c_uint, - pub ip6s: ::c_uint, - pub ip4: *mut ::in_addr, - pub ip6: *mut ::in6_addr, - } - - pub struct mq_attr { - pub mq_flags: ::c_long, - pub mq_maxmsg: ::c_long, - pub mq_msgsize: ::c_long, - pub mq_curmsgs: ::c_long, - __reserved: [::c_long; 4] - } - - pub struct sigevent { - pub sigev_notify: ::c_int, - pub sigev_signo: ::c_int, - pub sigev_value: ::sigval, - //The rest of the structure is actually a union. We expose only - //sigev_notify_thread_id because it's the most useful union member. - pub sigev_notify_thread_id: ::lwpid_t, - #[cfg(target_pointer_width = "64")] - __unused1: ::c_int, - __unused2: [::c_long; 7] - } - - pub struct statvfs { - pub f_bavail: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_blocks: ::fsblkcnt_t, - pub f_favail: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_bsize: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_fsid: ::c_ulong, - pub f_namemax: ::c_ulong, - } - - // internal structure has changed over time - pub struct _sem { - data: [u32; 4], - } - - pub struct ipc_perm { - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub mode: ::mode_t, - pub seq: ::c_ushort, - pub key: ::key_t, - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - __unused1: *mut ::c_void, - __unused2: *mut ::c_void, - pub msg_cbytes: ::msglen_t, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - pub msg_stime: ::time_t, - pub msg_rtime: ::time_t, - pub msg_ctime: ::time_t, - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_lpid: ::pid_t, - pub shm_cpid: ::pid_t, - pub shm_nattch: ::c_int, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - } - - pub struct xucred { - pub cr_version: ::c_uint, - pub cr_uid: ::uid_t, - pub cr_ngroups: ::c_short, - pub cr_groups: [::gid_t;16], - __cr_unused1: *mut ::c_void, - } - - pub struct sockaddr_dl { - pub sdl_len: ::c_uchar, - pub sdl_family: ::c_uchar, - pub sdl_index: ::c_ushort, - pub sdl_type: ::c_uchar, - pub sdl_nlen: ::c_uchar, - pub sdl_alen: ::c_uchar, - pub sdl_slen: ::c_uchar, - pub sdl_data: [::c_char; 46], - } -} - -pub const SIGEV_THREAD_ID: ::c_int = 4; - -pub const RAND_MAX: ::c_int = 0x7fff_fffd; -pub const PTHREAD_STACK_MIN: ::size_t = 2048; -pub const PTHREAD_MUTEX_ADAPTIVE_NP: ::c_int = 4; -pub const SIGSTKSZ: ::size_t = 34816; -pub const SF_NODISKIO: ::c_int = 0x00000001; -pub const SF_MNOWAIT: ::c_int = 0x00000002; -pub const SF_SYNC: ::c_int = 0x00000004; -pub const O_CLOEXEC: ::c_int = 0x00100000; -pub const O_DIRECTORY: ::c_int = 0x00020000; -pub const O_EXEC: ::c_int = 0x00040000; -pub const O_TTY_INIT: ::c_int = 0x00080000; -pub const F_GETLK: ::c_int = 11; -pub const F_SETLK: ::c_int = 12; -pub const F_SETLKW: ::c_int = 13; -pub const ENOTCAPABLE: ::c_int = 93; -pub const ECAPMODE: ::c_int = 94; -pub const ENOTRECOVERABLE: ::c_int = 95; -pub const EOWNERDEAD: ::c_int = 96; -pub const ELAST: ::c_int = 96; -pub const RLIMIT_NPTS: ::c_int = 11; -pub const RLIMIT_SWAP: ::c_int = 12; -pub const RLIM_NLIMITS: ::rlim_t = 13; - -pub const Q_GETQUOTA: ::c_int = 0x700; -pub const Q_SETQUOTA: ::c_int = 0x800; - -pub const POSIX_FADV_NORMAL: ::c_int = 0; -pub const POSIX_FADV_RANDOM: ::c_int = 1; -pub const POSIX_FADV_SEQUENTIAL: ::c_int = 2; -pub const POSIX_FADV_WILLNEED: ::c_int = 3; -pub const POSIX_FADV_DONTNEED: ::c_int = 4; -pub const POSIX_FADV_NOREUSE: ::c_int = 5; - -pub const POLLINIGNEOF: ::c_short = 0x2000; - -pub const EVFILT_READ: ::int16_t = -1; -pub const EVFILT_WRITE: ::int16_t = -2; -pub const EVFILT_AIO: ::int16_t = -3; -pub const EVFILT_VNODE: ::int16_t = -4; -pub const EVFILT_PROC: ::int16_t = -5; -pub const EVFILT_SIGNAL: ::int16_t = -6; -pub const EVFILT_TIMER: ::int16_t = -7; -pub const EVFILT_FS: ::int16_t = -9; -pub const EVFILT_LIO: ::int16_t = -10; -pub const EVFILT_USER: ::int16_t = -11; - -pub const EV_ADD: ::uint16_t = 0x1; -pub const EV_DELETE: ::uint16_t = 0x2; -pub const EV_ENABLE: ::uint16_t = 0x4; -pub const EV_DISABLE: ::uint16_t = 0x8; -pub const EV_ONESHOT: ::uint16_t = 0x10; -pub const EV_CLEAR: ::uint16_t = 0x20; -pub const EV_RECEIPT: ::uint16_t = 0x40; -pub const EV_DISPATCH: ::uint16_t = 0x80; -pub const EV_DROP: ::uint16_t = 0x1000; -pub const EV_FLAG1: ::uint16_t = 0x2000; -pub const EV_ERROR: ::uint16_t = 0x4000; -pub const EV_EOF: ::uint16_t = 0x8000; -pub const EV_SYSFLAGS: ::uint16_t = 0xf000; - -pub const NOTE_TRIGGER: ::uint32_t = 0x01000000; -pub const NOTE_FFNOP: ::uint32_t = 0x00000000; -pub const NOTE_FFAND: ::uint32_t = 0x40000000; -pub const NOTE_FFOR: ::uint32_t = 0x80000000; -pub const NOTE_FFCOPY: ::uint32_t = 0xc0000000; -pub const NOTE_FFCTRLMASK: ::uint32_t = 0xc0000000; -pub const NOTE_FFLAGSMASK: ::uint32_t = 0x00ffffff; -pub const NOTE_LOWAT: ::uint32_t = 0x00000001; -pub const NOTE_DELETE: ::uint32_t = 0x00000001; -pub const NOTE_WRITE: ::uint32_t = 0x00000002; -pub const NOTE_EXTEND: ::uint32_t = 0x00000004; -pub const NOTE_ATTRIB: ::uint32_t = 0x00000008; -pub const NOTE_LINK: ::uint32_t = 0x00000010; -pub const NOTE_RENAME: ::uint32_t = 0x00000020; -pub const NOTE_REVOKE: ::uint32_t = 0x00000040; -pub const NOTE_EXIT: ::uint32_t = 0x80000000; -pub const NOTE_FORK: ::uint32_t = 0x40000000; -pub const NOTE_EXEC: ::uint32_t = 0x20000000; -pub const NOTE_PDATAMASK: ::uint32_t = 0x000fffff; -pub const NOTE_PCTRLMASK: ::uint32_t = 0xf0000000; -pub const NOTE_TRACK: ::uint32_t = 0x00000001; -pub const NOTE_TRACKERR: ::uint32_t = 0x00000002; -pub const NOTE_CHILD: ::uint32_t = 0x00000004; -pub const NOTE_SECONDS: ::uint32_t = 0x00000001; -pub const NOTE_MSECONDS: ::uint32_t = 0x00000002; -pub const NOTE_USECONDS: ::uint32_t = 0x00000004; -pub const NOTE_NSECONDS: ::uint32_t = 0x00000008; - -pub const MADV_PROTECT: ::c_int = 10; -pub const RUSAGE_THREAD: ::c_int = 1; - -pub const CLOCK_REALTIME: ::clockid_t = 0; -pub const CLOCK_VIRTUAL: ::clockid_t = 1; -pub const CLOCK_PROF: ::clockid_t = 2; -pub const CLOCK_MONOTONIC: ::clockid_t = 4; -pub const CLOCK_UPTIME: ::clockid_t = 5; -pub const CLOCK_UPTIME_PRECISE: ::clockid_t = 7; -pub const CLOCK_UPTIME_FAST: ::clockid_t = 8; -pub const CLOCK_REALTIME_PRECISE: ::clockid_t = 9; -pub const CLOCK_REALTIME_FAST: ::clockid_t = 10; -pub const CLOCK_MONOTONIC_PRECISE: ::clockid_t = 11; -pub const CLOCK_MONOTONIC_FAST: ::clockid_t = 12; -pub const CLOCK_SECOND: ::clockid_t = 13; -pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 14; -pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 15; - -pub const CTL_UNSPEC: ::c_int = 0; -pub const CTL_KERN: ::c_int = 1; -pub const CTL_VM: ::c_int = 2; -pub const CTL_VFS: ::c_int = 3; -pub const CTL_NET: ::c_int = 4; -pub const CTL_DEBUG: ::c_int = 5; -pub const CTL_HW: ::c_int = 6; -pub const CTL_MACHDEP: ::c_int = 7; -pub const CTL_USER: ::c_int = 8; -pub const CTL_P1003_1B: ::c_int = 9; -pub const KERN_OSTYPE: ::c_int = 1; -pub const KERN_OSRELEASE: ::c_int = 2; -pub const KERN_OSREV: ::c_int = 3; -pub const KERN_VERSION: ::c_int = 4; -pub const KERN_MAXVNODES: ::c_int = 5; -pub const KERN_MAXPROC: ::c_int = 6; -pub const KERN_MAXFILES: ::c_int = 7; -pub const KERN_ARGMAX: ::c_int = 8; -pub const KERN_SECURELVL: ::c_int = 9; -pub const KERN_HOSTNAME: ::c_int = 10; -pub const KERN_HOSTID: ::c_int = 11; -pub const KERN_CLOCKRATE: ::c_int = 12; -pub const KERN_VNODE: ::c_int = 13; -pub const KERN_PROC: ::c_int = 14; -pub const KERN_FILE: ::c_int = 15; -pub const KERN_PROF: ::c_int = 16; -pub const KERN_POSIX1: ::c_int = 17; -pub const KERN_NGROUPS: ::c_int = 18; -pub const KERN_JOB_CONTROL: ::c_int = 19; -pub const KERN_SAVED_IDS: ::c_int = 20; -pub const KERN_BOOTTIME: ::c_int = 21; -pub const KERN_NISDOMAINNAME: ::c_int = 22; -pub const KERN_UPDATEINTERVAL: ::c_int = 23; -pub const KERN_OSRELDATE: ::c_int = 24; -pub const KERN_NTP_PLL: ::c_int = 25; -pub const KERN_BOOTFILE: ::c_int = 26; -pub const KERN_MAXFILESPERPROC: ::c_int = 27; -pub const KERN_MAXPROCPERUID: ::c_int = 28; -pub const KERN_DUMPDEV: ::c_int = 29; -pub const KERN_IPC: ::c_int = 30; -pub const KERN_DUMMY: ::c_int = 31; -pub const KERN_PS_STRINGS: ::c_int = 32; -pub const KERN_USRSTACK: ::c_int = 33; -pub const KERN_LOGSIGEXIT: ::c_int = 34; -pub const KERN_IOV_MAX: ::c_int = 35; -pub const KERN_HOSTUUID: ::c_int = 36; -pub const KERN_ARND: ::c_int = 37; -pub const KERN_PROC_ALL: ::c_int = 0; -pub const KERN_PROC_PID: ::c_int = 1; -pub const KERN_PROC_PGRP: ::c_int = 2; -pub const KERN_PROC_SESSION: ::c_int = 3; -pub const KERN_PROC_TTY: ::c_int = 4; -pub const KERN_PROC_UID: ::c_int = 5; -pub const KERN_PROC_RUID: ::c_int = 6; -pub const KERN_PROC_ARGS: ::c_int = 7; -pub const KERN_PROC_PROC: ::c_int = 8; -pub const KERN_PROC_SV_NAME: ::c_int = 9; -pub const KERN_PROC_RGID: ::c_int = 10; -pub const KERN_PROC_GID: ::c_int = 11; -pub const KERN_PROC_PATHNAME: ::c_int = 12; -pub const KERN_PROC_OVMMAP: ::c_int = 13; -pub const KERN_PROC_OFILEDESC: ::c_int = 14; -pub const KERN_PROC_KSTACK: ::c_int = 15; -pub const KERN_PROC_INC_THREAD: ::c_int = 0x10; -pub const KERN_PROC_VMMAP: ::c_int = 32; -pub const KERN_PROC_FILEDESC: ::c_int = 33; -pub const KERN_PROC_GROUPS: ::c_int = 34; -pub const KERN_PROC_ENV: ::c_int = 35; -pub const KERN_PROC_AUXV: ::c_int = 36; -pub const KERN_PROC_RLIMIT: ::c_int = 37; -pub const KERN_PROC_PS_STRINGS: ::c_int = 38; -pub const KERN_PROC_UMASK: ::c_int = 39; -pub const KERN_PROC_OSREL: ::c_int = 40; -pub const KERN_PROC_SIGTRAMP: ::c_int = 41; -pub const KIPC_MAXSOCKBUF: ::c_int = 1; -pub const KIPC_SOCKBUF_WASTE: ::c_int = 2; -pub const KIPC_SOMAXCONN: ::c_int = 3; -pub const KIPC_MAX_LINKHDR: ::c_int = 4; -pub const KIPC_MAX_PROTOHDR: ::c_int = 5; -pub const KIPC_MAX_HDR: ::c_int = 6; -pub const KIPC_MAX_DATALEN: ::c_int = 7; -pub const HW_MACHINE: ::c_int = 1; -pub const HW_MODEL: ::c_int = 2; -pub const HW_NCPU: ::c_int = 3; -pub const HW_BYTEORDER: ::c_int = 4; -pub const HW_PHYSMEM: ::c_int = 5; -pub const HW_USERMEM: ::c_int = 6; -pub const HW_PAGESIZE: ::c_int = 7; -pub const HW_DISKNAMES: ::c_int = 8; -pub const HW_DISKSTATS: ::c_int = 9; -pub const HW_FLOATINGPT: ::c_int = 10; -pub const HW_MACHINE_ARCH: ::c_int = 11; -pub const HW_REALMEM: ::c_int = 12; -pub const USER_CS_PATH: ::c_int = 1; -pub const USER_BC_BASE_MAX: ::c_int = 2; -pub const USER_BC_DIM_MAX: ::c_int = 3; -pub const USER_BC_SCALE_MAX: ::c_int = 4; -pub const USER_BC_STRING_MAX: ::c_int = 5; -pub const USER_COLL_WEIGHTS_MAX: ::c_int = 6; -pub const USER_EXPR_NEST_MAX: ::c_int = 7; -pub const USER_LINE_MAX: ::c_int = 8; -pub const USER_RE_DUP_MAX: ::c_int = 9; -pub const USER_POSIX2_VERSION: ::c_int = 10; -pub const USER_POSIX2_C_BIND: ::c_int = 11; -pub const USER_POSIX2_C_DEV: ::c_int = 12; -pub const USER_POSIX2_CHAR_TERM: ::c_int = 13; -pub const USER_POSIX2_FORT_DEV: ::c_int = 14; -pub const USER_POSIX2_FORT_RUN: ::c_int = 15; -pub const USER_POSIX2_LOCALEDEF: ::c_int = 16; -pub const USER_POSIX2_SW_DEV: ::c_int = 17; -pub const USER_POSIX2_UPE: ::c_int = 18; -pub const USER_STREAM_MAX: ::c_int = 19; -pub const USER_TZNAME_MAX: ::c_int = 20; -pub const CTL_P1003_1B_ASYNCHRONOUS_IO: ::c_int = 1; -pub const CTL_P1003_1B_MAPPED_FILES: ::c_int = 2; -pub const CTL_P1003_1B_MEMLOCK: ::c_int = 3; -pub const CTL_P1003_1B_MEMLOCK_RANGE: ::c_int = 4; -pub const CTL_P1003_1B_MEMORY_PROTECTION: ::c_int = 5; -pub const CTL_P1003_1B_MESSAGE_PASSING: ::c_int = 6; -pub const CTL_P1003_1B_PRIORITIZED_IO: ::c_int = 7; -pub const CTL_P1003_1B_PRIORITY_SCHEDULING: ::c_int = 8; -pub const CTL_P1003_1B_REALTIME_SIGNALS: ::c_int = 9; -pub const CTL_P1003_1B_SEMAPHORES: ::c_int = 10; -pub const CTL_P1003_1B_FSYNC: ::c_int = 11; -pub const CTL_P1003_1B_SHARED_MEMORY_OBJECTS: ::c_int = 12; -pub const CTL_P1003_1B_SYNCHRONIZED_IO: ::c_int = 13; -pub const CTL_P1003_1B_TIMERS: ::c_int = 14; -pub const CTL_P1003_1B_AIO_LISTIO_MAX: ::c_int = 15; -pub const CTL_P1003_1B_AIO_MAX: ::c_int = 16; -pub const CTL_P1003_1B_AIO_PRIO_DELTA_MAX: ::c_int = 17; -pub const CTL_P1003_1B_DELAYTIMER_MAX: ::c_int = 18; -pub const CTL_P1003_1B_MQ_OPEN_MAX: ::c_int = 19; -pub const CTL_P1003_1B_PAGESIZE: ::c_int = 20; -pub const CTL_P1003_1B_RTSIG_MAX: ::c_int = 21; -pub const CTL_P1003_1B_SEM_NSEMS_MAX: ::c_int = 22; -pub const CTL_P1003_1B_SEM_VALUE_MAX: ::c_int = 23; -pub const CTL_P1003_1B_SIGQUEUE_MAX: ::c_int = 24; -pub const CTL_P1003_1B_TIMER_MAX: ::c_int = 25; -pub const TIOCGPTN: ::c_uint = 0x4004740f; -pub const TIOCPTMASTER: ::c_uint = 0x2000741c; -pub const TIOCSIG: ::c_uint = 0x2004745f; -pub const TIOCM_DCD: ::c_int = 0x40; -pub const H4DISC: ::c_int = 0x7; - -pub const JAIL_API_VERSION: u32 = 2; -pub const JAIL_CREATE: ::c_int = 0x01; -pub const JAIL_UPDATE: ::c_int = 0x02; -pub const JAIL_ATTACH: ::c_int = 0x04; -pub const JAIL_DYING: ::c_int = 0x08; -pub const JAIL_SET_MASK: ::c_int = 0x0f; -pub const JAIL_GET_MASK: ::c_int = 0x08; -pub const JAIL_SYS_DISABLE: ::c_int = 0; -pub const JAIL_SYS_NEW: ::c_int = 1; -pub const JAIL_SYS_INHERIT: ::c_int = 2; - -pub const SO_BINTIME: ::c_int = 0x2000; -pub const SO_NO_OFFLOAD: ::c_int = 0x4000; -pub const SO_NO_DDP: ::c_int = 0x8000; -pub const SO_LABEL: ::c_int = 0x1009; -pub const SO_PEERLABEL: ::c_int = 0x1010; -pub const SO_LISTENQLIMIT: ::c_int = 0x1011; -pub const SO_LISTENQLEN: ::c_int = 0x1012; -pub const SO_LISTENINCQLEN: ::c_int = 0x1013; -pub const SO_SETFIB: ::c_int = 0x1014; -pub const SO_USER_COOKIE: ::c_int = 0x1015; -pub const SO_PROTOCOL: ::c_int = 0x1016; -pub const SO_PROTOTYPE: ::c_int = SO_PROTOCOL; -pub const SO_VENDOR: ::c_int = 0x80000000; - -pub const LOCAL_PEERCRED: ::c_int = 1; -pub const LOCAL_CREDS: ::c_int = 2; -pub const LOCAL_CONNWAIT: ::c_int = 4; -pub const LOCAL_VENDOR: ::c_int = SO_VENDOR; - -pub const AF_SLOW: ::c_int = 33; -pub const AF_SCLUSTER: ::c_int = 34; -pub const AF_ARP: ::c_int = 35; -pub const AF_BLUETOOTH: ::c_int = 36; -pub const AF_IEEE80211: ::c_int = 37; -pub const AF_INET_SDP: ::c_int = 40; -pub const AF_INET6_SDP: ::c_int = 42; -#[doc(hidden)] -pub const AF_MAX: ::c_int = 42; - -// https://github.com/freebsd/freebsd/blob/master/sys/net/if.h#L140 -pub const IFF_UP: ::c_int = 0x1; // (n) interface is up -pub const IFF_BROADCAST: ::c_int = 0x2; // (i) broadcast address valid -pub const IFF_DEBUG: ::c_int = 0x4; // (n) turn on debugging -pub const IFF_LOOPBACK: ::c_int = 0x8; // (i) is a loopback net -pub const IFF_POINTOPOINT: ::c_int = 0x10; // (i) is a point-to-point link -// 0x20 was IFF_SMART -pub const IFF_RUNNING: ::c_int = 0x40; // (d) resources allocated -#[doc(hidden)] -// IFF_DRV_RUNNING is deprecated. Use the portable `IFF_RUNNING` instead -pub const IFF_DRV_RUNNING: ::c_int = 0x40; -pub const IFF_NOARP: ::c_int = 0x80; // (n) no address resolution protocol -pub const IFF_PROMISC: ::c_int = 0x100; // (n) receive all packets -pub const IFF_ALLMULTI: ::c_int = 0x200; // (n) receive all multicast packets -pub const IFF_OACTIVE: ::c_int = 0x400; // (d) tx hardware queue is full -#[doc(hidden)] -// IFF_DRV_OACTIVE is deprecated. Use the portable `IFF_OACTIVE` instead -pub const IFF_DRV_OACTIVE: ::c_int = 0x400; -pub const IFF_SIMPLEX: ::c_int = 0x800; // (i) can't hear own transmissions -pub const IFF_LINK0: ::c_int = 0x1000; // per link layer defined bit -pub const IFF_LINK1: ::c_int = 0x2000; // per link layer defined bit -pub const IFF_LINK2: ::c_int = 0x4000; // per link layer defined bit -pub const IFF_ALTPHYS: ::c_int = IFF_LINK2; // use alternate physical connection -pub const IFF_MULTICAST: ::c_int = 0x8000; // (i) supports multicast -// (i) unconfigurable using ioctl(2) -pub const IFF_CANTCONFIG: ::c_int = 0x10000; -pub const IFF_PPROMISC: ::c_int = 0x20000; // (n) user-requested promisc mode -pub const IFF_MONITOR: ::c_int = 0x40000; // (n) user-requested monitor mode -pub const IFF_STATICARP: ::c_int = 0x80000; // (n) static ARP -pub const IFF_DYING: ::c_int = 0x200000; // (n) interface is winding down -pub const IFF_RENAMING: ::c_int = 0x400000; // (n) interface is being renamed - -// sys/netinet/in.h -// Protocols (RFC 1700) -// NOTE: These are in addition to the constants defined in src/unix/mod.rs - -// IPPROTO_IP defined in src/unix/mod.rs -/// IP6 hop-by-hop options -pub const IPPROTO_HOPOPTS: ::c_int = 0; -// IPPROTO_ICMP defined in src/unix/mod.rs -/// group mgmt protocol -pub const IPPROTO_IGMP: ::c_int = 2; -/// gateway^2 (deprecated) -pub const IPPROTO_GGP: ::c_int = 3; -/// for compatibility -pub const IPPROTO_IPIP: ::c_int = 4; -// IPPROTO_TCP defined in src/unix/mod.rs -/// Stream protocol II. -pub const IPPROTO_ST: ::c_int = 7; -/// exterior gateway protocol -pub const IPPROTO_EGP: ::c_int = 8; -/// private interior gateway -pub const IPPROTO_PIGP: ::c_int = 9; -/// BBN RCC Monitoring -pub const IPPROTO_RCCMON: ::c_int = 10; -/// network voice protocol -pub const IPPROTO_NVPII: ::c_int = 11; -/// pup -pub const IPPROTO_PUP: ::c_int = 12; -/// Argus -pub const IPPROTO_ARGUS: ::c_int = 13; -/// EMCON -pub const IPPROTO_EMCON: ::c_int = 14; -/// Cross Net Debugger -pub const IPPROTO_XNET: ::c_int = 15; -/// Chaos -pub const IPPROTO_CHAOS: ::c_int = 16; -// IPPROTO_UDP defined in src/unix/mod.rs -/// Multiplexing -pub const IPPROTO_MUX: ::c_int = 18; -/// DCN Measurement Subsystems -pub const IPPROTO_MEAS: ::c_int = 19; -/// Host Monitoring -pub const IPPROTO_HMP: ::c_int = 20; -/// Packet Radio Measurement -pub const IPPROTO_PRM: ::c_int = 21; -/// xns idp -pub const IPPROTO_IDP: ::c_int = 22; -/// Trunk-1 -pub const IPPROTO_TRUNK1: ::c_int = 23; -/// Trunk-2 -pub const IPPROTO_TRUNK2: ::c_int = 24; -/// Leaf-1 -pub const IPPROTO_LEAF1: ::c_int = 25; -/// Leaf-2 -pub const IPPROTO_LEAF2: ::c_int = 26; -/// Reliable Data -pub const IPPROTO_RDP: ::c_int = 27; -/// Reliable Transaction -pub const IPPROTO_IRTP: ::c_int = 28; -/// tp-4 w/ class negotiation -pub const IPPROTO_TP: ::c_int = 29; -/// Bulk Data Transfer -pub const IPPROTO_BLT: ::c_int = 30; -/// Network Services -pub const IPPROTO_NSP: ::c_int = 31; -/// Merit Internodal -pub const IPPROTO_INP: ::c_int = 32; -/// Sequential Exchange -pub const IPPROTO_SEP: ::c_int = 33; -/// Third Party Connect -pub const IPPROTO_3PC: ::c_int = 34; -/// InterDomain Policy Routing -pub const IPPROTO_IDPR: ::c_int = 35; -/// XTP -pub const IPPROTO_XTP: ::c_int = 36; -/// Datagram Delivery -pub const IPPROTO_DDP: ::c_int = 37; -/// Control Message Transport -pub const IPPROTO_CMTP: ::c_int = 38; -/// TP++ Transport -pub const IPPROTO_TPXX: ::c_int = 39; -/// IL transport protocol -pub const IPPROTO_IL: ::c_int = 40; -// IPPROTO_IPV6 defined in src/unix/mod.rs -/// Source Demand Routing -pub const IPPROTO_SDRP: ::c_int = 42; -/// IP6 routing header -pub const IPPROTO_ROUTING: ::c_int = 43; -/// IP6 fragmentation header -pub const IPPROTO_FRAGMENT: ::c_int = 44; -/// InterDomain Routing -pub const IPPROTO_IDRP: ::c_int = 45; -/// resource reservation -pub const IPPROTO_RSVP: ::c_int = 46; -/// General Routing Encap. -pub const IPPROTO_GRE: ::c_int = 47; -/// Mobile Host Routing -pub const IPPROTO_MHRP: ::c_int = 48; -/// BHA -pub const IPPROTO_BHA: ::c_int = 49; -/// IP6 Encap Sec. Payload -pub const IPPROTO_ESP: ::c_int = 50; -/// IP6 Auth Header -pub const IPPROTO_AH: ::c_int = 51; -/// Integ. Net Layer Security -pub const IPPROTO_INLSP: ::c_int = 52; -/// IP with encryption -pub const IPPROTO_SWIPE: ::c_int = 53; -/// Next Hop Resolution -pub const IPPROTO_NHRP: ::c_int = 54; -/// IP Mobility -pub const IPPROTO_MOBILE: ::c_int = 55; -/// Transport Layer Security -pub const IPPROTO_TLSP: ::c_int = 56; -/// SKIP -pub const IPPROTO_SKIP: ::c_int = 57; -// IPPROTO_ICMPV6 defined in src/unix/mod.rs -/// IP6 no next header -pub const IPPROTO_NONE: ::c_int = 59; -/// IP6 destination option -pub const IPPROTO_DSTOPTS: ::c_int = 60; -/// any host internal protocol -pub const IPPROTO_AHIP: ::c_int = 61; -/// CFTP -pub const IPPROTO_CFTP: ::c_int = 62; -/// "hello" routing protocol -pub const IPPROTO_HELLO: ::c_int = 63; -/// SATNET/Backroom EXPAK -pub const IPPROTO_SATEXPAK: ::c_int = 64; -/// Kryptolan -pub const IPPROTO_KRYPTOLAN: ::c_int = 65; -/// Remote Virtual Disk -pub const IPPROTO_RVD: ::c_int = 66; -/// Pluribus Packet Core -pub const IPPROTO_IPPC: ::c_int = 67; -/// Any distributed FS -pub const IPPROTO_ADFS: ::c_int = 68; -/// Satnet Monitoring -pub const IPPROTO_SATMON: ::c_int = 69; -/// VISA Protocol -pub const IPPROTO_VISA: ::c_int = 70; -/// Packet Core Utility -pub const IPPROTO_IPCV: ::c_int = 71; -/// Comp. Prot. Net. Executive -pub const IPPROTO_CPNX: ::c_int = 72; -/// Comp. Prot. HeartBeat -pub const IPPROTO_CPHB: ::c_int = 73; -/// Wang Span Network -pub const IPPROTO_WSN: ::c_int = 74; -/// Packet Video Protocol -pub const IPPROTO_PVP: ::c_int = 75; -/// BackRoom SATNET Monitoring -pub const IPPROTO_BRSATMON: ::c_int = 76; -/// Sun net disk proto (temp.) -pub const IPPROTO_ND: ::c_int = 77; -/// WIDEBAND Monitoring -pub const IPPROTO_WBMON: ::c_int = 78; -/// WIDEBAND EXPAK -pub const IPPROTO_WBEXPAK: ::c_int = 79; -/// ISO cnlp -pub const IPPROTO_EON: ::c_int = 80; -/// VMTP -pub const IPPROTO_VMTP: ::c_int = 81; -/// Secure VMTP -pub const IPPROTO_SVMTP: ::c_int = 82; -/// Banyon VINES -pub const IPPROTO_VINES: ::c_int = 83; -/// TTP -pub const IPPROTO_TTP: ::c_int = 84; -/// NSFNET-IGP -pub const IPPROTO_IGP: ::c_int = 85; -/// dissimilar gateway prot. -pub const IPPROTO_DGP: ::c_int = 86; -/// TCF -pub const IPPROTO_TCF: ::c_int = 87; -/// Cisco/GXS IGRP -pub const IPPROTO_IGRP: ::c_int = 88; -/// OSPFIGP -pub const IPPROTO_OSPFIGP: ::c_int = 89; -/// Strite RPC protocol -pub const IPPROTO_SRPC: ::c_int = 90; -/// Locus Address Resoloution -pub const IPPROTO_LARP: ::c_int = 91; -/// Multicast Transport -pub const IPPROTO_MTP: ::c_int = 92; -/// AX.25 Frames -pub const IPPROTO_AX25: ::c_int = 93; -/// IP encapsulated in IP -pub const IPPROTO_IPEIP: ::c_int = 94; -/// Mobile Int.ing control -pub const IPPROTO_MICP: ::c_int = 95; -/// Semaphore Comm. security -pub const IPPROTO_SCCSP: ::c_int = 96; -/// Ethernet IP encapsulation -pub const IPPROTO_ETHERIP: ::c_int = 97; -/// encapsulation header -pub const IPPROTO_ENCAP: ::c_int = 98; -/// any private encr. scheme -pub const IPPROTO_APES: ::c_int = 99; -/// GMTP -pub const IPPROTO_GMTP: ::c_int = 100; -/// payload compression (IPComp) -pub const IPPROTO_IPCOMP: ::c_int = 108; -/// SCTP -pub const IPPROTO_SCTP: ::c_int = 132; -/// IPv6 Mobility Header -pub const IPPROTO_MH: ::c_int = 135; -/// UDP-Lite -pub const IPPROTO_UDPLITE: ::c_int = 136; -/// IP6 Host Identity Protocol -pub const IPPROTO_HIP: ::c_int = 139; -/// IP6 Shim6 Protocol -pub const IPPROTO_SHIM6: ::c_int = 140; - -/* 101-254: Partly Unassigned */ -/// Protocol Independent Mcast -pub const IPPROTO_PIM: ::c_int = 103; -/// CARP -pub const IPPROTO_CARP: ::c_int = 112; -/// PGM -pub const IPPROTO_PGM: ::c_int = 113; -/// MPLS-in-IP -pub const IPPROTO_MPLS: ::c_int = 137; -/// PFSYNC -pub const IPPROTO_PFSYNC: ::c_int = 240; - -/* 255: Reserved */ -/* BSD Private, local use, namespace incursion, no longer used */ -/// OLD divert pseudo-proto -pub const IPPROTO_OLD_DIVERT: ::c_int = 254; -pub const IPPROTO_MAX: ::c_int = 256; -/// last return value of *_input(), meaning "all job for this pkt is done". -pub const IPPROTO_DONE: ::c_int = 257; - -/* Only used internally, so can be outside the range of valid IP protocols. */ -/// divert pseudo-protocol -pub const IPPROTO_DIVERT: ::c_int = 258; -/// SeND pseudo-protocol -pub const IPPROTO_SEND: ::c_int = 259; - -pub const IP_BINDANY: ::c_int = 24; - -pub const PF_SLOW: ::c_int = AF_SLOW; -pub const PF_SCLUSTER: ::c_int = AF_SCLUSTER; -pub const PF_ARP: ::c_int = AF_ARP; -pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; -pub const PF_IEEE80211: ::c_int = AF_IEEE80211; -pub const PF_INET_SDP: ::c_int = AF_INET_SDP; -pub const PF_INET6_SDP: ::c_int = AF_INET6_SDP; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; - -pub const NET_RT_DUMP: ::c_int = 1; -pub const NET_RT_FLAGS: ::c_int = 2; -pub const NET_RT_IFLIST: ::c_int = 3; -pub const NET_RT_IFMALIST: ::c_int = 4; -pub const NET_RT_IFLISTL: ::c_int = 5; - -// System V IPC -pub const IPC_PRIVATE: ::key_t = 0; -pub const IPC_CREAT: ::c_int = 0o1000; -pub const IPC_EXCL: ::c_int = 0o2000; -pub const IPC_NOWAIT: ::c_int = 0o4000; -pub const IPC_RMID: ::c_int = 0; -pub const IPC_SET: ::c_int = 1; -pub const IPC_STAT: ::c_int = 2; -pub const IPC_INFO: ::c_int = 3; -pub const IPC_R : ::c_int = 0o400; -pub const IPC_W : ::c_int = 0o200; -pub const IPC_M : ::c_int = 0o10000; -pub const MSG_NOERROR: ::c_int = 0o10000; -pub const SHM_RDONLY: ::c_int = 0o10000; -pub const SHM_RND: ::c_int = 0o20000; -pub const SHM_R: ::c_int = 0o400; -pub const SHM_W: ::c_int = 0o200; -pub const SHM_LOCK: ::c_int = 11; -pub const SHM_UNLOCK: ::c_int = 12; -pub const SHM_STAT: ::c_int = 13; -pub const SHM_INFO: ::c_int = 14; -pub const SHM_ANON: *mut ::c_char = 1 as *mut ::c_char; - -// The *_MAXID constants never should've been used outside of the -// FreeBSD base system. And with the exception of CTL_P1003_1B_MAXID, -// they were all removed in svn r262489. They remain here for backwards -// compatibility only, and are scheduled to be removed in libc 1.0.0. -#[doc(hidden)] -pub const NET_MAXID: ::c_int = AF_MAX; -#[doc(hidden)] -pub const CTL_MAXID: ::c_int = 10; -#[doc(hidden)] -pub const KERN_MAXID: ::c_int = 38; -#[doc(hidden)] -pub const HW_MAXID: ::c_int = 13; -#[doc(hidden)] -pub const USER_MAXID: ::c_int = 21; -#[doc(hidden)] -pub const CTL_P1003_1B_MAXID: ::c_int = 26; - -pub const MSG_NOTIFICATION: ::c_int = 0x00002000; -pub const MSG_NBIO: ::c_int = 0x00004000; -pub const MSG_COMPAT: ::c_int = 0x00008000; -pub const MSG_CMSG_CLOEXEC: ::c_int = 0x00040000; -pub const MSG_NOSIGNAL: ::c_int = 0x20000; - -pub const EMPTY: ::c_short = 0; -pub const BOOT_TIME: ::c_short = 1; -pub const OLD_TIME: ::c_short = 2; -pub const NEW_TIME: ::c_short = 3; -pub const USER_PROCESS: ::c_short = 4; -pub const INIT_PROCESS: ::c_short = 5; -pub const LOGIN_PROCESS: ::c_short = 6; -pub const DEAD_PROCESS: ::c_short = 7; -pub const SHUTDOWN_TIME: ::c_short = 8; - -pub const LC_COLLATE_MASK: ::c_int = (1 << 0); -pub const LC_CTYPE_MASK: ::c_int = (1 << 1); -pub const LC_MESSAGES_MASK: ::c_int = (1 << 2); -pub const LC_MONETARY_MASK: ::c_int = (1 << 3); -pub const LC_NUMERIC_MASK: ::c_int = (1 << 4); -pub const LC_TIME_MASK: ::c_int = (1 << 5); -pub const LC_ALL_MASK: ::c_int = LC_COLLATE_MASK - | LC_CTYPE_MASK - | LC_MESSAGES_MASK - | LC_MONETARY_MASK - | LC_NUMERIC_MASK - | LC_TIME_MASK; - -pub const WSTOPPED: ::c_int = 2; // same as WUNTRACED -pub const WCONTINUED: ::c_int = 4; -pub const WNOWAIT: ::c_int = 8; -pub const WEXITED: ::c_int = 16; -pub const WTRAPPED: ::c_int = 32; - -// FreeBSD defines a great many more of these, we only expose the -// standardized ones. -pub const P_PID: idtype_t = 0; -pub const P_PGID: idtype_t = 2; -pub const P_ALL: idtype_t = 7; - -pub const B460800: ::speed_t = 460800; -pub const B921600: ::speed_t = 921600; - -pub const AT_FDCWD: ::c_int = -100; -pub const AT_EACCESS: ::c_int = 0x100; -pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x200; -pub const AT_SYMLINK_FOLLOW: ::c_int = 0x400; -pub const AT_REMOVEDIR: ::c_int = 0x800; - -pub const TABDLY: ::tcflag_t = 0x00000004; -pub const TAB0: ::tcflag_t = 0x00000000; -pub const TAB3: ::tcflag_t = 0x00000004; - -pub const _PC_ACL_NFS4: ::c_int = 64; - -pub const _SC_CPUSET_SIZE: ::c_int = 122; - -pub const XU_NGROUPS: ::c_int = 16; -pub const XUCRED_VERSION: ::c_uint = 0; - -extern { - pub fn __error() -> *mut ::c_int; - - pub fn mprotect(addr: *const ::c_void, len: ::size_t, prot: ::c_int) - -> ::c_int; - - pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; - - pub fn jail(jail: *mut ::jail) -> ::c_int; - pub fn jail_attach(jid: ::c_int) -> ::c_int; - pub fn jail_remove(jid: ::c_int) -> ::c_int; - pub fn jail_get(iov: *mut ::iovec, niov: ::c_uint, flags: ::c_int) - -> ::c_int; - pub fn jail_set(iov: *mut ::iovec, niov: ::c_uint, flags: ::c_int) - -> ::c_int; - - pub fn posix_fallocate(fd: ::c_int, offset: ::off_t, - len: ::off_t) -> ::c_int; - pub fn posix_fadvise(fd: ::c_int, offset: ::off_t, len: ::off_t, - advise: ::c_int) -> ::c_int; - pub fn mkostemp(template: *mut ::c_char, flags: ::c_int) -> ::c_int; - pub fn mkostemps(template: *mut ::c_char, - suffixlen: ::c_int, - flags: ::c_int) -> ::c_int; - - pub fn getutxuser(user: *const ::c_char) -> *mut utmpx; - pub fn setutxdb(_type: ::c_int, file: *const ::c_char) -> ::c_int; - - pub fn aio_waitcomplete(iocbp: *mut *mut aiocb, - timeout: *mut ::timespec) -> ::ssize_t; - - pub fn freelocale(loc: ::locale_t) -> ::c_int; - pub fn waitid(idtype: idtype_t, id: ::id_t, infop: *mut ::siginfo_t, - options: ::c_int) -> ::c_int; - - pub fn ftok(pathname: *const ::c_char, proj_id: ::c_int) -> ::key_t; - pub fn shmget(key: ::key_t, size: ::size_t, shmflg: ::c_int) -> ::c_int; - pub fn shmat(shmid: ::c_int, shmaddr: *const ::c_void, - shmflg: ::c_int) -> *mut ::c_void; - pub fn shmdt(shmaddr: *const ::c_void) -> ::c_int; - pub fn shmctl(shmid: ::c_int, cmd: ::c_int, - buf: *mut ::shmid_ds) -> ::c_int; - pub fn msgctl(msqid: ::c_int, cmd: ::c_int, - buf: *mut ::msqid_ds) -> ::c_int; - pub fn msgget(key: ::key_t, msgflg: ::c_int) -> ::c_int; - pub fn msgrcv(msqid: ::c_int, msgp: *mut ::c_void, msgsz: ::size_t, - msgtyp: ::c_long, msgflg: ::c_int) -> ::c_int; - pub fn msgsnd(msqid: ::c_int, msgp: *const ::c_void, msgsz: ::size_t, - msgflg: ::c_int) -> ::c_int; - pub fn cfmakesane(termios: *mut ::termios); - pub fn fexecve(fd: ::c_int, argv: *const *const ::c_char, - envp: *const *const ::c_char) - -> ::c_int; -} - -cfg_if! { - if #[cfg(target_arch = "x86")] { - mod x86; - pub use self::x86::*; - } else if #[cfg(target_arch = "x86_64")] { - mod x86_64; - pub use self::x86_64::*; - } else if #[cfg(target_arch = "aarch64")] { - mod aarch64; - pub use self::aarch64::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/x86_64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/x86_64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -pub type c_long = i64; -pub type c_ulong = u64; -pub type time_t = i64; -pub type suseconds_t = i64; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_size: ::off_t, - pub st_blocks: ::blkcnt_t, - pub st_blksize: ::blksize_t, - pub st_flags: ::fflags_t, - pub st_gen: ::uint32_t, - pub st_lspare: ::int32_t, - pub st_birthtime: ::time_t, - pub st_birthtime_nsec: ::c_long, - } -} - -pub const MAP_32BIT: ::c_int = 0x00080000; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/x86.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/x86.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/x86.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/freebsd/x86.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -pub type c_long = i32; -pub type c_ulong = u32; -pub type time_t = i32; -pub type suseconds_t = i32; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_size: ::off_t, - pub st_blocks: ::blkcnt_t, - pub st_blksize: ::blksize_t, - pub st_flags: ::fflags_t, - pub st_gen: ::uint32_t, - pub st_lspare: ::int32_t, - pub st_birthtime: ::time_t, - pub st_birthtime_nsec: ::c_long, - __unused: [u8; 8], - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/freebsdlike/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1172 +0,0 @@ -pub type c_char = i8; -pub type dev_t = u32; -pub type mode_t = u16; -pub type pthread_attr_t = *mut ::c_void; -pub type rlim_t = i64; -pub type mqd_t = *mut ::c_void; -pub type pthread_mutex_t = *mut ::c_void; -pub type pthread_mutexattr_t = *mut ::c_void; -pub type pthread_cond_t = *mut ::c_void; -pub type pthread_condattr_t = *mut ::c_void; -pub type pthread_rwlock_t = *mut ::c_void; -pub type pthread_rwlockattr_t = *mut ::c_void; -pub type pthread_key_t = ::c_int; -pub type tcflag_t = ::c_uint; -pub type speed_t = ::c_uint; -pub type nl_item = ::c_int; -pub type id_t = i64; - -pub enum timezone {} - -s! { - pub struct glob_t { - pub gl_pathc: ::size_t, - pub gl_matchc: ::size_t, - pub gl_offs: ::size_t, - pub gl_flags: ::c_int, - pub gl_pathv: *mut *mut ::c_char, - __unused3: *mut ::c_void, - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - __unused6: *mut ::c_void, - __unused7: *mut ::c_void, - __unused8: *mut ::c_void, - } - - pub struct kevent { - pub ident: ::uintptr_t, - pub filter: ::c_short, - pub flags: ::c_ushort, - pub fflags: ::c_uint, - pub data: ::intptr_t, - pub udata: *mut ::c_void, - } - - pub struct sockaddr_storage { - pub ss_len: u8, - pub ss_family: ::sa_family_t, - __ss_pad1: [u8; 6], - __ss_align: i64, - __ss_pad2: [u8; 112], - } - - pub struct addrinfo { - pub ai_flags: ::c_int, - pub ai_family: ::c_int, - pub ai_socktype: ::c_int, - pub ai_protocol: ::c_int, - pub ai_addrlen: ::socklen_t, - pub ai_canonname: *mut ::c_char, - pub ai_addr: *mut ::sockaddr, - pub ai_next: *mut addrinfo, - } - - pub struct sigset_t { - bits: [u32; 4], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_errno: ::c_int, - pub si_code: ::c_int, - pub si_pid: ::pid_t, - pub si_uid: ::uid_t, - pub si_status: ::c_int, - pub si_addr: *mut ::c_void, - _pad: [::c_int; 12], - } - - pub struct sigaction { - pub sa_sigaction: ::sighandler_t, - pub sa_flags: ::c_int, - pub sa_mask: sigset_t, - } - - pub struct stack_t { - // In FreeBSD 11 and later, ss_sp is actually a void* - pub ss_sp: *mut ::c_char, - pub ss_size: ::size_t, - pub ss_flags: ::c_int, - } - - pub struct sched_param { - pub sched_priority: ::c_int, - } - - pub struct Dl_info { - pub dli_fname: *const ::c_char, - pub dli_fbase: *mut ::c_void, - pub dli_sname: *const ::c_char, - pub dli_saddr: *mut ::c_void, - } - - pub struct sockaddr_in { - pub sin_len: u8, - pub sin_family: ::sa_family_t, - pub sin_port: ::in_port_t, - pub sin_addr: ::in_addr, - pub sin_zero: [::c_char; 8], - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_cc: [::cc_t; ::NCCS], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } - - pub struct flock { - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_pid: ::pid_t, - pub l_type: ::c_short, - pub l_whence: ::c_short, - #[cfg(not(target_os = "dragonfly"))] - pub l_sysid: ::c_int, - } - - pub struct sf_hdtr { - pub headers: *mut ::iovec, - pub hdr_cnt: ::c_int, - pub trailers: *mut ::iovec, - pub trl_cnt: ::c_int, - } - - pub struct lconv { - pub decimal_point: *mut ::c_char, - pub thousands_sep: *mut ::c_char, - pub grouping: *mut ::c_char, - pub int_curr_symbol: *mut ::c_char, - pub currency_symbol: *mut ::c_char, - pub mon_decimal_point: *mut ::c_char, - pub mon_thousands_sep: *mut ::c_char, - pub mon_grouping: *mut ::c_char, - pub positive_sign: *mut ::c_char, - pub negative_sign: *mut ::c_char, - pub int_frac_digits: ::c_char, - pub frac_digits: ::c_char, - pub p_cs_precedes: ::c_char, - pub p_sep_by_space: ::c_char, - pub n_cs_precedes: ::c_char, - pub n_sep_by_space: ::c_char, - pub p_sign_posn: ::c_char, - pub n_sign_posn: ::c_char, - pub int_p_cs_precedes: ::c_char, - pub int_n_cs_precedes: ::c_char, - pub int_p_sep_by_space: ::c_char, - pub int_n_sep_by_space: ::c_char, - pub int_p_sign_posn: ::c_char, - pub int_n_sign_posn: ::c_char, - } - - pub struct cmsgcred { - pub cmcred_pid: ::pid_t, - pub cmcred_uid: ::uid_t, - pub cmcred_euid: ::uid_t, - pub cmcred_gid: ::gid_t, - pub cmcred_ngroups: ::c_short, - pub cmcred_groups: [::gid_t; CMGROUP_MAX], - } -} - -pub const AIO_LISTIO_MAX: ::c_int = 16; -pub const AIO_CANCELED: ::c_int = 1; -pub const AIO_NOTCANCELED: ::c_int = 2; -pub const AIO_ALLDONE: ::c_int = 3; -pub const LIO_NOP: ::c_int = 0; -pub const LIO_WRITE: ::c_int = 1; -pub const LIO_READ: ::c_int = 2; -pub const LIO_WAIT: ::c_int = 1; -pub const LIO_NOWAIT: ::c_int = 0; - -pub const SIGEV_NONE: ::c_int = 0; -pub const SIGEV_SIGNAL: ::c_int = 1; -pub const SIGEV_THREAD: ::c_int = 2; -pub const SIGEV_KEVENT: ::c_int = 3; - -pub const CODESET: ::nl_item = 0; -pub const D_T_FMT: ::nl_item = 1; -pub const D_FMT: ::nl_item = 2; -pub const T_FMT: ::nl_item = 3; -pub const T_FMT_AMPM: ::nl_item = 4; -pub const AM_STR: ::nl_item = 5; -pub const PM_STR: ::nl_item = 6; - -pub const DAY_1: ::nl_item = 7; -pub const DAY_2: ::nl_item = 8; -pub const DAY_3: ::nl_item = 9; -pub const DAY_4: ::nl_item = 10; -pub const DAY_5: ::nl_item = 11; -pub const DAY_6: ::nl_item = 12; -pub const DAY_7: ::nl_item = 13; - -pub const ABDAY_1: ::nl_item = 14; -pub const ABDAY_2: ::nl_item = 15; -pub const ABDAY_3: ::nl_item = 16; -pub const ABDAY_4: ::nl_item = 17; -pub const ABDAY_5: ::nl_item = 18; -pub const ABDAY_6: ::nl_item = 19; -pub const ABDAY_7: ::nl_item = 20; - -pub const MON_1: ::nl_item = 21; -pub const MON_2: ::nl_item = 22; -pub const MON_3: ::nl_item = 23; -pub const MON_4: ::nl_item = 24; -pub const MON_5: ::nl_item = 25; -pub const MON_6: ::nl_item = 26; -pub const MON_7: ::nl_item = 27; -pub const MON_8: ::nl_item = 28; -pub const MON_9: ::nl_item = 29; -pub const MON_10: ::nl_item = 30; -pub const MON_11: ::nl_item = 31; -pub const MON_12: ::nl_item = 32; - -pub const ABMON_1: ::nl_item = 33; -pub const ABMON_2: ::nl_item = 34; -pub const ABMON_3: ::nl_item = 35; -pub const ABMON_4: ::nl_item = 36; -pub const ABMON_5: ::nl_item = 37; -pub const ABMON_6: ::nl_item = 38; -pub const ABMON_7: ::nl_item = 39; -pub const ABMON_8: ::nl_item = 40; -pub const ABMON_9: ::nl_item = 41; -pub const ABMON_10: ::nl_item = 42; -pub const ABMON_11: ::nl_item = 43; -pub const ABMON_12: ::nl_item = 44; - -pub const ERA: ::nl_item = 45; -pub const ERA_D_FMT: ::nl_item = 46; -pub const ERA_D_T_FMT: ::nl_item = 47; -pub const ERA_T_FMT: ::nl_item = 48; -pub const ALT_DIGITS: ::nl_item = 49; - -pub const RADIXCHAR: ::nl_item = 50; -pub const THOUSEP: ::nl_item = 51; - -pub const YESEXPR: ::nl_item = 52; -pub const NOEXPR: ::nl_item = 53; - -pub const YESSTR: ::nl_item = 54; -pub const NOSTR: ::nl_item = 55; - -pub const CRNCYSTR: ::nl_item = 56; - -pub const D_MD_ORDER: ::nl_item = 57; - -pub const ALTMON_1: ::nl_item = 58; -pub const ALTMON_2: ::nl_item = 59; -pub const ALTMON_3: ::nl_item = 60; -pub const ALTMON_4: ::nl_item = 61; -pub const ALTMON_5: ::nl_item = 62; -pub const ALTMON_6: ::nl_item = 63; -pub const ALTMON_7: ::nl_item = 64; -pub const ALTMON_8: ::nl_item = 65; -pub const ALTMON_9: ::nl_item = 66; -pub const ALTMON_10: ::nl_item = 67; -pub const ALTMON_11: ::nl_item = 68; -pub const ALTMON_12: ::nl_item = 69; - -pub const EXIT_FAILURE: ::c_int = 1; -pub const EXIT_SUCCESS: ::c_int = 0; -pub const EOF: ::c_int = -1; -pub const SEEK_SET: ::c_int = 0; -pub const SEEK_CUR: ::c_int = 1; -pub const SEEK_END: ::c_int = 2; -pub const SEEK_DATA: ::c_int = 3; -pub const SEEK_HOLE: ::c_int = 4; -pub const _IOFBF: ::c_int = 0; -pub const _IONBF: ::c_int = 2; -pub const _IOLBF: ::c_int = 1; -pub const BUFSIZ: ::c_uint = 1024; -pub const FOPEN_MAX: ::c_uint = 20; -pub const FILENAME_MAX: ::c_uint = 1024; -pub const L_tmpnam: ::c_uint = 1024; -pub const TMP_MAX: ::c_uint = 308915776; - -pub const O_NOCTTY: ::c_int = 32768; -pub const O_DIRECT: ::c_int = 0x00010000; - -pub const S_IFIFO: mode_t = 4096; -pub const S_IFCHR: mode_t = 8192; -pub const S_IFBLK: mode_t = 24576; -pub const S_IFDIR: mode_t = 16384; -pub const S_IFREG: mode_t = 32768; -pub const S_IFLNK: mode_t = 40960; -pub const S_IFSOCK: mode_t = 49152; -pub const S_IFMT: mode_t = 61440; -pub const S_IEXEC: mode_t = 64; -pub const S_IWRITE: mode_t = 128; -pub const S_IREAD: mode_t = 256; -pub const S_IRWXU: mode_t = 448; -pub const S_IXUSR: mode_t = 64; -pub const S_IWUSR: mode_t = 128; -pub const S_IRUSR: mode_t = 256; -pub const S_IRWXG: mode_t = 56; -pub const S_IXGRP: mode_t = 8; -pub const S_IWGRP: mode_t = 16; -pub const S_IRGRP: mode_t = 32; -pub const S_IRWXO: mode_t = 7; -pub const S_IXOTH: mode_t = 1; -pub const S_IWOTH: mode_t = 2; -pub const S_IROTH: mode_t = 4; -pub const F_OK: ::c_int = 0; -pub const R_OK: ::c_int = 4; -pub const W_OK: ::c_int = 2; -pub const X_OK: ::c_int = 1; -pub const STDIN_FILENO: ::c_int = 0; -pub const STDOUT_FILENO: ::c_int = 1; -pub const STDERR_FILENO: ::c_int = 2; -pub const F_LOCK: ::c_int = 1; -pub const F_TEST: ::c_int = 3; -pub const F_TLOCK: ::c_int = 2; -pub const F_ULOCK: ::c_int = 0; -pub const F_DUPFD_CLOEXEC: ::c_int = 17; -pub const SIGHUP: ::c_int = 1; -pub const SIGINT: ::c_int = 2; -pub const SIGQUIT: ::c_int = 3; -pub const SIGILL: ::c_int = 4; -pub const SIGABRT: ::c_int = 6; -pub const SIGEMT: ::c_int = 7; -pub const SIGFPE: ::c_int = 8; -pub const SIGKILL: ::c_int = 9; -pub const SIGSEGV: ::c_int = 11; -pub const SIGPIPE: ::c_int = 13; -pub const SIGALRM: ::c_int = 14; -pub const SIGTERM: ::c_int = 15; - -pub const PROT_NONE: ::c_int = 0; -pub const PROT_READ: ::c_int = 1; -pub const PROT_WRITE: ::c_int = 2; -pub const PROT_EXEC: ::c_int = 4; - -pub const MAP_FILE: ::c_int = 0x0000; -pub const MAP_SHARED: ::c_int = 0x0001; -pub const MAP_PRIVATE: ::c_int = 0x0002; -pub const MAP_FIXED: ::c_int = 0x0010; -pub const MAP_ANON: ::c_int = 0x1000; -pub const MAP_ANONYMOUS: ::c_int = MAP_ANON; - -pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const MS_SYNC: ::c_int = 0x0000; -pub const MS_ASYNC: ::c_int = 0x0001; -pub const MS_INVALIDATE: ::c_int = 0x0002; - -pub const EPERM: ::c_int = 1; -pub const ENOENT: ::c_int = 2; -pub const ESRCH: ::c_int = 3; -pub const EINTR: ::c_int = 4; -pub const EIO: ::c_int = 5; -pub const ENXIO: ::c_int = 6; -pub const E2BIG: ::c_int = 7; -pub const ENOEXEC: ::c_int = 8; -pub const EBADF: ::c_int = 9; -pub const ECHILD: ::c_int = 10; -pub const EDEADLK: ::c_int = 11; -pub const ENOMEM: ::c_int = 12; -pub const EACCES: ::c_int = 13; -pub const EFAULT: ::c_int = 14; -pub const ENOTBLK: ::c_int = 15; -pub const EBUSY: ::c_int = 16; -pub const EEXIST: ::c_int = 17; -pub const EXDEV: ::c_int = 18; -pub const ENODEV: ::c_int = 19; -pub const ENOTDIR: ::c_int = 20; -pub const EISDIR: ::c_int = 21; -pub const EINVAL: ::c_int = 22; -pub const ENFILE: ::c_int = 23; -pub const EMFILE: ::c_int = 24; -pub const ENOTTY: ::c_int = 25; -pub const ETXTBSY: ::c_int = 26; -pub const EFBIG: ::c_int = 27; -pub const ENOSPC: ::c_int = 28; -pub const ESPIPE: ::c_int = 29; -pub const EROFS: ::c_int = 30; -pub const EMLINK: ::c_int = 31; -pub const EPIPE: ::c_int = 32; -pub const EDOM: ::c_int = 33; -pub const ERANGE: ::c_int = 34; -pub const EAGAIN: ::c_int = 35; -pub const EWOULDBLOCK: ::c_int = 35; -pub const EINPROGRESS: ::c_int = 36; -pub const EALREADY: ::c_int = 37; -pub const ENOTSOCK: ::c_int = 38; -pub const EDESTADDRREQ: ::c_int = 39; -pub const EMSGSIZE: ::c_int = 40; -pub const EPROTOTYPE: ::c_int = 41; -pub const ENOPROTOOPT: ::c_int = 42; -pub const EPROTONOSUPPORT: ::c_int = 43; -pub const ESOCKTNOSUPPORT: ::c_int = 44; -pub const EOPNOTSUPP: ::c_int = 45; -pub const ENOTSUP: ::c_int = EOPNOTSUPP; -pub const EPFNOSUPPORT: ::c_int = 46; -pub const EAFNOSUPPORT: ::c_int = 47; -pub const EADDRINUSE: ::c_int = 48; -pub const EADDRNOTAVAIL: ::c_int = 49; -pub const ENETDOWN: ::c_int = 50; -pub const ENETUNREACH: ::c_int = 51; -pub const ENETRESET: ::c_int = 52; -pub const ECONNABORTED: ::c_int = 53; -pub const ECONNRESET: ::c_int = 54; -pub const ENOBUFS: ::c_int = 55; -pub const EISCONN: ::c_int = 56; -pub const ENOTCONN: ::c_int = 57; -pub const ESHUTDOWN: ::c_int = 58; -pub const ETOOMANYREFS: ::c_int = 59; -pub const ETIMEDOUT: ::c_int = 60; -pub const ECONNREFUSED: ::c_int = 61; -pub const ELOOP: ::c_int = 62; -pub const ENAMETOOLONG: ::c_int = 63; -pub const EHOSTDOWN: ::c_int = 64; -pub const EHOSTUNREACH: ::c_int = 65; -pub const ENOTEMPTY: ::c_int = 66; -pub const EPROCLIM: ::c_int = 67; -pub const EUSERS: ::c_int = 68; -pub const EDQUOT: ::c_int = 69; -pub const ESTALE: ::c_int = 70; -pub const EREMOTE: ::c_int = 71; -pub const EBADRPC: ::c_int = 72; -pub const ERPCMISMATCH: ::c_int = 73; -pub const EPROGUNAVAIL: ::c_int = 74; -pub const EPROGMISMATCH: ::c_int = 75; -pub const EPROCUNAVAIL: ::c_int = 76; -pub const ENOLCK: ::c_int = 77; -pub const ENOSYS: ::c_int = 78; -pub const EFTYPE: ::c_int = 79; -pub const EAUTH: ::c_int = 80; -pub const ENEEDAUTH: ::c_int = 81; -pub const EIDRM: ::c_int = 82; -pub const ENOMSG: ::c_int = 83; -pub const EOVERFLOW: ::c_int = 84; -pub const ECANCELED: ::c_int = 85; -pub const EILSEQ: ::c_int = 86; -pub const ENOATTR: ::c_int = 87; -pub const EDOOFUS: ::c_int = 88; -pub const EBADMSG: ::c_int = 89; -pub const EMULTIHOP: ::c_int = 90; -pub const ENOLINK: ::c_int = 91; -pub const EPROTO: ::c_int = 92; - -pub const POLLSTANDARD: ::c_short = ::POLLIN | ::POLLPRI | ::POLLOUT | - ::POLLRDNORM | ::POLLRDBAND | ::POLLWRBAND | ::POLLERR | - ::POLLHUP | ::POLLNVAL; - -pub const EAI_AGAIN: ::c_int = 2; -pub const EAI_BADFLAGS: ::c_int = 3; -pub const EAI_FAIL: ::c_int = 4; -pub const EAI_FAMILY: ::c_int = 5; -pub const EAI_MEMORY: ::c_int = 6; -pub const EAI_NONAME: ::c_int = 8; -pub const EAI_SERVICE: ::c_int = 9; -pub const EAI_SOCKTYPE: ::c_int = 10; -pub const EAI_SYSTEM: ::c_int = 11; -pub const EAI_OVERFLOW: ::c_int = 14; - -pub const F_DUPFD: ::c_int = 0; -pub const F_GETFD: ::c_int = 1; -pub const F_SETFD: ::c_int = 2; -pub const F_GETFL: ::c_int = 3; -pub const F_SETFL: ::c_int = 4; - -pub const SIGTRAP: ::c_int = 5; - -pub const GLOB_APPEND : ::c_int = 0x0001; -pub const GLOB_DOOFFS : ::c_int = 0x0002; -pub const GLOB_ERR : ::c_int = 0x0004; -pub const GLOB_MARK : ::c_int = 0x0008; -pub const GLOB_NOCHECK : ::c_int = 0x0010; -pub const GLOB_NOSORT : ::c_int = 0x0020; -pub const GLOB_NOESCAPE: ::c_int = 0x2000; - -pub const GLOB_NOSPACE : ::c_int = -1; -pub const GLOB_ABORTED : ::c_int = -2; -pub const GLOB_NOMATCH : ::c_int = -3; - -pub const POSIX_MADV_NORMAL: ::c_int = 0; -pub const POSIX_MADV_RANDOM: ::c_int = 1; -pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; -pub const POSIX_MADV_WILLNEED: ::c_int = 3; -pub const POSIX_MADV_DONTNEED: ::c_int = 4; - -pub const PTHREAD_PROCESS_PRIVATE: ::c_int = 0; -pub const PTHREAD_PROCESS_SHARED: ::c_int = 1; -pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; -pub const PTHREAD_CREATE_DETACHED: ::c_int = 1; - -pub const RLIMIT_CPU: ::c_int = 0; -pub const RLIMIT_FSIZE: ::c_int = 1; -pub const RLIMIT_DATA: ::c_int = 2; -pub const RLIMIT_STACK: ::c_int = 3; -pub const RLIMIT_CORE: ::c_int = 4; -pub const RLIMIT_RSS: ::c_int = 5; -pub const RLIMIT_MEMLOCK: ::c_int = 6; -pub const RLIMIT_NPROC: ::c_int = 7; -pub const RLIMIT_NOFILE: ::c_int = 8; -pub const RLIMIT_SBSIZE: ::c_int = 9; -pub const RLIMIT_VMEM: ::c_int = 10; -pub const RLIMIT_AS: ::c_int = RLIMIT_VMEM; -pub const RLIM_INFINITY: rlim_t = 0x7fff_ffff_ffff_ffff; - -pub const RUSAGE_SELF: ::c_int = 0; -pub const RUSAGE_CHILDREN: ::c_int = -1; - -pub const MADV_NORMAL: ::c_int = 0; -pub const MADV_RANDOM: ::c_int = 1; -pub const MADV_SEQUENTIAL: ::c_int = 2; -pub const MADV_WILLNEED: ::c_int = 3; -pub const MADV_DONTNEED: ::c_int = 4; -pub const MADV_FREE: ::c_int = 5; -pub const MADV_NOSYNC: ::c_int = 6; -pub const MADV_AUTOSYNC: ::c_int = 7; -pub const MADV_NOCORE: ::c_int = 8; -pub const MADV_CORE: ::c_int = 9; - -pub const MINCORE_INCORE: ::c_int = 0x1; -pub const MINCORE_REFERENCED: ::c_int = 0x2; -pub const MINCORE_MODIFIED: ::c_int = 0x4; -pub const MINCORE_REFERENCED_OTHER: ::c_int = 0x8; -pub const MINCORE_MODIFIED_OTHER: ::c_int = 0x10; -pub const MINCORE_SUPER: ::c_int = 0x20; - -pub const AF_UNSPEC: ::c_int = 0; -pub const AF_LOCAL: ::c_int = 1; -pub const AF_UNIX: ::c_int = AF_LOCAL; -pub const AF_INET: ::c_int = 2; -pub const AF_IMPLINK: ::c_int = 3; -pub const AF_PUP: ::c_int = 4; -pub const AF_CHAOS: ::c_int = 5; -pub const AF_NETBIOS: ::c_int = 6; -pub const AF_ISO: ::c_int = 7; -pub const AF_OSI: ::c_int = AF_ISO; -pub const AF_ECMA: ::c_int = 8; -pub const AF_DATAKIT: ::c_int = 9; -pub const AF_CCITT: ::c_int = 10; -pub const AF_SNA: ::c_int = 11; -pub const AF_DECnet: ::c_int = 12; -pub const AF_DLI: ::c_int = 13; -pub const AF_LAT: ::c_int = 14; -pub const AF_HYLINK: ::c_int = 15; -pub const AF_APPLETALK: ::c_int = 16; -pub const AF_ROUTE: ::c_int = 17; -pub const AF_LINK: ::c_int = 18; -pub const pseudo_AF_XTP: ::c_int = 19; -pub const AF_COIP: ::c_int = 20; -pub const AF_CNT: ::c_int = 21; -pub const pseudo_AF_RTIP: ::c_int = 22; -pub const AF_IPX: ::c_int = 23; -pub const AF_SIP: ::c_int = 24; -pub const pseudo_AF_PIP: ::c_int = 25; -pub const AF_ISDN: ::c_int = 26; -pub const AF_E164: ::c_int = AF_ISDN; -pub const pseudo_AF_KEY: ::c_int = 27; -pub const AF_INET6: ::c_int = 28; -pub const AF_NATM: ::c_int = 29; -pub const AF_ATM: ::c_int = 30; -pub const pseudo_AF_HDRCMPLT: ::c_int = 31; -pub const AF_NETGRAPH: ::c_int = 32; - -pub const PF_UNSPEC: ::c_int = AF_UNSPEC; -pub const PF_LOCAL: ::c_int = AF_LOCAL; -pub const PF_UNIX: ::c_int = PF_LOCAL; -pub const PF_INET: ::c_int = AF_INET; -pub const PF_IMPLINK: ::c_int = AF_IMPLINK; -pub const PF_PUP: ::c_int = AF_PUP; -pub const PF_CHAOS: ::c_int = AF_CHAOS; -pub const PF_NETBIOS: ::c_int = AF_NETBIOS; -pub const PF_ISO: ::c_int = AF_ISO; -pub const PF_OSI: ::c_int = AF_ISO; -pub const PF_ECMA: ::c_int = AF_ECMA; -pub const PF_DATAKIT: ::c_int = AF_DATAKIT; -pub const PF_CCITT: ::c_int = AF_CCITT; -pub const PF_SNA: ::c_int = AF_SNA; -pub const PF_DECnet: ::c_int = AF_DECnet; -pub const PF_DLI: ::c_int = AF_DLI; -pub const PF_LAT: ::c_int = AF_LAT; -pub const PF_HYLINK: ::c_int = AF_HYLINK; -pub const PF_APPLETALK: ::c_int = AF_APPLETALK; -pub const PF_ROUTE: ::c_int = AF_ROUTE; -pub const PF_LINK: ::c_int = AF_LINK; -pub const PF_XTP: ::c_int = pseudo_AF_XTP; -pub const PF_COIP: ::c_int = AF_COIP; -pub const PF_CNT: ::c_int = AF_CNT; -pub const PF_SIP: ::c_int = AF_SIP; -pub const PF_IPX: ::c_int = AF_IPX; -pub const PF_RTIP: ::c_int = pseudo_AF_RTIP; -pub const PF_PIP: ::c_int = pseudo_AF_PIP; -pub const PF_ISDN: ::c_int = AF_ISDN; -pub const PF_KEY: ::c_int = pseudo_AF_KEY; -pub const PF_INET6: ::c_int = AF_INET6; -pub const PF_NATM: ::c_int = AF_NATM; -pub const PF_ATM: ::c_int = AF_ATM; -pub const PF_NETGRAPH: ::c_int = AF_NETGRAPH; - -pub const SOMAXCONN: ::c_int = 128; - -pub const MSG_OOB: ::c_int = 0x00000001; -pub const MSG_PEEK: ::c_int = 0x00000002; -pub const MSG_DONTROUTE: ::c_int = 0x00000004; -pub const MSG_EOR: ::c_int = 0x00000008; -pub const MSG_TRUNC: ::c_int = 0x00000010; -pub const MSG_CTRUNC: ::c_int = 0x00000020; -pub const MSG_WAITALL: ::c_int = 0x00000040; -pub const MSG_DONTWAIT: ::c_int = 0x00000080; -pub const MSG_EOF: ::c_int = 0x00000100; - -pub const SCM_TIMESTAMP: ::c_int = 0x02; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; -pub const SOCK_RAW: ::c_int = 3; -pub const SOCK_RDM: ::c_int = 4; -pub const SOCK_SEQPACKET: ::c_int = 5; -pub const SOCK_CLOEXEC: ::c_int = 0x10000000; -pub const SOCK_NONBLOCK: ::c_int = 0x20000000; -pub const SOCK_MAXADDRLEN: ::c_int = 255; -pub const IP_TTL: ::c_int = 4; -pub const IP_HDRINCL: ::c_int = 2; -pub const IP_ADD_MEMBERSHIP: ::c_int = 12; -pub const IP_DROP_MEMBERSHIP: ::c_int = 13; -pub const IPV6_JOIN_GROUP: ::c_int = 12; -pub const IPV6_LEAVE_GROUP: ::c_int = 13; - -pub const TCP_NODELAY: ::c_int = 1; -pub const TCP_KEEPIDLE: ::c_int = 256; -pub const SOL_SOCKET: ::c_int = 0xffff; -pub const SO_DEBUG: ::c_int = 0x01; -pub const SO_ACCEPTCONN: ::c_int = 0x0002; -pub const SO_REUSEADDR: ::c_int = 0x0004; -pub const SO_KEEPALIVE: ::c_int = 0x0008; -pub const SO_DONTROUTE: ::c_int = 0x0010; -pub const SO_BROADCAST: ::c_int = 0x0020; -pub const SO_USELOOPBACK: ::c_int = 0x0040; -pub const SO_LINGER: ::c_int = 0x0080; -pub const SO_OOBINLINE: ::c_int = 0x0100; -pub const SO_REUSEPORT: ::c_int = 0x0200; -pub const SO_TIMESTAMP: ::c_int = 0x0400; -pub const SO_NOSIGPIPE: ::c_int = 0x0800; -pub const SO_ACCEPTFILTER: ::c_int = 0x1000; -pub const SO_SNDBUF: ::c_int = 0x1001; -pub const SO_RCVBUF: ::c_int = 0x1002; -pub const SO_SNDLOWAT: ::c_int = 0x1003; -pub const SO_RCVLOWAT: ::c_int = 0x1004; -pub const SO_SNDTIMEO: ::c_int = 0x1005; -pub const SO_RCVTIMEO: ::c_int = 0x1006; -pub const SO_ERROR: ::c_int = 0x1007; -pub const SO_TYPE: ::c_int = 0x1008; - -pub const SHUT_RD: ::c_int = 0; -pub const SHUT_WR: ::c_int = 1; -pub const SHUT_RDWR: ::c_int = 2; - -pub const LOCK_SH: ::c_int = 1; -pub const LOCK_EX: ::c_int = 2; -pub const LOCK_NB: ::c_int = 4; -pub const LOCK_UN: ::c_int = 8; - -pub const MAP_COPY: ::c_int = 0x0002; -pub const MAP_RENAME: ::c_int = 0x0020; -pub const MAP_NORESERVE: ::c_int = 0x0040; -pub const MAP_HASSEMAPHORE: ::c_int = 0x0200; -pub const MAP_STACK: ::c_int = 0x0400; -pub const MAP_NOSYNC: ::c_int = 0x0800; -pub const MAP_NOCORE: ::c_int = 0x020000; - -pub const IPPROTO_RAW: ::c_int = 255; - -pub const _PC_LINK_MAX: ::c_int = 1; -pub const _PC_MAX_CANON: ::c_int = 2; -pub const _PC_MAX_INPUT: ::c_int = 3; -pub const _PC_NAME_MAX: ::c_int = 4; -pub const _PC_PATH_MAX: ::c_int = 5; -pub const _PC_PIPE_BUF: ::c_int = 6; -pub const _PC_CHOWN_RESTRICTED: ::c_int = 7; -pub const _PC_NO_TRUNC: ::c_int = 8; -pub const _PC_VDISABLE: ::c_int = 9; -pub const _PC_ALLOC_SIZE_MIN: ::c_int = 10; -pub const _PC_FILESIZEBITS: ::c_int = 12; -pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 14; -pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 15; -pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 16; -pub const _PC_REC_XFER_ALIGN: ::c_int = 17; -pub const _PC_SYMLINK_MAX: ::c_int = 18; -pub const _PC_MIN_HOLE_SIZE: ::c_int = 21; -pub const _PC_ASYNC_IO: ::c_int = 53; -pub const _PC_PRIO_IO: ::c_int = 54; -pub const _PC_SYNC_IO: ::c_int = 55; -pub const _PC_ACL_EXTENDED: ::c_int = 59; -pub const _PC_ACL_PATH_MAX: ::c_int = 60; -pub const _PC_CAP_PRESENT: ::c_int = 61; -pub const _PC_INF_PRESENT: ::c_int = 62; -pub const _PC_MAC_PRESENT: ::c_int = 63; - -pub const _SC_ARG_MAX: ::c_int = 1; -pub const _SC_CHILD_MAX: ::c_int = 2; -pub const _SC_CLK_TCK: ::c_int = 3; -pub const _SC_NGROUPS_MAX: ::c_int = 4; -pub const _SC_OPEN_MAX: ::c_int = 5; -pub const _SC_JOB_CONTROL: ::c_int = 6; -pub const _SC_SAVED_IDS: ::c_int = 7; -pub const _SC_VERSION: ::c_int = 8; -pub const _SC_BC_BASE_MAX: ::c_int = 9; -pub const _SC_BC_DIM_MAX: ::c_int = 10; -pub const _SC_BC_SCALE_MAX: ::c_int = 11; -pub const _SC_BC_STRING_MAX: ::c_int = 12; -pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 13; -pub const _SC_EXPR_NEST_MAX: ::c_int = 14; -pub const _SC_LINE_MAX: ::c_int = 15; -pub const _SC_RE_DUP_MAX: ::c_int = 16; -pub const _SC_2_VERSION: ::c_int = 17; -pub const _SC_2_C_BIND: ::c_int = 18; -pub const _SC_2_C_DEV: ::c_int = 19; -pub const _SC_2_CHAR_TERM: ::c_int = 20; -pub const _SC_2_FORT_DEV: ::c_int = 21; -pub const _SC_2_FORT_RUN: ::c_int = 22; -pub const _SC_2_LOCALEDEF: ::c_int = 23; -pub const _SC_2_SW_DEV: ::c_int = 24; -pub const _SC_2_UPE: ::c_int = 25; -pub const _SC_STREAM_MAX: ::c_int = 26; -pub const _SC_TZNAME_MAX: ::c_int = 27; -pub const _SC_ASYNCHRONOUS_IO: ::c_int = 28; -pub const _SC_MAPPED_FILES: ::c_int = 29; -pub const _SC_MEMLOCK: ::c_int = 30; -pub const _SC_MEMLOCK_RANGE: ::c_int = 31; -pub const _SC_MEMORY_PROTECTION: ::c_int = 32; -pub const _SC_MESSAGE_PASSING: ::c_int = 33; -pub const _SC_PRIORITIZED_IO: ::c_int = 34; -pub const _SC_PRIORITY_SCHEDULING: ::c_int = 35; -pub const _SC_REALTIME_SIGNALS: ::c_int = 36; -pub const _SC_SEMAPHORES: ::c_int = 37; -pub const _SC_FSYNC: ::c_int = 38; -pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 39; -pub const _SC_SYNCHRONIZED_IO: ::c_int = 40; -pub const _SC_TIMERS: ::c_int = 41; -pub const _SC_AIO_LISTIO_MAX: ::c_int = 42; -pub const _SC_AIO_MAX: ::c_int = 43; -pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 44; -pub const _SC_DELAYTIMER_MAX: ::c_int = 45; -pub const _SC_MQ_OPEN_MAX: ::c_int = 46; -pub const _SC_PAGESIZE: ::c_int = 47; -pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; -pub const _SC_RTSIG_MAX: ::c_int = 48; -pub const _SC_SEM_NSEMS_MAX: ::c_int = 49; -pub const _SC_SEM_VALUE_MAX: ::c_int = 50; -pub const _SC_SIGQUEUE_MAX: ::c_int = 51; -pub const _SC_TIMER_MAX: ::c_int = 52; -pub const _SC_IOV_MAX: ::c_int = 56; -pub const _SC_NPROCESSORS_CONF: ::c_int = 57; -pub const _SC_2_PBS: ::c_int = 59; -pub const _SC_2_PBS_ACCOUNTING: ::c_int = 60; -pub const _SC_2_PBS_CHECKPOINT: ::c_int = 61; -pub const _SC_2_PBS_LOCATE: ::c_int = 62; -pub const _SC_2_PBS_MESSAGE: ::c_int = 63; -pub const _SC_2_PBS_TRACK: ::c_int = 64; -pub const _SC_ADVISORY_INFO: ::c_int = 65; -pub const _SC_BARRIERS: ::c_int = 66; -pub const _SC_CLOCK_SELECTION: ::c_int = 67; -pub const _SC_CPUTIME: ::c_int = 68; -pub const _SC_FILE_LOCKING: ::c_int = 69; -pub const _SC_NPROCESSORS_ONLN: ::c_int = 58; -pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 70; -pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 71; -pub const _SC_HOST_NAME_MAX: ::c_int = 72; -pub const _SC_LOGIN_NAME_MAX: ::c_int = 73; -pub const _SC_MONOTONIC_CLOCK: ::c_int = 74; -pub const _SC_MQ_PRIO_MAX: ::c_int = 75; -pub const _SC_READER_WRITER_LOCKS: ::c_int = 76; -pub const _SC_REGEXP: ::c_int = 77; -pub const _SC_SHELL: ::c_int = 78; -pub const _SC_SPAWN: ::c_int = 79; -pub const _SC_SPIN_LOCKS: ::c_int = 80; -pub const _SC_SPORADIC_SERVER: ::c_int = 81; -pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 82; -pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 83; -pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 85; -pub const _SC_THREAD_KEYS_MAX: ::c_int = 86; -pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 87; -pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 88; -pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 89; -pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 90; -pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 91; -pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 92; -pub const _SC_THREAD_STACK_MIN: ::c_int = 93; -pub const _SC_THREAD_THREADS_MAX: ::c_int = 94; -pub const _SC_TIMEOUTS: ::c_int = 95; -pub const _SC_THREADS: ::c_int = 96; -pub const _SC_TRACE: ::c_int = 97; -pub const _SC_TRACE_EVENT_FILTER: ::c_int = 98; -pub const _SC_TRACE_INHERIT: ::c_int = 99; -pub const _SC_TRACE_LOG: ::c_int = 100; -pub const _SC_TTY_NAME_MAX: ::c_int = 101; -pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 102; -pub const _SC_V6_ILP32_OFF32: ::c_int = 103; -pub const _SC_V6_ILP32_OFFBIG: ::c_int = 104; -pub const _SC_V6_LP64_OFF64: ::c_int = 105; -pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 106; -pub const _SC_ATEXIT_MAX: ::c_int = 107; -pub const _SC_XOPEN_CRYPT: ::c_int = 108; -pub const _SC_XOPEN_ENH_I18N: ::c_int = 109; -pub const _SC_XOPEN_LEGACY: ::c_int = 110; -pub const _SC_XOPEN_REALTIME: ::c_int = 111; -pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 112; -pub const _SC_XOPEN_SHM: ::c_int = 113; -pub const _SC_XOPEN_STREAMS: ::c_int = 114; -pub const _SC_XOPEN_UNIX: ::c_int = 115; -pub const _SC_XOPEN_VERSION: ::c_int = 116; -pub const _SC_XOPEN_XCU_VERSION: ::c_int = 117; -pub const _SC_IPV6: ::c_int = 118; -pub const _SC_RAW_SOCKETS: ::c_int = 119; -pub const _SC_SYMLOOP_MAX: ::c_int = 120; -pub const _SC_PHYS_PAGES: ::c_int = 121; - -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = 0 as *mut _; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = 0 as *mut _; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = 0 as *mut _; -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 1; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 2; -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 3; -pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_ERRORCHECK; - -pub const SCHED_FIFO: ::c_int = 1; -pub const SCHED_OTHER: ::c_int = 2; -pub const SCHED_RR: ::c_int = 3; - -pub const FD_SETSIZE: usize = 1024; - -pub const ST_NOSUID: ::c_ulong = 2; - -pub const NI_MAXHOST: ::size_t = 1025; - -pub const RTLD_LOCAL: ::c_int = 0; -pub const RTLD_NODELETE: ::c_int = 0x1000; -pub const RTLD_NOLOAD: ::c_int = 0x2000; -pub const RTLD_GLOBAL: ::c_int = 0x100; - -pub const LOG_NTP: ::c_int = 12 << 3; -pub const LOG_SECURITY: ::c_int = 13 << 3; -pub const LOG_CONSOLE: ::c_int = 14 << 3; -pub const LOG_NFACILITIES: ::c_int = 24; - -pub const TIOCEXCL: ::c_uint = 0x2000740d; -pub const TIOCNXCL: ::c_uint = 0x2000740e; -pub const TIOCFLUSH: ::c_ulong = 0x80047410; -pub const TIOCGETA: ::c_uint = 0x402c7413; -pub const TIOCSETA: ::c_ulong = 0x802c7414; -pub const TIOCSETAW: ::c_ulong = 0x802c7415; -pub const TIOCSETAF: ::c_ulong = 0x802c7416; -pub const TIOCGETD: ::c_uint = 0x4004741a; -pub const TIOCSETD: ::c_ulong = 0x8004741b; -pub const TIOCGDRAINWAIT: ::c_uint = 0x40047456; -pub const TIOCSDRAINWAIT: ::c_ulong = 0x80047457; -pub const TIOCTIMESTAMP: ::c_uint = 0x40107459; -pub const TIOCMGDTRWAIT: ::c_uint = 0x4004745a; -pub const TIOCMSDTRWAIT: ::c_ulong = 0x8004745b; -pub const TIOCDRAIN: ::c_uint = 0x2000745e; -pub const TIOCEXT: ::c_ulong = 0x80047460; -pub const TIOCSCTTY: ::c_uint = 0x20007461; -pub const TIOCCONS: ::c_ulong = 0x80047462; -pub const TIOCGSID: ::c_uint = 0x40047463; -pub const TIOCSTAT: ::c_uint = 0x20007465; -pub const TIOCUCNTL: ::c_ulong = 0x80047466; -pub const TIOCSWINSZ: ::c_ulong = 0x80087467; -pub const TIOCGWINSZ: ::c_uint = 0x40087468; -pub const TIOCMGET: ::c_uint = 0x4004746a; -pub const TIOCM_LE: ::c_int = 0x1; -pub const TIOCM_DTR: ::c_int = 0x2; -pub const TIOCM_RTS: ::c_int = 0x4; -pub const TIOCM_ST: ::c_int = 0x8; -pub const TIOCM_SR: ::c_int = 0x10; -pub const TIOCM_CTS: ::c_int = 0x20; -pub const TIOCM_RI: ::c_int = 0x80; -pub const TIOCM_DSR: ::c_int = 0x100; -pub const TIOCM_CD: ::c_int = 0x40; -pub const TIOCM_CAR: ::c_int = 0x40; -pub const TIOCM_RNG: ::c_int = 0x80; -pub const TIOCMBIC: ::c_ulong = 0x8004746b; -pub const TIOCMBIS: ::c_ulong = 0x8004746c; -pub const TIOCMSET: ::c_ulong = 0x8004746d; -pub const TIOCSTART: ::c_uint = 0x2000746e; -pub const TIOCSTOP: ::c_uint = 0x2000746f; -pub const TIOCPKT: ::c_ulong = 0x80047470; -pub const TIOCPKT_DATA: ::c_int = 0x0; -pub const TIOCPKT_FLUSHREAD: ::c_int = 0x1; -pub const TIOCPKT_FLUSHWRITE: ::c_int = 0x2; -pub const TIOCPKT_STOP: ::c_int = 0x4; -pub const TIOCPKT_START: ::c_int = 0x8; -pub const TIOCPKT_NOSTOP: ::c_int = 0x10; -pub const TIOCPKT_DOSTOP: ::c_int = 0x20; -pub const TIOCPKT_IOCTL: ::c_int = 0x40; -pub const TIOCNOTTY: ::c_uint = 0x20007471; -pub const TIOCSTI: ::c_ulong = 0x80017472; -pub const TIOCOUTQ: ::c_uint = 0x40047473; -pub const TIOCSPGRP: ::c_ulong = 0x80047476; -pub const TIOCGPGRP: ::c_uint = 0x40047477; -pub const TIOCCDTR: ::c_uint = 0x20007478; -pub const TIOCSDTR: ::c_uint = 0x20007479; -pub const TIOCCBRK: ::c_uint = 0x2000747a; -pub const TIOCSBRK: ::c_uint = 0x2000747b; -pub const TTYDISC: ::c_int = 0x0; -pub const SLIPDISC: ::c_int = 0x4; -pub const PPPDISC: ::c_int = 0x5; -pub const NETGRAPHDISC: ::c_int = 0x6; - -pub const B0: speed_t = 0; -pub const B50: speed_t = 50; -pub const B75: speed_t = 75; -pub const B110: speed_t = 110; -pub const B134: speed_t = 134; -pub const B150: speed_t = 150; -pub const B200: speed_t = 200; -pub const B300: speed_t = 300; -pub const B600: speed_t = 600; -pub const B1200: speed_t = 1200; -pub const B1800: speed_t = 1800; -pub const B2400: speed_t = 2400; -pub const B4800: speed_t = 4800; -pub const B9600: speed_t = 9600; -pub const B19200: speed_t = 19200; -pub const B38400: speed_t = 38400; -pub const B7200: speed_t = 7200; -pub const B14400: speed_t = 14400; -pub const B28800: speed_t = 28800; -pub const B57600: speed_t = 57600; -pub const B76800: speed_t = 76800; -pub const B115200: speed_t = 115200; -pub const B230400: speed_t = 230400; -pub const EXTA: speed_t = 19200; -pub const EXTB: speed_t = 38400; - -pub const SEM_FAILED: *mut sem_t = 0 as *mut sem_t; - -pub const CRTSCTS: ::tcflag_t = 0x00030000; -pub const CCTS_OFLOW: ::tcflag_t = 0x00010000; -pub const CRTS_IFLOW: ::tcflag_t = 0x00020000; -pub const CDTR_IFLOW: ::tcflag_t = 0x00040000; -pub const CDSR_OFLOW: ::tcflag_t = 0x00080000; -pub const CCAR_OFLOW: ::tcflag_t = 0x00100000; -pub const VERASE2: usize = 7; -pub const OCRNL: ::tcflag_t = 0x10; -pub const ONOCR: ::tcflag_t = 0x20; -pub const ONLRET: ::tcflag_t = 0x40; - -pub const CMGROUP_MAX: usize = 16; - -// https://github.com/freebsd/freebsd/blob/master/sys/net/bpf.h -// sizeof(long) -pub const BPF_ALIGNMENT: ::c_int = 8; - -f! { - pub fn WIFCONTINUED(status: ::c_int) -> bool { - status == 0x13 - } - - pub fn WSTOPSIG(status: ::c_int) -> ::c_int { - status >> 8 - } - - pub fn WIFSIGNALED(status: ::c_int) -> bool { - (status & 0o177) != 0o177 && (status & 0o177) != 0 - } - - pub fn WIFSTOPPED(status: ::c_int) -> bool { - (status & 0o177) == 0o177 - } -} - -extern { - pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; - pub fn endutxent(); - pub fn getutxent() -> *mut utmpx; - pub fn getutxid(ut: *const utmpx) -> *mut utmpx; - pub fn getutxline(ut: *const utmpx) -> *mut utmpx; - pub fn pututxline(ut: *const utmpx) -> *mut utmpx; - pub fn setutxent(); - pub fn setresgid(rgid: ::gid_t, egid: ::gid_t, sgid: ::gid_t) -> ::c_int; - pub fn setresuid(ruid: ::uid_t, euid: ::uid_t, suid: ::uid_t) -> ::c_int; - pub fn getgrouplist(name: *const ::c_char, - basegid: ::gid_t, - groups: *mut ::gid_t, - ngroups: *mut ::c_int) -> ::c_int; - pub fn initgroups(name: *const ::c_char, basegid: ::gid_t) -> ::c_int; - pub fn mq_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::mqd_t; - pub fn mq_close(mqd: ::mqd_t) -> ::c_int; - pub fn mq_getattr(mqd: ::mqd_t, attr: *mut ::mq_attr) -> ::c_int; - pub fn mq_notify(mqd: ::mqd_t, notification: *const ::sigevent) -> ::c_int; - pub fn mq_receive(mqd: ::mqd_t, - msg_ptr: *mut ::c_char, - msg_len: ::size_t, - msq_prio: *mut ::c_uint) -> ::ssize_t; - pub fn mq_send(mqd: ::mqd_t, - msg_ptr: *const ::c_char, - msg_len: ::size_t, - msq_prio: ::c_uint) -> ::c_int; - pub fn mq_setattr(mqd: ::mqd_t, - newattr: *const ::mq_attr, - oldattr: *mut ::mq_attr) -> ::c_int; - pub fn mq_timedreceive(mqd: ::mqd_t, - msg_ptr: *mut ::c_char, - msg_len: ::size_t, - msq_prio: *mut ::c_uint, - abs_timeout: *const ::timespec) -> ::ssize_t; - pub fn mq_timedsend(mqd: ::mqd_t, - msg_ptr: *const ::c_char, - msg_len: ::size_t, - msq_prio: ::c_uint, - abs_timeout: *const ::timespec) -> ::c_int; - pub fn mq_unlink(name: *const ::c_char) -> ::c_int; -} - -#[link(name = "util")] -extern { - pub fn aio_read(aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_write(aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_fsync(op: ::c_int, aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_error(aiocbp: *const aiocb) -> ::c_int; - pub fn aio_return(aiocbp: *mut aiocb) -> ::ssize_t; - pub fn aio_suspend(aiocb_list: *const *const aiocb, nitems: ::c_int, - timeout: *const ::timespec) -> ::c_int; - pub fn aio_cancel(fd: ::c_int, aiocbp: *mut aiocb) -> ::c_int; - pub fn lio_listio(mode: ::c_int, aiocb_list: *const *mut aiocb, - nitems: ::c_int, sevp: *mut sigevent) -> ::c_int; - pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; - pub fn getnameinfo(sa: *const ::sockaddr, - salen: ::socklen_t, - host: *mut ::c_char, - hostlen: ::size_t, - serv: *mut ::c_char, - servlen: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn kevent(kq: ::c_int, - changelist: *const ::kevent, - nchanges: ::c_int, - eventlist: *mut ::kevent, - nevents: ::c_int, - timeout: *const ::timespec) -> ::c_int; - pub fn mincore(addr: *const ::c_void, len: ::size_t, - vec: *mut ::c_char) -> ::c_int; - pub fn pwritev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off_t) -> ::ssize_t; - pub fn preadv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off_t) -> ::ssize_t; - pub fn sysctlnametomib(name: *const ::c_char, - mibp: *mut ::c_int, - sizep: *mut ::size_t) - -> ::c_int; - pub fn shm_open(name: *const ::c_char, oflag: ::c_int, mode: ::mode_t) - -> ::c_int; - pub fn sysctl(name: *const ::c_int, - namelen: ::c_uint, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *const ::c_void, - newlen: ::size_t) - -> ::c_int; - pub fn sysctlbyname(name: *const ::c_char, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *const ::c_void, - newlen: ::size_t) - -> ::c_int; - pub fn sched_setscheduler(pid: ::pid_t, - policy: ::c_int, - param: *const ::sched_param) -> ::c_int; - pub fn sched_getscheduler(pid: ::pid_t) -> ::c_int; - pub fn memrchr(cx: *const ::c_void, - c: ::c_int, - n: ::size_t) -> *mut ::c_void; - pub fn sendfile(fd: ::c_int, - s: ::c_int, - offset: ::off_t, - nbytes: ::size_t, - hdtr: *mut ::sf_hdtr, - sbytes: *mut ::off_t, - flags: ::c_int) -> ::c_int; - pub fn sigtimedwait(set: *const sigset_t, - info: *mut siginfo_t, - timeout: *const ::timespec) -> ::c_int; - pub fn sigwaitinfo(set: *const sigset_t, - info: *mut siginfo_t) -> ::c_int; - pub fn openpty(amaster: *mut ::c_int, - aslave: *mut ::c_int, - name: *mut ::c_char, - termp: *mut termios, - winp: *mut ::winsize) -> ::c_int; - pub fn forkpty(amaster: *mut ::c_int, - name: *mut ::c_char, - termp: *mut termios, - winp: *mut ::winsize) -> ::pid_t; - pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; - pub fn duplocale(base: ::locale_t) -> ::locale_t; - pub fn newlocale(mask: ::c_int, - locale: *const ::c_char, - base: ::locale_t) -> ::locale_t; - pub fn uselocale(loc: ::locale_t) -> ::locale_t; - pub fn querylocale(mask: ::c_int, loc: ::locale_t) -> *const ::c_char; - pub fn accept4(s: ::c_int, addr: *mut ::sockaddr, - addrlen: *mut ::socklen_t, flags: ::c_int) -> ::c_int; - pub fn pthread_set_name_np(tid: ::pthread_t, name: *const ::c_char); - pub fn pthread_attr_get_np(tid: ::pthread_t, - attr: *mut ::pthread_attr_t) -> ::c_int; - pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, - guardsize: *mut ::size_t) -> ::c_int; - pub fn pthread_attr_getstack(attr: *const ::pthread_attr_t, - stackaddr: *mut *mut ::c_void, - stacksize: *mut ::size_t) -> ::c_int; - pub fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, - pshared: ::c_int) -> ::c_int; - pub fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, - pshared: *mut ::c_int) -> ::c_int; - pub fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, - pshared: ::c_int) -> ::c_int; - pub fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, - pshared: *mut ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, - val: *mut ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, - val: ::c_int) -> ::c_int; - pub fn getpriority(which: ::c_int, who: ::c_int) -> ::c_int; - pub fn setpriority(which: ::c_int, who: ::c_int, prio: ::c_int) -> ::c_int; - - pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; - - pub fn mknodat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t, dev: dev_t) -> ::c_int; - pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t) -> ::c_int; - pub fn pthread_condattr_getclock(attr: *const pthread_condattr_t, - clock_id: *mut clockid_t) -> ::c_int; - pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, - clock_id: ::clockid_t) -> ::c_int; - pub fn sethostname(name: *const ::c_char, len: ::c_int) -> ::c_int; - pub fn sem_timedwait(sem: *mut sem_t, - abstime: *const ::timespec) -> ::c_int; - pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, - abstime: *const ::timespec) -> ::c_int; - pub fn pipe2(fds: *mut ::c_int, flags: ::c_int) -> ::c_int; - pub fn ppoll(fds: *mut ::pollfd, - nfds: ::nfds_t, - timeout: *const ::timespec, - sigmask: *const sigset_t) -> ::c_int; - pub fn settimeofday(tv: *const ::timeval, tz: *const ::timezone) -> ::c_int; -} - -cfg_if! { - if #[cfg(target_os = "freebsd")] { - mod freebsd; - pub use self::freebsd::*; - } else if #[cfg(target_os = "dragonfly")] { - mod dragonfly; - pub use self::dragonfly::*; - } else { - // ... - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,548 +0,0 @@ -use dox::{mem, Option}; - -pub type wchar_t = i32; -pub type off_t = i64; -pub type useconds_t = u32; -pub type blkcnt_t = i64; -pub type socklen_t = u32; -pub type sa_family_t = u8; -pub type pthread_t = ::uintptr_t; -pub type nfds_t = ::c_uint; - -s! { - pub struct sockaddr { - pub sa_len: u8, - pub sa_family: sa_family_t, - pub sa_data: [::c_char; 14], - } - - pub struct sockaddr_in6 { - pub sin6_len: u8, - pub sin6_family: sa_family_t, - pub sin6_port: ::in_port_t, - pub sin6_flowinfo: u32, - pub sin6_addr: ::in6_addr, - pub sin6_scope_id: u32, - } - - pub struct sockaddr_un { - pub sun_len: u8, - pub sun_family: sa_family_t, - pub sun_path: [c_char; 104] - } - - pub struct passwd { - pub pw_name: *mut ::c_char, - pub pw_passwd: *mut ::c_char, - pub pw_uid: ::uid_t, - pub pw_gid: ::gid_t, - pub pw_change: ::time_t, - pub pw_class: *mut ::c_char, - pub pw_gecos: *mut ::c_char, - pub pw_dir: *mut ::c_char, - pub pw_shell: *mut ::c_char, - pub pw_expire: ::time_t, - - #[cfg(not(any(target_os = "macos", - target_os = "ios", - target_os = "netbsd", - target_os = "openbsd")))] - pub pw_fields: ::c_int, - } - - pub struct ifaddrs { - pub ifa_next: *mut ifaddrs, - pub ifa_name: *mut ::c_char, - pub ifa_flags: ::c_uint, - pub ifa_addr: *mut ::sockaddr, - pub ifa_netmask: *mut ::sockaddr, - pub ifa_dstaddr: *mut ::sockaddr, - pub ifa_data: *mut ::c_void - } - - pub struct fd_set { - #[cfg(all(target_pointer_width = "64", - any(target_os = "freebsd", target_os = "dragonfly")))] - fds_bits: [i64; FD_SETSIZE / 64], - #[cfg(not(all(target_pointer_width = "64", - any(target_os = "freebsd", target_os = "dragonfly"))))] - fds_bits: [i32; FD_SETSIZE / 32], - } - - pub struct tm { - pub tm_sec: ::c_int, - pub tm_min: ::c_int, - pub tm_hour: ::c_int, - pub tm_mday: ::c_int, - pub tm_mon: ::c_int, - pub tm_year: ::c_int, - pub tm_wday: ::c_int, - pub tm_yday: ::c_int, - pub tm_isdst: ::c_int, - pub tm_gmtoff: ::c_long, - pub tm_zone: *mut ::c_char, - } - - pub struct utsname { - #[cfg(not(target_os = "dragonfly"))] - pub sysname: [::c_char; 256], - #[cfg(target_os = "dragonfly")] - pub sysname: [::c_char; 32], - #[cfg(not(target_os = "dragonfly"))] - pub nodename: [::c_char; 256], - #[cfg(target_os = "dragonfly")] - pub nodename: [::c_char; 32], - #[cfg(not(target_os = "dragonfly"))] - pub release: [::c_char; 256], - #[cfg(target_os = "dragonfly")] - pub release: [::c_char; 32], - #[cfg(not(target_os = "dragonfly"))] - pub version: [::c_char; 256], - #[cfg(target_os = "dragonfly")] - pub version: [::c_char; 32], - #[cfg(not(target_os = "dragonfly"))] - pub machine: [::c_char; 256], - #[cfg(target_os = "dragonfly")] - pub machine: [::c_char; 32], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::c_int, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::socklen_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::socklen_t, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct fsid_t { - __fsid_val: [::int32_t; 2], - } - - pub struct if_nameindex { - pub if_index: ::c_uint, - pub if_name: *mut ::c_char, - } -} - -pub const LC_ALL: ::c_int = 0; -pub const LC_COLLATE: ::c_int = 1; -pub const LC_CTYPE: ::c_int = 2; -pub const LC_MONETARY: ::c_int = 3; -pub const LC_NUMERIC: ::c_int = 4; -pub const LC_TIME: ::c_int = 5; -pub const LC_MESSAGES: ::c_int = 6; - -pub const FIOCLEX: ::c_ulong = 0x20006601; -pub const FIONBIO: ::c_ulong = 0x8004667e; - -pub const PATH_MAX: ::c_int = 1024; - -pub const SA_ONSTACK: ::c_int = 0x0001; -pub const SA_SIGINFO: ::c_int = 0x0040; -pub const SA_RESTART: ::c_int = 0x0002; -pub const SA_RESETHAND: ::c_int = 0x0004; -pub const SA_NOCLDSTOP: ::c_int = 0x0008; -pub const SA_NODEFER: ::c_int = 0x0010; -pub const SA_NOCLDWAIT: ::c_int = 0x0020; - -pub const SS_ONSTACK: ::c_int = 1; -pub const SS_DISABLE: ::c_int = 4; - -pub const SIGCHLD: ::c_int = 20; -pub const SIGBUS: ::c_int = 10; -pub const SIGUSR1: ::c_int = 30; -pub const SIGUSR2: ::c_int = 31; -pub const SIGCONT: ::c_int = 19; -pub const SIGSTOP: ::c_int = 17; -pub const SIGTSTP: ::c_int = 18; -pub const SIGURG: ::c_int = 16; -pub const SIGIO: ::c_int = 23; -pub const SIGSYS: ::c_int = 12; -pub const SIGTTIN: ::c_int = 21; -pub const SIGTTOU: ::c_int = 22; -pub const SIGXCPU: ::c_int = 24; -pub const SIGXFSZ: ::c_int = 25; -pub const SIGVTALRM: ::c_int = 26; -pub const SIGPROF: ::c_int = 27; -pub const SIGWINCH: ::c_int = 28; -pub const SIGINFO: ::c_int = 29; - -pub const SIG_SETMASK: ::c_int = 3; -pub const SIG_BLOCK: ::c_int = 0x1; -pub const SIG_UNBLOCK: ::c_int = 0x2; - -pub const IP_MULTICAST_IF: ::c_int = 9; -pub const IP_MULTICAST_TTL: ::c_int = 10; -pub const IP_MULTICAST_LOOP: ::c_int = 11; - -pub const IPV6_MULTICAST_LOOP: ::c_int = 11; -pub const IPV6_V6ONLY: ::c_int = 27; - -pub const ST_RDONLY: ::c_ulong = 1; - -pub const SCM_RIGHTS: ::c_int = 0x01; - -pub const NCCS: usize = 20; - -pub const O_ACCMODE: ::c_int = 0x3; -pub const O_RDONLY: ::c_int = 0; -pub const O_WRONLY: ::c_int = 1; -pub const O_RDWR: ::c_int = 2; -pub const O_APPEND: ::c_int = 8; -pub const O_CREAT: ::c_int = 512; -pub const O_TRUNC: ::c_int = 1024; -pub const O_EXCL: ::c_int = 2048; -pub const O_ASYNC: ::c_int = 0x40; -pub const O_SYNC: ::c_int = 0x80; -pub const O_NONBLOCK: ::c_int = 0x4; -pub const O_NOFOLLOW: ::c_int = 0x100; -pub const O_SHLOCK: ::c_int = 0x10; -pub const O_EXLOCK: ::c_int = 0x20; -pub const O_FSYNC: ::c_int = O_SYNC; -pub const O_NDELAY: ::c_int = O_NONBLOCK; - -pub const F_GETOWN: ::c_int = 5; -pub const F_SETOWN: ::c_int = 6; - -pub const MNT_FORCE: ::c_int = 0x80000; - -pub const Q_SYNC: ::c_int = 0x600; -pub const Q_QUOTAON: ::c_int = 0x100; -pub const Q_QUOTAOFF: ::c_int = 0x200; - -pub const TCIOFF: ::c_int = 3; -pub const TCION: ::c_int = 4; -pub const TCOOFF: ::c_int = 1; -pub const TCOON: ::c_int = 2; -pub const TCIFLUSH: ::c_int = 1; -pub const TCOFLUSH: ::c_int = 2; -pub const TCIOFLUSH: ::c_int = 3; -pub const TCSANOW: ::c_int = 0; -pub const TCSADRAIN: ::c_int = 1; -pub const TCSAFLUSH: ::c_int = 2; -pub const VEOF: usize = 0; -pub const VEOL: usize = 1; -pub const VEOL2: usize = 2; -pub const VERASE: usize = 3; -pub const VWERASE: usize = 4; -pub const VKILL: usize = 5; -pub const VREPRINT: usize = 6; -pub const VINTR: usize = 8; -pub const VQUIT: usize = 9; -pub const VSUSP: usize = 10; -pub const VDSUSP: usize = 11; -pub const VSTART: usize = 12; -pub const VSTOP: usize = 13; -pub const VLNEXT: usize = 14; -pub const VDISCARD: usize = 15; -pub const VMIN: usize = 16; -pub const VTIME: usize = 17; -pub const VSTATUS: usize = 18; -pub const _POSIX_VDISABLE: ::cc_t = 0xff; -pub const IGNBRK: ::tcflag_t = 0x00000001; -pub const BRKINT: ::tcflag_t = 0x00000002; -pub const IGNPAR: ::tcflag_t = 0x00000004; -pub const PARMRK: ::tcflag_t = 0x00000008; -pub const INPCK: ::tcflag_t = 0x00000010; -pub const ISTRIP: ::tcflag_t = 0x00000020; -pub const INLCR: ::tcflag_t = 0x00000040; -pub const IGNCR: ::tcflag_t = 0x00000080; -pub const ICRNL: ::tcflag_t = 0x00000100; -pub const IXON: ::tcflag_t = 0x00000200; -pub const IXOFF: ::tcflag_t = 0x00000400; -pub const IXANY: ::tcflag_t = 0x00000800; -pub const IMAXBEL: ::tcflag_t = 0x00002000; -pub const OPOST: ::tcflag_t = 0x1; -pub const ONLCR: ::tcflag_t = 0x2; -pub const OXTABS: ::tcflag_t = 0x4; -pub const ONOEOT: ::tcflag_t = 0x8; -pub const CIGNORE: ::tcflag_t = 0x00000001; -pub const CSIZE: ::tcflag_t = 0x00000300; -pub const CS5: ::tcflag_t = 0x00000000; -pub const CS6: ::tcflag_t = 0x00000100; -pub const CS7: ::tcflag_t = 0x00000200; -pub const CS8: ::tcflag_t = 0x00000300; -pub const CSTOPB: ::tcflag_t = 0x00000400; -pub const CREAD: ::tcflag_t = 0x00000800; -pub const PARENB: ::tcflag_t = 0x00001000; -pub const PARODD: ::tcflag_t = 0x00002000; -pub const HUPCL: ::tcflag_t = 0x00004000; -pub const CLOCAL: ::tcflag_t = 0x00008000; -pub const ECHOKE: ::tcflag_t = 0x00000001; -pub const ECHOE: ::tcflag_t = 0x00000002; -pub const ECHOK: ::tcflag_t = 0x00000004; -pub const ECHO: ::tcflag_t = 0x00000008; -pub const ECHONL: ::tcflag_t = 0x00000010; -pub const ECHOPRT: ::tcflag_t = 0x00000020; -pub const ECHOCTL: ::tcflag_t = 0x00000040; -pub const ISIG: ::tcflag_t = 0x00000080; -pub const ICANON: ::tcflag_t = 0x00000100; -pub const ALTWERASE: ::tcflag_t = 0x00000200; -pub const IEXTEN: ::tcflag_t = 0x00000400; -pub const EXTPROC: ::tcflag_t = 0x00000800; -pub const TOSTOP: ::tcflag_t = 0x00400000; -pub const FLUSHO: ::tcflag_t = 0x00800000; -pub const NOKERNINFO: ::tcflag_t = 0x02000000; -pub const PENDIN: ::tcflag_t = 0x20000000; -pub const NOFLSH: ::tcflag_t = 0x80000000; -pub const MDMBUF: ::tcflag_t = 0x00100000; - -pub const WNOHANG: ::c_int = 0x00000001; -pub const WUNTRACED: ::c_int = 0x00000002; - -pub const RTLD_LAZY: ::c_int = 0x1; -pub const RTLD_NOW: ::c_int = 0x2; -pub const RTLD_NEXT: *mut ::c_void = -1isize as *mut ::c_void; -pub const RTLD_DEFAULT: *mut ::c_void = -2isize as *mut ::c_void; -pub const RTLD_SELF: *mut ::c_void = -3isize as *mut ::c_void; - -pub const LOG_CRON: ::c_int = 9 << 3; -pub const LOG_AUTHPRIV: ::c_int = 10 << 3; -pub const LOG_FTP: ::c_int = 11 << 3; -pub const LOG_PERROR: ::c_int = 0x20; - -pub const TCP_MAXSEG: ::c_int = 2; - -pub const PIPE_BUF: usize = 512; - -pub const POLLIN: ::c_short = 0x1; -pub const POLLPRI: ::c_short = 0x2; -pub const POLLOUT: ::c_short = 0x4; -pub const POLLERR: ::c_short = 0x8; -pub const POLLHUP: ::c_short = 0x10; -pub const POLLNVAL: ::c_short = 0x20; -pub const POLLRDNORM: ::c_short = 0x040; -pub const POLLWRNORM: ::c_short = 0x004; -pub const POLLRDBAND: ::c_short = 0x080; -pub const POLLWRBAND: ::c_short = 0x100; - -f! { - pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { - let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; - let fd = fd as usize; - (*set).fds_bits[fd / bits] &= !(1 << (fd % bits)); - return - } - - pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { - let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; - let fd = fd as usize; - return ((*set).fds_bits[fd / bits] & (1 << (fd % bits))) != 0 - } - - pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { - let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; - let fd = fd as usize; - (*set).fds_bits[fd / bits] |= 1 << (fd % bits); - return - } - - pub fn FD_ZERO(set: *mut fd_set) -> () { - for slot in (*set).fds_bits.iter_mut() { - *slot = 0; - } - } - - pub fn WTERMSIG(status: ::c_int) -> ::c_int { - status & 0o177 - } - - pub fn WIFEXITED(status: ::c_int) -> bool { - (status & 0o177) == 0 - } - - pub fn WEXITSTATUS(status: ::c_int) -> ::c_int { - status >> 8 - } - - pub fn WCOREDUMP(status: ::c_int) -> bool { - (status & 0o200) != 0 - } - - pub fn QCMD(cmd: ::c_int, type_: ::c_int) -> ::c_int { - (cmd << 8) | (type_ & 0x00ff) - } -} - -extern { - pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; - pub fn freeifaddrs(ifa: *mut ::ifaddrs); - pub fn setgroups(ngroups: ::c_int, - ptr: *const ::gid_t) -> ::c_int; - pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; - pub fn kqueue() -> ::c_int; - pub fn unmount(target: *const ::c_char, arg: ::c_int) -> ::c_int; - pub fn syscall(num: ::c_int, ...) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwent50")] - pub fn getpwent() -> *mut passwd; - pub fn setpwent(); - pub fn endpwent(); - pub fn getprogname() -> *const ::c_char; - pub fn setprogname(name: *const ::c_char); - pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int; - pub fn if_nameindex() -> *mut if_nameindex; - pub fn if_freenameindex(ptr: *mut if_nameindex); - - pub fn getpeereid(socket: ::c_int, - euid: *mut ::uid_t, - egid: *mut ::gid_t) -> ::c_int; - - #[cfg_attr(target_os = "macos", link_name = "glob$INODE64")] - #[cfg_attr(target_os = "netbsd", link_name = "__glob30")] - pub fn glob(pattern: *const ::c_char, - flags: ::c_int, - errfunc: Option ::c_int>, - pglob: *mut ::glob_t) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__globfree30")] - pub fn globfree(pglob: *mut ::glob_t); - - pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - pub fn shm_unlink(name: *const ::c_char) -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), - link_name = "seekdir$INODE64")] - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "seekdir$INODE64$UNIX2003")] - pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); - - #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), - link_name = "telldir$INODE64")] - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "telldir$INODE64$UNIX2003")] - pub fn telldir(dirp: *mut ::DIR) -> ::c_long; - pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "msync$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__msync13")] - pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "recvfrom$UNIX2003")] - pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, - flags: ::c_int, addr: *mut ::sockaddr, - addrlen: *mut ::socklen_t) -> ::ssize_t; - pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; - pub fn futimes(fd: ::c_int, times: *const ::timeval) -> ::c_int; - pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "bind$UNIX2003")] - pub fn bind(socket: ::c_int, address: *const ::sockaddr, - address_len: ::socklen_t) -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "writev$UNIX2003")] - pub fn writev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "readv$UNIX2003")] - pub fn readv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "sendmsg$UNIX2003")] - pub fn sendmsg(fd: ::c_int, - msg: *const ::msghdr, - flags: ::c_int) -> ::ssize_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "recvmsg$UNIX2003")] - pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) - -> ::ssize_t; - - pub fn sync(); - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] - pub fn getgrgid_r(uid: ::uid_t, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "sigaltstack$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")] - pub fn sigaltstack(ss: *const stack_t, - oss: *mut stack_t) -> ::c_int; - pub fn sem_close(sem: *mut sem_t) -> ::c_int; - pub fn getdtablesize() -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] - pub fn getgrnam_r(name: *const ::c_char, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_sigmask$UNIX2003")] - pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, - oldset: *mut sigset_t) -> ::c_int; - pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; - pub fn getgrnam(name: *const ::c_char) -> *mut ::group; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_cancel$UNIX2003")] - pub fn pthread_cancel(thread: ::pthread_t) -> ::c_int; - pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; - pub fn sem_unlink(name: *const ::c_char) -> ::c_int; - pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] - pub fn getpwnam_r(name: *const ::c_char, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] - pub fn getpwuid_r(uid: ::uid_t, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch ="x86"), - link_name = "sigwait$UNIX2003")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] - pub fn sigwait(set: *const sigset_t, - sig: *mut ::c_int) -> ::c_int; - pub fn pthread_atfork(prepare: Option, - parent: Option, - child: Option) -> ::c_int; - pub fn getgrgid(gid: ::gid_t) -> *mut ::group; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "popen$UNIX2003")] - pub fn popen(command: *const c_char, - mode: *const c_char) -> *mut ::FILE; - pub fn faccessat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::c_int, flags: ::c_int) -> ::c_int; - pub fn pthread_create(native: *mut ::pthread_t, - attr: *const ::pthread_attr_t, - f: extern fn(*mut ::c_void) -> *mut ::c_void, - value: *mut ::c_void) -> ::c_int; -} - -cfg_if! { - if #[cfg(any(target_os = "macos", target_os = "ios"))] { - mod apple; - pub use self::apple::*; - } else if #[cfg(any(target_os = "openbsd", target_os = "netbsd", - target_os = "bitrig"))] { - mod netbsdlike; - pub use self::netbsdlike::*; - } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] { - mod freebsdlike; - pub use self::freebsdlike::*; - } else { - // Unknown target_os - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,640 +0,0 @@ -pub type time_t = i64; -pub type mode_t = u32; -pub type nlink_t = ::uint32_t; -pub type ino_t = ::uint64_t; -pub type pthread_key_t = ::c_int; -pub type rlim_t = u64; -pub type speed_t = ::c_uint; -pub type tcflag_t = ::c_uint; -pub type nl_item = c_long; -pub type clockid_t = ::c_int; -pub type id_t = ::uint32_t; -pub type sem_t = *mut sem; - -pub enum timezone {} -pub enum sem {} - -s! { - pub struct sigaction { - pub sa_sigaction: ::sighandler_t, - pub sa_mask: ::sigset_t, - pub sa_flags: ::c_int, - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_size: ::size_t, - pub ss_flags: ::c_int, - } - - pub struct sockaddr_in { - pub sin_len: u8, - pub sin_family: ::sa_family_t, - pub sin_port: ::in_port_t, - pub sin_addr: ::in_addr, - pub sin_zero: [::int8_t; 8], - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_cc: [::cc_t; ::NCCS], - pub c_ispeed: ::c_int, - pub c_ospeed: ::c_int, - } - - pub struct flock { - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_pid: ::pid_t, - pub l_type: ::c_short, - pub l_whence: ::c_short, - } -} - -pub const D_T_FMT: ::nl_item = 0; -pub const D_FMT: ::nl_item = 1; -pub const T_FMT: ::nl_item = 2; -pub const T_FMT_AMPM: ::nl_item = 3; -pub const AM_STR: ::nl_item = 4; -pub const PM_STR: ::nl_item = 5; - -pub const DAY_1: ::nl_item = 6; -pub const DAY_2: ::nl_item = 7; -pub const DAY_3: ::nl_item = 8; -pub const DAY_4: ::nl_item = 9; -pub const DAY_5: ::nl_item = 10; -pub const DAY_6: ::nl_item = 11; -pub const DAY_7: ::nl_item = 12; - -pub const ABDAY_1: ::nl_item = 13; -pub const ABDAY_2: ::nl_item = 14; -pub const ABDAY_3: ::nl_item = 15; -pub const ABDAY_4: ::nl_item = 16; -pub const ABDAY_5: ::nl_item = 17; -pub const ABDAY_6: ::nl_item = 18; -pub const ABDAY_7: ::nl_item = 19; - -pub const MON_1: ::nl_item = 20; -pub const MON_2: ::nl_item = 21; -pub const MON_3: ::nl_item = 22; -pub const MON_4: ::nl_item = 23; -pub const MON_5: ::nl_item = 24; -pub const MON_6: ::nl_item = 25; -pub const MON_7: ::nl_item = 26; -pub const MON_8: ::nl_item = 27; -pub const MON_9: ::nl_item = 28; -pub const MON_10: ::nl_item = 29; -pub const MON_11: ::nl_item = 30; -pub const MON_12: ::nl_item = 31; - -pub const ABMON_1: ::nl_item = 32; -pub const ABMON_2: ::nl_item = 33; -pub const ABMON_3: ::nl_item = 34; -pub const ABMON_4: ::nl_item = 35; -pub const ABMON_5: ::nl_item = 36; -pub const ABMON_6: ::nl_item = 37; -pub const ABMON_7: ::nl_item = 38; -pub const ABMON_8: ::nl_item = 39; -pub const ABMON_9: ::nl_item = 40; -pub const ABMON_10: ::nl_item = 41; -pub const ABMON_11: ::nl_item = 42; -pub const ABMON_12: ::nl_item = 43; - -pub const RADIXCHAR: ::nl_item = 44; -pub const THOUSEP: ::nl_item = 45; -pub const YESSTR: ::nl_item = 46; -pub const YESEXPR: ::nl_item = 47; -pub const NOSTR: ::nl_item = 48; -pub const NOEXPR: ::nl_item = 49; -pub const CRNCYSTR: ::nl_item = 50; - -pub const CODESET: ::nl_item = 51; - -pub const EXIT_FAILURE : ::c_int = 1; -pub const EXIT_SUCCESS : ::c_int = 0; -pub const RAND_MAX : ::c_int = 2147483647; -pub const EOF : ::c_int = -1; -pub const SEEK_SET : ::c_int = 0; -pub const SEEK_CUR : ::c_int = 1; -pub const SEEK_END : ::c_int = 2; -pub const _IOFBF : ::c_int = 0; -pub const _IONBF : ::c_int = 2; -pub const _IOLBF : ::c_int = 1; -pub const BUFSIZ : ::c_uint = 1024; -pub const FOPEN_MAX : ::c_uint = 20; -pub const FILENAME_MAX : ::c_uint = 1024; -pub const L_tmpnam : ::c_uint = 1024; -pub const O_NOCTTY : ::c_int = 32768; -pub const S_IFIFO : mode_t = 4096; -pub const S_IFCHR : mode_t = 8192; -pub const S_IFBLK : mode_t = 24576; -pub const S_IFDIR : mode_t = 16384; -pub const S_IFREG : mode_t = 32768; -pub const S_IFLNK : mode_t = 40960; -pub const S_IFSOCK : mode_t = 49152; -pub const S_IFMT : mode_t = 61440; -pub const S_IEXEC : mode_t = 64; -pub const S_IWRITE : mode_t = 128; -pub const S_IREAD : mode_t = 256; -pub const S_IRWXU : mode_t = 448; -pub const S_IXUSR : mode_t = 64; -pub const S_IWUSR : mode_t = 128; -pub const S_IRUSR : mode_t = 256; -pub const S_IRWXG : mode_t = 56; -pub const S_IXGRP : mode_t = 8; -pub const S_IWGRP : mode_t = 16; -pub const S_IRGRP : mode_t = 32; -pub const S_IRWXO : mode_t = 7; -pub const S_IXOTH : mode_t = 1; -pub const S_IWOTH : mode_t = 2; -pub const S_IROTH : mode_t = 4; -pub const F_OK : ::c_int = 0; -pub const R_OK : ::c_int = 4; -pub const W_OK : ::c_int = 2; -pub const X_OK : ::c_int = 1; -pub const STDIN_FILENO : ::c_int = 0; -pub const STDOUT_FILENO : ::c_int = 1; -pub const STDERR_FILENO : ::c_int = 2; -pub const F_LOCK : ::c_int = 1; -pub const F_TEST : ::c_int = 3; -pub const F_TLOCK : ::c_int = 2; -pub const F_ULOCK : ::c_int = 0; -pub const F_GETLK: ::c_int = 7; -pub const F_SETLK: ::c_int = 8; -pub const F_SETLKW: ::c_int = 9; -pub const SIGHUP : ::c_int = 1; -pub const SIGINT : ::c_int = 2; -pub const SIGQUIT : ::c_int = 3; -pub const SIGILL : ::c_int = 4; -pub const SIGABRT : ::c_int = 6; -pub const SIGEMT: ::c_int = 7; -pub const SIGFPE : ::c_int = 8; -pub const SIGKILL : ::c_int = 9; -pub const SIGSEGV : ::c_int = 11; -pub const SIGPIPE : ::c_int = 13; -pub const SIGALRM : ::c_int = 14; -pub const SIGTERM : ::c_int = 15; -pub const SIGSTKSZ : ::size_t = 40960; - -pub const PROT_NONE : ::c_int = 0; -pub const PROT_READ : ::c_int = 1; -pub const PROT_WRITE : ::c_int = 2; -pub const PROT_EXEC : ::c_int = 4; - -pub const MAP_FILE : ::c_int = 0x0000; -pub const MAP_SHARED : ::c_int = 0x0001; -pub const MAP_PRIVATE : ::c_int = 0x0002; -pub const MAP_FIXED : ::c_int = 0x0010; -pub const MAP_ANON : ::c_int = 0x1000; - -pub const MAP_FAILED : *mut ::c_void = !0 as *mut ::c_void; - -pub const MCL_CURRENT : ::c_int = 0x0001; -pub const MCL_FUTURE : ::c_int = 0x0002; - -pub const MS_ASYNC : ::c_int = 0x0001; - -pub const EPERM : ::c_int = 1; -pub const ENOENT : ::c_int = 2; -pub const ESRCH : ::c_int = 3; -pub const EINTR : ::c_int = 4; -pub const EIO : ::c_int = 5; -pub const ENXIO : ::c_int = 6; -pub const E2BIG : ::c_int = 7; -pub const ENOEXEC : ::c_int = 8; -pub const EBADF : ::c_int = 9; -pub const ECHILD : ::c_int = 10; -pub const EDEADLK : ::c_int = 11; -pub const ENOMEM : ::c_int = 12; -pub const EACCES : ::c_int = 13; -pub const EFAULT : ::c_int = 14; -pub const ENOTBLK : ::c_int = 15; -pub const EBUSY : ::c_int = 16; -pub const EEXIST : ::c_int = 17; -pub const EXDEV : ::c_int = 18; -pub const ENODEV : ::c_int = 19; -pub const ENOTDIR : ::c_int = 20; -pub const EISDIR : ::c_int = 21; -pub const EINVAL : ::c_int = 22; -pub const ENFILE : ::c_int = 23; -pub const EMFILE : ::c_int = 24; -pub const ENOTTY : ::c_int = 25; -pub const ETXTBSY : ::c_int = 26; -pub const EFBIG : ::c_int = 27; -pub const ENOSPC : ::c_int = 28; -pub const ESPIPE : ::c_int = 29; -pub const EROFS : ::c_int = 30; -pub const EMLINK : ::c_int = 31; -pub const EPIPE : ::c_int = 32; -pub const EDOM : ::c_int = 33; -pub const ERANGE : ::c_int = 34; -pub const EAGAIN : ::c_int = 35; -pub const EWOULDBLOCK : ::c_int = 35; -pub const EINPROGRESS : ::c_int = 36; -pub const EALREADY : ::c_int = 37; -pub const ENOTSOCK : ::c_int = 38; -pub const EDESTADDRREQ : ::c_int = 39; -pub const EMSGSIZE : ::c_int = 40; -pub const EPROTOTYPE : ::c_int = 41; -pub const ENOPROTOOPT : ::c_int = 42; -pub const EPROTONOSUPPORT : ::c_int = 43; -pub const ESOCKTNOSUPPORT : ::c_int = 44; -pub const EOPNOTSUPP : ::c_int = 45; -pub const EPFNOSUPPORT : ::c_int = 46; -pub const EAFNOSUPPORT : ::c_int = 47; -pub const EADDRINUSE : ::c_int = 48; -pub const EADDRNOTAVAIL : ::c_int = 49; -pub const ENETDOWN : ::c_int = 50; -pub const ENETUNREACH : ::c_int = 51; -pub const ENETRESET : ::c_int = 52; -pub const ECONNABORTED : ::c_int = 53; -pub const ECONNRESET : ::c_int = 54; -pub const ENOBUFS : ::c_int = 55; -pub const EISCONN : ::c_int = 56; -pub const ENOTCONN : ::c_int = 57; -pub const ESHUTDOWN : ::c_int = 58; -pub const ETOOMANYREFS : ::c_int = 59; -pub const ETIMEDOUT : ::c_int = 60; -pub const ECONNREFUSED : ::c_int = 61; -pub const ELOOP : ::c_int = 62; -pub const ENAMETOOLONG : ::c_int = 63; -pub const EHOSTDOWN : ::c_int = 64; -pub const EHOSTUNREACH : ::c_int = 65; -pub const ENOTEMPTY : ::c_int = 66; -pub const EPROCLIM : ::c_int = 67; -pub const EUSERS : ::c_int = 68; -pub const EDQUOT : ::c_int = 69; -pub const ESTALE : ::c_int = 70; -pub const EREMOTE : ::c_int = 71; -pub const EBADRPC : ::c_int = 72; -pub const ERPCMISMATCH : ::c_int = 73; -pub const EPROGUNAVAIL : ::c_int = 74; -pub const EPROGMISMATCH : ::c_int = 75; -pub const EPROCUNAVAIL : ::c_int = 76; -pub const ENOLCK : ::c_int = 77; -pub const ENOSYS : ::c_int = 78; -pub const EFTYPE : ::c_int = 79; -pub const EAUTH : ::c_int = 80; -pub const ENEEDAUTH : ::c_int = 81; - -pub const F_DUPFD : ::c_int = 0; -pub const F_GETFD : ::c_int = 1; -pub const F_SETFD : ::c_int = 2; -pub const F_GETFL : ::c_int = 3; -pub const F_SETFL : ::c_int = 4; - -pub const SIGTRAP : ::c_int = 5; - -pub const GLOB_APPEND : ::c_int = 0x0001; -pub const GLOB_DOOFFS : ::c_int = 0x0002; -pub const GLOB_ERR : ::c_int = 0x0004; -pub const GLOB_MARK : ::c_int = 0x0008; -pub const GLOB_NOCHECK : ::c_int = 0x0010; -pub const GLOB_NOSORT : ::c_int = 0x0020; -pub const GLOB_NOESCAPE : ::c_int = 0x1000; - -pub const GLOB_NOSPACE : ::c_int = -1; -pub const GLOB_ABORTED : ::c_int = -2; -pub const GLOB_NOMATCH : ::c_int = -3; -pub const GLOB_NOSYS : ::c_int = -4; - -pub const POSIX_MADV_NORMAL : ::c_int = 0; -pub const POSIX_MADV_RANDOM : ::c_int = 1; -pub const POSIX_MADV_SEQUENTIAL : ::c_int = 2; -pub const POSIX_MADV_WILLNEED : ::c_int = 3; -pub const POSIX_MADV_DONTNEED : ::c_int = 4; - -pub const PTHREAD_CREATE_JOINABLE : ::c_int = 0; -pub const PTHREAD_CREATE_DETACHED : ::c_int = 1; - -// http://man.openbsd.org/OpenBSD-current/man2/clock_getres.2 -// The man page says clock_gettime(3) can accept various values as clockid_t but -// http://fxr.watson.org/fxr/source/kern/kern_time.c?v=OPENBSD;im=excerpts#L161 -// the implementation rejects anything other than the below two -// -// http://netbsd.gw.com/cgi-bin/man-cgi?clock_gettime -// https://github.com/jsonn/src/blob/HEAD/sys/kern/subr_time.c#L222 -// Basically the same goes for NetBSD -pub const CLOCK_REALTIME: ::clockid_t = 0; -pub const CLOCK_MONOTONIC: ::clockid_t = 3; - -pub const RLIMIT_CPU: ::c_int = 0; -pub const RLIMIT_FSIZE: ::c_int = 1; -pub const RLIMIT_DATA: ::c_int = 2; -pub const RLIMIT_STACK: ::c_int = 3; -pub const RLIMIT_CORE: ::c_int = 4; -pub const RLIMIT_RSS: ::c_int = 5; -pub const RLIMIT_MEMLOCK: ::c_int = 6; -pub const RLIMIT_NPROC: ::c_int = 7; -pub const RLIMIT_NOFILE: ::c_int = 8; - -pub const RLIM_INFINITY: rlim_t = 0x7fff_ffff_ffff_ffff; -pub const RLIM_SAVED_MAX: rlim_t = RLIM_INFINITY; -pub const RLIM_SAVED_CUR: rlim_t = RLIM_INFINITY; - -pub const RUSAGE_SELF: ::c_int = 0; -pub const RUSAGE_CHILDREN: ::c_int = -1; - -pub const MADV_NORMAL : ::c_int = 0; -pub const MADV_RANDOM : ::c_int = 1; -pub const MADV_SEQUENTIAL : ::c_int = 2; -pub const MADV_WILLNEED : ::c_int = 3; -pub const MADV_DONTNEED : ::c_int = 4; -pub const MADV_FREE : ::c_int = 6; - -pub const AF_UNSPEC: ::c_int = 0; -pub const AF_LOCAL: ::c_int = 1; -pub const AF_UNIX: ::c_int = AF_LOCAL; -pub const AF_INET: ::c_int = 2; -pub const AF_IMPLINK: ::c_int = 3; -pub const AF_PUP: ::c_int = 4; -pub const AF_CHAOS: ::c_int = 5; -pub const AF_NS: ::c_int = 6; -pub const AF_ISO: ::c_int = 7; -pub const AF_OSI: ::c_int = AF_ISO; -pub const AF_DATAKIT: ::c_int = 9; -pub const AF_CCITT: ::c_int = 10; -pub const AF_SNA: ::c_int = 11; -pub const AF_DECnet: ::c_int = 12; -pub const AF_DLI: ::c_int = 13; -pub const AF_LAT: ::c_int = 14; -pub const AF_HYLINK: ::c_int = 15; -pub const AF_APPLETALK: ::c_int = 16; -pub const AF_LINK: ::c_int = 18; -pub const pseudo_AF_XTP: ::c_int = 19; -pub const AF_COIP: ::c_int = 20; -pub const AF_CNT: ::c_int = 21; -pub const pseudo_AF_RTIP: ::c_int = 22; -pub const AF_IPX: ::c_int = 23; -pub const AF_INET6: ::c_int = 24; -pub const pseudo_AF_PIP: ::c_int = 25; -pub const AF_ISDN: ::c_int = 26; -pub const AF_E164: ::c_int = AF_ISDN; -pub const AF_NATM: ::c_int = 27; - -pub const PF_UNSPEC: ::c_int = AF_UNSPEC; -pub const PF_LOCAL: ::c_int = AF_LOCAL; -pub const PF_UNIX: ::c_int = PF_LOCAL; -pub const PF_INET: ::c_int = AF_INET; -pub const PF_IMPLINK: ::c_int = AF_IMPLINK; -pub const PF_PUP: ::c_int = AF_PUP; -pub const PF_CHAOS: ::c_int = AF_CHAOS; -pub const PF_NS: ::c_int = AF_NS; -pub const PF_ISO: ::c_int = AF_ISO; -pub const PF_OSI: ::c_int = AF_ISO; -pub const PF_DATAKIT: ::c_int = AF_DATAKIT; -pub const PF_CCITT: ::c_int = AF_CCITT; -pub const PF_SNA: ::c_int = AF_SNA; -pub const PF_DECnet: ::c_int = AF_DECnet; -pub const PF_DLI: ::c_int = AF_DLI; -pub const PF_LAT: ::c_int = AF_LAT; -pub const PF_HYLINK: ::c_int = AF_HYLINK; -pub const PF_APPLETALK: ::c_int = AF_APPLETALK; -pub const PF_LINK: ::c_int = AF_LINK; -pub const PF_XTP: ::c_int = pseudo_AF_XTP; -pub const PF_COIP: ::c_int = AF_COIP; -pub const PF_CNT: ::c_int = AF_CNT; -pub const PF_IPX: ::c_int = AF_IPX; -pub const PF_INET6: ::c_int = AF_INET6; -pub const PF_RTIP: ::c_int = pseudo_AF_RTIP; -pub const PF_PIP: ::c_int = pseudo_AF_PIP; -pub const PF_ISDN: ::c_int = AF_ISDN; -pub const PF_NATM: ::c_int = AF_NATM; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; -pub const SOCK_RAW: ::c_int = 3; -pub const SOCK_RDM: ::c_int = 4; -pub const SOCK_SEQPACKET: ::c_int = 5; -pub const IP_TTL: ::c_int = 4; -pub const IP_HDRINCL: ::c_int = 2; -pub const IP_ADD_MEMBERSHIP: ::c_int = 12; -pub const IP_DROP_MEMBERSHIP: ::c_int = 13; - -pub const TCP_NODELAY: ::c_int = 0x01; -pub const SOL_SOCKET: ::c_int = 0xffff; -pub const SO_DEBUG: ::c_int = 0x01; -pub const SO_ACCEPTCONN: ::c_int = 0x0002; -pub const SO_REUSEADDR: ::c_int = 0x0004; -pub const SO_KEEPALIVE: ::c_int = 0x0008; -pub const SO_DONTROUTE: ::c_int = 0x0010; -pub const SO_BROADCAST: ::c_int = 0x0020; -pub const SO_USELOOPBACK: ::c_int = 0x0040; -pub const SO_LINGER: ::c_int = 0x0080; -pub const SO_OOBINLINE: ::c_int = 0x0100; -pub const SO_REUSEPORT: ::c_int = 0x0200; -pub const SO_SNDBUF: ::c_int = 0x1001; -pub const SO_RCVBUF: ::c_int = 0x1002; -pub const SO_SNDLOWAT: ::c_int = 0x1003; -pub const SO_RCVLOWAT: ::c_int = 0x1004; -pub const SO_ERROR: ::c_int = 0x1007; -pub const SO_TYPE: ::c_int = 0x1008; - -pub const SOMAXCONN: ::c_int = 128; - -pub const MSG_OOB: ::c_int = 0x1; -pub const MSG_PEEK: ::c_int = 0x2; -pub const MSG_DONTROUTE: ::c_int = 0x4; -pub const MSG_EOR: ::c_int = 0x8; -pub const MSG_TRUNC: ::c_int = 0x10; -pub const MSG_CTRUNC: ::c_int = 0x20; -pub const MSG_WAITALL: ::c_int = 0x40; -pub const MSG_DONTWAIT: ::c_int = 0x80; -pub const MSG_BCAST: ::c_int = 0x100; -pub const MSG_MCAST: ::c_int = 0x200; -pub const MSG_NOSIGNAL: ::c_int = 0x400; -pub const MSG_CMSG_CLOEXEC: ::c_int = 0x800; - -pub const SHUT_RD: ::c_int = 0; -pub const SHUT_WR: ::c_int = 1; -pub const SHUT_RDWR: ::c_int = 2; - -pub const LOCK_SH: ::c_int = 1; -pub const LOCK_EX: ::c_int = 2; -pub const LOCK_NB: ::c_int = 4; -pub const LOCK_UN: ::c_int = 8; - -pub const IPPROTO_RAW : ::c_int = 255; - -pub const _SC_ARG_MAX : ::c_int = 1; -pub const _SC_CHILD_MAX : ::c_int = 2; -pub const _SC_NGROUPS_MAX : ::c_int = 4; -pub const _SC_OPEN_MAX : ::c_int = 5; -pub const _SC_JOB_CONTROL : ::c_int = 6; -pub const _SC_SAVED_IDS : ::c_int = 7; -pub const _SC_VERSION : ::c_int = 8; -pub const _SC_BC_BASE_MAX : ::c_int = 9; -pub const _SC_BC_DIM_MAX : ::c_int = 10; -pub const _SC_BC_SCALE_MAX : ::c_int = 11; -pub const _SC_BC_STRING_MAX : ::c_int = 12; -pub const _SC_COLL_WEIGHTS_MAX : ::c_int = 13; -pub const _SC_EXPR_NEST_MAX : ::c_int = 14; -pub const _SC_LINE_MAX : ::c_int = 15; -pub const _SC_RE_DUP_MAX : ::c_int = 16; -pub const _SC_2_VERSION : ::c_int = 17; -pub const _SC_2_C_BIND : ::c_int = 18; -pub const _SC_2_C_DEV : ::c_int = 19; -pub const _SC_2_CHAR_TERM : ::c_int = 20; -pub const _SC_2_FORT_DEV : ::c_int = 21; -pub const _SC_2_FORT_RUN : ::c_int = 22; -pub const _SC_2_LOCALEDEF : ::c_int = 23; -pub const _SC_2_SW_DEV : ::c_int = 24; -pub const _SC_2_UPE : ::c_int = 25; -pub const _SC_STREAM_MAX : ::c_int = 26; -pub const _SC_TZNAME_MAX : ::c_int = 27; -pub const _SC_PAGESIZE : ::c_int = 28; -pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; -pub const _SC_FSYNC : ::c_int = 29; -pub const _SC_XOPEN_SHM : ::c_int = 30; - -pub const Q_GETQUOTA: ::c_int = 0x300; -pub const Q_SETQUOTA: ::c_int = 0x400; - -pub const RTLD_GLOBAL: ::c_int = 0x100; - -pub const LOG_NFACILITIES: ::c_int = 24; - -pub const HW_NCPU: ::c_int = 3; - -pub const B0: speed_t = 0; -pub const B50: speed_t = 50; -pub const B75: speed_t = 75; -pub const B110: speed_t = 110; -pub const B134: speed_t = 134; -pub const B150: speed_t = 150; -pub const B200: speed_t = 200; -pub const B300: speed_t = 300; -pub const B600: speed_t = 600; -pub const B1200: speed_t = 1200; -pub const B1800: speed_t = 1800; -pub const B2400: speed_t = 2400; -pub const B4800: speed_t = 4800; -pub const B9600: speed_t = 9600; -pub const B19200: speed_t = 19200; -pub const B38400: speed_t = 38400; -pub const B7200: speed_t = 7200; -pub const B14400: speed_t = 14400; -pub const B28800: speed_t = 28800; -pub const B57600: speed_t = 57600; -pub const B76800: speed_t = 76800; -pub const B115200: speed_t = 115200; -pub const B230400: speed_t = 230400; -pub const EXTA: speed_t = 19200; -pub const EXTB: speed_t = 38400; - -pub const SEM_FAILED: *mut sem_t = 0 as *mut sem_t; - -pub const CRTSCTS: ::tcflag_t = 0x00010000; -pub const CRTS_IFLOW: ::tcflag_t = CRTSCTS; -pub const CCTS_OFLOW: ::tcflag_t = CRTSCTS; -pub const OCRNL: ::tcflag_t = 0x10; - -pub const TIOCM_LE: ::c_int = 0o0001; -pub const TIOCM_DTR: ::c_int = 0o0002; -pub const TIOCM_RTS: ::c_int = 0o0004; -pub const TIOCM_ST: ::c_int = 0o0010; -pub const TIOCM_SR: ::c_int = 0o0020; -pub const TIOCM_CTS: ::c_int = 0o0040; -pub const TIOCM_CAR: ::c_int = 0o0100; -pub const TIOCM_RNG: ::c_int = 0o0200; -pub const TIOCM_DSR: ::c_int = 0o0400; -pub const TIOCM_CD: ::c_int = TIOCM_CAR; -pub const TIOCM_RI: ::c_int = TIOCM_RNG; - -f! { - pub fn WSTOPSIG(status: ::c_int) -> ::c_int { - status >> 8 - } - - pub fn WIFSIGNALED(status: ::c_int) -> bool { - (status & 0o177) != 0o177 && (status & 0o177) != 0 - } - - pub fn WIFSTOPPED(status: ::c_int) -> bool { - (status & 0o177) == 0o177 - } -} - -#[link(name = "util")] -extern { - pub fn mincore(addr: *mut ::c_void, len: ::size_t, - vec: *mut ::c_char) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__clock_getres50")] - pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__clock_gettime50")] - pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__clock_settime50")] - pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; - pub fn __errno() -> *mut ::c_int; - pub fn shm_open(name: *const ::c_char, oflag: ::c_int, mode: ::mode_t) - -> ::c_int; - pub fn memrchr(cx: *const ::c_void, - c: ::c_int, - n: ::size_t) -> *mut ::c_void; - pub fn mkostemp(template: *mut ::c_char, flags: ::c_int) -> ::c_int; - pub fn mkostemps(template: *mut ::c_char, - suffixlen: ::c_int, - flags: ::c_int) -> ::c_int; - pub fn pwritev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off_t) -> ::ssize_t; - pub fn preadv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off_t) -> ::ssize_t; - pub fn futimens(fd: ::c_int, times: *const ::timespec) -> ::c_int; - pub fn utimensat(dirfd: ::c_int, path: *const ::c_char, - times: *const ::timespec, flag: ::c_int) -> ::c_int; - pub fn fdatasync(fd: ::c_int) -> ::c_int; - pub fn openpty(amaster: *mut ::c_int, - aslave: *mut ::c_int, - name: *mut ::c_char, - termp: *mut termios, - winp: *mut ::winsize) -> ::c_int; - pub fn forkpty(amaster: *mut ::c_int, - name: *mut ::c_char, - termp: *mut termios, - winp: *mut ::winsize) -> ::pid_t; - pub fn getpriority(which: ::c_int, who: ::id_t) -> ::c_int; - pub fn setpriority(which: ::c_int, who: ::id_t, prio: ::c_int) -> ::c_int; - - pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; - - pub fn mknodat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t, dev: dev_t) -> ::c_int; - pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t) -> ::c_int; - pub fn sem_timedwait(sem: *mut sem_t, - abstime: *const ::timespec) -> ::c_int; - pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, - clock_id: ::clockid_t) -> ::c_int; - pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; - pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, - abstime: *const ::timespec) -> ::c_int; - pub fn pipe2(fds: *mut ::c_int, flags: ::c_int) -> ::c_int; - - pub fn getgrouplist(name: *const ::c_char, - basegid: ::gid_t, - groups: *mut ::gid_t, - ngroups: *mut ::c_int) -> ::c_int; - pub fn initgroups(name: *const ::c_char, basegid: ::gid_t) -> ::c_int; - pub fn fexecve(fd: ::c_int, argv: *const *const ::c_char, - envp: *const *const ::c_char) - -> ::c_int; -} - -cfg_if! { - if #[cfg(target_os = "netbsd")] { - mod netbsd; - pub use self::netbsd::*; - } else if #[cfg(any(target_os = "openbsd", target_os = "bitrig"))] { - mod openbsdlike; - pub use self::openbsdlike::*; - } else { - // Unknown target_os - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1078 +0,0 @@ -use dox::mem; - -pub type c_char = i8; -pub type clock_t = ::c_uint; -pub type suseconds_t = ::c_int; -pub type dev_t = u64; -pub type blksize_t = ::int32_t; -pub type fsblkcnt_t = ::uint64_t; -pub type fsfilcnt_t = ::uint64_t; -pub type idtype_t = ::c_int; -pub type mqd_t = ::c_int; - -s! { - pub struct aiocb { - pub aio_offset: ::off_t, - pub aio_buf: *mut ::c_void, - pub aio_nbytes: ::size_t, - pub aio_fildes: ::c_int, - pub aio_lio_opcode: ::c_int, - pub aio_reqprio: ::c_int, - pub aio_sigevent: ::sigevent, - _state: ::c_int, - _errno: ::c_int, - _retval: ::ssize_t - } - - pub struct dirent { - pub d_fileno: ::ino_t, - pub d_reclen: u16, - pub d_namlen: u16, - pub d_type: u8, - pub d_name: [::c_char; 512], - } - - pub struct glob_t { - pub gl_pathc: ::size_t, - pub gl_matchc: ::size_t, - pub gl_offs: ::size_t, - pub gl_flags: ::c_int, - pub gl_pathv: *mut *mut ::c_char, - - __unused3: *mut ::c_void, - - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - __unused6: *mut ::c_void, - __unused7: *mut ::c_void, - __unused8: *mut ::c_void, - } - - pub struct mq_attr { - pub mq_flags: ::c_long, - pub mq_maxmsg: ::c_long, - pub mq_msgsize: ::c_long, - pub mq_curmsgs: ::c_long, - } - - pub struct sigevent { - pub sigev_notify: ::c_int, - pub sigev_signo: ::c_int, - pub sigev_value: ::sigval, - __unused1: *mut ::c_void, //actually a function pointer - pub sigev_notify_attributes: *mut ::c_void - } - - pub struct sigset_t { - __bits: [u32; 4], - } - - pub struct stat { - pub st_dev: ::dev_t, - pub st_mode: ::mode_t, - pub st_ino: ::ino_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - pub st_atime: ::time_t, - pub st_atimensec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtimensec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctimensec: ::c_long, - pub st_birthtime: ::time_t, - pub st_birthtimensec: ::c_long, - pub st_size: ::off_t, - pub st_blocks: ::blkcnt_t, - pub st_blksize: ::blksize_t, - pub st_flags: ::uint32_t, - pub st_gen: ::uint32_t, - pub st_spare: [::uint32_t; 2], - } - - pub struct statvfs { - pub f_flag: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_iosize: ::c_ulong, - - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_bresvd: ::fsblkcnt_t, - - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_favail: ::fsfilcnt_t, - pub f_fresvd: ::fsfilcnt_t, - - pub f_syncreads: ::uint64_t, - pub f_syncwrites: ::uint64_t, - - pub f_asyncreads: ::uint64_t, - pub f_asyncwrites: ::uint64_t, - - pub f_fsidx: ::fsid_t, - pub f_fsid: ::c_ulong, - pub f_namemax: ::c_ulong, - pub f_owner: ::uid_t, - - pub f_spare: [::uint32_t; 4], - - pub f_fstypename: [::c_char; 32], - pub f_mntonname: [::c_char; 1024], - pub f_mntfromname: [::c_char; 1024], - } - - pub struct addrinfo { - pub ai_flags: ::c_int, - pub ai_family: ::c_int, - pub ai_socktype: ::c_int, - pub ai_protocol: ::c_int, - pub ai_addrlen: ::socklen_t, - pub ai_canonname: *mut ::c_char, - pub ai_addr: *mut ::sockaddr, - pub ai_next: *mut ::addrinfo, - } - - pub struct sockaddr_storage { - pub ss_len: u8, - pub ss_family: ::sa_family_t, - __ss_pad1: [u8; 6], - __ss_pad2: i64, - __ss_pad3: [u8; 112], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_code: ::c_int, - pub si_errno: ::c_int, - __pad1: ::c_int, - pub si_addr: *mut ::c_void, - __pad2: [u64; 13], - } - - pub struct pthread_attr_t { - pta_magic: ::c_uint, - pta_flags: ::c_int, - pta_private: *mut ::c_void, - } - - pub struct pthread_mutex_t { - ptm_magic: ::c_uint, - ptm_errorcheck: ::c_uchar, - ptm_pad1: [u8; 3], - ptm_interlock: ::c_uchar, - ptm_pad2: [u8; 3], - ptm_owner: ::pthread_t, - ptm_waiters: *mut u8, - ptm_recursed: ::c_uint, - ptm_spare2: *mut ::c_void, - } - - pub struct pthread_mutexattr_t { - ptma_magic: ::c_uint, - ptma_private: *mut ::c_void, - } - - pub struct pthread_rwlockattr_t { - ptra_magic: ::c_uint, - ptra_private: *mut ::c_void, - } - - pub struct pthread_cond_t { - ptc_magic: ::c_uint, - ptc_lock: ::c_uchar, - ptc_waiters_first: *mut u8, - ptc_waiters_last: *mut u8, - ptc_mutex: *mut ::pthread_mutex_t, - ptc_private: *mut ::c_void, - } - - pub struct pthread_condattr_t { - ptca_magic: ::c_uint, - ptca_private: *mut ::c_void, - } - - pub struct pthread_rwlock_t { - ptr_magic: ::c_uint, - ptr_interlock: ::c_uchar, - ptr_rblocked_first: *mut u8, - ptr_rblocked_last: *mut u8, - ptr_wblocked_first: *mut u8, - ptr_wblocked_last: *mut u8, - ptr_nreaders: ::c_uint, - ptr_owner: ::pthread_t, - ptr_private: *mut ::c_void, - } - - pub struct kevent { - pub ident: ::uintptr_t, - pub filter: ::uint32_t, - pub flags: ::uint32_t, - pub fflags: ::uint32_t, - pub data: ::int64_t, - pub udata: ::intptr_t, - } - - pub struct dqblk { - pub dqb_bhardlimit: ::uint32_t, - pub dqb_bsoftlimit: ::uint32_t, - pub dqb_curblocks: ::uint32_t, - pub dqb_ihardlimit: ::uint32_t, - pub dqb_isoftlimit: ::uint32_t, - pub dqb_curinodes: ::uint32_t, - pub dqb_btime: ::int32_t, - pub dqb_itime: ::int32_t, - } - - pub struct Dl_info { - pub dli_fname: *const ::c_char, - pub dli_fbase: *mut ::c_void, - pub dli_sname: *const ::c_char, - pub dli_saddr: *const ::c_void, - } - - pub struct lconv { - pub decimal_point: *mut ::c_char, - pub thousands_sep: *mut ::c_char, - pub grouping: *mut ::c_char, - pub int_curr_symbol: *mut ::c_char, - pub currency_symbol: *mut ::c_char, - pub mon_decimal_point: *mut ::c_char, - pub mon_thousands_sep: *mut ::c_char, - pub mon_grouping: *mut ::c_char, - pub positive_sign: *mut ::c_char, - pub negative_sign: *mut ::c_char, - pub int_frac_digits: ::c_char, - pub frac_digits: ::c_char, - pub p_cs_precedes: ::c_char, - pub p_sep_by_space: ::c_char, - pub n_cs_precedes: ::c_char, - pub n_sep_by_space: ::c_char, - pub p_sign_posn: ::c_char, - pub n_sign_posn: ::c_char, - pub int_p_cs_precedes: ::c_char, - pub int_n_cs_precedes: ::c_char, - pub int_p_sep_by_space: ::c_char, - pub int_n_sep_by_space: ::c_char, - pub int_p_sign_posn: ::c_char, - pub int_n_sign_posn: ::c_char, - } - - pub struct if_data { - pub ifi_type: ::c_uchar, - pub ifi_addrlen: ::c_uchar, - pub ifi_hdrlen: ::c_uchar, - pub ifi_link_state: ::c_int, - pub ifi_mtu: u64, - pub ifi_metric: u64, - pub ifi_baudrate: u64, - pub ifi_ipackets: u64, - pub ifi_ierrors: u64, - pub ifi_opackets: u64, - pub ifi_oerrors: u64, - pub ifi_collisions: u64, - pub ifi_ibytes: u64, - pub ifi_obytes: u64, - pub ifi_imcasts: u64, - pub ifi_omcasts: u64, - pub ifi_iqdrops: u64, - pub ifi_noproto: u64, - pub ifi_lastchange: ::timespec, - } - - pub struct if_msghdr { - pub ifm_msglen: ::c_ushort, - pub ifm_version: ::c_uchar, - pub ifm_type: ::c_uchar, - pub ifm_addrs: ::c_int, - pub ifm_flags: ::c_int, - pub ifm_index: ::c_ushort, - pub ifm_data: if_data, - } - - pub struct sockcred { - pub sc_pid: ::pid_t, - pub sc_uid: ::uid_t, - pub sc_euid: ::uid_t, - pub sc_gid: ::gid_t, - pub sc_egid: ::gid_t, - pub sc_ngroups: ::c_int, - pub sc_groups: [::gid_t; 1], - } - - pub struct sockaddr_dl { - pub sdl_len: ::c_uchar, - pub sdl_family: ::c_uchar, - pub sdl_index: ::c_ushort, - pub sdl_type: ::uint8_t, - pub sdl_nlen: ::uint8_t, - pub sdl_alen: ::uint8_t, - pub sdl_slen: ::uint8_t, - pub sdl_data: [::c_char; 12], - } -} - -pub const AT_FDCWD: ::c_int = -100; -pub const AT_EACCESS: ::c_int = 0x100; -pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x200; -pub const AT_SYMLINK_FOLLOW: ::c_int = 0x400; -pub const AT_REMOVEDIR: ::c_int = 0x800; - -pub const LC_COLLATE_MASK: ::c_int = (1 << ::LC_COLLATE); -pub const LC_CTYPE_MASK: ::c_int = (1 << ::LC_CTYPE); -pub const LC_MONETARY_MASK: ::c_int = (1 << ::LC_MONETARY); -pub const LC_NUMERIC_MASK: ::c_int = (1 << ::LC_NUMERIC); -pub const LC_TIME_MASK: ::c_int = (1 << ::LC_TIME); -pub const LC_MESSAGES_MASK: ::c_int = (1 << ::LC_MESSAGES); -pub const LC_ALL_MASK: ::c_int = !0; - -pub const ERA: ::nl_item = 52; -pub const ERA_D_FMT: ::nl_item = 53; -pub const ERA_D_T_FMT: ::nl_item = 54; -pub const ERA_T_FMT: ::nl_item = 55; -pub const ALT_DIGITS: ::nl_item = 56; - -pub const O_CLOEXEC: ::c_int = 0x400000; -pub const O_ALT_IO: ::c_int = 0x40000; -pub const O_NOSIGPIPE: ::c_int = 0x1000000; -pub const O_SEARCH: ::c_int = 0x800000; -pub const O_DIRECTORY: ::c_int = 0x200000; -pub const O_DIRECT : ::c_int = 0x00080000; -pub const O_RSYNC : ::c_int = 0x00020000; - -pub const MS_SYNC : ::c_int = 0x4; -pub const MS_INVALIDATE : ::c_int = 0x2; - -pub const RLIM_NLIMITS: ::c_int = 12; - -pub const EIDRM: ::c_int = 82; -pub const ENOMSG: ::c_int = 83; -pub const EOVERFLOW: ::c_int = 84; -pub const EILSEQ: ::c_int = 85; -pub const ENOTSUP: ::c_int = 86; -pub const ECANCELED: ::c_int = 87; -pub const EBADMSG: ::c_int = 88; -pub const ENODATA: ::c_int = 89; -pub const ENOSR: ::c_int = 90; -pub const ENOSTR: ::c_int = 91; -pub const ETIME: ::c_int = 92; -pub const ENOATTR: ::c_int = 93; -pub const EMULTIHOP: ::c_int = 94; -pub const ENOLINK: ::c_int = 95; -pub const EPROTO: ::c_int = 96; -pub const ELAST: ::c_int = 96; - -pub const F_DUPFD_CLOEXEC : ::c_int = 12; -pub const F_CLOSEM: ::c_int = 10; -pub const F_GETNOSIGPIPE: ::c_int = 13; -pub const F_SETNOSIGPIPE: ::c_int = 14; -pub const F_MAXFD: ::c_int = 11; - -pub const IPV6_JOIN_GROUP: ::c_int = 12; -pub const IPV6_LEAVE_GROUP: ::c_int = 13; - -pub const SOCK_CONN_DGRAM: ::c_int = 6; -pub const SOCK_DCCP: ::c_int = SOCK_CONN_DGRAM; -pub const SOCK_NOSIGPIPE: ::c_int = 0x40000000; -pub const SOCK_FLAGS_MASK: ::c_int = 0xf0000000; - -pub const SO_SNDTIMEO: ::c_int = 0x100b; -pub const SO_RCVTIMEO: ::c_int = 0x100c; -pub const SO_ACCEPTFILTER: ::c_int = 0x1000; -pub const SO_TIMESTAMP: ::c_int = 0x2000; -pub const SO_OVERFLOWED: ::c_int = 0x1009; -pub const SO_NOHEADER: ::c_int = 0x100a; - -// https://github.com/NetBSD/src/blob/trunk/sys/net/if.h#L373 -pub const IFF_UP: ::c_int = 0x0001; // interface is up -pub const IFF_BROADCAST: ::c_int = 0x0002; // broadcast address valid -pub const IFF_DEBUG: ::c_int = 0x0004; // turn on debugging -pub const IFF_LOOPBACK: ::c_int = 0x0008; // is a loopback net -pub const IFF_POINTOPOINT: ::c_int = 0x0010; // interface is point-to-point link -pub const IFF_NOTRAILERS: ::c_int = 0x0020; // avoid use of trailers -pub const IFF_RUNNING: ::c_int = 0x0040; // resources allocated -pub const IFF_NOARP: ::c_int = 0x0080; // no address resolution protocol -pub const IFF_PROMISC: ::c_int = 0x0100; // receive all packets -pub const IFF_ALLMULTI: ::c_int = 0x0200; // receive all multicast packets -pub const IFF_OACTIVE: ::c_int = 0x0400; // transmission in progress -pub const IFF_SIMPLEX: ::c_int = 0x0800; // can't hear own transmissions -pub const IFF_LINK0: ::c_int = 0x1000; // per link layer defined bit -pub const IFF_LINK1: ::c_int = 0x2000; // per link layer defined bit -pub const IFF_LINK2: ::c_int = 0x4000; // per link layer defined bit -pub const IFF_MULTICAST: ::c_int = 0x8000; // supports multicast - -// sys/netinet/in.h -// Protocols (RFC 1700) -// NOTE: These are in addition to the constants defined in src/unix/mod.rs - -// IPPROTO_IP defined in src/unix/mod.rs -/// Hop-by-hop option header -pub const IPPROTO_HOPOPTS: ::c_int = 0; -// IPPROTO_ICMP defined in src/unix/mod.rs -/// group mgmt protocol -pub const IPPROTO_IGMP: ::c_int = 2; -/// gateway^2 (deprecated) -pub const IPPROTO_GGP: ::c_int = 3; -/// for compatibility -pub const IPPROTO_IPIP: ::c_int = 4; -// IPPROTO_TCP defined in src/unix/mod.rs -/// exterior gateway protocol -pub const IPPROTO_EGP: ::c_int = 8; -/// pup -pub const IPPROTO_PUP: ::c_int = 12; -// IPPROTO_UDP defined in src/unix/mod.rs -/// xns idp -pub const IPPROTO_IDP: ::c_int = 22; -/// tp-4 w/ class negotiation -pub const IPPROTO_TP: ::c_int = 29; -/// DCCP -pub const IPPROTO_DCCP: ::c_int = 33; -// IPPROTO_IPV6 defined in src/unix/mod.rs -/// IP6 routing header -pub const IPPROTO_ROUTING: ::c_int = 43; -/// IP6 fragmentation header -pub const IPPROTO_FRAGMENT: ::c_int = 44; -/// resource reservation -pub const IPPROTO_RSVP: ::c_int = 46; -/// General Routing Encap. -pub const IPPROTO_GRE: ::c_int = 47; -/// IP6 Encap Sec. Payload -pub const IPPROTO_ESP: ::c_int = 50; -/// IP6 Auth Header -pub const IPPROTO_AH: ::c_int = 51; -/// IP Mobility RFC 2004 -pub const IPPROTO_MOBILE: ::c_int = 55; -/// IPv6 ICMP -pub const IPPROTO_IPV6_ICMP: ::c_int = 58; -// IPPROTO_ICMPV6 defined in src/unix/mod.rs -/// IP6 no next header -pub const IPPROTO_NONE: ::c_int = 59; -/// IP6 destination option -pub const IPPROTO_DSTOPTS: ::c_int = 60; -/// ISO cnlp -pub const IPPROTO_EON: ::c_int = 80; -/// Ethernet-in-IP -pub const IPPROTO_ETHERIP: ::c_int = 97; -/// encapsulation header -pub const IPPROTO_ENCAP: ::c_int = 98; -/// Protocol indep. multicast -pub const IPPROTO_PIM: ::c_int = 103; -/// IP Payload Comp. Protocol -pub const IPPROTO_IPCOMP: ::c_int = 108; -/// VRRP RFC 2338 -pub const IPPROTO_VRRP: ::c_int = 112; -/// Common Address Resolution Protocol -pub const IPPROTO_CARP: ::c_int = 112; -/// L2TPv3 -// TEMP: Disabled for now; this constant was added to NetBSD on 2017-02-16, -// but isn't yet supported by the NetBSD rumprun kernel image used for -// libc testing. -//pub const IPPROTO_L2TP: ::c_int = 115; -/// SCTP -pub const IPPROTO_SCTP: ::c_int = 132; -/// PFSYNC -pub const IPPROTO_PFSYNC: ::c_int = 240; -pub const IPPROTO_MAX: ::c_int = 256; - -/// last return value of *_input(), meaning "all job for this pkt is done". -pub const IPPROTO_DONE: ::c_int = 257; - -/// sysctl placeholder for (FAST_)IPSEC -pub const CTL_IPPROTO_IPSEC: ::c_int = 258; - -pub const AF_OROUTE: ::c_int = 17; -pub const AF_ARP: ::c_int = 28; -pub const pseudo_AF_KEY: ::c_int = 29; -pub const pseudo_AF_HDRCMPLT: ::c_int = 30; -pub const AF_BLUETOOTH: ::c_int = 31; -pub const AF_IEEE80211: ::c_int = 32; -pub const AF_MPLS: ::c_int = 33; -pub const AF_ROUTE: ::c_int = 34; -pub const AF_MAX: ::c_int = 35; - -pub const NET_MAXID: ::c_int = AF_MAX; -pub const NET_RT_DUMP: ::c_int = 1; -pub const NET_RT_FLAGS: ::c_int = 2; -pub const NET_RT_OOIFLIST: ::c_int = 3; -pub const NET_RT_OIFLIST: ::c_int = 4; -pub const NET_RT_IFLIST: ::c_int = 5; -pub const NET_RT_MAXID: ::c_int = 6; - -pub const PF_OROUTE: ::c_int = AF_OROUTE; -pub const PF_ARP: ::c_int = AF_ARP; -pub const PF_KEY: ::c_int = pseudo_AF_KEY; -pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; -pub const PF_MPLS: ::c_int = AF_MPLS; -pub const PF_ROUTE: ::c_int = AF_ROUTE; -pub const PF_MAX: ::c_int = AF_MAX; - -pub const MSG_NBIO: ::c_int = 0x1000; -pub const MSG_WAITFORONE: ::c_int = 0x2000; -pub const MSG_NOTIFICATION: ::c_int = 0x4000; - -pub const SCM_TIMESTAMP: ::c_int = 0x08; -pub const SCM_CREDS: ::c_int = 0x10; - -pub const O_DSYNC : ::c_int = 0x10000; - -pub const MAP_RENAME : ::c_int = 0x20; -pub const MAP_NORESERVE : ::c_int = 0x40; -pub const MAP_HASSEMAPHORE : ::c_int = 0x200; -pub const MAP_WIRED: ::c_int = 0x800; - -pub const DCCP_TYPE_REQUEST: ::c_int = 0; -pub const DCCP_TYPE_RESPONSE: ::c_int = 1; -pub const DCCP_TYPE_DATA: ::c_int = 2; -pub const DCCP_TYPE_ACK: ::c_int = 3; -pub const DCCP_TYPE_DATAACK: ::c_int = 4; -pub const DCCP_TYPE_CLOSEREQ: ::c_int = 5; -pub const DCCP_TYPE_CLOSE: ::c_int = 6; -pub const DCCP_TYPE_RESET: ::c_int = 7; -pub const DCCP_TYPE_MOVE: ::c_int = 8; - -pub const DCCP_FEATURE_CC: ::c_int = 1; -pub const DCCP_FEATURE_ECN: ::c_int = 2; -pub const DCCP_FEATURE_ACKRATIO: ::c_int = 3; -pub const DCCP_FEATURE_ACKVECTOR: ::c_int = 4; -pub const DCCP_FEATURE_MOBILITY: ::c_int = 5; -pub const DCCP_FEATURE_LOSSWINDOW: ::c_int = 6; -pub const DCCP_FEATURE_CONN_NONCE: ::c_int = 8; -pub const DCCP_FEATURE_IDENTREG: ::c_int = 7; - -pub const DCCP_OPT_PADDING: ::c_int = 0; -pub const DCCP_OPT_DATA_DISCARD: ::c_int = 1; -pub const DCCP_OPT_SLOW_RECV: ::c_int = 2; -pub const DCCP_OPT_BUF_CLOSED: ::c_int = 3; -pub const DCCP_OPT_CHANGE_L: ::c_int = 32; -pub const DCCP_OPT_CONFIRM_L: ::c_int = 33; -pub const DCCP_OPT_CHANGE_R: ::c_int = 34; -pub const DCCP_OPT_CONFIRM_R: ::c_int = 35; -pub const DCCP_OPT_INIT_COOKIE: ::c_int = 36; -pub const DCCP_OPT_NDP_COUNT: ::c_int = 37; -pub const DCCP_OPT_ACK_VECTOR0: ::c_int = 38; -pub const DCCP_OPT_ACK_VECTOR1: ::c_int = 39; -pub const DCCP_OPT_RECV_BUF_DROPS: ::c_int = 40; -pub const DCCP_OPT_TIMESTAMP: ::c_int = 41; -pub const DCCP_OPT_TIMESTAMP_ECHO: ::c_int = 42; -pub const DCCP_OPT_ELAPSEDTIME: ::c_int = 43; -pub const DCCP_OPT_DATACHECKSUM: ::c_int = 44; - -pub const DCCP_REASON_UNSPEC: ::c_int = 0; -pub const DCCP_REASON_CLOSED: ::c_int = 1; -pub const DCCP_REASON_INVALID: ::c_int = 2; -pub const DCCP_REASON_OPTION_ERR: ::c_int = 3; -pub const DCCP_REASON_FEA_ERR: ::c_int = 4; -pub const DCCP_REASON_CONN_REF: ::c_int = 5; -pub const DCCP_REASON_BAD_SNAME: ::c_int = 6; -pub const DCCP_REASON_BAD_COOKIE: ::c_int = 7; -pub const DCCP_REASON_INV_MOVE: ::c_int = 8; -pub const DCCP_REASON_UNANSW_CH: ::c_int = 10; -pub const DCCP_REASON_FRUITLESS_NEG: ::c_int = 11; - -pub const DCCP_CCID: ::c_int = 1; -pub const DCCP_CSLEN: ::c_int = 2; -pub const DCCP_MAXSEG: ::c_int = 4; -pub const DCCP_SERVICE: ::c_int = 8; - -pub const DCCP_NDP_LIMIT: ::c_int = 16; -pub const DCCP_SEQ_NUM_LIMIT: ::c_int = 16777216; -pub const DCCP_MAX_OPTIONS: ::c_int = 32; -pub const DCCP_MAX_PKTS: ::c_int = 100; - -pub const _PC_LINK_MAX : ::c_int = 1; -pub const _PC_MAX_CANON : ::c_int = 2; -pub const _PC_MAX_INPUT : ::c_int = 3; -pub const _PC_NAME_MAX : ::c_int = 4; -pub const _PC_PATH_MAX : ::c_int = 5; -pub const _PC_PIPE_BUF : ::c_int = 6; -pub const _PC_CHOWN_RESTRICTED : ::c_int = 7; -pub const _PC_NO_TRUNC : ::c_int = 8; -pub const _PC_VDISABLE : ::c_int = 9; -pub const _PC_SYNC_IO : ::c_int = 10; -pub const _PC_FILESIZEBITS : ::c_int = 11; -pub const _PC_SYMLINK_MAX : ::c_int = 12; -pub const _PC_2_SYMLINKS : ::c_int = 13; -pub const _PC_ACL_EXTENDED : ::c_int = 14; -pub const _PC_MIN_HOLE_SIZE : ::c_int = 15; - -pub const _SC_SYNCHRONIZED_IO : ::c_int = 31; -pub const _SC_IOV_MAX : ::c_int = 32; -pub const _SC_MAPPED_FILES : ::c_int = 33; -pub const _SC_MEMLOCK : ::c_int = 34; -pub const _SC_MEMLOCK_RANGE : ::c_int = 35; -pub const _SC_MEMORY_PROTECTION : ::c_int = 36; -pub const _SC_LOGIN_NAME_MAX : ::c_int = 37; -pub const _SC_MONOTONIC_CLOCK : ::c_int = 38; -pub const _SC_CLK_TCK : ::c_int = 39; -pub const _SC_ATEXIT_MAX : ::c_int = 40; -pub const _SC_THREADS : ::c_int = 41; -pub const _SC_SEMAPHORES : ::c_int = 42; -pub const _SC_BARRIERS : ::c_int = 43; -pub const _SC_TIMERS : ::c_int = 44; -pub const _SC_SPIN_LOCKS : ::c_int = 45; -pub const _SC_READER_WRITER_LOCKS : ::c_int = 46; -pub const _SC_GETGR_R_SIZE_MAX : ::c_int = 47; -pub const _SC_GETPW_R_SIZE_MAX : ::c_int = 48; -pub const _SC_CLOCK_SELECTION : ::c_int = 49; -pub const _SC_ASYNCHRONOUS_IO : ::c_int = 50; -pub const _SC_AIO_LISTIO_MAX : ::c_int = 51; -pub const _SC_AIO_MAX : ::c_int = 52; -pub const _SC_MESSAGE_PASSING : ::c_int = 53; -pub const _SC_MQ_OPEN_MAX : ::c_int = 54; -pub const _SC_MQ_PRIO_MAX : ::c_int = 55; -pub const _SC_PRIORITY_SCHEDULING : ::c_int = 56; -pub const _SC_THREAD_DESTRUCTOR_ITERATIONS : ::c_int = 57; -pub const _SC_THREAD_KEYS_MAX : ::c_int = 58; -pub const _SC_THREAD_STACK_MIN : ::c_int = 59; -pub const _SC_THREAD_THREADS_MAX : ::c_int = 60; -pub const _SC_THREAD_ATTR_STACKADDR : ::c_int = 61; -pub const _SC_THREAD_ATTR_STACKSIZE : ::c_int = 62; -pub const _SC_THREAD_PRIORITY_SCHEDULING : ::c_int = 63; -pub const _SC_THREAD_PRIO_INHERIT : ::c_int = 64; -pub const _SC_THREAD_PRIO_PROTECT : ::c_int = 65; -pub const _SC_THREAD_PROCESS_SHARED : ::c_int = 66; -pub const _SC_THREAD_SAFE_FUNCTIONS : ::c_int = 67; -pub const _SC_TTY_NAME_MAX : ::c_int = 68; -pub const _SC_HOST_NAME_MAX : ::c_int = 69; -pub const _SC_PASS_MAX : ::c_int = 70; -pub const _SC_REGEXP : ::c_int = 71; -pub const _SC_SHELL : ::c_int = 72; -pub const _SC_SYMLOOP_MAX : ::c_int = 73; -pub const _SC_V6_ILP32_OFF32 : ::c_int = 74; -pub const _SC_V6_ILP32_OFFBIG : ::c_int = 75; -pub const _SC_V6_LP64_OFF64 : ::c_int = 76; -pub const _SC_V6_LPBIG_OFFBIG : ::c_int = 77; -pub const _SC_2_PBS : ::c_int = 80; -pub const _SC_2_PBS_ACCOUNTING : ::c_int = 81; -pub const _SC_2_PBS_CHECKPOINT : ::c_int = 82; -pub const _SC_2_PBS_LOCATE : ::c_int = 83; -pub const _SC_2_PBS_MESSAGE : ::c_int = 84; -pub const _SC_2_PBS_TRACK : ::c_int = 85; -pub const _SC_SPAWN : ::c_int = 86; -pub const _SC_SHARED_MEMORY_OBJECTS : ::c_int = 87; -pub const _SC_TIMER_MAX : ::c_int = 88; -pub const _SC_SEM_NSEMS_MAX : ::c_int = 89; -pub const _SC_CPUTIME : ::c_int = 90; -pub const _SC_THREAD_CPUTIME : ::c_int = 91; -pub const _SC_DELAYTIMER_MAX : ::c_int = 92; -// These two variables will be supported in NetBSD 8.0 -// pub const _SC_SIGQUEUE_MAX : ::c_int = 93; -// pub const _SC_REALTIME_SIGNALS : ::c_int = 94; -pub const _SC_PHYS_PAGES : ::c_int = 121; -pub const _SC_NPROCESSORS_CONF : ::c_int = 1001; -pub const _SC_NPROCESSORS_ONLN : ::c_int = 1002; -pub const _SC_SCHED_RT_TS : ::c_int = 2001; -pub const _SC_SCHED_PRI_MIN : ::c_int = 2002; -pub const _SC_SCHED_PRI_MAX : ::c_int = 2003; - -pub const FD_SETSIZE: usize = 0x100; - -pub const ST_NOSUID: ::c_ulong = 8; - -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { - ptm_magic: 0x33330003, - ptm_errorcheck: 0, - ptm_interlock: 0, - ptm_waiters: 0 as *mut _, - ptm_owner: 0, - ptm_pad1: [0; 3], - ptm_pad2: [0; 3], - ptm_recursed: 0, - ptm_spare2: 0 as *mut _, -}; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { - ptc_magic: 0x55550005, - ptc_lock: 0, - ptc_waiters_first: 0 as *mut _, - ptc_waiters_last: 0 as *mut _, - ptc_mutex: 0 as *mut _, - ptc_private: 0 as *mut _, -}; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { - ptr_magic: 0x99990009, - ptr_interlock: 0, - ptr_rblocked_first: 0 as *mut _, - ptr_rblocked_last: 0 as *mut _, - ptr_wblocked_first: 0 as *mut _, - ptr_wblocked_last: 0 as *mut _, - ptr_nreaders: 0, - ptr_owner: 0, - ptr_private: 0 as *mut _, -}; -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 1; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 2; -pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; - -pub const EVFILT_AIO: ::uint32_t = 2; -pub const EVFILT_PROC: ::uint32_t = 4; -pub const EVFILT_READ: ::uint32_t = 0; -pub const EVFILT_SIGNAL: ::uint32_t = 5; -pub const EVFILT_TIMER: ::uint32_t = 6; -pub const EVFILT_VNODE: ::uint32_t = 3; -pub const EVFILT_WRITE: ::uint32_t = 1; - -pub const EV_ADD: ::uint32_t = 0x1; -pub const EV_DELETE: ::uint32_t = 0x2; -pub const EV_ENABLE: ::uint32_t = 0x4; -pub const EV_DISABLE: ::uint32_t = 0x8; -pub const EV_ONESHOT: ::uint32_t = 0x10; -pub const EV_CLEAR: ::uint32_t = 0x20; -pub const EV_RECEIPT: ::uint32_t = 0x40; -pub const EV_DISPATCH: ::uint32_t = 0x80; -pub const EV_FLAG1: ::uint32_t = 0x2000; -pub const EV_ERROR: ::uint32_t = 0x4000; -pub const EV_EOF: ::uint32_t = 0x8000; -pub const EV_SYSFLAGS: ::uint32_t = 0xf000; - -pub const NOTE_LOWAT: ::uint32_t = 0x00000001; -pub const NOTE_DELETE: ::uint32_t = 0x00000001; -pub const NOTE_WRITE: ::uint32_t = 0x00000002; -pub const NOTE_EXTEND: ::uint32_t = 0x00000004; -pub const NOTE_ATTRIB: ::uint32_t = 0x00000008; -pub const NOTE_LINK: ::uint32_t = 0x00000010; -pub const NOTE_RENAME: ::uint32_t = 0x00000020; -pub const NOTE_REVOKE: ::uint32_t = 0x00000040; -pub const NOTE_EXIT: ::uint32_t = 0x80000000; -pub const NOTE_FORK: ::uint32_t = 0x40000000; -pub const NOTE_EXEC: ::uint32_t = 0x20000000; -pub const NOTE_PDATAMASK: ::uint32_t = 0x000fffff; -pub const NOTE_PCTRLMASK: ::uint32_t = 0xf0000000; -pub const NOTE_TRACK: ::uint32_t = 0x00000001; -pub const NOTE_TRACKERR: ::uint32_t = 0x00000002; -pub const NOTE_CHILD: ::uint32_t = 0x00000004; - -pub const TMP_MAX : ::c_uint = 308915776; - -pub const NI_MAXHOST: ::socklen_t = 1025; - -pub const RTLD_NOLOAD: ::c_int = 0x2000; -pub const RTLD_LOCAL: ::c_int = 0x200; - -pub const CTL_MAXNAME: ::c_int = 12; -pub const SYSCTL_NAMELEN: ::c_int = 32; -pub const SYSCTL_DEFSIZE: ::c_int = 8; -pub const CTLTYPE_NODE: ::c_int = 1; -pub const CTLTYPE_INT: ::c_int = 2; -pub const CTLTYPE_STRING: ::c_int = 3; -pub const CTLTYPE_QUAD: ::c_int = 4; -pub const CTLTYPE_STRUCT: ::c_int = 5; -pub const CTLTYPE_BOOL: ::c_int = 6; -pub const CTLFLAG_READONLY: ::c_int = 0x00000000; -pub const CTLFLAG_READWRITE: ::c_int = 0x00000070; -pub const CTLFLAG_ANYWRITE: ::c_int = 0x00000080; -pub const CTLFLAG_PRIVATE: ::c_int = 0x00000100; -pub const CTLFLAG_PERMANENT: ::c_int = 0x00000200; -pub const CTLFLAG_OWNDATA: ::c_int = 0x00000400; -pub const CTLFLAG_IMMEDIATE: ::c_int = 0x00000800; -pub const CTLFLAG_HEX: ::c_int = 0x00001000; -pub const CTLFLAG_ROOT: ::c_int = 0x00002000; -pub const CTLFLAG_ANYNUMBER: ::c_int = 0x00004000; -pub const CTLFLAG_HIDDEN: ::c_int = 0x00008000; -pub const CTLFLAG_ALIAS: ::c_int = 0x00010000; -pub const CTLFLAG_MMAP: ::c_int = 0x00020000; -pub const CTLFLAG_OWNDESC: ::c_int = 0x00040000; -pub const CTLFLAG_UNSIGNED: ::c_int = 0x00080000; -pub const SYSCTL_VERS_MASK: ::c_int = 0xff000000; -pub const SYSCTL_VERS_0: ::c_int = 0x00000000; -pub const SYSCTL_VERS_1: ::c_int = 0x01000000; -pub const SYSCTL_VERSION: ::c_int = SYSCTL_VERS_1; -pub const CTL_EOL: ::c_int = -1; -pub const CTL_QUERY: ::c_int = -2; -pub const CTL_CREATE: ::c_int = -3; -pub const CTL_CREATESYM: ::c_int = -4; -pub const CTL_DESTROY: ::c_int = -5; -pub const CTL_MMAP: ::c_int = -6; -pub const CTL_DESCRIBE: ::c_int = -7; -pub const CTL_UNSPEC: ::c_int = 0; -pub const CTL_KERN: ::c_int = 1; -pub const CTL_VM: ::c_int = 2; -pub const CTL_VFS: ::c_int = 3; -pub const CTL_NET: ::c_int = 4; -pub const CTL_DEBUG: ::c_int = 5; -pub const CTL_HW: ::c_int = 6; -pub const CTL_MACHDEP: ::c_int = 7; -pub const CTL_USER: ::c_int = 8; -pub const CTL_DDB: ::c_int = 9; -pub const CTL_PROC: ::c_int = 10; -pub const CTL_VENDOR: ::c_int = 11; -pub const CTL_EMUL: ::c_int = 12; -pub const CTL_SECURITY: ::c_int = 13; -pub const CTL_MAXID: ::c_int = 14; -pub const KERN_OSTYPE: ::c_int = 1; -pub const KERN_OSRELEASE: ::c_int = 2; -pub const KERN_OSREV: ::c_int = 3; -pub const KERN_VERSION: ::c_int = 4; -pub const KERN_MAXVNODES: ::c_int = 5; -pub const KERN_MAXPROC: ::c_int = 6; -pub const KERN_MAXFILES: ::c_int = 7; -pub const KERN_ARGMAX: ::c_int = 8; -pub const KERN_SECURELVL: ::c_int = 9; -pub const KERN_HOSTNAME: ::c_int = 10; -pub const KERN_HOSTID: ::c_int = 11; -pub const KERN_CLOCKRATE: ::c_int = 12; -pub const KERN_VNODE: ::c_int = 13; -pub const KERN_PROC: ::c_int = 14; -pub const KERN_FILE: ::c_int = 15; -pub const KERN_PROF: ::c_int = 16; -pub const KERN_POSIX1: ::c_int = 17; -pub const KERN_NGROUPS: ::c_int = 18; -pub const KERN_JOB_CONTROL: ::c_int = 19; -pub const KERN_SAVED_IDS: ::c_int = 20; -pub const KERN_OBOOTTIME: ::c_int = 21; -pub const KERN_DOMAINNAME: ::c_int = 22; -pub const KERN_MAXPARTITIONS: ::c_int = 23; -pub const KERN_RAWPARTITION: ::c_int = 24; -pub const KERN_NTPTIME: ::c_int = 25; -pub const KERN_TIMEX: ::c_int = 26; -pub const KERN_AUTONICETIME: ::c_int = 27; -pub const KERN_AUTONICEVAL: ::c_int = 28; -pub const KERN_RTC_OFFSET: ::c_int = 29; -pub const KERN_ROOT_DEVICE: ::c_int = 30; -pub const KERN_MSGBUFSIZE: ::c_int = 31; -pub const KERN_FSYNC: ::c_int = 32; -pub const KERN_OLDSYSVMSG: ::c_int = 33; -pub const KERN_OLDSYSVSEM: ::c_int = 34; -pub const KERN_OLDSYSVSHM: ::c_int = 35; -pub const KERN_OLDSHORTCORENAME: ::c_int = 36; -pub const KERN_SYNCHRONIZED_IO: ::c_int = 37; -pub const KERN_IOV_MAX: ::c_int = 38; -pub const KERN_MBUF: ::c_int = 39; -pub const KERN_MAPPED_FILES: ::c_int = 40; -pub const KERN_MEMLOCK: ::c_int = 41; -pub const KERN_MEMLOCK_RANGE: ::c_int = 42; -pub const KERN_MEMORY_PROTECTION: ::c_int = 43; -pub const KERN_LOGIN_NAME_MAX: ::c_int = 44; -pub const KERN_DEFCORENAME: ::c_int = 45; -pub const KERN_LOGSIGEXIT: ::c_int = 46; -pub const KERN_PROC2: ::c_int = 47; -pub const KERN_PROC_ARGS: ::c_int = 48; -pub const KERN_FSCALE: ::c_int = 49; -pub const KERN_CCPU: ::c_int = 50; -pub const KERN_CP_TIME: ::c_int = 51; -pub const KERN_OLDSYSVIPC_INFO: ::c_int = 52; -pub const KERN_MSGBUF: ::c_int = 53; -pub const KERN_CONSDEV: ::c_int = 54; -pub const KERN_MAXPTYS: ::c_int = 55; -pub const KERN_PIPE: ::c_int = 56; -pub const KERN_MAXPHYS: ::c_int = 57; -pub const KERN_SBMAX: ::c_int = 58; -pub const KERN_TKSTAT: ::c_int = 59; -pub const KERN_MONOTONIC_CLOCK: ::c_int = 60; -pub const KERN_URND: ::c_int = 61; -pub const KERN_LABELSECTOR: ::c_int = 62; -pub const KERN_LABELOFFSET: ::c_int = 63; -pub const KERN_LWP: ::c_int = 64; -pub const KERN_FORKFSLEEP: ::c_int = 65; -pub const KERN_POSIX_THREADS: ::c_int = 66; -pub const KERN_POSIX_SEMAPHORES: ::c_int = 67; -pub const KERN_POSIX_BARRIERS: ::c_int = 68; -pub const KERN_POSIX_TIMERS: ::c_int = 69; -pub const KERN_POSIX_SPIN_LOCKS: ::c_int = 70; -pub const KERN_POSIX_READER_WRITER_LOCKS: ::c_int = 71; -pub const KERN_DUMP_ON_PANIC: ::c_int = 72; -pub const KERN_SOMAXKVA: ::c_int = 73; -pub const KERN_ROOT_PARTITION: ::c_int = 74; -pub const KERN_DRIVERS: ::c_int = 75; -pub const KERN_BUF: ::c_int = 76; -pub const KERN_FILE2: ::c_int = 77; -pub const KERN_VERIEXEC: ::c_int = 78; -pub const KERN_CP_ID: ::c_int = 79; -pub const KERN_HARDCLOCK_TICKS: ::c_int = 80; -pub const KERN_ARND: ::c_int = 81; -pub const KERN_SYSVIPC: ::c_int = 82; -pub const KERN_BOOTTIME: ::c_int = 83; -pub const KERN_EVCNT: ::c_int = 84; -pub const KERN_MAXID: ::c_int = 85; -pub const KERN_PROC_ALL: ::c_int = 0; -pub const KERN_PROC_PID: ::c_int = 1; -pub const KERN_PROC_PGRP: ::c_int = 2; -pub const KERN_PROC_SESSION: ::c_int = 3; -pub const KERN_PROC_TTY: ::c_int = 4; -pub const KERN_PROC_UID: ::c_int = 5; -pub const KERN_PROC_RUID: ::c_int = 6; -pub const KERN_PROC_GID: ::c_int = 7; -pub const KERN_PROC_RGID: ::c_int = 8; -pub const KERN_PROC_ARGV: ::c_int = 1; -pub const KERN_PROC_NARGV: ::c_int = 2; -pub const KERN_PROC_ENV: ::c_int = 3; -pub const KERN_PROC_NENV: ::c_int = 4; -pub const KERN_PROC_PATHNAME: ::c_int = 5; - -pub const EAI_AGAIN: ::c_int = 2; -pub const EAI_BADFLAGS: ::c_int = 3; -pub const EAI_FAIL: ::c_int = 4; -pub const EAI_FAMILY: ::c_int = 5; -pub const EAI_MEMORY: ::c_int = 6; -pub const EAI_NODATA: ::c_int = 7; -pub const EAI_NONAME: ::c_int = 8; -pub const EAI_SERVICE: ::c_int = 9; -pub const EAI_SOCKTYPE: ::c_int = 10; -pub const EAI_SYSTEM: ::c_int = 11; -pub const EAI_OVERFLOW: ::c_int = 14; - -pub const AIO_CANCELED: ::c_int = 1; -pub const AIO_NOTCANCELED: ::c_int = 2; -pub const AIO_ALLDONE: ::c_int = 3; -pub const LIO_NOP: ::c_int = 0; -pub const LIO_WRITE: ::c_int = 1; -pub const LIO_READ: ::c_int = 2; -pub const LIO_WAIT: ::c_int = 1; -pub const LIO_NOWAIT: ::c_int = 0; - -pub const SIGEV_NONE: ::c_int = 0; -pub const SIGEV_SIGNAL: ::c_int = 1; -pub const SIGEV_THREAD: ::c_int = 2; - -pub const WSTOPPED: ::c_int = 0x00000002; // same as WUNTRACED -pub const WCONTINUED: ::c_int = 0x00000010; -pub const WEXITED: ::c_int = 0x000000020; -pub const WNOWAIT: ::c_int = 0x00010000; - -pub const P_ALL: idtype_t = 0; -pub const P_PID: idtype_t = 1; -pub const P_PGID: idtype_t = 4; - -pub const B460800: ::speed_t = 460800; -pub const B921600: ::speed_t = 921600; - -pub const ONOCR: ::tcflag_t = 0x20; -pub const ONLRET: ::tcflag_t = 0x40; -pub const CDTRCTS: ::tcflag_t = 0x00020000; -pub const CHWFLOW: ::tcflag_t = ::MDMBUF | ::CRTSCTS | ::CDTRCTS; - -pub const SOCK_CLOEXEC: ::c_int = 0x10000000; -pub const SOCK_NONBLOCK: ::c_int = 0x20000000; - -// dirfd() is a macro on netbsd to access -// the first field of the struct where dirp points to: -// http://cvsweb.netbsd.org/bsdweb.cgi/src/include/dirent.h?rev=1.36 -f! { - pub fn dirfd(dirp: *mut ::DIR) -> ::c_int { - *(dirp as *const ::c_int) - } - - pub fn WIFCONTINUED(status: ::c_int) -> bool { - status == 0xffff - } - - pub fn SOCKCREDSIZE(ngrps: usize) -> usize { - let ngrps = if ngrps > 0 { - ngrps - 1 - } else { - 0 - }; - mem::size_of::() + mem::size_of::<::gid_t>() * ngrps - } -} - -extern { - pub fn aio_read(aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_write(aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_fsync(op: ::c_int, aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_error(aiocbp: *const aiocb) -> ::c_int; - pub fn aio_return(aiocbp: *mut aiocb) -> ::ssize_t; - #[link_name = "__aio_suspend50"] - pub fn aio_suspend(aiocb_list: *const *const aiocb, nitems: ::c_int, - timeout: *const ::timespec) -> ::c_int; - pub fn aio_cancel(fd: ::c_int, aiocbp: *mut aiocb) -> ::c_int; - pub fn lio_listio(mode: ::c_int, aiocb_list: *const *mut aiocb, - nitems: ::c_int, sevp: *mut sigevent) -> ::c_int; - - pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; - pub fn getnameinfo(sa: *const ::sockaddr, - salen: ::socklen_t, - host: *mut ::c_char, - hostlen: ::socklen_t, - serv: *mut ::c_char, - sevlen: ::socklen_t, - flags: ::c_int) -> ::c_int; - pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) - -> ::c_int; - pub fn sysctl(name: *const ::c_int, - namelen: ::c_uint, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *const ::c_void, - newlen: ::size_t) - -> ::c_int; - pub fn sysctlbyname(name: *const ::c_char, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *const ::c_void, - newlen: ::size_t) - -> ::c_int; - #[link_name = "__kevent50"] - pub fn kevent(kq: ::c_int, - changelist: *const ::kevent, - nchanges: ::size_t, - eventlist: *mut ::kevent, - nevents: ::size_t, - timeout: *const ::timespec) -> ::c_int; - #[link_name = "__mount50"] - pub fn mount(src: *const ::c_char, - target: *const ::c_char, - flags: ::c_int, - data: *mut ::c_void, - size: ::size_t) -> ::c_int; - pub fn mq_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::mqd_t; - pub fn mq_close(mqd: ::mqd_t) -> ::c_int; - pub fn mq_getattr(mqd: ::mqd_t, attr: *mut ::mq_attr) -> ::c_int; - pub fn mq_notify(mqd: ::mqd_t, notification: *const ::sigevent) -> ::c_int; - pub fn mq_receive(mqd: ::mqd_t, - msg_ptr: *mut ::c_char, - msg_len: ::size_t, - msq_prio: *mut ::c_uint) -> ::ssize_t; - pub fn mq_send(mqd: ::mqd_t, - msg_ptr: *const ::c_char, - msg_len: ::size_t, - msq_prio: ::c_uint) -> ::c_int; - pub fn mq_setattr(mqd: ::mqd_t, - newattr: *const ::mq_attr, - oldattr: *mut ::mq_attr) -> ::c_int; - pub fn mq_timedreceive(mqd: ::mqd_t, - msg_ptr: *mut ::c_char, - msg_len: ::size_t, - msq_prio: *mut ::c_uint, - abs_timeout: *const ::timespec) -> ::ssize_t; - pub fn mq_timedsend(mqd: ::mqd_t, - msg_ptr: *const ::c_char, - msg_len: ::size_t, - msq_prio: ::c_uint, - abs_timeout: *const ::timespec) -> ::c_int; - pub fn mq_unlink(name: *const ::c_char) -> ::c_int; - pub fn ptrace(request: ::c_int, - pid: ::pid_t, - addr: *mut ::c_void, - data: ::c_int) -> ::c_int; - pub fn pthread_setname_np(t: ::pthread_t, - name: *const ::c_char, - arg: *mut ::c_void) -> ::c_int; - pub fn pthread_getattr_np(native: ::pthread_t, - attr: *mut ::pthread_attr_t) -> ::c_int; - pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, - guardsize: *mut ::size_t) -> ::c_int; - pub fn pthread_attr_getstack(attr: *const ::pthread_attr_t, - stackaddr: *mut *mut ::c_void, - stacksize: *mut ::size_t) -> ::c_int; - #[link_name = "__sigtimedwait50"] - pub fn sigtimedwait(set: *const sigset_t, - info: *mut siginfo_t, - timeout: *const ::timespec) -> ::c_int; - pub fn sigwaitinfo(set: *const sigset_t, - info: *mut siginfo_t) -> ::c_int; - pub fn duplocale(base: ::locale_t) -> ::locale_t; - pub fn freelocale(loc: ::locale_t); - pub fn localeconv_l(loc: ::locale_t) -> *mut lconv; - pub fn newlocale(mask: ::c_int, - locale: *const ::c_char, - base: ::locale_t) -> ::locale_t; - #[link_name = "__settimeofday50"] - pub fn settimeofday(tv: *const ::timeval, tz: *const ::c_void) -> ::c_int; -} - -mod other; -pub use self::other::*; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/other/b32/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/other/b32/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/other/b32/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/other/b32/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -pub type c_long = i32; -pub type c_ulong = u32; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/other/b64/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/other/b64/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/other/b64/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/other/b64/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -pub type c_long = i64; -pub type c_ulong = u64; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/other/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/other/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/other/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/netbsd/other/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -cfg_if! { - if #[cfg(any(target_arch = "sparc64", - target_arch = "x86_64"))] { - mod b64; - pub use self::b64::*; - } else if #[cfg(any(target_arch = "arm", - target_arch = "powerpc", - target_arch = "x86"))] { - mod b32; - pub use self::b32::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/bitrig/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/bitrig/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/bitrig/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/bitrig/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,89 +0,0 @@ -pub type c_char = i8; - -s! { - pub struct lconv { - pub decimal_point: *mut ::c_char, - pub thousands_sep: *mut ::c_char, - pub grouping: *mut ::c_char, - pub int_curr_symbol: *mut ::c_char, - pub currency_symbol: *mut ::c_char, - pub mon_decimal_point: *mut ::c_char, - pub mon_thousands_sep: *mut ::c_char, - pub mon_grouping: *mut ::c_char, - pub positive_sign: *mut ::c_char, - pub negative_sign: *mut ::c_char, - pub int_frac_digits: ::c_char, - pub frac_digits: ::c_char, - pub p_cs_precedes: ::c_char, - pub p_sep_by_space: ::c_char, - pub n_cs_precedes: ::c_char, - pub n_sep_by_space: ::c_char, - pub p_sign_posn: ::c_char, - pub n_sign_posn: ::c_char, - pub int_p_cs_precedes: ::c_char, - pub int_n_cs_precedes: ::c_char, - pub int_p_sep_by_space: ::c_char, - pub int_n_sep_by_space: ::c_char, - pub int_p_sign_posn: ::c_char, - pub int_n_sign_posn: ::c_char, - } -} - -pub const LC_COLLATE_MASK: ::c_int = (1 << 0); -pub const LC_CTYPE_MASK: ::c_int = (1 << 1); -pub const LC_MESSAGES_MASK: ::c_int = (1 << 2); -pub const LC_MONETARY_MASK: ::c_int = (1 << 3); -pub const LC_NUMERIC_MASK: ::c_int = (1 << 4); -pub const LC_TIME_MASK: ::c_int = (1 << 5); -pub const LC_ALL_MASK: ::c_int = LC_COLLATE_MASK - | LC_CTYPE_MASK - | LC_MESSAGES_MASK - | LC_MONETARY_MASK - | LC_NUMERIC_MASK - | LC_TIME_MASK; - -pub const ERA: ::nl_item = 52; -pub const ERA_D_FMT: ::nl_item = 53; -pub const ERA_D_T_FMT: ::nl_item = 54; -pub const ERA_T_FMT: ::nl_item = 55; -pub const ALT_DIGITS: ::nl_item = 56; - -pub const D_MD_ORDER: ::nl_item = 57; - -pub const ALTMON_1: ::nl_item = 58; -pub const ALTMON_2: ::nl_item = 59; -pub const ALTMON_3: ::nl_item = 60; -pub const ALTMON_4: ::nl_item = 61; -pub const ALTMON_5: ::nl_item = 62; -pub const ALTMON_6: ::nl_item = 63; -pub const ALTMON_7: ::nl_item = 64; -pub const ALTMON_8: ::nl_item = 65; -pub const ALTMON_9: ::nl_item = 66; -pub const ALTMON_10: ::nl_item = 67; -pub const ALTMON_11: ::nl_item = 68; -pub const ALTMON_12: ::nl_item = 69; - -pub const KERN_RND: ::c_int = 31; - -extern { - pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; - pub fn duplocale(base: ::locale_t) -> ::locale_t; - pub fn freelocale(loc: ::locale_t) -> ::c_int; - pub fn newlocale(mask: ::c_int, - locale: *const ::c_char, - base: ::locale_t) -> ::locale_t; - pub fn uselocale(loc: ::locale_t) -> ::locale_t; - pub fn querylocale(mask: ::c_int, loc: ::locale_t) -> *const ::c_char; -} - -cfg_if! { - if #[cfg(target_arch = "x86")] { - mod x86; - pub use self::x86::*; - } else if #[cfg(target_arch = "x86_64")] { - mod x86_64; - pub use self::x86_64::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86_64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86_64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -pub type c_long = i64; -pub type c_ulong = u64; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -pub type c_long = i32; -pub type c_ulong = u32; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,750 +0,0 @@ -use unix::bsd::O_SYNC; - -pub type clock_t = i64; -pub type suseconds_t = ::c_long; -pub type dev_t = i32; -pub type sigset_t = ::c_uint; -pub type blksize_t = ::int32_t; -pub type fsblkcnt_t = ::uint64_t; -pub type fsfilcnt_t = ::uint64_t; -pub type pthread_attr_t = *mut ::c_void; -pub type pthread_mutex_t = *mut ::c_void; -pub type pthread_mutexattr_t = *mut ::c_void; -pub type pthread_cond_t = *mut ::c_void; -pub type pthread_condattr_t = *mut ::c_void; -pub type pthread_rwlock_t = *mut ::c_void; -pub type pthread_rwlockattr_t = *mut ::c_void; - -s! { - pub struct dirent { - pub d_fileno: ::ino_t, - pub d_off: ::off_t, - pub d_reclen: u16, - pub d_type: u8, - pub d_namlen: u8, - __d_padding: [u8; 4], - pub d_name: [::c_char; 256], - } - - pub struct glob_t { - pub gl_pathc: ::c_int, - pub gl_matchc: ::c_int, - pub gl_offs: ::c_int, - pub gl_flags: ::c_int, - pub gl_pathv: *mut *mut ::c_char, - __unused1: *mut ::c_void, - __unused2: *mut ::c_void, - __unused3: *mut ::c_void, - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - __unused6: *mut ::c_void, - __unused7: *mut ::c_void, - } - - pub struct kevent { - pub ident: ::uintptr_t, - pub filter: ::c_short, - pub flags: ::c_ushort, - pub fflags: ::c_uint, - pub data: ::int64_t, - pub udata: *mut ::c_void, - } - - pub struct stat { - pub st_mode: ::mode_t, - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_size: ::off_t, - pub st_blocks: ::blkcnt_t, - pub st_blksize: ::blksize_t, - pub st_flags: ::uint32_t, - pub st_gen: ::uint32_t, - pub st_birthtime: ::time_t, - pub st_birthtime_nsec: ::c_long, - } - - pub struct statvfs { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_favail: ::fsfilcnt_t, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - } - - pub struct addrinfo { - pub ai_flags: ::c_int, - pub ai_family: ::c_int, - pub ai_socktype: ::c_int, - pub ai_protocol: ::c_int, - pub ai_addrlen: ::socklen_t, - pub ai_addr: *mut ::sockaddr, - pub ai_canonname: *mut ::c_char, - pub ai_next: *mut ::addrinfo, - } - - pub struct sockaddr_storage { - pub ss_len: u8, - pub ss_family: ::sa_family_t, - __ss_pad1: [u8; 6], - __ss_pad2: i64, - __ss_pad3: [u8; 240], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_code: ::c_int, - pub si_errno: ::c_int, - pub si_addr: *mut ::c_char, - #[cfg(target_pointer_width = "32")] - __pad: [u8; 112], - #[cfg(target_pointer_width = "64")] - __pad: [u8; 108], - } - - pub struct Dl_info { - pub dli_fname: *const ::c_char, - pub dli_fbase: *mut ::c_void, - pub dli_sname: *const ::c_char, - pub dli_saddr: *mut ::c_void, - } - - pub struct lastlog { - ll_time: ::time_t, - ll_line: [::c_char; UT_LINESIZE], - ll_host: [::c_char; UT_HOSTSIZE], - } - - pub struct utmp { - pub ut_line: [::c_char; UT_LINESIZE], - pub ut_name: [::c_char; UT_NAMESIZE], - pub ut_host: [::c_char; UT_HOSTSIZE], - pub ut_time: ::time_t, - } - - pub struct if_data { - pub ifi_type: ::c_uchar, - pub ifi_addrlen: ::c_uchar, - pub ifi_hdrlen: ::c_uchar, - pub ifi_link_state: ::c_uchar, - pub ifi_mtu: u32, - pub ifi_metric: u32, - pub ifi_rdomain: u32, - pub ifi_baudrate: u64, - pub ifi_ipackets: u64, - pub ifi_ierrors: u64, - pub ifi_opackets: u64, - pub ifi_oerrors: u64, - pub ifi_collisions: u64, - pub ifi_ibytes: u64, - pub ifi_obytes: u64, - pub ifi_imcasts: u64, - pub ifi_omcasts: u64, - pub ifi_iqdrops: u64, - pub ifi_oqdrops: u64, - pub ifi_noproto: u64, - pub ifi_capabilities: u32, - pub ifi_lastchange: ::timeval, - } - - pub struct if_msghdr { - pub ifm_msglen: ::c_ushort, - pub ifm_version: ::c_uchar, - pub ifm_type: ::c_uchar, - pub ifm_hdrlen: ::c_ushort, - pub ifm_index: ::c_ushort, - pub ifm_tableid: ::c_ushort, - pub ifm_pad1: ::c_uchar, - pub ifm_pad2: ::c_uchar, - pub ifm_addrs: ::c_int, - pub ifm_flags: ::c_int, - pub ifm_xflags: ::c_int, - pub ifm_data: if_data, - } - - pub struct sockaddr_dl { - pub sdl_len: ::c_uchar, - pub sdl_family: ::c_uchar, - pub sdl_index: ::c_ushort, - pub sdl_type: ::c_uchar, - pub sdl_nlen: ::c_uchar, - pub sdl_alen: ::c_uchar, - pub sdl_slen: ::c_uchar, - pub sdl_data: [::c_char; 24], - } -} - -pub const UT_NAMESIZE: usize = 32; -pub const UT_LINESIZE: usize = 8; -pub const UT_HOSTSIZE: usize = 256; - -pub const O_CLOEXEC: ::c_int = 0x10000; -pub const O_DIRECTORY: ::c_int = 0x20000; -pub const O_RSYNC: ::c_int = O_SYNC; - -pub const MS_SYNC : ::c_int = 0x0002; -pub const MS_INVALIDATE : ::c_int = 0x0004; - -pub const PTHREAD_STACK_MIN : ::size_t = 2048; - -pub const POLLNORM: ::c_short = ::POLLRDNORM; - -pub const ENOATTR : ::c_int = 83; -pub const EILSEQ : ::c_int = 84; -pub const EOVERFLOW : ::c_int = 87; -pub const ECANCELED : ::c_int = 88; -pub const EIDRM : ::c_int = 89; -pub const ENOMSG : ::c_int = 90; -pub const ENOTSUP : ::c_int = 91; -pub const EBADMSG : ::c_int = 92; -pub const ENOTRECOVERABLE : ::c_int = 93; -pub const EOWNERDEAD : ::c_int = 94; -pub const EPROTO : ::c_int = 95; -pub const ELAST : ::c_int = 95; - -pub const F_DUPFD_CLOEXEC : ::c_int = 10; - -pub const AT_FDCWD: ::c_int = -100; -pub const AT_EACCESS: ::c_int = 0x01; -pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x02; -pub const AT_SYMLINK_FOLLOW: ::c_int = 0x04; -pub const AT_REMOVEDIR: ::c_int = 0x08; - -pub const RLIM_NLIMITS: ::c_int = 9; - -pub const SO_TIMESTAMP: ::c_int = 0x0800; -pub const SO_SNDTIMEO: ::c_int = 0x1005; -pub const SO_RCVTIMEO: ::c_int = 0x1006; -pub const SO_BINDANY: ::c_int = 0x1000; -pub const SO_NETPROC: ::c_int = 0x1020; -pub const SO_RTABLE: ::c_int = 0x1021; -pub const SO_PEERCRED: ::c_int = 0x1022; -pub const SO_SPLICE: ::c_int = 0x1023; - -// https://github.com/openbsd/src/blob/master/sys/net/if.h#L187 -pub const IFF_UP: ::c_int = 0x1; // interface is up -pub const IFF_BROADCAST: ::c_int = 0x2; // broadcast address valid -pub const IFF_DEBUG: ::c_int = 0x4; // turn on debugging -pub const IFF_LOOPBACK: ::c_int = 0x8; // is a loopback net -pub const IFF_POINTOPOINT: ::c_int = 0x10; // interface is point-to-point link -pub const IFF_NOTRAILERS: ::c_int = 0x20; // avoid use of trailers -pub const IFF_RUNNING: ::c_int = 0x40; // resources allocated -pub const IFF_NOARP: ::c_int = 0x80; // no address resolution protocol -pub const IFF_PROMISC: ::c_int = 0x100; // receive all packets -pub const IFF_ALLMULTI: ::c_int = 0x200; // receive all multicast packets -pub const IFF_OACTIVE: ::c_int = 0x400; // transmission in progress -pub const IFF_SIMPLEX: ::c_int = 0x800; // can't hear own transmissions -pub const IFF_LINK0: ::c_int = 0x1000; // per link layer defined bit -pub const IFF_LINK1: ::c_int = 0x2000; // per link layer defined bit -pub const IFF_LINK2: ::c_int = 0x4000; // per link layer defined bit -pub const IFF_MULTICAST: ::c_int = 0x8000; // supports multicast - -// sys/netinet/in.h -// Protocols (RFC 1700) -// NOTE: These are in addition to the constants defined in src/unix/mod.rs - -// IPPROTO_IP defined in src/unix/mod.rs -/// Hop-by-hop option header -pub const IPPROTO_HOPOPTS: ::c_int = 0; -// IPPROTO_ICMP defined in src/unix/mod.rs -/// group mgmt protocol -pub const IPPROTO_IGMP: ::c_int = 2; -/// gateway^2 (deprecated) -pub const IPPROTO_GGP: ::c_int = 3; -/// for compatibility -pub const IPPROTO_IPIP: ::c_int = 4; -// IPPROTO_TCP defined in src/unix/mod.rs -/// exterior gateway protocol -pub const IPPROTO_EGP: ::c_int = 8; -/// pup -pub const IPPROTO_PUP: ::c_int = 12; -// IPPROTO_UDP defined in src/unix/mod.rs -/// xns idp -pub const IPPROTO_IDP: ::c_int = 22; -/// tp-4 w/ class negotiation -pub const IPPROTO_TP: ::c_int = 29; -// IPPROTO_IPV6 defined in src/unix/mod.rs -/// IP6 routing header -pub const IPPROTO_ROUTING: ::c_int = 43; -/// IP6 fragmentation header -pub const IPPROTO_FRAGMENT: ::c_int = 44; -/// resource reservation -pub const IPPROTO_RSVP: ::c_int = 46; -/// General Routing Encap. -pub const IPPROTO_GRE: ::c_int = 47; -/// IP6 Encap Sec. Payload -pub const IPPROTO_ESP: ::c_int = 50; -/// IP6 Auth Header -pub const IPPROTO_AH: ::c_int = 51; -/// IP Mobility RFC 2004 -pub const IPPROTO_MOBILE: ::c_int = 55; -// IPPROTO_ICMPV6 defined in src/unix/mod.rs -/// IP6 no next header -pub const IPPROTO_NONE: ::c_int = 59; -/// IP6 destination option -pub const IPPROTO_DSTOPTS: ::c_int = 60; -/// ISO cnlp -pub const IPPROTO_EON: ::c_int = 80; -/// Ethernet-in-IP -pub const IPPROTO_ETHERIP: ::c_int = 97; -/// encapsulation header -pub const IPPROTO_ENCAP: ::c_int = 98; -/// Protocol indep. multicast -pub const IPPROTO_PIM: ::c_int = 103; -/// IP Payload Comp. Protocol -pub const IPPROTO_IPCOMP: ::c_int = 108; -/// CARP -pub const IPPROTO_CARP: ::c_int = 112; -/// unicast MPLS packet -pub const IPPROTO_MPLS: ::c_int = 137; -/// PFSYNC -pub const IPPROTO_PFSYNC: ::c_int = 240; -pub const IPPROTO_MAX: ::c_int = 256; - -/* Only used internally, so it can be outside the range of valid IP protocols */ -/// Divert sockets -pub const IPPROTO_DIVERT: ::c_int = 258; - -pub const AF_ECMA: ::c_int = 8; -pub const AF_ROUTE: ::c_int = 17; -pub const AF_ENCAP: ::c_int = 28; -pub const AF_SIP: ::c_int = 29; -pub const AF_KEY: ::c_int = 30; -pub const pseudo_AF_HDRCMPLT: ::c_int = 31; -pub const AF_BLUETOOTH: ::c_int = 32; -pub const AF_MPLS: ::c_int = 33; -pub const pseudo_AF_PFLOW: ::c_int = 34; -pub const pseudo_AF_PIPEX: ::c_int = 35; -#[doc(hidden)] -pub const AF_MAX: ::c_int = 36; - -#[doc(hidden)] -pub const NET_MAXID: ::c_int = AF_MAX; -pub const NET_RT_DUMP: ::c_int = 1; -pub const NET_RT_FLAGS: ::c_int = 2; -pub const NET_RT_IFLIST: ::c_int = 3; -pub const NET_RT_STATS: ::c_int = 4; -pub const NET_RT_TABLE: ::c_int = 5; -pub const NET_RT_IFNAMES: ::c_int = 6; -#[doc(hidden)] -pub const NET_RT_MAXID: ::c_int = 7; - -pub const IPV6_JOIN_GROUP: ::c_int = 12; -pub const IPV6_LEAVE_GROUP: ::c_int = 13; - -pub const PF_ROUTE: ::c_int = AF_ROUTE; -pub const PF_ECMA: ::c_int = AF_ECMA; -pub const PF_ENCAP: ::c_int = AF_ENCAP; -pub const PF_SIP: ::c_int = AF_SIP; -pub const PF_KEY: ::c_int = AF_KEY; -pub const PF_BPF: ::c_int = pseudo_AF_HDRCMPLT; -pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; -pub const PF_MPLS: ::c_int = AF_MPLS; -pub const PF_PFLOW: ::c_int = pseudo_AF_PFLOW; -pub const PF_PIPEX: ::c_int = pseudo_AF_PIPEX; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; - -pub const SCM_TIMESTAMP: ::c_int = 0x04; - -pub const O_DSYNC : ::c_int = 128; - -pub const MAP_RENAME : ::c_int = 0x0000; -pub const MAP_NORESERVE : ::c_int = 0x0000; -pub const MAP_HASSEMAPHORE : ::c_int = 0x0000; - -pub const EIPSEC : ::c_int = 82; -pub const ENOMEDIUM : ::c_int = 85; -pub const EMEDIUMTYPE : ::c_int = 86; - -pub const EAI_BADFLAGS: ::c_int = -1; -pub const EAI_NONAME: ::c_int = -2; -pub const EAI_AGAIN: ::c_int = -3; -pub const EAI_FAIL: ::c_int = -4; -pub const EAI_NODATA: ::c_int = -5; -pub const EAI_FAMILY: ::c_int = -6; -pub const EAI_SOCKTYPE: ::c_int = -7; -pub const EAI_SERVICE: ::c_int = -8; -pub const EAI_MEMORY: ::c_int = -10; -pub const EAI_SYSTEM: ::c_int = -11; -pub const EAI_OVERFLOW: ::c_int = -14; - -pub const RUSAGE_THREAD: ::c_int = 1; - -pub const MAP_COPY : ::c_int = 0x0002; -pub const MAP_NOEXTEND : ::c_int = 0x0000; - -pub const _PC_LINK_MAX : ::c_int = 1; -pub const _PC_MAX_CANON : ::c_int = 2; -pub const _PC_MAX_INPUT : ::c_int = 3; -pub const _PC_NAME_MAX : ::c_int = 4; -pub const _PC_PATH_MAX : ::c_int = 5; -pub const _PC_PIPE_BUF : ::c_int = 6; -pub const _PC_CHOWN_RESTRICTED : ::c_int = 7; -pub const _PC_NO_TRUNC : ::c_int = 8; -pub const _PC_VDISABLE : ::c_int = 9; -pub const _PC_2_SYMLINKS : ::c_int = 10; -pub const _PC_ALLOC_SIZE_MIN : ::c_int = 11; -pub const _PC_ASYNC_IO : ::c_int = 12; -pub const _PC_FILESIZEBITS : ::c_int = 13; -pub const _PC_PRIO_IO : ::c_int = 14; -pub const _PC_REC_INCR_XFER_SIZE : ::c_int = 15; -pub const _PC_REC_MAX_XFER_SIZE : ::c_int = 16; -pub const _PC_REC_MIN_XFER_SIZE : ::c_int = 17; -pub const _PC_REC_XFER_ALIGN : ::c_int = 18; -pub const _PC_SYMLINK_MAX : ::c_int = 19; -pub const _PC_SYNC_IO : ::c_int = 20; -pub const _PC_TIMESTAMP_RESOLUTION : ::c_int = 21; - -pub const _SC_CLK_TCK : ::c_int = 3; -pub const _SC_SEM_NSEMS_MAX : ::c_int = 31; -pub const _SC_SEM_VALUE_MAX : ::c_int = 32; -pub const _SC_HOST_NAME_MAX : ::c_int = 33; -pub const _SC_MONOTONIC_CLOCK : ::c_int = 34; -pub const _SC_2_PBS : ::c_int = 35; -pub const _SC_2_PBS_ACCOUNTING : ::c_int = 36; -pub const _SC_2_PBS_CHECKPOINT : ::c_int = 37; -pub const _SC_2_PBS_LOCATE : ::c_int = 38; -pub const _SC_2_PBS_MESSAGE : ::c_int = 39; -pub const _SC_2_PBS_TRACK : ::c_int = 40; -pub const _SC_ADVISORY_INFO : ::c_int = 41; -pub const _SC_AIO_LISTIO_MAX : ::c_int = 42; -pub const _SC_AIO_MAX : ::c_int = 43; -pub const _SC_AIO_PRIO_DELTA_MAX : ::c_int = 44; -pub const _SC_ASYNCHRONOUS_IO : ::c_int = 45; -pub const _SC_ATEXIT_MAX : ::c_int = 46; -pub const _SC_BARRIERS : ::c_int = 47; -pub const _SC_CLOCK_SELECTION : ::c_int = 48; -pub const _SC_CPUTIME : ::c_int = 49; -pub const _SC_DELAYTIMER_MAX : ::c_int = 50; -pub const _SC_IOV_MAX : ::c_int = 51; -pub const _SC_IPV6 : ::c_int = 52; -pub const _SC_MAPPED_FILES : ::c_int = 53; -pub const _SC_MEMLOCK : ::c_int = 54; -pub const _SC_MEMLOCK_RANGE : ::c_int = 55; -pub const _SC_MEMORY_PROTECTION : ::c_int = 56; -pub const _SC_MESSAGE_PASSING : ::c_int = 57; -pub const _SC_MQ_OPEN_MAX : ::c_int = 58; -pub const _SC_MQ_PRIO_MAX : ::c_int = 59; -pub const _SC_PRIORITIZED_IO : ::c_int = 60; -pub const _SC_PRIORITY_SCHEDULING : ::c_int = 61; -pub const _SC_RAW_SOCKETS : ::c_int = 62; -pub const _SC_READER_WRITER_LOCKS : ::c_int = 63; -pub const _SC_REALTIME_SIGNALS : ::c_int = 64; -pub const _SC_REGEXP : ::c_int = 65; -pub const _SC_RTSIG_MAX : ::c_int = 66; -pub const _SC_SEMAPHORES : ::c_int = 67; -pub const _SC_SHARED_MEMORY_OBJECTS : ::c_int = 68; -pub const _SC_SHELL : ::c_int = 69; -pub const _SC_SIGQUEUE_MAX : ::c_int = 70; -pub const _SC_SPAWN : ::c_int = 71; -pub const _SC_SPIN_LOCKS : ::c_int = 72; -pub const _SC_SPORADIC_SERVER : ::c_int = 73; -pub const _SC_SS_REPL_MAX : ::c_int = 74; -pub const _SC_SYNCHRONIZED_IO : ::c_int = 75; -pub const _SC_SYMLOOP_MAX : ::c_int = 76; -pub const _SC_THREAD_ATTR_STACKADDR : ::c_int = 77; -pub const _SC_THREAD_ATTR_STACKSIZE : ::c_int = 78; -pub const _SC_THREAD_CPUTIME : ::c_int = 79; -pub const _SC_THREAD_DESTRUCTOR_ITERATIONS : ::c_int = 80; -pub const _SC_THREAD_KEYS_MAX : ::c_int = 81; -pub const _SC_THREAD_PRIO_INHERIT : ::c_int = 82; -pub const _SC_THREAD_PRIO_PROTECT : ::c_int = 83; -pub const _SC_THREAD_PRIORITY_SCHEDULING : ::c_int = 84; -pub const _SC_THREAD_PROCESS_SHARED : ::c_int = 85; -pub const _SC_THREAD_ROBUST_PRIO_INHERIT : ::c_int = 86; -pub const _SC_THREAD_ROBUST_PRIO_PROTECT : ::c_int = 87; -pub const _SC_THREAD_SPORADIC_SERVER : ::c_int = 88; -pub const _SC_THREAD_STACK_MIN : ::c_int = 89; -pub const _SC_THREAD_THREADS_MAX : ::c_int = 90; -pub const _SC_THREADS : ::c_int = 91; -pub const _SC_TIMEOUTS : ::c_int = 92; -pub const _SC_TIMER_MAX : ::c_int = 93; -pub const _SC_TIMERS : ::c_int = 94; -pub const _SC_TRACE : ::c_int = 95; -pub const _SC_TRACE_EVENT_FILTER : ::c_int = 96; -pub const _SC_TRACE_EVENT_NAME_MAX : ::c_int = 97; -pub const _SC_TRACE_INHERIT : ::c_int = 98; -pub const _SC_TRACE_LOG : ::c_int = 99; -pub const _SC_GETGR_R_SIZE_MAX : ::c_int = 100; -pub const _SC_GETPW_R_SIZE_MAX : ::c_int = 101; -pub const _SC_LOGIN_NAME_MAX : ::c_int = 102; -pub const _SC_THREAD_SAFE_FUNCTIONS : ::c_int = 103; -pub const _SC_TRACE_NAME_MAX : ::c_int = 104; -pub const _SC_TRACE_SYS_MAX : ::c_int = 105; -pub const _SC_TRACE_USER_EVENT_MAX : ::c_int = 106; -pub const _SC_TTY_NAME_MAX : ::c_int = 107; -pub const _SC_TYPED_MEMORY_OBJECTS : ::c_int = 108; -pub const _SC_V6_ILP32_OFF32 : ::c_int = 109; -pub const _SC_V6_ILP32_OFFBIG : ::c_int = 110; -pub const _SC_V6_LP64_OFF64 : ::c_int = 111; -pub const _SC_V6_LPBIG_OFFBIG : ::c_int = 112; -pub const _SC_V7_ILP32_OFF32 : ::c_int = 113; -pub const _SC_V7_ILP32_OFFBIG : ::c_int = 114; -pub const _SC_V7_LP64_OFF64 : ::c_int = 115; -pub const _SC_V7_LPBIG_OFFBIG : ::c_int = 116; -pub const _SC_XOPEN_CRYPT : ::c_int = 117; -pub const _SC_XOPEN_ENH_I18N : ::c_int = 118; -pub const _SC_XOPEN_LEGACY : ::c_int = 119; -pub const _SC_XOPEN_REALTIME : ::c_int = 120; -pub const _SC_XOPEN_REALTIME_THREADS : ::c_int = 121; -pub const _SC_XOPEN_STREAMS : ::c_int = 122; -pub const _SC_XOPEN_UNIX : ::c_int = 123; -pub const _SC_XOPEN_UUCP : ::c_int = 124; -pub const _SC_XOPEN_VERSION : ::c_int = 125; -pub const _SC_PHYS_PAGES : ::c_int = 500; -pub const _SC_AVPHYS_PAGES : ::c_int = 501; -pub const _SC_NPROCESSORS_CONF : ::c_int = 502; -pub const _SC_NPROCESSORS_ONLN : ::c_int = 503; - -pub const FD_SETSIZE: usize = 1024; - -pub const ST_NOSUID: ::c_ulong = 2; - -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = 0 as *mut _; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = 0 as *mut _; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = 0 as *mut _; - -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 1; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 2; -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 3; -pub const PTHREAD_MUTEX_STRICT_NP: ::c_int = 4; -pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_STRICT_NP; - -pub const EVFILT_AIO: ::int16_t = -3; -pub const EVFILT_PROC: ::int16_t = -5; -pub const EVFILT_READ: ::int16_t = -1; -pub const EVFILT_SIGNAL: ::int16_t = -6; -pub const EVFILT_TIMER: ::int16_t = -7; -pub const EVFILT_VNODE: ::int16_t = -4; -pub const EVFILT_WRITE: ::int16_t = -2; - -pub const EV_ADD: ::uint16_t = 0x1; -pub const EV_DELETE: ::uint16_t = 0x2; -pub const EV_ENABLE: ::uint16_t = 0x4; -pub const EV_DISABLE: ::uint16_t = 0x8; -pub const EV_ONESHOT: ::uint16_t = 0x10; -pub const EV_CLEAR: ::uint16_t = 0x20; -pub const EV_RECEIPT: ::uint16_t = 0x40; -pub const EV_DISPATCH: ::uint16_t = 0x80; -pub const EV_FLAG1: ::uint16_t = 0x2000; -pub const EV_ERROR: ::uint16_t = 0x4000; -pub const EV_EOF: ::uint16_t = 0x8000; -pub const EV_SYSFLAGS: ::uint16_t = 0xf000; - -pub const NOTE_LOWAT: ::uint32_t = 0x00000001; -pub const NOTE_EOF: ::uint32_t = 0x00000002; -pub const NOTE_DELETE: ::uint32_t = 0x00000001; -pub const NOTE_WRITE: ::uint32_t = 0x00000002; -pub const NOTE_EXTEND: ::uint32_t = 0x00000004; -pub const NOTE_ATTRIB: ::uint32_t = 0x00000008; -pub const NOTE_LINK: ::uint32_t = 0x00000010; -pub const NOTE_RENAME: ::uint32_t = 0x00000020; -pub const NOTE_REVOKE: ::uint32_t = 0x00000040; -pub const NOTE_TRUNCATE: ::uint32_t = 0x00000080; -pub const NOTE_EXIT: ::uint32_t = 0x80000000; -pub const NOTE_FORK: ::uint32_t = 0x40000000; -pub const NOTE_EXEC: ::uint32_t = 0x20000000; -pub const NOTE_PDATAMASK: ::uint32_t = 0x000fffff; -pub const NOTE_PCTRLMASK: ::uint32_t = 0xf0000000; -pub const NOTE_TRACK: ::uint32_t = 0x00000001; -pub const NOTE_TRACKERR: ::uint32_t = 0x00000002; -pub const NOTE_CHILD: ::uint32_t = 0x00000004; - -pub const TMP_MAX : ::c_uint = 0x7fffffff; - -pub const NI_MAXHOST: ::size_t = 256; - -pub const RTLD_LOCAL: ::c_int = 0; -pub const CTL_MAXNAME: ::c_int = 12; -pub const CTLTYPE_NODE: ::c_int = 1; -pub const CTLTYPE_INT: ::c_int = 2; -pub const CTLTYPE_STRING: ::c_int = 3; -pub const CTLTYPE_QUAD: ::c_int = 4; -pub const CTLTYPE_STRUCT: ::c_int = 5; -pub const CTL_UNSPEC: ::c_int = 0; -pub const CTL_KERN: ::c_int = 1; -pub const CTL_VM: ::c_int = 2; -pub const CTL_FS: ::c_int = 3; -pub const CTL_NET: ::c_int = 4; -pub const CTL_DEBUG: ::c_int = 5; -pub const CTL_HW: ::c_int = 6; -pub const CTL_MACHDEP: ::c_int = 7; -pub const CTL_DDB: ::c_int = 9; -pub const CTL_VFS: ::c_int = 10; -pub const CTL_MAXID: ::c_int = 11; -pub const KERN_OSTYPE: ::c_int = 1; -pub const KERN_OSRELEASE: ::c_int = 2; -pub const KERN_OSREV: ::c_int = 3; -pub const KERN_VERSION: ::c_int = 4; -pub const KERN_MAXVNODES: ::c_int = 5; -pub const KERN_MAXPROC: ::c_int = 6; -pub const KERN_MAXFILES: ::c_int = 7; -pub const KERN_ARGMAX: ::c_int = 8; -pub const KERN_SECURELVL: ::c_int = 9; -pub const KERN_HOSTNAME: ::c_int = 10; -pub const KERN_HOSTID: ::c_int = 11; -pub const KERN_CLOCKRATE: ::c_int = 12; -pub const KERN_PROF: ::c_int = 16; -pub const KERN_POSIX1: ::c_int = 17; -pub const KERN_NGROUPS: ::c_int = 18; -pub const KERN_JOB_CONTROL: ::c_int = 19; -pub const KERN_SAVED_IDS: ::c_int = 20; -pub const KERN_BOOTTIME: ::c_int = 21; -pub const KERN_DOMAINNAME: ::c_int = 22; -pub const KERN_MAXPARTITIONS: ::c_int = 23; -pub const KERN_RAWPARTITION: ::c_int = 24; -pub const KERN_MAXTHREAD: ::c_int = 25; -pub const KERN_NTHREADS: ::c_int = 26; -pub const KERN_OSVERSION: ::c_int = 27; -pub const KERN_SOMAXCONN: ::c_int = 28; -pub const KERN_SOMINCONN: ::c_int = 29; -pub const KERN_USERMOUNT: ::c_int = 30; -pub const KERN_NOSUIDCOREDUMP: ::c_int = 32; -pub const KERN_FSYNC: ::c_int = 33; -pub const KERN_SYSVMSG: ::c_int = 34; -pub const KERN_SYSVSEM: ::c_int = 35; -pub const KERN_SYSVSHM: ::c_int = 36; -pub const KERN_ARND: ::c_int = 37; -pub const KERN_MSGBUFSIZE: ::c_int = 38; -pub const KERN_MALLOCSTATS: ::c_int = 39; -pub const KERN_CPTIME: ::c_int = 40; -pub const KERN_NCHSTATS: ::c_int = 41; -pub const KERN_FORKSTAT: ::c_int = 42; -pub const KERN_NSELCOLL: ::c_int = 43; -pub const KERN_TTY: ::c_int = 44; -pub const KERN_CCPU: ::c_int = 45; -pub const KERN_FSCALE: ::c_int = 46; -pub const KERN_NPROCS: ::c_int = 47; -pub const KERN_MSGBUF: ::c_int = 48; -pub const KERN_POOL: ::c_int = 49; -pub const KERN_STACKGAPRANDOM: ::c_int = 50; -pub const KERN_SYSVIPC_INFO: ::c_int = 51; -pub const KERN_SPLASSERT: ::c_int = 54; -pub const KERN_PROC_ARGS: ::c_int = 55; -pub const KERN_NFILES: ::c_int = 56; -pub const KERN_TTYCOUNT: ::c_int = 57; -pub const KERN_NUMVNODES: ::c_int = 58; -pub const KERN_MBSTAT: ::c_int = 59; -pub const KERN_SEMINFO: ::c_int = 61; -pub const KERN_SHMINFO: ::c_int = 62; -pub const KERN_INTRCNT: ::c_int = 63; -pub const KERN_WATCHDOG: ::c_int = 64; -pub const KERN_PROC: ::c_int = 66; -pub const KERN_MAXCLUSTERS: ::c_int = 67; -pub const KERN_EVCOUNT: ::c_int = 68; -pub const KERN_TIMECOUNTER: ::c_int = 69; -pub const KERN_MAXLOCKSPERUID: ::c_int = 70; -pub const KERN_CPTIME2: ::c_int = 71; -pub const KERN_CACHEPCT: ::c_int = 72; -pub const KERN_FILE: ::c_int = 73; -pub const KERN_CONSDEV: ::c_int = 75; -pub const KERN_NETLIVELOCKS: ::c_int = 76; -pub const KERN_POOL_DEBUG: ::c_int = 77; -pub const KERN_PROC_CWD: ::c_int = 78; -pub const KERN_PROC_NOBROADCASTKILL: ::c_int = 79; -pub const KERN_PROC_VMMAP: ::c_int = 80; -pub const KERN_GLOBAL_PTRACE: ::c_int = 81; -pub const KERN_CONSBUFSIZE: ::c_int = 82; -pub const KERN_CONSBUF: ::c_int = 83; -pub const KERN_MAXID: ::c_int = 84; -pub const KERN_PROC_ALL: ::c_int = 0; -pub const KERN_PROC_PID: ::c_int = 1; -pub const KERN_PROC_PGRP: ::c_int = 2; -pub const KERN_PROC_SESSION: ::c_int = 3; -pub const KERN_PROC_TTY: ::c_int = 4; -pub const KERN_PROC_UID: ::c_int = 5; -pub const KERN_PROC_RUID: ::c_int = 6; -pub const KERN_PROC_KTHREAD: ::c_int = 7; -pub const KERN_PROC_SHOW_THREADS: ::c_int = 0x40000000; -pub const KERN_SYSVIPC_MSG_INFO: ::c_int = 1; -pub const KERN_SYSVIPC_SEM_INFO: ::c_int = 2; -pub const KERN_SYSVIPC_SHM_INFO: ::c_int = 3; -pub const KERN_PROC_ARGV: ::c_int = 1; -pub const KERN_PROC_NARGV: ::c_int = 2; -pub const KERN_PROC_ENV: ::c_int = 3; -pub const KERN_PROC_NENV: ::c_int = 4; -pub const KI_NGROUPS: ::c_int = 16; -pub const KI_MAXCOMLEN: ::c_int = 24; -pub const KI_WMESGLEN: ::c_int = 8; -pub const KI_MAXLOGNAME: ::c_int = 32; -pub const KI_EMULNAMELEN: ::c_int = 8; - -pub const CHWFLOW: ::tcflag_t = ::MDMBUF | ::CRTSCTS; -pub const OLCUC: ::tcflag_t = 0x20; -pub const ONOCR: ::tcflag_t = 0x40; -pub const ONLRET: ::tcflag_t = 0x80; - -pub const SOCK_CLOEXEC: ::c_int = 0x8000; -pub const SOCK_NONBLOCK: ::c_int = 0x4000; -pub const SOCK_DNS: ::c_int = 0x1000; - -pub const WCONTINUED: ::c_int = 8; - -f! { - pub fn WIFCONTINUED(status: ::c_int) -> bool { - status & 0o177777 == 0o177777 - } -} - -extern { - pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; - pub fn getnameinfo(sa: *const ::sockaddr, - salen: ::socklen_t, - host: *mut ::c_char, - hostlen: ::size_t, - serv: *mut ::c_char, - servlen: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn kevent(kq: ::c_int, - changelist: *const ::kevent, - nchanges: ::c_int, - eventlist: *mut ::kevent, - nevents: ::c_int, - timeout: *const ::timespec) -> ::c_int; - pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) - -> ::c_int; - pub fn pthread_main_np() -> ::c_int; - pub fn pthread_set_name_np(tid: ::pthread_t, name: *const ::c_char); - pub fn pthread_stackseg_np(thread: ::pthread_t, - sinfo: *mut ::stack_t) -> ::c_int; - pub fn sysctl(name: *const ::c_int, - namelen: ::c_uint, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *mut ::c_void, - newlen: ::size_t) - -> ::c_int; - pub fn getentropy(buf: *mut ::c_void, buflen: ::size_t) -> ::c_int; - pub fn pledge(promises: *const ::c_char, - paths: *mut *const ::c_char) -> ::c_int; - pub fn setresgid(rgid: ::gid_t, egid: ::gid_t, sgid: ::gid_t) -> ::c_int; - pub fn setresuid(ruid: ::uid_t, euid: ::uid_t, suid: ::uid_t) -> ::c_int; -} - -cfg_if! { - if #[cfg(target_os = "openbsd")] { - mod openbsd; - pub use self::openbsd::*; - } else if #[cfg(target_os = "bitrig")] { - mod bitrig; - pub use self::bitrig::*; - } else { - // Unknown target_os - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/aarch64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/aarch64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -pub type c_long = i64; -pub type c_ulong = u64; -pub type c_char = u8; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -s! { - pub struct lconv { - pub decimal_point: *mut ::c_char, - pub thousands_sep: *mut ::c_char, - pub grouping: *mut ::c_char, - pub int_curr_symbol: *mut ::c_char, - pub currency_symbol: *mut ::c_char, - pub mon_decimal_point: *mut ::c_char, - pub mon_thousands_sep: *mut ::c_char, - pub mon_grouping: *mut ::c_char, - pub positive_sign: *mut ::c_char, - pub negative_sign: *mut ::c_char, - pub int_frac_digits: ::c_char, - pub frac_digits: ::c_char, - pub p_cs_precedes: ::c_char, - pub p_sep_by_space: ::c_char, - pub n_cs_precedes: ::c_char, - pub n_sep_by_space: ::c_char, - pub p_sign_posn: ::c_char, - pub n_sign_posn: ::c_char, - pub int_p_cs_precedes: ::c_char, - pub int_p_sep_by_space: ::c_char, - pub int_n_cs_precedes: ::c_char, - pub int_n_sep_by_space: ::c_char, - pub int_p_sign_posn: ::c_char, - pub int_n_sign_posn: ::c_char, - } -} - -extern { - pub fn accept4(s: ::c_int, addr: *mut ::sockaddr, - addrlen: *mut ::socklen_t, flags: ::c_int) -> ::c_int; - pub fn execvpe(file: *const ::c_char, argv: *const *const ::c_char, - envp: *const *const ::c_char) -> ::c_int; -} - -cfg_if! { - if #[cfg(target_arch = "x86")] { - mod x86; - pub use self::x86::*; - } else if #[cfg(target_arch = "x86_64")] { - mod x86_64; - pub use self::x86_64::*; - } else if #[cfg(target_arch = "aarch64")] { - mod aarch64; - pub use self::aarch64::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86_64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86_64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -pub type c_long = i64; -pub type c_ulong = u64; -pub type c_char = i8; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -pub type c_long = i32; -pub type c_ulong = u32; -pub type c_char = i8; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/haiku/b32.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/haiku/b32.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/haiku/b32.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/haiku/b32.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -pub type c_long = i32; -pub type c_ulong = u32; -pub type time_t = i32; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/haiku/b64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/haiku/b64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/haiku/b64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/haiku/b64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -pub type c_ulong = u64; -pub type c_long = i64; -pub type time_t = i64; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/haiku/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/haiku/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/haiku/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/haiku/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1220 +0,0 @@ -use dox::{mem, Option}; - -pub type rlim_t = ::uintptr_t; -pub type sa_family_t = u8; -pub type pthread_key_t = ::c_int; -pub type nfds_t = ::c_long; -pub type tcflag_t = ::c_uint; -pub type speed_t = ::c_uint; -pub type c_char = i8; -pub type clock_t = i32; -pub type clockid_t = i32; -pub type suseconds_t = i32; -pub type wchar_t = i32; -pub type off_t = i64; -pub type ino_t = i64; -pub type blkcnt_t = i64; -pub type blksize_t = i32; -pub type dev_t = i32; -pub type mode_t = u32; -pub type nlink_t = i32; -pub type useconds_t = u32; -pub type socklen_t = u32; -pub type pthread_t = ::uintptr_t; -pub type pthread_mutexattr_t = ::uintptr_t; -pub type pthread_rwlockattr_t = ::uintptr_t; -pub type sigset_t = u64; -pub type fsblkcnt_t = i64; -pub type fsfilcnt_t = i64; -pub type pthread_attr_t = *mut ::c_void; -pub type nl_item = ::c_int; -pub type id_t = i32; -pub type idtype_t = ::c_uint; - -pub enum timezone {} - -s! { - pub struct sockaddr { - pub sa_len: u8, - pub sa_family: sa_family_t, - pub sa_data: [::c_char; 30], - } - - pub struct sockaddr_in { - pub sin_len: u8, - pub sin_family: sa_family_t, - pub sin_port: ::in_port_t, - pub sin_addr: ::in_addr, - pub sin_zero: [u8; 24], - } - - pub struct sockaddr_in6 { - pub sin6_len: u8, - pub sin6_family: sa_family_t, - pub sin6_port: ::in_port_t, - pub sin6_flowinfo: u32, - pub sin6_addr: ::in6_addr, - pub sin6_scope_id: u32, - } - - pub struct sockaddr_un { - pub sun_len: u8, - pub sun_family: sa_family_t, - pub sun_path: [::c_char; 126] - } - - pub struct sockaddr_storage { - pub ss_len: u8, - pub ss_family: sa_family_t, - __ss_pad1: [u8; 6], - __ss_pad2: u64, - __ss_pad3: [u8; 112], - } - - pub struct addrinfo { - pub ai_flags: ::c_int, - pub ai_family: ::c_int, - pub ai_socktype: ::c_int, - pub ai_protocol: ::c_int, - pub ai_addrlen: socklen_t, - pub ai_canonname: *mut c_char, - pub ai_addr: *mut ::sockaddr, - pub ai_next: *mut addrinfo, - } - - pub struct fd_set { - fds_bits: [c_ulong; FD_SETSIZE / ULONG_SIZE], - } - - pub struct tm { - pub tm_sec: ::c_int, - pub tm_min: ::c_int, - pub tm_hour: ::c_int, - pub tm_mday: ::c_int, - pub tm_mon: ::c_int, - pub tm_year: ::c_int, - pub tm_wday: ::c_int, - pub tm_yday: ::c_int, - pub tm_isdst: ::c_int, - pub tm_gmtoff: ::c_long, - pub tm_zone: *const ::c_char, - } - - pub struct utsname { - pub sysname: [::c_char; 32], - pub nodename: [::c_char; 32], - pub release: [::c_char; 32], - pub version: [::c_char; 32], - pub machine: [::c_char; 32], - } - - pub struct lconv { - pub decimal_point: *mut ::c_char, - pub thousands_sep: *mut ::c_char, - pub grouping: *mut ::c_char, - pub int_curr_symbol: *mut ::c_char, - pub currency_symbol: *mut ::c_char, - pub mon_decimal_point: *mut ::c_char, - pub mon_thousands_sep: *mut ::c_char, - pub mon_grouping: *mut ::c_char, - pub positive_sign: *mut ::c_char, - pub negative_sign: *mut ::c_char, - pub int_frac_digits: ::c_char, - pub frac_digits: ::c_char, - pub p_cs_precedes: ::c_char, - pub p_sep_by_space: ::c_char, - pub n_cs_precedes: ::c_char, - pub n_sep_by_space: ::c_char, - pub p_sign_posn: ::c_char, - pub n_sign_posn: ::c_char, - pub int_p_cs_precedes: ::c_char, - pub int_p_sep_by_space: ::c_char, - pub int_n_cs_precedes: ::c_char, - pub int_n_sep_by_space: ::c_char, - pub int_p_sign_posn: ::c_char, - pub int_n_sign_posn: ::c_char, - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::c_int, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::socklen_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::size_t, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct Dl_info { - pub dli_fname: *const ::c_char, - pub dli_fbase: *mut ::c_void, - pub dli_sname: *const ::c_char, - pub dli_saddr: *mut ::c_void, - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::c_char, - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - pub c_cc: [::cc_t; ::NCCS], - } - - pub struct flock { - pub l_type: ::c_short, - pub l_whence: ::c_short, - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_pid: ::pid_t, - } - - pub struct stat { - pub st_dev: dev_t, - pub st_ino: ino_t, - pub st_mode: mode_t, - pub st_nlink: nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_size: off_t, - pub st_rdev: dev_t, - pub st_blksize: blksize_t, - pub st_atime: time_t, - pub st_atime_nsec: c_long, - pub st_mtime: time_t, - pub st_mtime_nsec: c_long, - pub st_ctime: time_t, - pub st_ctime_nsec: c_long, - pub st_crtime: time_t, - pub st_crtime_nsec: c_long, - pub st_type: u32, - pub st_blocks: blkcnt_t, - } - - pub struct dirent { - pub d_dev: dev_t, - pub d_pdev: dev_t, - pub d_ino: ino_t, - pub d_pino: i64, - pub d_reclen: ::c_ushort, - pub d_name: [::c_char; 1024], // Max length is _POSIX_PATH_MAX - } - - pub struct glob_t { - pub gl_pathc: ::size_t, - __unused1: ::size_t, - pub gl_offs: ::size_t, - __unused2: ::size_t, - pub gl_pathv: *mut *mut c_char, - - __unused3: *mut ::c_void, - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - __unused6: *mut ::c_void, - __unused7: *mut ::c_void, - __unused8: *mut ::c_void, - } - - pub struct pthread_mutex_t { - flags: u32, - lock: i32, - unused: i32, - owner: i32, - owner_count: i32, - } - - pub struct pthread_cond_t { - flags: u32, - unused: i32, - mutex: *mut ::c_void, - waiter_count: i32, - lock: i32, - } - - pub struct pthread_rwlock_t { - flags: u32, - owner: i32, - lock_sem: i32, // this is actually a union - lock_count: i32, - reader_count: i32, - writer_count: i32, - waiters: [*mut ::c_void; 2], - } - - pub struct passwd { - pub pw_name: *mut ::c_char, - pub pw_passwd: *mut ::c_char, - pub pw_uid: ::uid_t, - pub pw_gid: ::gid_t, - pub pw_dir: *mut ::c_char, - pub pw_shell: *mut ::c_char, - pub pw_gecos: *mut ::c_char, - } - - pub struct statvfs { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_favail: ::fsfilcnt_t, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_size: ::size_t, - pub ss_flags: ::c_int, - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_code: ::c_int, - pub si_errno: ::c_int, - pub si_pid: ::pid_t, - pub si_uid: ::uid_t, - pub si_addr: *mut ::c_void, - pub si_status: ::c_int, - pub si_band: c_long, - pub sigval: *mut ::c_void, - } - - pub struct sigaction { - pub sa_sigaction: ::sighandler_t, - pub sa_mask: ::sigset_t, - pub sa_flags: ::c_int, - sa_userdata: *mut ::c_void, - } - - pub struct sigevent { - pub sigev_notify: ::c_int, - pub sigev_signo: ::c_int, - pub sigev_value: ::sigval, - __unused1: *mut ::c_void, // actually a function pointer - pub sigev_notify_attributes: *mut ::pthread_attr_t, - } - - pub struct sem_t { - pub se_type: i32, - pub se_named_id: i32, // this is actually a union - pub se_unnamed: i32, - pub se_padding: [i32; 4], - } - - pub struct pthread_condattr_t { - pub process_shared: bool, - pub clock_id: i32, - } -} - -// intentionally not public, only used for fd_set -cfg_if! { - if #[cfg(target_pointer_width = "32")] { - const ULONG_SIZE: usize = 32; - } else if #[cfg(target_pointer_width = "64")] { - const ULONG_SIZE: usize = 64; - } else { - // Unknown target_pointer_width - } -} - -pub const EXIT_FAILURE: ::c_int = 1; -pub const EXIT_SUCCESS: ::c_int = 0; -pub const RAND_MAX: ::c_int = 2147483647; -pub const EOF: ::c_int = -1; -pub const SEEK_SET: ::c_int = 0; -pub const SEEK_CUR: ::c_int = 1; -pub const SEEK_END: ::c_int = 2; -pub const _IOFBF: ::c_int = 0; -pub const _IONBF: ::c_int = 2; -pub const _IOLBF: ::c_int = 1; - -pub const F_DUPFD: ::c_int = 0x0001; -pub const F_GETFD: ::c_int = 0x0002; -pub const F_SETFD: ::c_int = 0x0004; -pub const F_GETFL: ::c_int = 0x0008; -pub const F_SETFL: ::c_int = 0x0010; -pub const F_GETLK: ::c_int = 0x0020; -pub const F_SETLK: ::c_int = 0x0080; -pub const F_SETLKW: ::c_int = 0x0100; -pub const F_DUPFD_CLOEXEC: ::c_int = 0x0200; - -pub const AT_FDCWD: ::c_int = -1; -pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x01; -pub const AT_SYMLINK_FOLLOW: ::c_int = 0x02; -pub const AT_REMOVEDIR: ::c_int = 0x04; -pub const AT_EACCESS: ::c_int = 0x08; - -pub const POLLIN: ::c_short = 0x0001; -pub const POLLOUT: ::c_short = 0x0002; -pub const POLLRDNORM: ::c_short = POLLIN; -pub const POLLWRNORM: ::c_short = POLLOUT; -pub const POLLRDBAND: ::c_short = 0x0008; -pub const POLLWRBAND: ::c_short = 0x0010; -pub const POLLPRI: ::c_short = 0x0020; -pub const POLLERR: ::c_short = 0x0004; -pub const POLLHUP: ::c_short = 0x0080; -pub const POLLNVAL: ::c_short = 0x1000; - -pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; -pub const PTHREAD_CREATE_DETACHED: ::c_int = 1; - -pub const CLOCK_REALTIME: ::c_int = -1; -pub const CLOCK_MONOTONIC: ::c_int = 0; - -pub const RLIMIT_CORE: ::c_int = 0; -pub const RLIMIT_CPU: ::c_int = 1; -pub const RLIMIT_DATA: ::c_int = 2; -pub const RLIMIT_FSIZE: ::c_int = 3; -pub const RLIMIT_NOFILE: ::c_int = 4; -pub const RLIMIT_AS: ::c_int = 6; -// Haiku specific -pub const RLIMIT_NOVMON: ::c_int = 7; -pub const RLIMIT_NLIMITS: ::c_int = 8; - -pub const RUSAGE_SELF: ::c_int = 0; - -pub const RTLD_LAXY: ::c_int = 0; - -pub const NCCS: usize = 11; - -pub const O_RDONLY: ::c_int = 0x0000; -pub const O_WRONLY: ::c_int = 0x0001; -pub const O_RDWR: ::c_int = 0x0002; -pub const O_ACCMODE: ::c_int = 0x0003; - -pub const O_EXCL: ::c_int = 0x0100; -pub const O_CREAT: ::c_int = 0x0200; -pub const O_TRUNC: ::c_int = 0x0400; -pub const O_NOCTTY: ::c_int = 0x1000; -pub const O_NOTRAVERSE: ::c_int = 0x2000; - -pub const O_CLOEXEC: ::c_int = 0x00000040; -pub const O_NONBLOCK: ::c_int = 0x00000080; -pub const O_APPEND: ::c_int = 0x00000800; -pub const O_SYNC: ::c_int = 0x00010000; -pub const O_RSYNC: ::c_int = 0x00020000; -pub const O_DSYNC: ::c_int = 0x00040000; -pub const O_NOFOLLOW: ::c_int = 0x00080000; -pub const O_NOCACHE: ::c_int = 0x00100000; -pub const O_DIRECTORY: ::c_int = 0x00200000; - -pub const S_IFIFO: ::mode_t = 61440; -pub const S_IFCHR: ::mode_t = 49152; -pub const S_IFBLK: ::mode_t = 24576; -pub const S_IFDIR: ::mode_t = 16384; -pub const S_IFREG: ::mode_t = 32768; -pub const S_IFLNK: ::mode_t = 40960; -pub const S_IFSOCK: ::mode_t = 49152; -pub const S_IFMT: ::mode_t = 61440; -pub const S_IRWXU: ::mode_t = 448; -pub const S_IXUSR: ::mode_t = 64; -pub const S_IWUSR: ::mode_t = 128; -pub const S_IRUSR: ::mode_t = 256; -pub const S_IRWXG: ::mode_t = 70; -pub const S_IXGRP: ::mode_t = 10; -pub const S_IWGRP: ::mode_t = 20; -pub const S_IRGRP: ::mode_t = 40; -pub const S_IRWXO: ::mode_t = 7; -pub const S_IXOTH: ::mode_t = 1; -pub const S_IWOTH: ::mode_t = 2; -pub const S_IROTH: ::mode_t = 4; -pub const F_OK: ::c_int = 0; -pub const R_OK: ::c_int = 4; -pub const W_OK: ::c_int = 2; -pub const X_OK: ::c_int = 1; -pub const STDIN_FILENO: ::c_int = 0; -pub const STDOUT_FILENO: ::c_int = 1; -pub const STDERR_FILENO: ::c_int = 2; - -pub const SIGHUP: ::c_int = 1; -pub const SIGINT: ::c_int = 2; -pub const SIGQUIT: ::c_int = 3; -pub const SIGILL: ::c_int = 4; -pub const SIGCHLD: ::c_int = 5; -pub const SIGABRT: ::c_int = 6; -pub const SIGPIPE: ::c_int = 7; -pub const SIGFPE: ::c_int = 8; -pub const SIGKILL: ::c_int = 9; -pub const SIGSTOP: ::c_int = 10; -pub const SIGSEGV: ::c_int = 11; -pub const SIGCONT: ::c_int = 12; -pub const SIGTSTP: ::c_int = 13; -pub const SIGALRM: ::c_int = 14; -pub const SIGTERM: ::c_int = 15; -pub const SIGTTIN: ::c_int = 16; -pub const SIGTTOU: ::c_int = 17; -pub const SIGUSR1: ::c_int = 18; -pub const SIGUSR2: ::c_int = 19; -pub const SIGWINCH: ::c_int = 20; -pub const SIGKILLTHR: ::c_int = 21; -pub const SIGTRAP: ::c_int = 22; -pub const SIGPOLL: ::c_int = 23; -pub const SIGPROF: ::c_int = 24; -pub const SIGSYS: ::c_int = 25; -pub const SIGURG: ::c_int = 26; -pub const SIGVTALRM: ::c_int = 27; -pub const SIGXCPU: ::c_int = 28; -pub const SIGXFSZ: ::c_int = 29; -pub const SIGBUS: ::c_int = 30; - -pub const SIG_BLOCK: ::c_int = 1; -pub const SIG_UNBLOCK: ::c_int = 2; -pub const SIG_SETMASK: ::c_int = 3; - -pub const SIGEV_NONE: ::c_int = 0; -pub const SIGEV_SIGNAL: ::c_int = 1; -pub const SIGEV_THREAD: ::c_int = 2; - -pub const EAI_AGAIN: ::c_int = 2; -pub const EAI_BADFLAGS: ::c_int = 3; -pub const EAI_FAIL: ::c_int = 4; -pub const EAI_FAMILY: ::c_int = 5; -pub const EAI_MEMORY: ::c_int = 6; -pub const EAI_NODATA: ::c_int = 7; -pub const EAI_NONAME: ::c_int = 8; -pub const EAI_SERVICE: ::c_int = 9; -pub const EAI_SOCKTYPE: ::c_int = 10; -pub const EAI_SYSTEM: ::c_int = 11; -pub const EAI_OVERFLOW: ::c_int = 14; - -pub const PROT_NONE: ::c_int = 0; -pub const PROT_READ: ::c_int = 1; -pub const PROT_WRITE: ::c_int = 2; -pub const PROT_EXEC: ::c_int = 4; - -pub const LC_ALL: ::c_int = 0; -pub const LC_COLLATE: ::c_int = 1; -pub const LC_CTYPE: ::c_int = 2; -pub const LC_MONETARY: ::c_int = 3; -pub const LC_NUMERIC: ::c_int = 4; -pub const LC_TIME: ::c_int = 5; -pub const LC_MESSAGES: ::c_int = 6; - -// TODO: Haiku does not have MAP_FILE, but libstd/os.rs requires it -pub const MAP_FILE: ::c_int = 0x00; -pub const MAP_SHARED: ::c_int = 0x01; -pub const MAP_PRIVATE: ::c_int = 0x02; -pub const MAP_FIXED: ::c_int = 0x04; -pub const MAP_ANONYMOUS: ::c_int = 0x08; -pub const MAP_ANON: ::c_int = MAP_ANONYMOUS; - -pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; - -pub const MS_ASYNC: ::c_int = 0x01; -pub const MS_INVALIDATE: ::c_int = 0x04; -pub const MS_SYNC: ::c_int = 0x02; - -pub const E2BIG : ::c_int = -2147454975; -pub const ECHILD : ::c_int = -2147454974; -pub const EDEADLK : ::c_int = -2147454973; -pub const EFBIG : ::c_int = -2147454972; -pub const EMLINK : ::c_int = -2147454971; -pub const ENFILE : ::c_int = -2147454970; -pub const ENODEV : ::c_int = -2147454969; -pub const ENOLCK : ::c_int = -2147454968; -pub const ENOSYS : ::c_int = -2147454967; -pub const ENOTTY : ::c_int = -2147454966; -pub const ENXIO : ::c_int = -2147454965; -pub const ESPIPE : ::c_int = -2147454964; -pub const ESRCH : ::c_int = -2147454963; -pub const EFPOS : ::c_int = -2147457962; -pub const ESIGPARM : ::c_int = -2147457961; -pub const EDOM : ::c_int = -2147454960; -pub const ERANGE : ::c_int = -2147454959; -pub const EPROTOTYPE : ::c_int = -2147454958; -pub const EPROTONOSUPPORT : ::c_int = -2147454957; -pub const EPFNOSUPPORT : ::c_int = -2147454956; -pub const EAFNOSUPPORT : ::c_int = -2147454955; -pub const EADDRINUSE : ::c_int = -2147454954; -pub const EADDRNOTAVAIL : ::c_int = -2147454953; -pub const ENETDOWN : ::c_int = -2147454952; -pub const ENETUNREACH : ::c_int = -2147454951; -pub const ENETRESET : ::c_int = -2147454950; -pub const ECONNABORTED : ::c_int = -2147454949; -pub const ECONNRESET : ::c_int = -2147454948; -pub const EISCONN : ::c_int = -2147454947; -pub const ENOTCONN : ::c_int = -2147454946; -pub const ESHUTDOWN : ::c_int = -2147454945; -pub const ECONNREFUSED : ::c_int = -2147454944; -pub const EHOSTUNREACH : ::c_int = -2147454943; -pub const ENOPROTOOPT : ::c_int = -2147454942; -pub const ENOBUFS : ::c_int = -2147454941; -pub const EINPROGRESS : ::c_int = -2147454940; -pub const EALREADY : ::c_int = -2147454939; -pub const EILSEQ : ::c_int = -2147454938; -pub const ENOMSG : ::c_int = -2147454937; -pub const ESTALE : ::c_int = -2147454936; -pub const EOVERFLOW : ::c_int = -2147454935; -pub const EMSGSIZE : ::c_int = -2147454934; -pub const EOPNOTSUPP : ::c_int = -2147454933; -pub const ENOTSOCK : ::c_int = -2147454932; -pub const EHOSTDOWN : ::c_int = -2147454931; -pub const EBADMSG : ::c_int = -2147454930; -pub const ECANCELED : ::c_int = -2147454929; -pub const EDESTADDRREQ : ::c_int = -2147454928; -pub const EDQUOT : ::c_int = -2147454927; -pub const EIDRM : ::c_int = -2147454926; -pub const EMULTIHOP : ::c_int = -2147454925; -pub const ENODATA : ::c_int = -2147454924; -pub const ENOLINK : ::c_int = -2147454923; -pub const ENOSR : ::c_int = -2147454922; -pub const ENOSTR : ::c_int = -2147454921; -pub const ENOTSUP : ::c_int = -2147454920; -pub const EPROTO : ::c_int = -2147454919; -pub const ETIME : ::c_int = -2147454918; -pub const ETXTBSY : ::c_int = -2147454917; -pub const ENOATTR : ::c_int = -2147454916; - -// INT_MIN -pub const ENOMEM : ::c_int = -2147454976; - -// POSIX errors that can be mapped to BeOS error codes -pub const EACCES : ::c_int = -2147483646; -pub const EINTR : ::c_int = -2147483638; -pub const EIO : ::c_int = -2147483647; -pub const EBUSY : ::c_int = -2147483634; -pub const EFAULT : ::c_int = -2147478783; -pub const ETIMEDOUT : ::c_int = -2147483639; -pub const EAGAIN : ::c_int = -2147483637; -pub const EWOULDBLOCK : ::c_int = -2147483637; -pub const EBADF : ::c_int = -2147459072; -pub const EEXIST : ::c_int = -2147459070; -pub const EINVAL : ::c_int = -2147483643; -pub const ENAMETOOLONG : ::c_int = -2147459068; -pub const ENOENT : ::c_int = -2147459069; -pub const EPERM : ::c_int = -2147483633; -pub const ENOTDIR : ::c_int = -2147459067; -pub const EISDIR : ::c_int = -2147459063; -pub const ENOTEMPTY : ::c_int = -2147459066; -pub const ENOSPC : ::c_int = -2147459065; -pub const EROFS : ::c_int = -2147459064; -pub const EMFILE : ::c_int = -2147459062; -pub const EXDEV : ::c_int = -2147459061; -pub const ELOOP : ::c_int = -2147459060; -pub const ENOEXEC : ::c_int = -2147478782; -pub const EPIPE : ::c_int = -2147459059; - -pub const IPPROTO_RAW: ::c_int = 255; - -// These are prefixed with POSIX_ on Haiku -pub const MADV_NORMAL: ::c_int = 1; -pub const MADV_SEQUENTIAL: ::c_int = 2; -pub const MADV_RANDOM: ::c_int = 3; -pub const MADV_WILLNEED: ::c_int = 4; -pub const MADV_DONTNEED: ::c_int = 5; - -// https://github.com/haiku/haiku/blob/master/headers/posix/net/if.h#L80 -pub const IFF_UP: ::c_int = 0x0001; -pub const IFF_BROADCAST: ::c_int = 0x0002; // valid broadcast address -pub const IFF_LOOPBACK: ::c_int = 0x0008; -pub const IFF_POINTOPOINT: ::c_int = 0x0010; // point-to-point link -pub const IFF_NOARP: ::c_int = 0x0040; // no address resolution -pub const IFF_AUTOUP: ::c_int = 0x0080; // auto dial -pub const IFF_PROMISC: ::c_int = 0x0100; // receive all packets -pub const IFF_ALLMULTI: ::c_int = 0x0200; // receive all multicast packets -pub const IFF_SIMPLEX: ::c_int = 0x0800; // doesn't receive own transmissions -pub const IFF_LINK: ::c_int = 0x1000; // has link -pub const IFF_AUTO_CONFIGURED: ::c_int = 0x2000; -pub const IFF_CONFIGURING: ::c_int = 0x4000; -pub const IFF_MULTICAST: ::c_int = 0x8000; // supports multicast - -pub const AF_UNSEC: ::c_int = 0; -pub const AF_INET: ::c_int = 1; -pub const AF_APPLETALK: ::c_int = 2; -pub const AF_ROUTE: ::c_int = 3; -pub const AF_LINK: ::c_int = 4; -pub const AF_INET6: ::c_int = 5; -pub const AF_DLI: ::c_int = 6; -pub const AF_IPX: ::c_int = 7; -pub const AF_NOTIFY: ::c_int = 8; -pub const AF_LOCAL: ::c_int = 9; -pub const AF_UNIX: ::c_int = AF_LOCAL; -pub const AF_BLUETOOTH: ::c_int = 10; -pub const AF_MAX: ::c_int = 11; - -pub const IP_MULTICAST_TTL: ::c_int = 10; -pub const IP_MULTICAST_LOOP: ::c_int = 11; -pub const IP_TTL: ::c_int = 4; -pub const IP_HDRINCL: ::c_int = 2; -pub const IP_ADD_MEMBERSHIP: ::c_int = 12; -pub const IP_DROP_MEMBERSHIP: ::c_int = 13; - -pub const TCP_NODELAY: ::c_int = 0x01; -pub const TCP_MAXSEG: ::c_int = 0x02; -pub const TCP_NOPUSH: ::c_int = 0x04; -pub const TCP_NOOPT: ::c_int = 0x08; - -pub const IPV6_MULTICAST_LOOP: ::c_int = 26; -pub const IPV6_JOIN_GROUP: ::c_int = 28; -pub const IPV6_LEAVE_GROUP: ::c_int = 29; -pub const IPV6_V6ONLY: ::c_int = 30; - -pub const MSG_OOB: ::c_int = 0x0001; -pub const MSG_PEEK: ::c_int = 0x0002; -pub const MSG_DONTROUTE: ::c_int = 0x0004; -pub const MSG_EOR: ::c_int = 0x0008; -pub const MSG_TRUNC: ::c_int = 0x0010; -pub const MSG_CTRUNC: ::c_int = 0x0020; -pub const MSG_WAITALL: ::c_int = 0x0040; -pub const MSG_DONTWAIT: ::c_int = 0x0080; -pub const MSG_BCAST: ::c_int = 0x0100; -pub const MSG_MCAST: ::c_int = 0x0200; -pub const MSG_EOF: ::c_int = 0x0400; -pub const MSG_NOSIGNAL: ::c_int = 0x0800; - -pub const SHUT_RD: ::c_int = 0; -pub const SHUT_WR: ::c_int = 1; -pub const SHUT_RDWR: ::c_int = 2; - -pub const LOCK_SH: ::c_int = 0x01; -pub const LOCK_EX: ::c_int = 0x02; -pub const LOCK_NB: ::c_int = 0x04; -pub const LOCK_UN: ::c_int = 0x08; - -pub const SIGSTKSZ: ::size_t = 16384; - -pub const PATH_MAX: ::c_int = 1024; - -pub const SA_NOCLDSTOP: ::c_int = 0x01; -pub const SA_NOCLDWAIT: ::c_int = 0x02; -pub const SA_RESETHAND: ::c_int = 0x04; -pub const SA_NODEFER: ::c_int = 0x08; -pub const SA_RESTART: ::c_int = 0x10; -pub const SA_ONSTACK: ::c_int = 0x20; -pub const SA_SIGINFO: ::c_int = 0x40; -pub const SA_NOMASK: ::c_int = SA_NODEFER; -pub const SA_STACK: ::c_int = SA_ONSTACK; -pub const SA_ONESHOT: ::c_int = SA_RESETHAND; - -pub const FD_SETSIZE: usize = 1024; - -pub const RTLD_NOW: ::c_int = 0x1; -pub const RTLD_DEFAULT: *mut ::c_void = 0isize as *mut ::c_void; - -pub const BUFSIZ: ::c_uint = 8192; -pub const FILENAME_MAX: ::c_uint = 256; -pub const FOPEN_MAX: ::c_uint = 128; -pub const L_tmpnam: ::c_uint = 512; -pub const TMP_MAX: ::c_uint = 32768; - -pub const _PC_CHOWN_RESTRICTED: ::c_int = 1; -pub const _PC_MAX_CANON: ::c_int = 2; -pub const _PC_MAX_INPUT: ::c_int = 3; -pub const _PC_NAME_MAX: ::c_int = 4; -pub const _PC_NO_TRUNC: ::c_int = 5; -pub const _PC_PATH_MAX: ::c_int = 6; -pub const _PC_PIPE_BUF: ::c_int = 7; -pub const _PC_VDISABLE: ::c_int = 8; -pub const _PC_LINK_MAX: ::c_int = 25; -pub const _PC_SYNC_IO: ::c_int = 26; -pub const _PC_ASYNC_IO: ::c_int = 27; -pub const _PC_PRIO_IO: ::c_int = 28; -pub const _PC_SOCK_MAXBUF: ::c_int = 29; -pub const _PC_FILESIZEBITS: ::c_int = 30; -pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 31; -pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 32; -pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 33; -pub const _PC_REC_XFER_ALIGN: ::c_int = 34; -pub const _PC_ALLOC_SIZE_MIN: ::c_int = 35; -pub const _PC_SYMLINK_MAX: ::c_int = 36; -pub const _PC_2_SYMLINKS: ::c_int = 37; -pub const _PC_XATTR_EXISTS: ::c_int = 38; -pub const _PC_XATTR_ENABLED: ::c_int = 39; - -pub const FIONBIO: ::c_int = 0xbe000000; - -pub const _SC_ARG_MAX : ::c_int = 15; -pub const _SC_CHILD_MAX : ::c_int = 16; -pub const _SC_CLK_TCK : ::c_int = 17; -pub const _SC_JOB_CONTROL : ::c_int = 18; -pub const _SC_NGROUPS_MAX : ::c_int = 19; -pub const _SC_OPEN_MAX : ::c_int = 20; -pub const _SC_SAVED_IDS : ::c_int = 21; -pub const _SC_STREAM_MAX : ::c_int = 22; -pub const _SC_TZNAME_MAX : ::c_int = 23; -pub const _SC_VERSION : ::c_int = 24; -pub const _SC_GETGR_R_SIZE_MAX : ::c_int = 25; -pub const _SC_GETPW_R_SIZE_MAX : ::c_int = 26; -pub const _SC_PAGESIZE : ::c_int = 27; -pub const _SC_PAGE_SIZE : ::c_int = 27; -pub const _SC_SEM_NSEMS_MAX : ::c_int = 28; -pub const _SC_SEM_VALUE_MAX : ::c_int = 29; -pub const _SC_SEMAPHORES : ::c_int = 30; -pub const _SC_THREADS : ::c_int = 31; -pub const _SC_IOV_MAX : ::c_int = 32; -pub const _SC_UIO_MAXIOV : ::c_int = 32; -pub const _SC_NPROCESSORS_CONF : ::c_int = 34; -pub const _SC_NPROCESSORS_ONLN : ::c_int = 35; -pub const _SC_ATEXIT_MAX : ::c_int = 37; -pub const _SC_PASS_MAX : ::c_int = 39; -pub const _SC_PHYS_PAGES : ::c_int = 40; -pub const _SC_AVPHYS_PAGES : ::c_int = 41; -pub const _SC_PIPE : ::c_int = 42; -pub const _SC_SELECT : ::c_int = 43; -pub const _SC_POLL : ::c_int = 44; -pub const _SC_MAPPED_FILES : ::c_int = 45; -pub const _SC_THREAD_PROCESS_SHARED : ::c_int = 46; -pub const _SC_THREAD_STACK_MIN : ::c_int = 47; -pub const _SC_THREAD_ATTR_STACKADDR : ::c_int = 48; -pub const _SC_THREAD_ATTR_STACKSIZE : ::c_int = 49; -pub const _SC_THREAD_PRIORITY_SCHEDULING : ::c_int = 50; -pub const _SC_REALTIME_SIGNALS : ::c_int = 51; -pub const _SC_MEMORY_PROTECTION : ::c_int = 52; -pub const _SC_SIGQUEUE_MAX : ::c_int = 53; -pub const _SC_RTSIG_MAX : ::c_int = 54; -pub const _SC_MONOTONIC_CLOCK : ::c_int = 55; -pub const _SC_DELAYTIMER_MAX : ::c_int = 56; -pub const _SC_TIMER_MAX : ::c_int = 57; -pub const _SC_TIMERS : ::c_int = 58; -pub const _SC_CPUTIME : ::c_int = 59; -pub const _SC_THREAD_CPUTIME : ::c_int = 60; - -pub const PTHREAD_STACK_MIN: ::size_t = 8192; - -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { - flags: 0, - lock: 0, - unused: -42, - owner: -1, - owner_count: 0, -}; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { - flags: 0, - unused: -42, - mutex: 0 as *mut _, - waiter_count: 0, - lock: 0, -}; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { - flags: 0, - owner: -1, - lock_sem: 0, - lock_count: 0, - reader_count: 0, - writer_count: 0, - waiters: [0 as *mut _; 2], -}; - -pub const PTHREAD_MUTEX_DEFAULT: ::c_int = 0; -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 1; -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 3; - -pub const FIOCLEX: c_ulong = 0; // TODO: does not exist on Haiku! - -pub const RUSAGE_CHILDREN: ::c_int = -1; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; -pub const SOCK_RAW: ::c_int = 3; -pub const SOCK_SEQPACKET: ::c_int = 5; - -pub const SOL_SOCKET: ::c_int = -1; -pub const SO_ACCEPTCONN: ::c_int = 0x00000001; -pub const SO_BROADCAST: ::c_int = 0x00000002; -pub const SO_DEBUG: ::c_int = 0x00000004; -pub const SO_DONTROUTE: ::c_int = 0x00000008; -pub const SO_KEEPALIVE: ::c_int = 0x00000010; -pub const SO_OOBINLINE: ::c_int = 0x00000020; -pub const SO_REUSEADDR: ::c_int = 0x00000040; -pub const SO_REUSEPORT: ::c_int = 0x00000080; -pub const SO_USELOOPBACK: ::c_int = 0x00000100; -pub const SO_LINGER: ::c_int = 0x00000200; -pub const SO_SNDBUF: ::c_int = 0x40000001; -pub const SO_SNDLOWAT: ::c_int = 0x40000002; -pub const SO_SNDTIMEO: ::c_int = 0x40000003; -pub const SO_RCVBUF: ::c_int = 0x40000004; -pub const SO_RCVLOWAT: ::c_int = 0x40000005; -pub const SO_RCVTIMEO: ::c_int = 0x40000006; -pub const SO_ERROR: ::c_int = 0x40000007; -pub const SO_TYPE: ::c_int = 0x40000008; -pub const SO_NONBLOCK: ::c_int = 0x40000009; -pub const SO_BINDTODEVICE: ::c_int = 0x4000000a; -pub const SO_PEERCRED: ::c_int = 0x4000000b; - -pub const SCM_RIGHTS: ::c_int = 0x01; - -pub const NI_MAXHOST: ::size_t = 1025; - -pub const WNOHANG: ::c_int = 0x01; -pub const WUNTRACED: ::c_int = 0x02; -pub const WCONTINUED: ::c_int = 0x04; -pub const WEXITED: ::c_int = 0x08; -pub const WSTOPPED: ::c_int = 0x10; -pub const WNOWAIT: ::c_int = 0x20; - -pub const P_ALL: idtype_t = 0; -pub const P_PID: idtype_t = 1; -pub const P_PGID: idtype_t = 2; - -pub const VINTR: usize = 0; -pub const VQUIT: usize = 1; -pub const VERASE: usize = 2; -pub const VKILL: usize = 3; -pub const VEOF: usize = 4; -pub const VEOL: usize = 5; -pub const VMIN: usize = 4; -pub const VTIME: usize = 5; -pub const VEOL2: usize = 6; -pub const VSWTCH: usize = 7; -pub const VSTART: usize = 8; -pub const VSTOP: usize = 9; -pub const VSUSP: usize = 10; - -pub const IGNBRK: ::tcflag_t = 0x01; -pub const BRKINT: ::tcflag_t = 0x02; -pub const IGNPAR: ::tcflag_t = 0x04; -pub const PARMRK: ::tcflag_t = 0x08; -pub const INPCK: ::tcflag_t = 0x10; -pub const ISTRIP: ::tcflag_t = 0x20; -pub const INLCR: ::tcflag_t = 0x40; -pub const IGNCR: ::tcflag_t = 0x80; -pub const ICRNL: ::tcflag_t = 0x100; -pub const IUCLC: ::tcflag_t = 0x200; -pub const IXON: ::tcflag_t = 0x400; -pub const IXANY: ::tcflag_t = 0x800; -pub const IXOFF: ::tcflag_t = 0x1000; - -pub const OPOST: ::tcflag_t = 0x00000001; -pub const OLCUC: ::tcflag_t = 0x00000002; -pub const ONLCR: ::tcflag_t = 0x00000004; -pub const OCRNL: ::tcflag_t = 0x00000008; -pub const ONOCR: ::tcflag_t = 0x00000010; -pub const ONLRET: ::tcflag_t = 0x00000020; -pub const OFILL: ::tcflag_t = 0x00000040; -pub const OFDEL: ::tcflag_t = 0x00000080; -pub const NLDLY: ::tcflag_t = 0x00000100; -pub const NL0: ::tcflag_t = 0x00000000; -pub const NL1: ::tcflag_t = 0x00000100; -pub const CRDLY: ::tcflag_t = 0x00000600; -pub const CR0: ::tcflag_t = 0x00000000; -pub const CR1: ::tcflag_t = 0x00000200; -pub const CR2: ::tcflag_t = 0x00000400; -pub const CR3: ::tcflag_t = 0x00000600; -pub const TABDLY: ::tcflag_t = 0x00001800; -pub const TAB0: ::tcflag_t = 0x00000000; -pub const TAB1: ::tcflag_t = 0x00000800; -pub const TAB2: ::tcflag_t = 0x00001000; -pub const TAB3: ::tcflag_t = 0x00001800; -pub const BSDLY: ::tcflag_t = 0x00002000; -pub const BS0: ::tcflag_t = 0x00000000; -pub const BS1: ::tcflag_t = 0x00002000; -pub const VTDLY: ::tcflag_t = 0x00004000; -pub const VT0: ::tcflag_t = 0x00000000; -pub const VT1: ::tcflag_t = 0x00004000; -pub const FFDLY: ::tcflag_t = 0x00008000; -pub const FF0: ::tcflag_t = 0x00000000; -pub const FF1: ::tcflag_t = 0x00008000; - -pub const CSIZE: ::tcflag_t = 0x00000020; -pub const CS5: ::tcflag_t = 0x00000000; -pub const CS6: ::tcflag_t = 0x00000000; -pub const CS7: ::tcflag_t = 0x00000000; -pub const CS8: ::tcflag_t = 0x00000020; -pub const CSTOPB: ::tcflag_t = 0x00000040; -pub const CREAD: ::tcflag_t = 0x00000080; -pub const PARENB: ::tcflag_t = 0x00000100; -pub const PARODD: ::tcflag_t = 0x00000200; -pub const HUPCL: ::tcflag_t = 0x00000400; -pub const CLOCAL: ::tcflag_t = 0x00000800; -pub const XLOBLK: ::tcflag_t = 0x00001000; -pub const CTSFLOW: ::tcflag_t = 0x00002000; -pub const RTSFLOW: ::tcflag_t = 0x00004000; -pub const CRTSCTS: ::tcflag_t = RTSFLOW | CTSFLOW; - -pub const ISIG: ::tcflag_t = 0x00000001; -pub const ICANON: ::tcflag_t = 0x00000002; -pub const XCASE: ::tcflag_t = 0x00000004; -pub const ECHO: ::tcflag_t = 0x00000008; -pub const ECHOE: ::tcflag_t = 0x00000010; -pub const ECHOK: ::tcflag_t = 0x00000020; -pub const ECHONL: ::tcflag_t = 0x00000040; -pub const NOFLSH: ::tcflag_t = 0x00000080; -pub const TOSTOP: ::tcflag_t = 0x00000100; -pub const IEXTEN: ::tcflag_t = 0x00000200; -pub const ECHOCTL: ::tcflag_t = 0x00000400; -pub const ECHOPRT: ::tcflag_t = 0x00000800; -pub const ECHOKE: ::tcflag_t = 0x00001000; -pub const FLUSHO: ::tcflag_t = 0x00002000; -pub const PENDIN: ::tcflag_t = 0x00004000; - -pub const TCGB_CTS: ::c_int = 0x01; -pub const TCGB_DSR: ::c_int = 0x02; -pub const TCGB_RI: ::c_int = 0x04; -pub const TCGB_DCD: ::c_int = 0x08; -pub const TIOCM_CTS: ::c_int = TCGB_CTS; -pub const TIOCM_CD: ::c_int = TCGB_DCD; -pub const TIOCM_CAR: ::c_int = TIOCM_CD; -pub const TIOCM_RI: ::c_int = TCGB_RI; -pub const TIOCM_DSR: ::c_int = TCGB_DSR; -pub const TIOCM_DTR: ::c_int = 0x10; -pub const TIOCM_RTS: ::c_int = 0x20; - -pub const B0: speed_t = 0x00; -pub const B50: speed_t = 0x01; -pub const B75: speed_t = 0x02; -pub const B110: speed_t = 0x03; -pub const B134: speed_t = 0x04; -pub const B150: speed_t = 0x05; -pub const B200: speed_t = 0x06; -pub const B300: speed_t = 0x07; -pub const B600: speed_t = 0x08; -pub const B1200: speed_t = 0x09; -pub const B1800: speed_t = 0x0A; -pub const B2400: speed_t = 0x0B; -pub const B4800: speed_t = 0x0C; -pub const B9600: speed_t = 0x0D; -pub const B19200: speed_t = 0x0E; -pub const B38400: speed_t = 0x0F; -pub const B57600: speed_t = 0x10; -pub const B115200: speed_t = 0x11; -pub const B230400: speed_t = 0x12; -pub const B31250: speed_t = 0x13; - -pub const TCSANOW: ::c_int = 0x01; -pub const TCSADRAIN: ::c_int = 0x02; -pub const TCSAFLUSH: ::c_int = 0x04; - -pub const TCOOFF: ::c_int = 0x01; -pub const TCOON: ::c_int = 0x02; -pub const TCIOFF: ::c_int = 0x04; -pub const TCION: ::c_int = 0x08; - -pub const TCIFLUSH: ::c_int = 0x01; -pub const TCOFLUSH: ::c_int = 0x02; -pub const TCIOFLUSH: ::c_int = 0x03; - -f! { - pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { - let fd = fd as usize; - let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; - (*set).fds_bits[fd / size] &= !(1 << (fd % size)); - return - } - - pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { - let fd = fd as usize; - let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; - return ((*set).fds_bits[fd / size] & (1 << (fd % size))) != 0 - } - - pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { - let fd = fd as usize; - let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; - (*set).fds_bits[fd / size] |= 1 << (fd % size); - return - } - - pub fn FD_ZERO(set: *mut fd_set) -> () { - for slot in (*set).fds_bits.iter_mut() { - *slot = 0; - } - } - - pub fn WIFEXITED(status: ::c_int) -> bool { - (status & !0xff) == 0 - } - - pub fn WEXITSTATUS(status: ::c_int) -> ::c_int { - (status & 0xff) - } - - pub fn WIFSIGNALED(status: ::c_int) -> bool { - ((status >> 8) & 0xff) != 0 - } - - pub fn WTERMSIG(status: ::c_int) -> ::c_int { - (status >> 8) & 0xff - } - - pub fn WIFSTOPPED(status: ::c_int) -> bool { - ((status >> 16) & 0xff) != 0 - } - - pub fn WSTOPSIG(status: ::c_int) -> ::c_int { - (status >> 16) & 0xff - } - - // actually WIFCORED, but this is used everywhere else - pub fn WCOREDUMP(status: ::c_int) -> bool { - (status & 0x10000) != 0 - } - - pub fn WIFCONTINUED(status: ::c_int) -> bool { - (status & 0x20000) != 0 - } -} - -#[link(name = "bsd")] -extern { - pub fn clock_gettime(clk_id: ::c_int, tp: *mut ::timespec) -> ::c_int; - pub fn clock_settime(clk_id: ::c_int, tp: *const ::timespec) -> ::c_int; - pub fn pthread_create(thread: *mut ::pthread_t, - attr: *const ::pthread_attr_t, - f: extern fn(*mut ::c_void) -> *mut ::c_void, - value: *mut ::c_void) -> ::c_int; - pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, - guardsize: *mut ::size_t) -> ::c_int; - pub fn pthread_attr_getstack(attr: *const ::pthread_attr_t, - stackaddr: *mut *mut ::c_void, - stacksize: *mut ::size_t) -> ::c_int; - pub fn pthread_condattr_getclock(attr: *const pthread_condattr_t, - clock_id: *mut clockid_t) -> ::c_int; - pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, - clock_id: ::clockid_t) -> ::c_int; - pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; - pub fn setgroups(ngroups: ::size_t, - ptr: *const ::gid_t) -> ::c_int; - pub fn ioctl(fd: ::c_int, request: ::c_int, ...) -> ::c_int; - pub fn mprotect(addr: *const ::c_void, len: ::size_t, prot: ::c_int) - -> ::c_int; - pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; - pub fn getnameinfo(sa: *const ::sockaddr, - salen: ::socklen_t, - host: *mut ::c_char, - hostlen: ::size_t, - serv: *mut ::c_char, - sevlen: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, - abstime: *const ::timespec) -> ::c_int; - pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, - options: ::c_int) -> ::c_int; - - pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; - pub fn glob(pattern: *const ::c_char, - flags: ::c_int, - errfunc: Option ::c_int>, - pglob: *mut ::glob_t) -> ::c_int; - pub fn globfree(pglob: *mut ::glob_t); - - pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - pub fn shm_open(name: *const ::c_char, oflag: ::c_int, mode: ::mode_t) - -> ::c_int; - pub fn shm_unlink(name: *const ::c_char) -> ::c_int; - - pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); - - pub fn telldir(dirp: *mut ::DIR) -> ::c_long; - pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; - - pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, - flags: ::c_int, addr: *mut ::sockaddr, - addrlen: *mut ::socklen_t) -> ::ssize_t; - pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; - pub fn futimes(fd: ::c_int, times: *const ::timeval) -> ::c_int; - pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; - pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; - - pub fn bind(socket: ::c_int, address: *const ::sockaddr, - address_len: ::socklen_t) -> ::c_int; - - pub fn writev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - pub fn readv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - - pub fn sendmsg(fd: ::c_int, - msg: *const ::msghdr, - flags: ::c_int) -> ::ssize_t; - pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) - -> ::ssize_t; - pub fn execvpe(file: *const ::c_char, argv: *const *const ::c_char, - environment: *const *const ::c_char) -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] - pub fn getgrgid_r(uid: ::uid_t, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "sigaltstack$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")] - pub fn sigaltstack(ss: *const stack_t, - oss: *mut stack_t) -> ::c_int; - pub fn sem_close(sem: *mut sem_t) -> ::c_int; - pub fn getdtablesize() -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] - pub fn getgrnam_r(name: *const ::c_char, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_sigmask$UNIX2003")] - pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, - oldset: *mut sigset_t) -> ::c_int; - pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; - pub fn getgrnam(name: *const ::c_char) -> *mut ::group; - pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; - pub fn sem_unlink(name: *const ::c_char) -> ::c_int; - pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] - pub fn getpwnam_r(name: *const ::c_char, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] - pub fn getpwuid_r(uid: ::uid_t, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch ="x86"), - link_name = "sigwait$UNIX2003")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] - pub fn sigwait(set: *const sigset_t, - sig: *mut ::c_int) -> ::c_int; - pub fn pthread_atfork(prepare: Option, - parent: Option, - child: Option) -> ::c_int; - pub fn getgrgid(gid: ::gid_t) -> *mut ::group; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "popen$UNIX2003")] - pub fn popen(command: *const c_char, - mode: *const c_char) -> *mut ::FILE; - pub fn openpty(amaster: *mut ::c_int, - aslave: *mut ::c_int, - name: *mut ::c_char, - termp: *mut termios, - winp: *mut ::winsize) -> ::c_int; - pub fn forkpty(amaster: *mut ::c_int, - name: *mut ::c_char, - termp: *mut termios, - winp: *mut ::winsize) -> ::pid_t; - pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; -} - -cfg_if! { - if #[cfg(target_pointer_width = "64")] { - mod b64; - pub use self::b64::*; - } else { - mod b32; - pub use self::b32::*; - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,944 +0,0 @@ -//! Definitions found commonly among almost all Unix derivatives -//! -//! More functions and definitions can be found in the more specific modules -//! according to the platform in question. - -use dox::Option; - -pub type pid_t = i32; -pub type uid_t = u32; -pub type gid_t = u32; -pub type in_addr_t = u32; -pub type in_port_t = u16; -pub type sighandler_t = ::size_t; -pub type cc_t = ::c_uchar; - -pub enum DIR {} -pub enum locale_t {} - -s! { - pub struct group { - pub gr_name: *mut ::c_char, - pub gr_passwd: *mut ::c_char, - pub gr_gid: ::gid_t, - pub gr_mem: *mut *mut ::c_char, - } - - pub struct utimbuf { - pub actime: time_t, - pub modtime: time_t, - } - - pub struct timeval { - pub tv_sec: time_t, - pub tv_usec: suseconds_t, - } - - // linux x32 compatibility - // See https://sourceware.org/bugzilla/show_bug.cgi?id=16437 - pub struct timespec { - pub tv_sec: time_t, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - pub tv_nsec: i64, - #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] - pub tv_nsec: ::c_long, - } - - pub struct rlimit { - pub rlim_cur: rlim_t, - pub rlim_max: rlim_t, - } - - pub struct rusage { - pub ru_utime: timeval, - pub ru_stime: timeval, - pub ru_maxrss: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad1: u32, - pub ru_ixrss: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad2: u32, - pub ru_idrss: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad3: u32, - pub ru_isrss: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad4: u32, - pub ru_minflt: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad5: u32, - pub ru_majflt: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad6: u32, - pub ru_nswap: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad7: u32, - pub ru_inblock: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad8: u32, - pub ru_oublock: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad9: u32, - pub ru_msgsnd: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad10: u32, - pub ru_msgrcv: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad11: u32, - pub ru_nsignals: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad12: u32, - pub ru_nvcsw: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad13: u32, - pub ru_nivcsw: c_long, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - __pad14: u32, - - #[cfg(any(target_env = "musl", target_os = "emscripten"))] - __reserved: [c_long; 16], - } - - #[cfg_attr(target_os = "netbsd", repr(packed))] - pub struct in_addr { - pub s_addr: in_addr_t, - } - - pub struct in6_addr { - pub s6_addr: [u8; 16], - __align: [u32; 0], - } - - pub struct ip_mreq { - pub imr_multiaddr: in_addr, - pub imr_interface: in_addr, - } - - pub struct ipv6_mreq { - pub ipv6mr_multiaddr: in6_addr, - #[cfg(target_os = "android")] - pub ipv6mr_interface: ::c_int, - #[cfg(not(target_os = "android"))] - pub ipv6mr_interface: ::c_uint, - } - - pub struct hostent { - pub h_name: *mut ::c_char, - pub h_aliases: *mut *mut ::c_char, - pub h_addrtype: ::c_int, - pub h_length: ::c_int, - pub h_addr_list: *mut *mut ::c_char, - } - - pub struct iovec { - pub iov_base: *mut ::c_void, - pub iov_len: ::size_t, - } - - pub struct pollfd { - pub fd: ::c_int, - pub events: ::c_short, - pub revents: ::c_short, - } - - pub struct winsize { - pub ws_row: ::c_ushort, - pub ws_col: ::c_ushort, - pub ws_xpixel: ::c_ushort, - pub ws_ypixel: ::c_ushort, - } - - pub struct linger { - pub l_onoff: ::c_int, - pub l_linger: ::c_int, - } - - pub struct sigval { - // Actually a union of an int and a void* - pub sival_ptr: *mut ::c_void - } - - // - pub struct itimerval { - pub it_interval: ::timeval, - pub it_value: ::timeval, - } - - // - pub struct tms { - pub tms_utime: ::clock_t, - pub tms_stime: ::clock_t, - pub tms_cutime: ::clock_t, - pub tms_cstime: ::clock_t, - } - - pub struct servent { - pub s_name: *mut ::c_char, - pub s_aliases: *mut *mut ::c_char, - pub s_port: ::c_int, - pub s_proto: *mut ::c_char, - } - - pub struct protoent { - pub p_name: *mut ::c_char, - pub p_aliases: *mut *mut ::c_char, - pub p_proto: ::c_int, - } -} - -pub const SIG_DFL: sighandler_t = 0 as sighandler_t; -pub const SIG_IGN: sighandler_t = 1 as sighandler_t; -pub const SIG_ERR: sighandler_t = !0 as sighandler_t; - -pub const DT_FIFO: u8 = 1; -pub const DT_CHR: u8 = 2; -pub const DT_DIR: u8 = 4; -pub const DT_BLK: u8 = 6; -pub const DT_REG: u8 = 8; -pub const DT_LNK: u8 = 10; -pub const DT_SOCK: u8 = 12; - -pub const FD_CLOEXEC: ::c_int = 0x1; - -pub const USRQUOTA: ::c_int = 0; -pub const GRPQUOTA: ::c_int = 1; - -pub const SIGIOT: ::c_int = 6; - -pub const S_ISUID: ::c_int = 0x800; -pub const S_ISGID: ::c_int = 0x400; -pub const S_ISVTX: ::c_int = 0x200; - -pub const IF_NAMESIZE: ::size_t = 16; -pub const IFNAMSIZ: ::size_t = IF_NAMESIZE; - -pub const LOG_EMERG: ::c_int = 0; -pub const LOG_ALERT: ::c_int = 1; -pub const LOG_CRIT: ::c_int = 2; -pub const LOG_ERR: ::c_int = 3; -pub const LOG_WARNING: ::c_int = 4; -pub const LOG_NOTICE: ::c_int = 5; -pub const LOG_INFO: ::c_int = 6; -pub const LOG_DEBUG: ::c_int = 7; - -pub const LOG_KERN: ::c_int = 0; -pub const LOG_USER: ::c_int = 1 << 3; -pub const LOG_MAIL: ::c_int = 2 << 3; -pub const LOG_DAEMON: ::c_int = 3 << 3; -pub const LOG_AUTH: ::c_int = 4 << 3; -pub const LOG_SYSLOG: ::c_int = 5 << 3; -pub const LOG_LPR: ::c_int = 6 << 3; -pub const LOG_NEWS: ::c_int = 7 << 3; -pub const LOG_UUCP: ::c_int = 8 << 3; -pub const LOG_LOCAL0: ::c_int = 16 << 3; -pub const LOG_LOCAL1: ::c_int = 17 << 3; -pub const LOG_LOCAL2: ::c_int = 18 << 3; -pub const LOG_LOCAL3: ::c_int = 19 << 3; -pub const LOG_LOCAL4: ::c_int = 20 << 3; -pub const LOG_LOCAL5: ::c_int = 21 << 3; -pub const LOG_LOCAL6: ::c_int = 22 << 3; -pub const LOG_LOCAL7: ::c_int = 23 << 3; - -pub const LOG_PID: ::c_int = 0x01; -pub const LOG_CONS: ::c_int = 0x02; -pub const LOG_ODELAY: ::c_int = 0x04; -pub const LOG_NDELAY: ::c_int = 0x08; -pub const LOG_NOWAIT: ::c_int = 0x10; - -pub const LOG_PRIMASK: ::c_int = 7; -pub const LOG_FACMASK: ::c_int = 0x3f8; - -pub const PRIO_PROCESS: ::c_int = 0; -pub const PRIO_PGRP: ::c_int = 1; -pub const PRIO_USER: ::c_int = 2; - -pub const PRIO_MIN: ::c_int = -20; -pub const PRIO_MAX: ::c_int = 20; - -pub const IPPROTO_ICMP: ::c_int = 1; -pub const IPPROTO_ICMPV6: ::c_int = 58; -pub const IPPROTO_TCP: ::c_int = 6; -pub const IPPROTO_UDP: ::c_int = 17; -pub const IPPROTO_IP: ::c_int = 0; -pub const IPPROTO_IPV6: ::c_int = 41; - -pub const INADDR_LOOPBACK: in_addr_t = 2130706433; -pub const INADDR_ANY: in_addr_t = 0; -pub const INADDR_BROADCAST: in_addr_t = 4294967295; -pub const INADDR_NONE: in_addr_t = 4294967295; - -cfg_if! { - if #[cfg(dox)] { - // on dox builds don't pull in anything - } else if #[cfg(target_os = "l4re")] { - // required libraries for L4Re are linked externally, ATM - } else if #[cfg(feature = "use_std")] { - // cargo build, don't pull in anything extra as the libstd dep - // already pulls in all libs. - } else if #[cfg(any(all(target_env = "musl", not(target_arch = "mips"))))] { - #[link(name = "c", kind = "static", cfg(target_feature = "crt-static"))] - #[link(name = "c", cfg(not(target_feature = "crt-static")))] - extern {} - } else if #[cfg(target_os = "emscripten")] { - #[link(name = "c")] - extern {} - } else if #[cfg(all(target_os = "netbsd", target_vendor = "rumprun"))] { - // Since we don't use -nodefaultlibs on Rumprun, libc is always pulled - // in automatically by the linker. We avoid passing it explicitly, as it - // causes some versions of binutils to crash with an assertion failure. - #[link(name = "m")] - extern {} - } else if #[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "android", - target_os = "openbsd", - target_os = "bitrig"))] { - #[link(name = "c")] - #[link(name = "m")] - extern {} - } else if #[cfg(target_os = "haiku")] { - #[link(name = "root")] - #[link(name = "network")] - extern {} - } else if #[cfg(target_os = "fuchsia")] { - #[link(name = "c")] - #[link(name = "fdio")] - extern {} - } else if #[cfg(target_env = "newlib")] { - #[link(name = "c")] - #[link(name = "m")] - extern {} - } else { - #[link(name = "c")] - #[link(name = "m")] - #[link(name = "rt")] - #[link(name = "pthread")] - extern {} - } -} - -extern { - #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam50")] - pub fn getpwnam(name: *const ::c_char) -> *mut passwd; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid50")] - pub fn getpwuid(uid: ::uid_t) -> *mut passwd; - - pub fn fprintf(stream: *mut ::FILE, - format: *const ::c_char, ...) -> ::c_int; - pub fn printf(format: *const ::c_char, ...) -> ::c_int; - pub fn snprintf(s: *mut ::c_char, n: ::size_t, - format: *const ::c_char, ...) -> ::c_int; - pub fn sprintf(s: *mut ::c_char, format: *const ::c_char, ...) -> ::c_int; - pub fn fscanf(stream: *mut ::FILE, format: *const ::c_char, ...) -> ::c_int; - pub fn scanf(format: *const ::c_char, ...) -> ::c_int; - pub fn sscanf(s: *const ::c_char, format: *const ::c_char, ...) -> ::c_int; - pub fn getchar_unlocked() -> ::c_int; - pub fn putchar_unlocked(c: ::c_int) -> ::c_int; - - #[cfg_attr(target_os = "netbsd", link_name = "__socket30")] - pub fn socket(domain: ::c_int, ty: ::c_int, protocol: ::c_int) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "connect$UNIX2003")] - pub fn connect(socket: ::c_int, address: *const sockaddr, - len: socklen_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "listen$UNIX2003")] - pub fn listen(socket: ::c_int, backlog: ::c_int) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "accept$UNIX2003")] - pub fn accept(socket: ::c_int, address: *mut sockaddr, - address_len: *mut socklen_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "getpeername$UNIX2003")] - pub fn getpeername(socket: ::c_int, address: *mut sockaddr, - address_len: *mut socklen_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "getsockname$UNIX2003")] - pub fn getsockname(socket: ::c_int, address: *mut sockaddr, - address_len: *mut socklen_t) -> ::c_int; - pub fn setsockopt(socket: ::c_int, level: ::c_int, name: ::c_int, - value: *const ::c_void, - option_len: socklen_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "socketpair$UNIX2003")] - pub fn socketpair(domain: ::c_int, type_: ::c_int, protocol: ::c_int, - socket_vector: *mut ::c_int) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "sendto$UNIX2003")] - pub fn sendto(socket: ::c_int, buf: *const ::c_void, len: ::size_t, - flags: ::c_int, addr: *const sockaddr, - addrlen: socklen_t) -> ::ssize_t; - pub fn shutdown(socket: ::c_int, how: ::c_int) -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "chmod$UNIX2003")] - pub fn chmod(path: *const c_char, mode: mode_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "fchmod$UNIX2003")] - pub fn fchmod(fd: ::c_int, mode: mode_t) -> ::c_int; - - #[cfg_attr(target_os = "macos", link_name = "fstat$INODE64")] - #[cfg_attr(target_os = "netbsd", link_name = "__fstat50")] - pub fn fstat(fildes: ::c_int, buf: *mut stat) -> ::c_int; - - pub fn mkdir(path: *const c_char, mode: mode_t) -> ::c_int; - - #[cfg_attr(target_os = "macos", link_name = "stat$INODE64")] - #[cfg_attr(target_os = "netbsd", link_name = "__stat50")] - pub fn stat(path: *const c_char, buf: *mut stat) -> ::c_int; - - pub fn pclose(stream: *mut ::FILE) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "fdopen$UNIX2003")] - pub fn fdopen(fd: ::c_int, mode: *const c_char) -> *mut ::FILE; - pub fn fileno(stream: *mut ::FILE) -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "open$UNIX2003")] - pub fn open(path: *const c_char, oflag: ::c_int, ...) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "creat$UNIX2003")] - pub fn creat(path: *const c_char, mode: mode_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "fcntl$UNIX2003")] - pub fn fcntl(fd: ::c_int, cmd: ::c_int, ...) -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), - link_name = "opendir$INODE64")] - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "opendir$INODE64$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__opendir30")] - pub fn opendir(dirname: *const c_char) -> *mut ::DIR; - #[cfg_attr(target_os = "macos", link_name = "readdir$INODE64")] - #[cfg_attr(target_os = "netbsd", link_name = "__readdir30")] - pub fn readdir(dirp: *mut ::DIR) -> *mut ::dirent; - #[cfg_attr(target_os = "macos", link_name = "readdir_r$INODE64")] - #[cfg_attr(target_os = "netbsd", link_name = "__readdir_r30")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_readdir_r")] - pub fn readdir_r(dirp: *mut ::DIR, entry: *mut ::dirent, - result: *mut *mut ::dirent) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "closedir$UNIX2003")] - pub fn closedir(dirp: *mut ::DIR) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), - link_name = "rewinddir$INODE64")] - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "rewinddir$INODE64$UNIX2003")] - pub fn rewinddir(dirp: *mut ::DIR); - - pub fn openat(dirfd: ::c_int, pathname: *const ::c_char, - flags: ::c_int, ...) -> ::c_int; - pub fn fchmodat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t, flags: ::c_int) -> ::c_int; - pub fn fchown(fd: ::c_int, - owner: ::uid_t, - group: ::gid_t) -> ::c_int; - pub fn fchownat(dirfd: ::c_int, pathname: *const ::c_char, - owner: ::uid_t, group: ::gid_t, - flags: ::c_int) -> ::c_int; - #[cfg_attr(target_os = "macos", link_name = "fstatat$INODE64")] - pub fn fstatat(dirfd: ::c_int, pathname: *const ::c_char, - buf: *mut stat, flags: ::c_int) -> ::c_int; - pub fn linkat(olddirfd: ::c_int, oldpath: *const ::c_char, - newdirfd: ::c_int, newpath: *const ::c_char, - flags: ::c_int) -> ::c_int; - pub fn mkdirat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t) -> ::c_int; - pub fn readlinkat(dirfd: ::c_int, pathname: *const ::c_char, - buf: *mut ::c_char, bufsiz: ::size_t) -> ::ssize_t; - pub fn renameat(olddirfd: ::c_int, oldpath: *const ::c_char, - newdirfd: ::c_int, newpath: *const ::c_char) - -> ::c_int; - pub fn symlinkat(target: *const ::c_char, newdirfd: ::c_int, - linkpath: *const ::c_char) -> ::c_int; - pub fn unlinkat(dirfd: ::c_int, pathname: *const ::c_char, - flags: ::c_int) -> ::c_int; - - pub fn access(path: *const c_char, amode: ::c_int) -> ::c_int; - pub fn alarm(seconds: ::c_uint) -> ::c_uint; - pub fn chdir(dir: *const c_char) -> ::c_int; - pub fn fchdir(dirfd: ::c_int) -> ::c_int; - pub fn chown(path: *const c_char, uid: uid_t, - gid: gid_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "lchown$UNIX2003")] - pub fn lchown(path: *const c_char, uid: uid_t, - gid: gid_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "close$NOCANCEL$UNIX2003")] - #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), - link_name = "close$NOCANCEL")] - pub fn close(fd: ::c_int) -> ::c_int; - pub fn dup(fd: ::c_int) -> ::c_int; - pub fn dup2(src: ::c_int, dst: ::c_int) -> ::c_int; - pub fn execl(path: *const c_char, - arg0: *const c_char, ...) -> ::c_int; - pub fn execle(path: *const ::c_char, - arg0: *const ::c_char, ...) -> ::c_int; - pub fn execlp(file: *const ::c_char, - arg0: *const ::c_char, ...) -> ::c_int; - pub fn execv(prog: *const c_char, - argv: *const *const c_char) -> ::c_int; - pub fn execve(prog: *const c_char, argv: *const *const c_char, - envp: *const *const c_char) - -> ::c_int; - pub fn execvp(c: *const c_char, - argv: *const *const c_char) -> ::c_int; - pub fn fork() -> pid_t; - pub fn fpathconf(filedes: ::c_int, name: ::c_int) -> c_long; - pub fn getcwd(buf: *mut c_char, size: ::size_t) -> *mut c_char; - pub fn getegid() -> gid_t; - pub fn geteuid() -> uid_t; - pub fn getgid() -> gid_t; - pub fn getgroups(ngroups_max: ::c_int, groups: *mut gid_t) - -> ::c_int; - pub fn getlogin() -> *mut c_char; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "getopt$UNIX2003")] - pub fn getopt(argc: ::c_int, argv: *const *mut c_char, - optstr: *const c_char) -> ::c_int; - pub fn getpgid(pid: pid_t) -> pid_t; - pub fn getpgrp() -> pid_t; - pub fn getpid() -> pid_t; - pub fn getppid() -> pid_t; - pub fn getuid() -> uid_t; - pub fn isatty(fd: ::c_int) -> ::c_int; - pub fn link(src: *const c_char, dst: *const c_char) -> ::c_int; - pub fn lseek(fd: ::c_int, offset: off_t, whence: ::c_int) -> off_t; - pub fn pathconf(path: *const c_char, name: ::c_int) -> c_long; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pause$UNIX2003")] - pub fn pause() -> ::c_int; - pub fn pipe(fds: *mut ::c_int) -> ::c_int; - pub fn posix_memalign(memptr: *mut *mut ::c_void, - align: ::size_t, - size: ::size_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "read$UNIX2003")] - pub fn read(fd: ::c_int, buf: *mut ::c_void, count: ::size_t) - -> ::ssize_t; - pub fn rmdir(path: *const c_char) -> ::c_int; - pub fn seteuid(uid: uid_t) -> ::c_int; - pub fn setgid(gid: gid_t) -> ::c_int; - pub fn setpgid(pid: pid_t, pgid: pid_t) -> ::c_int; - pub fn setsid() -> pid_t; - pub fn setuid(uid: uid_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "sleep$UNIX2003")] - pub fn sleep(secs: ::c_uint) -> ::c_uint; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "nanosleep$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__nanosleep50")] - pub fn nanosleep(rqtp: *const timespec, - rmtp: *mut timespec) -> ::c_int; - pub fn tcgetpgrp(fd: ::c_int) -> pid_t; - pub fn tcsetpgrp(fd: ::c_int, pgrp: ::pid_t) -> ::c_int; - pub fn ttyname(fd: ::c_int) -> *mut c_char; - pub fn unlink(c: *const c_char) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "wait$UNIX2003")] - pub fn wait(status: *mut ::c_int) -> pid_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "waitpid$UNIX2003")] - pub fn waitpid(pid: pid_t, status: *mut ::c_int, options: ::c_int) - -> pid_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "write$UNIX2003")] - pub fn write(fd: ::c_int, buf: *const ::c_void, count: ::size_t) - -> ::ssize_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pread$UNIX2003")] - pub fn pread(fd: ::c_int, buf: *mut ::c_void, count: ::size_t, - offset: off_t) -> ::ssize_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pwrite$UNIX2003")] - pub fn pwrite(fd: ::c_int, buf: *const ::c_void, count: ::size_t, - offset: off_t) -> ::ssize_t; - pub fn umask(mask: mode_t) -> mode_t; - - #[cfg_attr(target_os = "netbsd", link_name = "__utime50")] - pub fn utime(file: *const c_char, buf: *const utimbuf) -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "kill$UNIX2003")] - pub fn kill(pid: pid_t, sig: ::c_int) -> ::c_int; - - pub fn mlock(addr: *const ::c_void, len: ::size_t) -> ::c_int; - pub fn munlock(addr: *const ::c_void, len: ::size_t) -> ::c_int; - pub fn mlockall(flags: ::c_int) -> ::c_int; - pub fn munlockall() -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "mmap$UNIX2003")] - pub fn mmap(addr: *mut ::c_void, - len: ::size_t, - prot: ::c_int, - flags: ::c_int, - fd: ::c_int, - offset: off_t) - -> *mut ::c_void; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "munmap$UNIX2003")] - pub fn munmap(addr: *mut ::c_void, len: ::size_t) -> ::c_int; - - pub fn if_nametoindex(ifname: *const c_char) -> ::c_uint; - pub fn if_indextoname(ifindex: ::c_uint, - ifname: *mut ::c_char) -> *mut ::c_char; - - #[cfg_attr(target_os = "macos", link_name = "lstat$INODE64")] - #[cfg_attr(target_os = "netbsd", link_name = "__lstat50")] - pub fn lstat(path: *const c_char, buf: *mut stat) -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "fsync$UNIX2003")] - pub fn fsync(fd: ::c_int) -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "setenv$UNIX2003")] - pub fn setenv(name: *const c_char, val: *const c_char, - overwrite: ::c_int) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "unsetenv$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__unsetenv13")] - pub fn unsetenv(name: *const c_char) -> ::c_int; - - pub fn symlink(path1: *const c_char, - path2: *const c_char) -> ::c_int; - - pub fn ftruncate(fd: ::c_int, length: off_t) -> ::c_int; - - pub fn signal(signum: ::c_int, handler: sighandler_t) -> sighandler_t; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "getrlimit$UNIX2003")] - pub fn getrlimit(resource: ::c_int, rlim: *mut rlimit) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "setrlimit$UNIX2003")] - pub fn setrlimit(resource: ::c_int, rlim: *const rlimit) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getrusage50")] - pub fn getrusage(resource: ::c_int, usage: *mut rusage) -> ::c_int; - - #[cfg_attr(any(target_os = "macos", target_os = "ios"), - link_name = "realpath$DARWIN_EXTSN")] - pub fn realpath(pathname: *const ::c_char, resolved: *mut ::c_char) - -> *mut ::c_char; - - pub fn flock(fd: ::c_int, operation: ::c_int) -> ::c_int; - - #[cfg_attr(target_os = "netbsd", link_name = "__gettimeofday50")] - pub fn gettimeofday(tp: *mut ::timeval, - tz: *mut ::c_void) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__times13")] - pub fn times(buf: *mut ::tms) -> ::clock_t; - - pub fn pthread_self() -> ::pthread_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_join$UNIX2003")] - pub fn pthread_join(native: ::pthread_t, - value: *mut *mut ::c_void) -> ::c_int; - pub fn pthread_exit(value: *mut ::c_void); - pub fn pthread_attr_init(attr: *mut ::pthread_attr_t) -> ::c_int; - pub fn pthread_attr_destroy(attr: *mut ::pthread_attr_t) -> ::c_int; - pub fn pthread_attr_setstacksize(attr: *mut ::pthread_attr_t, - stack_size: ::size_t) -> ::c_int; - pub fn pthread_attr_setdetachstate(attr: *mut ::pthread_attr_t, - state: ::c_int) -> ::c_int; - pub fn pthread_detach(thread: ::pthread_t) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__libc_thr_yield")] - pub fn sched_yield() -> ::c_int; - pub fn pthread_key_create(key: *mut pthread_key_t, - dtor: Option) - -> ::c_int; - pub fn pthread_key_delete(key: pthread_key_t) -> ::c_int; - pub fn pthread_getspecific(key: pthread_key_t) -> *mut ::c_void; - pub fn pthread_setspecific(key: pthread_key_t, value: *const ::c_void) - -> ::c_int; - pub fn pthread_mutex_init(lock: *mut pthread_mutex_t, - attr: *const pthread_mutexattr_t) -> ::c_int; - pub fn pthread_mutex_destroy(lock: *mut pthread_mutex_t) -> ::c_int; - pub fn pthread_mutex_lock(lock: *mut pthread_mutex_t) -> ::c_int; - pub fn pthread_mutex_trylock(lock: *mut pthread_mutex_t) -> ::c_int; - pub fn pthread_mutex_unlock(lock: *mut pthread_mutex_t) -> ::c_int; - - pub fn pthread_mutexattr_init(attr: *mut pthread_mutexattr_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_mutexattr_destroy$UNIX2003")] - pub fn pthread_mutexattr_destroy(attr: *mut pthread_mutexattr_t) -> ::c_int; - pub fn pthread_mutexattr_settype(attr: *mut pthread_mutexattr_t, - _type: ::c_int) -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_cond_init$UNIX2003")] - pub fn pthread_cond_init(cond: *mut pthread_cond_t, - attr: *const pthread_condattr_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_cond_wait$UNIX2003")] - pub fn pthread_cond_wait(cond: *mut pthread_cond_t, - lock: *mut pthread_mutex_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_cond_timedwait$UNIX2003")] - pub fn pthread_cond_timedwait(cond: *mut pthread_cond_t, - lock: *mut pthread_mutex_t, - abstime: *const ::timespec) -> ::c_int; - pub fn pthread_cond_signal(cond: *mut pthread_cond_t) -> ::c_int; - pub fn pthread_cond_broadcast(cond: *mut pthread_cond_t) -> ::c_int; - pub fn pthread_cond_destroy(cond: *mut pthread_cond_t) -> ::c_int; - pub fn pthread_condattr_init(attr: *mut pthread_condattr_t) -> ::c_int; - pub fn pthread_condattr_destroy(attr: *mut pthread_condattr_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_rwlock_init$UNIX2003")] - pub fn pthread_rwlock_init(lock: *mut pthread_rwlock_t, - attr: *const pthread_rwlockattr_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_rwlock_destroy$UNIX2003")] - pub fn pthread_rwlock_destroy(lock: *mut pthread_rwlock_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_rwlock_rdlock$UNIX2003")] - pub fn pthread_rwlock_rdlock(lock: *mut pthread_rwlock_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_rwlock_tryrdlock$UNIX2003")] - pub fn pthread_rwlock_tryrdlock(lock: *mut pthread_rwlock_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_rwlock_wrlock$UNIX2003")] - pub fn pthread_rwlock_wrlock(lock: *mut pthread_rwlock_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_rwlock_trywrlock$UNIX2003")] - pub fn pthread_rwlock_trywrlock(lock: *mut pthread_rwlock_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_rwlock_unlock$UNIX2003")] - pub fn pthread_rwlock_unlock(lock: *mut pthread_rwlock_t) -> ::c_int; - pub fn pthread_rwlockattr_init(attr: *mut pthread_rwlockattr_t) -> ::c_int; - pub fn pthread_rwlockattr_destroy(attr: *mut pthread_rwlockattr_t) - -> ::c_int; - #[cfg_attr(all(target_os = "linux", not(target_env = "musl")), - link_name = "__xpg_strerror_r")] - pub fn strerror_r(errnum: ::c_int, buf: *mut c_char, - buflen: ::size_t) -> ::c_int; - - pub fn getsockopt(sockfd: ::c_int, - level: ::c_int, - optname: ::c_int, - optval: *mut ::c_void, - optlen: *mut ::socklen_t) -> ::c_int; - pub fn raise(signum: ::c_int) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__sigaction14")] - pub fn sigaction(signum: ::c_int, - act: *const sigaction, - oldact: *mut sigaction) -> ::c_int; - - #[cfg_attr(target_os = "netbsd", link_name = "__utimes50")] - pub fn utimes(filename: *const ::c_char, - times: *const ::timeval) -> ::c_int; - pub fn dlopen(filename: *const ::c_char, - flag: ::c_int) -> *mut ::c_void; - pub fn dlerror() -> *mut ::c_char; - pub fn dlsym(handle: *mut ::c_void, - symbol: *const ::c_char) -> *mut ::c_void; - pub fn dlclose(handle: *mut ::c_void) -> ::c_int; - pub fn dladdr(addr: *const ::c_void, info: *mut Dl_info) -> ::c_int; - - pub fn getaddrinfo(node: *const c_char, - service: *const c_char, - hints: *const addrinfo, - res: *mut *mut addrinfo) -> ::c_int; - pub fn freeaddrinfo(res: *mut addrinfo); - pub fn gai_strerror(errcode: ::c_int) -> *const ::c_char; - #[cfg_attr(any( - all(target_os = "linux", not(target_env = "musl")), - target_os = "freebsd", - target_os = "dragonfly", - target_os = "haiku"), - link_name = "__res_init")] - #[cfg_attr(any(target_os = "macos", target_os = "ios"), - link_name = "res_9_init")] - pub fn res_init() -> ::c_int; - - #[cfg_attr(target_os = "netbsd", link_name = "__gmtime_r50")] - pub fn gmtime_r(time_p: *const time_t, result: *mut tm) -> *mut tm; - #[cfg_attr(target_os = "netbsd", link_name = "__localtime_r50")] - pub fn localtime_r(time_p: *const time_t, result: *mut tm) -> *mut tm; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "mktime$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__mktime50")] - pub fn mktime(tm: *mut tm) -> time_t; - #[cfg_attr(target_os = "netbsd", link_name = "__time50")] - pub fn time(time: *mut time_t) -> time_t; - #[cfg_attr(target_os = "netbsd", link_name = "__gmtime50")] - pub fn gmtime(time_p: *const time_t) -> *mut tm; - #[cfg_attr(target_os = "netbsd", link_name = "__locatime50")] - pub fn localtime(time_p: *const time_t) -> *mut tm; - #[cfg_attr(target_os = "netbsd", link_name = "__difftime50")] - pub fn difftime(time1: time_t, time0: time_t) -> ::c_double; - - #[cfg_attr(target_os = "netbsd", link_name = "__mknod50")] - pub fn mknod(pathname: *const ::c_char, mode: ::mode_t, - dev: ::dev_t) -> ::c_int; - pub fn uname(buf: *mut ::utsname) -> ::c_int; - pub fn gethostname(name: *mut ::c_char, len: ::size_t) -> ::c_int; - pub fn getservbyname(name: *const ::c_char, - proto: *const ::c_char) -> *mut servent; - pub fn getprotobyname(name: *const ::c_char) -> *mut protoent; - pub fn getprotobynumber(proto: ::c_int) -> *mut protoent; - pub fn chroot(name: *const ::c_char) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "usleep$UNIX2003")] - pub fn usleep(secs: ::c_uint) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "send$UNIX2003")] - pub fn send(socket: ::c_int, buf: *const ::c_void, len: ::size_t, - flags: ::c_int) -> ::ssize_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "recv$UNIX2003")] - pub fn recv(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, - flags: ::c_int) -> ::ssize_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "putenv$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__putenv50")] - pub fn putenv(string: *mut c_char) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "poll$UNIX2003")] - pub fn poll(fds: *mut pollfd, nfds: nfds_t, timeout: ::c_int) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), - link_name = "select$1050")] - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "select$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__select50")] - pub fn select(nfds: ::c_int, - readfs: *mut fd_set, - writefds: *mut fd_set, - errorfds: *mut fd_set, - timeout: *mut timeval) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__setlocale50")] - pub fn setlocale(category: ::c_int, - locale: *const ::c_char) -> *mut ::c_char; - pub fn localeconv() -> *mut lconv; - - pub fn sem_destroy(sem: *mut sem_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "sem_wait$UNIX2003")] - pub fn sem_wait(sem: *mut sem_t) -> ::c_int; - pub fn sem_trywait(sem: *mut sem_t) -> ::c_int; - pub fn sem_post(sem: *mut sem_t) -> ::c_int; - pub fn sem_init(sem: *mut sem_t, - pshared: ::c_int, - value: ::c_uint) - -> ::c_int; - pub fn statvfs(path: *const c_char, buf: *mut statvfs) -> ::c_int; - pub fn fstatvfs(fd: ::c_int, buf: *mut statvfs) -> ::c_int; - - pub fn readlink(path: *const c_char, - buf: *mut c_char, - bufsz: ::size_t) - -> ::ssize_t; - - #[cfg_attr(target_os = "netbsd", link_name = "__sigemptyset14")] - pub fn sigemptyset(set: *mut sigset_t) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__sigaddset14")] - pub fn sigaddset(set: *mut sigset_t, signum: ::c_int) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__sigfillset14")] - pub fn sigfillset(set: *mut sigset_t) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__sigdelset14")] - pub fn sigdelset(set: *mut sigset_t, signum: ::c_int) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__sigismember14")] - pub fn sigismember(set: *const sigset_t, signum: ::c_int) -> ::c_int; - - #[cfg_attr(target_os = "netbsd", link_name = "__sigprocmask14")] - pub fn sigprocmask(how: ::c_int, - set: *const sigset_t, - oldset: *mut sigset_t) - -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__sigpending14")] - pub fn sigpending(set: *mut sigset_t) -> ::c_int; - - #[cfg_attr(target_os = "netbsd", link_name = "__timegm50")] - pub fn timegm(tm: *mut ::tm) -> time_t; - - pub fn getsid(pid: pid_t) -> pid_t; - - pub fn sysconf(name: ::c_int) -> ::c_long; - - pub fn mkfifo(path: *const c_char, mode: mode_t) -> ::c_int; - - #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), - link_name = "pselect$1050")] - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pselect$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__pselect50")] - pub fn pselect(nfds: ::c_int, - readfs: *mut fd_set, - writefds: *mut fd_set, - errorfds: *mut fd_set, - timeout: *const timespec, - sigmask: *const sigset_t) -> ::c_int; - pub fn fseeko(stream: *mut ::FILE, - offset: ::off_t, - whence: ::c_int) -> ::c_int; - pub fn ftello(stream: *mut ::FILE) -> ::off_t; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "tcdrain$UNIX2003")] - pub fn tcdrain(fd: ::c_int) -> ::c_int; - pub fn cfgetispeed(termios: *const ::termios) -> ::speed_t; - pub fn cfgetospeed(termios: *const ::termios) -> ::speed_t; - pub fn cfmakeraw(termios: *mut ::termios); - pub fn cfsetispeed(termios: *mut ::termios, speed: ::speed_t) -> ::c_int; - pub fn cfsetospeed(termios: *mut ::termios, speed: ::speed_t) -> ::c_int; - pub fn cfsetspeed(termios: *mut ::termios, speed: ::speed_t) -> ::c_int; - pub fn tcgetattr(fd: ::c_int, termios: *mut ::termios) -> ::c_int; - pub fn tcsetattr(fd: ::c_int, - optional_actions: ::c_int, - termios: *const ::termios) -> ::c_int; - pub fn tcflow(fd: ::c_int, action: ::c_int) -> ::c_int; - pub fn tcflush(fd: ::c_int, action: ::c_int) -> ::c_int; - pub fn tcgetsid(fd: ::c_int) -> ::pid_t; - pub fn tcsendbreak(fd: ::c_int, duration: ::c_int) -> ::c_int; - pub fn mkstemp(template: *mut ::c_char) -> ::c_int; - pub fn mkdtemp(template: *mut ::c_char) -> *mut ::c_char; - - pub fn tmpnam(ptr: *mut ::c_char) -> *mut ::c_char; - - pub fn openlog(ident: *const ::c_char, logopt: ::c_int, facility: ::c_int); - pub fn closelog(); - pub fn setlogmask(maskpri: ::c_int) -> ::c_int; - pub fn syslog(priority: ::c_int, message: *const ::c_char, ...); - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "nice$UNIX2003")] - pub fn nice(incr: ::c_int) -> ::c_int; - - pub fn grantpt(fd: ::c_int) -> ::c_int; - pub fn posix_openpt(flags: ::c_int) -> ::c_int; - pub fn ptsname(fd: ::c_int) -> *mut ::c_char; - pub fn unlockpt(fd: ::c_int) -> ::c_int; -} - -cfg_if! { - if #[cfg(target_env = "uclibc")] { - mod uclibc; - pub use self::uclibc::*; - } else if #[cfg(target_env = "newlib")] { - mod newlib; - pub use self::newlib::*; - } else if #[cfg(any(target_os = "linux", - target_os = "android", - target_os = "emscripten", - target_os = "fuchsia"))] { - mod notbsd; - pub use self::notbsd::*; - } else if #[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "freebsd", - target_os = "dragonfly", - target_os = "openbsd", - target_os = "netbsd", - target_os = "bitrig"))] { - mod bsd; - pub use self::bsd::*; - } else if #[cfg(target_os = "solaris")] { - mod solaris; - pub use self::solaris::*; - } else if #[cfg(target_os = "haiku")] { - mod haiku; - pub use self::haiku::*; - } else { - // Unknown target_os - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/newlib/aarch64/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/newlib/aarch64/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/newlib/aarch64/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/newlib/aarch64/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -pub type c_char = u8; -pub type wchar_t = u32; - -pub type c_long = i64; -pub type c_ulong = u64; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/newlib/arm/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/newlib/arm/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/newlib/arm/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/newlib/arm/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -pub type c_char = u8; -pub type wchar_t = u32; - -pub type c_long = i32; -pub type c_ulong = u32; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/newlib/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/newlib/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/newlib/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/newlib/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,690 +0,0 @@ -use dox::mem; - -pub type blkcnt_t = i32; -pub type blksize_t = i32; -pub type clock_t = i32; -pub type clockid_t = ::c_ulong; -pub type dev_t = u32; -pub type fsblkcnt_t = u64; -pub type fsfilcnt_t = u32; -pub type id_t = u32; -pub type ino_t = u32; -pub type key_t = ::c_int; -pub type loff_t = ::c_longlong; -pub type mode_t = ::c_uint; -pub type nfds_t = u32; -pub type nlink_t = ::c_ushort; -pub type off_t = i64; -pub type pthread_t = ::c_ulong; -pub type pthread_key_t = ::c_uint; -pub type rlim_t = u32; -pub type sa_family_t = u8; -pub type socklen_t = u32; -pub type speed_t = u32; -pub type suseconds_t = i32; -pub type tcflag_t = ::c_uint; -pub type time_t = i32; -pub type useconds_t = u32; - -s! { - pub struct sockaddr { - pub sa_family: sa_family_t, - pub sa_data: [::c_char; 14], - } - - pub struct sockaddr_in { - pub sin_family: sa_family_t, - pub sin_port: ::in_port_t, - pub sin_addr: ::in_addr, - pub sin_zero: [u8; 8], - } - - pub struct sockaddr_in6 { // Unverified - pub sin6_family: sa_family_t, - pub sin6_port: ::in_port_t, - pub sin6_flowinfo: u32, - pub sin6_addr: ::in6_addr, - pub sin6_scope_id: u32, - } - - pub struct sockaddr_storage { - pub ss_family: sa_family_t, - pub __ss_padding: [u8; 26], - } - - pub struct addrinfo { - pub ai_flags: ::c_int, - pub ai_family: ::c_int, - pub ai_socktype: ::c_int, - pub ai_protocol: ::c_int, - pub ai_addrlen: socklen_t, - pub ai_canonname: *mut ::c_char, - pub ai_addr: *mut sockaddr, - pub ai_next: *mut addrinfo, - } - - pub struct ip_mreq { - pub imr_multiaddr: in_addr, - pub imr_interface: in_addr, - } - - pub struct linger { - pub l_onoff: ::c_int, - pub l_linger: ::c_int, - } - - pub struct in_addr { - pub s_addr: ::in_addr_t, - } - - pub struct hostent { - pub h_name: *mut ::c_char, - pub h_aliases: *mut *mut ::c_char, - pub h_addrtype: ::c_int, - pub h_length: ::c_int, - pub h_addr_list: *mut *mut ::c_char, - pub h_addr: *mut ::c_char, - } - - pub struct pollfd { - pub fd: ::c_int, - pub events: ::c_int, - pub revents: ::c_int, - } - - pub struct lconv { - pub decimal_point: *mut ::c_char, - pub thousands_sep: *mut ::c_char, - pub grouping: *mut ::c_char, - pub int_curr_symbol: *mut ::c_char, - pub currency_symbol: *mut ::c_char, - pub mon_decimal_point: *mut ::c_char, - pub mon_thousands_sep: *mut ::c_char, - pub mon_grouping: *mut ::c_char, - pub positive_sign: *mut ::c_char, - pub negative_sign: *mut ::c_char, - pub int_frac_digits: ::c_char, - pub frac_digits: ::c_char, - pub p_cs_precedes: ::c_char, - pub p_sep_by_space: ::c_char, - pub n_cs_precedes: ::c_char, - pub n_sep_by_space: ::c_char, - pub p_sign_posn: ::c_char, - pub n_sign_posn: ::c_char, - pub int_n_cs_precedes: ::c_char, - pub int_n_sep_by_space: ::c_char, - pub int_n_sign_posn: ::c_char, - pub int_p_cs_precedes: ::c_char, - pub int_p_sep_by_space: ::c_char, - pub int_p_sign_posn: ::c_char, - } - - pub struct tm { - pub tm_sec: ::c_int, - pub tm_min: ::c_int, - pub tm_hour: ::c_int, - pub tm_mday: ::c_int, - pub tm_mon: ::c_int, - pub tm_year: ::c_int, - pub tm_wday: ::c_int, - pub tm_yday: ::c_int, - pub tm_isdst: ::c_int, - } - - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: dev_t, - pub st_size: off_t, - pub st_atime: time_t, - pub st_spare1: ::c_long, - pub st_mtime: time_t, - pub st_spare2: ::c_long, - pub st_ctime: time_t, - pub st_spare3: ::c_long, - pub st_blksize: blksize_t, - pub st_blocks: blkcnt_t, - pub st_spare4: [::c_long; 2usize], - } - - pub struct statvfs { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: fsblkcnt_t, - pub f_bfree: fsblkcnt_t, - pub f_bavail: fsblkcnt_t, - pub f_files: fsfilcnt_t, - pub f_ffree: fsfilcnt_t, - pub f_favail: fsfilcnt_t, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - } - - pub struct sigset_t { - __val: [::c_ulong; 16], - } - - pub struct sigaction { - pub sa_handler: extern fn(arg1: ::c_int), - pub sa_mask: sigset_t, - pub sa_flags: ::c_int, - } - - pub struct dirent { - pub d_ino: ino_t, - pub d_type: ::c_uchar, - pub d_name: [::c_char; 256usize], - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_flags: ::c_int, - pub ss_size: usize, - } - - pub struct fd_set { // Unverified - fds_bits: [::c_ulong; FD_SETSIZE / ULONG_SIZE], - } - - pub struct passwd { // Unverified - pub pw_name: *mut ::c_char, - pub pw_passwd: *mut ::c_char, - pub pw_uid: ::uid_t, - pub pw_gid: ::gid_t, - pub pw_gecos: *mut ::c_char, - pub pw_dir: *mut ::c_char, - pub pw_shell: *mut ::c_char, - } - - pub struct termios { // Unverified - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; ::NCCS], - } - - pub struct sem_t { // Unverified - __size: [::c_char; 16], - } - - pub struct Dl_info { // Unverified - pub dli_fname: *const ::c_char, - pub dli_fbase: *mut ::c_void, - pub dli_sname: *const ::c_char, - pub dli_saddr: *mut ::c_void, - } - - pub struct utsname { // Unverified - pub sysname: [::c_char; 65], - pub nodename: [::c_char; 65], - pub release: [::c_char; 65], - pub version: [::c_char; 65], - pub machine: [::c_char; 65], - pub domainname: [::c_char; 65] - } - - pub struct cpu_set_t { // Unverified - bits: [u32; 32], - } - - pub struct pthread_attr_t { // Unverified - __size: [u64; 7] - } - - pub struct pthread_mutex_t { // Unverified - #[cfg(any(target_arch = "mips", target_arch = "arm", - target_arch = "powerpc"))] - __align: [::c_long; 0], - #[cfg(not(any(target_arch = "mips", target_arch = "arm", - target_arch = "powerpc")))] - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_MUTEX_T], - } - - pub struct pthread_rwlock_t { // Unverified - #[cfg(any(target_arch = "mips", target_arch = "arm", - target_arch = "powerpc"))] - __align: [::c_long; 0], - #[cfg(not(any(target_arch = "mips", target_arch = "arm", - target_arch = "powerpc")))] - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_RWLOCK_T], - } - - pub struct pthread_mutexattr_t { // Unverified - #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", - target_arch = "mips64", target_arch = "s390x", - target_arch = "sparc64"))] - __align: [::c_int; 0], - #[cfg(not(any(target_arch = "x86_64", target_arch = "powerpc64", - target_arch = "mips64", target_arch = "s390x", - target_arch = "sparc64")))] - __align: [::c_long; 0], - size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T], - } - - pub struct pthread_rwlockattr_t { // Unverified - __lockkind: ::c_int, - __pshared: ::c_int, - } - - pub struct pthread_cond_t { // Unverified - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_COND_T], - } - - pub struct pthread_condattr_t { // Unverified - __align: [::c_int; 0], - size: [u8; __SIZEOF_PTHREAD_CONDATTR_T], - } - -} - -// unverified constants -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_MUTEX_T], -}; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_COND_T], -}; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_RWLOCK_T], -}; -pub const NCCS: usize = 32; -pub const __SIZEOF_PTHREAD_ATTR_T: usize = 56; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_COND_T: usize = 48; -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; -pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; -pub const __SIZEOF_PTHREAD_BARRIER_T: usize = 32; -pub const __SIZEOF_PTHREAD_BARRIERATTR_T: usize = 4; -pub const __PTHREAD_MUTEX_HAVE_PREV: usize = 1; -pub const __PTHREAD_RWLOCK_INT_FLAGS_SHARED: usize = 1; -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; -pub const FD_SETSIZE: usize = 1024; -// intentionally not public, only used for fd_set -const ULONG_SIZE: usize = 32; - -// Other constants -pub const EPERM: ::c_int = 1; -pub const ENOENT: ::c_int = 2; -pub const ESRCH: ::c_int = 3; -pub const EINTR: ::c_int = 4; -pub const EIO: ::c_int = 5; -pub const ENXIO: ::c_int = 6; -pub const E2BIG: ::c_int = 7; -pub const ENOEXEC: ::c_int = 8; -pub const EBADF: ::c_int = 9; -pub const ECHILD: ::c_int = 10; -pub const EAGAIN: ::c_int = 11; -pub const ENOMEM: ::c_int = 12; -pub const EACCES: ::c_int = 13; -pub const EFAULT: ::c_int = 14; -pub const EBUSY: ::c_int = 16; -pub const EEXIST: ::c_int = 17; -pub const EXDEV: ::c_int = 18; -pub const ENODEV: ::c_int = 19; -pub const ENOTDIR: ::c_int = 20; -pub const EISDIR: ::c_int = 21; -pub const EINVAL: ::c_int = 22; -pub const ENFILE: ::c_int = 23; -pub const EMFILE: ::c_int = 24; -pub const ENOTTY: ::c_int = 25; -pub const ETXTBSY: ::c_int = 26; -pub const EFBIG: ::c_int = 27; -pub const ENOSPC: ::c_int = 28; -pub const ESPIPE: ::c_int = 29; -pub const EROFS: ::c_int = 30; -pub const EMLINK: ::c_int = 31; -pub const EPIPE: ::c_int = 32; -pub const EDOM: ::c_int = 33; -pub const ERANGE: ::c_int = 34; -pub const ENOMSG: ::c_int = 35; -pub const EIDRM: ::c_int = 36; -pub const EDEADLK: ::c_int = 45; -pub const ENOLCK: ::c_int = 46; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENOLINK: ::c_int = 67; -pub const EPROTO: ::c_int = 71; -pub const EMULTIHOP: ::c_int = 74; -pub const EBADMSG: ::c_int = 77; -pub const EFTYPE: ::c_int = 79; -pub const ENOSYS: ::c_int = 88; -pub const ENOTEMPTY: ::c_int = 90; -pub const ENAMETOOLONG: ::c_int = 91; -pub const ELOOP: ::c_int = 92; -pub const EOPNOTSUPP: ::c_int = 95; -pub const EPFNOSUPPORT: ::c_int = 96; -pub const ECONNRESET: ::c_int = 104; -pub const ENOBUFS: ::c_int = 105; -pub const EAFNOSUPPORT: ::c_int = 106; -pub const EPROTOTYPE: ::c_int = 107; -pub const ENOTSOCK: ::c_int = 108; -pub const ENOPROTOOPT: ::c_int = 109; -pub const ECONNREFUSED: ::c_int = 111; -pub const EADDRINUSE: ::c_int = 112; -pub const ECONNABORTED: ::c_int = 113; -pub const ENETUNREACH: ::c_int = 114; -pub const ENETDOWN: ::c_int = 115; -pub const ETIMEDOUT: ::c_int = 116; -pub const EHOSTDOWN: ::c_int = 117; -pub const EHOSTUNREACH: ::c_int = 118; -pub const EINPROGRESS: ::c_int = 119; -pub const EALREADY: ::c_int = 120; -pub const EDESTADDRREQ: ::c_int = 121; -pub const EMSGSIZE: ::c_int = 122; -pub const EPROTONOSUPPORT: ::c_int = 123; -pub const EADDRNOTAVAIL: ::c_int = 125; -pub const ENETRESET: ::c_int = 126; -pub const EISCONN: ::c_int = 127; -pub const ENOTCONN: ::c_int = 128; -pub const ETOOMANYREFS: ::c_int = 129; -pub const EDQUOT: ::c_int = 132; -pub const ESTALE: ::c_int = 133; -pub const ENOTSUP: ::c_int = 134; -pub const EILSEQ: ::c_int = 138; -pub const EOVERFLOW: ::c_int = 139; -pub const ECANCELED: ::c_int = 140; -pub const ENOTRECOVERABLE: ::c_int = 141; -pub const EOWNERDEAD: ::c_int = 142; -pub const EWOULDBLOCK: ::c_int = 11; - -pub const F_DUPFD: ::c_int = 0; -pub const F_GETFD: ::c_int = 1; -pub const F_SETFD: ::c_int = 2; -pub const F_GETFL: ::c_int = 3; -pub const F_SETFL: ::c_int = 4; -pub const F_GETOWN: ::c_int = 5; -pub const F_SETOWN: ::c_int = 6; -pub const F_GETLK: ::c_int = 7; -pub const F_SETLK: ::c_int = 8; -pub const F_SETLKW: ::c_int = 9; -pub const F_RGETLK: ::c_int = 10; -pub const F_RSETLK: ::c_int = 11; -pub const F_CNVT: ::c_int = 12; -pub const F_RSETLKW: ::c_int = 13; -pub const F_DUPFD_CLOEXEC: ::c_int = 14; - -pub const O_RDONLY: ::c_int = 0; -pub const O_WRONLY: ::c_int = 1; -pub const O_RDWR: ::c_int = 2; -pub const O_APPEND: ::c_int = 8; -pub const O_CREAT: ::c_int = 512; -pub const O_TRUNC: ::c_int = 1024; -pub const O_EXCL: ::c_int = 2048; -pub const O_SYNC: ::c_int = 8192; -pub const O_NONBLOCK: ::c_int = 16384; - -pub const O_ACCMODE: ::c_int = 3; -pub const O_CLOEXEC: ::c_int = 0x80000; - -pub const POLLIN: ::c_short = 0x1; -pub const POLLPRI: ::c_short = 0x2; -pub const POLLOUT: ::c_short = 0x4; -pub const POLLERR: ::c_short = 0x8; -pub const POLLHUP: ::c_short = 0x10; -pub const POLLNVAL: ::c_short = 0x20; - -pub const RTLD_LAZY: ::c_int = 0x1; - -pub const STDIN_FILENO: ::c_int = 0; -pub const STDOUT_FILENO: ::c_int = 1; -pub const STDERR_FILENO: ::c_int = 2; - -pub const SEEK_SET: ::c_int = 0; -pub const SEEK_CUR: ::c_int = 1; -pub const SEEK_END: ::c_int = 2; - -pub const FIONBIO: ::c_int = 1; - -pub const S_BLKSIZE: ::mode_t = 1024; -pub const S_IREAD: ::mode_t = 256; -pub const S_IWRITE: ::mode_t = 128; -pub const S_IEXEC: ::mode_t = 64; -pub const S_ENFMT: ::mode_t = 1024; -pub const S_IFMT: ::mode_t = 61440; -pub const S_IFDIR: ::mode_t = 16384; -pub const S_IFCHR: ::mode_t = 8192; -pub const S_IFBLK: ::mode_t = 24576; -pub const S_IFREG: ::mode_t = 32768; -pub const S_IFLNK: ::mode_t = 40960; -pub const S_IFSOCK: ::mode_t = 49152; -pub const S_IFIFO: ::mode_t = 4096; -pub const S_IRUSR: ::mode_t = 256; -pub const S_IWUSR: ::mode_t = 128; -pub const S_IXUSR: ::mode_t = 64; -pub const S_IRGRP: ::mode_t = 32; -pub const S_IWGRP: ::mode_t = 16; -pub const S_IXGRP: ::mode_t = 8; -pub const S_IROTH: ::mode_t = 4; -pub const S_IWOTH: ::mode_t = 2; -pub const S_IXOTH: ::mode_t = 1; - -pub const SOL_SOCKET: ::c_int = 65535; -pub const SOL_TCP: ::c_int = 6; - -pub const PF_UNSPEC: ::c_int = 0; -pub const PF_INET: ::c_int = 2; -pub const PF_INET6: ::c_int = 23; - -pub const AF_UNSPEC: ::c_int = 0; -pub const AF_INET: ::c_int = 2; -pub const AF_INET6: ::c_int = 23; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; - -pub const MSG_OOB: ::c_int = 1; -pub const MSG_PEEK: ::c_int = 2; -pub const MSG_DONTWAIT: ::c_int = 4; -pub const MSG_DONTROUTE: ::c_int = 0; -pub const MSG_WAITALL: ::c_int = 0; -pub const MSG_MORE: ::c_int = 0; -pub const MSG_NOSIGNAL: ::c_int = 0; - -pub const SHUT_RD: ::c_int = 0; -pub const SHUT_WR: ::c_int = 1; -pub const SHUT_RDWR: ::c_int = 2; - -pub const SO_REUSEADDR: ::c_int = 4; -pub const SO_LINGER: ::c_int = 128; -pub const SO_OOBINLINE: ::c_int = 256; -pub const SO_SNDBUF: ::c_int = 4097; -pub const SO_RCVBUF: ::c_int = 4098; -pub const SO_SNDLOWAT: ::c_int = 4099; -pub const SO_RCVLOWAT: ::c_int = 4100; -pub const SO_TYPE: ::c_int = 4104; -pub const SO_ERROR: ::c_int = 4105; - -pub const SOCK_CLOEXEC: ::c_int = O_CLOEXEC; - -pub const INET_ADDRSTRLEN: ::c_int = 16; - -// https://github. -// com/bminor/newlib/blob/master/newlib/libc/sys/linux/include/net/if.h#L121 -pub const IFF_UP: ::c_int = 0x1; // interface is up -pub const IFF_BROADCAST: ::c_int = 0x2; // broadcast address valid -pub const IFF_DEBUG: ::c_int = 0x4; // turn on debugging -pub const IFF_LOOPBACK: ::c_int = 0x8; // is a loopback net -pub const IFF_POINTOPOINT: ::c_int = 0x10; // interface is point-to-point link -pub const IFF_NOTRAILERS: ::c_int = 0x20; // avoid use of trailers -pub const IFF_RUNNING: ::c_int = 0x40; // resources allocated -pub const IFF_NOARP: ::c_int = 0x80; // no address resolution protocol -pub const IFF_PROMISC: ::c_int = 0x100; // receive all packets -pub const IFF_ALLMULTI: ::c_int = 0x200; // receive all multicast packets -pub const IFF_OACTIVE: ::c_int = 0x400; // transmission in progress -pub const IFF_SIMPLEX: ::c_int = 0x800; // can't hear own transmissions -pub const IFF_LINK0: ::c_int = 0x1000; // per link layer defined bit -pub const IFF_LINK1: ::c_int = 0x2000; // per link layer defined bit -pub const IFF_LINK2: ::c_int = 0x4000; // per link layer defined bit -pub const IFF_ALTPHYS: ::c_int = IFF_LINK2; // use alternate physical connection -pub const IFF_MULTICAST: ::c_int = 0x8000; // supports multicast - -pub const IPPROTO_IP: ::c_int = 0; -pub const IPPROTO_UDP: ::c_int = 17; -pub const IPPROTO_TCP: ::c_int = 6; - -pub const TCP_NODELAY: ::c_int = 8193; -pub const TCP_MAXSEG: ::c_int = 8194; - -pub const IP_TOS: ::c_int = 7; -pub const IP_TTL: ::c_int = 8; -pub const IP_MULTICAST_LOOP: ::c_int = 9; -pub const IP_MULTICAST_TTL: ::c_int = 10; -pub const IP_ADD_MEMBERSHIP: ::c_int = 11; -pub const IP_DROP_MEMBERSHIP: ::c_int = 12; - -pub const HOST_NOT_FOUND: ::c_int = 1; -pub const NO_DATA: ::c_int = 2; -pub const NO_ADDRESS: ::c_int = 2; -pub const NO_RECOVERY: ::c_int = 3; -pub const TRY_AGAIN: ::c_int = 4; - -pub const AI_PASSIVE: ::c_int = 1; -pub const AI_CANONNAME: ::c_int = 2; -pub const AI_NUMERICHOST: ::c_int = 4; -pub const AI_NUMERICSERV: ::c_int = 0; -pub const AI_ADDRCONFIG: ::c_int = 0; - -pub const NI_MAXHOST: ::c_int = 1025; -pub const NI_MAXSERV: ::c_int = 32; -pub const NI_NOFQDN: ::c_int = 1; -pub const NI_NUMERICHOST: ::c_int = 2; -pub const NI_NAMEREQD: ::c_int = 4; -pub const NI_NUMERICSERV: ::c_int = 0; -pub const NI_DGRAM: ::c_int = 0; - -pub const EAI_FAMILY: ::c_int = -303; -pub const EAI_MEMORY: ::c_int = -304; -pub const EAI_NONAME: ::c_int = -305; -pub const EAI_SOCKTYPE: ::c_int = -307; - -f! { - pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { - let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; - let fd = fd as usize; - (*set).fds_bits[fd / bits] &= !(1 << (fd % bits)); - return - } - - pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { - let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; - let fd = fd as usize; - return ((*set).fds_bits[fd / bits] & (1 << (fd % bits))) != 0 - } - - pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { - let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; - let fd = fd as usize; - (*set).fds_bits[fd / bits] |= 1 << (fd % bits); - return - } - - pub fn FD_ZERO(set: *mut fd_set) -> () { - for slot in (*set).fds_bits.iter_mut() { - *slot = 0; - } - } -} - -extern { - pub fn bind(fd: ::c_int, addr: *const sockaddr, len: socklen_t) -> ::c_int; - pub fn closesocket(sockfd: ::c_int) -> ::c_int; - pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; - pub fn recvfrom(fd: ::c_int, buf: *mut ::c_void, n: usize, flags: ::c_int, - addr: *mut sockaddr, addr_len: *mut socklen_t) -> isize; - pub fn getnameinfo(sa: *const sockaddr, salen: socklen_t, - host: *mut ::c_char, hostlen: socklen_t, - serv: *mut ::c_char, servlen: socklen_t, - flags: ::c_int) -> ::c_int; - pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; - pub fn fexecve(fd: ::c_int, argv: *const *const ::c_char, - envp: *const *const ::c_char) - -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] - pub fn getgrgid_r(uid: ::uid_t, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "sigaltstack$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")] - pub fn sigaltstack(ss: *const stack_t, - oss: *mut stack_t) -> ::c_int; - pub fn sem_close(sem: *mut sem_t) -> ::c_int; - pub fn getdtablesize() -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] - pub fn getgrnam_r(name: *const ::c_char, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_sigmask$UNIX2003")] - pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, - oldset: *mut sigset_t) -> ::c_int; - pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; - pub fn getgrnam(name: *const ::c_char) -> *mut ::group; - pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; - pub fn sem_unlink(name: *const ::c_char) -> ::c_int; - pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] - pub fn getpwnam_r(name: *const ::c_char, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] - pub fn getpwuid_r(uid: ::uid_t, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch ="x86"), - link_name = "sigwait$UNIX2003")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] - pub fn sigwait(set: *const sigset_t, - sig: *mut ::c_int) -> ::c_int; - pub fn pthread_atfork(prepare: Option, - parent: Option, - child: Option) -> ::c_int; - pub fn getgrgid(gid: ::gid_t) -> *mut ::group; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "popen$UNIX2003")] - pub fn popen(command: *const c_char, - mode: *const c_char) -> *mut ::FILE; -} - -cfg_if! { - if #[cfg(target_arch = "arm")] { - mod arm; - pub use self::arm::*; - } else if #[cfg(target_arch = "aarch64")] { - mod aarch64; - pub use self::aarch64::*; - } else { - // Only tested on ARM so far. Other platforms might have different - // definitions for types and constants. - pub use target_arch_not_implemented; - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/b32/arm.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/b32/arm.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/b32/arm.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/b32/arm.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,357 +0,0 @@ -pub type c_char = u8; -pub type wchar_t = u32; - -pub const O_DIRECT: ::c_int = 0x10000; -pub const O_DIRECTORY: ::c_int = 0x4000; -pub const O_NOFOLLOW: ::c_int = 0x8000; -pub const O_LARGEFILE: ::c_int = 0o400000; - -pub const SYS_restart_syscall: ::c_long = 0; -pub const SYS_exit: ::c_long = 1; -pub const SYS_fork: ::c_long = 2; -pub const SYS_read: ::c_long = 3; -pub const SYS_write: ::c_long = 4; -pub const SYS_open: ::c_long = 5; -pub const SYS_close: ::c_long = 6; -pub const SYS_creat: ::c_long = 8; -pub const SYS_link: ::c_long = 9; -pub const SYS_unlink: ::c_long = 10; -pub const SYS_execve: ::c_long = 11; -pub const SYS_chdir: ::c_long = 12; -pub const SYS_mknod: ::c_long = 14; -pub const SYS_chmod: ::c_long = 15; -pub const SYS_lchown: ::c_long = 16; -pub const SYS_lseek: ::c_long = 19; -pub const SYS_getpid: ::c_long = 20; -pub const SYS_mount: ::c_long = 21; -pub const SYS_setuid: ::c_long = 23; -pub const SYS_getuid: ::c_long = 24; -pub const SYS_ptrace: ::c_long = 26; -pub const SYS_pause: ::c_long = 29; -pub const SYS_access: ::c_long = 33; -pub const SYS_nice: ::c_long = 34; -pub const SYS_sync: ::c_long = 36; -pub const SYS_kill: ::c_long = 37; -pub const SYS_rename: ::c_long = 38; -pub const SYS_mkdir: ::c_long = 39; -pub const SYS_rmdir: ::c_long = 40; -pub const SYS_dup: ::c_long = 41; -pub const SYS_pipe: ::c_long = 42; -pub const SYS_times: ::c_long = 43; -pub const SYS_brk: ::c_long = 45; -pub const SYS_setgid: ::c_long = 46; -pub const SYS_getgid: ::c_long = 47; -pub const SYS_geteuid: ::c_long = 49; -pub const SYS_getegid: ::c_long = 50; -pub const SYS_acct: ::c_long = 51; -pub const SYS_umount2: ::c_long = 52; -pub const SYS_ioctl: ::c_long = 54; -pub const SYS_fcntl: ::c_long = 55; -pub const SYS_setpgid: ::c_long = 57; -pub const SYS_umask: ::c_long = 60; -pub const SYS_chroot: ::c_long = 61; -pub const SYS_ustat: ::c_long = 62; -pub const SYS_dup2: ::c_long = 63; -pub const SYS_getppid: ::c_long = 64; -pub const SYS_getpgrp: ::c_long = 65; -pub const SYS_setsid: ::c_long = 66; -pub const SYS_sigaction: ::c_long = 67; -pub const SYS_setreuid: ::c_long = 70; -pub const SYS_setregid: ::c_long = 71; -pub const SYS_sigsuspend: ::c_long = 72; -pub const SYS_sigpending: ::c_long = 73; -pub const SYS_sethostname: ::c_long = 74; -pub const SYS_setrlimit: ::c_long = 75; -pub const SYS_getrusage: ::c_long = 77; -pub const SYS_gettimeofday: ::c_long = 78; -pub const SYS_settimeofday: ::c_long = 79; -pub const SYS_getgroups: ::c_long = 80; -pub const SYS_setgroups: ::c_long = 81; -pub const SYS_symlink: ::c_long = 83; -pub const SYS_readlink: ::c_long = 85; -pub const SYS_uselib: ::c_long = 86; -pub const SYS_swapon: ::c_long = 87; -pub const SYS_reboot: ::c_long = 88; -pub const SYS_munmap: ::c_long = 91; -pub const SYS_truncate: ::c_long = 92; -pub const SYS_ftruncate: ::c_long = 93; -pub const SYS_fchmod: ::c_long = 94; -pub const SYS_fchown: ::c_long = 95; -pub const SYS_getpriority: ::c_long = 96; -pub const SYS_setpriority: ::c_long = 97; -pub const SYS_statfs: ::c_long = 99; -pub const SYS_fstatfs: ::c_long = 100; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_setitimer: ::c_long = 104; -pub const SYS_getitimer: ::c_long = 105; -pub const SYS_stat: ::c_long = 106; -pub const SYS_lstat: ::c_long = 107; -pub const SYS_fstat: ::c_long = 108; -pub const SYS_vhangup: ::c_long = 111; -pub const SYS_wait4: ::c_long = 114; -pub const SYS_swapoff: ::c_long = 115; -pub const SYS_sysinfo: ::c_long = 116; -pub const SYS_fsync: ::c_long = 118; -pub const SYS_sigreturn: ::c_long = 119; -pub const SYS_clone: ::c_long = 120; -pub const SYS_setdomainname: ::c_long = 121; -pub const SYS_uname: ::c_long = 122; -pub const SYS_adjtimex: ::c_long = 124; -pub const SYS_mprotect: ::c_long = 125; -pub const SYS_sigprocmask: ::c_long = 126; -pub const SYS_init_module: ::c_long = 128; -pub const SYS_delete_module: ::c_long = 129; -pub const SYS_quotactl: ::c_long = 131; -pub const SYS_getpgid: ::c_long = 132; -pub const SYS_fchdir: ::c_long = 133; -pub const SYS_bdflush: ::c_long = 134; -pub const SYS_sysfs: ::c_long = 135; -pub const SYS_personality: ::c_long = 136; -pub const SYS_setfsuid: ::c_long = 138; -pub const SYS_setfsgid: ::c_long = 139; -pub const SYS_getdents: ::c_long = 141; -pub const SYS_flock: ::c_long = 143; -pub const SYS_msync: ::c_long = 144; -pub const SYS_readv: ::c_long = 145; -pub const SYS_writev: ::c_long = 146; -pub const SYS_getsid: ::c_long = 147; -pub const SYS_fdatasync: ::c_long = 148; -pub const SYS_mlock: ::c_long = 150; -pub const SYS_munlock: ::c_long = 151; -pub const SYS_mlockall: ::c_long = 152; -pub const SYS_munlockall: ::c_long = 153; -pub const SYS_sched_setparam: ::c_long = 154; -pub const SYS_sched_getparam: ::c_long = 155; -pub const SYS_sched_setscheduler: ::c_long = 156; -pub const SYS_sched_getscheduler: ::c_long = 157; -pub const SYS_sched_yield: ::c_long = 158; -pub const SYS_sched_get_priority_max: ::c_long = 159; -pub const SYS_sched_get_priority_min: ::c_long = 160; -pub const SYS_sched_rr_get_interval: ::c_long = 161; -pub const SYS_nanosleep: ::c_long = 162; -pub const SYS_mremap: ::c_long = 163; -pub const SYS_setresuid: ::c_long = 164; -pub const SYS_getresuid: ::c_long = 165; -pub const SYS_poll: ::c_long = 168; -pub const SYS_nfsservctl: ::c_long = 169; -pub const SYS_setresgid: ::c_long = 170; -pub const SYS_getresgid: ::c_long = 171; -pub const SYS_prctl: ::c_long = 172; -pub const SYS_rt_sigreturn: ::c_long = 173; -pub const SYS_rt_sigaction: ::c_long = 174; -pub const SYS_rt_sigprocmask: ::c_long = 175; -pub const SYS_rt_sigpending: ::c_long = 176; -pub const SYS_rt_sigtimedwait: ::c_long = 177; -pub const SYS_rt_sigqueueinfo: ::c_long = 178; -pub const SYS_rt_sigsuspend: ::c_long = 179; -pub const SYS_pread64: ::c_long = 180; -pub const SYS_pwrite64: ::c_long = 181; -pub const SYS_chown: ::c_long = 182; -pub const SYS_getcwd: ::c_long = 183; -pub const SYS_capget: ::c_long = 184; -pub const SYS_capset: ::c_long = 185; -pub const SYS_sigaltstack: ::c_long = 186; -pub const SYS_sendfile: ::c_long = 187; -pub const SYS_vfork: ::c_long = 190; -pub const SYS_ugetrlimit: ::c_long = 191; -pub const SYS_mmap2: ::c_long = 192; -pub const SYS_truncate64: ::c_long = 193; -pub const SYS_ftruncate64: ::c_long = 194; -pub const SYS_stat64: ::c_long = 195; -pub const SYS_lstat64: ::c_long = 196; -pub const SYS_fstat64: ::c_long = 197; -pub const SYS_lchown32: ::c_long = 198; -pub const SYS_getuid32: ::c_long = 199; -pub const SYS_getgid32: ::c_long = 200; -pub const SYS_geteuid32: ::c_long = 201; -pub const SYS_getegid32: ::c_long = 202; -pub const SYS_setreuid32: ::c_long = 203; -pub const SYS_setregid32: ::c_long = 204; -pub const SYS_getgroups32: ::c_long = 205; -pub const SYS_setgroups32: ::c_long = 206; -pub const SYS_fchown32: ::c_long = 207; -pub const SYS_setresuid32: ::c_long = 208; -pub const SYS_getresuid32: ::c_long = 209; -pub const SYS_setresgid32: ::c_long = 210; -pub const SYS_getresgid32: ::c_long = 211; -pub const SYS_chown32: ::c_long = 212; -pub const SYS_setuid32: ::c_long = 213; -pub const SYS_setgid32: ::c_long = 214; -pub const SYS_setfsuid32: ::c_long = 215; -pub const SYS_setfsgid32: ::c_long = 216; -pub const SYS_getdents64: ::c_long = 217; -pub const SYS_pivot_root: ::c_long = 218; -pub const SYS_mincore: ::c_long = 219; -pub const SYS_madvise: ::c_long = 220; -pub const SYS_fcntl64: ::c_long = 221; -pub const SYS_gettid: ::c_long = 224; -pub const SYS_readahead: ::c_long = 225; -pub const SYS_setxattr: ::c_long = 226; -pub const SYS_lsetxattr: ::c_long = 227; -pub const SYS_fsetxattr: ::c_long = 228; -pub const SYS_getxattr: ::c_long = 229; -pub const SYS_lgetxattr: ::c_long = 230; -pub const SYS_fgetxattr: ::c_long = 231; -pub const SYS_listxattr: ::c_long = 232; -pub const SYS_llistxattr: ::c_long = 233; -pub const SYS_flistxattr: ::c_long = 234; -pub const SYS_removexattr: ::c_long = 235; -pub const SYS_lremovexattr: ::c_long = 236; -pub const SYS_fremovexattr: ::c_long = 237; -pub const SYS_tkill: ::c_long = 238; -pub const SYS_sendfile64: ::c_long = 239; -pub const SYS_futex: ::c_long = 240; -pub const SYS_sched_setaffinity: ::c_long = 241; -pub const SYS_sched_getaffinity: ::c_long = 242; -pub const SYS_io_setup: ::c_long = 243; -pub const SYS_io_destroy: ::c_long = 244; -pub const SYS_io_getevents: ::c_long = 245; -pub const SYS_io_submit: ::c_long = 246; -pub const SYS_io_cancel: ::c_long = 247; -pub const SYS_exit_group: ::c_long = 248; -pub const SYS_lookup_dcookie: ::c_long = 249; -pub const SYS_epoll_create: ::c_long = 250; -pub const SYS_epoll_ctl: ::c_long = 251; -pub const SYS_epoll_wait: ::c_long = 252; -pub const SYS_remap_file_pages: ::c_long = 253; -pub const SYS_set_tid_address: ::c_long = 256; -pub const SYS_timer_create: ::c_long = 257; -pub const SYS_timer_settime: ::c_long = 258; -pub const SYS_timer_gettime: ::c_long = 259; -pub const SYS_timer_getoverrun: ::c_long = 260; -pub const SYS_timer_delete: ::c_long = 261; -pub const SYS_clock_settime: ::c_long = 262; -pub const SYS_clock_gettime: ::c_long = 263; -pub const SYS_clock_getres: ::c_long = 264; -pub const SYS_clock_nanosleep: ::c_long = 265; -pub const SYS_statfs64: ::c_long = 266; -pub const SYS_fstatfs64: ::c_long = 267; -pub const SYS_tgkill: ::c_long = 268; -pub const SYS_utimes: ::c_long = 269; -pub const SYS_arm_fadvise64_64: ::c_long = 270; -pub const SYS_pciconfig_iobase: ::c_long = 271; -pub const SYS_pciconfig_read: ::c_long = 272; -pub const SYS_pciconfig_write: ::c_long = 273; -pub const SYS_mq_open: ::c_long = 274; -pub const SYS_mq_unlink: ::c_long = 275; -pub const SYS_mq_timedsend: ::c_long = 276; -pub const SYS_mq_timedreceive: ::c_long = 277; -pub const SYS_mq_notify: ::c_long = 278; -pub const SYS_mq_getsetattr: ::c_long = 279; -pub const SYS_waitid: ::c_long = 280; -pub const SYS_socket: ::c_long = 281; -pub const SYS_bind: ::c_long = 282; -pub const SYS_connect: ::c_long = 283; -pub const SYS_listen: ::c_long = 284; -pub const SYS_accept: ::c_long = 285; -pub const SYS_getsockname: ::c_long = 286; -pub const SYS_getpeername: ::c_long = 287; -pub const SYS_socketpair: ::c_long = 288; -pub const SYS_send: ::c_long = 289; -pub const SYS_sendto: ::c_long = 290; -pub const SYS_recv: ::c_long = 291; -pub const SYS_recvfrom: ::c_long = 292; -pub const SYS_shutdown: ::c_long = 293; -pub const SYS_setsockopt: ::c_long = 294; -pub const SYS_getsockopt: ::c_long = 295; -pub const SYS_sendmsg: ::c_long = 296; -pub const SYS_recvmsg: ::c_long = 297; -pub const SYS_semop: ::c_long = 298; -pub const SYS_semget: ::c_long = 299; -pub const SYS_semctl: ::c_long = 300; -pub const SYS_msgsnd: ::c_long = 301; -pub const SYS_msgrcv: ::c_long = 302; -pub const SYS_msgget: ::c_long = 303; -pub const SYS_msgctl: ::c_long = 304; -pub const SYS_shmat: ::c_long = 305; -pub const SYS_shmdt: ::c_long = 306; -pub const SYS_shmget: ::c_long = 307; -pub const SYS_shmctl: ::c_long = 308; -pub const SYS_add_key: ::c_long = 309; -pub const SYS_request_key: ::c_long = 310; -pub const SYS_keyctl: ::c_long = 311; -pub const SYS_semtimedop: ::c_long = 312; -pub const SYS_vserver: ::c_long = 313; -pub const SYS_ioprio_set: ::c_long = 314; -pub const SYS_ioprio_get: ::c_long = 315; -pub const SYS_inotify_init: ::c_long = 316; -pub const SYS_inotify_add_watch: ::c_long = 317; -pub const SYS_inotify_rm_watch: ::c_long = 318; -pub const SYS_mbind: ::c_long = 319; -pub const SYS_get_mempolicy: ::c_long = 320; -pub const SYS_set_mempolicy: ::c_long = 321; -pub const SYS_openat: ::c_long = 322; -pub const SYS_mkdirat: ::c_long = 323; -pub const SYS_mknodat: ::c_long = 324; -pub const SYS_fchownat: ::c_long = 325; -pub const SYS_futimesat: ::c_long = 326; -pub const SYS_fstatat64: ::c_long = 327; -pub const SYS_unlinkat: ::c_long = 328; -pub const SYS_renameat: ::c_long = 329; -pub const SYS_linkat: ::c_long = 330; -pub const SYS_symlinkat: ::c_long = 331; -pub const SYS_readlinkat: ::c_long = 332; -pub const SYS_fchmodat: ::c_long = 333; -pub const SYS_faccessat: ::c_long = 334; -pub const SYS_pselect6: ::c_long = 335; -pub const SYS_ppoll: ::c_long = 336; -pub const SYS_unshare: ::c_long = 337; -pub const SYS_set_robust_list: ::c_long = 338; -pub const SYS_get_robust_list: ::c_long = 339; -pub const SYS_splice: ::c_long = 340; -pub const SYS_arm_sync_file_range: ::c_long = 341; -pub const SYS_tee: ::c_long = 342; -pub const SYS_vmsplice: ::c_long = 343; -pub const SYS_move_pages: ::c_long = 344; -pub const SYS_getcpu: ::c_long = 345; -pub const SYS_epoll_pwait: ::c_long = 346; -pub const SYS_kexec_load: ::c_long = 347; -pub const SYS_utimensat: ::c_long = 348; -pub const SYS_signalfd: ::c_long = 349; -pub const SYS_timerfd_create: ::c_long = 350; -pub const SYS_eventfd: ::c_long = 351; -pub const SYS_fallocate: ::c_long = 352; -pub const SYS_timerfd_settime: ::c_long = 353; -pub const SYS_timerfd_gettime: ::c_long = 354; -pub const SYS_signalfd4: ::c_long = 355; -pub const SYS_eventfd2: ::c_long = 356; -pub const SYS_epoll_create1: ::c_long = 357; -pub const SYS_dup3: ::c_long = 358; -pub const SYS_pipe2: ::c_long = 359; -pub const SYS_inotify_init1: ::c_long = 360; -pub const SYS_preadv: ::c_long = 361; -pub const SYS_pwritev: ::c_long = 362; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 363; -pub const SYS_perf_event_open: ::c_long = 364; -pub const SYS_recvmmsg: ::c_long = 365; -pub const SYS_accept4: ::c_long = 366; -pub const SYS_fanotify_init: ::c_long = 367; -pub const SYS_fanotify_mark: ::c_long = 368; -pub const SYS_prlimit64: ::c_long = 369; -pub const SYS_name_to_handle_at: ::c_long = 370; -pub const SYS_open_by_handle_at: ::c_long = 371; -pub const SYS_clock_adjtime: ::c_long = 372; -pub const SYS_syncfs: ::c_long = 373; -pub const SYS_sendmmsg: ::c_long = 374; -pub const SYS_setns: ::c_long = 375; -pub const SYS_process_vm_readv: ::c_long = 376; -pub const SYS_process_vm_writev: ::c_long = 377; -pub const SYS_kcmp: ::c_long = 378; -pub const SYS_finit_module: ::c_long = 379; -pub const SYS_sched_setattr: ::c_long = 380; -pub const SYS_sched_getattr: ::c_long = 381; -pub const SYS_renameat2: ::c_long = 382; -pub const SYS_seccomp: ::c_long = 383; -pub const SYS_getrandom: ::c_long = 384; -pub const SYS_memfd_create: ::c_long = 385; -pub const SYS_bpf: ::c_long = 386; -pub const SYS_execveat: ::c_long = 387; -pub const SYS_userfaultfd: ::c_long = 388; -pub const SYS_membarrier: ::c_long = 389; -pub const SYS_mlock2: ::c_long = 390; -pub const SYS_copy_file_range: ::c_long = 391; -pub const SYS_preadv2: ::c_long = 392; -pub const SYS_pwritev2: ::c_long = 393; -pub const SYS_pkey_mprotect: ::c_long = 394; -pub const SYS_pkey_alloc: ::c_long = 395; -pub const SYS_pkey_free: ::c_long = 396; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/b32/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/b32/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/b32/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/b32/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,230 +0,0 @@ -// The following definitions are correct for arm and i686, -// but may be wrong for mips - -pub type c_long = i32; -pub type c_ulong = u32; -pub type mode_t = u16; -pub type off64_t = ::c_longlong; -pub type sigset_t = ::c_ulong; -pub type socklen_t = i32; -pub type time64_t = i64; - -s! { - pub struct sigaction { - pub sa_sigaction: ::sighandler_t, - pub sa_mask: ::sigset_t, - pub sa_flags: ::c_ulong, - pub sa_restorer: ::dox::Option, - } - - pub struct rlimit64 { - pub rlim_cur: u64, - pub rlim_max: u64, - } - - pub struct stat { - pub st_dev: ::c_ulonglong, - __pad0: [::c_uchar; 4], - __st_ino: ::ino_t, - pub st_mode: ::c_uint, - pub st_nlink: ::c_uint, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::c_ulonglong, - __pad3: [::c_uchar; 4], - pub st_size: ::c_longlong, - pub st_blksize: ::blksize_t, - pub st_blocks: ::c_ulonglong, - pub st_atime: ::c_ulong, - pub st_atime_nsec: ::c_ulong, - pub st_mtime: ::c_ulong, - pub st_mtime_nsec: ::c_ulong, - pub st_ctime: ::c_ulong, - pub st_ctime_nsec: ::c_ulong, - pub st_ino: ::c_ulonglong, - } - - pub struct stat64 { - pub st_dev: ::c_ulonglong, - __pad0: [::c_uchar; 4], - __st_ino: ::ino_t, - pub st_mode: ::c_uint, - pub st_nlink: ::c_uint, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::c_ulonglong, - __pad3: [::c_uchar; 4], - pub st_size: ::c_longlong, - pub st_blksize: ::blksize_t, - pub st_blocks: ::c_ulonglong, - pub st_atime: ::c_ulong, - pub st_atime_nsec: ::c_ulong, - pub st_mtime: ::c_ulong, - pub st_mtime_nsec: ::c_ulong, - pub st_ctime: ::c_ulong, - pub st_ctime_nsec: ::c_ulong, - pub st_ino: ::c_ulonglong, - } - - pub struct statfs64 { - pub f_type: u32, - pub f_bsize: u32, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - f_fsid: [u32; 2], - pub f_namelen: u32, - pub f_frsize: u32, - pub f_flags: u32, - pub f_spare: [u32; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::c_ulong, - pub f_bfree: ::c_ulong, - pub f_bavail: ::c_ulong, - pub f_files: ::c_ulong, - pub f_ffree: ::c_ulong, - pub f_favail: ::c_ulong, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - } - - pub struct pthread_attr_t { - pub flags: ::uint32_t, - pub stack_base: *mut ::c_void, - pub stack_size: ::size_t, - pub guard_size: ::size_t, - pub sched_policy: ::int32_t, - pub sched_priority: ::int32_t, - } - - pub struct pthread_mutex_t { value: ::c_int } - - pub struct pthread_cond_t { value: ::c_int } - - pub struct pthread_rwlock_t { - lock: pthread_mutex_t, - cond: pthread_cond_t, - numLocks: ::c_int, - writerThreadId: ::c_int, - pendingReaders: ::c_int, - pendingWriters: ::c_int, - attr: i32, - __reserved: [::c_char; 12], - } - - pub struct passwd { - pub pw_name: *mut ::c_char, - pub pw_passwd: *mut ::c_char, - pub pw_uid: ::uid_t, - pub pw_gid: ::gid_t, - pub pw_dir: *mut ::c_char, - pub pw_shell: *mut ::c_char, - } - - pub struct statfs { - pub f_type: ::uint32_t, - pub f_bsize: ::uint32_t, - pub f_blocks: ::uint64_t, - pub f_bfree: ::uint64_t, - pub f_bavail: ::uint64_t, - pub f_files: ::uint64_t, - pub f_ffree: ::uint64_t, - pub f_fsid: ::__fsid_t, - pub f_namelen: ::uint32_t, - pub f_frsize: ::uint32_t, - pub f_flags: ::uint32_t, - pub f_spare: [::uint32_t; 4], - } - - pub struct sysinfo { - pub uptime: ::c_long, - pub loads: [::c_ulong; 3], - pub totalram: ::c_ulong, - pub freeram: ::c_ulong, - pub sharedram: ::c_ulong, - pub bufferram: ::c_ulong, - pub totalswap: ::c_ulong, - pub freeswap: ::c_ulong, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: ::c_ulong, - pub freehigh: ::c_ulong, - pub mem_unit: ::c_uint, - pub _f: [::c_char; 8], - } -} - -pub const RTLD_GLOBAL: ::c_int = 2; -pub const RTLD_NOW: ::c_int = 0; -pub const RTLD_DEFAULT: *mut ::c_void = -1isize as *mut ::c_void; - -pub const PTRACE_GETFPREGS: ::c_int = 14; -pub const PTRACE_SETFPREGS: ::c_int = 15; -pub const PTRACE_GETREGS: ::c_int = 12; -pub const PTRACE_SETREGS: ::c_int = 13; - -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { - value: 0, -}; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { - value: 0, -}; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { - lock: PTHREAD_MUTEX_INITIALIZER, - cond: PTHREAD_COND_INITIALIZER, - numLocks: 0, - writerThreadId: 0, - pendingReaders: 0, - pendingWriters: 0, - attr: 0, - __reserved: [0; 12], -}; -pub const PTHREAD_STACK_MIN: ::size_t = 4096 * 2; -pub const CPU_SETSIZE: ::size_t = 32; -pub const __CPU_BITS: ::size_t = 32; - -pub const UT_LINESIZE: usize = 8; -pub const UT_NAMESIZE: usize = 8; -pub const UT_HOSTSIZE: usize = 16; - -pub const SIGSTKSZ: ::size_t = 8192; -pub const MINSIGSTKSZ: ::size_t = 2048; - -extern { - pub fn bind(socket: ::c_int, address: *const ::sockaddr, - address_len: socklen_t) -> ::c_int; - - pub fn writev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - pub fn readv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - - pub fn sendmsg(fd: ::c_int, - msg: *const ::msghdr, - flags: ::c_int) -> ::ssize_t; - pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) - -> ::ssize_t; - - pub fn timegm64(tm: *const ::tm) -> ::time64_t; -} - -cfg_if! { - if #[cfg(target_arch = "x86")] { - mod x86; - pub use self::x86::*; - } else if #[cfg(target_arch = "arm")] { - mod arm; - pub use self::arm::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/b32/x86.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/b32/x86.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/b32/x86.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/b32/x86.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,415 +0,0 @@ -pub type c_char = i8; -pub type wchar_t = i32; - -pub const O_DIRECT: ::c_int = 0x4000; -pub const O_DIRECTORY: ::c_int = 0x10000; -pub const O_NOFOLLOW: ::c_int = 0x20000; -pub const O_LARGEFILE: ::c_int = 0o0100000; - -pub const MAP_32BIT: ::c_int = 0x40; - -// Syscall table -pub const SYS_restart_syscall: ::c_long = 0; -pub const SYS_exit: ::c_long = 1; -pub const SYS_fork: ::c_long = 2; -pub const SYS_read: ::c_long = 3; -pub const SYS_write: ::c_long = 4; -pub const SYS_open: ::c_long = 5; -pub const SYS_close: ::c_long = 6; -pub const SYS_waitpid: ::c_long = 7; -pub const SYS_creat: ::c_long = 8; -pub const SYS_link: ::c_long = 9; -pub const SYS_unlink: ::c_long = 10; -pub const SYS_execve: ::c_long = 11; -pub const SYS_chdir: ::c_long = 12; -pub const SYS_time: ::c_long = 13; -pub const SYS_mknod: ::c_long = 14; -pub const SYS_chmod: ::c_long = 15; -pub const SYS_lchown: ::c_long = 16; -pub const SYS_break: ::c_long = 17; -pub const SYS_oldstat: ::c_long = 18; -pub const SYS_lseek: ::c_long = 19; -pub const SYS_getpid: ::c_long = 20; -pub const SYS_mount: ::c_long = 21; -pub const SYS_umount: ::c_long = 22; -pub const SYS_setuid: ::c_long = 23; -pub const SYS_getuid: ::c_long = 24; -pub const SYS_stime: ::c_long = 25; -pub const SYS_ptrace: ::c_long = 26; -pub const SYS_alarm: ::c_long = 27; -pub const SYS_oldfstat: ::c_long = 28; -pub const SYS_pause: ::c_long = 29; -pub const SYS_utime: ::c_long = 30; -pub const SYS_stty: ::c_long = 31; -pub const SYS_gtty: ::c_long = 32; -pub const SYS_access: ::c_long = 33; -pub const SYS_nice: ::c_long = 34; -pub const SYS_ftime: ::c_long = 35; -pub const SYS_sync: ::c_long = 36; -pub const SYS_kill: ::c_long = 37; -pub const SYS_rename: ::c_long = 38; -pub const SYS_mkdir: ::c_long = 39; -pub const SYS_rmdir: ::c_long = 40; -pub const SYS_dup: ::c_long = 41; -pub const SYS_pipe: ::c_long = 42; -pub const SYS_times: ::c_long = 43; -pub const SYS_prof: ::c_long = 44; -pub const SYS_brk: ::c_long = 45; -pub const SYS_setgid: ::c_long = 46; -pub const SYS_getgid: ::c_long = 47; -pub const SYS_signal: ::c_long = 48; -pub const SYS_geteuid: ::c_long = 49; -pub const SYS_getegid: ::c_long = 50; -pub const SYS_acct: ::c_long = 51; -pub const SYS_umount2: ::c_long = 52; -pub const SYS_lock: ::c_long = 53; -pub const SYS_ioctl: ::c_long = 54; -pub const SYS_fcntl: ::c_long = 55; -pub const SYS_mpx: ::c_long = 56; -pub const SYS_setpgid: ::c_long = 57; -pub const SYS_ulimit: ::c_long = 58; -pub const SYS_oldolduname: ::c_long = 59; -pub const SYS_umask: ::c_long = 60; -pub const SYS_chroot: ::c_long = 61; -pub const SYS_ustat: ::c_long = 62; -pub const SYS_dup2: ::c_long = 63; -pub const SYS_getppid: ::c_long = 64; -pub const SYS_getpgrp: ::c_long = 65; -pub const SYS_setsid: ::c_long = 66; -pub const SYS_sigaction: ::c_long = 67; -pub const SYS_sgetmask: ::c_long = 68; -pub const SYS_ssetmask: ::c_long = 69; -pub const SYS_setreuid: ::c_long = 70; -pub const SYS_setregid: ::c_long = 71; -pub const SYS_sigsuspend: ::c_long = 72; -pub const SYS_sigpending: ::c_long = 73; -pub const SYS_sethostname: ::c_long = 74; -pub const SYS_setrlimit: ::c_long = 75; -pub const SYS_getrlimit: ::c_long = 76; -pub const SYS_getrusage: ::c_long = 77; -pub const SYS_gettimeofday: ::c_long = 78; -pub const SYS_settimeofday: ::c_long = 79; -pub const SYS_getgroups: ::c_long = 80; -pub const SYS_setgroups: ::c_long = 81; -pub const SYS_select: ::c_long = 82; -pub const SYS_symlink: ::c_long = 83; -pub const SYS_oldlstat: ::c_long = 84; -pub const SYS_readlink: ::c_long = 85; -pub const SYS_uselib: ::c_long = 86; -pub const SYS_swapon: ::c_long = 87; -pub const SYS_reboot: ::c_long = 88; -pub const SYS_readdir: ::c_long = 89; -pub const SYS_mmap: ::c_long = 90; -pub const SYS_munmap: ::c_long = 91; -pub const SYS_truncate: ::c_long = 92; -pub const SYS_ftruncate: ::c_long = 93; -pub const SYS_fchmod: ::c_long = 94; -pub const SYS_fchown: ::c_long = 95; -pub const SYS_getpriority: ::c_long = 96; -pub const SYS_setpriority: ::c_long = 97; -pub const SYS_profil: ::c_long = 98; -pub const SYS_statfs: ::c_long = 99; -pub const SYS_fstatfs: ::c_long = 100; -pub const SYS_ioperm: ::c_long = 101; -pub const SYS_socketcall: ::c_long = 102; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_setitimer: ::c_long = 104; -pub const SYS_getitimer: ::c_long = 105; -pub const SYS_stat: ::c_long = 106; -pub const SYS_lstat: ::c_long = 107; -pub const SYS_fstat: ::c_long = 108; -pub const SYS_olduname: ::c_long = 109; -pub const SYS_iopl: ::c_long = 110; -pub const SYS_vhangup: ::c_long = 111; -pub const SYS_idle: ::c_long = 112; -pub const SYS_vm86old: ::c_long = 113; -pub const SYS_wait4: ::c_long = 114; -pub const SYS_swapoff: ::c_long = 115; -pub const SYS_sysinfo: ::c_long = 116; -pub const SYS_ipc: ::c_long = 117; -pub const SYS_fsync: ::c_long = 118; -pub const SYS_sigreturn: ::c_long = 119; -pub const SYS_clone: ::c_long = 120; -pub const SYS_setdomainname: ::c_long = 121; -pub const SYS_uname: ::c_long = 122; -pub const SYS_modify_ldt: ::c_long = 123; -pub const SYS_adjtimex: ::c_long = 124; -pub const SYS_mprotect: ::c_long = 125; -pub const SYS_sigprocmask: ::c_long = 126; -pub const SYS_create_module: ::c_long = 127; -pub const SYS_init_module: ::c_long = 128; -pub const SYS_delete_module: ::c_long = 129; -pub const SYS_get_kernel_syms: ::c_long = 130; -pub const SYS_quotactl: ::c_long = 131; -pub const SYS_getpgid: ::c_long = 132; -pub const SYS_fchdir: ::c_long = 133; -pub const SYS_bdflush: ::c_long = 134; -pub const SYS_sysfs: ::c_long = 135; -pub const SYS_personality: ::c_long = 136; -pub const SYS_afs_syscall: ::c_long = 137; -pub const SYS_setfsuid: ::c_long = 138; -pub const SYS_setfsgid: ::c_long = 139; -// FIXME: SYS__llseek is in the NDK sources but for some reason is -// not available in the tests -// pub const SYS__llseek: ::c_long = 140; -pub const SYS_getdents: ::c_long = 141; -// FIXME: SYS__newselect is in the NDK sources but for some reason is -// not available in the tests -// pub const SYS__newselect: ::c_long = 142; -pub const SYS_flock: ::c_long = 143; -pub const SYS_msync: ::c_long = 144; -pub const SYS_readv: ::c_long = 145; -pub const SYS_writev: ::c_long = 146; -pub const SYS_getsid: ::c_long = 147; -pub const SYS_fdatasync: ::c_long = 148; -// FIXME: SYS__llseek is in the NDK sources but for some reason is -// not available in the tests -// pub const SYS__sysctl: ::c_long = 149; -pub const SYS_mlock: ::c_long = 150; -pub const SYS_munlock: ::c_long = 151; -pub const SYS_mlockall: ::c_long = 152; -pub const SYS_munlockall: ::c_long = 153; -pub const SYS_sched_setparam: ::c_long = 154; -pub const SYS_sched_getparam: ::c_long = 155; -pub const SYS_sched_setscheduler: ::c_long = 156; -pub const SYS_sched_getscheduler: ::c_long = 157; -pub const SYS_sched_yield: ::c_long = 158; -pub const SYS_sched_get_priority_max: ::c_long = 159; -pub const SYS_sched_get_priority_min: ::c_long = 160; -pub const SYS_sched_rr_get_interval: ::c_long = 161; -pub const SYS_nanosleep: ::c_long = 162; -pub const SYS_mremap: ::c_long = 163; -pub const SYS_setresuid: ::c_long = 164; -pub const SYS_getresuid: ::c_long = 165; -pub const SYS_vm86: ::c_long = 166; -pub const SYS_query_module: ::c_long = 167; -pub const SYS_poll: ::c_long = 168; -pub const SYS_nfsservctl: ::c_long = 169; -pub const SYS_setresgid: ::c_long = 170; -pub const SYS_getresgid: ::c_long = 171; -pub const SYS_prctl: ::c_long = 172; -pub const SYS_rt_sigreturn: ::c_long = 173; -pub const SYS_rt_sigaction: ::c_long = 174; -pub const SYS_rt_sigprocmask: ::c_long = 175; -pub const SYS_rt_sigpending: ::c_long = 176; -pub const SYS_rt_sigtimedwait: ::c_long = 177; -pub const SYS_rt_sigqueueinfo: ::c_long = 178; -pub const SYS_rt_sigsuspend: ::c_long = 179; -pub const SYS_pread64: ::c_long = 180; -pub const SYS_pwrite64: ::c_long = 181; -pub const SYS_chown: ::c_long = 182; -pub const SYS_getcwd: ::c_long = 183; -pub const SYS_capget: ::c_long = 184; -pub const SYS_capset: ::c_long = 185; -pub const SYS_sigaltstack: ::c_long = 186; -pub const SYS_sendfile: ::c_long = 187; -pub const SYS_getpmsg: ::c_long = 188; -pub const SYS_putpmsg: ::c_long = 189; -pub const SYS_vfork: ::c_long = 190; -pub const SYS_ugetrlimit: ::c_long = 191; -pub const SYS_mmap2: ::c_long = 192; -pub const SYS_truncate64: ::c_long = 193; -pub const SYS_ftruncate64: ::c_long = 194; -pub const SYS_stat64: ::c_long = 195; -pub const SYS_lstat64: ::c_long = 196; -pub const SYS_fstat64: ::c_long = 197; -pub const SYS_lchown32: ::c_long = 198; -pub const SYS_getuid32: ::c_long = 199; -pub const SYS_getgid32: ::c_long = 200; -pub const SYS_geteuid32: ::c_long = 201; -pub const SYS_getegid32: ::c_long = 202; -pub const SYS_setreuid32: ::c_long = 203; -pub const SYS_setregid32: ::c_long = 204; -pub const SYS_getgroups32: ::c_long = 205; -pub const SYS_setgroups32: ::c_long = 206; -pub const SYS_fchown32: ::c_long = 207; -pub const SYS_setresuid32: ::c_long = 208; -pub const SYS_getresuid32: ::c_long = 209; -pub const SYS_setresgid32: ::c_long = 210; -pub const SYS_getresgid32: ::c_long = 211; -pub const SYS_chown32: ::c_long = 212; -pub const SYS_setuid32: ::c_long = 213; -pub const SYS_setgid32: ::c_long = 214; -pub const SYS_setfsuid32: ::c_long = 215; -pub const SYS_setfsgid32: ::c_long = 216; -pub const SYS_pivot_root: ::c_long = 217; -pub const SYS_mincore: ::c_long = 218; -pub const SYS_madvise: ::c_long = 219; -pub const SYS_getdents64: ::c_long = 220; -pub const SYS_fcntl64: ::c_long = 221; -pub const SYS_gettid: ::c_long = 224; -pub const SYS_readahead: ::c_long = 225; -pub const SYS_setxattr: ::c_long = 226; -pub const SYS_lsetxattr: ::c_long = 227; -pub const SYS_fsetxattr: ::c_long = 228; -pub const SYS_getxattr: ::c_long = 229; -pub const SYS_lgetxattr: ::c_long = 230; -pub const SYS_fgetxattr: ::c_long = 231; -pub const SYS_listxattr: ::c_long = 232; -pub const SYS_llistxattr: ::c_long = 233; -pub const SYS_flistxattr: ::c_long = 234; -pub const SYS_removexattr: ::c_long = 235; -pub const SYS_lremovexattr: ::c_long = 236; -pub const SYS_fremovexattr: ::c_long = 237; -pub const SYS_tkill: ::c_long = 238; -pub const SYS_sendfile64: ::c_long = 239; -pub const SYS_futex: ::c_long = 240; -pub const SYS_sched_setaffinity: ::c_long = 241; -pub const SYS_sched_getaffinity: ::c_long = 242; -pub const SYS_set_thread_area: ::c_long = 243; -pub const SYS_get_thread_area: ::c_long = 244; -pub const SYS_io_setup: ::c_long = 245; -pub const SYS_io_destroy: ::c_long = 246; -pub const SYS_io_getevents: ::c_long = 247; -pub const SYS_io_submit: ::c_long = 248; -pub const SYS_io_cancel: ::c_long = 249; -pub const SYS_fadvise64: ::c_long = 250; -pub const SYS_exit_group: ::c_long = 252; -pub const SYS_lookup_dcookie: ::c_long = 253; -pub const SYS_epoll_create: ::c_long = 254; -pub const SYS_epoll_ctl: ::c_long = 255; -pub const SYS_epoll_wait: ::c_long = 256; -pub const SYS_remap_file_pages: ::c_long = 257; -pub const SYS_set_tid_address: ::c_long = 258; -pub const SYS_timer_create: ::c_long = 259; -pub const SYS_timer_settime: ::c_long = 260; -pub const SYS_timer_gettime: ::c_long = 261; -pub const SYS_timer_getoverrun: ::c_long = 262; -pub const SYS_timer_delete: ::c_long = 263; -pub const SYS_clock_settime: ::c_long = 264; -pub const SYS_clock_gettime: ::c_long = 265; -pub const SYS_clock_getres: ::c_long = 266; -pub const SYS_clock_nanosleep: ::c_long = 267; -pub const SYS_statfs64: ::c_long = 268; -pub const SYS_fstatfs64: ::c_long = 269; -pub const SYS_tgkill: ::c_long = 270; -pub const SYS_utimes: ::c_long = 271; -pub const SYS_fadvise64_64: ::c_long = 272; -pub const SYS_vserver: ::c_long = 273; -pub const SYS_mbind: ::c_long = 274; -pub const SYS_get_mempolicy: ::c_long = 275; -pub const SYS_set_mempolicy: ::c_long = 276; -pub const SYS_mq_open: ::c_long = 277; -pub const SYS_mq_unlink: ::c_long = 278; -pub const SYS_mq_timedsend: ::c_long = 279; -pub const SYS_mq_timedreceive: ::c_long = 280; -pub const SYS_mq_notify: ::c_long = 281; -pub const SYS_mq_getsetattr: ::c_long = 282; -pub const SYS_kexec_load: ::c_long = 283; -pub const SYS_waitid: ::c_long = 284; -pub const SYS_add_key: ::c_long = 286; -pub const SYS_request_key: ::c_long = 287; -pub const SYS_keyctl: ::c_long = 288; -pub const SYS_ioprio_set: ::c_long = 289; -pub const SYS_ioprio_get: ::c_long = 290; -pub const SYS_inotify_init: ::c_long = 291; -pub const SYS_inotify_add_watch: ::c_long = 292; -pub const SYS_inotify_rm_watch: ::c_long = 293; -pub const SYS_migrate_pages: ::c_long = 294; -pub const SYS_openat: ::c_long = 295; -pub const SYS_mkdirat: ::c_long = 296; -pub const SYS_mknodat: ::c_long = 297; -pub const SYS_fchownat: ::c_long = 298; -pub const SYS_futimesat: ::c_long = 299; -pub const SYS_fstatat64: ::c_long = 300; -pub const SYS_unlinkat: ::c_long = 301; -pub const SYS_renameat: ::c_long = 302; -pub const SYS_linkat: ::c_long = 303; -pub const SYS_symlinkat: ::c_long = 304; -pub const SYS_readlinkat: ::c_long = 305; -pub const SYS_fchmodat: ::c_long = 306; -pub const SYS_faccessat: ::c_long = 307; -pub const SYS_pselect6: ::c_long = 308; -pub const SYS_ppoll: ::c_long = 309; -pub const SYS_unshare: ::c_long = 310; -pub const SYS_set_robust_list: ::c_long = 311; -pub const SYS_get_robust_list: ::c_long = 312; -pub const SYS_splice: ::c_long = 313; -pub const SYS_sync_file_range: ::c_long = 314; -pub const SYS_tee: ::c_long = 315; -pub const SYS_vmsplice: ::c_long = 316; -pub const SYS_move_pages: ::c_long = 317; -pub const SYS_getcpu: ::c_long = 318; -pub const SYS_epoll_pwait: ::c_long = 319; -pub const SYS_utimensat: ::c_long = 320; -pub const SYS_signalfd: ::c_long = 321; -pub const SYS_timerfd_create: ::c_long = 322; -pub const SYS_eventfd: ::c_long = 323; -pub const SYS_fallocate: ::c_long = 324; -pub const SYS_timerfd_settime: ::c_long = 325; -pub const SYS_timerfd_gettime: ::c_long = 326; -pub const SYS_signalfd4: ::c_long = 327; -pub const SYS_eventfd2: ::c_long = 328; -pub const SYS_epoll_create1: ::c_long = 329; -pub const SYS_dup3: ::c_long = 330; -pub const SYS_pipe2: ::c_long = 331; -pub const SYS_inotify_init1: ::c_long = 332; -pub const SYS_preadv: ::c_long = 333; -pub const SYS_pwritev: ::c_long = 334; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 335; -pub const SYS_perf_event_open: ::c_long = 336; -pub const SYS_recvmmsg: ::c_long = 337; -pub const SYS_fanotify_init: ::c_long = 338; -pub const SYS_fanotify_mark: ::c_long = 339; -pub const SYS_prlimit64: ::c_long = 340; -pub const SYS_name_to_handle_at: ::c_long = 341; -pub const SYS_open_by_handle_at: ::c_long = 342; -pub const SYS_clock_adjtime: ::c_long = 343; -pub const SYS_syncfs: ::c_long = 344; -pub const SYS_sendmmsg: ::c_long = 345; -pub const SYS_setns: ::c_long = 346; -pub const SYS_process_vm_readv: ::c_long = 347; -pub const SYS_process_vm_writev: ::c_long = 348; -pub const SYS_kcmp: ::c_long = 349; -pub const SYS_finit_module: ::c_long = 350; -pub const SYS_sched_setattr: ::c_long = 351; -pub const SYS_sched_getattr: ::c_long = 352; -pub const SYS_renameat2: ::c_long = 353; -pub const SYS_seccomp: ::c_long = 354; -pub const SYS_getrandom: ::c_long = 355; -pub const SYS_memfd_create: ::c_long = 356; -pub const SYS_bpf: ::c_long = 357; -pub const SYS_execveat: ::c_long = 358; -pub const SYS_socket: ::c_long = 359; -pub const SYS_socketpair: ::c_long = 360; -pub const SYS_bind: ::c_long = 361; -pub const SYS_connect: ::c_long = 362; -pub const SYS_listen: ::c_long = 363; -pub const SYS_accept4: ::c_long = 364; -pub const SYS_getsockopt: ::c_long = 365; -pub const SYS_setsockopt: ::c_long = 366; -pub const SYS_getsockname: ::c_long = 367; -pub const SYS_getpeername: ::c_long = 368; -pub const SYS_sendto: ::c_long = 369; -pub const SYS_sendmsg: ::c_long = 370; -pub const SYS_recvfrom: ::c_long = 371; -pub const SYS_recvmsg: ::c_long = 372; -pub const SYS_shutdown: ::c_long = 373; -pub const SYS_userfaultfd: ::c_long = 374; -pub const SYS_membarrier: ::c_long = 375; -pub const SYS_mlock2: ::c_long = 376; -pub const SYS_copy_file_range: ::c_long = 377; -pub const SYS_preadv2: ::c_long = 378; -pub const SYS_pwritev2: ::c_long = 379; -pub const SYS_pkey_mprotect: ::c_long = 380; -pub const SYS_pkey_alloc: ::c_long = 381; -pub const SYS_pkey_free: ::c_long = 382; - -// offsets in user_regs_structs, from sys/reg.h -pub const EBX: ::c_int = 0; -pub const ECX: ::c_int = 1; -pub const EDX: ::c_int = 2; -pub const ESI: ::c_int = 3; -pub const EDI: ::c_int = 4; -pub const EBP: ::c_int = 5; -pub const EAX: ::c_int = 6; -pub const DS: ::c_int = 7; -pub const ES: ::c_int = 8; -pub const FS: ::c_int = 9; -pub const GS: ::c_int = 10; -pub const ORIG_EAX: ::c_int = 11; -pub const EIP: ::c_int = 12; -pub const CS: ::c_int = 13; -pub const EFL: ::c_int = 14; -pub const UESP: ::c_int = 15; -pub const SS: ::c_int = 16; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/b64/aarch64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/b64/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/b64/aarch64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/b64/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,325 +0,0 @@ -pub type c_char = u8; -pub type wchar_t = u32; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::c_uint, - pub st_nlink: ::c_uint, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad1: ::c_ulong, - pub st_size: ::off64_t, - pub st_blksize: ::c_int, - __pad2: ::c_int, - pub st_blocks: ::c_long, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_ulong, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_ulong, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_ulong, - __unused4: ::c_uint, - __unused5: ::c_uint, - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::c_uint, - pub st_nlink: ::c_uint, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad1: ::c_ulong, - pub st_size: ::off64_t, - pub st_blksize: ::c_int, - __pad2: ::c_int, - pub st_blocks: ::c_long, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_ulong, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_ulong, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_ulong, - __unused4: ::c_uint, - __unused5: ::c_uint, - } -} - -pub const O_DIRECT: ::c_int = 0x10000; -pub const O_DIRECTORY: ::c_int = 0x4000; -pub const O_NOFOLLOW: ::c_int = 0x8000; -pub const O_LARGEFILE: ::c_int = 0o400000; - -pub const SIGSTKSZ: ::size_t = 16384; -pub const MINSIGSTKSZ: ::size_t = 5120; - -pub const SYS_io_setup: ::c_long = 0; -pub const SYS_io_destroy: ::c_long = 1; -pub const SYS_io_submit: ::c_long = 2; -pub const SYS_io_cancel: ::c_long = 3; -pub const SYS_io_getevents: ::c_long = 4; -pub const SYS_setxattr: ::c_long = 5; -pub const SYS_lsetxattr: ::c_long = 6; -pub const SYS_fsetxattr: ::c_long = 7; -pub const SYS_getxattr: ::c_long = 8; -pub const SYS_lgetxattr: ::c_long = 9; -pub const SYS_fgetxattr: ::c_long = 10; -pub const SYS_listxattr: ::c_long = 11; -pub const SYS_llistxattr: ::c_long = 12; -pub const SYS_flistxattr: ::c_long = 13; -pub const SYS_removexattr: ::c_long = 14; -pub const SYS_lremovexattr: ::c_long = 15; -pub const SYS_fremovexattr: ::c_long = 16; -pub const SYS_getcwd: ::c_long = 17; -pub const SYS_lookup_dcookie: ::c_long = 18; -pub const SYS_eventfd2: ::c_long = 19; -pub const SYS_epoll_create1: ::c_long = 20; -pub const SYS_epoll_ctl: ::c_long = 21; -pub const SYS_epoll_pwait: ::c_long = 22; -pub const SYS_dup: ::c_long = 23; -pub const SYS_dup3: ::c_long = 24; -pub const SYS_inotify_init1: ::c_long = 26; -pub const SYS_inotify_add_watch: ::c_long = 27; -pub const SYS_inotify_rm_watch: ::c_long = 28; -pub const SYS_ioctl: ::c_long = 29; -pub const SYS_ioprio_set: ::c_long = 30; -pub const SYS_ioprio_get: ::c_long = 31; -pub const SYS_flock: ::c_long = 32; -pub const SYS_mknodat: ::c_long = 33; -pub const SYS_mkdirat: ::c_long = 34; -pub const SYS_unlinkat: ::c_long = 35; -pub const SYS_symlinkat: ::c_long = 36; -pub const SYS_linkat: ::c_long = 37; -pub const SYS_renameat: ::c_long = 38; -pub const SYS_umount2: ::c_long = 39; -pub const SYS_mount: ::c_long = 40; -pub const SYS_pivot_root: ::c_long = 41; -pub const SYS_nfsservctl: ::c_long = 42; -pub const SYS_fallocate: ::c_long = 47; -pub const SYS_faccessat: ::c_long = 48; -pub const SYS_chdir: ::c_long = 49; -pub const SYS_fchdir: ::c_long = 50; -pub const SYS_chroot: ::c_long = 51; -pub const SYS_fchmod: ::c_long = 52; -pub const SYS_fchmodat: ::c_long = 53; -pub const SYS_fchownat: ::c_long = 54; -pub const SYS_fchown: ::c_long = 55; -pub const SYS_openat: ::c_long = 56; -pub const SYS_close: ::c_long = 57; -pub const SYS_vhangup: ::c_long = 58; -pub const SYS_pipe2: ::c_long = 59; -pub const SYS_quotactl: ::c_long = 60; -pub const SYS_getdents64: ::c_long = 61; -pub const SYS_read: ::c_long = 63; -pub const SYS_write: ::c_long = 64; -pub const SYS_readv: ::c_long = 65; -pub const SYS_writev: ::c_long = 66; -pub const SYS_pread64: ::c_long = 67; -pub const SYS_pwrite64: ::c_long = 68; -pub const SYS_preadv: ::c_long = 69; -pub const SYS_pwritev: ::c_long = 70; -pub const SYS_pselect6: ::c_long = 72; -pub const SYS_ppoll: ::c_long = 73; -pub const SYS_signalfd4: ::c_long = 74; -pub const SYS_vmsplice: ::c_long = 75; -pub const SYS_splice: ::c_long = 76; -pub const SYS_tee: ::c_long = 77; -pub const SYS_readlinkat: ::c_long = 78; -pub const SYS_sync: ::c_long = 81; -pub const SYS_fsync: ::c_long = 82; -pub const SYS_fdatasync: ::c_long = 83; -pub const SYS_sync_file_range: ::c_long = 84; -pub const SYS_timerfd_create: ::c_long = 85; -pub const SYS_timerfd_settime: ::c_long = 86; -pub const SYS_timerfd_gettime: ::c_long = 87; -pub const SYS_utimensat: ::c_long = 88; -pub const SYS_acct: ::c_long = 89; -pub const SYS_capget: ::c_long = 90; -pub const SYS_capset: ::c_long = 91; -pub const SYS_personality: ::c_long = 92; -pub const SYS_exit: ::c_long = 93; -pub const SYS_exit_group: ::c_long = 94; -pub const SYS_waitid: ::c_long = 95; -pub const SYS_set_tid_address: ::c_long = 96; -pub const SYS_unshare: ::c_long = 97; -pub const SYS_futex: ::c_long = 98; -pub const SYS_set_robust_list: ::c_long = 99; -pub const SYS_get_robust_list: ::c_long = 100; -pub const SYS_nanosleep: ::c_long = 101; -pub const SYS_getitimer: ::c_long = 102; -pub const SYS_setitimer: ::c_long = 103; -pub const SYS_kexec_load: ::c_long = 104; -pub const SYS_init_module: ::c_long = 105; -pub const SYS_delete_module: ::c_long = 106; -pub const SYS_timer_create: ::c_long = 107; -pub const SYS_timer_gettime: ::c_long = 108; -pub const SYS_timer_getoverrun: ::c_long = 109; -pub const SYS_timer_settime: ::c_long = 110; -pub const SYS_timer_delete: ::c_long = 111; -pub const SYS_clock_settime: ::c_long = 112; -pub const SYS_clock_gettime: ::c_long = 113; -pub const SYS_clock_getres: ::c_long = 114; -pub const SYS_clock_nanosleep: ::c_long = 115; -pub const SYS_syslog: ::c_long = 116; -pub const SYS_ptrace: ::c_long = 117; -pub const SYS_sched_setparam: ::c_long = 118; -pub const SYS_sched_setscheduler: ::c_long = 119; -pub const SYS_sched_getscheduler: ::c_long = 120; -pub const SYS_sched_getparam: ::c_long = 121; -pub const SYS_sched_setaffinity: ::c_long = 122; -pub const SYS_sched_getaffinity: ::c_long = 123; -pub const SYS_sched_yield: ::c_long = 124; -pub const SYS_sched_get_priority_max: ::c_long = 125; -pub const SYS_sched_get_priority_min: ::c_long = 126; -pub const SYS_sched_rr_get_interval: ::c_long = 127; -pub const SYS_restart_syscall: ::c_long = 128; -pub const SYS_kill: ::c_long = 129; -pub const SYS_tkill: ::c_long = 130; -pub const SYS_tgkill: ::c_long = 131; -pub const SYS_sigaltstack: ::c_long = 132; -pub const SYS_rt_sigsuspend: ::c_long = 133; -pub const SYS_rt_sigaction: ::c_long = 134; -pub const SYS_rt_sigprocmask: ::c_long = 135; -pub const SYS_rt_sigpending: ::c_long = 136; -pub const SYS_rt_sigtimedwait: ::c_long = 137; -pub const SYS_rt_sigqueueinfo: ::c_long = 138; -pub const SYS_rt_sigreturn: ::c_long = 139; -pub const SYS_setpriority: ::c_long = 140; -pub const SYS_getpriority: ::c_long = 141; -pub const SYS_reboot: ::c_long = 142; -pub const SYS_setregid: ::c_long = 143; -pub const SYS_setgid: ::c_long = 144; -pub const SYS_setreuid: ::c_long = 145; -pub const SYS_setuid: ::c_long = 146; -pub const SYS_setresuid: ::c_long = 147; -pub const SYS_getresuid: ::c_long = 148; -pub const SYS_setresgid: ::c_long = 149; -pub const SYS_getresgid: ::c_long = 150; -pub const SYS_setfsuid: ::c_long = 151; -pub const SYS_setfsgid: ::c_long = 152; -pub const SYS_times: ::c_long = 153; -pub const SYS_setpgid: ::c_long = 154; -pub const SYS_getpgid: ::c_long = 155; -pub const SYS_getsid: ::c_long = 156; -pub const SYS_setsid: ::c_long = 157; -pub const SYS_getgroups: ::c_long = 158; -pub const SYS_setgroups: ::c_long = 159; -pub const SYS_uname: ::c_long = 160; -pub const SYS_sethostname: ::c_long = 161; -pub const SYS_setdomainname: ::c_long = 162; -pub const SYS_getrlimit: ::c_long = 163; -pub const SYS_setrlimit: ::c_long = 164; -pub const SYS_getrusage: ::c_long = 165; -pub const SYS_umask: ::c_long = 166; -pub const SYS_prctl: ::c_long = 167; -pub const SYS_getcpu: ::c_long = 168; -pub const SYS_gettimeofday: ::c_long = 169; -pub const SYS_settimeofday: ::c_long = 170; -pub const SYS_adjtimex: ::c_long = 171; -pub const SYS_getpid: ::c_long = 172; -pub const SYS_getppid: ::c_long = 173; -pub const SYS_getuid: ::c_long = 174; -pub const SYS_geteuid: ::c_long = 175; -pub const SYS_getgid: ::c_long = 176; -pub const SYS_getegid: ::c_long = 177; -pub const SYS_gettid: ::c_long = 178; -pub const SYS_sysinfo: ::c_long = 179; -pub const SYS_mq_open: ::c_long = 180; -pub const SYS_mq_unlink: ::c_long = 181; -pub const SYS_mq_timedsend: ::c_long = 182; -pub const SYS_mq_timedreceive: ::c_long = 183; -pub const SYS_mq_notify: ::c_long = 184; -pub const SYS_mq_getsetattr: ::c_long = 185; -pub const SYS_msgget: ::c_long = 186; -pub const SYS_msgctl: ::c_long = 187; -pub const SYS_msgrcv: ::c_long = 188; -pub const SYS_msgsnd: ::c_long = 189; -pub const SYS_semget: ::c_long = 190; -pub const SYS_semctl: ::c_long = 191; -pub const SYS_semtimedop: ::c_long = 192; -pub const SYS_semop: ::c_long = 193; -pub const SYS_shmget: ::c_long = 194; -pub const SYS_shmctl: ::c_long = 195; -pub const SYS_shmat: ::c_long = 196; -pub const SYS_shmdt: ::c_long = 197; -pub const SYS_socket: ::c_long = 198; -pub const SYS_socketpair: ::c_long = 199; -pub const SYS_bind: ::c_long = 200; -pub const SYS_listen: ::c_long = 201; -pub const SYS_accept: ::c_long = 202; -pub const SYS_connect: ::c_long = 203; -pub const SYS_getsockname: ::c_long = 204; -pub const SYS_getpeername: ::c_long = 205; -pub const SYS_sendto: ::c_long = 206; -pub const SYS_recvfrom: ::c_long = 207; -pub const SYS_setsockopt: ::c_long = 208; -pub const SYS_getsockopt: ::c_long = 209; -pub const SYS_shutdown: ::c_long = 210; -pub const SYS_sendmsg: ::c_long = 211; -pub const SYS_recvmsg: ::c_long = 212; -pub const SYS_readahead: ::c_long = 213; -pub const SYS_brk: ::c_long = 214; -pub const SYS_munmap: ::c_long = 215; -pub const SYS_mremap: ::c_long = 216; -pub const SYS_add_key: ::c_long = 217; -pub const SYS_request_key: ::c_long = 218; -pub const SYS_keyctl: ::c_long = 219; -pub const SYS_clone: ::c_long = 220; -pub const SYS_execve: ::c_long = 221; -pub const SYS_swapon: ::c_long = 224; -pub const SYS_swapoff: ::c_long = 225; -pub const SYS_mprotect: ::c_long = 226; -pub const SYS_msync: ::c_long = 227; -pub const SYS_mlock: ::c_long = 228; -pub const SYS_munlock: ::c_long = 229; -pub const SYS_mlockall: ::c_long = 230; -pub const SYS_munlockall: ::c_long = 231; -pub const SYS_mincore: ::c_long = 232; -pub const SYS_madvise: ::c_long = 233; -pub const SYS_remap_file_pages: ::c_long = 234; -pub const SYS_mbind: ::c_long = 235; -pub const SYS_get_mempolicy: ::c_long = 236; -pub const SYS_set_mempolicy: ::c_long = 237; -pub const SYS_migrate_pages: ::c_long = 238; -pub const SYS_move_pages: ::c_long = 239; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 240; -pub const SYS_perf_event_open: ::c_long = 241; -pub const SYS_accept4: ::c_long = 242; -pub const SYS_recvmmsg: ::c_long = 243; -pub const SYS_arch_specific_syscall: ::c_long = 244; -pub const SYS_wait4: ::c_long = 260; -pub const SYS_prlimit64: ::c_long = 261; -pub const SYS_fanotify_init: ::c_long = 262; -pub const SYS_fanotify_mark: ::c_long = 263; -pub const SYS_name_to_handle_at: ::c_long = 264; -pub const SYS_open_by_handle_at: ::c_long = 265; -pub const SYS_clock_adjtime: ::c_long = 266; -pub const SYS_syncfs: ::c_long = 267; -pub const SYS_setns: ::c_long = 268; -pub const SYS_sendmmsg: ::c_long = 269; -pub const SYS_process_vm_readv: ::c_long = 270; -pub const SYS_process_vm_writev: ::c_long = 271; -pub const SYS_kcmp: ::c_long = 272; -pub const SYS_finit_module: ::c_long = 273; -pub const SYS_sched_setattr: ::c_long = 274; -pub const SYS_sched_getattr: ::c_long = 275; -pub const SYS_renameat2: ::c_long = 276; -pub const SYS_seccomp: ::c_long = 277; -pub const SYS_getrandom: ::c_long = 278; -pub const SYS_memfd_create: ::c_long = 279; -pub const SYS_bpf: ::c_long = 280; -pub const SYS_execveat: ::c_long = 281; -pub const SYS_userfaultfd: ::c_long = 282; -pub const SYS_membarrier: ::c_long = 283; -pub const SYS_mlock2: ::c_long = 284; -pub const SYS_copy_file_range: ::c_long = 285; -pub const SYS_preadv2: ::c_long = 286; -pub const SYS_pwritev2: ::c_long = 287; -pub const SYS_pkey_mprotect: ::c_long = 288; -pub const SYS_pkey_alloc: ::c_long = 289; -pub const SYS_pkey_free: ::c_long = 290; -pub const SYS_syscalls: ::c_long = 291; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/b64/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/b64/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/b64/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/b64/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,192 +0,0 @@ -// The following definitions are correct for aarch64 and x86_64, -// but may be wrong for mips64 - -pub type c_long = i64; -pub type c_ulong = u64; -pub type mode_t = u32; -pub type off64_t = i64; -pub type socklen_t = u32; - -s! { - pub struct sigset_t { - __val: [::c_ulong; 1], - } - - pub struct sigaction { - pub sa_flags: ::c_uint, - pub sa_sigaction: ::sighandler_t, - pub sa_mask: ::sigset_t, - pub sa_restorer: ::dox::Option, - } - - pub struct rlimit64 { - pub rlim_cur: ::c_ulonglong, - pub rlim_max: ::c_ulonglong, - } - - pub struct pthread_attr_t { - pub flags: ::uint32_t, - pub stack_base: *mut ::c_void, - pub stack_size: ::size_t, - pub guard_size: ::size_t, - pub sched_policy: ::int32_t, - pub sched_priority: ::int32_t, - __reserved: [::c_char; 16], - } - - pub struct pthread_mutex_t { - value: ::c_int, - __reserved: [::c_char; 36], - } - - pub struct pthread_cond_t { - value: ::c_int, - __reserved: [::c_char; 44], - } - - pub struct pthread_rwlock_t { - numLocks: ::c_int, - writerThreadId: ::c_int, - pendingReaders: ::c_int, - pendingWriters: ::c_int, - attr: i32, - __reserved: [::c_char; 36], - } - - pub struct passwd { - pub pw_name: *mut ::c_char, - pub pw_passwd: *mut ::c_char, - pub pw_uid: ::uid_t, - pub pw_gid: ::gid_t, - pub pw_gecos: *mut ::c_char, - pub pw_dir: *mut ::c_char, - pub pw_shell: *mut ::c_char, - } - - pub struct statfs { - pub f_type: ::uint64_t, - pub f_bsize: ::uint64_t, - pub f_blocks: ::uint64_t, - pub f_bfree: ::uint64_t, - pub f_bavail: ::uint64_t, - pub f_files: ::uint64_t, - pub f_ffree: ::uint64_t, - pub f_fsid: ::__fsid_t, - pub f_namelen: ::uint64_t, - pub f_frsize: ::uint64_t, - pub f_flags: ::uint64_t, - pub f_spare: [::uint64_t; 4], - } - - pub struct sysinfo { - pub uptime: ::c_long, - pub loads: [::c_ulong; 3], - pub totalram: ::c_ulong, - pub freeram: ::c_ulong, - pub sharedram: ::c_ulong, - pub bufferram: ::c_ulong, - pub totalswap: ::c_ulong, - pub freeswap: ::c_ulong, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: ::c_ulong, - pub freehigh: ::c_ulong, - pub mem_unit: ::c_uint, - pub _f: [::c_char; 0], - } - - pub struct statfs64 { - pub f_type: u64, - pub f_bsize: u64, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - f_fsid: [u32; 2], - pub f_namelen: u64, - pub f_frsize: u64, - pub f_flags: u64, - pub f_spare: [u64; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } -} - -pub const RTLD_GLOBAL: ::c_int = 0x00100; -pub const RTLD_NOW: ::c_int = 2; -pub const RTLD_DEFAULT: *mut ::c_void = 0i64 as *mut ::c_void; - -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { - value: 0, - __reserved: [0; 36], -}; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { - value: 0, - __reserved: [0; 44], -}; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { - numLocks: 0, - writerThreadId: 0, - pendingReaders: 0, - pendingWriters: 0, - attr: 0, - __reserved: [0; 36], -}; -pub const PTHREAD_STACK_MIN: ::size_t = 4096 * 4; -pub const CPU_SETSIZE: ::size_t = 1024; -pub const __CPU_BITS: ::size_t = 64; - -pub const UT_LINESIZE: usize = 32; -pub const UT_NAMESIZE: usize = 32; -pub const UT_HOSTSIZE: usize = 256; - -// Some weirdness in Android -extern { - // address_len should be socklen_t, but it is c_int! - pub fn bind(socket: ::c_int, address: *const ::sockaddr, - address_len: ::c_int) -> ::c_int; - - // the return type should be ::ssize_t, but it is c_int! - pub fn writev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::c_int; - - // the return type should be ::ssize_t, but it is c_int! - pub fn readv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::c_int; - - // the return type should be ::ssize_t, but it is c_int! - pub fn sendmsg(fd: ::c_int, - msg: *const ::msghdr, - flags: ::c_int) -> ::c_int; - - // the return type should be ::ssize_t, but it is c_int! - pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) -> ::c_int; -} - -cfg_if! { - if #[cfg(target_arch = "x86_64")] { - mod x86_64; - pub use self::x86_64::*; - } else if #[cfg(target_arch = "aarch64")] { - mod aarch64; - pub use self::aarch64::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/b64/x86_64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/b64/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/b64/x86_64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/b64/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,420 +0,0 @@ -pub type c_char = i8; -pub type wchar_t = i32; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_nlink: ::c_ulong, - pub st_mode: ::c_uint, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - pub st_size: ::off64_t, - pub st_blksize: ::c_long, - pub st_blocks: ::c_long, - pub st_atime: ::c_ulong, - pub st_atime_nsec: ::c_ulong, - pub st_mtime: ::c_ulong, - pub st_mtime_nsec: ::c_ulong, - pub st_ctime: ::c_ulong, - pub st_ctime_nsec: ::c_ulong, - __unused: [::c_long; 3], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_nlink: ::c_ulong, - pub st_mode: ::c_uint, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - pub st_size: ::off64_t, - pub st_blksize: ::c_long, - pub st_blocks: ::c_long, - pub st_atime: ::c_ulong, - pub st_atime_nsec: ::c_ulong, - pub st_mtime: ::c_ulong, - pub st_mtime_nsec: ::c_ulong, - pub st_ctime: ::c_ulong, - pub st_ctime_nsec: ::c_ulong, - __unused: [::c_long; 3], - } -} - -pub const O_DIRECT: ::c_int = 0x4000; -pub const O_DIRECTORY: ::c_int = 0x10000; -pub const O_NOFOLLOW: ::c_int = 0x20000; -pub const O_LARGEFILE: ::c_int = 0o0100000; - -pub const SIGSTKSZ: ::size_t = 8192; -pub const MINSIGSTKSZ: ::size_t = 2048; - -pub const MAP_32BIT: ::c_int = 0x40; - -// Syscall table - -pub const SYS_read: ::c_long = 0; -pub const SYS_write: ::c_long = 1; -pub const SYS_open: ::c_long = 2; -pub const SYS_close: ::c_long = 3; -pub const SYS_stat: ::c_long = 4; -pub const SYS_fstat: ::c_long = 5; -pub const SYS_lstat: ::c_long = 6; -pub const SYS_poll: ::c_long = 7; -pub const SYS_lseek: ::c_long = 8; -pub const SYS_mmap: ::c_long = 9; -pub const SYS_mprotect: ::c_long = 10; -pub const SYS_munmap: ::c_long = 11; -pub const SYS_brk: ::c_long = 12; -pub const SYS_rt_sigaction: ::c_long = 13; -pub const SYS_rt_sigprocmask: ::c_long = 14; -pub const SYS_rt_sigreturn: ::c_long = 15; -pub const SYS_ioctl: ::c_long = 16; -pub const SYS_pread64: ::c_long = 17; -pub const SYS_pwrite64: ::c_long = 18; -pub const SYS_readv: ::c_long = 19; -pub const SYS_writev: ::c_long = 20; -pub const SYS_access: ::c_long = 21; -pub const SYS_pipe: ::c_long = 22; -pub const SYS_select: ::c_long = 23; -pub const SYS_sched_yield: ::c_long = 24; -pub const SYS_mremap: ::c_long = 25; -pub const SYS_msync: ::c_long = 26; -pub const SYS_mincore: ::c_long = 27; -pub const SYS_madvise: ::c_long = 28; -pub const SYS_shmget: ::c_long = 29; -pub const SYS_shmat: ::c_long = 30; -pub const SYS_shmctl: ::c_long = 31; -pub const SYS_dup: ::c_long = 32; -pub const SYS_dup2: ::c_long = 33; -pub const SYS_pause: ::c_long = 34; -pub const SYS_nanosleep: ::c_long = 35; -pub const SYS_getitimer: ::c_long = 36; -pub const SYS_alarm: ::c_long = 37; -pub const SYS_setitimer: ::c_long = 38; -pub const SYS_getpid: ::c_long = 39; -pub const SYS_sendfile: ::c_long = 40; -pub const SYS_socket: ::c_long = 41; -pub const SYS_connect: ::c_long = 42; -pub const SYS_accept: ::c_long = 43; -pub const SYS_sendto: ::c_long = 44; -pub const SYS_recvfrom: ::c_long = 45; -pub const SYS_sendmsg: ::c_long = 46; -pub const SYS_recvmsg: ::c_long = 47; -pub const SYS_shutdown: ::c_long = 48; -pub const SYS_bind: ::c_long = 49; -pub const SYS_listen: ::c_long = 50; -pub const SYS_getsockname: ::c_long = 51; -pub const SYS_getpeername: ::c_long = 52; -pub const SYS_socketpair: ::c_long = 53; -pub const SYS_setsockopt: ::c_long = 54; -pub const SYS_getsockopt: ::c_long = 55; -pub const SYS_clone: ::c_long = 56; -pub const SYS_fork: ::c_long = 57; -pub const SYS_vfork: ::c_long = 58; -pub const SYS_execve: ::c_long = 59; -pub const SYS_exit: ::c_long = 60; -pub const SYS_wait4: ::c_long = 61; -pub const SYS_kill: ::c_long = 62; -pub const SYS_uname: ::c_long = 63; -pub const SYS_semget: ::c_long = 64; -pub const SYS_semop: ::c_long = 65; -pub const SYS_semctl: ::c_long = 66; -pub const SYS_shmdt: ::c_long = 67; -pub const SYS_msgget: ::c_long = 68; -pub const SYS_msgsnd: ::c_long = 69; -pub const SYS_msgrcv: ::c_long = 70; -pub const SYS_msgctl: ::c_long = 71; -pub const SYS_fcntl: ::c_long = 72; -pub const SYS_flock: ::c_long = 73; -pub const SYS_fsync: ::c_long = 74; -pub const SYS_fdatasync: ::c_long = 75; -pub const SYS_truncate: ::c_long = 76; -pub const SYS_ftruncate: ::c_long = 77; -pub const SYS_getdents: ::c_long = 78; -pub const SYS_getcwd: ::c_long = 79; -pub const SYS_chdir: ::c_long = 80; -pub const SYS_fchdir: ::c_long = 81; -pub const SYS_rename: ::c_long = 82; -pub const SYS_mkdir: ::c_long = 83; -pub const SYS_rmdir: ::c_long = 84; -pub const SYS_creat: ::c_long = 85; -pub const SYS_link: ::c_long = 86; -pub const SYS_unlink: ::c_long = 87; -pub const SYS_symlink: ::c_long = 88; -pub const SYS_readlink: ::c_long = 89; -pub const SYS_chmod: ::c_long = 90; -pub const SYS_fchmod: ::c_long = 91; -pub const SYS_chown: ::c_long = 92; -pub const SYS_fchown: ::c_long = 93; -pub const SYS_lchown: ::c_long = 94; -pub const SYS_umask: ::c_long = 95; -pub const SYS_gettimeofday: ::c_long = 96; -pub const SYS_getrlimit: ::c_long = 97; -pub const SYS_getrusage: ::c_long = 98; -pub const SYS_sysinfo: ::c_long = 99; -pub const SYS_times: ::c_long = 100; -pub const SYS_ptrace: ::c_long = 101; -pub const SYS_getuid: ::c_long = 102; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_getgid: ::c_long = 104; -pub const SYS_setuid: ::c_long = 105; -pub const SYS_setgid: ::c_long = 106; -pub const SYS_geteuid: ::c_long = 107; -pub const SYS_getegid: ::c_long = 108; -pub const SYS_setpgid: ::c_long = 109; -pub const SYS_getppid: ::c_long = 110; -pub const SYS_getpgrp: ::c_long = 111; -pub const SYS_setsid: ::c_long = 112; -pub const SYS_setreuid: ::c_long = 113; -pub const SYS_setregid: ::c_long = 114; -pub const SYS_getgroups: ::c_long = 115; -pub const SYS_setgroups: ::c_long = 116; -pub const SYS_setresuid: ::c_long = 117; -pub const SYS_getresuid: ::c_long = 118; -pub const SYS_setresgid: ::c_long = 119; -pub const SYS_getresgid: ::c_long = 120; -pub const SYS_getpgid: ::c_long = 121; -pub const SYS_setfsuid: ::c_long = 122; -pub const SYS_setfsgid: ::c_long = 123; -pub const SYS_getsid: ::c_long = 124; -pub const SYS_capget: ::c_long = 125; -pub const SYS_capset: ::c_long = 126; -pub const SYS_rt_sigpending: ::c_long = 127; -pub const SYS_rt_sigtimedwait: ::c_long = 128; -pub const SYS_rt_sigqueueinfo: ::c_long = 129; -pub const SYS_rt_sigsuspend: ::c_long = 130; -pub const SYS_sigaltstack: ::c_long = 131; -pub const SYS_utime: ::c_long = 132; -pub const SYS_mknod: ::c_long = 133; -pub const SYS_uselib: ::c_long = 134; -pub const SYS_personality: ::c_long = 135; -pub const SYS_ustat: ::c_long = 136; -pub const SYS_statfs: ::c_long = 137; -pub const SYS_fstatfs: ::c_long = 138; -pub const SYS_sysfs: ::c_long = 139; -pub const SYS_getpriority: ::c_long = 140; -pub const SYS_setpriority: ::c_long = 141; -pub const SYS_sched_setparam: ::c_long = 142; -pub const SYS_sched_getparam: ::c_long = 143; -pub const SYS_sched_setscheduler: ::c_long = 144; -pub const SYS_sched_getscheduler: ::c_long = 145; -pub const SYS_sched_get_priority_max: ::c_long = 146; -pub const SYS_sched_get_priority_min: ::c_long = 147; -pub const SYS_sched_rr_get_interval: ::c_long = 148; -pub const SYS_mlock: ::c_long = 149; -pub const SYS_munlock: ::c_long = 150; -pub const SYS_mlockall: ::c_long = 151; -pub const SYS_munlockall: ::c_long = 152; -pub const SYS_vhangup: ::c_long = 153; -pub const SYS_modify_ldt: ::c_long = 154; -pub const SYS_pivot_root: ::c_long = 155; -// FIXME: SYS__sysctl is in the NDK sources but for some reason is -// not available in the tests -// pub const SYS__sysctl: ::c_long = 156; -pub const SYS_prctl: ::c_long = 157; -pub const SYS_arch_prctl: ::c_long = 158; -pub const SYS_adjtimex: ::c_long = 159; -pub const SYS_setrlimit: ::c_long = 160; -pub const SYS_chroot: ::c_long = 161; -pub const SYS_sync: ::c_long = 162; -pub const SYS_acct: ::c_long = 163; -pub const SYS_settimeofday: ::c_long = 164; -pub const SYS_mount: ::c_long = 165; -pub const SYS_umount2: ::c_long = 166; -pub const SYS_swapon: ::c_long = 167; -pub const SYS_swapoff: ::c_long = 168; -pub const SYS_reboot: ::c_long = 169; -pub const SYS_sethostname: ::c_long = 170; -pub const SYS_setdomainname: ::c_long = 171; -pub const SYS_iopl: ::c_long = 172; -pub const SYS_ioperm: ::c_long = 173; -pub const SYS_create_module: ::c_long = 174; -pub const SYS_init_module: ::c_long = 175; -pub const SYS_delete_module: ::c_long = 176; -pub const SYS_get_kernel_syms: ::c_long = 177; -pub const SYS_query_module: ::c_long = 178; -pub const SYS_quotactl: ::c_long = 179; -pub const SYS_nfsservctl: ::c_long = 180; -pub const SYS_getpmsg: ::c_long = 181; -pub const SYS_putpmsg: ::c_long = 182; -pub const SYS_afs_syscall: ::c_long = 183; -pub const SYS_tuxcall: ::c_long = 184; -pub const SYS_security: ::c_long = 185; -pub const SYS_gettid: ::c_long = 186; -pub const SYS_readahead: ::c_long = 187; -pub const SYS_setxattr: ::c_long = 188; -pub const SYS_lsetxattr: ::c_long = 189; -pub const SYS_fsetxattr: ::c_long = 190; -pub const SYS_getxattr: ::c_long = 191; -pub const SYS_lgetxattr: ::c_long = 192; -pub const SYS_fgetxattr: ::c_long = 193; -pub const SYS_listxattr: ::c_long = 194; -pub const SYS_llistxattr: ::c_long = 195; -pub const SYS_flistxattr: ::c_long = 196; -pub const SYS_removexattr: ::c_long = 197; -pub const SYS_lremovexattr: ::c_long = 198; -pub const SYS_fremovexattr: ::c_long = 199; -pub const SYS_tkill: ::c_long = 200; -pub const SYS_time: ::c_long = 201; -pub const SYS_futex: ::c_long = 202; -pub const SYS_sched_setaffinity: ::c_long = 203; -pub const SYS_sched_getaffinity: ::c_long = 204; -pub const SYS_set_thread_area: ::c_long = 205; -pub const SYS_io_setup: ::c_long = 206; -pub const SYS_io_destroy: ::c_long = 207; -pub const SYS_io_getevents: ::c_long = 208; -pub const SYS_io_submit: ::c_long = 209; -pub const SYS_io_cancel: ::c_long = 210; -pub const SYS_get_thread_area: ::c_long = 211; -pub const SYS_lookup_dcookie: ::c_long = 212; -pub const SYS_epoll_create: ::c_long = 213; -pub const SYS_epoll_ctl_old: ::c_long = 214; -pub const SYS_epoll_wait_old: ::c_long = 215; -pub const SYS_remap_file_pages: ::c_long = 216; -pub const SYS_getdents64: ::c_long = 217; -pub const SYS_set_tid_address: ::c_long = 218; -pub const SYS_restart_syscall: ::c_long = 219; -pub const SYS_semtimedop: ::c_long = 220; -pub const SYS_fadvise64: ::c_long = 221; -pub const SYS_timer_create: ::c_long = 222; -pub const SYS_timer_settime: ::c_long = 223; -pub const SYS_timer_gettime: ::c_long = 224; -pub const SYS_timer_getoverrun: ::c_long = 225; -pub const SYS_timer_delete: ::c_long = 226; -pub const SYS_clock_settime: ::c_long = 227; -pub const SYS_clock_gettime: ::c_long = 228; -pub const SYS_clock_getres: ::c_long = 229; -pub const SYS_clock_nanosleep: ::c_long = 230; -pub const SYS_exit_group: ::c_long = 231; -pub const SYS_epoll_wait: ::c_long = 232; -pub const SYS_epoll_ctl: ::c_long = 233; -pub const SYS_tgkill: ::c_long = 234; -pub const SYS_utimes: ::c_long = 235; -pub const SYS_vserver: ::c_long = 236; -pub const SYS_mbind: ::c_long = 237; -pub const SYS_set_mempolicy: ::c_long = 238; -pub const SYS_get_mempolicy: ::c_long = 239; -pub const SYS_mq_open: ::c_long = 240; -pub const SYS_mq_unlink: ::c_long = 241; -pub const SYS_mq_timedsend: ::c_long = 242; -pub const SYS_mq_timedreceive: ::c_long = 243; -pub const SYS_mq_notify: ::c_long = 244; -pub const SYS_mq_getsetattr: ::c_long = 245; -pub const SYS_kexec_load: ::c_long = 246; -pub const SYS_waitid: ::c_long = 247; -pub const SYS_add_key: ::c_long = 248; -pub const SYS_request_key: ::c_long = 249; -pub const SYS_keyctl: ::c_long = 250; -pub const SYS_ioprio_set: ::c_long = 251; -pub const SYS_ioprio_get: ::c_long = 252; -pub const SYS_inotify_init: ::c_long = 253; -pub const SYS_inotify_add_watch: ::c_long = 254; -pub const SYS_inotify_rm_watch: ::c_long = 255; -pub const SYS_migrate_pages: ::c_long = 256; -pub const SYS_openat: ::c_long = 257; -pub const SYS_mkdirat: ::c_long = 258; -pub const SYS_mknodat: ::c_long = 259; -pub const SYS_fchownat: ::c_long = 260; -pub const SYS_futimesat: ::c_long = 261; -pub const SYS_newfstatat: ::c_long = 262; -pub const SYS_unlinkat: ::c_long = 263; -pub const SYS_renameat: ::c_long = 264; -pub const SYS_linkat: ::c_long = 265; -pub const SYS_symlinkat: ::c_long = 266; -pub const SYS_readlinkat: ::c_long = 267; -pub const SYS_fchmodat: ::c_long = 268; -pub const SYS_faccessat: ::c_long = 269; -pub const SYS_pselect6: ::c_long = 270; -pub const SYS_ppoll: ::c_long = 271; -pub const SYS_unshare: ::c_long = 272; -pub const SYS_set_robust_list: ::c_long = 273; -pub const SYS_get_robust_list: ::c_long = 274; -pub const SYS_splice: ::c_long = 275; -pub const SYS_tee: ::c_long = 276; -pub const SYS_sync_file_range: ::c_long = 277; -pub const SYS_vmsplice: ::c_long = 278; -pub const SYS_move_pages: ::c_long = 279; -pub const SYS_utimensat: ::c_long = 280; -pub const SYS_epoll_pwait: ::c_long = 281; -pub const SYS_signalfd: ::c_long = 282; -pub const SYS_timerfd_create: ::c_long = 283; -pub const SYS_eventfd: ::c_long = 284; -pub const SYS_fallocate: ::c_long = 285; -pub const SYS_timerfd_settime: ::c_long = 286; -pub const SYS_timerfd_gettime: ::c_long = 287; -pub const SYS_accept4: ::c_long = 288; -pub const SYS_signalfd4: ::c_long = 289; -pub const SYS_eventfd2: ::c_long = 290; -pub const SYS_epoll_create1: ::c_long = 291; -pub const SYS_dup3: ::c_long = 292; -pub const SYS_pipe2: ::c_long = 293; -pub const SYS_inotify_init1: ::c_long = 294; -pub const SYS_preadv: ::c_long = 295; -pub const SYS_pwritev: ::c_long = 296; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 297; -pub const SYS_perf_event_open: ::c_long = 298; -pub const SYS_recvmmsg: ::c_long = 299; -pub const SYS_fanotify_init: ::c_long = 300; -pub const SYS_fanotify_mark: ::c_long = 301; -pub const SYS_prlimit64: ::c_long = 302; -pub const SYS_name_to_handle_at: ::c_long = 303; -pub const SYS_open_by_handle_at: ::c_long = 304; -pub const SYS_clock_adjtime: ::c_long = 305; -pub const SYS_syncfs: ::c_long = 306; -pub const SYS_sendmmsg: ::c_long = 307; -pub const SYS_setns: ::c_long = 308; -pub const SYS_getcpu: ::c_long = 309; -pub const SYS_process_vm_readv: ::c_long = 310; -pub const SYS_process_vm_writev: ::c_long = 311; -pub const SYS_kcmp: ::c_long = 312; -pub const SYS_finit_module: ::c_long = 313; -pub const SYS_sched_setattr: ::c_long = 314; -pub const SYS_sched_getattr: ::c_long = 315; -pub const SYS_renameat2: ::c_long = 316; -pub const SYS_seccomp: ::c_long = 317; -pub const SYS_getrandom: ::c_long = 318; -pub const SYS_memfd_create: ::c_long = 319; -pub const SYS_kexec_file_load: ::c_long = 320; -pub const SYS_bpf: ::c_long = 321; -pub const SYS_execveat: ::c_long = 322; -pub const SYS_userfaultfd: ::c_long = 323; -pub const SYS_membarrier: ::c_long = 324; -pub const SYS_mlock2: ::c_long = 325; -pub const SYS_copy_file_range: ::c_long = 326; -pub const SYS_preadv2: ::c_long = 327; -pub const SYS_pwritev2: ::c_long = 328; -pub const SYS_pkey_mprotect: ::c_long = 329; -pub const SYS_pkey_alloc: ::c_long = 330; -pub const SYS_pkey_free: ::c_long = 331; - -// offsets in user_regs_structs, from sys/reg.h -pub const R15: ::c_int = 0; -pub const R14: ::c_int = 1; -pub const R13: ::c_int = 2; -pub const R12: ::c_int = 3; -pub const RBP: ::c_int = 4; -pub const RBX: ::c_int = 5; -pub const R11: ::c_int = 6; -pub const R10: ::c_int = 7; -pub const R9: ::c_int = 8; -pub const R8: ::c_int = 9; -pub const RAX: ::c_int = 10; -pub const RCX: ::c_int = 11; -pub const RDX: ::c_int = 12; -pub const RSI: ::c_int = 13; -pub const RDI: ::c_int = 14; -pub const ORIG_RAX: ::c_int = 15; -pub const RIP: ::c_int = 16; -pub const CS: ::c_int = 17; -pub const EFLAGS: ::c_int = 18; -pub const RSP: ::c_int = 19; -pub const SS: ::c_int = 20; -pub const FS_BASE: ::c_int = 21; -pub const GS_BASE: ::c_int = 22; -pub const DS: ::c_int = 23; -pub const ES: ::c_int = 24; -pub const FS: ::c_int = 25; -pub const GS: ::c_int = 26; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/android/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/android/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1167 +0,0 @@ -//! Android-specific definitions for linux-like values - -use dox::{mem, Option}; - -pub type clock_t = ::c_long; -pub type time_t = ::c_long; -pub type suseconds_t = ::c_long; -pub type off_t = ::c_long; -pub type blkcnt_t = ::c_ulong; -pub type blksize_t = ::c_ulong; -pub type nlink_t = u32; -pub type useconds_t = u32; -pub type pthread_t = ::c_long; -pub type pthread_mutexattr_t = ::c_long; -pub type pthread_rwlockattr_t = ::c_long; -pub type pthread_condattr_t = ::c_long; -pub type fsfilcnt_t = ::c_ulong; -pub type fsblkcnt_t = ::c_ulong; -pub type nfds_t = ::c_uint; -pub type rlim_t = ::c_ulong; -pub type dev_t = ::c_ulong; -pub type ino_t = ::c_ulong; -pub type __CPU_BITTYPE = ::c_ulong; -pub type idtype_t = ::c_int; -pub type loff_t = ::c_longlong; - -s! { - pub struct dirent { - pub d_ino: u64, - pub d_off: i64, - pub d_reclen: ::c_ushort, - pub d_type: ::c_uchar, - pub d_name: [::c_char; 256], - } - - pub struct dirent64 { - pub d_ino: u64, - pub d_off: i64, - pub d_reclen: ::c_ushort, - pub d_type: ::c_uchar, - pub d_name: [::c_char; 256], - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_flags: ::c_int, - pub ss_size: ::size_t - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_errno: ::c_int, - pub si_code: ::c_int, - pub _pad: [::c_int; 29], - _align: [usize; 0], - } - - pub struct __fsid_t { - __val: [::c_int; 2], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::size_t, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::size_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::size_t, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; ::NCCS], - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 19], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } - - pub struct flock { - pub l_type: ::c_short, - pub l_whence: ::c_short, - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_pid: ::pid_t, - } - - pub struct cpu_set_t { - #[cfg(target_pointer_width = "64")] - __bits: [__CPU_BITTYPE; 16], - #[cfg(target_pointer_width = "32")] - __bits: [__CPU_BITTYPE; 1], - } - - pub struct sem_t { - count: ::c_uint, - #[cfg(target_pointer_width = "64")] - __reserved: [::c_int; 3], - } - - pub struct lastlog { - ll_time: ::time_t, - ll_line: [::c_char; UT_LINESIZE], - ll_host: [::c_char; UT_HOSTSIZE], - } - - pub struct exit_status { - pub e_termination: ::c_short, - pub e_exit: ::c_short, - } - - pub struct utmp { - pub ut_type: ::c_short, - pub ut_pid: ::pid_t, - pub ut_line: [::c_char; UT_LINESIZE], - pub ut_id: [::c_char; 4], - - pub ut_user: [::c_char; UT_NAMESIZE], - pub ut_host: [::c_char; UT_HOSTSIZE], - pub ut_exit: exit_status, - pub ut_session: ::c_long, - pub ut_tv: ::timeval, - - pub ut_addr_v6: [::int32_t; 4], - unused: [::c_char; 20], - } - - pub struct statvfs { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_favail: ::fsfilcnt_t, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - #[cfg(target_pointer_width = "64")] - __f_reserved: [u32; 6], - } - - pub struct signalfd_siginfo { - pub ssi_signo: ::uint32_t, - pub ssi_errno: ::int32_t, - pub ssi_code: ::int32_t, - pub ssi_pid: ::uint32_t, - pub ssi_uid: ::uint32_t, - pub ssi_fd: ::int32_t, - pub ssi_tid: ::uint32_t, - pub ssi_band: ::uint32_t, - pub ssi_overrun: ::uint32_t, - pub ssi_trapno: ::uint32_t, - pub ssi_status: ::int32_t, - pub ssi_int: ::int32_t, - pub ssi_ptr: ::c_ulonglong, - pub ssi_utime: ::c_ulonglong, - pub ssi_stime: ::c_ulonglong, - pub ssi_addr: ::c_ulonglong, - pub ssi_addr_lsb: ::uint16_t, - _pad: [::uint8_t; 46], - } - - pub struct ucred { - pub pid: ::pid_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - } -} - -pub const O_TRUNC: ::c_int = 512; -pub const O_CLOEXEC: ::c_int = 0x80000; -pub const O_PATH: ::c_int = 0o10000000; -pub const O_NOATIME: ::c_int = 0o1000000; - -pub const EBFONT: ::c_int = 59; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENONET: ::c_int = 64; -pub const ENOPKG: ::c_int = 65; -pub const EREMOTE: ::c_int = 66; -pub const ENOLINK: ::c_int = 67; -pub const EADV: ::c_int = 68; -pub const ESRMNT: ::c_int = 69; -pub const ECOMM: ::c_int = 70; -pub const EPROTO: ::c_int = 71; -pub const EDOTDOT: ::c_int = 73; - -pub const SA_NODEFER: ::c_int = 0x40000000; -pub const SA_RESETHAND: ::c_int = 0x80000000; -pub const SA_RESTART: ::c_int = 0x10000000; -pub const SA_NOCLDSTOP: ::c_int = 0x00000001; - -pub const EPOLL_CLOEXEC: ::c_int = 0x80000; -pub const EPOLLONESHOT: ::c_int = 0x40000000; -pub const EPOLLRDHUP: ::c_int = 0x00002000; -pub const EPOLLWAKEUP: ::c_int = 0x20000000; - -pub const EFD_CLOEXEC: ::c_int = 0x80000; - -pub const USER_PROCESS: ::c_short = 7; - -pub const BUFSIZ: ::c_uint = 1024; -pub const FILENAME_MAX: ::c_uint = 1024; -pub const FOPEN_MAX: ::c_uint = 20; -pub const POSIX_FADV_DONTNEED: ::c_int = 4; -pub const POSIX_FADV_NOREUSE: ::c_int = 5; -pub const L_tmpnam: ::c_uint = 1024; -pub const TMP_MAX: ::c_uint = 308915776; -pub const _PC_LINK_MAX: ::c_int = 1; -pub const _PC_MAX_CANON: ::c_int = 2; -pub const _PC_MAX_INPUT: ::c_int = 3; -pub const _PC_NAME_MAX: ::c_int = 4; -pub const _PC_PATH_MAX: ::c_int = 5; -pub const _PC_PIPE_BUF: ::c_int = 6; -pub const _PC_2_SYMLINKS: ::c_int = 7; -pub const _PC_ALLOC_SIZE_MIN: ::c_int = 8; -pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 9; -pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 10; -pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 11; -pub const _PC_REC_XFER_ALIGN: ::c_int = 12; -pub const _PC_SYMLINK_MAX: ::c_int = 13; -pub const _PC_CHOWN_RESTRICTED: ::c_int = 14; -pub const _PC_NO_TRUNC: ::c_int = 15; -pub const _PC_VDISABLE: ::c_int = 16; -pub const _PC_ASYNC_IO: ::c_int = 17; -pub const _PC_PRIO_IO: ::c_int = 18; -pub const _PC_SYNC_IO: ::c_int = 19; - -pub const FIONBIO: ::c_int = 0x5421; - -pub const _SC_ARG_MAX: ::c_int = 0; -pub const _SC_BC_BASE_MAX: ::c_int = 1; -pub const _SC_BC_DIM_MAX: ::c_int = 2; -pub const _SC_BC_SCALE_MAX: ::c_int = 3; -pub const _SC_BC_STRING_MAX: ::c_int = 4; -pub const _SC_CHILD_MAX: ::c_int = 5; -pub const _SC_CLK_TCK: ::c_int = 6; -pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 7; -pub const _SC_EXPR_NEST_MAX: ::c_int = 8; -pub const _SC_LINE_MAX: ::c_int = 9; -pub const _SC_NGROUPS_MAX: ::c_int = 10; -pub const _SC_OPEN_MAX: ::c_int = 11; -pub const _SC_PASS_MAX: ::c_int = 12; -pub const _SC_2_C_BIND: ::c_int = 13; -pub const _SC_2_C_DEV: ::c_int = 14; -pub const _SC_2_C_VERSION: ::c_int = 15; -pub const _SC_2_CHAR_TERM: ::c_int = 16; -pub const _SC_2_FORT_DEV: ::c_int = 17; -pub const _SC_2_FORT_RUN: ::c_int = 18; -pub const _SC_2_LOCALEDEF: ::c_int = 19; -pub const _SC_2_SW_DEV: ::c_int = 20; -pub const _SC_2_UPE: ::c_int = 21; -pub const _SC_2_VERSION: ::c_int = 22; -pub const _SC_JOB_CONTROL: ::c_int = 23; -pub const _SC_SAVED_IDS: ::c_int = 24; -pub const _SC_VERSION: ::c_int = 25; -pub const _SC_RE_DUP_MAX: ::c_int = 26; -pub const _SC_STREAM_MAX: ::c_int = 27; -pub const _SC_TZNAME_MAX: ::c_int = 28; -pub const _SC_XOPEN_CRYPT: ::c_int = 29; -pub const _SC_XOPEN_ENH_I18N: ::c_int = 30; -pub const _SC_XOPEN_SHM: ::c_int = 31; -pub const _SC_XOPEN_VERSION: ::c_int = 32; -pub const _SC_XOPEN_XCU_VERSION: ::c_int = 33; -pub const _SC_XOPEN_REALTIME: ::c_int = 34; -pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 35; -pub const _SC_XOPEN_LEGACY: ::c_int = 36; -pub const _SC_ATEXIT_MAX: ::c_int = 37; -pub const _SC_IOV_MAX: ::c_int = 38; -pub const _SC_PAGESIZE: ::c_int = 39; -pub const _SC_PAGE_SIZE: ::c_int = 40; -pub const _SC_XOPEN_UNIX: ::c_int = 41; -pub const _SC_XBS5_ILP32_OFF32: ::c_int = 42; -pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 43; -pub const _SC_XBS5_LP64_OFF64: ::c_int = 44; -pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 45; -pub const _SC_AIO_LISTIO_MAX: ::c_int = 46; -pub const _SC_AIO_MAX: ::c_int = 47; -pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 48; -pub const _SC_DELAYTIMER_MAX: ::c_int = 49; -pub const _SC_MQ_OPEN_MAX: ::c_int = 50; -pub const _SC_MQ_PRIO_MAX: ::c_int = 51; -pub const _SC_RTSIG_MAX: ::c_int = 52; -pub const _SC_SEM_NSEMS_MAX: ::c_int = 53; -pub const _SC_SEM_VALUE_MAX: ::c_int = 54; -pub const _SC_SIGQUEUE_MAX: ::c_int = 55; -pub const _SC_TIMER_MAX: ::c_int = 56; -pub const _SC_ASYNCHRONOUS_IO: ::c_int = 57; -pub const _SC_FSYNC: ::c_int = 58; -pub const _SC_MAPPED_FILES: ::c_int = 59; -pub const _SC_MEMLOCK: ::c_int = 60; -pub const _SC_MEMLOCK_RANGE: ::c_int = 61; -pub const _SC_MEMORY_PROTECTION: ::c_int = 62; -pub const _SC_MESSAGE_PASSING: ::c_int = 63; -pub const _SC_PRIORITIZED_IO: ::c_int = 64; -pub const _SC_PRIORITY_SCHEDULING: ::c_int = 65; -pub const _SC_REALTIME_SIGNALS: ::c_int = 66; -pub const _SC_SEMAPHORES: ::c_int = 67; -pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 68; -pub const _SC_SYNCHRONIZED_IO: ::c_int = 69; -pub const _SC_TIMERS: ::c_int = 70; -pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 71; -pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 72; -pub const _SC_LOGIN_NAME_MAX: ::c_int = 73; -pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 74; -pub const _SC_THREAD_KEYS_MAX: ::c_int = 75; -pub const _SC_THREAD_STACK_MIN: ::c_int = 76; -pub const _SC_THREAD_THREADS_MAX: ::c_int = 77; -pub const _SC_TTY_NAME_MAX: ::c_int = 78; -pub const _SC_THREADS: ::c_int = 79; -pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 80; -pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 81; -pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 82; -pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 83; -pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 84; -pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 85; -pub const _SC_NPROCESSORS_CONF: ::c_int = 96; -pub const _SC_NPROCESSORS_ONLN: ::c_int = 97; -pub const _SC_PHYS_PAGES: ::c_int = 98; -pub const _SC_AVPHYS_PAGES: ::c_int = 99; -pub const _SC_MONOTONIC_CLOCK: ::c_int = 100; - -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; -pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; - -pub const FIOCLEX: ::c_int = 0x5451; - -pub const SA_ONSTACK: ::c_ulong = 0x08000000; -pub const SA_SIGINFO: ::c_ulong = 0x00000004; -pub const SA_NOCLDWAIT: ::c_ulong = 0x00000002; -pub const SIGCHLD: ::c_int = 17; -pub const SIGBUS: ::c_int = 7; -pub const SIGUSR1: ::c_int = 10; -pub const SIGUSR2: ::c_int = 12; -pub const SIGCONT: ::c_int = 18; -pub const SIGSTOP: ::c_int = 19; -pub const SIGTSTP: ::c_int = 20; -pub const SIGURG: ::c_int = 23; -pub const SIGIO: ::c_int = 29; -pub const SIGSYS: ::c_int = 31; -pub const SIGSTKFLT: ::c_int = 16; -pub const SIGUNUSED: ::c_int = 31; -pub const SIGTTIN: ::c_int = 21; -pub const SIGTTOU: ::c_int = 22; -pub const SIGXCPU: ::c_int = 24; -pub const SIGXFSZ: ::c_int = 25; -pub const SIGVTALRM: ::c_int = 26; -pub const SIGPROF: ::c_int = 27; -pub const SIGWINCH: ::c_int = 28; -pub const SIGPOLL: ::c_int = 29; -pub const SIGPWR: ::c_int = 30; -pub const SIG_SETMASK: ::c_int = 2; -pub const SIG_BLOCK: ::c_int = 0x000000; -pub const SIG_UNBLOCK: ::c_int = 0x01; - -pub const RUSAGE_CHILDREN: ::c_int = -1; - -pub const LC_PAPER: ::c_int = 7; -pub const LC_NAME: ::c_int = 8; -pub const LC_ADDRESS: ::c_int = 9; -pub const LC_TELEPHONE: ::c_int = 10; -pub const LC_MEASUREMENT: ::c_int = 11; -pub const LC_IDENTIFICATION: ::c_int = 12; -pub const LC_PAPER_MASK: ::c_int = (1 << LC_PAPER); -pub const LC_NAME_MASK: ::c_int = (1 << LC_NAME); -pub const LC_ADDRESS_MASK: ::c_int = (1 << LC_ADDRESS); -pub const LC_TELEPHONE_MASK: ::c_int = (1 << LC_TELEPHONE); -pub const LC_MEASUREMENT_MASK: ::c_int = (1 << LC_MEASUREMENT); -pub const LC_IDENTIFICATION_MASK: ::c_int = (1 << LC_IDENTIFICATION); -pub const LC_ALL_MASK: ::c_int = ::LC_CTYPE_MASK - | ::LC_NUMERIC_MASK - | ::LC_TIME_MASK - | ::LC_COLLATE_MASK - | ::LC_MONETARY_MASK - | ::LC_MESSAGES_MASK - | LC_PAPER_MASK - | LC_NAME_MASK - | LC_ADDRESS_MASK - | LC_TELEPHONE_MASK - | LC_MEASUREMENT_MASK - | LC_IDENTIFICATION_MASK; - -pub const MAP_ANON: ::c_int = 0x0020; -pub const MAP_ANONYMOUS: ::c_int = 0x0020; -pub const MAP_GROWSDOWN: ::c_int = 0x0100; -pub const MAP_DENYWRITE: ::c_int = 0x0800; -pub const MAP_EXECUTABLE: ::c_int = 0x01000; -pub const MAP_LOCKED: ::c_int = 0x02000; -pub const MAP_NORESERVE: ::c_int = 0x04000; -pub const MAP_POPULATE: ::c_int = 0x08000; -pub const MAP_NONBLOCK: ::c_int = 0x010000; -pub const MAP_STACK: ::c_int = 0x020000; - -pub const EDEADLK: ::c_int = 35; -pub const ENAMETOOLONG: ::c_int = 36; -pub const ENOLCK: ::c_int = 37; -pub const ENOSYS: ::c_int = 38; -pub const ENOTEMPTY: ::c_int = 39; -pub const ELOOP: ::c_int = 40; -pub const ENOMSG: ::c_int = 42; -pub const EIDRM: ::c_int = 43; -pub const ECHRNG: ::c_int = 44; -pub const EL2NSYNC: ::c_int = 45; -pub const EL3HLT: ::c_int = 46; -pub const EL3RST: ::c_int = 47; -pub const ELNRNG: ::c_int = 48; -pub const EUNATCH: ::c_int = 49; -pub const ENOCSI: ::c_int = 50; -pub const EL2HLT: ::c_int = 51; -pub const EBADE: ::c_int = 52; -pub const EBADR: ::c_int = 53; -pub const EXFULL: ::c_int = 54; -pub const ENOANO: ::c_int = 55; -pub const EBADRQC: ::c_int = 56; -pub const EBADSLT: ::c_int = 57; - -pub const EMULTIHOP: ::c_int = 72; -pub const EBADMSG: ::c_int = 74; -pub const EOVERFLOW: ::c_int = 75; -pub const ENOTUNIQ: ::c_int = 76; -pub const EBADFD: ::c_int = 77; -pub const EREMCHG: ::c_int = 78; -pub const ELIBACC: ::c_int = 79; -pub const ELIBBAD: ::c_int = 80; -pub const ELIBSCN: ::c_int = 81; -pub const ELIBMAX: ::c_int = 82; -pub const ELIBEXEC: ::c_int = 83; -pub const EILSEQ: ::c_int = 84; -pub const ERESTART: ::c_int = 85; -pub const ESTRPIPE: ::c_int = 86; -pub const EUSERS: ::c_int = 87; -pub const ENOTSOCK: ::c_int = 88; -pub const EDESTADDRREQ: ::c_int = 89; -pub const EMSGSIZE: ::c_int = 90; -pub const EPROTOTYPE: ::c_int = 91; -pub const ENOPROTOOPT: ::c_int = 92; -pub const EPROTONOSUPPORT: ::c_int = 93; -pub const ESOCKTNOSUPPORT: ::c_int = 94; -pub const EOPNOTSUPP: ::c_int = 95; -pub const ENOTSUP: ::c_int = EOPNOTSUPP; -pub const EPFNOSUPPORT: ::c_int = 96; -pub const EAFNOSUPPORT: ::c_int = 97; -pub const EADDRINUSE: ::c_int = 98; -pub const EADDRNOTAVAIL: ::c_int = 99; -pub const ENETDOWN: ::c_int = 100; -pub const ENETUNREACH: ::c_int = 101; -pub const ENETRESET: ::c_int = 102; -pub const ECONNABORTED: ::c_int = 103; -pub const ECONNRESET: ::c_int = 104; -pub const ENOBUFS: ::c_int = 105; -pub const EISCONN: ::c_int = 106; -pub const ENOTCONN: ::c_int = 107; -pub const ESHUTDOWN: ::c_int = 108; -pub const ETOOMANYREFS: ::c_int = 109; -pub const ETIMEDOUT: ::c_int = 110; -pub const ECONNREFUSED: ::c_int = 111; -pub const EHOSTDOWN: ::c_int = 112; -pub const EHOSTUNREACH: ::c_int = 113; -pub const EALREADY: ::c_int = 114; -pub const EINPROGRESS: ::c_int = 115; -pub const ESTALE: ::c_int = 116; -pub const EUCLEAN: ::c_int = 117; -pub const ENOTNAM: ::c_int = 118; -pub const ENAVAIL: ::c_int = 119; -pub const EISNAM: ::c_int = 120; -pub const EREMOTEIO: ::c_int = 121; -pub const EDQUOT: ::c_int = 122; -pub const ENOMEDIUM: ::c_int = 123; -pub const EMEDIUMTYPE: ::c_int = 124; -pub const ECANCELED: ::c_int = 125; -pub const ENOKEY: ::c_int = 126; -pub const EKEYEXPIRED: ::c_int = 127; -pub const EKEYREVOKED: ::c_int = 128; -pub const EKEYREJECTED: ::c_int = 129; -pub const EOWNERDEAD: ::c_int = 130; -pub const ENOTRECOVERABLE: ::c_int = 131; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; -pub const SOCK_SEQPACKET: ::c_int = 5; -pub const SOCK_DCCP: ::c_int = 6; -pub const SOCK_PACKET: ::c_int = 10; - -pub const SOL_SOCKET: ::c_int = 1; -pub const SOL_SCTP: ::c_int = 132; -pub const SOL_IPX: ::c_int = 256; -pub const SOL_AX25: ::c_int = 257; -pub const SOL_ATALK: ::c_int = 258; -pub const SOL_NETROM: ::c_int = 259; -pub const SOL_ROSE: ::c_int = 260; - -#[doc(hidden)] -pub const AF_MAX: ::c_int = 43; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; - -/* DCCP socket options */ -pub const DCCP_SOCKOPT_PACKET_SIZE: ::c_int = 1; -pub const DCCP_SOCKOPT_SERVICE: ::c_int = 2; -pub const DCCP_SOCKOPT_CHANGE_L: ::c_int = 3; -pub const DCCP_SOCKOPT_CHANGE_R: ::c_int = 4; -pub const DCCP_SOCKOPT_GET_CUR_MPS: ::c_int = 5; -pub const DCCP_SOCKOPT_SERVER_TIMEWAIT: ::c_int = 6; -pub const DCCP_SOCKOPT_SEND_CSCOV: ::c_int = 10; -pub const DCCP_SOCKOPT_RECV_CSCOV: ::c_int = 11; -pub const DCCP_SOCKOPT_AVAILABLE_CCIDS: ::c_int = 12; -pub const DCCP_SOCKOPT_CCID: ::c_int = 13; -pub const DCCP_SOCKOPT_TX_CCID: ::c_int = 14; -pub const DCCP_SOCKOPT_RX_CCID: ::c_int = 15; -pub const DCCP_SOCKOPT_QPOLICY_ID: ::c_int = 16; -pub const DCCP_SOCKOPT_QPOLICY_TXQLEN: ::c_int = 17; -pub const DCCP_SOCKOPT_CCID_RX_INFO: ::c_int = 128; -pub const DCCP_SOCKOPT_CCID_TX_INFO: ::c_int = 192; - -/// maximum number of services provided on the same listening port -pub const DCCP_SERVICE_LIST_MAX_LEN: ::c_int = 32; - -pub const SO_REUSEADDR: ::c_int = 2; -pub const SO_TYPE: ::c_int = 3; -pub const SO_ERROR: ::c_int = 4; -pub const SO_DONTROUTE: ::c_int = 5; -pub const SO_BROADCAST: ::c_int = 6; -pub const SO_SNDBUF: ::c_int = 7; -pub const SO_RCVBUF: ::c_int = 8; -pub const SO_KEEPALIVE: ::c_int = 9; -pub const SO_OOBINLINE: ::c_int = 10; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_LINGER: ::c_int = 13; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_REUSEPORT: ::c_int = 15; -pub const SO_PASSCRED: ::c_int = 16; -pub const SO_PEERCRED: ::c_int = 17; -pub const SO_RCVLOWAT: ::c_int = 18; -pub const SO_SNDLOWAT: ::c_int = 19; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_SNDTIMEO: ::c_int = 21; -pub const SO_BINDTODEVICE: ::c_int = 25; -pub const SO_TIMESTAMP: ::c_int = 29; -pub const SO_ACCEPTCONN: ::c_int = 30; -pub const SO_SNDBUFFORCE: ::c_int = 32; -pub const SO_RCVBUFFORCE: ::c_int = 33; -pub const SO_MARK: ::c_int = 36; -pub const SO_PROTOCOL: ::c_int = 38; -pub const SO_DOMAIN: ::c_int = 39; -pub const SO_RXQ_OVFL: ::c_int = 40; -pub const SO_PEEK_OFF: ::c_int = 42; -pub const SO_BUSY_POLL: ::c_int = 46; - -pub const O_ACCMODE: ::c_int = 3; -pub const O_APPEND: ::c_int = 1024; -pub const O_CREAT: ::c_int = 64; -pub const O_EXCL: ::c_int = 128; -pub const O_NOCTTY: ::c_int = 256; -pub const O_NONBLOCK: ::c_int = 2048; -pub const O_SYNC: ::c_int = 0x101000; -pub const O_ASYNC: ::c_int = 0x2000; -pub const O_NDELAY: ::c_int = 0x800; -pub const O_DSYNC: ::c_int = 4096; - -pub const NI_MAXHOST: ::size_t = 1025; - -pub const NCCS: usize = 19; -pub const TCSBRKP: ::c_int = 0x5425; -pub const TCSANOW: ::c_int = 0; -pub const TCSADRAIN: ::c_int = 0x1; -pub const TCSAFLUSH: ::c_int = 0x2; -pub const VEOF: usize = 4; -pub const VEOL: usize = 11; -pub const VEOL2: usize = 16; -pub const VMIN: usize = 6; -pub const IEXTEN: ::tcflag_t = 0x00008000; -pub const TOSTOP: ::tcflag_t = 0x00000100; -pub const FLUSHO: ::tcflag_t = 0x00001000; -pub const EXTPROC: ::tcflag_t = 0o200000; - -pub const ADFS_SUPER_MAGIC: ::c_long = 0x0000adf5; -pub const AFFS_SUPER_MAGIC: ::c_long = 0x0000adff; -pub const CODA_SUPER_MAGIC: ::c_long = 0x73757245; -pub const CRAMFS_MAGIC: ::c_long = 0x28cd3d45; -pub const EFS_SUPER_MAGIC: ::c_long = 0x00414a53; -pub const EXT2_SUPER_MAGIC: ::c_long = 0x0000ef53; -pub const EXT3_SUPER_MAGIC: ::c_long = 0x0000ef53; -pub const EXT4_SUPER_MAGIC: ::c_long = 0x0000ef53; -pub const HPFS_SUPER_MAGIC: ::c_long = 0xf995e849; -pub const HUGETLBFS_MAGIC: ::c_long = 0x958458f6; -pub const ISOFS_SUPER_MAGIC: ::c_long = 0x00009660; -pub const JFFS2_SUPER_MAGIC: ::c_long = 0x000072b6; -pub const MINIX_SUPER_MAGIC: ::c_long = 0x0000137f; -pub const MINIX_SUPER_MAGIC2: ::c_long = 0x0000138f; -pub const MINIX2_SUPER_MAGIC: ::c_long = 0x00002468; -pub const MINIX2_SUPER_MAGIC2: ::c_long = 0x00002478; -pub const MSDOS_SUPER_MAGIC: ::c_long = 0x00004d44; -pub const NCP_SUPER_MAGIC: ::c_long = 0x0000564c; -pub const NFS_SUPER_MAGIC: ::c_long = 0x00006969; -pub const OPENPROM_SUPER_MAGIC: ::c_long = 0x00009fa1; -pub const PROC_SUPER_MAGIC: ::c_long = 0x00009fa0; -pub const QNX4_SUPER_MAGIC: ::c_long = 0x0000002f; -pub const REISERFS_SUPER_MAGIC: ::c_long = 0x52654973; -pub const SMB_SUPER_MAGIC: ::c_long = 0x0000517b; -pub const TMPFS_MAGIC: ::c_long = 0x01021994; -pub const USBDEVICE_SUPER_MAGIC: ::c_long = 0x00009fa2; - -pub const MAP_HUGETLB: ::c_int = 0x040000; - -pub const PTRACE_TRACEME: ::c_int = 0; -pub const PTRACE_PEEKTEXT: ::c_int = 1; -pub const PTRACE_PEEKDATA: ::c_int = 2; -pub const PTRACE_PEEKUSER: ::c_int = 3; -pub const PTRACE_POKETEXT: ::c_int = 4; -pub const PTRACE_POKEDATA: ::c_int = 5; -pub const PTRACE_POKEUSER: ::c_int = 6; -pub const PTRACE_CONT: ::c_int = 7; -pub const PTRACE_KILL: ::c_int = 8; -pub const PTRACE_SINGLESTEP: ::c_int = 9; -pub const PTRACE_ATTACH: ::c_int = 16; -pub const PTRACE_DETACH: ::c_int = 17; -pub const PTRACE_SYSCALL: ::c_int = 24; -pub const PTRACE_SETOPTIONS: ::c_int = 0x4200; -pub const PTRACE_GETEVENTMSG: ::c_int = 0x4201; -pub const PTRACE_GETSIGINFO: ::c_int = 0x4202; -pub const PTRACE_SETSIGINFO: ::c_int = 0x4203; - -pub const EFD_NONBLOCK: ::c_int = 0x800; - -pub const F_GETLK: ::c_int = 5; -pub const F_GETOWN: ::c_int = 9; -pub const F_SETOWN: ::c_int = 8; -pub const F_SETLK: ::c_int = 6; -pub const F_SETLKW: ::c_int = 7; - -pub const TCGETS: ::c_int = 0x5401; -pub const TCSETS: ::c_int = 0x5402; -pub const TCSETSW: ::c_int = 0x5403; -pub const TCSETSF: ::c_int = 0x5404; -pub const TCGETA: ::c_int = 0x5405; -pub const TCSETA: ::c_int = 0x5406; -pub const TCSETAW: ::c_int = 0x5407; -pub const TCSETAF: ::c_int = 0x5408; -pub const TCSBRK: ::c_int = 0x5409; -pub const TCXONC: ::c_int = 0x540A; -pub const TCFLSH: ::c_int = 0x540B; -pub const TIOCGSOFTCAR: ::c_int = 0x5419; -pub const TIOCSSOFTCAR: ::c_int = 0x541A; -pub const TIOCINQ: ::c_int = 0x541B; -pub const TIOCLINUX: ::c_int = 0x541C; -pub const TIOCGSERIAL: ::c_int = 0x541E; -pub const TIOCEXCL: ::c_int = 0x540C; -pub const TIOCNXCL: ::c_int = 0x540D; -pub const TIOCSCTTY: ::c_int = 0x540E; -pub const TIOCGPGRP: ::c_int = 0x540F; -pub const TIOCSPGRP: ::c_int = 0x5410; -pub const TIOCOUTQ: ::c_int = 0x5411; -pub const TIOCSTI: ::c_int = 0x5412; -pub const TIOCGWINSZ: ::c_int = 0x5413; -pub const TIOCSWINSZ: ::c_int = 0x5414; -pub const TIOCMGET: ::c_int = 0x5415; -pub const TIOCMBIS: ::c_int = 0x5416; -pub const TIOCMBIC: ::c_int = 0x5417; -pub const TIOCMSET: ::c_int = 0x5418; -pub const FIONREAD: ::c_int = 0x541B; -pub const TIOCCONS: ::c_int = 0x541D; - -pub const ST_RDONLY: ::c_ulong = 1; -pub const ST_NOSUID: ::c_ulong = 2; -pub const ST_NODEV: ::c_ulong = 4; -pub const ST_NOEXEC: ::c_ulong = 8; -pub const ST_SYNCHRONOUS: ::c_ulong = 16; -pub const ST_MANDLOCK: ::c_ulong = 64; -pub const ST_NOATIME: ::c_ulong = 1024; -pub const ST_NODIRATIME: ::c_ulong = 2048; -pub const ST_RELATIME: ::c_ulong = 4096; - -pub const RTLD_NOLOAD: ::c_int = 0x4; - -pub const SEM_FAILED: *mut sem_t = 0 as *mut sem_t; - -pub const LINUX_REBOOT_MAGIC1: ::c_int = 0xfee1dead; -pub const LINUX_REBOOT_MAGIC2: ::c_int = 672274793; -pub const LINUX_REBOOT_MAGIC2A: ::c_int = 85072278; -pub const LINUX_REBOOT_MAGIC2B: ::c_int = 369367448; -pub const LINUX_REBOOT_MAGIC2C: ::c_int = 537993216; - -pub const LINUX_REBOOT_CMD_RESTART: ::c_int = 0x01234567; -pub const LINUX_REBOOT_CMD_HALT: ::c_int = 0xCDEF0123; -pub const LINUX_REBOOT_CMD_CAD_ON: ::c_int = 0x89ABCDEF; -pub const LINUX_REBOOT_CMD_CAD_OFF: ::c_int = 0x00000000; -pub const LINUX_REBOOT_CMD_POWER_OFF: ::c_int = 0x4321FEDC; -pub const LINUX_REBOOT_CMD_RESTART2: ::c_int = 0xA1B2C3D4; -pub const LINUX_REBOOT_CMD_SW_SUSPEND: ::c_int = 0xD000FCE2; -pub const LINUX_REBOOT_CMD_KEXEC: ::c_int = 0x45584543; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const CBAUD: ::tcflag_t = 0o0010017; -pub const TAB1: ::c_int = 0x00000800; -pub const TAB2: ::c_int = 0x00001000; -pub const TAB3: ::c_int = 0x00001800; -pub const CR1: ::c_int = 0x00000200; -pub const CR2: ::c_int = 0x00000400; -pub const CR3: ::c_int = 0x00000600; -pub const FF1: ::c_int = 0x00008000; -pub const BS1: ::c_int = 0x00002000; -pub const VT1: ::c_int = 0x00004000; -pub const VWERASE: usize = 14; -pub const VREPRINT: usize = 12; -pub const VSUSP: usize = 10; -pub const VSTART: usize = 8; -pub const VSTOP: usize = 9; -pub const VDISCARD: usize = 13; -pub const VTIME: usize = 5; -pub const IXON: ::tcflag_t = 0x00000400; -pub const IXOFF: ::tcflag_t = 0x00001000; -pub const ONLCR: ::tcflag_t = 0x4; -pub const CSIZE: ::tcflag_t = 0x00000030; -pub const CS6: ::tcflag_t = 0x00000010; -pub const CS7: ::tcflag_t = 0x00000020; -pub const CS8: ::tcflag_t = 0x00000030; -pub const CSTOPB: ::tcflag_t = 0x00000040; -pub const CREAD: ::tcflag_t = 0x00000080; -pub const PARENB: ::tcflag_t = 0x00000100; -pub const PARODD: ::tcflag_t = 0x00000200; -pub const HUPCL: ::tcflag_t = 0x00000400; -pub const CLOCAL: ::tcflag_t = 0x00000800; -pub const ECHOKE: ::tcflag_t = 0x00000800; -pub const ECHOE: ::tcflag_t = 0x00000010; -pub const ECHOK: ::tcflag_t = 0x00000020; -pub const ECHONL: ::tcflag_t = 0x00000040; -pub const ECHOPRT: ::tcflag_t = 0x00000400; -pub const ECHOCTL: ::tcflag_t = 0x00000200; -pub const ISIG: ::tcflag_t = 0x00000001; -pub const ICANON: ::tcflag_t = 0x00000002; -pub const PENDIN: ::tcflag_t = 0x00004000; -pub const NOFLSH: ::tcflag_t = 0x00000080; -pub const VSWTC: usize = 7; -pub const OLCUC: ::tcflag_t = 0o000002; -pub const NLDLY: ::tcflag_t = 0o000400; -pub const CRDLY: ::tcflag_t = 0o003000; -pub const TABDLY: ::tcflag_t = 0o014000; -pub const BSDLY: ::tcflag_t = 0o020000; -pub const FFDLY: ::tcflag_t = 0o100000; -pub const VTDLY: ::tcflag_t = 0o040000; -pub const XTABS: ::tcflag_t = 0o014000; - -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const EXTA: ::speed_t = B19200; -pub const EXTB: ::speed_t = B38400; -pub const BOTHER: ::speed_t = 0o010000; -pub const B57600: ::speed_t = 0o010001; -pub const B115200: ::speed_t = 0o010002; -pub const B230400: ::speed_t = 0o010003; -pub const B460800: ::speed_t = 0o010004; -pub const B500000: ::speed_t = 0o010005; -pub const B576000: ::speed_t = 0o010006; -pub const B921600: ::speed_t = 0o010007; -pub const B1000000: ::speed_t = 0o010010; -pub const B1152000: ::speed_t = 0o010011; -pub const B1500000: ::speed_t = 0o010012; -pub const B2000000: ::speed_t = 0o010013; -pub const B2500000: ::speed_t = 0o010014; -pub const B3000000: ::speed_t = 0o010015; -pub const B3500000: ::speed_t = 0o010016; -pub const B4000000: ::speed_t = 0o010017; - -pub const EAI_AGAIN: ::c_int = 2; -pub const EAI_BADFLAGS: ::c_int = 3; -pub const EAI_FAIL: ::c_int = 4; -pub const EAI_FAMILY: ::c_int = 5; -pub const EAI_MEMORY: ::c_int = 6; -pub const EAI_NODATA: ::c_int = 7; -pub const EAI_NONAME: ::c_int = 8; -pub const EAI_SERVICE: ::c_int = 9; -pub const EAI_SOCKTYPE: ::c_int = 10; -pub const EAI_SYSTEM: ::c_int = 11; -pub const EAI_OVERFLOW: ::c_int = 14; - -pub const NETLINK_ROUTE: ::c_int = 0; -pub const NETLINK_UNUSED: ::c_int = 1; -pub const NETLINK_USERSOCK: ::c_int = 2; -pub const NETLINK_FIREWALL: ::c_int = 3; -pub const NETLINK_SOCK_DIAG: ::c_int = 4; -pub const NETLINK_NFLOG: ::c_int = 5; -pub const NETLINK_XFRM: ::c_int = 6; -pub const NETLINK_SELINUX: ::c_int = 7; -pub const NETLINK_ISCSI: ::c_int = 8; -pub const NETLINK_AUDIT: ::c_int = 9; -pub const NETLINK_FIB_LOOKUP: ::c_int = 10; -pub const NETLINK_CONNECTOR: ::c_int = 11; -pub const NETLINK_NETFILTER: ::c_int = 12; -pub const NETLINK_IP6_FW: ::c_int = 13; -pub const NETLINK_DNRTMSG: ::c_int = 14; -pub const NETLINK_KOBJECT_UEVENT: ::c_int = 15; -pub const NETLINK_GENERIC: ::c_int = 16; -pub const NETLINK_SCSITRANSPORT: ::c_int = 18; -pub const NETLINK_ECRYPTFS: ::c_int = 19; -pub const NETLINK_RDMA: ::c_int = 20; -pub const NETLINK_CRYPTO: ::c_int = 21; -pub const NETLINK_INET_DIAG: ::c_int = NETLINK_SOCK_DIAG; - -pub const MAX_LINKS: ::c_int = 32; - -pub const NLM_F_REQUEST: ::c_int = 1; -pub const NLM_F_MULTI: ::c_int = 2; -pub const NLM_F_ACK: ::c_int = 4; -pub const NLM_F_ECHO: ::c_int = 8; -pub const NLM_F_DUMP_INTR: ::c_int = 16; - -pub const NLM_F_ROOT: ::c_int = 0x100; -pub const NLM_F_MATCH: ::c_int = 0x200; -pub const NLM_F_ATOMIC: ::c_int = 0x400; -pub const NLM_F_DUMP: ::c_int = NLM_F_ROOT | NLM_F_MATCH; - -pub const NLM_F_REPLACE: ::c_int = 0x100; -pub const NLM_F_EXCL: ::c_int = 0x200; -pub const NLM_F_CREATE: ::c_int = 0x400; -pub const NLM_F_APPEND: ::c_int = 0x800; - -pub const NLMSG_NOOP: ::c_int = 0x1; -pub const NLMSG_ERROR: ::c_int = 0x2; -pub const NLMSG_DONE: ::c_int = 0x3; -pub const NLMSG_OVERRUN: ::c_int = 0x4; -pub const NLMSG_MIN_TYPE: ::c_int = 0x10; - -pub const NETLINK_ADD_MEMBERSHIP: ::c_int = 1; -pub const NETLINK_DROP_MEMBERSHIP: ::c_int = 2; -pub const NETLINK_PKTINFO: ::c_int = 3; -pub const NETLINK_BROADCAST_ERROR: ::c_int = 4; -pub const NETLINK_NO_ENOBUFS: ::c_int = 5; -pub const NETLINK_RX_RING: ::c_int = 6; -pub const NETLINK_TX_RING: ::c_int = 7; - -pub const GRND_NONBLOCK: ::c_uint = 0x0001; -pub const GRND_RANDOM: ::c_uint = 0x0002; - -pub const SECCOMP_MODE_DISABLED: ::c_uint = 0; -pub const SECCOMP_MODE_STRICT: ::c_uint = 1; -pub const SECCOMP_MODE_FILTER: ::c_uint = 2; - -pub const NLA_F_NESTED: ::c_int = 1 << 15; -pub const NLA_F_NET_BYTEORDER: ::c_int = 1 << 14; -pub const NLA_TYPE_MASK: ::c_int = !(NLA_F_NESTED | NLA_F_NET_BYTEORDER); - -pub const SIGEV_THREAD_ID: ::c_int = 4; - -pub const CIBAUD: ::tcflag_t = 0o02003600000; -pub const CBAUDEX: ::tcflag_t = 0o010000; - -pub const TIOCM_LE: ::c_int = 0x001; -pub const TIOCM_DTR: ::c_int = 0x002; -pub const TIOCM_RTS: ::c_int = 0x004; -pub const TIOCM_ST: ::c_int = 0x008; -pub const TIOCM_SR: ::c_int = 0x010; -pub const TIOCM_CTS: ::c_int = 0x020; -pub const TIOCM_CAR: ::c_int = 0x040; -pub const TIOCM_RNG: ::c_int = 0x080; -pub const TIOCM_DSR: ::c_int = 0x100; -pub const TIOCM_CD: ::c_int = TIOCM_CAR; -pub const TIOCM_RI: ::c_int = TIOCM_RNG; - -pub const POLLWRNORM: ::c_short = 0x100; -pub const POLLWRBAND: ::c_short = 0x200; - -pub const SFD_CLOEXEC: ::c_int = O_CLOEXEC; -pub const SFD_NONBLOCK: ::c_int = O_NONBLOCK; - -pub const SOCK_NONBLOCK: ::c_int = O_NONBLOCK; - -pub const SO_ORIGINAL_DST: ::c_int = 80; -pub const IUTF8: ::tcflag_t = 0x00004000; -pub const CMSPAR: ::tcflag_t = 0o10000000000; -pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; - -pub const MFD_CLOEXEC: ::c_uint = 0x0001; -pub const MFD_ALLOW_SEALING: ::c_uint = 0x0002; - -f! { - pub fn CPU_ZERO(cpuset: &mut cpu_set_t) -> () { - for slot in cpuset.__bits.iter_mut() { - *slot = 0; - } - } - - pub fn CPU_SET(cpu: usize, cpuset: &mut cpu_set_t) -> () { - let size_in___bits = 8 * mem::size_of_val(&cpuset.__bits[0]); - let (idx, offset) = (cpu / size_in___bits, cpu % size_in___bits); - cpuset.__bits[idx] |= 1 << offset; - () - } - - pub fn CPU_CLR(cpu: usize, cpuset: &mut cpu_set_t) -> () { - let size_in___bits = 8 * mem::size_of_val(&cpuset.__bits[0]); - let (idx, offset) = (cpu / size_in___bits, cpu % size_in___bits); - cpuset.__bits[idx] &= !(1 << offset); - () - } - - pub fn CPU_ISSET(cpu: usize, cpuset: &cpu_set_t) -> bool { - let size_in___bits = 8 * mem::size_of_val(&cpuset.__bits[0]); - let (idx, offset) = (cpu / size_in___bits, cpu % size_in___bits); - 0 != (cpuset.__bits[idx] & (1 << offset)) - } - - pub fn CPU_EQUAL(set1: &cpu_set_t, set2: &cpu_set_t) -> bool { - set1.__bits == set2.__bits - } - pub fn major(dev: ::dev_t) -> ::c_int { - ((dev >> 8) & 0xfff) as ::c_int - } - pub fn minor(dev: ::dev_t) -> ::c_int { - ((dev & 0xff) | ((dev >> 12) & 0xfff00)) as ::c_int - } - pub fn makedev(ma: ::c_int, mi: ::c_int) -> ::dev_t { - let ma = ma as ::dev_t; - let mi = mi as ::dev_t; - ((ma & 0xfff) << 8) | (mi & 0xff) | ((mi & 0xfff00) << 12) - } -} - -extern { - static mut __progname: *mut ::c_char; -} - -extern { - pub fn madvise(addr: *const ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - pub fn ioctl(fd: ::c_int, request: ::c_int, ...) -> ::c_int; - pub fn msync(addr: *const ::c_void, len: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn mprotect(addr: *const ::c_void, len: ::size_t, prot: ::c_int) - -> ::c_int; - pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, - flags: ::c_int, addr: *const ::sockaddr, - addrlen: *mut ::socklen_t) -> ::ssize_t; - pub fn getnameinfo(sa: *const ::sockaddr, - salen: ::socklen_t, - host: *mut ::c_char, - hostlen: ::size_t, - serv: *mut ::c_char, - sevlen: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn ptrace(request: ::c_int, ...) -> ::c_long; - pub fn getpriority(which: ::c_int, who: ::c_int) -> ::c_int; - pub fn setpriority(which: ::c_int, who: ::c_int, prio: ::c_int) -> ::c_int; - pub fn __sched_cpualloc(count: ::size_t) -> *mut ::cpu_set_t; - pub fn __sched_cpufree(set: *mut ::cpu_set_t); - pub fn __sched_cpucount(setsize: ::size_t, set: *mut cpu_set_t) -> ::c_int; - pub fn sched_getcpu() -> ::c_int; - - pub fn utmpname(name: *const ::c_char) -> ::c_int; - pub fn setutent(); - pub fn getutent() -> *mut utmp; - - pub fn posix_fallocate(fd: ::c_int, offset: ::off_t, - len: ::off_t) -> ::c_int; - pub fn signalfd(fd: ::c_int, mask: *const ::sigset_t, flags: ::c_int) - -> ::c_int; - pub fn syscall(num: ::c_long, ...) -> ::c_long; - pub fn sched_getaffinity(pid: ::pid_t, - cpusetsize: ::size_t, - cpuset: *mut cpu_set_t) -> ::c_int; - pub fn sched_setaffinity(pid: ::pid_t, - cpusetsize: ::size_t, - cpuset: *const cpu_set_t) -> ::c_int; - pub fn epoll_create(size: ::c_int) -> ::c_int; - pub fn epoll_create1(flags: ::c_int) -> ::c_int; - pub fn epoll_wait(epfd: ::c_int, - events: *mut ::epoll_event, - maxevents: ::c_int, - timeout: ::c_int) -> ::c_int; - pub fn epoll_ctl(epfd: ::c_int, - op: ::c_int, - fd: ::c_int, - event: *mut ::epoll_event) -> ::c_int; - pub fn pthread_getschedparam(native: ::pthread_t, - policy: *mut ::c_int, - param: *mut ::sched_param) -> ::c_int; - pub fn unshare(flags: ::c_int) -> ::c_int; - pub fn umount(target: *const ::c_char) -> ::c_int; - pub fn sched_get_priority_max(policy: ::c_int) -> ::c_int; - pub fn tee(fd_in: ::c_int, - fd_out: ::c_int, - len: ::size_t, - flags: ::c_uint) -> ::ssize_t; - pub fn settimeofday(tv: *const ::timeval, tz: *const ::timezone) -> ::c_int; - pub fn splice(fd_in: ::c_int, - off_in: *mut ::loff_t, - fd_out: ::c_int, - off_out: *mut ::loff_t, - len: ::size_t, - flags: ::c_uint) -> ::ssize_t; - pub fn eventfd(init: ::c_uint, flags: ::c_int) -> ::c_int; - pub fn sched_rr_get_interval(pid: ::pid_t, tp: *mut ::timespec) -> ::c_int; - pub fn sem_timedwait(sem: *mut sem_t, - abstime: *const ::timespec) -> ::c_int; - pub fn sched_setparam(pid: ::pid_t, param: *const ::sched_param) -> ::c_int; - pub fn setns(fd: ::c_int, nstype: ::c_int) -> ::c_int; - pub fn swapoff(puath: *const ::c_char) -> ::c_int; - pub fn vmsplice(fd: ::c_int, - iov: *const ::iovec, - nr_segs: ::size_t, - flags: ::c_uint) -> ::ssize_t; - pub fn mount(src: *const ::c_char, - target: *const ::c_char, - fstype: *const ::c_char, - flags: ::c_ulong, - data: *const ::c_void) -> ::c_int; - pub fn personality(persona: ::c_ulong) -> ::c_int; - pub fn prctl(option: ::c_int, ...) -> ::c_int; - pub fn sched_getparam(pid: ::pid_t, param: *mut ::sched_param) -> ::c_int; - pub fn ppoll(fds: *mut ::pollfd, - nfds: nfds_t, - timeout: *const ::timespec, - sigmask: *const sigset_t) -> ::c_int; - pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, - abstime: *const ::timespec) -> ::c_int; - pub fn clone(cb: extern fn(*mut ::c_void) -> ::c_int, - child_stack: *mut ::c_void, - flags: ::c_int, - arg: *mut ::c_void, ...) -> ::c_int; - pub fn sched_getscheduler(pid: ::pid_t) -> ::c_int; - pub fn clock_nanosleep(clk_id: ::clockid_t, - flags: ::c_int, - rqtp: *const ::timespec, - rmtp: *mut ::timespec) -> ::c_int; - pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, - guardsize: *mut ::size_t) -> ::c_int; - pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; - pub fn sched_get_priority_min(policy: ::c_int) -> ::c_int; - pub fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, - pshared: *mut ::c_int) -> ::c_int; - pub fn sysinfo(info: *mut ::sysinfo) -> ::c_int; - pub fn umount2(target: *const ::c_char, flags: ::c_int) -> ::c_int; - pub fn pthread_setschedparam(native: ::pthread_t, - policy: ::c_int, - param: *const ::sched_param) -> ::c_int; - pub fn swapon(path: *const ::c_char, swapflags: ::c_int) -> ::c_int; - pub fn sched_setscheduler(pid: ::pid_t, - policy: ::c_int, - param: *const ::sched_param) -> ::c_int; - pub fn sendfile(out_fd: ::c_int, - in_fd: ::c_int, - offset: *mut off_t, - count: ::size_t) -> ::ssize_t; - pub fn setfsgid(gid: ::gid_t) -> ::c_int; - pub fn setfsuid(uid: ::uid_t) -> ::c_int; - pub fn sigsuspend(mask: *const ::sigset_t) -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] - pub fn getgrgid_r(uid: ::uid_t, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "sigaltstack$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")] - pub fn sigaltstack(ss: *const stack_t, - oss: *mut stack_t) -> ::c_int; - pub fn sem_close(sem: *mut sem_t) -> ::c_int; - pub fn getdtablesize() -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] - pub fn getgrnam_r(name: *const ::c_char, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_sigmask$UNIX2003")] - pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, - oldset: *mut sigset_t) -> ::c_int; - pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; - pub fn getgrnam(name: *const ::c_char) -> *mut ::group; - pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; - pub fn sem_unlink(name: *const ::c_char) -> ::c_int; - pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] - pub fn getpwnam_r(name: *const ::c_char, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] - pub fn getpwuid_r(uid: ::uid_t, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch ="x86"), - link_name = "sigwait$UNIX2003")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] - pub fn sigwait(set: *const sigset_t, - sig: *mut ::c_int) -> ::c_int; - pub fn pthread_atfork(prepare: Option, - parent: Option, - child: Option) -> ::c_int; - pub fn getgrgid(gid: ::gid_t) -> *mut ::group; - pub fn getgrouplist(user: *const ::c_char, - group: ::gid_t, - groups: *mut ::gid_t, - ngroups: *mut ::c_int) -> ::c_int; - pub fn initgroups(user: *const ::c_char, group: ::gid_t) -> ::c_int; - pub fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, - pshared: *mut ::c_int) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "popen$UNIX2003")] - pub fn popen(command: *const c_char, - mode: *const c_char) -> *mut ::FILE; - pub fn faccessat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::c_int, flags: ::c_int) -> ::c_int; - pub fn pthread_create(native: *mut ::pthread_t, - attr: *const ::pthread_attr_t, - f: extern fn(*mut ::c_void) -> *mut ::c_void, - value: *mut ::c_void) -> ::c_int; - pub fn __errno() -> *mut ::c_int; -} - -cfg_if! { - if #[cfg(target_pointer_width = "32")] { - mod b32; - pub use self::b32::*; - } else if #[cfg(target_pointer_width = "64")] { - mod b64; - pub use self::b64::*; - } else { - // Unknown target_pointer_width - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/emscripten.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/emscripten.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/emscripten.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/emscripten.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1667 +0,0 @@ -use dox::{mem, Option}; - -pub type c_char = i8; -pub type wchar_t = i32; -pub type useconds_t = u32; -pub type dev_t = u32; -pub type socklen_t = u32; -pub type pthread_t = c_ulong; -pub type mode_t = u32; -pub type ino64_t = u32; -pub type off64_t = i32; -pub type blkcnt64_t = i32; -pub type rlim64_t = u64; -pub type shmatt_t = ::c_ulong; -pub type mqd_t = ::c_int; -pub type msgqnum_t = ::c_ulong; -pub type msglen_t = ::c_ulong; -pub type nfds_t = ::c_ulong; -pub type nl_item = ::c_int; -pub type idtype_t = ::c_uint; -pub type loff_t = i32; - -pub type clock_t = c_long; -pub type time_t = c_long; -pub type suseconds_t = c_long; -pub type ino_t = u32; -pub type off_t = i32; -pub type blkcnt_t = i32; - -pub type blksize_t = c_long; -pub type fsblkcnt_t = u32; -pub type fsfilcnt_t = u32; -pub type rlim_t = ::c_ulonglong; -pub type c_long = i32; -pub type c_ulong = u32; -pub type nlink_t = u32; - -pub enum fpos64_t {} // TODO: fill this out with a struct - -s! { - pub struct dirent { - pub d_ino: ::ino_t, - pub d_off: ::off_t, - pub d_reclen: ::c_ushort, - pub d_type: ::c_uchar, - pub d_name: [::c_char; 256], - } - - pub struct dirent64 { - pub d_ino: ::ino64_t, - pub d_off: ::off64_t, - pub d_reclen: ::c_ushort, - pub d_type: ::c_uchar, - pub d_name: [::c_char; 256], - } - - pub struct rlimit64 { - pub rlim_cur: rlim64_t, - pub rlim_max: rlim64_t, - } - - pub struct glob_t { - pub gl_pathc: ::size_t, - pub gl_pathv: *mut *mut c_char, - pub gl_offs: ::size_t, - pub gl_flags: ::c_int, - - __unused1: *mut ::c_void, - __unused2: *mut ::c_void, - __unused3: *mut ::c_void, - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - } - - pub struct ifaddrs { - pub ifa_next: *mut ifaddrs, - pub ifa_name: *mut c_char, - pub ifa_flags: ::c_uint, - pub ifa_addr: *mut ::sockaddr, - pub ifa_netmask: *mut ::sockaddr, - pub ifa_ifu: *mut ::sockaddr, // FIXME This should be a union - pub ifa_data: *mut ::c_void - } - - pub struct pthread_mutex_t { - __align: [::c_long; 0], - size: [u8; __SIZEOF_PTHREAD_MUTEX_T], - } - - pub struct pthread_rwlock_t { - __align: [::c_long; 0], - size: [u8; __SIZEOF_PTHREAD_RWLOCK_T], - } - - pub struct pthread_mutexattr_t { - __align: [::c_int; 0], - size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T], - } - - pub struct pthread_rwlockattr_t { - __align: [::c_int; 0], - size: [u8; __SIZEOF_PTHREAD_RWLOCKATTR_T], - } - - pub struct pthread_cond_t { - __align: [*const ::c_void; 0], - size: [u8; __SIZEOF_PTHREAD_COND_T], - } - - pub struct pthread_condattr_t { - __align: [::c_int; 0], - size: [u8; __SIZEOF_PTHREAD_CONDATTR_T], - } - - pub struct passwd { - pub pw_name: *mut ::c_char, - pub pw_passwd: *mut ::c_char, - pub pw_uid: ::uid_t, - pub pw_gid: ::gid_t, - pub pw_gecos: *mut ::c_char, - pub pw_dir: *mut ::c_char, - pub pw_shell: *mut ::c_char, - } - - pub struct spwd { - pub sp_namp: *mut ::c_char, - pub sp_pwdp: *mut ::c_char, - pub sp_lstchg: ::c_long, - pub sp_min: ::c_long, - pub sp_max: ::c_long, - pub sp_warn: ::c_long, - pub sp_inact: ::c_long, - pub sp_expire: ::c_long, - pub sp_flag: ::c_ulong, - } - - pub struct statvfs { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_favail: ::fsfilcnt_t, - pub f_fsid: ::c_ulong, - __f_unused: ::c_int, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct dqblk { - pub dqb_bhardlimit: ::uint64_t, - pub dqb_bsoftlimit: ::uint64_t, - pub dqb_curspace: ::uint64_t, - pub dqb_ihardlimit: ::uint64_t, - pub dqb_isoftlimit: ::uint64_t, - pub dqb_curinodes: ::uint64_t, - pub dqb_btime: ::uint64_t, - pub dqb_itime: ::uint64_t, - pub dqb_valid: ::uint32_t, - } - - pub struct signalfd_siginfo { - pub ssi_signo: ::uint32_t, - pub ssi_errno: ::int32_t, - pub ssi_code: ::int32_t, - pub ssi_pid: ::uint32_t, - pub ssi_uid: ::uint32_t, - pub ssi_fd: ::int32_t, - pub ssi_tid: ::uint32_t, - pub ssi_band: ::uint32_t, - pub ssi_overrun: ::uint32_t, - pub ssi_trapno: ::uint32_t, - pub ssi_status: ::int32_t, - pub ssi_int: ::int32_t, - pub ssi_ptr: ::uint64_t, - pub ssi_utime: ::uint64_t, - pub ssi_stime: ::uint64_t, - pub ssi_addr: ::uint64_t, - _pad: [::uint8_t; 48], - } - - pub struct fsid_t { - __val: [::c_int; 2], - } - - pub struct mq_attr { - pub mq_flags: ::c_long, - pub mq_maxmsg: ::c_long, - pub mq_msgsize: ::c_long, - pub mq_curmsgs: ::c_long, - pad: [::c_long; 4] - } - - pub struct cpu_set_t { - bits: [u32; 32], - } - - pub struct if_nameindex { - pub if_index: ::c_uint, - pub if_name: *mut ::c_char, - } - - // System V IPC - pub struct msginfo { - pub msgpool: ::c_int, - pub msgmap: ::c_int, - pub msgmax: ::c_int, - pub msgmnb: ::c_int, - pub msgmni: ::c_int, - pub msgssz: ::c_int, - pub msgtql: ::c_int, - pub msgseg: ::c_ushort, - } - - pub struct mmsghdr { - pub msg_hdr: ::msghdr, - pub msg_len: ::c_uint, - } - - pub struct sembuf { - pub sem_num: ::c_ushort, - pub sem_op: ::c_short, - pub sem_flg: ::c_short, - } - - pub struct aiocb { - pub aio_fildes: ::c_int, - pub aio_lio_opcode: ::c_int, - pub aio_reqprio: ::c_int, - pub aio_buf: *mut ::c_void, - pub aio_nbytes: ::size_t, - pub aio_sigevent: ::sigevent, - __td: *mut ::c_void, - __lock: [::c_int; 2], - __err: ::c_int, - __ret: ::ssize_t, - pub aio_offset: off_t, - __next: *mut ::c_void, - __prev: *mut ::c_void, - __dummy4: [::c_char; 24], - } - - pub struct sigaction { - pub sa_sigaction: ::sighandler_t, - pub sa_mask: ::sigset_t, - pub sa_flags: ::c_int, - pub sa_restorer: ::dox::Option, - } - - pub struct ipc_perm { - pub __ipc_perm_key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::mode_t, - pub __seq: ::c_int, - __unused1: ::c_long, - __unused2: ::c_long - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; ::NCCS], - pub __c_ispeed: ::speed_t, - pub __c_ospeed: ::speed_t, - } - - pub struct flock { - pub l_type: ::c_short, - pub l_whence: ::c_short, - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_pid: ::pid_t, - } - - pub struct sysinfo { - pub uptime: ::c_ulong, - pub loads: [::c_ulong; 3], - pub totalram: ::c_ulong, - pub freeram: ::c_ulong, - pub sharedram: ::c_ulong, - pub bufferram: ::c_ulong, - pub totalswap: ::c_ulong, - pub freeswap: ::c_ulong, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: ::c_ulong, - pub freehigh: ::c_ulong, - pub mem_unit: ::c_uint, - pub __reserved: [::c_char; 256], - } - - pub struct pthread_attr_t { - __size: [u32; 11] - } - - pub struct sigset_t { - __val: [::c_ulong; 32], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::c_int, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::socklen_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::socklen_t, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct sem_t { - __val: [::c_int; 4], - } - pub struct stat { - pub st_dev: ::dev_t, - __st_dev_padding: ::c_int, - __st_ino_truncated: ::c_long, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __st_rdev_padding: ::c_int, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_ino: ::ino_t, - } - - pub struct stat64 { - pub st_dev: ::dev_t, - __st_dev_padding: ::c_int, - __st_ino_truncated: ::c_long, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __st_rdev_padding: ::c_int, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_ino: ::ino_t, - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_flags: ::c_int, - pub ss_size: ::size_t - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - __unused1: ::c_int, - pub shm_dtime: ::time_t, - __unused2: ::c_int, - pub shm_ctime: ::time_t, - __unused3: ::c_int, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::c_ulong, - __pad1: ::c_ulong, - __pad2: ::c_ulong, - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - pub msg_stime: ::time_t, - __unused1: ::c_int, - pub msg_rtime: ::time_t, - __unused2: ::c_int, - pub msg_ctime: ::time_t, - __unused3: ::c_int, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __pad1: ::c_ulong, - __pad2: ::c_ulong, - } - - pub struct statfs { - pub f_type: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_flags: ::c_ulong, - pub f_spare: [::c_ulong; 4], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_errno: ::c_int, - pub si_code: ::c_int, - pub _pad: [::c_int; 29], - _align: [usize; 0], - } - - pub struct statfs64 { - pub f_type: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_flags: ::c_ulong, - pub f_spare: [::c_ulong; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u32, - pub f_bfree: u32, - pub f_bavail: u32, - pub f_files: u32, - pub f_ffree: u32, - pub f_favail: u32, - pub f_fsid: ::c_ulong, - __f_unused: ::c_int, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } -} - -pub const ABDAY_1: ::nl_item = 0x20000; -pub const ABDAY_2: ::nl_item = 0x20001; -pub const ABDAY_3: ::nl_item = 0x20002; -pub const ABDAY_4: ::nl_item = 0x20003; -pub const ABDAY_5: ::nl_item = 0x20004; -pub const ABDAY_6: ::nl_item = 0x20005; -pub const ABDAY_7: ::nl_item = 0x20006; - -pub const DAY_1: ::nl_item = 0x20007; -pub const DAY_2: ::nl_item = 0x20008; -pub const DAY_3: ::nl_item = 0x20009; -pub const DAY_4: ::nl_item = 0x2000A; -pub const DAY_5: ::nl_item = 0x2000B; -pub const DAY_6: ::nl_item = 0x2000C; -pub const DAY_7: ::nl_item = 0x2000D; - -pub const ABMON_1: ::nl_item = 0x2000E; -pub const ABMON_2: ::nl_item = 0x2000F; -pub const ABMON_3: ::nl_item = 0x20010; -pub const ABMON_4: ::nl_item = 0x20011; -pub const ABMON_5: ::nl_item = 0x20012; -pub const ABMON_6: ::nl_item = 0x20013; -pub const ABMON_7: ::nl_item = 0x20014; -pub const ABMON_8: ::nl_item = 0x20015; -pub const ABMON_9: ::nl_item = 0x20016; -pub const ABMON_10: ::nl_item = 0x20017; -pub const ABMON_11: ::nl_item = 0x20018; -pub const ABMON_12: ::nl_item = 0x20019; - -pub const MON_1: ::nl_item = 0x2001A; -pub const MON_2: ::nl_item = 0x2001B; -pub const MON_3: ::nl_item = 0x2001C; -pub const MON_4: ::nl_item = 0x2001D; -pub const MON_5: ::nl_item = 0x2001E; -pub const MON_6: ::nl_item = 0x2001F; -pub const MON_7: ::nl_item = 0x20020; -pub const MON_8: ::nl_item = 0x20021; -pub const MON_9: ::nl_item = 0x20022; -pub const MON_10: ::nl_item = 0x20023; -pub const MON_11: ::nl_item = 0x20024; -pub const MON_12: ::nl_item = 0x20025; - -pub const AM_STR: ::nl_item = 0x20026; -pub const PM_STR: ::nl_item = 0x20027; - -pub const D_T_FMT: ::nl_item = 0x20028; -pub const D_FMT: ::nl_item = 0x20029; -pub const T_FMT: ::nl_item = 0x2002A; -pub const T_FMT_AMPM: ::nl_item = 0x2002B; - -pub const ERA: ::nl_item = 0x2002C; -pub const ERA_D_FMT: ::nl_item = 0x2002E; -pub const ALT_DIGITS: ::nl_item = 0x2002F; -pub const ERA_D_T_FMT: ::nl_item = 0x20030; -pub const ERA_T_FMT: ::nl_item = 0x20031; - -pub const CODESET: ::nl_item = 14; - -pub const CRNCYSTR: ::nl_item = 0x4000F; - -pub const RUSAGE_THREAD: ::c_int = 1; -pub const RUSAGE_CHILDREN: ::c_int = -1; - -pub const RADIXCHAR: ::nl_item = 0x10000; -pub const THOUSEP: ::nl_item = 0x10001; - -pub const YESEXPR: ::nl_item = 0x50000; -pub const NOEXPR: ::nl_item = 0x50001; -pub const YESSTR: ::nl_item = 0x50002; -pub const NOSTR: ::nl_item = 0x50003; - -pub const FILENAME_MAX: ::c_uint = 4096; -pub const L_tmpnam: ::c_uint = 20; -pub const _PC_LINK_MAX: ::c_int = 0; -pub const _PC_MAX_CANON: ::c_int = 1; -pub const _PC_MAX_INPUT: ::c_int = 2; -pub const _PC_NAME_MAX: ::c_int = 3; -pub const _PC_PATH_MAX: ::c_int = 4; -pub const _PC_PIPE_BUF: ::c_int = 5; -pub const _PC_CHOWN_RESTRICTED: ::c_int = 6; -pub const _PC_NO_TRUNC: ::c_int = 7; -pub const _PC_VDISABLE: ::c_int = 8; -pub const _PC_SYNC_IO: ::c_int = 9; -pub const _PC_ASYNC_IO: ::c_int = 10; -pub const _PC_PRIO_IO: ::c_int = 11; -pub const _PC_SOCK_MAXBUF: ::c_int = 12; -pub const _PC_FILESIZEBITS: ::c_int = 13; -pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 14; -pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 15; -pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 16; -pub const _PC_REC_XFER_ALIGN: ::c_int = 17; -pub const _PC_ALLOC_SIZE_MIN: ::c_int = 18; -pub const _PC_SYMLINK_MAX: ::c_int = 19; -pub const _PC_2_SYMLINKS: ::c_int = 20; - -pub const _SC_ARG_MAX: ::c_int = 0; -pub const _SC_CHILD_MAX: ::c_int = 1; -pub const _SC_CLK_TCK: ::c_int = 2; -pub const _SC_NGROUPS_MAX: ::c_int = 3; -pub const _SC_OPEN_MAX: ::c_int = 4; -pub const _SC_STREAM_MAX: ::c_int = 5; -pub const _SC_TZNAME_MAX: ::c_int = 6; -pub const _SC_JOB_CONTROL: ::c_int = 7; -pub const _SC_SAVED_IDS: ::c_int = 8; -pub const _SC_REALTIME_SIGNALS: ::c_int = 9; -pub const _SC_PRIORITY_SCHEDULING: ::c_int = 10; -pub const _SC_TIMERS: ::c_int = 11; -pub const _SC_ASYNCHRONOUS_IO: ::c_int = 12; -pub const _SC_PRIORITIZED_IO: ::c_int = 13; -pub const _SC_SYNCHRONIZED_IO: ::c_int = 14; -pub const _SC_FSYNC: ::c_int = 15; -pub const _SC_MAPPED_FILES: ::c_int = 16; -pub const _SC_MEMLOCK: ::c_int = 17; -pub const _SC_MEMLOCK_RANGE: ::c_int = 18; -pub const _SC_MEMORY_PROTECTION: ::c_int = 19; -pub const _SC_MESSAGE_PASSING: ::c_int = 20; -pub const _SC_SEMAPHORES: ::c_int = 21; -pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 22; -pub const _SC_AIO_LISTIO_MAX: ::c_int = 23; -pub const _SC_AIO_MAX: ::c_int = 24; -pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 25; -pub const _SC_DELAYTIMER_MAX: ::c_int = 26; -pub const _SC_MQ_OPEN_MAX: ::c_int = 27; -pub const _SC_MQ_PRIO_MAX: ::c_int = 28; -pub const _SC_VERSION: ::c_int = 29; -pub const _SC_PAGESIZE: ::c_int = 30; -pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; -pub const _SC_RTSIG_MAX: ::c_int = 31; -pub const _SC_SEM_NSEMS_MAX: ::c_int = 32; -pub const _SC_SEM_VALUE_MAX: ::c_int = 33; -pub const _SC_SIGQUEUE_MAX: ::c_int = 34; -pub const _SC_TIMER_MAX: ::c_int = 35; -pub const _SC_BC_BASE_MAX: ::c_int = 36; -pub const _SC_BC_DIM_MAX: ::c_int = 37; -pub const _SC_BC_SCALE_MAX: ::c_int = 38; -pub const _SC_BC_STRING_MAX: ::c_int = 39; -pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 40; -pub const _SC_EXPR_NEST_MAX: ::c_int = 42; -pub const _SC_LINE_MAX: ::c_int = 43; -pub const _SC_RE_DUP_MAX: ::c_int = 44; -pub const _SC_2_VERSION: ::c_int = 46; -pub const _SC_2_C_BIND: ::c_int = 47; -pub const _SC_2_C_DEV: ::c_int = 48; -pub const _SC_2_FORT_DEV: ::c_int = 49; -pub const _SC_2_FORT_RUN: ::c_int = 50; -pub const _SC_2_SW_DEV: ::c_int = 51; -pub const _SC_2_LOCALEDEF: ::c_int = 52; -pub const _SC_UIO_MAXIOV: ::c_int = 60; -pub const _SC_IOV_MAX: ::c_int = 60; -pub const _SC_THREADS: ::c_int = 67; -pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 68; -pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 69; -pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 70; -pub const _SC_LOGIN_NAME_MAX: ::c_int = 71; -pub const _SC_TTY_NAME_MAX: ::c_int = 72; -pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 73; -pub const _SC_THREAD_KEYS_MAX: ::c_int = 74; -pub const _SC_THREAD_STACK_MIN: ::c_int = 75; -pub const _SC_THREAD_THREADS_MAX: ::c_int = 76; -pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 77; -pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 78; -pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 79; -pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 80; -pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 81; -pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 82; -pub const _SC_NPROCESSORS_CONF: ::c_int = 83; -pub const _SC_NPROCESSORS_ONLN: ::c_int = 84; -pub const _SC_PHYS_PAGES: ::c_int = 85; -pub const _SC_AVPHYS_PAGES: ::c_int = 86; -pub const _SC_ATEXIT_MAX: ::c_int = 87; -pub const _SC_PASS_MAX: ::c_int = 88; -pub const _SC_XOPEN_VERSION: ::c_int = 89; -pub const _SC_XOPEN_XCU_VERSION: ::c_int = 90; -pub const _SC_XOPEN_UNIX: ::c_int = 91; -pub const _SC_XOPEN_CRYPT: ::c_int = 92; -pub const _SC_XOPEN_ENH_I18N: ::c_int = 93; -pub const _SC_XOPEN_SHM: ::c_int = 94; -pub const _SC_2_CHAR_TERM: ::c_int = 95; -pub const _SC_2_UPE: ::c_int = 97; -pub const _SC_XOPEN_XPG2: ::c_int = 98; -pub const _SC_XOPEN_XPG3: ::c_int = 99; -pub const _SC_XOPEN_XPG4: ::c_int = 100; -pub const _SC_NZERO: ::c_int = 109; -pub const _SC_XBS5_ILP32_OFF32: ::c_int = 125; -pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 126; -pub const _SC_XBS5_LP64_OFF64: ::c_int = 127; -pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 128; -pub const _SC_XOPEN_LEGACY: ::c_int = 129; -pub const _SC_XOPEN_REALTIME: ::c_int = 130; -pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 131; -pub const _SC_ADVISORY_INFO: ::c_int = 132; -pub const _SC_BARRIERS: ::c_int = 133; -pub const _SC_CLOCK_SELECTION: ::c_int = 137; -pub const _SC_CPUTIME: ::c_int = 138; -pub const _SC_THREAD_CPUTIME: ::c_int = 139; -pub const _SC_MONOTONIC_CLOCK: ::c_int = 149; -pub const _SC_READER_WRITER_LOCKS: ::c_int = 153; -pub const _SC_SPIN_LOCKS: ::c_int = 154; -pub const _SC_REGEXP: ::c_int = 155; -pub const _SC_SHELL: ::c_int = 157; -pub const _SC_SPAWN: ::c_int = 159; -pub const _SC_SPORADIC_SERVER: ::c_int = 160; -pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 161; -pub const _SC_TIMEOUTS: ::c_int = 164; -pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 165; -pub const _SC_2_PBS: ::c_int = 168; -pub const _SC_2_PBS_ACCOUNTING: ::c_int = 169; -pub const _SC_2_PBS_LOCATE: ::c_int = 170; -pub const _SC_2_PBS_MESSAGE: ::c_int = 171; -pub const _SC_2_PBS_TRACK: ::c_int = 172; -pub const _SC_SYMLOOP_MAX: ::c_int = 173; -pub const _SC_STREAMS: ::c_int = 174; -pub const _SC_2_PBS_CHECKPOINT: ::c_int = 175; -pub const _SC_V6_ILP32_OFF32: ::c_int = 176; -pub const _SC_V6_ILP32_OFFBIG: ::c_int = 177; -pub const _SC_V6_LP64_OFF64: ::c_int = 178; -pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 179; -pub const _SC_HOST_NAME_MAX: ::c_int = 180; -pub const _SC_TRACE: ::c_int = 181; -pub const _SC_TRACE_EVENT_FILTER: ::c_int = 182; -pub const _SC_TRACE_INHERIT: ::c_int = 183; -pub const _SC_TRACE_LOG: ::c_int = 184; -pub const _SC_IPV6: ::c_int = 235; -pub const _SC_RAW_SOCKETS: ::c_int = 236; -pub const _SC_V7_ILP32_OFF32: ::c_int = 237; -pub const _SC_V7_ILP32_OFFBIG: ::c_int = 238; -pub const _SC_V7_LP64_OFF64: ::c_int = 239; -pub const _SC_V7_LPBIG_OFFBIG: ::c_int = 240; -pub const _SC_SS_REPL_MAX: ::c_int = 241; -pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 242; -pub const _SC_TRACE_NAME_MAX: ::c_int = 243; -pub const _SC_TRACE_SYS_MAX: ::c_int = 244; -pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 245; -pub const _SC_XOPEN_STREAMS: ::c_int = 246; -pub const _SC_THREAD_ROBUST_PRIO_INHERIT: ::c_int = 247; -pub const _SC_THREAD_ROBUST_PRIO_PROTECT: ::c_int = 248; - -pub const RLIM_SAVED_MAX: ::rlim_t = RLIM_INFINITY; -pub const RLIM_SAVED_CUR: ::rlim_t = RLIM_INFINITY; - -pub const GLOB_ERR: ::c_int = 1 << 0; -pub const GLOB_MARK: ::c_int = 1 << 1; -pub const GLOB_NOSORT: ::c_int = 1 << 2; -pub const GLOB_DOOFFS: ::c_int = 1 << 3; -pub const GLOB_NOCHECK: ::c_int = 1 << 4; -pub const GLOB_APPEND: ::c_int = 1 << 5; -pub const GLOB_NOESCAPE: ::c_int = 1 << 6; - -pub const GLOB_NOSPACE: ::c_int = 1; -pub const GLOB_ABORTED: ::c_int = 2; -pub const GLOB_NOMATCH: ::c_int = 3; - -pub const POSIX_MADV_NORMAL: ::c_int = 0; -pub const POSIX_MADV_RANDOM: ::c_int = 1; -pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; -pub const POSIX_MADV_WILLNEED: ::c_int = 3; - -pub const S_IEXEC: mode_t = 64; -pub const S_IWRITE: mode_t = 128; -pub const S_IREAD: mode_t = 256; - -pub const F_LOCK: ::c_int = 1; -pub const F_TEST: ::c_int = 3; -pub const F_TLOCK: ::c_int = 2; -pub const F_ULOCK: ::c_int = 0; - -pub const ST_RDONLY: ::c_ulong = 1; -pub const ST_NOSUID: ::c_ulong = 2; -pub const ST_NODEV: ::c_ulong = 4; -pub const ST_NOEXEC: ::c_ulong = 8; -pub const ST_SYNCHRONOUS: ::c_ulong = 16; -pub const ST_MANDLOCK: ::c_ulong = 64; -pub const ST_WRITE: ::c_ulong = 128; -pub const ST_APPEND: ::c_ulong = 256; -pub const ST_IMMUTABLE: ::c_ulong = 512; -pub const ST_NOATIME: ::c_ulong = 1024; -pub const ST_NODIRATIME: ::c_ulong = 2048; - -pub const RTLD_NEXT: *mut ::c_void = -1i64 as *mut ::c_void; -pub const RTLD_DEFAULT: *mut ::c_void = 0i64 as *mut ::c_void; -pub const RTLD_NODELETE: ::c_int = 0x1000; -pub const RTLD_NOW: ::c_int = 0x2; - -pub const TCP_MD5SIG: ::c_int = 14; - -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_MUTEX_T], -}; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_COND_T], -}; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_RWLOCK_T], -}; -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; -pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; -pub const PTHREAD_PROCESS_PRIVATE: ::c_int = 0; -pub const PTHREAD_PROCESS_SHARED: ::c_int = 1; -pub const __SIZEOF_PTHREAD_COND_T: usize = 48; - -pub const SCHED_OTHER: ::c_int = 0; -pub const SCHED_FIFO: ::c_int = 1; -pub const SCHED_RR: ::c_int = 2; -pub const SCHED_BATCH: ::c_int = 3; -pub const SCHED_IDLE: ::c_int = 5; - -pub const AF_IB: ::c_int = 27; -pub const AF_MPLS: ::c_int = 28; -pub const AF_NFC: ::c_int = 39; -pub const AF_VSOCK: ::c_int = 40; -#[doc(hidden)] -pub const AF_MAX: ::c_int = 42; -pub const PF_IB: ::c_int = AF_IB; -pub const PF_MPLS: ::c_int = AF_MPLS; -pub const PF_NFC: ::c_int = AF_NFC; -pub const PF_VSOCK: ::c_int = AF_VSOCK; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; - -// System V IPC -pub const IPC_PRIVATE: ::key_t = 0; - -pub const IPC_CREAT: ::c_int = 0o1000; -pub const IPC_EXCL: ::c_int = 0o2000; -pub const IPC_NOWAIT: ::c_int = 0o4000; - -pub const IPC_RMID: ::c_int = 0; -pub const IPC_SET: ::c_int = 1; -pub const IPC_STAT: ::c_int = 2; -pub const IPC_INFO: ::c_int = 3; -pub const MSG_STAT: ::c_int = 11; -pub const MSG_INFO: ::c_int = 12; - -pub const MSG_NOERROR: ::c_int = 0o10000; -pub const MSG_EXCEPT: ::c_int = 0o20000; -pub const MSG_COPY: ::c_int = 0o40000; - -pub const SHM_R: ::c_int = 0o400; -pub const SHM_W: ::c_int = 0o200; - -pub const SHM_RDONLY: ::c_int = 0o10000; -pub const SHM_RND: ::c_int = 0o20000; -pub const SHM_REMAP: ::c_int = 0o40000; -pub const SHM_EXEC: ::c_int = 0o100000; - -pub const SHM_LOCK: ::c_int = 11; -pub const SHM_UNLOCK: ::c_int = 12; - -pub const SHM_HUGETLB: ::c_int = 0o4000; -pub const SHM_NORESERVE: ::c_int = 0o10000; - -pub const EPOLLRDHUP: ::c_int = 0x2000; -pub const EPOLLEXCLUSIVE: ::c_int = 0x10000000; -pub const EPOLLONESHOT: ::c_int = 0x40000000; - -pub const QFMT_VFS_OLD: ::c_int = 1; -pub const QFMT_VFS_V0: ::c_int = 2; - -pub const EFD_SEMAPHORE: ::c_int = 0x1; - -pub const LOG_NFACILITIES: ::c_int = 24; - -pub const SEM_FAILED: *mut ::sem_t = 0 as *mut sem_t; - -pub const RB_AUTOBOOT: ::c_int = 0x01234567u32 as i32; -pub const RB_HALT_SYSTEM: ::c_int = 0xcdef0123u32 as i32; -pub const RB_ENABLE_CAD: ::c_int = 0x89abcdefu32 as i32; -pub const RB_DISABLE_CAD: ::c_int = 0x00000000u32 as i32; -pub const RB_POWER_OFF: ::c_int = 0x4321fedcu32 as i32; -pub const RB_SW_SUSPEND: ::c_int = 0xd000fce2u32 as i32; -pub const RB_KEXEC: ::c_int = 0x45584543u32 as i32; - -pub const AI_PASSIVE: ::c_int = 0x0001; -pub const AI_CANONNAME: ::c_int = 0x0002; -pub const AI_NUMERICHOST: ::c_int = 0x0004; -pub const AI_V4MAPPED: ::c_int = 0x0008; -pub const AI_ALL: ::c_int = 0x0010; -pub const AI_ADDRCONFIG: ::c_int = 0x0020; - -pub const AI_NUMERICSERV: ::c_int = 0x0400; - -pub const EAI_BADFLAGS: ::c_int = -1; -pub const EAI_NONAME: ::c_int = -2; -pub const EAI_AGAIN: ::c_int = -3; -pub const EAI_FAIL: ::c_int = -4; -pub const EAI_FAMILY: ::c_int = -6; -pub const EAI_SOCKTYPE: ::c_int = -7; -pub const EAI_SERVICE: ::c_int = -8; -pub const EAI_MEMORY: ::c_int = -10; -pub const EAI_OVERFLOW: ::c_int = -12; - -pub const NI_NUMERICHOST: ::c_int = 1; -pub const NI_NUMERICSERV: ::c_int = 2; -pub const NI_NOFQDN: ::c_int = 4; -pub const NI_NAMEREQD: ::c_int = 8; -pub const NI_DGRAM: ::c_int = 16; - -pub const SYNC_FILE_RANGE_WAIT_BEFORE: ::c_uint = 1; -pub const SYNC_FILE_RANGE_WRITE: ::c_uint = 2; -pub const SYNC_FILE_RANGE_WAIT_AFTER: ::c_uint = 4; - -pub const EAI_SYSTEM: ::c_int = -11; - -pub const AIO_CANCELED: ::c_int = 0; -pub const AIO_NOTCANCELED: ::c_int = 1; -pub const AIO_ALLDONE: ::c_int = 2; -pub const LIO_READ: ::c_int = 0; -pub const LIO_WRITE: ::c_int = 1; -pub const LIO_NOP: ::c_int = 2; -pub const LIO_WAIT: ::c_int = 0; -pub const LIO_NOWAIT: ::c_int = 1; - -pub const MREMAP_MAYMOVE: ::c_int = 1; -pub const MREMAP_FIXED: ::c_int = 2; - -pub const PR_SET_PDEATHSIG: ::c_int = 1; -pub const PR_GET_PDEATHSIG: ::c_int = 2; - -pub const PR_GET_DUMPABLE: ::c_int = 3; -pub const PR_SET_DUMPABLE: ::c_int = 4; - -pub const PR_GET_UNALIGN: ::c_int = 5; -pub const PR_SET_UNALIGN: ::c_int = 6; -pub const PR_UNALIGN_NOPRINT: ::c_int = 1; -pub const PR_UNALIGN_SIGBUS: ::c_int = 2; - -pub const PR_GET_KEEPCAPS: ::c_int = 7; -pub const PR_SET_KEEPCAPS: ::c_int = 8; - -pub const PR_GET_FPEMU: ::c_int = 9; -pub const PR_SET_FPEMU: ::c_int = 10; -pub const PR_FPEMU_NOPRINT: ::c_int = 1; -pub const PR_FPEMU_SIGFPE: ::c_int = 2; - -pub const PR_GET_FPEXC: ::c_int = 11; -pub const PR_SET_FPEXC: ::c_int = 12; -pub const PR_FP_EXC_SW_ENABLE: ::c_int = 0x80; -pub const PR_FP_EXC_DIV: ::c_int = 0x010000; -pub const PR_FP_EXC_OVF: ::c_int = 0x020000; -pub const PR_FP_EXC_UND: ::c_int = 0x040000; -pub const PR_FP_EXC_RES: ::c_int = 0x080000; -pub const PR_FP_EXC_INV: ::c_int = 0x100000; -pub const PR_FP_EXC_DISABLED: ::c_int = 0; -pub const PR_FP_EXC_NONRECOV: ::c_int = 1; -pub const PR_FP_EXC_ASYNC: ::c_int = 2; -pub const PR_FP_EXC_PRECISE: ::c_int = 3; - -pub const PR_GET_TIMING: ::c_int = 13; -pub const PR_SET_TIMING: ::c_int = 14; -pub const PR_TIMING_STATISTICAL: ::c_int = 0; -pub const PR_TIMING_TIMESTAMP: ::c_int = 1; - -pub const PR_SET_NAME: ::c_int = 15; -pub const PR_GET_NAME: ::c_int = 16; - -pub const PR_GET_ENDIAN: ::c_int = 19; -pub const PR_SET_ENDIAN: ::c_int = 20; -pub const PR_ENDIAN_BIG: ::c_int = 0; -pub const PR_ENDIAN_LITTLE: ::c_int = 1; -pub const PR_ENDIAN_PPC_LITTLE: ::c_int = 2; - -pub const PR_GET_SECCOMP: ::c_int = 21; -pub const PR_SET_SECCOMP: ::c_int = 22; - -pub const PR_CAPBSET_READ: ::c_int = 23; -pub const PR_CAPBSET_DROP: ::c_int = 24; - -pub const PR_GET_TSC: ::c_int = 25; -pub const PR_SET_TSC: ::c_int = 26; -pub const PR_TSC_ENABLE: ::c_int = 1; -pub const PR_TSC_SIGSEGV: ::c_int = 2; - -pub const PR_GET_SECUREBITS: ::c_int = 27; -pub const PR_SET_SECUREBITS: ::c_int = 28; - -pub const PR_SET_TIMERSLACK: ::c_int = 29; -pub const PR_GET_TIMERSLACK: ::c_int = 30; - -pub const PR_TASK_PERF_EVENTS_DISABLE: ::c_int = 31; -pub const PR_TASK_PERF_EVENTS_ENABLE: ::c_int = 32; - -pub const PR_MCE_KILL: ::c_int = 33; -pub const PR_MCE_KILL_CLEAR: ::c_int = 0; -pub const PR_MCE_KILL_SET: ::c_int = 1; - -pub const PR_MCE_KILL_LATE: ::c_int = 0; -pub const PR_MCE_KILL_EARLY: ::c_int = 1; -pub const PR_MCE_KILL_DEFAULT: ::c_int = 2; - -pub const PR_MCE_KILL_GET: ::c_int = 34; - -pub const PR_SET_MM: ::c_int = 35; -pub const PR_SET_MM_START_CODE: ::c_int = 1; -pub const PR_SET_MM_END_CODE: ::c_int = 2; -pub const PR_SET_MM_START_DATA: ::c_int = 3; -pub const PR_SET_MM_END_DATA: ::c_int = 4; -pub const PR_SET_MM_START_STACK: ::c_int = 5; -pub const PR_SET_MM_START_BRK: ::c_int = 6; -pub const PR_SET_MM_BRK: ::c_int = 7; -pub const PR_SET_MM_ARG_START: ::c_int = 8; -pub const PR_SET_MM_ARG_END: ::c_int = 9; -pub const PR_SET_MM_ENV_START: ::c_int = 10; -pub const PR_SET_MM_ENV_END: ::c_int = 11; -pub const PR_SET_MM_AUXV: ::c_int = 12; -pub const PR_SET_MM_EXE_FILE: ::c_int = 13; -pub const PR_SET_MM_MAP: ::c_int = 14; -pub const PR_SET_MM_MAP_SIZE: ::c_int = 15; - -pub const PR_SET_PTRACER: ::c_int = 0x59616d61; - -pub const PR_SET_CHILD_SUBREAPER: ::c_int = 36; -pub const PR_GET_CHILD_SUBREAPER: ::c_int = 37; - -pub const PR_SET_NO_NEW_PRIVS: ::c_int = 38; -pub const PR_GET_NO_NEW_PRIVS: ::c_int = 39; - -pub const PR_GET_TID_ADDRESS: ::c_int = 40; - -pub const PR_SET_THP_DISABLE: ::c_int = 41; -pub const PR_GET_THP_DISABLE: ::c_int = 42; - -pub const PR_MPX_ENABLE_MANAGEMENT: ::c_int = 43; -pub const PR_MPX_DISABLE_MANAGEMENT: ::c_int = 44; - -pub const PR_SET_FP_MODE: ::c_int = 45; -pub const PR_GET_FP_MODE: ::c_int = 46; -pub const PR_FP_MODE_FR: ::c_int = 1 << 0; -pub const PR_FP_MODE_FRE: ::c_int = 1 << 1; - -pub const PR_CAP_AMBIENT: ::c_int = 47; -pub const PR_CAP_AMBIENT_IS_SET: ::c_int = 1; -pub const PR_CAP_AMBIENT_RAISE: ::c_int = 2; -pub const PR_CAP_AMBIENT_LOWER: ::c_int = 3; -pub const PR_CAP_AMBIENT_CLEAR_ALL: ::c_int = 4; - -pub const ITIMER_REAL: ::c_int = 0; -pub const ITIMER_VIRTUAL: ::c_int = 1; -pub const ITIMER_PROF: ::c_int = 2; - -pub const XATTR_CREATE: ::c_int = 0x1; -pub const XATTR_REPLACE: ::c_int = 0x2; - -pub const _POSIX_VDISABLE: ::cc_t = 0; - -pub const FALLOC_FL_KEEP_SIZE: ::c_int = 0x01; -pub const FALLOC_FL_PUNCH_HOLE: ::c_int = 0x02; -pub const FALLOC_FL_COLLAPSE_RANGE: ::c_int = 0x08; -pub const FALLOC_FL_ZERO_RANGE: ::c_int = 0x10; -pub const FALLOC_FL_INSERT_RANGE: ::c_int = 0x20; -pub const FALLOC_FL_UNSHARE_RANGE: ::c_int = 0x40; - -// On Linux, libc doesn't define this constant, libattr does instead. -// We still define it for Linux as it's defined by libc on other platforms, -// and it's mentioned in the man pages for getxattr and setxattr. -pub const SFD_CLOEXEC: ::c_int = 0x080000; - -pub const NCCS: usize = 32; - -pub const O_TRUNC: ::c_int = 512; -pub const O_NOATIME: ::c_int = 0o1000000; -pub const O_CLOEXEC: ::c_int = 0x80000; - -pub const EBFONT: ::c_int = 59; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENONET: ::c_int = 64; -pub const ENOPKG: ::c_int = 65; -pub const EREMOTE: ::c_int = 66; -pub const ENOLINK: ::c_int = 67; -pub const EADV: ::c_int = 68; -pub const ESRMNT: ::c_int = 69; -pub const ECOMM: ::c_int = 70; -pub const EPROTO: ::c_int = 71; -pub const EDOTDOT: ::c_int = 73; - -pub const SA_NODEFER: ::c_int = 0x40000000; -pub const SA_RESETHAND: ::c_int = 0x80000000; -pub const SA_RESTART: ::c_int = 0x10000000; -pub const SA_NOCLDSTOP: ::c_int = 0x00000001; - -pub const EPOLL_CLOEXEC: ::c_int = 0x80000; - -pub const EFD_CLOEXEC: ::c_int = 0x80000; - -pub const BUFSIZ: ::c_uint = 1024; -pub const TMP_MAX: ::c_uint = 10000; -pub const FOPEN_MAX: ::c_uint = 1000; -pub const O_PATH: ::c_int = 0o10000000; -pub const O_EXEC: ::c_int = 0o10000000; -pub const O_SEARCH: ::c_int = 0o10000000; -pub const O_ACCMODE: ::c_int = 0o10000003; -pub const O_NDELAY: ::c_int = O_NONBLOCK; -pub const NI_MAXHOST: ::socklen_t = 255; -pub const PTHREAD_STACK_MIN: ::size_t = 2048; -pub const POSIX_FADV_DONTNEED: ::c_int = 4; -pub const POSIX_FADV_NOREUSE: ::c_int = 5; - -pub const POSIX_MADV_DONTNEED: ::c_int = 0; - -pub const RLIM_INFINITY: ::rlim_t = !0; -pub const RLIMIT_RTTIME: ::c_int = 15; -pub const RLIMIT_NLIMITS: ::c_int = 16; - -pub const MAP_ANONYMOUS: ::c_int = MAP_ANON; - -pub const TCP_COOKIE_TRANSACTIONS: ::c_int = 15; -pub const TCP_THIN_LINEAR_TIMEOUTS: ::c_int = 16; -pub const TCP_THIN_DUPACK: ::c_int = 17; -pub const TCP_USER_TIMEOUT: ::c_int = 18; -pub const TCP_REPAIR: ::c_int = 19; -pub const TCP_REPAIR_QUEUE: ::c_int = 20; -pub const TCP_QUEUE_SEQ: ::c_int = 21; -pub const TCP_REPAIR_OPTIONS: ::c_int = 22; -pub const TCP_FASTOPEN: ::c_int = 23; -pub const TCP_TIMESTAMP: ::c_int = 24; - -pub const SIGUNUSED: ::c_int = ::SIGSYS; - -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; - -pub const CPU_SETSIZE: ::c_int = 128; - -pub const QFMT_VFS_V1: ::c_int = 4; - -pub const PTRACE_TRACEME: ::c_int = 0; -pub const PTRACE_PEEKTEXT: ::c_int = 1; -pub const PTRACE_PEEKDATA: ::c_int = 2; -pub const PTRACE_PEEKUSER: ::c_int = 3; -pub const PTRACE_POKETEXT: ::c_int = 4; -pub const PTRACE_POKEDATA: ::c_int = 5; -pub const PTRACE_POKEUSER: ::c_int = 6; -pub const PTRACE_CONT: ::c_int = 7; -pub const PTRACE_KILL: ::c_int = 8; -pub const PTRACE_SINGLESTEP: ::c_int = 9; -pub const PTRACE_ATTACH: ::c_int = 16; -pub const PTRACE_DETACH: ::c_int = 17; -pub const PTRACE_SYSCALL: ::c_int = 24; -pub const PTRACE_SETOPTIONS: ::c_int = 0x4200; -pub const PTRACE_GETEVENTMSG: ::c_int = 0x4201; -pub const PTRACE_GETSIGINFO: ::c_int = 0x4202; -pub const PTRACE_SETSIGINFO: ::c_int = 0x4203; -pub const PTRACE_GETREGSET: ::c_int = 0x4204; -pub const PTRACE_SETREGSET: ::c_int = 0x4205; -pub const PTRACE_SEIZE: ::c_int = 0x4206; -pub const PTRACE_INTERRUPT: ::c_int = 0x4207; -pub const PTRACE_LISTEN: ::c_int = 0x4208; -pub const PTRACE_PEEKSIGINFO: ::c_int = 0x4209; - -pub const EPOLLWAKEUP: ::c_int = 0x20000000; - -pub const PTRACE_GETFPREGS: ::c_uint = 14; -pub const PTRACE_SETFPREGS: ::c_uint = 15; -pub const PTRACE_GETFPXREGS: ::c_uint = 18; -pub const PTRACE_SETFPXREGS: ::c_uint = 19; -pub const PTRACE_GETREGS: ::c_uint = 12; -pub const PTRACE_SETREGS: ::c_uint = 13; - -pub const EFD_NONBLOCK: ::c_int = ::O_NONBLOCK; - -pub const SFD_NONBLOCK: ::c_int = ::O_NONBLOCK; - -pub const TCSANOW: ::c_int = 0; -pub const TCSADRAIN: ::c_int = 1; -pub const TCSAFLUSH: ::c_int = 2; - -pub const TIOCINQ: ::c_int = ::FIONREAD; - -pub const RTLD_GLOBAL: ::c_int = 0x100; -pub const RTLD_NOLOAD: ::c_int = 0x4; - -// TODO(#247) Temporarily musl-specific (available since musl 0.9.12 / Linux -// kernel 3.10). See also notbsd/mod.rs -pub const CLOCK_SGI_CYCLE: ::clockid_t = 10; -pub const CLOCK_TAI: ::clockid_t = 11; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const SIGSTKSZ: ::size_t = 8192; -pub const MINSIGSTKSZ: ::size_t = 2048; -pub const CBAUD: ::tcflag_t = 0o0010017; -pub const TAB1: ::c_int = 0x00000800; -pub const TAB2: ::c_int = 0x00001000; -pub const TAB3: ::c_int = 0x00001800; -pub const CR1: ::c_int = 0x00000200; -pub const CR2: ::c_int = 0x00000400; -pub const CR3: ::c_int = 0x00000600; -pub const FF1: ::c_int = 0x00008000; -pub const BS1: ::c_int = 0x00002000; -pub const VT1: ::c_int = 0x00004000; -pub const VWERASE: usize = 14; -pub const VREPRINT: usize = 12; -pub const VSUSP: usize = 10; -pub const VSTART: usize = 8; -pub const VSTOP: usize = 9; -pub const VDISCARD: usize = 13; -pub const VTIME: usize = 5; -pub const IXON: ::tcflag_t = 0x00000400; -pub const IXOFF: ::tcflag_t = 0x00001000; -pub const ONLCR: ::tcflag_t = 0x4; -pub const CSIZE: ::tcflag_t = 0x00000030; -pub const CS6: ::tcflag_t = 0x00000010; -pub const CS7: ::tcflag_t = 0x00000020; -pub const CS8: ::tcflag_t = 0x00000030; -pub const CSTOPB: ::tcflag_t = 0x00000040; -pub const CREAD: ::tcflag_t = 0x00000080; -pub const PARENB: ::tcflag_t = 0x00000100; -pub const PARODD: ::tcflag_t = 0x00000200; -pub const HUPCL: ::tcflag_t = 0x00000400; -pub const CLOCAL: ::tcflag_t = 0x00000800; -pub const ECHOKE: ::tcflag_t = 0x00000800; -pub const ECHOE: ::tcflag_t = 0x00000010; -pub const ECHOK: ::tcflag_t = 0x00000020; -pub const ECHONL: ::tcflag_t = 0x00000040; -pub const ECHOPRT: ::tcflag_t = 0x00000400; -pub const ECHOCTL: ::tcflag_t = 0x00000200; -pub const ISIG: ::tcflag_t = 0x00000001; -pub const ICANON: ::tcflag_t = 0x00000002; -pub const PENDIN: ::tcflag_t = 0x00004000; -pub const NOFLSH: ::tcflag_t = 0x00000080; -pub const CBAUDEX: ::tcflag_t = 0o010000; -pub const VSWTC: usize = 7; -pub const OLCUC: ::tcflag_t = 0o000002; -pub const NLDLY: ::tcflag_t = 0o000400; -pub const CRDLY: ::tcflag_t = 0o003000; -pub const TABDLY: ::tcflag_t = 0o014000; -pub const BSDLY: ::tcflag_t = 0o020000; -pub const FFDLY: ::tcflag_t = 0o100000; -pub const VTDLY: ::tcflag_t = 0o040000; -pub const XTABS: ::tcflag_t = 0o014000; - -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const B57600: ::speed_t = 0o010001; -pub const B115200: ::speed_t = 0o010002; -pub const B230400: ::speed_t = 0o010003; -pub const B460800: ::speed_t = 0o010004; -pub const B500000: ::speed_t = 0o010005; -pub const B576000: ::speed_t = 0o010006; -pub const B921600: ::speed_t = 0o010007; -pub const B1000000: ::speed_t = 0o010010; -pub const B1152000: ::speed_t = 0o010011; -pub const B1500000: ::speed_t = 0o010012; -pub const B2000000: ::speed_t = 0o010013; -pub const B2500000: ::speed_t = 0o010014; -pub const B3000000: ::speed_t = 0o010015; -pub const B3500000: ::speed_t = 0o010016; -pub const B4000000: ::speed_t = 0o010017; - -pub const SO_BINDTODEVICE: ::c_int = 25; -pub const SO_TIMESTAMP: ::c_int = 29; -pub const SO_MARK: ::c_int = 36; -pub const SO_RXQ_OVFL: ::c_int = 40; -pub const SO_PEEK_OFF: ::c_int = 42; -pub const SO_BUSY_POLL: ::c_int = 46; - -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 32; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 28; - -pub const O_DIRECT: ::c_int = 0x4000; -pub const O_DIRECTORY: ::c_int = 0x10000; -pub const O_NOFOLLOW: ::c_int = 0x20000; -pub const O_ASYNC: ::c_int = 0x2000; - -pub const FIOCLEX: ::c_int = 0x5451; -pub const FIONBIO: ::c_int = 0x5421; - -pub const RLIMIT_RSS: ::c_int = 5; -pub const RLIMIT_NOFILE: ::c_int = 7; -pub const RLIMIT_AS: ::c_int = 9; -pub const RLIMIT_NPROC: ::c_int = 6; -pub const RLIMIT_MEMLOCK: ::c_int = 8; - -pub const O_APPEND: ::c_int = 1024; -pub const O_CREAT: ::c_int = 64; -pub const O_EXCL: ::c_int = 128; -pub const O_NOCTTY: ::c_int = 256; -pub const O_NONBLOCK: ::c_int = 2048; -pub const O_SYNC: ::c_int = 1052672; -pub const O_RSYNC: ::c_int = 1052672; -pub const O_DSYNC: ::c_int = 4096; - -pub const SOCK_NONBLOCK: ::c_int = 2048; - -pub const MAP_ANON: ::c_int = 0x0020; -pub const MAP_GROWSDOWN: ::c_int = 0x0100; -pub const MAP_DENYWRITE: ::c_int = 0x0800; -pub const MAP_EXECUTABLE: ::c_int = 0x01000; -pub const MAP_LOCKED: ::c_int = 0x02000; -pub const MAP_NORESERVE: ::c_int = 0x04000; -pub const MAP_POPULATE: ::c_int = 0x08000; -pub const MAP_NONBLOCK: ::c_int = 0x010000; -pub const MAP_STACK: ::c_int = 0x020000; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; -pub const SOCK_SEQPACKET: ::c_int = 5; - -pub const SOL_SOCKET: ::c_int = 1; - -pub const EDEADLK: ::c_int = 35; -pub const ENAMETOOLONG: ::c_int = 36; -pub const ENOLCK: ::c_int = 37; -pub const ENOSYS: ::c_int = 38; -pub const ENOTEMPTY: ::c_int = 39; -pub const ELOOP: ::c_int = 40; -pub const ENOMSG: ::c_int = 42; -pub const EIDRM: ::c_int = 43; -pub const ECHRNG: ::c_int = 44; -pub const EL2NSYNC: ::c_int = 45; -pub const EL3HLT: ::c_int = 46; -pub const EL3RST: ::c_int = 47; -pub const ELNRNG: ::c_int = 48; -pub const EUNATCH: ::c_int = 49; -pub const ENOCSI: ::c_int = 50; -pub const EL2HLT: ::c_int = 51; -pub const EBADE: ::c_int = 52; -pub const EBADR: ::c_int = 53; -pub const EXFULL: ::c_int = 54; -pub const ENOANO: ::c_int = 55; -pub const EBADRQC: ::c_int = 56; -pub const EBADSLT: ::c_int = 57; -pub const EDEADLOCK: ::c_int = EDEADLK; -pub const EMULTIHOP: ::c_int = 72; -pub const EBADMSG: ::c_int = 74; -pub const EOVERFLOW: ::c_int = 75; -pub const ENOTUNIQ: ::c_int = 76; -pub const EBADFD: ::c_int = 77; -pub const EREMCHG: ::c_int = 78; -pub const ELIBACC: ::c_int = 79; -pub const ELIBBAD: ::c_int = 80; -pub const ELIBSCN: ::c_int = 81; -pub const ELIBMAX: ::c_int = 82; -pub const ELIBEXEC: ::c_int = 83; -pub const EILSEQ: ::c_int = 84; -pub const ERESTART: ::c_int = 85; -pub const ESTRPIPE: ::c_int = 86; -pub const EUSERS: ::c_int = 87; -pub const ENOTSOCK: ::c_int = 88; -pub const EDESTADDRREQ: ::c_int = 89; -pub const EMSGSIZE: ::c_int = 90; -pub const EPROTOTYPE: ::c_int = 91; -pub const ENOPROTOOPT: ::c_int = 92; -pub const EPROTONOSUPPORT: ::c_int = 93; -pub const ESOCKTNOSUPPORT: ::c_int = 94; -pub const EOPNOTSUPP: ::c_int = 95; -pub const ENOTSUP: ::c_int = EOPNOTSUPP; -pub const EPFNOSUPPORT: ::c_int = 96; -pub const EAFNOSUPPORT: ::c_int = 97; -pub const EADDRINUSE: ::c_int = 98; -pub const EADDRNOTAVAIL: ::c_int = 99; -pub const ENETDOWN: ::c_int = 100; -pub const ENETUNREACH: ::c_int = 101; -pub const ENETRESET: ::c_int = 102; -pub const ECONNABORTED: ::c_int = 103; -pub const ECONNRESET: ::c_int = 104; -pub const ENOBUFS: ::c_int = 105; -pub const EISCONN: ::c_int = 106; -pub const ENOTCONN: ::c_int = 107; -pub const ESHUTDOWN: ::c_int = 108; -pub const ETOOMANYREFS: ::c_int = 109; -pub const ETIMEDOUT: ::c_int = 110; -pub const ECONNREFUSED: ::c_int = 111; -pub const EHOSTDOWN: ::c_int = 112; -pub const EHOSTUNREACH: ::c_int = 113; -pub const EALREADY: ::c_int = 114; -pub const EINPROGRESS: ::c_int = 115; -pub const ESTALE: ::c_int = 116; -pub const EUCLEAN: ::c_int = 117; -pub const ENOTNAM: ::c_int = 118; -pub const ENAVAIL: ::c_int = 119; -pub const EISNAM: ::c_int = 120; -pub const EREMOTEIO: ::c_int = 121; -pub const EDQUOT: ::c_int = 122; -pub const ENOMEDIUM: ::c_int = 123; -pub const EMEDIUMTYPE: ::c_int = 124; -pub const ECANCELED: ::c_int = 125; -pub const ENOKEY: ::c_int = 126; -pub const EKEYEXPIRED: ::c_int = 127; -pub const EKEYREVOKED: ::c_int = 128; -pub const EKEYREJECTED: ::c_int = 129; -pub const EOWNERDEAD: ::c_int = 130; -pub const ENOTRECOVERABLE: ::c_int = 131; -pub const ERFKILL: ::c_int = 132; -pub const EHWPOISON: ::c_int = 133; - -pub const SO_REUSEADDR: ::c_int = 2; -pub const SO_TYPE: ::c_int = 3; -pub const SO_ERROR: ::c_int = 4; -pub const SO_DONTROUTE: ::c_int = 5; -pub const SO_BROADCAST: ::c_int = 6; -pub const SO_SNDBUF: ::c_int = 7; -pub const SO_RCVBUF: ::c_int = 8; -pub const SO_KEEPALIVE: ::c_int = 9; -pub const SO_OOBINLINE: ::c_int = 10; -pub const SO_LINGER: ::c_int = 13; -pub const SO_REUSEPORT: ::c_int = 15; -pub const SO_RCVLOWAT: ::c_int = 18; -pub const SO_SNDLOWAT: ::c_int = 19; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_SNDTIMEO: ::c_int = 21; -pub const SO_ACCEPTCONN: ::c_int = 30; - -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 0x00000004; -pub const SA_NOCLDWAIT: ::c_int = 0x00000002; - -pub const SIGCHLD: ::c_int = 17; -pub const SIGBUS: ::c_int = 7; -pub const SIGTTIN: ::c_int = 21; -pub const SIGTTOU: ::c_int = 22; -pub const SIGXCPU: ::c_int = 24; -pub const SIGXFSZ: ::c_int = 25; -pub const SIGVTALRM: ::c_int = 26; -pub const SIGPROF: ::c_int = 27; -pub const SIGWINCH: ::c_int = 28; -pub const SIGUSR1: ::c_int = 10; -pub const SIGUSR2: ::c_int = 12; -pub const SIGCONT: ::c_int = 18; -pub const SIGSTOP: ::c_int = 19; -pub const SIGTSTP: ::c_int = 20; -pub const SIGURG: ::c_int = 23; -pub const SIGIO: ::c_int = 29; -pub const SIGSYS: ::c_int = 31; -pub const SIGSTKFLT: ::c_int = 16; -pub const SIGPOLL: ::c_int = 29; -pub const SIGPWR: ::c_int = 30; -pub const SIG_SETMASK: ::c_int = 2; -pub const SIG_BLOCK: ::c_int = 0x000000; -pub const SIG_UNBLOCK: ::c_int = 0x01; - -pub const EXTPROC: ::tcflag_t = 0x00010000; - -pub const MAP_HUGETLB: ::c_int = 0x040000; - -pub const F_GETLK: ::c_int = 12; -pub const F_GETOWN: ::c_int = 9; -pub const F_SETLK: ::c_int = 13; -pub const F_SETLKW: ::c_int = 14; -pub const F_SETOWN: ::c_int = 8; - -pub const VEOF: usize = 4; -pub const VEOL: usize = 11; -pub const VEOL2: usize = 16; -pub const VMIN: usize = 6; -pub const IEXTEN: ::tcflag_t = 0x00008000; -pub const TOSTOP: ::tcflag_t = 0x00000100; -pub const FLUSHO: ::tcflag_t = 0x00001000; - -pub const TCGETS: ::c_int = 0x5401; -pub const TCSETS: ::c_int = 0x5402; -pub const TCSETSW: ::c_int = 0x5403; -pub const TCSETSF: ::c_int = 0x5404; -pub const TCGETA: ::c_int = 0x5405; -pub const TCSETA: ::c_int = 0x5406; -pub const TCSETAW: ::c_int = 0x5407; -pub const TCSETAF: ::c_int = 0x5408; -pub const TCSBRK: ::c_int = 0x5409; -pub const TCXONC: ::c_int = 0x540A; -pub const TCFLSH: ::c_int = 0x540B; -pub const TIOCGSOFTCAR: ::c_int = 0x5419; -pub const TIOCSSOFTCAR: ::c_int = 0x541A; -pub const TIOCLINUX: ::c_int = 0x541C; -pub const TIOCGSERIAL: ::c_int = 0x541E; -pub const TIOCEXCL: ::c_int = 0x540C; -pub const TIOCNXCL: ::c_int = 0x540D; -pub const TIOCSCTTY: ::c_int = 0x540E; -pub const TIOCGPGRP: ::c_int = 0x540F; -pub const TIOCSPGRP: ::c_int = 0x5410; -pub const TIOCOUTQ: ::c_int = 0x5411; -pub const TIOCSTI: ::c_int = 0x5412; -pub const TIOCGWINSZ: ::c_int = 0x5413; -pub const TIOCSWINSZ: ::c_int = 0x5414; -pub const TIOCMGET: ::c_int = 0x5415; -pub const TIOCMBIS: ::c_int = 0x5416; -pub const TIOCMBIC: ::c_int = 0x5417; -pub const TIOCMSET: ::c_int = 0x5418; -pub const FIONREAD: ::c_int = 0x541B; -pub const TIOCCONS: ::c_int = 0x541D; - -pub const SYS_gettid: ::c_long = 224; // Valid for arm (32-bit) and x86 (32-bit) - -pub const POLLWRNORM: ::c_short = 0x100; -pub const POLLWRBAND: ::c_short = 0x200; - -pub const TIOCM_LE: ::c_int = 0x001; -pub const TIOCM_DTR: ::c_int = 0x002; -pub const TIOCM_RTS: ::c_int = 0x004; -pub const TIOCM_ST: ::c_int = 0x008; -pub const TIOCM_SR: ::c_int = 0x010; -pub const TIOCM_CTS: ::c_int = 0x020; -pub const TIOCM_CAR: ::c_int = 0x040; -pub const TIOCM_RNG: ::c_int = 0x080; -pub const TIOCM_DSR: ::c_int = 0x100; -pub const TIOCM_CD: ::c_int = TIOCM_CAR; -pub const TIOCM_RI: ::c_int = TIOCM_RNG; -pub const O_TMPFILE: ::c_int = 0x400000; - -f! { - pub fn CPU_ZERO(cpuset: &mut cpu_set_t) -> () { - for slot in cpuset.bits.iter_mut() { - *slot = 0; - } - } - - pub fn CPU_SET(cpu: usize, cpuset: &mut cpu_set_t) -> () { - let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc - let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); - cpuset.bits[idx] |= 1 << offset; - () - } - - pub fn CPU_CLR(cpu: usize, cpuset: &mut cpu_set_t) -> () { - let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc - let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); - cpuset.bits[idx] &= !(1 << offset); - () - } - - pub fn CPU_ISSET(cpu: usize, cpuset: &cpu_set_t) -> bool { - let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); - let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); - 0 != (cpuset.bits[idx] & (1 << offset)) - } - - pub fn CPU_EQUAL(set1: &cpu_set_t, set2: &cpu_set_t) -> bool { - set1.bits == set2.bits - } - - pub fn major(dev: ::dev_t) -> ::c_uint { - // see - // https://github.com/kripken/emscripten/blob/ - // master/system/include/libc/sys/sysmacros.h - let mut major = 0; - major |= (dev & 0x00000fff) >> 8; - major |= (dev & 0xfffff000) >> 31 >> 1; - major as ::c_uint - } - - pub fn minor(dev: ::dev_t) -> ::c_uint { - // see - // https://github.com/kripken/emscripten/blob/ - // master/system/include/libc/sys/sysmacros.h - let mut minor = 0; - minor |= (dev & 0x000000ff) >> 0; - minor |= (dev & 0xffffff00) >> 12; - minor as ::c_uint - } - - pub fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { - let major = major as ::dev_t; - let minor = minor as ::dev_t; - let mut dev = 0; - dev |= (major & 0x00000fff) << 8; - dev |= (major & 0xfffff000) << 31 << 1; - dev |= (minor & 0x000000ff) << 0; - dev |= (minor & 0xffffff00) << 12; - dev - } -} - -extern { - pub fn setpwent(); - pub fn endpwent(); - pub fn getpwent() -> *mut passwd; - - pub fn shm_open(name: *const c_char, oflag: ::c_int, - mode: mode_t) -> ::c_int; - - pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) - -> ::c_int; - pub fn __errno_location() -> *mut ::c_int; - - pub fn fopen64(filename: *const c_char, - mode: *const c_char) -> *mut ::FILE; - pub fn freopen64(filename: *const c_char, mode: *const c_char, - file: *mut ::FILE) -> *mut ::FILE; - pub fn tmpfile64() -> *mut ::FILE; - pub fn fgetpos64(stream: *mut ::FILE, ptr: *mut fpos64_t) -> ::c_int; - pub fn fsetpos64(stream: *mut ::FILE, ptr: *const fpos64_t) -> ::c_int; - pub fn fseeko64(stream: *mut ::FILE, - offset: ::off64_t, - whence: ::c_int) -> ::c_int; - pub fn ftello64(stream: *mut ::FILE) -> ::off64_t; - pub fn posix_fallocate(fd: ::c_int, offset: ::off_t, - len: ::off_t) -> ::c_int; - pub fn pwritev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off_t) -> ::ssize_t; - pub fn preadv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off_t) -> ::ssize_t; - pub fn dup3(oldfd: ::c_int, newfd: ::c_int, flags: ::c_int) -> ::c_int; - pub fn mkostemp(template: *mut ::c_char, flags: ::c_int) -> ::c_int; - pub fn mkostemps(template: *mut ::c_char, - suffixlen: ::c_int, - flags: ::c_int) -> ::c_int; - pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; - pub fn getnameinfo(sa: *const ::sockaddr, - salen: ::socklen_t, - host: *mut ::c_char, - hostlen: ::socklen_t, - serv: *mut ::c_char, - sevlen: ::socklen_t, - flags: ::c_int) -> ::c_int; - pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int; - - // Not available now on Android - pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t) -> ::c_int; - pub fn if_nameindex() -> *mut if_nameindex; - pub fn if_freenameindex(ptr: *mut if_nameindex); - pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; - pub fn freeifaddrs(ifa: *mut ::ifaddrs); - - pub fn mremap(addr: *mut ::c_void, - len: ::size_t, - new_len: ::size_t, - flags: ::c_int, - ...) -> *mut ::c_void; - - pub fn glob(pattern: *const c_char, - flags: ::c_int, - errfunc: Option ::c_int>, - pglob: *mut ::glob_t) -> ::c_int; - pub fn globfree(pglob: *mut ::glob_t); - - pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - pub fn shm_unlink(name: *const ::c_char) -> ::c_int; - - pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); - - pub fn telldir(dirp: *mut ::DIR) -> ::c_long; - pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; - - pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, - flags: ::c_int, addr: *mut ::sockaddr, - addrlen: *mut ::socklen_t) -> ::ssize_t; - pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; - pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; - - pub fn bind(socket: ::c_int, address: *const ::sockaddr, - address_len: ::socklen_t) -> ::c_int; - - pub fn writev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - pub fn readv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - - pub fn sendmsg(fd: ::c_int, - msg: *const ::msghdr, - flags: ::c_int) -> ::ssize_t; - pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) - -> ::ssize_t; - pub fn getdomainname(name: *mut ::c_char, len: ::size_t) -> ::c_int; - pub fn setdomainname(name: *const ::c_char, len: ::size_t) -> ::c_int; - pub fn sendmmsg(sockfd: ::c_int, msgvec: *mut mmsghdr, vlen: ::c_uint, - flags: ::c_int) -> ::c_int; - pub fn recvmmsg(sockfd: ::c_int, msgvec: *mut mmsghdr, vlen: ::c_uint, - flags: ::c_int, timeout: *mut ::timespec) -> ::c_int; - pub fn sync(); - pub fn ioctl(fd: ::c_int, request: ::c_int, ...) -> ::c_int; - pub fn getpriority(which: ::c_int, who: ::id_t) -> ::c_int; - pub fn setpriority(which: ::c_int, who: ::id_t, prio: ::c_int) -> ::c_int; - pub fn pthread_create(native: *mut ::pthread_t, - attr: *const ::pthread_attr_t, - f: extern fn(*mut ::c_void) -> *mut ::c_void, - value: *mut ::c_void) -> ::c_int; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mips/mips32.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mips/mips32.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mips/mips32.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mips/mips32.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,637 +0,0 @@ -pub type c_char = i8; -pub type c_long = i32; -pub type c_ulong = u32; -pub type clock_t = i32; -pub type time_t = i32; -pub type suseconds_t = i32; -pub type wchar_t = i32; -pub type off_t = i32; -pub type ino_t = u32; -pub type blkcnt_t = i32; -pub type blksize_t = i32; -pub type nlink_t = u32; -pub type __u64 = ::c_ulonglong; - -s! { - pub struct aiocb { - pub aio_fildes: ::c_int, - pub aio_lio_opcode: ::c_int, - pub aio_reqprio: ::c_int, - pub aio_buf: *mut ::c_void, - pub aio_nbytes: ::size_t, - pub aio_sigevent: ::sigevent, - __next_prio: *mut aiocb, - __abs_prio: ::c_int, - __policy: ::c_int, - __error_code: ::c_int, - __return_value: ::ssize_t, - pub aio_offset: off_t, - __unused1: [::c_char; 4], - __glibc_reserved: [::c_char; 32] - } - - pub struct stat { - pub st_dev: ::c_ulong, - st_pad1: [::c_long; 3], - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::c_ulong, - pub st_pad2: [::c_long; 2], - pub st_size: ::off_t, - st_pad3: ::c_long, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - st_pad5: [::c_long; 14], - } - - pub struct stat64 { - pub st_dev: ::c_ulong, - st_pad1: [::c_long; 3], - pub st_ino: ::ino64_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::c_ulong, - st_pad2: [::c_long; 2], - pub st_size: ::off64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - st_pad3: ::c_long, - pub st_blocks: ::blkcnt64_t, - st_pad5: [::c_long; 14], - } - - pub struct statfs64 { - pub f_type: ::c_long, - pub f_bsize: ::c_long, - pub f_frsize: ::c_long, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_bavail: u64, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_long, - pub f_flags: ::c_long, - pub f_spare: [::c_long; 5], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - #[cfg(target_endian = "little")] - pub f_fsid: ::c_ulong, - __f_unused: ::c_int, - #[cfg(target_endian = "big")] - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct pthread_attr_t { - __size: [u32; 9] - } - - pub struct sigaction { - pub sa_flags: ::c_int, - pub sa_sigaction: ::sighandler_t, - pub sa_mask: sigset_t, - pub sa_restorer: ::dox::Option, - _resv: [::c_int; 1], - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_size: ::size_t, - pub ss_flags: ::c_int, - } - - pub struct sigset_t { - __val: [::c_ulong; 32], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_code: ::c_int, - pub si_errno: ::c_int, - pub _pad: [::c_int; 29], - } - - pub struct ipc_perm { - pub __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::c_uint, - pub __seq: ::c_ushort, - __pad1: ::c_ushort, - __unused1: ::c_ulong, - __unused2: ::c_ulong - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __unused4: ::c_ulong, - __unused5: ::c_ulong - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - #[cfg(target_endian = "big")] - __glibc_reserved1: ::c_ulong, - pub msg_stime: ::time_t, - #[cfg(target_endian = "little")] - __glibc_reserved1: ::c_ulong, - #[cfg(target_endian = "big")] - __glibc_reserved2: ::c_ulong, - pub msg_rtime: ::time_t, - #[cfg(target_endian = "little")] - __glibc_reserved2: ::c_ulong, - #[cfg(target_endian = "big")] - __glibc_reserved3: ::c_ulong, - pub msg_ctime: ::time_t, - #[cfg(target_endian = "little")] - __glibc_reserved3: ::c_ulong, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __glibc_reserved4: ::c_ulong, - __glibc_reserved5: ::c_ulong, - } - - pub struct statfs { - pub f_type: ::c_long, - pub f_bsize: ::c_long, - pub f_frsize: ::c_long, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_files: ::fsblkcnt_t, - pub f_ffree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_fsid: ::fsid_t, - - pub f_namelen: ::c_long, - f_spare: [::c_long; 6], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::size_t, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::size_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::size_t, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; ::NCCS], - } - - pub struct flock { - pub l_type: ::c_short, - pub l_whence: ::c_short, - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_sysid: ::c_long, - pub l_pid: ::pid_t, - pad: [::c_long; 4], - } - - pub struct sysinfo { - pub uptime: ::c_long, - pub loads: [::c_ulong; 3], - pub totalram: ::c_ulong, - pub freeram: ::c_ulong, - pub sharedram: ::c_ulong, - pub bufferram: ::c_ulong, - pub totalswap: ::c_ulong, - pub freeswap: ::c_ulong, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: ::c_ulong, - pub freehigh: ::c_ulong, - pub mem_unit: ::c_uint, - pub _f: [::c_char; 8], - } -} - -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 24; -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 32; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; - -pub const O_LARGEFILE: ::c_int = 0x2000; - -pub const RLIM_INFINITY: ::rlim_t = 0x7fffffff; - -pub const SYS_syscall: ::c_long = 4000 + 0; -pub const SYS_exit: ::c_long = 4000 + 1; -pub const SYS_fork: ::c_long = 4000 + 2; -pub const SYS_read: ::c_long = 4000 + 3; -pub const SYS_write: ::c_long = 4000 + 4; -pub const SYS_open: ::c_long = 4000 + 5; -pub const SYS_close: ::c_long = 4000 + 6; -pub const SYS_waitpid: ::c_long = 4000 + 7; -pub const SYS_creat: ::c_long = 4000 + 8; -pub const SYS_link: ::c_long = 4000 + 9; -pub const SYS_unlink: ::c_long = 4000 + 10; -pub const SYS_execve: ::c_long = 4000 + 11; -pub const SYS_chdir: ::c_long = 4000 + 12; -pub const SYS_time: ::c_long = 4000 + 13; -pub const SYS_mknod: ::c_long = 4000 + 14; -pub const SYS_chmod: ::c_long = 4000 + 15; -pub const SYS_lchown: ::c_long = 4000 + 16; -pub const SYS_break: ::c_long = 4000 + 17; -pub const SYS_unused18: ::c_long = 4000 + 18; -pub const SYS_lseek: ::c_long = 4000 + 19; -pub const SYS_getpid: ::c_long = 4000 + 20; -pub const SYS_mount: ::c_long = 4000 + 21; -pub const SYS_umount: ::c_long = 4000 + 22; -pub const SYS_setuid: ::c_long = 4000 + 23; -pub const SYS_getuid: ::c_long = 4000 + 24; -pub const SYS_stime: ::c_long = 4000 + 25; -pub const SYS_ptrace: ::c_long = 4000 + 26; -pub const SYS_alarm: ::c_long = 4000 + 27; -pub const SYS_unused28: ::c_long = 4000 + 28; -pub const SYS_pause: ::c_long = 4000 + 29; -pub const SYS_utime: ::c_long = 4000 + 30; -pub const SYS_stty: ::c_long = 4000 + 31; -pub const SYS_gtty: ::c_long = 4000 + 32; -pub const SYS_access: ::c_long = 4000 + 33; -pub const SYS_nice: ::c_long = 4000 + 34; -pub const SYS_ftime: ::c_long = 4000 + 35; -pub const SYS_sync: ::c_long = 4000 + 36; -pub const SYS_kill: ::c_long = 4000 + 37; -pub const SYS_rename: ::c_long = 4000 + 38; -pub const SYS_mkdir: ::c_long = 4000 + 39; -pub const SYS_rmdir: ::c_long = 4000 + 40; -pub const SYS_dup: ::c_long = 4000 + 41; -pub const SYS_pipe: ::c_long = 4000 + 42; -pub const SYS_times: ::c_long = 4000 + 43; -pub const SYS_prof: ::c_long = 4000 + 44; -pub const SYS_brk: ::c_long = 4000 + 45; -pub const SYS_setgid: ::c_long = 4000 + 46; -pub const SYS_getgid: ::c_long = 4000 + 47; -pub const SYS_signal: ::c_long = 4000 + 48; -pub const SYS_geteuid: ::c_long = 4000 + 49; -pub const SYS_getegid: ::c_long = 4000 + 50; -pub const SYS_acct: ::c_long = 4000 + 51; -pub const SYS_umount2: ::c_long = 4000 + 52; -pub const SYS_lock: ::c_long = 4000 + 53; -pub const SYS_ioctl: ::c_long = 4000 + 54; -pub const SYS_fcntl: ::c_long = 4000 + 55; -pub const SYS_mpx: ::c_long = 4000 + 56; -pub const SYS_setpgid: ::c_long = 4000 + 57; -pub const SYS_ulimit: ::c_long = 4000 + 58; -pub const SYS_unused59: ::c_long = 4000 + 59; -pub const SYS_umask: ::c_long = 4000 + 60; -pub const SYS_chroot: ::c_long = 4000 + 61; -pub const SYS_ustat: ::c_long = 4000 + 62; -pub const SYS_dup2: ::c_long = 4000 + 63; -pub const SYS_getppid: ::c_long = 4000 + 64; -pub const SYS_getpgrp: ::c_long = 4000 + 65; -pub const SYS_setsid: ::c_long = 4000 + 66; -pub const SYS_sigaction: ::c_long = 4000 + 67; -pub const SYS_sgetmask: ::c_long = 4000 + 68; -pub const SYS_ssetmask: ::c_long = 4000 + 69; -pub const SYS_setreuid: ::c_long = 4000 + 70; -pub const SYS_setregid: ::c_long = 4000 + 71; -pub const SYS_sigsuspend: ::c_long = 4000 + 72; -pub const SYS_sigpending: ::c_long = 4000 + 73; -pub const SYS_sethostname: ::c_long = 4000 + 74; -pub const SYS_setrlimit: ::c_long = 4000 + 75; -pub const SYS_getrlimit: ::c_long = 4000 + 76; -pub const SYS_getrusage: ::c_long = 4000 + 77; -pub const SYS_gettimeofday: ::c_long = 4000 + 78; -pub const SYS_settimeofday: ::c_long = 4000 + 79; -pub const SYS_getgroups: ::c_long = 4000 + 80; -pub const SYS_setgroups: ::c_long = 4000 + 81; -pub const SYS_reserved82: ::c_long = 4000 + 82; -pub const SYS_symlink: ::c_long = 4000 + 83; -pub const SYS_unused84: ::c_long = 4000 + 84; -pub const SYS_readlink: ::c_long = 4000 + 85; -pub const SYS_uselib: ::c_long = 4000 + 86; -pub const SYS_swapon: ::c_long = 4000 + 87; -pub const SYS_reboot: ::c_long = 4000 + 88; -pub const SYS_readdir: ::c_long = 4000 + 89; -pub const SYS_mmap: ::c_long = 4000 + 90; -pub const SYS_munmap: ::c_long = 4000 + 91; -pub const SYS_truncate: ::c_long = 4000 + 92; -pub const SYS_ftruncate: ::c_long = 4000 + 93; -pub const SYS_fchmod: ::c_long = 4000 + 94; -pub const SYS_fchown: ::c_long = 4000 + 95; -pub const SYS_getpriority: ::c_long = 4000 + 96; -pub const SYS_setpriority: ::c_long = 4000 + 97; -pub const SYS_profil: ::c_long = 4000 + 98; -pub const SYS_statfs: ::c_long = 4000 + 99; -pub const SYS_fstatfs: ::c_long = 4000 + 100; -pub const SYS_ioperm: ::c_long = 4000 + 101; -pub const SYS_socketcall: ::c_long = 4000 + 102; -pub const SYS_syslog: ::c_long = 4000 + 103; -pub const SYS_setitimer: ::c_long = 4000 + 104; -pub const SYS_getitimer: ::c_long = 4000 + 105; -pub const SYS_stat: ::c_long = 4000 + 106; -pub const SYS_lstat: ::c_long = 4000 + 107; -pub const SYS_fstat: ::c_long = 4000 + 108; -pub const SYS_unused109: ::c_long = 4000 + 109; -pub const SYS_iopl: ::c_long = 4000 + 110; -pub const SYS_vhangup: ::c_long = 4000 + 111; -pub const SYS_idle: ::c_long = 4000 + 112; -pub const SYS_vm86: ::c_long = 4000 + 113; -pub const SYS_wait4: ::c_long = 4000 + 114; -pub const SYS_swapoff: ::c_long = 4000 + 115; -pub const SYS_sysinfo: ::c_long = 4000 + 116; -pub const SYS_ipc: ::c_long = 4000 + 117; -pub const SYS_fsync: ::c_long = 4000 + 118; -pub const SYS_sigreturn: ::c_long = 4000 + 119; -pub const SYS_clone: ::c_long = 4000 + 120; -pub const SYS_setdomainname: ::c_long = 4000 + 121; -pub const SYS_uname: ::c_long = 4000 + 122; -pub const SYS_modify_ldt: ::c_long = 4000 + 123; -pub const SYS_adjtimex: ::c_long = 4000 + 124; -pub const SYS_mprotect: ::c_long = 4000 + 125; -pub const SYS_sigprocmask: ::c_long = 4000 + 126; -pub const SYS_create_module: ::c_long = 4000 + 127; -pub const SYS_init_module: ::c_long = 4000 + 128; -pub const SYS_delete_module: ::c_long = 4000 + 129; -pub const SYS_get_kernel_syms: ::c_long = 4000 + 130; -pub const SYS_quotactl: ::c_long = 4000 + 131; -pub const SYS_getpgid: ::c_long = 4000 + 132; -pub const SYS_fchdir: ::c_long = 4000 + 133; -pub const SYS_bdflush: ::c_long = 4000 + 134; -pub const SYS_sysfs: ::c_long = 4000 + 135; -pub const SYS_personality: ::c_long = 4000 + 136; -pub const SYS_afs_syscall: ::c_long = 4000 + 137; -pub const SYS_setfsuid: ::c_long = 4000 + 138; -pub const SYS_setfsgid: ::c_long = 4000 + 139; -pub const SYS__llseek: ::c_long = 4000 + 140; -pub const SYS_getdents: ::c_long = 4000 + 141; -pub const SYS__newselect: ::c_long = 4000 + 142; -pub const SYS_flock: ::c_long = 4000 + 143; -pub const SYS_msync: ::c_long = 4000 + 144; -pub const SYS_readv: ::c_long = 4000 + 145; -pub const SYS_writev: ::c_long = 4000 + 146; -pub const SYS_cacheflush: ::c_long = 4000 + 147; -pub const SYS_cachectl: ::c_long = 4000 + 148; -pub const SYS_sysmips: ::c_long = 4000 + 149; -pub const SYS_unused150: ::c_long = 4000 + 150; -pub const SYS_getsid: ::c_long = 4000 + 151; -pub const SYS_fdatasync: ::c_long = 4000 + 152; -pub const SYS__sysctl: ::c_long = 4000 + 153; -pub const SYS_mlock: ::c_long = 4000 + 154; -pub const SYS_munlock: ::c_long = 4000 + 155; -pub const SYS_mlockall: ::c_long = 4000 + 156; -pub const SYS_munlockall: ::c_long = 4000 + 157; -pub const SYS_sched_setparam: ::c_long = 4000 + 158; -pub const SYS_sched_getparam: ::c_long = 4000 + 159; -pub const SYS_sched_setscheduler: ::c_long = 4000 + 160; -pub const SYS_sched_getscheduler: ::c_long = 4000 + 161; -pub const SYS_sched_yield: ::c_long = 4000 + 162; -pub const SYS_sched_get_priority_max: ::c_long = 4000 + 163; -pub const SYS_sched_get_priority_min: ::c_long = 4000 + 164; -pub const SYS_sched_rr_get_interval: ::c_long = 4000 + 165; -pub const SYS_nanosleep: ::c_long = 4000 + 166; -pub const SYS_mremap: ::c_long = 4000 + 167; -pub const SYS_accept: ::c_long = 4000 + 168; -pub const SYS_bind: ::c_long = 4000 + 169; -pub const SYS_connect: ::c_long = 4000 + 170; -pub const SYS_getpeername: ::c_long = 4000 + 171; -pub const SYS_getsockname: ::c_long = 4000 + 172; -pub const SYS_getsockopt: ::c_long = 4000 + 173; -pub const SYS_listen: ::c_long = 4000 + 174; -pub const SYS_recv: ::c_long = 4000 + 175; -pub const SYS_recvfrom: ::c_long = 4000 + 176; -pub const SYS_recvmsg: ::c_long = 4000 + 177; -pub const SYS_send: ::c_long = 4000 + 178; -pub const SYS_sendmsg: ::c_long = 4000 + 179; -pub const SYS_sendto: ::c_long = 4000 + 180; -pub const SYS_setsockopt: ::c_long = 4000 + 181; -pub const SYS_shutdown: ::c_long = 4000 + 182; -pub const SYS_socket: ::c_long = 4000 + 183; -pub const SYS_socketpair: ::c_long = 4000 + 184; -pub const SYS_setresuid: ::c_long = 4000 + 185; -pub const SYS_getresuid: ::c_long = 4000 + 186; -pub const SYS_query_module: ::c_long = 4000 + 187; -pub const SYS_poll: ::c_long = 4000 + 188; -pub const SYS_nfsservctl: ::c_long = 4000 + 189; -pub const SYS_setresgid: ::c_long = 4000 + 190; -pub const SYS_getresgid: ::c_long = 4000 + 191; -pub const SYS_prctl: ::c_long = 4000 + 192; -pub const SYS_rt_sigreturn: ::c_long = 4000 + 193; -pub const SYS_rt_sigaction: ::c_long = 4000 + 194; -pub const SYS_rt_sigprocmask: ::c_long = 4000 + 195; -pub const SYS_rt_sigpending: ::c_long = 4000 + 196; -pub const SYS_rt_sigtimedwait: ::c_long = 4000 + 197; -pub const SYS_rt_sigqueueinfo: ::c_long = 4000 + 198; -pub const SYS_rt_sigsuspend: ::c_long = 4000 + 199; -pub const SYS_pread64: ::c_long = 4000 + 200; -pub const SYS_pwrite64: ::c_long = 4000 + 201; -pub const SYS_chown: ::c_long = 4000 + 202; -pub const SYS_getcwd: ::c_long = 4000 + 203; -pub const SYS_capget: ::c_long = 4000 + 204; -pub const SYS_capset: ::c_long = 4000 + 205; -pub const SYS_sigaltstack: ::c_long = 4000 + 206; -pub const SYS_sendfile: ::c_long = 4000 + 207; -pub const SYS_getpmsg: ::c_long = 4000 + 208; -pub const SYS_putpmsg: ::c_long = 4000 + 209; -pub const SYS_mmap2: ::c_long = 4000 + 210; -pub const SYS_truncate64: ::c_long = 4000 + 211; -pub const SYS_ftruncate64: ::c_long = 4000 + 212; -pub const SYS_stat64: ::c_long = 4000 + 213; -pub const SYS_lstat64: ::c_long = 4000 + 214; -pub const SYS_fstat64: ::c_long = 4000 + 215; -pub const SYS_pivot_root: ::c_long = 4000 + 216; -pub const SYS_mincore: ::c_long = 4000 + 217; -pub const SYS_madvise: ::c_long = 4000 + 218; -pub const SYS_getdents64: ::c_long = 4000 + 219; -pub const SYS_fcntl64: ::c_long = 4000 + 220; -pub const SYS_reserved221: ::c_long = 4000 + 221; -pub const SYS_gettid: ::c_long = 4000 + 222; -pub const SYS_readahead: ::c_long = 4000 + 223; -pub const SYS_setxattr: ::c_long = 4000 + 224; -pub const SYS_lsetxattr: ::c_long = 4000 + 225; -pub const SYS_fsetxattr: ::c_long = 4000 + 226; -pub const SYS_getxattr: ::c_long = 4000 + 227; -pub const SYS_lgetxattr: ::c_long = 4000 + 228; -pub const SYS_fgetxattr: ::c_long = 4000 + 229; -pub const SYS_listxattr: ::c_long = 4000 + 230; -pub const SYS_llistxattr: ::c_long = 4000 + 231; -pub const SYS_flistxattr: ::c_long = 4000 + 232; -pub const SYS_removexattr: ::c_long = 4000 + 233; -pub const SYS_lremovexattr: ::c_long = 4000 + 234; -pub const SYS_fremovexattr: ::c_long = 4000 + 235; -pub const SYS_tkill: ::c_long = 4000 + 236; -pub const SYS_sendfile64: ::c_long = 4000 + 237; -pub const SYS_futex: ::c_long = 4000 + 238; -pub const SYS_sched_setaffinity: ::c_long = 4000 + 239; -pub const SYS_sched_getaffinity: ::c_long = 4000 + 240; -pub const SYS_io_setup: ::c_long = 4000 + 241; -pub const SYS_io_destroy: ::c_long = 4000 + 242; -pub const SYS_io_getevents: ::c_long = 4000 + 243; -pub const SYS_io_submit: ::c_long = 4000 + 244; -pub const SYS_io_cancel: ::c_long = 4000 + 245; -pub const SYS_exit_group: ::c_long = 4000 + 246; -pub const SYS_lookup_dcookie: ::c_long = 4000 + 247; -pub const SYS_epoll_create: ::c_long = 4000 + 248; -pub const SYS_epoll_ctl: ::c_long = 4000 + 249; -pub const SYS_epoll_wait: ::c_long = 4000 + 250; -pub const SYS_remap_file_pages: ::c_long = 4000 + 251; -pub const SYS_set_tid_address: ::c_long = 4000 + 252; -pub const SYS_restart_syscall: ::c_long = 4000 + 253; -pub const SYS_fadvise64: ::c_long = 4000 + 254; -pub const SYS_statfs64: ::c_long = 4000 + 255; -pub const SYS_fstatfs64: ::c_long = 4000 + 256; -pub const SYS_timer_create: ::c_long = 4000 + 257; -pub const SYS_timer_settime: ::c_long = 4000 + 258; -pub const SYS_timer_gettime: ::c_long = 4000 + 259; -pub const SYS_timer_getoverrun: ::c_long = 4000 + 260; -pub const SYS_timer_delete: ::c_long = 4000 + 261; -pub const SYS_clock_settime: ::c_long = 4000 + 262; -pub const SYS_clock_gettime: ::c_long = 4000 + 263; -pub const SYS_clock_getres: ::c_long = 4000 + 264; -pub const SYS_clock_nanosleep: ::c_long = 4000 + 265; -pub const SYS_tgkill: ::c_long = 4000 + 266; -pub const SYS_utimes: ::c_long = 4000 + 267; -pub const SYS_mbind: ::c_long = 4000 + 268; -pub const SYS_get_mempolicy: ::c_long = 4000 + 269; -pub const SYS_set_mempolicy: ::c_long = 4000 + 270; -pub const SYS_mq_open: ::c_long = 4000 + 271; -pub const SYS_mq_unlink: ::c_long = 4000 + 272; -pub const SYS_mq_timedsend: ::c_long = 4000 + 273; -pub const SYS_mq_timedreceive: ::c_long = 4000 + 274; -pub const SYS_mq_notify: ::c_long = 4000 + 275; -pub const SYS_mq_getsetattr: ::c_long = 4000 + 276; -pub const SYS_vserver: ::c_long = 4000 + 277; -pub const SYS_waitid: ::c_long = 4000 + 278; -/* pub const SYS_sys_setaltroot: ::c_long = 4000 + 279; */ -pub const SYS_add_key: ::c_long = 4000 + 280; -pub const SYS_request_key: ::c_long = 4000 + 281; -pub const SYS_keyctl: ::c_long = 4000 + 282; -pub const SYS_set_thread_area: ::c_long = 4000 + 283; -pub const SYS_inotify_init: ::c_long = 4000 + 284; -pub const SYS_inotify_add_watch: ::c_long = 4000 + 285; -pub const SYS_inotify_rm_watch: ::c_long = 4000 + 286; -pub const SYS_migrate_pages: ::c_long = 4000 + 287; -pub const SYS_openat: ::c_long = 4000 + 288; -pub const SYS_mkdirat: ::c_long = 4000 + 289; -pub const SYS_mknodat: ::c_long = 4000 + 290; -pub const SYS_fchownat: ::c_long = 4000 + 291; -pub const SYS_futimesat: ::c_long = 4000 + 292; -pub const SYS_fstatat64: ::c_long = 4000 + 293; -pub const SYS_unlinkat: ::c_long = 4000 + 294; -pub const SYS_renameat: ::c_long = 4000 + 295; -pub const SYS_linkat: ::c_long = 4000 + 296; -pub const SYS_symlinkat: ::c_long = 4000 + 297; -pub const SYS_readlinkat: ::c_long = 4000 + 298; -pub const SYS_fchmodat: ::c_long = 4000 + 299; -pub const SYS_faccessat: ::c_long = 4000 + 300; -pub const SYS_pselect6: ::c_long = 4000 + 301; -pub const SYS_ppoll: ::c_long = 4000 + 302; -pub const SYS_unshare: ::c_long = 4000 + 303; -pub const SYS_splice: ::c_long = 4000 + 304; -pub const SYS_sync_file_range: ::c_long = 4000 + 305; -pub const SYS_tee: ::c_long = 4000 + 306; -pub const SYS_vmsplice: ::c_long = 4000 + 307; -pub const SYS_move_pages: ::c_long = 4000 + 308; -pub const SYS_set_robust_list: ::c_long = 4000 + 309; -pub const SYS_get_robust_list: ::c_long = 4000 + 310; -pub const SYS_kexec_load: ::c_long = 4000 + 311; -pub const SYS_getcpu: ::c_long = 4000 + 312; -pub const SYS_epoll_pwait: ::c_long = 4000 + 313; -pub const SYS_ioprio_set: ::c_long = 4000 + 314; -pub const SYS_ioprio_get: ::c_long = 4000 + 315; -pub const SYS_utimensat: ::c_long = 4000 + 316; -pub const SYS_signalfd: ::c_long = 4000 + 317; -pub const SYS_timerfd: ::c_long = 4000 + 318; -pub const SYS_eventfd: ::c_long = 4000 + 319; -pub const SYS_fallocate: ::c_long = 4000 + 320; -pub const SYS_timerfd_create: ::c_long = 4000 + 321; -pub const SYS_timerfd_gettime: ::c_long = 4000 + 322; -pub const SYS_timerfd_settime: ::c_long = 4000 + 323; -pub const SYS_signalfd4: ::c_long = 4000 + 324; -pub const SYS_eventfd2: ::c_long = 4000 + 325; -pub const SYS_epoll_create1: ::c_long = 4000 + 326; -pub const SYS_dup3: ::c_long = 4000 + 327; -pub const SYS_pipe2: ::c_long = 4000 + 328; -pub const SYS_inotify_init1: ::c_long = 4000 + 329; -pub const SYS_preadv: ::c_long = 4000 + 330; -pub const SYS_pwritev: ::c_long = 4000 + 331; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 4000 + 332; -pub const SYS_perf_event_open: ::c_long = 4000 + 333; -pub const SYS_accept4: ::c_long = 4000 + 334; -pub const SYS_recvmmsg: ::c_long = 4000 + 335; -pub const SYS_fanotify_init: ::c_long = 4000 + 336; -pub const SYS_fanotify_mark: ::c_long = 4000 + 337; -pub const SYS_prlimit64: ::c_long = 4000 + 338; -pub const SYS_name_to_handle_at: ::c_long = 4000 + 339; -pub const SYS_open_by_handle_at: ::c_long = 4000 + 340; -pub const SYS_clock_adjtime: ::c_long = 4000 + 341; -pub const SYS_syncfs: ::c_long = 4000 + 342; -pub const SYS_sendmmsg: ::c_long = 4000 + 343; -pub const SYS_setns: ::c_long = 4000 + 344; -pub const SYS_process_vm_readv: ::c_long = 4000 + 345; -pub const SYS_process_vm_writev: ::c_long = 4000 + 346; -pub const SYS_kcmp: ::c_long = 4000 + 347; -pub const SYS_finit_module: ::c_long = 4000 + 348; -pub const SYS_sched_setattr: ::c_long = 4000 + 349; -pub const SYS_sched_getattr: ::c_long = 4000 + 350; -pub const SYS_renameat2: ::c_long = 4000 + 351; -pub const SYS_seccomp: ::c_long = 4000 + 352; -pub const SYS_getrandom: ::c_long = 4000 + 353; -pub const SYS_memfd_create: ::c_long = 4000 + 354; -pub const SYS_bpf: ::c_long = 4000 + 355; -pub const SYS_execveat: ::c_long = 4000 + 356; -pub const SYS_userfaultfd: ::c_long = 4000 + 357; -pub const SYS_membarrier: ::c_long = 4000 + 358; -pub const SYS_mlock2: ::c_long = 4000 + 359; -pub const SYS_copy_file_range: ::c_long = 4000 + 360; -pub const SYS_preadv2: ::c_long = 4000 + 361; -pub const SYS_pwritev2: ::c_long = 4000 + 362; -pub const SYS_pkey_mprotect: ::c_long = 4000 + 363; -pub const SYS_pkey_alloc: ::c_long = 4000 + 364; -pub const SYS_pkey_free: ::c_long = 4000 + 365; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mips/mips64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mips/mips64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mips/mips64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mips/mips64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,579 +0,0 @@ -pub type blkcnt_t = i64; -pub type blksize_t = i64; -pub type c_char = i8; -pub type c_long = i64; -pub type c_ulong = u64; -pub type ino_t = u64; -pub type nlink_t = u64; -pub type off_t = i64; -pub type suseconds_t = i64; -pub type time_t = i64; -pub type wchar_t = i32; -pub type clock_t = i64; -pub type __u64 = ::c_ulong; - -s! { - pub struct aiocb { - pub aio_fildes: ::c_int, - pub aio_lio_opcode: ::c_int, - pub aio_reqprio: ::c_int, - pub aio_buf: *mut ::c_void, - pub aio_nbytes: ::size_t, - pub aio_sigevent: ::sigevent, - __next_prio: *mut aiocb, - __abs_prio: ::c_int, - __policy: ::c_int, - __error_code: ::c_int, - __return_value: ::ssize_t, - pub aio_offset: off_t, - __glibc_reserved: [::c_char; 32] - } - - pub struct stat { - pub st_dev: ::c_ulong, - st_pad1: [::c_long; 2], - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::c_ulong, - st_pad2: [::c_ulong; 1], - pub st_size: ::off_t, - st_pad3: ::c_long, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - st_pad4: ::c_long, - pub st_blocks: ::blkcnt_t, - st_pad5: [::c_long; 7], - } - - pub struct stat64 { - pub st_dev: ::c_ulong, - st_pad1: [::c_long; 2], - pub st_ino: ::ino64_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::c_ulong, - st_pad2: [::c_long; 2], - pub st_size: ::off64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - st_pad3: ::c_long, - pub st_blocks: ::blkcnt64_t, - st_pad5: [::c_long; 7], - } - - pub struct statfs64 { - pub f_type: ::c_long, - pub f_bsize: ::c_long, - pub f_frsize: ::c_long, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_bavail: u64, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_long, - pub f_flags: ::c_long, - pub f_spare: [::c_long; 5], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct pthread_attr_t { - __size: [::c_ulong; 7] - } - - pub struct sigaction { - pub sa_flags: ::c_int, - pub sa_sigaction: ::sighandler_t, - pub sa_mask: sigset_t, - pub sa_restorer: ::dox::Option, - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_size: ::size_t, - pub ss_flags: ::c_int, - } - - pub struct sigset_t { - __size: [::c_ulong; 16], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_code: ::c_int, - pub si_errno: ::c_int, - _pad: ::c_int, - _pad2: [::c_long; 14], - } - - pub struct ipc_perm { - pub __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::c_uint, - pub __seq: ::c_ushort, - __pad1: ::c_ushort, - __unused1: ::c_ulong, - __unused2: ::c_ulong - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __unused4: ::c_ulong, - __unused5: ::c_ulong - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - pub msg_stime: ::time_t, - pub msg_rtime: ::time_t, - pub msg_ctime: ::time_t, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __glibc_reserved4: ::c_ulong, - __glibc_reserved5: ::c_ulong, - } - - pub struct statfs { - pub f_type: ::c_long, - pub f_bsize: ::c_long, - pub f_frsize: ::c_long, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_files: ::fsblkcnt_t, - pub f_ffree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_fsid: ::fsid_t, - - pub f_namelen: ::c_long, - f_spare: [::c_long; 6], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::size_t, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::size_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::size_t, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; ::NCCS], - } - - pub struct flock { - pub l_type: ::c_short, - pub l_whence: ::c_short, - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_pid: ::pid_t, - } - - pub struct sysinfo { - pub uptime: ::c_long, - pub loads: [::c_ulong; 3], - pub totalram: ::c_ulong, - pub freeram: ::c_ulong, - pub sharedram: ::c_ulong, - pub bufferram: ::c_ulong, - pub totalswap: ::c_ulong, - pub freeswap: ::c_ulong, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: ::c_ulong, - pub freehigh: ::c_ulong, - pub mem_unit: ::c_uint, - pub _f: [::c_char; 0], - } -} - -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; -pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; - -pub const O_LARGEFILE: ::c_int = 0; - -pub const RLIM_INFINITY: ::rlim_t = 0xffff_ffff_ffff_ffff; - -pub const SYS_read: ::c_long = 5000 + 0; -pub const SYS_write: ::c_long = 5000 + 1; -pub const SYS_open: ::c_long = 5000 + 2; -pub const SYS_close: ::c_long = 5000 + 3; -pub const SYS_stat: ::c_long = 5000 + 4; -pub const SYS_fstat: ::c_long = 5000 + 5; -pub const SYS_lstat: ::c_long = 5000 + 6; -pub const SYS_poll: ::c_long = 5000 + 7; -pub const SYS_lseek: ::c_long = 5000 + 8; -pub const SYS_mmap: ::c_long = 5000 + 9; -pub const SYS_mprotect: ::c_long = 5000 + 10; -pub const SYS_munmap: ::c_long = 5000 + 11; -pub const SYS_brk: ::c_long = 5000 + 12; -pub const SYS_rt_sigaction: ::c_long = 5000 + 13; -pub const SYS_rt_sigprocmask: ::c_long = 5000 + 14; -pub const SYS_ioctl: ::c_long = 5000 + 15; -pub const SYS_pread64: ::c_long = 5000 + 16; -pub const SYS_pwrite64: ::c_long = 5000 + 17; -pub const SYS_readv: ::c_long = 5000 + 18; -pub const SYS_writev: ::c_long = 5000 + 19; -pub const SYS_access: ::c_long = 5000 + 20; -pub const SYS_pipe: ::c_long = 5000 + 21; -pub const SYS__newselect: ::c_long = 5000 + 22; -pub const SYS_sched_yield: ::c_long = 5000 + 23; -pub const SYS_mremap: ::c_long = 5000 + 24; -pub const SYS_msync: ::c_long = 5000 + 25; -pub const SYS_mincore: ::c_long = 5000 + 26; -pub const SYS_madvise: ::c_long = 5000 + 27; -pub const SYS_shmget: ::c_long = 5000 + 28; -pub const SYS_shmat: ::c_long = 5000 + 29; -pub const SYS_shmctl: ::c_long = 5000 + 30; -pub const SYS_dup: ::c_long = 5000 + 31; -pub const SYS_dup2: ::c_long = 5000 + 32; -pub const SYS_pause: ::c_long = 5000 + 33; -pub const SYS_nanosleep: ::c_long = 5000 + 34; -pub const SYS_getitimer: ::c_long = 5000 + 35; -pub const SYS_setitimer: ::c_long = 5000 + 36; -pub const SYS_alarm: ::c_long = 5000 + 37; -pub const SYS_getpid: ::c_long = 5000 + 38; -pub const SYS_sendfile: ::c_long = 5000 + 39; -pub const SYS_socket: ::c_long = 5000 + 40; -pub const SYS_connect: ::c_long = 5000 + 41; -pub const SYS_accept: ::c_long = 5000 + 42; -pub const SYS_sendto: ::c_long = 5000 + 43; -pub const SYS_recvfrom: ::c_long = 5000 + 44; -pub const SYS_sendmsg: ::c_long = 5000 + 45; -pub const SYS_recvmsg: ::c_long = 5000 + 46; -pub const SYS_shutdown: ::c_long = 5000 + 47; -pub const SYS_bind: ::c_long = 5000 + 48; -pub const SYS_listen: ::c_long = 5000 + 49; -pub const SYS_getsockname: ::c_long = 5000 + 50; -pub const SYS_getpeername: ::c_long = 5000 + 51; -pub const SYS_socketpair: ::c_long = 5000 + 52; -pub const SYS_setsockopt: ::c_long = 5000 + 53; -pub const SYS_getsockopt: ::c_long = 5000 + 54; -pub const SYS_clone: ::c_long = 5000 + 55; -pub const SYS_fork: ::c_long = 5000 + 56; -pub const SYS_execve: ::c_long = 5000 + 57; -pub const SYS_exit: ::c_long = 5000 + 58; -pub const SYS_wait4: ::c_long = 5000 + 59; -pub const SYS_kill: ::c_long = 5000 + 60; -pub const SYS_uname: ::c_long = 5000 + 61; -pub const SYS_semget: ::c_long = 5000 + 62; -pub const SYS_semop: ::c_long = 5000 + 63; -pub const SYS_semctl: ::c_long = 5000 + 64; -pub const SYS_shmdt: ::c_long = 5000 + 65; -pub const SYS_msgget: ::c_long = 5000 + 66; -pub const SYS_msgsnd: ::c_long = 5000 + 67; -pub const SYS_msgrcv: ::c_long = 5000 + 68; -pub const SYS_msgctl: ::c_long = 5000 + 69; -pub const SYS_fcntl: ::c_long = 5000 + 70; -pub const SYS_flock: ::c_long = 5000 + 71; -pub const SYS_fsync: ::c_long = 5000 + 72; -pub const SYS_fdatasync: ::c_long = 5000 + 73; -pub const SYS_truncate: ::c_long = 5000 + 74; -pub const SYS_ftruncate: ::c_long = 5000 + 75; -pub const SYS_getdents: ::c_long = 5000 + 76; -pub const SYS_getcwd: ::c_long = 5000 + 77; -pub const SYS_chdir: ::c_long = 5000 + 78; -pub const SYS_fchdir: ::c_long = 5000 + 79; -pub const SYS_rename: ::c_long = 5000 + 80; -pub const SYS_mkdir: ::c_long = 5000 + 81; -pub const SYS_rmdir: ::c_long = 5000 + 82; -pub const SYS_creat: ::c_long = 5000 + 83; -pub const SYS_link: ::c_long = 5000 + 84; -pub const SYS_unlink: ::c_long = 5000 + 85; -pub const SYS_symlink: ::c_long = 5000 + 86; -pub const SYS_readlink: ::c_long = 5000 + 87; -pub const SYS_chmod: ::c_long = 5000 + 88; -pub const SYS_fchmod: ::c_long = 5000 + 89; -pub const SYS_chown: ::c_long = 5000 + 90; -pub const SYS_fchown: ::c_long = 5000 + 91; -pub const SYS_lchown: ::c_long = 5000 + 92; -pub const SYS_umask: ::c_long = 5000 + 93; -pub const SYS_gettimeofday: ::c_long = 5000 + 94; -pub const SYS_getrlimit: ::c_long = 5000 + 95; -pub const SYS_getrusage: ::c_long = 5000 + 96; -pub const SYS_sysinfo: ::c_long = 5000 + 97; -pub const SYS_times: ::c_long = 5000 + 98; -pub const SYS_ptrace: ::c_long = 5000 + 99; -pub const SYS_getuid: ::c_long = 5000 + 100; -pub const SYS_syslog: ::c_long = 5000 + 101; -pub const SYS_getgid: ::c_long = 5000 + 102; -pub const SYS_setuid: ::c_long = 5000 + 103; -pub const SYS_setgid: ::c_long = 5000 + 104; -pub const SYS_geteuid: ::c_long = 5000 + 105; -pub const SYS_getegid: ::c_long = 5000 + 106; -pub const SYS_setpgid: ::c_long = 5000 + 107; -pub const SYS_getppid: ::c_long = 5000 + 108; -pub const SYS_getpgrp: ::c_long = 5000 + 109; -pub const SYS_setsid: ::c_long = 5000 + 110; -pub const SYS_setreuid: ::c_long = 5000 + 111; -pub const SYS_setregid: ::c_long = 5000 + 112; -pub const SYS_getgroups: ::c_long = 5000 + 113; -pub const SYS_setgroups: ::c_long = 5000 + 114; -pub const SYS_setresuid: ::c_long = 5000 + 115; -pub const SYS_getresuid: ::c_long = 5000 + 116; -pub const SYS_setresgid: ::c_long = 5000 + 117; -pub const SYS_getresgid: ::c_long = 5000 + 118; -pub const SYS_getpgid: ::c_long = 5000 + 119; -pub const SYS_setfsuid: ::c_long = 5000 + 120; -pub const SYS_setfsgid: ::c_long = 5000 + 121; -pub const SYS_getsid: ::c_long = 5000 + 122; -pub const SYS_capget: ::c_long = 5000 + 123; -pub const SYS_capset: ::c_long = 5000 + 124; -pub const SYS_rt_sigpending: ::c_long = 5000 + 125; -pub const SYS_rt_sigtimedwait: ::c_long = 5000 + 126; -pub const SYS_rt_sigqueueinfo: ::c_long = 5000 + 127; -pub const SYS_rt_sigsuspend: ::c_long = 5000 + 128; -pub const SYS_sigaltstack: ::c_long = 5000 + 129; -pub const SYS_utime: ::c_long = 5000 + 130; -pub const SYS_mknod: ::c_long = 5000 + 131; -pub const SYS_personality: ::c_long = 5000 + 132; -pub const SYS_ustat: ::c_long = 5000 + 133; -pub const SYS_statfs: ::c_long = 5000 + 134; -pub const SYS_fstatfs: ::c_long = 5000 + 135; -pub const SYS_sysfs: ::c_long = 5000 + 136; -pub const SYS_getpriority: ::c_long = 5000 + 137; -pub const SYS_setpriority: ::c_long = 5000 + 138; -pub const SYS_sched_setparam: ::c_long = 5000 + 139; -pub const SYS_sched_getparam: ::c_long = 5000 + 140; -pub const SYS_sched_setscheduler: ::c_long = 5000 + 141; -pub const SYS_sched_getscheduler: ::c_long = 5000 + 142; -pub const SYS_sched_get_priority_max: ::c_long = 5000 + 143; -pub const SYS_sched_get_priority_min: ::c_long = 5000 + 144; -pub const SYS_sched_rr_get_interval: ::c_long = 5000 + 145; -pub const SYS_mlock: ::c_long = 5000 + 146; -pub const SYS_munlock: ::c_long = 5000 + 147; -pub const SYS_mlockall: ::c_long = 5000 + 148; -pub const SYS_munlockall: ::c_long = 5000 + 149; -pub const SYS_vhangup: ::c_long = 5000 + 150; -pub const SYS_pivot_root: ::c_long = 5000 + 151; -pub const SYS__sysctl: ::c_long = 5000 + 152; -pub const SYS_prctl: ::c_long = 5000 + 153; -pub const SYS_adjtimex: ::c_long = 5000 + 154; -pub const SYS_setrlimit: ::c_long = 5000 + 155; -pub const SYS_chroot: ::c_long = 5000 + 156; -pub const SYS_sync: ::c_long = 5000 + 157; -pub const SYS_acct: ::c_long = 5000 + 158; -pub const SYS_settimeofday: ::c_long = 5000 + 159; -pub const SYS_mount: ::c_long = 5000 + 160; -pub const SYS_umount2: ::c_long = 5000 + 161; -pub const SYS_swapon: ::c_long = 5000 + 162; -pub const SYS_swapoff: ::c_long = 5000 + 163; -pub const SYS_reboot: ::c_long = 5000 + 164; -pub const SYS_sethostname: ::c_long = 5000 + 165; -pub const SYS_setdomainname: ::c_long = 5000 + 166; -pub const SYS_create_module: ::c_long = 5000 + 167; -pub const SYS_init_module: ::c_long = 5000 + 168; -pub const SYS_delete_module: ::c_long = 5000 + 169; -pub const SYS_get_kernel_syms: ::c_long = 5000 + 170; -pub const SYS_query_module: ::c_long = 5000 + 171; -pub const SYS_quotactl: ::c_long = 5000 + 172; -pub const SYS_nfsservctl: ::c_long = 5000 + 173; -pub const SYS_getpmsg: ::c_long = 5000 + 174; -pub const SYS_putpmsg: ::c_long = 5000 + 175; -pub const SYS_afs_syscall: ::c_long = 5000 + 176; -pub const SYS_reserved177: ::c_long = 5000 + 177; -pub const SYS_gettid: ::c_long = 5000 + 178; -pub const SYS_readahead: ::c_long = 5000 + 179; -pub const SYS_setxattr: ::c_long = 5000 + 180; -pub const SYS_lsetxattr: ::c_long = 5000 + 181; -pub const SYS_fsetxattr: ::c_long = 5000 + 182; -pub const SYS_getxattr: ::c_long = 5000 + 183; -pub const SYS_lgetxattr: ::c_long = 5000 + 184; -pub const SYS_fgetxattr: ::c_long = 5000 + 185; -pub const SYS_listxattr: ::c_long = 5000 + 186; -pub const SYS_llistxattr: ::c_long = 5000 + 187; -pub const SYS_flistxattr: ::c_long = 5000 + 188; -pub const SYS_removexattr: ::c_long = 5000 + 189; -pub const SYS_lremovexattr: ::c_long = 5000 + 190; -pub const SYS_fremovexattr: ::c_long = 5000 + 191; -pub const SYS_tkill: ::c_long = 5000 + 192; -pub const SYS_reserved193: ::c_long = 5000 + 193; -pub const SYS_futex: ::c_long = 5000 + 194; -pub const SYS_sched_setaffinity: ::c_long = 5000 + 195; -pub const SYS_sched_getaffinity: ::c_long = 5000 + 196; -pub const SYS_cacheflush: ::c_long = 5000 + 197; -pub const SYS_cachectl: ::c_long = 5000 + 198; -pub const SYS_sysmips: ::c_long = 5000 + 199; -pub const SYS_io_setup: ::c_long = 5000 + 200; -pub const SYS_io_destroy: ::c_long = 5000 + 201; -pub const SYS_io_getevents: ::c_long = 5000 + 202; -pub const SYS_io_submit: ::c_long = 5000 + 203; -pub const SYS_io_cancel: ::c_long = 5000 + 204; -pub const SYS_exit_group: ::c_long = 5000 + 205; -pub const SYS_lookup_dcookie: ::c_long = 5000 + 206; -pub const SYS_epoll_create: ::c_long = 5000 + 207; -pub const SYS_epoll_ctl: ::c_long = 5000 + 208; -pub const SYS_epoll_wait: ::c_long = 5000 + 209; -pub const SYS_remap_file_pages: ::c_long = 5000 + 210; -pub const SYS_rt_sigreturn: ::c_long = 5000 + 211; -pub const SYS_set_tid_address: ::c_long = 5000 + 212; -pub const SYS_restart_syscall: ::c_long = 5000 + 213; -pub const SYS_semtimedop: ::c_long = 5000 + 214; -pub const SYS_fadvise64: ::c_long = 5000 + 215; -pub const SYS_timer_create: ::c_long = 5000 + 216; -pub const SYS_timer_settime: ::c_long = 5000 + 217; -pub const SYS_timer_gettime: ::c_long = 5000 + 218; -pub const SYS_timer_getoverrun: ::c_long = 5000 + 219; -pub const SYS_timer_delete: ::c_long = 5000 + 220; -pub const SYS_clock_settime: ::c_long = 5000 + 221; -pub const SYS_clock_gettime: ::c_long = 5000 + 222; -pub const SYS_clock_getres: ::c_long = 5000 + 223; -pub const SYS_clock_nanosleep: ::c_long = 5000 + 224; -pub const SYS_tgkill: ::c_long = 5000 + 225; -pub const SYS_utimes: ::c_long = 5000 + 226; -pub const SYS_mbind: ::c_long = 5000 + 227; -pub const SYS_get_mempolicy: ::c_long = 5000 + 228; -pub const SYS_set_mempolicy: ::c_long = 5000 + 229; -pub const SYS_mq_open: ::c_long = 5000 + 230; -pub const SYS_mq_unlink: ::c_long = 5000 + 231; -pub const SYS_mq_timedsend: ::c_long = 5000 + 232; -pub const SYS_mq_timedreceive: ::c_long = 5000 + 233; -pub const SYS_mq_notify: ::c_long = 5000 + 234; -pub const SYS_mq_getsetattr: ::c_long = 5000 + 235; -pub const SYS_vserver: ::c_long = 5000 + 236; -pub const SYS_waitid: ::c_long = 5000 + 237; -/* pub const SYS_sys_setaltroot: ::c_long = 5000 + 238; */ -pub const SYS_add_key: ::c_long = 5000 + 239; -pub const SYS_request_key: ::c_long = 5000 + 240; -pub const SYS_keyctl: ::c_long = 5000 + 241; -pub const SYS_set_thread_area: ::c_long = 5000 + 242; -pub const SYS_inotify_init: ::c_long = 5000 + 243; -pub const SYS_inotify_add_watch: ::c_long = 5000 + 244; -pub const SYS_inotify_rm_watch: ::c_long = 5000 + 245; -pub const SYS_migrate_pages: ::c_long = 5000 + 246; -pub const SYS_openat: ::c_long = 5000 + 247; -pub const SYS_mkdirat: ::c_long = 5000 + 248; -pub const SYS_mknodat: ::c_long = 5000 + 249; -pub const SYS_fchownat: ::c_long = 5000 + 250; -pub const SYS_futimesat: ::c_long = 5000 + 251; -pub const SYS_newfstatat: ::c_long = 5000 + 252; -pub const SYS_unlinkat: ::c_long = 5000 + 253; -pub const SYS_renameat: ::c_long = 5000 + 254; -pub const SYS_linkat: ::c_long = 5000 + 255; -pub const SYS_symlinkat: ::c_long = 5000 + 256; -pub const SYS_readlinkat: ::c_long = 5000 + 257; -pub const SYS_fchmodat: ::c_long = 5000 + 258; -pub const SYS_faccessat: ::c_long = 5000 + 259; -pub const SYS_pselect6: ::c_long = 5000 + 260; -pub const SYS_ppoll: ::c_long = 5000 + 261; -pub const SYS_unshare: ::c_long = 5000 + 262; -pub const SYS_splice: ::c_long = 5000 + 263; -pub const SYS_sync_file_range: ::c_long = 5000 + 264; -pub const SYS_tee: ::c_long = 5000 + 265; -pub const SYS_vmsplice: ::c_long = 5000 + 266; -pub const SYS_move_pages: ::c_long = 5000 + 267; -pub const SYS_set_robust_list: ::c_long = 5000 + 268; -pub const SYS_get_robust_list: ::c_long = 5000 + 269; -pub const SYS_kexec_load: ::c_long = 5000 + 270; -pub const SYS_getcpu: ::c_long = 5000 + 271; -pub const SYS_epoll_pwait: ::c_long = 5000 + 272; -pub const SYS_ioprio_set: ::c_long = 5000 + 273; -pub const SYS_ioprio_get: ::c_long = 5000 + 274; -pub const SYS_utimensat: ::c_long = 5000 + 275; -pub const SYS_signalfd: ::c_long = 5000 + 276; -pub const SYS_timerfd: ::c_long = 5000 + 277; -pub const SYS_eventfd: ::c_long = 5000 + 278; -pub const SYS_fallocate: ::c_long = 5000 + 279; -pub const SYS_timerfd_create: ::c_long = 5000 + 280; -pub const SYS_timerfd_gettime: ::c_long = 5000 + 281; -pub const SYS_timerfd_settime: ::c_long = 5000 + 282; -pub const SYS_signalfd4: ::c_long = 5000 + 283; -pub const SYS_eventfd2: ::c_long = 5000 + 284; -pub const SYS_epoll_create1: ::c_long = 5000 + 285; -pub const SYS_dup3: ::c_long = 5000 + 286; -pub const SYS_pipe2: ::c_long = 5000 + 287; -pub const SYS_inotify_init1: ::c_long = 5000 + 288; -pub const SYS_preadv: ::c_long = 5000 + 289; -pub const SYS_pwritev: ::c_long = 5000 + 290; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 5000 + 291; -pub const SYS_perf_event_open: ::c_long = 5000 + 292; -pub const SYS_accept4: ::c_long = 5000 + 293; -pub const SYS_recvmmsg: ::c_long = 5000 + 294; -pub const SYS_fanotify_init: ::c_long = 5000 + 295; -pub const SYS_fanotify_mark: ::c_long = 5000 + 296; -pub const SYS_prlimit64: ::c_long = 5000 + 297; -pub const SYS_name_to_handle_at: ::c_long = 5000 + 298; -pub const SYS_open_by_handle_at: ::c_long = 5000 + 299; -pub const SYS_clock_adjtime: ::c_long = 5000 + 300; -pub const SYS_syncfs: ::c_long = 5000 + 301; -pub const SYS_sendmmsg: ::c_long = 5000 + 302; -pub const SYS_setns: ::c_long = 5000 + 303; -pub const SYS_process_vm_readv: ::c_long = 5000 + 304; -pub const SYS_process_vm_writev: ::c_long = 5000 + 305; -pub const SYS_kcmp: ::c_long = 5000 + 306; -pub const SYS_finit_module: ::c_long = 5000 + 307; -pub const SYS_getdents64: ::c_long = 5000 + 308; -pub const SYS_sched_setattr: ::c_long = 5000 + 309; -pub const SYS_sched_getattr: ::c_long = 5000 + 310; -pub const SYS_renameat2: ::c_long = 5000 + 311; -pub const SYS_seccomp: ::c_long = 5000 + 312; -pub const SYS_getrandom: ::c_long = 5000 + 313; -pub const SYS_memfd_create: ::c_long = 5000 + 314; -pub const SYS_bpf: ::c_long = 5000 + 315; -pub const SYS_execveat: ::c_long = 5000 + 316; -pub const SYS_userfaultfd: ::c_long = 5000 + 317; -pub const SYS_membarrier: ::c_long = 5000 + 318; -pub const SYS_mlock2: ::c_long = 5000 + 319; -pub const SYS_copy_file_range: ::c_long = 5000 + 320; -pub const SYS_preadv2: ::c_long = 5000 + 321; -pub const SYS_pwritev2: ::c_long = 5000 + 322; -pub const SYS_pkey_mprotect: ::c_long = 5000 + 323; -pub const SYS_pkey_alloc: ::c_long = 5000 + 324; -pub const SYS_pkey_free: ::c_long = 5000 + 325; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mips/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mips/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mips/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mips/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,718 +0,0 @@ -pub type shmatt_t = ::c_ulong; -pub type msgqnum_t = ::c_ulong; -pub type msglen_t = ::c_ulong; -pub type fsblkcnt_t = ::c_ulong; -pub type fsfilcnt_t = ::c_ulong; -pub type rlim_t = c_ulong; -pub type __priority_which_t = ::c_uint; - -s! { - pub struct glob64_t { - pub gl_pathc: ::size_t, - pub gl_pathv: *mut *mut ::c_char, - pub gl_offs: ::size_t, - pub gl_flags: ::c_int, - - __unused1: *mut ::c_void, - __unused2: *mut ::c_void, - __unused3: *mut ::c_void, - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - } - - // FIXME this is actually a union - pub struct sem_t { - #[cfg(target_pointer_width = "32")] - __size: [::c_char; 16], - #[cfg(target_pointer_width = "64")] - __size: [::c_char; 32], - __align: [::c_long; 0], - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 23], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } -} - -pub const SFD_CLOEXEC: ::c_int = 0x080000; - -pub const NCCS: usize = 32; - -pub const O_TRUNC: ::c_int = 512; - -pub const O_NOATIME: ::c_int = 0o1000000; -pub const O_CLOEXEC: ::c_int = 0x80000; -pub const O_PATH: ::c_int = 0o10000000; -pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; - -pub const EBFONT: ::c_int = 59; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENONET: ::c_int = 64; -pub const ENOPKG: ::c_int = 65; -pub const EREMOTE: ::c_int = 66; -pub const ENOLINK: ::c_int = 67; -pub const EADV: ::c_int = 68; -pub const ESRMNT: ::c_int = 69; -pub const ECOMM: ::c_int = 70; -pub const EPROTO: ::c_int = 71; -pub const EDOTDOT: ::c_int = 73; - -pub const SA_NODEFER: ::c_int = 0x40000000; -pub const SA_RESETHAND: ::c_int = 0x80000000; -pub const SA_RESTART: ::c_int = 0x10000000; -pub const SA_NOCLDSTOP: ::c_int = 0x00000001; - -pub const EPOLL_CLOEXEC: ::c_int = 0x80000; - -pub const EFD_CLOEXEC: ::c_int = 0x80000; - -pub const BUFSIZ: ::c_uint = 8192; -pub const TMP_MAX: ::c_uint = 238328; -pub const FOPEN_MAX: ::c_uint = 16; -pub const POSIX_FADV_DONTNEED: ::c_int = 4; -pub const POSIX_FADV_NOREUSE: ::c_int = 5; -pub const POSIX_MADV_DONTNEED: ::c_int = 4; -pub const _SC_EQUIV_CLASS_MAX: ::c_int = 41; -pub const _SC_CHARCLASS_NAME_MAX: ::c_int = 45; -pub const _SC_PII: ::c_int = 53; -pub const _SC_PII_XTI: ::c_int = 54; -pub const _SC_PII_SOCKET: ::c_int = 55; -pub const _SC_PII_INTERNET: ::c_int = 56; -pub const _SC_PII_OSI: ::c_int = 57; -pub const _SC_POLL: ::c_int = 58; -pub const _SC_SELECT: ::c_int = 59; -pub const _SC_PII_INTERNET_STREAM: ::c_int = 61; -pub const _SC_PII_INTERNET_DGRAM: ::c_int = 62; -pub const _SC_PII_OSI_COTS: ::c_int = 63; -pub const _SC_PII_OSI_CLTS: ::c_int = 64; -pub const _SC_PII_OSI_M: ::c_int = 65; -pub const _SC_T_IOV_MAX: ::c_int = 66; -pub const _SC_2_C_VERSION: ::c_int = 96; -pub const _SC_CHAR_BIT: ::c_int = 101; -pub const _SC_CHAR_MAX: ::c_int = 102; -pub const _SC_CHAR_MIN: ::c_int = 103; -pub const _SC_INT_MAX: ::c_int = 104; -pub const _SC_INT_MIN: ::c_int = 105; -pub const _SC_LONG_BIT: ::c_int = 106; -pub const _SC_WORD_BIT: ::c_int = 107; -pub const _SC_MB_LEN_MAX: ::c_int = 108; -pub const _SC_SSIZE_MAX: ::c_int = 110; -pub const _SC_SCHAR_MAX: ::c_int = 111; -pub const _SC_SCHAR_MIN: ::c_int = 112; -pub const _SC_SHRT_MAX: ::c_int = 113; -pub const _SC_SHRT_MIN: ::c_int = 114; -pub const _SC_UCHAR_MAX: ::c_int = 115; -pub const _SC_UINT_MAX: ::c_int = 116; -pub const _SC_ULONG_MAX: ::c_int = 117; -pub const _SC_USHRT_MAX: ::c_int = 118; -pub const _SC_NL_ARGMAX: ::c_int = 119; -pub const _SC_NL_LANGMAX: ::c_int = 120; -pub const _SC_NL_MSGMAX: ::c_int = 121; -pub const _SC_NL_NMAX: ::c_int = 122; -pub const _SC_NL_SETMAX: ::c_int = 123; -pub const _SC_NL_TEXTMAX: ::c_int = 124; -pub const _SC_BASE: ::c_int = 134; -pub const _SC_C_LANG_SUPPORT: ::c_int = 135; -pub const _SC_C_LANG_SUPPORT_R: ::c_int = 136; -pub const _SC_DEVICE_IO: ::c_int = 140; -pub const _SC_DEVICE_SPECIFIC: ::c_int = 141; -pub const _SC_DEVICE_SPECIFIC_R: ::c_int = 142; -pub const _SC_FD_MGMT: ::c_int = 143; -pub const _SC_FIFO: ::c_int = 144; -pub const _SC_PIPE: ::c_int = 145; -pub const _SC_FILE_ATTRIBUTES: ::c_int = 146; -pub const _SC_FILE_LOCKING: ::c_int = 147; -pub const _SC_FILE_SYSTEM: ::c_int = 148; -pub const _SC_MULTI_PROCESS: ::c_int = 150; -pub const _SC_SINGLE_PROCESS: ::c_int = 151; -pub const _SC_NETWORKING: ::c_int = 152; -pub const _SC_REGEX_VERSION: ::c_int = 156; -pub const _SC_SIGNALS: ::c_int = 158; -pub const _SC_SYSTEM_DATABASE: ::c_int = 162; -pub const _SC_SYSTEM_DATABASE_R: ::c_int = 163; -pub const _SC_USER_GROUPS: ::c_int = 166; -pub const _SC_USER_GROUPS_R: ::c_int = 167; -pub const _SC_LEVEL1_ICACHE_SIZE: ::c_int = 185; -pub const _SC_LEVEL1_ICACHE_ASSOC: ::c_int = 186; -pub const _SC_LEVEL1_ICACHE_LINESIZE: ::c_int = 187; -pub const _SC_LEVEL1_DCACHE_SIZE: ::c_int = 188; -pub const _SC_LEVEL1_DCACHE_ASSOC: ::c_int = 189; -pub const _SC_LEVEL1_DCACHE_LINESIZE: ::c_int = 190; -pub const _SC_LEVEL2_CACHE_SIZE: ::c_int = 191; -pub const _SC_LEVEL2_CACHE_ASSOC: ::c_int = 192; -pub const _SC_LEVEL2_CACHE_LINESIZE: ::c_int = 193; -pub const _SC_LEVEL3_CACHE_SIZE: ::c_int = 194; -pub const _SC_LEVEL3_CACHE_ASSOC: ::c_int = 195; -pub const _SC_LEVEL3_CACHE_LINESIZE: ::c_int = 196; -pub const _SC_LEVEL4_CACHE_SIZE: ::c_int = 197; -pub const _SC_LEVEL4_CACHE_ASSOC: ::c_int = 198; -pub const _SC_LEVEL4_CACHE_LINESIZE: ::c_int = 199; -pub const O_ACCMODE: ::c_int = 3; -pub const O_DIRECT: ::c_int = 0x8000; -pub const O_DIRECTORY: ::c_int = 0x10000; -pub const O_NOFOLLOW: ::c_int = 0x20000; -pub const ST_RELATIME: ::c_ulong = 4096; -pub const NI_MAXHOST: ::socklen_t = 1025; - -pub const RLIMIT_NOFILE: ::c_int = 5; -pub const RLIMIT_AS: ::c_int = 6; -pub const RLIMIT_RSS: ::c_int = 7; -pub const RLIMIT_NPROC: ::c_int = 8; -pub const RLIMIT_MEMLOCK: ::c_int = 9; -pub const RLIMIT_NLIMITS: ::c_int = 16; - -pub const O_APPEND: ::c_int = 8; -pub const O_CREAT: ::c_int = 256; -pub const O_EXCL: ::c_int = 1024; -pub const O_NOCTTY: ::c_int = 2048; -pub const O_NONBLOCK: ::c_int = 128; -pub const O_SYNC: ::c_int = 0x4010; -pub const O_RSYNC: ::c_int = 0x4010; -pub const O_DSYNC: ::c_int = 0x10; -pub const O_FSYNC: ::c_int = 0x4010; -pub const O_ASYNC: ::c_int = 0x1000; -pub const O_NDELAY: ::c_int = 0x80; - -pub const SOCK_NONBLOCK: ::c_int = 128; - -pub const EDEADLK: ::c_int = 45; -pub const ENAMETOOLONG: ::c_int = 78; -pub const ENOLCK: ::c_int = 46; -pub const ENOSYS: ::c_int = 89; -pub const ENOTEMPTY: ::c_int = 93; -pub const ELOOP: ::c_int = 90; -pub const ENOMSG: ::c_int = 35; -pub const EIDRM: ::c_int = 36; -pub const ECHRNG: ::c_int = 37; -pub const EL2NSYNC: ::c_int = 38; -pub const EL3HLT: ::c_int = 39; -pub const EL3RST: ::c_int = 40; -pub const ELNRNG: ::c_int = 41; -pub const EUNATCH: ::c_int = 42; -pub const ENOCSI: ::c_int = 43; -pub const EL2HLT: ::c_int = 44; -pub const EBADE: ::c_int = 50; -pub const EBADR: ::c_int = 51; -pub const EXFULL: ::c_int = 52; -pub const ENOANO: ::c_int = 53; -pub const EBADRQC: ::c_int = 54; -pub const EBADSLT: ::c_int = 55; -pub const EDEADLOCK: ::c_int = 56; -pub const EMULTIHOP: ::c_int = 74; -pub const EOVERFLOW: ::c_int = 79; -pub const ENOTUNIQ: ::c_int = 80; -pub const EBADFD: ::c_int = 81; -pub const EBADMSG: ::c_int = 77; -pub const EREMCHG: ::c_int = 82; -pub const ELIBACC: ::c_int = 83; -pub const ELIBBAD: ::c_int = 84; -pub const ELIBSCN: ::c_int = 85; -pub const ELIBMAX: ::c_int = 86; -pub const ELIBEXEC: ::c_int = 87; -pub const EILSEQ: ::c_int = 88; -pub const ERESTART: ::c_int = 91; -pub const ESTRPIPE: ::c_int = 92; -pub const EUSERS: ::c_int = 94; -pub const ENOTSOCK: ::c_int = 95; -pub const EDESTADDRREQ: ::c_int = 96; -pub const EMSGSIZE: ::c_int = 97; -pub const EPROTOTYPE: ::c_int = 98; -pub const ENOPROTOOPT: ::c_int = 99; -pub const EPROTONOSUPPORT: ::c_int = 120; -pub const ESOCKTNOSUPPORT: ::c_int = 121; -pub const EOPNOTSUPP: ::c_int = 122; -pub const ENOTSUP: ::c_int = EOPNOTSUPP; -pub const EPFNOSUPPORT: ::c_int = 123; -pub const EAFNOSUPPORT: ::c_int = 124; -pub const EADDRINUSE: ::c_int = 125; -pub const EADDRNOTAVAIL: ::c_int = 126; -pub const ENETDOWN: ::c_int = 127; -pub const ENETUNREACH: ::c_int = 128; -pub const ENETRESET: ::c_int = 129; -pub const ECONNABORTED: ::c_int = 130; -pub const ECONNRESET: ::c_int = 131; -pub const ENOBUFS: ::c_int = 132; -pub const EISCONN: ::c_int = 133; -pub const ENOTCONN: ::c_int = 134; -pub const ESHUTDOWN: ::c_int = 143; -pub const ETOOMANYREFS: ::c_int = 144; -pub const ETIMEDOUT: ::c_int = 145; -pub const ECONNREFUSED: ::c_int = 146; -pub const EHOSTDOWN: ::c_int = 147; -pub const EHOSTUNREACH: ::c_int = 148; -pub const EALREADY: ::c_int = 149; -pub const EINPROGRESS: ::c_int = 150; -pub const ESTALE: ::c_int = 151; -pub const EUCLEAN: ::c_int = 135; -pub const ENOTNAM: ::c_int = 137; -pub const ENAVAIL: ::c_int = 138; -pub const EISNAM: ::c_int = 139; -pub const EREMOTEIO: ::c_int = 140; -pub const EDQUOT: ::c_int = 1133; -pub const ENOMEDIUM: ::c_int = 159; -pub const EMEDIUMTYPE: ::c_int = 160; -pub const ECANCELED: ::c_int = 158; -pub const ENOKEY: ::c_int = 161; -pub const EKEYEXPIRED: ::c_int = 162; -pub const EKEYREVOKED: ::c_int = 163; -pub const EKEYREJECTED: ::c_int = 164; -pub const EOWNERDEAD: ::c_int = 165; -pub const ENOTRECOVERABLE: ::c_int = 166; -pub const ERFKILL: ::c_int = 167; - -pub const LC_PAPER: ::c_int = 7; -pub const LC_NAME: ::c_int = 8; -pub const LC_ADDRESS: ::c_int = 9; -pub const LC_TELEPHONE: ::c_int = 10; -pub const LC_MEASUREMENT: ::c_int = 11; -pub const LC_IDENTIFICATION: ::c_int = 12; -pub const LC_PAPER_MASK: ::c_int = (1 << LC_PAPER); -pub const LC_NAME_MASK: ::c_int = (1 << LC_NAME); -pub const LC_ADDRESS_MASK: ::c_int = (1 << LC_ADDRESS); -pub const LC_TELEPHONE_MASK: ::c_int = (1 << LC_TELEPHONE); -pub const LC_MEASUREMENT_MASK: ::c_int = (1 << LC_MEASUREMENT); -pub const LC_IDENTIFICATION_MASK: ::c_int = (1 << LC_IDENTIFICATION); -pub const LC_ALL_MASK: ::c_int = ::LC_CTYPE_MASK - | ::LC_NUMERIC_MASK - | ::LC_TIME_MASK - | ::LC_COLLATE_MASK - | ::LC_MONETARY_MASK - | ::LC_MESSAGES_MASK - | LC_PAPER_MASK - | LC_NAME_MASK - | LC_ADDRESS_MASK - | LC_TELEPHONE_MASK - | LC_MEASUREMENT_MASK - | LC_IDENTIFICATION_MASK; - -pub const MAP_NORESERVE: ::c_int = 0x400; -pub const MAP_ANON: ::c_int = 0x800; -pub const MAP_ANONYMOUS: ::c_int = 0x800; -pub const MAP_GROWSDOWN: ::c_int = 0x1000; -pub const MAP_DENYWRITE: ::c_int = 0x2000; -pub const MAP_EXECUTABLE: ::c_int = 0x4000; -pub const MAP_LOCKED: ::c_int = 0x8000; -pub const MAP_POPULATE: ::c_int = 0x10000; -pub const MAP_NONBLOCK: ::c_int = 0x20000; -pub const MAP_STACK: ::c_int = 0x40000; - -pub const SOCK_STREAM: ::c_int = 2; -pub const SOCK_DGRAM: ::c_int = 1; -pub const SOCK_SEQPACKET: ::c_int = 5; -pub const SOCK_DCCP: ::c_int = 6; -pub const SOCK_PACKET: ::c_int = 10; - -pub const SOL_SOCKET: ::c_int = 0xffff; - -pub const SO_REUSEADDR: ::c_int = 0x0004; -pub const SO_KEEPALIVE: ::c_int = 0x0008; -pub const SO_DONTROUTE: ::c_int = 0x0010; -pub const SO_BROADCAST: ::c_int = 0x0020; -pub const SO_LINGER: ::c_int = 0x0080; -pub const SO_OOBINLINE: ::c_int = 0x0100; -pub const SO_REUSEPORT: ::c_int = 0x0200; -pub const SO_TYPE: ::c_int = 0x1008; -pub const SO_STYLE: ::c_int = SO_TYPE; -pub const SO_ERROR: ::c_int = 0x1007; -pub const SO_SNDBUF: ::c_int = 0x1001; -pub const SO_RCVBUF: ::c_int = 0x1002; -pub const SO_SNDLOWAT: ::c_int = 0x1003; -pub const SO_RCVLOWAT: ::c_int = 0x1004; -pub const SO_SNDTIMEO: ::c_int = 0x1005; -pub const SO_RCVTIMEO: ::c_int = 0x1006; -pub const SO_ACCEPTCONN: ::c_int = 0x1009; -pub const SO_PROTOCOL: ::c_int = 0x1028; -pub const SO_DOMAIN: ::c_int = 0x1029; -pub const SO_NO_CHECK: ::c_int = 11; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_PASSCRED: ::c_int = 17; -pub const SO_PEERCRED: ::c_int = 18; -pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22; -pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23; -pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24; -pub const SO_BINDTODEVICE: ::c_int = 25; -pub const SO_ATTACH_FILTER: ::c_int = 26; -pub const SO_DETACH_FILTER: ::c_int = 27; -pub const SO_GET_FILTER: ::c_int = SO_ATTACH_FILTER; -pub const SO_PEERNAME: ::c_int = 28; -pub const SO_TIMESTAMP: ::c_int = 29; -pub const SO_PEERSEC: ::c_int = 30; -pub const SO_SNDBUFFORCE: ::c_int = 31; -pub const SO_RCVBUFFORCE: ::c_int = 33; -pub const SO_PASSSEC: ::c_int = 34; -pub const SO_TIMESTAMPNS: ::c_int = 35; -pub const SCM_TIMESTAMPNS: ::c_int = SO_TIMESTAMPNS; -pub const SO_MARK: ::c_int = 36; -pub const SO_TIMESTAMPING: ::c_int = 37; -pub const SCM_TIMESTAMPING: ::c_int = SO_TIMESTAMPING; -pub const SO_RXQ_OVFL: ::c_int = 40; -pub const SO_WIFI_STATUS: ::c_int = 41; -pub const SCM_WIFI_STATUS: ::c_int = SO_WIFI_STATUS; -pub const SO_PEEK_OFF: ::c_int = 42; -pub const SO_NOFCS: ::c_int = 43; -pub const SO_LOCK_FILTER: ::c_int = 44; -pub const SO_SELECT_ERR_QUEUE: ::c_int = 45; -pub const SO_BUSY_POLL: ::c_int = 46; -pub const SO_MAX_PACING_RATE: ::c_int = 47; -pub const SO_BPF_EXTENSIONS: ::c_int = 48; -pub const SO_INCOMING_CPU: ::c_int = 49; -pub const SO_ATTACH_BPF: ::c_int = 50; -pub const SO_DETACH_BPF: ::c_int = SO_DETACH_FILTER; - -/* DCCP socket options */ -pub const DCCP_SOCKOPT_PACKET_SIZE: ::c_int = 1; -pub const DCCP_SOCKOPT_SERVICE: ::c_int = 2; -pub const DCCP_SOCKOPT_CHANGE_L: ::c_int = 3; -pub const DCCP_SOCKOPT_CHANGE_R: ::c_int = 4; -pub const DCCP_SOCKOPT_GET_CUR_MPS: ::c_int = 5; -pub const DCCP_SOCKOPT_SERVER_TIMEWAIT: ::c_int = 6; -pub const DCCP_SOCKOPT_SEND_CSCOV: ::c_int = 10; -pub const DCCP_SOCKOPT_RECV_CSCOV: ::c_int = 11; -pub const DCCP_SOCKOPT_AVAILABLE_CCIDS: ::c_int = 12; -pub const DCCP_SOCKOPT_CCID: ::c_int = 13; -pub const DCCP_SOCKOPT_TX_CCID: ::c_int = 14; -pub const DCCP_SOCKOPT_RX_CCID: ::c_int = 15; -pub const DCCP_SOCKOPT_QPOLICY_ID: ::c_int = 16; -pub const DCCP_SOCKOPT_QPOLICY_TXQLEN: ::c_int = 17; -pub const DCCP_SOCKOPT_CCID_RX_INFO: ::c_int = 128; -pub const DCCP_SOCKOPT_CCID_TX_INFO: ::c_int = 192; - -/// maximum number of services provided on the same listening port -pub const DCCP_SERVICE_LIST_MAX_LEN: ::c_int = 32; - -pub const FIOCLEX: ::c_ulong = 0x6601; -pub const FIONBIO: ::c_ulong = 0x667e; - -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 0x00000008; -pub const SA_NOCLDWAIT: ::c_int = 0x00010000; - -pub const SIGCHLD: ::c_int = 18; -pub const SIGBUS: ::c_int = 10; -pub const SIGTTIN: ::c_int = 26; -pub const SIGTTOU: ::c_int = 27; -pub const SIGXCPU: ::c_int = 30; -pub const SIGXFSZ: ::c_int = 31; -pub const SIGVTALRM: ::c_int = 28; -pub const SIGPROF: ::c_int = 29; -pub const SIGWINCH: ::c_int = 20; -pub const SIGUSR1: ::c_int = 16; -pub const SIGUSR2: ::c_int = 17; -pub const SIGCONT: ::c_int = 25; -pub const SIGSTOP: ::c_int = 23; -pub const SIGTSTP: ::c_int = 24; -pub const SIGURG: ::c_int = 21; -pub const SIGIO: ::c_int = 22; -pub const SIGSYS: ::c_int = 12; -pub const SIGPOLL: ::c_int = 22; -pub const SIGPWR: ::c_int = 19; -pub const SIG_SETMASK: ::c_int = 3; -pub const SIG_BLOCK: ::c_int = 0x1; -pub const SIG_UNBLOCK: ::c_int = 0x2; - -pub const POLLWRNORM: ::c_short = 0x004; -pub const POLLWRBAND: ::c_short = 0x100; - -pub const PTHREAD_STACK_MIN: ::size_t = 131072; - -pub const ADFS_SUPER_MAGIC: ::c_long = 0x0000adf5; -pub const AFFS_SUPER_MAGIC: ::c_long = 0x0000adff; -pub const CODA_SUPER_MAGIC: ::c_long = 0x73757245; -pub const CRAMFS_MAGIC: ::c_long = 0x28cd3d45; -pub const EFS_SUPER_MAGIC: ::c_long = 0x00414a53; -pub const EXT2_SUPER_MAGIC: ::c_long = 0x0000ef53; -pub const EXT3_SUPER_MAGIC: ::c_long = 0x0000ef53; -pub const EXT4_SUPER_MAGIC: ::c_long = 0x0000ef53; -pub const HPFS_SUPER_MAGIC: ::c_long = 0xf995e849; -pub const HUGETLBFS_MAGIC: ::c_long = 0x958458f6; -pub const ISOFS_SUPER_MAGIC: ::c_long = 0x00009660; -pub const JFFS2_SUPER_MAGIC: ::c_long = 0x000072b6; -pub const MINIX_SUPER_MAGIC: ::c_long = 0x0000137f; -pub const MINIX_SUPER_MAGIC2: ::c_long = 0x0000138f; -pub const MINIX2_SUPER_MAGIC: ::c_long = 0x00002468; -pub const MINIX2_SUPER_MAGIC2: ::c_long = 0x00002478; -pub const MSDOS_SUPER_MAGIC: ::c_long = 0x00004d44; -pub const NCP_SUPER_MAGIC: ::c_long = 0x0000564c; -pub const NFS_SUPER_MAGIC: ::c_long = 0x00006969; -pub const OPENPROM_SUPER_MAGIC: ::c_long = 0x00009fa1; -pub const PROC_SUPER_MAGIC: ::c_long = 0x00009fa0; -pub const QNX4_SUPER_MAGIC: ::c_long = 0x0000002f; -pub const REISERFS_SUPER_MAGIC: ::c_long = 0x52654973; -pub const SMB_SUPER_MAGIC: ::c_long = 0x0000517b; -pub const TMPFS_MAGIC: ::c_long = 0x01021994; -pub const USBDEVICE_SUPER_MAGIC: ::c_long = 0x00009fa2; - -pub const VEOF: usize = 16; -pub const VEOL: usize = 17; -pub const VEOL2: usize = 6; -pub const VMIN: usize = 4; -pub const IEXTEN: ::tcflag_t = 0x00000100; -pub const TOSTOP: ::tcflag_t = 0x00008000; -pub const FLUSHO: ::tcflag_t = 0x00002000; -pub const EXTPROC: ::tcflag_t = 0o200000; -pub const TCSANOW: ::c_int = 0x540e; -pub const TCSADRAIN: ::c_int = 0x540f; -pub const TCSAFLUSH: ::c_int = 0x5410; - -pub const CPU_SETSIZE: ::c_int = 0x400; - -pub const PTRACE_TRACEME: ::c_uint = 0; -pub const PTRACE_PEEKTEXT: ::c_uint = 1; -pub const PTRACE_PEEKDATA: ::c_uint = 2; -pub const PTRACE_PEEKUSER: ::c_uint = 3; -pub const PTRACE_POKETEXT: ::c_uint = 4; -pub const PTRACE_POKEDATA: ::c_uint = 5; -pub const PTRACE_POKEUSER: ::c_uint = 6; -pub const PTRACE_CONT: ::c_uint = 7; -pub const PTRACE_KILL: ::c_uint = 8; -pub const PTRACE_SINGLESTEP: ::c_uint = 9; -pub const PTRACE_ATTACH: ::c_uint = 16; -pub const PTRACE_DETACH: ::c_uint = 17; -pub const PTRACE_SYSCALL: ::c_uint = 24; -pub const PTRACE_SETOPTIONS: ::c_uint = 0x4200; -pub const PTRACE_GETEVENTMSG: ::c_uint = 0x4201; -pub const PTRACE_GETSIGINFO: ::c_uint = 0x4202; -pub const PTRACE_SETSIGINFO: ::c_uint = 0x4203; -pub const PTRACE_GETFPREGS: ::c_uint = 14; -pub const PTRACE_SETFPREGS: ::c_uint = 15; -pub const PTRACE_GETFPXREGS: ::c_uint = 18; -pub const PTRACE_SETFPXREGS: ::c_uint = 19; -pub const PTRACE_GETREGS: ::c_uint = 12; -pub const PTRACE_SETREGS: ::c_uint = 13; - -pub const MAP_HUGETLB: ::c_int = 0x080000; - -pub const EFD_NONBLOCK: ::c_int = 0x80; - -pub const F_GETLK: ::c_int = 14; -pub const F_GETOWN: ::c_int = 23; -pub const F_SETOWN: ::c_int = 24; -pub const F_SETLK: ::c_int = 6; -pub const F_SETLKW: ::c_int = 7; - -pub const SFD_NONBLOCK: ::c_int = 0x80; - -pub const TCGETS: ::c_ulong = 0x540d; -pub const TCSETS: ::c_ulong = 0x540e; -pub const TCSETSW: ::c_ulong = 0x540f; -pub const TCSETSF: ::c_ulong = 0x5410; -pub const TCGETA: ::c_ulong = 0x5401; -pub const TCSETA: ::c_ulong = 0x5402; -pub const TCSETAW: ::c_ulong = 0x5403; -pub const TCSETAF: ::c_ulong = 0x5404; -pub const TCSBRK: ::c_ulong = 0x5405; -pub const TCXONC: ::c_ulong = 0x5406; -pub const TCFLSH: ::c_ulong = 0x5407; -pub const TIOCGSOFTCAR: ::c_ulong = 0x5481; -pub const TIOCSSOFTCAR: ::c_ulong = 0x5482; -pub const TIOCINQ: ::c_ulong = 0x467f; -pub const TIOCLINUX: ::c_ulong = 0x5483; -pub const TIOCGSERIAL: ::c_ulong = 0x5484; -pub const TIOCEXCL: ::c_ulong = 0x740d; -pub const TIOCNXCL: ::c_ulong = 0x740e; -pub const TIOCSCTTY: ::c_ulong = 0x5480; -pub const TIOCGPGRP: ::c_ulong = 0x40047477; -pub const TIOCSPGRP: ::c_ulong = 0x80047476; -pub const TIOCOUTQ: ::c_ulong = 0x7472; -pub const TIOCSTI: ::c_ulong = 0x5472; -pub const TIOCGWINSZ: ::c_ulong = 0x40087468; -pub const TIOCSWINSZ: ::c_ulong = 0x80087467; -pub const TIOCMGET: ::c_ulong = 0x741d; -pub const TIOCMBIS: ::c_ulong = 0x741b; -pub const TIOCMBIC: ::c_ulong = 0x741c; -pub const TIOCMSET: ::c_ulong = 0x741a; -pub const FIONREAD: ::c_ulong = 0x467f; -pub const TIOCCONS: ::c_ulong = 0x80047478; - -pub const RTLD_DEEPBIND: ::c_int = 0x10; -pub const RTLD_GLOBAL: ::c_int = 0x4; -pub const RTLD_NOLOAD: ::c_int = 0x8; - -pub const LINUX_REBOOT_MAGIC1: ::c_int = 0xfee1dead; -pub const LINUX_REBOOT_MAGIC2: ::c_int = 672274793; -pub const LINUX_REBOOT_MAGIC2A: ::c_int = 85072278; -pub const LINUX_REBOOT_MAGIC2B: ::c_int = 369367448; -pub const LINUX_REBOOT_MAGIC2C: ::c_int = 537993216; - -pub const LINUX_REBOOT_CMD_RESTART: ::c_int = 0x01234567; -pub const LINUX_REBOOT_CMD_HALT: ::c_int = 0xCDEF0123; -pub const LINUX_REBOOT_CMD_CAD_ON: ::c_int = 0x89ABCDEF; -pub const LINUX_REBOOT_CMD_CAD_OFF: ::c_int = 0x00000000; -pub const LINUX_REBOOT_CMD_POWER_OFF: ::c_int = 0x4321FEDC; -pub const LINUX_REBOOT_CMD_RESTART2: ::c_int = 0xA1B2C3D4; -pub const LINUX_REBOOT_CMD_SW_SUSPEND: ::c_int = 0xD000FCE2; -pub const LINUX_REBOOT_CMD_KEXEC: ::c_int = 0x45584543; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const SIGSTKSZ: ::size_t = 8192; -pub const MINSIGSTKSZ: ::size_t = 2048; -pub const CBAUD: ::tcflag_t = 0o0010017; -pub const TAB1: ::c_int = 0x00000800; -pub const TAB2: ::c_int = 0x00001000; -pub const TAB3: ::c_int = 0x00001800; -pub const CR1: ::c_int = 0x00000200; -pub const CR2: ::c_int = 0x00000400; -pub const CR3: ::c_int = 0x00000600; -pub const FF1: ::c_int = 0x00008000; -pub const BS1: ::c_int = 0x00002000; -pub const VT1: ::c_int = 0x00004000; -pub const VWERASE: usize = 14; -pub const VREPRINT: usize = 12; -pub const VSUSP: usize = 10; -pub const VSTART: usize = 8; -pub const VSTOP: usize = 9; -pub const VDISCARD: usize = 13; -pub const VTIME: usize = 5; -pub const IXON: ::tcflag_t = 0x00000400; -pub const IXOFF: ::tcflag_t = 0x00001000; -pub const ONLCR: ::tcflag_t = 0x4; -pub const CSIZE: ::tcflag_t = 0x00000030; -pub const CS6: ::tcflag_t = 0x00000010; -pub const CS7: ::tcflag_t = 0x00000020; -pub const CS8: ::tcflag_t = 0x00000030; -pub const CSTOPB: ::tcflag_t = 0x00000040; -pub const CREAD: ::tcflag_t = 0x00000080; -pub const PARENB: ::tcflag_t = 0x00000100; -pub const PARODD: ::tcflag_t = 0x00000200; -pub const HUPCL: ::tcflag_t = 0x00000400; -pub const CLOCAL: ::tcflag_t = 0x00000800; -pub const ECHOKE: ::tcflag_t = 0x00000800; -pub const ECHOE: ::tcflag_t = 0x00000010; -pub const ECHOK: ::tcflag_t = 0x00000020; -pub const ECHONL: ::tcflag_t = 0x00000040; -pub const ECHOPRT: ::tcflag_t = 0x00000400; -pub const ECHOCTL: ::tcflag_t = 0x00000200; -pub const ISIG: ::tcflag_t = 0x00000001; -pub const ICANON: ::tcflag_t = 0x00000002; -pub const PENDIN: ::tcflag_t = 0x00004000; -pub const NOFLSH: ::tcflag_t = 0x00000080; -pub const CIBAUD: ::tcflag_t = 0o02003600000; -pub const CBAUDEX: ::tcflag_t = 0o010000; -pub const VSWTC: usize = 7; -pub const OLCUC: ::tcflag_t = 0o000002; -pub const NLDLY: ::tcflag_t = 0o000400; -pub const CRDLY: ::tcflag_t = 0o003000; -pub const TABDLY: ::tcflag_t = 0o014000; -pub const BSDLY: ::tcflag_t = 0o020000; -pub const FFDLY: ::tcflag_t = 0o100000; -pub const VTDLY: ::tcflag_t = 0o040000; -pub const XTABS: ::tcflag_t = 0o014000; - -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const EXTA: ::speed_t = B19200; -pub const EXTB: ::speed_t = B38400; -pub const BOTHER: ::speed_t = 0o010000; -pub const B57600: ::speed_t = 0o010001; -pub const B115200: ::speed_t = 0o010002; -pub const B230400: ::speed_t = 0o010003; -pub const B460800: ::speed_t = 0o010004; -pub const B500000: ::speed_t = 0o010005; -pub const B576000: ::speed_t = 0o010006; -pub const B921600: ::speed_t = 0o010007; -pub const B1000000: ::speed_t = 0o010010; -pub const B1152000: ::speed_t = 0o010011; -pub const B1500000: ::speed_t = 0o010012; -pub const B2000000: ::speed_t = 0o010013; -pub const B2500000: ::speed_t = 0o010014; -pub const B3000000: ::speed_t = 0o010015; -pub const B3500000: ::speed_t = 0o010016; -pub const B4000000: ::speed_t = 0o010017; - -pub const TIOCM_LE: ::c_int = 0x001; -pub const TIOCM_DTR: ::c_int = 0x002; -pub const TIOCM_RTS: ::c_int = 0x004; -pub const TIOCM_ST: ::c_int = 0x010; -pub const TIOCM_SR: ::c_int = 0x020; -pub const TIOCM_CTS: ::c_int = 0x040; -pub const TIOCM_CAR: ::c_int = 0x100; -pub const TIOCM_CD: ::c_int = TIOCM_CAR; -pub const TIOCM_RNG: ::c_int = 0x200; -pub const TIOCM_RI: ::c_int = TIOCM_RNG; -pub const TIOCM_DSR: ::c_int = 0x400; - -pub const EHWPOISON: ::c_int = 168; -pub const SIGEV_THREAD_ID: ::c_int = 4; -pub const EPOLLWAKEUP: ::c_int = 0x20000000; - -#[doc(hidden)] -pub const AF_MAX: ::c_int = 42; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; - -#[link(name = "util")] -extern { - pub fn sysctl(name: *mut ::c_int, - namelen: ::c_int, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *mut ::c_void, - newlen: ::size_t) - -> ::c_int; - pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; - pub fn backtrace(buf: *mut *mut ::c_void, - sz: ::c_int) -> ::c_int; - pub fn glob64(pattern: *const ::c_char, - flags: ::c_int, - errfunc: ::dox::Option ::c_int>, - pglob: *mut glob64_t) -> ::c_int; - pub fn globfree64(pglob: *mut glob64_t); - pub fn ptrace(request: ::c_uint, ...) -> ::c_long; - pub fn pthread_attr_getaffinity_np(attr: *const ::pthread_attr_t, - cpusetsize: ::size_t, - cpuset: *mut ::cpu_set_t) -> ::c_int; - pub fn pthread_attr_setaffinity_np(attr: *mut ::pthread_attr_t, - cpusetsize: ::size_t, - cpuset: *const ::cpu_set_t) -> ::c_int; - pub fn getpriority(which: ::__priority_which_t, who: ::id_t) -> ::c_int; - pub fn setpriority(which: ::__priority_which_t, who: ::id_t, - prio: ::c_int) -> ::c_int; - pub fn pthread_getaffinity_np(thread: ::pthread_t, - cpusetsize: ::size_t, - cpuset: *mut ::cpu_set_t) -> ::c_int; - pub fn pthread_setaffinity_np(thread: ::pthread_t, - cpusetsize: ::size_t, - cpuset: *const ::cpu_set_t) -> ::c_int; - pub fn sched_getcpu() -> ::c_int; -} - -cfg_if! { - if #[cfg(target_arch = "mips")] { - mod mips32; - pub use self::mips32::*; - } else if #[cfg(target_arch = "mips64")] { - mod mips64; - pub use self::mips64::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1731 +0,0 @@ -//! Linux-specific definitions for linux-like values - -use dox::{mem, Option}; - -pub type useconds_t = u32; -pub type dev_t = u64; -pub type socklen_t = u32; -pub type pthread_t = c_ulong; -pub type mode_t = u32; -pub type ino64_t = u64; -pub type off64_t = i64; -pub type blkcnt64_t = i64; -pub type rlim64_t = u64; -pub type mqd_t = ::c_int; -pub type nfds_t = ::c_ulong; -pub type nl_item = ::c_int; -pub type idtype_t = ::c_uint; -pub type loff_t = ::c_longlong; - -pub type __u8 = ::c_uchar; -pub type __u16 = ::c_ushort; -pub type __s16 = ::c_short; -pub type __u32 = ::c_uint; -pub type __s32 = ::c_int; - -pub type Elf32_Half = u16; -pub type Elf32_Word = u32; -pub type Elf32_Off = u32; -pub type Elf32_Addr = u32; - -pub type Elf64_Half = u16; -pub type Elf64_Word = u32; -pub type Elf64_Off = u64; -pub type Elf64_Addr = u64; -pub type Elf64_Xword = u64; - -pub enum fpos64_t {} // TODO: fill this out with a struct - -s! { - pub struct dirent { - pub d_ino: ::ino_t, - pub d_off: ::off_t, - pub d_reclen: ::c_ushort, - pub d_type: ::c_uchar, - pub d_name: [::c_char; 256], - } - - pub struct dirent64 { - pub d_ino: ::ino64_t, - pub d_off: ::off64_t, - pub d_reclen: ::c_ushort, - pub d_type: ::c_uchar, - pub d_name: [::c_char; 256], - } - - pub struct rlimit64 { - pub rlim_cur: rlim64_t, - pub rlim_max: rlim64_t, - } - - pub struct glob_t { - pub gl_pathc: ::size_t, - pub gl_pathv: *mut *mut c_char, - pub gl_offs: ::size_t, - pub gl_flags: ::c_int, - - __unused1: *mut ::c_void, - __unused2: *mut ::c_void, - __unused3: *mut ::c_void, - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - } - - pub struct ifaddrs { - pub ifa_next: *mut ifaddrs, - pub ifa_name: *mut c_char, - pub ifa_flags: ::c_uint, - pub ifa_addr: *mut ::sockaddr, - pub ifa_netmask: *mut ::sockaddr, - pub ifa_ifu: *mut ::sockaddr, // FIXME This should be a union - pub ifa_data: *mut ::c_void - } - - pub struct pthread_mutex_t { - #[cfg(any(target_arch = "mips", - target_arch = "arm", - target_arch = "powerpc", - all(target_arch = "x86_64", - target_pointer_width = "32")))] - __align: [::c_long; 0], - #[cfg(not(any(target_arch = "mips", - target_arch = "arm", - target_arch = "powerpc", - all(target_arch = "x86_64", - target_pointer_width = "32"))))] - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_MUTEX_T], - } - - pub struct pthread_rwlock_t { - #[cfg(any(target_arch = "mips", - target_arch = "arm", - target_arch = "powerpc", - all(target_arch = "x86_64", - target_pointer_width = "32")))] - __align: [::c_long; 0], - #[cfg(not(any(target_arch = "mips", - target_arch = "arm", - target_arch = "powerpc", - all(target_arch = "x86_64", - target_pointer_width = "32"))))] - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_RWLOCK_T], - } - - pub struct pthread_mutexattr_t { - #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", - target_arch = "mips64", target_arch = "s390x", - target_arch = "sparc64"))] - __align: [::c_int; 0], - #[cfg(not(any(target_arch = "x86_64", target_arch = "powerpc64", - target_arch = "mips64", target_arch = "s390x", - target_arch = "sparc64", target_arch = "aarch64")))] - __align: [::c_long; 0], - #[cfg(all(target_arch = "aarch64", target_env = "gnu"))] - __align: [::c_long; 0], - #[cfg(all(target_arch = "aarch64", target_env = "musl"))] - __align: [::c_int; 0], - size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T], - } - - pub struct pthread_rwlockattr_t { - #[cfg(any(target_env = "musl"))] - __align: [::c_int; 0], - #[cfg(not(any(target_env = "musl")))] - __align: [::c_long; 0], - size: [u8; __SIZEOF_PTHREAD_RWLOCKATTR_T], - } - - pub struct pthread_cond_t { - #[cfg(any(target_env = "musl"))] - __align: [*const ::c_void; 0], - #[cfg(not(any(target_env = "musl")))] - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_COND_T], - } - - pub struct pthread_condattr_t { - __align: [::c_int; 0], - size: [u8; __SIZEOF_PTHREAD_CONDATTR_T], - } - - pub struct passwd { - pub pw_name: *mut ::c_char, - pub pw_passwd: *mut ::c_char, - pub pw_uid: ::uid_t, - pub pw_gid: ::gid_t, - pub pw_gecos: *mut ::c_char, - pub pw_dir: *mut ::c_char, - pub pw_shell: *mut ::c_char, - } - - pub struct spwd { - pub sp_namp: *mut ::c_char, - pub sp_pwdp: *mut ::c_char, - pub sp_lstchg: ::c_long, - pub sp_min: ::c_long, - pub sp_max: ::c_long, - pub sp_warn: ::c_long, - pub sp_inact: ::c_long, - pub sp_expire: ::c_long, - pub sp_flag: ::c_ulong, - } - - pub struct statvfs { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_favail: ::fsfilcnt_t, - #[cfg(target_endian = "little")] - pub f_fsid: ::c_ulong, - #[cfg(all(target_pointer_width = "32", not(target_arch = "x86_64")))] - __f_unused: ::c_int, - #[cfg(target_endian = "big")] - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct dqblk { - pub dqb_bhardlimit: ::uint64_t, - pub dqb_bsoftlimit: ::uint64_t, - pub dqb_curspace: ::uint64_t, - pub dqb_ihardlimit: ::uint64_t, - pub dqb_isoftlimit: ::uint64_t, - pub dqb_curinodes: ::uint64_t, - pub dqb_btime: ::uint64_t, - pub dqb_itime: ::uint64_t, - pub dqb_valid: ::uint32_t, - } - - pub struct signalfd_siginfo { - pub ssi_signo: ::uint32_t, - pub ssi_errno: ::int32_t, - pub ssi_code: ::int32_t, - pub ssi_pid: ::uint32_t, - pub ssi_uid: ::uint32_t, - pub ssi_fd: ::int32_t, - pub ssi_tid: ::uint32_t, - pub ssi_band: ::uint32_t, - pub ssi_overrun: ::uint32_t, - pub ssi_trapno: ::uint32_t, - pub ssi_status: ::int32_t, - pub ssi_int: ::int32_t, - pub ssi_ptr: ::uint64_t, - pub ssi_utime: ::uint64_t, - pub ssi_stime: ::uint64_t, - pub ssi_addr: ::uint64_t, - _pad: [::uint8_t; 48], - } - - pub struct itimerspec { - pub it_interval: ::timespec, - pub it_value: ::timespec, - } - - pub struct fsid_t { - __val: [::c_int; 2], - } - - // x32 compatibility - // See https://sourceware.org/bugzilla/show_bug.cgi?id=21279 - pub struct mq_attr { - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - pub mq_flags: i64, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - pub mq_maxmsg: i64, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - pub mq_msgsize: i64, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - pub mq_curmsgs: i64, - #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] - pad: [i64; 4], - - #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] - pub mq_flags: ::c_long, - #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] - pub mq_maxmsg: ::c_long, - #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] - pub mq_msgsize: ::c_long, - #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] - pub mq_curmsgs: ::c_long, - #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] - pad: [::c_long; 4], - } - - pub struct cpu_set_t { - #[cfg(all(target_pointer_width = "32", - not(target_arch = "x86_64")))] - bits: [u32; 32], - #[cfg(not(all(target_pointer_width = "32", - not(target_arch = "x86_64"))))] - bits: [u64; 16], - } - - pub struct if_nameindex { - pub if_index: ::c_uint, - pub if_name: *mut ::c_char, - } - - // System V IPC - pub struct msginfo { - pub msgpool: ::c_int, - pub msgmap: ::c_int, - pub msgmax: ::c_int, - pub msgmnb: ::c_int, - pub msgmni: ::c_int, - pub msgssz: ::c_int, - pub msgtql: ::c_int, - pub msgseg: ::c_ushort, - } - - pub struct mmsghdr { - pub msg_hdr: ::msghdr, - pub msg_len: ::c_uint, - } - - pub struct sembuf { - pub sem_num: ::c_ushort, - pub sem_op: ::c_short, - pub sem_flg: ::c_short, - } - - pub struct input_event { - pub time: ::timeval, - pub type_: ::__u16, - pub code: ::__u16, - pub value: ::__s32, - } - - pub struct input_id { - pub bustype: ::__u16, - pub vendor: ::__u16, - pub product: ::__u16, - pub version: ::__u16, - } - - pub struct input_absinfo { - pub value: ::__s32, - pub minimum: ::__s32, - pub maximum: ::__s32, - pub fuzz: ::__s32, - pub flat: ::__s32, - pub resolution: ::__s32, - } - - pub struct input_keymap_entry { - pub flags: ::__u8, - pub len: ::__u8, - pub index: ::__u16, - pub keycode: ::__u32, - pub scancode: [::__u8; 32], - } - - pub struct input_mask { - pub type_: ::__u32, - pub codes_size: ::__u32, - pub codes_ptr: ::__u64, - } - - pub struct ff_replay { - pub length: ::__u16, - pub delay: ::__u16, - } - - pub struct ff_trigger { - pub button: ::__u16, - pub interval: ::__u16, - } - - pub struct ff_envelope { - pub attack_length: ::__u16, - pub attack_level: ::__u16, - pub fade_length: ::__u16, - pub fade_level: ::__u16, - } - - pub struct ff_constant_effect { - pub level: ::__s16, - pub envelope: ff_envelope, - } - - pub struct ff_ramp_effect { - pub start_level: ::__s16, - pub end_level: ::__s16, - pub envelope: ff_envelope, - } - - pub struct ff_condition_effect { - pub right_saturation: ::__u16, - pub left_saturation: ::__u16, - - pub right_coeff: ::__s16, - pub left_coeff: ::__s16, - - pub deadband: ::__u16, - pub center: ::__s16, - } - - pub struct ff_periodic_effect { - pub waveform: ::__u16, - pub period: ::__u16, - pub magnitude: ::__s16, - pub offset: ::__s16, - pub phase: ::__u16, - - pub envelope: ff_envelope, - - pub custom_len: ::__u32, - pub custom_data: *mut ::__s16, - } - - pub struct ff_rumble_effect { - pub strong_magnitude: ::__u16, - pub weak_magnitude: ::__u16, - } - - pub struct ff_effect { - pub type_: ::__u16, - pub id: ::__s16, - pub direction: ::__u16, - pub trigger: ff_trigger, - pub replay: ff_replay, - // FIXME this is actually a union - #[cfg(target_pointer_width = "64")] - pub u: [u64; 4], - #[cfg(target_pointer_width = "32")] - pub u: [u32; 7], - } - - pub struct dl_phdr_info { - #[cfg(target_pointer_width = "64")] - pub dlpi_addr: Elf64_Addr, - #[cfg(target_pointer_width = "32")] - pub dlpi_addr: Elf32_Addr, - - pub dlpi_name: *const ::c_char, - - #[cfg(target_pointer_width = "64")] - pub dlpi_phdr: *const Elf64_Phdr, - #[cfg(target_pointer_width = "32")] - pub dlpi_phdr: *const Elf32_Phdr, - - #[cfg(target_pointer_width = "64")] - pub dlpi_phnum: Elf64_Half, - #[cfg(target_pointer_width = "32")] - pub dlpi_phnum: Elf32_Half, - - pub dlpi_adds: ::c_ulonglong, - pub dlpi_subs: ::c_ulonglong, - pub dlpi_tls_modid: ::size_t, - pub dlpi_tls_data: *mut ::c_void, - } - - pub struct Elf32_Phdr { - pub p_type: Elf32_Word, - pub p_offset: Elf32_Off, - pub p_vaddr: Elf32_Addr, - pub p_paddr: Elf32_Addr, - pub p_filesz: Elf32_Word, - pub p_memsz: Elf32_Word, - pub p_flags: Elf32_Word, - pub p_align: Elf32_Word, - } - - pub struct Elf64_Phdr { - pub p_type: Elf64_Word, - pub p_flags: Elf64_Word, - pub p_offset: Elf64_Off, - pub p_vaddr: Elf64_Addr, - pub p_paddr: Elf64_Addr, - pub p_filesz: Elf64_Xword, - pub p_memsz: Elf64_Xword, - pub p_align: Elf64_Xword, - } - - pub struct ucred { - pub pid: ::pid_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - } - - pub struct mntent { - pub mnt_fsname: *mut ::c_char, - pub mnt_dir: *mut ::c_char, - pub mnt_type: *mut ::c_char, - pub mnt_opts: *mut ::c_char, - pub mnt_freq: ::c_int, - pub mnt_passno: ::c_int, - } -} - -pub const ABDAY_1: ::nl_item = 0x20000; -pub const ABDAY_2: ::nl_item = 0x20001; -pub const ABDAY_3: ::nl_item = 0x20002; -pub const ABDAY_4: ::nl_item = 0x20003; -pub const ABDAY_5: ::nl_item = 0x20004; -pub const ABDAY_6: ::nl_item = 0x20005; -pub const ABDAY_7: ::nl_item = 0x20006; - -pub const DAY_1: ::nl_item = 0x20007; -pub const DAY_2: ::nl_item = 0x20008; -pub const DAY_3: ::nl_item = 0x20009; -pub const DAY_4: ::nl_item = 0x2000A; -pub const DAY_5: ::nl_item = 0x2000B; -pub const DAY_6: ::nl_item = 0x2000C; -pub const DAY_7: ::nl_item = 0x2000D; - -pub const ABMON_1: ::nl_item = 0x2000E; -pub const ABMON_2: ::nl_item = 0x2000F; -pub const ABMON_3: ::nl_item = 0x20010; -pub const ABMON_4: ::nl_item = 0x20011; -pub const ABMON_5: ::nl_item = 0x20012; -pub const ABMON_6: ::nl_item = 0x20013; -pub const ABMON_7: ::nl_item = 0x20014; -pub const ABMON_8: ::nl_item = 0x20015; -pub const ABMON_9: ::nl_item = 0x20016; -pub const ABMON_10: ::nl_item = 0x20017; -pub const ABMON_11: ::nl_item = 0x20018; -pub const ABMON_12: ::nl_item = 0x20019; - -pub const MON_1: ::nl_item = 0x2001A; -pub const MON_2: ::nl_item = 0x2001B; -pub const MON_3: ::nl_item = 0x2001C; -pub const MON_4: ::nl_item = 0x2001D; -pub const MON_5: ::nl_item = 0x2001E; -pub const MON_6: ::nl_item = 0x2001F; -pub const MON_7: ::nl_item = 0x20020; -pub const MON_8: ::nl_item = 0x20021; -pub const MON_9: ::nl_item = 0x20022; -pub const MON_10: ::nl_item = 0x20023; -pub const MON_11: ::nl_item = 0x20024; -pub const MON_12: ::nl_item = 0x20025; - -pub const AM_STR: ::nl_item = 0x20026; -pub const PM_STR: ::nl_item = 0x20027; - -pub const D_T_FMT: ::nl_item = 0x20028; -pub const D_FMT: ::nl_item = 0x20029; -pub const T_FMT: ::nl_item = 0x2002A; -pub const T_FMT_AMPM: ::nl_item = 0x2002B; - -pub const ERA: ::nl_item = 0x2002C; -pub const ERA_D_FMT: ::nl_item = 0x2002E; -pub const ALT_DIGITS: ::nl_item = 0x2002F; -pub const ERA_D_T_FMT: ::nl_item = 0x20030; -pub const ERA_T_FMT: ::nl_item = 0x20031; - -pub const CODESET: ::nl_item = 14; - -pub const CRNCYSTR: ::nl_item = 0x4000F; - -pub const RUSAGE_THREAD: ::c_int = 1; -pub const RUSAGE_CHILDREN: ::c_int = -1; - -pub const RADIXCHAR: ::nl_item = 0x10000; -pub const THOUSEP: ::nl_item = 0x10001; - -pub const YESEXPR: ::nl_item = 0x50000; -pub const NOEXPR: ::nl_item = 0x50001; -pub const YESSTR: ::nl_item = 0x50002; -pub const NOSTR: ::nl_item = 0x50003; - -pub const FILENAME_MAX: ::c_uint = 4096; -pub const L_tmpnam: ::c_uint = 20; -pub const _PC_LINK_MAX: ::c_int = 0; -pub const _PC_MAX_CANON: ::c_int = 1; -pub const _PC_MAX_INPUT: ::c_int = 2; -pub const _PC_NAME_MAX: ::c_int = 3; -pub const _PC_PATH_MAX: ::c_int = 4; -pub const _PC_PIPE_BUF: ::c_int = 5; -pub const _PC_CHOWN_RESTRICTED: ::c_int = 6; -pub const _PC_NO_TRUNC: ::c_int = 7; -pub const _PC_VDISABLE: ::c_int = 8; -pub const _PC_SYNC_IO: ::c_int = 9; -pub const _PC_ASYNC_IO: ::c_int = 10; -pub const _PC_PRIO_IO: ::c_int = 11; -pub const _PC_SOCK_MAXBUF: ::c_int = 12; -pub const _PC_FILESIZEBITS: ::c_int = 13; -pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 14; -pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 15; -pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 16; -pub const _PC_REC_XFER_ALIGN: ::c_int = 17; -pub const _PC_ALLOC_SIZE_MIN: ::c_int = 18; -pub const _PC_SYMLINK_MAX: ::c_int = 19; -pub const _PC_2_SYMLINKS: ::c_int = 20; - -pub const _SC_ARG_MAX: ::c_int = 0; -pub const _SC_CHILD_MAX: ::c_int = 1; -pub const _SC_CLK_TCK: ::c_int = 2; -pub const _SC_NGROUPS_MAX: ::c_int = 3; -pub const _SC_OPEN_MAX: ::c_int = 4; -pub const _SC_STREAM_MAX: ::c_int = 5; -pub const _SC_TZNAME_MAX: ::c_int = 6; -pub const _SC_JOB_CONTROL: ::c_int = 7; -pub const _SC_SAVED_IDS: ::c_int = 8; -pub const _SC_REALTIME_SIGNALS: ::c_int = 9; -pub const _SC_PRIORITY_SCHEDULING: ::c_int = 10; -pub const _SC_TIMERS: ::c_int = 11; -pub const _SC_ASYNCHRONOUS_IO: ::c_int = 12; -pub const _SC_PRIORITIZED_IO: ::c_int = 13; -pub const _SC_SYNCHRONIZED_IO: ::c_int = 14; -pub const _SC_FSYNC: ::c_int = 15; -pub const _SC_MAPPED_FILES: ::c_int = 16; -pub const _SC_MEMLOCK: ::c_int = 17; -pub const _SC_MEMLOCK_RANGE: ::c_int = 18; -pub const _SC_MEMORY_PROTECTION: ::c_int = 19; -pub const _SC_MESSAGE_PASSING: ::c_int = 20; -pub const _SC_SEMAPHORES: ::c_int = 21; -pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 22; -pub const _SC_AIO_LISTIO_MAX: ::c_int = 23; -pub const _SC_AIO_MAX: ::c_int = 24; -pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 25; -pub const _SC_DELAYTIMER_MAX: ::c_int = 26; -pub const _SC_MQ_OPEN_MAX: ::c_int = 27; -pub const _SC_MQ_PRIO_MAX: ::c_int = 28; -pub const _SC_VERSION: ::c_int = 29; -pub const _SC_PAGESIZE: ::c_int = 30; -pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; -pub const _SC_RTSIG_MAX: ::c_int = 31; -pub const _SC_SEM_NSEMS_MAX: ::c_int = 32; -pub const _SC_SEM_VALUE_MAX: ::c_int = 33; -pub const _SC_SIGQUEUE_MAX: ::c_int = 34; -pub const _SC_TIMER_MAX: ::c_int = 35; -pub const _SC_BC_BASE_MAX: ::c_int = 36; -pub const _SC_BC_DIM_MAX: ::c_int = 37; -pub const _SC_BC_SCALE_MAX: ::c_int = 38; -pub const _SC_BC_STRING_MAX: ::c_int = 39; -pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 40; -pub const _SC_EXPR_NEST_MAX: ::c_int = 42; -pub const _SC_LINE_MAX: ::c_int = 43; -pub const _SC_RE_DUP_MAX: ::c_int = 44; -pub const _SC_2_VERSION: ::c_int = 46; -pub const _SC_2_C_BIND: ::c_int = 47; -pub const _SC_2_C_DEV: ::c_int = 48; -pub const _SC_2_FORT_DEV: ::c_int = 49; -pub const _SC_2_FORT_RUN: ::c_int = 50; -pub const _SC_2_SW_DEV: ::c_int = 51; -pub const _SC_2_LOCALEDEF: ::c_int = 52; -pub const _SC_UIO_MAXIOV: ::c_int = 60; -pub const _SC_IOV_MAX: ::c_int = 60; -pub const _SC_THREADS: ::c_int = 67; -pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 68; -pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 69; -pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 70; -pub const _SC_LOGIN_NAME_MAX: ::c_int = 71; -pub const _SC_TTY_NAME_MAX: ::c_int = 72; -pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 73; -pub const _SC_THREAD_KEYS_MAX: ::c_int = 74; -pub const _SC_THREAD_STACK_MIN: ::c_int = 75; -pub const _SC_THREAD_THREADS_MAX: ::c_int = 76; -pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 77; -pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 78; -pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 79; -pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 80; -pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 81; -pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 82; -pub const _SC_NPROCESSORS_CONF: ::c_int = 83; -pub const _SC_NPROCESSORS_ONLN: ::c_int = 84; -pub const _SC_PHYS_PAGES: ::c_int = 85; -pub const _SC_AVPHYS_PAGES: ::c_int = 86; -pub const _SC_ATEXIT_MAX: ::c_int = 87; -pub const _SC_PASS_MAX: ::c_int = 88; -pub const _SC_XOPEN_VERSION: ::c_int = 89; -pub const _SC_XOPEN_XCU_VERSION: ::c_int = 90; -pub const _SC_XOPEN_UNIX: ::c_int = 91; -pub const _SC_XOPEN_CRYPT: ::c_int = 92; -pub const _SC_XOPEN_ENH_I18N: ::c_int = 93; -pub const _SC_XOPEN_SHM: ::c_int = 94; -pub const _SC_2_CHAR_TERM: ::c_int = 95; -pub const _SC_2_UPE: ::c_int = 97; -pub const _SC_XOPEN_XPG2: ::c_int = 98; -pub const _SC_XOPEN_XPG3: ::c_int = 99; -pub const _SC_XOPEN_XPG4: ::c_int = 100; -pub const _SC_NZERO: ::c_int = 109; -pub const _SC_XBS5_ILP32_OFF32: ::c_int = 125; -pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 126; -pub const _SC_XBS5_LP64_OFF64: ::c_int = 127; -pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 128; -pub const _SC_XOPEN_LEGACY: ::c_int = 129; -pub const _SC_XOPEN_REALTIME: ::c_int = 130; -pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 131; -pub const _SC_ADVISORY_INFO: ::c_int = 132; -pub const _SC_BARRIERS: ::c_int = 133; -pub const _SC_CLOCK_SELECTION: ::c_int = 137; -pub const _SC_CPUTIME: ::c_int = 138; -pub const _SC_THREAD_CPUTIME: ::c_int = 139; -pub const _SC_MONOTONIC_CLOCK: ::c_int = 149; -pub const _SC_READER_WRITER_LOCKS: ::c_int = 153; -pub const _SC_SPIN_LOCKS: ::c_int = 154; -pub const _SC_REGEXP: ::c_int = 155; -pub const _SC_SHELL: ::c_int = 157; -pub const _SC_SPAWN: ::c_int = 159; -pub const _SC_SPORADIC_SERVER: ::c_int = 160; -pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 161; -pub const _SC_TIMEOUTS: ::c_int = 164; -pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 165; -pub const _SC_2_PBS: ::c_int = 168; -pub const _SC_2_PBS_ACCOUNTING: ::c_int = 169; -pub const _SC_2_PBS_LOCATE: ::c_int = 170; -pub const _SC_2_PBS_MESSAGE: ::c_int = 171; -pub const _SC_2_PBS_TRACK: ::c_int = 172; -pub const _SC_SYMLOOP_MAX: ::c_int = 173; -pub const _SC_STREAMS: ::c_int = 174; -pub const _SC_2_PBS_CHECKPOINT: ::c_int = 175; -pub const _SC_V6_ILP32_OFF32: ::c_int = 176; -pub const _SC_V6_ILP32_OFFBIG: ::c_int = 177; -pub const _SC_V6_LP64_OFF64: ::c_int = 178; -pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 179; -pub const _SC_HOST_NAME_MAX: ::c_int = 180; -pub const _SC_TRACE: ::c_int = 181; -pub const _SC_TRACE_EVENT_FILTER: ::c_int = 182; -pub const _SC_TRACE_INHERIT: ::c_int = 183; -pub const _SC_TRACE_LOG: ::c_int = 184; -pub const _SC_IPV6: ::c_int = 235; -pub const _SC_RAW_SOCKETS: ::c_int = 236; -pub const _SC_V7_ILP32_OFF32: ::c_int = 237; -pub const _SC_V7_ILP32_OFFBIG: ::c_int = 238; -pub const _SC_V7_LP64_OFF64: ::c_int = 239; -pub const _SC_V7_LPBIG_OFFBIG: ::c_int = 240; -pub const _SC_SS_REPL_MAX: ::c_int = 241; -pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 242; -pub const _SC_TRACE_NAME_MAX: ::c_int = 243; -pub const _SC_TRACE_SYS_MAX: ::c_int = 244; -pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 245; -pub const _SC_XOPEN_STREAMS: ::c_int = 246; -pub const _SC_THREAD_ROBUST_PRIO_INHERIT: ::c_int = 247; -pub const _SC_THREAD_ROBUST_PRIO_PROTECT: ::c_int = 248; - -pub const RLIM_SAVED_MAX: ::rlim_t = RLIM_INFINITY; -pub const RLIM_SAVED_CUR: ::rlim_t = RLIM_INFINITY; - -pub const GLOB_ERR: ::c_int = 1 << 0; -pub const GLOB_MARK: ::c_int = 1 << 1; -pub const GLOB_NOSORT: ::c_int = 1 << 2; -pub const GLOB_DOOFFS: ::c_int = 1 << 3; -pub const GLOB_NOCHECK: ::c_int = 1 << 4; -pub const GLOB_APPEND: ::c_int = 1 << 5; -pub const GLOB_NOESCAPE: ::c_int = 1 << 6; - -pub const GLOB_NOSPACE: ::c_int = 1; -pub const GLOB_ABORTED: ::c_int = 2; -pub const GLOB_NOMATCH: ::c_int = 3; - -pub const POSIX_MADV_NORMAL: ::c_int = 0; -pub const POSIX_MADV_RANDOM: ::c_int = 1; -pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; -pub const POSIX_MADV_WILLNEED: ::c_int = 3; - -pub const S_IEXEC: mode_t = 64; -pub const S_IWRITE: mode_t = 128; -pub const S_IREAD: mode_t = 256; - -pub const F_LOCK: ::c_int = 1; -pub const F_TEST: ::c_int = 3; -pub const F_TLOCK: ::c_int = 2; -pub const F_ULOCK: ::c_int = 0; - -pub const IFF_LOWER_UP: ::c_int = 0x10000; -pub const IFF_DORMANT: ::c_int = 0x20000; -pub const IFF_ECHO: ::c_int = 0x40000; - -// linux/if_tun.h -// Read queue size -pub const TUN_READQ_SIZE: ::c_short = 500; -// TUN device type flags: deprecated. Use IFF_TUN/IFF_TAP instead. -pub const TUN_TUN_DEV: ::c_short = IFF_TUN; -pub const TUN_TAP_DEV: ::c_short = IFF_TAP; -pub const TUN_TYPE_MASK: ::c_short = 0x000f; -// TUNSETIFF ifr flags -pub const IFF_TUN: ::c_short = 0x0001; -pub const IFF_TAP: ::c_short = 0x0002; -pub const IFF_NO_PI: ::c_short = 0x1000; -// This flag has no real effect -pub const IFF_ONE_QUEUE: ::c_short = 0x2000; -pub const IFF_VNET_HDR: ::c_short = 0x4000; -pub const IFF_TUN_EXCL: ::c_short = 0x8000; -pub const IFF_MULTI_QUEUE: ::c_short = 0x0100; -pub const IFF_ATTACH_QUEUE: ::c_short = 0x0200; -pub const IFF_DETACH_QUEUE: ::c_short = 0x0400; -// read-only flag -pub const IFF_PERSIST: ::c_short = 0x0800; -pub const IFF_NOFILTER: ::c_short = 0x1000; - -pub const ST_RDONLY: ::c_ulong = 1; -pub const ST_NOSUID: ::c_ulong = 2; -pub const ST_NODEV: ::c_ulong = 4; -pub const ST_NOEXEC: ::c_ulong = 8; -pub const ST_SYNCHRONOUS: ::c_ulong = 16; -pub const ST_MANDLOCK: ::c_ulong = 64; -pub const ST_WRITE: ::c_ulong = 128; -pub const ST_APPEND: ::c_ulong = 256; -pub const ST_IMMUTABLE: ::c_ulong = 512; -pub const ST_NOATIME: ::c_ulong = 1024; -pub const ST_NODIRATIME: ::c_ulong = 2048; - -pub const RTLD_NEXT: *mut ::c_void = -1i64 as *mut ::c_void; -pub const RTLD_DEFAULT: *mut ::c_void = 0i64 as *mut ::c_void; -pub const RTLD_NODELETE: ::c_int = 0x1000; -pub const RTLD_NOW: ::c_int = 0x2; - -pub const TCP_MD5SIG: ::c_int = 14; - -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_MUTEX_T], -}; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_COND_T], -}; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_RWLOCK_T], -}; -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; -pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; -pub const PTHREAD_PROCESS_PRIVATE: ::c_int = 0; -pub const PTHREAD_PROCESS_SHARED: ::c_int = 1; -pub const __SIZEOF_PTHREAD_COND_T: usize = 48; - -pub const RENAME_NOREPLACE: ::c_int = 1; -pub const RENAME_EXCHANGE: ::c_int = 2; -pub const RENAME_WHITEOUT: ::c_int = 4; - -pub const SCHED_OTHER: ::c_int = 0; -pub const SCHED_FIFO: ::c_int = 1; -pub const SCHED_RR: ::c_int = 2; -pub const SCHED_BATCH: ::c_int = 3; -pub const SCHED_IDLE: ::c_int = 5; - -// netinet/in.h -// NOTE: These are in addition to the constants defined in src/unix/mod.rs - -// IPPROTO_IP defined in src/unix/mod.rs -/// Hop-by-hop option header -pub const IPPROTO_HOPOPTS: ::c_int = 0; -// IPPROTO_ICMP defined in src/unix/mod.rs -/// group mgmt protocol -pub const IPPROTO_IGMP: ::c_int = 2; -/// for compatibility -pub const IPPROTO_IPIP: ::c_int = 4; -// IPPROTO_TCP defined in src/unix/mod.rs -/// exterior gateway protocol -pub const IPPROTO_EGP: ::c_int = 8; -/// pup -pub const IPPROTO_PUP: ::c_int = 12; -// IPPROTO_UDP defined in src/unix/mod.rs -/// xns idp -pub const IPPROTO_IDP: ::c_int = 22; -/// tp-4 w/ class negotiation -pub const IPPROTO_TP: ::c_int = 29; -/// DCCP -pub const IPPROTO_DCCP: ::c_int = 33; -// IPPROTO_IPV6 defined in src/unix/mod.rs -/// IP6 routing header -pub const IPPROTO_ROUTING: ::c_int = 43; -/// IP6 fragmentation header -pub const IPPROTO_FRAGMENT: ::c_int = 44; -/// resource reservation -pub const IPPROTO_RSVP: ::c_int = 46; -/// General Routing Encap. -pub const IPPROTO_GRE: ::c_int = 47; -/// IP6 Encap Sec. Payload -pub const IPPROTO_ESP: ::c_int = 50; -/// IP6 Auth Header -pub const IPPROTO_AH: ::c_int = 51; -// IPPROTO_ICMPV6 defined in src/unix/mod.rs -/// IP6 no next header -pub const IPPROTO_NONE: ::c_int = 59; -/// IP6 destination option -pub const IPPROTO_DSTOPTS: ::c_int = 60; -pub const IPPROTO_MTP: ::c_int = 92; -pub const IPPROTO_BEETPH: ::c_int = 94; -/// encapsulation header -pub const IPPROTO_ENCAP: ::c_int = 98; -/// Protocol indep. multicast -pub const IPPROTO_PIM: ::c_int = 103; -/// IP Payload Comp. Protocol -pub const IPPROTO_COMP: ::c_int = 108; -/// SCTP -pub const IPPROTO_SCTP: ::c_int = 132; -pub const IPPROTO_MH: ::c_int = 135; -pub const IPPROTO_UDPLITE: ::c_int = 136; -pub const IPPROTO_MPLS: ::c_int = 137; -/// raw IP packet -pub const IPPROTO_RAW: ::c_int = 255; -pub const IPPROTO_MAX: ::c_int = 256; - -pub const AF_IB: ::c_int = 27; -pub const AF_MPLS: ::c_int = 28; -pub const AF_NFC: ::c_int = 39; -pub const AF_VSOCK: ::c_int = 40; -pub const PF_IB: ::c_int = AF_IB; -pub const PF_MPLS: ::c_int = AF_MPLS; -pub const PF_NFC: ::c_int = AF_NFC; -pub const PF_VSOCK: ::c_int = AF_VSOCK; - -// System V IPC -pub const IPC_PRIVATE: ::key_t = 0; - -pub const IPC_CREAT: ::c_int = 0o1000; -pub const IPC_EXCL: ::c_int = 0o2000; -pub const IPC_NOWAIT: ::c_int = 0o4000; - -pub const IPC_RMID: ::c_int = 0; -pub const IPC_SET: ::c_int = 1; -pub const IPC_STAT: ::c_int = 2; -pub const IPC_INFO: ::c_int = 3; -pub const MSG_STAT: ::c_int = 11; -pub const MSG_INFO: ::c_int = 12; - -pub const MSG_NOERROR: ::c_int = 0o10000; -pub const MSG_EXCEPT: ::c_int = 0o20000; -pub const MSG_COPY: ::c_int = 0o40000; - -pub const SHM_R: ::c_int = 0o400; -pub const SHM_W: ::c_int = 0o200; - -pub const SHM_RDONLY: ::c_int = 0o10000; -pub const SHM_RND: ::c_int = 0o20000; -pub const SHM_REMAP: ::c_int = 0o40000; -pub const SHM_EXEC: ::c_int = 0o100000; - -pub const SHM_LOCK: ::c_int = 11; -pub const SHM_UNLOCK: ::c_int = 12; - -pub const SHM_HUGETLB: ::c_int = 0o4000; -pub const SHM_NORESERVE: ::c_int = 0o10000; - -pub const EPOLLRDHUP: ::c_int = 0x2000; -pub const EPOLLEXCLUSIVE: ::c_int = 0x10000000; -pub const EPOLLONESHOT: ::c_int = 0x40000000; - -pub const QFMT_VFS_OLD: ::c_int = 1; -pub const QFMT_VFS_V0: ::c_int = 2; -pub const QFMT_VFS_V1: ::c_int = 4; - -pub const EFD_SEMAPHORE: ::c_int = 0x1; - -pub const LOG_NFACILITIES: ::c_int = 24; - -pub const SEM_FAILED: *mut ::sem_t = 0 as *mut sem_t; - -pub const RB_AUTOBOOT: ::c_int = 0x01234567u32 as i32; -pub const RB_HALT_SYSTEM: ::c_int = 0xcdef0123u32 as i32; -pub const RB_ENABLE_CAD: ::c_int = 0x89abcdefu32 as i32; -pub const RB_DISABLE_CAD: ::c_int = 0x00000000u32 as i32; -pub const RB_POWER_OFF: ::c_int = 0x4321fedcu32 as i32; -pub const RB_SW_SUSPEND: ::c_int = 0xd000fce2u32 as i32; -pub const RB_KEXEC: ::c_int = 0x45584543u32 as i32; - -pub const AI_PASSIVE: ::c_int = 0x0001; -pub const AI_CANONNAME: ::c_int = 0x0002; -pub const AI_NUMERICHOST: ::c_int = 0x0004; -pub const AI_V4MAPPED: ::c_int = 0x0008; -pub const AI_ALL: ::c_int = 0x0010; -pub const AI_ADDRCONFIG: ::c_int = 0x0020; - -pub const AI_NUMERICSERV: ::c_int = 0x0400; - -pub const EAI_BADFLAGS: ::c_int = -1; -pub const EAI_NONAME: ::c_int = -2; -pub const EAI_AGAIN: ::c_int = -3; -pub const EAI_FAIL: ::c_int = -4; -pub const EAI_NODATA: ::c_int = -5; -pub const EAI_FAMILY: ::c_int = -6; -pub const EAI_SOCKTYPE: ::c_int = -7; -pub const EAI_SERVICE: ::c_int = -8; -pub const EAI_MEMORY: ::c_int = -10; -pub const EAI_SYSTEM: ::c_int = -11; -pub const EAI_OVERFLOW: ::c_int = -12; - -pub const NI_NUMERICHOST: ::c_int = 1; -pub const NI_NUMERICSERV: ::c_int = 2; -pub const NI_NOFQDN: ::c_int = 4; -pub const NI_NAMEREQD: ::c_int = 8; -pub const NI_DGRAM: ::c_int = 16; - -pub const SYNC_FILE_RANGE_WAIT_BEFORE: ::c_uint = 1; -pub const SYNC_FILE_RANGE_WRITE: ::c_uint = 2; -pub const SYNC_FILE_RANGE_WAIT_AFTER: ::c_uint = 4; - -pub const AIO_CANCELED: ::c_int = 0; -pub const AIO_NOTCANCELED: ::c_int = 1; -pub const AIO_ALLDONE: ::c_int = 2; -pub const LIO_READ: ::c_int = 0; -pub const LIO_WRITE: ::c_int = 1; -pub const LIO_NOP: ::c_int = 2; -pub const LIO_WAIT: ::c_int = 0; -pub const LIO_NOWAIT: ::c_int = 1; - -pub const MREMAP_MAYMOVE: ::c_int = 1; -pub const MREMAP_FIXED: ::c_int = 2; - -pub const PR_SET_PDEATHSIG: ::c_int = 1; -pub const PR_GET_PDEATHSIG: ::c_int = 2; - -pub const PR_GET_DUMPABLE: ::c_int = 3; -pub const PR_SET_DUMPABLE: ::c_int = 4; - -pub const PR_GET_UNALIGN: ::c_int = 5; -pub const PR_SET_UNALIGN: ::c_int = 6; -pub const PR_UNALIGN_NOPRINT: ::c_int = 1; -pub const PR_UNALIGN_SIGBUS: ::c_int = 2; - -pub const PR_GET_KEEPCAPS: ::c_int = 7; -pub const PR_SET_KEEPCAPS: ::c_int = 8; - -pub const PR_GET_FPEMU: ::c_int = 9; -pub const PR_SET_FPEMU: ::c_int = 10; -pub const PR_FPEMU_NOPRINT: ::c_int = 1; -pub const PR_FPEMU_SIGFPE: ::c_int = 2; - -pub const PR_GET_FPEXC: ::c_int = 11; -pub const PR_SET_FPEXC: ::c_int = 12; -pub const PR_FP_EXC_SW_ENABLE: ::c_int = 0x80; -pub const PR_FP_EXC_DIV: ::c_int = 0x010000; -pub const PR_FP_EXC_OVF: ::c_int = 0x020000; -pub const PR_FP_EXC_UND: ::c_int = 0x040000; -pub const PR_FP_EXC_RES: ::c_int = 0x080000; -pub const PR_FP_EXC_INV: ::c_int = 0x100000; -pub const PR_FP_EXC_DISABLED: ::c_int = 0; -pub const PR_FP_EXC_NONRECOV: ::c_int = 1; -pub const PR_FP_EXC_ASYNC: ::c_int = 2; -pub const PR_FP_EXC_PRECISE: ::c_int = 3; - -pub const PR_GET_TIMING: ::c_int = 13; -pub const PR_SET_TIMING: ::c_int = 14; -pub const PR_TIMING_STATISTICAL: ::c_int = 0; -pub const PR_TIMING_TIMESTAMP: ::c_int = 1; - -pub const PR_SET_NAME: ::c_int = 15; -pub const PR_GET_NAME: ::c_int = 16; - -pub const PR_GET_ENDIAN: ::c_int = 19; -pub const PR_SET_ENDIAN: ::c_int = 20; -pub const PR_ENDIAN_BIG: ::c_int = 0; -pub const PR_ENDIAN_LITTLE: ::c_int = 1; -pub const PR_ENDIAN_PPC_LITTLE: ::c_int = 2; - -pub const PR_GET_SECCOMP: ::c_int = 21; -pub const PR_SET_SECCOMP: ::c_int = 22; - -pub const PR_CAPBSET_READ: ::c_int = 23; -pub const PR_CAPBSET_DROP: ::c_int = 24; - -pub const PR_GET_TSC: ::c_int = 25; -pub const PR_SET_TSC: ::c_int = 26; -pub const PR_TSC_ENABLE: ::c_int = 1; -pub const PR_TSC_SIGSEGV: ::c_int = 2; - -pub const PR_GET_SECUREBITS: ::c_int = 27; -pub const PR_SET_SECUREBITS: ::c_int = 28; - -pub const PR_SET_TIMERSLACK: ::c_int = 29; -pub const PR_GET_TIMERSLACK: ::c_int = 30; - -pub const PR_TASK_PERF_EVENTS_DISABLE: ::c_int = 31; -pub const PR_TASK_PERF_EVENTS_ENABLE: ::c_int = 32; - -pub const PR_MCE_KILL: ::c_int = 33; -pub const PR_MCE_KILL_CLEAR: ::c_int = 0; -pub const PR_MCE_KILL_SET: ::c_int = 1; - -pub const PR_MCE_KILL_LATE: ::c_int = 0; -pub const PR_MCE_KILL_EARLY: ::c_int = 1; -pub const PR_MCE_KILL_DEFAULT: ::c_int = 2; - -pub const PR_MCE_KILL_GET: ::c_int = 34; - -pub const PR_SET_MM: ::c_int = 35; -pub const PR_SET_MM_START_CODE: ::c_int = 1; -pub const PR_SET_MM_END_CODE: ::c_int = 2; -pub const PR_SET_MM_START_DATA: ::c_int = 3; -pub const PR_SET_MM_END_DATA: ::c_int = 4; -pub const PR_SET_MM_START_STACK: ::c_int = 5; -pub const PR_SET_MM_START_BRK: ::c_int = 6; -pub const PR_SET_MM_BRK: ::c_int = 7; -pub const PR_SET_MM_ARG_START: ::c_int = 8; -pub const PR_SET_MM_ARG_END: ::c_int = 9; -pub const PR_SET_MM_ENV_START: ::c_int = 10; -pub const PR_SET_MM_ENV_END: ::c_int = 11; -pub const PR_SET_MM_AUXV: ::c_int = 12; -pub const PR_SET_MM_EXE_FILE: ::c_int = 13; -pub const PR_SET_MM_MAP: ::c_int = 14; -pub const PR_SET_MM_MAP_SIZE: ::c_int = 15; - -pub const PR_SET_PTRACER: ::c_int = 0x59616d61; - -pub const PR_SET_CHILD_SUBREAPER: ::c_int = 36; -pub const PR_GET_CHILD_SUBREAPER: ::c_int = 37; - -pub const PR_SET_NO_NEW_PRIVS: ::c_int = 38; -pub const PR_GET_NO_NEW_PRIVS: ::c_int = 39; - -pub const PR_GET_TID_ADDRESS: ::c_int = 40; - -pub const PR_SET_THP_DISABLE: ::c_int = 41; -pub const PR_GET_THP_DISABLE: ::c_int = 42; - -pub const PR_MPX_ENABLE_MANAGEMENT: ::c_int = 43; -pub const PR_MPX_DISABLE_MANAGEMENT: ::c_int = 44; - -pub const PR_SET_FP_MODE: ::c_int = 45; -pub const PR_GET_FP_MODE: ::c_int = 46; -pub const PR_FP_MODE_FR: ::c_int = 1 << 0; -pub const PR_FP_MODE_FRE: ::c_int = 1 << 1; - -pub const PR_CAP_AMBIENT: ::c_int = 47; -pub const PR_CAP_AMBIENT_IS_SET: ::c_int = 1; -pub const PR_CAP_AMBIENT_RAISE: ::c_int = 2; -pub const PR_CAP_AMBIENT_LOWER: ::c_int = 3; -pub const PR_CAP_AMBIENT_CLEAR_ALL: ::c_int = 4; - -pub const GRND_NONBLOCK: ::c_uint = 0x0001; -pub const GRND_RANDOM: ::c_uint = 0x0002; - -pub const SECCOMP_MODE_DISABLED: ::c_uint = 0; -pub const SECCOMP_MODE_STRICT: ::c_uint = 1; -pub const SECCOMP_MODE_FILTER: ::c_uint = 2; - -pub const ITIMER_REAL: ::c_int = 0; -pub const ITIMER_VIRTUAL: ::c_int = 1; -pub const ITIMER_PROF: ::c_int = 2; - -pub const TFD_CLOEXEC: ::c_int = O_CLOEXEC; -pub const TFD_NONBLOCK: ::c_int = O_NONBLOCK; -pub const TFD_TIMER_ABSTIME: ::c_int = 1; - -pub const XATTR_CREATE: ::c_int = 0x1; -pub const XATTR_REPLACE: ::c_int = 0x2; - -pub const _POSIX_VDISABLE: ::cc_t = 0; - -pub const FALLOC_FL_KEEP_SIZE: ::c_int = 0x01; -pub const FALLOC_FL_PUNCH_HOLE: ::c_int = 0x02; -pub const FALLOC_FL_COLLAPSE_RANGE: ::c_int = 0x08; -pub const FALLOC_FL_ZERO_RANGE: ::c_int = 0x10; -pub const FALLOC_FL_INSERT_RANGE: ::c_int = 0x20; -pub const FALLOC_FL_UNSHARE_RANGE: ::c_int = 0x40; - -// On Linux, libc doesn't define this constant, libattr does instead. -// We still define it for Linux as it's defined by libc on other platforms, -// and it's mentioned in the man pages for getxattr and setxattr. -pub const ENOATTR: ::c_int = ::ENODATA; - -pub const SO_ORIGINAL_DST: ::c_int = 80; -pub const IUTF8: ::tcflag_t = 0x00004000; -pub const CMSPAR: ::tcflag_t = 0o10000000000; - -pub const MFD_CLOEXEC: ::c_uint = 0x0001; -pub const MFD_ALLOW_SEALING: ::c_uint = 0x0002; - -// these are used in the p_type field of Elf32_Phdr and Elf64_Phdr, which has -// the type Elf32Word and Elf64Word respectively. Luckily, both of those are u32 -// so we can use that type here to avoid having to cast. -pub const PT_NULL: u32 = 0; -pub const PT_LOAD: u32 = 1; -pub const PT_DYNAMIC: u32 = 2; -pub const PT_INTERP: u32 = 3; -pub const PT_NOTE: u32 = 4; -pub const PT_SHLIB: u32 = 5; -pub const PT_PHDR: u32 = 6; -pub const PT_TLS: u32 = 7; -pub const PT_NUM: u32 = 8; -pub const PT_LOOS: u32 = 0x60000000; -pub const PT_GNU_EH_FRAME: u32 = 0x6474e550; -pub const PT_GNU_STACK: u32 = 0x6474e551; -pub const PT_GNU_RELRO: u32 = 0x6474e552; - -// linux/if_ether.h -pub const ETH_ALEN: ::c_int = 6; -pub const ETH_HLEN: ::c_int = 14; -pub const ETH_ZLEN: ::c_int = 60; -pub const ETH_DATA_LEN: ::c_int = 1500; -pub const ETH_FRAME_LEN: ::c_int = 1514; -pub const ETH_FCS_LEN: ::c_int = 4; - -// These are the defined Ethernet Protocol ID's. -pub const ETH_P_LOOP: ::c_int = 0x0060; -pub const ETH_P_PUP: ::c_int = 0x0200; -pub const ETH_P_PUPAT: ::c_int = 0x0201; -pub const ETH_P_IP: ::c_int = 0x0800; -pub const ETH_P_X25: ::c_int = 0x0805; -pub const ETH_P_ARP: ::c_int = 0x0806; -pub const ETH_P_BPQ: ::c_int = 0x08FF; -pub const ETH_P_IEEEPUP: ::c_int = 0x0a00; -pub const ETH_P_IEEEPUPAT: ::c_int = 0x0a01; -pub const ETH_P_BATMAN: ::c_int = 0x4305; -pub const ETH_P_DEC: ::c_int = 0x6000; -pub const ETH_P_DNA_DL: ::c_int = 0x6001; -pub const ETH_P_DNA_RC: ::c_int = 0x6002; -pub const ETH_P_DNA_RT: ::c_int = 0x6003; -pub const ETH_P_LAT: ::c_int = 0x6004; -pub const ETH_P_DIAG: ::c_int = 0x6005; -pub const ETH_P_CUST: ::c_int = 0x6006; -pub const ETH_P_SCA: ::c_int = 0x6007; -pub const ETH_P_TEB: ::c_int = 0x6558; -pub const ETH_P_RARP: ::c_int = 0x8035; -pub const ETH_P_ATALK: ::c_int = 0x809B; -pub const ETH_P_AARP: ::c_int = 0x80F3; -pub const ETH_P_8021Q: ::c_int = 0x8100; -pub const ETH_P_IPX: ::c_int = 0x8137; -pub const ETH_P_IPV6: ::c_int = 0x86DD; -pub const ETH_P_PAUSE: ::c_int = 0x8808; -pub const ETH_P_SLOW: ::c_int = 0x8809; -pub const ETH_P_WCCP: ::c_int = 0x883E; -pub const ETH_P_MPLS_UC: ::c_int = 0x8847; -pub const ETH_P_MPLS_MC: ::c_int = 0x8848; -pub const ETH_P_ATMMPOA: ::c_int = 0x884c; -pub const ETH_P_PPP_DISC: ::c_int = 0x8863; -pub const ETH_P_PPP_SES: ::c_int = 0x8864; -pub const ETH_P_LINK_CTL: ::c_int = 0x886c; -pub const ETH_P_ATMFATE: ::c_int = 0x8884; -pub const ETH_P_PAE: ::c_int = 0x888E; -pub const ETH_P_AOE: ::c_int = 0x88A2; -pub const ETH_P_8021AD: ::c_int = 0x88A8; -pub const ETH_P_802_EX1: ::c_int = 0x88B5; -pub const ETH_P_TIPC: ::c_int = 0x88CA; -pub const ETH_P_MACSEC: ::c_int = 0x88E5; -pub const ETH_P_8021AH: ::c_int = 0x88E7; -pub const ETH_P_MVRP: ::c_int = 0x88F5; -pub const ETH_P_1588: ::c_int = 0x88F7; -pub const ETH_P_PRP: ::c_int = 0x88FB; -pub const ETH_P_FCOE: ::c_int = 0x8906; -pub const ETH_P_TDLS: ::c_int = 0x890D; -pub const ETH_P_FIP: ::c_int = 0x8914; -pub const ETH_P_80221: ::c_int = 0x8917; -pub const ETH_P_LOOPBACK: ::c_int = 0x9000; -pub const ETH_P_QINQ1: ::c_int = 0x9100; -pub const ETH_P_QINQ2: ::c_int = 0x9200; -pub const ETH_P_QINQ3: ::c_int = 0x9300; -pub const ETH_P_EDSA: ::c_int = 0xDADA; -pub const ETH_P_AF_IUCV: ::c_int = 0xFBFB; - -pub const ETH_P_802_3_MIN: ::c_int = 0x0600; - -// Non DIX types. Won't clash for 1500 types. -pub const ETH_P_802_3: ::c_int = 0x0001; -pub const ETH_P_AX25: ::c_int = 0x0002; -pub const ETH_P_ALL: ::c_int = 0x0003; -pub const ETH_P_802_2: ::c_int = 0x0004; -pub const ETH_P_SNAP: ::c_int = 0x0005; -pub const ETH_P_DDCMP: ::c_int = 0x0006; -pub const ETH_P_WAN_PPP: ::c_int = 0x0007; -pub const ETH_P_PPP_MP: ::c_int = 0x0008; -pub const ETH_P_LOCALTALK: ::c_int = 0x0009; -pub const ETH_P_CANFD: ::c_int = 0x000D; -pub const ETH_P_PPPTALK: ::c_int = 0x0010; -pub const ETH_P_TR_802_2: ::c_int = 0x0011; -pub const ETH_P_MOBITEX: ::c_int = 0x0015; -pub const ETH_P_CONTROL: ::c_int = 0x0016; -pub const ETH_P_IRDA: ::c_int = 0x0017; -pub const ETH_P_ECONET: ::c_int = 0x0018; -pub const ETH_P_HDLC: ::c_int = 0x0019; -pub const ETH_P_ARCNET: ::c_int = 0x001A; -pub const ETH_P_DSA: ::c_int = 0x001B; -pub const ETH_P_TRAILER: ::c_int = 0x001C; -pub const ETH_P_PHONET: ::c_int = 0x00F5; -pub const ETH_P_IEEE802154: ::c_int = 0x00F6; -pub const ETH_P_CAIF: ::c_int = 0x00F7; - -f! { - pub fn CPU_ZERO(cpuset: &mut cpu_set_t) -> () { - for slot in cpuset.bits.iter_mut() { - *slot = 0; - } - } - - pub fn CPU_SET(cpu: usize, cpuset: &mut cpu_set_t) -> () { - let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc - let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); - cpuset.bits[idx] |= 1 << offset; - () - } - - pub fn CPU_CLR(cpu: usize, cpuset: &mut cpu_set_t) -> () { - let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc - let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); - cpuset.bits[idx] &= !(1 << offset); - () - } - - pub fn CPU_ISSET(cpu: usize, cpuset: &cpu_set_t) -> bool { - let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); - let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); - 0 != (cpuset.bits[idx] & (1 << offset)) - } - - pub fn CPU_EQUAL(set1: &cpu_set_t, set2: &cpu_set_t) -> bool { - set1.bits == set2.bits - } - - pub fn major(dev: ::dev_t) -> ::c_uint { - let mut major = 0; - major |= (dev & 0x00000000000fff00) >> 8; - major |= (dev & 0xfffff00000000000) >> 32; - major as ::c_uint - } - - pub fn minor(dev: ::dev_t) -> ::c_uint { - let mut minor = 0; - minor |= (dev & 0x00000000000000ff) >> 0; - minor |= (dev & 0x00000ffffff00000) >> 12; - minor as ::c_uint - } - - pub fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { - let major = major as ::dev_t; - let minor = minor as ::dev_t; - let mut dev = 0; - dev |= (major & 0x00000fff) << 8; - dev |= (major & 0xfffff000) << 32; - dev |= (minor & 0x000000ff) << 0; - dev |= (minor & 0xffffff00) << 12; - dev - } -} - -extern { - pub fn aio_read(aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_write(aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_fsync(op: ::c_int, aiocbp: *mut aiocb) -> ::c_int; - pub fn aio_error(aiocbp: *const aiocb) -> ::c_int; - pub fn aio_return(aiocbp: *mut aiocb) -> ::ssize_t; - pub fn aio_suspend(aiocb_list: *const *const aiocb, nitems: ::c_int, - timeout: *const ::timespec) -> ::c_int; - pub fn aio_cancel(fd: ::c_int, aiocbp: *mut aiocb) -> ::c_int; - pub fn lio_listio(mode: ::c_int, aiocb_list: *const *mut aiocb, - nitems: ::c_int, sevp: *mut ::sigevent) -> ::c_int; - - pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; - - pub fn setpwent(); - pub fn endpwent(); - pub fn getpwent() -> *mut passwd; - pub fn setspent(); - pub fn endspent(); - pub fn getspent() -> *mut spwd; - pub fn getspnam(__name: *const ::c_char) -> *mut spwd; - - pub fn shm_open(name: *const c_char, oflag: ::c_int, - mode: mode_t) -> ::c_int; - - // System V IPC - pub fn shmget(key: ::key_t, size: ::size_t, shmflg: ::c_int) -> ::c_int; - pub fn shmat(shmid: ::c_int, - shmaddr: *const ::c_void, - shmflg: ::c_int) -> *mut ::c_void; - pub fn shmdt(shmaddr: *const ::c_void) -> ::c_int; - pub fn shmctl(shmid: ::c_int, - cmd: ::c_int, - buf: *mut ::shmid_ds) -> ::c_int; - pub fn ftok(pathname: *const ::c_char, proj_id: ::c_int) -> ::key_t; - pub fn semget(key: ::key_t, nsems: ::c_int, semflag: ::c_int) -> ::c_int; - pub fn semop(semid: ::c_int, - sops: *mut ::sembuf, nsops: ::size_t) -> ::c_int; - pub fn semctl(semid: ::c_int, - semnum: ::c_int, cmd: ::c_int, ...) -> ::c_int; - pub fn msgctl(msqid: ::c_int, cmd: ::c_int, buf: *mut msqid_ds) -> ::c_int; - pub fn msgget(key: ::key_t, msgflg: ::c_int) -> ::c_int; - pub fn msgrcv(msqid: ::c_int, msgp: *mut ::c_void, msgsz: ::size_t, - msgtyp: ::c_long, msgflg: ::c_int) -> ::ssize_t; - pub fn msgsnd(msqid: ::c_int, msgp: *const ::c_void, msgsz: ::size_t, - msgflg: ::c_int) -> ::c_int; - - pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) - -> ::c_int; - pub fn __errno_location() -> *mut ::c_int; - - pub fn fopen64(filename: *const c_char, - mode: *const c_char) -> *mut ::FILE; - pub fn freopen64(filename: *const c_char, mode: *const c_char, - file: *mut ::FILE) -> *mut ::FILE; - pub fn tmpfile64() -> *mut ::FILE; - pub fn fgetpos64(stream: *mut ::FILE, ptr: *mut fpos64_t) -> ::c_int; - pub fn fsetpos64(stream: *mut ::FILE, ptr: *const fpos64_t) -> ::c_int; - pub fn fseeko64(stream: *mut ::FILE, - offset: ::off64_t, - whence: ::c_int) -> ::c_int; - pub fn ftello64(stream: *mut ::FILE) -> ::off64_t; - pub fn fallocate(fd: ::c_int, mode: ::c_int, - offset: ::off_t, len: ::off_t) -> ::c_int; - pub fn posix_fallocate(fd: ::c_int, offset: ::off_t, - len: ::off_t) -> ::c_int; - pub fn readahead(fd: ::c_int, offset: ::off64_t, - count: ::size_t) -> ::ssize_t; - pub fn getxattr(path: *const c_char, name: *const c_char, - value: *mut ::c_void, size: ::size_t) -> ::ssize_t; - pub fn lgetxattr(path: *const c_char, name: *const c_char, - value: *mut ::c_void, size: ::size_t) -> ::ssize_t; - pub fn fgetxattr(filedes: ::c_int, name: *const c_char, - value: *mut ::c_void, size: ::size_t) -> ::ssize_t; - pub fn setxattr(path: *const c_char, name: *const c_char, - value: *const ::c_void, size: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn lsetxattr(path: *const c_char, name: *const c_char, - value: *const ::c_void, size: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn fsetxattr(filedes: ::c_int, name: *const c_char, - value: *const ::c_void, size: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn listxattr(path: *const c_char, list: *mut c_char, - size: ::size_t) -> ::ssize_t; - pub fn llistxattr(path: *const c_char, list: *mut c_char, - size: ::size_t) -> ::ssize_t; - pub fn flistxattr(filedes: ::c_int, list: *mut c_char, - size: ::size_t) -> ::ssize_t; - pub fn removexattr(path: *const c_char, name: *const c_char) -> ::c_int; - pub fn lremovexattr(path: *const c_char, name: *const c_char) -> ::c_int; - pub fn fremovexattr(filedes: ::c_int, name: *const c_char) -> ::c_int; - pub fn signalfd(fd: ::c_int, - mask: *const ::sigset_t, - flags: ::c_int) -> ::c_int; - pub fn timerfd_create(clockid: ::c_int, flags: ::c_int) -> ::c_int; - pub fn timerfd_gettime(fd: ::c_int, - curr_value: *mut itimerspec) -> ::c_int; - pub fn timerfd_settime(fd: ::c_int, - flags: ::c_int, - new_value: *const itimerspec, - old_value: *mut itimerspec) -> ::c_int; - pub fn pwritev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off_t) -> ::ssize_t; - pub fn preadv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off_t) -> ::ssize_t; - pub fn quotactl(cmd: ::c_int, - special: *const ::c_char, - id: ::c_int, - data: *mut ::c_char) -> ::c_int; - pub fn mq_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::mqd_t; - pub fn mq_close(mqd: ::mqd_t) -> ::c_int; - pub fn mq_unlink(name: *const ::c_char) -> ::c_int; - pub fn mq_receive(mqd: ::mqd_t, - msg_ptr: *mut ::c_char, - msg_len: ::size_t, - msq_prio: *mut ::c_uint) -> ::ssize_t; - pub fn mq_send(mqd: ::mqd_t, - msg_ptr: *const ::c_char, - msg_len: ::size_t, - msq_prio: ::c_uint) -> ::c_int; - pub fn mq_getattr(mqd: ::mqd_t, attr: *mut ::mq_attr) -> ::c_int; - pub fn mq_setattr(mqd: ::mqd_t, - newattr: *const ::mq_attr, - oldattr: *mut ::mq_attr) -> ::c_int; - pub fn epoll_pwait(epfd: ::c_int, - events: *mut ::epoll_event, - maxevents: ::c_int, - timeout: ::c_int, - sigmask: *const ::sigset_t) -> ::c_int; - pub fn dup3(oldfd: ::c_int, newfd: ::c_int, flags: ::c_int) -> ::c_int; - pub fn mkostemp(template: *mut ::c_char, flags: ::c_int) -> ::c_int; - pub fn mkostemps(template: *mut ::c_char, - suffixlen: ::c_int, - flags: ::c_int) -> ::c_int; - pub fn sigtimedwait(set: *const sigset_t, - info: *mut siginfo_t, - timeout: *const ::timespec) -> ::c_int; - pub fn sigwaitinfo(set: *const sigset_t, - info: *mut siginfo_t) -> ::c_int; - pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; - pub fn getnameinfo(sa: *const ::sockaddr, - salen: ::socklen_t, - host: *mut ::c_char, - hostlen: ::socklen_t, - serv: *mut ::c_char, - sevlen: ::socklen_t, - flags: ::c_int) -> ::c_int; - pub fn pthread_setschedprio(native: ::pthread_t, - priority: ::c_int) -> ::c_int; - pub fn prlimit(pid: ::pid_t, resource: ::c_int, new_limit: *const ::rlimit, - old_limit: *mut ::rlimit) -> ::c_int; - pub fn prlimit64(pid: ::pid_t, - resource: ::c_int, - new_limit: *const ::rlimit64, - old_limit: *mut ::rlimit64) -> ::c_int; - pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int; - pub fn process_vm_readv(pid: ::pid_t, - local_iov: *const ::iovec, - liovcnt: ::c_ulong, - remote_iov: *const ::iovec, - riovcnt: ::c_ulong, - flags: ::c_ulong) -> isize; - pub fn process_vm_writev(pid: ::pid_t, - local_iov: *const ::iovec, - liovcnt: ::c_ulong, - remote_iov: *const ::iovec, - riovcnt: ::c_ulong, - flags: ::c_ulong) -> isize; - pub fn reboot(how_to: ::c_int) -> ::c_int; - pub fn setfsgid(gid: ::gid_t) -> ::c_int; - pub fn setfsuid(uid: ::uid_t) -> ::c_int; - - // Not available now on Android - pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t) -> ::c_int; - pub fn if_nameindex() -> *mut if_nameindex; - pub fn if_freenameindex(ptr: *mut if_nameindex); - pub fn sync_file_range(fd: ::c_int, offset: ::off64_t, - nbytes: ::off64_t, flags: ::c_uint) -> ::c_int; - pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; - pub fn freeifaddrs(ifa: *mut ::ifaddrs); - - pub fn mremap(addr: *mut ::c_void, - len: ::size_t, - new_len: ::size_t, - flags: ::c_int, - ...) -> *mut ::c_void; - - pub fn glob(pattern: *const c_char, - flags: ::c_int, - errfunc: Option ::c_int>, - pglob: *mut ::glob_t) -> ::c_int; - pub fn globfree(pglob: *mut ::glob_t); - - pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - pub fn shm_unlink(name: *const ::c_char) -> ::c_int; - - pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); - - pub fn telldir(dirp: *mut ::DIR) -> ::c_long; - pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; - - pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, - flags: ::c_int, addr: *mut ::sockaddr, - addrlen: *mut ::socklen_t) -> ::ssize_t; - pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; - pub fn futimes(fd: ::c_int, times: *const ::timeval) -> ::c_int; - pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; - - pub fn bind(socket: ::c_int, address: *const ::sockaddr, - address_len: ::socklen_t) -> ::c_int; - - pub fn writev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - pub fn readv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - - pub fn sendmsg(fd: ::c_int, - msg: *const ::msghdr, - flags: ::c_int) -> ::ssize_t; - pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) - -> ::ssize_t; - pub fn getdomainname(name: *mut ::c_char, len: ::size_t) -> ::c_int; - pub fn setdomainname(name: *const ::c_char, len: ::size_t) -> ::c_int; - pub fn vhangup() -> ::c_int; - pub fn sendmmsg(sockfd: ::c_int, msgvec: *mut mmsghdr, vlen: ::c_uint, - flags: ::c_int) -> ::c_int; - pub fn recvmmsg(sockfd: ::c_int, msgvec: *mut mmsghdr, vlen: ::c_uint, - flags: ::c_int, timeout: *mut ::timespec) -> ::c_int; - pub fn sync(); - pub fn syscall(num: ::c_long, ...) -> ::c_long; - pub fn sched_getaffinity(pid: ::pid_t, - cpusetsize: ::size_t, - cpuset: *mut cpu_set_t) -> ::c_int; - pub fn sched_setaffinity(pid: ::pid_t, - cpusetsize: ::size_t, - cpuset: *const cpu_set_t) -> ::c_int; - pub fn epoll_create(size: ::c_int) -> ::c_int; - pub fn epoll_create1(flags: ::c_int) -> ::c_int; - pub fn epoll_wait(epfd: ::c_int, - events: *mut ::epoll_event, - maxevents: ::c_int, - timeout: ::c_int) -> ::c_int; - pub fn epoll_ctl(epfd: ::c_int, - op: ::c_int, - fd: ::c_int, - event: *mut ::epoll_event) -> ::c_int; - pub fn pthread_getschedparam(native: ::pthread_t, - policy: *mut ::c_int, - param: *mut ::sched_param) -> ::c_int; - pub fn unshare(flags: ::c_int) -> ::c_int; - pub fn umount(target: *const ::c_char) -> ::c_int; - pub fn sched_get_priority_max(policy: ::c_int) -> ::c_int; - pub fn tee(fd_in: ::c_int, - fd_out: ::c_int, - len: ::size_t, - flags: ::c_uint) -> ::ssize_t; - pub fn settimeofday(tv: *const ::timeval, tz: *const ::timezone) -> ::c_int; - pub fn splice(fd_in: ::c_int, - off_in: *mut ::loff_t, - fd_out: ::c_int, - off_out: *mut ::loff_t, - len: ::size_t, - flags: ::c_uint) -> ::ssize_t; - pub fn eventfd(init: ::c_uint, flags: ::c_int) -> ::c_int; - pub fn sched_rr_get_interval(pid: ::pid_t, tp: *mut ::timespec) -> ::c_int; - pub fn sem_timedwait(sem: *mut sem_t, - abstime: *const ::timespec) -> ::c_int; - pub fn sched_setparam(pid: ::pid_t, param: *const ::sched_param) -> ::c_int; - pub fn setns(fd: ::c_int, nstype: ::c_int) -> ::c_int; - pub fn swapoff(puath: *const ::c_char) -> ::c_int; - pub fn vmsplice(fd: ::c_int, - iov: *const ::iovec, - nr_segs: ::size_t, - flags: ::c_uint) -> ::ssize_t; - pub fn mount(src: *const ::c_char, - target: *const ::c_char, - fstype: *const ::c_char, - flags: ::c_ulong, - data: *const ::c_void) -> ::c_int; - pub fn personality(persona: ::c_ulong) -> ::c_int; - pub fn prctl(option: ::c_int, ...) -> ::c_int; - pub fn sched_getparam(pid: ::pid_t, param: *mut ::sched_param) -> ::c_int; - pub fn ppoll(fds: *mut ::pollfd, - nfds: nfds_t, - timeout: *const ::timespec, - sigmask: *const sigset_t) -> ::c_int; - pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, - abstime: *const ::timespec) -> ::c_int; - pub fn clone(cb: extern fn(*mut ::c_void) -> ::c_int, - child_stack: *mut ::c_void, - flags: ::c_int, - arg: *mut ::c_void, ...) -> ::c_int; - pub fn sched_getscheduler(pid: ::pid_t) -> ::c_int; - pub fn clock_nanosleep(clk_id: ::clockid_t, - flags: ::c_int, - rqtp: *const ::timespec, - rmtp: *mut ::timespec) -> ::c_int; - pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, - guardsize: *mut ::size_t) -> ::c_int; - pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; - pub fn sched_get_priority_min(policy: ::c_int) -> ::c_int; - pub fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, - pshared: *mut ::c_int) -> ::c_int; - pub fn sysinfo(info: *mut ::sysinfo) -> ::c_int; - pub fn umount2(target: *const ::c_char, flags: ::c_int) -> ::c_int; - pub fn pthread_setschedparam(native: ::pthread_t, - policy: ::c_int, - param: *const ::sched_param) -> ::c_int; - pub fn swapon(path: *const ::c_char, swapflags: ::c_int) -> ::c_int; - pub fn sched_setscheduler(pid: ::pid_t, - policy: ::c_int, - param: *const ::sched_param) -> ::c_int; - pub fn sendfile(out_fd: ::c_int, - in_fd: ::c_int, - offset: *mut off_t, - count: ::size_t) -> ::ssize_t; - pub fn sigsuspend(mask: *const ::sigset_t) -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] - pub fn getgrgid_r(uid: ::uid_t, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "sigaltstack$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")] - pub fn sigaltstack(ss: *const stack_t, - oss: *mut stack_t) -> ::c_int; - pub fn sem_close(sem: *mut sem_t) -> ::c_int; - pub fn getdtablesize() -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] - pub fn getgrnam_r(name: *const ::c_char, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - pub fn initgroups(user: *const ::c_char, group: ::gid_t) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_sigmask$UNIX2003")] - pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, - oldset: *mut sigset_t) -> ::c_int; - pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; - pub fn getgrnam(name: *const ::c_char) -> *mut ::group; - pub fn pthread_cancel(thread: ::pthread_t) -> ::c_int; - pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; - pub fn sem_unlink(name: *const ::c_char) -> ::c_int; - pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] - pub fn getpwnam_r(name: *const ::c_char, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] - pub fn getpwuid_r(uid: ::uid_t, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch ="x86"), - link_name = "sigwait$UNIX2003")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] - pub fn sigwait(set: *const sigset_t, - sig: *mut ::c_int) -> ::c_int; - pub fn pthread_atfork(prepare: Option, - parent: Option, - child: Option) -> ::c_int; - pub fn getgrgid(gid: ::gid_t) -> *mut ::group; - pub fn getgrouplist(user: *const ::c_char, - group: ::gid_t, - groups: *mut ::gid_t, - ngroups: *mut ::c_int) -> ::c_int; - pub fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, - pshared: *mut ::c_int) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "popen$UNIX2003")] - pub fn popen(command: *const c_char, - mode: *const c_char) -> *mut ::FILE; - pub fn faccessat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::c_int, flags: ::c_int) -> ::c_int; - pub fn pthread_create(native: *mut ::pthread_t, - attr: *const ::pthread_attr_t, - f: extern fn(*mut ::c_void) -> *mut ::c_void, - value: *mut ::c_void) -> ::c_int; - pub fn dl_iterate_phdr( - callback: Option ::c_int>, - data: *mut ::c_void - ) -> ::c_int; - - pub fn setmntent(filename: *const ::c_char, - ty: *const ::c_char) -> *mut ::FILE; - pub fn getmntent(stream: *mut ::FILE) -> *mut ::mntent; - pub fn addmntent(stream: *mut ::FILE, mnt: *const ::mntent) -> ::c_int; - pub fn endmntent(streamp: *mut ::FILE) -> ::c_int; - pub fn hasmntopt(mnt: *const ::mntent, - opt: *const ::c_char) -> *mut ::c_char; -} - -cfg_if! { - if #[cfg(any(target_env = "musl", target_os = "fuchsia"))] { - mod musl; - pub use self::musl::*; - } else if #[cfg(any(target_arch = "mips", - target_arch = "mips64"))] { - mod mips; - pub use self::mips::*; - } else if #[cfg(any(target_arch = "s390x"))] { - mod s390x; - pub use self::s390x::*; - } else { - mod other; - pub use self::other::*; - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/arm.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/arm.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/arm.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/arm.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,755 +0,0 @@ -pub type c_char = u8; -pub type wchar_t = u32; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - __st_dev_padding: ::c_int, - __st_ino_truncated: ::c_long, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __st_rdev_padding: ::c_int, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_ino: ::ino_t, - } - - pub struct stat64 { - pub st_dev: ::dev_t, - __st_dev_padding: ::c_int, - __st_ino_truncated: ::c_long, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __st_rdev_padding: ::c_int, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_ino: ::ino_t, - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_flags: ::c_int, - pub ss_size: ::size_t - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - __unused1: ::c_int, - pub shm_dtime: ::time_t, - __unused2: ::c_int, - pub shm_ctime: ::time_t, - __unused3: ::c_int, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::c_ulong, - __pad1: ::c_ulong, - __pad2: ::c_ulong, - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - pub msg_stime: ::time_t, - __unused1: ::c_int, - pub msg_rtime: ::time_t, - __unused2: ::c_int, - pub msg_ctime: ::time_t, - __unused3: ::c_int, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __pad1: ::c_ulong, - __pad2: ::c_ulong, - } - - pub struct statfs { - pub f_type: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_flags: ::c_ulong, - pub f_spare: [::c_ulong; 4], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_errno: ::c_int, - pub si_code: ::c_int, - pub _pad: [::c_int; 29], - _align: [usize; 0], - } - - pub struct statfs64 { - pub f_type: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_flags: ::c_ulong, - pub f_spare: [::c_ulong; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - __f_unused: ::c_int, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 19], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } -} - -pub const O_DIRECT: ::c_int = 0x10000; -pub const O_DIRECTORY: ::c_int = 0x4000; -pub const O_NOFOLLOW: ::c_int = 0x8000; -pub const O_ASYNC: ::c_int = 0x2000; -pub const O_LARGEFILE: ::c_int = 0o400000; - -pub const FIOCLEX: ::c_int = 0x5451; -pub const FIONBIO: ::c_int = 0x5421; - -pub const RLIMIT_RSS: ::c_int = 5; -pub const RLIMIT_NOFILE: ::c_int = 7; -pub const RLIMIT_AS: ::c_int = 9; -pub const RLIMIT_NPROC: ::c_int = 6; -pub const RLIMIT_MEMLOCK: ::c_int = 8; - -pub const O_APPEND: ::c_int = 1024; -pub const O_CREAT: ::c_int = 64; -pub const O_EXCL: ::c_int = 128; -pub const O_NOCTTY: ::c_int = 256; -pub const O_NONBLOCK: ::c_int = 2048; -pub const O_SYNC: ::c_int = 1052672; -pub const O_RSYNC: ::c_int = 1052672; -pub const O_DSYNC: ::c_int = 4096; - -pub const SOCK_NONBLOCK: ::c_int = 2048; - -pub const MAP_ANON: ::c_int = 0x0020; -pub const MAP_GROWSDOWN: ::c_int = 0x0100; -pub const MAP_DENYWRITE: ::c_int = 0x0800; -pub const MAP_EXECUTABLE: ::c_int = 0x01000; -pub const MAP_LOCKED: ::c_int = 0x02000; -pub const MAP_NORESERVE: ::c_int = 0x04000; -pub const MAP_POPULATE: ::c_int = 0x08000; -pub const MAP_NONBLOCK: ::c_int = 0x010000; -pub const MAP_STACK: ::c_int = 0x020000; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; -pub const SOCK_SEQPACKET: ::c_int = 5; - -pub const SOL_SOCKET: ::c_int = 1; - -pub const EDEADLK: ::c_int = 35; -pub const ENAMETOOLONG: ::c_int = 36; -pub const ENOLCK: ::c_int = 37; -pub const ENOSYS: ::c_int = 38; -pub const ENOTEMPTY: ::c_int = 39; -pub const ELOOP: ::c_int = 40; -pub const ENOMSG: ::c_int = 42; -pub const EIDRM: ::c_int = 43; -pub const ECHRNG: ::c_int = 44; -pub const EL2NSYNC: ::c_int = 45; -pub const EL3HLT: ::c_int = 46; -pub const EL3RST: ::c_int = 47; -pub const ELNRNG: ::c_int = 48; -pub const EUNATCH: ::c_int = 49; -pub const ENOCSI: ::c_int = 50; -pub const EL2HLT: ::c_int = 51; -pub const EBADE: ::c_int = 52; -pub const EBADR: ::c_int = 53; -pub const EXFULL: ::c_int = 54; -pub const ENOANO: ::c_int = 55; -pub const EBADRQC: ::c_int = 56; -pub const EBADSLT: ::c_int = 57; -pub const EDEADLOCK: ::c_int = EDEADLK; -pub const EMULTIHOP: ::c_int = 72; -pub const EBADMSG: ::c_int = 74; -pub const EOVERFLOW: ::c_int = 75; -pub const ENOTUNIQ: ::c_int = 76; -pub const EBADFD: ::c_int = 77; -pub const EREMCHG: ::c_int = 78; -pub const ELIBACC: ::c_int = 79; -pub const ELIBBAD: ::c_int = 80; -pub const ELIBSCN: ::c_int = 81; -pub const ELIBMAX: ::c_int = 82; -pub const ELIBEXEC: ::c_int = 83; -pub const EILSEQ: ::c_int = 84; -pub const ERESTART: ::c_int = 85; -pub const ESTRPIPE: ::c_int = 86; -pub const EUSERS: ::c_int = 87; -pub const ENOTSOCK: ::c_int = 88; -pub const EDESTADDRREQ: ::c_int = 89; -pub const EMSGSIZE: ::c_int = 90; -pub const EPROTOTYPE: ::c_int = 91; -pub const ENOPROTOOPT: ::c_int = 92; -pub const EPROTONOSUPPORT: ::c_int = 93; -pub const ESOCKTNOSUPPORT: ::c_int = 94; -pub const EOPNOTSUPP: ::c_int = 95; -pub const ENOTSUP: ::c_int = EOPNOTSUPP; -pub const EPFNOSUPPORT: ::c_int = 96; -pub const EAFNOSUPPORT: ::c_int = 97; -pub const EADDRINUSE: ::c_int = 98; -pub const EADDRNOTAVAIL: ::c_int = 99; -pub const ENETDOWN: ::c_int = 100; -pub const ENETUNREACH: ::c_int = 101; -pub const ENETRESET: ::c_int = 102; -pub const ECONNABORTED: ::c_int = 103; -pub const ECONNRESET: ::c_int = 104; -pub const ENOBUFS: ::c_int = 105; -pub const EISCONN: ::c_int = 106; -pub const ENOTCONN: ::c_int = 107; -pub const ESHUTDOWN: ::c_int = 108; -pub const ETOOMANYREFS: ::c_int = 109; -pub const ETIMEDOUT: ::c_int = 110; -pub const ECONNREFUSED: ::c_int = 111; -pub const EHOSTDOWN: ::c_int = 112; -pub const EHOSTUNREACH: ::c_int = 113; -pub const EALREADY: ::c_int = 114; -pub const EINPROGRESS: ::c_int = 115; -pub const ESTALE: ::c_int = 116; -pub const EUCLEAN: ::c_int = 117; -pub const ENOTNAM: ::c_int = 118; -pub const ENAVAIL: ::c_int = 119; -pub const EISNAM: ::c_int = 120; -pub const EREMOTEIO: ::c_int = 121; -pub const EDQUOT: ::c_int = 122; -pub const ENOMEDIUM: ::c_int = 123; -pub const EMEDIUMTYPE: ::c_int = 124; -pub const ECANCELED: ::c_int = 125; -pub const ENOKEY: ::c_int = 126; -pub const EKEYEXPIRED: ::c_int = 127; -pub const EKEYREVOKED: ::c_int = 128; -pub const EKEYREJECTED: ::c_int = 129; -pub const EOWNERDEAD: ::c_int = 130; -pub const ENOTRECOVERABLE: ::c_int = 131; -pub const ERFKILL: ::c_int = 132; -pub const EHWPOISON: ::c_int = 133; - -pub const SO_REUSEADDR: ::c_int = 2; -pub const SO_TYPE: ::c_int = 3; -pub const SO_ERROR: ::c_int = 4; -pub const SO_DONTROUTE: ::c_int = 5; -pub const SO_BROADCAST: ::c_int = 6; -pub const SO_SNDBUF: ::c_int = 7; -pub const SO_RCVBUF: ::c_int = 8; -pub const SO_KEEPALIVE: ::c_int = 9; -pub const SO_OOBINLINE: ::c_int = 10; -pub const SO_NO_CHECK: ::c_int = 11; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_LINGER: ::c_int = 13; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_REUSEPORT: ::c_int = 15; -pub const SO_PASSCRED: ::c_int = 16; -pub const SO_PEERCRED: ::c_int = 17; -pub const SO_RCVLOWAT: ::c_int = 18; -pub const SO_SNDLOWAT: ::c_int = 19; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_SNDTIMEO: ::c_int = 21; -pub const SO_ACCEPTCONN: ::c_int = 30; -pub const SO_SNDBUFFORCE: ::c_int = 32; -pub const SO_RCVBUFFORCE: ::c_int = 33; -pub const SO_PROTOCOL: ::c_int = 38; -pub const SO_DOMAIN: ::c_int = 39; - -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 0x00000004; -pub const SA_NOCLDWAIT: ::c_int = 0x00000002; - -pub const SIGCHLD: ::c_int = 17; -pub const SIGBUS: ::c_int = 7; -pub const SIGTTIN: ::c_int = 21; -pub const SIGTTOU: ::c_int = 22; -pub const SIGXCPU: ::c_int = 24; -pub const SIGXFSZ: ::c_int = 25; -pub const SIGVTALRM: ::c_int = 26; -pub const SIGPROF: ::c_int = 27; -pub const SIGWINCH: ::c_int = 28; -pub const SIGUSR1: ::c_int = 10; -pub const SIGUSR2: ::c_int = 12; -pub const SIGCONT: ::c_int = 18; -pub const SIGSTOP: ::c_int = 19; -pub const SIGTSTP: ::c_int = 20; -pub const SIGURG: ::c_int = 23; -pub const SIGIO: ::c_int = 29; -pub const SIGSYS: ::c_int = 31; -pub const SIGSTKFLT: ::c_int = 16; -pub const SIGPOLL: ::c_int = 29; -pub const SIGPWR: ::c_int = 30; -pub const SIG_SETMASK: ::c_int = 2; -pub const SIG_BLOCK: ::c_int = 0x000000; -pub const SIG_UNBLOCK: ::c_int = 0x01; - -pub const EXTPROC: ::tcflag_t = 0x00010000; - -pub const MAP_HUGETLB: ::c_int = 0x040000; - -pub const F_GETLK: ::c_int = 12; -pub const F_GETOWN: ::c_int = 9; -pub const F_SETLK: ::c_int = 13; -pub const F_SETLKW: ::c_int = 14; -pub const F_SETOWN: ::c_int = 8; - -pub const VEOF: usize = 4; -pub const VEOL: usize = 11; -pub const VEOL2: usize = 16; -pub const VMIN: usize = 6; -pub const IEXTEN: ::tcflag_t = 0x00008000; -pub const TOSTOP: ::tcflag_t = 0x00000100; -pub const FLUSHO: ::tcflag_t = 0x00001000; - -pub const TCGETS: ::c_int = 0x5401; -pub const TCSETS: ::c_int = 0x5402; -pub const TCSETSW: ::c_int = 0x5403; -pub const TCSETSF: ::c_int = 0x5404; -pub const TCGETA: ::c_int = 0x5405; -pub const TCSETA: ::c_int = 0x5406; -pub const TCSETAW: ::c_int = 0x5407; -pub const TCSETAF: ::c_int = 0x5408; -pub const TCSBRK: ::c_int = 0x5409; -pub const TCXONC: ::c_int = 0x540A; -pub const TCFLSH: ::c_int = 0x540B; -pub const TIOCGSOFTCAR: ::c_int = 0x5419; -pub const TIOCSSOFTCAR: ::c_int = 0x541A; -pub const TIOCLINUX: ::c_int = 0x541C; -pub const TIOCGSERIAL: ::c_int = 0x541E; -pub const TIOCEXCL: ::c_int = 0x540C; -pub const TIOCNXCL: ::c_int = 0x540D; -pub const TIOCSCTTY: ::c_int = 0x540E; -pub const TIOCGPGRP: ::c_int = 0x540F; -pub const TIOCSPGRP: ::c_int = 0x5410; -pub const TIOCOUTQ: ::c_int = 0x5411; -pub const TIOCSTI: ::c_int = 0x5412; -pub const TIOCGWINSZ: ::c_int = 0x5413; -pub const TIOCSWINSZ: ::c_int = 0x5414; -pub const TIOCMGET: ::c_int = 0x5415; -pub const TIOCMBIS: ::c_int = 0x5416; -pub const TIOCMBIC: ::c_int = 0x5417; -pub const TIOCMSET: ::c_int = 0x5418; -pub const FIONREAD: ::c_int = 0x541B; -pub const TIOCCONS: ::c_int = 0x541D; - -pub const POLLWRNORM: ::c_short = 0x100; -pub const POLLWRBAND: ::c_short = 0x200; - -pub const TIOCM_LE: ::c_int = 0x001; -pub const TIOCM_DTR: ::c_int = 0x002; -pub const TIOCM_RTS: ::c_int = 0x004; -pub const TIOCM_ST: ::c_int = 0x008; -pub const TIOCM_SR: ::c_int = 0x010; -pub const TIOCM_CTS: ::c_int = 0x020; -pub const TIOCM_CAR: ::c_int = 0x040; -pub const TIOCM_RNG: ::c_int = 0x080; -pub const TIOCM_DSR: ::c_int = 0x100; -pub const TIOCM_CD: ::c_int = TIOCM_CAR; -pub const TIOCM_RI: ::c_int = TIOCM_RNG; - -// Syscall table -pub const SYS_restart_syscall: ::c_long = 0; -pub const SYS_exit: ::c_long = 1; -pub const SYS_fork: ::c_long = 2; -pub const SYS_read: ::c_long = 3; -pub const SYS_write: ::c_long = 4; -pub const SYS_open: ::c_long = 5; -pub const SYS_close: ::c_long = 6; -pub const SYS_creat: ::c_long = 8; -pub const SYS_link: ::c_long = 9; -pub const SYS_unlink: ::c_long = 10; -pub const SYS_execve: ::c_long = 11; -pub const SYS_chdir: ::c_long = 12; -pub const SYS_mknod: ::c_long = 14; -pub const SYS_chmod: ::c_long = 15; -pub const SYS_lchown: ::c_long = 16; -pub const SYS_lseek: ::c_long = 19; -pub const SYS_getpid: ::c_long = 20; -pub const SYS_mount: ::c_long = 21; -pub const SYS_setuid: ::c_long = 23; -pub const SYS_getuid: ::c_long = 24; -pub const SYS_ptrace: ::c_long = 26; -pub const SYS_pause: ::c_long = 29; -pub const SYS_access: ::c_long = 33; -pub const SYS_nice: ::c_long = 34; -pub const SYS_sync: ::c_long = 36; -pub const SYS_kill: ::c_long = 37; -pub const SYS_rename: ::c_long = 38; -pub const SYS_mkdir: ::c_long = 39; -pub const SYS_rmdir: ::c_long = 40; -pub const SYS_dup: ::c_long = 41; -pub const SYS_pipe: ::c_long = 42; -pub const SYS_times: ::c_long = 43; -pub const SYS_brk: ::c_long = 45; -pub const SYS_setgid: ::c_long = 46; -pub const SYS_getgid: ::c_long = 47; -pub const SYS_geteuid: ::c_long = 49; -pub const SYS_getegid: ::c_long = 50; -pub const SYS_acct: ::c_long = 51; -pub const SYS_umount2: ::c_long = 52; -pub const SYS_ioctl: ::c_long = 54; -pub const SYS_fcntl: ::c_long = 55; -pub const SYS_setpgid: ::c_long = 57; -pub const SYS_umask: ::c_long = 60; -pub const SYS_chroot: ::c_long = 61; -pub const SYS_ustat: ::c_long = 62; -pub const SYS_dup2: ::c_long = 63; -pub const SYS_getppid: ::c_long = 64; -pub const SYS_getpgrp: ::c_long = 65; -pub const SYS_setsid: ::c_long = 66; -pub const SYS_sigaction: ::c_long = 67; -pub const SYS_setreuid: ::c_long = 70; -pub const SYS_setregid: ::c_long = 71; -pub const SYS_sigsuspend: ::c_long = 72; -pub const SYS_sigpending: ::c_long = 73; -pub const SYS_sethostname: ::c_long = 74; -pub const SYS_setrlimit: ::c_long = 75; -pub const SYS_getrusage: ::c_long = 77; -pub const SYS_gettimeofday: ::c_long = 78; -pub const SYS_settimeofday: ::c_long = 79; -pub const SYS_getgroups: ::c_long = 80; -pub const SYS_setgroups: ::c_long = 81; -pub const SYS_symlink: ::c_long = 83; -pub const SYS_readlink: ::c_long = 85; -pub const SYS_uselib: ::c_long = 86; -pub const SYS_swapon: ::c_long = 87; -pub const SYS_reboot: ::c_long = 88; -pub const SYS_munmap: ::c_long = 91; -pub const SYS_truncate: ::c_long = 92; -pub const SYS_ftruncate: ::c_long = 93; -pub const SYS_fchmod: ::c_long = 94; -pub const SYS_fchown: ::c_long = 95; -pub const SYS_getpriority: ::c_long = 96; -pub const SYS_setpriority: ::c_long = 97; -pub const SYS_statfs: ::c_long = 99; -pub const SYS_fstatfs: ::c_long = 100; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_setitimer: ::c_long = 104; -pub const SYS_getitimer: ::c_long = 105; -pub const SYS_stat: ::c_long = 106; -pub const SYS_lstat: ::c_long = 107; -pub const SYS_fstat: ::c_long = 108; -pub const SYS_vhangup: ::c_long = 111; -pub const SYS_wait4: ::c_long = 114; -pub const SYS_swapoff: ::c_long = 115; -pub const SYS_sysinfo: ::c_long = 116; -pub const SYS_fsync: ::c_long = 118; -pub const SYS_sigreturn: ::c_long = 119; -pub const SYS_clone: ::c_long = 120; -pub const SYS_setdomainname: ::c_long = 121; -pub const SYS_uname: ::c_long = 122; -pub const SYS_adjtimex: ::c_long = 124; -pub const SYS_mprotect: ::c_long = 125; -pub const SYS_sigprocmask: ::c_long = 126; -pub const SYS_init_module: ::c_long = 128; -pub const SYS_delete_module: ::c_long = 129; -pub const SYS_quotactl: ::c_long = 131; -pub const SYS_getpgid: ::c_long = 132; -pub const SYS_fchdir: ::c_long = 133; -pub const SYS_bdflush: ::c_long = 134; -pub const SYS_sysfs: ::c_long = 135; -pub const SYS_personality: ::c_long = 136; -pub const SYS_setfsuid: ::c_long = 138; -pub const SYS_setfsgid: ::c_long = 139; -pub const SYS__llseek: ::c_long = 140; -pub const SYS_getdents: ::c_long = 141; -pub const SYS__newselect: ::c_long = 142; -pub const SYS_flock: ::c_long = 143; -pub const SYS_msync: ::c_long = 144; -pub const SYS_readv: ::c_long = 145; -pub const SYS_writev: ::c_long = 146; -pub const SYS_getsid: ::c_long = 147; -pub const SYS_fdatasync: ::c_long = 148; -pub const SYS__sysctl: ::c_long = 149; -pub const SYS_mlock: ::c_long = 150; -pub const SYS_munlock: ::c_long = 151; -pub const SYS_mlockall: ::c_long = 152; -pub const SYS_munlockall: ::c_long = 153; -pub const SYS_sched_setparam: ::c_long = 154; -pub const SYS_sched_getparam: ::c_long = 155; -pub const SYS_sched_setscheduler: ::c_long = 156; -pub const SYS_sched_getscheduler: ::c_long = 157; -pub const SYS_sched_yield: ::c_long = 158; -pub const SYS_sched_get_priority_max: ::c_long = 159; -pub const SYS_sched_get_priority_min: ::c_long = 160; -pub const SYS_sched_rr_get_interval: ::c_long = 161; -pub const SYS_nanosleep: ::c_long = 162; -pub const SYS_mremap: ::c_long = 163; -pub const SYS_setresuid: ::c_long = 164; -pub const SYS_getresuid: ::c_long = 165; -pub const SYS_poll: ::c_long = 168; -pub const SYS_nfsservctl: ::c_long = 169; -pub const SYS_setresgid: ::c_long = 170; -pub const SYS_getresgid: ::c_long = 171; -pub const SYS_prctl: ::c_long = 172; -pub const SYS_rt_sigreturn: ::c_long = 173; -pub const SYS_rt_sigaction: ::c_long = 174; -pub const SYS_rt_sigprocmask: ::c_long = 175; -pub const SYS_rt_sigpending: ::c_long = 176; -pub const SYS_rt_sigtimedwait: ::c_long = 177; -pub const SYS_rt_sigqueueinfo: ::c_long = 178; -pub const SYS_rt_sigsuspend: ::c_long = 179; -pub const SYS_pread64: ::c_long = 180; -pub const SYS_pwrite64: ::c_long = 181; -pub const SYS_chown: ::c_long = 182; -pub const SYS_getcwd: ::c_long = 183; -pub const SYS_capget: ::c_long = 184; -pub const SYS_capset: ::c_long = 185; -pub const SYS_sigaltstack: ::c_long = 186; -pub const SYS_sendfile: ::c_long = 187; -pub const SYS_vfork: ::c_long = 190; -pub const SYS_ugetrlimit: ::c_long = 191; -pub const SYS_mmap2: ::c_long = 192; -pub const SYS_truncate64: ::c_long = 193; -pub const SYS_ftruncate64: ::c_long = 194; -pub const SYS_stat64: ::c_long = 195; -pub const SYS_lstat64: ::c_long = 196; -pub const SYS_fstat64: ::c_long = 197; -pub const SYS_lchown32: ::c_long = 198; -pub const SYS_getuid32: ::c_long = 199; -pub const SYS_getgid32: ::c_long = 200; -pub const SYS_geteuid32: ::c_long = 201; -pub const SYS_getegid32: ::c_long = 202; -pub const SYS_setreuid32: ::c_long = 203; -pub const SYS_setregid32: ::c_long = 204; -pub const SYS_getgroups32: ::c_long = 205; -pub const SYS_setgroups32: ::c_long = 206; -pub const SYS_fchown32: ::c_long = 207; -pub const SYS_setresuid32: ::c_long = 208; -pub const SYS_getresuid32: ::c_long = 209; -pub const SYS_setresgid32: ::c_long = 210; -pub const SYS_getresgid32: ::c_long = 211; -pub const SYS_chown32: ::c_long = 212; -pub const SYS_setuid32: ::c_long = 213; -pub const SYS_setgid32: ::c_long = 214; -pub const SYS_setfsuid32: ::c_long = 215; -pub const SYS_setfsgid32: ::c_long = 216; -pub const SYS_getdents64: ::c_long = 217; -pub const SYS_pivot_root: ::c_long = 218; -pub const SYS_mincore: ::c_long = 219; -pub const SYS_madvise: ::c_long = 220; -pub const SYS_fcntl64: ::c_long = 221; -pub const SYS_gettid: ::c_long = 224; -pub const SYS_readahead: ::c_long = 225; -pub const SYS_setxattr: ::c_long = 226; -pub const SYS_lsetxattr: ::c_long = 227; -pub const SYS_fsetxattr: ::c_long = 228; -pub const SYS_getxattr: ::c_long = 229; -pub const SYS_lgetxattr: ::c_long = 230; -pub const SYS_fgetxattr: ::c_long = 231; -pub const SYS_listxattr: ::c_long = 232; -pub const SYS_llistxattr: ::c_long = 233; -pub const SYS_flistxattr: ::c_long = 234; -pub const SYS_removexattr: ::c_long = 235; -pub const SYS_lremovexattr: ::c_long = 236; -pub const SYS_fremovexattr: ::c_long = 237; -pub const SYS_tkill: ::c_long = 238; -pub const SYS_sendfile64: ::c_long = 239; -pub const SYS_futex: ::c_long = 240; -pub const SYS_sched_setaffinity: ::c_long = 241; -pub const SYS_sched_getaffinity: ::c_long = 242; -pub const SYS_io_setup: ::c_long = 243; -pub const SYS_io_destroy: ::c_long = 244; -pub const SYS_io_getevents: ::c_long = 245; -pub const SYS_io_submit: ::c_long = 246; -pub const SYS_io_cancel: ::c_long = 247; -pub const SYS_exit_group: ::c_long = 248; -pub const SYS_lookup_dcookie: ::c_long = 249; -pub const SYS_epoll_create: ::c_long = 250; -pub const SYS_epoll_ctl: ::c_long = 251; -pub const SYS_epoll_wait: ::c_long = 252; -pub const SYS_remap_file_pages: ::c_long = 253; -pub const SYS_set_tid_address: ::c_long = 256; -pub const SYS_timer_create: ::c_long = 257; -pub const SYS_timer_settime: ::c_long = 258; -pub const SYS_timer_gettime: ::c_long = 259; -pub const SYS_timer_getoverrun: ::c_long = 260; -pub const SYS_timer_delete: ::c_long = 261; -pub const SYS_clock_settime: ::c_long = 262; -pub const SYS_clock_gettime: ::c_long = 263; -pub const SYS_clock_getres: ::c_long = 264; -pub const SYS_clock_nanosleep: ::c_long = 265; -pub const SYS_statfs64: ::c_long = 266; -pub const SYS_fstatfs64: ::c_long = 267; -pub const SYS_tgkill: ::c_long = 268; -pub const SYS_utimes: ::c_long = 269; -pub const SYS_pciconfig_iobase: ::c_long = 271; -pub const SYS_pciconfig_read: ::c_long = 272; -pub const SYS_pciconfig_write: ::c_long = 273; -pub const SYS_mq_open: ::c_long = 274; -pub const SYS_mq_unlink: ::c_long = 275; -pub const SYS_mq_timedsend: ::c_long = 276; -pub const SYS_mq_timedreceive: ::c_long = 277; -pub const SYS_mq_notify: ::c_long = 278; -pub const SYS_mq_getsetattr: ::c_long = 279; -pub const SYS_waitid: ::c_long = 280; -pub const SYS_socket: ::c_long = 281; -pub const SYS_bind: ::c_long = 282; -pub const SYS_connect: ::c_long = 283; -pub const SYS_listen: ::c_long = 284; -pub const SYS_accept: ::c_long = 285; -pub const SYS_getsockname: ::c_long = 286; -pub const SYS_getpeername: ::c_long = 287; -pub const SYS_socketpair: ::c_long = 288; -pub const SYS_send: ::c_long = 289; -pub const SYS_sendto: ::c_long = 290; -pub const SYS_recv: ::c_long = 291; -pub const SYS_recvfrom: ::c_long = 292; -pub const SYS_shutdown: ::c_long = 293; -pub const SYS_setsockopt: ::c_long = 294; -pub const SYS_getsockopt: ::c_long = 295; -pub const SYS_sendmsg: ::c_long = 296; -pub const SYS_recvmsg: ::c_long = 297; -pub const SYS_semop: ::c_long = 298; -pub const SYS_semget: ::c_long = 299; -pub const SYS_semctl: ::c_long = 300; -pub const SYS_msgsnd: ::c_long = 301; -pub const SYS_msgrcv: ::c_long = 302; -pub const SYS_msgget: ::c_long = 303; -pub const SYS_msgctl: ::c_long = 304; -pub const SYS_shmat: ::c_long = 305; -pub const SYS_shmdt: ::c_long = 306; -pub const SYS_shmget: ::c_long = 307; -pub const SYS_shmctl: ::c_long = 308; -pub const SYS_add_key: ::c_long = 309; -pub const SYS_request_key: ::c_long = 310; -pub const SYS_keyctl: ::c_long = 311; -pub const SYS_semtimedop: ::c_long = 312; -pub const SYS_vserver: ::c_long = 313; -pub const SYS_ioprio_set: ::c_long = 314; -pub const SYS_ioprio_get: ::c_long = 315; -pub const SYS_inotify_init: ::c_long = 316; -pub const SYS_inotify_add_watch: ::c_long = 317; -pub const SYS_inotify_rm_watch: ::c_long = 318; -pub const SYS_mbind: ::c_long = 319; -pub const SYS_get_mempolicy: ::c_long = 320; -pub const SYS_set_mempolicy: ::c_long = 321; -pub const SYS_openat: ::c_long = 322; -pub const SYS_mkdirat: ::c_long = 323; -pub const SYS_mknodat: ::c_long = 324; -pub const SYS_fchownat: ::c_long = 325; -pub const SYS_futimesat: ::c_long = 326; -pub const SYS_fstatat64: ::c_long = 327; -pub const SYS_unlinkat: ::c_long = 328; -pub const SYS_renameat: ::c_long = 329; -pub const SYS_linkat: ::c_long = 330; -pub const SYS_symlinkat: ::c_long = 331; -pub const SYS_readlinkat: ::c_long = 332; -pub const SYS_fchmodat: ::c_long = 333; -pub const SYS_faccessat: ::c_long = 334; -pub const SYS_pselect6: ::c_long = 335; -pub const SYS_ppoll: ::c_long = 336; -pub const SYS_unshare: ::c_long = 337; -pub const SYS_set_robust_list: ::c_long = 338; -pub const SYS_get_robust_list: ::c_long = 339; -pub const SYS_splice: ::c_long = 340; -pub const SYS_tee: ::c_long = 342; -pub const SYS_vmsplice: ::c_long = 343; -pub const SYS_move_pages: ::c_long = 344; -pub const SYS_getcpu: ::c_long = 345; -pub const SYS_epoll_pwait: ::c_long = 346; -pub const SYS_kexec_load: ::c_long = 347; -pub const SYS_utimensat: ::c_long = 348; -pub const SYS_signalfd: ::c_long = 349; -pub const SYS_timerfd_create: ::c_long = 350; -pub const SYS_eventfd: ::c_long = 351; -pub const SYS_fallocate: ::c_long = 352; -pub const SYS_timerfd_settime: ::c_long = 353; -pub const SYS_timerfd_gettime: ::c_long = 354; -pub const SYS_signalfd4: ::c_long = 355; -pub const SYS_eventfd2: ::c_long = 356; -pub const SYS_epoll_create1: ::c_long = 357; -pub const SYS_dup3: ::c_long = 358; -pub const SYS_pipe2: ::c_long = 359; -pub const SYS_inotify_init1: ::c_long = 360; -pub const SYS_preadv: ::c_long = 361; -pub const SYS_pwritev: ::c_long = 362; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 363; -pub const SYS_perf_event_open: ::c_long = 364; -pub const SYS_recvmmsg: ::c_long = 365; -pub const SYS_accept4: ::c_long = 366; -pub const SYS_fanotify_init: ::c_long = 367; -pub const SYS_fanotify_mark: ::c_long = 368; -pub const SYS_prlimit64: ::c_long = 369; -pub const SYS_name_to_handle_at: ::c_long = 370; -pub const SYS_open_by_handle_at: ::c_long = 371; -pub const SYS_clock_adjtime: ::c_long = 372; -pub const SYS_syncfs: ::c_long = 373; -pub const SYS_sendmmsg: ::c_long = 374; -pub const SYS_setns: ::c_long = 375; -pub const SYS_process_vm_readv: ::c_long = 376; -pub const SYS_process_vm_writev: ::c_long = 377; -pub const SYS_kcmp: ::c_long = 378; -pub const SYS_finit_module: ::c_long = 379; -pub const SYS_sched_setattr: ::c_long = 380; -pub const SYS_sched_getattr: ::c_long = 381; -pub const SYS_renameat2: ::c_long = 382; -pub const SYS_seccomp: ::c_long = 383; -pub const SYS_getrandom: ::c_long = 384; -pub const SYS_memfd_create: ::c_long = 385; -pub const SYS_bpf: ::c_long = 386; -pub const SYS_execveat: ::c_long = 387; -pub const SYS_userfaultfd: ::c_long = 388; -pub const SYS_membarrier: ::c_long = 389; -pub const SYS_mlock2: ::c_long = 390; -pub const SYS_copy_file_range: ::c_long = 391; -pub const SYS_preadv2: ::c_long = 392; -pub const SYS_pwritev2: ::c_long = 393; -pub const SYS_pkey_mprotect: ::c_long = 394; -pub const SYS_pkey_alloc: ::c_long = 395; -pub const SYS_pkey_free: ::c_long = 396; - -#[doc(hidden)] -pub const AF_MAX: ::c_int = 43; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/mips.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/mips.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/mips.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/mips.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,773 +0,0 @@ -pub type c_char = i8; -pub type wchar_t = ::c_int; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - __st_padding1: [::c_long; 2], - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __st_padding2: [::c_long; 2], - pub st_size: ::off_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - __st_padding3: ::c_long, - pub st_blocks: ::blkcnt_t, - __st_padding4: [::c_long; 14], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - __st_padding1: [::c_long; 2], - pub st_ino: ::ino64_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __st_padding2: [::c_long; 2], - pub st_size: ::off_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - __st_padding3: ::c_long, - pub st_blocks: ::blkcnt64_t, - __st_padding4: [::c_long; 14], - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_size: ::size_t, - pub ss_flags: ::c_int, - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::c_ulong, - __pad1: ::c_ulong, - __pad2: ::c_ulong, - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - #[cfg(target_endian = "big")] - __unused1: ::c_int, - pub msg_stime: ::time_t, - #[cfg(target_endian = "little")] - __unused1: ::c_int, - #[cfg(target_endian = "big")] - __unused2: ::c_int, - pub msg_rtime: ::time_t, - #[cfg(target_endian = "little")] - __unused2: ::c_int, - #[cfg(target_endian = "big")] - __unused3: ::c_int, - pub msg_ctime: ::time_t, - #[cfg(target_endian = "little")] - __unused3: ::c_int, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __pad1: ::c_ulong, - __pad2: ::c_ulong, - } - - pub struct statfs { - pub f_type: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_ulong, - pub f_flags: ::c_ulong, - pub f_spare: [::c_ulong; 5], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_code: ::c_int, - pub si_errno: ::c_int, - pub _pad: [::c_int; 29], - _align: [usize; 0], - } - - pub struct statfs64 { - pub f_type: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_ulong, - pub f_flags: ::c_ulong, - pub f_spare: [::c_ulong; 5], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - #[cfg(target_endian = "little")] - pub f_fsid: ::c_ulong, - __f_unused: ::c_int, - #[cfg(target_endian = "big")] - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 23], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } -} - -pub const O_DIRECT: ::c_int = 0o100000; -pub const O_DIRECTORY: ::c_int = 0o200000; -pub const O_NOFOLLOW: ::c_int = 0o400000; -pub const O_ASYNC: ::c_int = 0o10000; -pub const O_LARGEFILE: ::c_int = 0x2000; - -pub const FIOCLEX: ::c_int = 0x6601; -pub const FIONBIO: ::c_int = 0x667E; - -pub const RLIMIT_RSS: ::c_int = 7; -pub const RLIMIT_NOFILE: ::c_int = 5; -pub const RLIMIT_AS: ::c_int = 6; -pub const RLIMIT_NPROC: ::c_int = 8; -pub const RLIMIT_MEMLOCK: ::c_int = 9; - -pub const O_APPEND: ::c_int = 0o010; -pub const O_CREAT: ::c_int = 0o400; -pub const O_EXCL: ::c_int = 0o2000; -pub const O_NOCTTY: ::c_int = 0o4000; -pub const O_NONBLOCK: ::c_int = 0o200; -pub const O_SYNC: ::c_int = 0o40020; -pub const O_RSYNC: ::c_int = 0o40020; -pub const O_DSYNC: ::c_int = 0o020; - -pub const SOCK_NONBLOCK: ::c_int = 0o200; - -pub const MAP_ANON: ::c_int = 0x800; -pub const MAP_GROWSDOWN: ::c_int = 0x1000; -pub const MAP_DENYWRITE: ::c_int = 0x2000; -pub const MAP_EXECUTABLE: ::c_int = 0x4000; -pub const MAP_LOCKED: ::c_int = 0x8000; -pub const MAP_NORESERVE: ::c_int = 0x0400; -pub const MAP_POPULATE: ::c_int = 0x10000; -pub const MAP_NONBLOCK: ::c_int = 0x20000; -pub const MAP_STACK: ::c_int = 0x40000; - -pub const EDEADLK: ::c_int = 45; -pub const ENAMETOOLONG: ::c_int = 78; -pub const ENOLCK: ::c_int = 46; -pub const ENOSYS: ::c_int = 89; -pub const ENOTEMPTY: ::c_int = 93; -pub const ELOOP: ::c_int = 90; -pub const ENOMSG: ::c_int = 35; -pub const EIDRM: ::c_int = 36; -pub const ECHRNG: ::c_int = 37; -pub const EL2NSYNC: ::c_int = 38; -pub const EL3HLT: ::c_int = 39; -pub const EL3RST: ::c_int = 40; -pub const ELNRNG: ::c_int = 41; -pub const EUNATCH: ::c_int = 42; -pub const ENOCSI: ::c_int = 43; -pub const EL2HLT: ::c_int = 44; -pub const EBADE: ::c_int = 50; -pub const EBADR: ::c_int = 51; -pub const EXFULL: ::c_int = 52; -pub const ENOANO: ::c_int = 53; -pub const EBADRQC: ::c_int = 54; -pub const EBADSLT: ::c_int = 55; -pub const EDEADLOCK: ::c_int = 56; -pub const EMULTIHOP: ::c_int = 74; -pub const EOVERFLOW: ::c_int = 79; -pub const ENOTUNIQ: ::c_int = 80; -pub const EBADFD: ::c_int = 81; -pub const EBADMSG: ::c_int = 77; -pub const EREMCHG: ::c_int = 82; -pub const ELIBACC: ::c_int = 83; -pub const ELIBBAD: ::c_int = 84; -pub const ELIBSCN: ::c_int = 85; -pub const ELIBMAX: ::c_int = 86; -pub const ELIBEXEC: ::c_int = 87; -pub const EILSEQ: ::c_int = 88; -pub const ERESTART: ::c_int = 91; -pub const ESTRPIPE: ::c_int = 92; -pub const EUSERS: ::c_int = 94; -pub const ENOTSOCK: ::c_int = 95; -pub const EDESTADDRREQ: ::c_int = 96; -pub const EMSGSIZE: ::c_int = 97; -pub const EPROTOTYPE: ::c_int = 98; -pub const ENOPROTOOPT: ::c_int = 99; -pub const EPROTONOSUPPORT: ::c_int = 120; -pub const ESOCKTNOSUPPORT: ::c_int = 121; -pub const EOPNOTSUPP: ::c_int = 122; -pub const ENOTSUP: ::c_int = EOPNOTSUPP; -pub const EPFNOSUPPORT: ::c_int = 123; -pub const EAFNOSUPPORT: ::c_int = 124; -pub const EADDRINUSE: ::c_int = 125; -pub const EADDRNOTAVAIL: ::c_int = 126; -pub const ENETDOWN: ::c_int = 127; -pub const ENETUNREACH: ::c_int = 128; -pub const ENETRESET: ::c_int = 129; -pub const ECONNABORTED: ::c_int = 130; -pub const ECONNRESET: ::c_int = 131; -pub const ENOBUFS: ::c_int = 132; -pub const EISCONN: ::c_int = 133; -pub const ENOTCONN: ::c_int = 134; -pub const ESHUTDOWN: ::c_int = 143; -pub const ETOOMANYREFS: ::c_int = 144; -pub const ETIMEDOUT: ::c_int = 145; -pub const ECONNREFUSED: ::c_int = 146; -pub const EHOSTDOWN: ::c_int = 147; -pub const EHOSTUNREACH: ::c_int = 148; -pub const EALREADY: ::c_int = 149; -pub const EINPROGRESS: ::c_int = 150; -pub const ESTALE: ::c_int = 151; -pub const EUCLEAN: ::c_int = 135; -pub const ENOTNAM: ::c_int = 137; -pub const ENAVAIL: ::c_int = 138; -pub const EISNAM: ::c_int = 139; -pub const EREMOTEIO: ::c_int = 140; -pub const EDQUOT: ::c_int = 1133; -pub const ENOMEDIUM: ::c_int = 159; -pub const EMEDIUMTYPE: ::c_int = 160; -pub const ECANCELED: ::c_int = 158; -pub const ENOKEY: ::c_int = 161; -pub const EKEYEXPIRED: ::c_int = 162; -pub const EKEYREVOKED: ::c_int = 163; -pub const EKEYREJECTED: ::c_int = 164; -pub const EOWNERDEAD: ::c_int = 165; -pub const ENOTRECOVERABLE: ::c_int = 166; -pub const EHWPOISON: ::c_int = 168; -pub const ERFKILL: ::c_int = 167; - -pub const SOCK_STREAM: ::c_int = 2; -pub const SOCK_DGRAM: ::c_int = 1; -pub const SOCK_SEQPACKET: ::c_int = 5; - -pub const SOL_SOCKET: ::c_int = 65535; - -pub const SO_REUSEADDR: ::c_int = 0x0004; -pub const SO_KEEPALIVE: ::c_int = 0x0008; -pub const SO_DONTROUTE: ::c_int = 0x0010; -pub const SO_BROADCAST: ::c_int = 0x0020; -pub const SO_LINGER: ::c_int = 0x0080; -pub const SO_OOBINLINE: ::c_int = 0x0100; -pub const SO_REUSEPORT: ::c_int = 0x0200; -pub const SO_SNDBUF: ::c_int = 0x1001; -pub const SO_RCVBUF: ::c_int = 0x1002; -pub const SO_SNDLOWAT: ::c_int = 0x1003; -pub const SO_RCVLOWAT: ::c_int = 0x1004; -pub const SO_RCVTIMEO: ::c_int = 0x1006; -pub const SO_SNDTIMEO: ::c_int = 0x1005; -pub const SO_ERROR: ::c_int = 0x1007; -pub const SO_TYPE: ::c_int = 0x1008; -pub const SO_ACCEPTCONN: ::c_int = 0x1009; -pub const SO_PROTOCOL: ::c_int = 0x1028; -pub const SO_DOMAIN: ::c_int = 0x1029; -pub const SO_NO_CHECK: ::c_int = 11; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_PASSCRED: ::c_int = 17; -pub const SO_PEERCRED: ::c_int = 18; -pub const SO_SNDBUFFORCE: ::c_int = 31; -pub const SO_RCVBUFFORCE: ::c_int = 33; - -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 8; -pub const SA_NOCLDWAIT: ::c_int = 0x10000; - -pub const SIGCHLD: ::c_int = 18; -pub const SIGBUS: ::c_int = 10; -pub const SIGTTIN: ::c_int = 26; -pub const SIGTTOU: ::c_int = 27; -pub const SIGXCPU: ::c_int = 30; -pub const SIGXFSZ: ::c_int = 31; -pub const SIGVTALRM: ::c_int = 28; -pub const SIGPROF: ::c_int = 29; -pub const SIGWINCH: ::c_int = 20; -pub const SIGUSR1: ::c_int = 16; -pub const SIGUSR2: ::c_int = 17; -pub const SIGCONT: ::c_int = 25; -pub const SIGSTOP: ::c_int = 23; -pub const SIGTSTP: ::c_int = 24; -pub const SIGURG: ::c_int = 21; -pub const SIGIO: ::c_int = 22; -pub const SIGSYS: ::c_int = 12; -pub const SIGSTKFLT: ::c_int = 7; -pub const SIGPOLL: ::c_int = ::SIGIO; -pub const SIGPWR: ::c_int = 19; -pub const SIG_SETMASK: ::c_int = 3; -pub const SIG_BLOCK: ::c_int = 1; -pub const SIG_UNBLOCK: ::c_int = 2; - -pub const EXTPROC: ::tcflag_t = 0o200000; - -pub const MAP_HUGETLB: ::c_int = 0x80000; - -pub const F_GETLK: ::c_int = 33; -pub const F_GETOWN: ::c_int = 23; -pub const F_SETLK: ::c_int = 34; -pub const F_SETLKW: ::c_int = 35; -pub const F_SETOWN: ::c_int = 24; - -pub const VEOF: usize = 16; -pub const VEOL: usize = 17; -pub const VEOL2: usize = 6; -pub const VMIN: usize = 4; -pub const IEXTEN: ::tcflag_t = 0o000400; -pub const TOSTOP: ::tcflag_t = 0o100000; -pub const FLUSHO: ::tcflag_t = 0o020000; - -pub const TCGETS: ::c_int = 0x540D; -pub const TCSETS: ::c_int = 0x540E; -pub const TCSETSW: ::c_int = 0x540F; -pub const TCSETSF: ::c_int = 0x5410; -pub const TCGETA: ::c_int = 0x5401; -pub const TCSETA: ::c_int = 0x5402; -pub const TCSETAW: ::c_int = 0x5403; -pub const TCSETAF: ::c_int = 0x5404; -pub const TCSBRK: ::c_int = 0x5405; -pub const TCXONC: ::c_int = 0x5406; -pub const TCFLSH: ::c_int = 0x5407; -pub const TIOCGSOFTCAR: ::c_int = 0x5481; -pub const TIOCSSOFTCAR: ::c_int = 0x5482; -pub const TIOCLINUX: ::c_int = 0x5483; -pub const TIOCGSERIAL: ::c_int = 0x5484; -pub const TIOCEXCL: ::c_int = 0x740D; -pub const TIOCNXCL: ::c_int = 0x740E; -pub const TIOCSCTTY: ::c_int = 0x5480; -pub const TIOCGPGRP: ::c_int = 0x40047477; -pub const TIOCSPGRP: ::c_int = 0x80047476; -pub const TIOCOUTQ: ::c_int = 0x7472; -pub const TIOCSTI: ::c_int = 0x5472; -pub const TIOCGWINSZ: ::c_int = 0x40087468; -pub const TIOCSWINSZ: ::c_int = 0x80087467; -pub const TIOCMGET: ::c_int = 0x741D; -pub const TIOCMBIS: ::c_int = 0x741B; -pub const TIOCMBIC: ::c_int = 0x741C; -pub const TIOCMSET: ::c_int = 0x741A; -pub const FIONREAD: ::c_int = 0x467F; -pub const TIOCCONS: ::c_int = 0x80047478; - -pub const POLLWRNORM: ::c_short = 0x4; -pub const POLLWRBAND: ::c_short = 0x100; - -pub const TIOCM_LE: ::c_int = 0x001; -pub const TIOCM_DTR: ::c_int = 0x002; -pub const TIOCM_RTS: ::c_int = 0x004; -pub const TIOCM_ST: ::c_int = 0x010; -pub const TIOCM_SR: ::c_int = 0x020; -pub const TIOCM_CTS: ::c_int = 0x040; -pub const TIOCM_CAR: ::c_int = 0x100; -pub const TIOCM_CD: ::c_int = TIOCM_CAR; -pub const TIOCM_RNG: ::c_int = 0x200; -pub const TIOCM_RI: ::c_int = TIOCM_RNG; -pub const TIOCM_DSR: ::c_int = 0x400; - -pub const SYS_syscall: ::c_long = 4000 + 0; -pub const SYS_exit: ::c_long = 4000 + 1; -pub const SYS_fork: ::c_long = 4000 + 2; -pub const SYS_read: ::c_long = 4000 + 3; -pub const SYS_write: ::c_long = 4000 + 4; -pub const SYS_open: ::c_long = 4000 + 5; -pub const SYS_close: ::c_long = 4000 + 6; -pub const SYS_waitpid: ::c_long = 4000 + 7; -pub const SYS_creat: ::c_long = 4000 + 8; -pub const SYS_link: ::c_long = 4000 + 9; -pub const SYS_unlink: ::c_long = 4000 + 10; -pub const SYS_execve: ::c_long = 4000 + 11; -pub const SYS_chdir: ::c_long = 4000 + 12; -pub const SYS_time: ::c_long = 4000 + 13; -pub const SYS_mknod: ::c_long = 4000 + 14; -pub const SYS_chmod: ::c_long = 4000 + 15; -pub const SYS_lchown: ::c_long = 4000 + 16; -pub const SYS_break: ::c_long = 4000 + 17; -pub const SYS_unused18: ::c_long = 4000 + 18; -pub const SYS_lseek: ::c_long = 4000 + 19; -pub const SYS_getpid: ::c_long = 4000 + 20; -pub const SYS_mount: ::c_long = 4000 + 21; -pub const SYS_umount: ::c_long = 4000 + 22; -pub const SYS_setuid: ::c_long = 4000 + 23; -pub const SYS_getuid: ::c_long = 4000 + 24; -pub const SYS_stime: ::c_long = 4000 + 25; -pub const SYS_ptrace: ::c_long = 4000 + 26; -pub const SYS_alarm: ::c_long = 4000 + 27; -pub const SYS_unused28: ::c_long = 4000 + 28; -pub const SYS_pause: ::c_long = 4000 + 29; -pub const SYS_utime: ::c_long = 4000 + 30; -pub const SYS_stty: ::c_long = 4000 + 31; -pub const SYS_gtty: ::c_long = 4000 + 32; -pub const SYS_access: ::c_long = 4000 + 33; -pub const SYS_nice: ::c_long = 4000 + 34; -pub const SYS_ftime: ::c_long = 4000 + 35; -pub const SYS_sync: ::c_long = 4000 + 36; -pub const SYS_kill: ::c_long = 4000 + 37; -pub const SYS_rename: ::c_long = 4000 + 38; -pub const SYS_mkdir: ::c_long = 4000 + 39; -pub const SYS_rmdir: ::c_long = 4000 + 40; -pub const SYS_dup: ::c_long = 4000 + 41; -pub const SYS_pipe: ::c_long = 4000 + 42; -pub const SYS_times: ::c_long = 4000 + 43; -pub const SYS_prof: ::c_long = 4000 + 44; -pub const SYS_brk: ::c_long = 4000 + 45; -pub const SYS_setgid: ::c_long = 4000 + 46; -pub const SYS_getgid: ::c_long = 4000 + 47; -pub const SYS_signal: ::c_long = 4000 + 48; -pub const SYS_geteuid: ::c_long = 4000 + 49; -pub const SYS_getegid: ::c_long = 4000 + 50; -pub const SYS_acct: ::c_long = 4000 + 51; -pub const SYS_umount2: ::c_long = 4000 + 52; -pub const SYS_lock: ::c_long = 4000 + 53; -pub const SYS_ioctl: ::c_long = 4000 + 54; -pub const SYS_fcntl: ::c_long = 4000 + 55; -pub const SYS_mpx: ::c_long = 4000 + 56; -pub const SYS_setpgid: ::c_long = 4000 + 57; -pub const SYS_ulimit: ::c_long = 4000 + 58; -pub const SYS_unused59: ::c_long = 4000 + 59; -pub const SYS_umask: ::c_long = 4000 + 60; -pub const SYS_chroot: ::c_long = 4000 + 61; -pub const SYS_ustat: ::c_long = 4000 + 62; -pub const SYS_dup2: ::c_long = 4000 + 63; -pub const SYS_getppid: ::c_long = 4000 + 64; -pub const SYS_getpgrp: ::c_long = 4000 + 65; -pub const SYS_setsid: ::c_long = 4000 + 66; -pub const SYS_sigaction: ::c_long = 4000 + 67; -pub const SYS_sgetmask: ::c_long = 4000 + 68; -pub const SYS_ssetmask: ::c_long = 4000 + 69; -pub const SYS_setreuid: ::c_long = 4000 + 70; -pub const SYS_setregid: ::c_long = 4000 + 71; -pub const SYS_sigsuspend: ::c_long = 4000 + 72; -pub const SYS_sigpending: ::c_long = 4000 + 73; -pub const SYS_sethostname: ::c_long = 4000 + 74; -pub const SYS_setrlimit: ::c_long = 4000 + 75; -pub const SYS_getrlimit: ::c_long = 4000 + 76; -pub const SYS_getrusage: ::c_long = 4000 + 77; -pub const SYS_gettimeofday: ::c_long = 4000 + 78; -pub const SYS_settimeofday: ::c_long = 4000 + 79; -pub const SYS_getgroups: ::c_long = 4000 + 80; -pub const SYS_setgroups: ::c_long = 4000 + 81; -pub const SYS_reserved82: ::c_long = 4000 + 82; -pub const SYS_symlink: ::c_long = 4000 + 83; -pub const SYS_unused84: ::c_long = 4000 + 84; -pub const SYS_readlink: ::c_long = 4000 + 85; -pub const SYS_uselib: ::c_long = 4000 + 86; -pub const SYS_swapon: ::c_long = 4000 + 87; -pub const SYS_reboot: ::c_long = 4000 + 88; -pub const SYS_readdir: ::c_long = 4000 + 89; -pub const SYS_mmap: ::c_long = 4000 + 90; -pub const SYS_munmap: ::c_long = 4000 + 91; -pub const SYS_truncate: ::c_long = 4000 + 92; -pub const SYS_ftruncate: ::c_long = 4000 + 93; -pub const SYS_fchmod: ::c_long = 4000 + 94; -pub const SYS_fchown: ::c_long = 4000 + 95; -pub const SYS_getpriority: ::c_long = 4000 + 96; -pub const SYS_setpriority: ::c_long = 4000 + 97; -pub const SYS_profil: ::c_long = 4000 + 98; -pub const SYS_statfs: ::c_long = 4000 + 99; -pub const SYS_fstatfs: ::c_long = 4000 + 100; -pub const SYS_ioperm: ::c_long = 4000 + 101; -pub const SYS_socketcall: ::c_long = 4000 + 102; -pub const SYS_syslog: ::c_long = 4000 + 103; -pub const SYS_setitimer: ::c_long = 4000 + 104; -pub const SYS_getitimer: ::c_long = 4000 + 105; -pub const SYS_stat: ::c_long = 4000 + 106; -pub const SYS_lstat: ::c_long = 4000 + 107; -pub const SYS_fstat: ::c_long = 4000 + 108; -pub const SYS_unused109: ::c_long = 4000 + 109; -pub const SYS_iopl: ::c_long = 4000 + 110; -pub const SYS_vhangup: ::c_long = 4000 + 111; -pub const SYS_idle: ::c_long = 4000 + 112; -pub const SYS_vm86: ::c_long = 4000 + 113; -pub const SYS_wait4: ::c_long = 4000 + 114; -pub const SYS_swapoff: ::c_long = 4000 + 115; -pub const SYS_sysinfo: ::c_long = 4000 + 116; -pub const SYS_ipc: ::c_long = 4000 + 117; -pub const SYS_fsync: ::c_long = 4000 + 118; -pub const SYS_sigreturn: ::c_long = 4000 + 119; -pub const SYS_clone: ::c_long = 4000 + 120; -pub const SYS_setdomainname: ::c_long = 4000 + 121; -pub const SYS_uname: ::c_long = 4000 + 122; -pub const SYS_modify_ldt: ::c_long = 4000 + 123; -pub const SYS_adjtimex: ::c_long = 4000 + 124; -pub const SYS_mprotect: ::c_long = 4000 + 125; -pub const SYS_sigprocmask: ::c_long = 4000 + 126; -pub const SYS_create_module: ::c_long = 4000 + 127; -pub const SYS_init_module: ::c_long = 4000 + 128; -pub const SYS_delete_module: ::c_long = 4000 + 129; -pub const SYS_get_kernel_syms: ::c_long = 4000 + 130; -pub const SYS_quotactl: ::c_long = 4000 + 131; -pub const SYS_getpgid: ::c_long = 4000 + 132; -pub const SYS_fchdir: ::c_long = 4000 + 133; -pub const SYS_bdflush: ::c_long = 4000 + 134; -pub const SYS_sysfs: ::c_long = 4000 + 135; -pub const SYS_personality: ::c_long = 4000 + 136; -pub const SYS_afs_syscall: ::c_long = 4000 + 137; -pub const SYS_setfsuid: ::c_long = 4000 + 138; -pub const SYS_setfsgid: ::c_long = 4000 + 139; -pub const SYS__llseek: ::c_long = 4000 + 140; -pub const SYS_getdents: ::c_long = 4000 + 141; -pub const SYS_flock: ::c_long = 4000 + 143; -pub const SYS_msync: ::c_long = 4000 + 144; -pub const SYS_readv: ::c_long = 4000 + 145; -pub const SYS_writev: ::c_long = 4000 + 146; -pub const SYS_cacheflush: ::c_long = 4000 + 147; -pub const SYS_cachectl: ::c_long = 4000 + 148; -pub const SYS_sysmips: ::c_long = 4000 + 149; -pub const SYS_unused150: ::c_long = 4000 + 150; -pub const SYS_getsid: ::c_long = 4000 + 151; -pub const SYS_fdatasync: ::c_long = 4000 + 152; -pub const SYS__sysctl: ::c_long = 4000 + 153; -pub const SYS_mlock: ::c_long = 4000 + 154; -pub const SYS_munlock: ::c_long = 4000 + 155; -pub const SYS_mlockall: ::c_long = 4000 + 156; -pub const SYS_munlockall: ::c_long = 4000 + 157; -pub const SYS_sched_setparam: ::c_long = 4000 + 158; -pub const SYS_sched_getparam: ::c_long = 4000 + 159; -pub const SYS_sched_setscheduler: ::c_long = 4000 + 160; -pub const SYS_sched_getscheduler: ::c_long = 4000 + 161; -pub const SYS_sched_yield: ::c_long = 4000 + 162; -pub const SYS_sched_get_priority_max: ::c_long = 4000 + 163; -pub const SYS_sched_get_priority_min: ::c_long = 4000 + 164; -pub const SYS_sched_rr_get_interval: ::c_long = 4000 + 165; -pub const SYS_nanosleep: ::c_long = 4000 + 166; -pub const SYS_mremap: ::c_long = 4000 + 167; -pub const SYS_accept: ::c_long = 4000 + 168; -pub const SYS_bind: ::c_long = 4000 + 169; -pub const SYS_connect: ::c_long = 4000 + 170; -pub const SYS_getpeername: ::c_long = 4000 + 171; -pub const SYS_getsockname: ::c_long = 4000 + 172; -pub const SYS_getsockopt: ::c_long = 4000 + 173; -pub const SYS_listen: ::c_long = 4000 + 174; -pub const SYS_recv: ::c_long = 4000 + 175; -pub const SYS_recvfrom: ::c_long = 4000 + 176; -pub const SYS_recvmsg: ::c_long = 4000 + 177; -pub const SYS_send: ::c_long = 4000 + 178; -pub const SYS_sendmsg: ::c_long = 4000 + 179; -pub const SYS_sendto: ::c_long = 4000 + 180; -pub const SYS_setsockopt: ::c_long = 4000 + 181; -pub const SYS_shutdown: ::c_long = 4000 + 182; -pub const SYS_socket: ::c_long = 4000 + 183; -pub const SYS_socketpair: ::c_long = 4000 + 184; -pub const SYS_setresuid: ::c_long = 4000 + 185; -pub const SYS_getresuid: ::c_long = 4000 + 186; -pub const SYS_query_module: ::c_long = 4000 + 187; -pub const SYS_poll: ::c_long = 4000 + 188; -pub const SYS_nfsservctl: ::c_long = 4000 + 189; -pub const SYS_setresgid: ::c_long = 4000 + 190; -pub const SYS_getresgid: ::c_long = 4000 + 191; -pub const SYS_prctl: ::c_long = 4000 + 192; -pub const SYS_rt_sigreturn: ::c_long = 4000 + 193; -pub const SYS_rt_sigaction: ::c_long = 4000 + 194; -pub const SYS_rt_sigprocmask: ::c_long = 4000 + 195; -pub const SYS_rt_sigpending: ::c_long = 4000 + 196; -pub const SYS_rt_sigtimedwait: ::c_long = 4000 + 197; -pub const SYS_rt_sigqueueinfo: ::c_long = 4000 + 198; -pub const SYS_rt_sigsuspend: ::c_long = 4000 + 199; -pub const SYS_chown: ::c_long = 4000 + 202; -pub const SYS_getcwd: ::c_long = 4000 + 203; -pub const SYS_capget: ::c_long = 4000 + 204; -pub const SYS_capset: ::c_long = 4000 + 205; -pub const SYS_sigaltstack: ::c_long = 4000 + 206; -pub const SYS_sendfile: ::c_long = 4000 + 207; -pub const SYS_getpmsg: ::c_long = 4000 + 208; -pub const SYS_putpmsg: ::c_long = 4000 + 209; -pub const SYS_mmap2: ::c_long = 4000 + 210; -pub const SYS_truncate64: ::c_long = 4000 + 211; -pub const SYS_ftruncate64: ::c_long = 4000 + 212; -pub const SYS_stat64: ::c_long = 4000 + 213; -pub const SYS_lstat64: ::c_long = 4000 + 214; -pub const SYS_fstat64: ::c_long = 4000 + 215; -pub const SYS_pivot_root: ::c_long = 4000 + 216; -pub const SYS_mincore: ::c_long = 4000 + 217; -pub const SYS_madvise: ::c_long = 4000 + 218; -pub const SYS_getdents64: ::c_long = 4000 + 219; -pub const SYS_fcntl64: ::c_long = 4000 + 220; -pub const SYS_reserved221: ::c_long = 4000 + 221; -pub const SYS_gettid: ::c_long = 4000 + 222; -pub const SYS_readahead: ::c_long = 4000 + 223; -pub const SYS_setxattr: ::c_long = 4000 + 224; -pub const SYS_lsetxattr: ::c_long = 4000 + 225; -pub const SYS_fsetxattr: ::c_long = 4000 + 226; -pub const SYS_getxattr: ::c_long = 4000 + 227; -pub const SYS_lgetxattr: ::c_long = 4000 + 228; -pub const SYS_fgetxattr: ::c_long = 4000 + 229; -pub const SYS_listxattr: ::c_long = 4000 + 230; -pub const SYS_llistxattr: ::c_long = 4000 + 231; -pub const SYS_flistxattr: ::c_long = 4000 + 232; -pub const SYS_removexattr: ::c_long = 4000 + 233; -pub const SYS_lremovexattr: ::c_long = 4000 + 234; -pub const SYS_fremovexattr: ::c_long = 4000 + 235; -pub const SYS_tkill: ::c_long = 4000 + 236; -pub const SYS_sendfile64: ::c_long = 4000 + 237; -pub const SYS_futex: ::c_long = 4000 + 238; -pub const SYS_sched_setaffinity: ::c_long = 4000 + 239; -pub const SYS_sched_getaffinity: ::c_long = 4000 + 240; -pub const SYS_io_setup: ::c_long = 4000 + 241; -pub const SYS_io_destroy: ::c_long = 4000 + 242; -pub const SYS_io_getevents: ::c_long = 4000 + 243; -pub const SYS_io_submit: ::c_long = 4000 + 244; -pub const SYS_io_cancel: ::c_long = 4000 + 245; -pub const SYS_exit_group: ::c_long = 4000 + 246; -pub const SYS_lookup_dcookie: ::c_long = 4000 + 247; -pub const SYS_epoll_create: ::c_long = 4000 + 248; -pub const SYS_epoll_ctl: ::c_long = 4000 + 249; -pub const SYS_epoll_wait: ::c_long = 4000 + 250; -pub const SYS_remap_file_pages: ::c_long = 4000 + 251; -pub const SYS_set_tid_address: ::c_long = 4000 + 252; -pub const SYS_restart_syscall: ::c_long = 4000 + 253; -pub const SYS_statfs64: ::c_long = 4000 + 255; -pub const SYS_fstatfs64: ::c_long = 4000 + 256; -pub const SYS_timer_create: ::c_long = 4000 + 257; -pub const SYS_timer_settime: ::c_long = 4000 + 258; -pub const SYS_timer_gettime: ::c_long = 4000 + 259; -pub const SYS_timer_getoverrun: ::c_long = 4000 + 260; -pub const SYS_timer_delete: ::c_long = 4000 + 261; -pub const SYS_clock_settime: ::c_long = 4000 + 262; -pub const SYS_clock_gettime: ::c_long = 4000 + 263; -pub const SYS_clock_getres: ::c_long = 4000 + 264; -pub const SYS_clock_nanosleep: ::c_long = 4000 + 265; -pub const SYS_tgkill: ::c_long = 4000 + 266; -pub const SYS_utimes: ::c_long = 4000 + 267; -pub const SYS_mbind: ::c_long = 4000 + 268; -pub const SYS_get_mempolicy: ::c_long = 4000 + 269; -pub const SYS_set_mempolicy: ::c_long = 4000 + 270; -pub const SYS_mq_open: ::c_long = 4000 + 271; -pub const SYS_mq_unlink: ::c_long = 4000 + 272; -pub const SYS_mq_timedsend: ::c_long = 4000 + 273; -pub const SYS_mq_timedreceive: ::c_long = 4000 + 274; -pub const SYS_mq_notify: ::c_long = 4000 + 275; -pub const SYS_mq_getsetattr: ::c_long = 4000 + 276; -pub const SYS_vserver: ::c_long = 4000 + 277; -pub const SYS_waitid: ::c_long = 4000 + 278; -/* pub const SYS_sys_setaltroot: ::c_long = 4000 + 279; */ -pub const SYS_add_key: ::c_long = 4000 + 280; -pub const SYS_request_key: ::c_long = 4000 + 281; -pub const SYS_keyctl: ::c_long = 4000 + 282; -pub const SYS_set_thread_area: ::c_long = 4000 + 283; -pub const SYS_inotify_init: ::c_long = 4000 + 284; -pub const SYS_inotify_add_watch: ::c_long = 4000 + 285; -pub const SYS_inotify_rm_watch: ::c_long = 4000 + 286; -pub const SYS_migrate_pages: ::c_long = 4000 + 287; -pub const SYS_openat: ::c_long = 4000 + 288; -pub const SYS_mkdirat: ::c_long = 4000 + 289; -pub const SYS_mknodat: ::c_long = 4000 + 290; -pub const SYS_fchownat: ::c_long = 4000 + 291; -pub const SYS_futimesat: ::c_long = 4000 + 292; -pub const SYS_unlinkat: ::c_long = 4000 + 294; -pub const SYS_renameat: ::c_long = 4000 + 295; -pub const SYS_linkat: ::c_long = 4000 + 296; -pub const SYS_symlinkat: ::c_long = 4000 + 297; -pub const SYS_readlinkat: ::c_long = 4000 + 298; -pub const SYS_fchmodat: ::c_long = 4000 + 299; -pub const SYS_faccessat: ::c_long = 4000 + 300; -pub const SYS_pselect6: ::c_long = 4000 + 301; -pub const SYS_ppoll: ::c_long = 4000 + 302; -pub const SYS_unshare: ::c_long = 4000 + 303; -pub const SYS_splice: ::c_long = 4000 + 304; -pub const SYS_sync_file_range: ::c_long = 4000 + 305; -pub const SYS_tee: ::c_long = 4000 + 306; -pub const SYS_vmsplice: ::c_long = 4000 + 307; -pub const SYS_move_pages: ::c_long = 4000 + 308; -pub const SYS_set_robust_list: ::c_long = 4000 + 309; -pub const SYS_get_robust_list: ::c_long = 4000 + 310; -pub const SYS_kexec_load: ::c_long = 4000 + 311; -pub const SYS_getcpu: ::c_long = 4000 + 312; -pub const SYS_epoll_pwait: ::c_long = 4000 + 313; -pub const SYS_ioprio_set: ::c_long = 4000 + 314; -pub const SYS_ioprio_get: ::c_long = 4000 + 315; -pub const SYS_utimensat: ::c_long = 4000 + 316; -pub const SYS_signalfd: ::c_long = 4000 + 317; -pub const SYS_timerfd: ::c_long = 4000 + 318; -pub const SYS_eventfd: ::c_long = 4000 + 319; -pub const SYS_fallocate: ::c_long = 4000 + 320; -pub const SYS_timerfd_create: ::c_long = 4000 + 321; -pub const SYS_timerfd_gettime: ::c_long = 4000 + 322; -pub const SYS_timerfd_settime: ::c_long = 4000 + 323; -pub const SYS_signalfd4: ::c_long = 4000 + 324; -pub const SYS_eventfd2: ::c_long = 4000 + 325; -pub const SYS_epoll_create1: ::c_long = 4000 + 326; -pub const SYS_dup3: ::c_long = 4000 + 327; -pub const SYS_pipe2: ::c_long = 4000 + 328; -pub const SYS_inotify_init1: ::c_long = 4000 + 329; -pub const SYS_preadv: ::c_long = 4000 + 330; -pub const SYS_pwritev: ::c_long = 4000 + 331; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 4000 + 332; -pub const SYS_perf_event_open: ::c_long = 4000 + 333; -pub const SYS_accept4: ::c_long = 4000 + 334; -pub const SYS_recvmmsg: ::c_long = 4000 + 335; -pub const SYS_fanotify_init: ::c_long = 4000 + 336; -pub const SYS_fanotify_mark: ::c_long = 4000 + 337; -pub const SYS_prlimit64: ::c_long = 4000 + 338; -pub const SYS_name_to_handle_at: ::c_long = 4000 + 339; -pub const SYS_open_by_handle_at: ::c_long = 4000 + 340; -pub const SYS_clock_adjtime: ::c_long = 4000 + 341; -pub const SYS_syncfs: ::c_long = 4000 + 342; -pub const SYS_sendmmsg: ::c_long = 4000 + 343; -pub const SYS_setns: ::c_long = 4000 + 344; -pub const SYS_process_vm_readv: ::c_long = 4000 + 345; -pub const SYS_process_vm_writev: ::c_long = 4000 + 346; -pub const SYS_kcmp: ::c_long = 4000 + 347; -pub const SYS_finit_module: ::c_long = 4000 + 348; -pub const SYS_sched_setattr: ::c_long = 4000 + 349; -pub const SYS_sched_getattr: ::c_long = 4000 + 350; -pub const SYS_renameat2: ::c_long = 4000 + 351; -pub const SYS_seccomp: ::c_long = 4000 + 352; -pub const SYS_getrandom: ::c_long = 4000 + 353; -pub const SYS_memfd_create: ::c_long = 4000 + 354; -pub const SYS_bpf: ::c_long = 4000 + 355; -pub const SYS_execveat: ::c_long = 4000 + 356; -pub const SYS_userfaultfd: ::c_long = 4000 + 357; -pub const SYS_membarrier: ::c_long = 4000 + 358; -pub const SYS_mlock2: ::c_long = 4000 + 359; -pub const SYS_copy_file_range: ::c_long = 4000 + 360; -pub const SYS_preadv2: ::c_long = 4000 + 361; -pub const SYS_pwritev2: ::c_long = 4000 + 362; - -#[doc(hidden)] -pub const AF_MAX: ::c_int = 42; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -pub type c_long = i32; -pub type c_ulong = u32; -pub type nlink_t = u32; -pub type blksize_t = ::c_long; -pub type __u64 = ::c_ulonglong; - -s! { - pub struct pthread_attr_t { - __size: [u32; 9] - } - - pub struct sigset_t { - __val: [::c_ulong; 32], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::c_int, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::socklen_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::socklen_t, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct sem_t { - __val: [::c_int; 4], - } - - pub struct ipc_perm { - pub __ipc_perm_key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::mode_t, - pub __seq: ::c_int, - __unused1: ::c_long, - __unused2: ::c_long - } -} - -pub const SIGSTKSZ: ::size_t = 8192; -pub const MINSIGSTKSZ: ::size_t = 2048; - -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 32; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 24; - -cfg_if! { - if #[cfg(any(target_arch = "x86"))] { - mod x86; - pub use self::x86::*; - } else if #[cfg(any(target_arch = "mips"))] { - mod mips; - pub use self::mips::*; - } else if #[cfg(any(target_arch = "arm"))] { - mod arm; - pub use self::arm::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/x86.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/x86.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/x86.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b32/x86.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,816 +0,0 @@ -pub type c_char = i8; -pub type wchar_t = i32; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - __st_dev_padding: ::c_int, - __st_ino_truncated: ::c_long, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __st_rdev_padding: ::c_int, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_ino: ::ino_t, - } - - pub struct stat64 { - pub st_dev: ::dev_t, - __st_dev_padding: ::c_int, - __st_ino_truncated: ::c_long, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __st_rdev_padding: ::c_int, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_ino: ::ino_t, - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_flags: ::c_int, - pub ss_size: ::size_t - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - __unused1: ::c_int, - pub shm_dtime: ::time_t, - __unused2: ::c_int, - pub shm_ctime: ::time_t, - __unused3: ::c_int, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::c_ulong, - __pad1: ::c_ulong, - __pad2: ::c_ulong, - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - pub msg_stime: ::time_t, - __unused1: ::c_int, - pub msg_rtime: ::time_t, - __unused2: ::c_int, - pub msg_ctime: ::time_t, - __unused3: ::c_int, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __pad1: ::c_ulong, - __pad2: ::c_ulong, - } - - pub struct statfs { - pub f_type: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_flags: ::c_ulong, - pub f_spare: [::c_ulong; 4], - } - - pub struct mcontext_t { - __private: [u32; 22] - } - - pub struct ucontext_t { - pub uc_flags: ::c_ulong, - pub uc_link: *mut ucontext_t, - pub uc_stack: ::stack_t, - pub uc_mcontext: mcontext_t, - pub uc_sigmask: ::sigset_t, - __private: [u8; 112], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_errno: ::c_int, - pub si_code: ::c_int, - pub _pad: [::c_int; 29], - _align: [usize; 0], - } - - pub struct statfs64 { - pub f_type: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_flags: ::c_ulong, - pub f_spare: [::c_ulong; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - __f_unused: ::c_int, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 19], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } -} - -pub const O_DIRECT: ::c_int = 0x4000; -pub const O_DIRECTORY: ::c_int = 0x10000; -pub const O_NOFOLLOW: ::c_int = 0x20000; -pub const O_ASYNC: ::c_int = 0x2000; -pub const O_LARGEFILE: ::c_int = 0o0100000; - -pub const FIOCLEX: ::c_int = 0x5451; -pub const FIONBIO: ::c_int = 0x5421; - -pub const RLIMIT_RSS: ::c_int = 5; -pub const RLIMIT_NOFILE: ::c_int = 7; -pub const RLIMIT_AS: ::c_int = 9; -pub const RLIMIT_NPROC: ::c_int = 6; -pub const RLIMIT_MEMLOCK: ::c_int = 8; - -pub const O_APPEND: ::c_int = 1024; -pub const O_CREAT: ::c_int = 64; -pub const O_EXCL: ::c_int = 128; -pub const O_NOCTTY: ::c_int = 256; -pub const O_NONBLOCK: ::c_int = 2048; -pub const O_SYNC: ::c_int = 1052672; -pub const O_RSYNC: ::c_int = 1052672; -pub const O_DSYNC: ::c_int = 4096; - -pub const SOCK_NONBLOCK: ::c_int = 2048; - -pub const MAP_ANON: ::c_int = 0x0020; -pub const MAP_GROWSDOWN: ::c_int = 0x0100; -pub const MAP_DENYWRITE: ::c_int = 0x0800; -pub const MAP_EXECUTABLE: ::c_int = 0x01000; -pub const MAP_LOCKED: ::c_int = 0x02000; -pub const MAP_NORESERVE: ::c_int = 0x04000; -pub const MAP_POPULATE: ::c_int = 0x08000; -pub const MAP_NONBLOCK: ::c_int = 0x010000; -pub const MAP_STACK: ::c_int = 0x020000; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; -pub const SOCK_SEQPACKET: ::c_int = 5; - -pub const SOL_SOCKET: ::c_int = 1; - -pub const EDEADLK: ::c_int = 35; -pub const ENAMETOOLONG: ::c_int = 36; -pub const ENOLCK: ::c_int = 37; -pub const ENOSYS: ::c_int = 38; -pub const ENOTEMPTY: ::c_int = 39; -pub const ELOOP: ::c_int = 40; -pub const ENOMSG: ::c_int = 42; -pub const EIDRM: ::c_int = 43; -pub const ECHRNG: ::c_int = 44; -pub const EL2NSYNC: ::c_int = 45; -pub const EL3HLT: ::c_int = 46; -pub const EL3RST: ::c_int = 47; -pub const ELNRNG: ::c_int = 48; -pub const EUNATCH: ::c_int = 49; -pub const ENOCSI: ::c_int = 50; -pub const EL2HLT: ::c_int = 51; -pub const EBADE: ::c_int = 52; -pub const EBADR: ::c_int = 53; -pub const EXFULL: ::c_int = 54; -pub const ENOANO: ::c_int = 55; -pub const EBADRQC: ::c_int = 56; -pub const EBADSLT: ::c_int = 57; -pub const EDEADLOCK: ::c_int = EDEADLK; -pub const EMULTIHOP: ::c_int = 72; -pub const EBADMSG: ::c_int = 74; -pub const EOVERFLOW: ::c_int = 75; -pub const ENOTUNIQ: ::c_int = 76; -pub const EBADFD: ::c_int = 77; -pub const EREMCHG: ::c_int = 78; -pub const ELIBACC: ::c_int = 79; -pub const ELIBBAD: ::c_int = 80; -pub const ELIBSCN: ::c_int = 81; -pub const ELIBMAX: ::c_int = 82; -pub const ELIBEXEC: ::c_int = 83; -pub const EILSEQ: ::c_int = 84; -pub const ERESTART: ::c_int = 85; -pub const ESTRPIPE: ::c_int = 86; -pub const EUSERS: ::c_int = 87; -pub const ENOTSOCK: ::c_int = 88; -pub const EDESTADDRREQ: ::c_int = 89; -pub const EMSGSIZE: ::c_int = 90; -pub const EPROTOTYPE: ::c_int = 91; -pub const ENOPROTOOPT: ::c_int = 92; -pub const EPROTONOSUPPORT: ::c_int = 93; -pub const ESOCKTNOSUPPORT: ::c_int = 94; -pub const EOPNOTSUPP: ::c_int = 95; -pub const ENOTSUP: ::c_int = EOPNOTSUPP; -pub const EPFNOSUPPORT: ::c_int = 96; -pub const EAFNOSUPPORT: ::c_int = 97; -pub const EADDRINUSE: ::c_int = 98; -pub const EADDRNOTAVAIL: ::c_int = 99; -pub const ENETDOWN: ::c_int = 100; -pub const ENETUNREACH: ::c_int = 101; -pub const ENETRESET: ::c_int = 102; -pub const ECONNABORTED: ::c_int = 103; -pub const ECONNRESET: ::c_int = 104; -pub const ENOBUFS: ::c_int = 105; -pub const EISCONN: ::c_int = 106; -pub const ENOTCONN: ::c_int = 107; -pub const ESHUTDOWN: ::c_int = 108; -pub const ETOOMANYREFS: ::c_int = 109; -pub const ETIMEDOUT: ::c_int = 110; -pub const ECONNREFUSED: ::c_int = 111; -pub const EHOSTDOWN: ::c_int = 112; -pub const EHOSTUNREACH: ::c_int = 113; -pub const EALREADY: ::c_int = 114; -pub const EINPROGRESS: ::c_int = 115; -pub const ESTALE: ::c_int = 116; -pub const EUCLEAN: ::c_int = 117; -pub const ENOTNAM: ::c_int = 118; -pub const ENAVAIL: ::c_int = 119; -pub const EISNAM: ::c_int = 120; -pub const EREMOTEIO: ::c_int = 121; -pub const EDQUOT: ::c_int = 122; -pub const ENOMEDIUM: ::c_int = 123; -pub const EMEDIUMTYPE: ::c_int = 124; -pub const ECANCELED: ::c_int = 125; -pub const ENOKEY: ::c_int = 126; -pub const EKEYEXPIRED: ::c_int = 127; -pub const EKEYREVOKED: ::c_int = 128; -pub const EKEYREJECTED: ::c_int = 129; -pub const EOWNERDEAD: ::c_int = 130; -pub const ENOTRECOVERABLE: ::c_int = 131; -pub const ERFKILL: ::c_int = 132; -pub const EHWPOISON: ::c_int = 133; - -pub const SO_REUSEADDR: ::c_int = 2; -pub const SO_TYPE: ::c_int = 3; -pub const SO_ERROR: ::c_int = 4; -pub const SO_DONTROUTE: ::c_int = 5; -pub const SO_BROADCAST: ::c_int = 6; -pub const SO_SNDBUF: ::c_int = 7; -pub const SO_RCVBUF: ::c_int = 8; -pub const SO_KEEPALIVE: ::c_int = 9; -pub const SO_OOBINLINE: ::c_int = 10; -pub const SO_NO_CHECK: ::c_int = 11; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_LINGER: ::c_int = 13; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_REUSEPORT: ::c_int = 15; -pub const SO_PASSCRED: ::c_int = 16; -pub const SO_PEERCRED: ::c_int = 17; -pub const SO_RCVLOWAT: ::c_int = 18; -pub const SO_SNDLOWAT: ::c_int = 19; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_SNDTIMEO: ::c_int = 21; -pub const SO_ACCEPTCONN: ::c_int = 30; -pub const SO_SNDBUFFORCE: ::c_int = 32; -pub const SO_RCVBUFFORCE: ::c_int = 33; -pub const SO_PROTOCOL: ::c_int = 38; -pub const SO_DOMAIN: ::c_int = 39; - -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 0x00000004; -pub const SA_NOCLDWAIT: ::c_int = 0x00000002; - -pub const SIGCHLD: ::c_int = 17; -pub const SIGBUS: ::c_int = 7; -pub const SIGTTIN: ::c_int = 21; -pub const SIGTTOU: ::c_int = 22; -pub const SIGXCPU: ::c_int = 24; -pub const SIGXFSZ: ::c_int = 25; -pub const SIGVTALRM: ::c_int = 26; -pub const SIGPROF: ::c_int = 27; -pub const SIGWINCH: ::c_int = 28; -pub const SIGUSR1: ::c_int = 10; -pub const SIGUSR2: ::c_int = 12; -pub const SIGCONT: ::c_int = 18; -pub const SIGSTOP: ::c_int = 19; -pub const SIGTSTP: ::c_int = 20; -pub const SIGURG: ::c_int = 23; -pub const SIGIO: ::c_int = 29; -pub const SIGSYS: ::c_int = 31; -pub const SIGSTKFLT: ::c_int = 16; -pub const SIGPOLL: ::c_int = 29; -pub const SIGPWR: ::c_int = 30; -pub const SIG_SETMASK: ::c_int = 2; -pub const SIG_BLOCK: ::c_int = 0x000000; -pub const SIG_UNBLOCK: ::c_int = 0x01; - -pub const EXTPROC: ::tcflag_t = 0x00010000; - -pub const MAP_HUGETLB: ::c_int = 0x040000; -pub const MAP_32BIT: ::c_int = 0x0040; - -pub const F_GETLK: ::c_int = 12; -pub const F_GETOWN: ::c_int = 9; -pub const F_SETLK: ::c_int = 13; -pub const F_SETLKW: ::c_int = 14; -pub const F_SETOWN: ::c_int = 8; - -pub const VEOF: usize = 4; -pub const VEOL: usize = 11; -pub const VEOL2: usize = 16; -pub const VMIN: usize = 6; -pub const IEXTEN: ::tcflag_t = 0x00008000; -pub const TOSTOP: ::tcflag_t = 0x00000100; -pub const FLUSHO: ::tcflag_t = 0x00001000; - -pub const TCGETS: ::c_int = 0x5401; -pub const TCSETS: ::c_int = 0x5402; -pub const TCSETSW: ::c_int = 0x5403; -pub const TCSETSF: ::c_int = 0x5404; -pub const TCGETA: ::c_int = 0x5405; -pub const TCSETA: ::c_int = 0x5406; -pub const TCSETAW: ::c_int = 0x5407; -pub const TCSETAF: ::c_int = 0x5408; -pub const TCSBRK: ::c_int = 0x5409; -pub const TCXONC: ::c_int = 0x540A; -pub const TCFLSH: ::c_int = 0x540B; -pub const TIOCGSOFTCAR: ::c_int = 0x5419; -pub const TIOCSSOFTCAR: ::c_int = 0x541A; -pub const TIOCLINUX: ::c_int = 0x541C; -pub const TIOCGSERIAL: ::c_int = 0x541E; -pub const TIOCEXCL: ::c_int = 0x540C; -pub const TIOCNXCL: ::c_int = 0x540D; -pub const TIOCSCTTY: ::c_int = 0x540E; -pub const TIOCGPGRP: ::c_int = 0x540F; -pub const TIOCSPGRP: ::c_int = 0x5410; -pub const TIOCOUTQ: ::c_int = 0x5411; -pub const TIOCSTI: ::c_int = 0x5412; -pub const TIOCGWINSZ: ::c_int = 0x5413; -pub const TIOCSWINSZ: ::c_int = 0x5414; -pub const TIOCMGET: ::c_int = 0x5415; -pub const TIOCMBIS: ::c_int = 0x5416; -pub const TIOCMBIC: ::c_int = 0x5417; -pub const TIOCMSET: ::c_int = 0x5418; -pub const FIONREAD: ::c_int = 0x541B; -pub const TIOCCONS: ::c_int = 0x541D; - -pub const POLLWRNORM: ::c_short = 0x100; -pub const POLLWRBAND: ::c_short = 0x200; - -pub const TIOCM_LE: ::c_int = 0x001; -pub const TIOCM_DTR: ::c_int = 0x002; -pub const TIOCM_RTS: ::c_int = 0x004; -pub const TIOCM_ST: ::c_int = 0x008; -pub const TIOCM_SR: ::c_int = 0x010; -pub const TIOCM_CTS: ::c_int = 0x020; -pub const TIOCM_CAR: ::c_int = 0x040; -pub const TIOCM_RNG: ::c_int = 0x080; -pub const TIOCM_DSR: ::c_int = 0x100; -pub const TIOCM_CD: ::c_int = TIOCM_CAR; -pub const TIOCM_RI: ::c_int = TIOCM_RNG; - -// Syscall table -pub const SYS_restart_syscall: ::c_long = 0; -pub const SYS_exit: ::c_long = 1; -pub const SYS_fork: ::c_long = 2; -pub const SYS_read: ::c_long = 3; -pub const SYS_write: ::c_long = 4; -pub const SYS_open: ::c_long = 5; -pub const SYS_close: ::c_long = 6; -pub const SYS_waitpid: ::c_long = 7; -pub const SYS_creat: ::c_long = 8; -pub const SYS_link: ::c_long = 9; -pub const SYS_unlink: ::c_long = 10; -pub const SYS_execve: ::c_long = 11; -pub const SYS_chdir: ::c_long = 12; -pub const SYS_time: ::c_long = 13; -pub const SYS_mknod: ::c_long = 14; -pub const SYS_chmod: ::c_long = 15; -pub const SYS_lchown: ::c_long = 16; -pub const SYS_break: ::c_long = 17; -pub const SYS_oldstat: ::c_long = 18; -pub const SYS_lseek: ::c_long = 19; -pub const SYS_getpid: ::c_long = 20; -pub const SYS_mount: ::c_long = 21; -pub const SYS_umount: ::c_long = 22; -pub const SYS_setuid: ::c_long = 23; -pub const SYS_getuid: ::c_long = 24; -pub const SYS_stime: ::c_long = 25; -pub const SYS_ptrace: ::c_long = 26; -pub const SYS_alarm: ::c_long = 27; -pub const SYS_oldfstat: ::c_long = 28; -pub const SYS_pause: ::c_long = 29; -pub const SYS_utime: ::c_long = 30; -pub const SYS_stty: ::c_long = 31; -pub const SYS_gtty: ::c_long = 32; -pub const SYS_access: ::c_long = 33; -pub const SYS_nice: ::c_long = 34; -pub const SYS_ftime: ::c_long = 35; -pub const SYS_sync: ::c_long = 36; -pub const SYS_kill: ::c_long = 37; -pub const SYS_rename: ::c_long = 38; -pub const SYS_mkdir: ::c_long = 39; -pub const SYS_rmdir: ::c_long = 40; -pub const SYS_dup: ::c_long = 41; -pub const SYS_pipe: ::c_long = 42; -pub const SYS_times: ::c_long = 43; -pub const SYS_prof: ::c_long = 44; -pub const SYS_brk: ::c_long = 45; -pub const SYS_setgid: ::c_long = 46; -pub const SYS_getgid: ::c_long = 47; -pub const SYS_signal: ::c_long = 48; -pub const SYS_geteuid: ::c_long = 49; -pub const SYS_getegid: ::c_long = 50; -pub const SYS_acct: ::c_long = 51; -pub const SYS_umount2: ::c_long = 52; -pub const SYS_lock: ::c_long = 53; -pub const SYS_ioctl: ::c_long = 54; -pub const SYS_fcntl: ::c_long = 55; -pub const SYS_mpx: ::c_long = 56; -pub const SYS_setpgid: ::c_long = 57; -pub const SYS_ulimit: ::c_long = 58; -pub const SYS_oldolduname: ::c_long = 59; -pub const SYS_umask: ::c_long = 60; -pub const SYS_chroot: ::c_long = 61; -pub const SYS_ustat: ::c_long = 62; -pub const SYS_dup2: ::c_long = 63; -pub const SYS_getppid: ::c_long = 64; -pub const SYS_getpgrp: ::c_long = 65; -pub const SYS_setsid: ::c_long = 66; -pub const SYS_sigaction: ::c_long = 67; -pub const SYS_sgetmask: ::c_long = 68; -pub const SYS_ssetmask: ::c_long = 69; -pub const SYS_setreuid: ::c_long = 70; -pub const SYS_setregid: ::c_long = 71; -pub const SYS_sigsuspend: ::c_long = 72; -pub const SYS_sigpending: ::c_long = 73; -pub const SYS_sethostname: ::c_long = 74; -pub const SYS_setrlimit: ::c_long = 75; -pub const SYS_getrlimit: ::c_long = 76; -pub const SYS_getrusage: ::c_long = 77; -pub const SYS_gettimeofday: ::c_long = 78; -pub const SYS_settimeofday: ::c_long = 79; -pub const SYS_getgroups: ::c_long = 80; -pub const SYS_setgroups: ::c_long = 81; -pub const SYS_select: ::c_long = 82; -pub const SYS_symlink: ::c_long = 83; -pub const SYS_oldlstat: ::c_long = 84; -pub const SYS_readlink: ::c_long = 85; -pub const SYS_uselib: ::c_long = 86; -pub const SYS_swapon: ::c_long = 87; -pub const SYS_reboot: ::c_long = 88; -pub const SYS_readdir: ::c_long = 89; -pub const SYS_mmap: ::c_long = 90; -pub const SYS_munmap: ::c_long = 91; -pub const SYS_truncate: ::c_long = 92; -pub const SYS_ftruncate: ::c_long = 93; -pub const SYS_fchmod: ::c_long = 94; -pub const SYS_fchown: ::c_long = 95; -pub const SYS_getpriority: ::c_long = 96; -pub const SYS_setpriority: ::c_long = 97; -pub const SYS_profil: ::c_long = 98; -pub const SYS_statfs: ::c_long = 99; -pub const SYS_fstatfs: ::c_long = 100; -pub const SYS_ioperm: ::c_long = 101; -pub const SYS_socketcall: ::c_long = 102; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_setitimer: ::c_long = 104; -pub const SYS_getitimer: ::c_long = 105; -pub const SYS_stat: ::c_long = 106; -pub const SYS_lstat: ::c_long = 107; -pub const SYS_fstat: ::c_long = 108; -pub const SYS_olduname: ::c_long = 109; -pub const SYS_iopl: ::c_long = 110; -pub const SYS_vhangup: ::c_long = 111; -pub const SYS_idle: ::c_long = 112; -pub const SYS_vm86old: ::c_long = 113; -pub const SYS_wait4: ::c_long = 114; -pub const SYS_swapoff: ::c_long = 115; -pub const SYS_sysinfo: ::c_long = 116; -pub const SYS_ipc: ::c_long = 117; -pub const SYS_fsync: ::c_long = 118; -pub const SYS_sigreturn: ::c_long = 119; -pub const SYS_clone: ::c_long = 120; -pub const SYS_setdomainname: ::c_long = 121; -pub const SYS_uname: ::c_long = 122; -pub const SYS_modify_ldt: ::c_long = 123; -pub const SYS_adjtimex: ::c_long = 124; -pub const SYS_mprotect: ::c_long = 125; -pub const SYS_sigprocmask: ::c_long = 126; -pub const SYS_create_module: ::c_long = 127; -pub const SYS_init_module: ::c_long = 128; -pub const SYS_delete_module: ::c_long = 129; -pub const SYS_get_kernel_syms: ::c_long = 130; -pub const SYS_quotactl: ::c_long = 131; -pub const SYS_getpgid: ::c_long = 132; -pub const SYS_fchdir: ::c_long = 133; -pub const SYS_bdflush: ::c_long = 134; -pub const SYS_sysfs: ::c_long = 135; -pub const SYS_personality: ::c_long = 136; -pub const SYS_afs_syscall: ::c_long = 137; -pub const SYS_setfsuid: ::c_long = 138; -pub const SYS_setfsgid: ::c_long = 139; -pub const SYS__llseek: ::c_long = 140; -pub const SYS_getdents: ::c_long = 141; -pub const SYS__newselect: ::c_long = 142; -pub const SYS_flock: ::c_long = 143; -pub const SYS_msync: ::c_long = 144; -pub const SYS_readv: ::c_long = 145; -pub const SYS_writev: ::c_long = 146; -pub const SYS_getsid: ::c_long = 147; -pub const SYS_fdatasync: ::c_long = 148; -pub const SYS__sysctl: ::c_long = 149; -pub const SYS_mlock: ::c_long = 150; -pub const SYS_munlock: ::c_long = 151; -pub const SYS_mlockall: ::c_long = 152; -pub const SYS_munlockall: ::c_long = 153; -pub const SYS_sched_setparam: ::c_long = 154; -pub const SYS_sched_getparam: ::c_long = 155; -pub const SYS_sched_setscheduler: ::c_long = 156; -pub const SYS_sched_getscheduler: ::c_long = 157; -pub const SYS_sched_yield: ::c_long = 158; -pub const SYS_sched_get_priority_max: ::c_long = 159; -pub const SYS_sched_get_priority_min: ::c_long = 160; -pub const SYS_sched_rr_get_interval: ::c_long = 161; -pub const SYS_nanosleep: ::c_long = 162; -pub const SYS_mremap: ::c_long = 163; -pub const SYS_setresuid: ::c_long = 164; -pub const SYS_getresuid: ::c_long = 165; -pub const SYS_vm86: ::c_long = 166; -pub const SYS_query_module: ::c_long = 167; -pub const SYS_poll: ::c_long = 168; -pub const SYS_nfsservctl: ::c_long = 169; -pub const SYS_setresgid: ::c_long = 170; -pub const SYS_getresgid: ::c_long = 171; -pub const SYS_prctl: ::c_long = 172; -pub const SYS_rt_sigreturn: ::c_long = 173; -pub const SYS_rt_sigaction: ::c_long = 174; -pub const SYS_rt_sigprocmask: ::c_long = 175; -pub const SYS_rt_sigpending: ::c_long = 176; -pub const SYS_rt_sigtimedwait: ::c_long = 177; -pub const SYS_rt_sigqueueinfo: ::c_long = 178; -pub const SYS_rt_sigsuspend: ::c_long = 179; -pub const SYS_pread64: ::c_long = 180; -pub const SYS_pwrite64: ::c_long = 181; -pub const SYS_chown: ::c_long = 182; -pub const SYS_getcwd: ::c_long = 183; -pub const SYS_capget: ::c_long = 184; -pub const SYS_capset: ::c_long = 185; -pub const SYS_sigaltstack: ::c_long = 186; -pub const SYS_sendfile: ::c_long = 187; -pub const SYS_getpmsg: ::c_long = 188; -pub const SYS_putpmsg: ::c_long = 189; -pub const SYS_vfork: ::c_long = 190; -pub const SYS_ugetrlimit: ::c_long = 191; -pub const SYS_mmap2: ::c_long = 192; -pub const SYS_truncate64: ::c_long = 193; -pub const SYS_ftruncate64: ::c_long = 194; -pub const SYS_stat64: ::c_long = 195; -pub const SYS_lstat64: ::c_long = 196; -pub const SYS_fstat64: ::c_long = 197; -pub const SYS_lchown32: ::c_long = 198; -pub const SYS_getuid32: ::c_long = 199; -pub const SYS_getgid32: ::c_long = 200; -pub const SYS_geteuid32: ::c_long = 201; -pub const SYS_getegid32: ::c_long = 202; -pub const SYS_setreuid32: ::c_long = 203; -pub const SYS_setregid32: ::c_long = 204; -pub const SYS_getgroups32: ::c_long = 205; -pub const SYS_setgroups32: ::c_long = 206; -pub const SYS_fchown32: ::c_long = 207; -pub const SYS_setresuid32: ::c_long = 208; -pub const SYS_getresuid32: ::c_long = 209; -pub const SYS_setresgid32: ::c_long = 210; -pub const SYS_getresgid32: ::c_long = 211; -pub const SYS_chown32: ::c_long = 212; -pub const SYS_setuid32: ::c_long = 213; -pub const SYS_setgid32: ::c_long = 214; -pub const SYS_setfsuid32: ::c_long = 215; -pub const SYS_setfsgid32: ::c_long = 216; -pub const SYS_pivot_root: ::c_long = 217; -pub const SYS_mincore: ::c_long = 218; -pub const SYS_madvise: ::c_long = 219; -pub const SYS_getdents64: ::c_long = 220; -pub const SYS_fcntl64: ::c_long = 221; -pub const SYS_gettid: ::c_long = 224; -pub const SYS_readahead: ::c_long = 225; -pub const SYS_setxattr: ::c_long = 226; -pub const SYS_lsetxattr: ::c_long = 227; -pub const SYS_fsetxattr: ::c_long = 228; -pub const SYS_getxattr: ::c_long = 229; -pub const SYS_lgetxattr: ::c_long = 230; -pub const SYS_fgetxattr: ::c_long = 231; -pub const SYS_listxattr: ::c_long = 232; -pub const SYS_llistxattr: ::c_long = 233; -pub const SYS_flistxattr: ::c_long = 234; -pub const SYS_removexattr: ::c_long = 235; -pub const SYS_lremovexattr: ::c_long = 236; -pub const SYS_fremovexattr: ::c_long = 237; -pub const SYS_tkill: ::c_long = 238; -pub const SYS_sendfile64: ::c_long = 239; -pub const SYS_futex: ::c_long = 240; -pub const SYS_sched_setaffinity: ::c_long = 241; -pub const SYS_sched_getaffinity: ::c_long = 242; -pub const SYS_set_thread_area: ::c_long = 243; -pub const SYS_get_thread_area: ::c_long = 244; -pub const SYS_io_setup: ::c_long = 245; -pub const SYS_io_destroy: ::c_long = 246; -pub const SYS_io_getevents: ::c_long = 247; -pub const SYS_io_submit: ::c_long = 248; -pub const SYS_io_cancel: ::c_long = 249; -pub const SYS_fadvise64: ::c_long = 250; -pub const SYS_exit_group: ::c_long = 252; -pub const SYS_lookup_dcookie: ::c_long = 253; -pub const SYS_epoll_create: ::c_long = 254; -pub const SYS_epoll_ctl: ::c_long = 255; -pub const SYS_epoll_wait: ::c_long = 256; -pub const SYS_remap_file_pages: ::c_long = 257; -pub const SYS_set_tid_address: ::c_long = 258; -pub const SYS_timer_create: ::c_long = 259; -pub const SYS_timer_settime: ::c_long = 260; -pub const SYS_timer_gettime: ::c_long = 261; -pub const SYS_timer_getoverrun: ::c_long = 262; -pub const SYS_timer_delete: ::c_long = 263; -pub const SYS_clock_settime: ::c_long = 264; -pub const SYS_clock_gettime: ::c_long = 265; -pub const SYS_clock_getres: ::c_long = 266; -pub const SYS_clock_nanosleep: ::c_long = 267; -pub const SYS_statfs64: ::c_long = 268; -pub const SYS_fstatfs64: ::c_long = 269; -pub const SYS_tgkill: ::c_long = 270; -pub const SYS_utimes: ::c_long = 271; -pub const SYS_fadvise64_64: ::c_long = 272; -pub const SYS_vserver: ::c_long = 273; -pub const SYS_mbind: ::c_long = 274; -pub const SYS_get_mempolicy: ::c_long = 275; -pub const SYS_set_mempolicy: ::c_long = 276; -pub const SYS_mq_open: ::c_long = 277; -pub const SYS_mq_unlink: ::c_long = 278; -pub const SYS_mq_timedsend: ::c_long = 279; -pub const SYS_mq_timedreceive: ::c_long = 280; -pub const SYS_mq_notify: ::c_long = 281; -pub const SYS_mq_getsetattr: ::c_long = 282; -pub const SYS_kexec_load: ::c_long = 283; -pub const SYS_waitid: ::c_long = 284; -pub const SYS_add_key: ::c_long = 286; -pub const SYS_request_key: ::c_long = 287; -pub const SYS_keyctl: ::c_long = 288; -pub const SYS_ioprio_set: ::c_long = 289; -pub const SYS_ioprio_get: ::c_long = 290; -pub const SYS_inotify_init: ::c_long = 291; -pub const SYS_inotify_add_watch: ::c_long = 292; -pub const SYS_inotify_rm_watch: ::c_long = 293; -pub const SYS_migrate_pages: ::c_long = 294; -pub const SYS_openat: ::c_long = 295; -pub const SYS_mkdirat: ::c_long = 296; -pub const SYS_mknodat: ::c_long = 297; -pub const SYS_fchownat: ::c_long = 298; -pub const SYS_futimesat: ::c_long = 299; -pub const SYS_fstatat64: ::c_long = 300; -pub const SYS_unlinkat: ::c_long = 301; -pub const SYS_renameat: ::c_long = 302; -pub const SYS_linkat: ::c_long = 303; -pub const SYS_symlinkat: ::c_long = 304; -pub const SYS_readlinkat: ::c_long = 305; -pub const SYS_fchmodat: ::c_long = 306; -pub const SYS_faccessat: ::c_long = 307; -pub const SYS_pselect6: ::c_long = 308; -pub const SYS_ppoll: ::c_long = 309; -pub const SYS_unshare: ::c_long = 310; -pub const SYS_set_robust_list: ::c_long = 311; -pub const SYS_get_robust_list: ::c_long = 312; -pub const SYS_splice: ::c_long = 313; -pub const SYS_sync_file_range: ::c_long = 314; -pub const SYS_tee: ::c_long = 315; -pub const SYS_vmsplice: ::c_long = 316; -pub const SYS_move_pages: ::c_long = 317; -pub const SYS_getcpu: ::c_long = 318; -pub const SYS_epoll_pwait: ::c_long = 319; -pub const SYS_utimensat: ::c_long = 320; -pub const SYS_signalfd: ::c_long = 321; -pub const SYS_timerfd_create: ::c_long = 322; -pub const SYS_eventfd: ::c_long = 323; -pub const SYS_fallocate: ::c_long = 324; -pub const SYS_timerfd_settime: ::c_long = 325; -pub const SYS_timerfd_gettime: ::c_long = 326; -pub const SYS_signalfd4: ::c_long = 327; -pub const SYS_eventfd2: ::c_long = 328; -pub const SYS_epoll_create1: ::c_long = 329; -pub const SYS_dup3: ::c_long = 330; -pub const SYS_pipe2: ::c_long = 331; -pub const SYS_inotify_init1: ::c_long = 332; -pub const SYS_preadv: ::c_long = 333; -pub const SYS_pwritev: ::c_long = 334; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 335; -pub const SYS_perf_event_open: ::c_long = 336; -pub const SYS_recvmmsg: ::c_long = 337; -pub const SYS_fanotify_init: ::c_long = 338; -pub const SYS_fanotify_mark: ::c_long = 339; -pub const SYS_prlimit64: ::c_long = 340; -pub const SYS_name_to_handle_at: ::c_long = 341; -pub const SYS_open_by_handle_at: ::c_long = 342; -pub const SYS_clock_adjtime: ::c_long = 343; -pub const SYS_syncfs: ::c_long = 344; -pub const SYS_sendmmsg: ::c_long = 345; -pub const SYS_setns: ::c_long = 346; -pub const SYS_process_vm_readv: ::c_long = 347; -pub const SYS_process_vm_writev: ::c_long = 348; -pub const SYS_kcmp: ::c_long = 349; -pub const SYS_finit_module: ::c_long = 350; -pub const SYS_sched_setattr: ::c_long = 351; -pub const SYS_sched_getattr: ::c_long = 352; -pub const SYS_renameat2: ::c_long = 353; -pub const SYS_seccomp: ::c_long = 354; -pub const SYS_getrandom: ::c_long = 355; -pub const SYS_memfd_create: ::c_long = 356; -pub const SYS_bpf: ::c_long = 357; -pub const SYS_execveat: ::c_long = 358; -pub const SYS_socket: ::c_long = 359; -pub const SYS_socketpair: ::c_long = 360; -pub const SYS_bind: ::c_long = 361; -pub const SYS_connect: ::c_long = 362; -pub const SYS_listen: ::c_long = 363; -pub const SYS_accept4: ::c_long = 364; -pub const SYS_getsockopt: ::c_long = 365; -pub const SYS_setsockopt: ::c_long = 366; -pub const SYS_getsockname: ::c_long = 367; -pub const SYS_getpeername: ::c_long = 368; -pub const SYS_sendto: ::c_long = 369; -pub const SYS_sendmsg: ::c_long = 370; -pub const SYS_recvfrom: ::c_long = 371; -pub const SYS_recvmsg: ::c_long = 372; -pub const SYS_shutdown: ::c_long = 373; -pub const SYS_userfaultfd: ::c_long = 374; -pub const SYS_membarrier: ::c_long = 375; -pub const SYS_mlock2: ::c_long = 376; -pub const SYS_copy_file_range: ::c_long = 377; -pub const SYS_preadv2: ::c_long = 378; -pub const SYS_pwritev2: ::c_long = 379; -// FIXME syscalls 380-382 have been added in musl 1.16 -// See discussion https://github.com/rust-lang/libc/pull/699 - -// offsets in user_regs_structs, from sys/reg.h -pub const EBX: ::c_int = 0; -pub const ECX: ::c_int = 1; -pub const EDX: ::c_int = 2; -pub const ESI: ::c_int = 3; -pub const EDI: ::c_int = 4; -pub const EBP: ::c_int = 5; -pub const EAX: ::c_int = 6; -pub const DS: ::c_int = 7; -pub const ES: ::c_int = 8; -pub const FS: ::c_int = 9; -pub const GS: ::c_int = 10; -pub const ORIG_EAX: ::c_int = 11; -pub const EIP: ::c_int = 12; -pub const CS: ::c_int = 13; -pub const EFL: ::c_int = 14; -pub const UESP: ::c_int = 15; -pub const SS: ::c_int = 16; - -#[doc(hidden)] -pub const AF_MAX: ::c_int = 42; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/aarch64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/aarch64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,341 +0,0 @@ -pub type c_char = u8; -pub type __u64 = ::c_ulonglong; -pub type wchar_t = u32; -pub type nlink_t = u32; -pub type blksize_t = ::c_int; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad0: ::c_ulong, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - __pad1: ::c_int, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused: [::c_uint; 2], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad0: ::c_ulong, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - __pad1: ::c_int, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused: [::c_uint; 2], - } - - pub struct ipc_perm { - pub __ipc_perm_key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::mode_t, - pub __seq: ::c_ushort, - __unused1: ::c_ulong, - __unused2: ::c_ulong, - } -} - -pub const O_DIRECT: ::c_int = 0x10000; -pub const O_DIRECTORY: ::c_int = 0x4000; -pub const O_LARGEFILE: ::c_int = 0x20000; -pub const O_NOFOLLOW: ::c_int = 0x8000; - -pub const MINSIGSTKSZ: ::size_t = 6144; -pub const SIGSTKSZ: ::size_t = 12288; - -#[doc(hidden)] -pub const PF_MAX: ::c_int = 43; -#[doc(hidden)] -pub const AF_MAX: ::c_int = PF_MAX; - -pub const SYS_io_setup: ::c_long = 0; -pub const SYS_io_destroy: ::c_long = 1; -pub const SYS_io_submit: ::c_long = 2; -pub const SYS_io_cancel: ::c_long = 3; -pub const SYS_io_getevents: ::c_long = 4; -pub const SYS_setxattr: ::c_long = 5; -pub const SYS_lsetxattr: ::c_long = 6; -pub const SYS_fsetxattr: ::c_long = 7; -pub const SYS_getxattr: ::c_long = 8; -pub const SYS_lgetxattr: ::c_long = 9; -pub const SYS_fgetxattr: ::c_long = 10; -pub const SYS_listxattr: ::c_long = 11; -pub const SYS_llistxattr: ::c_long = 12; -pub const SYS_flistxattr: ::c_long = 13; -pub const SYS_removexattr: ::c_long = 14; -pub const SYS_lremovexattr: ::c_long = 15; -pub const SYS_fremovexattr: ::c_long = 16; -pub const SYS_getcwd: ::c_long = 17; -pub const SYS_lookup_dcookie: ::c_long = 18; -pub const SYS_eventfd2: ::c_long = 19; -pub const SYS_epoll_create1: ::c_long = 20; -pub const SYS_epoll_ctl: ::c_long = 21; -pub const SYS_epoll_pwait: ::c_long = 22; -pub const SYS_dup: ::c_long = 23; -pub const SYS_dup3: ::c_long = 24; -pub const SYS_inotify_init1: ::c_long = 26; -pub const SYS_inotify_add_watch: ::c_long = 27; -pub const SYS_inotify_rm_watch: ::c_long = 28; -pub const SYS_ioctl: ::c_long = 29; -pub const SYS_ioprio_set: ::c_long = 30; -pub const SYS_ioprio_get: ::c_long = 31; -pub const SYS_flock: ::c_long = 32; -pub const SYS_mknodat: ::c_long = 33; -pub const SYS_mkdirat: ::c_long = 34; -pub const SYS_unlinkat: ::c_long = 35; -pub const SYS_symlinkat: ::c_long = 36; -pub const SYS_linkat: ::c_long = 37; -pub const SYS_renameat: ::c_long = 38; -pub const SYS_umount2: ::c_long = 39; -pub const SYS_mount: ::c_long = 40; -pub const SYS_pivot_root: ::c_long = 41; -pub const SYS_nfsservctl: ::c_long = 42; -pub const SYS_fallocate: ::c_long = 47; -pub const SYS_faccessat: ::c_long = 48; -pub const SYS_chdir: ::c_long = 49; -pub const SYS_fchdir: ::c_long = 50; -pub const SYS_chroot: ::c_long = 51; -pub const SYS_fchmod: ::c_long = 52; -pub const SYS_fchmodat: ::c_long = 53; -pub const SYS_fchownat: ::c_long = 54; -pub const SYS_fchown: ::c_long = 55; -pub const SYS_openat: ::c_long = 56; -pub const SYS_close: ::c_long = 57; -pub const SYS_vhangup: ::c_long = 58; -pub const SYS_pipe2: ::c_long = 59; -pub const SYS_quotactl: ::c_long = 60; -pub const SYS_getdents64: ::c_long = 61; -pub const SYS_read: ::c_long = 63; -pub const SYS_write: ::c_long = 64; -pub const SYS_readv: ::c_long = 65; -pub const SYS_writev: ::c_long = 66; -pub const SYS_pread64: ::c_long = 67; -pub const SYS_pwrite64: ::c_long = 68; -pub const SYS_preadv: ::c_long = 69; -pub const SYS_pwritev: ::c_long = 70; -pub const SYS_pselect6: ::c_long = 72; -pub const SYS_ppoll: ::c_long = 73; -pub const SYS_signalfd4: ::c_long = 74; -pub const SYS_vmsplice: ::c_long = 75; -pub const SYS_splice: ::c_long = 76; -pub const SYS_tee: ::c_long = 77; -pub const SYS_readlinkat: ::c_long = 78; -pub const SYS_sync: ::c_long = 81; -pub const SYS_fsync: ::c_long = 82; -pub const SYS_fdatasync: ::c_long = 83; -pub const SYS_sync_file_range: ::c_long = 84; -pub const SYS_timerfd_create: ::c_long = 85; -pub const SYS_timerfd_settime: ::c_long = 86; -pub const SYS_timerfd_gettime: ::c_long = 87; -pub const SYS_utimensat: ::c_long = 88; -pub const SYS_acct: ::c_long = 89; -pub const SYS_capget: ::c_long = 90; -pub const SYS_capset: ::c_long = 91; -pub const SYS_personality: ::c_long = 92; -pub const SYS_exit: ::c_long = 93; -pub const SYS_exit_group: ::c_long = 94; -pub const SYS_waitid: ::c_long = 95; -pub const SYS_set_tid_address: ::c_long = 96; -pub const SYS_unshare: ::c_long = 97; -pub const SYS_futex: ::c_long = 98; -pub const SYS_set_robust_list: ::c_long = 99; -pub const SYS_get_robust_list: ::c_long = 100; -pub const SYS_nanosleep: ::c_long = 101; -pub const SYS_getitimer: ::c_long = 102; -pub const SYS_setitimer: ::c_long = 103; -pub const SYS_kexec_load: ::c_long = 104; -pub const SYS_init_module: ::c_long = 105; -pub const SYS_delete_module: ::c_long = 106; -pub const SYS_timer_create: ::c_long = 107; -pub const SYS_timer_gettime: ::c_long = 108; -pub const SYS_timer_getoverrun: ::c_long = 109; -pub const SYS_timer_settime: ::c_long = 110; -pub const SYS_timer_delete: ::c_long = 111; -pub const SYS_clock_settime: ::c_long = 112; -pub const SYS_clock_gettime: ::c_long = 113; -pub const SYS_clock_getres: ::c_long = 114; -pub const SYS_clock_nanosleep: ::c_long = 115; -pub const SYS_syslog: ::c_long = 116; -pub const SYS_ptrace: ::c_long = 117; -pub const SYS_sched_setparam: ::c_long = 118; -pub const SYS_sched_setscheduler: ::c_long = 119; -pub const SYS_sched_getscheduler: ::c_long = 120; -pub const SYS_sched_getparam: ::c_long = 121; -pub const SYS_sched_setaffinity: ::c_long = 122; -pub const SYS_sched_getaffinity: ::c_long = 123; -pub const SYS_sched_yield: ::c_long = 124; -pub const SYS_sched_get_priority_max: ::c_long = 125; -pub const SYS_sched_get_priority_min: ::c_long = 126; -pub const SYS_sched_rr_get_interval: ::c_long = 127; -pub const SYS_restart_syscall: ::c_long = 128; -pub const SYS_kill: ::c_long = 129; -pub const SYS_tkill: ::c_long = 130; -pub const SYS_tgkill: ::c_long = 131; -pub const SYS_sigaltstack: ::c_long = 132; -pub const SYS_rt_sigsuspend: ::c_long = 133; -pub const SYS_rt_sigaction: ::c_long = 134; -pub const SYS_rt_sigprocmask: ::c_long = 135; -pub const SYS_rt_sigpending: ::c_long = 136; -pub const SYS_rt_sigtimedwait: ::c_long = 137; -pub const SYS_rt_sigqueueinfo: ::c_long = 138; -pub const SYS_rt_sigreturn: ::c_long = 139; -pub const SYS_setpriority: ::c_long = 140; -pub const SYS_getpriority: ::c_long = 141; -pub const SYS_reboot: ::c_long = 142; -pub const SYS_setregid: ::c_long = 143; -pub const SYS_setgid: ::c_long = 144; -pub const SYS_setreuid: ::c_long = 145; -pub const SYS_setuid: ::c_long = 146; -pub const SYS_setresuid: ::c_long = 147; -pub const SYS_getresuid: ::c_long = 148; -pub const SYS_setresgid: ::c_long = 149; -pub const SYS_getresgid: ::c_long = 150; -pub const SYS_setfsuid: ::c_long = 151; -pub const SYS_setfsgid: ::c_long = 152; -pub const SYS_times: ::c_long = 153; -pub const SYS_setpgid: ::c_long = 154; -pub const SYS_getpgid: ::c_long = 155; -pub const SYS_getsid: ::c_long = 156; -pub const SYS_setsid: ::c_long = 157; -pub const SYS_getgroups: ::c_long = 158; -pub const SYS_setgroups: ::c_long = 159; -pub const SYS_uname: ::c_long = 160; -pub const SYS_sethostname: ::c_long = 161; -pub const SYS_setdomainname: ::c_long = 162; -pub const SYS_getrlimit: ::c_long = 163; -pub const SYS_setrlimit: ::c_long = 164; -pub const SYS_getrusage: ::c_long = 165; -pub const SYS_umask: ::c_long = 166; -pub const SYS_prctl: ::c_long = 167; -pub const SYS_getcpu: ::c_long = 168; -pub const SYS_gettimeofday: ::c_long = 169; -pub const SYS_settimeofday: ::c_long = 170; -pub const SYS_adjtimex: ::c_long = 171; -pub const SYS_getpid: ::c_long = 172; -pub const SYS_getppid: ::c_long = 173; -pub const SYS_getuid: ::c_long = 174; -pub const SYS_geteuid: ::c_long = 175; -pub const SYS_getgid: ::c_long = 176; -pub const SYS_getegid: ::c_long = 177; -pub const SYS_gettid: ::c_long = 178; -pub const SYS_sysinfo: ::c_long = 179; -pub const SYS_mq_open: ::c_long = 180; -pub const SYS_mq_unlink: ::c_long = 181; -pub const SYS_mq_timedsend: ::c_long = 182; -pub const SYS_mq_timedreceive: ::c_long = 183; -pub const SYS_mq_notify: ::c_long = 184; -pub const SYS_mq_getsetattr: ::c_long = 185; -pub const SYS_msgget: ::c_long = 186; -pub const SYS_msgctl: ::c_long = 187; -pub const SYS_msgrcv: ::c_long = 188; -pub const SYS_msgsnd: ::c_long = 189; -pub const SYS_semget: ::c_long = 190; -pub const SYS_semctl: ::c_long = 191; -pub const SYS_semtimedop: ::c_long = 192; -pub const SYS_semop: ::c_long = 193; -pub const SYS_shmget: ::c_long = 194; -pub const SYS_shmctl: ::c_long = 195; -pub const SYS_shmat: ::c_long = 196; -pub const SYS_shmdt: ::c_long = 197; -pub const SYS_socket: ::c_long = 198; -pub const SYS_socketpair: ::c_long = 199; -pub const SYS_bind: ::c_long = 200; -pub const SYS_listen: ::c_long = 201; -pub const SYS_accept: ::c_long = 202; -pub const SYS_connect: ::c_long = 203; -pub const SYS_getsockname: ::c_long = 204; -pub const SYS_getpeername: ::c_long = 205; -pub const SYS_sendto: ::c_long = 206; -pub const SYS_recvfrom: ::c_long = 207; -pub const SYS_setsockopt: ::c_long = 208; -pub const SYS_getsockopt: ::c_long = 209; -pub const SYS_shutdown: ::c_long = 210; -pub const SYS_sendmsg: ::c_long = 211; -pub const SYS_recvmsg: ::c_long = 212; -pub const SYS_readahead: ::c_long = 213; -pub const SYS_brk: ::c_long = 214; -pub const SYS_munmap: ::c_long = 215; -pub const SYS_mremap: ::c_long = 216; -pub const SYS_add_key: ::c_long = 217; -pub const SYS_request_key: ::c_long = 218; -pub const SYS_keyctl: ::c_long = 219; -pub const SYS_clone: ::c_long = 220; -pub const SYS_execve: ::c_long = 221; -pub const SYS_swapon: ::c_long = 224; -pub const SYS_swapoff: ::c_long = 225; -pub const SYS_mprotect: ::c_long = 226; -pub const SYS_msync: ::c_long = 227; -pub const SYS_mlock: ::c_long = 228; -pub const SYS_munlock: ::c_long = 229; -pub const SYS_mlockall: ::c_long = 230; -pub const SYS_munlockall: ::c_long = 231; -pub const SYS_mincore: ::c_long = 232; -pub const SYS_madvise: ::c_long = 233; -pub const SYS_remap_file_pages: ::c_long = 234; -pub const SYS_mbind: ::c_long = 235; -pub const SYS_get_mempolicy: ::c_long = 236; -pub const SYS_set_mempolicy: ::c_long = 237; -pub const SYS_migrate_pages: ::c_long = 238; -pub const SYS_move_pages: ::c_long = 239; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 240; -pub const SYS_perf_event_open: ::c_long = 241; -pub const SYS_accept4: ::c_long = 242; -pub const SYS_recvmmsg: ::c_long = 243; -pub const SYS_wait4: ::c_long = 260; -pub const SYS_prlimit64: ::c_long = 261; -pub const SYS_fanotify_init: ::c_long = 262; -pub const SYS_fanotify_mark: ::c_long = 263; -pub const SYS_name_to_handle_at: ::c_long = 264; -pub const SYS_open_by_handle_at: ::c_long = 265; -pub const SYS_clock_adjtime: ::c_long = 266; -pub const SYS_syncfs: ::c_long = 267; -pub const SYS_setns: ::c_long = 268; -pub const SYS_sendmmsg: ::c_long = 269; -pub const SYS_process_vm_readv: ::c_long = 270; -pub const SYS_process_vm_writev: ::c_long = 271; -pub const SYS_kcmp: ::c_long = 272; -pub const SYS_finit_module: ::c_long = 273; -pub const SYS_sched_setattr: ::c_long = 274; -pub const SYS_sched_getattr: ::c_long = 275; -pub const SYS_renameat2: ::c_long = 276; -pub const SYS_seccomp: ::c_long = 277; -pub const SYS_getrandom: ::c_long = 278; -pub const SYS_memfd_create: ::c_long = 279; -pub const SYS_bpf: ::c_long = 280; -pub const SYS_execveat: ::c_long = 281; -pub const SYS_userfaultfd: ::c_long = 282; -pub const SYS_membarrier: ::c_long = 283; -pub const SYS_mlock2: ::c_long = 284; -pub const SYS_copy_file_range: ::c_long = 285; -pub const SYS_preadv2: ::c_long = 286; -pub const SYS_pwritev2: ::c_long = 287; -pub const SYS_pkey_mprotect: ::c_long = 288; -pub const SYS_pkey_alloc: ::c_long = 289; -pub const SYS_pkey_free: ::c_long = 290; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,392 +0,0 @@ -pub type c_long = i64; -pub type c_ulong = u64; - -s! { - pub struct statfs64 { - pub f_type: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_flags: ::c_ulong, - pub f_spare: [::c_ulong; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_flags: ::c_int, - pub ss_size: ::size_t - } - - pub struct pthread_attr_t { - __size: [u64; 7] - } - - pub struct sigset_t { - __val: [::c_ulong; 16], - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::c_ulong, - __pad1: ::c_ulong, - __pad2: ::c_ulong, - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - pub msg_stime: ::time_t, - pub msg_rtime: ::time_t, - pub msg_ctime: ::time_t, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __pad1: ::c_ulong, - __pad2: ::c_ulong, - } - - pub struct statfs { - pub f_type: ::c_ulong, - pub f_bsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_flags: ::c_ulong, - pub f_spare: [::c_ulong; 4], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::c_int, - __pad1: ::c_int, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::socklen_t, - __pad2: ::socklen_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::socklen_t, - pub __pad1: ::c_int, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct sem_t { - __val: [::c_int; 8], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_errno: ::c_int, - pub si_code: ::c_int, - pub _pad: [::c_int; 29], - _align: [usize; 0], - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 19], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } -} - -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; - -pub const O_ASYNC: ::c_int = 0x2000; - -pub const FIOCLEX: ::c_int = 0x5451; -pub const FIONBIO: ::c_int = 0x5421; - -pub const RLIMIT_RSS: ::c_int = 5; -pub const RLIMIT_NOFILE: ::c_int = 7; -pub const RLIMIT_AS: ::c_int = 9; -pub const RLIMIT_NPROC: ::c_int = 6; -pub const RLIMIT_MEMLOCK: ::c_int = 8; - -pub const O_APPEND: ::c_int = 1024; -pub const O_CREAT: ::c_int = 64; -pub const O_EXCL: ::c_int = 128; -pub const O_NOCTTY: ::c_int = 256; -pub const O_NONBLOCK: ::c_int = 2048; -pub const O_SYNC: ::c_int = 1052672; -pub const O_RSYNC: ::c_int = 1052672; -pub const O_DSYNC: ::c_int = 4096; - -pub const SOCK_NONBLOCK: ::c_int = 2048; - -pub const MAP_ANON: ::c_int = 0x0020; -pub const MAP_GROWSDOWN: ::c_int = 0x0100; -pub const MAP_DENYWRITE: ::c_int = 0x0800; -pub const MAP_EXECUTABLE: ::c_int = 0x01000; -pub const MAP_LOCKED: ::c_int = 0x02000; -pub const MAP_NORESERVE: ::c_int = 0x04000; -pub const MAP_POPULATE: ::c_int = 0x08000; -pub const MAP_NONBLOCK: ::c_int = 0x010000; -pub const MAP_STACK: ::c_int = 0x020000; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; -pub const SOCK_SEQPACKET: ::c_int = 5; - -pub const SOL_SOCKET: ::c_int = 1; - -pub const EDEADLK: ::c_int = 35; -pub const ENAMETOOLONG: ::c_int = 36; -pub const ENOLCK: ::c_int = 37; -pub const ENOSYS: ::c_int = 38; -pub const ENOTEMPTY: ::c_int = 39; -pub const ELOOP: ::c_int = 40; -pub const ENOMSG: ::c_int = 42; -pub const EIDRM: ::c_int = 43; -pub const ECHRNG: ::c_int = 44; -pub const EL2NSYNC: ::c_int = 45; -pub const EL3HLT: ::c_int = 46; -pub const EL3RST: ::c_int = 47; -pub const ELNRNG: ::c_int = 48; -pub const EUNATCH: ::c_int = 49; -pub const ENOCSI: ::c_int = 50; -pub const EL2HLT: ::c_int = 51; -pub const EBADE: ::c_int = 52; -pub const EBADR: ::c_int = 53; -pub const EXFULL: ::c_int = 54; -pub const ENOANO: ::c_int = 55; -pub const EBADRQC: ::c_int = 56; -pub const EBADSLT: ::c_int = 57; -pub const EDEADLOCK: ::c_int = EDEADLK; -pub const EMULTIHOP: ::c_int = 72; -pub const EBADMSG: ::c_int = 74; -pub const EOVERFLOW: ::c_int = 75; -pub const ENOTUNIQ: ::c_int = 76; -pub const EBADFD: ::c_int = 77; -pub const EREMCHG: ::c_int = 78; -pub const ELIBACC: ::c_int = 79; -pub const ELIBBAD: ::c_int = 80; -pub const ELIBSCN: ::c_int = 81; -pub const ELIBMAX: ::c_int = 82; -pub const ELIBEXEC: ::c_int = 83; -pub const EILSEQ: ::c_int = 84; -pub const ERESTART: ::c_int = 85; -pub const ESTRPIPE: ::c_int = 86; -pub const EUSERS: ::c_int = 87; -pub const ENOTSOCK: ::c_int = 88; -pub const EDESTADDRREQ: ::c_int = 89; -pub const EMSGSIZE: ::c_int = 90; -pub const EPROTOTYPE: ::c_int = 91; -pub const ENOPROTOOPT: ::c_int = 92; -pub const EPROTONOSUPPORT: ::c_int = 93; -pub const ESOCKTNOSUPPORT: ::c_int = 94; -pub const EOPNOTSUPP: ::c_int = 95; -pub const ENOTSUP: ::c_int = EOPNOTSUPP; -pub const EPFNOSUPPORT: ::c_int = 96; -pub const EAFNOSUPPORT: ::c_int = 97; -pub const EADDRINUSE: ::c_int = 98; -pub const EADDRNOTAVAIL: ::c_int = 99; -pub const ENETDOWN: ::c_int = 100; -pub const ENETUNREACH: ::c_int = 101; -pub const ENETRESET: ::c_int = 102; -pub const ECONNABORTED: ::c_int = 103; -pub const ECONNRESET: ::c_int = 104; -pub const ENOBUFS: ::c_int = 105; -pub const EISCONN: ::c_int = 106; -pub const ENOTCONN: ::c_int = 107; -pub const ESHUTDOWN: ::c_int = 108; -pub const ETOOMANYREFS: ::c_int = 109; -pub const ETIMEDOUT: ::c_int = 110; -pub const ECONNREFUSED: ::c_int = 111; -pub const EHOSTDOWN: ::c_int = 112; -pub const EHOSTUNREACH: ::c_int = 113; -pub const EALREADY: ::c_int = 114; -pub const EINPROGRESS: ::c_int = 115; -pub const ESTALE: ::c_int = 116; -pub const EUCLEAN: ::c_int = 117; -pub const ENOTNAM: ::c_int = 118; -pub const ENAVAIL: ::c_int = 119; -pub const EISNAM: ::c_int = 120; -pub const EREMOTEIO: ::c_int = 121; -pub const EDQUOT: ::c_int = 122; -pub const ENOMEDIUM: ::c_int = 123; -pub const EMEDIUMTYPE: ::c_int = 124; -pub const ECANCELED: ::c_int = 125; -pub const ENOKEY: ::c_int = 126; -pub const EKEYEXPIRED: ::c_int = 127; -pub const EKEYREVOKED: ::c_int = 128; -pub const EKEYREJECTED: ::c_int = 129; -pub const EOWNERDEAD: ::c_int = 130; -pub const ENOTRECOVERABLE: ::c_int = 131; -pub const ERFKILL: ::c_int = 132; -pub const EHWPOISON: ::c_int = 133; - -pub const SO_REUSEADDR: ::c_int = 2; -pub const SO_TYPE: ::c_int = 3; -pub const SO_ERROR: ::c_int = 4; -pub const SO_DONTROUTE: ::c_int = 5; -pub const SO_BROADCAST: ::c_int = 6; -pub const SO_SNDBUF: ::c_int = 7; -pub const SO_RCVBUF: ::c_int = 8; -pub const SO_KEEPALIVE: ::c_int = 9; -pub const SO_OOBINLINE: ::c_int = 10; -pub const SO_NO_CHECK: ::c_int = 11; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_LINGER: ::c_int = 13; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_REUSEPORT: ::c_int = 15; -pub const SO_PASSCRED: ::c_int = 16; -pub const SO_PEERCRED: ::c_int = 17; -pub const SO_RCVLOWAT: ::c_int = 18; -pub const SO_SNDLOWAT: ::c_int = 19; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_SNDTIMEO: ::c_int = 21; -pub const SO_ACCEPTCONN: ::c_int = 30; -pub const SO_SNDBUFFORCE: ::c_int = 32; -pub const SO_RCVBUFFORCE: ::c_int = 33; -pub const SO_PROTOCOL: ::c_int = 38; -pub const SO_DOMAIN: ::c_int = 39; - -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 0x00000004; -pub const SA_NOCLDWAIT: ::c_int = 0x00000002; - -pub const SIGCHLD: ::c_int = 17; -pub const SIGBUS: ::c_int = 7; -pub const SIGTTIN: ::c_int = 21; -pub const SIGTTOU: ::c_int = 22; -pub const SIGXCPU: ::c_int = 24; -pub const SIGXFSZ: ::c_int = 25; -pub const SIGVTALRM: ::c_int = 26; -pub const SIGPROF: ::c_int = 27; -pub const SIGWINCH: ::c_int = 28; -pub const SIGUSR1: ::c_int = 10; -pub const SIGUSR2: ::c_int = 12; -pub const SIGCONT: ::c_int = 18; -pub const SIGSTOP: ::c_int = 19; -pub const SIGTSTP: ::c_int = 20; -pub const SIGURG: ::c_int = 23; -pub const SIGIO: ::c_int = 29; -pub const SIGSYS: ::c_int = 31; -pub const SIGSTKFLT: ::c_int = 16; -pub const SIGPOLL: ::c_int = 29; -pub const SIGPWR: ::c_int = 30; -pub const SIG_SETMASK: ::c_int = 2; -pub const SIG_BLOCK: ::c_int = 0x000000; -pub const SIG_UNBLOCK: ::c_int = 0x01; - -pub const EXTPROC: ::tcflag_t = 0x00010000; - -pub const MAP_HUGETLB: ::c_int = 0x040000; - -pub const F_GETLK: ::c_int = 5; -pub const F_GETOWN: ::c_int = 9; -pub const F_SETLK: ::c_int = 6; -pub const F_SETLKW: ::c_int = 7; -pub const F_SETOWN: ::c_int = 8; - -pub const VEOF: usize = 4; -pub const VEOL: usize = 11; -pub const VEOL2: usize = 16; -pub const VMIN: usize = 6; -pub const IEXTEN: ::tcflag_t = 0x00008000; -pub const TOSTOP: ::tcflag_t = 0x00000100; -pub const FLUSHO: ::tcflag_t = 0x00001000; - -pub const TCGETS: ::c_int = 0x5401; -pub const TCSETS: ::c_int = 0x5402; -pub const TCSETSW: ::c_int = 0x5403; -pub const TCSETSF: ::c_int = 0x5404; -pub const TCGETA: ::c_int = 0x5405; -pub const TCSETA: ::c_int = 0x5406; -pub const TCSETAW: ::c_int = 0x5407; -pub const TCSETAF: ::c_int = 0x5408; -pub const TCSBRK: ::c_int = 0x5409; -pub const TCXONC: ::c_int = 0x540A; -pub const TCFLSH: ::c_int = 0x540B; -pub const TIOCGSOFTCAR: ::c_int = 0x5419; -pub const TIOCSSOFTCAR: ::c_int = 0x541A; -pub const TIOCLINUX: ::c_int = 0x541C; -pub const TIOCGSERIAL: ::c_int = 0x541E; -pub const TIOCEXCL: ::c_int = 0x540C; -pub const TIOCNXCL: ::c_int = 0x540D; -pub const TIOCSCTTY: ::c_int = 0x540E; -pub const TIOCGPGRP: ::c_int = 0x540F; -pub const TIOCSPGRP: ::c_int = 0x5410; -pub const TIOCOUTQ: ::c_int = 0x5411; -pub const TIOCSTI: ::c_int = 0x5412; -pub const TIOCGWINSZ: ::c_int = 0x5413; -pub const TIOCSWINSZ: ::c_int = 0x5414; -pub const TIOCMGET: ::c_int = 0x5415; -pub const TIOCMBIS: ::c_int = 0x5416; -pub const TIOCMBIC: ::c_int = 0x5417; -pub const TIOCMSET: ::c_int = 0x5418; -pub const FIONREAD: ::c_int = 0x541B; -pub const TIOCCONS: ::c_int = 0x541D; - -pub const POLLWRNORM: ::c_short = 0x100; -pub const POLLWRBAND: ::c_short = 0x200; - -pub const TIOCM_LE: ::c_int = 0x001; -pub const TIOCM_DTR: ::c_int = 0x002; -pub const TIOCM_RTS: ::c_int = 0x004; -pub const TIOCM_ST: ::c_int = 0x008; -pub const TIOCM_SR: ::c_int = 0x010; -pub const TIOCM_CTS: ::c_int = 0x020; -pub const TIOCM_CAR: ::c_int = 0x040; -pub const TIOCM_RNG: ::c_int = 0x080; -pub const TIOCM_DSR: ::c_int = 0x100; -pub const TIOCM_CD: ::c_int = TIOCM_CAR; -pub const TIOCM_RI: ::c_int = TIOCM_RNG; - -cfg_if! { - if #[cfg(target_arch = "aarch64")] { - mod aarch64; - pub use self::aarch64::*; - } else if #[cfg(any(target_arch = "powerpc64"))] { - mod powerpc64; - pub use self::powerpc64::*; - } else if #[cfg(any(target_arch = "x86_64"))] { - mod x86_64; - pub use self::x86_64::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/powerpc64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/powerpc64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/powerpc64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/powerpc64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -pub type c_char = u8; -pub type wchar_t = i32; -pub type __u64 = ::c_ulong; -pub type nlink_t = u64; -pub type blksize_t = ::c_long; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - __pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused: [::c_long; 3], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino64_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - __pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __reserved: [::c_long; 3], - } - - pub struct ipc_perm { - pub __ipc_perm_key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::mode_t, - pub __seq: ::c_int, - __unused1: ::c_long, - __unused2: ::c_long - } -} - -pub const SYS_pivot_root: ::c_long = 203; -pub const SYS_gettid: ::c_long = 207; -pub const SYS_perf_event_open: ::c_long = 319; -pub const SYS_memfd_create: ::c_long = 360; - -pub const MAP_32BIT: ::c_int = 0x0040; -pub const O_DIRECT: ::c_int = 0x4000; -pub const O_DIRECTORY: ::c_int = 0x10000; -pub const O_LARGEFILE: ::c_int = 0; -pub const O_NOFOLLOW: ::c_int = 0x20000; - -pub const SIGSTKSZ: ::size_t = 8192; -pub const MINSIGSTKSZ: ::size_t = 2048; - -#[doc(hidden)] -pub const AF_MAX: ::c_int = 42; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; - -// Syscall table -pub const SYS_renameat2: ::c_long = 357; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/x86_64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/x86_64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/b64/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,451 +0,0 @@ -pub type c_char = i8; -pub type wchar_t = i32; -pub type nlink_t = u64; -pub type blksize_t = ::c_long; -pub type __u64 = ::c_ulonglong; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - __pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused: [::c_long; 3], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino64_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - __pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __reserved: [::c_long; 3], - } - - pub struct mcontext_t { - __private: [u64; 32], - } - - pub struct ucontext_t { - pub uc_flags: ::c_ulong, - pub uc_link: *mut ucontext_t, - pub uc_stack: ::stack_t, - pub uc_mcontext: mcontext_t, - pub uc_sigmask: ::sigset_t, - __private: [u8; 512], - } - - pub struct ipc_perm { - pub __ipc_perm_key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::mode_t, - pub __seq: ::c_int, - __unused1: ::c_long, - __unused2: ::c_long - } -} - -// Syscall table - -pub const SYS_read: ::c_long = 0; -pub const SYS_write: ::c_long = 1; -pub const SYS_open: ::c_long = 2; -pub const SYS_close: ::c_long = 3; -pub const SYS_stat: ::c_long = 4; -pub const SYS_fstat: ::c_long = 5; -pub const SYS_lstat: ::c_long = 6; -pub const SYS_poll: ::c_long = 7; -pub const SYS_lseek: ::c_long = 8; -pub const SYS_mmap: ::c_long = 9; -pub const SYS_mprotect: ::c_long = 10; -pub const SYS_munmap: ::c_long = 11; -pub const SYS_brk: ::c_long = 12; -pub const SYS_rt_sigaction: ::c_long = 13; -pub const SYS_rt_sigprocmask: ::c_long = 14; -pub const SYS_rt_sigreturn: ::c_long = 15; -pub const SYS_ioctl: ::c_long = 16; -pub const SYS_pread64: ::c_long = 17; -pub const SYS_pwrite64: ::c_long = 18; -pub const SYS_readv: ::c_long = 19; -pub const SYS_writev: ::c_long = 20; -pub const SYS_access: ::c_long = 21; -pub const SYS_pipe: ::c_long = 22; -pub const SYS_select: ::c_long = 23; -pub const SYS_sched_yield: ::c_long = 24; -pub const SYS_mremap: ::c_long = 25; -pub const SYS_msync: ::c_long = 26; -pub const SYS_mincore: ::c_long = 27; -pub const SYS_madvise: ::c_long = 28; -pub const SYS_shmget: ::c_long = 29; -pub const SYS_shmat: ::c_long = 30; -pub const SYS_shmctl: ::c_long = 31; -pub const SYS_dup: ::c_long = 32; -pub const SYS_dup2: ::c_long = 33; -pub const SYS_pause: ::c_long = 34; -pub const SYS_nanosleep: ::c_long = 35; -pub const SYS_getitimer: ::c_long = 36; -pub const SYS_alarm: ::c_long = 37; -pub const SYS_setitimer: ::c_long = 38; -pub const SYS_getpid: ::c_long = 39; -pub const SYS_sendfile: ::c_long = 40; -pub const SYS_socket: ::c_long = 41; -pub const SYS_connect: ::c_long = 42; -pub const SYS_accept: ::c_long = 43; -pub const SYS_sendto: ::c_long = 44; -pub const SYS_recvfrom: ::c_long = 45; -pub const SYS_sendmsg: ::c_long = 46; -pub const SYS_recvmsg: ::c_long = 47; -pub const SYS_shutdown: ::c_long = 48; -pub const SYS_bind: ::c_long = 49; -pub const SYS_listen: ::c_long = 50; -pub const SYS_getsockname: ::c_long = 51; -pub const SYS_getpeername: ::c_long = 52; -pub const SYS_socketpair: ::c_long = 53; -pub const SYS_setsockopt: ::c_long = 54; -pub const SYS_getsockopt: ::c_long = 55; -pub const SYS_clone: ::c_long = 56; -pub const SYS_fork: ::c_long = 57; -pub const SYS_vfork: ::c_long = 58; -pub const SYS_execve: ::c_long = 59; -pub const SYS_exit: ::c_long = 60; -pub const SYS_wait4: ::c_long = 61; -pub const SYS_kill: ::c_long = 62; -pub const SYS_uname: ::c_long = 63; -pub const SYS_semget: ::c_long = 64; -pub const SYS_semop: ::c_long = 65; -pub const SYS_semctl: ::c_long = 66; -pub const SYS_shmdt: ::c_long = 67; -pub const SYS_msgget: ::c_long = 68; -pub const SYS_msgsnd: ::c_long = 69; -pub const SYS_msgrcv: ::c_long = 70; -pub const SYS_msgctl: ::c_long = 71; -pub const SYS_fcntl: ::c_long = 72; -pub const SYS_flock: ::c_long = 73; -pub const SYS_fsync: ::c_long = 74; -pub const SYS_fdatasync: ::c_long = 75; -pub const SYS_truncate: ::c_long = 76; -pub const SYS_ftruncate: ::c_long = 77; -pub const SYS_getdents: ::c_long = 78; -pub const SYS_getcwd: ::c_long = 79; -pub const SYS_chdir: ::c_long = 80; -pub const SYS_fchdir: ::c_long = 81; -pub const SYS_rename: ::c_long = 82; -pub const SYS_mkdir: ::c_long = 83; -pub const SYS_rmdir: ::c_long = 84; -pub const SYS_creat: ::c_long = 85; -pub const SYS_link: ::c_long = 86; -pub const SYS_unlink: ::c_long = 87; -pub const SYS_symlink: ::c_long = 88; -pub const SYS_readlink: ::c_long = 89; -pub const SYS_chmod: ::c_long = 90; -pub const SYS_fchmod: ::c_long = 91; -pub const SYS_chown: ::c_long = 92; -pub const SYS_fchown: ::c_long = 93; -pub const SYS_lchown: ::c_long = 94; -pub const SYS_umask: ::c_long = 95; -pub const SYS_gettimeofday: ::c_long = 96; -pub const SYS_getrlimit: ::c_long = 97; -pub const SYS_getrusage: ::c_long = 98; -pub const SYS_sysinfo: ::c_long = 99; -pub const SYS_times: ::c_long = 100; -pub const SYS_ptrace: ::c_long = 101; -pub const SYS_getuid: ::c_long = 102; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_getgid: ::c_long = 104; -pub const SYS_setuid: ::c_long = 105; -pub const SYS_setgid: ::c_long = 106; -pub const SYS_geteuid: ::c_long = 107; -pub const SYS_getegid: ::c_long = 108; -pub const SYS_setpgid: ::c_long = 109; -pub const SYS_getppid: ::c_long = 110; -pub const SYS_getpgrp: ::c_long = 111; -pub const SYS_setsid: ::c_long = 112; -pub const SYS_setreuid: ::c_long = 113; -pub const SYS_setregid: ::c_long = 114; -pub const SYS_getgroups: ::c_long = 115; -pub const SYS_setgroups: ::c_long = 116; -pub const SYS_setresuid: ::c_long = 117; -pub const SYS_getresuid: ::c_long = 118; -pub const SYS_setresgid: ::c_long = 119; -pub const SYS_getresgid: ::c_long = 120; -pub const SYS_getpgid: ::c_long = 121; -pub const SYS_setfsuid: ::c_long = 122; -pub const SYS_setfsgid: ::c_long = 123; -pub const SYS_getsid: ::c_long = 124; -pub const SYS_capget: ::c_long = 125; -pub const SYS_capset: ::c_long = 126; -pub const SYS_rt_sigpending: ::c_long = 127; -pub const SYS_rt_sigtimedwait: ::c_long = 128; -pub const SYS_rt_sigqueueinfo: ::c_long = 129; -pub const SYS_rt_sigsuspend: ::c_long = 130; -pub const SYS_sigaltstack: ::c_long = 131; -pub const SYS_utime: ::c_long = 132; -pub const SYS_mknod: ::c_long = 133; -pub const SYS_uselib: ::c_long = 134; -pub const SYS_personality: ::c_long = 135; -pub const SYS_ustat: ::c_long = 136; -pub const SYS_statfs: ::c_long = 137; -pub const SYS_fstatfs: ::c_long = 138; -pub const SYS_sysfs: ::c_long = 139; -pub const SYS_getpriority: ::c_long = 140; -pub const SYS_setpriority: ::c_long = 141; -pub const SYS_sched_setparam: ::c_long = 142; -pub const SYS_sched_getparam: ::c_long = 143; -pub const SYS_sched_setscheduler: ::c_long = 144; -pub const SYS_sched_getscheduler: ::c_long = 145; -pub const SYS_sched_get_priority_max: ::c_long = 146; -pub const SYS_sched_get_priority_min: ::c_long = 147; -pub const SYS_sched_rr_get_interval: ::c_long = 148; -pub const SYS_mlock: ::c_long = 149; -pub const SYS_munlock: ::c_long = 150; -pub const SYS_mlockall: ::c_long = 151; -pub const SYS_munlockall: ::c_long = 152; -pub const SYS_vhangup: ::c_long = 153; -pub const SYS_modify_ldt: ::c_long = 154; -pub const SYS_pivot_root: ::c_long = 155; -pub const SYS__sysctl: ::c_long = 156; -pub const SYS_prctl: ::c_long = 157; -pub const SYS_arch_prctl: ::c_long = 158; -pub const SYS_adjtimex: ::c_long = 159; -pub const SYS_setrlimit: ::c_long = 160; -pub const SYS_chroot: ::c_long = 161; -pub const SYS_sync: ::c_long = 162; -pub const SYS_acct: ::c_long = 163; -pub const SYS_settimeofday: ::c_long = 164; -pub const SYS_mount: ::c_long = 165; -pub const SYS_umount2: ::c_long = 166; -pub const SYS_swapon: ::c_long = 167; -pub const SYS_swapoff: ::c_long = 168; -pub const SYS_reboot: ::c_long = 169; -pub const SYS_sethostname: ::c_long = 170; -pub const SYS_setdomainname: ::c_long = 171; -pub const SYS_iopl: ::c_long = 172; -pub const SYS_ioperm: ::c_long = 173; -pub const SYS_create_module: ::c_long = 174; -pub const SYS_init_module: ::c_long = 175; -pub const SYS_delete_module: ::c_long = 176; -pub const SYS_get_kernel_syms: ::c_long = 177; -pub const SYS_query_module: ::c_long = 178; -pub const SYS_quotactl: ::c_long = 179; -pub const SYS_nfsservctl: ::c_long = 180; -pub const SYS_getpmsg: ::c_long = 181; -pub const SYS_putpmsg: ::c_long = 182; -pub const SYS_afs_syscall: ::c_long = 183; -pub const SYS_tuxcall: ::c_long = 184; -pub const SYS_security: ::c_long = 185; -pub const SYS_gettid: ::c_long = 186; -pub const SYS_readahead: ::c_long = 187; -pub const SYS_setxattr: ::c_long = 188; -pub const SYS_lsetxattr: ::c_long = 189; -pub const SYS_fsetxattr: ::c_long = 190; -pub const SYS_getxattr: ::c_long = 191; -pub const SYS_lgetxattr: ::c_long = 192; -pub const SYS_fgetxattr: ::c_long = 193; -pub const SYS_listxattr: ::c_long = 194; -pub const SYS_llistxattr: ::c_long = 195; -pub const SYS_flistxattr: ::c_long = 196; -pub const SYS_removexattr: ::c_long = 197; -pub const SYS_lremovexattr: ::c_long = 198; -pub const SYS_fremovexattr: ::c_long = 199; -pub const SYS_tkill: ::c_long = 200; -pub const SYS_time: ::c_long = 201; -pub const SYS_futex: ::c_long = 202; -pub const SYS_sched_setaffinity: ::c_long = 203; -pub const SYS_sched_getaffinity: ::c_long = 204; -pub const SYS_set_thread_area: ::c_long = 205; -pub const SYS_io_setup: ::c_long = 206; -pub const SYS_io_destroy: ::c_long = 207; -pub const SYS_io_getevents: ::c_long = 208; -pub const SYS_io_submit: ::c_long = 209; -pub const SYS_io_cancel: ::c_long = 210; -pub const SYS_get_thread_area: ::c_long = 211; -pub const SYS_lookup_dcookie: ::c_long = 212; -pub const SYS_epoll_create: ::c_long = 213; -pub const SYS_epoll_ctl_old: ::c_long = 214; -pub const SYS_epoll_wait_old: ::c_long = 215; -pub const SYS_remap_file_pages: ::c_long = 216; -pub const SYS_getdents64: ::c_long = 217; -pub const SYS_set_tid_address: ::c_long = 218; -pub const SYS_restart_syscall: ::c_long = 219; -pub const SYS_semtimedop: ::c_long = 220; -pub const SYS_fadvise64: ::c_long = 221; -pub const SYS_timer_create: ::c_long = 222; -pub const SYS_timer_settime: ::c_long = 223; -pub const SYS_timer_gettime: ::c_long = 224; -pub const SYS_timer_getoverrun: ::c_long = 225; -pub const SYS_timer_delete: ::c_long = 226; -pub const SYS_clock_settime: ::c_long = 227; -pub const SYS_clock_gettime: ::c_long = 228; -pub const SYS_clock_getres: ::c_long = 229; -pub const SYS_clock_nanosleep: ::c_long = 230; -pub const SYS_exit_group: ::c_long = 231; -pub const SYS_epoll_wait: ::c_long = 232; -pub const SYS_epoll_ctl: ::c_long = 233; -pub const SYS_tgkill: ::c_long = 234; -pub const SYS_utimes: ::c_long = 235; -pub const SYS_vserver: ::c_long = 236; -pub const SYS_mbind: ::c_long = 237; -pub const SYS_set_mempolicy: ::c_long = 238; -pub const SYS_get_mempolicy: ::c_long = 239; -pub const SYS_mq_open: ::c_long = 240; -pub const SYS_mq_unlink: ::c_long = 241; -pub const SYS_mq_timedsend: ::c_long = 242; -pub const SYS_mq_timedreceive: ::c_long = 243; -pub const SYS_mq_notify: ::c_long = 244; -pub const SYS_mq_getsetattr: ::c_long = 245; -pub const SYS_kexec_load: ::c_long = 246; -pub const SYS_waitid: ::c_long = 247; -pub const SYS_add_key: ::c_long = 248; -pub const SYS_request_key: ::c_long = 249; -pub const SYS_keyctl: ::c_long = 250; -pub const SYS_ioprio_set: ::c_long = 251; -pub const SYS_ioprio_get: ::c_long = 252; -pub const SYS_inotify_init: ::c_long = 253; -pub const SYS_inotify_add_watch: ::c_long = 254; -pub const SYS_inotify_rm_watch: ::c_long = 255; -pub const SYS_migrate_pages: ::c_long = 256; -pub const SYS_openat: ::c_long = 257; -pub const SYS_mkdirat: ::c_long = 258; -pub const SYS_mknodat: ::c_long = 259; -pub const SYS_fchownat: ::c_long = 260; -pub const SYS_futimesat: ::c_long = 261; -pub const SYS_newfstatat: ::c_long = 262; -pub const SYS_unlinkat: ::c_long = 263; -pub const SYS_renameat: ::c_long = 264; -pub const SYS_linkat: ::c_long = 265; -pub const SYS_symlinkat: ::c_long = 266; -pub const SYS_readlinkat: ::c_long = 267; -pub const SYS_fchmodat: ::c_long = 268; -pub const SYS_faccessat: ::c_long = 269; -pub const SYS_pselect6: ::c_long = 270; -pub const SYS_ppoll: ::c_long = 271; -pub const SYS_unshare: ::c_long = 272; -pub const SYS_set_robust_list: ::c_long = 273; -pub const SYS_get_robust_list: ::c_long = 274; -pub const SYS_splice: ::c_long = 275; -pub const SYS_tee: ::c_long = 276; -pub const SYS_sync_file_range: ::c_long = 277; -pub const SYS_vmsplice: ::c_long = 278; -pub const SYS_move_pages: ::c_long = 279; -pub const SYS_utimensat: ::c_long = 280; -pub const SYS_epoll_pwait: ::c_long = 281; -pub const SYS_signalfd: ::c_long = 282; -pub const SYS_timerfd_create: ::c_long = 283; -pub const SYS_eventfd: ::c_long = 284; -pub const SYS_fallocate: ::c_long = 285; -pub const SYS_timerfd_settime: ::c_long = 286; -pub const SYS_timerfd_gettime: ::c_long = 287; -pub const SYS_accept4: ::c_long = 288; -pub const SYS_signalfd4: ::c_long = 289; -pub const SYS_eventfd2: ::c_long = 290; -pub const SYS_epoll_create1: ::c_long = 291; -pub const SYS_dup3: ::c_long = 292; -pub const SYS_pipe2: ::c_long = 293; -pub const SYS_inotify_init1: ::c_long = 294; -pub const SYS_preadv: ::c_long = 295; -pub const SYS_pwritev: ::c_long = 296; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 297; -pub const SYS_perf_event_open: ::c_long = 298; -pub const SYS_recvmmsg: ::c_long = 299; -pub const SYS_fanotify_init: ::c_long = 300; -pub const SYS_fanotify_mark: ::c_long = 301; -pub const SYS_prlimit64: ::c_long = 302; -pub const SYS_name_to_handle_at: ::c_long = 303; -pub const SYS_open_by_handle_at: ::c_long = 304; -pub const SYS_clock_adjtime: ::c_long = 305; -pub const SYS_syncfs: ::c_long = 306; -pub const SYS_sendmmsg: ::c_long = 307; -pub const SYS_setns: ::c_long = 308; -pub const SYS_getcpu: ::c_long = 309; -pub const SYS_process_vm_readv: ::c_long = 310; -pub const SYS_process_vm_writev: ::c_long = 311; -pub const SYS_kcmp: ::c_long = 312; -pub const SYS_finit_module: ::c_long = 313; -pub const SYS_sched_setattr: ::c_long = 314; -pub const SYS_sched_getattr: ::c_long = 315; -pub const SYS_renameat2: ::c_long = 316; -pub const SYS_seccomp: ::c_long = 317; -pub const SYS_getrandom: ::c_long = 318; -pub const SYS_memfd_create: ::c_long = 319; -pub const SYS_kexec_file_load: ::c_long = 320; -pub const SYS_bpf: ::c_long = 321; -pub const SYS_execveat: ::c_long = 322; -pub const SYS_userfaultfd: ::c_long = 323; -pub const SYS_membarrier: ::c_long = 324; -pub const SYS_mlock2: ::c_long = 325; -pub const SYS_copy_file_range: ::c_long = 326; -pub const SYS_preadv2: ::c_long = 327; -pub const SYS_pwritev2: ::c_long = 328; -// FIXME syscalls 329-331 have been added in musl 1.16 -// See discussion https://github.com/rust-lang/libc/pull/699 - -// offsets in user_regs_structs, from sys/reg.h -pub const R15: ::c_int = 0; -pub const R14: ::c_int = 1; -pub const R13: ::c_int = 2; -pub const R12: ::c_int = 3; -pub const RBP: ::c_int = 4; -pub const RBX: ::c_int = 5; -pub const R11: ::c_int = 6; -pub const R10: ::c_int = 7; -pub const R9: ::c_int = 8; -pub const R8: ::c_int = 9; -pub const RAX: ::c_int = 10; -pub const RCX: ::c_int = 11; -pub const RDX: ::c_int = 12; -pub const RSI: ::c_int = 13; -pub const RDI: ::c_int = 14; -pub const ORIG_RAX: ::c_int = 15; -pub const RIP: ::c_int = 16; -pub const CS: ::c_int = 17; -pub const EFLAGS: ::c_int = 18; -pub const RSP: ::c_int = 19; -pub const SS: ::c_int = 20; -pub const FS_BASE: ::c_int = 21; -pub const GS_BASE: ::c_int = 22; -pub const DS: ::c_int = 23; -pub const ES: ::c_int = 24; -pub const FS: ::c_int = 25; -pub const GS: ::c_int = 26; - -pub const MAP_32BIT: ::c_int = 0x0040; -pub const O_DIRECT: ::c_int = 0x4000; -pub const O_DIRECTORY: ::c_int = 0x10000; -pub const O_LARGEFILE: ::c_int = 0; -pub const O_NOFOLLOW: ::c_int = 0x20000; - -pub const SIGSTKSZ: ::size_t = 8192; -pub const MINSIGSTKSZ: ::size_t = 2048; - -#[doc(hidden)] -pub const AF_MAX: ::c_int = 42; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/musl/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,321 +0,0 @@ -pub type clock_t = c_long; -pub type time_t = c_long; -pub type suseconds_t = c_long; -pub type ino_t = u64; -pub type off_t = i64; -pub type blkcnt_t = i64; - -pub type shmatt_t = ::c_ulong; -pub type msgqnum_t = ::c_ulong; -pub type msglen_t = ::c_ulong; -pub type fsblkcnt_t = ::c_ulonglong; -pub type fsfilcnt_t = ::c_ulonglong; -pub type rlim_t = ::c_ulonglong; - -s! { - pub struct aiocb { - pub aio_fildes: ::c_int, - pub aio_lio_opcode: ::c_int, - pub aio_reqprio: ::c_int, - pub aio_buf: *mut ::c_void, - pub aio_nbytes: ::size_t, - pub aio_sigevent: ::sigevent, - __td: *mut ::c_void, - __lock: [::c_int; 2], - __err: ::c_int, - __ret: ::ssize_t, - pub aio_offset: off_t, - __next: *mut ::c_void, - __prev: *mut ::c_void, - #[cfg(target_pointer_width = "32")] - __dummy4: [::c_char; 24], - #[cfg(target_pointer_width = "64")] - __dummy4: [::c_char; 16], - } - - pub struct sigaction { - pub sa_sigaction: ::sighandler_t, - pub sa_mask: ::sigset_t, - pub sa_flags: ::c_int, - pub sa_restorer: ::dox::Option, - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; ::NCCS], - pub __c_ispeed: ::speed_t, - pub __c_ospeed: ::speed_t, - } - - pub struct flock { - pub l_type: ::c_short, - pub l_whence: ::c_short, - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_pid: ::pid_t, - } - - pub struct sysinfo { - pub uptime: ::c_ulong, - pub loads: [::c_ulong; 3], - pub totalram: ::c_ulong, - pub freeram: ::c_ulong, - pub sharedram: ::c_ulong, - pub bufferram: ::c_ulong, - pub totalswap: ::c_ulong, - pub freeswap: ::c_ulong, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: ::c_ulong, - pub freehigh: ::c_ulong, - pub mem_unit: ::c_uint, - pub __reserved: [::c_char; 256], - } -} - -pub const SFD_CLOEXEC: ::c_int = 0x080000; - -pub const NCCS: usize = 32; - -pub const O_TRUNC: ::c_int = 512; -pub const O_NOATIME: ::c_int = 0o1000000; -pub const O_CLOEXEC: ::c_int = 0x80000; -pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; - -pub const EBFONT: ::c_int = 59; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENONET: ::c_int = 64; -pub const ENOPKG: ::c_int = 65; -pub const EREMOTE: ::c_int = 66; -pub const ENOLINK: ::c_int = 67; -pub const EADV: ::c_int = 68; -pub const ESRMNT: ::c_int = 69; -pub const ECOMM: ::c_int = 70; -pub const EPROTO: ::c_int = 71; -pub const EDOTDOT: ::c_int = 73; - -pub const SA_NODEFER: ::c_int = 0x40000000; -pub const SA_RESETHAND: ::c_int = 0x80000000; -pub const SA_RESTART: ::c_int = 0x10000000; -pub const SA_NOCLDSTOP: ::c_int = 0x00000001; - -pub const EPOLL_CLOEXEC: ::c_int = 0x80000; - -pub const EFD_CLOEXEC: ::c_int = 0x80000; - -pub const BUFSIZ: ::c_uint = 1024; -pub const TMP_MAX: ::c_uint = 10000; -pub const FOPEN_MAX: ::c_uint = 1000; -pub const O_PATH: ::c_int = 0o10000000; -pub const O_EXEC: ::c_int = 0o10000000; -pub const O_SEARCH: ::c_int = 0o10000000; -pub const O_ACCMODE: ::c_int = 0o10000003; -pub const O_NDELAY: ::c_int = O_NONBLOCK; -pub const NI_MAXHOST: ::socklen_t = 255; -pub const PTHREAD_STACK_MIN: ::size_t = 2048; -pub const POSIX_FADV_DONTNEED: ::c_int = 4; -pub const POSIX_FADV_NOREUSE: ::c_int = 5; - -pub const POSIX_MADV_DONTNEED: ::c_int = 4; - -pub const RLIM_INFINITY: ::rlim_t = !0; -pub const RLIMIT_RTTIME: ::c_int = 15; -pub const RLIMIT_NLIMITS: ::c_int = 16; - -pub const MAP_ANONYMOUS: ::c_int = MAP_ANON; - -pub const SOCK_DCCP: ::c_int = 6; -pub const SOCK_PACKET: ::c_int = 10; - -pub const TCP_COOKIE_TRANSACTIONS: ::c_int = 15; -pub const TCP_THIN_LINEAR_TIMEOUTS: ::c_int = 16; -pub const TCP_THIN_DUPACK: ::c_int = 17; -pub const TCP_USER_TIMEOUT: ::c_int = 18; -pub const TCP_REPAIR: ::c_int = 19; -pub const TCP_REPAIR_QUEUE: ::c_int = 20; -pub const TCP_QUEUE_SEQ: ::c_int = 21; -pub const TCP_REPAIR_OPTIONS: ::c_int = 22; -pub const TCP_FASTOPEN: ::c_int = 23; -pub const TCP_TIMESTAMP: ::c_int = 24; - -pub const SIGUNUSED: ::c_int = ::SIGSYS; - -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; - -pub const CPU_SETSIZE: ::c_int = 128; - -pub const PTRACE_TRACEME: ::c_int = 0; -pub const PTRACE_PEEKTEXT: ::c_int = 1; -pub const PTRACE_PEEKDATA: ::c_int = 2; -pub const PTRACE_PEEKUSER: ::c_int = 3; -pub const PTRACE_POKETEXT: ::c_int = 4; -pub const PTRACE_POKEDATA: ::c_int = 5; -pub const PTRACE_POKEUSER: ::c_int = 6; -pub const PTRACE_CONT: ::c_int = 7; -pub const PTRACE_KILL: ::c_int = 8; -pub const PTRACE_SINGLESTEP: ::c_int = 9; -pub const PTRACE_GETREGS: ::c_int = 12; -pub const PTRACE_SETREGS: ::c_int = 13; -pub const PTRACE_GETFPREGS: ::c_int = 14; -pub const PTRACE_SETFPREGS: ::c_int = 15; -pub const PTRACE_ATTACH: ::c_int = 16; -pub const PTRACE_DETACH: ::c_int = 17; -pub const PTRACE_GETFPXREGS: ::c_int = 18; -pub const PTRACE_SETFPXREGS: ::c_int = 19; -pub const PTRACE_SYSCALL: ::c_int = 24; -pub const PTRACE_SETOPTIONS: ::c_int = 0x4200; -pub const PTRACE_GETEVENTMSG: ::c_int = 0x4201; -pub const PTRACE_GETSIGINFO: ::c_int = 0x4202; -pub const PTRACE_SETSIGINFO: ::c_int = 0x4203; -pub const PTRACE_GETREGSET: ::c_int = 0x4204; -pub const PTRACE_SETREGSET: ::c_int = 0x4205; -pub const PTRACE_SEIZE: ::c_int = 0x4206; -pub const PTRACE_INTERRUPT: ::c_int = 0x4207; -pub const PTRACE_LISTEN: ::c_int = 0x4208; -pub const PTRACE_PEEKSIGINFO: ::c_int = 0x4209; - -pub const EPOLLWAKEUP: ::c_int = 0x20000000; - -pub const EFD_NONBLOCK: ::c_int = ::O_NONBLOCK; - -pub const SFD_NONBLOCK: ::c_int = ::O_NONBLOCK; - -pub const TCSANOW: ::c_int = 0; -pub const TCSADRAIN: ::c_int = 1; -pub const TCSAFLUSH: ::c_int = 2; - -pub const TIOCINQ: ::c_int = ::FIONREAD; - -pub const RTLD_GLOBAL: ::c_int = 0x100; -pub const RTLD_NOLOAD: ::c_int = 0x4; - -// TODO(#247) Temporarily musl-specific (available since musl 0.9.12 / Linux -// kernel 3.10). See also notbsd/mod.rs -pub const CLOCK_SGI_CYCLE: ::clockid_t = 10; -pub const CLOCK_TAI: ::clockid_t = 11; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const CBAUD: ::tcflag_t = 0o0010017; -pub const TAB1: ::c_int = 0x00000800; -pub const TAB2: ::c_int = 0x00001000; -pub const TAB3: ::c_int = 0x00001800; -pub const CR1: ::c_int = 0x00000200; -pub const CR2: ::c_int = 0x00000400; -pub const CR3: ::c_int = 0x00000600; -pub const FF1: ::c_int = 0x00008000; -pub const BS1: ::c_int = 0x00002000; -pub const VT1: ::c_int = 0x00004000; -pub const VWERASE: usize = 14; -pub const VREPRINT: usize = 12; -pub const VSUSP: usize = 10; -pub const VSTART: usize = 8; -pub const VSTOP: usize = 9; -pub const VDISCARD: usize = 13; -pub const VTIME: usize = 5; -pub const IXON: ::tcflag_t = 0x00000400; -pub const IXOFF: ::tcflag_t = 0x00001000; -pub const ONLCR: ::tcflag_t = 0x4; -pub const CSIZE: ::tcflag_t = 0x00000030; -pub const CS6: ::tcflag_t = 0x00000010; -pub const CS7: ::tcflag_t = 0x00000020; -pub const CS8: ::tcflag_t = 0x00000030; -pub const CSTOPB: ::tcflag_t = 0x00000040; -pub const CREAD: ::tcflag_t = 0x00000080; -pub const PARENB: ::tcflag_t = 0x00000100; -pub const PARODD: ::tcflag_t = 0x00000200; -pub const HUPCL: ::tcflag_t = 0x00000400; -pub const CLOCAL: ::tcflag_t = 0x00000800; -pub const ECHOKE: ::tcflag_t = 0x00000800; -pub const ECHOE: ::tcflag_t = 0x00000010; -pub const ECHOK: ::tcflag_t = 0x00000020; -pub const ECHONL: ::tcflag_t = 0x00000040; -pub const ECHOPRT: ::tcflag_t = 0x00000400; -pub const ECHOCTL: ::tcflag_t = 0x00000200; -pub const ISIG: ::tcflag_t = 0x00000001; -pub const ICANON: ::tcflag_t = 0x00000002; -pub const PENDIN: ::tcflag_t = 0x00004000; -pub const NOFLSH: ::tcflag_t = 0x00000080; -pub const CIBAUD: ::tcflag_t = 0o02003600000; -pub const CBAUDEX: ::tcflag_t = 0o010000; -pub const VSWTC: usize = 7; -pub const OLCUC: ::tcflag_t = 0o000002; -pub const NLDLY: ::tcflag_t = 0o000400; -pub const CRDLY: ::tcflag_t = 0o003000; -pub const TABDLY: ::tcflag_t = 0o014000; -pub const BSDLY: ::tcflag_t = 0o020000; -pub const FFDLY: ::tcflag_t = 0o100000; -pub const VTDLY: ::tcflag_t = 0o040000; -pub const XTABS: ::tcflag_t = 0o014000; - -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const EXTA: ::speed_t = B19200; -pub const EXTB: ::speed_t = B38400; -pub const B57600: ::speed_t = 0o010001; -pub const B115200: ::speed_t = 0o010002; -pub const B230400: ::speed_t = 0o010003; -pub const B460800: ::speed_t = 0o010004; -pub const B500000: ::speed_t = 0o010005; -pub const B576000: ::speed_t = 0o010006; -pub const B921600: ::speed_t = 0o010007; -pub const B1000000: ::speed_t = 0o010010; -pub const B1152000: ::speed_t = 0o010011; -pub const B1500000: ::speed_t = 0o010012; -pub const B2000000: ::speed_t = 0o010013; -pub const B2500000: ::speed_t = 0o010014; -pub const B3000000: ::speed_t = 0o010015; -pub const B3500000: ::speed_t = 0o010016; -pub const B4000000: ::speed_t = 0o010017; - -pub const SO_BINDTODEVICE: ::c_int = 25; -pub const SO_TIMESTAMP: ::c_int = 29; -pub const SO_MARK: ::c_int = 36; -pub const SO_RXQ_OVFL: ::c_int = 40; -pub const SO_PEEK_OFF: ::c_int = 42; -pub const SO_BUSY_POLL: ::c_int = 46; - -extern { - pub fn ioctl(fd: ::c_int, request: ::c_int, ...) -> ::c_int; - pub fn ptrace(request: ::c_int, ...) -> ::c_long; - pub fn getpriority(which: ::c_int, who: ::id_t) -> ::c_int; - pub fn setpriority(which: ::c_int, who: ::id_t, prio: ::c_int) -> ::c_int; -} - -cfg_if! { - if #[cfg(any(target_arch = "x86_64", - target_arch = "aarch64", - target_arch = "powerpc64"))] { - mod b64; - pub use self::b64::*; - } else if #[cfg(any(target_arch = "x86", - target_arch = "mips", - target_arch = "arm"))] { - mod b32; - pub use self::b32::*; - } else { } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/arm.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/arm.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/arm.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/arm.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,612 +0,0 @@ -pub type c_char = u8; -pub type wchar_t = u32; - -s! { - pub struct ipc_perm { - pub __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::c_ushort, - __pad1: ::c_ushort, - pub __seq: ::c_ushort, - __pad2: ::c_ushort, - __unused1: ::c_ulong, - __unused2: ::c_ulong - } - - pub struct stat64 { - pub st_dev: ::dev_t, - __pad1: ::c_uint, - __st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad2: ::c_uint, - pub st_size: ::off64_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_ino: ::ino64_t, - } - - pub struct statfs64 { - pub f_type: ::__fsword_t, - pub f_bsize: ::__fsword_t, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_fsid: ::fsid_t, - pub f_namelen: ::__fsword_t, - pub f_frsize: ::__fsword_t, - pub f_flags: ::__fsword_t, - pub f_spare: [::__fsword_t; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - __f_unused: ::c_int, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - __unused1: ::c_ulong, - pub shm_dtime: ::time_t, - __unused2: ::c_ulong, - pub shm_ctime: ::time_t, - __unused3: ::c_ulong, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __unused4: ::c_ulong, - __unused5: ::c_ulong - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - pub msg_stime: ::time_t, - __glibc_reserved1: ::c_ulong, - pub msg_rtime: ::time_t, - __glibc_reserved2: ::c_ulong, - pub msg_ctime: ::time_t, - __glibc_reserved3: ::c_ulong, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __glibc_reserved4: ::c_ulong, - __glibc_reserved5: ::c_ulong, - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 19], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } -} - -pub const O_DIRECT: ::c_int = 0x10000; -pub const O_DIRECTORY: ::c_int = 0x4000; -pub const O_NOFOLLOW: ::c_int = 0x8000; -pub const O_LARGEFILE: ::c_int = 0o400000; - -pub const MAP_LOCKED: ::c_int = 0x02000; -pub const MAP_NORESERVE: ::c_int = 0x04000; - -pub const EDEADLOCK: ::c_int = 35; - -pub const SO_PASSCRED: ::c_int = 16; -pub const SO_PEERCRED: ::c_int = 17; -pub const SO_RCVLOWAT: ::c_int = 18; -pub const SO_SNDLOWAT: ::c_int = 19; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_SNDTIMEO: ::c_int = 21; -pub const SO_SNDBUFFORCE: ::c_int = 32; -pub const SO_RCVBUFFORCE: ::c_int = 33; - -pub const FIOCLEX: ::c_ulong = 0x5451; -pub const FIONBIO: ::c_ulong = 0x5421; - -pub const PTRACE_GETFPXREGS: ::c_uint = 18; -pub const PTRACE_SETFPXREGS: ::c_uint = 19; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const SIGSTKSZ: ::size_t = 8192; -pub const MINSIGSTKSZ: ::size_t = 2048; -pub const CBAUD: ::tcflag_t = 0o0010017; -pub const TAB1: ::c_int = 0x00000800; -pub const TAB2: ::c_int = 0x00001000; -pub const TAB3: ::c_int = 0x00001800; -pub const CR1: ::c_int = 0x00000200; -pub const CR2: ::c_int = 0x00000400; -pub const CR3: ::c_int = 0x00000600; -pub const FF1: ::c_int = 0x00008000; -pub const BS1: ::c_int = 0x00002000; -pub const VT1: ::c_int = 0x00004000; -pub const VWERASE: usize = 14; -pub const VREPRINT: usize = 12; -pub const VSUSP: usize = 10; -pub const VSTART: usize = 8; -pub const VSTOP: usize = 9; -pub const VDISCARD: usize = 13; -pub const VTIME: usize = 5; -pub const IXON: ::tcflag_t = 0x00000400; -pub const IXOFF: ::tcflag_t = 0x00001000; -pub const ONLCR: ::tcflag_t = 0x4; -pub const CSIZE: ::tcflag_t = 0x00000030; -pub const CS6: ::tcflag_t = 0x00000010; -pub const CS7: ::tcflag_t = 0x00000020; -pub const CS8: ::tcflag_t = 0x00000030; -pub const CSTOPB: ::tcflag_t = 0x00000040; -pub const CREAD: ::tcflag_t = 0x00000080; -pub const PARENB: ::tcflag_t = 0x00000100; -pub const PARODD: ::tcflag_t = 0x00000200; -pub const HUPCL: ::tcflag_t = 0x00000400; -pub const CLOCAL: ::tcflag_t = 0x00000800; -pub const ECHOKE: ::tcflag_t = 0x00000800; -pub const ECHOE: ::tcflag_t = 0x00000010; -pub const ECHOK: ::tcflag_t = 0x00000020; -pub const ECHONL: ::tcflag_t = 0x00000040; -pub const ECHOPRT: ::tcflag_t = 0x00000400; -pub const ECHOCTL: ::tcflag_t = 0x00000200; -pub const ISIG: ::tcflag_t = 0x00000001; -pub const ICANON: ::tcflag_t = 0x00000002; -pub const PENDIN: ::tcflag_t = 0x00004000; -pub const NOFLSH: ::tcflag_t = 0x00000080; -pub const CIBAUD: ::tcflag_t = 0o02003600000; -pub const CBAUDEX: ::tcflag_t = 0o010000; -pub const VSWTC: usize = 7; -pub const OLCUC: ::tcflag_t = 0o000002; -pub const NLDLY: ::tcflag_t = 0o000400; -pub const CRDLY: ::tcflag_t = 0o003000; -pub const TABDLY: ::tcflag_t = 0o014000; -pub const BSDLY: ::tcflag_t = 0o020000; -pub const FFDLY: ::tcflag_t = 0o100000; -pub const VTDLY: ::tcflag_t = 0o040000; -pub const XTABS: ::tcflag_t = 0o014000; - -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const EXTA: ::speed_t = B19200; -pub const EXTB: ::speed_t = B38400; -pub const BOTHER: ::speed_t = 0o010000; -pub const B57600: ::speed_t = 0o010001; -pub const B115200: ::speed_t = 0o010002; -pub const B230400: ::speed_t = 0o010003; -pub const B460800: ::speed_t = 0o010004; -pub const B500000: ::speed_t = 0o010005; -pub const B576000: ::speed_t = 0o010006; -pub const B921600: ::speed_t = 0o010007; -pub const B1000000: ::speed_t = 0o010010; -pub const B1152000: ::speed_t = 0o010011; -pub const B1500000: ::speed_t = 0o010012; -pub const B2000000: ::speed_t = 0o010013; -pub const B2500000: ::speed_t = 0o010014; -pub const B3000000: ::speed_t = 0o010015; -pub const B3500000: ::speed_t = 0o010016; -pub const B4000000: ::speed_t = 0o010017; - -pub const VEOL: usize = 11; -pub const VEOL2: usize = 16; -pub const VMIN: usize = 6; -pub const IEXTEN: ::tcflag_t = 0x00008000; -pub const TOSTOP: ::tcflag_t = 0x00000100; -pub const FLUSHO: ::tcflag_t = 0x00001000; -pub const EXTPROC: ::tcflag_t = 0x00010000; -pub const TCGETS: ::c_ulong = 0x5401; -pub const TCSETS: ::c_ulong = 0x5402; -pub const TCSETSW: ::c_ulong = 0x5403; -pub const TCSETSF: ::c_ulong = 0x5404; -pub const TCGETA: ::c_ulong = 0x5405; -pub const TCSETA: ::c_ulong = 0x5406; -pub const TCSETAW: ::c_ulong = 0x5407; -pub const TCSETAF: ::c_ulong = 0x5408; -pub const TCSBRK: ::c_ulong = 0x5409; -pub const TCXONC: ::c_ulong = 0x540A; -pub const TCFLSH: ::c_ulong = 0x540B; -pub const TIOCINQ: ::c_ulong = 0x541B; -pub const TIOCGPGRP: ::c_ulong = 0x540F; -pub const TIOCSPGRP: ::c_ulong = 0x5410; -pub const TIOCOUTQ: ::c_ulong = 0x5411; -pub const TIOCGWINSZ: ::c_ulong = 0x5413; -pub const TIOCSWINSZ: ::c_ulong = 0x5414; -pub const FIONREAD: ::c_ulong = 0x541B; - -// Syscall table -pub const SYS_restart_syscall: ::c_long = 0; -pub const SYS_exit: ::c_long = 1; -pub const SYS_fork: ::c_long = 2; -pub const SYS_read: ::c_long = 3; -pub const SYS_write: ::c_long = 4; -pub const SYS_open: ::c_long = 5; -pub const SYS_close: ::c_long = 6; -pub const SYS_creat: ::c_long = 8; -pub const SYS_link: ::c_long = 9; -pub const SYS_unlink: ::c_long = 10; -pub const SYS_execve: ::c_long = 11; -pub const SYS_chdir: ::c_long = 12; -pub const SYS_mknod: ::c_long = 14; -pub const SYS_chmod: ::c_long = 15; -pub const SYS_lchown: ::c_long = 16; -pub const SYS_lseek: ::c_long = 19; -pub const SYS_getpid: ::c_long = 20; -pub const SYS_mount: ::c_long = 21; -pub const SYS_setuid: ::c_long = 23; -pub const SYS_getuid: ::c_long = 24; -pub const SYS_ptrace: ::c_long = 26; -pub const SYS_pause: ::c_long = 29; -pub const SYS_access: ::c_long = 33; -pub const SYS_nice: ::c_long = 34; -pub const SYS_sync: ::c_long = 36; -pub const SYS_kill: ::c_long = 37; -pub const SYS_rename: ::c_long = 38; -pub const SYS_mkdir: ::c_long = 39; -pub const SYS_rmdir: ::c_long = 40; -pub const SYS_dup: ::c_long = 41; -pub const SYS_pipe: ::c_long = 42; -pub const SYS_times: ::c_long = 43; -pub const SYS_brk: ::c_long = 45; -pub const SYS_setgid: ::c_long = 46; -pub const SYS_getgid: ::c_long = 47; -pub const SYS_geteuid: ::c_long = 49; -pub const SYS_getegid: ::c_long = 50; -pub const SYS_acct: ::c_long = 51; -pub const SYS_umount2: ::c_long = 52; -pub const SYS_ioctl: ::c_long = 54; -pub const SYS_fcntl: ::c_long = 55; -pub const SYS_setpgid: ::c_long = 57; -pub const SYS_umask: ::c_long = 60; -pub const SYS_chroot: ::c_long = 61; -pub const SYS_ustat: ::c_long = 62; -pub const SYS_dup2: ::c_long = 63; -pub const SYS_getppid: ::c_long = 64; -pub const SYS_getpgrp: ::c_long = 65; -pub const SYS_setsid: ::c_long = 66; -pub const SYS_sigaction: ::c_long = 67; -pub const SYS_setreuid: ::c_long = 70; -pub const SYS_setregid: ::c_long = 71; -pub const SYS_sigsuspend: ::c_long = 72; -pub const SYS_sigpending: ::c_long = 73; -pub const SYS_sethostname: ::c_long = 74; -pub const SYS_setrlimit: ::c_long = 75; -pub const SYS_getrusage: ::c_long = 77; -pub const SYS_gettimeofday: ::c_long = 78; -pub const SYS_settimeofday: ::c_long = 79; -pub const SYS_getgroups: ::c_long = 80; -pub const SYS_setgroups: ::c_long = 81; -pub const SYS_symlink: ::c_long = 83; -pub const SYS_readlink: ::c_long = 85; -pub const SYS_uselib: ::c_long = 86; -pub const SYS_swapon: ::c_long = 87; -pub const SYS_reboot: ::c_long = 88; -pub const SYS_munmap: ::c_long = 91; -pub const SYS_truncate: ::c_long = 92; -pub const SYS_ftruncate: ::c_long = 93; -pub const SYS_fchmod: ::c_long = 94; -pub const SYS_fchown: ::c_long = 95; -pub const SYS_getpriority: ::c_long = 96; -pub const SYS_setpriority: ::c_long = 97; -pub const SYS_statfs: ::c_long = 99; -pub const SYS_fstatfs: ::c_long = 100; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_setitimer: ::c_long = 104; -pub const SYS_getitimer: ::c_long = 105; -pub const SYS_stat: ::c_long = 106; -pub const SYS_lstat: ::c_long = 107; -pub const SYS_fstat: ::c_long = 108; -pub const SYS_vhangup: ::c_long = 111; -pub const SYS_wait4: ::c_long = 114; -pub const SYS_swapoff: ::c_long = 115; -pub const SYS_sysinfo: ::c_long = 116; -pub const SYS_fsync: ::c_long = 118; -pub const SYS_sigreturn: ::c_long = 119; -pub const SYS_clone: ::c_long = 120; -pub const SYS_setdomainname: ::c_long = 121; -pub const SYS_uname: ::c_long = 122; -pub const SYS_adjtimex: ::c_long = 124; -pub const SYS_mprotect: ::c_long = 125; -pub const SYS_sigprocmask: ::c_long = 126; -pub const SYS_init_module: ::c_long = 128; -pub const SYS_delete_module: ::c_long = 129; -pub const SYS_quotactl: ::c_long = 131; -pub const SYS_getpgid: ::c_long = 132; -pub const SYS_fchdir: ::c_long = 133; -pub const SYS_bdflush: ::c_long = 134; -pub const SYS_sysfs: ::c_long = 135; -pub const SYS_personality: ::c_long = 136; -pub const SYS_setfsuid: ::c_long = 138; -pub const SYS_setfsgid: ::c_long = 139; -pub const SYS__llseek: ::c_long = 140; -pub const SYS_getdents: ::c_long = 141; -pub const SYS__newselect: ::c_long = 142; -pub const SYS_flock: ::c_long = 143; -pub const SYS_msync: ::c_long = 144; -pub const SYS_readv: ::c_long = 145; -pub const SYS_writev: ::c_long = 146; -pub const SYS_getsid: ::c_long = 147; -pub const SYS_fdatasync: ::c_long = 148; -pub const SYS__sysctl: ::c_long = 149; -pub const SYS_mlock: ::c_long = 150; -pub const SYS_munlock: ::c_long = 151; -pub const SYS_mlockall: ::c_long = 152; -pub const SYS_munlockall: ::c_long = 153; -pub const SYS_sched_setparam: ::c_long = 154; -pub const SYS_sched_getparam: ::c_long = 155; -pub const SYS_sched_setscheduler: ::c_long = 156; -pub const SYS_sched_getscheduler: ::c_long = 157; -pub const SYS_sched_yield: ::c_long = 158; -pub const SYS_sched_get_priority_max: ::c_long = 159; -pub const SYS_sched_get_priority_min: ::c_long = 160; -pub const SYS_sched_rr_get_interval: ::c_long = 161; -pub const SYS_nanosleep: ::c_long = 162; -pub const SYS_mremap: ::c_long = 163; -pub const SYS_setresuid: ::c_long = 164; -pub const SYS_getresuid: ::c_long = 165; -pub const SYS_poll: ::c_long = 168; -pub const SYS_nfsservctl: ::c_long = 169; -pub const SYS_setresgid: ::c_long = 170; -pub const SYS_getresgid: ::c_long = 171; -pub const SYS_prctl: ::c_long = 172; -pub const SYS_rt_sigreturn: ::c_long = 173; -pub const SYS_rt_sigaction: ::c_long = 174; -pub const SYS_rt_sigprocmask: ::c_long = 175; -pub const SYS_rt_sigpending: ::c_long = 176; -pub const SYS_rt_sigtimedwait: ::c_long = 177; -pub const SYS_rt_sigqueueinfo: ::c_long = 178; -pub const SYS_rt_sigsuspend: ::c_long = 179; -pub const SYS_pread64: ::c_long = 180; -pub const SYS_pwrite64: ::c_long = 181; -pub const SYS_chown: ::c_long = 182; -pub const SYS_getcwd: ::c_long = 183; -pub const SYS_capget: ::c_long = 184; -pub const SYS_capset: ::c_long = 185; -pub const SYS_sigaltstack: ::c_long = 186; -pub const SYS_sendfile: ::c_long = 187; -pub const SYS_vfork: ::c_long = 190; -pub const SYS_ugetrlimit: ::c_long = 191; -pub const SYS_mmap2: ::c_long = 192; -pub const SYS_truncate64: ::c_long = 193; -pub const SYS_ftruncate64: ::c_long = 194; -pub const SYS_stat64: ::c_long = 195; -pub const SYS_lstat64: ::c_long = 196; -pub const SYS_fstat64: ::c_long = 197; -pub const SYS_lchown32: ::c_long = 198; -pub const SYS_getuid32: ::c_long = 199; -pub const SYS_getgid32: ::c_long = 200; -pub const SYS_geteuid32: ::c_long = 201; -pub const SYS_getegid32: ::c_long = 202; -pub const SYS_setreuid32: ::c_long = 203; -pub const SYS_setregid32: ::c_long = 204; -pub const SYS_getgroups32: ::c_long = 205; -pub const SYS_setgroups32: ::c_long = 206; -pub const SYS_fchown32: ::c_long = 207; -pub const SYS_setresuid32: ::c_long = 208; -pub const SYS_getresuid32: ::c_long = 209; -pub const SYS_setresgid32: ::c_long = 210; -pub const SYS_getresgid32: ::c_long = 211; -pub const SYS_chown32: ::c_long = 212; -pub const SYS_setuid32: ::c_long = 213; -pub const SYS_setgid32: ::c_long = 214; -pub const SYS_setfsuid32: ::c_long = 215; -pub const SYS_setfsgid32: ::c_long = 216; -pub const SYS_getdents64: ::c_long = 217; -pub const SYS_pivot_root: ::c_long = 218; -pub const SYS_mincore: ::c_long = 219; -pub const SYS_madvise: ::c_long = 220; -pub const SYS_fcntl64: ::c_long = 221; -pub const SYS_gettid: ::c_long = 224; -pub const SYS_readahead: ::c_long = 225; -pub const SYS_setxattr: ::c_long = 226; -pub const SYS_lsetxattr: ::c_long = 227; -pub const SYS_fsetxattr: ::c_long = 228; -pub const SYS_getxattr: ::c_long = 229; -pub const SYS_lgetxattr: ::c_long = 230; -pub const SYS_fgetxattr: ::c_long = 231; -pub const SYS_listxattr: ::c_long = 232; -pub const SYS_llistxattr: ::c_long = 233; -pub const SYS_flistxattr: ::c_long = 234; -pub const SYS_removexattr: ::c_long = 235; -pub const SYS_lremovexattr: ::c_long = 236; -pub const SYS_fremovexattr: ::c_long = 237; -pub const SYS_tkill: ::c_long = 238; -pub const SYS_sendfile64: ::c_long = 239; -pub const SYS_futex: ::c_long = 240; -pub const SYS_sched_setaffinity: ::c_long = 241; -pub const SYS_sched_getaffinity: ::c_long = 242; -pub const SYS_io_setup: ::c_long = 243; -pub const SYS_io_destroy: ::c_long = 244; -pub const SYS_io_getevents: ::c_long = 245; -pub const SYS_io_submit: ::c_long = 246; -pub const SYS_io_cancel: ::c_long = 247; -pub const SYS_exit_group: ::c_long = 248; -pub const SYS_lookup_dcookie: ::c_long = 249; -pub const SYS_epoll_create: ::c_long = 250; -pub const SYS_epoll_ctl: ::c_long = 251; -pub const SYS_epoll_wait: ::c_long = 252; -pub const SYS_remap_file_pages: ::c_long = 253; -pub const SYS_set_tid_address: ::c_long = 256; -pub const SYS_timer_create: ::c_long = 257; -pub const SYS_timer_settime: ::c_long = 258; -pub const SYS_timer_gettime: ::c_long = 259; -pub const SYS_timer_getoverrun: ::c_long = 260; -pub const SYS_timer_delete: ::c_long = 261; -pub const SYS_clock_settime: ::c_long = 262; -pub const SYS_clock_gettime: ::c_long = 263; -pub const SYS_clock_getres: ::c_long = 264; -pub const SYS_clock_nanosleep: ::c_long = 265; -pub const SYS_statfs64: ::c_long = 266; -pub const SYS_fstatfs64: ::c_long = 267; -pub const SYS_tgkill: ::c_long = 268; -pub const SYS_utimes: ::c_long = 269; -pub const SYS_arm_fadvise64_64: ::c_long = 270; -pub const SYS_pciconfig_iobase: ::c_long = 271; -pub const SYS_pciconfig_read: ::c_long = 272; -pub const SYS_pciconfig_write: ::c_long = 273; -pub const SYS_mq_open: ::c_long = 274; -pub const SYS_mq_unlink: ::c_long = 275; -pub const SYS_mq_timedsend: ::c_long = 276; -pub const SYS_mq_timedreceive: ::c_long = 277; -pub const SYS_mq_notify: ::c_long = 278; -pub const SYS_mq_getsetattr: ::c_long = 279; -pub const SYS_waitid: ::c_long = 280; -pub const SYS_socket: ::c_long = 281; -pub const SYS_bind: ::c_long = 282; -pub const SYS_connect: ::c_long = 283; -pub const SYS_listen: ::c_long = 284; -pub const SYS_accept: ::c_long = 285; -pub const SYS_getsockname: ::c_long = 286; -pub const SYS_getpeername: ::c_long = 287; -pub const SYS_socketpair: ::c_long = 288; -pub const SYS_send: ::c_long = 289; -pub const SYS_sendto: ::c_long = 290; -pub const SYS_recv: ::c_long = 291; -pub const SYS_recvfrom: ::c_long = 292; -pub const SYS_shutdown: ::c_long = 293; -pub const SYS_setsockopt: ::c_long = 294; -pub const SYS_getsockopt: ::c_long = 295; -pub const SYS_sendmsg: ::c_long = 296; -pub const SYS_recvmsg: ::c_long = 297; -pub const SYS_semop: ::c_long = 298; -pub const SYS_semget: ::c_long = 299; -pub const SYS_semctl: ::c_long = 300; -pub const SYS_msgsnd: ::c_long = 301; -pub const SYS_msgrcv: ::c_long = 302; -pub const SYS_msgget: ::c_long = 303; -pub const SYS_msgctl: ::c_long = 304; -pub const SYS_shmat: ::c_long = 305; -pub const SYS_shmdt: ::c_long = 306; -pub const SYS_shmget: ::c_long = 307; -pub const SYS_shmctl: ::c_long = 308; -pub const SYS_add_key: ::c_long = 309; -pub const SYS_request_key: ::c_long = 310; -pub const SYS_keyctl: ::c_long = 311; -pub const SYS_semtimedop: ::c_long = 312; -pub const SYS_vserver: ::c_long = 313; -pub const SYS_ioprio_set: ::c_long = 314; -pub const SYS_ioprio_get: ::c_long = 315; -pub const SYS_inotify_init: ::c_long = 316; -pub const SYS_inotify_add_watch: ::c_long = 317; -pub const SYS_inotify_rm_watch: ::c_long = 318; -pub const SYS_mbind: ::c_long = 319; -pub const SYS_get_mempolicy: ::c_long = 320; -pub const SYS_set_mempolicy: ::c_long = 321; -pub const SYS_openat: ::c_long = 322; -pub const SYS_mkdirat: ::c_long = 323; -pub const SYS_mknodat: ::c_long = 324; -pub const SYS_fchownat: ::c_long = 325; -pub const SYS_futimesat: ::c_long = 326; -pub const SYS_fstatat64: ::c_long = 327; -pub const SYS_unlinkat: ::c_long = 328; -pub const SYS_renameat: ::c_long = 329; -pub const SYS_linkat: ::c_long = 330; -pub const SYS_symlinkat: ::c_long = 331; -pub const SYS_readlinkat: ::c_long = 332; -pub const SYS_fchmodat: ::c_long = 333; -pub const SYS_faccessat: ::c_long = 334; -pub const SYS_pselect6: ::c_long = 335; -pub const SYS_ppoll: ::c_long = 336; -pub const SYS_unshare: ::c_long = 337; -pub const SYS_set_robust_list: ::c_long = 338; -pub const SYS_get_robust_list: ::c_long = 339; -pub const SYS_splice: ::c_long = 340; -pub const SYS_arm_sync_file_range: ::c_long = 341; -pub const SYS_tee: ::c_long = 342; -pub const SYS_vmsplice: ::c_long = 343; -pub const SYS_move_pages: ::c_long = 344; -pub const SYS_getcpu: ::c_long = 345; -pub const SYS_epoll_pwait: ::c_long = 346; -pub const SYS_kexec_load: ::c_long = 347; -pub const SYS_utimensat: ::c_long = 348; -pub const SYS_signalfd: ::c_long = 349; -pub const SYS_timerfd_create: ::c_long = 350; -pub const SYS_eventfd: ::c_long = 351; -pub const SYS_fallocate: ::c_long = 352; -pub const SYS_timerfd_settime: ::c_long = 353; -pub const SYS_timerfd_gettime: ::c_long = 354; -pub const SYS_signalfd4: ::c_long = 355; -pub const SYS_eventfd2: ::c_long = 356; -pub const SYS_epoll_create1: ::c_long = 357; -pub const SYS_dup3: ::c_long = 358; -pub const SYS_pipe2: ::c_long = 359; -pub const SYS_inotify_init1: ::c_long = 360; -pub const SYS_preadv: ::c_long = 361; -pub const SYS_pwritev: ::c_long = 362; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 363; -pub const SYS_perf_event_open: ::c_long = 364; -pub const SYS_recvmmsg: ::c_long = 365; -pub const SYS_accept4: ::c_long = 366; -pub const SYS_fanotify_init: ::c_long = 367; -pub const SYS_fanotify_mark: ::c_long = 368; -pub const SYS_prlimit64: ::c_long = 369; -pub const SYS_name_to_handle_at: ::c_long = 370; -pub const SYS_open_by_handle_at: ::c_long = 371; -pub const SYS_clock_adjtime: ::c_long = 372; -pub const SYS_syncfs: ::c_long = 373; -pub const SYS_sendmmsg: ::c_long = 374; -pub const SYS_setns: ::c_long = 375; -pub const SYS_process_vm_readv: ::c_long = 376; -pub const SYS_process_vm_writev: ::c_long = 377; -pub const SYS_kcmp: ::c_long = 378; -pub const SYS_finit_module: ::c_long = 379; -pub const SYS_sched_setattr: ::c_long = 380; -pub const SYS_sched_getattr: ::c_long = 381; -pub const SYS_renameat2: ::c_long = 382; -pub const SYS_seccomp: ::c_long = 383; -pub const SYS_getrandom: ::c_long = 384; -pub const SYS_memfd_create: ::c_long = 385; -pub const SYS_bpf: ::c_long = 386; -pub const SYS_execveat: ::c_long = 387; -pub const SYS_userfaultfd: ::c_long = 388; -pub const SYS_membarrier: ::c_long = 389; -pub const SYS_mlock2: ::c_long = 390; -pub const SYS_copy_file_range: ::c_long = 391; -pub const SYS_preadv2: ::c_long = 392; -pub const SYS_pwritev2: ::c_long = 393; -pub const SYS_pkey_mprotect: ::c_long = 394; -pub const SYS_pkey_alloc: ::c_long = 395; -pub const SYS_pkey_free: ::c_long = 396; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,315 +0,0 @@ -//! 32-bit specific definitions for linux-like values - -pub type c_long = i32; -pub type c_ulong = u32; -pub type clock_t = i32; -pub type time_t = i32; -pub type suseconds_t = i32; -pub type ino_t = u32; -pub type off_t = i32; -pub type blkcnt_t = i32; -pub type __fsword_t = i32; - -pub type fsblkcnt_t = ::c_ulong; -pub type fsfilcnt_t = ::c_ulong; -pub type rlim_t = c_ulong; -pub type shmatt_t = ::c_ulong; -pub type msgqnum_t = ::c_ulong; -pub type msglen_t = ::c_ulong; -pub type blksize_t = i32; -pub type nlink_t = u32; -pub type __u64 = ::c_ulonglong; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - __pad1: ::c_short, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad2: ::c_short, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused4: ::c_long, - __unused5: ::c_long, - } - - pub struct pthread_attr_t { - __size: [u32; 9] - } - - pub struct sigset_t { - __val: [::c_ulong; 32], - } - - pub struct sysinfo { - pub uptime: ::c_long, - pub loads: [::c_ulong; 3], - pub totalram: ::c_ulong, - pub freeram: ::c_ulong, - pub sharedram: ::c_ulong, - pub bufferram: ::c_ulong, - pub totalswap: ::c_ulong, - pub freeswap: ::c_ulong, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: ::c_ulong, - pub freehigh: ::c_ulong, - pub mem_unit: ::c_uint, - pub _f: [::c_char; 8], - } -} - -pub const TIOCGSOFTCAR: ::c_ulong = 0x5419; -pub const TIOCSSOFTCAR: ::c_ulong = 0x541A; - -pub const RLIMIT_NOFILE: ::c_int = 7; -pub const RLIMIT_NPROC: ::c_int = 6; - -pub const O_APPEND: ::c_int = 1024; -pub const O_CREAT: ::c_int = 64; -pub const O_EXCL: ::c_int = 128; -pub const O_NOCTTY: ::c_int = 256; -pub const O_NONBLOCK: ::c_int = 2048; -pub const O_SYNC: ::c_int = 1052672; -pub const O_RSYNC: ::c_int = 1052672; -pub const O_DSYNC: ::c_int = 4096; -pub const O_FSYNC: ::c_int = 0x101000; -pub const O_NOATIME: ::c_int = 0o1000000; -pub const O_PATH: ::c_int = 0o10000000; -pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; - -pub const MAP_GROWSDOWN: ::c_int = 0x0100; - -pub const EDEADLK: ::c_int = 35; -pub const ENAMETOOLONG: ::c_int = 36; -pub const ENOLCK: ::c_int = 37; -pub const ENOSYS: ::c_int = 38; -pub const ENOTEMPTY: ::c_int = 39; -pub const ELOOP: ::c_int = 40; -pub const ENOMSG: ::c_int = 42; -pub const EIDRM: ::c_int = 43; -pub const ECHRNG: ::c_int = 44; -pub const EL2NSYNC: ::c_int = 45; -pub const EL3HLT: ::c_int = 46; -pub const EL3RST: ::c_int = 47; -pub const ELNRNG: ::c_int = 48; -pub const EUNATCH: ::c_int = 49; -pub const ENOCSI: ::c_int = 50; -pub const EL2HLT: ::c_int = 51; -pub const EBADE: ::c_int = 52; -pub const EBADR: ::c_int = 53; -pub const EXFULL: ::c_int = 54; -pub const ENOANO: ::c_int = 55; -pub const EBADRQC: ::c_int = 56; -pub const EBADSLT: ::c_int = 57; -pub const EMULTIHOP: ::c_int = 72; -pub const EOVERFLOW: ::c_int = 75; -pub const ENOTUNIQ: ::c_int = 76; -pub const EBADFD: ::c_int = 77; -pub const EBADMSG: ::c_int = 74; -pub const EREMCHG: ::c_int = 78; -pub const ELIBACC: ::c_int = 79; -pub const ELIBBAD: ::c_int = 80; -pub const ELIBSCN: ::c_int = 81; -pub const ELIBMAX: ::c_int = 82; -pub const ELIBEXEC: ::c_int = 83; -pub const EILSEQ: ::c_int = 84; -pub const ERESTART: ::c_int = 85; -pub const ESTRPIPE: ::c_int = 86; -pub const EUSERS: ::c_int = 87; -pub const ENOTSOCK: ::c_int = 88; -pub const EDESTADDRREQ: ::c_int = 89; -pub const EMSGSIZE: ::c_int = 90; -pub const EPROTOTYPE: ::c_int = 91; -pub const ENOPROTOOPT: ::c_int = 92; -pub const EPROTONOSUPPORT: ::c_int = 93; -pub const ESOCKTNOSUPPORT: ::c_int = 94; -pub const EOPNOTSUPP: ::c_int = 95; -pub const EPFNOSUPPORT: ::c_int = 96; -pub const EAFNOSUPPORT: ::c_int = 97; -pub const EADDRINUSE: ::c_int = 98; -pub const EADDRNOTAVAIL: ::c_int = 99; -pub const ENETDOWN: ::c_int = 100; -pub const ENETUNREACH: ::c_int = 101; -pub const ENETRESET: ::c_int = 102; -pub const ECONNABORTED: ::c_int = 103; -pub const ECONNRESET: ::c_int = 104; -pub const ENOBUFS: ::c_int = 105; -pub const EISCONN: ::c_int = 106; -pub const ENOTCONN: ::c_int = 107; -pub const ESHUTDOWN: ::c_int = 108; -pub const ETOOMANYREFS: ::c_int = 109; -pub const ETIMEDOUT: ::c_int = 110; -pub const ECONNREFUSED: ::c_int = 111; -pub const EHOSTDOWN: ::c_int = 112; -pub const EHOSTUNREACH: ::c_int = 113; -pub const EALREADY: ::c_int = 114; -pub const EINPROGRESS: ::c_int = 115; -pub const ESTALE: ::c_int = 116; -pub const EDQUOT: ::c_int = 122; -pub const ENOMEDIUM: ::c_int = 123; -pub const EMEDIUMTYPE: ::c_int = 124; -pub const ECANCELED: ::c_int = 125; -pub const ENOKEY: ::c_int = 126; -pub const EKEYEXPIRED: ::c_int = 127; -pub const EKEYREVOKED: ::c_int = 128; -pub const EKEYREJECTED: ::c_int = 129; -pub const EOWNERDEAD: ::c_int = 130; -pub const ENOTRECOVERABLE: ::c_int = 131; -pub const EHWPOISON: ::c_int = 133; -pub const ERFKILL: ::c_int = 132; - -pub const SOL_SOCKET: ::c_int = 1; - -pub const SO_REUSEADDR: ::c_int = 2; -pub const SO_TYPE: ::c_int = 3; -pub const SO_ERROR: ::c_int = 4; -pub const SO_DONTROUTE: ::c_int = 5; -pub const SO_BROADCAST: ::c_int = 6; -pub const SO_SNDBUF: ::c_int = 7; -pub const SO_RCVBUF: ::c_int = 8; -pub const SO_KEEPALIVE: ::c_int = 9; -pub const SO_OOBINLINE: ::c_int = 10; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_LINGER: ::c_int = 13; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_REUSEPORT: ::c_int = 15; -pub const SO_BINDTODEVICE: ::c_int = 25; -pub const SO_TIMESTAMP: ::c_int = 29; -pub const SO_ACCEPTCONN: ::c_int = 30; -pub const SO_MARK: ::c_int = 36; -pub const SO_PROTOCOL: ::c_int = 38; -pub const SO_DOMAIN: ::c_int = 39; -pub const SO_RXQ_OVFL: ::c_int = 40; -pub const SO_PEEK_OFF: ::c_int = 42; -pub const SO_BUSY_POLL: ::c_int = 46; - -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 0x00000004; -pub const SA_NOCLDWAIT: ::c_int = 0x00000002; - -pub const SIGCHLD: ::c_int = 17; -pub const SIGBUS: ::c_int = 7; -pub const SIGUSR1: ::c_int = 10; -pub const SIGUSR2: ::c_int = 12; -pub const SIGCONT: ::c_int = 18; -pub const SIGSTOP: ::c_int = 19; -pub const SIGTSTP: ::c_int = 20; -pub const SIGURG: ::c_int = 23; -pub const SIGIO: ::c_int = 29; -pub const SIGSYS: ::c_int = 31; -pub const SIGSTKFLT: ::c_int = 16; -pub const SIGUNUSED: ::c_int = 31; -pub const SIGPOLL: ::c_int = 29; -pub const SIGPWR: ::c_int = 30; -pub const SIG_SETMASK: ::c_int = 2; -pub const SIG_BLOCK: ::c_int = 0x000000; -pub const SIG_UNBLOCK: ::c_int = 0x01; - -pub const POLLWRNORM: ::c_short = 0x100; -pub const POLLWRBAND: ::c_short = 0x200; - -pub const O_ASYNC: ::c_int = 0x2000; -pub const O_NDELAY: ::c_int = 0x800; - -pub const PTRACE_DETACH: ::c_uint = 17; - -pub const EFD_NONBLOCK: ::c_int = 0x800; - -pub const F_GETLK: ::c_int = 5; -pub const F_GETOWN: ::c_int = 9; -pub const F_SETOWN: ::c_int = 8; -pub const F_SETLK: ::c_int = 6; -pub const F_SETLKW: ::c_int = 7; - -pub const SFD_NONBLOCK: ::c_int = 0x0800; - -pub const TIOCEXCL: ::c_ulong = 0x540C; -pub const TIOCNXCL: ::c_ulong = 0x540D; -pub const TIOCSCTTY: ::c_ulong = 0x540E; -pub const TIOCSTI: ::c_ulong = 0x5412; -pub const TIOCMGET: ::c_ulong = 0x5415; -pub const TIOCMBIS: ::c_ulong = 0x5416; -pub const TIOCMBIC: ::c_ulong = 0x5417; -pub const TIOCMSET: ::c_ulong = 0x5418; -pub const TIOCCONS: ::c_ulong = 0x541D; - -pub const SFD_CLOEXEC: ::c_int = 0x080000; - -pub const NCCS: usize = 32; - -pub const O_TRUNC: ::c_int = 512; - -pub const O_CLOEXEC: ::c_int = 0x80000; - -pub const EBFONT: ::c_int = 59; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENONET: ::c_int = 64; -pub const ENOPKG: ::c_int = 65; -pub const EREMOTE: ::c_int = 66; -pub const ENOLINK: ::c_int = 67; -pub const EADV: ::c_int = 68; -pub const ESRMNT: ::c_int = 69; -pub const ECOMM: ::c_int = 70; -pub const EPROTO: ::c_int = 71; -pub const EDOTDOT: ::c_int = 73; - -pub const SA_NODEFER: ::c_int = 0x40000000; -pub const SA_RESETHAND: ::c_int = 0x80000000; -pub const SA_RESTART: ::c_int = 0x10000000; -pub const SA_NOCLDSTOP: ::c_int = 0x00000001; - -pub const EPOLL_CLOEXEC: ::c_int = 0x80000; - -pub const EFD_CLOEXEC: ::c_int = 0x80000; - -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 24; -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 32; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; - -pub const PTRACE_GETFPREGS: ::c_uint = 14; -pub const PTRACE_SETFPREGS: ::c_uint = 15; -pub const PTRACE_GETREGS: ::c_uint = 12; -pub const PTRACE_SETREGS: ::c_uint = 13; - -#[link(name = "util")] -extern { - pub fn sysctl(name: *mut ::c_int, - namelen: ::c_int, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *mut ::c_void, - newlen: ::size_t) - -> ::c_int; -} - -cfg_if! { - if #[cfg(target_arch = "x86")] { - mod x86; - pub use self::x86::*; - } else if #[cfg(target_arch = "arm")] { - mod arm; - pub use self::arm::*; - } else if #[cfg(target_arch = "powerpc")] { - mod powerpc; - pub use self::powerpc::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/powerpc.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/powerpc.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/powerpc.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/powerpc.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,614 +0,0 @@ -pub type c_char = u8; -pub type wchar_t = i32; - -s! { - pub struct ipc_perm { - __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::mode_t, - __seq: ::uint32_t, - __pad1: ::uint32_t, - __glibc_reserved1: ::uint64_t, - __glibc_reserved2: ::uint64_t, - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino64_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad2: ::c_ushort, - pub st_size: ::off64_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __glibc_reserved4: ::c_ulong, - __glibc_reserved5: ::c_ulong, - } - - pub struct statfs64 { - pub f_type: ::__fsword_t, - pub f_bsize: ::__fsword_t, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_fsid: ::fsid_t, - pub f_namelen: ::__fsword_t, - pub f_frsize: ::__fsword_t, - pub f_flags: ::__fsword_t, - pub f_spare: [::__fsword_t; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - __f_unused: ::c_int, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - __glibc_reserved1: ::c_uint, - pub shm_atime: ::time_t, - __glibc_reserved2: ::c_uint, - pub shm_dtime: ::time_t, - __glibc_reserved3: ::c_uint, - pub shm_ctime: ::time_t, - __glibc_reserved4: ::c_uint, - pub shm_segsz: ::size_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __glibc_reserved5: ::c_ulong, - __glibc_reserved6: ::c_ulong, - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - __glibc_reserved1: ::c_uint, - pub msg_stime: ::time_t, - __glibc_reserved2: ::c_uint, - pub msg_rtime: ::time_t, - __glibc_reserved3: ::c_uint, - pub msg_ctime: ::time_t, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __glibc_reserved4: ::c_ulong, - __glibc_reserved5: ::c_ulong, - } -} - -pub const O_DIRECT: ::c_int = 0x20000; -pub const O_DIRECTORY: ::c_int = 0x4000; -pub const O_NOFOLLOW: ::c_int = 0x8000; -pub const O_LARGEFILE: ::c_int = 0o200000; - -pub const MAP_LOCKED: ::c_int = 0x00080; -pub const MAP_NORESERVE: ::c_int = 0x00040; - -pub const EDEADLOCK: ::c_int = 58; - -pub const SO_SNDBUFFORCE: ::c_int = 32; -pub const SO_RCVBUFFORCE: ::c_int = 33; -pub const SO_NO_CHECK: ::c_int = 11; -pub const SO_RCVLOWAT: ::c_int = 16; -pub const SO_SNDLOWAT: ::c_int = 17; -pub const SO_RCVTIMEO: ::c_int = 18; -pub const SO_SNDTIMEO: ::c_int = 19; -pub const SO_PASSCRED: ::c_int = 20; -pub const SO_PEERCRED: ::c_int = 21; - -pub const FIOCLEX: ::c_ulong = 0x20006601; -pub const FIONBIO: ::c_ulong = 0x8004667e; - -pub const MCL_CURRENT: ::c_int = 0x2000; -pub const MCL_FUTURE: ::c_int = 0x4000; - -pub const SIGSTKSZ: ::size_t = 0x4000; -pub const MINSIGSTKSZ: ::size_t = 4096; -pub const CBAUD: ::tcflag_t = 0xff; -pub const TAB1: ::c_int = 0x400; -pub const TAB2: ::c_int = 0x800; -pub const TAB3: ::c_int = 0xc00; -pub const CR1: ::c_int = 0x1000; -pub const CR2: ::c_int = 0x2000; -pub const CR3: ::c_int = 0x3000; -pub const FF1: ::c_int = 0x4000; -pub const BS1: ::c_int = 0x8000; -pub const VT1: ::c_int = 0x10000; -pub const VWERASE: usize = 0xa; -pub const VREPRINT: usize = 0xb; -pub const VSUSP: usize = 0xc; -pub const VSTART: usize = 0xd; -pub const VSTOP: usize = 0xe; -pub const VDISCARD: usize = 0x10; -pub const VTIME: usize = 0x7; -pub const IXON: ::tcflag_t = 0x200; -pub const IXOFF: ::tcflag_t = 0x400; -pub const ONLCR: ::tcflag_t = 0x2; -pub const CSIZE: ::tcflag_t = 0x300; -pub const CS6: ::tcflag_t = 0x100; -pub const CS7: ::tcflag_t = 0x200; -pub const CS8: ::tcflag_t = 0x300; -pub const CSTOPB: ::tcflag_t = 0x400; -pub const CREAD: ::tcflag_t = 0x800; -pub const PARENB: ::tcflag_t = 0x1000; -pub const PARODD: ::tcflag_t = 0x2000; -pub const HUPCL: ::tcflag_t = 0x4000; -pub const CLOCAL: ::tcflag_t = 0x8000; -pub const ECHOKE: ::tcflag_t = 0x1; -pub const ECHOE: ::tcflag_t = 0x2; -pub const ECHOK: ::tcflag_t = 0x4; -pub const ECHONL: ::tcflag_t = 0x10; -pub const ECHOPRT: ::tcflag_t = 0x20; -pub const ECHOCTL: ::tcflag_t = 0x40; -pub const ISIG: ::tcflag_t = 0x80; -pub const ICANON: ::tcflag_t = 0x100; -pub const PENDIN: ::tcflag_t = 0x20000000; -pub const NOFLSH: ::tcflag_t = 0x80000000; -pub const VSWTC: usize = 9; -pub const OLCUC: ::tcflag_t = 0o000004; -pub const NLDLY: ::tcflag_t = 0o001400; -pub const CRDLY: ::tcflag_t = 0o030000; -pub const TABDLY: ::tcflag_t = 0o006000; -pub const BSDLY: ::tcflag_t = 0o100000; -pub const FFDLY: ::tcflag_t = 0o040000; -pub const VTDLY: ::tcflag_t = 0o200000; -pub const XTABS: ::tcflag_t = 0o006000; - -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const EXTA: ::speed_t = B19200; -pub const EXTB: ::speed_t = B38400; -pub const CBAUDEX: ::speed_t = 0o000020; -pub const B57600: ::speed_t = 0o0020; -pub const B115200: ::speed_t = 0o0021; -pub const B230400: ::speed_t = 0o0022; -pub const B460800: ::speed_t = 0o0023; -pub const B500000: ::speed_t = 0o0024; -pub const B576000: ::speed_t = 0o0025; -pub const B921600: ::speed_t = 0o0026; -pub const B1000000: ::speed_t = 0o0027; -pub const B1152000: ::speed_t = 0o0030; -pub const B1500000: ::speed_t = 0o0031; -pub const B2000000: ::speed_t = 0o0032; -pub const B2500000: ::speed_t = 0o0033; -pub const B3000000: ::speed_t = 0o0034; -pub const B3500000: ::speed_t = 0o0035; -pub const B4000000: ::speed_t = 0o0036; -pub const BOTHER: ::speed_t = 0o0037; - -pub const VEOL: usize = 6; -pub const VEOL2: usize = 8; -pub const VMIN: usize = 5; -pub const IEXTEN: ::tcflag_t = 0x400; -pub const TOSTOP: ::tcflag_t = 0x400000; -pub const FLUSHO: ::tcflag_t = 0x800000; -pub const EXTPROC: ::tcflag_t = 0x10000000; -pub const TCGETS: ::c_ulong = 0x403c7413; -pub const TCSETS: ::c_ulong = 0x803c7414; -pub const TCSETSW: ::c_ulong = 0x803c7415; -pub const TCSETSF: ::c_ulong = 0x803c7416; -pub const TCGETA: ::c_ulong = 0x40147417; -pub const TCSETA: ::c_ulong = 0x80147418; -pub const TCSETAW: ::c_ulong = 0x80147419; -pub const TCSETAF: ::c_ulong = 0x8014741c; -pub const TCSBRK: ::c_ulong = 0x2000741d; -pub const TCXONC: ::c_ulong = 0x2000741e; -pub const TCFLSH: ::c_ulong = 0x2000741f; -pub const TIOCINQ: ::c_ulong = 0x4004667f; -pub const TIOCGPGRP: ::c_ulong = 0x40047477; -pub const TIOCSPGRP: ::c_ulong = 0x80047476; -pub const TIOCOUTQ: ::c_ulong = 0x40047473; -pub const TIOCGWINSZ: ::c_ulong = 0x40087468; -pub const TIOCSWINSZ: ::c_ulong = 0x80087467; -pub const FIONREAD: ::c_ulong = 0x4004667f; - -pub const SYS_restart_syscall: ::c_long = 0; -pub const SYS_exit: ::c_long = 1; -pub const SYS_fork: ::c_long = 2; -pub const SYS_read: ::c_long = 3; -pub const SYS_write: ::c_long = 4; -pub const SYS_open: ::c_long = 5; -pub const SYS_close: ::c_long = 6; -pub const SYS_waitpid: ::c_long = 7; -pub const SYS_creat: ::c_long = 8; -pub const SYS_link: ::c_long = 9; -pub const SYS_unlink: ::c_long = 10; -pub const SYS_execve: ::c_long = 11; -pub const SYS_chdir: ::c_long = 12; -pub const SYS_time: ::c_long = 13; -pub const SYS_mknod: ::c_long = 14; -pub const SYS_chmod: ::c_long = 15; -pub const SYS_lchown: ::c_long = 16; -pub const SYS_break: ::c_long = 17; -pub const SYS_oldstat: ::c_long = 18; -pub const SYS_lseek: ::c_long = 19; -pub const SYS_getpid: ::c_long = 20; -pub const SYS_mount: ::c_long = 21; -pub const SYS_umount: ::c_long = 22; -pub const SYS_setuid: ::c_long = 23; -pub const SYS_getuid: ::c_long = 24; -pub const SYS_stime: ::c_long = 25; -pub const SYS_ptrace: ::c_long = 26; -pub const SYS_alarm: ::c_long = 27; -pub const SYS_oldfstat: ::c_long = 28; -pub const SYS_pause: ::c_long = 29; -pub const SYS_utime: ::c_long = 30; -pub const SYS_stty: ::c_long = 31; -pub const SYS_gtty: ::c_long = 32; -pub const SYS_access: ::c_long = 33; -pub const SYS_nice: ::c_long = 34; -pub const SYS_ftime: ::c_long = 35; -pub const SYS_sync: ::c_long = 36; -pub const SYS_kill: ::c_long = 37; -pub const SYS_rename: ::c_long = 38; -pub const SYS_mkdir: ::c_long = 39; -pub const SYS_rmdir: ::c_long = 40; -pub const SYS_dup: ::c_long = 41; -pub const SYS_pipe: ::c_long = 42; -pub const SYS_times: ::c_long = 43; -pub const SYS_prof: ::c_long = 44; -pub const SYS_brk: ::c_long = 45; -pub const SYS_setgid: ::c_long = 46; -pub const SYS_getgid: ::c_long = 47; -pub const SYS_signal: ::c_long = 48; -pub const SYS_geteuid: ::c_long = 49; -pub const SYS_getegid: ::c_long = 50; -pub const SYS_acct: ::c_long = 51; -pub const SYS_umount2: ::c_long = 52; -pub const SYS_lock: ::c_long = 53; -pub const SYS_ioctl: ::c_long = 54; -pub const SYS_fcntl: ::c_long = 55; -pub const SYS_mpx: ::c_long = 56; -pub const SYS_setpgid: ::c_long = 57; -pub const SYS_ulimit: ::c_long = 58; -pub const SYS_oldolduname: ::c_long = 59; -pub const SYS_umask: ::c_long = 60; -pub const SYS_chroot: ::c_long = 61; -pub const SYS_ustat: ::c_long = 62; -pub const SYS_dup2: ::c_long = 63; -pub const SYS_getppid: ::c_long = 64; -pub const SYS_getpgrp: ::c_long = 65; -pub const SYS_setsid: ::c_long = 66; -pub const SYS_sigaction: ::c_long = 67; -pub const SYS_sgetmask: ::c_long = 68; -pub const SYS_ssetmask: ::c_long = 69; -pub const SYS_setreuid: ::c_long = 70; -pub const SYS_setregid: ::c_long = 71; -pub const SYS_sigsuspend: ::c_long = 72; -pub const SYS_sigpending: ::c_long = 73; -pub const SYS_sethostname: ::c_long = 74; -pub const SYS_setrlimit: ::c_long = 75; -pub const SYS_getrlimit: ::c_long = 76; -pub const SYS_getrusage: ::c_long = 77; -pub const SYS_gettimeofday: ::c_long = 78; -pub const SYS_settimeofday: ::c_long = 79; -pub const SYS_getgroups: ::c_long = 80; -pub const SYS_setgroups: ::c_long = 81; -pub const SYS_select: ::c_long = 82; -pub const SYS_symlink: ::c_long = 83; -pub const SYS_oldlstat: ::c_long = 84; -pub const SYS_readlink: ::c_long = 85; -pub const SYS_uselib: ::c_long = 86; -pub const SYS_swapon: ::c_long = 87; -pub const SYS_reboot: ::c_long = 88; -pub const SYS_readdir: ::c_long = 89; -pub const SYS_mmap: ::c_long = 90; -pub const SYS_munmap: ::c_long = 91; -pub const SYS_truncate: ::c_long = 92; -pub const SYS_ftruncate: ::c_long = 93; -pub const SYS_fchmod: ::c_long = 94; -pub const SYS_fchown: ::c_long = 95; -pub const SYS_getpriority: ::c_long = 96; -pub const SYS_setpriority: ::c_long = 97; -pub const SYS_profil: ::c_long = 98; -pub const SYS_statfs: ::c_long = 99; -pub const SYS_fstatfs: ::c_long = 100; -pub const SYS_ioperm: ::c_long = 101; -pub const SYS_socketcall: ::c_long = 102; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_setitimer: ::c_long = 104; -pub const SYS_getitimer: ::c_long = 105; -pub const SYS_stat: ::c_long = 106; -pub const SYS_lstat: ::c_long = 107; -pub const SYS_fstat: ::c_long = 108; -pub const SYS_olduname: ::c_long = 109; -pub const SYS_iopl: ::c_long = 110; -pub const SYS_vhangup: ::c_long = 111; -pub const SYS_idle: ::c_long = 112; -pub const SYS_vm86: ::c_long = 113; -pub const SYS_wait4: ::c_long = 114; -pub const SYS_swapoff: ::c_long = 115; -pub const SYS_sysinfo: ::c_long = 116; -pub const SYS_ipc: ::c_long = 117; -pub const SYS_fsync: ::c_long = 118; -pub const SYS_sigreturn: ::c_long = 119; -pub const SYS_clone: ::c_long = 120; -pub const SYS_setdomainname: ::c_long = 121; -pub const SYS_uname: ::c_long = 122; -pub const SYS_modify_ldt: ::c_long = 123; -pub const SYS_adjtimex: ::c_long = 124; -pub const SYS_mprotect: ::c_long = 125; -pub const SYS_sigprocmask: ::c_long = 126; -pub const SYS_create_module: ::c_long = 127; -pub const SYS_init_module: ::c_long = 128; -pub const SYS_delete_module: ::c_long = 129; -pub const SYS_get_kernel_syms: ::c_long = 130; -pub const SYS_quotactl: ::c_long = 131; -pub const SYS_getpgid: ::c_long = 132; -pub const SYS_fchdir: ::c_long = 133; -pub const SYS_bdflush: ::c_long = 134; -pub const SYS_sysfs: ::c_long = 135; -pub const SYS_personality: ::c_long = 136; -pub const SYS_afs_syscall: ::c_long = 137; /* Syscall for Andrew File System */ -pub const SYS_setfsuid: ::c_long = 138; -pub const SYS_setfsgid: ::c_long = 139; -pub const SYS__llseek: ::c_long = 140; -pub const SYS_getdents: ::c_long = 141; -pub const SYS__newselect: ::c_long = 142; -pub const SYS_flock: ::c_long = 143; -pub const SYS_msync: ::c_long = 144; -pub const SYS_readv: ::c_long = 145; -pub const SYS_writev: ::c_long = 146; -pub const SYS_getsid: ::c_long = 147; -pub const SYS_fdatasync: ::c_long = 148; -pub const SYS__sysctl: ::c_long = 149; -pub const SYS_mlock: ::c_long = 150; -pub const SYS_munlock: ::c_long = 151; -pub const SYS_mlockall: ::c_long = 152; -pub const SYS_munlockall: ::c_long = 153; -pub const SYS_sched_setparam: ::c_long = 154; -pub const SYS_sched_getparam: ::c_long = 155; -pub const SYS_sched_setscheduler: ::c_long = 156; -pub const SYS_sched_getscheduler: ::c_long = 157; -pub const SYS_sched_yield: ::c_long = 158; -pub const SYS_sched_get_priority_max: ::c_long = 159; -pub const SYS_sched_get_priority_min: ::c_long = 160; -pub const SYS_sched_rr_get_interval: ::c_long = 161; -pub const SYS_nanosleep: ::c_long = 162; -pub const SYS_mremap: ::c_long = 163; -pub const SYS_setresuid: ::c_long = 164; -pub const SYS_getresuid: ::c_long = 165; -pub const SYS_query_module: ::c_long = 166; -pub const SYS_poll: ::c_long = 167; -pub const SYS_nfsservctl: ::c_long = 168; -pub const SYS_setresgid: ::c_long = 169; -pub const SYS_getresgid: ::c_long = 170; -pub const SYS_prctl: ::c_long = 171; -pub const SYS_rt_sigreturn: ::c_long = 172; -pub const SYS_rt_sigaction: ::c_long = 173; -pub const SYS_rt_sigprocmask: ::c_long = 174; -pub const SYS_rt_sigpending: ::c_long = 175; -pub const SYS_rt_sigtimedwait: ::c_long = 176; -pub const SYS_rt_sigqueueinfo: ::c_long = 177; -pub const SYS_rt_sigsuspend: ::c_long = 178; -pub const SYS_pread64: ::c_long = 179; -pub const SYS_pwrite64: ::c_long = 180; -pub const SYS_chown: ::c_long = 181; -pub const SYS_getcwd: ::c_long = 182; -pub const SYS_capget: ::c_long = 183; -pub const SYS_capset: ::c_long = 184; -pub const SYS_sigaltstack: ::c_long = 185; -pub const SYS_sendfile: ::c_long = 186; -pub const SYS_getpmsg: ::c_long = 187; /* some people actually want streams */ -pub const SYS_putpmsg: ::c_long = 188; /* some people actually want streams */ -pub const SYS_vfork: ::c_long = 189; -pub const SYS_ugetrlimit: ::c_long = 190; /* SuS compliant getrlimit */ -pub const SYS_readahead: ::c_long = 191; -pub const SYS_mmap2: ::c_long = 192; -pub const SYS_truncate64: ::c_long = 193; -pub const SYS_ftruncate64: ::c_long = 194; -pub const SYS_stat64: ::c_long = 195; -pub const SYS_lstat64: ::c_long = 196; -pub const SYS_fstat64: ::c_long = 197; -pub const SYS_pciconfig_read: ::c_long = 198; -pub const SYS_pciconfig_write: ::c_long = 199; -pub const SYS_pciconfig_iobase: ::c_long = 200; -pub const SYS_multiplexer: ::c_long = 201; -pub const SYS_getdents64: ::c_long = 202; -pub const SYS_pivot_root: ::c_long = 203; -pub const SYS_fcntl64: ::c_long = 204; -pub const SYS_madvise: ::c_long = 205; -pub const SYS_mincore: ::c_long = 206; -pub const SYS_gettid: ::c_long = 207; -pub const SYS_tkill: ::c_long = 208; -pub const SYS_setxattr: ::c_long = 209; -pub const SYS_lsetxattr: ::c_long = 210; -pub const SYS_fsetxattr: ::c_long = 211; -pub const SYS_getxattr: ::c_long = 212; -pub const SYS_lgetxattr: ::c_long = 213; -pub const SYS_fgetxattr: ::c_long = 214; -pub const SYS_listxattr: ::c_long = 215; -pub const SYS_llistxattr: ::c_long = 216; -pub const SYS_flistxattr: ::c_long = 217; -pub const SYS_removexattr: ::c_long = 218; -pub const SYS_lremovexattr: ::c_long = 219; -pub const SYS_fremovexattr: ::c_long = 220; -pub const SYS_futex: ::c_long = 221; -pub const SYS_sched_setaffinity: ::c_long = 222; -pub const SYS_sched_getaffinity: ::c_long = 223; -pub const SYS_tuxcall: ::c_long = 225; -pub const SYS_sendfile64: ::c_long = 226; -pub const SYS_io_setup: ::c_long = 227; -pub const SYS_io_destroy: ::c_long = 228; -pub const SYS_io_getevents: ::c_long = 229; -pub const SYS_io_submit: ::c_long = 230; -pub const SYS_io_cancel: ::c_long = 231; -pub const SYS_set_tid_address: ::c_long = 232; -pub const SYS_fadvise64: ::c_long = 233; -pub const SYS_exit_group: ::c_long = 234; -pub const SYS_lookup_dcookie: ::c_long = 235; -pub const SYS_epoll_create: ::c_long = 236; -pub const SYS_epoll_ctl: ::c_long = 237; -pub const SYS_epoll_wait: ::c_long = 238; -pub const SYS_remap_file_pages: ::c_long = 239; -pub const SYS_timer_create: ::c_long = 240; -pub const SYS_timer_settime: ::c_long = 241; -pub const SYS_timer_gettime: ::c_long = 242; -pub const SYS_timer_getoverrun: ::c_long = 243; -pub const SYS_timer_delete: ::c_long = 244; -pub const SYS_clock_settime: ::c_long = 245; -pub const SYS_clock_gettime: ::c_long = 246; -pub const SYS_clock_getres: ::c_long = 247; -pub const SYS_clock_nanosleep: ::c_long = 248; -pub const SYS_swapcontext: ::c_long = 249; -pub const SYS_tgkill: ::c_long = 250; -pub const SYS_utimes: ::c_long = 251; -pub const SYS_statfs64: ::c_long = 252; -pub const SYS_fstatfs64: ::c_long = 253; -pub const SYS_fadvise64_64: ::c_long = 254; -pub const SYS_rtas: ::c_long = 255; -pub const SYS_sys_debug_setcontext: ::c_long = 256; -pub const SYS_migrate_pages: ::c_long = 258; -pub const SYS_mbind: ::c_long = 259; -pub const SYS_get_mempolicy: ::c_long = 260; -pub const SYS_set_mempolicy: ::c_long = 261; -pub const SYS_mq_open: ::c_long = 262; -pub const SYS_mq_unlink: ::c_long = 263; -pub const SYS_mq_timedsend: ::c_long = 264; -pub const SYS_mq_timedreceive: ::c_long = 265; -pub const SYS_mq_notify: ::c_long = 266; -pub const SYS_mq_getsetattr: ::c_long = 267; -pub const SYS_kexec_load: ::c_long = 268; -pub const SYS_add_key: ::c_long = 269; -pub const SYS_request_key: ::c_long = 270; -pub const SYS_keyctl: ::c_long = 271; -pub const SYS_waitid: ::c_long = 272; -pub const SYS_ioprio_set: ::c_long = 273; -pub const SYS_ioprio_get: ::c_long = 274; -pub const SYS_inotify_init: ::c_long = 275; -pub const SYS_inotify_add_watch: ::c_long = 276; -pub const SYS_inotify_rm_watch: ::c_long = 277; -pub const SYS_spu_run: ::c_long = 278; -pub const SYS_spu_create: ::c_long = 279; -pub const SYS_pselect6: ::c_long = 280; -pub const SYS_ppoll: ::c_long = 281; -pub const SYS_unshare: ::c_long = 282; -pub const SYS_splice: ::c_long = 283; -pub const SYS_tee: ::c_long = 284; -pub const SYS_vmsplice: ::c_long = 285; -pub const SYS_openat: ::c_long = 286; -pub const SYS_mkdirat: ::c_long = 287; -pub const SYS_mknodat: ::c_long = 288; -pub const SYS_fchownat: ::c_long = 289; -pub const SYS_futimesat: ::c_long = 290; -pub const SYS_fstatat64: ::c_long = 291; -pub const SYS_unlinkat: ::c_long = 292; -pub const SYS_renameat: ::c_long = 293; -pub const SYS_linkat: ::c_long = 294; -pub const SYS_symlinkat: ::c_long = 295; -pub const SYS_readlinkat: ::c_long = 296; -pub const SYS_fchmodat: ::c_long = 297; -pub const SYS_faccessat: ::c_long = 298; -pub const SYS_get_robust_list: ::c_long = 299; -pub const SYS_set_robust_list: ::c_long = 300; -pub const SYS_move_pages: ::c_long = 301; -pub const SYS_getcpu: ::c_long = 302; -pub const SYS_epoll_pwait: ::c_long = 303; -pub const SYS_utimensat: ::c_long = 304; -pub const SYS_signalfd: ::c_long = 305; -pub const SYS_timerfd_create: ::c_long = 306; -pub const SYS_eventfd: ::c_long = 307; -pub const SYS_sync_file_range2: ::c_long = 308; -pub const SYS_fallocate: ::c_long = 309; -pub const SYS_subpage_prot: ::c_long = 310; -pub const SYS_timerfd_settime: ::c_long = 311; -pub const SYS_timerfd_gettime: ::c_long = 312; -pub const SYS_signalfd4: ::c_long = 313; -pub const SYS_eventfd2: ::c_long = 314; -pub const SYS_epoll_create1: ::c_long = 315; -pub const SYS_dup3: ::c_long = 316; -pub const SYS_pipe2: ::c_long = 317; -pub const SYS_inotify_init1: ::c_long = 318; -pub const SYS_perf_event_open: ::c_long = 319; -pub const SYS_preadv: ::c_long = 320; -pub const SYS_pwritev: ::c_long = 321; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 322; -pub const SYS_fanotify_init: ::c_long = 323; -pub const SYS_fanotify_mark: ::c_long = 324; -pub const SYS_prlimit64: ::c_long = 325; -pub const SYS_socket: ::c_long = 326; -pub const SYS_bind: ::c_long = 327; -pub const SYS_connect: ::c_long = 328; -pub const SYS_listen: ::c_long = 329; -pub const SYS_accept: ::c_long = 330; -pub const SYS_getsockname: ::c_long = 331; -pub const SYS_getpeername: ::c_long = 332; -pub const SYS_socketpair: ::c_long = 333; -pub const SYS_send: ::c_long = 334; -pub const SYS_sendto: ::c_long = 335; -pub const SYS_recv: ::c_long = 336; -pub const SYS_recvfrom: ::c_long = 337; -pub const SYS_shutdown: ::c_long = 338; -pub const SYS_setsockopt: ::c_long = 339; -pub const SYS_getsockopt: ::c_long = 340; -pub const SYS_sendmsg: ::c_long = 341; -pub const SYS_recvmsg: ::c_long = 342; -pub const SYS_recvmmsg: ::c_long = 343; -pub const SYS_accept4: ::c_long = 344; -pub const SYS_name_to_handle_at: ::c_long = 345; -pub const SYS_open_by_handle_at: ::c_long = 346; -pub const SYS_clock_adjtime: ::c_long = 347; -pub const SYS_syncfs: ::c_long = 348; -pub const SYS_sendmmsg: ::c_long = 349; -pub const SYS_setns: ::c_long = 350; -pub const SYS_process_vm_readv: ::c_long = 351; -pub const SYS_process_vm_writev: ::c_long = 352; -pub const SYS_finit_module: ::c_long = 353; -pub const SYS_kcmp: ::c_long = 354; -pub const SYS_sched_setattr: ::c_long = 355; -pub const SYS_sched_getattr: ::c_long = 356; -pub const SYS_renameat2: ::c_long = 357; -pub const SYS_seccomp: ::c_long = 358; -pub const SYS_getrandom: ::c_long = 359; -pub const SYS_memfd_create: ::c_long = 360; -pub const SYS_bpf: ::c_long = 361; -pub const SYS_execveat: ::c_long = 362; -pub const SYS_switch_endian: ::c_long = 363; -pub const SYS_userfaultfd: ::c_long = 364; -pub const SYS_membarrier: ::c_long = 365; -pub const SYS_mlock2: ::c_long = 378; -pub const SYS_copy_file_range: ::c_long = 379; -pub const SYS_preadv2: ::c_long = 380; -pub const SYS_pwritev2: ::c_long = 381; -pub const SYS_kexec_file_load: ::c_long = 382; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/x86.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/x86.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/x86.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b32/x86.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,769 +0,0 @@ -pub type c_char = i8; -pub type wchar_t = i32; -pub type greg_t = i32; - -s! { - pub struct _libc_fpreg { - pub significand: [u16; 4], - pub exponent: u16, - } - - pub struct _libc_fpstate { - pub cw: ::c_ulong, - pub sw: ::c_ulong, - pub tag: ::c_ulong, - pub ipoff: ::c_ulong, - pub cssel: ::c_ulong, - pub dataoff: ::c_ulong, - pub datasel: ::c_ulong, - pub _st: [_libc_fpreg; 8], - pub status: ::c_ulong, - } - - pub struct user_fpregs_struct { - pub cwd: ::c_long, - pub swd: ::c_long, - pub twd: ::c_long, - pub fip: ::c_long, - pub fcs: ::c_long, - pub foo: ::c_long, - pub fos: ::c_long, - pub st_space: [::c_long; 20], - } - - pub struct user_fpxregs_struct { - pub cwd: ::c_ushort, - pub swd: ::c_ushort, - pub twd: ::c_ushort, - pub fop: ::c_ushort, - pub fip: ::c_long, - pub fcs: ::c_long, - pub foo: ::c_long, - pub fos: ::c_long, - pub mxcsr: ::c_long, - __reserved: ::c_long, - pub st_space: [::c_long; 32], - pub xmm_space: [::c_long; 32], - padding: [::c_long; 56], - } - - pub struct user_regs_struct { - pub ebx: ::c_long, - pub ecx: ::c_long, - pub edx: ::c_long, - pub esi: ::c_long, - pub edi: ::c_long, - pub ebp: ::c_long, - pub eax: ::c_long, - pub xds: ::c_long, - pub xes: ::c_long, - pub xfs: ::c_long, - pub xgs: ::c_long, - pub orig_eax: ::c_long, - pub eip: ::c_long, - pub xcs: ::c_long, - pub eflags: ::c_long, - pub esp: ::c_long, - pub xss: ::c_long, - } - - pub struct user { - pub regs: user_regs_struct, - pub u_fpvalid: ::c_int, - pub i387: user_fpregs_struct, - pub u_tsize: ::c_ulong, - pub u_dsize: ::c_ulong, - pub u_ssize: ::c_ulong, - pub start_code: ::c_ulong, - pub start_stack: ::c_ulong, - pub signal: ::c_long, - __reserved: ::c_int, - pub u_ar0: *mut user_regs_struct, - pub u_fpstate: *mut user_fpregs_struct, - pub magic: ::c_ulong, - pub u_comm: [c_char; 32], - pub u_debugreg: [::c_int; 8], - } - - pub struct mcontext_t { - pub gregs: [greg_t; 19], - pub fpregs: *mut _libc_fpstate, - pub oldmask: ::c_ulong, - pub cr2: ::c_ulong, - } - - pub struct ucontext_t { - pub uc_flags: ::c_ulong, - pub uc_link: *mut ucontext_t, - pub uc_stack: ::stack_t, - pub uc_mcontext: mcontext_t, - pub uc_sigmask: ::sigset_t, - __private: [u8; 112], - } - - pub struct ipc_perm { - pub __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::c_ushort, - __pad1: ::c_ushort, - pub __seq: ::c_ushort, - __pad2: ::c_ushort, - __unused1: ::c_ulong, - __unused2: ::c_ulong - } - - pub struct stat64 { - pub st_dev: ::dev_t, - __pad1: ::c_uint, - __st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad2: ::c_uint, - pub st_size: ::off64_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_ino: ::ino64_t, - } - - pub struct statfs64 { - pub f_type: ::__fsword_t, - pub f_bsize: ::__fsword_t, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_fsid: ::fsid_t, - pub f_namelen: ::__fsword_t, - pub f_frsize: ::__fsword_t, - pub f_flags: ::__fsword_t, - pub f_spare: [::__fsword_t; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - __f_unused: ::c_int, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - __unused1: ::c_ulong, - pub shm_dtime: ::time_t, - __unused2: ::c_ulong, - pub shm_ctime: ::time_t, - __unused3: ::c_ulong, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __unused4: ::c_ulong, - __unused5: ::c_ulong - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - pub msg_stime: ::time_t, - __glibc_reserved1: ::c_ulong, - pub msg_rtime: ::time_t, - __glibc_reserved2: ::c_ulong, - pub msg_ctime: ::time_t, - __glibc_reserved3: ::c_ulong, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __glibc_reserved4: ::c_ulong, - __glibc_reserved5: ::c_ulong, - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 19], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } -} - -pub const O_DIRECT: ::c_int = 0x4000; -pub const O_DIRECTORY: ::c_int = 0x10000; -pub const O_NOFOLLOW: ::c_int = 0x20000; -pub const O_LARGEFILE: ::c_int = 0o0100000; - -pub const MAP_LOCKED: ::c_int = 0x02000; -pub const MAP_NORESERVE: ::c_int = 0x04000; -pub const MAP_32BIT: ::c_int = 0x0040; - -pub const EDEADLOCK: ::c_int = 35; - -pub const SO_SNDBUFFORCE: ::c_int = 32; -pub const SO_RCVBUFFORCE: ::c_int = 33; -pub const SO_NO_CHECK: ::c_int = 11; -pub const SO_PASSCRED: ::c_int = 16; -pub const SO_PEERCRED: ::c_int = 17; -pub const SO_RCVLOWAT: ::c_int = 18; -pub const SO_SNDLOWAT: ::c_int = 19; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_SNDTIMEO: ::c_int = 21; - -pub const FIOCLEX: ::c_ulong = 0x5451; -pub const FIONBIO: ::c_ulong = 0x5421; - -pub const PTRACE_GETFPXREGS: ::c_uint = 18; -pub const PTRACE_SETFPXREGS: ::c_uint = 19; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const SIGSTKSZ: ::size_t = 8192; -pub const MINSIGSTKSZ: ::size_t = 2048; -pub const CBAUD: ::tcflag_t = 0o0010017; -pub const TAB1: ::c_int = 0x00000800; -pub const TAB2: ::c_int = 0x00001000; -pub const TAB3: ::c_int = 0x00001800; -pub const CR1: ::c_int = 0x00000200; -pub const CR2: ::c_int = 0x00000400; -pub const CR3: ::c_int = 0x00000600; -pub const FF1: ::c_int = 0x00008000; -pub const BS1: ::c_int = 0x00002000; -pub const VT1: ::c_int = 0x00004000; -pub const VWERASE: usize = 14; -pub const VREPRINT: usize = 12; -pub const VSUSP: usize = 10; -pub const VSTART: usize = 8; -pub const VSTOP: usize = 9; -pub const VDISCARD: usize = 13; -pub const VTIME: usize = 5; -pub const IXON: ::tcflag_t = 0x00000400; -pub const IXOFF: ::tcflag_t = 0x00001000; -pub const ONLCR: ::tcflag_t = 0x4; -pub const CSIZE: ::tcflag_t = 0x00000030; -pub const CS6: ::tcflag_t = 0x00000010; -pub const CS7: ::tcflag_t = 0x00000020; -pub const CS8: ::tcflag_t = 0x00000030; -pub const CSTOPB: ::tcflag_t = 0x00000040; -pub const CREAD: ::tcflag_t = 0x00000080; -pub const PARENB: ::tcflag_t = 0x00000100; -pub const PARODD: ::tcflag_t = 0x00000200; -pub const HUPCL: ::tcflag_t = 0x00000400; -pub const CLOCAL: ::tcflag_t = 0x00000800; -pub const ECHOKE: ::tcflag_t = 0x00000800; -pub const ECHOE: ::tcflag_t = 0x00000010; -pub const ECHOK: ::tcflag_t = 0x00000020; -pub const ECHONL: ::tcflag_t = 0x00000040; -pub const ECHOPRT: ::tcflag_t = 0x00000400; -pub const ECHOCTL: ::tcflag_t = 0x00000200; -pub const ISIG: ::tcflag_t = 0x00000001; -pub const ICANON: ::tcflag_t = 0x00000002; -pub const PENDIN: ::tcflag_t = 0x00004000; -pub const NOFLSH: ::tcflag_t = 0x00000080; -pub const CIBAUD: ::tcflag_t = 0o02003600000; -pub const CBAUDEX: ::tcflag_t = 0o010000; -pub const VSWTC: usize = 7; -pub const OLCUC: ::tcflag_t = 0o000002; -pub const NLDLY: ::tcflag_t = 0o000400; -pub const CRDLY: ::tcflag_t = 0o003000; -pub const TABDLY: ::tcflag_t = 0o014000; -pub const BSDLY: ::tcflag_t = 0o020000; -pub const FFDLY: ::tcflag_t = 0o100000; -pub const VTDLY: ::tcflag_t = 0o040000; -pub const XTABS: ::tcflag_t = 0o014000; - -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const EXTA: ::speed_t = B19200; -pub const EXTB: ::speed_t = B38400; -pub const BOTHER: ::speed_t = 0o010000; -pub const B57600: ::speed_t = 0o010001; -pub const B115200: ::speed_t = 0o010002; -pub const B230400: ::speed_t = 0o010003; -pub const B460800: ::speed_t = 0o010004; -pub const B500000: ::speed_t = 0o010005; -pub const B576000: ::speed_t = 0o010006; -pub const B921600: ::speed_t = 0o010007; -pub const B1000000: ::speed_t = 0o010010; -pub const B1152000: ::speed_t = 0o010011; -pub const B1500000: ::speed_t = 0o010012; -pub const B2000000: ::speed_t = 0o010013; -pub const B2500000: ::speed_t = 0o010014; -pub const B3000000: ::speed_t = 0o010015; -pub const B3500000: ::speed_t = 0o010016; -pub const B4000000: ::speed_t = 0o010017; - -pub const VEOL: usize = 11; -pub const VEOL2: usize = 16; -pub const VMIN: usize = 6; -pub const IEXTEN: ::tcflag_t = 0x00008000; -pub const TOSTOP: ::tcflag_t = 0x00000100; -pub const FLUSHO: ::tcflag_t = 0x00001000; -pub const EXTPROC: ::tcflag_t = 0x00010000; -pub const TCGETS: ::c_ulong = 0x5401; -pub const TCSETS: ::c_ulong = 0x5402; -pub const TCSETSW: ::c_ulong = 0x5403; -pub const TCSETSF: ::c_ulong = 0x5404; -pub const TCGETA: ::c_ulong = 0x5405; -pub const TCSETA: ::c_ulong = 0x5406; -pub const TCSETAW: ::c_ulong = 0x5407; -pub const TCSETAF: ::c_ulong = 0x5408; -pub const TCSBRK: ::c_ulong = 0x5409; -pub const TCXONC: ::c_ulong = 0x540A; -pub const TCFLSH: ::c_ulong = 0x540B; -pub const TIOCINQ: ::c_ulong = 0x541B; -pub const TIOCGPGRP: ::c_ulong = 0x540F; -pub const TIOCSPGRP: ::c_ulong = 0x5410; -pub const TIOCOUTQ: ::c_ulong = 0x5411; -pub const TIOCGWINSZ: ::c_ulong = 0x5413; -pub const TIOCSWINSZ: ::c_ulong = 0x5414; -pub const FIONREAD: ::c_ulong = 0x541B; - -// Syscall table -pub const SYS_restart_syscall: ::c_long = 0; -pub const SYS_exit: ::c_long = 1; -pub const SYS_fork: ::c_long = 2; -pub const SYS_read: ::c_long = 3; -pub const SYS_write: ::c_long = 4; -pub const SYS_open: ::c_long = 5; -pub const SYS_close: ::c_long = 6; -pub const SYS_waitpid: ::c_long = 7; -pub const SYS_creat: ::c_long = 8; -pub const SYS_link: ::c_long = 9; -pub const SYS_unlink: ::c_long = 10; -pub const SYS_execve: ::c_long = 11; -pub const SYS_chdir: ::c_long = 12; -pub const SYS_time: ::c_long = 13; -pub const SYS_mknod: ::c_long = 14; -pub const SYS_chmod: ::c_long = 15; -pub const SYS_lchown: ::c_long = 16; -pub const SYS_break: ::c_long = 17; -pub const SYS_oldstat: ::c_long = 18; -pub const SYS_lseek: ::c_long = 19; -pub const SYS_getpid: ::c_long = 20; -pub const SYS_mount: ::c_long = 21; -pub const SYS_umount: ::c_long = 22; -pub const SYS_setuid: ::c_long = 23; -pub const SYS_getuid: ::c_long = 24; -pub const SYS_stime: ::c_long = 25; -pub const SYS_ptrace: ::c_long = 26; -pub const SYS_alarm: ::c_long = 27; -pub const SYS_oldfstat: ::c_long = 28; -pub const SYS_pause: ::c_long = 29; -pub const SYS_utime: ::c_long = 30; -pub const SYS_stty: ::c_long = 31; -pub const SYS_gtty: ::c_long = 32; -pub const SYS_access: ::c_long = 33; -pub const SYS_nice: ::c_long = 34; -pub const SYS_ftime: ::c_long = 35; -pub const SYS_sync: ::c_long = 36; -pub const SYS_kill: ::c_long = 37; -pub const SYS_rename: ::c_long = 38; -pub const SYS_mkdir: ::c_long = 39; -pub const SYS_rmdir: ::c_long = 40; -pub const SYS_dup: ::c_long = 41; -pub const SYS_pipe: ::c_long = 42; -pub const SYS_times: ::c_long = 43; -pub const SYS_prof: ::c_long = 44; -pub const SYS_brk: ::c_long = 45; -pub const SYS_setgid: ::c_long = 46; -pub const SYS_getgid: ::c_long = 47; -pub const SYS_signal: ::c_long = 48; -pub const SYS_geteuid: ::c_long = 49; -pub const SYS_getegid: ::c_long = 50; -pub const SYS_acct: ::c_long = 51; -pub const SYS_umount2: ::c_long = 52; -pub const SYS_lock: ::c_long = 53; -pub const SYS_ioctl: ::c_long = 54; -pub const SYS_fcntl: ::c_long = 55; -pub const SYS_mpx: ::c_long = 56; -pub const SYS_setpgid: ::c_long = 57; -pub const SYS_ulimit: ::c_long = 58; -pub const SYS_oldolduname: ::c_long = 59; -pub const SYS_umask: ::c_long = 60; -pub const SYS_chroot: ::c_long = 61; -pub const SYS_ustat: ::c_long = 62; -pub const SYS_dup2: ::c_long = 63; -pub const SYS_getppid: ::c_long = 64; -pub const SYS_getpgrp: ::c_long = 65; -pub const SYS_setsid: ::c_long = 66; -pub const SYS_sigaction: ::c_long = 67; -pub const SYS_sgetmask: ::c_long = 68; -pub const SYS_ssetmask: ::c_long = 69; -pub const SYS_setreuid: ::c_long = 70; -pub const SYS_setregid: ::c_long = 71; -pub const SYS_sigsuspend: ::c_long = 72; -pub const SYS_sigpending: ::c_long = 73; -pub const SYS_sethostname: ::c_long = 74; -pub const SYS_setrlimit: ::c_long = 75; -pub const SYS_getrlimit: ::c_long = 76; -pub const SYS_getrusage: ::c_long = 77; -pub const SYS_gettimeofday: ::c_long = 78; -pub const SYS_settimeofday: ::c_long = 79; -pub const SYS_getgroups: ::c_long = 80; -pub const SYS_setgroups: ::c_long = 81; -pub const SYS_select: ::c_long = 82; -pub const SYS_symlink: ::c_long = 83; -pub const SYS_oldlstat: ::c_long = 84; -pub const SYS_readlink: ::c_long = 85; -pub const SYS_uselib: ::c_long = 86; -pub const SYS_swapon: ::c_long = 87; -pub const SYS_reboot: ::c_long = 88; -pub const SYS_readdir: ::c_long = 89; -pub const SYS_mmap: ::c_long = 90; -pub const SYS_munmap: ::c_long = 91; -pub const SYS_truncate: ::c_long = 92; -pub const SYS_ftruncate: ::c_long = 93; -pub const SYS_fchmod: ::c_long = 94; -pub const SYS_fchown: ::c_long = 95; -pub const SYS_getpriority: ::c_long = 96; -pub const SYS_setpriority: ::c_long = 97; -pub const SYS_profil: ::c_long = 98; -pub const SYS_statfs: ::c_long = 99; -pub const SYS_fstatfs: ::c_long = 100; -pub const SYS_ioperm: ::c_long = 101; -pub const SYS_socketcall: ::c_long = 102; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_setitimer: ::c_long = 104; -pub const SYS_getitimer: ::c_long = 105; -pub const SYS_stat: ::c_long = 106; -pub const SYS_lstat: ::c_long = 107; -pub const SYS_fstat: ::c_long = 108; -pub const SYS_olduname: ::c_long = 109; -pub const SYS_iopl: ::c_long = 110; -pub const SYS_vhangup: ::c_long = 111; -pub const SYS_idle: ::c_long = 112; -pub const SYS_vm86old: ::c_long = 113; -pub const SYS_wait4: ::c_long = 114; -pub const SYS_swapoff: ::c_long = 115; -pub const SYS_sysinfo: ::c_long = 116; -pub const SYS_ipc: ::c_long = 117; -pub const SYS_fsync: ::c_long = 118; -pub const SYS_sigreturn: ::c_long = 119; -pub const SYS_clone: ::c_long = 120; -pub const SYS_setdomainname: ::c_long = 121; -pub const SYS_uname: ::c_long = 122; -pub const SYS_modify_ldt: ::c_long = 123; -pub const SYS_adjtimex: ::c_long = 124; -pub const SYS_mprotect: ::c_long = 125; -pub const SYS_sigprocmask: ::c_long = 126; -pub const SYS_create_module: ::c_long = 127; -pub const SYS_init_module: ::c_long = 128; -pub const SYS_delete_module: ::c_long = 129; -pub const SYS_get_kernel_syms: ::c_long = 130; -pub const SYS_quotactl: ::c_long = 131; -pub const SYS_getpgid: ::c_long = 132; -pub const SYS_fchdir: ::c_long = 133; -pub const SYS_bdflush: ::c_long = 134; -pub const SYS_sysfs: ::c_long = 135; -pub const SYS_personality: ::c_long = 136; -pub const SYS_afs_syscall: ::c_long = 137; -pub const SYS_setfsuid: ::c_long = 138; -pub const SYS_setfsgid: ::c_long = 139; -pub const SYS__llseek: ::c_long = 140; -pub const SYS_getdents: ::c_long = 141; -pub const SYS__newselect: ::c_long = 142; -pub const SYS_flock: ::c_long = 143; -pub const SYS_msync: ::c_long = 144; -pub const SYS_readv: ::c_long = 145; -pub const SYS_writev: ::c_long = 146; -pub const SYS_getsid: ::c_long = 147; -pub const SYS_fdatasync: ::c_long = 148; -pub const SYS__sysctl: ::c_long = 149; -pub const SYS_mlock: ::c_long = 150; -pub const SYS_munlock: ::c_long = 151; -pub const SYS_mlockall: ::c_long = 152; -pub const SYS_munlockall: ::c_long = 153; -pub const SYS_sched_setparam: ::c_long = 154; -pub const SYS_sched_getparam: ::c_long = 155; -pub const SYS_sched_setscheduler: ::c_long = 156; -pub const SYS_sched_getscheduler: ::c_long = 157; -pub const SYS_sched_yield: ::c_long = 158; -pub const SYS_sched_get_priority_max: ::c_long = 159; -pub const SYS_sched_get_priority_min: ::c_long = 160; -pub const SYS_sched_rr_get_interval: ::c_long = 161; -pub const SYS_nanosleep: ::c_long = 162; -pub const SYS_mremap: ::c_long = 163; -pub const SYS_setresuid: ::c_long = 164; -pub const SYS_getresuid: ::c_long = 165; -pub const SYS_vm86: ::c_long = 166; -pub const SYS_query_module: ::c_long = 167; -pub const SYS_poll: ::c_long = 168; -pub const SYS_nfsservctl: ::c_long = 169; -pub const SYS_setresgid: ::c_long = 170; -pub const SYS_getresgid: ::c_long = 171; -pub const SYS_prctl: ::c_long = 172; -pub const SYS_rt_sigreturn: ::c_long = 173; -pub const SYS_rt_sigaction: ::c_long = 174; -pub const SYS_rt_sigprocmask: ::c_long = 175; -pub const SYS_rt_sigpending: ::c_long = 176; -pub const SYS_rt_sigtimedwait: ::c_long = 177; -pub const SYS_rt_sigqueueinfo: ::c_long = 178; -pub const SYS_rt_sigsuspend: ::c_long = 179; -pub const SYS_pread64: ::c_long = 180; -pub const SYS_pwrite64: ::c_long = 181; -pub const SYS_chown: ::c_long = 182; -pub const SYS_getcwd: ::c_long = 183; -pub const SYS_capget: ::c_long = 184; -pub const SYS_capset: ::c_long = 185; -pub const SYS_sigaltstack: ::c_long = 186; -pub const SYS_sendfile: ::c_long = 187; -pub const SYS_getpmsg: ::c_long = 188; -pub const SYS_putpmsg: ::c_long = 189; -pub const SYS_vfork: ::c_long = 190; -pub const SYS_ugetrlimit: ::c_long = 191; -pub const SYS_mmap2: ::c_long = 192; -pub const SYS_truncate64: ::c_long = 193; -pub const SYS_ftruncate64: ::c_long = 194; -pub const SYS_stat64: ::c_long = 195; -pub const SYS_lstat64: ::c_long = 196; -pub const SYS_fstat64: ::c_long = 197; -pub const SYS_lchown32: ::c_long = 198; -pub const SYS_getuid32: ::c_long = 199; -pub const SYS_getgid32: ::c_long = 200; -pub const SYS_geteuid32: ::c_long = 201; -pub const SYS_getegid32: ::c_long = 202; -pub const SYS_setreuid32: ::c_long = 203; -pub const SYS_setregid32: ::c_long = 204; -pub const SYS_getgroups32: ::c_long = 205; -pub const SYS_setgroups32: ::c_long = 206; -pub const SYS_fchown32: ::c_long = 207; -pub const SYS_setresuid32: ::c_long = 208; -pub const SYS_getresuid32: ::c_long = 209; -pub const SYS_setresgid32: ::c_long = 210; -pub const SYS_getresgid32: ::c_long = 211; -pub const SYS_chown32: ::c_long = 212; -pub const SYS_setuid32: ::c_long = 213; -pub const SYS_setgid32: ::c_long = 214; -pub const SYS_setfsuid32: ::c_long = 215; -pub const SYS_setfsgid32: ::c_long = 216; -pub const SYS_pivot_root: ::c_long = 217; -pub const SYS_mincore: ::c_long = 218; -pub const SYS_madvise: ::c_long = 219; -pub const SYS_getdents64: ::c_long = 220; -pub const SYS_fcntl64: ::c_long = 221; -pub const SYS_gettid: ::c_long = 224; -pub const SYS_readahead: ::c_long = 225; -pub const SYS_setxattr: ::c_long = 226; -pub const SYS_lsetxattr: ::c_long = 227; -pub const SYS_fsetxattr: ::c_long = 228; -pub const SYS_getxattr: ::c_long = 229; -pub const SYS_lgetxattr: ::c_long = 230; -pub const SYS_fgetxattr: ::c_long = 231; -pub const SYS_listxattr: ::c_long = 232; -pub const SYS_llistxattr: ::c_long = 233; -pub const SYS_flistxattr: ::c_long = 234; -pub const SYS_removexattr: ::c_long = 235; -pub const SYS_lremovexattr: ::c_long = 236; -pub const SYS_fremovexattr: ::c_long = 237; -pub const SYS_tkill: ::c_long = 238; -pub const SYS_sendfile64: ::c_long = 239; -pub const SYS_futex: ::c_long = 240; -pub const SYS_sched_setaffinity: ::c_long = 241; -pub const SYS_sched_getaffinity: ::c_long = 242; -pub const SYS_set_thread_area: ::c_long = 243; -pub const SYS_get_thread_area: ::c_long = 244; -pub const SYS_io_setup: ::c_long = 245; -pub const SYS_io_destroy: ::c_long = 246; -pub const SYS_io_getevents: ::c_long = 247; -pub const SYS_io_submit: ::c_long = 248; -pub const SYS_io_cancel: ::c_long = 249; -pub const SYS_fadvise64: ::c_long = 250; -pub const SYS_exit_group: ::c_long = 252; -pub const SYS_lookup_dcookie: ::c_long = 253; -pub const SYS_epoll_create: ::c_long = 254; -pub const SYS_epoll_ctl: ::c_long = 255; -pub const SYS_epoll_wait: ::c_long = 256; -pub const SYS_remap_file_pages: ::c_long = 257; -pub const SYS_set_tid_address: ::c_long = 258; -pub const SYS_timer_create: ::c_long = 259; -pub const SYS_timer_settime: ::c_long = 260; -pub const SYS_timer_gettime: ::c_long = 261; -pub const SYS_timer_getoverrun: ::c_long = 262; -pub const SYS_timer_delete: ::c_long = 263; -pub const SYS_clock_settime: ::c_long = 264; -pub const SYS_clock_gettime: ::c_long = 265; -pub const SYS_clock_getres: ::c_long = 266; -pub const SYS_clock_nanosleep: ::c_long = 267; -pub const SYS_statfs64: ::c_long = 268; -pub const SYS_fstatfs64: ::c_long = 269; -pub const SYS_tgkill: ::c_long = 270; -pub const SYS_utimes: ::c_long = 271; -pub const SYS_fadvise64_64: ::c_long = 272; -pub const SYS_vserver: ::c_long = 273; -pub const SYS_mbind: ::c_long = 274; -pub const SYS_get_mempolicy: ::c_long = 275; -pub const SYS_set_mempolicy: ::c_long = 276; -pub const SYS_mq_open: ::c_long = 277; -pub const SYS_mq_unlink: ::c_long = 278; -pub const SYS_mq_timedsend: ::c_long = 279; -pub const SYS_mq_timedreceive: ::c_long = 280; -pub const SYS_mq_notify: ::c_long = 281; -pub const SYS_mq_getsetattr: ::c_long = 282; -pub const SYS_kexec_load: ::c_long = 283; -pub const SYS_waitid: ::c_long = 284; -pub const SYS_add_key: ::c_long = 286; -pub const SYS_request_key: ::c_long = 287; -pub const SYS_keyctl: ::c_long = 288; -pub const SYS_ioprio_set: ::c_long = 289; -pub const SYS_ioprio_get: ::c_long = 290; -pub const SYS_inotify_init: ::c_long = 291; -pub const SYS_inotify_add_watch: ::c_long = 292; -pub const SYS_inotify_rm_watch: ::c_long = 293; -pub const SYS_migrate_pages: ::c_long = 294; -pub const SYS_openat: ::c_long = 295; -pub const SYS_mkdirat: ::c_long = 296; -pub const SYS_mknodat: ::c_long = 297; -pub const SYS_fchownat: ::c_long = 298; -pub const SYS_futimesat: ::c_long = 299; -pub const SYS_fstatat64: ::c_long = 300; -pub const SYS_unlinkat: ::c_long = 301; -pub const SYS_renameat: ::c_long = 302; -pub const SYS_linkat: ::c_long = 303; -pub const SYS_symlinkat: ::c_long = 304; -pub const SYS_readlinkat: ::c_long = 305; -pub const SYS_fchmodat: ::c_long = 306; -pub const SYS_faccessat: ::c_long = 307; -pub const SYS_pselect6: ::c_long = 308; -pub const SYS_ppoll: ::c_long = 309; -pub const SYS_unshare: ::c_long = 310; -pub const SYS_set_robust_list: ::c_long = 311; -pub const SYS_get_robust_list: ::c_long = 312; -pub const SYS_splice: ::c_long = 313; -pub const SYS_sync_file_range: ::c_long = 314; -pub const SYS_tee: ::c_long = 315; -pub const SYS_vmsplice: ::c_long = 316; -pub const SYS_move_pages: ::c_long = 317; -pub const SYS_getcpu: ::c_long = 318; -pub const SYS_epoll_pwait: ::c_long = 319; -pub const SYS_utimensat: ::c_long = 320; -pub const SYS_signalfd: ::c_long = 321; -pub const SYS_timerfd_create: ::c_long = 322; -pub const SYS_eventfd: ::c_long = 323; -pub const SYS_fallocate: ::c_long = 324; -pub const SYS_timerfd_settime: ::c_long = 325; -pub const SYS_timerfd_gettime: ::c_long = 326; -pub const SYS_signalfd4: ::c_long = 327; -pub const SYS_eventfd2: ::c_long = 328; -pub const SYS_epoll_create1: ::c_long = 329; -pub const SYS_dup3: ::c_long = 330; -pub const SYS_pipe2: ::c_long = 331; -pub const SYS_inotify_init1: ::c_long = 332; -pub const SYS_preadv: ::c_long = 333; -pub const SYS_pwritev: ::c_long = 334; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 335; -pub const SYS_perf_event_open: ::c_long = 336; -pub const SYS_recvmmsg: ::c_long = 337; -pub const SYS_fanotify_init: ::c_long = 338; -pub const SYS_fanotify_mark: ::c_long = 339; -pub const SYS_prlimit64: ::c_long = 340; -pub const SYS_name_to_handle_at: ::c_long = 341; -pub const SYS_open_by_handle_at: ::c_long = 342; -pub const SYS_clock_adjtime: ::c_long = 343; -pub const SYS_syncfs: ::c_long = 344; -pub const SYS_sendmmsg: ::c_long = 345; -pub const SYS_setns: ::c_long = 346; -pub const SYS_process_vm_readv: ::c_long = 347; -pub const SYS_process_vm_writev: ::c_long = 348; -pub const SYS_kcmp: ::c_long = 349; -pub const SYS_finit_module: ::c_long = 350; -pub const SYS_sched_setattr: ::c_long = 351; -pub const SYS_sched_getattr: ::c_long = 352; -pub const SYS_renameat2: ::c_long = 353; -pub const SYS_seccomp: ::c_long = 354; -pub const SYS_getrandom: ::c_long = 355; -pub const SYS_memfd_create: ::c_long = 356; -pub const SYS_bpf: ::c_long = 357; -pub const SYS_execveat: ::c_long = 358; -pub const SYS_socket: ::c_long = 359; -pub const SYS_socketpair: ::c_long = 360; -pub const SYS_bind: ::c_long = 361; -pub const SYS_connect: ::c_long = 362; -pub const SYS_listen: ::c_long = 363; -pub const SYS_accept4: ::c_long = 364; -pub const SYS_getsockopt: ::c_long = 365; -pub const SYS_setsockopt: ::c_long = 366; -pub const SYS_getsockname: ::c_long = 367; -pub const SYS_getpeername: ::c_long = 368; -pub const SYS_sendto: ::c_long = 369; -pub const SYS_sendmsg: ::c_long = 370; -pub const SYS_recvfrom: ::c_long = 371; -pub const SYS_recvmsg: ::c_long = 372; -pub const SYS_shutdown: ::c_long = 373; -pub const SYS_userfaultfd: ::c_long = 374; -pub const SYS_membarrier: ::c_long = 375; -pub const SYS_mlock2: ::c_long = 376; -pub const SYS_copy_file_range: ::c_long = 377; -pub const SYS_preadv2: ::c_long = 378; -pub const SYS_pwritev2: ::c_long = 379; -pub const SYS_pkey_mprotect: ::c_long = 380; -pub const SYS_pkey_alloc: ::c_long = 381; -pub const SYS_pkey_free: ::c_long = 382; - -// offsets in user_regs_structs, from sys/reg.h -pub const EBX: ::c_int = 0; -pub const ECX: ::c_int = 1; -pub const EDX: ::c_int = 2; -pub const ESI: ::c_int = 3; -pub const EDI: ::c_int = 4; -pub const EBP: ::c_int = 5; -pub const EAX: ::c_int = 6; -pub const DS: ::c_int = 7; -pub const ES: ::c_int = 8; -pub const FS: ::c_int = 9; -pub const GS: ::c_int = 10; -pub const ORIG_EAX: ::c_int = 11; -pub const EIP: ::c_int = 12; -pub const CS: ::c_int = 13; -pub const EFL: ::c_int = 14; -pub const UESP: ::c_int = 15; -pub const SS: ::c_int = 16; - -extern { - pub fn getcontext(ucp: *mut ucontext_t) -> ::c_int; - pub fn setcontext(ucp: *const ucontext_t) -> ::c_int; - pub fn makecontext(ucp: *mut ucontext_t, - func: extern fn (), - argc: ::c_int, ...); - pub fn swapcontext(uocp: *mut ucontext_t, - ucp: *const ucontext_t) -> ::c_int; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/aarch64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/aarch64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,786 +0,0 @@ -//! AArch64-specific definitions for 64-bit linux-like values - -pub type c_long = i64; -pub type c_ulong = u64; -pub type c_char = u8; -pub type wchar_t = u32; -pub type nlink_t = u32; -pub type blksize_t = i32; -pub type suseconds_t = i64; -pub type __u64 = ::c_ulonglong; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad1: ::dev_t, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - __pad2: ::c_int, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused: [::c_int; 2], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad1: ::dev_t, - pub st_size: ::off64_t, - pub st_blksize: ::blksize_t, - __pad2: ::c_int, - pub st_blocks: ::blkcnt64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused: [::c_int; 2], - } - - pub struct statfs64 { - pub f_type: ::__fsword_t, - pub f_bsize: ::__fsword_t, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_fsid: ::fsid_t, - pub f_namelen: ::__fsword_t, - pub f_frsize: ::__fsword_t, - pub f_flags: ::__fsword_t, - pub f_spare: [::__fsword_t; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct pthread_attr_t { - __size: [u64; 8] - } - - pub struct ipc_perm { - pub __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::c_uint, - pub __seq: ::c_ushort, - __pad1: ::c_ushort, - __unused1: ::c_ulong, - __unused2: ::c_ulong - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __unused4: ::c_ulong, - __unused5: ::c_ulong - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 19], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } -} - -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; - -pub const TIOCGSOFTCAR: ::c_ulong = 0x5419; -pub const TIOCSSOFTCAR: ::c_ulong = 0x541A; - -pub const RLIMIT_NOFILE: ::c_int = 7; -pub const RLIMIT_NPROC: ::c_int = 6; - -pub const O_APPEND: ::c_int = 1024; -pub const O_CREAT: ::c_int = 64; -pub const O_EXCL: ::c_int = 128; -pub const O_NOCTTY: ::c_int = 256; -pub const O_NONBLOCK: ::c_int = 2048; -pub const O_SYNC: ::c_int = 1052672; -pub const O_RSYNC: ::c_int = 1052672; -pub const O_DSYNC: ::c_int = 4096; -pub const O_FSYNC: ::c_int = 0x101000; -pub const O_NOATIME: ::c_int = 0o1000000; -pub const O_PATH: ::c_int = 0o10000000; -pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; - -pub const MAP_GROWSDOWN: ::c_int = 0x0100; - -pub const EDEADLK: ::c_int = 35; -pub const ENAMETOOLONG: ::c_int = 36; -pub const ENOLCK: ::c_int = 37; -pub const ENOSYS: ::c_int = 38; -pub const ENOTEMPTY: ::c_int = 39; -pub const ELOOP: ::c_int = 40; -pub const ENOMSG: ::c_int = 42; -pub const EIDRM: ::c_int = 43; -pub const ECHRNG: ::c_int = 44; -pub const EL2NSYNC: ::c_int = 45; -pub const EL3HLT: ::c_int = 46; -pub const EL3RST: ::c_int = 47; -pub const ELNRNG: ::c_int = 48; -pub const EUNATCH: ::c_int = 49; -pub const ENOCSI: ::c_int = 50; -pub const EL2HLT: ::c_int = 51; -pub const EBADE: ::c_int = 52; -pub const EBADR: ::c_int = 53; -pub const EXFULL: ::c_int = 54; -pub const ENOANO: ::c_int = 55; -pub const EBADRQC: ::c_int = 56; -pub const EBADSLT: ::c_int = 57; -pub const EMULTIHOP: ::c_int = 72; -pub const EOVERFLOW: ::c_int = 75; -pub const ENOTUNIQ: ::c_int = 76; -pub const EBADFD: ::c_int = 77; -pub const EBADMSG: ::c_int = 74; -pub const EREMCHG: ::c_int = 78; -pub const ELIBACC: ::c_int = 79; -pub const ELIBBAD: ::c_int = 80; -pub const ELIBSCN: ::c_int = 81; -pub const ELIBMAX: ::c_int = 82; -pub const ELIBEXEC: ::c_int = 83; -pub const EILSEQ: ::c_int = 84; -pub const ERESTART: ::c_int = 85; -pub const ESTRPIPE: ::c_int = 86; -pub const EUSERS: ::c_int = 87; -pub const ENOTSOCK: ::c_int = 88; -pub const EDESTADDRREQ: ::c_int = 89; -pub const EMSGSIZE: ::c_int = 90; -pub const EPROTOTYPE: ::c_int = 91; -pub const ENOPROTOOPT: ::c_int = 92; -pub const EPROTONOSUPPORT: ::c_int = 93; -pub const ESOCKTNOSUPPORT: ::c_int = 94; -pub const EOPNOTSUPP: ::c_int = 95; -pub const EPFNOSUPPORT: ::c_int = 96; -pub const EAFNOSUPPORT: ::c_int = 97; -pub const EADDRINUSE: ::c_int = 98; -pub const EADDRNOTAVAIL: ::c_int = 99; -pub const ENETDOWN: ::c_int = 100; -pub const ENETUNREACH: ::c_int = 101; -pub const ENETRESET: ::c_int = 102; -pub const ECONNABORTED: ::c_int = 103; -pub const ECONNRESET: ::c_int = 104; -pub const ENOBUFS: ::c_int = 105; -pub const EISCONN: ::c_int = 106; -pub const ENOTCONN: ::c_int = 107; -pub const ESHUTDOWN: ::c_int = 108; -pub const ETOOMANYREFS: ::c_int = 109; -pub const ETIMEDOUT: ::c_int = 110; -pub const ECONNREFUSED: ::c_int = 111; -pub const EHOSTDOWN: ::c_int = 112; -pub const EHOSTUNREACH: ::c_int = 113; -pub const EALREADY: ::c_int = 114; -pub const EINPROGRESS: ::c_int = 115; -pub const ESTALE: ::c_int = 116; -pub const EDQUOT: ::c_int = 122; -pub const ENOMEDIUM: ::c_int = 123; -pub const EMEDIUMTYPE: ::c_int = 124; -pub const ECANCELED: ::c_int = 125; -pub const ENOKEY: ::c_int = 126; -pub const EKEYEXPIRED: ::c_int = 127; -pub const EKEYREVOKED: ::c_int = 128; -pub const EKEYREJECTED: ::c_int = 129; -pub const EOWNERDEAD: ::c_int = 130; -pub const ENOTRECOVERABLE: ::c_int = 131; -pub const EHWPOISON: ::c_int = 133; -pub const ERFKILL: ::c_int = 132; - -pub const SOL_SOCKET: ::c_int = 1; - -pub const SO_REUSEADDR: ::c_int = 2; -pub const SO_TYPE: ::c_int = 3; -pub const SO_ERROR: ::c_int = 4; -pub const SO_DONTROUTE: ::c_int = 5; -pub const SO_BROADCAST: ::c_int = 6; -pub const SO_SNDBUF: ::c_int = 7; -pub const SO_RCVBUF: ::c_int = 8; -pub const SO_SNDBUFFORCE: ::c_int = 32; -pub const SO_RCVBUFFORCE: ::c_int = 33; -pub const SO_KEEPALIVE: ::c_int = 9; -pub const SO_OOBINLINE: ::c_int = 10; -pub const SO_NO_CHECK: ::c_int = 11; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_LINGER: ::c_int = 13; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_REUSEPORT: ::c_int = 15; -pub const SO_PASSCRED: ::c_int = 16; -pub const SO_PEERCRED: ::c_int = 17; -pub const SO_RCVLOWAT: ::c_int = 18; -pub const SO_SNDLOWAT: ::c_int = 19; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_SNDTIMEO: ::c_int = 21; -pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22; -pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23; -pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24; -pub const SO_BINDTODEVICE: ::c_int = 25; -pub const SO_ATTACH_FILTER: ::c_int = 26; -pub const SO_DETACH_FILTER: ::c_int = 27; -pub const SO_GET_FILTER: ::c_int = SO_ATTACH_FILTER; -pub const SO_PEERNAME: ::c_int = 28; -pub const SO_TIMESTAMP: ::c_int = 29; -pub const SO_ACCEPTCONN: ::c_int = 30; -pub const SO_PEERSEC: ::c_int = 31; -pub const SO_PASSSEC: ::c_int = 34; -pub const SO_TIMESTAMPNS: ::c_int = 35; -pub const SCM_TIMESTAMPNS: ::c_int = SO_TIMESTAMPNS; -pub const SO_MARK: ::c_int = 36; -pub const SO_TIMESTAMPING: ::c_int = 37; -pub const SCM_TIMESTAMPING: ::c_int = SO_TIMESTAMPING; -pub const SO_PROTOCOL: ::c_int = 38; -pub const SO_DOMAIN: ::c_int = 39; -pub const SO_RXQ_OVFL: ::c_int = 40; -pub const SO_WIFI_STATUS: ::c_int = 41; -pub const SCM_WIFI_STATUS: ::c_int = SO_WIFI_STATUS; -pub const SO_PEEK_OFF: ::c_int = 42; -pub const SO_NOFCS: ::c_int = 43; -pub const SO_LOCK_FILTER: ::c_int = 44; -pub const SO_SELECT_ERR_QUEUE: ::c_int = 45; -pub const SO_BUSY_POLL: ::c_int = 46; -pub const SO_MAX_PACING_RATE: ::c_int = 47; -pub const SO_BPF_EXTENSIONS: ::c_int = 48; -pub const SO_INCOMING_CPU: ::c_int = 49; -pub const SO_ATTACH_BPF: ::c_int = 50; -pub const SO_DETACH_BPF: ::c_int = SO_DETACH_FILTER; - -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 0x00000004; -pub const SA_NOCLDWAIT: ::c_int = 0x00000002; - -pub const SIGCHLD: ::c_int = 17; -pub const SIGBUS: ::c_int = 7; -pub const SIGUSR1: ::c_int = 10; -pub const SIGUSR2: ::c_int = 12; -pub const SIGCONT: ::c_int = 18; -pub const SIGSTOP: ::c_int = 19; -pub const SIGTSTP: ::c_int = 20; -pub const SIGURG: ::c_int = 23; -pub const SIGIO: ::c_int = 29; -pub const SIGSYS: ::c_int = 31; -pub const SIGSTKFLT: ::c_int = 16; -pub const SIGUNUSED: ::c_int = 31; -pub const SIGPOLL: ::c_int = 29; -pub const SIGPWR: ::c_int = 30; -pub const SIG_SETMASK: ::c_int = 2; -pub const SIG_BLOCK: ::c_int = 0x000000; -pub const SIG_UNBLOCK: ::c_int = 0x01; - -pub const POLLWRNORM: ::c_short = 0x100; -pub const POLLWRBAND: ::c_short = 0x200; - -pub const O_ASYNC: ::c_int = 0x2000; -pub const O_NDELAY: ::c_int = 0x800; - -pub const PTRACE_DETACH: ::c_uint = 17; - -pub const EFD_NONBLOCK: ::c_int = 0x800; - -pub const F_GETLK: ::c_int = 5; -pub const F_GETOWN: ::c_int = 9; -pub const F_SETOWN: ::c_int = 8; -pub const F_SETLK: ::c_int = 6; -pub const F_SETLKW: ::c_int = 7; - -pub const SFD_NONBLOCK: ::c_int = 0x0800; - -pub const TIOCEXCL: ::c_ulong = 0x540C; -pub const TIOCNXCL: ::c_ulong = 0x540D; -pub const TIOCSCTTY: ::c_ulong = 0x540E; -pub const TIOCSTI: ::c_ulong = 0x5412; -pub const TIOCMGET: ::c_ulong = 0x5415; -pub const TIOCMBIS: ::c_ulong = 0x5416; -pub const TIOCMBIC: ::c_ulong = 0x5417; -pub const TIOCMSET: ::c_ulong = 0x5418; -pub const TIOCCONS: ::c_ulong = 0x541D; - -pub const SFD_CLOEXEC: ::c_int = 0x080000; - -pub const NCCS: usize = 32; - -pub const O_TRUNC: ::c_int = 512; - -pub const O_CLOEXEC: ::c_int = 0x80000; - -pub const EBFONT: ::c_int = 59; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENONET: ::c_int = 64; -pub const ENOPKG: ::c_int = 65; -pub const EREMOTE: ::c_int = 66; -pub const ENOLINK: ::c_int = 67; -pub const EADV: ::c_int = 68; -pub const ESRMNT: ::c_int = 69; -pub const ECOMM: ::c_int = 70; -pub const EPROTO: ::c_int = 71; -pub const EDOTDOT: ::c_int = 73; - -pub const SA_NODEFER: ::c_int = 0x40000000; -pub const SA_RESETHAND: ::c_int = 0x80000000; -pub const SA_RESTART: ::c_int = 0x10000000; -pub const SA_NOCLDSTOP: ::c_int = 0x00000001; - -pub const EPOLL_CLOEXEC: ::c_int = 0x80000; - -pub const EFD_CLOEXEC: ::c_int = 0x80000; - -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 8; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 48; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 8; - -pub const O_DIRECT: ::c_int = 0x10000; -pub const O_DIRECTORY: ::c_int = 0x4000; -pub const O_NOFOLLOW: ::c_int = 0x8000; - -pub const MAP_LOCKED: ::c_int = 0x02000; -pub const MAP_NORESERVE: ::c_int = 0x04000; - -pub const EDEADLOCK: ::c_int = 35; - -pub const FIOCLEX: ::c_ulong = 0x5451; -pub const FIONBIO: ::c_ulong = 0x5421; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const SIGSTKSZ: ::size_t = 16384; -pub const MINSIGSTKSZ: ::size_t = 5120; -pub const CBAUD: ::tcflag_t = 0o0010017; -pub const TAB1: ::c_int = 0x00000800; -pub const TAB2: ::c_int = 0x00001000; -pub const TAB3: ::c_int = 0x00001800; -pub const CR1: ::c_int = 0x00000200; -pub const CR2: ::c_int = 0x00000400; -pub const CR3: ::c_int = 0x00000600; -pub const FF1: ::c_int = 0x00008000; -pub const BS1: ::c_int = 0x00002000; -pub const VT1: ::c_int = 0x00004000; -pub const VWERASE: usize = 14; -pub const VREPRINT: usize = 12; -pub const VSUSP: usize = 10; -pub const VSTART: usize = 8; -pub const VSTOP: usize = 9; -pub const VDISCARD: usize = 13; -pub const VTIME: usize = 5; -pub const IXON: ::tcflag_t = 0x00000400; -pub const IXOFF: ::tcflag_t = 0x00001000; -pub const ONLCR: ::tcflag_t = 0x4; -pub const CSIZE: ::tcflag_t = 0x00000030; -pub const CS6: ::tcflag_t = 0x00000010; -pub const CS7: ::tcflag_t = 0x00000020; -pub const CS8: ::tcflag_t = 0x00000030; -pub const CSTOPB: ::tcflag_t = 0x00000040; -pub const CREAD: ::tcflag_t = 0x00000080; -pub const PARENB: ::tcflag_t = 0x00000100; -pub const PARODD: ::tcflag_t = 0x00000200; -pub const HUPCL: ::tcflag_t = 0x00000400; -pub const CLOCAL: ::tcflag_t = 0x00000800; -pub const ECHOKE: ::tcflag_t = 0x00000800; -pub const ECHOE: ::tcflag_t = 0x00000010; -pub const ECHOK: ::tcflag_t = 0x00000020; -pub const ECHONL: ::tcflag_t = 0x00000040; -pub const ECHOPRT: ::tcflag_t = 0x00000400; -pub const ECHOCTL: ::tcflag_t = 0x00000200; -pub const ISIG: ::tcflag_t = 0x00000001; -pub const ICANON: ::tcflag_t = 0x00000002; -pub const PENDIN: ::tcflag_t = 0x00004000; -pub const NOFLSH: ::tcflag_t = 0x00000080; -pub const CIBAUD: ::tcflag_t = 0o02003600000; -pub const CBAUDEX: ::tcflag_t = 0o010000; -pub const VSWTC: usize = 7; -pub const OLCUC: ::tcflag_t = 0o000002; -pub const NLDLY: ::tcflag_t = 0o000400; -pub const CRDLY: ::tcflag_t = 0o003000; -pub const TABDLY: ::tcflag_t = 0o014000; -pub const BSDLY: ::tcflag_t = 0o020000; -pub const FFDLY: ::tcflag_t = 0o100000; -pub const VTDLY: ::tcflag_t = 0o040000; -pub const XTABS: ::tcflag_t = 0o014000; - -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const EXTA: ::speed_t = B19200; -pub const EXTB: ::speed_t = B38400; -pub const BOTHER: ::speed_t = 0o010000; -pub const B57600: ::speed_t = 0o010001; -pub const B115200: ::speed_t = 0o010002; -pub const B230400: ::speed_t = 0o010003; -pub const B460800: ::speed_t = 0o010004; -pub const B500000: ::speed_t = 0o010005; -pub const B576000: ::speed_t = 0o010006; -pub const B921600: ::speed_t = 0o010007; -pub const B1000000: ::speed_t = 0o010010; -pub const B1152000: ::speed_t = 0o010011; -pub const B1500000: ::speed_t = 0o010012; -pub const B2000000: ::speed_t = 0o010013; -pub const B2500000: ::speed_t = 0o010014; -pub const B3000000: ::speed_t = 0o010015; -pub const B3500000: ::speed_t = 0o010016; -pub const B4000000: ::speed_t = 0o010017; - -pub const VEOL: usize = 11; -pub const VEOL2: usize = 16; -pub const VMIN: usize = 6; -pub const IEXTEN: ::tcflag_t = 0x00008000; -pub const TOSTOP: ::tcflag_t = 0x00000100; -pub const FLUSHO: ::tcflag_t = 0x00001000; -pub const EXTPROC: ::tcflag_t = 0x00010000; -pub const TCGETS: ::c_ulong = 0x5401; -pub const TCSETS: ::c_ulong = 0x5402; -pub const TCSETSW: ::c_ulong = 0x5403; -pub const TCSETSF: ::c_ulong = 0x5404; -pub const TCGETA: ::c_ulong = 0x5405; -pub const TCSETA: ::c_ulong = 0x5406; -pub const TCSETAW: ::c_ulong = 0x5407; -pub const TCSETAF: ::c_ulong = 0x5408; -pub const TCSBRK: ::c_ulong = 0x5409; -pub const TCXONC: ::c_ulong = 0x540A; -pub const TCFLSH: ::c_ulong = 0x540B; -pub const TIOCINQ: ::c_ulong = 0x541B; -pub const TIOCGPGRP: ::c_ulong = 0x540F; -pub const TIOCSPGRP: ::c_ulong = 0x5410; -pub const TIOCOUTQ: ::c_ulong = 0x5411; -pub const TIOCGWINSZ: ::c_ulong = 0x5413; -pub const TIOCSWINSZ: ::c_ulong = 0x5414; -pub const FIONREAD: ::c_ulong = 0x541B; - -// Syscall table -pub const SYS_io_setup: ::c_long = 0; -pub const SYS_io_destroy: ::c_long = 1; -pub const SYS_io_submit: ::c_long = 2; -pub const SYS_io_cancel: ::c_long = 3; -pub const SYS_io_getevents: ::c_long = 4; -pub const SYS_setxattr: ::c_long = 5; -pub const SYS_lsetxattr: ::c_long = 6; -pub const SYS_fsetxattr: ::c_long = 7; -pub const SYS_getxattr: ::c_long = 8; -pub const SYS_lgetxattr: ::c_long = 9; -pub const SYS_fgetxattr: ::c_long = 10; -pub const SYS_listxattr: ::c_long = 11; -pub const SYS_llistxattr: ::c_long = 12; -pub const SYS_flistxattr: ::c_long = 13; -pub const SYS_removexattr: ::c_long = 14; -pub const SYS_lremovexattr: ::c_long = 15; -pub const SYS_fremovexattr: ::c_long = 16; -pub const SYS_getcwd: ::c_long = 17; -pub const SYS_lookup_dcookie: ::c_long = 18; -pub const SYS_eventfd2: ::c_long = 19; -pub const SYS_epoll_create1: ::c_long = 20; -pub const SYS_epoll_ctl: ::c_long = 21; -pub const SYS_epoll_pwait: ::c_long = 22; -pub const SYS_dup: ::c_long = 23; -pub const SYS_dup3: ::c_long = 24; -pub const SYS_fcntl: ::c_long = 25; -pub const SYS_inotify_init1: ::c_long = 26; -pub const SYS_inotify_add_watch: ::c_long = 27; -pub const SYS_inotify_rm_watch: ::c_long = 28; -pub const SYS_ioctl: ::c_long = 29; -pub const SYS_ioprio_set: ::c_long = 30; -pub const SYS_ioprio_get: ::c_long = 31; -pub const SYS_flock: ::c_long = 32; -pub const SYS_mknodat: ::c_long = 33; -pub const SYS_mkdirat: ::c_long = 34; -pub const SYS_unlinkat: ::c_long = 35; -pub const SYS_symlinkat: ::c_long = 36; -pub const SYS_linkat: ::c_long = 37; -pub const SYS_renameat: ::c_long = 38; -pub const SYS_umount2: ::c_long = 39; -pub const SYS_mount: ::c_long = 40; -pub const SYS_pivot_root: ::c_long = 41; -pub const SYS_nfsservctl: ::c_long = 42; -pub const SYS_fallocate: ::c_long = 47; -pub const SYS_faccessat: ::c_long = 48; -pub const SYS_chdir: ::c_long = 49; -pub const SYS_fchdir: ::c_long = 50; -pub const SYS_chroot: ::c_long = 51; -pub const SYS_fchmod: ::c_long = 52; -pub const SYS_fchmodat: ::c_long = 53; -pub const SYS_fchownat: ::c_long = 54; -pub const SYS_fchown: ::c_long = 55; -pub const SYS_openat: ::c_long = 56; -pub const SYS_close: ::c_long = 57; -pub const SYS_vhangup: ::c_long = 58; -pub const SYS_pipe2: ::c_long = 59; -pub const SYS_quotactl: ::c_long = 60; -pub const SYS_getdents64: ::c_long = 61; -pub const SYS_lseek: ::c_long = 62; -pub const SYS_read: ::c_long = 63; -pub const SYS_write: ::c_long = 64; -pub const SYS_readv: ::c_long = 65; -pub const SYS_writev: ::c_long = 66; -pub const SYS_pread64: ::c_long = 67; -pub const SYS_pwrite64: ::c_long = 68; -pub const SYS_preadv: ::c_long = 69; -pub const SYS_pwritev: ::c_long = 70; -pub const SYS_pselect6: ::c_long = 72; -pub const SYS_ppoll: ::c_long = 73; -pub const SYS_signalfd4: ::c_long = 74; -pub const SYS_vmsplice: ::c_long = 75; -pub const SYS_splice: ::c_long = 76; -pub const SYS_tee: ::c_long = 77; -pub const SYS_readlinkat: ::c_long = 78; -pub const SYS_newfstatat: ::c_long = 79; -pub const SYS_fstat: ::c_long = 80; -pub const SYS_sync: ::c_long = 81; -pub const SYS_fsync: ::c_long = 82; -pub const SYS_fdatasync: ::c_long = 83; -pub const SYS_sync_file_range: ::c_long = 84; -pub const SYS_timerfd_create: ::c_long = 85; -pub const SYS_timerfd_settime: ::c_long = 86; -pub const SYS_timerfd_gettime: ::c_long = 87; -pub const SYS_utimensat: ::c_long = 88; -pub const SYS_acct: ::c_long = 89; -pub const SYS_capget: ::c_long = 90; -pub const SYS_capset: ::c_long = 91; -pub const SYS_personality: ::c_long = 92; -pub const SYS_exit: ::c_long = 93; -pub const SYS_exit_group: ::c_long = 94; -pub const SYS_waitid: ::c_long = 95; -pub const SYS_set_tid_address: ::c_long = 96; -pub const SYS_unshare: ::c_long = 97; -pub const SYS_futex: ::c_long = 98; -pub const SYS_set_robust_list: ::c_long = 99; -pub const SYS_get_robust_list: ::c_long = 100; -pub const SYS_nanosleep: ::c_long = 101; -pub const SYS_getitimer: ::c_long = 102; -pub const SYS_setitimer: ::c_long = 103; -pub const SYS_kexec_load: ::c_long = 104; -pub const SYS_init_module: ::c_long = 105; -pub const SYS_delete_module: ::c_long = 106; -pub const SYS_timer_create: ::c_long = 107; -pub const SYS_timer_gettime: ::c_long = 108; -pub const SYS_timer_getoverrun: ::c_long = 109; -pub const SYS_timer_settime: ::c_long = 110; -pub const SYS_timer_delete: ::c_long = 111; -pub const SYS_clock_settime: ::c_long = 112; -pub const SYS_clock_gettime: ::c_long = 113; -pub const SYS_clock_getres: ::c_long = 114; -pub const SYS_clock_nanosleep: ::c_long = 115; -pub const SYS_syslog: ::c_long = 116; -pub const SYS_ptrace: ::c_long = 117; -pub const SYS_sched_setparam: ::c_long = 118; -pub const SYS_sched_setscheduler: ::c_long = 119; -pub const SYS_sched_getscheduler: ::c_long = 120; -pub const SYS_sched_getparam: ::c_long = 121; -pub const SYS_sched_setaffinity: ::c_long = 122; -pub const SYS_sched_getaffinity: ::c_long = 123; -pub const SYS_sched_yield: ::c_long = 124; -pub const SYS_sched_get_priority_max: ::c_long = 125; -pub const SYS_sched_get_priority_min: ::c_long = 126; -pub const SYS_sched_rr_get_interval: ::c_long = 127; -pub const SYS_restart_syscall: ::c_long = 128; -pub const SYS_kill: ::c_long = 129; -pub const SYS_tkill: ::c_long = 130; -pub const SYS_tgkill: ::c_long = 131; -pub const SYS_sigaltstack: ::c_long = 132; -pub const SYS_rt_sigsuspend: ::c_long = 133; -pub const SYS_rt_sigaction: ::c_long = 134; -pub const SYS_rt_sigprocmask: ::c_long = 135; -pub const SYS_rt_sigpending: ::c_long = 136; -pub const SYS_rt_sigtimedwait: ::c_long = 137; -pub const SYS_rt_sigqueueinfo: ::c_long = 138; -pub const SYS_rt_sigreturn: ::c_long = 139; -pub const SYS_setpriority: ::c_long = 140; -pub const SYS_getpriority: ::c_long = 141; -pub const SYS_reboot: ::c_long = 142; -pub const SYS_setregid: ::c_long = 143; -pub const SYS_setgid: ::c_long = 144; -pub const SYS_setreuid: ::c_long = 145; -pub const SYS_setuid: ::c_long = 146; -pub const SYS_setresuid: ::c_long = 147; -pub const SYS_getresuid: ::c_long = 148; -pub const SYS_setresgid: ::c_long = 149; -pub const SYS_getresgid: ::c_long = 150; -pub const SYS_setfsuid: ::c_long = 151; -pub const SYS_setfsgid: ::c_long = 152; -pub const SYS_times: ::c_long = 153; -pub const SYS_setpgid: ::c_long = 154; -pub const SYS_getpgid: ::c_long = 155; -pub const SYS_getsid: ::c_long = 156; -pub const SYS_setsid: ::c_long = 157; -pub const SYS_getgroups: ::c_long = 158; -pub const SYS_setgroups: ::c_long = 159; -pub const SYS_uname: ::c_long = 160; -pub const SYS_sethostname: ::c_long = 161; -pub const SYS_setdomainname: ::c_long = 162; -pub const SYS_getrlimit: ::c_long = 163; -pub const SYS_setrlimit: ::c_long = 164; -pub const SYS_getrusage: ::c_long = 165; -pub const SYS_umask: ::c_long = 166; -pub const SYS_prctl: ::c_long = 167; -pub const SYS_getcpu: ::c_long = 168; -pub const SYS_gettimeofday: ::c_long = 169; -pub const SYS_settimeofday: ::c_long = 170; -pub const SYS_adjtimex: ::c_long = 171; -pub const SYS_getpid: ::c_long = 172; -pub const SYS_getppid: ::c_long = 173; -pub const SYS_getuid: ::c_long = 174; -pub const SYS_geteuid: ::c_long = 175; -pub const SYS_getgid: ::c_long = 176; -pub const SYS_getegid: ::c_long = 177; -pub const SYS_gettid: ::c_long = 178; -pub const SYS_sysinfo: ::c_long = 179; -pub const SYS_mq_open: ::c_long = 180; -pub const SYS_mq_unlink: ::c_long = 181; -pub const SYS_mq_timedsend: ::c_long = 182; -pub const SYS_mq_timedreceive: ::c_long = 183; -pub const SYS_mq_notify: ::c_long = 184; -pub const SYS_mq_getsetattr: ::c_long = 185; -pub const SYS_msgget: ::c_long = 186; -pub const SYS_msgctl: ::c_long = 187; -pub const SYS_msgrcv: ::c_long = 188; -pub const SYS_msgsnd: ::c_long = 189; -pub const SYS_semget: ::c_long = 190; -pub const SYS_semctl: ::c_long = 191; -pub const SYS_semtimedop: ::c_long = 192; -pub const SYS_semop: ::c_long = 193; -pub const SYS_shmget: ::c_long = 194; -pub const SYS_shmctl: ::c_long = 195; -pub const SYS_shmat: ::c_long = 196; -pub const SYS_shmdt: ::c_long = 197; -pub const SYS_socket: ::c_long = 198; -pub const SYS_socketpair: ::c_long = 199; -pub const SYS_bind: ::c_long = 200; -pub const SYS_listen: ::c_long = 201; -pub const SYS_accept: ::c_long = 202; -pub const SYS_connect: ::c_long = 203; -pub const SYS_getsockname: ::c_long = 204; -pub const SYS_getpeername: ::c_long = 205; -pub const SYS_sendto: ::c_long = 206; -pub const SYS_recvfrom: ::c_long = 207; -pub const SYS_setsockopt: ::c_long = 208; -pub const SYS_getsockopt: ::c_long = 209; -pub const SYS_shutdown: ::c_long = 210; -pub const SYS_sendmsg: ::c_long = 211; -pub const SYS_recvmsg: ::c_long = 212; -pub const SYS_readahead: ::c_long = 213; -pub const SYS_brk: ::c_long = 214; -pub const SYS_munmap: ::c_long = 215; -pub const SYS_mremap: ::c_long = 216; -pub const SYS_add_key: ::c_long = 217; -pub const SYS_request_key: ::c_long = 218; -pub const SYS_keyctl: ::c_long = 219; -pub const SYS_clone: ::c_long = 220; -pub const SYS_execve: ::c_long = 221; -pub const SYS_mmap: ::c_long = 222; -pub const SYS_swapon: ::c_long = 224; -pub const SYS_swapoff: ::c_long = 225; -pub const SYS_mprotect: ::c_long = 226; -pub const SYS_msync: ::c_long = 227; -pub const SYS_mlock: ::c_long = 228; -pub const SYS_munlock: ::c_long = 229; -pub const SYS_mlockall: ::c_long = 230; -pub const SYS_munlockall: ::c_long = 231; -pub const SYS_mincore: ::c_long = 232; -pub const SYS_madvise: ::c_long = 233; -pub const SYS_remap_file_pages: ::c_long = 234; -pub const SYS_mbind: ::c_long = 235; -pub const SYS_get_mempolicy: ::c_long = 236; -pub const SYS_set_mempolicy: ::c_long = 237; -pub const SYS_migrate_pages: ::c_long = 238; -pub const SYS_move_pages: ::c_long = 239; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 240; -pub const SYS_perf_event_open: ::c_long = 241; -pub const SYS_accept4: ::c_long = 242; -pub const SYS_recvmmsg: ::c_long = 243; -pub const SYS_arch_specific_syscall: ::c_long = 244; -pub const SYS_wait4: ::c_long = 260; -pub const SYS_prlimit64: ::c_long = 261; -pub const SYS_fanotify_init: ::c_long = 262; -pub const SYS_fanotify_mark: ::c_long = 263; -pub const SYS_name_to_handle_at: ::c_long = 264; -pub const SYS_open_by_handle_at: ::c_long = 265; -pub const SYS_clock_adjtime: ::c_long = 266; -pub const SYS_syncfs: ::c_long = 267; -pub const SYS_setns: ::c_long = 268; -pub const SYS_sendmmsg: ::c_long = 269; -pub const SYS_process_vm_readv: ::c_long = 270; -pub const SYS_process_vm_writev: ::c_long = 271; -pub const SYS_kcmp: ::c_long = 272; -pub const SYS_finit_module: ::c_long = 273; -pub const SYS_sched_setattr: ::c_long = 274; -pub const SYS_sched_getattr: ::c_long = 275; -pub const SYS_renameat2: ::c_long = 276; -pub const SYS_seccomp: ::c_long = 277; -pub const SYS_getrandom: ::c_long = 278; -pub const SYS_memfd_create: ::c_long = 279; -pub const SYS_bpf: ::c_long = 280; -pub const SYS_execveat: ::c_long = 281; -pub const SYS_userfaultfd: ::c_long = 282; -pub const SYS_membarrier: ::c_long = 283; -pub const SYS_mlock2: ::c_long = 284; -pub const SYS_copy_file_range: ::c_long = 285; -pub const SYS_preadv2: ::c_long = 286; -pub const SYS_pwritev2: ::c_long = 287; -pub const SYS_pkey_mprotect: ::c_long = 288; -pub const SYS_pkey_alloc: ::c_long = 289; -pub const SYS_pkey_free: ::c_long = 290; -pub const SYS_syscalls: ::c_long = 291; - -#[link(name = "util")] -extern { - pub fn sysctl(name: *mut ::c_int, - namelen: ::c_int, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *mut ::c_void, - newlen: ::size_t) - -> ::c_int; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,85 +0,0 @@ -//! 64-bit specific definitions for linux-like values - -pub type clock_t = i64; -pub type time_t = i64; -pub type ino_t = u64; -pub type off_t = i64; -pub type blkcnt_t = i64; -pub type __fsword_t = i64; -pub type shmatt_t = u64; -pub type msgqnum_t = u64; -pub type msglen_t = u64; -pub type fsblkcnt_t = u64; -pub type fsfilcnt_t = u64; -pub type rlim_t = u64; - -s! { - pub struct sigset_t { - #[cfg(target_pointer_width = "32")] - __val: [u32; 32], - #[cfg(target_pointer_width = "64")] - __val: [u64; 16], - } - - pub struct sysinfo { - pub uptime: i64, - pub loads: [u64; 3], - pub totalram: u64, - pub freeram: u64, - pub sharedram: u64, - pub bufferram: u64, - pub totalswap: u64, - pub freeswap: u64, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: u64, - pub freehigh: u64, - pub mem_unit: ::c_uint, - pub _f: [::c_char; 0], - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - pub msg_stime: ::time_t, - pub msg_rtime: ::time_t, - pub msg_ctime: ::time_t, - __msg_cbytes: u64, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __glibc_reserved4: u64, - __glibc_reserved5: u64, - } -} - -pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; - -pub const O_LARGEFILE: ::c_int = 0; - -cfg_if! { - if #[cfg(target_arch = "aarch64")] { - mod aarch64; - pub use self::aarch64::*; - } else if #[cfg(any(target_arch = "powerpc64"))] { - mod powerpc64; - pub use self::powerpc64::*; - } else if #[cfg(any(target_arch = "sparc64"))] { - mod sparc64; - pub use self::sparc64::*; - } else if #[cfg(any(target_arch = "x86_64"))] { - mod x86_64; - pub use self::x86_64::*; - cfg_if! { - if #[cfg(target_pointer_width = "32")] { - mod x32; - pub use self::x32::*; - } else { - mod not_x32; - pub use self::not_x32::*; - } - } - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/not_x32.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/not_x32.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/not_x32.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/not_x32.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,351 +0,0 @@ -pub type c_long = i64; -pub type c_ulong = u64; - -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; - -// Syscall table - -pub const SYS_read: ::c_long = 0; -pub const SYS_write: ::c_long = 1; -pub const SYS_open: ::c_long = 2; -pub const SYS_close: ::c_long = 3; -pub const SYS_stat: ::c_long = 4; -pub const SYS_fstat: ::c_long = 5; -pub const SYS_lstat: ::c_long = 6; -pub const SYS_poll: ::c_long = 7; -pub const SYS_lseek: ::c_long = 8; -pub const SYS_mmap: ::c_long = 9; -pub const SYS_mprotect: ::c_long = 10; -pub const SYS_munmap: ::c_long = 11; -pub const SYS_brk: ::c_long = 12; -pub const SYS_rt_sigaction: ::c_long = 13; -pub const SYS_rt_sigprocmask: ::c_long = 14; -pub const SYS_rt_sigreturn: ::c_long = 15; -pub const SYS_ioctl: ::c_long = 16; -pub const SYS_pread64: ::c_long = 17; -pub const SYS_pwrite64: ::c_long = 18; -pub const SYS_readv: ::c_long = 19; -pub const SYS_writev: ::c_long = 20; -pub const SYS_access: ::c_long = 21; -pub const SYS_pipe: ::c_long = 22; -pub const SYS_select: ::c_long = 23; -pub const SYS_sched_yield: ::c_long = 24; -pub const SYS_mremap: ::c_long = 25; -pub const SYS_msync: ::c_long = 26; -pub const SYS_mincore: ::c_long = 27; -pub const SYS_madvise: ::c_long = 28; -pub const SYS_shmget: ::c_long = 29; -pub const SYS_shmat: ::c_long = 30; -pub const SYS_shmctl: ::c_long = 31; -pub const SYS_dup: ::c_long = 32; -pub const SYS_dup2: ::c_long = 33; -pub const SYS_pause: ::c_long = 34; -pub const SYS_nanosleep: ::c_long = 35; -pub const SYS_getitimer: ::c_long = 36; -pub const SYS_alarm: ::c_long = 37; -pub const SYS_setitimer: ::c_long = 38; -pub const SYS_getpid: ::c_long = 39; -pub const SYS_sendfile: ::c_long = 40; -pub const SYS_socket: ::c_long = 41; -pub const SYS_connect: ::c_long = 42; -pub const SYS_accept: ::c_long = 43; -pub const SYS_sendto: ::c_long = 44; -pub const SYS_recvfrom: ::c_long = 45; -pub const SYS_sendmsg: ::c_long = 46; -pub const SYS_recvmsg: ::c_long = 47; -pub const SYS_shutdown: ::c_long = 48; -pub const SYS_bind: ::c_long = 49; -pub const SYS_listen: ::c_long = 50; -pub const SYS_getsockname: ::c_long = 51; -pub const SYS_getpeername: ::c_long = 52; -pub const SYS_socketpair: ::c_long = 53; -pub const SYS_setsockopt: ::c_long = 54; -pub const SYS_getsockopt: ::c_long = 55; -pub const SYS_clone: ::c_long = 56; -pub const SYS_fork: ::c_long = 57; -pub const SYS_vfork: ::c_long = 58; -pub const SYS_execve: ::c_long = 59; -pub const SYS_exit: ::c_long = 60; -pub const SYS_wait4: ::c_long = 61; -pub const SYS_kill: ::c_long = 62; -pub const SYS_uname: ::c_long = 63; -pub const SYS_semget: ::c_long = 64; -pub const SYS_semop: ::c_long = 65; -pub const SYS_semctl: ::c_long = 66; -pub const SYS_shmdt: ::c_long = 67; -pub const SYS_msgget: ::c_long = 68; -pub const SYS_msgsnd: ::c_long = 69; -pub const SYS_msgrcv: ::c_long = 70; -pub const SYS_msgctl: ::c_long = 71; -pub const SYS_fcntl: ::c_long = 72; -pub const SYS_flock: ::c_long = 73; -pub const SYS_fsync: ::c_long = 74; -pub const SYS_fdatasync: ::c_long = 75; -pub const SYS_truncate: ::c_long = 76; -pub const SYS_ftruncate: ::c_long = 77; -pub const SYS_getdents: ::c_long = 78; -pub const SYS_getcwd: ::c_long = 79; -pub const SYS_chdir: ::c_long = 80; -pub const SYS_fchdir: ::c_long = 81; -pub const SYS_rename: ::c_long = 82; -pub const SYS_mkdir: ::c_long = 83; -pub const SYS_rmdir: ::c_long = 84; -pub const SYS_creat: ::c_long = 85; -pub const SYS_link: ::c_long = 86; -pub const SYS_unlink: ::c_long = 87; -pub const SYS_symlink: ::c_long = 88; -pub const SYS_readlink: ::c_long = 89; -pub const SYS_chmod: ::c_long = 90; -pub const SYS_fchmod: ::c_long = 91; -pub const SYS_chown: ::c_long = 92; -pub const SYS_fchown: ::c_long = 93; -pub const SYS_lchown: ::c_long = 94; -pub const SYS_umask: ::c_long = 95; -pub const SYS_gettimeofday: ::c_long = 96; -pub const SYS_getrlimit: ::c_long = 97; -pub const SYS_getrusage: ::c_long = 98; -pub const SYS_sysinfo: ::c_long = 99; -pub const SYS_times: ::c_long = 100; -pub const SYS_ptrace: ::c_long = 101; -pub const SYS_getuid: ::c_long = 102; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_getgid: ::c_long = 104; -pub const SYS_setuid: ::c_long = 105; -pub const SYS_setgid: ::c_long = 106; -pub const SYS_geteuid: ::c_long = 107; -pub const SYS_getegid: ::c_long = 108; -pub const SYS_setpgid: ::c_long = 109; -pub const SYS_getppid: ::c_long = 110; -pub const SYS_getpgrp: ::c_long = 111; -pub const SYS_setsid: ::c_long = 112; -pub const SYS_setreuid: ::c_long = 113; -pub const SYS_setregid: ::c_long = 114; -pub const SYS_getgroups: ::c_long = 115; -pub const SYS_setgroups: ::c_long = 116; -pub const SYS_setresuid: ::c_long = 117; -pub const SYS_getresuid: ::c_long = 118; -pub const SYS_setresgid: ::c_long = 119; -pub const SYS_getresgid: ::c_long = 120; -pub const SYS_getpgid: ::c_long = 121; -pub const SYS_setfsuid: ::c_long = 122; -pub const SYS_setfsgid: ::c_long = 123; -pub const SYS_getsid: ::c_long = 124; -pub const SYS_capget: ::c_long = 125; -pub const SYS_capset: ::c_long = 126; -pub const SYS_rt_sigpending: ::c_long = 127; -pub const SYS_rt_sigtimedwait: ::c_long = 128; -pub const SYS_rt_sigqueueinfo: ::c_long = 129; -pub const SYS_rt_sigsuspend: ::c_long = 130; -pub const SYS_sigaltstack: ::c_long = 131; -pub const SYS_utime: ::c_long = 132; -pub const SYS_mknod: ::c_long = 133; -pub const SYS_uselib: ::c_long = 134; -pub const SYS_personality: ::c_long = 135; -pub const SYS_ustat: ::c_long = 136; -pub const SYS_statfs: ::c_long = 137; -pub const SYS_fstatfs: ::c_long = 138; -pub const SYS_sysfs: ::c_long = 139; -pub const SYS_getpriority: ::c_long = 140; -pub const SYS_setpriority: ::c_long = 141; -pub const SYS_sched_setparam: ::c_long = 142; -pub const SYS_sched_getparam: ::c_long = 143; -pub const SYS_sched_setscheduler: ::c_long = 144; -pub const SYS_sched_getscheduler: ::c_long = 145; -pub const SYS_sched_get_priority_max: ::c_long = 146; -pub const SYS_sched_get_priority_min: ::c_long = 147; -pub const SYS_sched_rr_get_interval: ::c_long = 148; -pub const SYS_mlock: ::c_long = 149; -pub const SYS_munlock: ::c_long = 150; -pub const SYS_mlockall: ::c_long = 151; -pub const SYS_munlockall: ::c_long = 152; -pub const SYS_vhangup: ::c_long = 153; -pub const SYS_modify_ldt: ::c_long = 154; -pub const SYS_pivot_root: ::c_long = 155; -pub const SYS__sysctl: ::c_long = 156; -pub const SYS_prctl: ::c_long = 157; -pub const SYS_arch_prctl: ::c_long = 158; -pub const SYS_adjtimex: ::c_long = 159; -pub const SYS_setrlimit: ::c_long = 160; -pub const SYS_chroot: ::c_long = 161; -pub const SYS_sync: ::c_long = 162; -pub const SYS_acct: ::c_long = 163; -pub const SYS_settimeofday: ::c_long = 164; -pub const SYS_mount: ::c_long = 165; -pub const SYS_umount2: ::c_long = 166; -pub const SYS_swapon: ::c_long = 167; -pub const SYS_swapoff: ::c_long = 168; -pub const SYS_reboot: ::c_long = 169; -pub const SYS_sethostname: ::c_long = 170; -pub const SYS_setdomainname: ::c_long = 171; -pub const SYS_iopl: ::c_long = 172; -pub const SYS_ioperm: ::c_long = 173; -pub const SYS_create_module: ::c_long = 174; -pub const SYS_init_module: ::c_long = 175; -pub const SYS_delete_module: ::c_long = 176; -pub const SYS_get_kernel_syms: ::c_long = 177; -pub const SYS_query_module: ::c_long = 178; -pub const SYS_quotactl: ::c_long = 179; -pub const SYS_nfsservctl: ::c_long = 180; -pub const SYS_getpmsg: ::c_long = 181; -pub const SYS_putpmsg: ::c_long = 182; -pub const SYS_afs_syscall: ::c_long = 183; -pub const SYS_tuxcall: ::c_long = 184; -pub const SYS_security: ::c_long = 185; -pub const SYS_gettid: ::c_long = 186; -pub const SYS_readahead: ::c_long = 187; -pub const SYS_setxattr: ::c_long = 188; -pub const SYS_lsetxattr: ::c_long = 189; -pub const SYS_fsetxattr: ::c_long = 190; -pub const SYS_getxattr: ::c_long = 191; -pub const SYS_lgetxattr: ::c_long = 192; -pub const SYS_fgetxattr: ::c_long = 193; -pub const SYS_listxattr: ::c_long = 194; -pub const SYS_llistxattr: ::c_long = 195; -pub const SYS_flistxattr: ::c_long = 196; -pub const SYS_removexattr: ::c_long = 197; -pub const SYS_lremovexattr: ::c_long = 198; -pub const SYS_fremovexattr: ::c_long = 199; -pub const SYS_tkill: ::c_long = 200; -pub const SYS_time: ::c_long = 201; -pub const SYS_futex: ::c_long = 202; -pub const SYS_sched_setaffinity: ::c_long = 203; -pub const SYS_sched_getaffinity: ::c_long = 204; -pub const SYS_set_thread_area: ::c_long = 205; -pub const SYS_io_setup: ::c_long = 206; -pub const SYS_io_destroy: ::c_long = 207; -pub const SYS_io_getevents: ::c_long = 208; -pub const SYS_io_submit: ::c_long = 209; -pub const SYS_io_cancel: ::c_long = 210; -pub const SYS_get_thread_area: ::c_long = 211; -pub const SYS_lookup_dcookie: ::c_long = 212; -pub const SYS_epoll_create: ::c_long = 213; -pub const SYS_epoll_ctl_old: ::c_long = 214; -pub const SYS_epoll_wait_old: ::c_long = 215; -pub const SYS_remap_file_pages: ::c_long = 216; -pub const SYS_getdents64: ::c_long = 217; -pub const SYS_set_tid_address: ::c_long = 218; -pub const SYS_restart_syscall: ::c_long = 219; -pub const SYS_semtimedop: ::c_long = 220; -pub const SYS_fadvise64: ::c_long = 221; -pub const SYS_timer_create: ::c_long = 222; -pub const SYS_timer_settime: ::c_long = 223; -pub const SYS_timer_gettime: ::c_long = 224; -pub const SYS_timer_getoverrun: ::c_long = 225; -pub const SYS_timer_delete: ::c_long = 226; -pub const SYS_clock_settime: ::c_long = 227; -pub const SYS_clock_gettime: ::c_long = 228; -pub const SYS_clock_getres: ::c_long = 229; -pub const SYS_clock_nanosleep: ::c_long = 230; -pub const SYS_exit_group: ::c_long = 231; -pub const SYS_epoll_wait: ::c_long = 232; -pub const SYS_epoll_ctl: ::c_long = 233; -pub const SYS_tgkill: ::c_long = 234; -pub const SYS_utimes: ::c_long = 235; -pub const SYS_vserver: ::c_long = 236; -pub const SYS_mbind: ::c_long = 237; -pub const SYS_set_mempolicy: ::c_long = 238; -pub const SYS_get_mempolicy: ::c_long = 239; -pub const SYS_mq_open: ::c_long = 240; -pub const SYS_mq_unlink: ::c_long = 241; -pub const SYS_mq_timedsend: ::c_long = 242; -pub const SYS_mq_timedreceive: ::c_long = 243; -pub const SYS_mq_notify: ::c_long = 244; -pub const SYS_mq_getsetattr: ::c_long = 245; -pub const SYS_kexec_load: ::c_long = 246; -pub const SYS_waitid: ::c_long = 247; -pub const SYS_add_key: ::c_long = 248; -pub const SYS_request_key: ::c_long = 249; -pub const SYS_keyctl: ::c_long = 250; -pub const SYS_ioprio_set: ::c_long = 251; -pub const SYS_ioprio_get: ::c_long = 252; -pub const SYS_inotify_init: ::c_long = 253; -pub const SYS_inotify_add_watch: ::c_long = 254; -pub const SYS_inotify_rm_watch: ::c_long = 255; -pub const SYS_migrate_pages: ::c_long = 256; -pub const SYS_openat: ::c_long = 257; -pub const SYS_mkdirat: ::c_long = 258; -pub const SYS_mknodat: ::c_long = 259; -pub const SYS_fchownat: ::c_long = 260; -pub const SYS_futimesat: ::c_long = 261; -pub const SYS_newfstatat: ::c_long = 262; -pub const SYS_unlinkat: ::c_long = 263; -pub const SYS_renameat: ::c_long = 264; -pub const SYS_linkat: ::c_long = 265; -pub const SYS_symlinkat: ::c_long = 266; -pub const SYS_readlinkat: ::c_long = 267; -pub const SYS_fchmodat: ::c_long = 268; -pub const SYS_faccessat: ::c_long = 269; -pub const SYS_pselect6: ::c_long = 270; -pub const SYS_ppoll: ::c_long = 271; -pub const SYS_unshare: ::c_long = 272; -pub const SYS_set_robust_list: ::c_long = 273; -pub const SYS_get_robust_list: ::c_long = 274; -pub const SYS_splice: ::c_long = 275; -pub const SYS_tee: ::c_long = 276; -pub const SYS_sync_file_range: ::c_long = 277; -pub const SYS_vmsplice: ::c_long = 278; -pub const SYS_move_pages: ::c_long = 279; -pub const SYS_utimensat: ::c_long = 280; -pub const SYS_epoll_pwait: ::c_long = 281; -pub const SYS_signalfd: ::c_long = 282; -pub const SYS_timerfd_create: ::c_long = 283; -pub const SYS_eventfd: ::c_long = 284; -pub const SYS_fallocate: ::c_long = 285; -pub const SYS_timerfd_settime: ::c_long = 286; -pub const SYS_timerfd_gettime: ::c_long = 287; -pub const SYS_accept4: ::c_long = 288; -pub const SYS_signalfd4: ::c_long = 289; -pub const SYS_eventfd2: ::c_long = 290; -pub const SYS_epoll_create1: ::c_long = 291; -pub const SYS_dup3: ::c_long = 292; -pub const SYS_pipe2: ::c_long = 293; -pub const SYS_inotify_init1: ::c_long = 294; -pub const SYS_preadv: ::c_long = 295; -pub const SYS_pwritev: ::c_long = 296; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 297; -pub const SYS_perf_event_open: ::c_long = 298; -pub const SYS_recvmmsg: ::c_long = 299; -pub const SYS_fanotify_init: ::c_long = 300; -pub const SYS_fanotify_mark: ::c_long = 301; -pub const SYS_prlimit64: ::c_long = 302; -pub const SYS_name_to_handle_at: ::c_long = 303; -pub const SYS_open_by_handle_at: ::c_long = 304; -pub const SYS_clock_adjtime: ::c_long = 305; -pub const SYS_syncfs: ::c_long = 306; -pub const SYS_sendmmsg: ::c_long = 307; -pub const SYS_setns: ::c_long = 308; -pub const SYS_getcpu: ::c_long = 309; -pub const SYS_process_vm_readv: ::c_long = 310; -pub const SYS_process_vm_writev: ::c_long = 311; -pub const SYS_kcmp: ::c_long = 312; -pub const SYS_finit_module: ::c_long = 313; -pub const SYS_sched_setattr: ::c_long = 314; -pub const SYS_sched_getattr: ::c_long = 315; -pub const SYS_renameat2: ::c_long = 316; -pub const SYS_seccomp: ::c_long = 317; -pub const SYS_getrandom: ::c_long = 318; -pub const SYS_memfd_create: ::c_long = 319; -pub const SYS_kexec_file_load: ::c_long = 320; -pub const SYS_bpf: ::c_long = 321; -pub const SYS_execveat: ::c_long = 322; -pub const SYS_userfaultfd: ::c_long = 323; -pub const SYS_membarrier: ::c_long = 324; -pub const SYS_mlock2: ::c_long = 325; -pub const SYS_copy_file_range: ::c_long = 326; -pub const SYS_preadv2: ::c_long = 327; -pub const SYS_pwritev2: ::c_long = 328; -pub const SYS_pkey_mprotect: ::c_long = 329; -pub const SYS_pkey_alloc: ::c_long = 330; -pub const SYS_pkey_free: ::c_long = 331; - -#[link(name = "util")] -extern { - pub fn sysctl(name: *mut ::c_int, - namelen: ::c_int, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *mut ::c_void, - newlen: ::size_t) - -> ::c_int; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/powerpc64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/powerpc64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/powerpc64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/powerpc64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,860 +0,0 @@ -//! PowerPC64-specific definitions for 64-bit linux-like values - -pub type c_long = i64; -pub type c_ulong = u64; -pub type c_char = u8; -pub type wchar_t = i32; -pub type nlink_t = u64; -pub type blksize_t = i64; -pub type suseconds_t = i64; -pub type __u64 = ::c_ulong; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - __pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused: [::c_long; 3], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino64_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - __pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off64_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __reserved: [::c_long; 3], - } - - pub struct statfs64 { - pub f_type: ::__fsword_t, - pub f_bsize: ::__fsword_t, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_fsid: ::fsid_t, - pub f_namelen: ::__fsword_t, - pub f_frsize: ::__fsword_t, - pub f_flags: ::__fsword_t, - pub f_spare: [::__fsword_t; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct pthread_attr_t { - __size: [u64; 7] - } - - pub struct ipc_perm { - pub __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::mode_t, - pub __seq: ::uint32_t, - __pad1: ::uint32_t, - __unused1: ::uint64_t, - __unused2: ::c_ulong, - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_segsz: ::size_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __unused4: ::c_ulong, - __unused5: ::c_ulong - } -} - -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; - -pub const TIOCGSOFTCAR: ::c_ulong = 0x5419; -pub const TIOCSSOFTCAR: ::c_ulong = 0x541A; - -pub const RLIMIT_NOFILE: ::c_int = 7; -pub const RLIMIT_NPROC: ::c_int = 6; - -pub const O_APPEND: ::c_int = 1024; -pub const O_CREAT: ::c_int = 64; -pub const O_EXCL: ::c_int = 128; -pub const O_NOCTTY: ::c_int = 256; -pub const O_NONBLOCK: ::c_int = 2048; -pub const O_SYNC: ::c_int = 1052672; -pub const O_RSYNC: ::c_int = 1052672; -pub const O_DSYNC: ::c_int = 4096; -pub const O_FSYNC: ::c_int = 0x101000; -pub const O_NOATIME: ::c_int = 0o1000000; -pub const O_PATH: ::c_int = 0o10000000; -pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; - -pub const MAP_GROWSDOWN: ::c_int = 0x0100; - -pub const EDEADLK: ::c_int = 35; -pub const ENAMETOOLONG: ::c_int = 36; -pub const ENOLCK: ::c_int = 37; -pub const ENOSYS: ::c_int = 38; -pub const ENOTEMPTY: ::c_int = 39; -pub const ELOOP: ::c_int = 40; -pub const ENOMSG: ::c_int = 42; -pub const EIDRM: ::c_int = 43; -pub const ECHRNG: ::c_int = 44; -pub const EL2NSYNC: ::c_int = 45; -pub const EL3HLT: ::c_int = 46; -pub const EL3RST: ::c_int = 47; -pub const ELNRNG: ::c_int = 48; -pub const EUNATCH: ::c_int = 49; -pub const ENOCSI: ::c_int = 50; -pub const EL2HLT: ::c_int = 51; -pub const EBADE: ::c_int = 52; -pub const EBADR: ::c_int = 53; -pub const EXFULL: ::c_int = 54; -pub const ENOANO: ::c_int = 55; -pub const EBADRQC: ::c_int = 56; -pub const EBADSLT: ::c_int = 57; -pub const EMULTIHOP: ::c_int = 72; -pub const EOVERFLOW: ::c_int = 75; -pub const ENOTUNIQ: ::c_int = 76; -pub const EBADFD: ::c_int = 77; -pub const EBADMSG: ::c_int = 74; -pub const EREMCHG: ::c_int = 78; -pub const ELIBACC: ::c_int = 79; -pub const ELIBBAD: ::c_int = 80; -pub const ELIBSCN: ::c_int = 81; -pub const ELIBMAX: ::c_int = 82; -pub const ELIBEXEC: ::c_int = 83; -pub const EILSEQ: ::c_int = 84; -pub const ERESTART: ::c_int = 85; -pub const ESTRPIPE: ::c_int = 86; -pub const EUSERS: ::c_int = 87; -pub const ENOTSOCK: ::c_int = 88; -pub const EDESTADDRREQ: ::c_int = 89; -pub const EMSGSIZE: ::c_int = 90; -pub const EPROTOTYPE: ::c_int = 91; -pub const ENOPROTOOPT: ::c_int = 92; -pub const EPROTONOSUPPORT: ::c_int = 93; -pub const ESOCKTNOSUPPORT: ::c_int = 94; -pub const EOPNOTSUPP: ::c_int = 95; -pub const EPFNOSUPPORT: ::c_int = 96; -pub const EAFNOSUPPORT: ::c_int = 97; -pub const EADDRINUSE: ::c_int = 98; -pub const EADDRNOTAVAIL: ::c_int = 99; -pub const ENETDOWN: ::c_int = 100; -pub const ENETUNREACH: ::c_int = 101; -pub const ENETRESET: ::c_int = 102; -pub const ECONNABORTED: ::c_int = 103; -pub const ECONNRESET: ::c_int = 104; -pub const ENOBUFS: ::c_int = 105; -pub const EISCONN: ::c_int = 106; -pub const ENOTCONN: ::c_int = 107; -pub const ESHUTDOWN: ::c_int = 108; -pub const ETOOMANYREFS: ::c_int = 109; -pub const ETIMEDOUT: ::c_int = 110; -pub const ECONNREFUSED: ::c_int = 111; -pub const EHOSTDOWN: ::c_int = 112; -pub const EHOSTUNREACH: ::c_int = 113; -pub const EALREADY: ::c_int = 114; -pub const EINPROGRESS: ::c_int = 115; -pub const ESTALE: ::c_int = 116; -pub const EDQUOT: ::c_int = 122; -pub const ENOMEDIUM: ::c_int = 123; -pub const EMEDIUMTYPE: ::c_int = 124; -pub const ECANCELED: ::c_int = 125; -pub const ENOKEY: ::c_int = 126; -pub const EKEYEXPIRED: ::c_int = 127; -pub const EKEYREVOKED: ::c_int = 128; -pub const EKEYREJECTED: ::c_int = 129; -pub const EOWNERDEAD: ::c_int = 130; -pub const ENOTRECOVERABLE: ::c_int = 131; -pub const EHWPOISON: ::c_int = 133; -pub const ERFKILL: ::c_int = 132; - -pub const SOL_SOCKET: ::c_int = 1; - -pub const SO_REUSEADDR: ::c_int = 2; -pub const SO_TYPE: ::c_int = 3; -pub const SO_ERROR: ::c_int = 4; -pub const SO_DONTROUTE: ::c_int = 5; -pub const SO_BROADCAST: ::c_int = 6; -pub const SO_SNDBUF: ::c_int = 7; -pub const SO_RCVBUF: ::c_int = 8; -pub const SO_SNDBUFFORCE: ::c_int = 32; -pub const SO_RCVBUFFORCE: ::c_int = 33; -pub const SO_KEEPALIVE: ::c_int = 9; -pub const SO_OOBINLINE: ::c_int = 10; -pub const SO_NO_CHECK: ::c_int = 11; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_LINGER: ::c_int = 13; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_REUSEPORT: ::c_int = 15; -pub const SO_PASSCRED: ::c_int = 20; -pub const SO_PEERCRED: ::c_int = 21; -pub const SO_RCVLOWAT: ::c_int = 16; -pub const SO_SNDLOWAT: ::c_int = 17; -pub const SO_RCVTIMEO: ::c_int = 18; -pub const SO_SNDTIMEO: ::c_int = 19; -pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22; -pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23; -pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24; -pub const SO_BINDTODEVICE: ::c_int = 25; -pub const SO_ATTACH_FILTER: ::c_int = 26; -pub const SO_DETACH_FILTER: ::c_int = 27; -pub const SO_GET_FILTER: ::c_int = SO_ATTACH_FILTER; -pub const SO_PEERNAME: ::c_int = 28; -pub const SO_TIMESTAMP: ::c_int = 29; -pub const SO_ACCEPTCONN: ::c_int = 30; -pub const SO_PEERSEC: ::c_int = 31; -pub const SO_PASSSEC: ::c_int = 34; -pub const SO_TIMESTAMPNS: ::c_int = 35; -pub const SCM_TIMESTAMPNS: ::c_int = SO_TIMESTAMPNS; -pub const SO_MARK: ::c_int = 36; -pub const SO_TIMESTAMPING: ::c_int = 37; -pub const SCM_TIMESTAMPING: ::c_int = SO_TIMESTAMPING; -pub const SO_PROTOCOL: ::c_int = 38; -pub const SO_DOMAIN: ::c_int = 39; -pub const SO_RXQ_OVFL: ::c_int = 40; -pub const SO_WIFI_STATUS: ::c_int = 41; -pub const SCM_WIFI_STATUS: ::c_int = SO_WIFI_STATUS; -pub const SO_PEEK_OFF: ::c_int = 42; -pub const SO_NOFCS: ::c_int = 43; -pub const SO_LOCK_FILTER: ::c_int = 44; -pub const SO_SELECT_ERR_QUEUE: ::c_int = 45; -pub const SO_BUSY_POLL: ::c_int = 46; -pub const SO_MAX_PACING_RATE: ::c_int = 47; -pub const SO_BPF_EXTENSIONS: ::c_int = 48; -pub const SO_INCOMING_CPU: ::c_int = 49; -pub const SO_ATTACH_BPF: ::c_int = 50; -pub const SO_DETACH_BPF: ::c_int = SO_DETACH_FILTER; - -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 0x00000004; -pub const SA_NOCLDWAIT: ::c_int = 0x00000002; - -pub const SIGCHLD: ::c_int = 17; -pub const SIGBUS: ::c_int = 7; -pub const SIGUSR1: ::c_int = 10; -pub const SIGUSR2: ::c_int = 12; -pub const SIGCONT: ::c_int = 18; -pub const SIGSTOP: ::c_int = 19; -pub const SIGTSTP: ::c_int = 20; -pub const SIGURG: ::c_int = 23; -pub const SIGIO: ::c_int = 29; -pub const SIGSYS: ::c_int = 31; -pub const SIGSTKFLT: ::c_int = 16; -pub const SIGUNUSED: ::c_int = 31; -pub const SIGPOLL: ::c_int = 29; -pub const SIGPWR: ::c_int = 30; -pub const SIG_SETMASK: ::c_int = 2; -pub const SIG_BLOCK: ::c_int = 0x000000; -pub const SIG_UNBLOCK: ::c_int = 0x01; - -pub const POLLWRNORM: ::c_short = 0x100; -pub const POLLWRBAND: ::c_short = 0x200; - -pub const O_ASYNC: ::c_int = 0x2000; -pub const O_NDELAY: ::c_int = 0x800; - -pub const PTRACE_DETACH: ::c_uint = 17; - -pub const EFD_NONBLOCK: ::c_int = 0x800; - -pub const F_GETLK: ::c_int = 5; -pub const F_GETOWN: ::c_int = 9; -pub const F_SETOWN: ::c_int = 8; -pub const F_SETLK: ::c_int = 6; -pub const F_SETLKW: ::c_int = 7; - -pub const SFD_NONBLOCK: ::c_int = 0x0800; - -pub const TIOCEXCL: ::c_ulong = 0x540C; -pub const TIOCNXCL: ::c_ulong = 0x540D; -pub const TIOCSCTTY: ::c_ulong = 0x540E; -pub const TIOCSTI: ::c_ulong = 0x5412; -pub const TIOCMGET: ::c_ulong = 0x5415; -pub const TIOCMBIS: ::c_ulong = 0x5416; -pub const TIOCMBIC: ::c_ulong = 0x5417; -pub const TIOCMSET: ::c_ulong = 0x5418; -pub const TIOCCONS: ::c_ulong = 0x541D; - -pub const SFD_CLOEXEC: ::c_int = 0x080000; - -pub const NCCS: usize = 32; - -pub const O_TRUNC: ::c_int = 512; - -pub const O_CLOEXEC: ::c_int = 0x80000; - -pub const EBFONT: ::c_int = 59; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENONET: ::c_int = 64; -pub const ENOPKG: ::c_int = 65; -pub const EREMOTE: ::c_int = 66; -pub const ENOLINK: ::c_int = 67; -pub const EADV: ::c_int = 68; -pub const ESRMNT: ::c_int = 69; -pub const ECOMM: ::c_int = 70; -pub const EPROTO: ::c_int = 71; -pub const EDOTDOT: ::c_int = 73; - -pub const SA_NODEFER: ::c_int = 0x40000000; -pub const SA_RESETHAND: ::c_int = 0x80000000; -pub const SA_RESTART: ::c_int = 0x10000000; -pub const SA_NOCLDSTOP: ::c_int = 0x00000001; - -pub const EPOLL_CLOEXEC: ::c_int = 0x80000; - -pub const EFD_CLOEXEC: ::c_int = 0x80000; - -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; - -pub const O_DIRECTORY: ::c_int = 0x4000; -pub const O_NOFOLLOW: ::c_int = 0x8000; -pub const O_DIRECT: ::c_int = 0x20000; - -pub const MAP_LOCKED: ::c_int = 0x00080; -pub const MAP_NORESERVE: ::c_int = 0x00040; - -pub const EDEADLOCK: ::c_int = 58; - -pub const FIOCLEX: ::c_ulong = 0x20006601; -pub const FIONBIO: ::c_ulong = 0x8004667e; - -pub const MCL_CURRENT: ::c_int = 0x2000; -pub const MCL_FUTURE: ::c_int = 0x4000; - -pub const SIGSTKSZ: ::size_t = 0x4000; -pub const MINSIGSTKSZ: ::size_t = 4096; -pub const CBAUD: ::tcflag_t = 0xff; -pub const TAB1: ::c_int = 0x400; -pub const TAB2: ::c_int = 0x800; -pub const TAB3: ::c_int = 0xc00; -pub const CR1: ::c_int = 0x1000; -pub const CR2: ::c_int = 0x2000; -pub const CR3: ::c_int = 0x3000; -pub const FF1: ::c_int = 0x4000; -pub const BS1: ::c_int = 0x8000; -pub const VT1: ::c_int = 0x10000; -pub const VWERASE: usize = 0xa; -pub const VREPRINT: usize = 0xb; -pub const VSUSP: usize = 0xc; -pub const VSTART: usize = 0xd; -pub const VSTOP: usize = 0xe; -pub const VDISCARD: usize = 0x10; -pub const VTIME: usize = 0x7; -pub const IXON: ::tcflag_t = 0x200; -pub const IXOFF: ::tcflag_t = 0x400; -pub const ONLCR: ::tcflag_t = 0x2; -pub const CSIZE: ::tcflag_t = 0x300; -pub const CS6: ::tcflag_t = 0x100; -pub const CS7: ::tcflag_t = 0x200; -pub const CS8: ::tcflag_t = 0x300; -pub const CSTOPB: ::tcflag_t = 0x400; -pub const CREAD: ::tcflag_t = 0x800; -pub const PARENB: ::tcflag_t = 0x1000; -pub const PARODD: ::tcflag_t = 0x2000; -pub const HUPCL: ::tcflag_t = 0x4000; -pub const CLOCAL: ::tcflag_t = 0x8000; -pub const ECHOKE: ::tcflag_t = 0x1; -pub const ECHOE: ::tcflag_t = 0x2; -pub const ECHOK: ::tcflag_t = 0x4; -pub const ECHONL: ::tcflag_t = 0x10; -pub const ECHOPRT: ::tcflag_t = 0x20; -pub const ECHOCTL: ::tcflag_t = 0x40; -pub const ISIG: ::tcflag_t = 0x80; -pub const ICANON: ::tcflag_t = 0x100; -pub const PENDIN: ::tcflag_t = 0x20000000; -pub const NOFLSH: ::tcflag_t = 0x80000000; -pub const VSWTC: usize = 9; -pub const OLCUC: ::tcflag_t = 0o000004; -pub const NLDLY: ::tcflag_t = 0o001400; -pub const CRDLY: ::tcflag_t = 0o030000; -pub const TABDLY: ::tcflag_t = 0o006000; -pub const BSDLY: ::tcflag_t = 0o100000; -pub const FFDLY: ::tcflag_t = 0o040000; -pub const VTDLY: ::tcflag_t = 0o200000; -pub const XTABS: ::tcflag_t = 0o006000; - -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const EXTA: ::speed_t = B19200; -pub const EXTB: ::speed_t = B38400; -pub const CBAUDEX: ::speed_t = 0o000020; -pub const B57600: ::speed_t = 0o0020; -pub const B115200: ::speed_t = 0o0021; -pub const B230400: ::speed_t = 0o0022; -pub const B460800: ::speed_t = 0o0023; -pub const B500000: ::speed_t = 0o0024; -pub const B576000: ::speed_t = 0o0025; -pub const B921600: ::speed_t = 0o0026; -pub const B1000000: ::speed_t = 0o0027; -pub const B1152000: ::speed_t = 0o0030; -pub const B1500000: ::speed_t = 0o0031; -pub const B2000000: ::speed_t = 0o0032; -pub const B2500000: ::speed_t = 0o0033; -pub const B3000000: ::speed_t = 0o0034; -pub const B3500000: ::speed_t = 0o0035; -pub const B4000000: ::speed_t = 0o0036; -pub const BOTHER: ::speed_t = 0o0037; - -pub const VEOL: usize = 6; -pub const VEOL2: usize = 8; -pub const VMIN: usize = 5; -pub const IEXTEN: ::tcflag_t = 0x400; -pub const TOSTOP: ::tcflag_t = 0x400000; -pub const FLUSHO: ::tcflag_t = 0x800000; -pub const EXTPROC: ::tcflag_t = 0x10000000; -pub const TCGETS: ::c_ulong = 0x403c7413; -pub const TCSETS: ::c_ulong = 0x803c7414; -pub const TCSETSW: ::c_ulong = 0x803c7415; -pub const TCSETSF: ::c_ulong = 0x803c7416; -pub const TCGETA: ::c_ulong = 0x40147417; -pub const TCSETA: ::c_ulong = 0x80147418; -pub const TCSETAW: ::c_ulong = 0x80147419; -pub const TCSETAF: ::c_ulong = 0x8014741c; -pub const TCSBRK: ::c_ulong = 0x2000741d; -pub const TCXONC: ::c_ulong = 0x2000741e; -pub const TCFLSH: ::c_ulong = 0x2000741f; -pub const TIOCINQ: ::c_ulong = 0x4004667f; -pub const TIOCGPGRP: ::c_ulong = 0x40047477; -pub const TIOCSPGRP: ::c_ulong = 0x80047476; -pub const TIOCOUTQ: ::c_ulong = 0x40047473; -pub const TIOCGWINSZ: ::c_ulong = 0x40087468; -pub const TIOCSWINSZ: ::c_ulong = 0x80087467; -pub const FIONREAD: ::c_ulong = 0x4004667f; - -// Syscall table -pub const SYS_restart_syscall: ::c_long = 0; -pub const SYS_exit: ::c_long = 1; -pub const SYS_fork: ::c_long = 2; -pub const SYS_read: ::c_long = 3; -pub const SYS_write: ::c_long = 4; -pub const SYS_open: ::c_long = 5; -pub const SYS_close: ::c_long = 6; -pub const SYS_waitpid: ::c_long = 7; -pub const SYS_creat: ::c_long = 8; -pub const SYS_link: ::c_long = 9; -pub const SYS_unlink: ::c_long = 10; -pub const SYS_execve: ::c_long = 11; -pub const SYS_chdir: ::c_long = 12; -pub const SYS_time: ::c_long = 13; -pub const SYS_mknod: ::c_long = 14; -pub const SYS_chmod: ::c_long = 15; -pub const SYS_lchown: ::c_long = 16; -pub const SYS_break: ::c_long = 17; -pub const SYS_oldstat: ::c_long = 18; -pub const SYS_lseek: ::c_long = 19; -pub const SYS_getpid: ::c_long = 20; -pub const SYS_mount: ::c_long = 21; -pub const SYS_umount: ::c_long = 22; -pub const SYS_setuid: ::c_long = 23; -pub const SYS_getuid: ::c_long = 24; -pub const SYS_stime: ::c_long = 25; -pub const SYS_ptrace: ::c_long = 26; -pub const SYS_alarm: ::c_long = 27; -pub const SYS_oldfstat: ::c_long = 28; -pub const SYS_pause: ::c_long = 29; -pub const SYS_utime: ::c_long = 30; -pub const SYS_stty: ::c_long = 31; -pub const SYS_gtty: ::c_long = 32; -pub const SYS_access: ::c_long = 33; -pub const SYS_nice: ::c_long = 34; -pub const SYS_ftime: ::c_long = 35; -pub const SYS_sync: ::c_long = 36; -pub const SYS_kill: ::c_long = 37; -pub const SYS_rename: ::c_long = 38; -pub const SYS_mkdir: ::c_long = 39; -pub const SYS_rmdir: ::c_long = 40; -pub const SYS_dup: ::c_long = 41; -pub const SYS_pipe: ::c_long = 42; -pub const SYS_times: ::c_long = 43; -pub const SYS_prof: ::c_long = 44; -pub const SYS_brk: ::c_long = 45; -pub const SYS_setgid: ::c_long = 46; -pub const SYS_getgid: ::c_long = 47; -pub const SYS_signal: ::c_long = 48; -pub const SYS_geteuid: ::c_long = 49; -pub const SYS_getegid: ::c_long = 50; -pub const SYS_acct: ::c_long = 51; -pub const SYS_umount2: ::c_long = 52; -pub const SYS_lock: ::c_long = 53; -pub const SYS_ioctl: ::c_long = 54; -pub const SYS_fcntl: ::c_long = 55; -pub const SYS_mpx: ::c_long = 56; -pub const SYS_setpgid: ::c_long = 57; -pub const SYS_ulimit: ::c_long = 58; -pub const SYS_oldolduname: ::c_long = 59; -pub const SYS_umask: ::c_long = 60; -pub const SYS_chroot: ::c_long = 61; -pub const SYS_ustat: ::c_long = 62; -pub const SYS_dup2: ::c_long = 63; -pub const SYS_getppid: ::c_long = 64; -pub const SYS_getpgrp: ::c_long = 65; -pub const SYS_setsid: ::c_long = 66; -pub const SYS_sigaction: ::c_long = 67; -pub const SYS_sgetmask: ::c_long = 68; -pub const SYS_ssetmask: ::c_long = 69; -pub const SYS_setreuid: ::c_long = 70; -pub const SYS_setregid: ::c_long = 71; -pub const SYS_sigsuspend: ::c_long = 72; -pub const SYS_sigpending: ::c_long = 73; -pub const SYS_sethostname: ::c_long = 74; -pub const SYS_setrlimit: ::c_long = 75; -pub const SYS_getrlimit: ::c_long = 76; -pub const SYS_getrusage: ::c_long = 77; -pub const SYS_gettimeofday: ::c_long = 78; -pub const SYS_settimeofday: ::c_long = 79; -pub const SYS_getgroups: ::c_long = 80; -pub const SYS_setgroups: ::c_long = 81; -pub const SYS_select: ::c_long = 82; -pub const SYS_symlink: ::c_long = 83; -pub const SYS_oldlstat: ::c_long = 84; -pub const SYS_readlink: ::c_long = 85; -pub const SYS_uselib: ::c_long = 86; -pub const SYS_swapon: ::c_long = 87; -pub const SYS_reboot: ::c_long = 88; -pub const SYS_readdir: ::c_long = 89; -pub const SYS_mmap: ::c_long = 90; -pub const SYS_munmap: ::c_long = 91; -pub const SYS_truncate: ::c_long = 92; -pub const SYS_ftruncate: ::c_long = 93; -pub const SYS_fchmod: ::c_long = 94; -pub const SYS_fchown: ::c_long = 95; -pub const SYS_getpriority: ::c_long = 96; -pub const SYS_setpriority: ::c_long = 97; -pub const SYS_profil: ::c_long = 98; -pub const SYS_statfs: ::c_long = 99; -pub const SYS_fstatfs: ::c_long = 100; -pub const SYS_ioperm: ::c_long = 101; -pub const SYS_socketcall: ::c_long = 102; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_setitimer: ::c_long = 104; -pub const SYS_getitimer: ::c_long = 105; -pub const SYS_stat: ::c_long = 106; -pub const SYS_lstat: ::c_long = 107; -pub const SYS_fstat: ::c_long = 108; -pub const SYS_olduname: ::c_long = 109; -pub const SYS_iopl: ::c_long = 110; -pub const SYS_vhangup: ::c_long = 111; -pub const SYS_idle: ::c_long = 112; -pub const SYS_vm86: ::c_long = 113; -pub const SYS_wait4: ::c_long = 114; -pub const SYS_swapoff: ::c_long = 115; -pub const SYS_sysinfo: ::c_long = 116; -pub const SYS_ipc: ::c_long = 117; -pub const SYS_fsync: ::c_long = 118; -pub const SYS_sigreturn: ::c_long = 119; -pub const SYS_clone: ::c_long = 120; -pub const SYS_setdomainname: ::c_long = 121; -pub const SYS_uname: ::c_long = 122; -pub const SYS_modify_ldt: ::c_long = 123; -pub const SYS_adjtimex: ::c_long = 124; -pub const SYS_mprotect: ::c_long = 125; -pub const SYS_sigprocmask: ::c_long = 126; -pub const SYS_create_module: ::c_long = 127; -pub const SYS_init_module: ::c_long = 128; -pub const SYS_delete_module: ::c_long = 129; -pub const SYS_get_kernel_syms: ::c_long = 130; -pub const SYS_quotactl: ::c_long = 131; -pub const SYS_getpgid: ::c_long = 132; -pub const SYS_fchdir: ::c_long = 133; -pub const SYS_bdflush: ::c_long = 134; -pub const SYS_sysfs: ::c_long = 135; -pub const SYS_personality: ::c_long = 136; -pub const SYS_afs_syscall: ::c_long = 137; /* Syscall for Andrew File System */ -pub const SYS_setfsuid: ::c_long = 138; -pub const SYS_setfsgid: ::c_long = 139; -pub const SYS__llseek: ::c_long = 140; -pub const SYS_getdents: ::c_long = 141; -pub const SYS__newselect: ::c_long = 142; -pub const SYS_flock: ::c_long = 143; -pub const SYS_msync: ::c_long = 144; -pub const SYS_readv: ::c_long = 145; -pub const SYS_writev: ::c_long = 146; -pub const SYS_getsid: ::c_long = 147; -pub const SYS_fdatasync: ::c_long = 148; -pub const SYS__sysctl: ::c_long = 149; -pub const SYS_mlock: ::c_long = 150; -pub const SYS_munlock: ::c_long = 151; -pub const SYS_mlockall: ::c_long = 152; -pub const SYS_munlockall: ::c_long = 153; -pub const SYS_sched_setparam: ::c_long = 154; -pub const SYS_sched_getparam: ::c_long = 155; -pub const SYS_sched_setscheduler: ::c_long = 156; -pub const SYS_sched_getscheduler: ::c_long = 157; -pub const SYS_sched_yield: ::c_long = 158; -pub const SYS_sched_get_priority_max: ::c_long = 159; -pub const SYS_sched_get_priority_min: ::c_long = 160; -pub const SYS_sched_rr_get_interval: ::c_long = 161; -pub const SYS_nanosleep: ::c_long = 162; -pub const SYS_mremap: ::c_long = 163; -pub const SYS_setresuid: ::c_long = 164; -pub const SYS_getresuid: ::c_long = 165; -pub const SYS_query_module: ::c_long = 166; -pub const SYS_poll: ::c_long = 167; -pub const SYS_nfsservctl: ::c_long = 168; -pub const SYS_setresgid: ::c_long = 169; -pub const SYS_getresgid: ::c_long = 170; -pub const SYS_prctl: ::c_long = 171; -pub const SYS_rt_sigreturn: ::c_long = 172; -pub const SYS_rt_sigaction: ::c_long = 173; -pub const SYS_rt_sigprocmask: ::c_long = 174; -pub const SYS_rt_sigpending: ::c_long = 175; -pub const SYS_rt_sigtimedwait: ::c_long = 176; -pub const SYS_rt_sigqueueinfo: ::c_long = 177; -pub const SYS_rt_sigsuspend: ::c_long = 178; -pub const SYS_pread64: ::c_long = 179; -pub const SYS_pwrite64: ::c_long = 180; -pub const SYS_chown: ::c_long = 181; -pub const SYS_getcwd: ::c_long = 182; -pub const SYS_capget: ::c_long = 183; -pub const SYS_capset: ::c_long = 184; -pub const SYS_sigaltstack: ::c_long = 185; -pub const SYS_sendfile: ::c_long = 186; -pub const SYS_getpmsg: ::c_long = 187; /* some people actually want streams */ -pub const SYS_putpmsg: ::c_long = 188; /* some people actually want streams */ -pub const SYS_vfork: ::c_long = 189; -pub const SYS_ugetrlimit: ::c_long = 190; /* SuS compliant getrlimit */ -pub const SYS_readahead: ::c_long = 191; -pub const SYS_pciconfig_read: ::c_long = 198; -pub const SYS_pciconfig_write: ::c_long = 199; -pub const SYS_pciconfig_iobase: ::c_long = 200; -pub const SYS_multiplexer: ::c_long = 201; -pub const SYS_getdents64: ::c_long = 202; -pub const SYS_pivot_root: ::c_long = 203; -pub const SYS_madvise: ::c_long = 205; -pub const SYS_mincore: ::c_long = 206; -pub const SYS_gettid: ::c_long = 207; -pub const SYS_tkill: ::c_long = 208; -pub const SYS_setxattr: ::c_long = 209; -pub const SYS_lsetxattr: ::c_long = 210; -pub const SYS_fsetxattr: ::c_long = 211; -pub const SYS_getxattr: ::c_long = 212; -pub const SYS_lgetxattr: ::c_long = 213; -pub const SYS_fgetxattr: ::c_long = 214; -pub const SYS_listxattr: ::c_long = 215; -pub const SYS_llistxattr: ::c_long = 216; -pub const SYS_flistxattr: ::c_long = 217; -pub const SYS_removexattr: ::c_long = 218; -pub const SYS_lremovexattr: ::c_long = 219; -pub const SYS_fremovexattr: ::c_long = 220; -pub const SYS_futex: ::c_long = 221; -pub const SYS_sched_setaffinity: ::c_long = 222; -pub const SYS_sched_getaffinity: ::c_long = 223; -pub const SYS_tuxcall: ::c_long = 225; -pub const SYS_io_setup: ::c_long = 227; -pub const SYS_io_destroy: ::c_long = 228; -pub const SYS_io_getevents: ::c_long = 229; -pub const SYS_io_submit: ::c_long = 230; -pub const SYS_io_cancel: ::c_long = 231; -pub const SYS_set_tid_address: ::c_long = 232; -pub const SYS_exit_group: ::c_long = 234; -pub const SYS_lookup_dcookie: ::c_long = 235; -pub const SYS_epoll_create: ::c_long = 236; -pub const SYS_epoll_ctl: ::c_long = 237; -pub const SYS_epoll_wait: ::c_long = 238; -pub const SYS_remap_file_pages: ::c_long = 239; -pub const SYS_timer_create: ::c_long = 240; -pub const SYS_timer_settime: ::c_long = 241; -pub const SYS_timer_gettime: ::c_long = 242; -pub const SYS_timer_getoverrun: ::c_long = 243; -pub const SYS_timer_delete: ::c_long = 244; -pub const SYS_clock_settime: ::c_long = 245; -pub const SYS_clock_gettime: ::c_long = 246; -pub const SYS_clock_getres: ::c_long = 247; -pub const SYS_clock_nanosleep: ::c_long = 248; -pub const SYS_swapcontext: ::c_long = 249; -pub const SYS_tgkill: ::c_long = 250; -pub const SYS_utimes: ::c_long = 251; -pub const SYS_statfs64: ::c_long = 252; -pub const SYS_fstatfs64: ::c_long = 253; -pub const SYS_rtas: ::c_long = 255; -pub const SYS_sys_debug_setcontext: ::c_long = 256; -pub const SYS_migrate_pages: ::c_long = 258; -pub const SYS_mbind: ::c_long = 259; -pub const SYS_get_mempolicy: ::c_long = 260; -pub const SYS_set_mempolicy: ::c_long = 261; -pub const SYS_mq_open: ::c_long = 262; -pub const SYS_mq_unlink: ::c_long = 263; -pub const SYS_mq_timedsend: ::c_long = 264; -pub const SYS_mq_timedreceive: ::c_long = 265; -pub const SYS_mq_notify: ::c_long = 266; -pub const SYS_mq_getsetattr: ::c_long = 267; -pub const SYS_kexec_load: ::c_long = 268; -pub const SYS_add_key: ::c_long = 269; -pub const SYS_request_key: ::c_long = 270; -pub const SYS_keyctl: ::c_long = 271; -pub const SYS_waitid: ::c_long = 272; -pub const SYS_ioprio_set: ::c_long = 273; -pub const SYS_ioprio_get: ::c_long = 274; -pub const SYS_inotify_init: ::c_long = 275; -pub const SYS_inotify_add_watch: ::c_long = 276; -pub const SYS_inotify_rm_watch: ::c_long = 277; -pub const SYS_spu_run: ::c_long = 278; -pub const SYS_spu_create: ::c_long = 279; -pub const SYS_pselect6: ::c_long = 280; -pub const SYS_ppoll: ::c_long = 281; -pub const SYS_unshare: ::c_long = 282; -pub const SYS_splice: ::c_long = 283; -pub const SYS_tee: ::c_long = 284; -pub const SYS_vmsplice: ::c_long = 285; -pub const SYS_openat: ::c_long = 286; -pub const SYS_mkdirat: ::c_long = 287; -pub const SYS_mknodat: ::c_long = 288; -pub const SYS_fchownat: ::c_long = 289; -pub const SYS_futimesat: ::c_long = 290; -pub const SYS_newfstatat: ::c_long = 291; -pub const SYS_unlinkat: ::c_long = 292; -pub const SYS_renameat: ::c_long = 293; -pub const SYS_linkat: ::c_long = 294; -pub const SYS_symlinkat: ::c_long = 295; -pub const SYS_readlinkat: ::c_long = 296; -pub const SYS_fchmodat: ::c_long = 297; -pub const SYS_faccessat: ::c_long = 298; -pub const SYS_get_robust_list: ::c_long = 299; -pub const SYS_set_robust_list: ::c_long = 300; -pub const SYS_move_pages: ::c_long = 301; -pub const SYS_getcpu: ::c_long = 302; -pub const SYS_epoll_pwait: ::c_long = 303; -pub const SYS_utimensat: ::c_long = 304; -pub const SYS_signalfd: ::c_long = 305; -pub const SYS_timerfd_create: ::c_long = 306; -pub const SYS_eventfd: ::c_long = 307; -pub const SYS_sync_file_range2: ::c_long = 308; -pub const SYS_fallocate: ::c_long = 309; -pub const SYS_subpage_prot: ::c_long = 310; -pub const SYS_timerfd_settime: ::c_long = 311; -pub const SYS_timerfd_gettime: ::c_long = 312; -pub const SYS_signalfd4: ::c_long = 313; -pub const SYS_eventfd2: ::c_long = 314; -pub const SYS_epoll_create1: ::c_long = 315; -pub const SYS_dup3: ::c_long = 316; -pub const SYS_pipe2: ::c_long = 317; -pub const SYS_inotify_init1: ::c_long = 318; -pub const SYS_perf_event_open: ::c_long = 319; -pub const SYS_preadv: ::c_long = 320; -pub const SYS_pwritev: ::c_long = 321; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 322; -pub const SYS_fanotify_init: ::c_long = 323; -pub const SYS_fanotify_mark: ::c_long = 324; -pub const SYS_prlimit64: ::c_long = 325; -pub const SYS_socket: ::c_long = 326; -pub const SYS_bind: ::c_long = 327; -pub const SYS_connect: ::c_long = 328; -pub const SYS_listen: ::c_long = 329; -pub const SYS_accept: ::c_long = 330; -pub const SYS_getsockname: ::c_long = 331; -pub const SYS_getpeername: ::c_long = 332; -pub const SYS_socketpair: ::c_long = 333; -pub const SYS_send: ::c_long = 334; -pub const SYS_sendto: ::c_long = 335; -pub const SYS_recv: ::c_long = 336; -pub const SYS_recvfrom: ::c_long = 337; -pub const SYS_shutdown: ::c_long = 338; -pub const SYS_setsockopt: ::c_long = 339; -pub const SYS_getsockopt: ::c_long = 340; -pub const SYS_sendmsg: ::c_long = 341; -pub const SYS_recvmsg: ::c_long = 342; -pub const SYS_recvmmsg: ::c_long = 343; -pub const SYS_accept4: ::c_long = 344; -pub const SYS_name_to_handle_at: ::c_long = 345; -pub const SYS_open_by_handle_at: ::c_long = 346; -pub const SYS_clock_adjtime: ::c_long = 347; -pub const SYS_syncfs: ::c_long = 348; -pub const SYS_sendmmsg: ::c_long = 349; -pub const SYS_setns: ::c_long = 350; -pub const SYS_process_vm_readv: ::c_long = 351; -pub const SYS_process_vm_writev: ::c_long = 352; -pub const SYS_finit_module: ::c_long = 353; -pub const SYS_kcmp: ::c_long = 354; -pub const SYS_sched_setattr: ::c_long = 355; -pub const SYS_sched_getattr: ::c_long = 356; -pub const SYS_renameat2: ::c_long = 357; -pub const SYS_seccomp: ::c_long = 358; -pub const SYS_getrandom: ::c_long = 359; -pub const SYS_memfd_create: ::c_long = 360; -pub const SYS_bpf: ::c_long = 361; -pub const SYS_execveat: ::c_long = 362; -pub const SYS_switch_endian: ::c_long = 363; -pub const SYS_userfaultfd: ::c_long = 364; -pub const SYS_membarrier: ::c_long = 365; -pub const SYS_mlock2: ::c_long = 378; -pub const SYS_copy_file_range: ::c_long = 379; -pub const SYS_preadv2: ::c_long = 380; -pub const SYS_pwritev2: ::c_long = 381; -pub const SYS_kexec_file_load: ::c_long = 382; - -#[link(name = "util")] -extern { - pub fn sysctl(name: *mut ::c_int, - namelen: ::c_int, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *mut ::c_void, - newlen: ::size_t) - -> ::c_int; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/sparc64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/sparc64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/sparc64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/sparc64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,785 +0,0 @@ -//! SPARC64-specific definitions for 64-bit linux-like values - -pub type c_long = i64; -pub type c_ulong = u64; -pub type c_char = i8; -pub type wchar_t = i32; -pub type nlink_t = u32; -pub type blksize_t = i64; -pub type suseconds_t = i32; -pub type __u64 = ::c_ulonglong; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - __pad0: u64, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad1: u64, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __unused: [::c_long; 2], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - __pad0: u64, - pub st_ino: ::ino64_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - __pad2: ::c_int, - pub st_size: ::off64_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - __reserved: [::c_long; 2], - } - - pub struct statfs64 { - pub f_type: ::__fsword_t, - pub f_bsize: ::__fsword_t, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_fsid: ::fsid_t, - pub f_namelen: ::__fsword_t, - pub f_frsize: ::__fsword_t, - pub f_flags: ::__fsword_t, - pub f_spare: [::__fsword_t; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct pthread_attr_t { - __size: [u64; 7] - } - - pub struct ipc_perm { - pub __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::mode_t, - __pad0: u16, - pub __seq: ::c_ushort, - __unused1: ::c_ulonglong, - __unused2: ::c_ulonglong, - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_segsz: ::size_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __reserved1: ::c_ulong, - __reserved2: ::c_ulong - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 19], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } -} - -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; - -pub const TIOCGSOFTCAR: ::c_ulong = 0x40047464; -pub const TIOCSSOFTCAR: ::c_ulong = 0x80047465; - -pub const RLIMIT_NOFILE: ::c_int = 6; -pub const RLIMIT_NPROC: ::c_int = 7; - -pub const O_APPEND: ::c_int = 0x8; -pub const O_CREAT: ::c_int = 0x200; -pub const O_EXCL: ::c_int = 0x800; -pub const O_NOCTTY: ::c_int = 0x8000; -pub const O_NONBLOCK: ::c_int = 0x4000; -pub const O_SYNC: ::c_int = 0x802000; -pub const O_RSYNC: ::c_int = 0x802000; -pub const O_DSYNC: ::c_int = 0x2000; -pub const O_FSYNC: ::c_int = 0x802000; -pub const O_NOATIME: ::c_int = 0x200000; -pub const O_PATH: ::c_int = 0x1000000; -pub const O_TMPFILE: ::c_int = 0o200000000 | O_DIRECTORY; - -pub const MAP_GROWSDOWN: ::c_int = 0x0200; - -pub const EDEADLK: ::c_int = 78; -pub const ENAMETOOLONG: ::c_int = 63; -pub const ENOLCK: ::c_int = 79; -pub const ENOSYS: ::c_int = 90; -pub const ENOTEMPTY: ::c_int = 66; -pub const ELOOP: ::c_int = 62; -pub const ENOMSG: ::c_int = 75; -pub const EIDRM: ::c_int = 77; -pub const ECHRNG: ::c_int = 94; -pub const EL2NSYNC: ::c_int = 95; -pub const EL3HLT: ::c_int = 96; -pub const EL3RST: ::c_int = 97; -pub const ELNRNG: ::c_int = 98; -pub const EUNATCH: ::c_int = 99; -pub const ENOCSI: ::c_int = 100; -pub const EL2HLT: ::c_int = 101; -pub const EBADE: ::c_int = 102; -pub const EBADR: ::c_int = 103; -pub const EXFULL: ::c_int = 104; -pub const ENOANO: ::c_int = 105; -pub const EBADRQC: ::c_int = 106; -pub const EBADSLT: ::c_int = 107; -pub const EMULTIHOP: ::c_int = 87; -pub const EOVERFLOW: ::c_int = 92; -pub const ENOTUNIQ: ::c_int = 115; -pub const EBADFD: ::c_int = 93; -pub const EBADMSG: ::c_int = 76; -pub const EREMCHG: ::c_int = 89; -pub const ELIBACC: ::c_int = 114; -pub const ELIBBAD: ::c_int = 112; -pub const ELIBSCN: ::c_int = 124; -pub const ELIBMAX: ::c_int = 123; -pub const ELIBEXEC: ::c_int = 110; -pub const EILSEQ: ::c_int = 122; -pub const ERESTART: ::c_int = 116; -pub const ESTRPIPE: ::c_int = 91; -pub const EUSERS: ::c_int = 68; -pub const ENOTSOCK: ::c_int = 38; -pub const EDESTADDRREQ: ::c_int = 39; -pub const EMSGSIZE: ::c_int = 40; -pub const EPROTOTYPE: ::c_int = 41; -pub const ENOPROTOOPT: ::c_int = 42; -pub const EPROTONOSUPPORT: ::c_int = 43; -pub const ESOCKTNOSUPPORT: ::c_int = 44; -pub const EOPNOTSUPP: ::c_int = 45; -pub const EPFNOSUPPORT: ::c_int = 46; -pub const EAFNOSUPPORT: ::c_int = 47; -pub const EADDRINUSE: ::c_int = 48; -pub const EADDRNOTAVAIL: ::c_int = 49; -pub const ENETDOWN: ::c_int = 50; -pub const ENETUNREACH: ::c_int = 51; -pub const ENETRESET: ::c_int = 52; -pub const ECONNABORTED: ::c_int = 53; -pub const ECONNRESET: ::c_int = 54; -pub const ENOBUFS: ::c_int = 55; -pub const EISCONN: ::c_int = 56; -pub const ENOTCONN: ::c_int = 57; -pub const ESHUTDOWN: ::c_int = 58; -pub const ETOOMANYREFS: ::c_int = 59; -pub const ETIMEDOUT: ::c_int = 60; -pub const ECONNREFUSED: ::c_int = 61; -pub const EHOSTDOWN: ::c_int = 64; -pub const EHOSTUNREACH: ::c_int = 65; -pub const EALREADY: ::c_int = 37; -pub const EINPROGRESS: ::c_int = 36; -pub const ESTALE: ::c_int = 70; -pub const EDQUOT: ::c_int = 69; -pub const ENOMEDIUM: ::c_int = 125; -pub const EMEDIUMTYPE: ::c_int = 126; -pub const ECANCELED: ::c_int = 127; -pub const ENOKEY: ::c_int = 128; -pub const EKEYEXPIRED: ::c_int = 129; -pub const EKEYREVOKED: ::c_int = 130; -pub const EKEYREJECTED: ::c_int = 131; -pub const EOWNERDEAD: ::c_int = 132; -pub const ENOTRECOVERABLE: ::c_int = 133; -pub const EHWPOISON: ::c_int = 135; -pub const ERFKILL: ::c_int = 134; - -pub const SOL_SOCKET: ::c_int = 0xffff; - -pub const SO_REUSEADDR: ::c_int = 4; -pub const SO_BINDTODEVICE: ::c_int = 0x000d; -pub const SO_TIMESTAMP: ::c_int = 0x001d; -pub const SO_MARK: ::c_int = 0x0022; -pub const SO_RXQ_OVFL: ::c_int = 0x0024; -pub const SO_PEEK_OFF: ::c_int = 0x0026; -pub const SO_BUSY_POLL: ::c_int = 0x0030; -pub const SO_TYPE: ::c_int = 0x1008; -pub const SO_ERROR: ::c_int = 0x1007; -pub const SO_DONTROUTE: ::c_int = 16; -pub const SO_BROADCAST: ::c_int = 32; -pub const SO_SNDBUF: ::c_int = 0x1001; -pub const SO_RCVBUF: ::c_int = 0x1002; -pub const SO_DOMAIN: ::c_int = 0x1029; -pub const SO_KEEPALIVE: ::c_int = 8; -pub const SO_OOBINLINE: ::c_int = 0x100; -pub const SO_LINGER: ::c_int = 128; -pub const SO_REUSEPORT: ::c_int = 0x200; -pub const SO_ACCEPTCONN: ::c_int = 0x8000; - -pub const SA_ONSTACK: ::c_int = 1; -pub const SA_SIGINFO: ::c_int = 0x200; -pub const SA_NOCLDWAIT: ::c_int = 0x100; - -pub const SIGCHLD: ::c_int = 20; -pub const SIGBUS: ::c_int = 10; -pub const SIGUSR1: ::c_int = 30; -pub const SIGUSR2: ::c_int = 31; -pub const SIGCONT: ::c_int = 19; -pub const SIGSTOP: ::c_int = 17; -pub const SIGTSTP: ::c_int = 18; -pub const SIGURG: ::c_int = 16; -pub const SIGIO: ::c_int = 23; -pub const SIGSYS: ::c_int = 12; -pub const SIGPOLL: ::c_int = 23; -pub const SIGPWR: ::c_int = 29; -pub const SIG_SETMASK: ::c_int = 4; -pub const SIG_BLOCK: ::c_int = 1; -pub const SIG_UNBLOCK: ::c_int = 2; - -pub const POLLWRNORM: ::c_short = 4; -pub const POLLWRBAND: ::c_short = 0x100; - -pub const O_ASYNC: ::c_int = 0x40; -pub const O_NDELAY: ::c_int = 0x4004; - -pub const PTRACE_DETACH: ::c_uint = 11; - -pub const EFD_NONBLOCK: ::c_int = 0x4000; - -pub const F_GETLK: ::c_int = 7; -pub const F_GETOWN: ::c_int = 5; -pub const F_SETOWN: ::c_int = 6; -pub const F_SETLK: ::c_int = 8; -pub const F_SETLKW: ::c_int = 9; - -pub const SFD_NONBLOCK: ::c_int = 0x4000; - -pub const TIOCEXCL: ::c_ulong = 0x2000740d; -pub const TIOCNXCL: ::c_ulong = 0x2000740e; -pub const TIOCSCTTY: ::c_ulong = 0x20007484; -pub const TIOCSTI: ::c_ulong = 0x80017472; -pub const TIOCMGET: ::c_ulong = 0x4004746a; -pub const TIOCMBIS: ::c_ulong = 0x8004746c; -pub const TIOCMBIC: ::c_ulong = 0x8004746b; -pub const TIOCMSET: ::c_ulong = 0x8004746d; -pub const TIOCCONS: ::c_ulong = 0x20007424; - -pub const SFD_CLOEXEC: ::c_int = 0x400000; - -pub const NCCS: usize = 17; -pub const O_TRUNC: ::c_int = 0x400; - -pub const O_CLOEXEC: ::c_int = 0x400000; - -pub const EBFONT: ::c_int = 109; -pub const ENOSTR: ::c_int = 72; -pub const ENODATA: ::c_int = 111; -pub const ETIME: ::c_int = 73; -pub const ENOSR: ::c_int = 74; -pub const ENONET: ::c_int = 80; -pub const ENOPKG: ::c_int = 113; -pub const EREMOTE: ::c_int = 71; -pub const ENOLINK: ::c_int = 82; -pub const EADV: ::c_int = 83; -pub const ESRMNT: ::c_int = 84; -pub const ECOMM: ::c_int = 85; -pub const EPROTO: ::c_int = 86; -pub const EDOTDOT: ::c_int = 88; - -pub const SA_NODEFER: ::c_int = 0x20; -pub const SA_RESETHAND: ::c_int = 0x4; -pub const SA_RESTART: ::c_int = 0x2; -pub const SA_NOCLDSTOP: ::c_int = 0x00000008; - -pub const EPOLL_CLOEXEC: ::c_int = 0x400000; - -pub const EFD_CLOEXEC: ::c_int = 0x400000; -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; - -pub const O_DIRECTORY: ::c_int = 0o200000; -pub const O_NOFOLLOW: ::c_int = 0o400000; -pub const O_DIRECT: ::c_int = 0x100000; - -pub const MAP_LOCKED: ::c_int = 0x0100; -pub const MAP_NORESERVE: ::c_int = 0x00040; - -pub const EDEADLOCK: ::c_int = 108; - -pub const SO_PEERCRED: ::c_int = 0x40; -pub const SO_RCVLOWAT: ::c_int = 0x800; -pub const SO_SNDLOWAT: ::c_int = 0x1000; -pub const SO_RCVTIMEO: ::c_int = 0x2000; -pub const SO_SNDTIMEO: ::c_int = 0x4000; - -pub const FIOCLEX: ::c_ulong = 0x20006601; -pub const FIONBIO: ::c_ulong = 0x8004667e; - -pub const MCL_CURRENT: ::c_int = 0x2000; -pub const MCL_FUTURE: ::c_int = 0x4000; - -pub const SIGSTKSZ: ::size_t = 16384; -pub const MINSIGSTKSZ: ::size_t = 4096; -pub const CBAUD: ::tcflag_t = 0x0000100f; -pub const TAB1: ::c_int = 0x800; -pub const TAB2: ::c_int = 0x1000; -pub const TAB3: ::c_int = 0x1800; -pub const CR1: ::c_int = 0x200; -pub const CR2: ::c_int = 0x400; -pub const CR3: ::c_int = 0x600; -pub const FF1: ::c_int = 0x8000; -pub const BS1: ::c_int = 0x2000; -pub const VT1: ::c_int = 0x4000; -pub const VWERASE: usize = 0xe; -pub const VREPRINT: usize = 0xc; -pub const VSUSP: usize = 0xa; -pub const VSTART: usize = 0x8; -pub const VSTOP: usize = 0x9; -pub const VDISCARD: usize = 0xd; -pub const VTIME: usize = 0x5; -pub const IXON: ::tcflag_t = 0x400; -pub const IXOFF: ::tcflag_t = 0x1000; -pub const ONLCR: ::tcflag_t = 0x4; -pub const CSIZE: ::tcflag_t = 0x30; -pub const CS6: ::tcflag_t = 0x10; -pub const CS7: ::tcflag_t = 0x20; -pub const CS8: ::tcflag_t = 0x30; -pub const CSTOPB: ::tcflag_t = 0x40; -pub const CREAD: ::tcflag_t = 0x80; -pub const PARENB: ::tcflag_t = 0x100; -pub const PARODD: ::tcflag_t = 0x200; -pub const HUPCL: ::tcflag_t = 0x400; -pub const CLOCAL: ::tcflag_t = 0x800; -pub const ECHOKE: ::tcflag_t = 0x800; -pub const ECHOE: ::tcflag_t = 0x10; -pub const ECHOK: ::tcflag_t = 0x20; -pub const ECHONL: ::tcflag_t = 0x40; -pub const ECHOPRT: ::tcflag_t = 0x400; -pub const ECHOCTL: ::tcflag_t = 0x200; -pub const ISIG: ::tcflag_t = 0x1; -pub const ICANON: ::tcflag_t = 0x2; -pub const PENDIN: ::tcflag_t = 0x4000; -pub const NOFLSH: ::tcflag_t = 0x80; -pub const CIBAUD: ::tcflag_t = 0o02003600000; -pub const CBAUDEX: ::tcflag_t = 0x00001000; -pub const VSWTC: usize = 7; -pub const OLCUC: ::tcflag_t = 0o000002; -pub const NLDLY: ::tcflag_t = 0o000400; -pub const CRDLY: ::tcflag_t = 0o003000; -pub const TABDLY: ::tcflag_t = 0o014000; -pub const BSDLY: ::tcflag_t = 0o020000; -pub const FFDLY: ::tcflag_t = 0o100000; -pub const VTDLY: ::tcflag_t = 0o040000; -pub const XTABS: ::tcflag_t = 0o014000; - -pub const VEOL: usize = 5; -pub const VEOL2: usize = 6; -pub const VMIN: usize = 4; -pub const IEXTEN: ::tcflag_t = 0x8000; -pub const TOSTOP: ::tcflag_t = 0x100; -pub const FLUSHO: ::tcflag_t = 0x2000; -pub const EXTPROC: ::tcflag_t = 0x10000; -pub const TCGETS: ::c_ulong = 0x40245408; -pub const TCSETS: ::c_ulong = 0x80245409; -pub const TCSETSW: ::c_ulong = 0x8024540a; -pub const TCSETSF: ::c_ulong = 0x8024540b; -pub const TCGETA: ::c_ulong = 0x40125401; -pub const TCSETA: ::c_ulong = 0x80125402; -pub const TCSETAW: ::c_ulong = 0x80125403; -pub const TCSETAF: ::c_ulong = 0x80125404; -pub const TCSBRK: ::c_ulong = 0x20005405; -pub const TCXONC: ::c_ulong = 0x20005406; -pub const TCFLSH: ::c_ulong = 0x20005407; -pub const TIOCINQ: ::c_ulong = 0x4004667f; -pub const TIOCGPGRP: ::c_ulong = 0x40047483; -pub const TIOCSPGRP: ::c_ulong = 0x80047482; -pub const TIOCOUTQ: ::c_ulong = 0x40047473; -pub const TIOCGWINSZ: ::c_ulong = 0x40087468; -pub const TIOCSWINSZ: ::c_ulong = 0x80087467; -pub const FIONREAD: ::c_ulong = 0x4004667f; - -pub const SYS_restart_syscall: ::c_long = 0; -pub const SYS_exit: ::c_long = 1; -pub const SYS_fork: ::c_long = 2; -pub const SYS_read: ::c_long = 3; -pub const SYS_write: ::c_long = 4; -pub const SYS_open: ::c_long = 5; -pub const SYS_close: ::c_long = 6; -pub const SYS_wait4: ::c_long = 7; -pub const SYS_creat: ::c_long = 8; -pub const SYS_link: ::c_long = 9; -pub const SYS_unlink: ::c_long = 10; -pub const SYS_execv: ::c_long = 11; -pub const SYS_chdir: ::c_long = 12; -pub const SYS_chown: ::c_long = 13; -pub const SYS_mknod: ::c_long = 14; -pub const SYS_chmod: ::c_long = 15; -pub const SYS_lchown: ::c_long = 16; -pub const SYS_brk: ::c_long = 17; -pub const SYS_perfctr: ::c_long = 18; -pub const SYS_lseek: ::c_long = 19; -pub const SYS_getpid: ::c_long = 20; -pub const SYS_capget: ::c_long = 21; -pub const SYS_capset: ::c_long = 22; -pub const SYS_setuid: ::c_long = 23; -pub const SYS_getuid: ::c_long = 24; -pub const SYS_vmsplice: ::c_long = 25; -pub const SYS_ptrace: ::c_long = 26; -pub const SYS_alarm: ::c_long = 27; -pub const SYS_sigaltstack: ::c_long = 28; -pub const SYS_pause: ::c_long = 29; -pub const SYS_utime: ::c_long = 30; -pub const SYS_access: ::c_long = 33; -pub const SYS_nice: ::c_long = 34; -pub const SYS_sync: ::c_long = 36; -pub const SYS_kill: ::c_long = 37; -pub const SYS_stat: ::c_long = 38; -pub const SYS_sendfile: ::c_long = 39; -pub const SYS_lstat: ::c_long = 40; -pub const SYS_dup: ::c_long = 41; -pub const SYS_pipe: ::c_long = 42; -pub const SYS_times: ::c_long = 43; -pub const SYS_umount2: ::c_long = 45; -pub const SYS_setgid: ::c_long = 46; -pub const SYS_getgid: ::c_long = 47; -pub const SYS_signal: ::c_long = 48; -pub const SYS_geteuid: ::c_long = 49; -pub const SYS_getegid: ::c_long = 50; -pub const SYS_acct: ::c_long = 51; -pub const SYS_memory_ordering: ::c_long = 52; -pub const SYS_ioctl: ::c_long = 54; -pub const SYS_reboot: ::c_long = 55; -pub const SYS_symlink: ::c_long = 57; -pub const SYS_readlink: ::c_long = 58; -pub const SYS_execve: ::c_long = 59; -pub const SYS_umask: ::c_long = 60; -pub const SYS_chroot: ::c_long = 61; -pub const SYS_fstat: ::c_long = 62; -pub const SYS_fstat64: ::c_long = 63; -pub const SYS_getpagesize: ::c_long = 64; -pub const SYS_msync: ::c_long = 65; -pub const SYS_vfork: ::c_long = 66; -pub const SYS_pread64: ::c_long = 67; -pub const SYS_pwrite64: ::c_long = 68; -pub const SYS_mmap: ::c_long = 71; -pub const SYS_munmap: ::c_long = 73; -pub const SYS_mprotect: ::c_long = 74; -pub const SYS_madvise: ::c_long = 75; -pub const SYS_vhangup: ::c_long = 76; -pub const SYS_mincore: ::c_long = 78; -pub const SYS_getgroups: ::c_long = 79; -pub const SYS_setgroups: ::c_long = 80; -pub const SYS_getpgrp: ::c_long = 81; -pub const SYS_setitimer: ::c_long = 83; -pub const SYS_swapon: ::c_long = 85; -pub const SYS_getitimer: ::c_long = 86; -pub const SYS_sethostname: ::c_long = 88; -pub const SYS_dup2: ::c_long = 90; -pub const SYS_fcntl: ::c_long = 92; -pub const SYS_select: ::c_long = 93; -pub const SYS_fsync: ::c_long = 95; -pub const SYS_setpriority: ::c_long = 96; -pub const SYS_socket: ::c_long = 97; -pub const SYS_connect: ::c_long = 98; -pub const SYS_accept: ::c_long = 99; -pub const SYS_getpriority: ::c_long = 100; -pub const SYS_rt_sigreturn: ::c_long = 101; -pub const SYS_rt_sigaction: ::c_long = 102; -pub const SYS_rt_sigprocmask: ::c_long = 103; -pub const SYS_rt_sigpending: ::c_long = 104; -pub const SYS_rt_sigtimedwait: ::c_long = 105; -pub const SYS_rt_sigqueueinfo: ::c_long = 106; -pub const SYS_rt_sigsuspend: ::c_long = 107; -pub const SYS_setresuid: ::c_long = 108; -pub const SYS_getresuid: ::c_long = 109; -pub const SYS_setresgid: ::c_long = 110; -pub const SYS_getresgid: ::c_long = 111; -pub const SYS_recvmsg: ::c_long = 113; -pub const SYS_sendmsg: ::c_long = 114; -pub const SYS_gettimeofday: ::c_long = 116; -pub const SYS_getrusage: ::c_long = 117; -pub const SYS_getsockopt: ::c_long = 118; -pub const SYS_getcwd: ::c_long = 119; -pub const SYS_readv: ::c_long = 120; -pub const SYS_writev: ::c_long = 121; -pub const SYS_settimeofday: ::c_long = 122; -pub const SYS_fchown: ::c_long = 123; -pub const SYS_fchmod: ::c_long = 124; -pub const SYS_recvfrom: ::c_long = 125; -pub const SYS_setreuid: ::c_long = 126; -pub const SYS_setregid: ::c_long = 127; -pub const SYS_rename: ::c_long = 128; -pub const SYS_truncate: ::c_long = 129; -pub const SYS_ftruncate: ::c_long = 130; -pub const SYS_flock: ::c_long = 131; -pub const SYS_lstat64: ::c_long = 132; -pub const SYS_sendto: ::c_long = 133; -pub const SYS_shutdown: ::c_long = 134; -pub const SYS_socketpair: ::c_long = 135; -pub const SYS_mkdir: ::c_long = 136; -pub const SYS_rmdir: ::c_long = 137; -pub const SYS_utimes: ::c_long = 138; -pub const SYS_stat64: ::c_long = 139; -pub const SYS_sendfile64: ::c_long = 140; -pub const SYS_getpeername: ::c_long = 141; -pub const SYS_futex: ::c_long = 142; -pub const SYS_gettid: ::c_long = 143; -pub const SYS_getrlimit: ::c_long = 144; -pub const SYS_setrlimit: ::c_long = 145; -pub const SYS_pivot_root: ::c_long = 146; -pub const SYS_prctl: ::c_long = 147; -pub const SYS_pciconfig_read: ::c_long = 148; -pub const SYS_pciconfig_write: ::c_long = 149; -pub const SYS_getsockname: ::c_long = 150; -pub const SYS_inotify_init: ::c_long = 151; -pub const SYS_inotify_add_watch: ::c_long = 152; -pub const SYS_poll: ::c_long = 153; -pub const SYS_getdents64: ::c_long = 154; -pub const SYS_inotify_rm_watch: ::c_long = 156; -pub const SYS_statfs: ::c_long = 157; -pub const SYS_fstatfs: ::c_long = 158; -pub const SYS_umount: ::c_long = 159; -pub const SYS_sched_set_affinity: ::c_long = 160; -pub const SYS_sched_get_affinity: ::c_long = 161; -pub const SYS_getdomainname: ::c_long = 162; -pub const SYS_setdomainname: ::c_long = 163; -pub const SYS_utrap_install: ::c_long = 164; -pub const SYS_quotactl: ::c_long = 165; -pub const SYS_set_tid_address: ::c_long = 166; -pub const SYS_mount: ::c_long = 167; -pub const SYS_ustat: ::c_long = 168; -pub const SYS_setxattr: ::c_long = 169; -pub const SYS_lsetxattr: ::c_long = 170; -pub const SYS_fsetxattr: ::c_long = 171; -pub const SYS_getxattr: ::c_long = 172; -pub const SYS_lgetxattr: ::c_long = 173; -pub const SYS_getdents: ::c_long = 174; -pub const SYS_setsid: ::c_long = 175; -pub const SYS_fchdir: ::c_long = 176; -pub const SYS_fgetxattr: ::c_long = 177; -pub const SYS_listxattr: ::c_long = 178; -pub const SYS_llistxattr: ::c_long = 179; -pub const SYS_flistxattr: ::c_long = 180; -pub const SYS_removexattr: ::c_long = 181; -pub const SYS_lremovexattr: ::c_long = 182; -pub const SYS_sigpending: ::c_long = 183; -pub const SYS_query_module: ::c_long = 184; -pub const SYS_setpgid: ::c_long = 185; -pub const SYS_fremovexattr: ::c_long = 186; -pub const SYS_tkill: ::c_long = 187; -pub const SYS_exit_group: ::c_long = 188; -pub const SYS_uname: ::c_long = 189; -pub const SYS_init_module: ::c_long = 190; -pub const SYS_personality: ::c_long = 191; -pub const SYS_remap_file_pages: ::c_long = 192; -pub const SYS_epoll_create: ::c_long = 193; -pub const SYS_epoll_ctl: ::c_long = 194; -pub const SYS_epoll_wait: ::c_long = 195; -pub const SYS_ioprio_set: ::c_long = 196; -pub const SYS_getppid: ::c_long = 197; -pub const SYS_sigaction: ::c_long = 198; -pub const SYS_sgetmask: ::c_long = 199; -pub const SYS_ssetmask: ::c_long = 200; -pub const SYS_sigsuspend: ::c_long = 201; -pub const SYS_oldlstat: ::c_long = 202; -pub const SYS_uselib: ::c_long = 203; -pub const SYS_readdir: ::c_long = 204; -pub const SYS_readahead: ::c_long = 205; -pub const SYS_socketcall: ::c_long = 206; -pub const SYS_syslog: ::c_long = 207; -pub const SYS_lookup_dcookie: ::c_long = 208; -pub const SYS_fadvise64: ::c_long = 209; -pub const SYS_fadvise64_64: ::c_long = 210; -pub const SYS_tgkill: ::c_long = 211; -pub const SYS_waitpid: ::c_long = 212; -pub const SYS_swapoff: ::c_long = 213; -pub const SYS_sysinfo: ::c_long = 214; -pub const SYS_ipc: ::c_long = 215; -pub const SYS_sigreturn: ::c_long = 216; -pub const SYS_clone: ::c_long = 217; -pub const SYS_ioprio_get: ::c_long = 218; -pub const SYS_adjtimex: ::c_long = 219; -pub const SYS_sigprocmask: ::c_long = 220; -pub const SYS_create_module: ::c_long = 221; -pub const SYS_delete_module: ::c_long = 222; -pub const SYS_get_kernel_syms: ::c_long = 223; -pub const SYS_getpgid: ::c_long = 224; -pub const SYS_bdflush: ::c_long = 225; -pub const SYS_sysfs: ::c_long = 226; -pub const SYS_afs_syscall: ::c_long = 227; -pub const SYS_setfsuid: ::c_long = 228; -pub const SYS_setfsgid: ::c_long = 229; -pub const SYS__newselect: ::c_long = 230; -pub const SYS_splice: ::c_long = 232; -pub const SYS_stime: ::c_long = 233; -pub const SYS_statfs64: ::c_long = 234; -pub const SYS_fstatfs64: ::c_long = 235; -pub const SYS__llseek: ::c_long = 236; -pub const SYS_mlock: ::c_long = 237; -pub const SYS_munlock: ::c_long = 238; -pub const SYS_mlockall: ::c_long = 239; -pub const SYS_munlockall: ::c_long = 240; -pub const SYS_sched_setparam: ::c_long = 241; -pub const SYS_sched_getparam: ::c_long = 242; -pub const SYS_sched_setscheduler: ::c_long =243; -pub const SYS_sched_getscheduler: ::c_long =244; -pub const SYS_sched_yield: ::c_long = 245; -pub const SYS_sched_get_priority_max: ::c_long =246; -pub const SYS_sched_get_priority_min: ::c_long =247; -pub const SYS_sched_rr_get_interval: ::c_long = 248; -pub const SYS_nanosleep: ::c_long = 249; -pub const SYS_mremap: ::c_long = 250; -pub const SYS__sysctl: ::c_long = 251; -pub const SYS_getsid: ::c_long = 252; -pub const SYS_fdatasync: ::c_long = 253; -pub const SYS_nfsservctl: ::c_long = 254; -pub const SYS_sync_file_range: ::c_long = 255; -pub const SYS_clock_settime: ::c_long = 256; -pub const SYS_clock_gettime: ::c_long = 257; -pub const SYS_clock_getres: ::c_long = 258; -pub const SYS_clock_nanosleep: ::c_long = 259; -pub const SYS_sched_getaffinity: ::c_long = 260; -pub const SYS_sched_setaffinity: ::c_long = 261; -pub const SYS_timer_settime: ::c_long = 262; -pub const SYS_timer_gettime: ::c_long = 263; -pub const SYS_timer_getoverrun: ::c_long = 264; -pub const SYS_timer_delete: ::c_long = 265; -pub const SYS_timer_create: ::c_long = 266; -pub const SYS_io_setup: ::c_long = 268; -pub const SYS_io_destroy: ::c_long = 269; -pub const SYS_io_submit: ::c_long = 270; -pub const SYS_io_cancel: ::c_long = 271; -pub const SYS_io_getevents: ::c_long = 272; -pub const SYS_mq_open: ::c_long = 273; -pub const SYS_mq_unlink: ::c_long = 274; -pub const SYS_mq_timedsend: ::c_long = 275; -pub const SYS_mq_timedreceive: ::c_long = 276; -pub const SYS_mq_notify: ::c_long = 277; -pub const SYS_mq_getsetattr: ::c_long = 278; -pub const SYS_waitid: ::c_long = 279; -pub const SYS_tee: ::c_long = 280; -pub const SYS_add_key: ::c_long = 281; -pub const SYS_request_key: ::c_long = 282; -pub const SYS_keyctl: ::c_long = 283; -pub const SYS_openat: ::c_long = 284; -pub const SYS_mkdirat: ::c_long = 285; -pub const SYS_mknodat: ::c_long = 286; -pub const SYS_fchownat: ::c_long = 287; -pub const SYS_futimesat: ::c_long = 288; -pub const SYS_fstatat64: ::c_long = 289; -pub const SYS_unlinkat: ::c_long = 290; -pub const SYS_renameat: ::c_long = 291; -pub const SYS_linkat: ::c_long = 292; -pub const SYS_symlinkat: ::c_long = 293; -pub const SYS_readlinkat: ::c_long = 294; -pub const SYS_fchmodat: ::c_long = 295; -pub const SYS_faccessat: ::c_long = 296; -pub const SYS_pselect6: ::c_long = 297; -pub const SYS_ppoll: ::c_long = 298; -pub const SYS_unshare: ::c_long = 299; -pub const SYS_set_robust_list: ::c_long = 300; -pub const SYS_get_robust_list: ::c_long = 301; -pub const SYS_migrate_pages: ::c_long =302; -pub const SYS_mbind: ::c_long = 303; -pub const SYS_get_mempolicy: ::c_long = 304; -pub const SYS_set_mempolicy: ::c_long = 305; -pub const SYS_kexec_load: ::c_long = 306; -pub const SYS_move_pages: ::c_long = 307; -pub const SYS_getcpu: ::c_long = 308; -pub const SYS_epoll_pwait: ::c_long = 309; -pub const SYS_utimensat: ::c_long = 310; -pub const SYS_signalfd: ::c_long = 311; -pub const SYS_timerfd_create: ::c_long = 312; -pub const SYS_eventfd: ::c_long = 313; -pub const SYS_fallocate: ::c_long = 314; -pub const SYS_timerfd_settime: ::c_long = 315; -pub const SYS_timerfd_gettime: ::c_long = 316; -pub const SYS_signalfd4: ::c_long = 317; -pub const SYS_eventfd2: ::c_long = 318; -pub const SYS_epoll_create1: ::c_long = 319; -pub const SYS_dup3: ::c_long = 320; -pub const SYS_pipe2: ::c_long = 321; -pub const SYS_inotify_init1: ::c_long = 322; -pub const SYS_accept4: ::c_long = 323; -pub const SYS_preadv: ::c_long = 324; -pub const SYS_pwritev: ::c_long = 325; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 326; -pub const SYS_perf_event_open: ::c_long = 327; -pub const SYS_recvmmsg: ::c_long = 328; -pub const SYS_fanotify_init: ::c_long = 329; -pub const SYS_fanotify_mark: ::c_long = 330; -pub const SYS_prlimit64: ::c_long = 331; -pub const SYS_name_to_handle_at: ::c_long = 332; -pub const SYS_open_by_handle_at: ::c_long = 333; -pub const SYS_clock_adjtime: ::c_long = 334; -pub const SYS_syncfs: ::c_long = 335; -pub const SYS_sendmmsg: ::c_long = 336; -pub const SYS_setns: ::c_long = 337; -pub const SYS_process_vm_readv: ::c_long = 338; -pub const SYS_process_vm_writev: ::c_long = 339; -pub const SYS_kern_features: ::c_long = 340; -pub const SYS_kcmp: ::c_long = 341; -pub const SYS_finit_module: ::c_long = 342; -pub const SYS_sched_setattr: ::c_long = 343; -pub const SYS_sched_getattr: ::c_long = 344; -pub const SYS_renameat2: ::c_long = 345; -pub const SYS_seccomp: ::c_long = 346; -pub const SYS_getrandom: ::c_long = 347; -pub const SYS_memfd_create: ::c_long = 348; -pub const SYS_bpf: ::c_long = 349; -pub const SYS_execveat: ::c_long = 350; -pub const SYS_membarrier: ::c_long = 351; -pub const SYS_userfaultfd: ::c_long = 352; -pub const SYS_bind: ::c_long = 353; -pub const SYS_listen: ::c_long = 354; -pub const SYS_setsockopt: ::c_long = 355; -pub const SYS_mlock2: ::c_long = 356; -pub const SYS_copy_file_range: ::c_long = 357; -pub const SYS_preadv2: ::c_long = 358; -pub const SYS_pwritev2: ::c_long = 359; - -#[link(name = "util")] -extern { - pub fn sysctl(name: *mut ::c_int, - namelen: ::c_int, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *mut ::c_void, - newlen: ::size_t) - -> ::c_int; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/x32.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/x32.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/x32.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/x32.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,331 +0,0 @@ -pub type c_long = i32; -pub type c_ulong = u32; - -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 32; -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 44; - -// Syscall table - -pub const __X32_SYSCALL_BIT: ::c_long = 0x40000000; - -pub const SYS_read: ::c_long = __X32_SYSCALL_BIT + 0; -pub const SYS_write: ::c_long = __X32_SYSCALL_BIT + 1; -pub const SYS_open: ::c_long = __X32_SYSCALL_BIT + 2; -pub const SYS_close: ::c_long = __X32_SYSCALL_BIT + 3; -pub const SYS_stat: ::c_long = __X32_SYSCALL_BIT + 4; -pub const SYS_fstat: ::c_long = __X32_SYSCALL_BIT + 5; -pub const SYS_lstat: ::c_long = __X32_SYSCALL_BIT + 6; -pub const SYS_poll: ::c_long = __X32_SYSCALL_BIT + 7; -pub const SYS_lseek: ::c_long = __X32_SYSCALL_BIT + 8; -pub const SYS_mmap: ::c_long = __X32_SYSCALL_BIT + 9; -pub const SYS_mprotect: ::c_long = __X32_SYSCALL_BIT + 10; -pub const SYS_munmap: ::c_long = __X32_SYSCALL_BIT + 11; -pub const SYS_brk: ::c_long = __X32_SYSCALL_BIT + 12; -pub const SYS_rt_sigprocmask: ::c_long = __X32_SYSCALL_BIT + 14; -pub const SYS_pread64: ::c_long = __X32_SYSCALL_BIT + 17; -pub const SYS_pwrite64: ::c_long = __X32_SYSCALL_BIT + 18; -pub const SYS_access: ::c_long = __X32_SYSCALL_BIT + 21; -pub const SYS_pipe: ::c_long = __X32_SYSCALL_BIT + 22; -pub const SYS_select: ::c_long = __X32_SYSCALL_BIT + 23; -pub const SYS_sched_yield: ::c_long = __X32_SYSCALL_BIT + 24; -pub const SYS_mremap: ::c_long = __X32_SYSCALL_BIT + 25; -pub const SYS_msync: ::c_long = __X32_SYSCALL_BIT + 26; -pub const SYS_mincore: ::c_long = __X32_SYSCALL_BIT + 27; -pub const SYS_madvise: ::c_long = __X32_SYSCALL_BIT + 28; -pub const SYS_shmget: ::c_long = __X32_SYSCALL_BIT + 29; -pub const SYS_shmat: ::c_long = __X32_SYSCALL_BIT + 30; -pub const SYS_shmctl: ::c_long = __X32_SYSCALL_BIT + 31; -pub const SYS_dup: ::c_long = __X32_SYSCALL_BIT + 32; -pub const SYS_dup2: ::c_long = __X32_SYSCALL_BIT + 33; -pub const SYS_pause: ::c_long = __X32_SYSCALL_BIT + 34; -pub const SYS_nanosleep: ::c_long = __X32_SYSCALL_BIT + 35; -pub const SYS_getitimer: ::c_long = __X32_SYSCALL_BIT + 36; -pub const SYS_alarm: ::c_long = __X32_SYSCALL_BIT + 37; -pub const SYS_setitimer: ::c_long = __X32_SYSCALL_BIT + 38; -pub const SYS_getpid: ::c_long = __X32_SYSCALL_BIT + 39; -pub const SYS_sendfile: ::c_long = __X32_SYSCALL_BIT + 40; -pub const SYS_socket: ::c_long = __X32_SYSCALL_BIT + 41; -pub const SYS_connect: ::c_long = __X32_SYSCALL_BIT + 42; -pub const SYS_accept: ::c_long = __X32_SYSCALL_BIT + 43; -pub const SYS_sendto: ::c_long = __X32_SYSCALL_BIT + 44; -pub const SYS_shutdown: ::c_long = __X32_SYSCALL_BIT + 48; -pub const SYS_bind: ::c_long = __X32_SYSCALL_BIT + 49; -pub const SYS_listen: ::c_long = __X32_SYSCALL_BIT + 50; -pub const SYS_getsockname: ::c_long = __X32_SYSCALL_BIT + 51; -pub const SYS_getpeername: ::c_long = __X32_SYSCALL_BIT + 52; -pub const SYS_socketpair: ::c_long = __X32_SYSCALL_BIT + 53; -pub const SYS_clone: ::c_long = __X32_SYSCALL_BIT + 56; -pub const SYS_fork: ::c_long = __X32_SYSCALL_BIT + 57; -pub const SYS_vfork: ::c_long = __X32_SYSCALL_BIT + 58; -pub const SYS_exit: ::c_long = __X32_SYSCALL_BIT + 60; -pub const SYS_wait4: ::c_long = __X32_SYSCALL_BIT + 61; -pub const SYS_kill: ::c_long = __X32_SYSCALL_BIT + 62; -pub const SYS_uname: ::c_long = __X32_SYSCALL_BIT + 63; -pub const SYS_semget: ::c_long = __X32_SYSCALL_BIT + 64; -pub const SYS_semop: ::c_long = __X32_SYSCALL_BIT + 65; -pub const SYS_semctl: ::c_long = __X32_SYSCALL_BIT + 66; -pub const SYS_shmdt: ::c_long = __X32_SYSCALL_BIT + 67; -pub const SYS_msgget: ::c_long = __X32_SYSCALL_BIT + 68; -pub const SYS_msgsnd: ::c_long = __X32_SYSCALL_BIT + 69; -pub const SYS_msgrcv: ::c_long = __X32_SYSCALL_BIT + 70; -pub const SYS_msgctl: ::c_long = __X32_SYSCALL_BIT + 71; -pub const SYS_fcntl: ::c_long = __X32_SYSCALL_BIT + 72; -pub const SYS_flock: ::c_long = __X32_SYSCALL_BIT + 73; -pub const SYS_fsync: ::c_long = __X32_SYSCALL_BIT + 74; -pub const SYS_fdatasync: ::c_long = __X32_SYSCALL_BIT + 75; -pub const SYS_truncate: ::c_long = __X32_SYSCALL_BIT + 76; -pub const SYS_ftruncate: ::c_long = __X32_SYSCALL_BIT + 77; -pub const SYS_getdents: ::c_long = __X32_SYSCALL_BIT + 78; -pub const SYS_getcwd: ::c_long = __X32_SYSCALL_BIT + 79; -pub const SYS_chdir: ::c_long = __X32_SYSCALL_BIT + 80; -pub const SYS_fchdir: ::c_long = __X32_SYSCALL_BIT + 81; -pub const SYS_rename: ::c_long = __X32_SYSCALL_BIT + 82; -pub const SYS_mkdir: ::c_long = __X32_SYSCALL_BIT + 83; -pub const SYS_rmdir: ::c_long = __X32_SYSCALL_BIT + 84; -pub const SYS_creat: ::c_long = __X32_SYSCALL_BIT + 85; -pub const SYS_link: ::c_long = __X32_SYSCALL_BIT + 86; -pub const SYS_unlink: ::c_long = __X32_SYSCALL_BIT + 87; -pub const SYS_symlink: ::c_long = __X32_SYSCALL_BIT + 88; -pub const SYS_readlink: ::c_long = __X32_SYSCALL_BIT + 89; -pub const SYS_chmod: ::c_long = __X32_SYSCALL_BIT + 90; -pub const SYS_fchmod: ::c_long = __X32_SYSCALL_BIT + 91; -pub const SYS_chown: ::c_long = __X32_SYSCALL_BIT + 92; -pub const SYS_fchown: ::c_long = __X32_SYSCALL_BIT + 93; -pub const SYS_lchown: ::c_long = __X32_SYSCALL_BIT + 94; -pub const SYS_umask: ::c_long = __X32_SYSCALL_BIT + 95; -pub const SYS_gettimeofday: ::c_long = __X32_SYSCALL_BIT + 96; -pub const SYS_getrlimit: ::c_long = __X32_SYSCALL_BIT + 97; -pub const SYS_getrusage: ::c_long = __X32_SYSCALL_BIT + 98; -pub const SYS_sysinfo: ::c_long = __X32_SYSCALL_BIT + 99; -pub const SYS_times: ::c_long = __X32_SYSCALL_BIT + 100; -pub const SYS_getuid: ::c_long = __X32_SYSCALL_BIT + 102; -pub const SYS_syslog: ::c_long = __X32_SYSCALL_BIT + 103; -pub const SYS_getgid: ::c_long = __X32_SYSCALL_BIT + 104; -pub const SYS_setuid: ::c_long = __X32_SYSCALL_BIT + 105; -pub const SYS_setgid: ::c_long = __X32_SYSCALL_BIT + 106; -pub const SYS_geteuid: ::c_long = __X32_SYSCALL_BIT + 107; -pub const SYS_getegid: ::c_long = __X32_SYSCALL_BIT + 108; -pub const SYS_setpgid: ::c_long = __X32_SYSCALL_BIT + 109; -pub const SYS_getppid: ::c_long = __X32_SYSCALL_BIT + 110; -pub const SYS_getpgrp: ::c_long = __X32_SYSCALL_BIT + 111; -pub const SYS_setsid: ::c_long = __X32_SYSCALL_BIT + 112; -pub const SYS_setreuid: ::c_long = __X32_SYSCALL_BIT + 113; -pub const SYS_setregid: ::c_long = __X32_SYSCALL_BIT + 114; -pub const SYS_getgroups: ::c_long = __X32_SYSCALL_BIT + 115; -pub const SYS_setgroups: ::c_long = __X32_SYSCALL_BIT + 116; -pub const SYS_setresuid: ::c_long = __X32_SYSCALL_BIT + 117; -pub const SYS_getresuid: ::c_long = __X32_SYSCALL_BIT + 118; -pub const SYS_setresgid: ::c_long = __X32_SYSCALL_BIT + 119; -pub const SYS_getresgid: ::c_long = __X32_SYSCALL_BIT + 120; -pub const SYS_getpgid: ::c_long = __X32_SYSCALL_BIT + 121; -pub const SYS_setfsuid: ::c_long = __X32_SYSCALL_BIT + 122; -pub const SYS_setfsgid: ::c_long = __X32_SYSCALL_BIT + 123; -pub const SYS_getsid: ::c_long = __X32_SYSCALL_BIT + 124; -pub const SYS_capget: ::c_long = __X32_SYSCALL_BIT + 125; -pub const SYS_capset: ::c_long = __X32_SYSCALL_BIT + 126; -pub const SYS_rt_sigsuspend: ::c_long = __X32_SYSCALL_BIT + 130; -pub const SYS_utime: ::c_long = __X32_SYSCALL_BIT + 132; -pub const SYS_mknod: ::c_long = __X32_SYSCALL_BIT + 133; -pub const SYS_personality: ::c_long = __X32_SYSCALL_BIT + 135; -pub const SYS_ustat: ::c_long = __X32_SYSCALL_BIT + 136; -pub const SYS_statfs: ::c_long = __X32_SYSCALL_BIT + 137; -pub const SYS_fstatfs: ::c_long = __X32_SYSCALL_BIT + 138; -pub const SYS_sysfs: ::c_long = __X32_SYSCALL_BIT + 139; -pub const SYS_getpriority: ::c_long = __X32_SYSCALL_BIT + 140; -pub const SYS_setpriority: ::c_long = __X32_SYSCALL_BIT + 141; -pub const SYS_sched_setparam: ::c_long = __X32_SYSCALL_BIT + 142; -pub const SYS_sched_getparam: ::c_long = __X32_SYSCALL_BIT + 143; -pub const SYS_sched_setscheduler: ::c_long = __X32_SYSCALL_BIT + 144; -pub const SYS_sched_getscheduler: ::c_long = __X32_SYSCALL_BIT + 145; -pub const SYS_sched_get_priority_max: ::c_long = __X32_SYSCALL_BIT + 146; -pub const SYS_sched_get_priority_min: ::c_long = __X32_SYSCALL_BIT + 147; -pub const SYS_sched_rr_get_interval: ::c_long = __X32_SYSCALL_BIT + 148; -pub const SYS_mlock: ::c_long = __X32_SYSCALL_BIT + 149; -pub const SYS_munlock: ::c_long = __X32_SYSCALL_BIT + 150; -pub const SYS_mlockall: ::c_long = __X32_SYSCALL_BIT + 151; -pub const SYS_munlockall: ::c_long = __X32_SYSCALL_BIT + 152; -pub const SYS_vhangup: ::c_long = __X32_SYSCALL_BIT + 153; -pub const SYS_modify_ldt: ::c_long = __X32_SYSCALL_BIT + 154; -pub const SYS_pivot_root: ::c_long = __X32_SYSCALL_BIT + 155; -pub const SYS_prctl: ::c_long = __X32_SYSCALL_BIT + 157; -pub const SYS_arch_prctl: ::c_long = __X32_SYSCALL_BIT + 158; -pub const SYS_adjtimex: ::c_long = __X32_SYSCALL_BIT + 159; -pub const SYS_setrlimit: ::c_long = __X32_SYSCALL_BIT + 160; -pub const SYS_chroot: ::c_long = __X32_SYSCALL_BIT + 161; -pub const SYS_sync: ::c_long = __X32_SYSCALL_BIT + 162; -pub const SYS_acct: ::c_long = __X32_SYSCALL_BIT + 163; -pub const SYS_settimeofday: ::c_long = __X32_SYSCALL_BIT + 164; -pub const SYS_mount: ::c_long = __X32_SYSCALL_BIT + 165; -pub const SYS_umount2: ::c_long = __X32_SYSCALL_BIT + 166; -pub const SYS_swapon: ::c_long = __X32_SYSCALL_BIT + 167; -pub const SYS_swapoff: ::c_long = __X32_SYSCALL_BIT + 168; -pub const SYS_reboot: ::c_long = __X32_SYSCALL_BIT + 169; -pub const SYS_sethostname: ::c_long = __X32_SYSCALL_BIT + 170; -pub const SYS_setdomainname: ::c_long = __X32_SYSCALL_BIT + 171; -pub const SYS_iopl: ::c_long = __X32_SYSCALL_BIT + 172; -pub const SYS_ioperm: ::c_long = __X32_SYSCALL_BIT + 173; -pub const SYS_init_module: ::c_long = __X32_SYSCALL_BIT + 175; -pub const SYS_delete_module: ::c_long = __X32_SYSCALL_BIT + 176; -pub const SYS_quotactl: ::c_long = __X32_SYSCALL_BIT + 179; -pub const SYS_getpmsg: ::c_long = __X32_SYSCALL_BIT + 181; -pub const SYS_putpmsg: ::c_long = __X32_SYSCALL_BIT + 182; -pub const SYS_afs_syscall: ::c_long = __X32_SYSCALL_BIT + 183; -pub const SYS_tuxcall: ::c_long = __X32_SYSCALL_BIT + 184; -pub const SYS_security: ::c_long = __X32_SYSCALL_BIT + 185; -pub const SYS_gettid: ::c_long = __X32_SYSCALL_BIT + 186; -pub const SYS_readahead: ::c_long = __X32_SYSCALL_BIT + 187; -pub const SYS_setxattr: ::c_long = __X32_SYSCALL_BIT + 188; -pub const SYS_lsetxattr: ::c_long = __X32_SYSCALL_BIT + 189; -pub const SYS_fsetxattr: ::c_long = __X32_SYSCALL_BIT + 190; -pub const SYS_getxattr: ::c_long = __X32_SYSCALL_BIT + 191; -pub const SYS_lgetxattr: ::c_long = __X32_SYSCALL_BIT + 192; -pub const SYS_fgetxattr: ::c_long = __X32_SYSCALL_BIT + 193; -pub const SYS_listxattr: ::c_long = __X32_SYSCALL_BIT + 194; -pub const SYS_llistxattr: ::c_long = __X32_SYSCALL_BIT + 195; -pub const SYS_flistxattr: ::c_long = __X32_SYSCALL_BIT + 196; -pub const SYS_removexattr: ::c_long = __X32_SYSCALL_BIT + 197; -pub const SYS_lremovexattr: ::c_long = __X32_SYSCALL_BIT + 198; -pub const SYS_fremovexattr: ::c_long = __X32_SYSCALL_BIT + 199; -pub const SYS_tkill: ::c_long = __X32_SYSCALL_BIT + 200; -pub const SYS_time: ::c_long = __X32_SYSCALL_BIT + 201; -pub const SYS_futex: ::c_long = __X32_SYSCALL_BIT + 202; -pub const SYS_sched_setaffinity: ::c_long = __X32_SYSCALL_BIT + 203; -pub const SYS_sched_getaffinity: ::c_long = __X32_SYSCALL_BIT + 204; -pub const SYS_io_destroy: ::c_long = __X32_SYSCALL_BIT + 207; -pub const SYS_io_getevents: ::c_long = __X32_SYSCALL_BIT + 208; -pub const SYS_io_cancel: ::c_long = __X32_SYSCALL_BIT + 210; -pub const SYS_lookup_dcookie: ::c_long = __X32_SYSCALL_BIT + 212; -pub const SYS_epoll_create: ::c_long = __X32_SYSCALL_BIT + 213; -pub const SYS_remap_file_pages: ::c_long = __X32_SYSCALL_BIT + 216; -pub const SYS_getdents64: ::c_long = __X32_SYSCALL_BIT + 217; -pub const SYS_set_tid_address: ::c_long = __X32_SYSCALL_BIT + 218; -pub const SYS_restart_syscall: ::c_long = __X32_SYSCALL_BIT + 219; -pub const SYS_semtimedop: ::c_long = __X32_SYSCALL_BIT + 220; -pub const SYS_fadvise64: ::c_long = __X32_SYSCALL_BIT + 221; -pub const SYS_timer_settime: ::c_long = __X32_SYSCALL_BIT + 223; -pub const SYS_timer_gettime: ::c_long = __X32_SYSCALL_BIT + 224; -pub const SYS_timer_getoverrun: ::c_long = __X32_SYSCALL_BIT + 225; -pub const SYS_timer_delete: ::c_long = __X32_SYSCALL_BIT + 226; -pub const SYS_clock_settime: ::c_long = __X32_SYSCALL_BIT + 227; -pub const SYS_clock_gettime: ::c_long = __X32_SYSCALL_BIT + 228; -pub const SYS_clock_getres: ::c_long = __X32_SYSCALL_BIT + 229; -pub const SYS_clock_nanosleep: ::c_long = __X32_SYSCALL_BIT + 230; -pub const SYS_exit_group: ::c_long = __X32_SYSCALL_BIT + 231; -pub const SYS_epoll_wait: ::c_long = __X32_SYSCALL_BIT + 232; -pub const SYS_epoll_ctl: ::c_long = __X32_SYSCALL_BIT + 233; -pub const SYS_tgkill: ::c_long = __X32_SYSCALL_BIT + 234; -pub const SYS_utimes: ::c_long = __X32_SYSCALL_BIT + 235; -pub const SYS_mbind: ::c_long = __X32_SYSCALL_BIT + 237; -pub const SYS_set_mempolicy: ::c_long = __X32_SYSCALL_BIT + 238; -pub const SYS_get_mempolicy: ::c_long = __X32_SYSCALL_BIT + 239; -pub const SYS_mq_open: ::c_long = __X32_SYSCALL_BIT + 240; -pub const SYS_mq_unlink: ::c_long = __X32_SYSCALL_BIT + 241; -pub const SYS_mq_timedsend: ::c_long = __X32_SYSCALL_BIT + 242; -pub const SYS_mq_timedreceive: ::c_long = __X32_SYSCALL_BIT + 243; -pub const SYS_mq_getsetattr: ::c_long = __X32_SYSCALL_BIT + 245; -pub const SYS_add_key: ::c_long = __X32_SYSCALL_BIT + 248; -pub const SYS_request_key: ::c_long = __X32_SYSCALL_BIT + 249; -pub const SYS_keyctl: ::c_long = __X32_SYSCALL_BIT + 250; -pub const SYS_ioprio_set: ::c_long = __X32_SYSCALL_BIT + 251; -pub const SYS_ioprio_get: ::c_long = __X32_SYSCALL_BIT + 252; -pub const SYS_inotify_init: ::c_long = __X32_SYSCALL_BIT + 253; -pub const SYS_inotify_add_watch: ::c_long = __X32_SYSCALL_BIT + 254; -pub const SYS_inotify_rm_watch: ::c_long = __X32_SYSCALL_BIT + 255; -pub const SYS_migrate_pages: ::c_long = __X32_SYSCALL_BIT + 256; -pub const SYS_openat: ::c_long = __X32_SYSCALL_BIT + 257; -pub const SYS_mkdirat: ::c_long = __X32_SYSCALL_BIT + 258; -pub const SYS_mknodat: ::c_long = __X32_SYSCALL_BIT + 259; -pub const SYS_fchownat: ::c_long = __X32_SYSCALL_BIT + 260; -pub const SYS_futimesat: ::c_long = __X32_SYSCALL_BIT + 261; -pub const SYS_newfstatat: ::c_long = __X32_SYSCALL_BIT + 262; -pub const SYS_unlinkat: ::c_long = __X32_SYSCALL_BIT + 263; -pub const SYS_renameat: ::c_long = __X32_SYSCALL_BIT + 264; -pub const SYS_linkat: ::c_long = __X32_SYSCALL_BIT + 265; -pub const SYS_symlinkat: ::c_long = __X32_SYSCALL_BIT + 266; -pub const SYS_readlinkat: ::c_long = __X32_SYSCALL_BIT + 267; -pub const SYS_fchmodat: ::c_long = __X32_SYSCALL_BIT + 268; -pub const SYS_faccessat: ::c_long = __X32_SYSCALL_BIT + 269; -pub const SYS_pselect6: ::c_long = __X32_SYSCALL_BIT + 270; -pub const SYS_ppoll: ::c_long = __X32_SYSCALL_BIT + 271; -pub const SYS_unshare: ::c_long = __X32_SYSCALL_BIT + 272; -pub const SYS_splice: ::c_long = __X32_SYSCALL_BIT + 275; -pub const SYS_tee: ::c_long = __X32_SYSCALL_BIT + 276; -pub const SYS_sync_file_range: ::c_long = __X32_SYSCALL_BIT + 277; -pub const SYS_utimensat: ::c_long = __X32_SYSCALL_BIT + 280; -pub const SYS_epoll_pwait: ::c_long = __X32_SYSCALL_BIT + 281; -pub const SYS_signalfd: ::c_long = __X32_SYSCALL_BIT + 282; -pub const SYS_timerfd_create: ::c_long = __X32_SYSCALL_BIT + 283; -pub const SYS_eventfd: ::c_long = __X32_SYSCALL_BIT + 284; -pub const SYS_fallocate: ::c_long = __X32_SYSCALL_BIT + 285; -pub const SYS_timerfd_settime: ::c_long = __X32_SYSCALL_BIT + 286; -pub const SYS_timerfd_gettime: ::c_long = __X32_SYSCALL_BIT + 287; -pub const SYS_accept4: ::c_long = __X32_SYSCALL_BIT + 288; -pub const SYS_signalfd4: ::c_long = __X32_SYSCALL_BIT + 289; -pub const SYS_eventfd2: ::c_long = __X32_SYSCALL_BIT + 290; -pub const SYS_epoll_create1: ::c_long = __X32_SYSCALL_BIT + 291; -pub const SYS_dup3: ::c_long = __X32_SYSCALL_BIT + 292; -pub const SYS_pipe2: ::c_long = __X32_SYSCALL_BIT + 293; -pub const SYS_inotify_init1: ::c_long = __X32_SYSCALL_BIT + 294; -pub const SYS_perf_event_open: ::c_long = __X32_SYSCALL_BIT + 298; -pub const SYS_fanotify_init: ::c_long = __X32_SYSCALL_BIT + 300; -pub const SYS_fanotify_mark: ::c_long = __X32_SYSCALL_BIT + 301; -pub const SYS_prlimit64: ::c_long = __X32_SYSCALL_BIT + 302; -pub const SYS_name_to_handle_at: ::c_long = __X32_SYSCALL_BIT + 303; -pub const SYS_open_by_handle_at: ::c_long = __X32_SYSCALL_BIT + 304; -pub const SYS_clock_adjtime: ::c_long = __X32_SYSCALL_BIT + 305; -pub const SYS_syncfs: ::c_long = __X32_SYSCALL_BIT + 306; -pub const SYS_setns: ::c_long = __X32_SYSCALL_BIT + 308; -pub const SYS_getcpu: ::c_long = __X32_SYSCALL_BIT + 309; -pub const SYS_kcmp: ::c_long = __X32_SYSCALL_BIT + 312; -pub const SYS_finit_module: ::c_long = __X32_SYSCALL_BIT + 313; -pub const SYS_sched_setattr: ::c_long = __X32_SYSCALL_BIT + 314; -pub const SYS_sched_getattr: ::c_long = __X32_SYSCALL_BIT + 315; -pub const SYS_renameat2: ::c_long = __X32_SYSCALL_BIT + 316; -pub const SYS_seccomp: ::c_long = __X32_SYSCALL_BIT + 317; -pub const SYS_getrandom: ::c_long = __X32_SYSCALL_BIT + 318; -pub const SYS_memfd_create: ::c_long = __X32_SYSCALL_BIT + 319; -pub const SYS_kexec_file_load: ::c_long = __X32_SYSCALL_BIT + 320; -pub const SYS_bpf: ::c_long = __X32_SYSCALL_BIT + 321; -pub const SYS_userfaultfd: ::c_long = __X32_SYSCALL_BIT + 323; -pub const SYS_membarrier: ::c_long = __X32_SYSCALL_BIT + 324; -pub const SYS_mlock2: ::c_long = __X32_SYSCALL_BIT + 325; -pub const SYS_copy_file_range: ::c_long = __X32_SYSCALL_BIT + 326; -pub const SYS_pkey_mprotect: ::c_long = __X32_SYSCALL_BIT + 329; -pub const SYS_pkey_alloc: ::c_long = __X32_SYSCALL_BIT + 330; -pub const SYS_pkey_free: ::c_long = __X32_SYSCALL_BIT + 331; -pub const SYS_rt_sigaction: ::c_long = __X32_SYSCALL_BIT + 512; -pub const SYS_rt_sigreturn: ::c_long = __X32_SYSCALL_BIT + 513; -pub const SYS_ioctl: ::c_long = __X32_SYSCALL_BIT + 514; -pub const SYS_readv: ::c_long = __X32_SYSCALL_BIT + 515; -pub const SYS_writev: ::c_long = __X32_SYSCALL_BIT + 516; -pub const SYS_recvfrom: ::c_long = __X32_SYSCALL_BIT + 517; -pub const SYS_sendmsg: ::c_long = __X32_SYSCALL_BIT + 518; -pub const SYS_recvmsg: ::c_long = __X32_SYSCALL_BIT + 519; -pub const SYS_execve: ::c_long = __X32_SYSCALL_BIT + 520; -pub const SYS_ptrace: ::c_long = __X32_SYSCALL_BIT + 521; -pub const SYS_rt_sigpending: ::c_long = __X32_SYSCALL_BIT + 522; -pub const SYS_rt_sigtimedwait: ::c_long = __X32_SYSCALL_BIT + 523; -pub const SYS_rt_sigqueueinfo: ::c_long = __X32_SYSCALL_BIT + 524; -pub const SYS_sigaltstack: ::c_long = __X32_SYSCALL_BIT + 525; -pub const SYS_timer_create: ::c_long = __X32_SYSCALL_BIT + 526; -pub const SYS_mq_notify: ::c_long = __X32_SYSCALL_BIT + 527; -pub const SYS_kexec_load: ::c_long = __X32_SYSCALL_BIT + 528; -pub const SYS_waitid: ::c_long = __X32_SYSCALL_BIT + 529; -pub const SYS_set_robust_list: ::c_long = __X32_SYSCALL_BIT + 530; -pub const SYS_get_robust_list: ::c_long = __X32_SYSCALL_BIT + 531; -pub const SYS_vmsplice: ::c_long = __X32_SYSCALL_BIT + 532; -pub const SYS_move_pages: ::c_long = __X32_SYSCALL_BIT + 533; -pub const SYS_preadv: ::c_long = __X32_SYSCALL_BIT + 534; -pub const SYS_pwritev: ::c_long = __X32_SYSCALL_BIT + 535; -pub const SYS_rt_tgsigqueueinfo: ::c_long = __X32_SYSCALL_BIT + 536; -pub const SYS_recvmmsg: ::c_long = __X32_SYSCALL_BIT + 537; -pub const SYS_sendmmsg: ::c_long = __X32_SYSCALL_BIT + 538; -pub const SYS_process_vm_readv: ::c_long = __X32_SYSCALL_BIT + 539; -pub const SYS_process_vm_writev: ::c_long = __X32_SYSCALL_BIT + 540; -pub const SYS_setsockopt: ::c_long = __X32_SYSCALL_BIT + 541; -pub const SYS_getsockopt: ::c_long = __X32_SYSCALL_BIT + 542; -pub const SYS_io_setup: ::c_long = __X32_SYSCALL_BIT + 543; -pub const SYS_io_submit: ::c_long = __X32_SYSCALL_BIT + 544; -pub const SYS_execveat: ::c_long = __X32_SYSCALL_BIT + 545; -pub const SYS_preadv2: ::c_long = __X32_SYSCALL_BIT + 546; -pub const SYS_pwritev2: ::c_long = __X32_SYSCALL_BIT + 547; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/x86_64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/x86_64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/b64/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,656 +0,0 @@ -//! x86_64-specific definitions for 64-bit linux-like values - -pub type c_char = i8; -pub type wchar_t = i32; -pub type nlink_t = u64; -pub type blksize_t = i64; -pub type greg_t = i64; -pub type suseconds_t = i64; -pub type __u64 = ::c_ulonglong; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - __pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: i64, - pub st_mtime: ::time_t, - pub st_mtime_nsec: i64, - pub st_ctime: ::time_t, - pub st_ctime_nsec: i64, - __unused: [i64; 3], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino64_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - __pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: i64, - pub st_mtime: ::time_t, - pub st_mtime_nsec: i64, - pub st_ctime: ::time_t, - pub st_ctime_nsec: i64, - __reserved: [i64; 3], - } - - pub struct statfs64 { - pub f_type: ::__fsword_t, - pub f_bsize: ::__fsword_t, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_fsid: ::fsid_t, - pub f_namelen: ::__fsword_t, - pub f_frsize: ::__fsword_t, - pub f_flags: ::__fsword_t, - pub f_spare: [::__fsword_t; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct pthread_attr_t { - #[cfg(target_pointer_width = "32")] - __size: [u32; 8], - #[cfg(target_pointer_width = "64")] - __size: [u64; 7] - } - - pub struct _libc_fpxreg { - pub significand: [u16; 4], - pub exponent: u16, - __private: [u16; 3], - } - - pub struct _libc_xmmreg { - pub element: [u32; 4], - } - - pub struct _libc_fpstate { - pub cwd: u16, - pub swd: u16, - pub ftw: u16, - pub fop: u16, - pub rip: u64, - pub rdp: u64, - pub mxcsr: u32, - pub mxcr_mask: u32, - pub _st: [_libc_fpxreg; 8], - pub _xmm: [_libc_xmmreg; 16], - __private: [u64; 12], - } - - pub struct user_fpregs_struct { - pub cwd: ::c_ushort, - pub swd: ::c_ushort, - pub ftw: ::c_ushort, - pub fop: ::c_ushort, - pub rip: ::c_ulonglong, - pub rdp: ::c_ulonglong, - pub mxcsr: ::c_uint, - pub mxcr_mask: ::c_uint, - pub st_space: [::c_uint; 32], - pub xmm_space: [::c_uint; 64], - padding: [::c_uint; 24], - } - - pub struct user_regs_struct { - pub r15: ::c_ulonglong, - pub r14: ::c_ulonglong, - pub r13: ::c_ulonglong, - pub r12: ::c_ulonglong, - pub rbp: ::c_ulonglong, - pub rbx: ::c_ulonglong, - pub r11: ::c_ulonglong, - pub r10: ::c_ulonglong, - pub r9: ::c_ulonglong, - pub r8: ::c_ulonglong, - pub rax: ::c_ulonglong, - pub rcx: ::c_ulonglong, - pub rdx: ::c_ulonglong, - pub rsi: ::c_ulonglong, - pub rdi: ::c_ulonglong, - pub orig_rax: ::c_ulonglong, - pub rip: ::c_ulonglong, - pub cs: ::c_ulonglong, - pub eflags: ::c_ulonglong, - pub rsp: ::c_ulonglong, - pub ss: ::c_ulonglong, - pub fs_base: ::c_ulonglong, - pub gs_base: ::c_ulonglong, - pub ds: ::c_ulonglong, - pub es: ::c_ulonglong, - pub fs: ::c_ulonglong, - pub gs: ::c_ulonglong, - } - - pub struct user { - pub regs: user_regs_struct, - pub u_fpvalid: ::c_int, - pub i387: user_fpregs_struct, - pub u_tsize: ::c_ulonglong, - pub u_dsize: ::c_ulonglong, - pub u_ssize: ::c_ulonglong, - pub start_code: ::c_ulonglong, - pub start_stack: ::c_ulonglong, - pub signal: ::c_longlong, - __reserved: ::c_int, - #[cfg(target_pointer_width = "32")] - __pad1: u32, - pub u_ar0: *mut user_regs_struct, - #[cfg(target_pointer_width = "32")] - __pad2: u32, - pub u_fpstate: *mut user_fpregs_struct, - pub magic: ::c_ulonglong, - pub u_comm: [::c_char; 32], - pub u_debugreg: [::c_ulonglong; 8], - } - - pub struct mcontext_t { - pub gregs: [greg_t; 23], - pub fpregs: *mut _libc_fpstate, - __private: [u64; 8], - } - - pub struct ucontext_t { - pub uc_flags: ::c_ulong, - pub uc_link: *mut ucontext_t, - pub uc_stack: ::stack_t, - pub uc_mcontext: mcontext_t, - pub uc_sigmask: ::sigset_t, - __private: [u8; 512], - } - - pub struct ipc_perm { - pub __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::c_ushort, - __pad1: ::c_ushort, - pub __seq: ::c_ushort, - __pad2: ::c_ushort, - __unused1: u64, - __unused2: u64 - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __unused4: u64, - __unused5: u64 - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 19], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } -} - -pub const TIOCGSOFTCAR: ::c_ulong = 0x5419; -pub const TIOCSSOFTCAR: ::c_ulong = 0x541A; - -pub const RLIMIT_NOFILE: ::c_int = 7; -pub const RLIMIT_NPROC: ::c_int = 6; - -pub const O_APPEND: ::c_int = 1024; -pub const O_CREAT: ::c_int = 64; -pub const O_EXCL: ::c_int = 128; -pub const O_NOCTTY: ::c_int = 256; -pub const O_NONBLOCK: ::c_int = 2048; -pub const O_SYNC: ::c_int = 1052672; -pub const O_RSYNC: ::c_int = 1052672; -pub const O_DSYNC: ::c_int = 4096; -pub const O_FSYNC: ::c_int = 0x101000; -pub const O_NOATIME: ::c_int = 0o1000000; -pub const O_PATH: ::c_int = 0o10000000; -pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; - -pub const MAP_GROWSDOWN: ::c_int = 0x0100; - -pub const EDEADLK: ::c_int = 35; -pub const ENAMETOOLONG: ::c_int = 36; -pub const ENOLCK: ::c_int = 37; -pub const ENOSYS: ::c_int = 38; -pub const ENOTEMPTY: ::c_int = 39; -pub const ELOOP: ::c_int = 40; -pub const ENOMSG: ::c_int = 42; -pub const EIDRM: ::c_int = 43; -pub const ECHRNG: ::c_int = 44; -pub const EL2NSYNC: ::c_int = 45; -pub const EL3HLT: ::c_int = 46; -pub const EL3RST: ::c_int = 47; -pub const ELNRNG: ::c_int = 48; -pub const EUNATCH: ::c_int = 49; -pub const ENOCSI: ::c_int = 50; -pub const EL2HLT: ::c_int = 51; -pub const EBADE: ::c_int = 52; -pub const EBADR: ::c_int = 53; -pub const EXFULL: ::c_int = 54; -pub const ENOANO: ::c_int = 55; -pub const EBADRQC: ::c_int = 56; -pub const EBADSLT: ::c_int = 57; -pub const EMULTIHOP: ::c_int = 72; -pub const EOVERFLOW: ::c_int = 75; -pub const ENOTUNIQ: ::c_int = 76; -pub const EBADFD: ::c_int = 77; -pub const EBADMSG: ::c_int = 74; -pub const EREMCHG: ::c_int = 78; -pub const ELIBACC: ::c_int = 79; -pub const ELIBBAD: ::c_int = 80; -pub const ELIBSCN: ::c_int = 81; -pub const ELIBMAX: ::c_int = 82; -pub const ELIBEXEC: ::c_int = 83; -pub const EILSEQ: ::c_int = 84; -pub const ERESTART: ::c_int = 85; -pub const ESTRPIPE: ::c_int = 86; -pub const EUSERS: ::c_int = 87; -pub const ENOTSOCK: ::c_int = 88; -pub const EDESTADDRREQ: ::c_int = 89; -pub const EMSGSIZE: ::c_int = 90; -pub const EPROTOTYPE: ::c_int = 91; -pub const ENOPROTOOPT: ::c_int = 92; -pub const EPROTONOSUPPORT: ::c_int = 93; -pub const ESOCKTNOSUPPORT: ::c_int = 94; -pub const EOPNOTSUPP: ::c_int = 95; -pub const EPFNOSUPPORT: ::c_int = 96; -pub const EAFNOSUPPORT: ::c_int = 97; -pub const EADDRINUSE: ::c_int = 98; -pub const EADDRNOTAVAIL: ::c_int = 99; -pub const ENETDOWN: ::c_int = 100; -pub const ENETUNREACH: ::c_int = 101; -pub const ENETRESET: ::c_int = 102; -pub const ECONNABORTED: ::c_int = 103; -pub const ECONNRESET: ::c_int = 104; -pub const ENOBUFS: ::c_int = 105; -pub const EISCONN: ::c_int = 106; -pub const ENOTCONN: ::c_int = 107; -pub const ESHUTDOWN: ::c_int = 108; -pub const ETOOMANYREFS: ::c_int = 109; -pub const ETIMEDOUT: ::c_int = 110; -pub const ECONNREFUSED: ::c_int = 111; -pub const EHOSTDOWN: ::c_int = 112; -pub const EHOSTUNREACH: ::c_int = 113; -pub const EALREADY: ::c_int = 114; -pub const EINPROGRESS: ::c_int = 115; -pub const ESTALE: ::c_int = 116; -pub const EDQUOT: ::c_int = 122; -pub const ENOMEDIUM: ::c_int = 123; -pub const EMEDIUMTYPE: ::c_int = 124; -pub const ECANCELED: ::c_int = 125; -pub const ENOKEY: ::c_int = 126; -pub const EKEYEXPIRED: ::c_int = 127; -pub const EKEYREVOKED: ::c_int = 128; -pub const EKEYREJECTED: ::c_int = 129; -pub const EOWNERDEAD: ::c_int = 130; -pub const ENOTRECOVERABLE: ::c_int = 131; -pub const EHWPOISON: ::c_int = 133; -pub const ERFKILL: ::c_int = 132; - -pub const SOL_SOCKET: ::c_int = 1; - -pub const SO_REUSEADDR: ::c_int = 2; -pub const SO_TYPE: ::c_int = 3; -pub const SO_ERROR: ::c_int = 4; -pub const SO_DONTROUTE: ::c_int = 5; -pub const SO_BROADCAST: ::c_int = 6; -pub const SO_SNDBUF: ::c_int = 7; -pub const SO_RCVBUF: ::c_int = 8; -pub const SO_SNDBUFFORCE: ::c_int = 32; -pub const SO_RCVBUFFORCE: ::c_int = 33; -pub const SO_KEEPALIVE: ::c_int = 9; -pub const SO_OOBINLINE: ::c_int = 10; -pub const SO_NO_CHECK: ::c_int = 11; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_LINGER: ::c_int = 13; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_REUSEPORT: ::c_int = 15; -pub const SO_PASSCRED: ::c_int = 16; -pub const SO_PEERCRED: ::c_int = 17; -pub const SO_RCVLOWAT: ::c_int = 18; -pub const SO_SNDLOWAT: ::c_int = 19; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_SNDTIMEO: ::c_int = 21; -pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22; -pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23; -pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24; -pub const SO_BINDTODEVICE: ::c_int = 25; -pub const SO_ATTACH_FILTER: ::c_int = 26; -pub const SO_DETACH_FILTER: ::c_int = 27; -pub const SO_GET_FILTER: ::c_int = SO_ATTACH_FILTER; -pub const SO_PEERNAME: ::c_int = 28; -pub const SO_TIMESTAMP: ::c_int = 29; -pub const SO_ACCEPTCONN: ::c_int = 30; -pub const SO_PEERSEC: ::c_int = 31; -pub const SO_PASSSEC: ::c_int = 34; -pub const SO_TIMESTAMPNS: ::c_int = 35; -pub const SCM_TIMESTAMPNS: ::c_int = SO_TIMESTAMPNS; -pub const SO_MARK: ::c_int = 36; -pub const SO_TIMESTAMPING: ::c_int = 37; -pub const SCM_TIMESTAMPING: ::c_int = SO_TIMESTAMPING; -pub const SO_PROTOCOL: ::c_int = 38; -pub const SO_DOMAIN: ::c_int = 39; -pub const SO_RXQ_OVFL: ::c_int = 40; -pub const SO_WIFI_STATUS: ::c_int = 41; -pub const SCM_WIFI_STATUS: ::c_int = SO_WIFI_STATUS; -pub const SO_PEEK_OFF: ::c_int = 42; -pub const SO_NOFCS: ::c_int = 43; -pub const SO_LOCK_FILTER: ::c_int = 44; -pub const SO_SELECT_ERR_QUEUE: ::c_int = 45; -pub const SO_BUSY_POLL: ::c_int = 46; -pub const SO_MAX_PACING_RATE: ::c_int = 47; -pub const SO_BPF_EXTENSIONS: ::c_int = 48; -pub const SO_INCOMING_CPU: ::c_int = 49; -pub const SO_ATTACH_BPF: ::c_int = 50; -pub const SO_DETACH_BPF: ::c_int = SO_DETACH_FILTER; - -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 0x00000004; -pub const SA_NOCLDWAIT: ::c_int = 0x00000002; - -pub const SIGCHLD: ::c_int = 17; -pub const SIGBUS: ::c_int = 7; -pub const SIGUSR1: ::c_int = 10; -pub const SIGUSR2: ::c_int = 12; -pub const SIGCONT: ::c_int = 18; -pub const SIGSTOP: ::c_int = 19; -pub const SIGTSTP: ::c_int = 20; -pub const SIGURG: ::c_int = 23; -pub const SIGIO: ::c_int = 29; -pub const SIGSYS: ::c_int = 31; -pub const SIGSTKFLT: ::c_int = 16; -pub const SIGUNUSED: ::c_int = 31; -pub const SIGPOLL: ::c_int = 29; -pub const SIGPWR: ::c_int = 30; -pub const SIG_SETMASK: ::c_int = 2; -pub const SIG_BLOCK: ::c_int = 0x000000; -pub const SIG_UNBLOCK: ::c_int = 0x01; - -pub const POLLWRNORM: ::c_short = 0x100; -pub const POLLWRBAND: ::c_short = 0x200; - -pub const O_ASYNC: ::c_int = 0x2000; -pub const O_NDELAY: ::c_int = 0x800; - -pub const PTRACE_DETACH: ::c_uint = 17; - -pub const EFD_NONBLOCK: ::c_int = 0x800; - -pub const F_GETLK: ::c_int = 5; -pub const F_GETOWN: ::c_int = 9; -pub const F_SETOWN: ::c_int = 8; -pub const F_SETLK: ::c_int = 6; -pub const F_SETLKW: ::c_int = 7; - -pub const SFD_NONBLOCK: ::c_int = 0x0800; - -pub const TIOCEXCL: ::c_ulong = 0x540C; -pub const TIOCNXCL: ::c_ulong = 0x540D; -pub const TIOCSCTTY: ::c_ulong = 0x540E; -pub const TIOCSTI: ::c_ulong = 0x5412; -pub const TIOCMGET: ::c_ulong = 0x5415; -pub const TIOCMBIS: ::c_ulong = 0x5416; -pub const TIOCMBIC: ::c_ulong = 0x5417; -pub const TIOCMSET: ::c_ulong = 0x5418; -pub const TIOCCONS: ::c_ulong = 0x541D; - -pub const SFD_CLOEXEC: ::c_int = 0x080000; - -pub const NCCS: usize = 32; - -pub const O_TRUNC: ::c_int = 512; - -pub const O_CLOEXEC: ::c_int = 0x80000; - -pub const EBFONT: ::c_int = 59; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENONET: ::c_int = 64; -pub const ENOPKG: ::c_int = 65; -pub const EREMOTE: ::c_int = 66; -pub const ENOLINK: ::c_int = 67; -pub const EADV: ::c_int = 68; -pub const ESRMNT: ::c_int = 69; -pub const ECOMM: ::c_int = 70; -pub const EPROTO: ::c_int = 71; -pub const EDOTDOT: ::c_int = 73; - -pub const SA_NODEFER: ::c_int = 0x40000000; -pub const SA_RESETHAND: ::c_int = 0x80000000; -pub const SA_RESTART: ::c_int = 0x10000000; -pub const SA_NOCLDSTOP: ::c_int = 0x00000001; - -pub const EPOLL_CLOEXEC: ::c_int = 0x80000; - -pub const EFD_CLOEXEC: ::c_int = 0x80000; - -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; - -pub const O_DIRECT: ::c_int = 0x4000; -pub const O_DIRECTORY: ::c_int = 0x10000; -pub const O_NOFOLLOW: ::c_int = 0x20000; - -pub const MAP_LOCKED: ::c_int = 0x02000; -pub const MAP_NORESERVE: ::c_int = 0x04000; -pub const MAP_32BIT: ::c_int = 0x0040; - -pub const EDEADLOCK: ::c_int = 35; - -pub const FIOCLEX: ::c_ulong = 0x5451; -pub const FIONBIO: ::c_ulong = 0x5421; - -pub const PTRACE_GETFPREGS: ::c_uint = 14; -pub const PTRACE_SETFPREGS: ::c_uint = 15; -pub const PTRACE_GETFPXREGS: ::c_uint = 18; -pub const PTRACE_SETFPXREGS: ::c_uint = 19; -pub const PTRACE_GETREGS: ::c_uint = 12; -pub const PTRACE_SETREGS: ::c_uint = 13; -pub const PTRACE_PEEKSIGINFO_SHARED: ::c_uint = 1; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const SIGSTKSZ: ::size_t = 8192; -pub const MINSIGSTKSZ: ::size_t = 2048; -pub const CBAUD: ::tcflag_t = 0o0010017; -pub const TAB1: ::c_int = 0x00000800; -pub const TAB2: ::c_int = 0x00001000; -pub const TAB3: ::c_int = 0x00001800; -pub const CR1: ::c_int = 0x00000200; -pub const CR2: ::c_int = 0x00000400; -pub const CR3: ::c_int = 0x00000600; -pub const FF1: ::c_int = 0x00008000; -pub const BS1: ::c_int = 0x00002000; -pub const VT1: ::c_int = 0x00004000; -pub const VWERASE: usize = 14; -pub const VREPRINT: usize = 12; -pub const VSUSP: usize = 10; -pub const VSTART: usize = 8; -pub const VSTOP: usize = 9; -pub const VDISCARD: usize = 13; -pub const VTIME: usize = 5; -pub const IXON: ::tcflag_t = 0x00000400; -pub const IXOFF: ::tcflag_t = 0x00001000; -pub const ONLCR: ::tcflag_t = 0x4; -pub const CSIZE: ::tcflag_t = 0x00000030; -pub const CS6: ::tcflag_t = 0x00000010; -pub const CS7: ::tcflag_t = 0x00000020; -pub const CS8: ::tcflag_t = 0x00000030; -pub const CSTOPB: ::tcflag_t = 0x00000040; -pub const CREAD: ::tcflag_t = 0x00000080; -pub const PARENB: ::tcflag_t = 0x00000100; -pub const PARODD: ::tcflag_t = 0x00000200; -pub const HUPCL: ::tcflag_t = 0x00000400; -pub const CLOCAL: ::tcflag_t = 0x00000800; -pub const ECHOKE: ::tcflag_t = 0x00000800; -pub const ECHOE: ::tcflag_t = 0x00000010; -pub const ECHOK: ::tcflag_t = 0x00000020; -pub const ECHONL: ::tcflag_t = 0x00000040; -pub const ECHOPRT: ::tcflag_t = 0x00000400; -pub const ECHOCTL: ::tcflag_t = 0x00000200; -pub const ISIG: ::tcflag_t = 0x00000001; -pub const ICANON: ::tcflag_t = 0x00000002; -pub const PENDIN: ::tcflag_t = 0x00004000; -pub const NOFLSH: ::tcflag_t = 0x00000080; -pub const CIBAUD: ::tcflag_t = 0o02003600000; -pub const CBAUDEX: ::tcflag_t = 0o010000; -pub const VSWTC: usize = 7; -pub const OLCUC: ::tcflag_t = 0o000002; -pub const NLDLY: ::tcflag_t = 0o000400; -pub const CRDLY: ::tcflag_t = 0o003000; -pub const TABDLY: ::tcflag_t = 0o014000; -pub const BSDLY: ::tcflag_t = 0o020000; -pub const FFDLY: ::tcflag_t = 0o100000; -pub const VTDLY: ::tcflag_t = 0o040000; -pub const XTABS: ::tcflag_t = 0o014000; - -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const EXTA: ::speed_t = B19200; -pub const EXTB: ::speed_t = B38400; -pub const BOTHER: ::speed_t = 0o010000; -pub const B57600: ::speed_t = 0o010001; -pub const B115200: ::speed_t = 0o010002; -pub const B230400: ::speed_t = 0o010003; -pub const B460800: ::speed_t = 0o010004; -pub const B500000: ::speed_t = 0o010005; -pub const B576000: ::speed_t = 0o010006; -pub const B921600: ::speed_t = 0o010007; -pub const B1000000: ::speed_t = 0o010010; -pub const B1152000: ::speed_t = 0o010011; -pub const B1500000: ::speed_t = 0o010012; -pub const B2000000: ::speed_t = 0o010013; -pub const B2500000: ::speed_t = 0o010014; -pub const B3000000: ::speed_t = 0o010015; -pub const B3500000: ::speed_t = 0o010016; -pub const B4000000: ::speed_t = 0o010017; - -pub const VEOL: usize = 11; -pub const VEOL2: usize = 16; -pub const VMIN: usize = 6; -pub const IEXTEN: ::tcflag_t = 0x00008000; -pub const TOSTOP: ::tcflag_t = 0x00000100; -pub const FLUSHO: ::tcflag_t = 0x00001000; -pub const EXTPROC: ::tcflag_t = 0x00010000; -pub const TCGETS: ::c_ulong = 0x5401; -pub const TCSETS: ::c_ulong = 0x5402; -pub const TCSETSW: ::c_ulong = 0x5403; -pub const TCSETSF: ::c_ulong = 0x5404; -pub const TCGETA: ::c_ulong = 0x5405; -pub const TCSETA: ::c_ulong = 0x5406; -pub const TCSETAW: ::c_ulong = 0x5407; -pub const TCSETAF: ::c_ulong = 0x5408; -pub const TCSBRK: ::c_ulong = 0x5409; -pub const TCXONC: ::c_ulong = 0x540A; -pub const TCFLSH: ::c_ulong = 0x540B; -pub const TIOCINQ: ::c_ulong = 0x541B; -pub const TIOCGPGRP: ::c_ulong = 0x540F; -pub const TIOCSPGRP: ::c_ulong = 0x5410; -pub const TIOCOUTQ: ::c_ulong = 0x5411; -pub const TIOCGWINSZ: ::c_ulong = 0x5413; -pub const TIOCSWINSZ: ::c_ulong = 0x5414; -pub const FIONREAD: ::c_ulong = 0x541B; - -// offsets in user_regs_structs, from sys/reg.h -pub const R15: ::c_int = 0; -pub const R14: ::c_int = 1; -pub const R13: ::c_int = 2; -pub const R12: ::c_int = 3; -pub const RBP: ::c_int = 4; -pub const RBX: ::c_int = 5; -pub const R11: ::c_int = 6; -pub const R10: ::c_int = 7; -pub const R9: ::c_int = 8; -pub const R8: ::c_int = 9; -pub const RAX: ::c_int = 10; -pub const RCX: ::c_int = 11; -pub const RDX: ::c_int = 12; -pub const RSI: ::c_int = 13; -pub const RDI: ::c_int = 14; -pub const ORIG_RAX: ::c_int = 15; -pub const RIP: ::c_int = 16; -pub const CS: ::c_int = 17; -pub const EFLAGS: ::c_int = 18; -pub const RSP: ::c_int = 19; -pub const SS: ::c_int = 20; -pub const FS_BASE: ::c_int = 21; -pub const GS_BASE: ::c_int = 22; -pub const DS: ::c_int = 23; -pub const ES: ::c_int = 24; -pub const FS: ::c_int = 25; -pub const GS: ::c_int = 26; - -extern { - pub fn getcontext(ucp: *mut ucontext_t) -> ::c_int; - pub fn setcontext(ucp: *const ucontext_t) -> ::c_int; - pub fn makecontext(ucp: *mut ucontext_t, - func: extern fn (), - argc: ::c_int, ...); - pub fn swapcontext(uocp: *mut ucontext_t, - ucp: *const ucontext_t) -> ::c_int; - pub fn iopl(level: ::c_int) -> ::c_int; - pub fn ioperm(from: ::c_ulong, num: ::c_ulong, - turn_on: ::c_int) -> ::c_int; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/other/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,617 +0,0 @@ -pub type __priority_which_t = ::c_uint; - -s! { - pub struct aiocb { - pub aio_fildes: ::c_int, - pub aio_lio_opcode: ::c_int, - pub aio_reqprio: ::c_int, - pub aio_buf: *mut ::c_void, - pub aio_nbytes: ::size_t, - pub aio_sigevent: ::sigevent, - __next_prio: *mut aiocb, - __abs_prio: ::c_int, - __policy: ::c_int, - __error_code: ::c_int, - __return_value: ::ssize_t, - pub aio_offset: off_t, - #[cfg(all(not(target_arch = "x86_64"), target_pointer_width = "32"))] - __unused1: [::c_char; 4], - __glibc_reserved: [::c_char; 32] - } - - pub struct __exit_status { - pub e_termination: ::c_short, - pub e_exit: ::c_short, - } - - pub struct __timeval { - pub tv_sec: ::int32_t, - pub tv_usec: ::int32_t, - } - - pub struct utmpx { - pub ut_type: ::c_short, - pub ut_pid: ::pid_t, - pub ut_line: [::c_char; __UT_LINESIZE], - pub ut_id: [::c_char; 4], - - pub ut_user: [::c_char; __UT_NAMESIZE], - pub ut_host: [::c_char; __UT_HOSTSIZE], - pub ut_exit: __exit_status, - - #[cfg(any(target_arch = "aarch64", - target_arch = "sparc64", - all(target_pointer_width = "32", - not(target_arch = "x86_64"))))] - pub ut_session: ::c_long, - #[cfg(any(target_arch = "aarch64", - target_arch = "sparc64", - all(target_pointer_width = "32", - not(target_arch = "x86_64"))))] - pub ut_tv: ::timeval, - - #[cfg(not(any(target_arch = "aarch64", - target_arch = "sparc64", - all(target_pointer_width = "32", - not(target_arch = "x86_64")))))] - pub ut_session: ::int32_t, - #[cfg(not(any(target_arch = "aarch64", - target_arch = "sparc64", - all(target_pointer_width = "32", - not(target_arch = "x86_64")))))] - pub ut_tv: __timeval, - - pub ut_addr_v6: [::int32_t; 4], - __glibc_reserved: [::c_char; 20], - } - - pub struct sigaction { - pub sa_sigaction: ::sighandler_t, - pub sa_mask: ::sigset_t, - #[cfg(target_arch = "sparc64")] - __reserved0: ::c_int, - pub sa_flags: ::c_int, - pub sa_restorer: ::dox::Option, - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_flags: ::c_int, - pub ss_size: ::size_t - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_errno: ::c_int, - pub si_code: ::c_int, - pub _pad: [::c_int; 29], - #[cfg(target_arch = "x86_64")] - _align: [u64; 0], - #[cfg(not(target_arch = "x86_64"))] - _align: [usize; 0], - } - - pub struct glob64_t { - pub gl_pathc: ::size_t, - pub gl_pathv: *mut *mut ::c_char, - pub gl_offs: ::size_t, - pub gl_flags: ::c_int, - - __unused1: *mut ::c_void, - __unused2: *mut ::c_void, - __unused3: *mut ::c_void, - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - } - - pub struct statfs { - pub f_type: __fsword_t, - pub f_bsize: __fsword_t, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - - pub f_namelen: __fsword_t, - pub f_frsize: __fsword_t, - f_spare: [__fsword_t; 5], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::size_t, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::size_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::size_t, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; ::NCCS], - #[cfg(not(target_arch = "sparc64"))] - pub c_ispeed: ::speed_t, - #[cfg(not(target_arch = "sparc64"))] - pub c_ospeed: ::speed_t, - } - - pub struct flock { - pub l_type: ::c_short, - pub l_whence: ::c_short, - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_pid: ::pid_t, - } - - // FIXME this is actually a union - pub struct sem_t { - #[cfg(target_pointer_width = "32")] - __size: [::c_char; 16], - #[cfg(target_pointer_width = "64")] - __size: [::c_char; 32], - __align: [::c_long; 0], - } -} - -pub const __UT_LINESIZE: usize = 32; -pub const __UT_NAMESIZE: usize = 32; -pub const __UT_HOSTSIZE: usize = 256; -pub const EMPTY: ::c_short = 0; -pub const RUN_LVL: ::c_short = 1; -pub const BOOT_TIME: ::c_short = 2; -pub const NEW_TIME: ::c_short = 3; -pub const OLD_TIME: ::c_short = 4; -pub const INIT_PROCESS: ::c_short = 5; -pub const LOGIN_PROCESS: ::c_short = 6; -pub const USER_PROCESS: ::c_short = 7; -pub const DEAD_PROCESS: ::c_short = 8; -pub const ACCOUNTING: ::c_short = 9; - -pub const RLIMIT_RSS: ::c_int = 5; -pub const RLIMIT_AS: ::c_int = 9; -pub const RLIMIT_MEMLOCK: ::c_int = 8; -pub const RLIM_INFINITY: ::rlim_t = !0; -pub const RLIMIT_RTTIME: ::c_int = 15; -pub const RLIMIT_NLIMITS: ::c_int = 16; - -pub const SOCK_NONBLOCK: ::c_int = O_NONBLOCK; - -pub const SOL_RXRPC: ::c_int = 272; -pub const SOL_PPPOL2TP: ::c_int = 273; -pub const SOL_BLUETOOTH: ::c_int = 274; -pub const SOL_PNPIPE: ::c_int = 275; -pub const SOL_RDS: ::c_int = 276; -pub const SOL_IUCV: ::c_int = 277; -pub const SOL_CAIF: ::c_int = 278; -pub const SOL_ALG: ::c_int = 279; -pub const SOL_NFC: ::c_int = 280; - -pub const MSG_TRYHARD: ::c_int = 4; - -pub const LC_PAPER: ::c_int = 7; -pub const LC_NAME: ::c_int = 8; -pub const LC_ADDRESS: ::c_int = 9; -pub const LC_TELEPHONE: ::c_int = 10; -pub const LC_MEASUREMENT: ::c_int = 11; -pub const LC_IDENTIFICATION: ::c_int = 12; -pub const LC_PAPER_MASK: ::c_int = (1 << LC_PAPER); -pub const LC_NAME_MASK: ::c_int = (1 << LC_NAME); -pub const LC_ADDRESS_MASK: ::c_int = (1 << LC_ADDRESS); -pub const LC_TELEPHONE_MASK: ::c_int = (1 << LC_TELEPHONE); -pub const LC_MEASUREMENT_MASK: ::c_int = (1 << LC_MEASUREMENT); -pub const LC_IDENTIFICATION_MASK: ::c_int = (1 << LC_IDENTIFICATION); -pub const LC_ALL_MASK: ::c_int = ::LC_CTYPE_MASK - | ::LC_NUMERIC_MASK - | ::LC_TIME_MASK - | ::LC_COLLATE_MASK - | ::LC_MONETARY_MASK - | ::LC_MESSAGES_MASK - | LC_PAPER_MASK - | LC_NAME_MASK - | LC_ADDRESS_MASK - | LC_TELEPHONE_MASK - | LC_MEASUREMENT_MASK - | LC_IDENTIFICATION_MASK; - -pub const MAP_ANON: ::c_int = 0x0020; -pub const MAP_ANONYMOUS: ::c_int = 0x0020; -pub const MAP_DENYWRITE: ::c_int = 0x0800; -pub const MAP_EXECUTABLE: ::c_int = 0x01000; -pub const MAP_POPULATE: ::c_int = 0x08000; -pub const MAP_NONBLOCK: ::c_int = 0x010000; -pub const MAP_STACK: ::c_int = 0x020000; - -pub const ENOTSUP: ::c_int = EOPNOTSUPP; -pub const EUCLEAN: ::c_int = 117; -pub const ENOTNAM: ::c_int = 118; -pub const ENAVAIL: ::c_int = 119; -pub const EISNAM: ::c_int = 120; -pub const EREMOTEIO: ::c_int = 121; - -pub const SOCK_STREAM: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 2; -pub const SOCK_SEQPACKET: ::c_int = 5; -pub const SOCK_DCCP: ::c_int = 6; -pub const SOCK_PACKET: ::c_int = 10; - -pub const TCP_COOKIE_TRANSACTIONS: ::c_int = 15; -pub const TCP_THIN_LINEAR_TIMEOUTS: ::c_int = 16; -pub const TCP_THIN_DUPACK: ::c_int = 17; -pub const TCP_USER_TIMEOUT: ::c_int = 18; -pub const TCP_REPAIR: ::c_int = 19; -pub const TCP_REPAIR_QUEUE: ::c_int = 20; -pub const TCP_QUEUE_SEQ: ::c_int = 21; -pub const TCP_REPAIR_OPTIONS: ::c_int = 22; -pub const TCP_FASTOPEN: ::c_int = 23; -pub const TCP_TIMESTAMP: ::c_int = 24; - -/* DCCP socket options */ -pub const DCCP_SOCKOPT_PACKET_SIZE: ::c_int = 1; -pub const DCCP_SOCKOPT_SERVICE: ::c_int = 2; -pub const DCCP_SOCKOPT_CHANGE_L: ::c_int = 3; -pub const DCCP_SOCKOPT_CHANGE_R: ::c_int = 4; -pub const DCCP_SOCKOPT_GET_CUR_MPS: ::c_int = 5; -pub const DCCP_SOCKOPT_SERVER_TIMEWAIT: ::c_int = 6; -pub const DCCP_SOCKOPT_SEND_CSCOV: ::c_int = 10; -pub const DCCP_SOCKOPT_RECV_CSCOV: ::c_int = 11; -pub const DCCP_SOCKOPT_AVAILABLE_CCIDS: ::c_int = 12; -pub const DCCP_SOCKOPT_CCID: ::c_int = 13; -pub const DCCP_SOCKOPT_TX_CCID: ::c_int = 14; -pub const DCCP_SOCKOPT_RX_CCID: ::c_int = 15; -pub const DCCP_SOCKOPT_QPOLICY_ID: ::c_int = 16; -pub const DCCP_SOCKOPT_QPOLICY_TXQLEN: ::c_int = 17; -pub const DCCP_SOCKOPT_CCID_RX_INFO: ::c_int = 128; -pub const DCCP_SOCKOPT_CCID_TX_INFO: ::c_int = 192; - -/// maximum number of services provided on the same listening port -pub const DCCP_SERVICE_LIST_MAX_LEN: ::c_int = 32; - -pub const SIGTTIN: ::c_int = 21; -pub const SIGTTOU: ::c_int = 22; -pub const SIGXCPU: ::c_int = 24; -pub const SIGXFSZ: ::c_int = 25; -pub const SIGVTALRM: ::c_int = 26; -pub const SIGPROF: ::c_int = 27; -pub const SIGWINCH: ::c_int = 28; - -pub const SIGEV_THREAD_ID: ::c_int = 4; - -pub const BUFSIZ: ::c_uint = 8192; -pub const TMP_MAX: ::c_uint = 238328; -pub const FOPEN_MAX: ::c_uint = 16; -pub const POSIX_FADV_DONTNEED: ::c_int = 4; -pub const POSIX_FADV_NOREUSE: ::c_int = 5; -pub const POSIX_MADV_DONTNEED: ::c_int = 4; -pub const _SC_EQUIV_CLASS_MAX: ::c_int = 41; -pub const _SC_CHARCLASS_NAME_MAX: ::c_int = 45; -pub const _SC_PII: ::c_int = 53; -pub const _SC_PII_XTI: ::c_int = 54; -pub const _SC_PII_SOCKET: ::c_int = 55; -pub const _SC_PII_INTERNET: ::c_int = 56; -pub const _SC_PII_OSI: ::c_int = 57; -pub const _SC_POLL: ::c_int = 58; -pub const _SC_SELECT: ::c_int = 59; -pub const _SC_PII_INTERNET_STREAM: ::c_int = 61; -pub const _SC_PII_INTERNET_DGRAM: ::c_int = 62; -pub const _SC_PII_OSI_COTS: ::c_int = 63; -pub const _SC_PII_OSI_CLTS: ::c_int = 64; -pub const _SC_PII_OSI_M: ::c_int = 65; -pub const _SC_T_IOV_MAX: ::c_int = 66; -pub const _SC_2_C_VERSION: ::c_int = 96; -pub const _SC_CHAR_BIT: ::c_int = 101; -pub const _SC_CHAR_MAX: ::c_int = 102; -pub const _SC_CHAR_MIN: ::c_int = 103; -pub const _SC_INT_MAX: ::c_int = 104; -pub const _SC_INT_MIN: ::c_int = 105; -pub const _SC_LONG_BIT: ::c_int = 106; -pub const _SC_WORD_BIT: ::c_int = 107; -pub const _SC_MB_LEN_MAX: ::c_int = 108; -pub const _SC_SSIZE_MAX: ::c_int = 110; -pub const _SC_SCHAR_MAX: ::c_int = 111; -pub const _SC_SCHAR_MIN: ::c_int = 112; -pub const _SC_SHRT_MAX: ::c_int = 113; -pub const _SC_SHRT_MIN: ::c_int = 114; -pub const _SC_UCHAR_MAX: ::c_int = 115; -pub const _SC_UINT_MAX: ::c_int = 116; -pub const _SC_ULONG_MAX: ::c_int = 117; -pub const _SC_USHRT_MAX: ::c_int = 118; -pub const _SC_NL_ARGMAX: ::c_int = 119; -pub const _SC_NL_LANGMAX: ::c_int = 120; -pub const _SC_NL_MSGMAX: ::c_int = 121; -pub const _SC_NL_NMAX: ::c_int = 122; -pub const _SC_NL_SETMAX: ::c_int = 123; -pub const _SC_NL_TEXTMAX: ::c_int = 124; -pub const _SC_BASE: ::c_int = 134; -pub const _SC_C_LANG_SUPPORT: ::c_int = 135; -pub const _SC_C_LANG_SUPPORT_R: ::c_int = 136; -pub const _SC_DEVICE_IO: ::c_int = 140; -pub const _SC_DEVICE_SPECIFIC: ::c_int = 141; -pub const _SC_DEVICE_SPECIFIC_R: ::c_int = 142; -pub const _SC_FD_MGMT: ::c_int = 143; -pub const _SC_FIFO: ::c_int = 144; -pub const _SC_PIPE: ::c_int = 145; -pub const _SC_FILE_ATTRIBUTES: ::c_int = 146; -pub const _SC_FILE_LOCKING: ::c_int = 147; -pub const _SC_FILE_SYSTEM: ::c_int = 148; -pub const _SC_MULTI_PROCESS: ::c_int = 150; -pub const _SC_SINGLE_PROCESS: ::c_int = 151; -pub const _SC_NETWORKING: ::c_int = 152; -pub const _SC_REGEX_VERSION: ::c_int = 156; -pub const _SC_SIGNALS: ::c_int = 158; -pub const _SC_SYSTEM_DATABASE: ::c_int = 162; -pub const _SC_SYSTEM_DATABASE_R: ::c_int = 163; -pub const _SC_USER_GROUPS: ::c_int = 166; -pub const _SC_USER_GROUPS_R: ::c_int = 167; -pub const _SC_LEVEL1_ICACHE_SIZE: ::c_int = 185; -pub const _SC_LEVEL1_ICACHE_ASSOC: ::c_int = 186; -pub const _SC_LEVEL1_ICACHE_LINESIZE: ::c_int = 187; -pub const _SC_LEVEL1_DCACHE_SIZE: ::c_int = 188; -pub const _SC_LEVEL1_DCACHE_ASSOC: ::c_int = 189; -pub const _SC_LEVEL1_DCACHE_LINESIZE: ::c_int = 190; -pub const _SC_LEVEL2_CACHE_SIZE: ::c_int = 191; -pub const _SC_LEVEL2_CACHE_ASSOC: ::c_int = 192; -pub const _SC_LEVEL2_CACHE_LINESIZE: ::c_int = 193; -pub const _SC_LEVEL3_CACHE_SIZE: ::c_int = 194; -pub const _SC_LEVEL3_CACHE_ASSOC: ::c_int = 195; -pub const _SC_LEVEL3_CACHE_LINESIZE: ::c_int = 196; -pub const _SC_LEVEL4_CACHE_SIZE: ::c_int = 197; -pub const _SC_LEVEL4_CACHE_ASSOC: ::c_int = 198; -pub const _SC_LEVEL4_CACHE_LINESIZE: ::c_int = 199; -pub const O_ACCMODE: ::c_int = 3; -pub const ST_RELATIME: ::c_ulong = 4096; -pub const NI_MAXHOST: ::socklen_t = 1025; - -pub const ADFS_SUPER_MAGIC: ::c_long = 0x0000adf5; -pub const AFFS_SUPER_MAGIC: ::c_long = 0x0000adff; -pub const CODA_SUPER_MAGIC: ::c_long = 0x73757245; -pub const CRAMFS_MAGIC: ::c_long = 0x28cd3d45; -pub const EFS_SUPER_MAGIC: ::c_long = 0x00414a53; -pub const EXT2_SUPER_MAGIC: ::c_long = 0x0000ef53; -pub const EXT3_SUPER_MAGIC: ::c_long = 0x0000ef53; -pub const EXT4_SUPER_MAGIC: ::c_long = 0x0000ef53; -pub const HPFS_SUPER_MAGIC: ::c_long = 0xf995e849; -pub const HUGETLBFS_MAGIC: ::c_long = 0x958458f6; -pub const ISOFS_SUPER_MAGIC: ::c_long = 0x00009660; -pub const JFFS2_SUPER_MAGIC: ::c_long = 0x000072b6; -pub const MINIX_SUPER_MAGIC: ::c_long = 0x0000137f; -pub const MINIX_SUPER_MAGIC2: ::c_long = 0x0000138f; -pub const MINIX2_SUPER_MAGIC: ::c_long = 0x00002468; -pub const MINIX2_SUPER_MAGIC2: ::c_long = 0x00002478; -pub const MSDOS_SUPER_MAGIC: ::c_long = 0x00004d44; -pub const NCP_SUPER_MAGIC: ::c_long = 0x0000564c; -pub const NFS_SUPER_MAGIC: ::c_long = 0x00006969; -pub const OPENPROM_SUPER_MAGIC: ::c_long = 0x00009fa1; -pub const PROC_SUPER_MAGIC: ::c_long = 0x00009fa0; -pub const QNX4_SUPER_MAGIC: ::c_long = 0x0000002f; -pub const REISERFS_SUPER_MAGIC: ::c_long = 0x52654973; -pub const SMB_SUPER_MAGIC: ::c_long = 0x0000517b; -pub const TMPFS_MAGIC: ::c_long = 0x01021994; -pub const USBDEVICE_SUPER_MAGIC: ::c_long = 0x00009fa2; - -pub const VEOF: usize = 4; - -pub const CPU_SETSIZE: ::c_int = 0x400; - -pub const PTRACE_TRACEME: ::c_uint = 0; -pub const PTRACE_PEEKTEXT: ::c_uint = 1; -pub const PTRACE_PEEKDATA: ::c_uint = 2; -pub const PTRACE_PEEKUSER: ::c_uint = 3; -pub const PTRACE_POKETEXT: ::c_uint = 4; -pub const PTRACE_POKEDATA: ::c_uint = 5; -pub const PTRACE_POKEUSER: ::c_uint = 6; -pub const PTRACE_CONT: ::c_uint = 7; -pub const PTRACE_KILL: ::c_uint = 8; -pub const PTRACE_SINGLESTEP: ::c_uint = 9; -pub const PTRACE_ATTACH: ::c_uint = 16; -pub const PTRACE_SYSCALL: ::c_uint = 24; -pub const PTRACE_SETOPTIONS: ::c_uint = 0x4200; -pub const PTRACE_GETEVENTMSG: ::c_uint = 0x4201; -pub const PTRACE_GETSIGINFO: ::c_uint = 0x4202; -pub const PTRACE_SETSIGINFO: ::c_uint = 0x4203; -pub const PTRACE_GETREGSET: ::c_uint = 0x4204; -pub const PTRACE_SETREGSET: ::c_uint = 0x4205; -pub const PTRACE_SEIZE: ::c_uint = 0x4206; -pub const PTRACE_INTERRUPT: ::c_uint = 0x4207; -pub const PTRACE_LISTEN: ::c_uint = 0x4208; -pub const PTRACE_PEEKSIGINFO: ::c_uint = 0x4209; - -pub const EPOLLWAKEUP: ::c_int = 0x20000000; - -pub const MAP_HUGETLB: ::c_int = 0x040000; - -pub const SEEK_DATA: ::c_int = 3; -pub const SEEK_HOLE: ::c_int = 4; - -pub const TCSANOW: ::c_int = 0; -pub const TCSADRAIN: ::c_int = 1; -pub const TCSAFLUSH: ::c_int = 2; - -pub const TIOCLINUX: ::c_ulong = 0x541C; -pub const TIOCGSERIAL: ::c_ulong = 0x541E; - -pub const RTLD_DEEPBIND: ::c_int = 0x8; -pub const RTLD_GLOBAL: ::c_int = 0x100; -pub const RTLD_NOLOAD: ::c_int = 0x4; - -pub const LINUX_REBOOT_MAGIC1: ::c_int = 0xfee1dead; -pub const LINUX_REBOOT_MAGIC2: ::c_int = 672274793; -pub const LINUX_REBOOT_MAGIC2A: ::c_int = 85072278; -pub const LINUX_REBOOT_MAGIC2B: ::c_int = 369367448; -pub const LINUX_REBOOT_MAGIC2C: ::c_int = 537993216; - -pub const LINUX_REBOOT_CMD_RESTART: ::c_int = 0x01234567; -pub const LINUX_REBOOT_CMD_HALT: ::c_int = 0xCDEF0123; -pub const LINUX_REBOOT_CMD_CAD_ON: ::c_int = 0x89ABCDEF; -pub const LINUX_REBOOT_CMD_CAD_OFF: ::c_int = 0x00000000; -pub const LINUX_REBOOT_CMD_POWER_OFF: ::c_int = 0x4321FEDC; -pub const LINUX_REBOOT_CMD_RESTART2: ::c_int = 0xA1B2C3D4; -pub const LINUX_REBOOT_CMD_SW_SUSPEND: ::c_int = 0xD000FCE2; -pub const LINUX_REBOOT_CMD_KEXEC: ::c_int = 0x45584543; - -pub const NETLINK_ROUTE: ::c_int = 0; -pub const NETLINK_UNUSED: ::c_int = 1; -pub const NETLINK_USERSOCK: ::c_int = 2; -pub const NETLINK_FIREWALL: ::c_int = 3; -pub const NETLINK_SOCK_DIAG: ::c_int = 4; -pub const NETLINK_NFLOG: ::c_int = 5; -pub const NETLINK_XFRM: ::c_int = 6; -pub const NETLINK_SELINUX: ::c_int = 7; -pub const NETLINK_ISCSI: ::c_int = 8; -pub const NETLINK_AUDIT: ::c_int = 9; -pub const NETLINK_FIB_LOOKUP: ::c_int = 10; -pub const NETLINK_CONNECTOR: ::c_int = 11; -pub const NETLINK_NETFILTER: ::c_int = 12; -pub const NETLINK_IP6_FW: ::c_int = 13; -pub const NETLINK_DNRTMSG: ::c_int = 14; -pub const NETLINK_KOBJECT_UEVENT: ::c_int = 15; -pub const NETLINK_GENERIC: ::c_int = 16; -pub const NETLINK_SCSITRANSPORT: ::c_int = 18; -pub const NETLINK_ECRYPTFS: ::c_int = 19; -pub const NETLINK_RDMA: ::c_int = 20; -pub const NETLINK_CRYPTO: ::c_int = 21; -pub const NETLINK_INET_DIAG: ::c_int = NETLINK_SOCK_DIAG; - -pub const MAX_LINKS: ::c_int = 32; - -pub const NLM_F_REQUEST: ::c_int = 1; -pub const NLM_F_MULTI: ::c_int = 2; -pub const NLM_F_ACK: ::c_int = 4; -pub const NLM_F_ECHO: ::c_int = 8; -pub const NLM_F_DUMP_INTR: ::c_int = 16; -pub const NLM_F_DUMP_FILTERED: ::c_int = 32; - -pub const NLM_F_ROOT: ::c_int = 0x100; -pub const NLM_F_MATCH: ::c_int = 0x200; -pub const NLM_F_ATOMIC: ::c_int = 0x400; -pub const NLM_F_DUMP: ::c_int = NLM_F_ROOT | NLM_F_MATCH; - -pub const NLM_F_REPLACE: ::c_int = 0x100; -pub const NLM_F_EXCL: ::c_int = 0x200; -pub const NLM_F_CREATE: ::c_int = 0x400; -pub const NLM_F_APPEND: ::c_int = 0x800; - -pub const NLMSG_NOOP: ::c_int = 0x1; -pub const NLMSG_ERROR: ::c_int = 0x2; -pub const NLMSG_DONE: ::c_int = 0x3; -pub const NLMSG_OVERRUN: ::c_int = 0x4; -pub const NLMSG_MIN_TYPE: ::c_int = 0x10; - -pub const NETLINK_ADD_MEMBERSHIP: ::c_int = 1; -pub const NETLINK_DROP_MEMBERSHIP: ::c_int = 2; -pub const NETLINK_PKTINFO: ::c_int = 3; -pub const NETLINK_BROADCAST_ERROR: ::c_int = 4; -pub const NETLINK_NO_ENOBUFS: ::c_int = 5; -pub const NETLINK_RX_RING: ::c_int = 6; -pub const NETLINK_TX_RING: ::c_int = 7; -pub const NETLINK_LISTEN_ALL_NSID: ::c_int = 8; -pub const NETLINK_LIST_MEMBERSHIPS: ::c_int = 9; -pub const NETLINK_CAP_ACK: ::c_int = 10; - -pub const NLA_F_NESTED: ::c_int = 1 << 15; -pub const NLA_F_NET_BYTEORDER: ::c_int = 1 << 14; -pub const NLA_TYPE_MASK: ::c_int = !(NLA_F_NESTED | NLA_F_NET_BYTEORDER); - -pub const TIOCM_LE: ::c_int = 0x001; -pub const TIOCM_DTR: ::c_int = 0x002; -pub const TIOCM_RTS: ::c_int = 0x004; -pub const TIOCM_ST: ::c_int = 0x008; -pub const TIOCM_SR: ::c_int = 0x010; -pub const TIOCM_CTS: ::c_int = 0x020; -pub const TIOCM_CAR: ::c_int = 0x040; -pub const TIOCM_RNG: ::c_int = 0x080; -pub const TIOCM_DSR: ::c_int = 0x100; -pub const TIOCM_CD: ::c_int = TIOCM_CAR; -pub const TIOCM_RI: ::c_int = TIOCM_RNG; - -#[doc(hidden)] -pub const AF_MAX: ::c_int = 42; -#[doc(hidden)] -pub const PF_MAX: ::c_int = AF_MAX; - -cfg_if! { - if #[cfg(any(target_arch = "arm", target_arch = "x86", - target_arch = "x86_64"))] { - pub const PTHREAD_STACK_MIN: ::size_t = 16384; - } else if #[cfg(target_arch = "sparc64")] { - pub const PTHREAD_STACK_MIN: ::size_t = 0x6000; - } else { - pub const PTHREAD_STACK_MIN: ::size_t = 131072; - } -} - -extern { - pub fn utmpxname(file: *const ::c_char) -> ::c_int; - pub fn getutxent() -> *mut utmpx; - pub fn getutxid(ut: *const utmpx) -> *mut utmpx; - pub fn getutxline(ut: *const utmpx) -> *mut utmpx; - pub fn pututxline(ut: *const utmpx) -> *mut utmpx; - pub fn setutxent(); - pub fn endutxent(); - pub fn getpt() -> ::c_int; -} - -#[link(name = "util")] -extern { - pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; - pub fn backtrace(buf: *mut *mut ::c_void, - sz: ::c_int) -> ::c_int; - pub fn glob64(pattern: *const ::c_char, - flags: ::c_int, - errfunc: ::dox::Option ::c_int>, - pglob: *mut glob64_t) -> ::c_int; - pub fn globfree64(pglob: *mut glob64_t); - pub fn ptrace(request: ::c_uint, ...) -> ::c_long; - pub fn pthread_attr_getaffinity_np(attr: *const ::pthread_attr_t, - cpusetsize: ::size_t, - cpuset: *mut ::cpu_set_t) -> ::c_int; - pub fn pthread_attr_setaffinity_np(attr: *mut ::pthread_attr_t, - cpusetsize: ::size_t, - cpuset: *const ::cpu_set_t) -> ::c_int; - pub fn getpriority(which: ::__priority_which_t, who: ::id_t) -> ::c_int; - pub fn setpriority(which: ::__priority_which_t, who: ::id_t, - prio: ::c_int) -> ::c_int; - pub fn pthread_getaffinity_np(thread: ::pthread_t, - cpusetsize: ::size_t, - cpuset: *mut ::cpu_set_t) -> ::c_int; - pub fn pthread_setaffinity_np(thread: ::pthread_t, - cpusetsize: ::size_t, - cpuset: *const ::cpu_set_t) -> ::c_int; - pub fn pthread_rwlockattr_getkind_np(attr: *const ::pthread_rwlockattr_t, - val: *mut ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_setkind_np(attr: *mut ::pthread_rwlockattr_t, - val: ::c_int) -> ::c_int; - pub fn sched_getcpu() -> ::c_int; -} - -cfg_if! { - if #[cfg(any(target_arch = "x86", - target_arch = "arm", - target_arch = "powerpc"))] { - mod b32; - pub use self::b32::*; - } else if #[cfg(any(target_arch = "x86_64", - target_arch = "aarch64", - target_arch = "powerpc64", - target_arch = "sparc64"))] { - mod b64; - pub use self::b64::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/s390x.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/s390x.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/linux/s390x.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/linux/s390x.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1283 +0,0 @@ -pub type blkcnt_t = i64; -pub type blksize_t = i64; -pub type c_char = u8; -pub type c_long = i64; -pub type c_ulong = u64; -pub type fsblkcnt_t = u64; -pub type fsfilcnt_t = u64; -pub type ino_t = u64; -pub type nlink_t = u64; -pub type off_t = i64; -pub type rlim_t = u64; -pub type suseconds_t = i64; -pub type time_t = i64; -pub type wchar_t = i32; -pub type greg_t = u64; -pub type clock_t = i64; -pub type shmatt_t = ::c_ulong; -pub type msgqnum_t = ::c_ulong; -pub type msglen_t = ::c_ulong; -pub type __fsword_t = ::c_long; -pub type __priority_which_t = ::c_uint; -pub type __u64 = u64; - -s! { - pub struct aiocb { - pub aio_fildes: ::c_int, - pub aio_lio_opcode: ::c_int, - pub aio_reqprio: ::c_int, - pub aio_buf: *mut ::c_void, - pub aio_nbytes: ::size_t, - pub aio_sigevent: ::sigevent, - __next_prio: *mut aiocb, - __abs_prio: ::c_int, - __policy: ::c_int, - __error_code: ::c_int, - __return_value: ::ssize_t, - pub aio_offset: off_t, - #[cfg(target_pointer_width = "32")] - __unused1: [::c_char; 4], - __glibc_reserved: [::c_char; 32] - } - - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - st_pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - __glibc_reserved: [::c_long; 3], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - pub st_ino: ::ino64_t, - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - st_pad0: ::c_int, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt64_t, - __glibc_reserved: [::c_long; 3], - } - - pub struct pthread_attr_t { - __size: [::c_ulong; 7] - } - - pub struct sigaction { - pub sa_sigaction: ::sighandler_t, - __glibc_reserved0: ::c_int, - pub sa_flags: ::c_int, - pub sa_restorer: ::dox::Option, - pub sa_mask: sigset_t, - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_flags: ::c_int, - pub ss_size: ::size_t, - } - - pub struct sigset_t { - __size: [::c_ulong; 16], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_errno: ::c_int, - pub si_code: ::c_int, - _pad: ::c_int, - _pad2: [::c_long; 14], - } - - pub struct ipc_perm { - pub __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::mode_t, - pub __seq: ::c_ushort, - __pad1: ::c_ushort, - __unused1: ::c_ulong, - __unused2: ::c_ulong - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __unused4: ::c_ulong, - __unused5: ::c_ulong - } - - pub struct statfs { - pub f_type: ::c_uint, - pub f_bsize: ::c_uint, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_uint, - pub f_frsize: ::c_uint, - pub f_flags: ::c_uint, - f_spare: [::c_uint; 4], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::size_t, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::size_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::size_t, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; ::NCCS], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } - - pub struct termios2 { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; 19], - pub c_ispeed: ::speed_t, - pub c_ospeed: ::speed_t, - } - - pub struct sysinfo { - pub uptime: ::c_long, - pub loads: [::c_ulong; 3], - pub totalram: ::c_ulong, - pub freeram: ::c_ulong, - pub sharedram: ::c_ulong, - pub bufferram: ::c_ulong, - pub totalswap: ::c_ulong, - pub freeswap: ::c_ulong, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: ::c_ulong, - pub freehigh: ::c_ulong, - pub mem_unit: ::c_uint, - pub _f: [::c_char; 0], - } - - pub struct glob64_t { - pub gl_pathc: ::size_t, - pub gl_pathv: *mut *mut ::c_char, - pub gl_offs: ::size_t, - pub gl_flags: ::c_int, - - __unused1: *mut ::c_void, - __unused2: *mut ::c_void, - __unused3: *mut ::c_void, - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - } - - pub struct flock { - pub l_type: ::c_short, - pub l_whence: ::c_short, - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_pid: ::pid_t, - } - - // FIXME this is actually a union - pub struct sem_t { - __size: [::c_char; 32], - __align: [::c_long; 0], - } - - pub struct __psw_t { - pub mask: u64, - pub addr: u64, - } - - // FIXME: This is actually a union. - pub struct fpreg_t { - pub d: ::c_double, - // f: ::c_float, - } - - pub struct fpregset_t { - pub fpc: u32, - __pad: u32, - pub fprs: [fpreg_t; 16], - } - - pub struct mcontext_t { - pub psw: __psw_t, - pub gregs: [u64; 16], - pub aregs: [u32; 16], - pub fpregs: fpregset_t, - } - - pub struct ucontext_t { - pub uc_flags: ::c_ulong, - pub uc_link: *mut ucontext_t, - pub uc_stack: ::stack_t, - pub uc_mcontext: mcontext_t, - pub uc_sigmask: ::sigset_t, - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - pub msg_stime: ::time_t, - pub msg_rtime: ::time_t, - pub msg_ctime: ::time_t, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __glibc_reserved4: ::c_ulong, - __glibc_reserved5: ::c_ulong, - } - - pub struct statfs64 { - pub f_type: ::c_uint, - pub f_bsize: ::c_uint, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_fsid: ::fsid_t, - pub f_namelen: ::c_uint, - pub f_frsize: ::c_uint, - pub f_flags: ::c_uint, - pub f_spare: [::c_uint; 4], - } - - pub struct statvfs64 { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: u64, - pub f_bfree: u64, - pub f_bavail: u64, - pub f_files: u64, - pub f_ffree: u64, - pub f_favail: u64, - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } -} - -pub const SFD_CLOEXEC: ::c_int = 0x080000; - -pub const NCCS: usize = 32; - -pub const O_TRUNC: ::c_int = 512; -pub const O_LARGEFILE: ::c_int = 0; -pub const O_NOATIME: ::c_int = 0o1000000; -pub const O_CLOEXEC: ::c_int = 0x80000; -pub const O_PATH: ::c_int = 0o10000000; -pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; - -pub const EBFONT: ::c_int = 59; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENONET: ::c_int = 64; -pub const ENOPKG: ::c_int = 65; -pub const EREMOTE: ::c_int = 66; -pub const ENOLINK: ::c_int = 67; -pub const EADV: ::c_int = 68; -pub const ESRMNT: ::c_int = 69; -pub const ECOMM: ::c_int = 70; -pub const EPROTO: ::c_int = 71; -pub const EDOTDOT: ::c_int = 73; - -pub const SA_NODEFER: ::c_int = 0x40000000; -pub const SA_RESETHAND: ::c_int = 0x80000000; -pub const SA_RESTART: ::c_int = 0x10000000; -pub const SA_NOCLDSTOP: ::c_int = 0x00000001; - -pub const EPOLL_CLOEXEC: ::c_int = 0x80000; - -pub const EFD_CLOEXEC: ::c_int = 0x80000; - -pub const POSIX_FADV_DONTNEED: ::c_int = 6; -pub const POSIX_FADV_NOREUSE: ::c_int = 7; - -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; -pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; - -pub const EADDRINUSE: ::c_int = 98; -pub const EADDRNOTAVAIL: ::c_int = 99; -pub const ECONNABORTED: ::c_int = 103; -pub const ECONNREFUSED: ::c_int = 111; -pub const ECONNRESET: ::c_int = 104; -pub const EDEADLK: ::c_int = 35; -pub const ENOSYS: ::c_int = 38; -pub const ENOTCONN: ::c_int = 107; -pub const ETIMEDOUT: ::c_int = 110; -pub const FIOCLEX: ::c_ulong = 0x5451; -pub const FIONBIO: ::c_ulong = 0x5421; -pub const MAP_ANON: ::c_int = 0x20; -pub const O_ACCMODE: ::c_int = 3; -pub const O_APPEND: ::c_int = 1024; -pub const O_CREAT: ::c_int = 64; -pub const O_EXCL: ::c_int = 128; -pub const O_NONBLOCK: ::c_int = 2048; -pub const PTHREAD_STACK_MIN: ::size_t = 16384; -pub const RLIM_INFINITY: ::rlim_t = 0xffffffffffffffff; -pub const SA_NOCLDWAIT: ::c_int = 2; -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 4; -pub const SIGBUS: ::c_int = 7; -pub const SIGSTKSZ: ::size_t = 0x2000; -pub const MINSIGSTKSZ: ::size_t = 2048; -pub const SIG_SETMASK: ::c_int = 2; -pub const SOCK_DGRAM: ::c_int = 2; -pub const SOCK_STREAM: ::c_int = 1; -pub const SOL_SOCKET: ::c_int = 1; -pub const SO_BROADCAST: ::c_int = 6; -pub const SO_ERROR: ::c_int = 4; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_REUSEADDR: ::c_int = 2; -pub const SO_SNDTIMEO: ::c_int = 21; -pub const SO_BINDTODEVICE: ::c_int = 25; -pub const SO_TIMESTAMP: ::c_int = 29; -pub const SO_MARK: ::c_int = 36; -pub const SO_PROTOCOL: ::c_int = 38; -pub const SO_DOMAIN: ::c_int = 39; -pub const SO_RXQ_OVFL: ::c_int = 40; -pub const SO_PEEK_OFF: ::c_int = 42; -pub const SO_BUSY_POLL: ::c_int = 46; - -pub const RLIMIT_RSS: ::c_int = 5; -pub const RLIMIT_NOFILE: ::c_int = 7; -pub const RLIMIT_AS: ::c_int = 9; -pub const RLIMIT_NPROC: ::c_int = 6; -pub const RLIMIT_MEMLOCK: ::c_int = 8; -pub const RLIMIT_RTTIME: ::c_int = 15; -pub const RLIMIT_NLIMITS: ::c_int = 16; - -pub const O_NOCTTY: ::c_int = 256; -pub const O_SYNC: ::c_int = 1052672; -pub const O_RSYNC: ::c_int = 1052672; -pub const O_DSYNC: ::c_int = 4096; -pub const O_FSYNC: ::c_int = 0x101000; -pub const O_DIRECT: ::c_int = 0x4000; -pub const O_DIRECTORY: ::c_int = 0x10000; -pub const O_NOFOLLOW: ::c_int = 0x20000; - -pub const SOCK_NONBLOCK: ::c_int = O_NONBLOCK; - -pub const LC_PAPER: ::c_int = 7; -pub const LC_NAME: ::c_int = 8; -pub const LC_ADDRESS: ::c_int = 9; -pub const LC_TELEPHONE: ::c_int = 10; -pub const LC_MEASUREMENT: ::c_int = 11; -pub const LC_IDENTIFICATION: ::c_int = 12; -pub const LC_PAPER_MASK: ::c_int = (1 << LC_PAPER); -pub const LC_NAME_MASK: ::c_int = (1 << LC_NAME); -pub const LC_ADDRESS_MASK: ::c_int = (1 << LC_ADDRESS); -pub const LC_TELEPHONE_MASK: ::c_int = (1 << LC_TELEPHONE); -pub const LC_MEASUREMENT_MASK: ::c_int = (1 << LC_MEASUREMENT); -pub const LC_IDENTIFICATION_MASK: ::c_int = (1 << LC_IDENTIFICATION); -pub const LC_ALL_MASK: ::c_int = ::LC_CTYPE_MASK - | ::LC_NUMERIC_MASK - | ::LC_TIME_MASK - | ::LC_COLLATE_MASK - | ::LC_MONETARY_MASK - | ::LC_MESSAGES_MASK - | LC_PAPER_MASK - | LC_NAME_MASK - | LC_ADDRESS_MASK - | LC_TELEPHONE_MASK - | LC_MEASUREMENT_MASK - | LC_IDENTIFICATION_MASK; - -pub const MAP_ANONYMOUS: ::c_int = 0x0020; -pub const MAP_GROWSDOWN: ::c_int = 0x0100; -pub const MAP_DENYWRITE: ::c_int = 0x0800; -pub const MAP_EXECUTABLE: ::c_int = 0x01000; -pub const MAP_LOCKED: ::c_int = 0x02000; -pub const MAP_NORESERVE: ::c_int = 0x04000; -pub const MAP_POPULATE: ::c_int = 0x08000; -pub const MAP_NONBLOCK: ::c_int = 0x010000; -pub const MAP_STACK: ::c_int = 0x020000; - -pub const EDEADLOCK: ::c_int = 35; -pub const ENAMETOOLONG: ::c_int = 36; -pub const ENOLCK: ::c_int = 37; -pub const ENOTEMPTY: ::c_int = 39; -pub const ELOOP: ::c_int = 40; -pub const ENOMSG: ::c_int = 42; -pub const EIDRM: ::c_int = 43; -pub const ECHRNG: ::c_int = 44; -pub const EL2NSYNC: ::c_int = 45; -pub const EL3HLT: ::c_int = 46; -pub const EL3RST: ::c_int = 47; -pub const ELNRNG: ::c_int = 48; -pub const EUNATCH: ::c_int = 49; -pub const ENOCSI: ::c_int = 50; -pub const EL2HLT: ::c_int = 51; -pub const EBADE: ::c_int = 52; -pub const EBADR: ::c_int = 53; -pub const EXFULL: ::c_int = 54; -pub const ENOANO: ::c_int = 55; -pub const EBADRQC: ::c_int = 56; -pub const EBADSLT: ::c_int = 57; -pub const EMULTIHOP: ::c_int = 72; -pub const EOVERFLOW: ::c_int = 75; -pub const ENOTUNIQ: ::c_int = 76; -pub const EBADFD: ::c_int = 77; -pub const EBADMSG: ::c_int = 74; -pub const EREMCHG: ::c_int = 78; -pub const ELIBACC: ::c_int = 79; -pub const ELIBBAD: ::c_int = 80; -pub const ELIBSCN: ::c_int = 81; -pub const ELIBMAX: ::c_int = 82; -pub const ELIBEXEC: ::c_int = 83; -pub const EILSEQ: ::c_int = 84; -pub const ERESTART: ::c_int = 85; -pub const ESTRPIPE: ::c_int = 86; -pub const EUSERS: ::c_int = 87; -pub const ENOTSOCK: ::c_int = 88; -pub const EDESTADDRREQ: ::c_int = 89; -pub const EMSGSIZE: ::c_int = 90; -pub const EPROTOTYPE: ::c_int = 91; -pub const ENOPROTOOPT: ::c_int = 92; -pub const EPROTONOSUPPORT: ::c_int = 93; -pub const ESOCKTNOSUPPORT: ::c_int = 94; -pub const EOPNOTSUPP: ::c_int = 95; -pub const ENOTSUP: ::c_int = EOPNOTSUPP; -pub const EPFNOSUPPORT: ::c_int = 96; -pub const EAFNOSUPPORT: ::c_int = 97; -pub const ENETDOWN: ::c_int = 100; -pub const ENETUNREACH: ::c_int = 101; -pub const ENETRESET: ::c_int = 102; -pub const ENOBUFS: ::c_int = 105; -pub const EISCONN: ::c_int = 106; -pub const ESHUTDOWN: ::c_int = 108; -pub const ETOOMANYREFS: ::c_int = 109; -pub const EHOSTDOWN: ::c_int = 112; -pub const EHOSTUNREACH: ::c_int = 113; -pub const EALREADY: ::c_int = 114; -pub const EINPROGRESS: ::c_int = 115; -pub const ESTALE: ::c_int = 116; -pub const EUCLEAN: ::c_int = 117; -pub const ENOTNAM: ::c_int = 118; -pub const ENAVAIL: ::c_int = 119; -pub const EISNAM: ::c_int = 120; -pub const EREMOTEIO: ::c_int = 121; -pub const EDQUOT: ::c_int = 122; -pub const ENOMEDIUM: ::c_int = 123; -pub const EMEDIUMTYPE: ::c_int = 124; -pub const ECANCELED: ::c_int = 125; -pub const ENOKEY: ::c_int = 126; -pub const EKEYEXPIRED: ::c_int = 127; -pub const EKEYREVOKED: ::c_int = 128; -pub const EKEYREJECTED: ::c_int = 129; -pub const EOWNERDEAD: ::c_int = 130; -pub const ENOTRECOVERABLE: ::c_int = 131; -pub const EHWPOISON: ::c_int = 133; -pub const ERFKILL: ::c_int = 132; - -pub const SOCK_SEQPACKET: ::c_int = 5; - -pub const SO_TYPE: ::c_int = 3; -pub const SO_DONTROUTE: ::c_int = 5; -pub const SO_SNDBUF: ::c_int = 7; -pub const SO_RCVBUF: ::c_int = 8; -pub const SO_KEEPALIVE: ::c_int = 9; -pub const SO_OOBINLINE: ::c_int = 10; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_LINGER: ::c_int = 13; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_REUSEPORT: ::c_int = 15; -pub const SO_PASSCRED: ::c_int = 16; -pub const SO_PEERCRED: ::c_int = 17; -pub const SO_RCVLOWAT: ::c_int = 18; -pub const SO_SNDLOWAT: ::c_int = 19; -pub const SO_ACCEPTCONN: ::c_int = 30; -pub const SO_SNDBUFFORCE: ::c_int = 32; -pub const SO_RCVBUFFORCE: ::c_int = 33; - -pub const TCP_COOKIE_TRANSACTIONS: ::c_int = 15; -pub const TCP_THIN_LINEAR_TIMEOUTS: ::c_int = 16; -pub const TCP_THIN_DUPACK: ::c_int = 17; -pub const TCP_USER_TIMEOUT: ::c_int = 18; -pub const TCP_REPAIR: ::c_int = 19; -pub const TCP_REPAIR_QUEUE: ::c_int = 20; -pub const TCP_QUEUE_SEQ: ::c_int = 21; -pub const TCP_REPAIR_OPTIONS: ::c_int = 22; -pub const TCP_FASTOPEN: ::c_int = 23; -pub const TCP_TIMESTAMP: ::c_int = 24; - -pub const SIGCHLD: ::c_int = 17; -pub const SIGUSR1: ::c_int = 10; -pub const SIGUSR2: ::c_int = 12; -pub const SIGCONT: ::c_int = 18; -pub const SIGSTOP: ::c_int = 19; -pub const SIGTSTP: ::c_int = 20; -pub const SIGURG: ::c_int = 23; -pub const SIGIO: ::c_int = 29; -pub const SIGSYS: ::c_int = 31; -pub const SIGSTKFLT: ::c_int = 16; -pub const SIGUNUSED: ::c_int = 31; -pub const SIGTTIN: ::c_int = 21; -pub const SIGTTOU: ::c_int = 22; -pub const SIGXCPU: ::c_int = 24; -pub const SIGXFSZ: ::c_int = 25; -pub const SIGVTALRM: ::c_int = 26; -pub const SIGPROF: ::c_int = 27; -pub const SIGWINCH: ::c_int = 28; -pub const SIGPOLL: ::c_int = 29; -pub const SIGPWR: ::c_int = 30; -pub const SIG_BLOCK: ::c_int = 0x000000; -pub const SIG_UNBLOCK: ::c_int = 0x01; - -pub const BUFSIZ: ::c_uint = 8192; -pub const TMP_MAX: ::c_uint = 238328; -pub const FOPEN_MAX: ::c_uint = 16; -pub const POSIX_MADV_DONTNEED: ::c_int = 4; -pub const _SC_EQUIV_CLASS_MAX: ::c_int = 41; -pub const _SC_CHARCLASS_NAME_MAX: ::c_int = 45; -pub const _SC_PII: ::c_int = 53; -pub const _SC_PII_XTI: ::c_int = 54; -pub const _SC_PII_SOCKET: ::c_int = 55; -pub const _SC_PII_INTERNET: ::c_int = 56; -pub const _SC_PII_OSI: ::c_int = 57; -pub const _SC_POLL: ::c_int = 58; -pub const _SC_SELECT: ::c_int = 59; -pub const _SC_PII_INTERNET_STREAM: ::c_int = 61; -pub const _SC_PII_INTERNET_DGRAM: ::c_int = 62; -pub const _SC_PII_OSI_COTS: ::c_int = 63; -pub const _SC_PII_OSI_CLTS: ::c_int = 64; -pub const _SC_PII_OSI_M: ::c_int = 65; -pub const _SC_T_IOV_MAX: ::c_int = 66; -pub const _SC_2_C_VERSION: ::c_int = 96; -pub const _SC_CHAR_BIT: ::c_int = 101; -pub const _SC_CHAR_MAX: ::c_int = 102; -pub const _SC_CHAR_MIN: ::c_int = 103; -pub const _SC_INT_MAX: ::c_int = 104; -pub const _SC_INT_MIN: ::c_int = 105; -pub const _SC_LONG_BIT: ::c_int = 106; -pub const _SC_WORD_BIT: ::c_int = 107; -pub const _SC_MB_LEN_MAX: ::c_int = 108; -pub const _SC_SSIZE_MAX: ::c_int = 110; -pub const _SC_SCHAR_MAX: ::c_int = 111; -pub const _SC_SCHAR_MIN: ::c_int = 112; -pub const _SC_SHRT_MAX: ::c_int = 113; -pub const _SC_SHRT_MIN: ::c_int = 114; -pub const _SC_UCHAR_MAX: ::c_int = 115; -pub const _SC_UINT_MAX: ::c_int = 116; -pub const _SC_ULONG_MAX: ::c_int = 117; -pub const _SC_USHRT_MAX: ::c_int = 118; -pub const _SC_NL_ARGMAX: ::c_int = 119; -pub const _SC_NL_LANGMAX: ::c_int = 120; -pub const _SC_NL_MSGMAX: ::c_int = 121; -pub const _SC_NL_NMAX: ::c_int = 122; -pub const _SC_NL_SETMAX: ::c_int = 123; -pub const _SC_NL_TEXTMAX: ::c_int = 124; -pub const _SC_BASE: ::c_int = 134; -pub const _SC_C_LANG_SUPPORT: ::c_int = 135; -pub const _SC_C_LANG_SUPPORT_R: ::c_int = 136; -pub const _SC_DEVICE_IO: ::c_int = 140; -pub const _SC_DEVICE_SPECIFIC: ::c_int = 141; -pub const _SC_DEVICE_SPECIFIC_R: ::c_int = 142; -pub const _SC_FD_MGMT: ::c_int = 143; -pub const _SC_FIFO: ::c_int = 144; -pub const _SC_PIPE: ::c_int = 145; -pub const _SC_FILE_ATTRIBUTES: ::c_int = 146; -pub const _SC_FILE_LOCKING: ::c_int = 147; -pub const _SC_FILE_SYSTEM: ::c_int = 148; -pub const _SC_MULTI_PROCESS: ::c_int = 150; -pub const _SC_SINGLE_PROCESS: ::c_int = 151; -pub const _SC_NETWORKING: ::c_int = 152; -pub const _SC_REGEX_VERSION: ::c_int = 156; -pub const _SC_SIGNALS: ::c_int = 158; -pub const _SC_SYSTEM_DATABASE: ::c_int = 162; -pub const _SC_SYSTEM_DATABASE_R: ::c_int = 163; -pub const _SC_USER_GROUPS: ::c_int = 166; -pub const _SC_USER_GROUPS_R: ::c_int = 167; -pub const _SC_LEVEL1_ICACHE_SIZE: ::c_int = 185; -pub const _SC_LEVEL1_ICACHE_ASSOC: ::c_int = 186; -pub const _SC_LEVEL1_ICACHE_LINESIZE: ::c_int = 187; -pub const _SC_LEVEL1_DCACHE_SIZE: ::c_int = 188; -pub const _SC_LEVEL1_DCACHE_ASSOC: ::c_int = 189; -pub const _SC_LEVEL1_DCACHE_LINESIZE: ::c_int = 190; -pub const _SC_LEVEL2_CACHE_SIZE: ::c_int = 191; -pub const _SC_LEVEL2_CACHE_ASSOC: ::c_int = 192; -pub const _SC_LEVEL2_CACHE_LINESIZE: ::c_int = 193; -pub const _SC_LEVEL3_CACHE_SIZE: ::c_int = 194; -pub const _SC_LEVEL3_CACHE_ASSOC: ::c_int = 195; -pub const _SC_LEVEL3_CACHE_LINESIZE: ::c_int = 196; -pub const _SC_LEVEL4_CACHE_SIZE: ::c_int = 197; -pub const _SC_LEVEL4_CACHE_ASSOC: ::c_int = 198; -pub const _SC_LEVEL4_CACHE_LINESIZE: ::c_int = 199; -pub const O_ASYNC: ::c_int = 0x2000; -pub const O_NDELAY: ::c_int = 0x800; -pub const ST_RELATIME: ::c_ulong = 4096; -pub const NI_MAXHOST: ::socklen_t = 1025; - -pub const ADFS_SUPER_MAGIC: ::c_int = 0x0000adf5; -pub const AFFS_SUPER_MAGIC: ::c_int = 0x0000adff; -pub const CODA_SUPER_MAGIC: ::c_int = 0x73757245; -pub const CRAMFS_MAGIC: ::c_int = 0x28cd3d45; -pub const EFS_SUPER_MAGIC: ::c_int = 0x00414a53; -pub const EXT2_SUPER_MAGIC: ::c_int = 0x0000ef53; -pub const EXT3_SUPER_MAGIC: ::c_int = 0x0000ef53; -pub const EXT4_SUPER_MAGIC: ::c_int = 0x0000ef53; -pub const HPFS_SUPER_MAGIC: ::c_int = 0xf995e849; -pub const HUGETLBFS_MAGIC: ::c_int = 0x958458f6; -pub const ISOFS_SUPER_MAGIC: ::c_int = 0x00009660; -pub const JFFS2_SUPER_MAGIC: ::c_int = 0x000072b6; -pub const MINIX_SUPER_MAGIC: ::c_int = 0x0000137f; -pub const MINIX_SUPER_MAGIC2: ::c_int = 0x0000138f; -pub const MINIX2_SUPER_MAGIC: ::c_int = 0x00002468; -pub const MINIX2_SUPER_MAGIC2: ::c_int = 0x00002478; -pub const MSDOS_SUPER_MAGIC: ::c_int = 0x00004d44; -pub const NCP_SUPER_MAGIC: ::c_int = 0x0000564c; -pub const NFS_SUPER_MAGIC: ::c_int = 0x00006969; -pub const OPENPROM_SUPER_MAGIC: ::c_int = 0x00009fa1; -pub const PROC_SUPER_MAGIC: ::c_int = 0x00009fa0; -pub const QNX4_SUPER_MAGIC: ::c_int = 0x0000002f; -pub const REISERFS_SUPER_MAGIC: ::c_int = 0x52654973; -pub const SMB_SUPER_MAGIC: ::c_int = 0x0000517b; -pub const TMPFS_MAGIC: ::c_int = 0x01021994; -pub const USBDEVICE_SUPER_MAGIC: ::c_int = 0x00009fa2; - -pub const VEOF: usize = 4; -pub const VEOL: usize = 11; -pub const VEOL2: usize = 16; -pub const VMIN: usize = 6; -pub const IEXTEN: ::tcflag_t = 0x00008000; -pub const TOSTOP: ::tcflag_t = 0x00000100; -pub const FLUSHO: ::tcflag_t = 0x00001000; - -pub const CPU_SETSIZE: ::c_int = 0x400; - -pub const EXTPROC: ::tcflag_t = 0x00010000; - -pub const PTRACE_TRACEME: ::c_uint = 0; -pub const PTRACE_PEEKTEXT: ::c_uint = 1; -pub const PTRACE_PEEKDATA: ::c_uint = 2; -pub const PTRACE_PEEKUSER: ::c_uint = 3; -pub const PTRACE_POKETEXT: ::c_uint = 4; -pub const PTRACE_POKEDATA: ::c_uint = 5; -pub const PTRACE_POKEUSER: ::c_uint = 6; -pub const PTRACE_CONT: ::c_uint = 7; -pub const PTRACE_KILL: ::c_uint = 8; -pub const PTRACE_SINGLESTEP: ::c_uint = 9; -pub const PTRACE_GETREGS: ::c_uint = 12; -pub const PTRACE_SETREGS: ::c_uint = 13; -pub const PTRACE_GETFPREGS: ::c_uint = 14; -pub const PTRACE_SETFPREGS: ::c_uint = 15; -pub const PTRACE_ATTACH: ::c_uint = 16; -pub const PTRACE_DETACH: ::c_uint = 17; -pub const PTRACE_SYSCALL: ::c_uint = 24; -pub const PTRACE_SETOPTIONS: ::c_uint = 0x4200; -pub const PTRACE_GETEVENTMSG: ::c_uint = 0x4201; -pub const PTRACE_GETSIGINFO: ::c_uint = 0x4202; -pub const PTRACE_SETSIGINFO: ::c_uint = 0x4203; -pub const PTRACE_GETREGSET: ::c_uint = 0x4204; -pub const PTRACE_SETREGSET: ::c_uint = 0x4205; -pub const PTRACE_SEIZE: ::c_uint = 0x4206; -pub const PTRACE_INTERRUPT: ::c_uint = 0x4207; -pub const PTRACE_LISTEN: ::c_uint = 0x4208; -pub const PTRACE_PEEKSIGINFO: ::c_uint = 0x4209; - -pub const EPOLLWAKEUP: ::c_int = 0x20000000; - -pub const MAP_HUGETLB: ::c_int = 0x040000; - -pub const EFD_NONBLOCK: ::c_int = 0x800; - -pub const F_GETLK: ::c_int = 5; -pub const F_GETOWN: ::c_int = 9; -pub const F_SETOWN: ::c_int = 8; -pub const F_SETLK: ::c_int = 6; -pub const F_SETLKW: ::c_int = 7; - -pub const SEEK_DATA: ::c_int = 3; -pub const SEEK_HOLE: ::c_int = 4; - -pub const SFD_NONBLOCK: ::c_int = 0x0800; - -pub const TCSANOW: ::c_int = 0; -pub const TCSADRAIN: ::c_int = 1; -pub const TCSAFLUSH: ::c_int = 2; - -pub const TCGETS: ::c_ulong = 0x5401; -pub const TCSETS: ::c_ulong = 0x5402; -pub const TCSETSW: ::c_ulong = 0x5403; -pub const TCSETSF: ::c_ulong = 0x5404; -pub const TCGETA: ::c_ulong = 0x5405; -pub const TCSETA: ::c_ulong = 0x5406; -pub const TCSETAW: ::c_ulong = 0x5407; -pub const TCSETAF: ::c_ulong = 0x5408; -pub const TCSBRK: ::c_ulong = 0x5409; -pub const TCXONC: ::c_ulong = 0x540A; -pub const TCFLSH: ::c_ulong = 0x540B; -pub const TIOCGSOFTCAR: ::c_ulong = 0x5419; -pub const TIOCSSOFTCAR: ::c_ulong = 0x541A; -pub const TIOCINQ: ::c_ulong = 0x541B; -pub const TIOCLINUX: ::c_ulong = 0x541C; -pub const TIOCGSERIAL: ::c_ulong = 0x541E; -pub const TIOCEXCL: ::c_ulong = 0x540C; -pub const TIOCNXCL: ::c_ulong = 0x540D; -pub const TIOCSCTTY: ::c_ulong = 0x540E; -pub const TIOCGPGRP: ::c_ulong = 0x540F; -pub const TIOCSPGRP: ::c_ulong = 0x5410; -pub const TIOCOUTQ: ::c_ulong = 0x5411; -pub const TIOCSTI: ::c_ulong = 0x5412; -pub const TIOCGWINSZ: ::c_ulong = 0x5413; -pub const TIOCSWINSZ: ::c_ulong = 0x5414; -pub const TIOCMGET: ::c_ulong = 0x5415; -pub const TIOCMBIS: ::c_ulong = 0x5416; -pub const TIOCMBIC: ::c_ulong = 0x5417; -pub const TIOCMSET: ::c_ulong = 0x5418; -pub const FIONREAD: ::c_ulong = 0x541B; -pub const TIOCCONS: ::c_ulong = 0x541D; - -pub const RTLD_DEEPBIND: ::c_int = 0x8; -pub const RTLD_GLOBAL: ::c_int = 0x100; -pub const RTLD_NOLOAD: ::c_int = 0x4; - -pub const LINUX_REBOOT_MAGIC1: ::c_int = 0xfee1dead; -pub const LINUX_REBOOT_MAGIC2: ::c_int = 672274793; -pub const LINUX_REBOOT_MAGIC2A: ::c_int = 85072278; -pub const LINUX_REBOOT_MAGIC2B: ::c_int = 369367448; -pub const LINUX_REBOOT_MAGIC2C: ::c_int = 537993216; - -pub const LINUX_REBOOT_CMD_RESTART: ::c_int = 0x01234567; -pub const LINUX_REBOOT_CMD_HALT: ::c_int = 0xCDEF0123; -pub const LINUX_REBOOT_CMD_CAD_ON: ::c_int = 0x89ABCDEF; -pub const LINUX_REBOOT_CMD_CAD_OFF: ::c_int = 0x00000000; -pub const LINUX_REBOOT_CMD_POWER_OFF: ::c_int = 0x4321FEDC; -pub const LINUX_REBOOT_CMD_RESTART2: ::c_int = 0xA1B2C3D4; -pub const LINUX_REBOOT_CMD_SW_SUSPEND: ::c_int = 0xD000FCE2; -pub const LINUX_REBOOT_CMD_KEXEC: ::c_int = 0x45584543; - -pub const VTIME: usize = 5; -pub const VSWTC: usize = 7; -pub const VSTART: usize = 8; -pub const VSTOP: usize = 9; -pub const VSUSP: usize = 10; -pub const VREPRINT: usize = 12; -pub const VDISCARD: usize = 13; -pub const VWERASE: usize = 14; -pub const OLCUC: ::tcflag_t = 0o000002; -pub const ONLCR: ::tcflag_t = 0o000004; -pub const NLDLY: ::tcflag_t = 0o000400; -pub const CRDLY: ::tcflag_t = 0o003000; -pub const CR1: ::tcflag_t = 0x00000200; -pub const CR2: ::tcflag_t = 0x00000400; -pub const CR3: ::tcflag_t = 0x00000600; -pub const TABDLY: ::tcflag_t = 0o014000; -pub const TAB1: ::tcflag_t = 0x00000800; -pub const TAB2: ::tcflag_t = 0x00001000; -pub const TAB3: ::tcflag_t = 0x00001800; -pub const BSDLY: ::tcflag_t = 0o020000; -pub const BS1: ::tcflag_t = 0x00002000; -pub const FFDLY: ::tcflag_t = 0o100000; -pub const FF1: ::tcflag_t = 0x00008000; -pub const VTDLY: ::tcflag_t = 0o040000; -pub const VT1: ::tcflag_t = 0x00004000; -pub const XTABS: ::tcflag_t = 0o014000; - -pub const TIOCM_LE: ::c_int = 0x001; -pub const TIOCM_DTR: ::c_int = 0x002; -pub const TIOCM_RTS: ::c_int = 0x004; -pub const TIOCM_ST: ::c_int = 0x008; -pub const TIOCM_SR: ::c_int = 0x010; -pub const TIOCM_CTS: ::c_int = 0x020; -pub const TIOCM_CAR: ::c_int = 0x040; -pub const TIOCM_RNG: ::c_int = 0x080; -pub const TIOCM_DSR: ::c_int = 0x100; -pub const TIOCM_CD: ::c_int = TIOCM_CAR; -pub const TIOCM_RI: ::c_int = TIOCM_RNG; - -pub const SIGEV_THREAD_ID: ::c_int = 4; - -pub const CBAUD: ::speed_t = 0o010017; -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const EXTA: ::speed_t = B19200; -pub const EXTB: ::speed_t = B38400; -pub const CSIZE: ::tcflag_t = 0o000060; -pub const CS6: ::tcflag_t = 0o000020; -pub const CS7: ::tcflag_t = 0o000040; -pub const CS8: ::tcflag_t = 0o000060; -pub const CSTOPB: ::tcflag_t = 0o000100; -pub const CREAD: ::tcflag_t = 0o000200; -pub const PARENB: ::tcflag_t = 0o000400; -pub const PARODD: ::tcflag_t = 0o001000; -pub const HUPCL: ::tcflag_t = 0o002000; -pub const CLOCAL: ::tcflag_t = 0o004000; -pub const CBAUDEX: ::tcflag_t = 0o010000; -pub const BOTHER: ::speed_t = 0o010000; -pub const B57600: ::speed_t = 0o010001; -pub const B115200: ::speed_t = 0o010002; -pub const B230400: ::speed_t = 0o010003; -pub const B460800: ::speed_t = 0o010004; -pub const B500000: ::speed_t = 0o010005; -pub const B576000: ::speed_t = 0o010006; -pub const B921600: ::speed_t = 0o010007; -pub const B1000000: ::speed_t = 0o010010; -pub const B1152000: ::speed_t = 0o010011; -pub const B1500000: ::speed_t = 0o010012; -pub const B2000000: ::speed_t = 0o010013; -pub const B2500000: ::speed_t = 0o010014; -pub const B3000000: ::speed_t = 0o010015; -pub const B3500000: ::speed_t = 0o010016; -pub const B4000000: ::speed_t = 0o010017; -pub const CIBAUD: ::tcflag_t = 0o02003600000; - -pub const ISIG: ::tcflag_t = 0o000001; -pub const ICANON: ::tcflag_t = 0o000002; -pub const XCASE: ::tcflag_t = 0o000004; -pub const ECHOE: ::tcflag_t = 0o000020; -pub const ECHOK: ::tcflag_t = 0o000040; -pub const ECHONL: ::tcflag_t = 0o000100; -pub const NOFLSH: ::tcflag_t = 0o000200; -pub const ECHOCTL: ::tcflag_t = 0o001000; -pub const ECHOPRT: ::tcflag_t = 0o002000; -pub const ECHOKE: ::tcflag_t = 0o004000; -pub const PENDIN: ::tcflag_t = 0o040000; - -pub const POLLWRNORM: ::c_short = 0x100; -pub const POLLWRBAND: ::c_short = 0x200; - -pub const IXON: ::tcflag_t = 0o002000; -pub const IXOFF: ::tcflag_t = 0o010000; - -pub const SYS_exit: ::c_long = 1; -pub const SYS_fork: ::c_long = 2; -pub const SYS_read: ::c_long = 3; -pub const SYS_write: ::c_long = 4; -pub const SYS_open: ::c_long = 5; -pub const SYS_close: ::c_long = 6; -pub const SYS_restart_syscall: ::c_long = 7; -pub const SYS_creat: ::c_long = 8; -pub const SYS_link: ::c_long = 9; -pub const SYS_unlink: ::c_long = 10; -pub const SYS_execve: ::c_long = 11; -pub const SYS_chdir: ::c_long = 12; -pub const SYS_mknod: ::c_long = 14; -pub const SYS_chmod: ::c_long = 15; -pub const SYS_lseek: ::c_long = 19; -pub const SYS_getpid: ::c_long = 20; -pub const SYS_mount: ::c_long = 21; -pub const SYS_umount: ::c_long = 22; -pub const SYS_ptrace: ::c_long = 26; -pub const SYS_alarm: ::c_long = 27; -pub const SYS_pause: ::c_long = 29; -pub const SYS_utime: ::c_long = 30; -pub const SYS_access: ::c_long = 33; -pub const SYS_nice: ::c_long = 34; -pub const SYS_sync: ::c_long = 36; -pub const SYS_kill: ::c_long = 37; -pub const SYS_rename: ::c_long = 38; -pub const SYS_mkdir: ::c_long = 39; -pub const SYS_rmdir: ::c_long = 40; -pub const SYS_dup: ::c_long = 41; -pub const SYS_pipe: ::c_long = 42; -pub const SYS_times: ::c_long = 43; -pub const SYS_brk: ::c_long = 45; -pub const SYS_signal: ::c_long = 48; -pub const SYS_acct: ::c_long = 51; -pub const SYS_umount2: ::c_long = 52; -pub const SYS_ioctl: ::c_long = 54; -pub const SYS_fcntl: ::c_long = 55; -pub const SYS_setpgid: ::c_long = 57; -pub const SYS_umask: ::c_long = 60; -pub const SYS_chroot: ::c_long = 61; -pub const SYS_ustat: ::c_long = 62; -pub const SYS_dup2: ::c_long = 63; -pub const SYS_getppid: ::c_long = 64; -pub const SYS_getpgrp: ::c_long = 65; -pub const SYS_setsid: ::c_long = 66; -pub const SYS_sigaction: ::c_long = 67; -pub const SYS_sigsuspend: ::c_long = 72; -pub const SYS_sigpending: ::c_long = 73; -pub const SYS_sethostname: ::c_long = 74; -pub const SYS_setrlimit: ::c_long = 75; -pub const SYS_getrusage: ::c_long = 77; -pub const SYS_gettimeofday: ::c_long = 78; -pub const SYS_settimeofday: ::c_long = 79; -pub const SYS_symlink: ::c_long = 83; -pub const SYS_readlink: ::c_long = 85; -pub const SYS_uselib: ::c_long = 86; -pub const SYS_swapon: ::c_long = 87; -pub const SYS_reboot: ::c_long = 88; -pub const SYS_readdir: ::c_long = 89; -pub const SYS_mmap: ::c_long = 90; -pub const SYS_munmap: ::c_long = 91; -pub const SYS_truncate: ::c_long = 92; -pub const SYS_ftruncate: ::c_long = 93; -pub const SYS_fchmod: ::c_long = 94; -pub const SYS_getpriority: ::c_long = 96; -pub const SYS_setpriority: ::c_long = 97; -pub const SYS_statfs: ::c_long = 99; -pub const SYS_fstatfs: ::c_long = 100; -pub const SYS_socketcall: ::c_long = 102; -pub const SYS_syslog: ::c_long = 103; -pub const SYS_setitimer: ::c_long = 104; -pub const SYS_getitimer: ::c_long = 105; -pub const SYS_stat: ::c_long = 106; -pub const SYS_lstat: ::c_long = 107; -pub const SYS_fstat: ::c_long = 108; -pub const SYS_lookup_dcookie: ::c_long = 110; -pub const SYS_vhangup: ::c_long = 111; -pub const SYS_idle: ::c_long = 112; -pub const SYS_wait4: ::c_long = 114; -pub const SYS_swapoff: ::c_long = 115; -pub const SYS_sysinfo: ::c_long = 116; -pub const SYS_ipc: ::c_long = 117; -pub const SYS_fsync: ::c_long = 118; -pub const SYS_sigreturn: ::c_long = 119; -pub const SYS_clone: ::c_long = 120; -pub const SYS_setdomainname: ::c_long = 121; -pub const SYS_uname: ::c_long = 122; -pub const SYS_adjtimex: ::c_long = 124; -pub const SYS_mprotect: ::c_long = 125; -pub const SYS_sigprocmask: ::c_long = 126; -pub const SYS_create_module: ::c_long = 127; -pub const SYS_init_module: ::c_long = 128; -pub const SYS_delete_module: ::c_long = 129; -pub const SYS_get_kernel_syms: ::c_long = 130; -pub const SYS_quotactl: ::c_long = 131; -pub const SYS_getpgid: ::c_long = 132; -pub const SYS_fchdir: ::c_long = 133; -pub const SYS_bdflush: ::c_long = 134; -pub const SYS_sysfs: ::c_long = 135; -pub const SYS_personality: ::c_long = 136; -pub const SYS_afs_syscall: ::c_long = 137; /* Syscall for Andrew File System */ -pub const SYS_getdents: ::c_long = 141; -pub const SYS_flock: ::c_long = 143; -pub const SYS_msync: ::c_long = 144; -pub const SYS_readv: ::c_long = 145; -pub const SYS_writev: ::c_long = 146; -pub const SYS_getsid: ::c_long = 147; -pub const SYS_fdatasync: ::c_long = 148; -pub const SYS__sysctl: ::c_long = 149; -pub const SYS_mlock: ::c_long = 150; -pub const SYS_munlock: ::c_long = 151; -pub const SYS_mlockall: ::c_long = 152; -pub const SYS_munlockall: ::c_long = 153; -pub const SYS_sched_setparam: ::c_long = 154; -pub const SYS_sched_getparam: ::c_long = 155; -pub const SYS_sched_setscheduler: ::c_long = 156; -pub const SYS_sched_getscheduler: ::c_long = 157; -pub const SYS_sched_yield: ::c_long = 158; -pub const SYS_sched_get_priority_max: ::c_long = 159; -pub const SYS_sched_get_priority_min: ::c_long = 160; -pub const SYS_sched_rr_get_interval: ::c_long = 161; -pub const SYS_nanosleep: ::c_long = 162; -pub const SYS_mremap: ::c_long = 163; -pub const SYS_query_module: ::c_long = 167; -pub const SYS_poll: ::c_long = 168; -pub const SYS_nfsservctl: ::c_long = 169; -pub const SYS_prctl: ::c_long = 172; -pub const SYS_rt_sigreturn: ::c_long = 173; -pub const SYS_rt_sigaction: ::c_long = 174; -pub const SYS_rt_sigprocmask: ::c_long = 175; -pub const SYS_rt_sigpending: ::c_long = 176; -pub const SYS_rt_sigtimedwait: ::c_long = 177; -pub const SYS_rt_sigqueueinfo: ::c_long = 178; -pub const SYS_rt_sigsuspend: ::c_long = 179; -pub const SYS_pread64: ::c_long = 180; -pub const SYS_pwrite64: ::c_long = 181; -pub const SYS_getcwd: ::c_long = 183; -pub const SYS_capget: ::c_long = 184; -pub const SYS_capset: ::c_long = 185; -pub const SYS_sigaltstack: ::c_long = 186; -pub const SYS_sendfile: ::c_long = 187; -pub const SYS_getpmsg: ::c_long = 188; -pub const SYS_putpmsg: ::c_long = 189; -pub const SYS_vfork: ::c_long = 190; -pub const SYS_pivot_root: ::c_long = 217; -pub const SYS_mincore: ::c_long = 218; -pub const SYS_madvise: ::c_long = 219; -pub const SYS_getdents64: ::c_long = 220; -pub const SYS_readahead: ::c_long = 222; -pub const SYS_setxattr: ::c_long = 224; -pub const SYS_lsetxattr: ::c_long = 225; -pub const SYS_fsetxattr: ::c_long = 226; -pub const SYS_getxattr: ::c_long = 227; -pub const SYS_lgetxattr: ::c_long = 228; -pub const SYS_fgetxattr: ::c_long = 229; -pub const SYS_listxattr: ::c_long = 230; -pub const SYS_llistxattr: ::c_long = 231; -pub const SYS_flistxattr: ::c_long = 232; -pub const SYS_removexattr: ::c_long = 233; -pub const SYS_lremovexattr: ::c_long = 234; -pub const SYS_fremovexattr: ::c_long = 235; -pub const SYS_gettid: ::c_long = 236; -pub const SYS_tkill: ::c_long = 237; -pub const SYS_futex: ::c_long = 238; -pub const SYS_sched_setaffinity: ::c_long = 239; -pub const SYS_sched_getaffinity: ::c_long = 240; -pub const SYS_tgkill: ::c_long = 241; -pub const SYS_io_setup: ::c_long = 243; -pub const SYS_io_destroy: ::c_long = 244; -pub const SYS_io_getevents: ::c_long = 245; -pub const SYS_io_submit: ::c_long = 246; -pub const SYS_io_cancel: ::c_long = 247; -pub const SYS_exit_group: ::c_long = 248; -pub const SYS_epoll_create: ::c_long = 249; -pub const SYS_epoll_ctl: ::c_long = 250; -pub const SYS_epoll_wait: ::c_long = 251; -pub const SYS_set_tid_address: ::c_long = 252; -pub const SYS_fadvise64: ::c_long = 253; -pub const SYS_timer_create: ::c_long = 254; -pub const SYS_timer_settime: ::c_long = 255; -pub const SYS_timer_gettime: ::c_long = 256; -pub const SYS_timer_getoverrun: ::c_long = 257; -pub const SYS_timer_delete: ::c_long = 258; -pub const SYS_clock_settime: ::c_long = 259; -pub const SYS_clock_gettime: ::c_long = 260; -pub const SYS_clock_getres: ::c_long = 261; -pub const SYS_clock_nanosleep: ::c_long = 262; -pub const SYS_statfs64: ::c_long = 265; -pub const SYS_fstatfs64: ::c_long = 266; -pub const SYS_remap_file_pages: ::c_long = 267; -pub const SYS_mbind: ::c_long = 268; -pub const SYS_get_mempolicy: ::c_long = 269; -pub const SYS_set_mempolicy: ::c_long = 270; -pub const SYS_mq_open: ::c_long = 271; -pub const SYS_mq_unlink: ::c_long = 272; -pub const SYS_mq_timedsend: ::c_long = 273; -pub const SYS_mq_timedreceive: ::c_long = 274; -pub const SYS_mq_notify: ::c_long = 275; -pub const SYS_mq_getsetattr: ::c_long = 276; -pub const SYS_kexec_load: ::c_long = 277; -pub const SYS_add_key: ::c_long = 278; -pub const SYS_request_key: ::c_long = 279; -pub const SYS_keyctl: ::c_long = 280; -pub const SYS_waitid: ::c_long = 281; -pub const SYS_ioprio_set: ::c_long = 282; -pub const SYS_ioprio_get: ::c_long = 283; -pub const SYS_inotify_init: ::c_long = 284; -pub const SYS_inotify_add_watch: ::c_long = 285; -pub const SYS_inotify_rm_watch: ::c_long = 286; -pub const SYS_migrate_pages: ::c_long = 287; -pub const SYS_openat: ::c_long = 288; -pub const SYS_mkdirat: ::c_long = 289; -pub const SYS_mknodat: ::c_long = 290; -pub const SYS_fchownat: ::c_long = 291; -pub const SYS_futimesat: ::c_long = 292; -pub const SYS_unlinkat: ::c_long = 294; -pub const SYS_renameat: ::c_long = 295; -pub const SYS_linkat: ::c_long = 296; -pub const SYS_symlinkat: ::c_long = 297; -pub const SYS_readlinkat: ::c_long = 298; -pub const SYS_fchmodat: ::c_long = 299; -pub const SYS_faccessat: ::c_long = 300; -pub const SYS_pselect6: ::c_long = 301; -pub const SYS_ppoll: ::c_long = 302; -pub const SYS_unshare: ::c_long = 303; -pub const SYS_set_robust_list: ::c_long = 304; -pub const SYS_get_robust_list: ::c_long = 305; -pub const SYS_splice: ::c_long = 306; -pub const SYS_sync_file_range: ::c_long = 307; -pub const SYS_tee: ::c_long = 308; -pub const SYS_vmsplice: ::c_long = 309; -pub const SYS_move_pages: ::c_long = 310; -pub const SYS_getcpu: ::c_long = 311; -pub const SYS_epoll_pwait: ::c_long = 312; -pub const SYS_utimes: ::c_long = 313; -pub const SYS_fallocate: ::c_long = 314; -pub const SYS_utimensat: ::c_long = 315; -pub const SYS_signalfd: ::c_long = 316; -pub const SYS_timerfd: ::c_long = 317; -pub const SYS_eventfd: ::c_long = 318; -pub const SYS_timerfd_create: ::c_long = 319; -pub const SYS_timerfd_settime: ::c_long = 320; -pub const SYS_timerfd_gettime: ::c_long = 321; -pub const SYS_signalfd4: ::c_long = 322; -pub const SYS_eventfd2: ::c_long = 323; -pub const SYS_inotify_init1: ::c_long = 324; -pub const SYS_pipe2: ::c_long = 325; -pub const SYS_dup3: ::c_long = 326; -pub const SYS_epoll_create1: ::c_long = 327; -pub const SYS_preadv: ::c_long = 328; -pub const SYS_pwritev: ::c_long = 329; -pub const SYS_rt_tgsigqueueinfo: ::c_long = 330; -pub const SYS_perf_event_open: ::c_long = 331; -pub const SYS_fanotify_init: ::c_long = 332; -pub const SYS_fanotify_mark: ::c_long = 333; -pub const SYS_prlimit64: ::c_long = 334; -pub const SYS_name_to_handle_at: ::c_long = 335; -pub const SYS_open_by_handle_at: ::c_long = 336; -pub const SYS_clock_adjtime: ::c_long = 337; -pub const SYS_syncfs: ::c_long = 338; -pub const SYS_setns: ::c_long = 339; -pub const SYS_process_vm_readv: ::c_long = 340; -pub const SYS_process_vm_writev: ::c_long = 341; -pub const SYS_s390_runtime_instr: ::c_long = 342; -pub const SYS_kcmp: ::c_long = 343; -pub const SYS_finit_module: ::c_long = 344; -pub const SYS_sched_setattr: ::c_long = 345; -pub const SYS_sched_getattr: ::c_long = 346; -pub const SYS_renameat2: ::c_long = 347; -pub const SYS_seccomp: ::c_long = 348; -pub const SYS_getrandom: ::c_long = 349; -pub const SYS_memfd_create: ::c_long = 350; -pub const SYS_bpf: ::c_long = 351; -pub const SYS_s390_pci_mmio_write: ::c_long = 352; -pub const SYS_s390_pci_mmio_read: ::c_long = 353; -pub const SYS_execveat: ::c_long = 354; -pub const SYS_userfaultfd: ::c_long = 355; -pub const SYS_membarrier: ::c_long = 356; -pub const SYS_recvmmsg: ::c_long = 357; -pub const SYS_sendmmsg: ::c_long = 358; -pub const SYS_socket: ::c_long = 359; -pub const SYS_socketpair: ::c_long = 360; -pub const SYS_bind: ::c_long = 361; -pub const SYS_connect: ::c_long = 362; -pub const SYS_listen: ::c_long = 363; -pub const SYS_accept4: ::c_long = 364; -pub const SYS_getsockopt: ::c_long = 365; -pub const SYS_setsockopt: ::c_long = 366; -pub const SYS_getsockname: ::c_long = 367; -pub const SYS_getpeername: ::c_long = 368; -pub const SYS_sendto: ::c_long = 369; -pub const SYS_sendmsg: ::c_long = 370; -pub const SYS_recvfrom: ::c_long = 371; -pub const SYS_recvmsg: ::c_long = 372; -pub const SYS_shutdown: ::c_long = 373; -pub const SYS_mlock2: ::c_long = 374; -pub const SYS_copy_file_range: ::c_long = 375; -pub const SYS_preadv2: ::c_long = 376; -pub const SYS_pwritev2: ::c_long = 377; -pub const SYS_lchown: ::c_long = 198; -pub const SYS_setuid: ::c_long = 213; -pub const SYS_getuid: ::c_long = 199; -pub const SYS_setgid: ::c_long = 214; -pub const SYS_getgid: ::c_long = 200; -pub const SYS_geteuid: ::c_long = 201; -pub const SYS_setreuid: ::c_long = 203; -pub const SYS_setregid: ::c_long = 204; -pub const SYS_getrlimit: ::c_long = 191; -pub const SYS_getgroups: ::c_long = 205; -pub const SYS_fchown: ::c_long = 207; -pub const SYS_setresuid: ::c_long = 208; -pub const SYS_setresgid: ::c_long = 210; -pub const SYS_getresgid: ::c_long = 211; -pub const SYS_select: ::c_long = 142; -pub const SYS_getegid: ::c_long = 202; -pub const SYS_setgroups: ::c_long = 206; -pub const SYS_getresuid: ::c_long = 209; -pub const SYS_chown: ::c_long = 212; -pub const SYS_setfsuid: ::c_long = 215; -pub const SYS_setfsgid: ::c_long = 216; -pub const SYS_newfstatat: ::c_long = 293; - -#[link(name = "util")] -extern { - pub fn sysctl(name: *mut ::c_int, - namelen: ::c_int, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *mut ::c_void, - newlen: ::size_t) - -> ::c_int; - pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; - pub fn backtrace(buf: *mut *mut ::c_void, - sz: ::c_int) -> ::c_int; - pub fn glob64(pattern: *const ::c_char, - flags: ::c_int, - errfunc: ::dox::Option ::c_int>, - pglob: *mut glob64_t) -> ::c_int; - pub fn globfree64(pglob: *mut glob64_t); - pub fn ptrace(request: ::c_uint, ...) -> ::c_long; - pub fn pthread_attr_getaffinity_np(attr: *const ::pthread_attr_t, - cpusetsize: ::size_t, - cpuset: *mut ::cpu_set_t) -> ::c_int; - pub fn pthread_attr_setaffinity_np(attr: *mut ::pthread_attr_t, - cpusetsize: ::size_t, - cpuset: *const ::cpu_set_t) -> ::c_int; - pub fn getpriority(which: ::__priority_which_t, who: ::id_t) -> ::c_int; - pub fn setpriority(which: ::__priority_which_t, who: ::id_t, - prio: ::c_int) -> ::c_int; - pub fn pthread_getaffinity_np(thread: ::pthread_t, - cpusetsize: ::size_t, - cpuset: *mut ::cpu_set_t) -> ::c_int; - pub fn pthread_setaffinity_np(thread: ::pthread_t, - cpusetsize: ::size_t, - cpuset: *const ::cpu_set_t) -> ::c_int; - pub fn sched_getcpu() -> ::c_int; - pub fn getcontext(ucp: *mut ucontext_t) -> ::c_int; - pub fn setcontext(ucp: *const ucontext_t) -> ::c_int; - pub fn makecontext(ucp: *mut ucontext_t, - func: extern fn (), - argc: ::c_int, ...); - pub fn swapcontext(uocp: *mut ucontext_t, - ucp: *const ucontext_t) -> ::c_int; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/notbsd/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/notbsd/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1014 +0,0 @@ -use dox::mem; - -pub type sa_family_t = u16; -pub type pthread_key_t = ::c_uint; -pub type speed_t = ::c_uint; -pub type tcflag_t = ::c_uint; -pub type clockid_t = ::c_int; -pub type key_t = ::c_int; -pub type id_t = ::c_uint; - -pub enum timezone {} - -s! { - pub struct sockaddr { - pub sa_family: sa_family_t, - pub sa_data: [::c_char; 14], - } - - pub struct sockaddr_in { - pub sin_family: sa_family_t, - pub sin_port: ::in_port_t, - pub sin_addr: ::in_addr, - pub sin_zero: [u8; 8], - } - - pub struct sockaddr_in6 { - pub sin6_family: sa_family_t, - pub sin6_port: ::in_port_t, - pub sin6_flowinfo: u32, - pub sin6_addr: ::in6_addr, - pub sin6_scope_id: u32, - } - - pub struct sockaddr_un { - pub sun_family: sa_family_t, - pub sun_path: [::c_char; 108] - } - - pub struct sockaddr_storage { - pub ss_family: sa_family_t, - __ss_align: ::size_t, - #[cfg(target_pointer_width = "32")] - __ss_pad2: [u8; 128 - 2 * 4], - #[cfg(target_pointer_width = "64")] - __ss_pad2: [u8; 128 - 2 * 8], - } - - pub struct addrinfo { - pub ai_flags: ::c_int, - pub ai_family: ::c_int, - pub ai_socktype: ::c_int, - pub ai_protocol: ::c_int, - pub ai_addrlen: socklen_t, - - #[cfg(any(target_os = "linux", - target_os = "emscripten", - target_os = "fuchsia"))] - pub ai_addr: *mut ::sockaddr, - - pub ai_canonname: *mut c_char, - - #[cfg(target_os = "android")] - pub ai_addr: *mut ::sockaddr, - - pub ai_next: *mut addrinfo, - } - - pub struct sockaddr_nl { - pub nl_family: ::sa_family_t, - nl_pad: ::c_ushort, - pub nl_pid: u32, - pub nl_groups: u32 - } - - pub struct sockaddr_ll { - pub sll_family: ::c_ushort, - pub sll_protocol: ::c_ushort, - pub sll_ifindex: ::c_int, - pub sll_hatype: ::c_ushort, - pub sll_pkttype: ::c_uchar, - pub sll_halen: ::c_uchar, - pub sll_addr: [::c_uchar; 8] - } - - pub struct fd_set { - fds_bits: [::c_ulong; FD_SETSIZE / ULONG_SIZE], - } - - pub struct tm { - pub tm_sec: ::c_int, - pub tm_min: ::c_int, - pub tm_hour: ::c_int, - pub tm_mday: ::c_int, - pub tm_mon: ::c_int, - pub tm_year: ::c_int, - pub tm_wday: ::c_int, - pub tm_yday: ::c_int, - pub tm_isdst: ::c_int, - pub tm_gmtoff: ::c_long, - pub tm_zone: *const ::c_char, - } - - pub struct sched_param { - pub sched_priority: ::c_int, - #[cfg(any(target_env = "musl", target_os = "emscripten"))] - pub sched_ss_low_priority: ::c_int, - #[cfg(any(target_env = "musl", target_os = "emscripten"))] - pub sched_ss_repl_period: ::timespec, - #[cfg(any(target_env = "musl", target_os = "emscripten"))] - pub sched_ss_init_budget: ::timespec, - #[cfg(any(target_env = "musl", target_os = "emscripten"))] - pub sched_ss_max_repl: ::c_int, - } - - pub struct Dl_info { - pub dli_fname: *const ::c_char, - pub dli_fbase: *mut ::c_void, - pub dli_sname: *const ::c_char, - pub dli_saddr: *mut ::c_void, - } - - #[cfg_attr(any(all(target_arch = "x86", - not(target_env = "musl"), - not(target_os = "android")), - target_arch = "x86_64"), - repr(packed))] - pub struct epoll_event { - pub events: ::uint32_t, - pub u64: ::uint64_t, - } - - pub struct utsname { - pub sysname: [::c_char; 65], - pub nodename: [::c_char; 65], - pub release: [::c_char; 65], - pub version: [::c_char; 65], - pub machine: [::c_char; 65], - pub domainname: [::c_char; 65] - } - - pub struct lconv { - pub decimal_point: *mut ::c_char, - pub thousands_sep: *mut ::c_char, - pub grouping: *mut ::c_char, - pub int_curr_symbol: *mut ::c_char, - pub currency_symbol: *mut ::c_char, - pub mon_decimal_point: *mut ::c_char, - pub mon_thousands_sep: *mut ::c_char, - pub mon_grouping: *mut ::c_char, - pub positive_sign: *mut ::c_char, - pub negative_sign: *mut ::c_char, - pub int_frac_digits: ::c_char, - pub frac_digits: ::c_char, - pub p_cs_precedes: ::c_char, - pub p_sep_by_space: ::c_char, - pub n_cs_precedes: ::c_char, - pub n_sep_by_space: ::c_char, - pub p_sign_posn: ::c_char, - pub n_sign_posn: ::c_char, - pub int_p_cs_precedes: ::c_char, - pub int_p_sep_by_space: ::c_char, - pub int_n_cs_precedes: ::c_char, - pub int_n_sep_by_space: ::c_char, - pub int_p_sign_posn: ::c_char, - pub int_n_sign_posn: ::c_char, - } - - pub struct sigevent { - pub sigev_value: ::sigval, - pub sigev_signo: ::c_int, - pub sigev_notify: ::c_int, - // Actually a union. We only expose sigev_notify_thread_id because it's - // the most useful member - pub sigev_notify_thread_id: ::c_int, - #[cfg(target_pointer_width = "64")] - __unused1: [::c_int; 11], - #[cfg(target_pointer_width = "32")] - __unused1: [::c_int; 12] - } -} - -// intentionally not public, only used for fd_set -cfg_if! { - if #[cfg(target_pointer_width = "32")] { - const ULONG_SIZE: usize = 32; - } else if #[cfg(target_pointer_width = "64")] { - const ULONG_SIZE: usize = 64; - } else { - // Unknown target_pointer_width - } -} - -pub const EXIT_FAILURE: ::c_int = 1; -pub const EXIT_SUCCESS: ::c_int = 0; -pub const RAND_MAX: ::c_int = 2147483647; -pub const EOF: ::c_int = -1; -pub const SEEK_SET: ::c_int = 0; -pub const SEEK_CUR: ::c_int = 1; -pub const SEEK_END: ::c_int = 2; -pub const _IOFBF: ::c_int = 0; -pub const _IONBF: ::c_int = 2; -pub const _IOLBF: ::c_int = 1; - -pub const F_DUPFD: ::c_int = 0; -pub const F_GETFD: ::c_int = 1; -pub const F_SETFD: ::c_int = 2; -pub const F_GETFL: ::c_int = 3; -pub const F_SETFL: ::c_int = 4; - -// Linux-specific fcntls -pub const F_SETLEASE: ::c_int = 1024; -pub const F_GETLEASE: ::c_int = 1025; -pub const F_NOTIFY: ::c_int = 1026; -pub const F_CANCELLK: ::c_int = 1029; -pub const F_DUPFD_CLOEXEC: ::c_int = 1030; -pub const F_SETPIPE_SZ: ::c_int = 1031; -pub const F_GETPIPE_SZ: ::c_int = 1032; -pub const F_ADD_SEALS: ::c_int = 1033; -pub const F_GET_SEALS: ::c_int = 1034; - -pub const F_SEAL_SEAL: ::c_int = 0x0001; -pub const F_SEAL_SHRINK: ::c_int = 0x0002; -pub const F_SEAL_GROW: ::c_int = 0x0004; -pub const F_SEAL_WRITE: ::c_int = 0x0008; - -// TODO(#235): Include file sealing fcntls once we have a way to verify them. - -pub const SIGTRAP: ::c_int = 5; - -pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; -pub const PTHREAD_CREATE_DETACHED: ::c_int = 1; - -pub const CLOCK_REALTIME: ::clockid_t = 0; -pub const CLOCK_MONOTONIC: ::clockid_t = 1; -pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 2; -pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 3; -pub const CLOCK_MONOTONIC_RAW: ::clockid_t = 4; -pub const CLOCK_REALTIME_COARSE: ::clockid_t = 5; -pub const CLOCK_MONOTONIC_COARSE: ::clockid_t = 6; -pub const CLOCK_BOOTTIME: ::clockid_t = 7; -pub const CLOCK_REALTIME_ALARM: ::clockid_t = 8; -pub const CLOCK_BOOTTIME_ALARM: ::clockid_t = 9; -// TODO(#247) Someday our Travis shall have glibc 2.21 (released in Sep -// 2014.) See also musl/mod.rs -// pub const CLOCK_SGI_CYCLE: ::clockid_t = 10; -// pub const CLOCK_TAI: ::clockid_t = 11; -pub const TIMER_ABSTIME: ::c_int = 1; - -pub const RLIMIT_CPU: ::c_int = 0; -pub const RLIMIT_FSIZE: ::c_int = 1; -pub const RLIMIT_DATA: ::c_int = 2; -pub const RLIMIT_STACK: ::c_int = 3; -pub const RLIMIT_CORE: ::c_int = 4; -pub const RLIMIT_LOCKS: ::c_int = 10; -pub const RLIMIT_SIGPENDING: ::c_int = 11; -pub const RLIMIT_MSGQUEUE: ::c_int = 12; -pub const RLIMIT_NICE: ::c_int = 13; -pub const RLIMIT_RTPRIO: ::c_int = 14; - -pub const RUSAGE_SELF: ::c_int = 0; - -pub const O_RDONLY: ::c_int = 0; -pub const O_WRONLY: ::c_int = 1; -pub const O_RDWR: ::c_int = 2; - -pub const SOCK_CLOEXEC: ::c_int = O_CLOEXEC; - -pub const S_IFIFO: ::mode_t = 4096; -pub const S_IFCHR: ::mode_t = 8192; -pub const S_IFBLK: ::mode_t = 24576; -pub const S_IFDIR: ::mode_t = 16384; -pub const S_IFREG: ::mode_t = 32768; -pub const S_IFLNK: ::mode_t = 40960; -pub const S_IFSOCK: ::mode_t = 49152; -pub const S_IFMT: ::mode_t = 61440; -pub const S_IRWXU: ::mode_t = 448; -pub const S_IXUSR: ::mode_t = 64; -pub const S_IWUSR: ::mode_t = 128; -pub const S_IRUSR: ::mode_t = 256; -pub const S_IRWXG: ::mode_t = 56; -pub const S_IXGRP: ::mode_t = 8; -pub const S_IWGRP: ::mode_t = 16; -pub const S_IRGRP: ::mode_t = 32; -pub const S_IRWXO: ::mode_t = 7; -pub const S_IXOTH: ::mode_t = 1; -pub const S_IWOTH: ::mode_t = 2; -pub const S_IROTH: ::mode_t = 4; -pub const F_OK: ::c_int = 0; -pub const R_OK: ::c_int = 4; -pub const W_OK: ::c_int = 2; -pub const X_OK: ::c_int = 1; -pub const STDIN_FILENO: ::c_int = 0; -pub const STDOUT_FILENO: ::c_int = 1; -pub const STDERR_FILENO: ::c_int = 2; -pub const SIGHUP: ::c_int = 1; -pub const SIGINT: ::c_int = 2; -pub const SIGQUIT: ::c_int = 3; -pub const SIGILL: ::c_int = 4; -pub const SIGABRT: ::c_int = 6; -pub const SIGFPE: ::c_int = 8; -pub const SIGKILL: ::c_int = 9; -pub const SIGSEGV: ::c_int = 11; -pub const SIGPIPE: ::c_int = 13; -pub const SIGALRM: ::c_int = 14; -pub const SIGTERM: ::c_int = 15; - -pub const PROT_NONE: ::c_int = 0; -pub const PROT_READ: ::c_int = 1; -pub const PROT_WRITE: ::c_int = 2; -pub const PROT_EXEC: ::c_int = 4; - -pub const LC_CTYPE: ::c_int = 0; -pub const LC_NUMERIC: ::c_int = 1; -pub const LC_TIME: ::c_int = 2; -pub const LC_COLLATE: ::c_int = 3; -pub const LC_MONETARY: ::c_int = 4; -pub const LC_MESSAGES: ::c_int = 5; -pub const LC_ALL: ::c_int = 6; -pub const LC_CTYPE_MASK: ::c_int = (1 << LC_CTYPE); -pub const LC_NUMERIC_MASK: ::c_int = (1 << LC_NUMERIC); -pub const LC_TIME_MASK: ::c_int = (1 << LC_TIME); -pub const LC_COLLATE_MASK: ::c_int = (1 << LC_COLLATE); -pub const LC_MONETARY_MASK: ::c_int = (1 << LC_MONETARY); -pub const LC_MESSAGES_MASK: ::c_int = (1 << LC_MESSAGES); -// LC_ALL_MASK defined per platform - -pub const MAP_FILE: ::c_int = 0x0000; -pub const MAP_SHARED: ::c_int = 0x0001; -pub const MAP_PRIVATE: ::c_int = 0x0002; -pub const MAP_FIXED: ::c_int = 0x0010; - -pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; - -// MS_ flags for msync(2) -pub const MS_ASYNC: ::c_int = 0x0001; -pub const MS_INVALIDATE: ::c_int = 0x0002; -pub const MS_SYNC: ::c_int = 0x0004; - -// MS_ flags for mount(2) -pub const MS_RDONLY: ::c_ulong = 0x01; -pub const MS_NOSUID: ::c_ulong = 0x02; -pub const MS_NODEV: ::c_ulong = 0x04; -pub const MS_NOEXEC: ::c_ulong = 0x08; -pub const MS_SYNCHRONOUS: ::c_ulong = 0x10; -pub const MS_REMOUNT: ::c_ulong = 0x20; -pub const MS_MANDLOCK: ::c_ulong = 0x40; -pub const MS_DIRSYNC: ::c_ulong = 0x80; -pub const MS_NOATIME: ::c_ulong = 0x0400; -pub const MS_NODIRATIME: ::c_ulong = 0x0800; -pub const MS_BIND: ::c_ulong = 0x1000; -pub const MS_MOVE: ::c_ulong = 0x2000; -pub const MS_REC: ::c_ulong = 0x4000; -pub const MS_SILENT: ::c_ulong = 0x8000; -pub const MS_POSIXACL: ::c_ulong = 0x010000; -pub const MS_UNBINDABLE: ::c_ulong = 0x020000; -pub const MS_PRIVATE: ::c_ulong = 0x040000; -pub const MS_SLAVE: ::c_ulong = 0x080000; -pub const MS_SHARED: ::c_ulong = 0x100000; -pub const MS_RELATIME: ::c_ulong = 0x200000; -pub const MS_KERNMOUNT: ::c_ulong = 0x400000; -pub const MS_I_VERSION: ::c_ulong = 0x800000; -pub const MS_STRICTATIME: ::c_ulong = 0x1000000; -pub const MS_ACTIVE: ::c_ulong = 0x40000000; -pub const MS_NOUSER: ::c_ulong = 0x80000000; -pub const MS_MGC_VAL: ::c_ulong = 0xc0ed0000; -pub const MS_MGC_MSK: ::c_ulong = 0xffff0000; -pub const MS_RMT_MASK: ::c_ulong = 0x800051; - -pub const EPERM: ::c_int = 1; -pub const ENOENT: ::c_int = 2; -pub const ESRCH: ::c_int = 3; -pub const EINTR: ::c_int = 4; -pub const EIO: ::c_int = 5; -pub const ENXIO: ::c_int = 6; -pub const E2BIG: ::c_int = 7; -pub const ENOEXEC: ::c_int = 8; -pub const EBADF: ::c_int = 9; -pub const ECHILD: ::c_int = 10; -pub const EAGAIN: ::c_int = 11; -pub const ENOMEM: ::c_int = 12; -pub const EACCES: ::c_int = 13; -pub const EFAULT: ::c_int = 14; -pub const ENOTBLK: ::c_int = 15; -pub const EBUSY: ::c_int = 16; -pub const EEXIST: ::c_int = 17; -pub const EXDEV: ::c_int = 18; -pub const ENODEV: ::c_int = 19; -pub const ENOTDIR: ::c_int = 20; -pub const EISDIR: ::c_int = 21; -pub const EINVAL: ::c_int = 22; -pub const ENFILE: ::c_int = 23; -pub const EMFILE: ::c_int = 24; -pub const ENOTTY: ::c_int = 25; -pub const ETXTBSY: ::c_int = 26; -pub const EFBIG: ::c_int = 27; -pub const ENOSPC: ::c_int = 28; -pub const ESPIPE: ::c_int = 29; -pub const EROFS: ::c_int = 30; -pub const EMLINK: ::c_int = 31; -pub const EPIPE: ::c_int = 32; -pub const EDOM: ::c_int = 33; -pub const ERANGE: ::c_int = 34; -pub const EWOULDBLOCK: ::c_int = EAGAIN; - -pub const SCM_RIGHTS: ::c_int = 0x01; -pub const SCM_CREDENTIALS: ::c_int = 0x02; - -pub const PROT_GROWSDOWN: ::c_int = 0x1000000; -pub const PROT_GROWSUP: ::c_int = 0x2000000; - -pub const MAP_TYPE: ::c_int = 0x000f; - -pub const MADV_NORMAL: ::c_int = 0; -pub const MADV_RANDOM: ::c_int = 1; -pub const MADV_SEQUENTIAL: ::c_int = 2; -pub const MADV_WILLNEED: ::c_int = 3; -pub const MADV_DONTNEED: ::c_int = 4; -pub const MADV_FREE: ::c_int = 8; -pub const MADV_REMOVE: ::c_int = 9; -pub const MADV_DONTFORK: ::c_int = 10; -pub const MADV_DOFORK: ::c_int = 11; -pub const MADV_MERGEABLE: ::c_int = 12; -pub const MADV_UNMERGEABLE: ::c_int = 13; -pub const MADV_HUGEPAGE: ::c_int = 14; -pub const MADV_NOHUGEPAGE: ::c_int = 15; -pub const MADV_DONTDUMP: ::c_int = 16; -pub const MADV_DODUMP: ::c_int = 17; -pub const MADV_HWPOISON: ::c_int = 100; -pub const MADV_SOFT_OFFLINE: ::c_int = 101; - -pub const IFF_UP: ::c_int = 0x1; -pub const IFF_BROADCAST: ::c_int = 0x2; -pub const IFF_DEBUG: ::c_int = 0x4; -pub const IFF_LOOPBACK: ::c_int = 0x8; -pub const IFF_POINTOPOINT: ::c_int = 0x10; -pub const IFF_NOTRAILERS: ::c_int = 0x20; -pub const IFF_RUNNING: ::c_int = 0x40; -pub const IFF_NOARP: ::c_int = 0x80; -pub const IFF_PROMISC: ::c_int = 0x100; -pub const IFF_ALLMULTI: ::c_int = 0x200; -pub const IFF_MASTER: ::c_int = 0x400; -pub const IFF_SLAVE: ::c_int = 0x800; -pub const IFF_MULTICAST: ::c_int = 0x1000; -pub const IFF_PORTSEL: ::c_int = 0x2000; -pub const IFF_AUTOMEDIA: ::c_int = 0x4000; -pub const IFF_DYNAMIC: ::c_int = 0x8000; - -pub const SOL_IP: ::c_int = 0; -pub const SOL_TCP: ::c_int = 6; -pub const SOL_UDP: ::c_int = 17; -pub const SOL_IPV6: ::c_int = 41; -pub const SOL_ICMPV6: ::c_int = 58; -pub const SOL_RAW: ::c_int = 255; -pub const SOL_DECNET: ::c_int = 261; -pub const SOL_X25: ::c_int = 262; -pub const SOL_PACKET: ::c_int = 263; -pub const SOL_ATM: ::c_int = 264; -pub const SOL_AAL: ::c_int = 265; -pub const SOL_IRDA: ::c_int = 266; -pub const SOL_NETBEUI: ::c_int = 267; -pub const SOL_LLC: ::c_int = 268; -pub const SOL_DCCP: ::c_int = 269; -pub const SOL_NETLINK: ::c_int = 270; -pub const SOL_TIPC: ::c_int = 271; - -pub const AF_UNSPEC: ::c_int = 0; -pub const AF_UNIX: ::c_int = 1; -pub const AF_LOCAL: ::c_int = 1; -pub const AF_INET: ::c_int = 2; -pub const AF_AX25: ::c_int = 3; -pub const AF_IPX: ::c_int = 4; -pub const AF_APPLETALK: ::c_int = 5; -pub const AF_NETROM: ::c_int = 6; -pub const AF_BRIDGE: ::c_int = 7; -pub const AF_ATMPVC: ::c_int = 8; -pub const AF_X25: ::c_int = 9; -pub const AF_INET6: ::c_int = 10; -pub const AF_ROSE: ::c_int = 11; -pub const AF_DECnet: ::c_int = 12; -pub const AF_NETBEUI: ::c_int = 13; -pub const AF_SECURITY: ::c_int = 14; -pub const AF_KEY: ::c_int = 15; -pub const AF_NETLINK: ::c_int = 16; -pub const AF_ROUTE: ::c_int = AF_NETLINK; -pub const AF_PACKET: ::c_int = 17; -pub const AF_ASH: ::c_int = 18; -pub const AF_ECONET: ::c_int = 19; -pub const AF_ATMSVC: ::c_int = 20; -pub const AF_RDS: ::c_int = 21; -pub const AF_SNA: ::c_int = 22; -pub const AF_IRDA: ::c_int = 23; -pub const AF_PPPOX: ::c_int = 24; -pub const AF_WANPIPE: ::c_int = 25; -pub const AF_LLC: ::c_int = 26; -pub const AF_CAN: ::c_int = 29; -pub const AF_TIPC: ::c_int = 30; -pub const AF_BLUETOOTH: ::c_int = 31; -pub const AF_IUCV: ::c_int = 32; -pub const AF_RXRPC: ::c_int = 33; -pub const AF_ISDN: ::c_int = 34; -pub const AF_PHONET: ::c_int = 35; -pub const AF_IEEE802154: ::c_int = 36; -pub const AF_CAIF: ::c_int = 37; -pub const AF_ALG: ::c_int = 38; - -pub const PF_UNSPEC: ::c_int = AF_UNSPEC; -pub const PF_UNIX: ::c_int = AF_UNIX; -pub const PF_LOCAL: ::c_int = AF_LOCAL; -pub const PF_INET: ::c_int = AF_INET; -pub const PF_AX25: ::c_int = AF_AX25; -pub const PF_IPX: ::c_int = AF_IPX; -pub const PF_APPLETALK: ::c_int = AF_APPLETALK; -pub const PF_NETROM: ::c_int = AF_NETROM; -pub const PF_BRIDGE: ::c_int = AF_BRIDGE; -pub const PF_ATMPVC: ::c_int = AF_ATMPVC; -pub const PF_X25: ::c_int = AF_X25; -pub const PF_INET6: ::c_int = AF_INET6; -pub const PF_ROSE: ::c_int = AF_ROSE; -pub const PF_DECnet: ::c_int = AF_DECnet; -pub const PF_NETBEUI: ::c_int = AF_NETBEUI; -pub const PF_SECURITY: ::c_int = AF_SECURITY; -pub const PF_KEY: ::c_int = AF_KEY; -pub const PF_NETLINK: ::c_int = AF_NETLINK; -pub const PF_ROUTE: ::c_int = AF_ROUTE; -pub const PF_PACKET: ::c_int = AF_PACKET; -pub const PF_ASH: ::c_int = AF_ASH; -pub const PF_ECONET: ::c_int = AF_ECONET; -pub const PF_ATMSVC: ::c_int = AF_ATMSVC; -pub const PF_RDS: ::c_int = AF_RDS; -pub const PF_SNA: ::c_int = AF_SNA; -pub const PF_IRDA: ::c_int = AF_IRDA; -pub const PF_PPPOX: ::c_int = AF_PPPOX; -pub const PF_WANPIPE: ::c_int = AF_WANPIPE; -pub const PF_LLC: ::c_int = AF_LLC; -pub const PF_CAN: ::c_int = AF_CAN; -pub const PF_TIPC: ::c_int = AF_TIPC; -pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; -pub const PF_IUCV: ::c_int = AF_IUCV; -pub const PF_RXRPC: ::c_int = AF_RXRPC; -pub const PF_ISDN: ::c_int = AF_ISDN; -pub const PF_PHONET: ::c_int = AF_PHONET; -pub const PF_IEEE802154: ::c_int = AF_IEEE802154; -pub const PF_CAIF: ::c_int = AF_CAIF; -pub const PF_ALG: ::c_int = AF_ALG; - -pub const SOMAXCONN: ::c_int = 128; - -pub const MSG_OOB: ::c_int = 1; -pub const MSG_PEEK: ::c_int = 2; -pub const MSG_DONTROUTE: ::c_int = 4; -pub const MSG_CTRUNC: ::c_int = 8; -pub const MSG_TRUNC: ::c_int = 0x20; -pub const MSG_DONTWAIT: ::c_int = 0x40; -pub const MSG_EOR: ::c_int = 0x80; -pub const MSG_WAITALL: ::c_int = 0x100; -pub const MSG_FIN: ::c_int = 0x200; -pub const MSG_SYN: ::c_int = 0x400; -pub const MSG_CONFIRM: ::c_int = 0x800; -pub const MSG_RST: ::c_int = 0x1000; -pub const MSG_ERRQUEUE: ::c_int = 0x2000; -pub const MSG_NOSIGNAL: ::c_int = 0x4000; -pub const MSG_MORE: ::c_int = 0x8000; -pub const MSG_WAITFORONE: ::c_int = 0x10000; -pub const MSG_FASTOPEN: ::c_int = 0x20000000; -pub const MSG_CMSG_CLOEXEC: ::c_int = 0x40000000; - -pub const SCM_TIMESTAMP: ::c_int = SO_TIMESTAMP; - -pub const SOCK_RAW: ::c_int = 3; -pub const SOCK_RDM: ::c_int = 4; -pub const IP_MULTICAST_IF: ::c_int = 32; -pub const IP_MULTICAST_TTL: ::c_int = 33; -pub const IP_MULTICAST_LOOP: ::c_int = 34; -pub const IP_TTL: ::c_int = 2; -pub const IP_HDRINCL: ::c_int = 3; -pub const IP_ADD_MEMBERSHIP: ::c_int = 35; -pub const IP_DROP_MEMBERSHIP: ::c_int = 36; -pub const IP_TRANSPARENT: ::c_int = 19; -pub const IPV6_ADD_MEMBERSHIP: ::c_int = 20; -pub const IPV6_DROP_MEMBERSHIP: ::c_int = 21; - -pub const TCP_NODELAY: ::c_int = 1; -pub const TCP_MAXSEG: ::c_int = 2; -pub const TCP_CORK: ::c_int = 3; -pub const TCP_KEEPIDLE: ::c_int = 4; -pub const TCP_KEEPINTVL: ::c_int = 5; -pub const TCP_KEEPCNT: ::c_int = 6; -pub const TCP_SYNCNT: ::c_int = 7; -pub const TCP_LINGER2: ::c_int = 8; -pub const TCP_DEFER_ACCEPT: ::c_int = 9; -pub const TCP_WINDOW_CLAMP: ::c_int = 10; -pub const TCP_INFO: ::c_int = 11; -pub const TCP_QUICKACK: ::c_int = 12; -pub const TCP_CONGESTION: ::c_int = 13; - -pub const IPV6_MULTICAST_LOOP: ::c_int = 19; -pub const IPV6_V6ONLY: ::c_int = 26; - -pub const SO_DEBUG: ::c_int = 1; - -pub const SHUT_RD: ::c_int = 0; -pub const SHUT_WR: ::c_int = 1; -pub const SHUT_RDWR: ::c_int = 2; - -pub const LOCK_SH: ::c_int = 1; -pub const LOCK_EX: ::c_int = 2; -pub const LOCK_NB: ::c_int = 4; -pub const LOCK_UN: ::c_int = 8; - -pub const SS_ONSTACK: ::c_int = 1; -pub const SS_DISABLE: ::c_int = 2; - -pub const PATH_MAX: ::c_int = 4096; - -pub const FD_SETSIZE: usize = 1024; - -pub const EPOLLIN: ::c_int = 0x1; -pub const EPOLLPRI: ::c_int = 0x2; -pub const EPOLLOUT: ::c_int = 0x4; -pub const EPOLLRDNORM: ::c_int = 0x40; -pub const EPOLLRDBAND: ::c_int = 0x80; -pub const EPOLLWRNORM: ::c_int = 0x100; -pub const EPOLLWRBAND: ::c_int = 0x200; -pub const EPOLLMSG: ::c_int = 0x400; -pub const EPOLLERR: ::c_int = 0x8; -pub const EPOLLHUP: ::c_int = 0x10; -pub const EPOLLET: ::c_int = 0x80000000; - -pub const EPOLL_CTL_ADD: ::c_int = 1; -pub const EPOLL_CTL_MOD: ::c_int = 3; -pub const EPOLL_CTL_DEL: ::c_int = 2; - -pub const MNT_DETACH: ::c_int = 0x2; -pub const MNT_EXPIRE: ::c_int = 0x4; - -pub const Q_GETFMT: ::c_int = 0x800004; -pub const Q_GETINFO: ::c_int = 0x800005; -pub const Q_SETINFO: ::c_int = 0x800006; -pub const QIF_BLIMITS: ::uint32_t = 1; -pub const QIF_SPACE: ::uint32_t = 2; -pub const QIF_ILIMITS: ::uint32_t = 4; -pub const QIF_INODES: ::uint32_t = 8; -pub const QIF_BTIME: ::uint32_t = 16; -pub const QIF_ITIME: ::uint32_t = 32; -pub const QIF_LIMITS: ::uint32_t = 5; -pub const QIF_USAGE: ::uint32_t = 10; -pub const QIF_TIMES: ::uint32_t = 48; -pub const QIF_ALL: ::uint32_t = 63; - -pub const MNT_FORCE: ::c_int = 0x1; - -pub const Q_SYNC: ::c_int = 0x800001; -pub const Q_QUOTAON: ::c_int = 0x800002; -pub const Q_QUOTAOFF: ::c_int = 0x800003; -pub const Q_GETQUOTA: ::c_int = 0x800007; -pub const Q_SETQUOTA: ::c_int = 0x800008; - -pub const TCIOFF: ::c_int = 2; -pub const TCION: ::c_int = 3; -pub const TCOOFF: ::c_int = 0; -pub const TCOON: ::c_int = 1; -pub const TCIFLUSH: ::c_int = 0; -pub const TCOFLUSH: ::c_int = 1; -pub const TCIOFLUSH: ::c_int = 2; -pub const NL0: ::c_int = 0x00000000; -pub const NL1: ::c_int = 0x00000100; -pub const TAB0: ::c_int = 0x00000000; -pub const CR0: ::c_int = 0x00000000; -pub const FF0: ::c_int = 0x00000000; -pub const BS0: ::c_int = 0x00000000; -pub const VT0: ::c_int = 0x00000000; -pub const VERASE: usize = 2; -pub const VKILL: usize = 3; -pub const VINTR: usize = 0; -pub const VQUIT: usize = 1; -pub const VLNEXT: usize = 15; -pub const IGNBRK: ::tcflag_t = 0x00000001; -pub const BRKINT: ::tcflag_t = 0x00000002; -pub const IGNPAR: ::tcflag_t = 0x00000004; -pub const PARMRK: ::tcflag_t = 0x00000008; -pub const INPCK: ::tcflag_t = 0x00000010; -pub const ISTRIP: ::tcflag_t = 0x00000020; -pub const INLCR: ::tcflag_t = 0x00000040; -pub const IGNCR: ::tcflag_t = 0x00000080; -pub const ICRNL: ::tcflag_t = 0x00000100; -pub const IXANY: ::tcflag_t = 0x00000800; -pub const IMAXBEL: ::tcflag_t = 0x00002000; -pub const OPOST: ::tcflag_t = 0x1; -pub const CS5: ::tcflag_t = 0x00000000; -pub const CRTSCTS: ::tcflag_t = 0x80000000; -pub const ECHO: ::tcflag_t = 0x00000008; -pub const OCRNL: ::tcflag_t = 0o000010; -pub const ONOCR: ::tcflag_t = 0o000020; -pub const ONLRET: ::tcflag_t = 0o000040; -pub const OFILL: ::tcflag_t = 0o000100; -pub const OFDEL: ::tcflag_t = 0o000200; - -pub const CLONE_VM: ::c_int = 0x100; -pub const CLONE_FS: ::c_int = 0x200; -pub const CLONE_FILES: ::c_int = 0x400; -pub const CLONE_SIGHAND: ::c_int = 0x800; -pub const CLONE_PTRACE: ::c_int = 0x2000; -pub const CLONE_VFORK: ::c_int = 0x4000; -pub const CLONE_PARENT: ::c_int = 0x8000; -pub const CLONE_THREAD: ::c_int = 0x10000; -pub const CLONE_NEWNS: ::c_int = 0x20000; -pub const CLONE_SYSVSEM: ::c_int = 0x40000; -pub const CLONE_SETTLS: ::c_int = 0x80000; -pub const CLONE_PARENT_SETTID: ::c_int = 0x100000; -pub const CLONE_CHILD_CLEARTID: ::c_int = 0x200000; -pub const CLONE_DETACHED: ::c_int = 0x400000; -pub const CLONE_UNTRACED: ::c_int = 0x800000; -pub const CLONE_CHILD_SETTID: ::c_int = 0x01000000; -pub const CLONE_NEWUTS: ::c_int = 0x04000000; -pub const CLONE_NEWIPC: ::c_int = 0x08000000; -pub const CLONE_NEWUSER: ::c_int = 0x10000000; -pub const CLONE_NEWPID: ::c_int = 0x20000000; -pub const CLONE_NEWNET: ::c_int = 0x40000000; -pub const CLONE_IO: ::c_int = 0x80000000; -pub const CLONE_NEWCGROUP: ::c_int = 0x02000000; - -pub const WNOHANG: ::c_int = 0x00000001; -pub const WUNTRACED: ::c_int = 0x00000002; -pub const WSTOPPED: ::c_int = WUNTRACED; -pub const WEXITED: ::c_int = 0x00000004; -pub const WCONTINUED: ::c_int = 0x00000008; -pub const WNOWAIT: ::c_int = 0x01000000; - -// Options set using PTRACE_SETOPTIONS. -pub const PTRACE_O_TRACESYSGOOD: ::c_int = 0x00000001; -pub const PTRACE_O_TRACEFORK: ::c_int = 0x00000002; -pub const PTRACE_O_TRACEVFORK: ::c_int = 0x00000004; -pub const PTRACE_O_TRACECLONE: ::c_int = 0x00000008; -pub const PTRACE_O_TRACEEXEC: ::c_int = 0x00000010; -pub const PTRACE_O_TRACEVFORKDONE: ::c_int = 0x00000020; -pub const PTRACE_O_TRACEEXIT: ::c_int = 0x00000040; -pub const PTRACE_O_TRACESECCOMP: ::c_int = 0x00000080; -pub const PTRACE_O_EXITKILL: ::c_int = 0x00100000; -pub const PTRACE_O_SUSPEND_SECCOMP: ::c_int = 0x00200000; -pub const PTRACE_O_MASK: ::c_int = 0x003000ff; - -// Wait extended result codes for the above trace options. -pub const PTRACE_EVENT_FORK: ::c_int = 1; -pub const PTRACE_EVENT_VFORK: ::c_int = 2; -pub const PTRACE_EVENT_CLONE: ::c_int = 3; -pub const PTRACE_EVENT_EXEC: ::c_int = 4; -pub const PTRACE_EVENT_VFORK_DONE: ::c_int = 5; -pub const PTRACE_EVENT_EXIT: ::c_int = 6; -pub const PTRACE_EVENT_SECCOMP: ::c_int = 7; -// PTRACE_EVENT_STOP was added to glibc in 2.26 -// pub const PTRACE_EVENT_STOP: ::c_int = 128; - -pub const __WNOTHREAD: ::c_int = 0x20000000; -pub const __WALL: ::c_int = 0x40000000; -pub const __WCLONE: ::c_int = 0x80000000; - -pub const SPLICE_F_MOVE: ::c_uint = 0x01; -pub const SPLICE_F_NONBLOCK: ::c_uint = 0x02; -pub const SPLICE_F_MORE: ::c_uint = 0x04; -pub const SPLICE_F_GIFT: ::c_uint = 0x08; - -pub const RTLD_LOCAL: ::c_int = 0; -pub const RTLD_LAZY: ::c_int = 1; - -pub const POSIX_FADV_NORMAL: ::c_int = 0; -pub const POSIX_FADV_RANDOM: ::c_int = 1; -pub const POSIX_FADV_SEQUENTIAL: ::c_int = 2; -pub const POSIX_FADV_WILLNEED: ::c_int = 3; - -pub const AT_FDCWD: ::c_int = -100; -pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x100; -pub const AT_REMOVEDIR: ::c_int = 0x200; -pub const AT_SYMLINK_FOLLOW: ::c_int = 0x400; -pub const AT_NO_AUTOMOUNT: ::c_int = 0x800; -pub const AT_EMPTY_PATH: ::c_int = 0x1000; - -pub const LOG_CRON: ::c_int = 9 << 3; -pub const LOG_AUTHPRIV: ::c_int = 10 << 3; -pub const LOG_FTP: ::c_int = 11 << 3; -pub const LOG_PERROR: ::c_int = 0x20; - -pub const PIPE_BUF: usize = 4096; - -pub const SI_LOAD_SHIFT: ::c_uint = 16; - -pub const SIGEV_SIGNAL: ::c_int = 0; -pub const SIGEV_NONE: ::c_int = 1; -pub const SIGEV_THREAD: ::c_int = 2; - -pub const P_ALL: idtype_t = 0; -pub const P_PID: idtype_t = 1; -pub const P_PGID: idtype_t = 2; - -pub const UTIME_OMIT: c_long = 1073741822; -pub const UTIME_NOW: c_long = 1073741823; - -pub const POLLIN: ::c_short = 0x1; -pub const POLLPRI: ::c_short = 0x2; -pub const POLLOUT: ::c_short = 0x4; -pub const POLLERR: ::c_short = 0x8; -pub const POLLHUP: ::c_short = 0x10; -pub const POLLNVAL: ::c_short = 0x20; -pub const POLLRDNORM: ::c_short = 0x040; -pub const POLLRDBAND: ::c_short = 0x080; - -f! { - pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { - let fd = fd as usize; - let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; - (*set).fds_bits[fd / size] &= !(1 << (fd % size)); - return - } - - pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { - let fd = fd as usize; - let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; - return ((*set).fds_bits[fd / size] & (1 << (fd % size))) != 0 - } - - pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { - let fd = fd as usize; - let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; - (*set).fds_bits[fd / size] |= 1 << (fd % size); - return - } - - pub fn FD_ZERO(set: *mut fd_set) -> () { - for slot in (*set).fds_bits.iter_mut() { - *slot = 0; - } - } - - pub fn WIFSTOPPED(status: ::c_int) -> bool { - (status & 0xff) == 0x7f - } - - pub fn WSTOPSIG(status: ::c_int) -> ::c_int { - (status >> 8) & 0xff - } - - pub fn WIFCONTINUED(status: ::c_int) -> bool { - status == 0xffff - } - - pub fn WIFSIGNALED(status: ::c_int) -> bool { - ((status & 0x7f) + 1) as i8 >= 2 - } - - pub fn WTERMSIG(status: ::c_int) -> ::c_int { - status & 0x7f - } - - pub fn WIFEXITED(status: ::c_int) -> bool { - (status & 0x7f) == 0 - } - - pub fn WEXITSTATUS(status: ::c_int) -> ::c_int { - (status >> 8) & 0xff - } - - pub fn WCOREDUMP(status: ::c_int) -> bool { - (status & 0x80) != 0 - } - - pub fn QCMD(cmd: ::c_int, type_: ::c_int) -> ::c_int { - (cmd << 8) | (type_ & 0x00ff) - } -} - -extern { - pub fn fdatasync(fd: ::c_int) -> ::c_int; - pub fn mincore(addr: *mut ::c_void, len: ::size_t, - vec: *mut ::c_uchar) -> ::c_int; - pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; - pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; - - pub fn pthread_getattr_np(native: ::pthread_t, - attr: *mut ::pthread_attr_t) -> ::c_int; - pub fn pthread_attr_getstack(attr: *const ::pthread_attr_t, - stackaddr: *mut *mut ::c_void, - stacksize: *mut ::size_t) -> ::c_int; - pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; - pub fn setgroups(ngroups: ::size_t, - ptr: *const ::gid_t) -> ::c_int; - pub fn pipe2(fds: *mut ::c_int, flags: ::c_int) -> ::c_int; - pub fn statfs(path: *const ::c_char, buf: *mut statfs) -> ::c_int; - pub fn statfs64(path: *const ::c_char, buf: *mut statfs64) -> ::c_int; - pub fn fstatfs(fd: ::c_int, buf: *mut statfs) -> ::c_int; - pub fn fstatfs64(fd: ::c_int, buf: *mut statfs64) -> ::c_int; - pub fn statvfs64(path: *const ::c_char, buf: *mut statvfs64) -> ::c_int; - pub fn fstatvfs64(fd: ::c_int, buf: *mut statvfs64) -> ::c_int; - pub fn memrchr(cx: *const ::c_void, - c: ::c_int, - n: ::size_t) -> *mut ::c_void; - - pub fn posix_fadvise(fd: ::c_int, offset: ::off_t, len: ::off_t, - advise: ::c_int) -> ::c_int; - pub fn futimens(fd: ::c_int, times: *const ::timespec) -> ::c_int; - pub fn utimensat(dirfd: ::c_int, path: *const ::c_char, - times: *const ::timespec, flag: ::c_int) -> ::c_int; - pub fn duplocale(base: ::locale_t) -> ::locale_t; - pub fn freelocale(loc: ::locale_t); - pub fn newlocale(mask: ::c_int, - locale: *const ::c_char, - base: ::locale_t) -> ::locale_t; - pub fn uselocale(loc: ::locale_t) -> ::locale_t; - pub fn creat64(path: *const c_char, mode: mode_t) -> ::c_int; - pub fn fstat64(fildes: ::c_int, buf: *mut stat64) -> ::c_int; - pub fn fstatat64(dirfd: ::c_int, pathname: *const c_char, - buf: *mut stat64, flags: ::c_int) -> ::c_int; - pub fn ftruncate64(fd: ::c_int, length: off64_t) -> ::c_int; - pub fn getrlimit64(resource: ::c_int, rlim: *mut rlimit64) -> ::c_int; - pub fn lseek64(fd: ::c_int, offset: off64_t, whence: ::c_int) -> off64_t; - pub fn lstat64(path: *const c_char, buf: *mut stat64) -> ::c_int; - pub fn mmap64(addr: *mut ::c_void, - len: ::size_t, - prot: ::c_int, - flags: ::c_int, - fd: ::c_int, - offset: off64_t) - -> *mut ::c_void; - pub fn open64(path: *const c_char, oflag: ::c_int, ...) -> ::c_int; - pub fn openat64(fd: ::c_int, - path: *const c_char, - oflag: ::c_int, ...) -> ::c_int; - pub fn pread64(fd: ::c_int, buf: *mut ::c_void, count: ::size_t, - offset: off64_t) -> ::ssize_t; - pub fn preadv64(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off64_t) -> ::ssize_t; - pub fn pwrite64(fd: ::c_int, buf: *const ::c_void, count: ::size_t, - offset: off64_t) -> ::ssize_t; - pub fn pwritev64(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int, - offset: ::off64_t) -> ::ssize_t; - pub fn readdir64(dirp: *mut ::DIR) -> *mut ::dirent64; - pub fn readdir64_r(dirp: *mut ::DIR, entry: *mut ::dirent64, - result: *mut *mut ::dirent64) -> ::c_int; - pub fn setrlimit64(resource: ::c_int, rlim: *const rlimit64) -> ::c_int; - pub fn stat64(path: *const c_char, buf: *mut stat64) -> ::c_int; - pub fn truncate64(path: *const c_char, length: off64_t) -> ::c_int; - - pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; - - pub fn mknodat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t, dev: dev_t) -> ::c_int; - pub fn pthread_condattr_getclock(attr: *const pthread_condattr_t, - clock_id: *mut clockid_t) -> ::c_int; - pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, - clock_id: ::clockid_t) -> ::c_int; - pub fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, - pshared: ::c_int) -> ::c_int; - pub fn accept4(fd: ::c_int, addr: *mut ::sockaddr, len: *mut ::socklen_t, - flg: ::c_int) -> ::c_int; - pub fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, - pshared: ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, - val: *mut ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, - val: ::c_int) -> ::c_int; - pub fn ptsname_r(fd: ::c_int, - buf: *mut ::c_char, - buflen: ::size_t) -> ::c_int; - pub fn clearenv() -> ::c_int; - pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, - options: ::c_int) -> ::c_int; - pub fn setreuid(ruid: ::uid_t, euid: ::uid_t) -> ::c_int; - pub fn setregid(rgid: ::gid_t, egid: ::gid_t) -> ::c_int; - pub fn getresuid(ruid: *mut ::uid_t, euid: *mut ::uid_t, - suid: *mut ::uid_t) -> ::c_int; - pub fn getresgid(rgid: *mut ::gid_t, egid: *mut ::gid_t, - sgid: *mut ::gid_t) -> ::c_int; - pub fn acct(filename: *const ::c_char) -> ::c_int; - pub fn brk(addr: *mut ::c_void) -> ::c_int; - pub fn sbrk(increment: ::intptr_t) -> *mut ::c_void; - pub fn vfork() -> ::pid_t; - pub fn setresgid(rgid: ::gid_t, egid: ::gid_t, sgid: ::gid_t) -> ::c_int; - pub fn setresuid(ruid: ::uid_t, euid: ::uid_t, suid: ::uid_t) -> ::c_int; - pub fn wait4(pid: ::pid_t, status: *mut ::c_int, options: ::c_int, - rusage: *mut ::rusage) -> ::pid_t; - pub fn openpty(amaster: *mut ::c_int, - aslave: *mut ::c_int, - name: *mut ::c_char, - termp: *const termios, - winp: *const ::winsize) -> ::c_int; - pub fn execvpe(file: *const ::c_char, argv: *const *const ::c_char, - envp: *const *const ::c_char) -> ::c_int; - pub fn fexecve(fd: ::c_int, argv: *const *const ::c_char, - envp: *const *const ::c_char) - -> ::c_int; -} - -cfg_if! { - if #[cfg(target_os = "emscripten")] { - mod emscripten; - pub use self::emscripten::*; - } else if #[cfg(any(target_os = "linux", target_os = "fuchsia"))] { - mod linux; - pub use self::linux::*; - } else if #[cfg(target_os = "android")] { - mod android; - pub use self::android::*; - } else { - // Unknown target_os - } -} - // pub fn forkpty(amaster: *mut ::c_int, - // name: *mut ::c_char, - // termp: *const termios, - // winp: *const ::winsize) -> ::pid_t; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/solaris/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/solaris/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/solaris/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/solaris/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1398 +0,0 @@ -use dox::{mem, Option}; - -pub type c_char = i8; -pub type c_long = i64; -pub type c_ulong = u64; - -pub type clockid_t = ::c_int; -pub type blkcnt_t = ::c_long; -pub type clock_t = ::c_long; -pub type daddr_t = ::c_long; -pub type dev_t = ::c_ulong; -pub type fsblkcnt_t = ::c_ulong; -pub type fsfilcnt_t = ::c_ulong; -pub type ino_t = ::c_ulong; -pub type key_t = ::c_int; -pub type major_t = ::c_uint; -pub type minor_t = ::c_uint; -pub type mode_t = ::c_uint; -pub type nlink_t = ::c_uint; -pub type rlim_t = ::c_ulong; -pub type speed_t = ::c_uint; -pub type tcflag_t = ::c_uint; -pub type time_t = ::c_long; -pub type wchar_t = ::c_int; -pub type nfds_t = ::c_ulong; - -pub type suseconds_t = ::c_long; -pub type off_t = ::c_long; -pub type useconds_t = ::c_uint; -pub type socklen_t = ::c_uint; -pub type sa_family_t = u16; -pub type pthread_t = ::c_uint; -pub type pthread_key_t = ::c_uint; -pub type blksize_t = ::c_int; -pub type nl_item = ::c_int; -pub type id_t = ::c_int; -pub type idtype_t = ::c_uint; - -pub enum timezone {} - -s! { - pub struct sockaddr { - pub sa_family: sa_family_t, - pub sa_data: [::c_char; 14], - } - - pub struct sockaddr_in { - pub sin_family: sa_family_t, - pub sin_port: ::in_port_t, - pub sin_addr: ::in_addr, - pub sin_zero: [::c_char; 8] - } - - pub struct sockaddr_in6 { - pub sin6_family: sa_family_t, - pub sin6_port: ::in_port_t, - pub sin6_flowinfo: u32, - pub sin6_addr: ::in6_addr, - pub sin6_scope_id: u32, - pub __sin6_src_id: u32 - } - - pub struct sockaddr_un { - pub sun_family: sa_family_t, - pub sun_path: [c_char; 108] - } - - pub struct passwd { - pub pw_name: *mut ::c_char, - pub pw_passwd: *mut ::c_char, - pub pw_uid: ::uid_t, - pub pw_gid: ::gid_t, - pub pw_age: *mut ::c_char, - pub pw_comment: *mut ::c_char, - pub pw_gecos: *mut ::c_char, - pub pw_dir: *mut ::c_char, - pub pw_shell: *mut ::c_char - } - - pub struct ifaddrs { - pub ifa_next: *mut ifaddrs, - pub ifa_name: *mut ::c_char, - pub ifa_flags: ::c_ulong, - pub ifa_addr: *mut ::sockaddr, - pub ifa_netmask: *mut ::sockaddr, - pub ifa_dstaddr: *mut ::sockaddr, - pub ifa_data: *mut ::c_void - } - - pub struct tm { - pub tm_sec: ::c_int, - pub tm_min: ::c_int, - pub tm_hour: ::c_int, - pub tm_mday: ::c_int, - pub tm_mon: ::c_int, - pub tm_year: ::c_int, - pub tm_wday: ::c_int, - pub tm_yday: ::c_int, - pub tm_isdst: ::c_int - } - - pub struct utsname { - pub sysname: [::c_char; 257], - pub nodename: [::c_char; 257], - pub release: [::c_char; 257], - pub version: [::c_char; 257], - pub machine: [::c_char; 257], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::c_int, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::socklen_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::socklen_t, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct fd_set { - #[cfg(target_pointer_width = "64")] - fds_bits: [i64; FD_SETSIZE / 64], - #[cfg(target_pointer_width = "32")] - fds_bits: [i32; FD_SETSIZE / 32], - } - - pub struct pthread_attr_t { - __pthread_attrp: *mut ::c_void - } - - pub struct pthread_mutex_t { - __pthread_mutex_flag1: u16, - __pthread_mutex_flag2: u8, - __pthread_mutex_ceiling: u8, - __pthread_mutex_type: u16, - __pthread_mutex_magic: u16, - __pthread_mutex_lock: u64, - __pthread_mutex_data: u64 - } - - pub struct pthread_mutexattr_t { - __pthread_mutexattrp: *mut ::c_void - } - - pub struct pthread_cond_t { - __pthread_cond_flag: [u8; 4], - __pthread_cond_type: u16, - __pthread_cond_magic: u16, - __pthread_cond_data: u64 - } - - pub struct pthread_condattr_t { - __pthread_condattrp: *mut ::c_void, - } - - pub struct pthread_rwlock_t { - __pthread_rwlock_readers: i32, - __pthread_rwlock_type: u16, - __pthread_rwlock_magic: u16, - __pthread_rwlock_mutex: ::pthread_mutex_t, - __pthread_rwlock_readercv: ::pthread_cond_t, - __pthread_rwlock_writercv: ::pthread_cond_t - } - - pub struct pthread_rwlockattr_t { - __pthread_rwlockattrp: *mut ::c_void, - } - - pub struct dirent { - pub d_ino: ::ino_t, - pub d_off: ::off_t, - pub d_reclen: u16, - pub d_name: [::c_char; 3] - } - - pub struct glob_t { - pub gl_pathc: ::size_t, - pub gl_pathv: *mut *mut ::c_char, - pub gl_offs: ::size_t, - __unused1: *mut ::c_void, - __unused2: ::c_int, - __unused3: ::c_int, - __unused4: ::c_int, - __unused5: *mut ::c_void, - __unused6: *mut ::c_void, - __unused7: *mut ::c_void, - __unused8: *mut ::c_void, - __unused9: *mut ::c_void, - __unused10: *mut ::c_void, - } - - pub struct sockaddr_storage { - pub ss_family: ::sa_family_t, - __ss_pad1: [u8; 6], - __ss_align: i64, - __ss_pad2: [u8; 240], - } - - pub struct addrinfo { - pub ai_flags: ::c_int, - pub ai_family: ::c_int, - pub ai_socktype: ::c_int, - pub ai_protocol: ::c_int, - #[cfg(target_arch = "sparc64")] - __sparcv9_pad: ::c_int, - pub ai_addrlen: ::socklen_t, - pub ai_canonname: *mut ::c_char, - pub ai_addr: *mut ::sockaddr, - pub ai_next: *mut addrinfo, - } - - pub struct sigset_t { - bits: [u32; 4], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_code: ::c_int, - pub si_errno: ::c_int, - pub si_pad: ::c_int, - pub si_addr: *mut ::c_void, - __pad: [u8; 232], - } - - pub struct sigaction { - pub sa_flags: ::c_int, - pub sa_sigaction: ::sighandler_t, - pub sa_mask: sigset_t, - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_size: ::size_t, - pub ss_flags: ::c_int, - } - - pub struct statvfs { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_favail: ::fsfilcnt_t, - pub f_fsid: ::c_ulong, - pub f_basetype: [::c_char; 16], - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - pub f_fstr: [::c_char; 32] - } - - pub struct sched_param { - pub sched_priority: ::c_int, - sched_pad: [::c_int; 8] - } - - pub struct Dl_info { - pub dli_fname: *const ::c_char, - pub dli_fbase: *mut ::c_void, - pub dli_sname: *const ::c_char, - pub dli_saddr: *mut ::c_void, - } - - pub struct stat { - pub st_dev: ::dev_t, - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - pub st_size: ::off_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - __unused: [::c_char; 16] - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_cc: [::cc_t; ::NCCS] - } - - pub struct lconv { - pub decimal_point: *mut ::c_char, - pub thousands_sep: *mut ::c_char, - pub grouping: *mut ::c_char, - pub int_curr_symbol: *mut ::c_char, - pub currency_symbol: *mut ::c_char, - pub mon_decimal_point: *mut ::c_char, - pub mon_thousands_sep: *mut ::c_char, - pub mon_grouping: *mut ::c_char, - pub positive_sign: *mut ::c_char, - pub negative_sign: *mut ::c_char, - pub int_frac_digits: ::c_char, - pub frac_digits: ::c_char, - pub p_cs_precedes: ::c_char, - pub p_sep_by_space: ::c_char, - pub n_cs_precedes: ::c_char, - pub n_sep_by_space: ::c_char, - pub p_sign_posn: ::c_char, - pub n_sign_posn: ::c_char, - pub int_p_cs_precedes: ::c_char, - pub int_p_sep_by_space: ::c_char, - pub int_n_cs_precedes: ::c_char, - pub int_n_sep_by_space: ::c_char, - pub int_p_sign_posn: ::c_char, - pub int_n_sign_posn: ::c_char, - } - - pub struct sem_t { - pub sem_count: u32, - pub sem_type: u16, - pub sem_magic: u16, - pub sem_pad1: [u64; 3], - pub sem_pad2: [u64; 2] - } - - pub struct flock { - pub l_type: ::c_short, - pub l_whence: ::c_short, - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_sysid: ::c_int, - pub l_pid: ::pid_t, - pub l_pad: [::c_long; 4] - } - - pub struct if_nameindex { - pub if_index: ::c_uint, - pub if_name: *mut ::c_char, - } - - pub struct port_event { - pub portev_events: ::c_int, - pub portev_source: ::c_ushort, - pub portev_pad: ::c_ushort, - pub portev_object: ::uintptr_t, - pub portev_user: *mut ::c_void, - } -} - -pub const LC_CTYPE: ::c_int = 0; -pub const LC_NUMERIC: ::c_int = 1; -pub const LC_TIME: ::c_int = 2; -pub const LC_COLLATE: ::c_int = 3; -pub const LC_MONETARY: ::c_int = 4; -pub const LC_MESSAGES: ::c_int = 5; -pub const LC_ALL: ::c_int = 6; -pub const LC_CTYPE_MASK: ::c_int = (1 << LC_CTYPE); -pub const LC_NUMERIC_MASK: ::c_int = (1 << LC_NUMERIC); -pub const LC_TIME_MASK: ::c_int = (1 << LC_TIME); -pub const LC_COLLATE_MASK: ::c_int = (1 << LC_COLLATE); -pub const LC_MONETARY_MASK: ::c_int = (1 << LC_MONETARY); -pub const LC_MESSAGES_MASK: ::c_int = (1 << LC_MESSAGES); -pub const LC_ALL_MASK: ::c_int = LC_CTYPE_MASK - | LC_NUMERIC_MASK - | LC_TIME_MASK - | LC_COLLATE_MASK - | LC_MONETARY_MASK - | LC_MESSAGES_MASK; - -pub const DAY_1: ::nl_item = 1; -pub const DAY_2: ::nl_item = 2; -pub const DAY_3: ::nl_item = 3; -pub const DAY_4: ::nl_item = 4; -pub const DAY_5: ::nl_item = 5; -pub const DAY_6: ::nl_item = 6; -pub const DAY_7: ::nl_item = 7; - -pub const ABDAY_1: ::nl_item = 8; -pub const ABDAY_2: ::nl_item = 9; -pub const ABDAY_3: ::nl_item = 10; -pub const ABDAY_4: ::nl_item = 11; -pub const ABDAY_5: ::nl_item = 12; -pub const ABDAY_6: ::nl_item = 13; -pub const ABDAY_7: ::nl_item = 14; - -pub const MON_1: ::nl_item = 15; -pub const MON_2: ::nl_item = 16; -pub const MON_3: ::nl_item = 17; -pub const MON_4: ::nl_item = 18; -pub const MON_5: ::nl_item = 19; -pub const MON_6: ::nl_item = 20; -pub const MON_7: ::nl_item = 21; -pub const MON_8: ::nl_item = 22; -pub const MON_9: ::nl_item = 23; -pub const MON_10: ::nl_item = 24; -pub const MON_11: ::nl_item = 25; -pub const MON_12: ::nl_item = 26; - -pub const ABMON_1: ::nl_item = 27; -pub const ABMON_2: ::nl_item = 28; -pub const ABMON_3: ::nl_item = 29; -pub const ABMON_4: ::nl_item = 30; -pub const ABMON_5: ::nl_item = 31; -pub const ABMON_6: ::nl_item = 32; -pub const ABMON_7: ::nl_item = 33; -pub const ABMON_8: ::nl_item = 34; -pub const ABMON_9: ::nl_item = 35; -pub const ABMON_10: ::nl_item = 36; -pub const ABMON_11: ::nl_item = 37; -pub const ABMON_12: ::nl_item = 38; - -pub const RADIXCHAR: ::nl_item = 39; -pub const THOUSEP: ::nl_item = 40; -pub const YESSTR: ::nl_item = 41; -pub const NOSTR: ::nl_item = 42; -pub const CRNCYSTR: ::nl_item = 43; - -pub const D_T_FMT: ::nl_item = 44; -pub const D_FMT: ::nl_item = 45; -pub const T_FMT: ::nl_item = 46; -pub const AM_STR: ::nl_item = 47; -pub const PM_STR: ::nl_item = 48; - -pub const CODESET: ::nl_item = 49; -pub const T_FMT_AMPM: ::nl_item = 50; -pub const ERA: ::nl_item = 51; -pub const ERA_D_FMT: ::nl_item = 52; -pub const ERA_D_T_FMT: ::nl_item = 53; -pub const ERA_T_FMT: ::nl_item = 54; -pub const ALT_DIGITS: ::nl_item = 55; -pub const YESEXPR: ::nl_item = 56; -pub const NOEXPR: ::nl_item = 57; -pub const _DATE_FMT: ::nl_item = 58; -pub const MAXSTRMSG: ::nl_item = 58; - -pub const PATH_MAX: ::c_int = 1024; - -pub const SA_ONSTACK: ::c_int = 0x00000001; -pub const SA_RESETHAND: ::c_int = 0x00000002; -pub const SA_RESTART: ::c_int = 0x00000004; -pub const SA_SIGINFO: ::c_int = 0x00000008; -pub const SA_NODEFER: ::c_int = 0x00000010; -pub const SA_NOCLDWAIT: ::c_int = 0x00010000; -pub const SA_NOCLDSTOP: ::c_int = 0x00020000; - -pub const SS_ONSTACK: ::c_int = 1; -pub const SS_DISABLE: ::c_int = 2; - -pub const FIOCLEX: ::c_int = 0x20006601; -pub const FIONCLEX: ::c_int = 0x20006602; -pub const FIONREAD: ::c_int = 0x4004667f; -pub const FIONBIO: ::c_int = 0x8004667e; -pub const FIOASYNC: ::c_int = 0x8004667d; -pub const FIOSETOWN: ::c_int = 0x8004667c; -pub const FIOGETOWN: ::c_int = 0x4004667b; - -pub const SIGCHLD: ::c_int = 18; -pub const SIGBUS: ::c_int = 10; -pub const SIGINFO: ::c_int = 41; -pub const SIG_BLOCK: ::c_int = 1; -pub const SIG_UNBLOCK: ::c_int = 2; -pub const SIG_SETMASK: ::c_int = 3; - -pub const IPV6_MULTICAST_LOOP: ::c_int = 0x8; -pub const IPV6_V6ONLY: ::c_int = 0x27; - -cfg_if! { - if #[cfg(target_pointer_width = "64")] { - pub const FD_SETSIZE: usize = 65536; - } else { - pub const FD_SETSIZE: usize = 1024; - } -} - -pub const ST_RDONLY: ::c_ulong = 1; -pub const ST_NOSUID: ::c_ulong = 2; - -pub const NI_MAXHOST: ::socklen_t = 1025; - -pub const EXIT_FAILURE: ::c_int = 1; -pub const EXIT_SUCCESS: ::c_int = 0; -pub const RAND_MAX: ::c_int = 32767; -pub const EOF: ::c_int = -1; -pub const SEEK_SET: ::c_int = 0; -pub const SEEK_CUR: ::c_int = 1; -pub const SEEK_END: ::c_int = 2; -pub const _IOFBF: ::c_int = 0; -pub const _IONBF: ::c_int = 4; -pub const _IOLBF: ::c_int = 64; -pub const BUFSIZ: ::c_uint = 1024; -pub const FOPEN_MAX: ::c_uint = 20; -pub const FILENAME_MAX: ::c_uint = 1024; -pub const L_tmpnam: ::c_uint = 25; -pub const TMP_MAX: ::c_uint = 17576; - -pub const O_RDONLY: ::c_int = 0; -pub const O_WRONLY: ::c_int = 1; -pub const O_RDWR: ::c_int = 2; -pub const O_SEARCH: ::c_int = 0x200000; -pub const O_EXEC: ::c_int = 0x400000; -pub const O_APPEND: ::c_int = 8; -pub const O_CREAT: ::c_int = 256; -pub const O_EXCL: ::c_int = 1024; -pub const O_NOCTTY: ::c_int = 2048; -pub const O_TRUNC: ::c_int = 512; -pub const O_CLOEXEC: ::c_int = 0x800000; -pub const O_ACCMODE: ::c_int = 0x600003; -pub const S_IFIFO: mode_t = 4096; -pub const S_IFCHR: mode_t = 8192; -pub const S_IFBLK: mode_t = 24576; -pub const S_IFDIR: mode_t = 16384; -pub const S_IFREG: mode_t = 32768; -pub const S_IFLNK: mode_t = 40960; -pub const S_IFSOCK: mode_t = 49152; -pub const S_IFMT: mode_t = 61440; -pub const S_IEXEC: mode_t = 64; -pub const S_IWRITE: mode_t = 128; -pub const S_IREAD: mode_t = 256; -pub const S_IRWXU: mode_t = 448; -pub const S_IXUSR: mode_t = 64; -pub const S_IWUSR: mode_t = 128; -pub const S_IRUSR: mode_t = 256; -pub const S_IRWXG: mode_t = 56; -pub const S_IXGRP: mode_t = 8; -pub const S_IWGRP: mode_t = 16; -pub const S_IRGRP: mode_t = 32; -pub const S_IRWXO: mode_t = 7; -pub const S_IXOTH: mode_t = 1; -pub const S_IWOTH: mode_t = 2; -pub const S_IROTH: mode_t = 4; -pub const F_OK: ::c_int = 0; -pub const R_OK: ::c_int = 4; -pub const W_OK: ::c_int = 2; -pub const X_OK: ::c_int = 1; -pub const STDIN_FILENO: ::c_int = 0; -pub const STDOUT_FILENO: ::c_int = 1; -pub const STDERR_FILENO: ::c_int = 2; -pub const F_LOCK: ::c_int = 1; -pub const F_TEST: ::c_int = 3; -pub const F_TLOCK: ::c_int = 2; -pub const F_ULOCK: ::c_int = 0; -pub const F_DUPFD_CLOEXEC: ::c_int = 37; -pub const F_SETLK: ::c_int = 6; -pub const F_SETLKW: ::c_int = 7; -pub const F_GETLK: ::c_int = 14; -pub const SIGHUP: ::c_int = 1; -pub const SIGINT: ::c_int = 2; -pub const SIGQUIT: ::c_int = 3; -pub const SIGILL: ::c_int = 4; -pub const SIGABRT: ::c_int = 6; -pub const SIGEMT: ::c_int = 7; -pub const SIGFPE: ::c_int = 8; -pub const SIGKILL: ::c_int = 9; -pub const SIGSEGV: ::c_int = 11; -pub const SIGSYS: ::c_int = 12; -pub const SIGPIPE: ::c_int = 13; -pub const SIGALRM: ::c_int = 14; -pub const SIGTERM: ::c_int = 15; -pub const SIGUSR1: ::c_int = 16; -pub const SIGUSR2: ::c_int = 17; -pub const SIGPWR: ::c_int = 19; -pub const SIGWINCH: ::c_int = 20; -pub const SIGURG: ::c_int = 21; -pub const SIGPOLL: ::c_int = 22; -pub const SIGIO: ::c_int = SIGPOLL; -pub const SIGSTOP: ::c_int = 23; -pub const SIGTSTP: ::c_int = 24; -pub const SIGCONT: ::c_int = 25; -pub const SIGTTIN: ::c_int = 26; -pub const SIGTTOU: ::c_int = 27; -pub const SIGVTALRM: ::c_int = 28; -pub const SIGPROF: ::c_int = 29; -pub const SIGXCPU: ::c_int = 30; -pub const SIGXFSZ: ::c_int = 31; - -pub const WNOHANG: ::c_int = 0x40; -pub const WUNTRACED: ::c_int = 0x04; - -pub const WEXITED: ::c_int = 0x01; -pub const WTRAPPED: ::c_int = 0x02; -pub const WSTOPPED: ::c_int = WUNTRACED; -pub const WCONTINUED: ::c_int = 0x08; -pub const WNOWAIT: ::c_int = 0x80; - -pub const AT_FDCWD: ::c_int = 0xffd19553; -pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x1000; - -// Solaris defines a great many more of these; we only expose the -// standardized ones. -pub const P_PID: idtype_t = 0; -pub const P_PGID: idtype_t = 2; -pub const P_ALL: idtype_t = 7; - -pub const PROT_NONE: ::c_int = 0; -pub const PROT_READ: ::c_int = 1; -pub const PROT_WRITE: ::c_int = 2; -pub const PROT_EXEC: ::c_int = 4; - -pub const MAP_SHARED: ::c_int = 0x0001; -pub const MAP_PRIVATE: ::c_int = 0x0002; -pub const MAP_FIXED: ::c_int = 0x0010; -pub const MAP_NORESERVE: ::c_int = 0x40; -pub const MAP_ANON: ::c_int = 0x0100; -pub const MAP_RENAME: ::c_int = 0x20; -pub const MAP_ALIGN: ::c_int = 0x200; -pub const MAP_TEXT: ::c_int = 0x400; -pub const MAP_INITDATA: ::c_int = 0x800; -pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const MS_SYNC: ::c_int = 0x0004; -pub const MS_ASYNC: ::c_int = 0x0001; -pub const MS_INVALIDATE: ::c_int = 0x0002; -pub const MS_INVALCURPROC: ::c_int = 0x0008; - -pub const EPERM: ::c_int = 1; -pub const ENOENT: ::c_int = 2; -pub const ESRCH: ::c_int = 3; -pub const EINTR: ::c_int = 4; -pub const EIO: ::c_int = 5; -pub const ENXIO: ::c_int = 6; -pub const E2BIG: ::c_int = 7; -pub const ENOEXEC: ::c_int = 8; -pub const EBADF: ::c_int = 9; -pub const ECHILD: ::c_int = 10; -pub const EAGAIN: ::c_int = 11; -pub const ENOMEM: ::c_int = 12; -pub const EACCES: ::c_int = 13; -pub const EFAULT: ::c_int = 14; -pub const ENOTBLK: ::c_int = 15; -pub const EBUSY: ::c_int = 16; -pub const EEXIST: ::c_int = 17; -pub const EXDEV: ::c_int = 18; -pub const ENODEV: ::c_int = 19; -pub const ENOTDIR: ::c_int = 20; -pub const EISDIR: ::c_int = 21; -pub const EINVAL: ::c_int = 22; -pub const ENFILE: ::c_int = 23; -pub const EMFILE: ::c_int = 24; -pub const ENOTTY: ::c_int = 25; -pub const ETXTBSY: ::c_int = 26; -pub const EFBIG: ::c_int = 27; -pub const ENOSPC: ::c_int = 28; -pub const ESPIPE: ::c_int = 29; -pub const EROFS: ::c_int = 30; -pub const EMLINK: ::c_int = 31; -pub const EPIPE: ::c_int = 32; -pub const EDOM: ::c_int = 33; -pub const ERANGE: ::c_int = 34; -pub const ENOMSG: ::c_int = 35; -pub const EIDRM: ::c_int = 36; -pub const ECHRNG: ::c_int = 37; -pub const EL2NSYNC: ::c_int = 38; -pub const EL3HLT: ::c_int = 39; -pub const EL3RST: ::c_int = 40; -pub const ELNRNG: ::c_int = 41; -pub const EUNATCH: ::c_int = 42; -pub const ENOCSI: ::c_int = 43; -pub const EL2HLT: ::c_int = 44; -pub const EDEADLK: ::c_int = 45; -pub const ENOLCK: ::c_int = 46; -pub const ECANCELED: ::c_int = 47; -pub const ENOTSUP: ::c_int = 48; -pub const EDQUOT: ::c_int = 49; -pub const EBADE: ::c_int = 50; -pub const EBADR: ::c_int = 51; -pub const EXFULL: ::c_int = 52; -pub const ENOANO: ::c_int = 53; -pub const EBADRQC: ::c_int = 54; -pub const EBADSLT: ::c_int = 55; -pub const EDEADLOCK: ::c_int = 56; -pub const EBFONT: ::c_int = 57; -pub const EOWNERDEAD: ::c_int = 58; -pub const ENOTRECOVERABLE: ::c_int = 59; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENONET: ::c_int = 64; -pub const ENOPKG: ::c_int = 65; -pub const EREMOTE: ::c_int = 66; -pub const ENOLINK: ::c_int = 67; -pub const EADV: ::c_int = 68; -pub const ESRMNT: ::c_int = 69; -pub const ECOMM: ::c_int = 70; -pub const EPROTO: ::c_int = 71; -pub const ELOCKUNMAPPED: ::c_int = 72; -pub const ENOTACTIVE: ::c_int = 73; -pub const EMULTIHOP: ::c_int = 74; -pub const EADI: ::c_int = 75; -pub const EBADMSG: ::c_int = 77; -pub const ENAMETOOLONG: ::c_int = 78; -pub const EOVERFLOW: ::c_int = 79; -pub const ENOTUNIQ: ::c_int = 80; -pub const EBADFD: ::c_int = 81; -pub const EREMCHG: ::c_int = 82; -pub const ELIBACC: ::c_int = 83; -pub const ELIBBAD: ::c_int = 84; -pub const ELIBSCN: ::c_int = 85; -pub const ELIBMAX: ::c_int = 86; -pub const ELIBEXEC: ::c_int = 87; -pub const EILSEQ: ::c_int = 88; -pub const ENOSYS: ::c_int = 89; -pub const ELOOP: ::c_int = 90; -pub const ERESTART: ::c_int = 91; -pub const ESTRPIPE: ::c_int = 92; -pub const ENOTEMPTY: ::c_int = 93; -pub const EUSERS: ::c_int = 94; -pub const ENOTSOCK: ::c_int = 95; -pub const EDESTADDRREQ: ::c_int = 96; -pub const EMSGSIZE: ::c_int = 97; -pub const EPROTOTYPE: ::c_int = 98; -pub const ENOPROTOOPT: ::c_int = 99; -pub const EPROTONOSUPPORT: ::c_int = 120; -pub const ESOCKTNOSUPPORT: ::c_int = 121; -pub const EOPNOTSUPP: ::c_int = 122; -pub const EPFNOSUPPORT: ::c_int = 123; -pub const EAFNOSUPPORT: ::c_int = 124; -pub const EADDRINUSE: ::c_int = 125; -pub const EADDRNOTAVAIL: ::c_int = 126; -pub const ENETDOWN: ::c_int = 127; -pub const ENETUNREACH: ::c_int = 128; -pub const ENETRESET: ::c_int = 129; -pub const ECONNABORTED: ::c_int = 130; -pub const ECONNRESET: ::c_int = 131; -pub const ENOBUFS: ::c_int = 132; -pub const EISCONN: ::c_int = 133; -pub const ENOTCONN: ::c_int = 134; -pub const ESHUTDOWN: ::c_int = 143; -pub const ETOOMANYREFS: ::c_int = 144; -pub const ETIMEDOUT: ::c_int = 145; -pub const ECONNREFUSED: ::c_int = 146; -pub const EHOSTDOWN: ::c_int = 147; -pub const EHOSTUNREACH: ::c_int = 148; -pub const EWOULDBLOCK: ::c_int = EAGAIN; -pub const EALREADY: ::c_int = 149; -pub const EINPROGRESS: ::c_int = 150; - -pub const EAI_AGAIN: ::c_int = 2; -pub const EAI_BADFLAGS: ::c_int = 3; -pub const EAI_FAIL: ::c_int = 4; -pub const EAI_FAMILY: ::c_int = 5; -pub const EAI_MEMORY: ::c_int = 6; -pub const EAI_NODATA: ::c_int = 7; -pub const EAI_NONAME: ::c_int = 8; -pub const EAI_SERVICE: ::c_int = 9; -pub const EAI_SOCKTYPE: ::c_int = 10; -pub const EAI_SYSTEM: ::c_int = 11; -pub const EAI_OVERFLOW: ::c_int = 12; - -pub const F_DUPFD: ::c_int = 0; -pub const F_GETFD: ::c_int = 1; -pub const F_SETFD: ::c_int = 2; -pub const F_GETFL: ::c_int = 3; -pub const F_SETFL: ::c_int = 4; - -pub const SIGTRAP: ::c_int = 5; - -pub const GLOB_APPEND : ::c_int = 32; -pub const GLOB_DOOFFS : ::c_int = 16; -pub const GLOB_ERR : ::c_int = 1; -pub const GLOB_MARK : ::c_int = 2; -pub const GLOB_NOCHECK : ::c_int = 8; -pub const GLOB_NOSORT : ::c_int = 4; -pub const GLOB_NOESCAPE: ::c_int = 64; - -pub const GLOB_NOSPACE : ::c_int = -2; -pub const GLOB_ABORTED : ::c_int = -1; -pub const GLOB_NOMATCH : ::c_int = -3; - -pub const POLLIN: ::c_short = 0x1; -pub const POLLPRI: ::c_short = 0x2; -pub const POLLOUT: ::c_short = 0x4; -pub const POLLERR: ::c_short = 0x8; -pub const POLLHUP: ::c_short = 0x10; -pub const POLLNVAL: ::c_short = 0x20; - -pub const POSIX_MADV_NORMAL: ::c_int = 0; -pub const POSIX_MADV_RANDOM: ::c_int = 1; -pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; -pub const POSIX_MADV_WILLNEED: ::c_int = 3; -pub const POSIX_MADV_DONTNEED: ::c_int = 4; - -pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; -pub const PTHREAD_CREATE_DETACHED: ::c_int = 0x40; -pub const PTHREAD_PROCESS_SHARED: ::c_int = 1; -pub const PTHREAD_PROCESS_PRIVATE: ::c_ushort = 0; -pub const PTHREAD_STACK_MIN: ::size_t = 4096; - -pub const SIGSTKSZ: ::size_t = 8192; - -// https://illumos.org/man/3c/clock_gettime -// https://github.com/illumos/illumos-gate/ -// blob/HEAD/usr/src/lib/libc/amd64/sys/__clock_gettime.s -// clock_gettime(3c) doesn't seem to accept anything other than CLOCK_REALTIME -// or __CLOCK_REALTIME0 -// -// https://github.com/illumos/illumos-gate/ -// blob/HEAD/usr/src/uts/common/sys/time_impl.h -// Confusing! CLOCK_HIGHRES==CLOCK_MONOTONIC==4 -// __CLOCK_REALTIME0==0 is an obsoleted version of CLOCK_REALTIME==3 -pub const CLOCK_REALTIME: ::clockid_t = 3; -pub const CLOCK_MONOTONIC: ::clockid_t = 4; -pub const TIMER_RELTIME: ::c_int = 0; -pub const TIMER_ABSTIME: ::c_int = 1; - -pub const RLIMIT_CPU: ::c_int = 0; -pub const RLIMIT_FSIZE: ::c_int = 1; -pub const RLIMIT_DATA: ::c_int = 2; -pub const RLIMIT_STACK: ::c_int = 3; -pub const RLIMIT_CORE: ::c_int = 4; -pub const RLIMIT_NOFILE: ::c_int = 5; -pub const RLIMIT_VMEM: ::c_int = 6; -pub const RLIMIT_AS: ::c_int = RLIMIT_VMEM; - -pub const RLIM_NLIMITS: rlim_t = 7; -pub const RLIM_INFINITY: rlim_t = 0x7fffffff; - -pub const RUSAGE_SELF: ::c_int = 0; -pub const RUSAGE_CHILDREN: ::c_int = -1; - -pub const MADV_NORMAL: ::c_int = 0; -pub const MADV_RANDOM: ::c_int = 1; -pub const MADV_SEQUENTIAL: ::c_int = 2; -pub const MADV_WILLNEED: ::c_int = 3; -pub const MADV_DONTNEED: ::c_int = 4; -pub const MADV_FREE: ::c_int = 5; - -pub const AF_INET: ::c_int = 2; -pub const AF_INET6: ::c_int = 26; -pub const AF_UNIX: ::c_int = 1; -pub const SOCK_DGRAM: ::c_int = 1; -pub const SOCK_STREAM: ::c_int = 2; -pub const SOCK_RAW: ::c_int = 4; -pub const SOCK_RDM: ::c_int = 5; -pub const SOCK_SEQPACKET: ::c_int = 6; -pub const IP_MULTICAST_TTL: ::c_int = 17; -pub const IP_MULTICAST_LOOP: ::c_int = 18; -pub const IP_TTL: ::c_int = 4; -pub const IP_HDRINCL: ::c_int = 2; -pub const IP_ADD_MEMBERSHIP: ::c_int = 19; -pub const IP_DROP_MEMBERSHIP: ::c_int = 20; -pub const IPV6_JOIN_GROUP: ::c_int = 9; -pub const IPV6_LEAVE_GROUP: ::c_int = 10; - -pub const TCP_NODELAY: ::c_int = 1; -pub const TCP_KEEPIDLE: ::c_int = 34; -pub const SOL_SOCKET: ::c_int = 0xffff; -pub const SO_DEBUG: ::c_int = 0x01; -pub const SO_ACCEPTCONN: ::c_int = 0x0002; -pub const SO_REUSEADDR: ::c_int = 0x0004; -pub const SO_KEEPALIVE: ::c_int = 0x0008; -pub const SO_DONTROUTE: ::c_int = 0x0010; -pub const SO_BROADCAST: ::c_int = 0x0020; -pub const SO_USELOOPBACK: ::c_int = 0x0040; -pub const SO_LINGER: ::c_int = 0x0080; -pub const SO_OOBINLINE: ::c_int = 0x0100; -pub const SO_SNDBUF: ::c_int = 0x1001; -pub const SO_RCVBUF: ::c_int = 0x1002; -pub const SO_SNDLOWAT: ::c_int = 0x1003; -pub const SO_RCVLOWAT: ::c_int = 0x1004; -pub const SO_SNDTIMEO: ::c_int = 0x1005; -pub const SO_RCVTIMEO: ::c_int = 0x1006; -pub const SO_ERROR: ::c_int = 0x1007; -pub const SO_TYPE: ::c_int = 0x1008; - -pub const MSG_PEEK: ::c_int = 0x2; - -// https://docs.oracle.com/cd/E23824_01/html/821-1475/if-7p.html -pub const IFF_UP: ::c_int = 0x0000000001; // Address is up -pub const IFF_BROADCAST: ::c_int = 0x0000000002; // Broadcast address valid -pub const IFF_DEBUG: ::c_int = 0x0000000004; // Turn on debugging -pub const IFF_LOOPBACK: ::c_int = 0x0000000008; // Loopback net -pub const IFF_POINTOPOINT: ::c_int = 0x0000000010; // Interface is p-to-p -pub const IFF_NOTRAILERS: ::c_int = 0x0000000020; // Avoid use of trailers -pub const IFF_RUNNING: ::c_int = 0x0000000040; // Resources allocated -pub const IFF_NOARP: ::c_int = 0x0000000080; // No address res. protocol -pub const IFF_PROMISC: ::c_int = 0x0000000100; // Receive all packets -pub const IFF_ALLMULTI: ::c_int = 0x0000000200; // Receive all multicast pkts -pub const IFF_INTELLIGENT: ::c_int = 0x0000000400; // Protocol code on board -pub const IFF_MULTICAST: ::c_int = 0x0000000800; // Supports multicast -// Multicast using broadcst. add. -pub const IFF_MULTI_BCAST: ::c_int = 0x0000001000; -pub const IFF_UNNUMBERED: ::c_int = 0x0000002000; // Non-unique address -pub const IFF_DHCPRUNNING: ::c_int = 0x0000004000; // DHCP controls interface -pub const IFF_PRIVATE: ::c_int = 0x0000008000; // Do not advertise -pub const IFF_NOXMIT: ::c_int = 0x0000010000; // Do not transmit pkts -// No address - just on-link subnet -pub const IFF_NOLOCAL: ::c_int = 0x0000020000; -pub const IFF_DEPRECATED: ::c_int = 0x0000040000; // Address is deprecated -pub const IFF_ADDRCONF: ::c_int = 0x0000080000; // Addr. from stateless addrconf -pub const IFF_ROUTER: ::c_int = 0x0000100000; // Router on interface -pub const IFF_NONUD: ::c_int = 0x0000200000; // No NUD on interface -pub const IFF_ANYCAST: ::c_int = 0x0000400000; // Anycast address -pub const IFF_NORTEXCH: ::c_int = 0x0000800000; // Don't xchange rout. info -pub const IFF_IPV4: ::c_int = 0x0001000000; // IPv4 interface -pub const IFF_IPV6: ::c_int = 0x0002000000; // IPv6 interface -pub const IFF_NOFAILOVER: ::c_int = 0x0008000000; // in.mpathd test address -pub const IFF_FAILED: ::c_int = 0x0010000000; // Interface has failed -pub const IFF_STANDBY: ::c_int = 0x0020000000; // Interface is a hot-spare -pub const IFF_INACTIVE: ::c_int = 0x0040000000; // Functioning but not used -pub const IFF_OFFLINE: ::c_int = 0x0080000000; // Interface is offline -// If CoS marking is supported -pub const IFF_COS_ENABLED: ::c_longlong = 0x0200000000; -pub const IFF_PREFERRED: ::c_longlong = 0x0400000000; // Prefer as source addr. -pub const IFF_TEMPORARY: ::c_longlong = 0x0800000000; // RFC3041 -pub const IFF_FIXEDMTU: ::c_longlong = 0x1000000000; // MTU set with SIOCSLIFMTU -pub const IFF_VIRTUAL: ::c_longlong = 0x2000000000; // Cannot send/receive pkts -pub const IFF_DUPLICATE: ::c_longlong = 0x4000000000; // Local address in use -pub const IFF_IPMP: ::c_longlong = 0x8000000000; // IPMP IP interface - -pub const SHUT_RD: ::c_int = 0; -pub const SHUT_WR: ::c_int = 1; -pub const SHUT_RDWR: ::c_int = 2; - -pub const LOCK_SH: ::c_int = 1; -pub const LOCK_EX: ::c_int = 2; -pub const LOCK_NB: ::c_int = 4; -pub const LOCK_UN: ::c_int = 8; - -pub const F_RDLCK: ::c_short = 1; -pub const F_WRLCK: ::c_short = 2; -pub const F_UNLCK: ::c_short = 3; - -pub const O_SYNC: ::c_int = 16; -pub const O_NONBLOCK: ::c_int = 128; - -pub const IPPROTO_RAW: ::c_int = 255; - -pub const _PC_LINK_MAX: ::c_int = 1; -pub const _PC_MAX_CANON: ::c_int = 2; -pub const _PC_MAX_INPUT: ::c_int = 3; -pub const _PC_NAME_MAX: ::c_int = 4; -pub const _PC_PATH_MAX: ::c_int = 5; -pub const _PC_PIPE_BUF: ::c_int = 6; -pub const _PC_NO_TRUNC: ::c_int = 7; -pub const _PC_VDISABLE: ::c_int = 8; -pub const _PC_CHOWN_RESTRICTED: ::c_int = 9; -pub const _PC_ASYNC_IO: ::c_int = 10; -pub const _PC_PRIO_IO: ::c_int = 11; -pub const _PC_SYNC_IO: ::c_int = 12; -pub const _PC_ALLOC_SIZE_MIN: ::c_int = 13; -pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 14; -pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 15; -pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 16; -pub const _PC_REC_XFER_ALIGN: ::c_int = 17; -pub const _PC_SYMLINK_MAX: ::c_int = 18; -pub const _PC_2_SYMLINKS: ::c_int = 19; -pub const _PC_ACL_ENABLED: ::c_int = 20; -pub const _PC_MIN_HOLE_SIZE: ::c_int = 21; -pub const _PC_CASE_BEHAVIOR: ::c_int = 22; -pub const _PC_SATTR_ENABLED: ::c_int = 23; -pub const _PC_SATTR_EXISTS: ::c_int = 24; -pub const _PC_ACCESS_FILTERING: ::c_int = 25; -pub const _PC_TIMESTAMP_RESOLUTION: ::c_int = 26; -pub const _PC_FILESIZEBITS: ::c_int = 67; -pub const _PC_XATTR_ENABLED: ::c_int = 100; -pub const _PC_LAST: ::c_int = 101; -pub const _PC_XATTR_EXISTS: ::c_int = 101; - -pub const _SC_ARG_MAX: ::c_int = 1; -pub const _SC_CHILD_MAX: ::c_int = 2; -pub const _SC_CLK_TCK: ::c_int = 3; -pub const _SC_NGROUPS_MAX: ::c_int = 4; -pub const _SC_OPEN_MAX: ::c_int = 5; -pub const _SC_JOB_CONTROL: ::c_int = 6; -pub const _SC_SAVED_IDS: ::c_int = 7; -pub const _SC_VERSION: ::c_int = 8; -pub const _SC_PASS_MAX: ::c_int = 9; -pub const _SC_LOGNAME_MAX: ::c_int = 10; -pub const _SC_PAGESIZE: ::c_int = 11; -pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; -pub const _SC_XOPEN_VERSION: ::c_int = 12; -pub const _SC_NPROCESSORS_CONF: ::c_int = 14; -pub const _SC_NPROCESSORS_ONLN: ::c_int = 15; -pub const _SC_STREAM_MAX: ::c_int = 16; -pub const _SC_TZNAME_MAX: ::c_int = 17; -pub const _SC_AIO_LISTIO_MAX: ::c_int = 18; -pub const _SC_AIO_MAX: ::c_int = 19; -pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 20; -pub const _SC_ASYNCHRONOUS_IO: ::c_int = 21; -pub const _SC_DELAYTIMER_MAX: ::c_int = 22; -pub const _SC_FSYNC: ::c_int = 23; -pub const _SC_MAPPED_FILES: ::c_int = 24; -pub const _SC_MEMLOCK: ::c_int = 25; -pub const _SC_MEMLOCK_RANGE: ::c_int = 26; -pub const _SC_MEMORY_PROTECTION: ::c_int = 27; -pub const _SC_MESSAGE_PASSING: ::c_int = 28; -pub const _SC_MQ_OPEN_MAX: ::c_int = 29; -pub const _SC_MQ_PRIO_MAX: ::c_int = 30; -pub const _SC_PRIORITIZED_IO: ::c_int = 31; -pub const _SC_PRIORITY_SCHEDULING: ::c_int = 32; -pub const _SC_REALTIME_SIGNALS: ::c_int = 33; -pub const _SC_RTSIG_MAX: ::c_int = 34; -pub const _SC_SEMAPHORES: ::c_int = 35; -pub const _SC_SEM_NSEMS_MAX: ::c_int = 36; -pub const _SC_SEM_VALUE_MAX: ::c_int = 37; -pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 38; -pub const _SC_SIGQUEUE_MAX: ::c_int = 39; -pub const _SC_SIGRT_MIN: ::c_int = 40; -pub const _SC_SIGRT_MAX: ::c_int = 41; -pub const _SC_SYNCHRONIZED_IO: ::c_int = 42; -pub const _SC_TIMERS: ::c_int = 43; -pub const _SC_TIMER_MAX: ::c_int = 44; -pub const _SC_2_C_BIND: ::c_int = 45; -pub const _SC_2_C_DEV: ::c_int = 46; -pub const _SC_2_C_VERSION: ::c_int = 47; -pub const _SC_2_FORT_DEV: ::c_int = 48; -pub const _SC_2_FORT_RUN: ::c_int = 49; -pub const _SC_2_LOCALEDEF: ::c_int = 50; -pub const _SC_2_SW_DEV: ::c_int = 51; -pub const _SC_2_UPE: ::c_int = 52; -pub const _SC_2_VERSION: ::c_int = 53; -pub const _SC_BC_BASE_MAX: ::c_int = 54; -pub const _SC_BC_DIM_MAX: ::c_int = 55; -pub const _SC_BC_SCALE_MAX: ::c_int = 56; -pub const _SC_BC_STRING_MAX: ::c_int = 57; -pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 58; -pub const _SC_EXPR_NEST_MAX: ::c_int = 59; -pub const _SC_LINE_MAX: ::c_int = 60; -pub const _SC_RE_DUP_MAX: ::c_int = 61; -pub const _SC_XOPEN_CRYPT: ::c_int = 62; -pub const _SC_XOPEN_ENH_I18N: ::c_int = 63; -pub const _SC_XOPEN_SHM: ::c_int = 64; -pub const _SC_2_CHAR_TERM: ::c_int = 66; -pub const _SC_XOPEN_XCU_VERSION: ::c_int = 67; -pub const _SC_ATEXIT_MAX: ::c_int = 76; -pub const _SC_IOV_MAX: ::c_int = 77; -pub const _SC_XOPEN_UNIX: ::c_int = 78; -pub const _SC_T_IOV_MAX: ::c_int = 79; -pub const _SC_PHYS_PAGES: ::c_int = 500; -pub const _SC_AVPHYS_PAGES: ::c_int = 501; -pub const _SC_COHER_BLKSZ: ::c_int = 503; -pub const _SC_SPLIT_CACHE: ::c_int = 504; -pub const _SC_ICACHE_SZ: ::c_int = 505; -pub const _SC_DCACHE_SZ: ::c_int = 506; -pub const _SC_ICACHE_LINESZ: ::c_int = 507; -pub const _SC_DCACHE_LINESZ: ::c_int = 508; -pub const _SC_ICACHE_BLKSZ: ::c_int = 509; -pub const _SC_DCACHE_BLKSZ: ::c_int = 510; -pub const _SC_DCACHE_TBLKSZ: ::c_int = 511; -pub const _SC_ICACHE_ASSOC: ::c_int = 512; -pub const _SC_DCACHE_ASSOC: ::c_int = 513; -pub const _SC_MAXPID: ::c_int = 514; -pub const _SC_STACK_PROT: ::c_int = 515; -pub const _SC_NPROCESSORS_MAX: ::c_int = 516; -pub const _SC_CPUID_MAX: ::c_int = 517; -pub const _SC_EPHID_MAX: ::c_int = 518; -pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 568; -pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 569; -pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 570; -pub const _SC_LOGIN_NAME_MAX: ::c_int = 571; -pub const _SC_THREAD_KEYS_MAX: ::c_int = 572; -pub const _SC_THREAD_STACK_MIN: ::c_int = 573; -pub const _SC_THREAD_THREADS_MAX: ::c_int = 574; -pub const _SC_TTY_NAME_MAX: ::c_int = 575; -pub const _SC_THREADS: ::c_int = 576; -pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 577; -pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 578; -pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 579; -pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 580; -pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 581; -pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 582; -pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 583; -pub const _SC_XOPEN_LEGACY: ::c_int = 717; -pub const _SC_XOPEN_REALTIME: ::c_int = 718; -pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 719; -pub const _SC_XBS5_ILP32_OFF32: ::c_int = 720; -pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 721; -pub const _SC_XBS5_LP64_OFF64: ::c_int = 722; -pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 723; -pub const _SC_2_PBS: ::c_int = 724; -pub const _SC_2_PBS_ACCOUNTING: ::c_int = 725; -pub const _SC_2_PBS_CHECKPOINT: ::c_int = 726; -pub const _SC_2_PBS_LOCATE: ::c_int = 728; -pub const _SC_2_PBS_MESSAGE: ::c_int = 729; -pub const _SC_2_PBS_TRACK: ::c_int = 730; -pub const _SC_ADVISORY_INFO: ::c_int = 731; -pub const _SC_BARRIERS: ::c_int = 732; -pub const _SC_CLOCK_SELECTION: ::c_int = 733; -pub const _SC_CPUTIME: ::c_int = 734; -pub const _SC_HOST_NAME_MAX: ::c_int = 735; -pub const _SC_MONOTONIC_CLOCK: ::c_int = 736; -pub const _SC_READER_WRITER_LOCKS: ::c_int = 737; -pub const _SC_REGEXP: ::c_int = 738; -pub const _SC_SHELL: ::c_int = 739; -pub const _SC_SPAWN: ::c_int = 740; -pub const _SC_SPIN_LOCKS: ::c_int = 741; -pub const _SC_SPORADIC_SERVER: ::c_int = 742; -pub const _SC_SS_REPL_MAX: ::c_int = 743; -pub const _SC_SYMLOOP_MAX: ::c_int = 744; -pub const _SC_THREAD_CPUTIME: ::c_int = 745; -pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 746; -pub const _SC_TIMEOUTS: ::c_int = 747; -pub const _SC_TRACE: ::c_int = 748; -pub const _SC_TRACE_EVENT_FILTER: ::c_int = 749; -pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 750; -pub const _SC_TRACE_INHERIT: ::c_int = 751; -pub const _SC_TRACE_LOG: ::c_int = 752; -pub const _SC_TRACE_NAME_MAX: ::c_int = 753; -pub const _SC_TRACE_SYS_MAX: ::c_int = 754; -pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 755; -pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 756; -pub const _SC_V6_ILP32_OFF32: ::c_int = 757; -pub const _SC_V6_ILP32_OFFBIG: ::c_int = 758; -pub const _SC_V6_LP64_OFF64: ::c_int = 759; -pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 760; -pub const _SC_XOPEN_STREAMS: ::c_int = 761; -pub const _SC_IPV6: ::c_int = 762; -pub const _SC_RAW_SOCKETS: ::c_int = 763; - -pub const _MUTEX_MAGIC: u16 = 0x4d58; // MX -pub const _COND_MAGIC: u16 = 0x4356; // CV -pub const _RWL_MAGIC: u16 = 0x5257; // RW - -pub const NCCS: usize = 19; - -pub const LOG_CRON: ::c_int = 15 << 3; - -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { - __pthread_mutex_flag1: 0, - __pthread_mutex_flag2: 0, - __pthread_mutex_ceiling: 0, - __pthread_mutex_type: PTHREAD_PROCESS_PRIVATE, - __pthread_mutex_magic: _MUTEX_MAGIC, - __pthread_mutex_lock: 0, - __pthread_mutex_data: 0 -}; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { - __pthread_cond_flag: [0; 4], - __pthread_cond_type: PTHREAD_PROCESS_PRIVATE, - __pthread_cond_magic: _COND_MAGIC, - __pthread_cond_data: 0 -}; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { - __pthread_rwlock_readers: 0, - __pthread_rwlock_type: PTHREAD_PROCESS_PRIVATE, - __pthread_rwlock_magic: _RWL_MAGIC, - __pthread_rwlock_mutex: PTHREAD_MUTEX_INITIALIZER, - __pthread_rwlock_readercv: PTHREAD_COND_INITIALIZER, - __pthread_rwlock_writercv: PTHREAD_COND_INITIALIZER -}; -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 4; -pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; - -pub const RTLD_NEXT: *mut ::c_void = -1isize as *mut ::c_void; -pub const RTLD_DEFAULT: *mut ::c_void = -2isize as *mut ::c_void; -pub const RTLD_SELF: *mut ::c_void = -3isize as *mut ::c_void; -pub const RTLD_PROBE: *mut ::c_void = -4isize as *mut ::c_void; - -pub const RTLD_LAZY: ::c_int = 0x1; -pub const RTLD_NOW: ::c_int = 0x2; -pub const RTLD_NOLOAD: ::c_int = 0x4; -pub const RTLD_GLOBAL: ::c_int = 0x100; -pub const RTLD_LOCAL: ::c_int = 0x0; -pub const RTLD_PARENT: ::c_int = 0x200; -pub const RTLD_GROUP: ::c_int = 0x400; -pub const RTLD_WORLD: ::c_int = 0x800; -pub const RTLD_NODELETE: ::c_int = 0x1000; -pub const RTLD_FIRST: ::c_int = 0x2000; -pub const RTLD_CONFGEN: ::c_int = 0x10000; - -pub const PORT_SOURCE_AIO: ::c_int = 1; -pub const PORT_SOURCE_TIMER: ::c_int = 2; -pub const PORT_SOURCE_USER: ::c_int = 3; -pub const PORT_SOURCE_FD: ::c_int = 4; -pub const PORT_SOURCE_ALERT: ::c_int = 5; -pub const PORT_SOURCE_MQ: ::c_int = 6; -pub const PORT_SOURCE_FILE: ::c_int = 7; -pub const PORT_SOURCE_POSTWAIT: ::c_int = 8; -pub const PORT_SOURCE_SIGNAL: ::c_int = 9; - -f! { - pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { - let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; - let fd = fd as usize; - (*set).fds_bits[fd / bits] &= !(1 << (fd % bits)); - return - } - - pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { - let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; - let fd = fd as usize; - return ((*set).fds_bits[fd / bits] & (1 << (fd % bits))) != 0 - } - - pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { - let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; - let fd = fd as usize; - (*set).fds_bits[fd / bits] |= 1 << (fd % bits); - return - } - - pub fn FD_ZERO(set: *mut fd_set) -> () { - for slot in (*set).fds_bits.iter_mut() { - *slot = 0; - } - } - - pub fn WIFEXITED(status: ::c_int) -> bool { - (status & 0xFF) == 0 - } - - pub fn WEXITSTATUS(status: ::c_int) -> ::c_int { - (status >> 8) & 0xFF - } - - pub fn WTERMSIG(status: ::c_int) -> ::c_int { - status & 0x7F - } -} - -extern { - pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; - pub fn freeifaddrs(ifa: *mut ::ifaddrs); - - pub fn stack_getbounds(sp: *mut ::stack_t) -> ::c_int; - pub fn mincore(addr: *const ::c_void, len: ::size_t, - vec: *mut c_char) -> ::c_int; - pub fn setgroups(ngroups: ::c_int, - ptr: *const ::gid_t) -> ::c_int; - pub fn ioctl(fildes: ::c_int, request: ::c_int, ...) -> ::c_int; - pub fn mprotect(addr: *const ::c_void, len: ::size_t, prot: ::c_int) - -> ::c_int; - pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_nanosleep(clk_id: ::clockid_t, - flags: ::c_int, - rqtp: *const ::timespec, - rmtp: *mut ::timespec) -> ::c_int; - pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; - pub fn getnameinfo(sa: *const ::sockaddr, - salen: ::socklen_t, - host: *mut ::c_char, - hostlen: ::socklen_t, - serv: *mut ::c_char, - sevlen: ::socklen_t, - flags: ::c_int) -> ::c_int; - pub fn setpwent(); - pub fn endpwent(); - pub fn getpwent() -> *mut passwd; - pub fn fdatasync(fd: ::c_int) -> ::c_int; - pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; - pub fn duplocale(base: ::locale_t) -> ::locale_t; - pub fn freelocale(loc: ::locale_t); - pub fn newlocale(mask: ::c_int, - locale: *const ::c_char, - base: ::locale_t) -> ::locale_t; - pub fn uselocale(loc: ::locale_t) -> ::locale_t; - pub fn getprogname() -> *const ::c_char; - pub fn setprogname(name: *const ::c_char); - pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int; - pub fn getpriority(which: ::c_int, who: ::c_int) -> ::c_int; - pub fn setpriority(which: ::c_int, who: ::c_int, prio: ::c_int) -> ::c_int; - - pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; - - pub fn mknodat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t, dev: dev_t) -> ::c_int; - pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t) -> ::c_int; - pub fn sethostname(name: *mut ::c_char, len: ::c_int) -> ::c_int; - pub fn if_nameindex() -> *mut if_nameindex; - pub fn if_freenameindex(ptr: *mut if_nameindex); - pub fn pthread_create(native: *mut ::pthread_t, - attr: *const ::pthread_attr_t, - f: extern fn(*mut ::c_void) -> *mut ::c_void, - value: *mut ::c_void) -> ::c_int; - pub fn pthread_condattr_getclock(attr: *const pthread_condattr_t, - clock_id: *mut clockid_t) -> ::c_int; - pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, - clock_id: ::clockid_t) -> ::c_int; - pub fn sem_timedwait(sem: *mut sem_t, - abstime: *const ::timespec) -> ::c_int; - pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, - abstime: *const ::timespec) -> ::c_int; - pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, - options: ::c_int) -> ::c_int; - - pub fn glob(pattern: *const ::c_char, - flags: ::c_int, - errfunc: Option ::c_int>, - pglob: *mut ::glob_t) -> ::c_int; - - pub fn globfree(pglob: *mut ::glob_t); - - pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - pub fn shm_unlink(name: *const ::c_char) -> ::c_int; - - pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); - - pub fn telldir(dirp: *mut ::DIR) -> ::c_long; - pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; - - pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; - - pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, - flags: ::c_int, addr: *mut ::sockaddr, - addrlen: *mut ::socklen_t) -> ::ssize_t; - pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; - pub fn futimesat(fd: ::c_int, path: *const ::c_char, - times: *const ::timeval) -> ::c_int; - pub fn utimensat(dirfd: ::c_int, path: *const ::c_char, - times: *const ::timespec, flag: ::c_int) -> ::c_int; - pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; - - pub fn bind(socket: ::c_int, address: *const ::sockaddr, - address_len: ::socklen_t) -> ::c_int; - - pub fn writev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - pub fn readv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - - pub fn sendmsg(fd: ::c_int, - msg: *const ::msghdr, - flags: ::c_int) -> ::ssize_t; - pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) - -> ::ssize_t; - - pub fn port_create() -> ::c_int; - pub fn port_associate(port: ::c_int, source: ::c_int, object: ::uintptr_t, - events: ::c_int, user: *mut ::c_void) -> ::c_int; - pub fn port_dissociate(port: ::c_int, source: ::c_int, object: ::uintptr_t) - -> ::c_int; - pub fn port_get(port: ::c_int, pe: *mut port_event, - timeout: *mut ::timespec) -> ::c_int; - pub fn port_getn(port: ::c_int, pe_list: *mut port_event, max: ::c_uint, - nget: *mut ::c_uint, timeout: *mut ::timespec) - -> ::c_int; - pub fn fexecve(fd: ::c_int, argv: *const *const ::c_char, - envp: *const *const ::c_char) - -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] - pub fn getgrgid_r(uid: ::uid_t, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - pub fn sigaltstack(ss: *const stack_t, - oss: *mut stack_t) -> ::c_int; - pub fn sem_close(sem: *mut sem_t) -> ::c_int; - pub fn getdtablesize() -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] - pub fn getgrnam_r(name: *const ::c_char, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, - oldset: *mut sigset_t) -> ::c_int; - pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; - pub fn getgrnam(name: *const ::c_char) -> *mut ::group; - pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; - pub fn sem_unlink(name: *const ::c_char) -> ::c_int; - pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] - pub fn getpwnam_r(name: *const ::c_char, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] - pub fn getpwuid_r(uid: ::uid_t, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] - pub fn sigwait(set: *const sigset_t, - sig: *mut ::c_int) -> ::c_int; - pub fn pthread_atfork(prepare: Option, - parent: Option, - child: Option) -> ::c_int; - pub fn getgrgid(gid: ::gid_t) -> *mut ::group; - pub fn popen(command: *const c_char, - mode: *const c_char) -> *mut ::FILE; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/uclibc/mips/mips32.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/uclibc/mips/mips32.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/uclibc/mips/mips32.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/uclibc/mips/mips32.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,269 +0,0 @@ -pub type c_char = i8; -pub type c_long = i32; -pub type c_ulong = u32; -pub type clock_t = i32; -pub type time_t = i32; -pub type suseconds_t = i32; -pub type wchar_t = i32; -pub type off_t = i32; -pub type ino_t = u32; -pub type blkcnt_t = i32; -pub type blksize_t = i32; -pub type nlink_t = u32; -pub type fsblkcnt_t = ::c_ulong; -pub type fsfilcnt_t = ::c_ulong; -pub type rlim_t = c_ulong; - -s! { - pub struct stat { - pub st_dev: ::dev_t, - st_pad1: [::c_long; 2], - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - pub st_pad2: [::c_long; 1], - pub st_size: ::off_t, - st_pad3: ::c_long, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - st_pad5: [::c_long; 14], - } - - pub struct stat64 { - pub st_dev: ::dev_t, - st_pad1: [::c_long; 2], - pub st_ino: ::ino64_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::dev_t, - st_pad2: [::c_long; 2], - pub st_size: ::off64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - st_pad3: ::c_long, - pub st_blocks: ::blkcnt64_t, - st_pad5: [::c_long; 14], - } - - pub struct pthread_attr_t { - __size: [u32; 9] - } - - pub struct sigaction { - pub sa_flags: ::c_int, - pub sa_sigaction: ::sighandler_t, - pub sa_mask: sigset_t, - _restorer: *mut ::c_void, - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_size: ::size_t, - pub ss_flags: ::c_int, - } - - pub struct sigset_t { - __val: [::c_ulong; 4], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_code: ::c_int, - pub si_errno: ::c_int, - pub _pad: [::c_int; 29], - } - - pub struct glob64_t { - pub gl_pathc: ::size_t, - pub gl_pathv: *mut *mut ::c_char, - pub gl_offs: ::size_t, - pub gl_flags: ::c_int, - - __unused1: *mut ::c_void, - __unused2: *mut ::c_void, - __unused3: *mut ::c_void, - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - } - - pub struct ipc_perm { - pub __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::c_uint, - pub __seq: ::c_ushort, - __pad1: ::c_ushort, - __unused1: ::c_ulong, - __unused2: ::c_ulong - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __unused4: ::c_ulong, - __unused5: ::c_ulong - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - #[cfg(target_endian = "big")] - __glibc_reserved1: ::c_ulong, - pub msg_stime: ::time_t, - #[cfg(target_endian = "little")] - __glibc_reserved1: ::c_ulong, - #[cfg(target_endian = "big")] - __glibc_reserved2: ::c_ulong, - pub msg_rtime: ::time_t, - #[cfg(target_endian = "little")] - __glibc_reserved2: ::c_ulong, - #[cfg(target_endian = "big")] - __glibc_reserved3: ::c_ulong, - pub msg_ctime: ::time_t, - #[cfg(target_endian = "little")] - __glibc_reserved3: ::c_ulong, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __glibc_reserved4: ::c_ulong, - __glibc_reserved5: ::c_ulong, - } - - pub struct statfs { - pub f_type: ::c_long, - pub f_bsize: ::c_long, - pub f_frsize: ::c_long, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_files: ::fsblkcnt_t, - pub f_ffree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_fsid: ::fsid_t, - - pub f_namelen: ::c_long, - f_spare: [::c_long; 6], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::c_int, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::size_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::size_t, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; ::NCCS], - } - - pub struct flock { - pub l_type: ::c_short, - pub l_whence: ::c_short, - pub l_start: ::off_t, - pub l_len: ::off_t, - pub l_sysid: ::c_long, - pub l_pid: ::pid_t, - pad: [::c_long; 4], - } - - pub struct sysinfo { - pub uptime: ::c_long, - pub loads: [::c_ulong; 3], - pub totalram: ::c_ulong, - pub freeram: ::c_ulong, - pub sharedram: ::c_ulong, - pub bufferram: ::c_ulong, - pub totalswap: ::c_ulong, - pub freeswap: ::c_ulong, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: ::c_ulong, - pub freehigh: ::c_ulong, - pub mem_unit: ::c_uint, - pub _f: [::c_char; 8], - } - - // FIXME this is actually a union - pub struct sem_t { - #[cfg(target_pointer_width = "32")] - __size: [::c_char; 16], - #[cfg(target_pointer_width = "64")] - __size: [::c_char; 32], - __align: [::c_long; 0], - } -} - -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 24; -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 32; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; - -pub const RLIM_INFINITY: ::rlim_t = 0x7fffffff; - -pub const SYS_gettid: ::c_long = 4222; // Valid for O32 - -#[link(name = "util")] -extern { - pub fn sysctl(name: *mut ::c_int, - namelen: ::c_int, - oldp: *mut ::c_void, - oldlenp: *mut ::size_t, - newp: *mut ::c_void, - newlen: ::size_t) - -> ::c_int; - pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; - pub fn backtrace(buf: *mut *mut ::c_void, - sz: ::c_int) -> ::c_int; - pub fn glob64(pattern: *const ::c_char, - flags: ::c_int, - errfunc: ::dox::Option ::c_int>, - pglob: *mut glob64_t) -> ::c_int; - pub fn globfree64(pglob: *mut glob64_t); - pub fn ptrace(request: ::c_uint, ...) -> ::c_long; - pub fn pthread_attr_getaffinity_np(attr: *const ::pthread_attr_t, - cpusetsize: ::size_t, - cpuset: *mut ::cpu_set_t) -> ::c_int; - pub fn pthread_attr_setaffinity_np(attr: *mut ::pthread_attr_t, - cpusetsize: ::size_t, - cpuset: *const ::cpu_set_t) -> ::c_int; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/uclibc/mips/mips64.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/uclibc/mips/mips64.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/uclibc/mips/mips64.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/uclibc/mips/mips64.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,209 +0,0 @@ -pub type blkcnt_t = i64; -pub type blksize_t = i64; -pub type c_char = i8; -pub type c_long = i64; -pub type c_ulong = u64; -pub type fsblkcnt_t = ::c_ulong; -pub type fsfilcnt_t = ::c_ulong; -pub type ino_t = u64; -pub type nlink_t = u64; -pub type off_t = i64; -pub type rlim_t = ::c_ulong; -pub type suseconds_t = i64; -pub type time_t = i64; -pub type wchar_t = i32; - -s! { - pub struct stat { - pub st_dev: ::c_ulong, - st_pad1: [::c_long; 2], - pub st_ino: ::ino_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::c_ulong, - st_pad2: [::c_ulong; 1], - pub st_size: ::off_t, - st_pad3: ::c_long, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - st_pad4: ::c_long, - pub st_blocks: ::blkcnt_t, - st_pad5: [::c_long; 7], - } - - pub struct stat64 { - pub st_dev: ::c_ulong, - st_pad1: [::c_long; 2], - pub st_ino: ::ino64_t, - pub st_mode: ::mode_t, - pub st_nlink: ::nlink_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::c_ulong, - st_pad2: [::c_long; 2], - pub st_size: ::off64_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_long, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_long, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_long, - pub st_blksize: ::blksize_t, - st_pad3: ::c_long, - pub st_blocks: ::blkcnt64_t, - st_pad5: [::c_long; 7], - } - - pub struct pthread_attr_t { - __size: [::c_ulong; 7] - } - - pub struct sigaction { - pub sa_flags: ::c_int, - pub sa_sigaction: ::sighandler_t, - pub sa_mask: sigset_t, - _restorer: *mut ::c_void, - } - - pub struct stack_t { - pub ss_sp: *mut ::c_void, - pub ss_size: ::size_t, - pub ss_flags: ::c_int, - } - - pub struct sigset_t { - __size: [::c_ulong; 16], - } - - pub struct siginfo_t { - pub si_signo: ::c_int, - pub si_code: ::c_int, - pub si_errno: ::c_int, - _pad: ::c_int, - _pad2: [::c_long; 14], - } - - pub struct ipc_perm { - pub __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::c_uint, - pub __seq: ::c_ushort, - __pad1: ::c_ushort, - __unused1: ::c_ulong, - __unused2: ::c_ulong - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, - pub shm_atime: ::time_t, - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __unused4: ::c_ulong, - __unused5: ::c_ulong - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - pub msg_stime: ::time_t, - pub msg_rtime: ::time_t, - pub msg_ctime: ::time_t, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __glibc_reserved4: ::c_ulong, - __glibc_reserved5: ::c_ulong, - } - - pub struct statfs { - pub f_type: ::c_long, - pub f_bsize: ::c_long, - pub f_frsize: ::c_long, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_files: ::fsblkcnt_t, - pub f_ffree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_fsid: ::fsid_t, - - pub f_namelen: ::c_long, - f_spare: [::c_long; 6], - } - - pub struct msghdr { - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::size_t, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::size_t, - pub msg_flags: ::c_int, - } - - pub struct cmsghdr { - pub cmsg_len: ::size_t, - pub cmsg_level: ::c_int, - pub cmsg_type: ::c_int, - } - - pub struct termios { - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; ::NCCS], - } - - pub struct sysinfo { - pub uptime: ::c_long, - pub loads: [::c_ulong; 3], - pub totalram: ::c_ulong, - pub freeram: ::c_ulong, - pub sharedram: ::c_ulong, - pub bufferram: ::c_ulong, - pub totalswap: ::c_ulong, - pub freeswap: ::c_ulong, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: ::c_ulong, - pub freehigh: ::c_ulong, - pub mem_unit: ::c_uint, - pub _f: [::c_char; 0], - } - - // FIXME this is actually a union - pub struct sem_t { - __size: [::c_char; 32], - __align: [::c_long; 0], - } -} - -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; - -pub const RLIM_INFINITY: ::rlim_t = 0xffff_ffff_ffff_ffff; - -pub const SYS_gettid: ::c_long = 5178; // Valid for n64 - -#[link(name = "util")] -extern { - pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/uclibc/mips/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/uclibc/mips/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/uclibc/mips/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/uclibc/mips/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,476 +0,0 @@ -pub const SFD_CLOEXEC: ::c_int = 0x080000; - -pub const NCCS: usize = 32; - -pub const O_TRUNC: ::c_int = 512; - -pub const O_CLOEXEC: ::c_int = 0x80000; - -pub const EBFONT: ::c_int = 59; -pub const ENOSTR: ::c_int = 60; -pub const ENODATA: ::c_int = 61; -pub const ETIME: ::c_int = 62; -pub const ENOSR: ::c_int = 63; -pub const ENONET: ::c_int = 64; -pub const ENOPKG: ::c_int = 65; -pub const EREMOTE: ::c_int = 66; -pub const ENOLINK: ::c_int = 67; -pub const EADV: ::c_int = 68; -pub const ESRMNT: ::c_int = 69; -pub const ECOMM: ::c_int = 70; -pub const EPROTO: ::c_int = 71; -pub const EDOTDOT: ::c_int = 73; - -pub const SA_NODEFER: ::c_int = 0x40000000; -pub const SA_RESETHAND: ::c_int = 0x80000000; -pub const SA_RESTART: ::c_int = 0x10000000; -pub const SA_NOCLDSTOP: ::c_int = 0x00000001; - -pub const EPOLL_CLOEXEC: ::c_int = 0x80000; - -pub const EFD_CLOEXEC: ::c_int = 0x80000; - -pub const BUFSIZ: ::c_uint = 4096; -pub const TMP_MAX: ::c_uint = 238328; -pub const FOPEN_MAX: ::c_uint = 16; -pub const POSIX_FADV_DONTNEED: ::c_int = 4; -pub const POSIX_FADV_NOREUSE: ::c_int = 5; -pub const POSIX_MADV_DONTNEED: ::c_int = 4; -pub const _SC_2_C_VERSION: ::c_int = 96; -pub const O_ACCMODE: ::c_int = 3; -pub const O_DIRECT: ::c_int = 0x8000; -pub const O_DIRECTORY: ::c_int = 0x10000; -pub const O_NOFOLLOW: ::c_int = 0x20000; -pub const ST_RELATIME: ::c_ulong = 4096; -pub const NI_MAXHOST: ::socklen_t = 1025; - -pub const RLIMIT_NOFILE: ::c_int = 5; -pub const RLIMIT_AS: ::c_int = 6; -pub const RLIMIT_RSS: ::c_int = 7; -pub const RLIMIT_NPROC: ::c_int = 8; -pub const RLIMIT_MEMLOCK: ::c_int = 9; -pub const RLIMIT_NLIMITS: ::c_int = 15; - -pub const O_APPEND: ::c_int = 8; -pub const O_CREAT: ::c_int = 256; -pub const O_EXCL: ::c_int = 1024; -pub const O_NOCTTY: ::c_int = 2048; -pub const O_NONBLOCK: ::c_int = 128; -pub const O_SYNC: ::c_int = 0x10; -pub const O_RSYNC: ::c_int = 0x10; -pub const O_DSYNC: ::c_int = 0x10; -pub const O_FSYNC: ::c_int = 0x10; -pub const O_ASYNC: ::c_int = 0x1000; -pub const O_NDELAY: ::c_int = 0x80; - -pub const SOCK_NONBLOCK: ::c_int = 128; - -pub const EDEADLK: ::c_int = 45; -pub const ENAMETOOLONG: ::c_int = 78; -pub const ENOLCK: ::c_int = 46; -pub const ENOSYS: ::c_int = 89; -pub const ENOTEMPTY: ::c_int = 93; -pub const ELOOP: ::c_int = 90; -pub const ENOMSG: ::c_int = 35; -pub const EIDRM: ::c_int = 36; -pub const ECHRNG: ::c_int = 37; -pub const EL2NSYNC: ::c_int = 38; -pub const EL3HLT: ::c_int = 39; -pub const EL3RST: ::c_int = 40; -pub const ELNRNG: ::c_int = 41; -pub const EUNATCH: ::c_int = 42; -pub const ENOCSI: ::c_int = 43; -pub const EL2HLT: ::c_int = 44; -pub const EBADE: ::c_int = 50; -pub const EBADR: ::c_int = 51; -pub const EXFULL: ::c_int = 52; -pub const ENOANO: ::c_int = 53; -pub const EBADRQC: ::c_int = 54; -pub const EBADSLT: ::c_int = 55; -pub const EDEADLOCK: ::c_int = 56; -pub const EMULTIHOP: ::c_int = 74; -pub const EOVERFLOW: ::c_int = 79; -pub const ENOTUNIQ: ::c_int = 80; -pub const EBADFD: ::c_int = 81; -pub const EBADMSG: ::c_int = 77; -pub const EREMCHG: ::c_int = 82; -pub const ELIBACC: ::c_int = 83; -pub const ELIBBAD: ::c_int = 84; -pub const ELIBSCN: ::c_int = 85; -pub const ELIBMAX: ::c_int = 86; -pub const ELIBEXEC: ::c_int = 87; -pub const EILSEQ: ::c_int = 88; -pub const ERESTART: ::c_int = 91; -pub const ESTRPIPE: ::c_int = 92; -pub const EUSERS: ::c_int = 94; -pub const ENOTSOCK: ::c_int = 95; -pub const EDESTADDRREQ: ::c_int = 96; -pub const EMSGSIZE: ::c_int = 97; -pub const EPROTOTYPE: ::c_int = 98; -pub const ENOPROTOOPT: ::c_int = 99; -pub const EPROTONOSUPPORT: ::c_int = 120; -pub const ESOCKTNOSUPPORT: ::c_int = 121; -pub const EOPNOTSUPP: ::c_int = 122; -pub const ENOTSUP: ::c_int = EOPNOTSUPP; -pub const EPFNOSUPPORT: ::c_int = 123; -pub const EAFNOSUPPORT: ::c_int = 124; -pub const EADDRINUSE: ::c_int = 125; -pub const EADDRNOTAVAIL: ::c_int = 126; -pub const ENETDOWN: ::c_int = 127; -pub const ENETUNREACH: ::c_int = 128; -pub const ENETRESET: ::c_int = 129; -pub const ECONNABORTED: ::c_int = 130; -pub const ECONNRESET: ::c_int = 131; -pub const ENOBUFS: ::c_int = 132; -pub const EISCONN: ::c_int = 133; -pub const ENOTCONN: ::c_int = 134; -pub const ESHUTDOWN: ::c_int = 143; -pub const ETOOMANYREFS: ::c_int = 144; -pub const ETIMEDOUT: ::c_int = 145; -pub const ECONNREFUSED: ::c_int = 146; -pub const EHOSTDOWN: ::c_int = 147; -pub const EHOSTUNREACH: ::c_int = 148; -pub const EALREADY: ::c_int = 149; -pub const EINPROGRESS: ::c_int = 150; -pub const ESTALE: ::c_int = 151; -pub const EUCLEAN: ::c_int = 135; -pub const ENOTNAM: ::c_int = 137; -pub const ENAVAIL: ::c_int = 138; -pub const EISNAM: ::c_int = 139; -pub const EREMOTEIO: ::c_int = 140; -pub const EDQUOT: ::c_int = 1133; -pub const ENOMEDIUM: ::c_int = 159; -pub const EMEDIUMTYPE: ::c_int = 160; -pub const ECANCELED: ::c_int = 158; -pub const ENOKEY: ::c_int = 161; -pub const EKEYEXPIRED: ::c_int = 162; -pub const EKEYREVOKED: ::c_int = 163; -pub const EKEYREJECTED: ::c_int = 164; -pub const EOWNERDEAD: ::c_int = 165; -pub const ENOTRECOVERABLE: ::c_int = 166; -pub const ERFKILL: ::c_int = 167; - -pub const MAP_NORESERVE: ::c_int = 0x400; -pub const MAP_ANON: ::c_int = 0x800; -pub const MAP_ANONYMOUS: ::c_int = 0x800; -pub const MAP_GROWSDOWN: ::c_int = 0x1000; -pub const MAP_DENYWRITE: ::c_int = 0x2000; -pub const MAP_EXECUTABLE: ::c_int = 0x4000; -pub const MAP_LOCKED: ::c_int = 0x8000; -pub const MAP_POPULATE: ::c_int = 0x10000; -pub const MAP_NONBLOCK: ::c_int = 0x20000; -pub const MAP_STACK: ::c_int = 0x40000; - -pub const SOCK_STREAM: ::c_int = 2; -pub const SOCK_DGRAM: ::c_int = 1; -pub const SOCK_SEQPACKET: ::c_int = 5; - -pub const SOL_SOCKET: ::c_int = 0xffff; - -pub const SO_REUSEADDR: ::c_int = 0x0004; -pub const SO_KEEPALIVE: ::c_int = 0x0008; -pub const SO_DONTROUTE: ::c_int = 0x0010; -pub const SO_BROADCAST: ::c_int = 0x0020; -pub const SO_LINGER: ::c_int = 0x0080; -pub const SO_OOBINLINE: ::c_int = 0x0100; -pub const SO_REUSEPORT: ::c_int = 0x0200; -pub const SO_TYPE: ::c_int = 0x1008; -pub const SO_STYLE: ::c_int = SO_TYPE; -pub const SO_ERROR: ::c_int = 0x1007; -pub const SO_SNDBUF: ::c_int = 0x1001; -pub const SO_RCVBUF: ::c_int = 0x1002; -pub const SO_SNDLOWAT: ::c_int = 0x1003; -pub const SO_RCVLOWAT: ::c_int = 0x1004; -pub const SO_SNDTIMEO: ::c_int = 0x1005; -pub const SO_RCVTIMEO: ::c_int = 0x1006; -pub const SO_ACCEPTCONN: ::c_int = 0x1009; -pub const SO_PROTOCOL: ::c_int = 0x1028; -pub const SO_DOMAIN: ::c_int = 0x1029; -pub const SO_NO_CHECK: ::c_int = 11; -pub const SO_PRIORITY: ::c_int = 12; -pub const SO_BSDCOMPAT: ::c_int = 14; -pub const SO_PASSCRED: ::c_int = 17; -pub const SO_PEERCRED: ::c_int = 18; -pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22; -pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23; -pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24; -pub const SO_BINDTODEVICE: ::c_int = 25; -pub const SO_ATTACH_FILTER: ::c_int = 26; -pub const SO_DETACH_FILTER: ::c_int = 27; -pub const SO_GET_FILTER: ::c_int = SO_ATTACH_FILTER; -pub const SO_PEERNAME: ::c_int = 28; -pub const SO_TIMESTAMP: ::c_int = 29; -pub const SCM_TIMESTAMP: ::c_int = SO_TIMESTAMP; -pub const SO_PEERSEC: ::c_int = 30; -pub const SO_SNDBUFFORCE: ::c_int = 31; -pub const SO_RCVBUFFORCE: ::c_int = 33; -pub const SO_PASSSEC: ::c_int = 34; -pub const SO_TIMESTAMPNS: ::c_int = 35; -pub const SCM_TIMESTAMPNS: ::c_int = SO_TIMESTAMPNS; -pub const SO_MARK: ::c_int = 36; -pub const SO_TIMESTAMPING: ::c_int = 37; -pub const SCM_TIMESTAMPING: ::c_int = SO_TIMESTAMPING; -pub const SO_RXQ_OVFL: ::c_int = 40; -pub const SO_WIFI_STATUS: ::c_int = 41; -pub const SCM_WIFI_STATUS: ::c_int = SO_WIFI_STATUS; -pub const SO_PEEK_OFF: ::c_int = 42; -pub const SO_NOFCS: ::c_int = 43; -pub const SO_LOCK_FILTER: ::c_int = 44; -pub const SO_SELECT_ERR_QUEUE: ::c_int = 45; -pub const SO_BUSY_POLL: ::c_int = 46; -pub const SO_MAX_PACING_RATE: ::c_int = 47; -pub const SO_BPF_EXTENSIONS: ::c_int = 48; - -pub const FIOCLEX: ::c_ulong = 0x6601; -pub const FIONBIO: ::c_ulong = 0x667e; - -pub const SA_ONSTACK: ::c_int = 0x08000000; -pub const SA_SIGINFO: ::c_int = 0x00000008; -pub const SA_NOCLDWAIT: ::c_int = 0x00010000; - -pub const SIGCHLD: ::c_int = 18; -pub const SIGBUS: ::c_int = 10; -pub const SIGTTIN: ::c_int = 26; -pub const SIGTTOU: ::c_int = 27; -pub const SIGXCPU: ::c_int = 30; -pub const SIGXFSZ: ::c_int = 31; -pub const SIGVTALRM: ::c_int = 28; -pub const SIGPROF: ::c_int = 29; -pub const SIGWINCH: ::c_int = 20; -pub const SIGUSR1: ::c_int = 16; -pub const SIGUSR2: ::c_int = 17; -pub const SIGCONT: ::c_int = 25; -pub const SIGSTOP: ::c_int = 23; -pub const SIGTSTP: ::c_int = 24; -pub const SIGURG: ::c_int = 21; -pub const SIGIO: ::c_int = 22; -pub const SIGSYS: ::c_int = 12; -pub const SIGPOLL: ::c_int = 22; -pub const SIGPWR: ::c_int = 19; -pub const SIG_SETMASK: ::c_int = 3; -pub const SIG_BLOCK: ::c_int = 0x1; -pub const SIG_UNBLOCK: ::c_int = 0x2; - -pub const POLLRDNORM: ::c_short = 0x040; -pub const POLLWRNORM: ::c_short = 0x004; -pub const POLLRDBAND: ::c_short = 0x080; -pub const POLLWRBAND: ::c_short = 0x100; - -pub const PTHREAD_STACK_MIN: ::size_t = 16384; - -pub const ADFS_SUPER_MAGIC: ::c_long = 0x0000adf5; -pub const AFFS_SUPER_MAGIC: ::c_long = 0x0000adff; -pub const CODA_SUPER_MAGIC: ::c_long = 0x73757245; -pub const CRAMFS_MAGIC: ::c_long = 0x28cd3d45; -pub const EFS_SUPER_MAGIC: ::c_long = 0x00414a53; -pub const EXT2_SUPER_MAGIC: ::c_long = 0x0000ef53; -pub const EXT3_SUPER_MAGIC: ::c_long = 0x0000ef53; -pub const EXT4_SUPER_MAGIC: ::c_long = 0x0000ef53; -pub const HPFS_SUPER_MAGIC: ::c_long = 0xf995e849; -pub const HUGETLBFS_MAGIC: ::c_long = 0x958458f6; -pub const ISOFS_SUPER_MAGIC: ::c_long = 0x00009660; -pub const JFFS2_SUPER_MAGIC: ::c_long = 0x000072b6; -pub const MINIX_SUPER_MAGIC: ::c_long = 0x0000137f; -pub const MINIX_SUPER_MAGIC2: ::c_long = 0x0000138f; -pub const MINIX2_SUPER_MAGIC: ::c_long = 0x00002468; -pub const MINIX2_SUPER_MAGIC2: ::c_long = 0x00002478; -pub const MSDOS_SUPER_MAGIC: ::c_long = 0x00004d44; -pub const NCP_SUPER_MAGIC: ::c_long = 0x0000564c; -pub const NFS_SUPER_MAGIC: ::c_long = 0x00006969; -pub const OPENPROM_SUPER_MAGIC: ::c_long = 0x00009fa1; -pub const PROC_SUPER_MAGIC: ::c_long = 0x00009fa0; -pub const QNX4_SUPER_MAGIC: ::c_long = 0x0000002f; -pub const REISERFS_SUPER_MAGIC: ::c_long = 0x52654973; -pub const SMB_SUPER_MAGIC: ::c_long = 0x0000517b; -pub const TMPFS_MAGIC: ::c_long = 0x01021994; -pub const USBDEVICE_SUPER_MAGIC: ::c_long = 0x00009fa2; - -pub const VEOF: usize = 16; -pub const VEOL: usize = 17; -pub const VEOL2: usize = 6; -pub const VMIN: usize = 4; -pub const IEXTEN: ::tcflag_t = 0x00000100; -pub const TOSTOP: ::tcflag_t = 0x00008000; -pub const FLUSHO: ::tcflag_t = 0x00002000; -pub const IUTF8: ::tcflag_t = 0x00004000; -pub const TCSANOW: ::c_int = 0x540e; -pub const TCSADRAIN: ::c_int = 0x540f; -pub const TCSAFLUSH: ::c_int = 0x5410; - -pub const CPU_SETSIZE: ::c_int = 0x400; - -pub const PTRACE_TRACEME: ::c_uint = 0; -pub const PTRACE_PEEKTEXT: ::c_uint = 1; -pub const PTRACE_PEEKDATA: ::c_uint = 2; -pub const PTRACE_PEEKUSER: ::c_uint = 3; -pub const PTRACE_POKETEXT: ::c_uint = 4; -pub const PTRACE_POKEDATA: ::c_uint = 5; -pub const PTRACE_POKEUSER: ::c_uint = 6; -pub const PTRACE_CONT: ::c_uint = 7; -pub const PTRACE_KILL: ::c_uint = 8; -pub const PTRACE_SINGLESTEP: ::c_uint = 9; -pub const PTRACE_ATTACH: ::c_uint = 16; -pub const PTRACE_DETACH: ::c_uint = 17; -pub const PTRACE_SYSCALL: ::c_uint = 24; -pub const PTRACE_SETOPTIONS: ::c_uint = 0x4200; -pub const PTRACE_GETEVENTMSG: ::c_uint = 0x4201; -pub const PTRACE_GETSIGINFO: ::c_uint = 0x4202; -pub const PTRACE_SETSIGINFO: ::c_uint = 0x4203; -pub const PTRACE_GETFPREGS: ::c_uint = 14; -pub const PTRACE_SETFPREGS: ::c_uint = 15; -pub const PTRACE_GETFPXREGS: ::c_uint = 18; -pub const PTRACE_SETFPXREGS: ::c_uint = 19; -pub const PTRACE_GETREGS: ::c_uint = 12; -pub const PTRACE_SETREGS: ::c_uint = 13; - -pub const EFD_NONBLOCK: ::c_int = 0x80; - -pub const F_GETLK: ::c_int = 14; -pub const F_GETOWN: ::c_int = 23; -pub const F_SETOWN: ::c_int = 24; -pub const F_SETLK: ::c_int = 6; -pub const F_SETLKW: ::c_int = 7; - -pub const SFD_NONBLOCK: ::c_int = 0x80; - -pub const TCGETS: ::c_ulong = 0x540d; -pub const TCSETS: ::c_ulong = 0x540e; -pub const TCSETSW: ::c_ulong = 0x540f; -pub const TCSETSF: ::c_ulong = 0x5410; -pub const TCGETA: ::c_ulong = 0x5401; -pub const TCSETA: ::c_ulong = 0x5402; -pub const TCSETAW: ::c_ulong = 0x5403; -pub const TCSETAF: ::c_ulong = 0x5404; -pub const TCSBRK: ::c_ulong = 0x5405; -pub const TCXONC: ::c_ulong = 0x5406; -pub const TCFLSH: ::c_ulong = 0x5407; -pub const TIOCGSOFTCAR: ::c_ulong = 0x5481; -pub const TIOCSSOFTCAR: ::c_ulong = 0x5482; -pub const TIOCINQ: ::c_ulong = 0x467f; -pub const TIOCLINUX: ::c_ulong = 0x5483; -pub const TIOCGSERIAL: ::c_ulong = 0x5484; -pub const TIOCEXCL: ::c_ulong = 0x740d; -pub const TIOCNXCL: ::c_ulong = 0x740e; -pub const TIOCSCTTY: ::c_ulong = 0x5480; -pub const TIOCGPGRP: ::c_ulong = 0x40047477; -pub const TIOCSPGRP: ::c_ulong = 0x80047476; -pub const TIOCOUTQ: ::c_ulong = 0x7472; -pub const TIOCSTI: ::c_ulong = 0x5472; -pub const TIOCGWINSZ: ::c_ulong = 0x40087468; -pub const TIOCSWINSZ: ::c_ulong = 0x80087467; -pub const TIOCMGET: ::c_ulong = 0x741d; -pub const TIOCMBIS: ::c_ulong = 0x741b; -pub const TIOCMBIC: ::c_ulong = 0x741c; -pub const TIOCMSET: ::c_ulong = 0x741a; -pub const FIONREAD: ::c_ulong = 0x467f; -pub const TIOCCONS: ::c_ulong = 0x80047478; - -pub const RTLD_DEEPBIND: ::c_int = 0x10; -pub const RTLD_GLOBAL: ::c_int = 0x4; -pub const RTLD_NOLOAD: ::c_int = 0x8; - -pub const LINUX_REBOOT_MAGIC1: ::c_int = 0xfee1dead; -pub const LINUX_REBOOT_MAGIC2: ::c_int = 672274793; -pub const LINUX_REBOOT_MAGIC2A: ::c_int = 85072278; -pub const LINUX_REBOOT_MAGIC2B: ::c_int = 369367448; -pub const LINUX_REBOOT_MAGIC2C: ::c_int = 537993216; - -pub const LINUX_REBOOT_CMD_RESTART: ::c_int = 0x01234567; -pub const LINUX_REBOOT_CMD_HALT: ::c_int = 0xCDEF0123; -pub const LINUX_REBOOT_CMD_CAD_ON: ::c_int = 0x89ABCDEF; -pub const LINUX_REBOOT_CMD_CAD_OFF: ::c_int = 0x00000000; -pub const LINUX_REBOOT_CMD_POWER_OFF: ::c_int = 0x4321FEDC; -pub const LINUX_REBOOT_CMD_RESTART2: ::c_int = 0xA1B2C3D4; -pub const LINUX_REBOOT_CMD_SW_SUSPEND: ::c_int = 0xD000FCE2; -pub const LINUX_REBOOT_CMD_KEXEC: ::c_int = 0x45584543; - -pub const MCL_CURRENT: ::c_int = 0x0001; -pub const MCL_FUTURE: ::c_int = 0x0002; - -pub const SIGSTKSZ: ::size_t = 8192; -pub const CBAUD: ::tcflag_t = 0o0010017; -pub const TAB1: ::c_int = 0x00000800; -pub const TAB2: ::c_int = 0x00001000; -pub const TAB3: ::c_int = 0x00001800; -pub const CR1: ::c_int = 0x00000200; -pub const CR2: ::c_int = 0x00000400; -pub const CR3: ::c_int = 0x00000600; -pub const FF1: ::c_int = 0x00008000; -pub const BS1: ::c_int = 0x00002000; -pub const VT1: ::c_int = 0x00004000; -pub const VWERASE: usize = 14; -pub const VREPRINT: usize = 12; -pub const VSUSP: usize = 10; -pub const VSTART: usize = 8; -pub const VSTOP: usize = 9; -pub const VDISCARD: usize = 13; -pub const VTIME: usize = 5; -pub const IXON: ::tcflag_t = 0x00000400; -pub const IXOFF: ::tcflag_t = 0x00001000; -pub const ONLCR: ::tcflag_t = 0x4; -pub const CSIZE: ::tcflag_t = 0x00000030; -pub const CS6: ::tcflag_t = 0x00000010; -pub const CS7: ::tcflag_t = 0x00000020; -pub const CS8: ::tcflag_t = 0x00000030; -pub const CSTOPB: ::tcflag_t = 0x00000040; -pub const CREAD: ::tcflag_t = 0x00000080; -pub const PARENB: ::tcflag_t = 0x00000100; -pub const PARODD: ::tcflag_t = 0x00000200; -pub const HUPCL: ::tcflag_t = 0x00000400; -pub const CLOCAL: ::tcflag_t = 0x00000800; -pub const ECHOKE: ::tcflag_t = 0x00000800; -pub const ECHOE: ::tcflag_t = 0x00000010; -pub const ECHOK: ::tcflag_t = 0x00000020; -pub const ECHONL: ::tcflag_t = 0x00000040; -pub const ECHOPRT: ::tcflag_t = 0x00000400; -pub const ECHOCTL: ::tcflag_t = 0x00000200; -pub const ISIG: ::tcflag_t = 0x00000001; -pub const ICANON: ::tcflag_t = 0x00000002; -pub const PENDIN: ::tcflag_t = 0x00004000; -pub const NOFLSH: ::tcflag_t = 0x00000080; - -pub const B0: ::speed_t = 0o000000; -pub const B50: ::speed_t = 0o000001; -pub const B75: ::speed_t = 0o000002; -pub const B110: ::speed_t = 0o000003; -pub const B134: ::speed_t = 0o000004; -pub const B150: ::speed_t = 0o000005; -pub const B200: ::speed_t = 0o000006; -pub const B300: ::speed_t = 0o000007; -pub const B600: ::speed_t = 0o000010; -pub const B1200: ::speed_t = 0o000011; -pub const B1800: ::speed_t = 0o000012; -pub const B2400: ::speed_t = 0o000013; -pub const B4800: ::speed_t = 0o000014; -pub const B9600: ::speed_t = 0o000015; -pub const B19200: ::speed_t = 0o000016; -pub const B38400: ::speed_t = 0o000017; -pub const EXTA: ::speed_t = B19200; -pub const EXTB: ::speed_t = B38400; -pub const B57600: ::speed_t = 0o010001; -pub const B115200: ::speed_t = 0o010002; -pub const B230400: ::speed_t = 0o010003; -pub const B460800: ::speed_t = 0o010004; -pub const B500000: ::speed_t = 0o010005; -pub const B576000: ::speed_t = 0o010006; -pub const B921600: ::speed_t = 0o010007; -pub const B1000000: ::speed_t = 0o010010; -pub const B1152000: ::speed_t = 0o010011; -pub const B1500000: ::speed_t = 0o010012; -pub const B2000000: ::speed_t = 0o010013; -pub const B2500000: ::speed_t = 0o010014; -pub const B3000000: ::speed_t = 0o010015; -pub const B3500000: ::speed_t = 0o010016; -pub const B4000000: ::speed_t = 0o010017; - -cfg_if! { - if #[cfg(target_arch = "mips")] { - mod mips32; - pub use self::mips32::*; - } else if #[cfg(target_arch = "mips64")] { - mod mips64; - pub use self::mips64::*; - } else { - // Unknown target_arch - } -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/uclibc/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/uclibc/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/uclibc/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/uclibc/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1903 +0,0 @@ -use dox::{mem, Option}; - -pub type sa_family_t = u16; -pub type pthread_key_t = ::c_uint; -pub type speed_t = ::c_uint; -pub type tcflag_t = ::c_uint; -pub type loff_t = ::c_longlong; -pub type clockid_t = ::c_int; -pub type key_t = ::c_int; -pub type id_t = ::c_uint; -pub type useconds_t = u32; -pub type dev_t = u64; -pub type socklen_t = u32; -pub type pthread_t = ::c_ulong; -pub type mode_t = u32; -pub type ino64_t = u64; -pub type off64_t = i64; -pub type blkcnt64_t = i64; -pub type rlim64_t = u64; -pub type shmatt_t = ::c_ulong; -pub type mqd_t = ::c_int; -pub type msgqnum_t = ::c_ulong; -pub type msglen_t = ::c_ulong; -pub type nfds_t = ::c_ulong; -pub type nl_item = ::c_int; -pub type idtype_t = ::c_uint; - -pub enum fpos64_t {} // TODO: fill this out with a struct - -pub enum timezone {} - -s! { - pub struct sockaddr { - pub sa_family: sa_family_t, - pub sa_data: [::c_char; 14], - } - - pub struct sockaddr_in { - pub sin_family: sa_family_t, - pub sin_port: ::in_port_t, - pub sin_addr: ::in_addr, - pub sin_zero: [u8; 8], - } - - pub struct sockaddr_in6 { - pub sin6_family: sa_family_t, - pub sin6_port: ::in_port_t, - pub sin6_flowinfo: u32, - pub sin6_addr: ::in6_addr, - pub sin6_scope_id: u32, - } - - pub struct sockaddr_un { - pub sun_family: sa_family_t, - pub sun_path: [::c_char; 108] - } - - pub struct sockaddr_storage { - pub ss_family: sa_family_t, - __ss_align: ::size_t, - #[cfg(target_pointer_width = "32")] - __ss_pad2: [u8; 128 - 2 * 4], - #[cfg(target_pointer_width = "64")] - __ss_pad2: [u8; 128 - 2 * 8], - } - - pub struct addrinfo { - pub ai_flags: ::c_int, - pub ai_family: ::c_int, - pub ai_socktype: ::c_int, - pub ai_protocol: ::c_int, - pub ai_addrlen: socklen_t, - - pub ai_addr: *mut ::sockaddr, - - pub ai_canonname: *mut c_char, - - pub ai_next: *mut addrinfo, - } - - pub struct sockaddr_nl { - pub nl_family: ::sa_family_t, - nl_pad: ::c_ushort, - pub nl_pid: u32, - pub nl_groups: u32 - } - - pub struct sockaddr_ll { - pub sll_family: ::c_ushort, - pub sll_protocol: ::c_ushort, - pub sll_ifindex: ::c_int, - pub sll_hatype: ::c_ushort, - pub sll_pkttype: ::c_uchar, - pub sll_halen: ::c_uchar, - pub sll_addr: [::c_uchar; 8] - } - - pub struct fd_set { - fds_bits: [::c_ulong; FD_SETSIZE / ULONG_SIZE], - } - - pub struct tm { - pub tm_sec: ::c_int, - pub tm_min: ::c_int, - pub tm_hour: ::c_int, - pub tm_mday: ::c_int, - pub tm_mon: ::c_int, - pub tm_year: ::c_int, - pub tm_wday: ::c_int, - pub tm_yday: ::c_int, - pub tm_isdst: ::c_int, - pub tm_gmtoff: ::c_long, - pub tm_zone: *const ::c_char, - } - - pub struct sched_param { - pub sched_priority: ::c_int, - } - - pub struct Dl_info { - pub dli_fname: *const ::c_char, - pub dli_fbase: *mut ::c_void, - pub dli_sname: *const ::c_char, - pub dli_saddr: *mut ::c_void, - } - - #[cfg_attr(any(all(target_arch = "x86", - target_arch = "x86_64")), - repr(packed))] - pub struct epoll_event { - pub events: ::uint32_t, - pub u64: ::uint64_t, - } - - pub struct utsname { - pub sysname: [::c_char; 65], - pub nodename: [::c_char; 65], - pub release: [::c_char; 65], - pub version: [::c_char; 65], - pub machine: [::c_char; 65], - pub domainname: [::c_char; 65] - } - - pub struct lconv { - pub decimal_point: *mut ::c_char, - pub thousands_sep: *mut ::c_char, - pub grouping: *mut ::c_char, - pub int_curr_symbol: *mut ::c_char, - pub currency_symbol: *mut ::c_char, - pub mon_decimal_point: *mut ::c_char, - pub mon_thousands_sep: *mut ::c_char, - pub mon_grouping: *mut ::c_char, - pub positive_sign: *mut ::c_char, - pub negative_sign: *mut ::c_char, - pub int_frac_digits: ::c_char, - pub frac_digits: ::c_char, - pub p_cs_precedes: ::c_char, - pub p_sep_by_space: ::c_char, - pub n_cs_precedes: ::c_char, - pub n_sep_by_space: ::c_char, - pub p_sign_posn: ::c_char, - pub n_sign_posn: ::c_char, - pub int_p_cs_precedes: ::c_char, - pub int_p_sep_by_space: ::c_char, - pub int_n_cs_precedes: ::c_char, - pub int_n_sep_by_space: ::c_char, - pub int_p_sign_posn: ::c_char, - pub int_n_sign_posn: ::c_char, - } - - pub struct sigevent { - pub sigev_value: ::sigval, - pub sigev_signo: ::c_int, - pub sigev_notify: ::c_int, - // Actually a union. We only expose sigev_notify_thread_id because it's - // the most useful member - pub sigev_notify_thread_id: ::c_int, - #[cfg(target_pointer_width = "64")] - __unused1: [::c_int; 11], - #[cfg(target_pointer_width = "32")] - __unused1: [::c_int; 12] - } - - pub struct dirent { - pub d_ino: ::ino_t, - pub d_off: ::off_t, - pub d_reclen: ::c_ushort, - pub d_type: ::c_uchar, - pub d_name: [::c_char; 256], - } - - pub struct dirent64 { - pub d_ino: ::ino64_t, - pub d_off: ::off64_t, - pub d_reclen: ::c_ushort, - pub d_type: ::c_uchar, - pub d_name: [::c_char; 256], - } - - pub struct rlimit64 { - pub rlim_cur: rlim64_t, - pub rlim_max: rlim64_t, - } - - pub struct glob_t { - pub gl_pathc: ::size_t, - pub gl_pathv: *mut *mut c_char, - pub gl_offs: ::size_t, - pub gl_flags: ::c_int, - - __unused1: *mut ::c_void, - __unused2: *mut ::c_void, - __unused3: *mut ::c_void, - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - } - - pub struct ifaddrs { - pub ifa_next: *mut ifaddrs, - pub ifa_name: *mut c_char, - pub ifa_flags: ::c_uint, - pub ifa_addr: *mut ::sockaddr, - pub ifa_netmask: *mut ::sockaddr, - pub ifa_ifu: *mut ::sockaddr, // FIXME This should be a union - pub ifa_data: *mut ::c_void - } - - pub struct pthread_mutex_t { - #[cfg(any(target_arch = "mips", target_arch = "arm", - target_arch = "powerpc"))] - __align: [::c_long; 0], - #[cfg(not(any(target_arch = "mips", target_arch = "arm", - target_arch = "powerpc")))] - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_MUTEX_T], - } - - pub struct pthread_rwlock_t { - #[cfg(any(target_arch = "mips", target_arch = "arm", - target_arch = "powerpc"))] - __align: [::c_long; 0], - #[cfg(not(any(target_arch = "mips", target_arch = "arm", - target_arch = "powerpc")))] - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_RWLOCK_T], - } - - pub struct pthread_mutexattr_t { - #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", - target_arch = "mips64", target_arch = "s390x", - target_arch = "sparc64"))] - __align: [::c_int; 0], - #[cfg(not(any(target_arch = "x86_64", target_arch = "powerpc64", - target_arch = "mips64", target_arch = "s390x", - target_arch = "sparc64")))] - __align: [::c_long; 0], - size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T], - } - - pub struct pthread_rwlockattr_t { - __lockkind: ::c_int, - __pshared: ::c_int, - } - - pub struct pthread_cond_t { - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_COND_T], - } - - pub struct pthread_condattr_t { - __align: [::c_int; 0], - size: [u8; __SIZEOF_PTHREAD_CONDATTR_T], - } - - pub struct passwd { - pub pw_name: *mut ::c_char, - pub pw_passwd: *mut ::c_char, - pub pw_uid: ::uid_t, - pub pw_gid: ::gid_t, - pub pw_gecos: *mut ::c_char, - pub pw_dir: *mut ::c_char, - pub pw_shell: *mut ::c_char, - } - - pub struct spwd { - pub sp_namp: *mut ::c_char, - pub sp_pwdp: *mut ::c_char, - pub sp_lstchg: ::c_long, - pub sp_min: ::c_long, - pub sp_max: ::c_long, - pub sp_warn: ::c_long, - pub sp_inact: ::c_long, - pub sp_expire: ::c_long, - pub sp_flag: ::c_ulong, - } - - pub struct statvfs { - pub f_bsize: ::c_ulong, - pub f_frsize: ::c_ulong, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_favail: ::fsfilcnt_t, - #[cfg(target_endian = "little")] - pub f_fsid: ::c_ulong, - #[cfg(target_pointer_width = "32")] - __f_unused: ::c_int, - #[cfg(target_endian = "big")] - pub f_fsid: ::c_ulong, - pub f_flag: ::c_ulong, - pub f_namemax: ::c_ulong, - __f_spare: [::c_int; 6], - } - - pub struct dqblk { - pub dqb_bhardlimit: ::uint32_t, - pub dqb_bsoftlimit: ::uint32_t, - pub dqb_curblocks: ::uint32_t, - pub dqb_ihardlimit: ::uint32_t, - pub dqb_isoftlimit: ::uint32_t, - pub dqb_curinodes: ::uint32_t, - pub dqb_btime: ::time_t, - pub dqb_itime: ::time_t, - } - - pub struct signalfd_siginfo { - pub ssi_signo: ::uint32_t, - pub ssi_errno: ::int32_t, - pub ssi_code: ::int32_t, - pub ssi_pid: ::uint32_t, - pub ssi_uid: ::uint32_t, - pub ssi_fd: ::int32_t, - pub ssi_tid: ::uint32_t, - pub ssi_band: ::uint32_t, - pub ssi_overrun: ::uint32_t, - pub ssi_trapno: ::uint32_t, - pub ssi_status: ::int32_t, - pub ssi_int: ::int32_t, - pub ssi_ptr: ::uint64_t, - pub ssi_utime: ::uint64_t, - pub ssi_stime: ::uint64_t, - pub ssi_addr: ::uint64_t, - _pad: [::uint8_t; 48], - } - - pub struct fsid_t { - __val: [::c_int; 2], - } - - pub struct mq_attr { - pub mq_flags: ::c_long, - pub mq_maxmsg: ::c_long, - pub mq_msgsize: ::c_long, - pub mq_curmsgs: ::c_long, - pad: [::c_long; 4] - } - - pub struct cpu_set_t { - #[cfg(target_pointer_width = "32")] - bits: [u32; 32], - #[cfg(target_pointer_width = "64")] - bits: [u64; 16], - } - - pub struct if_nameindex { - pub if_index: ::c_uint, - pub if_name: *mut ::c_char, - } - - // System V IPC - pub struct msginfo { - pub msgpool: ::c_int, - pub msgmap: ::c_int, - pub msgmax: ::c_int, - pub msgmnb: ::c_int, - pub msgmni: ::c_int, - pub msgssz: ::c_int, - pub msgtql: ::c_int, - pub msgseg: ::c_ushort, - } -} - -// intentionally not public, only used for fd_set -cfg_if! { - if #[cfg(target_pointer_width = "32")] { - const ULONG_SIZE: usize = 32; - } else if #[cfg(target_pointer_width = "64")] { - const ULONG_SIZE: usize = 64; - } else { - // Unknown target_pointer_width - } -} - -pub const EXIT_FAILURE: ::c_int = 1; -pub const EXIT_SUCCESS: ::c_int = 0; -pub const RAND_MAX: ::c_int = 2147483647; -pub const EOF: ::c_int = -1; -pub const SEEK_SET: ::c_int = 0; -pub const SEEK_CUR: ::c_int = 1; -pub const SEEK_END: ::c_int = 2; -pub const _IOFBF: ::c_int = 0; -pub const _IONBF: ::c_int = 2; -pub const _IOLBF: ::c_int = 1; - -pub const F_DUPFD: ::c_int = 0; -pub const F_GETFD: ::c_int = 1; -pub const F_SETFD: ::c_int = 2; -pub const F_GETFL: ::c_int = 3; -pub const F_SETFL: ::c_int = 4; - -// Linux-specific fcntls -pub const F_SETLEASE: ::c_int = 1024; -pub const F_GETLEASE: ::c_int = 1025; -pub const F_NOTIFY: ::c_int = 1026; -pub const F_DUPFD_CLOEXEC: ::c_int = 1030; - -// TODO(#235): Include file sealing fcntls once we have a way to verify them. - -pub const SIGTRAP: ::c_int = 5; - -pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; -pub const PTHREAD_CREATE_DETACHED: ::c_int = 1; - -pub const CLOCK_REALTIME: ::clockid_t = 0; -pub const CLOCK_MONOTONIC: ::clockid_t = 1; -pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 2; -pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 3; -// TODO(#247) Someday our Travis shall have glibc 2.21 (released in Sep -// 2014.) See also musl/mod.rs -// pub const CLOCK_SGI_CYCLE: ::clockid_t = 10; -// pub const CLOCK_TAI: ::clockid_t = 11; -pub const TIMER_ABSTIME: ::c_int = 1; - -pub const RLIMIT_CPU: ::c_int = 0; -pub const RLIMIT_FSIZE: ::c_int = 1; -pub const RLIMIT_DATA: ::c_int = 2; -pub const RLIMIT_STACK: ::c_int = 3; -pub const RLIMIT_CORE: ::c_int = 4; -pub const RLIMIT_LOCKS: ::c_int = 10; -pub const RLIMIT_SIGPENDING: ::c_int = 11; -pub const RLIMIT_MSGQUEUE: ::c_int = 12; -pub const RLIMIT_NICE: ::c_int = 13; -pub const RLIMIT_RTPRIO: ::c_int = 14; - -pub const RUSAGE_SELF: ::c_int = 0; - -pub const O_RDONLY: ::c_int = 0; -pub const O_WRONLY: ::c_int = 1; -pub const O_RDWR: ::c_int = 2; - -pub const SOCK_CLOEXEC: ::c_int = O_CLOEXEC; - -pub const S_IFIFO: ::mode_t = 4096; -pub const S_IFCHR: ::mode_t = 8192; -pub const S_IFBLK: ::mode_t = 24576; -pub const S_IFDIR: ::mode_t = 16384; -pub const S_IFREG: ::mode_t = 32768; -pub const S_IFLNK: ::mode_t = 40960; -pub const S_IFSOCK: ::mode_t = 49152; -pub const S_IFMT: ::mode_t = 61440; -pub const S_IRWXU: ::mode_t = 448; -pub const S_IXUSR: ::mode_t = 64; -pub const S_IWUSR: ::mode_t = 128; -pub const S_IRUSR: ::mode_t = 256; -pub const S_IRWXG: ::mode_t = 56; -pub const S_IXGRP: ::mode_t = 8; -pub const S_IWGRP: ::mode_t = 16; -pub const S_IRGRP: ::mode_t = 32; -pub const S_IRWXO: ::mode_t = 7; -pub const S_IXOTH: ::mode_t = 1; -pub const S_IWOTH: ::mode_t = 2; -pub const S_IROTH: ::mode_t = 4; -pub const F_OK: ::c_int = 0; -pub const R_OK: ::c_int = 4; -pub const W_OK: ::c_int = 2; -pub const X_OK: ::c_int = 1; -pub const STDIN_FILENO: ::c_int = 0; -pub const STDOUT_FILENO: ::c_int = 1; -pub const STDERR_FILENO: ::c_int = 2; -pub const SIGHUP: ::c_int = 1; -pub const SIGINT: ::c_int = 2; -pub const SIGQUIT: ::c_int = 3; -pub const SIGILL: ::c_int = 4; -pub const SIGABRT: ::c_int = 6; -pub const SIGFPE: ::c_int = 8; -pub const SIGKILL: ::c_int = 9; -pub const SIGSEGV: ::c_int = 11; -pub const SIGPIPE: ::c_int = 13; -pub const SIGALRM: ::c_int = 14; -pub const SIGTERM: ::c_int = 15; - -pub const PROT_NONE: ::c_int = 0; -pub const PROT_READ: ::c_int = 1; -pub const PROT_WRITE: ::c_int = 2; -pub const PROT_EXEC: ::c_int = 4; - -pub const LC_CTYPE: ::c_int = 0; -pub const LC_NUMERIC: ::c_int = 1; -pub const LC_MONETARY: ::c_int = 2; -pub const LC_TIME: ::c_int = 3; -pub const LC_COLLATE: ::c_int = 4; -pub const LC_MESSAGES: ::c_int = 5; -pub const LC_ALL: ::c_int = 6; -pub const LC_CTYPE_MASK: ::c_int = (1 << LC_CTYPE); -pub const LC_NUMERIC_MASK: ::c_int = (1 << LC_NUMERIC); -pub const LC_TIME_MASK: ::c_int = (1 << LC_TIME); -pub const LC_COLLATE_MASK: ::c_int = (1 << LC_COLLATE); -pub const LC_MONETARY_MASK: ::c_int = (1 << LC_MONETARY); -pub const LC_MESSAGES_MASK: ::c_int = (1 << LC_MESSAGES); -// LC_ALL_MASK defined per platform - -pub const MAP_FILE: ::c_int = 0x0000; -pub const MAP_SHARED: ::c_int = 0x0001; -pub const MAP_PRIVATE: ::c_int = 0x0002; -pub const MAP_FIXED: ::c_int = 0x0010; - -pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; - -// MS_ flags for msync(2) -pub const MS_ASYNC: ::c_int = 0x0001; -pub const MS_INVALIDATE: ::c_int = 0x0002; -pub const MS_SYNC: ::c_int = 0x0004; - -// MS_ flags for mount(2) -pub const MS_RDONLY: ::c_ulong = 0x01; -pub const MS_NOSUID: ::c_ulong = 0x02; -pub const MS_NODEV: ::c_ulong = 0x04; -pub const MS_NOEXEC: ::c_ulong = 0x08; -pub const MS_SYNCHRONOUS: ::c_ulong = 0x10; -pub const MS_REMOUNT: ::c_ulong = 0x20; -pub const MS_MANDLOCK: ::c_ulong = 0x40; -pub const MS_NOATIME: ::c_ulong = 0x0400; -pub const MS_NODIRATIME: ::c_ulong = 0x0800; -pub const MS_BIND: ::c_ulong = 0x1000; -pub const MS_NOUSER: ::c_ulong = 0x80000000; -pub const MS_MGC_VAL: ::c_ulong = 0xc0ed0000; -pub const MS_MGC_MSK: ::c_ulong = 0xffff0000; -pub const MS_RMT_MASK: ::c_ulong = 0x800051; - -pub const EPERM: ::c_int = 1; -pub const ENOENT: ::c_int = 2; -pub const ESRCH: ::c_int = 3; -pub const EINTR: ::c_int = 4; -pub const EIO: ::c_int = 5; -pub const ENXIO: ::c_int = 6; -pub const E2BIG: ::c_int = 7; -pub const ENOEXEC: ::c_int = 8; -pub const EBADF: ::c_int = 9; -pub const ECHILD: ::c_int = 10; -pub const EAGAIN: ::c_int = 11; -pub const ENOMEM: ::c_int = 12; -pub const EACCES: ::c_int = 13; -pub const EFAULT: ::c_int = 14; -pub const ENOTBLK: ::c_int = 15; -pub const EBUSY: ::c_int = 16; -pub const EEXIST: ::c_int = 17; -pub const EXDEV: ::c_int = 18; -pub const ENODEV: ::c_int = 19; -pub const ENOTDIR: ::c_int = 20; -pub const EISDIR: ::c_int = 21; -pub const EINVAL: ::c_int = 22; -pub const ENFILE: ::c_int = 23; -pub const EMFILE: ::c_int = 24; -pub const ENOTTY: ::c_int = 25; -pub const ETXTBSY: ::c_int = 26; -pub const EFBIG: ::c_int = 27; -pub const ENOSPC: ::c_int = 28; -pub const ESPIPE: ::c_int = 29; -pub const EROFS: ::c_int = 30; -pub const EMLINK: ::c_int = 31; -pub const EPIPE: ::c_int = 32; -pub const EDOM: ::c_int = 33; -pub const ERANGE: ::c_int = 34; -pub const EWOULDBLOCK: ::c_int = EAGAIN; - -pub const SCM_RIGHTS: ::c_int = 0x01; -pub const SCM_CREDENTIALS: ::c_int = 0x02; - -// netinet/in.h -// NOTE: These are in addition to the constants defined in src/unix/mod.rs - -// IPPROTO_IP defined in src/unix/mod.rs -/// Hop-by-hop option header -pub const IPPROTO_HOPOPTS: ::c_int = 0; -// IPPROTO_ICMP defined in src/unix/mod.rs -/// group mgmt protocol -pub const IPPROTO_IGMP: ::c_int = 2; -/// for compatibility -pub const IPPROTO_IPIP: ::c_int = 4; -// IPPROTO_TCP defined in src/unix/mod.rs -/// exterior gateway protocol -pub const IPPROTO_EGP: ::c_int = 8; -/// pup -pub const IPPROTO_PUP: ::c_int = 12; -// IPPROTO_UDP defined in src/unix/mod.rs -/// xns idp -pub const IPPROTO_IDP: ::c_int = 22; -/// tp-4 w/ class negotiation -pub const IPPROTO_TP: ::c_int = 29; -/// DCCP -pub const IPPROTO_DCCP: ::c_int = 33; -// IPPROTO_IPV6 defined in src/unix/mod.rs -/// IP6 routing header -pub const IPPROTO_ROUTING: ::c_int = 43; -/// IP6 fragmentation header -pub const IPPROTO_FRAGMENT: ::c_int = 44; -/// resource reservation -pub const IPPROTO_RSVP: ::c_int = 46; -/// General Routing Encap. -pub const IPPROTO_GRE: ::c_int = 47; -/// IP6 Encap Sec. Payload -pub const IPPROTO_ESP: ::c_int = 50; -/// IP6 Auth Header -pub const IPPROTO_AH: ::c_int = 51; -// IPPROTO_ICMPV6 defined in src/unix/mod.rs -/// IP6 no next header -pub const IPPROTO_NONE: ::c_int = 59; -/// IP6 destination option -pub const IPPROTO_DSTOPTS: ::c_int = 60; -pub const IPPROTO_MTP: ::c_int = 92; -pub const IPPROTO_BEETPH: ::c_int = 94; -/// encapsulation header -pub const IPPROTO_ENCAP: ::c_int = 98; -/// Protocol indep. multicast -pub const IPPROTO_PIM: ::c_int = 103; -/// IP Payload Comp. Protocol -pub const IPPROTO_COMP: ::c_int = 108; -/// SCTP -pub const IPPROTO_SCTP: ::c_int = 132; -pub const IPPROTO_MH: ::c_int = 135; -pub const IPPROTO_UDPLITE: ::c_int = 136; -pub const IPPROTO_MPLS: ::c_int = 137; -/// raw IP packet -pub const IPPROTO_RAW: ::c_int = 255; -pub const IPPROTO_MAX: ::c_int = 256; - -pub const PROT_GROWSDOWN: ::c_int = 0x1000000; -pub const PROT_GROWSUP: ::c_int = 0x2000000; - -pub const MAP_TYPE: ::c_int = 0x000f; - -pub const MADV_NORMAL: ::c_int = 0; -pub const MADV_RANDOM: ::c_int = 1; -pub const MADV_SEQUENTIAL: ::c_int = 2; -pub const MADV_WILLNEED: ::c_int = 3; -pub const MADV_DONTNEED: ::c_int = 4; -pub const MADV_REMOVE: ::c_int = 9; -pub const MADV_DONTFORK: ::c_int = 10; -pub const MADV_DOFORK: ::c_int = 11; -pub const MADV_MERGEABLE: ::c_int = 12; -pub const MADV_UNMERGEABLE: ::c_int = 13; -pub const MADV_HWPOISON: ::c_int = 100; - -// https://github.com/kraj/uClibc/blob/master/include/net/if.h#L44 -pub const IFF_UP: ::c_int = 0x1; // Interface is up. -pub const IFF_BROADCAST: ::c_int = 0x2; // Broadcast address valid. -pub const IFF_DEBUG: ::c_int = 0x4; // Turn on debugging. -pub const IFF_LOOPBACK: ::c_int = 0x8; // Is a loopback net. -pub const IFF_POINTOPOINT: ::c_int = 0x10; // Interface is point-to-point link. -pub const IFF_NOTRAILERS: ::c_int = 0x20; // Avoid use of trailers. -pub const IFF_RUNNING: ::c_int = 0x40; // Resources allocated. -pub const IFF_NOARP: ::c_int = 0x80; // No address resolution protocol. -pub const IFF_PROMISC: ::c_int = 0x100; // Receive all packets. -// Not supported -pub const IFF_ALLMULTI: ::c_int = 0x200; // Receive all multicast packets. -pub const IFF_MASTER: ::c_int = 0x400; // Master of a load balancer. -pub const IFF_SLAVE: ::c_int = 0x800; // Slave of a load balancer. -pub const IFF_MULTICAST: ::c_int = 0x1000; // Supports multicast. -pub const IFF_PORTSEL: ::c_int = 0x2000; // Can set media type. -pub const IFF_AUTOMEDIA: ::c_int = 0x4000; // Auto media select active. -// Dialup device with changing addresses. -pub const IFF_DYNAMIC: ::c_int = 0x8000; - -pub const SOL_IP: ::c_int = 0; -pub const SOL_TCP: ::c_int = 6; -pub const SOL_IPV6: ::c_int = 41; -pub const SOL_ICMPV6: ::c_int = 58; -pub const SOL_RAW: ::c_int = 255; -pub const SOL_DECNET: ::c_int = 261; -pub const SOL_X25: ::c_int = 262; -pub const SOL_PACKET: ::c_int = 263; -pub const SOL_ATM: ::c_int = 264; -pub const SOL_AAL: ::c_int = 265; -pub const SOL_IRDA: ::c_int = 266; - -pub const AF_UNSPEC: ::c_int = 0; -pub const AF_UNIX: ::c_int = 1; -pub const AF_LOCAL: ::c_int = 1; -pub const AF_INET: ::c_int = 2; -pub const AF_AX25: ::c_int = 3; -pub const AF_IPX: ::c_int = 4; -pub const AF_APPLETALK: ::c_int = 5; -pub const AF_NETROM: ::c_int = 6; -pub const AF_BRIDGE: ::c_int = 7; -pub const AF_ATMPVC: ::c_int = 8; -pub const AF_X25: ::c_int = 9; -pub const AF_INET6: ::c_int = 10; -pub const AF_ROSE: ::c_int = 11; -pub const AF_DECnet: ::c_int = 12; -pub const AF_NETBEUI: ::c_int = 13; -pub const AF_SECURITY: ::c_int = 14; -pub const AF_KEY: ::c_int = 15; -pub const AF_NETLINK: ::c_int = 16; -pub const AF_ROUTE: ::c_int = AF_NETLINK; -pub const AF_PACKET: ::c_int = 17; -pub const AF_ASH: ::c_int = 18; -pub const AF_ECONET: ::c_int = 19; -pub const AF_ATMSVC: ::c_int = 20; -pub const AF_SNA: ::c_int = 22; -pub const AF_IRDA: ::c_int = 23; -pub const AF_PPPOX: ::c_int = 24; -pub const AF_WANPIPE: ::c_int = 25; -pub const AF_LLC: ::c_int = 26; -pub const AF_CAN: ::c_int = 29; -pub const AF_TIPC: ::c_int = 30; -pub const AF_BLUETOOTH: ::c_int = 31; -pub const AF_IUCV: ::c_int = 32; -pub const AF_RXRPC: ::c_int = 33; -pub const AF_ISDN: ::c_int = 34; -pub const AF_PHONET: ::c_int = 35; -pub const AF_IEEE802154: ::c_int = 36; -pub const AF_CAIF: ::c_int = 37; -pub const AF_ALG: ::c_int = 38; - -pub const PF_UNSPEC: ::c_int = AF_UNSPEC; -pub const PF_UNIX: ::c_int = AF_UNIX; -pub const PF_LOCAL: ::c_int = AF_LOCAL; -pub const PF_INET: ::c_int = AF_INET; -pub const PF_AX25: ::c_int = AF_AX25; -pub const PF_IPX: ::c_int = AF_IPX; -pub const PF_APPLETALK: ::c_int = AF_APPLETALK; -pub const PF_NETROM: ::c_int = AF_NETROM; -pub const PF_BRIDGE: ::c_int = AF_BRIDGE; -pub const PF_ATMPVC: ::c_int = AF_ATMPVC; -pub const PF_X25: ::c_int = AF_X25; -pub const PF_INET6: ::c_int = AF_INET6; -pub const PF_ROSE: ::c_int = AF_ROSE; -pub const PF_DECnet: ::c_int = AF_DECnet; -pub const PF_NETBEUI: ::c_int = AF_NETBEUI; -pub const PF_SECURITY: ::c_int = AF_SECURITY; -pub const PF_KEY: ::c_int = AF_KEY; -pub const PF_NETLINK: ::c_int = AF_NETLINK; -pub const PF_ROUTE: ::c_int = AF_ROUTE; -pub const PF_PACKET: ::c_int = AF_PACKET; -pub const PF_ASH: ::c_int = AF_ASH; -pub const PF_ECONET: ::c_int = AF_ECONET; -pub const PF_ATMSVC: ::c_int = AF_ATMSVC; -pub const PF_SNA: ::c_int = AF_SNA; -pub const PF_IRDA: ::c_int = AF_IRDA; -pub const PF_PPPOX: ::c_int = AF_PPPOX; -pub const PF_WANPIPE: ::c_int = AF_WANPIPE; -pub const PF_LLC: ::c_int = AF_LLC; -pub const PF_CAN: ::c_int = AF_CAN; -pub const PF_TIPC: ::c_int = AF_TIPC; -pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; -pub const PF_IUCV: ::c_int = AF_IUCV; -pub const PF_RXRPC: ::c_int = AF_RXRPC; -pub const PF_ISDN: ::c_int = AF_ISDN; -pub const PF_PHONET: ::c_int = AF_PHONET; -pub const PF_IEEE802154: ::c_int = AF_IEEE802154; -pub const PF_CAIF: ::c_int = AF_CAIF; -pub const PF_ALG: ::c_int = AF_ALG; - -pub const SOMAXCONN: ::c_int = 128; - -pub const MSG_OOB: ::c_int = 1; -pub const MSG_PEEK: ::c_int = 2; -pub const MSG_DONTROUTE: ::c_int = 4; -pub const MSG_CTRUNC: ::c_int = 8; -pub const MSG_TRUNC: ::c_int = 0x20; -pub const MSG_DONTWAIT: ::c_int = 0x40; -pub const MSG_EOR: ::c_int = 0x80; -pub const MSG_WAITALL: ::c_int = 0x100; -pub const MSG_FIN: ::c_int = 0x200; -pub const MSG_SYN: ::c_int = 0x400; -pub const MSG_CONFIRM: ::c_int = 0x800; -pub const MSG_RST: ::c_int = 0x1000; -pub const MSG_ERRQUEUE: ::c_int = 0x2000; -pub const MSG_NOSIGNAL: ::c_int = 0x4000; -pub const MSG_MORE: ::c_int = 0x8000; -pub const MSG_WAITFORONE: ::c_int = 0x10000; -pub const MSG_CMSG_CLOEXEC: ::c_int = 0x40000000; - -pub const SOCK_RAW: ::c_int = 3; -pub const IP_MULTICAST_TTL: ::c_int = 33; -pub const IP_MULTICAST_LOOP: ::c_int = 34; -pub const IP_TTL: ::c_int = 2; -pub const IP_HDRINCL: ::c_int = 3; -pub const IP_ADD_MEMBERSHIP: ::c_int = 35; -pub const IP_DROP_MEMBERSHIP: ::c_int = 36; -pub const IPV6_ADD_MEMBERSHIP: ::c_int = 20; -pub const IPV6_DROP_MEMBERSHIP: ::c_int = 21; - -pub const IPV6_JOIN_GROUP: ::c_int = 20; -pub const IPV6_LEAVE_GROUP: ::c_int = 21; - -pub const TCP_NODELAY: ::c_int = 1; -pub const TCP_MAXSEG: ::c_int = 2; -pub const TCP_CORK: ::c_int = 3; -pub const TCP_KEEPIDLE: ::c_int = 4; -pub const TCP_KEEPINTVL: ::c_int = 5; -pub const TCP_KEEPCNT: ::c_int = 6; -pub const TCP_SYNCNT: ::c_int = 7; -pub const TCP_LINGER2: ::c_int = 8; -pub const TCP_DEFER_ACCEPT: ::c_int = 9; -pub const TCP_WINDOW_CLAMP: ::c_int = 10; -pub const TCP_INFO: ::c_int = 11; -pub const TCP_QUICKACK: ::c_int = 12; -pub const TCP_CONGESTION: ::c_int = 13; - -pub const IPV6_MULTICAST_LOOP: ::c_int = 19; -pub const IPV6_V6ONLY: ::c_int = 26; - -pub const SO_DEBUG: ::c_int = 1; - -pub const SHUT_RD: ::c_int = 0; -pub const SHUT_WR: ::c_int = 1; -pub const SHUT_RDWR: ::c_int = 2; - -pub const LOCK_SH: ::c_int = 1; -pub const LOCK_EX: ::c_int = 2; -pub const LOCK_NB: ::c_int = 4; -pub const LOCK_UN: ::c_int = 8; - -pub const SS_ONSTACK: ::c_int = 1; -pub const SS_DISABLE: ::c_int = 2; - -pub const PATH_MAX: ::c_int = 4096; - -pub const FD_SETSIZE: usize = 1024; - -pub const EPOLLIN: ::c_int = 0x1; -pub const EPOLLPRI: ::c_int = 0x2; -pub const EPOLLOUT: ::c_int = 0x4; -pub const EPOLLRDNORM: ::c_int = 0x40; -pub const EPOLLRDBAND: ::c_int = 0x80; -pub const EPOLLWRNORM: ::c_int = 0x100; -pub const EPOLLWRBAND: ::c_int = 0x200; -pub const EPOLLMSG: ::c_int = 0x400; -pub const EPOLLERR: ::c_int = 0x8; -pub const EPOLLHUP: ::c_int = 0x10; -pub const EPOLLET: ::c_int = 0x80000000; - -pub const EPOLL_CTL_ADD: ::c_int = 1; -pub const EPOLL_CTL_MOD: ::c_int = 3; -pub const EPOLL_CTL_DEL: ::c_int = 2; - -pub const MNT_DETACH: ::c_int = 0x2; -pub const MNT_EXPIRE: ::c_int = 0x4; - -pub const MNT_FORCE: ::c_int = 0x1; - -pub const Q_SYNC: ::c_int = 0x600; -pub const Q_QUOTAON: ::c_int = 0x100; -pub const Q_QUOTAOFF: ::c_int = 0x200; -pub const Q_GETQUOTA: ::c_int = 0x300; -pub const Q_SETQUOTA: ::c_int = 0x400; - -pub const TCIOFF: ::c_int = 2; -pub const TCION: ::c_int = 3; -pub const TCOOFF: ::c_int = 0; -pub const TCOON: ::c_int = 1; -pub const TCIFLUSH: ::c_int = 0; -pub const TCOFLUSH: ::c_int = 1; -pub const TCIOFLUSH: ::c_int = 2; -pub const NL0: ::c_int = 0x00000000; -pub const NL1: ::c_int = 0x00000100; -pub const TAB0: ::c_int = 0x00000000; -pub const CR0: ::c_int = 0x00000000; -pub const FF0: ::c_int = 0x00000000; -pub const BS0: ::c_int = 0x00000000; -pub const VT0: ::c_int = 0x00000000; -pub const VERASE: usize = 2; -pub const VKILL: usize = 3; -pub const VINTR: usize = 0; -pub const VQUIT: usize = 1; -pub const VLNEXT: usize = 15; -pub const IGNBRK: ::tcflag_t = 0x00000001; -pub const BRKINT: ::tcflag_t = 0x00000002; -pub const IGNPAR: ::tcflag_t = 0x00000004; -pub const PARMRK: ::tcflag_t = 0x00000008; -pub const INPCK: ::tcflag_t = 0x00000010; -pub const ISTRIP: ::tcflag_t = 0x00000020; -pub const INLCR: ::tcflag_t = 0x00000040; -pub const IGNCR: ::tcflag_t = 0x00000080; -pub const ICRNL: ::tcflag_t = 0x00000100; -pub const IXANY: ::tcflag_t = 0x00000800; -pub const IMAXBEL: ::tcflag_t = 0x00002000; -pub const OPOST: ::tcflag_t = 0x1; -pub const CS5: ::tcflag_t = 0x00000000; -pub const CRTSCTS: ::tcflag_t = 0x80000000; -pub const ECHO: ::tcflag_t = 0x00000008; - -pub const CLONE_VM: ::c_int = 0x100; -pub const CLONE_FS: ::c_int = 0x200; -pub const CLONE_FILES: ::c_int = 0x400; -pub const CLONE_SIGHAND: ::c_int = 0x800; -pub const CLONE_PTRACE: ::c_int = 0x2000; -pub const CLONE_VFORK: ::c_int = 0x4000; -pub const CLONE_PARENT: ::c_int = 0x8000; -pub const CLONE_THREAD: ::c_int = 0x10000; -pub const CLONE_NEWNS: ::c_int = 0x20000; -pub const CLONE_SYSVSEM: ::c_int = 0x40000; -pub const CLONE_SETTLS: ::c_int = 0x80000; -pub const CLONE_PARENT_SETTID: ::c_int = 0x100000; -pub const CLONE_CHILD_CLEARTID: ::c_int = 0x200000; -pub const CLONE_DETACHED: ::c_int = 0x400000; -pub const CLONE_UNTRACED: ::c_int = 0x800000; -pub const CLONE_CHILD_SETTID: ::c_int = 0x01000000; -pub const CLONE_NEWUTS: ::c_int = 0x04000000; -pub const CLONE_NEWIPC: ::c_int = 0x08000000; -pub const CLONE_NEWUSER: ::c_int = 0x10000000; -pub const CLONE_NEWPID: ::c_int = 0x20000000; -pub const CLONE_NEWNET: ::c_int = 0x40000000; -pub const CLONE_IO: ::c_int = 0x80000000; - -pub const WNOHANG: ::c_int = 0x00000001; -pub const WUNTRACED: ::c_int = 0x00000002; -pub const WSTOPPED: ::c_int = WUNTRACED; -pub const WEXITED: ::c_int = 0x00000004; -pub const WCONTINUED: ::c_int = 0x00000008; -pub const WNOWAIT: ::c_int = 0x01000000; - -pub const __WNOTHREAD: ::c_int = 0x20000000; -pub const __WALL: ::c_int = 0x40000000; -pub const __WCLONE: ::c_int = 0x80000000; - -pub const SPLICE_F_MOVE: ::c_uint = 0x01; -pub const SPLICE_F_NONBLOCK: ::c_uint = 0x02; -pub const SPLICE_F_MORE: ::c_uint = 0x04; -pub const SPLICE_F_GIFT: ::c_uint = 0x08; - -pub const RTLD_LOCAL: ::c_int = 0; -pub const RTLD_LAZY: ::c_int = 1; - -pub const POSIX_FADV_NORMAL: ::c_int = 0; -pub const POSIX_FADV_RANDOM: ::c_int = 1; -pub const POSIX_FADV_SEQUENTIAL: ::c_int = 2; -pub const POSIX_FADV_WILLNEED: ::c_int = 3; - -pub const AT_FDCWD: ::c_int = -100; -pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x100; -pub const AT_REMOVEDIR: ::c_int = 0x200; -pub const AT_SYMLINK_FOLLOW: ::c_int = 0x400; - -pub const LOG_CRON: ::c_int = 9 << 3; -pub const LOG_AUTHPRIV: ::c_int = 10 << 3; -pub const LOG_FTP: ::c_int = 11 << 3; -pub const LOG_PERROR: ::c_int = 0x20; - -pub const POLLIN: ::c_short = 0x1; -pub const POLLPRI: ::c_short = 0x2; -pub const POLLOUT: ::c_short = 0x4; -pub const POLLERR: ::c_short = 0x8; -pub const POLLHUP: ::c_short = 0x10; -pub const POLLNVAL: ::c_short = 0x20; - -pub const PIPE_BUF: usize = 4096; - -pub const SI_LOAD_SHIFT: ::c_uint = 16; - -pub const SIGEV_SIGNAL: ::c_int = 0; -pub const SIGEV_NONE: ::c_int = 1; -pub const SIGEV_THREAD: ::c_int = 2; - -pub const P_ALL: idtype_t = 0; -pub const P_PID: idtype_t = 1; -pub const P_PGID: idtype_t = 2; - -pub const UTIME_OMIT: c_long = 1073741822; -pub const UTIME_NOW: c_long = 1073741823; - -pub const L_tmpnam: ::c_uint = 20; -pub const _PC_LINK_MAX: ::c_int = 0; -pub const _PC_MAX_CANON: ::c_int = 1; -pub const _PC_MAX_INPUT: ::c_int = 2; -pub const _PC_NAME_MAX: ::c_int = 3; -pub const _PC_PATH_MAX: ::c_int = 4; -pub const _PC_PIPE_BUF: ::c_int = 5; -pub const _PC_CHOWN_RESTRICTED: ::c_int = 6; -pub const _PC_NO_TRUNC: ::c_int = 7; -pub const _PC_VDISABLE: ::c_int = 8; - -pub const _SC_ARG_MAX: ::c_int = 0; -pub const _SC_CHILD_MAX: ::c_int = 1; -pub const _SC_CLK_TCK: ::c_int = 2; -pub const _SC_NGROUPS_MAX: ::c_int = 3; -pub const _SC_OPEN_MAX: ::c_int = 4; -pub const _SC_STREAM_MAX: ::c_int = 5; -pub const _SC_TZNAME_MAX: ::c_int = 6; -pub const _SC_JOB_CONTROL: ::c_int = 7; -pub const _SC_SAVED_IDS: ::c_int = 8; -pub const _SC_REALTIME_SIGNALS: ::c_int = 9; -pub const _SC_PRIORITY_SCHEDULING: ::c_int = 10; -pub const _SC_TIMERS: ::c_int = 11; -pub const _SC_ASYNCHRONOUS_IO: ::c_int = 12; -pub const _SC_PRIORITIZED_IO: ::c_int = 13; -pub const _SC_SYNCHRONIZED_IO: ::c_int = 14; -pub const _SC_FSYNC: ::c_int = 15; -pub const _SC_MAPPED_FILES: ::c_int = 16; -pub const _SC_MEMLOCK: ::c_int = 17; -pub const _SC_MEMLOCK_RANGE: ::c_int = 18; -pub const _SC_MEMORY_PROTECTION: ::c_int = 19; -pub const _SC_MESSAGE_PASSING: ::c_int = 20; -pub const _SC_SEMAPHORES: ::c_int = 21; -pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 22; -pub const _SC_AIO_LISTIO_MAX: ::c_int = 23; -pub const _SC_AIO_MAX: ::c_int = 24; -pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 25; -pub const _SC_DELAYTIMER_MAX: ::c_int = 26; -pub const _SC_MQ_OPEN_MAX: ::c_int = 27; -pub const _SC_MQ_PRIO_MAX: ::c_int = 28; -pub const _SC_VERSION: ::c_int = 29; -pub const _SC_PAGESIZE: ::c_int = 30; -pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; -pub const _SC_RTSIG_MAX: ::c_int = 31; -pub const _SC_SEM_NSEMS_MAX: ::c_int = 32; -pub const _SC_SEM_VALUE_MAX: ::c_int = 33; -pub const _SC_SIGQUEUE_MAX: ::c_int = 34; -pub const _SC_TIMER_MAX: ::c_int = 35; -pub const _SC_BC_BASE_MAX: ::c_int = 36; -pub const _SC_BC_DIM_MAX: ::c_int = 37; -pub const _SC_BC_SCALE_MAX: ::c_int = 38; -pub const _SC_BC_STRING_MAX: ::c_int = 39; -pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 40; -pub const _SC_EXPR_NEST_MAX: ::c_int = 42; -pub const _SC_LINE_MAX: ::c_int = 43; -pub const _SC_RE_DUP_MAX: ::c_int = 44; -pub const _SC_2_VERSION: ::c_int = 46; -pub const _SC_2_C_BIND: ::c_int = 47; -pub const _SC_2_C_DEV: ::c_int = 48; -pub const _SC_2_FORT_DEV: ::c_int = 49; -pub const _SC_2_FORT_RUN: ::c_int = 50; -pub const _SC_2_SW_DEV: ::c_int = 51; -pub const _SC_2_LOCALEDEF: ::c_int = 52; -pub const _SC_IOV_MAX: ::c_int = 60; -pub const _SC_THREADS: ::c_int = 67; -pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 68; -pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 69; -pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 70; -pub const _SC_LOGIN_NAME_MAX: ::c_int = 71; -pub const _SC_TTY_NAME_MAX: ::c_int = 72; -pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 73; -pub const _SC_THREAD_KEYS_MAX: ::c_int = 74; -pub const _SC_THREAD_STACK_MIN: ::c_int = 75; -pub const _SC_THREAD_THREADS_MAX: ::c_int = 76; -pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 77; -pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 78; -pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 79; -pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 80; -pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 81; -pub const _SC_NPROCESSORS_ONLN: ::c_int = 84; -pub const _SC_ATEXIT_MAX: ::c_int = 87; -pub const _SC_XOPEN_VERSION: ::c_int = 89; -pub const _SC_XOPEN_XCU_VERSION: ::c_int = 90; -pub const _SC_XOPEN_UNIX: ::c_int = 91; -pub const _SC_XOPEN_CRYPT: ::c_int = 92; -pub const _SC_XOPEN_ENH_I18N: ::c_int = 93; -pub const _SC_XOPEN_SHM: ::c_int = 94; -pub const _SC_2_CHAR_TERM: ::c_int = 95; -pub const _SC_2_UPE: ::c_int = 97; -pub const _SC_XBS5_ILP32_OFF32: ::c_int = 125; -pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 126; -pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 128; -pub const _SC_XOPEN_LEGACY: ::c_int = 129; -pub const _SC_XOPEN_REALTIME: ::c_int = 130; -pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 131; -pub const _SC_HOST_NAME_MAX: ::c_int = 180; - -pub const RLIM_SAVED_MAX: ::rlim_t = RLIM_INFINITY; -pub const RLIM_SAVED_CUR: ::rlim_t = RLIM_INFINITY; - -pub const GLOB_ERR: ::c_int = 1 << 0; -pub const GLOB_MARK: ::c_int = 1 << 1; -pub const GLOB_NOSORT: ::c_int = 1 << 2; -pub const GLOB_DOOFFS: ::c_int = 1 << 3; -pub const GLOB_NOCHECK: ::c_int = 1 << 4; -pub const GLOB_APPEND: ::c_int = 1 << 5; -pub const GLOB_NOESCAPE: ::c_int = 1 << 6; - -pub const GLOB_NOSPACE: ::c_int = 1; -pub const GLOB_ABORTED: ::c_int = 2; -pub const GLOB_NOMATCH: ::c_int = 3; - -pub const POSIX_MADV_NORMAL: ::c_int = 0; -pub const POSIX_MADV_RANDOM: ::c_int = 1; -pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; -pub const POSIX_MADV_WILLNEED: ::c_int = 3; - -pub const S_IEXEC: mode_t = 64; -pub const S_IWRITE: mode_t = 128; -pub const S_IREAD: mode_t = 256; - -pub const F_LOCK: ::c_int = 1; -pub const F_TEST: ::c_int = 3; -pub const F_TLOCK: ::c_int = 2; -pub const F_ULOCK: ::c_int = 0; - -pub const ST_RDONLY: ::c_ulong = 1; -pub const ST_NOSUID: ::c_ulong = 2; -pub const ST_NODEV: ::c_ulong = 4; -pub const ST_NOEXEC: ::c_ulong = 8; -pub const ST_SYNCHRONOUS: ::c_ulong = 16; -pub const ST_MANDLOCK: ::c_ulong = 64; -pub const ST_WRITE: ::c_ulong = 128; -pub const ST_APPEND: ::c_ulong = 256; -pub const ST_IMMUTABLE: ::c_ulong = 512; -pub const ST_NOATIME: ::c_ulong = 1024; -pub const ST_NODIRATIME: ::c_ulong = 2048; - -pub const RTLD_NEXT: *mut ::c_void = -1i64 as *mut ::c_void; -pub const RTLD_DEFAULT: *mut ::c_void = 0i64 as *mut ::c_void; -pub const RTLD_NODELETE: ::c_int = 0x1000; -pub const RTLD_NOW: ::c_int = 0x2; - -pub const TCP_MD5SIG: ::c_int = 14; - -pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_MUTEX_T], -}; -pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_COND_T], -}; -pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { - __align: [], - size: [0; __SIZEOF_PTHREAD_RWLOCK_T], -}; -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; -pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; -pub const __SIZEOF_PTHREAD_COND_T: usize = 48; - -pub const SCHED_OTHER: ::c_int = 0; -pub const SCHED_FIFO: ::c_int = 1; -pub const SCHED_RR: ::c_int = 2; -pub const SCHED_BATCH: ::c_int = 3; -pub const SCHED_IDLE: ::c_int = 5; - -// System V IPC -pub const IPC_PRIVATE: ::key_t = 0; - -pub const IPC_CREAT: ::c_int = 0o1000; -pub const IPC_EXCL: ::c_int = 0o2000; -pub const IPC_NOWAIT: ::c_int = 0o4000; - -pub const IPC_RMID: ::c_int = 0; -pub const IPC_SET: ::c_int = 1; -pub const IPC_STAT: ::c_int = 2; -pub const IPC_INFO: ::c_int = 3; -pub const MSG_STAT: ::c_int = 11; -pub const MSG_INFO: ::c_int = 12; - -pub const MSG_NOERROR: ::c_int = 0o10000; -pub const MSG_EXCEPT: ::c_int = 0o20000; - -pub const SHM_R: ::c_int = 0o400; -pub const SHM_W: ::c_int = 0o200; - -pub const SHM_RDONLY: ::c_int = 0o10000; -pub const SHM_RND: ::c_int = 0o20000; -pub const SHM_REMAP: ::c_int = 0o40000; - -pub const SHM_LOCK: ::c_int = 11; -pub const SHM_UNLOCK: ::c_int = 12; - -pub const SHM_HUGETLB: ::c_int = 0o4000; -pub const SHM_NORESERVE: ::c_int = 0o10000; - -pub const EPOLLRDHUP: ::c_int = 0x2000; -pub const EPOLLONESHOT: ::c_int = 0x40000000; - -pub const QFMT_VFS_OLD: ::c_int = 1; -pub const QFMT_VFS_V0: ::c_int = 2; - -pub const EFD_SEMAPHORE: ::c_int = 0x1; - -pub const LOG_NFACILITIES: ::c_int = 24; - -pub const SEM_FAILED: *mut ::sem_t = 0 as *mut sem_t; - -pub const RB_AUTOBOOT: ::c_int = 0x01234567u32 as i32; -pub const RB_HALT_SYSTEM: ::c_int = 0xcdef0123u32 as i32; -pub const RB_ENABLE_CAD: ::c_int = 0x89abcdefu32 as i32; -pub const RB_DISABLE_CAD: ::c_int = 0x00000000u32 as i32; -pub const RB_POWER_OFF: ::c_int = 0x4321fedcu32 as i32; - -pub const AI_PASSIVE: ::c_int = 0x0001; -pub const AI_CANONNAME: ::c_int = 0x0002; -pub const AI_NUMERICHOST: ::c_int = 0x0004; -pub const AI_V4MAPPED: ::c_int = 0x0008; -pub const AI_ALL: ::c_int = 0x0010; -pub const AI_ADDRCONFIG: ::c_int = 0x0020; - -pub const AI_NUMERICSERV: ::c_int = 0x0400; - -pub const EAI_BADFLAGS: ::c_int = -1; -pub const EAI_NONAME: ::c_int = -2; -pub const EAI_AGAIN: ::c_int = -3; -pub const EAI_FAIL: ::c_int = -4; -pub const EAI_FAMILY: ::c_int = -6; -pub const EAI_SOCKTYPE: ::c_int = -7; -pub const EAI_SERVICE: ::c_int = -8; -pub const EAI_MEMORY: ::c_int = -10; -pub const EAI_OVERFLOW: ::c_int = -12; - -pub const NI_NUMERICHOST: ::c_int = 1; -pub const NI_NUMERICSERV: ::c_int = 2; -pub const NI_NOFQDN: ::c_int = 4; -pub const NI_NAMEREQD: ::c_int = 8; -pub const NI_DGRAM: ::c_int = 16; - -pub const SYNC_FILE_RANGE_WAIT_BEFORE: ::c_uint = 1; -pub const SYNC_FILE_RANGE_WRITE: ::c_uint = 2; -pub const SYNC_FILE_RANGE_WAIT_AFTER: ::c_uint = 4; - -pub const EAI_SYSTEM: ::c_int = -11; - -pub const MREMAP_MAYMOVE: ::c_int = 1; -pub const MREMAP_FIXED: ::c_int = 2; - -pub const PR_SET_PDEATHSIG: ::c_int = 1; -pub const PR_GET_PDEATHSIG: ::c_int = 2; - -pub const PR_GET_DUMPABLE: ::c_int = 3; -pub const PR_SET_DUMPABLE: ::c_int = 4; - -pub const PR_GET_UNALIGN: ::c_int = 5; -pub const PR_SET_UNALIGN: ::c_int = 6; -pub const PR_UNALIGN_NOPRINT: ::c_int = 1; -pub const PR_UNALIGN_SIGBUS: ::c_int = 2; - -pub const PR_GET_KEEPCAPS: ::c_int = 7; -pub const PR_SET_KEEPCAPS: ::c_int = 8; - -pub const PR_GET_FPEMU: ::c_int = 9; -pub const PR_SET_FPEMU: ::c_int = 10; -pub const PR_FPEMU_NOPRINT: ::c_int = 1; -pub const PR_FPEMU_SIGFPE: ::c_int = 2; - -pub const PR_GET_FPEXC: ::c_int = 11; -pub const PR_SET_FPEXC: ::c_int = 12; -pub const PR_FP_EXC_SW_ENABLE: ::c_int = 0x80; -pub const PR_FP_EXC_DIV: ::c_int = 0x010000; -pub const PR_FP_EXC_OVF: ::c_int = 0x020000; -pub const PR_FP_EXC_UND: ::c_int = 0x040000; -pub const PR_FP_EXC_RES: ::c_int = 0x080000; -pub const PR_FP_EXC_INV: ::c_int = 0x100000; -pub const PR_FP_EXC_DISABLED: ::c_int = 0; -pub const PR_FP_EXC_NONRECOV: ::c_int = 1; -pub const PR_FP_EXC_ASYNC: ::c_int = 2; -pub const PR_FP_EXC_PRECISE: ::c_int = 3; - -pub const PR_GET_TIMING: ::c_int = 13; -pub const PR_SET_TIMING: ::c_int = 14; -pub const PR_TIMING_STATISTICAL: ::c_int = 0; -pub const PR_TIMING_TIMESTAMP: ::c_int = 1; - -pub const PR_SET_NAME: ::c_int = 15; -pub const PR_GET_NAME: ::c_int = 16; - -pub const PR_GET_ENDIAN: ::c_int = 19; -pub const PR_SET_ENDIAN: ::c_int = 20; -pub const PR_ENDIAN_BIG: ::c_int = 0; -pub const PR_ENDIAN_LITTLE: ::c_int = 1; -pub const PR_ENDIAN_PPC_LITTLE: ::c_int = 2; - -pub const PR_GET_SECCOMP: ::c_int = 21; -pub const PR_SET_SECCOMP: ::c_int = 22; - -pub const PR_CAPBSET_READ: ::c_int = 23; -pub const PR_CAPBSET_DROP: ::c_int = 24; - -pub const PR_GET_TSC: ::c_int = 25; -pub const PR_SET_TSC: ::c_int = 26; -pub const PR_TSC_ENABLE: ::c_int = 1; -pub const PR_TSC_SIGSEGV: ::c_int = 2; - -pub const PR_GET_SECUREBITS: ::c_int = 27; -pub const PR_SET_SECUREBITS: ::c_int = 28; - -pub const PR_SET_TIMERSLACK: ::c_int = 29; -pub const PR_GET_TIMERSLACK: ::c_int = 30; - -pub const PR_TASK_PERF_EVENTS_DISABLE: ::c_int = 31; -pub const PR_TASK_PERF_EVENTS_ENABLE: ::c_int = 32; - -pub const PR_MCE_KILL: ::c_int = 33; -pub const PR_MCE_KILL_CLEAR: ::c_int = 0; -pub const PR_MCE_KILL_SET: ::c_int = 1; - -pub const PR_MCE_KILL_LATE: ::c_int = 0; -pub const PR_MCE_KILL_EARLY: ::c_int = 1; -pub const PR_MCE_KILL_DEFAULT: ::c_int = 2; - -pub const PR_MCE_KILL_GET: ::c_int = 34; - -pub const PR_SET_MM: ::c_int = 35; -pub const PR_SET_MM_START_CODE: ::c_int = 1; -pub const PR_SET_MM_END_CODE: ::c_int = 2; -pub const PR_SET_MM_START_DATA: ::c_int = 3; -pub const PR_SET_MM_END_DATA: ::c_int = 4; -pub const PR_SET_MM_START_STACK: ::c_int = 5; -pub const PR_SET_MM_START_BRK: ::c_int = 6; -pub const PR_SET_MM_BRK: ::c_int = 7; -pub const PR_SET_MM_ARG_START: ::c_int = 8; -pub const PR_SET_MM_ARG_END: ::c_int = 9; -pub const PR_SET_MM_ENV_START: ::c_int = 10; -pub const PR_SET_MM_ENV_END: ::c_int = 11; -pub const PR_SET_MM_AUXV: ::c_int = 12; -pub const PR_SET_MM_EXE_FILE: ::c_int = 13; -pub const PR_SET_MM_MAP: ::c_int = 14; -pub const PR_SET_MM_MAP_SIZE: ::c_int = 15; - -pub const PR_SET_PTRACER: ::c_int = 0x59616d61; - -pub const PR_SET_CHILD_SUBREAPER: ::c_int = 36; -pub const PR_GET_CHILD_SUBREAPER: ::c_int = 37; - -pub const PR_SET_NO_NEW_PRIVS: ::c_int = 38; -pub const PR_GET_NO_NEW_PRIVS: ::c_int = 39; - -pub const PR_GET_TID_ADDRESS: ::c_int = 40; - -pub const PR_SET_THP_DISABLE: ::c_int = 41; -pub const PR_GET_THP_DISABLE: ::c_int = 42; - -pub const ABDAY_1: ::nl_item = 0x300; -pub const ABDAY_2: ::nl_item = 0x301; -pub const ABDAY_3: ::nl_item = 0x302; -pub const ABDAY_4: ::nl_item = 0x303; -pub const ABDAY_5: ::nl_item = 0x304; -pub const ABDAY_6: ::nl_item = 0x305; -pub const ABDAY_7: ::nl_item = 0x306; - -pub const DAY_1: ::nl_item = 0x307; -pub const DAY_2: ::nl_item = 0x308; -pub const DAY_3: ::nl_item = 0x309; -pub const DAY_4: ::nl_item = 0x30A; -pub const DAY_5: ::nl_item = 0x30B; -pub const DAY_6: ::nl_item = 0x30C; -pub const DAY_7: ::nl_item = 0x30D; - -pub const ABMON_1: ::nl_item = 0x30E; -pub const ABMON_2: ::nl_item = 0x30F; -pub const ABMON_3: ::nl_item = 0x310; -pub const ABMON_4: ::nl_item = 0x311; -pub const ABMON_5: ::nl_item = 0x312; -pub const ABMON_6: ::nl_item = 0x313; -pub const ABMON_7: ::nl_item = 0x314; -pub const ABMON_8: ::nl_item = 0x315; -pub const ABMON_9: ::nl_item = 0x316; -pub const ABMON_10: ::nl_item = 0x317; -pub const ABMON_11: ::nl_item = 0x318; -pub const ABMON_12: ::nl_item = 0x319; - -pub const MON_1: ::nl_item = 0x31A; -pub const MON_2: ::nl_item = 0x31B; -pub const MON_3: ::nl_item = 0x31C; -pub const MON_4: ::nl_item = 0x31D; -pub const MON_5: ::nl_item = 0x31E; -pub const MON_6: ::nl_item = 0x31F; -pub const MON_7: ::nl_item = 0x320; -pub const MON_8: ::nl_item = 0x321; -pub const MON_9: ::nl_item = 0x322; -pub const MON_10: ::nl_item = 0x323; -pub const MON_11: ::nl_item = 0x324; -pub const MON_12: ::nl_item = 0x325; - -pub const AM_STR: ::nl_item = 0x326; -pub const PM_STR: ::nl_item = 0x327; - -pub const D_T_FMT: ::nl_item = 0x328; -pub const D_FMT: ::nl_item = 0x329; -pub const T_FMT: ::nl_item = 0x32A; -pub const T_FMT_AMPM: ::nl_item = 0x32B; - -pub const ERA: ::nl_item = 0x32C; -pub const ERA_D_FMT: ::nl_item = 0x32E; -pub const ALT_DIGITS: ::nl_item = 0x32F; -pub const ERA_D_T_FMT: ::nl_item = 0x330; -pub const ERA_T_FMT: ::nl_item = 0x331; - -pub const CODESET: ::nl_item = 10; - -pub const CRNCYSTR: ::nl_item = 0x215; - -pub const RADIXCHAR: ::nl_item = 0x100; -pub const THOUSEP: ::nl_item = 0x101; - -pub const NOEXPR: ::nl_item = 0x501; -pub const YESSTR: ::nl_item = 0x502; -pub const NOSTR: ::nl_item = 0x503; - -pub const FILENAME_MAX: ::c_uint = 4095; - -pub const AF_MAX: ::c_int = 39; - -f! { - pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { - let fd = fd as usize; - let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; - (*set).fds_bits[fd / size] &= !(1 << (fd % size)); - return - } - - pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { - let fd = fd as usize; - let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; - return ((*set).fds_bits[fd / size] & (1 << (fd % size))) != 0 - } - - pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { - let fd = fd as usize; - let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; - (*set).fds_bits[fd / size] |= 1 << (fd % size); - return - } - - pub fn FD_ZERO(set: *mut fd_set) -> () { - for slot in (*set).fds_bits.iter_mut() { - *slot = 0; - } - } - - pub fn WIFSTOPPED(status: ::c_int) -> bool { - (status & 0xff) == 0x7f - } - - pub fn WSTOPSIG(status: ::c_int) -> ::c_int { - (status >> 8) & 0xff - } - - pub fn WIFCONTINUED(status: ::c_int) -> bool { - status == 0xffff - } - - pub fn WIFSIGNALED(status: ::c_int) -> bool { - ((status & 0x7f) + 1) as i8 >= 2 - } - - pub fn WTERMSIG(status: ::c_int) -> ::c_int { - status & 0x7f - } - - pub fn WIFEXITED(status: ::c_int) -> bool { - (status & 0x7f) == 0 - } - - pub fn WEXITSTATUS(status: ::c_int) -> ::c_int { - (status >> 8) & 0xff - } - - pub fn WCOREDUMP(status: ::c_int) -> bool { - (status & 0x80) != 0 - } - - pub fn CPU_ZERO(cpuset: &mut cpu_set_t) -> () { - for slot in cpuset.bits.iter_mut() { - *slot = 0; - } - } - - pub fn CPU_SET(cpu: usize, cpuset: &mut cpu_set_t) -> () { - let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc - let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); - cpuset.bits[idx] |= 1 << offset; - () - } - - pub fn CPU_CLR(cpu: usize, cpuset: &mut cpu_set_t) -> () { - let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc - let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); - cpuset.bits[idx] &= !(1 << offset); - () - } - - pub fn CPU_ISSET(cpu: usize, cpuset: &cpu_set_t) -> bool { - let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); - let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); - 0 != (cpuset.bits[idx] & (1 << offset)) - } - - pub fn CPU_EQUAL(set1: &cpu_set_t, set2: &cpu_set_t) -> bool { - set1.bits == set2.bits - } - - pub fn QCMD(cmd: ::c_int, type_: ::c_int) -> ::c_int { - (cmd << 8) | (type_ & 0x00ff) - } -} - -extern { - pub fn fdatasync(fd: ::c_int) -> ::c_int; - pub fn mincore(addr: *mut ::c_void, len: ::size_t, - vec: *mut ::c_uchar) -> ::c_int; - pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; - pub fn clock_nanosleep(clk_id: ::clockid_t, - flags: ::c_int, - rqtp: *const ::timespec, - rmtp: *mut ::timespec) -> ::c_int; - pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; - pub fn prctl(option: ::c_int, ...) -> ::c_int; - pub fn pthread_getattr_np(native: ::pthread_t, - attr: *mut ::pthread_attr_t) -> ::c_int; - pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, - guardsize: *mut ::size_t) -> ::c_int; - pub fn pthread_attr_getstack(attr: *const ::pthread_attr_t, - stackaddr: *mut *mut ::c_void, - stacksize: *mut ::size_t) -> ::c_int; - pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; - pub fn setgroups(ngroups: ::size_t, - ptr: *const ::gid_t) -> ::c_int; - pub fn initgroups(user: *const ::c_char, group: ::gid_t) -> ::c_int; - pub fn sched_setscheduler(pid: ::pid_t, - policy: ::c_int, - param: *const ::sched_param) -> ::c_int; - pub fn sched_getscheduler(pid: ::pid_t) -> ::c_int; - pub fn sched_get_priority_max(policy: ::c_int) -> ::c_int; - pub fn sched_get_priority_min(policy: ::c_int) -> ::c_int; - pub fn epoll_create(size: ::c_int) -> ::c_int; - pub fn epoll_create1(flags: ::c_int) -> ::c_int; - pub fn epoll_ctl(epfd: ::c_int, - op: ::c_int, - fd: ::c_int, - event: *mut ::epoll_event) -> ::c_int; - pub fn epoll_wait(epfd: ::c_int, - events: *mut ::epoll_event, - maxevents: ::c_int, - timeout: ::c_int) -> ::c_int; - pub fn pipe2(fds: *mut ::c_int, flags: ::c_int) -> ::c_int; - pub fn mount(src: *const ::c_char, - target: *const ::c_char, - fstype: *const ::c_char, - flags: ::c_ulong, - data: *const ::c_void) -> ::c_int; - pub fn umount(target: *const ::c_char) -> ::c_int; - pub fn umount2(target: *const ::c_char, flags: ::c_int) -> ::c_int; - pub fn clone(cb: extern fn(*mut ::c_void) -> ::c_int, - child_stack: *mut ::c_void, - flags: ::c_int, - arg: *mut ::c_void, ...) -> ::c_int; - pub fn statfs(path: *const ::c_char, buf: *mut statfs) -> ::c_int; - pub fn fstatfs(fd: ::c_int, buf: *mut statfs) -> ::c_int; - pub fn memrchr(cx: *const ::c_void, - c: ::c_int, - n: ::size_t) -> *mut ::c_void; - pub fn syscall(num: ::c_long, ...) -> ::c_long; - pub fn sendfile(out_fd: ::c_int, - in_fd: ::c_int, - offset: *mut off_t, - count: ::size_t) -> ::ssize_t; - pub fn splice(fd_in: ::c_int, - off_in: *mut ::loff_t, - fd_out: ::c_int, - off_out: *mut ::loff_t, - len: ::size_t, - flags: ::c_uint) -> ::ssize_t; - pub fn tee(fd_in: ::c_int, - fd_out: ::c_int, - len: ::size_t, - flags: ::c_uint) -> ::ssize_t; - pub fn vmsplice(fd: ::c_int, - iov: *const ::iovec, - nr_segs: ::size_t, - flags: ::c_uint) -> ::ssize_t; - - pub fn posix_fadvise(fd: ::c_int, offset: ::off_t, len: ::off_t, - advise: ::c_int) -> ::c_int; - pub fn futimens(fd: ::c_int, times: *const ::timespec) -> ::c_int; - pub fn utimensat(dirfd: ::c_int, path: *const ::c_char, - times: *const ::timespec, flag: ::c_int) -> ::c_int; - pub fn duplocale(base: ::locale_t) -> ::locale_t; - pub fn freelocale(loc: ::locale_t); - pub fn newlocale(mask: ::c_int, - locale: *const ::c_char, - base: ::locale_t) -> ::locale_t; - pub fn uselocale(loc: ::locale_t) -> ::locale_t; - pub fn creat64(path: *const c_char, mode: mode_t) -> ::c_int; - pub fn fstat64(fildes: ::c_int, buf: *mut stat64) -> ::c_int; - pub fn ftruncate64(fd: ::c_int, length: off64_t) -> ::c_int; - pub fn getrlimit64(resource: ::c_int, rlim: *mut rlimit64) -> ::c_int; - pub fn lseek64(fd: ::c_int, offset: off64_t, whence: ::c_int) -> off64_t; - pub fn lstat64(path: *const c_char, buf: *mut stat64) -> ::c_int; - pub fn mmap64(addr: *mut ::c_void, - len: ::size_t, - prot: ::c_int, - flags: ::c_int, - fd: ::c_int, - offset: off64_t) - -> *mut ::c_void; - pub fn open64(path: *const c_char, oflag: ::c_int, ...) -> ::c_int; - pub fn openat64(fd: ::c_int, - path: *const c_char, - oflag: ::c_int, ...) -> ::c_int; - pub fn pread64(fd: ::c_int, buf: *mut ::c_void, count: ::size_t, - offset: off64_t) -> ::ssize_t; - pub fn pwrite64(fd: ::c_int, buf: *const ::c_void, count: ::size_t, - offset: off64_t) -> ::ssize_t; - pub fn readdir64(dirp: *mut ::DIR) -> *mut ::dirent64; - pub fn readdir64_r(dirp: *mut ::DIR, entry: *mut ::dirent64, - result: *mut *mut ::dirent64) -> ::c_int; - pub fn setrlimit64(resource: ::c_int, rlim: *const rlimit64) -> ::c_int; - pub fn stat64(path: *const c_char, buf: *mut stat64) -> ::c_int; - pub fn truncate64(path: *const c_char, length: off64_t) -> ::c_int; - pub fn eventfd(init: ::c_uint, flags: ::c_int) -> ::c_int; - - pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; - - pub fn mknodat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t, dev: dev_t) -> ::c_int; - pub fn ppoll(fds: *mut ::pollfd, - nfds: nfds_t, - timeout: *const ::timespec, - sigmask: *const sigset_t) -> ::c_int; - pub fn pthread_condattr_getclock(attr: *const pthread_condattr_t, - clock_id: *mut clockid_t) -> ::c_int; - pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, - clock_id: ::clockid_t) -> ::c_int; - pub fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, - pshared: ::c_int) -> ::c_int; - pub fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, - pshared: *mut ::c_int) -> ::c_int; - pub fn sched_getaffinity(pid: ::pid_t, - cpusetsize: ::size_t, - cpuset: *mut cpu_set_t) -> ::c_int; - pub fn sched_setaffinity(pid: ::pid_t, - cpusetsize: ::size_t, - cpuset: *const cpu_set_t) -> ::c_int; - pub fn unshare(flags: ::c_int) -> ::c_int; - pub fn sem_timedwait(sem: *mut sem_t, - abstime: *const ::timespec) -> ::c_int; - pub fn accept4(fd: ::c_int, addr: *mut ::sockaddr, len: *mut ::socklen_t, - flg: ::c_int) -> ::c_int; - pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, - abstime: *const ::timespec) -> ::c_int; - pub fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, - pshared: ::c_int) -> ::c_int; - pub fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, - pshared: *mut ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_getkind_np(attr: *const pthread_rwlockattr_t, - val: *mut ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_setkind_np(attr: *mut pthread_rwlockattr_t, - val: ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, - val: *mut ::c_int) -> ::c_int; - pub fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, - val: ::c_int) -> ::c_int; - pub fn ptsname_r(fd: ::c_int, - buf: *mut ::c_char, - buflen: ::size_t) -> ::c_int; - pub fn clearenv() -> ::c_int; - pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, - options: ::c_int) -> ::c_int; - - pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; - - pub fn setpwent(); - pub fn endpwent(); - pub fn getpwent() -> *mut passwd; - pub fn setspent(); - pub fn endspent(); - pub fn getspent() -> *mut spwd; - pub fn getspnam(__name: *const ::c_char) -> *mut spwd; - - pub fn shm_open(name: *const c_char, oflag: ::c_int, - mode: mode_t) -> ::c_int; - - // System V IPC - pub fn shmget(key: ::key_t, size: ::size_t, shmflg: ::c_int) -> ::c_int; - pub fn shmat(shmid: ::c_int, - shmaddr: *const ::c_void, - shmflg: ::c_int) -> *mut ::c_void; - pub fn shmdt(shmaddr: *const ::c_void) -> ::c_int; - pub fn shmctl(shmid: ::c_int, - cmd: ::c_int, - buf: *mut ::shmid_ds) -> ::c_int; - pub fn ftok(pathname: *const ::c_char, proj_id: ::c_int) -> ::key_t; - pub fn msgctl(msqid: ::c_int, cmd: ::c_int, buf: *mut msqid_ds) -> ::c_int; - pub fn msgget(key: ::key_t, msgflg: ::c_int) -> ::c_int; - pub fn msgrcv(msqid: ::c_int, msgp: *mut ::c_void, msgsz: ::size_t, - msgtyp: ::c_long, msgflg: ::c_int) -> ::ssize_t; - pub fn msgsnd(msqid: ::c_int, msgp: *const ::c_void, msgsz: ::size_t, - msgflg: ::c_int) -> ::c_int; - - pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) - -> ::c_int; - pub fn __errno_location() -> *mut ::c_int; - - pub fn fopen64(filename: *const c_char, - mode: *const c_char) -> *mut ::FILE; - pub fn freopen64(filename: *const c_char, mode: *const c_char, - file: *mut ::FILE) -> *mut ::FILE; - pub fn tmpfile64() -> *mut ::FILE; - pub fn fgetpos64(stream: *mut ::FILE, ptr: *mut fpos64_t) -> ::c_int; - pub fn fsetpos64(stream: *mut ::FILE, ptr: *const fpos64_t) -> ::c_int; - pub fn fseeko64(stream: *mut ::FILE, - offset: ::off64_t, - whence: ::c_int) -> ::c_int; - pub fn ftello64(stream: *mut ::FILE) -> ::off64_t; - pub fn readahead(fd: ::c_int, offset: ::off64_t, - count: ::size_t) -> ::ssize_t; - pub fn getxattr(path: *const c_char, name: *const c_char, - value: *mut ::c_void, size: ::size_t) -> ::ssize_t; - pub fn lgetxattr(path: *const c_char, name: *const c_char, - value: *mut ::c_void, size: ::size_t) -> ::ssize_t; - pub fn fgetxattr(filedes: ::c_int, name: *const c_char, - value: *mut ::c_void, size: ::size_t) -> ::ssize_t; - pub fn setxattr(path: *const c_char, name: *const c_char, - value: *const ::c_void, size: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn lsetxattr(path: *const c_char, name: *const c_char, - value: *const ::c_void, size: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn fsetxattr(filedes: ::c_int, name: *const c_char, - value: *const ::c_void, size: ::size_t, - flags: ::c_int) -> ::c_int; - pub fn listxattr(path: *const c_char, list: *mut c_char, - size: ::size_t) -> ::ssize_t; - pub fn llistxattr(path: *const c_char, list: *mut c_char, - size: ::size_t) -> ::ssize_t; - pub fn flistxattr(filedes: ::c_int, list: *mut c_char, - size: ::size_t) -> ::ssize_t; - pub fn removexattr(path: *const c_char, name: *const c_char) -> ::c_int; - pub fn lremovexattr(path: *const c_char, name: *const c_char) -> ::c_int; - pub fn fremovexattr(filedes: ::c_int, name: *const c_char) -> ::c_int; - pub fn signalfd(fd: ::c_int, - mask: *const ::sigset_t, - flags: ::c_int) -> ::c_int; - pub fn quotactl(cmd: ::c_int, - special: *const ::c_char, - id: ::c_int, - data: *mut ::c_char) -> ::c_int; - pub fn mq_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::mqd_t; - pub fn mq_close(mqd: ::mqd_t) -> ::c_int; - pub fn mq_unlink(name: *const ::c_char) -> ::c_int; - pub fn mq_receive(mqd: ::mqd_t, - msg_ptr: *mut ::c_char, - msg_len: ::size_t, - msq_prio: *mut ::c_uint) -> ::ssize_t; - pub fn mq_send(mqd: ::mqd_t, - msg_ptr: *const ::c_char, - msg_len: ::size_t, - msq_prio: ::c_uint) -> ::c_int; - pub fn mq_getattr(mqd: ::mqd_t, attr: *mut ::mq_attr) -> ::c_int; - pub fn mq_setattr(mqd: ::mqd_t, - newattr: *const ::mq_attr, - oldattr: *mut ::mq_attr) -> ::c_int; - pub fn epoll_pwait(epfd: ::c_int, - events: *mut ::epoll_event, - maxevents: ::c_int, - timeout: ::c_int, - sigmask: *const ::sigset_t) -> ::c_int; - pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; - pub fn sigtimedwait(set: *const sigset_t, - info: *mut siginfo_t, - timeout: *const ::timespec) -> ::c_int; - pub fn sigwaitinfo(set: *const sigset_t, - info: *mut siginfo_t) -> ::c_int; - pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; - pub fn prlimit(pid: ::pid_t, resource: ::c_int, new_limit: *const ::rlimit, - old_limit: *mut ::rlimit) -> ::c_int; - pub fn prlimit64(pid: ::pid_t, - resource: ::c_int, - new_limit: *const ::rlimit64, - old_limit: *mut ::rlimit64) -> ::c_int; - pub fn reboot(how_to: ::c_int) -> ::c_int; - pub fn setfsgid(gid: ::gid_t) -> ::c_int; - pub fn setfsuid(uid: ::uid_t) -> ::c_int; - pub fn setresgid(rgid: ::gid_t, egid: ::gid_t, sgid: ::gid_t) -> ::c_int; - pub fn setresuid(ruid: ::uid_t, euid: ::uid_t, suid: ::uid_t) -> ::c_int; - - // Not available now on Android - pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, - mode: ::mode_t) -> ::c_int; - pub fn if_nameindex() -> *mut if_nameindex; - pub fn if_freenameindex(ptr: *mut if_nameindex); - pub fn sync_file_range(fd: ::c_int, offset: ::off64_t, - nbytes: ::off64_t, flags: ::c_uint) -> ::c_int; - pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; - pub fn freeifaddrs(ifa: *mut ::ifaddrs); - - pub fn mremap(addr: *mut ::c_void, - len: ::size_t, - new_len: ::size_t, - flags: ::c_int, - ...) -> *mut ::c_void; - - pub fn glob(pattern: *const c_char, - flags: ::c_int, - errfunc: Option ::c_int>, - pglob: *mut ::glob_t) -> ::c_int; - pub fn globfree(pglob: *mut ::glob_t); - - pub fn shm_unlink(name: *const ::c_char) -> ::c_int; - - pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); - - pub fn telldir(dirp: *mut ::DIR) -> ::c_long; - pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) - -> ::c_int; - - pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; - - pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, - flags: ::c_int, addr: *mut ::sockaddr, - addrlen: *mut ::socklen_t) -> ::ssize_t; - pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; - - pub fn bind(socket: ::c_int, address: *const ::sockaddr, - address_len: ::socklen_t) -> ::c_int; - - pub fn writev(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - pub fn readv(fd: ::c_int, - iov: *const ::iovec, - iovcnt: ::c_int) -> ::ssize_t; - - pub fn sendmsg(fd: ::c_int, - msg: *const ::msghdr, - flags: ::c_int) -> ::ssize_t; - pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) - -> ::ssize_t; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] - pub fn getgrgid_r(uid: ::uid_t, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "sigaltstack$UNIX2003")] - #[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")] - pub fn sigaltstack(ss: *const stack_t, - oss: *mut stack_t) -> ::c_int; - pub fn sem_close(sem: *mut sem_t) -> ::c_int; - pub fn getdtablesize() -> ::c_int; - #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] - pub fn getgrnam_r(name: *const ::c_char, - grp: *mut ::group, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut ::group) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "pthread_sigmask$UNIX2003")] - pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, - oldset: *mut sigset_t) -> ::c_int; - pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; - pub fn getgrnam(name: *const ::c_char) -> *mut ::group; - pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; - pub fn sem_unlink(name: *const ::c_char) -> ::c_int; - pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] - pub fn getpwnam_r(name: *const ::c_char, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] - pub fn getpwuid_r(uid: ::uid_t, - pwd: *mut passwd, - buf: *mut ::c_char, - buflen: ::size_t, - result: *mut *mut passwd) -> ::c_int; - #[cfg_attr(all(target_os = "macos", target_arch ="x86"), - link_name = "sigwait$UNIX2003")] - #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] - pub fn sigwait(set: *const sigset_t, - sig: *mut ::c_int) -> ::c_int; - pub fn pthread_atfork(prepare: Option, - parent: Option, - child: Option) -> ::c_int; - pub fn pthread_create(native: *mut ::pthread_t, - attr: *const ::pthread_attr_t, - f: extern fn(*mut ::c_void) -> *mut ::c_void, - value: *mut ::c_void) -> ::c_int; - pub fn getgrgid(gid: ::gid_t) -> *mut ::group; - #[cfg_attr(all(target_os = "macos", target_arch = "x86"), - link_name = "popen$UNIX2003")] - pub fn popen(command: *const c_char, - mode: *const c_char) -> *mut ::FILE; -} - -cfg_if! { - if #[cfg(target_arch = "mips")] { - mod mips; - pub use self::mips::*; - } else if #[cfg(target_arch = "x86_64")] { - mod x86_64; - pub use self::x86_64::*; - } else { - pub use unsupported_target; - } -} - diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/uclibc/x86_64/l4re.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/uclibc/x86_64/l4re.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/uclibc/x86_64/l4re.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/uclibc/x86_64/l4re.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -/// L4Re specifics -/// This module contains definitions required by various L4Re libc backends. -/// Some of them are formally not part of the libc, but are a dependency of the -/// libc and hence we should provide them here. - -pub type l4_umword_t = ::c_ulong; // Unsigned machine word. - -s! { - /// CPU sets. - pub struct l4_sched_cpu_set_t { - // from the L4Re docs - /// Combination of granularity and offset. - /// - /// The granularity defines how many CPUs each bit in map describes. - /// The offset is the numer of the first CPU described by the first - /// bit in the bitmap. - /// offset must be a multiple of 2^graularity. - /// - /// | MSB | LSB | - /// | ---------------- | ------------------- | - /// | 8bit granularity | 24bit offset .. | - gran_offset: l4_umword_t , - /// Bitmap of CPUs. - map: l4_umword_t , - } -} - -#[cfg(target_os = "l4re")] -pub struct pthread_attr_t { - pub __detachstate: ::c_int, - pub __schedpolicy: ::c_int, - pub __schedparam: super::__sched_param, - pub __inheritsched: ::c_int, - pub __scope: ::c_int, - pub __guardsize: ::size_t, - pub __stackaddr_set: ::c_int, - pub __stackaddr: *mut ::c_void, // better don't use it - pub __stacksize: ::size_t, - // L4Re specifics - pub affinity: l4_sched_cpu_set_t, - pub create_flags: ::c_uint, -} - -// L4Re requires a min stack size of 64k; that isn't defined in uClibc, but -// somewhere in the core libraries. uClibc wants 16k, but that's not enough. -pub const PTHREAD_STACK_MIN: usize = 65536; diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/unix/uclibc/x86_64/mod.rs cargo-0.26.0/vendor/libc-0.2.36/src/unix/uclibc/x86_64/mod.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/unix/uclibc/x86_64/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/unix/uclibc/x86_64/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,357 +0,0 @@ -//! Definitions for uclibc on 64bit systems -//! -pub type blkcnt_t = i64; -pub type blksize_t = i64; -pub type clock_t = i64; -pub type c_char = u8; -pub type c_long = i64; -pub type c_ulong = u64; -pub type fsblkcnt_t = ::c_ulong; -pub type fsfilcnt_t = ::c_ulong; -pub type fsword_t = ::c_long; -pub type ino_t = ::c_ulong; -pub type nlink_t = ::c_uint; -pub type off_t = ::c_long; -pub type rlim_t = c_ulong; -pub type rlim64_t = u64; -// [uClibc docs] Note stat64 has the same shape as stat for x86-64. -pub type stat64 = stat; -pub type suseconds_t = ::c_long; -pub type time_t = ::c_int; -pub type wchar_t = ::c_int; - -pub type nfds_t = ::c_ulong; - -s! { - pub struct dirent { - pub d_ino: ::ino64_t, - pub d_off: ::off64_t, - pub d_reclen: u16, - pub d_type: u8, - pub d_name: [::c_char; 256], - } - - pub struct dirent64 { - pub d_ino: ::ino64_t, - pub d_off: ::off64_t, - pub d_reclen: u16, - pub d_type: u8, - pub d_name: [::c_char; 256], - } - - pub struct ipc_perm { - pub __key: ::key_t, - pub uid: ::uid_t, - pub gid: ::gid_t, - pub cuid: ::uid_t, - pub cgid: ::gid_t, - pub mode: ::c_ushort, // read / write - __pad1: ::c_ushort, - pub __seq: ::c_ushort, - __pad2: ::c_ushort, - __unused1: ::c_ulong, - __unused2: ::c_ulong - } - - #[cfg(not(target_os = "l4re"))] - pub struct pthread_attr_t { - __detachstate: ::c_int, - __schedpolicy: ::c_int, - __schedparam: __sched_param, - __inheritsched: ::c_int, - __scope: ::c_int, - __guardsize: ::size_t, - __stackaddr_set: ::c_int, - __stackaddr: *mut ::c_void, // better don't use it - __stacksize: ::size_t, - } - - pub struct __sched_param { - __sched_priority: ::c_int, - } - - pub struct siginfo_t { - si_signo: ::c_int, // signal number - si_errno: ::c_int, // if not zero: error value of signal, see errno.h - si_code: ::c_int, // signal code - pub _pad: [::c_int; 28], // unported union - _align: [usize; 0], - } - - pub struct shmid_ds { - pub shm_perm: ::ipc_perm, - pub shm_segsz: ::size_t, // segment size in bytes - pub shm_atime: ::time_t, // time of last shmat() - pub shm_dtime: ::time_t, - pub shm_ctime: ::time_t, - pub shm_cpid: ::pid_t, - pub shm_lpid: ::pid_t, - pub shm_nattch: ::shmatt_t, - __unused1: ::c_ulong, - __unused2: ::c_ulong - } - - pub struct msqid_ds { - pub msg_perm: ::ipc_perm, - pub msg_stime: ::time_t, - pub msg_rtime: ::time_t, - pub msg_ctime: ::time_t, - __msg_cbytes: ::c_ulong, - pub msg_qnum: ::msgqnum_t, - pub msg_qbytes: ::msglen_t, - pub msg_lspid: ::pid_t, - pub msg_lrpid: ::pid_t, - __ignored1: ::c_ulong, - __ignored2: ::c_ulong, - } - - pub struct sockaddr { - pub sa_family: ::sa_family_t, - pub sa_data: [::c_char; 14], - } - - pub struct sockaddr_in { - pub sin_family: ::sa_family_t, - pub sin_port: ::in_port_t, - pub sin_addr: ::in_addr, - pub sin_zero: [u8; 8], - } - - pub struct sockaddr_in6 { - pub sin6_family: ::sa_family_t, - pub sin6_port: ::in_port_t, - pub sin6_flowinfo: u32, - pub sin6_addr: ::in6_addr, - pub sin6_scope_id: u32, - } - - // ------------------------------------------------------------ - // definitions below are *unverified* and might **break** the software -// pub struct in_addr { -// pub s_addr: in_addr_t, -// } -// -// pub struct in6_addr { -// pub s6_addr: [u8; 16], -// __align: [u32; 0], -// } - - pub struct stat { - pub st_dev: ::c_ulong, - pub st_ino: ::ino_t, - // According to uclibc/libc/sysdeps/linux/x86_64/bits/stat.h, order of - // nlink and mode are swapped on 64 bit systems. - pub st_nlink: ::nlink_t, - pub st_mode: ::mode_t, - pub st_uid: ::uid_t, - pub st_gid: ::gid_t, - pub st_rdev: ::c_ulong, // dev_t - pub st_size: off_t, // file size - pub st_blksize: ::blksize_t, - pub st_blocks: ::blkcnt_t, - pub st_atime: ::time_t, - pub st_atime_nsec: ::c_ulong, - pub st_mtime: ::time_t, - pub st_mtime_nsec: ::c_ulong, - pub st_ctime: ::time_t, - pub st_ctime_nsec: ::c_ulong, - st_pad4: [::c_long; 3] - } - - pub struct sigaction { - pub sa_handler: ::sighandler_t, - pub sa_flags: ::c_ulong, - pub sa_restorer: *mut ::c_void, - pub sa_mask: ::sigset_t, - } - - pub struct stack_t { // ToDo - pub ss_sp: *mut ::c_void, - pub ss_flags: ::c_int, - pub ss_size: ::size_t - } - - pub struct statfs { // ToDo - pub f_type: fsword_t, - pub f_bsize: fsword_t, - pub f_blocks: ::fsblkcnt_t, - pub f_bfree: ::fsblkcnt_t, - pub f_bavail: ::fsblkcnt_t, - pub f_files: ::fsfilcnt_t, - pub f_ffree: ::fsfilcnt_t, - pub f_fsid: ::fsid_t, - pub f_namelen: fsword_t, - pub f_frsize: fsword_t, - f_spare: [fsword_t; 5], - } - - pub struct msghdr { // ToDo - pub msg_name: *mut ::c_void, - pub msg_namelen: ::socklen_t, - pub msg_iov: *mut ::iovec, - pub msg_iovlen: ::size_t, - pub msg_control: *mut ::c_void, - pub msg_controllen: ::size_t, - pub msg_flags: ::c_int, - } - - pub struct termios { // ToDo - pub c_iflag: ::tcflag_t, - pub c_oflag: ::tcflag_t, - pub c_cflag: ::tcflag_t, - pub c_lflag: ::tcflag_t, - pub c_line: ::cc_t, - pub c_cc: [::cc_t; ::NCCS], - } - - pub struct sem_t { // ToDo - #[cfg(target_pointer_width = "32")] - __size: [::c_char; 16], - #[cfg(target_pointer_width = "64")] - __size: [::c_char; 32], - __align: [::c_long; 0], - } - - pub struct pthread_mutex_t { // ToDo - #[cfg(any(target_arch = "mips", target_arch = "arm", - target_arch = "powerpc"))] - __align: [::c_long; 0], - #[cfg(not(any(target_arch = "mips", target_arch = "arm", - target_arch = "powerpc")))] - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_MUTEX_T], - } - - pub struct pthread_mutexattr_t { // ToDo - #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", - target_arch = "mips64", target_arch = "s390x", - target_arch = "sparc64"))] - __align: [::c_int; 0], - #[cfg(not(any(target_arch = "x86_64", target_arch = "powerpc64", - target_arch = "mips64", target_arch = "s390x", - target_arch = "sparc64")))] - __align: [::c_long; 0], - size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T], - } - - pub struct pthread_cond_t { // ToDo - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_COND_T], - } - - pub struct pthread_condattr_t { // ToDo - __align: [::c_int; 0], - size: [u8; __SIZEOF_PTHREAD_CONDATTR_T], - } - - pub struct pthread_rwlock_t { // ToDo - #[cfg(any(target_arch = "mips", target_arch = "arm", - target_arch = "powerpc"))] - __align: [::c_long; 0], - #[cfg(not(any(target_arch = "mips", target_arch = "arm", - target_arch = "powerpc")))] - __align: [::c_longlong; 0], - size: [u8; __SIZEOF_PTHREAD_RWLOCK_T], - } - - pub struct sigset_t { // ToDo - __val: [::c_ulong; 16], - } - - pub struct sysinfo { // ToDo - pub uptime: ::c_long, - pub loads: [::c_ulong; 3], - pub totalram: ::c_ulong, - pub freeram: ::c_ulong, - pub sharedram: ::c_ulong, - pub bufferram: ::c_ulong, - pub totalswap: ::c_ulong, - pub freeswap: ::c_ulong, - pub procs: ::c_ushort, - pub pad: ::c_ushort, - pub totalhigh: ::c_ulong, - pub freehigh: ::c_ulong, - pub mem_unit: ::c_uint, - pub _f: [::c_char; 0], - } - - pub struct glob_t { // ToDo - pub gl_pathc: ::size_t, - pub gl_pathv: *mut *mut c_char, - pub gl_offs: ::size_t, - pub gl_flags: ::c_int, - __unused1: *mut ::c_void, - __unused2: *mut ::c_void, - __unused3: *mut ::c_void, - __unused4: *mut ::c_void, - __unused5: *mut ::c_void, - } - - pub struct rlimit64 { // ToDo - pub rlim_cur: rlim64_t, - pub rlim_max: rlim64_t, - } - - pub struct cpu_set_t { // ToDo - #[cfg(target_pointer_width = "32")] - bits: [u32; 32], - #[cfg(target_pointer_width = "64")] - bits: [u64; 16], - } - - pub struct fsid_t { // ToDo - __val: [::c_int; 2], - } -} - -// constants -pub const EADDRINUSE: ::c_int = 98; // Address already in use -pub const EADDRNOTAVAIL: ::c_int = 99; // Cannot assign requested address -pub const ECONNABORTED: ::c_int = 103; // Software caused connection abort -pub const ECONNREFUSED: ::c_int = 111; // Connection refused -pub const ECONNRESET: ::c_int = 104; // Connection reset by peer -pub const EDEADLK: ::c_int = 35; // Resource deadlock would occur -pub const ENOSYS: ::c_int = 38; // Function not implemented -pub const ENOTCONN: ::c_int = 107; // Transport endpoint is not connected -pub const ETIMEDOUT: ::c_int = 110; // connection timed out -pub const O_APPEND: ::c_int = 02000; -pub const O_ACCMODE: ::c_int = 0003; -pub const O_CLOEXEC: ::c_int = 0x80000; -pub const O_CREAT: ::c_int = 0100; -pub const O_DIRECTORY: ::c_int = 0200000; -pub const O_EXCL: ::c_int = 0200; -pub const O_NONBLOCK: ::c_int = 04000; -pub const O_TRUNC: ::c_int = 01000; -pub const NCCS: usize = 32; -pub const SIG_SETMASK: ::c_int = 2; // Set the set of blocked signals -pub const PTHREAD_STACK_MIN: usize = 16384; -pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; -pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; -pub const SO_BROADCAST: ::c_int = 6; -pub const SOCK_DGRAM: ::c_int = 2; // connectionless, unreliable datagrams -pub const SOCK_STREAM: ::c_int = 1; // …/common/bits/socket_type.h -pub const SO_ERROR: ::c_int = 4; -pub const SOL_SOCKET: ::c_int = 1; -pub const SO_RCVTIMEO: ::c_int = 20; -pub const SO_REUSEADDR: ::c_int = 2; -pub const SO_SNDTIMEO: ::c_int = 21; -pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; -pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; -pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; -pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; -pub const RLIM_INFINITY: u64 = 0xffffffffffffffff; -pub const __SIZEOF_PTHREAD_COND_T: usize = 48; -pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; -pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; - -extern { - pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; -} - -cfg_if! { - if #[cfg(target_os = "l4re")] { - mod l4re; - pub use self::l4re::*; - } else { } -} - diff -Nru cargo-0.25.0/vendor/libc-0.2.36/src/windows.rs cargo-0.26.0/vendor/libc-0.2.36/src/windows.rs --- cargo-0.25.0/vendor/libc-0.2.36/src/windows.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/src/windows.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,248 +0,0 @@ -//! Windows CRT definitions - -pub type c_char = i8; -pub type c_long = i32; -pub type c_ulong = u32; -pub type wchar_t = u16; - -pub type clock_t = i32; - -cfg_if! { - if #[cfg(all(target_arch = "x86", target_env = "gnu"))] { - pub type time_t = i32; - } else { - pub type time_t = i64; - } -} - -pub type off_t = i32; -pub type dev_t = u32; -pub type ino_t = u16; -pub enum timezone {} -pub type time64_t = i64; - -s! { - // note this is the struct called stat64 in Windows. Not stat, nor stati64. - pub struct stat { - pub st_dev: dev_t, - pub st_ino: ino_t, - pub st_mode: u16, - pub st_nlink: ::c_short, - pub st_uid: ::c_short, - pub st_gid: ::c_short, - pub st_rdev: dev_t, - pub st_size: i64, - pub st_atime: time64_t, - pub st_mtime: time64_t, - pub st_ctime: time64_t, - } - - // note that this is called utimbuf64 in Windows - pub struct utimbuf { - pub actime: time64_t, - pub modtime: time64_t, - } - - pub struct tm { - tm_sec: ::c_int, - tm_min: ::c_int, - tm_hour: ::c_int, - tm_mday: ::c_int, - tm_mon: ::c_int, - tm_year: ::c_int, - tm_wday: ::c_int, - tm_yday: ::c_int, - tm_isdst: ::c_int, - } - - pub struct timeval { - pub tv_sec: c_long, - pub tv_usec: c_long, - } - - pub struct timespec { - pub tv_sec: time_t, - pub tv_nsec: c_long, - } -} - -pub const EXIT_FAILURE: ::c_int = 1; -pub const EXIT_SUCCESS: ::c_int = 0; -pub const RAND_MAX: ::c_int = 32767; -pub const EOF: ::c_int = -1; -pub const SEEK_SET: ::c_int = 0; -pub const SEEK_CUR: ::c_int = 1; -pub const SEEK_END: ::c_int = 2; -pub const _IOFBF: ::c_int = 0; -pub const _IONBF: ::c_int = 4; -pub const _IOLBF: ::c_int = 64; -pub const BUFSIZ: ::c_uint = 512; -pub const FOPEN_MAX: ::c_uint = 20; -pub const FILENAME_MAX: ::c_uint = 260; - -cfg_if! { - if #[cfg(all(target_env = "gnu"))] { - pub const L_tmpnam: ::c_uint = 14; - pub const TMP_MAX: ::c_uint = 0x7fff; - } else if #[cfg(all(target_env = "msvc"))] { - pub const L_tmpnam: ::c_uint = 260; - pub const TMP_MAX: ::c_uint = 0x7fff_ffff; - } else { - // Unknown target_env - } -} - -pub const O_RDONLY: ::c_int = 0; -pub const O_WRONLY: ::c_int = 1; -pub const O_RDWR: ::c_int = 2; -pub const O_APPEND: ::c_int = 8; -pub const O_CREAT: ::c_int = 256; -pub const O_EXCL: ::c_int = 1024; -pub const O_TEXT: ::c_int = 16384; -pub const O_BINARY: ::c_int = 32768; -pub const O_NOINHERIT: ::c_int = 128; -pub const O_TRUNC: ::c_int = 512; -pub const S_IFCHR: ::c_int = 8192; -pub const S_IFDIR: ::c_int = 16384; -pub const S_IFREG: ::c_int = 32768; -pub const S_IFMT: ::c_int = 61440; -pub const S_IEXEC: ::c_int = 64; -pub const S_IWRITE: ::c_int = 128; -pub const S_IREAD: ::c_int = 256; - -pub const LC_ALL: ::c_int = 0; -pub const LC_COLLATE: ::c_int = 1; -pub const LC_CTYPE: ::c_int = 2; -pub const LC_MONETARY: ::c_int = 3; -pub const LC_NUMERIC: ::c_int = 4; -pub const LC_TIME: ::c_int = 5; - -pub const EPERM: ::c_int = 1; -pub const ENOENT: ::c_int = 2; -pub const ESRCH: ::c_int = 3; -pub const EINTR: ::c_int = 4; -pub const EIO: ::c_int = 5; -pub const ENXIO: ::c_int = 6; -pub const E2BIG: ::c_int = 7; -pub const ENOEXEC: ::c_int = 8; -pub const EBADF: ::c_int = 9; -pub const ECHILD: ::c_int = 10; -pub const EAGAIN: ::c_int = 11; -pub const ENOMEM: ::c_int = 12; -pub const EACCES: ::c_int = 13; -pub const EFAULT: ::c_int = 14; -pub const EBUSY: ::c_int = 16; -pub const EEXIST: ::c_int = 17; -pub const EXDEV: ::c_int = 18; -pub const ENODEV: ::c_int = 19; -pub const ENOTDIR: ::c_int = 20; -pub const EISDIR: ::c_int = 21; -pub const EINVAL: ::c_int = 22; -pub const ENFILE: ::c_int = 23; -pub const EMFILE: ::c_int = 24; -pub const ENOTTY: ::c_int = 25; -pub const EFBIG: ::c_int = 27; -pub const ENOSPC: ::c_int = 28; -pub const ESPIPE: ::c_int = 29; -pub const EROFS: ::c_int = 30; -pub const EMLINK: ::c_int = 31; -pub const EPIPE: ::c_int = 32; -pub const EDOM: ::c_int = 33; -pub const ERANGE: ::c_int = 34; -pub const EDEADLK: ::c_int = 36; -pub const EDEADLOCK: ::c_int = 36; -pub const ENAMETOOLONG: ::c_int = 38; -pub const ENOLCK: ::c_int = 39; -pub const ENOSYS: ::c_int = 40; -pub const ENOTEMPTY: ::c_int = 41; -pub const EILSEQ: ::c_int = 42; -pub const STRUNCATE: ::c_int = 80; - -// inline comment below appeases style checker -#[cfg(all(target_env = "msvc", feature = "stdbuild"))] // " if " -#[link(name = "msvcrt", cfg(not(target_feature = "crt-static")))] -#[link(name = "libcmt", cfg(target_feature = "crt-static"))] -extern {} - -extern { - #[link_name = "_chmod"] - pub fn chmod(path: *const c_char, mode: ::c_int) -> ::c_int; - #[link_name = "_wchmod"] - pub fn wchmod(path: *const wchar_t, mode: ::c_int) -> ::c_int; - #[link_name = "_mkdir"] - pub fn mkdir(path: *const c_char) -> ::c_int; - #[link_name = "_wrmdir"] - pub fn wrmdir(path: *const wchar_t) -> ::c_int; - #[link_name = "_fstat64"] - pub fn fstat(fildes: ::c_int, buf: *mut stat) -> ::c_int; - #[link_name = "_stat64"] - pub fn stat(path: *const c_char, buf: *mut stat) -> ::c_int; - #[link_name = "_wstat64"] - pub fn wstat(path: *const wchar_t, buf: *mut stat) -> ::c_int; - #[link_name = "_wutime64"] - pub fn wutime(file: *const wchar_t, buf: *mut utimbuf) -> ::c_int; - #[link_name = "_popen"] - pub fn popen(command: *const c_char, mode: *const c_char) -> *mut ::FILE; - #[link_name = "_pclose"] - pub fn pclose(stream: *mut ::FILE) -> ::c_int; - #[link_name = "_fdopen"] - pub fn fdopen(fd: ::c_int, mode: *const c_char) -> *mut ::FILE; - #[link_name = "_fileno"] - pub fn fileno(stream: *mut ::FILE) -> ::c_int; - #[link_name = "_open"] - pub fn open(path: *const c_char, oflag: ::c_int, ...) -> ::c_int; - #[link_name = "_wopen"] - pub fn wopen(path: *const wchar_t, oflag: ::c_int, ...) -> ::c_int; - #[link_name = "_creat"] - pub fn creat(path: *const c_char, mode: ::c_int) -> ::c_int; - #[link_name = "_access"] - pub fn access(path: *const c_char, amode: ::c_int) -> ::c_int; - #[link_name = "_chdir"] - pub fn chdir(dir: *const c_char) -> ::c_int; - #[link_name = "_close"] - pub fn close(fd: ::c_int) -> ::c_int; - #[link_name = "_dup"] - pub fn dup(fd: ::c_int) -> ::c_int; - #[link_name = "_dup2"] - pub fn dup2(src: ::c_int, dst: ::c_int) -> ::c_int; - #[link_name = "_execv"] - pub fn execv(prog: *const c_char, argv: *const *const c_char) -> ::intptr_t; - #[link_name = "_execve"] - pub fn execve(prog: *const c_char, argv: *const *const c_char, - envp: *const *const c_char) -> ::c_int; - #[link_name = "_execvp"] - pub fn execvp(c: *const c_char, argv: *const *const c_char) -> ::c_int; - #[link_name = "_execvpe"] - pub fn execvpe(c: *const c_char, argv: *const *const c_char, - envp: *const *const c_char) -> ::c_int; - #[link_name = "_getcwd"] - pub fn getcwd(buf: *mut c_char, size: ::c_int) -> *mut c_char; - #[link_name = "_getpid"] - pub fn getpid() -> ::c_int; - #[link_name = "_isatty"] - pub fn isatty(fd: ::c_int) -> ::c_int; - #[link_name = "_lseek"] - pub fn lseek(fd: ::c_int, offset: c_long, origin: ::c_int) -> c_long; - #[link_name = "_pipe"] - pub fn pipe(fds: *mut ::c_int, - psize: ::c_uint, - textmode: ::c_int) -> ::c_int; - #[link_name = "_read"] - pub fn read(fd: ::c_int, buf: *mut ::c_void, count: ::c_uint) -> ::c_int; - #[link_name = "_rmdir"] - pub fn rmdir(path: *const c_char) -> ::c_int; - #[link_name = "_unlink"] - pub fn unlink(c: *const c_char) -> ::c_int; - #[link_name = "_write"] - pub fn write(fd: ::c_int, buf: *const ::c_void, count: ::c_uint) -> ::c_int; - #[link_name = "_commit"] - pub fn commit(fd: ::c_int) -> ::c_int; - #[link_name = "_get_osfhandle"] - pub fn get_osfhandle(fd: ::c_int) -> ::intptr_t; - #[link_name = "_open_osfhandle"] - pub fn open_osfhandle(osfhandle: ::intptr_t, flags: ::c_int) -> ::c_int; - pub fn setlocale(category: ::c_int, locale: *const c_char) -> *mut c_char; - #[link_name = "_wsetlocale"] - pub fn wsetlocale(category: ::c_int, - locale: *const wchar_t) -> *mut wchar_t; -} diff -Nru cargo-0.25.0/vendor/libc-0.2.36/.travis.yml cargo-0.26.0/vendor/libc-0.2.36/.travis.yml --- cargo-0.25.0/vendor/libc-0.2.36/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.36/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,113 +0,0 @@ -language: rust -rust: stable -sudo: required -dist: trusty -services: - - docker -install: - - if [ -z "$NO_ADD" ]; then rustup target add $TARGET; fi -script: - - cargo build $OPT - - cargo build $OPT --no-default-features - - cargo generate-lockfile --manifest-path libc-test/Cargo.toml - - if [[ $TRAVIS_OS_NAME = "linux" ]]; then - sh ci/run-docker.sh $TARGET; - else - export CARGO_TARGET_DIR=`pwd`/target; - sh ci/run.sh $TARGET; - fi - - rustc ci/style.rs && ./style src -env: - global: - secure: "e2/3QjgRN9atOuSHp22TrYG7QVKcYUWY48Hi9b60w+r1+BhPkTseIJLte7WefRhdXtqpjjUJTooKDhnurFOeHaCT+nmBgiv+FPU893sBl4bhesY4m0vgUJVbNZcs6lTImYekWVb+aqjGdgV/XAgCw7c3kPmrZV0MzGDWL64Xaps=" -matrix: - include: - # 1.0.0 compat - - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 - rust: 1.0.0 - script: rm -f Cargo.lock && cargo build - install: - - # build documentation - - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 - rust: nightly - script: sh ci/dox.sh - - # stable compat - - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 - - env: TARGET=i686-unknown-linux-gnu - - os: osx - env: TARGET=x86_64-apple-darwin NO_ADD=1 - osx_image: xcode8.3 - - os: osx - env: TARGET=i686-apple-darwin - osx_image: xcode8.3 - - env: TARGET=arm-linux-androideabi - - env: TARGET=aarch64-linux-android - # FIXME(#826) should reenable - #- env: TARGET=i686-linux-android - - env: TARGET=x86_64-linux-android - - env: TARGET=x86_64-unknown-linux-musl - - env: TARGET=i686-unknown-linux-musl - - env: TARGET=arm-unknown-linux-gnueabihf - - env: TARGET=arm-unknown-linux-musleabihf - - env: TARGET=aarch64-unknown-linux-gnu - - env: TARGET=aarch64-unknown-linux-musl - # FIXME(#856) - rust: 1.22.1 - - os: osx - osx_image: xcode8.2 - env: TARGET=i386-apple-ios - CARGO_TARGET_I386_APPLE_IOS_RUNNER=$HOME/runtest - RUSTFLAGS=-Clink-arg=-mios-simulator-version-min=7.0 - before_install: - rustc ./ci/ios/deploy_and_run_on_ios_simulator.rs -o $HOME/runtest - - os: osx - osx_image: xcode8.2 - env: TARGET=x86_64-apple-ios - CARGO_TARGET_X86_64_APPLE_IOS_RUNNER=$HOME/runtest - RUSTFLAGS=-Clink-arg=-mios-simulator-version-min=7.0 - before_install: - rustc ./ci/ios/deploy_and_run_on_ios_simulator.rs -o $HOME/runtest - - env: TARGET=x86_64-rumprun-netbsd - - env: TARGET=powerpc-unknown-linux-gnu - - env: TARGET=powerpc64-unknown-linux-gnu - - env: TARGET=powerpc64le-unknown-linux-gnu - - env: TARGET=mips-unknown-linux-musl - - env: TARGET=mipsel-unknown-linux-musl - - env: TARGET=mips64-unknown-linux-gnuabi64 - - env: TARGET=mips64el-unknown-linux-gnuabi64 - - env: TARGET=mips-unknown-linux-gnu - - env: TARGET=s390x-unknown-linux-gnu - - env: TARGET=sparc64-unknown-linux-gnu - - env: TARGET=asmjs-unknown-emscripten - - env: TARGET=wasm32-unknown-emscripten - - # beta - - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 - rust: beta - - os: osx - env: TARGET=x86_64-apple-darwin NO_ADD=1 - osx_image: xcode8.3 - rust: beta - - # nightly - - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 - rust: nightly - - os: osx - env: TARGET=x86_64-apple-darwin NO_ADD=1 - osx_image: xcode8.3 - rust: nightly - # not available on stable - # without --release the build fails - # see https://github.com/rust-lang/rust/issues/45417 - - env: TARGET=x86_64-unknown-linux-gnux32 OPT="--release" - rust: nightly - - # QEMU based targets that compile in an emulator - - env: TARGET=x86_64-unknown-freebsd - -notifications: - email: - on_success: never - webhooks: https://buildbot.rust-lang.org/homu/travis diff -Nru cargo-0.25.0/vendor/libc-0.2.40/appveyor.yml cargo-0.26.0/vendor/libc-0.2.40/appveyor.yml --- cargo-0.25.0/vendor/libc-0.2.40/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,28 @@ +environment: + # When this was added there were revocation check failures when using the + # libcurl backend as libcurl checks by default, but rustup doesn't provide the + # switch to turn this off. Switch to Hyper which looks to not check for + # revocation by default like libcurl does. + RUSTUP_USE_HYPER: 1 + CARGO_HTTP_CHECK_REVOKE: false + matrix: + - TARGET: x86_64-pc-windows-gnu + MSYS2_BITS: 64 + - TARGET: i686-pc-windows-gnu + MSYS2_BITS: 32 + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc +install: + - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe + - rustup-init.exe -y --default-host %TARGET% + - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin + - if defined MSYS2_BITS set PATH=%PATH%;C:\msys64\mingw%MSYS2_BITS%\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --target %TARGET% + - cargo test --no-default-features --target %TARGET% + - cargo test --manifest-path libc-test/Cargo.toml --target %TARGET% diff -Nru cargo-0.25.0/vendor/libc-0.2.40/.cargo-checksum.json cargo-0.26.0/vendor/libc-0.2.40/.cargo-checksum.json --- cargo-0.25.0/vendor/libc-0.2.40/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"6fd41f331ac7c5b8ac259b8bf82c75c0fb2e469bbf37d2becbba9a6a2221965b"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/libc-0.2.40/Cargo.toml cargo-0.26.0/vendor/libc-0.2.40/Cargo.toml --- cargo-0.25.0/vendor/libc-0.2.40/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,32 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "libc" +version = "0.2.40" +authors = ["The Rust Project Developers"] +description = "A library for types and bindings to native C functions often found in libc or\nother common platform libraries.\n" +homepage = "https://github.com/rust-lang/libc" +documentation = "http://doc.rust-lang.org/libc" +readme = "README.md" +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-lang/libc" + +[features] +default = ["use_std"] +use_std = [] +[badges.appveyor] +project_name = "rust-lang-libs/libc" +repository = "rust-lang/libc" + +[badges.travis-ci] +repository = "rust-lang/libc" diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/android-install-ndk.sh cargo-0.26.0/vendor/libc-0.2.40/ci/android-install-ndk.sh --- cargo-0.25.0/vendor/libc-0.2.40/ci/android-install-ndk.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/android-install-ndk.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,37 @@ +#!/bin/sh +# Copyright 2016 The Rust Project Developers. See the COPYRIGHT +# file at the top-level directory of this distribution and at +# http://rust-lang.org/COPYRIGHT. +# +# Licensed under the Apache License, Version 2.0 or the MIT license +# , at your +# option. This file may not be copied, modified, or distributed +# except according to those terms. + +set -ex + +curl -O https://dl.google.com/android/repository/android-ndk-r15b-linux-x86_64.zip +unzip -q android-ndk-r15b-linux-x86_64.zip + +case "$1" in + aarch64) + arch=arm64 + ;; + + i686) + arch=x86 + ;; + + *) + arch=$1 + ;; +esac; + +android-ndk-r15b/build/tools/make_standalone_toolchain.py \ + --unified-headers \ + --install-dir /android/ndk-$1 \ + --arch $arch \ + --api 24 + +rm -rf ./android-ndk-r15b-linux-x86_64.zip ./android-ndk-r15b diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/android-install-sdk.sh cargo-0.26.0/vendor/libc-0.2.40/ci/android-install-sdk.sh --- cargo-0.25.0/vendor/libc-0.2.40/ci/android-install-sdk.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/android-install-sdk.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,60 @@ +#!/bin/sh +# Copyright 2016 The Rust Project Developers. See the COPYRIGHT +# file at the top-level directory of this distribution and at +# http://rust-lang.org/COPYRIGHT. +# +# Licensed under the Apache License, Version 2.0 or the MIT license +# , at your +# option. This file may not be copied, modified, or distributed +# except according to those terms. + +set -ex + +# Prep the SDK and emulator +# +# Note that the update process requires that we accept a bunch of licenses, and +# we can't just pipe `yes` into it for some reason, so we take the same strategy +# located in https://github.com/appunite/docker by just wrapping it in a script +# which apparently magically accepts the licenses. + +mkdir sdk +curl https://dl.google.com/android/repository/sdk-tools-linux-3859397.zip -O +unzip -d sdk sdk-tools-linux-3859397.zip + +case "$1" in + arm | armv7) + abi=armeabi-v7a + ;; + + aarch64) + abi=arm64-v8a + ;; + + i686) + abi=x86 + ;; + + x86_64) + abi=x86_64 + ;; + + *) + echo "invalid arch: $1" + exit 1 + ;; +esac; + +# --no_https avoids +# javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found +echo "yes" | \ + ./sdk/tools/bin/sdkmanager --no_https \ + "emulator" \ + "platform-tools" \ + "platforms;android-24" \ + "system-images;android-24;default;$abi" + +echo "no" | + ./sdk/tools/bin/avdmanager create avd \ + --name $1 \ + --package "system-images;android-24;default;$abi" diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/android-sysimage.sh cargo-0.26.0/vendor/libc-0.2.40/ci/android-sysimage.sh --- cargo-0.25.0/vendor/libc-0.2.40/ci/android-sysimage.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/android-sysimage.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,52 @@ +# Copyright 2017 The Rust Project Developers. See the COPYRIGHT +# file at the top-level directory of this distribution and at +# http://rust-lang.org/COPYRIGHT. +# +# Licensed under the Apache License, Version 2.0 or the MIT license +# , at your +# option. This file may not be copied, modified, or distributed +# except according to those terms. + +set -ex + +URL=https://dl.google.com/android/repository/sys-img/android + +main() { + local arch=$1 + local name=$2 + local dest=/system + local td=$(mktemp -d) + + apt-get install --no-install-recommends e2tools + + pushd $td + curl -O $URL/$name + unzip -q $name + + local system=$(find . -name system.img) + mkdir -p $dest/{bin,lib,lib64} + + # Extract android linker and libraries to /system + # This allows android executables to be run directly (or with qemu) + if [ $arch = "x86_64" -o $arch = "arm64" ]; then + e2cp -p $system:/bin/linker64 $dest/bin/ + e2cp -p $system:/lib64/libdl.so $dest/lib64/ + e2cp -p $system:/lib64/libc.so $dest/lib64/ + e2cp -p $system:/lib64/libm.so $dest/lib64/ + else + e2cp -p $system:/bin/linker $dest/bin/ + e2cp -p $system:/lib/libdl.so $dest/lib/ + e2cp -p $system:/lib/libc.so $dest/lib/ + e2cp -p $system:/lib/libm.so $dest/lib/ + fi + + # clean up + apt-get purge --auto-remove -y e2tools + + popd + + rm -rf $td +} + +main "${@}" diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/aarch64-linux-android/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/aarch64-linux-android/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/aarch64-linux-android/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/aarch64-linux-android/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,45 @@ +FROM ubuntu:16.04 + +RUN dpkg --add-architecture i386 && \ + apt-get update && \ + apt-get install -y --no-install-recommends \ + file \ + curl \ + ca-certificates \ + python \ + unzip \ + expect \ + openjdk-9-jre \ + libstdc++6:i386 \ + libpulse0 \ + gcc \ + libc6-dev + +WORKDIR /android/ +COPY android* /android/ + +ENV ANDROID_ARCH=aarch64 +ENV PATH=$PATH:/android/ndk-$ANDROID_ARCH/bin:/android/sdk/tools:/android/sdk/platform-tools + +RUN sh /android/android-install-ndk.sh $ANDROID_ARCH +RUN sh /android/android-install-sdk.sh $ANDROID_ARCH +RUN mv /root/.android /tmp +RUN chmod 777 -R /tmp/.android +RUN chmod 755 /android/sdk/tools/* /android/sdk/emulator/qemu/linux-x86_64/* + +ENV PATH=$PATH:/rust/bin \ + CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER=aarch64-linux-android-gcc \ + CARGO_TARGET_AARCH64_LINUX_ANDROID_RUNNER=/tmp/runtest \ + HOME=/tmp + +ADD runtest-android.rs /tmp/runtest.rs +ENTRYPOINT [ \ + "bash", \ + "-c", \ + # set SHELL so android can detect a 64bits system, see + # http://stackoverflow.com/a/41789144 + "SHELL=/bin/dash /android/sdk/emulator/emulator @aarch64 -no-window & \ + rustc /tmp/runtest.rs -o /tmp/runtest && \ + exec \"$@\"", \ + "--" \ +] diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/aarch64-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/aarch64-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/aarch64-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/aarch64-unknown-linux-gnu/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,7 @@ +FROM ubuntu:17.10 +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc libc6-dev ca-certificates \ + gcc-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user +ENV CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc \ + CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUNNER="qemu-aarch64 -L /usr/aarch64-linux-gnu" \ + PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/aarch64-unknown-linux-musl/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/aarch64-unknown-linux-musl/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/aarch64-unknown-linux-musl/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/aarch64-unknown-linux-musl/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,27 @@ +FROM ubuntu:17.10 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc make libc6-dev git curl ca-certificates \ + gcc-aarch64-linux-gnu qemu-user +RUN curl https://www.musl-libc.org/releases/musl-1.1.16.tar.gz | \ + tar xzf - && \ + cd musl-1.1.16 && \ + CC=aarch64-linux-gnu-gcc \ + ./configure --prefix=/musl-aarch64 --enable-wrapper=yes && \ + make install -j4 && \ + cd .. && \ + rm -rf musl-1.1.16 && \ +# Install linux kernel headers sanitized for use with musl + curl -L https://github.com/sabotage-linux/kernel-headers/archive/v3.12.6-5.tar.gz | \ + tar xzf - && \ + cd kernel-headers-3.12.6-5 && \ + make ARCH=arm64 prefix=/musl-aarch64 install -j4 && \ + cd .. && \ + rm -rf kernel-headers-3.12.6-5 + +# FIXME: shouldn't need the `-lgcc` here, shouldn't that be in libstd? +ENV PATH=$PATH:/musl-aarch64/bin:/rust/bin \ + CC_aarch64_unknown_linux_musl=musl-gcc \ + RUSTFLAGS='-Clink-args=-lgcc' \ + CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_LINKER=musl-gcc \ + CARGO_TARGET_AARCH64_UNKNOWN_LINUX_MUSL_RUNNER="qemu-aarch64 -L /musl-aarch64" diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/arm-linux-androideabi/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/arm-linux-androideabi/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/arm-linux-androideabi/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/arm-linux-androideabi/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,45 @@ +FROM ubuntu:16.04 + +RUN dpkg --add-architecture i386 && \ + apt-get update && \ + apt-get install -y --no-install-recommends \ + file \ + curl \ + ca-certificates \ + python \ + unzip \ + expect \ + openjdk-9-jre \ + libstdc++6:i386 \ + libpulse0 \ + gcc \ + libc6-dev + +WORKDIR /android/ +COPY android* /android/ + +ENV ANDROID_ARCH=arm +ENV PATH=$PATH:/android/ndk-$ANDROID_ARCH/bin:/android/sdk/tools:/android/sdk/platform-tools + +RUN sh /android/android-install-ndk.sh $ANDROID_ARCH +RUN sh /android/android-install-sdk.sh $ANDROID_ARCH +RUN mv /root/.android /tmp +RUN chmod 777 -R /tmp/.android +RUN chmod 755 /android/sdk/tools/* /android/sdk/emulator/qemu/linux-x86_64/* + +ENV PATH=$PATH:/rust/bin \ + CARGO_TARGET_ARM_LINUX_ANDROIDEABI_LINKER=arm-linux-androideabi-gcc \ + CARGO_TARGET_ARM_LINUX_ANDROIDEABI_RUNNER=/tmp/runtest \ + HOME=/tmp + +ADD runtest-android.rs /tmp/runtest.rs +ENTRYPOINT [ \ + "bash", \ + "-c", \ + # set SHELL so android can detect a 64bits system, see + # http://stackoverflow.com/a/41789144 + "SHELL=/bin/dash /android/sdk/emulator/emulator @arm -no-window & \ + rustc /tmp/runtest.rs -o /tmp/runtest && \ + exec \"$@\"", \ + "--" \ +] diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/arm-unknown-linux-gnueabihf/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,7 @@ +FROM ubuntu:17.10 +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc libc6-dev ca-certificates \ + gcc-arm-linux-gnueabihf libc6-dev-armhf-cross qemu-user +ENV CARGO_TARGET_ARM_UNKNOWN_LINUX_GNUEABIHF_LINKER=arm-linux-gnueabihf-gcc \ + CARGO_TARGET_ARM_UNKNOWN_LINUX_GNUEABIHF_RUNNER="qemu-arm -L /usr/arm-linux-gnueabihf" \ + PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/arm-unknown-linux-musleabihf/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/arm-unknown-linux-musleabihf/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/arm-unknown-linux-musleabihf/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/arm-unknown-linux-musleabihf/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +FROM ubuntu:17.10 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc make libc6-dev git curl ca-certificates \ + gcc-arm-linux-gnueabihf qemu-user + +RUN curl https://www.musl-libc.org/releases/musl-1.1.16.tar.gz | tar xzf - +WORKDIR /musl-1.1.16 +RUN CC=arm-linux-gnueabihf-gcc \ + CFLAGS="-march=armv6 -marm" \ + ./configure --prefix=/musl-arm --enable-wrapper=yes +RUN make install -j4 + +# Install linux kernel headers sanitized for use with musl +RUN \ + curl -L https://github.com/sabotage-linux/kernel-headers/archive/v3.12.6-5.tar.gz | \ + tar xzf - && \ + cd kernel-headers-3.12.6-5 && \ + make ARCH=arm prefix=/musl-arm install -j4 && \ + cd .. && \ + rm -rf kernel-headers-3.12.6-5 +ENV PATH=$PATH:/musl-arm/bin:/rust/bin \ + CC_arm_unknown_linux_musleabihf=musl-gcc \ + CARGO_TARGET_ARM_UNKNOWN_LINUX_MUSLEABIHF_LINKER=musl-gcc \ + CARGO_TARGET_ARM_UNKNOWN_LINUX_MUSLEABIHF_RUNNER="qemu-arm -L /musl-arm" diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/asmjs-unknown-emscripten/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/asmjs-unknown-emscripten/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/asmjs-unknown-emscripten/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/asmjs-unknown-emscripten/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +FROM ubuntu:16.04 + +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + ca-certificates \ + curl \ + gcc \ + git \ + libc6-dev \ + python \ + xz-utils + +COPY emscripten.sh / +RUN bash /emscripten.sh + +ENV PATH=$PATH:/rust/bin \ + CARGO_TARGET_ASMJS_UNKNOWN_EMSCRIPTEN_RUNNER=node + +COPY emscripten-entry.sh / +ENTRYPOINT ["/emscripten-entry.sh"] diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/i686-linux-android/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/i686-linux-android/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/i686-linux-android/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/i686-linux-android/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,45 @@ +FROM ubuntu:16.04 + +RUN dpkg --add-architecture i386 && \ + apt-get update && \ + apt-get install -y --no-install-recommends \ + file \ + curl \ + ca-certificates \ + python \ + unzip \ + expect \ + openjdk-9-jre \ + libstdc++6:i386 \ + libpulse0 \ + gcc \ + libc6-dev + +WORKDIR /android/ +COPY android* /android/ + +ENV ANDROID_ARCH=i686 +ENV PATH=$PATH:/android/ndk-$ANDROID_ARCH/bin:/android/sdk/tools:/android/sdk/platform-tools + +RUN sh /android/android-install-ndk.sh $ANDROID_ARCH +RUN sh /android/android-install-sdk.sh $ANDROID_ARCH +RUN mv /root/.android /tmp +RUN chmod 777 -R /tmp/.android +RUN chmod 755 /android/sdk/tools/* /android/sdk/emulator/qemu/linux-x86_64/* + +ENV PATH=$PATH:/rust/bin \ + CARGO_TARGET_I686_LINUX_ANDROID_LINKER=i686-linux-android-gcc \ + CARGO_TARGET_I686_LINUX_ANDROID_RUNNER=/tmp/runtest \ + HOME=/tmp + +ADD runtest-android.rs /tmp/runtest.rs +ENTRYPOINT [ \ + "bash", \ + "-c", \ + # set SHELL so android can detect a 64bits system, see + # http://stackoverflow.com/a/41789144 + "SHELL=/bin/dash /android/sdk/emulator/emulator @i686 -no-window -no-accel & \ + rustc /tmp/runtest.rs -o /tmp/runtest && \ + exec \"$@\"", \ + "--" \ +] diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/i686-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/i686-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/i686-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/i686-unknown-linux-gnu/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,5 @@ +FROM ubuntu:18.04 +RUN apt-get update +RUN apt-get install -y --no-install-recommends \ + gcc-multilib libc6-dev ca-certificates +ENV PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/i686-unknown-linux-musl/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/i686-unknown-linux-musl/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/i686-unknown-linux-musl/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/i686-unknown-linux-musl/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,30 @@ +FROM ubuntu:17.10 + +RUN dpkg --add-architecture i386 +RUN apt-get update +RUN apt-get install -y --no-install-recommends \ + gcc-multilib make libc6-dev git curl ca-certificates libc6:i386 +# Below we're cross-compiling musl for i686 using the system compiler on an +# x86_64 system. This is an awkward thing to be doing and so we have to jump +# through a couple hoops to get musl to be happy. In particular: +# +# * We specifically pass -m32 in CFLAGS and override CC when running ./configure, +# since otherwise the script will fail to find a compiler. +# * We manually unset CROSS_COMPILE when running make; otherwise the makefile +# will call the non-existent binary 'i686-ar'. +RUN curl https://www.musl-libc.org/releases/musl-1.1.15.tar.gz | \ + tar xzf - && \ + cd musl-1.1.15 && \ + CC=gcc CFLAGS=-m32 ./configure --prefix=/musl-i686 --disable-shared --target=i686 && \ + make CROSS_COMPILE= install -j4 && \ + cd .. && \ + rm -rf musl-1.1.15 && \ +# Install linux kernel headers sanitized for use with musl + curl -L https://github.com/sabotage-linux/kernel-headers/archive/v3.12.6-5.tar.gz | \ + tar xzf - && \ + cd kernel-headers-3.12.6-5 && \ + make ARCH=i386 prefix=/musl-i686 install -j4 && \ + cd .. && \ + rm -rf kernel-headers-3.12.6-5 +ENV PATH=$PATH:/musl-i686/bin:/rust/bin \ + CC_i686_unknown_linux_musl=musl-gcc diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/mips64el-unknown-linux-gnuabi64/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,11 @@ +FROM ubuntu:17.10 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc libc6-dev qemu-user ca-certificates \ + gcc-mips64el-linux-gnuabi64 libc6-dev-mips64el-cross \ + qemu-system-mips64el + +ENV CARGO_TARGET_MIPS64EL_UNKNOWN_LINUX_GNUABI64_LINKER=mips64el-linux-gnuabi64-gcc \ + CARGO_TARGET_MIPS64EL_UNKNOWN_LINUX_GNUABI64_RUNNER="qemu-mips64el -L /usr/mips64el-linux-gnuabi64" \ + CC_mips64el_unknown_linux_gnuabi64=mips64el-linux-gnuabi64-gcc \ + PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/mips64-unknown-linux-gnuabi64/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,11 @@ +FROM ubuntu:17.10 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc libc6-dev qemu-user ca-certificates \ + gcc-mips64-linux-gnuabi64 libc6-dev-mips64-cross \ + qemu-system-mips64 + +ENV CARGO_TARGET_MIPS64_UNKNOWN_LINUX_GNUABI64_LINKER=mips64-linux-gnuabi64-gcc \ + CARGO_TARGET_MIPS64_UNKNOWN_LINUX_GNUABI64_RUNNER="qemu-mips64 -L /usr/mips64-linux-gnuabi64" \ + CC_mips64_unknown_linux_gnuabi64=mips64-linux-gnuabi64-gcc \ + PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/mipsel-unknown-linux-musl/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/mipsel-unknown-linux-musl/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/mipsel-unknown-linux-musl/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/mipsel-unknown-linux-musl/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,17 @@ +FROM ubuntu:17.10 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc libc6-dev qemu-user ca-certificates qemu-system-mips curl \ + bzip2 + +RUN mkdir /toolchain + +# Note that this originally came from: +# https://downloads.openwrt.org/snapshots/trunk/malta/generic/OpenWrt-Toolchain-malta-le_gcc-5.3.0_musl-1.1.15.Linux-x86_64.tar.bz2 +RUN curl -L https://s3-us-west-1.amazonaws.com/rust-lang-ci2/libc/OpenWrt-Toolchain-malta-le_gcc-5.3.0_musl-1.1.15.Linux-x86_64.tar.bz2 | \ + tar xjf - -C /toolchain --strip-components=2 + +ENV PATH=$PATH:/rust/bin:/toolchain/bin \ + CC_mipsel_unknown_linux_musl=mipsel-openwrt-linux-gcc \ + CARGO_TARGET_MIPSEL_UNKNOWN_LINUX_MUSL_LINKER=mipsel-openwrt-linux-gcc \ + CARGO_TARGET_MIPSEL_UNKNOWN_LINUX_MUSL_RUNNER="qemu-mipsel -L /toolchain" diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/mips-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/mips-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/mips-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/mips-unknown-linux-gnu/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,10 @@ +FROM ubuntu:17.10 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc libc6-dev qemu-user ca-certificates \ + gcc-mips-linux-gnu libc6-dev-mips-cross \ + qemu-system-mips + +ENV CARGO_TARGET_MIPS_UNKNOWN_LINUX_GNU_LINKER=mips-linux-gnu-gcc \ + CARGO_TARGET_MIPS_UNKNOWN_LINUX_GNU_RUNNER="qemu-mips -L /usr/mips-linux-gnu" \ + PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/mips-unknown-linux-musl/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/mips-unknown-linux-musl/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/mips-unknown-linux-musl/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/mips-unknown-linux-musl/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,17 @@ +FROM ubuntu:17.10 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc libc6-dev qemu-user ca-certificates qemu-system-mips curl \ + bzip2 + +RUN mkdir /toolchain + +# Note that this originally came from: +# https://downloads.openwrt.org/snapshots/trunk/ar71xx/generic/OpenWrt-SDK-ar71xx-generic_gcc-5.3.0_musl-1.1.15.Linux-x86_64.tar.bz2 +RUN curl -L https://s3-us-west-1.amazonaws.com/rust-lang-ci2/libc/OpenWrt-SDK-ar71xx-generic_gcc-5.3.0_musl-1.1.15.Linux-x86_64.tar.bz2 | \ + tar xjf - -C /toolchain --strip-components=1 + +ENV PATH=$PATH:/rust/bin:/toolchain/staging_dir/toolchain-mips_34kc_gcc-5.3.0_musl-1.1.15/bin \ + CC_mips_unknown_linux_musl=mips-openwrt-linux-gcc \ + CARGO_TARGET_MIPS_UNKNOWN_LINUX_MUSL_LINKER=mips-openwrt-linux-gcc \ + CARGO_TARGET_MIPS_UNKNOWN_LINUX_MUSL_RUNNER="qemu-mips -L /toolchain/staging_dir/toolchain-mips_34kc_gcc-5.3.0_musl-1.1.15" diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/powerpc64le-unknown-linux-gnu/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,11 @@ +FROM ubuntu:17.10 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc libc6-dev qemu-user ca-certificates \ + gcc-powerpc64le-linux-gnu libc6-dev-ppc64el-cross \ + qemu-system-ppc + +ENV CARGO_TARGET_POWERPC64LE_UNKNOWN_LINUX_GNU_LINKER=powerpc64le-linux-gnu-gcc \ + CARGO_TARGET_POWERPC64LE_UNKNOWN_LINUX_GNU_RUNNER="qemu-ppc64le -L /usr/powerpc64le-linux-gnu" \ + CC=powerpc64le-linux-gnu-gcc \ + PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/powerpc64-unknown-linux-gnu/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,11 @@ +FROM ubuntu:17.10 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc libc6-dev qemu-user ca-certificates \ + gcc-powerpc64-linux-gnu libc6-dev-ppc64-cross \ + qemu-system-ppc + +ENV CARGO_TARGET_POWERPC64_UNKNOWN_LINUX_GNU_LINKER=powerpc64-linux-gnu-gcc \ + CARGO_TARGET_POWERPC64_UNKNOWN_LINUX_GNU_RUNNER="qemu-ppc64 -L /usr/powerpc64-linux-gnu" \ + CC=powerpc64-linux-gnu-gcc \ + PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/powerpc-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/powerpc-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/powerpc-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/powerpc-unknown-linux-gnu/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,10 @@ +FROM ubuntu:17.10 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + gcc libc6-dev qemu-user ca-certificates \ + gcc-powerpc-linux-gnu libc6-dev-powerpc-cross \ + qemu-system-ppc + +ENV CARGO_TARGET_POWERPC_UNKNOWN_LINUX_GNU_LINKER=powerpc-linux-gnu-gcc \ + CARGO_TARGET_POWERPC_UNKNOWN_LINUX_GNU_RUNNER="qemu-ppc -L /usr/powerpc-linux-gnu" \ + PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/s390x-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/s390x-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/s390x-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/s390x-unknown-linux-gnu/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,18 @@ +FROM ubuntu:17.10 + +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl ca-certificates \ + gcc libc6-dev \ + gcc-s390x-linux-gnu libc6-dev-s390x-cross \ + qemu-system-s390x \ + cpio + +COPY linux-s390x.sh / +RUN bash /linux-s390x.sh + +COPY test-runner-linux / + +ENV CARGO_TARGET_S390X_UNKNOWN_LINUX_GNU_LINKER=s390x-linux-gnu-gcc \ + CARGO_TARGET_S390X_UNKNOWN_LINUX_GNU_RUNNER="/test-runner-linux s390x" \ + CC_s390x_unknown_linux_gnu=s390x-linux-gnu-gcc \ + PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/sparc64-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/sparc64-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/sparc64-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/sparc64-unknown-linux-gnu/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,18 @@ +FROM debian:stretch + +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl ca-certificates \ + gcc libc6-dev \ + gcc-sparc64-linux-gnu libc6-dev-sparc64-cross \ + qemu-system-sparc64 openbios-sparc seabios ipxe-qemu \ + p7zip-full cpio + +COPY linux-sparc64.sh / +RUN bash /linux-sparc64.sh + +COPY test-runner-linux / + +ENV CARGO_TARGET_SPARC64_UNKNOWN_LINUX_GNU_LINKER=sparc64-linux-gnu-gcc \ + CARGO_TARGET_SPARC64_UNKNOWN_LINUX_GNU_RUNNER="/test-runner-linux sparc64" \ + CC_sparc64_unknown_linux_gnu=sparc64-linux-gnu-gcc \ + PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/wasm32-unknown-emscripten/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/wasm32-unknown-emscripten/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/wasm32-unknown-emscripten/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/wasm32-unknown-emscripten/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,21 @@ +FROM ubuntu:16.04 + +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + ca-certificates \ + curl \ + gcc \ + git \ + libc6-dev \ + python \ + xz-utils + +COPY emscripten.sh / +RUN bash /emscripten.sh + +ENV PATH=$PATH:/rust/bin \ + CARGO_TARGET_WASM32_UNKNOWN_EMSCRIPTEN_RUNNER=node-wrapper.sh + +COPY emscripten-entry.sh / +COPY docker/wasm32-unknown-emscripten/node-wrapper.sh /usr/local/bin/node-wrapper.sh +ENTRYPOINT ["/emscripten-entry.sh"] diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/wasm32-unknown-emscripten/node-wrapper.sh cargo-0.26.0/vendor/libc-0.2.40/ci/docker/wasm32-unknown-emscripten/node-wrapper.sh --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/wasm32-unknown-emscripten/node-wrapper.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/wasm32-unknown-emscripten/node-wrapper.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,15 @@ +#!/bin/sh + +set -e + +me=$1 +shift +dir=$(dirname $me) +file=$(basename $me) + +if echo $file | grep -q wasm; then + exit 0 # FIXME(rust-lang/cargo#4750) +fi + +cd $dir +exec node $file "$@" diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-linux-android/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-linux-android/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-linux-android/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-linux-android/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,26 @@ +FROM ubuntu:16.04 + +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + ca-certificates \ + curl \ + gcc \ + libc-dev \ + python \ + unzip + +WORKDIR /android/ +ENV ANDROID_ARCH=x86_64 +COPY android-install-ndk.sh /android/ +RUN sh /android/android-install-ndk.sh $ANDROID_ARCH + +# We do not run x86_64-linux-android tests on an android emulator. +# See ci/android-sysimage.sh for informations about how tests are run. +COPY android-sysimage.sh /android/ +RUN bash /android/android-sysimage.sh x86_64 x86_64-24_r07.zip + +ENV PATH=$PATH:/rust/bin:/android/ndk-$ANDROID_ARCH/bin \ + CARGO_TARGET_X86_64_LINUX_ANDROID_LINKER=x86_64-linux-android-gcc \ + CC_x86_64_linux_android=x86_64-linux-android-gcc \ + CXX_x86_64_linux_android=x86_64-linux-android-g++ \ + HOME=/tmp diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-rumprun-netbsd/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-rumprun-netbsd/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-rumprun-netbsd/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-rumprun-netbsd/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,10 @@ +FROM mato/rumprun-toolchain-hw-x86_64 +USER root +RUN apt-get update +RUN apt-get install -y --no-install-recommends \ + qemu +ENV PATH=$PATH:/rust/bin \ + CARGO_TARGET_X86_64_RUMPRUN_NETBSD_RUNNER=/tmp/runtest + +ADD docker/x86_64-rumprun-netbsd/runtest.rs /tmp/ +ENTRYPOINT ["sh", "-c", "rustc /tmp/runtest.rs -o /tmp/runtest && exec \"$@\"", "--"] diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-rumprun-netbsd/runtest.rs cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-rumprun-netbsd/runtest.rs --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-rumprun-netbsd/runtest.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-rumprun-netbsd/runtest.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,54 @@ +use std::env; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use std::thread; +use std::time::Duration; +use std::io::{BufRead, BufReader, Read}; + +fn main() { + assert_eq!(env::args().len(), 2); + + let status = Command::new("rumprun-bake") + .arg("hw_virtio") + .arg("/tmp/libc-test.img") + .arg(env::args().nth(1).unwrap()) + .status() + .expect("failed to run rumprun-bake"); + assert!(status.success()); + + let mut child = Command::new("qemu-system-x86_64") + .arg("-nographic") + .arg("-vga").arg("none") + .arg("-m").arg("64") + .arg("-kernel").arg("/tmp/libc-test.img") + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("failed to spawn qemu"); + + let mut stdout = child.stdout.take().unwrap(); + let mut stderr = child.stderr.take().unwrap(); + let (tx, rx) = mpsc::channel(); + let tx2 = tx.clone(); + let t1 = thread::spawn(move || find_ok(&mut stdout, tx)); + let t2 = thread::spawn(move || find_ok(&mut stderr, tx2)); + + let res = rx.recv_timeout(Duration::new(5, 0)); + child.kill().unwrap(); + t1.join().unwrap(); + t2.join().unwrap(); + + if res.is_err() { + panic!("didn't find success"); + } +} + +fn find_ok(input: &mut Read, tx: mpsc::Sender<()>) { + for line in BufReader::new(input).lines() { + let line = line.unwrap(); + println!("{}", line); + if line.starts_with("PASSED ") && line.contains(" tests") { + tx.send(()).unwrap(); + } + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-freebsd/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-freebsd/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-freebsd/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-freebsd/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,13 @@ +FROM wezm/port-prebuilt-freebsd11@sha256:43553e2265ec702ec72a63a765df333f50b1858b896e69385749e96d8624e9b0 + +RUN apt-get update +RUN apt-get install -y --no-install-recommends \ + qemu genext2fs xz-utils +RUN apt-get install -y curl ca-certificates gcc + +ENTRYPOINT ["sh"] + +ENV PATH=$PATH:/rust/bin \ + QEMU=2018-03-15/FreeBSD-11.1-RELEASE-amd64.qcow2.xz \ + CAN_CROSS=1 \ + CARGO_TARGET_X86_64_UNKNOWN_FREEBSD_LINKER=x86_64-unknown-freebsd11-gcc diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-linux-gnu/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-linux-gnu/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-linux-gnu/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-linux-gnu/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,5 @@ +FROM ubuntu:18.04 +RUN apt-get update +RUN apt-get install -y --no-install-recommends \ + gcc libc6-dev ca-certificates +ENV PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-linux-gnux32/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-linux-gnux32/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-linux-gnux32/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-linux-gnux32/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,5 @@ +FROM ubuntu:18.04 +RUN apt-get update +RUN apt-get install -y --no-install-recommends \ + gcc-multilib libc6-dev ca-certificates +ENV PATH=$PATH:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-linux-musl/Dockerfile cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-linux-musl/Dockerfile --- cargo-0.25.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-linux-musl/Dockerfile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/docker/x86_64-unknown-linux-musl/Dockerfile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +FROM ubuntu:17.10 + +RUN apt-get update +RUN apt-get install -y --no-install-recommends \ + gcc make libc6-dev git curl ca-certificates +RUN curl https://www.musl-libc.org/releases/musl-1.1.15.tar.gz | \ + tar xzf - && \ + cd musl-1.1.15 && \ + ./configure --prefix=/musl-x86_64 && \ + make install -j4 && \ + cd .. && \ + rm -rf musl-1.1.15 && \ +# Install linux kernel headers sanitized for use with musl + curl -L https://github.com/sabotage-linux/kernel-headers/archive/v3.12.6-5.tar.gz | \ + tar xzf - && \ + cd kernel-headers-3.12.6-5 && \ + make ARCH=x86_64 prefix=/musl-x86_64 install -j4 && \ + cd .. && \ + rm -rf kernel-headers-3.12.6-5 +ENV PATH=$PATH:/musl-x86_64/bin:/rust/bin diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/dox.sh cargo-0.26.0/vendor/libc-0.2.40/ci/dox.sh --- cargo-0.25.0/vendor/libc-0.2.40/ci/dox.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/dox.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,33 @@ +#!/bin/sh + +# Builds documentation for all target triples that we have a registered URL for +# in liblibc. This scrapes the list of triples to document from `src/lib.rs` +# which has a bunch of `html_root_url` directives we pick up. + +set -e + +TARGETS=`grep html_root_url src/lib.rs | sed 's/.*".*\/\(.*\)"/\1/'` + +rm -rf target/doc +mkdir -p target/doc + +cp ci/landing-page-head.html target/doc/index.html + +for target in $TARGETS; do + echo documenting $target + + rustdoc -o target/doc/$target --target $target src/lib.rs --cfg cross_platform_docs \ + --crate-name libc + + echo "
    • $target
    • " \ + >> target/doc/index.html +done + +cat ci/landing-page-footer.html >> target/doc/index.html + +# If we're on travis, not a PR, and on the right branch, publish! +if [ "$TRAVIS_PULL_REQUEST" = "false" ] && [ "$TRAVIS_BRANCH" = "master" ]; then + pip install ghp_import --install-option="--prefix=$HOME/.local" + $HOME/.local/bin/ghp-import -n target/doc + git push -qf https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages +fi diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/emscripten-entry.sh cargo-0.26.0/vendor/libc-0.2.40/ci/emscripten-entry.sh --- cargo-0.25.0/vendor/libc-0.2.40/ci/emscripten-entry.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/emscripten-entry.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Copyright 2017 The Rust Project Developers. See the COPYRIGHT +# file at the top-level directory of this distribution and at +# http://rust-lang.org/COPYRIGHT. +# +# Licensed under the Apache License, Version 2.0 or the MIT license +# , at your +# option. This file may not be copied, modified, or distributed +# except according to those terms. + +set -ex + +source /emsdk-portable/emsdk_env.sh &> /dev/null + +# emsdk-portable provides a node binary, but we need version 8 to run wasm +export PATH="/node-v8.0.0-linux-x64/bin:$PATH" + +exec "$@" diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/emscripten.sh cargo-0.26.0/vendor/libc-0.2.40/ci/emscripten.sh --- cargo-0.25.0/vendor/libc-0.2.40/ci/emscripten.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/emscripten.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,54 @@ +# Copyright 2017 The Rust Project Developers. See the COPYRIGHT +# file at the top-level directory of this distribution and at +# http://rust-lang.org/COPYRIGHT. +# +# Licensed under the Apache License, Version 2.0 or the MIT license +# , at your +# option. This file may not be copied, modified, or distributed +# except according to those terms. + +set -ex + +hide_output() { + set +x + on_err=" +echo ERROR: An error was encountered with the build. +cat /tmp/build.log +exit 1 +" + trap "$on_err" ERR + bash -c "while true; do sleep 30; echo \$(date) - building ...; done" & + PING_LOOP_PID=$! + $@ &> /tmp/build.log + trap - ERR + kill $PING_LOOP_PID + rm -f /tmp/build.log + set -x +} + +cd / +curl -L https://s3.amazonaws.com/mozilla-games/emscripten/releases/emsdk-portable.tar.gz | \ + tar -xz + +cd /emsdk-portable +./emsdk update +hide_output ./emsdk install sdk-1.37.20-64bit +./emsdk activate sdk-1.37.20-64bit + +# Compile and cache libc +source ./emsdk_env.sh +echo "main(){}" > a.c +HOME=/emsdk-portable/ emcc a.c +HOME=/emsdk-portable/ emcc -s BINARYEN=1 a.c +rm -f a.* + +# Make emsdk usable by any user +cp /root/.emscripten /emsdk-portable +chmod a+rxw -R /emsdk-portable + +# node 8 is required to run wasm +cd / +curl -L https://nodejs.org/dist/v8.0.0/node-v8.0.0-linux-x64.tar.xz | \ + tar -xJ + diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/ios/deploy_and_run_on_ios_simulator.rs cargo-0.26.0/vendor/libc-0.2.40/ci/ios/deploy_and_run_on_ios_simulator.rs --- cargo-0.25.0/vendor/libc-0.2.40/ci/ios/deploy_and_run_on_ios_simulator.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/ios/deploy_and_run_on_ios_simulator.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,171 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// This is a script to deploy and execute a binary on an iOS simulator. +// The primary use of this is to be able to run unit tests on the simulator and +// retrieve the results. +// +// To do this through Cargo instead, use Dinghy +// (https://github.com/snipsco/dinghy): cargo dinghy install, then cargo dinghy +// test. + +use std::env; +use std::fs::{self, File}; +use std::io::Write; +use std::path::Path; +use std::process; +use std::process::Command; + +macro_rules! t { + ($e:expr) => (match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with: {}", stringify!($e), e), + }) +} + +// Step one: Wrap as an app +fn package_as_simulator_app(crate_name: &str, test_binary_path: &Path) { + println!("Packaging simulator app"); + drop(fs::remove_dir_all("ios_simulator_app")); + t!(fs::create_dir("ios_simulator_app")); + t!(fs::copy(test_binary_path, + Path::new("ios_simulator_app").join(crate_name))); + + let mut f = t!(File::create("ios_simulator_app/Info.plist")); + t!(f.write_all(format!(r#" + + + + + CFBundleExecutable + {} + CFBundleIdentifier + com.rust.unittests + + + "#, crate_name).as_bytes())); +} + +// Step two: Start the iOS simulator +fn start_simulator() { + println!("Looking for iOS simulator"); + let output = t!(Command::new("xcrun").arg("simctl").arg("list").output()); + assert!(output.status.success()); + let mut simulator_exists = false; + let mut simulator_booted = false; + let mut found_rust_sim = false; + let stdout = t!(String::from_utf8(output.stdout)); + for line in stdout.lines() { + if line.contains("rust_ios") { + if found_rust_sim { + panic!("Duplicate rust_ios simulators found. Please \ + double-check xcrun simctl list."); + } + simulator_exists = true; + simulator_booted = line.contains("(Booted)"); + found_rust_sim = true; + } + } + + if simulator_exists == false { + println!("Creating iOS simulator"); + Command::new("xcrun") + .arg("simctl") + .arg("create") + .arg("rust_ios") + .arg("com.apple.CoreSimulator.SimDeviceType.iPhone-SE") + .arg("com.apple.CoreSimulator.SimRuntime.iOS-10-2") + .check_status(); + } else if simulator_booted == true { + println!("Shutting down already-booted simulator"); + Command::new("xcrun") + .arg("simctl") + .arg("shutdown") + .arg("rust_ios") + .check_status(); + } + + println!("Starting iOS simulator"); + // We can't uninstall the app (if present) as that will hang if the + // simulator isn't completely booted; just erase the simulator instead. + Command::new("xcrun").arg("simctl").arg("erase").arg("rust_ios").check_status(); + Command::new("xcrun").arg("simctl").arg("boot").arg("rust_ios").check_status(); +} + +// Step three: Install the app +fn install_app_to_simulator() { + println!("Installing app to simulator"); + Command::new("xcrun") + .arg("simctl") + .arg("install") + .arg("booted") + .arg("ios_simulator_app/") + .check_status(); +} + +// Step four: Run the app +fn run_app_on_simulator() { + println!("Running app"); + let output = t!(Command::new("xcrun") + .arg("simctl") + .arg("launch") + .arg("--console") + .arg("booted") + .arg("com.rust.unittests") + .output()); + + println!("stdout --\n{}\n", String::from_utf8_lossy(&output.stdout)); + println!("stderr --\n{}\n", String::from_utf8_lossy(&output.stderr)); + + let stdout = String::from_utf8_lossy(&output.stdout); + let passed = stdout.lines() + .find(|l| l.contains("PASSED")) + .map(|l| l.contains("tests")) + .unwrap_or(false); + + println!("Shutting down simulator"); + Command::new("xcrun") + .arg("simctl") + .arg("shutdown") + .arg("rust_ios") + .check_status(); + if !passed { + panic!("tests didn't pass"); + } +} + +trait CheckStatus { + fn check_status(&mut self); +} + +impl CheckStatus for Command { + fn check_status(&mut self) { + println!("\trunning: {:?}", self); + assert!(t!(self.status()).success()); + } +} + +fn main() { + let args: Vec = env::args().collect(); + if args.len() != 2 { + println!("Usage: {} ", args[0]); + process::exit(-1); + } + + let test_binary_path = Path::new(&args[1]); + let crate_name = test_binary_path.file_name().unwrap(); + + package_as_simulator_app(crate_name.to_str().unwrap(), test_binary_path); + start_simulator(); + install_app_to_simulator(); + run_app_on_simulator(); +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/landing-page-footer.html cargo-0.26.0/vendor/libc-0.2.40/ci/landing-page-footer.html --- cargo-0.25.0/vendor/libc-0.2.40/ci/landing-page-footer.html 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/landing-page-footer.html 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3 @@ +
    + + diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/landing-page-head.html cargo-0.26.0/vendor/libc-0.2.40/ci/landing-page-head.html --- cargo-0.25.0/vendor/libc-0.2.40/ci/landing-page-head.html 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/landing-page-head.html 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,7 @@ + + + + + + +
      diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/linux-s390x.sh cargo-0.26.0/vendor/libc-0.2.40/ci/linux-s390x.sh --- cargo-0.25.0/vendor/libc-0.2.40/ci/linux-s390x.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/linux-s390x.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,18 @@ +set -ex + +mkdir -m 777 /qemu +cd /qemu + +curl -LO https://github.com/qemu/qemu/raw/master/pc-bios/s390-ccw.img +curl -LO http://ftp.debian.org/debian/dists/testing/main/installer-s390x/20170828/images/generic/kernel.debian +curl -LO http://ftp.debian.org/debian/dists/testing/main/installer-s390x/20170828/images/generic/initrd.debian + +mv kernel.debian kernel +mv initrd.debian initrd.gz + +mkdir init +cd init +gunzip -c ../initrd.gz | cpio -id +rm ../initrd.gz +cp /usr/s390x-linux-gnu/lib/libgcc_s.so.1 usr/lib/ +chmod a+w . diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/linux-sparc64.sh cargo-0.26.0/vendor/libc-0.2.40/ci/linux-sparc64.sh --- cargo-0.25.0/vendor/libc-0.2.40/ci/linux-sparc64.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/linux-sparc64.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,17 @@ +set -ex + +mkdir -m 777 /qemu +cd /qemu + +curl -LO https://cdimage.debian.org/cdimage/ports/debian-9.0-sparc64-NETINST-1.iso +7z e debian-9.0-sparc64-NETINST-1.iso boot/initrd.gz +7z e debian-9.0-sparc64-NETINST-1.iso boot/sparc64 +mv sparc64 kernel +rm debian-9.0-sparc64-NETINST-1.iso + +mkdir init +cd init +gunzip -c ../initrd.gz | cpio -id +rm ../initrd.gz +cp /usr/sparc64-linux-gnu/lib/libgcc_s.so.1 usr/lib/ +chmod a+w . diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/README.md cargo-0.26.0/vendor/libc-0.2.40/ci/README.md --- cargo-0.25.0/vendor/libc-0.2.40/ci/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,243 @@ +The goal of the libc crate is to have CI running everywhere to have the +strongest guarantees about the definitions that this library contains, and as a +result the CI is pretty complicated and also pretty large! Hopefully this can +serve as a guide through the sea of scripts in this directory and elsewhere in +this project. + +# Files + +First up, let's talk about the files in this directory: + +* `run-travis.sh` - a shell script run by all Travis builders, this is + responsible for setting up the rest of the environment such as installing new + packages, downloading Rust target libraries, etc. + +* `run.sh` - the actual script which runs tests for a particular architecture. + Called from the `run-travis.sh` script this will run all tests for the target + specified. + +* `cargo-config` - Cargo configuration of linkers to use copied into place by + the `run-travis.sh` script before builds are run. + +* `dox.sh` - script called from `run-travis.sh` on only the linux 64-bit nightly + Travis bots to build documentation for this crate. + +* `landing-page-*.html` - used by `dox.sh` to generate a landing page for all + architectures' documentation. + +* `run-qemu.sh` - see discussion about QEMU below + +* `mips`, `rumprun` - instructions to build the docker image for each respective + CI target + +# CI Systems + +Currently this repository leverages a combination of Travis CI and AppVeyor for +running tests. The triples tested are: + +* AppVeyor + * `{i686,x86_64}-pc-windows-{msvc,gnu}` +* Travis + * `{i686,x86_64,mips,aarch64}-unknown-linux-gnu` + * `{x86_64,aarch64}-unknown-linux-musl` + * `arm-unknown-linux-gnueabihf` + * `arm-linux-androideabi` + * `{i686,x86_64}-apple-{darwin,ios}` + * `x86_64-rumprun-netbsd` + * `x86_64-unknown-freebsd` + * `x86_64-unknown-openbsd` + +The Windows triples are all pretty standard, they just set up their environment +then run tests, no need for downloading any extra target libs (we just download +the right installer). The Intel Linux/OSX builds are similar in that we just +download the right target libs and run tests. Note that the Intel Linux/OSX +builds are run on stable/beta/nightly, but are the only ones that do so. + +The remaining architectures look like: + +* Android runs in a [docker image][android-docker] with an emulator, the NDK, + and the SDK already set up. The entire build happens within the docker image. +* The MIPS, ARM, and AArch64 builds all use the QEMU userspace emulator to run + the generated binary to actually verify the tests pass. +* The MUSL build just has to download a MUSL compiler and target libraries and + then otherwise runs tests normally. +* iOS builds need an extra linker flag currently, but beyond that they're built + as standard as everything else. +* The rumprun target builds an entire kernel from the test suite and then runs + it inside QEMU using the serial console to test whether it succeeded or + failed. +* The BSD builds, currently OpenBSD and FreeBSD, use QEMU to boot up a system + and compile/run tests. More information on that below. + +[android-docker]: https://github.com/rust-lang/rust-buildbot/blob/master/slaves/android/Dockerfile + +## QEMU + +Lots of the architectures tested here use QEMU in the tests, so it's worth going +over all the crazy capabilities QEMU has and the various flavors in which we use +it! + +First up, QEMU has userspace emulation where it doesn't boot a full kernel, it +just runs a binary from another architecture (using the `qemu-` wrappers). +We provide it the runtime path for the dynamically loaded system libraries, +however. This strategy is used for all Linux architectures that aren't intel. +Note that one downside of this QEMU system is that threads are barely +implemented, so we're careful to not spawn many threads. + +For the rumprun target the only output is a kernel image, so we just use that +plus the `rumpbake` command to create a full kernel image which is then run from +within QEMU. + +Finally, the fun part, the BSDs. Quite a few hoops are jumped through to get CI +working for these platforms, but the gist of it looks like: + +* Cross compiling from Linux to any of the BSDs seems to be quite non-standard. + We may be able to get it working but it might be difficult at that point to + ensure that the libc definitions align with what you'd get on the BSD itself. + As a result, we try to do compiles within the BSD distro. +* On Travis we can't run a VM-in-a-VM, so we resort to userspace emulation + (QEMU). +* Unfortunately on Travis we also can't use KVM, so the emulation is super slow. + +With all that in mind, the way BSD is tested looks like: + +1. Download a pre-prepared image for the OS being tested. +2. Generate the tests for the OS being tested. This involves running the `ctest` + library over libc to generate a Rust file and a C file which will then be + compiled into the final test. +3. Generate a disk image which will later be mounted by the OS being tested. + This image is mostly just the libc directory, but some modifications are made + to compile the generated files from step 2. +4. The kernel is booted in QEMU, and it is configured to detect the libc-test + image being available, run the test script, and then shut down afterwards. +5. Look for whether the tests passed in the serial console output of the kernel. + +There's some pretty specific instructions for setting up each image (detailed +below), but the main gist of this is that we must avoid a vanilla `cargo run` +inside of the `libc-test` directory (which is what it's intended for) because +that would compile `syntex_syntax`, a large library, with userspace emulation. +This invariably times out on Travis, so we can't do that. + +Once all those hoops are jumped through, however, we can be happy that we're +testing almost everything! + +Below are some details of how to set up the initial OS images which are +downloaded. Each image must be enabled have input/output over the serial +console, log in automatically at the serial console, detect if a second drive in +QEMU is available, and if so mount it, run a script (it'll specifically be +`run-qemu.sh` in this folder which is copied into the generated image talked +about above), and then shut down. + +### QEMU Setup - FreeBSD + +1. [Download the latest stable amd64-bootonly release ISO](https://www.freebsd.org/where.html). + E.g. FreeBSD-11.1-RELEASE-amd64-bootonly.iso +2. Create the disk image: `qemu-img create -f qcow2 FreeBSD-11.1-RELEASE-amd64.qcow2 2G` +3. Boot the machine: `qemu-system-x86_64 -cdrom FreeBSD-11.1-RELEASE-amd64-bootonly.iso -drive if=virtio,file=FreeBSD-11.1-RELEASE-amd64.qcow2 -net nic,model=virtio -net user` +4. Run the installer, and install FreeBSD: + 1. Install + 1. Continue with default keymap + 1. Set Hostname: freebsd-ci + 1. Distribution Select: + 1. Uncheck lib32 + 1. Uncheck ports + 1. Network Configuration: vtnet0 + 1. Configure IPv4? Yes + 1. DHCP? Yes + 1. Configure IPv6? No + 1. Resolver Configuration: Ok + 1. Mirror Selection: Main Site + 1. Partitioning: Auto (UFS) + 1. Partition: Entire Disk + 1. Partition Scheme: MBR + 1. App Partition: Ok + 1. Partition Editor: Finish + 1. Confirmation: Commit + 1. Wait for sets to install + 1. Set the root password to nothing (press enter twice) + 1. Set time zone to UTC + 1. Set Date: Skip + 1. Set Time: Skip + 1. System Configuration: + 1. Disable sshd + 1. Disable dumpdev + 1. System Hardening + 1. Disable Sendmail service + 1. Add User Accounts: No + 1. Final Configuration: Exit + 1. Manual Configuration: Yes + 1. `echo 'console="comconsole"' >> /boot/loader.conf` + 1. `echo 'autoboot_delay="0"' >> /boot/loader.conf` + 1. `echo 'ext2fs_load="YES"' >> /boot/loader.conf` + 1. Look at `/etc/ttys`, see what getty argument is for `ttyu0` (E.g. `3wire`) + 1. Edit `/etc/gettytab` (with `vi` for example), look for `ttyu0` argument, + prepend `:al=root` to the line beneath to have the machine auto-login as + root. E.g. + + 3wire:\ + :np:nc:sp#0: + becomes: + + 3wire:\ + :al=root:np:nc:sp#0: + + 1. Edit `/root/.login` and put this in it: + + [ -e /dev/vtbd1 ] || exit 0 + mount -t ext2fs /dev/vtbd1 /mnt + sh /mnt/run.sh /mnt + poweroff + + 1. Exit the post install shell: `exit` + 1. Back in in the installer choose Reboot + 1. If all went well the machine should reboot and show a login prompt. + If you switch to the serial console by choosing View > serial0 in + the qemu menu, you should be logged in as root. + 1. Shutdown the machine: `shutdown -p now` + +Helpful links + +* https://en.wikibooks.org/wiki/QEMU/Images +* https://blog.nekoconeko.nl/blog/2015/06/04/creating-an-openstack-freebsd-image.html +* https://www.freebsd.org/doc/handbook/serialconsole-setup.html + + +### QEMU setup - OpenBSD + +1. Download CD installer +2. `qemu-img create -f qcow2 foo.qcow2 2G` +3. `qemu -cdrom foo.iso -drive if=virtio,file=foo.qcow2 -net nic,model=virtio -net user` +4. run installer +5. `echo 'set tty com0' >> /etc/boot.conf` +6. `echo 'boot' >> /etc/boot.conf` +7. Modify /etc/ttys, change the `tty00` at the end from 'unknown off' to + 'vt220 on secure' +8. Modify same line in /etc/ttys to have `"/root/foo.sh"` as the shell +9. Add this script to `/root/foo.sh` + +``` +#!/bin/sh +exec 1>/dev/tty00 +exec 2>&1 + +if mount -t ext2fs /dev/sd1c /mnt; then + sh /mnt/run.sh /mnt + shutdown -ph now +fi + +# limited shell... +exec /bin/sh < /dev/tty00 +``` + +10. `chmod +x /root/foo.sh` + +Helpful links: + +* https://en.wikibooks.org/wiki/QEMU/Images +* http://www.openbsd.org/faq/faq7.html#SerCon + +# Questions? + +Hopefully that's at least somewhat of an introduction to everything going on +here, and feel free to ping @alexcrichton with questions! + diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/run-docker.sh cargo-0.26.0/vendor/libc-0.2.40/ci/run-docker.sh --- cargo-0.25.0/vendor/libc-0.2.40/ci/run-docker.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/run-docker.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,36 @@ +# Small script to run tests for a target (or all targets) inside all the +# respective docker images. + +set -ex + +run() { + echo $1 + # use -f so we can use ci/ as build context + docker build -t libc -f ci/docker/$1/Dockerfile ci/ + mkdir -p target + if [ -w /dev/kvm ]; then + kvm="--volume /dev/kvm:/dev/kvm" + fi + docker run \ + --user `id -u`:`id -g` \ + --rm \ + --init \ + --volume $HOME/.cargo:/cargo \ + $kvm \ + --env CARGO_HOME=/cargo \ + --volume `rustc --print sysroot`:/rust:ro \ + --volume `pwd`:/checkout:ro \ + --volume `pwd`/target:/checkout/target \ + --env CARGO_TARGET_DIR=/checkout/target \ + --workdir /checkout \ + libc \ + ci/run.sh $1 +} + +if [ -z "$1" ]; then + for d in `ls ci/docker/`; do + run $d + done +else + run $1 +fi diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/run-qemu.sh cargo-0.26.0/vendor/libc-0.2.40/ci/run-qemu.sh --- cargo-0.25.0/vendor/libc-0.2.40/ci/run-qemu.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/run-qemu.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,32 @@ +# Initial script which is run inside of all qemu images. The first argument to +# this script (as arranged by the qemu image itself) is the path to where the +# libc crate is mounted. +# +# For qemu images we currently need to install Rust manually as this wasn't done +# by the initial run-travis.sh script +# +# FIXME: feels like run-travis.sh should be responsible for downloading the +# compiler. + +set -ex + +ROOT=$1 +cp -r $ROOT/libc /tmp/libc +cd /tmp/libc + +TARGET=$(cat $ROOT/TARGET) +export CARGO_TARGET_DIR=/tmp + +case $TARGET in + *-openbsd) + pkg_add cargo gcc%4.9 rust + export CC=egcc + ;; + + *) + echo "Unknown target: $TARGET" + exit 1 + ;; +esac + +exec sh ci/run.sh $TARGET diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/run.sh cargo-0.26.0/vendor/libc-0.2.40/ci/run.sh --- cargo-0.25.0/vendor/libc-0.2.40/ci/run.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/run.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,90 @@ +#!/bin/sh + +# Builds and runs tests for a particular target passed as an argument to this +# script. + +set -ex + +TARGET=$1 + +# If we're going to run tests inside of a qemu image, then we don't need any of +# the scripts below. Instead, download the image, prepare a filesystem which has +# the current state of this repository, and then run the image. +# +# It's assume that all images, when run with two disks, will run the `run.sh` +# script from the second which we place inside. +if [ "$QEMU" != "" ]; then + tmpdir=/tmp/qemu-img-creation + mkdir -p $tmpdir + + if [ -z "${QEMU#*.gz}" ]; then + # image is .gz : download and uncompress it + qemufile=$(echo ${QEMU%.gz} | sed 's/\//__/g') + if [ ! -f $tmpdir/$qemufile ]; then + curl https://s3-us-west-1.amazonaws.com/rust-lang-ci2/libc/$QEMU | \ + gunzip -d > $tmpdir/$qemufile + fi + elif [ -z "${QEMU#*.xz}" ]; then + # image is .xz : download and uncompress it + qemufile=$(echo ${QEMU%.xz} | sed 's/\//__/g') + if [ ! -f $tmpdir/$qemufile ]; then + curl https://s3-us-west-1.amazonaws.com/rust-lang-ci2/libc/$QEMU | \ + unxz > $tmpdir/$qemufile + fi + else + # plain qcow2 image: just download it + qemufile=$(echo ${QEMU} | sed 's/\//__/g') + if [ ! -f $tmpdir/$qemufile ]; then + curl https://s3-us-west-1.amazonaws.com/rust-lang-ci2/libc/$QEMU \ + > $tmpdir/$qemufile + fi + fi + + # Create a mount a fresh new filesystem image that we'll later pass to QEMU. + # This will have a `run.sh` script will which use the artifacts inside to run + # on the host. + rm -f $tmpdir/libc-test.img + mkdir $tmpdir/mount + + # Do the standard rigamarole of cross-compiling an executable and then the + # script to run just executes the binary. + cargo build \ + --manifest-path libc-test/Cargo.toml \ + --target $TARGET \ + --test main + rm $CARGO_TARGET_DIR/$TARGET/debug/main-*.d + cp $CARGO_TARGET_DIR/$TARGET/debug/main-* $tmpdir/mount/libc-test + echo 'exec $1/libc-test' > $tmpdir/mount/run.sh + + du -sh $tmpdir/mount + genext2fs \ + --root $tmpdir/mount \ + --size-in-blocks 100000 \ + $tmpdir/libc-test.img + + # Pass -snapshot to prevent tampering with the disk images, this helps when + # running this script in development. The two drives are then passed next, + # first is the OS and second is the one we just made. Next the network is + # configured to work (I'm not entirely sure how), and then finally we turn off + # graphics and redirect the serial console output to out.log. + qemu-system-x86_64 \ + -m 1024 \ + -snapshot \ + -drive if=virtio,file=$tmpdir/$qemufile \ + -drive if=virtio,file=$tmpdir/libc-test.img \ + -net nic,model=virtio \ + -net user \ + -nographic \ + -vga none 2>&1 | tee $CARGO_TARGET_DIR/out.log + exec grep "^PASSED .* tests" $CARGO_TARGET_DIR/out.log +fi + +# FIXME: x86_64-unknown-linux-gnux32 fail to compile wihout --release +# See https://github.com/rust-lang/rust/issues/45417 +opt= +if [ "$TARGET" = "x86_64-unknown-linux-gnux32" ]; then + opt="--release" +fi + +cargo test $opt --no-default-features --manifest-path libc-test/Cargo.toml --target $TARGET +exec cargo test $opt --manifest-path libc-test/Cargo.toml --target $TARGET diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/runtest-android.rs cargo-0.26.0/vendor/libc-0.2.40/ci/runtest-android.rs --- cargo-0.25.0/vendor/libc-0.2.40/ci/runtest-android.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/runtest-android.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,41 @@ +use std::env; +use std::process::Command; +use std::path::{Path, PathBuf}; + +fn main() { + assert_eq!(env::args_os().len(), 2); + let test = PathBuf::from(env::args_os().nth(1).unwrap()); + let dst = Path::new("/data/local/tmp").join(test.file_name().unwrap()); + + let status = Command::new("adb") + .arg("wait-for-device") + .status() + .expect("failed to run rumprun-bake"); + assert!(status.success()); + + let status = Command::new("adb") + .arg("push") + .arg(&test) + .arg(&dst) + .status() + .expect("failed to run rumprun-bake"); + assert!(status.success()); + + let output = Command::new("adb") + .arg("shell") + .arg(&dst) + .output() + .expect("failed to run rumprun-bake"); + assert!(status.success()); + + println!("status: {}\nstdout ---\n{}\nstderr ---\n{}", + output.status, + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr)); + + let stdout = String::from_utf8_lossy(&output.stdout); + let mut lines = stdout.lines().filter(|l| l.starts_with("PASSED ")); + if !lines.any(|l| l.contains(" tests")) { + panic!("failed to find successful test run"); + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/style.rs cargo-0.26.0/vendor/libc-0.2.40/ci/style.rs --- cargo-0.25.0/vendor/libc-0.2.40/ci/style.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/style.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,204 @@ +//! Simple script to verify the coding style of this library +//! +//! ## How to run +//! +//! The first argument to this script is the directory to run on, so running +//! this script should be as simple as: +//! +//! ```notrust +//! rustc ci/style.rs +//! ./style src +//! ``` +//! +//! ## Guidelines +//! +//! The current style is: +//! +//! * No trailing whitespace +//! * No tabs +//! * 80-character lines +//! * `extern` instead of `extern "C"` +//! * Specific module layout: +//! 1. use directives +//! 2. typedefs +//! 3. structs +//! 4. constants +//! 5. f! { ... } functions +//! 6. extern functions +//! 7. modules + pub use +//! +//! Things not verified: +//! +//! * alignment +//! * 4-space tabs +//! * leading colons on paths + +use std::env; +use std::fs; +use std::io::prelude::*; +use std::path::Path; + +macro_rules! t { + ($e:expr) => (match $e { + Ok(e) => e, + Err(e) => panic!("{} failed with {}", stringify!($e), e), + }) +} + +fn main() { + let arg = env::args().skip(1).next().unwrap_or(".".to_string()); + + let mut errors = Errors { errs: false }; + walk(Path::new(&arg), &mut errors); + + if errors.errs { + panic!("found some lint errors"); + } else { + println!("good style!"); + } +} + +fn walk(path: &Path, err: &mut Errors) { + for entry in t!(path.read_dir()).map(|e| t!(e)) { + let path = entry.path(); + if t!(entry.file_type()).is_dir() { + walk(&path, err); + continue + } + + let name = entry.file_name().into_string().unwrap(); + match &name[..] { + n if !n.ends_with(".rs") => continue, + + "dox.rs" | + "lib.rs" | + "macros.rs" => continue, + + _ => {} + } + + let mut contents = String::new(); + t!(t!(fs::File::open(&path)).read_to_string(&mut contents)); + + check_style(&contents, &path, err); + } +} + +struct Errors { + errs: bool, +} + +#[derive(Clone, Copy, PartialEq)] +enum State { + Start, + Imports, + Typedefs, + Structs, + Constants, + FunctionDefinitions, + Functions, + Modules, +} + +fn check_style(file: &str, path: &Path, err: &mut Errors) { + let mut state = State::Start; + let mut s_macros = 0; + let mut f_macros = 0; + let mut prev_blank = false; + + for (i, line) in file.lines().enumerate() { + if line == "" { + if prev_blank { + err.error(path, i, "double blank line"); + } + prev_blank = true; + } else { + prev_blank = false; + } + if line != line.trim_right() { + err.error(path, i, "trailing whitespace"); + } + if line.contains("\t") { + err.error(path, i, "tab character"); + } + if line.len() > 80 { + err.error(path, i, "line longer than 80 chars"); + } + if line.contains("extern \"C\"") { + err.error(path, i, "use `extern` instead of `extern \"C\""); + } + if line.contains("#[cfg(") && !line.contains(" if ") { + if state != State::Structs { + err.error(path, i, "use cfg_if! and submodules \ + instead of #[cfg]"); + } + } + + let line = line.trim_left(); + let is_pub = line.starts_with("pub "); + let line = if is_pub {&line[4..]} else {line}; + + let line_state = if line.starts_with("use ") { + if is_pub { + State::Modules + } else { + State::Imports + } + } else if line.starts_with("const ") { + State::Constants + } else if line.starts_with("type ") { + State::Typedefs + } else if line.starts_with("s! {") { + s_macros += 1; + State::Structs + } else if line.starts_with("f! {") { + f_macros += 1; + State::FunctionDefinitions + } else if line.starts_with("extern ") { + State::Functions + } else if line.starts_with("mod ") { + State::Modules + } else { + continue + }; + + if state as usize > line_state as usize { + err.error(path, i, &format!("{} found after {} when \ + it belongs before", + line_state.desc(), state.desc())); + } + + if f_macros == 2 { + f_macros += 1; + err.error(path, i, "multiple f! macros in one module"); + } + if s_macros == 2 { + s_macros += 1; + err.error(path, i, "multiple s! macros in one module"); + } + + state = line_state; + } +} + +impl State { + fn desc(&self) -> &str { + match *self { + State::Start => "start", + State::Imports => "import", + State::Typedefs => "typedef", + State::Structs => "struct", + State::Constants => "constant", + State::FunctionDefinitions => "function definition", + State::Functions => "extern function", + State::Modules => "module", + } + } +} + +impl Errors { + fn error(&mut self, path: &Path, line: usize, msg: &str) { + self.errs = true; + println!("{}:{} - {}", path.display(), line + 1, msg); + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/ci/test-runner-linux cargo-0.26.0/vendor/libc-0.2.40/ci/test-runner-linux --- cargo-0.25.0/vendor/libc-0.2.40/ci/test-runner-linux 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/ci/test-runner-linux 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,23 @@ +#!/bin/sh + +set -e + +arch=$1 +prog=$2 + +cd /qemu/init +cp -f $2 prog +find . | cpio --create --format='newc' --quiet | gzip > ../initrd.gz +cd .. + +timeout 30s qemu-system-$arch \ + -m 1024 \ + -nographic \ + -kernel kernel \ + -initrd initrd.gz \ + -append init=/prog > output || true + +# remove kernel messages +tr -d '\r' < output | egrep -v '^\[' + +grep PASSED output > /dev/null diff -Nru cargo-0.25.0/vendor/libc-0.2.40/LICENSE-APACHE cargo-0.26.0/vendor/libc-0.2.40/LICENSE-APACHE --- cargo-0.25.0/vendor/libc-0.2.40/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/libc-0.2.40/LICENSE-MIT cargo-0.26.0/vendor/libc-0.2.40/LICENSE-MIT --- cargo-0.25.0/vendor/libc-0.2.40/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/libc-0.2.40/README.md cargo-0.26.0/vendor/libc-0.2.40/README.md --- cargo-0.25.0/vendor/libc-0.2.40/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,162 @@ +libc +==== + +A Rust library with native bindings to the types and functions commonly found on +various systems, including libc. + +[![Build Status](https://travis-ci.org/rust-lang/libc.svg?branch=master)](https://travis-ci.org/rust-lang/libc) +[![Build status](https://ci.appveyor.com/api/projects/status/github/rust-lang/libc?svg=true)](https://ci.appveyor.com/project/rust-lang-libs/libc) + +[Documentation](#platforms-and-documentation) + +## Usage + +First, add the following to your `Cargo.toml`: + +```toml +[dependencies] +libc = "0.2" +``` + +Next, add this to your crate root: + +```rust +extern crate libc; +``` + +Currently libc by default links to the standard library, but if you would +instead like to use libc in a `#![no_std]` situation or crate you can request +this via: + +```toml +[dependencies] +libc = { version = "0.2", default-features = false } +``` + +## What is libc? + +The primary purpose of this crate is to provide all of the definitions necessary +to easily interoperate with C code (or "C-like" code) on each of the platforms +that Rust supports. This includes type definitions (e.g. `c_int`), constants +(e.g. `EINVAL`) as well as function headers (e.g. `malloc`). + +This crate does not strive to have any form of compatibility across platforms, +but rather it is simply a straight binding to the system libraries on the +platform in question. + +## Public API + +This crate exports all underlying platform types, functions, and constants under +the crate root, so all items are accessible as `libc::foo`. The types and values +of all the exported APIs match the platform that libc is compiled for. + +More detailed information about the design of this library can be found in its +[associated RFC][rfc]. + +[rfc]: https://github.com/rust-lang/rfcs/blob/master/text/1291-promote-libc.md + +## Adding an API + +Want to use an API which currently isn't bound in `libc`? It's quite easy to add +one! + +The internal structure of this crate is designed to minimize the number of +`#[cfg]` attributes in order to easily be able to add new items which apply +to all platforms in the future. As a result, the crate is organized +hierarchically based on platform. Each module has a number of `#[cfg]`'d +children, but only one is ever actually compiled. Each module then reexports all +the contents of its children. + +This means that for each platform that libc supports, the path from a +leaf module to the root will contain all bindings for the platform in question. +Consequently, this indicates where an API should be added! Adding an API at a +particular level in the hierarchy means that it is supported on all the child +platforms of that level. For example, when adding a Unix API it should be added +to `src/unix/mod.rs`, but when adding a Linux-only API it should be added to +`src/unix/notbsd/linux/mod.rs`. + +If you're not 100% sure at what level of the hierarchy an API should be added +at, fear not! This crate has CI support which tests any binding against all +platforms supported, so you'll see failures if an API is added at the wrong +level or has different signatures across platforms. + +With that in mind, the steps for adding a new API are: + +1. Determine where in the module hierarchy your API should be added. +2. Add the API. +3. Send a PR to this repo. +4. Wait for CI to pass, fixing errors. +5. Wait for a merge! + +### Test before you commit + +We have two automated tests running on [Travis](https://travis-ci.org/rust-lang/libc): + +1. [`libc-test`](https://github.com/alexcrichton/ctest) + - `cd libc-test && cargo test` + - Use the `skip_*()` functions in `build.rs` if you really need a workaround. +2. Style checker + - `rustc ci/style.rs && ./style src` + +### Releasing your change to crates.io + +Now that you've done the amazing job of landing your new API or your new +platform in this crate, the next step is to get that sweet, sweet usage from +crates.io! The only next step is to bump the version of libc and then publish +it. If you'd like to get a release out ASAP you can follow these steps: + +1. Update the version number in `Cargo.toml`, you'll just be bumping the patch + version number. +2. Run `cargo update` to regenerate the lockfile to encode your version bump in + the lock file. You may pull in some other updated dependencies, that's ok. +3. Send a PR to this repository. It should [look like this][example], but it'd + also be nice to fill out the description with a small rationale for the + release (any rationale is ok though!) +4. Once merged the release will be tagged and published by one of the libc crate + maintainers. + +[example]: https://github.com/rust-lang/libc/pull/583 + +## Platforms and Documentation + +The following platforms are currently tested and have documentation available: + +Tested: + * [`i686-pc-windows-msvc`](https://doc.rust-lang.org/libc/i686-pc-windows-msvc/libc/) + * [`x86_64-pc-windows-msvc`](https://doc.rust-lang.org/libc/x86_64-pc-windows-msvc/libc/) + (Windows) + * [`i686-pc-windows-gnu`](https://doc.rust-lang.org/libc/i686-pc-windows-gnu/libc/) + * [`x86_64-pc-windows-gnu`](https://doc.rust-lang.org/libc/x86_64-pc-windows-gnu/libc/) + * [`i686-apple-darwin`](https://doc.rust-lang.org/libc/i686-apple-darwin/libc/) + * [`x86_64-apple-darwin`](https://doc.rust-lang.org/libc/x86_64-apple-darwin/libc/) + (OSX) + * `i386-apple-ios` + * `x86_64-apple-ios` + * [`i686-unknown-linux-gnu`](https://doc.rust-lang.org/libc/i686-unknown-linux-gnu/libc/) + * [`x86_64-unknown-linux-gnu`](https://doc.rust-lang.org/libc/x86_64-unknown-linux-gnu/libc/) + (Linux) + * [`x86_64-unknown-linux-musl`](https://doc.rust-lang.org/libc/x86_64-unknown-linux-musl/libc/) + (Linux MUSL) + * [`aarch64-unknown-linux-gnu`](https://doc.rust-lang.org/libc/aarch64-unknown-linux-gnu/libc/) + (Linux) + * `aarch64-unknown-linux-musl` + (Linux MUSL) + * [`sparc64-unknown-linux-gnu`](https://doc.rust-lang.org/libc/sparc64-unknown-linux-gnu/libc/) + (Linux) + * [`mips-unknown-linux-gnu`](https://doc.rust-lang.org/libc/mips-unknown-linux-gnu/libc/) + * [`arm-unknown-linux-gnueabihf`](https://doc.rust-lang.org/libc/arm-unknown-linux-gnueabihf/libc/) + * [`arm-linux-androideabi`](https://doc.rust-lang.org/libc/arm-linux-androideabi/libc/) + (Android) + * [`x86_64-unknown-freebsd`](https://doc.rust-lang.org/libc/x86_64-unknown-freebsd/libc/) + * [`x86_64-unknown-openbsd`](https://doc.rust-lang.org/libc/x86_64-unknown-openbsd/libc/) + * [`x86_64-rumprun-netbsd`](https://doc.rust-lang.org/libc/x86_64-unknown-netbsd/libc/) + +The following may be supported, but are not guaranteed to always work: + + * `i686-unknown-freebsd` + * [`x86_64-unknown-bitrig`](https://doc.rust-lang.org/libc/x86_64-unknown-bitrig/libc/) + * [`x86_64-unknown-dragonfly`](https://doc.rust-lang.org/libc/x86_64-unknown-dragonfly/libc/) + * `i686-unknown-haiku` + * `x86_64-unknown-haiku` + * [`x86_64-unknown-netbsd`](https://doc.rust-lang.org/libc/x86_64-unknown-netbsd/libc/) + * [`x86_64-sun-solaris`](https://doc.rust-lang.org/libc/x86_64-sun-solaris/libc/) diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/cloudabi/aarch64.rs cargo-0.26.0/vendor/libc-0.2.40/src/cloudabi/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/cloudabi/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/cloudabi/aarch64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,4 @@ +pub type c_char = u8; +pub type c_long = i64; +pub type c_ulong = u64; +pub type wchar_t = u32; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/cloudabi/arm.rs cargo-0.26.0/vendor/libc-0.2.40/src/cloudabi/arm.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/cloudabi/arm.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/cloudabi/arm.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,4 @@ +pub type c_char = u8; +pub type c_long = i32; +pub type c_ulong = u32; +pub type wchar_t = u32; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/cloudabi/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/cloudabi/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/cloudabi/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/cloudabi/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,166 @@ +pub type in_addr_t = u32; +pub type in_port_t = u16; +pub type pthread_key_t = usize; +pub type pthread_t = usize; +pub type sa_family_t = u8; +pub type socklen_t = usize; +pub type time_t = i64; + +s! { + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + pub ai_addrlen: ::socklen_t, + pub ai_addr: *mut ::sockaddr, + pub ai_canonname: *mut ::c_char, + pub ai_next: *mut addrinfo, + } + + pub struct in_addr { + pub s_addr: in_addr_t, + } + + pub struct in6_addr { + pub s6_addr: [u8; 16], + } + + pub struct pthread_attr_t { + __detachstate: ::c_int, + __stacksize: usize, + } + + pub struct sockaddr { + pub sa_family: sa_family_t, + pub sa_data: [::c_char; 0], + } + + pub struct sockaddr_in { + pub sin_family: ::sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + } + + pub struct sockaddr_in6 { + pub sin6_family: sa_family_t, + pub sin6_port: ::in_port_t, + pub sin6_flowinfo: u32, + pub sin6_addr: ::in6_addr, + pub sin6_scope_id: u32, + } + + pub struct sockaddr_storage { + pub ss_family: ::sa_family_t, + __ss_data: [u8; 32], + } +} + +pub const _SC_NPROCESSORS_ONLN: ::c_int = 52; +pub const _SC_PAGESIZE: ::c_int = 54; + +pub const AF_INET: ::c_int = 1; +pub const AF_INET6: ::c_int = 2; + +pub const EACCES: ::c_int = 2; +pub const EADDRINUSE: ::c_int = 3; +pub const EADDRNOTAVAIL: ::c_int = 4; +pub const EAGAIN: ::c_int = 6; +pub const ECONNABORTED: ::c_int = 13; +pub const ECONNREFUSED: ::c_int = 14; +pub const ECONNRESET: ::c_int = 15; +pub const EEXIST: ::c_int = 20; +pub const EINTR: ::c_int = 27; +pub const EINVAL: ::c_int = 28; +pub const ENOENT: ::c_int = 44; +pub const ENOTCONN: ::c_int = 53; +pub const EPERM: ::c_int = 63; +pub const EPIPE: ::c_int = 64; +pub const ETIMEDOUT: ::c_int = 73; +pub const EWOULDBLOCK: ::c_int = EAGAIN; + +pub const EAI_SYSTEM: ::c_int = 9; + +pub const EXIT_FAILURE: ::c_int = 1; +pub const EXIT_SUCCESS: ::c_int = 0; + +pub const PTHREAD_STACK_MIN: ::size_t = 1024; + +pub const SOCK_DGRAM: ::c_int = 128; +pub const SOCK_STREAM: ::c_int = 130; + +extern { + pub fn arc4random_buf(buf: *const ::c_void, len: ::size_t); + pub fn freeaddrinfo(res: *mut addrinfo); + pub fn gai_strerror(errcode: ::c_int) -> *const ::c_char; + pub fn getaddrinfo( + node: *const c_char, + service: *const c_char, + hints: *const addrinfo, + res: *mut *mut addrinfo, + ) -> ::c_int; + pub fn getsockopt( + sockfd: ::c_int, + level: ::c_int, + optname: ::c_int, + optval: *mut ::c_void, + optlen: *mut ::socklen_t, + ) -> ::c_int; + pub fn posix_memalign( + memptr: *mut *mut ::c_void, + align: ::size_t, + size: ::size_t, + ) -> ::c_int; + pub fn pthread_attr_destroy(attr: *mut ::pthread_attr_t) -> ::c_int; + pub fn pthread_attr_init(attr: *mut ::pthread_attr_t) -> ::c_int; + pub fn pthread_attr_setstacksize( + attr: *mut ::pthread_attr_t, + stack_size: ::size_t, + ) -> ::c_int; + pub fn pthread_create( + native: *mut ::pthread_t, + attr: *const ::pthread_attr_t, + f: extern fn(*mut ::c_void) -> *mut ::c_void, + value: *mut ::c_void, + ) -> ::c_int; + pub fn pthread_detach(thread: ::pthread_t) -> ::c_int; + pub fn pthread_getspecific(key: pthread_key_t) -> *mut ::c_void; + pub fn pthread_join( + native: ::pthread_t, + value: *mut *mut ::c_void, + ) -> ::c_int; + pub fn pthread_key_create( + key: *mut pthread_key_t, + dtor: Option, + ) -> ::c_int; + pub fn pthread_key_delete(key: pthread_key_t) -> ::c_int; + pub fn pthread_setspecific( + key: pthread_key_t, + value: *const ::c_void, + ) -> ::c_int; + pub fn send( + socket: ::c_int, + buf: *const ::c_void, + len: ::size_t, + flags: ::c_int, + ) -> ::ssize_t; + pub fn sysconf(name: ::c_int) -> ::c_long; +} + +cfg_if! { + if #[cfg(target_arch = "aarch64")] { + mod aarch64; + pub use self::aarch64::*; + } else if #[cfg(any(target_arch = "arm"))] { + mod arm; + pub use self::arm::*; + } else if #[cfg(any(target_arch = "x86"))] { + mod x86; + pub use self::x86::*; + } else if #[cfg(any(target_arch = "x86_64"))] { + mod x86_64; + pub use self::x86_64::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/cloudabi/x86_64.rs cargo-0.26.0/vendor/libc-0.2.40/src/cloudabi/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/cloudabi/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/cloudabi/x86_64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,4 @@ +pub type c_char = i8; +pub type c_long = i64; +pub type c_ulong = u64; +pub type wchar_t = i32; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/cloudabi/x86.rs cargo-0.26.0/vendor/libc-0.2.40/src/cloudabi/x86.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/cloudabi/x86.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/cloudabi/x86.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,4 @@ +pub type c_char = i8; +pub type c_long = i32; +pub type c_ulong = u32; +pub type wchar_t = i32; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/dox.rs cargo-0.26.0/vendor/libc-0.2.40/src/dox.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/dox.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/dox.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,151 @@ +pub use self::imp::*; + +#[cfg(not(cross_platform_docs))] +mod imp { + pub use core::option::Option; + pub use core::clone::Clone; + pub use core::marker::Copy; + pub use core::mem; +} + +#[cfg(cross_platform_docs)] +mod imp { + pub enum Option { + Some(T), + None, + } + impl Copy for Option {} + impl Clone for Option { + fn clone(&self) -> Option { loop {} } + } + + pub trait Clone { + fn clone(&self) -> Self; + } + + #[lang = "copy"] + pub trait Copy {} + + #[lang = "freeze"] + pub trait Freeze {} + + #[lang = "sync"] + pub trait Sync {} + impl Sync for T {} + + #[lang = "sized"] + pub trait Sized {} + + macro_rules! each_int { + ($mac:ident) => ( + $mac!(u8); + $mac!(u16); + $mac!(u32); + $mac!(u64); + $mac!(usize); + each_signed_int!($mac); + ) + } + + macro_rules! each_signed_int { + ($mac:ident) => ( + $mac!(i8); + $mac!(i16); + $mac!(i32); + $mac!(i64); + $mac!(isize); + ) + } + + #[lang = "div"] + pub trait Div { + type Output; + fn div(self, rhs: RHS) -> Self::Output; + } + + #[lang = "shl"] + pub trait Shl { + type Output; + fn shl(self, rhs: RHS) -> Self::Output; + } + + #[lang = "mul"] + pub trait Mul { + type Output; + fn mul(self, rhs: RHS) -> Self::Output; + } + + #[lang = "sub"] + pub trait Sub { + type Output; + fn sub(self, rhs: RHS) -> Self::Output; + } + + #[lang = "bitor"] + pub trait Bitor { + type Output; + fn bitor(self, rhs: RHS) -> Self::Output; + } + + #[lang = "neg"] + pub trait Neg { + type Output; + fn neg(self) -> Self::Output; + } + + #[lang = "not"] + pub trait Not { + type Output; + fn not(self) -> Self::Output; + } + + #[lang = "add"] + pub trait Add { + type Output; + fn add(self, r: RHS) -> Self::Output; + } + + macro_rules! impl_traits { + ($($i:ident)*) => ($( + impl Div<$i> for $i { + type Output = $i; + fn div(self, rhs: $i) -> $i { self / rhs } + } + impl Shl<$i> for $i { + type Output = $i; + fn shl(self, rhs: $i) -> $i { self << rhs } + } + impl Mul for $i { + type Output = $i; + fn mul(self, rhs: $i) -> $i { self * rhs } + } + + impl Sub for $i { + type Output = $i; + fn sub(self, rhs: $i) -> $i { self - rhs } + } + impl Bitor for $i { + type Output = $i; + fn bitor(self, rhs: $i) -> $i { self | rhs } + } + impl Neg for $i { + type Output = $i; + fn neg(self) -> $i { -self } + } + impl Not for $i { + type Output = $i; + fn not(self) -> $i { !self } + } + impl Add<$i> for $i { + type Output = $i; + fn add(self, other: $i) -> $i { self + other } + } + )*) + } + each_int!(impl_traits); + + pub mod mem { + pub fn size_of_val(_: &T) -> usize { 4 } + pub fn size_of(_: &T) -> usize { 4 } + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/fuchsia/aarch64.rs cargo-0.26.0/vendor/libc-0.2.40/src/fuchsia/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/fuchsia/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/fuchsia/aarch64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,336 @@ +pub type c_char = u8; +pub type __u64 = ::c_ulonglong; +pub type wchar_t = u32; +pub type nlink_t = u32; +pub type blksize_t = ::c_int; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad0: ::c_ulong, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + __pad1: ::c_int, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused: [::c_uint; 2], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad0: ::c_ulong, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + __pad1: ::c_int, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused: [::c_uint; 2], + } + + pub struct ipc_perm { + pub __ipc_perm_key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + pub __seq: ::c_ushort, + __unused1: ::c_ulong, + __unused2: ::c_ulong, + } +} + +pub const MINSIGSTKSZ: ::size_t = 6144; +pub const SIGSTKSZ: ::size_t = 12288; + +#[doc(hidden)] +pub const PF_MAX: ::c_int = 43; +#[doc(hidden)] +pub const AF_MAX: ::c_int = PF_MAX; + +pub const SYS_io_setup: ::c_long = 0; +pub const SYS_io_destroy: ::c_long = 1; +pub const SYS_io_submit: ::c_long = 2; +pub const SYS_io_cancel: ::c_long = 3; +pub const SYS_io_getevents: ::c_long = 4; +pub const SYS_setxattr: ::c_long = 5; +pub const SYS_lsetxattr: ::c_long = 6; +pub const SYS_fsetxattr: ::c_long = 7; +pub const SYS_getxattr: ::c_long = 8; +pub const SYS_lgetxattr: ::c_long = 9; +pub const SYS_fgetxattr: ::c_long = 10; +pub const SYS_listxattr: ::c_long = 11; +pub const SYS_llistxattr: ::c_long = 12; +pub const SYS_flistxattr: ::c_long = 13; +pub const SYS_removexattr: ::c_long = 14; +pub const SYS_lremovexattr: ::c_long = 15; +pub const SYS_fremovexattr: ::c_long = 16; +pub const SYS_getcwd: ::c_long = 17; +pub const SYS_lookup_dcookie: ::c_long = 18; +pub const SYS_eventfd2: ::c_long = 19; +pub const SYS_epoll_create1: ::c_long = 20; +pub const SYS_epoll_ctl: ::c_long = 21; +pub const SYS_epoll_pwait: ::c_long = 22; +pub const SYS_dup: ::c_long = 23; +pub const SYS_dup3: ::c_long = 24; +pub const SYS_inotify_init1: ::c_long = 26; +pub const SYS_inotify_add_watch: ::c_long = 27; +pub const SYS_inotify_rm_watch: ::c_long = 28; +pub const SYS_ioctl: ::c_long = 29; +pub const SYS_ioprio_set: ::c_long = 30; +pub const SYS_ioprio_get: ::c_long = 31; +pub const SYS_flock: ::c_long = 32; +pub const SYS_mknodat: ::c_long = 33; +pub const SYS_mkdirat: ::c_long = 34; +pub const SYS_unlinkat: ::c_long = 35; +pub const SYS_symlinkat: ::c_long = 36; +pub const SYS_linkat: ::c_long = 37; +pub const SYS_renameat: ::c_long = 38; +pub const SYS_umount2: ::c_long = 39; +pub const SYS_mount: ::c_long = 40; +pub const SYS_pivot_root: ::c_long = 41; +pub const SYS_nfsservctl: ::c_long = 42; +pub const SYS_fallocate: ::c_long = 47; +pub const SYS_faccessat: ::c_long = 48; +pub const SYS_chdir: ::c_long = 49; +pub const SYS_fchdir: ::c_long = 50; +pub const SYS_chroot: ::c_long = 51; +pub const SYS_fchmod: ::c_long = 52; +pub const SYS_fchmodat: ::c_long = 53; +pub const SYS_fchownat: ::c_long = 54; +pub const SYS_fchown: ::c_long = 55; +pub const SYS_openat: ::c_long = 56; +pub const SYS_close: ::c_long = 57; +pub const SYS_vhangup: ::c_long = 58; +pub const SYS_pipe2: ::c_long = 59; +pub const SYS_quotactl: ::c_long = 60; +pub const SYS_getdents64: ::c_long = 61; +pub const SYS_read: ::c_long = 63; +pub const SYS_write: ::c_long = 64; +pub const SYS_readv: ::c_long = 65; +pub const SYS_writev: ::c_long = 66; +pub const SYS_pread64: ::c_long = 67; +pub const SYS_pwrite64: ::c_long = 68; +pub const SYS_preadv: ::c_long = 69; +pub const SYS_pwritev: ::c_long = 70; +pub const SYS_pselect6: ::c_long = 72; +pub const SYS_ppoll: ::c_long = 73; +pub const SYS_signalfd4: ::c_long = 74; +pub const SYS_vmsplice: ::c_long = 75; +pub const SYS_splice: ::c_long = 76; +pub const SYS_tee: ::c_long = 77; +pub const SYS_readlinkat: ::c_long = 78; +pub const SYS_sync: ::c_long = 81; +pub const SYS_fsync: ::c_long = 82; +pub const SYS_fdatasync: ::c_long = 83; +pub const SYS_sync_file_range: ::c_long = 84; +pub const SYS_timerfd_create: ::c_long = 85; +pub const SYS_timerfd_settime: ::c_long = 86; +pub const SYS_timerfd_gettime: ::c_long = 87; +pub const SYS_utimensat: ::c_long = 88; +pub const SYS_acct: ::c_long = 89; +pub const SYS_capget: ::c_long = 90; +pub const SYS_capset: ::c_long = 91; +pub const SYS_personality: ::c_long = 92; +pub const SYS_exit: ::c_long = 93; +pub const SYS_exit_group: ::c_long = 94; +pub const SYS_waitid: ::c_long = 95; +pub const SYS_set_tid_address: ::c_long = 96; +pub const SYS_unshare: ::c_long = 97; +pub const SYS_futex: ::c_long = 98; +pub const SYS_set_robust_list: ::c_long = 99; +pub const SYS_get_robust_list: ::c_long = 100; +pub const SYS_nanosleep: ::c_long = 101; +pub const SYS_getitimer: ::c_long = 102; +pub const SYS_setitimer: ::c_long = 103; +pub const SYS_kexec_load: ::c_long = 104; +pub const SYS_init_module: ::c_long = 105; +pub const SYS_delete_module: ::c_long = 106; +pub const SYS_timer_create: ::c_long = 107; +pub const SYS_timer_gettime: ::c_long = 108; +pub const SYS_timer_getoverrun: ::c_long = 109; +pub const SYS_timer_settime: ::c_long = 110; +pub const SYS_timer_delete: ::c_long = 111; +pub const SYS_clock_settime: ::c_long = 112; +pub const SYS_clock_gettime: ::c_long = 113; +pub const SYS_clock_getres: ::c_long = 114; +pub const SYS_clock_nanosleep: ::c_long = 115; +pub const SYS_syslog: ::c_long = 116; +pub const SYS_ptrace: ::c_long = 117; +pub const SYS_sched_setparam: ::c_long = 118; +pub const SYS_sched_setscheduler: ::c_long = 119; +pub const SYS_sched_getscheduler: ::c_long = 120; +pub const SYS_sched_getparam: ::c_long = 121; +pub const SYS_sched_setaffinity: ::c_long = 122; +pub const SYS_sched_getaffinity: ::c_long = 123; +pub const SYS_sched_yield: ::c_long = 124; +pub const SYS_sched_get_priority_max: ::c_long = 125; +pub const SYS_sched_get_priority_min: ::c_long = 126; +pub const SYS_sched_rr_get_interval: ::c_long = 127; +pub const SYS_restart_syscall: ::c_long = 128; +pub const SYS_kill: ::c_long = 129; +pub const SYS_tkill: ::c_long = 130; +pub const SYS_tgkill: ::c_long = 131; +pub const SYS_sigaltstack: ::c_long = 132; +pub const SYS_rt_sigsuspend: ::c_long = 133; +pub const SYS_rt_sigaction: ::c_long = 134; +pub const SYS_rt_sigprocmask: ::c_long = 135; +pub const SYS_rt_sigpending: ::c_long = 136; +pub const SYS_rt_sigtimedwait: ::c_long = 137; +pub const SYS_rt_sigqueueinfo: ::c_long = 138; +pub const SYS_rt_sigreturn: ::c_long = 139; +pub const SYS_setpriority: ::c_long = 140; +pub const SYS_getpriority: ::c_long = 141; +pub const SYS_reboot: ::c_long = 142; +pub const SYS_setregid: ::c_long = 143; +pub const SYS_setgid: ::c_long = 144; +pub const SYS_setreuid: ::c_long = 145; +pub const SYS_setuid: ::c_long = 146; +pub const SYS_setresuid: ::c_long = 147; +pub const SYS_getresuid: ::c_long = 148; +pub const SYS_setresgid: ::c_long = 149; +pub const SYS_getresgid: ::c_long = 150; +pub const SYS_setfsuid: ::c_long = 151; +pub const SYS_setfsgid: ::c_long = 152; +pub const SYS_times: ::c_long = 153; +pub const SYS_setpgid: ::c_long = 154; +pub const SYS_getpgid: ::c_long = 155; +pub const SYS_getsid: ::c_long = 156; +pub const SYS_setsid: ::c_long = 157; +pub const SYS_getgroups: ::c_long = 158; +pub const SYS_setgroups: ::c_long = 159; +pub const SYS_uname: ::c_long = 160; +pub const SYS_sethostname: ::c_long = 161; +pub const SYS_setdomainname: ::c_long = 162; +pub const SYS_getrlimit: ::c_long = 163; +pub const SYS_setrlimit: ::c_long = 164; +pub const SYS_getrusage: ::c_long = 165; +pub const SYS_umask: ::c_long = 166; +pub const SYS_prctl: ::c_long = 167; +pub const SYS_getcpu: ::c_long = 168; +pub const SYS_gettimeofday: ::c_long = 169; +pub const SYS_settimeofday: ::c_long = 170; +pub const SYS_adjtimex: ::c_long = 171; +pub const SYS_getpid: ::c_long = 172; +pub const SYS_getppid: ::c_long = 173; +pub const SYS_getuid: ::c_long = 174; +pub const SYS_geteuid: ::c_long = 175; +pub const SYS_getgid: ::c_long = 176; +pub const SYS_getegid: ::c_long = 177; +pub const SYS_gettid: ::c_long = 178; +pub const SYS_sysinfo: ::c_long = 179; +pub const SYS_mq_open: ::c_long = 180; +pub const SYS_mq_unlink: ::c_long = 181; +pub const SYS_mq_timedsend: ::c_long = 182; +pub const SYS_mq_timedreceive: ::c_long = 183; +pub const SYS_mq_notify: ::c_long = 184; +pub const SYS_mq_getsetattr: ::c_long = 185; +pub const SYS_msgget: ::c_long = 186; +pub const SYS_msgctl: ::c_long = 187; +pub const SYS_msgrcv: ::c_long = 188; +pub const SYS_msgsnd: ::c_long = 189; +pub const SYS_semget: ::c_long = 190; +pub const SYS_semctl: ::c_long = 191; +pub const SYS_semtimedop: ::c_long = 192; +pub const SYS_semop: ::c_long = 193; +pub const SYS_shmget: ::c_long = 194; +pub const SYS_shmctl: ::c_long = 195; +pub const SYS_shmat: ::c_long = 196; +pub const SYS_shmdt: ::c_long = 197; +pub const SYS_socket: ::c_long = 198; +pub const SYS_socketpair: ::c_long = 199; +pub const SYS_bind: ::c_long = 200; +pub const SYS_listen: ::c_long = 201; +pub const SYS_accept: ::c_long = 202; +pub const SYS_connect: ::c_long = 203; +pub const SYS_getsockname: ::c_long = 204; +pub const SYS_getpeername: ::c_long = 205; +pub const SYS_sendto: ::c_long = 206; +pub const SYS_recvfrom: ::c_long = 207; +pub const SYS_setsockopt: ::c_long = 208; +pub const SYS_getsockopt: ::c_long = 209; +pub const SYS_shutdown: ::c_long = 210; +pub const SYS_sendmsg: ::c_long = 211; +pub const SYS_recvmsg: ::c_long = 212; +pub const SYS_readahead: ::c_long = 213; +pub const SYS_brk: ::c_long = 214; +pub const SYS_munmap: ::c_long = 215; +pub const SYS_mremap: ::c_long = 216; +pub const SYS_add_key: ::c_long = 217; +pub const SYS_request_key: ::c_long = 218; +pub const SYS_keyctl: ::c_long = 219; +pub const SYS_clone: ::c_long = 220; +pub const SYS_execve: ::c_long = 221; +pub const SYS_swapon: ::c_long = 224; +pub const SYS_swapoff: ::c_long = 225; +pub const SYS_mprotect: ::c_long = 226; +pub const SYS_msync: ::c_long = 227; +pub const SYS_mlock: ::c_long = 228; +pub const SYS_munlock: ::c_long = 229; +pub const SYS_mlockall: ::c_long = 230; +pub const SYS_munlockall: ::c_long = 231; +pub const SYS_mincore: ::c_long = 232; +pub const SYS_madvise: ::c_long = 233; +pub const SYS_remap_file_pages: ::c_long = 234; +pub const SYS_mbind: ::c_long = 235; +pub const SYS_get_mempolicy: ::c_long = 236; +pub const SYS_set_mempolicy: ::c_long = 237; +pub const SYS_migrate_pages: ::c_long = 238; +pub const SYS_move_pages: ::c_long = 239; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 240; +pub const SYS_perf_event_open: ::c_long = 241; +pub const SYS_accept4: ::c_long = 242; +pub const SYS_recvmmsg: ::c_long = 243; +pub const SYS_wait4: ::c_long = 260; +pub const SYS_prlimit64: ::c_long = 261; +pub const SYS_fanotify_init: ::c_long = 262; +pub const SYS_fanotify_mark: ::c_long = 263; +pub const SYS_name_to_handle_at: ::c_long = 264; +pub const SYS_open_by_handle_at: ::c_long = 265; +pub const SYS_clock_adjtime: ::c_long = 266; +pub const SYS_syncfs: ::c_long = 267; +pub const SYS_setns: ::c_long = 268; +pub const SYS_sendmmsg: ::c_long = 269; +pub const SYS_process_vm_readv: ::c_long = 270; +pub const SYS_process_vm_writev: ::c_long = 271; +pub const SYS_kcmp: ::c_long = 272; +pub const SYS_finit_module: ::c_long = 273; +pub const SYS_sched_setattr: ::c_long = 274; +pub const SYS_sched_getattr: ::c_long = 275; +pub const SYS_renameat2: ::c_long = 276; +pub const SYS_seccomp: ::c_long = 277; +pub const SYS_getrandom: ::c_long = 278; +pub const SYS_memfd_create: ::c_long = 279; +pub const SYS_bpf: ::c_long = 280; +pub const SYS_execveat: ::c_long = 281; +pub const SYS_userfaultfd: ::c_long = 282; +pub const SYS_membarrier: ::c_long = 283; +pub const SYS_mlock2: ::c_long = 284; +pub const SYS_copy_file_range: ::c_long = 285; +pub const SYS_preadv2: ::c_long = 286; +pub const SYS_pwritev2: ::c_long = 287; +pub const SYS_pkey_mprotect: ::c_long = 288; +pub const SYS_pkey_alloc: ::c_long = 289; +pub const SYS_pkey_free: ::c_long = 290; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/fuchsia/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/fuchsia/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/fuchsia/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/fuchsia/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3925 @@ +//! Definitions found commonly among almost all Unix derivatives +//! +//! More functions and definitions can be found in the more specific modules +//! according to the platform in question. + +use dox::{mem, Option}; + +// PUB_TYPE + +pub type pid_t = i32; +pub type uid_t = u32; +pub type gid_t = u32; +pub type in_addr_t = u32; +pub type in_port_t = u16; +pub type sighandler_t = ::size_t; +pub type cc_t = ::c_uchar; +pub type sa_family_t = u16; +pub type pthread_key_t = ::c_uint; +pub type speed_t = ::c_uint; +pub type tcflag_t = ::c_uint; +pub type clockid_t = ::c_int; +pub type key_t = ::c_int; +pub type id_t = ::c_uint; +pub type useconds_t = u32; +pub type dev_t = u64; +pub type socklen_t = u32; +pub type pthread_t = c_ulong; +pub type mode_t = u32; +pub type ino64_t = u64; +pub type off64_t = i64; +pub type blkcnt64_t = i64; +pub type rlim64_t = u64; +pub type mqd_t = ::c_int; +pub type nfds_t = ::c_ulong; +pub type nl_item = ::c_int; +pub type idtype_t = ::c_uint; +pub type loff_t = ::c_longlong; + +pub type __u8 = ::c_uchar; +pub type __u16 = ::c_ushort; +pub type __s16 = ::c_short; +pub type __u32 = ::c_uint; +pub type __s32 = ::c_int; + +pub type Elf32_Half = u16; +pub type Elf32_Word = u32; +pub type Elf32_Off = u32; +pub type Elf32_Addr = u32; + +pub type Elf64_Half = u16; +pub type Elf64_Word = u32; +pub type Elf64_Off = u64; +pub type Elf64_Addr = u64; +pub type Elf64_Xword = u64; + +pub type clock_t = c_long; +pub type time_t = c_long; +pub type suseconds_t = c_long; +pub type ino_t = u64; +pub type off_t = i64; +pub type blkcnt_t = i64; + +pub type shmatt_t = ::c_ulong; +pub type msgqnum_t = ::c_ulong; +pub type msglen_t = ::c_ulong; +pub type fsblkcnt_t = ::c_ulonglong; +pub type fsfilcnt_t = ::c_ulonglong; +pub type rlim_t = ::c_ulonglong; + +pub type c_long = i64; +pub type c_ulong = u64; + +// FIXME: why are these uninhabited types? that seems... wrong? +// Presumably these should be `()` or an `extern type` (when that stabilizes). +pub enum timezone {} +pub enum DIR {} +pub enum locale_t {} +pub enum fpos64_t {} // TODO: fill this out with a struct + +// PUB_STRUCT + +s! { + pub struct group { + pub gr_name: *mut ::c_char, + pub gr_passwd: *mut ::c_char, + pub gr_gid: ::gid_t, + pub gr_mem: *mut *mut ::c_char, + } + + pub struct utimbuf { + pub actime: time_t, + pub modtime: time_t, + } + + pub struct timeval { + pub tv_sec: time_t, + pub tv_usec: suseconds_t, + } + + // linux x32 compatibility + // See https://sourceware.org/bugzilla/show_bug.cgi?id=16437 + pub struct timespec { + pub tv_sec: time_t, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + pub tv_nsec: i64, + #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] + pub tv_nsec: ::c_long, + } + + pub struct rlimit { + pub rlim_cur: rlim_t, + pub rlim_max: rlim_t, + } + + pub struct rusage { + pub ru_utime: timeval, + pub ru_stime: timeval, + pub ru_maxrss: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad1: u32, + pub ru_ixrss: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad2: u32, + pub ru_idrss: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad3: u32, + pub ru_isrss: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad4: u32, + pub ru_minflt: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad5: u32, + pub ru_majflt: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad6: u32, + pub ru_nswap: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad7: u32, + pub ru_inblock: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad8: u32, + pub ru_oublock: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad9: u32, + pub ru_msgsnd: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad10: u32, + pub ru_msgrcv: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad11: u32, + pub ru_nsignals: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad12: u32, + pub ru_nvcsw: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad13: u32, + pub ru_nivcsw: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad14: u32, + + #[cfg(any(target_env = "musl", target_os = "emscripten"))] + __reserved: [c_long; 16], + } + + pub struct in_addr { + pub s_addr: in_addr_t, + } + + pub struct in6_addr { + pub s6_addr: [u8; 16], + __align: [u32; 0], + } + + pub struct ip_mreq { + pub imr_multiaddr: in_addr, + pub imr_interface: in_addr, + } + + pub struct ipv6_mreq { + pub ipv6mr_multiaddr: in6_addr, + #[cfg(target_os = "android")] + pub ipv6mr_interface: ::c_int, + #[cfg(not(target_os = "android"))] + pub ipv6mr_interface: ::c_uint, + } + + pub struct hostent { + pub h_name: *mut ::c_char, + pub h_aliases: *mut *mut ::c_char, + pub h_addrtype: ::c_int, + pub h_length: ::c_int, + pub h_addr_list: *mut *mut ::c_char, + } + + pub struct iovec { + pub iov_base: *mut ::c_void, + pub iov_len: ::size_t, + } + + pub struct pollfd { + pub fd: ::c_int, + pub events: ::c_short, + pub revents: ::c_short, + } + + pub struct winsize { + pub ws_row: ::c_ushort, + pub ws_col: ::c_ushort, + pub ws_xpixel: ::c_ushort, + pub ws_ypixel: ::c_ushort, + } + + pub struct linger { + pub l_onoff: ::c_int, + pub l_linger: ::c_int, + } + + pub struct sigval { + // Actually a union of an int and a void* + pub sival_ptr: *mut ::c_void + } + + // + pub struct itimerval { + pub it_interval: ::timeval, + pub it_value: ::timeval, + } + + // + pub struct tms { + pub tms_utime: ::clock_t, + pub tms_stime: ::clock_t, + pub tms_cutime: ::clock_t, + pub tms_cstime: ::clock_t, + } + + pub struct servent { + pub s_name: *mut ::c_char, + pub s_aliases: *mut *mut ::c_char, + pub s_port: ::c_int, + pub s_proto: *mut ::c_char, + } + + pub struct protoent { + pub p_name: *mut ::c_char, + pub p_aliases: *mut *mut ::c_char, + pub p_proto: ::c_int, + } + + pub struct aiocb { + pub aio_fildes: ::c_int, + pub aio_lio_opcode: ::c_int, + pub aio_reqprio: ::c_int, + pub aio_buf: *mut ::c_void, + pub aio_nbytes: ::size_t, + pub aio_sigevent: ::sigevent, + __td: *mut ::c_void, + __lock: [::c_int; 2], + __err: ::c_int, + __ret: ::ssize_t, + pub aio_offset: off_t, + __next: *mut ::c_void, + __prev: *mut ::c_void, + #[cfg(target_pointer_width = "32")] + __dummy4: [::c_char; 24], + #[cfg(target_pointer_width = "64")] + __dummy4: [::c_char; 16], + } + + pub struct sigaction { + pub sa_sigaction: ::sighandler_t, + pub sa_mask: ::sigset_t, + pub sa_flags: ::c_int, + pub sa_restorer: ::dox::Option, + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; ::NCCS], + pub __c_ispeed: ::speed_t, + pub __c_ospeed: ::speed_t, + } + + pub struct flock { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_pid: ::pid_t, + } + + pub struct sysinfo { + pub uptime: ::c_ulong, + pub loads: [::c_ulong; 3], + pub totalram: ::c_ulong, + pub freeram: ::c_ulong, + pub sharedram: ::c_ulong, + pub bufferram: ::c_ulong, + pub totalswap: ::c_ulong, + pub freeswap: ::c_ulong, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: ::c_ulong, + pub freehigh: ::c_ulong, + pub mem_unit: ::c_uint, + pub __reserved: [::c_char; 256], + } + + pub struct ucred { + pub pid: ::pid_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + } + + pub struct sockaddr { + pub sa_family: sa_family_t, + pub sa_data: [::c_char; 14], + } + + pub struct sockaddr_in { + pub sin_family: sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + pub sin_zero: [u8; 8], + } + + pub struct sockaddr_in6 { + pub sin6_family: sa_family_t, + pub sin6_port: ::in_port_t, + pub sin6_flowinfo: u32, + pub sin6_addr: ::in6_addr, + pub sin6_scope_id: u32, + } + + pub struct sockaddr_un { + pub sun_family: sa_family_t, + pub sun_path: [::c_char; 108] + } + + pub struct sockaddr_storage { + pub ss_family: sa_family_t, + __ss_align: ::size_t, + __ss_pad2: [u8; 128 - 2 * 8], + } + + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + pub ai_addrlen: socklen_t, + + pub ai_addr: *mut ::sockaddr, + + pub ai_canonname: *mut c_char, + + pub ai_next: *mut addrinfo, + } + + pub struct sockaddr_nl { + pub nl_family: ::sa_family_t, + nl_pad: ::c_ushort, + pub nl_pid: u32, + pub nl_groups: u32 + } + + pub struct sockaddr_ll { + pub sll_family: ::c_ushort, + pub sll_protocol: ::c_ushort, + pub sll_ifindex: ::c_int, + pub sll_hatype: ::c_ushort, + pub sll_pkttype: ::c_uchar, + pub sll_halen: ::c_uchar, + pub sll_addr: [::c_uchar; 8] + } + + pub struct fd_set { + fds_bits: [::c_ulong; FD_SETSIZE / ULONG_SIZE], + } + + pub struct tm { + pub tm_sec: ::c_int, + pub tm_min: ::c_int, + pub tm_hour: ::c_int, + pub tm_mday: ::c_int, + pub tm_mon: ::c_int, + pub tm_year: ::c_int, + pub tm_wday: ::c_int, + pub tm_yday: ::c_int, + pub tm_isdst: ::c_int, + pub tm_gmtoff: ::c_long, + pub tm_zone: *const ::c_char, + } + + pub struct sched_param { + pub sched_priority: ::c_int, + #[cfg(target_env = "musl")] + pub sched_ss_low_priority: ::c_int, + #[cfg(target_env = "musl")] + pub sched_ss_repl_period: ::timespec, + #[cfg(target_env = "musl")] + pub sched_ss_init_budget: ::timespec, + #[cfg(target_env = "musl")] + pub sched_ss_max_repl: ::c_int, + } + + pub struct Dl_info { + pub dli_fname: *const ::c_char, + pub dli_fbase: *mut ::c_void, + pub dli_sname: *const ::c_char, + pub dli_saddr: *mut ::c_void, + } + + #[cfg_attr(any(all(target_arch = "x86", + not(target_env = "musl"), + not(target_os = "android")), + target_arch = "x86_64"), + repr(packed))] + pub struct epoll_event { + pub events: ::uint32_t, + pub u64: ::uint64_t, + } + + pub struct utsname { + pub sysname: [::c_char; 65], + pub nodename: [::c_char; 65], + pub release: [::c_char; 65], + pub version: [::c_char; 65], + pub machine: [::c_char; 65], + pub domainname: [::c_char; 65] + } + + pub struct lconv { + pub decimal_point: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + pub grouping: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub currency_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub int_frac_digits: ::c_char, + pub frac_digits: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + pub n_sign_posn: ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_n_cs_precedes: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + pub int_n_sign_posn: ::c_char, + } + + pub struct sigevent { + pub sigev_value: ::sigval, + pub sigev_signo: ::c_int, + pub sigev_notify: ::c_int, + // Actually a union. We only expose sigev_notify_thread_id because it's + // the most useful member + pub sigev_notify_thread_id: ::c_int, + #[cfg(target_pointer_width = "64")] + __unused1: [::c_int; 11], + #[cfg(target_pointer_width = "32")] + __unused1: [::c_int; 12] + } + + pub struct dirent { + pub d_ino: ::ino_t, + pub d_off: ::off_t, + pub d_reclen: ::c_ushort, + pub d_type: ::c_uchar, + pub d_name: [::c_char; 256], + } + + pub struct dirent64 { + pub d_ino: ::ino64_t, + pub d_off: ::off64_t, + pub d_reclen: ::c_ushort, + pub d_type: ::c_uchar, + pub d_name: [::c_char; 256], + } + + pub struct rlimit64 { + pub rlim_cur: rlim64_t, + pub rlim_max: rlim64_t, + } + + pub struct glob_t { + pub gl_pathc: ::size_t, + pub gl_pathv: *mut *mut c_char, + pub gl_offs: ::size_t, + pub gl_flags: ::c_int, + + __unused1: *mut ::c_void, + __unused2: *mut ::c_void, + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + } + + pub struct ifaddrs { + pub ifa_next: *mut ifaddrs, + pub ifa_name: *mut c_char, + pub ifa_flags: ::c_uint, + pub ifa_addr: *mut ::sockaddr, + pub ifa_netmask: *mut ::sockaddr, + pub ifa_ifu: *mut ::sockaddr, // FIXME This should be a union + pub ifa_data: *mut ::c_void + } + + pub struct pthread_mutex_t { + #[cfg(any(target_arch = "mips", + target_arch = "arm", + target_arch = "powerpc", + all(target_arch = "x86_64", + target_pointer_width = "32")))] + __align: [::c_long; 0], + #[cfg(not(any(target_arch = "mips", + target_arch = "arm", + target_arch = "powerpc", + all(target_arch = "x86_64", + target_pointer_width = "32"))))] + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_MUTEX_T], + } + + pub struct pthread_rwlock_t { + #[cfg(any(target_arch = "mips", + target_arch = "arm", + target_arch = "powerpc", + all(target_arch = "x86_64", + target_pointer_width = "32")))] + __align: [::c_long; 0], + #[cfg(not(any(target_arch = "mips", + target_arch = "arm", + target_arch = "powerpc", + all(target_arch = "x86_64", + target_pointer_width = "32"))))] + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_RWLOCK_T], + } + + pub struct pthread_mutexattr_t { + #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", + target_arch = "mips64", target_arch = "s390x", + target_arch = "sparc64"))] + __align: [::c_int; 0], + #[cfg(not(any(target_arch = "x86_64", target_arch = "powerpc64", + target_arch = "mips64", target_arch = "s390x", + target_arch = "sparc64", target_arch = "aarch64")))] + __align: [::c_long; 0], + #[cfg(all(target_arch = "aarch64", target_env = "gnu"))] + __align: [::c_long; 0], + #[cfg(all(target_arch = "aarch64", target_env = "musl"))] + __align: [::c_int; 0], + size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T], + } + + pub struct pthread_rwlockattr_t { + #[cfg(any(target_env = "musl"))] + __align: [::c_int; 0], + #[cfg(not(any(target_env = "musl")))] + __align: [::c_long; 0], + size: [u8; __SIZEOF_PTHREAD_RWLOCKATTR_T], + } + + pub struct pthread_cond_t { + #[cfg(any(target_env = "musl"))] + __align: [*const ::c_void; 0], + #[cfg(not(any(target_env = "musl")))] + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_COND_T], + } + + pub struct pthread_condattr_t { + __align: [::c_int; 0], + size: [u8; __SIZEOF_PTHREAD_CONDATTR_T], + } + + pub struct passwd { + pub pw_name: *mut ::c_char, + pub pw_passwd: *mut ::c_char, + pub pw_uid: ::uid_t, + pub pw_gid: ::gid_t, + pub pw_gecos: *mut ::c_char, + pub pw_dir: *mut ::c_char, + pub pw_shell: *mut ::c_char, + } + + pub struct spwd { + pub sp_namp: *mut ::c_char, + pub sp_pwdp: *mut ::c_char, + pub sp_lstchg: ::c_long, + pub sp_min: ::c_long, + pub sp_max: ::c_long, + pub sp_warn: ::c_long, + pub sp_inact: ::c_long, + pub sp_expire: ::c_long, + pub sp_flag: ::c_ulong, + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + #[cfg(target_endian = "little")] + pub f_fsid: ::c_ulong, + #[cfg(all(target_pointer_width = "32", not(target_arch = "x86_64")))] + __f_unused: ::c_int, + #[cfg(target_endian = "big")] + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct dqblk { + pub dqb_bhardlimit: ::uint64_t, + pub dqb_bsoftlimit: ::uint64_t, + pub dqb_curspace: ::uint64_t, + pub dqb_ihardlimit: ::uint64_t, + pub dqb_isoftlimit: ::uint64_t, + pub dqb_curinodes: ::uint64_t, + pub dqb_btime: ::uint64_t, + pub dqb_itime: ::uint64_t, + pub dqb_valid: ::uint32_t, + } + + pub struct signalfd_siginfo { + pub ssi_signo: ::uint32_t, + pub ssi_errno: ::int32_t, + pub ssi_code: ::int32_t, + pub ssi_pid: ::uint32_t, + pub ssi_uid: ::uint32_t, + pub ssi_fd: ::int32_t, + pub ssi_tid: ::uint32_t, + pub ssi_band: ::uint32_t, + pub ssi_overrun: ::uint32_t, + pub ssi_trapno: ::uint32_t, + pub ssi_status: ::int32_t, + pub ssi_int: ::int32_t, + pub ssi_ptr: ::uint64_t, + pub ssi_utime: ::uint64_t, + pub ssi_stime: ::uint64_t, + pub ssi_addr: ::uint64_t, + _pad: [::uint8_t; 48], + } + + pub struct itimerspec { + pub it_interval: ::timespec, + pub it_value: ::timespec, + } + + pub struct fsid_t { + __val: [::c_int; 2], + } + + // x32 compatibility + // See https://sourceware.org/bugzilla/show_bug.cgi?id=21279 + pub struct mq_attr { + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + pub mq_flags: i64, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + pub mq_maxmsg: i64, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + pub mq_msgsize: i64, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + pub mq_curmsgs: i64, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + pad: [i64; 4], + + #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] + pub mq_flags: ::c_long, + #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] + pub mq_maxmsg: ::c_long, + #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] + pub mq_msgsize: ::c_long, + #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] + pub mq_curmsgs: ::c_long, + #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] + pad: [::c_long; 4], + } + + pub struct cpu_set_t { + #[cfg(all(target_pointer_width = "32", + not(target_arch = "x86_64")))] + bits: [u32; 32], + #[cfg(not(all(target_pointer_width = "32", + not(target_arch = "x86_64"))))] + bits: [u64; 16], + } + + pub struct if_nameindex { + pub if_index: ::c_uint, + pub if_name: *mut ::c_char, + } + + // System V IPC + pub struct msginfo { + pub msgpool: ::c_int, + pub msgmap: ::c_int, + pub msgmax: ::c_int, + pub msgmnb: ::c_int, + pub msgmni: ::c_int, + pub msgssz: ::c_int, + pub msgtql: ::c_int, + pub msgseg: ::c_ushort, + } + + pub struct mmsghdr { + pub msg_hdr: ::msghdr, + pub msg_len: ::c_uint, + } + + pub struct sembuf { + pub sem_num: ::c_ushort, + pub sem_op: ::c_short, + pub sem_flg: ::c_short, + } + + pub struct input_event { + pub time: ::timeval, + pub type_: ::__u16, + pub code: ::__u16, + pub value: ::__s32, + } + + pub struct input_id { + pub bustype: ::__u16, + pub vendor: ::__u16, + pub product: ::__u16, + pub version: ::__u16, + } + + pub struct input_absinfo { + pub value: ::__s32, + pub minimum: ::__s32, + pub maximum: ::__s32, + pub fuzz: ::__s32, + pub flat: ::__s32, + pub resolution: ::__s32, + } + + pub struct input_keymap_entry { + pub flags: ::__u8, + pub len: ::__u8, + pub index: ::__u16, + pub keycode: ::__u32, + pub scancode: [::__u8; 32], + } + + pub struct input_mask { + pub type_: ::__u32, + pub codes_size: ::__u32, + pub codes_ptr: ::__u64, + } + + pub struct ff_replay { + pub length: ::__u16, + pub delay: ::__u16, + } + + pub struct ff_trigger { + pub button: ::__u16, + pub interval: ::__u16, + } + + pub struct ff_envelope { + pub attack_length: ::__u16, + pub attack_level: ::__u16, + pub fade_length: ::__u16, + pub fade_level: ::__u16, + } + + pub struct ff_constant_effect { + pub level: ::__s16, + pub envelope: ff_envelope, + } + + pub struct ff_ramp_effect { + pub start_level: ::__s16, + pub end_level: ::__s16, + pub envelope: ff_envelope, + } + + pub struct ff_condition_effect { + pub right_saturation: ::__u16, + pub left_saturation: ::__u16, + + pub right_coeff: ::__s16, + pub left_coeff: ::__s16, + + pub deadband: ::__u16, + pub center: ::__s16, + } + + pub struct ff_periodic_effect { + pub waveform: ::__u16, + pub period: ::__u16, + pub magnitude: ::__s16, + pub offset: ::__s16, + pub phase: ::__u16, + + pub envelope: ff_envelope, + + pub custom_len: ::__u32, + pub custom_data: *mut ::__s16, + } + + pub struct ff_rumble_effect { + pub strong_magnitude: ::__u16, + pub weak_magnitude: ::__u16, + } + + pub struct ff_effect { + pub type_: ::__u16, + pub id: ::__s16, + pub direction: ::__u16, + pub trigger: ff_trigger, + pub replay: ff_replay, + // FIXME this is actually a union + #[cfg(target_pointer_width = "64")] + pub u: [u64; 4], + #[cfg(target_pointer_width = "32")] + pub u: [u32; 7], + } + + pub struct dl_phdr_info { + #[cfg(target_pointer_width = "64")] + pub dlpi_addr: Elf64_Addr, + #[cfg(target_pointer_width = "32")] + pub dlpi_addr: Elf32_Addr, + + pub dlpi_name: *const ::c_char, + + #[cfg(target_pointer_width = "64")] + pub dlpi_phdr: *const Elf64_Phdr, + #[cfg(target_pointer_width = "32")] + pub dlpi_phdr: *const Elf32_Phdr, + + #[cfg(target_pointer_width = "64")] + pub dlpi_phnum: Elf64_Half, + #[cfg(target_pointer_width = "32")] + pub dlpi_phnum: Elf32_Half, + + pub dlpi_adds: ::c_ulonglong, + pub dlpi_subs: ::c_ulonglong, + pub dlpi_tls_modid: ::size_t, + pub dlpi_tls_data: *mut ::c_void, + } + + pub struct Elf32_Phdr { + pub p_type: Elf32_Word, + pub p_offset: Elf32_Off, + pub p_vaddr: Elf32_Addr, + pub p_paddr: Elf32_Addr, + pub p_filesz: Elf32_Word, + pub p_memsz: Elf32_Word, + pub p_flags: Elf32_Word, + pub p_align: Elf32_Word, + } + + pub struct Elf64_Phdr { + pub p_type: Elf64_Word, + pub p_flags: Elf64_Word, + pub p_offset: Elf64_Off, + pub p_vaddr: Elf64_Addr, + pub p_paddr: Elf64_Addr, + pub p_filesz: Elf64_Xword, + pub p_memsz: Elf64_Xword, + pub p_align: Elf64_Xword, + } + + pub struct statfs64 { + pub f_type: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_flags: ::c_ulong, + pub f_spare: [::c_ulong; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_flags: ::c_int, + pub ss_size: ::size_t + } + + pub struct pthread_attr_t { + __size: [u64; 7] + } + + pub struct sigset_t { + __val: [::c_ulong; 16], + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::c_ulong, + __pad1: ::c_ulong, + __pad2: ::c_ulong, + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_stime: ::time_t, + pub msg_rtime: ::time_t, + pub msg_ctime: ::time_t, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __pad1: ::c_ulong, + __pad2: ::c_ulong, + } + + pub struct statfs { + pub f_type: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_flags: ::c_ulong, + pub f_spare: [::c_ulong; 4], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::c_int, + __pad1: ::c_int, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::socklen_t, + __pad2: ::socklen_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::socklen_t, + pub __pad1: ::c_int, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct sem_t { + __val: [::c_int; 8], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_errno: ::c_int, + pub si_code: ::c_int, + pub _pad: [::c_int; 29], + _align: [usize; 0], + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 19], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } +} + +// PUB_CONST + +pub const SIG_DFL: sighandler_t = 0 as sighandler_t; +pub const SIG_IGN: sighandler_t = 1 as sighandler_t; +pub const SIG_ERR: sighandler_t = !0 as sighandler_t; + +pub const DT_FIFO: u8 = 1; +pub const DT_CHR: u8 = 2; +pub const DT_DIR: u8 = 4; +pub const DT_BLK: u8 = 6; +pub const DT_REG: u8 = 8; +pub const DT_LNK: u8 = 10; +pub const DT_SOCK: u8 = 12; + +pub const FD_CLOEXEC: ::c_int = 0x1; + +pub const USRQUOTA: ::c_int = 0; +pub const GRPQUOTA: ::c_int = 1; + +pub const SIGIOT: ::c_int = 6; + +pub const S_ISUID: ::c_int = 0x800; +pub const S_ISGID: ::c_int = 0x400; +pub const S_ISVTX: ::c_int = 0x200; + +pub const IF_NAMESIZE: ::size_t = 16; + +pub const LOG_EMERG: ::c_int = 0; +pub const LOG_ALERT: ::c_int = 1; +pub const LOG_CRIT: ::c_int = 2; +pub const LOG_ERR: ::c_int = 3; +pub const LOG_WARNING: ::c_int = 4; +pub const LOG_NOTICE: ::c_int = 5; +pub const LOG_INFO: ::c_int = 6; +pub const LOG_DEBUG: ::c_int = 7; + +pub const LOG_KERN: ::c_int = 0; +pub const LOG_USER: ::c_int = 1 << 3; +pub const LOG_MAIL: ::c_int = 2 << 3; +pub const LOG_DAEMON: ::c_int = 3 << 3; +pub const LOG_AUTH: ::c_int = 4 << 3; +pub const LOG_SYSLOG: ::c_int = 5 << 3; +pub const LOG_LPR: ::c_int = 6 << 3; +pub const LOG_NEWS: ::c_int = 7 << 3; +pub const LOG_UUCP: ::c_int = 8 << 3; +pub const LOG_LOCAL0: ::c_int = 16 << 3; +pub const LOG_LOCAL1: ::c_int = 17 << 3; +pub const LOG_LOCAL2: ::c_int = 18 << 3; +pub const LOG_LOCAL3: ::c_int = 19 << 3; +pub const LOG_LOCAL4: ::c_int = 20 << 3; +pub const LOG_LOCAL5: ::c_int = 21 << 3; +pub const LOG_LOCAL6: ::c_int = 22 << 3; +pub const LOG_LOCAL7: ::c_int = 23 << 3; + +pub const LOG_PID: ::c_int = 0x01; +pub const LOG_CONS: ::c_int = 0x02; +pub const LOG_ODELAY: ::c_int = 0x04; +pub const LOG_NDELAY: ::c_int = 0x08; +pub const LOG_NOWAIT: ::c_int = 0x10; + +pub const LOG_PRIMASK: ::c_int = 7; +pub const LOG_FACMASK: ::c_int = 0x3f8; + +pub const PRIO_PROCESS: ::c_int = 0; +pub const PRIO_PGRP: ::c_int = 1; +pub const PRIO_USER: ::c_int = 2; + +pub const PRIO_MIN: ::c_int = -20; +pub const PRIO_MAX: ::c_int = 20; + +pub const IPPROTO_ICMP: ::c_int = 1; +pub const IPPROTO_ICMPV6: ::c_int = 58; +pub const IPPROTO_TCP: ::c_int = 6; +pub const IPPROTO_UDP: ::c_int = 17; +pub const IPPROTO_IP: ::c_int = 0; +pub const IPPROTO_IPV6: ::c_int = 41; + +pub const INADDR_LOOPBACK: in_addr_t = 2130706433; +pub const INADDR_ANY: in_addr_t = 0; +pub const INADDR_BROADCAST: in_addr_t = 4294967295; +pub const INADDR_NONE: in_addr_t = 4294967295; + +pub const EXIT_FAILURE: ::c_int = 1; +pub const EXIT_SUCCESS: ::c_int = 0; +pub const RAND_MAX: ::c_int = 2147483647; +pub const EOF: ::c_int = -1; +pub const SEEK_SET: ::c_int = 0; +pub const SEEK_CUR: ::c_int = 1; +pub const SEEK_END: ::c_int = 2; +pub const _IOFBF: ::c_int = 0; +pub const _IONBF: ::c_int = 2; +pub const _IOLBF: ::c_int = 1; + +pub const F_DUPFD: ::c_int = 0; +pub const F_GETFD: ::c_int = 1; +pub const F_SETFD: ::c_int = 2; +pub const F_GETFL: ::c_int = 3; +pub const F_SETFL: ::c_int = 4; + +// Linux-specific fcntls +pub const F_SETLEASE: ::c_int = 1024; +pub const F_GETLEASE: ::c_int = 1025; +pub const F_NOTIFY: ::c_int = 1026; +pub const F_CANCELLK: ::c_int = 1029; +pub const F_DUPFD_CLOEXEC: ::c_int = 1030; +pub const F_SETPIPE_SZ: ::c_int = 1031; +pub const F_GETPIPE_SZ: ::c_int = 1032; +pub const F_ADD_SEALS: ::c_int = 1033; +pub const F_GET_SEALS: ::c_int = 1034; + +pub const F_SEAL_SEAL: ::c_int = 0x0001; +pub const F_SEAL_SHRINK: ::c_int = 0x0002; +pub const F_SEAL_GROW: ::c_int = 0x0004; +pub const F_SEAL_WRITE: ::c_int = 0x0008; + +// TODO(#235): Include file sealing fcntls once we have a way to verify them. + +pub const SIGTRAP: ::c_int = 5; + +pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; +pub const PTHREAD_CREATE_DETACHED: ::c_int = 1; + +pub const CLOCK_REALTIME: ::clockid_t = 0; +pub const CLOCK_MONOTONIC: ::clockid_t = 1; +pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 2; +pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 3; +pub const CLOCK_MONOTONIC_RAW: ::clockid_t = 4; +pub const CLOCK_REALTIME_COARSE: ::clockid_t = 5; +pub const CLOCK_MONOTONIC_COARSE: ::clockid_t = 6; +pub const CLOCK_BOOTTIME: ::clockid_t = 7; +pub const CLOCK_REALTIME_ALARM: ::clockid_t = 8; +pub const CLOCK_BOOTTIME_ALARM: ::clockid_t = 9; +// TODO(#247) Someday our Travis shall have glibc 2.21 (released in Sep +// 2014.) See also musl/mod.rs +// pub const CLOCK_SGI_CYCLE: ::clockid_t = 10; +// pub const CLOCK_TAI: ::clockid_t = 11; +pub const TIMER_ABSTIME: ::c_int = 1; + +pub const RLIMIT_CPU: ::c_int = 0; +pub const RLIMIT_FSIZE: ::c_int = 1; +pub const RLIMIT_DATA: ::c_int = 2; +pub const RLIMIT_STACK: ::c_int = 3; +pub const RLIMIT_CORE: ::c_int = 4; +pub const RLIMIT_LOCKS: ::c_int = 10; +pub const RLIMIT_SIGPENDING: ::c_int = 11; +pub const RLIMIT_MSGQUEUE: ::c_int = 12; +pub const RLIMIT_NICE: ::c_int = 13; +pub const RLIMIT_RTPRIO: ::c_int = 14; + +pub const RUSAGE_SELF: ::c_int = 0; + +pub const O_RDONLY: ::c_int = 0; +pub const O_WRONLY: ::c_int = 1; +pub const O_RDWR: ::c_int = 2; + +pub const SOCK_CLOEXEC: ::c_int = O_CLOEXEC; + +pub const S_IFIFO: ::mode_t = 4096; +pub const S_IFCHR: ::mode_t = 8192; +pub const S_IFBLK: ::mode_t = 24576; +pub const S_IFDIR: ::mode_t = 16384; +pub const S_IFREG: ::mode_t = 32768; +pub const S_IFLNK: ::mode_t = 40960; +pub const S_IFSOCK: ::mode_t = 49152; +pub const S_IFMT: ::mode_t = 61440; +pub const S_IRWXU: ::mode_t = 448; +pub const S_IXUSR: ::mode_t = 64; +pub const S_IWUSR: ::mode_t = 128; +pub const S_IRUSR: ::mode_t = 256; +pub const S_IRWXG: ::mode_t = 56; +pub const S_IXGRP: ::mode_t = 8; +pub const S_IWGRP: ::mode_t = 16; +pub const S_IRGRP: ::mode_t = 32; +pub const S_IRWXO: ::mode_t = 7; +pub const S_IXOTH: ::mode_t = 1; +pub const S_IWOTH: ::mode_t = 2; +pub const S_IROTH: ::mode_t = 4; +pub const F_OK: ::c_int = 0; +pub const R_OK: ::c_int = 4; +pub const W_OK: ::c_int = 2; +pub const X_OK: ::c_int = 1; +pub const STDIN_FILENO: ::c_int = 0; +pub const STDOUT_FILENO: ::c_int = 1; +pub const STDERR_FILENO: ::c_int = 2; +pub const SIGHUP: ::c_int = 1; +pub const SIGINT: ::c_int = 2; +pub const SIGQUIT: ::c_int = 3; +pub const SIGILL: ::c_int = 4; +pub const SIGABRT: ::c_int = 6; +pub const SIGFPE: ::c_int = 8; +pub const SIGKILL: ::c_int = 9; +pub const SIGSEGV: ::c_int = 11; +pub const SIGPIPE: ::c_int = 13; +pub const SIGALRM: ::c_int = 14; +pub const SIGTERM: ::c_int = 15; + +pub const PROT_NONE: ::c_int = 0; +pub const PROT_READ: ::c_int = 1; +pub const PROT_WRITE: ::c_int = 2; +pub const PROT_EXEC: ::c_int = 4; + +pub const LC_CTYPE: ::c_int = 0; +pub const LC_NUMERIC: ::c_int = 1; +pub const LC_TIME: ::c_int = 2; +pub const LC_COLLATE: ::c_int = 3; +pub const LC_MONETARY: ::c_int = 4; +pub const LC_MESSAGES: ::c_int = 5; +pub const LC_ALL: ::c_int = 6; +pub const LC_CTYPE_MASK: ::c_int = (1 << LC_CTYPE); +pub const LC_NUMERIC_MASK: ::c_int = (1 << LC_NUMERIC); +pub const LC_TIME_MASK: ::c_int = (1 << LC_TIME); +pub const LC_COLLATE_MASK: ::c_int = (1 << LC_COLLATE); +pub const LC_MONETARY_MASK: ::c_int = (1 << LC_MONETARY); +pub const LC_MESSAGES_MASK: ::c_int = (1 << LC_MESSAGES); +// LC_ALL_MASK defined per platform + +pub const MAP_FILE: ::c_int = 0x0000; +pub const MAP_SHARED: ::c_int = 0x0001; +pub const MAP_PRIVATE: ::c_int = 0x0002; +pub const MAP_FIXED: ::c_int = 0x0010; + +pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; + +// MS_ flags for msync(2) +pub const MS_ASYNC: ::c_int = 0x0001; +pub const MS_INVALIDATE: ::c_int = 0x0002; +pub const MS_SYNC: ::c_int = 0x0004; + +// MS_ flags for mount(2) +pub const MS_RDONLY: ::c_ulong = 0x01; +pub const MS_NOSUID: ::c_ulong = 0x02; +pub const MS_NODEV: ::c_ulong = 0x04; +pub const MS_NOEXEC: ::c_ulong = 0x08; +pub const MS_SYNCHRONOUS: ::c_ulong = 0x10; +pub const MS_REMOUNT: ::c_ulong = 0x20; +pub const MS_MANDLOCK: ::c_ulong = 0x40; +pub const MS_DIRSYNC: ::c_ulong = 0x80; +pub const MS_NOATIME: ::c_ulong = 0x0400; +pub const MS_NODIRATIME: ::c_ulong = 0x0800; +pub const MS_BIND: ::c_ulong = 0x1000; +pub const MS_MOVE: ::c_ulong = 0x2000; +pub const MS_REC: ::c_ulong = 0x4000; +pub const MS_SILENT: ::c_ulong = 0x8000; +pub const MS_POSIXACL: ::c_ulong = 0x010000; +pub const MS_UNBINDABLE: ::c_ulong = 0x020000; +pub const MS_PRIVATE: ::c_ulong = 0x040000; +pub const MS_SLAVE: ::c_ulong = 0x080000; +pub const MS_SHARED: ::c_ulong = 0x100000; +pub const MS_RELATIME: ::c_ulong = 0x200000; +pub const MS_KERNMOUNT: ::c_ulong = 0x400000; +pub const MS_I_VERSION: ::c_ulong = 0x800000; +pub const MS_STRICTATIME: ::c_ulong = 0x1000000; +pub const MS_ACTIVE: ::c_ulong = 0x40000000; +pub const MS_NOUSER: ::c_ulong = 0x80000000; +pub const MS_MGC_VAL: ::c_ulong = 0xc0ed0000; +pub const MS_MGC_MSK: ::c_ulong = 0xffff0000; +pub const MS_RMT_MASK: ::c_ulong = 0x800051; + +pub const EPERM: ::c_int = 1; +pub const ENOENT: ::c_int = 2; +pub const ESRCH: ::c_int = 3; +pub const EINTR: ::c_int = 4; +pub const EIO: ::c_int = 5; +pub const ENXIO: ::c_int = 6; +pub const E2BIG: ::c_int = 7; +pub const ENOEXEC: ::c_int = 8; +pub const EBADF: ::c_int = 9; +pub const ECHILD: ::c_int = 10; +pub const EAGAIN: ::c_int = 11; +pub const ENOMEM: ::c_int = 12; +pub const EACCES: ::c_int = 13; +pub const EFAULT: ::c_int = 14; +pub const ENOTBLK: ::c_int = 15; +pub const EBUSY: ::c_int = 16; +pub const EEXIST: ::c_int = 17; +pub const EXDEV: ::c_int = 18; +pub const ENODEV: ::c_int = 19; +pub const ENOTDIR: ::c_int = 20; +pub const EISDIR: ::c_int = 21; +pub const EINVAL: ::c_int = 22; +pub const ENFILE: ::c_int = 23; +pub const EMFILE: ::c_int = 24; +pub const ENOTTY: ::c_int = 25; +pub const ETXTBSY: ::c_int = 26; +pub const EFBIG: ::c_int = 27; +pub const ENOSPC: ::c_int = 28; +pub const ESPIPE: ::c_int = 29; +pub const EROFS: ::c_int = 30; +pub const EMLINK: ::c_int = 31; +pub const EPIPE: ::c_int = 32; +pub const EDOM: ::c_int = 33; +pub const ERANGE: ::c_int = 34; +pub const EWOULDBLOCK: ::c_int = EAGAIN; + +pub const SCM_RIGHTS: ::c_int = 0x01; +pub const SCM_CREDENTIALS: ::c_int = 0x02; + +pub const PROT_GROWSDOWN: ::c_int = 0x1000000; +pub const PROT_GROWSUP: ::c_int = 0x2000000; + +pub const MAP_TYPE: ::c_int = 0x000f; + +pub const MADV_NORMAL: ::c_int = 0; +pub const MADV_RANDOM: ::c_int = 1; +pub const MADV_SEQUENTIAL: ::c_int = 2; +pub const MADV_WILLNEED: ::c_int = 3; +pub const MADV_DONTNEED: ::c_int = 4; +pub const MADV_FREE: ::c_int = 8; +pub const MADV_REMOVE: ::c_int = 9; +pub const MADV_DONTFORK: ::c_int = 10; +pub const MADV_DOFORK: ::c_int = 11; +pub const MADV_MERGEABLE: ::c_int = 12; +pub const MADV_UNMERGEABLE: ::c_int = 13; +pub const MADV_HUGEPAGE: ::c_int = 14; +pub const MADV_NOHUGEPAGE: ::c_int = 15; +pub const MADV_DONTDUMP: ::c_int = 16; +pub const MADV_DODUMP: ::c_int = 17; +pub const MADV_HWPOISON: ::c_int = 100; +pub const MADV_SOFT_OFFLINE: ::c_int = 101; + +pub const IFF_UP: ::c_int = 0x1; +pub const IFF_BROADCAST: ::c_int = 0x2; +pub const IFF_DEBUG: ::c_int = 0x4; +pub const IFF_LOOPBACK: ::c_int = 0x8; +pub const IFF_POINTOPOINT: ::c_int = 0x10; +pub const IFF_NOTRAILERS: ::c_int = 0x20; +pub const IFF_RUNNING: ::c_int = 0x40; +pub const IFF_NOARP: ::c_int = 0x80; +pub const IFF_PROMISC: ::c_int = 0x100; +pub const IFF_ALLMULTI: ::c_int = 0x200; +pub const IFF_MASTER: ::c_int = 0x400; +pub const IFF_SLAVE: ::c_int = 0x800; +pub const IFF_MULTICAST: ::c_int = 0x1000; +pub const IFF_PORTSEL: ::c_int = 0x2000; +pub const IFF_AUTOMEDIA: ::c_int = 0x4000; +pub const IFF_DYNAMIC: ::c_int = 0x8000; +pub const IFF_TUN: ::c_int = 0x0001; +pub const IFF_TAP: ::c_int = 0x0002; +pub const IFF_NO_PI: ::c_int = 0x1000; + +pub const SOL_IP: ::c_int = 0; +pub const SOL_TCP: ::c_int = 6; +pub const SOL_UDP: ::c_int = 17; +pub const SOL_IPV6: ::c_int = 41; +pub const SOL_ICMPV6: ::c_int = 58; +pub const SOL_RAW: ::c_int = 255; +pub const SOL_DECNET: ::c_int = 261; +pub const SOL_X25: ::c_int = 262; +pub const SOL_PACKET: ::c_int = 263; +pub const SOL_ATM: ::c_int = 264; +pub const SOL_AAL: ::c_int = 265; +pub const SOL_IRDA: ::c_int = 266; +pub const SOL_NETBEUI: ::c_int = 267; +pub const SOL_LLC: ::c_int = 268; +pub const SOL_DCCP: ::c_int = 269; +pub const SOL_NETLINK: ::c_int = 270; +pub const SOL_TIPC: ::c_int = 271; + +pub const AF_UNSPEC: ::c_int = 0; +pub const AF_UNIX: ::c_int = 1; +pub const AF_LOCAL: ::c_int = 1; +pub const AF_INET: ::c_int = 2; +pub const AF_AX25: ::c_int = 3; +pub const AF_IPX: ::c_int = 4; +pub const AF_APPLETALK: ::c_int = 5; +pub const AF_NETROM: ::c_int = 6; +pub const AF_BRIDGE: ::c_int = 7; +pub const AF_ATMPVC: ::c_int = 8; +pub const AF_X25: ::c_int = 9; +pub const AF_INET6: ::c_int = 10; +pub const AF_ROSE: ::c_int = 11; +pub const AF_DECnet: ::c_int = 12; +pub const AF_NETBEUI: ::c_int = 13; +pub const AF_SECURITY: ::c_int = 14; +pub const AF_KEY: ::c_int = 15; +pub const AF_NETLINK: ::c_int = 16; +pub const AF_ROUTE: ::c_int = AF_NETLINK; +pub const AF_PACKET: ::c_int = 17; +pub const AF_ASH: ::c_int = 18; +pub const AF_ECONET: ::c_int = 19; +pub const AF_ATMSVC: ::c_int = 20; +pub const AF_RDS: ::c_int = 21; +pub const AF_SNA: ::c_int = 22; +pub const AF_IRDA: ::c_int = 23; +pub const AF_PPPOX: ::c_int = 24; +pub const AF_WANPIPE: ::c_int = 25; +pub const AF_LLC: ::c_int = 26; +pub const AF_CAN: ::c_int = 29; +pub const AF_TIPC: ::c_int = 30; +pub const AF_BLUETOOTH: ::c_int = 31; +pub const AF_IUCV: ::c_int = 32; +pub const AF_RXRPC: ::c_int = 33; +pub const AF_ISDN: ::c_int = 34; +pub const AF_PHONET: ::c_int = 35; +pub const AF_IEEE802154: ::c_int = 36; +pub const AF_CAIF: ::c_int = 37; +pub const AF_ALG: ::c_int = 38; + +pub const PF_UNSPEC: ::c_int = AF_UNSPEC; +pub const PF_UNIX: ::c_int = AF_UNIX; +pub const PF_LOCAL: ::c_int = AF_LOCAL; +pub const PF_INET: ::c_int = AF_INET; +pub const PF_AX25: ::c_int = AF_AX25; +pub const PF_IPX: ::c_int = AF_IPX; +pub const PF_APPLETALK: ::c_int = AF_APPLETALK; +pub const PF_NETROM: ::c_int = AF_NETROM; +pub const PF_BRIDGE: ::c_int = AF_BRIDGE; +pub const PF_ATMPVC: ::c_int = AF_ATMPVC; +pub const PF_X25: ::c_int = AF_X25; +pub const PF_INET6: ::c_int = AF_INET6; +pub const PF_ROSE: ::c_int = AF_ROSE; +pub const PF_DECnet: ::c_int = AF_DECnet; +pub const PF_NETBEUI: ::c_int = AF_NETBEUI; +pub const PF_SECURITY: ::c_int = AF_SECURITY; +pub const PF_KEY: ::c_int = AF_KEY; +pub const PF_NETLINK: ::c_int = AF_NETLINK; +pub const PF_ROUTE: ::c_int = AF_ROUTE; +pub const PF_PACKET: ::c_int = AF_PACKET; +pub const PF_ASH: ::c_int = AF_ASH; +pub const PF_ECONET: ::c_int = AF_ECONET; +pub const PF_ATMSVC: ::c_int = AF_ATMSVC; +pub const PF_RDS: ::c_int = AF_RDS; +pub const PF_SNA: ::c_int = AF_SNA; +pub const PF_IRDA: ::c_int = AF_IRDA; +pub const PF_PPPOX: ::c_int = AF_PPPOX; +pub const PF_WANPIPE: ::c_int = AF_WANPIPE; +pub const PF_LLC: ::c_int = AF_LLC; +pub const PF_CAN: ::c_int = AF_CAN; +pub const PF_TIPC: ::c_int = AF_TIPC; +pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; +pub const PF_IUCV: ::c_int = AF_IUCV; +pub const PF_RXRPC: ::c_int = AF_RXRPC; +pub const PF_ISDN: ::c_int = AF_ISDN; +pub const PF_PHONET: ::c_int = AF_PHONET; +pub const PF_IEEE802154: ::c_int = AF_IEEE802154; +pub const PF_CAIF: ::c_int = AF_CAIF; +pub const PF_ALG: ::c_int = AF_ALG; + +pub const SOMAXCONN: ::c_int = 128; + +pub const MSG_OOB: ::c_int = 1; +pub const MSG_PEEK: ::c_int = 2; +pub const MSG_DONTROUTE: ::c_int = 4; +pub const MSG_CTRUNC: ::c_int = 8; +pub const MSG_TRUNC: ::c_int = 0x20; +pub const MSG_DONTWAIT: ::c_int = 0x40; +pub const MSG_EOR: ::c_int = 0x80; +pub const MSG_WAITALL: ::c_int = 0x100; +pub const MSG_FIN: ::c_int = 0x200; +pub const MSG_SYN: ::c_int = 0x400; +pub const MSG_CONFIRM: ::c_int = 0x800; +pub const MSG_RST: ::c_int = 0x1000; +pub const MSG_ERRQUEUE: ::c_int = 0x2000; +pub const MSG_NOSIGNAL: ::c_int = 0x4000; +pub const MSG_MORE: ::c_int = 0x8000; +pub const MSG_WAITFORONE: ::c_int = 0x10000; +pub const MSG_FASTOPEN: ::c_int = 0x20000000; +pub const MSG_CMSG_CLOEXEC: ::c_int = 0x40000000; + +pub const SCM_TIMESTAMP: ::c_int = SO_TIMESTAMP; + +pub const SOCK_RAW: ::c_int = 3; +pub const SOCK_RDM: ::c_int = 4; +pub const IP_MULTICAST_IF: ::c_int = 32; +pub const IP_MULTICAST_TTL: ::c_int = 33; +pub const IP_MULTICAST_LOOP: ::c_int = 34; +pub const IP_TTL: ::c_int = 2; +pub const IP_HDRINCL: ::c_int = 3; +pub const IP_ADD_MEMBERSHIP: ::c_int = 35; +pub const IP_DROP_MEMBERSHIP: ::c_int = 36; +pub const IP_TRANSPARENT: ::c_int = 19; +pub const IPV6_UNICAST_HOPS: ::c_int = 16; +pub const IPV6_MULTICAST_IF: ::c_int = 17; +pub const IPV6_MULTICAST_HOPS: ::c_int = 18; +pub const IPV6_MULTICAST_LOOP: ::c_int = 19; +pub const IPV6_ADD_MEMBERSHIP: ::c_int = 20; +pub const IPV6_DROP_MEMBERSHIP: ::c_int = 21; +pub const IPV6_V6ONLY: ::c_int = 26; + +pub const TCP_NODELAY: ::c_int = 1; +pub const TCP_MAXSEG: ::c_int = 2; +pub const TCP_CORK: ::c_int = 3; +pub const TCP_KEEPIDLE: ::c_int = 4; +pub const TCP_KEEPINTVL: ::c_int = 5; +pub const TCP_KEEPCNT: ::c_int = 6; +pub const TCP_SYNCNT: ::c_int = 7; +pub const TCP_LINGER2: ::c_int = 8; +pub const TCP_DEFER_ACCEPT: ::c_int = 9; +pub const TCP_WINDOW_CLAMP: ::c_int = 10; +pub const TCP_INFO: ::c_int = 11; +pub const TCP_QUICKACK: ::c_int = 12; +pub const TCP_CONGESTION: ::c_int = 13; + +pub const SO_DEBUG: ::c_int = 1; + +pub const SHUT_RD: ::c_int = 0; +pub const SHUT_WR: ::c_int = 1; +pub const SHUT_RDWR: ::c_int = 2; + +pub const LOCK_SH: ::c_int = 1; +pub const LOCK_EX: ::c_int = 2; +pub const LOCK_NB: ::c_int = 4; +pub const LOCK_UN: ::c_int = 8; + +pub const SS_ONSTACK: ::c_int = 1; +pub const SS_DISABLE: ::c_int = 2; + +pub const PATH_MAX: ::c_int = 4096; + +pub const FD_SETSIZE: usize = 1024; + +pub const EPOLLIN: ::c_int = 0x1; +pub const EPOLLPRI: ::c_int = 0x2; +pub const EPOLLOUT: ::c_int = 0x4; +pub const EPOLLRDNORM: ::c_int = 0x40; +pub const EPOLLRDBAND: ::c_int = 0x80; +pub const EPOLLWRNORM: ::c_int = 0x100; +pub const EPOLLWRBAND: ::c_int = 0x200; +pub const EPOLLMSG: ::c_int = 0x400; +pub const EPOLLERR: ::c_int = 0x8; +pub const EPOLLHUP: ::c_int = 0x10; +pub const EPOLLET: ::c_int = 0x80000000; + +pub const EPOLL_CTL_ADD: ::c_int = 1; +pub const EPOLL_CTL_MOD: ::c_int = 3; +pub const EPOLL_CTL_DEL: ::c_int = 2; + +pub const MNT_DETACH: ::c_int = 0x2; +pub const MNT_EXPIRE: ::c_int = 0x4; + +pub const Q_GETFMT: ::c_int = 0x800004; +pub const Q_GETINFO: ::c_int = 0x800005; +pub const Q_SETINFO: ::c_int = 0x800006; +pub const QIF_BLIMITS: ::uint32_t = 1; +pub const QIF_SPACE: ::uint32_t = 2; +pub const QIF_ILIMITS: ::uint32_t = 4; +pub const QIF_INODES: ::uint32_t = 8; +pub const QIF_BTIME: ::uint32_t = 16; +pub const QIF_ITIME: ::uint32_t = 32; +pub const QIF_LIMITS: ::uint32_t = 5; +pub const QIF_USAGE: ::uint32_t = 10; +pub const QIF_TIMES: ::uint32_t = 48; +pub const QIF_ALL: ::uint32_t = 63; + +pub const MNT_FORCE: ::c_int = 0x1; + +pub const Q_SYNC: ::c_int = 0x800001; +pub const Q_QUOTAON: ::c_int = 0x800002; +pub const Q_QUOTAOFF: ::c_int = 0x800003; +pub const Q_GETQUOTA: ::c_int = 0x800007; +pub const Q_SETQUOTA: ::c_int = 0x800008; + +pub const TCIOFF: ::c_int = 2; +pub const TCION: ::c_int = 3; +pub const TCOOFF: ::c_int = 0; +pub const TCOON: ::c_int = 1; +pub const TCIFLUSH: ::c_int = 0; +pub const TCOFLUSH: ::c_int = 1; +pub const TCIOFLUSH: ::c_int = 2; +pub const NL0: ::c_int = 0x00000000; +pub const NL1: ::c_int = 0x00000100; +pub const TAB0: ::c_int = 0x00000000; +pub const CR0: ::c_int = 0x00000000; +pub const FF0: ::c_int = 0x00000000; +pub const BS0: ::c_int = 0x00000000; +pub const VT0: ::c_int = 0x00000000; +pub const VERASE: usize = 2; +pub const VKILL: usize = 3; +pub const VINTR: usize = 0; +pub const VQUIT: usize = 1; +pub const VLNEXT: usize = 15; +pub const IGNBRK: ::tcflag_t = 0x00000001; +pub const BRKINT: ::tcflag_t = 0x00000002; +pub const IGNPAR: ::tcflag_t = 0x00000004; +pub const PARMRK: ::tcflag_t = 0x00000008; +pub const INPCK: ::tcflag_t = 0x00000010; +pub const ISTRIP: ::tcflag_t = 0x00000020; +pub const INLCR: ::tcflag_t = 0x00000040; +pub const IGNCR: ::tcflag_t = 0x00000080; +pub const ICRNL: ::tcflag_t = 0x00000100; +pub const IXANY: ::tcflag_t = 0x00000800; +pub const IMAXBEL: ::tcflag_t = 0x00002000; +pub const OPOST: ::tcflag_t = 0x1; +pub const CS5: ::tcflag_t = 0x00000000; +pub const CRTSCTS: ::tcflag_t = 0x80000000; +pub const ECHO: ::tcflag_t = 0x00000008; +pub const OCRNL: ::tcflag_t = 0o000010; +pub const ONOCR: ::tcflag_t = 0o000020; +pub const ONLRET: ::tcflag_t = 0o000040; +pub const OFILL: ::tcflag_t = 0o000100; +pub const OFDEL: ::tcflag_t = 0o000200; + +pub const CLONE_VM: ::c_int = 0x100; +pub const CLONE_FS: ::c_int = 0x200; +pub const CLONE_FILES: ::c_int = 0x400; +pub const CLONE_SIGHAND: ::c_int = 0x800; +pub const CLONE_PTRACE: ::c_int = 0x2000; +pub const CLONE_VFORK: ::c_int = 0x4000; +pub const CLONE_PARENT: ::c_int = 0x8000; +pub const CLONE_THREAD: ::c_int = 0x10000; +pub const CLONE_NEWNS: ::c_int = 0x20000; +pub const CLONE_SYSVSEM: ::c_int = 0x40000; +pub const CLONE_SETTLS: ::c_int = 0x80000; +pub const CLONE_PARENT_SETTID: ::c_int = 0x100000; +pub const CLONE_CHILD_CLEARTID: ::c_int = 0x200000; +pub const CLONE_DETACHED: ::c_int = 0x400000; +pub const CLONE_UNTRACED: ::c_int = 0x800000; +pub const CLONE_CHILD_SETTID: ::c_int = 0x01000000; +pub const CLONE_NEWUTS: ::c_int = 0x04000000; +pub const CLONE_NEWIPC: ::c_int = 0x08000000; +pub const CLONE_NEWUSER: ::c_int = 0x10000000; +pub const CLONE_NEWPID: ::c_int = 0x20000000; +pub const CLONE_NEWNET: ::c_int = 0x40000000; +pub const CLONE_IO: ::c_int = 0x80000000; +pub const CLONE_NEWCGROUP: ::c_int = 0x02000000; + +pub const WNOHANG: ::c_int = 0x00000001; +pub const WUNTRACED: ::c_int = 0x00000002; +pub const WSTOPPED: ::c_int = WUNTRACED; +pub const WEXITED: ::c_int = 0x00000004; +pub const WCONTINUED: ::c_int = 0x00000008; +pub const WNOWAIT: ::c_int = 0x01000000; + +// Options set using PTRACE_SETOPTIONS. +pub const PTRACE_O_TRACESYSGOOD: ::c_int = 0x00000001; +pub const PTRACE_O_TRACEFORK: ::c_int = 0x00000002; +pub const PTRACE_O_TRACEVFORK: ::c_int = 0x00000004; +pub const PTRACE_O_TRACECLONE: ::c_int = 0x00000008; +pub const PTRACE_O_TRACEEXEC: ::c_int = 0x00000010; +pub const PTRACE_O_TRACEVFORKDONE: ::c_int = 0x00000020; +pub const PTRACE_O_TRACEEXIT: ::c_int = 0x00000040; +pub const PTRACE_O_TRACESECCOMP: ::c_int = 0x00000080; +pub const PTRACE_O_EXITKILL: ::c_int = 0x00100000; +pub const PTRACE_O_SUSPEND_SECCOMP: ::c_int = 0x00200000; +pub const PTRACE_O_MASK: ::c_int = 0x003000ff; + +// Wait extended result codes for the above trace options. +pub const PTRACE_EVENT_FORK: ::c_int = 1; +pub const PTRACE_EVENT_VFORK: ::c_int = 2; +pub const PTRACE_EVENT_CLONE: ::c_int = 3; +pub const PTRACE_EVENT_EXEC: ::c_int = 4; +pub const PTRACE_EVENT_VFORK_DONE: ::c_int = 5; +pub const PTRACE_EVENT_EXIT: ::c_int = 6; +pub const PTRACE_EVENT_SECCOMP: ::c_int = 7; +// PTRACE_EVENT_STOP was added to glibc in 2.26 +// pub const PTRACE_EVENT_STOP: ::c_int = 128; + +pub const __WNOTHREAD: ::c_int = 0x20000000; +pub const __WALL: ::c_int = 0x40000000; +pub const __WCLONE: ::c_int = 0x80000000; + +pub const SPLICE_F_MOVE: ::c_uint = 0x01; +pub const SPLICE_F_NONBLOCK: ::c_uint = 0x02; +pub const SPLICE_F_MORE: ::c_uint = 0x04; +pub const SPLICE_F_GIFT: ::c_uint = 0x08; + +pub const RTLD_LOCAL: ::c_int = 0; +pub const RTLD_LAZY: ::c_int = 1; + +pub const POSIX_FADV_NORMAL: ::c_int = 0; +pub const POSIX_FADV_RANDOM: ::c_int = 1; +pub const POSIX_FADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_FADV_WILLNEED: ::c_int = 3; + +pub const AT_FDCWD: ::c_int = -100; +pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x100; +pub const AT_REMOVEDIR: ::c_int = 0x200; +pub const AT_SYMLINK_FOLLOW: ::c_int = 0x400; +pub const AT_NO_AUTOMOUNT: ::c_int = 0x800; +pub const AT_EMPTY_PATH: ::c_int = 0x1000; + +pub const LOG_CRON: ::c_int = 9 << 3; +pub const LOG_AUTHPRIV: ::c_int = 10 << 3; +pub const LOG_FTP: ::c_int = 11 << 3; +pub const LOG_PERROR: ::c_int = 0x20; + +pub const PIPE_BUF: usize = 4096; + +pub const SI_LOAD_SHIFT: ::c_uint = 16; + +pub const SIGEV_SIGNAL: ::c_int = 0; +pub const SIGEV_NONE: ::c_int = 1; +pub const SIGEV_THREAD: ::c_int = 2; + +pub const P_ALL: idtype_t = 0; +pub const P_PID: idtype_t = 1; +pub const P_PGID: idtype_t = 2; + +pub const UTIME_OMIT: c_long = 1073741822; +pub const UTIME_NOW: c_long = 1073741823; + +pub const POLLIN: ::c_short = 0x1; +pub const POLLPRI: ::c_short = 0x2; +pub const POLLOUT: ::c_short = 0x4; +pub const POLLERR: ::c_short = 0x8; +pub const POLLHUP: ::c_short = 0x10; +pub const POLLNVAL: ::c_short = 0x20; +pub const POLLRDNORM: ::c_short = 0x040; +pub const POLLRDBAND: ::c_short = 0x080; + +pub const ABDAY_1: ::nl_item = 0x20000; +pub const ABDAY_2: ::nl_item = 0x20001; +pub const ABDAY_3: ::nl_item = 0x20002; +pub const ABDAY_4: ::nl_item = 0x20003; +pub const ABDAY_5: ::nl_item = 0x20004; +pub const ABDAY_6: ::nl_item = 0x20005; +pub const ABDAY_7: ::nl_item = 0x20006; + +pub const DAY_1: ::nl_item = 0x20007; +pub const DAY_2: ::nl_item = 0x20008; +pub const DAY_3: ::nl_item = 0x20009; +pub const DAY_4: ::nl_item = 0x2000A; +pub const DAY_5: ::nl_item = 0x2000B; +pub const DAY_6: ::nl_item = 0x2000C; +pub const DAY_7: ::nl_item = 0x2000D; + +pub const ABMON_1: ::nl_item = 0x2000E; +pub const ABMON_2: ::nl_item = 0x2000F; +pub const ABMON_3: ::nl_item = 0x20010; +pub const ABMON_4: ::nl_item = 0x20011; +pub const ABMON_5: ::nl_item = 0x20012; +pub const ABMON_6: ::nl_item = 0x20013; +pub const ABMON_7: ::nl_item = 0x20014; +pub const ABMON_8: ::nl_item = 0x20015; +pub const ABMON_9: ::nl_item = 0x20016; +pub const ABMON_10: ::nl_item = 0x20017; +pub const ABMON_11: ::nl_item = 0x20018; +pub const ABMON_12: ::nl_item = 0x20019; + +pub const MON_1: ::nl_item = 0x2001A; +pub const MON_2: ::nl_item = 0x2001B; +pub const MON_3: ::nl_item = 0x2001C; +pub const MON_4: ::nl_item = 0x2001D; +pub const MON_5: ::nl_item = 0x2001E; +pub const MON_6: ::nl_item = 0x2001F; +pub const MON_7: ::nl_item = 0x20020; +pub const MON_8: ::nl_item = 0x20021; +pub const MON_9: ::nl_item = 0x20022; +pub const MON_10: ::nl_item = 0x20023; +pub const MON_11: ::nl_item = 0x20024; +pub const MON_12: ::nl_item = 0x20025; + +pub const AM_STR: ::nl_item = 0x20026; +pub const PM_STR: ::nl_item = 0x20027; + +pub const D_T_FMT: ::nl_item = 0x20028; +pub const D_FMT: ::nl_item = 0x20029; +pub const T_FMT: ::nl_item = 0x2002A; +pub const T_FMT_AMPM: ::nl_item = 0x2002B; + +pub const ERA: ::nl_item = 0x2002C; +pub const ERA_D_FMT: ::nl_item = 0x2002E; +pub const ALT_DIGITS: ::nl_item = 0x2002F; +pub const ERA_D_T_FMT: ::nl_item = 0x20030; +pub const ERA_T_FMT: ::nl_item = 0x20031; + +pub const CODESET: ::nl_item = 14; + +pub const CRNCYSTR: ::nl_item = 0x4000F; + +pub const RUSAGE_THREAD: ::c_int = 1; +pub const RUSAGE_CHILDREN: ::c_int = -1; + +pub const RADIXCHAR: ::nl_item = 0x10000; +pub const THOUSEP: ::nl_item = 0x10001; + +pub const YESEXPR: ::nl_item = 0x50000; +pub const NOEXPR: ::nl_item = 0x50001; +pub const YESSTR: ::nl_item = 0x50002; +pub const NOSTR: ::nl_item = 0x50003; + +pub const FILENAME_MAX: ::c_uint = 4096; +pub const L_tmpnam: ::c_uint = 20; +pub const _PC_LINK_MAX: ::c_int = 0; +pub const _PC_MAX_CANON: ::c_int = 1; +pub const _PC_MAX_INPUT: ::c_int = 2; +pub const _PC_NAME_MAX: ::c_int = 3; +pub const _PC_PATH_MAX: ::c_int = 4; +pub const _PC_PIPE_BUF: ::c_int = 5; +pub const _PC_CHOWN_RESTRICTED: ::c_int = 6; +pub const _PC_NO_TRUNC: ::c_int = 7; +pub const _PC_VDISABLE: ::c_int = 8; +pub const _PC_SYNC_IO: ::c_int = 9; +pub const _PC_ASYNC_IO: ::c_int = 10; +pub const _PC_PRIO_IO: ::c_int = 11; +pub const _PC_SOCK_MAXBUF: ::c_int = 12; +pub const _PC_FILESIZEBITS: ::c_int = 13; +pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 14; +pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 15; +pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 16; +pub const _PC_REC_XFER_ALIGN: ::c_int = 17; +pub const _PC_ALLOC_SIZE_MIN: ::c_int = 18; +pub const _PC_SYMLINK_MAX: ::c_int = 19; +pub const _PC_2_SYMLINKS: ::c_int = 20; + +pub const _SC_ARG_MAX: ::c_int = 0; +pub const _SC_CHILD_MAX: ::c_int = 1; +pub const _SC_CLK_TCK: ::c_int = 2; +pub const _SC_NGROUPS_MAX: ::c_int = 3; +pub const _SC_OPEN_MAX: ::c_int = 4; +pub const _SC_STREAM_MAX: ::c_int = 5; +pub const _SC_TZNAME_MAX: ::c_int = 6; +pub const _SC_JOB_CONTROL: ::c_int = 7; +pub const _SC_SAVED_IDS: ::c_int = 8; +pub const _SC_REALTIME_SIGNALS: ::c_int = 9; +pub const _SC_PRIORITY_SCHEDULING: ::c_int = 10; +pub const _SC_TIMERS: ::c_int = 11; +pub const _SC_ASYNCHRONOUS_IO: ::c_int = 12; +pub const _SC_PRIORITIZED_IO: ::c_int = 13; +pub const _SC_SYNCHRONIZED_IO: ::c_int = 14; +pub const _SC_FSYNC: ::c_int = 15; +pub const _SC_MAPPED_FILES: ::c_int = 16; +pub const _SC_MEMLOCK: ::c_int = 17; +pub const _SC_MEMLOCK_RANGE: ::c_int = 18; +pub const _SC_MEMORY_PROTECTION: ::c_int = 19; +pub const _SC_MESSAGE_PASSING: ::c_int = 20; +pub const _SC_SEMAPHORES: ::c_int = 21; +pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 22; +pub const _SC_AIO_LISTIO_MAX: ::c_int = 23; +pub const _SC_AIO_MAX: ::c_int = 24; +pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 25; +pub const _SC_DELAYTIMER_MAX: ::c_int = 26; +pub const _SC_MQ_OPEN_MAX: ::c_int = 27; +pub const _SC_MQ_PRIO_MAX: ::c_int = 28; +pub const _SC_VERSION: ::c_int = 29; +pub const _SC_PAGESIZE: ::c_int = 30; +pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; +pub const _SC_RTSIG_MAX: ::c_int = 31; +pub const _SC_SEM_NSEMS_MAX: ::c_int = 32; +pub const _SC_SEM_VALUE_MAX: ::c_int = 33; +pub const _SC_SIGQUEUE_MAX: ::c_int = 34; +pub const _SC_TIMER_MAX: ::c_int = 35; +pub const _SC_BC_BASE_MAX: ::c_int = 36; +pub const _SC_BC_DIM_MAX: ::c_int = 37; +pub const _SC_BC_SCALE_MAX: ::c_int = 38; +pub const _SC_BC_STRING_MAX: ::c_int = 39; +pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 40; +pub const _SC_EXPR_NEST_MAX: ::c_int = 42; +pub const _SC_LINE_MAX: ::c_int = 43; +pub const _SC_RE_DUP_MAX: ::c_int = 44; +pub const _SC_2_VERSION: ::c_int = 46; +pub const _SC_2_C_BIND: ::c_int = 47; +pub const _SC_2_C_DEV: ::c_int = 48; +pub const _SC_2_FORT_DEV: ::c_int = 49; +pub const _SC_2_FORT_RUN: ::c_int = 50; +pub const _SC_2_SW_DEV: ::c_int = 51; +pub const _SC_2_LOCALEDEF: ::c_int = 52; +pub const _SC_UIO_MAXIOV: ::c_int = 60; +pub const _SC_IOV_MAX: ::c_int = 60; +pub const _SC_THREADS: ::c_int = 67; +pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 68; +pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 69; +pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 70; +pub const _SC_LOGIN_NAME_MAX: ::c_int = 71; +pub const _SC_TTY_NAME_MAX: ::c_int = 72; +pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 73; +pub const _SC_THREAD_KEYS_MAX: ::c_int = 74; +pub const _SC_THREAD_STACK_MIN: ::c_int = 75; +pub const _SC_THREAD_THREADS_MAX: ::c_int = 76; +pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 77; +pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 78; +pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 79; +pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 80; +pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 81; +pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 82; +pub const _SC_NPROCESSORS_CONF: ::c_int = 83; +pub const _SC_NPROCESSORS_ONLN: ::c_int = 84; +pub const _SC_PHYS_PAGES: ::c_int = 85; +pub const _SC_AVPHYS_PAGES: ::c_int = 86; +pub const _SC_ATEXIT_MAX: ::c_int = 87; +pub const _SC_PASS_MAX: ::c_int = 88; +pub const _SC_XOPEN_VERSION: ::c_int = 89; +pub const _SC_XOPEN_XCU_VERSION: ::c_int = 90; +pub const _SC_XOPEN_UNIX: ::c_int = 91; +pub const _SC_XOPEN_CRYPT: ::c_int = 92; +pub const _SC_XOPEN_ENH_I18N: ::c_int = 93; +pub const _SC_XOPEN_SHM: ::c_int = 94; +pub const _SC_2_CHAR_TERM: ::c_int = 95; +pub const _SC_2_UPE: ::c_int = 97; +pub const _SC_XOPEN_XPG2: ::c_int = 98; +pub const _SC_XOPEN_XPG3: ::c_int = 99; +pub const _SC_XOPEN_XPG4: ::c_int = 100; +pub const _SC_NZERO: ::c_int = 109; +pub const _SC_XBS5_ILP32_OFF32: ::c_int = 125; +pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 126; +pub const _SC_XBS5_LP64_OFF64: ::c_int = 127; +pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 128; +pub const _SC_XOPEN_LEGACY: ::c_int = 129; +pub const _SC_XOPEN_REALTIME: ::c_int = 130; +pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 131; +pub const _SC_ADVISORY_INFO: ::c_int = 132; +pub const _SC_BARRIERS: ::c_int = 133; +pub const _SC_CLOCK_SELECTION: ::c_int = 137; +pub const _SC_CPUTIME: ::c_int = 138; +pub const _SC_THREAD_CPUTIME: ::c_int = 139; +pub const _SC_MONOTONIC_CLOCK: ::c_int = 149; +pub const _SC_READER_WRITER_LOCKS: ::c_int = 153; +pub const _SC_SPIN_LOCKS: ::c_int = 154; +pub const _SC_REGEXP: ::c_int = 155; +pub const _SC_SHELL: ::c_int = 157; +pub const _SC_SPAWN: ::c_int = 159; +pub const _SC_SPORADIC_SERVER: ::c_int = 160; +pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 161; +pub const _SC_TIMEOUTS: ::c_int = 164; +pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 165; +pub const _SC_2_PBS: ::c_int = 168; +pub const _SC_2_PBS_ACCOUNTING: ::c_int = 169; +pub const _SC_2_PBS_LOCATE: ::c_int = 170; +pub const _SC_2_PBS_MESSAGE: ::c_int = 171; +pub const _SC_2_PBS_TRACK: ::c_int = 172; +pub const _SC_SYMLOOP_MAX: ::c_int = 173; +pub const _SC_STREAMS: ::c_int = 174; +pub const _SC_2_PBS_CHECKPOINT: ::c_int = 175; +pub const _SC_V6_ILP32_OFF32: ::c_int = 176; +pub const _SC_V6_ILP32_OFFBIG: ::c_int = 177; +pub const _SC_V6_LP64_OFF64: ::c_int = 178; +pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 179; +pub const _SC_HOST_NAME_MAX: ::c_int = 180; +pub const _SC_TRACE: ::c_int = 181; +pub const _SC_TRACE_EVENT_FILTER: ::c_int = 182; +pub const _SC_TRACE_INHERIT: ::c_int = 183; +pub const _SC_TRACE_LOG: ::c_int = 184; +pub const _SC_IPV6: ::c_int = 235; +pub const _SC_RAW_SOCKETS: ::c_int = 236; +pub const _SC_V7_ILP32_OFF32: ::c_int = 237; +pub const _SC_V7_ILP32_OFFBIG: ::c_int = 238; +pub const _SC_V7_LP64_OFF64: ::c_int = 239; +pub const _SC_V7_LPBIG_OFFBIG: ::c_int = 240; +pub const _SC_SS_REPL_MAX: ::c_int = 241; +pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 242; +pub const _SC_TRACE_NAME_MAX: ::c_int = 243; +pub const _SC_TRACE_SYS_MAX: ::c_int = 244; +pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 245; +pub const _SC_XOPEN_STREAMS: ::c_int = 246; +pub const _SC_THREAD_ROBUST_PRIO_INHERIT: ::c_int = 247; +pub const _SC_THREAD_ROBUST_PRIO_PROTECT: ::c_int = 248; + +pub const RLIM_SAVED_MAX: ::rlim_t = RLIM_INFINITY; +pub const RLIM_SAVED_CUR: ::rlim_t = RLIM_INFINITY; + +pub const GLOB_ERR: ::c_int = 1 << 0; +pub const GLOB_MARK: ::c_int = 1 << 1; +pub const GLOB_NOSORT: ::c_int = 1 << 2; +pub const GLOB_DOOFFS: ::c_int = 1 << 3; +pub const GLOB_NOCHECK: ::c_int = 1 << 4; +pub const GLOB_APPEND: ::c_int = 1 << 5; +pub const GLOB_NOESCAPE: ::c_int = 1 << 6; + +pub const GLOB_NOSPACE: ::c_int = 1; +pub const GLOB_ABORTED: ::c_int = 2; +pub const GLOB_NOMATCH: ::c_int = 3; + +pub const POSIX_MADV_NORMAL: ::c_int = 0; +pub const POSIX_MADV_RANDOM: ::c_int = 1; +pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_MADV_WILLNEED: ::c_int = 3; + +pub const S_IEXEC: mode_t = 64; +pub const S_IWRITE: mode_t = 128; +pub const S_IREAD: mode_t = 256; + +pub const F_LOCK: ::c_int = 1; +pub const F_TEST: ::c_int = 3; +pub const F_TLOCK: ::c_int = 2; +pub const F_ULOCK: ::c_int = 0; + +pub const IFF_LOWER_UP: ::c_int = 0x10000; +pub const IFF_DORMANT: ::c_int = 0x20000; +pub const IFF_ECHO: ::c_int = 0x40000; + +pub const ST_RDONLY: ::c_ulong = 1; +pub const ST_NOSUID: ::c_ulong = 2; +pub const ST_NODEV: ::c_ulong = 4; +pub const ST_NOEXEC: ::c_ulong = 8; +pub const ST_SYNCHRONOUS: ::c_ulong = 16; +pub const ST_MANDLOCK: ::c_ulong = 64; +pub const ST_WRITE: ::c_ulong = 128; +pub const ST_APPEND: ::c_ulong = 256; +pub const ST_IMMUTABLE: ::c_ulong = 512; +pub const ST_NOATIME: ::c_ulong = 1024; +pub const ST_NODIRATIME: ::c_ulong = 2048; + +pub const RTLD_NEXT: *mut ::c_void = -1i64 as *mut ::c_void; +pub const RTLD_DEFAULT: *mut ::c_void = 0i64 as *mut ::c_void; +pub const RTLD_NODELETE: ::c_int = 0x1000; +pub const RTLD_NOW: ::c_int = 0x2; + +pub const TCP_MD5SIG: ::c_int = 14; + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_MUTEX_T], +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_COND_T], +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_RWLOCK_T], +}; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; +pub const PTHREAD_PROCESS_PRIVATE: ::c_int = 0; +pub const PTHREAD_PROCESS_SHARED: ::c_int = 1; +pub const __SIZEOF_PTHREAD_COND_T: usize = 48; + +pub const RENAME_NOREPLACE: ::c_int = 1; +pub const RENAME_EXCHANGE: ::c_int = 2; +pub const RENAME_WHITEOUT: ::c_int = 4; + +pub const SCHED_OTHER: ::c_int = 0; +pub const SCHED_FIFO: ::c_int = 1; +pub const SCHED_RR: ::c_int = 2; +pub const SCHED_BATCH: ::c_int = 3; +pub const SCHED_IDLE: ::c_int = 5; + +// netinet/in.h +// NOTE: These are in addition to the constants defined in src/unix/mod.rs + +// IPPROTO_IP defined in src/unix/mod.rs +/// Hop-by-hop option header +pub const IPPROTO_HOPOPTS: ::c_int = 0; +// IPPROTO_ICMP defined in src/unix/mod.rs +/// group mgmt protocol +pub const IPPROTO_IGMP: ::c_int = 2; +/// for compatibility +pub const IPPROTO_IPIP: ::c_int = 4; +// IPPROTO_TCP defined in src/unix/mod.rs +/// exterior gateway protocol +pub const IPPROTO_EGP: ::c_int = 8; +/// pup +pub const IPPROTO_PUP: ::c_int = 12; +// IPPROTO_UDP defined in src/unix/mod.rs +/// xns idp +pub const IPPROTO_IDP: ::c_int = 22; +/// tp-4 w/ class negotiation +pub const IPPROTO_TP: ::c_int = 29; +/// DCCP +pub const IPPROTO_DCCP: ::c_int = 33; +// IPPROTO_IPV6 defined in src/unix/mod.rs +/// IP6 routing header +pub const IPPROTO_ROUTING: ::c_int = 43; +/// IP6 fragmentation header +pub const IPPROTO_FRAGMENT: ::c_int = 44; +/// resource reservation +pub const IPPROTO_RSVP: ::c_int = 46; +/// General Routing Encap. +pub const IPPROTO_GRE: ::c_int = 47; +/// IP6 Encap Sec. Payload +pub const IPPROTO_ESP: ::c_int = 50; +/// IP6 Auth Header +pub const IPPROTO_AH: ::c_int = 51; +// IPPROTO_ICMPV6 defined in src/unix/mod.rs +/// IP6 no next header +pub const IPPROTO_NONE: ::c_int = 59; +/// IP6 destination option +pub const IPPROTO_DSTOPTS: ::c_int = 60; +pub const IPPROTO_MTP: ::c_int = 92; +pub const IPPROTO_BEETPH: ::c_int = 94; +/// encapsulation header +pub const IPPROTO_ENCAP: ::c_int = 98; +/// Protocol indep. multicast +pub const IPPROTO_PIM: ::c_int = 103; +/// IP Payload Comp. Protocol +pub const IPPROTO_COMP: ::c_int = 108; +/// SCTP +pub const IPPROTO_SCTP: ::c_int = 132; +pub const IPPROTO_MH: ::c_int = 135; +pub const IPPROTO_UDPLITE: ::c_int = 136; +pub const IPPROTO_MPLS: ::c_int = 137; +/// raw IP packet +pub const IPPROTO_RAW: ::c_int = 255; +pub const IPPROTO_MAX: ::c_int = 256; + +pub const AF_IB: ::c_int = 27; +pub const AF_MPLS: ::c_int = 28; +pub const AF_NFC: ::c_int = 39; +pub const AF_VSOCK: ::c_int = 40; +pub const PF_IB: ::c_int = AF_IB; +pub const PF_MPLS: ::c_int = AF_MPLS; +pub const PF_NFC: ::c_int = AF_NFC; +pub const PF_VSOCK: ::c_int = AF_VSOCK; + +// System V IPC +pub const IPC_PRIVATE: ::key_t = 0; + +pub const IPC_CREAT: ::c_int = 0o1000; +pub const IPC_EXCL: ::c_int = 0o2000; +pub const IPC_NOWAIT: ::c_int = 0o4000; + +pub const IPC_RMID: ::c_int = 0; +pub const IPC_SET: ::c_int = 1; +pub const IPC_STAT: ::c_int = 2; +pub const IPC_INFO: ::c_int = 3; +pub const MSG_STAT: ::c_int = 11; +pub const MSG_INFO: ::c_int = 12; + +pub const MSG_NOERROR: ::c_int = 0o10000; +pub const MSG_EXCEPT: ::c_int = 0o20000; +pub const MSG_COPY: ::c_int = 0o40000; + +pub const SHM_R: ::c_int = 0o400; +pub const SHM_W: ::c_int = 0o200; + +pub const SHM_RDONLY: ::c_int = 0o10000; +pub const SHM_RND: ::c_int = 0o20000; +pub const SHM_REMAP: ::c_int = 0o40000; +pub const SHM_EXEC: ::c_int = 0o100000; + +pub const SHM_LOCK: ::c_int = 11; +pub const SHM_UNLOCK: ::c_int = 12; + +pub const SHM_HUGETLB: ::c_int = 0o4000; +pub const SHM_NORESERVE: ::c_int = 0o10000; + +pub const EPOLLRDHUP: ::c_int = 0x2000; +pub const EPOLLEXCLUSIVE: ::c_int = 0x10000000; +pub const EPOLLONESHOT: ::c_int = 0x40000000; + +pub const QFMT_VFS_OLD: ::c_int = 1; +pub const QFMT_VFS_V0: ::c_int = 2; +pub const QFMT_VFS_V1: ::c_int = 4; + +pub const EFD_SEMAPHORE: ::c_int = 0x1; + +pub const LOG_NFACILITIES: ::c_int = 24; + +pub const SEM_FAILED: *mut ::sem_t = 0 as *mut sem_t; + +pub const RB_AUTOBOOT: ::c_int = 0x01234567u32 as i32; +pub const RB_HALT_SYSTEM: ::c_int = 0xcdef0123u32 as i32; +pub const RB_ENABLE_CAD: ::c_int = 0x89abcdefu32 as i32; +pub const RB_DISABLE_CAD: ::c_int = 0x00000000u32 as i32; +pub const RB_POWER_OFF: ::c_int = 0x4321fedcu32 as i32; +pub const RB_SW_SUSPEND: ::c_int = 0xd000fce2u32 as i32; +pub const RB_KEXEC: ::c_int = 0x45584543u32 as i32; + +pub const AI_PASSIVE: ::c_int = 0x0001; +pub const AI_CANONNAME: ::c_int = 0x0002; +pub const AI_NUMERICHOST: ::c_int = 0x0004; +pub const AI_V4MAPPED: ::c_int = 0x0008; +pub const AI_ALL: ::c_int = 0x0010; +pub const AI_ADDRCONFIG: ::c_int = 0x0020; + +pub const AI_NUMERICSERV: ::c_int = 0x0400; + +pub const EAI_BADFLAGS: ::c_int = -1; +pub const EAI_NONAME: ::c_int = -2; +pub const EAI_AGAIN: ::c_int = -3; +pub const EAI_FAIL: ::c_int = -4; +pub const EAI_FAMILY: ::c_int = -6; +pub const EAI_SOCKTYPE: ::c_int = -7; +pub const EAI_SERVICE: ::c_int = -8; +pub const EAI_MEMORY: ::c_int = -10; +pub const EAI_OVERFLOW: ::c_int = -12; + +pub const NI_NUMERICHOST: ::c_int = 1; +pub const NI_NUMERICSERV: ::c_int = 2; +pub const NI_NOFQDN: ::c_int = 4; +pub const NI_NAMEREQD: ::c_int = 8; +pub const NI_DGRAM: ::c_int = 16; + +pub const SYNC_FILE_RANGE_WAIT_BEFORE: ::c_uint = 1; +pub const SYNC_FILE_RANGE_WRITE: ::c_uint = 2; +pub const SYNC_FILE_RANGE_WAIT_AFTER: ::c_uint = 4; + +pub const EAI_SYSTEM: ::c_int = -11; + +pub const AIO_CANCELED: ::c_int = 0; +pub const AIO_NOTCANCELED: ::c_int = 1; +pub const AIO_ALLDONE: ::c_int = 2; +pub const LIO_READ: ::c_int = 0; +pub const LIO_WRITE: ::c_int = 1; +pub const LIO_NOP: ::c_int = 2; +pub const LIO_WAIT: ::c_int = 0; +pub const LIO_NOWAIT: ::c_int = 1; + +pub const MREMAP_MAYMOVE: ::c_int = 1; +pub const MREMAP_FIXED: ::c_int = 2; + +pub const PR_SET_PDEATHSIG: ::c_int = 1; +pub const PR_GET_PDEATHSIG: ::c_int = 2; + +pub const PR_GET_DUMPABLE: ::c_int = 3; +pub const PR_SET_DUMPABLE: ::c_int = 4; + +pub const PR_GET_UNALIGN: ::c_int = 5; +pub const PR_SET_UNALIGN: ::c_int = 6; +pub const PR_UNALIGN_NOPRINT: ::c_int = 1; +pub const PR_UNALIGN_SIGBUS: ::c_int = 2; + +pub const PR_GET_KEEPCAPS: ::c_int = 7; +pub const PR_SET_KEEPCAPS: ::c_int = 8; + +pub const PR_GET_FPEMU: ::c_int = 9; +pub const PR_SET_FPEMU: ::c_int = 10; +pub const PR_FPEMU_NOPRINT: ::c_int = 1; +pub const PR_FPEMU_SIGFPE: ::c_int = 2; + +pub const PR_GET_FPEXC: ::c_int = 11; +pub const PR_SET_FPEXC: ::c_int = 12; +pub const PR_FP_EXC_SW_ENABLE: ::c_int = 0x80; +pub const PR_FP_EXC_DIV: ::c_int = 0x010000; +pub const PR_FP_EXC_OVF: ::c_int = 0x020000; +pub const PR_FP_EXC_UND: ::c_int = 0x040000; +pub const PR_FP_EXC_RES: ::c_int = 0x080000; +pub const PR_FP_EXC_INV: ::c_int = 0x100000; +pub const PR_FP_EXC_DISABLED: ::c_int = 0; +pub const PR_FP_EXC_NONRECOV: ::c_int = 1; +pub const PR_FP_EXC_ASYNC: ::c_int = 2; +pub const PR_FP_EXC_PRECISE: ::c_int = 3; + +pub const PR_GET_TIMING: ::c_int = 13; +pub const PR_SET_TIMING: ::c_int = 14; +pub const PR_TIMING_STATISTICAL: ::c_int = 0; +pub const PR_TIMING_TIMESTAMP: ::c_int = 1; + +pub const PR_SET_NAME: ::c_int = 15; +pub const PR_GET_NAME: ::c_int = 16; + +pub const PR_GET_ENDIAN: ::c_int = 19; +pub const PR_SET_ENDIAN: ::c_int = 20; +pub const PR_ENDIAN_BIG: ::c_int = 0; +pub const PR_ENDIAN_LITTLE: ::c_int = 1; +pub const PR_ENDIAN_PPC_LITTLE: ::c_int = 2; + +pub const PR_GET_SECCOMP: ::c_int = 21; +pub const PR_SET_SECCOMP: ::c_int = 22; + +pub const PR_CAPBSET_READ: ::c_int = 23; +pub const PR_CAPBSET_DROP: ::c_int = 24; + +pub const PR_GET_TSC: ::c_int = 25; +pub const PR_SET_TSC: ::c_int = 26; +pub const PR_TSC_ENABLE: ::c_int = 1; +pub const PR_TSC_SIGSEGV: ::c_int = 2; + +pub const PR_GET_SECUREBITS: ::c_int = 27; +pub const PR_SET_SECUREBITS: ::c_int = 28; + +pub const PR_SET_TIMERSLACK: ::c_int = 29; +pub const PR_GET_TIMERSLACK: ::c_int = 30; + +pub const PR_TASK_PERF_EVENTS_DISABLE: ::c_int = 31; +pub const PR_TASK_PERF_EVENTS_ENABLE: ::c_int = 32; + +pub const PR_MCE_KILL: ::c_int = 33; +pub const PR_MCE_KILL_CLEAR: ::c_int = 0; +pub const PR_MCE_KILL_SET: ::c_int = 1; + +pub const PR_MCE_KILL_LATE: ::c_int = 0; +pub const PR_MCE_KILL_EARLY: ::c_int = 1; +pub const PR_MCE_KILL_DEFAULT: ::c_int = 2; + +pub const PR_MCE_KILL_GET: ::c_int = 34; + +pub const PR_SET_MM: ::c_int = 35; +pub const PR_SET_MM_START_CODE: ::c_int = 1; +pub const PR_SET_MM_END_CODE: ::c_int = 2; +pub const PR_SET_MM_START_DATA: ::c_int = 3; +pub const PR_SET_MM_END_DATA: ::c_int = 4; +pub const PR_SET_MM_START_STACK: ::c_int = 5; +pub const PR_SET_MM_START_BRK: ::c_int = 6; +pub const PR_SET_MM_BRK: ::c_int = 7; +pub const PR_SET_MM_ARG_START: ::c_int = 8; +pub const PR_SET_MM_ARG_END: ::c_int = 9; +pub const PR_SET_MM_ENV_START: ::c_int = 10; +pub const PR_SET_MM_ENV_END: ::c_int = 11; +pub const PR_SET_MM_AUXV: ::c_int = 12; +pub const PR_SET_MM_EXE_FILE: ::c_int = 13; +pub const PR_SET_MM_MAP: ::c_int = 14; +pub const PR_SET_MM_MAP_SIZE: ::c_int = 15; + +pub const PR_SET_PTRACER: ::c_int = 0x59616d61; + +pub const PR_SET_CHILD_SUBREAPER: ::c_int = 36; +pub const PR_GET_CHILD_SUBREAPER: ::c_int = 37; + +pub const PR_SET_NO_NEW_PRIVS: ::c_int = 38; +pub const PR_GET_NO_NEW_PRIVS: ::c_int = 39; + +pub const PR_GET_TID_ADDRESS: ::c_int = 40; + +pub const PR_SET_THP_DISABLE: ::c_int = 41; +pub const PR_GET_THP_DISABLE: ::c_int = 42; + +pub const PR_MPX_ENABLE_MANAGEMENT: ::c_int = 43; +pub const PR_MPX_DISABLE_MANAGEMENT: ::c_int = 44; + +pub const PR_SET_FP_MODE: ::c_int = 45; +pub const PR_GET_FP_MODE: ::c_int = 46; +pub const PR_FP_MODE_FR: ::c_int = 1 << 0; +pub const PR_FP_MODE_FRE: ::c_int = 1 << 1; + +pub const PR_CAP_AMBIENT: ::c_int = 47; +pub const PR_CAP_AMBIENT_IS_SET: ::c_int = 1; +pub const PR_CAP_AMBIENT_RAISE: ::c_int = 2; +pub const PR_CAP_AMBIENT_LOWER: ::c_int = 3; +pub const PR_CAP_AMBIENT_CLEAR_ALL: ::c_int = 4; + +pub const GRND_NONBLOCK: ::c_uint = 0x0001; +pub const GRND_RANDOM: ::c_uint = 0x0002; + +pub const ITIMER_REAL: ::c_int = 0; +pub const ITIMER_VIRTUAL: ::c_int = 1; +pub const ITIMER_PROF: ::c_int = 2; + +pub const TFD_CLOEXEC: ::c_int = O_CLOEXEC; +pub const TFD_NONBLOCK: ::c_int = O_NONBLOCK; +pub const TFD_TIMER_ABSTIME: ::c_int = 1; + +pub const XATTR_CREATE: ::c_int = 0x1; +pub const XATTR_REPLACE: ::c_int = 0x2; + +pub const _POSIX_VDISABLE: ::cc_t = 0; + +pub const FALLOC_FL_KEEP_SIZE: ::c_int = 0x01; +pub const FALLOC_FL_PUNCH_HOLE: ::c_int = 0x02; +pub const FALLOC_FL_COLLAPSE_RANGE: ::c_int = 0x08; +pub const FALLOC_FL_ZERO_RANGE: ::c_int = 0x10; +pub const FALLOC_FL_INSERT_RANGE: ::c_int = 0x20; +pub const FALLOC_FL_UNSHARE_RANGE: ::c_int = 0x40; + +// On Linux, libc doesn't define this constant, libattr does instead. +// We still define it for Linux as it's defined by libc on other platforms, +// and it's mentioned in the man pages for getxattr and setxattr. +pub const ENOATTR: ::c_int = ::ENODATA; + +pub const SO_ORIGINAL_DST: ::c_int = 80; +pub const IUTF8: ::tcflag_t = 0x00004000; +pub const CMSPAR: ::tcflag_t = 0o10000000000; + +pub const MFD_CLOEXEC: ::c_uint = 0x0001; +pub const MFD_ALLOW_SEALING: ::c_uint = 0x0002; + +// these are used in the p_type field of Elf32_Phdr and Elf64_Phdr, which has +// the type Elf32Word and Elf64Word respectively. Luckily, both of those are u32 +// so we can use that type here to avoid having to cast. +pub const PT_NULL: u32 = 0; +pub const PT_LOAD: u32 = 1; +pub const PT_DYNAMIC: u32 = 2; +pub const PT_INTERP: u32 = 3; +pub const PT_NOTE: u32 = 4; +pub const PT_SHLIB: u32 = 5; +pub const PT_PHDR: u32 = 6; +pub const PT_TLS: u32 = 7; +pub const PT_NUM: u32 = 8; +pub const PT_LOOS: u32 = 0x60000000; +pub const PT_GNU_EH_FRAME: u32 = 0x6474e550; +pub const PT_GNU_STACK: u32 = 0x6474e551; +pub const PT_GNU_RELRO: u32 = 0x6474e552; + +pub const SFD_CLOEXEC: ::c_int = 0x080000; + +pub const NCCS: usize = 32; + +pub const O_TRUNC: ::c_int = 0x00040000; +pub const O_NOATIME: ::c_int = 0x00002000; +pub const O_CLOEXEC: ::c_int = 0x00000100; +pub const O_TMPFILE: ::c_int = 0x00004000; + +pub const EBFONT: ::c_int = 59; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const EDOTDOT: ::c_int = 73; + +pub const SA_NODEFER: ::c_int = 0x40000000; +pub const SA_RESETHAND: ::c_int = 0x80000000; +pub const SA_RESTART: ::c_int = 0x10000000; +pub const SA_NOCLDSTOP: ::c_int = 0x00000001; + +pub const EPOLL_CLOEXEC: ::c_int = 0x80000; + +pub const EFD_CLOEXEC: ::c_int = 0x80000; + +pub const BUFSIZ: ::c_uint = 1024; +pub const TMP_MAX: ::c_uint = 10000; +pub const FOPEN_MAX: ::c_uint = 1000; +pub const O_PATH: ::c_int = 0x00400000; +pub const O_EXEC: ::c_int = O_PATH; +pub const O_SEARCH: ::c_int = O_PATH; +pub const O_ACCMODE: ::c_int = (03 | O_SEARCH); +pub const O_NDELAY: ::c_int = O_NONBLOCK; +pub const NI_MAXHOST: ::socklen_t = 255; +pub const PTHREAD_STACK_MIN: ::size_t = 2048; +pub const POSIX_FADV_DONTNEED: ::c_int = 4; +pub const POSIX_FADV_NOREUSE: ::c_int = 5; + +pub const POSIX_MADV_DONTNEED: ::c_int = 4; + +pub const RLIM_INFINITY: ::rlim_t = !0; +pub const RLIMIT_RTTIME: ::c_int = 15; +pub const RLIMIT_NLIMITS: ::c_int = 16; + +pub const MAP_ANONYMOUS: ::c_int = MAP_ANON; + +pub const SOCK_DCCP: ::c_int = 6; +pub const SOCK_PACKET: ::c_int = 10; + +pub const TCP_COOKIE_TRANSACTIONS: ::c_int = 15; +pub const TCP_THIN_LINEAR_TIMEOUTS: ::c_int = 16; +pub const TCP_THIN_DUPACK: ::c_int = 17; +pub const TCP_USER_TIMEOUT: ::c_int = 18; +pub const TCP_REPAIR: ::c_int = 19; +pub const TCP_REPAIR_QUEUE: ::c_int = 20; +pub const TCP_QUEUE_SEQ: ::c_int = 21; +pub const TCP_REPAIR_OPTIONS: ::c_int = 22; +pub const TCP_FASTOPEN: ::c_int = 23; +pub const TCP_TIMESTAMP: ::c_int = 24; + +pub const SIGUNUSED: ::c_int = ::SIGSYS; + +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; + +pub const CPU_SETSIZE: ::c_int = 128; + +pub const PTRACE_TRACEME: ::c_int = 0; +pub const PTRACE_PEEKTEXT: ::c_int = 1; +pub const PTRACE_PEEKDATA: ::c_int = 2; +pub const PTRACE_PEEKUSER: ::c_int = 3; +pub const PTRACE_POKETEXT: ::c_int = 4; +pub const PTRACE_POKEDATA: ::c_int = 5; +pub const PTRACE_POKEUSER: ::c_int = 6; +pub const PTRACE_CONT: ::c_int = 7; +pub const PTRACE_KILL: ::c_int = 8; +pub const PTRACE_SINGLESTEP: ::c_int = 9; +pub const PTRACE_GETREGS: ::c_int = 12; +pub const PTRACE_SETREGS: ::c_int = 13; +pub const PTRACE_GETFPREGS: ::c_int = 14; +pub const PTRACE_SETFPREGS: ::c_int = 15; +pub const PTRACE_ATTACH: ::c_int = 16; +pub const PTRACE_DETACH: ::c_int = 17; +pub const PTRACE_GETFPXREGS: ::c_int = 18; +pub const PTRACE_SETFPXREGS: ::c_int = 19; +pub const PTRACE_SYSCALL: ::c_int = 24; +pub const PTRACE_SETOPTIONS: ::c_int = 0x4200; +pub const PTRACE_GETEVENTMSG: ::c_int = 0x4201; +pub const PTRACE_GETSIGINFO: ::c_int = 0x4202; +pub const PTRACE_SETSIGINFO: ::c_int = 0x4203; +pub const PTRACE_GETREGSET: ::c_int = 0x4204; +pub const PTRACE_SETREGSET: ::c_int = 0x4205; +pub const PTRACE_SEIZE: ::c_int = 0x4206; +pub const PTRACE_INTERRUPT: ::c_int = 0x4207; +pub const PTRACE_LISTEN: ::c_int = 0x4208; +pub const PTRACE_PEEKSIGINFO: ::c_int = 0x4209; + +pub const EPOLLWAKEUP: ::c_int = 0x20000000; + +pub const EFD_NONBLOCK: ::c_int = ::O_NONBLOCK; + +pub const SFD_NONBLOCK: ::c_int = ::O_NONBLOCK; + +pub const TCSANOW: ::c_int = 0; +pub const TCSADRAIN: ::c_int = 1; +pub const TCSAFLUSH: ::c_int = 2; + +pub const TIOCINQ: ::c_int = ::FIONREAD; + +pub const RTLD_GLOBAL: ::c_int = 0x100; +pub const RTLD_NOLOAD: ::c_int = 0x4; + +// TODO(#247) Temporarily musl-specific (available since musl 0.9.12 / Linux +// kernel 3.10). See also notbsd/mod.rs +pub const CLOCK_SGI_CYCLE: ::clockid_t = 10; +pub const CLOCK_TAI: ::clockid_t = 11; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const CBAUD: ::tcflag_t = 0o0010017; +pub const TAB1: ::c_int = 0x00000800; +pub const TAB2: ::c_int = 0x00001000; +pub const TAB3: ::c_int = 0x00001800; +pub const CR1: ::c_int = 0x00000200; +pub const CR2: ::c_int = 0x00000400; +pub const CR3: ::c_int = 0x00000600; +pub const FF1: ::c_int = 0x00008000; +pub const BS1: ::c_int = 0x00002000; +pub const VT1: ::c_int = 0x00004000; +pub const VWERASE: usize = 14; +pub const VREPRINT: usize = 12; +pub const VSUSP: usize = 10; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VDISCARD: usize = 13; +pub const VTIME: usize = 5; +pub const IXON: ::tcflag_t = 0x00000400; +pub const IXOFF: ::tcflag_t = 0x00001000; +pub const ONLCR: ::tcflag_t = 0x4; +pub const CSIZE: ::tcflag_t = 0x00000030; +pub const CS6: ::tcflag_t = 0x00000010; +pub const CS7: ::tcflag_t = 0x00000020; +pub const CS8: ::tcflag_t = 0x00000030; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const ECHOKE: ::tcflag_t = 0x00000800; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const ECHOPRT: ::tcflag_t = 0x00000400; +pub const ECHOCTL: ::tcflag_t = 0x00000200; +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const PENDIN: ::tcflag_t = 0x00004000; +pub const NOFLSH: ::tcflag_t = 0x00000080; +pub const CIBAUD: ::tcflag_t = 0o02003600000; +pub const CBAUDEX: ::tcflag_t = 0o010000; +pub const VSWTC: usize = 7; +pub const OLCUC: ::tcflag_t = 0o000002; +pub const NLDLY: ::tcflag_t = 0o000400; +pub const CRDLY: ::tcflag_t = 0o003000; +pub const TABDLY: ::tcflag_t = 0o014000; +pub const BSDLY: ::tcflag_t = 0o020000; +pub const FFDLY: ::tcflag_t = 0o100000; +pub const VTDLY: ::tcflag_t = 0o040000; +pub const XTABS: ::tcflag_t = 0o014000; + +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const B57600: ::speed_t = 0o010001; +pub const B115200: ::speed_t = 0o010002; +pub const B230400: ::speed_t = 0o010003; +pub const B460800: ::speed_t = 0o010004; +pub const B500000: ::speed_t = 0o010005; +pub const B576000: ::speed_t = 0o010006; +pub const B921600: ::speed_t = 0o010007; +pub const B1000000: ::speed_t = 0o010010; +pub const B1152000: ::speed_t = 0o010011; +pub const B1500000: ::speed_t = 0o010012; +pub const B2000000: ::speed_t = 0o010013; +pub const B2500000: ::speed_t = 0o010014; +pub const B3000000: ::speed_t = 0o010015; +pub const B3500000: ::speed_t = 0o010016; +pub const B4000000: ::speed_t = 0o010017; + +pub const SO_BINDTODEVICE: ::c_int = 25; +pub const SO_TIMESTAMP: ::c_int = 29; +pub const SO_MARK: ::c_int = 36; +pub const SO_RXQ_OVFL: ::c_int = 40; +pub const SO_PEEK_OFF: ::c_int = 42; +pub const SO_BUSY_POLL: ::c_int = 46; + +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; + +pub const O_ASYNC: ::c_int = 0x00000400; + +pub const FIOCLEX: ::c_int = 0x5451; +pub const FIONBIO: ::c_int = 0x5421; + +pub const RLIMIT_RSS: ::c_int = 5; +pub const RLIMIT_NOFILE: ::c_int = 7; +pub const RLIMIT_AS: ::c_int = 9; +pub const RLIMIT_NPROC: ::c_int = 6; +pub const RLIMIT_MEMLOCK: ::c_int = 8; + +pub const O_APPEND: ::c_int = 0x00100000; +pub const O_CREAT: ::c_int = 0x00010000; +pub const O_EXCL: ::c_int = 0x00020000; +pub const O_NOCTTY: ::c_int = 0x00000200; +pub const O_NONBLOCK: ::c_int = 0x00000010; +pub const O_SYNC: ::c_int = (0x00000040 | O_DSYNC); +pub const O_RSYNC: ::c_int = O_SYNC; +pub const O_DSYNC: ::c_int = 0x00000020; + +pub const SOCK_NONBLOCK: ::c_int = 2048; + +pub const MAP_ANON: ::c_int = 0x0020; +pub const MAP_GROWSDOWN: ::c_int = 0x0100; +pub const MAP_DENYWRITE: ::c_int = 0x0800; +pub const MAP_EXECUTABLE: ::c_int = 0x01000; +pub const MAP_LOCKED: ::c_int = 0x02000; +pub const MAP_NORESERVE: ::c_int = 0x04000; +pub const MAP_POPULATE: ::c_int = 0x08000; +pub const MAP_NONBLOCK: ::c_int = 0x010000; +pub const MAP_STACK: ::c_int = 0x020000; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_SEQPACKET: ::c_int = 5; + +pub const SOL_SOCKET: ::c_int = 1; + +pub const EDEADLK: ::c_int = 35; +pub const ENAMETOOLONG: ::c_int = 36; +pub const ENOLCK: ::c_int = 37; +pub const ENOSYS: ::c_int = 38; +pub const ENOTEMPTY: ::c_int = 39; +pub const ELOOP: ::c_int = 40; +pub const ENOMSG: ::c_int = 42; +pub const EIDRM: ::c_int = 43; +pub const ECHRNG: ::c_int = 44; +pub const EL2NSYNC: ::c_int = 45; +pub const EL3HLT: ::c_int = 46; +pub const EL3RST: ::c_int = 47; +pub const ELNRNG: ::c_int = 48; +pub const EUNATCH: ::c_int = 49; +pub const ENOCSI: ::c_int = 50; +pub const EL2HLT: ::c_int = 51; +pub const EBADE: ::c_int = 52; +pub const EBADR: ::c_int = 53; +pub const EXFULL: ::c_int = 54; +pub const ENOANO: ::c_int = 55; +pub const EBADRQC: ::c_int = 56; +pub const EBADSLT: ::c_int = 57; +pub const EDEADLOCK: ::c_int = EDEADLK; +pub const EMULTIHOP: ::c_int = 72; +pub const EBADMSG: ::c_int = 74; +pub const EOVERFLOW: ::c_int = 75; +pub const ENOTUNIQ: ::c_int = 76; +pub const EBADFD: ::c_int = 77; +pub const EREMCHG: ::c_int = 78; +pub const ELIBACC: ::c_int = 79; +pub const ELIBBAD: ::c_int = 80; +pub const ELIBSCN: ::c_int = 81; +pub const ELIBMAX: ::c_int = 82; +pub const ELIBEXEC: ::c_int = 83; +pub const EILSEQ: ::c_int = 84; +pub const ERESTART: ::c_int = 85; +pub const ESTRPIPE: ::c_int = 86; +pub const EUSERS: ::c_int = 87; +pub const ENOTSOCK: ::c_int = 88; +pub const EDESTADDRREQ: ::c_int = 89; +pub const EMSGSIZE: ::c_int = 90; +pub const EPROTOTYPE: ::c_int = 91; +pub const ENOPROTOOPT: ::c_int = 92; +pub const EPROTONOSUPPORT: ::c_int = 93; +pub const ESOCKTNOSUPPORT: ::c_int = 94; +pub const EOPNOTSUPP: ::c_int = 95; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; +pub const EPFNOSUPPORT: ::c_int = 96; +pub const EAFNOSUPPORT: ::c_int = 97; +pub const EADDRINUSE: ::c_int = 98; +pub const EADDRNOTAVAIL: ::c_int = 99; +pub const ENETDOWN: ::c_int = 100; +pub const ENETUNREACH: ::c_int = 101; +pub const ENETRESET: ::c_int = 102; +pub const ECONNABORTED: ::c_int = 103; +pub const ECONNRESET: ::c_int = 104; +pub const ENOBUFS: ::c_int = 105; +pub const EISCONN: ::c_int = 106; +pub const ENOTCONN: ::c_int = 107; +pub const ESHUTDOWN: ::c_int = 108; +pub const ETOOMANYREFS: ::c_int = 109; +pub const ETIMEDOUT: ::c_int = 110; +pub const ECONNREFUSED: ::c_int = 111; +pub const EHOSTDOWN: ::c_int = 112; +pub const EHOSTUNREACH: ::c_int = 113; +pub const EALREADY: ::c_int = 114; +pub const EINPROGRESS: ::c_int = 115; +pub const ESTALE: ::c_int = 116; +pub const EUCLEAN: ::c_int = 117; +pub const ENOTNAM: ::c_int = 118; +pub const ENAVAIL: ::c_int = 119; +pub const EISNAM: ::c_int = 120; +pub const EREMOTEIO: ::c_int = 121; +pub const EDQUOT: ::c_int = 122; +pub const ENOMEDIUM: ::c_int = 123; +pub const EMEDIUMTYPE: ::c_int = 124; +pub const ECANCELED: ::c_int = 125; +pub const ENOKEY: ::c_int = 126; +pub const EKEYEXPIRED: ::c_int = 127; +pub const EKEYREVOKED: ::c_int = 128; +pub const EKEYREJECTED: ::c_int = 129; +pub const EOWNERDEAD: ::c_int = 130; +pub const ENOTRECOVERABLE: ::c_int = 131; +pub const ERFKILL: ::c_int = 132; +pub const EHWPOISON: ::c_int = 133; + +pub const SO_REUSEADDR: ::c_int = 2; +pub const SO_TYPE: ::c_int = 3; +pub const SO_ERROR: ::c_int = 4; +pub const SO_DONTROUTE: ::c_int = 5; +pub const SO_BROADCAST: ::c_int = 6; +pub const SO_SNDBUF: ::c_int = 7; +pub const SO_RCVBUF: ::c_int = 8; +pub const SO_KEEPALIVE: ::c_int = 9; +pub const SO_OOBINLINE: ::c_int = 10; +pub const SO_NO_CHECK: ::c_int = 11; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_LINGER: ::c_int = 13; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_REUSEPORT: ::c_int = 15; +pub const SO_PASSCRED: ::c_int = 16; +pub const SO_PEERCRED: ::c_int = 17; +pub const SO_RCVLOWAT: ::c_int = 18; +pub const SO_SNDLOWAT: ::c_int = 19; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_SNDTIMEO: ::c_int = 21; +pub const SO_ACCEPTCONN: ::c_int = 30; +pub const SO_SNDBUFFORCE: ::c_int = 32; +pub const SO_RCVBUFFORCE: ::c_int = 33; +pub const SO_PROTOCOL: ::c_int = 38; +pub const SO_DOMAIN: ::c_int = 39; + +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 0x00000004; +pub const SA_NOCLDWAIT: ::c_int = 0x00000002; + +pub const SIGCHLD: ::c_int = 17; +pub const SIGBUS: ::c_int = 7; +pub const SIGTTIN: ::c_int = 21; +pub const SIGTTOU: ::c_int = 22; +pub const SIGXCPU: ::c_int = 24; +pub const SIGXFSZ: ::c_int = 25; +pub const SIGVTALRM: ::c_int = 26; +pub const SIGPROF: ::c_int = 27; +pub const SIGWINCH: ::c_int = 28; +pub const SIGUSR1: ::c_int = 10; +pub const SIGUSR2: ::c_int = 12; +pub const SIGCONT: ::c_int = 18; +pub const SIGSTOP: ::c_int = 19; +pub const SIGTSTP: ::c_int = 20; +pub const SIGURG: ::c_int = 23; +pub const SIGIO: ::c_int = 29; +pub const SIGSYS: ::c_int = 31; +pub const SIGSTKFLT: ::c_int = 16; +pub const SIGPOLL: ::c_int = 29; +pub const SIGPWR: ::c_int = 30; +pub const SIG_SETMASK: ::c_int = 2; +pub const SIG_BLOCK: ::c_int = 0x000000; +pub const SIG_UNBLOCK: ::c_int = 0x01; + +pub const EXTPROC: ::tcflag_t = 0x00010000; + +pub const MAP_HUGETLB: ::c_int = 0x040000; + +pub const F_GETLK: ::c_int = 5; +pub const F_GETOWN: ::c_int = 9; +pub const F_SETLK: ::c_int = 6; +pub const F_SETLKW: ::c_int = 7; +pub const F_SETOWN: ::c_int = 8; + +pub const VEOF: usize = 4; +pub const VEOL: usize = 11; +pub const VEOL2: usize = 16; +pub const VMIN: usize = 6; +pub const IEXTEN: ::tcflag_t = 0x00008000; +pub const TOSTOP: ::tcflag_t = 0x00000100; +pub const FLUSHO: ::tcflag_t = 0x00001000; + +pub const TCGETS: ::c_int = 0x5401; +pub const TCSETS: ::c_int = 0x5402; +pub const TCSETSW: ::c_int = 0x5403; +pub const TCSETSF: ::c_int = 0x5404; +pub const TCGETA: ::c_int = 0x5405; +pub const TCSETA: ::c_int = 0x5406; +pub const TCSETAW: ::c_int = 0x5407; +pub const TCSETAF: ::c_int = 0x5408; +pub const TCSBRK: ::c_int = 0x5409; +pub const TCXONC: ::c_int = 0x540A; +pub const TCFLSH: ::c_int = 0x540B; +pub const TIOCGSOFTCAR: ::c_int = 0x5419; +pub const TIOCSSOFTCAR: ::c_int = 0x541A; +pub const TIOCLINUX: ::c_int = 0x541C; +pub const TIOCGSERIAL: ::c_int = 0x541E; +pub const TIOCEXCL: ::c_int = 0x540C; +pub const TIOCNXCL: ::c_int = 0x540D; +pub const TIOCSCTTY: ::c_int = 0x540E; +pub const TIOCGPGRP: ::c_int = 0x540F; +pub const TIOCSPGRP: ::c_int = 0x5410; +pub const TIOCOUTQ: ::c_int = 0x5411; +pub const TIOCSTI: ::c_int = 0x5412; +pub const TIOCGWINSZ: ::c_int = 0x5413; +pub const TIOCSWINSZ: ::c_int = 0x5414; +pub const TIOCMGET: ::c_int = 0x5415; +pub const TIOCMBIS: ::c_int = 0x5416; +pub const TIOCMBIC: ::c_int = 0x5417; +pub const TIOCMSET: ::c_int = 0x5418; +pub const FIONREAD: ::c_int = 0x541B; +pub const TIOCCONS: ::c_int = 0x541D; + +pub const POLLWRNORM: ::c_short = 0x100; +pub const POLLWRBAND: ::c_short = 0x200; + +pub const TIOCM_LE: ::c_int = 0x001; +pub const TIOCM_DTR: ::c_int = 0x002; +pub const TIOCM_RTS: ::c_int = 0x004; +pub const TIOCM_ST: ::c_int = 0x008; +pub const TIOCM_SR: ::c_int = 0x010; +pub const TIOCM_CTS: ::c_int = 0x020; +pub const TIOCM_CAR: ::c_int = 0x040; +pub const TIOCM_RNG: ::c_int = 0x080; +pub const TIOCM_DSR: ::c_int = 0x100; +pub const TIOCM_CD: ::c_int = TIOCM_CAR; +pub const TIOCM_RI: ::c_int = TIOCM_RNG; + +pub const O_DIRECTORY: ::c_int = 0x00080000; +pub const O_DIRECT: ::c_int = 0x00000800; +pub const O_LARGEFILE: ::c_int = 0x00001000; +pub const O_NOFOLLOW: ::c_int = 0x00000080; + +// intentionally not public, only used for fd_set +cfg_if! { + if #[cfg(target_pointer_width = "32")] { + const ULONG_SIZE: usize = 32; + } else if #[cfg(target_pointer_width = "64")] { + const ULONG_SIZE: usize = 64; + } else { + // Unknown target_pointer_width + } +} + +// END_PUB_CONST + +f! { + pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { + let fd = fd as usize; + let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; + (*set).fds_bits[fd / size] &= !(1 << (fd % size)); + return + } + + pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { + let fd = fd as usize; + let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; + return ((*set).fds_bits[fd / size] & (1 << (fd % size))) != 0 + } + + pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { + let fd = fd as usize; + let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; + (*set).fds_bits[fd / size] |= 1 << (fd % size); + return + } + + pub fn FD_ZERO(set: *mut fd_set) -> () { + for slot in (*set).fds_bits.iter_mut() { + *slot = 0; + } + } + + pub fn WIFSTOPPED(status: ::c_int) -> bool { + (status & 0xff) == 0x7f + } + + pub fn WSTOPSIG(status: ::c_int) -> ::c_int { + (status >> 8) & 0xff + } + + pub fn WIFCONTINUED(status: ::c_int) -> bool { + status == 0xffff + } + + pub fn WIFSIGNALED(status: ::c_int) -> bool { + ((status & 0x7f) + 1) as i8 >= 2 + } + + pub fn WTERMSIG(status: ::c_int) -> ::c_int { + status & 0x7f + } + + pub fn WIFEXITED(status: ::c_int) -> bool { + (status & 0x7f) == 0 + } + + pub fn WEXITSTATUS(status: ::c_int) -> ::c_int { + (status >> 8) & 0xff + } + + pub fn WCOREDUMP(status: ::c_int) -> bool { + (status & 0x80) != 0 + } + + pub fn QCMD(cmd: ::c_int, type_: ::c_int) -> ::c_int { + (cmd << 8) | (type_ & 0x00ff) + } + + pub fn CPU_ZERO(cpuset: &mut cpu_set_t) -> () { + for slot in cpuset.bits.iter_mut() { + *slot = 0; + } + } + + pub fn CPU_SET(cpu: usize, cpuset: &mut cpu_set_t) -> () { + let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc + let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); + cpuset.bits[idx] |= 1 << offset; + () + } + + pub fn CPU_CLR(cpu: usize, cpuset: &mut cpu_set_t) -> () { + let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc + let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); + cpuset.bits[idx] &= !(1 << offset); + () + } + + pub fn CPU_ISSET(cpu: usize, cpuset: &cpu_set_t) -> bool { + let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); + let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); + 0 != (cpuset.bits[idx] & (1 << offset)) + } + + pub fn CPU_EQUAL(set1: &cpu_set_t, set2: &cpu_set_t) -> bool { + set1.bits == set2.bits + } + + pub fn major(dev: ::dev_t) -> ::c_uint { + let mut major = 0; + major |= (dev & 0x00000000000fff00) >> 8; + major |= (dev & 0xfffff00000000000) >> 32; + major as ::c_uint + } + + pub fn minor(dev: ::dev_t) -> ::c_uint { + let mut minor = 0; + minor |= (dev & 0x00000000000000ff) >> 0; + minor |= (dev & 0x00000ffffff00000) >> 12; + minor as ::c_uint + } + + pub fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + let mut dev = 0; + dev |= (major & 0x00000fff) << 8; + dev |= (major & 0xfffff000) << 32; + dev |= (minor & 0x000000ff) << 0; + dev |= (minor & 0xffffff00) << 12; + dev + } +} + +// EXTERN_FN + +#[link(name = "c")] +#[link(name = "fdio")] +extern {} + +extern { + pub fn getpwnam(name: *const ::c_char) -> *mut passwd; + pub fn getpwuid(uid: ::uid_t) -> *mut passwd; + + pub fn fprintf(stream: *mut ::FILE, + format: *const ::c_char, ...) -> ::c_int; + pub fn printf(format: *const ::c_char, ...) -> ::c_int; + pub fn snprintf(s: *mut ::c_char, n: ::size_t, + format: *const ::c_char, ...) -> ::c_int; + pub fn sprintf(s: *mut ::c_char, format: *const ::c_char, ...) -> ::c_int; + pub fn fscanf(stream: *mut ::FILE, format: *const ::c_char, ...) -> ::c_int; + pub fn scanf(format: *const ::c_char, ...) -> ::c_int; + pub fn sscanf(s: *const ::c_char, format: *const ::c_char, ...) -> ::c_int; + pub fn getchar_unlocked() -> ::c_int; + pub fn putchar_unlocked(c: ::c_int) -> ::c_int; + + pub fn socket(domain: ::c_int, ty: ::c_int, protocol: ::c_int) -> ::c_int; + pub fn connect(socket: ::c_int, address: *const sockaddr, + len: socklen_t) -> ::c_int; + pub fn listen(socket: ::c_int, backlog: ::c_int) -> ::c_int; + pub fn accept(socket: ::c_int, address: *mut sockaddr, + address_len: *mut socklen_t) -> ::c_int; + pub fn getpeername(socket: ::c_int, address: *mut sockaddr, + address_len: *mut socklen_t) -> ::c_int; + pub fn getsockname(socket: ::c_int, address: *mut sockaddr, + address_len: *mut socklen_t) -> ::c_int; + pub fn setsockopt(socket: ::c_int, level: ::c_int, name: ::c_int, + value: *const ::c_void, + option_len: socklen_t) -> ::c_int; + pub fn socketpair(domain: ::c_int, type_: ::c_int, protocol: ::c_int, + socket_vector: *mut ::c_int) -> ::c_int; + pub fn sendto(socket: ::c_int, buf: *const ::c_void, len: ::size_t, + flags: ::c_int, addr: *const sockaddr, + addrlen: socklen_t) -> ::ssize_t; + pub fn shutdown(socket: ::c_int, how: ::c_int) -> ::c_int; + + pub fn chmod(path: *const c_char, mode: mode_t) -> ::c_int; + pub fn fchmod(fd: ::c_int, mode: mode_t) -> ::c_int; + + pub fn fstat(fildes: ::c_int, buf: *mut stat) -> ::c_int; + + pub fn mkdir(path: *const c_char, mode: mode_t) -> ::c_int; + + pub fn stat(path: *const c_char, buf: *mut stat) -> ::c_int; + + pub fn pclose(stream: *mut ::FILE) -> ::c_int; + pub fn fdopen(fd: ::c_int, mode: *const c_char) -> *mut ::FILE; + pub fn fileno(stream: *mut ::FILE) -> ::c_int; + + pub fn open(path: *const c_char, oflag: ::c_int, ...) -> ::c_int; + pub fn creat(path: *const c_char, mode: mode_t) -> ::c_int; + pub fn fcntl(fd: ::c_int, cmd: ::c_int, ...) -> ::c_int; + + pub fn opendir(dirname: *const c_char) -> *mut ::DIR; + pub fn readdir(dirp: *mut ::DIR) -> *mut ::dirent; + pub fn readdir_r(dirp: *mut ::DIR, entry: *mut ::dirent, + result: *mut *mut ::dirent) -> ::c_int; + pub fn closedir(dirp: *mut ::DIR) -> ::c_int; + pub fn rewinddir(dirp: *mut ::DIR); + + pub fn openat(dirfd: ::c_int, pathname: *const ::c_char, + flags: ::c_int, ...) -> ::c_int; + pub fn fchmodat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t, flags: ::c_int) -> ::c_int; + pub fn fchown(fd: ::c_int, + owner: ::uid_t, + group: ::gid_t) -> ::c_int; + pub fn fchownat(dirfd: ::c_int, pathname: *const ::c_char, + owner: ::uid_t, group: ::gid_t, + flags: ::c_int) -> ::c_int; + pub fn fstatat(dirfd: ::c_int, pathname: *const ::c_char, + buf: *mut stat, flags: ::c_int) -> ::c_int; + pub fn linkat(olddirfd: ::c_int, oldpath: *const ::c_char, + newdirfd: ::c_int, newpath: *const ::c_char, + flags: ::c_int) -> ::c_int; + pub fn mkdirat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t) -> ::c_int; + pub fn readlinkat(dirfd: ::c_int, pathname: *const ::c_char, + buf: *mut ::c_char, bufsiz: ::size_t) -> ::ssize_t; + pub fn renameat(olddirfd: ::c_int, oldpath: *const ::c_char, + newdirfd: ::c_int, newpath: *const ::c_char) + -> ::c_int; + pub fn symlinkat(target: *const ::c_char, newdirfd: ::c_int, + linkpath: *const ::c_char) -> ::c_int; + pub fn unlinkat(dirfd: ::c_int, pathname: *const ::c_char, + flags: ::c_int) -> ::c_int; + + pub fn access(path: *const c_char, amode: ::c_int) -> ::c_int; + pub fn alarm(seconds: ::c_uint) -> ::c_uint; + pub fn chdir(dir: *const c_char) -> ::c_int; + pub fn fchdir(dirfd: ::c_int) -> ::c_int; + pub fn chown(path: *const c_char, uid: uid_t, + gid: gid_t) -> ::c_int; + pub fn lchown(path: *const c_char, uid: uid_t, + gid: gid_t) -> ::c_int; + pub fn close(fd: ::c_int) -> ::c_int; + pub fn dup(fd: ::c_int) -> ::c_int; + pub fn dup2(src: ::c_int, dst: ::c_int) -> ::c_int; + pub fn execl(path: *const c_char, + arg0: *const c_char, ...) -> ::c_int; + pub fn execle(path: *const ::c_char, + arg0: *const ::c_char, ...) -> ::c_int; + pub fn execlp(file: *const ::c_char, + arg0: *const ::c_char, ...) -> ::c_int; + pub fn execv(prog: *const c_char, + argv: *const *const c_char) -> ::c_int; + pub fn execve(prog: *const c_char, argv: *const *const c_char, + envp: *const *const c_char) + -> ::c_int; + pub fn execvp(c: *const c_char, + argv: *const *const c_char) -> ::c_int; + pub fn fork() -> pid_t; + pub fn fpathconf(filedes: ::c_int, name: ::c_int) -> c_long; + pub fn getcwd(buf: *mut c_char, size: ::size_t) -> *mut c_char; + pub fn getegid() -> gid_t; + pub fn geteuid() -> uid_t; + pub fn getgid() -> gid_t; + pub fn getgroups(ngroups_max: ::c_int, groups: *mut gid_t) + -> ::c_int; + pub fn getlogin() -> *mut c_char; + pub fn getopt(argc: ::c_int, argv: *const *mut c_char, + optstr: *const c_char) -> ::c_int; + pub fn getpgid(pid: pid_t) -> pid_t; + pub fn getpgrp() -> pid_t; + pub fn getpid() -> pid_t; + pub fn getppid() -> pid_t; + pub fn getuid() -> uid_t; + pub fn isatty(fd: ::c_int) -> ::c_int; + pub fn link(src: *const c_char, dst: *const c_char) -> ::c_int; + pub fn lseek(fd: ::c_int, offset: off_t, whence: ::c_int) -> off_t; + pub fn pathconf(path: *const c_char, name: ::c_int) -> c_long; + pub fn pause() -> ::c_int; + pub fn pipe(fds: *mut ::c_int) -> ::c_int; + pub fn posix_memalign(memptr: *mut *mut ::c_void, + align: ::size_t, + size: ::size_t) -> ::c_int; + pub fn read(fd: ::c_int, buf: *mut ::c_void, count: ::size_t) + -> ::ssize_t; + pub fn rmdir(path: *const c_char) -> ::c_int; + pub fn seteuid(uid: uid_t) -> ::c_int; + pub fn setgid(gid: gid_t) -> ::c_int; + pub fn setpgid(pid: pid_t, pgid: pid_t) -> ::c_int; + pub fn setsid() -> pid_t; + pub fn setuid(uid: uid_t) -> ::c_int; + pub fn sleep(secs: ::c_uint) -> ::c_uint; + pub fn nanosleep(rqtp: *const timespec, + rmtp: *mut timespec) -> ::c_int; + pub fn tcgetpgrp(fd: ::c_int) -> pid_t; + pub fn tcsetpgrp(fd: ::c_int, pgrp: ::pid_t) -> ::c_int; + pub fn ttyname(fd: ::c_int) -> *mut c_char; + pub fn unlink(c: *const c_char) -> ::c_int; + pub fn wait(status: *mut ::c_int) -> pid_t; + pub fn waitpid(pid: pid_t, status: *mut ::c_int, options: ::c_int) + -> pid_t; + pub fn write(fd: ::c_int, buf: *const ::c_void, count: ::size_t) + -> ::ssize_t; + pub fn pread(fd: ::c_int, buf: *mut ::c_void, count: ::size_t, + offset: off_t) -> ::ssize_t; + pub fn pwrite(fd: ::c_int, buf: *const ::c_void, count: ::size_t, + offset: off_t) -> ::ssize_t; + pub fn umask(mask: mode_t) -> mode_t; + + pub fn utime(file: *const c_char, buf: *const utimbuf) -> ::c_int; + + pub fn kill(pid: pid_t, sig: ::c_int) -> ::c_int; + + pub fn mlock(addr: *const ::c_void, len: ::size_t) -> ::c_int; + pub fn munlock(addr: *const ::c_void, len: ::size_t) -> ::c_int; + pub fn mlockall(flags: ::c_int) -> ::c_int; + pub fn munlockall() -> ::c_int; + + pub fn mmap(addr: *mut ::c_void, + len: ::size_t, + prot: ::c_int, + flags: ::c_int, + fd: ::c_int, + offset: off_t) + -> *mut ::c_void; + pub fn munmap(addr: *mut ::c_void, len: ::size_t) -> ::c_int; + + pub fn if_nametoindex(ifname: *const c_char) -> ::c_uint; + pub fn if_indextoname(ifindex: ::c_uint, + ifname: *mut ::c_char) -> *mut ::c_char; + + pub fn lstat(path: *const c_char, buf: *mut stat) -> ::c_int; + + pub fn fsync(fd: ::c_int) -> ::c_int; + + pub fn setenv(name: *const c_char, val: *const c_char, + overwrite: ::c_int) -> ::c_int; + pub fn unsetenv(name: *const c_char) -> ::c_int; + + pub fn symlink(path1: *const c_char, + path2: *const c_char) -> ::c_int; + + pub fn ftruncate(fd: ::c_int, length: off_t) -> ::c_int; + + pub fn signal(signum: ::c_int, handler: sighandler_t) -> sighandler_t; + + pub fn getrlimit(resource: ::c_int, rlim: *mut rlimit) -> ::c_int; + pub fn setrlimit(resource: ::c_int, rlim: *const rlimit) -> ::c_int; + pub fn getrusage(resource: ::c_int, usage: *mut rusage) -> ::c_int; + + pub fn realpath(pathname: *const ::c_char, resolved: *mut ::c_char) + -> *mut ::c_char; + + pub fn flock(fd: ::c_int, operation: ::c_int) -> ::c_int; + + pub fn gettimeofday(tp: *mut ::timeval, + tz: *mut ::c_void) -> ::c_int; + pub fn times(buf: *mut ::tms) -> ::clock_t; + + pub fn pthread_self() -> ::pthread_t; + pub fn pthread_join(native: ::pthread_t, + value: *mut *mut ::c_void) -> ::c_int; + pub fn pthread_exit(value: *mut ::c_void); + pub fn pthread_attr_init(attr: *mut ::pthread_attr_t) -> ::c_int; + pub fn pthread_attr_destroy(attr: *mut ::pthread_attr_t) -> ::c_int; + pub fn pthread_attr_setstacksize(attr: *mut ::pthread_attr_t, + stack_size: ::size_t) -> ::c_int; + pub fn pthread_attr_setdetachstate(attr: *mut ::pthread_attr_t, + state: ::c_int) -> ::c_int; + pub fn pthread_detach(thread: ::pthread_t) -> ::c_int; + pub fn sched_yield() -> ::c_int; + pub fn pthread_key_create(key: *mut pthread_key_t, + dtor: Option) + -> ::c_int; + pub fn pthread_key_delete(key: pthread_key_t) -> ::c_int; + pub fn pthread_getspecific(key: pthread_key_t) -> *mut ::c_void; + pub fn pthread_setspecific(key: pthread_key_t, value: *const ::c_void) + -> ::c_int; + pub fn pthread_mutex_init(lock: *mut pthread_mutex_t, + attr: *const pthread_mutexattr_t) -> ::c_int; + pub fn pthread_mutex_destroy(lock: *mut pthread_mutex_t) -> ::c_int; + pub fn pthread_mutex_lock(lock: *mut pthread_mutex_t) -> ::c_int; + pub fn pthread_mutex_trylock(lock: *mut pthread_mutex_t) -> ::c_int; + pub fn pthread_mutex_unlock(lock: *mut pthread_mutex_t) -> ::c_int; + + pub fn pthread_mutexattr_init(attr: *mut pthread_mutexattr_t) -> ::c_int; + pub fn pthread_mutexattr_destroy(attr: *mut pthread_mutexattr_t) -> ::c_int; + pub fn pthread_mutexattr_settype(attr: *mut pthread_mutexattr_t, + _type: ::c_int) -> ::c_int; + + pub fn pthread_cond_init(cond: *mut pthread_cond_t, + attr: *const pthread_condattr_t) -> ::c_int; + pub fn pthread_cond_wait(cond: *mut pthread_cond_t, + lock: *mut pthread_mutex_t) -> ::c_int; + pub fn pthread_cond_timedwait(cond: *mut pthread_cond_t, + lock: *mut pthread_mutex_t, + abstime: *const ::timespec) -> ::c_int; + pub fn pthread_cond_signal(cond: *mut pthread_cond_t) -> ::c_int; + pub fn pthread_cond_broadcast(cond: *mut pthread_cond_t) -> ::c_int; + pub fn pthread_cond_destroy(cond: *mut pthread_cond_t) -> ::c_int; + pub fn pthread_condattr_init(attr: *mut pthread_condattr_t) -> ::c_int; + pub fn pthread_condattr_destroy(attr: *mut pthread_condattr_t) -> ::c_int; + pub fn pthread_rwlock_init(lock: *mut pthread_rwlock_t, + attr: *const pthread_rwlockattr_t) -> ::c_int; + pub fn pthread_rwlock_destroy(lock: *mut pthread_rwlock_t) -> ::c_int; + pub fn pthread_rwlock_rdlock(lock: *mut pthread_rwlock_t) -> ::c_int; + pub fn pthread_rwlock_tryrdlock(lock: *mut pthread_rwlock_t) -> ::c_int; + pub fn pthread_rwlock_wrlock(lock: *mut pthread_rwlock_t) -> ::c_int; + pub fn pthread_rwlock_trywrlock(lock: *mut pthread_rwlock_t) -> ::c_int; + pub fn pthread_rwlock_unlock(lock: *mut pthread_rwlock_t) -> ::c_int; + pub fn pthread_rwlockattr_init(attr: *mut pthread_rwlockattr_t) -> ::c_int; + pub fn pthread_rwlockattr_destroy(attr: *mut pthread_rwlockattr_t) + -> ::c_int; + pub fn strerror_r(errnum: ::c_int, buf: *mut c_char, + buflen: ::size_t) -> ::c_int; + + pub fn getsockopt(sockfd: ::c_int, + level: ::c_int, + optname: ::c_int, + optval: *mut ::c_void, + optlen: *mut ::socklen_t) -> ::c_int; + pub fn raise(signum: ::c_int) -> ::c_int; + pub fn sigaction(signum: ::c_int, + act: *const sigaction, + oldact: *mut sigaction) -> ::c_int; + + pub fn utimes(filename: *const ::c_char, + times: *const ::timeval) -> ::c_int; + pub fn dlopen(filename: *const ::c_char, + flag: ::c_int) -> *mut ::c_void; + pub fn dlerror() -> *mut ::c_char; + pub fn dlsym(handle: *mut ::c_void, + symbol: *const ::c_char) -> *mut ::c_void; + pub fn dlclose(handle: *mut ::c_void) -> ::c_int; + pub fn dladdr(addr: *const ::c_void, info: *mut Dl_info) -> ::c_int; + + pub fn getaddrinfo(node: *const c_char, + service: *const c_char, + hints: *const addrinfo, + res: *mut *mut addrinfo) -> ::c_int; + pub fn freeaddrinfo(res: *mut addrinfo); + pub fn gai_strerror(errcode: ::c_int) -> *const ::c_char; + pub fn res_init() -> ::c_int; + + pub fn gmtime_r(time_p: *const time_t, result: *mut tm) -> *mut tm; + pub fn localtime_r(time_p: *const time_t, result: *mut tm) -> *mut tm; + pub fn mktime(tm: *mut tm) -> time_t; + pub fn time(time: *mut time_t) -> time_t; + pub fn gmtime(time_p: *const time_t) -> *mut tm; + pub fn localtime(time_p: *const time_t) -> *mut tm; + + pub fn mknod(pathname: *const ::c_char, mode: ::mode_t, + dev: ::dev_t) -> ::c_int; + pub fn uname(buf: *mut ::utsname) -> ::c_int; + pub fn gethostname(name: *mut ::c_char, len: ::size_t) -> ::c_int; + pub fn getservbyname(name: *const ::c_char, + proto: *const ::c_char) -> *mut servent; + pub fn getprotobyname(name: *const ::c_char) -> *mut protoent; + pub fn getprotobynumber(proto: ::c_int) -> *mut protoent; + pub fn chroot(name: *const ::c_char) -> ::c_int; + pub fn usleep(secs: ::c_uint) -> ::c_int; + pub fn send(socket: ::c_int, buf: *const ::c_void, len: ::size_t, + flags: ::c_int) -> ::ssize_t; + pub fn recv(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, + flags: ::c_int) -> ::ssize_t; + pub fn putenv(string: *mut c_char) -> ::c_int; + pub fn poll(fds: *mut pollfd, nfds: nfds_t, timeout: ::c_int) -> ::c_int; + pub fn select(nfds: ::c_int, + readfs: *mut fd_set, + writefds: *mut fd_set, + errorfds: *mut fd_set, + timeout: *mut timeval) -> ::c_int; + pub fn setlocale(category: ::c_int, + locale: *const ::c_char) -> *mut ::c_char; + pub fn localeconv() -> *mut lconv; + + pub fn sem_destroy(sem: *mut sem_t) -> ::c_int; + pub fn sem_wait(sem: *mut sem_t) -> ::c_int; + pub fn sem_trywait(sem: *mut sem_t) -> ::c_int; + pub fn sem_post(sem: *mut sem_t) -> ::c_int; + pub fn sem_init(sem: *mut sem_t, + pshared: ::c_int, + value: ::c_uint) + -> ::c_int; + pub fn statvfs(path: *const c_char, buf: *mut statvfs) -> ::c_int; + pub fn fstatvfs(fd: ::c_int, buf: *mut statvfs) -> ::c_int; + + pub fn readlink(path: *const c_char, + buf: *mut c_char, + bufsz: ::size_t) + -> ::ssize_t; + + pub fn sigemptyset(set: *mut sigset_t) -> ::c_int; + pub fn sigaddset(set: *mut sigset_t, signum: ::c_int) -> ::c_int; + pub fn sigfillset(set: *mut sigset_t) -> ::c_int; + pub fn sigdelset(set: *mut sigset_t, signum: ::c_int) -> ::c_int; + pub fn sigismember(set: *const sigset_t, signum: ::c_int) -> ::c_int; + + pub fn sigprocmask(how: ::c_int, + set: *const sigset_t, + oldset: *mut sigset_t) + -> ::c_int; + pub fn sigpending(set: *mut sigset_t) -> ::c_int; + + pub fn timegm(tm: *mut ::tm) -> time_t; + + pub fn getsid(pid: pid_t) -> pid_t; + + pub fn sysconf(name: ::c_int) -> ::c_long; + + pub fn mkfifo(path: *const c_char, mode: mode_t) -> ::c_int; + + pub fn pselect(nfds: ::c_int, + readfs: *mut fd_set, + writefds: *mut fd_set, + errorfds: *mut fd_set, + timeout: *const timespec, + sigmask: *const sigset_t) -> ::c_int; + pub fn fseeko(stream: *mut ::FILE, + offset: ::off_t, + whence: ::c_int) -> ::c_int; + pub fn ftello(stream: *mut ::FILE) -> ::off_t; + pub fn tcdrain(fd: ::c_int) -> ::c_int; + pub fn cfgetispeed(termios: *const ::termios) -> ::speed_t; + pub fn cfgetospeed(termios: *const ::termios) -> ::speed_t; + pub fn cfmakeraw(termios: *mut ::termios); + pub fn cfsetispeed(termios: *mut ::termios, speed: ::speed_t) -> ::c_int; + pub fn cfsetospeed(termios: *mut ::termios, speed: ::speed_t) -> ::c_int; + pub fn cfsetspeed(termios: *mut ::termios, speed: ::speed_t) -> ::c_int; + pub fn tcgetattr(fd: ::c_int, termios: *mut ::termios) -> ::c_int; + pub fn tcsetattr(fd: ::c_int, + optional_actions: ::c_int, + termios: *const ::termios) -> ::c_int; + pub fn tcflow(fd: ::c_int, action: ::c_int) -> ::c_int; + pub fn tcflush(fd: ::c_int, action: ::c_int) -> ::c_int; + pub fn tcgetsid(fd: ::c_int) -> ::pid_t; + pub fn tcsendbreak(fd: ::c_int, duration: ::c_int) -> ::c_int; + pub fn mkstemp(template: *mut ::c_char) -> ::c_int; + pub fn mkdtemp(template: *mut ::c_char) -> *mut ::c_char; + + pub fn tmpnam(ptr: *mut ::c_char) -> *mut ::c_char; + + pub fn openlog(ident: *const ::c_char, logopt: ::c_int, facility: ::c_int); + pub fn closelog(); + pub fn setlogmask(maskpri: ::c_int) -> ::c_int; + pub fn syslog(priority: ::c_int, message: *const ::c_char, ...); + pub fn nice(incr: ::c_int) -> ::c_int; + + pub fn grantpt(fd: ::c_int) -> ::c_int; + pub fn posix_openpt(flags: ::c_int) -> ::c_int; + pub fn ptsname(fd: ::c_int) -> *mut ::c_char; + pub fn unlockpt(fd: ::c_int) -> ::c_int; + + pub fn fdatasync(fd: ::c_int) -> ::c_int; + pub fn mincore(addr: *mut ::c_void, len: ::size_t, + vec: *mut ::c_uchar) -> ::c_int; + pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; + pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; + + pub fn pthread_getattr_np(native: ::pthread_t, + attr: *mut ::pthread_attr_t) -> ::c_int; + pub fn pthread_attr_getstack(attr: *const ::pthread_attr_t, + stackaddr: *mut *mut ::c_void, + stacksize: *mut ::size_t) -> ::c_int; + pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; + pub fn setgroups(ngroups: ::size_t, + ptr: *const ::gid_t) -> ::c_int; + pub fn pipe2(fds: *mut ::c_int, flags: ::c_int) -> ::c_int; + pub fn statfs(path: *const ::c_char, buf: *mut statfs) -> ::c_int; + pub fn statfs64(path: *const ::c_char, buf: *mut statfs64) -> ::c_int; + pub fn fstatfs(fd: ::c_int, buf: *mut statfs) -> ::c_int; + pub fn fstatfs64(fd: ::c_int, buf: *mut statfs64) -> ::c_int; + pub fn statvfs64(path: *const ::c_char, buf: *mut statvfs64) -> ::c_int; + pub fn fstatvfs64(fd: ::c_int, buf: *mut statvfs64) -> ::c_int; + pub fn memrchr(cx: *const ::c_void, + c: ::c_int, + n: ::size_t) -> *mut ::c_void; + + pub fn posix_fadvise(fd: ::c_int, offset: ::off_t, len: ::off_t, + advise: ::c_int) -> ::c_int; + pub fn futimens(fd: ::c_int, times: *const ::timespec) -> ::c_int; + pub fn utimensat(dirfd: ::c_int, path: *const ::c_char, + times: *const ::timespec, flag: ::c_int) -> ::c_int; + pub fn duplocale(base: ::locale_t) -> ::locale_t; + pub fn freelocale(loc: ::locale_t); + pub fn newlocale(mask: ::c_int, + locale: *const ::c_char, + base: ::locale_t) -> ::locale_t; + pub fn uselocale(loc: ::locale_t) -> ::locale_t; + pub fn creat64(path: *const c_char, mode: mode_t) -> ::c_int; + pub fn fstat64(fildes: ::c_int, buf: *mut stat64) -> ::c_int; + pub fn fstatat64(dirfd: ::c_int, pathname: *const c_char, + buf: *mut stat64, flags: ::c_int) -> ::c_int; + pub fn ftruncate64(fd: ::c_int, length: off64_t) -> ::c_int; + pub fn getrlimit64(resource: ::c_int, rlim: *mut rlimit64) -> ::c_int; + pub fn lseek64(fd: ::c_int, offset: off64_t, whence: ::c_int) -> off64_t; + pub fn lstat64(path: *const c_char, buf: *mut stat64) -> ::c_int; + pub fn mmap64(addr: *mut ::c_void, + len: ::size_t, + prot: ::c_int, + flags: ::c_int, + fd: ::c_int, + offset: off64_t) + -> *mut ::c_void; + pub fn open64(path: *const c_char, oflag: ::c_int, ...) -> ::c_int; + pub fn openat64(fd: ::c_int, + path: *const c_char, + oflag: ::c_int, ...) -> ::c_int; + pub fn pread64(fd: ::c_int, buf: *mut ::c_void, count: ::size_t, + offset: off64_t) -> ::ssize_t; + pub fn preadv64(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off64_t) -> ::ssize_t; + pub fn pwrite64(fd: ::c_int, buf: *const ::c_void, count: ::size_t, + offset: off64_t) -> ::ssize_t; + pub fn pwritev64(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off64_t) -> ::ssize_t; + pub fn readdir64(dirp: *mut ::DIR) -> *mut ::dirent64; + pub fn readdir64_r(dirp: *mut ::DIR, entry: *mut ::dirent64, + result: *mut *mut ::dirent64) -> ::c_int; + pub fn setrlimit64(resource: ::c_int, rlim: *const rlimit64) -> ::c_int; + pub fn stat64(path: *const c_char, buf: *mut stat64) -> ::c_int; + pub fn truncate64(path: *const c_char, length: off64_t) -> ::c_int; + + pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; + + pub fn mknodat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t, dev: dev_t) -> ::c_int; + pub fn pthread_condattr_getclock(attr: *const pthread_condattr_t, + clock_id: *mut clockid_t) -> ::c_int; + pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, + clock_id: ::clockid_t) -> ::c_int; + pub fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, + pshared: ::c_int) -> ::c_int; + pub fn accept4(fd: ::c_int, addr: *mut ::sockaddr, len: *mut ::socklen_t, + flg: ::c_int) -> ::c_int; + pub fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, + pshared: ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, + val: *mut ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, + val: ::c_int) -> ::c_int; + pub fn ptsname_r(fd: ::c_int, + buf: *mut ::c_char, + buflen: ::size_t) -> ::c_int; + pub fn clearenv() -> ::c_int; + pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, + options: ::c_int) -> ::c_int; + pub fn setreuid(ruid: ::uid_t, euid: ::uid_t) -> ::c_int; + pub fn setregid(rgid: ::gid_t, egid: ::gid_t) -> ::c_int; + pub fn getresuid(ruid: *mut ::uid_t, euid: *mut ::uid_t, + suid: *mut ::uid_t) -> ::c_int; + pub fn getresgid(rgid: *mut ::gid_t, egid: *mut ::gid_t, + sgid: *mut ::gid_t) -> ::c_int; + pub fn acct(filename: *const ::c_char) -> ::c_int; + pub fn brk(addr: *mut ::c_void) -> ::c_int; + pub fn sbrk(increment: ::intptr_t) -> *mut ::c_void; + pub fn vfork() -> ::pid_t; + pub fn setresgid(rgid: ::gid_t, egid: ::gid_t, sgid: ::gid_t) -> ::c_int; + pub fn setresuid(ruid: ::uid_t, euid: ::uid_t, suid: ::uid_t) -> ::c_int; + pub fn wait4(pid: ::pid_t, status: *mut ::c_int, options: ::c_int, + rusage: *mut ::rusage) -> ::pid_t; + pub fn openpty(amaster: *mut ::c_int, + aslave: *mut ::c_int, + name: *mut ::c_char, + termp: *const termios, + winp: *const ::winsize) -> ::c_int; + pub fn execvpe(file: *const ::c_char, argv: *const *const ::c_char, + envp: *const *const ::c_char) -> ::c_int; + pub fn fexecve(fd: ::c_int, argv: *const *const ::c_char, + envp: *const *const ::c_char) + -> ::c_int; + + pub fn ioctl(fd: ::c_int, request: ::c_int, ...) -> ::c_int; + pub fn ptrace(request: ::c_int, ...) -> ::c_long; + pub fn getpriority(which: ::c_int, who: ::id_t) -> ::c_int; + pub fn setpriority(which: ::c_int, who: ::id_t, prio: ::c_int) -> ::c_int; + + pub fn aio_read(aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_write(aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_fsync(op: ::c_int, aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_error(aiocbp: *const aiocb) -> ::c_int; + pub fn aio_return(aiocbp: *mut aiocb) -> ::ssize_t; + pub fn aio_suspend(aiocb_list: *const *const aiocb, nitems: ::c_int, + timeout: *const ::timespec) -> ::c_int; + pub fn aio_cancel(fd: ::c_int, aiocbp: *mut aiocb) -> ::c_int; + pub fn lio_listio(mode: ::c_int, aiocb_list: *const *mut aiocb, + nitems: ::c_int, sevp: *mut ::sigevent) -> ::c_int; + + pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; + + pub fn setpwent(); + pub fn endpwent(); + pub fn getpwent() -> *mut passwd; + pub fn setspent(); + pub fn endspent(); + pub fn getspent() -> *mut spwd; + pub fn getspnam(__name: *const ::c_char) -> *mut spwd; + + pub fn shm_open(name: *const c_char, oflag: ::c_int, + mode: mode_t) -> ::c_int; + + // System V IPC + pub fn shmget(key: ::key_t, size: ::size_t, shmflg: ::c_int) -> ::c_int; + pub fn shmat(shmid: ::c_int, + shmaddr: *const ::c_void, + shmflg: ::c_int) -> *mut ::c_void; + pub fn shmdt(shmaddr: *const ::c_void) -> ::c_int; + pub fn shmctl(shmid: ::c_int, + cmd: ::c_int, + buf: *mut ::shmid_ds) -> ::c_int; + pub fn ftok(pathname: *const ::c_char, proj_id: ::c_int) -> ::key_t; + pub fn semget(key: ::key_t, nsems: ::c_int, semflag: ::c_int) -> ::c_int; + pub fn semop(semid: ::c_int, + sops: *mut ::sembuf, nsops: ::size_t) -> ::c_int; + pub fn semctl(semid: ::c_int, + semnum: ::c_int, cmd: ::c_int, ...) -> ::c_int; + pub fn msgctl(msqid: ::c_int, cmd: ::c_int, buf: *mut msqid_ds) -> ::c_int; + pub fn msgget(key: ::key_t, msgflg: ::c_int) -> ::c_int; + pub fn msgrcv(msqid: ::c_int, msgp: *mut ::c_void, msgsz: ::size_t, + msgtyp: ::c_long, msgflg: ::c_int) -> ::ssize_t; + pub fn msgsnd(msqid: ::c_int, msgp: *const ::c_void, msgsz: ::size_t, + msgflg: ::c_int) -> ::c_int; + + pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) + -> ::c_int; + pub fn __errno_location() -> *mut ::c_int; + + pub fn fopen64(filename: *const c_char, + mode: *const c_char) -> *mut ::FILE; + pub fn freopen64(filename: *const c_char, mode: *const c_char, + file: *mut ::FILE) -> *mut ::FILE; + pub fn tmpfile64() -> *mut ::FILE; + pub fn fgetpos64(stream: *mut ::FILE, ptr: *mut fpos64_t) -> ::c_int; + pub fn fsetpos64(stream: *mut ::FILE, ptr: *const fpos64_t) -> ::c_int; + pub fn fseeko64(stream: *mut ::FILE, + offset: ::off64_t, + whence: ::c_int) -> ::c_int; + pub fn ftello64(stream: *mut ::FILE) -> ::off64_t; + pub fn fallocate(fd: ::c_int, mode: ::c_int, + offset: ::off_t, len: ::off_t) -> ::c_int; + pub fn posix_fallocate(fd: ::c_int, offset: ::off_t, + len: ::off_t) -> ::c_int; + pub fn readahead(fd: ::c_int, offset: ::off64_t, + count: ::size_t) -> ::ssize_t; + pub fn getxattr(path: *const c_char, name: *const c_char, + value: *mut ::c_void, size: ::size_t) -> ::ssize_t; + pub fn lgetxattr(path: *const c_char, name: *const c_char, + value: *mut ::c_void, size: ::size_t) -> ::ssize_t; + pub fn fgetxattr(filedes: ::c_int, name: *const c_char, + value: *mut ::c_void, size: ::size_t) -> ::ssize_t; + pub fn setxattr(path: *const c_char, name: *const c_char, + value: *const ::c_void, size: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn lsetxattr(path: *const c_char, name: *const c_char, + value: *const ::c_void, size: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn fsetxattr(filedes: ::c_int, name: *const c_char, + value: *const ::c_void, size: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn listxattr(path: *const c_char, list: *mut c_char, + size: ::size_t) -> ::ssize_t; + pub fn llistxattr(path: *const c_char, list: *mut c_char, + size: ::size_t) -> ::ssize_t; + pub fn flistxattr(filedes: ::c_int, list: *mut c_char, + size: ::size_t) -> ::ssize_t; + pub fn removexattr(path: *const c_char, name: *const c_char) -> ::c_int; + pub fn lremovexattr(path: *const c_char, name: *const c_char) -> ::c_int; + pub fn fremovexattr(filedes: ::c_int, name: *const c_char) -> ::c_int; + pub fn signalfd(fd: ::c_int, + mask: *const ::sigset_t, + flags: ::c_int) -> ::c_int; + pub fn timerfd_create(clockid: ::c_int, flags: ::c_int) -> ::c_int; + pub fn timerfd_gettime(fd: ::c_int, + curr_value: *mut itimerspec) -> ::c_int; + pub fn timerfd_settime(fd: ::c_int, + flags: ::c_int, + new_value: *const itimerspec, + old_value: *mut itimerspec) -> ::c_int; + pub fn pwritev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off_t) -> ::ssize_t; + pub fn preadv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off_t) -> ::ssize_t; + pub fn quotactl(cmd: ::c_int, + special: *const ::c_char, + id: ::c_int, + data: *mut ::c_char) -> ::c_int; + pub fn mq_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::mqd_t; + pub fn mq_close(mqd: ::mqd_t) -> ::c_int; + pub fn mq_unlink(name: *const ::c_char) -> ::c_int; + pub fn mq_receive(mqd: ::mqd_t, + msg_ptr: *mut ::c_char, + msg_len: ::size_t, + msq_prio: *mut ::c_uint) -> ::ssize_t; + pub fn mq_send(mqd: ::mqd_t, + msg_ptr: *const ::c_char, + msg_len: ::size_t, + msq_prio: ::c_uint) -> ::c_int; + pub fn mq_getattr(mqd: ::mqd_t, attr: *mut ::mq_attr) -> ::c_int; + pub fn mq_setattr(mqd: ::mqd_t, + newattr: *const ::mq_attr, + oldattr: *mut ::mq_attr) -> ::c_int; + pub fn epoll_pwait(epfd: ::c_int, + events: *mut ::epoll_event, + maxevents: ::c_int, + timeout: ::c_int, + sigmask: *const ::sigset_t) -> ::c_int; + pub fn dup3(oldfd: ::c_int, newfd: ::c_int, flags: ::c_int) -> ::c_int; + pub fn mkostemp(template: *mut ::c_char, flags: ::c_int) -> ::c_int; + pub fn mkostemps(template: *mut ::c_char, + suffixlen: ::c_int, + flags: ::c_int) -> ::c_int; + pub fn sigtimedwait(set: *const sigset_t, + info: *mut siginfo_t, + timeout: *const ::timespec) -> ::c_int; + pub fn sigwaitinfo(set: *const sigset_t, + info: *mut siginfo_t) -> ::c_int; + pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; + pub fn getnameinfo(sa: *const ::sockaddr, + salen: ::socklen_t, + host: *mut ::c_char, + hostlen: ::socklen_t, + serv: *mut ::c_char, + sevlen: ::socklen_t, + flags: ::c_int) -> ::c_int; + pub fn pthread_setschedprio(native: ::pthread_t, + priority: ::c_int) -> ::c_int; + pub fn prlimit(pid: ::pid_t, resource: ::c_int, new_limit: *const ::rlimit, + old_limit: *mut ::rlimit) -> ::c_int; + pub fn prlimit64(pid: ::pid_t, + resource: ::c_int, + new_limit: *const ::rlimit64, + old_limit: *mut ::rlimit64) -> ::c_int; + pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int; + pub fn process_vm_readv(pid: ::pid_t, + local_iov: *const ::iovec, + liovcnt: ::c_ulong, + remote_iov: *const ::iovec, + riovcnt: ::c_ulong, + flags: ::c_ulong) -> isize; + pub fn process_vm_writev(pid: ::pid_t, + local_iov: *const ::iovec, + liovcnt: ::c_ulong, + remote_iov: *const ::iovec, + riovcnt: ::c_ulong, + flags: ::c_ulong) -> isize; + pub fn reboot(how_to: ::c_int) -> ::c_int; + pub fn setfsgid(gid: ::gid_t) -> ::c_int; + pub fn setfsuid(uid: ::uid_t) -> ::c_int; + + // Not available now on Android + pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t) -> ::c_int; + pub fn if_nameindex() -> *mut if_nameindex; + pub fn if_freenameindex(ptr: *mut if_nameindex); + pub fn sync_file_range(fd: ::c_int, offset: ::off64_t, + nbytes: ::off64_t, flags: ::c_uint) -> ::c_int; + pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; + pub fn freeifaddrs(ifa: *mut ::ifaddrs); + + pub fn mremap(addr: *mut ::c_void, + len: ::size_t, + new_len: ::size_t, + flags: ::c_int, + ...) -> *mut ::c_void; + + pub fn glob(pattern: *const c_char, + flags: ::c_int, + errfunc: Option ::c_int>, + pglob: *mut ::glob_t) -> ::c_int; + pub fn globfree(pglob: *mut ::glob_t); + + pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + pub fn shm_unlink(name: *const ::c_char) -> ::c_int; + + pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); + + pub fn telldir(dirp: *mut ::DIR) -> ::c_long; + pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; + + pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, + flags: ::c_int, addr: *mut ::sockaddr, + addrlen: *mut ::socklen_t) -> ::ssize_t; + pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; + pub fn futimes(fd: ::c_int, times: *const ::timeval) -> ::c_int; + pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; + + pub fn bind(socket: ::c_int, address: *const ::sockaddr, + address_len: ::socklen_t) -> ::c_int; + + pub fn writev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + pub fn readv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + + pub fn sendmsg(fd: ::c_int, + msg: *const ::msghdr, + flags: ::c_int) -> ::ssize_t; + pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) + -> ::ssize_t; + pub fn getdomainname(name: *mut ::c_char, len: ::size_t) -> ::c_int; + pub fn setdomainname(name: *const ::c_char, len: ::size_t) -> ::c_int; + pub fn vhangup() -> ::c_int; + pub fn sendmmsg(sockfd: ::c_int, msgvec: *mut mmsghdr, vlen: ::c_uint, + flags: ::c_int) -> ::c_int; + pub fn recvmmsg(sockfd: ::c_int, msgvec: *mut mmsghdr, vlen: ::c_uint, + flags: ::c_int, timeout: *mut ::timespec) -> ::c_int; + pub fn sync(); + pub fn syscall(num: ::c_long, ...) -> ::c_long; + pub fn sched_getaffinity(pid: ::pid_t, + cpusetsize: ::size_t, + cpuset: *mut cpu_set_t) -> ::c_int; + pub fn sched_setaffinity(pid: ::pid_t, + cpusetsize: ::size_t, + cpuset: *const cpu_set_t) -> ::c_int; + pub fn epoll_create(size: ::c_int) -> ::c_int; + pub fn epoll_create1(flags: ::c_int) -> ::c_int; + pub fn epoll_wait(epfd: ::c_int, + events: *mut ::epoll_event, + maxevents: ::c_int, + timeout: ::c_int) -> ::c_int; + pub fn epoll_ctl(epfd: ::c_int, + op: ::c_int, + fd: ::c_int, + event: *mut ::epoll_event) -> ::c_int; + pub fn pthread_getschedparam(native: ::pthread_t, + policy: *mut ::c_int, + param: *mut ::sched_param) -> ::c_int; + pub fn unshare(flags: ::c_int) -> ::c_int; + pub fn umount(target: *const ::c_char) -> ::c_int; + pub fn sched_get_priority_max(policy: ::c_int) -> ::c_int; + pub fn tee(fd_in: ::c_int, + fd_out: ::c_int, + len: ::size_t, + flags: ::c_uint) -> ::ssize_t; + pub fn settimeofday(tv: *const ::timeval, tz: *const ::timezone) -> ::c_int; + pub fn splice(fd_in: ::c_int, + off_in: *mut ::loff_t, + fd_out: ::c_int, + off_out: *mut ::loff_t, + len: ::size_t, + flags: ::c_uint) -> ::ssize_t; + pub fn eventfd(init: ::c_uint, flags: ::c_int) -> ::c_int; + pub fn sched_rr_get_interval(pid: ::pid_t, tp: *mut ::timespec) -> ::c_int; + pub fn sem_timedwait(sem: *mut sem_t, + abstime: *const ::timespec) -> ::c_int; + pub fn sched_setparam(pid: ::pid_t, param: *const ::sched_param) -> ::c_int; + pub fn setns(fd: ::c_int, nstype: ::c_int) -> ::c_int; + pub fn swapoff(puath: *const ::c_char) -> ::c_int; + pub fn vmsplice(fd: ::c_int, + iov: *const ::iovec, + nr_segs: ::size_t, + flags: ::c_uint) -> ::ssize_t; + pub fn mount(src: *const ::c_char, + target: *const ::c_char, + fstype: *const ::c_char, + flags: ::c_ulong, + data: *const ::c_void) -> ::c_int; + pub fn personality(persona: ::c_ulong) -> ::c_int; + pub fn prctl(option: ::c_int, ...) -> ::c_int; + pub fn sched_getparam(pid: ::pid_t, param: *mut ::sched_param) -> ::c_int; + pub fn ppoll(fds: *mut ::pollfd, + nfds: nfds_t, + timeout: *const ::timespec, + sigmask: *const sigset_t) -> ::c_int; + pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, + abstime: *const ::timespec) -> ::c_int; + pub fn clone(cb: extern fn(*mut ::c_void) -> ::c_int, + child_stack: *mut ::c_void, + flags: ::c_int, + arg: *mut ::c_void, ...) -> ::c_int; + pub fn sched_getscheduler(pid: ::pid_t) -> ::c_int; + pub fn clock_nanosleep(clk_id: ::clockid_t, + flags: ::c_int, + rqtp: *const ::timespec, + rmtp: *mut ::timespec) -> ::c_int; + pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, + guardsize: *mut ::size_t) -> ::c_int; + pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; + pub fn sched_get_priority_min(policy: ::c_int) -> ::c_int; + pub fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, + pshared: *mut ::c_int) -> ::c_int; + pub fn sysinfo(info: *mut ::sysinfo) -> ::c_int; + pub fn umount2(target: *const ::c_char, flags: ::c_int) -> ::c_int; + pub fn pthread_setschedparam(native: ::pthread_t, + policy: ::c_int, + param: *const ::sched_param) -> ::c_int; + pub fn swapon(path: *const ::c_char, swapflags: ::c_int) -> ::c_int; + pub fn sched_setscheduler(pid: ::pid_t, + policy: ::c_int, + param: *const ::sched_param) -> ::c_int; + pub fn sendfile(out_fd: ::c_int, + in_fd: ::c_int, + offset: *mut off_t, + count: ::size_t) -> ::ssize_t; + pub fn sigsuspend(mask: *const ::sigset_t) -> ::c_int; + pub fn getgrgid_r(uid: ::uid_t, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + pub fn sigaltstack(ss: *const stack_t, + oss: *mut stack_t) -> ::c_int; + pub fn sem_close(sem: *mut sem_t) -> ::c_int; + pub fn getdtablesize() -> ::c_int; + pub fn getgrnam_r(name: *const ::c_char, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + pub fn initgroups(user: *const ::c_char, group: ::gid_t) -> ::c_int; + pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, + oldset: *mut sigset_t) -> ::c_int; + pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; + pub fn getgrnam(name: *const ::c_char) -> *mut ::group; + pub fn pthread_cancel(thread: ::pthread_t) -> ::c_int; + pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; + pub fn sem_unlink(name: *const ::c_char) -> ::c_int; + pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; + pub fn getpwnam_r(name: *const ::c_char, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + pub fn getpwuid_r(uid: ::uid_t, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + pub fn sigwait(set: *const sigset_t, + sig: *mut ::c_int) -> ::c_int; + pub fn pthread_atfork(prepare: Option, + parent: Option, + child: Option) -> ::c_int; + pub fn getgrgid(gid: ::gid_t) -> *mut ::group; + pub fn getgrouplist(user: *const ::c_char, + group: ::gid_t, + groups: *mut ::gid_t, + ngroups: *mut ::c_int) -> ::c_int; + pub fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, + pshared: *mut ::c_int) -> ::c_int; + pub fn popen(command: *const c_char, + mode: *const c_char) -> *mut ::FILE; + pub fn faccessat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::c_int, flags: ::c_int) -> ::c_int; + pub fn pthread_create(native: *mut ::pthread_t, + attr: *const ::pthread_attr_t, + f: extern fn(*mut ::c_void) -> *mut ::c_void, + value: *mut ::c_void) -> ::c_int; + pub fn dl_iterate_phdr( + callback: Option ::c_int>, + data: *mut ::c_void + ) -> ::c_int; +} + +cfg_if! { + if #[cfg(target_arch = "aarch64")] { + mod aarch64; + pub use self::aarch64::*; + } else if #[cfg(any(target_arch = "powerpc64"))] { + mod powerpc64; + pub use self::powerpc64::*; + } else if #[cfg(any(target_arch = "x86_64"))] { + mod x86_64; + pub use self::x86_64::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/fuchsia/powerpc64.rs cargo-0.26.0/vendor/libc-0.2.40/src/fuchsia/powerpc64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/fuchsia/powerpc64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/fuchsia/powerpc64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,79 @@ +pub type c_char = u8; +pub type wchar_t = i32; +pub type __u64 = ::c_ulong; +pub type nlink_t = u64; +pub type blksize_t = ::c_long; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + __pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused: [::c_long; 3], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino64_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + __pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __reserved: [::c_long; 3], + } + + pub struct ipc_perm { + pub __ipc_perm_key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + pub __seq: ::c_int, + __unused1: ::c_long, + __unused2: ::c_long + } +} + +pub const SYS_pivot_root: ::c_long = 203; +pub const SYS_gettid: ::c_long = 207; +pub const SYS_perf_event_open: ::c_long = 319; +pub const SYS_memfd_create: ::c_long = 360; + +pub const MAP_32BIT: ::c_int = 0x0040; + +pub const SIGSTKSZ: ::size_t = 8192; +pub const MINSIGSTKSZ: ::size_t = 2048; + +#[doc(hidden)] +pub const AF_MAX: ::c_int = 42; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; + +// Syscall table +pub const SYS_renameat2: ::c_long = 357; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/fuchsia/x86_64.rs cargo-0.26.0/vendor/libc-0.2.40/src/fuchsia/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/fuchsia/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/fuchsia/x86_64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,447 @@ +pub type c_char = i8; +pub type wchar_t = i32; +pub type nlink_t = u64; +pub type blksize_t = ::c_long; +pub type __u64 = ::c_ulonglong; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + __pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused: [::c_long; 3], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino64_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + __pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __reserved: [::c_long; 3], + } + + pub struct mcontext_t { + __private: [u64; 32], + } + + pub struct ucontext_t { + pub uc_flags: ::c_ulong, + pub uc_link: *mut ucontext_t, + pub uc_stack: ::stack_t, + pub uc_mcontext: mcontext_t, + pub uc_sigmask: ::sigset_t, + __private: [u8; 512], + } + + pub struct ipc_perm { + pub __ipc_perm_key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + pub __seq: ::c_int, + __unused1: ::c_long, + __unused2: ::c_long + } +} + +// Syscall table + +pub const SYS_read: ::c_long = 0; +pub const SYS_write: ::c_long = 1; +pub const SYS_open: ::c_long = 2; +pub const SYS_close: ::c_long = 3; +pub const SYS_stat: ::c_long = 4; +pub const SYS_fstat: ::c_long = 5; +pub const SYS_lstat: ::c_long = 6; +pub const SYS_poll: ::c_long = 7; +pub const SYS_lseek: ::c_long = 8; +pub const SYS_mmap: ::c_long = 9; +pub const SYS_mprotect: ::c_long = 10; +pub const SYS_munmap: ::c_long = 11; +pub const SYS_brk: ::c_long = 12; +pub const SYS_rt_sigaction: ::c_long = 13; +pub const SYS_rt_sigprocmask: ::c_long = 14; +pub const SYS_rt_sigreturn: ::c_long = 15; +pub const SYS_ioctl: ::c_long = 16; +pub const SYS_pread64: ::c_long = 17; +pub const SYS_pwrite64: ::c_long = 18; +pub const SYS_readv: ::c_long = 19; +pub const SYS_writev: ::c_long = 20; +pub const SYS_access: ::c_long = 21; +pub const SYS_pipe: ::c_long = 22; +pub const SYS_select: ::c_long = 23; +pub const SYS_sched_yield: ::c_long = 24; +pub const SYS_mremap: ::c_long = 25; +pub const SYS_msync: ::c_long = 26; +pub const SYS_mincore: ::c_long = 27; +pub const SYS_madvise: ::c_long = 28; +pub const SYS_shmget: ::c_long = 29; +pub const SYS_shmat: ::c_long = 30; +pub const SYS_shmctl: ::c_long = 31; +pub const SYS_dup: ::c_long = 32; +pub const SYS_dup2: ::c_long = 33; +pub const SYS_pause: ::c_long = 34; +pub const SYS_nanosleep: ::c_long = 35; +pub const SYS_getitimer: ::c_long = 36; +pub const SYS_alarm: ::c_long = 37; +pub const SYS_setitimer: ::c_long = 38; +pub const SYS_getpid: ::c_long = 39; +pub const SYS_sendfile: ::c_long = 40; +pub const SYS_socket: ::c_long = 41; +pub const SYS_connect: ::c_long = 42; +pub const SYS_accept: ::c_long = 43; +pub const SYS_sendto: ::c_long = 44; +pub const SYS_recvfrom: ::c_long = 45; +pub const SYS_sendmsg: ::c_long = 46; +pub const SYS_recvmsg: ::c_long = 47; +pub const SYS_shutdown: ::c_long = 48; +pub const SYS_bind: ::c_long = 49; +pub const SYS_listen: ::c_long = 50; +pub const SYS_getsockname: ::c_long = 51; +pub const SYS_getpeername: ::c_long = 52; +pub const SYS_socketpair: ::c_long = 53; +pub const SYS_setsockopt: ::c_long = 54; +pub const SYS_getsockopt: ::c_long = 55; +pub const SYS_clone: ::c_long = 56; +pub const SYS_fork: ::c_long = 57; +pub const SYS_vfork: ::c_long = 58; +pub const SYS_execve: ::c_long = 59; +pub const SYS_exit: ::c_long = 60; +pub const SYS_wait4: ::c_long = 61; +pub const SYS_kill: ::c_long = 62; +pub const SYS_uname: ::c_long = 63; +pub const SYS_semget: ::c_long = 64; +pub const SYS_semop: ::c_long = 65; +pub const SYS_semctl: ::c_long = 66; +pub const SYS_shmdt: ::c_long = 67; +pub const SYS_msgget: ::c_long = 68; +pub const SYS_msgsnd: ::c_long = 69; +pub const SYS_msgrcv: ::c_long = 70; +pub const SYS_msgctl: ::c_long = 71; +pub const SYS_fcntl: ::c_long = 72; +pub const SYS_flock: ::c_long = 73; +pub const SYS_fsync: ::c_long = 74; +pub const SYS_fdatasync: ::c_long = 75; +pub const SYS_truncate: ::c_long = 76; +pub const SYS_ftruncate: ::c_long = 77; +pub const SYS_getdents: ::c_long = 78; +pub const SYS_getcwd: ::c_long = 79; +pub const SYS_chdir: ::c_long = 80; +pub const SYS_fchdir: ::c_long = 81; +pub const SYS_rename: ::c_long = 82; +pub const SYS_mkdir: ::c_long = 83; +pub const SYS_rmdir: ::c_long = 84; +pub const SYS_creat: ::c_long = 85; +pub const SYS_link: ::c_long = 86; +pub const SYS_unlink: ::c_long = 87; +pub const SYS_symlink: ::c_long = 88; +pub const SYS_readlink: ::c_long = 89; +pub const SYS_chmod: ::c_long = 90; +pub const SYS_fchmod: ::c_long = 91; +pub const SYS_chown: ::c_long = 92; +pub const SYS_fchown: ::c_long = 93; +pub const SYS_lchown: ::c_long = 94; +pub const SYS_umask: ::c_long = 95; +pub const SYS_gettimeofday: ::c_long = 96; +pub const SYS_getrlimit: ::c_long = 97; +pub const SYS_getrusage: ::c_long = 98; +pub const SYS_sysinfo: ::c_long = 99; +pub const SYS_times: ::c_long = 100; +pub const SYS_ptrace: ::c_long = 101; +pub const SYS_getuid: ::c_long = 102; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_getgid: ::c_long = 104; +pub const SYS_setuid: ::c_long = 105; +pub const SYS_setgid: ::c_long = 106; +pub const SYS_geteuid: ::c_long = 107; +pub const SYS_getegid: ::c_long = 108; +pub const SYS_setpgid: ::c_long = 109; +pub const SYS_getppid: ::c_long = 110; +pub const SYS_getpgrp: ::c_long = 111; +pub const SYS_setsid: ::c_long = 112; +pub const SYS_setreuid: ::c_long = 113; +pub const SYS_setregid: ::c_long = 114; +pub const SYS_getgroups: ::c_long = 115; +pub const SYS_setgroups: ::c_long = 116; +pub const SYS_setresuid: ::c_long = 117; +pub const SYS_getresuid: ::c_long = 118; +pub const SYS_setresgid: ::c_long = 119; +pub const SYS_getresgid: ::c_long = 120; +pub const SYS_getpgid: ::c_long = 121; +pub const SYS_setfsuid: ::c_long = 122; +pub const SYS_setfsgid: ::c_long = 123; +pub const SYS_getsid: ::c_long = 124; +pub const SYS_capget: ::c_long = 125; +pub const SYS_capset: ::c_long = 126; +pub const SYS_rt_sigpending: ::c_long = 127; +pub const SYS_rt_sigtimedwait: ::c_long = 128; +pub const SYS_rt_sigqueueinfo: ::c_long = 129; +pub const SYS_rt_sigsuspend: ::c_long = 130; +pub const SYS_sigaltstack: ::c_long = 131; +pub const SYS_utime: ::c_long = 132; +pub const SYS_mknod: ::c_long = 133; +pub const SYS_uselib: ::c_long = 134; +pub const SYS_personality: ::c_long = 135; +pub const SYS_ustat: ::c_long = 136; +pub const SYS_statfs: ::c_long = 137; +pub const SYS_fstatfs: ::c_long = 138; +pub const SYS_sysfs: ::c_long = 139; +pub const SYS_getpriority: ::c_long = 140; +pub const SYS_setpriority: ::c_long = 141; +pub const SYS_sched_setparam: ::c_long = 142; +pub const SYS_sched_getparam: ::c_long = 143; +pub const SYS_sched_setscheduler: ::c_long = 144; +pub const SYS_sched_getscheduler: ::c_long = 145; +pub const SYS_sched_get_priority_max: ::c_long = 146; +pub const SYS_sched_get_priority_min: ::c_long = 147; +pub const SYS_sched_rr_get_interval: ::c_long = 148; +pub const SYS_mlock: ::c_long = 149; +pub const SYS_munlock: ::c_long = 150; +pub const SYS_mlockall: ::c_long = 151; +pub const SYS_munlockall: ::c_long = 152; +pub const SYS_vhangup: ::c_long = 153; +pub const SYS_modify_ldt: ::c_long = 154; +pub const SYS_pivot_root: ::c_long = 155; +pub const SYS__sysctl: ::c_long = 156; +pub const SYS_prctl: ::c_long = 157; +pub const SYS_arch_prctl: ::c_long = 158; +pub const SYS_adjtimex: ::c_long = 159; +pub const SYS_setrlimit: ::c_long = 160; +pub const SYS_chroot: ::c_long = 161; +pub const SYS_sync: ::c_long = 162; +pub const SYS_acct: ::c_long = 163; +pub const SYS_settimeofday: ::c_long = 164; +pub const SYS_mount: ::c_long = 165; +pub const SYS_umount2: ::c_long = 166; +pub const SYS_swapon: ::c_long = 167; +pub const SYS_swapoff: ::c_long = 168; +pub const SYS_reboot: ::c_long = 169; +pub const SYS_sethostname: ::c_long = 170; +pub const SYS_setdomainname: ::c_long = 171; +pub const SYS_iopl: ::c_long = 172; +pub const SYS_ioperm: ::c_long = 173; +pub const SYS_create_module: ::c_long = 174; +pub const SYS_init_module: ::c_long = 175; +pub const SYS_delete_module: ::c_long = 176; +pub const SYS_get_kernel_syms: ::c_long = 177; +pub const SYS_query_module: ::c_long = 178; +pub const SYS_quotactl: ::c_long = 179; +pub const SYS_nfsservctl: ::c_long = 180; +pub const SYS_getpmsg: ::c_long = 181; +pub const SYS_putpmsg: ::c_long = 182; +pub const SYS_afs_syscall: ::c_long = 183; +pub const SYS_tuxcall: ::c_long = 184; +pub const SYS_security: ::c_long = 185; +pub const SYS_gettid: ::c_long = 186; +pub const SYS_readahead: ::c_long = 187; +pub const SYS_setxattr: ::c_long = 188; +pub const SYS_lsetxattr: ::c_long = 189; +pub const SYS_fsetxattr: ::c_long = 190; +pub const SYS_getxattr: ::c_long = 191; +pub const SYS_lgetxattr: ::c_long = 192; +pub const SYS_fgetxattr: ::c_long = 193; +pub const SYS_listxattr: ::c_long = 194; +pub const SYS_llistxattr: ::c_long = 195; +pub const SYS_flistxattr: ::c_long = 196; +pub const SYS_removexattr: ::c_long = 197; +pub const SYS_lremovexattr: ::c_long = 198; +pub const SYS_fremovexattr: ::c_long = 199; +pub const SYS_tkill: ::c_long = 200; +pub const SYS_time: ::c_long = 201; +pub const SYS_futex: ::c_long = 202; +pub const SYS_sched_setaffinity: ::c_long = 203; +pub const SYS_sched_getaffinity: ::c_long = 204; +pub const SYS_set_thread_area: ::c_long = 205; +pub const SYS_io_setup: ::c_long = 206; +pub const SYS_io_destroy: ::c_long = 207; +pub const SYS_io_getevents: ::c_long = 208; +pub const SYS_io_submit: ::c_long = 209; +pub const SYS_io_cancel: ::c_long = 210; +pub const SYS_get_thread_area: ::c_long = 211; +pub const SYS_lookup_dcookie: ::c_long = 212; +pub const SYS_epoll_create: ::c_long = 213; +pub const SYS_epoll_ctl_old: ::c_long = 214; +pub const SYS_epoll_wait_old: ::c_long = 215; +pub const SYS_remap_file_pages: ::c_long = 216; +pub const SYS_getdents64: ::c_long = 217; +pub const SYS_set_tid_address: ::c_long = 218; +pub const SYS_restart_syscall: ::c_long = 219; +pub const SYS_semtimedop: ::c_long = 220; +pub const SYS_fadvise64: ::c_long = 221; +pub const SYS_timer_create: ::c_long = 222; +pub const SYS_timer_settime: ::c_long = 223; +pub const SYS_timer_gettime: ::c_long = 224; +pub const SYS_timer_getoverrun: ::c_long = 225; +pub const SYS_timer_delete: ::c_long = 226; +pub const SYS_clock_settime: ::c_long = 227; +pub const SYS_clock_gettime: ::c_long = 228; +pub const SYS_clock_getres: ::c_long = 229; +pub const SYS_clock_nanosleep: ::c_long = 230; +pub const SYS_exit_group: ::c_long = 231; +pub const SYS_epoll_wait: ::c_long = 232; +pub const SYS_epoll_ctl: ::c_long = 233; +pub const SYS_tgkill: ::c_long = 234; +pub const SYS_utimes: ::c_long = 235; +pub const SYS_vserver: ::c_long = 236; +pub const SYS_mbind: ::c_long = 237; +pub const SYS_set_mempolicy: ::c_long = 238; +pub const SYS_get_mempolicy: ::c_long = 239; +pub const SYS_mq_open: ::c_long = 240; +pub const SYS_mq_unlink: ::c_long = 241; +pub const SYS_mq_timedsend: ::c_long = 242; +pub const SYS_mq_timedreceive: ::c_long = 243; +pub const SYS_mq_notify: ::c_long = 244; +pub const SYS_mq_getsetattr: ::c_long = 245; +pub const SYS_kexec_load: ::c_long = 246; +pub const SYS_waitid: ::c_long = 247; +pub const SYS_add_key: ::c_long = 248; +pub const SYS_request_key: ::c_long = 249; +pub const SYS_keyctl: ::c_long = 250; +pub const SYS_ioprio_set: ::c_long = 251; +pub const SYS_ioprio_get: ::c_long = 252; +pub const SYS_inotify_init: ::c_long = 253; +pub const SYS_inotify_add_watch: ::c_long = 254; +pub const SYS_inotify_rm_watch: ::c_long = 255; +pub const SYS_migrate_pages: ::c_long = 256; +pub const SYS_openat: ::c_long = 257; +pub const SYS_mkdirat: ::c_long = 258; +pub const SYS_mknodat: ::c_long = 259; +pub const SYS_fchownat: ::c_long = 260; +pub const SYS_futimesat: ::c_long = 261; +pub const SYS_newfstatat: ::c_long = 262; +pub const SYS_unlinkat: ::c_long = 263; +pub const SYS_renameat: ::c_long = 264; +pub const SYS_linkat: ::c_long = 265; +pub const SYS_symlinkat: ::c_long = 266; +pub const SYS_readlinkat: ::c_long = 267; +pub const SYS_fchmodat: ::c_long = 268; +pub const SYS_faccessat: ::c_long = 269; +pub const SYS_pselect6: ::c_long = 270; +pub const SYS_ppoll: ::c_long = 271; +pub const SYS_unshare: ::c_long = 272; +pub const SYS_set_robust_list: ::c_long = 273; +pub const SYS_get_robust_list: ::c_long = 274; +pub const SYS_splice: ::c_long = 275; +pub const SYS_tee: ::c_long = 276; +pub const SYS_sync_file_range: ::c_long = 277; +pub const SYS_vmsplice: ::c_long = 278; +pub const SYS_move_pages: ::c_long = 279; +pub const SYS_utimensat: ::c_long = 280; +pub const SYS_epoll_pwait: ::c_long = 281; +pub const SYS_signalfd: ::c_long = 282; +pub const SYS_timerfd_create: ::c_long = 283; +pub const SYS_eventfd: ::c_long = 284; +pub const SYS_fallocate: ::c_long = 285; +pub const SYS_timerfd_settime: ::c_long = 286; +pub const SYS_timerfd_gettime: ::c_long = 287; +pub const SYS_accept4: ::c_long = 288; +pub const SYS_signalfd4: ::c_long = 289; +pub const SYS_eventfd2: ::c_long = 290; +pub const SYS_epoll_create1: ::c_long = 291; +pub const SYS_dup3: ::c_long = 292; +pub const SYS_pipe2: ::c_long = 293; +pub const SYS_inotify_init1: ::c_long = 294; +pub const SYS_preadv: ::c_long = 295; +pub const SYS_pwritev: ::c_long = 296; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 297; +pub const SYS_perf_event_open: ::c_long = 298; +pub const SYS_recvmmsg: ::c_long = 299; +pub const SYS_fanotify_init: ::c_long = 300; +pub const SYS_fanotify_mark: ::c_long = 301; +pub const SYS_prlimit64: ::c_long = 302; +pub const SYS_name_to_handle_at: ::c_long = 303; +pub const SYS_open_by_handle_at: ::c_long = 304; +pub const SYS_clock_adjtime: ::c_long = 305; +pub const SYS_syncfs: ::c_long = 306; +pub const SYS_sendmmsg: ::c_long = 307; +pub const SYS_setns: ::c_long = 308; +pub const SYS_getcpu: ::c_long = 309; +pub const SYS_process_vm_readv: ::c_long = 310; +pub const SYS_process_vm_writev: ::c_long = 311; +pub const SYS_kcmp: ::c_long = 312; +pub const SYS_finit_module: ::c_long = 313; +pub const SYS_sched_setattr: ::c_long = 314; +pub const SYS_sched_getattr: ::c_long = 315; +pub const SYS_renameat2: ::c_long = 316; +pub const SYS_seccomp: ::c_long = 317; +pub const SYS_getrandom: ::c_long = 318; +pub const SYS_memfd_create: ::c_long = 319; +pub const SYS_kexec_file_load: ::c_long = 320; +pub const SYS_bpf: ::c_long = 321; +pub const SYS_execveat: ::c_long = 322; +pub const SYS_userfaultfd: ::c_long = 323; +pub const SYS_membarrier: ::c_long = 324; +pub const SYS_mlock2: ::c_long = 325; +pub const SYS_copy_file_range: ::c_long = 326; +pub const SYS_preadv2: ::c_long = 327; +pub const SYS_pwritev2: ::c_long = 328; +// FIXME syscalls 329-331 have been added in musl 1.16 +// See discussion https://github.com/rust-lang/libc/pull/699 + +// offsets in user_regs_structs, from sys/reg.h +pub const R15: ::c_int = 0; +pub const R14: ::c_int = 1; +pub const R13: ::c_int = 2; +pub const R12: ::c_int = 3; +pub const RBP: ::c_int = 4; +pub const RBX: ::c_int = 5; +pub const R11: ::c_int = 6; +pub const R10: ::c_int = 7; +pub const R9: ::c_int = 8; +pub const R8: ::c_int = 9; +pub const RAX: ::c_int = 10; +pub const RCX: ::c_int = 11; +pub const RDX: ::c_int = 12; +pub const RSI: ::c_int = 13; +pub const RDI: ::c_int = 14; +pub const ORIG_RAX: ::c_int = 15; +pub const RIP: ::c_int = 16; +pub const CS: ::c_int = 17; +pub const EFLAGS: ::c_int = 18; +pub const RSP: ::c_int = 19; +pub const SS: ::c_int = 20; +pub const FS_BASE: ::c_int = 21; +pub const GS_BASE: ::c_int = 22; +pub const DS: ::c_int = 23; +pub const ES: ::c_int = 24; +pub const FS: ::c_int = 25; +pub const GS: ::c_int = 26; + +pub const MAP_32BIT: ::c_int = 0x0040; + +pub const SIGSTKSZ: ::size_t = 8192; +pub const MINSIGSTKSZ: ::size_t = 2048; + +#[doc(hidden)] +pub const AF_MAX: ::c_int = 42; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/lib.rs cargo-0.26.0/vendor/libc-0.2.40/src/lib.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,307 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Crate docs + +#![allow(bad_style, overflowing_literals, improper_ctypes)] +#![crate_type = "rlib"] +#![crate_name = "libc"] +#![cfg_attr(cross_platform_docs, feature(no_core, lang_items))] +#![cfg_attr(cross_platform_docs, no_core)] +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://doc.rust-lang.org/favicon.ico")] + +#![cfg_attr(all(target_os = "linux", target_arch = "x86_64"), doc( + html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-linux-gnu" +))] +#![cfg_attr(all(target_os = "linux", target_arch = "x86"), doc( + html_root_url = "https://doc.rust-lang.org/libc/i686-unknown-linux-gnu" +))] +#![cfg_attr(all(target_os = "linux", target_arch = "arm"), doc( + html_root_url = "https://doc.rust-lang.org/libc/arm-unknown-linux-gnueabihf" +))] +#![cfg_attr(all(target_os = "linux", target_arch = "mips"), doc( + html_root_url = "https://doc.rust-lang.org/libc/mips-unknown-linux-gnu" +))] +#![cfg_attr(all(target_os = "linux", target_arch = "aarch64"), doc( + html_root_url = "https://doc.rust-lang.org/libc/aarch64-unknown-linux-gnu" +))] +#![cfg_attr(all(target_os = "linux", target_env = "musl"), doc( + html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-linux-musl" +))] +#![cfg_attr(all(target_os = "macos", target_arch = "x86_64"), doc( + html_root_url = "https://doc.rust-lang.org/libc/x86_64-apple-darwin" +))] +#![cfg_attr(all(target_os = "macos", target_arch = "x86"), doc( + html_root_url = "https://doc.rust-lang.org/libc/i686-apple-darwin" +))] +#![cfg_attr(all(windows, target_arch = "x86_64", target_env = "gnu"), doc( + html_root_url = "https://doc.rust-lang.org/libc/x86_64-pc-windows-gnu" +))] +#![cfg_attr(all(windows, target_arch = "x86", target_env = "gnu"), doc( + html_root_url = "https://doc.rust-lang.org/libc/i686-pc-windows-gnu" +))] +#![cfg_attr(all(windows, target_arch = "x86_64", target_env = "msvc"), doc( + html_root_url = "https://doc.rust-lang.org/libc/x86_64-pc-windows-msvc" +))] +#![cfg_attr(all(windows, target_arch = "x86", target_env = "msvc"), doc( + html_root_url = "https://doc.rust-lang.org/libc/i686-pc-windows-msvc" +))] +#![cfg_attr(target_os = "android", doc( + html_root_url = "https://doc.rust-lang.org/libc/arm-linux-androideabi" +))] +#![cfg_attr(target_os = "freebsd", doc( + html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-freebsd" +))] +#![cfg_attr(target_os = "openbsd", doc( + html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-openbsd" +))] +#![cfg_attr(target_os = "bitrig", doc( + html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-bitrig" +))] +#![cfg_attr(target_os = "netbsd", doc( + html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-netbsd" +))] +#![cfg_attr(target_os = "dragonfly", doc( + html_root_url = "https://doc.rust-lang.org/libc/x86_64-unknown-dragonfly" +))] +#![cfg_attr(target_os = "solaris", doc( + html_root_url = "https://doc.rust-lang.org/libc/x86_64-sun-solaris" +))] +#![cfg_attr(all(target_os = "emscripten", target_arch = "asmjs"), doc( + html_root_url = "https://doc.rust-lang.org/libc/asmjs-unknown-emscripten" +))] +#![cfg_attr(all(target_os = "emscripten", target_arch = "wasm32"), doc( + html_root_url = "https://doc.rust-lang.org/libc/wasm32-unknown-emscripten" +))] +#![cfg_attr(all(target_os = "linux", target_arch = "sparc64"), doc( + html_root_url = "https://doc.rust-lang.org/libc/sparc64-unknown-linux-gnu" +))] + +// Attributes needed when building as part of the standard library +#![cfg_attr(feature = "stdbuild", feature(no_std, staged_api, custom_attribute, cfg_target_vendor))] +#![cfg_attr(feature = "stdbuild", feature(link_cfg))] +#![cfg_attr(feature = "stdbuild", no_std)] +#![cfg_attr(feature = "stdbuild", staged_api)] +#![cfg_attr(feature = "stdbuild", allow(warnings))] +#![cfg_attr(feature = "stdbuild", unstable(feature = "libc", + reason = "use `libc` from crates.io", + issue = "27783"))] + +#![cfg_attr(not(feature = "use_std"), no_std)] + +#[cfg(all(not(cross_platform_docs), feature = "use_std"))] +extern crate std as core; + +#[macro_use] mod macros; +mod dox; + +cfg_if! { + if #[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))] { + // empty ... + } else { + + // Use repr(u8) as LLVM expects `void*` to be the same as `i8*` to help enable + // more optimization opportunities around it recognizing things like + // malloc/free. + #[repr(u8)] + pub enum c_void { + // Two dummy variants so the #[repr] attribute can be used. + #[doc(hidden)] + __variant1, + #[doc(hidden)] + __variant2, + } + + pub type int8_t = i8; + pub type int16_t = i16; + pub type int32_t = i32; + pub type int64_t = i64; + pub type uint8_t = u8; + pub type uint16_t = u16; + pub type uint32_t = u32; + pub type uint64_t = u64; + + pub type c_schar = i8; + pub type c_uchar = u8; + pub type c_short = i16; + pub type c_ushort = u16; + pub type c_int = i32; + pub type c_uint = u32; + pub type c_float = f32; + pub type c_double = f64; + pub type c_longlong = i64; + pub type c_ulonglong = u64; + pub type intmax_t = i64; + pub type uintmax_t = u64; + + pub type size_t = usize; + pub type ptrdiff_t = isize; + pub type intptr_t = isize; + pub type uintptr_t = usize; + pub type ssize_t = isize; + + pub enum FILE {} + pub enum fpos_t {} // TODO: fill this out with a struct + + pub const INT_MIN: c_int = -2147483648; + pub const INT_MAX: c_int = 2147483647; + + extern { + pub fn isalnum(c: c_int) -> c_int; + pub fn isalpha(c: c_int) -> c_int; + pub fn iscntrl(c: c_int) -> c_int; + pub fn isdigit(c: c_int) -> c_int; + pub fn isgraph(c: c_int) -> c_int; + pub fn islower(c: c_int) -> c_int; + pub fn isprint(c: c_int) -> c_int; + pub fn ispunct(c: c_int) -> c_int; + pub fn isspace(c: c_int) -> c_int; + pub fn isupper(c: c_int) -> c_int; + pub fn isxdigit(c: c_int) -> c_int; + pub fn tolower(c: c_int) -> c_int; + pub fn toupper(c: c_int) -> c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "fopen$UNIX2003")] + pub fn fopen(filename: *const c_char, + mode: *const c_char) -> *mut FILE; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "freopen$UNIX2003")] + pub fn freopen(filename: *const c_char, mode: *const c_char, + file: *mut FILE) -> *mut FILE; + pub fn fflush(file: *mut FILE) -> c_int; + pub fn fclose(file: *mut FILE) -> c_int; + pub fn remove(filename: *const c_char) -> c_int; + pub fn rename(oldname: *const c_char, newname: *const c_char) -> c_int; + pub fn tmpfile() -> *mut FILE; + pub fn setvbuf(stream: *mut FILE, + buffer: *mut c_char, + mode: c_int, + size: size_t) -> c_int; + pub fn setbuf(stream: *mut FILE, buf: *mut c_char); + pub fn getchar() -> c_int; + pub fn putchar(c: c_int) -> c_int; + pub fn fgetc(stream: *mut FILE) -> c_int; + pub fn fgets(buf: *mut c_char, n: c_int, stream: *mut FILE) -> *mut c_char; + pub fn fputc(c: c_int, stream: *mut FILE) -> c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "fputs$UNIX2003")] + pub fn fputs(s: *const c_char, stream: *mut FILE)-> c_int; + pub fn puts(s: *const c_char) -> c_int; + pub fn ungetc(c: c_int, stream: *mut FILE) -> c_int; + pub fn fread(ptr: *mut c_void, + size: size_t, + nobj: size_t, + stream: *mut FILE) + -> size_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "fwrite$UNIX2003")] + pub fn fwrite(ptr: *const c_void, + size: size_t, + nobj: size_t, + stream: *mut FILE) + -> size_t; + pub fn fseek(stream: *mut FILE, offset: c_long, whence: c_int) -> c_int; + pub fn ftell(stream: *mut FILE) -> c_long; + pub fn rewind(stream: *mut FILE); + #[cfg_attr(target_os = "netbsd", link_name = "__fgetpos50")] + pub fn fgetpos(stream: *mut FILE, ptr: *mut fpos_t) -> c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__fsetpos50")] + pub fn fsetpos(stream: *mut FILE, ptr: *const fpos_t) -> c_int; + pub fn feof(stream: *mut FILE) -> c_int; + pub fn ferror(stream: *mut FILE) -> c_int; + pub fn perror(s: *const c_char); + pub fn atoi(s: *const c_char) -> c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "strtod$UNIX2003")] + pub fn strtod(s: *const c_char, endp: *mut *mut c_char) -> c_double; + pub fn strtol(s: *const c_char, + endp: *mut *mut c_char, base: c_int) -> c_long; + pub fn strtoul(s: *const c_char, endp: *mut *mut c_char, + base: c_int) -> c_ulong; + pub fn calloc(nobj: size_t, size: size_t) -> *mut c_void; + pub fn malloc(size: size_t) -> *mut c_void; + pub fn realloc(p: *mut c_void, size: size_t) -> *mut c_void; + pub fn free(p: *mut c_void); + pub fn abort() -> !; + pub fn exit(status: c_int) -> !; + pub fn _exit(status: c_int) -> !; + pub fn atexit(cb: extern fn()) -> c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "system$UNIX2003")] + pub fn system(s: *const c_char) -> c_int; + pub fn getenv(s: *const c_char) -> *mut c_char; + + pub fn strcpy(dst: *mut c_char, src: *const c_char) -> *mut c_char; + pub fn strncpy(dst: *mut c_char, src: *const c_char, n: size_t) + -> *mut c_char; + pub fn strcat(s: *mut c_char, ct: *const c_char) -> *mut c_char; + pub fn strncat(s: *mut c_char, ct: *const c_char, n: size_t) -> *mut c_char; + pub fn strcmp(cs: *const c_char, ct: *const c_char) -> c_int; + pub fn strncmp(cs: *const c_char, ct: *const c_char, n: size_t) -> c_int; + pub fn strcoll(cs: *const c_char, ct: *const c_char) -> c_int; + pub fn strchr(cs: *const c_char, c: c_int) -> *mut c_char; + pub fn strrchr(cs: *const c_char, c: c_int) -> *mut c_char; + pub fn strspn(cs: *const c_char, ct: *const c_char) -> size_t; + pub fn strcspn(cs: *const c_char, ct: *const c_char) -> size_t; + pub fn strdup(cs: *const c_char) -> *mut c_char; + pub fn strpbrk(cs: *const c_char, ct: *const c_char) -> *mut c_char; + pub fn strstr(cs: *const c_char, ct: *const c_char) -> *mut c_char; + pub fn strlen(cs: *const c_char) -> size_t; + pub fn strnlen(cs: *const c_char, maxlen: size_t) -> size_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "strerror$UNIX2003")] + pub fn strerror(n: c_int) -> *mut c_char; + pub fn strtok(s: *mut c_char, t: *const c_char) -> *mut c_char; + pub fn strxfrm(s: *mut c_char, ct: *const c_char, n: size_t) -> size_t; + pub fn wcslen(buf: *const wchar_t) -> size_t; + pub fn wcstombs(dest: *mut c_char, src: *const wchar_t, n: size_t) -> ::size_t; + + pub fn memchr(cx: *const c_void, c: c_int, n: size_t) -> *mut c_void; + pub fn memcmp(cx: *const c_void, ct: *const c_void, n: size_t) -> c_int; + pub fn memcpy(dest: *mut c_void, src: *const c_void, n: size_t) -> *mut c_void; + pub fn memmove(dest: *mut c_void, src: *const c_void, n: size_t) -> *mut c_void; + pub fn memset(dest: *mut c_void, c: c_int, n: size_t) -> *mut c_void; + } + + // These are all inline functions on android, so they end up just being entirely + // missing on that platform. + #[cfg(not(target_os = "android"))] + extern { + pub fn abs(i: c_int) -> c_int; + pub fn atof(s: *const c_char) -> c_double; + pub fn labs(i: c_long) -> c_long; + pub fn rand() -> c_int; + pub fn srand(seed: c_uint); + } + } +} + +cfg_if! { + if #[cfg(windows)] { + mod windows; + pub use windows::*; + } else if #[cfg(target_os = "redox")] { + mod redox; + pub use redox::*; + } else if #[cfg(target_os = "cloudabi")] { + mod cloudabi; + pub use cloudabi::*; + } else if #[cfg(target_os = "fuchsia")] { + mod fuchsia; + pub use fuchsia::*; + } else if #[cfg(unix)] { + mod unix; + pub use unix::*; + } else { + // Unknown target_family + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/macros.rs cargo-0.26.0/vendor/libc-0.2.40/src/macros.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/macros.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/macros.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,71 @@ +/// A macro for defining #[cfg] if-else statements. +/// +/// This is similar to the `if/elif` C preprocessor macro by allowing definition +/// of a cascade of `#[cfg]` cases, emitting the implementation which matches +/// first. +/// +/// This allows you to conveniently provide a long list #[cfg]'d blocks of code +/// without having to rewrite each clause multiple times. +macro_rules! cfg_if { + ($( + if #[cfg($($meta:meta),*)] { $($it:item)* } + ) else * else { + $($it2:item)* + }) => { + __cfg_if_items! { + () ; + $( ( ($($meta),*) ($($it)*) ), )* + ( () ($($it2)*) ), + } + } +} + +macro_rules! __cfg_if_items { + (($($not:meta,)*) ; ) => {}; + (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => { + __cfg_if_apply! { cfg(all(not(any($($not),*)), $($m,)*)), $($it)* } + __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* } + } +} + +macro_rules! __cfg_if_apply { + ($m:meta, $($it:item)*) => { + $(#[$m] $it)* + } +} + +macro_rules! s { + ($($(#[$attr:meta])* pub struct $i:ident { $($field:tt)* })*) => ($( + __item! { + #[repr(C)] + $(#[$attr])* + pub struct $i { $($field)* } + } + impl ::dox::Copy for $i {} + impl ::dox::Clone for $i { + fn clone(&self) -> $i { *self } + } + )*) +} + +macro_rules! f { + ($(pub fn $i:ident($($arg:ident: $argty:ty),*) -> $ret:ty { + $($body:stmt);* + })*) => ($( + #[inline] + #[cfg(not(cross_platform_docs))] + pub unsafe extern fn $i($($arg: $argty),*) -> $ret { + $($body);* + } + + #[cfg(cross_platform_docs)] + #[allow(dead_code)] + pub unsafe extern fn $i($($arg: $argty),*) -> $ret { + loop {} + } + )*) +} + +macro_rules! __item { + ($i:item) => ($i) +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/redox/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/redox/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/redox/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/redox/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,104 @@ +pub type c_char = i8; +pub type c_long = i64; +pub type c_ulong = u64; + +pub type wchar_t = i16; + +pub type off_t = c_long; +pub type mode_t = u16; +pub type time_t = i64; +pub type pid_t = usize; +pub type gid_t = usize; +pub type uid_t = usize; + +pub type suseconds_t = i64; + +s! { + pub struct timeval { + pub tv_sec: time_t, + pub tv_usec: suseconds_t, + } + + pub struct timespec { + pub tv_sec: time_t, + pub tv_nsec: c_long, + } +} + +pub const STDIN_FILENO: ::c_int = 0; +pub const STDOUT_FILENO: ::c_int = 1; +pub const STDERR_FILENO: ::c_int = 2; + +pub const EXIT_FAILURE: ::c_int = 1; +pub const EXIT_SUCCESS: ::c_int = 0; + +pub const S_ISUID: ::c_int = 0x800; +pub const S_ISGID: ::c_int = 0x400; +pub const S_ISVTX: ::c_int = 0x200; + +pub const S_IFIFO: mode_t = 0x1000; +pub const S_IFCHR: mode_t = 0x2000; +pub const S_IFBLK: mode_t = 0x6000; +pub const S_IFDIR: mode_t = 0x4000; +pub const S_IFREG: mode_t = 0x8000; +pub const S_IFLNK: mode_t = 0xA000; +pub const S_IFSOCK: mode_t = 0xC000; +pub const S_IFMT: mode_t = 0xF000; +pub const S_IEXEC: mode_t = 0x40; +pub const S_IWRITE: mode_t = 0x80; +pub const S_IREAD: mode_t = 0x100; +pub const S_IRWXU: mode_t = 0x1C0; +pub const S_IXUSR: mode_t = 0x40; +pub const S_IWUSR: mode_t = 0x80; +pub const S_IRUSR: mode_t = 0x100; +pub const S_IRWXG: mode_t = 0x38; +pub const S_IXGRP: mode_t = 0x8; +pub const S_IWGRP: mode_t = 0x10; +pub const S_IRGRP: mode_t = 0x20; +pub const S_IRWXO: mode_t = 0x7; +pub const S_IXOTH: mode_t = 0x1; +pub const S_IWOTH: mode_t = 0x2; +pub const S_IROTH: mode_t = 0x4; + +pub const F_DUPFD: ::c_int = 0; +pub const F_GETFD: ::c_int = 1; +pub const F_SETFD: ::c_int = 2; +pub const F_GETFL: ::c_int = 3; +pub const F_SETFL: ::c_int = 4; + +pub const O_RDONLY: ::c_int = 0x0001_0000; +pub const O_WRONLY: ::c_int = 0x0002_0000; +pub const O_RDWR: ::c_int = 0x0003_0000; +pub const O_NONBLOCK: ::c_int = 0x0004_0000; +pub const O_APPEND: ::c_int = 0x0008_0000; +pub const O_SHLOCK: ::c_int = 0x0010_0000; +pub const O_EXLOCK: ::c_int = 0x0020_0000; +pub const O_ASYNC: ::c_int = 0x0040_0000; +pub const O_FSYNC: ::c_int = 0x0080_0000; +pub const O_CLOEXEC: ::c_int = 0x0100_0000; +pub const O_CREAT: ::c_int = 0x0200_0000; +pub const O_TRUNC: ::c_int = 0x0400_0000; +pub const O_EXCL: ::c_int = 0x0800_0000; +pub const O_DIRECTORY: ::c_int = 0x1000_0000; +pub const O_STAT: ::c_int = 0x2000_0000; +pub const O_SYMLINK: ::c_int = 0x4000_0000; +pub const O_NOFOLLOW: ::c_int = 0x8000_0000; +pub const O_ACCMODE: ::c_int = O_RDONLY | O_WRONLY | O_RDWR; + +extern { + pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; + pub fn read(fd: ::c_int, buf: *mut ::c_void, count: ::size_t) + -> ::ssize_t; + pub fn write(fd: ::c_int, buf: *const ::c_void, count: ::size_t) + -> ::ssize_t; + pub fn fcntl(fd: ::c_int, cmd: ::c_int, ...) -> ::c_int; + pub fn close(fd: ::c_int) -> ::c_int; +} + +#[link(name = "c")] +#[link(name = "m")] +extern {} + +pub use self::net::*; + +mod net; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/redox/net.rs cargo-0.26.0/vendor/libc-0.2.40/src/redox/net.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/redox/net.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/redox/net.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,110 @@ +pub type in_addr_t = u32; +pub type in_port_t = u16; + +pub type socklen_t = u32; +pub type sa_family_t = u16; + +s! { + pub struct in_addr { + pub s_addr: in_addr_t, + } + + pub struct in6_addr { + pub s6_addr: [u8; 16], + __align: [u32; 0], + } + + pub struct ip_mreq { + pub imr_multiaddr: in_addr, + pub imr_interface: in_addr, + } + + pub struct ipv6_mreq { + pub ipv6mr_multiaddr: in6_addr, + pub ipv6mr_interface: ::c_uint, + } + + pub struct linger { + pub l_onoff: ::c_int, + pub l_linger: ::c_int, + } + + pub struct sockaddr { + pub sa_family: sa_family_t, + pub sa_data: [::c_char; 14], + } + + pub struct sockaddr_in { + pub sin_family: sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + pub sin_zero: [u8; 8], + } + + pub struct sockaddr_in6 { + pub sin6_family: sa_family_t, + pub sin6_port: in_port_t, + pub sin6_flowinfo: u32, + pub sin6_addr: ::in6_addr, + pub sin6_scope_id: u32, + } + + pub struct sockaddr_storage { + pub ss_family: sa_family_t, + pub __ss_padding: [u8; 26], + } +} + +pub const AF_INET: ::c_int = 2; +pub const AF_INET6: ::c_int = 23; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; + +pub const IPPROTO_TCP: ::c_int = 6; +pub const IPPROTO_IP: ::c_int = 0; +pub const IPPROTO_IPV6: ::c_int = 41; + +pub const TCP_KEEPIDLE: ::c_int = 4; +pub const TCP_NODELAY: ::c_int = 8193; + +pub const IP_TTL: ::c_int = 8; +pub const IP_MULTICAST_LOOP: ::c_int = 9; +pub const IP_MULTICAST_TTL: ::c_int = 10; +pub const IP_ADD_MEMBERSHIP: ::c_int = 11; +pub const IP_DROP_MEMBERSHIP: ::c_int = 12; + +pub const IPV6_MULTICAST_LOOP: ::c_int = 19; +pub const IPV6_ADD_MEMBERSHIP: ::c_int = 20; +pub const IPV6_DROP_MEMBERSHIP: ::c_int = 21; +pub const IPV6_V6ONLY: ::c_int = 26; + +pub const SOL_SOCKET: ::c_int = 65535; + +pub const SO_REUSEADDR: ::c_int = 4; +pub const SO_BROADCAST: ::c_int = 6; +pub const SO_KEEPALIVE: ::c_int = 8; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_SNDTIMEO: ::c_int = 21; +pub const SO_LINGER: ::c_int = 128; +pub const SO_SNDBUF: ::c_int = 4097; +pub const SO_RCVBUF: ::c_int = 4098; +pub const SO_ERROR: ::c_int = 4105; + +extern { + pub fn socket(domain: ::c_int, ty: ::c_int, protocol: ::c_int) -> ::c_int; + pub fn bind(fd: ::c_int, addr: *const sockaddr, len: socklen_t) -> ::c_int; + pub fn connect(socket: ::c_int, address: *const sockaddr, + len: socklen_t) -> ::c_int; + pub fn listen(socket: ::c_int, backlog: ::c_int) -> ::c_int; + pub fn getsockname(socket: ::c_int, address: *mut sockaddr, + address_len: *mut socklen_t) -> ::c_int; + pub fn getsockopt(sockfd: ::c_int, + level: ::c_int, + optname: ::c_int, + optval: *mut ::c_void, + optlen: *mut ::socklen_t) -> ::c_int; + pub fn setsockopt(socket: ::c_int, level: ::c_int, name: ::c_int, + value: *const ::c_void, + option_len: socklen_t) -> ::c_int; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/apple/b32.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/apple/b32.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/apple/b32.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/apple/b32.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,60 @@ +//! 32-bit specific Apple (ios/darwin) definitions + +pub type c_long = i32; +pub type c_ulong = u32; +pub type boolean_t = ::c_int; + +s! { + pub struct pthread_attr_t { + __sig: c_long, + __opaque: [::c_char; 36] + } + + pub struct if_data { + pub ifi_type: ::c_uchar, + pub ifi_typelen: ::c_uchar, + pub ifi_physical: ::c_uchar, + pub ifi_addrlen: ::c_uchar, + pub ifi_hdrlen: ::c_uchar, + pub ifi_recvquota: ::c_uchar, + pub ifi_xmitquota: ::c_uchar, + pub ifi_unused1: ::c_uchar, + pub ifi_mtu: u32, + pub ifi_metric: u32, + pub ifi_baudrate: u32, + pub ifi_ipackets: u32, + pub ifi_ierrors: u32, + pub ifi_opackets: u32, + pub ifi_oerrors: u32, + pub ifi_collisions: u32, + pub ifi_ibytes: u32, + pub ifi_obytes: u32, + pub ifi_imcasts: u32, + pub ifi_omcasts: u32, + pub ifi_iqdrops: u32, + pub ifi_noproto: u32, + pub ifi_recvtiming: u32, + pub ifi_xmittiming: u32, + pub ifi_lastchange: ::timeval, + pub ifi_unused2: u32, + pub ifi_hwassist: u32, + pub ifi_reserved1: u32, + pub ifi_reserved2: u32, + } + + pub struct bpf_hdr { + pub bh_tstamp: ::timeval, + pub bh_caplen: ::uint32_t, + pub bh_datalen: ::uint32_t, + pub bh_hdrlen: ::c_ushort, + } +} + +pub const __PTHREAD_MUTEX_SIZE__: usize = 40; +pub const __PTHREAD_COND_SIZE__: usize = 24; +pub const __PTHREAD_CONDATTR_SIZE__: usize = 4; +pub const __PTHREAD_RWLOCK_SIZE__: usize = 124; +pub const __PTHREAD_RWLOCKATTR_SIZE__: usize = 12; + +pub const TIOCTIMESTAMP: ::c_ulong = 0x40087459; +pub const TIOCDCDTIMESTAMP: ::c_ulong = 0x40087458; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/apple/b64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/apple/b64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/apple/b64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/apple/b64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,67 @@ +//! 64-bit specific Apple (ios/darwin) definitions + +pub type c_long = i64; +pub type c_ulong = u64; +pub type boolean_t = ::c_uint; + +s! { + pub struct pthread_attr_t { + __sig: c_long, + __opaque: [::c_char; 56] + } + + pub struct timeval32 { + pub tv_sec: i32, + pub tv_usec: i32, + } + + pub struct if_data { + pub ifi_type: ::c_uchar, + pub ifi_typelen: ::c_uchar, + pub ifi_physical: ::c_uchar, + pub ifi_addrlen: ::c_uchar, + pub ifi_hdrlen: ::c_uchar, + pub ifi_recvquota: ::c_uchar, + pub ifi_xmitquota: ::c_uchar, + pub ifi_unused1: ::c_uchar, + pub ifi_mtu: u32, + pub ifi_metric: u32, + pub ifi_baudrate: u32, + pub ifi_ipackets: u32, + pub ifi_ierrors: u32, + pub ifi_opackets: u32, + pub ifi_oerrors: u32, + pub ifi_collisions: u32, + pub ifi_ibytes: u32, + pub ifi_obytes: u32, + pub ifi_imcasts: u32, + pub ifi_omcasts: u32, + pub ifi_iqdrops: u32, + pub ifi_noproto: u32, + pub ifi_recvtiming: u32, + pub ifi_xmittiming: u32, + pub ifi_lastchange: timeval32, + pub ifi_unused2: u32, + pub ifi_hwassist: u32, + pub ifi_reserved1: u32, + pub ifi_reserved2: u32, + } + + pub struct bpf_hdr { + pub bh_tstamp: ::timeval32, + pub bh_caplen: ::uint32_t, + pub bh_datalen: ::uint32_t, + pub bh_hdrlen: ::c_ushort, + } +} + +pub const __PTHREAD_MUTEX_SIZE__: usize = 56; +pub const __PTHREAD_COND_SIZE__: usize = 40; +pub const __PTHREAD_CONDATTR_SIZE__: usize = 8; +pub const __PTHREAD_RWLOCK_SIZE__: usize = 192; +pub const __PTHREAD_RWLOCKATTR_SIZE__: usize = 16; + +pub const TIOCTIMESTAMP: ::c_ulong = 0x40107459; +pub const TIOCDCDTIMESTAMP: ::c_ulong = 0x40107458; + +pub const FIONREAD: ::c_ulong = 0x4004667f; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/apple/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/apple/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/apple/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/apple/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2526 @@ +//! Apple (ios/darwin)-specific definitions +//! +//! This covers *-apple-* triples currently + +pub type c_char = i8; +pub type clock_t = c_ulong; +pub type time_t = c_long; +pub type suseconds_t = i32; +pub type dev_t = i32; +pub type ino_t = u64; +pub type mode_t = u16; +pub type nlink_t = u16; +pub type blksize_t = i32; +pub type rlim_t = u64; +pub type mach_timebase_info_data_t = mach_timebase_info; +pub type pthread_key_t = c_ulong; +pub type sigset_t = u32; +pub type clockid_t = ::c_uint; +pub type fsblkcnt_t = ::c_uint; +pub type fsfilcnt_t = ::c_uint; +pub type speed_t = ::c_ulong; +pub type tcflag_t = ::c_ulong; +pub type nl_item = ::c_int; +pub type id_t = ::c_uint; +pub type sem_t = ::c_int; +pub type idtype_t = ::c_uint; +pub type integer_t = ::c_int; +pub type cpu_type_t = integer_t; +pub type cpu_subtype_t = integer_t; +pub type vm_prot_t = ::c_int; +pub type posix_spawnattr_t = *mut ::c_void; +pub type posix_spawn_file_actions_t = *mut ::c_void; +pub type key_t = ::c_int; +pub type shmatt_t = ::c_ushort; + +pub enum timezone {} + +s! { + pub struct aiocb { + pub aio_fildes: ::c_int, + pub aio_offset: ::off_t, + pub aio_buf: *mut ::c_void, + pub aio_nbytes: ::size_t, + pub aio_reqprio: ::c_int, + pub aio_sigevent: sigevent, + pub aio_lio_opcode: ::c_int + } + + pub struct utmpx { + pub ut_user: [::c_char; _UTX_USERSIZE], + pub ut_id: [::c_char; _UTX_IDSIZE], + pub ut_line: [::c_char; _UTX_LINESIZE], + pub ut_pid: ::pid_t, + pub ut_type: ::c_short, + pub ut_tv: ::timeval, + pub ut_host: [::c_char; _UTX_HOSTSIZE], + ut_pad: [::uint32_t; 16], + } + + pub struct glob_t { + pub gl_pathc: ::size_t, + __unused1: ::c_int, + pub gl_offs: ::size_t, + __unused2: ::c_int, + pub gl_pathv: *mut *mut ::c_char, + + __unused3: *mut ::c_void, + + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + __unused6: *mut ::c_void, + __unused7: *mut ::c_void, + __unused8: *mut ::c_void, + } + + pub struct sockaddr_storage { + pub ss_len: u8, + pub ss_family: ::sa_family_t, + __ss_pad1: [u8; 6], + __ss_align: i64, + __ss_pad2: [u8; 112], + } + + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + pub ai_addrlen: ::socklen_t, + pub ai_canonname: *mut ::c_char, + pub ai_addr: *mut ::sockaddr, + pub ai_next: *mut addrinfo, + } + + pub struct mach_timebase_info { + pub numer: u32, + pub denom: u32, + } + + pub struct stat { + pub st_dev: dev_t, + pub st_mode: mode_t, + pub st_nlink: nlink_t, + pub st_ino: ino_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: dev_t, + pub st_atime: time_t, + pub st_atime_nsec: c_long, + pub st_mtime: time_t, + pub st_mtime_nsec: c_long, + pub st_ctime: time_t, + pub st_ctime_nsec: c_long, + pub st_birthtime: time_t, + pub st_birthtime_nsec: c_long, + pub st_size: ::off_t, + pub st_blocks: ::blkcnt_t, + pub st_blksize: blksize_t, + pub st_flags: ::uint32_t, + pub st_gen: ::uint32_t, + pub st_lspare: ::int32_t, + pub st_qspare: [::int64_t; 2], + } + + pub struct dirent { + pub d_ino: u64, + pub d_seekoff: u64, + pub d_reclen: u16, + pub d_namlen: u16, + pub d_type: u8, + pub d_name: [::c_char; 1024], + } + + pub struct pthread_mutex_t { + __sig: ::c_long, + __opaque: [u8; __PTHREAD_MUTEX_SIZE__], + } + + pub struct pthread_mutexattr_t { + __sig: ::c_long, + __opaque: [u8; 8], + } + + pub struct pthread_cond_t { + __sig: ::c_long, + __opaque: [u8; __PTHREAD_COND_SIZE__], + } + + pub struct pthread_condattr_t { + __sig: ::c_long, + __opaque: [u8; __PTHREAD_CONDATTR_SIZE__], + } + + pub struct pthread_rwlock_t { + __sig: ::c_long, + __opaque: [u8; __PTHREAD_RWLOCK_SIZE__], + } + + pub struct pthread_rwlockattr_t { + __sig: ::c_long, + __opaque: [u8; __PTHREAD_RWLOCKATTR_SIZE__], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_errno: ::c_int, + pub si_code: ::c_int, + pub si_pid: ::pid_t, + pub si_uid: ::uid_t, + pub si_status: ::c_int, + pub si_addr: *mut ::c_void, + _pad: [usize; 9], + } + + pub struct sigaction { + pub sa_sigaction: ::sighandler_t, + pub sa_mask: sigset_t, + pub sa_flags: ::c_int, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_size: ::size_t, + pub ss_flags: ::c_int, + } + + pub struct fstore_t { + pub fst_flags: ::c_uint, + pub fst_posmode: ::c_int, + pub fst_offset: ::off_t, + pub fst_length: ::off_t, + pub fst_bytesalloc: ::off_t, + } + + pub struct radvisory { + pub ra_offset: ::off_t, + pub ra_count: ::c_int, + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + } + + pub struct Dl_info { + pub dli_fname: *const ::c_char, + pub dli_fbase: *mut ::c_void, + pub dli_sname: *const ::c_char, + pub dli_saddr: *mut ::c_void, + } + + pub struct sockaddr_in { + pub sin_len: u8, + pub sin_family: ::sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + pub sin_zero: [::c_char; 8], + } + + pub struct statfs { + pub f_bsize: ::uint32_t, + pub f_iosize: ::int32_t, + pub f_blocks: ::uint64_t, + pub f_bfree: ::uint64_t, + pub f_bavail: ::uint64_t, + pub f_files: ::uint64_t, + pub f_ffree: ::uint64_t, + pub f_fsid: ::fsid_t, + pub f_owner: ::uid_t, + pub f_type: ::uint32_t, + pub f_flags: ::uint32_t, + pub f_fssubtype: ::uint32_t, + pub f_fstypename: [::c_char; 16], + pub f_mntonname: [::c_char; 1024], + pub f_mntfromname: [::c_char; 1024], + pub f_reserved: [::uint32_t; 8], + } + + // FIXME: this should have align 4 but it's got align 8 on 64-bit + pub struct kevent { + pub ident: ::uintptr_t, + pub filter: ::int16_t, + pub flags: ::uint16_t, + pub fflags: ::uint32_t, + pub data: ::intptr_t, + pub udata: *mut ::c_void, + } + + pub struct kevent64_s { + pub ident: ::uint64_t, + pub filter: ::int16_t, + pub flags: ::uint16_t, + pub fflags: ::uint32_t, + pub data: ::int64_t, + pub udata: ::uint64_t, + pub ext: [::uint64_t; 2], + } + + pub struct dqblk { + pub dqb_bhardlimit: ::uint64_t, + pub dqb_bsoftlimit: ::uint64_t, + pub dqb_curbytes: ::uint64_t, + pub dqb_ihardlimit: ::uint32_t, + pub dqb_isoftlimit: ::uint32_t, + pub dqb_curinodes: ::uint32_t, + pub dqb_btime: ::uint32_t, + pub dqb_itime: ::uint32_t, + pub dqb_id: ::uint32_t, + pub dqb_spare: [::uint32_t; 4], + } + + pub struct if_msghdr { + pub ifm_msglen: ::c_ushort, + pub ifm_version: ::c_uchar, + pub ifm_type: ::c_uchar, + pub ifm_addrs: ::c_int, + pub ifm_flags: ::c_int, + pub ifm_index: ::c_ushort, + pub ifm_data: if_data, + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_cc: [::cc_t; ::NCCS], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } + + pub struct flock { + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_pid: ::pid_t, + pub l_type: ::c_short, + pub l_whence: ::c_short, + } + + pub struct sf_hdtr { + pub headers: *mut ::iovec, + pub hdr_cnt: ::c_int, + pub trailers: *mut ::iovec, + pub trl_cnt: ::c_int, + } + + pub struct lconv { + pub decimal_point: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + pub grouping: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub currency_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub int_frac_digits: ::c_char, + pub frac_digits: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + pub n_sign_posn: ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_n_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + pub int_n_sign_posn: ::c_char, + } + + pub struct sigevent { + pub sigev_notify: ::c_int, + pub sigev_signo: ::c_int, + pub sigev_value: ::sigval, + __unused1: *mut ::c_void, //actually a function pointer + pub sigev_notify_attributes: *mut ::pthread_attr_t + } + + pub struct proc_taskinfo { + pub pti_virtual_size: u64, + pub pti_resident_size: u64, + pub pti_total_user: u64, + pub pti_total_system: u64, + pub pti_threads_user: u64, + pub pti_threads_system: u64, + pub pti_policy: i32, + pub pti_faults: i32, + pub pti_pageins: i32, + pub pti_cow_faults: i32, + pub pti_messages_sent: i32, + pub pti_messages_received: i32, + pub pti_syscalls_mach: i32, + pub pti_syscalls_unix: i32, + pub pti_csw: i32, + pub pti_threadnum: i32, + pub pti_numrunning: i32, + pub pti_priority: i32, + } + + pub struct proc_bsdinfo { + pub pbi_flags: u32, + pub pbi_status: u32, + pub pbi_xstatus: u32, + pub pbi_pid: u32, + pub pbi_ppid: u32, + pub pbi_uid: ::uid_t, + pub pbi_gid: ::gid_t, + pub pbi_ruid: ::uid_t, + pub pbi_rgid: ::gid_t, + pub pbi_svuid: ::uid_t, + pub pbi_svgid: ::gid_t, + pub rfu_1: u32, + pub pbi_comm: [::c_char; MAXCOMLEN], + pub pbi_name: [::c_char; 32], // MAXCOMLEN * 2, but macro isn't happy... + pub pbi_nfiles: u32, + pub pbi_pgid: u32, + pub pbi_pjobc: u32, + pub e_tdev: u32, + pub e_tpgid: u32, + pub pbi_nice: i32, + pub pbi_start_tvsec: u64, + pub pbi_start_tvusec: u64, + } + + pub struct proc_taskallinfo { + pub pbsd: proc_bsdinfo, + pub ptinfo: proc_taskinfo, + } + + pub struct proc_threadinfo { + pub pth_user_time: u64, + pub pth_system_time: u64, + pub pth_cpu_usage: i32, + pub pth_policy: i32, + pub pth_run_state: i32, + pub pth_flags: i32, + pub pth_sleep_time: i32, + pub pth_curpri: i32, + pub pth_priority: i32, + pub pth_maxpriority: i32, + pub pth_name: [::c_char; MAXTHREADNAMESIZE], + } + + pub struct xsw_usage { + pub xsu_total: u64, + pub xsu_avail: u64, + pub xsu_used: u64, + pub xsu_pagesize: u32, + pub xsu_encrypted: ::boolean_t, + } + + pub struct xucred { + pub cr_version: ::c_uint, + pub cr_uid: ::uid_t, + pub cr_ngroups: ::c_short, + pub cr_groups: [::gid_t;16] + } + + pub struct mach_header { + pub magic: u32, + pub cputype: cpu_type_t, + pub cpusubtype: cpu_subtype_t, + pub filetype: u32, + pub ncmds: u32, + pub sizeofcmds: u32, + pub flags: u32, + } + + pub struct mach_header_64 { + pub magic: u32, + pub cputype: cpu_type_t, + pub cpusubtype: cpu_subtype_t, + pub filetype: u32, + pub ncmds: u32, + pub sizeofcmds: u32, + pub flags: u32, + pub reserved: u32, + } + + pub struct segment_command { + pub cmd: u32, + pub cmdsize: u32, + pub segname: [::c_char; 16], + pub vmaddr: u32, + pub vmsize: u32, + pub fileoff: u32, + pub filesize: u32, + pub maxprot: vm_prot_t, + pub initprot: vm_prot_t, + pub nsects: u32, + pub flags: u32, + } + + pub struct segment_command_64 { + pub cmd: u32, + pub cmdsize: u32, + pub segname: [::c_char; 16], + pub vmaddr: u64, + pub vmsize: u64, + pub fileoff: u64, + pub filesize: u64, + pub maxprot: vm_prot_t, + pub initprot: vm_prot_t, + pub nsects: u32, + pub flags: u32, + } + + pub struct load_command { + pub cmd: u32, + pub cmdsize: u32, + } + + pub struct sockaddr_dl { + pub sdl_len: ::c_uchar, + pub sdl_family: ::c_uchar, + pub sdl_index: ::c_ushort, + pub sdl_type: ::c_uchar, + pub sdl_nlen: ::c_uchar, + pub sdl_alen: ::c_uchar, + pub sdl_slen: ::c_uchar, + pub sdl_data: [::c_char; 12], + } + + pub struct sockaddr_inarp { + pub sin_len: ::c_uchar, + pub sin_family: ::c_uchar, + pub sin_port: ::c_ushort, + pub sin_addr: ::in_addr, + pub sin_srcaddr: ::in_addr, + pub sin_tos: ::c_ushort, + pub sin_other: ::c_ushort, + } + + pub struct sockaddr_ctl { + pub sc_len: ::c_uchar, + pub sc_family: ::c_uchar, + pub ss_sysaddr: ::uint16_t, + pub sc_id: ::uint32_t, + pub sc_unit: ::uint32_t, + pub sc_reserved: [::uint32_t; 5], + } + + // sys/ipc.h: + + pub struct ipc_perm { + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + pub _seq: ::c_ushort, + pub _key: ::key_t, + } + + // FIXME: this should have align 4 but it's got align 8 on 64-bit + pub struct shmid_ds { + pub shm_perm: ipc_perm, + pub shm_segsz: ::size_t, + pub shm_lpid: ::pid_t, + pub shm_cpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + pub shm_atime: ::time_t, // FIXME: 64-bit wrong align => wrong offset + pub shm_dtime: ::time_t, // FIXME: 64-bit wrong align => wrong offset + pub shm_ctime: ::time_t, // FIXME: 64-bit wrong align => wrong offset + // FIXME: 64-bit wrong align => wrong offset: + pub shm_internal: *mut ::c_void, + + } +} + +pub const _UTX_USERSIZE: usize = 256; +pub const _UTX_LINESIZE: usize = 32; +pub const _UTX_IDSIZE: usize = 4; +pub const _UTX_HOSTSIZE: usize = 256; + +pub const EMPTY: ::c_short = 0; +pub const RUN_LVL: ::c_short = 1; +pub const BOOT_TIME: ::c_short = 2; +pub const OLD_TIME: ::c_short = 3; +pub const NEW_TIME: ::c_short = 4; +pub const INIT_PROCESS: ::c_short = 5; +pub const LOGIN_PROCESS: ::c_short = 6; +pub const USER_PROCESS: ::c_short = 7; +pub const DEAD_PROCESS: ::c_short = 8; +pub const ACCOUNTING: ::c_short = 9; +pub const SIGNATURE: ::c_short = 10; +pub const SHUTDOWN_TIME: ::c_short = 11; + +pub const LC_COLLATE_MASK: ::c_int = (1 << 0); +pub const LC_CTYPE_MASK: ::c_int = (1 << 1); +pub const LC_MESSAGES_MASK: ::c_int = (1 << 2); +pub const LC_MONETARY_MASK: ::c_int = (1 << 3); +pub const LC_NUMERIC_MASK: ::c_int = (1 << 4); +pub const LC_TIME_MASK: ::c_int = (1 << 5); +pub const LC_ALL_MASK: ::c_int = LC_COLLATE_MASK + | LC_CTYPE_MASK + | LC_MESSAGES_MASK + | LC_MONETARY_MASK + | LC_NUMERIC_MASK + | LC_TIME_MASK; + +pub const CODESET: ::nl_item = 0; +pub const D_T_FMT: ::nl_item = 1; +pub const D_FMT: ::nl_item = 2; +pub const T_FMT: ::nl_item = 3; +pub const T_FMT_AMPM: ::nl_item = 4; +pub const AM_STR: ::nl_item = 5; +pub const PM_STR: ::nl_item = 6; + +pub const DAY_1: ::nl_item = 7; +pub const DAY_2: ::nl_item = 8; +pub const DAY_3: ::nl_item = 9; +pub const DAY_4: ::nl_item = 10; +pub const DAY_5: ::nl_item = 11; +pub const DAY_6: ::nl_item = 12; +pub const DAY_7: ::nl_item = 13; + +pub const ABDAY_1: ::nl_item = 14; +pub const ABDAY_2: ::nl_item = 15; +pub const ABDAY_3: ::nl_item = 16; +pub const ABDAY_4: ::nl_item = 17; +pub const ABDAY_5: ::nl_item = 18; +pub const ABDAY_6: ::nl_item = 19; +pub const ABDAY_7: ::nl_item = 20; + +pub const MON_1: ::nl_item = 21; +pub const MON_2: ::nl_item = 22; +pub const MON_3: ::nl_item = 23; +pub const MON_4: ::nl_item = 24; +pub const MON_5: ::nl_item = 25; +pub const MON_6: ::nl_item = 26; +pub const MON_7: ::nl_item = 27; +pub const MON_8: ::nl_item = 28; +pub const MON_9: ::nl_item = 29; +pub const MON_10: ::nl_item = 30; +pub const MON_11: ::nl_item = 31; +pub const MON_12: ::nl_item = 32; + +pub const ABMON_1: ::nl_item = 33; +pub const ABMON_2: ::nl_item = 34; +pub const ABMON_3: ::nl_item = 35; +pub const ABMON_4: ::nl_item = 36; +pub const ABMON_5: ::nl_item = 37; +pub const ABMON_6: ::nl_item = 38; +pub const ABMON_7: ::nl_item = 39; +pub const ABMON_8: ::nl_item = 40; +pub const ABMON_9: ::nl_item = 41; +pub const ABMON_10: ::nl_item = 42; +pub const ABMON_11: ::nl_item = 43; +pub const ABMON_12: ::nl_item = 44; + +pub const CLOCK_REALTIME: ::clockid_t = 0; +pub const CLOCK_MONOTONIC: ::clockid_t = 6; +pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 12; +pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 16; + +pub const ERA: ::nl_item = 45; +pub const ERA_D_FMT: ::nl_item = 46; +pub const ERA_D_T_FMT: ::nl_item = 47; +pub const ERA_T_FMT: ::nl_item = 48; +pub const ALT_DIGITS: ::nl_item = 49; + +pub const RADIXCHAR: ::nl_item = 50; +pub const THOUSEP: ::nl_item = 51; + +pub const YESEXPR: ::nl_item = 52; +pub const NOEXPR: ::nl_item = 53; + +pub const YESSTR: ::nl_item = 54; +pub const NOSTR: ::nl_item = 55; + +pub const CRNCYSTR: ::nl_item = 56; + +pub const D_MD_ORDER: ::nl_item = 57; + +pub const EXIT_FAILURE: ::c_int = 1; +pub const EXIT_SUCCESS: ::c_int = 0; +pub const RAND_MAX: ::c_int = 2147483647; +pub const EOF: ::c_int = -1; +pub const SEEK_SET: ::c_int = 0; +pub const SEEK_CUR: ::c_int = 1; +pub const SEEK_END: ::c_int = 2; +pub const _IOFBF: ::c_int = 0; +pub const _IONBF: ::c_int = 2; +pub const _IOLBF: ::c_int = 1; +pub const BUFSIZ: ::c_uint = 1024; +pub const FOPEN_MAX: ::c_uint = 20; +pub const FILENAME_MAX: ::c_uint = 1024; +pub const L_tmpnam: ::c_uint = 1024; +pub const TMP_MAX: ::c_uint = 308915776; +pub const _PC_LINK_MAX: ::c_int = 1; +pub const _PC_MAX_CANON: ::c_int = 2; +pub const _PC_MAX_INPUT: ::c_int = 3; +pub const _PC_NAME_MAX: ::c_int = 4; +pub const _PC_PATH_MAX: ::c_int = 5; +pub const _PC_PIPE_BUF: ::c_int = 6; +pub const _PC_CHOWN_RESTRICTED: ::c_int = 7; +pub const _PC_NO_TRUNC: ::c_int = 8; +pub const _PC_VDISABLE: ::c_int = 9; +pub const O_DSYNC: ::c_int = 0x400000; +pub const O_NOCTTY: ::c_int = 0x20000; +pub const O_CLOEXEC: ::c_int = 0x1000000; +pub const O_DIRECTORY: ::c_int = 0x100000; +pub const S_IFIFO: mode_t = 4096; +pub const S_IFCHR: mode_t = 8192; +pub const S_IFBLK: mode_t = 24576; +pub const S_IFDIR: mode_t = 16384; +pub const S_IFREG: mode_t = 32768; +pub const S_IFLNK: mode_t = 40960; +pub const S_IFSOCK: mode_t = 49152; +pub const S_IFMT: mode_t = 61440; +pub const S_IEXEC: mode_t = 64; +pub const S_IWRITE: mode_t = 128; +pub const S_IREAD: mode_t = 256; +pub const S_IRWXU: mode_t = 448; +pub const S_IXUSR: mode_t = 64; +pub const S_IWUSR: mode_t = 128; +pub const S_IRUSR: mode_t = 256; +pub const S_IRWXG: mode_t = 56; +pub const S_IXGRP: mode_t = 8; +pub const S_IWGRP: mode_t = 16; +pub const S_IRGRP: mode_t = 32; +pub const S_IRWXO: mode_t = 7; +pub const S_IXOTH: mode_t = 1; +pub const S_IWOTH: mode_t = 2; +pub const S_IROTH: mode_t = 4; +pub const F_OK: ::c_int = 0; +pub const R_OK: ::c_int = 4; +pub const W_OK: ::c_int = 2; +pub const X_OK: ::c_int = 1; +pub const STDIN_FILENO: ::c_int = 0; +pub const STDOUT_FILENO: ::c_int = 1; +pub const STDERR_FILENO: ::c_int = 2; +pub const F_LOCK: ::c_int = 1; +pub const F_TEST: ::c_int = 3; +pub const F_TLOCK: ::c_int = 2; +pub const F_ULOCK: ::c_int = 0; +pub const F_GETLK: ::c_int = 7; +pub const F_SETLK: ::c_int = 8; +pub const F_SETLKW: ::c_int = 9; +pub const SIGHUP: ::c_int = 1; +pub const SIGINT: ::c_int = 2; +pub const SIGQUIT: ::c_int = 3; +pub const SIGILL: ::c_int = 4; +pub const SIGABRT: ::c_int = 6; +pub const SIGEMT: ::c_int = 7; +pub const SIGFPE: ::c_int = 8; +pub const SIGKILL: ::c_int = 9; +pub const SIGSEGV: ::c_int = 11; +pub const SIGPIPE: ::c_int = 13; +pub const SIGALRM: ::c_int = 14; +pub const SIGTERM: ::c_int = 15; + +pub const PROT_NONE: ::c_int = 0; +pub const PROT_READ: ::c_int = 1; +pub const PROT_WRITE: ::c_int = 2; +pub const PROT_EXEC: ::c_int = 4; + +pub const MAP_FILE: ::c_int = 0x0000; +pub const MAP_SHARED: ::c_int = 0x0001; +pub const MAP_PRIVATE: ::c_int = 0x0002; +pub const MAP_FIXED: ::c_int = 0x0010; +pub const MAP_ANON: ::c_int = 0x1000; + +pub const VM_FLAGS_FIXED: ::c_int = 0x0000; +pub const VM_FLAGS_ANYWHERE: ::c_int = 0x0001; +pub const VM_FLAGS_PURGABLE: ::c_int = 0x0002; +pub const VM_FLAGS_RANDOM_ADDR: ::c_int = 0x0008; +pub const VM_FLAGS_NO_CACHE: ::c_int = 0x0010; +pub const VM_FLAGS_RESILIENT_CODESIGN: ::c_int = 0x0020; +pub const VM_FLAGS_RESILIENT_MEDIA: ::c_int = 0x0040; +pub const VM_FLAGS_OVERWRITE: ::c_int = 0x4000; +pub const VM_FLAGS_SUPERPAGE_MASK: ::c_int = 0x70000; +pub const VM_FLAGS_RETURN_DATA_ADDR: ::c_int = 0x100000; +pub const VM_FLAGS_RETURN_4K_DATA_ADDR: ::c_int = 0x800000; +pub const VM_FLAGS_ALIAS_MASK: ::c_int = 0xFF000000; +pub const VM_FLAGS_USER_ALLOCATE: ::c_int = VM_FLAGS_FIXED | VM_FLAGS_ANYWHERE | + VM_FLAGS_PURGABLE | + VM_FLAGS_RANDOM_ADDR | + VM_FLAGS_NO_CACHE | + VM_FLAGS_OVERWRITE | + VM_FLAGS_SUPERPAGE_MASK | + VM_FLAGS_ALIAS_MASK; +pub const VM_FLAGS_USER_MAP: ::c_int = VM_FLAGS_USER_ALLOCATE | + VM_FLAGS_RETURN_4K_DATA_ADDR | + VM_FLAGS_RETURN_DATA_ADDR; +pub const VM_FLAGS_USER_REMAP: ::c_int = VM_FLAGS_FIXED | VM_FLAGS_ANYWHERE | + VM_FLAGS_RANDOM_ADDR | + VM_FLAGS_OVERWRITE | + VM_FLAGS_RETURN_DATA_ADDR | + VM_FLAGS_RESILIENT_CODESIGN; + +pub const VM_FLAGS_SUPERPAGE_SHIFT: ::c_int = 16; +pub const SUPERPAGE_NONE: ::c_int = 0; +pub const SUPERPAGE_SIZE_ANY: ::c_int = 1; +pub const VM_FLAGS_SUPERPAGE_NONE: ::c_int = SUPERPAGE_NONE << + VM_FLAGS_SUPERPAGE_SHIFT; +pub const VM_FLAGS_SUPERPAGE_SIZE_ANY: ::c_int = SUPERPAGE_SIZE_ANY << + VM_FLAGS_SUPERPAGE_SHIFT; +pub const SUPERPAGE_SIZE_2MB: ::c_int = 2; +pub const VM_FLAGS_SUPERPAGE_SIZE_2MB: ::c_int = SUPERPAGE_SIZE_2MB << + VM_FLAGS_SUPERPAGE_SHIFT; + +pub const VM_MEMORY_MALLOC: ::c_int = 1; +pub const VM_MEMORY_MALLOC_SMALL: ::c_int = 2; +pub const VM_MEMORY_MALLOC_LARGE: ::c_int = 3; +pub const VM_MEMORY_MALLOC_HUGE: ::c_int = 4; +pub const VM_MEMORY_SBRK: ::c_int = 5; +pub const VM_MEMORY_REALLOC: ::c_int = 6; +pub const VM_MEMORY_MALLOC_TINY: ::c_int = 7; +pub const VM_MEMORY_MALLOC_LARGE_REUSABLE: ::c_int = 8; +pub const VM_MEMORY_MALLOC_LARGE_REUSED: ::c_int = 9; +pub const VM_MEMORY_ANALYSIS_TOOL: ::c_int = 10; +pub const VM_MEMORY_MALLOC_NANO: ::c_int = 11; +pub const VM_MEMORY_MACH_MSG: ::c_int = 20; +pub const VM_MEMORY_IOKIT: ::c_int = 21; +pub const VM_MEMORY_STACK: ::c_int = 30; +pub const VM_MEMORY_GUARD: ::c_int = 31; +pub const VM_MEMORY_SHARED_PMAP: ::c_int = 32; +pub const VM_MEMORY_DYLIB: ::c_int = 33; +pub const VM_MEMORY_OBJC_DISPATCHERS: ::c_int = 34; +pub const VM_MEMORY_UNSHARED_PMAP: ::c_int = 35; +pub const VM_MEMORY_APPKIT: ::c_int = 40; +pub const VM_MEMORY_FOUNDATION: ::c_int = 41; +pub const VM_MEMORY_COREGRAPHICS: ::c_int = 42; +pub const VM_MEMORY_CORESERVICES: ::c_int = 43; +pub const VM_MEMORY_CARBON: ::c_int = VM_MEMORY_CORESERVICES; +pub const VM_MEMORY_JAVA: ::c_int = 44; +pub const VM_MEMORY_COREDATA: ::c_int = 45; +pub const VM_MEMORY_COREDATA_OBJECTIDS: ::c_int = 46; +pub const VM_MEMORY_ATS: ::c_int = 50; +pub const VM_MEMORY_LAYERKIT: ::c_int = 51; +pub const VM_MEMORY_CGIMAGE: ::c_int = 52; +pub const VM_MEMORY_TCMALLOC: ::c_int = 53; +pub const VM_MEMORY_COREGRAPHICS_DATA: ::c_int = 54; +pub const VM_MEMORY_COREGRAPHICS_SHARED: ::c_int = 55; +pub const VM_MEMORY_COREGRAPHICS_FRAMEBUFFERS: ::c_int = 56; +pub const VM_MEMORY_COREGRAPHICS_BACKINGSTORES: ::c_int = 57; +pub const VM_MEMORY_COREGRAPHICS_XALLOC: ::c_int = 58; +pub const VM_MEMORY_COREGRAPHICS_MISC: ::c_int = VM_MEMORY_COREGRAPHICS; +pub const VM_MEMORY_DYLD: ::c_int = 60; +pub const VM_MEMORY_DYLD_MALLOC: ::c_int = 61; +pub const VM_MEMORY_SQLITE: ::c_int = 62; +pub const VM_MEMORY_JAVASCRIPT_CORE: ::c_int = 63; +pub const VM_MEMORY_JAVASCRIPT_JIT_EXECUTABLE_ALLOCATOR: ::c_int = 64; +pub const VM_MEMORY_JAVASCRIPT_JIT_REGISTER_FILE: ::c_int = 65; +pub const VM_MEMORY_GLSL: ::c_int = 66; +pub const VM_MEMORY_OPENCL: ::c_int = 67; +pub const VM_MEMORY_COREIMAGE: ::c_int = 68; +pub const VM_MEMORY_WEBCORE_PURGEABLE_BUFFERS: ::c_int = 69; +pub const VM_MEMORY_IMAGEIO: ::c_int = 70; +pub const VM_MEMORY_COREPROFILE: ::c_int = 71; +pub const VM_MEMORY_ASSETSD: ::c_int = 72; +pub const VM_MEMORY_OS_ALLOC_ONCE: ::c_int = 73; +pub const VM_MEMORY_LIBDISPATCH: ::c_int = 74; +pub const VM_MEMORY_ACCELERATE: ::c_int = 75; +pub const VM_MEMORY_COREUI: ::c_int = 76; +pub const VM_MEMORY_COREUIFILE: ::c_int = 77; +pub const VM_MEMORY_GENEALOGY: ::c_int = 78; +pub const VM_MEMORY_RAWCAMERA: ::c_int = 79; +pub const VM_MEMORY_CORPSEINFO: ::c_int = 80; +pub const VM_MEMORY_ASL: ::c_int = 81; +pub const VM_MEMORY_SWIFT_RUNTIME: ::c_int = 82; +pub const VM_MEMORY_SWIFT_METADATA: ::c_int = 83; +pub const VM_MEMORY_DHMM: ::c_int = 84; +pub const VM_MEMORY_SCENEKIT: ::c_int = 86; +pub const VM_MEMORY_SKYWALK: ::c_int = 87; +pub const VM_MEMORY_APPLICATION_SPECIFIC_1: ::c_int = 240; +pub const VM_MEMORY_APPLICATION_SPECIFIC_16: ::c_int = 255; + +pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const MS_ASYNC: ::c_int = 0x0001; +pub const MS_INVALIDATE: ::c_int = 0x0002; +pub const MS_SYNC: ::c_int = 0x0010; + +pub const MS_KILLPAGES: ::c_int = 0x0004; +pub const MS_DEACTIVATE: ::c_int = 0x0008; + +pub const EPERM: ::c_int = 1; +pub const ENOENT: ::c_int = 2; +pub const ESRCH: ::c_int = 3; +pub const EINTR: ::c_int = 4; +pub const EIO: ::c_int = 5; +pub const ENXIO: ::c_int = 6; +pub const E2BIG: ::c_int = 7; +pub const ENOEXEC: ::c_int = 8; +pub const EBADF: ::c_int = 9; +pub const ECHILD: ::c_int = 10; +pub const EDEADLK: ::c_int = 11; +pub const ENOMEM: ::c_int = 12; +pub const EACCES: ::c_int = 13; +pub const EFAULT: ::c_int = 14; +pub const ENOTBLK: ::c_int = 15; +pub const EBUSY: ::c_int = 16; +pub const EEXIST: ::c_int = 17; +pub const EXDEV: ::c_int = 18; +pub const ENODEV: ::c_int = 19; +pub const ENOTDIR: ::c_int = 20; +pub const EISDIR: ::c_int = 21; +pub const EINVAL: ::c_int = 22; +pub const ENFILE: ::c_int = 23; +pub const EMFILE: ::c_int = 24; +pub const ENOTTY: ::c_int = 25; +pub const ETXTBSY: ::c_int = 26; +pub const EFBIG: ::c_int = 27; +pub const ENOSPC: ::c_int = 28; +pub const ESPIPE: ::c_int = 29; +pub const EROFS: ::c_int = 30; +pub const EMLINK: ::c_int = 31; +pub const EPIPE: ::c_int = 32; +pub const EDOM: ::c_int = 33; +pub const ERANGE: ::c_int = 34; +pub const EAGAIN: ::c_int = 35; +pub const EWOULDBLOCK: ::c_int = EAGAIN; +pub const EINPROGRESS: ::c_int = 36; +pub const EALREADY: ::c_int = 37; +pub const ENOTSOCK: ::c_int = 38; +pub const EDESTADDRREQ: ::c_int = 39; +pub const EMSGSIZE: ::c_int = 40; +pub const EPROTOTYPE: ::c_int = 41; +pub const ENOPROTOOPT: ::c_int = 42; +pub const EPROTONOSUPPORT: ::c_int = 43; +pub const ESOCKTNOSUPPORT: ::c_int = 44; +pub const ENOTSUP: ::c_int = 45; +pub const EPFNOSUPPORT: ::c_int = 46; +pub const EAFNOSUPPORT: ::c_int = 47; +pub const EADDRINUSE: ::c_int = 48; +pub const EADDRNOTAVAIL: ::c_int = 49; +pub const ENETDOWN: ::c_int = 50; +pub const ENETUNREACH: ::c_int = 51; +pub const ENETRESET: ::c_int = 52; +pub const ECONNABORTED: ::c_int = 53; +pub const ECONNRESET: ::c_int = 54; +pub const ENOBUFS: ::c_int = 55; +pub const EISCONN: ::c_int = 56; +pub const ENOTCONN: ::c_int = 57; +pub const ESHUTDOWN: ::c_int = 58; +pub const ETOOMANYREFS: ::c_int = 59; +pub const ETIMEDOUT: ::c_int = 60; +pub const ECONNREFUSED: ::c_int = 61; +pub const ELOOP: ::c_int = 62; +pub const ENAMETOOLONG: ::c_int = 63; +pub const EHOSTDOWN: ::c_int = 64; +pub const EHOSTUNREACH: ::c_int = 65; +pub const ENOTEMPTY: ::c_int = 66; +pub const EPROCLIM: ::c_int = 67; +pub const EUSERS: ::c_int = 68; +pub const EDQUOT: ::c_int = 69; +pub const ESTALE: ::c_int = 70; +pub const EREMOTE: ::c_int = 71; +pub const EBADRPC: ::c_int = 72; +pub const ERPCMISMATCH: ::c_int = 73; +pub const EPROGUNAVAIL: ::c_int = 74; +pub const EPROGMISMATCH: ::c_int = 75; +pub const EPROCUNAVAIL: ::c_int = 76; +pub const ENOLCK: ::c_int = 77; +pub const ENOSYS: ::c_int = 78; +pub const EFTYPE: ::c_int = 79; +pub const EAUTH: ::c_int = 80; +pub const ENEEDAUTH: ::c_int = 81; +pub const EPWROFF: ::c_int = 82; +pub const EDEVERR: ::c_int = 83; +pub const EOVERFLOW: ::c_int = 84; +pub const EBADEXEC: ::c_int = 85; +pub const EBADARCH: ::c_int = 86; +pub const ESHLIBVERS: ::c_int = 87; +pub const EBADMACHO: ::c_int = 88; +pub const ECANCELED: ::c_int = 89; +pub const EIDRM: ::c_int = 90; +pub const ENOMSG: ::c_int = 91; +pub const EILSEQ: ::c_int = 92; +pub const ENOATTR: ::c_int = 93; +pub const EBADMSG: ::c_int = 94; +pub const EMULTIHOP: ::c_int = 95; +pub const ENODATA: ::c_int = 96; +pub const ENOLINK: ::c_int = 97; +pub const ENOSR: ::c_int = 98; +pub const ENOSTR: ::c_int = 99; +pub const EPROTO: ::c_int = 100; +pub const ETIME: ::c_int = 101; +pub const EOPNOTSUPP: ::c_int = 102; +pub const ENOPOLICY: ::c_int = 103; +pub const ENOTRECOVERABLE: ::c_int = 104; +pub const EOWNERDEAD: ::c_int = 105; +pub const EQFULL: ::c_int = 106; +pub const ELAST: ::c_int = 106; + +pub const EAI_AGAIN: ::c_int = 2; +pub const EAI_BADFLAGS: ::c_int = 3; +pub const EAI_FAIL: ::c_int = 4; +pub const EAI_FAMILY: ::c_int = 5; +pub const EAI_MEMORY: ::c_int = 6; +pub const EAI_NODATA: ::c_int = 7; +pub const EAI_NONAME: ::c_int = 8; +pub const EAI_SERVICE: ::c_int = 9; +pub const EAI_SOCKTYPE: ::c_int = 10; +pub const EAI_SYSTEM: ::c_int = 11; +pub const EAI_OVERFLOW: ::c_int = 14; + +pub const F_DUPFD: ::c_int = 0; +pub const F_DUPFD_CLOEXEC: ::c_int = 67; +pub const F_GETFD: ::c_int = 1; +pub const F_SETFD: ::c_int = 2; +pub const F_GETFL: ::c_int = 3; +pub const F_SETFL: ::c_int = 4; +pub const F_PREALLOCATE: ::c_int = 42; +pub const F_RDADVISE: ::c_int = 44; +pub const F_RDAHEAD: ::c_int = 45; +pub const F_NOCACHE: ::c_int = 48; +pub const F_GETPATH: ::c_int = 50; +pub const F_FULLFSYNC: ::c_int = 51; +pub const F_FREEZE_FS: ::c_int = 53; +pub const F_THAW_FS: ::c_int = 54; +pub const F_GLOBAL_NOCACHE: ::c_int = 55; +pub const F_NODIRECT: ::c_int = 62; + +pub const F_ALLOCATECONTIG: ::c_uint = 0x02; +pub const F_ALLOCATEALL: ::c_uint = 0x04; + +pub const F_PEOFPOSMODE: ::c_int = 3; +pub const F_VOLPOSMODE: ::c_int = 4; + +pub const AT_FDCWD: ::c_int = -2; +pub const AT_EACCESS: ::c_int = 0x0010; +pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x0020; +pub const AT_SYMLINK_FOLLOW: ::c_int = 0x0040; +pub const AT_REMOVEDIR: ::c_int = 0x0080; + +pub const TIOCMODG: ::c_ulong = 0x40047403; +pub const TIOCMODS: ::c_ulong = 0x80047404; +pub const TIOCM_LE: ::c_int = 0x1; +pub const TIOCM_DTR: ::c_int = 0x2; +pub const TIOCM_RTS: ::c_int = 0x4; +pub const TIOCM_ST: ::c_int = 0x8; +pub const TIOCM_SR: ::c_int = 0x10; +pub const TIOCM_CTS: ::c_int = 0x20; +pub const TIOCM_CAR: ::c_int = 0x40; +pub const TIOCM_CD: ::c_int = 0x40; +pub const TIOCM_RNG: ::c_int = 0x80; +pub const TIOCM_RI: ::c_int = 0x80; +pub const TIOCM_DSR: ::c_int = 0x100; +pub const TIOCEXCL: ::c_int = 0x2000740d; +pub const TIOCNXCL: ::c_int = 0x2000740e; +pub const TIOCFLUSH: ::c_ulong = 0x80047410; +pub const TIOCGETD: ::c_ulong = 0x4004741a; +pub const TIOCSETD: ::c_ulong = 0x8004741b; +pub const TIOCIXON: ::c_uint = 0x20007481; +pub const TIOCIXOFF: ::c_uint = 0x20007480; +pub const TIOCSBRK: ::c_uint = 0x2000747b; +pub const TIOCCBRK: ::c_uint = 0x2000747a; +pub const TIOCSDTR: ::c_uint = 0x20007479; +pub const TIOCCDTR: ::c_uint = 0x20007478; +pub const TIOCGPGRP: ::c_ulong = 0x40047477; +pub const TIOCSPGRP: ::c_ulong = 0x80047476; +pub const TIOCOUTQ: ::c_ulong = 0x40047473; +pub const TIOCSTI: ::c_ulong = 0x80017472; +pub const TIOCNOTTY: ::c_uint = 0x20007471; +pub const TIOCPKT: ::c_ulong = 0x80047470; +pub const TIOCPKT_DATA: ::c_int = 0x0; +pub const TIOCPKT_FLUSHREAD: ::c_int = 0x1; +pub const TIOCPKT_FLUSHWRITE: ::c_int = 0x2; +pub const TIOCPKT_STOP: ::c_int = 0x4; +pub const TIOCPKT_START: ::c_int = 0x8; +pub const TIOCPKT_NOSTOP: ::c_int = 0x10; +pub const TIOCPKT_DOSTOP: ::c_int = 0x20; +pub const TIOCPKT_IOCTL: ::c_int = 0x40; +pub const TIOCSTOP: ::c_uint = 0x2000746f; +pub const TIOCSTART: ::c_uint = 0x2000746e; +pub const TIOCMSET: ::c_ulong = 0x8004746d; +pub const TIOCMBIS: ::c_ulong = 0x8004746c; +pub const TIOCMBIC: ::c_ulong = 0x8004746b; +pub const TIOCMGET: ::c_ulong = 0x4004746a; +pub const TIOCREMOTE: ::c_ulong = 0x80047469; +pub const TIOCGWINSZ: ::c_ulong = 0x40087468; +pub const TIOCSWINSZ: ::c_ulong = 0x80087467; +pub const TIOCUCNTL: ::c_ulong = 0x80047466; +pub const TIOCSTAT: ::c_uint = 0x20007465; +pub const TIOCSCONS: ::c_uint = 0x20007463; +pub const TIOCCONS: ::c_ulong = 0x80047462; +pub const TIOCSCTTY: ::c_uint = 0x20007461; +pub const TIOCEXT: ::c_ulong = 0x80047460; +pub const TIOCSIG: ::c_uint = 0x2000745f; +pub const TIOCDRAIN: ::c_uint = 0x2000745e; +pub const TIOCMSDTRWAIT: ::c_ulong = 0x8004745b; +pub const TIOCMGDTRWAIT: ::c_ulong = 0x4004745a; +pub const TIOCSDRAINWAIT: ::c_ulong = 0x80047457; +pub const TIOCGDRAINWAIT: ::c_ulong = 0x40047456; +pub const TIOCDSIMICROCODE: ::c_uint = 0x20007455; +pub const TIOCPTYGRANT: ::c_uint = 0x20007454; +pub const TIOCPTYGNAME: ::c_uint = 0x40807453; +pub const TIOCPTYUNLK: ::c_uint = 0x20007452; + +pub const B0: speed_t = 0; +pub const B50: speed_t = 50; +pub const B75: speed_t = 75; +pub const B110: speed_t = 110; +pub const B134: speed_t = 134; +pub const B150: speed_t = 150; +pub const B200: speed_t = 200; +pub const B300: speed_t = 300; +pub const B600: speed_t = 600; +pub const B1200: speed_t = 1200; +pub const B1800: speed_t = 1800; +pub const B2400: speed_t = 2400; +pub const B4800: speed_t = 4800; +pub const B9600: speed_t = 9600; +pub const B19200: speed_t = 19200; +pub const B38400: speed_t = 38400; +pub const B7200: speed_t = 7200; +pub const B14400: speed_t = 14400; +pub const B28800: speed_t = 28800; +pub const B57600: speed_t = 57600; +pub const B76800: speed_t = 76800; +pub const B115200: speed_t = 115200; +pub const B230400: speed_t = 230400; +pub const EXTA: speed_t = 19200; +pub const EXTB: speed_t = 38400; + +pub const SIGTRAP: ::c_int = 5; + +pub const GLOB_APPEND : ::c_int = 0x0001; +pub const GLOB_DOOFFS : ::c_int = 0x0002; +pub const GLOB_ERR : ::c_int = 0x0004; +pub const GLOB_MARK : ::c_int = 0x0008; +pub const GLOB_NOCHECK : ::c_int = 0x0010; +pub const GLOB_NOSORT : ::c_int = 0x0020; +pub const GLOB_NOESCAPE: ::c_int = 0x2000; + +pub const GLOB_NOSPACE : ::c_int = -1; +pub const GLOB_ABORTED : ::c_int = -2; +pub const GLOB_NOMATCH : ::c_int = -3; + +pub const POSIX_MADV_NORMAL: ::c_int = 0; +pub const POSIX_MADV_RANDOM: ::c_int = 1; +pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_MADV_WILLNEED: ::c_int = 3; +pub const POSIX_MADV_DONTNEED: ::c_int = 4; + +pub const _SC_IOV_MAX: ::c_int = 56; +pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 70; +pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 71; +pub const _SC_LOGIN_NAME_MAX: ::c_int = 73; +pub const _SC_MQ_PRIO_MAX: ::c_int = 75; +pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 82; +pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 83; +pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 85; +pub const _SC_THREAD_KEYS_MAX: ::c_int = 86; +pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 87; +pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 88; +pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 89; +pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 90; +pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 91; +pub const _SC_THREAD_STACK_MIN: ::c_int = 93; +pub const _SC_THREAD_THREADS_MAX: ::c_int = 94; +pub const _SC_THREADS: ::c_int = 96; +pub const _SC_TTY_NAME_MAX: ::c_int = 101; +pub const _SC_ATEXIT_MAX: ::c_int = 107; +pub const _SC_XOPEN_CRYPT: ::c_int = 108; +pub const _SC_XOPEN_ENH_I18N: ::c_int = 109; +pub const _SC_XOPEN_LEGACY: ::c_int = 110; +pub const _SC_XOPEN_REALTIME: ::c_int = 111; +pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 112; +pub const _SC_XOPEN_SHM: ::c_int = 113; +pub const _SC_XOPEN_UNIX: ::c_int = 115; +pub const _SC_XOPEN_VERSION: ::c_int = 116; +pub const _SC_XOPEN_XCU_VERSION: ::c_int = 121; + +pub const PTHREAD_PROCESS_PRIVATE: ::c_int = 2; +pub const PTHREAD_PROCESS_SHARED: ::c_int = 1; +pub const PTHREAD_CREATE_JOINABLE: ::c_int = 1; +pub const PTHREAD_CREATE_DETACHED: ::c_int = 2; +pub const PTHREAD_STACK_MIN: ::size_t = 8192; + +pub const RLIMIT_CPU: ::c_int = 0; +pub const RLIMIT_FSIZE: ::c_int = 1; +pub const RLIMIT_DATA: ::c_int = 2; +pub const RLIMIT_STACK: ::c_int = 3; +pub const RLIMIT_CORE: ::c_int = 4; +pub const RLIMIT_AS: ::c_int = 5; +pub const RLIMIT_RSS: ::c_int = RLIMIT_AS; +pub const RLIMIT_MEMLOCK: ::c_int = 6; +pub const RLIMIT_NPROC: ::c_int = 7; +pub const RLIMIT_NOFILE: ::c_int = 8; +pub const RLIM_NLIMITS: ::c_int = 9; +pub const _RLIMIT_POSIX_FLAG: ::c_int = 0x1000; + +pub const RLIM_INFINITY: rlim_t = 0x7fff_ffff_ffff_ffff; + +pub const RUSAGE_SELF: ::c_int = 0; +pub const RUSAGE_CHILDREN: ::c_int = -1; + +pub const MADV_NORMAL: ::c_int = 0; +pub const MADV_RANDOM: ::c_int = 1; +pub const MADV_SEQUENTIAL: ::c_int = 2; +pub const MADV_WILLNEED: ::c_int = 3; +pub const MADV_DONTNEED: ::c_int = 4; +pub const MADV_FREE: ::c_int = 5; +pub const MADV_ZERO_WIRED_PAGES: ::c_int = 6; +pub const MADV_FREE_REUSABLE: ::c_int = 7; +pub const MADV_FREE_REUSE: ::c_int = 8; +pub const MADV_CAN_REUSE: ::c_int = 9; + +pub const MINCORE_INCORE: ::c_int = 0x1; +pub const MINCORE_REFERENCED: ::c_int = 0x2; +pub const MINCORE_MODIFIED: ::c_int = 0x4; +pub const MINCORE_REFERENCED_OTHER: ::c_int = 0x8; +pub const MINCORE_MODIFIED_OTHER: ::c_int = 0x10; + +// +// sys/netinet/in.h +// Protocols (RFC 1700) +// NOTE: These are in addition to the constants defined in src/unix/mod.rs + +// IPPROTO_IP defined in src/unix/mod.rs +/// IP6 hop-by-hop options +pub const IPPROTO_HOPOPTS: ::c_int = 0; +// IPPROTO_ICMP defined in src/unix/mod.rs +/// group mgmt protocol +pub const IPPROTO_IGMP: ::c_int = 2; +/// gateway2 (deprecated) +pub const IPPROTO_GGP: ::c_int = 3; +/// for compatibility +pub const IPPROTO_IPIP: ::c_int = 4; +// IPPROTO_TCP defined in src/unix/mod.rs +/// Stream protocol II. +pub const IPPROTO_ST: ::c_int = 7; +/// exterior gateway protocol +pub const IPPROTO_EGP: ::c_int = 8; +/// private interior gateway +pub const IPPROTO_PIGP: ::c_int = 9; +/// BBN RCC Monitoring +pub const IPPROTO_RCCMON: ::c_int = 10; +/// network voice protocol +pub const IPPROTO_NVPII: ::c_int = 11; +/// pup +pub const IPPROTO_PUP: ::c_int = 12; +/// Argus +pub const IPPROTO_ARGUS: ::c_int = 13; +/// EMCON +pub const IPPROTO_EMCON: ::c_int = 14; +/// Cross Net Debugger +pub const IPPROTO_XNET: ::c_int = 15; +/// Chaos +pub const IPPROTO_CHAOS: ::c_int = 16; +// IPPROTO_UDP defined in src/unix/mod.rs +/// Multiplexing +pub const IPPROTO_MUX: ::c_int = 18; +/// DCN Measurement Subsystems +pub const IPPROTO_MEAS: ::c_int = 19; +/// Host Monitoring +pub const IPPROTO_HMP: ::c_int = 20; +/// Packet Radio Measurement +pub const IPPROTO_PRM: ::c_int = 21; +/// xns idp +pub const IPPROTO_IDP: ::c_int = 22; +/// Trunk-1 +pub const IPPROTO_TRUNK1: ::c_int = 23; +/// Trunk-2 +pub const IPPROTO_TRUNK2: ::c_int = 24; +/// Leaf-1 +pub const IPPROTO_LEAF1: ::c_int = 25; +/// Leaf-2 +pub const IPPROTO_LEAF2: ::c_int = 26; +/// Reliable Data +pub const IPPROTO_RDP: ::c_int = 27; +/// Reliable Transaction +pub const IPPROTO_IRTP: ::c_int = 28; +/// tp-4 w/ class negotiation +pub const IPPROTO_TP: ::c_int = 29; +/// Bulk Data Transfer +pub const IPPROTO_BLT: ::c_int = 30; +/// Network Services +pub const IPPROTO_NSP: ::c_int = 31; +/// Merit Internodal +pub const IPPROTO_INP: ::c_int = 32; +/// Sequential Exchange +pub const IPPROTO_SEP: ::c_int = 33; +/// Third Party Connect +pub const IPPROTO_3PC: ::c_int = 34; +/// InterDomain Policy Routing +pub const IPPROTO_IDPR: ::c_int = 35; +/// XTP +pub const IPPROTO_XTP: ::c_int = 36; +/// Datagram Delivery +pub const IPPROTO_DDP: ::c_int = 37; +/// Control Message Transport +pub const IPPROTO_CMTP: ::c_int = 38; +/// TP++ Transport +pub const IPPROTO_TPXX: ::c_int = 39; +/// IL transport protocol +pub const IPPROTO_IL: ::c_int = 40; +// IPPROTO_IPV6 defined in src/unix/mod.rs +/// Source Demand Routing +pub const IPPROTO_SDRP: ::c_int = 42; +/// IP6 routing header +pub const IPPROTO_ROUTING: ::c_int = 43; +/// IP6 fragmentation header +pub const IPPROTO_FRAGMENT: ::c_int = 44; +/// InterDomain Routing +pub const IPPROTO_IDRP: ::c_int = 45; +/// resource reservation +pub const IPPROTO_RSVP: ::c_int = 46; +/// General Routing Encap. +pub const IPPROTO_GRE: ::c_int = 47; +/// Mobile Host Routing +pub const IPPROTO_MHRP: ::c_int = 48; +/// BHA +pub const IPPROTO_BHA: ::c_int = 49; +/// IP6 Encap Sec. Payload +pub const IPPROTO_ESP: ::c_int = 50; +/// IP6 Auth Header +pub const IPPROTO_AH: ::c_int = 51; +/// Integ. Net Layer Security +pub const IPPROTO_INLSP: ::c_int = 52; +/// IP with encryption +pub const IPPROTO_SWIPE: ::c_int = 53; +/// Next Hop Resolution +pub const IPPROTO_NHRP: ::c_int = 54; +/* 55-57: Unassigned */ +// IPPROTO_ICMPV6 defined in src/unix/mod.rs +/// IP6 no next header +pub const IPPROTO_NONE: ::c_int = 59; +/// IP6 destination option +pub const IPPROTO_DSTOPTS: ::c_int = 60; +/// any host internal protocol +pub const IPPROTO_AHIP: ::c_int = 61; +/// CFTP +pub const IPPROTO_CFTP: ::c_int = 62; +/// "hello" routing protocol +pub const IPPROTO_HELLO: ::c_int = 63; +/// SATNET/Backroom EXPAK +pub const IPPROTO_SATEXPAK: ::c_int = 64; +/// Kryptolan +pub const IPPROTO_KRYPTOLAN: ::c_int = 65; +/// Remote Virtual Disk +pub const IPPROTO_RVD: ::c_int = 66; +/// Pluribus Packet Core +pub const IPPROTO_IPPC: ::c_int = 67; +/// Any distributed FS +pub const IPPROTO_ADFS: ::c_int = 68; +/// Satnet Monitoring +pub const IPPROTO_SATMON: ::c_int = 69; +/// VISA Protocol +pub const IPPROTO_VISA: ::c_int = 70; +/// Packet Core Utility +pub const IPPROTO_IPCV: ::c_int = 71; +/// Comp. Prot. Net. Executive +pub const IPPROTO_CPNX: ::c_int = 72; +/// Comp. Prot. HeartBeat +pub const IPPROTO_CPHB: ::c_int = 73; +/// Wang Span Network +pub const IPPROTO_WSN: ::c_int = 74; +/// Packet Video Protocol +pub const IPPROTO_PVP: ::c_int = 75; +/// BackRoom SATNET Monitoring +pub const IPPROTO_BRSATMON: ::c_int = 76; +/// Sun net disk proto (temp.) +pub const IPPROTO_ND: ::c_int = 77; +/// WIDEBAND Monitoring +pub const IPPROTO_WBMON: ::c_int = 78; +/// WIDEBAND EXPAK +pub const IPPROTO_WBEXPAK: ::c_int = 79; +/// ISO cnlp +pub const IPPROTO_EON: ::c_int = 80; +/// VMTP +pub const IPPROTO_VMTP: ::c_int = 81; +/// Secure VMTP +pub const IPPROTO_SVMTP: ::c_int = 82; +/// Banyon VINES +pub const IPPROTO_VINES: ::c_int = 83; +/// TTP +pub const IPPROTO_TTP: ::c_int = 84; +/// NSFNET-IGP +pub const IPPROTO_IGP: ::c_int = 85; +/// dissimilar gateway prot. +pub const IPPROTO_DGP: ::c_int = 86; +/// TCF +pub const IPPROTO_TCF: ::c_int = 87; +/// Cisco/GXS IGRP +pub const IPPROTO_IGRP: ::c_int = 88; +/// OSPFIGP +pub const IPPROTO_OSPFIGP: ::c_int = 89; +/// Strite RPC protocol +pub const IPPROTO_SRPC: ::c_int = 90; +/// Locus Address Resoloution +pub const IPPROTO_LARP: ::c_int = 91; +/// Multicast Transport +pub const IPPROTO_MTP: ::c_int = 92; +/// AX.25 Frames +pub const IPPROTO_AX25: ::c_int = 93; +/// IP encapsulated in IP +pub const IPPROTO_IPEIP: ::c_int = 94; +/// Mobile Int.ing control +pub const IPPROTO_MICP: ::c_int = 95; +/// Semaphore Comm. security +pub const IPPROTO_SCCSP: ::c_int = 96; +/// Ethernet IP encapsulation +pub const IPPROTO_ETHERIP: ::c_int = 97; +/// encapsulation header +pub const IPPROTO_ENCAP: ::c_int = 98; +/// any private encr. scheme +pub const IPPROTO_APES: ::c_int = 99; +/// GMTP +pub const IPPROTO_GMTP: ::c_int = 100; + +/* 101-254: Partly Unassigned */ +/// Protocol Independent Mcast +pub const IPPROTO_PIM: ::c_int = 103; +/// payload compression (IPComp) +pub const IPPROTO_IPCOMP: ::c_int = 108; +/// PGM +pub const IPPROTO_PGM: ::c_int = 113; +/// SCTP +pub const IPPROTO_SCTP: ::c_int = 132; + +/* 255: Reserved */ +/* BSD Private, local use, namespace incursion */ +/// divert pseudo-protocol +pub const IPPROTO_DIVERT: ::c_int = 254; +/// raw IP packet +pub const IPPROTO_RAW: ::c_int = 255; +pub const IPPROTO_MAX: ::c_int = 256; +/// last return value of *_input(), meaning "all job for this pkt is done". +pub const IPPROTO_DONE: ::c_int = 257; + +pub const AF_UNSPEC: ::c_int = 0; +pub const AF_LOCAL: ::c_int = 1; +pub const AF_UNIX: ::c_int = AF_LOCAL; +pub const AF_INET: ::c_int = 2; +pub const AF_IMPLINK: ::c_int = 3; +pub const AF_PUP: ::c_int = 4; +pub const AF_CHAOS: ::c_int = 5; +pub const AF_NS: ::c_int = 6; +pub const AF_ISO: ::c_int = 7; +pub const AF_OSI: ::c_int = AF_ISO; +pub const AF_ECMA: ::c_int = 8; +pub const AF_DATAKIT: ::c_int = 9; +pub const AF_CCITT: ::c_int = 10; +pub const AF_SNA: ::c_int = 11; +pub const AF_DECnet: ::c_int = 12; +pub const AF_DLI: ::c_int = 13; +pub const AF_LAT: ::c_int = 14; +pub const AF_HYLINK: ::c_int = 15; +pub const AF_APPLETALK: ::c_int = 16; +pub const AF_ROUTE: ::c_int = 17; +pub const AF_LINK: ::c_int = 18; +pub const pseudo_AF_XTP: ::c_int = 19; +pub const AF_COIP: ::c_int = 20; +pub const AF_CNT: ::c_int = 21; +pub const pseudo_AF_RTIP: ::c_int = 22; +pub const AF_IPX: ::c_int = 23; +pub const AF_SIP: ::c_int = 24; +pub const pseudo_AF_PIP: ::c_int = 25; +pub const AF_ISDN: ::c_int = 28; +pub const AF_E164: ::c_int = AF_ISDN; +pub const pseudo_AF_KEY: ::c_int = 29; +pub const AF_INET6: ::c_int = 30; +pub const AF_NATM: ::c_int = 31; +pub const AF_SYSTEM: ::c_int = 32; +pub const AF_NETBIOS: ::c_int = 33; +pub const AF_PPP: ::c_int = 34; +pub const pseudo_AF_HDRCMPLT: ::c_int = 35; +#[doc(hidden)] +pub const AF_MAX: ::c_int = 40; +pub const AF_SYS_CONTROL: ::c_int = 2; + +pub const SYSPROTO_EVENT: ::c_int = 1; +pub const SYSPROTO_CONTROL: ::c_int = 2; + +pub const PF_UNSPEC: ::c_int = AF_UNSPEC; +pub const PF_LOCAL: ::c_int = AF_LOCAL; +pub const PF_UNIX: ::c_int = PF_LOCAL; +pub const PF_INET: ::c_int = AF_INET; +pub const PF_IMPLINK: ::c_int = AF_IMPLINK; +pub const PF_PUP: ::c_int = AF_PUP; +pub const PF_CHAOS: ::c_int = AF_CHAOS; +pub const PF_NS: ::c_int = AF_NS; +pub const PF_ISO: ::c_int = AF_ISO; +pub const PF_OSI: ::c_int = AF_ISO; +pub const PF_ECMA: ::c_int = AF_ECMA; +pub const PF_DATAKIT: ::c_int = AF_DATAKIT; +pub const PF_CCITT: ::c_int = AF_CCITT; +pub const PF_SNA: ::c_int = AF_SNA; +pub const PF_DECnet: ::c_int = AF_DECnet; +pub const PF_DLI: ::c_int = AF_DLI; +pub const PF_LAT: ::c_int = AF_LAT; +pub const PF_HYLINK: ::c_int = AF_HYLINK; +pub const PF_APPLETALK: ::c_int = AF_APPLETALK; +pub const PF_ROUTE: ::c_int = AF_ROUTE; +pub const PF_LINK: ::c_int = AF_LINK; +pub const PF_XTP: ::c_int = pseudo_AF_XTP; +pub const PF_COIP: ::c_int = AF_COIP; +pub const PF_CNT: ::c_int = AF_CNT; +pub const PF_SIP: ::c_int = AF_SIP; +pub const PF_IPX: ::c_int = AF_IPX; +pub const PF_RTIP: ::c_int = pseudo_AF_RTIP; +pub const PF_PIP: ::c_int = pseudo_AF_PIP; +pub const PF_ISDN: ::c_int = AF_ISDN; +pub const PF_KEY: ::c_int = pseudo_AF_KEY; +pub const PF_INET6: ::c_int = AF_INET6; +pub const PF_NATM: ::c_int = AF_NATM; +pub const PF_SYSTEM: ::c_int = AF_SYSTEM; +pub const PF_NETBIOS: ::c_int = AF_NETBIOS; +pub const PF_PPP: ::c_int = AF_PPP; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; + +#[doc(hidden)] +pub const NET_MAXID: ::c_int = AF_MAX; + +pub const NET_RT_DUMP: ::c_int = 1; +pub const NET_RT_FLAGS: ::c_int = 2; +pub const NET_RT_IFLIST: ::c_int = 3; +#[doc(hidden)] +pub const NET_RT_MAXID: ::c_int = 10; + +pub const SOMAXCONN: ::c_int = 128; + +pub const SOCK_MAXADDRLEN: ::c_int = 255; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_RAW: ::c_int = 3; +pub const SOCK_RDM: ::c_int = 4; +pub const SOCK_SEQPACKET: ::c_int = 5; +pub const IP_TTL: ::c_int = 4; +pub const IP_HDRINCL: ::c_int = 2; +pub const IP_ADD_MEMBERSHIP: ::c_int = 12; +pub const IP_DROP_MEMBERSHIP: ::c_int = 13; +pub const IPV6_JOIN_GROUP: ::c_int = 12; +pub const IPV6_LEAVE_GROUP: ::c_int = 13; + +pub const TCP_NODELAY: ::c_int = 0x01; +pub const TCP_KEEPALIVE: ::c_int = 0x10; + +pub const SOL_LOCAL: ::c_int = 0; + +pub const LOCAL_PEERCRED: ::c_int = 0x001; +pub const LOCAL_PEERPID: ::c_int = 0x002; +pub const LOCAL_PEEREPID: ::c_int = 0x003; +pub const LOCAL_PEERUUID: ::c_int = 0x004; +pub const LOCAL_PEEREUUID: ::c_int = 0x005; + +pub const SOL_SOCKET: ::c_int = 0xffff; + +pub const SO_DEBUG: ::c_int = 0x01; +pub const SO_ACCEPTCONN: ::c_int = 0x0002; +pub const SO_REUSEADDR: ::c_int = 0x0004; +pub const SO_KEEPALIVE: ::c_int = 0x0008; +pub const SO_DONTROUTE: ::c_int = 0x0010; +pub const SO_BROADCAST: ::c_int = 0x0020; +pub const SO_USELOOPBACK: ::c_int = 0x0040; +pub const SO_LINGER: ::c_int = 0x0080; +pub const SO_OOBINLINE: ::c_int = 0x0100; +pub const SO_REUSEPORT: ::c_int = 0x0200; +pub const SO_TIMESTAMP: ::c_int = 0x0400; +pub const SO_TIMESTAMP_MONOTONIC: ::c_int = 0x0800; +pub const SO_DONTTRUNC: ::c_int = 0x2000; +pub const SO_WANTMORE: ::c_int = 0x4000; +pub const SO_WANTOOBFLAG: ::c_int = 0x8000; +pub const SO_SNDBUF: ::c_int = 0x1001; +pub const SO_RCVBUF: ::c_int = 0x1002; +pub const SO_SNDLOWAT: ::c_int = 0x1003; +pub const SO_RCVLOWAT: ::c_int = 0x1004; +pub const SO_SNDTIMEO: ::c_int = 0x1005; +pub const SO_RCVTIMEO: ::c_int = 0x1006; +pub const SO_ERROR: ::c_int = 0x1007; +pub const SO_TYPE: ::c_int = 0x1008; +pub const SO_LABEL: ::c_int = 0x1010; +pub const SO_PEERLABEL: ::c_int = 0x1011; +pub const SO_NREAD: ::c_int = 0x1020; +pub const SO_NKE: ::c_int = 0x1021; +pub const SO_NOSIGPIPE: ::c_int = 0x1022; +pub const SO_NOADDRERR: ::c_int = 0x1023; +pub const SO_NWRITE: ::c_int = 0x1024; +pub const SO_REUSESHAREUID: ::c_int = 0x1025; +pub const SO_NOTIFYCONFLICT: ::c_int = 0x1026; +pub const SO_RANDOMPORT: ::c_int = 0x1082; +pub const SO_NP_EXTENSIONS: ::c_int = 0x1083; + +pub const MSG_OOB: ::c_int = 0x1; +pub const MSG_PEEK: ::c_int = 0x2; +pub const MSG_DONTROUTE: ::c_int = 0x4; +pub const MSG_EOR: ::c_int = 0x8; +pub const MSG_TRUNC: ::c_int = 0x10; +pub const MSG_CTRUNC: ::c_int = 0x20; +pub const MSG_WAITALL: ::c_int = 0x40; +pub const MSG_DONTWAIT: ::c_int = 0x80; +pub const MSG_EOF: ::c_int = 0x100; +pub const MSG_FLUSH: ::c_int = 0x400; +pub const MSG_HOLD: ::c_int = 0x800; +pub const MSG_SEND: ::c_int = 0x1000; +pub const MSG_HAVEMORE: ::c_int = 0x2000; +pub const MSG_RCVMORE: ::c_int = 0x4000; +// pub const MSG_COMPAT: ::c_int = 0x8000; + +pub const SCM_TIMESTAMP: ::c_int = 0x02; +pub const SCM_CREDS: ::c_int = 0x03; + +// https://github.com/aosm/xnu/blob/master/bsd/net/if.h#L140-L156 +pub const IFF_UP: ::c_int = 0x1; // interface is up +pub const IFF_BROADCAST: ::c_int = 0x2; // broadcast address valid +pub const IFF_DEBUG: ::c_int = 0x4; // turn on debugging +pub const IFF_LOOPBACK: ::c_int = 0x8; // is a loopback net +pub const IFF_POINTOPOINT: ::c_int = 0x10; // interface is point-to-point link +pub const IFF_NOTRAILERS: ::c_int = 0x20; // obsolete: avoid use of trailers +pub const IFF_RUNNING: ::c_int = 0x40; // resources allocated +pub const IFF_NOARP: ::c_int = 0x80; // no address resolution protocol +pub const IFF_PROMISC: ::c_int = 0x100;// receive all packets +pub const IFF_ALLMULTI: ::c_int = 0x200;// receive all multicast packets +pub const IFF_OACTIVE: ::c_int = 0x400;// transmission in progress +pub const IFF_SIMPLEX: ::c_int = 0x800;// can't hear own transmissions +pub const IFF_LINK0: ::c_int = 0x1000;// per link layer defined bit +pub const IFF_LINK1: ::c_int = 0x2000;// per link layer defined bit +pub const IFF_LINK2: ::c_int = 0x4000;// per link layer defined bit +pub const IFF_ALTPHYS: ::c_int = IFF_LINK2;// use alternate physical connection +pub const IFF_MULTICAST: ::c_int = 0x8000;// supports multicast + +pub const SHUT_RD: ::c_int = 0; +pub const SHUT_WR: ::c_int = 1; +pub const SHUT_RDWR: ::c_int = 2; + +pub const LOCK_SH: ::c_int = 1; +pub const LOCK_EX: ::c_int = 2; +pub const LOCK_NB: ::c_int = 4; +pub const LOCK_UN: ::c_int = 8; + +pub const MAP_COPY: ::c_int = 0x0002; +pub const MAP_RENAME: ::c_int = 0x0020; +pub const MAP_NORESERVE: ::c_int = 0x0040; +pub const MAP_NOEXTEND: ::c_int = 0x0100; +pub const MAP_HASSEMAPHORE: ::c_int = 0x0200; +pub const MAP_NOCACHE: ::c_int = 0x0400; +pub const MAP_JIT: ::c_int = 0x0800; + +pub const _SC_ARG_MAX: ::c_int = 1; +pub const _SC_CHILD_MAX: ::c_int = 2; +pub const _SC_CLK_TCK: ::c_int = 3; +pub const _SC_NGROUPS_MAX: ::c_int = 4; +pub const _SC_OPEN_MAX: ::c_int = 5; +pub const _SC_JOB_CONTROL: ::c_int = 6; +pub const _SC_SAVED_IDS: ::c_int = 7; +pub const _SC_VERSION: ::c_int = 8; +pub const _SC_BC_BASE_MAX: ::c_int = 9; +pub const _SC_BC_DIM_MAX: ::c_int = 10; +pub const _SC_BC_SCALE_MAX: ::c_int = 11; +pub const _SC_BC_STRING_MAX: ::c_int = 12; +pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 13; +pub const _SC_EXPR_NEST_MAX: ::c_int = 14; +pub const _SC_LINE_MAX: ::c_int = 15; +pub const _SC_RE_DUP_MAX: ::c_int = 16; +pub const _SC_2_VERSION: ::c_int = 17; +pub const _SC_2_C_BIND: ::c_int = 18; +pub const _SC_2_C_DEV: ::c_int = 19; +pub const _SC_2_CHAR_TERM: ::c_int = 20; +pub const _SC_2_FORT_DEV: ::c_int = 21; +pub const _SC_2_FORT_RUN: ::c_int = 22; +pub const _SC_2_LOCALEDEF: ::c_int = 23; +pub const _SC_2_SW_DEV: ::c_int = 24; +pub const _SC_2_UPE: ::c_int = 25; +pub const _SC_STREAM_MAX: ::c_int = 26; +pub const _SC_TZNAME_MAX: ::c_int = 27; +pub const _SC_ASYNCHRONOUS_IO: ::c_int = 28; +pub const _SC_PAGESIZE: ::c_int = 29; +pub const _SC_MEMLOCK: ::c_int = 30; +pub const _SC_MEMLOCK_RANGE: ::c_int = 31; +pub const _SC_MEMORY_PROTECTION: ::c_int = 32; +pub const _SC_MESSAGE_PASSING: ::c_int = 33; +pub const _SC_PRIORITIZED_IO: ::c_int = 34; +pub const _SC_PRIORITY_SCHEDULING: ::c_int = 35; +pub const _SC_REALTIME_SIGNALS: ::c_int = 36; +pub const _SC_SEMAPHORES: ::c_int = 37; +pub const _SC_FSYNC: ::c_int = 38; +pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 39; +pub const _SC_SYNCHRONIZED_IO: ::c_int = 40; +pub const _SC_TIMERS: ::c_int = 41; +pub const _SC_AIO_LISTIO_MAX: ::c_int = 42; +pub const _SC_AIO_MAX: ::c_int = 43; +pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 44; +pub const _SC_DELAYTIMER_MAX: ::c_int = 45; +pub const _SC_MQ_OPEN_MAX: ::c_int = 46; +pub const _SC_MAPPED_FILES: ::c_int = 47; +pub const _SC_RTSIG_MAX: ::c_int = 48; +pub const _SC_SEM_NSEMS_MAX: ::c_int = 49; +pub const _SC_SEM_VALUE_MAX: ::c_int = 50; +pub const _SC_SIGQUEUE_MAX: ::c_int = 51; +pub const _SC_TIMER_MAX: ::c_int = 52; +pub const _SC_NPROCESSORS_CONF: ::c_int = 57; +pub const _SC_NPROCESSORS_ONLN: ::c_int = 58; +pub const _SC_2_PBS: ::c_int = 59; +pub const _SC_2_PBS_ACCOUNTING: ::c_int = 60; +pub const _SC_2_PBS_CHECKPOINT: ::c_int = 61; +pub const _SC_2_PBS_LOCATE: ::c_int = 62; +pub const _SC_2_PBS_MESSAGE: ::c_int = 63; +pub const _SC_2_PBS_TRACK: ::c_int = 64; +pub const _SC_ADVISORY_INFO: ::c_int = 65; +pub const _SC_BARRIERS: ::c_int = 66; +pub const _SC_CLOCK_SELECTION: ::c_int = 67; +pub const _SC_CPUTIME: ::c_int = 68; +pub const _SC_FILE_LOCKING: ::c_int = 69; +pub const _SC_HOST_NAME_MAX: ::c_int = 72; +pub const _SC_MONOTONIC_CLOCK: ::c_int = 74; +pub const _SC_READER_WRITER_LOCKS: ::c_int = 76; +pub const _SC_REGEXP: ::c_int = 77; +pub const _SC_SHELL: ::c_int = 78; +pub const _SC_SPAWN: ::c_int = 79; +pub const _SC_SPIN_LOCKS: ::c_int = 80; +pub const _SC_SPORADIC_SERVER: ::c_int = 81; +pub const _SC_THREAD_CPUTIME: ::c_int = 84; +pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 92; +pub const _SC_TIMEOUTS: ::c_int = 95; +pub const _SC_TRACE: ::c_int = 97; +pub const _SC_TRACE_EVENT_FILTER: ::c_int = 98; +pub const _SC_TRACE_INHERIT: ::c_int = 99; +pub const _SC_TRACE_LOG: ::c_int = 100; +pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 102; +pub const _SC_V6_ILP32_OFF32: ::c_int = 103; +pub const _SC_V6_ILP32_OFFBIG: ::c_int = 104; +pub const _SC_V6_LP64_OFF64: ::c_int = 105; +pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 106; +pub const _SC_IPV6: ::c_int = 118; +pub const _SC_RAW_SOCKETS: ::c_int = 119; +pub const _SC_SYMLOOP_MAX: ::c_int = 120; +pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; +pub const _SC_XOPEN_STREAMS: ::c_int = 114; +pub const _SC_XBS5_ILP32_OFF32: ::c_int = 122; +pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 123; +pub const _SC_XBS5_LP64_OFF64: ::c_int = 124; +pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 125; +pub const _SC_SS_REPL_MAX: ::c_int = 126; +pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 127; +pub const _SC_TRACE_NAME_MAX: ::c_int = 128; +pub const _SC_TRACE_SYS_MAX: ::c_int = 129; +pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 130; +pub const _SC_PASS_MAX: ::c_int = 131; + +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 1; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 2; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; +pub const _PTHREAD_MUTEX_SIG_init: ::c_long = 0x32AAABA7; +pub const _PTHREAD_COND_SIG_init: ::c_long = 0x3CB0B1BB; +pub const _PTHREAD_RWLOCK_SIG_init: ::c_long = 0x2DA8B3B4; +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + __sig: _PTHREAD_MUTEX_SIG_init, + __opaque: [0; __PTHREAD_MUTEX_SIZE__], +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + __sig: _PTHREAD_COND_SIG_init, + __opaque: [0; __PTHREAD_COND_SIZE__], +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + __sig: _PTHREAD_RWLOCK_SIG_init, + __opaque: [0; __PTHREAD_RWLOCK_SIZE__], +}; + +pub const SIGSTKSZ: ::size_t = 131072; + +pub const FD_SETSIZE: usize = 1024; + +pub const ST_NOSUID: ::c_ulong = 2; + +pub const EVFILT_READ: ::int16_t = -1; +pub const EVFILT_WRITE: ::int16_t = -2; +pub const EVFILT_AIO: ::int16_t = -3; +pub const EVFILT_VNODE: ::int16_t = -4; +pub const EVFILT_PROC: ::int16_t = -5; +pub const EVFILT_SIGNAL: ::int16_t = -6; +pub const EVFILT_TIMER: ::int16_t = -7; +pub const EVFILT_MACHPORT: ::int16_t = -8; +pub const EVFILT_FS: ::int16_t = -9; +pub const EVFILT_USER: ::int16_t = -10; +pub const EVFILT_VM: ::int16_t = -12; + +pub const EV_ADD: ::uint16_t = 0x1; +pub const EV_DELETE: ::uint16_t = 0x2; +pub const EV_ENABLE: ::uint16_t = 0x4; +pub const EV_DISABLE: ::uint16_t = 0x8; +pub const EV_ONESHOT: ::uint16_t = 0x10; +pub const EV_CLEAR: ::uint16_t = 0x20; +pub const EV_RECEIPT: ::uint16_t = 0x40; +pub const EV_DISPATCH: ::uint16_t = 0x80; +pub const EV_FLAG0: ::uint16_t = 0x1000; +pub const EV_POLL: ::uint16_t = 0x1000; +pub const EV_FLAG1: ::uint16_t = 0x2000; +pub const EV_OOBAND: ::uint16_t = 0x2000; +pub const EV_ERROR: ::uint16_t = 0x4000; +pub const EV_EOF: ::uint16_t = 0x8000; +pub const EV_SYSFLAGS: ::uint16_t = 0xf000; + +pub const NOTE_TRIGGER: ::uint32_t = 0x01000000; +pub const NOTE_FFNOP: ::uint32_t = 0x00000000; +pub const NOTE_FFAND: ::uint32_t = 0x40000000; +pub const NOTE_FFOR: ::uint32_t = 0x80000000; +pub const NOTE_FFCOPY: ::uint32_t = 0xc0000000; +pub const NOTE_FFCTRLMASK: ::uint32_t = 0xc0000000; +pub const NOTE_FFLAGSMASK: ::uint32_t = 0x00ffffff; +pub const NOTE_LOWAT: ::uint32_t = 0x00000001; +pub const NOTE_DELETE: ::uint32_t = 0x00000001; +pub const NOTE_WRITE: ::uint32_t = 0x00000002; +pub const NOTE_EXTEND: ::uint32_t = 0x00000004; +pub const NOTE_ATTRIB: ::uint32_t = 0x00000008; +pub const NOTE_LINK: ::uint32_t = 0x00000010; +pub const NOTE_RENAME: ::uint32_t = 0x00000020; +pub const NOTE_REVOKE: ::uint32_t = 0x00000040; +pub const NOTE_NONE: ::uint32_t = 0x00000080; +pub const NOTE_EXIT: ::uint32_t = 0x80000000; +pub const NOTE_FORK: ::uint32_t = 0x40000000; +pub const NOTE_EXEC: ::uint32_t = 0x20000000; +pub const NOTE_REAP: ::uint32_t = 0x10000000; +pub const NOTE_SIGNAL: ::uint32_t = 0x08000000; +pub const NOTE_EXITSTATUS: ::uint32_t = 0x04000000; +pub const NOTE_EXIT_DETAIL: ::uint32_t = 0x02000000; +pub const NOTE_PDATAMASK: ::uint32_t = 0x000fffff; +pub const NOTE_PCTRLMASK: ::uint32_t = 0xfff00000; +pub const NOTE_EXIT_REPARENTED: ::uint32_t = 0x00080000; +pub const NOTE_EXIT_DETAIL_MASK: ::uint32_t = 0x00070000; +pub const NOTE_EXIT_DECRYPTFAIL: ::uint32_t = 0x00010000; +pub const NOTE_EXIT_MEMORY: ::uint32_t = 0x00020000; +pub const NOTE_EXIT_CSERROR: ::uint32_t = 0x00040000; +pub const NOTE_VM_PRESSURE: ::uint32_t = 0x80000000; +pub const NOTE_VM_PRESSURE_TERMINATE: ::uint32_t = 0x40000000; +pub const NOTE_VM_PRESSURE_SUDDEN_TERMINATE: ::uint32_t = 0x20000000; +pub const NOTE_VM_ERROR: ::uint32_t = 0x10000000; +pub const NOTE_SECONDS: ::uint32_t = 0x00000001; +pub const NOTE_USECONDS: ::uint32_t = 0x00000002; +pub const NOTE_NSECONDS: ::uint32_t = 0x00000004; +pub const NOTE_ABSOLUTE: ::uint32_t = 0x00000008; +pub const NOTE_LEEWAY: ::uint32_t = 0x00000010; +pub const NOTE_CRITICAL: ::uint32_t = 0x00000020; +pub const NOTE_BACKGROUND: ::uint32_t = 0x00000040; +pub const NOTE_TRACK: ::uint32_t = 0x00000001; +pub const NOTE_TRACKERR: ::uint32_t = 0x00000002; +pub const NOTE_CHILD: ::uint32_t = 0x00000004; + +pub const OCRNL: ::c_int = 0x00000010; +pub const ONOCR: ::c_int = 0x00000020; +pub const ONLRET: ::c_int = 0x00000040; +pub const OFILL: ::c_int = 0x00000080; +pub const NLDLY: ::c_int = 0x00000300; +pub const TABDLY: ::c_int = 0x00000c04; +pub const CRDLY: ::c_int = 0x00003000; +pub const FFDLY: ::c_int = 0x00004000; +pub const BSDLY: ::c_int = 0x00008000; +pub const VTDLY: ::c_int = 0x00010000; +pub const OFDEL: ::c_int = 0x00020000; + +pub const NL0: ::c_int = 0x00000000; +pub const NL1: ::c_int = 0x00000100; +pub const TAB0: ::c_int = 0x00000000; +pub const TAB1: ::c_int = 0x00000400; +pub const TAB2: ::c_int = 0x00000800; +pub const CR0: ::c_int = 0x00000000; +pub const CR1: ::c_int = 0x00001000; +pub const CR2: ::c_int = 0x00002000; +pub const CR3: ::c_int = 0x00003000; +pub const FF0: ::c_int = 0x00000000; +pub const FF1: ::c_int = 0x00004000; +pub const BS0: ::c_int = 0x00000000; +pub const BS1: ::c_int = 0x00008000; +pub const TAB3: ::c_int = 0x00000004; +pub const VT0: ::c_int = 0x00000000; +pub const VT1: ::c_int = 0x00010000; +pub const IUTF8: ::tcflag_t = 0x00004000; +pub const CRTSCTS: ::tcflag_t = 0x00030000; + +pub const NI_MAXHOST: ::socklen_t = 1025; + +pub const Q_GETQUOTA: ::c_int = 0x300; +pub const Q_SETQUOTA: ::c_int = 0x400; + +pub const RTLD_LOCAL: ::c_int = 0x4; +pub const RTLD_FIRST: ::c_int = 0x100; +pub const RTLD_NODELETE: ::c_int = 0x80; +pub const RTLD_NOLOAD: ::c_int = 0x10; +pub const RTLD_GLOBAL: ::c_int = 0x8; + +pub const _WSTOPPED: ::c_int = 0o177; + +pub const LOG_NETINFO: ::c_int = 12 << 3; +pub const LOG_REMOTEAUTH: ::c_int = 13 << 3; +pub const LOG_INSTALL: ::c_int = 14 << 3; +pub const LOG_RAS: ::c_int = 15 << 3; +pub const LOG_LAUNCHD: ::c_int = 24 << 3; +pub const LOG_NFACILITIES: ::c_int = 25; + +pub const CTLTYPE: ::c_int = 0xf; +pub const CTLTYPE_NODE: ::c_int = 1; +pub const CTLTYPE_INT: ::c_int = 2; +pub const CTLTYPE_STRING: ::c_int = 3; +pub const CTLTYPE_QUAD: ::c_int = 4; +pub const CTLTYPE_OPAQUE: ::c_int = 5; +pub const CTLTYPE_STRUCT: ::c_int = CTLTYPE_OPAQUE; +pub const CTLFLAG_RD: ::c_int = 0x80000000; +pub const CTLFLAG_WR: ::c_int = 0x40000000; +pub const CTLFLAG_RW: ::c_int = CTLFLAG_RD | CTLFLAG_WR; +pub const CTLFLAG_NOLOCK: ::c_int = 0x20000000; +pub const CTLFLAG_ANYBODY: ::c_int = 0x10000000; +pub const CTLFLAG_SECURE: ::c_int = 0x08000000; +pub const CTLFLAG_MASKED: ::c_int = 0x04000000; +pub const CTLFLAG_NOAUTO: ::c_int = 0x02000000; +pub const CTLFLAG_KERN: ::c_int = 0x01000000; +pub const CTLFLAG_LOCKED: ::c_int = 0x00800000; +pub const CTLFLAG_OID2: ::c_int = 0x00400000; +pub const CTL_UNSPEC: ::c_int = 0; +pub const CTL_KERN: ::c_int = 1; +pub const CTL_VM: ::c_int = 2; +pub const CTL_VFS: ::c_int = 3; +pub const CTL_NET: ::c_int = 4; +pub const CTL_DEBUG: ::c_int = 5; +pub const CTL_HW: ::c_int = 6; +pub const CTL_MACHDEP: ::c_int = 7; +pub const CTL_USER: ::c_int = 8; +pub const CTL_MAXID: ::c_int = 9; +pub const KERN_OSTYPE: ::c_int = 1; +pub const KERN_OSRELEASE: ::c_int = 2; +pub const KERN_OSREV: ::c_int = 3; +pub const KERN_VERSION: ::c_int = 4; +pub const KERN_MAXVNODES: ::c_int = 5; +pub const KERN_MAXPROC: ::c_int = 6; +pub const KERN_MAXFILES: ::c_int = 7; +pub const KERN_ARGMAX: ::c_int = 8; +pub const KERN_SECURELVL: ::c_int = 9; +pub const KERN_HOSTNAME: ::c_int = 10; +pub const KERN_HOSTID: ::c_int = 11; +pub const KERN_CLOCKRATE: ::c_int = 12; +pub const KERN_VNODE: ::c_int = 13; +pub const KERN_PROC: ::c_int = 14; +pub const KERN_FILE: ::c_int = 15; +pub const KERN_PROF: ::c_int = 16; +pub const KERN_POSIX1: ::c_int = 17; +pub const KERN_NGROUPS: ::c_int = 18; +pub const KERN_JOB_CONTROL: ::c_int = 19; +pub const KERN_SAVED_IDS: ::c_int = 20; +pub const KERN_BOOTTIME: ::c_int = 21; +pub const KERN_NISDOMAINNAME: ::c_int = 22; +pub const KERN_DOMAINNAME: ::c_int = KERN_NISDOMAINNAME; +pub const KERN_MAXPARTITIONS: ::c_int = 23; +pub const KERN_KDEBUG: ::c_int = 24; +pub const KERN_UPDATEINTERVAL: ::c_int = 25; +pub const KERN_OSRELDATE: ::c_int = 26; +pub const KERN_NTP_PLL: ::c_int = 27; +pub const KERN_BOOTFILE: ::c_int = 28; +pub const KERN_MAXFILESPERPROC: ::c_int = 29; +pub const KERN_MAXPROCPERUID: ::c_int = 30; +pub const KERN_DUMPDEV: ::c_int = 31; +pub const KERN_IPC: ::c_int = 32; +pub const KERN_DUMMY: ::c_int = 33; +pub const KERN_PS_STRINGS: ::c_int = 34; +pub const KERN_USRSTACK32: ::c_int = 35; +pub const KERN_LOGSIGEXIT: ::c_int = 36; +pub const KERN_SYMFILE: ::c_int = 37; +pub const KERN_PROCARGS: ::c_int = 38; +pub const KERN_NETBOOT: ::c_int = 40; +pub const KERN_SYSV: ::c_int = 42; +pub const KERN_AFFINITY: ::c_int = 43; +pub const KERN_TRANSLATE: ::c_int = 44; +pub const KERN_CLASSIC: ::c_int = KERN_TRANSLATE; +pub const KERN_EXEC: ::c_int = 45; +pub const KERN_CLASSICHANDLER: ::c_int = KERN_EXEC; +pub const KERN_AIOMAX: ::c_int = 46; +pub const KERN_AIOPROCMAX: ::c_int = 47; +pub const KERN_AIOTHREADS: ::c_int = 48; +pub const KERN_COREFILE: ::c_int = 50; +pub const KERN_COREDUMP: ::c_int = 51; +pub const KERN_SUGID_COREDUMP: ::c_int = 52; +pub const KERN_PROCDELAYTERM: ::c_int = 53; +pub const KERN_SHREG_PRIVATIZABLE: ::c_int = 54; +pub const KERN_LOW_PRI_WINDOW: ::c_int = 56; +pub const KERN_LOW_PRI_DELAY: ::c_int = 57; +pub const KERN_POSIX: ::c_int = 58; +pub const KERN_USRSTACK64: ::c_int = 59; +pub const KERN_NX_PROTECTION: ::c_int = 60; +pub const KERN_TFP: ::c_int = 61; +pub const KERN_PROCNAME: ::c_int = 62; +pub const KERN_THALTSTACK: ::c_int = 63; +pub const KERN_SPECULATIVE_READS: ::c_int = 64; +pub const KERN_OSVERSION: ::c_int = 65; +pub const KERN_SAFEBOOT: ::c_int = 66; +pub const KERN_RAGEVNODE: ::c_int = 68; +pub const KERN_TTY: ::c_int = 69; +pub const KERN_CHECKOPENEVT: ::c_int = 70; +pub const KERN_THREADNAME: ::c_int = 71; +pub const KERN_MAXID: ::c_int = 72; +pub const KERN_RAGE_PROC: ::c_int = 1; +pub const KERN_RAGE_THREAD: ::c_int = 2; +pub const KERN_UNRAGE_PROC: ::c_int = 3; +pub const KERN_UNRAGE_THREAD: ::c_int = 4; +pub const KERN_OPENEVT_PROC: ::c_int = 1; +pub const KERN_UNOPENEVT_PROC: ::c_int = 2; +pub const KERN_TFP_POLICY: ::c_int = 1; +pub const KERN_TFP_POLICY_DENY: ::c_int = 0; +pub const KERN_TFP_POLICY_DEFAULT: ::c_int = 2; +pub const KERN_KDEFLAGS: ::c_int = 1; +pub const KERN_KDDFLAGS: ::c_int = 2; +pub const KERN_KDENABLE: ::c_int = 3; +pub const KERN_KDSETBUF: ::c_int = 4; +pub const KERN_KDGETBUF: ::c_int = 5; +pub const KERN_KDSETUP: ::c_int = 6; +pub const KERN_KDREMOVE: ::c_int = 7; +pub const KERN_KDSETREG: ::c_int = 8; +pub const KERN_KDGETREG: ::c_int = 9; +pub const KERN_KDREADTR: ::c_int = 10; +pub const KERN_KDPIDTR: ::c_int = 11; +pub const KERN_KDTHRMAP: ::c_int = 12; +pub const KERN_KDPIDEX: ::c_int = 14; +pub const KERN_KDSETRTCDEC: ::c_int = 15; +pub const KERN_KDGETENTROPY: ::c_int = 16; +pub const KERN_KDWRITETR: ::c_int = 17; +pub const KERN_KDWRITEMAP: ::c_int = 18; +pub const KERN_KDENABLE_BG_TRACE: ::c_int = 19; +pub const KERN_KDDISABLE_BG_TRACE: ::c_int = 20; +pub const KERN_KDREADCURTHRMAP: ::c_int = 21; +pub const KERN_KDSET_TYPEFILTER: ::c_int = 22; +pub const KERN_KDBUFWAIT: ::c_int = 23; +pub const KERN_KDCPUMAP: ::c_int = 24; +pub const KERN_PROC_ALL: ::c_int = 0; +pub const KERN_PROC_PID: ::c_int = 1; +pub const KERN_PROC_PGRP: ::c_int = 2; +pub const KERN_PROC_SESSION: ::c_int = 3; +pub const KERN_PROC_TTY: ::c_int = 4; +pub const KERN_PROC_UID: ::c_int = 5; +pub const KERN_PROC_RUID: ::c_int = 6; +pub const KERN_PROC_LCID: ::c_int = 7; +pub const KIPC_MAXSOCKBUF: ::c_int = 1; +pub const KIPC_SOCKBUF_WASTE: ::c_int = 2; +pub const KIPC_SOMAXCONN: ::c_int = 3; +pub const KIPC_MAX_LINKHDR: ::c_int = 4; +pub const KIPC_MAX_PROTOHDR: ::c_int = 5; +pub const KIPC_MAX_HDR: ::c_int = 6; +pub const KIPC_MAX_DATALEN: ::c_int = 7; +pub const KIPC_MBSTAT: ::c_int = 8; +pub const KIPC_NMBCLUSTERS: ::c_int = 9; +pub const KIPC_SOQLIMITCOMPAT: ::c_int = 10; +pub const VM_METER: ::c_int = 1; +pub const VM_LOADAVG: ::c_int = 2; +pub const VM_MACHFACTOR: ::c_int = 4; +pub const VM_SWAPUSAGE: ::c_int = 5; +pub const VM_MAXID: ::c_int = 6; +pub const HW_MACHINE: ::c_int = 1; +pub const HW_MODEL: ::c_int = 2; +pub const HW_NCPU: ::c_int = 3; +pub const HW_BYTEORDER: ::c_int = 4; +pub const HW_PHYSMEM: ::c_int = 5; +pub const HW_USERMEM: ::c_int = 6; +pub const HW_PAGESIZE: ::c_int = 7; +pub const HW_DISKNAMES: ::c_int = 8; +pub const HW_DISKSTATS: ::c_int = 9; +pub const HW_EPOCH: ::c_int = 10; +pub const HW_FLOATINGPT: ::c_int = 11; +pub const HW_MACHINE_ARCH: ::c_int = 12; +pub const HW_VECTORUNIT: ::c_int = 13; +pub const HW_BUS_FREQ: ::c_int = 14; +pub const HW_CPU_FREQ: ::c_int = 15; +pub const HW_CACHELINE: ::c_int = 16; +pub const HW_L1ICACHESIZE: ::c_int = 17; +pub const HW_L1DCACHESIZE: ::c_int = 18; +pub const HW_L2SETTINGS: ::c_int = 19; +pub const HW_L2CACHESIZE: ::c_int = 20; +pub const HW_L3SETTINGS: ::c_int = 21; +pub const HW_L3CACHESIZE: ::c_int = 22; +pub const HW_TB_FREQ: ::c_int = 23; +pub const HW_MEMSIZE: ::c_int = 24; +pub const HW_AVAILCPU: ::c_int = 25; +pub const HW_MAXID: ::c_int = 26; +pub const USER_CS_PATH: ::c_int = 1; +pub const USER_BC_BASE_MAX: ::c_int = 2; +pub const USER_BC_DIM_MAX: ::c_int = 3; +pub const USER_BC_SCALE_MAX: ::c_int = 4; +pub const USER_BC_STRING_MAX: ::c_int = 5; +pub const USER_COLL_WEIGHTS_MAX: ::c_int = 6; +pub const USER_EXPR_NEST_MAX: ::c_int = 7; +pub const USER_LINE_MAX: ::c_int = 8; +pub const USER_RE_DUP_MAX: ::c_int = 9; +pub const USER_POSIX2_VERSION: ::c_int = 10; +pub const USER_POSIX2_C_BIND: ::c_int = 11; +pub const USER_POSIX2_C_DEV: ::c_int = 12; +pub const USER_POSIX2_CHAR_TERM: ::c_int = 13; +pub const USER_POSIX2_FORT_DEV: ::c_int = 14; +pub const USER_POSIX2_FORT_RUN: ::c_int = 15; +pub const USER_POSIX2_LOCALEDEF: ::c_int = 16; +pub const USER_POSIX2_SW_DEV: ::c_int = 17; +pub const USER_POSIX2_UPE: ::c_int = 18; +pub const USER_STREAM_MAX: ::c_int = 19; +pub const USER_TZNAME_MAX: ::c_int = 20; +pub const USER_MAXID: ::c_int = 21; +pub const CTL_DEBUG_NAME: ::c_int = 0; +pub const CTL_DEBUG_VALUE: ::c_int = 1; +pub const CTL_DEBUG_MAXID: ::c_int = 20; + +pub const PRIO_DARWIN_THREAD: ::c_int = 3; +pub const PRIO_DARWIN_PROCESS: ::c_int = 4; +pub const PRIO_DARWIN_BG: ::c_int = 0x1000; +pub const PRIO_DARWIN_NONUI: ::c_int = 0x1001; + +pub const SEM_FAILED: *mut sem_t = -1isize as *mut ::sem_t; + +pub const SIGEV_NONE: ::c_int = 0; +pub const SIGEV_SIGNAL: ::c_int = 1; +pub const SIGEV_THREAD: ::c_int = 3; + +pub const AIO_CANCELED: ::c_int = 2; +pub const AIO_NOTCANCELED: ::c_int = 4; +pub const AIO_ALLDONE: ::c_int = 1; +pub const AIO_LISTIO_MAX: ::c_int = 16; +pub const LIO_NOP: ::c_int = 0; +pub const LIO_WRITE: ::c_int = 2; +pub const LIO_READ: ::c_int = 1; +pub const LIO_WAIT: ::c_int = 2; +pub const LIO_NOWAIT: ::c_int = 1; + +pub const WEXITED: ::c_int = 0x00000004; +pub const WSTOPPED: ::c_int = 0x00000008; +pub const WCONTINUED: ::c_int = 0x00000010; +pub const WNOWAIT: ::c_int = 0x00000020; + +pub const P_ALL: idtype_t = 0; +pub const P_PID: idtype_t = 1; +pub const P_PGID: idtype_t = 2; + +pub const XATTR_NOFOLLOW: ::c_int = 0x0001; +pub const XATTR_CREATE: ::c_int = 0x0002; +pub const XATTR_REPLACE: ::c_int = 0x0004; +pub const XATTR_NOSECURITY: ::c_int = 0x0008; +pub const XATTR_NODEFAULT: ::c_int = 0x0010; +pub const XATTR_SHOWCOMPRESSION: ::c_int = 0x0020; + +pub const NET_RT_IFLIST2: ::c_int = 0x0006; + +// net/route.h +pub const RTF_UP: ::c_int = 0x1; +pub const RTF_GATEWAY: ::c_int = 0x2; +pub const RTF_HOST: ::c_int = 0x4; +pub const RTF_REJECT: ::c_int = 0x8; +pub const RTF_DYNAMIC: ::c_int = 0x10; +pub const RTF_MODIFIED: ::c_int = 0x20; +pub const RTF_DONE: ::c_int = 0x40; +pub const RTF_DELCLONE: ::c_int = 0x80; +pub const RTF_CLONING: ::c_int = 0x100; +pub const RTF_XRESOLVE: ::c_int = 0x200; +pub const RTF_LLINFO: ::c_int = 0x400; +pub const RTF_STATIC: ::c_int = 0x800; +pub const RTF_BLACKHOLE: ::c_int = 0x1000; +pub const RTF_NOIFREF: ::c_int = 0x2000; +pub const RTF_PROTO2: ::c_int = 0x4000; +pub const RTF_PROTO1: ::c_int = 0x8000; +pub const RTF_PRCLONING: ::c_int = 0x10000; +pub const RTF_WASCLONED: ::c_int = 0x20000; +pub const RTF_PROTO3: ::c_int = 0x40000; +pub const RTF_PINNED: ::c_int = 0x100000; +pub const RTF_LOCAL: ::c_int = 0x200000; +pub const RTF_BROADCAST: ::c_int = 0x400000; +pub const RTF_MULTICAST: ::c_int = 0x800000; +pub const RTF_IFSCOPE: ::c_int = 0x1000000; +pub const RTF_CONDEMNED: ::c_int = 0x2000000; +pub const RTF_IFREF: ::c_int = 0x4000000; +pub const RTF_PROXY: ::c_int = 0x8000000; +pub const RTF_ROUTER: ::c_int = 0x10000000; + +pub const RTM_VERSION: ::c_int = 5; + +// Message types +pub const RTM_ADD: ::c_int = 0x1; +pub const RTM_DELETE: ::c_int = 0x2; +pub const RTM_CHANGE: ::c_int = 0x3; +pub const RTM_GET: ::c_int = 0x4; +pub const RTM_LOSING: ::c_int = 0x5; +pub const RTM_REDIRECT: ::c_int = 0x6; +pub const RTM_MISS: ::c_int = 0x7; +pub const RTM_LOCK: ::c_int = 0x8; +pub const RTM_OLDADD: ::c_int = 0x9; +pub const RTM_OLDDEL: ::c_int = 0xa; +pub const RTM_RESOLVE: ::c_int = 0xb; +pub const RTM_NEWADDR: ::c_int = 0xc; +pub const RTM_DELADDR: ::c_int = 0xd; +pub const RTM_IFINFO: ::c_int = 0xe; +pub const RTM_NEWMADDR: ::c_int = 0xf; +pub const RTM_DELMADDR: ::c_int = 0x10; +pub const RTM_IFINFO2: ::c_int = 0x12; +pub const RTM_NEWMADDR2: ::c_int = 0x13; +pub const RTM_GET2: ::c_int = 0x14; + +// Bitmask values for rtm_inits and rmx_locks. +pub const RTV_MTU: ::c_int = 0x1; +pub const RTV_HOPCOUNT: ::c_int = 0x2; +pub const RTV_EXPIRE: ::c_int = 0x4; +pub const RTV_RPIPE: ::c_int = 0x8; +pub const RTV_SPIPE: ::c_int = 0x10; +pub const RTV_SSTHRESH: ::c_int = 0x20; +pub const RTV_RTT: ::c_int = 0x40; +pub const RTV_RTTVAR: ::c_int = 0x80; + +// Bitmask values for rtm_addrs. +pub const RTA_DST: ::c_int = 0x1; +pub const RTA_GATEWAY: ::c_int = 0x2; +pub const RTA_NETMASK: ::c_int = 0x4; +pub const RTA_GENMASK: ::c_int = 0x8; +pub const RTA_IFP: ::c_int = 0x10; +pub const RTA_IFA: ::c_int = 0x20; +pub const RTA_AUTHOR: ::c_int = 0x40; +pub const RTA_BRD: ::c_int = 0x80; + +// Index offsets for sockaddr array for alternate internal encoding. +pub const RTAX_DST: ::c_int = 0; +pub const RTAX_GATEWAY: ::c_int = 1; +pub const RTAX_NETMASK: ::c_int = 2; +pub const RTAX_GENMASK: ::c_int = 3; +pub const RTAX_IFP: ::c_int = 4; +pub const RTAX_IFA: ::c_int = 5; +pub const RTAX_AUTHOR: ::c_int = 6; +pub const RTAX_BRD: ::c_int = 7; +pub const RTAX_MAX: ::c_int = 8; + +pub const KERN_PROCARGS2: ::c_int = 49; + +pub const PROC_PIDTASKALLINFO: ::c_int = 2; +pub const PROC_PIDTASKINFO: ::c_int = 4; +pub const PROC_PIDTHREADINFO: ::c_int = 5; +pub const MAXCOMLEN: usize = 16; +pub const MAXTHREADNAMESIZE: usize = 64; + +pub const XUCRED_VERSION: ::c_uint = 0; + +pub const LC_SEGMENT: u32 = 0x1; +pub const LC_SEGMENT_64: u32 = 0x19; + +pub const MH_MAGIC: u32 = 0xfeedface; +pub const MH_MAGIC_64: u32 = 0xfeedfacf; + +// net/if_utun.h +pub const UTUN_OPT_FLAGS: ::c_int = 1; +pub const UTUN_OPT_IFNAME: ::c_int = 2; + +// net/bpf.h +pub const DLT_NULL: ::c_uint = 0; // no link-layer encapsulation +pub const DLT_EN10MB: ::c_uint = 1; // Ethernet (10Mb) +pub const DLT_EN3MB: ::c_uint = 2; // Experimental Ethernet (3Mb) +pub const DLT_AX25: ::c_uint = 3; // Amateur Radio AX.25 +pub const DLT_PRONET: ::c_uint = 4; // Proteon ProNET Token Ring +pub const DLT_CHAOS: ::c_uint = 5; // Chaos +pub const DLT_IEEE802: ::c_uint = 6; // IEEE 802 Networks +pub const DLT_ARCNET: ::c_uint = 7; // ARCNET +pub const DLT_SLIP: ::c_uint = 8; // Serial Line IP +pub const DLT_PPP: ::c_uint = 9; // Point-to-point Protocol +pub const DLT_FDDI: ::c_uint = 10; // FDDI +pub const DLT_ATM_RFC1483: ::c_uint = 11; // LLC/SNAP encapsulated atm +pub const DLT_RAW: ::c_uint = 12; // raw IP +pub const DLT_LOOP: ::c_uint = 108; + +// https://github.com/apple/darwin-xnu/blob/master/bsd/net/bpf.h#L100 +// sizeof(int32_t) +pub const BPF_ALIGNMENT: ::c_int = 4; + +pub const POSIX_SPAWN_RESETIDS: ::c_int = 0x01; +pub const POSIX_SPAWN_SETPGROUP: ::c_int = 0x02; +pub const POSIX_SPAWN_SETSIGDEF: ::c_int = 0x04; +pub const POSIX_SPAWN_SETSIGMASK: ::c_int = 0x08; + +// sys/ipc.h: +pub const IPC_CREAT: ::c_int = 0x200; +pub const IPC_EXCL: ::c_int = 0x400; +pub const IPC_NOWAIT: ::c_int = 0x800; +pub const IPC_PRIVATE: key_t = 0; + +pub const IPC_RMID: ::c_int = 0; +pub const IPC_SET: ::c_int = 1; +pub const IPC_STAT: ::c_int = 2; + +pub const IPC_R: ::c_int = 0x100; +pub const IPC_W: ::c_int = 0x80; +pub const IPC_M: ::c_int = 0x1000; + +// sys/shm.h +pub const SHM_RDONLY: ::c_int = 0x1000; +pub const SHM_RND: ::c_int = 0x2000; +pub const SHMLBA: ::c_int = 4096; +pub const SHM_R: ::c_int = IPC_R; +pub const SHM_W: ::c_int = IPC_W; + +f! { + pub fn WSTOPSIG(status: ::c_int) -> ::c_int { + status >> 8 + } + + pub fn _WSTATUS(status: ::c_int) -> ::c_int { + status & 0x7f + } + + pub fn WIFCONTINUED(status: ::c_int) -> bool { + _WSTATUS(status) == _WSTOPPED && WSTOPSIG(status) == 0x13 + } + + pub fn WIFSIGNALED(status: ::c_int) -> bool { + _WSTATUS(status) != _WSTOPPED && _WSTATUS(status) != 0 + } + + pub fn WIFSTOPPED(status: ::c_int) -> bool { + _WSTATUS(status) == _WSTOPPED && WSTOPSIG(status) != 0x13 + } +} + +extern { + pub fn aio_read(aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_write(aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_fsync(op: ::c_int, aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_error(aiocbp: *const aiocb) -> ::c_int; + pub fn aio_return(aiocbp: *mut aiocb) -> ::ssize_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "aio_suspend$UNIX2003")] + pub fn aio_suspend(aiocb_list: *const *const aiocb, nitems: ::c_int, + timeout: *const ::timespec) -> ::c_int; + pub fn aio_cancel(fd: ::c_int, aiocbp: *mut aiocb) -> ::c_int; + pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn lio_listio(mode: ::c_int, aiocb_list: *const *mut aiocb, + nitems: ::c_int, sevp: *mut sigevent) -> ::c_int; + + pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; + + pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; + + pub fn getutxent() -> *mut utmpx; + pub fn getutxid(ut: *const utmpx) -> *mut utmpx; + pub fn getutxline(ut: *const utmpx) -> *mut utmpx; + pub fn pututxline(ut: *const utmpx) -> *mut utmpx; + pub fn setutxent(); + pub fn endutxent(); + pub fn utmpxname(file: *const ::c_char) -> ::c_int; + + pub fn getnameinfo(sa: *const ::sockaddr, + salen: ::socklen_t, + host: *mut ::c_char, + hostlen: ::socklen_t, + serv: *mut ::c_char, + sevlen: ::socklen_t, + flags: ::c_int) -> ::c_int; + pub fn mincore(addr: *const ::c_void, len: ::size_t, + vec: *mut ::c_char) -> ::c_int; + pub fn sysctlnametomib(name: *const ::c_char, + mibp: *mut ::c_int, + sizep: *mut ::size_t) + -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "mprotect$UNIX2003")] + pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) + -> ::c_int; + pub fn shm_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::c_int; + pub fn shmat(shmid: ::c_int, shmaddr: *const ::c_void, + shmflg: ::c_int) -> *mut ::c_void; + pub fn shmdt(shmaddr: *const ::c_void) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "shmctl$UNIX2003")] + pub fn shmctl(shmid: ::c_int, cmd: ::c_int, + buf: *mut ::shmid_ds) -> ::c_int; + pub fn shmget(key: key_t, size: ::size_t, shmflg: ::c_int) -> ::c_int; + pub fn sysctl(name: *mut ::c_int, + namelen: ::c_uint, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *mut ::c_void, + newlen: ::size_t) + -> ::c_int; + pub fn sysctlbyname(name: *const ::c_char, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *mut ::c_void, + newlen: ::size_t) + -> ::c_int; + pub fn mach_absolute_time() -> u64; + pub fn mach_timebase_info(info: *mut ::mach_timebase_info) -> ::c_int; + pub fn pthread_setname_np(name: *const ::c_char) -> ::c_int; + pub fn pthread_get_stackaddr_np(thread: ::pthread_t) -> *mut ::c_void; + pub fn pthread_get_stacksize_np(thread: ::pthread_t) -> ::size_t; + pub fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, + pshared: ::c_int) -> ::c_int; + pub fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, + pshared: *mut ::c_int) -> ::c_int; + pub fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, + pshared: ::c_int) -> ::c_int; + pub fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, + pshared: *mut ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, + val: *mut ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, + val: ::c_int) -> ::c_int; + pub fn __error() -> *mut ::c_int; + pub fn backtrace(buf: *mut *mut ::c_void, + sz: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "macos", link_name = "statfs$INODE64")] + pub fn statfs(path: *const ::c_char, buf: *mut statfs) -> ::c_int; + #[cfg_attr(target_os = "macos", link_name = "fstatfs$INODE64")] + pub fn fstatfs(fd: ::c_int, buf: *mut statfs) -> ::c_int; + pub fn kevent(kq: ::c_int, + changelist: *const ::kevent, + nchanges: ::c_int, + eventlist: *mut ::kevent, + nevents: ::c_int, + timeout: *const ::timespec) -> ::c_int; + pub fn kevent64(kq: ::c_int, + changelist: *const ::kevent64_s, + nchanges: ::c_int, + eventlist: *mut ::kevent64_s, + nevents: ::c_int, + flags: ::c_uint, + timeout: *const ::timespec) -> ::c_int; + pub fn mount(src: *const ::c_char, + target: *const ::c_char, + flags: ::c_int, + data: *mut ::c_void) -> ::c_int; + pub fn ptrace(request: ::c_int, + pid: ::pid_t, + addr: *mut ::c_char, + data: ::c_int) -> ::c_int; + pub fn quotactl(special: *const ::c_char, + cmd: ::c_int, + id: ::c_int, + data: *mut ::c_char) -> ::c_int; + pub fn sethostname(name: *const ::c_char, len: ::c_int) -> ::c_int; + pub fn sendfile(fd: ::c_int, + s: ::c_int, + offset: ::off_t, + len: *mut ::off_t, + hdtr: *mut ::sf_hdtr, + flags: ::c_int) -> ::c_int; + pub fn openpty(amaster: *mut ::c_int, + aslave: *mut ::c_int, + name: *mut ::c_char, + termp: *mut termios, + winp: *mut ::winsize) -> ::c_int; + pub fn forkpty(amaster: *mut ::c_int, + name: *mut ::c_char, + termp: *mut termios, + winp: *mut ::winsize) -> ::pid_t; + pub fn duplocale(base: ::locale_t) -> ::locale_t; + pub fn freelocale(loc: ::locale_t) -> ::c_int; + pub fn localeconv_l(loc: ::locale_t) -> *mut lconv; + pub fn newlocale(mask: ::c_int, + locale: *const ::c_char, + base: ::locale_t) -> ::locale_t; + pub fn uselocale(loc: ::locale_t) -> ::locale_t; + pub fn querylocale(mask: ::c_int, loc: ::locale_t) -> *const ::c_char; + pub fn getpriority(which: ::c_int, who: ::id_t) -> ::c_int; + pub fn setpriority(which: ::c_int, who: ::id_t, prio: ::c_int) -> ::c_int; + pub fn getdomainname(name: *mut ::c_char, len: ::c_int) -> ::c_int; + pub fn setdomainname(name: *const ::c_char, len: ::c_int) -> ::c_int; + pub fn getxattr(path: *const ::c_char, name: *const ::c_char, + value: *mut ::c_void, size: ::size_t, position: u32, + flags: ::c_int) -> ::ssize_t; + pub fn fgetxattr(filedes: ::c_int, name: *const ::c_char, + value: *mut ::c_void, size: ::size_t, position: u32, + flags: ::c_int) -> ::ssize_t; + pub fn setxattr(path: *const ::c_char, name: *const ::c_char, + value: *const ::c_void, size: ::size_t, position: u32, + flags: ::c_int) -> ::c_int; + pub fn fsetxattr(filedes: ::c_int, name: *const ::c_char, + value: *const ::c_void, size: ::size_t, position: u32, + flags: ::c_int) -> ::c_int; + pub fn listxattr(path: *const ::c_char, list: *mut ::c_char, + size: ::size_t, flags: ::c_int) -> ::ssize_t; + pub fn flistxattr(filedes: ::c_int, list: *mut ::c_char, + size: ::size_t, flags: ::c_int) -> ::ssize_t; + pub fn removexattr(path: *const ::c_char, name: *const ::c_char, + flags: ::c_int) -> ::c_int; + pub fn fremovexattr(filedes: ::c_int, name: *const ::c_char, + flags: ::c_int) -> ::c_int; + + pub fn getgrouplist(name: *const ::c_char, + basegid: ::c_int, + groups: *mut ::c_int, + ngroups: *mut ::c_int) -> ::c_int; + pub fn initgroups(user: *const ::c_char, basegroup: ::c_int) -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "waitid$UNIX2003")] + pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, + options: ::c_int) -> ::c_int; + pub fn brk(addr: *const ::c_void) -> *mut ::c_void; + pub fn sbrk(increment: ::c_int) -> *mut ::c_void; + pub fn settimeofday(tv: *const ::timeval, tz: *const ::timezone) -> ::c_int; + pub fn _dyld_image_count() -> u32; + pub fn _dyld_get_image_header(image_index: u32) -> *const mach_header; + pub fn _dyld_get_image_vmaddr_slide(image_index: u32) -> ::intptr_t; + pub fn _dyld_get_image_name(image_index: u32) -> *const ::c_char; + + pub fn posix_spawn(pid: *mut ::pid_t, + path: *const ::c_char, + file_actions: *const ::posix_spawn_file_actions_t, + attrp: *const ::posix_spawnattr_t, + argv: *const *mut ::c_char, + envp: *const *mut ::c_char) -> ::c_int; + pub fn posix_spawnp(pid: *mut ::pid_t, + file: *const ::c_char, + file_actions: *const ::posix_spawn_file_actions_t, + attrp: *const ::posix_spawnattr_t, + argv: *const *mut ::c_char, + envp: *const *mut ::c_char) -> ::c_int; + pub fn posix_spawnattr_init(attr: *mut posix_spawnattr_t) -> ::c_int; + pub fn posix_spawnattr_destroy(attr: *mut posix_spawnattr_t) -> ::c_int; + pub fn posix_spawnattr_getsigdefault(attr: *const posix_spawnattr_t, + default: *mut ::sigset_t) -> ::c_int; + pub fn posix_spawnattr_setsigdefault(attr: *mut posix_spawnattr_t, + default: *const ::sigset_t) -> ::c_int; + pub fn posix_spawnattr_getsigmask(attr: *const posix_spawnattr_t, + default: *mut ::sigset_t) -> ::c_int; + pub fn posix_spawnattr_setsigmask(attr: *mut posix_spawnattr_t, + default: *const ::sigset_t) -> ::c_int; + pub fn posix_spawnattr_getflags(attr: *const posix_spawnattr_t, + flags: *mut ::c_short) -> ::c_int; + pub fn posix_spawnattr_setflags(attr: *mut posix_spawnattr_t, + flags: ::c_short) -> ::c_int; + pub fn posix_spawnattr_getpgroup(attr: *const posix_spawnattr_t, + flags: *mut ::pid_t) -> ::c_int; + pub fn posix_spawnattr_setpgroup(attr: *mut posix_spawnattr_t, + flags: ::pid_t) -> ::c_int; + + pub fn posix_spawn_file_actions_init( + actions: *mut posix_spawn_file_actions_t, + ) -> ::c_int; + pub fn posix_spawn_file_actions_destroy( + actions: *mut posix_spawn_file_actions_t, + ) -> ::c_int; + pub fn posix_spawn_file_actions_addopen( + actions: *mut posix_spawn_file_actions_t, + fd: ::c_int, + path: *const ::c_char, + oflag: ::c_int, + mode: ::mode_t, + ) -> ::c_int; + pub fn posix_spawn_file_actions_addclose( + actions: *mut posix_spawn_file_actions_t, + fd: ::c_int, + ) -> ::c_int; + pub fn posix_spawn_file_actions_adddup2( + actions: *mut posix_spawn_file_actions_t, + fd: ::c_int, + newfd: ::c_int, + ) -> ::c_int; +} + +cfg_if! { + if #[cfg(any(target_arch = "arm", target_arch = "x86"))] { + mod b32; + pub use self::b32::*; + } else if #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] { + mod b64; + pub use self::b64::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/dragonfly/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/dragonfly/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/dragonfly/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/dragonfly/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,763 @@ +pub type clock_t = u64; +pub type ino_t = u64; +pub type lwpid_t = i32; +pub type nlink_t = u32; +pub type blksize_t = i64; +pub type clockid_t = ::c_ulong; + +pub type c_long = i64; +pub type c_ulong = u64; +pub type time_t = i64; +pub type suseconds_t = i64; + +pub type uuid_t = ::uuid; + +pub type fsblkcnt_t = u64; +pub type fsfilcnt_t = u64; + +pub type sem_t = *mut sem; + +pub enum sem {} + +s! { + + pub struct exit_status { + pub e_termination: u16, + pub e_exit: u16 + } + + pub struct utmpx { + pub ut_name: [::c_char; 32], + pub ut_id: [::c_char; 4], + + pub ut_line: [::c_char; 32], + pub ut_host: [::c_char; 256], + + pub ut_unused: [u8; 16], + pub ut_session: u16, + pub ut_type: u16, + pub ut_pid: ::pid_t, + ut_exit: exit_status, + ut_ss: ::sockaddr_storage, + pub ut_tv: ::timeval, + pub ut_unused2: [u8; 16], + } + + pub struct aiocb { + pub aio_fildes: ::c_int, + pub aio_offset: ::off_t, + pub aio_buf: *mut ::c_void, + pub aio_nbytes: ::size_t, + pub aio_sigevent: sigevent, + pub aio_lio_opcode: ::c_int, + pub aio_reqprio: ::c_int, + _aio_val: ::c_int, + _aio_err: ::c_int + } + + pub struct dirent { + pub d_fileno: ::ino_t, + pub d_namlen: u16, + pub d_type: u8, + __unused1: u8, + __unused2: u32, + pub d_name: [::c_char; 256], + } + + pub struct uuid { + pub time_low: u32, + pub time_mid: u16, + pub time_hi_and_version: u16, + pub clock_seq_hi_and_reserved: u8, + pub clock_seq_low: u8, + pub node: [u8; 6], + } + + pub struct mq_attr { + pub mq_flags: ::c_long, + pub mq_maxmsg: ::c_long, + pub mq_msgsize: ::c_long, + pub mq_curmsgs: ::c_long, + } + + pub struct sigevent { + pub sigev_notify: ::c_int, + // The union is 8-byte in size, so it is aligned at a 8-byte offset. + #[cfg(target_pointer_width = "64")] + __unused1: ::c_int, + pub sigev_signo: ::c_int, //actually a union + // pad the union + #[cfg(target_pointer_width = "64")] + __unused2: ::c_int, + pub sigev_value: ::sigval, + __unused3: *mut ::c_void //actually a function pointer + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + pub f_owner: ::uid_t, + pub f_type: ::c_uint, + pub f_syncreads: u64, + pub f_syncwrites: u64, + pub f_asyncreads: u64, + pub f_asyncwrites: u64, + pub f_fsid_uuid: ::uuid_t, + pub f_uid_uuid: ::uuid_t, + } + + pub struct stat { + pub st_ino: ::ino_t, + pub st_nlink: ::nlink_t, + pub st_dev: ::dev_t, + pub st_mode: ::mode_t, + pub st_padding1: ::uint16_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_size: ::off_t, + pub st_blocks: ::int64_t, + pub st_blksize: ::uint32_t, + pub st_flags: ::uint32_t, + pub st_gen: ::uint32_t, + pub st_lspare: ::int32_t, + pub st_qspare1: ::int64_t, + pub st_qspare2: ::int64_t, + } + + pub struct if_data { + pub ifi_type: ::c_uchar, + pub ifi_physical: ::c_uchar, + pub ifi_addrlen: ::c_uchar, + pub ifi_hdrlen: ::c_uchar, + pub ifi_recvquota: ::c_uchar, + pub ifi_xmitquota: ::c_uchar, + pub ifi_mtu: ::c_ulong, + pub ifi_metric: ::c_ulong, + pub ifi_link_state: ::c_ulong, + pub ifi_baudrate: u64, + pub ifi_ipackets: ::c_ulong, + pub ifi_ierrors: ::c_ulong, + pub ifi_opackets: ::c_ulong, + pub ifi_oerrors: ::c_ulong, + pub ifi_collisions: ::c_ulong, + pub ifi_ibytes: ::c_ulong, + pub ifi_obytes: ::c_ulong, + pub ifi_imcasts: ::c_ulong, + pub ifi_omcasts: ::c_ulong, + pub ifi_iqdrops: ::c_ulong, + pub ifi_noproto: ::c_ulong, + pub ifi_hwassist: ::c_ulong, + pub ifi_oqdrops: ::c_ulong, + pub ifi_lastchange: ::timeval, + } + + pub struct if_msghdr { + pub ifm_msglen: ::c_ushort, + pub ifm_version: ::c_uchar, + pub ifm_type: ::c_uchar, + pub ifm_addrs: ::c_int, + pub ifm_flags: ::c_int, + pub ifm_index: ::c_ushort, + pub ifm_data: if_data, + } + + pub struct sockaddr_dl { + pub sdl_len: ::c_uchar, + pub sdl_family: ::c_uchar, + pub sdl_index: ::c_ushort, + pub sdl_type: ::c_uchar, + pub sdl_nlen: ::c_uchar, + pub sdl_alen: ::c_uchar, + pub sdl_slen: ::c_uchar, + pub sdl_data: [::c_char; 12], + pub sdl_rcf: ::c_ushort, + pub sdl_route: [::c_ushort; 16], + } +} + +pub const RAND_MAX: ::c_int = 0x7fff_ffff; +pub const PTHREAD_STACK_MIN: ::size_t = 16384; +pub const SIGSTKSZ: ::size_t = 40960; +pub const MADV_INVAL: ::c_int = 10; +pub const MADV_SETMAP: ::c_int = 11; +pub const O_CLOEXEC: ::c_int = 0x00020000; +pub const O_DIRECTORY: ::c_int = 0x08000000; +pub const F_GETLK: ::c_int = 7; +pub const F_SETLK: ::c_int = 8; +pub const F_SETLKW: ::c_int = 9; +pub const ELAST: ::c_int = 99; +pub const RLIMIT_POSIXLOCKS: ::c_int = 11; +pub const RLIM_NLIMITS: ::rlim_t = 12; + +pub const Q_GETQUOTA: ::c_int = 0x300; +pub const Q_SETQUOTA: ::c_int = 0x400; + +pub const CLOCK_REALTIME: ::clockid_t = 0; +pub const CLOCK_VIRTUAL: ::clockid_t = 1; +pub const CLOCK_PROF: ::clockid_t = 2; +pub const CLOCK_MONOTONIC: ::clockid_t = 4; +pub const CLOCK_UPTIME: ::clockid_t = 5; +pub const CLOCK_UPTIME_PRECISE: ::clockid_t = 7; +pub const CLOCK_UPTIME_FAST: ::clockid_t = 8; +pub const CLOCK_REALTIME_PRECISE: ::clockid_t = 9; +pub const CLOCK_REALTIME_FAST: ::clockid_t = 10; +pub const CLOCK_MONOTONIC_PRECISE: ::clockid_t = 11; +pub const CLOCK_MONOTONIC_FAST: ::clockid_t = 12; +pub const CLOCK_SECOND: ::clockid_t = 13; +pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 14; +pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 15; + +pub const CTL_UNSPEC: ::c_int = 0; +pub const CTL_KERN: ::c_int = 1; +pub const CTL_VM: ::c_int = 2; +pub const CTL_VFS: ::c_int = 3; +pub const CTL_NET: ::c_int = 4; +pub const CTL_DEBUG: ::c_int = 5; +pub const CTL_HW: ::c_int = 6; +pub const CTL_MACHDEP: ::c_int = 7; +pub const CTL_USER: ::c_int = 8; +pub const CTL_P1003_1B: ::c_int = 9; +pub const CTL_LWKT: ::c_int = 10; +pub const CTL_MAXID: ::c_int = 11; +pub const KERN_OSTYPE: ::c_int = 1; +pub const KERN_OSRELEASE: ::c_int = 2; +pub const KERN_OSREV: ::c_int = 3; +pub const KERN_VERSION: ::c_int = 4; +pub const KERN_MAXVNODES: ::c_int = 5; +pub const KERN_MAXPROC: ::c_int = 6; +pub const KERN_MAXFILES: ::c_int = 7; +pub const KERN_ARGMAX: ::c_int = 8; +pub const KERN_SECURELVL: ::c_int = 9; +pub const KERN_HOSTNAME: ::c_int = 10; +pub const KERN_HOSTID: ::c_int = 11; +pub const KERN_CLOCKRATE: ::c_int = 12; +pub const KERN_VNODE: ::c_int = 13; +pub const KERN_PROC: ::c_int = 14; +pub const KERN_FILE: ::c_int = 15; +pub const KERN_PROF: ::c_int = 16; +pub const KERN_POSIX1: ::c_int = 17; +pub const KERN_NGROUPS: ::c_int = 18; +pub const KERN_JOB_CONTROL: ::c_int = 19; +pub const KERN_SAVED_IDS: ::c_int = 20; +pub const KERN_BOOTTIME: ::c_int = 21; +pub const KERN_NISDOMAINNAME: ::c_int = 22; +pub const KERN_UPDATEINTERVAL: ::c_int = 23; +pub const KERN_OSRELDATE: ::c_int = 24; +pub const KERN_NTP_PLL: ::c_int = 25; +pub const KERN_BOOTFILE: ::c_int = 26; +pub const KERN_MAXFILESPERPROC: ::c_int = 27; +pub const KERN_MAXPROCPERUID: ::c_int = 28; +pub const KERN_DUMPDEV: ::c_int = 29; +pub const KERN_IPC: ::c_int = 30; +pub const KERN_DUMMY: ::c_int = 31; +pub const KERN_PS_STRINGS: ::c_int = 32; +pub const KERN_USRSTACK: ::c_int = 33; +pub const KERN_LOGSIGEXIT: ::c_int = 34; +pub const KERN_IOV_MAX: ::c_int = 35; +pub const KERN_MAXPOSIXLOCKSPERUID: ::c_int = 36; +pub const KERN_MAXID: ::c_int = 37; +pub const KERN_PROC_ALL: ::c_int = 0; +pub const KERN_PROC_PID: ::c_int = 1; +pub const KERN_PROC_PGRP: ::c_int = 2; +pub const KERN_PROC_SESSION: ::c_int = 3; +pub const KERN_PROC_TTY: ::c_int = 4; +pub const KERN_PROC_UID: ::c_int = 5; +pub const KERN_PROC_RUID: ::c_int = 6; +pub const KERN_PROC_ARGS: ::c_int = 7; +pub const KERN_PROC_CWD: ::c_int = 8; +pub const KERN_PROC_PATHNAME: ::c_int = 9; +pub const KERN_PROC_FLAGMASK: ::c_int = 0x10; +pub const KERN_PROC_FLAG_LWP: ::c_int = 0x10; +pub const KIPC_MAXSOCKBUF: ::c_int = 1; +pub const KIPC_SOCKBUF_WASTE: ::c_int = 2; +pub const KIPC_SOMAXCONN: ::c_int = 3; +pub const KIPC_MAX_LINKHDR: ::c_int = 4; +pub const KIPC_MAX_PROTOHDR: ::c_int = 5; +pub const KIPC_MAX_HDR: ::c_int = 6; +pub const KIPC_MAX_DATALEN: ::c_int = 7; +pub const KIPC_MBSTAT: ::c_int = 8; +pub const KIPC_NMBCLUSTERS: ::c_int = 9; +pub const HW_MACHINE: ::c_int = 1; +pub const HW_MODEL: ::c_int = 2; +pub const HW_NCPU: ::c_int = 3; +pub const HW_BYTEORDER: ::c_int = 4; +pub const HW_PHYSMEM: ::c_int = 5; +pub const HW_USERMEM: ::c_int = 6; +pub const HW_PAGESIZE: ::c_int = 7; +pub const HW_DISKNAMES: ::c_int = 8; +pub const HW_DISKSTATS: ::c_int = 9; +pub const HW_FLOATINGPT: ::c_int = 10; +pub const HW_MACHINE_ARCH: ::c_int = 11; +pub const HW_MACHINE_PLATFORM: ::c_int = 12; +pub const HW_SENSORS: ::c_int = 13; +pub const HW_MAXID: ::c_int = 14; +pub const USER_CS_PATH: ::c_int = 1; +pub const USER_BC_BASE_MAX: ::c_int = 2; +pub const USER_BC_DIM_MAX: ::c_int = 3; +pub const USER_BC_SCALE_MAX: ::c_int = 4; +pub const USER_BC_STRING_MAX: ::c_int = 5; +pub const USER_COLL_WEIGHTS_MAX: ::c_int = 6; +pub const USER_EXPR_NEST_MAX: ::c_int = 7; +pub const USER_LINE_MAX: ::c_int = 8; +pub const USER_RE_DUP_MAX: ::c_int = 9; +pub const USER_POSIX2_VERSION: ::c_int = 10; +pub const USER_POSIX2_C_BIND: ::c_int = 11; +pub const USER_POSIX2_C_DEV: ::c_int = 12; +pub const USER_POSIX2_CHAR_TERM: ::c_int = 13; +pub const USER_POSIX2_FORT_DEV: ::c_int = 14; +pub const USER_POSIX2_FORT_RUN: ::c_int = 15; +pub const USER_POSIX2_LOCALEDEF: ::c_int = 16; +pub const USER_POSIX2_SW_DEV: ::c_int = 17; +pub const USER_POSIX2_UPE: ::c_int = 18; +pub const USER_STREAM_MAX: ::c_int = 19; +pub const USER_TZNAME_MAX: ::c_int = 20; +pub const USER_MAXID: ::c_int = 21; +pub const CTL_P1003_1B_ASYNCHRONOUS_IO: ::c_int = 1; +pub const CTL_P1003_1B_MAPPED_FILES: ::c_int = 2; +pub const CTL_P1003_1B_MEMLOCK: ::c_int = 3; +pub const CTL_P1003_1B_MEMLOCK_RANGE: ::c_int = 4; +pub const CTL_P1003_1B_MEMORY_PROTECTION: ::c_int = 5; +pub const CTL_P1003_1B_MESSAGE_PASSING: ::c_int = 6; +pub const CTL_P1003_1B_PRIORITIZED_IO: ::c_int = 7; +pub const CTL_P1003_1B_PRIORITY_SCHEDULING: ::c_int = 8; +pub const CTL_P1003_1B_REALTIME_SIGNALS: ::c_int = 9; +pub const CTL_P1003_1B_SEMAPHORES: ::c_int = 10; +pub const CTL_P1003_1B_FSYNC: ::c_int = 11; +pub const CTL_P1003_1B_SHARED_MEMORY_OBJECTS: ::c_int = 12; +pub const CTL_P1003_1B_SYNCHRONIZED_IO: ::c_int = 13; +pub const CTL_P1003_1B_TIMERS: ::c_int = 14; +pub const CTL_P1003_1B_AIO_LISTIO_MAX: ::c_int = 15; +pub const CTL_P1003_1B_AIO_MAX: ::c_int = 16; +pub const CTL_P1003_1B_AIO_PRIO_DELTA_MAX: ::c_int = 17; +pub const CTL_P1003_1B_DELAYTIMER_MAX: ::c_int = 18; +pub const CTL_P1003_1B_UNUSED1: ::c_int = 19; +pub const CTL_P1003_1B_PAGESIZE: ::c_int = 20; +pub const CTL_P1003_1B_RTSIG_MAX: ::c_int = 21; +pub const CTL_P1003_1B_SEM_NSEMS_MAX: ::c_int = 22; +pub const CTL_P1003_1B_SEM_VALUE_MAX: ::c_int = 23; +pub const CTL_P1003_1B_SIGQUEUE_MAX: ::c_int = 24; +pub const CTL_P1003_1B_TIMER_MAX: ::c_int = 25; +pub const CTL_P1003_1B_MAXID: ::c_int = 26; + +pub const EVFILT_READ: ::int16_t = -1; +pub const EVFILT_WRITE: ::int16_t = -2; +pub const EVFILT_AIO: ::int16_t = -3; +pub const EVFILT_VNODE: ::int16_t = -4; +pub const EVFILT_PROC: ::int16_t = -5; +pub const EVFILT_SIGNAL: ::int16_t = -6; +pub const EVFILT_TIMER: ::int16_t = -7; +pub const EVFILT_EXCEPT: ::int16_t = -8; +pub const EVFILT_USER: ::int16_t = -9; +pub const EVFILT_FS: ::int16_t = -10; + +pub const EV_ADD: ::uint16_t = 0x1; +pub const EV_DELETE: ::uint16_t = 0x2; +pub const EV_ENABLE: ::uint16_t = 0x4; +pub const EV_DISABLE: ::uint16_t = 0x8; +pub const EV_ONESHOT: ::uint16_t = 0x10; +pub const EV_CLEAR: ::uint16_t = 0x20; +pub const EV_RECEIPT: ::uint16_t = 0x40; +pub const EV_DISPATCH: ::uint16_t = 0x80; +pub const EV_NODATA: ::uint16_t = 0x1000; +pub const EV_FLAG1: ::uint16_t = 0x2000; +pub const EV_ERROR: ::uint16_t = 0x4000; +pub const EV_EOF: ::uint16_t = 0x8000; +pub const EV_SYSFLAGS: ::uint16_t = 0xf000; + +pub const NOTE_TRIGGER: ::uint32_t = 0x01000000; +pub const NOTE_FFNOP: ::uint32_t = 0x00000000; +pub const NOTE_FFAND: ::uint32_t = 0x40000000; +pub const NOTE_FFOR: ::uint32_t = 0x80000000; +pub const NOTE_FFCOPY: ::uint32_t = 0xc0000000; +pub const NOTE_FFCTRLMASK: ::uint32_t = 0xc0000000; +pub const NOTE_FFLAGSMASK: ::uint32_t = 0x00ffffff; +pub const NOTE_LOWAT: ::uint32_t = 0x00000001; +pub const NOTE_OOB: ::uint32_t = 0x00000002; +pub const NOTE_DELETE: ::uint32_t = 0x00000001; +pub const NOTE_WRITE: ::uint32_t = 0x00000002; +pub const NOTE_EXTEND: ::uint32_t = 0x00000004; +pub const NOTE_ATTRIB: ::uint32_t = 0x00000008; +pub const NOTE_LINK: ::uint32_t = 0x00000010; +pub const NOTE_RENAME: ::uint32_t = 0x00000020; +pub const NOTE_REVOKE: ::uint32_t = 0x00000040; +pub const NOTE_EXIT: ::uint32_t = 0x80000000; +pub const NOTE_FORK: ::uint32_t = 0x40000000; +pub const NOTE_EXEC: ::uint32_t = 0x20000000; +pub const NOTE_PDATAMASK: ::uint32_t = 0x000fffff; +pub const NOTE_PCTRLMASK: ::uint32_t = 0xf0000000; +pub const NOTE_TRACK: ::uint32_t = 0x00000001; +pub const NOTE_TRACKERR: ::uint32_t = 0x00000002; +pub const NOTE_CHILD: ::uint32_t = 0x00000004; + +pub const SO_SNDSPACE: ::c_int = 0x100a; +pub const SO_CPUHINT: ::c_int = 0x1030; + +// https://github.com/DragonFlyBSD/DragonFlyBSD/blob/master/sys/net/if.h#L101 +pub const IFF_UP: ::c_int = 0x1; // interface is up +pub const IFF_BROADCAST: ::c_int = 0x2; // broadcast address valid +pub const IFF_DEBUG: ::c_int = 0x4; // turn on debugging +pub const IFF_LOOPBACK: ::c_int = 0x8; // is a loopback net +pub const IFF_POINTOPOINT: ::c_int = 0x10; // interface is point-to-point link +pub const IFF_SMART: ::c_int = 0x20; // interface manages own routes +pub const IFF_RUNNING: ::c_int = 0x40; // resources allocated +pub const IFF_NOARP: ::c_int = 0x80; // no address resolution protocol +pub const IFF_PROMISC: ::c_int = 0x100; // receive all packets +pub const IFF_ALLMULTI: ::c_int = 0x200; // receive all multicast packets +pub const IFF_OACTIVE_COMPAT: ::c_int = 0x400; // was transmission in progress +pub const IFF_SIMPLEX: ::c_int = 0x800; // can't hear own transmissions +pub const IFF_LINK0: ::c_int = 0x1000; // per link layer defined bit +pub const IFF_LINK1: ::c_int = 0x2000; // per link layer defined bit +pub const IFF_LINK2: ::c_int = 0x4000; // per link layer defined bit +pub const IFF_ALTPHYS: ::c_int = IFF_LINK2; // use alternate physical connection +pub const IFF_MULTICAST: ::c_int = 0x8000; // supports multicast +// was interface is in polling mode +pub const IFF_POLLING_COMPAT: ::c_int = 0x10000; +pub const IFF_PPROMISC: ::c_int = 0x20000; // user-requested promisc mode +pub const IFF_MONITOR: ::c_int = 0x40000; // user-requested monitor mode +pub const IFF_STATICARP: ::c_int = 0x80000; // static ARP +pub const IFF_NPOLLING: ::c_int = 0x100000; // interface is in polling mode +pub const IFF_IDIRECT: ::c_int = 0x200000; // direct input + +// +// sys/netinet/in.h +// Protocols (RFC 1700) +// NOTE: These are in addition to the constants defined in src/unix/mod.rs + +// IPPROTO_IP defined in src/unix/mod.rs +/// IP6 hop-by-hop options +pub const IPPROTO_HOPOPTS: ::c_int = 0; +// IPPROTO_ICMP defined in src/unix/mod.rs +/// group mgmt protocol +pub const IPPROTO_IGMP: ::c_int = 2; +/// gateway^2 (deprecated) +pub const IPPROTO_GGP: ::c_int = 3; +/// for compatibility +pub const IPPROTO_IPIP: ::c_int = 4; +// IPPROTO_TCP defined in src/unix/mod.rs +/// Stream protocol II. +pub const IPPROTO_ST: ::c_int = 7; +/// exterior gateway protocol +pub const IPPROTO_EGP: ::c_int = 8; +/// private interior gateway +pub const IPPROTO_PIGP: ::c_int = 9; +/// BBN RCC Monitoring +pub const IPPROTO_RCCMON: ::c_int = 10; +/// network voice protocol +pub const IPPROTO_NVPII: ::c_int = 11; +/// pup +pub const IPPROTO_PUP: ::c_int = 12; +/// Argus +pub const IPPROTO_ARGUS: ::c_int = 13; +/// EMCON +pub const IPPROTO_EMCON: ::c_int = 14; +/// Cross Net Debugger +pub const IPPROTO_XNET: ::c_int = 15; +/// Chaos +pub const IPPROTO_CHAOS: ::c_int = 16; +// IPPROTO_UDP defined in src/unix/mod.rs +/// Multiplexing +pub const IPPROTO_MUX: ::c_int = 18; +/// DCN Measurement Subsystems +pub const IPPROTO_MEAS: ::c_int = 19; +/// Host Monitoring +pub const IPPROTO_HMP: ::c_int = 20; +/// Packet Radio Measurement +pub const IPPROTO_PRM: ::c_int = 21; +/// xns idp +pub const IPPROTO_IDP: ::c_int = 22; +/// Trunk-1 +pub const IPPROTO_TRUNK1: ::c_int = 23; +/// Trunk-2 +pub const IPPROTO_TRUNK2: ::c_int = 24; +/// Leaf-1 +pub const IPPROTO_LEAF1: ::c_int = 25; +/// Leaf-2 +pub const IPPROTO_LEAF2: ::c_int = 26; +/// Reliable Data +pub const IPPROTO_RDP: ::c_int = 27; +/// Reliable Transaction +pub const IPPROTO_IRTP: ::c_int = 28; +/// tp-4 w/ class negotiation +pub const IPPROTO_TP: ::c_int = 29; +/// Bulk Data Transfer +pub const IPPROTO_BLT: ::c_int = 30; +/// Network Services +pub const IPPROTO_NSP: ::c_int = 31; +/// Merit Internodal +pub const IPPROTO_INP: ::c_int = 32; +/// Sequential Exchange +pub const IPPROTO_SEP: ::c_int = 33; +/// Third Party Connect +pub const IPPROTO_3PC: ::c_int = 34; +/// InterDomain Policy Routing +pub const IPPROTO_IDPR: ::c_int = 35; +/// XTP +pub const IPPROTO_XTP: ::c_int = 36; +/// Datagram Delivery +pub const IPPROTO_DDP: ::c_int = 37; +/// Control Message Transport +pub const IPPROTO_CMTP: ::c_int = 38; +/// TP++ Transport +pub const IPPROTO_TPXX: ::c_int = 39; +/// IL transport protocol +pub const IPPROTO_IL: ::c_int = 40; +// IPPROTO_IPV6 defined in src/unix/mod.rs +/// Source Demand Routing +pub const IPPROTO_SDRP: ::c_int = 42; +/// IP6 routing header +pub const IPPROTO_ROUTING: ::c_int = 43; +/// IP6 fragmentation header +pub const IPPROTO_FRAGMENT: ::c_int = 44; +/// InterDomain Routing +pub const IPPROTO_IDRP: ::c_int = 45; +/// resource reservation +pub const IPPROTO_RSVP: ::c_int = 46; +/// General Routing Encap. +pub const IPPROTO_GRE: ::c_int = 47; +/// Mobile Host Routing +pub const IPPROTO_MHRP: ::c_int = 48; +/// BHA +pub const IPPROTO_BHA: ::c_int = 49; +/// IP6 Encap Sec. Payload +pub const IPPROTO_ESP: ::c_int = 50; +/// IP6 Auth Header +pub const IPPROTO_AH: ::c_int = 51; +/// Integ. Net Layer Security +pub const IPPROTO_INLSP: ::c_int = 52; +/// IP with encryption +pub const IPPROTO_SWIPE: ::c_int = 53; +/// Next Hop Resolution +pub const IPPROTO_NHRP: ::c_int = 54; +/// IP Mobility +pub const IPPROTO_MOBILE: ::c_int = 55; +/// Transport Layer Security +pub const IPPROTO_TLSP: ::c_int = 56; +/// SKIP +pub const IPPROTO_SKIP: ::c_int = 57; +// IPPROTO_ICMPV6 defined in src/unix/mod.rs +/// IP6 no next header +pub const IPPROTO_NONE: ::c_int = 59; +/// IP6 destination option +pub const IPPROTO_DSTOPTS: ::c_int = 60; +/// any host internal protocol +pub const IPPROTO_AHIP: ::c_int = 61; +/// CFTP +pub const IPPROTO_CFTP: ::c_int = 62; +/// "hello" routing protocol +pub const IPPROTO_HELLO: ::c_int = 63; +/// SATNET/Backroom EXPAK +pub const IPPROTO_SATEXPAK: ::c_int = 64; +/// Kryptolan +pub const IPPROTO_KRYPTOLAN: ::c_int = 65; +/// Remote Virtual Disk +pub const IPPROTO_RVD: ::c_int = 66; +/// Pluribus Packet Core +pub const IPPROTO_IPPC: ::c_int = 67; +/// Any distributed FS +pub const IPPROTO_ADFS: ::c_int = 68; +/// Satnet Monitoring +pub const IPPROTO_SATMON: ::c_int = 69; +/// VISA Protocol +pub const IPPROTO_VISA: ::c_int = 70; +/// Packet Core Utility +pub const IPPROTO_IPCV: ::c_int = 71; +/// Comp. Prot. Net. Executive +pub const IPPROTO_CPNX: ::c_int = 72; +/// Comp. Prot. HeartBeat +pub const IPPROTO_CPHB: ::c_int = 73; +/// Wang Span Network +pub const IPPROTO_WSN: ::c_int = 74; +/// Packet Video Protocol +pub const IPPROTO_PVP: ::c_int = 75; +/// BackRoom SATNET Monitoring +pub const IPPROTO_BRSATMON: ::c_int = 76; +/// Sun net disk proto (temp.) +pub const IPPROTO_ND: ::c_int = 77; +/// WIDEBAND Monitoring +pub const IPPROTO_WBMON: ::c_int = 78; +/// WIDEBAND EXPAK +pub const IPPROTO_WBEXPAK: ::c_int = 79; +/// ISO cnlp +pub const IPPROTO_EON: ::c_int = 80; +/// VMTP +pub const IPPROTO_VMTP: ::c_int = 81; +/// Secure VMTP +pub const IPPROTO_SVMTP: ::c_int = 82; +/// Banyon VINES +pub const IPPROTO_VINES: ::c_int = 83; +/// TTP +pub const IPPROTO_TTP: ::c_int = 84; +/// NSFNET-IGP +pub const IPPROTO_IGP: ::c_int = 85; +/// dissimilar gateway prot. +pub const IPPROTO_DGP: ::c_int = 86; +/// TCF +pub const IPPROTO_TCF: ::c_int = 87; +/// Cisco/GXS IGRP +pub const IPPROTO_IGRP: ::c_int = 88; +/// OSPFIGP +pub const IPPROTO_OSPFIGP: ::c_int = 89; +/// Strite RPC protocol +pub const IPPROTO_SRPC: ::c_int = 90; +/// Locus Address Resoloution +pub const IPPROTO_LARP: ::c_int = 91; +/// Multicast Transport +pub const IPPROTO_MTP: ::c_int = 92; +/// AX.25 Frames +pub const IPPROTO_AX25: ::c_int = 93; +/// IP encapsulated in IP +pub const IPPROTO_IPEIP: ::c_int = 94; +/// Mobile Int.ing control +pub const IPPROTO_MICP: ::c_int = 95; +/// Semaphore Comm. security +pub const IPPROTO_SCCSP: ::c_int = 96; +/// Ethernet IP encapsulation +pub const IPPROTO_ETHERIP: ::c_int = 97; +/// encapsulation header +pub const IPPROTO_ENCAP: ::c_int = 98; +/// any private encr. scheme +pub const IPPROTO_APES: ::c_int = 99; +/// GMTP +pub const IPPROTO_GMTP: ::c_int = 100; +/// payload compression (IPComp) +pub const IPPROTO_IPCOMP: ::c_int = 108; + +/* 101-254: Partly Unassigned */ +/// Protocol Independent Mcast +pub const IPPROTO_PIM: ::c_int = 103; +/// CARP +pub const IPPROTO_CARP: ::c_int = 112; +/// PGM +pub const IPPROTO_PGM: ::c_int = 113; +/// PFSYNC +pub const IPPROTO_PFSYNC: ::c_int = 240; + +/* 255: Reserved */ +/* BSD Private, local use, namespace incursion, no longer used */ +/// divert pseudo-protocol +pub const IPPROTO_DIVERT: ::c_int = 254; +pub const IPPROTO_MAX: ::c_int = 256; +/// last return value of *_input(), meaning "all job for this pkt is done". +pub const IPPROTO_DONE: ::c_int = 257; + +/// Used by RSS: the layer3 protocol is unknown +pub const IPPROTO_UNKNOWN: ::c_int = 258; + +pub const AF_BLUETOOTH: ::c_int = 33; +pub const AF_MPLS: ::c_int = 34; +pub const AF_IEEE80211: ::c_int = 35; +pub const AF_MAX: ::c_int = 36; + +pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; +pub const PF_MAX: ::c_int = AF_MAX; + +pub const NET_RT_DUMP: ::c_int = 1; +pub const NET_RT_FLAGS: ::c_int = 2; +pub const NET_RT_IFLIST: ::c_int = 3; +pub const NET_RT_MAXID: ::c_int = 4; + +pub const SOMAXOPT_SIZE: ::c_int = 65536; + +#[doc(hidden)] +pub const NET_MAXID: ::c_int = AF_MAX; + +pub const MSG_UNUSED09: ::c_int = 0x00000200; +pub const MSG_NOSIGNAL: ::c_int = 0x00000400; +pub const MSG_SYNC: ::c_int = 0x00000800; +pub const MSG_CMSG_CLOEXEC: ::c_int = 0x00001000; +pub const MSG_FBLOCKING: ::c_int = 0x00010000; +pub const MSG_FNONBLOCKING: ::c_int = 0x00020000; +pub const MSG_FMASK: ::c_int = 0xFFFF0000; + +pub const EMPTY: ::c_short = 0; +pub const RUN_LVL: ::c_short = 1; +pub const BOOT_TIME: ::c_short = 2; +pub const OLD_TIME: ::c_short = 3; +pub const NEW_TIME: ::c_short = 4; +pub const INIT_PROCESS: ::c_short = 5; +pub const LOGIN_PROCESS: ::c_short = 6; +pub const USER_PROCESS: ::c_short = 7; +pub const DEAD_PROCESS: ::c_short = 8; + +pub const LC_COLLATE_MASK: ::c_int = (1 << 0); +pub const LC_CTYPE_MASK: ::c_int = (1 << 1); +pub const LC_MONETARY_MASK: ::c_int = (1 << 2); +pub const LC_NUMERIC_MASK: ::c_int = (1 << 3); +pub const LC_TIME_MASK: ::c_int = (1 << 4); +pub const LC_MESSAGES_MASK: ::c_int = (1 << 5); +pub const LC_ALL_MASK: ::c_int = LC_COLLATE_MASK + | LC_CTYPE_MASK + | LC_MESSAGES_MASK + | LC_MONETARY_MASK + | LC_NUMERIC_MASK + | LC_TIME_MASK; + +pub const TIOCSIG: ::c_uint = 0x2000745f; +pub const BTUARTDISC: ::c_int = 0x7; +pub const TIOCDCDTIMESTAMP: ::c_uint = 0x40107458; +pub const TIOCISPTMASTER: ::c_uint = 0x20007455; +pub const TIOCMODG: ::c_uint = 0x40047403; +pub const TIOCMODS: ::c_ulong = 0x80047404; +pub const TIOCREMOTE: ::c_ulong = 0x80047469; + +// Constants used by "at" family of system calls. +pub const AT_FDCWD: ::c_int = 0xFFFAFDCD; // invalid file descriptor +pub const AT_SYMLINK_NOFOLLOW: ::c_int = 1; +pub const AT_REMOVEDIR: ::c_int = 2; +pub const AT_EACCESS: ::c_int = 4; +pub const AT_SYMLINK_FOLLOW: ::c_int = 8; + +pub const VCHECKPT: usize = 19; + +pub const _PC_2_SYMLINKS: ::c_int = 22; +pub const _PC_TIMESTAMP_RESOLUTION: ::c_int = 23; + +pub const _SC_V7_ILP32_OFF32: ::c_int = 122; +pub const _SC_V7_ILP32_OFFBIG: ::c_int = 123; +pub const _SC_V7_LP64_OFF64: ::c_int = 124; +pub const _SC_V7_LPBIG_OFFBIG: ::c_int = 125; +pub const _SC_THREAD_ROBUST_PRIO_INHERIT: ::c_int = 126; +pub const _SC_THREAD_ROBUST_PRIO_PROTECT: ::c_int = 127; + +pub const WCONTINUED: ::c_int = 4; +pub const WSTOPPED: ::c_int = 0o177; + +// Values for struct rtprio (type_ field) +pub const RTP_PRIO_REALTIME: ::c_ushort = 0; +pub const RTP_PRIO_NORMAL: ::c_ushort = 1; +pub const RTP_PRIO_IDLE: ::c_ushort = 2; +pub const RTP_PRIO_THREAD: ::c_ushort = 3; + +extern { + pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) + -> ::c_int; + pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; + + pub fn setutxdb(_type: ::c_uint, file: *mut ::c_char) -> ::c_int; + + pub fn aio_waitcomplete(iocbp: *mut *mut aiocb, + timeout: *mut ::timespec) -> ::c_int; + + pub fn freelocale(loc: ::locale_t); + + pub fn lwp_rtprio(function: ::c_int, pid: ::pid_t, lwpid: lwpid_t, + rtp: *mut super::rtprio) -> ::c_int; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/aarch64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/aarch64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,32 @@ +pub type c_long = i64; +pub type c_ulong = u64; +pub type time_t = i64; +pub type suseconds_t = i64; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_size: ::off_t, + pub st_blocks: ::blkcnt_t, + pub st_blksize: ::blksize_t, + pub st_flags: ::fflags_t, + pub st_gen: ::uint32_t, + pub st_lspare: ::int32_t, + pub st_birthtime: ::time_t, + pub st_birthtime_nsec: ::c_long, + } +} + +pub const MAP_32BIT: ::c_int = 0x00080000; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1010 @@ +pub type fflags_t = u32; +pub type clock_t = i32; +pub type ino_t = u32; +pub type lwpid_t = i32; +pub type nlink_t = u16; +pub type blksize_t = i32; +pub type clockid_t = ::c_int; +pub type sem_t = _sem; + +pub type fsblkcnt_t = ::uint64_t; +pub type fsfilcnt_t = ::uint64_t; +pub type idtype_t = ::c_uint; + +pub type key_t = ::c_long; +pub type msglen_t = ::c_ulong; +pub type msgqnum_t = ::c_ulong; + +pub type posix_spawnattr_t = *mut ::c_void; +pub type posix_spawn_file_actions_t = *mut ::c_void; + +s! { + pub struct utmpx { + pub ut_type: ::c_short, + pub ut_tv: ::timeval, + pub ut_id: [::c_char; 8], + pub ut_pid: ::pid_t, + pub ut_user: [::c_char; 32], + pub ut_line: [::c_char; 16], + pub ut_host: [::c_char; 128], + pub __ut_spare: [::c_char; 64], + } + + pub struct aiocb { + pub aio_fildes: ::c_int, + pub aio_offset: ::off_t, + pub aio_buf: *mut ::c_void, + pub aio_nbytes: ::size_t, + __unused1: [::c_int; 2], + __unused2: *mut ::c_void, + pub aio_lio_opcode: ::c_int, + pub aio_reqprio: ::c_int, + // unused 3 through 5 are the __aiocb_private structure + __unused3: ::c_long, + __unused4: ::c_long, + __unused5: *mut ::c_void, + pub aio_sigevent: sigevent + } + + pub struct dirent { + pub d_fileno: u32, + pub d_reclen: u16, + pub d_type: u8, + pub d_namlen: u8, + pub d_name: [::c_char; 256], + } + + pub struct jail { + pub version: u32, + pub path: *mut ::c_char, + pub hostname: *mut ::c_char, + pub jailname: *mut ::c_char, + pub ip4s: ::c_uint, + pub ip6s: ::c_uint, + pub ip4: *mut ::in_addr, + pub ip6: *mut ::in6_addr, + } + + pub struct mq_attr { + pub mq_flags: ::c_long, + pub mq_maxmsg: ::c_long, + pub mq_msgsize: ::c_long, + pub mq_curmsgs: ::c_long, + __reserved: [::c_long; 4] + } + + pub struct sigevent { + pub sigev_notify: ::c_int, + pub sigev_signo: ::c_int, + pub sigev_value: ::sigval, + //The rest of the structure is actually a union. We expose only + //sigev_notify_thread_id because it's the most useful union member. + pub sigev_notify_thread_id: ::lwpid_t, + #[cfg(target_pointer_width = "64")] + __unused1: ::c_int, + __unused2: [::c_long; 7] + } + + pub struct statvfs { + pub f_bavail: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_blocks: ::fsblkcnt_t, + pub f_favail: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_bsize: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_fsid: ::c_ulong, + pub f_namemax: ::c_ulong, + } + + // internal structure has changed over time + pub struct _sem { + data: [u32; 4], + } + + pub struct ipc_perm { + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub mode: ::mode_t, + pub seq: ::c_ushort, + pub key: ::key_t, + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + __unused1: *mut ::c_void, + __unused2: *mut ::c_void, + pub msg_cbytes: ::msglen_t, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + pub msg_stime: ::time_t, + pub msg_rtime: ::time_t, + pub msg_ctime: ::time_t, + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_lpid: ::pid_t, + pub shm_cpid: ::pid_t, + pub shm_nattch: ::c_int, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + } + + pub struct xucred { + pub cr_version: ::c_uint, + pub cr_uid: ::uid_t, + pub cr_ngroups: ::c_short, + pub cr_groups: [::gid_t;16], + __cr_unused1: *mut ::c_void, + } + + pub struct sockaddr_dl { + pub sdl_len: ::c_uchar, + pub sdl_family: ::c_uchar, + pub sdl_index: ::c_ushort, + pub sdl_type: ::c_uchar, + pub sdl_nlen: ::c_uchar, + pub sdl_alen: ::c_uchar, + pub sdl_slen: ::c_uchar, + pub sdl_data: [::c_char; 46], + } +} + +pub const SIGEV_THREAD_ID: ::c_int = 4; + +pub const RAND_MAX: ::c_int = 0x7fff_fffd; +pub const PTHREAD_STACK_MIN: ::size_t = 2048; +pub const PTHREAD_MUTEX_ADAPTIVE_NP: ::c_int = 4; +pub const SIGSTKSZ: ::size_t = 34816; +pub const SF_NODISKIO: ::c_int = 0x00000001; +pub const SF_MNOWAIT: ::c_int = 0x00000002; +pub const SF_SYNC: ::c_int = 0x00000004; +pub const O_CLOEXEC: ::c_int = 0x00100000; +pub const O_DIRECTORY: ::c_int = 0x00020000; +pub const O_EXEC: ::c_int = 0x00040000; +pub const O_TTY_INIT: ::c_int = 0x00080000; +pub const F_GETLK: ::c_int = 11; +pub const F_SETLK: ::c_int = 12; +pub const F_SETLKW: ::c_int = 13; +pub const ENOTCAPABLE: ::c_int = 93; +pub const ECAPMODE: ::c_int = 94; +pub const ENOTRECOVERABLE: ::c_int = 95; +pub const EOWNERDEAD: ::c_int = 96; +pub const ELAST: ::c_int = 96; +pub const RLIMIT_NPTS: ::c_int = 11; +pub const RLIMIT_SWAP: ::c_int = 12; +pub const RLIMIT_KQUEUES: ::c_int = 13; +pub const RLIMIT_UMTXP: ::c_int = 14; +pub const RLIM_NLIMITS: ::rlim_t = 15; + +pub const Q_GETQUOTA: ::c_int = 0x700; +pub const Q_SETQUOTA: ::c_int = 0x800; + +pub const POSIX_FADV_NORMAL: ::c_int = 0; +pub const POSIX_FADV_RANDOM: ::c_int = 1; +pub const POSIX_FADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_FADV_WILLNEED: ::c_int = 3; +pub const POSIX_FADV_DONTNEED: ::c_int = 4; +pub const POSIX_FADV_NOREUSE: ::c_int = 5; + +pub const POLLINIGNEOF: ::c_short = 0x2000; + +pub const EVFILT_READ: ::int16_t = -1; +pub const EVFILT_WRITE: ::int16_t = -2; +pub const EVFILT_AIO: ::int16_t = -3; +pub const EVFILT_VNODE: ::int16_t = -4; +pub const EVFILT_PROC: ::int16_t = -5; +pub const EVFILT_SIGNAL: ::int16_t = -6; +pub const EVFILT_TIMER: ::int16_t = -7; +pub const EVFILT_PROCDESC: ::int16_t = -8; +pub const EVFILT_FS: ::int16_t = -9; +pub const EVFILT_LIO: ::int16_t = -10; +pub const EVFILT_USER: ::int16_t = -11; +pub const EVFILT_SENDFILE: ::int16_t = -12; +pub const EVFILT_EMPTY: ::int16_t = -13; + +pub const EV_ADD: ::uint16_t = 0x1; +pub const EV_DELETE: ::uint16_t = 0x2; +pub const EV_ENABLE: ::uint16_t = 0x4; +pub const EV_DISABLE: ::uint16_t = 0x8; +pub const EV_ONESHOT: ::uint16_t = 0x10; +pub const EV_CLEAR: ::uint16_t = 0x20; +pub const EV_RECEIPT: ::uint16_t = 0x40; +pub const EV_DISPATCH: ::uint16_t = 0x80; +pub const EV_DROP: ::uint16_t = 0x1000; +pub const EV_FLAG1: ::uint16_t = 0x2000; +pub const EV_ERROR: ::uint16_t = 0x4000; +pub const EV_EOF: ::uint16_t = 0x8000; +pub const EV_SYSFLAGS: ::uint16_t = 0xf000; + +pub const NOTE_TRIGGER: ::uint32_t = 0x01000000; +pub const NOTE_FFNOP: ::uint32_t = 0x00000000; +pub const NOTE_FFAND: ::uint32_t = 0x40000000; +pub const NOTE_FFOR: ::uint32_t = 0x80000000; +pub const NOTE_FFCOPY: ::uint32_t = 0xc0000000; +pub const NOTE_FFCTRLMASK: ::uint32_t = 0xc0000000; +pub const NOTE_FFLAGSMASK: ::uint32_t = 0x00ffffff; +pub const NOTE_LOWAT: ::uint32_t = 0x00000001; +pub const NOTE_DELETE: ::uint32_t = 0x00000001; +pub const NOTE_WRITE: ::uint32_t = 0x00000002; +pub const NOTE_EXTEND: ::uint32_t = 0x00000004; +pub const NOTE_ATTRIB: ::uint32_t = 0x00000008; +pub const NOTE_LINK: ::uint32_t = 0x00000010; +pub const NOTE_RENAME: ::uint32_t = 0x00000020; +pub const NOTE_REVOKE: ::uint32_t = 0x00000040; +pub const NOTE_EXIT: ::uint32_t = 0x80000000; +pub const NOTE_FORK: ::uint32_t = 0x40000000; +pub const NOTE_EXEC: ::uint32_t = 0x20000000; +pub const NOTE_PDATAMASK: ::uint32_t = 0x000fffff; +pub const NOTE_PCTRLMASK: ::uint32_t = 0xf0000000; +pub const NOTE_TRACK: ::uint32_t = 0x00000001; +pub const NOTE_TRACKERR: ::uint32_t = 0x00000002; +pub const NOTE_CHILD: ::uint32_t = 0x00000004; +pub const NOTE_SECONDS: ::uint32_t = 0x00000001; +pub const NOTE_MSECONDS: ::uint32_t = 0x00000002; +pub const NOTE_USECONDS: ::uint32_t = 0x00000004; +pub const NOTE_NSECONDS: ::uint32_t = 0x00000008; + +pub const MADV_PROTECT: ::c_int = 10; +pub const RUSAGE_THREAD: ::c_int = 1; + +pub const CLOCK_REALTIME: ::clockid_t = 0; +pub const CLOCK_VIRTUAL: ::clockid_t = 1; +pub const CLOCK_PROF: ::clockid_t = 2; +pub const CLOCK_MONOTONIC: ::clockid_t = 4; +pub const CLOCK_UPTIME: ::clockid_t = 5; +pub const CLOCK_UPTIME_PRECISE: ::clockid_t = 7; +pub const CLOCK_UPTIME_FAST: ::clockid_t = 8; +pub const CLOCK_REALTIME_PRECISE: ::clockid_t = 9; +pub const CLOCK_REALTIME_FAST: ::clockid_t = 10; +pub const CLOCK_MONOTONIC_PRECISE: ::clockid_t = 11; +pub const CLOCK_MONOTONIC_FAST: ::clockid_t = 12; +pub const CLOCK_SECOND: ::clockid_t = 13; +pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 14; +pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 15; + +pub const CTL_UNSPEC: ::c_int = 0; +pub const CTL_KERN: ::c_int = 1; +pub const CTL_VM: ::c_int = 2; +pub const CTL_VFS: ::c_int = 3; +pub const CTL_NET: ::c_int = 4; +pub const CTL_DEBUG: ::c_int = 5; +pub const CTL_HW: ::c_int = 6; +pub const CTL_MACHDEP: ::c_int = 7; +pub const CTL_USER: ::c_int = 8; +pub const CTL_P1003_1B: ::c_int = 9; +pub const KERN_OSTYPE: ::c_int = 1; +pub const KERN_OSRELEASE: ::c_int = 2; +pub const KERN_OSREV: ::c_int = 3; +pub const KERN_VERSION: ::c_int = 4; +pub const KERN_MAXVNODES: ::c_int = 5; +pub const KERN_MAXPROC: ::c_int = 6; +pub const KERN_MAXFILES: ::c_int = 7; +pub const KERN_ARGMAX: ::c_int = 8; +pub const KERN_SECURELVL: ::c_int = 9; +pub const KERN_HOSTNAME: ::c_int = 10; +pub const KERN_HOSTID: ::c_int = 11; +pub const KERN_CLOCKRATE: ::c_int = 12; +pub const KERN_VNODE: ::c_int = 13; +pub const KERN_PROC: ::c_int = 14; +pub const KERN_FILE: ::c_int = 15; +pub const KERN_PROF: ::c_int = 16; +pub const KERN_POSIX1: ::c_int = 17; +pub const KERN_NGROUPS: ::c_int = 18; +pub const KERN_JOB_CONTROL: ::c_int = 19; +pub const KERN_SAVED_IDS: ::c_int = 20; +pub const KERN_BOOTTIME: ::c_int = 21; +pub const KERN_NISDOMAINNAME: ::c_int = 22; +pub const KERN_UPDATEINTERVAL: ::c_int = 23; +pub const KERN_OSRELDATE: ::c_int = 24; +pub const KERN_NTP_PLL: ::c_int = 25; +pub const KERN_BOOTFILE: ::c_int = 26; +pub const KERN_MAXFILESPERPROC: ::c_int = 27; +pub const KERN_MAXPROCPERUID: ::c_int = 28; +pub const KERN_DUMPDEV: ::c_int = 29; +pub const KERN_IPC: ::c_int = 30; +pub const KERN_DUMMY: ::c_int = 31; +pub const KERN_PS_STRINGS: ::c_int = 32; +pub const KERN_USRSTACK: ::c_int = 33; +pub const KERN_LOGSIGEXIT: ::c_int = 34; +pub const KERN_IOV_MAX: ::c_int = 35; +pub const KERN_HOSTUUID: ::c_int = 36; +pub const KERN_ARND: ::c_int = 37; +pub const KERN_PROC_ALL: ::c_int = 0; +pub const KERN_PROC_PID: ::c_int = 1; +pub const KERN_PROC_PGRP: ::c_int = 2; +pub const KERN_PROC_SESSION: ::c_int = 3; +pub const KERN_PROC_TTY: ::c_int = 4; +pub const KERN_PROC_UID: ::c_int = 5; +pub const KERN_PROC_RUID: ::c_int = 6; +pub const KERN_PROC_ARGS: ::c_int = 7; +pub const KERN_PROC_PROC: ::c_int = 8; +pub const KERN_PROC_SV_NAME: ::c_int = 9; +pub const KERN_PROC_RGID: ::c_int = 10; +pub const KERN_PROC_GID: ::c_int = 11; +pub const KERN_PROC_PATHNAME: ::c_int = 12; +pub const KERN_PROC_OVMMAP: ::c_int = 13; +pub const KERN_PROC_OFILEDESC: ::c_int = 14; +pub const KERN_PROC_KSTACK: ::c_int = 15; +pub const KERN_PROC_INC_THREAD: ::c_int = 0x10; +pub const KERN_PROC_VMMAP: ::c_int = 32; +pub const KERN_PROC_FILEDESC: ::c_int = 33; +pub const KERN_PROC_GROUPS: ::c_int = 34; +pub const KERN_PROC_ENV: ::c_int = 35; +pub const KERN_PROC_AUXV: ::c_int = 36; +pub const KERN_PROC_RLIMIT: ::c_int = 37; +pub const KERN_PROC_PS_STRINGS: ::c_int = 38; +pub const KERN_PROC_UMASK: ::c_int = 39; +pub const KERN_PROC_OSREL: ::c_int = 40; +pub const KERN_PROC_SIGTRAMP: ::c_int = 41; +pub const KIPC_MAXSOCKBUF: ::c_int = 1; +pub const KIPC_SOCKBUF_WASTE: ::c_int = 2; +pub const KIPC_SOMAXCONN: ::c_int = 3; +pub const KIPC_MAX_LINKHDR: ::c_int = 4; +pub const KIPC_MAX_PROTOHDR: ::c_int = 5; +pub const KIPC_MAX_HDR: ::c_int = 6; +pub const KIPC_MAX_DATALEN: ::c_int = 7; +pub const HW_MACHINE: ::c_int = 1; +pub const HW_MODEL: ::c_int = 2; +pub const HW_NCPU: ::c_int = 3; +pub const HW_BYTEORDER: ::c_int = 4; +pub const HW_PHYSMEM: ::c_int = 5; +pub const HW_USERMEM: ::c_int = 6; +pub const HW_PAGESIZE: ::c_int = 7; +pub const HW_DISKNAMES: ::c_int = 8; +pub const HW_DISKSTATS: ::c_int = 9; +pub const HW_FLOATINGPT: ::c_int = 10; +pub const HW_MACHINE_ARCH: ::c_int = 11; +pub const HW_REALMEM: ::c_int = 12; +pub const USER_CS_PATH: ::c_int = 1; +pub const USER_BC_BASE_MAX: ::c_int = 2; +pub const USER_BC_DIM_MAX: ::c_int = 3; +pub const USER_BC_SCALE_MAX: ::c_int = 4; +pub const USER_BC_STRING_MAX: ::c_int = 5; +pub const USER_COLL_WEIGHTS_MAX: ::c_int = 6; +pub const USER_EXPR_NEST_MAX: ::c_int = 7; +pub const USER_LINE_MAX: ::c_int = 8; +pub const USER_RE_DUP_MAX: ::c_int = 9; +pub const USER_POSIX2_VERSION: ::c_int = 10; +pub const USER_POSIX2_C_BIND: ::c_int = 11; +pub const USER_POSIX2_C_DEV: ::c_int = 12; +pub const USER_POSIX2_CHAR_TERM: ::c_int = 13; +pub const USER_POSIX2_FORT_DEV: ::c_int = 14; +pub const USER_POSIX2_FORT_RUN: ::c_int = 15; +pub const USER_POSIX2_LOCALEDEF: ::c_int = 16; +pub const USER_POSIX2_SW_DEV: ::c_int = 17; +pub const USER_POSIX2_UPE: ::c_int = 18; +pub const USER_STREAM_MAX: ::c_int = 19; +pub const USER_TZNAME_MAX: ::c_int = 20; +pub const CTL_P1003_1B_ASYNCHRONOUS_IO: ::c_int = 1; +pub const CTL_P1003_1B_MAPPED_FILES: ::c_int = 2; +pub const CTL_P1003_1B_MEMLOCK: ::c_int = 3; +pub const CTL_P1003_1B_MEMLOCK_RANGE: ::c_int = 4; +pub const CTL_P1003_1B_MEMORY_PROTECTION: ::c_int = 5; +pub const CTL_P1003_1B_MESSAGE_PASSING: ::c_int = 6; +pub const CTL_P1003_1B_PRIORITIZED_IO: ::c_int = 7; +pub const CTL_P1003_1B_PRIORITY_SCHEDULING: ::c_int = 8; +pub const CTL_P1003_1B_REALTIME_SIGNALS: ::c_int = 9; +pub const CTL_P1003_1B_SEMAPHORES: ::c_int = 10; +pub const CTL_P1003_1B_FSYNC: ::c_int = 11; +pub const CTL_P1003_1B_SHARED_MEMORY_OBJECTS: ::c_int = 12; +pub const CTL_P1003_1B_SYNCHRONIZED_IO: ::c_int = 13; +pub const CTL_P1003_1B_TIMERS: ::c_int = 14; +pub const CTL_P1003_1B_AIO_LISTIO_MAX: ::c_int = 15; +pub const CTL_P1003_1B_AIO_MAX: ::c_int = 16; +pub const CTL_P1003_1B_AIO_PRIO_DELTA_MAX: ::c_int = 17; +pub const CTL_P1003_1B_DELAYTIMER_MAX: ::c_int = 18; +pub const CTL_P1003_1B_MQ_OPEN_MAX: ::c_int = 19; +pub const CTL_P1003_1B_PAGESIZE: ::c_int = 20; +pub const CTL_P1003_1B_RTSIG_MAX: ::c_int = 21; +pub const CTL_P1003_1B_SEM_NSEMS_MAX: ::c_int = 22; +pub const CTL_P1003_1B_SEM_VALUE_MAX: ::c_int = 23; +pub const CTL_P1003_1B_SIGQUEUE_MAX: ::c_int = 24; +pub const CTL_P1003_1B_TIMER_MAX: ::c_int = 25; +pub const TIOCGPTN: ::c_uint = 0x4004740f; +pub const TIOCPTMASTER: ::c_uint = 0x2000741c; +pub const TIOCSIG: ::c_uint = 0x2004745f; +pub const TIOCM_DCD: ::c_int = 0x40; +pub const H4DISC: ::c_int = 0x7; + +pub const JAIL_API_VERSION: u32 = 2; +pub const JAIL_CREATE: ::c_int = 0x01; +pub const JAIL_UPDATE: ::c_int = 0x02; +pub const JAIL_ATTACH: ::c_int = 0x04; +pub const JAIL_DYING: ::c_int = 0x08; +pub const JAIL_SET_MASK: ::c_int = 0x0f; +pub const JAIL_GET_MASK: ::c_int = 0x08; +pub const JAIL_SYS_DISABLE: ::c_int = 0; +pub const JAIL_SYS_NEW: ::c_int = 1; +pub const JAIL_SYS_INHERIT: ::c_int = 2; + +pub const SO_BINTIME: ::c_int = 0x2000; +pub const SO_NO_OFFLOAD: ::c_int = 0x4000; +pub const SO_NO_DDP: ::c_int = 0x8000; +pub const SO_LABEL: ::c_int = 0x1009; +pub const SO_PEERLABEL: ::c_int = 0x1010; +pub const SO_LISTENQLIMIT: ::c_int = 0x1011; +pub const SO_LISTENQLEN: ::c_int = 0x1012; +pub const SO_LISTENINCQLEN: ::c_int = 0x1013; +pub const SO_SETFIB: ::c_int = 0x1014; +pub const SO_USER_COOKIE: ::c_int = 0x1015; +pub const SO_PROTOCOL: ::c_int = 0x1016; +pub const SO_PROTOTYPE: ::c_int = SO_PROTOCOL; +pub const SO_VENDOR: ::c_int = 0x80000000; + +pub const LOCAL_PEERCRED: ::c_int = 1; +pub const LOCAL_CREDS: ::c_int = 2; +pub const LOCAL_CONNWAIT: ::c_int = 4; +pub const LOCAL_VENDOR: ::c_int = SO_VENDOR; + +pub const AF_SLOW: ::c_int = 33; +pub const AF_SCLUSTER: ::c_int = 34; +pub const AF_ARP: ::c_int = 35; +pub const AF_BLUETOOTH: ::c_int = 36; +pub const AF_IEEE80211: ::c_int = 37; +pub const AF_INET_SDP: ::c_int = 40; +pub const AF_INET6_SDP: ::c_int = 42; +#[doc(hidden)] +pub const AF_MAX: ::c_int = 42; + +// https://github.com/freebsd/freebsd/blob/master/sys/net/if.h#L140 +pub const IFF_UP: ::c_int = 0x1; // (n) interface is up +pub const IFF_BROADCAST: ::c_int = 0x2; // (i) broadcast address valid +pub const IFF_DEBUG: ::c_int = 0x4; // (n) turn on debugging +pub const IFF_LOOPBACK: ::c_int = 0x8; // (i) is a loopback net +pub const IFF_POINTOPOINT: ::c_int = 0x10; // (i) is a point-to-point link +// 0x20 was IFF_SMART +pub const IFF_RUNNING: ::c_int = 0x40; // (d) resources allocated +#[doc(hidden)] +// IFF_DRV_RUNNING is deprecated. Use the portable `IFF_RUNNING` instead +pub const IFF_DRV_RUNNING: ::c_int = 0x40; +pub const IFF_NOARP: ::c_int = 0x80; // (n) no address resolution protocol +pub const IFF_PROMISC: ::c_int = 0x100; // (n) receive all packets +pub const IFF_ALLMULTI: ::c_int = 0x200; // (n) receive all multicast packets +pub const IFF_OACTIVE: ::c_int = 0x400; // (d) tx hardware queue is full +#[doc(hidden)] +// IFF_DRV_OACTIVE is deprecated. Use the portable `IFF_OACTIVE` instead +pub const IFF_DRV_OACTIVE: ::c_int = 0x400; +pub const IFF_SIMPLEX: ::c_int = 0x800; // (i) can't hear own transmissions +pub const IFF_LINK0: ::c_int = 0x1000; // per link layer defined bit +pub const IFF_LINK1: ::c_int = 0x2000; // per link layer defined bit +pub const IFF_LINK2: ::c_int = 0x4000; // per link layer defined bit +pub const IFF_ALTPHYS: ::c_int = IFF_LINK2; // use alternate physical connection +pub const IFF_MULTICAST: ::c_int = 0x8000; // (i) supports multicast +// (i) unconfigurable using ioctl(2) +pub const IFF_CANTCONFIG: ::c_int = 0x10000; +pub const IFF_PPROMISC: ::c_int = 0x20000; // (n) user-requested promisc mode +pub const IFF_MONITOR: ::c_int = 0x40000; // (n) user-requested monitor mode +pub const IFF_STATICARP: ::c_int = 0x80000; // (n) static ARP +pub const IFF_DYING: ::c_int = 0x200000; // (n) interface is winding down +pub const IFF_RENAMING: ::c_int = 0x400000; // (n) interface is being renamed + +// sys/netinet/in.h +// Protocols (RFC 1700) +// NOTE: These are in addition to the constants defined in src/unix/mod.rs + +// IPPROTO_IP defined in src/unix/mod.rs +/// IP6 hop-by-hop options +pub const IPPROTO_HOPOPTS: ::c_int = 0; +// IPPROTO_ICMP defined in src/unix/mod.rs +/// group mgmt protocol +pub const IPPROTO_IGMP: ::c_int = 2; +/// gateway^2 (deprecated) +pub const IPPROTO_GGP: ::c_int = 3; +/// for compatibility +pub const IPPROTO_IPIP: ::c_int = 4; +// IPPROTO_TCP defined in src/unix/mod.rs +/// Stream protocol II. +pub const IPPROTO_ST: ::c_int = 7; +/// exterior gateway protocol +pub const IPPROTO_EGP: ::c_int = 8; +/// private interior gateway +pub const IPPROTO_PIGP: ::c_int = 9; +/// BBN RCC Monitoring +pub const IPPROTO_RCCMON: ::c_int = 10; +/// network voice protocol +pub const IPPROTO_NVPII: ::c_int = 11; +/// pup +pub const IPPROTO_PUP: ::c_int = 12; +/// Argus +pub const IPPROTO_ARGUS: ::c_int = 13; +/// EMCON +pub const IPPROTO_EMCON: ::c_int = 14; +/// Cross Net Debugger +pub const IPPROTO_XNET: ::c_int = 15; +/// Chaos +pub const IPPROTO_CHAOS: ::c_int = 16; +// IPPROTO_UDP defined in src/unix/mod.rs +/// Multiplexing +pub const IPPROTO_MUX: ::c_int = 18; +/// DCN Measurement Subsystems +pub const IPPROTO_MEAS: ::c_int = 19; +/// Host Monitoring +pub const IPPROTO_HMP: ::c_int = 20; +/// Packet Radio Measurement +pub const IPPROTO_PRM: ::c_int = 21; +/// xns idp +pub const IPPROTO_IDP: ::c_int = 22; +/// Trunk-1 +pub const IPPROTO_TRUNK1: ::c_int = 23; +/// Trunk-2 +pub const IPPROTO_TRUNK2: ::c_int = 24; +/// Leaf-1 +pub const IPPROTO_LEAF1: ::c_int = 25; +/// Leaf-2 +pub const IPPROTO_LEAF2: ::c_int = 26; +/// Reliable Data +pub const IPPROTO_RDP: ::c_int = 27; +/// Reliable Transaction +pub const IPPROTO_IRTP: ::c_int = 28; +/// tp-4 w/ class negotiation +pub const IPPROTO_TP: ::c_int = 29; +/// Bulk Data Transfer +pub const IPPROTO_BLT: ::c_int = 30; +/// Network Services +pub const IPPROTO_NSP: ::c_int = 31; +/// Merit Internodal +pub const IPPROTO_INP: ::c_int = 32; +/// Sequential Exchange +pub const IPPROTO_SEP: ::c_int = 33; +/// Third Party Connect +pub const IPPROTO_3PC: ::c_int = 34; +/// InterDomain Policy Routing +pub const IPPROTO_IDPR: ::c_int = 35; +/// XTP +pub const IPPROTO_XTP: ::c_int = 36; +/// Datagram Delivery +pub const IPPROTO_DDP: ::c_int = 37; +/// Control Message Transport +pub const IPPROTO_CMTP: ::c_int = 38; +/// TP++ Transport +pub const IPPROTO_TPXX: ::c_int = 39; +/// IL transport protocol +pub const IPPROTO_IL: ::c_int = 40; +// IPPROTO_IPV6 defined in src/unix/mod.rs +/// Source Demand Routing +pub const IPPROTO_SDRP: ::c_int = 42; +/// IP6 routing header +pub const IPPROTO_ROUTING: ::c_int = 43; +/// IP6 fragmentation header +pub const IPPROTO_FRAGMENT: ::c_int = 44; +/// InterDomain Routing +pub const IPPROTO_IDRP: ::c_int = 45; +/// resource reservation +pub const IPPROTO_RSVP: ::c_int = 46; +/// General Routing Encap. +pub const IPPROTO_GRE: ::c_int = 47; +/// Mobile Host Routing +pub const IPPROTO_MHRP: ::c_int = 48; +/// BHA +pub const IPPROTO_BHA: ::c_int = 49; +/// IP6 Encap Sec. Payload +pub const IPPROTO_ESP: ::c_int = 50; +/// IP6 Auth Header +pub const IPPROTO_AH: ::c_int = 51; +/// Integ. Net Layer Security +pub const IPPROTO_INLSP: ::c_int = 52; +/// IP with encryption +pub const IPPROTO_SWIPE: ::c_int = 53; +/// Next Hop Resolution +pub const IPPROTO_NHRP: ::c_int = 54; +/// IP Mobility +pub const IPPROTO_MOBILE: ::c_int = 55; +/// Transport Layer Security +pub const IPPROTO_TLSP: ::c_int = 56; +/// SKIP +pub const IPPROTO_SKIP: ::c_int = 57; +// IPPROTO_ICMPV6 defined in src/unix/mod.rs +/// IP6 no next header +pub const IPPROTO_NONE: ::c_int = 59; +/// IP6 destination option +pub const IPPROTO_DSTOPTS: ::c_int = 60; +/// any host internal protocol +pub const IPPROTO_AHIP: ::c_int = 61; +/// CFTP +pub const IPPROTO_CFTP: ::c_int = 62; +/// "hello" routing protocol +pub const IPPROTO_HELLO: ::c_int = 63; +/// SATNET/Backroom EXPAK +pub const IPPROTO_SATEXPAK: ::c_int = 64; +/// Kryptolan +pub const IPPROTO_KRYPTOLAN: ::c_int = 65; +/// Remote Virtual Disk +pub const IPPROTO_RVD: ::c_int = 66; +/// Pluribus Packet Core +pub const IPPROTO_IPPC: ::c_int = 67; +/// Any distributed FS +pub const IPPROTO_ADFS: ::c_int = 68; +/// Satnet Monitoring +pub const IPPROTO_SATMON: ::c_int = 69; +/// VISA Protocol +pub const IPPROTO_VISA: ::c_int = 70; +/// Packet Core Utility +pub const IPPROTO_IPCV: ::c_int = 71; +/// Comp. Prot. Net. Executive +pub const IPPROTO_CPNX: ::c_int = 72; +/// Comp. Prot. HeartBeat +pub const IPPROTO_CPHB: ::c_int = 73; +/// Wang Span Network +pub const IPPROTO_WSN: ::c_int = 74; +/// Packet Video Protocol +pub const IPPROTO_PVP: ::c_int = 75; +/// BackRoom SATNET Monitoring +pub const IPPROTO_BRSATMON: ::c_int = 76; +/// Sun net disk proto (temp.) +pub const IPPROTO_ND: ::c_int = 77; +/// WIDEBAND Monitoring +pub const IPPROTO_WBMON: ::c_int = 78; +/// WIDEBAND EXPAK +pub const IPPROTO_WBEXPAK: ::c_int = 79; +/// ISO cnlp +pub const IPPROTO_EON: ::c_int = 80; +/// VMTP +pub const IPPROTO_VMTP: ::c_int = 81; +/// Secure VMTP +pub const IPPROTO_SVMTP: ::c_int = 82; +/// Banyon VINES +pub const IPPROTO_VINES: ::c_int = 83; +/// TTP +pub const IPPROTO_TTP: ::c_int = 84; +/// NSFNET-IGP +pub const IPPROTO_IGP: ::c_int = 85; +/// dissimilar gateway prot. +pub const IPPROTO_DGP: ::c_int = 86; +/// TCF +pub const IPPROTO_TCF: ::c_int = 87; +/// Cisco/GXS IGRP +pub const IPPROTO_IGRP: ::c_int = 88; +/// OSPFIGP +pub const IPPROTO_OSPFIGP: ::c_int = 89; +/// Strite RPC protocol +pub const IPPROTO_SRPC: ::c_int = 90; +/// Locus Address Resoloution +pub const IPPROTO_LARP: ::c_int = 91; +/// Multicast Transport +pub const IPPROTO_MTP: ::c_int = 92; +/// AX.25 Frames +pub const IPPROTO_AX25: ::c_int = 93; +/// IP encapsulated in IP +pub const IPPROTO_IPEIP: ::c_int = 94; +/// Mobile Int.ing control +pub const IPPROTO_MICP: ::c_int = 95; +/// Semaphore Comm. security +pub const IPPROTO_SCCSP: ::c_int = 96; +/// Ethernet IP encapsulation +pub const IPPROTO_ETHERIP: ::c_int = 97; +/// encapsulation header +pub const IPPROTO_ENCAP: ::c_int = 98; +/// any private encr. scheme +pub const IPPROTO_APES: ::c_int = 99; +/// GMTP +pub const IPPROTO_GMTP: ::c_int = 100; +/// payload compression (IPComp) +pub const IPPROTO_IPCOMP: ::c_int = 108; +/// SCTP +pub const IPPROTO_SCTP: ::c_int = 132; +/// IPv6 Mobility Header +pub const IPPROTO_MH: ::c_int = 135; +/// UDP-Lite +pub const IPPROTO_UDPLITE: ::c_int = 136; +/// IP6 Host Identity Protocol +pub const IPPROTO_HIP: ::c_int = 139; +/// IP6 Shim6 Protocol +pub const IPPROTO_SHIM6: ::c_int = 140; + +/* 101-254: Partly Unassigned */ +/// Protocol Independent Mcast +pub const IPPROTO_PIM: ::c_int = 103; +/// CARP +pub const IPPROTO_CARP: ::c_int = 112; +/// PGM +pub const IPPROTO_PGM: ::c_int = 113; +/// MPLS-in-IP +pub const IPPROTO_MPLS: ::c_int = 137; +/// PFSYNC +pub const IPPROTO_PFSYNC: ::c_int = 240; + +/* 255: Reserved */ +/* BSD Private, local use, namespace incursion, no longer used */ +/// OLD divert pseudo-proto +pub const IPPROTO_OLD_DIVERT: ::c_int = 254; +pub const IPPROTO_MAX: ::c_int = 256; +/// last return value of *_input(), meaning "all job for this pkt is done". +pub const IPPROTO_DONE: ::c_int = 257; + +/* Only used internally, so can be outside the range of valid IP protocols. */ +/// divert pseudo-protocol +pub const IPPROTO_DIVERT: ::c_int = 258; +/// SeND pseudo-protocol +pub const IPPROTO_SEND: ::c_int = 259; + +pub const IP_BINDANY: ::c_int = 24; + +pub const PF_SLOW: ::c_int = AF_SLOW; +pub const PF_SCLUSTER: ::c_int = AF_SCLUSTER; +pub const PF_ARP: ::c_int = AF_ARP; +pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; +pub const PF_IEEE80211: ::c_int = AF_IEEE80211; +pub const PF_INET_SDP: ::c_int = AF_INET_SDP; +pub const PF_INET6_SDP: ::c_int = AF_INET6_SDP; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; + +pub const NET_RT_DUMP: ::c_int = 1; +pub const NET_RT_FLAGS: ::c_int = 2; +pub const NET_RT_IFLIST: ::c_int = 3; +pub const NET_RT_IFMALIST: ::c_int = 4; +pub const NET_RT_IFLISTL: ::c_int = 5; + +// System V IPC +pub const IPC_PRIVATE: ::key_t = 0; +pub const IPC_CREAT: ::c_int = 0o1000; +pub const IPC_EXCL: ::c_int = 0o2000; +pub const IPC_NOWAIT: ::c_int = 0o4000; +pub const IPC_RMID: ::c_int = 0; +pub const IPC_SET: ::c_int = 1; +pub const IPC_STAT: ::c_int = 2; +pub const IPC_INFO: ::c_int = 3; +pub const IPC_R : ::c_int = 0o400; +pub const IPC_W : ::c_int = 0o200; +pub const IPC_M : ::c_int = 0o10000; +pub const MSG_NOERROR: ::c_int = 0o10000; +pub const SHM_RDONLY: ::c_int = 0o10000; +pub const SHM_RND: ::c_int = 0o20000; +pub const SHM_R: ::c_int = 0o400; +pub const SHM_W: ::c_int = 0o200; +pub const SHM_LOCK: ::c_int = 11; +pub const SHM_UNLOCK: ::c_int = 12; +pub const SHM_STAT: ::c_int = 13; +pub const SHM_INFO: ::c_int = 14; +pub const SHM_ANON: *mut ::c_char = 1 as *mut ::c_char; + +// The *_MAXID constants never should've been used outside of the +// FreeBSD base system. And with the exception of CTL_P1003_1B_MAXID, +// they were all removed in svn r262489. They remain here for backwards +// compatibility only, and are scheduled to be removed in libc 1.0.0. +#[doc(hidden)] +pub const NET_MAXID: ::c_int = AF_MAX; +#[doc(hidden)] +pub const CTL_MAXID: ::c_int = 10; +#[doc(hidden)] +pub const KERN_MAXID: ::c_int = 38; +#[doc(hidden)] +pub const HW_MAXID: ::c_int = 13; +#[doc(hidden)] +pub const USER_MAXID: ::c_int = 21; +#[doc(hidden)] +pub const CTL_P1003_1B_MAXID: ::c_int = 26; + +pub const MSG_NOTIFICATION: ::c_int = 0x00002000; +pub const MSG_NBIO: ::c_int = 0x00004000; +pub const MSG_COMPAT: ::c_int = 0x00008000; +pub const MSG_CMSG_CLOEXEC: ::c_int = 0x00040000; +pub const MSG_NOSIGNAL: ::c_int = 0x20000; + +pub const EMPTY: ::c_short = 0; +pub const BOOT_TIME: ::c_short = 1; +pub const OLD_TIME: ::c_short = 2; +pub const NEW_TIME: ::c_short = 3; +pub const USER_PROCESS: ::c_short = 4; +pub const INIT_PROCESS: ::c_short = 5; +pub const LOGIN_PROCESS: ::c_short = 6; +pub const DEAD_PROCESS: ::c_short = 7; +pub const SHUTDOWN_TIME: ::c_short = 8; + +pub const LC_COLLATE_MASK: ::c_int = (1 << 0); +pub const LC_CTYPE_MASK: ::c_int = (1 << 1); +pub const LC_MONETARY_MASK: ::c_int =(1 << 2); +pub const LC_NUMERIC_MASK: ::c_int = (1 << 3); +pub const LC_TIME_MASK: ::c_int = (1 << 4); +pub const LC_MESSAGES_MASK: ::c_int = (1 << 5); +pub const LC_ALL_MASK: ::c_int = LC_COLLATE_MASK + | LC_CTYPE_MASK + | LC_MESSAGES_MASK + | LC_MONETARY_MASK + | LC_NUMERIC_MASK + | LC_TIME_MASK; + +pub const WSTOPPED: ::c_int = 2; // same as WUNTRACED +pub const WCONTINUED: ::c_int = 4; +pub const WNOWAIT: ::c_int = 8; +pub const WEXITED: ::c_int = 16; +pub const WTRAPPED: ::c_int = 32; + +// FreeBSD defines a great many more of these, we only expose the +// standardized ones. +pub const P_PID: idtype_t = 0; +pub const P_PGID: idtype_t = 2; +pub const P_ALL: idtype_t = 7; + +pub const B460800: ::speed_t = 460800; +pub const B921600: ::speed_t = 921600; + +pub const AT_FDCWD: ::c_int = -100; +pub const AT_EACCESS: ::c_int = 0x100; +pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x200; +pub const AT_SYMLINK_FOLLOW: ::c_int = 0x400; +pub const AT_REMOVEDIR: ::c_int = 0x800; + +pub const TABDLY: ::tcflag_t = 0x00000004; +pub const TAB0: ::tcflag_t = 0x00000000; +pub const TAB3: ::tcflag_t = 0x00000004; + +pub const _PC_ACL_NFS4: ::c_int = 64; + +pub const _SC_CPUSET_SIZE: ::c_int = 122; + +pub const XU_NGROUPS: ::c_int = 16; +pub const XUCRED_VERSION: ::c_uint = 0; + +// Flags which can be passed to pdfork(2) +pub const PD_DAEMON: ::c_int = 0x00000001; +pub const PD_CLOEXEC: ::c_int = 0x00000002; +pub const PD_ALLOWED_AT_FORK: ::c_int = PD_DAEMON | PD_CLOEXEC; + +// Values for struct rtprio (type_ field) +pub const RTP_PRIO_REALTIME: ::c_ushort = 2; +pub const RTP_PRIO_NORMAL: ::c_ushort = 3; +pub const RTP_PRIO_IDLE: ::c_ushort = 4; + +pub const POSIX_SPAWN_RESETIDS: ::c_int = 0x01; +pub const POSIX_SPAWN_SETPGROUP: ::c_int = 0x02; +pub const POSIX_SPAWN_SETSCHEDPARAM: ::c_int = 0x04; +pub const POSIX_SPAWN_SETSCHEDULER: ::c_int = 0x08; +pub const POSIX_SPAWN_SETSIGDEF: ::c_int = 0x10; +pub const POSIX_SPAWN_SETSIGMASK: ::c_int = 0x20; + +extern { + pub fn __error() -> *mut ::c_int; + + pub fn mprotect(addr: *const ::c_void, len: ::size_t, prot: ::c_int) + -> ::c_int; + + pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; + + pub fn jail(jail: *mut ::jail) -> ::c_int; + pub fn jail_attach(jid: ::c_int) -> ::c_int; + pub fn jail_remove(jid: ::c_int) -> ::c_int; + pub fn jail_get(iov: *mut ::iovec, niov: ::c_uint, flags: ::c_int) + -> ::c_int; + pub fn jail_set(iov: *mut ::iovec, niov: ::c_uint, flags: ::c_int) + -> ::c_int; + + pub fn fdatasync(fd: ::c_int) -> ::c_int; + pub fn posix_fallocate(fd: ::c_int, offset: ::off_t, + len: ::off_t) -> ::c_int; + pub fn posix_fadvise(fd: ::c_int, offset: ::off_t, len: ::off_t, + advise: ::c_int) -> ::c_int; + pub fn mkostemp(template: *mut ::c_char, flags: ::c_int) -> ::c_int; + pub fn mkostemps(template: *mut ::c_char, + suffixlen: ::c_int, + flags: ::c_int) -> ::c_int; + + pub fn getutxuser(user: *const ::c_char) -> *mut utmpx; + pub fn setutxdb(_type: ::c_int, file: *const ::c_char) -> ::c_int; + + pub fn aio_waitcomplete(iocbp: *mut *mut aiocb, + timeout: *mut ::timespec) -> ::ssize_t; + + pub fn freelocale(loc: ::locale_t) -> ::c_int; + pub fn waitid(idtype: idtype_t, id: ::id_t, infop: *mut ::siginfo_t, + options: ::c_int) -> ::c_int; + + pub fn ftok(pathname: *const ::c_char, proj_id: ::c_int) -> ::key_t; + pub fn shmget(key: ::key_t, size: ::size_t, shmflg: ::c_int) -> ::c_int; + pub fn shmat(shmid: ::c_int, shmaddr: *const ::c_void, + shmflg: ::c_int) -> *mut ::c_void; + pub fn shmdt(shmaddr: *const ::c_void) -> ::c_int; + pub fn shmctl(shmid: ::c_int, cmd: ::c_int, + buf: *mut ::shmid_ds) -> ::c_int; + pub fn msgctl(msqid: ::c_int, cmd: ::c_int, + buf: *mut ::msqid_ds) -> ::c_int; + pub fn msgget(key: ::key_t, msgflg: ::c_int) -> ::c_int; + pub fn msgrcv(msqid: ::c_int, msgp: *mut ::c_void, msgsz: ::size_t, + msgtyp: ::c_long, msgflg: ::c_int) -> ::c_int; + pub fn msgsnd(msqid: ::c_int, msgp: *const ::c_void, msgsz: ::size_t, + msgflg: ::c_int) -> ::c_int; + pub fn cfmakesane(termios: *mut ::termios); + pub fn fexecve(fd: ::c_int, argv: *const *const ::c_char, + envp: *const *const ::c_char) + -> ::c_int; + + pub fn pdfork(fdp: *mut ::c_int, flags: ::c_int) -> ::pid_t; + pub fn pdgetpid(fd: ::c_int, pidp: *mut ::pid_t) -> ::c_int; + pub fn pdkill(fd: ::c_int, signum: ::c_int) -> ::c_int; + + pub fn rtprio_thread(function: ::c_int, lwpid: ::lwpid_t, + rtp: *mut super::rtprio) -> ::c_int; + + pub fn posix_spawn(pid: *mut ::pid_t, + path: *const ::c_char, + file_actions: *const ::posix_spawn_file_actions_t, + attrp: *const ::posix_spawnattr_t, + argv: *const *mut ::c_char, + envp: *const *mut ::c_char) -> ::c_int; + pub fn posix_spawnp(pid: *mut ::pid_t, + file: *const ::c_char, + file_actions: *const ::posix_spawn_file_actions_t, + attrp: *const ::posix_spawnattr_t, + argv: *const *mut ::c_char, + envp: *const *mut ::c_char) -> ::c_int; + pub fn posix_spawnattr_init(attr: *mut posix_spawnattr_t) -> ::c_int; + pub fn posix_spawnattr_destroy(attr: *mut posix_spawnattr_t) -> ::c_int; + pub fn posix_spawnattr_getsigdefault(attr: *const posix_spawnattr_t, + default: *mut ::sigset_t) -> ::c_int; + pub fn posix_spawnattr_setsigdefault(attr: *mut posix_spawnattr_t, + default: *const ::sigset_t) -> ::c_int; + pub fn posix_spawnattr_getsigmask(attr: *const posix_spawnattr_t, + default: *mut ::sigset_t) -> ::c_int; + pub fn posix_spawnattr_setsigmask(attr: *mut posix_spawnattr_t, + default: *const ::sigset_t) -> ::c_int; + pub fn posix_spawnattr_getflags(attr: *const posix_spawnattr_t, + flags: *mut ::c_short) -> ::c_int; + pub fn posix_spawnattr_setflags(attr: *mut posix_spawnattr_t, + flags: ::c_short) -> ::c_int; + pub fn posix_spawnattr_getpgroup(attr: *const posix_spawnattr_t, + flags: *mut ::pid_t) -> ::c_int; + pub fn posix_spawnattr_setpgroup(attr: *mut posix_spawnattr_t, + flags: ::pid_t) -> ::c_int; + pub fn posix_spawnattr_getschedpolicy(attr: *const posix_spawnattr_t, + flags: *mut ::c_int) -> ::c_int; + pub fn posix_spawnattr_setschedpolicy(attr: *mut posix_spawnattr_t, + flags: ::c_int) -> ::c_int; + pub fn posix_spawnattr_getschedparam( + attr: *const posix_spawnattr_t, + param: *mut ::sched_param, + ) -> ::c_int; + pub fn posix_spawnattr_setschedparam( + attr: *mut posix_spawnattr_t, + param: *const ::sched_param, + ) -> ::c_int; + + pub fn posix_spawn_file_actions_init( + actions: *mut posix_spawn_file_actions_t, + ) -> ::c_int; + pub fn posix_spawn_file_actions_destroy( + actions: *mut posix_spawn_file_actions_t, + ) -> ::c_int; + pub fn posix_spawn_file_actions_addopen( + actions: *mut posix_spawn_file_actions_t, + fd: ::c_int, + path: *const ::c_char, + oflag: ::c_int, + mode: ::mode_t, + ) -> ::c_int; + pub fn posix_spawn_file_actions_addclose( + actions: *mut posix_spawn_file_actions_t, + fd: ::c_int, + ) -> ::c_int; + pub fn posix_spawn_file_actions_adddup2( + actions: *mut posix_spawn_file_actions_t, + fd: ::c_int, + newfd: ::c_int, + ) -> ::c_int; +} + +cfg_if! { + if #[cfg(target_arch = "x86")] { + mod x86; + pub use self::x86::*; + } else if #[cfg(target_arch = "x86_64")] { + mod x86_64; + pub use self::x86_64::*; + } else if #[cfg(target_arch = "aarch64")] { + mod aarch64; + pub use self::aarch64::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/x86_64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/x86_64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,32 @@ +pub type c_long = i64; +pub type c_ulong = u64; +pub type time_t = i64; +pub type suseconds_t = i64; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_size: ::off_t, + pub st_blocks: ::blkcnt_t, + pub st_blksize: ::blksize_t, + pub st_flags: ::fflags_t, + pub st_gen: ::uint32_t, + pub st_lspare: ::int32_t, + pub st_birthtime: ::time_t, + pub st_birthtime_nsec: ::c_long, + } +} + +pub const MAP_32BIT: ::c_int = 0x00080000; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/x86.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/x86.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/x86.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/freebsd/x86.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,31 @@ +pub type c_long = i32; +pub type c_ulong = u32; +pub type time_t = i32; +pub type suseconds_t = i32; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_size: ::off_t, + pub st_blocks: ::blkcnt_t, + pub st_blksize: ::blksize_t, + pub st_flags: ::fflags_t, + pub st_gen: ::uint32_t, + pub st_lspare: ::int32_t, + pub st_birthtime: ::time_t, + pub st_birthtime_nsec: ::c_long, + __unused: [u8; 8], + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/freebsdlike/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1197 @@ +pub type c_char = i8; +pub type dev_t = u32; +pub type mode_t = u16; +pub type pthread_attr_t = *mut ::c_void; +pub type rlim_t = i64; +pub type mqd_t = *mut ::c_void; +pub type pthread_mutex_t = *mut ::c_void; +pub type pthread_mutexattr_t = *mut ::c_void; +pub type pthread_cond_t = *mut ::c_void; +pub type pthread_condattr_t = *mut ::c_void; +pub type pthread_rwlock_t = *mut ::c_void; +pub type pthread_rwlockattr_t = *mut ::c_void; +pub type pthread_key_t = ::c_int; +pub type tcflag_t = ::c_uint; +pub type speed_t = ::c_uint; +pub type nl_item = ::c_int; +pub type id_t = i64; + +pub enum timezone {} + +s! { + pub struct glob_t { + pub gl_pathc: ::size_t, + pub gl_matchc: ::size_t, + pub gl_offs: ::size_t, + pub gl_flags: ::c_int, + pub gl_pathv: *mut *mut ::c_char, + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + __unused6: *mut ::c_void, + __unused7: *mut ::c_void, + __unused8: *mut ::c_void, + } + + pub struct kevent { + pub ident: ::uintptr_t, + pub filter: ::c_short, + pub flags: ::c_ushort, + pub fflags: ::c_uint, + pub data: ::intptr_t, + pub udata: *mut ::c_void, + } + + pub struct sockaddr_storage { + pub ss_len: u8, + pub ss_family: ::sa_family_t, + __ss_pad1: [u8; 6], + __ss_align: i64, + __ss_pad2: [u8; 112], + } + + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + pub ai_addrlen: ::socklen_t, + pub ai_canonname: *mut ::c_char, + pub ai_addr: *mut ::sockaddr, + pub ai_next: *mut addrinfo, + } + + pub struct sigset_t { + bits: [u32; 4], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_errno: ::c_int, + pub si_code: ::c_int, + pub si_pid: ::pid_t, + pub si_uid: ::uid_t, + pub si_status: ::c_int, + pub si_addr: *mut ::c_void, + _pad: [::c_int; 12], + } + + pub struct sigaction { + pub sa_sigaction: ::sighandler_t, + pub sa_flags: ::c_int, + pub sa_mask: sigset_t, + } + + pub struct stack_t { + // In FreeBSD 11 and later, ss_sp is actually a void* + pub ss_sp: *mut ::c_char, + pub ss_size: ::size_t, + pub ss_flags: ::c_int, + } + + pub struct sched_param { + pub sched_priority: ::c_int, + } + + pub struct Dl_info { + pub dli_fname: *const ::c_char, + pub dli_fbase: *mut ::c_void, + pub dli_sname: *const ::c_char, + pub dli_saddr: *mut ::c_void, + } + + pub struct sockaddr_in { + pub sin_len: u8, + pub sin_family: ::sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + pub sin_zero: [::c_char; 8], + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_cc: [::cc_t; ::NCCS], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } + + pub struct flock { + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_pid: ::pid_t, + pub l_type: ::c_short, + pub l_whence: ::c_short, + #[cfg(not(target_os = "dragonfly"))] + pub l_sysid: ::c_int, + } + + pub struct sf_hdtr { + pub headers: *mut ::iovec, + pub hdr_cnt: ::c_int, + pub trailers: *mut ::iovec, + pub trl_cnt: ::c_int, + } + + pub struct lconv { + pub decimal_point: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + pub grouping: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub currency_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub int_frac_digits: ::c_char, + pub frac_digits: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + pub n_sign_posn: ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_n_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + pub int_n_sign_posn: ::c_char, + } + + pub struct cmsgcred { + pub cmcred_pid: ::pid_t, + pub cmcred_uid: ::uid_t, + pub cmcred_euid: ::uid_t, + pub cmcred_gid: ::gid_t, + pub cmcred_ngroups: ::c_short, + pub cmcred_groups: [::gid_t; CMGROUP_MAX], + } + + pub struct rtprio { + pub type_: ::c_ushort, + pub prio: ::c_ushort, + } +} + +pub const AIO_LISTIO_MAX: ::c_int = 16; +pub const AIO_CANCELED: ::c_int = 1; +pub const AIO_NOTCANCELED: ::c_int = 2; +pub const AIO_ALLDONE: ::c_int = 3; +pub const LIO_NOP: ::c_int = 0; +pub const LIO_WRITE: ::c_int = 1; +pub const LIO_READ: ::c_int = 2; +pub const LIO_WAIT: ::c_int = 1; +pub const LIO_NOWAIT: ::c_int = 0; + +pub const SIGEV_NONE: ::c_int = 0; +pub const SIGEV_SIGNAL: ::c_int = 1; +pub const SIGEV_THREAD: ::c_int = 2; +pub const SIGEV_KEVENT: ::c_int = 3; + +pub const CODESET: ::nl_item = 0; +pub const D_T_FMT: ::nl_item = 1; +pub const D_FMT: ::nl_item = 2; +pub const T_FMT: ::nl_item = 3; +pub const T_FMT_AMPM: ::nl_item = 4; +pub const AM_STR: ::nl_item = 5; +pub const PM_STR: ::nl_item = 6; + +pub const DAY_1: ::nl_item = 7; +pub const DAY_2: ::nl_item = 8; +pub const DAY_3: ::nl_item = 9; +pub const DAY_4: ::nl_item = 10; +pub const DAY_5: ::nl_item = 11; +pub const DAY_6: ::nl_item = 12; +pub const DAY_7: ::nl_item = 13; + +pub const ABDAY_1: ::nl_item = 14; +pub const ABDAY_2: ::nl_item = 15; +pub const ABDAY_3: ::nl_item = 16; +pub const ABDAY_4: ::nl_item = 17; +pub const ABDAY_5: ::nl_item = 18; +pub const ABDAY_6: ::nl_item = 19; +pub const ABDAY_7: ::nl_item = 20; + +pub const MON_1: ::nl_item = 21; +pub const MON_2: ::nl_item = 22; +pub const MON_3: ::nl_item = 23; +pub const MON_4: ::nl_item = 24; +pub const MON_5: ::nl_item = 25; +pub const MON_6: ::nl_item = 26; +pub const MON_7: ::nl_item = 27; +pub const MON_8: ::nl_item = 28; +pub const MON_9: ::nl_item = 29; +pub const MON_10: ::nl_item = 30; +pub const MON_11: ::nl_item = 31; +pub const MON_12: ::nl_item = 32; + +pub const ABMON_1: ::nl_item = 33; +pub const ABMON_2: ::nl_item = 34; +pub const ABMON_3: ::nl_item = 35; +pub const ABMON_4: ::nl_item = 36; +pub const ABMON_5: ::nl_item = 37; +pub const ABMON_6: ::nl_item = 38; +pub const ABMON_7: ::nl_item = 39; +pub const ABMON_8: ::nl_item = 40; +pub const ABMON_9: ::nl_item = 41; +pub const ABMON_10: ::nl_item = 42; +pub const ABMON_11: ::nl_item = 43; +pub const ABMON_12: ::nl_item = 44; + +pub const ERA: ::nl_item = 45; +pub const ERA_D_FMT: ::nl_item = 46; +pub const ERA_D_T_FMT: ::nl_item = 47; +pub const ERA_T_FMT: ::nl_item = 48; +pub const ALT_DIGITS: ::nl_item = 49; + +pub const RADIXCHAR: ::nl_item = 50; +pub const THOUSEP: ::nl_item = 51; + +pub const YESEXPR: ::nl_item = 52; +pub const NOEXPR: ::nl_item = 53; + +pub const YESSTR: ::nl_item = 54; +pub const NOSTR: ::nl_item = 55; + +pub const CRNCYSTR: ::nl_item = 56; + +pub const D_MD_ORDER: ::nl_item = 57; + +pub const ALTMON_1: ::nl_item = 58; +pub const ALTMON_2: ::nl_item = 59; +pub const ALTMON_3: ::nl_item = 60; +pub const ALTMON_4: ::nl_item = 61; +pub const ALTMON_5: ::nl_item = 62; +pub const ALTMON_6: ::nl_item = 63; +pub const ALTMON_7: ::nl_item = 64; +pub const ALTMON_8: ::nl_item = 65; +pub const ALTMON_9: ::nl_item = 66; +pub const ALTMON_10: ::nl_item = 67; +pub const ALTMON_11: ::nl_item = 68; +pub const ALTMON_12: ::nl_item = 69; + +pub const EXIT_FAILURE: ::c_int = 1; +pub const EXIT_SUCCESS: ::c_int = 0; +pub const EOF: ::c_int = -1; +pub const SEEK_SET: ::c_int = 0; +pub const SEEK_CUR: ::c_int = 1; +pub const SEEK_END: ::c_int = 2; +pub const SEEK_DATA: ::c_int = 3; +pub const SEEK_HOLE: ::c_int = 4; +pub const _IOFBF: ::c_int = 0; +pub const _IONBF: ::c_int = 2; +pub const _IOLBF: ::c_int = 1; +pub const BUFSIZ: ::c_uint = 1024; +pub const FOPEN_MAX: ::c_uint = 20; +pub const FILENAME_MAX: ::c_uint = 1024; +pub const L_tmpnam: ::c_uint = 1024; +pub const TMP_MAX: ::c_uint = 308915776; + +pub const O_NOCTTY: ::c_int = 32768; +pub const O_DIRECT: ::c_int = 0x00010000; + +pub const S_IFIFO: mode_t = 4096; +pub const S_IFCHR: mode_t = 8192; +pub const S_IFBLK: mode_t = 24576; +pub const S_IFDIR: mode_t = 16384; +pub const S_IFREG: mode_t = 32768; +pub const S_IFLNK: mode_t = 40960; +pub const S_IFSOCK: mode_t = 49152; +pub const S_IFMT: mode_t = 61440; +pub const S_IEXEC: mode_t = 64; +pub const S_IWRITE: mode_t = 128; +pub const S_IREAD: mode_t = 256; +pub const S_IRWXU: mode_t = 448; +pub const S_IXUSR: mode_t = 64; +pub const S_IWUSR: mode_t = 128; +pub const S_IRUSR: mode_t = 256; +pub const S_IRWXG: mode_t = 56; +pub const S_IXGRP: mode_t = 8; +pub const S_IWGRP: mode_t = 16; +pub const S_IRGRP: mode_t = 32; +pub const S_IRWXO: mode_t = 7; +pub const S_IXOTH: mode_t = 1; +pub const S_IWOTH: mode_t = 2; +pub const S_IROTH: mode_t = 4; +pub const F_OK: ::c_int = 0; +pub const R_OK: ::c_int = 4; +pub const W_OK: ::c_int = 2; +pub const X_OK: ::c_int = 1; +pub const STDIN_FILENO: ::c_int = 0; +pub const STDOUT_FILENO: ::c_int = 1; +pub const STDERR_FILENO: ::c_int = 2; +pub const F_LOCK: ::c_int = 1; +pub const F_TEST: ::c_int = 3; +pub const F_TLOCK: ::c_int = 2; +pub const F_ULOCK: ::c_int = 0; +pub const F_DUPFD_CLOEXEC: ::c_int = 17; +pub const SIGHUP: ::c_int = 1; +pub const SIGINT: ::c_int = 2; +pub const SIGQUIT: ::c_int = 3; +pub const SIGILL: ::c_int = 4; +pub const SIGABRT: ::c_int = 6; +pub const SIGEMT: ::c_int = 7; +pub const SIGFPE: ::c_int = 8; +pub const SIGKILL: ::c_int = 9; +pub const SIGSEGV: ::c_int = 11; +pub const SIGPIPE: ::c_int = 13; +pub const SIGALRM: ::c_int = 14; +pub const SIGTERM: ::c_int = 15; + +pub const PROT_NONE: ::c_int = 0; +pub const PROT_READ: ::c_int = 1; +pub const PROT_WRITE: ::c_int = 2; +pub const PROT_EXEC: ::c_int = 4; + +pub const MAP_FILE: ::c_int = 0x0000; +pub const MAP_SHARED: ::c_int = 0x0001; +pub const MAP_PRIVATE: ::c_int = 0x0002; +pub const MAP_FIXED: ::c_int = 0x0010; +pub const MAP_ANON: ::c_int = 0x1000; +pub const MAP_ANONYMOUS: ::c_int = MAP_ANON; + +pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const MS_SYNC: ::c_int = 0x0000; +pub const MS_ASYNC: ::c_int = 0x0001; +pub const MS_INVALIDATE: ::c_int = 0x0002; + +pub const EPERM: ::c_int = 1; +pub const ENOENT: ::c_int = 2; +pub const ESRCH: ::c_int = 3; +pub const EINTR: ::c_int = 4; +pub const EIO: ::c_int = 5; +pub const ENXIO: ::c_int = 6; +pub const E2BIG: ::c_int = 7; +pub const ENOEXEC: ::c_int = 8; +pub const EBADF: ::c_int = 9; +pub const ECHILD: ::c_int = 10; +pub const EDEADLK: ::c_int = 11; +pub const ENOMEM: ::c_int = 12; +pub const EACCES: ::c_int = 13; +pub const EFAULT: ::c_int = 14; +pub const ENOTBLK: ::c_int = 15; +pub const EBUSY: ::c_int = 16; +pub const EEXIST: ::c_int = 17; +pub const EXDEV: ::c_int = 18; +pub const ENODEV: ::c_int = 19; +pub const ENOTDIR: ::c_int = 20; +pub const EISDIR: ::c_int = 21; +pub const EINVAL: ::c_int = 22; +pub const ENFILE: ::c_int = 23; +pub const EMFILE: ::c_int = 24; +pub const ENOTTY: ::c_int = 25; +pub const ETXTBSY: ::c_int = 26; +pub const EFBIG: ::c_int = 27; +pub const ENOSPC: ::c_int = 28; +pub const ESPIPE: ::c_int = 29; +pub const EROFS: ::c_int = 30; +pub const EMLINK: ::c_int = 31; +pub const EPIPE: ::c_int = 32; +pub const EDOM: ::c_int = 33; +pub const ERANGE: ::c_int = 34; +pub const EAGAIN: ::c_int = 35; +pub const EWOULDBLOCK: ::c_int = 35; +pub const EINPROGRESS: ::c_int = 36; +pub const EALREADY: ::c_int = 37; +pub const ENOTSOCK: ::c_int = 38; +pub const EDESTADDRREQ: ::c_int = 39; +pub const EMSGSIZE: ::c_int = 40; +pub const EPROTOTYPE: ::c_int = 41; +pub const ENOPROTOOPT: ::c_int = 42; +pub const EPROTONOSUPPORT: ::c_int = 43; +pub const ESOCKTNOSUPPORT: ::c_int = 44; +pub const EOPNOTSUPP: ::c_int = 45; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; +pub const EPFNOSUPPORT: ::c_int = 46; +pub const EAFNOSUPPORT: ::c_int = 47; +pub const EADDRINUSE: ::c_int = 48; +pub const EADDRNOTAVAIL: ::c_int = 49; +pub const ENETDOWN: ::c_int = 50; +pub const ENETUNREACH: ::c_int = 51; +pub const ENETRESET: ::c_int = 52; +pub const ECONNABORTED: ::c_int = 53; +pub const ECONNRESET: ::c_int = 54; +pub const ENOBUFS: ::c_int = 55; +pub const EISCONN: ::c_int = 56; +pub const ENOTCONN: ::c_int = 57; +pub const ESHUTDOWN: ::c_int = 58; +pub const ETOOMANYREFS: ::c_int = 59; +pub const ETIMEDOUT: ::c_int = 60; +pub const ECONNREFUSED: ::c_int = 61; +pub const ELOOP: ::c_int = 62; +pub const ENAMETOOLONG: ::c_int = 63; +pub const EHOSTDOWN: ::c_int = 64; +pub const EHOSTUNREACH: ::c_int = 65; +pub const ENOTEMPTY: ::c_int = 66; +pub const EPROCLIM: ::c_int = 67; +pub const EUSERS: ::c_int = 68; +pub const EDQUOT: ::c_int = 69; +pub const ESTALE: ::c_int = 70; +pub const EREMOTE: ::c_int = 71; +pub const EBADRPC: ::c_int = 72; +pub const ERPCMISMATCH: ::c_int = 73; +pub const EPROGUNAVAIL: ::c_int = 74; +pub const EPROGMISMATCH: ::c_int = 75; +pub const EPROCUNAVAIL: ::c_int = 76; +pub const ENOLCK: ::c_int = 77; +pub const ENOSYS: ::c_int = 78; +pub const EFTYPE: ::c_int = 79; +pub const EAUTH: ::c_int = 80; +pub const ENEEDAUTH: ::c_int = 81; +pub const EIDRM: ::c_int = 82; +pub const ENOMSG: ::c_int = 83; +pub const EOVERFLOW: ::c_int = 84; +pub const ECANCELED: ::c_int = 85; +pub const EILSEQ: ::c_int = 86; +pub const ENOATTR: ::c_int = 87; +pub const EDOOFUS: ::c_int = 88; +pub const EBADMSG: ::c_int = 89; +pub const EMULTIHOP: ::c_int = 90; +pub const ENOLINK: ::c_int = 91; +pub const EPROTO: ::c_int = 92; + +pub const POLLSTANDARD: ::c_short = ::POLLIN | ::POLLPRI | ::POLLOUT | + ::POLLRDNORM | ::POLLRDBAND | ::POLLWRBAND | ::POLLERR | + ::POLLHUP | ::POLLNVAL; + +pub const EAI_AGAIN: ::c_int = 2; +pub const EAI_BADFLAGS: ::c_int = 3; +pub const EAI_FAIL: ::c_int = 4; +pub const EAI_FAMILY: ::c_int = 5; +pub const EAI_MEMORY: ::c_int = 6; +pub const EAI_NONAME: ::c_int = 8; +pub const EAI_SERVICE: ::c_int = 9; +pub const EAI_SOCKTYPE: ::c_int = 10; +pub const EAI_SYSTEM: ::c_int = 11; +pub const EAI_OVERFLOW: ::c_int = 14; + +pub const F_DUPFD: ::c_int = 0; +pub const F_GETFD: ::c_int = 1; +pub const F_SETFD: ::c_int = 2; +pub const F_GETFL: ::c_int = 3; +pub const F_SETFL: ::c_int = 4; + +pub const SIGTRAP: ::c_int = 5; + +pub const GLOB_APPEND : ::c_int = 0x0001; +pub const GLOB_DOOFFS : ::c_int = 0x0002; +pub const GLOB_ERR : ::c_int = 0x0004; +pub const GLOB_MARK : ::c_int = 0x0008; +pub const GLOB_NOCHECK : ::c_int = 0x0010; +pub const GLOB_NOSORT : ::c_int = 0x0020; +pub const GLOB_NOESCAPE: ::c_int = 0x2000; + +pub const GLOB_NOSPACE : ::c_int = -1; +pub const GLOB_ABORTED : ::c_int = -2; +pub const GLOB_NOMATCH : ::c_int = -3; + +pub const POSIX_MADV_NORMAL: ::c_int = 0; +pub const POSIX_MADV_RANDOM: ::c_int = 1; +pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_MADV_WILLNEED: ::c_int = 3; +pub const POSIX_MADV_DONTNEED: ::c_int = 4; + +pub const PTHREAD_PROCESS_PRIVATE: ::c_int = 0; +pub const PTHREAD_PROCESS_SHARED: ::c_int = 1; +pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; +pub const PTHREAD_CREATE_DETACHED: ::c_int = 1; + +pub const RLIMIT_CPU: ::c_int = 0; +pub const RLIMIT_FSIZE: ::c_int = 1; +pub const RLIMIT_DATA: ::c_int = 2; +pub const RLIMIT_STACK: ::c_int = 3; +pub const RLIMIT_CORE: ::c_int = 4; +pub const RLIMIT_RSS: ::c_int = 5; +pub const RLIMIT_MEMLOCK: ::c_int = 6; +pub const RLIMIT_NPROC: ::c_int = 7; +pub const RLIMIT_NOFILE: ::c_int = 8; +pub const RLIMIT_SBSIZE: ::c_int = 9; +pub const RLIMIT_VMEM: ::c_int = 10; +pub const RLIMIT_AS: ::c_int = RLIMIT_VMEM; +pub const RLIM_INFINITY: rlim_t = 0x7fff_ffff_ffff_ffff; + +pub const RUSAGE_SELF: ::c_int = 0; +pub const RUSAGE_CHILDREN: ::c_int = -1; + +pub const MADV_NORMAL: ::c_int = 0; +pub const MADV_RANDOM: ::c_int = 1; +pub const MADV_SEQUENTIAL: ::c_int = 2; +pub const MADV_WILLNEED: ::c_int = 3; +pub const MADV_DONTNEED: ::c_int = 4; +pub const MADV_FREE: ::c_int = 5; +pub const MADV_NOSYNC: ::c_int = 6; +pub const MADV_AUTOSYNC: ::c_int = 7; +pub const MADV_NOCORE: ::c_int = 8; +pub const MADV_CORE: ::c_int = 9; + +pub const MINCORE_INCORE: ::c_int = 0x1; +pub const MINCORE_REFERENCED: ::c_int = 0x2; +pub const MINCORE_MODIFIED: ::c_int = 0x4; +pub const MINCORE_REFERENCED_OTHER: ::c_int = 0x8; +pub const MINCORE_MODIFIED_OTHER: ::c_int = 0x10; +pub const MINCORE_SUPER: ::c_int = 0x20; + +pub const AF_UNSPEC: ::c_int = 0; +pub const AF_LOCAL: ::c_int = 1; +pub const AF_UNIX: ::c_int = AF_LOCAL; +pub const AF_INET: ::c_int = 2; +pub const AF_IMPLINK: ::c_int = 3; +pub const AF_PUP: ::c_int = 4; +pub const AF_CHAOS: ::c_int = 5; +pub const AF_NETBIOS: ::c_int = 6; +pub const AF_ISO: ::c_int = 7; +pub const AF_OSI: ::c_int = AF_ISO; +pub const AF_ECMA: ::c_int = 8; +pub const AF_DATAKIT: ::c_int = 9; +pub const AF_CCITT: ::c_int = 10; +pub const AF_SNA: ::c_int = 11; +pub const AF_DECnet: ::c_int = 12; +pub const AF_DLI: ::c_int = 13; +pub const AF_LAT: ::c_int = 14; +pub const AF_HYLINK: ::c_int = 15; +pub const AF_APPLETALK: ::c_int = 16; +pub const AF_ROUTE: ::c_int = 17; +pub const AF_LINK: ::c_int = 18; +pub const pseudo_AF_XTP: ::c_int = 19; +pub const AF_COIP: ::c_int = 20; +pub const AF_CNT: ::c_int = 21; +pub const pseudo_AF_RTIP: ::c_int = 22; +pub const AF_IPX: ::c_int = 23; +pub const AF_SIP: ::c_int = 24; +pub const pseudo_AF_PIP: ::c_int = 25; +pub const AF_ISDN: ::c_int = 26; +pub const AF_E164: ::c_int = AF_ISDN; +pub const pseudo_AF_KEY: ::c_int = 27; +pub const AF_INET6: ::c_int = 28; +pub const AF_NATM: ::c_int = 29; +pub const AF_ATM: ::c_int = 30; +pub const pseudo_AF_HDRCMPLT: ::c_int = 31; +pub const AF_NETGRAPH: ::c_int = 32; + +pub const PF_UNSPEC: ::c_int = AF_UNSPEC; +pub const PF_LOCAL: ::c_int = AF_LOCAL; +pub const PF_UNIX: ::c_int = PF_LOCAL; +pub const PF_INET: ::c_int = AF_INET; +pub const PF_IMPLINK: ::c_int = AF_IMPLINK; +pub const PF_PUP: ::c_int = AF_PUP; +pub const PF_CHAOS: ::c_int = AF_CHAOS; +pub const PF_NETBIOS: ::c_int = AF_NETBIOS; +pub const PF_ISO: ::c_int = AF_ISO; +pub const PF_OSI: ::c_int = AF_ISO; +pub const PF_ECMA: ::c_int = AF_ECMA; +pub const PF_DATAKIT: ::c_int = AF_DATAKIT; +pub const PF_CCITT: ::c_int = AF_CCITT; +pub const PF_SNA: ::c_int = AF_SNA; +pub const PF_DECnet: ::c_int = AF_DECnet; +pub const PF_DLI: ::c_int = AF_DLI; +pub const PF_LAT: ::c_int = AF_LAT; +pub const PF_HYLINK: ::c_int = AF_HYLINK; +pub const PF_APPLETALK: ::c_int = AF_APPLETALK; +pub const PF_ROUTE: ::c_int = AF_ROUTE; +pub const PF_LINK: ::c_int = AF_LINK; +pub const PF_XTP: ::c_int = pseudo_AF_XTP; +pub const PF_COIP: ::c_int = AF_COIP; +pub const PF_CNT: ::c_int = AF_CNT; +pub const PF_SIP: ::c_int = AF_SIP; +pub const PF_IPX: ::c_int = AF_IPX; +pub const PF_RTIP: ::c_int = pseudo_AF_RTIP; +pub const PF_PIP: ::c_int = pseudo_AF_PIP; +pub const PF_ISDN: ::c_int = AF_ISDN; +pub const PF_KEY: ::c_int = pseudo_AF_KEY; +pub const PF_INET6: ::c_int = AF_INET6; +pub const PF_NATM: ::c_int = AF_NATM; +pub const PF_ATM: ::c_int = AF_ATM; +pub const PF_NETGRAPH: ::c_int = AF_NETGRAPH; + +pub const SOMAXCONN: ::c_int = 128; + +pub const MSG_OOB: ::c_int = 0x00000001; +pub const MSG_PEEK: ::c_int = 0x00000002; +pub const MSG_DONTROUTE: ::c_int = 0x00000004; +pub const MSG_EOR: ::c_int = 0x00000008; +pub const MSG_TRUNC: ::c_int = 0x00000010; +pub const MSG_CTRUNC: ::c_int = 0x00000020; +pub const MSG_WAITALL: ::c_int = 0x00000040; +pub const MSG_DONTWAIT: ::c_int = 0x00000080; +pub const MSG_EOF: ::c_int = 0x00000100; + +pub const SCM_TIMESTAMP: ::c_int = 0x02; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_RAW: ::c_int = 3; +pub const SOCK_RDM: ::c_int = 4; +pub const SOCK_SEQPACKET: ::c_int = 5; +pub const SOCK_CLOEXEC: ::c_int = 0x10000000; +pub const SOCK_NONBLOCK: ::c_int = 0x20000000; +pub const SOCK_MAXADDRLEN: ::c_int = 255; +pub const IP_TTL: ::c_int = 4; +pub const IP_HDRINCL: ::c_int = 2; +pub const IP_ADD_MEMBERSHIP: ::c_int = 12; +pub const IP_DROP_MEMBERSHIP: ::c_int = 13; +pub const IPV6_JOIN_GROUP: ::c_int = 12; +pub const IPV6_LEAVE_GROUP: ::c_int = 13; + +pub const TCP_NODELAY: ::c_int = 1; +pub const TCP_KEEPIDLE: ::c_int = 256; +pub const SOL_SOCKET: ::c_int = 0xffff; +pub const SO_DEBUG: ::c_int = 0x01; +pub const SO_ACCEPTCONN: ::c_int = 0x0002; +pub const SO_REUSEADDR: ::c_int = 0x0004; +pub const SO_KEEPALIVE: ::c_int = 0x0008; +pub const SO_DONTROUTE: ::c_int = 0x0010; +pub const SO_BROADCAST: ::c_int = 0x0020; +pub const SO_USELOOPBACK: ::c_int = 0x0040; +pub const SO_LINGER: ::c_int = 0x0080; +pub const SO_OOBINLINE: ::c_int = 0x0100; +pub const SO_REUSEPORT: ::c_int = 0x0200; +pub const SO_TIMESTAMP: ::c_int = 0x0400; +pub const SO_NOSIGPIPE: ::c_int = 0x0800; +pub const SO_ACCEPTFILTER: ::c_int = 0x1000; +pub const SO_SNDBUF: ::c_int = 0x1001; +pub const SO_RCVBUF: ::c_int = 0x1002; +pub const SO_SNDLOWAT: ::c_int = 0x1003; +pub const SO_RCVLOWAT: ::c_int = 0x1004; +pub const SO_SNDTIMEO: ::c_int = 0x1005; +pub const SO_RCVTIMEO: ::c_int = 0x1006; +pub const SO_ERROR: ::c_int = 0x1007; +pub const SO_TYPE: ::c_int = 0x1008; + +pub const SHUT_RD: ::c_int = 0; +pub const SHUT_WR: ::c_int = 1; +pub const SHUT_RDWR: ::c_int = 2; + +pub const LOCK_SH: ::c_int = 1; +pub const LOCK_EX: ::c_int = 2; +pub const LOCK_NB: ::c_int = 4; +pub const LOCK_UN: ::c_int = 8; + +pub const MAP_COPY: ::c_int = 0x0002; +pub const MAP_RENAME: ::c_int = 0x0020; +pub const MAP_NORESERVE: ::c_int = 0x0040; +pub const MAP_HASSEMAPHORE: ::c_int = 0x0200; +pub const MAP_STACK: ::c_int = 0x0400; +pub const MAP_NOSYNC: ::c_int = 0x0800; +pub const MAP_NOCORE: ::c_int = 0x020000; + +pub const IPPROTO_RAW: ::c_int = 255; + +pub const _PC_LINK_MAX: ::c_int = 1; +pub const _PC_MAX_CANON: ::c_int = 2; +pub const _PC_MAX_INPUT: ::c_int = 3; +pub const _PC_NAME_MAX: ::c_int = 4; +pub const _PC_PATH_MAX: ::c_int = 5; +pub const _PC_PIPE_BUF: ::c_int = 6; +pub const _PC_CHOWN_RESTRICTED: ::c_int = 7; +pub const _PC_NO_TRUNC: ::c_int = 8; +pub const _PC_VDISABLE: ::c_int = 9; +pub const _PC_ALLOC_SIZE_MIN: ::c_int = 10; +pub const _PC_FILESIZEBITS: ::c_int = 12; +pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 14; +pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 15; +pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 16; +pub const _PC_REC_XFER_ALIGN: ::c_int = 17; +pub const _PC_SYMLINK_MAX: ::c_int = 18; +pub const _PC_MIN_HOLE_SIZE: ::c_int = 21; +pub const _PC_ASYNC_IO: ::c_int = 53; +pub const _PC_PRIO_IO: ::c_int = 54; +pub const _PC_SYNC_IO: ::c_int = 55; +pub const _PC_ACL_EXTENDED: ::c_int = 59; +pub const _PC_ACL_PATH_MAX: ::c_int = 60; +pub const _PC_CAP_PRESENT: ::c_int = 61; +pub const _PC_INF_PRESENT: ::c_int = 62; +pub const _PC_MAC_PRESENT: ::c_int = 63; + +pub const _SC_ARG_MAX: ::c_int = 1; +pub const _SC_CHILD_MAX: ::c_int = 2; +pub const _SC_CLK_TCK: ::c_int = 3; +pub const _SC_NGROUPS_MAX: ::c_int = 4; +pub const _SC_OPEN_MAX: ::c_int = 5; +pub const _SC_JOB_CONTROL: ::c_int = 6; +pub const _SC_SAVED_IDS: ::c_int = 7; +pub const _SC_VERSION: ::c_int = 8; +pub const _SC_BC_BASE_MAX: ::c_int = 9; +pub const _SC_BC_DIM_MAX: ::c_int = 10; +pub const _SC_BC_SCALE_MAX: ::c_int = 11; +pub const _SC_BC_STRING_MAX: ::c_int = 12; +pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 13; +pub const _SC_EXPR_NEST_MAX: ::c_int = 14; +pub const _SC_LINE_MAX: ::c_int = 15; +pub const _SC_RE_DUP_MAX: ::c_int = 16; +pub const _SC_2_VERSION: ::c_int = 17; +pub const _SC_2_C_BIND: ::c_int = 18; +pub const _SC_2_C_DEV: ::c_int = 19; +pub const _SC_2_CHAR_TERM: ::c_int = 20; +pub const _SC_2_FORT_DEV: ::c_int = 21; +pub const _SC_2_FORT_RUN: ::c_int = 22; +pub const _SC_2_LOCALEDEF: ::c_int = 23; +pub const _SC_2_SW_DEV: ::c_int = 24; +pub const _SC_2_UPE: ::c_int = 25; +pub const _SC_STREAM_MAX: ::c_int = 26; +pub const _SC_TZNAME_MAX: ::c_int = 27; +pub const _SC_ASYNCHRONOUS_IO: ::c_int = 28; +pub const _SC_MAPPED_FILES: ::c_int = 29; +pub const _SC_MEMLOCK: ::c_int = 30; +pub const _SC_MEMLOCK_RANGE: ::c_int = 31; +pub const _SC_MEMORY_PROTECTION: ::c_int = 32; +pub const _SC_MESSAGE_PASSING: ::c_int = 33; +pub const _SC_PRIORITIZED_IO: ::c_int = 34; +pub const _SC_PRIORITY_SCHEDULING: ::c_int = 35; +pub const _SC_REALTIME_SIGNALS: ::c_int = 36; +pub const _SC_SEMAPHORES: ::c_int = 37; +pub const _SC_FSYNC: ::c_int = 38; +pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 39; +pub const _SC_SYNCHRONIZED_IO: ::c_int = 40; +pub const _SC_TIMERS: ::c_int = 41; +pub const _SC_AIO_LISTIO_MAX: ::c_int = 42; +pub const _SC_AIO_MAX: ::c_int = 43; +pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 44; +pub const _SC_DELAYTIMER_MAX: ::c_int = 45; +pub const _SC_MQ_OPEN_MAX: ::c_int = 46; +pub const _SC_PAGESIZE: ::c_int = 47; +pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; +pub const _SC_RTSIG_MAX: ::c_int = 48; +pub const _SC_SEM_NSEMS_MAX: ::c_int = 49; +pub const _SC_SEM_VALUE_MAX: ::c_int = 50; +pub const _SC_SIGQUEUE_MAX: ::c_int = 51; +pub const _SC_TIMER_MAX: ::c_int = 52; +pub const _SC_IOV_MAX: ::c_int = 56; +pub const _SC_NPROCESSORS_CONF: ::c_int = 57; +pub const _SC_2_PBS: ::c_int = 59; +pub const _SC_2_PBS_ACCOUNTING: ::c_int = 60; +pub const _SC_2_PBS_CHECKPOINT: ::c_int = 61; +pub const _SC_2_PBS_LOCATE: ::c_int = 62; +pub const _SC_2_PBS_MESSAGE: ::c_int = 63; +pub const _SC_2_PBS_TRACK: ::c_int = 64; +pub const _SC_ADVISORY_INFO: ::c_int = 65; +pub const _SC_BARRIERS: ::c_int = 66; +pub const _SC_CLOCK_SELECTION: ::c_int = 67; +pub const _SC_CPUTIME: ::c_int = 68; +pub const _SC_FILE_LOCKING: ::c_int = 69; +pub const _SC_NPROCESSORS_ONLN: ::c_int = 58; +pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 70; +pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 71; +pub const _SC_HOST_NAME_MAX: ::c_int = 72; +pub const _SC_LOGIN_NAME_MAX: ::c_int = 73; +pub const _SC_MONOTONIC_CLOCK: ::c_int = 74; +pub const _SC_MQ_PRIO_MAX: ::c_int = 75; +pub const _SC_READER_WRITER_LOCKS: ::c_int = 76; +pub const _SC_REGEXP: ::c_int = 77; +pub const _SC_SHELL: ::c_int = 78; +pub const _SC_SPAWN: ::c_int = 79; +pub const _SC_SPIN_LOCKS: ::c_int = 80; +pub const _SC_SPORADIC_SERVER: ::c_int = 81; +pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 82; +pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 83; +pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 85; +pub const _SC_THREAD_KEYS_MAX: ::c_int = 86; +pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 87; +pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 88; +pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 89; +pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 90; +pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 91; +pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 92; +pub const _SC_THREAD_STACK_MIN: ::c_int = 93; +pub const _SC_THREAD_THREADS_MAX: ::c_int = 94; +pub const _SC_TIMEOUTS: ::c_int = 95; +pub const _SC_THREADS: ::c_int = 96; +pub const _SC_TRACE: ::c_int = 97; +pub const _SC_TRACE_EVENT_FILTER: ::c_int = 98; +pub const _SC_TRACE_INHERIT: ::c_int = 99; +pub const _SC_TRACE_LOG: ::c_int = 100; +pub const _SC_TTY_NAME_MAX: ::c_int = 101; +pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 102; +pub const _SC_V6_ILP32_OFF32: ::c_int = 103; +pub const _SC_V6_ILP32_OFFBIG: ::c_int = 104; +pub const _SC_V6_LP64_OFF64: ::c_int = 105; +pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 106; +pub const _SC_ATEXIT_MAX: ::c_int = 107; +pub const _SC_XOPEN_CRYPT: ::c_int = 108; +pub const _SC_XOPEN_ENH_I18N: ::c_int = 109; +pub const _SC_XOPEN_LEGACY: ::c_int = 110; +pub const _SC_XOPEN_REALTIME: ::c_int = 111; +pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 112; +pub const _SC_XOPEN_SHM: ::c_int = 113; +pub const _SC_XOPEN_STREAMS: ::c_int = 114; +pub const _SC_XOPEN_UNIX: ::c_int = 115; +pub const _SC_XOPEN_VERSION: ::c_int = 116; +pub const _SC_XOPEN_XCU_VERSION: ::c_int = 117; +pub const _SC_IPV6: ::c_int = 118; +pub const _SC_RAW_SOCKETS: ::c_int = 119; +pub const _SC_SYMLOOP_MAX: ::c_int = 120; +pub const _SC_PHYS_PAGES: ::c_int = 121; + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = 0 as *mut _; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = 0 as *mut _; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = 0 as *mut _; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 1; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 2; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 3; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_ERRORCHECK; + +pub const SCHED_FIFO: ::c_int = 1; +pub const SCHED_OTHER: ::c_int = 2; +pub const SCHED_RR: ::c_int = 3; + +pub const FD_SETSIZE: usize = 1024; + +pub const ST_NOSUID: ::c_ulong = 2; + +pub const NI_MAXHOST: ::size_t = 1025; + +pub const RTLD_LOCAL: ::c_int = 0; +pub const RTLD_NODELETE: ::c_int = 0x1000; +pub const RTLD_NOLOAD: ::c_int = 0x2000; +pub const RTLD_GLOBAL: ::c_int = 0x100; + +pub const LOG_NTP: ::c_int = 12 << 3; +pub const LOG_SECURITY: ::c_int = 13 << 3; +pub const LOG_CONSOLE: ::c_int = 14 << 3; +pub const LOG_NFACILITIES: ::c_int = 24; + +pub const TIOCEXCL: ::c_uint = 0x2000740d; +pub const TIOCNXCL: ::c_uint = 0x2000740e; +pub const TIOCFLUSH: ::c_ulong = 0x80047410; +pub const TIOCGETA: ::c_uint = 0x402c7413; +pub const TIOCSETA: ::c_ulong = 0x802c7414; +pub const TIOCSETAW: ::c_ulong = 0x802c7415; +pub const TIOCSETAF: ::c_ulong = 0x802c7416; +pub const TIOCGETD: ::c_uint = 0x4004741a; +pub const TIOCSETD: ::c_ulong = 0x8004741b; +pub const TIOCGDRAINWAIT: ::c_uint = 0x40047456; +pub const TIOCSDRAINWAIT: ::c_ulong = 0x80047457; +pub const TIOCTIMESTAMP: ::c_uint = 0x40107459; +pub const TIOCMGDTRWAIT: ::c_uint = 0x4004745a; +pub const TIOCMSDTRWAIT: ::c_ulong = 0x8004745b; +pub const TIOCDRAIN: ::c_uint = 0x2000745e; +pub const TIOCEXT: ::c_ulong = 0x80047460; +pub const TIOCSCTTY: ::c_uint = 0x20007461; +pub const TIOCCONS: ::c_ulong = 0x80047462; +pub const TIOCGSID: ::c_uint = 0x40047463; +pub const TIOCSTAT: ::c_uint = 0x20007465; +pub const TIOCUCNTL: ::c_ulong = 0x80047466; +pub const TIOCSWINSZ: ::c_ulong = 0x80087467; +pub const TIOCGWINSZ: ::c_uint = 0x40087468; +pub const TIOCMGET: ::c_uint = 0x4004746a; +pub const TIOCM_LE: ::c_int = 0x1; +pub const TIOCM_DTR: ::c_int = 0x2; +pub const TIOCM_RTS: ::c_int = 0x4; +pub const TIOCM_ST: ::c_int = 0x8; +pub const TIOCM_SR: ::c_int = 0x10; +pub const TIOCM_CTS: ::c_int = 0x20; +pub const TIOCM_RI: ::c_int = 0x80; +pub const TIOCM_DSR: ::c_int = 0x100; +pub const TIOCM_CD: ::c_int = 0x40; +pub const TIOCM_CAR: ::c_int = 0x40; +pub const TIOCM_RNG: ::c_int = 0x80; +pub const TIOCMBIC: ::c_ulong = 0x8004746b; +pub const TIOCMBIS: ::c_ulong = 0x8004746c; +pub const TIOCMSET: ::c_ulong = 0x8004746d; +pub const TIOCSTART: ::c_uint = 0x2000746e; +pub const TIOCSTOP: ::c_uint = 0x2000746f; +pub const TIOCPKT: ::c_ulong = 0x80047470; +pub const TIOCPKT_DATA: ::c_int = 0x0; +pub const TIOCPKT_FLUSHREAD: ::c_int = 0x1; +pub const TIOCPKT_FLUSHWRITE: ::c_int = 0x2; +pub const TIOCPKT_STOP: ::c_int = 0x4; +pub const TIOCPKT_START: ::c_int = 0x8; +pub const TIOCPKT_NOSTOP: ::c_int = 0x10; +pub const TIOCPKT_DOSTOP: ::c_int = 0x20; +pub const TIOCPKT_IOCTL: ::c_int = 0x40; +pub const TIOCNOTTY: ::c_uint = 0x20007471; +pub const TIOCSTI: ::c_ulong = 0x80017472; +pub const TIOCOUTQ: ::c_uint = 0x40047473; +pub const TIOCSPGRP: ::c_ulong = 0x80047476; +pub const TIOCGPGRP: ::c_uint = 0x40047477; +pub const TIOCCDTR: ::c_uint = 0x20007478; +pub const TIOCSDTR: ::c_uint = 0x20007479; +pub const TIOCCBRK: ::c_uint = 0x2000747a; +pub const TIOCSBRK: ::c_uint = 0x2000747b; +pub const TTYDISC: ::c_int = 0x0; +pub const SLIPDISC: ::c_int = 0x4; +pub const PPPDISC: ::c_int = 0x5; +pub const NETGRAPHDISC: ::c_int = 0x6; + +pub const B0: speed_t = 0; +pub const B50: speed_t = 50; +pub const B75: speed_t = 75; +pub const B110: speed_t = 110; +pub const B134: speed_t = 134; +pub const B150: speed_t = 150; +pub const B200: speed_t = 200; +pub const B300: speed_t = 300; +pub const B600: speed_t = 600; +pub const B1200: speed_t = 1200; +pub const B1800: speed_t = 1800; +pub const B2400: speed_t = 2400; +pub const B4800: speed_t = 4800; +pub const B9600: speed_t = 9600; +pub const B19200: speed_t = 19200; +pub const B38400: speed_t = 38400; +pub const B7200: speed_t = 7200; +pub const B14400: speed_t = 14400; +pub const B28800: speed_t = 28800; +pub const B57600: speed_t = 57600; +pub const B76800: speed_t = 76800; +pub const B115200: speed_t = 115200; +pub const B230400: speed_t = 230400; +pub const EXTA: speed_t = 19200; +pub const EXTB: speed_t = 38400; + +pub const SEM_FAILED: *mut sem_t = 0 as *mut sem_t; + +pub const CRTSCTS: ::tcflag_t = 0x00030000; +pub const CCTS_OFLOW: ::tcflag_t = 0x00010000; +pub const CRTS_IFLOW: ::tcflag_t = 0x00020000; +pub const CDTR_IFLOW: ::tcflag_t = 0x00040000; +pub const CDSR_OFLOW: ::tcflag_t = 0x00080000; +pub const CCAR_OFLOW: ::tcflag_t = 0x00100000; +pub const VERASE2: usize = 7; +pub const OCRNL: ::tcflag_t = 0x10; +pub const ONOCR: ::tcflag_t = 0x20; +pub const ONLRET: ::tcflag_t = 0x40; + +pub const CMGROUP_MAX: usize = 16; + +// https://github.com/freebsd/freebsd/blob/master/sys/net/bpf.h +// sizeof(long) +pub const BPF_ALIGNMENT: ::c_int = 8; + +// Values for rtprio struct (prio field) and syscall (function argument) +pub const RTP_PRIO_MIN: ::c_ushort = 0; +pub const RTP_PRIO_MAX: ::c_ushort = 31; +pub const RTP_LOOKUP: ::c_int = 0; +pub const RTP_SET: ::c_int = 1; + +f! { + pub fn WIFCONTINUED(status: ::c_int) -> bool { + status == 0x13 + } + + pub fn WSTOPSIG(status: ::c_int) -> ::c_int { + status >> 8 + } + + pub fn WIFSIGNALED(status: ::c_int) -> bool { + (status & 0o177) != 0o177 && (status & 0o177) != 0 + } + + pub fn WIFSTOPPED(status: ::c_int) -> bool { + (status & 0o177) == 0o177 + } +} + +extern { + pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; + pub fn endutxent(); + pub fn getutxent() -> *mut utmpx; + pub fn getutxid(ut: *const utmpx) -> *mut utmpx; + pub fn getutxline(ut: *const utmpx) -> *mut utmpx; + pub fn pututxline(ut: *const utmpx) -> *mut utmpx; + pub fn setutxent(); + pub fn setresgid(rgid: ::gid_t, egid: ::gid_t, sgid: ::gid_t) -> ::c_int; + pub fn setresuid(ruid: ::uid_t, euid: ::uid_t, suid: ::uid_t) -> ::c_int; + pub fn getgrouplist(name: *const ::c_char, + basegid: ::gid_t, + groups: *mut ::gid_t, + ngroups: *mut ::c_int) -> ::c_int; + pub fn initgroups(name: *const ::c_char, basegid: ::gid_t) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwent_r50")] + pub fn getpwent_r(pwd: *mut ::passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::passwd) -> ::c_int; + pub fn getgrent_r(grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + pub fn mq_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::mqd_t; + pub fn mq_close(mqd: ::mqd_t) -> ::c_int; + pub fn mq_getattr(mqd: ::mqd_t, attr: *mut ::mq_attr) -> ::c_int; + pub fn mq_notify(mqd: ::mqd_t, notification: *const ::sigevent) -> ::c_int; + pub fn mq_receive(mqd: ::mqd_t, + msg_ptr: *mut ::c_char, + msg_len: ::size_t, + msq_prio: *mut ::c_uint) -> ::ssize_t; + pub fn mq_send(mqd: ::mqd_t, + msg_ptr: *const ::c_char, + msg_len: ::size_t, + msq_prio: ::c_uint) -> ::c_int; + pub fn mq_setattr(mqd: ::mqd_t, + newattr: *const ::mq_attr, + oldattr: *mut ::mq_attr) -> ::c_int; + pub fn mq_timedreceive(mqd: ::mqd_t, + msg_ptr: *mut ::c_char, + msg_len: ::size_t, + msq_prio: *mut ::c_uint, + abs_timeout: *const ::timespec) -> ::ssize_t; + pub fn mq_timedsend(mqd: ::mqd_t, + msg_ptr: *const ::c_char, + msg_len: ::size_t, + msq_prio: ::c_uint, + abs_timeout: *const ::timespec) -> ::c_int; + pub fn mq_unlink(name: *const ::c_char) -> ::c_int; +} + +#[link(name = "util")] +extern { + pub fn aio_read(aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_write(aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_fsync(op: ::c_int, aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_error(aiocbp: *const aiocb) -> ::c_int; + pub fn aio_return(aiocbp: *mut aiocb) -> ::ssize_t; + pub fn aio_suspend(aiocb_list: *const *const aiocb, nitems: ::c_int, + timeout: *const ::timespec) -> ::c_int; + pub fn aio_cancel(fd: ::c_int, aiocbp: *mut aiocb) -> ::c_int; + pub fn lio_listio(mode: ::c_int, aiocb_list: *const *mut aiocb, + nitems: ::c_int, sevp: *mut sigevent) -> ::c_int; + pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; + pub fn getnameinfo(sa: *const ::sockaddr, + salen: ::socklen_t, + host: *mut ::c_char, + hostlen: ::size_t, + serv: *mut ::c_char, + servlen: ::size_t, + flags: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "freebsd", link_name = "kevent@FBSD_1.0")] + pub fn kevent(kq: ::c_int, + changelist: *const ::kevent, + nchanges: ::c_int, + eventlist: *mut ::kevent, + nevents: ::c_int, + timeout: *const ::timespec) -> ::c_int; + pub fn mincore(addr: *const ::c_void, len: ::size_t, + vec: *mut ::c_char) -> ::c_int; + pub fn pwritev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off_t) -> ::ssize_t; + pub fn preadv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off_t) -> ::ssize_t; + pub fn sysctlnametomib(name: *const ::c_char, + mibp: *mut ::c_int, + sizep: *mut ::size_t) + -> ::c_int; + pub fn shm_open(name: *const ::c_char, oflag: ::c_int, mode: ::mode_t) + -> ::c_int; + pub fn sysctl(name: *const ::c_int, + namelen: ::c_uint, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *const ::c_void, + newlen: ::size_t) + -> ::c_int; + pub fn sysctlbyname(name: *const ::c_char, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *const ::c_void, + newlen: ::size_t) + -> ::c_int; + pub fn sched_setscheduler(pid: ::pid_t, + policy: ::c_int, + param: *const ::sched_param) -> ::c_int; + pub fn sched_getscheduler(pid: ::pid_t) -> ::c_int; + pub fn memrchr(cx: *const ::c_void, + c: ::c_int, + n: ::size_t) -> *mut ::c_void; + pub fn sendfile(fd: ::c_int, + s: ::c_int, + offset: ::off_t, + nbytes: ::size_t, + hdtr: *mut ::sf_hdtr, + sbytes: *mut ::off_t, + flags: ::c_int) -> ::c_int; + pub fn sigtimedwait(set: *const sigset_t, + info: *mut siginfo_t, + timeout: *const ::timespec) -> ::c_int; + pub fn sigwaitinfo(set: *const sigset_t, + info: *mut siginfo_t) -> ::c_int; + pub fn openpty(amaster: *mut ::c_int, + aslave: *mut ::c_int, + name: *mut ::c_char, + termp: *mut termios, + winp: *mut ::winsize) -> ::c_int; + pub fn forkpty(amaster: *mut ::c_int, + name: *mut ::c_char, + termp: *mut termios, + winp: *mut ::winsize) -> ::pid_t; + pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; + pub fn duplocale(base: ::locale_t) -> ::locale_t; + pub fn newlocale(mask: ::c_int, + locale: *const ::c_char, + base: ::locale_t) -> ::locale_t; + pub fn uselocale(loc: ::locale_t) -> ::locale_t; + pub fn querylocale(mask: ::c_int, loc: ::locale_t) -> *const ::c_char; + pub fn accept4(s: ::c_int, addr: *mut ::sockaddr, + addrlen: *mut ::socklen_t, flags: ::c_int) -> ::c_int; + pub fn pthread_set_name_np(tid: ::pthread_t, name: *const ::c_char); + pub fn pthread_attr_get_np(tid: ::pthread_t, + attr: *mut ::pthread_attr_t) -> ::c_int; + pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, + guardsize: *mut ::size_t) -> ::c_int; + pub fn pthread_attr_getstack(attr: *const ::pthread_attr_t, + stackaddr: *mut *mut ::c_void, + stacksize: *mut ::size_t) -> ::c_int; + pub fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, + pshared: ::c_int) -> ::c_int; + pub fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, + pshared: *mut ::c_int) -> ::c_int; + pub fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, + pshared: ::c_int) -> ::c_int; + pub fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, + pshared: *mut ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, + val: *mut ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, + val: ::c_int) -> ::c_int; + pub fn getpriority(which: ::c_int, who: ::c_int) -> ::c_int; + pub fn setpriority(which: ::c_int, who: ::c_int, prio: ::c_int) -> ::c_int; + pub fn rtprio(function: ::c_int, pid: ::pid_t, rtp: *mut rtprio) -> ::c_int; + + pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; + + #[cfg_attr(target_os = "freebsd", link_name = "mknodat@FBSD_1.1")] + pub fn mknodat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t, dev: dev_t) -> ::c_int; + pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t) -> ::c_int; + pub fn pthread_condattr_getclock(attr: *const pthread_condattr_t, + clock_id: *mut clockid_t) -> ::c_int; + pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, + clock_id: ::clockid_t) -> ::c_int; + pub fn sethostname(name: *const ::c_char, len: ::c_int) -> ::c_int; + pub fn sem_timedwait(sem: *mut sem_t, + abstime: *const ::timespec) -> ::c_int; + pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, + abstime: *const ::timespec) -> ::c_int; + pub fn pipe2(fds: *mut ::c_int, flags: ::c_int) -> ::c_int; + pub fn ppoll(fds: *mut ::pollfd, + nfds: ::nfds_t, + timeout: *const ::timespec, + sigmask: *const sigset_t) -> ::c_int; + pub fn settimeofday(tv: *const ::timeval, tz: *const ::timezone) -> ::c_int; + pub fn getdomainname(name: *mut ::c_char, len: ::c_int) -> ::c_int; + pub fn setdomainname(name: *const ::c_char, len: ::c_int) -> ::c_int; +} + +cfg_if! { + if #[cfg(target_os = "freebsd")] { + mod freebsd; + pub use self::freebsd::*; + } else if #[cfg(target_os = "dragonfly")] { + mod dragonfly; + pub use self::dragonfly::*; + } else { + // ... + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,557 @@ +use dox::{mem, Option}; + +pub type wchar_t = i32; +pub type off_t = i64; +pub type useconds_t = u32; +pub type blkcnt_t = i64; +pub type socklen_t = u32; +pub type sa_family_t = u8; +pub type pthread_t = ::uintptr_t; +pub type nfds_t = ::c_uint; + +s! { + pub struct sockaddr { + pub sa_len: u8, + pub sa_family: sa_family_t, + pub sa_data: [::c_char; 14], + } + + pub struct sockaddr_in6 { + pub sin6_len: u8, + pub sin6_family: sa_family_t, + pub sin6_port: ::in_port_t, + pub sin6_flowinfo: u32, + pub sin6_addr: ::in6_addr, + pub sin6_scope_id: u32, + } + + pub struct sockaddr_un { + pub sun_len: u8, + pub sun_family: sa_family_t, + pub sun_path: [c_char; 104] + } + + pub struct passwd { + pub pw_name: *mut ::c_char, + pub pw_passwd: *mut ::c_char, + pub pw_uid: ::uid_t, + pub pw_gid: ::gid_t, + pub pw_change: ::time_t, + pub pw_class: *mut ::c_char, + pub pw_gecos: *mut ::c_char, + pub pw_dir: *mut ::c_char, + pub pw_shell: *mut ::c_char, + pub pw_expire: ::time_t, + + #[cfg(not(any(target_os = "macos", + target_os = "ios", + target_os = "netbsd", + target_os = "openbsd")))] + pub pw_fields: ::c_int, + } + + pub struct ifaddrs { + pub ifa_next: *mut ifaddrs, + pub ifa_name: *mut ::c_char, + pub ifa_flags: ::c_uint, + pub ifa_addr: *mut ::sockaddr, + pub ifa_netmask: *mut ::sockaddr, + pub ifa_dstaddr: *mut ::sockaddr, + pub ifa_data: *mut ::c_void + } + + pub struct fd_set { + #[cfg(all(target_pointer_width = "64", + any(target_os = "freebsd", target_os = "dragonfly")))] + fds_bits: [i64; FD_SETSIZE / 64], + #[cfg(not(all(target_pointer_width = "64", + any(target_os = "freebsd", target_os = "dragonfly"))))] + fds_bits: [i32; FD_SETSIZE / 32], + } + + pub struct tm { + pub tm_sec: ::c_int, + pub tm_min: ::c_int, + pub tm_hour: ::c_int, + pub tm_mday: ::c_int, + pub tm_mon: ::c_int, + pub tm_year: ::c_int, + pub tm_wday: ::c_int, + pub tm_yday: ::c_int, + pub tm_isdst: ::c_int, + pub tm_gmtoff: ::c_long, + pub tm_zone: *mut ::c_char, + } + + pub struct utsname { + #[cfg(not(target_os = "dragonfly"))] + pub sysname: [::c_char; 256], + #[cfg(target_os = "dragonfly")] + pub sysname: [::c_char; 32], + #[cfg(not(target_os = "dragonfly"))] + pub nodename: [::c_char; 256], + #[cfg(target_os = "dragonfly")] + pub nodename: [::c_char; 32], + #[cfg(not(target_os = "dragonfly"))] + pub release: [::c_char; 256], + #[cfg(target_os = "dragonfly")] + pub release: [::c_char; 32], + #[cfg(not(target_os = "dragonfly"))] + pub version: [::c_char; 256], + #[cfg(target_os = "dragonfly")] + pub version: [::c_char; 32], + #[cfg(not(target_os = "dragonfly"))] + pub machine: [::c_char; 256], + #[cfg(target_os = "dragonfly")] + pub machine: [::c_char; 32], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::c_int, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::socklen_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::socklen_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct fsid_t { + __fsid_val: [::int32_t; 2], + } + + pub struct if_nameindex { + pub if_index: ::c_uint, + pub if_name: *mut ::c_char, + } +} + +pub const LC_ALL: ::c_int = 0; +pub const LC_COLLATE: ::c_int = 1; +pub const LC_CTYPE: ::c_int = 2; +pub const LC_MONETARY: ::c_int = 3; +pub const LC_NUMERIC: ::c_int = 4; +pub const LC_TIME: ::c_int = 5; +pub const LC_MESSAGES: ::c_int = 6; + +pub const FIOCLEX: ::c_ulong = 0x20006601; +pub const FIONBIO: ::c_ulong = 0x8004667e; + +pub const PATH_MAX: ::c_int = 1024; + +pub const SA_ONSTACK: ::c_int = 0x0001; +pub const SA_SIGINFO: ::c_int = 0x0040; +pub const SA_RESTART: ::c_int = 0x0002; +pub const SA_RESETHAND: ::c_int = 0x0004; +pub const SA_NOCLDSTOP: ::c_int = 0x0008; +pub const SA_NODEFER: ::c_int = 0x0010; +pub const SA_NOCLDWAIT: ::c_int = 0x0020; + +pub const SS_ONSTACK: ::c_int = 1; +pub const SS_DISABLE: ::c_int = 4; + +pub const SIGCHLD: ::c_int = 20; +pub const SIGBUS: ::c_int = 10; +pub const SIGUSR1: ::c_int = 30; +pub const SIGUSR2: ::c_int = 31; +pub const SIGCONT: ::c_int = 19; +pub const SIGSTOP: ::c_int = 17; +pub const SIGTSTP: ::c_int = 18; +pub const SIGURG: ::c_int = 16; +pub const SIGIO: ::c_int = 23; +pub const SIGSYS: ::c_int = 12; +pub const SIGTTIN: ::c_int = 21; +pub const SIGTTOU: ::c_int = 22; +pub const SIGXCPU: ::c_int = 24; +pub const SIGXFSZ: ::c_int = 25; +pub const SIGVTALRM: ::c_int = 26; +pub const SIGPROF: ::c_int = 27; +pub const SIGWINCH: ::c_int = 28; +pub const SIGINFO: ::c_int = 29; + +pub const SIG_SETMASK: ::c_int = 3; +pub const SIG_BLOCK: ::c_int = 0x1; +pub const SIG_UNBLOCK: ::c_int = 0x2; + +pub const IP_MULTICAST_IF: ::c_int = 9; +pub const IP_MULTICAST_TTL: ::c_int = 10; +pub const IP_MULTICAST_LOOP: ::c_int = 11; + +pub const IPV6_UNICAST_HOPS: ::c_int = 4; +pub const IPV6_MULTICAST_IF: ::c_int = 9; +pub const IPV6_MULTICAST_HOPS: ::c_int = 10; +pub const IPV6_MULTICAST_LOOP: ::c_int = 11; +pub const IPV6_V6ONLY: ::c_int = 27; + +pub const ST_RDONLY: ::c_ulong = 1; + +pub const SCM_RIGHTS: ::c_int = 0x01; + +pub const NCCS: usize = 20; + +pub const O_ACCMODE: ::c_int = 0x3; +pub const O_RDONLY: ::c_int = 0; +pub const O_WRONLY: ::c_int = 1; +pub const O_RDWR: ::c_int = 2; +pub const O_APPEND: ::c_int = 8; +pub const O_CREAT: ::c_int = 512; +pub const O_TRUNC: ::c_int = 1024; +pub const O_EXCL: ::c_int = 2048; +pub const O_ASYNC: ::c_int = 0x40; +pub const O_SYNC: ::c_int = 0x80; +pub const O_NONBLOCK: ::c_int = 0x4; +pub const O_NOFOLLOW: ::c_int = 0x100; +pub const O_SHLOCK: ::c_int = 0x10; +pub const O_EXLOCK: ::c_int = 0x20; +pub const O_FSYNC: ::c_int = O_SYNC; +pub const O_NDELAY: ::c_int = O_NONBLOCK; + +pub const F_GETOWN: ::c_int = 5; +pub const F_SETOWN: ::c_int = 6; + +pub const MNT_FORCE: ::c_int = 0x80000; + +pub const Q_SYNC: ::c_int = 0x600; +pub const Q_QUOTAON: ::c_int = 0x100; +pub const Q_QUOTAOFF: ::c_int = 0x200; + +pub const TCIOFF: ::c_int = 3; +pub const TCION: ::c_int = 4; +pub const TCOOFF: ::c_int = 1; +pub const TCOON: ::c_int = 2; +pub const TCIFLUSH: ::c_int = 1; +pub const TCOFLUSH: ::c_int = 2; +pub const TCIOFLUSH: ::c_int = 3; +pub const TCSANOW: ::c_int = 0; +pub const TCSADRAIN: ::c_int = 1; +pub const TCSAFLUSH: ::c_int = 2; +pub const VEOF: usize = 0; +pub const VEOL: usize = 1; +pub const VEOL2: usize = 2; +pub const VERASE: usize = 3; +pub const VWERASE: usize = 4; +pub const VKILL: usize = 5; +pub const VREPRINT: usize = 6; +pub const VINTR: usize = 8; +pub const VQUIT: usize = 9; +pub const VSUSP: usize = 10; +pub const VDSUSP: usize = 11; +pub const VSTART: usize = 12; +pub const VSTOP: usize = 13; +pub const VLNEXT: usize = 14; +pub const VDISCARD: usize = 15; +pub const VMIN: usize = 16; +pub const VTIME: usize = 17; +pub const VSTATUS: usize = 18; +pub const _POSIX_VDISABLE: ::cc_t = 0xff; +pub const IGNBRK: ::tcflag_t = 0x00000001; +pub const BRKINT: ::tcflag_t = 0x00000002; +pub const IGNPAR: ::tcflag_t = 0x00000004; +pub const PARMRK: ::tcflag_t = 0x00000008; +pub const INPCK: ::tcflag_t = 0x00000010; +pub const ISTRIP: ::tcflag_t = 0x00000020; +pub const INLCR: ::tcflag_t = 0x00000040; +pub const IGNCR: ::tcflag_t = 0x00000080; +pub const ICRNL: ::tcflag_t = 0x00000100; +pub const IXON: ::tcflag_t = 0x00000200; +pub const IXOFF: ::tcflag_t = 0x00000400; +pub const IXANY: ::tcflag_t = 0x00000800; +pub const IMAXBEL: ::tcflag_t = 0x00002000; +pub const OPOST: ::tcflag_t = 0x1; +pub const ONLCR: ::tcflag_t = 0x2; +pub const OXTABS: ::tcflag_t = 0x4; +pub const ONOEOT: ::tcflag_t = 0x8; +pub const CIGNORE: ::tcflag_t = 0x00000001; +pub const CSIZE: ::tcflag_t = 0x00000300; +pub const CS5: ::tcflag_t = 0x00000000; +pub const CS6: ::tcflag_t = 0x00000100; +pub const CS7: ::tcflag_t = 0x00000200; +pub const CS8: ::tcflag_t = 0x00000300; +pub const CSTOPB: ::tcflag_t = 0x00000400; +pub const CREAD: ::tcflag_t = 0x00000800; +pub const PARENB: ::tcflag_t = 0x00001000; +pub const PARODD: ::tcflag_t = 0x00002000; +pub const HUPCL: ::tcflag_t = 0x00004000; +pub const CLOCAL: ::tcflag_t = 0x00008000; +pub const ECHOKE: ::tcflag_t = 0x00000001; +pub const ECHOE: ::tcflag_t = 0x00000002; +pub const ECHOK: ::tcflag_t = 0x00000004; +pub const ECHO: ::tcflag_t = 0x00000008; +pub const ECHONL: ::tcflag_t = 0x00000010; +pub const ECHOPRT: ::tcflag_t = 0x00000020; +pub const ECHOCTL: ::tcflag_t = 0x00000040; +pub const ISIG: ::tcflag_t = 0x00000080; +pub const ICANON: ::tcflag_t = 0x00000100; +pub const ALTWERASE: ::tcflag_t = 0x00000200; +pub const IEXTEN: ::tcflag_t = 0x00000400; +pub const EXTPROC: ::tcflag_t = 0x00000800; +pub const TOSTOP: ::tcflag_t = 0x00400000; +pub const FLUSHO: ::tcflag_t = 0x00800000; +pub const NOKERNINFO: ::tcflag_t = 0x02000000; +pub const PENDIN: ::tcflag_t = 0x20000000; +pub const NOFLSH: ::tcflag_t = 0x80000000; +pub const MDMBUF: ::tcflag_t = 0x00100000; + +pub const WNOHANG: ::c_int = 0x00000001; +pub const WUNTRACED: ::c_int = 0x00000002; + +pub const RTLD_LAZY: ::c_int = 0x1; +pub const RTLD_NOW: ::c_int = 0x2; +pub const RTLD_NEXT: *mut ::c_void = -1isize as *mut ::c_void; +pub const RTLD_DEFAULT: *mut ::c_void = -2isize as *mut ::c_void; +pub const RTLD_SELF: *mut ::c_void = -3isize as *mut ::c_void; + +pub const LOG_CRON: ::c_int = 9 << 3; +pub const LOG_AUTHPRIV: ::c_int = 10 << 3; +pub const LOG_FTP: ::c_int = 11 << 3; +pub const LOG_PERROR: ::c_int = 0x20; + +pub const TCP_MAXSEG: ::c_int = 2; + +pub const PIPE_BUF: usize = 512; + +pub const POLLIN: ::c_short = 0x1; +pub const POLLPRI: ::c_short = 0x2; +pub const POLLOUT: ::c_short = 0x4; +pub const POLLERR: ::c_short = 0x8; +pub const POLLHUP: ::c_short = 0x10; +pub const POLLNVAL: ::c_short = 0x20; +pub const POLLRDNORM: ::c_short = 0x040; +pub const POLLWRNORM: ::c_short = 0x004; +pub const POLLRDBAND: ::c_short = 0x080; +pub const POLLWRBAND: ::c_short = 0x100; + +f! { + pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { + let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; + let fd = fd as usize; + (*set).fds_bits[fd / bits] &= !(1 << (fd % bits)); + return + } + + pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { + let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; + let fd = fd as usize; + return ((*set).fds_bits[fd / bits] & (1 << (fd % bits))) != 0 + } + + pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { + let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; + let fd = fd as usize; + (*set).fds_bits[fd / bits] |= 1 << (fd % bits); + return + } + + pub fn FD_ZERO(set: *mut fd_set) -> () { + for slot in (*set).fds_bits.iter_mut() { + *slot = 0; + } + } + + pub fn WTERMSIG(status: ::c_int) -> ::c_int { + status & 0o177 + } + + pub fn WIFEXITED(status: ::c_int) -> bool { + (status & 0o177) == 0 + } + + pub fn WEXITSTATUS(status: ::c_int) -> ::c_int { + status >> 8 + } + + pub fn WCOREDUMP(status: ::c_int) -> bool { + (status & 0o200) != 0 + } + + pub fn QCMD(cmd: ::c_int, type_: ::c_int) -> ::c_int { + (cmd << 8) | (type_ & 0x00ff) + } +} + +extern { + pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; + pub fn freeifaddrs(ifa: *mut ::ifaddrs); + pub fn setgroups(ngroups: ::c_int, + ptr: *const ::gid_t) -> ::c_int; + pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; + pub fn kqueue() -> ::c_int; + pub fn unmount(target: *const ::c_char, arg: ::c_int) -> ::c_int; + pub fn syscall(num: ::c_int, ...) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwent50")] + pub fn getpwent() -> *mut passwd; + pub fn setpwent(); + pub fn endpwent(); + pub fn setgrent(); + pub fn endgrent(); + pub fn getgrent() -> *mut ::group; + + pub fn getprogname() -> *const ::c_char; + pub fn setprogname(name: *const ::c_char); + pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int; + pub fn if_nameindex() -> *mut if_nameindex; + pub fn if_freenameindex(ptr: *mut if_nameindex); + + pub fn getpeereid(socket: ::c_int, + euid: *mut ::uid_t, + egid: *mut ::gid_t) -> ::c_int; + + #[cfg_attr(target_os = "macos", link_name = "glob$INODE64")] + #[cfg_attr(target_os = "netbsd", link_name = "__glob30")] + #[cfg_attr(target_os = "freebsd", link_name = "glob@FBSD_1.0")] + pub fn glob(pattern: *const ::c_char, + flags: ::c_int, + errfunc: Option ::c_int>, + pglob: *mut ::glob_t) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__globfree30")] + #[cfg_attr(target_os = "freebsd", link_name = "globfree@FBSD_1.0")] + pub fn globfree(pglob: *mut ::glob_t); + + pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + pub fn shm_unlink(name: *const ::c_char) -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), + link_name = "seekdir$INODE64")] + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "seekdir$INODE64$UNIX2003")] + pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); + + #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), + link_name = "telldir$INODE64")] + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "telldir$INODE64$UNIX2003")] + pub fn telldir(dirp: *mut ::DIR) -> ::c_long; + pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "msync$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__msync13")] + pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "recvfrom$UNIX2003")] + pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, + flags: ::c_int, addr: *mut ::sockaddr, + addrlen: *mut ::socklen_t) -> ::ssize_t; + pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; + pub fn futimes(fd: ::c_int, times: *const ::timeval) -> ::c_int; + pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "bind$UNIX2003")] + pub fn bind(socket: ::c_int, address: *const ::sockaddr, + address_len: ::socklen_t) -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "writev$UNIX2003")] + pub fn writev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "readv$UNIX2003")] + pub fn readv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "sendmsg$UNIX2003")] + pub fn sendmsg(fd: ::c_int, + msg: *const ::msghdr, + flags: ::c_int) -> ::ssize_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "recvmsg$UNIX2003")] + pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) + -> ::ssize_t; + + pub fn sync(); + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] + pub fn getgrgid_r(uid: ::uid_t, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "sigaltstack$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")] + pub fn sigaltstack(ss: *const stack_t, + oss: *mut stack_t) -> ::c_int; + pub fn sem_close(sem: *mut sem_t) -> ::c_int; + pub fn getdtablesize() -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] + pub fn getgrnam_r(name: *const ::c_char, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_sigmask$UNIX2003")] + pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, + oldset: *mut sigset_t) -> ::c_int; + pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; + pub fn getgrnam(name: *const ::c_char) -> *mut ::group; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_cancel$UNIX2003")] + pub fn pthread_cancel(thread: ::pthread_t) -> ::c_int; + pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; + pub fn sem_unlink(name: *const ::c_char) -> ::c_int; + pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] + pub fn getpwnam_r(name: *const ::c_char, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] + pub fn getpwuid_r(uid: ::uid_t, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch ="x86"), + link_name = "sigwait$UNIX2003")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] + pub fn sigwait(set: *const sigset_t, + sig: *mut ::c_int) -> ::c_int; + pub fn pthread_atfork(prepare: Option, + parent: Option, + child: Option) -> ::c_int; + pub fn getgrgid(gid: ::gid_t) -> *mut ::group; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "popen$UNIX2003")] + pub fn popen(command: *const c_char, + mode: *const c_char) -> *mut ::FILE; + pub fn faccessat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::c_int, flags: ::c_int) -> ::c_int; + pub fn pthread_create(native: *mut ::pthread_t, + attr: *const ::pthread_attr_t, + f: extern fn(*mut ::c_void) -> *mut ::c_void, + value: *mut ::c_void) -> ::c_int; +} + +cfg_if! { + if #[cfg(any(target_os = "macos", target_os = "ios"))] { + mod apple; + pub use self::apple::*; + } else if #[cfg(any(target_os = "openbsd", target_os = "netbsd", + target_os = "bitrig"))] { + mod netbsdlike; + pub use self::netbsdlike::*; + } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] { + mod freebsdlike; + pub use self::freebsdlike::*; + } else { + // Unknown target_os + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,657 @@ +pub type time_t = i64; +pub type mode_t = u32; +pub type nlink_t = ::uint32_t; +pub type ino_t = ::uint64_t; +pub type pthread_key_t = ::c_int; +pub type rlim_t = u64; +pub type speed_t = ::c_uint; +pub type tcflag_t = ::c_uint; +pub type nl_item = c_long; +pub type clockid_t = ::c_int; +pub type id_t = ::uint32_t; +pub type sem_t = *mut sem; + +pub enum timezone {} +pub enum sem {} + +s! { + pub struct sigaction { + pub sa_sigaction: ::sighandler_t, + pub sa_mask: ::sigset_t, + pub sa_flags: ::c_int, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_size: ::size_t, + pub ss_flags: ::c_int, + } + + pub struct sockaddr_in { + pub sin_len: u8, + pub sin_family: ::sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + pub sin_zero: [::int8_t; 8], + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_cc: [::cc_t; ::NCCS], + pub c_ispeed: ::c_int, + pub c_ospeed: ::c_int, + } + + pub struct flock { + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_pid: ::pid_t, + pub l_type: ::c_short, + pub l_whence: ::c_short, + } +} + +pub const D_T_FMT: ::nl_item = 0; +pub const D_FMT: ::nl_item = 1; +pub const T_FMT: ::nl_item = 2; +pub const T_FMT_AMPM: ::nl_item = 3; +pub const AM_STR: ::nl_item = 4; +pub const PM_STR: ::nl_item = 5; + +pub const DAY_1: ::nl_item = 6; +pub const DAY_2: ::nl_item = 7; +pub const DAY_3: ::nl_item = 8; +pub const DAY_4: ::nl_item = 9; +pub const DAY_5: ::nl_item = 10; +pub const DAY_6: ::nl_item = 11; +pub const DAY_7: ::nl_item = 12; + +pub const ABDAY_1: ::nl_item = 13; +pub const ABDAY_2: ::nl_item = 14; +pub const ABDAY_3: ::nl_item = 15; +pub const ABDAY_4: ::nl_item = 16; +pub const ABDAY_5: ::nl_item = 17; +pub const ABDAY_6: ::nl_item = 18; +pub const ABDAY_7: ::nl_item = 19; + +pub const MON_1: ::nl_item = 20; +pub const MON_2: ::nl_item = 21; +pub const MON_3: ::nl_item = 22; +pub const MON_4: ::nl_item = 23; +pub const MON_5: ::nl_item = 24; +pub const MON_6: ::nl_item = 25; +pub const MON_7: ::nl_item = 26; +pub const MON_8: ::nl_item = 27; +pub const MON_9: ::nl_item = 28; +pub const MON_10: ::nl_item = 29; +pub const MON_11: ::nl_item = 30; +pub const MON_12: ::nl_item = 31; + +pub const ABMON_1: ::nl_item = 32; +pub const ABMON_2: ::nl_item = 33; +pub const ABMON_3: ::nl_item = 34; +pub const ABMON_4: ::nl_item = 35; +pub const ABMON_5: ::nl_item = 36; +pub const ABMON_6: ::nl_item = 37; +pub const ABMON_7: ::nl_item = 38; +pub const ABMON_8: ::nl_item = 39; +pub const ABMON_9: ::nl_item = 40; +pub const ABMON_10: ::nl_item = 41; +pub const ABMON_11: ::nl_item = 42; +pub const ABMON_12: ::nl_item = 43; + +pub const RADIXCHAR: ::nl_item = 44; +pub const THOUSEP: ::nl_item = 45; +pub const YESSTR: ::nl_item = 46; +pub const YESEXPR: ::nl_item = 47; +pub const NOSTR: ::nl_item = 48; +pub const NOEXPR: ::nl_item = 49; +pub const CRNCYSTR: ::nl_item = 50; + +pub const CODESET: ::nl_item = 51; + +pub const EXIT_FAILURE : ::c_int = 1; +pub const EXIT_SUCCESS : ::c_int = 0; +pub const RAND_MAX : ::c_int = 2147483647; +pub const EOF : ::c_int = -1; +pub const SEEK_SET : ::c_int = 0; +pub const SEEK_CUR : ::c_int = 1; +pub const SEEK_END : ::c_int = 2; +pub const _IOFBF : ::c_int = 0; +pub const _IONBF : ::c_int = 2; +pub const _IOLBF : ::c_int = 1; +pub const BUFSIZ : ::c_uint = 1024; +pub const FOPEN_MAX : ::c_uint = 20; +pub const FILENAME_MAX : ::c_uint = 1024; +pub const L_tmpnam : ::c_uint = 1024; +pub const O_NOCTTY : ::c_int = 32768; +pub const S_IFIFO : mode_t = 4096; +pub const S_IFCHR : mode_t = 8192; +pub const S_IFBLK : mode_t = 24576; +pub const S_IFDIR : mode_t = 16384; +pub const S_IFREG : mode_t = 32768; +pub const S_IFLNK : mode_t = 40960; +pub const S_IFSOCK : mode_t = 49152; +pub const S_IFMT : mode_t = 61440; +pub const S_IEXEC : mode_t = 64; +pub const S_IWRITE : mode_t = 128; +pub const S_IREAD : mode_t = 256; +pub const S_IRWXU : mode_t = 448; +pub const S_IXUSR : mode_t = 64; +pub const S_IWUSR : mode_t = 128; +pub const S_IRUSR : mode_t = 256; +pub const S_IRWXG : mode_t = 56; +pub const S_IXGRP : mode_t = 8; +pub const S_IWGRP : mode_t = 16; +pub const S_IRGRP : mode_t = 32; +pub const S_IRWXO : mode_t = 7; +pub const S_IXOTH : mode_t = 1; +pub const S_IWOTH : mode_t = 2; +pub const S_IROTH : mode_t = 4; +pub const F_OK : ::c_int = 0; +pub const R_OK : ::c_int = 4; +pub const W_OK : ::c_int = 2; +pub const X_OK : ::c_int = 1; +pub const STDIN_FILENO : ::c_int = 0; +pub const STDOUT_FILENO : ::c_int = 1; +pub const STDERR_FILENO : ::c_int = 2; +pub const F_LOCK : ::c_int = 1; +pub const F_TEST : ::c_int = 3; +pub const F_TLOCK : ::c_int = 2; +pub const F_ULOCK : ::c_int = 0; +pub const F_GETLK: ::c_int = 7; +pub const F_SETLK: ::c_int = 8; +pub const F_SETLKW: ::c_int = 9; +pub const SIGHUP : ::c_int = 1; +pub const SIGINT : ::c_int = 2; +pub const SIGQUIT : ::c_int = 3; +pub const SIGILL : ::c_int = 4; +pub const SIGABRT : ::c_int = 6; +pub const SIGEMT: ::c_int = 7; +pub const SIGFPE : ::c_int = 8; +pub const SIGKILL : ::c_int = 9; +pub const SIGSEGV : ::c_int = 11; +pub const SIGPIPE : ::c_int = 13; +pub const SIGALRM : ::c_int = 14; +pub const SIGTERM : ::c_int = 15; +pub const SIGSTKSZ : ::size_t = 40960; + +pub const PROT_NONE : ::c_int = 0; +pub const PROT_READ : ::c_int = 1; +pub const PROT_WRITE : ::c_int = 2; +pub const PROT_EXEC : ::c_int = 4; + +pub const MAP_FILE : ::c_int = 0x0000; +pub const MAP_SHARED : ::c_int = 0x0001; +pub const MAP_PRIVATE : ::c_int = 0x0002; +pub const MAP_FIXED : ::c_int = 0x0010; +pub const MAP_ANON : ::c_int = 0x1000; + +pub const MAP_FAILED : *mut ::c_void = !0 as *mut ::c_void; + +pub const MCL_CURRENT : ::c_int = 0x0001; +pub const MCL_FUTURE : ::c_int = 0x0002; + +pub const MS_ASYNC : ::c_int = 0x0001; + +pub const EPERM : ::c_int = 1; +pub const ENOENT : ::c_int = 2; +pub const ESRCH : ::c_int = 3; +pub const EINTR : ::c_int = 4; +pub const EIO : ::c_int = 5; +pub const ENXIO : ::c_int = 6; +pub const E2BIG : ::c_int = 7; +pub const ENOEXEC : ::c_int = 8; +pub const EBADF : ::c_int = 9; +pub const ECHILD : ::c_int = 10; +pub const EDEADLK : ::c_int = 11; +pub const ENOMEM : ::c_int = 12; +pub const EACCES : ::c_int = 13; +pub const EFAULT : ::c_int = 14; +pub const ENOTBLK : ::c_int = 15; +pub const EBUSY : ::c_int = 16; +pub const EEXIST : ::c_int = 17; +pub const EXDEV : ::c_int = 18; +pub const ENODEV : ::c_int = 19; +pub const ENOTDIR : ::c_int = 20; +pub const EISDIR : ::c_int = 21; +pub const EINVAL : ::c_int = 22; +pub const ENFILE : ::c_int = 23; +pub const EMFILE : ::c_int = 24; +pub const ENOTTY : ::c_int = 25; +pub const ETXTBSY : ::c_int = 26; +pub const EFBIG : ::c_int = 27; +pub const ENOSPC : ::c_int = 28; +pub const ESPIPE : ::c_int = 29; +pub const EROFS : ::c_int = 30; +pub const EMLINK : ::c_int = 31; +pub const EPIPE : ::c_int = 32; +pub const EDOM : ::c_int = 33; +pub const ERANGE : ::c_int = 34; +pub const EAGAIN : ::c_int = 35; +pub const EWOULDBLOCK : ::c_int = 35; +pub const EINPROGRESS : ::c_int = 36; +pub const EALREADY : ::c_int = 37; +pub const ENOTSOCK : ::c_int = 38; +pub const EDESTADDRREQ : ::c_int = 39; +pub const EMSGSIZE : ::c_int = 40; +pub const EPROTOTYPE : ::c_int = 41; +pub const ENOPROTOOPT : ::c_int = 42; +pub const EPROTONOSUPPORT : ::c_int = 43; +pub const ESOCKTNOSUPPORT : ::c_int = 44; +pub const EOPNOTSUPP : ::c_int = 45; +pub const EPFNOSUPPORT : ::c_int = 46; +pub const EAFNOSUPPORT : ::c_int = 47; +pub const EADDRINUSE : ::c_int = 48; +pub const EADDRNOTAVAIL : ::c_int = 49; +pub const ENETDOWN : ::c_int = 50; +pub const ENETUNREACH : ::c_int = 51; +pub const ENETRESET : ::c_int = 52; +pub const ECONNABORTED : ::c_int = 53; +pub const ECONNRESET : ::c_int = 54; +pub const ENOBUFS : ::c_int = 55; +pub const EISCONN : ::c_int = 56; +pub const ENOTCONN : ::c_int = 57; +pub const ESHUTDOWN : ::c_int = 58; +pub const ETOOMANYREFS : ::c_int = 59; +pub const ETIMEDOUT : ::c_int = 60; +pub const ECONNREFUSED : ::c_int = 61; +pub const ELOOP : ::c_int = 62; +pub const ENAMETOOLONG : ::c_int = 63; +pub const EHOSTDOWN : ::c_int = 64; +pub const EHOSTUNREACH : ::c_int = 65; +pub const ENOTEMPTY : ::c_int = 66; +pub const EPROCLIM : ::c_int = 67; +pub const EUSERS : ::c_int = 68; +pub const EDQUOT : ::c_int = 69; +pub const ESTALE : ::c_int = 70; +pub const EREMOTE : ::c_int = 71; +pub const EBADRPC : ::c_int = 72; +pub const ERPCMISMATCH : ::c_int = 73; +pub const EPROGUNAVAIL : ::c_int = 74; +pub const EPROGMISMATCH : ::c_int = 75; +pub const EPROCUNAVAIL : ::c_int = 76; +pub const ENOLCK : ::c_int = 77; +pub const ENOSYS : ::c_int = 78; +pub const EFTYPE : ::c_int = 79; +pub const EAUTH : ::c_int = 80; +pub const ENEEDAUTH : ::c_int = 81; + +pub const F_DUPFD : ::c_int = 0; +pub const F_GETFD : ::c_int = 1; +pub const F_SETFD : ::c_int = 2; +pub const F_GETFL : ::c_int = 3; +pub const F_SETFL : ::c_int = 4; + +pub const SIGTRAP : ::c_int = 5; + +pub const GLOB_APPEND : ::c_int = 0x0001; +pub const GLOB_DOOFFS : ::c_int = 0x0002; +pub const GLOB_ERR : ::c_int = 0x0004; +pub const GLOB_MARK : ::c_int = 0x0008; +pub const GLOB_NOCHECK : ::c_int = 0x0010; +pub const GLOB_NOSORT : ::c_int = 0x0020; +pub const GLOB_NOESCAPE : ::c_int = 0x1000; + +pub const GLOB_NOSPACE : ::c_int = -1; +pub const GLOB_ABORTED : ::c_int = -2; +pub const GLOB_NOMATCH : ::c_int = -3; +pub const GLOB_NOSYS : ::c_int = -4; + +pub const POSIX_MADV_NORMAL : ::c_int = 0; +pub const POSIX_MADV_RANDOM : ::c_int = 1; +pub const POSIX_MADV_SEQUENTIAL : ::c_int = 2; +pub const POSIX_MADV_WILLNEED : ::c_int = 3; +pub const POSIX_MADV_DONTNEED : ::c_int = 4; + +pub const PTHREAD_CREATE_JOINABLE : ::c_int = 0; +pub const PTHREAD_CREATE_DETACHED : ::c_int = 1; + +// http://man.openbsd.org/OpenBSD-current/man2/clock_getres.2 +// The man page says clock_gettime(3) can accept various values as clockid_t but +// http://fxr.watson.org/fxr/source/kern/kern_time.c?v=OPENBSD;im=excerpts#L161 +// the implementation rejects anything other than the below two +// +// http://netbsd.gw.com/cgi-bin/man-cgi?clock_gettime +// https://github.com/jsonn/src/blob/HEAD/sys/kern/subr_time.c#L222 +// Basically the same goes for NetBSD +pub const CLOCK_REALTIME: ::clockid_t = 0; +pub const CLOCK_MONOTONIC: ::clockid_t = 3; + +pub const RLIMIT_CPU: ::c_int = 0; +pub const RLIMIT_FSIZE: ::c_int = 1; +pub const RLIMIT_DATA: ::c_int = 2; +pub const RLIMIT_STACK: ::c_int = 3; +pub const RLIMIT_CORE: ::c_int = 4; +pub const RLIMIT_RSS: ::c_int = 5; +pub const RLIMIT_MEMLOCK: ::c_int = 6; +pub const RLIMIT_NPROC: ::c_int = 7; +pub const RLIMIT_NOFILE: ::c_int = 8; + +pub const RLIM_INFINITY: rlim_t = 0x7fff_ffff_ffff_ffff; +pub const RLIM_SAVED_MAX: rlim_t = RLIM_INFINITY; +pub const RLIM_SAVED_CUR: rlim_t = RLIM_INFINITY; + +pub const RUSAGE_SELF: ::c_int = 0; +pub const RUSAGE_CHILDREN: ::c_int = -1; + +pub const MADV_NORMAL : ::c_int = 0; +pub const MADV_RANDOM : ::c_int = 1; +pub const MADV_SEQUENTIAL : ::c_int = 2; +pub const MADV_WILLNEED : ::c_int = 3; +pub const MADV_DONTNEED : ::c_int = 4; +pub const MADV_FREE : ::c_int = 6; + +pub const AF_UNSPEC: ::c_int = 0; +pub const AF_LOCAL: ::c_int = 1; +pub const AF_UNIX: ::c_int = AF_LOCAL; +pub const AF_INET: ::c_int = 2; +pub const AF_IMPLINK: ::c_int = 3; +pub const AF_PUP: ::c_int = 4; +pub const AF_CHAOS: ::c_int = 5; +pub const AF_NS: ::c_int = 6; +pub const AF_ISO: ::c_int = 7; +pub const AF_OSI: ::c_int = AF_ISO; +pub const AF_DATAKIT: ::c_int = 9; +pub const AF_CCITT: ::c_int = 10; +pub const AF_SNA: ::c_int = 11; +pub const AF_DECnet: ::c_int = 12; +pub const AF_DLI: ::c_int = 13; +pub const AF_LAT: ::c_int = 14; +pub const AF_HYLINK: ::c_int = 15; +pub const AF_APPLETALK: ::c_int = 16; +pub const AF_LINK: ::c_int = 18; +pub const pseudo_AF_XTP: ::c_int = 19; +pub const AF_COIP: ::c_int = 20; +pub const AF_CNT: ::c_int = 21; +pub const pseudo_AF_RTIP: ::c_int = 22; +pub const AF_IPX: ::c_int = 23; +pub const AF_INET6: ::c_int = 24; +pub const pseudo_AF_PIP: ::c_int = 25; +pub const AF_ISDN: ::c_int = 26; +pub const AF_E164: ::c_int = AF_ISDN; +pub const AF_NATM: ::c_int = 27; + +pub const PF_UNSPEC: ::c_int = AF_UNSPEC; +pub const PF_LOCAL: ::c_int = AF_LOCAL; +pub const PF_UNIX: ::c_int = PF_LOCAL; +pub const PF_INET: ::c_int = AF_INET; +pub const PF_IMPLINK: ::c_int = AF_IMPLINK; +pub const PF_PUP: ::c_int = AF_PUP; +pub const PF_CHAOS: ::c_int = AF_CHAOS; +pub const PF_NS: ::c_int = AF_NS; +pub const PF_ISO: ::c_int = AF_ISO; +pub const PF_OSI: ::c_int = AF_ISO; +pub const PF_DATAKIT: ::c_int = AF_DATAKIT; +pub const PF_CCITT: ::c_int = AF_CCITT; +pub const PF_SNA: ::c_int = AF_SNA; +pub const PF_DECnet: ::c_int = AF_DECnet; +pub const PF_DLI: ::c_int = AF_DLI; +pub const PF_LAT: ::c_int = AF_LAT; +pub const PF_HYLINK: ::c_int = AF_HYLINK; +pub const PF_APPLETALK: ::c_int = AF_APPLETALK; +pub const PF_LINK: ::c_int = AF_LINK; +pub const PF_XTP: ::c_int = pseudo_AF_XTP; +pub const PF_COIP: ::c_int = AF_COIP; +pub const PF_CNT: ::c_int = AF_CNT; +pub const PF_IPX: ::c_int = AF_IPX; +pub const PF_INET6: ::c_int = AF_INET6; +pub const PF_RTIP: ::c_int = pseudo_AF_RTIP; +pub const PF_PIP: ::c_int = pseudo_AF_PIP; +pub const PF_ISDN: ::c_int = AF_ISDN; +pub const PF_NATM: ::c_int = AF_NATM; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_RAW: ::c_int = 3; +pub const SOCK_RDM: ::c_int = 4; +pub const SOCK_SEQPACKET: ::c_int = 5; +pub const IP_TTL: ::c_int = 4; +pub const IP_HDRINCL: ::c_int = 2; +pub const IP_ADD_MEMBERSHIP: ::c_int = 12; +pub const IP_DROP_MEMBERSHIP: ::c_int = 13; + +pub const TCP_NODELAY: ::c_int = 0x01; +pub const SOL_SOCKET: ::c_int = 0xffff; +pub const SO_DEBUG: ::c_int = 0x01; +pub const SO_ACCEPTCONN: ::c_int = 0x0002; +pub const SO_REUSEADDR: ::c_int = 0x0004; +pub const SO_KEEPALIVE: ::c_int = 0x0008; +pub const SO_DONTROUTE: ::c_int = 0x0010; +pub const SO_BROADCAST: ::c_int = 0x0020; +pub const SO_USELOOPBACK: ::c_int = 0x0040; +pub const SO_LINGER: ::c_int = 0x0080; +pub const SO_OOBINLINE: ::c_int = 0x0100; +pub const SO_REUSEPORT: ::c_int = 0x0200; +pub const SO_SNDBUF: ::c_int = 0x1001; +pub const SO_RCVBUF: ::c_int = 0x1002; +pub const SO_SNDLOWAT: ::c_int = 0x1003; +pub const SO_RCVLOWAT: ::c_int = 0x1004; +pub const SO_ERROR: ::c_int = 0x1007; +pub const SO_TYPE: ::c_int = 0x1008; + +pub const SOMAXCONN: ::c_int = 128; + +pub const MSG_OOB: ::c_int = 0x1; +pub const MSG_PEEK: ::c_int = 0x2; +pub const MSG_DONTROUTE: ::c_int = 0x4; +pub const MSG_EOR: ::c_int = 0x8; +pub const MSG_TRUNC: ::c_int = 0x10; +pub const MSG_CTRUNC: ::c_int = 0x20; +pub const MSG_WAITALL: ::c_int = 0x40; +pub const MSG_DONTWAIT: ::c_int = 0x80; +pub const MSG_BCAST: ::c_int = 0x100; +pub const MSG_MCAST: ::c_int = 0x200; +pub const MSG_NOSIGNAL: ::c_int = 0x400; +pub const MSG_CMSG_CLOEXEC: ::c_int = 0x800; + +pub const SHUT_RD: ::c_int = 0; +pub const SHUT_WR: ::c_int = 1; +pub const SHUT_RDWR: ::c_int = 2; + +pub const LOCK_SH: ::c_int = 1; +pub const LOCK_EX: ::c_int = 2; +pub const LOCK_NB: ::c_int = 4; +pub const LOCK_UN: ::c_int = 8; + +pub const IPPROTO_RAW : ::c_int = 255; + +pub const _SC_ARG_MAX : ::c_int = 1; +pub const _SC_CHILD_MAX : ::c_int = 2; +pub const _SC_NGROUPS_MAX : ::c_int = 4; +pub const _SC_OPEN_MAX : ::c_int = 5; +pub const _SC_JOB_CONTROL : ::c_int = 6; +pub const _SC_SAVED_IDS : ::c_int = 7; +pub const _SC_VERSION : ::c_int = 8; +pub const _SC_BC_BASE_MAX : ::c_int = 9; +pub const _SC_BC_DIM_MAX : ::c_int = 10; +pub const _SC_BC_SCALE_MAX : ::c_int = 11; +pub const _SC_BC_STRING_MAX : ::c_int = 12; +pub const _SC_COLL_WEIGHTS_MAX : ::c_int = 13; +pub const _SC_EXPR_NEST_MAX : ::c_int = 14; +pub const _SC_LINE_MAX : ::c_int = 15; +pub const _SC_RE_DUP_MAX : ::c_int = 16; +pub const _SC_2_VERSION : ::c_int = 17; +pub const _SC_2_C_BIND : ::c_int = 18; +pub const _SC_2_C_DEV : ::c_int = 19; +pub const _SC_2_CHAR_TERM : ::c_int = 20; +pub const _SC_2_FORT_DEV : ::c_int = 21; +pub const _SC_2_FORT_RUN : ::c_int = 22; +pub const _SC_2_LOCALEDEF : ::c_int = 23; +pub const _SC_2_SW_DEV : ::c_int = 24; +pub const _SC_2_UPE : ::c_int = 25; +pub const _SC_STREAM_MAX : ::c_int = 26; +pub const _SC_TZNAME_MAX : ::c_int = 27; +pub const _SC_PAGESIZE : ::c_int = 28; +pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; +pub const _SC_FSYNC : ::c_int = 29; +pub const _SC_XOPEN_SHM : ::c_int = 30; + +pub const Q_GETQUOTA: ::c_int = 0x300; +pub const Q_SETQUOTA: ::c_int = 0x400; + +pub const RTLD_GLOBAL: ::c_int = 0x100; + +pub const LOG_NFACILITIES: ::c_int = 24; + +pub const HW_NCPU: ::c_int = 3; + +pub const B0: speed_t = 0; +pub const B50: speed_t = 50; +pub const B75: speed_t = 75; +pub const B110: speed_t = 110; +pub const B134: speed_t = 134; +pub const B150: speed_t = 150; +pub const B200: speed_t = 200; +pub const B300: speed_t = 300; +pub const B600: speed_t = 600; +pub const B1200: speed_t = 1200; +pub const B1800: speed_t = 1800; +pub const B2400: speed_t = 2400; +pub const B4800: speed_t = 4800; +pub const B9600: speed_t = 9600; +pub const B19200: speed_t = 19200; +pub const B38400: speed_t = 38400; +pub const B7200: speed_t = 7200; +pub const B14400: speed_t = 14400; +pub const B28800: speed_t = 28800; +pub const B57600: speed_t = 57600; +pub const B76800: speed_t = 76800; +pub const B115200: speed_t = 115200; +pub const B230400: speed_t = 230400; +pub const EXTA: speed_t = 19200; +pub const EXTB: speed_t = 38400; + +pub const SEM_FAILED: *mut sem_t = 0 as *mut sem_t; + +pub const CRTSCTS: ::tcflag_t = 0x00010000; +pub const CRTS_IFLOW: ::tcflag_t = CRTSCTS; +pub const CCTS_OFLOW: ::tcflag_t = CRTSCTS; +pub const OCRNL: ::tcflag_t = 0x10; + +pub const TIOCEXCL: ::c_ulong = 0x2000740d; +pub const TIOCNXCL: ::c_ulong = 0x2000740e; +pub const TIOCFLUSH: ::c_ulong = 0x80047410; +pub const TIOCGETA: ::c_ulong = 0x402c7413; +pub const TIOCSETA: ::c_ulong = 0x802c7414; +pub const TIOCSETAW: ::c_ulong = 0x802c7415; +pub const TIOCSETAF: ::c_ulong = 0x802c7416; +pub const TIOCGETD: ::c_ulong = 0x4004741a; +pub const TIOCSETD: ::c_ulong = 0x8004741b; +pub const TIOCMGET: ::c_ulong = 0x4004746a; +pub const TIOCMBIC: ::c_ulong = 0x8004746b; +pub const TIOCMBIS: ::c_ulong = 0x8004746c; +pub const TIOCMSET: ::c_ulong = 0x8004746d; +pub const TIOCSTART: ::c_ulong = 0x2000746e; +pub const TIOCSTOP: ::c_ulong = 0x2000746f; +pub const TIOCM_LE: ::c_int = 0o0001; +pub const TIOCM_DTR: ::c_int = 0o0002; +pub const TIOCM_RTS: ::c_int = 0o0004; +pub const TIOCM_ST: ::c_int = 0o0010; +pub const TIOCM_SR: ::c_int = 0o0020; +pub const TIOCM_CTS: ::c_int = 0o0040; +pub const TIOCM_CAR: ::c_int = 0o0100; +pub const TIOCM_RNG: ::c_int = 0o0200; +pub const TIOCM_DSR: ::c_int = 0o0400; +pub const TIOCM_CD: ::c_int = TIOCM_CAR; +pub const TIOCM_RI: ::c_int = TIOCM_RNG; + +f! { + pub fn WSTOPSIG(status: ::c_int) -> ::c_int { + status >> 8 + } + + pub fn WIFSIGNALED(status: ::c_int) -> bool { + (status & 0o177) != 0o177 && (status & 0o177) != 0 + } + + pub fn WIFSTOPPED(status: ::c_int) -> bool { + (status & 0o177) == 0o177 + } +} + +#[link(name = "util")] +extern { + pub fn mincore(addr: *mut ::c_void, len: ::size_t, + vec: *mut ::c_char) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__clock_getres50")] + pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__clock_gettime50")] + pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__clock_settime50")] + pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; + pub fn __errno() -> *mut ::c_int; + pub fn shm_open(name: *const ::c_char, oflag: ::c_int, mode: ::mode_t) + -> ::c_int; + pub fn memrchr(cx: *const ::c_void, + c: ::c_int, + n: ::size_t) -> *mut ::c_void; + pub fn mkostemp(template: *mut ::c_char, flags: ::c_int) -> ::c_int; + pub fn mkostemps(template: *mut ::c_char, + suffixlen: ::c_int, + flags: ::c_int) -> ::c_int; + pub fn pwritev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off_t) -> ::ssize_t; + pub fn preadv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off_t) -> ::ssize_t; + pub fn futimens(fd: ::c_int, times: *const ::timespec) -> ::c_int; + pub fn utimensat(dirfd: ::c_int, path: *const ::c_char, + times: *const ::timespec, flag: ::c_int) -> ::c_int; + pub fn fdatasync(fd: ::c_int) -> ::c_int; + pub fn openpty(amaster: *mut ::c_int, + aslave: *mut ::c_int, + name: *mut ::c_char, + termp: *mut termios, + winp: *mut ::winsize) -> ::c_int; + pub fn forkpty(amaster: *mut ::c_int, + name: *mut ::c_char, + termp: *mut termios, + winp: *mut ::winsize) -> ::pid_t; + pub fn getpriority(which: ::c_int, who: ::id_t) -> ::c_int; + pub fn setpriority(which: ::c_int, who: ::id_t, prio: ::c_int) -> ::c_int; + + pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; + + pub fn mknodat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t, dev: dev_t) -> ::c_int; + pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t) -> ::c_int; + pub fn sem_timedwait(sem: *mut sem_t, + abstime: *const ::timespec) -> ::c_int; + pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, + clock_id: ::clockid_t) -> ::c_int; + pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; + pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, + abstime: *const ::timespec) -> ::c_int; + pub fn pipe2(fds: *mut ::c_int, flags: ::c_int) -> ::c_int; + + pub fn getgrouplist(name: *const ::c_char, + basegid: ::gid_t, + groups: *mut ::gid_t, + ngroups: *mut ::c_int) -> ::c_int; + pub fn initgroups(name: *const ::c_char, basegid: ::gid_t) -> ::c_int; + pub fn fexecve(fd: ::c_int, argv: *const *const ::c_char, + envp: *const *const ::c_char) + -> ::c_int; + pub fn getdomainname(name: *mut ::c_char, len: ::size_t) -> ::c_int; + pub fn setdomainname(name: *const ::c_char, len: ::size_t) -> ::c_int; +} + +cfg_if! { + if #[cfg(target_os = "netbsd")] { + mod netbsd; + pub use self::netbsd::*; + } else if #[cfg(any(target_os = "openbsd", target_os = "bitrig"))] { + mod openbsdlike; + pub use self::openbsdlike::*; + } else { + // Unknown target_os + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1091 @@ +use dox::mem; + +pub type c_char = i8; +pub type clock_t = ::c_uint; +pub type suseconds_t = ::c_int; +pub type dev_t = u64; +pub type blksize_t = ::int32_t; +pub type fsblkcnt_t = ::uint64_t; +pub type fsfilcnt_t = ::uint64_t; +pub type idtype_t = ::c_int; +pub type mqd_t = ::c_int; + +s! { + pub struct aiocb { + pub aio_offset: ::off_t, + pub aio_buf: *mut ::c_void, + pub aio_nbytes: ::size_t, + pub aio_fildes: ::c_int, + pub aio_lio_opcode: ::c_int, + pub aio_reqprio: ::c_int, + pub aio_sigevent: ::sigevent, + _state: ::c_int, + _errno: ::c_int, + _retval: ::ssize_t + } + + pub struct dirent { + pub d_fileno: ::ino_t, + pub d_reclen: u16, + pub d_namlen: u16, + pub d_type: u8, + pub d_name: [::c_char; 512], + } + + pub struct glob_t { + pub gl_pathc: ::size_t, + pub gl_matchc: ::size_t, + pub gl_offs: ::size_t, + pub gl_flags: ::c_int, + pub gl_pathv: *mut *mut ::c_char, + + __unused3: *mut ::c_void, + + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + __unused6: *mut ::c_void, + __unused7: *mut ::c_void, + __unused8: *mut ::c_void, + } + + pub struct mq_attr { + pub mq_flags: ::c_long, + pub mq_maxmsg: ::c_long, + pub mq_msgsize: ::c_long, + pub mq_curmsgs: ::c_long, + } + + pub struct sigevent { + pub sigev_notify: ::c_int, + pub sigev_signo: ::c_int, + pub sigev_value: ::sigval, + __unused1: *mut ::c_void, //actually a function pointer + pub sigev_notify_attributes: *mut ::c_void + } + + pub struct sigset_t { + __bits: [u32; 4], + } + + pub struct stat { + pub st_dev: ::dev_t, + pub st_mode: ::mode_t, + pub st_ino: ::ino_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + pub st_atime: ::time_t, + pub st_atimensec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtimensec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctimensec: ::c_long, + pub st_birthtime: ::time_t, + pub st_birthtimensec: ::c_long, + pub st_size: ::off_t, + pub st_blocks: ::blkcnt_t, + pub st_blksize: ::blksize_t, + pub st_flags: ::uint32_t, + pub st_gen: ::uint32_t, + pub st_spare: [::uint32_t; 2], + } + + pub struct statvfs { + pub f_flag: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_iosize: ::c_ulong, + + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_bresvd: ::fsblkcnt_t, + + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + pub f_fresvd: ::fsfilcnt_t, + + pub f_syncreads: ::uint64_t, + pub f_syncwrites: ::uint64_t, + + pub f_asyncreads: ::uint64_t, + pub f_asyncwrites: ::uint64_t, + + pub f_fsidx: ::fsid_t, + pub f_fsid: ::c_ulong, + pub f_namemax: ::c_ulong, + pub f_owner: ::uid_t, + + pub f_spare: [::uint32_t; 4], + + pub f_fstypename: [::c_char; 32], + pub f_mntonname: [::c_char; 1024], + pub f_mntfromname: [::c_char; 1024], + } + + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + pub ai_addrlen: ::socklen_t, + pub ai_canonname: *mut ::c_char, + pub ai_addr: *mut ::sockaddr, + pub ai_next: *mut ::addrinfo, + } + + pub struct sockaddr_storage { + pub ss_len: u8, + pub ss_family: ::sa_family_t, + __ss_pad1: [u8; 6], + __ss_pad2: i64, + __ss_pad3: [u8; 112], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_code: ::c_int, + pub si_errno: ::c_int, + __pad1: ::c_int, + pub si_addr: *mut ::c_void, + __pad2: [u64; 13], + } + + pub struct pthread_attr_t { + pta_magic: ::c_uint, + pta_flags: ::c_int, + pta_private: *mut ::c_void, + } + + pub struct pthread_mutex_t { + ptm_magic: ::c_uint, + ptm_errorcheck: ::c_uchar, + ptm_pad1: [u8; 3], + ptm_interlock: ::c_uchar, + ptm_pad2: [u8; 3], + ptm_owner: ::pthread_t, + ptm_waiters: *mut u8, + ptm_recursed: ::c_uint, + ptm_spare2: *mut ::c_void, + } + + pub struct pthread_mutexattr_t { + ptma_magic: ::c_uint, + ptma_private: *mut ::c_void, + } + + pub struct pthread_rwlockattr_t { + ptra_magic: ::c_uint, + ptra_private: *mut ::c_void, + } + + pub struct pthread_cond_t { + ptc_magic: ::c_uint, + ptc_lock: ::c_uchar, + ptc_waiters_first: *mut u8, + ptc_waiters_last: *mut u8, + ptc_mutex: *mut ::pthread_mutex_t, + ptc_private: *mut ::c_void, + } + + pub struct pthread_condattr_t { + ptca_magic: ::c_uint, + ptca_private: *mut ::c_void, + } + + pub struct pthread_rwlock_t { + ptr_magic: ::c_uint, + ptr_interlock: ::c_uchar, + ptr_rblocked_first: *mut u8, + ptr_rblocked_last: *mut u8, + ptr_wblocked_first: *mut u8, + ptr_wblocked_last: *mut u8, + ptr_nreaders: ::c_uint, + ptr_owner: ::pthread_t, + ptr_private: *mut ::c_void, + } + + pub struct kevent { + pub ident: ::uintptr_t, + pub filter: ::uint32_t, + pub flags: ::uint32_t, + pub fflags: ::uint32_t, + pub data: ::int64_t, + pub udata: ::intptr_t, + } + + pub struct dqblk { + pub dqb_bhardlimit: ::uint32_t, + pub dqb_bsoftlimit: ::uint32_t, + pub dqb_curblocks: ::uint32_t, + pub dqb_ihardlimit: ::uint32_t, + pub dqb_isoftlimit: ::uint32_t, + pub dqb_curinodes: ::uint32_t, + pub dqb_btime: ::int32_t, + pub dqb_itime: ::int32_t, + } + + pub struct Dl_info { + pub dli_fname: *const ::c_char, + pub dli_fbase: *mut ::c_void, + pub dli_sname: *const ::c_char, + pub dli_saddr: *const ::c_void, + } + + pub struct lconv { + pub decimal_point: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + pub grouping: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub currency_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub int_frac_digits: ::c_char, + pub frac_digits: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + pub n_sign_posn: ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_n_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + pub int_n_sign_posn: ::c_char, + } + + pub struct if_data { + pub ifi_type: ::c_uchar, + pub ifi_addrlen: ::c_uchar, + pub ifi_hdrlen: ::c_uchar, + pub ifi_link_state: ::c_int, + pub ifi_mtu: u64, + pub ifi_metric: u64, + pub ifi_baudrate: u64, + pub ifi_ipackets: u64, + pub ifi_ierrors: u64, + pub ifi_opackets: u64, + pub ifi_oerrors: u64, + pub ifi_collisions: u64, + pub ifi_ibytes: u64, + pub ifi_obytes: u64, + pub ifi_imcasts: u64, + pub ifi_omcasts: u64, + pub ifi_iqdrops: u64, + pub ifi_noproto: u64, + pub ifi_lastchange: ::timespec, + } + + pub struct if_msghdr { + pub ifm_msglen: ::c_ushort, + pub ifm_version: ::c_uchar, + pub ifm_type: ::c_uchar, + pub ifm_addrs: ::c_int, + pub ifm_flags: ::c_int, + pub ifm_index: ::c_ushort, + pub ifm_data: if_data, + } + + pub struct sockcred { + pub sc_pid: ::pid_t, + pub sc_uid: ::uid_t, + pub sc_euid: ::uid_t, + pub sc_gid: ::gid_t, + pub sc_egid: ::gid_t, + pub sc_ngroups: ::c_int, + pub sc_groups: [::gid_t; 1], + } + + pub struct sockaddr_dl { + pub sdl_len: ::c_uchar, + pub sdl_family: ::c_uchar, + pub sdl_index: ::c_ushort, + pub sdl_type: ::uint8_t, + pub sdl_nlen: ::uint8_t, + pub sdl_alen: ::uint8_t, + pub sdl_slen: ::uint8_t, + pub sdl_data: [::c_char; 12], + } +} + +pub const AT_FDCWD: ::c_int = -100; +pub const AT_EACCESS: ::c_int = 0x100; +pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x200; +pub const AT_SYMLINK_FOLLOW: ::c_int = 0x400; +pub const AT_REMOVEDIR: ::c_int = 0x800; + +pub const LC_COLLATE_MASK: ::c_int = (1 << ::LC_COLLATE); +pub const LC_CTYPE_MASK: ::c_int = (1 << ::LC_CTYPE); +pub const LC_MONETARY_MASK: ::c_int = (1 << ::LC_MONETARY); +pub const LC_NUMERIC_MASK: ::c_int = (1 << ::LC_NUMERIC); +pub const LC_TIME_MASK: ::c_int = (1 << ::LC_TIME); +pub const LC_MESSAGES_MASK: ::c_int = (1 << ::LC_MESSAGES); +pub const LC_ALL_MASK: ::c_int = !0; + +pub const ERA: ::nl_item = 52; +pub const ERA_D_FMT: ::nl_item = 53; +pub const ERA_D_T_FMT: ::nl_item = 54; +pub const ERA_T_FMT: ::nl_item = 55; +pub const ALT_DIGITS: ::nl_item = 56; + +pub const O_CLOEXEC: ::c_int = 0x400000; +pub const O_ALT_IO: ::c_int = 0x40000; +pub const O_NOSIGPIPE: ::c_int = 0x1000000; +pub const O_SEARCH: ::c_int = 0x800000; +pub const O_DIRECTORY: ::c_int = 0x200000; +pub const O_DIRECT : ::c_int = 0x00080000; +pub const O_RSYNC : ::c_int = 0x00020000; + +pub const MS_SYNC : ::c_int = 0x4; +pub const MS_INVALIDATE : ::c_int = 0x2; + +pub const RLIM_NLIMITS: ::c_int = 12; + +pub const EIDRM: ::c_int = 82; +pub const ENOMSG: ::c_int = 83; +pub const EOVERFLOW: ::c_int = 84; +pub const EILSEQ: ::c_int = 85; +pub const ENOTSUP: ::c_int = 86; +pub const ECANCELED: ::c_int = 87; +pub const EBADMSG: ::c_int = 88; +pub const ENODATA: ::c_int = 89; +pub const ENOSR: ::c_int = 90; +pub const ENOSTR: ::c_int = 91; +pub const ETIME: ::c_int = 92; +pub const ENOATTR: ::c_int = 93; +pub const EMULTIHOP: ::c_int = 94; +pub const ENOLINK: ::c_int = 95; +pub const EPROTO: ::c_int = 96; +pub const ELAST: ::c_int = 96; + +pub const F_DUPFD_CLOEXEC : ::c_int = 12; +pub const F_CLOSEM: ::c_int = 10; +pub const F_GETNOSIGPIPE: ::c_int = 13; +pub const F_SETNOSIGPIPE: ::c_int = 14; +pub const F_MAXFD: ::c_int = 11; + +pub const IPV6_JOIN_GROUP: ::c_int = 12; +pub const IPV6_LEAVE_GROUP: ::c_int = 13; + +pub const SOCK_CONN_DGRAM: ::c_int = 6; +pub const SOCK_DCCP: ::c_int = SOCK_CONN_DGRAM; +pub const SOCK_NOSIGPIPE: ::c_int = 0x40000000; +pub const SOCK_FLAGS_MASK: ::c_int = 0xf0000000; + +pub const SO_SNDTIMEO: ::c_int = 0x100b; +pub const SO_RCVTIMEO: ::c_int = 0x100c; +pub const SO_ACCEPTFILTER: ::c_int = 0x1000; +pub const SO_TIMESTAMP: ::c_int = 0x2000; +pub const SO_OVERFLOWED: ::c_int = 0x1009; +pub const SO_NOHEADER: ::c_int = 0x100a; + +// https://github.com/NetBSD/src/blob/trunk/sys/net/if.h#L373 +pub const IFF_UP: ::c_int = 0x0001; // interface is up +pub const IFF_BROADCAST: ::c_int = 0x0002; // broadcast address valid +pub const IFF_DEBUG: ::c_int = 0x0004; // turn on debugging +pub const IFF_LOOPBACK: ::c_int = 0x0008; // is a loopback net +pub const IFF_POINTOPOINT: ::c_int = 0x0010; // interface is point-to-point link +pub const IFF_NOTRAILERS: ::c_int = 0x0020; // avoid use of trailers +pub const IFF_RUNNING: ::c_int = 0x0040; // resources allocated +pub const IFF_NOARP: ::c_int = 0x0080; // no address resolution protocol +pub const IFF_PROMISC: ::c_int = 0x0100; // receive all packets +pub const IFF_ALLMULTI: ::c_int = 0x0200; // receive all multicast packets +pub const IFF_OACTIVE: ::c_int = 0x0400; // transmission in progress +pub const IFF_SIMPLEX: ::c_int = 0x0800; // can't hear own transmissions +pub const IFF_LINK0: ::c_int = 0x1000; // per link layer defined bit +pub const IFF_LINK1: ::c_int = 0x2000; // per link layer defined bit +pub const IFF_LINK2: ::c_int = 0x4000; // per link layer defined bit +pub const IFF_MULTICAST: ::c_int = 0x8000; // supports multicast + +// sys/netinet/in.h +// Protocols (RFC 1700) +// NOTE: These are in addition to the constants defined in src/unix/mod.rs + +// IPPROTO_IP defined in src/unix/mod.rs +/// Hop-by-hop option header +pub const IPPROTO_HOPOPTS: ::c_int = 0; +// IPPROTO_ICMP defined in src/unix/mod.rs +/// group mgmt protocol +pub const IPPROTO_IGMP: ::c_int = 2; +/// gateway^2 (deprecated) +pub const IPPROTO_GGP: ::c_int = 3; +/// for compatibility +pub const IPPROTO_IPIP: ::c_int = 4; +// IPPROTO_TCP defined in src/unix/mod.rs +/// exterior gateway protocol +pub const IPPROTO_EGP: ::c_int = 8; +/// pup +pub const IPPROTO_PUP: ::c_int = 12; +// IPPROTO_UDP defined in src/unix/mod.rs +/// xns idp +pub const IPPROTO_IDP: ::c_int = 22; +/// tp-4 w/ class negotiation +pub const IPPROTO_TP: ::c_int = 29; +/// DCCP +pub const IPPROTO_DCCP: ::c_int = 33; +// IPPROTO_IPV6 defined in src/unix/mod.rs +/// IP6 routing header +pub const IPPROTO_ROUTING: ::c_int = 43; +/// IP6 fragmentation header +pub const IPPROTO_FRAGMENT: ::c_int = 44; +/// resource reservation +pub const IPPROTO_RSVP: ::c_int = 46; +/// General Routing Encap. +pub const IPPROTO_GRE: ::c_int = 47; +/// IP6 Encap Sec. Payload +pub const IPPROTO_ESP: ::c_int = 50; +/// IP6 Auth Header +pub const IPPROTO_AH: ::c_int = 51; +/// IP Mobility RFC 2004 +pub const IPPROTO_MOBILE: ::c_int = 55; +/// IPv6 ICMP +pub const IPPROTO_IPV6_ICMP: ::c_int = 58; +// IPPROTO_ICMPV6 defined in src/unix/mod.rs +/// IP6 no next header +pub const IPPROTO_NONE: ::c_int = 59; +/// IP6 destination option +pub const IPPROTO_DSTOPTS: ::c_int = 60; +/// ISO cnlp +pub const IPPROTO_EON: ::c_int = 80; +/// Ethernet-in-IP +pub const IPPROTO_ETHERIP: ::c_int = 97; +/// encapsulation header +pub const IPPROTO_ENCAP: ::c_int = 98; +/// Protocol indep. multicast +pub const IPPROTO_PIM: ::c_int = 103; +/// IP Payload Comp. Protocol +pub const IPPROTO_IPCOMP: ::c_int = 108; +/// VRRP RFC 2338 +pub const IPPROTO_VRRP: ::c_int = 112; +/// Common Address Resolution Protocol +pub const IPPROTO_CARP: ::c_int = 112; +/// L2TPv3 +// TEMP: Disabled for now; this constant was added to NetBSD on 2017-02-16, +// but isn't yet supported by the NetBSD rumprun kernel image used for +// libc testing. +//pub const IPPROTO_L2TP: ::c_int = 115; +/// SCTP +pub const IPPROTO_SCTP: ::c_int = 132; +/// PFSYNC +pub const IPPROTO_PFSYNC: ::c_int = 240; +pub const IPPROTO_MAX: ::c_int = 256; + +/// last return value of *_input(), meaning "all job for this pkt is done". +pub const IPPROTO_DONE: ::c_int = 257; + +/// sysctl placeholder for (FAST_)IPSEC +pub const CTL_IPPROTO_IPSEC: ::c_int = 258; + +pub const AF_OROUTE: ::c_int = 17; +pub const AF_ARP: ::c_int = 28; +pub const pseudo_AF_KEY: ::c_int = 29; +pub const pseudo_AF_HDRCMPLT: ::c_int = 30; +pub const AF_BLUETOOTH: ::c_int = 31; +pub const AF_IEEE80211: ::c_int = 32; +pub const AF_MPLS: ::c_int = 33; +pub const AF_ROUTE: ::c_int = 34; +pub const AF_MAX: ::c_int = 35; + +pub const NET_MAXID: ::c_int = AF_MAX; +pub const NET_RT_DUMP: ::c_int = 1; +pub const NET_RT_FLAGS: ::c_int = 2; +pub const NET_RT_OOIFLIST: ::c_int = 3; +pub const NET_RT_OIFLIST: ::c_int = 4; +pub const NET_RT_IFLIST: ::c_int = 5; +pub const NET_RT_MAXID: ::c_int = 6; + +pub const PF_OROUTE: ::c_int = AF_OROUTE; +pub const PF_ARP: ::c_int = AF_ARP; +pub const PF_KEY: ::c_int = pseudo_AF_KEY; +pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; +pub const PF_MPLS: ::c_int = AF_MPLS; +pub const PF_ROUTE: ::c_int = AF_ROUTE; +pub const PF_MAX: ::c_int = AF_MAX; + +pub const MSG_NBIO: ::c_int = 0x1000; +pub const MSG_WAITFORONE: ::c_int = 0x2000; +pub const MSG_NOTIFICATION: ::c_int = 0x4000; + +pub const SCM_TIMESTAMP: ::c_int = 0x08; +pub const SCM_CREDS: ::c_int = 0x10; + +pub const O_DSYNC : ::c_int = 0x10000; + +pub const MAP_RENAME : ::c_int = 0x20; +pub const MAP_NORESERVE : ::c_int = 0x40; +pub const MAP_HASSEMAPHORE : ::c_int = 0x200; +pub const MAP_WIRED: ::c_int = 0x800; + +pub const DCCP_TYPE_REQUEST: ::c_int = 0; +pub const DCCP_TYPE_RESPONSE: ::c_int = 1; +pub const DCCP_TYPE_DATA: ::c_int = 2; +pub const DCCP_TYPE_ACK: ::c_int = 3; +pub const DCCP_TYPE_DATAACK: ::c_int = 4; +pub const DCCP_TYPE_CLOSEREQ: ::c_int = 5; +pub const DCCP_TYPE_CLOSE: ::c_int = 6; +pub const DCCP_TYPE_RESET: ::c_int = 7; +pub const DCCP_TYPE_MOVE: ::c_int = 8; + +pub const DCCP_FEATURE_CC: ::c_int = 1; +pub const DCCP_FEATURE_ECN: ::c_int = 2; +pub const DCCP_FEATURE_ACKRATIO: ::c_int = 3; +pub const DCCP_FEATURE_ACKVECTOR: ::c_int = 4; +pub const DCCP_FEATURE_MOBILITY: ::c_int = 5; +pub const DCCP_FEATURE_LOSSWINDOW: ::c_int = 6; +pub const DCCP_FEATURE_CONN_NONCE: ::c_int = 8; +pub const DCCP_FEATURE_IDENTREG: ::c_int = 7; + +pub const DCCP_OPT_PADDING: ::c_int = 0; +pub const DCCP_OPT_DATA_DISCARD: ::c_int = 1; +pub const DCCP_OPT_SLOW_RECV: ::c_int = 2; +pub const DCCP_OPT_BUF_CLOSED: ::c_int = 3; +pub const DCCP_OPT_CHANGE_L: ::c_int = 32; +pub const DCCP_OPT_CONFIRM_L: ::c_int = 33; +pub const DCCP_OPT_CHANGE_R: ::c_int = 34; +pub const DCCP_OPT_CONFIRM_R: ::c_int = 35; +pub const DCCP_OPT_INIT_COOKIE: ::c_int = 36; +pub const DCCP_OPT_NDP_COUNT: ::c_int = 37; +pub const DCCP_OPT_ACK_VECTOR0: ::c_int = 38; +pub const DCCP_OPT_ACK_VECTOR1: ::c_int = 39; +pub const DCCP_OPT_RECV_BUF_DROPS: ::c_int = 40; +pub const DCCP_OPT_TIMESTAMP: ::c_int = 41; +pub const DCCP_OPT_TIMESTAMP_ECHO: ::c_int = 42; +pub const DCCP_OPT_ELAPSEDTIME: ::c_int = 43; +pub const DCCP_OPT_DATACHECKSUM: ::c_int = 44; + +pub const DCCP_REASON_UNSPEC: ::c_int = 0; +pub const DCCP_REASON_CLOSED: ::c_int = 1; +pub const DCCP_REASON_INVALID: ::c_int = 2; +pub const DCCP_REASON_OPTION_ERR: ::c_int = 3; +pub const DCCP_REASON_FEA_ERR: ::c_int = 4; +pub const DCCP_REASON_CONN_REF: ::c_int = 5; +pub const DCCP_REASON_BAD_SNAME: ::c_int = 6; +pub const DCCP_REASON_BAD_COOKIE: ::c_int = 7; +pub const DCCP_REASON_INV_MOVE: ::c_int = 8; +pub const DCCP_REASON_UNANSW_CH: ::c_int = 10; +pub const DCCP_REASON_FRUITLESS_NEG: ::c_int = 11; + +pub const DCCP_CCID: ::c_int = 1; +pub const DCCP_CSLEN: ::c_int = 2; +pub const DCCP_MAXSEG: ::c_int = 4; +pub const DCCP_SERVICE: ::c_int = 8; + +pub const DCCP_NDP_LIMIT: ::c_int = 16; +pub const DCCP_SEQ_NUM_LIMIT: ::c_int = 16777216; +pub const DCCP_MAX_OPTIONS: ::c_int = 32; +pub const DCCP_MAX_PKTS: ::c_int = 100; + +pub const _PC_LINK_MAX : ::c_int = 1; +pub const _PC_MAX_CANON : ::c_int = 2; +pub const _PC_MAX_INPUT : ::c_int = 3; +pub const _PC_NAME_MAX : ::c_int = 4; +pub const _PC_PATH_MAX : ::c_int = 5; +pub const _PC_PIPE_BUF : ::c_int = 6; +pub const _PC_CHOWN_RESTRICTED : ::c_int = 7; +pub const _PC_NO_TRUNC : ::c_int = 8; +pub const _PC_VDISABLE : ::c_int = 9; +pub const _PC_SYNC_IO : ::c_int = 10; +pub const _PC_FILESIZEBITS : ::c_int = 11; +pub const _PC_SYMLINK_MAX : ::c_int = 12; +pub const _PC_2_SYMLINKS : ::c_int = 13; +pub const _PC_ACL_EXTENDED : ::c_int = 14; +pub const _PC_MIN_HOLE_SIZE : ::c_int = 15; + +pub const _SC_SYNCHRONIZED_IO : ::c_int = 31; +pub const _SC_IOV_MAX : ::c_int = 32; +pub const _SC_MAPPED_FILES : ::c_int = 33; +pub const _SC_MEMLOCK : ::c_int = 34; +pub const _SC_MEMLOCK_RANGE : ::c_int = 35; +pub const _SC_MEMORY_PROTECTION : ::c_int = 36; +pub const _SC_LOGIN_NAME_MAX : ::c_int = 37; +pub const _SC_MONOTONIC_CLOCK : ::c_int = 38; +pub const _SC_CLK_TCK : ::c_int = 39; +pub const _SC_ATEXIT_MAX : ::c_int = 40; +pub const _SC_THREADS : ::c_int = 41; +pub const _SC_SEMAPHORES : ::c_int = 42; +pub const _SC_BARRIERS : ::c_int = 43; +pub const _SC_TIMERS : ::c_int = 44; +pub const _SC_SPIN_LOCKS : ::c_int = 45; +pub const _SC_READER_WRITER_LOCKS : ::c_int = 46; +pub const _SC_GETGR_R_SIZE_MAX : ::c_int = 47; +pub const _SC_GETPW_R_SIZE_MAX : ::c_int = 48; +pub const _SC_CLOCK_SELECTION : ::c_int = 49; +pub const _SC_ASYNCHRONOUS_IO : ::c_int = 50; +pub const _SC_AIO_LISTIO_MAX : ::c_int = 51; +pub const _SC_AIO_MAX : ::c_int = 52; +pub const _SC_MESSAGE_PASSING : ::c_int = 53; +pub const _SC_MQ_OPEN_MAX : ::c_int = 54; +pub const _SC_MQ_PRIO_MAX : ::c_int = 55; +pub const _SC_PRIORITY_SCHEDULING : ::c_int = 56; +pub const _SC_THREAD_DESTRUCTOR_ITERATIONS : ::c_int = 57; +pub const _SC_THREAD_KEYS_MAX : ::c_int = 58; +pub const _SC_THREAD_STACK_MIN : ::c_int = 59; +pub const _SC_THREAD_THREADS_MAX : ::c_int = 60; +pub const _SC_THREAD_ATTR_STACKADDR : ::c_int = 61; +pub const _SC_THREAD_ATTR_STACKSIZE : ::c_int = 62; +pub const _SC_THREAD_PRIORITY_SCHEDULING : ::c_int = 63; +pub const _SC_THREAD_PRIO_INHERIT : ::c_int = 64; +pub const _SC_THREAD_PRIO_PROTECT : ::c_int = 65; +pub const _SC_THREAD_PROCESS_SHARED : ::c_int = 66; +pub const _SC_THREAD_SAFE_FUNCTIONS : ::c_int = 67; +pub const _SC_TTY_NAME_MAX : ::c_int = 68; +pub const _SC_HOST_NAME_MAX : ::c_int = 69; +pub const _SC_PASS_MAX : ::c_int = 70; +pub const _SC_REGEXP : ::c_int = 71; +pub const _SC_SHELL : ::c_int = 72; +pub const _SC_SYMLOOP_MAX : ::c_int = 73; +pub const _SC_V6_ILP32_OFF32 : ::c_int = 74; +pub const _SC_V6_ILP32_OFFBIG : ::c_int = 75; +pub const _SC_V6_LP64_OFF64 : ::c_int = 76; +pub const _SC_V6_LPBIG_OFFBIG : ::c_int = 77; +pub const _SC_2_PBS : ::c_int = 80; +pub const _SC_2_PBS_ACCOUNTING : ::c_int = 81; +pub const _SC_2_PBS_CHECKPOINT : ::c_int = 82; +pub const _SC_2_PBS_LOCATE : ::c_int = 83; +pub const _SC_2_PBS_MESSAGE : ::c_int = 84; +pub const _SC_2_PBS_TRACK : ::c_int = 85; +pub const _SC_SPAWN : ::c_int = 86; +pub const _SC_SHARED_MEMORY_OBJECTS : ::c_int = 87; +pub const _SC_TIMER_MAX : ::c_int = 88; +pub const _SC_SEM_NSEMS_MAX : ::c_int = 89; +pub const _SC_CPUTIME : ::c_int = 90; +pub const _SC_THREAD_CPUTIME : ::c_int = 91; +pub const _SC_DELAYTIMER_MAX : ::c_int = 92; +// These two variables will be supported in NetBSD 8.0 +// pub const _SC_SIGQUEUE_MAX : ::c_int = 93; +// pub const _SC_REALTIME_SIGNALS : ::c_int = 94; +pub const _SC_PHYS_PAGES : ::c_int = 121; +pub const _SC_NPROCESSORS_CONF : ::c_int = 1001; +pub const _SC_NPROCESSORS_ONLN : ::c_int = 1002; +pub const _SC_SCHED_RT_TS : ::c_int = 2001; +pub const _SC_SCHED_PRI_MIN : ::c_int = 2002; +pub const _SC_SCHED_PRI_MAX : ::c_int = 2003; + +pub const FD_SETSIZE: usize = 0x100; + +pub const ST_NOSUID: ::c_ulong = 8; + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + ptm_magic: 0x33330003, + ptm_errorcheck: 0, + ptm_interlock: 0, + ptm_waiters: 0 as *mut _, + ptm_owner: 0, + ptm_pad1: [0; 3], + ptm_pad2: [0; 3], + ptm_recursed: 0, + ptm_spare2: 0 as *mut _, +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + ptc_magic: 0x55550005, + ptc_lock: 0, + ptc_waiters_first: 0 as *mut _, + ptc_waiters_last: 0 as *mut _, + ptc_mutex: 0 as *mut _, + ptc_private: 0 as *mut _, +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + ptr_magic: 0x99990009, + ptr_interlock: 0, + ptr_rblocked_first: 0 as *mut _, + ptr_rblocked_last: 0 as *mut _, + ptr_wblocked_first: 0 as *mut _, + ptr_wblocked_last: 0 as *mut _, + ptr_nreaders: 0, + ptr_owner: 0, + ptr_private: 0 as *mut _, +}; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 1; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 2; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; + +pub const EVFILT_AIO: ::uint32_t = 2; +pub const EVFILT_PROC: ::uint32_t = 4; +pub const EVFILT_READ: ::uint32_t = 0; +pub const EVFILT_SIGNAL: ::uint32_t = 5; +pub const EVFILT_TIMER: ::uint32_t = 6; +pub const EVFILT_VNODE: ::uint32_t = 3; +pub const EVFILT_WRITE: ::uint32_t = 1; + +pub const EV_ADD: ::uint32_t = 0x1; +pub const EV_DELETE: ::uint32_t = 0x2; +pub const EV_ENABLE: ::uint32_t = 0x4; +pub const EV_DISABLE: ::uint32_t = 0x8; +pub const EV_ONESHOT: ::uint32_t = 0x10; +pub const EV_CLEAR: ::uint32_t = 0x20; +pub const EV_RECEIPT: ::uint32_t = 0x40; +pub const EV_DISPATCH: ::uint32_t = 0x80; +pub const EV_FLAG1: ::uint32_t = 0x2000; +pub const EV_ERROR: ::uint32_t = 0x4000; +pub const EV_EOF: ::uint32_t = 0x8000; +pub const EV_SYSFLAGS: ::uint32_t = 0xf000; + +pub const NOTE_LOWAT: ::uint32_t = 0x00000001; +pub const NOTE_DELETE: ::uint32_t = 0x00000001; +pub const NOTE_WRITE: ::uint32_t = 0x00000002; +pub const NOTE_EXTEND: ::uint32_t = 0x00000004; +pub const NOTE_ATTRIB: ::uint32_t = 0x00000008; +pub const NOTE_LINK: ::uint32_t = 0x00000010; +pub const NOTE_RENAME: ::uint32_t = 0x00000020; +pub const NOTE_REVOKE: ::uint32_t = 0x00000040; +pub const NOTE_EXIT: ::uint32_t = 0x80000000; +pub const NOTE_FORK: ::uint32_t = 0x40000000; +pub const NOTE_EXEC: ::uint32_t = 0x20000000; +pub const NOTE_PDATAMASK: ::uint32_t = 0x000fffff; +pub const NOTE_PCTRLMASK: ::uint32_t = 0xf0000000; +pub const NOTE_TRACK: ::uint32_t = 0x00000001; +pub const NOTE_TRACKERR: ::uint32_t = 0x00000002; +pub const NOTE_CHILD: ::uint32_t = 0x00000004; + +pub const TMP_MAX : ::c_uint = 308915776; + +pub const NI_MAXHOST: ::socklen_t = 1025; + +pub const RTLD_NOLOAD: ::c_int = 0x2000; +pub const RTLD_LOCAL: ::c_int = 0x200; + +pub const CTL_MAXNAME: ::c_int = 12; +pub const SYSCTL_NAMELEN: ::c_int = 32; +pub const SYSCTL_DEFSIZE: ::c_int = 8; +pub const CTLTYPE_NODE: ::c_int = 1; +pub const CTLTYPE_INT: ::c_int = 2; +pub const CTLTYPE_STRING: ::c_int = 3; +pub const CTLTYPE_QUAD: ::c_int = 4; +pub const CTLTYPE_STRUCT: ::c_int = 5; +pub const CTLTYPE_BOOL: ::c_int = 6; +pub const CTLFLAG_READONLY: ::c_int = 0x00000000; +pub const CTLFLAG_READWRITE: ::c_int = 0x00000070; +pub const CTLFLAG_ANYWRITE: ::c_int = 0x00000080; +pub const CTLFLAG_PRIVATE: ::c_int = 0x00000100; +pub const CTLFLAG_PERMANENT: ::c_int = 0x00000200; +pub const CTLFLAG_OWNDATA: ::c_int = 0x00000400; +pub const CTLFLAG_IMMEDIATE: ::c_int = 0x00000800; +pub const CTLFLAG_HEX: ::c_int = 0x00001000; +pub const CTLFLAG_ROOT: ::c_int = 0x00002000; +pub const CTLFLAG_ANYNUMBER: ::c_int = 0x00004000; +pub const CTLFLAG_HIDDEN: ::c_int = 0x00008000; +pub const CTLFLAG_ALIAS: ::c_int = 0x00010000; +pub const CTLFLAG_MMAP: ::c_int = 0x00020000; +pub const CTLFLAG_OWNDESC: ::c_int = 0x00040000; +pub const CTLFLAG_UNSIGNED: ::c_int = 0x00080000; +pub const SYSCTL_VERS_MASK: ::c_int = 0xff000000; +pub const SYSCTL_VERS_0: ::c_int = 0x00000000; +pub const SYSCTL_VERS_1: ::c_int = 0x01000000; +pub const SYSCTL_VERSION: ::c_int = SYSCTL_VERS_1; +pub const CTL_EOL: ::c_int = -1; +pub const CTL_QUERY: ::c_int = -2; +pub const CTL_CREATE: ::c_int = -3; +pub const CTL_CREATESYM: ::c_int = -4; +pub const CTL_DESTROY: ::c_int = -5; +pub const CTL_MMAP: ::c_int = -6; +pub const CTL_DESCRIBE: ::c_int = -7; +pub const CTL_UNSPEC: ::c_int = 0; +pub const CTL_KERN: ::c_int = 1; +pub const CTL_VM: ::c_int = 2; +pub const CTL_VFS: ::c_int = 3; +pub const CTL_NET: ::c_int = 4; +pub const CTL_DEBUG: ::c_int = 5; +pub const CTL_HW: ::c_int = 6; +pub const CTL_MACHDEP: ::c_int = 7; +pub const CTL_USER: ::c_int = 8; +pub const CTL_DDB: ::c_int = 9; +pub const CTL_PROC: ::c_int = 10; +pub const CTL_VENDOR: ::c_int = 11; +pub const CTL_EMUL: ::c_int = 12; +pub const CTL_SECURITY: ::c_int = 13; +pub const CTL_MAXID: ::c_int = 14; +pub const KERN_OSTYPE: ::c_int = 1; +pub const KERN_OSRELEASE: ::c_int = 2; +pub const KERN_OSREV: ::c_int = 3; +pub const KERN_VERSION: ::c_int = 4; +pub const KERN_MAXVNODES: ::c_int = 5; +pub const KERN_MAXPROC: ::c_int = 6; +pub const KERN_MAXFILES: ::c_int = 7; +pub const KERN_ARGMAX: ::c_int = 8; +pub const KERN_SECURELVL: ::c_int = 9; +pub const KERN_HOSTNAME: ::c_int = 10; +pub const KERN_HOSTID: ::c_int = 11; +pub const KERN_CLOCKRATE: ::c_int = 12; +pub const KERN_VNODE: ::c_int = 13; +pub const KERN_PROC: ::c_int = 14; +pub const KERN_FILE: ::c_int = 15; +pub const KERN_PROF: ::c_int = 16; +pub const KERN_POSIX1: ::c_int = 17; +pub const KERN_NGROUPS: ::c_int = 18; +pub const KERN_JOB_CONTROL: ::c_int = 19; +pub const KERN_SAVED_IDS: ::c_int = 20; +pub const KERN_OBOOTTIME: ::c_int = 21; +pub const KERN_DOMAINNAME: ::c_int = 22; +pub const KERN_MAXPARTITIONS: ::c_int = 23; +pub const KERN_RAWPARTITION: ::c_int = 24; +pub const KERN_NTPTIME: ::c_int = 25; +pub const KERN_TIMEX: ::c_int = 26; +pub const KERN_AUTONICETIME: ::c_int = 27; +pub const KERN_AUTONICEVAL: ::c_int = 28; +pub const KERN_RTC_OFFSET: ::c_int = 29; +pub const KERN_ROOT_DEVICE: ::c_int = 30; +pub const KERN_MSGBUFSIZE: ::c_int = 31; +pub const KERN_FSYNC: ::c_int = 32; +pub const KERN_OLDSYSVMSG: ::c_int = 33; +pub const KERN_OLDSYSVSEM: ::c_int = 34; +pub const KERN_OLDSYSVSHM: ::c_int = 35; +pub const KERN_OLDSHORTCORENAME: ::c_int = 36; +pub const KERN_SYNCHRONIZED_IO: ::c_int = 37; +pub const KERN_IOV_MAX: ::c_int = 38; +pub const KERN_MBUF: ::c_int = 39; +pub const KERN_MAPPED_FILES: ::c_int = 40; +pub const KERN_MEMLOCK: ::c_int = 41; +pub const KERN_MEMLOCK_RANGE: ::c_int = 42; +pub const KERN_MEMORY_PROTECTION: ::c_int = 43; +pub const KERN_LOGIN_NAME_MAX: ::c_int = 44; +pub const KERN_DEFCORENAME: ::c_int = 45; +pub const KERN_LOGSIGEXIT: ::c_int = 46; +pub const KERN_PROC2: ::c_int = 47; +pub const KERN_PROC_ARGS: ::c_int = 48; +pub const KERN_FSCALE: ::c_int = 49; +pub const KERN_CCPU: ::c_int = 50; +pub const KERN_CP_TIME: ::c_int = 51; +pub const KERN_OLDSYSVIPC_INFO: ::c_int = 52; +pub const KERN_MSGBUF: ::c_int = 53; +pub const KERN_CONSDEV: ::c_int = 54; +pub const KERN_MAXPTYS: ::c_int = 55; +pub const KERN_PIPE: ::c_int = 56; +pub const KERN_MAXPHYS: ::c_int = 57; +pub const KERN_SBMAX: ::c_int = 58; +pub const KERN_TKSTAT: ::c_int = 59; +pub const KERN_MONOTONIC_CLOCK: ::c_int = 60; +pub const KERN_URND: ::c_int = 61; +pub const KERN_LABELSECTOR: ::c_int = 62; +pub const KERN_LABELOFFSET: ::c_int = 63; +pub const KERN_LWP: ::c_int = 64; +pub const KERN_FORKFSLEEP: ::c_int = 65; +pub const KERN_POSIX_THREADS: ::c_int = 66; +pub const KERN_POSIX_SEMAPHORES: ::c_int = 67; +pub const KERN_POSIX_BARRIERS: ::c_int = 68; +pub const KERN_POSIX_TIMERS: ::c_int = 69; +pub const KERN_POSIX_SPIN_LOCKS: ::c_int = 70; +pub const KERN_POSIX_READER_WRITER_LOCKS: ::c_int = 71; +pub const KERN_DUMP_ON_PANIC: ::c_int = 72; +pub const KERN_SOMAXKVA: ::c_int = 73; +pub const KERN_ROOT_PARTITION: ::c_int = 74; +pub const KERN_DRIVERS: ::c_int = 75; +pub const KERN_BUF: ::c_int = 76; +pub const KERN_FILE2: ::c_int = 77; +pub const KERN_VERIEXEC: ::c_int = 78; +pub const KERN_CP_ID: ::c_int = 79; +pub const KERN_HARDCLOCK_TICKS: ::c_int = 80; +pub const KERN_ARND: ::c_int = 81; +pub const KERN_SYSVIPC: ::c_int = 82; +pub const KERN_BOOTTIME: ::c_int = 83; +pub const KERN_EVCNT: ::c_int = 84; +pub const KERN_MAXID: ::c_int = 85; +pub const KERN_PROC_ALL: ::c_int = 0; +pub const KERN_PROC_PID: ::c_int = 1; +pub const KERN_PROC_PGRP: ::c_int = 2; +pub const KERN_PROC_SESSION: ::c_int = 3; +pub const KERN_PROC_TTY: ::c_int = 4; +pub const KERN_PROC_UID: ::c_int = 5; +pub const KERN_PROC_RUID: ::c_int = 6; +pub const KERN_PROC_GID: ::c_int = 7; +pub const KERN_PROC_RGID: ::c_int = 8; +pub const KERN_PROC_ARGV: ::c_int = 1; +pub const KERN_PROC_NARGV: ::c_int = 2; +pub const KERN_PROC_ENV: ::c_int = 3; +pub const KERN_PROC_NENV: ::c_int = 4; +pub const KERN_PROC_PATHNAME: ::c_int = 5; + +pub const EAI_AGAIN: ::c_int = 2; +pub const EAI_BADFLAGS: ::c_int = 3; +pub const EAI_FAIL: ::c_int = 4; +pub const EAI_FAMILY: ::c_int = 5; +pub const EAI_MEMORY: ::c_int = 6; +pub const EAI_NODATA: ::c_int = 7; +pub const EAI_NONAME: ::c_int = 8; +pub const EAI_SERVICE: ::c_int = 9; +pub const EAI_SOCKTYPE: ::c_int = 10; +pub const EAI_SYSTEM: ::c_int = 11; +pub const EAI_OVERFLOW: ::c_int = 14; + +pub const AIO_CANCELED: ::c_int = 1; +pub const AIO_NOTCANCELED: ::c_int = 2; +pub const AIO_ALLDONE: ::c_int = 3; +pub const LIO_NOP: ::c_int = 0; +pub const LIO_WRITE: ::c_int = 1; +pub const LIO_READ: ::c_int = 2; +pub const LIO_WAIT: ::c_int = 1; +pub const LIO_NOWAIT: ::c_int = 0; + +pub const SIGEV_NONE: ::c_int = 0; +pub const SIGEV_SIGNAL: ::c_int = 1; +pub const SIGEV_THREAD: ::c_int = 2; + +pub const WSTOPPED: ::c_int = 0x00000002; // same as WUNTRACED +pub const WCONTINUED: ::c_int = 0x00000010; +pub const WEXITED: ::c_int = 0x000000020; +pub const WNOWAIT: ::c_int = 0x00010000; + +pub const P_ALL: idtype_t = 0; +pub const P_PID: idtype_t = 1; +pub const P_PGID: idtype_t = 4; + +pub const B460800: ::speed_t = 460800; +pub const B921600: ::speed_t = 921600; + +pub const ONOCR: ::tcflag_t = 0x20; +pub const ONLRET: ::tcflag_t = 0x40; +pub const CDTRCTS: ::tcflag_t = 0x00020000; +pub const CHWFLOW: ::tcflag_t = ::MDMBUF | ::CRTSCTS | ::CDTRCTS; + +pub const SOCK_CLOEXEC: ::c_int = 0x10000000; +pub const SOCK_NONBLOCK: ::c_int = 0x20000000; + +// dirfd() is a macro on netbsd to access +// the first field of the struct where dirp points to: +// http://cvsweb.netbsd.org/bsdweb.cgi/src/include/dirent.h?rev=1.36 +f! { + pub fn dirfd(dirp: *mut ::DIR) -> ::c_int { + *(dirp as *const ::c_int) + } + + pub fn WIFCONTINUED(status: ::c_int) -> bool { + status == 0xffff + } + + pub fn SOCKCREDSIZE(ngrps: usize) -> usize { + let ngrps = if ngrps > 0 { + ngrps - 1 + } else { + 0 + }; + mem::size_of::() + mem::size_of::<::gid_t>() * ngrps + } +} + +extern { + pub fn aio_read(aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_write(aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_fsync(op: ::c_int, aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_error(aiocbp: *const aiocb) -> ::c_int; + pub fn aio_return(aiocbp: *mut aiocb) -> ::ssize_t; + #[link_name = "__aio_suspend50"] + pub fn aio_suspend(aiocb_list: *const *const aiocb, nitems: ::c_int, + timeout: *const ::timespec) -> ::c_int; + pub fn aio_cancel(fd: ::c_int, aiocbp: *mut aiocb) -> ::c_int; + pub fn lio_listio(mode: ::c_int, aiocb_list: *const *mut aiocb, + nitems: ::c_int, sevp: *mut sigevent) -> ::c_int; + + pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; + pub fn getnameinfo(sa: *const ::sockaddr, + salen: ::socklen_t, + host: *mut ::c_char, + hostlen: ::socklen_t, + serv: *mut ::c_char, + sevlen: ::socklen_t, + flags: ::c_int) -> ::c_int; + pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) + -> ::c_int; + pub fn sysctl(name: *const ::c_int, + namelen: ::c_uint, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *const ::c_void, + newlen: ::size_t) + -> ::c_int; + pub fn sysctlbyname(name: *const ::c_char, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *const ::c_void, + newlen: ::size_t) + -> ::c_int; + #[link_name = "__kevent50"] + pub fn kevent(kq: ::c_int, + changelist: *const ::kevent, + nchanges: ::size_t, + eventlist: *mut ::kevent, + nevents: ::size_t, + timeout: *const ::timespec) -> ::c_int; + #[link_name = "__mount50"] + pub fn mount(src: *const ::c_char, + target: *const ::c_char, + flags: ::c_int, + data: *mut ::c_void, + size: ::size_t) -> ::c_int; + pub fn mq_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::mqd_t; + pub fn mq_close(mqd: ::mqd_t) -> ::c_int; + pub fn mq_getattr(mqd: ::mqd_t, attr: *mut ::mq_attr) -> ::c_int; + pub fn mq_notify(mqd: ::mqd_t, notification: *const ::sigevent) -> ::c_int; + pub fn mq_receive(mqd: ::mqd_t, + msg_ptr: *mut ::c_char, + msg_len: ::size_t, + msq_prio: *mut ::c_uint) -> ::ssize_t; + pub fn mq_send(mqd: ::mqd_t, + msg_ptr: *const ::c_char, + msg_len: ::size_t, + msq_prio: ::c_uint) -> ::c_int; + pub fn mq_setattr(mqd: ::mqd_t, + newattr: *const ::mq_attr, + oldattr: *mut ::mq_attr) -> ::c_int; + pub fn mq_timedreceive(mqd: ::mqd_t, + msg_ptr: *mut ::c_char, + msg_len: ::size_t, + msq_prio: *mut ::c_uint, + abs_timeout: *const ::timespec) -> ::ssize_t; + pub fn mq_timedsend(mqd: ::mqd_t, + msg_ptr: *const ::c_char, + msg_len: ::size_t, + msq_prio: ::c_uint, + abs_timeout: *const ::timespec) -> ::c_int; + pub fn mq_unlink(name: *const ::c_char) -> ::c_int; + pub fn ptrace(request: ::c_int, + pid: ::pid_t, + addr: *mut ::c_void, + data: ::c_int) -> ::c_int; + pub fn pthread_setname_np(t: ::pthread_t, + name: *const ::c_char, + arg: *mut ::c_void) -> ::c_int; + pub fn pthread_getattr_np(native: ::pthread_t, + attr: *mut ::pthread_attr_t) -> ::c_int; + pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, + guardsize: *mut ::size_t) -> ::c_int; + pub fn pthread_attr_getstack(attr: *const ::pthread_attr_t, + stackaddr: *mut *mut ::c_void, + stacksize: *mut ::size_t) -> ::c_int; + #[link_name = "__sigtimedwait50"] + pub fn sigtimedwait(set: *const sigset_t, + info: *mut siginfo_t, + timeout: *const ::timespec) -> ::c_int; + pub fn sigwaitinfo(set: *const sigset_t, + info: *mut siginfo_t) -> ::c_int; + pub fn duplocale(base: ::locale_t) -> ::locale_t; + pub fn freelocale(loc: ::locale_t); + pub fn localeconv_l(loc: ::locale_t) -> *mut lconv; + pub fn newlocale(mask: ::c_int, + locale: *const ::c_char, + base: ::locale_t) -> ::locale_t; + #[link_name = "__settimeofday50"] + pub fn settimeofday(tv: *const ::timeval, tz: *const ::c_void) -> ::c_int; +} + +#[link(name = "util")] +extern { + #[cfg_attr(target_os = "netbsd", link_name = "__getpwent_r50")] + pub fn getpwent_r(pwd: *mut ::passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::passwd) -> ::c_int; + pub fn getgrent_r(grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; +} + +mod other; +pub use self::other::*; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/other/b32/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/other/b32/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/other/b32/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/other/b32/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2 @@ +pub type c_long = i32; +pub type c_ulong = u32; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/other/b64/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/other/b64/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/other/b64/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/other/b64/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2 @@ +pub type c_long = i64; +pub type c_ulong = u64; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/other/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/other/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/other/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/netbsd/other/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,14 @@ +cfg_if! { + if #[cfg(any(target_arch = "sparc64", + target_arch = "x86_64"))] { + mod b64; + pub use self::b64::*; + } else if #[cfg(any(target_arch = "arm", + target_arch = "powerpc", + target_arch = "x86"))] { + mod b32; + pub use self::b32::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/bitrig/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/bitrig/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/bitrig/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/bitrig/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,109 @@ +pub type c_char = i8; + +s! { + pub struct lconv { + pub decimal_point: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + pub grouping: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub currency_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub int_frac_digits: ::c_char, + pub frac_digits: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + pub n_sign_posn: ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_n_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + pub int_n_sign_posn: ::c_char, + } +} + +pub const LC_COLLATE_MASK: ::c_int = (1 << 0); +pub const LC_CTYPE_MASK: ::c_int = (1 << 1); +pub const LC_MESSAGES_MASK: ::c_int = (1 << 2); +pub const LC_MONETARY_MASK: ::c_int = (1 << 3); +pub const LC_NUMERIC_MASK: ::c_int = (1 << 4); +pub const LC_TIME_MASK: ::c_int = (1 << 5); +pub const LC_ALL_MASK: ::c_int = LC_COLLATE_MASK + | LC_CTYPE_MASK + | LC_MESSAGES_MASK + | LC_MONETARY_MASK + | LC_NUMERIC_MASK + | LC_TIME_MASK; + +pub const ERA: ::nl_item = 52; +pub const ERA_D_FMT: ::nl_item = 53; +pub const ERA_D_T_FMT: ::nl_item = 54; +pub const ERA_T_FMT: ::nl_item = 55; +pub const ALT_DIGITS: ::nl_item = 56; + +pub const D_MD_ORDER: ::nl_item = 57; + +pub const ALTMON_1: ::nl_item = 58; +pub const ALTMON_2: ::nl_item = 59; +pub const ALTMON_3: ::nl_item = 60; +pub const ALTMON_4: ::nl_item = 61; +pub const ALTMON_5: ::nl_item = 62; +pub const ALTMON_6: ::nl_item = 63; +pub const ALTMON_7: ::nl_item = 64; +pub const ALTMON_8: ::nl_item = 65; +pub const ALTMON_9: ::nl_item = 66; +pub const ALTMON_10: ::nl_item = 67; +pub const ALTMON_11: ::nl_item = 68; +pub const ALTMON_12: ::nl_item = 69; + +pub const KERN_RND: ::c_int = 31; + +// https://github.com/bitrig/bitrig/blob/master/sys/net/if.h#L187 +pub const IFF_UP: ::c_int = 0x1; // interface is up +pub const IFF_BROADCAST: ::c_int = 0x2; // broadcast address valid +pub const IFF_DEBUG: ::c_int = 0x4; // turn on debugging +pub const IFF_LOOPBACK: ::c_int = 0x8; // is a loopback net +pub const IFF_POINTOPOINT: ::c_int = 0x10; // interface is point-to-point link +pub const IFF_NOTRAILERS: ::c_int = 0x20; // avoid use of trailers +pub const IFF_RUNNING: ::c_int = 0x40; // resources allocated +pub const IFF_NOARP: ::c_int = 0x80; // no address resolution protocol +pub const IFF_PROMISC: ::c_int = 0x100; // receive all packets +pub const IFF_ALLMULTI: ::c_int = 0x200; // receive all multicast packets +pub const IFF_OACTIVE: ::c_int = 0x400; // transmission in progress +pub const IFF_SIMPLEX: ::c_int = 0x800; // can't hear own transmissions +pub const IFF_LINK0: ::c_int = 0x1000; // per link layer defined bit +pub const IFF_LINK1: ::c_int = 0x2000; // per link layer defined bit +pub const IFF_LINK2: ::c_int = 0x4000; // per link layer defined bit +pub const IFF_MULTICAST: ::c_int = 0x8000; // supports multicast + +extern { + pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; + pub fn duplocale(base: ::locale_t) -> ::locale_t; + pub fn freelocale(loc: ::locale_t) -> ::c_int; + pub fn newlocale(mask: ::c_int, + locale: *const ::c_char, + base: ::locale_t) -> ::locale_t; + pub fn uselocale(loc: ::locale_t) -> ::locale_t; + pub fn pledge(promises: *const ::c_char, + paths: *mut *const ::c_char) -> ::c_int; + pub fn querylocale(mask: ::c_int, loc: ::locale_t) -> *const ::c_char; +} + +cfg_if! { + if #[cfg(target_arch = "x86")] { + mod x86; + pub use self::x86::*; + } else if #[cfg(target_arch = "x86_64")] { + mod x86_64; + pub use self::x86_64::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86_64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86_64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2 @@ +pub type c_long = i64; +pub type c_ulong = u64; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/bitrig/x86.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2 @@ +pub type c_long = i32; +pub type c_ulong = u32; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,736 @@ +use unix::bsd::O_SYNC; + +pub type clock_t = i64; +pub type suseconds_t = ::c_long; +pub type dev_t = i32; +pub type sigset_t = ::c_uint; +pub type blksize_t = ::int32_t; +pub type fsblkcnt_t = ::uint64_t; +pub type fsfilcnt_t = ::uint64_t; +pub type pthread_attr_t = *mut ::c_void; +pub type pthread_mutex_t = *mut ::c_void; +pub type pthread_mutexattr_t = *mut ::c_void; +pub type pthread_cond_t = *mut ::c_void; +pub type pthread_condattr_t = *mut ::c_void; +pub type pthread_rwlock_t = *mut ::c_void; +pub type pthread_rwlockattr_t = *mut ::c_void; + +s! { + pub struct dirent { + pub d_fileno: ::ino_t, + pub d_off: ::off_t, + pub d_reclen: u16, + pub d_type: u8, + pub d_namlen: u8, + __d_padding: [u8; 4], + pub d_name: [::c_char; 256], + } + + pub struct glob_t { + pub gl_pathc: ::c_int, + pub gl_matchc: ::c_int, + pub gl_offs: ::c_int, + pub gl_flags: ::c_int, + pub gl_pathv: *mut *mut ::c_char, + __unused1: *mut ::c_void, + __unused2: *mut ::c_void, + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + __unused6: *mut ::c_void, + __unused7: *mut ::c_void, + } + + pub struct kevent { + pub ident: ::uintptr_t, + pub filter: ::c_short, + pub flags: ::c_ushort, + pub fflags: ::c_uint, + pub data: ::int64_t, + pub udata: *mut ::c_void, + } + + pub struct stat { + pub st_mode: ::mode_t, + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_size: ::off_t, + pub st_blocks: ::blkcnt_t, + pub st_blksize: ::blksize_t, + pub st_flags: ::uint32_t, + pub st_gen: ::uint32_t, + pub st_birthtime: ::time_t, + pub st_birthtime_nsec: ::c_long, + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + } + + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + pub ai_addrlen: ::socklen_t, + pub ai_addr: *mut ::sockaddr, + pub ai_canonname: *mut ::c_char, + pub ai_next: *mut ::addrinfo, + } + + pub struct sockaddr_storage { + pub ss_len: u8, + pub ss_family: ::sa_family_t, + __ss_pad1: [u8; 6], + __ss_pad2: i64, + __ss_pad3: [u8; 240], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_code: ::c_int, + pub si_errno: ::c_int, + pub si_addr: *mut ::c_char, + #[cfg(target_pointer_width = "32")] + __pad: [u8; 112], + #[cfg(target_pointer_width = "64")] + __pad: [u8; 108], + } + + pub struct Dl_info { + pub dli_fname: *const ::c_char, + pub dli_fbase: *mut ::c_void, + pub dli_sname: *const ::c_char, + pub dli_saddr: *mut ::c_void, + } + + pub struct lastlog { + ll_time: ::time_t, + ll_line: [::c_char; UT_LINESIZE], + ll_host: [::c_char; UT_HOSTSIZE], + } + + pub struct utmp { + pub ut_line: [::c_char; UT_LINESIZE], + pub ut_name: [::c_char; UT_NAMESIZE], + pub ut_host: [::c_char; UT_HOSTSIZE], + pub ut_time: ::time_t, + } + + pub struct if_data { + pub ifi_type: ::c_uchar, + pub ifi_addrlen: ::c_uchar, + pub ifi_hdrlen: ::c_uchar, + pub ifi_link_state: ::c_uchar, + pub ifi_mtu: u32, + pub ifi_metric: u32, + pub ifi_rdomain: u32, + pub ifi_baudrate: u64, + pub ifi_ipackets: u64, + pub ifi_ierrors: u64, + pub ifi_opackets: u64, + pub ifi_oerrors: u64, + pub ifi_collisions: u64, + pub ifi_ibytes: u64, + pub ifi_obytes: u64, + pub ifi_imcasts: u64, + pub ifi_omcasts: u64, + pub ifi_iqdrops: u64, + pub ifi_oqdrops: u64, + pub ifi_noproto: u64, + pub ifi_capabilities: u32, + pub ifi_lastchange: ::timeval, + } + + pub struct if_msghdr { + pub ifm_msglen: ::c_ushort, + pub ifm_version: ::c_uchar, + pub ifm_type: ::c_uchar, + pub ifm_hdrlen: ::c_ushort, + pub ifm_index: ::c_ushort, + pub ifm_tableid: ::c_ushort, + pub ifm_pad1: ::c_uchar, + pub ifm_pad2: ::c_uchar, + pub ifm_addrs: ::c_int, + pub ifm_flags: ::c_int, + pub ifm_xflags: ::c_int, + pub ifm_data: if_data, + } + + pub struct sockaddr_dl { + pub sdl_len: ::c_uchar, + pub sdl_family: ::c_uchar, + pub sdl_index: ::c_ushort, + pub sdl_type: ::c_uchar, + pub sdl_nlen: ::c_uchar, + pub sdl_alen: ::c_uchar, + pub sdl_slen: ::c_uchar, + pub sdl_data: [::c_char; 24], + } + + pub struct sockpeercred { + pub uid: ::uid_t, + pub gid: ::gid_t, + pub pid: ::pid_t, + } +} + +pub const UT_NAMESIZE: usize = 32; +pub const UT_LINESIZE: usize = 8; +pub const UT_HOSTSIZE: usize = 256; + +pub const O_CLOEXEC: ::c_int = 0x10000; +pub const O_DIRECTORY: ::c_int = 0x20000; +pub const O_RSYNC: ::c_int = O_SYNC; + +pub const MS_SYNC : ::c_int = 0x0002; +pub const MS_INVALIDATE : ::c_int = 0x0004; + +pub const PTHREAD_STACK_MIN : ::size_t = 2048; + +pub const POLLNORM: ::c_short = ::POLLRDNORM; + +pub const ENOATTR : ::c_int = 83; +pub const EILSEQ : ::c_int = 84; +pub const EOVERFLOW : ::c_int = 87; +pub const ECANCELED : ::c_int = 88; +pub const EIDRM : ::c_int = 89; +pub const ENOMSG : ::c_int = 90; +pub const ENOTSUP : ::c_int = 91; +pub const EBADMSG : ::c_int = 92; +pub const ENOTRECOVERABLE : ::c_int = 93; +pub const EOWNERDEAD : ::c_int = 94; +pub const EPROTO : ::c_int = 95; +pub const ELAST : ::c_int = 95; + +pub const F_DUPFD_CLOEXEC : ::c_int = 10; + +pub const AT_FDCWD: ::c_int = -100; +pub const AT_EACCESS: ::c_int = 0x01; +pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x02; +pub const AT_SYMLINK_FOLLOW: ::c_int = 0x04; +pub const AT_REMOVEDIR: ::c_int = 0x08; + +pub const RLIM_NLIMITS: ::c_int = 9; + +pub const SO_TIMESTAMP: ::c_int = 0x0800; +pub const SO_SNDTIMEO: ::c_int = 0x1005; +pub const SO_RCVTIMEO: ::c_int = 0x1006; +pub const SO_BINDANY: ::c_int = 0x1000; +pub const SO_NETPROC: ::c_int = 0x1020; +pub const SO_RTABLE: ::c_int = 0x1021; +pub const SO_PEERCRED: ::c_int = 0x1022; +pub const SO_SPLICE: ::c_int = 0x1023; + +// sys/netinet/in.h +// Protocols (RFC 1700) +// NOTE: These are in addition to the constants defined in src/unix/mod.rs + +// IPPROTO_IP defined in src/unix/mod.rs +/// Hop-by-hop option header +pub const IPPROTO_HOPOPTS: ::c_int = 0; +// IPPROTO_ICMP defined in src/unix/mod.rs +/// group mgmt protocol +pub const IPPROTO_IGMP: ::c_int = 2; +/// gateway^2 (deprecated) +pub const IPPROTO_GGP: ::c_int = 3; +/// for compatibility +pub const IPPROTO_IPIP: ::c_int = 4; +// IPPROTO_TCP defined in src/unix/mod.rs +/// exterior gateway protocol +pub const IPPROTO_EGP: ::c_int = 8; +/// pup +pub const IPPROTO_PUP: ::c_int = 12; +// IPPROTO_UDP defined in src/unix/mod.rs +/// xns idp +pub const IPPROTO_IDP: ::c_int = 22; +/// tp-4 w/ class negotiation +pub const IPPROTO_TP: ::c_int = 29; +// IPPROTO_IPV6 defined in src/unix/mod.rs +/// IP6 routing header +pub const IPPROTO_ROUTING: ::c_int = 43; +/// IP6 fragmentation header +pub const IPPROTO_FRAGMENT: ::c_int = 44; +/// resource reservation +pub const IPPROTO_RSVP: ::c_int = 46; +/// General Routing Encap. +pub const IPPROTO_GRE: ::c_int = 47; +/// IP6 Encap Sec. Payload +pub const IPPROTO_ESP: ::c_int = 50; +/// IP6 Auth Header +pub const IPPROTO_AH: ::c_int = 51; +/// IP Mobility RFC 2004 +pub const IPPROTO_MOBILE: ::c_int = 55; +// IPPROTO_ICMPV6 defined in src/unix/mod.rs +/// IP6 no next header +pub const IPPROTO_NONE: ::c_int = 59; +/// IP6 destination option +pub const IPPROTO_DSTOPTS: ::c_int = 60; +/// ISO cnlp +pub const IPPROTO_EON: ::c_int = 80; +/// Ethernet-in-IP +pub const IPPROTO_ETHERIP: ::c_int = 97; +/// encapsulation header +pub const IPPROTO_ENCAP: ::c_int = 98; +/// Protocol indep. multicast +pub const IPPROTO_PIM: ::c_int = 103; +/// IP Payload Comp. Protocol +pub const IPPROTO_IPCOMP: ::c_int = 108; +/// CARP +pub const IPPROTO_CARP: ::c_int = 112; +/// unicast MPLS packet +pub const IPPROTO_MPLS: ::c_int = 137; +/// PFSYNC +pub const IPPROTO_PFSYNC: ::c_int = 240; +pub const IPPROTO_MAX: ::c_int = 256; + +/* Only used internally, so it can be outside the range of valid IP protocols */ +/// Divert sockets +pub const IPPROTO_DIVERT: ::c_int = 258; + +pub const AF_ECMA: ::c_int = 8; +pub const AF_ROUTE: ::c_int = 17; +pub const AF_ENCAP: ::c_int = 28; +pub const AF_SIP: ::c_int = 29; +pub const AF_KEY: ::c_int = 30; +pub const pseudo_AF_HDRCMPLT: ::c_int = 31; +pub const AF_BLUETOOTH: ::c_int = 32; +pub const AF_MPLS: ::c_int = 33; +pub const pseudo_AF_PFLOW: ::c_int = 34; +pub const pseudo_AF_PIPEX: ::c_int = 35; +#[doc(hidden)] +pub const AF_MAX: ::c_int = 36; + +#[doc(hidden)] +pub const NET_MAXID: ::c_int = AF_MAX; +pub const NET_RT_DUMP: ::c_int = 1; +pub const NET_RT_FLAGS: ::c_int = 2; +pub const NET_RT_IFLIST: ::c_int = 3; +pub const NET_RT_STATS: ::c_int = 4; +pub const NET_RT_TABLE: ::c_int = 5; +pub const NET_RT_IFNAMES: ::c_int = 6; +#[doc(hidden)] +pub const NET_RT_MAXID: ::c_int = 7; + +pub const IPV6_JOIN_GROUP: ::c_int = 12; +pub const IPV6_LEAVE_GROUP: ::c_int = 13; + +pub const PF_ROUTE: ::c_int = AF_ROUTE; +pub const PF_ECMA: ::c_int = AF_ECMA; +pub const PF_ENCAP: ::c_int = AF_ENCAP; +pub const PF_SIP: ::c_int = AF_SIP; +pub const PF_KEY: ::c_int = AF_KEY; +pub const PF_BPF: ::c_int = pseudo_AF_HDRCMPLT; +pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; +pub const PF_MPLS: ::c_int = AF_MPLS; +pub const PF_PFLOW: ::c_int = pseudo_AF_PFLOW; +pub const PF_PIPEX: ::c_int = pseudo_AF_PIPEX; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; + +pub const SCM_TIMESTAMP: ::c_int = 0x04; + +pub const O_DSYNC : ::c_int = 128; + +pub const MAP_RENAME : ::c_int = 0x0000; +pub const MAP_NORESERVE : ::c_int = 0x0000; +pub const MAP_HASSEMAPHORE : ::c_int = 0x0000; + +pub const EIPSEC : ::c_int = 82; +pub const ENOMEDIUM : ::c_int = 85; +pub const EMEDIUMTYPE : ::c_int = 86; + +pub const EAI_BADFLAGS: ::c_int = -1; +pub const EAI_NONAME: ::c_int = -2; +pub const EAI_AGAIN: ::c_int = -3; +pub const EAI_FAIL: ::c_int = -4; +pub const EAI_NODATA: ::c_int = -5; +pub const EAI_FAMILY: ::c_int = -6; +pub const EAI_SOCKTYPE: ::c_int = -7; +pub const EAI_SERVICE: ::c_int = -8; +pub const EAI_MEMORY: ::c_int = -10; +pub const EAI_SYSTEM: ::c_int = -11; +pub const EAI_OVERFLOW: ::c_int = -14; + +pub const RUSAGE_THREAD: ::c_int = 1; + +pub const MAP_COPY : ::c_int = 0x0002; +pub const MAP_NOEXTEND : ::c_int = 0x0000; + +pub const _PC_LINK_MAX : ::c_int = 1; +pub const _PC_MAX_CANON : ::c_int = 2; +pub const _PC_MAX_INPUT : ::c_int = 3; +pub const _PC_NAME_MAX : ::c_int = 4; +pub const _PC_PATH_MAX : ::c_int = 5; +pub const _PC_PIPE_BUF : ::c_int = 6; +pub const _PC_CHOWN_RESTRICTED : ::c_int = 7; +pub const _PC_NO_TRUNC : ::c_int = 8; +pub const _PC_VDISABLE : ::c_int = 9; +pub const _PC_2_SYMLINKS : ::c_int = 10; +pub const _PC_ALLOC_SIZE_MIN : ::c_int = 11; +pub const _PC_ASYNC_IO : ::c_int = 12; +pub const _PC_FILESIZEBITS : ::c_int = 13; +pub const _PC_PRIO_IO : ::c_int = 14; +pub const _PC_REC_INCR_XFER_SIZE : ::c_int = 15; +pub const _PC_REC_MAX_XFER_SIZE : ::c_int = 16; +pub const _PC_REC_MIN_XFER_SIZE : ::c_int = 17; +pub const _PC_REC_XFER_ALIGN : ::c_int = 18; +pub const _PC_SYMLINK_MAX : ::c_int = 19; +pub const _PC_SYNC_IO : ::c_int = 20; +pub const _PC_TIMESTAMP_RESOLUTION : ::c_int = 21; + +pub const _SC_CLK_TCK : ::c_int = 3; +pub const _SC_SEM_NSEMS_MAX : ::c_int = 31; +pub const _SC_SEM_VALUE_MAX : ::c_int = 32; +pub const _SC_HOST_NAME_MAX : ::c_int = 33; +pub const _SC_MONOTONIC_CLOCK : ::c_int = 34; +pub const _SC_2_PBS : ::c_int = 35; +pub const _SC_2_PBS_ACCOUNTING : ::c_int = 36; +pub const _SC_2_PBS_CHECKPOINT : ::c_int = 37; +pub const _SC_2_PBS_LOCATE : ::c_int = 38; +pub const _SC_2_PBS_MESSAGE : ::c_int = 39; +pub const _SC_2_PBS_TRACK : ::c_int = 40; +pub const _SC_ADVISORY_INFO : ::c_int = 41; +pub const _SC_AIO_LISTIO_MAX : ::c_int = 42; +pub const _SC_AIO_MAX : ::c_int = 43; +pub const _SC_AIO_PRIO_DELTA_MAX : ::c_int = 44; +pub const _SC_ASYNCHRONOUS_IO : ::c_int = 45; +pub const _SC_ATEXIT_MAX : ::c_int = 46; +pub const _SC_BARRIERS : ::c_int = 47; +pub const _SC_CLOCK_SELECTION : ::c_int = 48; +pub const _SC_CPUTIME : ::c_int = 49; +pub const _SC_DELAYTIMER_MAX : ::c_int = 50; +pub const _SC_IOV_MAX : ::c_int = 51; +pub const _SC_IPV6 : ::c_int = 52; +pub const _SC_MAPPED_FILES : ::c_int = 53; +pub const _SC_MEMLOCK : ::c_int = 54; +pub const _SC_MEMLOCK_RANGE : ::c_int = 55; +pub const _SC_MEMORY_PROTECTION : ::c_int = 56; +pub const _SC_MESSAGE_PASSING : ::c_int = 57; +pub const _SC_MQ_OPEN_MAX : ::c_int = 58; +pub const _SC_MQ_PRIO_MAX : ::c_int = 59; +pub const _SC_PRIORITIZED_IO : ::c_int = 60; +pub const _SC_PRIORITY_SCHEDULING : ::c_int = 61; +pub const _SC_RAW_SOCKETS : ::c_int = 62; +pub const _SC_READER_WRITER_LOCKS : ::c_int = 63; +pub const _SC_REALTIME_SIGNALS : ::c_int = 64; +pub const _SC_REGEXP : ::c_int = 65; +pub const _SC_RTSIG_MAX : ::c_int = 66; +pub const _SC_SEMAPHORES : ::c_int = 67; +pub const _SC_SHARED_MEMORY_OBJECTS : ::c_int = 68; +pub const _SC_SHELL : ::c_int = 69; +pub const _SC_SIGQUEUE_MAX : ::c_int = 70; +pub const _SC_SPAWN : ::c_int = 71; +pub const _SC_SPIN_LOCKS : ::c_int = 72; +pub const _SC_SPORADIC_SERVER : ::c_int = 73; +pub const _SC_SS_REPL_MAX : ::c_int = 74; +pub const _SC_SYNCHRONIZED_IO : ::c_int = 75; +pub const _SC_SYMLOOP_MAX : ::c_int = 76; +pub const _SC_THREAD_ATTR_STACKADDR : ::c_int = 77; +pub const _SC_THREAD_ATTR_STACKSIZE : ::c_int = 78; +pub const _SC_THREAD_CPUTIME : ::c_int = 79; +pub const _SC_THREAD_DESTRUCTOR_ITERATIONS : ::c_int = 80; +pub const _SC_THREAD_KEYS_MAX : ::c_int = 81; +pub const _SC_THREAD_PRIO_INHERIT : ::c_int = 82; +pub const _SC_THREAD_PRIO_PROTECT : ::c_int = 83; +pub const _SC_THREAD_PRIORITY_SCHEDULING : ::c_int = 84; +pub const _SC_THREAD_PROCESS_SHARED : ::c_int = 85; +pub const _SC_THREAD_ROBUST_PRIO_INHERIT : ::c_int = 86; +pub const _SC_THREAD_ROBUST_PRIO_PROTECT : ::c_int = 87; +pub const _SC_THREAD_SPORADIC_SERVER : ::c_int = 88; +pub const _SC_THREAD_STACK_MIN : ::c_int = 89; +pub const _SC_THREAD_THREADS_MAX : ::c_int = 90; +pub const _SC_THREADS : ::c_int = 91; +pub const _SC_TIMEOUTS : ::c_int = 92; +pub const _SC_TIMER_MAX : ::c_int = 93; +pub const _SC_TIMERS : ::c_int = 94; +pub const _SC_TRACE : ::c_int = 95; +pub const _SC_TRACE_EVENT_FILTER : ::c_int = 96; +pub const _SC_TRACE_EVENT_NAME_MAX : ::c_int = 97; +pub const _SC_TRACE_INHERIT : ::c_int = 98; +pub const _SC_TRACE_LOG : ::c_int = 99; +pub const _SC_GETGR_R_SIZE_MAX : ::c_int = 100; +pub const _SC_GETPW_R_SIZE_MAX : ::c_int = 101; +pub const _SC_LOGIN_NAME_MAX : ::c_int = 102; +pub const _SC_THREAD_SAFE_FUNCTIONS : ::c_int = 103; +pub const _SC_TRACE_NAME_MAX : ::c_int = 104; +pub const _SC_TRACE_SYS_MAX : ::c_int = 105; +pub const _SC_TRACE_USER_EVENT_MAX : ::c_int = 106; +pub const _SC_TTY_NAME_MAX : ::c_int = 107; +pub const _SC_TYPED_MEMORY_OBJECTS : ::c_int = 108; +pub const _SC_V6_ILP32_OFF32 : ::c_int = 109; +pub const _SC_V6_ILP32_OFFBIG : ::c_int = 110; +pub const _SC_V6_LP64_OFF64 : ::c_int = 111; +pub const _SC_V6_LPBIG_OFFBIG : ::c_int = 112; +pub const _SC_V7_ILP32_OFF32 : ::c_int = 113; +pub const _SC_V7_ILP32_OFFBIG : ::c_int = 114; +pub const _SC_V7_LP64_OFF64 : ::c_int = 115; +pub const _SC_V7_LPBIG_OFFBIG : ::c_int = 116; +pub const _SC_XOPEN_CRYPT : ::c_int = 117; +pub const _SC_XOPEN_ENH_I18N : ::c_int = 118; +pub const _SC_XOPEN_LEGACY : ::c_int = 119; +pub const _SC_XOPEN_REALTIME : ::c_int = 120; +pub const _SC_XOPEN_REALTIME_THREADS : ::c_int = 121; +pub const _SC_XOPEN_STREAMS : ::c_int = 122; +pub const _SC_XOPEN_UNIX : ::c_int = 123; +pub const _SC_XOPEN_UUCP : ::c_int = 124; +pub const _SC_XOPEN_VERSION : ::c_int = 125; +pub const _SC_PHYS_PAGES : ::c_int = 500; +pub const _SC_AVPHYS_PAGES : ::c_int = 501; +pub const _SC_NPROCESSORS_CONF : ::c_int = 502; +pub const _SC_NPROCESSORS_ONLN : ::c_int = 503; + +pub const FD_SETSIZE: usize = 1024; + +pub const ST_NOSUID: ::c_ulong = 2; + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = 0 as *mut _; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = 0 as *mut _; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = 0 as *mut _; + +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 1; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 2; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 3; +pub const PTHREAD_MUTEX_STRICT_NP: ::c_int = 4; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_STRICT_NP; + +pub const EVFILT_AIO: ::int16_t = -3; +pub const EVFILT_PROC: ::int16_t = -5; +pub const EVFILT_READ: ::int16_t = -1; +pub const EVFILT_SIGNAL: ::int16_t = -6; +pub const EVFILT_TIMER: ::int16_t = -7; +pub const EVFILT_VNODE: ::int16_t = -4; +pub const EVFILT_WRITE: ::int16_t = -2; + +pub const EV_ADD: ::uint16_t = 0x1; +pub const EV_DELETE: ::uint16_t = 0x2; +pub const EV_ENABLE: ::uint16_t = 0x4; +pub const EV_DISABLE: ::uint16_t = 0x8; +pub const EV_ONESHOT: ::uint16_t = 0x10; +pub const EV_CLEAR: ::uint16_t = 0x20; +pub const EV_RECEIPT: ::uint16_t = 0x40; +pub const EV_DISPATCH: ::uint16_t = 0x80; +pub const EV_FLAG1: ::uint16_t = 0x2000; +pub const EV_ERROR: ::uint16_t = 0x4000; +pub const EV_EOF: ::uint16_t = 0x8000; +pub const EV_SYSFLAGS: ::uint16_t = 0xf000; + +pub const NOTE_LOWAT: ::uint32_t = 0x00000001; +pub const NOTE_EOF: ::uint32_t = 0x00000002; +pub const NOTE_DELETE: ::uint32_t = 0x00000001; +pub const NOTE_WRITE: ::uint32_t = 0x00000002; +pub const NOTE_EXTEND: ::uint32_t = 0x00000004; +pub const NOTE_ATTRIB: ::uint32_t = 0x00000008; +pub const NOTE_LINK: ::uint32_t = 0x00000010; +pub const NOTE_RENAME: ::uint32_t = 0x00000020; +pub const NOTE_REVOKE: ::uint32_t = 0x00000040; +pub const NOTE_TRUNCATE: ::uint32_t = 0x00000080; +pub const NOTE_EXIT: ::uint32_t = 0x80000000; +pub const NOTE_FORK: ::uint32_t = 0x40000000; +pub const NOTE_EXEC: ::uint32_t = 0x20000000; +pub const NOTE_PDATAMASK: ::uint32_t = 0x000fffff; +pub const NOTE_PCTRLMASK: ::uint32_t = 0xf0000000; +pub const NOTE_TRACK: ::uint32_t = 0x00000001; +pub const NOTE_TRACKERR: ::uint32_t = 0x00000002; +pub const NOTE_CHILD: ::uint32_t = 0x00000004; + +pub const TMP_MAX : ::c_uint = 0x7fffffff; + +pub const NI_MAXHOST: ::size_t = 256; + +pub const RTLD_LOCAL: ::c_int = 0; +pub const CTL_MAXNAME: ::c_int = 12; +pub const CTLTYPE_NODE: ::c_int = 1; +pub const CTLTYPE_INT: ::c_int = 2; +pub const CTLTYPE_STRING: ::c_int = 3; +pub const CTLTYPE_QUAD: ::c_int = 4; +pub const CTLTYPE_STRUCT: ::c_int = 5; +pub const CTL_UNSPEC: ::c_int = 0; +pub const CTL_KERN: ::c_int = 1; +pub const CTL_VM: ::c_int = 2; +pub const CTL_FS: ::c_int = 3; +pub const CTL_NET: ::c_int = 4; +pub const CTL_DEBUG: ::c_int = 5; +pub const CTL_HW: ::c_int = 6; +pub const CTL_MACHDEP: ::c_int = 7; +pub const CTL_DDB: ::c_int = 9; +pub const CTL_VFS: ::c_int = 10; +pub const CTL_MAXID: ::c_int = 11; +pub const KERN_OSTYPE: ::c_int = 1; +pub const KERN_OSRELEASE: ::c_int = 2; +pub const KERN_OSREV: ::c_int = 3; +pub const KERN_VERSION: ::c_int = 4; +pub const KERN_MAXVNODES: ::c_int = 5; +pub const KERN_MAXPROC: ::c_int = 6; +pub const KERN_MAXFILES: ::c_int = 7; +pub const KERN_ARGMAX: ::c_int = 8; +pub const KERN_SECURELVL: ::c_int = 9; +pub const KERN_HOSTNAME: ::c_int = 10; +pub const KERN_HOSTID: ::c_int = 11; +pub const KERN_CLOCKRATE: ::c_int = 12; +pub const KERN_PROF: ::c_int = 16; +pub const KERN_POSIX1: ::c_int = 17; +pub const KERN_NGROUPS: ::c_int = 18; +pub const KERN_JOB_CONTROL: ::c_int = 19; +pub const KERN_SAVED_IDS: ::c_int = 20; +pub const KERN_BOOTTIME: ::c_int = 21; +pub const KERN_DOMAINNAME: ::c_int = 22; +pub const KERN_MAXPARTITIONS: ::c_int = 23; +pub const KERN_RAWPARTITION: ::c_int = 24; +pub const KERN_MAXTHREAD: ::c_int = 25; +pub const KERN_NTHREADS: ::c_int = 26; +pub const KERN_OSVERSION: ::c_int = 27; +pub const KERN_SOMAXCONN: ::c_int = 28; +pub const KERN_SOMINCONN: ::c_int = 29; +pub const KERN_USERMOUNT: ::c_int = 30; +pub const KERN_NOSUIDCOREDUMP: ::c_int = 32; +pub const KERN_FSYNC: ::c_int = 33; +pub const KERN_SYSVMSG: ::c_int = 34; +pub const KERN_SYSVSEM: ::c_int = 35; +pub const KERN_SYSVSHM: ::c_int = 36; +pub const KERN_ARND: ::c_int = 37; +pub const KERN_MSGBUFSIZE: ::c_int = 38; +pub const KERN_MALLOCSTATS: ::c_int = 39; +pub const KERN_CPTIME: ::c_int = 40; +pub const KERN_NCHSTATS: ::c_int = 41; +pub const KERN_FORKSTAT: ::c_int = 42; +pub const KERN_NSELCOLL: ::c_int = 43; +pub const KERN_TTY: ::c_int = 44; +pub const KERN_CCPU: ::c_int = 45; +pub const KERN_FSCALE: ::c_int = 46; +pub const KERN_NPROCS: ::c_int = 47; +pub const KERN_MSGBUF: ::c_int = 48; +pub const KERN_POOL: ::c_int = 49; +pub const KERN_STACKGAPRANDOM: ::c_int = 50; +pub const KERN_SYSVIPC_INFO: ::c_int = 51; +pub const KERN_SPLASSERT: ::c_int = 54; +pub const KERN_PROC_ARGS: ::c_int = 55; +pub const KERN_NFILES: ::c_int = 56; +pub const KERN_TTYCOUNT: ::c_int = 57; +pub const KERN_NUMVNODES: ::c_int = 58; +pub const KERN_MBSTAT: ::c_int = 59; +pub const KERN_SEMINFO: ::c_int = 61; +pub const KERN_SHMINFO: ::c_int = 62; +pub const KERN_INTRCNT: ::c_int = 63; +pub const KERN_WATCHDOG: ::c_int = 64; +pub const KERN_PROC: ::c_int = 66; +pub const KERN_MAXCLUSTERS: ::c_int = 67; +pub const KERN_EVCOUNT: ::c_int = 68; +pub const KERN_TIMECOUNTER: ::c_int = 69; +pub const KERN_MAXLOCKSPERUID: ::c_int = 70; +pub const KERN_CPTIME2: ::c_int = 71; +pub const KERN_CACHEPCT: ::c_int = 72; +pub const KERN_FILE: ::c_int = 73; +pub const KERN_CONSDEV: ::c_int = 75; +pub const KERN_NETLIVELOCKS: ::c_int = 76; +pub const KERN_POOL_DEBUG: ::c_int = 77; +pub const KERN_PROC_CWD: ::c_int = 78; +pub const KERN_PROC_NOBROADCASTKILL: ::c_int = 79; +pub const KERN_PROC_VMMAP: ::c_int = 80; +pub const KERN_GLOBAL_PTRACE: ::c_int = 81; +pub const KERN_CONSBUFSIZE: ::c_int = 82; +pub const KERN_CONSBUF: ::c_int = 83; +pub const KERN_MAXID: ::c_int = 84; +pub const KERN_PROC_ALL: ::c_int = 0; +pub const KERN_PROC_PID: ::c_int = 1; +pub const KERN_PROC_PGRP: ::c_int = 2; +pub const KERN_PROC_SESSION: ::c_int = 3; +pub const KERN_PROC_TTY: ::c_int = 4; +pub const KERN_PROC_UID: ::c_int = 5; +pub const KERN_PROC_RUID: ::c_int = 6; +pub const KERN_PROC_KTHREAD: ::c_int = 7; +pub const KERN_PROC_SHOW_THREADS: ::c_int = 0x40000000; +pub const KERN_SYSVIPC_MSG_INFO: ::c_int = 1; +pub const KERN_SYSVIPC_SEM_INFO: ::c_int = 2; +pub const KERN_SYSVIPC_SHM_INFO: ::c_int = 3; +pub const KERN_PROC_ARGV: ::c_int = 1; +pub const KERN_PROC_NARGV: ::c_int = 2; +pub const KERN_PROC_ENV: ::c_int = 3; +pub const KERN_PROC_NENV: ::c_int = 4; +pub const KI_NGROUPS: ::c_int = 16; +pub const KI_MAXCOMLEN: ::c_int = 24; +pub const KI_WMESGLEN: ::c_int = 8; +pub const KI_MAXLOGNAME: ::c_int = 32; +pub const KI_EMULNAMELEN: ::c_int = 8; + +pub const CHWFLOW: ::tcflag_t = ::MDMBUF | ::CRTSCTS; +pub const OLCUC: ::tcflag_t = 0x20; +pub const ONOCR: ::tcflag_t = 0x40; +pub const ONLRET: ::tcflag_t = 0x80; + +pub const SOCK_CLOEXEC: ::c_int = 0x8000; +pub const SOCK_NONBLOCK: ::c_int = 0x4000; +pub const SOCK_DNS: ::c_int = 0x1000; + +pub const WCONTINUED: ::c_int = 8; + +f! { + pub fn WIFCONTINUED(status: ::c_int) -> bool { + status & 0o177777 == 0o177777 + } +} + +extern { + pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; + pub fn getnameinfo(sa: *const ::sockaddr, + salen: ::socklen_t, + host: *mut ::c_char, + hostlen: ::size_t, + serv: *mut ::c_char, + servlen: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn kevent(kq: ::c_int, + changelist: *const ::kevent, + nchanges: ::c_int, + eventlist: *mut ::kevent, + nevents: ::c_int, + timeout: *const ::timespec) -> ::c_int; + pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) + -> ::c_int; + pub fn pthread_main_np() -> ::c_int; + pub fn pthread_set_name_np(tid: ::pthread_t, name: *const ::c_char); + pub fn pthread_stackseg_np(thread: ::pthread_t, + sinfo: *mut ::stack_t) -> ::c_int; + pub fn sysctl(name: *const ::c_int, + namelen: ::c_uint, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *mut ::c_void, + newlen: ::size_t) + -> ::c_int; + pub fn getentropy(buf: *mut ::c_void, buflen: ::size_t) -> ::c_int; + pub fn setresgid(rgid: ::gid_t, egid: ::gid_t, sgid: ::gid_t) -> ::c_int; + pub fn setresuid(ruid: ::uid_t, euid: ::uid_t, suid: ::uid_t) -> ::c_int; +} + +cfg_if! { + if #[cfg(target_os = "openbsd")] { + mod openbsd; + pub use self::openbsd::*; + } else if #[cfg(target_os = "bitrig")] { + mod bitrig; + pub use self::bitrig::*; + } else { + // Unknown target_os + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/aarch64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/aarch64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3 @@ +pub type c_long = i64; +pub type c_ulong = u64; +pub type c_char = u8; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,73 @@ +s! { + pub struct lconv { + pub decimal_point: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + pub grouping: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub currency_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub int_frac_digits: ::c_char, + pub frac_digits: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + pub n_sign_posn: ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_n_cs_precedes: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + pub int_n_sign_posn: ::c_char, + } +} + +// https://github.com/openbsd/src/blob/master/sys/net/if.h#L187 +pub const IFF_UP: ::c_int = 0x1; // interface is up +pub const IFF_BROADCAST: ::c_int = 0x2; // broadcast address valid +pub const IFF_DEBUG: ::c_int = 0x4; // turn on debugging +pub const IFF_LOOPBACK: ::c_int = 0x8; // is a loopback net +pub const IFF_POINTOPOINT: ::c_int = 0x10; // interface is point-to-point link +pub const IFF_STATICARP: ::c_int = 0x20; // only static ARP +pub const IFF_RUNNING: ::c_int = 0x40; // resources allocated +pub const IFF_NOARP: ::c_int = 0x80; // no address resolution protocol +pub const IFF_PROMISC: ::c_int = 0x100; // receive all packets +pub const IFF_ALLMULTI: ::c_int = 0x200; // receive all multicast packets +pub const IFF_OACTIVE: ::c_int = 0x400; // transmission in progress +pub const IFF_SIMPLEX: ::c_int = 0x800; // can't hear own transmissions +pub const IFF_LINK0: ::c_int = 0x1000; // per link layer defined bit +pub const IFF_LINK1: ::c_int = 0x2000; // per link layer defined bit +pub const IFF_LINK2: ::c_int = 0x4000; // per link layer defined bit +pub const IFF_MULTICAST: ::c_int = 0x8000; // supports multicast + +extern { + pub fn accept4(s: ::c_int, addr: *mut ::sockaddr, + addrlen: *mut ::socklen_t, flags: ::c_int) -> ::c_int; + pub fn execvpe(file: *const ::c_char, argv: *const *const ::c_char, + envp: *const *const ::c_char) -> ::c_int; + pub fn pledge(promises: *const ::c_char, + execpromises: *const ::c_char) -> ::c_int; + pub fn strtonum(nptr: *const ::c_char, minval: ::c_longlong, + maxval: ::c_longlong, + errstr: *mut *const ::c_char) -> ::c_longlong; +} + +cfg_if! { + if #[cfg(target_arch = "x86")] { + mod x86; + pub use self::x86::*; + } else if #[cfg(target_arch = "x86_64")] { + mod x86_64; + pub use self::x86_64::*; + } else if #[cfg(target_arch = "aarch64")] { + mod aarch64; + pub use self::aarch64::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86_64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86_64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3 @@ +pub type c_long = i64; +pub type c_ulong = u64; +pub type c_char = i8; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/bsd/netbsdlike/openbsdlike/openbsd/x86.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3 @@ +pub type c_long = i32; +pub type c_ulong = u32; +pub type c_char = i8; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/haiku/b32.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/haiku/b32.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/haiku/b32.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/haiku/b32.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3 @@ +pub type c_long = i32; +pub type c_ulong = u32; +pub type time_t = i32; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/haiku/b64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/haiku/b64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/haiku/b64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/haiku/b64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3 @@ +pub type c_ulong = u64; +pub type c_long = i64; +pub type time_t = i64; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/haiku/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/haiku/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/haiku/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/haiku/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1220 @@ +use dox::{mem, Option}; + +pub type rlim_t = ::uintptr_t; +pub type sa_family_t = u8; +pub type pthread_key_t = ::c_int; +pub type nfds_t = ::c_long; +pub type tcflag_t = ::c_uint; +pub type speed_t = ::c_uint; +pub type c_char = i8; +pub type clock_t = i32; +pub type clockid_t = i32; +pub type suseconds_t = i32; +pub type wchar_t = i32; +pub type off_t = i64; +pub type ino_t = i64; +pub type blkcnt_t = i64; +pub type blksize_t = i32; +pub type dev_t = i32; +pub type mode_t = u32; +pub type nlink_t = i32; +pub type useconds_t = u32; +pub type socklen_t = u32; +pub type pthread_t = ::uintptr_t; +pub type pthread_mutexattr_t = ::uintptr_t; +pub type pthread_rwlockattr_t = ::uintptr_t; +pub type sigset_t = u64; +pub type fsblkcnt_t = i64; +pub type fsfilcnt_t = i64; +pub type pthread_attr_t = *mut ::c_void; +pub type nl_item = ::c_int; +pub type id_t = i32; +pub type idtype_t = ::c_uint; + +pub enum timezone {} + +s! { + pub struct sockaddr { + pub sa_len: u8, + pub sa_family: sa_family_t, + pub sa_data: [::c_char; 30], + } + + pub struct sockaddr_in { + pub sin_len: u8, + pub sin_family: sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + pub sin_zero: [u8; 24], + } + + pub struct sockaddr_in6 { + pub sin6_len: u8, + pub sin6_family: sa_family_t, + pub sin6_port: ::in_port_t, + pub sin6_flowinfo: u32, + pub sin6_addr: ::in6_addr, + pub sin6_scope_id: u32, + } + + pub struct sockaddr_un { + pub sun_len: u8, + pub sun_family: sa_family_t, + pub sun_path: [::c_char; 126] + } + + pub struct sockaddr_storage { + pub ss_len: u8, + pub ss_family: sa_family_t, + __ss_pad1: [u8; 6], + __ss_pad2: u64, + __ss_pad3: [u8; 112], + } + + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + pub ai_addrlen: socklen_t, + pub ai_canonname: *mut c_char, + pub ai_addr: *mut ::sockaddr, + pub ai_next: *mut addrinfo, + } + + pub struct fd_set { + fds_bits: [c_ulong; FD_SETSIZE / ULONG_SIZE], + } + + pub struct tm { + pub tm_sec: ::c_int, + pub tm_min: ::c_int, + pub tm_hour: ::c_int, + pub tm_mday: ::c_int, + pub tm_mon: ::c_int, + pub tm_year: ::c_int, + pub tm_wday: ::c_int, + pub tm_yday: ::c_int, + pub tm_isdst: ::c_int, + pub tm_gmtoff: ::c_long, + pub tm_zone: *const ::c_char, + } + + pub struct utsname { + pub sysname: [::c_char; 32], + pub nodename: [::c_char; 32], + pub release: [::c_char; 32], + pub version: [::c_char; 32], + pub machine: [::c_char; 32], + } + + pub struct lconv { + pub decimal_point: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + pub grouping: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub currency_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub int_frac_digits: ::c_char, + pub frac_digits: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + pub n_sign_posn: ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_n_cs_precedes: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + pub int_n_sign_posn: ::c_char, + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::c_int, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::socklen_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::size_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct Dl_info { + pub dli_fname: *const ::c_char, + pub dli_fbase: *mut ::c_void, + pub dli_sname: *const ::c_char, + pub dli_saddr: *mut ::c_void, + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::c_char, + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + pub c_cc: [::cc_t; ::NCCS], + } + + pub struct flock { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_pid: ::pid_t, + } + + pub struct stat { + pub st_dev: dev_t, + pub st_ino: ino_t, + pub st_mode: mode_t, + pub st_nlink: nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_size: off_t, + pub st_rdev: dev_t, + pub st_blksize: blksize_t, + pub st_atime: time_t, + pub st_atime_nsec: c_long, + pub st_mtime: time_t, + pub st_mtime_nsec: c_long, + pub st_ctime: time_t, + pub st_ctime_nsec: c_long, + pub st_crtime: time_t, + pub st_crtime_nsec: c_long, + pub st_type: u32, + pub st_blocks: blkcnt_t, + } + + pub struct dirent { + pub d_dev: dev_t, + pub d_pdev: dev_t, + pub d_ino: ino_t, + pub d_pino: i64, + pub d_reclen: ::c_ushort, + pub d_name: [::c_char; 1024], // Max length is _POSIX_PATH_MAX + } + + pub struct glob_t { + pub gl_pathc: ::size_t, + __unused1: ::size_t, + pub gl_offs: ::size_t, + __unused2: ::size_t, + pub gl_pathv: *mut *mut c_char, + + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + __unused6: *mut ::c_void, + __unused7: *mut ::c_void, + __unused8: *mut ::c_void, + } + + pub struct pthread_mutex_t { + flags: u32, + lock: i32, + unused: i32, + owner: i32, + owner_count: i32, + } + + pub struct pthread_cond_t { + flags: u32, + unused: i32, + mutex: *mut ::c_void, + waiter_count: i32, + lock: i32, + } + + pub struct pthread_rwlock_t { + flags: u32, + owner: i32, + lock_sem: i32, // this is actually a union + lock_count: i32, + reader_count: i32, + writer_count: i32, + waiters: [*mut ::c_void; 2], + } + + pub struct passwd { + pub pw_name: *mut ::c_char, + pub pw_passwd: *mut ::c_char, + pub pw_uid: ::uid_t, + pub pw_gid: ::gid_t, + pub pw_dir: *mut ::c_char, + pub pw_shell: *mut ::c_char, + pub pw_gecos: *mut ::c_char, + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_size: ::size_t, + pub ss_flags: ::c_int, + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_code: ::c_int, + pub si_errno: ::c_int, + pub si_pid: ::pid_t, + pub si_uid: ::uid_t, + pub si_addr: *mut ::c_void, + pub si_status: ::c_int, + pub si_band: c_long, + pub sigval: *mut ::c_void, + } + + pub struct sigaction { + pub sa_sigaction: ::sighandler_t, + pub sa_mask: ::sigset_t, + pub sa_flags: ::c_int, + sa_userdata: *mut ::c_void, + } + + pub struct sigevent { + pub sigev_notify: ::c_int, + pub sigev_signo: ::c_int, + pub sigev_value: ::sigval, + __unused1: *mut ::c_void, // actually a function pointer + pub sigev_notify_attributes: *mut ::pthread_attr_t, + } + + pub struct sem_t { + pub se_type: i32, + pub se_named_id: i32, // this is actually a union + pub se_unnamed: i32, + pub se_padding: [i32; 4], + } + + pub struct pthread_condattr_t { + pub process_shared: bool, + pub clock_id: i32, + } +} + +// intentionally not public, only used for fd_set +cfg_if! { + if #[cfg(target_pointer_width = "32")] { + const ULONG_SIZE: usize = 32; + } else if #[cfg(target_pointer_width = "64")] { + const ULONG_SIZE: usize = 64; + } else { + // Unknown target_pointer_width + } +} + +pub const EXIT_FAILURE: ::c_int = 1; +pub const EXIT_SUCCESS: ::c_int = 0; +pub const RAND_MAX: ::c_int = 2147483647; +pub const EOF: ::c_int = -1; +pub const SEEK_SET: ::c_int = 0; +pub const SEEK_CUR: ::c_int = 1; +pub const SEEK_END: ::c_int = 2; +pub const _IOFBF: ::c_int = 0; +pub const _IONBF: ::c_int = 2; +pub const _IOLBF: ::c_int = 1; + +pub const F_DUPFD: ::c_int = 0x0001; +pub const F_GETFD: ::c_int = 0x0002; +pub const F_SETFD: ::c_int = 0x0004; +pub const F_GETFL: ::c_int = 0x0008; +pub const F_SETFL: ::c_int = 0x0010; +pub const F_GETLK: ::c_int = 0x0020; +pub const F_SETLK: ::c_int = 0x0080; +pub const F_SETLKW: ::c_int = 0x0100; +pub const F_DUPFD_CLOEXEC: ::c_int = 0x0200; + +pub const AT_FDCWD: ::c_int = -1; +pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x01; +pub const AT_SYMLINK_FOLLOW: ::c_int = 0x02; +pub const AT_REMOVEDIR: ::c_int = 0x04; +pub const AT_EACCESS: ::c_int = 0x08; + +pub const POLLIN: ::c_short = 0x0001; +pub const POLLOUT: ::c_short = 0x0002; +pub const POLLRDNORM: ::c_short = POLLIN; +pub const POLLWRNORM: ::c_short = POLLOUT; +pub const POLLRDBAND: ::c_short = 0x0008; +pub const POLLWRBAND: ::c_short = 0x0010; +pub const POLLPRI: ::c_short = 0x0020; +pub const POLLERR: ::c_short = 0x0004; +pub const POLLHUP: ::c_short = 0x0080; +pub const POLLNVAL: ::c_short = 0x1000; + +pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; +pub const PTHREAD_CREATE_DETACHED: ::c_int = 1; + +pub const CLOCK_REALTIME: ::c_int = -1; +pub const CLOCK_MONOTONIC: ::c_int = 0; + +pub const RLIMIT_CORE: ::c_int = 0; +pub const RLIMIT_CPU: ::c_int = 1; +pub const RLIMIT_DATA: ::c_int = 2; +pub const RLIMIT_FSIZE: ::c_int = 3; +pub const RLIMIT_NOFILE: ::c_int = 4; +pub const RLIMIT_AS: ::c_int = 6; +// Haiku specific +pub const RLIMIT_NOVMON: ::c_int = 7; +pub const RLIMIT_NLIMITS: ::c_int = 8; + +pub const RUSAGE_SELF: ::c_int = 0; + +pub const RTLD_LAXY: ::c_int = 0; + +pub const NCCS: usize = 11; + +pub const O_RDONLY: ::c_int = 0x0000; +pub const O_WRONLY: ::c_int = 0x0001; +pub const O_RDWR: ::c_int = 0x0002; +pub const O_ACCMODE: ::c_int = 0x0003; + +pub const O_EXCL: ::c_int = 0x0100; +pub const O_CREAT: ::c_int = 0x0200; +pub const O_TRUNC: ::c_int = 0x0400; +pub const O_NOCTTY: ::c_int = 0x1000; +pub const O_NOTRAVERSE: ::c_int = 0x2000; + +pub const O_CLOEXEC: ::c_int = 0x00000040; +pub const O_NONBLOCK: ::c_int = 0x00000080; +pub const O_APPEND: ::c_int = 0x00000800; +pub const O_SYNC: ::c_int = 0x00010000; +pub const O_RSYNC: ::c_int = 0x00020000; +pub const O_DSYNC: ::c_int = 0x00040000; +pub const O_NOFOLLOW: ::c_int = 0x00080000; +pub const O_NOCACHE: ::c_int = 0x00100000; +pub const O_DIRECTORY: ::c_int = 0x00200000; + +pub const S_IFIFO: ::mode_t = 61440; +pub const S_IFCHR: ::mode_t = 49152; +pub const S_IFBLK: ::mode_t = 24576; +pub const S_IFDIR: ::mode_t = 16384; +pub const S_IFREG: ::mode_t = 32768; +pub const S_IFLNK: ::mode_t = 40960; +pub const S_IFSOCK: ::mode_t = 49152; +pub const S_IFMT: ::mode_t = 61440; +pub const S_IRWXU: ::mode_t = 448; +pub const S_IXUSR: ::mode_t = 64; +pub const S_IWUSR: ::mode_t = 128; +pub const S_IRUSR: ::mode_t = 256; +pub const S_IRWXG: ::mode_t = 70; +pub const S_IXGRP: ::mode_t = 10; +pub const S_IWGRP: ::mode_t = 20; +pub const S_IRGRP: ::mode_t = 40; +pub const S_IRWXO: ::mode_t = 7; +pub const S_IXOTH: ::mode_t = 1; +pub const S_IWOTH: ::mode_t = 2; +pub const S_IROTH: ::mode_t = 4; +pub const F_OK: ::c_int = 0; +pub const R_OK: ::c_int = 4; +pub const W_OK: ::c_int = 2; +pub const X_OK: ::c_int = 1; +pub const STDIN_FILENO: ::c_int = 0; +pub const STDOUT_FILENO: ::c_int = 1; +pub const STDERR_FILENO: ::c_int = 2; + +pub const SIGHUP: ::c_int = 1; +pub const SIGINT: ::c_int = 2; +pub const SIGQUIT: ::c_int = 3; +pub const SIGILL: ::c_int = 4; +pub const SIGCHLD: ::c_int = 5; +pub const SIGABRT: ::c_int = 6; +pub const SIGPIPE: ::c_int = 7; +pub const SIGFPE: ::c_int = 8; +pub const SIGKILL: ::c_int = 9; +pub const SIGSTOP: ::c_int = 10; +pub const SIGSEGV: ::c_int = 11; +pub const SIGCONT: ::c_int = 12; +pub const SIGTSTP: ::c_int = 13; +pub const SIGALRM: ::c_int = 14; +pub const SIGTERM: ::c_int = 15; +pub const SIGTTIN: ::c_int = 16; +pub const SIGTTOU: ::c_int = 17; +pub const SIGUSR1: ::c_int = 18; +pub const SIGUSR2: ::c_int = 19; +pub const SIGWINCH: ::c_int = 20; +pub const SIGKILLTHR: ::c_int = 21; +pub const SIGTRAP: ::c_int = 22; +pub const SIGPOLL: ::c_int = 23; +pub const SIGPROF: ::c_int = 24; +pub const SIGSYS: ::c_int = 25; +pub const SIGURG: ::c_int = 26; +pub const SIGVTALRM: ::c_int = 27; +pub const SIGXCPU: ::c_int = 28; +pub const SIGXFSZ: ::c_int = 29; +pub const SIGBUS: ::c_int = 30; + +pub const SIG_BLOCK: ::c_int = 1; +pub const SIG_UNBLOCK: ::c_int = 2; +pub const SIG_SETMASK: ::c_int = 3; + +pub const SIGEV_NONE: ::c_int = 0; +pub const SIGEV_SIGNAL: ::c_int = 1; +pub const SIGEV_THREAD: ::c_int = 2; + +pub const EAI_AGAIN: ::c_int = 2; +pub const EAI_BADFLAGS: ::c_int = 3; +pub const EAI_FAIL: ::c_int = 4; +pub const EAI_FAMILY: ::c_int = 5; +pub const EAI_MEMORY: ::c_int = 6; +pub const EAI_NODATA: ::c_int = 7; +pub const EAI_NONAME: ::c_int = 8; +pub const EAI_SERVICE: ::c_int = 9; +pub const EAI_SOCKTYPE: ::c_int = 10; +pub const EAI_SYSTEM: ::c_int = 11; +pub const EAI_OVERFLOW: ::c_int = 14; + +pub const PROT_NONE: ::c_int = 0; +pub const PROT_READ: ::c_int = 1; +pub const PROT_WRITE: ::c_int = 2; +pub const PROT_EXEC: ::c_int = 4; + +pub const LC_ALL: ::c_int = 0; +pub const LC_COLLATE: ::c_int = 1; +pub const LC_CTYPE: ::c_int = 2; +pub const LC_MONETARY: ::c_int = 3; +pub const LC_NUMERIC: ::c_int = 4; +pub const LC_TIME: ::c_int = 5; +pub const LC_MESSAGES: ::c_int = 6; + +// TODO: Haiku does not have MAP_FILE, but libstd/os.rs requires it +pub const MAP_FILE: ::c_int = 0x00; +pub const MAP_SHARED: ::c_int = 0x01; +pub const MAP_PRIVATE: ::c_int = 0x02; +pub const MAP_FIXED: ::c_int = 0x04; +pub const MAP_ANONYMOUS: ::c_int = 0x08; +pub const MAP_ANON: ::c_int = MAP_ANONYMOUS; + +pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; + +pub const MS_ASYNC: ::c_int = 0x01; +pub const MS_INVALIDATE: ::c_int = 0x04; +pub const MS_SYNC: ::c_int = 0x02; + +pub const E2BIG : ::c_int = -2147454975; +pub const ECHILD : ::c_int = -2147454974; +pub const EDEADLK : ::c_int = -2147454973; +pub const EFBIG : ::c_int = -2147454972; +pub const EMLINK : ::c_int = -2147454971; +pub const ENFILE : ::c_int = -2147454970; +pub const ENODEV : ::c_int = -2147454969; +pub const ENOLCK : ::c_int = -2147454968; +pub const ENOSYS : ::c_int = -2147454967; +pub const ENOTTY : ::c_int = -2147454966; +pub const ENXIO : ::c_int = -2147454965; +pub const ESPIPE : ::c_int = -2147454964; +pub const ESRCH : ::c_int = -2147454963; +pub const EFPOS : ::c_int = -2147457962; +pub const ESIGPARM : ::c_int = -2147457961; +pub const EDOM : ::c_int = -2147454960; +pub const ERANGE : ::c_int = -2147454959; +pub const EPROTOTYPE : ::c_int = -2147454958; +pub const EPROTONOSUPPORT : ::c_int = -2147454957; +pub const EPFNOSUPPORT : ::c_int = -2147454956; +pub const EAFNOSUPPORT : ::c_int = -2147454955; +pub const EADDRINUSE : ::c_int = -2147454954; +pub const EADDRNOTAVAIL : ::c_int = -2147454953; +pub const ENETDOWN : ::c_int = -2147454952; +pub const ENETUNREACH : ::c_int = -2147454951; +pub const ENETRESET : ::c_int = -2147454950; +pub const ECONNABORTED : ::c_int = -2147454949; +pub const ECONNRESET : ::c_int = -2147454948; +pub const EISCONN : ::c_int = -2147454947; +pub const ENOTCONN : ::c_int = -2147454946; +pub const ESHUTDOWN : ::c_int = -2147454945; +pub const ECONNREFUSED : ::c_int = -2147454944; +pub const EHOSTUNREACH : ::c_int = -2147454943; +pub const ENOPROTOOPT : ::c_int = -2147454942; +pub const ENOBUFS : ::c_int = -2147454941; +pub const EINPROGRESS : ::c_int = -2147454940; +pub const EALREADY : ::c_int = -2147454939; +pub const EILSEQ : ::c_int = -2147454938; +pub const ENOMSG : ::c_int = -2147454937; +pub const ESTALE : ::c_int = -2147454936; +pub const EOVERFLOW : ::c_int = -2147454935; +pub const EMSGSIZE : ::c_int = -2147454934; +pub const EOPNOTSUPP : ::c_int = -2147454933; +pub const ENOTSOCK : ::c_int = -2147454932; +pub const EHOSTDOWN : ::c_int = -2147454931; +pub const EBADMSG : ::c_int = -2147454930; +pub const ECANCELED : ::c_int = -2147454929; +pub const EDESTADDRREQ : ::c_int = -2147454928; +pub const EDQUOT : ::c_int = -2147454927; +pub const EIDRM : ::c_int = -2147454926; +pub const EMULTIHOP : ::c_int = -2147454925; +pub const ENODATA : ::c_int = -2147454924; +pub const ENOLINK : ::c_int = -2147454923; +pub const ENOSR : ::c_int = -2147454922; +pub const ENOSTR : ::c_int = -2147454921; +pub const ENOTSUP : ::c_int = -2147454920; +pub const EPROTO : ::c_int = -2147454919; +pub const ETIME : ::c_int = -2147454918; +pub const ETXTBSY : ::c_int = -2147454917; +pub const ENOATTR : ::c_int = -2147454916; + +// INT_MIN +pub const ENOMEM : ::c_int = -2147454976; + +// POSIX errors that can be mapped to BeOS error codes +pub const EACCES : ::c_int = -2147483646; +pub const EINTR : ::c_int = -2147483638; +pub const EIO : ::c_int = -2147483647; +pub const EBUSY : ::c_int = -2147483634; +pub const EFAULT : ::c_int = -2147478783; +pub const ETIMEDOUT : ::c_int = -2147483639; +pub const EAGAIN : ::c_int = -2147483637; +pub const EWOULDBLOCK : ::c_int = -2147483637; +pub const EBADF : ::c_int = -2147459072; +pub const EEXIST : ::c_int = -2147459070; +pub const EINVAL : ::c_int = -2147483643; +pub const ENAMETOOLONG : ::c_int = -2147459068; +pub const ENOENT : ::c_int = -2147459069; +pub const EPERM : ::c_int = -2147483633; +pub const ENOTDIR : ::c_int = -2147459067; +pub const EISDIR : ::c_int = -2147459063; +pub const ENOTEMPTY : ::c_int = -2147459066; +pub const ENOSPC : ::c_int = -2147459065; +pub const EROFS : ::c_int = -2147459064; +pub const EMFILE : ::c_int = -2147459062; +pub const EXDEV : ::c_int = -2147459061; +pub const ELOOP : ::c_int = -2147459060; +pub const ENOEXEC : ::c_int = -2147478782; +pub const EPIPE : ::c_int = -2147459059; + +pub const IPPROTO_RAW: ::c_int = 255; + +// These are prefixed with POSIX_ on Haiku +pub const MADV_NORMAL: ::c_int = 1; +pub const MADV_SEQUENTIAL: ::c_int = 2; +pub const MADV_RANDOM: ::c_int = 3; +pub const MADV_WILLNEED: ::c_int = 4; +pub const MADV_DONTNEED: ::c_int = 5; + +// https://github.com/haiku/haiku/blob/master/headers/posix/net/if.h#L80 +pub const IFF_UP: ::c_int = 0x0001; +pub const IFF_BROADCAST: ::c_int = 0x0002; // valid broadcast address +pub const IFF_LOOPBACK: ::c_int = 0x0008; +pub const IFF_POINTOPOINT: ::c_int = 0x0010; // point-to-point link +pub const IFF_NOARP: ::c_int = 0x0040; // no address resolution +pub const IFF_AUTOUP: ::c_int = 0x0080; // auto dial +pub const IFF_PROMISC: ::c_int = 0x0100; // receive all packets +pub const IFF_ALLMULTI: ::c_int = 0x0200; // receive all multicast packets +pub const IFF_SIMPLEX: ::c_int = 0x0800; // doesn't receive own transmissions +pub const IFF_LINK: ::c_int = 0x1000; // has link +pub const IFF_AUTO_CONFIGURED: ::c_int = 0x2000; +pub const IFF_CONFIGURING: ::c_int = 0x4000; +pub const IFF_MULTICAST: ::c_int = 0x8000; // supports multicast + +pub const AF_UNSEC: ::c_int = 0; +pub const AF_INET: ::c_int = 1; +pub const AF_APPLETALK: ::c_int = 2; +pub const AF_ROUTE: ::c_int = 3; +pub const AF_LINK: ::c_int = 4; +pub const AF_INET6: ::c_int = 5; +pub const AF_DLI: ::c_int = 6; +pub const AF_IPX: ::c_int = 7; +pub const AF_NOTIFY: ::c_int = 8; +pub const AF_LOCAL: ::c_int = 9; +pub const AF_UNIX: ::c_int = AF_LOCAL; +pub const AF_BLUETOOTH: ::c_int = 10; +pub const AF_MAX: ::c_int = 11; + +pub const IP_MULTICAST_TTL: ::c_int = 10; +pub const IP_MULTICAST_LOOP: ::c_int = 11; +pub const IP_TTL: ::c_int = 4; +pub const IP_HDRINCL: ::c_int = 2; +pub const IP_ADD_MEMBERSHIP: ::c_int = 12; +pub const IP_DROP_MEMBERSHIP: ::c_int = 13; + +pub const TCP_NODELAY: ::c_int = 0x01; +pub const TCP_MAXSEG: ::c_int = 0x02; +pub const TCP_NOPUSH: ::c_int = 0x04; +pub const TCP_NOOPT: ::c_int = 0x08; + +pub const IPV6_MULTICAST_LOOP: ::c_int = 26; +pub const IPV6_JOIN_GROUP: ::c_int = 28; +pub const IPV6_LEAVE_GROUP: ::c_int = 29; +pub const IPV6_V6ONLY: ::c_int = 30; + +pub const MSG_OOB: ::c_int = 0x0001; +pub const MSG_PEEK: ::c_int = 0x0002; +pub const MSG_DONTROUTE: ::c_int = 0x0004; +pub const MSG_EOR: ::c_int = 0x0008; +pub const MSG_TRUNC: ::c_int = 0x0010; +pub const MSG_CTRUNC: ::c_int = 0x0020; +pub const MSG_WAITALL: ::c_int = 0x0040; +pub const MSG_DONTWAIT: ::c_int = 0x0080; +pub const MSG_BCAST: ::c_int = 0x0100; +pub const MSG_MCAST: ::c_int = 0x0200; +pub const MSG_EOF: ::c_int = 0x0400; +pub const MSG_NOSIGNAL: ::c_int = 0x0800; + +pub const SHUT_RD: ::c_int = 0; +pub const SHUT_WR: ::c_int = 1; +pub const SHUT_RDWR: ::c_int = 2; + +pub const LOCK_SH: ::c_int = 0x01; +pub const LOCK_EX: ::c_int = 0x02; +pub const LOCK_NB: ::c_int = 0x04; +pub const LOCK_UN: ::c_int = 0x08; + +pub const SIGSTKSZ: ::size_t = 16384; + +pub const PATH_MAX: ::c_int = 1024; + +pub const SA_NOCLDSTOP: ::c_int = 0x01; +pub const SA_NOCLDWAIT: ::c_int = 0x02; +pub const SA_RESETHAND: ::c_int = 0x04; +pub const SA_NODEFER: ::c_int = 0x08; +pub const SA_RESTART: ::c_int = 0x10; +pub const SA_ONSTACK: ::c_int = 0x20; +pub const SA_SIGINFO: ::c_int = 0x40; +pub const SA_NOMASK: ::c_int = SA_NODEFER; +pub const SA_STACK: ::c_int = SA_ONSTACK; +pub const SA_ONESHOT: ::c_int = SA_RESETHAND; + +pub const FD_SETSIZE: usize = 1024; + +pub const RTLD_NOW: ::c_int = 0x1; +pub const RTLD_DEFAULT: *mut ::c_void = 0isize as *mut ::c_void; + +pub const BUFSIZ: ::c_uint = 8192; +pub const FILENAME_MAX: ::c_uint = 256; +pub const FOPEN_MAX: ::c_uint = 128; +pub const L_tmpnam: ::c_uint = 512; +pub const TMP_MAX: ::c_uint = 32768; + +pub const _PC_CHOWN_RESTRICTED: ::c_int = 1; +pub const _PC_MAX_CANON: ::c_int = 2; +pub const _PC_MAX_INPUT: ::c_int = 3; +pub const _PC_NAME_MAX: ::c_int = 4; +pub const _PC_NO_TRUNC: ::c_int = 5; +pub const _PC_PATH_MAX: ::c_int = 6; +pub const _PC_PIPE_BUF: ::c_int = 7; +pub const _PC_VDISABLE: ::c_int = 8; +pub const _PC_LINK_MAX: ::c_int = 25; +pub const _PC_SYNC_IO: ::c_int = 26; +pub const _PC_ASYNC_IO: ::c_int = 27; +pub const _PC_PRIO_IO: ::c_int = 28; +pub const _PC_SOCK_MAXBUF: ::c_int = 29; +pub const _PC_FILESIZEBITS: ::c_int = 30; +pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 31; +pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 32; +pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 33; +pub const _PC_REC_XFER_ALIGN: ::c_int = 34; +pub const _PC_ALLOC_SIZE_MIN: ::c_int = 35; +pub const _PC_SYMLINK_MAX: ::c_int = 36; +pub const _PC_2_SYMLINKS: ::c_int = 37; +pub const _PC_XATTR_EXISTS: ::c_int = 38; +pub const _PC_XATTR_ENABLED: ::c_int = 39; + +pub const FIONBIO: ::c_int = 0xbe000000; + +pub const _SC_ARG_MAX : ::c_int = 15; +pub const _SC_CHILD_MAX : ::c_int = 16; +pub const _SC_CLK_TCK : ::c_int = 17; +pub const _SC_JOB_CONTROL : ::c_int = 18; +pub const _SC_NGROUPS_MAX : ::c_int = 19; +pub const _SC_OPEN_MAX : ::c_int = 20; +pub const _SC_SAVED_IDS : ::c_int = 21; +pub const _SC_STREAM_MAX : ::c_int = 22; +pub const _SC_TZNAME_MAX : ::c_int = 23; +pub const _SC_VERSION : ::c_int = 24; +pub const _SC_GETGR_R_SIZE_MAX : ::c_int = 25; +pub const _SC_GETPW_R_SIZE_MAX : ::c_int = 26; +pub const _SC_PAGESIZE : ::c_int = 27; +pub const _SC_PAGE_SIZE : ::c_int = 27; +pub const _SC_SEM_NSEMS_MAX : ::c_int = 28; +pub const _SC_SEM_VALUE_MAX : ::c_int = 29; +pub const _SC_SEMAPHORES : ::c_int = 30; +pub const _SC_THREADS : ::c_int = 31; +pub const _SC_IOV_MAX : ::c_int = 32; +pub const _SC_UIO_MAXIOV : ::c_int = 32; +pub const _SC_NPROCESSORS_CONF : ::c_int = 34; +pub const _SC_NPROCESSORS_ONLN : ::c_int = 35; +pub const _SC_ATEXIT_MAX : ::c_int = 37; +pub const _SC_PASS_MAX : ::c_int = 39; +pub const _SC_PHYS_PAGES : ::c_int = 40; +pub const _SC_AVPHYS_PAGES : ::c_int = 41; +pub const _SC_PIPE : ::c_int = 42; +pub const _SC_SELECT : ::c_int = 43; +pub const _SC_POLL : ::c_int = 44; +pub const _SC_MAPPED_FILES : ::c_int = 45; +pub const _SC_THREAD_PROCESS_SHARED : ::c_int = 46; +pub const _SC_THREAD_STACK_MIN : ::c_int = 47; +pub const _SC_THREAD_ATTR_STACKADDR : ::c_int = 48; +pub const _SC_THREAD_ATTR_STACKSIZE : ::c_int = 49; +pub const _SC_THREAD_PRIORITY_SCHEDULING : ::c_int = 50; +pub const _SC_REALTIME_SIGNALS : ::c_int = 51; +pub const _SC_MEMORY_PROTECTION : ::c_int = 52; +pub const _SC_SIGQUEUE_MAX : ::c_int = 53; +pub const _SC_RTSIG_MAX : ::c_int = 54; +pub const _SC_MONOTONIC_CLOCK : ::c_int = 55; +pub const _SC_DELAYTIMER_MAX : ::c_int = 56; +pub const _SC_TIMER_MAX : ::c_int = 57; +pub const _SC_TIMERS : ::c_int = 58; +pub const _SC_CPUTIME : ::c_int = 59; +pub const _SC_THREAD_CPUTIME : ::c_int = 60; + +pub const PTHREAD_STACK_MIN: ::size_t = 8192; + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + flags: 0, + lock: 0, + unused: -42, + owner: -1, + owner_count: 0, +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + flags: 0, + unused: -42, + mutex: 0 as *mut _, + waiter_count: 0, + lock: 0, +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + flags: 0, + owner: -1, + lock_sem: 0, + lock_count: 0, + reader_count: 0, + writer_count: 0, + waiters: [0 as *mut _; 2], +}; + +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = 0; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 1; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 3; + +pub const FIOCLEX: c_ulong = 0; // TODO: does not exist on Haiku! + +pub const RUSAGE_CHILDREN: ::c_int = -1; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_RAW: ::c_int = 3; +pub const SOCK_SEQPACKET: ::c_int = 5; + +pub const SOL_SOCKET: ::c_int = -1; +pub const SO_ACCEPTCONN: ::c_int = 0x00000001; +pub const SO_BROADCAST: ::c_int = 0x00000002; +pub const SO_DEBUG: ::c_int = 0x00000004; +pub const SO_DONTROUTE: ::c_int = 0x00000008; +pub const SO_KEEPALIVE: ::c_int = 0x00000010; +pub const SO_OOBINLINE: ::c_int = 0x00000020; +pub const SO_REUSEADDR: ::c_int = 0x00000040; +pub const SO_REUSEPORT: ::c_int = 0x00000080; +pub const SO_USELOOPBACK: ::c_int = 0x00000100; +pub const SO_LINGER: ::c_int = 0x00000200; +pub const SO_SNDBUF: ::c_int = 0x40000001; +pub const SO_SNDLOWAT: ::c_int = 0x40000002; +pub const SO_SNDTIMEO: ::c_int = 0x40000003; +pub const SO_RCVBUF: ::c_int = 0x40000004; +pub const SO_RCVLOWAT: ::c_int = 0x40000005; +pub const SO_RCVTIMEO: ::c_int = 0x40000006; +pub const SO_ERROR: ::c_int = 0x40000007; +pub const SO_TYPE: ::c_int = 0x40000008; +pub const SO_NONBLOCK: ::c_int = 0x40000009; +pub const SO_BINDTODEVICE: ::c_int = 0x4000000a; +pub const SO_PEERCRED: ::c_int = 0x4000000b; + +pub const SCM_RIGHTS: ::c_int = 0x01; + +pub const NI_MAXHOST: ::size_t = 1025; + +pub const WNOHANG: ::c_int = 0x01; +pub const WUNTRACED: ::c_int = 0x02; +pub const WCONTINUED: ::c_int = 0x04; +pub const WEXITED: ::c_int = 0x08; +pub const WSTOPPED: ::c_int = 0x10; +pub const WNOWAIT: ::c_int = 0x20; + +pub const P_ALL: idtype_t = 0; +pub const P_PID: idtype_t = 1; +pub const P_PGID: idtype_t = 2; + +pub const VINTR: usize = 0; +pub const VQUIT: usize = 1; +pub const VERASE: usize = 2; +pub const VKILL: usize = 3; +pub const VEOF: usize = 4; +pub const VEOL: usize = 5; +pub const VMIN: usize = 4; +pub const VTIME: usize = 5; +pub const VEOL2: usize = 6; +pub const VSWTCH: usize = 7; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VSUSP: usize = 10; + +pub const IGNBRK: ::tcflag_t = 0x01; +pub const BRKINT: ::tcflag_t = 0x02; +pub const IGNPAR: ::tcflag_t = 0x04; +pub const PARMRK: ::tcflag_t = 0x08; +pub const INPCK: ::tcflag_t = 0x10; +pub const ISTRIP: ::tcflag_t = 0x20; +pub const INLCR: ::tcflag_t = 0x40; +pub const IGNCR: ::tcflag_t = 0x80; +pub const ICRNL: ::tcflag_t = 0x100; +pub const IUCLC: ::tcflag_t = 0x200; +pub const IXON: ::tcflag_t = 0x400; +pub const IXANY: ::tcflag_t = 0x800; +pub const IXOFF: ::tcflag_t = 0x1000; + +pub const OPOST: ::tcflag_t = 0x00000001; +pub const OLCUC: ::tcflag_t = 0x00000002; +pub const ONLCR: ::tcflag_t = 0x00000004; +pub const OCRNL: ::tcflag_t = 0x00000008; +pub const ONOCR: ::tcflag_t = 0x00000010; +pub const ONLRET: ::tcflag_t = 0x00000020; +pub const OFILL: ::tcflag_t = 0x00000040; +pub const OFDEL: ::tcflag_t = 0x00000080; +pub const NLDLY: ::tcflag_t = 0x00000100; +pub const NL0: ::tcflag_t = 0x00000000; +pub const NL1: ::tcflag_t = 0x00000100; +pub const CRDLY: ::tcflag_t = 0x00000600; +pub const CR0: ::tcflag_t = 0x00000000; +pub const CR1: ::tcflag_t = 0x00000200; +pub const CR2: ::tcflag_t = 0x00000400; +pub const CR3: ::tcflag_t = 0x00000600; +pub const TABDLY: ::tcflag_t = 0x00001800; +pub const TAB0: ::tcflag_t = 0x00000000; +pub const TAB1: ::tcflag_t = 0x00000800; +pub const TAB2: ::tcflag_t = 0x00001000; +pub const TAB3: ::tcflag_t = 0x00001800; +pub const BSDLY: ::tcflag_t = 0x00002000; +pub const BS0: ::tcflag_t = 0x00000000; +pub const BS1: ::tcflag_t = 0x00002000; +pub const VTDLY: ::tcflag_t = 0x00004000; +pub const VT0: ::tcflag_t = 0x00000000; +pub const VT1: ::tcflag_t = 0x00004000; +pub const FFDLY: ::tcflag_t = 0x00008000; +pub const FF0: ::tcflag_t = 0x00000000; +pub const FF1: ::tcflag_t = 0x00008000; + +pub const CSIZE: ::tcflag_t = 0x00000020; +pub const CS5: ::tcflag_t = 0x00000000; +pub const CS6: ::tcflag_t = 0x00000000; +pub const CS7: ::tcflag_t = 0x00000000; +pub const CS8: ::tcflag_t = 0x00000020; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const XLOBLK: ::tcflag_t = 0x00001000; +pub const CTSFLOW: ::tcflag_t = 0x00002000; +pub const RTSFLOW: ::tcflag_t = 0x00004000; +pub const CRTSCTS: ::tcflag_t = RTSFLOW | CTSFLOW; + +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const XCASE: ::tcflag_t = 0x00000004; +pub const ECHO: ::tcflag_t = 0x00000008; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const NOFLSH: ::tcflag_t = 0x00000080; +pub const TOSTOP: ::tcflag_t = 0x00000100; +pub const IEXTEN: ::tcflag_t = 0x00000200; +pub const ECHOCTL: ::tcflag_t = 0x00000400; +pub const ECHOPRT: ::tcflag_t = 0x00000800; +pub const ECHOKE: ::tcflag_t = 0x00001000; +pub const FLUSHO: ::tcflag_t = 0x00002000; +pub const PENDIN: ::tcflag_t = 0x00004000; + +pub const TCGB_CTS: ::c_int = 0x01; +pub const TCGB_DSR: ::c_int = 0x02; +pub const TCGB_RI: ::c_int = 0x04; +pub const TCGB_DCD: ::c_int = 0x08; +pub const TIOCM_CTS: ::c_int = TCGB_CTS; +pub const TIOCM_CD: ::c_int = TCGB_DCD; +pub const TIOCM_CAR: ::c_int = TIOCM_CD; +pub const TIOCM_RI: ::c_int = TCGB_RI; +pub const TIOCM_DSR: ::c_int = TCGB_DSR; +pub const TIOCM_DTR: ::c_int = 0x10; +pub const TIOCM_RTS: ::c_int = 0x20; + +pub const B0: speed_t = 0x00; +pub const B50: speed_t = 0x01; +pub const B75: speed_t = 0x02; +pub const B110: speed_t = 0x03; +pub const B134: speed_t = 0x04; +pub const B150: speed_t = 0x05; +pub const B200: speed_t = 0x06; +pub const B300: speed_t = 0x07; +pub const B600: speed_t = 0x08; +pub const B1200: speed_t = 0x09; +pub const B1800: speed_t = 0x0A; +pub const B2400: speed_t = 0x0B; +pub const B4800: speed_t = 0x0C; +pub const B9600: speed_t = 0x0D; +pub const B19200: speed_t = 0x0E; +pub const B38400: speed_t = 0x0F; +pub const B57600: speed_t = 0x10; +pub const B115200: speed_t = 0x11; +pub const B230400: speed_t = 0x12; +pub const B31250: speed_t = 0x13; + +pub const TCSANOW: ::c_int = 0x01; +pub const TCSADRAIN: ::c_int = 0x02; +pub const TCSAFLUSH: ::c_int = 0x04; + +pub const TCOOFF: ::c_int = 0x01; +pub const TCOON: ::c_int = 0x02; +pub const TCIOFF: ::c_int = 0x04; +pub const TCION: ::c_int = 0x08; + +pub const TCIFLUSH: ::c_int = 0x01; +pub const TCOFLUSH: ::c_int = 0x02; +pub const TCIOFLUSH: ::c_int = 0x03; + +f! { + pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { + let fd = fd as usize; + let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; + (*set).fds_bits[fd / size] &= !(1 << (fd % size)); + return + } + + pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { + let fd = fd as usize; + let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; + return ((*set).fds_bits[fd / size] & (1 << (fd % size))) != 0 + } + + pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { + let fd = fd as usize; + let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; + (*set).fds_bits[fd / size] |= 1 << (fd % size); + return + } + + pub fn FD_ZERO(set: *mut fd_set) -> () { + for slot in (*set).fds_bits.iter_mut() { + *slot = 0; + } + } + + pub fn WIFEXITED(status: ::c_int) -> bool { + (status & !0xff) == 0 + } + + pub fn WEXITSTATUS(status: ::c_int) -> ::c_int { + (status & 0xff) + } + + pub fn WIFSIGNALED(status: ::c_int) -> bool { + ((status >> 8) & 0xff) != 0 + } + + pub fn WTERMSIG(status: ::c_int) -> ::c_int { + (status >> 8) & 0xff + } + + pub fn WIFSTOPPED(status: ::c_int) -> bool { + ((status >> 16) & 0xff) != 0 + } + + pub fn WSTOPSIG(status: ::c_int) -> ::c_int { + (status >> 16) & 0xff + } + + // actually WIFCORED, but this is used everywhere else + pub fn WCOREDUMP(status: ::c_int) -> bool { + (status & 0x10000) != 0 + } + + pub fn WIFCONTINUED(status: ::c_int) -> bool { + (status & 0x20000) != 0 + } +} + +#[link(name = "bsd")] +extern { + pub fn clock_gettime(clk_id: ::c_int, tp: *mut ::timespec) -> ::c_int; + pub fn clock_settime(clk_id: ::c_int, tp: *const ::timespec) -> ::c_int; + pub fn pthread_create(thread: *mut ::pthread_t, + attr: *const ::pthread_attr_t, + f: extern fn(*mut ::c_void) -> *mut ::c_void, + value: *mut ::c_void) -> ::c_int; + pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, + guardsize: *mut ::size_t) -> ::c_int; + pub fn pthread_attr_getstack(attr: *const ::pthread_attr_t, + stackaddr: *mut *mut ::c_void, + stacksize: *mut ::size_t) -> ::c_int; + pub fn pthread_condattr_getclock(attr: *const pthread_condattr_t, + clock_id: *mut clockid_t) -> ::c_int; + pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, + clock_id: ::clockid_t) -> ::c_int; + pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; + pub fn setgroups(ngroups: ::size_t, + ptr: *const ::gid_t) -> ::c_int; + pub fn ioctl(fd: ::c_int, request: ::c_int, ...) -> ::c_int; + pub fn mprotect(addr: *const ::c_void, len: ::size_t, prot: ::c_int) + -> ::c_int; + pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; + pub fn getnameinfo(sa: *const ::sockaddr, + salen: ::socklen_t, + host: *mut ::c_char, + hostlen: ::size_t, + serv: *mut ::c_char, + sevlen: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, + abstime: *const ::timespec) -> ::c_int; + pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, + options: ::c_int) -> ::c_int; + + pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; + pub fn glob(pattern: *const ::c_char, + flags: ::c_int, + errfunc: Option ::c_int>, + pglob: *mut ::glob_t) -> ::c_int; + pub fn globfree(pglob: *mut ::glob_t); + + pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + pub fn shm_open(name: *const ::c_char, oflag: ::c_int, mode: ::mode_t) + -> ::c_int; + pub fn shm_unlink(name: *const ::c_char) -> ::c_int; + + pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); + + pub fn telldir(dirp: *mut ::DIR) -> ::c_long; + pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; + + pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, + flags: ::c_int, addr: *mut ::sockaddr, + addrlen: *mut ::socklen_t) -> ::ssize_t; + pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; + pub fn futimes(fd: ::c_int, times: *const ::timeval) -> ::c_int; + pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; + pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; + + pub fn bind(socket: ::c_int, address: *const ::sockaddr, + address_len: ::socklen_t) -> ::c_int; + + pub fn writev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + pub fn readv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + + pub fn sendmsg(fd: ::c_int, + msg: *const ::msghdr, + flags: ::c_int) -> ::ssize_t; + pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) + -> ::ssize_t; + pub fn execvpe(file: *const ::c_char, argv: *const *const ::c_char, + environment: *const *const ::c_char) -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] + pub fn getgrgid_r(uid: ::uid_t, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "sigaltstack$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")] + pub fn sigaltstack(ss: *const stack_t, + oss: *mut stack_t) -> ::c_int; + pub fn sem_close(sem: *mut sem_t) -> ::c_int; + pub fn getdtablesize() -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] + pub fn getgrnam_r(name: *const ::c_char, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_sigmask$UNIX2003")] + pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, + oldset: *mut sigset_t) -> ::c_int; + pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; + pub fn getgrnam(name: *const ::c_char) -> *mut ::group; + pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; + pub fn sem_unlink(name: *const ::c_char) -> ::c_int; + pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] + pub fn getpwnam_r(name: *const ::c_char, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] + pub fn getpwuid_r(uid: ::uid_t, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch ="x86"), + link_name = "sigwait$UNIX2003")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] + pub fn sigwait(set: *const sigset_t, + sig: *mut ::c_int) -> ::c_int; + pub fn pthread_atfork(prepare: Option, + parent: Option, + child: Option) -> ::c_int; + pub fn getgrgid(gid: ::gid_t) -> *mut ::group; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "popen$UNIX2003")] + pub fn popen(command: *const c_char, + mode: *const c_char) -> *mut ::FILE; + pub fn openpty(amaster: *mut ::c_int, + aslave: *mut ::c_int, + name: *mut ::c_char, + termp: *mut termios, + winp: *mut ::winsize) -> ::c_int; + pub fn forkpty(amaster: *mut ::c_int, + name: *mut ::c_char, + termp: *mut termios, + winp: *mut ::winsize) -> ::pid_t; + pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; +} + +cfg_if! { + if #[cfg(target_pointer_width = "64")] { + mod b64; + pub use self::b64::*; + } else { + mod b32; + pub use self::b32::*; + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,959 @@ +//! Definitions found commonly among almost all Unix derivatives +//! +//! More functions and definitions can be found in the more specific modules +//! according to the platform in question. + +use dox::Option; + +pub type pid_t = i32; +pub type uid_t = u32; +pub type gid_t = u32; +pub type in_addr_t = u32; +pub type in_port_t = u16; +pub type sighandler_t = ::size_t; +pub type cc_t = ::c_uchar; + +pub enum DIR {} +pub enum locale_t {} + +s! { + pub struct group { + pub gr_name: *mut ::c_char, + pub gr_passwd: *mut ::c_char, + pub gr_gid: ::gid_t, + pub gr_mem: *mut *mut ::c_char, + } + + pub struct utimbuf { + pub actime: time_t, + pub modtime: time_t, + } + + pub struct timeval { + pub tv_sec: time_t, + pub tv_usec: suseconds_t, + } + + // linux x32 compatibility + // See https://sourceware.org/bugzilla/show_bug.cgi?id=16437 + pub struct timespec { + pub tv_sec: time_t, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + pub tv_nsec: i64, + #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] + pub tv_nsec: ::c_long, + } + + pub struct rlimit { + pub rlim_cur: rlim_t, + pub rlim_max: rlim_t, + } + + pub struct rusage { + pub ru_utime: timeval, + pub ru_stime: timeval, + pub ru_maxrss: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad1: u32, + pub ru_ixrss: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad2: u32, + pub ru_idrss: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad3: u32, + pub ru_isrss: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad4: u32, + pub ru_minflt: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad5: u32, + pub ru_majflt: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad6: u32, + pub ru_nswap: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad7: u32, + pub ru_inblock: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad8: u32, + pub ru_oublock: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad9: u32, + pub ru_msgsnd: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad10: u32, + pub ru_msgrcv: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad11: u32, + pub ru_nsignals: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad12: u32, + pub ru_nvcsw: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad13: u32, + pub ru_nivcsw: c_long, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + __pad14: u32, + + #[cfg(any(target_env = "musl", target_os = "emscripten"))] + __reserved: [c_long; 16], + } + + #[cfg_attr(target_os = "netbsd", repr(packed))] + pub struct in_addr { + pub s_addr: in_addr_t, + } + + pub struct in6_addr { + pub s6_addr: [u8; 16], + __align: [u32; 0], + } + + pub struct ip_mreq { + pub imr_multiaddr: in_addr, + pub imr_interface: in_addr, + } + + pub struct ipv6_mreq { + pub ipv6mr_multiaddr: in6_addr, + #[cfg(target_os = "android")] + pub ipv6mr_interface: ::c_int, + #[cfg(not(target_os = "android"))] + pub ipv6mr_interface: ::c_uint, + } + + pub struct hostent { + pub h_name: *mut ::c_char, + pub h_aliases: *mut *mut ::c_char, + pub h_addrtype: ::c_int, + pub h_length: ::c_int, + pub h_addr_list: *mut *mut ::c_char, + } + + pub struct iovec { + pub iov_base: *mut ::c_void, + pub iov_len: ::size_t, + } + + pub struct pollfd { + pub fd: ::c_int, + pub events: ::c_short, + pub revents: ::c_short, + } + + pub struct winsize { + pub ws_row: ::c_ushort, + pub ws_col: ::c_ushort, + pub ws_xpixel: ::c_ushort, + pub ws_ypixel: ::c_ushort, + } + + pub struct linger { + pub l_onoff: ::c_int, + pub l_linger: ::c_int, + } + + pub struct sigval { + // Actually a union of an int and a void* + pub sival_ptr: *mut ::c_void + } + + // + pub struct itimerval { + pub it_interval: ::timeval, + pub it_value: ::timeval, + } + + // + pub struct tms { + pub tms_utime: ::clock_t, + pub tms_stime: ::clock_t, + pub tms_cutime: ::clock_t, + pub tms_cstime: ::clock_t, + } + + pub struct servent { + pub s_name: *mut ::c_char, + pub s_aliases: *mut *mut ::c_char, + pub s_port: ::c_int, + pub s_proto: *mut ::c_char, + } + + pub struct protoent { + pub p_name: *mut ::c_char, + pub p_aliases: *mut *mut ::c_char, + pub p_proto: ::c_int, + } +} + +pub const SIG_DFL: sighandler_t = 0 as sighandler_t; +pub const SIG_IGN: sighandler_t = 1 as sighandler_t; +pub const SIG_ERR: sighandler_t = !0 as sighandler_t; + +pub const DT_UNKNOWN: u8 = 0; +pub const DT_FIFO: u8 = 1; +pub const DT_CHR: u8 = 2; +pub const DT_DIR: u8 = 4; +pub const DT_BLK: u8 = 6; +pub const DT_REG: u8 = 8; +pub const DT_LNK: u8 = 10; +pub const DT_SOCK: u8 = 12; + +pub const FD_CLOEXEC: ::c_int = 0x1; + +pub const USRQUOTA: ::c_int = 0; +pub const GRPQUOTA: ::c_int = 1; + +pub const SIGIOT: ::c_int = 6; + +pub const S_ISUID: ::c_int = 0x800; +pub const S_ISGID: ::c_int = 0x400; +pub const S_ISVTX: ::c_int = 0x200; + +pub const IF_NAMESIZE: ::size_t = 16; +pub const IFNAMSIZ: ::size_t = IF_NAMESIZE; + +pub const LOG_EMERG: ::c_int = 0; +pub const LOG_ALERT: ::c_int = 1; +pub const LOG_CRIT: ::c_int = 2; +pub const LOG_ERR: ::c_int = 3; +pub const LOG_WARNING: ::c_int = 4; +pub const LOG_NOTICE: ::c_int = 5; +pub const LOG_INFO: ::c_int = 6; +pub const LOG_DEBUG: ::c_int = 7; + +pub const LOG_KERN: ::c_int = 0; +pub const LOG_USER: ::c_int = 1 << 3; +pub const LOG_MAIL: ::c_int = 2 << 3; +pub const LOG_DAEMON: ::c_int = 3 << 3; +pub const LOG_AUTH: ::c_int = 4 << 3; +pub const LOG_SYSLOG: ::c_int = 5 << 3; +pub const LOG_LPR: ::c_int = 6 << 3; +pub const LOG_NEWS: ::c_int = 7 << 3; +pub const LOG_UUCP: ::c_int = 8 << 3; +pub const LOG_LOCAL0: ::c_int = 16 << 3; +pub const LOG_LOCAL1: ::c_int = 17 << 3; +pub const LOG_LOCAL2: ::c_int = 18 << 3; +pub const LOG_LOCAL3: ::c_int = 19 << 3; +pub const LOG_LOCAL4: ::c_int = 20 << 3; +pub const LOG_LOCAL5: ::c_int = 21 << 3; +pub const LOG_LOCAL6: ::c_int = 22 << 3; +pub const LOG_LOCAL7: ::c_int = 23 << 3; + +pub const LOG_PID: ::c_int = 0x01; +pub const LOG_CONS: ::c_int = 0x02; +pub const LOG_ODELAY: ::c_int = 0x04; +pub const LOG_NDELAY: ::c_int = 0x08; +pub const LOG_NOWAIT: ::c_int = 0x10; + +pub const LOG_PRIMASK: ::c_int = 7; +pub const LOG_FACMASK: ::c_int = 0x3f8; + +pub const PRIO_PROCESS: ::c_int = 0; +pub const PRIO_PGRP: ::c_int = 1; +pub const PRIO_USER: ::c_int = 2; + +pub const PRIO_MIN: ::c_int = -20; +pub const PRIO_MAX: ::c_int = 20; + +pub const IPPROTO_ICMP: ::c_int = 1; +pub const IPPROTO_ICMPV6: ::c_int = 58; +pub const IPPROTO_TCP: ::c_int = 6; +pub const IPPROTO_UDP: ::c_int = 17; +pub const IPPROTO_IP: ::c_int = 0; +pub const IPPROTO_IPV6: ::c_int = 41; + +pub const INADDR_LOOPBACK: in_addr_t = 2130706433; +pub const INADDR_ANY: in_addr_t = 0; +pub const INADDR_BROADCAST: in_addr_t = 4294967295; +pub const INADDR_NONE: in_addr_t = 4294967295; + +cfg_if! { + if #[cfg(cross_platform_docs)] { + // on dox builds don't pull in anything + } else if #[cfg(target_os = "l4re")] { + // required libraries for L4Re are linked externally, ATM + } else if #[cfg(feature = "use_std")] { + // cargo build, don't pull in anything extra as the libstd dep + // already pulls in all libs. + } else if #[cfg(target_env = "musl")] { + #[cfg_attr(feature = "stdbuild", + link(name = "c", kind = "static", + cfg(target_feature = "crt-static")))] + #[cfg_attr(feature = "stdbuild", + link(name = "c", cfg(not(target_feature = "crt-static"))))] + extern {} + } else if #[cfg(target_os = "emscripten")] { + #[link(name = "c")] + extern {} + } else if #[cfg(all(target_os = "netbsd"))] { + // Since we don't use -nodefaultlibs on Rumprun, libc is always pulled + // in automatically by the linker. We avoid passing it explicitly, as it + // causes some versions of binutils to crash with an assertion failure. + #[cfg_attr(feature = "stdbuild", target_vendor = "rumprun")] + #[link(name = "m")] + extern {} + } else if #[cfg(any(target_os = "macos", + target_os = "ios", + target_os = "android", + target_os = "openbsd", + target_os = "bitrig"))] { + #[link(name = "c")] + #[link(name = "m")] + extern {} + } else if #[cfg(target_os = "haiku")] { + #[link(name = "root")] + #[link(name = "network")] + extern {} + } else if #[cfg(target_os = "fuchsia")] { + #[link(name = "c")] + #[link(name = "fdio")] + extern {} + } else if #[cfg(target_env = "newlib")] { + #[link(name = "c")] + #[link(name = "m")] + extern {} + } else { + #[link(name = "c")] + #[link(name = "m")] + #[link(name = "rt")] + #[link(name = "pthread")] + extern {} + } +} + +extern { + #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam50")] + pub fn getpwnam(name: *const ::c_char) -> *mut passwd; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid50")] + pub fn getpwuid(uid: ::uid_t) -> *mut passwd; + + pub fn fprintf(stream: *mut ::FILE, + format: *const ::c_char, ...) -> ::c_int; + pub fn printf(format: *const ::c_char, ...) -> ::c_int; + pub fn snprintf(s: *mut ::c_char, n: ::size_t, + format: *const ::c_char, ...) -> ::c_int; + pub fn sprintf(s: *mut ::c_char, format: *const ::c_char, ...) -> ::c_int; + pub fn fscanf(stream: *mut ::FILE, format: *const ::c_char, ...) -> ::c_int; + pub fn scanf(format: *const ::c_char, ...) -> ::c_int; + pub fn sscanf(s: *const ::c_char, format: *const ::c_char, ...) -> ::c_int; + pub fn getchar_unlocked() -> ::c_int; + pub fn putchar_unlocked(c: ::c_int) -> ::c_int; + + #[cfg_attr(target_os = "netbsd", link_name = "__socket30")] + pub fn socket(domain: ::c_int, ty: ::c_int, protocol: ::c_int) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "connect$UNIX2003")] + pub fn connect(socket: ::c_int, address: *const sockaddr, + len: socklen_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "listen$UNIX2003")] + pub fn listen(socket: ::c_int, backlog: ::c_int) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "accept$UNIX2003")] + pub fn accept(socket: ::c_int, address: *mut sockaddr, + address_len: *mut socklen_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "getpeername$UNIX2003")] + pub fn getpeername(socket: ::c_int, address: *mut sockaddr, + address_len: *mut socklen_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "getsockname$UNIX2003")] + pub fn getsockname(socket: ::c_int, address: *mut sockaddr, + address_len: *mut socklen_t) -> ::c_int; + pub fn setsockopt(socket: ::c_int, level: ::c_int, name: ::c_int, + value: *const ::c_void, + option_len: socklen_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "socketpair$UNIX2003")] + pub fn socketpair(domain: ::c_int, type_: ::c_int, protocol: ::c_int, + socket_vector: *mut ::c_int) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "sendto$UNIX2003")] + pub fn sendto(socket: ::c_int, buf: *const ::c_void, len: ::size_t, + flags: ::c_int, addr: *const sockaddr, + addrlen: socklen_t) -> ::ssize_t; + pub fn shutdown(socket: ::c_int, how: ::c_int) -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "chmod$UNIX2003")] + pub fn chmod(path: *const c_char, mode: mode_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "fchmod$UNIX2003")] + pub fn fchmod(fd: ::c_int, mode: mode_t) -> ::c_int; + + #[cfg_attr(target_os = "macos", link_name = "fstat$INODE64")] + #[cfg_attr(target_os = "netbsd", link_name = "__fstat50")] + #[cfg_attr(target_os = "freebsd", link_name = "fstat@FBSD_1.0")] + pub fn fstat(fildes: ::c_int, buf: *mut stat) -> ::c_int; + + pub fn mkdir(path: *const c_char, mode: mode_t) -> ::c_int; + + #[cfg_attr(target_os = "macos", link_name = "stat$INODE64")] + #[cfg_attr(target_os = "netbsd", link_name = "__stat50")] + #[cfg_attr(target_os = "freebsd", link_name = "stat@FBSD_1.0")] + pub fn stat(path: *const c_char, buf: *mut stat) -> ::c_int; + + pub fn pclose(stream: *mut ::FILE) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "fdopen$UNIX2003")] + pub fn fdopen(fd: ::c_int, mode: *const c_char) -> *mut ::FILE; + pub fn fileno(stream: *mut ::FILE) -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "open$UNIX2003")] + pub fn open(path: *const c_char, oflag: ::c_int, ...) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "creat$UNIX2003")] + pub fn creat(path: *const c_char, mode: mode_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "fcntl$UNIX2003")] + pub fn fcntl(fd: ::c_int, cmd: ::c_int, ...) -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), + link_name = "opendir$INODE64")] + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "opendir$INODE64$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__opendir30")] + pub fn opendir(dirname: *const c_char) -> *mut ::DIR; + #[cfg_attr(target_os = "macos", link_name = "readdir$INODE64")] + #[cfg_attr(target_os = "netbsd", link_name = "__readdir30")] + #[cfg_attr(target_os = "freebsd", link_name = "readdir@FBSD_1.0")] + pub fn readdir(dirp: *mut ::DIR) -> *mut ::dirent; + #[cfg_attr(target_os = "macos", link_name = "readdir_r$INODE64")] + #[cfg_attr(target_os = "netbsd", link_name = "__readdir_r30")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_readdir_r")] + #[cfg_attr(target_os = "freebsd", link_name = "readdir_r@FBSD_1.0")] + pub fn readdir_r(dirp: *mut ::DIR, entry: *mut ::dirent, + result: *mut *mut ::dirent) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "closedir$UNIX2003")] + pub fn closedir(dirp: *mut ::DIR) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), + link_name = "rewinddir$INODE64")] + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "rewinddir$INODE64$UNIX2003")] + pub fn rewinddir(dirp: *mut ::DIR); + + pub fn openat(dirfd: ::c_int, pathname: *const ::c_char, + flags: ::c_int, ...) -> ::c_int; + pub fn fchmodat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t, flags: ::c_int) -> ::c_int; + pub fn fchown(fd: ::c_int, + owner: ::uid_t, + group: ::gid_t) -> ::c_int; + pub fn fchownat(dirfd: ::c_int, pathname: *const ::c_char, + owner: ::uid_t, group: ::gid_t, + flags: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "macos", link_name = "fstatat$INODE64")] + #[cfg_attr(target_os = "freebsd", link_name = "fstatat@FBSD_1.1")] + pub fn fstatat(dirfd: ::c_int, pathname: *const ::c_char, + buf: *mut stat, flags: ::c_int) -> ::c_int; + pub fn linkat(olddirfd: ::c_int, oldpath: *const ::c_char, + newdirfd: ::c_int, newpath: *const ::c_char, + flags: ::c_int) -> ::c_int; + pub fn mkdirat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t) -> ::c_int; + pub fn readlinkat(dirfd: ::c_int, pathname: *const ::c_char, + buf: *mut ::c_char, bufsiz: ::size_t) -> ::ssize_t; + pub fn renameat(olddirfd: ::c_int, oldpath: *const ::c_char, + newdirfd: ::c_int, newpath: *const ::c_char) + -> ::c_int; + pub fn symlinkat(target: *const ::c_char, newdirfd: ::c_int, + linkpath: *const ::c_char) -> ::c_int; + pub fn unlinkat(dirfd: ::c_int, pathname: *const ::c_char, + flags: ::c_int) -> ::c_int; + + pub fn access(path: *const c_char, amode: ::c_int) -> ::c_int; + pub fn alarm(seconds: ::c_uint) -> ::c_uint; + pub fn chdir(dir: *const c_char) -> ::c_int; + pub fn fchdir(dirfd: ::c_int) -> ::c_int; + pub fn chown(path: *const c_char, uid: uid_t, + gid: gid_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "lchown$UNIX2003")] + pub fn lchown(path: *const c_char, uid: uid_t, + gid: gid_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "close$NOCANCEL$UNIX2003")] + #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), + link_name = "close$NOCANCEL")] + pub fn close(fd: ::c_int) -> ::c_int; + pub fn dup(fd: ::c_int) -> ::c_int; + pub fn dup2(src: ::c_int, dst: ::c_int) -> ::c_int; + pub fn execl(path: *const c_char, + arg0: *const c_char, ...) -> ::c_int; + pub fn execle(path: *const ::c_char, + arg0: *const ::c_char, ...) -> ::c_int; + pub fn execlp(file: *const ::c_char, + arg0: *const ::c_char, ...) -> ::c_int; + pub fn execv(prog: *const c_char, + argv: *const *const c_char) -> ::c_int; + pub fn execve(prog: *const c_char, argv: *const *const c_char, + envp: *const *const c_char) + -> ::c_int; + pub fn execvp(c: *const c_char, + argv: *const *const c_char) -> ::c_int; + pub fn fork() -> pid_t; + pub fn fpathconf(filedes: ::c_int, name: ::c_int) -> c_long; + pub fn getcwd(buf: *mut c_char, size: ::size_t) -> *mut c_char; + pub fn getegid() -> gid_t; + pub fn geteuid() -> uid_t; + pub fn getgid() -> gid_t; + pub fn getgroups(ngroups_max: ::c_int, groups: *mut gid_t) + -> ::c_int; + pub fn getlogin() -> *mut c_char; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "getopt$UNIX2003")] + pub fn getopt(argc: ::c_int, argv: *const *mut c_char, + optstr: *const c_char) -> ::c_int; + pub fn getpgid(pid: pid_t) -> pid_t; + pub fn getpgrp() -> pid_t; + pub fn getpid() -> pid_t; + pub fn getppid() -> pid_t; + pub fn getuid() -> uid_t; + pub fn isatty(fd: ::c_int) -> ::c_int; + pub fn link(src: *const c_char, dst: *const c_char) -> ::c_int; + pub fn lseek(fd: ::c_int, offset: off_t, whence: ::c_int) -> off_t; + pub fn pathconf(path: *const c_char, name: ::c_int) -> c_long; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pause$UNIX2003")] + pub fn pause() -> ::c_int; + pub fn pipe(fds: *mut ::c_int) -> ::c_int; + pub fn posix_memalign(memptr: *mut *mut ::c_void, + align: ::size_t, + size: ::size_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "read$UNIX2003")] + pub fn read(fd: ::c_int, buf: *mut ::c_void, count: ::size_t) + -> ::ssize_t; + pub fn rmdir(path: *const c_char) -> ::c_int; + pub fn seteuid(uid: uid_t) -> ::c_int; + pub fn setgid(gid: gid_t) -> ::c_int; + pub fn setpgid(pid: pid_t, pgid: pid_t) -> ::c_int; + pub fn setsid() -> pid_t; + pub fn setuid(uid: uid_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "sleep$UNIX2003")] + pub fn sleep(secs: ::c_uint) -> ::c_uint; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "nanosleep$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__nanosleep50")] + pub fn nanosleep(rqtp: *const timespec, + rmtp: *mut timespec) -> ::c_int; + pub fn tcgetpgrp(fd: ::c_int) -> pid_t; + pub fn tcsetpgrp(fd: ::c_int, pgrp: ::pid_t) -> ::c_int; + pub fn ttyname(fd: ::c_int) -> *mut c_char; + pub fn unlink(c: *const c_char) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "wait$UNIX2003")] + pub fn wait(status: *mut ::c_int) -> pid_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "waitpid$UNIX2003")] + pub fn waitpid(pid: pid_t, status: *mut ::c_int, options: ::c_int) + -> pid_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "write$UNIX2003")] + pub fn write(fd: ::c_int, buf: *const ::c_void, count: ::size_t) + -> ::ssize_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pread$UNIX2003")] + pub fn pread(fd: ::c_int, buf: *mut ::c_void, count: ::size_t, + offset: off_t) -> ::ssize_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pwrite$UNIX2003")] + pub fn pwrite(fd: ::c_int, buf: *const ::c_void, count: ::size_t, + offset: off_t) -> ::ssize_t; + pub fn umask(mask: mode_t) -> mode_t; + + #[cfg_attr(target_os = "netbsd", link_name = "__utime50")] + pub fn utime(file: *const c_char, buf: *const utimbuf) -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "kill$UNIX2003")] + pub fn kill(pid: pid_t, sig: ::c_int) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "killpg$UNIX2003")] + pub fn killpg(pgrp: pid_t, sig: ::c_int) -> ::c_int; + + pub fn mlock(addr: *const ::c_void, len: ::size_t) -> ::c_int; + pub fn munlock(addr: *const ::c_void, len: ::size_t) -> ::c_int; + pub fn mlockall(flags: ::c_int) -> ::c_int; + pub fn munlockall() -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "mmap$UNIX2003")] + pub fn mmap(addr: *mut ::c_void, + len: ::size_t, + prot: ::c_int, + flags: ::c_int, + fd: ::c_int, + offset: off_t) + -> *mut ::c_void; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "munmap$UNIX2003")] + pub fn munmap(addr: *mut ::c_void, len: ::size_t) -> ::c_int; + + pub fn if_nametoindex(ifname: *const c_char) -> ::c_uint; + pub fn if_indextoname(ifindex: ::c_uint, + ifname: *mut ::c_char) -> *mut ::c_char; + + #[cfg_attr(target_os = "macos", link_name = "lstat$INODE64")] + #[cfg_attr(target_os = "netbsd", link_name = "__lstat50")] + #[cfg_attr(target_os = "freebsd", link_name = "lstat@FBSD_1.0")] + pub fn lstat(path: *const c_char, buf: *mut stat) -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "fsync$UNIX2003")] + pub fn fsync(fd: ::c_int) -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "setenv$UNIX2003")] + pub fn setenv(name: *const c_char, val: *const c_char, + overwrite: ::c_int) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "unsetenv$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__unsetenv13")] + pub fn unsetenv(name: *const c_char) -> ::c_int; + + pub fn symlink(path1: *const c_char, + path2: *const c_char) -> ::c_int; + + pub fn ftruncate(fd: ::c_int, length: off_t) -> ::c_int; + + pub fn signal(signum: ::c_int, handler: sighandler_t) -> sighandler_t; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "getrlimit$UNIX2003")] + pub fn getrlimit(resource: ::c_int, rlim: *mut rlimit) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "setrlimit$UNIX2003")] + pub fn setrlimit(resource: ::c_int, rlim: *const rlimit) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getrusage50")] + pub fn getrusage(resource: ::c_int, usage: *mut rusage) -> ::c_int; + + #[cfg_attr(any(target_os = "macos", target_os = "ios"), + link_name = "realpath$DARWIN_EXTSN")] + pub fn realpath(pathname: *const ::c_char, resolved: *mut ::c_char) + -> *mut ::c_char; + + pub fn flock(fd: ::c_int, operation: ::c_int) -> ::c_int; + + #[cfg_attr(target_os = "netbsd", link_name = "__gettimeofday50")] + pub fn gettimeofday(tp: *mut ::timeval, + tz: *mut ::c_void) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__times13")] + pub fn times(buf: *mut ::tms) -> ::clock_t; + + pub fn pthread_self() -> ::pthread_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_join$UNIX2003")] + pub fn pthread_join(native: ::pthread_t, + value: *mut *mut ::c_void) -> ::c_int; + pub fn pthread_exit(value: *mut ::c_void); + pub fn pthread_attr_init(attr: *mut ::pthread_attr_t) -> ::c_int; + pub fn pthread_attr_destroy(attr: *mut ::pthread_attr_t) -> ::c_int; + pub fn pthread_attr_setstacksize(attr: *mut ::pthread_attr_t, + stack_size: ::size_t) -> ::c_int; + pub fn pthread_attr_setdetachstate(attr: *mut ::pthread_attr_t, + state: ::c_int) -> ::c_int; + pub fn pthread_detach(thread: ::pthread_t) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__libc_thr_yield")] + pub fn sched_yield() -> ::c_int; + pub fn pthread_key_create(key: *mut pthread_key_t, + dtor: Option) + -> ::c_int; + pub fn pthread_key_delete(key: pthread_key_t) -> ::c_int; + pub fn pthread_getspecific(key: pthread_key_t) -> *mut ::c_void; + pub fn pthread_setspecific(key: pthread_key_t, value: *const ::c_void) + -> ::c_int; + pub fn pthread_mutex_init(lock: *mut pthread_mutex_t, + attr: *const pthread_mutexattr_t) -> ::c_int; + pub fn pthread_mutex_destroy(lock: *mut pthread_mutex_t) -> ::c_int; + pub fn pthread_mutex_lock(lock: *mut pthread_mutex_t) -> ::c_int; + pub fn pthread_mutex_trylock(lock: *mut pthread_mutex_t) -> ::c_int; + pub fn pthread_mutex_unlock(lock: *mut pthread_mutex_t) -> ::c_int; + + pub fn pthread_mutexattr_init(attr: *mut pthread_mutexattr_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_mutexattr_destroy$UNIX2003")] + pub fn pthread_mutexattr_destroy(attr: *mut pthread_mutexattr_t) -> ::c_int; + pub fn pthread_mutexattr_settype(attr: *mut pthread_mutexattr_t, + _type: ::c_int) -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_cond_init$UNIX2003")] + pub fn pthread_cond_init(cond: *mut pthread_cond_t, + attr: *const pthread_condattr_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_cond_wait$UNIX2003")] + pub fn pthread_cond_wait(cond: *mut pthread_cond_t, + lock: *mut pthread_mutex_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_cond_timedwait$UNIX2003")] + pub fn pthread_cond_timedwait(cond: *mut pthread_cond_t, + lock: *mut pthread_mutex_t, + abstime: *const ::timespec) -> ::c_int; + pub fn pthread_cond_signal(cond: *mut pthread_cond_t) -> ::c_int; + pub fn pthread_cond_broadcast(cond: *mut pthread_cond_t) -> ::c_int; + pub fn pthread_cond_destroy(cond: *mut pthread_cond_t) -> ::c_int; + pub fn pthread_condattr_init(attr: *mut pthread_condattr_t) -> ::c_int; + pub fn pthread_condattr_destroy(attr: *mut pthread_condattr_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_rwlock_init$UNIX2003")] + pub fn pthread_rwlock_init(lock: *mut pthread_rwlock_t, + attr: *const pthread_rwlockattr_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_rwlock_destroy$UNIX2003")] + pub fn pthread_rwlock_destroy(lock: *mut pthread_rwlock_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_rwlock_rdlock$UNIX2003")] + pub fn pthread_rwlock_rdlock(lock: *mut pthread_rwlock_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_rwlock_tryrdlock$UNIX2003")] + pub fn pthread_rwlock_tryrdlock(lock: *mut pthread_rwlock_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_rwlock_wrlock$UNIX2003")] + pub fn pthread_rwlock_wrlock(lock: *mut pthread_rwlock_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_rwlock_trywrlock$UNIX2003")] + pub fn pthread_rwlock_trywrlock(lock: *mut pthread_rwlock_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_rwlock_unlock$UNIX2003")] + pub fn pthread_rwlock_unlock(lock: *mut pthread_rwlock_t) -> ::c_int; + pub fn pthread_rwlockattr_init(attr: *mut pthread_rwlockattr_t) -> ::c_int; + pub fn pthread_rwlockattr_destroy(attr: *mut pthread_rwlockattr_t) + -> ::c_int; + #[cfg_attr(all(target_os = "linux", not(target_env = "musl")), + link_name = "__xpg_strerror_r")] + pub fn strerror_r(errnum: ::c_int, buf: *mut c_char, + buflen: ::size_t) -> ::c_int; + + pub fn getsockopt(sockfd: ::c_int, + level: ::c_int, + optname: ::c_int, + optval: *mut ::c_void, + optlen: *mut ::socklen_t) -> ::c_int; + pub fn raise(signum: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__sigaction14")] + pub fn sigaction(signum: ::c_int, + act: *const sigaction, + oldact: *mut sigaction) -> ::c_int; + + #[cfg_attr(target_os = "netbsd", link_name = "__utimes50")] + pub fn utimes(filename: *const ::c_char, + times: *const ::timeval) -> ::c_int; + pub fn dlopen(filename: *const ::c_char, + flag: ::c_int) -> *mut ::c_void; + pub fn dlerror() -> *mut ::c_char; + pub fn dlsym(handle: *mut ::c_void, + symbol: *const ::c_char) -> *mut ::c_void; + pub fn dlclose(handle: *mut ::c_void) -> ::c_int; + pub fn dladdr(addr: *const ::c_void, info: *mut Dl_info) -> ::c_int; + + pub fn getaddrinfo(node: *const c_char, + service: *const c_char, + hints: *const addrinfo, + res: *mut *mut addrinfo) -> ::c_int; + pub fn freeaddrinfo(res: *mut addrinfo); + pub fn gai_strerror(errcode: ::c_int) -> *const ::c_char; + #[cfg_attr(any( + all(target_os = "linux", not(target_env = "musl")), + target_os = "freebsd", + target_os = "dragonfly", + target_os = "haiku"), + link_name = "__res_init")] + #[cfg_attr(any(target_os = "macos", target_os = "ios"), + link_name = "res_9_init")] + pub fn res_init() -> ::c_int; + + #[cfg_attr(target_os = "netbsd", link_name = "__gmtime_r50")] + pub fn gmtime_r(time_p: *const time_t, result: *mut tm) -> *mut tm; + #[cfg_attr(target_os = "netbsd", link_name = "__localtime_r50")] + pub fn localtime_r(time_p: *const time_t, result: *mut tm) -> *mut tm; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "mktime$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__mktime50")] + pub fn mktime(tm: *mut tm) -> time_t; + #[cfg_attr(target_os = "netbsd", link_name = "__time50")] + pub fn time(time: *mut time_t) -> time_t; + #[cfg_attr(target_os = "netbsd", link_name = "__gmtime50")] + pub fn gmtime(time_p: *const time_t) -> *mut tm; + #[cfg_attr(target_os = "netbsd", link_name = "__locatime50")] + pub fn localtime(time_p: *const time_t) -> *mut tm; + #[cfg_attr(target_os = "netbsd", link_name = "__difftime50")] + pub fn difftime(time1: time_t, time0: time_t) -> ::c_double; + + #[cfg_attr(target_os = "netbsd", link_name = "__mknod50")] + #[cfg_attr(target_os = "freebsd", link_name = "mknod@FBSD_1.0")] + pub fn mknod(pathname: *const ::c_char, mode: ::mode_t, + dev: ::dev_t) -> ::c_int; + pub fn uname(buf: *mut ::utsname) -> ::c_int; + pub fn gethostname(name: *mut ::c_char, len: ::size_t) -> ::c_int; + pub fn getservbyname(name: *const ::c_char, + proto: *const ::c_char) -> *mut servent; + pub fn getprotobyname(name: *const ::c_char) -> *mut protoent; + pub fn getprotobynumber(proto: ::c_int) -> *mut protoent; + pub fn chroot(name: *const ::c_char) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "usleep$UNIX2003")] + pub fn usleep(secs: ::c_uint) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "send$UNIX2003")] + pub fn send(socket: ::c_int, buf: *const ::c_void, len: ::size_t, + flags: ::c_int) -> ::ssize_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "recv$UNIX2003")] + pub fn recv(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, + flags: ::c_int) -> ::ssize_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "putenv$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__putenv50")] + pub fn putenv(string: *mut c_char) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "poll$UNIX2003")] + pub fn poll(fds: *mut pollfd, nfds: nfds_t, timeout: ::c_int) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), + link_name = "select$1050")] + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "select$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__select50")] + pub fn select(nfds: ::c_int, + readfs: *mut fd_set, + writefds: *mut fd_set, + errorfds: *mut fd_set, + timeout: *mut timeval) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__setlocale50")] + pub fn setlocale(category: ::c_int, + locale: *const ::c_char) -> *mut ::c_char; + pub fn localeconv() -> *mut lconv; + + pub fn sem_destroy(sem: *mut sem_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "sem_wait$UNIX2003")] + pub fn sem_wait(sem: *mut sem_t) -> ::c_int; + pub fn sem_trywait(sem: *mut sem_t) -> ::c_int; + pub fn sem_post(sem: *mut sem_t) -> ::c_int; + pub fn sem_init(sem: *mut sem_t, + pshared: ::c_int, + value: ::c_uint) + -> ::c_int; + pub fn statvfs(path: *const c_char, buf: *mut statvfs) -> ::c_int; + pub fn fstatvfs(fd: ::c_int, buf: *mut statvfs) -> ::c_int; + + pub fn readlink(path: *const c_char, + buf: *mut c_char, + bufsz: ::size_t) + -> ::ssize_t; + + #[cfg_attr(target_os = "netbsd", link_name = "__sigemptyset14")] + pub fn sigemptyset(set: *mut sigset_t) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__sigaddset14")] + pub fn sigaddset(set: *mut sigset_t, signum: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__sigfillset14")] + pub fn sigfillset(set: *mut sigset_t) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__sigdelset14")] + pub fn sigdelset(set: *mut sigset_t, signum: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__sigismember14")] + pub fn sigismember(set: *const sigset_t, signum: ::c_int) -> ::c_int; + + #[cfg_attr(target_os = "netbsd", link_name = "__sigprocmask14")] + pub fn sigprocmask(how: ::c_int, + set: *const sigset_t, + oldset: *mut sigset_t) + -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__sigpending14")] + pub fn sigpending(set: *mut sigset_t) -> ::c_int; + + #[cfg_attr(target_os = "netbsd", link_name = "__timegm50")] + pub fn timegm(tm: *mut ::tm) -> time_t; + + pub fn getsid(pid: pid_t) -> pid_t; + + pub fn sysconf(name: ::c_int) -> ::c_long; + + pub fn mkfifo(path: *const c_char, mode: mode_t) -> ::c_int; + + #[cfg_attr(all(target_os = "macos", target_arch = "x86_64"), + link_name = "pselect$1050")] + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pselect$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__pselect50")] + pub fn pselect(nfds: ::c_int, + readfs: *mut fd_set, + writefds: *mut fd_set, + errorfds: *mut fd_set, + timeout: *const timespec, + sigmask: *const sigset_t) -> ::c_int; + pub fn fseeko(stream: *mut ::FILE, + offset: ::off_t, + whence: ::c_int) -> ::c_int; + pub fn ftello(stream: *mut ::FILE) -> ::off_t; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "tcdrain$UNIX2003")] + pub fn tcdrain(fd: ::c_int) -> ::c_int; + pub fn cfgetispeed(termios: *const ::termios) -> ::speed_t; + pub fn cfgetospeed(termios: *const ::termios) -> ::speed_t; + pub fn cfmakeraw(termios: *mut ::termios); + pub fn cfsetispeed(termios: *mut ::termios, speed: ::speed_t) -> ::c_int; + pub fn cfsetospeed(termios: *mut ::termios, speed: ::speed_t) -> ::c_int; + pub fn cfsetspeed(termios: *mut ::termios, speed: ::speed_t) -> ::c_int; + pub fn tcgetattr(fd: ::c_int, termios: *mut ::termios) -> ::c_int; + pub fn tcsetattr(fd: ::c_int, + optional_actions: ::c_int, + termios: *const ::termios) -> ::c_int; + pub fn tcflow(fd: ::c_int, action: ::c_int) -> ::c_int; + pub fn tcflush(fd: ::c_int, action: ::c_int) -> ::c_int; + pub fn tcgetsid(fd: ::c_int) -> ::pid_t; + pub fn tcsendbreak(fd: ::c_int, duration: ::c_int) -> ::c_int; + pub fn mkstemp(template: *mut ::c_char) -> ::c_int; + pub fn mkdtemp(template: *mut ::c_char) -> *mut ::c_char; + + pub fn tmpnam(ptr: *mut ::c_char) -> *mut ::c_char; + + pub fn openlog(ident: *const ::c_char, logopt: ::c_int, facility: ::c_int); + pub fn closelog(); + pub fn setlogmask(maskpri: ::c_int) -> ::c_int; + pub fn syslog(priority: ::c_int, message: *const ::c_char, ...); + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "nice$UNIX2003")] + pub fn nice(incr: ::c_int) -> ::c_int; + + pub fn grantpt(fd: ::c_int) -> ::c_int; + pub fn posix_openpt(flags: ::c_int) -> ::c_int; + pub fn ptsname(fd: ::c_int) -> *mut ::c_char; + pub fn unlockpt(fd: ::c_int) -> ::c_int; +} + +cfg_if! { + if #[cfg(target_env = "uclibc")] { + mod uclibc; + pub use self::uclibc::*; + } else if #[cfg(target_env = "newlib")] { + mod newlib; + pub use self::newlib::*; + } else if #[cfg(any(target_os = "linux", + target_os = "android", + target_os = "emscripten", + target_os = "fuchsia"))] { + mod notbsd; + pub use self::notbsd::*; + } else if #[cfg(any(target_os = "macos", + target_os = "ios", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "openbsd", + target_os = "netbsd", + target_os = "bitrig"))] { + mod bsd; + pub use self::bsd::*; + } else if #[cfg(target_os = "solaris")] { + mod solaris; + pub use self::solaris::*; + } else if #[cfg(target_os = "haiku")] { + mod haiku; + pub use self::haiku::*; + } else { + // Unknown target_os + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/newlib/aarch64/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/newlib/aarch64/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/newlib/aarch64/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/newlib/aarch64/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,5 @@ +pub type c_char = u8; +pub type wchar_t = u32; + +pub type c_long = i64; +pub type c_ulong = u64; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/newlib/arm/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/newlib/arm/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/newlib/arm/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/newlib/arm/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,5 @@ +pub type c_char = u8; +pub type wchar_t = u32; + +pub type c_long = i32; +pub type c_ulong = u32; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/newlib/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/newlib/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/newlib/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/newlib/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,690 @@ +use dox::mem; + +pub type blkcnt_t = i32; +pub type blksize_t = i32; +pub type clock_t = i32; +pub type clockid_t = ::c_ulong; +pub type dev_t = u32; +pub type fsblkcnt_t = u64; +pub type fsfilcnt_t = u32; +pub type id_t = u32; +pub type ino_t = u32; +pub type key_t = ::c_int; +pub type loff_t = ::c_longlong; +pub type mode_t = ::c_uint; +pub type nfds_t = u32; +pub type nlink_t = ::c_ushort; +pub type off_t = i64; +pub type pthread_t = ::c_ulong; +pub type pthread_key_t = ::c_uint; +pub type rlim_t = u32; +pub type sa_family_t = u8; +pub type socklen_t = u32; +pub type speed_t = u32; +pub type suseconds_t = i32; +pub type tcflag_t = ::c_uint; +pub type time_t = i32; +pub type useconds_t = u32; + +s! { + pub struct sockaddr { + pub sa_family: sa_family_t, + pub sa_data: [::c_char; 14], + } + + pub struct sockaddr_in { + pub sin_family: sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + pub sin_zero: [u8; 8], + } + + pub struct sockaddr_in6 { // Unverified + pub sin6_family: sa_family_t, + pub sin6_port: ::in_port_t, + pub sin6_flowinfo: u32, + pub sin6_addr: ::in6_addr, + pub sin6_scope_id: u32, + } + + pub struct sockaddr_storage { + pub ss_family: sa_family_t, + pub __ss_padding: [u8; 26], + } + + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + pub ai_addrlen: socklen_t, + pub ai_canonname: *mut ::c_char, + pub ai_addr: *mut sockaddr, + pub ai_next: *mut addrinfo, + } + + pub struct ip_mreq { + pub imr_multiaddr: in_addr, + pub imr_interface: in_addr, + } + + pub struct linger { + pub l_onoff: ::c_int, + pub l_linger: ::c_int, + } + + pub struct in_addr { + pub s_addr: ::in_addr_t, + } + + pub struct hostent { + pub h_name: *mut ::c_char, + pub h_aliases: *mut *mut ::c_char, + pub h_addrtype: ::c_int, + pub h_length: ::c_int, + pub h_addr_list: *mut *mut ::c_char, + pub h_addr: *mut ::c_char, + } + + pub struct pollfd { + pub fd: ::c_int, + pub events: ::c_int, + pub revents: ::c_int, + } + + pub struct lconv { + pub decimal_point: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + pub grouping: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub currency_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub int_frac_digits: ::c_char, + pub frac_digits: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + pub n_sign_posn: ::c_char, + pub int_n_cs_precedes: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_n_sign_posn: ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + } + + pub struct tm { + pub tm_sec: ::c_int, + pub tm_min: ::c_int, + pub tm_hour: ::c_int, + pub tm_mday: ::c_int, + pub tm_mon: ::c_int, + pub tm_year: ::c_int, + pub tm_wday: ::c_int, + pub tm_yday: ::c_int, + pub tm_isdst: ::c_int, + } + + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: dev_t, + pub st_size: off_t, + pub st_atime: time_t, + pub st_spare1: ::c_long, + pub st_mtime: time_t, + pub st_spare2: ::c_long, + pub st_ctime: time_t, + pub st_spare3: ::c_long, + pub st_blksize: blksize_t, + pub st_blocks: blkcnt_t, + pub st_spare4: [::c_long; 2usize], + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: fsblkcnt_t, + pub f_bfree: fsblkcnt_t, + pub f_bavail: fsblkcnt_t, + pub f_files: fsfilcnt_t, + pub f_ffree: fsfilcnt_t, + pub f_favail: fsfilcnt_t, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + } + + pub struct sigset_t { + __val: [::c_ulong; 16], + } + + pub struct sigaction { + pub sa_handler: extern fn(arg1: ::c_int), + pub sa_mask: sigset_t, + pub sa_flags: ::c_int, + } + + pub struct dirent { + pub d_ino: ino_t, + pub d_type: ::c_uchar, + pub d_name: [::c_char; 256usize], + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_flags: ::c_int, + pub ss_size: usize, + } + + pub struct fd_set { // Unverified + fds_bits: [::c_ulong; FD_SETSIZE / ULONG_SIZE], + } + + pub struct passwd { // Unverified + pub pw_name: *mut ::c_char, + pub pw_passwd: *mut ::c_char, + pub pw_uid: ::uid_t, + pub pw_gid: ::gid_t, + pub pw_gecos: *mut ::c_char, + pub pw_dir: *mut ::c_char, + pub pw_shell: *mut ::c_char, + } + + pub struct termios { // Unverified + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; ::NCCS], + } + + pub struct sem_t { // Unverified + __size: [::c_char; 16], + } + + pub struct Dl_info { // Unverified + pub dli_fname: *const ::c_char, + pub dli_fbase: *mut ::c_void, + pub dli_sname: *const ::c_char, + pub dli_saddr: *mut ::c_void, + } + + pub struct utsname { // Unverified + pub sysname: [::c_char; 65], + pub nodename: [::c_char; 65], + pub release: [::c_char; 65], + pub version: [::c_char; 65], + pub machine: [::c_char; 65], + pub domainname: [::c_char; 65] + } + + pub struct cpu_set_t { // Unverified + bits: [u32; 32], + } + + pub struct pthread_attr_t { // Unverified + __size: [u64; 7] + } + + pub struct pthread_mutex_t { // Unverified + #[cfg(any(target_arch = "mips", target_arch = "arm", + target_arch = "powerpc"))] + __align: [::c_long; 0], + #[cfg(not(any(target_arch = "mips", target_arch = "arm", + target_arch = "powerpc")))] + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_MUTEX_T], + } + + pub struct pthread_rwlock_t { // Unverified + #[cfg(any(target_arch = "mips", target_arch = "arm", + target_arch = "powerpc"))] + __align: [::c_long; 0], + #[cfg(not(any(target_arch = "mips", target_arch = "arm", + target_arch = "powerpc")))] + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_RWLOCK_T], + } + + pub struct pthread_mutexattr_t { // Unverified + #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", + target_arch = "mips64", target_arch = "s390x", + target_arch = "sparc64"))] + __align: [::c_int; 0], + #[cfg(not(any(target_arch = "x86_64", target_arch = "powerpc64", + target_arch = "mips64", target_arch = "s390x", + target_arch = "sparc64")))] + __align: [::c_long; 0], + size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T], + } + + pub struct pthread_rwlockattr_t { // Unverified + __lockkind: ::c_int, + __pshared: ::c_int, + } + + pub struct pthread_cond_t { // Unverified + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_COND_T], + } + + pub struct pthread_condattr_t { // Unverified + __align: [::c_int; 0], + size: [u8; __SIZEOF_PTHREAD_CONDATTR_T], + } + +} + +// unverified constants +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_MUTEX_T], +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_COND_T], +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_RWLOCK_T], +}; +pub const NCCS: usize = 32; +pub const __SIZEOF_PTHREAD_ATTR_T: usize = 56; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_COND_T: usize = 48; +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; +pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; +pub const __SIZEOF_PTHREAD_BARRIER_T: usize = 32; +pub const __SIZEOF_PTHREAD_BARRIERATTR_T: usize = 4; +pub const __PTHREAD_MUTEX_HAVE_PREV: usize = 1; +pub const __PTHREAD_RWLOCK_INT_FLAGS_SHARED: usize = 1; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; +pub const FD_SETSIZE: usize = 1024; +// intentionally not public, only used for fd_set +const ULONG_SIZE: usize = 32; + +// Other constants +pub const EPERM: ::c_int = 1; +pub const ENOENT: ::c_int = 2; +pub const ESRCH: ::c_int = 3; +pub const EINTR: ::c_int = 4; +pub const EIO: ::c_int = 5; +pub const ENXIO: ::c_int = 6; +pub const E2BIG: ::c_int = 7; +pub const ENOEXEC: ::c_int = 8; +pub const EBADF: ::c_int = 9; +pub const ECHILD: ::c_int = 10; +pub const EAGAIN: ::c_int = 11; +pub const ENOMEM: ::c_int = 12; +pub const EACCES: ::c_int = 13; +pub const EFAULT: ::c_int = 14; +pub const EBUSY: ::c_int = 16; +pub const EEXIST: ::c_int = 17; +pub const EXDEV: ::c_int = 18; +pub const ENODEV: ::c_int = 19; +pub const ENOTDIR: ::c_int = 20; +pub const EISDIR: ::c_int = 21; +pub const EINVAL: ::c_int = 22; +pub const ENFILE: ::c_int = 23; +pub const EMFILE: ::c_int = 24; +pub const ENOTTY: ::c_int = 25; +pub const ETXTBSY: ::c_int = 26; +pub const EFBIG: ::c_int = 27; +pub const ENOSPC: ::c_int = 28; +pub const ESPIPE: ::c_int = 29; +pub const EROFS: ::c_int = 30; +pub const EMLINK: ::c_int = 31; +pub const EPIPE: ::c_int = 32; +pub const EDOM: ::c_int = 33; +pub const ERANGE: ::c_int = 34; +pub const ENOMSG: ::c_int = 35; +pub const EIDRM: ::c_int = 36; +pub const EDEADLK: ::c_int = 45; +pub const ENOLCK: ::c_int = 46; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENOLINK: ::c_int = 67; +pub const EPROTO: ::c_int = 71; +pub const EMULTIHOP: ::c_int = 74; +pub const EBADMSG: ::c_int = 77; +pub const EFTYPE: ::c_int = 79; +pub const ENOSYS: ::c_int = 88; +pub const ENOTEMPTY: ::c_int = 90; +pub const ENAMETOOLONG: ::c_int = 91; +pub const ELOOP: ::c_int = 92; +pub const EOPNOTSUPP: ::c_int = 95; +pub const EPFNOSUPPORT: ::c_int = 96; +pub const ECONNRESET: ::c_int = 104; +pub const ENOBUFS: ::c_int = 105; +pub const EAFNOSUPPORT: ::c_int = 106; +pub const EPROTOTYPE: ::c_int = 107; +pub const ENOTSOCK: ::c_int = 108; +pub const ENOPROTOOPT: ::c_int = 109; +pub const ECONNREFUSED: ::c_int = 111; +pub const EADDRINUSE: ::c_int = 112; +pub const ECONNABORTED: ::c_int = 113; +pub const ENETUNREACH: ::c_int = 114; +pub const ENETDOWN: ::c_int = 115; +pub const ETIMEDOUT: ::c_int = 116; +pub const EHOSTDOWN: ::c_int = 117; +pub const EHOSTUNREACH: ::c_int = 118; +pub const EINPROGRESS: ::c_int = 119; +pub const EALREADY: ::c_int = 120; +pub const EDESTADDRREQ: ::c_int = 121; +pub const EMSGSIZE: ::c_int = 122; +pub const EPROTONOSUPPORT: ::c_int = 123; +pub const EADDRNOTAVAIL: ::c_int = 125; +pub const ENETRESET: ::c_int = 126; +pub const EISCONN: ::c_int = 127; +pub const ENOTCONN: ::c_int = 128; +pub const ETOOMANYREFS: ::c_int = 129; +pub const EDQUOT: ::c_int = 132; +pub const ESTALE: ::c_int = 133; +pub const ENOTSUP: ::c_int = 134; +pub const EILSEQ: ::c_int = 138; +pub const EOVERFLOW: ::c_int = 139; +pub const ECANCELED: ::c_int = 140; +pub const ENOTRECOVERABLE: ::c_int = 141; +pub const EOWNERDEAD: ::c_int = 142; +pub const EWOULDBLOCK: ::c_int = 11; + +pub const F_DUPFD: ::c_int = 0; +pub const F_GETFD: ::c_int = 1; +pub const F_SETFD: ::c_int = 2; +pub const F_GETFL: ::c_int = 3; +pub const F_SETFL: ::c_int = 4; +pub const F_GETOWN: ::c_int = 5; +pub const F_SETOWN: ::c_int = 6; +pub const F_GETLK: ::c_int = 7; +pub const F_SETLK: ::c_int = 8; +pub const F_SETLKW: ::c_int = 9; +pub const F_RGETLK: ::c_int = 10; +pub const F_RSETLK: ::c_int = 11; +pub const F_CNVT: ::c_int = 12; +pub const F_RSETLKW: ::c_int = 13; +pub const F_DUPFD_CLOEXEC: ::c_int = 14; + +pub const O_RDONLY: ::c_int = 0; +pub const O_WRONLY: ::c_int = 1; +pub const O_RDWR: ::c_int = 2; +pub const O_APPEND: ::c_int = 8; +pub const O_CREAT: ::c_int = 512; +pub const O_TRUNC: ::c_int = 1024; +pub const O_EXCL: ::c_int = 2048; +pub const O_SYNC: ::c_int = 8192; +pub const O_NONBLOCK: ::c_int = 16384; + +pub const O_ACCMODE: ::c_int = 3; +pub const O_CLOEXEC: ::c_int = 0x80000; + +pub const POLLIN: ::c_short = 0x1; +pub const POLLPRI: ::c_short = 0x2; +pub const POLLOUT: ::c_short = 0x4; +pub const POLLERR: ::c_short = 0x8; +pub const POLLHUP: ::c_short = 0x10; +pub const POLLNVAL: ::c_short = 0x20; + +pub const RTLD_LAZY: ::c_int = 0x1; + +pub const STDIN_FILENO: ::c_int = 0; +pub const STDOUT_FILENO: ::c_int = 1; +pub const STDERR_FILENO: ::c_int = 2; + +pub const SEEK_SET: ::c_int = 0; +pub const SEEK_CUR: ::c_int = 1; +pub const SEEK_END: ::c_int = 2; + +pub const FIONBIO: ::c_int = 1; + +pub const S_BLKSIZE: ::mode_t = 1024; +pub const S_IREAD: ::mode_t = 256; +pub const S_IWRITE: ::mode_t = 128; +pub const S_IEXEC: ::mode_t = 64; +pub const S_ENFMT: ::mode_t = 1024; +pub const S_IFMT: ::mode_t = 61440; +pub const S_IFDIR: ::mode_t = 16384; +pub const S_IFCHR: ::mode_t = 8192; +pub const S_IFBLK: ::mode_t = 24576; +pub const S_IFREG: ::mode_t = 32768; +pub const S_IFLNK: ::mode_t = 40960; +pub const S_IFSOCK: ::mode_t = 49152; +pub const S_IFIFO: ::mode_t = 4096; +pub const S_IRUSR: ::mode_t = 256; +pub const S_IWUSR: ::mode_t = 128; +pub const S_IXUSR: ::mode_t = 64; +pub const S_IRGRP: ::mode_t = 32; +pub const S_IWGRP: ::mode_t = 16; +pub const S_IXGRP: ::mode_t = 8; +pub const S_IROTH: ::mode_t = 4; +pub const S_IWOTH: ::mode_t = 2; +pub const S_IXOTH: ::mode_t = 1; + +pub const SOL_SOCKET: ::c_int = 65535; +pub const SOL_TCP: ::c_int = 6; + +pub const PF_UNSPEC: ::c_int = 0; +pub const PF_INET: ::c_int = 2; +pub const PF_INET6: ::c_int = 23; + +pub const AF_UNSPEC: ::c_int = 0; +pub const AF_INET: ::c_int = 2; +pub const AF_INET6: ::c_int = 23; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; + +pub const MSG_OOB: ::c_int = 1; +pub const MSG_PEEK: ::c_int = 2; +pub const MSG_DONTWAIT: ::c_int = 4; +pub const MSG_DONTROUTE: ::c_int = 0; +pub const MSG_WAITALL: ::c_int = 0; +pub const MSG_MORE: ::c_int = 0; +pub const MSG_NOSIGNAL: ::c_int = 0; + +pub const SHUT_RD: ::c_int = 0; +pub const SHUT_WR: ::c_int = 1; +pub const SHUT_RDWR: ::c_int = 2; + +pub const SO_REUSEADDR: ::c_int = 4; +pub const SO_LINGER: ::c_int = 128; +pub const SO_OOBINLINE: ::c_int = 256; +pub const SO_SNDBUF: ::c_int = 4097; +pub const SO_RCVBUF: ::c_int = 4098; +pub const SO_SNDLOWAT: ::c_int = 4099; +pub const SO_RCVLOWAT: ::c_int = 4100; +pub const SO_TYPE: ::c_int = 4104; +pub const SO_ERROR: ::c_int = 4105; + +pub const SOCK_CLOEXEC: ::c_int = O_CLOEXEC; + +pub const INET_ADDRSTRLEN: ::c_int = 16; + +// https://github. +// com/bminor/newlib/blob/master/newlib/libc/sys/linux/include/net/if.h#L121 +pub const IFF_UP: ::c_int = 0x1; // interface is up +pub const IFF_BROADCAST: ::c_int = 0x2; // broadcast address valid +pub const IFF_DEBUG: ::c_int = 0x4; // turn on debugging +pub const IFF_LOOPBACK: ::c_int = 0x8; // is a loopback net +pub const IFF_POINTOPOINT: ::c_int = 0x10; // interface is point-to-point link +pub const IFF_NOTRAILERS: ::c_int = 0x20; // avoid use of trailers +pub const IFF_RUNNING: ::c_int = 0x40; // resources allocated +pub const IFF_NOARP: ::c_int = 0x80; // no address resolution protocol +pub const IFF_PROMISC: ::c_int = 0x100; // receive all packets +pub const IFF_ALLMULTI: ::c_int = 0x200; // receive all multicast packets +pub const IFF_OACTIVE: ::c_int = 0x400; // transmission in progress +pub const IFF_SIMPLEX: ::c_int = 0x800; // can't hear own transmissions +pub const IFF_LINK0: ::c_int = 0x1000; // per link layer defined bit +pub const IFF_LINK1: ::c_int = 0x2000; // per link layer defined bit +pub const IFF_LINK2: ::c_int = 0x4000; // per link layer defined bit +pub const IFF_ALTPHYS: ::c_int = IFF_LINK2; // use alternate physical connection +pub const IFF_MULTICAST: ::c_int = 0x8000; // supports multicast + +pub const IPPROTO_IP: ::c_int = 0; +pub const IPPROTO_UDP: ::c_int = 17; +pub const IPPROTO_TCP: ::c_int = 6; + +pub const TCP_NODELAY: ::c_int = 8193; +pub const TCP_MAXSEG: ::c_int = 8194; + +pub const IP_TOS: ::c_int = 7; +pub const IP_TTL: ::c_int = 8; +pub const IP_MULTICAST_LOOP: ::c_int = 9; +pub const IP_MULTICAST_TTL: ::c_int = 10; +pub const IP_ADD_MEMBERSHIP: ::c_int = 11; +pub const IP_DROP_MEMBERSHIP: ::c_int = 12; + +pub const HOST_NOT_FOUND: ::c_int = 1; +pub const NO_DATA: ::c_int = 2; +pub const NO_ADDRESS: ::c_int = 2; +pub const NO_RECOVERY: ::c_int = 3; +pub const TRY_AGAIN: ::c_int = 4; + +pub const AI_PASSIVE: ::c_int = 1; +pub const AI_CANONNAME: ::c_int = 2; +pub const AI_NUMERICHOST: ::c_int = 4; +pub const AI_NUMERICSERV: ::c_int = 0; +pub const AI_ADDRCONFIG: ::c_int = 0; + +pub const NI_MAXHOST: ::c_int = 1025; +pub const NI_MAXSERV: ::c_int = 32; +pub const NI_NOFQDN: ::c_int = 1; +pub const NI_NUMERICHOST: ::c_int = 2; +pub const NI_NAMEREQD: ::c_int = 4; +pub const NI_NUMERICSERV: ::c_int = 0; +pub const NI_DGRAM: ::c_int = 0; + +pub const EAI_FAMILY: ::c_int = -303; +pub const EAI_MEMORY: ::c_int = -304; +pub const EAI_NONAME: ::c_int = -305; +pub const EAI_SOCKTYPE: ::c_int = -307; + +f! { + pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { + let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; + let fd = fd as usize; + (*set).fds_bits[fd / bits] &= !(1 << (fd % bits)); + return + } + + pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { + let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; + let fd = fd as usize; + return ((*set).fds_bits[fd / bits] & (1 << (fd % bits))) != 0 + } + + pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { + let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; + let fd = fd as usize; + (*set).fds_bits[fd / bits] |= 1 << (fd % bits); + return + } + + pub fn FD_ZERO(set: *mut fd_set) -> () { + for slot in (*set).fds_bits.iter_mut() { + *slot = 0; + } + } +} + +extern { + pub fn bind(fd: ::c_int, addr: *const sockaddr, len: socklen_t) -> ::c_int; + pub fn closesocket(sockfd: ::c_int) -> ::c_int; + pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; + pub fn recvfrom(fd: ::c_int, buf: *mut ::c_void, n: usize, flags: ::c_int, + addr: *mut sockaddr, addr_len: *mut socklen_t) -> isize; + pub fn getnameinfo(sa: *const sockaddr, salen: socklen_t, + host: *mut ::c_char, hostlen: socklen_t, + serv: *mut ::c_char, servlen: socklen_t, + flags: ::c_int) -> ::c_int; + pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; + pub fn fexecve(fd: ::c_int, argv: *const *const ::c_char, + envp: *const *const ::c_char) + -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] + pub fn getgrgid_r(uid: ::uid_t, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "sigaltstack$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")] + pub fn sigaltstack(ss: *const stack_t, + oss: *mut stack_t) -> ::c_int; + pub fn sem_close(sem: *mut sem_t) -> ::c_int; + pub fn getdtablesize() -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] + pub fn getgrnam_r(name: *const ::c_char, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_sigmask$UNIX2003")] + pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, + oldset: *mut sigset_t) -> ::c_int; + pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; + pub fn getgrnam(name: *const ::c_char) -> *mut ::group; + pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; + pub fn sem_unlink(name: *const ::c_char) -> ::c_int; + pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] + pub fn getpwnam_r(name: *const ::c_char, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] + pub fn getpwuid_r(uid: ::uid_t, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch ="x86"), + link_name = "sigwait$UNIX2003")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] + pub fn sigwait(set: *const sigset_t, + sig: *mut ::c_int) -> ::c_int; + pub fn pthread_atfork(prepare: Option, + parent: Option, + child: Option) -> ::c_int; + pub fn getgrgid(gid: ::gid_t) -> *mut ::group; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "popen$UNIX2003")] + pub fn popen(command: *const c_char, + mode: *const c_char) -> *mut ::FILE; +} + +cfg_if! { + if #[cfg(target_arch = "arm")] { + mod arm; + pub use self::arm::*; + } else if #[cfg(target_arch = "aarch64")] { + mod aarch64; + pub use self::aarch64::*; + } else { + // Only tested on ARM so far. Other platforms might have different + // definitions for types and constants. + pub use target_arch_not_implemented; + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/b32/arm.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/b32/arm.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/b32/arm.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/b32/arm.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,357 @@ +pub type c_char = u8; +pub type wchar_t = u32; + +pub const O_DIRECT: ::c_int = 0x10000; +pub const O_DIRECTORY: ::c_int = 0x4000; +pub const O_NOFOLLOW: ::c_int = 0x8000; +pub const O_LARGEFILE: ::c_int = 0o400000; + +pub const SYS_restart_syscall: ::c_long = 0; +pub const SYS_exit: ::c_long = 1; +pub const SYS_fork: ::c_long = 2; +pub const SYS_read: ::c_long = 3; +pub const SYS_write: ::c_long = 4; +pub const SYS_open: ::c_long = 5; +pub const SYS_close: ::c_long = 6; +pub const SYS_creat: ::c_long = 8; +pub const SYS_link: ::c_long = 9; +pub const SYS_unlink: ::c_long = 10; +pub const SYS_execve: ::c_long = 11; +pub const SYS_chdir: ::c_long = 12; +pub const SYS_mknod: ::c_long = 14; +pub const SYS_chmod: ::c_long = 15; +pub const SYS_lchown: ::c_long = 16; +pub const SYS_lseek: ::c_long = 19; +pub const SYS_getpid: ::c_long = 20; +pub const SYS_mount: ::c_long = 21; +pub const SYS_setuid: ::c_long = 23; +pub const SYS_getuid: ::c_long = 24; +pub const SYS_ptrace: ::c_long = 26; +pub const SYS_pause: ::c_long = 29; +pub const SYS_access: ::c_long = 33; +pub const SYS_nice: ::c_long = 34; +pub const SYS_sync: ::c_long = 36; +pub const SYS_kill: ::c_long = 37; +pub const SYS_rename: ::c_long = 38; +pub const SYS_mkdir: ::c_long = 39; +pub const SYS_rmdir: ::c_long = 40; +pub const SYS_dup: ::c_long = 41; +pub const SYS_pipe: ::c_long = 42; +pub const SYS_times: ::c_long = 43; +pub const SYS_brk: ::c_long = 45; +pub const SYS_setgid: ::c_long = 46; +pub const SYS_getgid: ::c_long = 47; +pub const SYS_geteuid: ::c_long = 49; +pub const SYS_getegid: ::c_long = 50; +pub const SYS_acct: ::c_long = 51; +pub const SYS_umount2: ::c_long = 52; +pub const SYS_ioctl: ::c_long = 54; +pub const SYS_fcntl: ::c_long = 55; +pub const SYS_setpgid: ::c_long = 57; +pub const SYS_umask: ::c_long = 60; +pub const SYS_chroot: ::c_long = 61; +pub const SYS_ustat: ::c_long = 62; +pub const SYS_dup2: ::c_long = 63; +pub const SYS_getppid: ::c_long = 64; +pub const SYS_getpgrp: ::c_long = 65; +pub const SYS_setsid: ::c_long = 66; +pub const SYS_sigaction: ::c_long = 67; +pub const SYS_setreuid: ::c_long = 70; +pub const SYS_setregid: ::c_long = 71; +pub const SYS_sigsuspend: ::c_long = 72; +pub const SYS_sigpending: ::c_long = 73; +pub const SYS_sethostname: ::c_long = 74; +pub const SYS_setrlimit: ::c_long = 75; +pub const SYS_getrusage: ::c_long = 77; +pub const SYS_gettimeofday: ::c_long = 78; +pub const SYS_settimeofday: ::c_long = 79; +pub const SYS_getgroups: ::c_long = 80; +pub const SYS_setgroups: ::c_long = 81; +pub const SYS_symlink: ::c_long = 83; +pub const SYS_readlink: ::c_long = 85; +pub const SYS_uselib: ::c_long = 86; +pub const SYS_swapon: ::c_long = 87; +pub const SYS_reboot: ::c_long = 88; +pub const SYS_munmap: ::c_long = 91; +pub const SYS_truncate: ::c_long = 92; +pub const SYS_ftruncate: ::c_long = 93; +pub const SYS_fchmod: ::c_long = 94; +pub const SYS_fchown: ::c_long = 95; +pub const SYS_getpriority: ::c_long = 96; +pub const SYS_setpriority: ::c_long = 97; +pub const SYS_statfs: ::c_long = 99; +pub const SYS_fstatfs: ::c_long = 100; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_setitimer: ::c_long = 104; +pub const SYS_getitimer: ::c_long = 105; +pub const SYS_stat: ::c_long = 106; +pub const SYS_lstat: ::c_long = 107; +pub const SYS_fstat: ::c_long = 108; +pub const SYS_vhangup: ::c_long = 111; +pub const SYS_wait4: ::c_long = 114; +pub const SYS_swapoff: ::c_long = 115; +pub const SYS_sysinfo: ::c_long = 116; +pub const SYS_fsync: ::c_long = 118; +pub const SYS_sigreturn: ::c_long = 119; +pub const SYS_clone: ::c_long = 120; +pub const SYS_setdomainname: ::c_long = 121; +pub const SYS_uname: ::c_long = 122; +pub const SYS_adjtimex: ::c_long = 124; +pub const SYS_mprotect: ::c_long = 125; +pub const SYS_sigprocmask: ::c_long = 126; +pub const SYS_init_module: ::c_long = 128; +pub const SYS_delete_module: ::c_long = 129; +pub const SYS_quotactl: ::c_long = 131; +pub const SYS_getpgid: ::c_long = 132; +pub const SYS_fchdir: ::c_long = 133; +pub const SYS_bdflush: ::c_long = 134; +pub const SYS_sysfs: ::c_long = 135; +pub const SYS_personality: ::c_long = 136; +pub const SYS_setfsuid: ::c_long = 138; +pub const SYS_setfsgid: ::c_long = 139; +pub const SYS_getdents: ::c_long = 141; +pub const SYS_flock: ::c_long = 143; +pub const SYS_msync: ::c_long = 144; +pub const SYS_readv: ::c_long = 145; +pub const SYS_writev: ::c_long = 146; +pub const SYS_getsid: ::c_long = 147; +pub const SYS_fdatasync: ::c_long = 148; +pub const SYS_mlock: ::c_long = 150; +pub const SYS_munlock: ::c_long = 151; +pub const SYS_mlockall: ::c_long = 152; +pub const SYS_munlockall: ::c_long = 153; +pub const SYS_sched_setparam: ::c_long = 154; +pub const SYS_sched_getparam: ::c_long = 155; +pub const SYS_sched_setscheduler: ::c_long = 156; +pub const SYS_sched_getscheduler: ::c_long = 157; +pub const SYS_sched_yield: ::c_long = 158; +pub const SYS_sched_get_priority_max: ::c_long = 159; +pub const SYS_sched_get_priority_min: ::c_long = 160; +pub const SYS_sched_rr_get_interval: ::c_long = 161; +pub const SYS_nanosleep: ::c_long = 162; +pub const SYS_mremap: ::c_long = 163; +pub const SYS_setresuid: ::c_long = 164; +pub const SYS_getresuid: ::c_long = 165; +pub const SYS_poll: ::c_long = 168; +pub const SYS_nfsservctl: ::c_long = 169; +pub const SYS_setresgid: ::c_long = 170; +pub const SYS_getresgid: ::c_long = 171; +pub const SYS_prctl: ::c_long = 172; +pub const SYS_rt_sigreturn: ::c_long = 173; +pub const SYS_rt_sigaction: ::c_long = 174; +pub const SYS_rt_sigprocmask: ::c_long = 175; +pub const SYS_rt_sigpending: ::c_long = 176; +pub const SYS_rt_sigtimedwait: ::c_long = 177; +pub const SYS_rt_sigqueueinfo: ::c_long = 178; +pub const SYS_rt_sigsuspend: ::c_long = 179; +pub const SYS_pread64: ::c_long = 180; +pub const SYS_pwrite64: ::c_long = 181; +pub const SYS_chown: ::c_long = 182; +pub const SYS_getcwd: ::c_long = 183; +pub const SYS_capget: ::c_long = 184; +pub const SYS_capset: ::c_long = 185; +pub const SYS_sigaltstack: ::c_long = 186; +pub const SYS_sendfile: ::c_long = 187; +pub const SYS_vfork: ::c_long = 190; +pub const SYS_ugetrlimit: ::c_long = 191; +pub const SYS_mmap2: ::c_long = 192; +pub const SYS_truncate64: ::c_long = 193; +pub const SYS_ftruncate64: ::c_long = 194; +pub const SYS_stat64: ::c_long = 195; +pub const SYS_lstat64: ::c_long = 196; +pub const SYS_fstat64: ::c_long = 197; +pub const SYS_lchown32: ::c_long = 198; +pub const SYS_getuid32: ::c_long = 199; +pub const SYS_getgid32: ::c_long = 200; +pub const SYS_geteuid32: ::c_long = 201; +pub const SYS_getegid32: ::c_long = 202; +pub const SYS_setreuid32: ::c_long = 203; +pub const SYS_setregid32: ::c_long = 204; +pub const SYS_getgroups32: ::c_long = 205; +pub const SYS_setgroups32: ::c_long = 206; +pub const SYS_fchown32: ::c_long = 207; +pub const SYS_setresuid32: ::c_long = 208; +pub const SYS_getresuid32: ::c_long = 209; +pub const SYS_setresgid32: ::c_long = 210; +pub const SYS_getresgid32: ::c_long = 211; +pub const SYS_chown32: ::c_long = 212; +pub const SYS_setuid32: ::c_long = 213; +pub const SYS_setgid32: ::c_long = 214; +pub const SYS_setfsuid32: ::c_long = 215; +pub const SYS_setfsgid32: ::c_long = 216; +pub const SYS_getdents64: ::c_long = 217; +pub const SYS_pivot_root: ::c_long = 218; +pub const SYS_mincore: ::c_long = 219; +pub const SYS_madvise: ::c_long = 220; +pub const SYS_fcntl64: ::c_long = 221; +pub const SYS_gettid: ::c_long = 224; +pub const SYS_readahead: ::c_long = 225; +pub const SYS_setxattr: ::c_long = 226; +pub const SYS_lsetxattr: ::c_long = 227; +pub const SYS_fsetxattr: ::c_long = 228; +pub const SYS_getxattr: ::c_long = 229; +pub const SYS_lgetxattr: ::c_long = 230; +pub const SYS_fgetxattr: ::c_long = 231; +pub const SYS_listxattr: ::c_long = 232; +pub const SYS_llistxattr: ::c_long = 233; +pub const SYS_flistxattr: ::c_long = 234; +pub const SYS_removexattr: ::c_long = 235; +pub const SYS_lremovexattr: ::c_long = 236; +pub const SYS_fremovexattr: ::c_long = 237; +pub const SYS_tkill: ::c_long = 238; +pub const SYS_sendfile64: ::c_long = 239; +pub const SYS_futex: ::c_long = 240; +pub const SYS_sched_setaffinity: ::c_long = 241; +pub const SYS_sched_getaffinity: ::c_long = 242; +pub const SYS_io_setup: ::c_long = 243; +pub const SYS_io_destroy: ::c_long = 244; +pub const SYS_io_getevents: ::c_long = 245; +pub const SYS_io_submit: ::c_long = 246; +pub const SYS_io_cancel: ::c_long = 247; +pub const SYS_exit_group: ::c_long = 248; +pub const SYS_lookup_dcookie: ::c_long = 249; +pub const SYS_epoll_create: ::c_long = 250; +pub const SYS_epoll_ctl: ::c_long = 251; +pub const SYS_epoll_wait: ::c_long = 252; +pub const SYS_remap_file_pages: ::c_long = 253; +pub const SYS_set_tid_address: ::c_long = 256; +pub const SYS_timer_create: ::c_long = 257; +pub const SYS_timer_settime: ::c_long = 258; +pub const SYS_timer_gettime: ::c_long = 259; +pub const SYS_timer_getoverrun: ::c_long = 260; +pub const SYS_timer_delete: ::c_long = 261; +pub const SYS_clock_settime: ::c_long = 262; +pub const SYS_clock_gettime: ::c_long = 263; +pub const SYS_clock_getres: ::c_long = 264; +pub const SYS_clock_nanosleep: ::c_long = 265; +pub const SYS_statfs64: ::c_long = 266; +pub const SYS_fstatfs64: ::c_long = 267; +pub const SYS_tgkill: ::c_long = 268; +pub const SYS_utimes: ::c_long = 269; +pub const SYS_arm_fadvise64_64: ::c_long = 270; +pub const SYS_pciconfig_iobase: ::c_long = 271; +pub const SYS_pciconfig_read: ::c_long = 272; +pub const SYS_pciconfig_write: ::c_long = 273; +pub const SYS_mq_open: ::c_long = 274; +pub const SYS_mq_unlink: ::c_long = 275; +pub const SYS_mq_timedsend: ::c_long = 276; +pub const SYS_mq_timedreceive: ::c_long = 277; +pub const SYS_mq_notify: ::c_long = 278; +pub const SYS_mq_getsetattr: ::c_long = 279; +pub const SYS_waitid: ::c_long = 280; +pub const SYS_socket: ::c_long = 281; +pub const SYS_bind: ::c_long = 282; +pub const SYS_connect: ::c_long = 283; +pub const SYS_listen: ::c_long = 284; +pub const SYS_accept: ::c_long = 285; +pub const SYS_getsockname: ::c_long = 286; +pub const SYS_getpeername: ::c_long = 287; +pub const SYS_socketpair: ::c_long = 288; +pub const SYS_send: ::c_long = 289; +pub const SYS_sendto: ::c_long = 290; +pub const SYS_recv: ::c_long = 291; +pub const SYS_recvfrom: ::c_long = 292; +pub const SYS_shutdown: ::c_long = 293; +pub const SYS_setsockopt: ::c_long = 294; +pub const SYS_getsockopt: ::c_long = 295; +pub const SYS_sendmsg: ::c_long = 296; +pub const SYS_recvmsg: ::c_long = 297; +pub const SYS_semop: ::c_long = 298; +pub const SYS_semget: ::c_long = 299; +pub const SYS_semctl: ::c_long = 300; +pub const SYS_msgsnd: ::c_long = 301; +pub const SYS_msgrcv: ::c_long = 302; +pub const SYS_msgget: ::c_long = 303; +pub const SYS_msgctl: ::c_long = 304; +pub const SYS_shmat: ::c_long = 305; +pub const SYS_shmdt: ::c_long = 306; +pub const SYS_shmget: ::c_long = 307; +pub const SYS_shmctl: ::c_long = 308; +pub const SYS_add_key: ::c_long = 309; +pub const SYS_request_key: ::c_long = 310; +pub const SYS_keyctl: ::c_long = 311; +pub const SYS_semtimedop: ::c_long = 312; +pub const SYS_vserver: ::c_long = 313; +pub const SYS_ioprio_set: ::c_long = 314; +pub const SYS_ioprio_get: ::c_long = 315; +pub const SYS_inotify_init: ::c_long = 316; +pub const SYS_inotify_add_watch: ::c_long = 317; +pub const SYS_inotify_rm_watch: ::c_long = 318; +pub const SYS_mbind: ::c_long = 319; +pub const SYS_get_mempolicy: ::c_long = 320; +pub const SYS_set_mempolicy: ::c_long = 321; +pub const SYS_openat: ::c_long = 322; +pub const SYS_mkdirat: ::c_long = 323; +pub const SYS_mknodat: ::c_long = 324; +pub const SYS_fchownat: ::c_long = 325; +pub const SYS_futimesat: ::c_long = 326; +pub const SYS_fstatat64: ::c_long = 327; +pub const SYS_unlinkat: ::c_long = 328; +pub const SYS_renameat: ::c_long = 329; +pub const SYS_linkat: ::c_long = 330; +pub const SYS_symlinkat: ::c_long = 331; +pub const SYS_readlinkat: ::c_long = 332; +pub const SYS_fchmodat: ::c_long = 333; +pub const SYS_faccessat: ::c_long = 334; +pub const SYS_pselect6: ::c_long = 335; +pub const SYS_ppoll: ::c_long = 336; +pub const SYS_unshare: ::c_long = 337; +pub const SYS_set_robust_list: ::c_long = 338; +pub const SYS_get_robust_list: ::c_long = 339; +pub const SYS_splice: ::c_long = 340; +pub const SYS_arm_sync_file_range: ::c_long = 341; +pub const SYS_tee: ::c_long = 342; +pub const SYS_vmsplice: ::c_long = 343; +pub const SYS_move_pages: ::c_long = 344; +pub const SYS_getcpu: ::c_long = 345; +pub const SYS_epoll_pwait: ::c_long = 346; +pub const SYS_kexec_load: ::c_long = 347; +pub const SYS_utimensat: ::c_long = 348; +pub const SYS_signalfd: ::c_long = 349; +pub const SYS_timerfd_create: ::c_long = 350; +pub const SYS_eventfd: ::c_long = 351; +pub const SYS_fallocate: ::c_long = 352; +pub const SYS_timerfd_settime: ::c_long = 353; +pub const SYS_timerfd_gettime: ::c_long = 354; +pub const SYS_signalfd4: ::c_long = 355; +pub const SYS_eventfd2: ::c_long = 356; +pub const SYS_epoll_create1: ::c_long = 357; +pub const SYS_dup3: ::c_long = 358; +pub const SYS_pipe2: ::c_long = 359; +pub const SYS_inotify_init1: ::c_long = 360; +pub const SYS_preadv: ::c_long = 361; +pub const SYS_pwritev: ::c_long = 362; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 363; +pub const SYS_perf_event_open: ::c_long = 364; +pub const SYS_recvmmsg: ::c_long = 365; +pub const SYS_accept4: ::c_long = 366; +pub const SYS_fanotify_init: ::c_long = 367; +pub const SYS_fanotify_mark: ::c_long = 368; +pub const SYS_prlimit64: ::c_long = 369; +pub const SYS_name_to_handle_at: ::c_long = 370; +pub const SYS_open_by_handle_at: ::c_long = 371; +pub const SYS_clock_adjtime: ::c_long = 372; +pub const SYS_syncfs: ::c_long = 373; +pub const SYS_sendmmsg: ::c_long = 374; +pub const SYS_setns: ::c_long = 375; +pub const SYS_process_vm_readv: ::c_long = 376; +pub const SYS_process_vm_writev: ::c_long = 377; +pub const SYS_kcmp: ::c_long = 378; +pub const SYS_finit_module: ::c_long = 379; +pub const SYS_sched_setattr: ::c_long = 380; +pub const SYS_sched_getattr: ::c_long = 381; +pub const SYS_renameat2: ::c_long = 382; +pub const SYS_seccomp: ::c_long = 383; +pub const SYS_getrandom: ::c_long = 384; +pub const SYS_memfd_create: ::c_long = 385; +pub const SYS_bpf: ::c_long = 386; +pub const SYS_execveat: ::c_long = 387; +pub const SYS_userfaultfd: ::c_long = 388; +pub const SYS_membarrier: ::c_long = 389; +pub const SYS_mlock2: ::c_long = 390; +pub const SYS_copy_file_range: ::c_long = 391; +pub const SYS_preadv2: ::c_long = 392; +pub const SYS_pwritev2: ::c_long = 393; +pub const SYS_pkey_mprotect: ::c_long = 394; +pub const SYS_pkey_alloc: ::c_long = 395; +pub const SYS_pkey_free: ::c_long = 396; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/b32/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/b32/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/b32/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/b32/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,230 @@ +// The following definitions are correct for arm and i686, +// but may be wrong for mips + +pub type c_long = i32; +pub type c_ulong = u32; +pub type mode_t = u16; +pub type off64_t = ::c_longlong; +pub type sigset_t = ::c_ulong; +pub type socklen_t = i32; +pub type time64_t = i64; + +s! { + pub struct sigaction { + pub sa_sigaction: ::sighandler_t, + pub sa_mask: ::sigset_t, + pub sa_flags: ::c_ulong, + pub sa_restorer: ::dox::Option, + } + + pub struct rlimit64 { + pub rlim_cur: u64, + pub rlim_max: u64, + } + + pub struct stat { + pub st_dev: ::c_ulonglong, + __pad0: [::c_uchar; 4], + __st_ino: ::ino_t, + pub st_mode: ::c_uint, + pub st_nlink: ::c_uint, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::c_ulonglong, + __pad3: [::c_uchar; 4], + pub st_size: ::c_longlong, + pub st_blksize: ::blksize_t, + pub st_blocks: ::c_ulonglong, + pub st_atime: ::c_ulong, + pub st_atime_nsec: ::c_ulong, + pub st_mtime: ::c_ulong, + pub st_mtime_nsec: ::c_ulong, + pub st_ctime: ::c_ulong, + pub st_ctime_nsec: ::c_ulong, + pub st_ino: ::c_ulonglong, + } + + pub struct stat64 { + pub st_dev: ::c_ulonglong, + __pad0: [::c_uchar; 4], + __st_ino: ::ino_t, + pub st_mode: ::c_uint, + pub st_nlink: ::c_uint, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::c_ulonglong, + __pad3: [::c_uchar; 4], + pub st_size: ::c_longlong, + pub st_blksize: ::blksize_t, + pub st_blocks: ::c_ulonglong, + pub st_atime: ::c_ulong, + pub st_atime_nsec: ::c_ulong, + pub st_mtime: ::c_ulong, + pub st_mtime_nsec: ::c_ulong, + pub st_ctime: ::c_ulong, + pub st_ctime_nsec: ::c_ulong, + pub st_ino: ::c_ulonglong, + } + + pub struct statfs64 { + pub f_type: u32, + pub f_bsize: u32, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + f_fsid: [u32; 2], + pub f_namelen: u32, + pub f_frsize: u32, + pub f_flags: u32, + pub f_spare: [u32; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::c_ulong, + pub f_bfree: ::c_ulong, + pub f_bavail: ::c_ulong, + pub f_files: ::c_ulong, + pub f_ffree: ::c_ulong, + pub f_favail: ::c_ulong, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + } + + pub struct pthread_attr_t { + pub flags: ::uint32_t, + pub stack_base: *mut ::c_void, + pub stack_size: ::size_t, + pub guard_size: ::size_t, + pub sched_policy: ::int32_t, + pub sched_priority: ::int32_t, + } + + pub struct pthread_mutex_t { value: ::c_int } + + pub struct pthread_cond_t { value: ::c_int } + + pub struct pthread_rwlock_t { + lock: pthread_mutex_t, + cond: pthread_cond_t, + numLocks: ::c_int, + writerThreadId: ::c_int, + pendingReaders: ::c_int, + pendingWriters: ::c_int, + attr: i32, + __reserved: [::c_char; 12], + } + + pub struct passwd { + pub pw_name: *mut ::c_char, + pub pw_passwd: *mut ::c_char, + pub pw_uid: ::uid_t, + pub pw_gid: ::gid_t, + pub pw_dir: *mut ::c_char, + pub pw_shell: *mut ::c_char, + } + + pub struct statfs { + pub f_type: ::uint32_t, + pub f_bsize: ::uint32_t, + pub f_blocks: ::uint64_t, + pub f_bfree: ::uint64_t, + pub f_bavail: ::uint64_t, + pub f_files: ::uint64_t, + pub f_ffree: ::uint64_t, + pub f_fsid: ::__fsid_t, + pub f_namelen: ::uint32_t, + pub f_frsize: ::uint32_t, + pub f_flags: ::uint32_t, + pub f_spare: [::uint32_t; 4], + } + + pub struct sysinfo { + pub uptime: ::c_long, + pub loads: [::c_ulong; 3], + pub totalram: ::c_ulong, + pub freeram: ::c_ulong, + pub sharedram: ::c_ulong, + pub bufferram: ::c_ulong, + pub totalswap: ::c_ulong, + pub freeswap: ::c_ulong, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: ::c_ulong, + pub freehigh: ::c_ulong, + pub mem_unit: ::c_uint, + pub _f: [::c_char; 8], + } +} + +pub const RTLD_GLOBAL: ::c_int = 2; +pub const RTLD_NOW: ::c_int = 0; +pub const RTLD_DEFAULT: *mut ::c_void = -1isize as *mut ::c_void; + +pub const PTRACE_GETFPREGS: ::c_int = 14; +pub const PTRACE_SETFPREGS: ::c_int = 15; +pub const PTRACE_GETREGS: ::c_int = 12; +pub const PTRACE_SETREGS: ::c_int = 13; + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + value: 0, +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + value: 0, +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + lock: PTHREAD_MUTEX_INITIALIZER, + cond: PTHREAD_COND_INITIALIZER, + numLocks: 0, + writerThreadId: 0, + pendingReaders: 0, + pendingWriters: 0, + attr: 0, + __reserved: [0; 12], +}; +pub const PTHREAD_STACK_MIN: ::size_t = 4096 * 2; +pub const CPU_SETSIZE: ::size_t = 32; +pub const __CPU_BITS: ::size_t = 32; + +pub const UT_LINESIZE: usize = 8; +pub const UT_NAMESIZE: usize = 8; +pub const UT_HOSTSIZE: usize = 16; + +pub const SIGSTKSZ: ::size_t = 8192; +pub const MINSIGSTKSZ: ::size_t = 2048; + +extern { + pub fn bind(socket: ::c_int, address: *const ::sockaddr, + address_len: socklen_t) -> ::c_int; + + pub fn writev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + pub fn readv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + + pub fn sendmsg(fd: ::c_int, + msg: *const ::msghdr, + flags: ::c_int) -> ::ssize_t; + pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) + -> ::ssize_t; + + pub fn timegm64(tm: *const ::tm) -> ::time64_t; +} + +cfg_if! { + if #[cfg(target_arch = "x86")] { + mod x86; + pub use self::x86::*; + } else if #[cfg(target_arch = "arm")] { + mod arm; + pub use self::arm::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/b32/x86.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/b32/x86.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/b32/x86.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/b32/x86.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,415 @@ +pub type c_char = i8; +pub type wchar_t = i32; + +pub const O_DIRECT: ::c_int = 0x4000; +pub const O_DIRECTORY: ::c_int = 0x10000; +pub const O_NOFOLLOW: ::c_int = 0x20000; +pub const O_LARGEFILE: ::c_int = 0o0100000; + +pub const MAP_32BIT: ::c_int = 0x40; + +// Syscall table +pub const SYS_restart_syscall: ::c_long = 0; +pub const SYS_exit: ::c_long = 1; +pub const SYS_fork: ::c_long = 2; +pub const SYS_read: ::c_long = 3; +pub const SYS_write: ::c_long = 4; +pub const SYS_open: ::c_long = 5; +pub const SYS_close: ::c_long = 6; +pub const SYS_waitpid: ::c_long = 7; +pub const SYS_creat: ::c_long = 8; +pub const SYS_link: ::c_long = 9; +pub const SYS_unlink: ::c_long = 10; +pub const SYS_execve: ::c_long = 11; +pub const SYS_chdir: ::c_long = 12; +pub const SYS_time: ::c_long = 13; +pub const SYS_mknod: ::c_long = 14; +pub const SYS_chmod: ::c_long = 15; +pub const SYS_lchown: ::c_long = 16; +pub const SYS_break: ::c_long = 17; +pub const SYS_oldstat: ::c_long = 18; +pub const SYS_lseek: ::c_long = 19; +pub const SYS_getpid: ::c_long = 20; +pub const SYS_mount: ::c_long = 21; +pub const SYS_umount: ::c_long = 22; +pub const SYS_setuid: ::c_long = 23; +pub const SYS_getuid: ::c_long = 24; +pub const SYS_stime: ::c_long = 25; +pub const SYS_ptrace: ::c_long = 26; +pub const SYS_alarm: ::c_long = 27; +pub const SYS_oldfstat: ::c_long = 28; +pub const SYS_pause: ::c_long = 29; +pub const SYS_utime: ::c_long = 30; +pub const SYS_stty: ::c_long = 31; +pub const SYS_gtty: ::c_long = 32; +pub const SYS_access: ::c_long = 33; +pub const SYS_nice: ::c_long = 34; +pub const SYS_ftime: ::c_long = 35; +pub const SYS_sync: ::c_long = 36; +pub const SYS_kill: ::c_long = 37; +pub const SYS_rename: ::c_long = 38; +pub const SYS_mkdir: ::c_long = 39; +pub const SYS_rmdir: ::c_long = 40; +pub const SYS_dup: ::c_long = 41; +pub const SYS_pipe: ::c_long = 42; +pub const SYS_times: ::c_long = 43; +pub const SYS_prof: ::c_long = 44; +pub const SYS_brk: ::c_long = 45; +pub const SYS_setgid: ::c_long = 46; +pub const SYS_getgid: ::c_long = 47; +pub const SYS_signal: ::c_long = 48; +pub const SYS_geteuid: ::c_long = 49; +pub const SYS_getegid: ::c_long = 50; +pub const SYS_acct: ::c_long = 51; +pub const SYS_umount2: ::c_long = 52; +pub const SYS_lock: ::c_long = 53; +pub const SYS_ioctl: ::c_long = 54; +pub const SYS_fcntl: ::c_long = 55; +pub const SYS_mpx: ::c_long = 56; +pub const SYS_setpgid: ::c_long = 57; +pub const SYS_ulimit: ::c_long = 58; +pub const SYS_oldolduname: ::c_long = 59; +pub const SYS_umask: ::c_long = 60; +pub const SYS_chroot: ::c_long = 61; +pub const SYS_ustat: ::c_long = 62; +pub const SYS_dup2: ::c_long = 63; +pub const SYS_getppid: ::c_long = 64; +pub const SYS_getpgrp: ::c_long = 65; +pub const SYS_setsid: ::c_long = 66; +pub const SYS_sigaction: ::c_long = 67; +pub const SYS_sgetmask: ::c_long = 68; +pub const SYS_ssetmask: ::c_long = 69; +pub const SYS_setreuid: ::c_long = 70; +pub const SYS_setregid: ::c_long = 71; +pub const SYS_sigsuspend: ::c_long = 72; +pub const SYS_sigpending: ::c_long = 73; +pub const SYS_sethostname: ::c_long = 74; +pub const SYS_setrlimit: ::c_long = 75; +pub const SYS_getrlimit: ::c_long = 76; +pub const SYS_getrusage: ::c_long = 77; +pub const SYS_gettimeofday: ::c_long = 78; +pub const SYS_settimeofday: ::c_long = 79; +pub const SYS_getgroups: ::c_long = 80; +pub const SYS_setgroups: ::c_long = 81; +pub const SYS_select: ::c_long = 82; +pub const SYS_symlink: ::c_long = 83; +pub const SYS_oldlstat: ::c_long = 84; +pub const SYS_readlink: ::c_long = 85; +pub const SYS_uselib: ::c_long = 86; +pub const SYS_swapon: ::c_long = 87; +pub const SYS_reboot: ::c_long = 88; +pub const SYS_readdir: ::c_long = 89; +pub const SYS_mmap: ::c_long = 90; +pub const SYS_munmap: ::c_long = 91; +pub const SYS_truncate: ::c_long = 92; +pub const SYS_ftruncate: ::c_long = 93; +pub const SYS_fchmod: ::c_long = 94; +pub const SYS_fchown: ::c_long = 95; +pub const SYS_getpriority: ::c_long = 96; +pub const SYS_setpriority: ::c_long = 97; +pub const SYS_profil: ::c_long = 98; +pub const SYS_statfs: ::c_long = 99; +pub const SYS_fstatfs: ::c_long = 100; +pub const SYS_ioperm: ::c_long = 101; +pub const SYS_socketcall: ::c_long = 102; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_setitimer: ::c_long = 104; +pub const SYS_getitimer: ::c_long = 105; +pub const SYS_stat: ::c_long = 106; +pub const SYS_lstat: ::c_long = 107; +pub const SYS_fstat: ::c_long = 108; +pub const SYS_olduname: ::c_long = 109; +pub const SYS_iopl: ::c_long = 110; +pub const SYS_vhangup: ::c_long = 111; +pub const SYS_idle: ::c_long = 112; +pub const SYS_vm86old: ::c_long = 113; +pub const SYS_wait4: ::c_long = 114; +pub const SYS_swapoff: ::c_long = 115; +pub const SYS_sysinfo: ::c_long = 116; +pub const SYS_ipc: ::c_long = 117; +pub const SYS_fsync: ::c_long = 118; +pub const SYS_sigreturn: ::c_long = 119; +pub const SYS_clone: ::c_long = 120; +pub const SYS_setdomainname: ::c_long = 121; +pub const SYS_uname: ::c_long = 122; +pub const SYS_modify_ldt: ::c_long = 123; +pub const SYS_adjtimex: ::c_long = 124; +pub const SYS_mprotect: ::c_long = 125; +pub const SYS_sigprocmask: ::c_long = 126; +pub const SYS_create_module: ::c_long = 127; +pub const SYS_init_module: ::c_long = 128; +pub const SYS_delete_module: ::c_long = 129; +pub const SYS_get_kernel_syms: ::c_long = 130; +pub const SYS_quotactl: ::c_long = 131; +pub const SYS_getpgid: ::c_long = 132; +pub const SYS_fchdir: ::c_long = 133; +pub const SYS_bdflush: ::c_long = 134; +pub const SYS_sysfs: ::c_long = 135; +pub const SYS_personality: ::c_long = 136; +pub const SYS_afs_syscall: ::c_long = 137; +pub const SYS_setfsuid: ::c_long = 138; +pub const SYS_setfsgid: ::c_long = 139; +// FIXME: SYS__llseek is in the NDK sources but for some reason is +// not available in the tests +// pub const SYS__llseek: ::c_long = 140; +pub const SYS_getdents: ::c_long = 141; +// FIXME: SYS__newselect is in the NDK sources but for some reason is +// not available in the tests +// pub const SYS__newselect: ::c_long = 142; +pub const SYS_flock: ::c_long = 143; +pub const SYS_msync: ::c_long = 144; +pub const SYS_readv: ::c_long = 145; +pub const SYS_writev: ::c_long = 146; +pub const SYS_getsid: ::c_long = 147; +pub const SYS_fdatasync: ::c_long = 148; +// FIXME: SYS__llseek is in the NDK sources but for some reason is +// not available in the tests +// pub const SYS__sysctl: ::c_long = 149; +pub const SYS_mlock: ::c_long = 150; +pub const SYS_munlock: ::c_long = 151; +pub const SYS_mlockall: ::c_long = 152; +pub const SYS_munlockall: ::c_long = 153; +pub const SYS_sched_setparam: ::c_long = 154; +pub const SYS_sched_getparam: ::c_long = 155; +pub const SYS_sched_setscheduler: ::c_long = 156; +pub const SYS_sched_getscheduler: ::c_long = 157; +pub const SYS_sched_yield: ::c_long = 158; +pub const SYS_sched_get_priority_max: ::c_long = 159; +pub const SYS_sched_get_priority_min: ::c_long = 160; +pub const SYS_sched_rr_get_interval: ::c_long = 161; +pub const SYS_nanosleep: ::c_long = 162; +pub const SYS_mremap: ::c_long = 163; +pub const SYS_setresuid: ::c_long = 164; +pub const SYS_getresuid: ::c_long = 165; +pub const SYS_vm86: ::c_long = 166; +pub const SYS_query_module: ::c_long = 167; +pub const SYS_poll: ::c_long = 168; +pub const SYS_nfsservctl: ::c_long = 169; +pub const SYS_setresgid: ::c_long = 170; +pub const SYS_getresgid: ::c_long = 171; +pub const SYS_prctl: ::c_long = 172; +pub const SYS_rt_sigreturn: ::c_long = 173; +pub const SYS_rt_sigaction: ::c_long = 174; +pub const SYS_rt_sigprocmask: ::c_long = 175; +pub const SYS_rt_sigpending: ::c_long = 176; +pub const SYS_rt_sigtimedwait: ::c_long = 177; +pub const SYS_rt_sigqueueinfo: ::c_long = 178; +pub const SYS_rt_sigsuspend: ::c_long = 179; +pub const SYS_pread64: ::c_long = 180; +pub const SYS_pwrite64: ::c_long = 181; +pub const SYS_chown: ::c_long = 182; +pub const SYS_getcwd: ::c_long = 183; +pub const SYS_capget: ::c_long = 184; +pub const SYS_capset: ::c_long = 185; +pub const SYS_sigaltstack: ::c_long = 186; +pub const SYS_sendfile: ::c_long = 187; +pub const SYS_getpmsg: ::c_long = 188; +pub const SYS_putpmsg: ::c_long = 189; +pub const SYS_vfork: ::c_long = 190; +pub const SYS_ugetrlimit: ::c_long = 191; +pub const SYS_mmap2: ::c_long = 192; +pub const SYS_truncate64: ::c_long = 193; +pub const SYS_ftruncate64: ::c_long = 194; +pub const SYS_stat64: ::c_long = 195; +pub const SYS_lstat64: ::c_long = 196; +pub const SYS_fstat64: ::c_long = 197; +pub const SYS_lchown32: ::c_long = 198; +pub const SYS_getuid32: ::c_long = 199; +pub const SYS_getgid32: ::c_long = 200; +pub const SYS_geteuid32: ::c_long = 201; +pub const SYS_getegid32: ::c_long = 202; +pub const SYS_setreuid32: ::c_long = 203; +pub const SYS_setregid32: ::c_long = 204; +pub const SYS_getgroups32: ::c_long = 205; +pub const SYS_setgroups32: ::c_long = 206; +pub const SYS_fchown32: ::c_long = 207; +pub const SYS_setresuid32: ::c_long = 208; +pub const SYS_getresuid32: ::c_long = 209; +pub const SYS_setresgid32: ::c_long = 210; +pub const SYS_getresgid32: ::c_long = 211; +pub const SYS_chown32: ::c_long = 212; +pub const SYS_setuid32: ::c_long = 213; +pub const SYS_setgid32: ::c_long = 214; +pub const SYS_setfsuid32: ::c_long = 215; +pub const SYS_setfsgid32: ::c_long = 216; +pub const SYS_pivot_root: ::c_long = 217; +pub const SYS_mincore: ::c_long = 218; +pub const SYS_madvise: ::c_long = 219; +pub const SYS_getdents64: ::c_long = 220; +pub const SYS_fcntl64: ::c_long = 221; +pub const SYS_gettid: ::c_long = 224; +pub const SYS_readahead: ::c_long = 225; +pub const SYS_setxattr: ::c_long = 226; +pub const SYS_lsetxattr: ::c_long = 227; +pub const SYS_fsetxattr: ::c_long = 228; +pub const SYS_getxattr: ::c_long = 229; +pub const SYS_lgetxattr: ::c_long = 230; +pub const SYS_fgetxattr: ::c_long = 231; +pub const SYS_listxattr: ::c_long = 232; +pub const SYS_llistxattr: ::c_long = 233; +pub const SYS_flistxattr: ::c_long = 234; +pub const SYS_removexattr: ::c_long = 235; +pub const SYS_lremovexattr: ::c_long = 236; +pub const SYS_fremovexattr: ::c_long = 237; +pub const SYS_tkill: ::c_long = 238; +pub const SYS_sendfile64: ::c_long = 239; +pub const SYS_futex: ::c_long = 240; +pub const SYS_sched_setaffinity: ::c_long = 241; +pub const SYS_sched_getaffinity: ::c_long = 242; +pub const SYS_set_thread_area: ::c_long = 243; +pub const SYS_get_thread_area: ::c_long = 244; +pub const SYS_io_setup: ::c_long = 245; +pub const SYS_io_destroy: ::c_long = 246; +pub const SYS_io_getevents: ::c_long = 247; +pub const SYS_io_submit: ::c_long = 248; +pub const SYS_io_cancel: ::c_long = 249; +pub const SYS_fadvise64: ::c_long = 250; +pub const SYS_exit_group: ::c_long = 252; +pub const SYS_lookup_dcookie: ::c_long = 253; +pub const SYS_epoll_create: ::c_long = 254; +pub const SYS_epoll_ctl: ::c_long = 255; +pub const SYS_epoll_wait: ::c_long = 256; +pub const SYS_remap_file_pages: ::c_long = 257; +pub const SYS_set_tid_address: ::c_long = 258; +pub const SYS_timer_create: ::c_long = 259; +pub const SYS_timer_settime: ::c_long = 260; +pub const SYS_timer_gettime: ::c_long = 261; +pub const SYS_timer_getoverrun: ::c_long = 262; +pub const SYS_timer_delete: ::c_long = 263; +pub const SYS_clock_settime: ::c_long = 264; +pub const SYS_clock_gettime: ::c_long = 265; +pub const SYS_clock_getres: ::c_long = 266; +pub const SYS_clock_nanosleep: ::c_long = 267; +pub const SYS_statfs64: ::c_long = 268; +pub const SYS_fstatfs64: ::c_long = 269; +pub const SYS_tgkill: ::c_long = 270; +pub const SYS_utimes: ::c_long = 271; +pub const SYS_fadvise64_64: ::c_long = 272; +pub const SYS_vserver: ::c_long = 273; +pub const SYS_mbind: ::c_long = 274; +pub const SYS_get_mempolicy: ::c_long = 275; +pub const SYS_set_mempolicy: ::c_long = 276; +pub const SYS_mq_open: ::c_long = 277; +pub const SYS_mq_unlink: ::c_long = 278; +pub const SYS_mq_timedsend: ::c_long = 279; +pub const SYS_mq_timedreceive: ::c_long = 280; +pub const SYS_mq_notify: ::c_long = 281; +pub const SYS_mq_getsetattr: ::c_long = 282; +pub const SYS_kexec_load: ::c_long = 283; +pub const SYS_waitid: ::c_long = 284; +pub const SYS_add_key: ::c_long = 286; +pub const SYS_request_key: ::c_long = 287; +pub const SYS_keyctl: ::c_long = 288; +pub const SYS_ioprio_set: ::c_long = 289; +pub const SYS_ioprio_get: ::c_long = 290; +pub const SYS_inotify_init: ::c_long = 291; +pub const SYS_inotify_add_watch: ::c_long = 292; +pub const SYS_inotify_rm_watch: ::c_long = 293; +pub const SYS_migrate_pages: ::c_long = 294; +pub const SYS_openat: ::c_long = 295; +pub const SYS_mkdirat: ::c_long = 296; +pub const SYS_mknodat: ::c_long = 297; +pub const SYS_fchownat: ::c_long = 298; +pub const SYS_futimesat: ::c_long = 299; +pub const SYS_fstatat64: ::c_long = 300; +pub const SYS_unlinkat: ::c_long = 301; +pub const SYS_renameat: ::c_long = 302; +pub const SYS_linkat: ::c_long = 303; +pub const SYS_symlinkat: ::c_long = 304; +pub const SYS_readlinkat: ::c_long = 305; +pub const SYS_fchmodat: ::c_long = 306; +pub const SYS_faccessat: ::c_long = 307; +pub const SYS_pselect6: ::c_long = 308; +pub const SYS_ppoll: ::c_long = 309; +pub const SYS_unshare: ::c_long = 310; +pub const SYS_set_robust_list: ::c_long = 311; +pub const SYS_get_robust_list: ::c_long = 312; +pub const SYS_splice: ::c_long = 313; +pub const SYS_sync_file_range: ::c_long = 314; +pub const SYS_tee: ::c_long = 315; +pub const SYS_vmsplice: ::c_long = 316; +pub const SYS_move_pages: ::c_long = 317; +pub const SYS_getcpu: ::c_long = 318; +pub const SYS_epoll_pwait: ::c_long = 319; +pub const SYS_utimensat: ::c_long = 320; +pub const SYS_signalfd: ::c_long = 321; +pub const SYS_timerfd_create: ::c_long = 322; +pub const SYS_eventfd: ::c_long = 323; +pub const SYS_fallocate: ::c_long = 324; +pub const SYS_timerfd_settime: ::c_long = 325; +pub const SYS_timerfd_gettime: ::c_long = 326; +pub const SYS_signalfd4: ::c_long = 327; +pub const SYS_eventfd2: ::c_long = 328; +pub const SYS_epoll_create1: ::c_long = 329; +pub const SYS_dup3: ::c_long = 330; +pub const SYS_pipe2: ::c_long = 331; +pub const SYS_inotify_init1: ::c_long = 332; +pub const SYS_preadv: ::c_long = 333; +pub const SYS_pwritev: ::c_long = 334; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 335; +pub const SYS_perf_event_open: ::c_long = 336; +pub const SYS_recvmmsg: ::c_long = 337; +pub const SYS_fanotify_init: ::c_long = 338; +pub const SYS_fanotify_mark: ::c_long = 339; +pub const SYS_prlimit64: ::c_long = 340; +pub const SYS_name_to_handle_at: ::c_long = 341; +pub const SYS_open_by_handle_at: ::c_long = 342; +pub const SYS_clock_adjtime: ::c_long = 343; +pub const SYS_syncfs: ::c_long = 344; +pub const SYS_sendmmsg: ::c_long = 345; +pub const SYS_setns: ::c_long = 346; +pub const SYS_process_vm_readv: ::c_long = 347; +pub const SYS_process_vm_writev: ::c_long = 348; +pub const SYS_kcmp: ::c_long = 349; +pub const SYS_finit_module: ::c_long = 350; +pub const SYS_sched_setattr: ::c_long = 351; +pub const SYS_sched_getattr: ::c_long = 352; +pub const SYS_renameat2: ::c_long = 353; +pub const SYS_seccomp: ::c_long = 354; +pub const SYS_getrandom: ::c_long = 355; +pub const SYS_memfd_create: ::c_long = 356; +pub const SYS_bpf: ::c_long = 357; +pub const SYS_execveat: ::c_long = 358; +pub const SYS_socket: ::c_long = 359; +pub const SYS_socketpair: ::c_long = 360; +pub const SYS_bind: ::c_long = 361; +pub const SYS_connect: ::c_long = 362; +pub const SYS_listen: ::c_long = 363; +pub const SYS_accept4: ::c_long = 364; +pub const SYS_getsockopt: ::c_long = 365; +pub const SYS_setsockopt: ::c_long = 366; +pub const SYS_getsockname: ::c_long = 367; +pub const SYS_getpeername: ::c_long = 368; +pub const SYS_sendto: ::c_long = 369; +pub const SYS_sendmsg: ::c_long = 370; +pub const SYS_recvfrom: ::c_long = 371; +pub const SYS_recvmsg: ::c_long = 372; +pub const SYS_shutdown: ::c_long = 373; +pub const SYS_userfaultfd: ::c_long = 374; +pub const SYS_membarrier: ::c_long = 375; +pub const SYS_mlock2: ::c_long = 376; +pub const SYS_copy_file_range: ::c_long = 377; +pub const SYS_preadv2: ::c_long = 378; +pub const SYS_pwritev2: ::c_long = 379; +pub const SYS_pkey_mprotect: ::c_long = 380; +pub const SYS_pkey_alloc: ::c_long = 381; +pub const SYS_pkey_free: ::c_long = 382; + +// offsets in user_regs_structs, from sys/reg.h +pub const EBX: ::c_int = 0; +pub const ECX: ::c_int = 1; +pub const EDX: ::c_int = 2; +pub const ESI: ::c_int = 3; +pub const EDI: ::c_int = 4; +pub const EBP: ::c_int = 5; +pub const EAX: ::c_int = 6; +pub const DS: ::c_int = 7; +pub const ES: ::c_int = 8; +pub const FS: ::c_int = 9; +pub const GS: ::c_int = 10; +pub const ORIG_EAX: ::c_int = 11; +pub const EIP: ::c_int = 12; +pub const CS: ::c_int = 13; +pub const EFL: ::c_int = 14; +pub const UESP: ::c_int = 15; +pub const SS: ::c_int = 16; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/b64/aarch64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/b64/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/b64/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/b64/aarch64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,325 @@ +pub type c_char = u8; +pub type wchar_t = u32; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::c_uint, + pub st_nlink: ::c_uint, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad1: ::c_ulong, + pub st_size: ::off64_t, + pub st_blksize: ::c_int, + __pad2: ::c_int, + pub st_blocks: ::c_long, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_ulong, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_ulong, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_ulong, + __unused4: ::c_uint, + __unused5: ::c_uint, + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::c_uint, + pub st_nlink: ::c_uint, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad1: ::c_ulong, + pub st_size: ::off64_t, + pub st_blksize: ::c_int, + __pad2: ::c_int, + pub st_blocks: ::c_long, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_ulong, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_ulong, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_ulong, + __unused4: ::c_uint, + __unused5: ::c_uint, + } +} + +pub const O_DIRECT: ::c_int = 0x10000; +pub const O_DIRECTORY: ::c_int = 0x4000; +pub const O_NOFOLLOW: ::c_int = 0x8000; +pub const O_LARGEFILE: ::c_int = 0o400000; + +pub const SIGSTKSZ: ::size_t = 16384; +pub const MINSIGSTKSZ: ::size_t = 5120; + +pub const SYS_io_setup: ::c_long = 0; +pub const SYS_io_destroy: ::c_long = 1; +pub const SYS_io_submit: ::c_long = 2; +pub const SYS_io_cancel: ::c_long = 3; +pub const SYS_io_getevents: ::c_long = 4; +pub const SYS_setxattr: ::c_long = 5; +pub const SYS_lsetxattr: ::c_long = 6; +pub const SYS_fsetxattr: ::c_long = 7; +pub const SYS_getxattr: ::c_long = 8; +pub const SYS_lgetxattr: ::c_long = 9; +pub const SYS_fgetxattr: ::c_long = 10; +pub const SYS_listxattr: ::c_long = 11; +pub const SYS_llistxattr: ::c_long = 12; +pub const SYS_flistxattr: ::c_long = 13; +pub const SYS_removexattr: ::c_long = 14; +pub const SYS_lremovexattr: ::c_long = 15; +pub const SYS_fremovexattr: ::c_long = 16; +pub const SYS_getcwd: ::c_long = 17; +pub const SYS_lookup_dcookie: ::c_long = 18; +pub const SYS_eventfd2: ::c_long = 19; +pub const SYS_epoll_create1: ::c_long = 20; +pub const SYS_epoll_ctl: ::c_long = 21; +pub const SYS_epoll_pwait: ::c_long = 22; +pub const SYS_dup: ::c_long = 23; +pub const SYS_dup3: ::c_long = 24; +pub const SYS_inotify_init1: ::c_long = 26; +pub const SYS_inotify_add_watch: ::c_long = 27; +pub const SYS_inotify_rm_watch: ::c_long = 28; +pub const SYS_ioctl: ::c_long = 29; +pub const SYS_ioprio_set: ::c_long = 30; +pub const SYS_ioprio_get: ::c_long = 31; +pub const SYS_flock: ::c_long = 32; +pub const SYS_mknodat: ::c_long = 33; +pub const SYS_mkdirat: ::c_long = 34; +pub const SYS_unlinkat: ::c_long = 35; +pub const SYS_symlinkat: ::c_long = 36; +pub const SYS_linkat: ::c_long = 37; +pub const SYS_renameat: ::c_long = 38; +pub const SYS_umount2: ::c_long = 39; +pub const SYS_mount: ::c_long = 40; +pub const SYS_pivot_root: ::c_long = 41; +pub const SYS_nfsservctl: ::c_long = 42; +pub const SYS_fallocate: ::c_long = 47; +pub const SYS_faccessat: ::c_long = 48; +pub const SYS_chdir: ::c_long = 49; +pub const SYS_fchdir: ::c_long = 50; +pub const SYS_chroot: ::c_long = 51; +pub const SYS_fchmod: ::c_long = 52; +pub const SYS_fchmodat: ::c_long = 53; +pub const SYS_fchownat: ::c_long = 54; +pub const SYS_fchown: ::c_long = 55; +pub const SYS_openat: ::c_long = 56; +pub const SYS_close: ::c_long = 57; +pub const SYS_vhangup: ::c_long = 58; +pub const SYS_pipe2: ::c_long = 59; +pub const SYS_quotactl: ::c_long = 60; +pub const SYS_getdents64: ::c_long = 61; +pub const SYS_read: ::c_long = 63; +pub const SYS_write: ::c_long = 64; +pub const SYS_readv: ::c_long = 65; +pub const SYS_writev: ::c_long = 66; +pub const SYS_pread64: ::c_long = 67; +pub const SYS_pwrite64: ::c_long = 68; +pub const SYS_preadv: ::c_long = 69; +pub const SYS_pwritev: ::c_long = 70; +pub const SYS_pselect6: ::c_long = 72; +pub const SYS_ppoll: ::c_long = 73; +pub const SYS_signalfd4: ::c_long = 74; +pub const SYS_vmsplice: ::c_long = 75; +pub const SYS_splice: ::c_long = 76; +pub const SYS_tee: ::c_long = 77; +pub const SYS_readlinkat: ::c_long = 78; +pub const SYS_sync: ::c_long = 81; +pub const SYS_fsync: ::c_long = 82; +pub const SYS_fdatasync: ::c_long = 83; +pub const SYS_sync_file_range: ::c_long = 84; +pub const SYS_timerfd_create: ::c_long = 85; +pub const SYS_timerfd_settime: ::c_long = 86; +pub const SYS_timerfd_gettime: ::c_long = 87; +pub const SYS_utimensat: ::c_long = 88; +pub const SYS_acct: ::c_long = 89; +pub const SYS_capget: ::c_long = 90; +pub const SYS_capset: ::c_long = 91; +pub const SYS_personality: ::c_long = 92; +pub const SYS_exit: ::c_long = 93; +pub const SYS_exit_group: ::c_long = 94; +pub const SYS_waitid: ::c_long = 95; +pub const SYS_set_tid_address: ::c_long = 96; +pub const SYS_unshare: ::c_long = 97; +pub const SYS_futex: ::c_long = 98; +pub const SYS_set_robust_list: ::c_long = 99; +pub const SYS_get_robust_list: ::c_long = 100; +pub const SYS_nanosleep: ::c_long = 101; +pub const SYS_getitimer: ::c_long = 102; +pub const SYS_setitimer: ::c_long = 103; +pub const SYS_kexec_load: ::c_long = 104; +pub const SYS_init_module: ::c_long = 105; +pub const SYS_delete_module: ::c_long = 106; +pub const SYS_timer_create: ::c_long = 107; +pub const SYS_timer_gettime: ::c_long = 108; +pub const SYS_timer_getoverrun: ::c_long = 109; +pub const SYS_timer_settime: ::c_long = 110; +pub const SYS_timer_delete: ::c_long = 111; +pub const SYS_clock_settime: ::c_long = 112; +pub const SYS_clock_gettime: ::c_long = 113; +pub const SYS_clock_getres: ::c_long = 114; +pub const SYS_clock_nanosleep: ::c_long = 115; +pub const SYS_syslog: ::c_long = 116; +pub const SYS_ptrace: ::c_long = 117; +pub const SYS_sched_setparam: ::c_long = 118; +pub const SYS_sched_setscheduler: ::c_long = 119; +pub const SYS_sched_getscheduler: ::c_long = 120; +pub const SYS_sched_getparam: ::c_long = 121; +pub const SYS_sched_setaffinity: ::c_long = 122; +pub const SYS_sched_getaffinity: ::c_long = 123; +pub const SYS_sched_yield: ::c_long = 124; +pub const SYS_sched_get_priority_max: ::c_long = 125; +pub const SYS_sched_get_priority_min: ::c_long = 126; +pub const SYS_sched_rr_get_interval: ::c_long = 127; +pub const SYS_restart_syscall: ::c_long = 128; +pub const SYS_kill: ::c_long = 129; +pub const SYS_tkill: ::c_long = 130; +pub const SYS_tgkill: ::c_long = 131; +pub const SYS_sigaltstack: ::c_long = 132; +pub const SYS_rt_sigsuspend: ::c_long = 133; +pub const SYS_rt_sigaction: ::c_long = 134; +pub const SYS_rt_sigprocmask: ::c_long = 135; +pub const SYS_rt_sigpending: ::c_long = 136; +pub const SYS_rt_sigtimedwait: ::c_long = 137; +pub const SYS_rt_sigqueueinfo: ::c_long = 138; +pub const SYS_rt_sigreturn: ::c_long = 139; +pub const SYS_setpriority: ::c_long = 140; +pub const SYS_getpriority: ::c_long = 141; +pub const SYS_reboot: ::c_long = 142; +pub const SYS_setregid: ::c_long = 143; +pub const SYS_setgid: ::c_long = 144; +pub const SYS_setreuid: ::c_long = 145; +pub const SYS_setuid: ::c_long = 146; +pub const SYS_setresuid: ::c_long = 147; +pub const SYS_getresuid: ::c_long = 148; +pub const SYS_setresgid: ::c_long = 149; +pub const SYS_getresgid: ::c_long = 150; +pub const SYS_setfsuid: ::c_long = 151; +pub const SYS_setfsgid: ::c_long = 152; +pub const SYS_times: ::c_long = 153; +pub const SYS_setpgid: ::c_long = 154; +pub const SYS_getpgid: ::c_long = 155; +pub const SYS_getsid: ::c_long = 156; +pub const SYS_setsid: ::c_long = 157; +pub const SYS_getgroups: ::c_long = 158; +pub const SYS_setgroups: ::c_long = 159; +pub const SYS_uname: ::c_long = 160; +pub const SYS_sethostname: ::c_long = 161; +pub const SYS_setdomainname: ::c_long = 162; +pub const SYS_getrlimit: ::c_long = 163; +pub const SYS_setrlimit: ::c_long = 164; +pub const SYS_getrusage: ::c_long = 165; +pub const SYS_umask: ::c_long = 166; +pub const SYS_prctl: ::c_long = 167; +pub const SYS_getcpu: ::c_long = 168; +pub const SYS_gettimeofday: ::c_long = 169; +pub const SYS_settimeofday: ::c_long = 170; +pub const SYS_adjtimex: ::c_long = 171; +pub const SYS_getpid: ::c_long = 172; +pub const SYS_getppid: ::c_long = 173; +pub const SYS_getuid: ::c_long = 174; +pub const SYS_geteuid: ::c_long = 175; +pub const SYS_getgid: ::c_long = 176; +pub const SYS_getegid: ::c_long = 177; +pub const SYS_gettid: ::c_long = 178; +pub const SYS_sysinfo: ::c_long = 179; +pub const SYS_mq_open: ::c_long = 180; +pub const SYS_mq_unlink: ::c_long = 181; +pub const SYS_mq_timedsend: ::c_long = 182; +pub const SYS_mq_timedreceive: ::c_long = 183; +pub const SYS_mq_notify: ::c_long = 184; +pub const SYS_mq_getsetattr: ::c_long = 185; +pub const SYS_msgget: ::c_long = 186; +pub const SYS_msgctl: ::c_long = 187; +pub const SYS_msgrcv: ::c_long = 188; +pub const SYS_msgsnd: ::c_long = 189; +pub const SYS_semget: ::c_long = 190; +pub const SYS_semctl: ::c_long = 191; +pub const SYS_semtimedop: ::c_long = 192; +pub const SYS_semop: ::c_long = 193; +pub const SYS_shmget: ::c_long = 194; +pub const SYS_shmctl: ::c_long = 195; +pub const SYS_shmat: ::c_long = 196; +pub const SYS_shmdt: ::c_long = 197; +pub const SYS_socket: ::c_long = 198; +pub const SYS_socketpair: ::c_long = 199; +pub const SYS_bind: ::c_long = 200; +pub const SYS_listen: ::c_long = 201; +pub const SYS_accept: ::c_long = 202; +pub const SYS_connect: ::c_long = 203; +pub const SYS_getsockname: ::c_long = 204; +pub const SYS_getpeername: ::c_long = 205; +pub const SYS_sendto: ::c_long = 206; +pub const SYS_recvfrom: ::c_long = 207; +pub const SYS_setsockopt: ::c_long = 208; +pub const SYS_getsockopt: ::c_long = 209; +pub const SYS_shutdown: ::c_long = 210; +pub const SYS_sendmsg: ::c_long = 211; +pub const SYS_recvmsg: ::c_long = 212; +pub const SYS_readahead: ::c_long = 213; +pub const SYS_brk: ::c_long = 214; +pub const SYS_munmap: ::c_long = 215; +pub const SYS_mremap: ::c_long = 216; +pub const SYS_add_key: ::c_long = 217; +pub const SYS_request_key: ::c_long = 218; +pub const SYS_keyctl: ::c_long = 219; +pub const SYS_clone: ::c_long = 220; +pub const SYS_execve: ::c_long = 221; +pub const SYS_swapon: ::c_long = 224; +pub const SYS_swapoff: ::c_long = 225; +pub const SYS_mprotect: ::c_long = 226; +pub const SYS_msync: ::c_long = 227; +pub const SYS_mlock: ::c_long = 228; +pub const SYS_munlock: ::c_long = 229; +pub const SYS_mlockall: ::c_long = 230; +pub const SYS_munlockall: ::c_long = 231; +pub const SYS_mincore: ::c_long = 232; +pub const SYS_madvise: ::c_long = 233; +pub const SYS_remap_file_pages: ::c_long = 234; +pub const SYS_mbind: ::c_long = 235; +pub const SYS_get_mempolicy: ::c_long = 236; +pub const SYS_set_mempolicy: ::c_long = 237; +pub const SYS_migrate_pages: ::c_long = 238; +pub const SYS_move_pages: ::c_long = 239; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 240; +pub const SYS_perf_event_open: ::c_long = 241; +pub const SYS_accept4: ::c_long = 242; +pub const SYS_recvmmsg: ::c_long = 243; +pub const SYS_arch_specific_syscall: ::c_long = 244; +pub const SYS_wait4: ::c_long = 260; +pub const SYS_prlimit64: ::c_long = 261; +pub const SYS_fanotify_init: ::c_long = 262; +pub const SYS_fanotify_mark: ::c_long = 263; +pub const SYS_name_to_handle_at: ::c_long = 264; +pub const SYS_open_by_handle_at: ::c_long = 265; +pub const SYS_clock_adjtime: ::c_long = 266; +pub const SYS_syncfs: ::c_long = 267; +pub const SYS_setns: ::c_long = 268; +pub const SYS_sendmmsg: ::c_long = 269; +pub const SYS_process_vm_readv: ::c_long = 270; +pub const SYS_process_vm_writev: ::c_long = 271; +pub const SYS_kcmp: ::c_long = 272; +pub const SYS_finit_module: ::c_long = 273; +pub const SYS_sched_setattr: ::c_long = 274; +pub const SYS_sched_getattr: ::c_long = 275; +pub const SYS_renameat2: ::c_long = 276; +pub const SYS_seccomp: ::c_long = 277; +pub const SYS_getrandom: ::c_long = 278; +pub const SYS_memfd_create: ::c_long = 279; +pub const SYS_bpf: ::c_long = 280; +pub const SYS_execveat: ::c_long = 281; +pub const SYS_userfaultfd: ::c_long = 282; +pub const SYS_membarrier: ::c_long = 283; +pub const SYS_mlock2: ::c_long = 284; +pub const SYS_copy_file_range: ::c_long = 285; +pub const SYS_preadv2: ::c_long = 286; +pub const SYS_pwritev2: ::c_long = 287; +pub const SYS_pkey_mprotect: ::c_long = 288; +pub const SYS_pkey_alloc: ::c_long = 289; +pub const SYS_pkey_free: ::c_long = 290; +pub const SYS_syscalls: ::c_long = 291; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/b64/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/b64/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/b64/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/b64/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,192 @@ +// The following definitions are correct for aarch64 and x86_64, +// but may be wrong for mips64 + +pub type c_long = i64; +pub type c_ulong = u64; +pub type mode_t = u32; +pub type off64_t = i64; +pub type socklen_t = u32; + +s! { + pub struct sigset_t { + __val: [::c_ulong; 1], + } + + pub struct sigaction { + pub sa_flags: ::c_uint, + pub sa_sigaction: ::sighandler_t, + pub sa_mask: ::sigset_t, + pub sa_restorer: ::dox::Option, + } + + pub struct rlimit64 { + pub rlim_cur: ::c_ulonglong, + pub rlim_max: ::c_ulonglong, + } + + pub struct pthread_attr_t { + pub flags: ::uint32_t, + pub stack_base: *mut ::c_void, + pub stack_size: ::size_t, + pub guard_size: ::size_t, + pub sched_policy: ::int32_t, + pub sched_priority: ::int32_t, + __reserved: [::c_char; 16], + } + + pub struct pthread_mutex_t { + value: ::c_int, + __reserved: [::c_char; 36], + } + + pub struct pthread_cond_t { + value: ::c_int, + __reserved: [::c_char; 44], + } + + pub struct pthread_rwlock_t { + numLocks: ::c_int, + writerThreadId: ::c_int, + pendingReaders: ::c_int, + pendingWriters: ::c_int, + attr: i32, + __reserved: [::c_char; 36], + } + + pub struct passwd { + pub pw_name: *mut ::c_char, + pub pw_passwd: *mut ::c_char, + pub pw_uid: ::uid_t, + pub pw_gid: ::gid_t, + pub pw_gecos: *mut ::c_char, + pub pw_dir: *mut ::c_char, + pub pw_shell: *mut ::c_char, + } + + pub struct statfs { + pub f_type: ::uint64_t, + pub f_bsize: ::uint64_t, + pub f_blocks: ::uint64_t, + pub f_bfree: ::uint64_t, + pub f_bavail: ::uint64_t, + pub f_files: ::uint64_t, + pub f_ffree: ::uint64_t, + pub f_fsid: ::__fsid_t, + pub f_namelen: ::uint64_t, + pub f_frsize: ::uint64_t, + pub f_flags: ::uint64_t, + pub f_spare: [::uint64_t; 4], + } + + pub struct sysinfo { + pub uptime: ::c_long, + pub loads: [::c_ulong; 3], + pub totalram: ::c_ulong, + pub freeram: ::c_ulong, + pub sharedram: ::c_ulong, + pub bufferram: ::c_ulong, + pub totalswap: ::c_ulong, + pub freeswap: ::c_ulong, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: ::c_ulong, + pub freehigh: ::c_ulong, + pub mem_unit: ::c_uint, + pub _f: [::c_char; 0], + } + + pub struct statfs64 { + pub f_type: u64, + pub f_bsize: u64, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + f_fsid: [u32; 2], + pub f_namelen: u64, + pub f_frsize: u64, + pub f_flags: u64, + pub f_spare: [u64; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } +} + +pub const RTLD_GLOBAL: ::c_int = 0x00100; +pub const RTLD_NOW: ::c_int = 2; +pub const RTLD_DEFAULT: *mut ::c_void = 0i64 as *mut ::c_void; + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + value: 0, + __reserved: [0; 36], +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + value: 0, + __reserved: [0; 44], +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + numLocks: 0, + writerThreadId: 0, + pendingReaders: 0, + pendingWriters: 0, + attr: 0, + __reserved: [0; 36], +}; +pub const PTHREAD_STACK_MIN: ::size_t = 4096 * 4; +pub const CPU_SETSIZE: ::size_t = 1024; +pub const __CPU_BITS: ::size_t = 64; + +pub const UT_LINESIZE: usize = 32; +pub const UT_NAMESIZE: usize = 32; +pub const UT_HOSTSIZE: usize = 256; + +// Some weirdness in Android +extern { + // address_len should be socklen_t, but it is c_int! + pub fn bind(socket: ::c_int, address: *const ::sockaddr, + address_len: ::c_int) -> ::c_int; + + // the return type should be ::ssize_t, but it is c_int! + pub fn writev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::c_int; + + // the return type should be ::ssize_t, but it is c_int! + pub fn readv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::c_int; + + // the return type should be ::ssize_t, but it is c_int! + pub fn sendmsg(fd: ::c_int, + msg: *const ::msghdr, + flags: ::c_int) -> ::c_int; + + // the return type should be ::ssize_t, but it is c_int! + pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) -> ::c_int; +} + +cfg_if! { + if #[cfg(target_arch = "x86_64")] { + mod x86_64; + pub use self::x86_64::*; + } else if #[cfg(target_arch = "aarch64")] { + mod aarch64; + pub use self::aarch64::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/b64/x86_64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/b64/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/b64/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/b64/x86_64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,420 @@ +pub type c_char = i8; +pub type wchar_t = i32; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_nlink: ::c_ulong, + pub st_mode: ::c_uint, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + pub st_size: ::off64_t, + pub st_blksize: ::c_long, + pub st_blocks: ::c_long, + pub st_atime: ::c_ulong, + pub st_atime_nsec: ::c_ulong, + pub st_mtime: ::c_ulong, + pub st_mtime_nsec: ::c_ulong, + pub st_ctime: ::c_ulong, + pub st_ctime_nsec: ::c_ulong, + __unused: [::c_long; 3], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_nlink: ::c_ulong, + pub st_mode: ::c_uint, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + pub st_size: ::off64_t, + pub st_blksize: ::c_long, + pub st_blocks: ::c_long, + pub st_atime: ::c_ulong, + pub st_atime_nsec: ::c_ulong, + pub st_mtime: ::c_ulong, + pub st_mtime_nsec: ::c_ulong, + pub st_ctime: ::c_ulong, + pub st_ctime_nsec: ::c_ulong, + __unused: [::c_long; 3], + } +} + +pub const O_DIRECT: ::c_int = 0x4000; +pub const O_DIRECTORY: ::c_int = 0x10000; +pub const O_NOFOLLOW: ::c_int = 0x20000; +pub const O_LARGEFILE: ::c_int = 0o0100000; + +pub const SIGSTKSZ: ::size_t = 8192; +pub const MINSIGSTKSZ: ::size_t = 2048; + +pub const MAP_32BIT: ::c_int = 0x40; + +// Syscall table + +pub const SYS_read: ::c_long = 0; +pub const SYS_write: ::c_long = 1; +pub const SYS_open: ::c_long = 2; +pub const SYS_close: ::c_long = 3; +pub const SYS_stat: ::c_long = 4; +pub const SYS_fstat: ::c_long = 5; +pub const SYS_lstat: ::c_long = 6; +pub const SYS_poll: ::c_long = 7; +pub const SYS_lseek: ::c_long = 8; +pub const SYS_mmap: ::c_long = 9; +pub const SYS_mprotect: ::c_long = 10; +pub const SYS_munmap: ::c_long = 11; +pub const SYS_brk: ::c_long = 12; +pub const SYS_rt_sigaction: ::c_long = 13; +pub const SYS_rt_sigprocmask: ::c_long = 14; +pub const SYS_rt_sigreturn: ::c_long = 15; +pub const SYS_ioctl: ::c_long = 16; +pub const SYS_pread64: ::c_long = 17; +pub const SYS_pwrite64: ::c_long = 18; +pub const SYS_readv: ::c_long = 19; +pub const SYS_writev: ::c_long = 20; +pub const SYS_access: ::c_long = 21; +pub const SYS_pipe: ::c_long = 22; +pub const SYS_select: ::c_long = 23; +pub const SYS_sched_yield: ::c_long = 24; +pub const SYS_mremap: ::c_long = 25; +pub const SYS_msync: ::c_long = 26; +pub const SYS_mincore: ::c_long = 27; +pub const SYS_madvise: ::c_long = 28; +pub const SYS_shmget: ::c_long = 29; +pub const SYS_shmat: ::c_long = 30; +pub const SYS_shmctl: ::c_long = 31; +pub const SYS_dup: ::c_long = 32; +pub const SYS_dup2: ::c_long = 33; +pub const SYS_pause: ::c_long = 34; +pub const SYS_nanosleep: ::c_long = 35; +pub const SYS_getitimer: ::c_long = 36; +pub const SYS_alarm: ::c_long = 37; +pub const SYS_setitimer: ::c_long = 38; +pub const SYS_getpid: ::c_long = 39; +pub const SYS_sendfile: ::c_long = 40; +pub const SYS_socket: ::c_long = 41; +pub const SYS_connect: ::c_long = 42; +pub const SYS_accept: ::c_long = 43; +pub const SYS_sendto: ::c_long = 44; +pub const SYS_recvfrom: ::c_long = 45; +pub const SYS_sendmsg: ::c_long = 46; +pub const SYS_recvmsg: ::c_long = 47; +pub const SYS_shutdown: ::c_long = 48; +pub const SYS_bind: ::c_long = 49; +pub const SYS_listen: ::c_long = 50; +pub const SYS_getsockname: ::c_long = 51; +pub const SYS_getpeername: ::c_long = 52; +pub const SYS_socketpair: ::c_long = 53; +pub const SYS_setsockopt: ::c_long = 54; +pub const SYS_getsockopt: ::c_long = 55; +pub const SYS_clone: ::c_long = 56; +pub const SYS_fork: ::c_long = 57; +pub const SYS_vfork: ::c_long = 58; +pub const SYS_execve: ::c_long = 59; +pub const SYS_exit: ::c_long = 60; +pub const SYS_wait4: ::c_long = 61; +pub const SYS_kill: ::c_long = 62; +pub const SYS_uname: ::c_long = 63; +pub const SYS_semget: ::c_long = 64; +pub const SYS_semop: ::c_long = 65; +pub const SYS_semctl: ::c_long = 66; +pub const SYS_shmdt: ::c_long = 67; +pub const SYS_msgget: ::c_long = 68; +pub const SYS_msgsnd: ::c_long = 69; +pub const SYS_msgrcv: ::c_long = 70; +pub const SYS_msgctl: ::c_long = 71; +pub const SYS_fcntl: ::c_long = 72; +pub const SYS_flock: ::c_long = 73; +pub const SYS_fsync: ::c_long = 74; +pub const SYS_fdatasync: ::c_long = 75; +pub const SYS_truncate: ::c_long = 76; +pub const SYS_ftruncate: ::c_long = 77; +pub const SYS_getdents: ::c_long = 78; +pub const SYS_getcwd: ::c_long = 79; +pub const SYS_chdir: ::c_long = 80; +pub const SYS_fchdir: ::c_long = 81; +pub const SYS_rename: ::c_long = 82; +pub const SYS_mkdir: ::c_long = 83; +pub const SYS_rmdir: ::c_long = 84; +pub const SYS_creat: ::c_long = 85; +pub const SYS_link: ::c_long = 86; +pub const SYS_unlink: ::c_long = 87; +pub const SYS_symlink: ::c_long = 88; +pub const SYS_readlink: ::c_long = 89; +pub const SYS_chmod: ::c_long = 90; +pub const SYS_fchmod: ::c_long = 91; +pub const SYS_chown: ::c_long = 92; +pub const SYS_fchown: ::c_long = 93; +pub const SYS_lchown: ::c_long = 94; +pub const SYS_umask: ::c_long = 95; +pub const SYS_gettimeofday: ::c_long = 96; +pub const SYS_getrlimit: ::c_long = 97; +pub const SYS_getrusage: ::c_long = 98; +pub const SYS_sysinfo: ::c_long = 99; +pub const SYS_times: ::c_long = 100; +pub const SYS_ptrace: ::c_long = 101; +pub const SYS_getuid: ::c_long = 102; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_getgid: ::c_long = 104; +pub const SYS_setuid: ::c_long = 105; +pub const SYS_setgid: ::c_long = 106; +pub const SYS_geteuid: ::c_long = 107; +pub const SYS_getegid: ::c_long = 108; +pub const SYS_setpgid: ::c_long = 109; +pub const SYS_getppid: ::c_long = 110; +pub const SYS_getpgrp: ::c_long = 111; +pub const SYS_setsid: ::c_long = 112; +pub const SYS_setreuid: ::c_long = 113; +pub const SYS_setregid: ::c_long = 114; +pub const SYS_getgroups: ::c_long = 115; +pub const SYS_setgroups: ::c_long = 116; +pub const SYS_setresuid: ::c_long = 117; +pub const SYS_getresuid: ::c_long = 118; +pub const SYS_setresgid: ::c_long = 119; +pub const SYS_getresgid: ::c_long = 120; +pub const SYS_getpgid: ::c_long = 121; +pub const SYS_setfsuid: ::c_long = 122; +pub const SYS_setfsgid: ::c_long = 123; +pub const SYS_getsid: ::c_long = 124; +pub const SYS_capget: ::c_long = 125; +pub const SYS_capset: ::c_long = 126; +pub const SYS_rt_sigpending: ::c_long = 127; +pub const SYS_rt_sigtimedwait: ::c_long = 128; +pub const SYS_rt_sigqueueinfo: ::c_long = 129; +pub const SYS_rt_sigsuspend: ::c_long = 130; +pub const SYS_sigaltstack: ::c_long = 131; +pub const SYS_utime: ::c_long = 132; +pub const SYS_mknod: ::c_long = 133; +pub const SYS_uselib: ::c_long = 134; +pub const SYS_personality: ::c_long = 135; +pub const SYS_ustat: ::c_long = 136; +pub const SYS_statfs: ::c_long = 137; +pub const SYS_fstatfs: ::c_long = 138; +pub const SYS_sysfs: ::c_long = 139; +pub const SYS_getpriority: ::c_long = 140; +pub const SYS_setpriority: ::c_long = 141; +pub const SYS_sched_setparam: ::c_long = 142; +pub const SYS_sched_getparam: ::c_long = 143; +pub const SYS_sched_setscheduler: ::c_long = 144; +pub const SYS_sched_getscheduler: ::c_long = 145; +pub const SYS_sched_get_priority_max: ::c_long = 146; +pub const SYS_sched_get_priority_min: ::c_long = 147; +pub const SYS_sched_rr_get_interval: ::c_long = 148; +pub const SYS_mlock: ::c_long = 149; +pub const SYS_munlock: ::c_long = 150; +pub const SYS_mlockall: ::c_long = 151; +pub const SYS_munlockall: ::c_long = 152; +pub const SYS_vhangup: ::c_long = 153; +pub const SYS_modify_ldt: ::c_long = 154; +pub const SYS_pivot_root: ::c_long = 155; +// FIXME: SYS__sysctl is in the NDK sources but for some reason is +// not available in the tests +// pub const SYS__sysctl: ::c_long = 156; +pub const SYS_prctl: ::c_long = 157; +pub const SYS_arch_prctl: ::c_long = 158; +pub const SYS_adjtimex: ::c_long = 159; +pub const SYS_setrlimit: ::c_long = 160; +pub const SYS_chroot: ::c_long = 161; +pub const SYS_sync: ::c_long = 162; +pub const SYS_acct: ::c_long = 163; +pub const SYS_settimeofday: ::c_long = 164; +pub const SYS_mount: ::c_long = 165; +pub const SYS_umount2: ::c_long = 166; +pub const SYS_swapon: ::c_long = 167; +pub const SYS_swapoff: ::c_long = 168; +pub const SYS_reboot: ::c_long = 169; +pub const SYS_sethostname: ::c_long = 170; +pub const SYS_setdomainname: ::c_long = 171; +pub const SYS_iopl: ::c_long = 172; +pub const SYS_ioperm: ::c_long = 173; +pub const SYS_create_module: ::c_long = 174; +pub const SYS_init_module: ::c_long = 175; +pub const SYS_delete_module: ::c_long = 176; +pub const SYS_get_kernel_syms: ::c_long = 177; +pub const SYS_query_module: ::c_long = 178; +pub const SYS_quotactl: ::c_long = 179; +pub const SYS_nfsservctl: ::c_long = 180; +pub const SYS_getpmsg: ::c_long = 181; +pub const SYS_putpmsg: ::c_long = 182; +pub const SYS_afs_syscall: ::c_long = 183; +pub const SYS_tuxcall: ::c_long = 184; +pub const SYS_security: ::c_long = 185; +pub const SYS_gettid: ::c_long = 186; +pub const SYS_readahead: ::c_long = 187; +pub const SYS_setxattr: ::c_long = 188; +pub const SYS_lsetxattr: ::c_long = 189; +pub const SYS_fsetxattr: ::c_long = 190; +pub const SYS_getxattr: ::c_long = 191; +pub const SYS_lgetxattr: ::c_long = 192; +pub const SYS_fgetxattr: ::c_long = 193; +pub const SYS_listxattr: ::c_long = 194; +pub const SYS_llistxattr: ::c_long = 195; +pub const SYS_flistxattr: ::c_long = 196; +pub const SYS_removexattr: ::c_long = 197; +pub const SYS_lremovexattr: ::c_long = 198; +pub const SYS_fremovexattr: ::c_long = 199; +pub const SYS_tkill: ::c_long = 200; +pub const SYS_time: ::c_long = 201; +pub const SYS_futex: ::c_long = 202; +pub const SYS_sched_setaffinity: ::c_long = 203; +pub const SYS_sched_getaffinity: ::c_long = 204; +pub const SYS_set_thread_area: ::c_long = 205; +pub const SYS_io_setup: ::c_long = 206; +pub const SYS_io_destroy: ::c_long = 207; +pub const SYS_io_getevents: ::c_long = 208; +pub const SYS_io_submit: ::c_long = 209; +pub const SYS_io_cancel: ::c_long = 210; +pub const SYS_get_thread_area: ::c_long = 211; +pub const SYS_lookup_dcookie: ::c_long = 212; +pub const SYS_epoll_create: ::c_long = 213; +pub const SYS_epoll_ctl_old: ::c_long = 214; +pub const SYS_epoll_wait_old: ::c_long = 215; +pub const SYS_remap_file_pages: ::c_long = 216; +pub const SYS_getdents64: ::c_long = 217; +pub const SYS_set_tid_address: ::c_long = 218; +pub const SYS_restart_syscall: ::c_long = 219; +pub const SYS_semtimedop: ::c_long = 220; +pub const SYS_fadvise64: ::c_long = 221; +pub const SYS_timer_create: ::c_long = 222; +pub const SYS_timer_settime: ::c_long = 223; +pub const SYS_timer_gettime: ::c_long = 224; +pub const SYS_timer_getoverrun: ::c_long = 225; +pub const SYS_timer_delete: ::c_long = 226; +pub const SYS_clock_settime: ::c_long = 227; +pub const SYS_clock_gettime: ::c_long = 228; +pub const SYS_clock_getres: ::c_long = 229; +pub const SYS_clock_nanosleep: ::c_long = 230; +pub const SYS_exit_group: ::c_long = 231; +pub const SYS_epoll_wait: ::c_long = 232; +pub const SYS_epoll_ctl: ::c_long = 233; +pub const SYS_tgkill: ::c_long = 234; +pub const SYS_utimes: ::c_long = 235; +pub const SYS_vserver: ::c_long = 236; +pub const SYS_mbind: ::c_long = 237; +pub const SYS_set_mempolicy: ::c_long = 238; +pub const SYS_get_mempolicy: ::c_long = 239; +pub const SYS_mq_open: ::c_long = 240; +pub const SYS_mq_unlink: ::c_long = 241; +pub const SYS_mq_timedsend: ::c_long = 242; +pub const SYS_mq_timedreceive: ::c_long = 243; +pub const SYS_mq_notify: ::c_long = 244; +pub const SYS_mq_getsetattr: ::c_long = 245; +pub const SYS_kexec_load: ::c_long = 246; +pub const SYS_waitid: ::c_long = 247; +pub const SYS_add_key: ::c_long = 248; +pub const SYS_request_key: ::c_long = 249; +pub const SYS_keyctl: ::c_long = 250; +pub const SYS_ioprio_set: ::c_long = 251; +pub const SYS_ioprio_get: ::c_long = 252; +pub const SYS_inotify_init: ::c_long = 253; +pub const SYS_inotify_add_watch: ::c_long = 254; +pub const SYS_inotify_rm_watch: ::c_long = 255; +pub const SYS_migrate_pages: ::c_long = 256; +pub const SYS_openat: ::c_long = 257; +pub const SYS_mkdirat: ::c_long = 258; +pub const SYS_mknodat: ::c_long = 259; +pub const SYS_fchownat: ::c_long = 260; +pub const SYS_futimesat: ::c_long = 261; +pub const SYS_newfstatat: ::c_long = 262; +pub const SYS_unlinkat: ::c_long = 263; +pub const SYS_renameat: ::c_long = 264; +pub const SYS_linkat: ::c_long = 265; +pub const SYS_symlinkat: ::c_long = 266; +pub const SYS_readlinkat: ::c_long = 267; +pub const SYS_fchmodat: ::c_long = 268; +pub const SYS_faccessat: ::c_long = 269; +pub const SYS_pselect6: ::c_long = 270; +pub const SYS_ppoll: ::c_long = 271; +pub const SYS_unshare: ::c_long = 272; +pub const SYS_set_robust_list: ::c_long = 273; +pub const SYS_get_robust_list: ::c_long = 274; +pub const SYS_splice: ::c_long = 275; +pub const SYS_tee: ::c_long = 276; +pub const SYS_sync_file_range: ::c_long = 277; +pub const SYS_vmsplice: ::c_long = 278; +pub const SYS_move_pages: ::c_long = 279; +pub const SYS_utimensat: ::c_long = 280; +pub const SYS_epoll_pwait: ::c_long = 281; +pub const SYS_signalfd: ::c_long = 282; +pub const SYS_timerfd_create: ::c_long = 283; +pub const SYS_eventfd: ::c_long = 284; +pub const SYS_fallocate: ::c_long = 285; +pub const SYS_timerfd_settime: ::c_long = 286; +pub const SYS_timerfd_gettime: ::c_long = 287; +pub const SYS_accept4: ::c_long = 288; +pub const SYS_signalfd4: ::c_long = 289; +pub const SYS_eventfd2: ::c_long = 290; +pub const SYS_epoll_create1: ::c_long = 291; +pub const SYS_dup3: ::c_long = 292; +pub const SYS_pipe2: ::c_long = 293; +pub const SYS_inotify_init1: ::c_long = 294; +pub const SYS_preadv: ::c_long = 295; +pub const SYS_pwritev: ::c_long = 296; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 297; +pub const SYS_perf_event_open: ::c_long = 298; +pub const SYS_recvmmsg: ::c_long = 299; +pub const SYS_fanotify_init: ::c_long = 300; +pub const SYS_fanotify_mark: ::c_long = 301; +pub const SYS_prlimit64: ::c_long = 302; +pub const SYS_name_to_handle_at: ::c_long = 303; +pub const SYS_open_by_handle_at: ::c_long = 304; +pub const SYS_clock_adjtime: ::c_long = 305; +pub const SYS_syncfs: ::c_long = 306; +pub const SYS_sendmmsg: ::c_long = 307; +pub const SYS_setns: ::c_long = 308; +pub const SYS_getcpu: ::c_long = 309; +pub const SYS_process_vm_readv: ::c_long = 310; +pub const SYS_process_vm_writev: ::c_long = 311; +pub const SYS_kcmp: ::c_long = 312; +pub const SYS_finit_module: ::c_long = 313; +pub const SYS_sched_setattr: ::c_long = 314; +pub const SYS_sched_getattr: ::c_long = 315; +pub const SYS_renameat2: ::c_long = 316; +pub const SYS_seccomp: ::c_long = 317; +pub const SYS_getrandom: ::c_long = 318; +pub const SYS_memfd_create: ::c_long = 319; +pub const SYS_kexec_file_load: ::c_long = 320; +pub const SYS_bpf: ::c_long = 321; +pub const SYS_execveat: ::c_long = 322; +pub const SYS_userfaultfd: ::c_long = 323; +pub const SYS_membarrier: ::c_long = 324; +pub const SYS_mlock2: ::c_long = 325; +pub const SYS_copy_file_range: ::c_long = 326; +pub const SYS_preadv2: ::c_long = 327; +pub const SYS_pwritev2: ::c_long = 328; +pub const SYS_pkey_mprotect: ::c_long = 329; +pub const SYS_pkey_alloc: ::c_long = 330; +pub const SYS_pkey_free: ::c_long = 331; + +// offsets in user_regs_structs, from sys/reg.h +pub const R15: ::c_int = 0; +pub const R14: ::c_int = 1; +pub const R13: ::c_int = 2; +pub const R12: ::c_int = 3; +pub const RBP: ::c_int = 4; +pub const RBX: ::c_int = 5; +pub const R11: ::c_int = 6; +pub const R10: ::c_int = 7; +pub const R9: ::c_int = 8; +pub const R8: ::c_int = 9; +pub const RAX: ::c_int = 10; +pub const RCX: ::c_int = 11; +pub const RDX: ::c_int = 12; +pub const RSI: ::c_int = 13; +pub const RDI: ::c_int = 14; +pub const ORIG_RAX: ::c_int = 15; +pub const RIP: ::c_int = 16; +pub const CS: ::c_int = 17; +pub const EFLAGS: ::c_int = 18; +pub const RSP: ::c_int = 19; +pub const SS: ::c_int = 20; +pub const FS_BASE: ::c_int = 21; +pub const GS_BASE: ::c_int = 22; +pub const DS: ::c_int = 23; +pub const ES: ::c_int = 24; +pub const FS: ::c_int = 25; +pub const GS: ::c_int = 26; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/android/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/android/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1631 @@ +//! Android-specific definitions for linux-like values + +use dox::{mem, Option}; + +pub type clock_t = ::c_long; +pub type time_t = ::c_long; +pub type suseconds_t = ::c_long; +pub type off_t = ::c_long; +pub type blkcnt_t = ::c_ulong; +pub type blksize_t = ::c_ulong; +pub type nlink_t = u32; +pub type useconds_t = u32; +pub type pthread_t = ::c_long; +pub type pthread_mutexattr_t = ::c_long; +pub type pthread_rwlockattr_t = ::c_long; +pub type pthread_condattr_t = ::c_long; +pub type fsfilcnt_t = ::c_ulong; +pub type fsblkcnt_t = ::c_ulong; +pub type nfds_t = ::c_uint; +pub type rlim_t = ::c_ulong; +pub type dev_t = ::c_ulong; +pub type ino_t = ::c_ulong; +pub type __CPU_BITTYPE = ::c_ulong; +pub type idtype_t = ::c_int; +pub type loff_t = ::c_longlong; + +s! { + pub struct dirent { + pub d_ino: u64, + pub d_off: i64, + pub d_reclen: ::c_ushort, + pub d_type: ::c_uchar, + pub d_name: [::c_char; 256], + } + + pub struct dirent64 { + pub d_ino: u64, + pub d_off: i64, + pub d_reclen: ::c_ushort, + pub d_type: ::c_uchar, + pub d_name: [::c_char; 256], + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_flags: ::c_int, + pub ss_size: ::size_t + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_errno: ::c_int, + pub si_code: ::c_int, + pub _pad: [::c_int; 29], + _align: [usize; 0], + } + + pub struct __fsid_t { + __val: [::c_int; 2], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::size_t, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::size_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::size_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; ::NCCS], + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 19], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } + + pub struct flock { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_pid: ::pid_t, + } + + pub struct cpu_set_t { + #[cfg(target_pointer_width = "64")] + __bits: [__CPU_BITTYPE; 16], + #[cfg(target_pointer_width = "32")] + __bits: [__CPU_BITTYPE; 1], + } + + pub struct sem_t { + count: ::c_uint, + #[cfg(target_pointer_width = "64")] + __reserved: [::c_int; 3], + } + + pub struct lastlog { + ll_time: ::time_t, + ll_line: [::c_char; UT_LINESIZE], + ll_host: [::c_char; UT_HOSTSIZE], + } + + pub struct exit_status { + pub e_termination: ::c_short, + pub e_exit: ::c_short, + } + + pub struct utmp { + pub ut_type: ::c_short, + pub ut_pid: ::pid_t, + pub ut_line: [::c_char; UT_LINESIZE], + pub ut_id: [::c_char; 4], + + pub ut_user: [::c_char; UT_NAMESIZE], + pub ut_host: [::c_char; UT_HOSTSIZE], + pub ut_exit: exit_status, + pub ut_session: ::c_long, + pub ut_tv: ::timeval, + + pub ut_addr_v6: [::int32_t; 4], + unused: [::c_char; 20], + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + #[cfg(target_pointer_width = "64")] + __f_reserved: [u32; 6], + } + + pub struct signalfd_siginfo { + pub ssi_signo: ::uint32_t, + pub ssi_errno: ::int32_t, + pub ssi_code: ::int32_t, + pub ssi_pid: ::uint32_t, + pub ssi_uid: ::uint32_t, + pub ssi_fd: ::int32_t, + pub ssi_tid: ::uint32_t, + pub ssi_band: ::uint32_t, + pub ssi_overrun: ::uint32_t, + pub ssi_trapno: ::uint32_t, + pub ssi_status: ::int32_t, + pub ssi_int: ::int32_t, + pub ssi_ptr: ::c_ulonglong, + pub ssi_utime: ::c_ulonglong, + pub ssi_stime: ::c_ulonglong, + pub ssi_addr: ::c_ulonglong, + pub ssi_addr_lsb: ::uint16_t, + _pad: [::uint8_t; 46], + } + + pub struct ucred { + pub pid: ::pid_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + } + + pub struct genlmsghdr { + cmd: u8, + version: u8, + reserved: u16, + } + + pub struct nlmsghdr { + nlmsg_len: u32, + nlmsg_type: u16, + nlmsg_flags: u16, + nlmsg_seq: u32, + nlmsg_pid: u32, + } + + pub struct nlmsgerr { + error: ::c_int, + msg: nlmsghdr, + } + + pub struct nl_pktinfo { + group: u32, + } + + pub struct nl_mmap_req { + nm_block_size: ::c_uint, + nm_block_nr: ::c_uint, + nm_frame_size: ::c_uint, + nm_frame_nr: ::c_uint, + } + + pub struct nl_mmap_hdr { + nm_status: ::c_uint, + nm_len: ::c_uint, + nm_group: u32, + nm_pid: u32, + nm_uid: u32, + nm_gid: u32, + } + + pub struct nlattr { + nla_len: u16, + nla_type: u16, + } +} + +pub const O_TRUNC: ::c_int = 512; +pub const O_CLOEXEC: ::c_int = 0x80000; +pub const O_PATH: ::c_int = 0o10000000; +pub const O_NOATIME: ::c_int = 0o1000000; + +pub const EBFONT: ::c_int = 59; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const EDOTDOT: ::c_int = 73; + +pub const SA_NODEFER: ::c_int = 0x40000000; +pub const SA_RESETHAND: ::c_int = 0x80000000; +pub const SA_RESTART: ::c_int = 0x10000000; +pub const SA_NOCLDSTOP: ::c_int = 0x00000001; + +pub const EPOLL_CLOEXEC: ::c_int = 0x80000; +pub const EPOLLONESHOT: ::c_int = 0x40000000; +pub const EPOLLRDHUP: ::c_int = 0x00002000; +pub const EPOLLWAKEUP: ::c_int = 0x20000000; + +pub const EFD_CLOEXEC: ::c_int = 0x80000; + +pub const USER_PROCESS: ::c_short = 7; + +pub const BUFSIZ: ::c_uint = 1024; +pub const FILENAME_MAX: ::c_uint = 1024; +pub const FOPEN_MAX: ::c_uint = 20; +pub const POSIX_FADV_DONTNEED: ::c_int = 4; +pub const POSIX_FADV_NOREUSE: ::c_int = 5; +pub const L_tmpnam: ::c_uint = 1024; +pub const TMP_MAX: ::c_uint = 308915776; +pub const _PC_LINK_MAX: ::c_int = 1; +pub const _PC_MAX_CANON: ::c_int = 2; +pub const _PC_MAX_INPUT: ::c_int = 3; +pub const _PC_NAME_MAX: ::c_int = 4; +pub const _PC_PATH_MAX: ::c_int = 5; +pub const _PC_PIPE_BUF: ::c_int = 6; +pub const _PC_2_SYMLINKS: ::c_int = 7; +pub const _PC_ALLOC_SIZE_MIN: ::c_int = 8; +pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 9; +pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 10; +pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 11; +pub const _PC_REC_XFER_ALIGN: ::c_int = 12; +pub const _PC_SYMLINK_MAX: ::c_int = 13; +pub const _PC_CHOWN_RESTRICTED: ::c_int = 14; +pub const _PC_NO_TRUNC: ::c_int = 15; +pub const _PC_VDISABLE: ::c_int = 16; +pub const _PC_ASYNC_IO: ::c_int = 17; +pub const _PC_PRIO_IO: ::c_int = 18; +pub const _PC_SYNC_IO: ::c_int = 19; + +pub const FIONBIO: ::c_int = 0x5421; + +pub const _SC_ARG_MAX: ::c_int = 0; +pub const _SC_BC_BASE_MAX: ::c_int = 1; +pub const _SC_BC_DIM_MAX: ::c_int = 2; +pub const _SC_BC_SCALE_MAX: ::c_int = 3; +pub const _SC_BC_STRING_MAX: ::c_int = 4; +pub const _SC_CHILD_MAX: ::c_int = 5; +pub const _SC_CLK_TCK: ::c_int = 6; +pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 7; +pub const _SC_EXPR_NEST_MAX: ::c_int = 8; +pub const _SC_LINE_MAX: ::c_int = 9; +pub const _SC_NGROUPS_MAX: ::c_int = 10; +pub const _SC_OPEN_MAX: ::c_int = 11; +pub const _SC_PASS_MAX: ::c_int = 12; +pub const _SC_2_C_BIND: ::c_int = 13; +pub const _SC_2_C_DEV: ::c_int = 14; +pub const _SC_2_C_VERSION: ::c_int = 15; +pub const _SC_2_CHAR_TERM: ::c_int = 16; +pub const _SC_2_FORT_DEV: ::c_int = 17; +pub const _SC_2_FORT_RUN: ::c_int = 18; +pub const _SC_2_LOCALEDEF: ::c_int = 19; +pub const _SC_2_SW_DEV: ::c_int = 20; +pub const _SC_2_UPE: ::c_int = 21; +pub const _SC_2_VERSION: ::c_int = 22; +pub const _SC_JOB_CONTROL: ::c_int = 23; +pub const _SC_SAVED_IDS: ::c_int = 24; +pub const _SC_VERSION: ::c_int = 25; +pub const _SC_RE_DUP_MAX: ::c_int = 26; +pub const _SC_STREAM_MAX: ::c_int = 27; +pub const _SC_TZNAME_MAX: ::c_int = 28; +pub const _SC_XOPEN_CRYPT: ::c_int = 29; +pub const _SC_XOPEN_ENH_I18N: ::c_int = 30; +pub const _SC_XOPEN_SHM: ::c_int = 31; +pub const _SC_XOPEN_VERSION: ::c_int = 32; +pub const _SC_XOPEN_XCU_VERSION: ::c_int = 33; +pub const _SC_XOPEN_REALTIME: ::c_int = 34; +pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 35; +pub const _SC_XOPEN_LEGACY: ::c_int = 36; +pub const _SC_ATEXIT_MAX: ::c_int = 37; +pub const _SC_IOV_MAX: ::c_int = 38; +pub const _SC_PAGESIZE: ::c_int = 39; +pub const _SC_PAGE_SIZE: ::c_int = 40; +pub const _SC_XOPEN_UNIX: ::c_int = 41; +pub const _SC_XBS5_ILP32_OFF32: ::c_int = 42; +pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 43; +pub const _SC_XBS5_LP64_OFF64: ::c_int = 44; +pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 45; +pub const _SC_AIO_LISTIO_MAX: ::c_int = 46; +pub const _SC_AIO_MAX: ::c_int = 47; +pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 48; +pub const _SC_DELAYTIMER_MAX: ::c_int = 49; +pub const _SC_MQ_OPEN_MAX: ::c_int = 50; +pub const _SC_MQ_PRIO_MAX: ::c_int = 51; +pub const _SC_RTSIG_MAX: ::c_int = 52; +pub const _SC_SEM_NSEMS_MAX: ::c_int = 53; +pub const _SC_SEM_VALUE_MAX: ::c_int = 54; +pub const _SC_SIGQUEUE_MAX: ::c_int = 55; +pub const _SC_TIMER_MAX: ::c_int = 56; +pub const _SC_ASYNCHRONOUS_IO: ::c_int = 57; +pub const _SC_FSYNC: ::c_int = 58; +pub const _SC_MAPPED_FILES: ::c_int = 59; +pub const _SC_MEMLOCK: ::c_int = 60; +pub const _SC_MEMLOCK_RANGE: ::c_int = 61; +pub const _SC_MEMORY_PROTECTION: ::c_int = 62; +pub const _SC_MESSAGE_PASSING: ::c_int = 63; +pub const _SC_PRIORITIZED_IO: ::c_int = 64; +pub const _SC_PRIORITY_SCHEDULING: ::c_int = 65; +pub const _SC_REALTIME_SIGNALS: ::c_int = 66; +pub const _SC_SEMAPHORES: ::c_int = 67; +pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 68; +pub const _SC_SYNCHRONIZED_IO: ::c_int = 69; +pub const _SC_TIMERS: ::c_int = 70; +pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 71; +pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 72; +pub const _SC_LOGIN_NAME_MAX: ::c_int = 73; +pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 74; +pub const _SC_THREAD_KEYS_MAX: ::c_int = 75; +pub const _SC_THREAD_STACK_MIN: ::c_int = 76; +pub const _SC_THREAD_THREADS_MAX: ::c_int = 77; +pub const _SC_TTY_NAME_MAX: ::c_int = 78; +pub const _SC_THREADS: ::c_int = 79; +pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 80; +pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 81; +pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 82; +pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 83; +pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 84; +pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 85; +pub const _SC_NPROCESSORS_CONF: ::c_int = 96; +pub const _SC_NPROCESSORS_ONLN: ::c_int = 97; +pub const _SC_PHYS_PAGES: ::c_int = 98; +pub const _SC_AVPHYS_PAGES: ::c_int = 99; +pub const _SC_MONOTONIC_CLOCK: ::c_int = 100; + +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; + +pub const FIOCLEX: ::c_int = 0x5451; + +pub const SA_ONSTACK: ::c_ulong = 0x08000000; +pub const SA_SIGINFO: ::c_ulong = 0x00000004; +pub const SA_NOCLDWAIT: ::c_ulong = 0x00000002; +pub const SIGCHLD: ::c_int = 17; +pub const SIGBUS: ::c_int = 7; +pub const SIGUSR1: ::c_int = 10; +pub const SIGUSR2: ::c_int = 12; +pub const SIGCONT: ::c_int = 18; +pub const SIGSTOP: ::c_int = 19; +pub const SIGTSTP: ::c_int = 20; +pub const SIGURG: ::c_int = 23; +pub const SIGIO: ::c_int = 29; +pub const SIGSYS: ::c_int = 31; +pub const SIGSTKFLT: ::c_int = 16; +pub const SIGUNUSED: ::c_int = 31; +pub const SIGTTIN: ::c_int = 21; +pub const SIGTTOU: ::c_int = 22; +pub const SIGXCPU: ::c_int = 24; +pub const SIGXFSZ: ::c_int = 25; +pub const SIGVTALRM: ::c_int = 26; +pub const SIGPROF: ::c_int = 27; +pub const SIGWINCH: ::c_int = 28; +pub const SIGPOLL: ::c_int = 29; +pub const SIGPWR: ::c_int = 30; +pub const SIG_SETMASK: ::c_int = 2; +pub const SIG_BLOCK: ::c_int = 0x000000; +pub const SIG_UNBLOCK: ::c_int = 0x01; + +pub const RUSAGE_CHILDREN: ::c_int = -1; + +pub const LC_PAPER: ::c_int = 7; +pub const LC_NAME: ::c_int = 8; +pub const LC_ADDRESS: ::c_int = 9; +pub const LC_TELEPHONE: ::c_int = 10; +pub const LC_MEASUREMENT: ::c_int = 11; +pub const LC_IDENTIFICATION: ::c_int = 12; +pub const LC_PAPER_MASK: ::c_int = (1 << LC_PAPER); +pub const LC_NAME_MASK: ::c_int = (1 << LC_NAME); +pub const LC_ADDRESS_MASK: ::c_int = (1 << LC_ADDRESS); +pub const LC_TELEPHONE_MASK: ::c_int = (1 << LC_TELEPHONE); +pub const LC_MEASUREMENT_MASK: ::c_int = (1 << LC_MEASUREMENT); +pub const LC_IDENTIFICATION_MASK: ::c_int = (1 << LC_IDENTIFICATION); +pub const LC_ALL_MASK: ::c_int = ::LC_CTYPE_MASK + | ::LC_NUMERIC_MASK + | ::LC_TIME_MASK + | ::LC_COLLATE_MASK + | ::LC_MONETARY_MASK + | ::LC_MESSAGES_MASK + | LC_PAPER_MASK + | LC_NAME_MASK + | LC_ADDRESS_MASK + | LC_TELEPHONE_MASK + | LC_MEASUREMENT_MASK + | LC_IDENTIFICATION_MASK; + +pub const MAP_ANON: ::c_int = 0x0020; +pub const MAP_ANONYMOUS: ::c_int = 0x0020; +pub const MAP_GROWSDOWN: ::c_int = 0x0100; +pub const MAP_DENYWRITE: ::c_int = 0x0800; +pub const MAP_EXECUTABLE: ::c_int = 0x01000; +pub const MAP_LOCKED: ::c_int = 0x02000; +pub const MAP_NORESERVE: ::c_int = 0x04000; +pub const MAP_POPULATE: ::c_int = 0x08000; +pub const MAP_NONBLOCK: ::c_int = 0x010000; +pub const MAP_STACK: ::c_int = 0x020000; + +pub const EDEADLK: ::c_int = 35; +pub const ENAMETOOLONG: ::c_int = 36; +pub const ENOLCK: ::c_int = 37; +pub const ENOSYS: ::c_int = 38; +pub const ENOTEMPTY: ::c_int = 39; +pub const ELOOP: ::c_int = 40; +pub const ENOMSG: ::c_int = 42; +pub const EIDRM: ::c_int = 43; +pub const ECHRNG: ::c_int = 44; +pub const EL2NSYNC: ::c_int = 45; +pub const EL3HLT: ::c_int = 46; +pub const EL3RST: ::c_int = 47; +pub const ELNRNG: ::c_int = 48; +pub const EUNATCH: ::c_int = 49; +pub const ENOCSI: ::c_int = 50; +pub const EL2HLT: ::c_int = 51; +pub const EBADE: ::c_int = 52; +pub const EBADR: ::c_int = 53; +pub const EXFULL: ::c_int = 54; +pub const ENOANO: ::c_int = 55; +pub const EBADRQC: ::c_int = 56; +pub const EBADSLT: ::c_int = 57; + +pub const EMULTIHOP: ::c_int = 72; +pub const EBADMSG: ::c_int = 74; +pub const EOVERFLOW: ::c_int = 75; +pub const ENOTUNIQ: ::c_int = 76; +pub const EBADFD: ::c_int = 77; +pub const EREMCHG: ::c_int = 78; +pub const ELIBACC: ::c_int = 79; +pub const ELIBBAD: ::c_int = 80; +pub const ELIBSCN: ::c_int = 81; +pub const ELIBMAX: ::c_int = 82; +pub const ELIBEXEC: ::c_int = 83; +pub const EILSEQ: ::c_int = 84; +pub const ERESTART: ::c_int = 85; +pub const ESTRPIPE: ::c_int = 86; +pub const EUSERS: ::c_int = 87; +pub const ENOTSOCK: ::c_int = 88; +pub const EDESTADDRREQ: ::c_int = 89; +pub const EMSGSIZE: ::c_int = 90; +pub const EPROTOTYPE: ::c_int = 91; +pub const ENOPROTOOPT: ::c_int = 92; +pub const EPROTONOSUPPORT: ::c_int = 93; +pub const ESOCKTNOSUPPORT: ::c_int = 94; +pub const EOPNOTSUPP: ::c_int = 95; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; +pub const EPFNOSUPPORT: ::c_int = 96; +pub const EAFNOSUPPORT: ::c_int = 97; +pub const EADDRINUSE: ::c_int = 98; +pub const EADDRNOTAVAIL: ::c_int = 99; +pub const ENETDOWN: ::c_int = 100; +pub const ENETUNREACH: ::c_int = 101; +pub const ENETRESET: ::c_int = 102; +pub const ECONNABORTED: ::c_int = 103; +pub const ECONNRESET: ::c_int = 104; +pub const ENOBUFS: ::c_int = 105; +pub const EISCONN: ::c_int = 106; +pub const ENOTCONN: ::c_int = 107; +pub const ESHUTDOWN: ::c_int = 108; +pub const ETOOMANYREFS: ::c_int = 109; +pub const ETIMEDOUT: ::c_int = 110; +pub const ECONNREFUSED: ::c_int = 111; +pub const EHOSTDOWN: ::c_int = 112; +pub const EHOSTUNREACH: ::c_int = 113; +pub const EALREADY: ::c_int = 114; +pub const EINPROGRESS: ::c_int = 115; +pub const ESTALE: ::c_int = 116; +pub const EUCLEAN: ::c_int = 117; +pub const ENOTNAM: ::c_int = 118; +pub const ENAVAIL: ::c_int = 119; +pub const EISNAM: ::c_int = 120; +pub const EREMOTEIO: ::c_int = 121; +pub const EDQUOT: ::c_int = 122; +pub const ENOMEDIUM: ::c_int = 123; +pub const EMEDIUMTYPE: ::c_int = 124; +pub const ECANCELED: ::c_int = 125; +pub const ENOKEY: ::c_int = 126; +pub const EKEYEXPIRED: ::c_int = 127; +pub const EKEYREVOKED: ::c_int = 128; +pub const EKEYREJECTED: ::c_int = 129; +pub const EOWNERDEAD: ::c_int = 130; +pub const ENOTRECOVERABLE: ::c_int = 131; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_SEQPACKET: ::c_int = 5; +pub const SOCK_DCCP: ::c_int = 6; +pub const SOCK_PACKET: ::c_int = 10; + +pub const SOL_SOCKET: ::c_int = 1; +pub const SOL_SCTP: ::c_int = 132; +pub const SOL_IPX: ::c_int = 256; +pub const SOL_AX25: ::c_int = 257; +pub const SOL_ATALK: ::c_int = 258; +pub const SOL_NETROM: ::c_int = 259; +pub const SOL_ROSE: ::c_int = 260; + +#[doc(hidden)] +pub const AF_MAX: ::c_int = 43; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; + +/* DCCP socket options */ +pub const DCCP_SOCKOPT_PACKET_SIZE: ::c_int = 1; +pub const DCCP_SOCKOPT_SERVICE: ::c_int = 2; +pub const DCCP_SOCKOPT_CHANGE_L: ::c_int = 3; +pub const DCCP_SOCKOPT_CHANGE_R: ::c_int = 4; +pub const DCCP_SOCKOPT_GET_CUR_MPS: ::c_int = 5; +pub const DCCP_SOCKOPT_SERVER_TIMEWAIT: ::c_int = 6; +pub const DCCP_SOCKOPT_SEND_CSCOV: ::c_int = 10; +pub const DCCP_SOCKOPT_RECV_CSCOV: ::c_int = 11; +pub const DCCP_SOCKOPT_AVAILABLE_CCIDS: ::c_int = 12; +pub const DCCP_SOCKOPT_CCID: ::c_int = 13; +pub const DCCP_SOCKOPT_TX_CCID: ::c_int = 14; +pub const DCCP_SOCKOPT_RX_CCID: ::c_int = 15; +pub const DCCP_SOCKOPT_QPOLICY_ID: ::c_int = 16; +pub const DCCP_SOCKOPT_QPOLICY_TXQLEN: ::c_int = 17; +pub const DCCP_SOCKOPT_CCID_RX_INFO: ::c_int = 128; +pub const DCCP_SOCKOPT_CCID_TX_INFO: ::c_int = 192; + +/// maximum number of services provided on the same listening port +pub const DCCP_SERVICE_LIST_MAX_LEN: ::c_int = 32; + +pub const SO_REUSEADDR: ::c_int = 2; +pub const SO_TYPE: ::c_int = 3; +pub const SO_ERROR: ::c_int = 4; +pub const SO_DONTROUTE: ::c_int = 5; +pub const SO_BROADCAST: ::c_int = 6; +pub const SO_SNDBUF: ::c_int = 7; +pub const SO_RCVBUF: ::c_int = 8; +pub const SO_KEEPALIVE: ::c_int = 9; +pub const SO_OOBINLINE: ::c_int = 10; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_LINGER: ::c_int = 13; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_REUSEPORT: ::c_int = 15; +pub const SO_PASSCRED: ::c_int = 16; +pub const SO_PEERCRED: ::c_int = 17; +pub const SO_RCVLOWAT: ::c_int = 18; +pub const SO_SNDLOWAT: ::c_int = 19; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_SNDTIMEO: ::c_int = 21; +pub const SO_BINDTODEVICE: ::c_int = 25; +pub const SO_TIMESTAMP: ::c_int = 29; +pub const SO_ACCEPTCONN: ::c_int = 30; +pub const SO_SNDBUFFORCE: ::c_int = 32; +pub const SO_RCVBUFFORCE: ::c_int = 33; +pub const SO_MARK: ::c_int = 36; +pub const SO_PROTOCOL: ::c_int = 38; +pub const SO_DOMAIN: ::c_int = 39; +pub const SO_RXQ_OVFL: ::c_int = 40; +pub const SO_PEEK_OFF: ::c_int = 42; +pub const SO_BUSY_POLL: ::c_int = 46; + +pub const O_ACCMODE: ::c_int = 3; +pub const O_APPEND: ::c_int = 1024; +pub const O_CREAT: ::c_int = 64; +pub const O_EXCL: ::c_int = 128; +pub const O_NOCTTY: ::c_int = 256; +pub const O_NONBLOCK: ::c_int = 2048; +pub const O_SYNC: ::c_int = 0x101000; +pub const O_ASYNC: ::c_int = 0x2000; +pub const O_NDELAY: ::c_int = 0x800; +pub const O_DSYNC: ::c_int = 4096; + +pub const NI_MAXHOST: ::size_t = 1025; + +pub const NCCS: usize = 19; +pub const TCSBRKP: ::c_int = 0x5425; +pub const TCSANOW: ::c_int = 0; +pub const TCSADRAIN: ::c_int = 0x1; +pub const TCSAFLUSH: ::c_int = 0x2; +pub const VEOF: usize = 4; +pub const VEOL: usize = 11; +pub const VEOL2: usize = 16; +pub const VMIN: usize = 6; +pub const IEXTEN: ::tcflag_t = 0x00008000; +pub const TOSTOP: ::tcflag_t = 0x00000100; +pub const FLUSHO: ::tcflag_t = 0x00001000; +pub const EXTPROC: ::tcflag_t = 0o200000; + +pub const ADFS_SUPER_MAGIC: ::c_long = 0x0000adf5; +pub const AFFS_SUPER_MAGIC: ::c_long = 0x0000adff; +pub const CODA_SUPER_MAGIC: ::c_long = 0x73757245; +pub const CRAMFS_MAGIC: ::c_long = 0x28cd3d45; +pub const EFS_SUPER_MAGIC: ::c_long = 0x00414a53; +pub const EXT2_SUPER_MAGIC: ::c_long = 0x0000ef53; +pub const EXT3_SUPER_MAGIC: ::c_long = 0x0000ef53; +pub const EXT4_SUPER_MAGIC: ::c_long = 0x0000ef53; +pub const HPFS_SUPER_MAGIC: ::c_long = 0xf995e849; +pub const HUGETLBFS_MAGIC: ::c_long = 0x958458f6; +pub const ISOFS_SUPER_MAGIC: ::c_long = 0x00009660; +pub const JFFS2_SUPER_MAGIC: ::c_long = 0x000072b6; +pub const MINIX_SUPER_MAGIC: ::c_long = 0x0000137f; +pub const MINIX_SUPER_MAGIC2: ::c_long = 0x0000138f; +pub const MINIX2_SUPER_MAGIC: ::c_long = 0x00002468; +pub const MINIX2_SUPER_MAGIC2: ::c_long = 0x00002478; +pub const MSDOS_SUPER_MAGIC: ::c_long = 0x00004d44; +pub const NCP_SUPER_MAGIC: ::c_long = 0x0000564c; +pub const NFS_SUPER_MAGIC: ::c_long = 0x00006969; +pub const OPENPROM_SUPER_MAGIC: ::c_long = 0x00009fa1; +pub const PROC_SUPER_MAGIC: ::c_long = 0x00009fa0; +pub const QNX4_SUPER_MAGIC: ::c_long = 0x0000002f; +pub const REISERFS_SUPER_MAGIC: ::c_long = 0x52654973; +pub const SMB_SUPER_MAGIC: ::c_long = 0x0000517b; +pub const TMPFS_MAGIC: ::c_long = 0x01021994; +pub const USBDEVICE_SUPER_MAGIC: ::c_long = 0x00009fa2; + +pub const MAP_HUGETLB: ::c_int = 0x040000; + +pub const PTRACE_TRACEME: ::c_int = 0; +pub const PTRACE_PEEKTEXT: ::c_int = 1; +pub const PTRACE_PEEKDATA: ::c_int = 2; +pub const PTRACE_PEEKUSER: ::c_int = 3; +pub const PTRACE_POKETEXT: ::c_int = 4; +pub const PTRACE_POKEDATA: ::c_int = 5; +pub const PTRACE_POKEUSER: ::c_int = 6; +pub const PTRACE_CONT: ::c_int = 7; +pub const PTRACE_KILL: ::c_int = 8; +pub const PTRACE_SINGLESTEP: ::c_int = 9; +pub const PTRACE_ATTACH: ::c_int = 16; +pub const PTRACE_DETACH: ::c_int = 17; +pub const PTRACE_SYSCALL: ::c_int = 24; +pub const PTRACE_SETOPTIONS: ::c_int = 0x4200; +pub const PTRACE_GETEVENTMSG: ::c_int = 0x4201; +pub const PTRACE_GETSIGINFO: ::c_int = 0x4202; +pub const PTRACE_SETSIGINFO: ::c_int = 0x4203; + +pub const EFD_NONBLOCK: ::c_int = 0x800; + +pub const F_GETLK: ::c_int = 5; +pub const F_GETOWN: ::c_int = 9; +pub const F_SETOWN: ::c_int = 8; +pub const F_SETLK: ::c_int = 6; +pub const F_SETLKW: ::c_int = 7; + +pub const TCGETS: ::c_int = 0x5401; +pub const TCSETS: ::c_int = 0x5402; +pub const TCSETSW: ::c_int = 0x5403; +pub const TCSETSF: ::c_int = 0x5404; +pub const TCGETA: ::c_int = 0x5405; +pub const TCSETA: ::c_int = 0x5406; +pub const TCSETAW: ::c_int = 0x5407; +pub const TCSETAF: ::c_int = 0x5408; +pub const TCSBRK: ::c_int = 0x5409; +pub const TCXONC: ::c_int = 0x540A; +pub const TCFLSH: ::c_int = 0x540B; +pub const TIOCGSOFTCAR: ::c_int = 0x5419; +pub const TIOCSSOFTCAR: ::c_int = 0x541A; +pub const TIOCINQ: ::c_int = 0x541B; +pub const TIOCLINUX: ::c_int = 0x541C; +pub const TIOCGSERIAL: ::c_int = 0x541E; +pub const TIOCEXCL: ::c_int = 0x540C; +pub const TIOCNXCL: ::c_int = 0x540D; +pub const TIOCSCTTY: ::c_int = 0x540E; +pub const TIOCGPGRP: ::c_int = 0x540F; +pub const TIOCSPGRP: ::c_int = 0x5410; +pub const TIOCOUTQ: ::c_int = 0x5411; +pub const TIOCSTI: ::c_int = 0x5412; +pub const TIOCGWINSZ: ::c_int = 0x5413; +pub const TIOCSWINSZ: ::c_int = 0x5414; +pub const TIOCMGET: ::c_int = 0x5415; +pub const TIOCMBIS: ::c_int = 0x5416; +pub const TIOCMBIC: ::c_int = 0x5417; +pub const TIOCMSET: ::c_int = 0x5418; +pub const FIONREAD: ::c_int = 0x541B; +pub const TIOCCONS: ::c_int = 0x541D; + +pub const ST_RDONLY: ::c_ulong = 1; +pub const ST_NOSUID: ::c_ulong = 2; +pub const ST_NODEV: ::c_ulong = 4; +pub const ST_NOEXEC: ::c_ulong = 8; +pub const ST_SYNCHRONOUS: ::c_ulong = 16; +pub const ST_MANDLOCK: ::c_ulong = 64; +pub const ST_NOATIME: ::c_ulong = 1024; +pub const ST_NODIRATIME: ::c_ulong = 2048; +pub const ST_RELATIME: ::c_ulong = 4096; + +pub const RTLD_NOLOAD: ::c_int = 0x4; + +pub const SEM_FAILED: *mut sem_t = 0 as *mut sem_t; + +pub const LINUX_REBOOT_MAGIC1: ::c_int = 0xfee1dead; +pub const LINUX_REBOOT_MAGIC2: ::c_int = 672274793; +pub const LINUX_REBOOT_MAGIC2A: ::c_int = 85072278; +pub const LINUX_REBOOT_MAGIC2B: ::c_int = 369367448; +pub const LINUX_REBOOT_MAGIC2C: ::c_int = 537993216; + +pub const LINUX_REBOOT_CMD_RESTART: ::c_int = 0x01234567; +pub const LINUX_REBOOT_CMD_HALT: ::c_int = 0xCDEF0123; +pub const LINUX_REBOOT_CMD_CAD_ON: ::c_int = 0x89ABCDEF; +pub const LINUX_REBOOT_CMD_CAD_OFF: ::c_int = 0x00000000; +pub const LINUX_REBOOT_CMD_POWER_OFF: ::c_int = 0x4321FEDC; +pub const LINUX_REBOOT_CMD_RESTART2: ::c_int = 0xA1B2C3D4; +pub const LINUX_REBOOT_CMD_SW_SUSPEND: ::c_int = 0xD000FCE2; +pub const LINUX_REBOOT_CMD_KEXEC: ::c_int = 0x45584543; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const CBAUD: ::tcflag_t = 0o0010017; +pub const TAB1: ::c_int = 0x00000800; +pub const TAB2: ::c_int = 0x00001000; +pub const TAB3: ::c_int = 0x00001800; +pub const CR1: ::c_int = 0x00000200; +pub const CR2: ::c_int = 0x00000400; +pub const CR3: ::c_int = 0x00000600; +pub const FF1: ::c_int = 0x00008000; +pub const BS1: ::c_int = 0x00002000; +pub const VT1: ::c_int = 0x00004000; +pub const VWERASE: usize = 14; +pub const VREPRINT: usize = 12; +pub const VSUSP: usize = 10; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VDISCARD: usize = 13; +pub const VTIME: usize = 5; +pub const IXON: ::tcflag_t = 0x00000400; +pub const IXOFF: ::tcflag_t = 0x00001000; +pub const ONLCR: ::tcflag_t = 0x4; +pub const CSIZE: ::tcflag_t = 0x00000030; +pub const CS6: ::tcflag_t = 0x00000010; +pub const CS7: ::tcflag_t = 0x00000020; +pub const CS8: ::tcflag_t = 0x00000030; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const ECHOKE: ::tcflag_t = 0x00000800; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const ECHOPRT: ::tcflag_t = 0x00000400; +pub const ECHOCTL: ::tcflag_t = 0x00000200; +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const PENDIN: ::tcflag_t = 0x00004000; +pub const NOFLSH: ::tcflag_t = 0x00000080; +pub const VSWTC: usize = 7; +pub const OLCUC: ::tcflag_t = 0o000002; +pub const NLDLY: ::tcflag_t = 0o000400; +pub const CRDLY: ::tcflag_t = 0o003000; +pub const TABDLY: ::tcflag_t = 0o014000; +pub const BSDLY: ::tcflag_t = 0o020000; +pub const FFDLY: ::tcflag_t = 0o100000; +pub const VTDLY: ::tcflag_t = 0o040000; +pub const XTABS: ::tcflag_t = 0o014000; + +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const BOTHER: ::speed_t = 0o010000; +pub const B57600: ::speed_t = 0o010001; +pub const B115200: ::speed_t = 0o010002; +pub const B230400: ::speed_t = 0o010003; +pub const B460800: ::speed_t = 0o010004; +pub const B500000: ::speed_t = 0o010005; +pub const B576000: ::speed_t = 0o010006; +pub const B921600: ::speed_t = 0o010007; +pub const B1000000: ::speed_t = 0o010010; +pub const B1152000: ::speed_t = 0o010011; +pub const B1500000: ::speed_t = 0o010012; +pub const B2000000: ::speed_t = 0o010013; +pub const B2500000: ::speed_t = 0o010014; +pub const B3000000: ::speed_t = 0o010015; +pub const B3500000: ::speed_t = 0o010016; +pub const B4000000: ::speed_t = 0o010017; + +pub const EAI_AGAIN: ::c_int = 2; +pub const EAI_BADFLAGS: ::c_int = 3; +pub const EAI_FAIL: ::c_int = 4; +pub const EAI_FAMILY: ::c_int = 5; +pub const EAI_MEMORY: ::c_int = 6; +pub const EAI_NODATA: ::c_int = 7; +pub const EAI_NONAME: ::c_int = 8; +pub const EAI_SERVICE: ::c_int = 9; +pub const EAI_SOCKTYPE: ::c_int = 10; +pub const EAI_SYSTEM: ::c_int = 11; +pub const EAI_OVERFLOW: ::c_int = 14; + +pub const NETLINK_ROUTE: ::c_int = 0; +pub const NETLINK_UNUSED: ::c_int = 1; +pub const NETLINK_USERSOCK: ::c_int = 2; +pub const NETLINK_FIREWALL: ::c_int = 3; +pub const NETLINK_SOCK_DIAG: ::c_int = 4; +pub const NETLINK_NFLOG: ::c_int = 5; +pub const NETLINK_XFRM: ::c_int = 6; +pub const NETLINK_SELINUX: ::c_int = 7; +pub const NETLINK_ISCSI: ::c_int = 8; +pub const NETLINK_AUDIT: ::c_int = 9; +pub const NETLINK_FIB_LOOKUP: ::c_int = 10; +pub const NETLINK_CONNECTOR: ::c_int = 11; +pub const NETLINK_NETFILTER: ::c_int = 12; +pub const NETLINK_IP6_FW: ::c_int = 13; +pub const NETLINK_DNRTMSG: ::c_int = 14; +pub const NETLINK_KOBJECT_UEVENT: ::c_int = 15; +pub const NETLINK_GENERIC: ::c_int = 16; +pub const NETLINK_SCSITRANSPORT: ::c_int = 18; +pub const NETLINK_ECRYPTFS: ::c_int = 19; +pub const NETLINK_RDMA: ::c_int = 20; +pub const NETLINK_CRYPTO: ::c_int = 21; +pub const NETLINK_INET_DIAG: ::c_int = NETLINK_SOCK_DIAG; + +pub const MAX_LINKS: ::c_int = 32; + +pub const NLM_F_REQUEST: ::c_int = 1; +pub const NLM_F_MULTI: ::c_int = 2; +pub const NLM_F_ACK: ::c_int = 4; +pub const NLM_F_ECHO: ::c_int = 8; +pub const NLM_F_DUMP_INTR: ::c_int = 16; + +pub const NLM_F_ROOT: ::c_int = 0x100; +pub const NLM_F_MATCH: ::c_int = 0x200; +pub const NLM_F_ATOMIC: ::c_int = 0x400; +pub const NLM_F_DUMP: ::c_int = NLM_F_ROOT | NLM_F_MATCH; + +pub const NLM_F_REPLACE: ::c_int = 0x100; +pub const NLM_F_EXCL: ::c_int = 0x200; +pub const NLM_F_CREATE: ::c_int = 0x400; +pub const NLM_F_APPEND: ::c_int = 0x800; + +pub const NLMSG_NOOP: ::c_int = 0x1; +pub const NLMSG_ERROR: ::c_int = 0x2; +pub const NLMSG_DONE: ::c_int = 0x3; +pub const NLMSG_OVERRUN: ::c_int = 0x4; +pub const NLMSG_MIN_TYPE: ::c_int = 0x10; + +pub const GENL_NAMSIZ: ::c_int = 16; + +pub const GENL_MIN_ID: ::c_int = NLMSG_MIN_TYPE; +pub const GENL_MAX_ID: ::c_int = 1023; + +pub const GENL_ADMIN_PERM: ::c_int = 0x01; +pub const GENL_CMD_CAP_DO: ::c_int = 0x02; +pub const GENL_CMD_CAP_DUMP: ::c_int = 0x04; +pub const GENL_CMD_CAP_HASPOL: ::c_int = 0x08; +pub const GENL_UNS_ADMIN_PERM: ::c_int = 0x10; + +pub const GENL_ID_CTRL: ::c_int = NLMSG_MIN_TYPE; +pub const GENL_ID_VFS_DQUOT: ::c_int = NLMSG_MIN_TYPE + 1; +pub const GENL_ID_PMCRAID: ::c_int = NLMSG_MIN_TYPE + 2; + +pub const CTRL_CMD_UNSPEC: ::c_int = 0; +pub const CTRL_CMD_NEWFAMILY: ::c_int = 1; +pub const CTRL_CMD_DELFAMILY: ::c_int = 2; +pub const CTRL_CMD_GETFAMILY: ::c_int = 3; +pub const CTRL_CMD_NEWOPS: ::c_int = 4; +pub const CTRL_CMD_DELOPS: ::c_int = 5; +pub const CTRL_CMD_GETOPS: ::c_int = 6; +pub const CTRL_CMD_NEWMCAST_GRP: ::c_int = 7; +pub const CTRL_CMD_DELMCAST_GRP: ::c_int = 8; +pub const CTRL_CMD_GETMCAST_GRP: ::c_int = 9; + +pub const CTRL_ATTR_UNSPEC: ::c_int = 0; +pub const CTRL_ATTR_FAMILY_ID: ::c_int = 1; +pub const CTRL_ATTR_FAMILY_NAME: ::c_int = 2; +pub const CTRL_ATTR_VERSION: ::c_int = 3; +pub const CTRL_ATTR_HDRSIZE: ::c_int = 4; +pub const CTRL_ATTR_MAXATTR: ::c_int = 5; +pub const CTRL_ATTR_OPS: ::c_int = 6; +pub const CTRL_ATTR_MCAST_GROUPS: ::c_int = 7; + +pub const CTRL_ATTR_OP_UNSPEC: ::c_int = 0; +pub const CTRL_ATTR_OP_ID: ::c_int = 1; +pub const CTRL_ATTR_OP_FLAGS: ::c_int = 2; + +pub const CTRL_ATTR_MCAST_GRP_UNSPEC: ::c_int = 0; +pub const CTRL_ATTR_MCAST_GRP_NAME: ::c_int = 1; +pub const CTRL_ATTR_MCAST_GRP_ID: ::c_int = 2; + +pub const NETLINK_ADD_MEMBERSHIP: ::c_int = 1; +pub const NETLINK_DROP_MEMBERSHIP: ::c_int = 2; +pub const NETLINK_PKTINFO: ::c_int = 3; +pub const NETLINK_BROADCAST_ERROR: ::c_int = 4; +pub const NETLINK_NO_ENOBUFS: ::c_int = 5; +pub const NETLINK_RX_RING: ::c_int = 6; +pub const NETLINK_TX_RING: ::c_int = 7; + +pub const GRND_NONBLOCK: ::c_uint = 0x0001; +pub const GRND_RANDOM: ::c_uint = 0x0002; + +pub const SECCOMP_MODE_DISABLED: ::c_uint = 0; +pub const SECCOMP_MODE_STRICT: ::c_uint = 1; +pub const SECCOMP_MODE_FILTER: ::c_uint = 2; + +pub const NLA_F_NESTED: ::c_int = 1 << 15; +pub const NLA_F_NET_BYTEORDER: ::c_int = 1 << 14; +pub const NLA_TYPE_MASK: ::c_int = !(NLA_F_NESTED | NLA_F_NET_BYTEORDER); + +pub const NLA_ALIGNTO: ::c_int = 4; + +pub const SIGEV_THREAD_ID: ::c_int = 4; + +pub const CIBAUD: ::tcflag_t = 0o02003600000; +pub const CBAUDEX: ::tcflag_t = 0o010000; + +pub const TIOCM_LE: ::c_int = 0x001; +pub const TIOCM_DTR: ::c_int = 0x002; +pub const TIOCM_RTS: ::c_int = 0x004; +pub const TIOCM_ST: ::c_int = 0x008; +pub const TIOCM_SR: ::c_int = 0x010; +pub const TIOCM_CTS: ::c_int = 0x020; +pub const TIOCM_CAR: ::c_int = 0x040; +pub const TIOCM_RNG: ::c_int = 0x080; +pub const TIOCM_DSR: ::c_int = 0x100; +pub const TIOCM_CD: ::c_int = TIOCM_CAR; +pub const TIOCM_RI: ::c_int = TIOCM_RNG; + +pub const POLLWRNORM: ::c_short = 0x100; +pub const POLLWRBAND: ::c_short = 0x200; + +pub const SFD_CLOEXEC: ::c_int = O_CLOEXEC; +pub const SFD_NONBLOCK: ::c_int = O_NONBLOCK; + +pub const SOCK_NONBLOCK: ::c_int = O_NONBLOCK; + +pub const SO_ORIGINAL_DST: ::c_int = 80; +pub const IUTF8: ::tcflag_t = 0x00004000; +pub const CMSPAR: ::tcflag_t = 0o10000000000; +pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; + +pub const MFD_CLOEXEC: ::c_uint = 0x0001; +pub const MFD_ALLOW_SEALING: ::c_uint = 0x0002; + +// linux/netfilter.h +pub const NF_DROP: ::c_int = 0; +pub const NF_ACCEPT: ::c_int = 1; +pub const NF_STOLEN: ::c_int = 2; +pub const NF_QUEUE: ::c_int = 3; +pub const NF_REPEAT: ::c_int = 4; +pub const NF_STOP: ::c_int = 5; +pub const NF_MAX_VERDICT: ::c_int = NF_STOP; + +pub const NF_VERDICT_MASK: ::c_int = 0x000000ff; +pub const NF_VERDICT_FLAG_QUEUE_BYPASS: ::c_int = 0x00008000; + +pub const NF_VERDICT_QMASK: ::c_int = 0xffff0000; +pub const NF_VERDICT_QBITS: ::c_int = 16; + +pub const NF_VERDICT_BITS: ::c_int = 16; + +pub const NF_INET_PRE_ROUTING: ::c_int = 0; +pub const NF_INET_LOCAL_IN: ::c_int = 1; +pub const NF_INET_FORWARD: ::c_int = 2; +pub const NF_INET_LOCAL_OUT: ::c_int = 3; +pub const NF_INET_POST_ROUTING: ::c_int = 4; +pub const NF_INET_NUMHOOKS: ::c_int = 5; + +pub const NF_NETDEV_INGRESS: ::c_int = 0; +pub const NF_NETDEV_NUMHOOKS: ::c_int = 1; + +pub const NFPROTO_UNSPEC: ::c_int = 0; +pub const NFPROTO_INET: ::c_int = 1; +pub const NFPROTO_IPV4: ::c_int = 2; +pub const NFPROTO_ARP: ::c_int = 3; +pub const NFPROTO_NETDEV: ::c_int = 5; +pub const NFPROTO_BRIDGE: ::c_int = 7; +pub const NFPROTO_IPV6: ::c_int = 10; +pub const NFPROTO_DECNET: ::c_int = 12; +pub const NFPROTO_NUMPROTO: ::c_int = 13; + +// linux/netfilter_ipv4.h +pub const NF_IP_PRE_ROUTING: ::c_int = 0; +pub const NF_IP_LOCAL_IN: ::c_int = 1; +pub const NF_IP_FORWARD: ::c_int = 2; +pub const NF_IP_LOCAL_OUT: ::c_int = 3; +pub const NF_IP_POST_ROUTING: ::c_int = 4; +pub const NF_IP_NUMHOOKS: ::c_int = 5; + +pub const NF_IP_PRI_FIRST: ::c_int = ::INT_MIN; +pub const NF_IP_PRI_CONNTRACK_DEFRAG: ::c_int = -400; +pub const NF_IP_PRI_RAW: ::c_int = -300; +pub const NF_IP_PRI_SELINUX_FIRST: ::c_int = -225; +pub const NF_IP_PRI_CONNTRACK: ::c_int = -200; +pub const NF_IP_PRI_MANGLE: ::c_int = -150; +pub const NF_IP_PRI_NAT_DST: ::c_int = -100; +pub const NF_IP_PRI_FILTER: ::c_int = 0; +pub const NF_IP_PRI_SECURITY: ::c_int = 50; +pub const NF_IP_PRI_NAT_SRC: ::c_int = 100; +pub const NF_IP_PRI_SELINUX_LAST: ::c_int = 225; +pub const NF_IP_PRI_CONNTRACK_HELPER: ::c_int = 300; +pub const NF_IP_PRI_CONNTRACK_CONFIRM: ::c_int = ::INT_MAX; +pub const NF_IP_PRI_LAST: ::c_int = ::INT_MAX; + +// linux/netfilter_ipv6.h +pub const NF_IP6_PRE_ROUTING: ::c_int = 0; +pub const NF_IP6_LOCAL_IN: ::c_int = 1; +pub const NF_IP6_FORWARD: ::c_int = 2; +pub const NF_IP6_LOCAL_OUT: ::c_int = 3; +pub const NF_IP6_POST_ROUTING: ::c_int = 4; +pub const NF_IP6_NUMHOOKS: ::c_int = 5; + +pub const NF_IP6_PRI_FIRST: ::c_int = ::INT_MIN; +pub const NF_IP6_PRI_CONNTRACK_DEFRAG: ::c_int = -400; +pub const NF_IP6_PRI_RAW: ::c_int = -300; +pub const NF_IP6_PRI_SELINUX_FIRST: ::c_int = -225; +pub const NF_IP6_PRI_CONNTRACK: ::c_int = -200; +pub const NF_IP6_PRI_MANGLE: ::c_int = -150; +pub const NF_IP6_PRI_NAT_DST: ::c_int = -100; +pub const NF_IP6_PRI_FILTER: ::c_int = 0; +pub const NF_IP6_PRI_SECURITY: ::c_int = 50; +pub const NF_IP6_PRI_NAT_SRC: ::c_int = 100; +pub const NF_IP6_PRI_SELINUX_LAST: ::c_int = 225; +pub const NF_IP6_PRI_CONNTRACK_HELPER: ::c_int = 300; +pub const NF_IP6_PRI_LAST: ::c_int = ::INT_MAX; + +// linux/netfilter/nf_tables.h +pub const NFT_TABLE_MAXNAMELEN: ::c_int = 32; +pub const NFT_CHAIN_MAXNAMELEN: ::c_int = 32; +pub const NFT_SET_MAXNAMELEN: ::c_int = 32; +pub const NFT_OBJ_MAXNAMELEN: ::c_int = 32; +pub const NFT_USERDATA_MAXLEN: ::c_int = 256; + +pub const NFT_REG_VERDICT: ::c_int = 0; +pub const NFT_REG_1: ::c_int = 1; +pub const NFT_REG_2: ::c_int = 2; +pub const NFT_REG_3: ::c_int = 3; +pub const NFT_REG_4: ::c_int = 4; +pub const __NFT_REG_MAX: ::c_int = 5; +pub const NFT_REG32_00: ::c_int = 8; +pub const NFT_REG32_01: ::c_int = 9; +pub const NFT_REG32_02: ::c_int = 10; +pub const NFT_REG32_03: ::c_int = 11; +pub const NFT_REG32_04: ::c_int = 12; +pub const NFT_REG32_05: ::c_int = 13; +pub const NFT_REG32_06: ::c_int = 14; +pub const NFT_REG32_07: ::c_int = 15; +pub const NFT_REG32_08: ::c_int = 16; +pub const NFT_REG32_09: ::c_int = 17; +pub const NFT_REG32_10: ::c_int = 18; +pub const NFT_REG32_11: ::c_int = 19; +pub const NFT_REG32_12: ::c_int = 20; +pub const NFT_REG32_13: ::c_int = 21; +pub const NFT_REG32_14: ::c_int = 22; +pub const NFT_REG32_15: ::c_int = 23; + +pub const NFT_REG_SIZE: ::c_int = 16; +pub const NFT_REG32_SIZE: ::c_int = 4; + +pub const NFT_CONTINUE: ::c_int = -1; +pub const NFT_BREAK: ::c_int = -2; +pub const NFT_JUMP: ::c_int = -3; +pub const NFT_GOTO: ::c_int = -4; +pub const NFT_RETURN: ::c_int = -5; + +pub const NFT_MSG_NEWTABLE: ::c_int = 0; +pub const NFT_MSG_GETTABLE: ::c_int = 1; +pub const NFT_MSG_DELTABLE: ::c_int = 2; +pub const NFT_MSG_NEWCHAIN: ::c_int = 3; +pub const NFT_MSG_GETCHAIN: ::c_int = 4; +pub const NFT_MSG_DELCHAIN: ::c_int = 5; +pub const NFT_MSG_NEWRULE: ::c_int = 6; +pub const NFT_MSG_GETRULE: ::c_int = 7; +pub const NFT_MSG_DELRULE: ::c_int = 8; +pub const NFT_MSG_NEWSET: ::c_int = 9; +pub const NFT_MSG_GETSET: ::c_int = 10; +pub const NFT_MSG_DELSET: ::c_int = 11; +pub const NFT_MSG_NEWSETELEM: ::c_int = 12; +pub const NFT_MSG_GETSETELEM: ::c_int = 13; +pub const NFT_MSG_DELSETELEM: ::c_int = 14; +pub const NFT_MSG_NEWGEN: ::c_int = 15; +pub const NFT_MSG_GETGEN: ::c_int = 16; +pub const NFT_MSG_TRACE: ::c_int = 17; +pub const NFT_MSG_NEWOBJ: ::c_int = 18; +pub const NFT_MSG_GETOBJ: ::c_int = 19; +pub const NFT_MSG_DELOBJ: ::c_int = 20; +pub const NFT_MSG_GETOBJ_RESET: ::c_int = 21; +pub const NFT_MSG_MAX: ::c_int = 22; + +pub const NFT_SET_ANONYMOUS: ::c_int = 0x1; +pub const NFT_SET_CONSTANT: ::c_int = 0x2; +pub const NFT_SET_INTERVAL: ::c_int = 0x4; +pub const NFT_SET_MAP: ::c_int = 0x8; +pub const NFT_SET_TIMEOUT: ::c_int = 0x10; +pub const NFT_SET_EVAL: ::c_int = 0x20; + +pub const NFT_SET_POL_PERFORMANCE: ::c_int = 0; +pub const NFT_SET_POL_MEMORY: ::c_int = 1; + +pub const NFT_SET_ELEM_INTERVAL_END: ::c_int = 0x1; + +pub const NFT_DATA_VALUE: ::c_uint = 0; +pub const NFT_DATA_VERDICT: ::c_uint = 0xffffff00; + +pub const NFT_DATA_RESERVED_MASK: ::c_uint = 0xffffff00; + +pub const NFT_DATA_VALUE_MAXLEN: ::c_int = 64; + +pub const NFT_BYTEORDER_NTOH: ::c_int = 0; +pub const NFT_BYTEORDER_HTON: ::c_int = 1; + +pub const NFT_CMP_EQ: ::c_int = 0; +pub const NFT_CMP_NEQ: ::c_int = 1; +pub const NFT_CMP_LT: ::c_int = 2; +pub const NFT_CMP_LTE: ::c_int = 3; +pub const NFT_CMP_GT: ::c_int = 4; +pub const NFT_CMP_GTE: ::c_int = 5; + +pub const NFT_RANGE_EQ: ::c_int = 0; +pub const NFT_RANGE_NEQ: ::c_int = 1; + +pub const NFT_LOOKUP_F_INV: ::c_int = (1 << 0); + +pub const NFT_DYNSET_OP_ADD: ::c_int = 0; +pub const NFT_DYNSET_OP_UPDATE: ::c_int = 1; + +pub const NFT_DYNSET_F_INV: ::c_int = (1 << 0); + +pub const NFT_PAYLOAD_LL_HEADER: ::c_int = 0; +pub const NFT_PAYLOAD_NETWORK_HEADER: ::c_int = 1; +pub const NFT_PAYLOAD_TRANSPORT_HEADER: ::c_int = 2; + +pub const NFT_PAYLOAD_CSUM_NONE: ::c_int = 0; +pub const NFT_PAYLOAD_CSUM_INET: ::c_int = 1; + +pub const NFT_META_LEN: ::c_int = 0; +pub const NFT_META_PROTOCOL: ::c_int = 1; +pub const NFT_META_PRIORITY: ::c_int = 2; +pub const NFT_META_MARK: ::c_int = 3; +pub const NFT_META_IIF: ::c_int = 4; +pub const NFT_META_OIF: ::c_int = 5; +pub const NFT_META_IIFNAME: ::c_int = 6; +pub const NFT_META_OIFNAME: ::c_int = 7; +pub const NFT_META_IIFTYPE: ::c_int = 8; +pub const NFT_META_OIFTYPE: ::c_int = 9; +pub const NFT_META_SKUID: ::c_int = 10; +pub const NFT_META_SKGID: ::c_int = 11; +pub const NFT_META_NFTRACE: ::c_int = 12; +pub const NFT_META_RTCLASSID: ::c_int = 13; +pub const NFT_META_SECMARK: ::c_int = 14; +pub const NFT_META_NFPROTO: ::c_int = 15; +pub const NFT_META_L4PROTO: ::c_int = 16; +pub const NFT_META_BRI_IIFNAME: ::c_int = 17; +pub const NFT_META_BRI_OIFNAME: ::c_int = 18; +pub const NFT_META_PKTTYPE: ::c_int = 19; +pub const NFT_META_CPU: ::c_int = 20; +pub const NFT_META_IIFGROUP: ::c_int = 21; +pub const NFT_META_OIFGROUP: ::c_int = 22; +pub const NFT_META_CGROUP: ::c_int = 23; +pub const NFT_META_PRANDOM: ::c_int = 24; + +pub const NFT_CT_STATE: ::c_int = 0; +pub const NFT_CT_DIRECTION: ::c_int = 1; +pub const NFT_CT_STATUS: ::c_int = 2; +pub const NFT_CT_MARK: ::c_int = 3; +pub const NFT_CT_SECMARK: ::c_int = 4; +pub const NFT_CT_EXPIRATION: ::c_int = 5; +pub const NFT_CT_HELPER: ::c_int = 6; +pub const NFT_CT_L3PROTOCOL: ::c_int = 7; +pub const NFT_CT_SRC: ::c_int = 8; +pub const NFT_CT_DST: ::c_int = 9; +pub const NFT_CT_PROTOCOL: ::c_int = 10; +pub const NFT_CT_PROTO_SRC: ::c_int = 11; +pub const NFT_CT_PROTO_DST: ::c_int = 12; +pub const NFT_CT_LABELS: ::c_int = 13; +pub const NFT_CT_PKTS: ::c_int = 14; +pub const NFT_CT_BYTES: ::c_int = 15; + +pub const NFT_LIMIT_PKTS: ::c_int = 0; +pub const NFT_LIMIT_PKT_BYTES: ::c_int = 1; + +pub const NFT_LIMIT_F_INV: ::c_int = (1 << 0); + +pub const NFT_QUEUE_FLAG_BYPASS: ::c_int = 0x01; +pub const NFT_QUEUE_FLAG_CPU_FANOUT: ::c_int = 0x02; +pub const NFT_QUEUE_FLAG_MASK: ::c_int = 0x03; + +pub const NFT_QUOTA_F_INV: ::c_int = (1 << 0); + +pub const NFT_REJECT_ICMP_UNREACH: ::c_int = 0; +pub const NFT_REJECT_TCP_RST: ::c_int = 1; +pub const NFT_REJECT_ICMPX_UNREACH: ::c_int = 2; + +pub const NFT_REJECT_ICMPX_NO_ROUTE: ::c_int = 0; +pub const NFT_REJECT_ICMPX_PORT_UNREACH: ::c_int = 1; +pub const NFT_REJECT_ICMPX_HOST_UNREACH: ::c_int = 2; +pub const NFT_REJECT_ICMPX_ADMIN_PROHIBITED: ::c_int = 3; + +pub const NFT_NAT_SNAT: ::c_int = 0; +pub const NFT_NAT_DNAT: ::c_int = 1; + +pub const NFT_TRACETYPE_UNSPEC: ::c_int = 0; +pub const NFT_TRACETYPE_POLICY: ::c_int = 1; +pub const NFT_TRACETYPE_RETURN: ::c_int = 2; +pub const NFT_TRACETYPE_RULE: ::c_int = 3; + +pub const NFT_NG_INCREMENTAL: ::c_int = 0; +pub const NFT_NG_RANDOM: ::c_int = 1; + +pub const IFF_TUN: ::c_int = 0x0001; +pub const IFF_TAP: ::c_int = 0x0002; +pub const IFF_NO_PI: ::c_int = 0x1000; + +// start android/platform/bionic/libc/kernel/uapi/linux/if_ether.h +// from https://android.googlesource.com/ +// platform/bionic/+/master/libc/kernel/uapi/linux/if_ether.h +pub const ETH_ALEN: ::c_int = 6; +pub const ETH_HLEN: ::c_int = 14; +pub const ETH_ZLEN: ::c_int = 60; +pub const ETH_DATA_LEN: ::c_int = 1500; +pub const ETH_FRAME_LEN: ::c_int = 1514; +pub const ETH_FCS_LEN: ::c_int = 4; +pub const ETH_MIN_MTU: ::c_int = 68; +pub const ETH_MAX_MTU: ::c_int = 0xFFFF; +pub const ETH_P_LOOP: ::c_int = 0x0060; +pub const ETH_P_PUP: ::c_int = 0x0200; +pub const ETH_P_PUPAT: ::c_int = 0x0201; +pub const ETH_P_TSN: ::c_int = 0x22F0; +pub const ETH_P_IP: ::c_int = 0x0800; +pub const ETH_P_X25: ::c_int = 0x0805; +pub const ETH_P_ARP: ::c_int = 0x0806; +pub const ETH_P_BPQ: ::c_int = 0x08FF; +pub const ETH_P_IEEEPUP: ::c_int = 0x0a00; +pub const ETH_P_IEEEPUPAT: ::c_int = 0x0a01; +pub const ETH_P_BATMAN: ::c_int = 0x4305; +pub const ETH_P_DEC: ::c_int = 0x6000; +pub const ETH_P_DNA_DL: ::c_int = 0x6001; +pub const ETH_P_DNA_RC: ::c_int = 0x6002; +pub const ETH_P_DNA_RT: ::c_int = 0x6003; +pub const ETH_P_LAT: ::c_int = 0x6004; +pub const ETH_P_DIAG: ::c_int = 0x6005; +pub const ETH_P_CUST: ::c_int = 0x6006; +pub const ETH_P_SCA: ::c_int = 0x6007; +pub const ETH_P_TEB: ::c_int = 0x6558; +pub const ETH_P_RARP: ::c_int = 0x8035; +pub const ETH_P_ATALK: ::c_int = 0x809B; +pub const ETH_P_AARP: ::c_int = 0x80F3; +pub const ETH_P_8021Q: ::c_int = 0x8100; +/* see rust-lang/libc#924 pub const ETH_P_ERSPAN: ::c_int = 0x88BE;*/ +pub const ETH_P_IPX: ::c_int = 0x8137; +pub const ETH_P_IPV6: ::c_int = 0x86DD; +pub const ETH_P_PAUSE: ::c_int = 0x8808; +pub const ETH_P_SLOW: ::c_int = 0x8809; +pub const ETH_P_WCCP: ::c_int = 0x883E; +pub const ETH_P_MPLS_UC: ::c_int = 0x8847; +pub const ETH_P_MPLS_MC: ::c_int = 0x8848; +pub const ETH_P_ATMMPOA: ::c_int = 0x884c; +pub const ETH_P_PPP_DISC: ::c_int = 0x8863; +pub const ETH_P_PPP_SES: ::c_int = 0x8864; +pub const ETH_P_LINK_CTL: ::c_int = 0x886c; +pub const ETH_P_ATMFATE: ::c_int = 0x8884; +pub const ETH_P_PAE: ::c_int = 0x888E; +pub const ETH_P_AOE: ::c_int = 0x88A2; +pub const ETH_P_8021AD: ::c_int = 0x88A8; +pub const ETH_P_802_EX1: ::c_int = 0x88B5; +pub const ETH_P_TIPC: ::c_int = 0x88CA; +pub const ETH_P_MACSEC: ::c_int = 0x88E5; +pub const ETH_P_8021AH: ::c_int = 0x88E7; +pub const ETH_P_MVRP: ::c_int = 0x88F5; +pub const ETH_P_1588: ::c_int = 0x88F7; +pub const ETH_P_NCSI: ::c_int = 0x88F8; +pub const ETH_P_PRP: ::c_int = 0x88FB; +pub const ETH_P_FCOE: ::c_int = 0x8906; +/* see rust-lang/libc#924 pub const ETH_P_IBOE: ::c_int = 0x8915;*/ +pub const ETH_P_TDLS: ::c_int = 0x890D; +pub const ETH_P_FIP: ::c_int = 0x8914; +pub const ETH_P_80221: ::c_int = 0x8917; +pub const ETH_P_HSR: ::c_int = 0x892F; +/* see rust-lang/libc#924 pub const ETH_P_NSH: ::c_int = 0x894F;*/ +pub const ETH_P_LOOPBACK: ::c_int = 0x9000; +pub const ETH_P_QINQ1: ::c_int = 0x9100; +pub const ETH_P_QINQ2: ::c_int = 0x9200; +pub const ETH_P_QINQ3: ::c_int = 0x9300; +pub const ETH_P_EDSA: ::c_int = 0xDADA; +/* see rust-lang/libc#924 pub const ETH_P_IFE: ::c_int = 0xED3E;*/ +pub const ETH_P_AF_IUCV: ::c_int = 0xFBFB; +pub const ETH_P_802_3_MIN: ::c_int = 0x0600; +pub const ETH_P_802_3: ::c_int = 0x0001; +pub const ETH_P_AX25: ::c_int = 0x0002; +pub const ETH_P_ALL: ::c_int = 0x0003; +pub const ETH_P_802_2: ::c_int = 0x0004; +pub const ETH_P_SNAP: ::c_int = 0x0005; +pub const ETH_P_DDCMP: ::c_int = 0x0006; +pub const ETH_P_WAN_PPP: ::c_int = 0x0007; +pub const ETH_P_PPP_MP: ::c_int = 0x0008; +pub const ETH_P_LOCALTALK: ::c_int = 0x0009; +pub const ETH_P_CAN: ::c_int = 0x000C; +pub const ETH_P_CANFD: ::c_int = 0x000D; +pub const ETH_P_PPPTALK: ::c_int = 0x0010; +pub const ETH_P_TR_802_2: ::c_int = 0x0011; +pub const ETH_P_MOBITEX: ::c_int = 0x0015; +pub const ETH_P_CONTROL: ::c_int = 0x0016; +pub const ETH_P_IRDA: ::c_int = 0x0017; +pub const ETH_P_ECONET: ::c_int = 0x0018; +pub const ETH_P_HDLC: ::c_int = 0x0019; +pub const ETH_P_ARCNET: ::c_int = 0x001A; +pub const ETH_P_DSA: ::c_int = 0x001B; +pub const ETH_P_TRAILER: ::c_int = 0x001C; +pub const ETH_P_PHONET: ::c_int = 0x00F5; +pub const ETH_P_IEEE802154: ::c_int = 0x00F6; +pub const ETH_P_CAIF: ::c_int = 0x00F7; +pub const ETH_P_XDSA: ::c_int = 0x00F8; +/* see rust-lang/libc#924 pub const ETH_P_MAP: ::c_int = 0x00F9;*/ +// end android/platform/bionic/libc/kernel/uapi/linux/if_ether.h + +f! { + pub fn CPU_ZERO(cpuset: &mut cpu_set_t) -> () { + for slot in cpuset.__bits.iter_mut() { + *slot = 0; + } + } + + pub fn CPU_SET(cpu: usize, cpuset: &mut cpu_set_t) -> () { + let size_in___bits = 8 * mem::size_of_val(&cpuset.__bits[0]); + let (idx, offset) = (cpu / size_in___bits, cpu % size_in___bits); + cpuset.__bits[idx] |= 1 << offset; + () + } + + pub fn CPU_CLR(cpu: usize, cpuset: &mut cpu_set_t) -> () { + let size_in___bits = 8 * mem::size_of_val(&cpuset.__bits[0]); + let (idx, offset) = (cpu / size_in___bits, cpu % size_in___bits); + cpuset.__bits[idx] &= !(1 << offset); + () + } + + pub fn CPU_ISSET(cpu: usize, cpuset: &cpu_set_t) -> bool { + let size_in___bits = 8 * mem::size_of_val(&cpuset.__bits[0]); + let (idx, offset) = (cpu / size_in___bits, cpu % size_in___bits); + 0 != (cpuset.__bits[idx] & (1 << offset)) + } + + pub fn CPU_EQUAL(set1: &cpu_set_t, set2: &cpu_set_t) -> bool { + set1.__bits == set2.__bits + } + pub fn major(dev: ::dev_t) -> ::c_int { + ((dev >> 8) & 0xfff) as ::c_int + } + pub fn minor(dev: ::dev_t) -> ::c_int { + ((dev & 0xff) | ((dev >> 12) & 0xfff00)) as ::c_int + } + pub fn makedev(ma: ::c_int, mi: ::c_int) -> ::dev_t { + let ma = ma as ::dev_t; + let mi = mi as ::dev_t; + ((ma & 0xfff) << 8) | (mi & 0xff) | ((mi & 0xfff00) << 12) + } + + pub fn NLA_ALIGN(len: ::c_int) -> ::c_int { + return ((len) + NLA_ALIGNTO - 1) & !(NLA_ALIGNTO - 1) + } +} + +extern { + static mut __progname: *mut ::c_char; +} + +extern { + pub fn madvise(addr: *const ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + pub fn ioctl(fd: ::c_int, request: ::c_int, ...) -> ::c_int; + pub fn msync(addr: *const ::c_void, len: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn mprotect(addr: *const ::c_void, len: ::size_t, prot: ::c_int) + -> ::c_int; + pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, + flags: ::c_int, addr: *const ::sockaddr, + addrlen: *mut ::socklen_t) -> ::ssize_t; + pub fn getnameinfo(sa: *const ::sockaddr, + salen: ::socklen_t, + host: *mut ::c_char, + hostlen: ::size_t, + serv: *mut ::c_char, + sevlen: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn ptrace(request: ::c_int, ...) -> ::c_long; + pub fn getpriority(which: ::c_int, who: ::c_int) -> ::c_int; + pub fn setpriority(which: ::c_int, who: ::c_int, prio: ::c_int) -> ::c_int; + pub fn __sched_cpualloc(count: ::size_t) -> *mut ::cpu_set_t; + pub fn __sched_cpufree(set: *mut ::cpu_set_t); + pub fn __sched_cpucount(setsize: ::size_t, set: *mut cpu_set_t) -> ::c_int; + pub fn sched_getcpu() -> ::c_int; + + pub fn utmpname(name: *const ::c_char) -> ::c_int; + pub fn setutent(); + pub fn getutent() -> *mut utmp; + + pub fn posix_fallocate(fd: ::c_int, offset: ::off_t, + len: ::off_t) -> ::c_int; + pub fn signalfd(fd: ::c_int, mask: *const ::sigset_t, flags: ::c_int) + -> ::c_int; + pub fn syscall(num: ::c_long, ...) -> ::c_long; + pub fn sched_getaffinity(pid: ::pid_t, + cpusetsize: ::size_t, + cpuset: *mut cpu_set_t) -> ::c_int; + pub fn sched_setaffinity(pid: ::pid_t, + cpusetsize: ::size_t, + cpuset: *const cpu_set_t) -> ::c_int; + pub fn epoll_create(size: ::c_int) -> ::c_int; + pub fn epoll_create1(flags: ::c_int) -> ::c_int; + pub fn epoll_wait(epfd: ::c_int, + events: *mut ::epoll_event, + maxevents: ::c_int, + timeout: ::c_int) -> ::c_int; + pub fn epoll_ctl(epfd: ::c_int, + op: ::c_int, + fd: ::c_int, + event: *mut ::epoll_event) -> ::c_int; + pub fn pthread_getschedparam(native: ::pthread_t, + policy: *mut ::c_int, + param: *mut ::sched_param) -> ::c_int; + pub fn unshare(flags: ::c_int) -> ::c_int; + pub fn umount(target: *const ::c_char) -> ::c_int; + pub fn sched_get_priority_max(policy: ::c_int) -> ::c_int; + pub fn tee(fd_in: ::c_int, + fd_out: ::c_int, + len: ::size_t, + flags: ::c_uint) -> ::ssize_t; + pub fn settimeofday(tv: *const ::timeval, tz: *const ::timezone) -> ::c_int; + pub fn splice(fd_in: ::c_int, + off_in: *mut ::loff_t, + fd_out: ::c_int, + off_out: *mut ::loff_t, + len: ::size_t, + flags: ::c_uint) -> ::ssize_t; + pub fn eventfd(init: ::c_uint, flags: ::c_int) -> ::c_int; + pub fn sched_rr_get_interval(pid: ::pid_t, tp: *mut ::timespec) -> ::c_int; + pub fn sem_timedwait(sem: *mut sem_t, + abstime: *const ::timespec) -> ::c_int; + pub fn sched_setparam(pid: ::pid_t, param: *const ::sched_param) -> ::c_int; + pub fn setns(fd: ::c_int, nstype: ::c_int) -> ::c_int; + pub fn swapoff(puath: *const ::c_char) -> ::c_int; + pub fn vmsplice(fd: ::c_int, + iov: *const ::iovec, + nr_segs: ::size_t, + flags: ::c_uint) -> ::ssize_t; + pub fn mount(src: *const ::c_char, + target: *const ::c_char, + fstype: *const ::c_char, + flags: ::c_ulong, + data: *const ::c_void) -> ::c_int; + pub fn personality(persona: ::c_ulong) -> ::c_int; + pub fn prctl(option: ::c_int, ...) -> ::c_int; + pub fn sched_getparam(pid: ::pid_t, param: *mut ::sched_param) -> ::c_int; + pub fn ppoll(fds: *mut ::pollfd, + nfds: nfds_t, + timeout: *const ::timespec, + sigmask: *const sigset_t) -> ::c_int; + pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, + abstime: *const ::timespec) -> ::c_int; + pub fn clone(cb: extern fn(*mut ::c_void) -> ::c_int, + child_stack: *mut ::c_void, + flags: ::c_int, + arg: *mut ::c_void, ...) -> ::c_int; + pub fn sched_getscheduler(pid: ::pid_t) -> ::c_int; + pub fn clock_nanosleep(clk_id: ::clockid_t, + flags: ::c_int, + rqtp: *const ::timespec, + rmtp: *mut ::timespec) -> ::c_int; + pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, + guardsize: *mut ::size_t) -> ::c_int; + pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; + pub fn sched_get_priority_min(policy: ::c_int) -> ::c_int; + pub fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, + pshared: *mut ::c_int) -> ::c_int; + pub fn sysinfo(info: *mut ::sysinfo) -> ::c_int; + pub fn umount2(target: *const ::c_char, flags: ::c_int) -> ::c_int; + pub fn pthread_setschedparam(native: ::pthread_t, + policy: ::c_int, + param: *const ::sched_param) -> ::c_int; + pub fn swapon(path: *const ::c_char, swapflags: ::c_int) -> ::c_int; + pub fn sched_setscheduler(pid: ::pid_t, + policy: ::c_int, + param: *const ::sched_param) -> ::c_int; + pub fn sendfile(out_fd: ::c_int, + in_fd: ::c_int, + offset: *mut off_t, + count: ::size_t) -> ::ssize_t; + pub fn setfsgid(gid: ::gid_t) -> ::c_int; + pub fn setfsuid(uid: ::uid_t) -> ::c_int; + pub fn sigsuspend(mask: *const ::sigset_t) -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] + pub fn getgrgid_r(uid: ::uid_t, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "sigaltstack$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")] + pub fn sigaltstack(ss: *const stack_t, + oss: *mut stack_t) -> ::c_int; + pub fn sem_close(sem: *mut sem_t) -> ::c_int; + pub fn getdtablesize() -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] + pub fn getgrnam_r(name: *const ::c_char, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_sigmask$UNIX2003")] + pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, + oldset: *mut sigset_t) -> ::c_int; + pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; + pub fn getgrnam(name: *const ::c_char) -> *mut ::group; + pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; + pub fn sem_unlink(name: *const ::c_char) -> ::c_int; + pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] + pub fn getpwnam_r(name: *const ::c_char, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] + pub fn getpwuid_r(uid: ::uid_t, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch ="x86"), + link_name = "sigwait$UNIX2003")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] + pub fn sigwait(set: *const sigset_t, + sig: *mut ::c_int) -> ::c_int; + pub fn pthread_atfork(prepare: Option, + parent: Option, + child: Option) -> ::c_int; + pub fn getgrgid(gid: ::gid_t) -> *mut ::group; + pub fn getgrouplist(user: *const ::c_char, + group: ::gid_t, + groups: *mut ::gid_t, + ngroups: *mut ::c_int) -> ::c_int; + pub fn initgroups(user: *const ::c_char, group: ::gid_t) -> ::c_int; + pub fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, + pshared: *mut ::c_int) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "popen$UNIX2003")] + pub fn popen(command: *const c_char, + mode: *const c_char) -> *mut ::FILE; + pub fn faccessat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::c_int, flags: ::c_int) -> ::c_int; + pub fn pthread_create(native: *mut ::pthread_t, + attr: *const ::pthread_attr_t, + f: extern fn(*mut ::c_void) -> *mut ::c_void, + value: *mut ::c_void) -> ::c_int; + pub fn __errno() -> *mut ::c_int; +} + +cfg_if! { + if #[cfg(target_pointer_width = "32")] { + mod b32; + pub use self::b32::*; + } else if #[cfg(target_pointer_width = "64")] { + mod b64; + pub use self::b64::*; + } else { + // Unknown target_pointer_width + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/emscripten.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/emscripten.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/emscripten.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/emscripten.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1667 @@ +use dox::{mem, Option}; + +pub type c_char = i8; +pub type wchar_t = i32; +pub type useconds_t = u32; +pub type dev_t = u32; +pub type socklen_t = u32; +pub type pthread_t = c_ulong; +pub type mode_t = u32; +pub type ino64_t = u32; +pub type off64_t = i32; +pub type blkcnt64_t = i32; +pub type rlim64_t = u64; +pub type shmatt_t = ::c_ulong; +pub type mqd_t = ::c_int; +pub type msgqnum_t = ::c_ulong; +pub type msglen_t = ::c_ulong; +pub type nfds_t = ::c_ulong; +pub type nl_item = ::c_int; +pub type idtype_t = ::c_uint; +pub type loff_t = i32; + +pub type clock_t = c_long; +pub type time_t = c_long; +pub type suseconds_t = c_long; +pub type ino_t = u32; +pub type off_t = i32; +pub type blkcnt_t = i32; + +pub type blksize_t = c_long; +pub type fsblkcnt_t = u32; +pub type fsfilcnt_t = u32; +pub type rlim_t = ::c_ulonglong; +pub type c_long = i32; +pub type c_ulong = u32; +pub type nlink_t = u32; + +pub enum fpos64_t {} // TODO: fill this out with a struct + +s! { + pub struct dirent { + pub d_ino: ::ino_t, + pub d_off: ::off_t, + pub d_reclen: ::c_ushort, + pub d_type: ::c_uchar, + pub d_name: [::c_char; 256], + } + + pub struct dirent64 { + pub d_ino: ::ino64_t, + pub d_off: ::off64_t, + pub d_reclen: ::c_ushort, + pub d_type: ::c_uchar, + pub d_name: [::c_char; 256], + } + + pub struct rlimit64 { + pub rlim_cur: rlim64_t, + pub rlim_max: rlim64_t, + } + + pub struct glob_t { + pub gl_pathc: ::size_t, + pub gl_pathv: *mut *mut c_char, + pub gl_offs: ::size_t, + pub gl_flags: ::c_int, + + __unused1: *mut ::c_void, + __unused2: *mut ::c_void, + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + } + + pub struct ifaddrs { + pub ifa_next: *mut ifaddrs, + pub ifa_name: *mut c_char, + pub ifa_flags: ::c_uint, + pub ifa_addr: *mut ::sockaddr, + pub ifa_netmask: *mut ::sockaddr, + pub ifa_ifu: *mut ::sockaddr, // FIXME This should be a union + pub ifa_data: *mut ::c_void + } + + pub struct pthread_mutex_t { + __align: [::c_long; 0], + size: [u8; __SIZEOF_PTHREAD_MUTEX_T], + } + + pub struct pthread_rwlock_t { + __align: [::c_long; 0], + size: [u8; __SIZEOF_PTHREAD_RWLOCK_T], + } + + pub struct pthread_mutexattr_t { + __align: [::c_int; 0], + size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T], + } + + pub struct pthread_rwlockattr_t { + __align: [::c_int; 0], + size: [u8; __SIZEOF_PTHREAD_RWLOCKATTR_T], + } + + pub struct pthread_cond_t { + __align: [*const ::c_void; 0], + size: [u8; __SIZEOF_PTHREAD_COND_T], + } + + pub struct pthread_condattr_t { + __align: [::c_int; 0], + size: [u8; __SIZEOF_PTHREAD_CONDATTR_T], + } + + pub struct passwd { + pub pw_name: *mut ::c_char, + pub pw_passwd: *mut ::c_char, + pub pw_uid: ::uid_t, + pub pw_gid: ::gid_t, + pub pw_gecos: *mut ::c_char, + pub pw_dir: *mut ::c_char, + pub pw_shell: *mut ::c_char, + } + + pub struct spwd { + pub sp_namp: *mut ::c_char, + pub sp_pwdp: *mut ::c_char, + pub sp_lstchg: ::c_long, + pub sp_min: ::c_long, + pub sp_max: ::c_long, + pub sp_warn: ::c_long, + pub sp_inact: ::c_long, + pub sp_expire: ::c_long, + pub sp_flag: ::c_ulong, + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + pub f_fsid: ::c_ulong, + __f_unused: ::c_int, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct dqblk { + pub dqb_bhardlimit: ::uint64_t, + pub dqb_bsoftlimit: ::uint64_t, + pub dqb_curspace: ::uint64_t, + pub dqb_ihardlimit: ::uint64_t, + pub dqb_isoftlimit: ::uint64_t, + pub dqb_curinodes: ::uint64_t, + pub dqb_btime: ::uint64_t, + pub dqb_itime: ::uint64_t, + pub dqb_valid: ::uint32_t, + } + + pub struct signalfd_siginfo { + pub ssi_signo: ::uint32_t, + pub ssi_errno: ::int32_t, + pub ssi_code: ::int32_t, + pub ssi_pid: ::uint32_t, + pub ssi_uid: ::uint32_t, + pub ssi_fd: ::int32_t, + pub ssi_tid: ::uint32_t, + pub ssi_band: ::uint32_t, + pub ssi_overrun: ::uint32_t, + pub ssi_trapno: ::uint32_t, + pub ssi_status: ::int32_t, + pub ssi_int: ::int32_t, + pub ssi_ptr: ::uint64_t, + pub ssi_utime: ::uint64_t, + pub ssi_stime: ::uint64_t, + pub ssi_addr: ::uint64_t, + _pad: [::uint8_t; 48], + } + + pub struct fsid_t { + __val: [::c_int; 2], + } + + pub struct mq_attr { + pub mq_flags: ::c_long, + pub mq_maxmsg: ::c_long, + pub mq_msgsize: ::c_long, + pub mq_curmsgs: ::c_long, + pad: [::c_long; 4] + } + + pub struct cpu_set_t { + bits: [u32; 32], + } + + pub struct if_nameindex { + pub if_index: ::c_uint, + pub if_name: *mut ::c_char, + } + + // System V IPC + pub struct msginfo { + pub msgpool: ::c_int, + pub msgmap: ::c_int, + pub msgmax: ::c_int, + pub msgmnb: ::c_int, + pub msgmni: ::c_int, + pub msgssz: ::c_int, + pub msgtql: ::c_int, + pub msgseg: ::c_ushort, + } + + pub struct mmsghdr { + pub msg_hdr: ::msghdr, + pub msg_len: ::c_uint, + } + + pub struct sembuf { + pub sem_num: ::c_ushort, + pub sem_op: ::c_short, + pub sem_flg: ::c_short, + } + + pub struct aiocb { + pub aio_fildes: ::c_int, + pub aio_lio_opcode: ::c_int, + pub aio_reqprio: ::c_int, + pub aio_buf: *mut ::c_void, + pub aio_nbytes: ::size_t, + pub aio_sigevent: ::sigevent, + __td: *mut ::c_void, + __lock: [::c_int; 2], + __err: ::c_int, + __ret: ::ssize_t, + pub aio_offset: off_t, + __next: *mut ::c_void, + __prev: *mut ::c_void, + __dummy4: [::c_char; 24], + } + + pub struct sigaction { + pub sa_sigaction: ::sighandler_t, + pub sa_mask: ::sigset_t, + pub sa_flags: ::c_int, + pub sa_restorer: ::dox::Option, + } + + pub struct ipc_perm { + pub __ipc_perm_key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + pub __seq: ::c_int, + __unused1: ::c_long, + __unused2: ::c_long + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; ::NCCS], + pub __c_ispeed: ::speed_t, + pub __c_ospeed: ::speed_t, + } + + pub struct flock { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_pid: ::pid_t, + } + + pub struct sysinfo { + pub uptime: ::c_ulong, + pub loads: [::c_ulong; 3], + pub totalram: ::c_ulong, + pub freeram: ::c_ulong, + pub sharedram: ::c_ulong, + pub bufferram: ::c_ulong, + pub totalswap: ::c_ulong, + pub freeswap: ::c_ulong, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: ::c_ulong, + pub freehigh: ::c_ulong, + pub mem_unit: ::c_uint, + pub __reserved: [::c_char; 256], + } + + pub struct pthread_attr_t { + __size: [u32; 11] + } + + pub struct sigset_t { + __val: [::c_ulong; 32], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::c_int, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::socklen_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::socklen_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct sem_t { + __val: [::c_int; 4], + } + pub struct stat { + pub st_dev: ::dev_t, + __st_dev_padding: ::c_int, + __st_ino_truncated: ::c_long, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __st_rdev_padding: ::c_int, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_ino: ::ino_t, + } + + pub struct stat64 { + pub st_dev: ::dev_t, + __st_dev_padding: ::c_int, + __st_ino_truncated: ::c_long, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __st_rdev_padding: ::c_int, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_ino: ::ino_t, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_flags: ::c_int, + pub ss_size: ::size_t + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + __unused1: ::c_int, + pub shm_dtime: ::time_t, + __unused2: ::c_int, + pub shm_ctime: ::time_t, + __unused3: ::c_int, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::c_ulong, + __pad1: ::c_ulong, + __pad2: ::c_ulong, + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_stime: ::time_t, + __unused1: ::c_int, + pub msg_rtime: ::time_t, + __unused2: ::c_int, + pub msg_ctime: ::time_t, + __unused3: ::c_int, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __pad1: ::c_ulong, + __pad2: ::c_ulong, + } + + pub struct statfs { + pub f_type: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_flags: ::c_ulong, + pub f_spare: [::c_ulong; 4], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_errno: ::c_int, + pub si_code: ::c_int, + pub _pad: [::c_int; 29], + _align: [usize; 0], + } + + pub struct statfs64 { + pub f_type: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_flags: ::c_ulong, + pub f_spare: [::c_ulong; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u32, + pub f_bfree: u32, + pub f_bavail: u32, + pub f_files: u32, + pub f_ffree: u32, + pub f_favail: u32, + pub f_fsid: ::c_ulong, + __f_unused: ::c_int, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } +} + +pub const ABDAY_1: ::nl_item = 0x20000; +pub const ABDAY_2: ::nl_item = 0x20001; +pub const ABDAY_3: ::nl_item = 0x20002; +pub const ABDAY_4: ::nl_item = 0x20003; +pub const ABDAY_5: ::nl_item = 0x20004; +pub const ABDAY_6: ::nl_item = 0x20005; +pub const ABDAY_7: ::nl_item = 0x20006; + +pub const DAY_1: ::nl_item = 0x20007; +pub const DAY_2: ::nl_item = 0x20008; +pub const DAY_3: ::nl_item = 0x20009; +pub const DAY_4: ::nl_item = 0x2000A; +pub const DAY_5: ::nl_item = 0x2000B; +pub const DAY_6: ::nl_item = 0x2000C; +pub const DAY_7: ::nl_item = 0x2000D; + +pub const ABMON_1: ::nl_item = 0x2000E; +pub const ABMON_2: ::nl_item = 0x2000F; +pub const ABMON_3: ::nl_item = 0x20010; +pub const ABMON_4: ::nl_item = 0x20011; +pub const ABMON_5: ::nl_item = 0x20012; +pub const ABMON_6: ::nl_item = 0x20013; +pub const ABMON_7: ::nl_item = 0x20014; +pub const ABMON_8: ::nl_item = 0x20015; +pub const ABMON_9: ::nl_item = 0x20016; +pub const ABMON_10: ::nl_item = 0x20017; +pub const ABMON_11: ::nl_item = 0x20018; +pub const ABMON_12: ::nl_item = 0x20019; + +pub const MON_1: ::nl_item = 0x2001A; +pub const MON_2: ::nl_item = 0x2001B; +pub const MON_3: ::nl_item = 0x2001C; +pub const MON_4: ::nl_item = 0x2001D; +pub const MON_5: ::nl_item = 0x2001E; +pub const MON_6: ::nl_item = 0x2001F; +pub const MON_7: ::nl_item = 0x20020; +pub const MON_8: ::nl_item = 0x20021; +pub const MON_9: ::nl_item = 0x20022; +pub const MON_10: ::nl_item = 0x20023; +pub const MON_11: ::nl_item = 0x20024; +pub const MON_12: ::nl_item = 0x20025; + +pub const AM_STR: ::nl_item = 0x20026; +pub const PM_STR: ::nl_item = 0x20027; + +pub const D_T_FMT: ::nl_item = 0x20028; +pub const D_FMT: ::nl_item = 0x20029; +pub const T_FMT: ::nl_item = 0x2002A; +pub const T_FMT_AMPM: ::nl_item = 0x2002B; + +pub const ERA: ::nl_item = 0x2002C; +pub const ERA_D_FMT: ::nl_item = 0x2002E; +pub const ALT_DIGITS: ::nl_item = 0x2002F; +pub const ERA_D_T_FMT: ::nl_item = 0x20030; +pub const ERA_T_FMT: ::nl_item = 0x20031; + +pub const CODESET: ::nl_item = 14; + +pub const CRNCYSTR: ::nl_item = 0x4000F; + +pub const RUSAGE_THREAD: ::c_int = 1; +pub const RUSAGE_CHILDREN: ::c_int = -1; + +pub const RADIXCHAR: ::nl_item = 0x10000; +pub const THOUSEP: ::nl_item = 0x10001; + +pub const YESEXPR: ::nl_item = 0x50000; +pub const NOEXPR: ::nl_item = 0x50001; +pub const YESSTR: ::nl_item = 0x50002; +pub const NOSTR: ::nl_item = 0x50003; + +pub const FILENAME_MAX: ::c_uint = 4096; +pub const L_tmpnam: ::c_uint = 20; +pub const _PC_LINK_MAX: ::c_int = 0; +pub const _PC_MAX_CANON: ::c_int = 1; +pub const _PC_MAX_INPUT: ::c_int = 2; +pub const _PC_NAME_MAX: ::c_int = 3; +pub const _PC_PATH_MAX: ::c_int = 4; +pub const _PC_PIPE_BUF: ::c_int = 5; +pub const _PC_CHOWN_RESTRICTED: ::c_int = 6; +pub const _PC_NO_TRUNC: ::c_int = 7; +pub const _PC_VDISABLE: ::c_int = 8; +pub const _PC_SYNC_IO: ::c_int = 9; +pub const _PC_ASYNC_IO: ::c_int = 10; +pub const _PC_PRIO_IO: ::c_int = 11; +pub const _PC_SOCK_MAXBUF: ::c_int = 12; +pub const _PC_FILESIZEBITS: ::c_int = 13; +pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 14; +pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 15; +pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 16; +pub const _PC_REC_XFER_ALIGN: ::c_int = 17; +pub const _PC_ALLOC_SIZE_MIN: ::c_int = 18; +pub const _PC_SYMLINK_MAX: ::c_int = 19; +pub const _PC_2_SYMLINKS: ::c_int = 20; + +pub const _SC_ARG_MAX: ::c_int = 0; +pub const _SC_CHILD_MAX: ::c_int = 1; +pub const _SC_CLK_TCK: ::c_int = 2; +pub const _SC_NGROUPS_MAX: ::c_int = 3; +pub const _SC_OPEN_MAX: ::c_int = 4; +pub const _SC_STREAM_MAX: ::c_int = 5; +pub const _SC_TZNAME_MAX: ::c_int = 6; +pub const _SC_JOB_CONTROL: ::c_int = 7; +pub const _SC_SAVED_IDS: ::c_int = 8; +pub const _SC_REALTIME_SIGNALS: ::c_int = 9; +pub const _SC_PRIORITY_SCHEDULING: ::c_int = 10; +pub const _SC_TIMERS: ::c_int = 11; +pub const _SC_ASYNCHRONOUS_IO: ::c_int = 12; +pub const _SC_PRIORITIZED_IO: ::c_int = 13; +pub const _SC_SYNCHRONIZED_IO: ::c_int = 14; +pub const _SC_FSYNC: ::c_int = 15; +pub const _SC_MAPPED_FILES: ::c_int = 16; +pub const _SC_MEMLOCK: ::c_int = 17; +pub const _SC_MEMLOCK_RANGE: ::c_int = 18; +pub const _SC_MEMORY_PROTECTION: ::c_int = 19; +pub const _SC_MESSAGE_PASSING: ::c_int = 20; +pub const _SC_SEMAPHORES: ::c_int = 21; +pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 22; +pub const _SC_AIO_LISTIO_MAX: ::c_int = 23; +pub const _SC_AIO_MAX: ::c_int = 24; +pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 25; +pub const _SC_DELAYTIMER_MAX: ::c_int = 26; +pub const _SC_MQ_OPEN_MAX: ::c_int = 27; +pub const _SC_MQ_PRIO_MAX: ::c_int = 28; +pub const _SC_VERSION: ::c_int = 29; +pub const _SC_PAGESIZE: ::c_int = 30; +pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; +pub const _SC_RTSIG_MAX: ::c_int = 31; +pub const _SC_SEM_NSEMS_MAX: ::c_int = 32; +pub const _SC_SEM_VALUE_MAX: ::c_int = 33; +pub const _SC_SIGQUEUE_MAX: ::c_int = 34; +pub const _SC_TIMER_MAX: ::c_int = 35; +pub const _SC_BC_BASE_MAX: ::c_int = 36; +pub const _SC_BC_DIM_MAX: ::c_int = 37; +pub const _SC_BC_SCALE_MAX: ::c_int = 38; +pub const _SC_BC_STRING_MAX: ::c_int = 39; +pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 40; +pub const _SC_EXPR_NEST_MAX: ::c_int = 42; +pub const _SC_LINE_MAX: ::c_int = 43; +pub const _SC_RE_DUP_MAX: ::c_int = 44; +pub const _SC_2_VERSION: ::c_int = 46; +pub const _SC_2_C_BIND: ::c_int = 47; +pub const _SC_2_C_DEV: ::c_int = 48; +pub const _SC_2_FORT_DEV: ::c_int = 49; +pub const _SC_2_FORT_RUN: ::c_int = 50; +pub const _SC_2_SW_DEV: ::c_int = 51; +pub const _SC_2_LOCALEDEF: ::c_int = 52; +pub const _SC_UIO_MAXIOV: ::c_int = 60; +pub const _SC_IOV_MAX: ::c_int = 60; +pub const _SC_THREADS: ::c_int = 67; +pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 68; +pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 69; +pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 70; +pub const _SC_LOGIN_NAME_MAX: ::c_int = 71; +pub const _SC_TTY_NAME_MAX: ::c_int = 72; +pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 73; +pub const _SC_THREAD_KEYS_MAX: ::c_int = 74; +pub const _SC_THREAD_STACK_MIN: ::c_int = 75; +pub const _SC_THREAD_THREADS_MAX: ::c_int = 76; +pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 77; +pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 78; +pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 79; +pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 80; +pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 81; +pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 82; +pub const _SC_NPROCESSORS_CONF: ::c_int = 83; +pub const _SC_NPROCESSORS_ONLN: ::c_int = 84; +pub const _SC_PHYS_PAGES: ::c_int = 85; +pub const _SC_AVPHYS_PAGES: ::c_int = 86; +pub const _SC_ATEXIT_MAX: ::c_int = 87; +pub const _SC_PASS_MAX: ::c_int = 88; +pub const _SC_XOPEN_VERSION: ::c_int = 89; +pub const _SC_XOPEN_XCU_VERSION: ::c_int = 90; +pub const _SC_XOPEN_UNIX: ::c_int = 91; +pub const _SC_XOPEN_CRYPT: ::c_int = 92; +pub const _SC_XOPEN_ENH_I18N: ::c_int = 93; +pub const _SC_XOPEN_SHM: ::c_int = 94; +pub const _SC_2_CHAR_TERM: ::c_int = 95; +pub const _SC_2_UPE: ::c_int = 97; +pub const _SC_XOPEN_XPG2: ::c_int = 98; +pub const _SC_XOPEN_XPG3: ::c_int = 99; +pub const _SC_XOPEN_XPG4: ::c_int = 100; +pub const _SC_NZERO: ::c_int = 109; +pub const _SC_XBS5_ILP32_OFF32: ::c_int = 125; +pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 126; +pub const _SC_XBS5_LP64_OFF64: ::c_int = 127; +pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 128; +pub const _SC_XOPEN_LEGACY: ::c_int = 129; +pub const _SC_XOPEN_REALTIME: ::c_int = 130; +pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 131; +pub const _SC_ADVISORY_INFO: ::c_int = 132; +pub const _SC_BARRIERS: ::c_int = 133; +pub const _SC_CLOCK_SELECTION: ::c_int = 137; +pub const _SC_CPUTIME: ::c_int = 138; +pub const _SC_THREAD_CPUTIME: ::c_int = 139; +pub const _SC_MONOTONIC_CLOCK: ::c_int = 149; +pub const _SC_READER_WRITER_LOCKS: ::c_int = 153; +pub const _SC_SPIN_LOCKS: ::c_int = 154; +pub const _SC_REGEXP: ::c_int = 155; +pub const _SC_SHELL: ::c_int = 157; +pub const _SC_SPAWN: ::c_int = 159; +pub const _SC_SPORADIC_SERVER: ::c_int = 160; +pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 161; +pub const _SC_TIMEOUTS: ::c_int = 164; +pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 165; +pub const _SC_2_PBS: ::c_int = 168; +pub const _SC_2_PBS_ACCOUNTING: ::c_int = 169; +pub const _SC_2_PBS_LOCATE: ::c_int = 170; +pub const _SC_2_PBS_MESSAGE: ::c_int = 171; +pub const _SC_2_PBS_TRACK: ::c_int = 172; +pub const _SC_SYMLOOP_MAX: ::c_int = 173; +pub const _SC_STREAMS: ::c_int = 174; +pub const _SC_2_PBS_CHECKPOINT: ::c_int = 175; +pub const _SC_V6_ILP32_OFF32: ::c_int = 176; +pub const _SC_V6_ILP32_OFFBIG: ::c_int = 177; +pub const _SC_V6_LP64_OFF64: ::c_int = 178; +pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 179; +pub const _SC_HOST_NAME_MAX: ::c_int = 180; +pub const _SC_TRACE: ::c_int = 181; +pub const _SC_TRACE_EVENT_FILTER: ::c_int = 182; +pub const _SC_TRACE_INHERIT: ::c_int = 183; +pub const _SC_TRACE_LOG: ::c_int = 184; +pub const _SC_IPV6: ::c_int = 235; +pub const _SC_RAW_SOCKETS: ::c_int = 236; +pub const _SC_V7_ILP32_OFF32: ::c_int = 237; +pub const _SC_V7_ILP32_OFFBIG: ::c_int = 238; +pub const _SC_V7_LP64_OFF64: ::c_int = 239; +pub const _SC_V7_LPBIG_OFFBIG: ::c_int = 240; +pub const _SC_SS_REPL_MAX: ::c_int = 241; +pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 242; +pub const _SC_TRACE_NAME_MAX: ::c_int = 243; +pub const _SC_TRACE_SYS_MAX: ::c_int = 244; +pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 245; +pub const _SC_XOPEN_STREAMS: ::c_int = 246; +pub const _SC_THREAD_ROBUST_PRIO_INHERIT: ::c_int = 247; +pub const _SC_THREAD_ROBUST_PRIO_PROTECT: ::c_int = 248; + +pub const RLIM_SAVED_MAX: ::rlim_t = RLIM_INFINITY; +pub const RLIM_SAVED_CUR: ::rlim_t = RLIM_INFINITY; + +pub const GLOB_ERR: ::c_int = 1 << 0; +pub const GLOB_MARK: ::c_int = 1 << 1; +pub const GLOB_NOSORT: ::c_int = 1 << 2; +pub const GLOB_DOOFFS: ::c_int = 1 << 3; +pub const GLOB_NOCHECK: ::c_int = 1 << 4; +pub const GLOB_APPEND: ::c_int = 1 << 5; +pub const GLOB_NOESCAPE: ::c_int = 1 << 6; + +pub const GLOB_NOSPACE: ::c_int = 1; +pub const GLOB_ABORTED: ::c_int = 2; +pub const GLOB_NOMATCH: ::c_int = 3; + +pub const POSIX_MADV_NORMAL: ::c_int = 0; +pub const POSIX_MADV_RANDOM: ::c_int = 1; +pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_MADV_WILLNEED: ::c_int = 3; + +pub const S_IEXEC: mode_t = 64; +pub const S_IWRITE: mode_t = 128; +pub const S_IREAD: mode_t = 256; + +pub const F_LOCK: ::c_int = 1; +pub const F_TEST: ::c_int = 3; +pub const F_TLOCK: ::c_int = 2; +pub const F_ULOCK: ::c_int = 0; + +pub const ST_RDONLY: ::c_ulong = 1; +pub const ST_NOSUID: ::c_ulong = 2; +pub const ST_NODEV: ::c_ulong = 4; +pub const ST_NOEXEC: ::c_ulong = 8; +pub const ST_SYNCHRONOUS: ::c_ulong = 16; +pub const ST_MANDLOCK: ::c_ulong = 64; +pub const ST_WRITE: ::c_ulong = 128; +pub const ST_APPEND: ::c_ulong = 256; +pub const ST_IMMUTABLE: ::c_ulong = 512; +pub const ST_NOATIME: ::c_ulong = 1024; +pub const ST_NODIRATIME: ::c_ulong = 2048; + +pub const RTLD_NEXT: *mut ::c_void = -1i64 as *mut ::c_void; +pub const RTLD_DEFAULT: *mut ::c_void = 0i64 as *mut ::c_void; +pub const RTLD_NODELETE: ::c_int = 0x1000; +pub const RTLD_NOW: ::c_int = 0x2; + +pub const TCP_MD5SIG: ::c_int = 14; + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_MUTEX_T], +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_COND_T], +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_RWLOCK_T], +}; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; +pub const PTHREAD_PROCESS_PRIVATE: ::c_int = 0; +pub const PTHREAD_PROCESS_SHARED: ::c_int = 1; +pub const __SIZEOF_PTHREAD_COND_T: usize = 48; + +pub const SCHED_OTHER: ::c_int = 0; +pub const SCHED_FIFO: ::c_int = 1; +pub const SCHED_RR: ::c_int = 2; +pub const SCHED_BATCH: ::c_int = 3; +pub const SCHED_IDLE: ::c_int = 5; + +pub const AF_IB: ::c_int = 27; +pub const AF_MPLS: ::c_int = 28; +pub const AF_NFC: ::c_int = 39; +pub const AF_VSOCK: ::c_int = 40; +#[doc(hidden)] +pub const AF_MAX: ::c_int = 42; +pub const PF_IB: ::c_int = AF_IB; +pub const PF_MPLS: ::c_int = AF_MPLS; +pub const PF_NFC: ::c_int = AF_NFC; +pub const PF_VSOCK: ::c_int = AF_VSOCK; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; + +// System V IPC +pub const IPC_PRIVATE: ::key_t = 0; + +pub const IPC_CREAT: ::c_int = 0o1000; +pub const IPC_EXCL: ::c_int = 0o2000; +pub const IPC_NOWAIT: ::c_int = 0o4000; + +pub const IPC_RMID: ::c_int = 0; +pub const IPC_SET: ::c_int = 1; +pub const IPC_STAT: ::c_int = 2; +pub const IPC_INFO: ::c_int = 3; +pub const MSG_STAT: ::c_int = 11; +pub const MSG_INFO: ::c_int = 12; + +pub const MSG_NOERROR: ::c_int = 0o10000; +pub const MSG_EXCEPT: ::c_int = 0o20000; +pub const MSG_COPY: ::c_int = 0o40000; + +pub const SHM_R: ::c_int = 0o400; +pub const SHM_W: ::c_int = 0o200; + +pub const SHM_RDONLY: ::c_int = 0o10000; +pub const SHM_RND: ::c_int = 0o20000; +pub const SHM_REMAP: ::c_int = 0o40000; +pub const SHM_EXEC: ::c_int = 0o100000; + +pub const SHM_LOCK: ::c_int = 11; +pub const SHM_UNLOCK: ::c_int = 12; + +pub const SHM_HUGETLB: ::c_int = 0o4000; +pub const SHM_NORESERVE: ::c_int = 0o10000; + +pub const EPOLLRDHUP: ::c_int = 0x2000; +pub const EPOLLEXCLUSIVE: ::c_int = 0x10000000; +pub const EPOLLONESHOT: ::c_int = 0x40000000; + +pub const QFMT_VFS_OLD: ::c_int = 1; +pub const QFMT_VFS_V0: ::c_int = 2; + +pub const EFD_SEMAPHORE: ::c_int = 0x1; + +pub const LOG_NFACILITIES: ::c_int = 24; + +pub const SEM_FAILED: *mut ::sem_t = 0 as *mut sem_t; + +pub const RB_AUTOBOOT: ::c_int = 0x01234567u32 as i32; +pub const RB_HALT_SYSTEM: ::c_int = 0xcdef0123u32 as i32; +pub const RB_ENABLE_CAD: ::c_int = 0x89abcdefu32 as i32; +pub const RB_DISABLE_CAD: ::c_int = 0x00000000u32 as i32; +pub const RB_POWER_OFF: ::c_int = 0x4321fedcu32 as i32; +pub const RB_SW_SUSPEND: ::c_int = 0xd000fce2u32 as i32; +pub const RB_KEXEC: ::c_int = 0x45584543u32 as i32; + +pub const AI_PASSIVE: ::c_int = 0x0001; +pub const AI_CANONNAME: ::c_int = 0x0002; +pub const AI_NUMERICHOST: ::c_int = 0x0004; +pub const AI_V4MAPPED: ::c_int = 0x0008; +pub const AI_ALL: ::c_int = 0x0010; +pub const AI_ADDRCONFIG: ::c_int = 0x0020; + +pub const AI_NUMERICSERV: ::c_int = 0x0400; + +pub const EAI_BADFLAGS: ::c_int = -1; +pub const EAI_NONAME: ::c_int = -2; +pub const EAI_AGAIN: ::c_int = -3; +pub const EAI_FAIL: ::c_int = -4; +pub const EAI_FAMILY: ::c_int = -6; +pub const EAI_SOCKTYPE: ::c_int = -7; +pub const EAI_SERVICE: ::c_int = -8; +pub const EAI_MEMORY: ::c_int = -10; +pub const EAI_OVERFLOW: ::c_int = -12; + +pub const NI_NUMERICHOST: ::c_int = 1; +pub const NI_NUMERICSERV: ::c_int = 2; +pub const NI_NOFQDN: ::c_int = 4; +pub const NI_NAMEREQD: ::c_int = 8; +pub const NI_DGRAM: ::c_int = 16; + +pub const SYNC_FILE_RANGE_WAIT_BEFORE: ::c_uint = 1; +pub const SYNC_FILE_RANGE_WRITE: ::c_uint = 2; +pub const SYNC_FILE_RANGE_WAIT_AFTER: ::c_uint = 4; + +pub const EAI_SYSTEM: ::c_int = -11; + +pub const AIO_CANCELED: ::c_int = 0; +pub const AIO_NOTCANCELED: ::c_int = 1; +pub const AIO_ALLDONE: ::c_int = 2; +pub const LIO_READ: ::c_int = 0; +pub const LIO_WRITE: ::c_int = 1; +pub const LIO_NOP: ::c_int = 2; +pub const LIO_WAIT: ::c_int = 0; +pub const LIO_NOWAIT: ::c_int = 1; + +pub const MREMAP_MAYMOVE: ::c_int = 1; +pub const MREMAP_FIXED: ::c_int = 2; + +pub const PR_SET_PDEATHSIG: ::c_int = 1; +pub const PR_GET_PDEATHSIG: ::c_int = 2; + +pub const PR_GET_DUMPABLE: ::c_int = 3; +pub const PR_SET_DUMPABLE: ::c_int = 4; + +pub const PR_GET_UNALIGN: ::c_int = 5; +pub const PR_SET_UNALIGN: ::c_int = 6; +pub const PR_UNALIGN_NOPRINT: ::c_int = 1; +pub const PR_UNALIGN_SIGBUS: ::c_int = 2; + +pub const PR_GET_KEEPCAPS: ::c_int = 7; +pub const PR_SET_KEEPCAPS: ::c_int = 8; + +pub const PR_GET_FPEMU: ::c_int = 9; +pub const PR_SET_FPEMU: ::c_int = 10; +pub const PR_FPEMU_NOPRINT: ::c_int = 1; +pub const PR_FPEMU_SIGFPE: ::c_int = 2; + +pub const PR_GET_FPEXC: ::c_int = 11; +pub const PR_SET_FPEXC: ::c_int = 12; +pub const PR_FP_EXC_SW_ENABLE: ::c_int = 0x80; +pub const PR_FP_EXC_DIV: ::c_int = 0x010000; +pub const PR_FP_EXC_OVF: ::c_int = 0x020000; +pub const PR_FP_EXC_UND: ::c_int = 0x040000; +pub const PR_FP_EXC_RES: ::c_int = 0x080000; +pub const PR_FP_EXC_INV: ::c_int = 0x100000; +pub const PR_FP_EXC_DISABLED: ::c_int = 0; +pub const PR_FP_EXC_NONRECOV: ::c_int = 1; +pub const PR_FP_EXC_ASYNC: ::c_int = 2; +pub const PR_FP_EXC_PRECISE: ::c_int = 3; + +pub const PR_GET_TIMING: ::c_int = 13; +pub const PR_SET_TIMING: ::c_int = 14; +pub const PR_TIMING_STATISTICAL: ::c_int = 0; +pub const PR_TIMING_TIMESTAMP: ::c_int = 1; + +pub const PR_SET_NAME: ::c_int = 15; +pub const PR_GET_NAME: ::c_int = 16; + +pub const PR_GET_ENDIAN: ::c_int = 19; +pub const PR_SET_ENDIAN: ::c_int = 20; +pub const PR_ENDIAN_BIG: ::c_int = 0; +pub const PR_ENDIAN_LITTLE: ::c_int = 1; +pub const PR_ENDIAN_PPC_LITTLE: ::c_int = 2; + +pub const PR_GET_SECCOMP: ::c_int = 21; +pub const PR_SET_SECCOMP: ::c_int = 22; + +pub const PR_CAPBSET_READ: ::c_int = 23; +pub const PR_CAPBSET_DROP: ::c_int = 24; + +pub const PR_GET_TSC: ::c_int = 25; +pub const PR_SET_TSC: ::c_int = 26; +pub const PR_TSC_ENABLE: ::c_int = 1; +pub const PR_TSC_SIGSEGV: ::c_int = 2; + +pub const PR_GET_SECUREBITS: ::c_int = 27; +pub const PR_SET_SECUREBITS: ::c_int = 28; + +pub const PR_SET_TIMERSLACK: ::c_int = 29; +pub const PR_GET_TIMERSLACK: ::c_int = 30; + +pub const PR_TASK_PERF_EVENTS_DISABLE: ::c_int = 31; +pub const PR_TASK_PERF_EVENTS_ENABLE: ::c_int = 32; + +pub const PR_MCE_KILL: ::c_int = 33; +pub const PR_MCE_KILL_CLEAR: ::c_int = 0; +pub const PR_MCE_KILL_SET: ::c_int = 1; + +pub const PR_MCE_KILL_LATE: ::c_int = 0; +pub const PR_MCE_KILL_EARLY: ::c_int = 1; +pub const PR_MCE_KILL_DEFAULT: ::c_int = 2; + +pub const PR_MCE_KILL_GET: ::c_int = 34; + +pub const PR_SET_MM: ::c_int = 35; +pub const PR_SET_MM_START_CODE: ::c_int = 1; +pub const PR_SET_MM_END_CODE: ::c_int = 2; +pub const PR_SET_MM_START_DATA: ::c_int = 3; +pub const PR_SET_MM_END_DATA: ::c_int = 4; +pub const PR_SET_MM_START_STACK: ::c_int = 5; +pub const PR_SET_MM_START_BRK: ::c_int = 6; +pub const PR_SET_MM_BRK: ::c_int = 7; +pub const PR_SET_MM_ARG_START: ::c_int = 8; +pub const PR_SET_MM_ARG_END: ::c_int = 9; +pub const PR_SET_MM_ENV_START: ::c_int = 10; +pub const PR_SET_MM_ENV_END: ::c_int = 11; +pub const PR_SET_MM_AUXV: ::c_int = 12; +pub const PR_SET_MM_EXE_FILE: ::c_int = 13; +pub const PR_SET_MM_MAP: ::c_int = 14; +pub const PR_SET_MM_MAP_SIZE: ::c_int = 15; + +pub const PR_SET_PTRACER: ::c_int = 0x59616d61; + +pub const PR_SET_CHILD_SUBREAPER: ::c_int = 36; +pub const PR_GET_CHILD_SUBREAPER: ::c_int = 37; + +pub const PR_SET_NO_NEW_PRIVS: ::c_int = 38; +pub const PR_GET_NO_NEW_PRIVS: ::c_int = 39; + +pub const PR_GET_TID_ADDRESS: ::c_int = 40; + +pub const PR_SET_THP_DISABLE: ::c_int = 41; +pub const PR_GET_THP_DISABLE: ::c_int = 42; + +pub const PR_MPX_ENABLE_MANAGEMENT: ::c_int = 43; +pub const PR_MPX_DISABLE_MANAGEMENT: ::c_int = 44; + +pub const PR_SET_FP_MODE: ::c_int = 45; +pub const PR_GET_FP_MODE: ::c_int = 46; +pub const PR_FP_MODE_FR: ::c_int = 1 << 0; +pub const PR_FP_MODE_FRE: ::c_int = 1 << 1; + +pub const PR_CAP_AMBIENT: ::c_int = 47; +pub const PR_CAP_AMBIENT_IS_SET: ::c_int = 1; +pub const PR_CAP_AMBIENT_RAISE: ::c_int = 2; +pub const PR_CAP_AMBIENT_LOWER: ::c_int = 3; +pub const PR_CAP_AMBIENT_CLEAR_ALL: ::c_int = 4; + +pub const ITIMER_REAL: ::c_int = 0; +pub const ITIMER_VIRTUAL: ::c_int = 1; +pub const ITIMER_PROF: ::c_int = 2; + +pub const XATTR_CREATE: ::c_int = 0x1; +pub const XATTR_REPLACE: ::c_int = 0x2; + +pub const _POSIX_VDISABLE: ::cc_t = 0; + +pub const FALLOC_FL_KEEP_SIZE: ::c_int = 0x01; +pub const FALLOC_FL_PUNCH_HOLE: ::c_int = 0x02; +pub const FALLOC_FL_COLLAPSE_RANGE: ::c_int = 0x08; +pub const FALLOC_FL_ZERO_RANGE: ::c_int = 0x10; +pub const FALLOC_FL_INSERT_RANGE: ::c_int = 0x20; +pub const FALLOC_FL_UNSHARE_RANGE: ::c_int = 0x40; + +// On Linux, libc doesn't define this constant, libattr does instead. +// We still define it for Linux as it's defined by libc on other platforms, +// and it's mentioned in the man pages for getxattr and setxattr. +pub const SFD_CLOEXEC: ::c_int = 0x080000; + +pub const NCCS: usize = 32; + +pub const O_TRUNC: ::c_int = 512; +pub const O_NOATIME: ::c_int = 0o1000000; +pub const O_CLOEXEC: ::c_int = 0x80000; + +pub const EBFONT: ::c_int = 59; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const EDOTDOT: ::c_int = 73; + +pub const SA_NODEFER: ::c_int = 0x40000000; +pub const SA_RESETHAND: ::c_int = 0x80000000; +pub const SA_RESTART: ::c_int = 0x10000000; +pub const SA_NOCLDSTOP: ::c_int = 0x00000001; + +pub const EPOLL_CLOEXEC: ::c_int = 0x80000; + +pub const EFD_CLOEXEC: ::c_int = 0x80000; + +pub const BUFSIZ: ::c_uint = 1024; +pub const TMP_MAX: ::c_uint = 10000; +pub const FOPEN_MAX: ::c_uint = 1000; +pub const O_PATH: ::c_int = 0o10000000; +pub const O_EXEC: ::c_int = 0o10000000; +pub const O_SEARCH: ::c_int = 0o10000000; +pub const O_ACCMODE: ::c_int = 0o10000003; +pub const O_NDELAY: ::c_int = O_NONBLOCK; +pub const NI_MAXHOST: ::socklen_t = 255; +pub const PTHREAD_STACK_MIN: ::size_t = 2048; +pub const POSIX_FADV_DONTNEED: ::c_int = 4; +pub const POSIX_FADV_NOREUSE: ::c_int = 5; + +pub const POSIX_MADV_DONTNEED: ::c_int = 0; + +pub const RLIM_INFINITY: ::rlim_t = !0; +pub const RLIMIT_RTTIME: ::c_int = 15; +pub const RLIMIT_NLIMITS: ::c_int = 16; + +pub const MAP_ANONYMOUS: ::c_int = MAP_ANON; + +pub const TCP_COOKIE_TRANSACTIONS: ::c_int = 15; +pub const TCP_THIN_LINEAR_TIMEOUTS: ::c_int = 16; +pub const TCP_THIN_DUPACK: ::c_int = 17; +pub const TCP_USER_TIMEOUT: ::c_int = 18; +pub const TCP_REPAIR: ::c_int = 19; +pub const TCP_REPAIR_QUEUE: ::c_int = 20; +pub const TCP_QUEUE_SEQ: ::c_int = 21; +pub const TCP_REPAIR_OPTIONS: ::c_int = 22; +pub const TCP_FASTOPEN: ::c_int = 23; +pub const TCP_TIMESTAMP: ::c_int = 24; + +pub const SIGUNUSED: ::c_int = ::SIGSYS; + +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; + +pub const CPU_SETSIZE: ::c_int = 128; + +pub const QFMT_VFS_V1: ::c_int = 4; + +pub const PTRACE_TRACEME: ::c_int = 0; +pub const PTRACE_PEEKTEXT: ::c_int = 1; +pub const PTRACE_PEEKDATA: ::c_int = 2; +pub const PTRACE_PEEKUSER: ::c_int = 3; +pub const PTRACE_POKETEXT: ::c_int = 4; +pub const PTRACE_POKEDATA: ::c_int = 5; +pub const PTRACE_POKEUSER: ::c_int = 6; +pub const PTRACE_CONT: ::c_int = 7; +pub const PTRACE_KILL: ::c_int = 8; +pub const PTRACE_SINGLESTEP: ::c_int = 9; +pub const PTRACE_ATTACH: ::c_int = 16; +pub const PTRACE_DETACH: ::c_int = 17; +pub const PTRACE_SYSCALL: ::c_int = 24; +pub const PTRACE_SETOPTIONS: ::c_int = 0x4200; +pub const PTRACE_GETEVENTMSG: ::c_int = 0x4201; +pub const PTRACE_GETSIGINFO: ::c_int = 0x4202; +pub const PTRACE_SETSIGINFO: ::c_int = 0x4203; +pub const PTRACE_GETREGSET: ::c_int = 0x4204; +pub const PTRACE_SETREGSET: ::c_int = 0x4205; +pub const PTRACE_SEIZE: ::c_int = 0x4206; +pub const PTRACE_INTERRUPT: ::c_int = 0x4207; +pub const PTRACE_LISTEN: ::c_int = 0x4208; +pub const PTRACE_PEEKSIGINFO: ::c_int = 0x4209; + +pub const EPOLLWAKEUP: ::c_int = 0x20000000; + +pub const PTRACE_GETFPREGS: ::c_uint = 14; +pub const PTRACE_SETFPREGS: ::c_uint = 15; +pub const PTRACE_GETFPXREGS: ::c_uint = 18; +pub const PTRACE_SETFPXREGS: ::c_uint = 19; +pub const PTRACE_GETREGS: ::c_uint = 12; +pub const PTRACE_SETREGS: ::c_uint = 13; + +pub const EFD_NONBLOCK: ::c_int = ::O_NONBLOCK; + +pub const SFD_NONBLOCK: ::c_int = ::O_NONBLOCK; + +pub const TCSANOW: ::c_int = 0; +pub const TCSADRAIN: ::c_int = 1; +pub const TCSAFLUSH: ::c_int = 2; + +pub const TIOCINQ: ::c_int = ::FIONREAD; + +pub const RTLD_GLOBAL: ::c_int = 0x100; +pub const RTLD_NOLOAD: ::c_int = 0x4; + +// TODO(#247) Temporarily musl-specific (available since musl 0.9.12 / Linux +// kernel 3.10). See also notbsd/mod.rs +pub const CLOCK_SGI_CYCLE: ::clockid_t = 10; +pub const CLOCK_TAI: ::clockid_t = 11; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const SIGSTKSZ: ::size_t = 8192; +pub const MINSIGSTKSZ: ::size_t = 2048; +pub const CBAUD: ::tcflag_t = 0o0010017; +pub const TAB1: ::c_int = 0x00000800; +pub const TAB2: ::c_int = 0x00001000; +pub const TAB3: ::c_int = 0x00001800; +pub const CR1: ::c_int = 0x00000200; +pub const CR2: ::c_int = 0x00000400; +pub const CR3: ::c_int = 0x00000600; +pub const FF1: ::c_int = 0x00008000; +pub const BS1: ::c_int = 0x00002000; +pub const VT1: ::c_int = 0x00004000; +pub const VWERASE: usize = 14; +pub const VREPRINT: usize = 12; +pub const VSUSP: usize = 10; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VDISCARD: usize = 13; +pub const VTIME: usize = 5; +pub const IXON: ::tcflag_t = 0x00000400; +pub const IXOFF: ::tcflag_t = 0x00001000; +pub const ONLCR: ::tcflag_t = 0x4; +pub const CSIZE: ::tcflag_t = 0x00000030; +pub const CS6: ::tcflag_t = 0x00000010; +pub const CS7: ::tcflag_t = 0x00000020; +pub const CS8: ::tcflag_t = 0x00000030; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const ECHOKE: ::tcflag_t = 0x00000800; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const ECHOPRT: ::tcflag_t = 0x00000400; +pub const ECHOCTL: ::tcflag_t = 0x00000200; +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const PENDIN: ::tcflag_t = 0x00004000; +pub const NOFLSH: ::tcflag_t = 0x00000080; +pub const CBAUDEX: ::tcflag_t = 0o010000; +pub const VSWTC: usize = 7; +pub const OLCUC: ::tcflag_t = 0o000002; +pub const NLDLY: ::tcflag_t = 0o000400; +pub const CRDLY: ::tcflag_t = 0o003000; +pub const TABDLY: ::tcflag_t = 0o014000; +pub const BSDLY: ::tcflag_t = 0o020000; +pub const FFDLY: ::tcflag_t = 0o100000; +pub const VTDLY: ::tcflag_t = 0o040000; +pub const XTABS: ::tcflag_t = 0o014000; + +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const B57600: ::speed_t = 0o010001; +pub const B115200: ::speed_t = 0o010002; +pub const B230400: ::speed_t = 0o010003; +pub const B460800: ::speed_t = 0o010004; +pub const B500000: ::speed_t = 0o010005; +pub const B576000: ::speed_t = 0o010006; +pub const B921600: ::speed_t = 0o010007; +pub const B1000000: ::speed_t = 0o010010; +pub const B1152000: ::speed_t = 0o010011; +pub const B1500000: ::speed_t = 0o010012; +pub const B2000000: ::speed_t = 0o010013; +pub const B2500000: ::speed_t = 0o010014; +pub const B3000000: ::speed_t = 0o010015; +pub const B3500000: ::speed_t = 0o010016; +pub const B4000000: ::speed_t = 0o010017; + +pub const SO_BINDTODEVICE: ::c_int = 25; +pub const SO_TIMESTAMP: ::c_int = 29; +pub const SO_MARK: ::c_int = 36; +pub const SO_RXQ_OVFL: ::c_int = 40; +pub const SO_PEEK_OFF: ::c_int = 42; +pub const SO_BUSY_POLL: ::c_int = 46; + +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 32; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 28; + +pub const O_DIRECT: ::c_int = 0x4000; +pub const O_DIRECTORY: ::c_int = 0x10000; +pub const O_NOFOLLOW: ::c_int = 0x20000; +pub const O_ASYNC: ::c_int = 0x2000; + +pub const FIOCLEX: ::c_int = 0x5451; +pub const FIONBIO: ::c_int = 0x5421; + +pub const RLIMIT_RSS: ::c_int = 5; +pub const RLIMIT_NOFILE: ::c_int = 7; +pub const RLIMIT_AS: ::c_int = 9; +pub const RLIMIT_NPROC: ::c_int = 6; +pub const RLIMIT_MEMLOCK: ::c_int = 8; + +pub const O_APPEND: ::c_int = 1024; +pub const O_CREAT: ::c_int = 64; +pub const O_EXCL: ::c_int = 128; +pub const O_NOCTTY: ::c_int = 256; +pub const O_NONBLOCK: ::c_int = 2048; +pub const O_SYNC: ::c_int = 1052672; +pub const O_RSYNC: ::c_int = 1052672; +pub const O_DSYNC: ::c_int = 4096; + +pub const SOCK_NONBLOCK: ::c_int = 2048; + +pub const MAP_ANON: ::c_int = 0x0020; +pub const MAP_GROWSDOWN: ::c_int = 0x0100; +pub const MAP_DENYWRITE: ::c_int = 0x0800; +pub const MAP_EXECUTABLE: ::c_int = 0x01000; +pub const MAP_LOCKED: ::c_int = 0x02000; +pub const MAP_NORESERVE: ::c_int = 0x04000; +pub const MAP_POPULATE: ::c_int = 0x08000; +pub const MAP_NONBLOCK: ::c_int = 0x010000; +pub const MAP_STACK: ::c_int = 0x020000; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_SEQPACKET: ::c_int = 5; + +pub const SOL_SOCKET: ::c_int = 1; + +pub const EDEADLK: ::c_int = 35; +pub const ENAMETOOLONG: ::c_int = 36; +pub const ENOLCK: ::c_int = 37; +pub const ENOSYS: ::c_int = 38; +pub const ENOTEMPTY: ::c_int = 39; +pub const ELOOP: ::c_int = 40; +pub const ENOMSG: ::c_int = 42; +pub const EIDRM: ::c_int = 43; +pub const ECHRNG: ::c_int = 44; +pub const EL2NSYNC: ::c_int = 45; +pub const EL3HLT: ::c_int = 46; +pub const EL3RST: ::c_int = 47; +pub const ELNRNG: ::c_int = 48; +pub const EUNATCH: ::c_int = 49; +pub const ENOCSI: ::c_int = 50; +pub const EL2HLT: ::c_int = 51; +pub const EBADE: ::c_int = 52; +pub const EBADR: ::c_int = 53; +pub const EXFULL: ::c_int = 54; +pub const ENOANO: ::c_int = 55; +pub const EBADRQC: ::c_int = 56; +pub const EBADSLT: ::c_int = 57; +pub const EDEADLOCK: ::c_int = EDEADLK; +pub const EMULTIHOP: ::c_int = 72; +pub const EBADMSG: ::c_int = 74; +pub const EOVERFLOW: ::c_int = 75; +pub const ENOTUNIQ: ::c_int = 76; +pub const EBADFD: ::c_int = 77; +pub const EREMCHG: ::c_int = 78; +pub const ELIBACC: ::c_int = 79; +pub const ELIBBAD: ::c_int = 80; +pub const ELIBSCN: ::c_int = 81; +pub const ELIBMAX: ::c_int = 82; +pub const ELIBEXEC: ::c_int = 83; +pub const EILSEQ: ::c_int = 84; +pub const ERESTART: ::c_int = 85; +pub const ESTRPIPE: ::c_int = 86; +pub const EUSERS: ::c_int = 87; +pub const ENOTSOCK: ::c_int = 88; +pub const EDESTADDRREQ: ::c_int = 89; +pub const EMSGSIZE: ::c_int = 90; +pub const EPROTOTYPE: ::c_int = 91; +pub const ENOPROTOOPT: ::c_int = 92; +pub const EPROTONOSUPPORT: ::c_int = 93; +pub const ESOCKTNOSUPPORT: ::c_int = 94; +pub const EOPNOTSUPP: ::c_int = 95; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; +pub const EPFNOSUPPORT: ::c_int = 96; +pub const EAFNOSUPPORT: ::c_int = 97; +pub const EADDRINUSE: ::c_int = 98; +pub const EADDRNOTAVAIL: ::c_int = 99; +pub const ENETDOWN: ::c_int = 100; +pub const ENETUNREACH: ::c_int = 101; +pub const ENETRESET: ::c_int = 102; +pub const ECONNABORTED: ::c_int = 103; +pub const ECONNRESET: ::c_int = 104; +pub const ENOBUFS: ::c_int = 105; +pub const EISCONN: ::c_int = 106; +pub const ENOTCONN: ::c_int = 107; +pub const ESHUTDOWN: ::c_int = 108; +pub const ETOOMANYREFS: ::c_int = 109; +pub const ETIMEDOUT: ::c_int = 110; +pub const ECONNREFUSED: ::c_int = 111; +pub const EHOSTDOWN: ::c_int = 112; +pub const EHOSTUNREACH: ::c_int = 113; +pub const EALREADY: ::c_int = 114; +pub const EINPROGRESS: ::c_int = 115; +pub const ESTALE: ::c_int = 116; +pub const EUCLEAN: ::c_int = 117; +pub const ENOTNAM: ::c_int = 118; +pub const ENAVAIL: ::c_int = 119; +pub const EISNAM: ::c_int = 120; +pub const EREMOTEIO: ::c_int = 121; +pub const EDQUOT: ::c_int = 122; +pub const ENOMEDIUM: ::c_int = 123; +pub const EMEDIUMTYPE: ::c_int = 124; +pub const ECANCELED: ::c_int = 125; +pub const ENOKEY: ::c_int = 126; +pub const EKEYEXPIRED: ::c_int = 127; +pub const EKEYREVOKED: ::c_int = 128; +pub const EKEYREJECTED: ::c_int = 129; +pub const EOWNERDEAD: ::c_int = 130; +pub const ENOTRECOVERABLE: ::c_int = 131; +pub const ERFKILL: ::c_int = 132; +pub const EHWPOISON: ::c_int = 133; + +pub const SO_REUSEADDR: ::c_int = 2; +pub const SO_TYPE: ::c_int = 3; +pub const SO_ERROR: ::c_int = 4; +pub const SO_DONTROUTE: ::c_int = 5; +pub const SO_BROADCAST: ::c_int = 6; +pub const SO_SNDBUF: ::c_int = 7; +pub const SO_RCVBUF: ::c_int = 8; +pub const SO_KEEPALIVE: ::c_int = 9; +pub const SO_OOBINLINE: ::c_int = 10; +pub const SO_LINGER: ::c_int = 13; +pub const SO_REUSEPORT: ::c_int = 15; +pub const SO_RCVLOWAT: ::c_int = 18; +pub const SO_SNDLOWAT: ::c_int = 19; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_SNDTIMEO: ::c_int = 21; +pub const SO_ACCEPTCONN: ::c_int = 30; + +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 0x00000004; +pub const SA_NOCLDWAIT: ::c_int = 0x00000002; + +pub const SIGCHLD: ::c_int = 17; +pub const SIGBUS: ::c_int = 7; +pub const SIGTTIN: ::c_int = 21; +pub const SIGTTOU: ::c_int = 22; +pub const SIGXCPU: ::c_int = 24; +pub const SIGXFSZ: ::c_int = 25; +pub const SIGVTALRM: ::c_int = 26; +pub const SIGPROF: ::c_int = 27; +pub const SIGWINCH: ::c_int = 28; +pub const SIGUSR1: ::c_int = 10; +pub const SIGUSR2: ::c_int = 12; +pub const SIGCONT: ::c_int = 18; +pub const SIGSTOP: ::c_int = 19; +pub const SIGTSTP: ::c_int = 20; +pub const SIGURG: ::c_int = 23; +pub const SIGIO: ::c_int = 29; +pub const SIGSYS: ::c_int = 31; +pub const SIGSTKFLT: ::c_int = 16; +pub const SIGPOLL: ::c_int = 29; +pub const SIGPWR: ::c_int = 30; +pub const SIG_SETMASK: ::c_int = 2; +pub const SIG_BLOCK: ::c_int = 0x000000; +pub const SIG_UNBLOCK: ::c_int = 0x01; + +pub const EXTPROC: ::tcflag_t = 0x00010000; + +pub const MAP_HUGETLB: ::c_int = 0x040000; + +pub const F_GETLK: ::c_int = 12; +pub const F_GETOWN: ::c_int = 9; +pub const F_SETLK: ::c_int = 13; +pub const F_SETLKW: ::c_int = 14; +pub const F_SETOWN: ::c_int = 8; + +pub const VEOF: usize = 4; +pub const VEOL: usize = 11; +pub const VEOL2: usize = 16; +pub const VMIN: usize = 6; +pub const IEXTEN: ::tcflag_t = 0x00008000; +pub const TOSTOP: ::tcflag_t = 0x00000100; +pub const FLUSHO: ::tcflag_t = 0x00001000; + +pub const TCGETS: ::c_int = 0x5401; +pub const TCSETS: ::c_int = 0x5402; +pub const TCSETSW: ::c_int = 0x5403; +pub const TCSETSF: ::c_int = 0x5404; +pub const TCGETA: ::c_int = 0x5405; +pub const TCSETA: ::c_int = 0x5406; +pub const TCSETAW: ::c_int = 0x5407; +pub const TCSETAF: ::c_int = 0x5408; +pub const TCSBRK: ::c_int = 0x5409; +pub const TCXONC: ::c_int = 0x540A; +pub const TCFLSH: ::c_int = 0x540B; +pub const TIOCGSOFTCAR: ::c_int = 0x5419; +pub const TIOCSSOFTCAR: ::c_int = 0x541A; +pub const TIOCLINUX: ::c_int = 0x541C; +pub const TIOCGSERIAL: ::c_int = 0x541E; +pub const TIOCEXCL: ::c_int = 0x540C; +pub const TIOCNXCL: ::c_int = 0x540D; +pub const TIOCSCTTY: ::c_int = 0x540E; +pub const TIOCGPGRP: ::c_int = 0x540F; +pub const TIOCSPGRP: ::c_int = 0x5410; +pub const TIOCOUTQ: ::c_int = 0x5411; +pub const TIOCSTI: ::c_int = 0x5412; +pub const TIOCGWINSZ: ::c_int = 0x5413; +pub const TIOCSWINSZ: ::c_int = 0x5414; +pub const TIOCMGET: ::c_int = 0x5415; +pub const TIOCMBIS: ::c_int = 0x5416; +pub const TIOCMBIC: ::c_int = 0x5417; +pub const TIOCMSET: ::c_int = 0x5418; +pub const FIONREAD: ::c_int = 0x541B; +pub const TIOCCONS: ::c_int = 0x541D; + +pub const SYS_gettid: ::c_long = 224; // Valid for arm (32-bit) and x86 (32-bit) + +pub const POLLWRNORM: ::c_short = 0x100; +pub const POLLWRBAND: ::c_short = 0x200; + +pub const TIOCM_LE: ::c_int = 0x001; +pub const TIOCM_DTR: ::c_int = 0x002; +pub const TIOCM_RTS: ::c_int = 0x004; +pub const TIOCM_ST: ::c_int = 0x008; +pub const TIOCM_SR: ::c_int = 0x010; +pub const TIOCM_CTS: ::c_int = 0x020; +pub const TIOCM_CAR: ::c_int = 0x040; +pub const TIOCM_RNG: ::c_int = 0x080; +pub const TIOCM_DSR: ::c_int = 0x100; +pub const TIOCM_CD: ::c_int = TIOCM_CAR; +pub const TIOCM_RI: ::c_int = TIOCM_RNG; +pub const O_TMPFILE: ::c_int = 0x400000; + +f! { + pub fn CPU_ZERO(cpuset: &mut cpu_set_t) -> () { + for slot in cpuset.bits.iter_mut() { + *slot = 0; + } + } + + pub fn CPU_SET(cpu: usize, cpuset: &mut cpu_set_t) -> () { + let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc + let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); + cpuset.bits[idx] |= 1 << offset; + () + } + + pub fn CPU_CLR(cpu: usize, cpuset: &mut cpu_set_t) -> () { + let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc + let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); + cpuset.bits[idx] &= !(1 << offset); + () + } + + pub fn CPU_ISSET(cpu: usize, cpuset: &cpu_set_t) -> bool { + let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); + let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); + 0 != (cpuset.bits[idx] & (1 << offset)) + } + + pub fn CPU_EQUAL(set1: &cpu_set_t, set2: &cpu_set_t) -> bool { + set1.bits == set2.bits + } + + pub fn major(dev: ::dev_t) -> ::c_uint { + // see + // https://github.com/kripken/emscripten/blob/ + // master/system/include/libc/sys/sysmacros.h + let mut major = 0; + major |= (dev & 0x00000fff) >> 8; + major |= (dev & 0xfffff000) >> 31 >> 1; + major as ::c_uint + } + + pub fn minor(dev: ::dev_t) -> ::c_uint { + // see + // https://github.com/kripken/emscripten/blob/ + // master/system/include/libc/sys/sysmacros.h + let mut minor = 0; + minor |= (dev & 0x000000ff) >> 0; + minor |= (dev & 0xffffff00) >> 12; + minor as ::c_uint + } + + pub fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + let mut dev = 0; + dev |= (major & 0x00000fff) << 8; + dev |= (major & 0xfffff000) << 31 << 1; + dev |= (minor & 0x000000ff) << 0; + dev |= (minor & 0xffffff00) << 12; + dev + } +} + +extern { + pub fn setpwent(); + pub fn endpwent(); + pub fn getpwent() -> *mut passwd; + + pub fn shm_open(name: *const c_char, oflag: ::c_int, + mode: mode_t) -> ::c_int; + + pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) + -> ::c_int; + pub fn __errno_location() -> *mut ::c_int; + + pub fn fopen64(filename: *const c_char, + mode: *const c_char) -> *mut ::FILE; + pub fn freopen64(filename: *const c_char, mode: *const c_char, + file: *mut ::FILE) -> *mut ::FILE; + pub fn tmpfile64() -> *mut ::FILE; + pub fn fgetpos64(stream: *mut ::FILE, ptr: *mut fpos64_t) -> ::c_int; + pub fn fsetpos64(stream: *mut ::FILE, ptr: *const fpos64_t) -> ::c_int; + pub fn fseeko64(stream: *mut ::FILE, + offset: ::off64_t, + whence: ::c_int) -> ::c_int; + pub fn ftello64(stream: *mut ::FILE) -> ::off64_t; + pub fn posix_fallocate(fd: ::c_int, offset: ::off_t, + len: ::off_t) -> ::c_int; + pub fn pwritev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off_t) -> ::ssize_t; + pub fn preadv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off_t) -> ::ssize_t; + pub fn dup3(oldfd: ::c_int, newfd: ::c_int, flags: ::c_int) -> ::c_int; + pub fn mkostemp(template: *mut ::c_char, flags: ::c_int) -> ::c_int; + pub fn mkostemps(template: *mut ::c_char, + suffixlen: ::c_int, + flags: ::c_int) -> ::c_int; + pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; + pub fn getnameinfo(sa: *const ::sockaddr, + salen: ::socklen_t, + host: *mut ::c_char, + hostlen: ::socklen_t, + serv: *mut ::c_char, + sevlen: ::socklen_t, + flags: ::c_int) -> ::c_int; + pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int; + + // Not available now on Android + pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t) -> ::c_int; + pub fn if_nameindex() -> *mut if_nameindex; + pub fn if_freenameindex(ptr: *mut if_nameindex); + pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; + pub fn freeifaddrs(ifa: *mut ::ifaddrs); + + pub fn mremap(addr: *mut ::c_void, + len: ::size_t, + new_len: ::size_t, + flags: ::c_int, + ...) -> *mut ::c_void; + + pub fn glob(pattern: *const c_char, + flags: ::c_int, + errfunc: Option ::c_int>, + pglob: *mut ::glob_t) -> ::c_int; + pub fn globfree(pglob: *mut ::glob_t); + + pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + pub fn shm_unlink(name: *const ::c_char) -> ::c_int; + + pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); + + pub fn telldir(dirp: *mut ::DIR) -> ::c_long; + pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; + + pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, + flags: ::c_int, addr: *mut ::sockaddr, + addrlen: *mut ::socklen_t) -> ::ssize_t; + pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; + pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; + + pub fn bind(socket: ::c_int, address: *const ::sockaddr, + address_len: ::socklen_t) -> ::c_int; + + pub fn writev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + pub fn readv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + + pub fn sendmsg(fd: ::c_int, + msg: *const ::msghdr, + flags: ::c_int) -> ::ssize_t; + pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) + -> ::ssize_t; + pub fn getdomainname(name: *mut ::c_char, len: ::size_t) -> ::c_int; + pub fn setdomainname(name: *const ::c_char, len: ::size_t) -> ::c_int; + pub fn sendmmsg(sockfd: ::c_int, msgvec: *mut mmsghdr, vlen: ::c_uint, + flags: ::c_int) -> ::c_int; + pub fn recvmmsg(sockfd: ::c_int, msgvec: *mut mmsghdr, vlen: ::c_uint, + flags: ::c_int, timeout: *mut ::timespec) -> ::c_int; + pub fn sync(); + pub fn ioctl(fd: ::c_int, request: ::c_int, ...) -> ::c_int; + pub fn getpriority(which: ::c_int, who: ::id_t) -> ::c_int; + pub fn setpriority(which: ::c_int, who: ::id_t, prio: ::c_int) -> ::c_int; + pub fn pthread_create(native: *mut ::pthread_t, + attr: *const ::pthread_attr_t, + f: extern fn(*mut ::c_void) -> *mut ::c_void, + value: *mut ::c_void) -> ::c_int; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mips/mips32.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mips/mips32.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mips/mips32.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mips/mips32.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,637 @@ +pub type c_char = i8; +pub type c_long = i32; +pub type c_ulong = u32; +pub type clock_t = i32; +pub type time_t = i32; +pub type suseconds_t = i32; +pub type wchar_t = i32; +pub type off_t = i32; +pub type ino_t = u32; +pub type blkcnt_t = i32; +pub type blksize_t = i32; +pub type nlink_t = u32; +pub type __u64 = ::c_ulonglong; + +s! { + pub struct aiocb { + pub aio_fildes: ::c_int, + pub aio_lio_opcode: ::c_int, + pub aio_reqprio: ::c_int, + pub aio_buf: *mut ::c_void, + pub aio_nbytes: ::size_t, + pub aio_sigevent: ::sigevent, + __next_prio: *mut aiocb, + __abs_prio: ::c_int, + __policy: ::c_int, + __error_code: ::c_int, + __return_value: ::ssize_t, + pub aio_offset: off_t, + __unused1: [::c_char; 4], + __glibc_reserved: [::c_char; 32] + } + + pub struct stat { + pub st_dev: ::c_ulong, + st_pad1: [::c_long; 3], + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::c_ulong, + pub st_pad2: [::c_long; 2], + pub st_size: ::off_t, + st_pad3: ::c_long, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + st_pad5: [::c_long; 14], + } + + pub struct stat64 { + pub st_dev: ::c_ulong, + st_pad1: [::c_long; 3], + pub st_ino: ::ino64_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::c_ulong, + st_pad2: [::c_long; 2], + pub st_size: ::off64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + st_pad3: ::c_long, + pub st_blocks: ::blkcnt64_t, + st_pad5: [::c_long; 14], + } + + pub struct statfs64 { + pub f_type: ::c_long, + pub f_bsize: ::c_long, + pub f_frsize: ::c_long, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_bavail: u64, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_long, + pub f_flags: ::c_long, + pub f_spare: [::c_long; 5], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + #[cfg(target_endian = "little")] + pub f_fsid: ::c_ulong, + __f_unused: ::c_int, + #[cfg(target_endian = "big")] + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct pthread_attr_t { + __size: [u32; 9] + } + + pub struct sigaction { + pub sa_flags: ::c_int, + pub sa_sigaction: ::sighandler_t, + pub sa_mask: sigset_t, + pub sa_restorer: ::dox::Option, + _resv: [::c_int; 1], + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_size: ::size_t, + pub ss_flags: ::c_int, + } + + pub struct sigset_t { + __val: [::c_ulong; 32], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_code: ::c_int, + pub si_errno: ::c_int, + pub _pad: [::c_int; 29], + } + + pub struct ipc_perm { + pub __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::c_uint, + pub __seq: ::c_ushort, + __pad1: ::c_ushort, + __unused1: ::c_ulong, + __unused2: ::c_ulong + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __unused4: ::c_ulong, + __unused5: ::c_ulong + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + #[cfg(target_endian = "big")] + __glibc_reserved1: ::c_ulong, + pub msg_stime: ::time_t, + #[cfg(target_endian = "little")] + __glibc_reserved1: ::c_ulong, + #[cfg(target_endian = "big")] + __glibc_reserved2: ::c_ulong, + pub msg_rtime: ::time_t, + #[cfg(target_endian = "little")] + __glibc_reserved2: ::c_ulong, + #[cfg(target_endian = "big")] + __glibc_reserved3: ::c_ulong, + pub msg_ctime: ::time_t, + #[cfg(target_endian = "little")] + __glibc_reserved3: ::c_ulong, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __glibc_reserved4: ::c_ulong, + __glibc_reserved5: ::c_ulong, + } + + pub struct statfs { + pub f_type: ::c_long, + pub f_bsize: ::c_long, + pub f_frsize: ::c_long, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_files: ::fsblkcnt_t, + pub f_ffree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_fsid: ::fsid_t, + + pub f_namelen: ::c_long, + f_spare: [::c_long; 6], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::size_t, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::size_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::size_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; ::NCCS], + } + + pub struct flock { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_sysid: ::c_long, + pub l_pid: ::pid_t, + pad: [::c_long; 4], + } + + pub struct sysinfo { + pub uptime: ::c_long, + pub loads: [::c_ulong; 3], + pub totalram: ::c_ulong, + pub freeram: ::c_ulong, + pub sharedram: ::c_ulong, + pub bufferram: ::c_ulong, + pub totalswap: ::c_ulong, + pub freeswap: ::c_ulong, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: ::c_ulong, + pub freehigh: ::c_ulong, + pub mem_unit: ::c_uint, + pub _f: [::c_char; 8], + } +} + +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 24; +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 32; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; + +pub const O_LARGEFILE: ::c_int = 0x2000; + +pub const RLIM_INFINITY: ::rlim_t = 0x7fffffff; + +pub const SYS_syscall: ::c_long = 4000 + 0; +pub const SYS_exit: ::c_long = 4000 + 1; +pub const SYS_fork: ::c_long = 4000 + 2; +pub const SYS_read: ::c_long = 4000 + 3; +pub const SYS_write: ::c_long = 4000 + 4; +pub const SYS_open: ::c_long = 4000 + 5; +pub const SYS_close: ::c_long = 4000 + 6; +pub const SYS_waitpid: ::c_long = 4000 + 7; +pub const SYS_creat: ::c_long = 4000 + 8; +pub const SYS_link: ::c_long = 4000 + 9; +pub const SYS_unlink: ::c_long = 4000 + 10; +pub const SYS_execve: ::c_long = 4000 + 11; +pub const SYS_chdir: ::c_long = 4000 + 12; +pub const SYS_time: ::c_long = 4000 + 13; +pub const SYS_mknod: ::c_long = 4000 + 14; +pub const SYS_chmod: ::c_long = 4000 + 15; +pub const SYS_lchown: ::c_long = 4000 + 16; +pub const SYS_break: ::c_long = 4000 + 17; +pub const SYS_unused18: ::c_long = 4000 + 18; +pub const SYS_lseek: ::c_long = 4000 + 19; +pub const SYS_getpid: ::c_long = 4000 + 20; +pub const SYS_mount: ::c_long = 4000 + 21; +pub const SYS_umount: ::c_long = 4000 + 22; +pub const SYS_setuid: ::c_long = 4000 + 23; +pub const SYS_getuid: ::c_long = 4000 + 24; +pub const SYS_stime: ::c_long = 4000 + 25; +pub const SYS_ptrace: ::c_long = 4000 + 26; +pub const SYS_alarm: ::c_long = 4000 + 27; +pub const SYS_unused28: ::c_long = 4000 + 28; +pub const SYS_pause: ::c_long = 4000 + 29; +pub const SYS_utime: ::c_long = 4000 + 30; +pub const SYS_stty: ::c_long = 4000 + 31; +pub const SYS_gtty: ::c_long = 4000 + 32; +pub const SYS_access: ::c_long = 4000 + 33; +pub const SYS_nice: ::c_long = 4000 + 34; +pub const SYS_ftime: ::c_long = 4000 + 35; +pub const SYS_sync: ::c_long = 4000 + 36; +pub const SYS_kill: ::c_long = 4000 + 37; +pub const SYS_rename: ::c_long = 4000 + 38; +pub const SYS_mkdir: ::c_long = 4000 + 39; +pub const SYS_rmdir: ::c_long = 4000 + 40; +pub const SYS_dup: ::c_long = 4000 + 41; +pub const SYS_pipe: ::c_long = 4000 + 42; +pub const SYS_times: ::c_long = 4000 + 43; +pub const SYS_prof: ::c_long = 4000 + 44; +pub const SYS_brk: ::c_long = 4000 + 45; +pub const SYS_setgid: ::c_long = 4000 + 46; +pub const SYS_getgid: ::c_long = 4000 + 47; +pub const SYS_signal: ::c_long = 4000 + 48; +pub const SYS_geteuid: ::c_long = 4000 + 49; +pub const SYS_getegid: ::c_long = 4000 + 50; +pub const SYS_acct: ::c_long = 4000 + 51; +pub const SYS_umount2: ::c_long = 4000 + 52; +pub const SYS_lock: ::c_long = 4000 + 53; +pub const SYS_ioctl: ::c_long = 4000 + 54; +pub const SYS_fcntl: ::c_long = 4000 + 55; +pub const SYS_mpx: ::c_long = 4000 + 56; +pub const SYS_setpgid: ::c_long = 4000 + 57; +pub const SYS_ulimit: ::c_long = 4000 + 58; +pub const SYS_unused59: ::c_long = 4000 + 59; +pub const SYS_umask: ::c_long = 4000 + 60; +pub const SYS_chroot: ::c_long = 4000 + 61; +pub const SYS_ustat: ::c_long = 4000 + 62; +pub const SYS_dup2: ::c_long = 4000 + 63; +pub const SYS_getppid: ::c_long = 4000 + 64; +pub const SYS_getpgrp: ::c_long = 4000 + 65; +pub const SYS_setsid: ::c_long = 4000 + 66; +pub const SYS_sigaction: ::c_long = 4000 + 67; +pub const SYS_sgetmask: ::c_long = 4000 + 68; +pub const SYS_ssetmask: ::c_long = 4000 + 69; +pub const SYS_setreuid: ::c_long = 4000 + 70; +pub const SYS_setregid: ::c_long = 4000 + 71; +pub const SYS_sigsuspend: ::c_long = 4000 + 72; +pub const SYS_sigpending: ::c_long = 4000 + 73; +pub const SYS_sethostname: ::c_long = 4000 + 74; +pub const SYS_setrlimit: ::c_long = 4000 + 75; +pub const SYS_getrlimit: ::c_long = 4000 + 76; +pub const SYS_getrusage: ::c_long = 4000 + 77; +pub const SYS_gettimeofday: ::c_long = 4000 + 78; +pub const SYS_settimeofday: ::c_long = 4000 + 79; +pub const SYS_getgroups: ::c_long = 4000 + 80; +pub const SYS_setgroups: ::c_long = 4000 + 81; +pub const SYS_reserved82: ::c_long = 4000 + 82; +pub const SYS_symlink: ::c_long = 4000 + 83; +pub const SYS_unused84: ::c_long = 4000 + 84; +pub const SYS_readlink: ::c_long = 4000 + 85; +pub const SYS_uselib: ::c_long = 4000 + 86; +pub const SYS_swapon: ::c_long = 4000 + 87; +pub const SYS_reboot: ::c_long = 4000 + 88; +pub const SYS_readdir: ::c_long = 4000 + 89; +pub const SYS_mmap: ::c_long = 4000 + 90; +pub const SYS_munmap: ::c_long = 4000 + 91; +pub const SYS_truncate: ::c_long = 4000 + 92; +pub const SYS_ftruncate: ::c_long = 4000 + 93; +pub const SYS_fchmod: ::c_long = 4000 + 94; +pub const SYS_fchown: ::c_long = 4000 + 95; +pub const SYS_getpriority: ::c_long = 4000 + 96; +pub const SYS_setpriority: ::c_long = 4000 + 97; +pub const SYS_profil: ::c_long = 4000 + 98; +pub const SYS_statfs: ::c_long = 4000 + 99; +pub const SYS_fstatfs: ::c_long = 4000 + 100; +pub const SYS_ioperm: ::c_long = 4000 + 101; +pub const SYS_socketcall: ::c_long = 4000 + 102; +pub const SYS_syslog: ::c_long = 4000 + 103; +pub const SYS_setitimer: ::c_long = 4000 + 104; +pub const SYS_getitimer: ::c_long = 4000 + 105; +pub const SYS_stat: ::c_long = 4000 + 106; +pub const SYS_lstat: ::c_long = 4000 + 107; +pub const SYS_fstat: ::c_long = 4000 + 108; +pub const SYS_unused109: ::c_long = 4000 + 109; +pub const SYS_iopl: ::c_long = 4000 + 110; +pub const SYS_vhangup: ::c_long = 4000 + 111; +pub const SYS_idle: ::c_long = 4000 + 112; +pub const SYS_vm86: ::c_long = 4000 + 113; +pub const SYS_wait4: ::c_long = 4000 + 114; +pub const SYS_swapoff: ::c_long = 4000 + 115; +pub const SYS_sysinfo: ::c_long = 4000 + 116; +pub const SYS_ipc: ::c_long = 4000 + 117; +pub const SYS_fsync: ::c_long = 4000 + 118; +pub const SYS_sigreturn: ::c_long = 4000 + 119; +pub const SYS_clone: ::c_long = 4000 + 120; +pub const SYS_setdomainname: ::c_long = 4000 + 121; +pub const SYS_uname: ::c_long = 4000 + 122; +pub const SYS_modify_ldt: ::c_long = 4000 + 123; +pub const SYS_adjtimex: ::c_long = 4000 + 124; +pub const SYS_mprotect: ::c_long = 4000 + 125; +pub const SYS_sigprocmask: ::c_long = 4000 + 126; +pub const SYS_create_module: ::c_long = 4000 + 127; +pub const SYS_init_module: ::c_long = 4000 + 128; +pub const SYS_delete_module: ::c_long = 4000 + 129; +pub const SYS_get_kernel_syms: ::c_long = 4000 + 130; +pub const SYS_quotactl: ::c_long = 4000 + 131; +pub const SYS_getpgid: ::c_long = 4000 + 132; +pub const SYS_fchdir: ::c_long = 4000 + 133; +pub const SYS_bdflush: ::c_long = 4000 + 134; +pub const SYS_sysfs: ::c_long = 4000 + 135; +pub const SYS_personality: ::c_long = 4000 + 136; +pub const SYS_afs_syscall: ::c_long = 4000 + 137; +pub const SYS_setfsuid: ::c_long = 4000 + 138; +pub const SYS_setfsgid: ::c_long = 4000 + 139; +pub const SYS__llseek: ::c_long = 4000 + 140; +pub const SYS_getdents: ::c_long = 4000 + 141; +pub const SYS__newselect: ::c_long = 4000 + 142; +pub const SYS_flock: ::c_long = 4000 + 143; +pub const SYS_msync: ::c_long = 4000 + 144; +pub const SYS_readv: ::c_long = 4000 + 145; +pub const SYS_writev: ::c_long = 4000 + 146; +pub const SYS_cacheflush: ::c_long = 4000 + 147; +pub const SYS_cachectl: ::c_long = 4000 + 148; +pub const SYS_sysmips: ::c_long = 4000 + 149; +pub const SYS_unused150: ::c_long = 4000 + 150; +pub const SYS_getsid: ::c_long = 4000 + 151; +pub const SYS_fdatasync: ::c_long = 4000 + 152; +pub const SYS__sysctl: ::c_long = 4000 + 153; +pub const SYS_mlock: ::c_long = 4000 + 154; +pub const SYS_munlock: ::c_long = 4000 + 155; +pub const SYS_mlockall: ::c_long = 4000 + 156; +pub const SYS_munlockall: ::c_long = 4000 + 157; +pub const SYS_sched_setparam: ::c_long = 4000 + 158; +pub const SYS_sched_getparam: ::c_long = 4000 + 159; +pub const SYS_sched_setscheduler: ::c_long = 4000 + 160; +pub const SYS_sched_getscheduler: ::c_long = 4000 + 161; +pub const SYS_sched_yield: ::c_long = 4000 + 162; +pub const SYS_sched_get_priority_max: ::c_long = 4000 + 163; +pub const SYS_sched_get_priority_min: ::c_long = 4000 + 164; +pub const SYS_sched_rr_get_interval: ::c_long = 4000 + 165; +pub const SYS_nanosleep: ::c_long = 4000 + 166; +pub const SYS_mremap: ::c_long = 4000 + 167; +pub const SYS_accept: ::c_long = 4000 + 168; +pub const SYS_bind: ::c_long = 4000 + 169; +pub const SYS_connect: ::c_long = 4000 + 170; +pub const SYS_getpeername: ::c_long = 4000 + 171; +pub const SYS_getsockname: ::c_long = 4000 + 172; +pub const SYS_getsockopt: ::c_long = 4000 + 173; +pub const SYS_listen: ::c_long = 4000 + 174; +pub const SYS_recv: ::c_long = 4000 + 175; +pub const SYS_recvfrom: ::c_long = 4000 + 176; +pub const SYS_recvmsg: ::c_long = 4000 + 177; +pub const SYS_send: ::c_long = 4000 + 178; +pub const SYS_sendmsg: ::c_long = 4000 + 179; +pub const SYS_sendto: ::c_long = 4000 + 180; +pub const SYS_setsockopt: ::c_long = 4000 + 181; +pub const SYS_shutdown: ::c_long = 4000 + 182; +pub const SYS_socket: ::c_long = 4000 + 183; +pub const SYS_socketpair: ::c_long = 4000 + 184; +pub const SYS_setresuid: ::c_long = 4000 + 185; +pub const SYS_getresuid: ::c_long = 4000 + 186; +pub const SYS_query_module: ::c_long = 4000 + 187; +pub const SYS_poll: ::c_long = 4000 + 188; +pub const SYS_nfsservctl: ::c_long = 4000 + 189; +pub const SYS_setresgid: ::c_long = 4000 + 190; +pub const SYS_getresgid: ::c_long = 4000 + 191; +pub const SYS_prctl: ::c_long = 4000 + 192; +pub const SYS_rt_sigreturn: ::c_long = 4000 + 193; +pub const SYS_rt_sigaction: ::c_long = 4000 + 194; +pub const SYS_rt_sigprocmask: ::c_long = 4000 + 195; +pub const SYS_rt_sigpending: ::c_long = 4000 + 196; +pub const SYS_rt_sigtimedwait: ::c_long = 4000 + 197; +pub const SYS_rt_sigqueueinfo: ::c_long = 4000 + 198; +pub const SYS_rt_sigsuspend: ::c_long = 4000 + 199; +pub const SYS_pread64: ::c_long = 4000 + 200; +pub const SYS_pwrite64: ::c_long = 4000 + 201; +pub const SYS_chown: ::c_long = 4000 + 202; +pub const SYS_getcwd: ::c_long = 4000 + 203; +pub const SYS_capget: ::c_long = 4000 + 204; +pub const SYS_capset: ::c_long = 4000 + 205; +pub const SYS_sigaltstack: ::c_long = 4000 + 206; +pub const SYS_sendfile: ::c_long = 4000 + 207; +pub const SYS_getpmsg: ::c_long = 4000 + 208; +pub const SYS_putpmsg: ::c_long = 4000 + 209; +pub const SYS_mmap2: ::c_long = 4000 + 210; +pub const SYS_truncate64: ::c_long = 4000 + 211; +pub const SYS_ftruncate64: ::c_long = 4000 + 212; +pub const SYS_stat64: ::c_long = 4000 + 213; +pub const SYS_lstat64: ::c_long = 4000 + 214; +pub const SYS_fstat64: ::c_long = 4000 + 215; +pub const SYS_pivot_root: ::c_long = 4000 + 216; +pub const SYS_mincore: ::c_long = 4000 + 217; +pub const SYS_madvise: ::c_long = 4000 + 218; +pub const SYS_getdents64: ::c_long = 4000 + 219; +pub const SYS_fcntl64: ::c_long = 4000 + 220; +pub const SYS_reserved221: ::c_long = 4000 + 221; +pub const SYS_gettid: ::c_long = 4000 + 222; +pub const SYS_readahead: ::c_long = 4000 + 223; +pub const SYS_setxattr: ::c_long = 4000 + 224; +pub const SYS_lsetxattr: ::c_long = 4000 + 225; +pub const SYS_fsetxattr: ::c_long = 4000 + 226; +pub const SYS_getxattr: ::c_long = 4000 + 227; +pub const SYS_lgetxattr: ::c_long = 4000 + 228; +pub const SYS_fgetxattr: ::c_long = 4000 + 229; +pub const SYS_listxattr: ::c_long = 4000 + 230; +pub const SYS_llistxattr: ::c_long = 4000 + 231; +pub const SYS_flistxattr: ::c_long = 4000 + 232; +pub const SYS_removexattr: ::c_long = 4000 + 233; +pub const SYS_lremovexattr: ::c_long = 4000 + 234; +pub const SYS_fremovexattr: ::c_long = 4000 + 235; +pub const SYS_tkill: ::c_long = 4000 + 236; +pub const SYS_sendfile64: ::c_long = 4000 + 237; +pub const SYS_futex: ::c_long = 4000 + 238; +pub const SYS_sched_setaffinity: ::c_long = 4000 + 239; +pub const SYS_sched_getaffinity: ::c_long = 4000 + 240; +pub const SYS_io_setup: ::c_long = 4000 + 241; +pub const SYS_io_destroy: ::c_long = 4000 + 242; +pub const SYS_io_getevents: ::c_long = 4000 + 243; +pub const SYS_io_submit: ::c_long = 4000 + 244; +pub const SYS_io_cancel: ::c_long = 4000 + 245; +pub const SYS_exit_group: ::c_long = 4000 + 246; +pub const SYS_lookup_dcookie: ::c_long = 4000 + 247; +pub const SYS_epoll_create: ::c_long = 4000 + 248; +pub const SYS_epoll_ctl: ::c_long = 4000 + 249; +pub const SYS_epoll_wait: ::c_long = 4000 + 250; +pub const SYS_remap_file_pages: ::c_long = 4000 + 251; +pub const SYS_set_tid_address: ::c_long = 4000 + 252; +pub const SYS_restart_syscall: ::c_long = 4000 + 253; +pub const SYS_fadvise64: ::c_long = 4000 + 254; +pub const SYS_statfs64: ::c_long = 4000 + 255; +pub const SYS_fstatfs64: ::c_long = 4000 + 256; +pub const SYS_timer_create: ::c_long = 4000 + 257; +pub const SYS_timer_settime: ::c_long = 4000 + 258; +pub const SYS_timer_gettime: ::c_long = 4000 + 259; +pub const SYS_timer_getoverrun: ::c_long = 4000 + 260; +pub const SYS_timer_delete: ::c_long = 4000 + 261; +pub const SYS_clock_settime: ::c_long = 4000 + 262; +pub const SYS_clock_gettime: ::c_long = 4000 + 263; +pub const SYS_clock_getres: ::c_long = 4000 + 264; +pub const SYS_clock_nanosleep: ::c_long = 4000 + 265; +pub const SYS_tgkill: ::c_long = 4000 + 266; +pub const SYS_utimes: ::c_long = 4000 + 267; +pub const SYS_mbind: ::c_long = 4000 + 268; +pub const SYS_get_mempolicy: ::c_long = 4000 + 269; +pub const SYS_set_mempolicy: ::c_long = 4000 + 270; +pub const SYS_mq_open: ::c_long = 4000 + 271; +pub const SYS_mq_unlink: ::c_long = 4000 + 272; +pub const SYS_mq_timedsend: ::c_long = 4000 + 273; +pub const SYS_mq_timedreceive: ::c_long = 4000 + 274; +pub const SYS_mq_notify: ::c_long = 4000 + 275; +pub const SYS_mq_getsetattr: ::c_long = 4000 + 276; +pub const SYS_vserver: ::c_long = 4000 + 277; +pub const SYS_waitid: ::c_long = 4000 + 278; +/* pub const SYS_sys_setaltroot: ::c_long = 4000 + 279; */ +pub const SYS_add_key: ::c_long = 4000 + 280; +pub const SYS_request_key: ::c_long = 4000 + 281; +pub const SYS_keyctl: ::c_long = 4000 + 282; +pub const SYS_set_thread_area: ::c_long = 4000 + 283; +pub const SYS_inotify_init: ::c_long = 4000 + 284; +pub const SYS_inotify_add_watch: ::c_long = 4000 + 285; +pub const SYS_inotify_rm_watch: ::c_long = 4000 + 286; +pub const SYS_migrate_pages: ::c_long = 4000 + 287; +pub const SYS_openat: ::c_long = 4000 + 288; +pub const SYS_mkdirat: ::c_long = 4000 + 289; +pub const SYS_mknodat: ::c_long = 4000 + 290; +pub const SYS_fchownat: ::c_long = 4000 + 291; +pub const SYS_futimesat: ::c_long = 4000 + 292; +pub const SYS_fstatat64: ::c_long = 4000 + 293; +pub const SYS_unlinkat: ::c_long = 4000 + 294; +pub const SYS_renameat: ::c_long = 4000 + 295; +pub const SYS_linkat: ::c_long = 4000 + 296; +pub const SYS_symlinkat: ::c_long = 4000 + 297; +pub const SYS_readlinkat: ::c_long = 4000 + 298; +pub const SYS_fchmodat: ::c_long = 4000 + 299; +pub const SYS_faccessat: ::c_long = 4000 + 300; +pub const SYS_pselect6: ::c_long = 4000 + 301; +pub const SYS_ppoll: ::c_long = 4000 + 302; +pub const SYS_unshare: ::c_long = 4000 + 303; +pub const SYS_splice: ::c_long = 4000 + 304; +pub const SYS_sync_file_range: ::c_long = 4000 + 305; +pub const SYS_tee: ::c_long = 4000 + 306; +pub const SYS_vmsplice: ::c_long = 4000 + 307; +pub const SYS_move_pages: ::c_long = 4000 + 308; +pub const SYS_set_robust_list: ::c_long = 4000 + 309; +pub const SYS_get_robust_list: ::c_long = 4000 + 310; +pub const SYS_kexec_load: ::c_long = 4000 + 311; +pub const SYS_getcpu: ::c_long = 4000 + 312; +pub const SYS_epoll_pwait: ::c_long = 4000 + 313; +pub const SYS_ioprio_set: ::c_long = 4000 + 314; +pub const SYS_ioprio_get: ::c_long = 4000 + 315; +pub const SYS_utimensat: ::c_long = 4000 + 316; +pub const SYS_signalfd: ::c_long = 4000 + 317; +pub const SYS_timerfd: ::c_long = 4000 + 318; +pub const SYS_eventfd: ::c_long = 4000 + 319; +pub const SYS_fallocate: ::c_long = 4000 + 320; +pub const SYS_timerfd_create: ::c_long = 4000 + 321; +pub const SYS_timerfd_gettime: ::c_long = 4000 + 322; +pub const SYS_timerfd_settime: ::c_long = 4000 + 323; +pub const SYS_signalfd4: ::c_long = 4000 + 324; +pub const SYS_eventfd2: ::c_long = 4000 + 325; +pub const SYS_epoll_create1: ::c_long = 4000 + 326; +pub const SYS_dup3: ::c_long = 4000 + 327; +pub const SYS_pipe2: ::c_long = 4000 + 328; +pub const SYS_inotify_init1: ::c_long = 4000 + 329; +pub const SYS_preadv: ::c_long = 4000 + 330; +pub const SYS_pwritev: ::c_long = 4000 + 331; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 4000 + 332; +pub const SYS_perf_event_open: ::c_long = 4000 + 333; +pub const SYS_accept4: ::c_long = 4000 + 334; +pub const SYS_recvmmsg: ::c_long = 4000 + 335; +pub const SYS_fanotify_init: ::c_long = 4000 + 336; +pub const SYS_fanotify_mark: ::c_long = 4000 + 337; +pub const SYS_prlimit64: ::c_long = 4000 + 338; +pub const SYS_name_to_handle_at: ::c_long = 4000 + 339; +pub const SYS_open_by_handle_at: ::c_long = 4000 + 340; +pub const SYS_clock_adjtime: ::c_long = 4000 + 341; +pub const SYS_syncfs: ::c_long = 4000 + 342; +pub const SYS_sendmmsg: ::c_long = 4000 + 343; +pub const SYS_setns: ::c_long = 4000 + 344; +pub const SYS_process_vm_readv: ::c_long = 4000 + 345; +pub const SYS_process_vm_writev: ::c_long = 4000 + 346; +pub const SYS_kcmp: ::c_long = 4000 + 347; +pub const SYS_finit_module: ::c_long = 4000 + 348; +pub const SYS_sched_setattr: ::c_long = 4000 + 349; +pub const SYS_sched_getattr: ::c_long = 4000 + 350; +pub const SYS_renameat2: ::c_long = 4000 + 351; +pub const SYS_seccomp: ::c_long = 4000 + 352; +pub const SYS_getrandom: ::c_long = 4000 + 353; +pub const SYS_memfd_create: ::c_long = 4000 + 354; +pub const SYS_bpf: ::c_long = 4000 + 355; +pub const SYS_execveat: ::c_long = 4000 + 356; +pub const SYS_userfaultfd: ::c_long = 4000 + 357; +pub const SYS_membarrier: ::c_long = 4000 + 358; +pub const SYS_mlock2: ::c_long = 4000 + 359; +pub const SYS_copy_file_range: ::c_long = 4000 + 360; +pub const SYS_preadv2: ::c_long = 4000 + 361; +pub const SYS_pwritev2: ::c_long = 4000 + 362; +pub const SYS_pkey_mprotect: ::c_long = 4000 + 363; +pub const SYS_pkey_alloc: ::c_long = 4000 + 364; +pub const SYS_pkey_free: ::c_long = 4000 + 365; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mips/mips64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mips/mips64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mips/mips64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mips/mips64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,579 @@ +pub type blkcnt_t = i64; +pub type blksize_t = i64; +pub type c_char = i8; +pub type c_long = i64; +pub type c_ulong = u64; +pub type ino_t = u64; +pub type nlink_t = u64; +pub type off_t = i64; +pub type suseconds_t = i64; +pub type time_t = i64; +pub type wchar_t = i32; +pub type clock_t = i64; +pub type __u64 = ::c_ulong; + +s! { + pub struct aiocb { + pub aio_fildes: ::c_int, + pub aio_lio_opcode: ::c_int, + pub aio_reqprio: ::c_int, + pub aio_buf: *mut ::c_void, + pub aio_nbytes: ::size_t, + pub aio_sigevent: ::sigevent, + __next_prio: *mut aiocb, + __abs_prio: ::c_int, + __policy: ::c_int, + __error_code: ::c_int, + __return_value: ::ssize_t, + pub aio_offset: off_t, + __glibc_reserved: [::c_char; 32] + } + + pub struct stat { + pub st_dev: ::c_ulong, + st_pad1: [::c_long; 2], + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::c_ulong, + st_pad2: [::c_ulong; 1], + pub st_size: ::off_t, + st_pad3: ::c_long, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + st_pad4: ::c_long, + pub st_blocks: ::blkcnt_t, + st_pad5: [::c_long; 7], + } + + pub struct stat64 { + pub st_dev: ::c_ulong, + st_pad1: [::c_long; 2], + pub st_ino: ::ino64_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::c_ulong, + st_pad2: [::c_long; 2], + pub st_size: ::off64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + st_pad3: ::c_long, + pub st_blocks: ::blkcnt64_t, + st_pad5: [::c_long; 7], + } + + pub struct statfs64 { + pub f_type: ::c_long, + pub f_bsize: ::c_long, + pub f_frsize: ::c_long, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_bavail: u64, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_long, + pub f_flags: ::c_long, + pub f_spare: [::c_long; 5], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct pthread_attr_t { + __size: [::c_ulong; 7] + } + + pub struct sigaction { + pub sa_flags: ::c_int, + pub sa_sigaction: ::sighandler_t, + pub sa_mask: sigset_t, + pub sa_restorer: ::dox::Option, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_size: ::size_t, + pub ss_flags: ::c_int, + } + + pub struct sigset_t { + __size: [::c_ulong; 16], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_code: ::c_int, + pub si_errno: ::c_int, + _pad: ::c_int, + _pad2: [::c_long; 14], + } + + pub struct ipc_perm { + pub __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::c_uint, + pub __seq: ::c_ushort, + __pad1: ::c_ushort, + __unused1: ::c_ulong, + __unused2: ::c_ulong + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __unused4: ::c_ulong, + __unused5: ::c_ulong + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_stime: ::time_t, + pub msg_rtime: ::time_t, + pub msg_ctime: ::time_t, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __glibc_reserved4: ::c_ulong, + __glibc_reserved5: ::c_ulong, + } + + pub struct statfs { + pub f_type: ::c_long, + pub f_bsize: ::c_long, + pub f_frsize: ::c_long, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_files: ::fsblkcnt_t, + pub f_ffree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_fsid: ::fsid_t, + + pub f_namelen: ::c_long, + f_spare: [::c_long; 6], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::size_t, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::size_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::size_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; ::NCCS], + } + + pub struct flock { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_pid: ::pid_t, + } + + pub struct sysinfo { + pub uptime: ::c_long, + pub loads: [::c_ulong; 3], + pub totalram: ::c_ulong, + pub freeram: ::c_ulong, + pub sharedram: ::c_ulong, + pub bufferram: ::c_ulong, + pub totalswap: ::c_ulong, + pub freeswap: ::c_ulong, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: ::c_ulong, + pub freehigh: ::c_ulong, + pub mem_unit: ::c_uint, + pub _f: [::c_char; 0], + } +} + +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; +pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; + +pub const O_LARGEFILE: ::c_int = 0; + +pub const RLIM_INFINITY: ::rlim_t = 0xffff_ffff_ffff_ffff; + +pub const SYS_read: ::c_long = 5000 + 0; +pub const SYS_write: ::c_long = 5000 + 1; +pub const SYS_open: ::c_long = 5000 + 2; +pub const SYS_close: ::c_long = 5000 + 3; +pub const SYS_stat: ::c_long = 5000 + 4; +pub const SYS_fstat: ::c_long = 5000 + 5; +pub const SYS_lstat: ::c_long = 5000 + 6; +pub const SYS_poll: ::c_long = 5000 + 7; +pub const SYS_lseek: ::c_long = 5000 + 8; +pub const SYS_mmap: ::c_long = 5000 + 9; +pub const SYS_mprotect: ::c_long = 5000 + 10; +pub const SYS_munmap: ::c_long = 5000 + 11; +pub const SYS_brk: ::c_long = 5000 + 12; +pub const SYS_rt_sigaction: ::c_long = 5000 + 13; +pub const SYS_rt_sigprocmask: ::c_long = 5000 + 14; +pub const SYS_ioctl: ::c_long = 5000 + 15; +pub const SYS_pread64: ::c_long = 5000 + 16; +pub const SYS_pwrite64: ::c_long = 5000 + 17; +pub const SYS_readv: ::c_long = 5000 + 18; +pub const SYS_writev: ::c_long = 5000 + 19; +pub const SYS_access: ::c_long = 5000 + 20; +pub const SYS_pipe: ::c_long = 5000 + 21; +pub const SYS__newselect: ::c_long = 5000 + 22; +pub const SYS_sched_yield: ::c_long = 5000 + 23; +pub const SYS_mremap: ::c_long = 5000 + 24; +pub const SYS_msync: ::c_long = 5000 + 25; +pub const SYS_mincore: ::c_long = 5000 + 26; +pub const SYS_madvise: ::c_long = 5000 + 27; +pub const SYS_shmget: ::c_long = 5000 + 28; +pub const SYS_shmat: ::c_long = 5000 + 29; +pub const SYS_shmctl: ::c_long = 5000 + 30; +pub const SYS_dup: ::c_long = 5000 + 31; +pub const SYS_dup2: ::c_long = 5000 + 32; +pub const SYS_pause: ::c_long = 5000 + 33; +pub const SYS_nanosleep: ::c_long = 5000 + 34; +pub const SYS_getitimer: ::c_long = 5000 + 35; +pub const SYS_setitimer: ::c_long = 5000 + 36; +pub const SYS_alarm: ::c_long = 5000 + 37; +pub const SYS_getpid: ::c_long = 5000 + 38; +pub const SYS_sendfile: ::c_long = 5000 + 39; +pub const SYS_socket: ::c_long = 5000 + 40; +pub const SYS_connect: ::c_long = 5000 + 41; +pub const SYS_accept: ::c_long = 5000 + 42; +pub const SYS_sendto: ::c_long = 5000 + 43; +pub const SYS_recvfrom: ::c_long = 5000 + 44; +pub const SYS_sendmsg: ::c_long = 5000 + 45; +pub const SYS_recvmsg: ::c_long = 5000 + 46; +pub const SYS_shutdown: ::c_long = 5000 + 47; +pub const SYS_bind: ::c_long = 5000 + 48; +pub const SYS_listen: ::c_long = 5000 + 49; +pub const SYS_getsockname: ::c_long = 5000 + 50; +pub const SYS_getpeername: ::c_long = 5000 + 51; +pub const SYS_socketpair: ::c_long = 5000 + 52; +pub const SYS_setsockopt: ::c_long = 5000 + 53; +pub const SYS_getsockopt: ::c_long = 5000 + 54; +pub const SYS_clone: ::c_long = 5000 + 55; +pub const SYS_fork: ::c_long = 5000 + 56; +pub const SYS_execve: ::c_long = 5000 + 57; +pub const SYS_exit: ::c_long = 5000 + 58; +pub const SYS_wait4: ::c_long = 5000 + 59; +pub const SYS_kill: ::c_long = 5000 + 60; +pub const SYS_uname: ::c_long = 5000 + 61; +pub const SYS_semget: ::c_long = 5000 + 62; +pub const SYS_semop: ::c_long = 5000 + 63; +pub const SYS_semctl: ::c_long = 5000 + 64; +pub const SYS_shmdt: ::c_long = 5000 + 65; +pub const SYS_msgget: ::c_long = 5000 + 66; +pub const SYS_msgsnd: ::c_long = 5000 + 67; +pub const SYS_msgrcv: ::c_long = 5000 + 68; +pub const SYS_msgctl: ::c_long = 5000 + 69; +pub const SYS_fcntl: ::c_long = 5000 + 70; +pub const SYS_flock: ::c_long = 5000 + 71; +pub const SYS_fsync: ::c_long = 5000 + 72; +pub const SYS_fdatasync: ::c_long = 5000 + 73; +pub const SYS_truncate: ::c_long = 5000 + 74; +pub const SYS_ftruncate: ::c_long = 5000 + 75; +pub const SYS_getdents: ::c_long = 5000 + 76; +pub const SYS_getcwd: ::c_long = 5000 + 77; +pub const SYS_chdir: ::c_long = 5000 + 78; +pub const SYS_fchdir: ::c_long = 5000 + 79; +pub const SYS_rename: ::c_long = 5000 + 80; +pub const SYS_mkdir: ::c_long = 5000 + 81; +pub const SYS_rmdir: ::c_long = 5000 + 82; +pub const SYS_creat: ::c_long = 5000 + 83; +pub const SYS_link: ::c_long = 5000 + 84; +pub const SYS_unlink: ::c_long = 5000 + 85; +pub const SYS_symlink: ::c_long = 5000 + 86; +pub const SYS_readlink: ::c_long = 5000 + 87; +pub const SYS_chmod: ::c_long = 5000 + 88; +pub const SYS_fchmod: ::c_long = 5000 + 89; +pub const SYS_chown: ::c_long = 5000 + 90; +pub const SYS_fchown: ::c_long = 5000 + 91; +pub const SYS_lchown: ::c_long = 5000 + 92; +pub const SYS_umask: ::c_long = 5000 + 93; +pub const SYS_gettimeofday: ::c_long = 5000 + 94; +pub const SYS_getrlimit: ::c_long = 5000 + 95; +pub const SYS_getrusage: ::c_long = 5000 + 96; +pub const SYS_sysinfo: ::c_long = 5000 + 97; +pub const SYS_times: ::c_long = 5000 + 98; +pub const SYS_ptrace: ::c_long = 5000 + 99; +pub const SYS_getuid: ::c_long = 5000 + 100; +pub const SYS_syslog: ::c_long = 5000 + 101; +pub const SYS_getgid: ::c_long = 5000 + 102; +pub const SYS_setuid: ::c_long = 5000 + 103; +pub const SYS_setgid: ::c_long = 5000 + 104; +pub const SYS_geteuid: ::c_long = 5000 + 105; +pub const SYS_getegid: ::c_long = 5000 + 106; +pub const SYS_setpgid: ::c_long = 5000 + 107; +pub const SYS_getppid: ::c_long = 5000 + 108; +pub const SYS_getpgrp: ::c_long = 5000 + 109; +pub const SYS_setsid: ::c_long = 5000 + 110; +pub const SYS_setreuid: ::c_long = 5000 + 111; +pub const SYS_setregid: ::c_long = 5000 + 112; +pub const SYS_getgroups: ::c_long = 5000 + 113; +pub const SYS_setgroups: ::c_long = 5000 + 114; +pub const SYS_setresuid: ::c_long = 5000 + 115; +pub const SYS_getresuid: ::c_long = 5000 + 116; +pub const SYS_setresgid: ::c_long = 5000 + 117; +pub const SYS_getresgid: ::c_long = 5000 + 118; +pub const SYS_getpgid: ::c_long = 5000 + 119; +pub const SYS_setfsuid: ::c_long = 5000 + 120; +pub const SYS_setfsgid: ::c_long = 5000 + 121; +pub const SYS_getsid: ::c_long = 5000 + 122; +pub const SYS_capget: ::c_long = 5000 + 123; +pub const SYS_capset: ::c_long = 5000 + 124; +pub const SYS_rt_sigpending: ::c_long = 5000 + 125; +pub const SYS_rt_sigtimedwait: ::c_long = 5000 + 126; +pub const SYS_rt_sigqueueinfo: ::c_long = 5000 + 127; +pub const SYS_rt_sigsuspend: ::c_long = 5000 + 128; +pub const SYS_sigaltstack: ::c_long = 5000 + 129; +pub const SYS_utime: ::c_long = 5000 + 130; +pub const SYS_mknod: ::c_long = 5000 + 131; +pub const SYS_personality: ::c_long = 5000 + 132; +pub const SYS_ustat: ::c_long = 5000 + 133; +pub const SYS_statfs: ::c_long = 5000 + 134; +pub const SYS_fstatfs: ::c_long = 5000 + 135; +pub const SYS_sysfs: ::c_long = 5000 + 136; +pub const SYS_getpriority: ::c_long = 5000 + 137; +pub const SYS_setpriority: ::c_long = 5000 + 138; +pub const SYS_sched_setparam: ::c_long = 5000 + 139; +pub const SYS_sched_getparam: ::c_long = 5000 + 140; +pub const SYS_sched_setscheduler: ::c_long = 5000 + 141; +pub const SYS_sched_getscheduler: ::c_long = 5000 + 142; +pub const SYS_sched_get_priority_max: ::c_long = 5000 + 143; +pub const SYS_sched_get_priority_min: ::c_long = 5000 + 144; +pub const SYS_sched_rr_get_interval: ::c_long = 5000 + 145; +pub const SYS_mlock: ::c_long = 5000 + 146; +pub const SYS_munlock: ::c_long = 5000 + 147; +pub const SYS_mlockall: ::c_long = 5000 + 148; +pub const SYS_munlockall: ::c_long = 5000 + 149; +pub const SYS_vhangup: ::c_long = 5000 + 150; +pub const SYS_pivot_root: ::c_long = 5000 + 151; +pub const SYS__sysctl: ::c_long = 5000 + 152; +pub const SYS_prctl: ::c_long = 5000 + 153; +pub const SYS_adjtimex: ::c_long = 5000 + 154; +pub const SYS_setrlimit: ::c_long = 5000 + 155; +pub const SYS_chroot: ::c_long = 5000 + 156; +pub const SYS_sync: ::c_long = 5000 + 157; +pub const SYS_acct: ::c_long = 5000 + 158; +pub const SYS_settimeofday: ::c_long = 5000 + 159; +pub const SYS_mount: ::c_long = 5000 + 160; +pub const SYS_umount2: ::c_long = 5000 + 161; +pub const SYS_swapon: ::c_long = 5000 + 162; +pub const SYS_swapoff: ::c_long = 5000 + 163; +pub const SYS_reboot: ::c_long = 5000 + 164; +pub const SYS_sethostname: ::c_long = 5000 + 165; +pub const SYS_setdomainname: ::c_long = 5000 + 166; +pub const SYS_create_module: ::c_long = 5000 + 167; +pub const SYS_init_module: ::c_long = 5000 + 168; +pub const SYS_delete_module: ::c_long = 5000 + 169; +pub const SYS_get_kernel_syms: ::c_long = 5000 + 170; +pub const SYS_query_module: ::c_long = 5000 + 171; +pub const SYS_quotactl: ::c_long = 5000 + 172; +pub const SYS_nfsservctl: ::c_long = 5000 + 173; +pub const SYS_getpmsg: ::c_long = 5000 + 174; +pub const SYS_putpmsg: ::c_long = 5000 + 175; +pub const SYS_afs_syscall: ::c_long = 5000 + 176; +pub const SYS_reserved177: ::c_long = 5000 + 177; +pub const SYS_gettid: ::c_long = 5000 + 178; +pub const SYS_readahead: ::c_long = 5000 + 179; +pub const SYS_setxattr: ::c_long = 5000 + 180; +pub const SYS_lsetxattr: ::c_long = 5000 + 181; +pub const SYS_fsetxattr: ::c_long = 5000 + 182; +pub const SYS_getxattr: ::c_long = 5000 + 183; +pub const SYS_lgetxattr: ::c_long = 5000 + 184; +pub const SYS_fgetxattr: ::c_long = 5000 + 185; +pub const SYS_listxattr: ::c_long = 5000 + 186; +pub const SYS_llistxattr: ::c_long = 5000 + 187; +pub const SYS_flistxattr: ::c_long = 5000 + 188; +pub const SYS_removexattr: ::c_long = 5000 + 189; +pub const SYS_lremovexattr: ::c_long = 5000 + 190; +pub const SYS_fremovexattr: ::c_long = 5000 + 191; +pub const SYS_tkill: ::c_long = 5000 + 192; +pub const SYS_reserved193: ::c_long = 5000 + 193; +pub const SYS_futex: ::c_long = 5000 + 194; +pub const SYS_sched_setaffinity: ::c_long = 5000 + 195; +pub const SYS_sched_getaffinity: ::c_long = 5000 + 196; +pub const SYS_cacheflush: ::c_long = 5000 + 197; +pub const SYS_cachectl: ::c_long = 5000 + 198; +pub const SYS_sysmips: ::c_long = 5000 + 199; +pub const SYS_io_setup: ::c_long = 5000 + 200; +pub const SYS_io_destroy: ::c_long = 5000 + 201; +pub const SYS_io_getevents: ::c_long = 5000 + 202; +pub const SYS_io_submit: ::c_long = 5000 + 203; +pub const SYS_io_cancel: ::c_long = 5000 + 204; +pub const SYS_exit_group: ::c_long = 5000 + 205; +pub const SYS_lookup_dcookie: ::c_long = 5000 + 206; +pub const SYS_epoll_create: ::c_long = 5000 + 207; +pub const SYS_epoll_ctl: ::c_long = 5000 + 208; +pub const SYS_epoll_wait: ::c_long = 5000 + 209; +pub const SYS_remap_file_pages: ::c_long = 5000 + 210; +pub const SYS_rt_sigreturn: ::c_long = 5000 + 211; +pub const SYS_set_tid_address: ::c_long = 5000 + 212; +pub const SYS_restart_syscall: ::c_long = 5000 + 213; +pub const SYS_semtimedop: ::c_long = 5000 + 214; +pub const SYS_fadvise64: ::c_long = 5000 + 215; +pub const SYS_timer_create: ::c_long = 5000 + 216; +pub const SYS_timer_settime: ::c_long = 5000 + 217; +pub const SYS_timer_gettime: ::c_long = 5000 + 218; +pub const SYS_timer_getoverrun: ::c_long = 5000 + 219; +pub const SYS_timer_delete: ::c_long = 5000 + 220; +pub const SYS_clock_settime: ::c_long = 5000 + 221; +pub const SYS_clock_gettime: ::c_long = 5000 + 222; +pub const SYS_clock_getres: ::c_long = 5000 + 223; +pub const SYS_clock_nanosleep: ::c_long = 5000 + 224; +pub const SYS_tgkill: ::c_long = 5000 + 225; +pub const SYS_utimes: ::c_long = 5000 + 226; +pub const SYS_mbind: ::c_long = 5000 + 227; +pub const SYS_get_mempolicy: ::c_long = 5000 + 228; +pub const SYS_set_mempolicy: ::c_long = 5000 + 229; +pub const SYS_mq_open: ::c_long = 5000 + 230; +pub const SYS_mq_unlink: ::c_long = 5000 + 231; +pub const SYS_mq_timedsend: ::c_long = 5000 + 232; +pub const SYS_mq_timedreceive: ::c_long = 5000 + 233; +pub const SYS_mq_notify: ::c_long = 5000 + 234; +pub const SYS_mq_getsetattr: ::c_long = 5000 + 235; +pub const SYS_vserver: ::c_long = 5000 + 236; +pub const SYS_waitid: ::c_long = 5000 + 237; +/* pub const SYS_sys_setaltroot: ::c_long = 5000 + 238; */ +pub const SYS_add_key: ::c_long = 5000 + 239; +pub const SYS_request_key: ::c_long = 5000 + 240; +pub const SYS_keyctl: ::c_long = 5000 + 241; +pub const SYS_set_thread_area: ::c_long = 5000 + 242; +pub const SYS_inotify_init: ::c_long = 5000 + 243; +pub const SYS_inotify_add_watch: ::c_long = 5000 + 244; +pub const SYS_inotify_rm_watch: ::c_long = 5000 + 245; +pub const SYS_migrate_pages: ::c_long = 5000 + 246; +pub const SYS_openat: ::c_long = 5000 + 247; +pub const SYS_mkdirat: ::c_long = 5000 + 248; +pub const SYS_mknodat: ::c_long = 5000 + 249; +pub const SYS_fchownat: ::c_long = 5000 + 250; +pub const SYS_futimesat: ::c_long = 5000 + 251; +pub const SYS_newfstatat: ::c_long = 5000 + 252; +pub const SYS_unlinkat: ::c_long = 5000 + 253; +pub const SYS_renameat: ::c_long = 5000 + 254; +pub const SYS_linkat: ::c_long = 5000 + 255; +pub const SYS_symlinkat: ::c_long = 5000 + 256; +pub const SYS_readlinkat: ::c_long = 5000 + 257; +pub const SYS_fchmodat: ::c_long = 5000 + 258; +pub const SYS_faccessat: ::c_long = 5000 + 259; +pub const SYS_pselect6: ::c_long = 5000 + 260; +pub const SYS_ppoll: ::c_long = 5000 + 261; +pub const SYS_unshare: ::c_long = 5000 + 262; +pub const SYS_splice: ::c_long = 5000 + 263; +pub const SYS_sync_file_range: ::c_long = 5000 + 264; +pub const SYS_tee: ::c_long = 5000 + 265; +pub const SYS_vmsplice: ::c_long = 5000 + 266; +pub const SYS_move_pages: ::c_long = 5000 + 267; +pub const SYS_set_robust_list: ::c_long = 5000 + 268; +pub const SYS_get_robust_list: ::c_long = 5000 + 269; +pub const SYS_kexec_load: ::c_long = 5000 + 270; +pub const SYS_getcpu: ::c_long = 5000 + 271; +pub const SYS_epoll_pwait: ::c_long = 5000 + 272; +pub const SYS_ioprio_set: ::c_long = 5000 + 273; +pub const SYS_ioprio_get: ::c_long = 5000 + 274; +pub const SYS_utimensat: ::c_long = 5000 + 275; +pub const SYS_signalfd: ::c_long = 5000 + 276; +pub const SYS_timerfd: ::c_long = 5000 + 277; +pub const SYS_eventfd: ::c_long = 5000 + 278; +pub const SYS_fallocate: ::c_long = 5000 + 279; +pub const SYS_timerfd_create: ::c_long = 5000 + 280; +pub const SYS_timerfd_gettime: ::c_long = 5000 + 281; +pub const SYS_timerfd_settime: ::c_long = 5000 + 282; +pub const SYS_signalfd4: ::c_long = 5000 + 283; +pub const SYS_eventfd2: ::c_long = 5000 + 284; +pub const SYS_epoll_create1: ::c_long = 5000 + 285; +pub const SYS_dup3: ::c_long = 5000 + 286; +pub const SYS_pipe2: ::c_long = 5000 + 287; +pub const SYS_inotify_init1: ::c_long = 5000 + 288; +pub const SYS_preadv: ::c_long = 5000 + 289; +pub const SYS_pwritev: ::c_long = 5000 + 290; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 5000 + 291; +pub const SYS_perf_event_open: ::c_long = 5000 + 292; +pub const SYS_accept4: ::c_long = 5000 + 293; +pub const SYS_recvmmsg: ::c_long = 5000 + 294; +pub const SYS_fanotify_init: ::c_long = 5000 + 295; +pub const SYS_fanotify_mark: ::c_long = 5000 + 296; +pub const SYS_prlimit64: ::c_long = 5000 + 297; +pub const SYS_name_to_handle_at: ::c_long = 5000 + 298; +pub const SYS_open_by_handle_at: ::c_long = 5000 + 299; +pub const SYS_clock_adjtime: ::c_long = 5000 + 300; +pub const SYS_syncfs: ::c_long = 5000 + 301; +pub const SYS_sendmmsg: ::c_long = 5000 + 302; +pub const SYS_setns: ::c_long = 5000 + 303; +pub const SYS_process_vm_readv: ::c_long = 5000 + 304; +pub const SYS_process_vm_writev: ::c_long = 5000 + 305; +pub const SYS_kcmp: ::c_long = 5000 + 306; +pub const SYS_finit_module: ::c_long = 5000 + 307; +pub const SYS_getdents64: ::c_long = 5000 + 308; +pub const SYS_sched_setattr: ::c_long = 5000 + 309; +pub const SYS_sched_getattr: ::c_long = 5000 + 310; +pub const SYS_renameat2: ::c_long = 5000 + 311; +pub const SYS_seccomp: ::c_long = 5000 + 312; +pub const SYS_getrandom: ::c_long = 5000 + 313; +pub const SYS_memfd_create: ::c_long = 5000 + 314; +pub const SYS_bpf: ::c_long = 5000 + 315; +pub const SYS_execveat: ::c_long = 5000 + 316; +pub const SYS_userfaultfd: ::c_long = 5000 + 317; +pub const SYS_membarrier: ::c_long = 5000 + 318; +pub const SYS_mlock2: ::c_long = 5000 + 319; +pub const SYS_copy_file_range: ::c_long = 5000 + 320; +pub const SYS_preadv2: ::c_long = 5000 + 321; +pub const SYS_pwritev2: ::c_long = 5000 + 322; +pub const SYS_pkey_mprotect: ::c_long = 5000 + 323; +pub const SYS_pkey_alloc: ::c_long = 5000 + 324; +pub const SYS_pkey_free: ::c_long = 5000 + 325; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mips/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mips/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mips/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mips/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,957 @@ +pub type shmatt_t = ::c_ulong; +pub type msgqnum_t = ::c_ulong; +pub type msglen_t = ::c_ulong; +pub type fsblkcnt_t = ::c_ulong; +pub type fsfilcnt_t = ::c_ulong; +pub type rlim_t = c_ulong; +pub type __priority_which_t = ::c_uint; + +s! { + pub struct glob64_t { + pub gl_pathc: ::size_t, + pub gl_pathv: *mut *mut ::c_char, + pub gl_offs: ::size_t, + pub gl_flags: ::c_int, + + __unused1: *mut ::c_void, + __unused2: *mut ::c_void, + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + } + + // FIXME this is actually a union + pub struct sem_t { + #[cfg(target_pointer_width = "32")] + __size: [::c_char; 16], + #[cfg(target_pointer_width = "64")] + __size: [::c_char; 32], + __align: [::c_long; 0], + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 23], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } + + pub struct nlmsghdr { + nlmsg_len: u32, + nlmsg_type: u16, + nlmsg_flags: u16, + nlmsg_seq: u32, + nlmsg_pid: u32, + } + + pub struct nlmsgerr { + error: ::c_int, + msg: nlmsghdr, + } + + pub struct nl_pktinfo { + group: u32, + } + + pub struct nl_mmap_req { + nm_block_size: ::c_uint, + nm_block_nr: ::c_uint, + nm_frame_size: ::c_uint, + nm_frame_nr: ::c_uint, + } + + pub struct nl_mmap_hdr { + nm_status: ::c_uint, + nm_len: ::c_uint, + nm_group: u32, + nm_pid: u32, + nm_uid: u32, + nm_gid: u32, + } + + pub struct nlattr { + nla_len: u16, + nla_type: u16, + } +} + +pub const SFD_CLOEXEC: ::c_int = 0x080000; + +pub const NCCS: usize = 32; + +pub const O_TRUNC: ::c_int = 512; + +pub const O_NOATIME: ::c_int = 0o1000000; +pub const O_CLOEXEC: ::c_int = 0x80000; +pub const O_PATH: ::c_int = 0o10000000; +pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; + +pub const EBFONT: ::c_int = 59; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const EDOTDOT: ::c_int = 73; + +pub const SA_NODEFER: ::c_int = 0x40000000; +pub const SA_RESETHAND: ::c_int = 0x80000000; +pub const SA_RESTART: ::c_int = 0x10000000; +pub const SA_NOCLDSTOP: ::c_int = 0x00000001; + +pub const EPOLL_CLOEXEC: ::c_int = 0x80000; + +pub const EFD_CLOEXEC: ::c_int = 0x80000; + +pub const BUFSIZ: ::c_uint = 8192; +pub const TMP_MAX: ::c_uint = 238328; +pub const FOPEN_MAX: ::c_uint = 16; +pub const POSIX_FADV_DONTNEED: ::c_int = 4; +pub const POSIX_FADV_NOREUSE: ::c_int = 5; +pub const POSIX_MADV_DONTNEED: ::c_int = 4; +pub const _SC_EQUIV_CLASS_MAX: ::c_int = 41; +pub const _SC_CHARCLASS_NAME_MAX: ::c_int = 45; +pub const _SC_PII: ::c_int = 53; +pub const _SC_PII_XTI: ::c_int = 54; +pub const _SC_PII_SOCKET: ::c_int = 55; +pub const _SC_PII_INTERNET: ::c_int = 56; +pub const _SC_PII_OSI: ::c_int = 57; +pub const _SC_POLL: ::c_int = 58; +pub const _SC_SELECT: ::c_int = 59; +pub const _SC_PII_INTERNET_STREAM: ::c_int = 61; +pub const _SC_PII_INTERNET_DGRAM: ::c_int = 62; +pub const _SC_PII_OSI_COTS: ::c_int = 63; +pub const _SC_PII_OSI_CLTS: ::c_int = 64; +pub const _SC_PII_OSI_M: ::c_int = 65; +pub const _SC_T_IOV_MAX: ::c_int = 66; +pub const _SC_2_C_VERSION: ::c_int = 96; +pub const _SC_CHAR_BIT: ::c_int = 101; +pub const _SC_CHAR_MAX: ::c_int = 102; +pub const _SC_CHAR_MIN: ::c_int = 103; +pub const _SC_INT_MAX: ::c_int = 104; +pub const _SC_INT_MIN: ::c_int = 105; +pub const _SC_LONG_BIT: ::c_int = 106; +pub const _SC_WORD_BIT: ::c_int = 107; +pub const _SC_MB_LEN_MAX: ::c_int = 108; +pub const _SC_SSIZE_MAX: ::c_int = 110; +pub const _SC_SCHAR_MAX: ::c_int = 111; +pub const _SC_SCHAR_MIN: ::c_int = 112; +pub const _SC_SHRT_MAX: ::c_int = 113; +pub const _SC_SHRT_MIN: ::c_int = 114; +pub const _SC_UCHAR_MAX: ::c_int = 115; +pub const _SC_UINT_MAX: ::c_int = 116; +pub const _SC_ULONG_MAX: ::c_int = 117; +pub const _SC_USHRT_MAX: ::c_int = 118; +pub const _SC_NL_ARGMAX: ::c_int = 119; +pub const _SC_NL_LANGMAX: ::c_int = 120; +pub const _SC_NL_MSGMAX: ::c_int = 121; +pub const _SC_NL_NMAX: ::c_int = 122; +pub const _SC_NL_SETMAX: ::c_int = 123; +pub const _SC_NL_TEXTMAX: ::c_int = 124; +pub const _SC_BASE: ::c_int = 134; +pub const _SC_C_LANG_SUPPORT: ::c_int = 135; +pub const _SC_C_LANG_SUPPORT_R: ::c_int = 136; +pub const _SC_DEVICE_IO: ::c_int = 140; +pub const _SC_DEVICE_SPECIFIC: ::c_int = 141; +pub const _SC_DEVICE_SPECIFIC_R: ::c_int = 142; +pub const _SC_FD_MGMT: ::c_int = 143; +pub const _SC_FIFO: ::c_int = 144; +pub const _SC_PIPE: ::c_int = 145; +pub const _SC_FILE_ATTRIBUTES: ::c_int = 146; +pub const _SC_FILE_LOCKING: ::c_int = 147; +pub const _SC_FILE_SYSTEM: ::c_int = 148; +pub const _SC_MULTI_PROCESS: ::c_int = 150; +pub const _SC_SINGLE_PROCESS: ::c_int = 151; +pub const _SC_NETWORKING: ::c_int = 152; +pub const _SC_REGEX_VERSION: ::c_int = 156; +pub const _SC_SIGNALS: ::c_int = 158; +pub const _SC_SYSTEM_DATABASE: ::c_int = 162; +pub const _SC_SYSTEM_DATABASE_R: ::c_int = 163; +pub const _SC_USER_GROUPS: ::c_int = 166; +pub const _SC_USER_GROUPS_R: ::c_int = 167; +pub const _SC_LEVEL1_ICACHE_SIZE: ::c_int = 185; +pub const _SC_LEVEL1_ICACHE_ASSOC: ::c_int = 186; +pub const _SC_LEVEL1_ICACHE_LINESIZE: ::c_int = 187; +pub const _SC_LEVEL1_DCACHE_SIZE: ::c_int = 188; +pub const _SC_LEVEL1_DCACHE_ASSOC: ::c_int = 189; +pub const _SC_LEVEL1_DCACHE_LINESIZE: ::c_int = 190; +pub const _SC_LEVEL2_CACHE_SIZE: ::c_int = 191; +pub const _SC_LEVEL2_CACHE_ASSOC: ::c_int = 192; +pub const _SC_LEVEL2_CACHE_LINESIZE: ::c_int = 193; +pub const _SC_LEVEL3_CACHE_SIZE: ::c_int = 194; +pub const _SC_LEVEL3_CACHE_ASSOC: ::c_int = 195; +pub const _SC_LEVEL3_CACHE_LINESIZE: ::c_int = 196; +pub const _SC_LEVEL4_CACHE_SIZE: ::c_int = 197; +pub const _SC_LEVEL4_CACHE_ASSOC: ::c_int = 198; +pub const _SC_LEVEL4_CACHE_LINESIZE: ::c_int = 199; +pub const O_ACCMODE: ::c_int = 3; +pub const O_DIRECT: ::c_int = 0x8000; +pub const O_DIRECTORY: ::c_int = 0x10000; +pub const O_NOFOLLOW: ::c_int = 0x20000; +pub const ST_RELATIME: ::c_ulong = 4096; +pub const NI_MAXHOST: ::socklen_t = 1025; + +pub const RLIMIT_NOFILE: ::c_int = 5; +pub const RLIMIT_AS: ::c_int = 6; +pub const RLIMIT_RSS: ::c_int = 7; +pub const RLIMIT_NPROC: ::c_int = 8; +pub const RLIMIT_MEMLOCK: ::c_int = 9; +pub const RLIMIT_NLIMITS: ::c_int = 16; + +pub const O_APPEND: ::c_int = 8; +pub const O_CREAT: ::c_int = 256; +pub const O_EXCL: ::c_int = 1024; +pub const O_NOCTTY: ::c_int = 2048; +pub const O_NONBLOCK: ::c_int = 128; +pub const O_SYNC: ::c_int = 0x4010; +pub const O_RSYNC: ::c_int = 0x4010; +pub const O_DSYNC: ::c_int = 0x10; +pub const O_FSYNC: ::c_int = 0x4010; +pub const O_ASYNC: ::c_int = 0x1000; +pub const O_NDELAY: ::c_int = 0x80; + +pub const SOCK_NONBLOCK: ::c_int = 128; + +pub const EDEADLK: ::c_int = 45; +pub const ENAMETOOLONG: ::c_int = 78; +pub const ENOLCK: ::c_int = 46; +pub const ENOSYS: ::c_int = 89; +pub const ENOTEMPTY: ::c_int = 93; +pub const ELOOP: ::c_int = 90; +pub const ENOMSG: ::c_int = 35; +pub const EIDRM: ::c_int = 36; +pub const ECHRNG: ::c_int = 37; +pub const EL2NSYNC: ::c_int = 38; +pub const EL3HLT: ::c_int = 39; +pub const EL3RST: ::c_int = 40; +pub const ELNRNG: ::c_int = 41; +pub const EUNATCH: ::c_int = 42; +pub const ENOCSI: ::c_int = 43; +pub const EL2HLT: ::c_int = 44; +pub const EBADE: ::c_int = 50; +pub const EBADR: ::c_int = 51; +pub const EXFULL: ::c_int = 52; +pub const ENOANO: ::c_int = 53; +pub const EBADRQC: ::c_int = 54; +pub const EBADSLT: ::c_int = 55; +pub const EDEADLOCK: ::c_int = 56; +pub const EMULTIHOP: ::c_int = 74; +pub const EOVERFLOW: ::c_int = 79; +pub const ENOTUNIQ: ::c_int = 80; +pub const EBADFD: ::c_int = 81; +pub const EBADMSG: ::c_int = 77; +pub const EREMCHG: ::c_int = 82; +pub const ELIBACC: ::c_int = 83; +pub const ELIBBAD: ::c_int = 84; +pub const ELIBSCN: ::c_int = 85; +pub const ELIBMAX: ::c_int = 86; +pub const ELIBEXEC: ::c_int = 87; +pub const EILSEQ: ::c_int = 88; +pub const ERESTART: ::c_int = 91; +pub const ESTRPIPE: ::c_int = 92; +pub const EUSERS: ::c_int = 94; +pub const ENOTSOCK: ::c_int = 95; +pub const EDESTADDRREQ: ::c_int = 96; +pub const EMSGSIZE: ::c_int = 97; +pub const EPROTOTYPE: ::c_int = 98; +pub const ENOPROTOOPT: ::c_int = 99; +pub const EPROTONOSUPPORT: ::c_int = 120; +pub const ESOCKTNOSUPPORT: ::c_int = 121; +pub const EOPNOTSUPP: ::c_int = 122; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; +pub const EPFNOSUPPORT: ::c_int = 123; +pub const EAFNOSUPPORT: ::c_int = 124; +pub const EADDRINUSE: ::c_int = 125; +pub const EADDRNOTAVAIL: ::c_int = 126; +pub const ENETDOWN: ::c_int = 127; +pub const ENETUNREACH: ::c_int = 128; +pub const ENETRESET: ::c_int = 129; +pub const ECONNABORTED: ::c_int = 130; +pub const ECONNRESET: ::c_int = 131; +pub const ENOBUFS: ::c_int = 132; +pub const EISCONN: ::c_int = 133; +pub const ENOTCONN: ::c_int = 134; +pub const ESHUTDOWN: ::c_int = 143; +pub const ETOOMANYREFS: ::c_int = 144; +pub const ETIMEDOUT: ::c_int = 145; +pub const ECONNREFUSED: ::c_int = 146; +pub const EHOSTDOWN: ::c_int = 147; +pub const EHOSTUNREACH: ::c_int = 148; +pub const EALREADY: ::c_int = 149; +pub const EINPROGRESS: ::c_int = 150; +pub const ESTALE: ::c_int = 151; +pub const EUCLEAN: ::c_int = 135; +pub const ENOTNAM: ::c_int = 137; +pub const ENAVAIL: ::c_int = 138; +pub const EISNAM: ::c_int = 139; +pub const EREMOTEIO: ::c_int = 140; +pub const EDQUOT: ::c_int = 1133; +pub const ENOMEDIUM: ::c_int = 159; +pub const EMEDIUMTYPE: ::c_int = 160; +pub const ECANCELED: ::c_int = 158; +pub const ENOKEY: ::c_int = 161; +pub const EKEYEXPIRED: ::c_int = 162; +pub const EKEYREVOKED: ::c_int = 163; +pub const EKEYREJECTED: ::c_int = 164; +pub const EOWNERDEAD: ::c_int = 165; +pub const ENOTRECOVERABLE: ::c_int = 166; +pub const ERFKILL: ::c_int = 167; + +pub const LC_PAPER: ::c_int = 7; +pub const LC_NAME: ::c_int = 8; +pub const LC_ADDRESS: ::c_int = 9; +pub const LC_TELEPHONE: ::c_int = 10; +pub const LC_MEASUREMENT: ::c_int = 11; +pub const LC_IDENTIFICATION: ::c_int = 12; +pub const LC_PAPER_MASK: ::c_int = (1 << LC_PAPER); +pub const LC_NAME_MASK: ::c_int = (1 << LC_NAME); +pub const LC_ADDRESS_MASK: ::c_int = (1 << LC_ADDRESS); +pub const LC_TELEPHONE_MASK: ::c_int = (1 << LC_TELEPHONE); +pub const LC_MEASUREMENT_MASK: ::c_int = (1 << LC_MEASUREMENT); +pub const LC_IDENTIFICATION_MASK: ::c_int = (1 << LC_IDENTIFICATION); +pub const LC_ALL_MASK: ::c_int = ::LC_CTYPE_MASK + | ::LC_NUMERIC_MASK + | ::LC_TIME_MASK + | ::LC_COLLATE_MASK + | ::LC_MONETARY_MASK + | ::LC_MESSAGES_MASK + | LC_PAPER_MASK + | LC_NAME_MASK + | LC_ADDRESS_MASK + | LC_TELEPHONE_MASK + | LC_MEASUREMENT_MASK + | LC_IDENTIFICATION_MASK; + +pub const MAP_NORESERVE: ::c_int = 0x400; +pub const MAP_ANON: ::c_int = 0x800; +pub const MAP_ANONYMOUS: ::c_int = 0x800; +pub const MAP_GROWSDOWN: ::c_int = 0x1000; +pub const MAP_DENYWRITE: ::c_int = 0x2000; +pub const MAP_EXECUTABLE: ::c_int = 0x4000; +pub const MAP_LOCKED: ::c_int = 0x8000; +pub const MAP_POPULATE: ::c_int = 0x10000; +pub const MAP_NONBLOCK: ::c_int = 0x20000; +pub const MAP_STACK: ::c_int = 0x40000; + +pub const SOCK_STREAM: ::c_int = 2; +pub const SOCK_DGRAM: ::c_int = 1; +pub const SOCK_SEQPACKET: ::c_int = 5; +pub const SOCK_DCCP: ::c_int = 6; +pub const SOCK_PACKET: ::c_int = 10; + +pub const SOL_SOCKET: ::c_int = 0xffff; + +pub const SO_REUSEADDR: ::c_int = 0x0004; +pub const SO_KEEPALIVE: ::c_int = 0x0008; +pub const SO_DONTROUTE: ::c_int = 0x0010; +pub const SO_BROADCAST: ::c_int = 0x0020; +pub const SO_LINGER: ::c_int = 0x0080; +pub const SO_OOBINLINE: ::c_int = 0x0100; +pub const SO_REUSEPORT: ::c_int = 0x0200; +pub const SO_TYPE: ::c_int = 0x1008; +pub const SO_STYLE: ::c_int = SO_TYPE; +pub const SO_ERROR: ::c_int = 0x1007; +pub const SO_SNDBUF: ::c_int = 0x1001; +pub const SO_RCVBUF: ::c_int = 0x1002; +pub const SO_SNDLOWAT: ::c_int = 0x1003; +pub const SO_RCVLOWAT: ::c_int = 0x1004; +pub const SO_SNDTIMEO: ::c_int = 0x1005; +pub const SO_RCVTIMEO: ::c_int = 0x1006; +pub const SO_ACCEPTCONN: ::c_int = 0x1009; +pub const SO_PROTOCOL: ::c_int = 0x1028; +pub const SO_DOMAIN: ::c_int = 0x1029; +pub const SO_NO_CHECK: ::c_int = 11; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_PASSCRED: ::c_int = 17; +pub const SO_PEERCRED: ::c_int = 18; +pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22; +pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23; +pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24; +pub const SO_BINDTODEVICE: ::c_int = 25; +pub const SO_ATTACH_FILTER: ::c_int = 26; +pub const SO_DETACH_FILTER: ::c_int = 27; +pub const SO_GET_FILTER: ::c_int = SO_ATTACH_FILTER; +pub const SO_PEERNAME: ::c_int = 28; +pub const SO_TIMESTAMP: ::c_int = 29; +pub const SO_PEERSEC: ::c_int = 30; +pub const SO_SNDBUFFORCE: ::c_int = 31; +pub const SO_RCVBUFFORCE: ::c_int = 33; +pub const SO_PASSSEC: ::c_int = 34; +pub const SO_TIMESTAMPNS: ::c_int = 35; +pub const SCM_TIMESTAMPNS: ::c_int = SO_TIMESTAMPNS; +pub const SO_MARK: ::c_int = 36; +pub const SO_TIMESTAMPING: ::c_int = 37; +pub const SCM_TIMESTAMPING: ::c_int = SO_TIMESTAMPING; +pub const SO_RXQ_OVFL: ::c_int = 40; +pub const SO_WIFI_STATUS: ::c_int = 41; +pub const SCM_WIFI_STATUS: ::c_int = SO_WIFI_STATUS; +pub const SO_PEEK_OFF: ::c_int = 42; +pub const SO_NOFCS: ::c_int = 43; +pub const SO_LOCK_FILTER: ::c_int = 44; +pub const SO_SELECT_ERR_QUEUE: ::c_int = 45; +pub const SO_BUSY_POLL: ::c_int = 46; +pub const SO_MAX_PACING_RATE: ::c_int = 47; +pub const SO_BPF_EXTENSIONS: ::c_int = 48; +pub const SO_INCOMING_CPU: ::c_int = 49; +pub const SO_ATTACH_BPF: ::c_int = 50; +pub const SO_DETACH_BPF: ::c_int = SO_DETACH_FILTER; + +/* DCCP socket options */ +pub const DCCP_SOCKOPT_PACKET_SIZE: ::c_int = 1; +pub const DCCP_SOCKOPT_SERVICE: ::c_int = 2; +pub const DCCP_SOCKOPT_CHANGE_L: ::c_int = 3; +pub const DCCP_SOCKOPT_CHANGE_R: ::c_int = 4; +pub const DCCP_SOCKOPT_GET_CUR_MPS: ::c_int = 5; +pub const DCCP_SOCKOPT_SERVER_TIMEWAIT: ::c_int = 6; +pub const DCCP_SOCKOPT_SEND_CSCOV: ::c_int = 10; +pub const DCCP_SOCKOPT_RECV_CSCOV: ::c_int = 11; +pub const DCCP_SOCKOPT_AVAILABLE_CCIDS: ::c_int = 12; +pub const DCCP_SOCKOPT_CCID: ::c_int = 13; +pub const DCCP_SOCKOPT_TX_CCID: ::c_int = 14; +pub const DCCP_SOCKOPT_RX_CCID: ::c_int = 15; +pub const DCCP_SOCKOPT_QPOLICY_ID: ::c_int = 16; +pub const DCCP_SOCKOPT_QPOLICY_TXQLEN: ::c_int = 17; +pub const DCCP_SOCKOPT_CCID_RX_INFO: ::c_int = 128; +pub const DCCP_SOCKOPT_CCID_TX_INFO: ::c_int = 192; + +/// maximum number of services provided on the same listening port +pub const DCCP_SERVICE_LIST_MAX_LEN: ::c_int = 32; + +pub const FIOCLEX: ::c_ulong = 0x6601; +pub const FIONBIO: ::c_ulong = 0x667e; + +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 0x00000008; +pub const SA_NOCLDWAIT: ::c_int = 0x00010000; + +pub const SIGCHLD: ::c_int = 18; +pub const SIGBUS: ::c_int = 10; +pub const SIGTTIN: ::c_int = 26; +pub const SIGTTOU: ::c_int = 27; +pub const SIGXCPU: ::c_int = 30; +pub const SIGXFSZ: ::c_int = 31; +pub const SIGVTALRM: ::c_int = 28; +pub const SIGPROF: ::c_int = 29; +pub const SIGWINCH: ::c_int = 20; +pub const SIGUSR1: ::c_int = 16; +pub const SIGUSR2: ::c_int = 17; +pub const SIGCONT: ::c_int = 25; +pub const SIGSTOP: ::c_int = 23; +pub const SIGTSTP: ::c_int = 24; +pub const SIGURG: ::c_int = 21; +pub const SIGIO: ::c_int = 22; +pub const SIGSYS: ::c_int = 12; +pub const SIGPOLL: ::c_int = 22; +pub const SIGPWR: ::c_int = 19; +pub const SIG_SETMASK: ::c_int = 3; +pub const SIG_BLOCK: ::c_int = 0x1; +pub const SIG_UNBLOCK: ::c_int = 0x2; + +pub const POLLWRNORM: ::c_short = 0x004; +pub const POLLWRBAND: ::c_short = 0x100; + +pub const PTHREAD_STACK_MIN: ::size_t = 131072; + +pub const ADFS_SUPER_MAGIC: ::c_long = 0x0000adf5; +pub const AFFS_SUPER_MAGIC: ::c_long = 0x0000adff; +pub const CODA_SUPER_MAGIC: ::c_long = 0x73757245; +pub const CRAMFS_MAGIC: ::c_long = 0x28cd3d45; +pub const EFS_SUPER_MAGIC: ::c_long = 0x00414a53; +pub const EXT2_SUPER_MAGIC: ::c_long = 0x0000ef53; +pub const EXT3_SUPER_MAGIC: ::c_long = 0x0000ef53; +pub const EXT4_SUPER_MAGIC: ::c_long = 0x0000ef53; +pub const HPFS_SUPER_MAGIC: ::c_long = 0xf995e849; +pub const HUGETLBFS_MAGIC: ::c_long = 0x958458f6; +pub const ISOFS_SUPER_MAGIC: ::c_long = 0x00009660; +pub const JFFS2_SUPER_MAGIC: ::c_long = 0x000072b6; +pub const MINIX_SUPER_MAGIC: ::c_long = 0x0000137f; +pub const MINIX_SUPER_MAGIC2: ::c_long = 0x0000138f; +pub const MINIX2_SUPER_MAGIC: ::c_long = 0x00002468; +pub const MINIX2_SUPER_MAGIC2: ::c_long = 0x00002478; +pub const MSDOS_SUPER_MAGIC: ::c_long = 0x00004d44; +pub const NCP_SUPER_MAGIC: ::c_long = 0x0000564c; +pub const NFS_SUPER_MAGIC: ::c_long = 0x00006969; +pub const OPENPROM_SUPER_MAGIC: ::c_long = 0x00009fa1; +pub const PROC_SUPER_MAGIC: ::c_long = 0x00009fa0; +pub const QNX4_SUPER_MAGIC: ::c_long = 0x0000002f; +pub const REISERFS_SUPER_MAGIC: ::c_long = 0x52654973; +pub const SMB_SUPER_MAGIC: ::c_long = 0x0000517b; +pub const TMPFS_MAGIC: ::c_long = 0x01021994; +pub const USBDEVICE_SUPER_MAGIC: ::c_long = 0x00009fa2; + +pub const VEOF: usize = 16; +pub const VEOL: usize = 17; +pub const VEOL2: usize = 6; +pub const VMIN: usize = 4; +pub const IEXTEN: ::tcflag_t = 0x00000100; +pub const TOSTOP: ::tcflag_t = 0x00008000; +pub const FLUSHO: ::tcflag_t = 0x00002000; +pub const EXTPROC: ::tcflag_t = 0o200000; +pub const TCSANOW: ::c_int = 0x540e; +pub const TCSADRAIN: ::c_int = 0x540f; +pub const TCSAFLUSH: ::c_int = 0x5410; + +pub const CPU_SETSIZE: ::c_int = 0x400; + +pub const PTRACE_TRACEME: ::c_uint = 0; +pub const PTRACE_PEEKTEXT: ::c_uint = 1; +pub const PTRACE_PEEKDATA: ::c_uint = 2; +pub const PTRACE_PEEKUSER: ::c_uint = 3; +pub const PTRACE_POKETEXT: ::c_uint = 4; +pub const PTRACE_POKEDATA: ::c_uint = 5; +pub const PTRACE_POKEUSER: ::c_uint = 6; +pub const PTRACE_CONT: ::c_uint = 7; +pub const PTRACE_KILL: ::c_uint = 8; +pub const PTRACE_SINGLESTEP: ::c_uint = 9; +pub const PTRACE_ATTACH: ::c_uint = 16; +pub const PTRACE_DETACH: ::c_uint = 17; +pub const PTRACE_SYSCALL: ::c_uint = 24; +pub const PTRACE_SETOPTIONS: ::c_uint = 0x4200; +pub const PTRACE_GETEVENTMSG: ::c_uint = 0x4201; +pub const PTRACE_GETSIGINFO: ::c_uint = 0x4202; +pub const PTRACE_SETSIGINFO: ::c_uint = 0x4203; +pub const PTRACE_GETFPREGS: ::c_uint = 14; +pub const PTRACE_SETFPREGS: ::c_uint = 15; +pub const PTRACE_GETFPXREGS: ::c_uint = 18; +pub const PTRACE_SETFPXREGS: ::c_uint = 19; +pub const PTRACE_GETREGS: ::c_uint = 12; +pub const PTRACE_SETREGS: ::c_uint = 13; + +pub const MAP_HUGETLB: ::c_int = 0x080000; + +pub const EFD_NONBLOCK: ::c_int = 0x80; + +pub const F_GETLK: ::c_int = 14; +pub const F_GETOWN: ::c_int = 23; +pub const F_SETOWN: ::c_int = 24; +pub const F_SETLK: ::c_int = 6; +pub const F_SETLKW: ::c_int = 7; + +pub const SFD_NONBLOCK: ::c_int = 0x80; + +pub const TCGETS: ::c_ulong = 0x540d; +pub const TCSETS: ::c_ulong = 0x540e; +pub const TCSETSW: ::c_ulong = 0x540f; +pub const TCSETSF: ::c_ulong = 0x5410; +pub const TCGETA: ::c_ulong = 0x5401; +pub const TCSETA: ::c_ulong = 0x5402; +pub const TCSETAW: ::c_ulong = 0x5403; +pub const TCSETAF: ::c_ulong = 0x5404; +pub const TCSBRK: ::c_ulong = 0x5405; +pub const TCXONC: ::c_ulong = 0x5406; +pub const TCFLSH: ::c_ulong = 0x5407; +pub const TIOCGSOFTCAR: ::c_ulong = 0x5481; +pub const TIOCSSOFTCAR: ::c_ulong = 0x5482; +pub const TIOCINQ: ::c_ulong = 0x467f; +pub const TIOCLINUX: ::c_ulong = 0x5483; +pub const TIOCGSERIAL: ::c_ulong = 0x5484; +pub const TIOCEXCL: ::c_ulong = 0x740d; +pub const TIOCNXCL: ::c_ulong = 0x740e; +pub const TIOCSCTTY: ::c_ulong = 0x5480; +pub const TIOCGPGRP: ::c_ulong = 0x40047477; +pub const TIOCSPGRP: ::c_ulong = 0x80047476; +pub const TIOCOUTQ: ::c_ulong = 0x7472; +pub const TIOCSTI: ::c_ulong = 0x5472; +pub const TIOCGWINSZ: ::c_ulong = 0x40087468; +pub const TIOCSWINSZ: ::c_ulong = 0x80087467; +pub const TIOCMGET: ::c_ulong = 0x741d; +pub const TIOCMBIS: ::c_ulong = 0x741b; +pub const TIOCMBIC: ::c_ulong = 0x741c; +pub const TIOCMSET: ::c_ulong = 0x741a; +pub const FIONREAD: ::c_ulong = 0x467f; +pub const TIOCCONS: ::c_ulong = 0x80047478; + +pub const RTLD_DEEPBIND: ::c_int = 0x10; +pub const RTLD_GLOBAL: ::c_int = 0x4; +pub const RTLD_NOLOAD: ::c_int = 0x8; + +pub const LINUX_REBOOT_MAGIC1: ::c_int = 0xfee1dead; +pub const LINUX_REBOOT_MAGIC2: ::c_int = 672274793; +pub const LINUX_REBOOT_MAGIC2A: ::c_int = 85072278; +pub const LINUX_REBOOT_MAGIC2B: ::c_int = 369367448; +pub const LINUX_REBOOT_MAGIC2C: ::c_int = 537993216; + +pub const LINUX_REBOOT_CMD_RESTART: ::c_int = 0x01234567; +pub const LINUX_REBOOT_CMD_HALT: ::c_int = 0xCDEF0123; +pub const LINUX_REBOOT_CMD_CAD_ON: ::c_int = 0x89ABCDEF; +pub const LINUX_REBOOT_CMD_CAD_OFF: ::c_int = 0x00000000; +pub const LINUX_REBOOT_CMD_POWER_OFF: ::c_int = 0x4321FEDC; +pub const LINUX_REBOOT_CMD_RESTART2: ::c_int = 0xA1B2C3D4; +pub const LINUX_REBOOT_CMD_SW_SUSPEND: ::c_int = 0xD000FCE2; +pub const LINUX_REBOOT_CMD_KEXEC: ::c_int = 0x45584543; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const SIGSTKSZ: ::size_t = 8192; +pub const MINSIGSTKSZ: ::size_t = 2048; +pub const CBAUD: ::tcflag_t = 0o0010017; +pub const TAB1: ::c_int = 0x00000800; +pub const TAB2: ::c_int = 0x00001000; +pub const TAB3: ::c_int = 0x00001800; +pub const CR1: ::c_int = 0x00000200; +pub const CR2: ::c_int = 0x00000400; +pub const CR3: ::c_int = 0x00000600; +pub const FF1: ::c_int = 0x00008000; +pub const BS1: ::c_int = 0x00002000; +pub const VT1: ::c_int = 0x00004000; +pub const VWERASE: usize = 14; +pub const VREPRINT: usize = 12; +pub const VSUSP: usize = 10; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VDISCARD: usize = 13; +pub const VTIME: usize = 5; +pub const IXON: ::tcflag_t = 0x00000400; +pub const IXOFF: ::tcflag_t = 0x00001000; +pub const ONLCR: ::tcflag_t = 0x4; +pub const CSIZE: ::tcflag_t = 0x00000030; +pub const CS6: ::tcflag_t = 0x00000010; +pub const CS7: ::tcflag_t = 0x00000020; +pub const CS8: ::tcflag_t = 0x00000030; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const ECHOKE: ::tcflag_t = 0x00000800; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const ECHOPRT: ::tcflag_t = 0x00000400; +pub const ECHOCTL: ::tcflag_t = 0x00000200; +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const PENDIN: ::tcflag_t = 0x00004000; +pub const NOFLSH: ::tcflag_t = 0x00000080; +pub const CIBAUD: ::tcflag_t = 0o02003600000; +pub const CBAUDEX: ::tcflag_t = 0o010000; +pub const VSWTC: usize = 7; +pub const OLCUC: ::tcflag_t = 0o000002; +pub const NLDLY: ::tcflag_t = 0o000400; +pub const CRDLY: ::tcflag_t = 0o003000; +pub const TABDLY: ::tcflag_t = 0o014000; +pub const BSDLY: ::tcflag_t = 0o020000; +pub const FFDLY: ::tcflag_t = 0o100000; +pub const VTDLY: ::tcflag_t = 0o040000; +pub const XTABS: ::tcflag_t = 0o014000; + +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const BOTHER: ::speed_t = 0o010000; +pub const B57600: ::speed_t = 0o010001; +pub const B115200: ::speed_t = 0o010002; +pub const B230400: ::speed_t = 0o010003; +pub const B460800: ::speed_t = 0o010004; +pub const B500000: ::speed_t = 0o010005; +pub const B576000: ::speed_t = 0o010006; +pub const B921600: ::speed_t = 0o010007; +pub const B1000000: ::speed_t = 0o010010; +pub const B1152000: ::speed_t = 0o010011; +pub const B1500000: ::speed_t = 0o010012; +pub const B2000000: ::speed_t = 0o010013; +pub const B2500000: ::speed_t = 0o010014; +pub const B3000000: ::speed_t = 0o010015; +pub const B3500000: ::speed_t = 0o010016; +pub const B4000000: ::speed_t = 0o010017; + +pub const TIOCM_LE: ::c_int = 0x001; +pub const TIOCM_DTR: ::c_int = 0x002; +pub const TIOCM_RTS: ::c_int = 0x004; +pub const TIOCM_ST: ::c_int = 0x010; +pub const TIOCM_SR: ::c_int = 0x020; +pub const TIOCM_CTS: ::c_int = 0x040; +pub const TIOCM_CAR: ::c_int = 0x100; +pub const TIOCM_CD: ::c_int = TIOCM_CAR; +pub const TIOCM_RNG: ::c_int = 0x200; +pub const TIOCM_RI: ::c_int = TIOCM_RNG; +pub const TIOCM_DSR: ::c_int = 0x400; + +pub const EHWPOISON: ::c_int = 168; +pub const SIGEV_THREAD_ID: ::c_int = 4; +pub const EPOLLWAKEUP: ::c_int = 0x20000000; + +pub const NF_NETDEV_INGRESS: ::c_int = 0; +pub const NF_NETDEV_NUMHOOKS: ::c_int = 1; + +pub const NFPROTO_INET: ::c_int = 1; +pub const NFPROTO_NETDEV: ::c_int = 5; + +pub const NLA_ALIGNTO: ::c_int = 4; + +pub const GENL_UNS_ADMIN_PERM: ::c_int = 0x10; + +pub const GENL_ID_VFS_DQUOT: ::c_int = ::NLMSG_MIN_TYPE + 1; +pub const GENL_ID_PMCRAID: ::c_int = ::NLMSG_MIN_TYPE + 2; + +pub const NFT_TABLE_MAXNAMELEN: ::c_int = 32; +pub const NFT_CHAIN_MAXNAMELEN: ::c_int = 32; +pub const NFT_SET_MAXNAMELEN: ::c_int = 32; +pub const NFT_OBJ_MAXNAMELEN: ::c_int = 32; +pub const NFT_USERDATA_MAXLEN: ::c_int = 256; + +pub const NFT_REG_VERDICT: ::c_int = 0; +pub const NFT_REG_1: ::c_int = 1; +pub const NFT_REG_2: ::c_int = 2; +pub const NFT_REG_3: ::c_int = 3; +pub const NFT_REG_4: ::c_int = 4; +pub const __NFT_REG_MAX: ::c_int = 5; +pub const NFT_REG32_00: ::c_int = 8; +pub const NFT_REG32_01: ::c_int = 9; +pub const NFT_REG32_02: ::c_int = 10; +pub const NFT_REG32_03: ::c_int = 11; +pub const NFT_REG32_04: ::c_int = 12; +pub const NFT_REG32_05: ::c_int = 13; +pub const NFT_REG32_06: ::c_int = 14; +pub const NFT_REG32_07: ::c_int = 15; +pub const NFT_REG32_08: ::c_int = 16; +pub const NFT_REG32_09: ::c_int = 17; +pub const NFT_REG32_10: ::c_int = 18; +pub const NFT_REG32_11: ::c_int = 19; +pub const NFT_REG32_12: ::c_int = 20; +pub const NFT_REG32_13: ::c_int = 21; +pub const NFT_REG32_14: ::c_int = 22; +pub const NFT_REG32_15: ::c_int = 23; + +pub const NFT_REG_SIZE: ::c_int = 16; +pub const NFT_REG32_SIZE: ::c_int = 4; + +pub const NFT_CONTINUE: ::c_int = -1; +pub const NFT_BREAK: ::c_int = -2; +pub const NFT_JUMP: ::c_int = -3; +pub const NFT_GOTO: ::c_int = -4; +pub const NFT_RETURN: ::c_int = -5; + +pub const NFT_MSG_NEWTABLE: ::c_int = 0; +pub const NFT_MSG_GETTABLE: ::c_int = 1; +pub const NFT_MSG_DELTABLE: ::c_int = 2; +pub const NFT_MSG_NEWCHAIN: ::c_int = 3; +pub const NFT_MSG_GETCHAIN: ::c_int = 4; +pub const NFT_MSG_DELCHAIN: ::c_int = 5; +pub const NFT_MSG_NEWRULE: ::c_int = 6; +pub const NFT_MSG_GETRULE: ::c_int = 7; +pub const NFT_MSG_DELRULE: ::c_int = 8; +pub const NFT_MSG_NEWSET: ::c_int = 9; +pub const NFT_MSG_GETSET: ::c_int = 10; +pub const NFT_MSG_DELSET: ::c_int = 11; +pub const NFT_MSG_NEWSETELEM: ::c_int = 12; +pub const NFT_MSG_GETSETELEM: ::c_int = 13; +pub const NFT_MSG_DELSETELEM: ::c_int = 14; +pub const NFT_MSG_NEWGEN: ::c_int = 15; +pub const NFT_MSG_GETGEN: ::c_int = 16; +pub const NFT_MSG_TRACE: ::c_int = 17; +pub const NFT_MSG_NEWOBJ: ::c_int = 18; +pub const NFT_MSG_GETOBJ: ::c_int = 19; +pub const NFT_MSG_DELOBJ: ::c_int = 20; +pub const NFT_MSG_GETOBJ_RESET: ::c_int = 21; +pub const NFT_MSG_MAX: ::c_int = 22; + +pub const NFT_SET_ANONYMOUS: ::c_int = 0x1; +pub const NFT_SET_CONSTANT: ::c_int = 0x2; +pub const NFT_SET_INTERVAL: ::c_int = 0x4; +pub const NFT_SET_MAP: ::c_int = 0x8; +pub const NFT_SET_TIMEOUT: ::c_int = 0x10; +pub const NFT_SET_EVAL: ::c_int = 0x20; + +pub const NFT_SET_POL_PERFORMANCE: ::c_int = 0; +pub const NFT_SET_POL_MEMORY: ::c_int = 1; + +pub const NFT_SET_ELEM_INTERVAL_END: ::c_int = 0x1; + +pub const NFT_DATA_VALUE: ::c_uint = 0; +pub const NFT_DATA_VERDICT: ::c_uint = 0xffffff00; + +pub const NFT_DATA_RESERVED_MASK: ::c_uint = 0xffffff00; + +pub const NFT_DATA_VALUE_MAXLEN: ::c_int = 64; + +pub const NFT_BYTEORDER_NTOH: ::c_int = 0; +pub const NFT_BYTEORDER_HTON: ::c_int = 1; + +pub const NFT_CMP_EQ: ::c_int = 0; +pub const NFT_CMP_NEQ: ::c_int = 1; +pub const NFT_CMP_LT: ::c_int = 2; +pub const NFT_CMP_LTE: ::c_int = 3; +pub const NFT_CMP_GT: ::c_int = 4; +pub const NFT_CMP_GTE: ::c_int = 5; + +pub const NFT_RANGE_EQ: ::c_int = 0; +pub const NFT_RANGE_NEQ: ::c_int = 1; + +pub const NFT_LOOKUP_F_INV: ::c_int = (1 << 0); + +pub const NFT_DYNSET_OP_ADD: ::c_int = 0; +pub const NFT_DYNSET_OP_UPDATE: ::c_int = 1; + +pub const NFT_DYNSET_F_INV: ::c_int = (1 << 0); + +pub const NFT_PAYLOAD_LL_HEADER: ::c_int = 0; +pub const NFT_PAYLOAD_NETWORK_HEADER: ::c_int = 1; +pub const NFT_PAYLOAD_TRANSPORT_HEADER: ::c_int = 2; + +pub const NFT_PAYLOAD_CSUM_NONE: ::c_int = 0; +pub const NFT_PAYLOAD_CSUM_INET: ::c_int = 1; + +pub const NFT_META_LEN: ::c_int = 0; +pub const NFT_META_PROTOCOL: ::c_int = 1; +pub const NFT_META_PRIORITY: ::c_int = 2; +pub const NFT_META_MARK: ::c_int = 3; +pub const NFT_META_IIF: ::c_int = 4; +pub const NFT_META_OIF: ::c_int = 5; +pub const NFT_META_IIFNAME: ::c_int = 6; +pub const NFT_META_OIFNAME: ::c_int = 7; +pub const NFT_META_IIFTYPE: ::c_int = 8; +pub const NFT_META_OIFTYPE: ::c_int = 9; +pub const NFT_META_SKUID: ::c_int = 10; +pub const NFT_META_SKGID: ::c_int = 11; +pub const NFT_META_NFTRACE: ::c_int = 12; +pub const NFT_META_RTCLASSID: ::c_int = 13; +pub const NFT_META_SECMARK: ::c_int = 14; +pub const NFT_META_NFPROTO: ::c_int = 15; +pub const NFT_META_L4PROTO: ::c_int = 16; +pub const NFT_META_BRI_IIFNAME: ::c_int = 17; +pub const NFT_META_BRI_OIFNAME: ::c_int = 18; +pub const NFT_META_PKTTYPE: ::c_int = 19; +pub const NFT_META_CPU: ::c_int = 20; +pub const NFT_META_IIFGROUP: ::c_int = 21; +pub const NFT_META_OIFGROUP: ::c_int = 22; +pub const NFT_META_CGROUP: ::c_int = 23; +pub const NFT_META_PRANDOM: ::c_int = 24; + +pub const NFT_CT_STATE: ::c_int = 0; +pub const NFT_CT_DIRECTION: ::c_int = 1; +pub const NFT_CT_STATUS: ::c_int = 2; +pub const NFT_CT_MARK: ::c_int = 3; +pub const NFT_CT_SECMARK: ::c_int = 4; +pub const NFT_CT_EXPIRATION: ::c_int = 5; +pub const NFT_CT_HELPER: ::c_int = 6; +pub const NFT_CT_L3PROTOCOL: ::c_int = 7; +pub const NFT_CT_SRC: ::c_int = 8; +pub const NFT_CT_DST: ::c_int = 9; +pub const NFT_CT_PROTOCOL: ::c_int = 10; +pub const NFT_CT_PROTO_SRC: ::c_int = 11; +pub const NFT_CT_PROTO_DST: ::c_int = 12; +pub const NFT_CT_LABELS: ::c_int = 13; +pub const NFT_CT_PKTS: ::c_int = 14; +pub const NFT_CT_BYTES: ::c_int = 15; + +pub const NFT_LIMIT_PKTS: ::c_int = 0; +pub const NFT_LIMIT_PKT_BYTES: ::c_int = 1; + +pub const NFT_LIMIT_F_INV: ::c_int = (1 << 0); + +pub const NFT_QUEUE_FLAG_BYPASS: ::c_int = 0x01; +pub const NFT_QUEUE_FLAG_CPU_FANOUT: ::c_int = 0x02; +pub const NFT_QUEUE_FLAG_MASK: ::c_int = 0x03; + +pub const NFT_QUOTA_F_INV: ::c_int = (1 << 0); + +pub const NFT_REJECT_ICMP_UNREACH: ::c_int = 0; +pub const NFT_REJECT_TCP_RST: ::c_int = 1; +pub const NFT_REJECT_ICMPX_UNREACH: ::c_int = 2; + +pub const NFT_REJECT_ICMPX_NO_ROUTE: ::c_int = 0; +pub const NFT_REJECT_ICMPX_PORT_UNREACH: ::c_int = 1; +pub const NFT_REJECT_ICMPX_HOST_UNREACH: ::c_int = 2; +pub const NFT_REJECT_ICMPX_ADMIN_PROHIBITED: ::c_int = 3; + +pub const NFT_NAT_SNAT: ::c_int = 0; +pub const NFT_NAT_DNAT: ::c_int = 1; + +pub const NFT_TRACETYPE_UNSPEC: ::c_int = 0; +pub const NFT_TRACETYPE_POLICY: ::c_int = 1; +pub const NFT_TRACETYPE_RETURN: ::c_int = 2; +pub const NFT_TRACETYPE_RULE: ::c_int = 3; + +pub const NFT_NG_INCREMENTAL: ::c_int = 0; +pub const NFT_NG_RANDOM: ::c_int = 1; + +#[doc(hidden)] +pub const AF_MAX: ::c_int = 42; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; + +f! { + pub fn NLA_ALIGN(len: ::c_int) -> ::c_int { + return ((len) + NLA_ALIGNTO - 1) & !(NLA_ALIGNTO - 1) + } +} + +#[link(name = "util")] +extern { + pub fn sysctl(name: *mut ::c_int, + namelen: ::c_int, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *mut ::c_void, + newlen: ::size_t) + -> ::c_int; + pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; + pub fn backtrace(buf: *mut *mut ::c_void, + sz: ::c_int) -> ::c_int; + pub fn glob64(pattern: *const ::c_char, + flags: ::c_int, + errfunc: ::dox::Option ::c_int>, + pglob: *mut glob64_t) -> ::c_int; + pub fn globfree64(pglob: *mut glob64_t); + pub fn ptrace(request: ::c_uint, ...) -> ::c_long; + pub fn pthread_attr_getaffinity_np(attr: *const ::pthread_attr_t, + cpusetsize: ::size_t, + cpuset: *mut ::cpu_set_t) -> ::c_int; + pub fn pthread_attr_setaffinity_np(attr: *mut ::pthread_attr_t, + cpusetsize: ::size_t, + cpuset: *const ::cpu_set_t) -> ::c_int; + pub fn getpriority(which: ::__priority_which_t, who: ::id_t) -> ::c_int; + pub fn setpriority(which: ::__priority_which_t, who: ::id_t, + prio: ::c_int) -> ::c_int; + pub fn pthread_getaffinity_np(thread: ::pthread_t, + cpusetsize: ::size_t, + cpuset: *mut ::cpu_set_t) -> ::c_int; + pub fn pthread_setaffinity_np(thread: ::pthread_t, + cpusetsize: ::size_t, + cpuset: *const ::cpu_set_t) -> ::c_int; + pub fn sched_getcpu() -> ::c_int; +} + +cfg_if! { + if #[cfg(target_arch = "mips")] { + mod mips32; + pub use self::mips32::*; + } else if #[cfg(target_arch = "mips64")] { + mod mips64; + pub use self::mips64::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1957 @@ +//! Linux-specific definitions for linux-like values + +use dox::{mem, Option}; + +pub type useconds_t = u32; +pub type dev_t = u64; +pub type socklen_t = u32; +pub type pthread_t = c_ulong; +pub type mode_t = u32; +pub type ino64_t = u64; +pub type off64_t = i64; +pub type blkcnt64_t = i64; +pub type rlim64_t = u64; +pub type mqd_t = ::c_int; +pub type nfds_t = ::c_ulong; +pub type nl_item = ::c_int; +pub type idtype_t = ::c_uint; +pub type loff_t = ::c_longlong; + +pub type __u8 = ::c_uchar; +pub type __u16 = ::c_ushort; +pub type __s16 = ::c_short; +pub type __u32 = ::c_uint; +pub type __s32 = ::c_int; + +pub type Elf32_Half = u16; +pub type Elf32_Word = u32; +pub type Elf32_Off = u32; +pub type Elf32_Addr = u32; + +pub type Elf64_Half = u16; +pub type Elf64_Word = u32; +pub type Elf64_Off = u64; +pub type Elf64_Addr = u64; +pub type Elf64_Xword = u64; + +pub enum fpos64_t {} // TODO: fill this out with a struct + +s! { + pub struct dirent { + pub d_ino: ::ino_t, + pub d_off: ::off_t, + pub d_reclen: ::c_ushort, + pub d_type: ::c_uchar, + pub d_name: [::c_char; 256], + } + + pub struct dirent64 { + pub d_ino: ::ino64_t, + pub d_off: ::off64_t, + pub d_reclen: ::c_ushort, + pub d_type: ::c_uchar, + pub d_name: [::c_char; 256], + } + + pub struct rlimit64 { + pub rlim_cur: rlim64_t, + pub rlim_max: rlim64_t, + } + + pub struct glob_t { + pub gl_pathc: ::size_t, + pub gl_pathv: *mut *mut c_char, + pub gl_offs: ::size_t, + pub gl_flags: ::c_int, + + __unused1: *mut ::c_void, + __unused2: *mut ::c_void, + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + } + + pub struct ifaddrs { + pub ifa_next: *mut ifaddrs, + pub ifa_name: *mut c_char, + pub ifa_flags: ::c_uint, + pub ifa_addr: *mut ::sockaddr, + pub ifa_netmask: *mut ::sockaddr, + pub ifa_ifu: *mut ::sockaddr, // FIXME This should be a union + pub ifa_data: *mut ::c_void + } + + pub struct pthread_mutex_t { + #[cfg(any(target_arch = "mips", + target_arch = "arm", + target_arch = "powerpc", + all(target_arch = "x86_64", + target_pointer_width = "32")))] + __align: [::c_long; 0], + #[cfg(not(any(target_arch = "mips", + target_arch = "arm", + target_arch = "powerpc", + all(target_arch = "x86_64", + target_pointer_width = "32"))))] + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_MUTEX_T], + } + + pub struct pthread_rwlock_t { + #[cfg(any(target_arch = "mips", + target_arch = "arm", + target_arch = "powerpc", + all(target_arch = "x86_64", + target_pointer_width = "32")))] + __align: [::c_long; 0], + #[cfg(not(any(target_arch = "mips", + target_arch = "arm", + target_arch = "powerpc", + all(target_arch = "x86_64", + target_pointer_width = "32"))))] + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_RWLOCK_T], + } + + pub struct pthread_mutexattr_t { + #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", + target_arch = "mips64", target_arch = "s390x", + target_arch = "sparc64"))] + __align: [::c_int; 0], + #[cfg(not(any(target_arch = "x86_64", target_arch = "powerpc64", + target_arch = "mips64", target_arch = "s390x", + target_arch = "sparc64", target_arch = "aarch64")))] + __align: [::c_long; 0], + #[cfg(all(target_arch = "aarch64", target_env = "gnu"))] + __align: [::c_long; 0], + #[cfg(all(target_arch = "aarch64", target_env = "musl"))] + __align: [::c_int; 0], + size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T], + } + + pub struct pthread_rwlockattr_t { + #[cfg(any(target_env = "musl"))] + __align: [::c_int; 0], + #[cfg(not(any(target_env = "musl")))] + __align: [::c_long; 0], + size: [u8; __SIZEOF_PTHREAD_RWLOCKATTR_T], + } + + pub struct pthread_cond_t { + #[cfg(any(target_env = "musl"))] + __align: [*const ::c_void; 0], + #[cfg(not(any(target_env = "musl")))] + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_COND_T], + } + + pub struct pthread_condattr_t { + __align: [::c_int; 0], + size: [u8; __SIZEOF_PTHREAD_CONDATTR_T], + } + + pub struct passwd { + pub pw_name: *mut ::c_char, + pub pw_passwd: *mut ::c_char, + pub pw_uid: ::uid_t, + pub pw_gid: ::gid_t, + pub pw_gecos: *mut ::c_char, + pub pw_dir: *mut ::c_char, + pub pw_shell: *mut ::c_char, + } + + pub struct spwd { + pub sp_namp: *mut ::c_char, + pub sp_pwdp: *mut ::c_char, + pub sp_lstchg: ::c_long, + pub sp_min: ::c_long, + pub sp_max: ::c_long, + pub sp_warn: ::c_long, + pub sp_inact: ::c_long, + pub sp_expire: ::c_long, + pub sp_flag: ::c_ulong, + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + #[cfg(target_endian = "little")] + pub f_fsid: ::c_ulong, + #[cfg(all(target_pointer_width = "32", not(target_arch = "x86_64")))] + __f_unused: ::c_int, + #[cfg(target_endian = "big")] + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct dqblk { + pub dqb_bhardlimit: ::uint64_t, + pub dqb_bsoftlimit: ::uint64_t, + pub dqb_curspace: ::uint64_t, + pub dqb_ihardlimit: ::uint64_t, + pub dqb_isoftlimit: ::uint64_t, + pub dqb_curinodes: ::uint64_t, + pub dqb_btime: ::uint64_t, + pub dqb_itime: ::uint64_t, + pub dqb_valid: ::uint32_t, + } + + pub struct signalfd_siginfo { + pub ssi_signo: ::uint32_t, + pub ssi_errno: ::int32_t, + pub ssi_code: ::int32_t, + pub ssi_pid: ::uint32_t, + pub ssi_uid: ::uint32_t, + pub ssi_fd: ::int32_t, + pub ssi_tid: ::uint32_t, + pub ssi_band: ::uint32_t, + pub ssi_overrun: ::uint32_t, + pub ssi_trapno: ::uint32_t, + pub ssi_status: ::int32_t, + pub ssi_int: ::int32_t, + pub ssi_ptr: ::uint64_t, + pub ssi_utime: ::uint64_t, + pub ssi_stime: ::uint64_t, + pub ssi_addr: ::uint64_t, + _pad: [::uint8_t; 48], + } + + pub struct itimerspec { + pub it_interval: ::timespec, + pub it_value: ::timespec, + } + + pub struct fsid_t { + __val: [::c_int; 2], + } + + // x32 compatibility + // See https://sourceware.org/bugzilla/show_bug.cgi?id=21279 + pub struct mq_attr { + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + pub mq_flags: i64, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + pub mq_maxmsg: i64, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + pub mq_msgsize: i64, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + pub mq_curmsgs: i64, + #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] + pad: [i64; 4], + + #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] + pub mq_flags: ::c_long, + #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] + pub mq_maxmsg: ::c_long, + #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] + pub mq_msgsize: ::c_long, + #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] + pub mq_curmsgs: ::c_long, + #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] + pad: [::c_long; 4], + } + + pub struct cpu_set_t { + #[cfg(all(target_pointer_width = "32", + not(target_arch = "x86_64")))] + bits: [u32; 32], + #[cfg(not(all(target_pointer_width = "32", + not(target_arch = "x86_64"))))] + bits: [u64; 16], + } + + pub struct if_nameindex { + pub if_index: ::c_uint, + pub if_name: *mut ::c_char, + } + + // System V IPC + pub struct msginfo { + pub msgpool: ::c_int, + pub msgmap: ::c_int, + pub msgmax: ::c_int, + pub msgmnb: ::c_int, + pub msgmni: ::c_int, + pub msgssz: ::c_int, + pub msgtql: ::c_int, + pub msgseg: ::c_ushort, + } + + pub struct mmsghdr { + pub msg_hdr: ::msghdr, + pub msg_len: ::c_uint, + } + + pub struct sembuf { + pub sem_num: ::c_ushort, + pub sem_op: ::c_short, + pub sem_flg: ::c_short, + } + + pub struct input_event { + pub time: ::timeval, + pub type_: ::__u16, + pub code: ::__u16, + pub value: ::__s32, + } + + pub struct input_id { + pub bustype: ::__u16, + pub vendor: ::__u16, + pub product: ::__u16, + pub version: ::__u16, + } + + pub struct input_absinfo { + pub value: ::__s32, + pub minimum: ::__s32, + pub maximum: ::__s32, + pub fuzz: ::__s32, + pub flat: ::__s32, + pub resolution: ::__s32, + } + + pub struct input_keymap_entry { + pub flags: ::__u8, + pub len: ::__u8, + pub index: ::__u16, + pub keycode: ::__u32, + pub scancode: [::__u8; 32], + } + + pub struct input_mask { + pub type_: ::__u32, + pub codes_size: ::__u32, + pub codes_ptr: ::__u64, + } + + pub struct ff_replay { + pub length: ::__u16, + pub delay: ::__u16, + } + + pub struct ff_trigger { + pub button: ::__u16, + pub interval: ::__u16, + } + + pub struct ff_envelope { + pub attack_length: ::__u16, + pub attack_level: ::__u16, + pub fade_length: ::__u16, + pub fade_level: ::__u16, + } + + pub struct ff_constant_effect { + pub level: ::__s16, + pub envelope: ff_envelope, + } + + pub struct ff_ramp_effect { + pub start_level: ::__s16, + pub end_level: ::__s16, + pub envelope: ff_envelope, + } + + pub struct ff_condition_effect { + pub right_saturation: ::__u16, + pub left_saturation: ::__u16, + + pub right_coeff: ::__s16, + pub left_coeff: ::__s16, + + pub deadband: ::__u16, + pub center: ::__s16, + } + + pub struct ff_periodic_effect { + pub waveform: ::__u16, + pub period: ::__u16, + pub magnitude: ::__s16, + pub offset: ::__s16, + pub phase: ::__u16, + + pub envelope: ff_envelope, + + pub custom_len: ::__u32, + pub custom_data: *mut ::__s16, + } + + pub struct ff_rumble_effect { + pub strong_magnitude: ::__u16, + pub weak_magnitude: ::__u16, + } + + pub struct ff_effect { + pub type_: ::__u16, + pub id: ::__s16, + pub direction: ::__u16, + pub trigger: ff_trigger, + pub replay: ff_replay, + // FIXME this is actually a union + #[cfg(target_pointer_width = "64")] + pub u: [u64; 4], + #[cfg(target_pointer_width = "32")] + pub u: [u32; 7], + } + + pub struct dl_phdr_info { + #[cfg(target_pointer_width = "64")] + pub dlpi_addr: Elf64_Addr, + #[cfg(target_pointer_width = "32")] + pub dlpi_addr: Elf32_Addr, + + pub dlpi_name: *const ::c_char, + + #[cfg(target_pointer_width = "64")] + pub dlpi_phdr: *const Elf64_Phdr, + #[cfg(target_pointer_width = "32")] + pub dlpi_phdr: *const Elf32_Phdr, + + #[cfg(target_pointer_width = "64")] + pub dlpi_phnum: Elf64_Half, + #[cfg(target_pointer_width = "32")] + pub dlpi_phnum: Elf32_Half, + + pub dlpi_adds: ::c_ulonglong, + pub dlpi_subs: ::c_ulonglong, + pub dlpi_tls_modid: ::size_t, + pub dlpi_tls_data: *mut ::c_void, + } + + pub struct Elf32_Phdr { + pub p_type: Elf32_Word, + pub p_offset: Elf32_Off, + pub p_vaddr: Elf32_Addr, + pub p_paddr: Elf32_Addr, + pub p_filesz: Elf32_Word, + pub p_memsz: Elf32_Word, + pub p_flags: Elf32_Word, + pub p_align: Elf32_Word, + } + + pub struct Elf64_Phdr { + pub p_type: Elf64_Word, + pub p_flags: Elf64_Word, + pub p_offset: Elf64_Off, + pub p_vaddr: Elf64_Addr, + pub p_paddr: Elf64_Addr, + pub p_filesz: Elf64_Xword, + pub p_memsz: Elf64_Xword, + pub p_align: Elf64_Xword, + } + + pub struct ucred { + pub pid: ::pid_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + } + + pub struct mntent { + pub mnt_fsname: *mut ::c_char, + pub mnt_dir: *mut ::c_char, + pub mnt_type: *mut ::c_char, + pub mnt_opts: *mut ::c_char, + pub mnt_freq: ::c_int, + pub mnt_passno: ::c_int, + } + + pub struct posix_spawn_file_actions_t { + __allocated: ::c_int, + __used: ::c_int, + __actions: *mut ::c_int, + __pad: [::c_int; 16], + } + + pub struct posix_spawnattr_t { + __flags: ::c_short, + __pgrp: ::pid_t, + __sd: ::sigset_t, + __ss: ::sigset_t, + #[cfg(target_env = "musl")] + __prio: ::c_int, + #[cfg(not(target_env = "musl"))] + __sp: ::sched_param, + __policy: ::c_int, + __pad: [::c_int; 16], + } + + pub struct genlmsghdr { + cmd: u8, + version: u8, + reserved: u16, + } +} + +pub const ABDAY_1: ::nl_item = 0x20000; +pub const ABDAY_2: ::nl_item = 0x20001; +pub const ABDAY_3: ::nl_item = 0x20002; +pub const ABDAY_4: ::nl_item = 0x20003; +pub const ABDAY_5: ::nl_item = 0x20004; +pub const ABDAY_6: ::nl_item = 0x20005; +pub const ABDAY_7: ::nl_item = 0x20006; + +pub const DAY_1: ::nl_item = 0x20007; +pub const DAY_2: ::nl_item = 0x20008; +pub const DAY_3: ::nl_item = 0x20009; +pub const DAY_4: ::nl_item = 0x2000A; +pub const DAY_5: ::nl_item = 0x2000B; +pub const DAY_6: ::nl_item = 0x2000C; +pub const DAY_7: ::nl_item = 0x2000D; + +pub const ABMON_1: ::nl_item = 0x2000E; +pub const ABMON_2: ::nl_item = 0x2000F; +pub const ABMON_3: ::nl_item = 0x20010; +pub const ABMON_4: ::nl_item = 0x20011; +pub const ABMON_5: ::nl_item = 0x20012; +pub const ABMON_6: ::nl_item = 0x20013; +pub const ABMON_7: ::nl_item = 0x20014; +pub const ABMON_8: ::nl_item = 0x20015; +pub const ABMON_9: ::nl_item = 0x20016; +pub const ABMON_10: ::nl_item = 0x20017; +pub const ABMON_11: ::nl_item = 0x20018; +pub const ABMON_12: ::nl_item = 0x20019; + +pub const MON_1: ::nl_item = 0x2001A; +pub const MON_2: ::nl_item = 0x2001B; +pub const MON_3: ::nl_item = 0x2001C; +pub const MON_4: ::nl_item = 0x2001D; +pub const MON_5: ::nl_item = 0x2001E; +pub const MON_6: ::nl_item = 0x2001F; +pub const MON_7: ::nl_item = 0x20020; +pub const MON_8: ::nl_item = 0x20021; +pub const MON_9: ::nl_item = 0x20022; +pub const MON_10: ::nl_item = 0x20023; +pub const MON_11: ::nl_item = 0x20024; +pub const MON_12: ::nl_item = 0x20025; + +pub const AM_STR: ::nl_item = 0x20026; +pub const PM_STR: ::nl_item = 0x20027; + +pub const D_T_FMT: ::nl_item = 0x20028; +pub const D_FMT: ::nl_item = 0x20029; +pub const T_FMT: ::nl_item = 0x2002A; +pub const T_FMT_AMPM: ::nl_item = 0x2002B; + +pub const ERA: ::nl_item = 0x2002C; +pub const ERA_D_FMT: ::nl_item = 0x2002E; +pub const ALT_DIGITS: ::nl_item = 0x2002F; +pub const ERA_D_T_FMT: ::nl_item = 0x20030; +pub const ERA_T_FMT: ::nl_item = 0x20031; + +pub const CODESET: ::nl_item = 14; + +pub const CRNCYSTR: ::nl_item = 0x4000F; + +pub const RUSAGE_THREAD: ::c_int = 1; +pub const RUSAGE_CHILDREN: ::c_int = -1; + +pub const RADIXCHAR: ::nl_item = 0x10000; +pub const THOUSEP: ::nl_item = 0x10001; + +pub const YESEXPR: ::nl_item = 0x50000; +pub const NOEXPR: ::nl_item = 0x50001; +pub const YESSTR: ::nl_item = 0x50002; +pub const NOSTR: ::nl_item = 0x50003; + +pub const FILENAME_MAX: ::c_uint = 4096; +pub const L_tmpnam: ::c_uint = 20; +pub const _PC_LINK_MAX: ::c_int = 0; +pub const _PC_MAX_CANON: ::c_int = 1; +pub const _PC_MAX_INPUT: ::c_int = 2; +pub const _PC_NAME_MAX: ::c_int = 3; +pub const _PC_PATH_MAX: ::c_int = 4; +pub const _PC_PIPE_BUF: ::c_int = 5; +pub const _PC_CHOWN_RESTRICTED: ::c_int = 6; +pub const _PC_NO_TRUNC: ::c_int = 7; +pub const _PC_VDISABLE: ::c_int = 8; +pub const _PC_SYNC_IO: ::c_int = 9; +pub const _PC_ASYNC_IO: ::c_int = 10; +pub const _PC_PRIO_IO: ::c_int = 11; +pub const _PC_SOCK_MAXBUF: ::c_int = 12; +pub const _PC_FILESIZEBITS: ::c_int = 13; +pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 14; +pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 15; +pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 16; +pub const _PC_REC_XFER_ALIGN: ::c_int = 17; +pub const _PC_ALLOC_SIZE_MIN: ::c_int = 18; +pub const _PC_SYMLINK_MAX: ::c_int = 19; +pub const _PC_2_SYMLINKS: ::c_int = 20; + +pub const _SC_ARG_MAX: ::c_int = 0; +pub const _SC_CHILD_MAX: ::c_int = 1; +pub const _SC_CLK_TCK: ::c_int = 2; +pub const _SC_NGROUPS_MAX: ::c_int = 3; +pub const _SC_OPEN_MAX: ::c_int = 4; +pub const _SC_STREAM_MAX: ::c_int = 5; +pub const _SC_TZNAME_MAX: ::c_int = 6; +pub const _SC_JOB_CONTROL: ::c_int = 7; +pub const _SC_SAVED_IDS: ::c_int = 8; +pub const _SC_REALTIME_SIGNALS: ::c_int = 9; +pub const _SC_PRIORITY_SCHEDULING: ::c_int = 10; +pub const _SC_TIMERS: ::c_int = 11; +pub const _SC_ASYNCHRONOUS_IO: ::c_int = 12; +pub const _SC_PRIORITIZED_IO: ::c_int = 13; +pub const _SC_SYNCHRONIZED_IO: ::c_int = 14; +pub const _SC_FSYNC: ::c_int = 15; +pub const _SC_MAPPED_FILES: ::c_int = 16; +pub const _SC_MEMLOCK: ::c_int = 17; +pub const _SC_MEMLOCK_RANGE: ::c_int = 18; +pub const _SC_MEMORY_PROTECTION: ::c_int = 19; +pub const _SC_MESSAGE_PASSING: ::c_int = 20; +pub const _SC_SEMAPHORES: ::c_int = 21; +pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 22; +pub const _SC_AIO_LISTIO_MAX: ::c_int = 23; +pub const _SC_AIO_MAX: ::c_int = 24; +pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 25; +pub const _SC_DELAYTIMER_MAX: ::c_int = 26; +pub const _SC_MQ_OPEN_MAX: ::c_int = 27; +pub const _SC_MQ_PRIO_MAX: ::c_int = 28; +pub const _SC_VERSION: ::c_int = 29; +pub const _SC_PAGESIZE: ::c_int = 30; +pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; +pub const _SC_RTSIG_MAX: ::c_int = 31; +pub const _SC_SEM_NSEMS_MAX: ::c_int = 32; +pub const _SC_SEM_VALUE_MAX: ::c_int = 33; +pub const _SC_SIGQUEUE_MAX: ::c_int = 34; +pub const _SC_TIMER_MAX: ::c_int = 35; +pub const _SC_BC_BASE_MAX: ::c_int = 36; +pub const _SC_BC_DIM_MAX: ::c_int = 37; +pub const _SC_BC_SCALE_MAX: ::c_int = 38; +pub const _SC_BC_STRING_MAX: ::c_int = 39; +pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 40; +pub const _SC_EXPR_NEST_MAX: ::c_int = 42; +pub const _SC_LINE_MAX: ::c_int = 43; +pub const _SC_RE_DUP_MAX: ::c_int = 44; +pub const _SC_2_VERSION: ::c_int = 46; +pub const _SC_2_C_BIND: ::c_int = 47; +pub const _SC_2_C_DEV: ::c_int = 48; +pub const _SC_2_FORT_DEV: ::c_int = 49; +pub const _SC_2_FORT_RUN: ::c_int = 50; +pub const _SC_2_SW_DEV: ::c_int = 51; +pub const _SC_2_LOCALEDEF: ::c_int = 52; +pub const _SC_UIO_MAXIOV: ::c_int = 60; +pub const _SC_IOV_MAX: ::c_int = 60; +pub const _SC_THREADS: ::c_int = 67; +pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 68; +pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 69; +pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 70; +pub const _SC_LOGIN_NAME_MAX: ::c_int = 71; +pub const _SC_TTY_NAME_MAX: ::c_int = 72; +pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 73; +pub const _SC_THREAD_KEYS_MAX: ::c_int = 74; +pub const _SC_THREAD_STACK_MIN: ::c_int = 75; +pub const _SC_THREAD_THREADS_MAX: ::c_int = 76; +pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 77; +pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 78; +pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 79; +pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 80; +pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 81; +pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 82; +pub const _SC_NPROCESSORS_CONF: ::c_int = 83; +pub const _SC_NPROCESSORS_ONLN: ::c_int = 84; +pub const _SC_PHYS_PAGES: ::c_int = 85; +pub const _SC_AVPHYS_PAGES: ::c_int = 86; +pub const _SC_ATEXIT_MAX: ::c_int = 87; +pub const _SC_PASS_MAX: ::c_int = 88; +pub const _SC_XOPEN_VERSION: ::c_int = 89; +pub const _SC_XOPEN_XCU_VERSION: ::c_int = 90; +pub const _SC_XOPEN_UNIX: ::c_int = 91; +pub const _SC_XOPEN_CRYPT: ::c_int = 92; +pub const _SC_XOPEN_ENH_I18N: ::c_int = 93; +pub const _SC_XOPEN_SHM: ::c_int = 94; +pub const _SC_2_CHAR_TERM: ::c_int = 95; +pub const _SC_2_UPE: ::c_int = 97; +pub const _SC_XOPEN_XPG2: ::c_int = 98; +pub const _SC_XOPEN_XPG3: ::c_int = 99; +pub const _SC_XOPEN_XPG4: ::c_int = 100; +pub const _SC_NZERO: ::c_int = 109; +pub const _SC_XBS5_ILP32_OFF32: ::c_int = 125; +pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 126; +pub const _SC_XBS5_LP64_OFF64: ::c_int = 127; +pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 128; +pub const _SC_XOPEN_LEGACY: ::c_int = 129; +pub const _SC_XOPEN_REALTIME: ::c_int = 130; +pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 131; +pub const _SC_ADVISORY_INFO: ::c_int = 132; +pub const _SC_BARRIERS: ::c_int = 133; +pub const _SC_CLOCK_SELECTION: ::c_int = 137; +pub const _SC_CPUTIME: ::c_int = 138; +pub const _SC_THREAD_CPUTIME: ::c_int = 139; +pub const _SC_MONOTONIC_CLOCK: ::c_int = 149; +pub const _SC_READER_WRITER_LOCKS: ::c_int = 153; +pub const _SC_SPIN_LOCKS: ::c_int = 154; +pub const _SC_REGEXP: ::c_int = 155; +pub const _SC_SHELL: ::c_int = 157; +pub const _SC_SPAWN: ::c_int = 159; +pub const _SC_SPORADIC_SERVER: ::c_int = 160; +pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 161; +pub const _SC_TIMEOUTS: ::c_int = 164; +pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 165; +pub const _SC_2_PBS: ::c_int = 168; +pub const _SC_2_PBS_ACCOUNTING: ::c_int = 169; +pub const _SC_2_PBS_LOCATE: ::c_int = 170; +pub const _SC_2_PBS_MESSAGE: ::c_int = 171; +pub const _SC_2_PBS_TRACK: ::c_int = 172; +pub const _SC_SYMLOOP_MAX: ::c_int = 173; +pub const _SC_STREAMS: ::c_int = 174; +pub const _SC_2_PBS_CHECKPOINT: ::c_int = 175; +pub const _SC_V6_ILP32_OFF32: ::c_int = 176; +pub const _SC_V6_ILP32_OFFBIG: ::c_int = 177; +pub const _SC_V6_LP64_OFF64: ::c_int = 178; +pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 179; +pub const _SC_HOST_NAME_MAX: ::c_int = 180; +pub const _SC_TRACE: ::c_int = 181; +pub const _SC_TRACE_EVENT_FILTER: ::c_int = 182; +pub const _SC_TRACE_INHERIT: ::c_int = 183; +pub const _SC_TRACE_LOG: ::c_int = 184; +pub const _SC_IPV6: ::c_int = 235; +pub const _SC_RAW_SOCKETS: ::c_int = 236; +pub const _SC_V7_ILP32_OFF32: ::c_int = 237; +pub const _SC_V7_ILP32_OFFBIG: ::c_int = 238; +pub const _SC_V7_LP64_OFF64: ::c_int = 239; +pub const _SC_V7_LPBIG_OFFBIG: ::c_int = 240; +pub const _SC_SS_REPL_MAX: ::c_int = 241; +pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 242; +pub const _SC_TRACE_NAME_MAX: ::c_int = 243; +pub const _SC_TRACE_SYS_MAX: ::c_int = 244; +pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 245; +pub const _SC_XOPEN_STREAMS: ::c_int = 246; +pub const _SC_THREAD_ROBUST_PRIO_INHERIT: ::c_int = 247; +pub const _SC_THREAD_ROBUST_PRIO_PROTECT: ::c_int = 248; + +pub const RLIM_SAVED_MAX: ::rlim_t = RLIM_INFINITY; +pub const RLIM_SAVED_CUR: ::rlim_t = RLIM_INFINITY; + +pub const GLOB_ERR: ::c_int = 1 << 0; +pub const GLOB_MARK: ::c_int = 1 << 1; +pub const GLOB_NOSORT: ::c_int = 1 << 2; +pub const GLOB_DOOFFS: ::c_int = 1 << 3; +pub const GLOB_NOCHECK: ::c_int = 1 << 4; +pub const GLOB_APPEND: ::c_int = 1 << 5; +pub const GLOB_NOESCAPE: ::c_int = 1 << 6; + +pub const GLOB_NOSPACE: ::c_int = 1; +pub const GLOB_ABORTED: ::c_int = 2; +pub const GLOB_NOMATCH: ::c_int = 3; + +pub const POSIX_MADV_NORMAL: ::c_int = 0; +pub const POSIX_MADV_RANDOM: ::c_int = 1; +pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_MADV_WILLNEED: ::c_int = 3; + +pub const S_IEXEC: mode_t = 64; +pub const S_IWRITE: mode_t = 128; +pub const S_IREAD: mode_t = 256; + +pub const F_LOCK: ::c_int = 1; +pub const F_TEST: ::c_int = 3; +pub const F_TLOCK: ::c_int = 2; +pub const F_ULOCK: ::c_int = 0; + +pub const IFF_LOWER_UP: ::c_int = 0x10000; +pub const IFF_DORMANT: ::c_int = 0x20000; +pub const IFF_ECHO: ::c_int = 0x40000; + +// linux/if_tun.h +pub const IFF_TUN: ::c_short = 0x0001; +pub const IFF_TAP: ::c_short = 0x0002; +pub const IFF_NO_PI: ::c_short = 0x1000; +// Read queue size +pub const TUN_READQ_SIZE: ::c_short = 500; +// TUN device type flags: deprecated. Use IFF_TUN/IFF_TAP instead. +pub const TUN_TUN_DEV: ::c_short = ::IFF_TUN; +pub const TUN_TAP_DEV: ::c_short = ::IFF_TAP; +pub const TUN_TYPE_MASK: ::c_short = 0x000f; +// This flag has no real effect +pub const IFF_ONE_QUEUE: ::c_short = 0x2000; +pub const IFF_VNET_HDR: ::c_short = 0x4000; +pub const IFF_TUN_EXCL: ::c_short = 0x8000; +pub const IFF_MULTI_QUEUE: ::c_short = 0x0100; +pub const IFF_ATTACH_QUEUE: ::c_short = 0x0200; +pub const IFF_DETACH_QUEUE: ::c_short = 0x0400; +// read-only flag +pub const IFF_PERSIST: ::c_short = 0x0800; +pub const IFF_NOFILTER: ::c_short = 0x1000; + +pub const ST_RDONLY: ::c_ulong = 1; +pub const ST_NOSUID: ::c_ulong = 2; +pub const ST_NODEV: ::c_ulong = 4; +pub const ST_NOEXEC: ::c_ulong = 8; +pub const ST_SYNCHRONOUS: ::c_ulong = 16; +pub const ST_MANDLOCK: ::c_ulong = 64; +pub const ST_WRITE: ::c_ulong = 128; +pub const ST_APPEND: ::c_ulong = 256; +pub const ST_IMMUTABLE: ::c_ulong = 512; +pub const ST_NOATIME: ::c_ulong = 1024; +pub const ST_NODIRATIME: ::c_ulong = 2048; + +pub const RTLD_NEXT: *mut ::c_void = -1i64 as *mut ::c_void; +pub const RTLD_DEFAULT: *mut ::c_void = 0i64 as *mut ::c_void; +pub const RTLD_NODELETE: ::c_int = 0x1000; +pub const RTLD_NOW: ::c_int = 0x2; + +pub const TCP_MD5SIG: ::c_int = 14; + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_MUTEX_T], +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_COND_T], +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_RWLOCK_T], +}; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; +pub const PTHREAD_PROCESS_PRIVATE: ::c_int = 0; +pub const PTHREAD_PROCESS_SHARED: ::c_int = 1; +pub const __SIZEOF_PTHREAD_COND_T: usize = 48; + +pub const RENAME_NOREPLACE: ::c_int = 1; +pub const RENAME_EXCHANGE: ::c_int = 2; +pub const RENAME_WHITEOUT: ::c_int = 4; + +pub const SCHED_OTHER: ::c_int = 0; +pub const SCHED_FIFO: ::c_int = 1; +pub const SCHED_RR: ::c_int = 2; +pub const SCHED_BATCH: ::c_int = 3; +pub const SCHED_IDLE: ::c_int = 5; + +// netinet/in.h +// NOTE: These are in addition to the constants defined in src/unix/mod.rs + +// IPPROTO_IP defined in src/unix/mod.rs +/// Hop-by-hop option header +pub const IPPROTO_HOPOPTS: ::c_int = 0; +// IPPROTO_ICMP defined in src/unix/mod.rs +/// group mgmt protocol +pub const IPPROTO_IGMP: ::c_int = 2; +/// for compatibility +pub const IPPROTO_IPIP: ::c_int = 4; +// IPPROTO_TCP defined in src/unix/mod.rs +/// exterior gateway protocol +pub const IPPROTO_EGP: ::c_int = 8; +/// pup +pub const IPPROTO_PUP: ::c_int = 12; +// IPPROTO_UDP defined in src/unix/mod.rs +/// xns idp +pub const IPPROTO_IDP: ::c_int = 22; +/// tp-4 w/ class negotiation +pub const IPPROTO_TP: ::c_int = 29; +/// DCCP +pub const IPPROTO_DCCP: ::c_int = 33; +// IPPROTO_IPV6 defined in src/unix/mod.rs +/// IP6 routing header +pub const IPPROTO_ROUTING: ::c_int = 43; +/// IP6 fragmentation header +pub const IPPROTO_FRAGMENT: ::c_int = 44; +/// resource reservation +pub const IPPROTO_RSVP: ::c_int = 46; +/// General Routing Encap. +pub const IPPROTO_GRE: ::c_int = 47; +/// IP6 Encap Sec. Payload +pub const IPPROTO_ESP: ::c_int = 50; +/// IP6 Auth Header +pub const IPPROTO_AH: ::c_int = 51; +// IPPROTO_ICMPV6 defined in src/unix/mod.rs +/// IP6 no next header +pub const IPPROTO_NONE: ::c_int = 59; +/// IP6 destination option +pub const IPPROTO_DSTOPTS: ::c_int = 60; +pub const IPPROTO_MTP: ::c_int = 92; +pub const IPPROTO_BEETPH: ::c_int = 94; +/// encapsulation header +pub const IPPROTO_ENCAP: ::c_int = 98; +/// Protocol indep. multicast +pub const IPPROTO_PIM: ::c_int = 103; +/// IP Payload Comp. Protocol +pub const IPPROTO_COMP: ::c_int = 108; +/// SCTP +pub const IPPROTO_SCTP: ::c_int = 132; +pub const IPPROTO_MH: ::c_int = 135; +pub const IPPROTO_UDPLITE: ::c_int = 136; +pub const IPPROTO_MPLS: ::c_int = 137; +/// raw IP packet +pub const IPPROTO_RAW: ::c_int = 255; +pub const IPPROTO_MAX: ::c_int = 256; + +pub const AF_IB: ::c_int = 27; +pub const AF_MPLS: ::c_int = 28; +pub const AF_NFC: ::c_int = 39; +pub const AF_VSOCK: ::c_int = 40; +pub const PF_IB: ::c_int = AF_IB; +pub const PF_MPLS: ::c_int = AF_MPLS; +pub const PF_NFC: ::c_int = AF_NFC; +pub const PF_VSOCK: ::c_int = AF_VSOCK; + +// System V IPC +pub const IPC_PRIVATE: ::key_t = 0; + +pub const IPC_CREAT: ::c_int = 0o1000; +pub const IPC_EXCL: ::c_int = 0o2000; +pub const IPC_NOWAIT: ::c_int = 0o4000; + +pub const IPC_RMID: ::c_int = 0; +pub const IPC_SET: ::c_int = 1; +pub const IPC_STAT: ::c_int = 2; +pub const IPC_INFO: ::c_int = 3; +pub const MSG_STAT: ::c_int = 11; +pub const MSG_INFO: ::c_int = 12; + +pub const MSG_NOERROR: ::c_int = 0o10000; +pub const MSG_EXCEPT: ::c_int = 0o20000; +pub const MSG_COPY: ::c_int = 0o40000; + +pub const SHM_R: ::c_int = 0o400; +pub const SHM_W: ::c_int = 0o200; + +pub const SHM_RDONLY: ::c_int = 0o10000; +pub const SHM_RND: ::c_int = 0o20000; +pub const SHM_REMAP: ::c_int = 0o40000; +pub const SHM_EXEC: ::c_int = 0o100000; + +pub const SHM_LOCK: ::c_int = 11; +pub const SHM_UNLOCK: ::c_int = 12; + +pub const SHM_HUGETLB: ::c_int = 0o4000; +pub const SHM_NORESERVE: ::c_int = 0o10000; + +pub const EPOLLRDHUP: ::c_int = 0x2000; +pub const EPOLLEXCLUSIVE: ::c_int = 0x10000000; +pub const EPOLLONESHOT: ::c_int = 0x40000000; + +pub const QFMT_VFS_OLD: ::c_int = 1; +pub const QFMT_VFS_V0: ::c_int = 2; +pub const QFMT_VFS_V1: ::c_int = 4; + +pub const EFD_SEMAPHORE: ::c_int = 0x1; + +pub const LOG_NFACILITIES: ::c_int = 24; + +pub const SEM_FAILED: *mut ::sem_t = 0 as *mut sem_t; + +pub const RB_AUTOBOOT: ::c_int = 0x01234567u32 as i32; +pub const RB_HALT_SYSTEM: ::c_int = 0xcdef0123u32 as i32; +pub const RB_ENABLE_CAD: ::c_int = 0x89abcdefu32 as i32; +pub const RB_DISABLE_CAD: ::c_int = 0x00000000u32 as i32; +pub const RB_POWER_OFF: ::c_int = 0x4321fedcu32 as i32; +pub const RB_SW_SUSPEND: ::c_int = 0xd000fce2u32 as i32; +pub const RB_KEXEC: ::c_int = 0x45584543u32 as i32; + +pub const AI_PASSIVE: ::c_int = 0x0001; +pub const AI_CANONNAME: ::c_int = 0x0002; +pub const AI_NUMERICHOST: ::c_int = 0x0004; +pub const AI_V4MAPPED: ::c_int = 0x0008; +pub const AI_ALL: ::c_int = 0x0010; +pub const AI_ADDRCONFIG: ::c_int = 0x0020; + +pub const AI_NUMERICSERV: ::c_int = 0x0400; + +pub const EAI_BADFLAGS: ::c_int = -1; +pub const EAI_NONAME: ::c_int = -2; +pub const EAI_AGAIN: ::c_int = -3; +pub const EAI_FAIL: ::c_int = -4; +pub const EAI_NODATA: ::c_int = -5; +pub const EAI_FAMILY: ::c_int = -6; +pub const EAI_SOCKTYPE: ::c_int = -7; +pub const EAI_SERVICE: ::c_int = -8; +pub const EAI_MEMORY: ::c_int = -10; +pub const EAI_SYSTEM: ::c_int = -11; +pub const EAI_OVERFLOW: ::c_int = -12; + +pub const NI_NUMERICHOST: ::c_int = 1; +pub const NI_NUMERICSERV: ::c_int = 2; +pub const NI_NOFQDN: ::c_int = 4; +pub const NI_NAMEREQD: ::c_int = 8; +pub const NI_DGRAM: ::c_int = 16; + +pub const SYNC_FILE_RANGE_WAIT_BEFORE: ::c_uint = 1; +pub const SYNC_FILE_RANGE_WRITE: ::c_uint = 2; +pub const SYNC_FILE_RANGE_WAIT_AFTER: ::c_uint = 4; + +pub const AIO_CANCELED: ::c_int = 0; +pub const AIO_NOTCANCELED: ::c_int = 1; +pub const AIO_ALLDONE: ::c_int = 2; +pub const LIO_READ: ::c_int = 0; +pub const LIO_WRITE: ::c_int = 1; +pub const LIO_NOP: ::c_int = 2; +pub const LIO_WAIT: ::c_int = 0; +pub const LIO_NOWAIT: ::c_int = 1; + +pub const MREMAP_MAYMOVE: ::c_int = 1; +pub const MREMAP_FIXED: ::c_int = 2; + +pub const PR_SET_PDEATHSIG: ::c_int = 1; +pub const PR_GET_PDEATHSIG: ::c_int = 2; + +pub const PR_GET_DUMPABLE: ::c_int = 3; +pub const PR_SET_DUMPABLE: ::c_int = 4; + +pub const PR_GET_UNALIGN: ::c_int = 5; +pub const PR_SET_UNALIGN: ::c_int = 6; +pub const PR_UNALIGN_NOPRINT: ::c_int = 1; +pub const PR_UNALIGN_SIGBUS: ::c_int = 2; + +pub const PR_GET_KEEPCAPS: ::c_int = 7; +pub const PR_SET_KEEPCAPS: ::c_int = 8; + +pub const PR_GET_FPEMU: ::c_int = 9; +pub const PR_SET_FPEMU: ::c_int = 10; +pub const PR_FPEMU_NOPRINT: ::c_int = 1; +pub const PR_FPEMU_SIGFPE: ::c_int = 2; + +pub const PR_GET_FPEXC: ::c_int = 11; +pub const PR_SET_FPEXC: ::c_int = 12; +pub const PR_FP_EXC_SW_ENABLE: ::c_int = 0x80; +pub const PR_FP_EXC_DIV: ::c_int = 0x010000; +pub const PR_FP_EXC_OVF: ::c_int = 0x020000; +pub const PR_FP_EXC_UND: ::c_int = 0x040000; +pub const PR_FP_EXC_RES: ::c_int = 0x080000; +pub const PR_FP_EXC_INV: ::c_int = 0x100000; +pub const PR_FP_EXC_DISABLED: ::c_int = 0; +pub const PR_FP_EXC_NONRECOV: ::c_int = 1; +pub const PR_FP_EXC_ASYNC: ::c_int = 2; +pub const PR_FP_EXC_PRECISE: ::c_int = 3; + +pub const PR_GET_TIMING: ::c_int = 13; +pub const PR_SET_TIMING: ::c_int = 14; +pub const PR_TIMING_STATISTICAL: ::c_int = 0; +pub const PR_TIMING_TIMESTAMP: ::c_int = 1; + +pub const PR_SET_NAME: ::c_int = 15; +pub const PR_GET_NAME: ::c_int = 16; + +pub const PR_GET_ENDIAN: ::c_int = 19; +pub const PR_SET_ENDIAN: ::c_int = 20; +pub const PR_ENDIAN_BIG: ::c_int = 0; +pub const PR_ENDIAN_LITTLE: ::c_int = 1; +pub const PR_ENDIAN_PPC_LITTLE: ::c_int = 2; + +pub const PR_GET_SECCOMP: ::c_int = 21; +pub const PR_SET_SECCOMP: ::c_int = 22; + +pub const PR_CAPBSET_READ: ::c_int = 23; +pub const PR_CAPBSET_DROP: ::c_int = 24; + +pub const PR_GET_TSC: ::c_int = 25; +pub const PR_SET_TSC: ::c_int = 26; +pub const PR_TSC_ENABLE: ::c_int = 1; +pub const PR_TSC_SIGSEGV: ::c_int = 2; + +pub const PR_GET_SECUREBITS: ::c_int = 27; +pub const PR_SET_SECUREBITS: ::c_int = 28; + +pub const PR_SET_TIMERSLACK: ::c_int = 29; +pub const PR_GET_TIMERSLACK: ::c_int = 30; + +pub const PR_TASK_PERF_EVENTS_DISABLE: ::c_int = 31; +pub const PR_TASK_PERF_EVENTS_ENABLE: ::c_int = 32; + +pub const PR_MCE_KILL: ::c_int = 33; +pub const PR_MCE_KILL_CLEAR: ::c_int = 0; +pub const PR_MCE_KILL_SET: ::c_int = 1; + +pub const PR_MCE_KILL_LATE: ::c_int = 0; +pub const PR_MCE_KILL_EARLY: ::c_int = 1; +pub const PR_MCE_KILL_DEFAULT: ::c_int = 2; + +pub const PR_MCE_KILL_GET: ::c_int = 34; + +pub const PR_SET_MM: ::c_int = 35; +pub const PR_SET_MM_START_CODE: ::c_int = 1; +pub const PR_SET_MM_END_CODE: ::c_int = 2; +pub const PR_SET_MM_START_DATA: ::c_int = 3; +pub const PR_SET_MM_END_DATA: ::c_int = 4; +pub const PR_SET_MM_START_STACK: ::c_int = 5; +pub const PR_SET_MM_START_BRK: ::c_int = 6; +pub const PR_SET_MM_BRK: ::c_int = 7; +pub const PR_SET_MM_ARG_START: ::c_int = 8; +pub const PR_SET_MM_ARG_END: ::c_int = 9; +pub const PR_SET_MM_ENV_START: ::c_int = 10; +pub const PR_SET_MM_ENV_END: ::c_int = 11; +pub const PR_SET_MM_AUXV: ::c_int = 12; +pub const PR_SET_MM_EXE_FILE: ::c_int = 13; +pub const PR_SET_MM_MAP: ::c_int = 14; +pub const PR_SET_MM_MAP_SIZE: ::c_int = 15; + +pub const PR_SET_PTRACER: ::c_int = 0x59616d61; + +pub const PR_SET_CHILD_SUBREAPER: ::c_int = 36; +pub const PR_GET_CHILD_SUBREAPER: ::c_int = 37; + +pub const PR_SET_NO_NEW_PRIVS: ::c_int = 38; +pub const PR_GET_NO_NEW_PRIVS: ::c_int = 39; + +pub const PR_GET_TID_ADDRESS: ::c_int = 40; + +pub const PR_SET_THP_DISABLE: ::c_int = 41; +pub const PR_GET_THP_DISABLE: ::c_int = 42; + +pub const PR_MPX_ENABLE_MANAGEMENT: ::c_int = 43; +pub const PR_MPX_DISABLE_MANAGEMENT: ::c_int = 44; + +pub const PR_SET_FP_MODE: ::c_int = 45; +pub const PR_GET_FP_MODE: ::c_int = 46; +pub const PR_FP_MODE_FR: ::c_int = 1 << 0; +pub const PR_FP_MODE_FRE: ::c_int = 1 << 1; + +pub const PR_CAP_AMBIENT: ::c_int = 47; +pub const PR_CAP_AMBIENT_IS_SET: ::c_int = 1; +pub const PR_CAP_AMBIENT_RAISE: ::c_int = 2; +pub const PR_CAP_AMBIENT_LOWER: ::c_int = 3; +pub const PR_CAP_AMBIENT_CLEAR_ALL: ::c_int = 4; + +pub const GRND_NONBLOCK: ::c_uint = 0x0001; +pub const GRND_RANDOM: ::c_uint = 0x0002; + +pub const SECCOMP_MODE_DISABLED: ::c_uint = 0; +pub const SECCOMP_MODE_STRICT: ::c_uint = 1; +pub const SECCOMP_MODE_FILTER: ::c_uint = 2; + +pub const ITIMER_REAL: ::c_int = 0; +pub const ITIMER_VIRTUAL: ::c_int = 1; +pub const ITIMER_PROF: ::c_int = 2; + +pub const TFD_CLOEXEC: ::c_int = O_CLOEXEC; +pub const TFD_NONBLOCK: ::c_int = O_NONBLOCK; +pub const TFD_TIMER_ABSTIME: ::c_int = 1; + +pub const XATTR_CREATE: ::c_int = 0x1; +pub const XATTR_REPLACE: ::c_int = 0x2; + +pub const _POSIX_VDISABLE: ::cc_t = 0; + +pub const FALLOC_FL_KEEP_SIZE: ::c_int = 0x01; +pub const FALLOC_FL_PUNCH_HOLE: ::c_int = 0x02; +pub const FALLOC_FL_COLLAPSE_RANGE: ::c_int = 0x08; +pub const FALLOC_FL_ZERO_RANGE: ::c_int = 0x10; +pub const FALLOC_FL_INSERT_RANGE: ::c_int = 0x20; +pub const FALLOC_FL_UNSHARE_RANGE: ::c_int = 0x40; + +// On Linux, libc doesn't define this constant, libattr does instead. +// We still define it for Linux as it's defined by libc on other platforms, +// and it's mentioned in the man pages for getxattr and setxattr. +pub const ENOATTR: ::c_int = ::ENODATA; + +pub const SO_ORIGINAL_DST: ::c_int = 80; +pub const IUTF8: ::tcflag_t = 0x00004000; +pub const CMSPAR: ::tcflag_t = 0o10000000000; + +pub const MFD_CLOEXEC: ::c_uint = 0x0001; +pub const MFD_ALLOW_SEALING: ::c_uint = 0x0002; + +// these are used in the p_type field of Elf32_Phdr and Elf64_Phdr, which has +// the type Elf32Word and Elf64Word respectively. Luckily, both of those are u32 +// so we can use that type here to avoid having to cast. +pub const PT_NULL: u32 = 0; +pub const PT_LOAD: u32 = 1; +pub const PT_DYNAMIC: u32 = 2; +pub const PT_INTERP: u32 = 3; +pub const PT_NOTE: u32 = 4; +pub const PT_SHLIB: u32 = 5; +pub const PT_PHDR: u32 = 6; +pub const PT_TLS: u32 = 7; +pub const PT_NUM: u32 = 8; +pub const PT_LOOS: u32 = 0x60000000; +pub const PT_GNU_EH_FRAME: u32 = 0x6474e550; +pub const PT_GNU_STACK: u32 = 0x6474e551; +pub const PT_GNU_RELRO: u32 = 0x6474e552; + +// linux/if_ether.h +pub const ETH_ALEN: ::c_int = 6; +pub const ETH_HLEN: ::c_int = 14; +pub const ETH_ZLEN: ::c_int = 60; +pub const ETH_DATA_LEN: ::c_int = 1500; +pub const ETH_FRAME_LEN: ::c_int = 1514; +pub const ETH_FCS_LEN: ::c_int = 4; + +// These are the defined Ethernet Protocol ID's. +pub const ETH_P_LOOP: ::c_int = 0x0060; +pub const ETH_P_PUP: ::c_int = 0x0200; +pub const ETH_P_PUPAT: ::c_int = 0x0201; +pub const ETH_P_IP: ::c_int = 0x0800; +pub const ETH_P_X25: ::c_int = 0x0805; +pub const ETH_P_ARP: ::c_int = 0x0806; +pub const ETH_P_BPQ: ::c_int = 0x08FF; +pub const ETH_P_IEEEPUP: ::c_int = 0x0a00; +pub const ETH_P_IEEEPUPAT: ::c_int = 0x0a01; +pub const ETH_P_BATMAN: ::c_int = 0x4305; +pub const ETH_P_DEC: ::c_int = 0x6000; +pub const ETH_P_DNA_DL: ::c_int = 0x6001; +pub const ETH_P_DNA_RC: ::c_int = 0x6002; +pub const ETH_P_DNA_RT: ::c_int = 0x6003; +pub const ETH_P_LAT: ::c_int = 0x6004; +pub const ETH_P_DIAG: ::c_int = 0x6005; +pub const ETH_P_CUST: ::c_int = 0x6006; +pub const ETH_P_SCA: ::c_int = 0x6007; +pub const ETH_P_TEB: ::c_int = 0x6558; +pub const ETH_P_RARP: ::c_int = 0x8035; +pub const ETH_P_ATALK: ::c_int = 0x809B; +pub const ETH_P_AARP: ::c_int = 0x80F3; +pub const ETH_P_8021Q: ::c_int = 0x8100; +pub const ETH_P_IPX: ::c_int = 0x8137; +pub const ETH_P_IPV6: ::c_int = 0x86DD; +pub const ETH_P_PAUSE: ::c_int = 0x8808; +pub const ETH_P_SLOW: ::c_int = 0x8809; +pub const ETH_P_WCCP: ::c_int = 0x883E; +pub const ETH_P_MPLS_UC: ::c_int = 0x8847; +pub const ETH_P_MPLS_MC: ::c_int = 0x8848; +pub const ETH_P_ATMMPOA: ::c_int = 0x884c; +pub const ETH_P_PPP_DISC: ::c_int = 0x8863; +pub const ETH_P_PPP_SES: ::c_int = 0x8864; +pub const ETH_P_LINK_CTL: ::c_int = 0x886c; +pub const ETH_P_ATMFATE: ::c_int = 0x8884; +pub const ETH_P_PAE: ::c_int = 0x888E; +pub const ETH_P_AOE: ::c_int = 0x88A2; +pub const ETH_P_8021AD: ::c_int = 0x88A8; +pub const ETH_P_802_EX1: ::c_int = 0x88B5; +pub const ETH_P_TIPC: ::c_int = 0x88CA; +pub const ETH_P_MACSEC: ::c_int = 0x88E5; +pub const ETH_P_8021AH: ::c_int = 0x88E7; +pub const ETH_P_MVRP: ::c_int = 0x88F5; +pub const ETH_P_1588: ::c_int = 0x88F7; +pub const ETH_P_PRP: ::c_int = 0x88FB; +pub const ETH_P_FCOE: ::c_int = 0x8906; +pub const ETH_P_TDLS: ::c_int = 0x890D; +pub const ETH_P_FIP: ::c_int = 0x8914; +pub const ETH_P_80221: ::c_int = 0x8917; +pub const ETH_P_LOOPBACK: ::c_int = 0x9000; +pub const ETH_P_QINQ1: ::c_int = 0x9100; +pub const ETH_P_QINQ2: ::c_int = 0x9200; +pub const ETH_P_QINQ3: ::c_int = 0x9300; +pub const ETH_P_EDSA: ::c_int = 0xDADA; +pub const ETH_P_AF_IUCV: ::c_int = 0xFBFB; + +pub const ETH_P_802_3_MIN: ::c_int = 0x0600; + +// Non DIX types. Won't clash for 1500 types. +pub const ETH_P_802_3: ::c_int = 0x0001; +pub const ETH_P_AX25: ::c_int = 0x0002; +pub const ETH_P_ALL: ::c_int = 0x0003; +pub const ETH_P_802_2: ::c_int = 0x0004; +pub const ETH_P_SNAP: ::c_int = 0x0005; +pub const ETH_P_DDCMP: ::c_int = 0x0006; +pub const ETH_P_WAN_PPP: ::c_int = 0x0007; +pub const ETH_P_PPP_MP: ::c_int = 0x0008; +pub const ETH_P_LOCALTALK: ::c_int = 0x0009; +pub const ETH_P_CANFD: ::c_int = 0x000D; +pub const ETH_P_PPPTALK: ::c_int = 0x0010; +pub const ETH_P_TR_802_2: ::c_int = 0x0011; +pub const ETH_P_MOBITEX: ::c_int = 0x0015; +pub const ETH_P_CONTROL: ::c_int = 0x0016; +pub const ETH_P_IRDA: ::c_int = 0x0017; +pub const ETH_P_ECONET: ::c_int = 0x0018; +pub const ETH_P_HDLC: ::c_int = 0x0019; +pub const ETH_P_ARCNET: ::c_int = 0x001A; +pub const ETH_P_DSA: ::c_int = 0x001B; +pub const ETH_P_TRAILER: ::c_int = 0x001C; +pub const ETH_P_PHONET: ::c_int = 0x00F5; +pub const ETH_P_IEEE802154: ::c_int = 0x00F6; +pub const ETH_P_CAIF: ::c_int = 0x00F7; + +pub const POSIX_SPAWN_RESETIDS: ::c_int = 0x01; +pub const POSIX_SPAWN_SETPGROUP: ::c_int = 0x02; +pub const POSIX_SPAWN_SETSIGDEF: ::c_int = 0x04; +pub const POSIX_SPAWN_SETSIGMASK: ::c_int = 0x08; +pub const POSIX_SPAWN_SETSCHEDPARAM: ::c_int = 0x10; +pub const POSIX_SPAWN_SETSCHEDULER: ::c_int = 0x20; + +pub const NLMSG_NOOP: ::c_int = 0x1; +pub const NLMSG_ERROR: ::c_int = 0x2; +pub const NLMSG_DONE: ::c_int = 0x3; +pub const NLMSG_OVERRUN: ::c_int = 0x4; +pub const NLMSG_MIN_TYPE: ::c_int = 0x10; + +pub const GENL_NAMSIZ: ::c_int = 16; + +pub const GENL_MIN_ID: ::c_int = NLMSG_MIN_TYPE; +pub const GENL_MAX_ID: ::c_int = 1023; + +pub const GENL_ADMIN_PERM: ::c_int = 0x01; +pub const GENL_CMD_CAP_DO: ::c_int = 0x02; +pub const GENL_CMD_CAP_DUMP: ::c_int = 0x04; +pub const GENL_CMD_CAP_HASPOL: ::c_int = 0x08; + +pub const GENL_ID_CTRL: ::c_int = NLMSG_MIN_TYPE; + +pub const CTRL_CMD_UNSPEC: ::c_int = 0; +pub const CTRL_CMD_NEWFAMILY: ::c_int = 1; +pub const CTRL_CMD_DELFAMILY: ::c_int = 2; +pub const CTRL_CMD_GETFAMILY: ::c_int = 3; +pub const CTRL_CMD_NEWOPS: ::c_int = 4; +pub const CTRL_CMD_DELOPS: ::c_int = 5; +pub const CTRL_CMD_GETOPS: ::c_int = 6; +pub const CTRL_CMD_NEWMCAST_GRP: ::c_int = 7; +pub const CTRL_CMD_DELMCAST_GRP: ::c_int = 8; +pub const CTRL_CMD_GETMCAST_GRP: ::c_int = 9; + +pub const CTRL_ATTR_UNSPEC: ::c_int = 0; +pub const CTRL_ATTR_FAMILY_ID: ::c_int = 1; +pub const CTRL_ATTR_FAMILY_NAME: ::c_int = 2; +pub const CTRL_ATTR_VERSION: ::c_int = 3; +pub const CTRL_ATTR_HDRSIZE: ::c_int = 4; +pub const CTRL_ATTR_MAXATTR: ::c_int = 5; +pub const CTRL_ATTR_OPS: ::c_int = 6; +pub const CTRL_ATTR_MCAST_GROUPS: ::c_int = 7; + +pub const CTRL_ATTR_OP_UNSPEC: ::c_int = 0; +pub const CTRL_ATTR_OP_ID: ::c_int = 1; +pub const CTRL_ATTR_OP_FLAGS: ::c_int = 2; + +pub const CTRL_ATTR_MCAST_GRP_UNSPEC: ::c_int = 0; +pub const CTRL_ATTR_MCAST_GRP_NAME: ::c_int = 1; +pub const CTRL_ATTR_MCAST_GRP_ID: ::c_int = 2; + +// linux/netfilter.h +pub const NF_DROP: ::c_int = 0; +pub const NF_ACCEPT: ::c_int = 1; +pub const NF_STOLEN: ::c_int = 2; +pub const NF_QUEUE: ::c_int = 3; +pub const NF_REPEAT: ::c_int = 4; +pub const NF_STOP: ::c_int = 5; +pub const NF_MAX_VERDICT: ::c_int = NF_STOP; + +pub const NF_VERDICT_MASK: ::c_int = 0x000000ff; +pub const NF_VERDICT_FLAG_QUEUE_BYPASS: ::c_int = 0x00008000; + +pub const NF_VERDICT_QMASK: ::c_int = 0xffff0000; +pub const NF_VERDICT_QBITS: ::c_int = 16; + +pub const NF_VERDICT_BITS: ::c_int = 16; + +pub const NF_INET_PRE_ROUTING: ::c_int = 0; +pub const NF_INET_LOCAL_IN: ::c_int = 1; +pub const NF_INET_FORWARD: ::c_int = 2; +pub const NF_INET_LOCAL_OUT: ::c_int = 3; +pub const NF_INET_POST_ROUTING: ::c_int = 4; +pub const NF_INET_NUMHOOKS: ::c_int = 5; + +// Some NFPROTO are not compatible with musl and are defined in submodules. +pub const NFPROTO_UNSPEC: ::c_int = 0; +pub const NFPROTO_IPV4: ::c_int = 2; +pub const NFPROTO_ARP: ::c_int = 3; +pub const NFPROTO_BRIDGE: ::c_int = 7; +pub const NFPROTO_IPV6: ::c_int = 10; +pub const NFPROTO_DECNET: ::c_int = 12; +pub const NFPROTO_NUMPROTO: ::c_int = 13; + +// linux/netfilter_ipv4.h +pub const NF_IP_PRE_ROUTING: ::c_int = 0; +pub const NF_IP_LOCAL_IN: ::c_int = 1; +pub const NF_IP_FORWARD: ::c_int = 2; +pub const NF_IP_LOCAL_OUT: ::c_int = 3; +pub const NF_IP_POST_ROUTING: ::c_int = 4; +pub const NF_IP_NUMHOOKS: ::c_int = 5; + +pub const NF_IP_PRI_FIRST: ::c_int = ::INT_MIN; +pub const NF_IP_PRI_CONNTRACK_DEFRAG: ::c_int = -400; +pub const NF_IP_PRI_RAW: ::c_int = -300; +pub const NF_IP_PRI_SELINUX_FIRST: ::c_int = -225; +pub const NF_IP_PRI_CONNTRACK: ::c_int = -200; +pub const NF_IP_PRI_MANGLE: ::c_int = -150; +pub const NF_IP_PRI_NAT_DST: ::c_int = -100; +pub const NF_IP_PRI_FILTER: ::c_int = 0; +pub const NF_IP_PRI_SECURITY: ::c_int = 50; +pub const NF_IP_PRI_NAT_SRC: ::c_int = 100; +pub const NF_IP_PRI_SELINUX_LAST: ::c_int = 225; +pub const NF_IP_PRI_CONNTRACK_HELPER: ::c_int = 300; +pub const NF_IP_PRI_CONNTRACK_CONFIRM: ::c_int = ::INT_MAX; +pub const NF_IP_PRI_LAST: ::c_int = ::INT_MAX; + +// linux/netfilter_ipv6.h +pub const NF_IP6_PRE_ROUTING: ::c_int = 0; +pub const NF_IP6_LOCAL_IN: ::c_int = 1; +pub const NF_IP6_FORWARD: ::c_int = 2; +pub const NF_IP6_LOCAL_OUT: ::c_int = 3; +pub const NF_IP6_POST_ROUTING: ::c_int = 4; +pub const NF_IP6_NUMHOOKS: ::c_int = 5; + +pub const NF_IP6_PRI_FIRST: ::c_int = ::INT_MIN; +pub const NF_IP6_PRI_CONNTRACK_DEFRAG: ::c_int = -400; +pub const NF_IP6_PRI_RAW: ::c_int = -300; +pub const NF_IP6_PRI_SELINUX_FIRST: ::c_int = -225; +pub const NF_IP6_PRI_CONNTRACK: ::c_int = -200; +pub const NF_IP6_PRI_MANGLE: ::c_int = -150; +pub const NF_IP6_PRI_NAT_DST: ::c_int = -100; +pub const NF_IP6_PRI_FILTER: ::c_int = 0; +pub const NF_IP6_PRI_SECURITY: ::c_int = 50; +pub const NF_IP6_PRI_NAT_SRC: ::c_int = 100; +pub const NF_IP6_PRI_SELINUX_LAST: ::c_int = 225; +pub const NF_IP6_PRI_CONNTRACK_HELPER: ::c_int = 300; +pub const NF_IP6_PRI_LAST: ::c_int = ::INT_MAX; + +f! { + pub fn CPU_ZERO(cpuset: &mut cpu_set_t) -> () { + for slot in cpuset.bits.iter_mut() { + *slot = 0; + } + } + + pub fn CPU_SET(cpu: usize, cpuset: &mut cpu_set_t) -> () { + let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc + let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); + cpuset.bits[idx] |= 1 << offset; + () + } + + pub fn CPU_CLR(cpu: usize, cpuset: &mut cpu_set_t) -> () { + let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc + let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); + cpuset.bits[idx] &= !(1 << offset); + () + } + + pub fn CPU_ISSET(cpu: usize, cpuset: &cpu_set_t) -> bool { + let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); + let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); + 0 != (cpuset.bits[idx] & (1 << offset)) + } + + pub fn CPU_EQUAL(set1: &cpu_set_t, set2: &cpu_set_t) -> bool { + set1.bits == set2.bits + } + + pub fn major(dev: ::dev_t) -> ::c_uint { + let mut major = 0; + major |= (dev & 0x00000000000fff00) >> 8; + major |= (dev & 0xfffff00000000000) >> 32; + major as ::c_uint + } + + pub fn minor(dev: ::dev_t) -> ::c_uint { + let mut minor = 0; + minor |= (dev & 0x00000000000000ff) >> 0; + minor |= (dev & 0x00000ffffff00000) >> 12; + minor as ::c_uint + } + + pub fn makedev(major: ::c_uint, minor: ::c_uint) -> ::dev_t { + let major = major as ::dev_t; + let minor = minor as ::dev_t; + let mut dev = 0; + dev |= (major & 0x00000fff) << 8; + dev |= (major & 0xfffff000) << 32; + dev |= (minor & 0x000000ff) << 0; + dev |= (minor & 0xffffff00) << 12; + dev + } +} + +extern { + pub fn aio_read(aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_write(aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_fsync(op: ::c_int, aiocbp: *mut aiocb) -> ::c_int; + pub fn aio_error(aiocbp: *const aiocb) -> ::c_int; + pub fn aio_return(aiocbp: *mut aiocb) -> ::ssize_t; + pub fn aio_suspend(aiocb_list: *const *const aiocb, nitems: ::c_int, + timeout: *const ::timespec) -> ::c_int; + pub fn aio_cancel(fd: ::c_int, aiocbp: *mut aiocb) -> ::c_int; + pub fn lio_listio(mode: ::c_int, aiocb_list: *const *mut aiocb, + nitems: ::c_int, sevp: *mut ::sigevent) -> ::c_int; + + pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; + + pub fn setpwent(); + pub fn endpwent(); + pub fn getpwent() -> *mut passwd; + pub fn setgrent(); + pub fn endgrent(); + pub fn getgrent() -> *mut ::group; + pub fn setspent(); + pub fn endspent(); + pub fn getspent() -> *mut spwd; + + pub fn getspnam(__name: *const ::c_char) -> *mut spwd; + + pub fn shm_open(name: *const c_char, oflag: ::c_int, + mode: mode_t) -> ::c_int; + + // System V IPC + pub fn shmget(key: ::key_t, size: ::size_t, shmflg: ::c_int) -> ::c_int; + pub fn shmat(shmid: ::c_int, + shmaddr: *const ::c_void, + shmflg: ::c_int) -> *mut ::c_void; + pub fn shmdt(shmaddr: *const ::c_void) -> ::c_int; + pub fn shmctl(shmid: ::c_int, + cmd: ::c_int, + buf: *mut ::shmid_ds) -> ::c_int; + pub fn ftok(pathname: *const ::c_char, proj_id: ::c_int) -> ::key_t; + pub fn semget(key: ::key_t, nsems: ::c_int, semflag: ::c_int) -> ::c_int; + pub fn semop(semid: ::c_int, + sops: *mut ::sembuf, nsops: ::size_t) -> ::c_int; + pub fn semctl(semid: ::c_int, + semnum: ::c_int, cmd: ::c_int, ...) -> ::c_int; + pub fn msgctl(msqid: ::c_int, cmd: ::c_int, buf: *mut msqid_ds) -> ::c_int; + pub fn msgget(key: ::key_t, msgflg: ::c_int) -> ::c_int; + pub fn msgrcv(msqid: ::c_int, msgp: *mut ::c_void, msgsz: ::size_t, + msgtyp: ::c_long, msgflg: ::c_int) -> ::ssize_t; + pub fn msgsnd(msqid: ::c_int, msgp: *const ::c_void, msgsz: ::size_t, + msgflg: ::c_int) -> ::c_int; + + pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) + -> ::c_int; + pub fn __errno_location() -> *mut ::c_int; + + pub fn fopen64(filename: *const c_char, + mode: *const c_char) -> *mut ::FILE; + pub fn freopen64(filename: *const c_char, mode: *const c_char, + file: *mut ::FILE) -> *mut ::FILE; + pub fn tmpfile64() -> *mut ::FILE; + pub fn fgetpos64(stream: *mut ::FILE, ptr: *mut fpos64_t) -> ::c_int; + pub fn fsetpos64(stream: *mut ::FILE, ptr: *const fpos64_t) -> ::c_int; + pub fn fseeko64(stream: *mut ::FILE, + offset: ::off64_t, + whence: ::c_int) -> ::c_int; + pub fn ftello64(stream: *mut ::FILE) -> ::off64_t; + pub fn fallocate(fd: ::c_int, mode: ::c_int, + offset: ::off_t, len: ::off_t) -> ::c_int; + pub fn posix_fallocate(fd: ::c_int, offset: ::off_t, + len: ::off_t) -> ::c_int; + pub fn readahead(fd: ::c_int, offset: ::off64_t, + count: ::size_t) -> ::ssize_t; + pub fn getxattr(path: *const c_char, name: *const c_char, + value: *mut ::c_void, size: ::size_t) -> ::ssize_t; + pub fn lgetxattr(path: *const c_char, name: *const c_char, + value: *mut ::c_void, size: ::size_t) -> ::ssize_t; + pub fn fgetxattr(filedes: ::c_int, name: *const c_char, + value: *mut ::c_void, size: ::size_t) -> ::ssize_t; + pub fn setxattr(path: *const c_char, name: *const c_char, + value: *const ::c_void, size: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn lsetxattr(path: *const c_char, name: *const c_char, + value: *const ::c_void, size: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn fsetxattr(filedes: ::c_int, name: *const c_char, + value: *const ::c_void, size: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn listxattr(path: *const c_char, list: *mut c_char, + size: ::size_t) -> ::ssize_t; + pub fn llistxattr(path: *const c_char, list: *mut c_char, + size: ::size_t) -> ::ssize_t; + pub fn flistxattr(filedes: ::c_int, list: *mut c_char, + size: ::size_t) -> ::ssize_t; + pub fn removexattr(path: *const c_char, name: *const c_char) -> ::c_int; + pub fn lremovexattr(path: *const c_char, name: *const c_char) -> ::c_int; + pub fn fremovexattr(filedes: ::c_int, name: *const c_char) -> ::c_int; + pub fn signalfd(fd: ::c_int, + mask: *const ::sigset_t, + flags: ::c_int) -> ::c_int; + pub fn timerfd_create(clockid: ::c_int, flags: ::c_int) -> ::c_int; + pub fn timerfd_gettime(fd: ::c_int, + curr_value: *mut itimerspec) -> ::c_int; + pub fn timerfd_settime(fd: ::c_int, + flags: ::c_int, + new_value: *const itimerspec, + old_value: *mut itimerspec) -> ::c_int; + pub fn pwritev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off_t) -> ::ssize_t; + pub fn preadv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off_t) -> ::ssize_t; + pub fn quotactl(cmd: ::c_int, + special: *const ::c_char, + id: ::c_int, + data: *mut ::c_char) -> ::c_int; + pub fn mq_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::mqd_t; + pub fn mq_close(mqd: ::mqd_t) -> ::c_int; + pub fn mq_unlink(name: *const ::c_char) -> ::c_int; + pub fn mq_receive(mqd: ::mqd_t, + msg_ptr: *mut ::c_char, + msg_len: ::size_t, + msq_prio: *mut ::c_uint) -> ::ssize_t; + pub fn mq_send(mqd: ::mqd_t, + msg_ptr: *const ::c_char, + msg_len: ::size_t, + msq_prio: ::c_uint) -> ::c_int; + pub fn mq_getattr(mqd: ::mqd_t, attr: *mut ::mq_attr) -> ::c_int; + pub fn mq_setattr(mqd: ::mqd_t, + newattr: *const ::mq_attr, + oldattr: *mut ::mq_attr) -> ::c_int; + pub fn epoll_pwait(epfd: ::c_int, + events: *mut ::epoll_event, + maxevents: ::c_int, + timeout: ::c_int, + sigmask: *const ::sigset_t) -> ::c_int; + pub fn dup3(oldfd: ::c_int, newfd: ::c_int, flags: ::c_int) -> ::c_int; + pub fn mkostemp(template: *mut ::c_char, flags: ::c_int) -> ::c_int; + pub fn mkostemps(template: *mut ::c_char, + suffixlen: ::c_int, + flags: ::c_int) -> ::c_int; + pub fn sigtimedwait(set: *const sigset_t, + info: *mut siginfo_t, + timeout: *const ::timespec) -> ::c_int; + pub fn sigwaitinfo(set: *const sigset_t, + info: *mut siginfo_t) -> ::c_int; + pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; + pub fn getnameinfo(sa: *const ::sockaddr, + salen: ::socklen_t, + host: *mut ::c_char, + hostlen: ::socklen_t, + serv: *mut ::c_char, + sevlen: ::socklen_t, + flags: ::c_int) -> ::c_int; + pub fn pthread_setschedprio(native: ::pthread_t, + priority: ::c_int) -> ::c_int; + pub fn prlimit(pid: ::pid_t, resource: ::c_int, new_limit: *const ::rlimit, + old_limit: *mut ::rlimit) -> ::c_int; + pub fn prlimit64(pid: ::pid_t, + resource: ::c_int, + new_limit: *const ::rlimit64, + old_limit: *mut ::rlimit64) -> ::c_int; + pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int; + pub fn process_vm_readv(pid: ::pid_t, + local_iov: *const ::iovec, + liovcnt: ::c_ulong, + remote_iov: *const ::iovec, + riovcnt: ::c_ulong, + flags: ::c_ulong) -> isize; + pub fn process_vm_writev(pid: ::pid_t, + local_iov: *const ::iovec, + liovcnt: ::c_ulong, + remote_iov: *const ::iovec, + riovcnt: ::c_ulong, + flags: ::c_ulong) -> isize; + pub fn reboot(how_to: ::c_int) -> ::c_int; + pub fn setfsgid(gid: ::gid_t) -> ::c_int; + pub fn setfsuid(uid: ::uid_t) -> ::c_int; + + // Not available now on Android + pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t) -> ::c_int; + pub fn if_nameindex() -> *mut if_nameindex; + pub fn if_freenameindex(ptr: *mut if_nameindex); + pub fn sync_file_range(fd: ::c_int, offset: ::off64_t, + nbytes: ::off64_t, flags: ::c_uint) -> ::c_int; + pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; + pub fn freeifaddrs(ifa: *mut ::ifaddrs); + pub fn mremap(addr: *mut ::c_void, + len: ::size_t, + new_len: ::size_t, + flags: ::c_int, + ...) -> *mut ::c_void; + + pub fn glob(pattern: *const c_char, + flags: ::c_int, + errfunc: Option ::c_int>, + pglob: *mut ::glob_t) -> ::c_int; + pub fn globfree(pglob: *mut ::glob_t); + + pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + pub fn shm_unlink(name: *const ::c_char) -> ::c_int; + + pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); + + pub fn telldir(dirp: *mut ::DIR) -> ::c_long; + pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; + pub fn remap_file_pages(addr: *mut ::c_void, size: ::size_t, prot: ::c_int, + pgoff: ::size_t, flags: ::c_int) -> ::c_int; + pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, + flags: ::c_int, addr: *mut ::sockaddr, + addrlen: *mut ::socklen_t) -> ::ssize_t; + pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; + pub fn futimes(fd: ::c_int, times: *const ::timeval) -> ::c_int; + pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; + + pub fn bind(socket: ::c_int, address: *const ::sockaddr, + address_len: ::socklen_t) -> ::c_int; + + pub fn writev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + pub fn readv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + + pub fn sendmsg(fd: ::c_int, + msg: *const ::msghdr, + flags: ::c_int) -> ::ssize_t; + pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) + -> ::ssize_t; + pub fn getdomainname(name: *mut ::c_char, len: ::size_t) -> ::c_int; + pub fn setdomainname(name: *const ::c_char, len: ::size_t) -> ::c_int; + pub fn vhangup() -> ::c_int; + pub fn sendmmsg(sockfd: ::c_int, msgvec: *mut mmsghdr, vlen: ::c_uint, + flags: ::c_int) -> ::c_int; + pub fn recvmmsg(sockfd: ::c_int, msgvec: *mut mmsghdr, vlen: ::c_uint, + flags: ::c_int, timeout: *mut ::timespec) -> ::c_int; + pub fn sync(); + pub fn syscall(num: ::c_long, ...) -> ::c_long; + pub fn sched_getaffinity(pid: ::pid_t, + cpusetsize: ::size_t, + cpuset: *mut cpu_set_t) -> ::c_int; + pub fn sched_setaffinity(pid: ::pid_t, + cpusetsize: ::size_t, + cpuset: *const cpu_set_t) -> ::c_int; + pub fn epoll_create(size: ::c_int) -> ::c_int; + pub fn epoll_create1(flags: ::c_int) -> ::c_int; + pub fn epoll_wait(epfd: ::c_int, + events: *mut ::epoll_event, + maxevents: ::c_int, + timeout: ::c_int) -> ::c_int; + pub fn epoll_ctl(epfd: ::c_int, + op: ::c_int, + fd: ::c_int, + event: *mut ::epoll_event) -> ::c_int; + pub fn pthread_getschedparam(native: ::pthread_t, + policy: *mut ::c_int, + param: *mut ::sched_param) -> ::c_int; + pub fn unshare(flags: ::c_int) -> ::c_int; + pub fn umount(target: *const ::c_char) -> ::c_int; + pub fn sched_get_priority_max(policy: ::c_int) -> ::c_int; + pub fn tee(fd_in: ::c_int, + fd_out: ::c_int, + len: ::size_t, + flags: ::c_uint) -> ::ssize_t; + pub fn settimeofday(tv: *const ::timeval, tz: *const ::timezone) -> ::c_int; + pub fn splice(fd_in: ::c_int, + off_in: *mut ::loff_t, + fd_out: ::c_int, + off_out: *mut ::loff_t, + len: ::size_t, + flags: ::c_uint) -> ::ssize_t; + pub fn eventfd(init: ::c_uint, flags: ::c_int) -> ::c_int; + pub fn sched_rr_get_interval(pid: ::pid_t, tp: *mut ::timespec) -> ::c_int; + pub fn sem_timedwait(sem: *mut sem_t, + abstime: *const ::timespec) -> ::c_int; + pub fn sched_setparam(pid: ::pid_t, param: *const ::sched_param) -> ::c_int; + pub fn setns(fd: ::c_int, nstype: ::c_int) -> ::c_int; + pub fn swapoff(puath: *const ::c_char) -> ::c_int; + pub fn vmsplice(fd: ::c_int, + iov: *const ::iovec, + nr_segs: ::size_t, + flags: ::c_uint) -> ::ssize_t; + pub fn mount(src: *const ::c_char, + target: *const ::c_char, + fstype: *const ::c_char, + flags: ::c_ulong, + data: *const ::c_void) -> ::c_int; + pub fn personality(persona: ::c_ulong) -> ::c_int; + pub fn prctl(option: ::c_int, ...) -> ::c_int; + pub fn sched_getparam(pid: ::pid_t, param: *mut ::sched_param) -> ::c_int; + pub fn ppoll(fds: *mut ::pollfd, + nfds: nfds_t, + timeout: *const ::timespec, + sigmask: *const sigset_t) -> ::c_int; + pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, + abstime: *const ::timespec) -> ::c_int; + pub fn clone(cb: extern fn(*mut ::c_void) -> ::c_int, + child_stack: *mut ::c_void, + flags: ::c_int, + arg: *mut ::c_void, ...) -> ::c_int; + pub fn sched_getscheduler(pid: ::pid_t) -> ::c_int; + pub fn clock_nanosleep(clk_id: ::clockid_t, + flags: ::c_int, + rqtp: *const ::timespec, + rmtp: *mut ::timespec) -> ::c_int; + pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, + guardsize: *mut ::size_t) -> ::c_int; + pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; + pub fn sched_get_priority_min(policy: ::c_int) -> ::c_int; + pub fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, + pshared: *mut ::c_int) -> ::c_int; + pub fn sysinfo(info: *mut ::sysinfo) -> ::c_int; + pub fn umount2(target: *const ::c_char, flags: ::c_int) -> ::c_int; + pub fn pthread_setschedparam(native: ::pthread_t, + policy: ::c_int, + param: *const ::sched_param) -> ::c_int; + pub fn swapon(path: *const ::c_char, swapflags: ::c_int) -> ::c_int; + pub fn sched_setscheduler(pid: ::pid_t, + policy: ::c_int, + param: *const ::sched_param) -> ::c_int; + pub fn sendfile(out_fd: ::c_int, + in_fd: ::c_int, + offset: *mut off_t, + count: ::size_t) -> ::ssize_t; + pub fn sigsuspend(mask: *const ::sigset_t) -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] + pub fn getgrgid_r(uid: ::uid_t, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "sigaltstack$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")] + pub fn sigaltstack(ss: *const stack_t, + oss: *mut stack_t) -> ::c_int; + pub fn sem_close(sem: *mut sem_t) -> ::c_int; + pub fn getdtablesize() -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] + pub fn getgrnam_r(name: *const ::c_char, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + pub fn initgroups(user: *const ::c_char, group: ::gid_t) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_sigmask$UNIX2003")] + pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, + oldset: *mut sigset_t) -> ::c_int; + pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; + pub fn getgrnam(name: *const ::c_char) -> *mut ::group; + pub fn pthread_cancel(thread: ::pthread_t) -> ::c_int; + pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; + pub fn sem_unlink(name: *const ::c_char) -> ::c_int; + pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] + pub fn getpwnam_r(name: *const ::c_char, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] + pub fn getpwuid_r(uid: ::uid_t, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch ="x86"), + link_name = "sigwait$UNIX2003")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] + pub fn sigwait(set: *const sigset_t, + sig: *mut ::c_int) -> ::c_int; + pub fn pthread_atfork(prepare: Option, + parent: Option, + child: Option) -> ::c_int; + pub fn getgrgid(gid: ::gid_t) -> *mut ::group; + pub fn getgrouplist(user: *const ::c_char, + group: ::gid_t, + groups: *mut ::gid_t, + ngroups: *mut ::c_int) -> ::c_int; + pub fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, + pshared: *mut ::c_int) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "popen$UNIX2003")] + pub fn popen(command: *const c_char, + mode: *const c_char) -> *mut ::FILE; + pub fn faccessat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::c_int, flags: ::c_int) -> ::c_int; + pub fn pthread_create(native: *mut ::pthread_t, + attr: *const ::pthread_attr_t, + f: extern fn(*mut ::c_void) -> *mut ::c_void, + value: *mut ::c_void) -> ::c_int; + pub fn dl_iterate_phdr( + callback: Option ::c_int>, + data: *mut ::c_void + ) -> ::c_int; + + pub fn setmntent(filename: *const ::c_char, + ty: *const ::c_char) -> *mut ::FILE; + pub fn getmntent(stream: *mut ::FILE) -> *mut ::mntent; + pub fn addmntent(stream: *mut ::FILE, mnt: *const ::mntent) -> ::c_int; + pub fn endmntent(streamp: *mut ::FILE) -> ::c_int; + pub fn hasmntopt(mnt: *const ::mntent, + opt: *const ::c_char) -> *mut ::c_char; + + pub fn posix_spawn(pid: *mut ::pid_t, + path: *const ::c_char, + file_actions: *const ::posix_spawn_file_actions_t, + attrp: *const ::posix_spawnattr_t, + argv: *const *mut ::c_char, + envp: *const *mut ::c_char) -> ::c_int; + pub fn posix_spawnp(pid: *mut ::pid_t, + file: *const ::c_char, + file_actions: *const ::posix_spawn_file_actions_t, + attrp: *const ::posix_spawnattr_t, + argv: *const *mut ::c_char, + envp: *const *mut ::c_char) -> ::c_int; + pub fn posix_spawnattr_init(attr: *mut posix_spawnattr_t) -> ::c_int; + pub fn posix_spawnattr_destroy(attr: *mut posix_spawnattr_t) -> ::c_int; + pub fn posix_spawnattr_getsigdefault(attr: *const posix_spawnattr_t, + default: *mut ::sigset_t) -> ::c_int; + pub fn posix_spawnattr_setsigdefault(attr: *mut posix_spawnattr_t, + default: *const ::sigset_t) -> ::c_int; + pub fn posix_spawnattr_getsigmask(attr: *const posix_spawnattr_t, + default: *mut ::sigset_t) -> ::c_int; + pub fn posix_spawnattr_setsigmask(attr: *mut posix_spawnattr_t, + default: *const ::sigset_t) -> ::c_int; + pub fn posix_spawnattr_getflags(attr: *const posix_spawnattr_t, + flags: *mut ::c_short) -> ::c_int; + pub fn posix_spawnattr_setflags(attr: *mut posix_spawnattr_t, + flags: ::c_short) -> ::c_int; + pub fn posix_spawnattr_getpgroup(attr: *const posix_spawnattr_t, + flags: *mut ::pid_t) -> ::c_int; + pub fn posix_spawnattr_setpgroup(attr: *mut posix_spawnattr_t, + flags: ::pid_t) -> ::c_int; + pub fn posix_spawnattr_getschedpolicy(attr: *const posix_spawnattr_t, + flags: *mut ::c_int) -> ::c_int; + pub fn posix_spawnattr_setschedpolicy(attr: *mut posix_spawnattr_t, + flags: ::c_int) -> ::c_int; + pub fn posix_spawnattr_getschedparam( + attr: *const posix_spawnattr_t, + param: *mut ::sched_param, + ) -> ::c_int; + pub fn posix_spawnattr_setschedparam( + attr: *mut posix_spawnattr_t, + param: *const ::sched_param, + ) -> ::c_int; + + pub fn posix_spawn_file_actions_init( + actions: *mut posix_spawn_file_actions_t, + ) -> ::c_int; + pub fn posix_spawn_file_actions_destroy( + actions: *mut posix_spawn_file_actions_t, + ) -> ::c_int; + pub fn posix_spawn_file_actions_addopen( + actions: *mut posix_spawn_file_actions_t, + fd: ::c_int, + path: *const ::c_char, + oflag: ::c_int, + mode: ::mode_t, + ) -> ::c_int; + pub fn posix_spawn_file_actions_addclose( + actions: *mut posix_spawn_file_actions_t, + fd: ::c_int, + ) -> ::c_int; + pub fn posix_spawn_file_actions_adddup2( + actions: *mut posix_spawn_file_actions_t, + fd: ::c_int, + newfd: ::c_int, + ) -> ::c_int; +} + +cfg_if! { + if #[cfg(any(target_env = "musl", target_os = "fuchsia"))] { + mod musl; + pub use self::musl::*; + } else if #[cfg(any(target_arch = "mips", + target_arch = "mips64"))] { + mod mips; + pub use self::mips::*; + } else if #[cfg(any(target_arch = "s390x"))] { + mod s390x; + pub use self::s390x::*; + } else { + mod other; + pub use self::other::*; + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/arm.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/arm.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/arm.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/arm.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,755 @@ +pub type c_char = u8; +pub type wchar_t = u32; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + __st_dev_padding: ::c_int, + __st_ino_truncated: ::c_long, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __st_rdev_padding: ::c_int, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_ino: ::ino_t, + } + + pub struct stat64 { + pub st_dev: ::dev_t, + __st_dev_padding: ::c_int, + __st_ino_truncated: ::c_long, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __st_rdev_padding: ::c_int, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_ino: ::ino_t, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_flags: ::c_int, + pub ss_size: ::size_t + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + __unused1: ::c_int, + pub shm_dtime: ::time_t, + __unused2: ::c_int, + pub shm_ctime: ::time_t, + __unused3: ::c_int, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::c_ulong, + __pad1: ::c_ulong, + __pad2: ::c_ulong, + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_stime: ::time_t, + __unused1: ::c_int, + pub msg_rtime: ::time_t, + __unused2: ::c_int, + pub msg_ctime: ::time_t, + __unused3: ::c_int, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __pad1: ::c_ulong, + __pad2: ::c_ulong, + } + + pub struct statfs { + pub f_type: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_flags: ::c_ulong, + pub f_spare: [::c_ulong; 4], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_errno: ::c_int, + pub si_code: ::c_int, + pub _pad: [::c_int; 29], + _align: [usize; 0], + } + + pub struct statfs64 { + pub f_type: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_flags: ::c_ulong, + pub f_spare: [::c_ulong; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + __f_unused: ::c_int, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 19], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } +} + +pub const O_DIRECT: ::c_int = 0x10000; +pub const O_DIRECTORY: ::c_int = 0x4000; +pub const O_NOFOLLOW: ::c_int = 0x8000; +pub const O_ASYNC: ::c_int = 0x2000; +pub const O_LARGEFILE: ::c_int = 0o400000; + +pub const FIOCLEX: ::c_int = 0x5451; +pub const FIONBIO: ::c_int = 0x5421; + +pub const RLIMIT_RSS: ::c_int = 5; +pub const RLIMIT_NOFILE: ::c_int = 7; +pub const RLIMIT_AS: ::c_int = 9; +pub const RLIMIT_NPROC: ::c_int = 6; +pub const RLIMIT_MEMLOCK: ::c_int = 8; + +pub const O_APPEND: ::c_int = 1024; +pub const O_CREAT: ::c_int = 64; +pub const O_EXCL: ::c_int = 128; +pub const O_NOCTTY: ::c_int = 256; +pub const O_NONBLOCK: ::c_int = 2048; +pub const O_SYNC: ::c_int = 1052672; +pub const O_RSYNC: ::c_int = 1052672; +pub const O_DSYNC: ::c_int = 4096; + +pub const SOCK_NONBLOCK: ::c_int = 2048; + +pub const MAP_ANON: ::c_int = 0x0020; +pub const MAP_GROWSDOWN: ::c_int = 0x0100; +pub const MAP_DENYWRITE: ::c_int = 0x0800; +pub const MAP_EXECUTABLE: ::c_int = 0x01000; +pub const MAP_LOCKED: ::c_int = 0x02000; +pub const MAP_NORESERVE: ::c_int = 0x04000; +pub const MAP_POPULATE: ::c_int = 0x08000; +pub const MAP_NONBLOCK: ::c_int = 0x010000; +pub const MAP_STACK: ::c_int = 0x020000; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_SEQPACKET: ::c_int = 5; + +pub const SOL_SOCKET: ::c_int = 1; + +pub const EDEADLK: ::c_int = 35; +pub const ENAMETOOLONG: ::c_int = 36; +pub const ENOLCK: ::c_int = 37; +pub const ENOSYS: ::c_int = 38; +pub const ENOTEMPTY: ::c_int = 39; +pub const ELOOP: ::c_int = 40; +pub const ENOMSG: ::c_int = 42; +pub const EIDRM: ::c_int = 43; +pub const ECHRNG: ::c_int = 44; +pub const EL2NSYNC: ::c_int = 45; +pub const EL3HLT: ::c_int = 46; +pub const EL3RST: ::c_int = 47; +pub const ELNRNG: ::c_int = 48; +pub const EUNATCH: ::c_int = 49; +pub const ENOCSI: ::c_int = 50; +pub const EL2HLT: ::c_int = 51; +pub const EBADE: ::c_int = 52; +pub const EBADR: ::c_int = 53; +pub const EXFULL: ::c_int = 54; +pub const ENOANO: ::c_int = 55; +pub const EBADRQC: ::c_int = 56; +pub const EBADSLT: ::c_int = 57; +pub const EDEADLOCK: ::c_int = EDEADLK; +pub const EMULTIHOP: ::c_int = 72; +pub const EBADMSG: ::c_int = 74; +pub const EOVERFLOW: ::c_int = 75; +pub const ENOTUNIQ: ::c_int = 76; +pub const EBADFD: ::c_int = 77; +pub const EREMCHG: ::c_int = 78; +pub const ELIBACC: ::c_int = 79; +pub const ELIBBAD: ::c_int = 80; +pub const ELIBSCN: ::c_int = 81; +pub const ELIBMAX: ::c_int = 82; +pub const ELIBEXEC: ::c_int = 83; +pub const EILSEQ: ::c_int = 84; +pub const ERESTART: ::c_int = 85; +pub const ESTRPIPE: ::c_int = 86; +pub const EUSERS: ::c_int = 87; +pub const ENOTSOCK: ::c_int = 88; +pub const EDESTADDRREQ: ::c_int = 89; +pub const EMSGSIZE: ::c_int = 90; +pub const EPROTOTYPE: ::c_int = 91; +pub const ENOPROTOOPT: ::c_int = 92; +pub const EPROTONOSUPPORT: ::c_int = 93; +pub const ESOCKTNOSUPPORT: ::c_int = 94; +pub const EOPNOTSUPP: ::c_int = 95; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; +pub const EPFNOSUPPORT: ::c_int = 96; +pub const EAFNOSUPPORT: ::c_int = 97; +pub const EADDRINUSE: ::c_int = 98; +pub const EADDRNOTAVAIL: ::c_int = 99; +pub const ENETDOWN: ::c_int = 100; +pub const ENETUNREACH: ::c_int = 101; +pub const ENETRESET: ::c_int = 102; +pub const ECONNABORTED: ::c_int = 103; +pub const ECONNRESET: ::c_int = 104; +pub const ENOBUFS: ::c_int = 105; +pub const EISCONN: ::c_int = 106; +pub const ENOTCONN: ::c_int = 107; +pub const ESHUTDOWN: ::c_int = 108; +pub const ETOOMANYREFS: ::c_int = 109; +pub const ETIMEDOUT: ::c_int = 110; +pub const ECONNREFUSED: ::c_int = 111; +pub const EHOSTDOWN: ::c_int = 112; +pub const EHOSTUNREACH: ::c_int = 113; +pub const EALREADY: ::c_int = 114; +pub const EINPROGRESS: ::c_int = 115; +pub const ESTALE: ::c_int = 116; +pub const EUCLEAN: ::c_int = 117; +pub const ENOTNAM: ::c_int = 118; +pub const ENAVAIL: ::c_int = 119; +pub const EISNAM: ::c_int = 120; +pub const EREMOTEIO: ::c_int = 121; +pub const EDQUOT: ::c_int = 122; +pub const ENOMEDIUM: ::c_int = 123; +pub const EMEDIUMTYPE: ::c_int = 124; +pub const ECANCELED: ::c_int = 125; +pub const ENOKEY: ::c_int = 126; +pub const EKEYEXPIRED: ::c_int = 127; +pub const EKEYREVOKED: ::c_int = 128; +pub const EKEYREJECTED: ::c_int = 129; +pub const EOWNERDEAD: ::c_int = 130; +pub const ENOTRECOVERABLE: ::c_int = 131; +pub const ERFKILL: ::c_int = 132; +pub const EHWPOISON: ::c_int = 133; + +pub const SO_REUSEADDR: ::c_int = 2; +pub const SO_TYPE: ::c_int = 3; +pub const SO_ERROR: ::c_int = 4; +pub const SO_DONTROUTE: ::c_int = 5; +pub const SO_BROADCAST: ::c_int = 6; +pub const SO_SNDBUF: ::c_int = 7; +pub const SO_RCVBUF: ::c_int = 8; +pub const SO_KEEPALIVE: ::c_int = 9; +pub const SO_OOBINLINE: ::c_int = 10; +pub const SO_NO_CHECK: ::c_int = 11; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_LINGER: ::c_int = 13; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_REUSEPORT: ::c_int = 15; +pub const SO_PASSCRED: ::c_int = 16; +pub const SO_PEERCRED: ::c_int = 17; +pub const SO_RCVLOWAT: ::c_int = 18; +pub const SO_SNDLOWAT: ::c_int = 19; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_SNDTIMEO: ::c_int = 21; +pub const SO_ACCEPTCONN: ::c_int = 30; +pub const SO_SNDBUFFORCE: ::c_int = 32; +pub const SO_RCVBUFFORCE: ::c_int = 33; +pub const SO_PROTOCOL: ::c_int = 38; +pub const SO_DOMAIN: ::c_int = 39; + +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 0x00000004; +pub const SA_NOCLDWAIT: ::c_int = 0x00000002; + +pub const SIGCHLD: ::c_int = 17; +pub const SIGBUS: ::c_int = 7; +pub const SIGTTIN: ::c_int = 21; +pub const SIGTTOU: ::c_int = 22; +pub const SIGXCPU: ::c_int = 24; +pub const SIGXFSZ: ::c_int = 25; +pub const SIGVTALRM: ::c_int = 26; +pub const SIGPROF: ::c_int = 27; +pub const SIGWINCH: ::c_int = 28; +pub const SIGUSR1: ::c_int = 10; +pub const SIGUSR2: ::c_int = 12; +pub const SIGCONT: ::c_int = 18; +pub const SIGSTOP: ::c_int = 19; +pub const SIGTSTP: ::c_int = 20; +pub const SIGURG: ::c_int = 23; +pub const SIGIO: ::c_int = 29; +pub const SIGSYS: ::c_int = 31; +pub const SIGSTKFLT: ::c_int = 16; +pub const SIGPOLL: ::c_int = 29; +pub const SIGPWR: ::c_int = 30; +pub const SIG_SETMASK: ::c_int = 2; +pub const SIG_BLOCK: ::c_int = 0x000000; +pub const SIG_UNBLOCK: ::c_int = 0x01; + +pub const EXTPROC: ::tcflag_t = 0x00010000; + +pub const MAP_HUGETLB: ::c_int = 0x040000; + +pub const F_GETLK: ::c_int = 12; +pub const F_GETOWN: ::c_int = 9; +pub const F_SETLK: ::c_int = 13; +pub const F_SETLKW: ::c_int = 14; +pub const F_SETOWN: ::c_int = 8; + +pub const VEOF: usize = 4; +pub const VEOL: usize = 11; +pub const VEOL2: usize = 16; +pub const VMIN: usize = 6; +pub const IEXTEN: ::tcflag_t = 0x00008000; +pub const TOSTOP: ::tcflag_t = 0x00000100; +pub const FLUSHO: ::tcflag_t = 0x00001000; + +pub const TCGETS: ::c_int = 0x5401; +pub const TCSETS: ::c_int = 0x5402; +pub const TCSETSW: ::c_int = 0x5403; +pub const TCSETSF: ::c_int = 0x5404; +pub const TCGETA: ::c_int = 0x5405; +pub const TCSETA: ::c_int = 0x5406; +pub const TCSETAW: ::c_int = 0x5407; +pub const TCSETAF: ::c_int = 0x5408; +pub const TCSBRK: ::c_int = 0x5409; +pub const TCXONC: ::c_int = 0x540A; +pub const TCFLSH: ::c_int = 0x540B; +pub const TIOCGSOFTCAR: ::c_int = 0x5419; +pub const TIOCSSOFTCAR: ::c_int = 0x541A; +pub const TIOCLINUX: ::c_int = 0x541C; +pub const TIOCGSERIAL: ::c_int = 0x541E; +pub const TIOCEXCL: ::c_int = 0x540C; +pub const TIOCNXCL: ::c_int = 0x540D; +pub const TIOCSCTTY: ::c_int = 0x540E; +pub const TIOCGPGRP: ::c_int = 0x540F; +pub const TIOCSPGRP: ::c_int = 0x5410; +pub const TIOCOUTQ: ::c_int = 0x5411; +pub const TIOCSTI: ::c_int = 0x5412; +pub const TIOCGWINSZ: ::c_int = 0x5413; +pub const TIOCSWINSZ: ::c_int = 0x5414; +pub const TIOCMGET: ::c_int = 0x5415; +pub const TIOCMBIS: ::c_int = 0x5416; +pub const TIOCMBIC: ::c_int = 0x5417; +pub const TIOCMSET: ::c_int = 0x5418; +pub const FIONREAD: ::c_int = 0x541B; +pub const TIOCCONS: ::c_int = 0x541D; + +pub const POLLWRNORM: ::c_short = 0x100; +pub const POLLWRBAND: ::c_short = 0x200; + +pub const TIOCM_LE: ::c_int = 0x001; +pub const TIOCM_DTR: ::c_int = 0x002; +pub const TIOCM_RTS: ::c_int = 0x004; +pub const TIOCM_ST: ::c_int = 0x008; +pub const TIOCM_SR: ::c_int = 0x010; +pub const TIOCM_CTS: ::c_int = 0x020; +pub const TIOCM_CAR: ::c_int = 0x040; +pub const TIOCM_RNG: ::c_int = 0x080; +pub const TIOCM_DSR: ::c_int = 0x100; +pub const TIOCM_CD: ::c_int = TIOCM_CAR; +pub const TIOCM_RI: ::c_int = TIOCM_RNG; + +// Syscall table +pub const SYS_restart_syscall: ::c_long = 0; +pub const SYS_exit: ::c_long = 1; +pub const SYS_fork: ::c_long = 2; +pub const SYS_read: ::c_long = 3; +pub const SYS_write: ::c_long = 4; +pub const SYS_open: ::c_long = 5; +pub const SYS_close: ::c_long = 6; +pub const SYS_creat: ::c_long = 8; +pub const SYS_link: ::c_long = 9; +pub const SYS_unlink: ::c_long = 10; +pub const SYS_execve: ::c_long = 11; +pub const SYS_chdir: ::c_long = 12; +pub const SYS_mknod: ::c_long = 14; +pub const SYS_chmod: ::c_long = 15; +pub const SYS_lchown: ::c_long = 16; +pub const SYS_lseek: ::c_long = 19; +pub const SYS_getpid: ::c_long = 20; +pub const SYS_mount: ::c_long = 21; +pub const SYS_setuid: ::c_long = 23; +pub const SYS_getuid: ::c_long = 24; +pub const SYS_ptrace: ::c_long = 26; +pub const SYS_pause: ::c_long = 29; +pub const SYS_access: ::c_long = 33; +pub const SYS_nice: ::c_long = 34; +pub const SYS_sync: ::c_long = 36; +pub const SYS_kill: ::c_long = 37; +pub const SYS_rename: ::c_long = 38; +pub const SYS_mkdir: ::c_long = 39; +pub const SYS_rmdir: ::c_long = 40; +pub const SYS_dup: ::c_long = 41; +pub const SYS_pipe: ::c_long = 42; +pub const SYS_times: ::c_long = 43; +pub const SYS_brk: ::c_long = 45; +pub const SYS_setgid: ::c_long = 46; +pub const SYS_getgid: ::c_long = 47; +pub const SYS_geteuid: ::c_long = 49; +pub const SYS_getegid: ::c_long = 50; +pub const SYS_acct: ::c_long = 51; +pub const SYS_umount2: ::c_long = 52; +pub const SYS_ioctl: ::c_long = 54; +pub const SYS_fcntl: ::c_long = 55; +pub const SYS_setpgid: ::c_long = 57; +pub const SYS_umask: ::c_long = 60; +pub const SYS_chroot: ::c_long = 61; +pub const SYS_ustat: ::c_long = 62; +pub const SYS_dup2: ::c_long = 63; +pub const SYS_getppid: ::c_long = 64; +pub const SYS_getpgrp: ::c_long = 65; +pub const SYS_setsid: ::c_long = 66; +pub const SYS_sigaction: ::c_long = 67; +pub const SYS_setreuid: ::c_long = 70; +pub const SYS_setregid: ::c_long = 71; +pub const SYS_sigsuspend: ::c_long = 72; +pub const SYS_sigpending: ::c_long = 73; +pub const SYS_sethostname: ::c_long = 74; +pub const SYS_setrlimit: ::c_long = 75; +pub const SYS_getrusage: ::c_long = 77; +pub const SYS_gettimeofday: ::c_long = 78; +pub const SYS_settimeofday: ::c_long = 79; +pub const SYS_getgroups: ::c_long = 80; +pub const SYS_setgroups: ::c_long = 81; +pub const SYS_symlink: ::c_long = 83; +pub const SYS_readlink: ::c_long = 85; +pub const SYS_uselib: ::c_long = 86; +pub const SYS_swapon: ::c_long = 87; +pub const SYS_reboot: ::c_long = 88; +pub const SYS_munmap: ::c_long = 91; +pub const SYS_truncate: ::c_long = 92; +pub const SYS_ftruncate: ::c_long = 93; +pub const SYS_fchmod: ::c_long = 94; +pub const SYS_fchown: ::c_long = 95; +pub const SYS_getpriority: ::c_long = 96; +pub const SYS_setpriority: ::c_long = 97; +pub const SYS_statfs: ::c_long = 99; +pub const SYS_fstatfs: ::c_long = 100; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_setitimer: ::c_long = 104; +pub const SYS_getitimer: ::c_long = 105; +pub const SYS_stat: ::c_long = 106; +pub const SYS_lstat: ::c_long = 107; +pub const SYS_fstat: ::c_long = 108; +pub const SYS_vhangup: ::c_long = 111; +pub const SYS_wait4: ::c_long = 114; +pub const SYS_swapoff: ::c_long = 115; +pub const SYS_sysinfo: ::c_long = 116; +pub const SYS_fsync: ::c_long = 118; +pub const SYS_sigreturn: ::c_long = 119; +pub const SYS_clone: ::c_long = 120; +pub const SYS_setdomainname: ::c_long = 121; +pub const SYS_uname: ::c_long = 122; +pub const SYS_adjtimex: ::c_long = 124; +pub const SYS_mprotect: ::c_long = 125; +pub const SYS_sigprocmask: ::c_long = 126; +pub const SYS_init_module: ::c_long = 128; +pub const SYS_delete_module: ::c_long = 129; +pub const SYS_quotactl: ::c_long = 131; +pub const SYS_getpgid: ::c_long = 132; +pub const SYS_fchdir: ::c_long = 133; +pub const SYS_bdflush: ::c_long = 134; +pub const SYS_sysfs: ::c_long = 135; +pub const SYS_personality: ::c_long = 136; +pub const SYS_setfsuid: ::c_long = 138; +pub const SYS_setfsgid: ::c_long = 139; +pub const SYS__llseek: ::c_long = 140; +pub const SYS_getdents: ::c_long = 141; +pub const SYS__newselect: ::c_long = 142; +pub const SYS_flock: ::c_long = 143; +pub const SYS_msync: ::c_long = 144; +pub const SYS_readv: ::c_long = 145; +pub const SYS_writev: ::c_long = 146; +pub const SYS_getsid: ::c_long = 147; +pub const SYS_fdatasync: ::c_long = 148; +pub const SYS__sysctl: ::c_long = 149; +pub const SYS_mlock: ::c_long = 150; +pub const SYS_munlock: ::c_long = 151; +pub const SYS_mlockall: ::c_long = 152; +pub const SYS_munlockall: ::c_long = 153; +pub const SYS_sched_setparam: ::c_long = 154; +pub const SYS_sched_getparam: ::c_long = 155; +pub const SYS_sched_setscheduler: ::c_long = 156; +pub const SYS_sched_getscheduler: ::c_long = 157; +pub const SYS_sched_yield: ::c_long = 158; +pub const SYS_sched_get_priority_max: ::c_long = 159; +pub const SYS_sched_get_priority_min: ::c_long = 160; +pub const SYS_sched_rr_get_interval: ::c_long = 161; +pub const SYS_nanosleep: ::c_long = 162; +pub const SYS_mremap: ::c_long = 163; +pub const SYS_setresuid: ::c_long = 164; +pub const SYS_getresuid: ::c_long = 165; +pub const SYS_poll: ::c_long = 168; +pub const SYS_nfsservctl: ::c_long = 169; +pub const SYS_setresgid: ::c_long = 170; +pub const SYS_getresgid: ::c_long = 171; +pub const SYS_prctl: ::c_long = 172; +pub const SYS_rt_sigreturn: ::c_long = 173; +pub const SYS_rt_sigaction: ::c_long = 174; +pub const SYS_rt_sigprocmask: ::c_long = 175; +pub const SYS_rt_sigpending: ::c_long = 176; +pub const SYS_rt_sigtimedwait: ::c_long = 177; +pub const SYS_rt_sigqueueinfo: ::c_long = 178; +pub const SYS_rt_sigsuspend: ::c_long = 179; +pub const SYS_pread64: ::c_long = 180; +pub const SYS_pwrite64: ::c_long = 181; +pub const SYS_chown: ::c_long = 182; +pub const SYS_getcwd: ::c_long = 183; +pub const SYS_capget: ::c_long = 184; +pub const SYS_capset: ::c_long = 185; +pub const SYS_sigaltstack: ::c_long = 186; +pub const SYS_sendfile: ::c_long = 187; +pub const SYS_vfork: ::c_long = 190; +pub const SYS_ugetrlimit: ::c_long = 191; +pub const SYS_mmap2: ::c_long = 192; +pub const SYS_truncate64: ::c_long = 193; +pub const SYS_ftruncate64: ::c_long = 194; +pub const SYS_stat64: ::c_long = 195; +pub const SYS_lstat64: ::c_long = 196; +pub const SYS_fstat64: ::c_long = 197; +pub const SYS_lchown32: ::c_long = 198; +pub const SYS_getuid32: ::c_long = 199; +pub const SYS_getgid32: ::c_long = 200; +pub const SYS_geteuid32: ::c_long = 201; +pub const SYS_getegid32: ::c_long = 202; +pub const SYS_setreuid32: ::c_long = 203; +pub const SYS_setregid32: ::c_long = 204; +pub const SYS_getgroups32: ::c_long = 205; +pub const SYS_setgroups32: ::c_long = 206; +pub const SYS_fchown32: ::c_long = 207; +pub const SYS_setresuid32: ::c_long = 208; +pub const SYS_getresuid32: ::c_long = 209; +pub const SYS_setresgid32: ::c_long = 210; +pub const SYS_getresgid32: ::c_long = 211; +pub const SYS_chown32: ::c_long = 212; +pub const SYS_setuid32: ::c_long = 213; +pub const SYS_setgid32: ::c_long = 214; +pub const SYS_setfsuid32: ::c_long = 215; +pub const SYS_setfsgid32: ::c_long = 216; +pub const SYS_getdents64: ::c_long = 217; +pub const SYS_pivot_root: ::c_long = 218; +pub const SYS_mincore: ::c_long = 219; +pub const SYS_madvise: ::c_long = 220; +pub const SYS_fcntl64: ::c_long = 221; +pub const SYS_gettid: ::c_long = 224; +pub const SYS_readahead: ::c_long = 225; +pub const SYS_setxattr: ::c_long = 226; +pub const SYS_lsetxattr: ::c_long = 227; +pub const SYS_fsetxattr: ::c_long = 228; +pub const SYS_getxattr: ::c_long = 229; +pub const SYS_lgetxattr: ::c_long = 230; +pub const SYS_fgetxattr: ::c_long = 231; +pub const SYS_listxattr: ::c_long = 232; +pub const SYS_llistxattr: ::c_long = 233; +pub const SYS_flistxattr: ::c_long = 234; +pub const SYS_removexattr: ::c_long = 235; +pub const SYS_lremovexattr: ::c_long = 236; +pub const SYS_fremovexattr: ::c_long = 237; +pub const SYS_tkill: ::c_long = 238; +pub const SYS_sendfile64: ::c_long = 239; +pub const SYS_futex: ::c_long = 240; +pub const SYS_sched_setaffinity: ::c_long = 241; +pub const SYS_sched_getaffinity: ::c_long = 242; +pub const SYS_io_setup: ::c_long = 243; +pub const SYS_io_destroy: ::c_long = 244; +pub const SYS_io_getevents: ::c_long = 245; +pub const SYS_io_submit: ::c_long = 246; +pub const SYS_io_cancel: ::c_long = 247; +pub const SYS_exit_group: ::c_long = 248; +pub const SYS_lookup_dcookie: ::c_long = 249; +pub const SYS_epoll_create: ::c_long = 250; +pub const SYS_epoll_ctl: ::c_long = 251; +pub const SYS_epoll_wait: ::c_long = 252; +pub const SYS_remap_file_pages: ::c_long = 253; +pub const SYS_set_tid_address: ::c_long = 256; +pub const SYS_timer_create: ::c_long = 257; +pub const SYS_timer_settime: ::c_long = 258; +pub const SYS_timer_gettime: ::c_long = 259; +pub const SYS_timer_getoverrun: ::c_long = 260; +pub const SYS_timer_delete: ::c_long = 261; +pub const SYS_clock_settime: ::c_long = 262; +pub const SYS_clock_gettime: ::c_long = 263; +pub const SYS_clock_getres: ::c_long = 264; +pub const SYS_clock_nanosleep: ::c_long = 265; +pub const SYS_statfs64: ::c_long = 266; +pub const SYS_fstatfs64: ::c_long = 267; +pub const SYS_tgkill: ::c_long = 268; +pub const SYS_utimes: ::c_long = 269; +pub const SYS_pciconfig_iobase: ::c_long = 271; +pub const SYS_pciconfig_read: ::c_long = 272; +pub const SYS_pciconfig_write: ::c_long = 273; +pub const SYS_mq_open: ::c_long = 274; +pub const SYS_mq_unlink: ::c_long = 275; +pub const SYS_mq_timedsend: ::c_long = 276; +pub const SYS_mq_timedreceive: ::c_long = 277; +pub const SYS_mq_notify: ::c_long = 278; +pub const SYS_mq_getsetattr: ::c_long = 279; +pub const SYS_waitid: ::c_long = 280; +pub const SYS_socket: ::c_long = 281; +pub const SYS_bind: ::c_long = 282; +pub const SYS_connect: ::c_long = 283; +pub const SYS_listen: ::c_long = 284; +pub const SYS_accept: ::c_long = 285; +pub const SYS_getsockname: ::c_long = 286; +pub const SYS_getpeername: ::c_long = 287; +pub const SYS_socketpair: ::c_long = 288; +pub const SYS_send: ::c_long = 289; +pub const SYS_sendto: ::c_long = 290; +pub const SYS_recv: ::c_long = 291; +pub const SYS_recvfrom: ::c_long = 292; +pub const SYS_shutdown: ::c_long = 293; +pub const SYS_setsockopt: ::c_long = 294; +pub const SYS_getsockopt: ::c_long = 295; +pub const SYS_sendmsg: ::c_long = 296; +pub const SYS_recvmsg: ::c_long = 297; +pub const SYS_semop: ::c_long = 298; +pub const SYS_semget: ::c_long = 299; +pub const SYS_semctl: ::c_long = 300; +pub const SYS_msgsnd: ::c_long = 301; +pub const SYS_msgrcv: ::c_long = 302; +pub const SYS_msgget: ::c_long = 303; +pub const SYS_msgctl: ::c_long = 304; +pub const SYS_shmat: ::c_long = 305; +pub const SYS_shmdt: ::c_long = 306; +pub const SYS_shmget: ::c_long = 307; +pub const SYS_shmctl: ::c_long = 308; +pub const SYS_add_key: ::c_long = 309; +pub const SYS_request_key: ::c_long = 310; +pub const SYS_keyctl: ::c_long = 311; +pub const SYS_semtimedop: ::c_long = 312; +pub const SYS_vserver: ::c_long = 313; +pub const SYS_ioprio_set: ::c_long = 314; +pub const SYS_ioprio_get: ::c_long = 315; +pub const SYS_inotify_init: ::c_long = 316; +pub const SYS_inotify_add_watch: ::c_long = 317; +pub const SYS_inotify_rm_watch: ::c_long = 318; +pub const SYS_mbind: ::c_long = 319; +pub const SYS_get_mempolicy: ::c_long = 320; +pub const SYS_set_mempolicy: ::c_long = 321; +pub const SYS_openat: ::c_long = 322; +pub const SYS_mkdirat: ::c_long = 323; +pub const SYS_mknodat: ::c_long = 324; +pub const SYS_fchownat: ::c_long = 325; +pub const SYS_futimesat: ::c_long = 326; +pub const SYS_fstatat64: ::c_long = 327; +pub const SYS_unlinkat: ::c_long = 328; +pub const SYS_renameat: ::c_long = 329; +pub const SYS_linkat: ::c_long = 330; +pub const SYS_symlinkat: ::c_long = 331; +pub const SYS_readlinkat: ::c_long = 332; +pub const SYS_fchmodat: ::c_long = 333; +pub const SYS_faccessat: ::c_long = 334; +pub const SYS_pselect6: ::c_long = 335; +pub const SYS_ppoll: ::c_long = 336; +pub const SYS_unshare: ::c_long = 337; +pub const SYS_set_robust_list: ::c_long = 338; +pub const SYS_get_robust_list: ::c_long = 339; +pub const SYS_splice: ::c_long = 340; +pub const SYS_tee: ::c_long = 342; +pub const SYS_vmsplice: ::c_long = 343; +pub const SYS_move_pages: ::c_long = 344; +pub const SYS_getcpu: ::c_long = 345; +pub const SYS_epoll_pwait: ::c_long = 346; +pub const SYS_kexec_load: ::c_long = 347; +pub const SYS_utimensat: ::c_long = 348; +pub const SYS_signalfd: ::c_long = 349; +pub const SYS_timerfd_create: ::c_long = 350; +pub const SYS_eventfd: ::c_long = 351; +pub const SYS_fallocate: ::c_long = 352; +pub const SYS_timerfd_settime: ::c_long = 353; +pub const SYS_timerfd_gettime: ::c_long = 354; +pub const SYS_signalfd4: ::c_long = 355; +pub const SYS_eventfd2: ::c_long = 356; +pub const SYS_epoll_create1: ::c_long = 357; +pub const SYS_dup3: ::c_long = 358; +pub const SYS_pipe2: ::c_long = 359; +pub const SYS_inotify_init1: ::c_long = 360; +pub const SYS_preadv: ::c_long = 361; +pub const SYS_pwritev: ::c_long = 362; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 363; +pub const SYS_perf_event_open: ::c_long = 364; +pub const SYS_recvmmsg: ::c_long = 365; +pub const SYS_accept4: ::c_long = 366; +pub const SYS_fanotify_init: ::c_long = 367; +pub const SYS_fanotify_mark: ::c_long = 368; +pub const SYS_prlimit64: ::c_long = 369; +pub const SYS_name_to_handle_at: ::c_long = 370; +pub const SYS_open_by_handle_at: ::c_long = 371; +pub const SYS_clock_adjtime: ::c_long = 372; +pub const SYS_syncfs: ::c_long = 373; +pub const SYS_sendmmsg: ::c_long = 374; +pub const SYS_setns: ::c_long = 375; +pub const SYS_process_vm_readv: ::c_long = 376; +pub const SYS_process_vm_writev: ::c_long = 377; +pub const SYS_kcmp: ::c_long = 378; +pub const SYS_finit_module: ::c_long = 379; +pub const SYS_sched_setattr: ::c_long = 380; +pub const SYS_sched_getattr: ::c_long = 381; +pub const SYS_renameat2: ::c_long = 382; +pub const SYS_seccomp: ::c_long = 383; +pub const SYS_getrandom: ::c_long = 384; +pub const SYS_memfd_create: ::c_long = 385; +pub const SYS_bpf: ::c_long = 386; +pub const SYS_execveat: ::c_long = 387; +pub const SYS_userfaultfd: ::c_long = 388; +pub const SYS_membarrier: ::c_long = 389; +pub const SYS_mlock2: ::c_long = 390; +pub const SYS_copy_file_range: ::c_long = 391; +pub const SYS_preadv2: ::c_long = 392; +pub const SYS_pwritev2: ::c_long = 393; +pub const SYS_pkey_mprotect: ::c_long = 394; +pub const SYS_pkey_alloc: ::c_long = 395; +pub const SYS_pkey_free: ::c_long = 396; + +#[doc(hidden)] +pub const AF_MAX: ::c_int = 43; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/mips.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/mips.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/mips.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/mips.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,773 @@ +pub type c_char = i8; +pub type wchar_t = ::c_int; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + __st_padding1: [::c_long; 2], + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __st_padding2: [::c_long; 2], + pub st_size: ::off_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + __st_padding3: ::c_long, + pub st_blocks: ::blkcnt_t, + __st_padding4: [::c_long; 14], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + __st_padding1: [::c_long; 2], + pub st_ino: ::ino64_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __st_padding2: [::c_long; 2], + pub st_size: ::off_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + __st_padding3: ::c_long, + pub st_blocks: ::blkcnt64_t, + __st_padding4: [::c_long; 14], + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_size: ::size_t, + pub ss_flags: ::c_int, + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::c_ulong, + __pad1: ::c_ulong, + __pad2: ::c_ulong, + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + #[cfg(target_endian = "big")] + __unused1: ::c_int, + pub msg_stime: ::time_t, + #[cfg(target_endian = "little")] + __unused1: ::c_int, + #[cfg(target_endian = "big")] + __unused2: ::c_int, + pub msg_rtime: ::time_t, + #[cfg(target_endian = "little")] + __unused2: ::c_int, + #[cfg(target_endian = "big")] + __unused3: ::c_int, + pub msg_ctime: ::time_t, + #[cfg(target_endian = "little")] + __unused3: ::c_int, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __pad1: ::c_ulong, + __pad2: ::c_ulong, + } + + pub struct statfs { + pub f_type: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_ulong, + pub f_flags: ::c_ulong, + pub f_spare: [::c_ulong; 5], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_code: ::c_int, + pub si_errno: ::c_int, + pub _pad: [::c_int; 29], + _align: [usize; 0], + } + + pub struct statfs64 { + pub f_type: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_ulong, + pub f_flags: ::c_ulong, + pub f_spare: [::c_ulong; 5], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + #[cfg(target_endian = "little")] + pub f_fsid: ::c_ulong, + __f_unused: ::c_int, + #[cfg(target_endian = "big")] + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 23], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } +} + +pub const O_DIRECT: ::c_int = 0o100000; +pub const O_DIRECTORY: ::c_int = 0o200000; +pub const O_NOFOLLOW: ::c_int = 0o400000; +pub const O_ASYNC: ::c_int = 0o10000; +pub const O_LARGEFILE: ::c_int = 0x2000; + +pub const FIOCLEX: ::c_int = 0x6601; +pub const FIONBIO: ::c_int = 0x667E; + +pub const RLIMIT_RSS: ::c_int = 7; +pub const RLIMIT_NOFILE: ::c_int = 5; +pub const RLIMIT_AS: ::c_int = 6; +pub const RLIMIT_NPROC: ::c_int = 8; +pub const RLIMIT_MEMLOCK: ::c_int = 9; + +pub const O_APPEND: ::c_int = 0o010; +pub const O_CREAT: ::c_int = 0o400; +pub const O_EXCL: ::c_int = 0o2000; +pub const O_NOCTTY: ::c_int = 0o4000; +pub const O_NONBLOCK: ::c_int = 0o200; +pub const O_SYNC: ::c_int = 0o40020; +pub const O_RSYNC: ::c_int = 0o40020; +pub const O_DSYNC: ::c_int = 0o020; + +pub const SOCK_NONBLOCK: ::c_int = 0o200; + +pub const MAP_ANON: ::c_int = 0x800; +pub const MAP_GROWSDOWN: ::c_int = 0x1000; +pub const MAP_DENYWRITE: ::c_int = 0x2000; +pub const MAP_EXECUTABLE: ::c_int = 0x4000; +pub const MAP_LOCKED: ::c_int = 0x8000; +pub const MAP_NORESERVE: ::c_int = 0x0400; +pub const MAP_POPULATE: ::c_int = 0x10000; +pub const MAP_NONBLOCK: ::c_int = 0x20000; +pub const MAP_STACK: ::c_int = 0x40000; + +pub const EDEADLK: ::c_int = 45; +pub const ENAMETOOLONG: ::c_int = 78; +pub const ENOLCK: ::c_int = 46; +pub const ENOSYS: ::c_int = 89; +pub const ENOTEMPTY: ::c_int = 93; +pub const ELOOP: ::c_int = 90; +pub const ENOMSG: ::c_int = 35; +pub const EIDRM: ::c_int = 36; +pub const ECHRNG: ::c_int = 37; +pub const EL2NSYNC: ::c_int = 38; +pub const EL3HLT: ::c_int = 39; +pub const EL3RST: ::c_int = 40; +pub const ELNRNG: ::c_int = 41; +pub const EUNATCH: ::c_int = 42; +pub const ENOCSI: ::c_int = 43; +pub const EL2HLT: ::c_int = 44; +pub const EBADE: ::c_int = 50; +pub const EBADR: ::c_int = 51; +pub const EXFULL: ::c_int = 52; +pub const ENOANO: ::c_int = 53; +pub const EBADRQC: ::c_int = 54; +pub const EBADSLT: ::c_int = 55; +pub const EDEADLOCK: ::c_int = 56; +pub const EMULTIHOP: ::c_int = 74; +pub const EOVERFLOW: ::c_int = 79; +pub const ENOTUNIQ: ::c_int = 80; +pub const EBADFD: ::c_int = 81; +pub const EBADMSG: ::c_int = 77; +pub const EREMCHG: ::c_int = 82; +pub const ELIBACC: ::c_int = 83; +pub const ELIBBAD: ::c_int = 84; +pub const ELIBSCN: ::c_int = 85; +pub const ELIBMAX: ::c_int = 86; +pub const ELIBEXEC: ::c_int = 87; +pub const EILSEQ: ::c_int = 88; +pub const ERESTART: ::c_int = 91; +pub const ESTRPIPE: ::c_int = 92; +pub const EUSERS: ::c_int = 94; +pub const ENOTSOCK: ::c_int = 95; +pub const EDESTADDRREQ: ::c_int = 96; +pub const EMSGSIZE: ::c_int = 97; +pub const EPROTOTYPE: ::c_int = 98; +pub const ENOPROTOOPT: ::c_int = 99; +pub const EPROTONOSUPPORT: ::c_int = 120; +pub const ESOCKTNOSUPPORT: ::c_int = 121; +pub const EOPNOTSUPP: ::c_int = 122; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; +pub const EPFNOSUPPORT: ::c_int = 123; +pub const EAFNOSUPPORT: ::c_int = 124; +pub const EADDRINUSE: ::c_int = 125; +pub const EADDRNOTAVAIL: ::c_int = 126; +pub const ENETDOWN: ::c_int = 127; +pub const ENETUNREACH: ::c_int = 128; +pub const ENETRESET: ::c_int = 129; +pub const ECONNABORTED: ::c_int = 130; +pub const ECONNRESET: ::c_int = 131; +pub const ENOBUFS: ::c_int = 132; +pub const EISCONN: ::c_int = 133; +pub const ENOTCONN: ::c_int = 134; +pub const ESHUTDOWN: ::c_int = 143; +pub const ETOOMANYREFS: ::c_int = 144; +pub const ETIMEDOUT: ::c_int = 145; +pub const ECONNREFUSED: ::c_int = 146; +pub const EHOSTDOWN: ::c_int = 147; +pub const EHOSTUNREACH: ::c_int = 148; +pub const EALREADY: ::c_int = 149; +pub const EINPROGRESS: ::c_int = 150; +pub const ESTALE: ::c_int = 151; +pub const EUCLEAN: ::c_int = 135; +pub const ENOTNAM: ::c_int = 137; +pub const ENAVAIL: ::c_int = 138; +pub const EISNAM: ::c_int = 139; +pub const EREMOTEIO: ::c_int = 140; +pub const EDQUOT: ::c_int = 1133; +pub const ENOMEDIUM: ::c_int = 159; +pub const EMEDIUMTYPE: ::c_int = 160; +pub const ECANCELED: ::c_int = 158; +pub const ENOKEY: ::c_int = 161; +pub const EKEYEXPIRED: ::c_int = 162; +pub const EKEYREVOKED: ::c_int = 163; +pub const EKEYREJECTED: ::c_int = 164; +pub const EOWNERDEAD: ::c_int = 165; +pub const ENOTRECOVERABLE: ::c_int = 166; +pub const EHWPOISON: ::c_int = 168; +pub const ERFKILL: ::c_int = 167; + +pub const SOCK_STREAM: ::c_int = 2; +pub const SOCK_DGRAM: ::c_int = 1; +pub const SOCK_SEQPACKET: ::c_int = 5; + +pub const SOL_SOCKET: ::c_int = 65535; + +pub const SO_REUSEADDR: ::c_int = 0x0004; +pub const SO_KEEPALIVE: ::c_int = 0x0008; +pub const SO_DONTROUTE: ::c_int = 0x0010; +pub const SO_BROADCAST: ::c_int = 0x0020; +pub const SO_LINGER: ::c_int = 0x0080; +pub const SO_OOBINLINE: ::c_int = 0x0100; +pub const SO_REUSEPORT: ::c_int = 0x0200; +pub const SO_SNDBUF: ::c_int = 0x1001; +pub const SO_RCVBUF: ::c_int = 0x1002; +pub const SO_SNDLOWAT: ::c_int = 0x1003; +pub const SO_RCVLOWAT: ::c_int = 0x1004; +pub const SO_RCVTIMEO: ::c_int = 0x1006; +pub const SO_SNDTIMEO: ::c_int = 0x1005; +pub const SO_ERROR: ::c_int = 0x1007; +pub const SO_TYPE: ::c_int = 0x1008; +pub const SO_ACCEPTCONN: ::c_int = 0x1009; +pub const SO_PROTOCOL: ::c_int = 0x1028; +pub const SO_DOMAIN: ::c_int = 0x1029; +pub const SO_NO_CHECK: ::c_int = 11; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_PASSCRED: ::c_int = 17; +pub const SO_PEERCRED: ::c_int = 18; +pub const SO_SNDBUFFORCE: ::c_int = 31; +pub const SO_RCVBUFFORCE: ::c_int = 33; + +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 8; +pub const SA_NOCLDWAIT: ::c_int = 0x10000; + +pub const SIGCHLD: ::c_int = 18; +pub const SIGBUS: ::c_int = 10; +pub const SIGTTIN: ::c_int = 26; +pub const SIGTTOU: ::c_int = 27; +pub const SIGXCPU: ::c_int = 30; +pub const SIGXFSZ: ::c_int = 31; +pub const SIGVTALRM: ::c_int = 28; +pub const SIGPROF: ::c_int = 29; +pub const SIGWINCH: ::c_int = 20; +pub const SIGUSR1: ::c_int = 16; +pub const SIGUSR2: ::c_int = 17; +pub const SIGCONT: ::c_int = 25; +pub const SIGSTOP: ::c_int = 23; +pub const SIGTSTP: ::c_int = 24; +pub const SIGURG: ::c_int = 21; +pub const SIGIO: ::c_int = 22; +pub const SIGSYS: ::c_int = 12; +pub const SIGSTKFLT: ::c_int = 7; +pub const SIGPOLL: ::c_int = ::SIGIO; +pub const SIGPWR: ::c_int = 19; +pub const SIG_SETMASK: ::c_int = 3; +pub const SIG_BLOCK: ::c_int = 1; +pub const SIG_UNBLOCK: ::c_int = 2; + +pub const EXTPROC: ::tcflag_t = 0o200000; + +pub const MAP_HUGETLB: ::c_int = 0x80000; + +pub const F_GETLK: ::c_int = 33; +pub const F_GETOWN: ::c_int = 23; +pub const F_SETLK: ::c_int = 34; +pub const F_SETLKW: ::c_int = 35; +pub const F_SETOWN: ::c_int = 24; + +pub const VEOF: usize = 16; +pub const VEOL: usize = 17; +pub const VEOL2: usize = 6; +pub const VMIN: usize = 4; +pub const IEXTEN: ::tcflag_t = 0o000400; +pub const TOSTOP: ::tcflag_t = 0o100000; +pub const FLUSHO: ::tcflag_t = 0o020000; + +pub const TCGETS: ::c_int = 0x540D; +pub const TCSETS: ::c_int = 0x540E; +pub const TCSETSW: ::c_int = 0x540F; +pub const TCSETSF: ::c_int = 0x5410; +pub const TCGETA: ::c_int = 0x5401; +pub const TCSETA: ::c_int = 0x5402; +pub const TCSETAW: ::c_int = 0x5403; +pub const TCSETAF: ::c_int = 0x5404; +pub const TCSBRK: ::c_int = 0x5405; +pub const TCXONC: ::c_int = 0x5406; +pub const TCFLSH: ::c_int = 0x5407; +pub const TIOCGSOFTCAR: ::c_int = 0x5481; +pub const TIOCSSOFTCAR: ::c_int = 0x5482; +pub const TIOCLINUX: ::c_int = 0x5483; +pub const TIOCGSERIAL: ::c_int = 0x5484; +pub const TIOCEXCL: ::c_int = 0x740D; +pub const TIOCNXCL: ::c_int = 0x740E; +pub const TIOCSCTTY: ::c_int = 0x5480; +pub const TIOCGPGRP: ::c_int = 0x40047477; +pub const TIOCSPGRP: ::c_int = 0x80047476; +pub const TIOCOUTQ: ::c_int = 0x7472; +pub const TIOCSTI: ::c_int = 0x5472; +pub const TIOCGWINSZ: ::c_int = 0x40087468; +pub const TIOCSWINSZ: ::c_int = 0x80087467; +pub const TIOCMGET: ::c_int = 0x741D; +pub const TIOCMBIS: ::c_int = 0x741B; +pub const TIOCMBIC: ::c_int = 0x741C; +pub const TIOCMSET: ::c_int = 0x741A; +pub const FIONREAD: ::c_int = 0x467F; +pub const TIOCCONS: ::c_int = 0x80047478; + +pub const POLLWRNORM: ::c_short = 0x4; +pub const POLLWRBAND: ::c_short = 0x100; + +pub const TIOCM_LE: ::c_int = 0x001; +pub const TIOCM_DTR: ::c_int = 0x002; +pub const TIOCM_RTS: ::c_int = 0x004; +pub const TIOCM_ST: ::c_int = 0x010; +pub const TIOCM_SR: ::c_int = 0x020; +pub const TIOCM_CTS: ::c_int = 0x040; +pub const TIOCM_CAR: ::c_int = 0x100; +pub const TIOCM_CD: ::c_int = TIOCM_CAR; +pub const TIOCM_RNG: ::c_int = 0x200; +pub const TIOCM_RI: ::c_int = TIOCM_RNG; +pub const TIOCM_DSR: ::c_int = 0x400; + +pub const SYS_syscall: ::c_long = 4000 + 0; +pub const SYS_exit: ::c_long = 4000 + 1; +pub const SYS_fork: ::c_long = 4000 + 2; +pub const SYS_read: ::c_long = 4000 + 3; +pub const SYS_write: ::c_long = 4000 + 4; +pub const SYS_open: ::c_long = 4000 + 5; +pub const SYS_close: ::c_long = 4000 + 6; +pub const SYS_waitpid: ::c_long = 4000 + 7; +pub const SYS_creat: ::c_long = 4000 + 8; +pub const SYS_link: ::c_long = 4000 + 9; +pub const SYS_unlink: ::c_long = 4000 + 10; +pub const SYS_execve: ::c_long = 4000 + 11; +pub const SYS_chdir: ::c_long = 4000 + 12; +pub const SYS_time: ::c_long = 4000 + 13; +pub const SYS_mknod: ::c_long = 4000 + 14; +pub const SYS_chmod: ::c_long = 4000 + 15; +pub const SYS_lchown: ::c_long = 4000 + 16; +pub const SYS_break: ::c_long = 4000 + 17; +pub const SYS_unused18: ::c_long = 4000 + 18; +pub const SYS_lseek: ::c_long = 4000 + 19; +pub const SYS_getpid: ::c_long = 4000 + 20; +pub const SYS_mount: ::c_long = 4000 + 21; +pub const SYS_umount: ::c_long = 4000 + 22; +pub const SYS_setuid: ::c_long = 4000 + 23; +pub const SYS_getuid: ::c_long = 4000 + 24; +pub const SYS_stime: ::c_long = 4000 + 25; +pub const SYS_ptrace: ::c_long = 4000 + 26; +pub const SYS_alarm: ::c_long = 4000 + 27; +pub const SYS_unused28: ::c_long = 4000 + 28; +pub const SYS_pause: ::c_long = 4000 + 29; +pub const SYS_utime: ::c_long = 4000 + 30; +pub const SYS_stty: ::c_long = 4000 + 31; +pub const SYS_gtty: ::c_long = 4000 + 32; +pub const SYS_access: ::c_long = 4000 + 33; +pub const SYS_nice: ::c_long = 4000 + 34; +pub const SYS_ftime: ::c_long = 4000 + 35; +pub const SYS_sync: ::c_long = 4000 + 36; +pub const SYS_kill: ::c_long = 4000 + 37; +pub const SYS_rename: ::c_long = 4000 + 38; +pub const SYS_mkdir: ::c_long = 4000 + 39; +pub const SYS_rmdir: ::c_long = 4000 + 40; +pub const SYS_dup: ::c_long = 4000 + 41; +pub const SYS_pipe: ::c_long = 4000 + 42; +pub const SYS_times: ::c_long = 4000 + 43; +pub const SYS_prof: ::c_long = 4000 + 44; +pub const SYS_brk: ::c_long = 4000 + 45; +pub const SYS_setgid: ::c_long = 4000 + 46; +pub const SYS_getgid: ::c_long = 4000 + 47; +pub const SYS_signal: ::c_long = 4000 + 48; +pub const SYS_geteuid: ::c_long = 4000 + 49; +pub const SYS_getegid: ::c_long = 4000 + 50; +pub const SYS_acct: ::c_long = 4000 + 51; +pub const SYS_umount2: ::c_long = 4000 + 52; +pub const SYS_lock: ::c_long = 4000 + 53; +pub const SYS_ioctl: ::c_long = 4000 + 54; +pub const SYS_fcntl: ::c_long = 4000 + 55; +pub const SYS_mpx: ::c_long = 4000 + 56; +pub const SYS_setpgid: ::c_long = 4000 + 57; +pub const SYS_ulimit: ::c_long = 4000 + 58; +pub const SYS_unused59: ::c_long = 4000 + 59; +pub const SYS_umask: ::c_long = 4000 + 60; +pub const SYS_chroot: ::c_long = 4000 + 61; +pub const SYS_ustat: ::c_long = 4000 + 62; +pub const SYS_dup2: ::c_long = 4000 + 63; +pub const SYS_getppid: ::c_long = 4000 + 64; +pub const SYS_getpgrp: ::c_long = 4000 + 65; +pub const SYS_setsid: ::c_long = 4000 + 66; +pub const SYS_sigaction: ::c_long = 4000 + 67; +pub const SYS_sgetmask: ::c_long = 4000 + 68; +pub const SYS_ssetmask: ::c_long = 4000 + 69; +pub const SYS_setreuid: ::c_long = 4000 + 70; +pub const SYS_setregid: ::c_long = 4000 + 71; +pub const SYS_sigsuspend: ::c_long = 4000 + 72; +pub const SYS_sigpending: ::c_long = 4000 + 73; +pub const SYS_sethostname: ::c_long = 4000 + 74; +pub const SYS_setrlimit: ::c_long = 4000 + 75; +pub const SYS_getrlimit: ::c_long = 4000 + 76; +pub const SYS_getrusage: ::c_long = 4000 + 77; +pub const SYS_gettimeofday: ::c_long = 4000 + 78; +pub const SYS_settimeofday: ::c_long = 4000 + 79; +pub const SYS_getgroups: ::c_long = 4000 + 80; +pub const SYS_setgroups: ::c_long = 4000 + 81; +pub const SYS_reserved82: ::c_long = 4000 + 82; +pub const SYS_symlink: ::c_long = 4000 + 83; +pub const SYS_unused84: ::c_long = 4000 + 84; +pub const SYS_readlink: ::c_long = 4000 + 85; +pub const SYS_uselib: ::c_long = 4000 + 86; +pub const SYS_swapon: ::c_long = 4000 + 87; +pub const SYS_reboot: ::c_long = 4000 + 88; +pub const SYS_readdir: ::c_long = 4000 + 89; +pub const SYS_mmap: ::c_long = 4000 + 90; +pub const SYS_munmap: ::c_long = 4000 + 91; +pub const SYS_truncate: ::c_long = 4000 + 92; +pub const SYS_ftruncate: ::c_long = 4000 + 93; +pub const SYS_fchmod: ::c_long = 4000 + 94; +pub const SYS_fchown: ::c_long = 4000 + 95; +pub const SYS_getpriority: ::c_long = 4000 + 96; +pub const SYS_setpriority: ::c_long = 4000 + 97; +pub const SYS_profil: ::c_long = 4000 + 98; +pub const SYS_statfs: ::c_long = 4000 + 99; +pub const SYS_fstatfs: ::c_long = 4000 + 100; +pub const SYS_ioperm: ::c_long = 4000 + 101; +pub const SYS_socketcall: ::c_long = 4000 + 102; +pub const SYS_syslog: ::c_long = 4000 + 103; +pub const SYS_setitimer: ::c_long = 4000 + 104; +pub const SYS_getitimer: ::c_long = 4000 + 105; +pub const SYS_stat: ::c_long = 4000 + 106; +pub const SYS_lstat: ::c_long = 4000 + 107; +pub const SYS_fstat: ::c_long = 4000 + 108; +pub const SYS_unused109: ::c_long = 4000 + 109; +pub const SYS_iopl: ::c_long = 4000 + 110; +pub const SYS_vhangup: ::c_long = 4000 + 111; +pub const SYS_idle: ::c_long = 4000 + 112; +pub const SYS_vm86: ::c_long = 4000 + 113; +pub const SYS_wait4: ::c_long = 4000 + 114; +pub const SYS_swapoff: ::c_long = 4000 + 115; +pub const SYS_sysinfo: ::c_long = 4000 + 116; +pub const SYS_ipc: ::c_long = 4000 + 117; +pub const SYS_fsync: ::c_long = 4000 + 118; +pub const SYS_sigreturn: ::c_long = 4000 + 119; +pub const SYS_clone: ::c_long = 4000 + 120; +pub const SYS_setdomainname: ::c_long = 4000 + 121; +pub const SYS_uname: ::c_long = 4000 + 122; +pub const SYS_modify_ldt: ::c_long = 4000 + 123; +pub const SYS_adjtimex: ::c_long = 4000 + 124; +pub const SYS_mprotect: ::c_long = 4000 + 125; +pub const SYS_sigprocmask: ::c_long = 4000 + 126; +pub const SYS_create_module: ::c_long = 4000 + 127; +pub const SYS_init_module: ::c_long = 4000 + 128; +pub const SYS_delete_module: ::c_long = 4000 + 129; +pub const SYS_get_kernel_syms: ::c_long = 4000 + 130; +pub const SYS_quotactl: ::c_long = 4000 + 131; +pub const SYS_getpgid: ::c_long = 4000 + 132; +pub const SYS_fchdir: ::c_long = 4000 + 133; +pub const SYS_bdflush: ::c_long = 4000 + 134; +pub const SYS_sysfs: ::c_long = 4000 + 135; +pub const SYS_personality: ::c_long = 4000 + 136; +pub const SYS_afs_syscall: ::c_long = 4000 + 137; +pub const SYS_setfsuid: ::c_long = 4000 + 138; +pub const SYS_setfsgid: ::c_long = 4000 + 139; +pub const SYS__llseek: ::c_long = 4000 + 140; +pub const SYS_getdents: ::c_long = 4000 + 141; +pub const SYS_flock: ::c_long = 4000 + 143; +pub const SYS_msync: ::c_long = 4000 + 144; +pub const SYS_readv: ::c_long = 4000 + 145; +pub const SYS_writev: ::c_long = 4000 + 146; +pub const SYS_cacheflush: ::c_long = 4000 + 147; +pub const SYS_cachectl: ::c_long = 4000 + 148; +pub const SYS_sysmips: ::c_long = 4000 + 149; +pub const SYS_unused150: ::c_long = 4000 + 150; +pub const SYS_getsid: ::c_long = 4000 + 151; +pub const SYS_fdatasync: ::c_long = 4000 + 152; +pub const SYS__sysctl: ::c_long = 4000 + 153; +pub const SYS_mlock: ::c_long = 4000 + 154; +pub const SYS_munlock: ::c_long = 4000 + 155; +pub const SYS_mlockall: ::c_long = 4000 + 156; +pub const SYS_munlockall: ::c_long = 4000 + 157; +pub const SYS_sched_setparam: ::c_long = 4000 + 158; +pub const SYS_sched_getparam: ::c_long = 4000 + 159; +pub const SYS_sched_setscheduler: ::c_long = 4000 + 160; +pub const SYS_sched_getscheduler: ::c_long = 4000 + 161; +pub const SYS_sched_yield: ::c_long = 4000 + 162; +pub const SYS_sched_get_priority_max: ::c_long = 4000 + 163; +pub const SYS_sched_get_priority_min: ::c_long = 4000 + 164; +pub const SYS_sched_rr_get_interval: ::c_long = 4000 + 165; +pub const SYS_nanosleep: ::c_long = 4000 + 166; +pub const SYS_mremap: ::c_long = 4000 + 167; +pub const SYS_accept: ::c_long = 4000 + 168; +pub const SYS_bind: ::c_long = 4000 + 169; +pub const SYS_connect: ::c_long = 4000 + 170; +pub const SYS_getpeername: ::c_long = 4000 + 171; +pub const SYS_getsockname: ::c_long = 4000 + 172; +pub const SYS_getsockopt: ::c_long = 4000 + 173; +pub const SYS_listen: ::c_long = 4000 + 174; +pub const SYS_recv: ::c_long = 4000 + 175; +pub const SYS_recvfrom: ::c_long = 4000 + 176; +pub const SYS_recvmsg: ::c_long = 4000 + 177; +pub const SYS_send: ::c_long = 4000 + 178; +pub const SYS_sendmsg: ::c_long = 4000 + 179; +pub const SYS_sendto: ::c_long = 4000 + 180; +pub const SYS_setsockopt: ::c_long = 4000 + 181; +pub const SYS_shutdown: ::c_long = 4000 + 182; +pub const SYS_socket: ::c_long = 4000 + 183; +pub const SYS_socketpair: ::c_long = 4000 + 184; +pub const SYS_setresuid: ::c_long = 4000 + 185; +pub const SYS_getresuid: ::c_long = 4000 + 186; +pub const SYS_query_module: ::c_long = 4000 + 187; +pub const SYS_poll: ::c_long = 4000 + 188; +pub const SYS_nfsservctl: ::c_long = 4000 + 189; +pub const SYS_setresgid: ::c_long = 4000 + 190; +pub const SYS_getresgid: ::c_long = 4000 + 191; +pub const SYS_prctl: ::c_long = 4000 + 192; +pub const SYS_rt_sigreturn: ::c_long = 4000 + 193; +pub const SYS_rt_sigaction: ::c_long = 4000 + 194; +pub const SYS_rt_sigprocmask: ::c_long = 4000 + 195; +pub const SYS_rt_sigpending: ::c_long = 4000 + 196; +pub const SYS_rt_sigtimedwait: ::c_long = 4000 + 197; +pub const SYS_rt_sigqueueinfo: ::c_long = 4000 + 198; +pub const SYS_rt_sigsuspend: ::c_long = 4000 + 199; +pub const SYS_chown: ::c_long = 4000 + 202; +pub const SYS_getcwd: ::c_long = 4000 + 203; +pub const SYS_capget: ::c_long = 4000 + 204; +pub const SYS_capset: ::c_long = 4000 + 205; +pub const SYS_sigaltstack: ::c_long = 4000 + 206; +pub const SYS_sendfile: ::c_long = 4000 + 207; +pub const SYS_getpmsg: ::c_long = 4000 + 208; +pub const SYS_putpmsg: ::c_long = 4000 + 209; +pub const SYS_mmap2: ::c_long = 4000 + 210; +pub const SYS_truncate64: ::c_long = 4000 + 211; +pub const SYS_ftruncate64: ::c_long = 4000 + 212; +pub const SYS_stat64: ::c_long = 4000 + 213; +pub const SYS_lstat64: ::c_long = 4000 + 214; +pub const SYS_fstat64: ::c_long = 4000 + 215; +pub const SYS_pivot_root: ::c_long = 4000 + 216; +pub const SYS_mincore: ::c_long = 4000 + 217; +pub const SYS_madvise: ::c_long = 4000 + 218; +pub const SYS_getdents64: ::c_long = 4000 + 219; +pub const SYS_fcntl64: ::c_long = 4000 + 220; +pub const SYS_reserved221: ::c_long = 4000 + 221; +pub const SYS_gettid: ::c_long = 4000 + 222; +pub const SYS_readahead: ::c_long = 4000 + 223; +pub const SYS_setxattr: ::c_long = 4000 + 224; +pub const SYS_lsetxattr: ::c_long = 4000 + 225; +pub const SYS_fsetxattr: ::c_long = 4000 + 226; +pub const SYS_getxattr: ::c_long = 4000 + 227; +pub const SYS_lgetxattr: ::c_long = 4000 + 228; +pub const SYS_fgetxattr: ::c_long = 4000 + 229; +pub const SYS_listxattr: ::c_long = 4000 + 230; +pub const SYS_llistxattr: ::c_long = 4000 + 231; +pub const SYS_flistxattr: ::c_long = 4000 + 232; +pub const SYS_removexattr: ::c_long = 4000 + 233; +pub const SYS_lremovexattr: ::c_long = 4000 + 234; +pub const SYS_fremovexattr: ::c_long = 4000 + 235; +pub const SYS_tkill: ::c_long = 4000 + 236; +pub const SYS_sendfile64: ::c_long = 4000 + 237; +pub const SYS_futex: ::c_long = 4000 + 238; +pub const SYS_sched_setaffinity: ::c_long = 4000 + 239; +pub const SYS_sched_getaffinity: ::c_long = 4000 + 240; +pub const SYS_io_setup: ::c_long = 4000 + 241; +pub const SYS_io_destroy: ::c_long = 4000 + 242; +pub const SYS_io_getevents: ::c_long = 4000 + 243; +pub const SYS_io_submit: ::c_long = 4000 + 244; +pub const SYS_io_cancel: ::c_long = 4000 + 245; +pub const SYS_exit_group: ::c_long = 4000 + 246; +pub const SYS_lookup_dcookie: ::c_long = 4000 + 247; +pub const SYS_epoll_create: ::c_long = 4000 + 248; +pub const SYS_epoll_ctl: ::c_long = 4000 + 249; +pub const SYS_epoll_wait: ::c_long = 4000 + 250; +pub const SYS_remap_file_pages: ::c_long = 4000 + 251; +pub const SYS_set_tid_address: ::c_long = 4000 + 252; +pub const SYS_restart_syscall: ::c_long = 4000 + 253; +pub const SYS_statfs64: ::c_long = 4000 + 255; +pub const SYS_fstatfs64: ::c_long = 4000 + 256; +pub const SYS_timer_create: ::c_long = 4000 + 257; +pub const SYS_timer_settime: ::c_long = 4000 + 258; +pub const SYS_timer_gettime: ::c_long = 4000 + 259; +pub const SYS_timer_getoverrun: ::c_long = 4000 + 260; +pub const SYS_timer_delete: ::c_long = 4000 + 261; +pub const SYS_clock_settime: ::c_long = 4000 + 262; +pub const SYS_clock_gettime: ::c_long = 4000 + 263; +pub const SYS_clock_getres: ::c_long = 4000 + 264; +pub const SYS_clock_nanosleep: ::c_long = 4000 + 265; +pub const SYS_tgkill: ::c_long = 4000 + 266; +pub const SYS_utimes: ::c_long = 4000 + 267; +pub const SYS_mbind: ::c_long = 4000 + 268; +pub const SYS_get_mempolicy: ::c_long = 4000 + 269; +pub const SYS_set_mempolicy: ::c_long = 4000 + 270; +pub const SYS_mq_open: ::c_long = 4000 + 271; +pub const SYS_mq_unlink: ::c_long = 4000 + 272; +pub const SYS_mq_timedsend: ::c_long = 4000 + 273; +pub const SYS_mq_timedreceive: ::c_long = 4000 + 274; +pub const SYS_mq_notify: ::c_long = 4000 + 275; +pub const SYS_mq_getsetattr: ::c_long = 4000 + 276; +pub const SYS_vserver: ::c_long = 4000 + 277; +pub const SYS_waitid: ::c_long = 4000 + 278; +/* pub const SYS_sys_setaltroot: ::c_long = 4000 + 279; */ +pub const SYS_add_key: ::c_long = 4000 + 280; +pub const SYS_request_key: ::c_long = 4000 + 281; +pub const SYS_keyctl: ::c_long = 4000 + 282; +pub const SYS_set_thread_area: ::c_long = 4000 + 283; +pub const SYS_inotify_init: ::c_long = 4000 + 284; +pub const SYS_inotify_add_watch: ::c_long = 4000 + 285; +pub const SYS_inotify_rm_watch: ::c_long = 4000 + 286; +pub const SYS_migrate_pages: ::c_long = 4000 + 287; +pub const SYS_openat: ::c_long = 4000 + 288; +pub const SYS_mkdirat: ::c_long = 4000 + 289; +pub const SYS_mknodat: ::c_long = 4000 + 290; +pub const SYS_fchownat: ::c_long = 4000 + 291; +pub const SYS_futimesat: ::c_long = 4000 + 292; +pub const SYS_unlinkat: ::c_long = 4000 + 294; +pub const SYS_renameat: ::c_long = 4000 + 295; +pub const SYS_linkat: ::c_long = 4000 + 296; +pub const SYS_symlinkat: ::c_long = 4000 + 297; +pub const SYS_readlinkat: ::c_long = 4000 + 298; +pub const SYS_fchmodat: ::c_long = 4000 + 299; +pub const SYS_faccessat: ::c_long = 4000 + 300; +pub const SYS_pselect6: ::c_long = 4000 + 301; +pub const SYS_ppoll: ::c_long = 4000 + 302; +pub const SYS_unshare: ::c_long = 4000 + 303; +pub const SYS_splice: ::c_long = 4000 + 304; +pub const SYS_sync_file_range: ::c_long = 4000 + 305; +pub const SYS_tee: ::c_long = 4000 + 306; +pub const SYS_vmsplice: ::c_long = 4000 + 307; +pub const SYS_move_pages: ::c_long = 4000 + 308; +pub const SYS_set_robust_list: ::c_long = 4000 + 309; +pub const SYS_get_robust_list: ::c_long = 4000 + 310; +pub const SYS_kexec_load: ::c_long = 4000 + 311; +pub const SYS_getcpu: ::c_long = 4000 + 312; +pub const SYS_epoll_pwait: ::c_long = 4000 + 313; +pub const SYS_ioprio_set: ::c_long = 4000 + 314; +pub const SYS_ioprio_get: ::c_long = 4000 + 315; +pub const SYS_utimensat: ::c_long = 4000 + 316; +pub const SYS_signalfd: ::c_long = 4000 + 317; +pub const SYS_timerfd: ::c_long = 4000 + 318; +pub const SYS_eventfd: ::c_long = 4000 + 319; +pub const SYS_fallocate: ::c_long = 4000 + 320; +pub const SYS_timerfd_create: ::c_long = 4000 + 321; +pub const SYS_timerfd_gettime: ::c_long = 4000 + 322; +pub const SYS_timerfd_settime: ::c_long = 4000 + 323; +pub const SYS_signalfd4: ::c_long = 4000 + 324; +pub const SYS_eventfd2: ::c_long = 4000 + 325; +pub const SYS_epoll_create1: ::c_long = 4000 + 326; +pub const SYS_dup3: ::c_long = 4000 + 327; +pub const SYS_pipe2: ::c_long = 4000 + 328; +pub const SYS_inotify_init1: ::c_long = 4000 + 329; +pub const SYS_preadv: ::c_long = 4000 + 330; +pub const SYS_pwritev: ::c_long = 4000 + 331; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 4000 + 332; +pub const SYS_perf_event_open: ::c_long = 4000 + 333; +pub const SYS_accept4: ::c_long = 4000 + 334; +pub const SYS_recvmmsg: ::c_long = 4000 + 335; +pub const SYS_fanotify_init: ::c_long = 4000 + 336; +pub const SYS_fanotify_mark: ::c_long = 4000 + 337; +pub const SYS_prlimit64: ::c_long = 4000 + 338; +pub const SYS_name_to_handle_at: ::c_long = 4000 + 339; +pub const SYS_open_by_handle_at: ::c_long = 4000 + 340; +pub const SYS_clock_adjtime: ::c_long = 4000 + 341; +pub const SYS_syncfs: ::c_long = 4000 + 342; +pub const SYS_sendmmsg: ::c_long = 4000 + 343; +pub const SYS_setns: ::c_long = 4000 + 344; +pub const SYS_process_vm_readv: ::c_long = 4000 + 345; +pub const SYS_process_vm_writev: ::c_long = 4000 + 346; +pub const SYS_kcmp: ::c_long = 4000 + 347; +pub const SYS_finit_module: ::c_long = 4000 + 348; +pub const SYS_sched_setattr: ::c_long = 4000 + 349; +pub const SYS_sched_getattr: ::c_long = 4000 + 350; +pub const SYS_renameat2: ::c_long = 4000 + 351; +pub const SYS_seccomp: ::c_long = 4000 + 352; +pub const SYS_getrandom: ::c_long = 4000 + 353; +pub const SYS_memfd_create: ::c_long = 4000 + 354; +pub const SYS_bpf: ::c_long = 4000 + 355; +pub const SYS_execveat: ::c_long = 4000 + 356; +pub const SYS_userfaultfd: ::c_long = 4000 + 357; +pub const SYS_membarrier: ::c_long = 4000 + 358; +pub const SYS_mlock2: ::c_long = 4000 + 359; +pub const SYS_copy_file_range: ::c_long = 4000 + 360; +pub const SYS_preadv2: ::c_long = 4000 + 361; +pub const SYS_pwritev2: ::c_long = 4000 + 362; + +#[doc(hidden)] +pub const AF_MAX: ::c_int = 42; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,68 @@ +pub type c_long = i32; +pub type c_ulong = u32; +pub type nlink_t = u32; +pub type blksize_t = ::c_long; +pub type __u64 = ::c_ulonglong; + +s! { + pub struct pthread_attr_t { + __size: [u32; 9] + } + + pub struct sigset_t { + __val: [::c_ulong; 32], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::c_int, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::socklen_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::socklen_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct sem_t { + __val: [::c_int; 4], + } + + pub struct ipc_perm { + pub __ipc_perm_key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + pub __seq: ::c_int, + __unused1: ::c_long, + __unused2: ::c_long + } +} + +pub const SIGSTKSZ: ::size_t = 8192; +pub const MINSIGSTKSZ: ::size_t = 2048; + +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 32; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 24; + +cfg_if! { + if #[cfg(any(target_arch = "x86"))] { + mod x86; + pub use self::x86::*; + } else if #[cfg(any(target_arch = "mips"))] { + mod mips; + pub use self::mips::*; + } else if #[cfg(any(target_arch = "arm"))] { + mod arm; + pub use self::arm::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/x86.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/x86.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/x86.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b32/x86.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,816 @@ +pub type c_char = i8; +pub type wchar_t = i32; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + __st_dev_padding: ::c_int, + __st_ino_truncated: ::c_long, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __st_rdev_padding: ::c_int, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_ino: ::ino_t, + } + + pub struct stat64 { + pub st_dev: ::dev_t, + __st_dev_padding: ::c_int, + __st_ino_truncated: ::c_long, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __st_rdev_padding: ::c_int, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_ino: ::ino_t, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_flags: ::c_int, + pub ss_size: ::size_t + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + __unused1: ::c_int, + pub shm_dtime: ::time_t, + __unused2: ::c_int, + pub shm_ctime: ::time_t, + __unused3: ::c_int, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::c_ulong, + __pad1: ::c_ulong, + __pad2: ::c_ulong, + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_stime: ::time_t, + __unused1: ::c_int, + pub msg_rtime: ::time_t, + __unused2: ::c_int, + pub msg_ctime: ::time_t, + __unused3: ::c_int, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __pad1: ::c_ulong, + __pad2: ::c_ulong, + } + + pub struct statfs { + pub f_type: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_flags: ::c_ulong, + pub f_spare: [::c_ulong; 4], + } + + pub struct mcontext_t { + __private: [u32; 22] + } + + pub struct ucontext_t { + pub uc_flags: ::c_ulong, + pub uc_link: *mut ucontext_t, + pub uc_stack: ::stack_t, + pub uc_mcontext: mcontext_t, + pub uc_sigmask: ::sigset_t, + __private: [u8; 112], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_errno: ::c_int, + pub si_code: ::c_int, + pub _pad: [::c_int; 29], + _align: [usize; 0], + } + + pub struct statfs64 { + pub f_type: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_flags: ::c_ulong, + pub f_spare: [::c_ulong; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + __f_unused: ::c_int, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 19], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } +} + +pub const O_DIRECT: ::c_int = 0x4000; +pub const O_DIRECTORY: ::c_int = 0x10000; +pub const O_NOFOLLOW: ::c_int = 0x20000; +pub const O_ASYNC: ::c_int = 0x2000; +pub const O_LARGEFILE: ::c_int = 0o0100000; + +pub const FIOCLEX: ::c_int = 0x5451; +pub const FIONBIO: ::c_int = 0x5421; + +pub const RLIMIT_RSS: ::c_int = 5; +pub const RLIMIT_NOFILE: ::c_int = 7; +pub const RLIMIT_AS: ::c_int = 9; +pub const RLIMIT_NPROC: ::c_int = 6; +pub const RLIMIT_MEMLOCK: ::c_int = 8; + +pub const O_APPEND: ::c_int = 1024; +pub const O_CREAT: ::c_int = 64; +pub const O_EXCL: ::c_int = 128; +pub const O_NOCTTY: ::c_int = 256; +pub const O_NONBLOCK: ::c_int = 2048; +pub const O_SYNC: ::c_int = 1052672; +pub const O_RSYNC: ::c_int = 1052672; +pub const O_DSYNC: ::c_int = 4096; + +pub const SOCK_NONBLOCK: ::c_int = 2048; + +pub const MAP_ANON: ::c_int = 0x0020; +pub const MAP_GROWSDOWN: ::c_int = 0x0100; +pub const MAP_DENYWRITE: ::c_int = 0x0800; +pub const MAP_EXECUTABLE: ::c_int = 0x01000; +pub const MAP_LOCKED: ::c_int = 0x02000; +pub const MAP_NORESERVE: ::c_int = 0x04000; +pub const MAP_POPULATE: ::c_int = 0x08000; +pub const MAP_NONBLOCK: ::c_int = 0x010000; +pub const MAP_STACK: ::c_int = 0x020000; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_SEQPACKET: ::c_int = 5; + +pub const SOL_SOCKET: ::c_int = 1; + +pub const EDEADLK: ::c_int = 35; +pub const ENAMETOOLONG: ::c_int = 36; +pub const ENOLCK: ::c_int = 37; +pub const ENOSYS: ::c_int = 38; +pub const ENOTEMPTY: ::c_int = 39; +pub const ELOOP: ::c_int = 40; +pub const ENOMSG: ::c_int = 42; +pub const EIDRM: ::c_int = 43; +pub const ECHRNG: ::c_int = 44; +pub const EL2NSYNC: ::c_int = 45; +pub const EL3HLT: ::c_int = 46; +pub const EL3RST: ::c_int = 47; +pub const ELNRNG: ::c_int = 48; +pub const EUNATCH: ::c_int = 49; +pub const ENOCSI: ::c_int = 50; +pub const EL2HLT: ::c_int = 51; +pub const EBADE: ::c_int = 52; +pub const EBADR: ::c_int = 53; +pub const EXFULL: ::c_int = 54; +pub const ENOANO: ::c_int = 55; +pub const EBADRQC: ::c_int = 56; +pub const EBADSLT: ::c_int = 57; +pub const EDEADLOCK: ::c_int = EDEADLK; +pub const EMULTIHOP: ::c_int = 72; +pub const EBADMSG: ::c_int = 74; +pub const EOVERFLOW: ::c_int = 75; +pub const ENOTUNIQ: ::c_int = 76; +pub const EBADFD: ::c_int = 77; +pub const EREMCHG: ::c_int = 78; +pub const ELIBACC: ::c_int = 79; +pub const ELIBBAD: ::c_int = 80; +pub const ELIBSCN: ::c_int = 81; +pub const ELIBMAX: ::c_int = 82; +pub const ELIBEXEC: ::c_int = 83; +pub const EILSEQ: ::c_int = 84; +pub const ERESTART: ::c_int = 85; +pub const ESTRPIPE: ::c_int = 86; +pub const EUSERS: ::c_int = 87; +pub const ENOTSOCK: ::c_int = 88; +pub const EDESTADDRREQ: ::c_int = 89; +pub const EMSGSIZE: ::c_int = 90; +pub const EPROTOTYPE: ::c_int = 91; +pub const ENOPROTOOPT: ::c_int = 92; +pub const EPROTONOSUPPORT: ::c_int = 93; +pub const ESOCKTNOSUPPORT: ::c_int = 94; +pub const EOPNOTSUPP: ::c_int = 95; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; +pub const EPFNOSUPPORT: ::c_int = 96; +pub const EAFNOSUPPORT: ::c_int = 97; +pub const EADDRINUSE: ::c_int = 98; +pub const EADDRNOTAVAIL: ::c_int = 99; +pub const ENETDOWN: ::c_int = 100; +pub const ENETUNREACH: ::c_int = 101; +pub const ENETRESET: ::c_int = 102; +pub const ECONNABORTED: ::c_int = 103; +pub const ECONNRESET: ::c_int = 104; +pub const ENOBUFS: ::c_int = 105; +pub const EISCONN: ::c_int = 106; +pub const ENOTCONN: ::c_int = 107; +pub const ESHUTDOWN: ::c_int = 108; +pub const ETOOMANYREFS: ::c_int = 109; +pub const ETIMEDOUT: ::c_int = 110; +pub const ECONNREFUSED: ::c_int = 111; +pub const EHOSTDOWN: ::c_int = 112; +pub const EHOSTUNREACH: ::c_int = 113; +pub const EALREADY: ::c_int = 114; +pub const EINPROGRESS: ::c_int = 115; +pub const ESTALE: ::c_int = 116; +pub const EUCLEAN: ::c_int = 117; +pub const ENOTNAM: ::c_int = 118; +pub const ENAVAIL: ::c_int = 119; +pub const EISNAM: ::c_int = 120; +pub const EREMOTEIO: ::c_int = 121; +pub const EDQUOT: ::c_int = 122; +pub const ENOMEDIUM: ::c_int = 123; +pub const EMEDIUMTYPE: ::c_int = 124; +pub const ECANCELED: ::c_int = 125; +pub const ENOKEY: ::c_int = 126; +pub const EKEYEXPIRED: ::c_int = 127; +pub const EKEYREVOKED: ::c_int = 128; +pub const EKEYREJECTED: ::c_int = 129; +pub const EOWNERDEAD: ::c_int = 130; +pub const ENOTRECOVERABLE: ::c_int = 131; +pub const ERFKILL: ::c_int = 132; +pub const EHWPOISON: ::c_int = 133; + +pub const SO_REUSEADDR: ::c_int = 2; +pub const SO_TYPE: ::c_int = 3; +pub const SO_ERROR: ::c_int = 4; +pub const SO_DONTROUTE: ::c_int = 5; +pub const SO_BROADCAST: ::c_int = 6; +pub const SO_SNDBUF: ::c_int = 7; +pub const SO_RCVBUF: ::c_int = 8; +pub const SO_KEEPALIVE: ::c_int = 9; +pub const SO_OOBINLINE: ::c_int = 10; +pub const SO_NO_CHECK: ::c_int = 11; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_LINGER: ::c_int = 13; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_REUSEPORT: ::c_int = 15; +pub const SO_PASSCRED: ::c_int = 16; +pub const SO_PEERCRED: ::c_int = 17; +pub const SO_RCVLOWAT: ::c_int = 18; +pub const SO_SNDLOWAT: ::c_int = 19; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_SNDTIMEO: ::c_int = 21; +pub const SO_ACCEPTCONN: ::c_int = 30; +pub const SO_SNDBUFFORCE: ::c_int = 32; +pub const SO_RCVBUFFORCE: ::c_int = 33; +pub const SO_PROTOCOL: ::c_int = 38; +pub const SO_DOMAIN: ::c_int = 39; + +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 0x00000004; +pub const SA_NOCLDWAIT: ::c_int = 0x00000002; + +pub const SIGCHLD: ::c_int = 17; +pub const SIGBUS: ::c_int = 7; +pub const SIGTTIN: ::c_int = 21; +pub const SIGTTOU: ::c_int = 22; +pub const SIGXCPU: ::c_int = 24; +pub const SIGXFSZ: ::c_int = 25; +pub const SIGVTALRM: ::c_int = 26; +pub const SIGPROF: ::c_int = 27; +pub const SIGWINCH: ::c_int = 28; +pub const SIGUSR1: ::c_int = 10; +pub const SIGUSR2: ::c_int = 12; +pub const SIGCONT: ::c_int = 18; +pub const SIGSTOP: ::c_int = 19; +pub const SIGTSTP: ::c_int = 20; +pub const SIGURG: ::c_int = 23; +pub const SIGIO: ::c_int = 29; +pub const SIGSYS: ::c_int = 31; +pub const SIGSTKFLT: ::c_int = 16; +pub const SIGPOLL: ::c_int = 29; +pub const SIGPWR: ::c_int = 30; +pub const SIG_SETMASK: ::c_int = 2; +pub const SIG_BLOCK: ::c_int = 0x000000; +pub const SIG_UNBLOCK: ::c_int = 0x01; + +pub const EXTPROC: ::tcflag_t = 0x00010000; + +pub const MAP_HUGETLB: ::c_int = 0x040000; +pub const MAP_32BIT: ::c_int = 0x0040; + +pub const F_GETLK: ::c_int = 12; +pub const F_GETOWN: ::c_int = 9; +pub const F_SETLK: ::c_int = 13; +pub const F_SETLKW: ::c_int = 14; +pub const F_SETOWN: ::c_int = 8; + +pub const VEOF: usize = 4; +pub const VEOL: usize = 11; +pub const VEOL2: usize = 16; +pub const VMIN: usize = 6; +pub const IEXTEN: ::tcflag_t = 0x00008000; +pub const TOSTOP: ::tcflag_t = 0x00000100; +pub const FLUSHO: ::tcflag_t = 0x00001000; + +pub const TCGETS: ::c_int = 0x5401; +pub const TCSETS: ::c_int = 0x5402; +pub const TCSETSW: ::c_int = 0x5403; +pub const TCSETSF: ::c_int = 0x5404; +pub const TCGETA: ::c_int = 0x5405; +pub const TCSETA: ::c_int = 0x5406; +pub const TCSETAW: ::c_int = 0x5407; +pub const TCSETAF: ::c_int = 0x5408; +pub const TCSBRK: ::c_int = 0x5409; +pub const TCXONC: ::c_int = 0x540A; +pub const TCFLSH: ::c_int = 0x540B; +pub const TIOCGSOFTCAR: ::c_int = 0x5419; +pub const TIOCSSOFTCAR: ::c_int = 0x541A; +pub const TIOCLINUX: ::c_int = 0x541C; +pub const TIOCGSERIAL: ::c_int = 0x541E; +pub const TIOCEXCL: ::c_int = 0x540C; +pub const TIOCNXCL: ::c_int = 0x540D; +pub const TIOCSCTTY: ::c_int = 0x540E; +pub const TIOCGPGRP: ::c_int = 0x540F; +pub const TIOCSPGRP: ::c_int = 0x5410; +pub const TIOCOUTQ: ::c_int = 0x5411; +pub const TIOCSTI: ::c_int = 0x5412; +pub const TIOCGWINSZ: ::c_int = 0x5413; +pub const TIOCSWINSZ: ::c_int = 0x5414; +pub const TIOCMGET: ::c_int = 0x5415; +pub const TIOCMBIS: ::c_int = 0x5416; +pub const TIOCMBIC: ::c_int = 0x5417; +pub const TIOCMSET: ::c_int = 0x5418; +pub const FIONREAD: ::c_int = 0x541B; +pub const TIOCCONS: ::c_int = 0x541D; + +pub const POLLWRNORM: ::c_short = 0x100; +pub const POLLWRBAND: ::c_short = 0x200; + +pub const TIOCM_LE: ::c_int = 0x001; +pub const TIOCM_DTR: ::c_int = 0x002; +pub const TIOCM_RTS: ::c_int = 0x004; +pub const TIOCM_ST: ::c_int = 0x008; +pub const TIOCM_SR: ::c_int = 0x010; +pub const TIOCM_CTS: ::c_int = 0x020; +pub const TIOCM_CAR: ::c_int = 0x040; +pub const TIOCM_RNG: ::c_int = 0x080; +pub const TIOCM_DSR: ::c_int = 0x100; +pub const TIOCM_CD: ::c_int = TIOCM_CAR; +pub const TIOCM_RI: ::c_int = TIOCM_RNG; + +// Syscall table +pub const SYS_restart_syscall: ::c_long = 0; +pub const SYS_exit: ::c_long = 1; +pub const SYS_fork: ::c_long = 2; +pub const SYS_read: ::c_long = 3; +pub const SYS_write: ::c_long = 4; +pub const SYS_open: ::c_long = 5; +pub const SYS_close: ::c_long = 6; +pub const SYS_waitpid: ::c_long = 7; +pub const SYS_creat: ::c_long = 8; +pub const SYS_link: ::c_long = 9; +pub const SYS_unlink: ::c_long = 10; +pub const SYS_execve: ::c_long = 11; +pub const SYS_chdir: ::c_long = 12; +pub const SYS_time: ::c_long = 13; +pub const SYS_mknod: ::c_long = 14; +pub const SYS_chmod: ::c_long = 15; +pub const SYS_lchown: ::c_long = 16; +pub const SYS_break: ::c_long = 17; +pub const SYS_oldstat: ::c_long = 18; +pub const SYS_lseek: ::c_long = 19; +pub const SYS_getpid: ::c_long = 20; +pub const SYS_mount: ::c_long = 21; +pub const SYS_umount: ::c_long = 22; +pub const SYS_setuid: ::c_long = 23; +pub const SYS_getuid: ::c_long = 24; +pub const SYS_stime: ::c_long = 25; +pub const SYS_ptrace: ::c_long = 26; +pub const SYS_alarm: ::c_long = 27; +pub const SYS_oldfstat: ::c_long = 28; +pub const SYS_pause: ::c_long = 29; +pub const SYS_utime: ::c_long = 30; +pub const SYS_stty: ::c_long = 31; +pub const SYS_gtty: ::c_long = 32; +pub const SYS_access: ::c_long = 33; +pub const SYS_nice: ::c_long = 34; +pub const SYS_ftime: ::c_long = 35; +pub const SYS_sync: ::c_long = 36; +pub const SYS_kill: ::c_long = 37; +pub const SYS_rename: ::c_long = 38; +pub const SYS_mkdir: ::c_long = 39; +pub const SYS_rmdir: ::c_long = 40; +pub const SYS_dup: ::c_long = 41; +pub const SYS_pipe: ::c_long = 42; +pub const SYS_times: ::c_long = 43; +pub const SYS_prof: ::c_long = 44; +pub const SYS_brk: ::c_long = 45; +pub const SYS_setgid: ::c_long = 46; +pub const SYS_getgid: ::c_long = 47; +pub const SYS_signal: ::c_long = 48; +pub const SYS_geteuid: ::c_long = 49; +pub const SYS_getegid: ::c_long = 50; +pub const SYS_acct: ::c_long = 51; +pub const SYS_umount2: ::c_long = 52; +pub const SYS_lock: ::c_long = 53; +pub const SYS_ioctl: ::c_long = 54; +pub const SYS_fcntl: ::c_long = 55; +pub const SYS_mpx: ::c_long = 56; +pub const SYS_setpgid: ::c_long = 57; +pub const SYS_ulimit: ::c_long = 58; +pub const SYS_oldolduname: ::c_long = 59; +pub const SYS_umask: ::c_long = 60; +pub const SYS_chroot: ::c_long = 61; +pub const SYS_ustat: ::c_long = 62; +pub const SYS_dup2: ::c_long = 63; +pub const SYS_getppid: ::c_long = 64; +pub const SYS_getpgrp: ::c_long = 65; +pub const SYS_setsid: ::c_long = 66; +pub const SYS_sigaction: ::c_long = 67; +pub const SYS_sgetmask: ::c_long = 68; +pub const SYS_ssetmask: ::c_long = 69; +pub const SYS_setreuid: ::c_long = 70; +pub const SYS_setregid: ::c_long = 71; +pub const SYS_sigsuspend: ::c_long = 72; +pub const SYS_sigpending: ::c_long = 73; +pub const SYS_sethostname: ::c_long = 74; +pub const SYS_setrlimit: ::c_long = 75; +pub const SYS_getrlimit: ::c_long = 76; +pub const SYS_getrusage: ::c_long = 77; +pub const SYS_gettimeofday: ::c_long = 78; +pub const SYS_settimeofday: ::c_long = 79; +pub const SYS_getgroups: ::c_long = 80; +pub const SYS_setgroups: ::c_long = 81; +pub const SYS_select: ::c_long = 82; +pub const SYS_symlink: ::c_long = 83; +pub const SYS_oldlstat: ::c_long = 84; +pub const SYS_readlink: ::c_long = 85; +pub const SYS_uselib: ::c_long = 86; +pub const SYS_swapon: ::c_long = 87; +pub const SYS_reboot: ::c_long = 88; +pub const SYS_readdir: ::c_long = 89; +pub const SYS_mmap: ::c_long = 90; +pub const SYS_munmap: ::c_long = 91; +pub const SYS_truncate: ::c_long = 92; +pub const SYS_ftruncate: ::c_long = 93; +pub const SYS_fchmod: ::c_long = 94; +pub const SYS_fchown: ::c_long = 95; +pub const SYS_getpriority: ::c_long = 96; +pub const SYS_setpriority: ::c_long = 97; +pub const SYS_profil: ::c_long = 98; +pub const SYS_statfs: ::c_long = 99; +pub const SYS_fstatfs: ::c_long = 100; +pub const SYS_ioperm: ::c_long = 101; +pub const SYS_socketcall: ::c_long = 102; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_setitimer: ::c_long = 104; +pub const SYS_getitimer: ::c_long = 105; +pub const SYS_stat: ::c_long = 106; +pub const SYS_lstat: ::c_long = 107; +pub const SYS_fstat: ::c_long = 108; +pub const SYS_olduname: ::c_long = 109; +pub const SYS_iopl: ::c_long = 110; +pub const SYS_vhangup: ::c_long = 111; +pub const SYS_idle: ::c_long = 112; +pub const SYS_vm86old: ::c_long = 113; +pub const SYS_wait4: ::c_long = 114; +pub const SYS_swapoff: ::c_long = 115; +pub const SYS_sysinfo: ::c_long = 116; +pub const SYS_ipc: ::c_long = 117; +pub const SYS_fsync: ::c_long = 118; +pub const SYS_sigreturn: ::c_long = 119; +pub const SYS_clone: ::c_long = 120; +pub const SYS_setdomainname: ::c_long = 121; +pub const SYS_uname: ::c_long = 122; +pub const SYS_modify_ldt: ::c_long = 123; +pub const SYS_adjtimex: ::c_long = 124; +pub const SYS_mprotect: ::c_long = 125; +pub const SYS_sigprocmask: ::c_long = 126; +pub const SYS_create_module: ::c_long = 127; +pub const SYS_init_module: ::c_long = 128; +pub const SYS_delete_module: ::c_long = 129; +pub const SYS_get_kernel_syms: ::c_long = 130; +pub const SYS_quotactl: ::c_long = 131; +pub const SYS_getpgid: ::c_long = 132; +pub const SYS_fchdir: ::c_long = 133; +pub const SYS_bdflush: ::c_long = 134; +pub const SYS_sysfs: ::c_long = 135; +pub const SYS_personality: ::c_long = 136; +pub const SYS_afs_syscall: ::c_long = 137; +pub const SYS_setfsuid: ::c_long = 138; +pub const SYS_setfsgid: ::c_long = 139; +pub const SYS__llseek: ::c_long = 140; +pub const SYS_getdents: ::c_long = 141; +pub const SYS__newselect: ::c_long = 142; +pub const SYS_flock: ::c_long = 143; +pub const SYS_msync: ::c_long = 144; +pub const SYS_readv: ::c_long = 145; +pub const SYS_writev: ::c_long = 146; +pub const SYS_getsid: ::c_long = 147; +pub const SYS_fdatasync: ::c_long = 148; +pub const SYS__sysctl: ::c_long = 149; +pub const SYS_mlock: ::c_long = 150; +pub const SYS_munlock: ::c_long = 151; +pub const SYS_mlockall: ::c_long = 152; +pub const SYS_munlockall: ::c_long = 153; +pub const SYS_sched_setparam: ::c_long = 154; +pub const SYS_sched_getparam: ::c_long = 155; +pub const SYS_sched_setscheduler: ::c_long = 156; +pub const SYS_sched_getscheduler: ::c_long = 157; +pub const SYS_sched_yield: ::c_long = 158; +pub const SYS_sched_get_priority_max: ::c_long = 159; +pub const SYS_sched_get_priority_min: ::c_long = 160; +pub const SYS_sched_rr_get_interval: ::c_long = 161; +pub const SYS_nanosleep: ::c_long = 162; +pub const SYS_mremap: ::c_long = 163; +pub const SYS_setresuid: ::c_long = 164; +pub const SYS_getresuid: ::c_long = 165; +pub const SYS_vm86: ::c_long = 166; +pub const SYS_query_module: ::c_long = 167; +pub const SYS_poll: ::c_long = 168; +pub const SYS_nfsservctl: ::c_long = 169; +pub const SYS_setresgid: ::c_long = 170; +pub const SYS_getresgid: ::c_long = 171; +pub const SYS_prctl: ::c_long = 172; +pub const SYS_rt_sigreturn: ::c_long = 173; +pub const SYS_rt_sigaction: ::c_long = 174; +pub const SYS_rt_sigprocmask: ::c_long = 175; +pub const SYS_rt_sigpending: ::c_long = 176; +pub const SYS_rt_sigtimedwait: ::c_long = 177; +pub const SYS_rt_sigqueueinfo: ::c_long = 178; +pub const SYS_rt_sigsuspend: ::c_long = 179; +pub const SYS_pread64: ::c_long = 180; +pub const SYS_pwrite64: ::c_long = 181; +pub const SYS_chown: ::c_long = 182; +pub const SYS_getcwd: ::c_long = 183; +pub const SYS_capget: ::c_long = 184; +pub const SYS_capset: ::c_long = 185; +pub const SYS_sigaltstack: ::c_long = 186; +pub const SYS_sendfile: ::c_long = 187; +pub const SYS_getpmsg: ::c_long = 188; +pub const SYS_putpmsg: ::c_long = 189; +pub const SYS_vfork: ::c_long = 190; +pub const SYS_ugetrlimit: ::c_long = 191; +pub const SYS_mmap2: ::c_long = 192; +pub const SYS_truncate64: ::c_long = 193; +pub const SYS_ftruncate64: ::c_long = 194; +pub const SYS_stat64: ::c_long = 195; +pub const SYS_lstat64: ::c_long = 196; +pub const SYS_fstat64: ::c_long = 197; +pub const SYS_lchown32: ::c_long = 198; +pub const SYS_getuid32: ::c_long = 199; +pub const SYS_getgid32: ::c_long = 200; +pub const SYS_geteuid32: ::c_long = 201; +pub const SYS_getegid32: ::c_long = 202; +pub const SYS_setreuid32: ::c_long = 203; +pub const SYS_setregid32: ::c_long = 204; +pub const SYS_getgroups32: ::c_long = 205; +pub const SYS_setgroups32: ::c_long = 206; +pub const SYS_fchown32: ::c_long = 207; +pub const SYS_setresuid32: ::c_long = 208; +pub const SYS_getresuid32: ::c_long = 209; +pub const SYS_setresgid32: ::c_long = 210; +pub const SYS_getresgid32: ::c_long = 211; +pub const SYS_chown32: ::c_long = 212; +pub const SYS_setuid32: ::c_long = 213; +pub const SYS_setgid32: ::c_long = 214; +pub const SYS_setfsuid32: ::c_long = 215; +pub const SYS_setfsgid32: ::c_long = 216; +pub const SYS_pivot_root: ::c_long = 217; +pub const SYS_mincore: ::c_long = 218; +pub const SYS_madvise: ::c_long = 219; +pub const SYS_getdents64: ::c_long = 220; +pub const SYS_fcntl64: ::c_long = 221; +pub const SYS_gettid: ::c_long = 224; +pub const SYS_readahead: ::c_long = 225; +pub const SYS_setxattr: ::c_long = 226; +pub const SYS_lsetxattr: ::c_long = 227; +pub const SYS_fsetxattr: ::c_long = 228; +pub const SYS_getxattr: ::c_long = 229; +pub const SYS_lgetxattr: ::c_long = 230; +pub const SYS_fgetxattr: ::c_long = 231; +pub const SYS_listxattr: ::c_long = 232; +pub const SYS_llistxattr: ::c_long = 233; +pub const SYS_flistxattr: ::c_long = 234; +pub const SYS_removexattr: ::c_long = 235; +pub const SYS_lremovexattr: ::c_long = 236; +pub const SYS_fremovexattr: ::c_long = 237; +pub const SYS_tkill: ::c_long = 238; +pub const SYS_sendfile64: ::c_long = 239; +pub const SYS_futex: ::c_long = 240; +pub const SYS_sched_setaffinity: ::c_long = 241; +pub const SYS_sched_getaffinity: ::c_long = 242; +pub const SYS_set_thread_area: ::c_long = 243; +pub const SYS_get_thread_area: ::c_long = 244; +pub const SYS_io_setup: ::c_long = 245; +pub const SYS_io_destroy: ::c_long = 246; +pub const SYS_io_getevents: ::c_long = 247; +pub const SYS_io_submit: ::c_long = 248; +pub const SYS_io_cancel: ::c_long = 249; +pub const SYS_fadvise64: ::c_long = 250; +pub const SYS_exit_group: ::c_long = 252; +pub const SYS_lookup_dcookie: ::c_long = 253; +pub const SYS_epoll_create: ::c_long = 254; +pub const SYS_epoll_ctl: ::c_long = 255; +pub const SYS_epoll_wait: ::c_long = 256; +pub const SYS_remap_file_pages: ::c_long = 257; +pub const SYS_set_tid_address: ::c_long = 258; +pub const SYS_timer_create: ::c_long = 259; +pub const SYS_timer_settime: ::c_long = 260; +pub const SYS_timer_gettime: ::c_long = 261; +pub const SYS_timer_getoverrun: ::c_long = 262; +pub const SYS_timer_delete: ::c_long = 263; +pub const SYS_clock_settime: ::c_long = 264; +pub const SYS_clock_gettime: ::c_long = 265; +pub const SYS_clock_getres: ::c_long = 266; +pub const SYS_clock_nanosleep: ::c_long = 267; +pub const SYS_statfs64: ::c_long = 268; +pub const SYS_fstatfs64: ::c_long = 269; +pub const SYS_tgkill: ::c_long = 270; +pub const SYS_utimes: ::c_long = 271; +pub const SYS_fadvise64_64: ::c_long = 272; +pub const SYS_vserver: ::c_long = 273; +pub const SYS_mbind: ::c_long = 274; +pub const SYS_get_mempolicy: ::c_long = 275; +pub const SYS_set_mempolicy: ::c_long = 276; +pub const SYS_mq_open: ::c_long = 277; +pub const SYS_mq_unlink: ::c_long = 278; +pub const SYS_mq_timedsend: ::c_long = 279; +pub const SYS_mq_timedreceive: ::c_long = 280; +pub const SYS_mq_notify: ::c_long = 281; +pub const SYS_mq_getsetattr: ::c_long = 282; +pub const SYS_kexec_load: ::c_long = 283; +pub const SYS_waitid: ::c_long = 284; +pub const SYS_add_key: ::c_long = 286; +pub const SYS_request_key: ::c_long = 287; +pub const SYS_keyctl: ::c_long = 288; +pub const SYS_ioprio_set: ::c_long = 289; +pub const SYS_ioprio_get: ::c_long = 290; +pub const SYS_inotify_init: ::c_long = 291; +pub const SYS_inotify_add_watch: ::c_long = 292; +pub const SYS_inotify_rm_watch: ::c_long = 293; +pub const SYS_migrate_pages: ::c_long = 294; +pub const SYS_openat: ::c_long = 295; +pub const SYS_mkdirat: ::c_long = 296; +pub const SYS_mknodat: ::c_long = 297; +pub const SYS_fchownat: ::c_long = 298; +pub const SYS_futimesat: ::c_long = 299; +pub const SYS_fstatat64: ::c_long = 300; +pub const SYS_unlinkat: ::c_long = 301; +pub const SYS_renameat: ::c_long = 302; +pub const SYS_linkat: ::c_long = 303; +pub const SYS_symlinkat: ::c_long = 304; +pub const SYS_readlinkat: ::c_long = 305; +pub const SYS_fchmodat: ::c_long = 306; +pub const SYS_faccessat: ::c_long = 307; +pub const SYS_pselect6: ::c_long = 308; +pub const SYS_ppoll: ::c_long = 309; +pub const SYS_unshare: ::c_long = 310; +pub const SYS_set_robust_list: ::c_long = 311; +pub const SYS_get_robust_list: ::c_long = 312; +pub const SYS_splice: ::c_long = 313; +pub const SYS_sync_file_range: ::c_long = 314; +pub const SYS_tee: ::c_long = 315; +pub const SYS_vmsplice: ::c_long = 316; +pub const SYS_move_pages: ::c_long = 317; +pub const SYS_getcpu: ::c_long = 318; +pub const SYS_epoll_pwait: ::c_long = 319; +pub const SYS_utimensat: ::c_long = 320; +pub const SYS_signalfd: ::c_long = 321; +pub const SYS_timerfd_create: ::c_long = 322; +pub const SYS_eventfd: ::c_long = 323; +pub const SYS_fallocate: ::c_long = 324; +pub const SYS_timerfd_settime: ::c_long = 325; +pub const SYS_timerfd_gettime: ::c_long = 326; +pub const SYS_signalfd4: ::c_long = 327; +pub const SYS_eventfd2: ::c_long = 328; +pub const SYS_epoll_create1: ::c_long = 329; +pub const SYS_dup3: ::c_long = 330; +pub const SYS_pipe2: ::c_long = 331; +pub const SYS_inotify_init1: ::c_long = 332; +pub const SYS_preadv: ::c_long = 333; +pub const SYS_pwritev: ::c_long = 334; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 335; +pub const SYS_perf_event_open: ::c_long = 336; +pub const SYS_recvmmsg: ::c_long = 337; +pub const SYS_fanotify_init: ::c_long = 338; +pub const SYS_fanotify_mark: ::c_long = 339; +pub const SYS_prlimit64: ::c_long = 340; +pub const SYS_name_to_handle_at: ::c_long = 341; +pub const SYS_open_by_handle_at: ::c_long = 342; +pub const SYS_clock_adjtime: ::c_long = 343; +pub const SYS_syncfs: ::c_long = 344; +pub const SYS_sendmmsg: ::c_long = 345; +pub const SYS_setns: ::c_long = 346; +pub const SYS_process_vm_readv: ::c_long = 347; +pub const SYS_process_vm_writev: ::c_long = 348; +pub const SYS_kcmp: ::c_long = 349; +pub const SYS_finit_module: ::c_long = 350; +pub const SYS_sched_setattr: ::c_long = 351; +pub const SYS_sched_getattr: ::c_long = 352; +pub const SYS_renameat2: ::c_long = 353; +pub const SYS_seccomp: ::c_long = 354; +pub const SYS_getrandom: ::c_long = 355; +pub const SYS_memfd_create: ::c_long = 356; +pub const SYS_bpf: ::c_long = 357; +pub const SYS_execveat: ::c_long = 358; +pub const SYS_socket: ::c_long = 359; +pub const SYS_socketpair: ::c_long = 360; +pub const SYS_bind: ::c_long = 361; +pub const SYS_connect: ::c_long = 362; +pub const SYS_listen: ::c_long = 363; +pub const SYS_accept4: ::c_long = 364; +pub const SYS_getsockopt: ::c_long = 365; +pub const SYS_setsockopt: ::c_long = 366; +pub const SYS_getsockname: ::c_long = 367; +pub const SYS_getpeername: ::c_long = 368; +pub const SYS_sendto: ::c_long = 369; +pub const SYS_sendmsg: ::c_long = 370; +pub const SYS_recvfrom: ::c_long = 371; +pub const SYS_recvmsg: ::c_long = 372; +pub const SYS_shutdown: ::c_long = 373; +pub const SYS_userfaultfd: ::c_long = 374; +pub const SYS_membarrier: ::c_long = 375; +pub const SYS_mlock2: ::c_long = 376; +pub const SYS_copy_file_range: ::c_long = 377; +pub const SYS_preadv2: ::c_long = 378; +pub const SYS_pwritev2: ::c_long = 379; +// FIXME syscalls 380-382 have been added in musl 1.16 +// See discussion https://github.com/rust-lang/libc/pull/699 + +// offsets in user_regs_structs, from sys/reg.h +pub const EBX: ::c_int = 0; +pub const ECX: ::c_int = 1; +pub const EDX: ::c_int = 2; +pub const ESI: ::c_int = 3; +pub const EDI: ::c_int = 4; +pub const EBP: ::c_int = 5; +pub const EAX: ::c_int = 6; +pub const DS: ::c_int = 7; +pub const ES: ::c_int = 8; +pub const FS: ::c_int = 9; +pub const GS: ::c_int = 10; +pub const ORIG_EAX: ::c_int = 11; +pub const EIP: ::c_int = 12; +pub const CS: ::c_int = 13; +pub const EFL: ::c_int = 14; +pub const UESP: ::c_int = 15; +pub const SS: ::c_int = 16; + +#[doc(hidden)] +pub const AF_MAX: ::c_int = 42; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/aarch64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/aarch64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,341 @@ +pub type c_char = u8; +pub type __u64 = ::c_ulonglong; +pub type wchar_t = u32; +pub type nlink_t = u32; +pub type blksize_t = ::c_int; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad0: ::c_ulong, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + __pad1: ::c_int, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused: [::c_uint; 2], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad0: ::c_ulong, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + __pad1: ::c_int, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused: [::c_uint; 2], + } + + pub struct ipc_perm { + pub __ipc_perm_key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + pub __seq: ::c_ushort, + __unused1: ::c_ulong, + __unused2: ::c_ulong, + } +} + +pub const O_DIRECT: ::c_int = 0x10000; +pub const O_DIRECTORY: ::c_int = 0x4000; +pub const O_LARGEFILE: ::c_int = 0x20000; +pub const O_NOFOLLOW: ::c_int = 0x8000; + +pub const MINSIGSTKSZ: ::size_t = 6144; +pub const SIGSTKSZ: ::size_t = 12288; + +#[doc(hidden)] +pub const PF_MAX: ::c_int = 43; +#[doc(hidden)] +pub const AF_MAX: ::c_int = PF_MAX; + +pub const SYS_io_setup: ::c_long = 0; +pub const SYS_io_destroy: ::c_long = 1; +pub const SYS_io_submit: ::c_long = 2; +pub const SYS_io_cancel: ::c_long = 3; +pub const SYS_io_getevents: ::c_long = 4; +pub const SYS_setxattr: ::c_long = 5; +pub const SYS_lsetxattr: ::c_long = 6; +pub const SYS_fsetxattr: ::c_long = 7; +pub const SYS_getxattr: ::c_long = 8; +pub const SYS_lgetxattr: ::c_long = 9; +pub const SYS_fgetxattr: ::c_long = 10; +pub const SYS_listxattr: ::c_long = 11; +pub const SYS_llistxattr: ::c_long = 12; +pub const SYS_flistxattr: ::c_long = 13; +pub const SYS_removexattr: ::c_long = 14; +pub const SYS_lremovexattr: ::c_long = 15; +pub const SYS_fremovexattr: ::c_long = 16; +pub const SYS_getcwd: ::c_long = 17; +pub const SYS_lookup_dcookie: ::c_long = 18; +pub const SYS_eventfd2: ::c_long = 19; +pub const SYS_epoll_create1: ::c_long = 20; +pub const SYS_epoll_ctl: ::c_long = 21; +pub const SYS_epoll_pwait: ::c_long = 22; +pub const SYS_dup: ::c_long = 23; +pub const SYS_dup3: ::c_long = 24; +pub const SYS_inotify_init1: ::c_long = 26; +pub const SYS_inotify_add_watch: ::c_long = 27; +pub const SYS_inotify_rm_watch: ::c_long = 28; +pub const SYS_ioctl: ::c_long = 29; +pub const SYS_ioprio_set: ::c_long = 30; +pub const SYS_ioprio_get: ::c_long = 31; +pub const SYS_flock: ::c_long = 32; +pub const SYS_mknodat: ::c_long = 33; +pub const SYS_mkdirat: ::c_long = 34; +pub const SYS_unlinkat: ::c_long = 35; +pub const SYS_symlinkat: ::c_long = 36; +pub const SYS_linkat: ::c_long = 37; +pub const SYS_renameat: ::c_long = 38; +pub const SYS_umount2: ::c_long = 39; +pub const SYS_mount: ::c_long = 40; +pub const SYS_pivot_root: ::c_long = 41; +pub const SYS_nfsservctl: ::c_long = 42; +pub const SYS_fallocate: ::c_long = 47; +pub const SYS_faccessat: ::c_long = 48; +pub const SYS_chdir: ::c_long = 49; +pub const SYS_fchdir: ::c_long = 50; +pub const SYS_chroot: ::c_long = 51; +pub const SYS_fchmod: ::c_long = 52; +pub const SYS_fchmodat: ::c_long = 53; +pub const SYS_fchownat: ::c_long = 54; +pub const SYS_fchown: ::c_long = 55; +pub const SYS_openat: ::c_long = 56; +pub const SYS_close: ::c_long = 57; +pub const SYS_vhangup: ::c_long = 58; +pub const SYS_pipe2: ::c_long = 59; +pub const SYS_quotactl: ::c_long = 60; +pub const SYS_getdents64: ::c_long = 61; +pub const SYS_read: ::c_long = 63; +pub const SYS_write: ::c_long = 64; +pub const SYS_readv: ::c_long = 65; +pub const SYS_writev: ::c_long = 66; +pub const SYS_pread64: ::c_long = 67; +pub const SYS_pwrite64: ::c_long = 68; +pub const SYS_preadv: ::c_long = 69; +pub const SYS_pwritev: ::c_long = 70; +pub const SYS_pselect6: ::c_long = 72; +pub const SYS_ppoll: ::c_long = 73; +pub const SYS_signalfd4: ::c_long = 74; +pub const SYS_vmsplice: ::c_long = 75; +pub const SYS_splice: ::c_long = 76; +pub const SYS_tee: ::c_long = 77; +pub const SYS_readlinkat: ::c_long = 78; +pub const SYS_sync: ::c_long = 81; +pub const SYS_fsync: ::c_long = 82; +pub const SYS_fdatasync: ::c_long = 83; +pub const SYS_sync_file_range: ::c_long = 84; +pub const SYS_timerfd_create: ::c_long = 85; +pub const SYS_timerfd_settime: ::c_long = 86; +pub const SYS_timerfd_gettime: ::c_long = 87; +pub const SYS_utimensat: ::c_long = 88; +pub const SYS_acct: ::c_long = 89; +pub const SYS_capget: ::c_long = 90; +pub const SYS_capset: ::c_long = 91; +pub const SYS_personality: ::c_long = 92; +pub const SYS_exit: ::c_long = 93; +pub const SYS_exit_group: ::c_long = 94; +pub const SYS_waitid: ::c_long = 95; +pub const SYS_set_tid_address: ::c_long = 96; +pub const SYS_unshare: ::c_long = 97; +pub const SYS_futex: ::c_long = 98; +pub const SYS_set_robust_list: ::c_long = 99; +pub const SYS_get_robust_list: ::c_long = 100; +pub const SYS_nanosleep: ::c_long = 101; +pub const SYS_getitimer: ::c_long = 102; +pub const SYS_setitimer: ::c_long = 103; +pub const SYS_kexec_load: ::c_long = 104; +pub const SYS_init_module: ::c_long = 105; +pub const SYS_delete_module: ::c_long = 106; +pub const SYS_timer_create: ::c_long = 107; +pub const SYS_timer_gettime: ::c_long = 108; +pub const SYS_timer_getoverrun: ::c_long = 109; +pub const SYS_timer_settime: ::c_long = 110; +pub const SYS_timer_delete: ::c_long = 111; +pub const SYS_clock_settime: ::c_long = 112; +pub const SYS_clock_gettime: ::c_long = 113; +pub const SYS_clock_getres: ::c_long = 114; +pub const SYS_clock_nanosleep: ::c_long = 115; +pub const SYS_syslog: ::c_long = 116; +pub const SYS_ptrace: ::c_long = 117; +pub const SYS_sched_setparam: ::c_long = 118; +pub const SYS_sched_setscheduler: ::c_long = 119; +pub const SYS_sched_getscheduler: ::c_long = 120; +pub const SYS_sched_getparam: ::c_long = 121; +pub const SYS_sched_setaffinity: ::c_long = 122; +pub const SYS_sched_getaffinity: ::c_long = 123; +pub const SYS_sched_yield: ::c_long = 124; +pub const SYS_sched_get_priority_max: ::c_long = 125; +pub const SYS_sched_get_priority_min: ::c_long = 126; +pub const SYS_sched_rr_get_interval: ::c_long = 127; +pub const SYS_restart_syscall: ::c_long = 128; +pub const SYS_kill: ::c_long = 129; +pub const SYS_tkill: ::c_long = 130; +pub const SYS_tgkill: ::c_long = 131; +pub const SYS_sigaltstack: ::c_long = 132; +pub const SYS_rt_sigsuspend: ::c_long = 133; +pub const SYS_rt_sigaction: ::c_long = 134; +pub const SYS_rt_sigprocmask: ::c_long = 135; +pub const SYS_rt_sigpending: ::c_long = 136; +pub const SYS_rt_sigtimedwait: ::c_long = 137; +pub const SYS_rt_sigqueueinfo: ::c_long = 138; +pub const SYS_rt_sigreturn: ::c_long = 139; +pub const SYS_setpriority: ::c_long = 140; +pub const SYS_getpriority: ::c_long = 141; +pub const SYS_reboot: ::c_long = 142; +pub const SYS_setregid: ::c_long = 143; +pub const SYS_setgid: ::c_long = 144; +pub const SYS_setreuid: ::c_long = 145; +pub const SYS_setuid: ::c_long = 146; +pub const SYS_setresuid: ::c_long = 147; +pub const SYS_getresuid: ::c_long = 148; +pub const SYS_setresgid: ::c_long = 149; +pub const SYS_getresgid: ::c_long = 150; +pub const SYS_setfsuid: ::c_long = 151; +pub const SYS_setfsgid: ::c_long = 152; +pub const SYS_times: ::c_long = 153; +pub const SYS_setpgid: ::c_long = 154; +pub const SYS_getpgid: ::c_long = 155; +pub const SYS_getsid: ::c_long = 156; +pub const SYS_setsid: ::c_long = 157; +pub const SYS_getgroups: ::c_long = 158; +pub const SYS_setgroups: ::c_long = 159; +pub const SYS_uname: ::c_long = 160; +pub const SYS_sethostname: ::c_long = 161; +pub const SYS_setdomainname: ::c_long = 162; +pub const SYS_getrlimit: ::c_long = 163; +pub const SYS_setrlimit: ::c_long = 164; +pub const SYS_getrusage: ::c_long = 165; +pub const SYS_umask: ::c_long = 166; +pub const SYS_prctl: ::c_long = 167; +pub const SYS_getcpu: ::c_long = 168; +pub const SYS_gettimeofday: ::c_long = 169; +pub const SYS_settimeofday: ::c_long = 170; +pub const SYS_adjtimex: ::c_long = 171; +pub const SYS_getpid: ::c_long = 172; +pub const SYS_getppid: ::c_long = 173; +pub const SYS_getuid: ::c_long = 174; +pub const SYS_geteuid: ::c_long = 175; +pub const SYS_getgid: ::c_long = 176; +pub const SYS_getegid: ::c_long = 177; +pub const SYS_gettid: ::c_long = 178; +pub const SYS_sysinfo: ::c_long = 179; +pub const SYS_mq_open: ::c_long = 180; +pub const SYS_mq_unlink: ::c_long = 181; +pub const SYS_mq_timedsend: ::c_long = 182; +pub const SYS_mq_timedreceive: ::c_long = 183; +pub const SYS_mq_notify: ::c_long = 184; +pub const SYS_mq_getsetattr: ::c_long = 185; +pub const SYS_msgget: ::c_long = 186; +pub const SYS_msgctl: ::c_long = 187; +pub const SYS_msgrcv: ::c_long = 188; +pub const SYS_msgsnd: ::c_long = 189; +pub const SYS_semget: ::c_long = 190; +pub const SYS_semctl: ::c_long = 191; +pub const SYS_semtimedop: ::c_long = 192; +pub const SYS_semop: ::c_long = 193; +pub const SYS_shmget: ::c_long = 194; +pub const SYS_shmctl: ::c_long = 195; +pub const SYS_shmat: ::c_long = 196; +pub const SYS_shmdt: ::c_long = 197; +pub const SYS_socket: ::c_long = 198; +pub const SYS_socketpair: ::c_long = 199; +pub const SYS_bind: ::c_long = 200; +pub const SYS_listen: ::c_long = 201; +pub const SYS_accept: ::c_long = 202; +pub const SYS_connect: ::c_long = 203; +pub const SYS_getsockname: ::c_long = 204; +pub const SYS_getpeername: ::c_long = 205; +pub const SYS_sendto: ::c_long = 206; +pub const SYS_recvfrom: ::c_long = 207; +pub const SYS_setsockopt: ::c_long = 208; +pub const SYS_getsockopt: ::c_long = 209; +pub const SYS_shutdown: ::c_long = 210; +pub const SYS_sendmsg: ::c_long = 211; +pub const SYS_recvmsg: ::c_long = 212; +pub const SYS_readahead: ::c_long = 213; +pub const SYS_brk: ::c_long = 214; +pub const SYS_munmap: ::c_long = 215; +pub const SYS_mremap: ::c_long = 216; +pub const SYS_add_key: ::c_long = 217; +pub const SYS_request_key: ::c_long = 218; +pub const SYS_keyctl: ::c_long = 219; +pub const SYS_clone: ::c_long = 220; +pub const SYS_execve: ::c_long = 221; +pub const SYS_swapon: ::c_long = 224; +pub const SYS_swapoff: ::c_long = 225; +pub const SYS_mprotect: ::c_long = 226; +pub const SYS_msync: ::c_long = 227; +pub const SYS_mlock: ::c_long = 228; +pub const SYS_munlock: ::c_long = 229; +pub const SYS_mlockall: ::c_long = 230; +pub const SYS_munlockall: ::c_long = 231; +pub const SYS_mincore: ::c_long = 232; +pub const SYS_madvise: ::c_long = 233; +pub const SYS_remap_file_pages: ::c_long = 234; +pub const SYS_mbind: ::c_long = 235; +pub const SYS_get_mempolicy: ::c_long = 236; +pub const SYS_set_mempolicy: ::c_long = 237; +pub const SYS_migrate_pages: ::c_long = 238; +pub const SYS_move_pages: ::c_long = 239; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 240; +pub const SYS_perf_event_open: ::c_long = 241; +pub const SYS_accept4: ::c_long = 242; +pub const SYS_recvmmsg: ::c_long = 243; +pub const SYS_wait4: ::c_long = 260; +pub const SYS_prlimit64: ::c_long = 261; +pub const SYS_fanotify_init: ::c_long = 262; +pub const SYS_fanotify_mark: ::c_long = 263; +pub const SYS_name_to_handle_at: ::c_long = 264; +pub const SYS_open_by_handle_at: ::c_long = 265; +pub const SYS_clock_adjtime: ::c_long = 266; +pub const SYS_syncfs: ::c_long = 267; +pub const SYS_setns: ::c_long = 268; +pub const SYS_sendmmsg: ::c_long = 269; +pub const SYS_process_vm_readv: ::c_long = 270; +pub const SYS_process_vm_writev: ::c_long = 271; +pub const SYS_kcmp: ::c_long = 272; +pub const SYS_finit_module: ::c_long = 273; +pub const SYS_sched_setattr: ::c_long = 274; +pub const SYS_sched_getattr: ::c_long = 275; +pub const SYS_renameat2: ::c_long = 276; +pub const SYS_seccomp: ::c_long = 277; +pub const SYS_getrandom: ::c_long = 278; +pub const SYS_memfd_create: ::c_long = 279; +pub const SYS_bpf: ::c_long = 280; +pub const SYS_execveat: ::c_long = 281; +pub const SYS_userfaultfd: ::c_long = 282; +pub const SYS_membarrier: ::c_long = 283; +pub const SYS_mlock2: ::c_long = 284; +pub const SYS_copy_file_range: ::c_long = 285; +pub const SYS_preadv2: ::c_long = 286; +pub const SYS_pwritev2: ::c_long = 287; +pub const SYS_pkey_mprotect: ::c_long = 288; +pub const SYS_pkey_alloc: ::c_long = 289; +pub const SYS_pkey_free: ::c_long = 290; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,392 @@ +pub type c_long = i64; +pub type c_ulong = u64; + +s! { + pub struct statfs64 { + pub f_type: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_flags: ::c_ulong, + pub f_spare: [::c_ulong; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_flags: ::c_int, + pub ss_size: ::size_t + } + + pub struct pthread_attr_t { + __size: [u64; 7] + } + + pub struct sigset_t { + __val: [::c_ulong; 16], + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::c_ulong, + __pad1: ::c_ulong, + __pad2: ::c_ulong, + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_stime: ::time_t, + pub msg_rtime: ::time_t, + pub msg_ctime: ::time_t, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __pad1: ::c_ulong, + __pad2: ::c_ulong, + } + + pub struct statfs { + pub f_type: ::c_ulong, + pub f_bsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_flags: ::c_ulong, + pub f_spare: [::c_ulong; 4], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::c_int, + __pad1: ::c_int, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::socklen_t, + __pad2: ::socklen_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::socklen_t, + pub __pad1: ::c_int, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct sem_t { + __val: [::c_int; 8], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_errno: ::c_int, + pub si_code: ::c_int, + pub _pad: [::c_int; 29], + _align: [usize; 0], + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 19], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } +} + +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; + +pub const O_ASYNC: ::c_int = 0x2000; + +pub const FIOCLEX: ::c_int = 0x5451; +pub const FIONBIO: ::c_int = 0x5421; + +pub const RLIMIT_RSS: ::c_int = 5; +pub const RLIMIT_NOFILE: ::c_int = 7; +pub const RLIMIT_AS: ::c_int = 9; +pub const RLIMIT_NPROC: ::c_int = 6; +pub const RLIMIT_MEMLOCK: ::c_int = 8; + +pub const O_APPEND: ::c_int = 1024; +pub const O_CREAT: ::c_int = 64; +pub const O_EXCL: ::c_int = 128; +pub const O_NOCTTY: ::c_int = 256; +pub const O_NONBLOCK: ::c_int = 2048; +pub const O_SYNC: ::c_int = 1052672; +pub const O_RSYNC: ::c_int = 1052672; +pub const O_DSYNC: ::c_int = 4096; + +pub const SOCK_NONBLOCK: ::c_int = 2048; + +pub const MAP_ANON: ::c_int = 0x0020; +pub const MAP_GROWSDOWN: ::c_int = 0x0100; +pub const MAP_DENYWRITE: ::c_int = 0x0800; +pub const MAP_EXECUTABLE: ::c_int = 0x01000; +pub const MAP_LOCKED: ::c_int = 0x02000; +pub const MAP_NORESERVE: ::c_int = 0x04000; +pub const MAP_POPULATE: ::c_int = 0x08000; +pub const MAP_NONBLOCK: ::c_int = 0x010000; +pub const MAP_STACK: ::c_int = 0x020000; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_SEQPACKET: ::c_int = 5; + +pub const SOL_SOCKET: ::c_int = 1; + +pub const EDEADLK: ::c_int = 35; +pub const ENAMETOOLONG: ::c_int = 36; +pub const ENOLCK: ::c_int = 37; +pub const ENOSYS: ::c_int = 38; +pub const ENOTEMPTY: ::c_int = 39; +pub const ELOOP: ::c_int = 40; +pub const ENOMSG: ::c_int = 42; +pub const EIDRM: ::c_int = 43; +pub const ECHRNG: ::c_int = 44; +pub const EL2NSYNC: ::c_int = 45; +pub const EL3HLT: ::c_int = 46; +pub const EL3RST: ::c_int = 47; +pub const ELNRNG: ::c_int = 48; +pub const EUNATCH: ::c_int = 49; +pub const ENOCSI: ::c_int = 50; +pub const EL2HLT: ::c_int = 51; +pub const EBADE: ::c_int = 52; +pub const EBADR: ::c_int = 53; +pub const EXFULL: ::c_int = 54; +pub const ENOANO: ::c_int = 55; +pub const EBADRQC: ::c_int = 56; +pub const EBADSLT: ::c_int = 57; +pub const EDEADLOCK: ::c_int = EDEADLK; +pub const EMULTIHOP: ::c_int = 72; +pub const EBADMSG: ::c_int = 74; +pub const EOVERFLOW: ::c_int = 75; +pub const ENOTUNIQ: ::c_int = 76; +pub const EBADFD: ::c_int = 77; +pub const EREMCHG: ::c_int = 78; +pub const ELIBACC: ::c_int = 79; +pub const ELIBBAD: ::c_int = 80; +pub const ELIBSCN: ::c_int = 81; +pub const ELIBMAX: ::c_int = 82; +pub const ELIBEXEC: ::c_int = 83; +pub const EILSEQ: ::c_int = 84; +pub const ERESTART: ::c_int = 85; +pub const ESTRPIPE: ::c_int = 86; +pub const EUSERS: ::c_int = 87; +pub const ENOTSOCK: ::c_int = 88; +pub const EDESTADDRREQ: ::c_int = 89; +pub const EMSGSIZE: ::c_int = 90; +pub const EPROTOTYPE: ::c_int = 91; +pub const ENOPROTOOPT: ::c_int = 92; +pub const EPROTONOSUPPORT: ::c_int = 93; +pub const ESOCKTNOSUPPORT: ::c_int = 94; +pub const EOPNOTSUPP: ::c_int = 95; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; +pub const EPFNOSUPPORT: ::c_int = 96; +pub const EAFNOSUPPORT: ::c_int = 97; +pub const EADDRINUSE: ::c_int = 98; +pub const EADDRNOTAVAIL: ::c_int = 99; +pub const ENETDOWN: ::c_int = 100; +pub const ENETUNREACH: ::c_int = 101; +pub const ENETRESET: ::c_int = 102; +pub const ECONNABORTED: ::c_int = 103; +pub const ECONNRESET: ::c_int = 104; +pub const ENOBUFS: ::c_int = 105; +pub const EISCONN: ::c_int = 106; +pub const ENOTCONN: ::c_int = 107; +pub const ESHUTDOWN: ::c_int = 108; +pub const ETOOMANYREFS: ::c_int = 109; +pub const ETIMEDOUT: ::c_int = 110; +pub const ECONNREFUSED: ::c_int = 111; +pub const EHOSTDOWN: ::c_int = 112; +pub const EHOSTUNREACH: ::c_int = 113; +pub const EALREADY: ::c_int = 114; +pub const EINPROGRESS: ::c_int = 115; +pub const ESTALE: ::c_int = 116; +pub const EUCLEAN: ::c_int = 117; +pub const ENOTNAM: ::c_int = 118; +pub const ENAVAIL: ::c_int = 119; +pub const EISNAM: ::c_int = 120; +pub const EREMOTEIO: ::c_int = 121; +pub const EDQUOT: ::c_int = 122; +pub const ENOMEDIUM: ::c_int = 123; +pub const EMEDIUMTYPE: ::c_int = 124; +pub const ECANCELED: ::c_int = 125; +pub const ENOKEY: ::c_int = 126; +pub const EKEYEXPIRED: ::c_int = 127; +pub const EKEYREVOKED: ::c_int = 128; +pub const EKEYREJECTED: ::c_int = 129; +pub const EOWNERDEAD: ::c_int = 130; +pub const ENOTRECOVERABLE: ::c_int = 131; +pub const ERFKILL: ::c_int = 132; +pub const EHWPOISON: ::c_int = 133; + +pub const SO_REUSEADDR: ::c_int = 2; +pub const SO_TYPE: ::c_int = 3; +pub const SO_ERROR: ::c_int = 4; +pub const SO_DONTROUTE: ::c_int = 5; +pub const SO_BROADCAST: ::c_int = 6; +pub const SO_SNDBUF: ::c_int = 7; +pub const SO_RCVBUF: ::c_int = 8; +pub const SO_KEEPALIVE: ::c_int = 9; +pub const SO_OOBINLINE: ::c_int = 10; +pub const SO_NO_CHECK: ::c_int = 11; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_LINGER: ::c_int = 13; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_REUSEPORT: ::c_int = 15; +pub const SO_PASSCRED: ::c_int = 16; +pub const SO_PEERCRED: ::c_int = 17; +pub const SO_RCVLOWAT: ::c_int = 18; +pub const SO_SNDLOWAT: ::c_int = 19; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_SNDTIMEO: ::c_int = 21; +pub const SO_ACCEPTCONN: ::c_int = 30; +pub const SO_SNDBUFFORCE: ::c_int = 32; +pub const SO_RCVBUFFORCE: ::c_int = 33; +pub const SO_PROTOCOL: ::c_int = 38; +pub const SO_DOMAIN: ::c_int = 39; + +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 0x00000004; +pub const SA_NOCLDWAIT: ::c_int = 0x00000002; + +pub const SIGCHLD: ::c_int = 17; +pub const SIGBUS: ::c_int = 7; +pub const SIGTTIN: ::c_int = 21; +pub const SIGTTOU: ::c_int = 22; +pub const SIGXCPU: ::c_int = 24; +pub const SIGXFSZ: ::c_int = 25; +pub const SIGVTALRM: ::c_int = 26; +pub const SIGPROF: ::c_int = 27; +pub const SIGWINCH: ::c_int = 28; +pub const SIGUSR1: ::c_int = 10; +pub const SIGUSR2: ::c_int = 12; +pub const SIGCONT: ::c_int = 18; +pub const SIGSTOP: ::c_int = 19; +pub const SIGTSTP: ::c_int = 20; +pub const SIGURG: ::c_int = 23; +pub const SIGIO: ::c_int = 29; +pub const SIGSYS: ::c_int = 31; +pub const SIGSTKFLT: ::c_int = 16; +pub const SIGPOLL: ::c_int = 29; +pub const SIGPWR: ::c_int = 30; +pub const SIG_SETMASK: ::c_int = 2; +pub const SIG_BLOCK: ::c_int = 0x000000; +pub const SIG_UNBLOCK: ::c_int = 0x01; + +pub const EXTPROC: ::tcflag_t = 0x00010000; + +pub const MAP_HUGETLB: ::c_int = 0x040000; + +pub const F_GETLK: ::c_int = 5; +pub const F_GETOWN: ::c_int = 9; +pub const F_SETLK: ::c_int = 6; +pub const F_SETLKW: ::c_int = 7; +pub const F_SETOWN: ::c_int = 8; + +pub const VEOF: usize = 4; +pub const VEOL: usize = 11; +pub const VEOL2: usize = 16; +pub const VMIN: usize = 6; +pub const IEXTEN: ::tcflag_t = 0x00008000; +pub const TOSTOP: ::tcflag_t = 0x00000100; +pub const FLUSHO: ::tcflag_t = 0x00001000; + +pub const TCGETS: ::c_int = 0x5401; +pub const TCSETS: ::c_int = 0x5402; +pub const TCSETSW: ::c_int = 0x5403; +pub const TCSETSF: ::c_int = 0x5404; +pub const TCGETA: ::c_int = 0x5405; +pub const TCSETA: ::c_int = 0x5406; +pub const TCSETAW: ::c_int = 0x5407; +pub const TCSETAF: ::c_int = 0x5408; +pub const TCSBRK: ::c_int = 0x5409; +pub const TCXONC: ::c_int = 0x540A; +pub const TCFLSH: ::c_int = 0x540B; +pub const TIOCGSOFTCAR: ::c_int = 0x5419; +pub const TIOCSSOFTCAR: ::c_int = 0x541A; +pub const TIOCLINUX: ::c_int = 0x541C; +pub const TIOCGSERIAL: ::c_int = 0x541E; +pub const TIOCEXCL: ::c_int = 0x540C; +pub const TIOCNXCL: ::c_int = 0x540D; +pub const TIOCSCTTY: ::c_int = 0x540E; +pub const TIOCGPGRP: ::c_int = 0x540F; +pub const TIOCSPGRP: ::c_int = 0x5410; +pub const TIOCOUTQ: ::c_int = 0x5411; +pub const TIOCSTI: ::c_int = 0x5412; +pub const TIOCGWINSZ: ::c_int = 0x5413; +pub const TIOCSWINSZ: ::c_int = 0x5414; +pub const TIOCMGET: ::c_int = 0x5415; +pub const TIOCMBIS: ::c_int = 0x5416; +pub const TIOCMBIC: ::c_int = 0x5417; +pub const TIOCMSET: ::c_int = 0x5418; +pub const FIONREAD: ::c_int = 0x541B; +pub const TIOCCONS: ::c_int = 0x541D; + +pub const POLLWRNORM: ::c_short = 0x100; +pub const POLLWRBAND: ::c_short = 0x200; + +pub const TIOCM_LE: ::c_int = 0x001; +pub const TIOCM_DTR: ::c_int = 0x002; +pub const TIOCM_RTS: ::c_int = 0x004; +pub const TIOCM_ST: ::c_int = 0x008; +pub const TIOCM_SR: ::c_int = 0x010; +pub const TIOCM_CTS: ::c_int = 0x020; +pub const TIOCM_CAR: ::c_int = 0x040; +pub const TIOCM_RNG: ::c_int = 0x080; +pub const TIOCM_DSR: ::c_int = 0x100; +pub const TIOCM_CD: ::c_int = TIOCM_CAR; +pub const TIOCM_RI: ::c_int = TIOCM_RNG; + +cfg_if! { + if #[cfg(target_arch = "aarch64")] { + mod aarch64; + pub use self::aarch64::*; + } else if #[cfg(any(target_arch = "powerpc64"))] { + mod powerpc64; + pub use self::powerpc64::*; + } else if #[cfg(any(target_arch = "x86_64"))] { + mod x86_64; + pub use self::x86_64::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/powerpc64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/powerpc64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/powerpc64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/powerpc64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,441 @@ +pub type c_char = u8; +pub type wchar_t = i32; +pub type __u64 = ::c_ulong; +pub type nlink_t = u64; +pub type blksize_t = ::c_long; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + __pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused: [::c_long; 3], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino64_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + __pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __reserved: [::c_long; 3], + } + + pub struct ipc_perm { + pub __ipc_perm_key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + pub __seq: ::c_int, + __unused1: ::c_long, + __unused2: ::c_long + } +} + +pub const SYS_pivot_root: ::c_long = 203; +pub const SYS_gettid: ::c_long = 207; +pub const SYS_perf_event_open: ::c_long = 319; +pub const SYS_memfd_create: ::c_long = 360; + +pub const MAP_32BIT: ::c_int = 0x0040; +pub const O_DIRECT: ::c_int = 0x4000; +pub const O_DIRECTORY: ::c_int = 0x10000; +pub const O_LARGEFILE: ::c_int = 0; +pub const O_NOFOLLOW: ::c_int = 0x20000; + +pub const SIGSTKSZ: ::size_t = 8192; +pub const MINSIGSTKSZ: ::size_t = 2048; + +#[doc(hidden)] +pub const AF_MAX: ::c_int = 42; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; + +// Syscall table +pub const SYS_restart_syscall: ::c_long = 0; +pub const SYS_exit: ::c_long = 1; +pub const SYS_fork: ::c_long = 2; +pub const SYS_read: ::c_long = 3; +pub const SYS_write: ::c_long = 4; +pub const SYS_open: ::c_long = 5; +pub const SYS_close: ::c_long = 6; +pub const SYS_waitpid: ::c_long = 7; +pub const SYS_creat: ::c_long = 8; +pub const SYS_link: ::c_long = 9; +pub const SYS_unlink: ::c_long = 10; +pub const SYS_execve: ::c_long = 11; +pub const SYS_chdir: ::c_long = 12; +pub const SYS_time: ::c_long = 13; +pub const SYS_mknod: ::c_long = 14; +pub const SYS_chmod: ::c_long = 15; +pub const SYS_lchown: ::c_long = 16; +pub const SYS_break: ::c_long = 17; +pub const SYS_oldstat: ::c_long = 18; +pub const SYS_lseek: ::c_long = 19; +pub const SYS_getpid: ::c_long = 20; +pub const SYS_mount: ::c_long = 21; +pub const SYS_umount: ::c_long = 22; +pub const SYS_setuid: ::c_long = 23; +pub const SYS_getuid: ::c_long = 24; +pub const SYS_stime: ::c_long = 25; +pub const SYS_ptrace: ::c_long = 26; +pub const SYS_alarm: ::c_long = 27; +pub const SYS_oldfstat: ::c_long = 28; +pub const SYS_pause: ::c_long = 29; +pub const SYS_utime: ::c_long = 30; +pub const SYS_stty: ::c_long = 31; +pub const SYS_gtty: ::c_long = 32; +pub const SYS_access: ::c_long = 33; +pub const SYS_nice: ::c_long = 34; +pub const SYS_ftime: ::c_long = 35; +pub const SYS_sync: ::c_long = 36; +pub const SYS_kill: ::c_long = 37; +pub const SYS_rename: ::c_long = 38; +pub const SYS_mkdir: ::c_long = 39; +pub const SYS_rmdir: ::c_long = 40; +pub const SYS_dup: ::c_long = 41; +pub const SYS_pipe: ::c_long = 42; +pub const SYS_times: ::c_long = 43; +pub const SYS_prof: ::c_long = 44; +pub const SYS_brk: ::c_long = 45; +pub const SYS_setgid: ::c_long = 46; +pub const SYS_getgid: ::c_long = 47; +pub const SYS_signal: ::c_long = 48; +pub const SYS_geteuid: ::c_long = 49; +pub const SYS_getegid: ::c_long = 50; +pub const SYS_acct: ::c_long = 51; +pub const SYS_umount2: ::c_long = 52; +pub const SYS_lock: ::c_long = 53; +pub const SYS_ioctl: ::c_long = 54; +pub const SYS_fcntl: ::c_long = 55; +pub const SYS_mpx: ::c_long = 56; +pub const SYS_setpgid: ::c_long = 57; +pub const SYS_ulimit: ::c_long = 58; +pub const SYS_oldolduname: ::c_long = 59; +pub const SYS_umask: ::c_long = 60; +pub const SYS_chroot: ::c_long = 61; +pub const SYS_ustat: ::c_long = 62; +pub const SYS_dup2: ::c_long = 63; +pub const SYS_getppid: ::c_long = 64; +pub const SYS_getpgrp: ::c_long = 65; +pub const SYS_setsid: ::c_long = 66; +pub const SYS_sigaction: ::c_long = 67; +pub const SYS_sgetmask: ::c_long = 68; +pub const SYS_ssetmask: ::c_long = 69; +pub const SYS_setreuid: ::c_long = 70; +pub const SYS_setregid: ::c_long = 71; +pub const SYS_sigsuspend: ::c_long = 72; +pub const SYS_sigpending: ::c_long = 73; +pub const SYS_sethostname: ::c_long = 74; +pub const SYS_setrlimit: ::c_long = 75; +pub const SYS_getrlimit: ::c_long = 76; +pub const SYS_getrusage: ::c_long = 77; +pub const SYS_gettimeofday: ::c_long = 78; +pub const SYS_settimeofday: ::c_long = 79; +pub const SYS_getgroups: ::c_long = 80; +pub const SYS_setgroups: ::c_long = 81; +pub const SYS_select: ::c_long = 82; +pub const SYS_symlink: ::c_long = 83; +pub const SYS_oldlstat: ::c_long = 84; +pub const SYS_readlink: ::c_long = 85; +pub const SYS_uselib: ::c_long = 86; +pub const SYS_swapon: ::c_long = 87; +pub const SYS_reboot: ::c_long = 88; +pub const SYS_readdir: ::c_long = 89; +pub const SYS_mmap: ::c_long = 90; +pub const SYS_munmap: ::c_long = 91; +pub const SYS_truncate: ::c_long = 92; +pub const SYS_ftruncate: ::c_long = 93; +pub const SYS_fchmod: ::c_long = 94; +pub const SYS_fchown: ::c_long = 95; +pub const SYS_getpriority: ::c_long = 96; +pub const SYS_setpriority: ::c_long = 97; +pub const SYS_profil: ::c_long = 98; +pub const SYS_statfs: ::c_long = 99; +pub const SYS_fstatfs: ::c_long = 100; +pub const SYS_ioperm: ::c_long = 101; +pub const SYS_socketcall: ::c_long = 102; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_setitimer: ::c_long = 104; +pub const SYS_getitimer: ::c_long = 105; +pub const SYS_stat: ::c_long = 106; +pub const SYS_lstat: ::c_long = 107; +pub const SYS_fstat: ::c_long = 108; +pub const SYS_olduname: ::c_long = 109; +pub const SYS_iopl: ::c_long = 110; +pub const SYS_vhangup: ::c_long = 111; +pub const SYS_idle: ::c_long = 112; +pub const SYS_vm86: ::c_long = 113; +pub const SYS_wait4: ::c_long = 114; +pub const SYS_swapoff: ::c_long = 115; +pub const SYS_sysinfo: ::c_long = 116; +pub const SYS_ipc: ::c_long = 117; +pub const SYS_fsync: ::c_long = 118; +pub const SYS_sigreturn: ::c_long = 119; +pub const SYS_clone: ::c_long = 120; +pub const SYS_setdomainname: ::c_long = 121; +pub const SYS_uname: ::c_long = 122; +pub const SYS_modify_ldt: ::c_long = 123; +pub const SYS_adjtimex: ::c_long = 124; +pub const SYS_mprotect: ::c_long = 125; +pub const SYS_sigprocmask: ::c_long = 126; +pub const SYS_create_module: ::c_long = 127; +pub const SYS_init_module: ::c_long = 128; +pub const SYS_delete_module: ::c_long = 129; +pub const SYS_get_kernel_syms: ::c_long = 130; +pub const SYS_quotactl: ::c_long = 131; +pub const SYS_getpgid: ::c_long = 132; +pub const SYS_fchdir: ::c_long = 133; +pub const SYS_bdflush: ::c_long = 134; +pub const SYS_sysfs: ::c_long = 135; +pub const SYS_personality: ::c_long = 136; +pub const SYS_afs_syscall: ::c_long = 137; /* Syscall for Andrew File System */ +pub const SYS_setfsuid: ::c_long = 138; +pub const SYS_setfsgid: ::c_long = 139; +pub const SYS__llseek: ::c_long = 140; +pub const SYS_getdents: ::c_long = 141; +pub const SYS__newselect: ::c_long = 142; +pub const SYS_flock: ::c_long = 143; +pub const SYS_msync: ::c_long = 144; +pub const SYS_readv: ::c_long = 145; +pub const SYS_writev: ::c_long = 146; +pub const SYS_getsid: ::c_long = 147; +pub const SYS_fdatasync: ::c_long = 148; +pub const SYS__sysctl: ::c_long = 149; +pub const SYS_mlock: ::c_long = 150; +pub const SYS_munlock: ::c_long = 151; +pub const SYS_mlockall: ::c_long = 152; +pub const SYS_munlockall: ::c_long = 153; +pub const SYS_sched_setparam: ::c_long = 154; +pub const SYS_sched_getparam: ::c_long = 155; +pub const SYS_sched_setscheduler: ::c_long = 156; +pub const SYS_sched_getscheduler: ::c_long = 157; +pub const SYS_sched_yield: ::c_long = 158; +pub const SYS_sched_get_priority_max: ::c_long = 159; +pub const SYS_sched_get_priority_min: ::c_long = 160; +pub const SYS_sched_rr_get_interval: ::c_long = 161; +pub const SYS_nanosleep: ::c_long = 162; +pub const SYS_mremap: ::c_long = 163; +pub const SYS_setresuid: ::c_long = 164; +pub const SYS_getresuid: ::c_long = 165; +pub const SYS_query_module: ::c_long = 166; +pub const SYS_poll: ::c_long = 167; +pub const SYS_nfsservctl: ::c_long = 168; +pub const SYS_setresgid: ::c_long = 169; +pub const SYS_getresgid: ::c_long = 170; +pub const SYS_prctl: ::c_long = 171; +pub const SYS_rt_sigreturn: ::c_long = 172; +pub const SYS_rt_sigaction: ::c_long = 173; +pub const SYS_rt_sigprocmask: ::c_long = 174; +pub const SYS_rt_sigpending: ::c_long = 175; +pub const SYS_rt_sigtimedwait: ::c_long = 176; +pub const SYS_rt_sigqueueinfo: ::c_long = 177; +pub const SYS_rt_sigsuspend: ::c_long = 178; +pub const SYS_pread64: ::c_long = 179; +pub const SYS_pwrite64: ::c_long = 180; +pub const SYS_chown: ::c_long = 181; +pub const SYS_getcwd: ::c_long = 182; +pub const SYS_capget: ::c_long = 183; +pub const SYS_capset: ::c_long = 184; +pub const SYS_sigaltstack: ::c_long = 185; +pub const SYS_sendfile: ::c_long = 186; +pub const SYS_getpmsg: ::c_long = 187; /* some people actually want streams */ +pub const SYS_putpmsg: ::c_long = 188; /* some people actually want streams */ +pub const SYS_vfork: ::c_long = 189; +pub const SYS_ugetrlimit: ::c_long = 190; /* SuS compliant getrlimit */ +pub const SYS_readahead: ::c_long = 191; +pub const SYS_pciconfig_read: ::c_long = 198; +pub const SYS_pciconfig_write: ::c_long = 199; +pub const SYS_pciconfig_iobase: ::c_long = 200; +pub const SYS_multiplexer: ::c_long = 201; +pub const SYS_getdents64: ::c_long = 202; +pub const SYS_pivot_root: ::c_long = 203; +pub const SYS_madvise: ::c_long = 205; +pub const SYS_mincore: ::c_long = 206; +pub const SYS_gettid: ::c_long = 207; +pub const SYS_tkill: ::c_long = 208; +pub const SYS_setxattr: ::c_long = 209; +pub const SYS_lsetxattr: ::c_long = 210; +pub const SYS_fsetxattr: ::c_long = 211; +pub const SYS_getxattr: ::c_long = 212; +pub const SYS_lgetxattr: ::c_long = 213; +pub const SYS_fgetxattr: ::c_long = 214; +pub const SYS_listxattr: ::c_long = 215; +pub const SYS_llistxattr: ::c_long = 216; +pub const SYS_flistxattr: ::c_long = 217; +pub const SYS_removexattr: ::c_long = 218; +pub const SYS_lremovexattr: ::c_long = 219; +pub const SYS_fremovexattr: ::c_long = 220; +pub const SYS_futex: ::c_long = 221; +pub const SYS_sched_setaffinity: ::c_long = 222; +pub const SYS_sched_getaffinity: ::c_long = 223; +pub const SYS_tuxcall: ::c_long = 225; +pub const SYS_io_setup: ::c_long = 227; +pub const SYS_io_destroy: ::c_long = 228; +pub const SYS_io_getevents: ::c_long = 229; +pub const SYS_io_submit: ::c_long = 230; +pub const SYS_io_cancel: ::c_long = 231; +pub const SYS_set_tid_address: ::c_long = 232; +pub const SYS_exit_group: ::c_long = 234; +pub const SYS_lookup_dcookie: ::c_long = 235; +pub const SYS_epoll_create: ::c_long = 236; +pub const SYS_epoll_ctl: ::c_long = 237; +pub const SYS_epoll_wait: ::c_long = 238; +pub const SYS_remap_file_pages: ::c_long = 239; +pub const SYS_timer_create: ::c_long = 240; +pub const SYS_timer_settime: ::c_long = 241; +pub const SYS_timer_gettime: ::c_long = 242; +pub const SYS_timer_getoverrun: ::c_long = 243; +pub const SYS_timer_delete: ::c_long = 244; +pub const SYS_clock_settime: ::c_long = 245; +pub const SYS_clock_gettime: ::c_long = 246; +pub const SYS_clock_getres: ::c_long = 247; +pub const SYS_clock_nanosleep: ::c_long = 248; +pub const SYS_swapcontext: ::c_long = 249; +pub const SYS_tgkill: ::c_long = 250; +pub const SYS_utimes: ::c_long = 251; +pub const SYS_statfs64: ::c_long = 252; +pub const SYS_fstatfs64: ::c_long = 253; +pub const SYS_rtas: ::c_long = 255; +pub const SYS_sys_debug_setcontext: ::c_long = 256; +pub const SYS_migrate_pages: ::c_long = 258; +pub const SYS_mbind: ::c_long = 259; +pub const SYS_get_mempolicy: ::c_long = 260; +pub const SYS_set_mempolicy: ::c_long = 261; +pub const SYS_mq_open: ::c_long = 262; +pub const SYS_mq_unlink: ::c_long = 263; +pub const SYS_mq_timedsend: ::c_long = 264; +pub const SYS_mq_timedreceive: ::c_long = 265; +pub const SYS_mq_notify: ::c_long = 266; +pub const SYS_mq_getsetattr: ::c_long = 267; +pub const SYS_kexec_load: ::c_long = 268; +pub const SYS_add_key: ::c_long = 269; +pub const SYS_request_key: ::c_long = 270; +pub const SYS_keyctl: ::c_long = 271; +pub const SYS_waitid: ::c_long = 272; +pub const SYS_ioprio_set: ::c_long = 273; +pub const SYS_ioprio_get: ::c_long = 274; +pub const SYS_inotify_init: ::c_long = 275; +pub const SYS_inotify_add_watch: ::c_long = 276; +pub const SYS_inotify_rm_watch: ::c_long = 277; +pub const SYS_spu_run: ::c_long = 278; +pub const SYS_spu_create: ::c_long = 279; +pub const SYS_pselect6: ::c_long = 280; +pub const SYS_ppoll: ::c_long = 281; +pub const SYS_unshare: ::c_long = 282; +pub const SYS_splice: ::c_long = 283; +pub const SYS_tee: ::c_long = 284; +pub const SYS_vmsplice: ::c_long = 285; +pub const SYS_openat: ::c_long = 286; +pub const SYS_mkdirat: ::c_long = 287; +pub const SYS_mknodat: ::c_long = 288; +pub const SYS_fchownat: ::c_long = 289; +pub const SYS_futimesat: ::c_long = 290; +pub const SYS_newfstatat: ::c_long = 291; +pub const SYS_unlinkat: ::c_long = 292; +pub const SYS_renameat: ::c_long = 293; +pub const SYS_linkat: ::c_long = 294; +pub const SYS_symlinkat: ::c_long = 295; +pub const SYS_readlinkat: ::c_long = 296; +pub const SYS_fchmodat: ::c_long = 297; +pub const SYS_faccessat: ::c_long = 298; +pub const SYS_get_robust_list: ::c_long = 299; +pub const SYS_set_robust_list: ::c_long = 300; +pub const SYS_move_pages: ::c_long = 301; +pub const SYS_getcpu: ::c_long = 302; +pub const SYS_epoll_pwait: ::c_long = 303; +pub const SYS_utimensat: ::c_long = 304; +pub const SYS_signalfd: ::c_long = 305; +pub const SYS_timerfd_create: ::c_long = 306; +pub const SYS_eventfd: ::c_long = 307; +pub const SYS_sync_file_range2: ::c_long = 308; +pub const SYS_fallocate: ::c_long = 309; +pub const SYS_subpage_prot: ::c_long = 310; +pub const SYS_timerfd_settime: ::c_long = 311; +pub const SYS_timerfd_gettime: ::c_long = 312; +pub const SYS_signalfd4: ::c_long = 313; +pub const SYS_eventfd2: ::c_long = 314; +pub const SYS_epoll_create1: ::c_long = 315; +pub const SYS_dup3: ::c_long = 316; +pub const SYS_pipe2: ::c_long = 317; +pub const SYS_inotify_init1: ::c_long = 318; +pub const SYS_perf_event_open: ::c_long = 319; +pub const SYS_preadv: ::c_long = 320; +pub const SYS_pwritev: ::c_long = 321; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 322; +pub const SYS_fanotify_init: ::c_long = 323; +pub const SYS_fanotify_mark: ::c_long = 324; +pub const SYS_prlimit64: ::c_long = 325; +pub const SYS_socket: ::c_long = 326; +pub const SYS_bind: ::c_long = 327; +pub const SYS_connect: ::c_long = 328; +pub const SYS_listen: ::c_long = 329; +pub const SYS_accept: ::c_long = 330; +pub const SYS_getsockname: ::c_long = 331; +pub const SYS_getpeername: ::c_long = 332; +pub const SYS_socketpair: ::c_long = 333; +pub const SYS_send: ::c_long = 334; +pub const SYS_sendto: ::c_long = 335; +pub const SYS_recv: ::c_long = 336; +pub const SYS_recvfrom: ::c_long = 337; +pub const SYS_shutdown: ::c_long = 338; +pub const SYS_setsockopt: ::c_long = 339; +pub const SYS_getsockopt: ::c_long = 340; +pub const SYS_sendmsg: ::c_long = 341; +pub const SYS_recvmsg: ::c_long = 342; +pub const SYS_recvmmsg: ::c_long = 343; +pub const SYS_accept4: ::c_long = 344; +pub const SYS_name_to_handle_at: ::c_long = 345; +pub const SYS_open_by_handle_at: ::c_long = 346; +pub const SYS_clock_adjtime: ::c_long = 347; +pub const SYS_syncfs: ::c_long = 348; +pub const SYS_sendmmsg: ::c_long = 349; +pub const SYS_setns: ::c_long = 350; +pub const SYS_process_vm_readv: ::c_long = 351; +pub const SYS_process_vm_writev: ::c_long = 352; +pub const SYS_finit_module: ::c_long = 353; +pub const SYS_kcmp: ::c_long = 354; +pub const SYS_sched_setattr: ::c_long = 355; +pub const SYS_sched_getattr: ::c_long = 356; +pub const SYS_renameat2: ::c_long = 357; +pub const SYS_seccomp: ::c_long = 358; +pub const SYS_getrandom: ::c_long = 359; +pub const SYS_memfd_create: ::c_long = 360; +pub const SYS_bpf: ::c_long = 361; +pub const SYS_execveat: ::c_long = 362; +pub const SYS_switch_endian: ::c_long = 363; +pub const SYS_userfaultfd: ::c_long = 364; +pub const SYS_membarrier: ::c_long = 365; +pub const SYS_mlock2: ::c_long = 378; +pub const SYS_copy_file_range: ::c_long = 379; +pub const SYS_preadv2: ::c_long = 380; +pub const SYS_pwritev2: ::c_long = 381; +pub const SYS_kexec_file_load: ::c_long = 382; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/x86_64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/b64/x86_64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,451 @@ +pub type c_char = i8; +pub type wchar_t = i32; +pub type nlink_t = u64; +pub type blksize_t = ::c_long; +pub type __u64 = ::c_ulonglong; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + __pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused: [::c_long; 3], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino64_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + __pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __reserved: [::c_long; 3], + } + + pub struct mcontext_t { + __private: [u64; 32], + } + + pub struct ucontext_t { + pub uc_flags: ::c_ulong, + pub uc_link: *mut ucontext_t, + pub uc_stack: ::stack_t, + pub uc_mcontext: mcontext_t, + pub uc_sigmask: ::sigset_t, + __private: [u8; 512], + } + + pub struct ipc_perm { + pub __ipc_perm_key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + pub __seq: ::c_int, + __unused1: ::c_long, + __unused2: ::c_long + } +} + +// Syscall table + +pub const SYS_read: ::c_long = 0; +pub const SYS_write: ::c_long = 1; +pub const SYS_open: ::c_long = 2; +pub const SYS_close: ::c_long = 3; +pub const SYS_stat: ::c_long = 4; +pub const SYS_fstat: ::c_long = 5; +pub const SYS_lstat: ::c_long = 6; +pub const SYS_poll: ::c_long = 7; +pub const SYS_lseek: ::c_long = 8; +pub const SYS_mmap: ::c_long = 9; +pub const SYS_mprotect: ::c_long = 10; +pub const SYS_munmap: ::c_long = 11; +pub const SYS_brk: ::c_long = 12; +pub const SYS_rt_sigaction: ::c_long = 13; +pub const SYS_rt_sigprocmask: ::c_long = 14; +pub const SYS_rt_sigreturn: ::c_long = 15; +pub const SYS_ioctl: ::c_long = 16; +pub const SYS_pread64: ::c_long = 17; +pub const SYS_pwrite64: ::c_long = 18; +pub const SYS_readv: ::c_long = 19; +pub const SYS_writev: ::c_long = 20; +pub const SYS_access: ::c_long = 21; +pub const SYS_pipe: ::c_long = 22; +pub const SYS_select: ::c_long = 23; +pub const SYS_sched_yield: ::c_long = 24; +pub const SYS_mremap: ::c_long = 25; +pub const SYS_msync: ::c_long = 26; +pub const SYS_mincore: ::c_long = 27; +pub const SYS_madvise: ::c_long = 28; +pub const SYS_shmget: ::c_long = 29; +pub const SYS_shmat: ::c_long = 30; +pub const SYS_shmctl: ::c_long = 31; +pub const SYS_dup: ::c_long = 32; +pub const SYS_dup2: ::c_long = 33; +pub const SYS_pause: ::c_long = 34; +pub const SYS_nanosleep: ::c_long = 35; +pub const SYS_getitimer: ::c_long = 36; +pub const SYS_alarm: ::c_long = 37; +pub const SYS_setitimer: ::c_long = 38; +pub const SYS_getpid: ::c_long = 39; +pub const SYS_sendfile: ::c_long = 40; +pub const SYS_socket: ::c_long = 41; +pub const SYS_connect: ::c_long = 42; +pub const SYS_accept: ::c_long = 43; +pub const SYS_sendto: ::c_long = 44; +pub const SYS_recvfrom: ::c_long = 45; +pub const SYS_sendmsg: ::c_long = 46; +pub const SYS_recvmsg: ::c_long = 47; +pub const SYS_shutdown: ::c_long = 48; +pub const SYS_bind: ::c_long = 49; +pub const SYS_listen: ::c_long = 50; +pub const SYS_getsockname: ::c_long = 51; +pub const SYS_getpeername: ::c_long = 52; +pub const SYS_socketpair: ::c_long = 53; +pub const SYS_setsockopt: ::c_long = 54; +pub const SYS_getsockopt: ::c_long = 55; +pub const SYS_clone: ::c_long = 56; +pub const SYS_fork: ::c_long = 57; +pub const SYS_vfork: ::c_long = 58; +pub const SYS_execve: ::c_long = 59; +pub const SYS_exit: ::c_long = 60; +pub const SYS_wait4: ::c_long = 61; +pub const SYS_kill: ::c_long = 62; +pub const SYS_uname: ::c_long = 63; +pub const SYS_semget: ::c_long = 64; +pub const SYS_semop: ::c_long = 65; +pub const SYS_semctl: ::c_long = 66; +pub const SYS_shmdt: ::c_long = 67; +pub const SYS_msgget: ::c_long = 68; +pub const SYS_msgsnd: ::c_long = 69; +pub const SYS_msgrcv: ::c_long = 70; +pub const SYS_msgctl: ::c_long = 71; +pub const SYS_fcntl: ::c_long = 72; +pub const SYS_flock: ::c_long = 73; +pub const SYS_fsync: ::c_long = 74; +pub const SYS_fdatasync: ::c_long = 75; +pub const SYS_truncate: ::c_long = 76; +pub const SYS_ftruncate: ::c_long = 77; +pub const SYS_getdents: ::c_long = 78; +pub const SYS_getcwd: ::c_long = 79; +pub const SYS_chdir: ::c_long = 80; +pub const SYS_fchdir: ::c_long = 81; +pub const SYS_rename: ::c_long = 82; +pub const SYS_mkdir: ::c_long = 83; +pub const SYS_rmdir: ::c_long = 84; +pub const SYS_creat: ::c_long = 85; +pub const SYS_link: ::c_long = 86; +pub const SYS_unlink: ::c_long = 87; +pub const SYS_symlink: ::c_long = 88; +pub const SYS_readlink: ::c_long = 89; +pub const SYS_chmod: ::c_long = 90; +pub const SYS_fchmod: ::c_long = 91; +pub const SYS_chown: ::c_long = 92; +pub const SYS_fchown: ::c_long = 93; +pub const SYS_lchown: ::c_long = 94; +pub const SYS_umask: ::c_long = 95; +pub const SYS_gettimeofday: ::c_long = 96; +pub const SYS_getrlimit: ::c_long = 97; +pub const SYS_getrusage: ::c_long = 98; +pub const SYS_sysinfo: ::c_long = 99; +pub const SYS_times: ::c_long = 100; +pub const SYS_ptrace: ::c_long = 101; +pub const SYS_getuid: ::c_long = 102; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_getgid: ::c_long = 104; +pub const SYS_setuid: ::c_long = 105; +pub const SYS_setgid: ::c_long = 106; +pub const SYS_geteuid: ::c_long = 107; +pub const SYS_getegid: ::c_long = 108; +pub const SYS_setpgid: ::c_long = 109; +pub const SYS_getppid: ::c_long = 110; +pub const SYS_getpgrp: ::c_long = 111; +pub const SYS_setsid: ::c_long = 112; +pub const SYS_setreuid: ::c_long = 113; +pub const SYS_setregid: ::c_long = 114; +pub const SYS_getgroups: ::c_long = 115; +pub const SYS_setgroups: ::c_long = 116; +pub const SYS_setresuid: ::c_long = 117; +pub const SYS_getresuid: ::c_long = 118; +pub const SYS_setresgid: ::c_long = 119; +pub const SYS_getresgid: ::c_long = 120; +pub const SYS_getpgid: ::c_long = 121; +pub const SYS_setfsuid: ::c_long = 122; +pub const SYS_setfsgid: ::c_long = 123; +pub const SYS_getsid: ::c_long = 124; +pub const SYS_capget: ::c_long = 125; +pub const SYS_capset: ::c_long = 126; +pub const SYS_rt_sigpending: ::c_long = 127; +pub const SYS_rt_sigtimedwait: ::c_long = 128; +pub const SYS_rt_sigqueueinfo: ::c_long = 129; +pub const SYS_rt_sigsuspend: ::c_long = 130; +pub const SYS_sigaltstack: ::c_long = 131; +pub const SYS_utime: ::c_long = 132; +pub const SYS_mknod: ::c_long = 133; +pub const SYS_uselib: ::c_long = 134; +pub const SYS_personality: ::c_long = 135; +pub const SYS_ustat: ::c_long = 136; +pub const SYS_statfs: ::c_long = 137; +pub const SYS_fstatfs: ::c_long = 138; +pub const SYS_sysfs: ::c_long = 139; +pub const SYS_getpriority: ::c_long = 140; +pub const SYS_setpriority: ::c_long = 141; +pub const SYS_sched_setparam: ::c_long = 142; +pub const SYS_sched_getparam: ::c_long = 143; +pub const SYS_sched_setscheduler: ::c_long = 144; +pub const SYS_sched_getscheduler: ::c_long = 145; +pub const SYS_sched_get_priority_max: ::c_long = 146; +pub const SYS_sched_get_priority_min: ::c_long = 147; +pub const SYS_sched_rr_get_interval: ::c_long = 148; +pub const SYS_mlock: ::c_long = 149; +pub const SYS_munlock: ::c_long = 150; +pub const SYS_mlockall: ::c_long = 151; +pub const SYS_munlockall: ::c_long = 152; +pub const SYS_vhangup: ::c_long = 153; +pub const SYS_modify_ldt: ::c_long = 154; +pub const SYS_pivot_root: ::c_long = 155; +pub const SYS__sysctl: ::c_long = 156; +pub const SYS_prctl: ::c_long = 157; +pub const SYS_arch_prctl: ::c_long = 158; +pub const SYS_adjtimex: ::c_long = 159; +pub const SYS_setrlimit: ::c_long = 160; +pub const SYS_chroot: ::c_long = 161; +pub const SYS_sync: ::c_long = 162; +pub const SYS_acct: ::c_long = 163; +pub const SYS_settimeofday: ::c_long = 164; +pub const SYS_mount: ::c_long = 165; +pub const SYS_umount2: ::c_long = 166; +pub const SYS_swapon: ::c_long = 167; +pub const SYS_swapoff: ::c_long = 168; +pub const SYS_reboot: ::c_long = 169; +pub const SYS_sethostname: ::c_long = 170; +pub const SYS_setdomainname: ::c_long = 171; +pub const SYS_iopl: ::c_long = 172; +pub const SYS_ioperm: ::c_long = 173; +pub const SYS_create_module: ::c_long = 174; +pub const SYS_init_module: ::c_long = 175; +pub const SYS_delete_module: ::c_long = 176; +pub const SYS_get_kernel_syms: ::c_long = 177; +pub const SYS_query_module: ::c_long = 178; +pub const SYS_quotactl: ::c_long = 179; +pub const SYS_nfsservctl: ::c_long = 180; +pub const SYS_getpmsg: ::c_long = 181; +pub const SYS_putpmsg: ::c_long = 182; +pub const SYS_afs_syscall: ::c_long = 183; +pub const SYS_tuxcall: ::c_long = 184; +pub const SYS_security: ::c_long = 185; +pub const SYS_gettid: ::c_long = 186; +pub const SYS_readahead: ::c_long = 187; +pub const SYS_setxattr: ::c_long = 188; +pub const SYS_lsetxattr: ::c_long = 189; +pub const SYS_fsetxattr: ::c_long = 190; +pub const SYS_getxattr: ::c_long = 191; +pub const SYS_lgetxattr: ::c_long = 192; +pub const SYS_fgetxattr: ::c_long = 193; +pub const SYS_listxattr: ::c_long = 194; +pub const SYS_llistxattr: ::c_long = 195; +pub const SYS_flistxattr: ::c_long = 196; +pub const SYS_removexattr: ::c_long = 197; +pub const SYS_lremovexattr: ::c_long = 198; +pub const SYS_fremovexattr: ::c_long = 199; +pub const SYS_tkill: ::c_long = 200; +pub const SYS_time: ::c_long = 201; +pub const SYS_futex: ::c_long = 202; +pub const SYS_sched_setaffinity: ::c_long = 203; +pub const SYS_sched_getaffinity: ::c_long = 204; +pub const SYS_set_thread_area: ::c_long = 205; +pub const SYS_io_setup: ::c_long = 206; +pub const SYS_io_destroy: ::c_long = 207; +pub const SYS_io_getevents: ::c_long = 208; +pub const SYS_io_submit: ::c_long = 209; +pub const SYS_io_cancel: ::c_long = 210; +pub const SYS_get_thread_area: ::c_long = 211; +pub const SYS_lookup_dcookie: ::c_long = 212; +pub const SYS_epoll_create: ::c_long = 213; +pub const SYS_epoll_ctl_old: ::c_long = 214; +pub const SYS_epoll_wait_old: ::c_long = 215; +pub const SYS_remap_file_pages: ::c_long = 216; +pub const SYS_getdents64: ::c_long = 217; +pub const SYS_set_tid_address: ::c_long = 218; +pub const SYS_restart_syscall: ::c_long = 219; +pub const SYS_semtimedop: ::c_long = 220; +pub const SYS_fadvise64: ::c_long = 221; +pub const SYS_timer_create: ::c_long = 222; +pub const SYS_timer_settime: ::c_long = 223; +pub const SYS_timer_gettime: ::c_long = 224; +pub const SYS_timer_getoverrun: ::c_long = 225; +pub const SYS_timer_delete: ::c_long = 226; +pub const SYS_clock_settime: ::c_long = 227; +pub const SYS_clock_gettime: ::c_long = 228; +pub const SYS_clock_getres: ::c_long = 229; +pub const SYS_clock_nanosleep: ::c_long = 230; +pub const SYS_exit_group: ::c_long = 231; +pub const SYS_epoll_wait: ::c_long = 232; +pub const SYS_epoll_ctl: ::c_long = 233; +pub const SYS_tgkill: ::c_long = 234; +pub const SYS_utimes: ::c_long = 235; +pub const SYS_vserver: ::c_long = 236; +pub const SYS_mbind: ::c_long = 237; +pub const SYS_set_mempolicy: ::c_long = 238; +pub const SYS_get_mempolicy: ::c_long = 239; +pub const SYS_mq_open: ::c_long = 240; +pub const SYS_mq_unlink: ::c_long = 241; +pub const SYS_mq_timedsend: ::c_long = 242; +pub const SYS_mq_timedreceive: ::c_long = 243; +pub const SYS_mq_notify: ::c_long = 244; +pub const SYS_mq_getsetattr: ::c_long = 245; +pub const SYS_kexec_load: ::c_long = 246; +pub const SYS_waitid: ::c_long = 247; +pub const SYS_add_key: ::c_long = 248; +pub const SYS_request_key: ::c_long = 249; +pub const SYS_keyctl: ::c_long = 250; +pub const SYS_ioprio_set: ::c_long = 251; +pub const SYS_ioprio_get: ::c_long = 252; +pub const SYS_inotify_init: ::c_long = 253; +pub const SYS_inotify_add_watch: ::c_long = 254; +pub const SYS_inotify_rm_watch: ::c_long = 255; +pub const SYS_migrate_pages: ::c_long = 256; +pub const SYS_openat: ::c_long = 257; +pub const SYS_mkdirat: ::c_long = 258; +pub const SYS_mknodat: ::c_long = 259; +pub const SYS_fchownat: ::c_long = 260; +pub const SYS_futimesat: ::c_long = 261; +pub const SYS_newfstatat: ::c_long = 262; +pub const SYS_unlinkat: ::c_long = 263; +pub const SYS_renameat: ::c_long = 264; +pub const SYS_linkat: ::c_long = 265; +pub const SYS_symlinkat: ::c_long = 266; +pub const SYS_readlinkat: ::c_long = 267; +pub const SYS_fchmodat: ::c_long = 268; +pub const SYS_faccessat: ::c_long = 269; +pub const SYS_pselect6: ::c_long = 270; +pub const SYS_ppoll: ::c_long = 271; +pub const SYS_unshare: ::c_long = 272; +pub const SYS_set_robust_list: ::c_long = 273; +pub const SYS_get_robust_list: ::c_long = 274; +pub const SYS_splice: ::c_long = 275; +pub const SYS_tee: ::c_long = 276; +pub const SYS_sync_file_range: ::c_long = 277; +pub const SYS_vmsplice: ::c_long = 278; +pub const SYS_move_pages: ::c_long = 279; +pub const SYS_utimensat: ::c_long = 280; +pub const SYS_epoll_pwait: ::c_long = 281; +pub const SYS_signalfd: ::c_long = 282; +pub const SYS_timerfd_create: ::c_long = 283; +pub const SYS_eventfd: ::c_long = 284; +pub const SYS_fallocate: ::c_long = 285; +pub const SYS_timerfd_settime: ::c_long = 286; +pub const SYS_timerfd_gettime: ::c_long = 287; +pub const SYS_accept4: ::c_long = 288; +pub const SYS_signalfd4: ::c_long = 289; +pub const SYS_eventfd2: ::c_long = 290; +pub const SYS_epoll_create1: ::c_long = 291; +pub const SYS_dup3: ::c_long = 292; +pub const SYS_pipe2: ::c_long = 293; +pub const SYS_inotify_init1: ::c_long = 294; +pub const SYS_preadv: ::c_long = 295; +pub const SYS_pwritev: ::c_long = 296; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 297; +pub const SYS_perf_event_open: ::c_long = 298; +pub const SYS_recvmmsg: ::c_long = 299; +pub const SYS_fanotify_init: ::c_long = 300; +pub const SYS_fanotify_mark: ::c_long = 301; +pub const SYS_prlimit64: ::c_long = 302; +pub const SYS_name_to_handle_at: ::c_long = 303; +pub const SYS_open_by_handle_at: ::c_long = 304; +pub const SYS_clock_adjtime: ::c_long = 305; +pub const SYS_syncfs: ::c_long = 306; +pub const SYS_sendmmsg: ::c_long = 307; +pub const SYS_setns: ::c_long = 308; +pub const SYS_getcpu: ::c_long = 309; +pub const SYS_process_vm_readv: ::c_long = 310; +pub const SYS_process_vm_writev: ::c_long = 311; +pub const SYS_kcmp: ::c_long = 312; +pub const SYS_finit_module: ::c_long = 313; +pub const SYS_sched_setattr: ::c_long = 314; +pub const SYS_sched_getattr: ::c_long = 315; +pub const SYS_renameat2: ::c_long = 316; +pub const SYS_seccomp: ::c_long = 317; +pub const SYS_getrandom: ::c_long = 318; +pub const SYS_memfd_create: ::c_long = 319; +pub const SYS_kexec_file_load: ::c_long = 320; +pub const SYS_bpf: ::c_long = 321; +pub const SYS_execveat: ::c_long = 322; +pub const SYS_userfaultfd: ::c_long = 323; +pub const SYS_membarrier: ::c_long = 324; +pub const SYS_mlock2: ::c_long = 325; +pub const SYS_copy_file_range: ::c_long = 326; +pub const SYS_preadv2: ::c_long = 327; +pub const SYS_pwritev2: ::c_long = 328; +// FIXME syscalls 329-331 have been added in musl 1.16 +// See discussion https://github.com/rust-lang/libc/pull/699 + +// offsets in user_regs_structs, from sys/reg.h +pub const R15: ::c_int = 0; +pub const R14: ::c_int = 1; +pub const R13: ::c_int = 2; +pub const R12: ::c_int = 3; +pub const RBP: ::c_int = 4; +pub const RBX: ::c_int = 5; +pub const R11: ::c_int = 6; +pub const R10: ::c_int = 7; +pub const R9: ::c_int = 8; +pub const R8: ::c_int = 9; +pub const RAX: ::c_int = 10; +pub const RCX: ::c_int = 11; +pub const RDX: ::c_int = 12; +pub const RSI: ::c_int = 13; +pub const RDI: ::c_int = 14; +pub const ORIG_RAX: ::c_int = 15; +pub const RIP: ::c_int = 16; +pub const CS: ::c_int = 17; +pub const EFLAGS: ::c_int = 18; +pub const RSP: ::c_int = 19; +pub const SS: ::c_int = 20; +pub const FS_BASE: ::c_int = 21; +pub const GS_BASE: ::c_int = 22; +pub const DS: ::c_int = 23; +pub const ES: ::c_int = 24; +pub const FS: ::c_int = 25; +pub const GS: ::c_int = 26; + +pub const MAP_32BIT: ::c_int = 0x0040; +pub const O_DIRECT: ::c_int = 0x4000; +pub const O_DIRECTORY: ::c_int = 0x10000; +pub const O_LARGEFILE: ::c_int = 0; +pub const O_NOFOLLOW: ::c_int = 0x20000; + +pub const SIGSTKSZ: ::size_t = 8192; +pub const MINSIGSTKSZ: ::size_t = 2048; + +#[doc(hidden)] +pub const AF_MAX: ::c_int = 42; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/musl/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,321 @@ +pub type clock_t = c_long; +pub type time_t = c_long; +pub type suseconds_t = c_long; +pub type ino_t = u64; +pub type off_t = i64; +pub type blkcnt_t = i64; + +pub type shmatt_t = ::c_ulong; +pub type msgqnum_t = ::c_ulong; +pub type msglen_t = ::c_ulong; +pub type fsblkcnt_t = ::c_ulonglong; +pub type fsfilcnt_t = ::c_ulonglong; +pub type rlim_t = ::c_ulonglong; + +s! { + pub struct aiocb { + pub aio_fildes: ::c_int, + pub aio_lio_opcode: ::c_int, + pub aio_reqprio: ::c_int, + pub aio_buf: *mut ::c_void, + pub aio_nbytes: ::size_t, + pub aio_sigevent: ::sigevent, + __td: *mut ::c_void, + __lock: [::c_int; 2], + __err: ::c_int, + __ret: ::ssize_t, + pub aio_offset: off_t, + __next: *mut ::c_void, + __prev: *mut ::c_void, + #[cfg(target_pointer_width = "32")] + __dummy4: [::c_char; 24], + #[cfg(target_pointer_width = "64")] + __dummy4: [::c_char; 16], + } + + pub struct sigaction { + pub sa_sigaction: ::sighandler_t, + pub sa_mask: ::sigset_t, + pub sa_flags: ::c_int, + pub sa_restorer: ::dox::Option, + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; ::NCCS], + pub __c_ispeed: ::speed_t, + pub __c_ospeed: ::speed_t, + } + + pub struct flock { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_pid: ::pid_t, + } + + pub struct sysinfo { + pub uptime: ::c_ulong, + pub loads: [::c_ulong; 3], + pub totalram: ::c_ulong, + pub freeram: ::c_ulong, + pub sharedram: ::c_ulong, + pub bufferram: ::c_ulong, + pub totalswap: ::c_ulong, + pub freeswap: ::c_ulong, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: ::c_ulong, + pub freehigh: ::c_ulong, + pub mem_unit: ::c_uint, + pub __reserved: [::c_char; 256], + } +} + +pub const SFD_CLOEXEC: ::c_int = 0x080000; + +pub const NCCS: usize = 32; + +pub const O_TRUNC: ::c_int = 512; +pub const O_NOATIME: ::c_int = 0o1000000; +pub const O_CLOEXEC: ::c_int = 0x80000; +pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; + +pub const EBFONT: ::c_int = 59; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const EDOTDOT: ::c_int = 73; + +pub const SA_NODEFER: ::c_int = 0x40000000; +pub const SA_RESETHAND: ::c_int = 0x80000000; +pub const SA_RESTART: ::c_int = 0x10000000; +pub const SA_NOCLDSTOP: ::c_int = 0x00000001; + +pub const EPOLL_CLOEXEC: ::c_int = 0x80000; + +pub const EFD_CLOEXEC: ::c_int = 0x80000; + +pub const BUFSIZ: ::c_uint = 1024; +pub const TMP_MAX: ::c_uint = 10000; +pub const FOPEN_MAX: ::c_uint = 1000; +pub const O_PATH: ::c_int = 0o10000000; +pub const O_EXEC: ::c_int = 0o10000000; +pub const O_SEARCH: ::c_int = 0o10000000; +pub const O_ACCMODE: ::c_int = 0o10000003; +pub const O_NDELAY: ::c_int = O_NONBLOCK; +pub const NI_MAXHOST: ::socklen_t = 255; +pub const PTHREAD_STACK_MIN: ::size_t = 2048; +pub const POSIX_FADV_DONTNEED: ::c_int = 4; +pub const POSIX_FADV_NOREUSE: ::c_int = 5; + +pub const POSIX_MADV_DONTNEED: ::c_int = 4; + +pub const RLIM_INFINITY: ::rlim_t = !0; +pub const RLIMIT_RTTIME: ::c_int = 15; +pub const RLIMIT_NLIMITS: ::c_int = 16; + +pub const MAP_ANONYMOUS: ::c_int = MAP_ANON; + +pub const SOCK_DCCP: ::c_int = 6; +pub const SOCK_PACKET: ::c_int = 10; + +pub const TCP_COOKIE_TRANSACTIONS: ::c_int = 15; +pub const TCP_THIN_LINEAR_TIMEOUTS: ::c_int = 16; +pub const TCP_THIN_DUPACK: ::c_int = 17; +pub const TCP_USER_TIMEOUT: ::c_int = 18; +pub const TCP_REPAIR: ::c_int = 19; +pub const TCP_REPAIR_QUEUE: ::c_int = 20; +pub const TCP_QUEUE_SEQ: ::c_int = 21; +pub const TCP_REPAIR_OPTIONS: ::c_int = 22; +pub const TCP_FASTOPEN: ::c_int = 23; +pub const TCP_TIMESTAMP: ::c_int = 24; + +pub const SIGUNUSED: ::c_int = ::SIGSYS; + +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; + +pub const CPU_SETSIZE: ::c_int = 128; + +pub const PTRACE_TRACEME: ::c_int = 0; +pub const PTRACE_PEEKTEXT: ::c_int = 1; +pub const PTRACE_PEEKDATA: ::c_int = 2; +pub const PTRACE_PEEKUSER: ::c_int = 3; +pub const PTRACE_POKETEXT: ::c_int = 4; +pub const PTRACE_POKEDATA: ::c_int = 5; +pub const PTRACE_POKEUSER: ::c_int = 6; +pub const PTRACE_CONT: ::c_int = 7; +pub const PTRACE_KILL: ::c_int = 8; +pub const PTRACE_SINGLESTEP: ::c_int = 9; +pub const PTRACE_GETREGS: ::c_int = 12; +pub const PTRACE_SETREGS: ::c_int = 13; +pub const PTRACE_GETFPREGS: ::c_int = 14; +pub const PTRACE_SETFPREGS: ::c_int = 15; +pub const PTRACE_ATTACH: ::c_int = 16; +pub const PTRACE_DETACH: ::c_int = 17; +pub const PTRACE_GETFPXREGS: ::c_int = 18; +pub const PTRACE_SETFPXREGS: ::c_int = 19; +pub const PTRACE_SYSCALL: ::c_int = 24; +pub const PTRACE_SETOPTIONS: ::c_int = 0x4200; +pub const PTRACE_GETEVENTMSG: ::c_int = 0x4201; +pub const PTRACE_GETSIGINFO: ::c_int = 0x4202; +pub const PTRACE_SETSIGINFO: ::c_int = 0x4203; +pub const PTRACE_GETREGSET: ::c_int = 0x4204; +pub const PTRACE_SETREGSET: ::c_int = 0x4205; +pub const PTRACE_SEIZE: ::c_int = 0x4206; +pub const PTRACE_INTERRUPT: ::c_int = 0x4207; +pub const PTRACE_LISTEN: ::c_int = 0x4208; +pub const PTRACE_PEEKSIGINFO: ::c_int = 0x4209; + +pub const EPOLLWAKEUP: ::c_int = 0x20000000; + +pub const EFD_NONBLOCK: ::c_int = ::O_NONBLOCK; + +pub const SFD_NONBLOCK: ::c_int = ::O_NONBLOCK; + +pub const TCSANOW: ::c_int = 0; +pub const TCSADRAIN: ::c_int = 1; +pub const TCSAFLUSH: ::c_int = 2; + +pub const TIOCINQ: ::c_int = ::FIONREAD; + +pub const RTLD_GLOBAL: ::c_int = 0x100; +pub const RTLD_NOLOAD: ::c_int = 0x4; + +// TODO(#247) Temporarily musl-specific (available since musl 0.9.12 / Linux +// kernel 3.10). See also notbsd/mod.rs +pub const CLOCK_SGI_CYCLE: ::clockid_t = 10; +pub const CLOCK_TAI: ::clockid_t = 11; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const CBAUD: ::tcflag_t = 0o0010017; +pub const TAB1: ::c_int = 0x00000800; +pub const TAB2: ::c_int = 0x00001000; +pub const TAB3: ::c_int = 0x00001800; +pub const CR1: ::c_int = 0x00000200; +pub const CR2: ::c_int = 0x00000400; +pub const CR3: ::c_int = 0x00000600; +pub const FF1: ::c_int = 0x00008000; +pub const BS1: ::c_int = 0x00002000; +pub const VT1: ::c_int = 0x00004000; +pub const VWERASE: usize = 14; +pub const VREPRINT: usize = 12; +pub const VSUSP: usize = 10; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VDISCARD: usize = 13; +pub const VTIME: usize = 5; +pub const IXON: ::tcflag_t = 0x00000400; +pub const IXOFF: ::tcflag_t = 0x00001000; +pub const ONLCR: ::tcflag_t = 0x4; +pub const CSIZE: ::tcflag_t = 0x00000030; +pub const CS6: ::tcflag_t = 0x00000010; +pub const CS7: ::tcflag_t = 0x00000020; +pub const CS8: ::tcflag_t = 0x00000030; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const ECHOKE: ::tcflag_t = 0x00000800; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const ECHOPRT: ::tcflag_t = 0x00000400; +pub const ECHOCTL: ::tcflag_t = 0x00000200; +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const PENDIN: ::tcflag_t = 0x00004000; +pub const NOFLSH: ::tcflag_t = 0x00000080; +pub const CIBAUD: ::tcflag_t = 0o02003600000; +pub const CBAUDEX: ::tcflag_t = 0o010000; +pub const VSWTC: usize = 7; +pub const OLCUC: ::tcflag_t = 0o000002; +pub const NLDLY: ::tcflag_t = 0o000400; +pub const CRDLY: ::tcflag_t = 0o003000; +pub const TABDLY: ::tcflag_t = 0o014000; +pub const BSDLY: ::tcflag_t = 0o020000; +pub const FFDLY: ::tcflag_t = 0o100000; +pub const VTDLY: ::tcflag_t = 0o040000; +pub const XTABS: ::tcflag_t = 0o014000; + +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const B57600: ::speed_t = 0o010001; +pub const B115200: ::speed_t = 0o010002; +pub const B230400: ::speed_t = 0o010003; +pub const B460800: ::speed_t = 0o010004; +pub const B500000: ::speed_t = 0o010005; +pub const B576000: ::speed_t = 0o010006; +pub const B921600: ::speed_t = 0o010007; +pub const B1000000: ::speed_t = 0o010010; +pub const B1152000: ::speed_t = 0o010011; +pub const B1500000: ::speed_t = 0o010012; +pub const B2000000: ::speed_t = 0o010013; +pub const B2500000: ::speed_t = 0o010014; +pub const B3000000: ::speed_t = 0o010015; +pub const B3500000: ::speed_t = 0o010016; +pub const B4000000: ::speed_t = 0o010017; + +pub const SO_BINDTODEVICE: ::c_int = 25; +pub const SO_TIMESTAMP: ::c_int = 29; +pub const SO_MARK: ::c_int = 36; +pub const SO_RXQ_OVFL: ::c_int = 40; +pub const SO_PEEK_OFF: ::c_int = 42; +pub const SO_BUSY_POLL: ::c_int = 46; + +extern { + pub fn ioctl(fd: ::c_int, request: ::c_int, ...) -> ::c_int; + pub fn ptrace(request: ::c_int, ...) -> ::c_long; + pub fn getpriority(which: ::c_int, who: ::id_t) -> ::c_int; + pub fn setpriority(which: ::c_int, who: ::id_t, prio: ::c_int) -> ::c_int; +} + +cfg_if! { + if #[cfg(any(target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "powerpc64"))] { + mod b64; + pub use self::b64::*; + } else if #[cfg(any(target_arch = "x86", + target_arch = "mips", + target_arch = "arm"))] { + mod b32; + pub use self::b32::*; + } else { } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/arm.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/arm.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/arm.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/arm.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,612 @@ +pub type c_char = u8; +pub type wchar_t = u32; + +s! { + pub struct ipc_perm { + pub __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::c_ushort, + __pad1: ::c_ushort, + pub __seq: ::c_ushort, + __pad2: ::c_ushort, + __unused1: ::c_ulong, + __unused2: ::c_ulong + } + + pub struct stat64 { + pub st_dev: ::dev_t, + __pad1: ::c_uint, + __st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad2: ::c_uint, + pub st_size: ::off64_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_ino: ::ino64_t, + } + + pub struct statfs64 { + pub f_type: ::__fsword_t, + pub f_bsize: ::__fsword_t, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_fsid: ::fsid_t, + pub f_namelen: ::__fsword_t, + pub f_frsize: ::__fsword_t, + pub f_flags: ::__fsword_t, + pub f_spare: [::__fsword_t; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + __f_unused: ::c_int, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + __unused1: ::c_ulong, + pub shm_dtime: ::time_t, + __unused2: ::c_ulong, + pub shm_ctime: ::time_t, + __unused3: ::c_ulong, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __unused4: ::c_ulong, + __unused5: ::c_ulong + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_stime: ::time_t, + __glibc_reserved1: ::c_ulong, + pub msg_rtime: ::time_t, + __glibc_reserved2: ::c_ulong, + pub msg_ctime: ::time_t, + __glibc_reserved3: ::c_ulong, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __glibc_reserved4: ::c_ulong, + __glibc_reserved5: ::c_ulong, + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 19], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } +} + +pub const O_DIRECT: ::c_int = 0x10000; +pub const O_DIRECTORY: ::c_int = 0x4000; +pub const O_NOFOLLOW: ::c_int = 0x8000; +pub const O_LARGEFILE: ::c_int = 0o400000; + +pub const MAP_LOCKED: ::c_int = 0x02000; +pub const MAP_NORESERVE: ::c_int = 0x04000; + +pub const EDEADLOCK: ::c_int = 35; + +pub const SO_PASSCRED: ::c_int = 16; +pub const SO_PEERCRED: ::c_int = 17; +pub const SO_RCVLOWAT: ::c_int = 18; +pub const SO_SNDLOWAT: ::c_int = 19; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_SNDTIMEO: ::c_int = 21; +pub const SO_SNDBUFFORCE: ::c_int = 32; +pub const SO_RCVBUFFORCE: ::c_int = 33; + +pub const FIOCLEX: ::c_ulong = 0x5451; +pub const FIONBIO: ::c_ulong = 0x5421; + +pub const PTRACE_GETFPXREGS: ::c_uint = 18; +pub const PTRACE_SETFPXREGS: ::c_uint = 19; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const SIGSTKSZ: ::size_t = 8192; +pub const MINSIGSTKSZ: ::size_t = 2048; +pub const CBAUD: ::tcflag_t = 0o0010017; +pub const TAB1: ::c_int = 0x00000800; +pub const TAB2: ::c_int = 0x00001000; +pub const TAB3: ::c_int = 0x00001800; +pub const CR1: ::c_int = 0x00000200; +pub const CR2: ::c_int = 0x00000400; +pub const CR3: ::c_int = 0x00000600; +pub const FF1: ::c_int = 0x00008000; +pub const BS1: ::c_int = 0x00002000; +pub const VT1: ::c_int = 0x00004000; +pub const VWERASE: usize = 14; +pub const VREPRINT: usize = 12; +pub const VSUSP: usize = 10; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VDISCARD: usize = 13; +pub const VTIME: usize = 5; +pub const IXON: ::tcflag_t = 0x00000400; +pub const IXOFF: ::tcflag_t = 0x00001000; +pub const ONLCR: ::tcflag_t = 0x4; +pub const CSIZE: ::tcflag_t = 0x00000030; +pub const CS6: ::tcflag_t = 0x00000010; +pub const CS7: ::tcflag_t = 0x00000020; +pub const CS8: ::tcflag_t = 0x00000030; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const ECHOKE: ::tcflag_t = 0x00000800; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const ECHOPRT: ::tcflag_t = 0x00000400; +pub const ECHOCTL: ::tcflag_t = 0x00000200; +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const PENDIN: ::tcflag_t = 0x00004000; +pub const NOFLSH: ::tcflag_t = 0x00000080; +pub const CIBAUD: ::tcflag_t = 0o02003600000; +pub const CBAUDEX: ::tcflag_t = 0o010000; +pub const VSWTC: usize = 7; +pub const OLCUC: ::tcflag_t = 0o000002; +pub const NLDLY: ::tcflag_t = 0o000400; +pub const CRDLY: ::tcflag_t = 0o003000; +pub const TABDLY: ::tcflag_t = 0o014000; +pub const BSDLY: ::tcflag_t = 0o020000; +pub const FFDLY: ::tcflag_t = 0o100000; +pub const VTDLY: ::tcflag_t = 0o040000; +pub const XTABS: ::tcflag_t = 0o014000; + +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const BOTHER: ::speed_t = 0o010000; +pub const B57600: ::speed_t = 0o010001; +pub const B115200: ::speed_t = 0o010002; +pub const B230400: ::speed_t = 0o010003; +pub const B460800: ::speed_t = 0o010004; +pub const B500000: ::speed_t = 0o010005; +pub const B576000: ::speed_t = 0o010006; +pub const B921600: ::speed_t = 0o010007; +pub const B1000000: ::speed_t = 0o010010; +pub const B1152000: ::speed_t = 0o010011; +pub const B1500000: ::speed_t = 0o010012; +pub const B2000000: ::speed_t = 0o010013; +pub const B2500000: ::speed_t = 0o010014; +pub const B3000000: ::speed_t = 0o010015; +pub const B3500000: ::speed_t = 0o010016; +pub const B4000000: ::speed_t = 0o010017; + +pub const VEOL: usize = 11; +pub const VEOL2: usize = 16; +pub const VMIN: usize = 6; +pub const IEXTEN: ::tcflag_t = 0x00008000; +pub const TOSTOP: ::tcflag_t = 0x00000100; +pub const FLUSHO: ::tcflag_t = 0x00001000; +pub const EXTPROC: ::tcflag_t = 0x00010000; +pub const TCGETS: ::c_ulong = 0x5401; +pub const TCSETS: ::c_ulong = 0x5402; +pub const TCSETSW: ::c_ulong = 0x5403; +pub const TCSETSF: ::c_ulong = 0x5404; +pub const TCGETA: ::c_ulong = 0x5405; +pub const TCSETA: ::c_ulong = 0x5406; +pub const TCSETAW: ::c_ulong = 0x5407; +pub const TCSETAF: ::c_ulong = 0x5408; +pub const TCSBRK: ::c_ulong = 0x5409; +pub const TCXONC: ::c_ulong = 0x540A; +pub const TCFLSH: ::c_ulong = 0x540B; +pub const TIOCINQ: ::c_ulong = 0x541B; +pub const TIOCGPGRP: ::c_ulong = 0x540F; +pub const TIOCSPGRP: ::c_ulong = 0x5410; +pub const TIOCOUTQ: ::c_ulong = 0x5411; +pub const TIOCGWINSZ: ::c_ulong = 0x5413; +pub const TIOCSWINSZ: ::c_ulong = 0x5414; +pub const FIONREAD: ::c_ulong = 0x541B; + +// Syscall table +pub const SYS_restart_syscall: ::c_long = 0; +pub const SYS_exit: ::c_long = 1; +pub const SYS_fork: ::c_long = 2; +pub const SYS_read: ::c_long = 3; +pub const SYS_write: ::c_long = 4; +pub const SYS_open: ::c_long = 5; +pub const SYS_close: ::c_long = 6; +pub const SYS_creat: ::c_long = 8; +pub const SYS_link: ::c_long = 9; +pub const SYS_unlink: ::c_long = 10; +pub const SYS_execve: ::c_long = 11; +pub const SYS_chdir: ::c_long = 12; +pub const SYS_mknod: ::c_long = 14; +pub const SYS_chmod: ::c_long = 15; +pub const SYS_lchown: ::c_long = 16; +pub const SYS_lseek: ::c_long = 19; +pub const SYS_getpid: ::c_long = 20; +pub const SYS_mount: ::c_long = 21; +pub const SYS_setuid: ::c_long = 23; +pub const SYS_getuid: ::c_long = 24; +pub const SYS_ptrace: ::c_long = 26; +pub const SYS_pause: ::c_long = 29; +pub const SYS_access: ::c_long = 33; +pub const SYS_nice: ::c_long = 34; +pub const SYS_sync: ::c_long = 36; +pub const SYS_kill: ::c_long = 37; +pub const SYS_rename: ::c_long = 38; +pub const SYS_mkdir: ::c_long = 39; +pub const SYS_rmdir: ::c_long = 40; +pub const SYS_dup: ::c_long = 41; +pub const SYS_pipe: ::c_long = 42; +pub const SYS_times: ::c_long = 43; +pub const SYS_brk: ::c_long = 45; +pub const SYS_setgid: ::c_long = 46; +pub const SYS_getgid: ::c_long = 47; +pub const SYS_geteuid: ::c_long = 49; +pub const SYS_getegid: ::c_long = 50; +pub const SYS_acct: ::c_long = 51; +pub const SYS_umount2: ::c_long = 52; +pub const SYS_ioctl: ::c_long = 54; +pub const SYS_fcntl: ::c_long = 55; +pub const SYS_setpgid: ::c_long = 57; +pub const SYS_umask: ::c_long = 60; +pub const SYS_chroot: ::c_long = 61; +pub const SYS_ustat: ::c_long = 62; +pub const SYS_dup2: ::c_long = 63; +pub const SYS_getppid: ::c_long = 64; +pub const SYS_getpgrp: ::c_long = 65; +pub const SYS_setsid: ::c_long = 66; +pub const SYS_sigaction: ::c_long = 67; +pub const SYS_setreuid: ::c_long = 70; +pub const SYS_setregid: ::c_long = 71; +pub const SYS_sigsuspend: ::c_long = 72; +pub const SYS_sigpending: ::c_long = 73; +pub const SYS_sethostname: ::c_long = 74; +pub const SYS_setrlimit: ::c_long = 75; +pub const SYS_getrusage: ::c_long = 77; +pub const SYS_gettimeofday: ::c_long = 78; +pub const SYS_settimeofday: ::c_long = 79; +pub const SYS_getgroups: ::c_long = 80; +pub const SYS_setgroups: ::c_long = 81; +pub const SYS_symlink: ::c_long = 83; +pub const SYS_readlink: ::c_long = 85; +pub const SYS_uselib: ::c_long = 86; +pub const SYS_swapon: ::c_long = 87; +pub const SYS_reboot: ::c_long = 88; +pub const SYS_munmap: ::c_long = 91; +pub const SYS_truncate: ::c_long = 92; +pub const SYS_ftruncate: ::c_long = 93; +pub const SYS_fchmod: ::c_long = 94; +pub const SYS_fchown: ::c_long = 95; +pub const SYS_getpriority: ::c_long = 96; +pub const SYS_setpriority: ::c_long = 97; +pub const SYS_statfs: ::c_long = 99; +pub const SYS_fstatfs: ::c_long = 100; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_setitimer: ::c_long = 104; +pub const SYS_getitimer: ::c_long = 105; +pub const SYS_stat: ::c_long = 106; +pub const SYS_lstat: ::c_long = 107; +pub const SYS_fstat: ::c_long = 108; +pub const SYS_vhangup: ::c_long = 111; +pub const SYS_wait4: ::c_long = 114; +pub const SYS_swapoff: ::c_long = 115; +pub const SYS_sysinfo: ::c_long = 116; +pub const SYS_fsync: ::c_long = 118; +pub const SYS_sigreturn: ::c_long = 119; +pub const SYS_clone: ::c_long = 120; +pub const SYS_setdomainname: ::c_long = 121; +pub const SYS_uname: ::c_long = 122; +pub const SYS_adjtimex: ::c_long = 124; +pub const SYS_mprotect: ::c_long = 125; +pub const SYS_sigprocmask: ::c_long = 126; +pub const SYS_init_module: ::c_long = 128; +pub const SYS_delete_module: ::c_long = 129; +pub const SYS_quotactl: ::c_long = 131; +pub const SYS_getpgid: ::c_long = 132; +pub const SYS_fchdir: ::c_long = 133; +pub const SYS_bdflush: ::c_long = 134; +pub const SYS_sysfs: ::c_long = 135; +pub const SYS_personality: ::c_long = 136; +pub const SYS_setfsuid: ::c_long = 138; +pub const SYS_setfsgid: ::c_long = 139; +pub const SYS__llseek: ::c_long = 140; +pub const SYS_getdents: ::c_long = 141; +pub const SYS__newselect: ::c_long = 142; +pub const SYS_flock: ::c_long = 143; +pub const SYS_msync: ::c_long = 144; +pub const SYS_readv: ::c_long = 145; +pub const SYS_writev: ::c_long = 146; +pub const SYS_getsid: ::c_long = 147; +pub const SYS_fdatasync: ::c_long = 148; +pub const SYS__sysctl: ::c_long = 149; +pub const SYS_mlock: ::c_long = 150; +pub const SYS_munlock: ::c_long = 151; +pub const SYS_mlockall: ::c_long = 152; +pub const SYS_munlockall: ::c_long = 153; +pub const SYS_sched_setparam: ::c_long = 154; +pub const SYS_sched_getparam: ::c_long = 155; +pub const SYS_sched_setscheduler: ::c_long = 156; +pub const SYS_sched_getscheduler: ::c_long = 157; +pub const SYS_sched_yield: ::c_long = 158; +pub const SYS_sched_get_priority_max: ::c_long = 159; +pub const SYS_sched_get_priority_min: ::c_long = 160; +pub const SYS_sched_rr_get_interval: ::c_long = 161; +pub const SYS_nanosleep: ::c_long = 162; +pub const SYS_mremap: ::c_long = 163; +pub const SYS_setresuid: ::c_long = 164; +pub const SYS_getresuid: ::c_long = 165; +pub const SYS_poll: ::c_long = 168; +pub const SYS_nfsservctl: ::c_long = 169; +pub const SYS_setresgid: ::c_long = 170; +pub const SYS_getresgid: ::c_long = 171; +pub const SYS_prctl: ::c_long = 172; +pub const SYS_rt_sigreturn: ::c_long = 173; +pub const SYS_rt_sigaction: ::c_long = 174; +pub const SYS_rt_sigprocmask: ::c_long = 175; +pub const SYS_rt_sigpending: ::c_long = 176; +pub const SYS_rt_sigtimedwait: ::c_long = 177; +pub const SYS_rt_sigqueueinfo: ::c_long = 178; +pub const SYS_rt_sigsuspend: ::c_long = 179; +pub const SYS_pread64: ::c_long = 180; +pub const SYS_pwrite64: ::c_long = 181; +pub const SYS_chown: ::c_long = 182; +pub const SYS_getcwd: ::c_long = 183; +pub const SYS_capget: ::c_long = 184; +pub const SYS_capset: ::c_long = 185; +pub const SYS_sigaltstack: ::c_long = 186; +pub const SYS_sendfile: ::c_long = 187; +pub const SYS_vfork: ::c_long = 190; +pub const SYS_ugetrlimit: ::c_long = 191; +pub const SYS_mmap2: ::c_long = 192; +pub const SYS_truncate64: ::c_long = 193; +pub const SYS_ftruncate64: ::c_long = 194; +pub const SYS_stat64: ::c_long = 195; +pub const SYS_lstat64: ::c_long = 196; +pub const SYS_fstat64: ::c_long = 197; +pub const SYS_lchown32: ::c_long = 198; +pub const SYS_getuid32: ::c_long = 199; +pub const SYS_getgid32: ::c_long = 200; +pub const SYS_geteuid32: ::c_long = 201; +pub const SYS_getegid32: ::c_long = 202; +pub const SYS_setreuid32: ::c_long = 203; +pub const SYS_setregid32: ::c_long = 204; +pub const SYS_getgroups32: ::c_long = 205; +pub const SYS_setgroups32: ::c_long = 206; +pub const SYS_fchown32: ::c_long = 207; +pub const SYS_setresuid32: ::c_long = 208; +pub const SYS_getresuid32: ::c_long = 209; +pub const SYS_setresgid32: ::c_long = 210; +pub const SYS_getresgid32: ::c_long = 211; +pub const SYS_chown32: ::c_long = 212; +pub const SYS_setuid32: ::c_long = 213; +pub const SYS_setgid32: ::c_long = 214; +pub const SYS_setfsuid32: ::c_long = 215; +pub const SYS_setfsgid32: ::c_long = 216; +pub const SYS_getdents64: ::c_long = 217; +pub const SYS_pivot_root: ::c_long = 218; +pub const SYS_mincore: ::c_long = 219; +pub const SYS_madvise: ::c_long = 220; +pub const SYS_fcntl64: ::c_long = 221; +pub const SYS_gettid: ::c_long = 224; +pub const SYS_readahead: ::c_long = 225; +pub const SYS_setxattr: ::c_long = 226; +pub const SYS_lsetxattr: ::c_long = 227; +pub const SYS_fsetxattr: ::c_long = 228; +pub const SYS_getxattr: ::c_long = 229; +pub const SYS_lgetxattr: ::c_long = 230; +pub const SYS_fgetxattr: ::c_long = 231; +pub const SYS_listxattr: ::c_long = 232; +pub const SYS_llistxattr: ::c_long = 233; +pub const SYS_flistxattr: ::c_long = 234; +pub const SYS_removexattr: ::c_long = 235; +pub const SYS_lremovexattr: ::c_long = 236; +pub const SYS_fremovexattr: ::c_long = 237; +pub const SYS_tkill: ::c_long = 238; +pub const SYS_sendfile64: ::c_long = 239; +pub const SYS_futex: ::c_long = 240; +pub const SYS_sched_setaffinity: ::c_long = 241; +pub const SYS_sched_getaffinity: ::c_long = 242; +pub const SYS_io_setup: ::c_long = 243; +pub const SYS_io_destroy: ::c_long = 244; +pub const SYS_io_getevents: ::c_long = 245; +pub const SYS_io_submit: ::c_long = 246; +pub const SYS_io_cancel: ::c_long = 247; +pub const SYS_exit_group: ::c_long = 248; +pub const SYS_lookup_dcookie: ::c_long = 249; +pub const SYS_epoll_create: ::c_long = 250; +pub const SYS_epoll_ctl: ::c_long = 251; +pub const SYS_epoll_wait: ::c_long = 252; +pub const SYS_remap_file_pages: ::c_long = 253; +pub const SYS_set_tid_address: ::c_long = 256; +pub const SYS_timer_create: ::c_long = 257; +pub const SYS_timer_settime: ::c_long = 258; +pub const SYS_timer_gettime: ::c_long = 259; +pub const SYS_timer_getoverrun: ::c_long = 260; +pub const SYS_timer_delete: ::c_long = 261; +pub const SYS_clock_settime: ::c_long = 262; +pub const SYS_clock_gettime: ::c_long = 263; +pub const SYS_clock_getres: ::c_long = 264; +pub const SYS_clock_nanosleep: ::c_long = 265; +pub const SYS_statfs64: ::c_long = 266; +pub const SYS_fstatfs64: ::c_long = 267; +pub const SYS_tgkill: ::c_long = 268; +pub const SYS_utimes: ::c_long = 269; +pub const SYS_arm_fadvise64_64: ::c_long = 270; +pub const SYS_pciconfig_iobase: ::c_long = 271; +pub const SYS_pciconfig_read: ::c_long = 272; +pub const SYS_pciconfig_write: ::c_long = 273; +pub const SYS_mq_open: ::c_long = 274; +pub const SYS_mq_unlink: ::c_long = 275; +pub const SYS_mq_timedsend: ::c_long = 276; +pub const SYS_mq_timedreceive: ::c_long = 277; +pub const SYS_mq_notify: ::c_long = 278; +pub const SYS_mq_getsetattr: ::c_long = 279; +pub const SYS_waitid: ::c_long = 280; +pub const SYS_socket: ::c_long = 281; +pub const SYS_bind: ::c_long = 282; +pub const SYS_connect: ::c_long = 283; +pub const SYS_listen: ::c_long = 284; +pub const SYS_accept: ::c_long = 285; +pub const SYS_getsockname: ::c_long = 286; +pub const SYS_getpeername: ::c_long = 287; +pub const SYS_socketpair: ::c_long = 288; +pub const SYS_send: ::c_long = 289; +pub const SYS_sendto: ::c_long = 290; +pub const SYS_recv: ::c_long = 291; +pub const SYS_recvfrom: ::c_long = 292; +pub const SYS_shutdown: ::c_long = 293; +pub const SYS_setsockopt: ::c_long = 294; +pub const SYS_getsockopt: ::c_long = 295; +pub const SYS_sendmsg: ::c_long = 296; +pub const SYS_recvmsg: ::c_long = 297; +pub const SYS_semop: ::c_long = 298; +pub const SYS_semget: ::c_long = 299; +pub const SYS_semctl: ::c_long = 300; +pub const SYS_msgsnd: ::c_long = 301; +pub const SYS_msgrcv: ::c_long = 302; +pub const SYS_msgget: ::c_long = 303; +pub const SYS_msgctl: ::c_long = 304; +pub const SYS_shmat: ::c_long = 305; +pub const SYS_shmdt: ::c_long = 306; +pub const SYS_shmget: ::c_long = 307; +pub const SYS_shmctl: ::c_long = 308; +pub const SYS_add_key: ::c_long = 309; +pub const SYS_request_key: ::c_long = 310; +pub const SYS_keyctl: ::c_long = 311; +pub const SYS_semtimedop: ::c_long = 312; +pub const SYS_vserver: ::c_long = 313; +pub const SYS_ioprio_set: ::c_long = 314; +pub const SYS_ioprio_get: ::c_long = 315; +pub const SYS_inotify_init: ::c_long = 316; +pub const SYS_inotify_add_watch: ::c_long = 317; +pub const SYS_inotify_rm_watch: ::c_long = 318; +pub const SYS_mbind: ::c_long = 319; +pub const SYS_get_mempolicy: ::c_long = 320; +pub const SYS_set_mempolicy: ::c_long = 321; +pub const SYS_openat: ::c_long = 322; +pub const SYS_mkdirat: ::c_long = 323; +pub const SYS_mknodat: ::c_long = 324; +pub const SYS_fchownat: ::c_long = 325; +pub const SYS_futimesat: ::c_long = 326; +pub const SYS_fstatat64: ::c_long = 327; +pub const SYS_unlinkat: ::c_long = 328; +pub const SYS_renameat: ::c_long = 329; +pub const SYS_linkat: ::c_long = 330; +pub const SYS_symlinkat: ::c_long = 331; +pub const SYS_readlinkat: ::c_long = 332; +pub const SYS_fchmodat: ::c_long = 333; +pub const SYS_faccessat: ::c_long = 334; +pub const SYS_pselect6: ::c_long = 335; +pub const SYS_ppoll: ::c_long = 336; +pub const SYS_unshare: ::c_long = 337; +pub const SYS_set_robust_list: ::c_long = 338; +pub const SYS_get_robust_list: ::c_long = 339; +pub const SYS_splice: ::c_long = 340; +pub const SYS_arm_sync_file_range: ::c_long = 341; +pub const SYS_tee: ::c_long = 342; +pub const SYS_vmsplice: ::c_long = 343; +pub const SYS_move_pages: ::c_long = 344; +pub const SYS_getcpu: ::c_long = 345; +pub const SYS_epoll_pwait: ::c_long = 346; +pub const SYS_kexec_load: ::c_long = 347; +pub const SYS_utimensat: ::c_long = 348; +pub const SYS_signalfd: ::c_long = 349; +pub const SYS_timerfd_create: ::c_long = 350; +pub const SYS_eventfd: ::c_long = 351; +pub const SYS_fallocate: ::c_long = 352; +pub const SYS_timerfd_settime: ::c_long = 353; +pub const SYS_timerfd_gettime: ::c_long = 354; +pub const SYS_signalfd4: ::c_long = 355; +pub const SYS_eventfd2: ::c_long = 356; +pub const SYS_epoll_create1: ::c_long = 357; +pub const SYS_dup3: ::c_long = 358; +pub const SYS_pipe2: ::c_long = 359; +pub const SYS_inotify_init1: ::c_long = 360; +pub const SYS_preadv: ::c_long = 361; +pub const SYS_pwritev: ::c_long = 362; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 363; +pub const SYS_perf_event_open: ::c_long = 364; +pub const SYS_recvmmsg: ::c_long = 365; +pub const SYS_accept4: ::c_long = 366; +pub const SYS_fanotify_init: ::c_long = 367; +pub const SYS_fanotify_mark: ::c_long = 368; +pub const SYS_prlimit64: ::c_long = 369; +pub const SYS_name_to_handle_at: ::c_long = 370; +pub const SYS_open_by_handle_at: ::c_long = 371; +pub const SYS_clock_adjtime: ::c_long = 372; +pub const SYS_syncfs: ::c_long = 373; +pub const SYS_sendmmsg: ::c_long = 374; +pub const SYS_setns: ::c_long = 375; +pub const SYS_process_vm_readv: ::c_long = 376; +pub const SYS_process_vm_writev: ::c_long = 377; +pub const SYS_kcmp: ::c_long = 378; +pub const SYS_finit_module: ::c_long = 379; +pub const SYS_sched_setattr: ::c_long = 380; +pub const SYS_sched_getattr: ::c_long = 381; +pub const SYS_renameat2: ::c_long = 382; +pub const SYS_seccomp: ::c_long = 383; +pub const SYS_getrandom: ::c_long = 384; +pub const SYS_memfd_create: ::c_long = 385; +pub const SYS_bpf: ::c_long = 386; +pub const SYS_execveat: ::c_long = 387; +pub const SYS_userfaultfd: ::c_long = 388; +pub const SYS_membarrier: ::c_long = 389; +pub const SYS_mlock2: ::c_long = 390; +pub const SYS_copy_file_range: ::c_long = 391; +pub const SYS_preadv2: ::c_long = 392; +pub const SYS_pwritev2: ::c_long = 393; +pub const SYS_pkey_mprotect: ::c_long = 394; +pub const SYS_pkey_alloc: ::c_long = 395; +pub const SYS_pkey_free: ::c_long = 396; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,315 @@ +//! 32-bit specific definitions for linux-like values + +pub type c_long = i32; +pub type c_ulong = u32; +pub type clock_t = i32; +pub type time_t = i32; +pub type suseconds_t = i32; +pub type ino_t = u32; +pub type off_t = i32; +pub type blkcnt_t = i32; +pub type __fsword_t = i32; + +pub type fsblkcnt_t = ::c_ulong; +pub type fsfilcnt_t = ::c_ulong; +pub type rlim_t = c_ulong; +pub type shmatt_t = ::c_ulong; +pub type msgqnum_t = ::c_ulong; +pub type msglen_t = ::c_ulong; +pub type blksize_t = i32; +pub type nlink_t = u32; +pub type __u64 = ::c_ulonglong; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + __pad1: ::c_short, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad2: ::c_short, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused4: ::c_long, + __unused5: ::c_long, + } + + pub struct pthread_attr_t { + __size: [u32; 9] + } + + pub struct sigset_t { + __val: [::c_ulong; 32], + } + + pub struct sysinfo { + pub uptime: ::c_long, + pub loads: [::c_ulong; 3], + pub totalram: ::c_ulong, + pub freeram: ::c_ulong, + pub sharedram: ::c_ulong, + pub bufferram: ::c_ulong, + pub totalswap: ::c_ulong, + pub freeswap: ::c_ulong, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: ::c_ulong, + pub freehigh: ::c_ulong, + pub mem_unit: ::c_uint, + pub _f: [::c_char; 8], + } +} + +pub const TIOCGSOFTCAR: ::c_ulong = 0x5419; +pub const TIOCSSOFTCAR: ::c_ulong = 0x541A; + +pub const RLIMIT_NOFILE: ::c_int = 7; +pub const RLIMIT_NPROC: ::c_int = 6; + +pub const O_APPEND: ::c_int = 1024; +pub const O_CREAT: ::c_int = 64; +pub const O_EXCL: ::c_int = 128; +pub const O_NOCTTY: ::c_int = 256; +pub const O_NONBLOCK: ::c_int = 2048; +pub const O_SYNC: ::c_int = 1052672; +pub const O_RSYNC: ::c_int = 1052672; +pub const O_DSYNC: ::c_int = 4096; +pub const O_FSYNC: ::c_int = 0x101000; +pub const O_NOATIME: ::c_int = 0o1000000; +pub const O_PATH: ::c_int = 0o10000000; +pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; + +pub const MAP_GROWSDOWN: ::c_int = 0x0100; + +pub const EDEADLK: ::c_int = 35; +pub const ENAMETOOLONG: ::c_int = 36; +pub const ENOLCK: ::c_int = 37; +pub const ENOSYS: ::c_int = 38; +pub const ENOTEMPTY: ::c_int = 39; +pub const ELOOP: ::c_int = 40; +pub const ENOMSG: ::c_int = 42; +pub const EIDRM: ::c_int = 43; +pub const ECHRNG: ::c_int = 44; +pub const EL2NSYNC: ::c_int = 45; +pub const EL3HLT: ::c_int = 46; +pub const EL3RST: ::c_int = 47; +pub const ELNRNG: ::c_int = 48; +pub const EUNATCH: ::c_int = 49; +pub const ENOCSI: ::c_int = 50; +pub const EL2HLT: ::c_int = 51; +pub const EBADE: ::c_int = 52; +pub const EBADR: ::c_int = 53; +pub const EXFULL: ::c_int = 54; +pub const ENOANO: ::c_int = 55; +pub const EBADRQC: ::c_int = 56; +pub const EBADSLT: ::c_int = 57; +pub const EMULTIHOP: ::c_int = 72; +pub const EOVERFLOW: ::c_int = 75; +pub const ENOTUNIQ: ::c_int = 76; +pub const EBADFD: ::c_int = 77; +pub const EBADMSG: ::c_int = 74; +pub const EREMCHG: ::c_int = 78; +pub const ELIBACC: ::c_int = 79; +pub const ELIBBAD: ::c_int = 80; +pub const ELIBSCN: ::c_int = 81; +pub const ELIBMAX: ::c_int = 82; +pub const ELIBEXEC: ::c_int = 83; +pub const EILSEQ: ::c_int = 84; +pub const ERESTART: ::c_int = 85; +pub const ESTRPIPE: ::c_int = 86; +pub const EUSERS: ::c_int = 87; +pub const ENOTSOCK: ::c_int = 88; +pub const EDESTADDRREQ: ::c_int = 89; +pub const EMSGSIZE: ::c_int = 90; +pub const EPROTOTYPE: ::c_int = 91; +pub const ENOPROTOOPT: ::c_int = 92; +pub const EPROTONOSUPPORT: ::c_int = 93; +pub const ESOCKTNOSUPPORT: ::c_int = 94; +pub const EOPNOTSUPP: ::c_int = 95; +pub const EPFNOSUPPORT: ::c_int = 96; +pub const EAFNOSUPPORT: ::c_int = 97; +pub const EADDRINUSE: ::c_int = 98; +pub const EADDRNOTAVAIL: ::c_int = 99; +pub const ENETDOWN: ::c_int = 100; +pub const ENETUNREACH: ::c_int = 101; +pub const ENETRESET: ::c_int = 102; +pub const ECONNABORTED: ::c_int = 103; +pub const ECONNRESET: ::c_int = 104; +pub const ENOBUFS: ::c_int = 105; +pub const EISCONN: ::c_int = 106; +pub const ENOTCONN: ::c_int = 107; +pub const ESHUTDOWN: ::c_int = 108; +pub const ETOOMANYREFS: ::c_int = 109; +pub const ETIMEDOUT: ::c_int = 110; +pub const ECONNREFUSED: ::c_int = 111; +pub const EHOSTDOWN: ::c_int = 112; +pub const EHOSTUNREACH: ::c_int = 113; +pub const EALREADY: ::c_int = 114; +pub const EINPROGRESS: ::c_int = 115; +pub const ESTALE: ::c_int = 116; +pub const EDQUOT: ::c_int = 122; +pub const ENOMEDIUM: ::c_int = 123; +pub const EMEDIUMTYPE: ::c_int = 124; +pub const ECANCELED: ::c_int = 125; +pub const ENOKEY: ::c_int = 126; +pub const EKEYEXPIRED: ::c_int = 127; +pub const EKEYREVOKED: ::c_int = 128; +pub const EKEYREJECTED: ::c_int = 129; +pub const EOWNERDEAD: ::c_int = 130; +pub const ENOTRECOVERABLE: ::c_int = 131; +pub const EHWPOISON: ::c_int = 133; +pub const ERFKILL: ::c_int = 132; + +pub const SOL_SOCKET: ::c_int = 1; + +pub const SO_REUSEADDR: ::c_int = 2; +pub const SO_TYPE: ::c_int = 3; +pub const SO_ERROR: ::c_int = 4; +pub const SO_DONTROUTE: ::c_int = 5; +pub const SO_BROADCAST: ::c_int = 6; +pub const SO_SNDBUF: ::c_int = 7; +pub const SO_RCVBUF: ::c_int = 8; +pub const SO_KEEPALIVE: ::c_int = 9; +pub const SO_OOBINLINE: ::c_int = 10; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_LINGER: ::c_int = 13; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_REUSEPORT: ::c_int = 15; +pub const SO_BINDTODEVICE: ::c_int = 25; +pub const SO_TIMESTAMP: ::c_int = 29; +pub const SO_ACCEPTCONN: ::c_int = 30; +pub const SO_MARK: ::c_int = 36; +pub const SO_PROTOCOL: ::c_int = 38; +pub const SO_DOMAIN: ::c_int = 39; +pub const SO_RXQ_OVFL: ::c_int = 40; +pub const SO_PEEK_OFF: ::c_int = 42; +pub const SO_BUSY_POLL: ::c_int = 46; + +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 0x00000004; +pub const SA_NOCLDWAIT: ::c_int = 0x00000002; + +pub const SIGCHLD: ::c_int = 17; +pub const SIGBUS: ::c_int = 7; +pub const SIGUSR1: ::c_int = 10; +pub const SIGUSR2: ::c_int = 12; +pub const SIGCONT: ::c_int = 18; +pub const SIGSTOP: ::c_int = 19; +pub const SIGTSTP: ::c_int = 20; +pub const SIGURG: ::c_int = 23; +pub const SIGIO: ::c_int = 29; +pub const SIGSYS: ::c_int = 31; +pub const SIGSTKFLT: ::c_int = 16; +pub const SIGUNUSED: ::c_int = 31; +pub const SIGPOLL: ::c_int = 29; +pub const SIGPWR: ::c_int = 30; +pub const SIG_SETMASK: ::c_int = 2; +pub const SIG_BLOCK: ::c_int = 0x000000; +pub const SIG_UNBLOCK: ::c_int = 0x01; + +pub const POLLWRNORM: ::c_short = 0x100; +pub const POLLWRBAND: ::c_short = 0x200; + +pub const O_ASYNC: ::c_int = 0x2000; +pub const O_NDELAY: ::c_int = 0x800; + +pub const PTRACE_DETACH: ::c_uint = 17; + +pub const EFD_NONBLOCK: ::c_int = 0x800; + +pub const F_GETLK: ::c_int = 5; +pub const F_GETOWN: ::c_int = 9; +pub const F_SETOWN: ::c_int = 8; +pub const F_SETLK: ::c_int = 6; +pub const F_SETLKW: ::c_int = 7; + +pub const SFD_NONBLOCK: ::c_int = 0x0800; + +pub const TIOCEXCL: ::c_ulong = 0x540C; +pub const TIOCNXCL: ::c_ulong = 0x540D; +pub const TIOCSCTTY: ::c_ulong = 0x540E; +pub const TIOCSTI: ::c_ulong = 0x5412; +pub const TIOCMGET: ::c_ulong = 0x5415; +pub const TIOCMBIS: ::c_ulong = 0x5416; +pub const TIOCMBIC: ::c_ulong = 0x5417; +pub const TIOCMSET: ::c_ulong = 0x5418; +pub const TIOCCONS: ::c_ulong = 0x541D; + +pub const SFD_CLOEXEC: ::c_int = 0x080000; + +pub const NCCS: usize = 32; + +pub const O_TRUNC: ::c_int = 512; + +pub const O_CLOEXEC: ::c_int = 0x80000; + +pub const EBFONT: ::c_int = 59; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const EDOTDOT: ::c_int = 73; + +pub const SA_NODEFER: ::c_int = 0x40000000; +pub const SA_RESETHAND: ::c_int = 0x80000000; +pub const SA_RESTART: ::c_int = 0x10000000; +pub const SA_NOCLDSTOP: ::c_int = 0x00000001; + +pub const EPOLL_CLOEXEC: ::c_int = 0x80000; + +pub const EFD_CLOEXEC: ::c_int = 0x80000; + +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 24; +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 32; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; + +pub const PTRACE_GETFPREGS: ::c_uint = 14; +pub const PTRACE_SETFPREGS: ::c_uint = 15; +pub const PTRACE_GETREGS: ::c_uint = 12; +pub const PTRACE_SETREGS: ::c_uint = 13; + +#[link(name = "util")] +extern { + pub fn sysctl(name: *mut ::c_int, + namelen: ::c_int, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *mut ::c_void, + newlen: ::size_t) + -> ::c_int; +} + +cfg_if! { + if #[cfg(target_arch = "x86")] { + mod x86; + pub use self::x86::*; + } else if #[cfg(target_arch = "arm")] { + mod arm; + pub use self::arm::*; + } else if #[cfg(target_arch = "powerpc")] { + mod powerpc; + pub use self::powerpc::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/powerpc.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/powerpc.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/powerpc.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/powerpc.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,614 @@ +pub type c_char = u8; +pub type wchar_t = i32; + +s! { + pub struct ipc_perm { + __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + __seq: ::uint32_t, + __pad1: ::uint32_t, + __glibc_reserved1: ::uint64_t, + __glibc_reserved2: ::uint64_t, + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino64_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad2: ::c_ushort, + pub st_size: ::off64_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __glibc_reserved4: ::c_ulong, + __glibc_reserved5: ::c_ulong, + } + + pub struct statfs64 { + pub f_type: ::__fsword_t, + pub f_bsize: ::__fsword_t, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_fsid: ::fsid_t, + pub f_namelen: ::__fsword_t, + pub f_frsize: ::__fsword_t, + pub f_flags: ::__fsword_t, + pub f_spare: [::__fsword_t; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + __f_unused: ::c_int, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + __glibc_reserved1: ::c_uint, + pub shm_atime: ::time_t, + __glibc_reserved2: ::c_uint, + pub shm_dtime: ::time_t, + __glibc_reserved3: ::c_uint, + pub shm_ctime: ::time_t, + __glibc_reserved4: ::c_uint, + pub shm_segsz: ::size_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __glibc_reserved5: ::c_ulong, + __glibc_reserved6: ::c_ulong, + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + __glibc_reserved1: ::c_uint, + pub msg_stime: ::time_t, + __glibc_reserved2: ::c_uint, + pub msg_rtime: ::time_t, + __glibc_reserved3: ::c_uint, + pub msg_ctime: ::time_t, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __glibc_reserved4: ::c_ulong, + __glibc_reserved5: ::c_ulong, + } +} + +pub const O_DIRECT: ::c_int = 0x20000; +pub const O_DIRECTORY: ::c_int = 0x4000; +pub const O_NOFOLLOW: ::c_int = 0x8000; +pub const O_LARGEFILE: ::c_int = 0o200000; + +pub const MAP_LOCKED: ::c_int = 0x00080; +pub const MAP_NORESERVE: ::c_int = 0x00040; + +pub const EDEADLOCK: ::c_int = 58; + +pub const SO_SNDBUFFORCE: ::c_int = 32; +pub const SO_RCVBUFFORCE: ::c_int = 33; +pub const SO_NO_CHECK: ::c_int = 11; +pub const SO_RCVLOWAT: ::c_int = 16; +pub const SO_SNDLOWAT: ::c_int = 17; +pub const SO_RCVTIMEO: ::c_int = 18; +pub const SO_SNDTIMEO: ::c_int = 19; +pub const SO_PASSCRED: ::c_int = 20; +pub const SO_PEERCRED: ::c_int = 21; + +pub const FIOCLEX: ::c_ulong = 0x20006601; +pub const FIONBIO: ::c_ulong = 0x8004667e; + +pub const MCL_CURRENT: ::c_int = 0x2000; +pub const MCL_FUTURE: ::c_int = 0x4000; + +pub const SIGSTKSZ: ::size_t = 0x4000; +pub const MINSIGSTKSZ: ::size_t = 4096; +pub const CBAUD: ::tcflag_t = 0xff; +pub const TAB1: ::c_int = 0x400; +pub const TAB2: ::c_int = 0x800; +pub const TAB3: ::c_int = 0xc00; +pub const CR1: ::c_int = 0x1000; +pub const CR2: ::c_int = 0x2000; +pub const CR3: ::c_int = 0x3000; +pub const FF1: ::c_int = 0x4000; +pub const BS1: ::c_int = 0x8000; +pub const VT1: ::c_int = 0x10000; +pub const VWERASE: usize = 0xa; +pub const VREPRINT: usize = 0xb; +pub const VSUSP: usize = 0xc; +pub const VSTART: usize = 0xd; +pub const VSTOP: usize = 0xe; +pub const VDISCARD: usize = 0x10; +pub const VTIME: usize = 0x7; +pub const IXON: ::tcflag_t = 0x200; +pub const IXOFF: ::tcflag_t = 0x400; +pub const ONLCR: ::tcflag_t = 0x2; +pub const CSIZE: ::tcflag_t = 0x300; +pub const CS6: ::tcflag_t = 0x100; +pub const CS7: ::tcflag_t = 0x200; +pub const CS8: ::tcflag_t = 0x300; +pub const CSTOPB: ::tcflag_t = 0x400; +pub const CREAD: ::tcflag_t = 0x800; +pub const PARENB: ::tcflag_t = 0x1000; +pub const PARODD: ::tcflag_t = 0x2000; +pub const HUPCL: ::tcflag_t = 0x4000; +pub const CLOCAL: ::tcflag_t = 0x8000; +pub const ECHOKE: ::tcflag_t = 0x1; +pub const ECHOE: ::tcflag_t = 0x2; +pub const ECHOK: ::tcflag_t = 0x4; +pub const ECHONL: ::tcflag_t = 0x10; +pub const ECHOPRT: ::tcflag_t = 0x20; +pub const ECHOCTL: ::tcflag_t = 0x40; +pub const ISIG: ::tcflag_t = 0x80; +pub const ICANON: ::tcflag_t = 0x100; +pub const PENDIN: ::tcflag_t = 0x20000000; +pub const NOFLSH: ::tcflag_t = 0x80000000; +pub const VSWTC: usize = 9; +pub const OLCUC: ::tcflag_t = 0o000004; +pub const NLDLY: ::tcflag_t = 0o001400; +pub const CRDLY: ::tcflag_t = 0o030000; +pub const TABDLY: ::tcflag_t = 0o006000; +pub const BSDLY: ::tcflag_t = 0o100000; +pub const FFDLY: ::tcflag_t = 0o040000; +pub const VTDLY: ::tcflag_t = 0o200000; +pub const XTABS: ::tcflag_t = 0o006000; + +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const CBAUDEX: ::speed_t = 0o000020; +pub const B57600: ::speed_t = 0o0020; +pub const B115200: ::speed_t = 0o0021; +pub const B230400: ::speed_t = 0o0022; +pub const B460800: ::speed_t = 0o0023; +pub const B500000: ::speed_t = 0o0024; +pub const B576000: ::speed_t = 0o0025; +pub const B921600: ::speed_t = 0o0026; +pub const B1000000: ::speed_t = 0o0027; +pub const B1152000: ::speed_t = 0o0030; +pub const B1500000: ::speed_t = 0o0031; +pub const B2000000: ::speed_t = 0o0032; +pub const B2500000: ::speed_t = 0o0033; +pub const B3000000: ::speed_t = 0o0034; +pub const B3500000: ::speed_t = 0o0035; +pub const B4000000: ::speed_t = 0o0036; +pub const BOTHER: ::speed_t = 0o0037; + +pub const VEOL: usize = 6; +pub const VEOL2: usize = 8; +pub const VMIN: usize = 5; +pub const IEXTEN: ::tcflag_t = 0x400; +pub const TOSTOP: ::tcflag_t = 0x400000; +pub const FLUSHO: ::tcflag_t = 0x800000; +pub const EXTPROC: ::tcflag_t = 0x10000000; +pub const TCGETS: ::c_ulong = 0x403c7413; +pub const TCSETS: ::c_ulong = 0x803c7414; +pub const TCSETSW: ::c_ulong = 0x803c7415; +pub const TCSETSF: ::c_ulong = 0x803c7416; +pub const TCGETA: ::c_ulong = 0x40147417; +pub const TCSETA: ::c_ulong = 0x80147418; +pub const TCSETAW: ::c_ulong = 0x80147419; +pub const TCSETAF: ::c_ulong = 0x8014741c; +pub const TCSBRK: ::c_ulong = 0x2000741d; +pub const TCXONC: ::c_ulong = 0x2000741e; +pub const TCFLSH: ::c_ulong = 0x2000741f; +pub const TIOCINQ: ::c_ulong = 0x4004667f; +pub const TIOCGPGRP: ::c_ulong = 0x40047477; +pub const TIOCSPGRP: ::c_ulong = 0x80047476; +pub const TIOCOUTQ: ::c_ulong = 0x40047473; +pub const TIOCGWINSZ: ::c_ulong = 0x40087468; +pub const TIOCSWINSZ: ::c_ulong = 0x80087467; +pub const FIONREAD: ::c_ulong = 0x4004667f; + +pub const SYS_restart_syscall: ::c_long = 0; +pub const SYS_exit: ::c_long = 1; +pub const SYS_fork: ::c_long = 2; +pub const SYS_read: ::c_long = 3; +pub const SYS_write: ::c_long = 4; +pub const SYS_open: ::c_long = 5; +pub const SYS_close: ::c_long = 6; +pub const SYS_waitpid: ::c_long = 7; +pub const SYS_creat: ::c_long = 8; +pub const SYS_link: ::c_long = 9; +pub const SYS_unlink: ::c_long = 10; +pub const SYS_execve: ::c_long = 11; +pub const SYS_chdir: ::c_long = 12; +pub const SYS_time: ::c_long = 13; +pub const SYS_mknod: ::c_long = 14; +pub const SYS_chmod: ::c_long = 15; +pub const SYS_lchown: ::c_long = 16; +pub const SYS_break: ::c_long = 17; +pub const SYS_oldstat: ::c_long = 18; +pub const SYS_lseek: ::c_long = 19; +pub const SYS_getpid: ::c_long = 20; +pub const SYS_mount: ::c_long = 21; +pub const SYS_umount: ::c_long = 22; +pub const SYS_setuid: ::c_long = 23; +pub const SYS_getuid: ::c_long = 24; +pub const SYS_stime: ::c_long = 25; +pub const SYS_ptrace: ::c_long = 26; +pub const SYS_alarm: ::c_long = 27; +pub const SYS_oldfstat: ::c_long = 28; +pub const SYS_pause: ::c_long = 29; +pub const SYS_utime: ::c_long = 30; +pub const SYS_stty: ::c_long = 31; +pub const SYS_gtty: ::c_long = 32; +pub const SYS_access: ::c_long = 33; +pub const SYS_nice: ::c_long = 34; +pub const SYS_ftime: ::c_long = 35; +pub const SYS_sync: ::c_long = 36; +pub const SYS_kill: ::c_long = 37; +pub const SYS_rename: ::c_long = 38; +pub const SYS_mkdir: ::c_long = 39; +pub const SYS_rmdir: ::c_long = 40; +pub const SYS_dup: ::c_long = 41; +pub const SYS_pipe: ::c_long = 42; +pub const SYS_times: ::c_long = 43; +pub const SYS_prof: ::c_long = 44; +pub const SYS_brk: ::c_long = 45; +pub const SYS_setgid: ::c_long = 46; +pub const SYS_getgid: ::c_long = 47; +pub const SYS_signal: ::c_long = 48; +pub const SYS_geteuid: ::c_long = 49; +pub const SYS_getegid: ::c_long = 50; +pub const SYS_acct: ::c_long = 51; +pub const SYS_umount2: ::c_long = 52; +pub const SYS_lock: ::c_long = 53; +pub const SYS_ioctl: ::c_long = 54; +pub const SYS_fcntl: ::c_long = 55; +pub const SYS_mpx: ::c_long = 56; +pub const SYS_setpgid: ::c_long = 57; +pub const SYS_ulimit: ::c_long = 58; +pub const SYS_oldolduname: ::c_long = 59; +pub const SYS_umask: ::c_long = 60; +pub const SYS_chroot: ::c_long = 61; +pub const SYS_ustat: ::c_long = 62; +pub const SYS_dup2: ::c_long = 63; +pub const SYS_getppid: ::c_long = 64; +pub const SYS_getpgrp: ::c_long = 65; +pub const SYS_setsid: ::c_long = 66; +pub const SYS_sigaction: ::c_long = 67; +pub const SYS_sgetmask: ::c_long = 68; +pub const SYS_ssetmask: ::c_long = 69; +pub const SYS_setreuid: ::c_long = 70; +pub const SYS_setregid: ::c_long = 71; +pub const SYS_sigsuspend: ::c_long = 72; +pub const SYS_sigpending: ::c_long = 73; +pub const SYS_sethostname: ::c_long = 74; +pub const SYS_setrlimit: ::c_long = 75; +pub const SYS_getrlimit: ::c_long = 76; +pub const SYS_getrusage: ::c_long = 77; +pub const SYS_gettimeofday: ::c_long = 78; +pub const SYS_settimeofday: ::c_long = 79; +pub const SYS_getgroups: ::c_long = 80; +pub const SYS_setgroups: ::c_long = 81; +pub const SYS_select: ::c_long = 82; +pub const SYS_symlink: ::c_long = 83; +pub const SYS_oldlstat: ::c_long = 84; +pub const SYS_readlink: ::c_long = 85; +pub const SYS_uselib: ::c_long = 86; +pub const SYS_swapon: ::c_long = 87; +pub const SYS_reboot: ::c_long = 88; +pub const SYS_readdir: ::c_long = 89; +pub const SYS_mmap: ::c_long = 90; +pub const SYS_munmap: ::c_long = 91; +pub const SYS_truncate: ::c_long = 92; +pub const SYS_ftruncate: ::c_long = 93; +pub const SYS_fchmod: ::c_long = 94; +pub const SYS_fchown: ::c_long = 95; +pub const SYS_getpriority: ::c_long = 96; +pub const SYS_setpriority: ::c_long = 97; +pub const SYS_profil: ::c_long = 98; +pub const SYS_statfs: ::c_long = 99; +pub const SYS_fstatfs: ::c_long = 100; +pub const SYS_ioperm: ::c_long = 101; +pub const SYS_socketcall: ::c_long = 102; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_setitimer: ::c_long = 104; +pub const SYS_getitimer: ::c_long = 105; +pub const SYS_stat: ::c_long = 106; +pub const SYS_lstat: ::c_long = 107; +pub const SYS_fstat: ::c_long = 108; +pub const SYS_olduname: ::c_long = 109; +pub const SYS_iopl: ::c_long = 110; +pub const SYS_vhangup: ::c_long = 111; +pub const SYS_idle: ::c_long = 112; +pub const SYS_vm86: ::c_long = 113; +pub const SYS_wait4: ::c_long = 114; +pub const SYS_swapoff: ::c_long = 115; +pub const SYS_sysinfo: ::c_long = 116; +pub const SYS_ipc: ::c_long = 117; +pub const SYS_fsync: ::c_long = 118; +pub const SYS_sigreturn: ::c_long = 119; +pub const SYS_clone: ::c_long = 120; +pub const SYS_setdomainname: ::c_long = 121; +pub const SYS_uname: ::c_long = 122; +pub const SYS_modify_ldt: ::c_long = 123; +pub const SYS_adjtimex: ::c_long = 124; +pub const SYS_mprotect: ::c_long = 125; +pub const SYS_sigprocmask: ::c_long = 126; +pub const SYS_create_module: ::c_long = 127; +pub const SYS_init_module: ::c_long = 128; +pub const SYS_delete_module: ::c_long = 129; +pub const SYS_get_kernel_syms: ::c_long = 130; +pub const SYS_quotactl: ::c_long = 131; +pub const SYS_getpgid: ::c_long = 132; +pub const SYS_fchdir: ::c_long = 133; +pub const SYS_bdflush: ::c_long = 134; +pub const SYS_sysfs: ::c_long = 135; +pub const SYS_personality: ::c_long = 136; +pub const SYS_afs_syscall: ::c_long = 137; /* Syscall for Andrew File System */ +pub const SYS_setfsuid: ::c_long = 138; +pub const SYS_setfsgid: ::c_long = 139; +pub const SYS__llseek: ::c_long = 140; +pub const SYS_getdents: ::c_long = 141; +pub const SYS__newselect: ::c_long = 142; +pub const SYS_flock: ::c_long = 143; +pub const SYS_msync: ::c_long = 144; +pub const SYS_readv: ::c_long = 145; +pub const SYS_writev: ::c_long = 146; +pub const SYS_getsid: ::c_long = 147; +pub const SYS_fdatasync: ::c_long = 148; +pub const SYS__sysctl: ::c_long = 149; +pub const SYS_mlock: ::c_long = 150; +pub const SYS_munlock: ::c_long = 151; +pub const SYS_mlockall: ::c_long = 152; +pub const SYS_munlockall: ::c_long = 153; +pub const SYS_sched_setparam: ::c_long = 154; +pub const SYS_sched_getparam: ::c_long = 155; +pub const SYS_sched_setscheduler: ::c_long = 156; +pub const SYS_sched_getscheduler: ::c_long = 157; +pub const SYS_sched_yield: ::c_long = 158; +pub const SYS_sched_get_priority_max: ::c_long = 159; +pub const SYS_sched_get_priority_min: ::c_long = 160; +pub const SYS_sched_rr_get_interval: ::c_long = 161; +pub const SYS_nanosleep: ::c_long = 162; +pub const SYS_mremap: ::c_long = 163; +pub const SYS_setresuid: ::c_long = 164; +pub const SYS_getresuid: ::c_long = 165; +pub const SYS_query_module: ::c_long = 166; +pub const SYS_poll: ::c_long = 167; +pub const SYS_nfsservctl: ::c_long = 168; +pub const SYS_setresgid: ::c_long = 169; +pub const SYS_getresgid: ::c_long = 170; +pub const SYS_prctl: ::c_long = 171; +pub const SYS_rt_sigreturn: ::c_long = 172; +pub const SYS_rt_sigaction: ::c_long = 173; +pub const SYS_rt_sigprocmask: ::c_long = 174; +pub const SYS_rt_sigpending: ::c_long = 175; +pub const SYS_rt_sigtimedwait: ::c_long = 176; +pub const SYS_rt_sigqueueinfo: ::c_long = 177; +pub const SYS_rt_sigsuspend: ::c_long = 178; +pub const SYS_pread64: ::c_long = 179; +pub const SYS_pwrite64: ::c_long = 180; +pub const SYS_chown: ::c_long = 181; +pub const SYS_getcwd: ::c_long = 182; +pub const SYS_capget: ::c_long = 183; +pub const SYS_capset: ::c_long = 184; +pub const SYS_sigaltstack: ::c_long = 185; +pub const SYS_sendfile: ::c_long = 186; +pub const SYS_getpmsg: ::c_long = 187; /* some people actually want streams */ +pub const SYS_putpmsg: ::c_long = 188; /* some people actually want streams */ +pub const SYS_vfork: ::c_long = 189; +pub const SYS_ugetrlimit: ::c_long = 190; /* SuS compliant getrlimit */ +pub const SYS_readahead: ::c_long = 191; +pub const SYS_mmap2: ::c_long = 192; +pub const SYS_truncate64: ::c_long = 193; +pub const SYS_ftruncate64: ::c_long = 194; +pub const SYS_stat64: ::c_long = 195; +pub const SYS_lstat64: ::c_long = 196; +pub const SYS_fstat64: ::c_long = 197; +pub const SYS_pciconfig_read: ::c_long = 198; +pub const SYS_pciconfig_write: ::c_long = 199; +pub const SYS_pciconfig_iobase: ::c_long = 200; +pub const SYS_multiplexer: ::c_long = 201; +pub const SYS_getdents64: ::c_long = 202; +pub const SYS_pivot_root: ::c_long = 203; +pub const SYS_fcntl64: ::c_long = 204; +pub const SYS_madvise: ::c_long = 205; +pub const SYS_mincore: ::c_long = 206; +pub const SYS_gettid: ::c_long = 207; +pub const SYS_tkill: ::c_long = 208; +pub const SYS_setxattr: ::c_long = 209; +pub const SYS_lsetxattr: ::c_long = 210; +pub const SYS_fsetxattr: ::c_long = 211; +pub const SYS_getxattr: ::c_long = 212; +pub const SYS_lgetxattr: ::c_long = 213; +pub const SYS_fgetxattr: ::c_long = 214; +pub const SYS_listxattr: ::c_long = 215; +pub const SYS_llistxattr: ::c_long = 216; +pub const SYS_flistxattr: ::c_long = 217; +pub const SYS_removexattr: ::c_long = 218; +pub const SYS_lremovexattr: ::c_long = 219; +pub const SYS_fremovexattr: ::c_long = 220; +pub const SYS_futex: ::c_long = 221; +pub const SYS_sched_setaffinity: ::c_long = 222; +pub const SYS_sched_getaffinity: ::c_long = 223; +pub const SYS_tuxcall: ::c_long = 225; +pub const SYS_sendfile64: ::c_long = 226; +pub const SYS_io_setup: ::c_long = 227; +pub const SYS_io_destroy: ::c_long = 228; +pub const SYS_io_getevents: ::c_long = 229; +pub const SYS_io_submit: ::c_long = 230; +pub const SYS_io_cancel: ::c_long = 231; +pub const SYS_set_tid_address: ::c_long = 232; +pub const SYS_fadvise64: ::c_long = 233; +pub const SYS_exit_group: ::c_long = 234; +pub const SYS_lookup_dcookie: ::c_long = 235; +pub const SYS_epoll_create: ::c_long = 236; +pub const SYS_epoll_ctl: ::c_long = 237; +pub const SYS_epoll_wait: ::c_long = 238; +pub const SYS_remap_file_pages: ::c_long = 239; +pub const SYS_timer_create: ::c_long = 240; +pub const SYS_timer_settime: ::c_long = 241; +pub const SYS_timer_gettime: ::c_long = 242; +pub const SYS_timer_getoverrun: ::c_long = 243; +pub const SYS_timer_delete: ::c_long = 244; +pub const SYS_clock_settime: ::c_long = 245; +pub const SYS_clock_gettime: ::c_long = 246; +pub const SYS_clock_getres: ::c_long = 247; +pub const SYS_clock_nanosleep: ::c_long = 248; +pub const SYS_swapcontext: ::c_long = 249; +pub const SYS_tgkill: ::c_long = 250; +pub const SYS_utimes: ::c_long = 251; +pub const SYS_statfs64: ::c_long = 252; +pub const SYS_fstatfs64: ::c_long = 253; +pub const SYS_fadvise64_64: ::c_long = 254; +pub const SYS_rtas: ::c_long = 255; +pub const SYS_sys_debug_setcontext: ::c_long = 256; +pub const SYS_migrate_pages: ::c_long = 258; +pub const SYS_mbind: ::c_long = 259; +pub const SYS_get_mempolicy: ::c_long = 260; +pub const SYS_set_mempolicy: ::c_long = 261; +pub const SYS_mq_open: ::c_long = 262; +pub const SYS_mq_unlink: ::c_long = 263; +pub const SYS_mq_timedsend: ::c_long = 264; +pub const SYS_mq_timedreceive: ::c_long = 265; +pub const SYS_mq_notify: ::c_long = 266; +pub const SYS_mq_getsetattr: ::c_long = 267; +pub const SYS_kexec_load: ::c_long = 268; +pub const SYS_add_key: ::c_long = 269; +pub const SYS_request_key: ::c_long = 270; +pub const SYS_keyctl: ::c_long = 271; +pub const SYS_waitid: ::c_long = 272; +pub const SYS_ioprio_set: ::c_long = 273; +pub const SYS_ioprio_get: ::c_long = 274; +pub const SYS_inotify_init: ::c_long = 275; +pub const SYS_inotify_add_watch: ::c_long = 276; +pub const SYS_inotify_rm_watch: ::c_long = 277; +pub const SYS_spu_run: ::c_long = 278; +pub const SYS_spu_create: ::c_long = 279; +pub const SYS_pselect6: ::c_long = 280; +pub const SYS_ppoll: ::c_long = 281; +pub const SYS_unshare: ::c_long = 282; +pub const SYS_splice: ::c_long = 283; +pub const SYS_tee: ::c_long = 284; +pub const SYS_vmsplice: ::c_long = 285; +pub const SYS_openat: ::c_long = 286; +pub const SYS_mkdirat: ::c_long = 287; +pub const SYS_mknodat: ::c_long = 288; +pub const SYS_fchownat: ::c_long = 289; +pub const SYS_futimesat: ::c_long = 290; +pub const SYS_fstatat64: ::c_long = 291; +pub const SYS_unlinkat: ::c_long = 292; +pub const SYS_renameat: ::c_long = 293; +pub const SYS_linkat: ::c_long = 294; +pub const SYS_symlinkat: ::c_long = 295; +pub const SYS_readlinkat: ::c_long = 296; +pub const SYS_fchmodat: ::c_long = 297; +pub const SYS_faccessat: ::c_long = 298; +pub const SYS_get_robust_list: ::c_long = 299; +pub const SYS_set_robust_list: ::c_long = 300; +pub const SYS_move_pages: ::c_long = 301; +pub const SYS_getcpu: ::c_long = 302; +pub const SYS_epoll_pwait: ::c_long = 303; +pub const SYS_utimensat: ::c_long = 304; +pub const SYS_signalfd: ::c_long = 305; +pub const SYS_timerfd_create: ::c_long = 306; +pub const SYS_eventfd: ::c_long = 307; +pub const SYS_sync_file_range2: ::c_long = 308; +pub const SYS_fallocate: ::c_long = 309; +pub const SYS_subpage_prot: ::c_long = 310; +pub const SYS_timerfd_settime: ::c_long = 311; +pub const SYS_timerfd_gettime: ::c_long = 312; +pub const SYS_signalfd4: ::c_long = 313; +pub const SYS_eventfd2: ::c_long = 314; +pub const SYS_epoll_create1: ::c_long = 315; +pub const SYS_dup3: ::c_long = 316; +pub const SYS_pipe2: ::c_long = 317; +pub const SYS_inotify_init1: ::c_long = 318; +pub const SYS_perf_event_open: ::c_long = 319; +pub const SYS_preadv: ::c_long = 320; +pub const SYS_pwritev: ::c_long = 321; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 322; +pub const SYS_fanotify_init: ::c_long = 323; +pub const SYS_fanotify_mark: ::c_long = 324; +pub const SYS_prlimit64: ::c_long = 325; +pub const SYS_socket: ::c_long = 326; +pub const SYS_bind: ::c_long = 327; +pub const SYS_connect: ::c_long = 328; +pub const SYS_listen: ::c_long = 329; +pub const SYS_accept: ::c_long = 330; +pub const SYS_getsockname: ::c_long = 331; +pub const SYS_getpeername: ::c_long = 332; +pub const SYS_socketpair: ::c_long = 333; +pub const SYS_send: ::c_long = 334; +pub const SYS_sendto: ::c_long = 335; +pub const SYS_recv: ::c_long = 336; +pub const SYS_recvfrom: ::c_long = 337; +pub const SYS_shutdown: ::c_long = 338; +pub const SYS_setsockopt: ::c_long = 339; +pub const SYS_getsockopt: ::c_long = 340; +pub const SYS_sendmsg: ::c_long = 341; +pub const SYS_recvmsg: ::c_long = 342; +pub const SYS_recvmmsg: ::c_long = 343; +pub const SYS_accept4: ::c_long = 344; +pub const SYS_name_to_handle_at: ::c_long = 345; +pub const SYS_open_by_handle_at: ::c_long = 346; +pub const SYS_clock_adjtime: ::c_long = 347; +pub const SYS_syncfs: ::c_long = 348; +pub const SYS_sendmmsg: ::c_long = 349; +pub const SYS_setns: ::c_long = 350; +pub const SYS_process_vm_readv: ::c_long = 351; +pub const SYS_process_vm_writev: ::c_long = 352; +pub const SYS_finit_module: ::c_long = 353; +pub const SYS_kcmp: ::c_long = 354; +pub const SYS_sched_setattr: ::c_long = 355; +pub const SYS_sched_getattr: ::c_long = 356; +pub const SYS_renameat2: ::c_long = 357; +pub const SYS_seccomp: ::c_long = 358; +pub const SYS_getrandom: ::c_long = 359; +pub const SYS_memfd_create: ::c_long = 360; +pub const SYS_bpf: ::c_long = 361; +pub const SYS_execveat: ::c_long = 362; +pub const SYS_switch_endian: ::c_long = 363; +pub const SYS_userfaultfd: ::c_long = 364; +pub const SYS_membarrier: ::c_long = 365; +pub const SYS_mlock2: ::c_long = 378; +pub const SYS_copy_file_range: ::c_long = 379; +pub const SYS_preadv2: ::c_long = 380; +pub const SYS_pwritev2: ::c_long = 381; +pub const SYS_kexec_file_load: ::c_long = 382; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/x86.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/x86.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/x86.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b32/x86.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,769 @@ +pub type c_char = i8; +pub type wchar_t = i32; +pub type greg_t = i32; + +s! { + pub struct _libc_fpreg { + pub significand: [u16; 4], + pub exponent: u16, + } + + pub struct _libc_fpstate { + pub cw: ::c_ulong, + pub sw: ::c_ulong, + pub tag: ::c_ulong, + pub ipoff: ::c_ulong, + pub cssel: ::c_ulong, + pub dataoff: ::c_ulong, + pub datasel: ::c_ulong, + pub _st: [_libc_fpreg; 8], + pub status: ::c_ulong, + } + + pub struct user_fpregs_struct { + pub cwd: ::c_long, + pub swd: ::c_long, + pub twd: ::c_long, + pub fip: ::c_long, + pub fcs: ::c_long, + pub foo: ::c_long, + pub fos: ::c_long, + pub st_space: [::c_long; 20], + } + + pub struct user_fpxregs_struct { + pub cwd: ::c_ushort, + pub swd: ::c_ushort, + pub twd: ::c_ushort, + pub fop: ::c_ushort, + pub fip: ::c_long, + pub fcs: ::c_long, + pub foo: ::c_long, + pub fos: ::c_long, + pub mxcsr: ::c_long, + __reserved: ::c_long, + pub st_space: [::c_long; 32], + pub xmm_space: [::c_long; 32], + padding: [::c_long; 56], + } + + pub struct user_regs_struct { + pub ebx: ::c_long, + pub ecx: ::c_long, + pub edx: ::c_long, + pub esi: ::c_long, + pub edi: ::c_long, + pub ebp: ::c_long, + pub eax: ::c_long, + pub xds: ::c_long, + pub xes: ::c_long, + pub xfs: ::c_long, + pub xgs: ::c_long, + pub orig_eax: ::c_long, + pub eip: ::c_long, + pub xcs: ::c_long, + pub eflags: ::c_long, + pub esp: ::c_long, + pub xss: ::c_long, + } + + pub struct user { + pub regs: user_regs_struct, + pub u_fpvalid: ::c_int, + pub i387: user_fpregs_struct, + pub u_tsize: ::c_ulong, + pub u_dsize: ::c_ulong, + pub u_ssize: ::c_ulong, + pub start_code: ::c_ulong, + pub start_stack: ::c_ulong, + pub signal: ::c_long, + __reserved: ::c_int, + pub u_ar0: *mut user_regs_struct, + pub u_fpstate: *mut user_fpregs_struct, + pub magic: ::c_ulong, + pub u_comm: [c_char; 32], + pub u_debugreg: [::c_int; 8], + } + + pub struct mcontext_t { + pub gregs: [greg_t; 19], + pub fpregs: *mut _libc_fpstate, + pub oldmask: ::c_ulong, + pub cr2: ::c_ulong, + } + + pub struct ucontext_t { + pub uc_flags: ::c_ulong, + pub uc_link: *mut ucontext_t, + pub uc_stack: ::stack_t, + pub uc_mcontext: mcontext_t, + pub uc_sigmask: ::sigset_t, + __private: [u8; 112], + } + + pub struct ipc_perm { + pub __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::c_ushort, + __pad1: ::c_ushort, + pub __seq: ::c_ushort, + __pad2: ::c_ushort, + __unused1: ::c_ulong, + __unused2: ::c_ulong + } + + pub struct stat64 { + pub st_dev: ::dev_t, + __pad1: ::c_uint, + __st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad2: ::c_uint, + pub st_size: ::off64_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_ino: ::ino64_t, + } + + pub struct statfs64 { + pub f_type: ::__fsword_t, + pub f_bsize: ::__fsword_t, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_fsid: ::fsid_t, + pub f_namelen: ::__fsword_t, + pub f_frsize: ::__fsword_t, + pub f_flags: ::__fsword_t, + pub f_spare: [::__fsword_t; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + __f_unused: ::c_int, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + __unused1: ::c_ulong, + pub shm_dtime: ::time_t, + __unused2: ::c_ulong, + pub shm_ctime: ::time_t, + __unused3: ::c_ulong, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __unused4: ::c_ulong, + __unused5: ::c_ulong + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_stime: ::time_t, + __glibc_reserved1: ::c_ulong, + pub msg_rtime: ::time_t, + __glibc_reserved2: ::c_ulong, + pub msg_ctime: ::time_t, + __glibc_reserved3: ::c_ulong, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __glibc_reserved4: ::c_ulong, + __glibc_reserved5: ::c_ulong, + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 19], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } +} + +pub const O_DIRECT: ::c_int = 0x4000; +pub const O_DIRECTORY: ::c_int = 0x10000; +pub const O_NOFOLLOW: ::c_int = 0x20000; +pub const O_LARGEFILE: ::c_int = 0o0100000; + +pub const MAP_LOCKED: ::c_int = 0x02000; +pub const MAP_NORESERVE: ::c_int = 0x04000; +pub const MAP_32BIT: ::c_int = 0x0040; + +pub const EDEADLOCK: ::c_int = 35; + +pub const SO_SNDBUFFORCE: ::c_int = 32; +pub const SO_RCVBUFFORCE: ::c_int = 33; +pub const SO_NO_CHECK: ::c_int = 11; +pub const SO_PASSCRED: ::c_int = 16; +pub const SO_PEERCRED: ::c_int = 17; +pub const SO_RCVLOWAT: ::c_int = 18; +pub const SO_SNDLOWAT: ::c_int = 19; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_SNDTIMEO: ::c_int = 21; + +pub const FIOCLEX: ::c_ulong = 0x5451; +pub const FIONBIO: ::c_ulong = 0x5421; + +pub const PTRACE_GETFPXREGS: ::c_uint = 18; +pub const PTRACE_SETFPXREGS: ::c_uint = 19; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const SIGSTKSZ: ::size_t = 8192; +pub const MINSIGSTKSZ: ::size_t = 2048; +pub const CBAUD: ::tcflag_t = 0o0010017; +pub const TAB1: ::c_int = 0x00000800; +pub const TAB2: ::c_int = 0x00001000; +pub const TAB3: ::c_int = 0x00001800; +pub const CR1: ::c_int = 0x00000200; +pub const CR2: ::c_int = 0x00000400; +pub const CR3: ::c_int = 0x00000600; +pub const FF1: ::c_int = 0x00008000; +pub const BS1: ::c_int = 0x00002000; +pub const VT1: ::c_int = 0x00004000; +pub const VWERASE: usize = 14; +pub const VREPRINT: usize = 12; +pub const VSUSP: usize = 10; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VDISCARD: usize = 13; +pub const VTIME: usize = 5; +pub const IXON: ::tcflag_t = 0x00000400; +pub const IXOFF: ::tcflag_t = 0x00001000; +pub const ONLCR: ::tcflag_t = 0x4; +pub const CSIZE: ::tcflag_t = 0x00000030; +pub const CS6: ::tcflag_t = 0x00000010; +pub const CS7: ::tcflag_t = 0x00000020; +pub const CS8: ::tcflag_t = 0x00000030; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const ECHOKE: ::tcflag_t = 0x00000800; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const ECHOPRT: ::tcflag_t = 0x00000400; +pub const ECHOCTL: ::tcflag_t = 0x00000200; +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const PENDIN: ::tcflag_t = 0x00004000; +pub const NOFLSH: ::tcflag_t = 0x00000080; +pub const CIBAUD: ::tcflag_t = 0o02003600000; +pub const CBAUDEX: ::tcflag_t = 0o010000; +pub const VSWTC: usize = 7; +pub const OLCUC: ::tcflag_t = 0o000002; +pub const NLDLY: ::tcflag_t = 0o000400; +pub const CRDLY: ::tcflag_t = 0o003000; +pub const TABDLY: ::tcflag_t = 0o014000; +pub const BSDLY: ::tcflag_t = 0o020000; +pub const FFDLY: ::tcflag_t = 0o100000; +pub const VTDLY: ::tcflag_t = 0o040000; +pub const XTABS: ::tcflag_t = 0o014000; + +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const BOTHER: ::speed_t = 0o010000; +pub const B57600: ::speed_t = 0o010001; +pub const B115200: ::speed_t = 0o010002; +pub const B230400: ::speed_t = 0o010003; +pub const B460800: ::speed_t = 0o010004; +pub const B500000: ::speed_t = 0o010005; +pub const B576000: ::speed_t = 0o010006; +pub const B921600: ::speed_t = 0o010007; +pub const B1000000: ::speed_t = 0o010010; +pub const B1152000: ::speed_t = 0o010011; +pub const B1500000: ::speed_t = 0o010012; +pub const B2000000: ::speed_t = 0o010013; +pub const B2500000: ::speed_t = 0o010014; +pub const B3000000: ::speed_t = 0o010015; +pub const B3500000: ::speed_t = 0o010016; +pub const B4000000: ::speed_t = 0o010017; + +pub const VEOL: usize = 11; +pub const VEOL2: usize = 16; +pub const VMIN: usize = 6; +pub const IEXTEN: ::tcflag_t = 0x00008000; +pub const TOSTOP: ::tcflag_t = 0x00000100; +pub const FLUSHO: ::tcflag_t = 0x00001000; +pub const EXTPROC: ::tcflag_t = 0x00010000; +pub const TCGETS: ::c_ulong = 0x5401; +pub const TCSETS: ::c_ulong = 0x5402; +pub const TCSETSW: ::c_ulong = 0x5403; +pub const TCSETSF: ::c_ulong = 0x5404; +pub const TCGETA: ::c_ulong = 0x5405; +pub const TCSETA: ::c_ulong = 0x5406; +pub const TCSETAW: ::c_ulong = 0x5407; +pub const TCSETAF: ::c_ulong = 0x5408; +pub const TCSBRK: ::c_ulong = 0x5409; +pub const TCXONC: ::c_ulong = 0x540A; +pub const TCFLSH: ::c_ulong = 0x540B; +pub const TIOCINQ: ::c_ulong = 0x541B; +pub const TIOCGPGRP: ::c_ulong = 0x540F; +pub const TIOCSPGRP: ::c_ulong = 0x5410; +pub const TIOCOUTQ: ::c_ulong = 0x5411; +pub const TIOCGWINSZ: ::c_ulong = 0x5413; +pub const TIOCSWINSZ: ::c_ulong = 0x5414; +pub const FIONREAD: ::c_ulong = 0x541B; + +// Syscall table +pub const SYS_restart_syscall: ::c_long = 0; +pub const SYS_exit: ::c_long = 1; +pub const SYS_fork: ::c_long = 2; +pub const SYS_read: ::c_long = 3; +pub const SYS_write: ::c_long = 4; +pub const SYS_open: ::c_long = 5; +pub const SYS_close: ::c_long = 6; +pub const SYS_waitpid: ::c_long = 7; +pub const SYS_creat: ::c_long = 8; +pub const SYS_link: ::c_long = 9; +pub const SYS_unlink: ::c_long = 10; +pub const SYS_execve: ::c_long = 11; +pub const SYS_chdir: ::c_long = 12; +pub const SYS_time: ::c_long = 13; +pub const SYS_mknod: ::c_long = 14; +pub const SYS_chmod: ::c_long = 15; +pub const SYS_lchown: ::c_long = 16; +pub const SYS_break: ::c_long = 17; +pub const SYS_oldstat: ::c_long = 18; +pub const SYS_lseek: ::c_long = 19; +pub const SYS_getpid: ::c_long = 20; +pub const SYS_mount: ::c_long = 21; +pub const SYS_umount: ::c_long = 22; +pub const SYS_setuid: ::c_long = 23; +pub const SYS_getuid: ::c_long = 24; +pub const SYS_stime: ::c_long = 25; +pub const SYS_ptrace: ::c_long = 26; +pub const SYS_alarm: ::c_long = 27; +pub const SYS_oldfstat: ::c_long = 28; +pub const SYS_pause: ::c_long = 29; +pub const SYS_utime: ::c_long = 30; +pub const SYS_stty: ::c_long = 31; +pub const SYS_gtty: ::c_long = 32; +pub const SYS_access: ::c_long = 33; +pub const SYS_nice: ::c_long = 34; +pub const SYS_ftime: ::c_long = 35; +pub const SYS_sync: ::c_long = 36; +pub const SYS_kill: ::c_long = 37; +pub const SYS_rename: ::c_long = 38; +pub const SYS_mkdir: ::c_long = 39; +pub const SYS_rmdir: ::c_long = 40; +pub const SYS_dup: ::c_long = 41; +pub const SYS_pipe: ::c_long = 42; +pub const SYS_times: ::c_long = 43; +pub const SYS_prof: ::c_long = 44; +pub const SYS_brk: ::c_long = 45; +pub const SYS_setgid: ::c_long = 46; +pub const SYS_getgid: ::c_long = 47; +pub const SYS_signal: ::c_long = 48; +pub const SYS_geteuid: ::c_long = 49; +pub const SYS_getegid: ::c_long = 50; +pub const SYS_acct: ::c_long = 51; +pub const SYS_umount2: ::c_long = 52; +pub const SYS_lock: ::c_long = 53; +pub const SYS_ioctl: ::c_long = 54; +pub const SYS_fcntl: ::c_long = 55; +pub const SYS_mpx: ::c_long = 56; +pub const SYS_setpgid: ::c_long = 57; +pub const SYS_ulimit: ::c_long = 58; +pub const SYS_oldolduname: ::c_long = 59; +pub const SYS_umask: ::c_long = 60; +pub const SYS_chroot: ::c_long = 61; +pub const SYS_ustat: ::c_long = 62; +pub const SYS_dup2: ::c_long = 63; +pub const SYS_getppid: ::c_long = 64; +pub const SYS_getpgrp: ::c_long = 65; +pub const SYS_setsid: ::c_long = 66; +pub const SYS_sigaction: ::c_long = 67; +pub const SYS_sgetmask: ::c_long = 68; +pub const SYS_ssetmask: ::c_long = 69; +pub const SYS_setreuid: ::c_long = 70; +pub const SYS_setregid: ::c_long = 71; +pub const SYS_sigsuspend: ::c_long = 72; +pub const SYS_sigpending: ::c_long = 73; +pub const SYS_sethostname: ::c_long = 74; +pub const SYS_setrlimit: ::c_long = 75; +pub const SYS_getrlimit: ::c_long = 76; +pub const SYS_getrusage: ::c_long = 77; +pub const SYS_gettimeofday: ::c_long = 78; +pub const SYS_settimeofday: ::c_long = 79; +pub const SYS_getgroups: ::c_long = 80; +pub const SYS_setgroups: ::c_long = 81; +pub const SYS_select: ::c_long = 82; +pub const SYS_symlink: ::c_long = 83; +pub const SYS_oldlstat: ::c_long = 84; +pub const SYS_readlink: ::c_long = 85; +pub const SYS_uselib: ::c_long = 86; +pub const SYS_swapon: ::c_long = 87; +pub const SYS_reboot: ::c_long = 88; +pub const SYS_readdir: ::c_long = 89; +pub const SYS_mmap: ::c_long = 90; +pub const SYS_munmap: ::c_long = 91; +pub const SYS_truncate: ::c_long = 92; +pub const SYS_ftruncate: ::c_long = 93; +pub const SYS_fchmod: ::c_long = 94; +pub const SYS_fchown: ::c_long = 95; +pub const SYS_getpriority: ::c_long = 96; +pub const SYS_setpriority: ::c_long = 97; +pub const SYS_profil: ::c_long = 98; +pub const SYS_statfs: ::c_long = 99; +pub const SYS_fstatfs: ::c_long = 100; +pub const SYS_ioperm: ::c_long = 101; +pub const SYS_socketcall: ::c_long = 102; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_setitimer: ::c_long = 104; +pub const SYS_getitimer: ::c_long = 105; +pub const SYS_stat: ::c_long = 106; +pub const SYS_lstat: ::c_long = 107; +pub const SYS_fstat: ::c_long = 108; +pub const SYS_olduname: ::c_long = 109; +pub const SYS_iopl: ::c_long = 110; +pub const SYS_vhangup: ::c_long = 111; +pub const SYS_idle: ::c_long = 112; +pub const SYS_vm86old: ::c_long = 113; +pub const SYS_wait4: ::c_long = 114; +pub const SYS_swapoff: ::c_long = 115; +pub const SYS_sysinfo: ::c_long = 116; +pub const SYS_ipc: ::c_long = 117; +pub const SYS_fsync: ::c_long = 118; +pub const SYS_sigreturn: ::c_long = 119; +pub const SYS_clone: ::c_long = 120; +pub const SYS_setdomainname: ::c_long = 121; +pub const SYS_uname: ::c_long = 122; +pub const SYS_modify_ldt: ::c_long = 123; +pub const SYS_adjtimex: ::c_long = 124; +pub const SYS_mprotect: ::c_long = 125; +pub const SYS_sigprocmask: ::c_long = 126; +pub const SYS_create_module: ::c_long = 127; +pub const SYS_init_module: ::c_long = 128; +pub const SYS_delete_module: ::c_long = 129; +pub const SYS_get_kernel_syms: ::c_long = 130; +pub const SYS_quotactl: ::c_long = 131; +pub const SYS_getpgid: ::c_long = 132; +pub const SYS_fchdir: ::c_long = 133; +pub const SYS_bdflush: ::c_long = 134; +pub const SYS_sysfs: ::c_long = 135; +pub const SYS_personality: ::c_long = 136; +pub const SYS_afs_syscall: ::c_long = 137; +pub const SYS_setfsuid: ::c_long = 138; +pub const SYS_setfsgid: ::c_long = 139; +pub const SYS__llseek: ::c_long = 140; +pub const SYS_getdents: ::c_long = 141; +pub const SYS__newselect: ::c_long = 142; +pub const SYS_flock: ::c_long = 143; +pub const SYS_msync: ::c_long = 144; +pub const SYS_readv: ::c_long = 145; +pub const SYS_writev: ::c_long = 146; +pub const SYS_getsid: ::c_long = 147; +pub const SYS_fdatasync: ::c_long = 148; +pub const SYS__sysctl: ::c_long = 149; +pub const SYS_mlock: ::c_long = 150; +pub const SYS_munlock: ::c_long = 151; +pub const SYS_mlockall: ::c_long = 152; +pub const SYS_munlockall: ::c_long = 153; +pub const SYS_sched_setparam: ::c_long = 154; +pub const SYS_sched_getparam: ::c_long = 155; +pub const SYS_sched_setscheduler: ::c_long = 156; +pub const SYS_sched_getscheduler: ::c_long = 157; +pub const SYS_sched_yield: ::c_long = 158; +pub const SYS_sched_get_priority_max: ::c_long = 159; +pub const SYS_sched_get_priority_min: ::c_long = 160; +pub const SYS_sched_rr_get_interval: ::c_long = 161; +pub const SYS_nanosleep: ::c_long = 162; +pub const SYS_mremap: ::c_long = 163; +pub const SYS_setresuid: ::c_long = 164; +pub const SYS_getresuid: ::c_long = 165; +pub const SYS_vm86: ::c_long = 166; +pub const SYS_query_module: ::c_long = 167; +pub const SYS_poll: ::c_long = 168; +pub const SYS_nfsservctl: ::c_long = 169; +pub const SYS_setresgid: ::c_long = 170; +pub const SYS_getresgid: ::c_long = 171; +pub const SYS_prctl: ::c_long = 172; +pub const SYS_rt_sigreturn: ::c_long = 173; +pub const SYS_rt_sigaction: ::c_long = 174; +pub const SYS_rt_sigprocmask: ::c_long = 175; +pub const SYS_rt_sigpending: ::c_long = 176; +pub const SYS_rt_sigtimedwait: ::c_long = 177; +pub const SYS_rt_sigqueueinfo: ::c_long = 178; +pub const SYS_rt_sigsuspend: ::c_long = 179; +pub const SYS_pread64: ::c_long = 180; +pub const SYS_pwrite64: ::c_long = 181; +pub const SYS_chown: ::c_long = 182; +pub const SYS_getcwd: ::c_long = 183; +pub const SYS_capget: ::c_long = 184; +pub const SYS_capset: ::c_long = 185; +pub const SYS_sigaltstack: ::c_long = 186; +pub const SYS_sendfile: ::c_long = 187; +pub const SYS_getpmsg: ::c_long = 188; +pub const SYS_putpmsg: ::c_long = 189; +pub const SYS_vfork: ::c_long = 190; +pub const SYS_ugetrlimit: ::c_long = 191; +pub const SYS_mmap2: ::c_long = 192; +pub const SYS_truncate64: ::c_long = 193; +pub const SYS_ftruncate64: ::c_long = 194; +pub const SYS_stat64: ::c_long = 195; +pub const SYS_lstat64: ::c_long = 196; +pub const SYS_fstat64: ::c_long = 197; +pub const SYS_lchown32: ::c_long = 198; +pub const SYS_getuid32: ::c_long = 199; +pub const SYS_getgid32: ::c_long = 200; +pub const SYS_geteuid32: ::c_long = 201; +pub const SYS_getegid32: ::c_long = 202; +pub const SYS_setreuid32: ::c_long = 203; +pub const SYS_setregid32: ::c_long = 204; +pub const SYS_getgroups32: ::c_long = 205; +pub const SYS_setgroups32: ::c_long = 206; +pub const SYS_fchown32: ::c_long = 207; +pub const SYS_setresuid32: ::c_long = 208; +pub const SYS_getresuid32: ::c_long = 209; +pub const SYS_setresgid32: ::c_long = 210; +pub const SYS_getresgid32: ::c_long = 211; +pub const SYS_chown32: ::c_long = 212; +pub const SYS_setuid32: ::c_long = 213; +pub const SYS_setgid32: ::c_long = 214; +pub const SYS_setfsuid32: ::c_long = 215; +pub const SYS_setfsgid32: ::c_long = 216; +pub const SYS_pivot_root: ::c_long = 217; +pub const SYS_mincore: ::c_long = 218; +pub const SYS_madvise: ::c_long = 219; +pub const SYS_getdents64: ::c_long = 220; +pub const SYS_fcntl64: ::c_long = 221; +pub const SYS_gettid: ::c_long = 224; +pub const SYS_readahead: ::c_long = 225; +pub const SYS_setxattr: ::c_long = 226; +pub const SYS_lsetxattr: ::c_long = 227; +pub const SYS_fsetxattr: ::c_long = 228; +pub const SYS_getxattr: ::c_long = 229; +pub const SYS_lgetxattr: ::c_long = 230; +pub const SYS_fgetxattr: ::c_long = 231; +pub const SYS_listxattr: ::c_long = 232; +pub const SYS_llistxattr: ::c_long = 233; +pub const SYS_flistxattr: ::c_long = 234; +pub const SYS_removexattr: ::c_long = 235; +pub const SYS_lremovexattr: ::c_long = 236; +pub const SYS_fremovexattr: ::c_long = 237; +pub const SYS_tkill: ::c_long = 238; +pub const SYS_sendfile64: ::c_long = 239; +pub const SYS_futex: ::c_long = 240; +pub const SYS_sched_setaffinity: ::c_long = 241; +pub const SYS_sched_getaffinity: ::c_long = 242; +pub const SYS_set_thread_area: ::c_long = 243; +pub const SYS_get_thread_area: ::c_long = 244; +pub const SYS_io_setup: ::c_long = 245; +pub const SYS_io_destroy: ::c_long = 246; +pub const SYS_io_getevents: ::c_long = 247; +pub const SYS_io_submit: ::c_long = 248; +pub const SYS_io_cancel: ::c_long = 249; +pub const SYS_fadvise64: ::c_long = 250; +pub const SYS_exit_group: ::c_long = 252; +pub const SYS_lookup_dcookie: ::c_long = 253; +pub const SYS_epoll_create: ::c_long = 254; +pub const SYS_epoll_ctl: ::c_long = 255; +pub const SYS_epoll_wait: ::c_long = 256; +pub const SYS_remap_file_pages: ::c_long = 257; +pub const SYS_set_tid_address: ::c_long = 258; +pub const SYS_timer_create: ::c_long = 259; +pub const SYS_timer_settime: ::c_long = 260; +pub const SYS_timer_gettime: ::c_long = 261; +pub const SYS_timer_getoverrun: ::c_long = 262; +pub const SYS_timer_delete: ::c_long = 263; +pub const SYS_clock_settime: ::c_long = 264; +pub const SYS_clock_gettime: ::c_long = 265; +pub const SYS_clock_getres: ::c_long = 266; +pub const SYS_clock_nanosleep: ::c_long = 267; +pub const SYS_statfs64: ::c_long = 268; +pub const SYS_fstatfs64: ::c_long = 269; +pub const SYS_tgkill: ::c_long = 270; +pub const SYS_utimes: ::c_long = 271; +pub const SYS_fadvise64_64: ::c_long = 272; +pub const SYS_vserver: ::c_long = 273; +pub const SYS_mbind: ::c_long = 274; +pub const SYS_get_mempolicy: ::c_long = 275; +pub const SYS_set_mempolicy: ::c_long = 276; +pub const SYS_mq_open: ::c_long = 277; +pub const SYS_mq_unlink: ::c_long = 278; +pub const SYS_mq_timedsend: ::c_long = 279; +pub const SYS_mq_timedreceive: ::c_long = 280; +pub const SYS_mq_notify: ::c_long = 281; +pub const SYS_mq_getsetattr: ::c_long = 282; +pub const SYS_kexec_load: ::c_long = 283; +pub const SYS_waitid: ::c_long = 284; +pub const SYS_add_key: ::c_long = 286; +pub const SYS_request_key: ::c_long = 287; +pub const SYS_keyctl: ::c_long = 288; +pub const SYS_ioprio_set: ::c_long = 289; +pub const SYS_ioprio_get: ::c_long = 290; +pub const SYS_inotify_init: ::c_long = 291; +pub const SYS_inotify_add_watch: ::c_long = 292; +pub const SYS_inotify_rm_watch: ::c_long = 293; +pub const SYS_migrate_pages: ::c_long = 294; +pub const SYS_openat: ::c_long = 295; +pub const SYS_mkdirat: ::c_long = 296; +pub const SYS_mknodat: ::c_long = 297; +pub const SYS_fchownat: ::c_long = 298; +pub const SYS_futimesat: ::c_long = 299; +pub const SYS_fstatat64: ::c_long = 300; +pub const SYS_unlinkat: ::c_long = 301; +pub const SYS_renameat: ::c_long = 302; +pub const SYS_linkat: ::c_long = 303; +pub const SYS_symlinkat: ::c_long = 304; +pub const SYS_readlinkat: ::c_long = 305; +pub const SYS_fchmodat: ::c_long = 306; +pub const SYS_faccessat: ::c_long = 307; +pub const SYS_pselect6: ::c_long = 308; +pub const SYS_ppoll: ::c_long = 309; +pub const SYS_unshare: ::c_long = 310; +pub const SYS_set_robust_list: ::c_long = 311; +pub const SYS_get_robust_list: ::c_long = 312; +pub const SYS_splice: ::c_long = 313; +pub const SYS_sync_file_range: ::c_long = 314; +pub const SYS_tee: ::c_long = 315; +pub const SYS_vmsplice: ::c_long = 316; +pub const SYS_move_pages: ::c_long = 317; +pub const SYS_getcpu: ::c_long = 318; +pub const SYS_epoll_pwait: ::c_long = 319; +pub const SYS_utimensat: ::c_long = 320; +pub const SYS_signalfd: ::c_long = 321; +pub const SYS_timerfd_create: ::c_long = 322; +pub const SYS_eventfd: ::c_long = 323; +pub const SYS_fallocate: ::c_long = 324; +pub const SYS_timerfd_settime: ::c_long = 325; +pub const SYS_timerfd_gettime: ::c_long = 326; +pub const SYS_signalfd4: ::c_long = 327; +pub const SYS_eventfd2: ::c_long = 328; +pub const SYS_epoll_create1: ::c_long = 329; +pub const SYS_dup3: ::c_long = 330; +pub const SYS_pipe2: ::c_long = 331; +pub const SYS_inotify_init1: ::c_long = 332; +pub const SYS_preadv: ::c_long = 333; +pub const SYS_pwritev: ::c_long = 334; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 335; +pub const SYS_perf_event_open: ::c_long = 336; +pub const SYS_recvmmsg: ::c_long = 337; +pub const SYS_fanotify_init: ::c_long = 338; +pub const SYS_fanotify_mark: ::c_long = 339; +pub const SYS_prlimit64: ::c_long = 340; +pub const SYS_name_to_handle_at: ::c_long = 341; +pub const SYS_open_by_handle_at: ::c_long = 342; +pub const SYS_clock_adjtime: ::c_long = 343; +pub const SYS_syncfs: ::c_long = 344; +pub const SYS_sendmmsg: ::c_long = 345; +pub const SYS_setns: ::c_long = 346; +pub const SYS_process_vm_readv: ::c_long = 347; +pub const SYS_process_vm_writev: ::c_long = 348; +pub const SYS_kcmp: ::c_long = 349; +pub const SYS_finit_module: ::c_long = 350; +pub const SYS_sched_setattr: ::c_long = 351; +pub const SYS_sched_getattr: ::c_long = 352; +pub const SYS_renameat2: ::c_long = 353; +pub const SYS_seccomp: ::c_long = 354; +pub const SYS_getrandom: ::c_long = 355; +pub const SYS_memfd_create: ::c_long = 356; +pub const SYS_bpf: ::c_long = 357; +pub const SYS_execveat: ::c_long = 358; +pub const SYS_socket: ::c_long = 359; +pub const SYS_socketpair: ::c_long = 360; +pub const SYS_bind: ::c_long = 361; +pub const SYS_connect: ::c_long = 362; +pub const SYS_listen: ::c_long = 363; +pub const SYS_accept4: ::c_long = 364; +pub const SYS_getsockopt: ::c_long = 365; +pub const SYS_setsockopt: ::c_long = 366; +pub const SYS_getsockname: ::c_long = 367; +pub const SYS_getpeername: ::c_long = 368; +pub const SYS_sendto: ::c_long = 369; +pub const SYS_sendmsg: ::c_long = 370; +pub const SYS_recvfrom: ::c_long = 371; +pub const SYS_recvmsg: ::c_long = 372; +pub const SYS_shutdown: ::c_long = 373; +pub const SYS_userfaultfd: ::c_long = 374; +pub const SYS_membarrier: ::c_long = 375; +pub const SYS_mlock2: ::c_long = 376; +pub const SYS_copy_file_range: ::c_long = 377; +pub const SYS_preadv2: ::c_long = 378; +pub const SYS_pwritev2: ::c_long = 379; +pub const SYS_pkey_mprotect: ::c_long = 380; +pub const SYS_pkey_alloc: ::c_long = 381; +pub const SYS_pkey_free: ::c_long = 382; + +// offsets in user_regs_structs, from sys/reg.h +pub const EBX: ::c_int = 0; +pub const ECX: ::c_int = 1; +pub const EDX: ::c_int = 2; +pub const ESI: ::c_int = 3; +pub const EDI: ::c_int = 4; +pub const EBP: ::c_int = 5; +pub const EAX: ::c_int = 6; +pub const DS: ::c_int = 7; +pub const ES: ::c_int = 8; +pub const FS: ::c_int = 9; +pub const GS: ::c_int = 10; +pub const ORIG_EAX: ::c_int = 11; +pub const EIP: ::c_int = 12; +pub const CS: ::c_int = 13; +pub const EFL: ::c_int = 14; +pub const UESP: ::c_int = 15; +pub const SS: ::c_int = 16; + +extern { + pub fn getcontext(ucp: *mut ucontext_t) -> ::c_int; + pub fn setcontext(ucp: *const ucontext_t) -> ::c_int; + pub fn makecontext(ucp: *mut ucontext_t, + func: extern fn (), + argc: ::c_int, ...); + pub fn swapcontext(uocp: *mut ucontext_t, + ucp: *const ucontext_t) -> ::c_int; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/aarch64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/aarch64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/aarch64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/aarch64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,786 @@ +//! AArch64-specific definitions for 64-bit linux-like values + +pub type c_long = i64; +pub type c_ulong = u64; +pub type c_char = u8; +pub type wchar_t = u32; +pub type nlink_t = u32; +pub type blksize_t = i32; +pub type suseconds_t = i64; +pub type __u64 = ::c_ulonglong; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad1: ::dev_t, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + __pad2: ::c_int, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused: [::c_int; 2], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad1: ::dev_t, + pub st_size: ::off64_t, + pub st_blksize: ::blksize_t, + __pad2: ::c_int, + pub st_blocks: ::blkcnt64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused: [::c_int; 2], + } + + pub struct statfs64 { + pub f_type: ::__fsword_t, + pub f_bsize: ::__fsword_t, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_fsid: ::fsid_t, + pub f_namelen: ::__fsword_t, + pub f_frsize: ::__fsword_t, + pub f_flags: ::__fsword_t, + pub f_spare: [::__fsword_t; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct pthread_attr_t { + __size: [u64; 8] + } + + pub struct ipc_perm { + pub __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::c_uint, + pub __seq: ::c_ushort, + __pad1: ::c_ushort, + __unused1: ::c_ulong, + __unused2: ::c_ulong + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __unused4: ::c_ulong, + __unused5: ::c_ulong + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 19], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } +} + +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; + +pub const TIOCGSOFTCAR: ::c_ulong = 0x5419; +pub const TIOCSSOFTCAR: ::c_ulong = 0x541A; + +pub const RLIMIT_NOFILE: ::c_int = 7; +pub const RLIMIT_NPROC: ::c_int = 6; + +pub const O_APPEND: ::c_int = 1024; +pub const O_CREAT: ::c_int = 64; +pub const O_EXCL: ::c_int = 128; +pub const O_NOCTTY: ::c_int = 256; +pub const O_NONBLOCK: ::c_int = 2048; +pub const O_SYNC: ::c_int = 1052672; +pub const O_RSYNC: ::c_int = 1052672; +pub const O_DSYNC: ::c_int = 4096; +pub const O_FSYNC: ::c_int = 0x101000; +pub const O_NOATIME: ::c_int = 0o1000000; +pub const O_PATH: ::c_int = 0o10000000; +pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; + +pub const MAP_GROWSDOWN: ::c_int = 0x0100; + +pub const EDEADLK: ::c_int = 35; +pub const ENAMETOOLONG: ::c_int = 36; +pub const ENOLCK: ::c_int = 37; +pub const ENOSYS: ::c_int = 38; +pub const ENOTEMPTY: ::c_int = 39; +pub const ELOOP: ::c_int = 40; +pub const ENOMSG: ::c_int = 42; +pub const EIDRM: ::c_int = 43; +pub const ECHRNG: ::c_int = 44; +pub const EL2NSYNC: ::c_int = 45; +pub const EL3HLT: ::c_int = 46; +pub const EL3RST: ::c_int = 47; +pub const ELNRNG: ::c_int = 48; +pub const EUNATCH: ::c_int = 49; +pub const ENOCSI: ::c_int = 50; +pub const EL2HLT: ::c_int = 51; +pub const EBADE: ::c_int = 52; +pub const EBADR: ::c_int = 53; +pub const EXFULL: ::c_int = 54; +pub const ENOANO: ::c_int = 55; +pub const EBADRQC: ::c_int = 56; +pub const EBADSLT: ::c_int = 57; +pub const EMULTIHOP: ::c_int = 72; +pub const EOVERFLOW: ::c_int = 75; +pub const ENOTUNIQ: ::c_int = 76; +pub const EBADFD: ::c_int = 77; +pub const EBADMSG: ::c_int = 74; +pub const EREMCHG: ::c_int = 78; +pub const ELIBACC: ::c_int = 79; +pub const ELIBBAD: ::c_int = 80; +pub const ELIBSCN: ::c_int = 81; +pub const ELIBMAX: ::c_int = 82; +pub const ELIBEXEC: ::c_int = 83; +pub const EILSEQ: ::c_int = 84; +pub const ERESTART: ::c_int = 85; +pub const ESTRPIPE: ::c_int = 86; +pub const EUSERS: ::c_int = 87; +pub const ENOTSOCK: ::c_int = 88; +pub const EDESTADDRREQ: ::c_int = 89; +pub const EMSGSIZE: ::c_int = 90; +pub const EPROTOTYPE: ::c_int = 91; +pub const ENOPROTOOPT: ::c_int = 92; +pub const EPROTONOSUPPORT: ::c_int = 93; +pub const ESOCKTNOSUPPORT: ::c_int = 94; +pub const EOPNOTSUPP: ::c_int = 95; +pub const EPFNOSUPPORT: ::c_int = 96; +pub const EAFNOSUPPORT: ::c_int = 97; +pub const EADDRINUSE: ::c_int = 98; +pub const EADDRNOTAVAIL: ::c_int = 99; +pub const ENETDOWN: ::c_int = 100; +pub const ENETUNREACH: ::c_int = 101; +pub const ENETRESET: ::c_int = 102; +pub const ECONNABORTED: ::c_int = 103; +pub const ECONNRESET: ::c_int = 104; +pub const ENOBUFS: ::c_int = 105; +pub const EISCONN: ::c_int = 106; +pub const ENOTCONN: ::c_int = 107; +pub const ESHUTDOWN: ::c_int = 108; +pub const ETOOMANYREFS: ::c_int = 109; +pub const ETIMEDOUT: ::c_int = 110; +pub const ECONNREFUSED: ::c_int = 111; +pub const EHOSTDOWN: ::c_int = 112; +pub const EHOSTUNREACH: ::c_int = 113; +pub const EALREADY: ::c_int = 114; +pub const EINPROGRESS: ::c_int = 115; +pub const ESTALE: ::c_int = 116; +pub const EDQUOT: ::c_int = 122; +pub const ENOMEDIUM: ::c_int = 123; +pub const EMEDIUMTYPE: ::c_int = 124; +pub const ECANCELED: ::c_int = 125; +pub const ENOKEY: ::c_int = 126; +pub const EKEYEXPIRED: ::c_int = 127; +pub const EKEYREVOKED: ::c_int = 128; +pub const EKEYREJECTED: ::c_int = 129; +pub const EOWNERDEAD: ::c_int = 130; +pub const ENOTRECOVERABLE: ::c_int = 131; +pub const EHWPOISON: ::c_int = 133; +pub const ERFKILL: ::c_int = 132; + +pub const SOL_SOCKET: ::c_int = 1; + +pub const SO_REUSEADDR: ::c_int = 2; +pub const SO_TYPE: ::c_int = 3; +pub const SO_ERROR: ::c_int = 4; +pub const SO_DONTROUTE: ::c_int = 5; +pub const SO_BROADCAST: ::c_int = 6; +pub const SO_SNDBUF: ::c_int = 7; +pub const SO_RCVBUF: ::c_int = 8; +pub const SO_SNDBUFFORCE: ::c_int = 32; +pub const SO_RCVBUFFORCE: ::c_int = 33; +pub const SO_KEEPALIVE: ::c_int = 9; +pub const SO_OOBINLINE: ::c_int = 10; +pub const SO_NO_CHECK: ::c_int = 11; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_LINGER: ::c_int = 13; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_REUSEPORT: ::c_int = 15; +pub const SO_PASSCRED: ::c_int = 16; +pub const SO_PEERCRED: ::c_int = 17; +pub const SO_RCVLOWAT: ::c_int = 18; +pub const SO_SNDLOWAT: ::c_int = 19; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_SNDTIMEO: ::c_int = 21; +pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22; +pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23; +pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24; +pub const SO_BINDTODEVICE: ::c_int = 25; +pub const SO_ATTACH_FILTER: ::c_int = 26; +pub const SO_DETACH_FILTER: ::c_int = 27; +pub const SO_GET_FILTER: ::c_int = SO_ATTACH_FILTER; +pub const SO_PEERNAME: ::c_int = 28; +pub const SO_TIMESTAMP: ::c_int = 29; +pub const SO_ACCEPTCONN: ::c_int = 30; +pub const SO_PEERSEC: ::c_int = 31; +pub const SO_PASSSEC: ::c_int = 34; +pub const SO_TIMESTAMPNS: ::c_int = 35; +pub const SCM_TIMESTAMPNS: ::c_int = SO_TIMESTAMPNS; +pub const SO_MARK: ::c_int = 36; +pub const SO_TIMESTAMPING: ::c_int = 37; +pub const SCM_TIMESTAMPING: ::c_int = SO_TIMESTAMPING; +pub const SO_PROTOCOL: ::c_int = 38; +pub const SO_DOMAIN: ::c_int = 39; +pub const SO_RXQ_OVFL: ::c_int = 40; +pub const SO_WIFI_STATUS: ::c_int = 41; +pub const SCM_WIFI_STATUS: ::c_int = SO_WIFI_STATUS; +pub const SO_PEEK_OFF: ::c_int = 42; +pub const SO_NOFCS: ::c_int = 43; +pub const SO_LOCK_FILTER: ::c_int = 44; +pub const SO_SELECT_ERR_QUEUE: ::c_int = 45; +pub const SO_BUSY_POLL: ::c_int = 46; +pub const SO_MAX_PACING_RATE: ::c_int = 47; +pub const SO_BPF_EXTENSIONS: ::c_int = 48; +pub const SO_INCOMING_CPU: ::c_int = 49; +pub const SO_ATTACH_BPF: ::c_int = 50; +pub const SO_DETACH_BPF: ::c_int = SO_DETACH_FILTER; + +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 0x00000004; +pub const SA_NOCLDWAIT: ::c_int = 0x00000002; + +pub const SIGCHLD: ::c_int = 17; +pub const SIGBUS: ::c_int = 7; +pub const SIGUSR1: ::c_int = 10; +pub const SIGUSR2: ::c_int = 12; +pub const SIGCONT: ::c_int = 18; +pub const SIGSTOP: ::c_int = 19; +pub const SIGTSTP: ::c_int = 20; +pub const SIGURG: ::c_int = 23; +pub const SIGIO: ::c_int = 29; +pub const SIGSYS: ::c_int = 31; +pub const SIGSTKFLT: ::c_int = 16; +pub const SIGUNUSED: ::c_int = 31; +pub const SIGPOLL: ::c_int = 29; +pub const SIGPWR: ::c_int = 30; +pub const SIG_SETMASK: ::c_int = 2; +pub const SIG_BLOCK: ::c_int = 0x000000; +pub const SIG_UNBLOCK: ::c_int = 0x01; + +pub const POLLWRNORM: ::c_short = 0x100; +pub const POLLWRBAND: ::c_short = 0x200; + +pub const O_ASYNC: ::c_int = 0x2000; +pub const O_NDELAY: ::c_int = 0x800; + +pub const PTRACE_DETACH: ::c_uint = 17; + +pub const EFD_NONBLOCK: ::c_int = 0x800; + +pub const F_GETLK: ::c_int = 5; +pub const F_GETOWN: ::c_int = 9; +pub const F_SETOWN: ::c_int = 8; +pub const F_SETLK: ::c_int = 6; +pub const F_SETLKW: ::c_int = 7; + +pub const SFD_NONBLOCK: ::c_int = 0x0800; + +pub const TIOCEXCL: ::c_ulong = 0x540C; +pub const TIOCNXCL: ::c_ulong = 0x540D; +pub const TIOCSCTTY: ::c_ulong = 0x540E; +pub const TIOCSTI: ::c_ulong = 0x5412; +pub const TIOCMGET: ::c_ulong = 0x5415; +pub const TIOCMBIS: ::c_ulong = 0x5416; +pub const TIOCMBIC: ::c_ulong = 0x5417; +pub const TIOCMSET: ::c_ulong = 0x5418; +pub const TIOCCONS: ::c_ulong = 0x541D; + +pub const SFD_CLOEXEC: ::c_int = 0x080000; + +pub const NCCS: usize = 32; + +pub const O_TRUNC: ::c_int = 512; + +pub const O_CLOEXEC: ::c_int = 0x80000; + +pub const EBFONT: ::c_int = 59; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const EDOTDOT: ::c_int = 73; + +pub const SA_NODEFER: ::c_int = 0x40000000; +pub const SA_RESETHAND: ::c_int = 0x80000000; +pub const SA_RESTART: ::c_int = 0x10000000; +pub const SA_NOCLDSTOP: ::c_int = 0x00000001; + +pub const EPOLL_CLOEXEC: ::c_int = 0x80000; + +pub const EFD_CLOEXEC: ::c_int = 0x80000; + +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 8; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 48; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 8; + +pub const O_DIRECT: ::c_int = 0x10000; +pub const O_DIRECTORY: ::c_int = 0x4000; +pub const O_NOFOLLOW: ::c_int = 0x8000; + +pub const MAP_LOCKED: ::c_int = 0x02000; +pub const MAP_NORESERVE: ::c_int = 0x04000; + +pub const EDEADLOCK: ::c_int = 35; + +pub const FIOCLEX: ::c_ulong = 0x5451; +pub const FIONBIO: ::c_ulong = 0x5421; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const SIGSTKSZ: ::size_t = 16384; +pub const MINSIGSTKSZ: ::size_t = 5120; +pub const CBAUD: ::tcflag_t = 0o0010017; +pub const TAB1: ::c_int = 0x00000800; +pub const TAB2: ::c_int = 0x00001000; +pub const TAB3: ::c_int = 0x00001800; +pub const CR1: ::c_int = 0x00000200; +pub const CR2: ::c_int = 0x00000400; +pub const CR3: ::c_int = 0x00000600; +pub const FF1: ::c_int = 0x00008000; +pub const BS1: ::c_int = 0x00002000; +pub const VT1: ::c_int = 0x00004000; +pub const VWERASE: usize = 14; +pub const VREPRINT: usize = 12; +pub const VSUSP: usize = 10; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VDISCARD: usize = 13; +pub const VTIME: usize = 5; +pub const IXON: ::tcflag_t = 0x00000400; +pub const IXOFF: ::tcflag_t = 0x00001000; +pub const ONLCR: ::tcflag_t = 0x4; +pub const CSIZE: ::tcflag_t = 0x00000030; +pub const CS6: ::tcflag_t = 0x00000010; +pub const CS7: ::tcflag_t = 0x00000020; +pub const CS8: ::tcflag_t = 0x00000030; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const ECHOKE: ::tcflag_t = 0x00000800; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const ECHOPRT: ::tcflag_t = 0x00000400; +pub const ECHOCTL: ::tcflag_t = 0x00000200; +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const PENDIN: ::tcflag_t = 0x00004000; +pub const NOFLSH: ::tcflag_t = 0x00000080; +pub const CIBAUD: ::tcflag_t = 0o02003600000; +pub const CBAUDEX: ::tcflag_t = 0o010000; +pub const VSWTC: usize = 7; +pub const OLCUC: ::tcflag_t = 0o000002; +pub const NLDLY: ::tcflag_t = 0o000400; +pub const CRDLY: ::tcflag_t = 0o003000; +pub const TABDLY: ::tcflag_t = 0o014000; +pub const BSDLY: ::tcflag_t = 0o020000; +pub const FFDLY: ::tcflag_t = 0o100000; +pub const VTDLY: ::tcflag_t = 0o040000; +pub const XTABS: ::tcflag_t = 0o014000; + +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const BOTHER: ::speed_t = 0o010000; +pub const B57600: ::speed_t = 0o010001; +pub const B115200: ::speed_t = 0o010002; +pub const B230400: ::speed_t = 0o010003; +pub const B460800: ::speed_t = 0o010004; +pub const B500000: ::speed_t = 0o010005; +pub const B576000: ::speed_t = 0o010006; +pub const B921600: ::speed_t = 0o010007; +pub const B1000000: ::speed_t = 0o010010; +pub const B1152000: ::speed_t = 0o010011; +pub const B1500000: ::speed_t = 0o010012; +pub const B2000000: ::speed_t = 0o010013; +pub const B2500000: ::speed_t = 0o010014; +pub const B3000000: ::speed_t = 0o010015; +pub const B3500000: ::speed_t = 0o010016; +pub const B4000000: ::speed_t = 0o010017; + +pub const VEOL: usize = 11; +pub const VEOL2: usize = 16; +pub const VMIN: usize = 6; +pub const IEXTEN: ::tcflag_t = 0x00008000; +pub const TOSTOP: ::tcflag_t = 0x00000100; +pub const FLUSHO: ::tcflag_t = 0x00001000; +pub const EXTPROC: ::tcflag_t = 0x00010000; +pub const TCGETS: ::c_ulong = 0x5401; +pub const TCSETS: ::c_ulong = 0x5402; +pub const TCSETSW: ::c_ulong = 0x5403; +pub const TCSETSF: ::c_ulong = 0x5404; +pub const TCGETA: ::c_ulong = 0x5405; +pub const TCSETA: ::c_ulong = 0x5406; +pub const TCSETAW: ::c_ulong = 0x5407; +pub const TCSETAF: ::c_ulong = 0x5408; +pub const TCSBRK: ::c_ulong = 0x5409; +pub const TCXONC: ::c_ulong = 0x540A; +pub const TCFLSH: ::c_ulong = 0x540B; +pub const TIOCINQ: ::c_ulong = 0x541B; +pub const TIOCGPGRP: ::c_ulong = 0x540F; +pub const TIOCSPGRP: ::c_ulong = 0x5410; +pub const TIOCOUTQ: ::c_ulong = 0x5411; +pub const TIOCGWINSZ: ::c_ulong = 0x5413; +pub const TIOCSWINSZ: ::c_ulong = 0x5414; +pub const FIONREAD: ::c_ulong = 0x541B; + +// Syscall table +pub const SYS_io_setup: ::c_long = 0; +pub const SYS_io_destroy: ::c_long = 1; +pub const SYS_io_submit: ::c_long = 2; +pub const SYS_io_cancel: ::c_long = 3; +pub const SYS_io_getevents: ::c_long = 4; +pub const SYS_setxattr: ::c_long = 5; +pub const SYS_lsetxattr: ::c_long = 6; +pub const SYS_fsetxattr: ::c_long = 7; +pub const SYS_getxattr: ::c_long = 8; +pub const SYS_lgetxattr: ::c_long = 9; +pub const SYS_fgetxattr: ::c_long = 10; +pub const SYS_listxattr: ::c_long = 11; +pub const SYS_llistxattr: ::c_long = 12; +pub const SYS_flistxattr: ::c_long = 13; +pub const SYS_removexattr: ::c_long = 14; +pub const SYS_lremovexattr: ::c_long = 15; +pub const SYS_fremovexattr: ::c_long = 16; +pub const SYS_getcwd: ::c_long = 17; +pub const SYS_lookup_dcookie: ::c_long = 18; +pub const SYS_eventfd2: ::c_long = 19; +pub const SYS_epoll_create1: ::c_long = 20; +pub const SYS_epoll_ctl: ::c_long = 21; +pub const SYS_epoll_pwait: ::c_long = 22; +pub const SYS_dup: ::c_long = 23; +pub const SYS_dup3: ::c_long = 24; +pub const SYS_fcntl: ::c_long = 25; +pub const SYS_inotify_init1: ::c_long = 26; +pub const SYS_inotify_add_watch: ::c_long = 27; +pub const SYS_inotify_rm_watch: ::c_long = 28; +pub const SYS_ioctl: ::c_long = 29; +pub const SYS_ioprio_set: ::c_long = 30; +pub const SYS_ioprio_get: ::c_long = 31; +pub const SYS_flock: ::c_long = 32; +pub const SYS_mknodat: ::c_long = 33; +pub const SYS_mkdirat: ::c_long = 34; +pub const SYS_unlinkat: ::c_long = 35; +pub const SYS_symlinkat: ::c_long = 36; +pub const SYS_linkat: ::c_long = 37; +pub const SYS_renameat: ::c_long = 38; +pub const SYS_umount2: ::c_long = 39; +pub const SYS_mount: ::c_long = 40; +pub const SYS_pivot_root: ::c_long = 41; +pub const SYS_nfsservctl: ::c_long = 42; +pub const SYS_fallocate: ::c_long = 47; +pub const SYS_faccessat: ::c_long = 48; +pub const SYS_chdir: ::c_long = 49; +pub const SYS_fchdir: ::c_long = 50; +pub const SYS_chroot: ::c_long = 51; +pub const SYS_fchmod: ::c_long = 52; +pub const SYS_fchmodat: ::c_long = 53; +pub const SYS_fchownat: ::c_long = 54; +pub const SYS_fchown: ::c_long = 55; +pub const SYS_openat: ::c_long = 56; +pub const SYS_close: ::c_long = 57; +pub const SYS_vhangup: ::c_long = 58; +pub const SYS_pipe2: ::c_long = 59; +pub const SYS_quotactl: ::c_long = 60; +pub const SYS_getdents64: ::c_long = 61; +pub const SYS_lseek: ::c_long = 62; +pub const SYS_read: ::c_long = 63; +pub const SYS_write: ::c_long = 64; +pub const SYS_readv: ::c_long = 65; +pub const SYS_writev: ::c_long = 66; +pub const SYS_pread64: ::c_long = 67; +pub const SYS_pwrite64: ::c_long = 68; +pub const SYS_preadv: ::c_long = 69; +pub const SYS_pwritev: ::c_long = 70; +pub const SYS_pselect6: ::c_long = 72; +pub const SYS_ppoll: ::c_long = 73; +pub const SYS_signalfd4: ::c_long = 74; +pub const SYS_vmsplice: ::c_long = 75; +pub const SYS_splice: ::c_long = 76; +pub const SYS_tee: ::c_long = 77; +pub const SYS_readlinkat: ::c_long = 78; +pub const SYS_newfstatat: ::c_long = 79; +pub const SYS_fstat: ::c_long = 80; +pub const SYS_sync: ::c_long = 81; +pub const SYS_fsync: ::c_long = 82; +pub const SYS_fdatasync: ::c_long = 83; +pub const SYS_sync_file_range: ::c_long = 84; +pub const SYS_timerfd_create: ::c_long = 85; +pub const SYS_timerfd_settime: ::c_long = 86; +pub const SYS_timerfd_gettime: ::c_long = 87; +pub const SYS_utimensat: ::c_long = 88; +pub const SYS_acct: ::c_long = 89; +pub const SYS_capget: ::c_long = 90; +pub const SYS_capset: ::c_long = 91; +pub const SYS_personality: ::c_long = 92; +pub const SYS_exit: ::c_long = 93; +pub const SYS_exit_group: ::c_long = 94; +pub const SYS_waitid: ::c_long = 95; +pub const SYS_set_tid_address: ::c_long = 96; +pub const SYS_unshare: ::c_long = 97; +pub const SYS_futex: ::c_long = 98; +pub const SYS_set_robust_list: ::c_long = 99; +pub const SYS_get_robust_list: ::c_long = 100; +pub const SYS_nanosleep: ::c_long = 101; +pub const SYS_getitimer: ::c_long = 102; +pub const SYS_setitimer: ::c_long = 103; +pub const SYS_kexec_load: ::c_long = 104; +pub const SYS_init_module: ::c_long = 105; +pub const SYS_delete_module: ::c_long = 106; +pub const SYS_timer_create: ::c_long = 107; +pub const SYS_timer_gettime: ::c_long = 108; +pub const SYS_timer_getoverrun: ::c_long = 109; +pub const SYS_timer_settime: ::c_long = 110; +pub const SYS_timer_delete: ::c_long = 111; +pub const SYS_clock_settime: ::c_long = 112; +pub const SYS_clock_gettime: ::c_long = 113; +pub const SYS_clock_getres: ::c_long = 114; +pub const SYS_clock_nanosleep: ::c_long = 115; +pub const SYS_syslog: ::c_long = 116; +pub const SYS_ptrace: ::c_long = 117; +pub const SYS_sched_setparam: ::c_long = 118; +pub const SYS_sched_setscheduler: ::c_long = 119; +pub const SYS_sched_getscheduler: ::c_long = 120; +pub const SYS_sched_getparam: ::c_long = 121; +pub const SYS_sched_setaffinity: ::c_long = 122; +pub const SYS_sched_getaffinity: ::c_long = 123; +pub const SYS_sched_yield: ::c_long = 124; +pub const SYS_sched_get_priority_max: ::c_long = 125; +pub const SYS_sched_get_priority_min: ::c_long = 126; +pub const SYS_sched_rr_get_interval: ::c_long = 127; +pub const SYS_restart_syscall: ::c_long = 128; +pub const SYS_kill: ::c_long = 129; +pub const SYS_tkill: ::c_long = 130; +pub const SYS_tgkill: ::c_long = 131; +pub const SYS_sigaltstack: ::c_long = 132; +pub const SYS_rt_sigsuspend: ::c_long = 133; +pub const SYS_rt_sigaction: ::c_long = 134; +pub const SYS_rt_sigprocmask: ::c_long = 135; +pub const SYS_rt_sigpending: ::c_long = 136; +pub const SYS_rt_sigtimedwait: ::c_long = 137; +pub const SYS_rt_sigqueueinfo: ::c_long = 138; +pub const SYS_rt_sigreturn: ::c_long = 139; +pub const SYS_setpriority: ::c_long = 140; +pub const SYS_getpriority: ::c_long = 141; +pub const SYS_reboot: ::c_long = 142; +pub const SYS_setregid: ::c_long = 143; +pub const SYS_setgid: ::c_long = 144; +pub const SYS_setreuid: ::c_long = 145; +pub const SYS_setuid: ::c_long = 146; +pub const SYS_setresuid: ::c_long = 147; +pub const SYS_getresuid: ::c_long = 148; +pub const SYS_setresgid: ::c_long = 149; +pub const SYS_getresgid: ::c_long = 150; +pub const SYS_setfsuid: ::c_long = 151; +pub const SYS_setfsgid: ::c_long = 152; +pub const SYS_times: ::c_long = 153; +pub const SYS_setpgid: ::c_long = 154; +pub const SYS_getpgid: ::c_long = 155; +pub const SYS_getsid: ::c_long = 156; +pub const SYS_setsid: ::c_long = 157; +pub const SYS_getgroups: ::c_long = 158; +pub const SYS_setgroups: ::c_long = 159; +pub const SYS_uname: ::c_long = 160; +pub const SYS_sethostname: ::c_long = 161; +pub const SYS_setdomainname: ::c_long = 162; +pub const SYS_getrlimit: ::c_long = 163; +pub const SYS_setrlimit: ::c_long = 164; +pub const SYS_getrusage: ::c_long = 165; +pub const SYS_umask: ::c_long = 166; +pub const SYS_prctl: ::c_long = 167; +pub const SYS_getcpu: ::c_long = 168; +pub const SYS_gettimeofday: ::c_long = 169; +pub const SYS_settimeofday: ::c_long = 170; +pub const SYS_adjtimex: ::c_long = 171; +pub const SYS_getpid: ::c_long = 172; +pub const SYS_getppid: ::c_long = 173; +pub const SYS_getuid: ::c_long = 174; +pub const SYS_geteuid: ::c_long = 175; +pub const SYS_getgid: ::c_long = 176; +pub const SYS_getegid: ::c_long = 177; +pub const SYS_gettid: ::c_long = 178; +pub const SYS_sysinfo: ::c_long = 179; +pub const SYS_mq_open: ::c_long = 180; +pub const SYS_mq_unlink: ::c_long = 181; +pub const SYS_mq_timedsend: ::c_long = 182; +pub const SYS_mq_timedreceive: ::c_long = 183; +pub const SYS_mq_notify: ::c_long = 184; +pub const SYS_mq_getsetattr: ::c_long = 185; +pub const SYS_msgget: ::c_long = 186; +pub const SYS_msgctl: ::c_long = 187; +pub const SYS_msgrcv: ::c_long = 188; +pub const SYS_msgsnd: ::c_long = 189; +pub const SYS_semget: ::c_long = 190; +pub const SYS_semctl: ::c_long = 191; +pub const SYS_semtimedop: ::c_long = 192; +pub const SYS_semop: ::c_long = 193; +pub const SYS_shmget: ::c_long = 194; +pub const SYS_shmctl: ::c_long = 195; +pub const SYS_shmat: ::c_long = 196; +pub const SYS_shmdt: ::c_long = 197; +pub const SYS_socket: ::c_long = 198; +pub const SYS_socketpair: ::c_long = 199; +pub const SYS_bind: ::c_long = 200; +pub const SYS_listen: ::c_long = 201; +pub const SYS_accept: ::c_long = 202; +pub const SYS_connect: ::c_long = 203; +pub const SYS_getsockname: ::c_long = 204; +pub const SYS_getpeername: ::c_long = 205; +pub const SYS_sendto: ::c_long = 206; +pub const SYS_recvfrom: ::c_long = 207; +pub const SYS_setsockopt: ::c_long = 208; +pub const SYS_getsockopt: ::c_long = 209; +pub const SYS_shutdown: ::c_long = 210; +pub const SYS_sendmsg: ::c_long = 211; +pub const SYS_recvmsg: ::c_long = 212; +pub const SYS_readahead: ::c_long = 213; +pub const SYS_brk: ::c_long = 214; +pub const SYS_munmap: ::c_long = 215; +pub const SYS_mremap: ::c_long = 216; +pub const SYS_add_key: ::c_long = 217; +pub const SYS_request_key: ::c_long = 218; +pub const SYS_keyctl: ::c_long = 219; +pub const SYS_clone: ::c_long = 220; +pub const SYS_execve: ::c_long = 221; +pub const SYS_mmap: ::c_long = 222; +pub const SYS_swapon: ::c_long = 224; +pub const SYS_swapoff: ::c_long = 225; +pub const SYS_mprotect: ::c_long = 226; +pub const SYS_msync: ::c_long = 227; +pub const SYS_mlock: ::c_long = 228; +pub const SYS_munlock: ::c_long = 229; +pub const SYS_mlockall: ::c_long = 230; +pub const SYS_munlockall: ::c_long = 231; +pub const SYS_mincore: ::c_long = 232; +pub const SYS_madvise: ::c_long = 233; +pub const SYS_remap_file_pages: ::c_long = 234; +pub const SYS_mbind: ::c_long = 235; +pub const SYS_get_mempolicy: ::c_long = 236; +pub const SYS_set_mempolicy: ::c_long = 237; +pub const SYS_migrate_pages: ::c_long = 238; +pub const SYS_move_pages: ::c_long = 239; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 240; +pub const SYS_perf_event_open: ::c_long = 241; +pub const SYS_accept4: ::c_long = 242; +pub const SYS_recvmmsg: ::c_long = 243; +pub const SYS_arch_specific_syscall: ::c_long = 244; +pub const SYS_wait4: ::c_long = 260; +pub const SYS_prlimit64: ::c_long = 261; +pub const SYS_fanotify_init: ::c_long = 262; +pub const SYS_fanotify_mark: ::c_long = 263; +pub const SYS_name_to_handle_at: ::c_long = 264; +pub const SYS_open_by_handle_at: ::c_long = 265; +pub const SYS_clock_adjtime: ::c_long = 266; +pub const SYS_syncfs: ::c_long = 267; +pub const SYS_setns: ::c_long = 268; +pub const SYS_sendmmsg: ::c_long = 269; +pub const SYS_process_vm_readv: ::c_long = 270; +pub const SYS_process_vm_writev: ::c_long = 271; +pub const SYS_kcmp: ::c_long = 272; +pub const SYS_finit_module: ::c_long = 273; +pub const SYS_sched_setattr: ::c_long = 274; +pub const SYS_sched_getattr: ::c_long = 275; +pub const SYS_renameat2: ::c_long = 276; +pub const SYS_seccomp: ::c_long = 277; +pub const SYS_getrandom: ::c_long = 278; +pub const SYS_memfd_create: ::c_long = 279; +pub const SYS_bpf: ::c_long = 280; +pub const SYS_execveat: ::c_long = 281; +pub const SYS_userfaultfd: ::c_long = 282; +pub const SYS_membarrier: ::c_long = 283; +pub const SYS_mlock2: ::c_long = 284; +pub const SYS_copy_file_range: ::c_long = 285; +pub const SYS_preadv2: ::c_long = 286; +pub const SYS_pwritev2: ::c_long = 287; +pub const SYS_pkey_mprotect: ::c_long = 288; +pub const SYS_pkey_alloc: ::c_long = 289; +pub const SYS_pkey_free: ::c_long = 290; +pub const SYS_syscalls: ::c_long = 291; + +#[link(name = "util")] +extern { + pub fn sysctl(name: *mut ::c_int, + namelen: ::c_int, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *mut ::c_void, + newlen: ::size_t) + -> ::c_int; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,85 @@ +//! 64-bit specific definitions for linux-like values + +pub type clock_t = i64; +pub type time_t = i64; +pub type ino_t = u64; +pub type off_t = i64; +pub type blkcnt_t = i64; +pub type __fsword_t = i64; +pub type shmatt_t = u64; +pub type msgqnum_t = u64; +pub type msglen_t = u64; +pub type fsblkcnt_t = u64; +pub type fsfilcnt_t = u64; +pub type rlim_t = u64; + +s! { + pub struct sigset_t { + #[cfg(target_pointer_width = "32")] + __val: [u32; 32], + #[cfg(target_pointer_width = "64")] + __val: [u64; 16], + } + + pub struct sysinfo { + pub uptime: i64, + pub loads: [u64; 3], + pub totalram: u64, + pub freeram: u64, + pub sharedram: u64, + pub bufferram: u64, + pub totalswap: u64, + pub freeswap: u64, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: u64, + pub freehigh: u64, + pub mem_unit: ::c_uint, + pub _f: [::c_char; 0], + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_stime: ::time_t, + pub msg_rtime: ::time_t, + pub msg_ctime: ::time_t, + __msg_cbytes: u64, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __glibc_reserved4: u64, + __glibc_reserved5: u64, + } +} + +pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; + +pub const O_LARGEFILE: ::c_int = 0; + +cfg_if! { + if #[cfg(target_arch = "aarch64")] { + mod aarch64; + pub use self::aarch64::*; + } else if #[cfg(any(target_arch = "powerpc64"))] { + mod powerpc64; + pub use self::powerpc64::*; + } else if #[cfg(any(target_arch = "sparc64"))] { + mod sparc64; + pub use self::sparc64::*; + } else if #[cfg(any(target_arch = "x86_64"))] { + mod x86_64; + pub use self::x86_64::*; + cfg_if! { + if #[cfg(target_pointer_width = "32")] { + mod x32; + pub use self::x32::*; + } else { + mod not_x32; + pub use self::not_x32::*; + } + } + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/not_x32.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/not_x32.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/not_x32.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/not_x32.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,351 @@ +pub type c_long = i64; +pub type c_ulong = u64; + +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; + +// Syscall table + +pub const SYS_read: ::c_long = 0; +pub const SYS_write: ::c_long = 1; +pub const SYS_open: ::c_long = 2; +pub const SYS_close: ::c_long = 3; +pub const SYS_stat: ::c_long = 4; +pub const SYS_fstat: ::c_long = 5; +pub const SYS_lstat: ::c_long = 6; +pub const SYS_poll: ::c_long = 7; +pub const SYS_lseek: ::c_long = 8; +pub const SYS_mmap: ::c_long = 9; +pub const SYS_mprotect: ::c_long = 10; +pub const SYS_munmap: ::c_long = 11; +pub const SYS_brk: ::c_long = 12; +pub const SYS_rt_sigaction: ::c_long = 13; +pub const SYS_rt_sigprocmask: ::c_long = 14; +pub const SYS_rt_sigreturn: ::c_long = 15; +pub const SYS_ioctl: ::c_long = 16; +pub const SYS_pread64: ::c_long = 17; +pub const SYS_pwrite64: ::c_long = 18; +pub const SYS_readv: ::c_long = 19; +pub const SYS_writev: ::c_long = 20; +pub const SYS_access: ::c_long = 21; +pub const SYS_pipe: ::c_long = 22; +pub const SYS_select: ::c_long = 23; +pub const SYS_sched_yield: ::c_long = 24; +pub const SYS_mremap: ::c_long = 25; +pub const SYS_msync: ::c_long = 26; +pub const SYS_mincore: ::c_long = 27; +pub const SYS_madvise: ::c_long = 28; +pub const SYS_shmget: ::c_long = 29; +pub const SYS_shmat: ::c_long = 30; +pub const SYS_shmctl: ::c_long = 31; +pub const SYS_dup: ::c_long = 32; +pub const SYS_dup2: ::c_long = 33; +pub const SYS_pause: ::c_long = 34; +pub const SYS_nanosleep: ::c_long = 35; +pub const SYS_getitimer: ::c_long = 36; +pub const SYS_alarm: ::c_long = 37; +pub const SYS_setitimer: ::c_long = 38; +pub const SYS_getpid: ::c_long = 39; +pub const SYS_sendfile: ::c_long = 40; +pub const SYS_socket: ::c_long = 41; +pub const SYS_connect: ::c_long = 42; +pub const SYS_accept: ::c_long = 43; +pub const SYS_sendto: ::c_long = 44; +pub const SYS_recvfrom: ::c_long = 45; +pub const SYS_sendmsg: ::c_long = 46; +pub const SYS_recvmsg: ::c_long = 47; +pub const SYS_shutdown: ::c_long = 48; +pub const SYS_bind: ::c_long = 49; +pub const SYS_listen: ::c_long = 50; +pub const SYS_getsockname: ::c_long = 51; +pub const SYS_getpeername: ::c_long = 52; +pub const SYS_socketpair: ::c_long = 53; +pub const SYS_setsockopt: ::c_long = 54; +pub const SYS_getsockopt: ::c_long = 55; +pub const SYS_clone: ::c_long = 56; +pub const SYS_fork: ::c_long = 57; +pub const SYS_vfork: ::c_long = 58; +pub const SYS_execve: ::c_long = 59; +pub const SYS_exit: ::c_long = 60; +pub const SYS_wait4: ::c_long = 61; +pub const SYS_kill: ::c_long = 62; +pub const SYS_uname: ::c_long = 63; +pub const SYS_semget: ::c_long = 64; +pub const SYS_semop: ::c_long = 65; +pub const SYS_semctl: ::c_long = 66; +pub const SYS_shmdt: ::c_long = 67; +pub const SYS_msgget: ::c_long = 68; +pub const SYS_msgsnd: ::c_long = 69; +pub const SYS_msgrcv: ::c_long = 70; +pub const SYS_msgctl: ::c_long = 71; +pub const SYS_fcntl: ::c_long = 72; +pub const SYS_flock: ::c_long = 73; +pub const SYS_fsync: ::c_long = 74; +pub const SYS_fdatasync: ::c_long = 75; +pub const SYS_truncate: ::c_long = 76; +pub const SYS_ftruncate: ::c_long = 77; +pub const SYS_getdents: ::c_long = 78; +pub const SYS_getcwd: ::c_long = 79; +pub const SYS_chdir: ::c_long = 80; +pub const SYS_fchdir: ::c_long = 81; +pub const SYS_rename: ::c_long = 82; +pub const SYS_mkdir: ::c_long = 83; +pub const SYS_rmdir: ::c_long = 84; +pub const SYS_creat: ::c_long = 85; +pub const SYS_link: ::c_long = 86; +pub const SYS_unlink: ::c_long = 87; +pub const SYS_symlink: ::c_long = 88; +pub const SYS_readlink: ::c_long = 89; +pub const SYS_chmod: ::c_long = 90; +pub const SYS_fchmod: ::c_long = 91; +pub const SYS_chown: ::c_long = 92; +pub const SYS_fchown: ::c_long = 93; +pub const SYS_lchown: ::c_long = 94; +pub const SYS_umask: ::c_long = 95; +pub const SYS_gettimeofday: ::c_long = 96; +pub const SYS_getrlimit: ::c_long = 97; +pub const SYS_getrusage: ::c_long = 98; +pub const SYS_sysinfo: ::c_long = 99; +pub const SYS_times: ::c_long = 100; +pub const SYS_ptrace: ::c_long = 101; +pub const SYS_getuid: ::c_long = 102; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_getgid: ::c_long = 104; +pub const SYS_setuid: ::c_long = 105; +pub const SYS_setgid: ::c_long = 106; +pub const SYS_geteuid: ::c_long = 107; +pub const SYS_getegid: ::c_long = 108; +pub const SYS_setpgid: ::c_long = 109; +pub const SYS_getppid: ::c_long = 110; +pub const SYS_getpgrp: ::c_long = 111; +pub const SYS_setsid: ::c_long = 112; +pub const SYS_setreuid: ::c_long = 113; +pub const SYS_setregid: ::c_long = 114; +pub const SYS_getgroups: ::c_long = 115; +pub const SYS_setgroups: ::c_long = 116; +pub const SYS_setresuid: ::c_long = 117; +pub const SYS_getresuid: ::c_long = 118; +pub const SYS_setresgid: ::c_long = 119; +pub const SYS_getresgid: ::c_long = 120; +pub const SYS_getpgid: ::c_long = 121; +pub const SYS_setfsuid: ::c_long = 122; +pub const SYS_setfsgid: ::c_long = 123; +pub const SYS_getsid: ::c_long = 124; +pub const SYS_capget: ::c_long = 125; +pub const SYS_capset: ::c_long = 126; +pub const SYS_rt_sigpending: ::c_long = 127; +pub const SYS_rt_sigtimedwait: ::c_long = 128; +pub const SYS_rt_sigqueueinfo: ::c_long = 129; +pub const SYS_rt_sigsuspend: ::c_long = 130; +pub const SYS_sigaltstack: ::c_long = 131; +pub const SYS_utime: ::c_long = 132; +pub const SYS_mknod: ::c_long = 133; +pub const SYS_uselib: ::c_long = 134; +pub const SYS_personality: ::c_long = 135; +pub const SYS_ustat: ::c_long = 136; +pub const SYS_statfs: ::c_long = 137; +pub const SYS_fstatfs: ::c_long = 138; +pub const SYS_sysfs: ::c_long = 139; +pub const SYS_getpriority: ::c_long = 140; +pub const SYS_setpriority: ::c_long = 141; +pub const SYS_sched_setparam: ::c_long = 142; +pub const SYS_sched_getparam: ::c_long = 143; +pub const SYS_sched_setscheduler: ::c_long = 144; +pub const SYS_sched_getscheduler: ::c_long = 145; +pub const SYS_sched_get_priority_max: ::c_long = 146; +pub const SYS_sched_get_priority_min: ::c_long = 147; +pub const SYS_sched_rr_get_interval: ::c_long = 148; +pub const SYS_mlock: ::c_long = 149; +pub const SYS_munlock: ::c_long = 150; +pub const SYS_mlockall: ::c_long = 151; +pub const SYS_munlockall: ::c_long = 152; +pub const SYS_vhangup: ::c_long = 153; +pub const SYS_modify_ldt: ::c_long = 154; +pub const SYS_pivot_root: ::c_long = 155; +pub const SYS__sysctl: ::c_long = 156; +pub const SYS_prctl: ::c_long = 157; +pub const SYS_arch_prctl: ::c_long = 158; +pub const SYS_adjtimex: ::c_long = 159; +pub const SYS_setrlimit: ::c_long = 160; +pub const SYS_chroot: ::c_long = 161; +pub const SYS_sync: ::c_long = 162; +pub const SYS_acct: ::c_long = 163; +pub const SYS_settimeofday: ::c_long = 164; +pub const SYS_mount: ::c_long = 165; +pub const SYS_umount2: ::c_long = 166; +pub const SYS_swapon: ::c_long = 167; +pub const SYS_swapoff: ::c_long = 168; +pub const SYS_reboot: ::c_long = 169; +pub const SYS_sethostname: ::c_long = 170; +pub const SYS_setdomainname: ::c_long = 171; +pub const SYS_iopl: ::c_long = 172; +pub const SYS_ioperm: ::c_long = 173; +pub const SYS_create_module: ::c_long = 174; +pub const SYS_init_module: ::c_long = 175; +pub const SYS_delete_module: ::c_long = 176; +pub const SYS_get_kernel_syms: ::c_long = 177; +pub const SYS_query_module: ::c_long = 178; +pub const SYS_quotactl: ::c_long = 179; +pub const SYS_nfsservctl: ::c_long = 180; +pub const SYS_getpmsg: ::c_long = 181; +pub const SYS_putpmsg: ::c_long = 182; +pub const SYS_afs_syscall: ::c_long = 183; +pub const SYS_tuxcall: ::c_long = 184; +pub const SYS_security: ::c_long = 185; +pub const SYS_gettid: ::c_long = 186; +pub const SYS_readahead: ::c_long = 187; +pub const SYS_setxattr: ::c_long = 188; +pub const SYS_lsetxattr: ::c_long = 189; +pub const SYS_fsetxattr: ::c_long = 190; +pub const SYS_getxattr: ::c_long = 191; +pub const SYS_lgetxattr: ::c_long = 192; +pub const SYS_fgetxattr: ::c_long = 193; +pub const SYS_listxattr: ::c_long = 194; +pub const SYS_llistxattr: ::c_long = 195; +pub const SYS_flistxattr: ::c_long = 196; +pub const SYS_removexattr: ::c_long = 197; +pub const SYS_lremovexattr: ::c_long = 198; +pub const SYS_fremovexattr: ::c_long = 199; +pub const SYS_tkill: ::c_long = 200; +pub const SYS_time: ::c_long = 201; +pub const SYS_futex: ::c_long = 202; +pub const SYS_sched_setaffinity: ::c_long = 203; +pub const SYS_sched_getaffinity: ::c_long = 204; +pub const SYS_set_thread_area: ::c_long = 205; +pub const SYS_io_setup: ::c_long = 206; +pub const SYS_io_destroy: ::c_long = 207; +pub const SYS_io_getevents: ::c_long = 208; +pub const SYS_io_submit: ::c_long = 209; +pub const SYS_io_cancel: ::c_long = 210; +pub const SYS_get_thread_area: ::c_long = 211; +pub const SYS_lookup_dcookie: ::c_long = 212; +pub const SYS_epoll_create: ::c_long = 213; +pub const SYS_epoll_ctl_old: ::c_long = 214; +pub const SYS_epoll_wait_old: ::c_long = 215; +pub const SYS_remap_file_pages: ::c_long = 216; +pub const SYS_getdents64: ::c_long = 217; +pub const SYS_set_tid_address: ::c_long = 218; +pub const SYS_restart_syscall: ::c_long = 219; +pub const SYS_semtimedop: ::c_long = 220; +pub const SYS_fadvise64: ::c_long = 221; +pub const SYS_timer_create: ::c_long = 222; +pub const SYS_timer_settime: ::c_long = 223; +pub const SYS_timer_gettime: ::c_long = 224; +pub const SYS_timer_getoverrun: ::c_long = 225; +pub const SYS_timer_delete: ::c_long = 226; +pub const SYS_clock_settime: ::c_long = 227; +pub const SYS_clock_gettime: ::c_long = 228; +pub const SYS_clock_getres: ::c_long = 229; +pub const SYS_clock_nanosleep: ::c_long = 230; +pub const SYS_exit_group: ::c_long = 231; +pub const SYS_epoll_wait: ::c_long = 232; +pub const SYS_epoll_ctl: ::c_long = 233; +pub const SYS_tgkill: ::c_long = 234; +pub const SYS_utimes: ::c_long = 235; +pub const SYS_vserver: ::c_long = 236; +pub const SYS_mbind: ::c_long = 237; +pub const SYS_set_mempolicy: ::c_long = 238; +pub const SYS_get_mempolicy: ::c_long = 239; +pub const SYS_mq_open: ::c_long = 240; +pub const SYS_mq_unlink: ::c_long = 241; +pub const SYS_mq_timedsend: ::c_long = 242; +pub const SYS_mq_timedreceive: ::c_long = 243; +pub const SYS_mq_notify: ::c_long = 244; +pub const SYS_mq_getsetattr: ::c_long = 245; +pub const SYS_kexec_load: ::c_long = 246; +pub const SYS_waitid: ::c_long = 247; +pub const SYS_add_key: ::c_long = 248; +pub const SYS_request_key: ::c_long = 249; +pub const SYS_keyctl: ::c_long = 250; +pub const SYS_ioprio_set: ::c_long = 251; +pub const SYS_ioprio_get: ::c_long = 252; +pub const SYS_inotify_init: ::c_long = 253; +pub const SYS_inotify_add_watch: ::c_long = 254; +pub const SYS_inotify_rm_watch: ::c_long = 255; +pub const SYS_migrate_pages: ::c_long = 256; +pub const SYS_openat: ::c_long = 257; +pub const SYS_mkdirat: ::c_long = 258; +pub const SYS_mknodat: ::c_long = 259; +pub const SYS_fchownat: ::c_long = 260; +pub const SYS_futimesat: ::c_long = 261; +pub const SYS_newfstatat: ::c_long = 262; +pub const SYS_unlinkat: ::c_long = 263; +pub const SYS_renameat: ::c_long = 264; +pub const SYS_linkat: ::c_long = 265; +pub const SYS_symlinkat: ::c_long = 266; +pub const SYS_readlinkat: ::c_long = 267; +pub const SYS_fchmodat: ::c_long = 268; +pub const SYS_faccessat: ::c_long = 269; +pub const SYS_pselect6: ::c_long = 270; +pub const SYS_ppoll: ::c_long = 271; +pub const SYS_unshare: ::c_long = 272; +pub const SYS_set_robust_list: ::c_long = 273; +pub const SYS_get_robust_list: ::c_long = 274; +pub const SYS_splice: ::c_long = 275; +pub const SYS_tee: ::c_long = 276; +pub const SYS_sync_file_range: ::c_long = 277; +pub const SYS_vmsplice: ::c_long = 278; +pub const SYS_move_pages: ::c_long = 279; +pub const SYS_utimensat: ::c_long = 280; +pub const SYS_epoll_pwait: ::c_long = 281; +pub const SYS_signalfd: ::c_long = 282; +pub const SYS_timerfd_create: ::c_long = 283; +pub const SYS_eventfd: ::c_long = 284; +pub const SYS_fallocate: ::c_long = 285; +pub const SYS_timerfd_settime: ::c_long = 286; +pub const SYS_timerfd_gettime: ::c_long = 287; +pub const SYS_accept4: ::c_long = 288; +pub const SYS_signalfd4: ::c_long = 289; +pub const SYS_eventfd2: ::c_long = 290; +pub const SYS_epoll_create1: ::c_long = 291; +pub const SYS_dup3: ::c_long = 292; +pub const SYS_pipe2: ::c_long = 293; +pub const SYS_inotify_init1: ::c_long = 294; +pub const SYS_preadv: ::c_long = 295; +pub const SYS_pwritev: ::c_long = 296; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 297; +pub const SYS_perf_event_open: ::c_long = 298; +pub const SYS_recvmmsg: ::c_long = 299; +pub const SYS_fanotify_init: ::c_long = 300; +pub const SYS_fanotify_mark: ::c_long = 301; +pub const SYS_prlimit64: ::c_long = 302; +pub const SYS_name_to_handle_at: ::c_long = 303; +pub const SYS_open_by_handle_at: ::c_long = 304; +pub const SYS_clock_adjtime: ::c_long = 305; +pub const SYS_syncfs: ::c_long = 306; +pub const SYS_sendmmsg: ::c_long = 307; +pub const SYS_setns: ::c_long = 308; +pub const SYS_getcpu: ::c_long = 309; +pub const SYS_process_vm_readv: ::c_long = 310; +pub const SYS_process_vm_writev: ::c_long = 311; +pub const SYS_kcmp: ::c_long = 312; +pub const SYS_finit_module: ::c_long = 313; +pub const SYS_sched_setattr: ::c_long = 314; +pub const SYS_sched_getattr: ::c_long = 315; +pub const SYS_renameat2: ::c_long = 316; +pub const SYS_seccomp: ::c_long = 317; +pub const SYS_getrandom: ::c_long = 318; +pub const SYS_memfd_create: ::c_long = 319; +pub const SYS_kexec_file_load: ::c_long = 320; +pub const SYS_bpf: ::c_long = 321; +pub const SYS_execveat: ::c_long = 322; +pub const SYS_userfaultfd: ::c_long = 323; +pub const SYS_membarrier: ::c_long = 324; +pub const SYS_mlock2: ::c_long = 325; +pub const SYS_copy_file_range: ::c_long = 326; +pub const SYS_preadv2: ::c_long = 327; +pub const SYS_pwritev2: ::c_long = 328; +pub const SYS_pkey_mprotect: ::c_long = 329; +pub const SYS_pkey_alloc: ::c_long = 330; +pub const SYS_pkey_free: ::c_long = 331; + +#[link(name = "util")] +extern { + pub fn sysctl(name: *mut ::c_int, + namelen: ::c_int, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *mut ::c_void, + newlen: ::size_t) + -> ::c_int; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/powerpc64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/powerpc64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/powerpc64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/powerpc64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,860 @@ +//! PowerPC64-specific definitions for 64-bit linux-like values + +pub type c_long = i64; +pub type c_ulong = u64; +pub type c_char = u8; +pub type wchar_t = i32; +pub type nlink_t = u64; +pub type blksize_t = i64; +pub type suseconds_t = i64; +pub type __u64 = ::c_ulong; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + __pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused: [::c_long; 3], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino64_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + __pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off64_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __reserved: [::c_long; 3], + } + + pub struct statfs64 { + pub f_type: ::__fsword_t, + pub f_bsize: ::__fsword_t, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_fsid: ::fsid_t, + pub f_namelen: ::__fsword_t, + pub f_frsize: ::__fsword_t, + pub f_flags: ::__fsword_t, + pub f_spare: [::__fsword_t; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct pthread_attr_t { + __size: [u64; 7] + } + + pub struct ipc_perm { + pub __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + pub __seq: ::uint32_t, + __pad1: ::uint32_t, + __unused1: ::uint64_t, + __unused2: ::c_ulong, + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_segsz: ::size_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __unused4: ::c_ulong, + __unused5: ::c_ulong + } +} + +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; + +pub const TIOCGSOFTCAR: ::c_ulong = 0x5419; +pub const TIOCSSOFTCAR: ::c_ulong = 0x541A; + +pub const RLIMIT_NOFILE: ::c_int = 7; +pub const RLIMIT_NPROC: ::c_int = 6; + +pub const O_APPEND: ::c_int = 1024; +pub const O_CREAT: ::c_int = 64; +pub const O_EXCL: ::c_int = 128; +pub const O_NOCTTY: ::c_int = 256; +pub const O_NONBLOCK: ::c_int = 2048; +pub const O_SYNC: ::c_int = 1052672; +pub const O_RSYNC: ::c_int = 1052672; +pub const O_DSYNC: ::c_int = 4096; +pub const O_FSYNC: ::c_int = 0x101000; +pub const O_NOATIME: ::c_int = 0o1000000; +pub const O_PATH: ::c_int = 0o10000000; +pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; + +pub const MAP_GROWSDOWN: ::c_int = 0x0100; + +pub const EDEADLK: ::c_int = 35; +pub const ENAMETOOLONG: ::c_int = 36; +pub const ENOLCK: ::c_int = 37; +pub const ENOSYS: ::c_int = 38; +pub const ENOTEMPTY: ::c_int = 39; +pub const ELOOP: ::c_int = 40; +pub const ENOMSG: ::c_int = 42; +pub const EIDRM: ::c_int = 43; +pub const ECHRNG: ::c_int = 44; +pub const EL2NSYNC: ::c_int = 45; +pub const EL3HLT: ::c_int = 46; +pub const EL3RST: ::c_int = 47; +pub const ELNRNG: ::c_int = 48; +pub const EUNATCH: ::c_int = 49; +pub const ENOCSI: ::c_int = 50; +pub const EL2HLT: ::c_int = 51; +pub const EBADE: ::c_int = 52; +pub const EBADR: ::c_int = 53; +pub const EXFULL: ::c_int = 54; +pub const ENOANO: ::c_int = 55; +pub const EBADRQC: ::c_int = 56; +pub const EBADSLT: ::c_int = 57; +pub const EMULTIHOP: ::c_int = 72; +pub const EOVERFLOW: ::c_int = 75; +pub const ENOTUNIQ: ::c_int = 76; +pub const EBADFD: ::c_int = 77; +pub const EBADMSG: ::c_int = 74; +pub const EREMCHG: ::c_int = 78; +pub const ELIBACC: ::c_int = 79; +pub const ELIBBAD: ::c_int = 80; +pub const ELIBSCN: ::c_int = 81; +pub const ELIBMAX: ::c_int = 82; +pub const ELIBEXEC: ::c_int = 83; +pub const EILSEQ: ::c_int = 84; +pub const ERESTART: ::c_int = 85; +pub const ESTRPIPE: ::c_int = 86; +pub const EUSERS: ::c_int = 87; +pub const ENOTSOCK: ::c_int = 88; +pub const EDESTADDRREQ: ::c_int = 89; +pub const EMSGSIZE: ::c_int = 90; +pub const EPROTOTYPE: ::c_int = 91; +pub const ENOPROTOOPT: ::c_int = 92; +pub const EPROTONOSUPPORT: ::c_int = 93; +pub const ESOCKTNOSUPPORT: ::c_int = 94; +pub const EOPNOTSUPP: ::c_int = 95; +pub const EPFNOSUPPORT: ::c_int = 96; +pub const EAFNOSUPPORT: ::c_int = 97; +pub const EADDRINUSE: ::c_int = 98; +pub const EADDRNOTAVAIL: ::c_int = 99; +pub const ENETDOWN: ::c_int = 100; +pub const ENETUNREACH: ::c_int = 101; +pub const ENETRESET: ::c_int = 102; +pub const ECONNABORTED: ::c_int = 103; +pub const ECONNRESET: ::c_int = 104; +pub const ENOBUFS: ::c_int = 105; +pub const EISCONN: ::c_int = 106; +pub const ENOTCONN: ::c_int = 107; +pub const ESHUTDOWN: ::c_int = 108; +pub const ETOOMANYREFS: ::c_int = 109; +pub const ETIMEDOUT: ::c_int = 110; +pub const ECONNREFUSED: ::c_int = 111; +pub const EHOSTDOWN: ::c_int = 112; +pub const EHOSTUNREACH: ::c_int = 113; +pub const EALREADY: ::c_int = 114; +pub const EINPROGRESS: ::c_int = 115; +pub const ESTALE: ::c_int = 116; +pub const EDQUOT: ::c_int = 122; +pub const ENOMEDIUM: ::c_int = 123; +pub const EMEDIUMTYPE: ::c_int = 124; +pub const ECANCELED: ::c_int = 125; +pub const ENOKEY: ::c_int = 126; +pub const EKEYEXPIRED: ::c_int = 127; +pub const EKEYREVOKED: ::c_int = 128; +pub const EKEYREJECTED: ::c_int = 129; +pub const EOWNERDEAD: ::c_int = 130; +pub const ENOTRECOVERABLE: ::c_int = 131; +pub const EHWPOISON: ::c_int = 133; +pub const ERFKILL: ::c_int = 132; + +pub const SOL_SOCKET: ::c_int = 1; + +pub const SO_REUSEADDR: ::c_int = 2; +pub const SO_TYPE: ::c_int = 3; +pub const SO_ERROR: ::c_int = 4; +pub const SO_DONTROUTE: ::c_int = 5; +pub const SO_BROADCAST: ::c_int = 6; +pub const SO_SNDBUF: ::c_int = 7; +pub const SO_RCVBUF: ::c_int = 8; +pub const SO_SNDBUFFORCE: ::c_int = 32; +pub const SO_RCVBUFFORCE: ::c_int = 33; +pub const SO_KEEPALIVE: ::c_int = 9; +pub const SO_OOBINLINE: ::c_int = 10; +pub const SO_NO_CHECK: ::c_int = 11; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_LINGER: ::c_int = 13; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_REUSEPORT: ::c_int = 15; +pub const SO_PASSCRED: ::c_int = 20; +pub const SO_PEERCRED: ::c_int = 21; +pub const SO_RCVLOWAT: ::c_int = 16; +pub const SO_SNDLOWAT: ::c_int = 17; +pub const SO_RCVTIMEO: ::c_int = 18; +pub const SO_SNDTIMEO: ::c_int = 19; +pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22; +pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23; +pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24; +pub const SO_BINDTODEVICE: ::c_int = 25; +pub const SO_ATTACH_FILTER: ::c_int = 26; +pub const SO_DETACH_FILTER: ::c_int = 27; +pub const SO_GET_FILTER: ::c_int = SO_ATTACH_FILTER; +pub const SO_PEERNAME: ::c_int = 28; +pub const SO_TIMESTAMP: ::c_int = 29; +pub const SO_ACCEPTCONN: ::c_int = 30; +pub const SO_PEERSEC: ::c_int = 31; +pub const SO_PASSSEC: ::c_int = 34; +pub const SO_TIMESTAMPNS: ::c_int = 35; +pub const SCM_TIMESTAMPNS: ::c_int = SO_TIMESTAMPNS; +pub const SO_MARK: ::c_int = 36; +pub const SO_TIMESTAMPING: ::c_int = 37; +pub const SCM_TIMESTAMPING: ::c_int = SO_TIMESTAMPING; +pub const SO_PROTOCOL: ::c_int = 38; +pub const SO_DOMAIN: ::c_int = 39; +pub const SO_RXQ_OVFL: ::c_int = 40; +pub const SO_WIFI_STATUS: ::c_int = 41; +pub const SCM_WIFI_STATUS: ::c_int = SO_WIFI_STATUS; +pub const SO_PEEK_OFF: ::c_int = 42; +pub const SO_NOFCS: ::c_int = 43; +pub const SO_LOCK_FILTER: ::c_int = 44; +pub const SO_SELECT_ERR_QUEUE: ::c_int = 45; +pub const SO_BUSY_POLL: ::c_int = 46; +pub const SO_MAX_PACING_RATE: ::c_int = 47; +pub const SO_BPF_EXTENSIONS: ::c_int = 48; +pub const SO_INCOMING_CPU: ::c_int = 49; +pub const SO_ATTACH_BPF: ::c_int = 50; +pub const SO_DETACH_BPF: ::c_int = SO_DETACH_FILTER; + +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 0x00000004; +pub const SA_NOCLDWAIT: ::c_int = 0x00000002; + +pub const SIGCHLD: ::c_int = 17; +pub const SIGBUS: ::c_int = 7; +pub const SIGUSR1: ::c_int = 10; +pub const SIGUSR2: ::c_int = 12; +pub const SIGCONT: ::c_int = 18; +pub const SIGSTOP: ::c_int = 19; +pub const SIGTSTP: ::c_int = 20; +pub const SIGURG: ::c_int = 23; +pub const SIGIO: ::c_int = 29; +pub const SIGSYS: ::c_int = 31; +pub const SIGSTKFLT: ::c_int = 16; +pub const SIGUNUSED: ::c_int = 31; +pub const SIGPOLL: ::c_int = 29; +pub const SIGPWR: ::c_int = 30; +pub const SIG_SETMASK: ::c_int = 2; +pub const SIG_BLOCK: ::c_int = 0x000000; +pub const SIG_UNBLOCK: ::c_int = 0x01; + +pub const POLLWRNORM: ::c_short = 0x100; +pub const POLLWRBAND: ::c_short = 0x200; + +pub const O_ASYNC: ::c_int = 0x2000; +pub const O_NDELAY: ::c_int = 0x800; + +pub const PTRACE_DETACH: ::c_uint = 17; + +pub const EFD_NONBLOCK: ::c_int = 0x800; + +pub const F_GETLK: ::c_int = 5; +pub const F_GETOWN: ::c_int = 9; +pub const F_SETOWN: ::c_int = 8; +pub const F_SETLK: ::c_int = 6; +pub const F_SETLKW: ::c_int = 7; + +pub const SFD_NONBLOCK: ::c_int = 0x0800; + +pub const TIOCEXCL: ::c_ulong = 0x540C; +pub const TIOCNXCL: ::c_ulong = 0x540D; +pub const TIOCSCTTY: ::c_ulong = 0x540E; +pub const TIOCSTI: ::c_ulong = 0x5412; +pub const TIOCMGET: ::c_ulong = 0x5415; +pub const TIOCMBIS: ::c_ulong = 0x5416; +pub const TIOCMBIC: ::c_ulong = 0x5417; +pub const TIOCMSET: ::c_ulong = 0x5418; +pub const TIOCCONS: ::c_ulong = 0x541D; + +pub const SFD_CLOEXEC: ::c_int = 0x080000; + +pub const NCCS: usize = 32; + +pub const O_TRUNC: ::c_int = 512; + +pub const O_CLOEXEC: ::c_int = 0x80000; + +pub const EBFONT: ::c_int = 59; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const EDOTDOT: ::c_int = 73; + +pub const SA_NODEFER: ::c_int = 0x40000000; +pub const SA_RESETHAND: ::c_int = 0x80000000; +pub const SA_RESTART: ::c_int = 0x10000000; +pub const SA_NOCLDSTOP: ::c_int = 0x00000001; + +pub const EPOLL_CLOEXEC: ::c_int = 0x80000; + +pub const EFD_CLOEXEC: ::c_int = 0x80000; + +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; + +pub const O_DIRECTORY: ::c_int = 0x4000; +pub const O_NOFOLLOW: ::c_int = 0x8000; +pub const O_DIRECT: ::c_int = 0x20000; + +pub const MAP_LOCKED: ::c_int = 0x00080; +pub const MAP_NORESERVE: ::c_int = 0x00040; + +pub const EDEADLOCK: ::c_int = 58; + +pub const FIOCLEX: ::c_ulong = 0x20006601; +pub const FIONBIO: ::c_ulong = 0x8004667e; + +pub const MCL_CURRENT: ::c_int = 0x2000; +pub const MCL_FUTURE: ::c_int = 0x4000; + +pub const SIGSTKSZ: ::size_t = 0x4000; +pub const MINSIGSTKSZ: ::size_t = 4096; +pub const CBAUD: ::tcflag_t = 0xff; +pub const TAB1: ::c_int = 0x400; +pub const TAB2: ::c_int = 0x800; +pub const TAB3: ::c_int = 0xc00; +pub const CR1: ::c_int = 0x1000; +pub const CR2: ::c_int = 0x2000; +pub const CR3: ::c_int = 0x3000; +pub const FF1: ::c_int = 0x4000; +pub const BS1: ::c_int = 0x8000; +pub const VT1: ::c_int = 0x10000; +pub const VWERASE: usize = 0xa; +pub const VREPRINT: usize = 0xb; +pub const VSUSP: usize = 0xc; +pub const VSTART: usize = 0xd; +pub const VSTOP: usize = 0xe; +pub const VDISCARD: usize = 0x10; +pub const VTIME: usize = 0x7; +pub const IXON: ::tcflag_t = 0x200; +pub const IXOFF: ::tcflag_t = 0x400; +pub const ONLCR: ::tcflag_t = 0x2; +pub const CSIZE: ::tcflag_t = 0x300; +pub const CS6: ::tcflag_t = 0x100; +pub const CS7: ::tcflag_t = 0x200; +pub const CS8: ::tcflag_t = 0x300; +pub const CSTOPB: ::tcflag_t = 0x400; +pub const CREAD: ::tcflag_t = 0x800; +pub const PARENB: ::tcflag_t = 0x1000; +pub const PARODD: ::tcflag_t = 0x2000; +pub const HUPCL: ::tcflag_t = 0x4000; +pub const CLOCAL: ::tcflag_t = 0x8000; +pub const ECHOKE: ::tcflag_t = 0x1; +pub const ECHOE: ::tcflag_t = 0x2; +pub const ECHOK: ::tcflag_t = 0x4; +pub const ECHONL: ::tcflag_t = 0x10; +pub const ECHOPRT: ::tcflag_t = 0x20; +pub const ECHOCTL: ::tcflag_t = 0x40; +pub const ISIG: ::tcflag_t = 0x80; +pub const ICANON: ::tcflag_t = 0x100; +pub const PENDIN: ::tcflag_t = 0x20000000; +pub const NOFLSH: ::tcflag_t = 0x80000000; +pub const VSWTC: usize = 9; +pub const OLCUC: ::tcflag_t = 0o000004; +pub const NLDLY: ::tcflag_t = 0o001400; +pub const CRDLY: ::tcflag_t = 0o030000; +pub const TABDLY: ::tcflag_t = 0o006000; +pub const BSDLY: ::tcflag_t = 0o100000; +pub const FFDLY: ::tcflag_t = 0o040000; +pub const VTDLY: ::tcflag_t = 0o200000; +pub const XTABS: ::tcflag_t = 0o006000; + +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const CBAUDEX: ::speed_t = 0o000020; +pub const B57600: ::speed_t = 0o0020; +pub const B115200: ::speed_t = 0o0021; +pub const B230400: ::speed_t = 0o0022; +pub const B460800: ::speed_t = 0o0023; +pub const B500000: ::speed_t = 0o0024; +pub const B576000: ::speed_t = 0o0025; +pub const B921600: ::speed_t = 0o0026; +pub const B1000000: ::speed_t = 0o0027; +pub const B1152000: ::speed_t = 0o0030; +pub const B1500000: ::speed_t = 0o0031; +pub const B2000000: ::speed_t = 0o0032; +pub const B2500000: ::speed_t = 0o0033; +pub const B3000000: ::speed_t = 0o0034; +pub const B3500000: ::speed_t = 0o0035; +pub const B4000000: ::speed_t = 0o0036; +pub const BOTHER: ::speed_t = 0o0037; + +pub const VEOL: usize = 6; +pub const VEOL2: usize = 8; +pub const VMIN: usize = 5; +pub const IEXTEN: ::tcflag_t = 0x400; +pub const TOSTOP: ::tcflag_t = 0x400000; +pub const FLUSHO: ::tcflag_t = 0x800000; +pub const EXTPROC: ::tcflag_t = 0x10000000; +pub const TCGETS: ::c_ulong = 0x403c7413; +pub const TCSETS: ::c_ulong = 0x803c7414; +pub const TCSETSW: ::c_ulong = 0x803c7415; +pub const TCSETSF: ::c_ulong = 0x803c7416; +pub const TCGETA: ::c_ulong = 0x40147417; +pub const TCSETA: ::c_ulong = 0x80147418; +pub const TCSETAW: ::c_ulong = 0x80147419; +pub const TCSETAF: ::c_ulong = 0x8014741c; +pub const TCSBRK: ::c_ulong = 0x2000741d; +pub const TCXONC: ::c_ulong = 0x2000741e; +pub const TCFLSH: ::c_ulong = 0x2000741f; +pub const TIOCINQ: ::c_ulong = 0x4004667f; +pub const TIOCGPGRP: ::c_ulong = 0x40047477; +pub const TIOCSPGRP: ::c_ulong = 0x80047476; +pub const TIOCOUTQ: ::c_ulong = 0x40047473; +pub const TIOCGWINSZ: ::c_ulong = 0x40087468; +pub const TIOCSWINSZ: ::c_ulong = 0x80087467; +pub const FIONREAD: ::c_ulong = 0x4004667f; + +// Syscall table +pub const SYS_restart_syscall: ::c_long = 0; +pub const SYS_exit: ::c_long = 1; +pub const SYS_fork: ::c_long = 2; +pub const SYS_read: ::c_long = 3; +pub const SYS_write: ::c_long = 4; +pub const SYS_open: ::c_long = 5; +pub const SYS_close: ::c_long = 6; +pub const SYS_waitpid: ::c_long = 7; +pub const SYS_creat: ::c_long = 8; +pub const SYS_link: ::c_long = 9; +pub const SYS_unlink: ::c_long = 10; +pub const SYS_execve: ::c_long = 11; +pub const SYS_chdir: ::c_long = 12; +pub const SYS_time: ::c_long = 13; +pub const SYS_mknod: ::c_long = 14; +pub const SYS_chmod: ::c_long = 15; +pub const SYS_lchown: ::c_long = 16; +pub const SYS_break: ::c_long = 17; +pub const SYS_oldstat: ::c_long = 18; +pub const SYS_lseek: ::c_long = 19; +pub const SYS_getpid: ::c_long = 20; +pub const SYS_mount: ::c_long = 21; +pub const SYS_umount: ::c_long = 22; +pub const SYS_setuid: ::c_long = 23; +pub const SYS_getuid: ::c_long = 24; +pub const SYS_stime: ::c_long = 25; +pub const SYS_ptrace: ::c_long = 26; +pub const SYS_alarm: ::c_long = 27; +pub const SYS_oldfstat: ::c_long = 28; +pub const SYS_pause: ::c_long = 29; +pub const SYS_utime: ::c_long = 30; +pub const SYS_stty: ::c_long = 31; +pub const SYS_gtty: ::c_long = 32; +pub const SYS_access: ::c_long = 33; +pub const SYS_nice: ::c_long = 34; +pub const SYS_ftime: ::c_long = 35; +pub const SYS_sync: ::c_long = 36; +pub const SYS_kill: ::c_long = 37; +pub const SYS_rename: ::c_long = 38; +pub const SYS_mkdir: ::c_long = 39; +pub const SYS_rmdir: ::c_long = 40; +pub const SYS_dup: ::c_long = 41; +pub const SYS_pipe: ::c_long = 42; +pub const SYS_times: ::c_long = 43; +pub const SYS_prof: ::c_long = 44; +pub const SYS_brk: ::c_long = 45; +pub const SYS_setgid: ::c_long = 46; +pub const SYS_getgid: ::c_long = 47; +pub const SYS_signal: ::c_long = 48; +pub const SYS_geteuid: ::c_long = 49; +pub const SYS_getegid: ::c_long = 50; +pub const SYS_acct: ::c_long = 51; +pub const SYS_umount2: ::c_long = 52; +pub const SYS_lock: ::c_long = 53; +pub const SYS_ioctl: ::c_long = 54; +pub const SYS_fcntl: ::c_long = 55; +pub const SYS_mpx: ::c_long = 56; +pub const SYS_setpgid: ::c_long = 57; +pub const SYS_ulimit: ::c_long = 58; +pub const SYS_oldolduname: ::c_long = 59; +pub const SYS_umask: ::c_long = 60; +pub const SYS_chroot: ::c_long = 61; +pub const SYS_ustat: ::c_long = 62; +pub const SYS_dup2: ::c_long = 63; +pub const SYS_getppid: ::c_long = 64; +pub const SYS_getpgrp: ::c_long = 65; +pub const SYS_setsid: ::c_long = 66; +pub const SYS_sigaction: ::c_long = 67; +pub const SYS_sgetmask: ::c_long = 68; +pub const SYS_ssetmask: ::c_long = 69; +pub const SYS_setreuid: ::c_long = 70; +pub const SYS_setregid: ::c_long = 71; +pub const SYS_sigsuspend: ::c_long = 72; +pub const SYS_sigpending: ::c_long = 73; +pub const SYS_sethostname: ::c_long = 74; +pub const SYS_setrlimit: ::c_long = 75; +pub const SYS_getrlimit: ::c_long = 76; +pub const SYS_getrusage: ::c_long = 77; +pub const SYS_gettimeofday: ::c_long = 78; +pub const SYS_settimeofday: ::c_long = 79; +pub const SYS_getgroups: ::c_long = 80; +pub const SYS_setgroups: ::c_long = 81; +pub const SYS_select: ::c_long = 82; +pub const SYS_symlink: ::c_long = 83; +pub const SYS_oldlstat: ::c_long = 84; +pub const SYS_readlink: ::c_long = 85; +pub const SYS_uselib: ::c_long = 86; +pub const SYS_swapon: ::c_long = 87; +pub const SYS_reboot: ::c_long = 88; +pub const SYS_readdir: ::c_long = 89; +pub const SYS_mmap: ::c_long = 90; +pub const SYS_munmap: ::c_long = 91; +pub const SYS_truncate: ::c_long = 92; +pub const SYS_ftruncate: ::c_long = 93; +pub const SYS_fchmod: ::c_long = 94; +pub const SYS_fchown: ::c_long = 95; +pub const SYS_getpriority: ::c_long = 96; +pub const SYS_setpriority: ::c_long = 97; +pub const SYS_profil: ::c_long = 98; +pub const SYS_statfs: ::c_long = 99; +pub const SYS_fstatfs: ::c_long = 100; +pub const SYS_ioperm: ::c_long = 101; +pub const SYS_socketcall: ::c_long = 102; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_setitimer: ::c_long = 104; +pub const SYS_getitimer: ::c_long = 105; +pub const SYS_stat: ::c_long = 106; +pub const SYS_lstat: ::c_long = 107; +pub const SYS_fstat: ::c_long = 108; +pub const SYS_olduname: ::c_long = 109; +pub const SYS_iopl: ::c_long = 110; +pub const SYS_vhangup: ::c_long = 111; +pub const SYS_idle: ::c_long = 112; +pub const SYS_vm86: ::c_long = 113; +pub const SYS_wait4: ::c_long = 114; +pub const SYS_swapoff: ::c_long = 115; +pub const SYS_sysinfo: ::c_long = 116; +pub const SYS_ipc: ::c_long = 117; +pub const SYS_fsync: ::c_long = 118; +pub const SYS_sigreturn: ::c_long = 119; +pub const SYS_clone: ::c_long = 120; +pub const SYS_setdomainname: ::c_long = 121; +pub const SYS_uname: ::c_long = 122; +pub const SYS_modify_ldt: ::c_long = 123; +pub const SYS_adjtimex: ::c_long = 124; +pub const SYS_mprotect: ::c_long = 125; +pub const SYS_sigprocmask: ::c_long = 126; +pub const SYS_create_module: ::c_long = 127; +pub const SYS_init_module: ::c_long = 128; +pub const SYS_delete_module: ::c_long = 129; +pub const SYS_get_kernel_syms: ::c_long = 130; +pub const SYS_quotactl: ::c_long = 131; +pub const SYS_getpgid: ::c_long = 132; +pub const SYS_fchdir: ::c_long = 133; +pub const SYS_bdflush: ::c_long = 134; +pub const SYS_sysfs: ::c_long = 135; +pub const SYS_personality: ::c_long = 136; +pub const SYS_afs_syscall: ::c_long = 137; /* Syscall for Andrew File System */ +pub const SYS_setfsuid: ::c_long = 138; +pub const SYS_setfsgid: ::c_long = 139; +pub const SYS__llseek: ::c_long = 140; +pub const SYS_getdents: ::c_long = 141; +pub const SYS__newselect: ::c_long = 142; +pub const SYS_flock: ::c_long = 143; +pub const SYS_msync: ::c_long = 144; +pub const SYS_readv: ::c_long = 145; +pub const SYS_writev: ::c_long = 146; +pub const SYS_getsid: ::c_long = 147; +pub const SYS_fdatasync: ::c_long = 148; +pub const SYS__sysctl: ::c_long = 149; +pub const SYS_mlock: ::c_long = 150; +pub const SYS_munlock: ::c_long = 151; +pub const SYS_mlockall: ::c_long = 152; +pub const SYS_munlockall: ::c_long = 153; +pub const SYS_sched_setparam: ::c_long = 154; +pub const SYS_sched_getparam: ::c_long = 155; +pub const SYS_sched_setscheduler: ::c_long = 156; +pub const SYS_sched_getscheduler: ::c_long = 157; +pub const SYS_sched_yield: ::c_long = 158; +pub const SYS_sched_get_priority_max: ::c_long = 159; +pub const SYS_sched_get_priority_min: ::c_long = 160; +pub const SYS_sched_rr_get_interval: ::c_long = 161; +pub const SYS_nanosleep: ::c_long = 162; +pub const SYS_mremap: ::c_long = 163; +pub const SYS_setresuid: ::c_long = 164; +pub const SYS_getresuid: ::c_long = 165; +pub const SYS_query_module: ::c_long = 166; +pub const SYS_poll: ::c_long = 167; +pub const SYS_nfsservctl: ::c_long = 168; +pub const SYS_setresgid: ::c_long = 169; +pub const SYS_getresgid: ::c_long = 170; +pub const SYS_prctl: ::c_long = 171; +pub const SYS_rt_sigreturn: ::c_long = 172; +pub const SYS_rt_sigaction: ::c_long = 173; +pub const SYS_rt_sigprocmask: ::c_long = 174; +pub const SYS_rt_sigpending: ::c_long = 175; +pub const SYS_rt_sigtimedwait: ::c_long = 176; +pub const SYS_rt_sigqueueinfo: ::c_long = 177; +pub const SYS_rt_sigsuspend: ::c_long = 178; +pub const SYS_pread64: ::c_long = 179; +pub const SYS_pwrite64: ::c_long = 180; +pub const SYS_chown: ::c_long = 181; +pub const SYS_getcwd: ::c_long = 182; +pub const SYS_capget: ::c_long = 183; +pub const SYS_capset: ::c_long = 184; +pub const SYS_sigaltstack: ::c_long = 185; +pub const SYS_sendfile: ::c_long = 186; +pub const SYS_getpmsg: ::c_long = 187; /* some people actually want streams */ +pub const SYS_putpmsg: ::c_long = 188; /* some people actually want streams */ +pub const SYS_vfork: ::c_long = 189; +pub const SYS_ugetrlimit: ::c_long = 190; /* SuS compliant getrlimit */ +pub const SYS_readahead: ::c_long = 191; +pub const SYS_pciconfig_read: ::c_long = 198; +pub const SYS_pciconfig_write: ::c_long = 199; +pub const SYS_pciconfig_iobase: ::c_long = 200; +pub const SYS_multiplexer: ::c_long = 201; +pub const SYS_getdents64: ::c_long = 202; +pub const SYS_pivot_root: ::c_long = 203; +pub const SYS_madvise: ::c_long = 205; +pub const SYS_mincore: ::c_long = 206; +pub const SYS_gettid: ::c_long = 207; +pub const SYS_tkill: ::c_long = 208; +pub const SYS_setxattr: ::c_long = 209; +pub const SYS_lsetxattr: ::c_long = 210; +pub const SYS_fsetxattr: ::c_long = 211; +pub const SYS_getxattr: ::c_long = 212; +pub const SYS_lgetxattr: ::c_long = 213; +pub const SYS_fgetxattr: ::c_long = 214; +pub const SYS_listxattr: ::c_long = 215; +pub const SYS_llistxattr: ::c_long = 216; +pub const SYS_flistxattr: ::c_long = 217; +pub const SYS_removexattr: ::c_long = 218; +pub const SYS_lremovexattr: ::c_long = 219; +pub const SYS_fremovexattr: ::c_long = 220; +pub const SYS_futex: ::c_long = 221; +pub const SYS_sched_setaffinity: ::c_long = 222; +pub const SYS_sched_getaffinity: ::c_long = 223; +pub const SYS_tuxcall: ::c_long = 225; +pub const SYS_io_setup: ::c_long = 227; +pub const SYS_io_destroy: ::c_long = 228; +pub const SYS_io_getevents: ::c_long = 229; +pub const SYS_io_submit: ::c_long = 230; +pub const SYS_io_cancel: ::c_long = 231; +pub const SYS_set_tid_address: ::c_long = 232; +pub const SYS_exit_group: ::c_long = 234; +pub const SYS_lookup_dcookie: ::c_long = 235; +pub const SYS_epoll_create: ::c_long = 236; +pub const SYS_epoll_ctl: ::c_long = 237; +pub const SYS_epoll_wait: ::c_long = 238; +pub const SYS_remap_file_pages: ::c_long = 239; +pub const SYS_timer_create: ::c_long = 240; +pub const SYS_timer_settime: ::c_long = 241; +pub const SYS_timer_gettime: ::c_long = 242; +pub const SYS_timer_getoverrun: ::c_long = 243; +pub const SYS_timer_delete: ::c_long = 244; +pub const SYS_clock_settime: ::c_long = 245; +pub const SYS_clock_gettime: ::c_long = 246; +pub const SYS_clock_getres: ::c_long = 247; +pub const SYS_clock_nanosleep: ::c_long = 248; +pub const SYS_swapcontext: ::c_long = 249; +pub const SYS_tgkill: ::c_long = 250; +pub const SYS_utimes: ::c_long = 251; +pub const SYS_statfs64: ::c_long = 252; +pub const SYS_fstatfs64: ::c_long = 253; +pub const SYS_rtas: ::c_long = 255; +pub const SYS_sys_debug_setcontext: ::c_long = 256; +pub const SYS_migrate_pages: ::c_long = 258; +pub const SYS_mbind: ::c_long = 259; +pub const SYS_get_mempolicy: ::c_long = 260; +pub const SYS_set_mempolicy: ::c_long = 261; +pub const SYS_mq_open: ::c_long = 262; +pub const SYS_mq_unlink: ::c_long = 263; +pub const SYS_mq_timedsend: ::c_long = 264; +pub const SYS_mq_timedreceive: ::c_long = 265; +pub const SYS_mq_notify: ::c_long = 266; +pub const SYS_mq_getsetattr: ::c_long = 267; +pub const SYS_kexec_load: ::c_long = 268; +pub const SYS_add_key: ::c_long = 269; +pub const SYS_request_key: ::c_long = 270; +pub const SYS_keyctl: ::c_long = 271; +pub const SYS_waitid: ::c_long = 272; +pub const SYS_ioprio_set: ::c_long = 273; +pub const SYS_ioprio_get: ::c_long = 274; +pub const SYS_inotify_init: ::c_long = 275; +pub const SYS_inotify_add_watch: ::c_long = 276; +pub const SYS_inotify_rm_watch: ::c_long = 277; +pub const SYS_spu_run: ::c_long = 278; +pub const SYS_spu_create: ::c_long = 279; +pub const SYS_pselect6: ::c_long = 280; +pub const SYS_ppoll: ::c_long = 281; +pub const SYS_unshare: ::c_long = 282; +pub const SYS_splice: ::c_long = 283; +pub const SYS_tee: ::c_long = 284; +pub const SYS_vmsplice: ::c_long = 285; +pub const SYS_openat: ::c_long = 286; +pub const SYS_mkdirat: ::c_long = 287; +pub const SYS_mknodat: ::c_long = 288; +pub const SYS_fchownat: ::c_long = 289; +pub const SYS_futimesat: ::c_long = 290; +pub const SYS_newfstatat: ::c_long = 291; +pub const SYS_unlinkat: ::c_long = 292; +pub const SYS_renameat: ::c_long = 293; +pub const SYS_linkat: ::c_long = 294; +pub const SYS_symlinkat: ::c_long = 295; +pub const SYS_readlinkat: ::c_long = 296; +pub const SYS_fchmodat: ::c_long = 297; +pub const SYS_faccessat: ::c_long = 298; +pub const SYS_get_robust_list: ::c_long = 299; +pub const SYS_set_robust_list: ::c_long = 300; +pub const SYS_move_pages: ::c_long = 301; +pub const SYS_getcpu: ::c_long = 302; +pub const SYS_epoll_pwait: ::c_long = 303; +pub const SYS_utimensat: ::c_long = 304; +pub const SYS_signalfd: ::c_long = 305; +pub const SYS_timerfd_create: ::c_long = 306; +pub const SYS_eventfd: ::c_long = 307; +pub const SYS_sync_file_range2: ::c_long = 308; +pub const SYS_fallocate: ::c_long = 309; +pub const SYS_subpage_prot: ::c_long = 310; +pub const SYS_timerfd_settime: ::c_long = 311; +pub const SYS_timerfd_gettime: ::c_long = 312; +pub const SYS_signalfd4: ::c_long = 313; +pub const SYS_eventfd2: ::c_long = 314; +pub const SYS_epoll_create1: ::c_long = 315; +pub const SYS_dup3: ::c_long = 316; +pub const SYS_pipe2: ::c_long = 317; +pub const SYS_inotify_init1: ::c_long = 318; +pub const SYS_perf_event_open: ::c_long = 319; +pub const SYS_preadv: ::c_long = 320; +pub const SYS_pwritev: ::c_long = 321; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 322; +pub const SYS_fanotify_init: ::c_long = 323; +pub const SYS_fanotify_mark: ::c_long = 324; +pub const SYS_prlimit64: ::c_long = 325; +pub const SYS_socket: ::c_long = 326; +pub const SYS_bind: ::c_long = 327; +pub const SYS_connect: ::c_long = 328; +pub const SYS_listen: ::c_long = 329; +pub const SYS_accept: ::c_long = 330; +pub const SYS_getsockname: ::c_long = 331; +pub const SYS_getpeername: ::c_long = 332; +pub const SYS_socketpair: ::c_long = 333; +pub const SYS_send: ::c_long = 334; +pub const SYS_sendto: ::c_long = 335; +pub const SYS_recv: ::c_long = 336; +pub const SYS_recvfrom: ::c_long = 337; +pub const SYS_shutdown: ::c_long = 338; +pub const SYS_setsockopt: ::c_long = 339; +pub const SYS_getsockopt: ::c_long = 340; +pub const SYS_sendmsg: ::c_long = 341; +pub const SYS_recvmsg: ::c_long = 342; +pub const SYS_recvmmsg: ::c_long = 343; +pub const SYS_accept4: ::c_long = 344; +pub const SYS_name_to_handle_at: ::c_long = 345; +pub const SYS_open_by_handle_at: ::c_long = 346; +pub const SYS_clock_adjtime: ::c_long = 347; +pub const SYS_syncfs: ::c_long = 348; +pub const SYS_sendmmsg: ::c_long = 349; +pub const SYS_setns: ::c_long = 350; +pub const SYS_process_vm_readv: ::c_long = 351; +pub const SYS_process_vm_writev: ::c_long = 352; +pub const SYS_finit_module: ::c_long = 353; +pub const SYS_kcmp: ::c_long = 354; +pub const SYS_sched_setattr: ::c_long = 355; +pub const SYS_sched_getattr: ::c_long = 356; +pub const SYS_renameat2: ::c_long = 357; +pub const SYS_seccomp: ::c_long = 358; +pub const SYS_getrandom: ::c_long = 359; +pub const SYS_memfd_create: ::c_long = 360; +pub const SYS_bpf: ::c_long = 361; +pub const SYS_execveat: ::c_long = 362; +pub const SYS_switch_endian: ::c_long = 363; +pub const SYS_userfaultfd: ::c_long = 364; +pub const SYS_membarrier: ::c_long = 365; +pub const SYS_mlock2: ::c_long = 378; +pub const SYS_copy_file_range: ::c_long = 379; +pub const SYS_preadv2: ::c_long = 380; +pub const SYS_pwritev2: ::c_long = 381; +pub const SYS_kexec_file_load: ::c_long = 382; + +#[link(name = "util")] +extern { + pub fn sysctl(name: *mut ::c_int, + namelen: ::c_int, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *mut ::c_void, + newlen: ::size_t) + -> ::c_int; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/sparc64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/sparc64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/sparc64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/sparc64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,785 @@ +//! SPARC64-specific definitions for 64-bit linux-like values + +pub type c_long = i64; +pub type c_ulong = u64; +pub type c_char = i8; +pub type wchar_t = i32; +pub type nlink_t = u32; +pub type blksize_t = i64; +pub type suseconds_t = i32; +pub type __u64 = ::c_ulonglong; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + __pad0: u64, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad1: u64, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __unused: [::c_long; 2], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + __pad0: u64, + pub st_ino: ::ino64_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + __pad2: ::c_int, + pub st_size: ::off64_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + __reserved: [::c_long; 2], + } + + pub struct statfs64 { + pub f_type: ::__fsword_t, + pub f_bsize: ::__fsword_t, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_fsid: ::fsid_t, + pub f_namelen: ::__fsword_t, + pub f_frsize: ::__fsword_t, + pub f_flags: ::__fsword_t, + pub f_spare: [::__fsword_t; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct pthread_attr_t { + __size: [u64; 7] + } + + pub struct ipc_perm { + pub __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + __pad0: u16, + pub __seq: ::c_ushort, + __unused1: ::c_ulonglong, + __unused2: ::c_ulonglong, + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_segsz: ::size_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __reserved1: ::c_ulong, + __reserved2: ::c_ulong + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 19], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } +} + +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; + +pub const TIOCGSOFTCAR: ::c_ulong = 0x40047464; +pub const TIOCSSOFTCAR: ::c_ulong = 0x80047465; + +pub const RLIMIT_NOFILE: ::c_int = 6; +pub const RLIMIT_NPROC: ::c_int = 7; + +pub const O_APPEND: ::c_int = 0x8; +pub const O_CREAT: ::c_int = 0x200; +pub const O_EXCL: ::c_int = 0x800; +pub const O_NOCTTY: ::c_int = 0x8000; +pub const O_NONBLOCK: ::c_int = 0x4000; +pub const O_SYNC: ::c_int = 0x802000; +pub const O_RSYNC: ::c_int = 0x802000; +pub const O_DSYNC: ::c_int = 0x2000; +pub const O_FSYNC: ::c_int = 0x802000; +pub const O_NOATIME: ::c_int = 0x200000; +pub const O_PATH: ::c_int = 0x1000000; +pub const O_TMPFILE: ::c_int = 0x2000000 | O_DIRECTORY; + +pub const MAP_GROWSDOWN: ::c_int = 0x0200; + +pub const EDEADLK: ::c_int = 78; +pub const ENAMETOOLONG: ::c_int = 63; +pub const ENOLCK: ::c_int = 79; +pub const ENOSYS: ::c_int = 90; +pub const ENOTEMPTY: ::c_int = 66; +pub const ELOOP: ::c_int = 62; +pub const ENOMSG: ::c_int = 75; +pub const EIDRM: ::c_int = 77; +pub const ECHRNG: ::c_int = 94; +pub const EL2NSYNC: ::c_int = 95; +pub const EL3HLT: ::c_int = 96; +pub const EL3RST: ::c_int = 97; +pub const ELNRNG: ::c_int = 98; +pub const EUNATCH: ::c_int = 99; +pub const ENOCSI: ::c_int = 100; +pub const EL2HLT: ::c_int = 101; +pub const EBADE: ::c_int = 102; +pub const EBADR: ::c_int = 103; +pub const EXFULL: ::c_int = 104; +pub const ENOANO: ::c_int = 105; +pub const EBADRQC: ::c_int = 106; +pub const EBADSLT: ::c_int = 107; +pub const EMULTIHOP: ::c_int = 87; +pub const EOVERFLOW: ::c_int = 92; +pub const ENOTUNIQ: ::c_int = 115; +pub const EBADFD: ::c_int = 93; +pub const EBADMSG: ::c_int = 76; +pub const EREMCHG: ::c_int = 89; +pub const ELIBACC: ::c_int = 114; +pub const ELIBBAD: ::c_int = 112; +pub const ELIBSCN: ::c_int = 124; +pub const ELIBMAX: ::c_int = 123; +pub const ELIBEXEC: ::c_int = 110; +pub const EILSEQ: ::c_int = 122; +pub const ERESTART: ::c_int = 116; +pub const ESTRPIPE: ::c_int = 91; +pub const EUSERS: ::c_int = 68; +pub const ENOTSOCK: ::c_int = 38; +pub const EDESTADDRREQ: ::c_int = 39; +pub const EMSGSIZE: ::c_int = 40; +pub const EPROTOTYPE: ::c_int = 41; +pub const ENOPROTOOPT: ::c_int = 42; +pub const EPROTONOSUPPORT: ::c_int = 43; +pub const ESOCKTNOSUPPORT: ::c_int = 44; +pub const EOPNOTSUPP: ::c_int = 45; +pub const EPFNOSUPPORT: ::c_int = 46; +pub const EAFNOSUPPORT: ::c_int = 47; +pub const EADDRINUSE: ::c_int = 48; +pub const EADDRNOTAVAIL: ::c_int = 49; +pub const ENETDOWN: ::c_int = 50; +pub const ENETUNREACH: ::c_int = 51; +pub const ENETRESET: ::c_int = 52; +pub const ECONNABORTED: ::c_int = 53; +pub const ECONNRESET: ::c_int = 54; +pub const ENOBUFS: ::c_int = 55; +pub const EISCONN: ::c_int = 56; +pub const ENOTCONN: ::c_int = 57; +pub const ESHUTDOWN: ::c_int = 58; +pub const ETOOMANYREFS: ::c_int = 59; +pub const ETIMEDOUT: ::c_int = 60; +pub const ECONNREFUSED: ::c_int = 61; +pub const EHOSTDOWN: ::c_int = 64; +pub const EHOSTUNREACH: ::c_int = 65; +pub const EALREADY: ::c_int = 37; +pub const EINPROGRESS: ::c_int = 36; +pub const ESTALE: ::c_int = 70; +pub const EDQUOT: ::c_int = 69; +pub const ENOMEDIUM: ::c_int = 125; +pub const EMEDIUMTYPE: ::c_int = 126; +pub const ECANCELED: ::c_int = 127; +pub const ENOKEY: ::c_int = 128; +pub const EKEYEXPIRED: ::c_int = 129; +pub const EKEYREVOKED: ::c_int = 130; +pub const EKEYREJECTED: ::c_int = 131; +pub const EOWNERDEAD: ::c_int = 132; +pub const ENOTRECOVERABLE: ::c_int = 133; +pub const EHWPOISON: ::c_int = 135; +pub const ERFKILL: ::c_int = 134; + +pub const SOL_SOCKET: ::c_int = 0xffff; + +pub const SO_REUSEADDR: ::c_int = 4; +pub const SO_BINDTODEVICE: ::c_int = 0x000d; +pub const SO_TIMESTAMP: ::c_int = 0x001d; +pub const SO_MARK: ::c_int = 0x0022; +pub const SO_RXQ_OVFL: ::c_int = 0x0024; +pub const SO_PEEK_OFF: ::c_int = 0x0026; +pub const SO_BUSY_POLL: ::c_int = 0x0030; +pub const SO_TYPE: ::c_int = 0x1008; +pub const SO_ERROR: ::c_int = 0x1007; +pub const SO_DONTROUTE: ::c_int = 16; +pub const SO_BROADCAST: ::c_int = 32; +pub const SO_SNDBUF: ::c_int = 0x1001; +pub const SO_RCVBUF: ::c_int = 0x1002; +pub const SO_DOMAIN: ::c_int = 0x1029; +pub const SO_KEEPALIVE: ::c_int = 8; +pub const SO_OOBINLINE: ::c_int = 0x100; +pub const SO_LINGER: ::c_int = 128; +pub const SO_REUSEPORT: ::c_int = 0x200; +pub const SO_ACCEPTCONN: ::c_int = 0x8000; + +pub const SA_ONSTACK: ::c_int = 1; +pub const SA_SIGINFO: ::c_int = 0x200; +pub const SA_NOCLDWAIT: ::c_int = 0x100; + +pub const SIGCHLD: ::c_int = 20; +pub const SIGBUS: ::c_int = 10; +pub const SIGUSR1: ::c_int = 30; +pub const SIGUSR2: ::c_int = 31; +pub const SIGCONT: ::c_int = 19; +pub const SIGSTOP: ::c_int = 17; +pub const SIGTSTP: ::c_int = 18; +pub const SIGURG: ::c_int = 16; +pub const SIGIO: ::c_int = 23; +pub const SIGSYS: ::c_int = 12; +pub const SIGPOLL: ::c_int = 23; +pub const SIGPWR: ::c_int = 29; +pub const SIG_SETMASK: ::c_int = 4; +pub const SIG_BLOCK: ::c_int = 1; +pub const SIG_UNBLOCK: ::c_int = 2; + +pub const POLLWRNORM: ::c_short = 4; +pub const POLLWRBAND: ::c_short = 0x100; + +pub const O_ASYNC: ::c_int = 0x40; +pub const O_NDELAY: ::c_int = 0x4004; + +pub const PTRACE_DETACH: ::c_uint = 11; + +pub const EFD_NONBLOCK: ::c_int = 0x4000; + +pub const F_GETLK: ::c_int = 7; +pub const F_GETOWN: ::c_int = 5; +pub const F_SETOWN: ::c_int = 6; +pub const F_SETLK: ::c_int = 8; +pub const F_SETLKW: ::c_int = 9; + +pub const SFD_NONBLOCK: ::c_int = 0x4000; + +pub const TIOCEXCL: ::c_ulong = 0x2000740d; +pub const TIOCNXCL: ::c_ulong = 0x2000740e; +pub const TIOCSCTTY: ::c_ulong = 0x20007484; +pub const TIOCSTI: ::c_ulong = 0x80017472; +pub const TIOCMGET: ::c_ulong = 0x4004746a; +pub const TIOCMBIS: ::c_ulong = 0x8004746c; +pub const TIOCMBIC: ::c_ulong = 0x8004746b; +pub const TIOCMSET: ::c_ulong = 0x8004746d; +pub const TIOCCONS: ::c_ulong = 0x20007424; + +pub const SFD_CLOEXEC: ::c_int = 0x400000; + +pub const NCCS: usize = 17; +pub const O_TRUNC: ::c_int = 0x400; + +pub const O_CLOEXEC: ::c_int = 0x400000; + +pub const EBFONT: ::c_int = 109; +pub const ENOSTR: ::c_int = 72; +pub const ENODATA: ::c_int = 111; +pub const ETIME: ::c_int = 73; +pub const ENOSR: ::c_int = 74; +pub const ENONET: ::c_int = 80; +pub const ENOPKG: ::c_int = 113; +pub const EREMOTE: ::c_int = 71; +pub const ENOLINK: ::c_int = 82; +pub const EADV: ::c_int = 83; +pub const ESRMNT: ::c_int = 84; +pub const ECOMM: ::c_int = 85; +pub const EPROTO: ::c_int = 86; +pub const EDOTDOT: ::c_int = 88; + +pub const SA_NODEFER: ::c_int = 0x20; +pub const SA_RESETHAND: ::c_int = 0x4; +pub const SA_RESTART: ::c_int = 0x2; +pub const SA_NOCLDSTOP: ::c_int = 0x00000008; + +pub const EPOLL_CLOEXEC: ::c_int = 0x400000; + +pub const EFD_CLOEXEC: ::c_int = 0x400000; +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; + +pub const O_DIRECTORY: ::c_int = 0o200000; +pub const O_NOFOLLOW: ::c_int = 0o400000; +pub const O_DIRECT: ::c_int = 0x100000; + +pub const MAP_LOCKED: ::c_int = 0x0100; +pub const MAP_NORESERVE: ::c_int = 0x00040; + +pub const EDEADLOCK: ::c_int = 108; + +pub const SO_PEERCRED: ::c_int = 0x40; +pub const SO_RCVLOWAT: ::c_int = 0x800; +pub const SO_SNDLOWAT: ::c_int = 0x1000; +pub const SO_RCVTIMEO: ::c_int = 0x2000; +pub const SO_SNDTIMEO: ::c_int = 0x4000; + +pub const FIOCLEX: ::c_ulong = 0x20006601; +pub const FIONBIO: ::c_ulong = 0x8004667e; + +pub const MCL_CURRENT: ::c_int = 0x2000; +pub const MCL_FUTURE: ::c_int = 0x4000; + +pub const SIGSTKSZ: ::size_t = 16384; +pub const MINSIGSTKSZ: ::size_t = 4096; +pub const CBAUD: ::tcflag_t = 0x0000100f; +pub const TAB1: ::c_int = 0x800; +pub const TAB2: ::c_int = 0x1000; +pub const TAB3: ::c_int = 0x1800; +pub const CR1: ::c_int = 0x200; +pub const CR2: ::c_int = 0x400; +pub const CR3: ::c_int = 0x600; +pub const FF1: ::c_int = 0x8000; +pub const BS1: ::c_int = 0x2000; +pub const VT1: ::c_int = 0x4000; +pub const VWERASE: usize = 0xe; +pub const VREPRINT: usize = 0xc; +pub const VSUSP: usize = 0xa; +pub const VSTART: usize = 0x8; +pub const VSTOP: usize = 0x9; +pub const VDISCARD: usize = 0xd; +pub const VTIME: usize = 0x5; +pub const IXON: ::tcflag_t = 0x400; +pub const IXOFF: ::tcflag_t = 0x1000; +pub const ONLCR: ::tcflag_t = 0x4; +pub const CSIZE: ::tcflag_t = 0x30; +pub const CS6: ::tcflag_t = 0x10; +pub const CS7: ::tcflag_t = 0x20; +pub const CS8: ::tcflag_t = 0x30; +pub const CSTOPB: ::tcflag_t = 0x40; +pub const CREAD: ::tcflag_t = 0x80; +pub const PARENB: ::tcflag_t = 0x100; +pub const PARODD: ::tcflag_t = 0x200; +pub const HUPCL: ::tcflag_t = 0x400; +pub const CLOCAL: ::tcflag_t = 0x800; +pub const ECHOKE: ::tcflag_t = 0x800; +pub const ECHOE: ::tcflag_t = 0x10; +pub const ECHOK: ::tcflag_t = 0x20; +pub const ECHONL: ::tcflag_t = 0x40; +pub const ECHOPRT: ::tcflag_t = 0x400; +pub const ECHOCTL: ::tcflag_t = 0x200; +pub const ISIG: ::tcflag_t = 0x1; +pub const ICANON: ::tcflag_t = 0x2; +pub const PENDIN: ::tcflag_t = 0x4000; +pub const NOFLSH: ::tcflag_t = 0x80; +pub const CIBAUD: ::tcflag_t = 0o02003600000; +pub const CBAUDEX: ::tcflag_t = 0x00001000; +pub const VSWTC: usize = 7; +pub const OLCUC: ::tcflag_t = 0o000002; +pub const NLDLY: ::tcflag_t = 0o000400; +pub const CRDLY: ::tcflag_t = 0o003000; +pub const TABDLY: ::tcflag_t = 0o014000; +pub const BSDLY: ::tcflag_t = 0o020000; +pub const FFDLY: ::tcflag_t = 0o100000; +pub const VTDLY: ::tcflag_t = 0o040000; +pub const XTABS: ::tcflag_t = 0o014000; + +pub const VEOL: usize = 5; +pub const VEOL2: usize = 6; +pub const VMIN: usize = 4; +pub const IEXTEN: ::tcflag_t = 0x8000; +pub const TOSTOP: ::tcflag_t = 0x100; +pub const FLUSHO: ::tcflag_t = 0x2000; +pub const EXTPROC: ::tcflag_t = 0x10000; +pub const TCGETS: ::c_ulong = 0x40245408; +pub const TCSETS: ::c_ulong = 0x80245409; +pub const TCSETSW: ::c_ulong = 0x8024540a; +pub const TCSETSF: ::c_ulong = 0x8024540b; +pub const TCGETA: ::c_ulong = 0x40125401; +pub const TCSETA: ::c_ulong = 0x80125402; +pub const TCSETAW: ::c_ulong = 0x80125403; +pub const TCSETAF: ::c_ulong = 0x80125404; +pub const TCSBRK: ::c_ulong = 0x20005405; +pub const TCXONC: ::c_ulong = 0x20005406; +pub const TCFLSH: ::c_ulong = 0x20005407; +pub const TIOCINQ: ::c_ulong = 0x4004667f; +pub const TIOCGPGRP: ::c_ulong = 0x40047483; +pub const TIOCSPGRP: ::c_ulong = 0x80047482; +pub const TIOCOUTQ: ::c_ulong = 0x40047473; +pub const TIOCGWINSZ: ::c_ulong = 0x40087468; +pub const TIOCSWINSZ: ::c_ulong = 0x80087467; +pub const FIONREAD: ::c_ulong = 0x4004667f; + +pub const SYS_restart_syscall: ::c_long = 0; +pub const SYS_exit: ::c_long = 1; +pub const SYS_fork: ::c_long = 2; +pub const SYS_read: ::c_long = 3; +pub const SYS_write: ::c_long = 4; +pub const SYS_open: ::c_long = 5; +pub const SYS_close: ::c_long = 6; +pub const SYS_wait4: ::c_long = 7; +pub const SYS_creat: ::c_long = 8; +pub const SYS_link: ::c_long = 9; +pub const SYS_unlink: ::c_long = 10; +pub const SYS_execv: ::c_long = 11; +pub const SYS_chdir: ::c_long = 12; +pub const SYS_chown: ::c_long = 13; +pub const SYS_mknod: ::c_long = 14; +pub const SYS_chmod: ::c_long = 15; +pub const SYS_lchown: ::c_long = 16; +pub const SYS_brk: ::c_long = 17; +pub const SYS_perfctr: ::c_long = 18; +pub const SYS_lseek: ::c_long = 19; +pub const SYS_getpid: ::c_long = 20; +pub const SYS_capget: ::c_long = 21; +pub const SYS_capset: ::c_long = 22; +pub const SYS_setuid: ::c_long = 23; +pub const SYS_getuid: ::c_long = 24; +pub const SYS_vmsplice: ::c_long = 25; +pub const SYS_ptrace: ::c_long = 26; +pub const SYS_alarm: ::c_long = 27; +pub const SYS_sigaltstack: ::c_long = 28; +pub const SYS_pause: ::c_long = 29; +pub const SYS_utime: ::c_long = 30; +pub const SYS_access: ::c_long = 33; +pub const SYS_nice: ::c_long = 34; +pub const SYS_sync: ::c_long = 36; +pub const SYS_kill: ::c_long = 37; +pub const SYS_stat: ::c_long = 38; +pub const SYS_sendfile: ::c_long = 39; +pub const SYS_lstat: ::c_long = 40; +pub const SYS_dup: ::c_long = 41; +pub const SYS_pipe: ::c_long = 42; +pub const SYS_times: ::c_long = 43; +pub const SYS_umount2: ::c_long = 45; +pub const SYS_setgid: ::c_long = 46; +pub const SYS_getgid: ::c_long = 47; +pub const SYS_signal: ::c_long = 48; +pub const SYS_geteuid: ::c_long = 49; +pub const SYS_getegid: ::c_long = 50; +pub const SYS_acct: ::c_long = 51; +pub const SYS_memory_ordering: ::c_long = 52; +pub const SYS_ioctl: ::c_long = 54; +pub const SYS_reboot: ::c_long = 55; +pub const SYS_symlink: ::c_long = 57; +pub const SYS_readlink: ::c_long = 58; +pub const SYS_execve: ::c_long = 59; +pub const SYS_umask: ::c_long = 60; +pub const SYS_chroot: ::c_long = 61; +pub const SYS_fstat: ::c_long = 62; +pub const SYS_fstat64: ::c_long = 63; +pub const SYS_getpagesize: ::c_long = 64; +pub const SYS_msync: ::c_long = 65; +pub const SYS_vfork: ::c_long = 66; +pub const SYS_pread64: ::c_long = 67; +pub const SYS_pwrite64: ::c_long = 68; +pub const SYS_mmap: ::c_long = 71; +pub const SYS_munmap: ::c_long = 73; +pub const SYS_mprotect: ::c_long = 74; +pub const SYS_madvise: ::c_long = 75; +pub const SYS_vhangup: ::c_long = 76; +pub const SYS_mincore: ::c_long = 78; +pub const SYS_getgroups: ::c_long = 79; +pub const SYS_setgroups: ::c_long = 80; +pub const SYS_getpgrp: ::c_long = 81; +pub const SYS_setitimer: ::c_long = 83; +pub const SYS_swapon: ::c_long = 85; +pub const SYS_getitimer: ::c_long = 86; +pub const SYS_sethostname: ::c_long = 88; +pub const SYS_dup2: ::c_long = 90; +pub const SYS_fcntl: ::c_long = 92; +pub const SYS_select: ::c_long = 93; +pub const SYS_fsync: ::c_long = 95; +pub const SYS_setpriority: ::c_long = 96; +pub const SYS_socket: ::c_long = 97; +pub const SYS_connect: ::c_long = 98; +pub const SYS_accept: ::c_long = 99; +pub const SYS_getpriority: ::c_long = 100; +pub const SYS_rt_sigreturn: ::c_long = 101; +pub const SYS_rt_sigaction: ::c_long = 102; +pub const SYS_rt_sigprocmask: ::c_long = 103; +pub const SYS_rt_sigpending: ::c_long = 104; +pub const SYS_rt_sigtimedwait: ::c_long = 105; +pub const SYS_rt_sigqueueinfo: ::c_long = 106; +pub const SYS_rt_sigsuspend: ::c_long = 107; +pub const SYS_setresuid: ::c_long = 108; +pub const SYS_getresuid: ::c_long = 109; +pub const SYS_setresgid: ::c_long = 110; +pub const SYS_getresgid: ::c_long = 111; +pub const SYS_recvmsg: ::c_long = 113; +pub const SYS_sendmsg: ::c_long = 114; +pub const SYS_gettimeofday: ::c_long = 116; +pub const SYS_getrusage: ::c_long = 117; +pub const SYS_getsockopt: ::c_long = 118; +pub const SYS_getcwd: ::c_long = 119; +pub const SYS_readv: ::c_long = 120; +pub const SYS_writev: ::c_long = 121; +pub const SYS_settimeofday: ::c_long = 122; +pub const SYS_fchown: ::c_long = 123; +pub const SYS_fchmod: ::c_long = 124; +pub const SYS_recvfrom: ::c_long = 125; +pub const SYS_setreuid: ::c_long = 126; +pub const SYS_setregid: ::c_long = 127; +pub const SYS_rename: ::c_long = 128; +pub const SYS_truncate: ::c_long = 129; +pub const SYS_ftruncate: ::c_long = 130; +pub const SYS_flock: ::c_long = 131; +pub const SYS_lstat64: ::c_long = 132; +pub const SYS_sendto: ::c_long = 133; +pub const SYS_shutdown: ::c_long = 134; +pub const SYS_socketpair: ::c_long = 135; +pub const SYS_mkdir: ::c_long = 136; +pub const SYS_rmdir: ::c_long = 137; +pub const SYS_utimes: ::c_long = 138; +pub const SYS_stat64: ::c_long = 139; +pub const SYS_sendfile64: ::c_long = 140; +pub const SYS_getpeername: ::c_long = 141; +pub const SYS_futex: ::c_long = 142; +pub const SYS_gettid: ::c_long = 143; +pub const SYS_getrlimit: ::c_long = 144; +pub const SYS_setrlimit: ::c_long = 145; +pub const SYS_pivot_root: ::c_long = 146; +pub const SYS_prctl: ::c_long = 147; +pub const SYS_pciconfig_read: ::c_long = 148; +pub const SYS_pciconfig_write: ::c_long = 149; +pub const SYS_getsockname: ::c_long = 150; +pub const SYS_inotify_init: ::c_long = 151; +pub const SYS_inotify_add_watch: ::c_long = 152; +pub const SYS_poll: ::c_long = 153; +pub const SYS_getdents64: ::c_long = 154; +pub const SYS_inotify_rm_watch: ::c_long = 156; +pub const SYS_statfs: ::c_long = 157; +pub const SYS_fstatfs: ::c_long = 158; +pub const SYS_umount: ::c_long = 159; +pub const SYS_sched_set_affinity: ::c_long = 160; +pub const SYS_sched_get_affinity: ::c_long = 161; +pub const SYS_getdomainname: ::c_long = 162; +pub const SYS_setdomainname: ::c_long = 163; +pub const SYS_utrap_install: ::c_long = 164; +pub const SYS_quotactl: ::c_long = 165; +pub const SYS_set_tid_address: ::c_long = 166; +pub const SYS_mount: ::c_long = 167; +pub const SYS_ustat: ::c_long = 168; +pub const SYS_setxattr: ::c_long = 169; +pub const SYS_lsetxattr: ::c_long = 170; +pub const SYS_fsetxattr: ::c_long = 171; +pub const SYS_getxattr: ::c_long = 172; +pub const SYS_lgetxattr: ::c_long = 173; +pub const SYS_getdents: ::c_long = 174; +pub const SYS_setsid: ::c_long = 175; +pub const SYS_fchdir: ::c_long = 176; +pub const SYS_fgetxattr: ::c_long = 177; +pub const SYS_listxattr: ::c_long = 178; +pub const SYS_llistxattr: ::c_long = 179; +pub const SYS_flistxattr: ::c_long = 180; +pub const SYS_removexattr: ::c_long = 181; +pub const SYS_lremovexattr: ::c_long = 182; +pub const SYS_sigpending: ::c_long = 183; +pub const SYS_query_module: ::c_long = 184; +pub const SYS_setpgid: ::c_long = 185; +pub const SYS_fremovexattr: ::c_long = 186; +pub const SYS_tkill: ::c_long = 187; +pub const SYS_exit_group: ::c_long = 188; +pub const SYS_uname: ::c_long = 189; +pub const SYS_init_module: ::c_long = 190; +pub const SYS_personality: ::c_long = 191; +pub const SYS_remap_file_pages: ::c_long = 192; +pub const SYS_epoll_create: ::c_long = 193; +pub const SYS_epoll_ctl: ::c_long = 194; +pub const SYS_epoll_wait: ::c_long = 195; +pub const SYS_ioprio_set: ::c_long = 196; +pub const SYS_getppid: ::c_long = 197; +pub const SYS_sigaction: ::c_long = 198; +pub const SYS_sgetmask: ::c_long = 199; +pub const SYS_ssetmask: ::c_long = 200; +pub const SYS_sigsuspend: ::c_long = 201; +pub const SYS_oldlstat: ::c_long = 202; +pub const SYS_uselib: ::c_long = 203; +pub const SYS_readdir: ::c_long = 204; +pub const SYS_readahead: ::c_long = 205; +pub const SYS_socketcall: ::c_long = 206; +pub const SYS_syslog: ::c_long = 207; +pub const SYS_lookup_dcookie: ::c_long = 208; +pub const SYS_fadvise64: ::c_long = 209; +pub const SYS_fadvise64_64: ::c_long = 210; +pub const SYS_tgkill: ::c_long = 211; +pub const SYS_waitpid: ::c_long = 212; +pub const SYS_swapoff: ::c_long = 213; +pub const SYS_sysinfo: ::c_long = 214; +pub const SYS_ipc: ::c_long = 215; +pub const SYS_sigreturn: ::c_long = 216; +pub const SYS_clone: ::c_long = 217; +pub const SYS_ioprio_get: ::c_long = 218; +pub const SYS_adjtimex: ::c_long = 219; +pub const SYS_sigprocmask: ::c_long = 220; +pub const SYS_create_module: ::c_long = 221; +pub const SYS_delete_module: ::c_long = 222; +pub const SYS_get_kernel_syms: ::c_long = 223; +pub const SYS_getpgid: ::c_long = 224; +pub const SYS_bdflush: ::c_long = 225; +pub const SYS_sysfs: ::c_long = 226; +pub const SYS_afs_syscall: ::c_long = 227; +pub const SYS_setfsuid: ::c_long = 228; +pub const SYS_setfsgid: ::c_long = 229; +pub const SYS__newselect: ::c_long = 230; +pub const SYS_splice: ::c_long = 232; +pub const SYS_stime: ::c_long = 233; +pub const SYS_statfs64: ::c_long = 234; +pub const SYS_fstatfs64: ::c_long = 235; +pub const SYS__llseek: ::c_long = 236; +pub const SYS_mlock: ::c_long = 237; +pub const SYS_munlock: ::c_long = 238; +pub const SYS_mlockall: ::c_long = 239; +pub const SYS_munlockall: ::c_long = 240; +pub const SYS_sched_setparam: ::c_long = 241; +pub const SYS_sched_getparam: ::c_long = 242; +pub const SYS_sched_setscheduler: ::c_long =243; +pub const SYS_sched_getscheduler: ::c_long =244; +pub const SYS_sched_yield: ::c_long = 245; +pub const SYS_sched_get_priority_max: ::c_long =246; +pub const SYS_sched_get_priority_min: ::c_long =247; +pub const SYS_sched_rr_get_interval: ::c_long = 248; +pub const SYS_nanosleep: ::c_long = 249; +pub const SYS_mremap: ::c_long = 250; +pub const SYS__sysctl: ::c_long = 251; +pub const SYS_getsid: ::c_long = 252; +pub const SYS_fdatasync: ::c_long = 253; +pub const SYS_nfsservctl: ::c_long = 254; +pub const SYS_sync_file_range: ::c_long = 255; +pub const SYS_clock_settime: ::c_long = 256; +pub const SYS_clock_gettime: ::c_long = 257; +pub const SYS_clock_getres: ::c_long = 258; +pub const SYS_clock_nanosleep: ::c_long = 259; +pub const SYS_sched_getaffinity: ::c_long = 260; +pub const SYS_sched_setaffinity: ::c_long = 261; +pub const SYS_timer_settime: ::c_long = 262; +pub const SYS_timer_gettime: ::c_long = 263; +pub const SYS_timer_getoverrun: ::c_long = 264; +pub const SYS_timer_delete: ::c_long = 265; +pub const SYS_timer_create: ::c_long = 266; +pub const SYS_io_setup: ::c_long = 268; +pub const SYS_io_destroy: ::c_long = 269; +pub const SYS_io_submit: ::c_long = 270; +pub const SYS_io_cancel: ::c_long = 271; +pub const SYS_io_getevents: ::c_long = 272; +pub const SYS_mq_open: ::c_long = 273; +pub const SYS_mq_unlink: ::c_long = 274; +pub const SYS_mq_timedsend: ::c_long = 275; +pub const SYS_mq_timedreceive: ::c_long = 276; +pub const SYS_mq_notify: ::c_long = 277; +pub const SYS_mq_getsetattr: ::c_long = 278; +pub const SYS_waitid: ::c_long = 279; +pub const SYS_tee: ::c_long = 280; +pub const SYS_add_key: ::c_long = 281; +pub const SYS_request_key: ::c_long = 282; +pub const SYS_keyctl: ::c_long = 283; +pub const SYS_openat: ::c_long = 284; +pub const SYS_mkdirat: ::c_long = 285; +pub const SYS_mknodat: ::c_long = 286; +pub const SYS_fchownat: ::c_long = 287; +pub const SYS_futimesat: ::c_long = 288; +pub const SYS_fstatat64: ::c_long = 289; +pub const SYS_unlinkat: ::c_long = 290; +pub const SYS_renameat: ::c_long = 291; +pub const SYS_linkat: ::c_long = 292; +pub const SYS_symlinkat: ::c_long = 293; +pub const SYS_readlinkat: ::c_long = 294; +pub const SYS_fchmodat: ::c_long = 295; +pub const SYS_faccessat: ::c_long = 296; +pub const SYS_pselect6: ::c_long = 297; +pub const SYS_ppoll: ::c_long = 298; +pub const SYS_unshare: ::c_long = 299; +pub const SYS_set_robust_list: ::c_long = 300; +pub const SYS_get_robust_list: ::c_long = 301; +pub const SYS_migrate_pages: ::c_long =302; +pub const SYS_mbind: ::c_long = 303; +pub const SYS_get_mempolicy: ::c_long = 304; +pub const SYS_set_mempolicy: ::c_long = 305; +pub const SYS_kexec_load: ::c_long = 306; +pub const SYS_move_pages: ::c_long = 307; +pub const SYS_getcpu: ::c_long = 308; +pub const SYS_epoll_pwait: ::c_long = 309; +pub const SYS_utimensat: ::c_long = 310; +pub const SYS_signalfd: ::c_long = 311; +pub const SYS_timerfd_create: ::c_long = 312; +pub const SYS_eventfd: ::c_long = 313; +pub const SYS_fallocate: ::c_long = 314; +pub const SYS_timerfd_settime: ::c_long = 315; +pub const SYS_timerfd_gettime: ::c_long = 316; +pub const SYS_signalfd4: ::c_long = 317; +pub const SYS_eventfd2: ::c_long = 318; +pub const SYS_epoll_create1: ::c_long = 319; +pub const SYS_dup3: ::c_long = 320; +pub const SYS_pipe2: ::c_long = 321; +pub const SYS_inotify_init1: ::c_long = 322; +pub const SYS_accept4: ::c_long = 323; +pub const SYS_preadv: ::c_long = 324; +pub const SYS_pwritev: ::c_long = 325; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 326; +pub const SYS_perf_event_open: ::c_long = 327; +pub const SYS_recvmmsg: ::c_long = 328; +pub const SYS_fanotify_init: ::c_long = 329; +pub const SYS_fanotify_mark: ::c_long = 330; +pub const SYS_prlimit64: ::c_long = 331; +pub const SYS_name_to_handle_at: ::c_long = 332; +pub const SYS_open_by_handle_at: ::c_long = 333; +pub const SYS_clock_adjtime: ::c_long = 334; +pub const SYS_syncfs: ::c_long = 335; +pub const SYS_sendmmsg: ::c_long = 336; +pub const SYS_setns: ::c_long = 337; +pub const SYS_process_vm_readv: ::c_long = 338; +pub const SYS_process_vm_writev: ::c_long = 339; +pub const SYS_kern_features: ::c_long = 340; +pub const SYS_kcmp: ::c_long = 341; +pub const SYS_finit_module: ::c_long = 342; +pub const SYS_sched_setattr: ::c_long = 343; +pub const SYS_sched_getattr: ::c_long = 344; +pub const SYS_renameat2: ::c_long = 345; +pub const SYS_seccomp: ::c_long = 346; +pub const SYS_getrandom: ::c_long = 347; +pub const SYS_memfd_create: ::c_long = 348; +pub const SYS_bpf: ::c_long = 349; +pub const SYS_execveat: ::c_long = 350; +pub const SYS_membarrier: ::c_long = 351; +pub const SYS_userfaultfd: ::c_long = 352; +pub const SYS_bind: ::c_long = 353; +pub const SYS_listen: ::c_long = 354; +pub const SYS_setsockopt: ::c_long = 355; +pub const SYS_mlock2: ::c_long = 356; +pub const SYS_copy_file_range: ::c_long = 357; +pub const SYS_preadv2: ::c_long = 358; +pub const SYS_pwritev2: ::c_long = 359; + +#[link(name = "util")] +extern { + pub fn sysctl(name: *mut ::c_int, + namelen: ::c_int, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *mut ::c_void, + newlen: ::size_t) + -> ::c_int; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/x32.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/x32.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/x32.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/x32.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,331 @@ +pub type c_long = i32; +pub type c_ulong = u32; + +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 32; +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 44; + +// Syscall table + +pub const __X32_SYSCALL_BIT: ::c_long = 0x40000000; + +pub const SYS_read: ::c_long = __X32_SYSCALL_BIT + 0; +pub const SYS_write: ::c_long = __X32_SYSCALL_BIT + 1; +pub const SYS_open: ::c_long = __X32_SYSCALL_BIT + 2; +pub const SYS_close: ::c_long = __X32_SYSCALL_BIT + 3; +pub const SYS_stat: ::c_long = __X32_SYSCALL_BIT + 4; +pub const SYS_fstat: ::c_long = __X32_SYSCALL_BIT + 5; +pub const SYS_lstat: ::c_long = __X32_SYSCALL_BIT + 6; +pub const SYS_poll: ::c_long = __X32_SYSCALL_BIT + 7; +pub const SYS_lseek: ::c_long = __X32_SYSCALL_BIT + 8; +pub const SYS_mmap: ::c_long = __X32_SYSCALL_BIT + 9; +pub const SYS_mprotect: ::c_long = __X32_SYSCALL_BIT + 10; +pub const SYS_munmap: ::c_long = __X32_SYSCALL_BIT + 11; +pub const SYS_brk: ::c_long = __X32_SYSCALL_BIT + 12; +pub const SYS_rt_sigprocmask: ::c_long = __X32_SYSCALL_BIT + 14; +pub const SYS_pread64: ::c_long = __X32_SYSCALL_BIT + 17; +pub const SYS_pwrite64: ::c_long = __X32_SYSCALL_BIT + 18; +pub const SYS_access: ::c_long = __X32_SYSCALL_BIT + 21; +pub const SYS_pipe: ::c_long = __X32_SYSCALL_BIT + 22; +pub const SYS_select: ::c_long = __X32_SYSCALL_BIT + 23; +pub const SYS_sched_yield: ::c_long = __X32_SYSCALL_BIT + 24; +pub const SYS_mremap: ::c_long = __X32_SYSCALL_BIT + 25; +pub const SYS_msync: ::c_long = __X32_SYSCALL_BIT + 26; +pub const SYS_mincore: ::c_long = __X32_SYSCALL_BIT + 27; +pub const SYS_madvise: ::c_long = __X32_SYSCALL_BIT + 28; +pub const SYS_shmget: ::c_long = __X32_SYSCALL_BIT + 29; +pub const SYS_shmat: ::c_long = __X32_SYSCALL_BIT + 30; +pub const SYS_shmctl: ::c_long = __X32_SYSCALL_BIT + 31; +pub const SYS_dup: ::c_long = __X32_SYSCALL_BIT + 32; +pub const SYS_dup2: ::c_long = __X32_SYSCALL_BIT + 33; +pub const SYS_pause: ::c_long = __X32_SYSCALL_BIT + 34; +pub const SYS_nanosleep: ::c_long = __X32_SYSCALL_BIT + 35; +pub const SYS_getitimer: ::c_long = __X32_SYSCALL_BIT + 36; +pub const SYS_alarm: ::c_long = __X32_SYSCALL_BIT + 37; +pub const SYS_setitimer: ::c_long = __X32_SYSCALL_BIT + 38; +pub const SYS_getpid: ::c_long = __X32_SYSCALL_BIT + 39; +pub const SYS_sendfile: ::c_long = __X32_SYSCALL_BIT + 40; +pub const SYS_socket: ::c_long = __X32_SYSCALL_BIT + 41; +pub const SYS_connect: ::c_long = __X32_SYSCALL_BIT + 42; +pub const SYS_accept: ::c_long = __X32_SYSCALL_BIT + 43; +pub const SYS_sendto: ::c_long = __X32_SYSCALL_BIT + 44; +pub const SYS_shutdown: ::c_long = __X32_SYSCALL_BIT + 48; +pub const SYS_bind: ::c_long = __X32_SYSCALL_BIT + 49; +pub const SYS_listen: ::c_long = __X32_SYSCALL_BIT + 50; +pub const SYS_getsockname: ::c_long = __X32_SYSCALL_BIT + 51; +pub const SYS_getpeername: ::c_long = __X32_SYSCALL_BIT + 52; +pub const SYS_socketpair: ::c_long = __X32_SYSCALL_BIT + 53; +pub const SYS_clone: ::c_long = __X32_SYSCALL_BIT + 56; +pub const SYS_fork: ::c_long = __X32_SYSCALL_BIT + 57; +pub const SYS_vfork: ::c_long = __X32_SYSCALL_BIT + 58; +pub const SYS_exit: ::c_long = __X32_SYSCALL_BIT + 60; +pub const SYS_wait4: ::c_long = __X32_SYSCALL_BIT + 61; +pub const SYS_kill: ::c_long = __X32_SYSCALL_BIT + 62; +pub const SYS_uname: ::c_long = __X32_SYSCALL_BIT + 63; +pub const SYS_semget: ::c_long = __X32_SYSCALL_BIT + 64; +pub const SYS_semop: ::c_long = __X32_SYSCALL_BIT + 65; +pub const SYS_semctl: ::c_long = __X32_SYSCALL_BIT + 66; +pub const SYS_shmdt: ::c_long = __X32_SYSCALL_BIT + 67; +pub const SYS_msgget: ::c_long = __X32_SYSCALL_BIT + 68; +pub const SYS_msgsnd: ::c_long = __X32_SYSCALL_BIT + 69; +pub const SYS_msgrcv: ::c_long = __X32_SYSCALL_BIT + 70; +pub const SYS_msgctl: ::c_long = __X32_SYSCALL_BIT + 71; +pub const SYS_fcntl: ::c_long = __X32_SYSCALL_BIT + 72; +pub const SYS_flock: ::c_long = __X32_SYSCALL_BIT + 73; +pub const SYS_fsync: ::c_long = __X32_SYSCALL_BIT + 74; +pub const SYS_fdatasync: ::c_long = __X32_SYSCALL_BIT + 75; +pub const SYS_truncate: ::c_long = __X32_SYSCALL_BIT + 76; +pub const SYS_ftruncate: ::c_long = __X32_SYSCALL_BIT + 77; +pub const SYS_getdents: ::c_long = __X32_SYSCALL_BIT + 78; +pub const SYS_getcwd: ::c_long = __X32_SYSCALL_BIT + 79; +pub const SYS_chdir: ::c_long = __X32_SYSCALL_BIT + 80; +pub const SYS_fchdir: ::c_long = __X32_SYSCALL_BIT + 81; +pub const SYS_rename: ::c_long = __X32_SYSCALL_BIT + 82; +pub const SYS_mkdir: ::c_long = __X32_SYSCALL_BIT + 83; +pub const SYS_rmdir: ::c_long = __X32_SYSCALL_BIT + 84; +pub const SYS_creat: ::c_long = __X32_SYSCALL_BIT + 85; +pub const SYS_link: ::c_long = __X32_SYSCALL_BIT + 86; +pub const SYS_unlink: ::c_long = __X32_SYSCALL_BIT + 87; +pub const SYS_symlink: ::c_long = __X32_SYSCALL_BIT + 88; +pub const SYS_readlink: ::c_long = __X32_SYSCALL_BIT + 89; +pub const SYS_chmod: ::c_long = __X32_SYSCALL_BIT + 90; +pub const SYS_fchmod: ::c_long = __X32_SYSCALL_BIT + 91; +pub const SYS_chown: ::c_long = __X32_SYSCALL_BIT + 92; +pub const SYS_fchown: ::c_long = __X32_SYSCALL_BIT + 93; +pub const SYS_lchown: ::c_long = __X32_SYSCALL_BIT + 94; +pub const SYS_umask: ::c_long = __X32_SYSCALL_BIT + 95; +pub const SYS_gettimeofday: ::c_long = __X32_SYSCALL_BIT + 96; +pub const SYS_getrlimit: ::c_long = __X32_SYSCALL_BIT + 97; +pub const SYS_getrusage: ::c_long = __X32_SYSCALL_BIT + 98; +pub const SYS_sysinfo: ::c_long = __X32_SYSCALL_BIT + 99; +pub const SYS_times: ::c_long = __X32_SYSCALL_BIT + 100; +pub const SYS_getuid: ::c_long = __X32_SYSCALL_BIT + 102; +pub const SYS_syslog: ::c_long = __X32_SYSCALL_BIT + 103; +pub const SYS_getgid: ::c_long = __X32_SYSCALL_BIT + 104; +pub const SYS_setuid: ::c_long = __X32_SYSCALL_BIT + 105; +pub const SYS_setgid: ::c_long = __X32_SYSCALL_BIT + 106; +pub const SYS_geteuid: ::c_long = __X32_SYSCALL_BIT + 107; +pub const SYS_getegid: ::c_long = __X32_SYSCALL_BIT + 108; +pub const SYS_setpgid: ::c_long = __X32_SYSCALL_BIT + 109; +pub const SYS_getppid: ::c_long = __X32_SYSCALL_BIT + 110; +pub const SYS_getpgrp: ::c_long = __X32_SYSCALL_BIT + 111; +pub const SYS_setsid: ::c_long = __X32_SYSCALL_BIT + 112; +pub const SYS_setreuid: ::c_long = __X32_SYSCALL_BIT + 113; +pub const SYS_setregid: ::c_long = __X32_SYSCALL_BIT + 114; +pub const SYS_getgroups: ::c_long = __X32_SYSCALL_BIT + 115; +pub const SYS_setgroups: ::c_long = __X32_SYSCALL_BIT + 116; +pub const SYS_setresuid: ::c_long = __X32_SYSCALL_BIT + 117; +pub const SYS_getresuid: ::c_long = __X32_SYSCALL_BIT + 118; +pub const SYS_setresgid: ::c_long = __X32_SYSCALL_BIT + 119; +pub const SYS_getresgid: ::c_long = __X32_SYSCALL_BIT + 120; +pub const SYS_getpgid: ::c_long = __X32_SYSCALL_BIT + 121; +pub const SYS_setfsuid: ::c_long = __X32_SYSCALL_BIT + 122; +pub const SYS_setfsgid: ::c_long = __X32_SYSCALL_BIT + 123; +pub const SYS_getsid: ::c_long = __X32_SYSCALL_BIT + 124; +pub const SYS_capget: ::c_long = __X32_SYSCALL_BIT + 125; +pub const SYS_capset: ::c_long = __X32_SYSCALL_BIT + 126; +pub const SYS_rt_sigsuspend: ::c_long = __X32_SYSCALL_BIT + 130; +pub const SYS_utime: ::c_long = __X32_SYSCALL_BIT + 132; +pub const SYS_mknod: ::c_long = __X32_SYSCALL_BIT + 133; +pub const SYS_personality: ::c_long = __X32_SYSCALL_BIT + 135; +pub const SYS_ustat: ::c_long = __X32_SYSCALL_BIT + 136; +pub const SYS_statfs: ::c_long = __X32_SYSCALL_BIT + 137; +pub const SYS_fstatfs: ::c_long = __X32_SYSCALL_BIT + 138; +pub const SYS_sysfs: ::c_long = __X32_SYSCALL_BIT + 139; +pub const SYS_getpriority: ::c_long = __X32_SYSCALL_BIT + 140; +pub const SYS_setpriority: ::c_long = __X32_SYSCALL_BIT + 141; +pub const SYS_sched_setparam: ::c_long = __X32_SYSCALL_BIT + 142; +pub const SYS_sched_getparam: ::c_long = __X32_SYSCALL_BIT + 143; +pub const SYS_sched_setscheduler: ::c_long = __X32_SYSCALL_BIT + 144; +pub const SYS_sched_getscheduler: ::c_long = __X32_SYSCALL_BIT + 145; +pub const SYS_sched_get_priority_max: ::c_long = __X32_SYSCALL_BIT + 146; +pub const SYS_sched_get_priority_min: ::c_long = __X32_SYSCALL_BIT + 147; +pub const SYS_sched_rr_get_interval: ::c_long = __X32_SYSCALL_BIT + 148; +pub const SYS_mlock: ::c_long = __X32_SYSCALL_BIT + 149; +pub const SYS_munlock: ::c_long = __X32_SYSCALL_BIT + 150; +pub const SYS_mlockall: ::c_long = __X32_SYSCALL_BIT + 151; +pub const SYS_munlockall: ::c_long = __X32_SYSCALL_BIT + 152; +pub const SYS_vhangup: ::c_long = __X32_SYSCALL_BIT + 153; +pub const SYS_modify_ldt: ::c_long = __X32_SYSCALL_BIT + 154; +pub const SYS_pivot_root: ::c_long = __X32_SYSCALL_BIT + 155; +pub const SYS_prctl: ::c_long = __X32_SYSCALL_BIT + 157; +pub const SYS_arch_prctl: ::c_long = __X32_SYSCALL_BIT + 158; +pub const SYS_adjtimex: ::c_long = __X32_SYSCALL_BIT + 159; +pub const SYS_setrlimit: ::c_long = __X32_SYSCALL_BIT + 160; +pub const SYS_chroot: ::c_long = __X32_SYSCALL_BIT + 161; +pub const SYS_sync: ::c_long = __X32_SYSCALL_BIT + 162; +pub const SYS_acct: ::c_long = __X32_SYSCALL_BIT + 163; +pub const SYS_settimeofday: ::c_long = __X32_SYSCALL_BIT + 164; +pub const SYS_mount: ::c_long = __X32_SYSCALL_BIT + 165; +pub const SYS_umount2: ::c_long = __X32_SYSCALL_BIT + 166; +pub const SYS_swapon: ::c_long = __X32_SYSCALL_BIT + 167; +pub const SYS_swapoff: ::c_long = __X32_SYSCALL_BIT + 168; +pub const SYS_reboot: ::c_long = __X32_SYSCALL_BIT + 169; +pub const SYS_sethostname: ::c_long = __X32_SYSCALL_BIT + 170; +pub const SYS_setdomainname: ::c_long = __X32_SYSCALL_BIT + 171; +pub const SYS_iopl: ::c_long = __X32_SYSCALL_BIT + 172; +pub const SYS_ioperm: ::c_long = __X32_SYSCALL_BIT + 173; +pub const SYS_init_module: ::c_long = __X32_SYSCALL_BIT + 175; +pub const SYS_delete_module: ::c_long = __X32_SYSCALL_BIT + 176; +pub const SYS_quotactl: ::c_long = __X32_SYSCALL_BIT + 179; +pub const SYS_getpmsg: ::c_long = __X32_SYSCALL_BIT + 181; +pub const SYS_putpmsg: ::c_long = __X32_SYSCALL_BIT + 182; +pub const SYS_afs_syscall: ::c_long = __X32_SYSCALL_BIT + 183; +pub const SYS_tuxcall: ::c_long = __X32_SYSCALL_BIT + 184; +pub const SYS_security: ::c_long = __X32_SYSCALL_BIT + 185; +pub const SYS_gettid: ::c_long = __X32_SYSCALL_BIT + 186; +pub const SYS_readahead: ::c_long = __X32_SYSCALL_BIT + 187; +pub const SYS_setxattr: ::c_long = __X32_SYSCALL_BIT + 188; +pub const SYS_lsetxattr: ::c_long = __X32_SYSCALL_BIT + 189; +pub const SYS_fsetxattr: ::c_long = __X32_SYSCALL_BIT + 190; +pub const SYS_getxattr: ::c_long = __X32_SYSCALL_BIT + 191; +pub const SYS_lgetxattr: ::c_long = __X32_SYSCALL_BIT + 192; +pub const SYS_fgetxattr: ::c_long = __X32_SYSCALL_BIT + 193; +pub const SYS_listxattr: ::c_long = __X32_SYSCALL_BIT + 194; +pub const SYS_llistxattr: ::c_long = __X32_SYSCALL_BIT + 195; +pub const SYS_flistxattr: ::c_long = __X32_SYSCALL_BIT + 196; +pub const SYS_removexattr: ::c_long = __X32_SYSCALL_BIT + 197; +pub const SYS_lremovexattr: ::c_long = __X32_SYSCALL_BIT + 198; +pub const SYS_fremovexattr: ::c_long = __X32_SYSCALL_BIT + 199; +pub const SYS_tkill: ::c_long = __X32_SYSCALL_BIT + 200; +pub const SYS_time: ::c_long = __X32_SYSCALL_BIT + 201; +pub const SYS_futex: ::c_long = __X32_SYSCALL_BIT + 202; +pub const SYS_sched_setaffinity: ::c_long = __X32_SYSCALL_BIT + 203; +pub const SYS_sched_getaffinity: ::c_long = __X32_SYSCALL_BIT + 204; +pub const SYS_io_destroy: ::c_long = __X32_SYSCALL_BIT + 207; +pub const SYS_io_getevents: ::c_long = __X32_SYSCALL_BIT + 208; +pub const SYS_io_cancel: ::c_long = __X32_SYSCALL_BIT + 210; +pub const SYS_lookup_dcookie: ::c_long = __X32_SYSCALL_BIT + 212; +pub const SYS_epoll_create: ::c_long = __X32_SYSCALL_BIT + 213; +pub const SYS_remap_file_pages: ::c_long = __X32_SYSCALL_BIT + 216; +pub const SYS_getdents64: ::c_long = __X32_SYSCALL_BIT + 217; +pub const SYS_set_tid_address: ::c_long = __X32_SYSCALL_BIT + 218; +pub const SYS_restart_syscall: ::c_long = __X32_SYSCALL_BIT + 219; +pub const SYS_semtimedop: ::c_long = __X32_SYSCALL_BIT + 220; +pub const SYS_fadvise64: ::c_long = __X32_SYSCALL_BIT + 221; +pub const SYS_timer_settime: ::c_long = __X32_SYSCALL_BIT + 223; +pub const SYS_timer_gettime: ::c_long = __X32_SYSCALL_BIT + 224; +pub const SYS_timer_getoverrun: ::c_long = __X32_SYSCALL_BIT + 225; +pub const SYS_timer_delete: ::c_long = __X32_SYSCALL_BIT + 226; +pub const SYS_clock_settime: ::c_long = __X32_SYSCALL_BIT + 227; +pub const SYS_clock_gettime: ::c_long = __X32_SYSCALL_BIT + 228; +pub const SYS_clock_getres: ::c_long = __X32_SYSCALL_BIT + 229; +pub const SYS_clock_nanosleep: ::c_long = __X32_SYSCALL_BIT + 230; +pub const SYS_exit_group: ::c_long = __X32_SYSCALL_BIT + 231; +pub const SYS_epoll_wait: ::c_long = __X32_SYSCALL_BIT + 232; +pub const SYS_epoll_ctl: ::c_long = __X32_SYSCALL_BIT + 233; +pub const SYS_tgkill: ::c_long = __X32_SYSCALL_BIT + 234; +pub const SYS_utimes: ::c_long = __X32_SYSCALL_BIT + 235; +pub const SYS_mbind: ::c_long = __X32_SYSCALL_BIT + 237; +pub const SYS_set_mempolicy: ::c_long = __X32_SYSCALL_BIT + 238; +pub const SYS_get_mempolicy: ::c_long = __X32_SYSCALL_BIT + 239; +pub const SYS_mq_open: ::c_long = __X32_SYSCALL_BIT + 240; +pub const SYS_mq_unlink: ::c_long = __X32_SYSCALL_BIT + 241; +pub const SYS_mq_timedsend: ::c_long = __X32_SYSCALL_BIT + 242; +pub const SYS_mq_timedreceive: ::c_long = __X32_SYSCALL_BIT + 243; +pub const SYS_mq_getsetattr: ::c_long = __X32_SYSCALL_BIT + 245; +pub const SYS_add_key: ::c_long = __X32_SYSCALL_BIT + 248; +pub const SYS_request_key: ::c_long = __X32_SYSCALL_BIT + 249; +pub const SYS_keyctl: ::c_long = __X32_SYSCALL_BIT + 250; +pub const SYS_ioprio_set: ::c_long = __X32_SYSCALL_BIT + 251; +pub const SYS_ioprio_get: ::c_long = __X32_SYSCALL_BIT + 252; +pub const SYS_inotify_init: ::c_long = __X32_SYSCALL_BIT + 253; +pub const SYS_inotify_add_watch: ::c_long = __X32_SYSCALL_BIT + 254; +pub const SYS_inotify_rm_watch: ::c_long = __X32_SYSCALL_BIT + 255; +pub const SYS_migrate_pages: ::c_long = __X32_SYSCALL_BIT + 256; +pub const SYS_openat: ::c_long = __X32_SYSCALL_BIT + 257; +pub const SYS_mkdirat: ::c_long = __X32_SYSCALL_BIT + 258; +pub const SYS_mknodat: ::c_long = __X32_SYSCALL_BIT + 259; +pub const SYS_fchownat: ::c_long = __X32_SYSCALL_BIT + 260; +pub const SYS_futimesat: ::c_long = __X32_SYSCALL_BIT + 261; +pub const SYS_newfstatat: ::c_long = __X32_SYSCALL_BIT + 262; +pub const SYS_unlinkat: ::c_long = __X32_SYSCALL_BIT + 263; +pub const SYS_renameat: ::c_long = __X32_SYSCALL_BIT + 264; +pub const SYS_linkat: ::c_long = __X32_SYSCALL_BIT + 265; +pub const SYS_symlinkat: ::c_long = __X32_SYSCALL_BIT + 266; +pub const SYS_readlinkat: ::c_long = __X32_SYSCALL_BIT + 267; +pub const SYS_fchmodat: ::c_long = __X32_SYSCALL_BIT + 268; +pub const SYS_faccessat: ::c_long = __X32_SYSCALL_BIT + 269; +pub const SYS_pselect6: ::c_long = __X32_SYSCALL_BIT + 270; +pub const SYS_ppoll: ::c_long = __X32_SYSCALL_BIT + 271; +pub const SYS_unshare: ::c_long = __X32_SYSCALL_BIT + 272; +pub const SYS_splice: ::c_long = __X32_SYSCALL_BIT + 275; +pub const SYS_tee: ::c_long = __X32_SYSCALL_BIT + 276; +pub const SYS_sync_file_range: ::c_long = __X32_SYSCALL_BIT + 277; +pub const SYS_utimensat: ::c_long = __X32_SYSCALL_BIT + 280; +pub const SYS_epoll_pwait: ::c_long = __X32_SYSCALL_BIT + 281; +pub const SYS_signalfd: ::c_long = __X32_SYSCALL_BIT + 282; +pub const SYS_timerfd_create: ::c_long = __X32_SYSCALL_BIT + 283; +pub const SYS_eventfd: ::c_long = __X32_SYSCALL_BIT + 284; +pub const SYS_fallocate: ::c_long = __X32_SYSCALL_BIT + 285; +pub const SYS_timerfd_settime: ::c_long = __X32_SYSCALL_BIT + 286; +pub const SYS_timerfd_gettime: ::c_long = __X32_SYSCALL_BIT + 287; +pub const SYS_accept4: ::c_long = __X32_SYSCALL_BIT + 288; +pub const SYS_signalfd4: ::c_long = __X32_SYSCALL_BIT + 289; +pub const SYS_eventfd2: ::c_long = __X32_SYSCALL_BIT + 290; +pub const SYS_epoll_create1: ::c_long = __X32_SYSCALL_BIT + 291; +pub const SYS_dup3: ::c_long = __X32_SYSCALL_BIT + 292; +pub const SYS_pipe2: ::c_long = __X32_SYSCALL_BIT + 293; +pub const SYS_inotify_init1: ::c_long = __X32_SYSCALL_BIT + 294; +pub const SYS_perf_event_open: ::c_long = __X32_SYSCALL_BIT + 298; +pub const SYS_fanotify_init: ::c_long = __X32_SYSCALL_BIT + 300; +pub const SYS_fanotify_mark: ::c_long = __X32_SYSCALL_BIT + 301; +pub const SYS_prlimit64: ::c_long = __X32_SYSCALL_BIT + 302; +pub const SYS_name_to_handle_at: ::c_long = __X32_SYSCALL_BIT + 303; +pub const SYS_open_by_handle_at: ::c_long = __X32_SYSCALL_BIT + 304; +pub const SYS_clock_adjtime: ::c_long = __X32_SYSCALL_BIT + 305; +pub const SYS_syncfs: ::c_long = __X32_SYSCALL_BIT + 306; +pub const SYS_setns: ::c_long = __X32_SYSCALL_BIT + 308; +pub const SYS_getcpu: ::c_long = __X32_SYSCALL_BIT + 309; +pub const SYS_kcmp: ::c_long = __X32_SYSCALL_BIT + 312; +pub const SYS_finit_module: ::c_long = __X32_SYSCALL_BIT + 313; +pub const SYS_sched_setattr: ::c_long = __X32_SYSCALL_BIT + 314; +pub const SYS_sched_getattr: ::c_long = __X32_SYSCALL_BIT + 315; +pub const SYS_renameat2: ::c_long = __X32_SYSCALL_BIT + 316; +pub const SYS_seccomp: ::c_long = __X32_SYSCALL_BIT + 317; +pub const SYS_getrandom: ::c_long = __X32_SYSCALL_BIT + 318; +pub const SYS_memfd_create: ::c_long = __X32_SYSCALL_BIT + 319; +pub const SYS_kexec_file_load: ::c_long = __X32_SYSCALL_BIT + 320; +pub const SYS_bpf: ::c_long = __X32_SYSCALL_BIT + 321; +pub const SYS_userfaultfd: ::c_long = __X32_SYSCALL_BIT + 323; +pub const SYS_membarrier: ::c_long = __X32_SYSCALL_BIT + 324; +pub const SYS_mlock2: ::c_long = __X32_SYSCALL_BIT + 325; +pub const SYS_copy_file_range: ::c_long = __X32_SYSCALL_BIT + 326; +pub const SYS_pkey_mprotect: ::c_long = __X32_SYSCALL_BIT + 329; +pub const SYS_pkey_alloc: ::c_long = __X32_SYSCALL_BIT + 330; +pub const SYS_pkey_free: ::c_long = __X32_SYSCALL_BIT + 331; +pub const SYS_rt_sigaction: ::c_long = __X32_SYSCALL_BIT + 512; +pub const SYS_rt_sigreturn: ::c_long = __X32_SYSCALL_BIT + 513; +pub const SYS_ioctl: ::c_long = __X32_SYSCALL_BIT + 514; +pub const SYS_readv: ::c_long = __X32_SYSCALL_BIT + 515; +pub const SYS_writev: ::c_long = __X32_SYSCALL_BIT + 516; +pub const SYS_recvfrom: ::c_long = __X32_SYSCALL_BIT + 517; +pub const SYS_sendmsg: ::c_long = __X32_SYSCALL_BIT + 518; +pub const SYS_recvmsg: ::c_long = __X32_SYSCALL_BIT + 519; +pub const SYS_execve: ::c_long = __X32_SYSCALL_BIT + 520; +pub const SYS_ptrace: ::c_long = __X32_SYSCALL_BIT + 521; +pub const SYS_rt_sigpending: ::c_long = __X32_SYSCALL_BIT + 522; +pub const SYS_rt_sigtimedwait: ::c_long = __X32_SYSCALL_BIT + 523; +pub const SYS_rt_sigqueueinfo: ::c_long = __X32_SYSCALL_BIT + 524; +pub const SYS_sigaltstack: ::c_long = __X32_SYSCALL_BIT + 525; +pub const SYS_timer_create: ::c_long = __X32_SYSCALL_BIT + 526; +pub const SYS_mq_notify: ::c_long = __X32_SYSCALL_BIT + 527; +pub const SYS_kexec_load: ::c_long = __X32_SYSCALL_BIT + 528; +pub const SYS_waitid: ::c_long = __X32_SYSCALL_BIT + 529; +pub const SYS_set_robust_list: ::c_long = __X32_SYSCALL_BIT + 530; +pub const SYS_get_robust_list: ::c_long = __X32_SYSCALL_BIT + 531; +pub const SYS_vmsplice: ::c_long = __X32_SYSCALL_BIT + 532; +pub const SYS_move_pages: ::c_long = __X32_SYSCALL_BIT + 533; +pub const SYS_preadv: ::c_long = __X32_SYSCALL_BIT + 534; +pub const SYS_pwritev: ::c_long = __X32_SYSCALL_BIT + 535; +pub const SYS_rt_tgsigqueueinfo: ::c_long = __X32_SYSCALL_BIT + 536; +pub const SYS_recvmmsg: ::c_long = __X32_SYSCALL_BIT + 537; +pub const SYS_sendmmsg: ::c_long = __X32_SYSCALL_BIT + 538; +pub const SYS_process_vm_readv: ::c_long = __X32_SYSCALL_BIT + 539; +pub const SYS_process_vm_writev: ::c_long = __X32_SYSCALL_BIT + 540; +pub const SYS_setsockopt: ::c_long = __X32_SYSCALL_BIT + 541; +pub const SYS_getsockopt: ::c_long = __X32_SYSCALL_BIT + 542; +pub const SYS_io_setup: ::c_long = __X32_SYSCALL_BIT + 543; +pub const SYS_io_submit: ::c_long = __X32_SYSCALL_BIT + 544; +pub const SYS_execveat: ::c_long = __X32_SYSCALL_BIT + 545; +pub const SYS_preadv2: ::c_long = __X32_SYSCALL_BIT + 546; +pub const SYS_pwritev2: ::c_long = __X32_SYSCALL_BIT + 547; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/x86_64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/x86_64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/x86_64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/b64/x86_64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,656 @@ +//! x86_64-specific definitions for 64-bit linux-like values + +pub type c_char = i8; +pub type wchar_t = i32; +pub type nlink_t = u64; +pub type blksize_t = i64; +pub type greg_t = i64; +pub type suseconds_t = i64; +pub type __u64 = ::c_ulonglong; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + __pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: i64, + pub st_mtime: ::time_t, + pub st_mtime_nsec: i64, + pub st_ctime: ::time_t, + pub st_ctime_nsec: i64, + __unused: [i64; 3], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino64_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + __pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: i64, + pub st_mtime: ::time_t, + pub st_mtime_nsec: i64, + pub st_ctime: ::time_t, + pub st_ctime_nsec: i64, + __reserved: [i64; 3], + } + + pub struct statfs64 { + pub f_type: ::__fsword_t, + pub f_bsize: ::__fsword_t, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_fsid: ::fsid_t, + pub f_namelen: ::__fsword_t, + pub f_frsize: ::__fsword_t, + pub f_flags: ::__fsword_t, + pub f_spare: [::__fsword_t; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct pthread_attr_t { + #[cfg(target_pointer_width = "32")] + __size: [u32; 8], + #[cfg(target_pointer_width = "64")] + __size: [u64; 7] + } + + pub struct _libc_fpxreg { + pub significand: [u16; 4], + pub exponent: u16, + __private: [u16; 3], + } + + pub struct _libc_xmmreg { + pub element: [u32; 4], + } + + pub struct _libc_fpstate { + pub cwd: u16, + pub swd: u16, + pub ftw: u16, + pub fop: u16, + pub rip: u64, + pub rdp: u64, + pub mxcsr: u32, + pub mxcr_mask: u32, + pub _st: [_libc_fpxreg; 8], + pub _xmm: [_libc_xmmreg; 16], + __private: [u64; 12], + } + + pub struct user_fpregs_struct { + pub cwd: ::c_ushort, + pub swd: ::c_ushort, + pub ftw: ::c_ushort, + pub fop: ::c_ushort, + pub rip: ::c_ulonglong, + pub rdp: ::c_ulonglong, + pub mxcsr: ::c_uint, + pub mxcr_mask: ::c_uint, + pub st_space: [::c_uint; 32], + pub xmm_space: [::c_uint; 64], + padding: [::c_uint; 24], + } + + pub struct user_regs_struct { + pub r15: ::c_ulonglong, + pub r14: ::c_ulonglong, + pub r13: ::c_ulonglong, + pub r12: ::c_ulonglong, + pub rbp: ::c_ulonglong, + pub rbx: ::c_ulonglong, + pub r11: ::c_ulonglong, + pub r10: ::c_ulonglong, + pub r9: ::c_ulonglong, + pub r8: ::c_ulonglong, + pub rax: ::c_ulonglong, + pub rcx: ::c_ulonglong, + pub rdx: ::c_ulonglong, + pub rsi: ::c_ulonglong, + pub rdi: ::c_ulonglong, + pub orig_rax: ::c_ulonglong, + pub rip: ::c_ulonglong, + pub cs: ::c_ulonglong, + pub eflags: ::c_ulonglong, + pub rsp: ::c_ulonglong, + pub ss: ::c_ulonglong, + pub fs_base: ::c_ulonglong, + pub gs_base: ::c_ulonglong, + pub ds: ::c_ulonglong, + pub es: ::c_ulonglong, + pub fs: ::c_ulonglong, + pub gs: ::c_ulonglong, + } + + pub struct user { + pub regs: user_regs_struct, + pub u_fpvalid: ::c_int, + pub i387: user_fpregs_struct, + pub u_tsize: ::c_ulonglong, + pub u_dsize: ::c_ulonglong, + pub u_ssize: ::c_ulonglong, + pub start_code: ::c_ulonglong, + pub start_stack: ::c_ulonglong, + pub signal: ::c_longlong, + __reserved: ::c_int, + #[cfg(target_pointer_width = "32")] + __pad1: u32, + pub u_ar0: *mut user_regs_struct, + #[cfg(target_pointer_width = "32")] + __pad2: u32, + pub u_fpstate: *mut user_fpregs_struct, + pub magic: ::c_ulonglong, + pub u_comm: [::c_char; 32], + pub u_debugreg: [::c_ulonglong; 8], + } + + pub struct mcontext_t { + pub gregs: [greg_t; 23], + pub fpregs: *mut _libc_fpstate, + __private: [u64; 8], + } + + pub struct ucontext_t { + pub uc_flags: ::c_ulong, + pub uc_link: *mut ucontext_t, + pub uc_stack: ::stack_t, + pub uc_mcontext: mcontext_t, + pub uc_sigmask: ::sigset_t, + __private: [u8; 512], + } + + pub struct ipc_perm { + pub __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::c_ushort, + __pad1: ::c_ushort, + pub __seq: ::c_ushort, + __pad2: ::c_ushort, + __unused1: u64, + __unused2: u64 + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __unused4: u64, + __unused5: u64 + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 19], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } +} + +pub const TIOCGSOFTCAR: ::c_ulong = 0x5419; +pub const TIOCSSOFTCAR: ::c_ulong = 0x541A; + +pub const RLIMIT_NOFILE: ::c_int = 7; +pub const RLIMIT_NPROC: ::c_int = 6; + +pub const O_APPEND: ::c_int = 1024; +pub const O_CREAT: ::c_int = 64; +pub const O_EXCL: ::c_int = 128; +pub const O_NOCTTY: ::c_int = 256; +pub const O_NONBLOCK: ::c_int = 2048; +pub const O_SYNC: ::c_int = 1052672; +pub const O_RSYNC: ::c_int = 1052672; +pub const O_DSYNC: ::c_int = 4096; +pub const O_FSYNC: ::c_int = 0x101000; +pub const O_NOATIME: ::c_int = 0o1000000; +pub const O_PATH: ::c_int = 0o10000000; +pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; + +pub const MAP_GROWSDOWN: ::c_int = 0x0100; + +pub const EDEADLK: ::c_int = 35; +pub const ENAMETOOLONG: ::c_int = 36; +pub const ENOLCK: ::c_int = 37; +pub const ENOSYS: ::c_int = 38; +pub const ENOTEMPTY: ::c_int = 39; +pub const ELOOP: ::c_int = 40; +pub const ENOMSG: ::c_int = 42; +pub const EIDRM: ::c_int = 43; +pub const ECHRNG: ::c_int = 44; +pub const EL2NSYNC: ::c_int = 45; +pub const EL3HLT: ::c_int = 46; +pub const EL3RST: ::c_int = 47; +pub const ELNRNG: ::c_int = 48; +pub const EUNATCH: ::c_int = 49; +pub const ENOCSI: ::c_int = 50; +pub const EL2HLT: ::c_int = 51; +pub const EBADE: ::c_int = 52; +pub const EBADR: ::c_int = 53; +pub const EXFULL: ::c_int = 54; +pub const ENOANO: ::c_int = 55; +pub const EBADRQC: ::c_int = 56; +pub const EBADSLT: ::c_int = 57; +pub const EMULTIHOP: ::c_int = 72; +pub const EOVERFLOW: ::c_int = 75; +pub const ENOTUNIQ: ::c_int = 76; +pub const EBADFD: ::c_int = 77; +pub const EBADMSG: ::c_int = 74; +pub const EREMCHG: ::c_int = 78; +pub const ELIBACC: ::c_int = 79; +pub const ELIBBAD: ::c_int = 80; +pub const ELIBSCN: ::c_int = 81; +pub const ELIBMAX: ::c_int = 82; +pub const ELIBEXEC: ::c_int = 83; +pub const EILSEQ: ::c_int = 84; +pub const ERESTART: ::c_int = 85; +pub const ESTRPIPE: ::c_int = 86; +pub const EUSERS: ::c_int = 87; +pub const ENOTSOCK: ::c_int = 88; +pub const EDESTADDRREQ: ::c_int = 89; +pub const EMSGSIZE: ::c_int = 90; +pub const EPROTOTYPE: ::c_int = 91; +pub const ENOPROTOOPT: ::c_int = 92; +pub const EPROTONOSUPPORT: ::c_int = 93; +pub const ESOCKTNOSUPPORT: ::c_int = 94; +pub const EOPNOTSUPP: ::c_int = 95; +pub const EPFNOSUPPORT: ::c_int = 96; +pub const EAFNOSUPPORT: ::c_int = 97; +pub const EADDRINUSE: ::c_int = 98; +pub const EADDRNOTAVAIL: ::c_int = 99; +pub const ENETDOWN: ::c_int = 100; +pub const ENETUNREACH: ::c_int = 101; +pub const ENETRESET: ::c_int = 102; +pub const ECONNABORTED: ::c_int = 103; +pub const ECONNRESET: ::c_int = 104; +pub const ENOBUFS: ::c_int = 105; +pub const EISCONN: ::c_int = 106; +pub const ENOTCONN: ::c_int = 107; +pub const ESHUTDOWN: ::c_int = 108; +pub const ETOOMANYREFS: ::c_int = 109; +pub const ETIMEDOUT: ::c_int = 110; +pub const ECONNREFUSED: ::c_int = 111; +pub const EHOSTDOWN: ::c_int = 112; +pub const EHOSTUNREACH: ::c_int = 113; +pub const EALREADY: ::c_int = 114; +pub const EINPROGRESS: ::c_int = 115; +pub const ESTALE: ::c_int = 116; +pub const EDQUOT: ::c_int = 122; +pub const ENOMEDIUM: ::c_int = 123; +pub const EMEDIUMTYPE: ::c_int = 124; +pub const ECANCELED: ::c_int = 125; +pub const ENOKEY: ::c_int = 126; +pub const EKEYEXPIRED: ::c_int = 127; +pub const EKEYREVOKED: ::c_int = 128; +pub const EKEYREJECTED: ::c_int = 129; +pub const EOWNERDEAD: ::c_int = 130; +pub const ENOTRECOVERABLE: ::c_int = 131; +pub const EHWPOISON: ::c_int = 133; +pub const ERFKILL: ::c_int = 132; + +pub const SOL_SOCKET: ::c_int = 1; + +pub const SO_REUSEADDR: ::c_int = 2; +pub const SO_TYPE: ::c_int = 3; +pub const SO_ERROR: ::c_int = 4; +pub const SO_DONTROUTE: ::c_int = 5; +pub const SO_BROADCAST: ::c_int = 6; +pub const SO_SNDBUF: ::c_int = 7; +pub const SO_RCVBUF: ::c_int = 8; +pub const SO_SNDBUFFORCE: ::c_int = 32; +pub const SO_RCVBUFFORCE: ::c_int = 33; +pub const SO_KEEPALIVE: ::c_int = 9; +pub const SO_OOBINLINE: ::c_int = 10; +pub const SO_NO_CHECK: ::c_int = 11; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_LINGER: ::c_int = 13; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_REUSEPORT: ::c_int = 15; +pub const SO_PASSCRED: ::c_int = 16; +pub const SO_PEERCRED: ::c_int = 17; +pub const SO_RCVLOWAT: ::c_int = 18; +pub const SO_SNDLOWAT: ::c_int = 19; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_SNDTIMEO: ::c_int = 21; +pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22; +pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23; +pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24; +pub const SO_BINDTODEVICE: ::c_int = 25; +pub const SO_ATTACH_FILTER: ::c_int = 26; +pub const SO_DETACH_FILTER: ::c_int = 27; +pub const SO_GET_FILTER: ::c_int = SO_ATTACH_FILTER; +pub const SO_PEERNAME: ::c_int = 28; +pub const SO_TIMESTAMP: ::c_int = 29; +pub const SO_ACCEPTCONN: ::c_int = 30; +pub const SO_PEERSEC: ::c_int = 31; +pub const SO_PASSSEC: ::c_int = 34; +pub const SO_TIMESTAMPNS: ::c_int = 35; +pub const SCM_TIMESTAMPNS: ::c_int = SO_TIMESTAMPNS; +pub const SO_MARK: ::c_int = 36; +pub const SO_TIMESTAMPING: ::c_int = 37; +pub const SCM_TIMESTAMPING: ::c_int = SO_TIMESTAMPING; +pub const SO_PROTOCOL: ::c_int = 38; +pub const SO_DOMAIN: ::c_int = 39; +pub const SO_RXQ_OVFL: ::c_int = 40; +pub const SO_WIFI_STATUS: ::c_int = 41; +pub const SCM_WIFI_STATUS: ::c_int = SO_WIFI_STATUS; +pub const SO_PEEK_OFF: ::c_int = 42; +pub const SO_NOFCS: ::c_int = 43; +pub const SO_LOCK_FILTER: ::c_int = 44; +pub const SO_SELECT_ERR_QUEUE: ::c_int = 45; +pub const SO_BUSY_POLL: ::c_int = 46; +pub const SO_MAX_PACING_RATE: ::c_int = 47; +pub const SO_BPF_EXTENSIONS: ::c_int = 48; +pub const SO_INCOMING_CPU: ::c_int = 49; +pub const SO_ATTACH_BPF: ::c_int = 50; +pub const SO_DETACH_BPF: ::c_int = SO_DETACH_FILTER; + +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 0x00000004; +pub const SA_NOCLDWAIT: ::c_int = 0x00000002; + +pub const SIGCHLD: ::c_int = 17; +pub const SIGBUS: ::c_int = 7; +pub const SIGUSR1: ::c_int = 10; +pub const SIGUSR2: ::c_int = 12; +pub const SIGCONT: ::c_int = 18; +pub const SIGSTOP: ::c_int = 19; +pub const SIGTSTP: ::c_int = 20; +pub const SIGURG: ::c_int = 23; +pub const SIGIO: ::c_int = 29; +pub const SIGSYS: ::c_int = 31; +pub const SIGSTKFLT: ::c_int = 16; +pub const SIGUNUSED: ::c_int = 31; +pub const SIGPOLL: ::c_int = 29; +pub const SIGPWR: ::c_int = 30; +pub const SIG_SETMASK: ::c_int = 2; +pub const SIG_BLOCK: ::c_int = 0x000000; +pub const SIG_UNBLOCK: ::c_int = 0x01; + +pub const POLLWRNORM: ::c_short = 0x100; +pub const POLLWRBAND: ::c_short = 0x200; + +pub const O_ASYNC: ::c_int = 0x2000; +pub const O_NDELAY: ::c_int = 0x800; + +pub const PTRACE_DETACH: ::c_uint = 17; + +pub const EFD_NONBLOCK: ::c_int = 0x800; + +pub const F_GETLK: ::c_int = 5; +pub const F_GETOWN: ::c_int = 9; +pub const F_SETOWN: ::c_int = 8; +pub const F_SETLK: ::c_int = 6; +pub const F_SETLKW: ::c_int = 7; + +pub const SFD_NONBLOCK: ::c_int = 0x0800; + +pub const TIOCEXCL: ::c_ulong = 0x540C; +pub const TIOCNXCL: ::c_ulong = 0x540D; +pub const TIOCSCTTY: ::c_ulong = 0x540E; +pub const TIOCSTI: ::c_ulong = 0x5412; +pub const TIOCMGET: ::c_ulong = 0x5415; +pub const TIOCMBIS: ::c_ulong = 0x5416; +pub const TIOCMBIC: ::c_ulong = 0x5417; +pub const TIOCMSET: ::c_ulong = 0x5418; +pub const TIOCCONS: ::c_ulong = 0x541D; + +pub const SFD_CLOEXEC: ::c_int = 0x080000; + +pub const NCCS: usize = 32; + +pub const O_TRUNC: ::c_int = 512; + +pub const O_CLOEXEC: ::c_int = 0x80000; + +pub const EBFONT: ::c_int = 59; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const EDOTDOT: ::c_int = 73; + +pub const SA_NODEFER: ::c_int = 0x40000000; +pub const SA_RESETHAND: ::c_int = 0x80000000; +pub const SA_RESTART: ::c_int = 0x10000000; +pub const SA_NOCLDSTOP: ::c_int = 0x00000001; + +pub const EPOLL_CLOEXEC: ::c_int = 0x80000; + +pub const EFD_CLOEXEC: ::c_int = 0x80000; + +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; + +pub const O_DIRECT: ::c_int = 0x4000; +pub const O_DIRECTORY: ::c_int = 0x10000; +pub const O_NOFOLLOW: ::c_int = 0x20000; + +pub const MAP_LOCKED: ::c_int = 0x02000; +pub const MAP_NORESERVE: ::c_int = 0x04000; +pub const MAP_32BIT: ::c_int = 0x0040; + +pub const EDEADLOCK: ::c_int = 35; + +pub const FIOCLEX: ::c_ulong = 0x5451; +pub const FIONBIO: ::c_ulong = 0x5421; + +pub const PTRACE_GETFPREGS: ::c_uint = 14; +pub const PTRACE_SETFPREGS: ::c_uint = 15; +pub const PTRACE_GETFPXREGS: ::c_uint = 18; +pub const PTRACE_SETFPXREGS: ::c_uint = 19; +pub const PTRACE_GETREGS: ::c_uint = 12; +pub const PTRACE_SETREGS: ::c_uint = 13; +pub const PTRACE_PEEKSIGINFO_SHARED: ::c_uint = 1; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const SIGSTKSZ: ::size_t = 8192; +pub const MINSIGSTKSZ: ::size_t = 2048; +pub const CBAUD: ::tcflag_t = 0o0010017; +pub const TAB1: ::c_int = 0x00000800; +pub const TAB2: ::c_int = 0x00001000; +pub const TAB3: ::c_int = 0x00001800; +pub const CR1: ::c_int = 0x00000200; +pub const CR2: ::c_int = 0x00000400; +pub const CR3: ::c_int = 0x00000600; +pub const FF1: ::c_int = 0x00008000; +pub const BS1: ::c_int = 0x00002000; +pub const VT1: ::c_int = 0x00004000; +pub const VWERASE: usize = 14; +pub const VREPRINT: usize = 12; +pub const VSUSP: usize = 10; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VDISCARD: usize = 13; +pub const VTIME: usize = 5; +pub const IXON: ::tcflag_t = 0x00000400; +pub const IXOFF: ::tcflag_t = 0x00001000; +pub const ONLCR: ::tcflag_t = 0x4; +pub const CSIZE: ::tcflag_t = 0x00000030; +pub const CS6: ::tcflag_t = 0x00000010; +pub const CS7: ::tcflag_t = 0x00000020; +pub const CS8: ::tcflag_t = 0x00000030; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const ECHOKE: ::tcflag_t = 0x00000800; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const ECHOPRT: ::tcflag_t = 0x00000400; +pub const ECHOCTL: ::tcflag_t = 0x00000200; +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const PENDIN: ::tcflag_t = 0x00004000; +pub const NOFLSH: ::tcflag_t = 0x00000080; +pub const CIBAUD: ::tcflag_t = 0o02003600000; +pub const CBAUDEX: ::tcflag_t = 0o010000; +pub const VSWTC: usize = 7; +pub const OLCUC: ::tcflag_t = 0o000002; +pub const NLDLY: ::tcflag_t = 0o000400; +pub const CRDLY: ::tcflag_t = 0o003000; +pub const TABDLY: ::tcflag_t = 0o014000; +pub const BSDLY: ::tcflag_t = 0o020000; +pub const FFDLY: ::tcflag_t = 0o100000; +pub const VTDLY: ::tcflag_t = 0o040000; +pub const XTABS: ::tcflag_t = 0o014000; + +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const BOTHER: ::speed_t = 0o010000; +pub const B57600: ::speed_t = 0o010001; +pub const B115200: ::speed_t = 0o010002; +pub const B230400: ::speed_t = 0o010003; +pub const B460800: ::speed_t = 0o010004; +pub const B500000: ::speed_t = 0o010005; +pub const B576000: ::speed_t = 0o010006; +pub const B921600: ::speed_t = 0o010007; +pub const B1000000: ::speed_t = 0o010010; +pub const B1152000: ::speed_t = 0o010011; +pub const B1500000: ::speed_t = 0o010012; +pub const B2000000: ::speed_t = 0o010013; +pub const B2500000: ::speed_t = 0o010014; +pub const B3000000: ::speed_t = 0o010015; +pub const B3500000: ::speed_t = 0o010016; +pub const B4000000: ::speed_t = 0o010017; + +pub const VEOL: usize = 11; +pub const VEOL2: usize = 16; +pub const VMIN: usize = 6; +pub const IEXTEN: ::tcflag_t = 0x00008000; +pub const TOSTOP: ::tcflag_t = 0x00000100; +pub const FLUSHO: ::tcflag_t = 0x00001000; +pub const EXTPROC: ::tcflag_t = 0x00010000; +pub const TCGETS: ::c_ulong = 0x5401; +pub const TCSETS: ::c_ulong = 0x5402; +pub const TCSETSW: ::c_ulong = 0x5403; +pub const TCSETSF: ::c_ulong = 0x5404; +pub const TCGETA: ::c_ulong = 0x5405; +pub const TCSETA: ::c_ulong = 0x5406; +pub const TCSETAW: ::c_ulong = 0x5407; +pub const TCSETAF: ::c_ulong = 0x5408; +pub const TCSBRK: ::c_ulong = 0x5409; +pub const TCXONC: ::c_ulong = 0x540A; +pub const TCFLSH: ::c_ulong = 0x540B; +pub const TIOCINQ: ::c_ulong = 0x541B; +pub const TIOCGPGRP: ::c_ulong = 0x540F; +pub const TIOCSPGRP: ::c_ulong = 0x5410; +pub const TIOCOUTQ: ::c_ulong = 0x5411; +pub const TIOCGWINSZ: ::c_ulong = 0x5413; +pub const TIOCSWINSZ: ::c_ulong = 0x5414; +pub const FIONREAD: ::c_ulong = 0x541B; + +// offsets in user_regs_structs, from sys/reg.h +pub const R15: ::c_int = 0; +pub const R14: ::c_int = 1; +pub const R13: ::c_int = 2; +pub const R12: ::c_int = 3; +pub const RBP: ::c_int = 4; +pub const RBX: ::c_int = 5; +pub const R11: ::c_int = 6; +pub const R10: ::c_int = 7; +pub const R9: ::c_int = 8; +pub const R8: ::c_int = 9; +pub const RAX: ::c_int = 10; +pub const RCX: ::c_int = 11; +pub const RDX: ::c_int = 12; +pub const RSI: ::c_int = 13; +pub const RDI: ::c_int = 14; +pub const ORIG_RAX: ::c_int = 15; +pub const RIP: ::c_int = 16; +pub const CS: ::c_int = 17; +pub const EFLAGS: ::c_int = 18; +pub const RSP: ::c_int = 19; +pub const SS: ::c_int = 20; +pub const FS_BASE: ::c_int = 21; +pub const GS_BASE: ::c_int = 22; +pub const DS: ::c_int = 23; +pub const ES: ::c_int = 24; +pub const FS: ::c_int = 25; +pub const GS: ::c_int = 26; + +extern { + pub fn getcontext(ucp: *mut ucontext_t) -> ::c_int; + pub fn setcontext(ucp: *const ucontext_t) -> ::c_int; + pub fn makecontext(ucp: *mut ucontext_t, + func: extern fn (), + argc: ::c_int, ...); + pub fn swapcontext(uocp: *mut ucontext_t, + ucp: *const ucontext_t) -> ::c_int; + pub fn iopl(level: ::c_int) -> ::c_int; + pub fn ioperm(from: ::c_ulong, num: ::c_ulong, + turn_on: ::c_int) -> ::c_int; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/other/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,900 @@ +pub type __priority_which_t = ::c_uint; + +s! { + pub struct aiocb { + pub aio_fildes: ::c_int, + pub aio_lio_opcode: ::c_int, + pub aio_reqprio: ::c_int, + pub aio_buf: *mut ::c_void, + pub aio_nbytes: ::size_t, + pub aio_sigevent: ::sigevent, + __next_prio: *mut aiocb, + __abs_prio: ::c_int, + __policy: ::c_int, + __error_code: ::c_int, + __return_value: ::ssize_t, + pub aio_offset: off_t, + #[cfg(all(not(target_arch = "x86_64"), target_pointer_width = "32"))] + __unused1: [::c_char; 4], + __glibc_reserved: [::c_char; 32] + } + + pub struct __exit_status { + pub e_termination: ::c_short, + pub e_exit: ::c_short, + } + + pub struct __timeval { + pub tv_sec: ::int32_t, + pub tv_usec: ::int32_t, + } + + pub struct utmpx { + pub ut_type: ::c_short, + pub ut_pid: ::pid_t, + pub ut_line: [::c_char; __UT_LINESIZE], + pub ut_id: [::c_char; 4], + + pub ut_user: [::c_char; __UT_NAMESIZE], + pub ut_host: [::c_char; __UT_HOSTSIZE], + pub ut_exit: __exit_status, + + #[cfg(any(target_arch = "aarch64", + target_arch = "sparc64", + all(target_pointer_width = "32", + not(target_arch = "x86_64"))))] + pub ut_session: ::c_long, + #[cfg(any(target_arch = "aarch64", + target_arch = "sparc64", + all(target_pointer_width = "32", + not(target_arch = "x86_64"))))] + pub ut_tv: ::timeval, + + #[cfg(not(any(target_arch = "aarch64", + target_arch = "sparc64", + all(target_pointer_width = "32", + not(target_arch = "x86_64")))))] + pub ut_session: ::int32_t, + #[cfg(not(any(target_arch = "aarch64", + target_arch = "sparc64", + all(target_pointer_width = "32", + not(target_arch = "x86_64")))))] + pub ut_tv: __timeval, + + pub ut_addr_v6: [::int32_t; 4], + __glibc_reserved: [::c_char; 20], + } + + pub struct sigaction { + pub sa_sigaction: ::sighandler_t, + pub sa_mask: ::sigset_t, + #[cfg(target_arch = "sparc64")] + __reserved0: ::c_int, + pub sa_flags: ::c_int, + pub sa_restorer: ::dox::Option, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_flags: ::c_int, + pub ss_size: ::size_t + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_errno: ::c_int, + pub si_code: ::c_int, + pub _pad: [::c_int; 29], + #[cfg(target_arch = "x86_64")] + _align: [u64; 0], + #[cfg(not(target_arch = "x86_64"))] + _align: [usize; 0], + } + + pub struct glob64_t { + pub gl_pathc: ::size_t, + pub gl_pathv: *mut *mut ::c_char, + pub gl_offs: ::size_t, + pub gl_flags: ::c_int, + + __unused1: *mut ::c_void, + __unused2: *mut ::c_void, + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + } + + pub struct statfs { + pub f_type: __fsword_t, + pub f_bsize: __fsword_t, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + + pub f_namelen: __fsword_t, + pub f_frsize: __fsword_t, + f_spare: [__fsword_t; 5], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::size_t, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::size_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::size_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; ::NCCS], + #[cfg(not(target_arch = "sparc64"))] + pub c_ispeed: ::speed_t, + #[cfg(not(target_arch = "sparc64"))] + pub c_ospeed: ::speed_t, + } + + pub struct flock { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_pid: ::pid_t, + } + + // FIXME this is actually a union + pub struct sem_t { + #[cfg(target_pointer_width = "32")] + __size: [::c_char; 16], + #[cfg(target_pointer_width = "64")] + __size: [::c_char; 32], + __align: [::c_long; 0], + } + + pub struct mallinfo { + pub arena: ::c_int, + pub ordblks: ::c_int, + pub smblks: ::c_int, + pub hblks: ::c_int, + pub hblkhd: ::c_int, + pub usmblks: ::c_int, + pub fsmblks: ::c_int, + pub uordblks: ::c_int, + pub fordblks: ::c_int, + pub keepcost: ::c_int, + } + + pub struct nlmsghdr { + nlmsg_len: u32, + nlmsg_type: u16, + nlmsg_flags: u16, + nlmsg_seq: u32, + nlmsg_pid: u32, + } + + pub struct nlmsgerr { + error: ::c_int, + msg: nlmsghdr, + } + + pub struct nl_pktinfo { + group: u32, + } + + pub struct nl_mmap_req { + nm_block_size: ::c_uint, + nm_block_nr: ::c_uint, + nm_frame_size: ::c_uint, + nm_frame_nr: ::c_uint, + } + + pub struct nl_mmap_hdr { + nm_status: ::c_uint, + nm_len: ::c_uint, + nm_group: u32, + nm_pid: u32, + nm_uid: u32, + nm_gid: u32, + } + + pub struct nlattr { + nla_len: u16, + nla_type: u16, + } +} + +pub const __UT_LINESIZE: usize = 32; +pub const __UT_NAMESIZE: usize = 32; +pub const __UT_HOSTSIZE: usize = 256; +pub const EMPTY: ::c_short = 0; +pub const RUN_LVL: ::c_short = 1; +pub const BOOT_TIME: ::c_short = 2; +pub const NEW_TIME: ::c_short = 3; +pub const OLD_TIME: ::c_short = 4; +pub const INIT_PROCESS: ::c_short = 5; +pub const LOGIN_PROCESS: ::c_short = 6; +pub const USER_PROCESS: ::c_short = 7; +pub const DEAD_PROCESS: ::c_short = 8; +pub const ACCOUNTING: ::c_short = 9; + +pub const RLIMIT_RSS: ::c_int = 5; +pub const RLIMIT_AS: ::c_int = 9; +pub const RLIMIT_MEMLOCK: ::c_int = 8; +pub const RLIM_INFINITY: ::rlim_t = !0; +pub const RLIMIT_RTTIME: ::c_int = 15; +pub const RLIMIT_NLIMITS: ::c_int = 16; + +pub const SOCK_NONBLOCK: ::c_int = O_NONBLOCK; + +pub const SOL_RXRPC: ::c_int = 272; +pub const SOL_PPPOL2TP: ::c_int = 273; +pub const SOL_BLUETOOTH: ::c_int = 274; +pub const SOL_PNPIPE: ::c_int = 275; +pub const SOL_RDS: ::c_int = 276; +pub const SOL_IUCV: ::c_int = 277; +pub const SOL_CAIF: ::c_int = 278; +pub const SOL_ALG: ::c_int = 279; +pub const SOL_NFC: ::c_int = 280; + +pub const MSG_TRYHARD: ::c_int = 4; + +pub const LC_PAPER: ::c_int = 7; +pub const LC_NAME: ::c_int = 8; +pub const LC_ADDRESS: ::c_int = 9; +pub const LC_TELEPHONE: ::c_int = 10; +pub const LC_MEASUREMENT: ::c_int = 11; +pub const LC_IDENTIFICATION: ::c_int = 12; +pub const LC_PAPER_MASK: ::c_int = (1 << LC_PAPER); +pub const LC_NAME_MASK: ::c_int = (1 << LC_NAME); +pub const LC_ADDRESS_MASK: ::c_int = (1 << LC_ADDRESS); +pub const LC_TELEPHONE_MASK: ::c_int = (1 << LC_TELEPHONE); +pub const LC_MEASUREMENT_MASK: ::c_int = (1 << LC_MEASUREMENT); +pub const LC_IDENTIFICATION_MASK: ::c_int = (1 << LC_IDENTIFICATION); +pub const LC_ALL_MASK: ::c_int = ::LC_CTYPE_MASK + | ::LC_NUMERIC_MASK + | ::LC_TIME_MASK + | ::LC_COLLATE_MASK + | ::LC_MONETARY_MASK + | ::LC_MESSAGES_MASK + | LC_PAPER_MASK + | LC_NAME_MASK + | LC_ADDRESS_MASK + | LC_TELEPHONE_MASK + | LC_MEASUREMENT_MASK + | LC_IDENTIFICATION_MASK; + +pub const MAP_ANON: ::c_int = 0x0020; +pub const MAP_ANONYMOUS: ::c_int = 0x0020; +pub const MAP_DENYWRITE: ::c_int = 0x0800; +pub const MAP_EXECUTABLE: ::c_int = 0x01000; +pub const MAP_POPULATE: ::c_int = 0x08000; +pub const MAP_NONBLOCK: ::c_int = 0x010000; +pub const MAP_STACK: ::c_int = 0x020000; + +pub const ENOTSUP: ::c_int = EOPNOTSUPP; +pub const EUCLEAN: ::c_int = 117; +pub const ENOTNAM: ::c_int = 118; +pub const ENAVAIL: ::c_int = 119; +pub const EISNAM: ::c_int = 120; +pub const EREMOTEIO: ::c_int = 121; + +pub const SOCK_STREAM: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_SEQPACKET: ::c_int = 5; +pub const SOCK_DCCP: ::c_int = 6; +pub const SOCK_PACKET: ::c_int = 10; + +pub const TCP_COOKIE_TRANSACTIONS: ::c_int = 15; +pub const TCP_THIN_LINEAR_TIMEOUTS: ::c_int = 16; +pub const TCP_THIN_DUPACK: ::c_int = 17; +pub const TCP_USER_TIMEOUT: ::c_int = 18; +pub const TCP_REPAIR: ::c_int = 19; +pub const TCP_REPAIR_QUEUE: ::c_int = 20; +pub const TCP_QUEUE_SEQ: ::c_int = 21; +pub const TCP_REPAIR_OPTIONS: ::c_int = 22; +pub const TCP_FASTOPEN: ::c_int = 23; +pub const TCP_TIMESTAMP: ::c_int = 24; + +/* DCCP socket options */ +pub const DCCP_SOCKOPT_PACKET_SIZE: ::c_int = 1; +pub const DCCP_SOCKOPT_SERVICE: ::c_int = 2; +pub const DCCP_SOCKOPT_CHANGE_L: ::c_int = 3; +pub const DCCP_SOCKOPT_CHANGE_R: ::c_int = 4; +pub const DCCP_SOCKOPT_GET_CUR_MPS: ::c_int = 5; +pub const DCCP_SOCKOPT_SERVER_TIMEWAIT: ::c_int = 6; +pub const DCCP_SOCKOPT_SEND_CSCOV: ::c_int = 10; +pub const DCCP_SOCKOPT_RECV_CSCOV: ::c_int = 11; +pub const DCCP_SOCKOPT_AVAILABLE_CCIDS: ::c_int = 12; +pub const DCCP_SOCKOPT_CCID: ::c_int = 13; +pub const DCCP_SOCKOPT_TX_CCID: ::c_int = 14; +pub const DCCP_SOCKOPT_RX_CCID: ::c_int = 15; +pub const DCCP_SOCKOPT_QPOLICY_ID: ::c_int = 16; +pub const DCCP_SOCKOPT_QPOLICY_TXQLEN: ::c_int = 17; +pub const DCCP_SOCKOPT_CCID_RX_INFO: ::c_int = 128; +pub const DCCP_SOCKOPT_CCID_TX_INFO: ::c_int = 192; + +/// maximum number of services provided on the same listening port +pub const DCCP_SERVICE_LIST_MAX_LEN: ::c_int = 32; + +pub const SIGTTIN: ::c_int = 21; +pub const SIGTTOU: ::c_int = 22; +pub const SIGXCPU: ::c_int = 24; +pub const SIGXFSZ: ::c_int = 25; +pub const SIGVTALRM: ::c_int = 26; +pub const SIGPROF: ::c_int = 27; +pub const SIGWINCH: ::c_int = 28; + +pub const SIGEV_THREAD_ID: ::c_int = 4; + +pub const BUFSIZ: ::c_uint = 8192; +pub const TMP_MAX: ::c_uint = 238328; +pub const FOPEN_MAX: ::c_uint = 16; +pub const POSIX_FADV_DONTNEED: ::c_int = 4; +pub const POSIX_FADV_NOREUSE: ::c_int = 5; +pub const POSIX_MADV_DONTNEED: ::c_int = 4; +pub const _SC_EQUIV_CLASS_MAX: ::c_int = 41; +pub const _SC_CHARCLASS_NAME_MAX: ::c_int = 45; +pub const _SC_PII: ::c_int = 53; +pub const _SC_PII_XTI: ::c_int = 54; +pub const _SC_PII_SOCKET: ::c_int = 55; +pub const _SC_PII_INTERNET: ::c_int = 56; +pub const _SC_PII_OSI: ::c_int = 57; +pub const _SC_POLL: ::c_int = 58; +pub const _SC_SELECT: ::c_int = 59; +pub const _SC_PII_INTERNET_STREAM: ::c_int = 61; +pub const _SC_PII_INTERNET_DGRAM: ::c_int = 62; +pub const _SC_PII_OSI_COTS: ::c_int = 63; +pub const _SC_PII_OSI_CLTS: ::c_int = 64; +pub const _SC_PII_OSI_M: ::c_int = 65; +pub const _SC_T_IOV_MAX: ::c_int = 66; +pub const _SC_2_C_VERSION: ::c_int = 96; +pub const _SC_CHAR_BIT: ::c_int = 101; +pub const _SC_CHAR_MAX: ::c_int = 102; +pub const _SC_CHAR_MIN: ::c_int = 103; +pub const _SC_INT_MAX: ::c_int = 104; +pub const _SC_INT_MIN: ::c_int = 105; +pub const _SC_LONG_BIT: ::c_int = 106; +pub const _SC_WORD_BIT: ::c_int = 107; +pub const _SC_MB_LEN_MAX: ::c_int = 108; +pub const _SC_SSIZE_MAX: ::c_int = 110; +pub const _SC_SCHAR_MAX: ::c_int = 111; +pub const _SC_SCHAR_MIN: ::c_int = 112; +pub const _SC_SHRT_MAX: ::c_int = 113; +pub const _SC_SHRT_MIN: ::c_int = 114; +pub const _SC_UCHAR_MAX: ::c_int = 115; +pub const _SC_UINT_MAX: ::c_int = 116; +pub const _SC_ULONG_MAX: ::c_int = 117; +pub const _SC_USHRT_MAX: ::c_int = 118; +pub const _SC_NL_ARGMAX: ::c_int = 119; +pub const _SC_NL_LANGMAX: ::c_int = 120; +pub const _SC_NL_MSGMAX: ::c_int = 121; +pub const _SC_NL_NMAX: ::c_int = 122; +pub const _SC_NL_SETMAX: ::c_int = 123; +pub const _SC_NL_TEXTMAX: ::c_int = 124; +pub const _SC_BASE: ::c_int = 134; +pub const _SC_C_LANG_SUPPORT: ::c_int = 135; +pub const _SC_C_LANG_SUPPORT_R: ::c_int = 136; +pub const _SC_DEVICE_IO: ::c_int = 140; +pub const _SC_DEVICE_SPECIFIC: ::c_int = 141; +pub const _SC_DEVICE_SPECIFIC_R: ::c_int = 142; +pub const _SC_FD_MGMT: ::c_int = 143; +pub const _SC_FIFO: ::c_int = 144; +pub const _SC_PIPE: ::c_int = 145; +pub const _SC_FILE_ATTRIBUTES: ::c_int = 146; +pub const _SC_FILE_LOCKING: ::c_int = 147; +pub const _SC_FILE_SYSTEM: ::c_int = 148; +pub const _SC_MULTI_PROCESS: ::c_int = 150; +pub const _SC_SINGLE_PROCESS: ::c_int = 151; +pub const _SC_NETWORKING: ::c_int = 152; +pub const _SC_REGEX_VERSION: ::c_int = 156; +pub const _SC_SIGNALS: ::c_int = 158; +pub const _SC_SYSTEM_DATABASE: ::c_int = 162; +pub const _SC_SYSTEM_DATABASE_R: ::c_int = 163; +pub const _SC_USER_GROUPS: ::c_int = 166; +pub const _SC_USER_GROUPS_R: ::c_int = 167; +pub const _SC_LEVEL1_ICACHE_SIZE: ::c_int = 185; +pub const _SC_LEVEL1_ICACHE_ASSOC: ::c_int = 186; +pub const _SC_LEVEL1_ICACHE_LINESIZE: ::c_int = 187; +pub const _SC_LEVEL1_DCACHE_SIZE: ::c_int = 188; +pub const _SC_LEVEL1_DCACHE_ASSOC: ::c_int = 189; +pub const _SC_LEVEL1_DCACHE_LINESIZE: ::c_int = 190; +pub const _SC_LEVEL2_CACHE_SIZE: ::c_int = 191; +pub const _SC_LEVEL2_CACHE_ASSOC: ::c_int = 192; +pub const _SC_LEVEL2_CACHE_LINESIZE: ::c_int = 193; +pub const _SC_LEVEL3_CACHE_SIZE: ::c_int = 194; +pub const _SC_LEVEL3_CACHE_ASSOC: ::c_int = 195; +pub const _SC_LEVEL3_CACHE_LINESIZE: ::c_int = 196; +pub const _SC_LEVEL4_CACHE_SIZE: ::c_int = 197; +pub const _SC_LEVEL4_CACHE_ASSOC: ::c_int = 198; +pub const _SC_LEVEL4_CACHE_LINESIZE: ::c_int = 199; +pub const O_ACCMODE: ::c_int = 3; +pub const ST_RELATIME: ::c_ulong = 4096; +pub const NI_MAXHOST: ::socklen_t = 1025; + +pub const ADFS_SUPER_MAGIC: ::c_long = 0x0000adf5; +pub const AFFS_SUPER_MAGIC: ::c_long = 0x0000adff; +pub const CODA_SUPER_MAGIC: ::c_long = 0x73757245; +pub const CRAMFS_MAGIC: ::c_long = 0x28cd3d45; +pub const EFS_SUPER_MAGIC: ::c_long = 0x00414a53; +pub const EXT2_SUPER_MAGIC: ::c_long = 0x0000ef53; +pub const EXT3_SUPER_MAGIC: ::c_long = 0x0000ef53; +pub const EXT4_SUPER_MAGIC: ::c_long = 0x0000ef53; +pub const HPFS_SUPER_MAGIC: ::c_long = 0xf995e849; +pub const HUGETLBFS_MAGIC: ::c_long = 0x958458f6; +pub const ISOFS_SUPER_MAGIC: ::c_long = 0x00009660; +pub const JFFS2_SUPER_MAGIC: ::c_long = 0x000072b6; +pub const MINIX_SUPER_MAGIC: ::c_long = 0x0000137f; +pub const MINIX_SUPER_MAGIC2: ::c_long = 0x0000138f; +pub const MINIX2_SUPER_MAGIC: ::c_long = 0x00002468; +pub const MINIX2_SUPER_MAGIC2: ::c_long = 0x00002478; +pub const MSDOS_SUPER_MAGIC: ::c_long = 0x00004d44; +pub const NCP_SUPER_MAGIC: ::c_long = 0x0000564c; +pub const NFS_SUPER_MAGIC: ::c_long = 0x00006969; +pub const OPENPROM_SUPER_MAGIC: ::c_long = 0x00009fa1; +pub const PROC_SUPER_MAGIC: ::c_long = 0x00009fa0; +pub const QNX4_SUPER_MAGIC: ::c_long = 0x0000002f; +pub const REISERFS_SUPER_MAGIC: ::c_long = 0x52654973; +pub const SMB_SUPER_MAGIC: ::c_long = 0x0000517b; +pub const TMPFS_MAGIC: ::c_long = 0x01021994; +pub const USBDEVICE_SUPER_MAGIC: ::c_long = 0x00009fa2; + +pub const VEOF: usize = 4; + +pub const CPU_SETSIZE: ::c_int = 0x400; + +pub const PTRACE_TRACEME: ::c_uint = 0; +pub const PTRACE_PEEKTEXT: ::c_uint = 1; +pub const PTRACE_PEEKDATA: ::c_uint = 2; +pub const PTRACE_PEEKUSER: ::c_uint = 3; +pub const PTRACE_POKETEXT: ::c_uint = 4; +pub const PTRACE_POKEDATA: ::c_uint = 5; +pub const PTRACE_POKEUSER: ::c_uint = 6; +pub const PTRACE_CONT: ::c_uint = 7; +pub const PTRACE_KILL: ::c_uint = 8; +pub const PTRACE_SINGLESTEP: ::c_uint = 9; +pub const PTRACE_ATTACH: ::c_uint = 16; +pub const PTRACE_SYSCALL: ::c_uint = 24; +pub const PTRACE_SETOPTIONS: ::c_uint = 0x4200; +pub const PTRACE_GETEVENTMSG: ::c_uint = 0x4201; +pub const PTRACE_GETSIGINFO: ::c_uint = 0x4202; +pub const PTRACE_SETSIGINFO: ::c_uint = 0x4203; +pub const PTRACE_GETREGSET: ::c_uint = 0x4204; +pub const PTRACE_SETREGSET: ::c_uint = 0x4205; +pub const PTRACE_SEIZE: ::c_uint = 0x4206; +pub const PTRACE_INTERRUPT: ::c_uint = 0x4207; +pub const PTRACE_LISTEN: ::c_uint = 0x4208; +pub const PTRACE_PEEKSIGINFO: ::c_uint = 0x4209; + +pub const EPOLLWAKEUP: ::c_int = 0x20000000; + +pub const MAP_HUGETLB: ::c_int = 0x040000; + +pub const SEEK_DATA: ::c_int = 3; +pub const SEEK_HOLE: ::c_int = 4; + +pub const TCSANOW: ::c_int = 0; +pub const TCSADRAIN: ::c_int = 1; +pub const TCSAFLUSH: ::c_int = 2; + +pub const TIOCLINUX: ::c_ulong = 0x541C; +pub const TIOCGSERIAL: ::c_ulong = 0x541E; + +pub const RTLD_DEEPBIND: ::c_int = 0x8; +pub const RTLD_GLOBAL: ::c_int = 0x100; +pub const RTLD_NOLOAD: ::c_int = 0x4; + +pub const LINUX_REBOOT_MAGIC1: ::c_int = 0xfee1dead; +pub const LINUX_REBOOT_MAGIC2: ::c_int = 672274793; +pub const LINUX_REBOOT_MAGIC2A: ::c_int = 85072278; +pub const LINUX_REBOOT_MAGIC2B: ::c_int = 369367448; +pub const LINUX_REBOOT_MAGIC2C: ::c_int = 537993216; + +pub const LINUX_REBOOT_CMD_RESTART: ::c_int = 0x01234567; +pub const LINUX_REBOOT_CMD_HALT: ::c_int = 0xCDEF0123; +pub const LINUX_REBOOT_CMD_CAD_ON: ::c_int = 0x89ABCDEF; +pub const LINUX_REBOOT_CMD_CAD_OFF: ::c_int = 0x00000000; +pub const LINUX_REBOOT_CMD_POWER_OFF: ::c_int = 0x4321FEDC; +pub const LINUX_REBOOT_CMD_RESTART2: ::c_int = 0xA1B2C3D4; +pub const LINUX_REBOOT_CMD_SW_SUSPEND: ::c_int = 0xD000FCE2; +pub const LINUX_REBOOT_CMD_KEXEC: ::c_int = 0x45584543; + +pub const NETLINK_ROUTE: ::c_int = 0; +pub const NETLINK_UNUSED: ::c_int = 1; +pub const NETLINK_USERSOCK: ::c_int = 2; +pub const NETLINK_FIREWALL: ::c_int = 3; +pub const NETLINK_SOCK_DIAG: ::c_int = 4; +pub const NETLINK_NFLOG: ::c_int = 5; +pub const NETLINK_XFRM: ::c_int = 6; +pub const NETLINK_SELINUX: ::c_int = 7; +pub const NETLINK_ISCSI: ::c_int = 8; +pub const NETLINK_AUDIT: ::c_int = 9; +pub const NETLINK_FIB_LOOKUP: ::c_int = 10; +pub const NETLINK_CONNECTOR: ::c_int = 11; +pub const NETLINK_NETFILTER: ::c_int = 12; +pub const NETLINK_IP6_FW: ::c_int = 13; +pub const NETLINK_DNRTMSG: ::c_int = 14; +pub const NETLINK_KOBJECT_UEVENT: ::c_int = 15; +pub const NETLINK_GENERIC: ::c_int = 16; +pub const NETLINK_SCSITRANSPORT: ::c_int = 18; +pub const NETLINK_ECRYPTFS: ::c_int = 19; +pub const NETLINK_RDMA: ::c_int = 20; +pub const NETLINK_CRYPTO: ::c_int = 21; +pub const NETLINK_INET_DIAG: ::c_int = NETLINK_SOCK_DIAG; + +pub const MAX_LINKS: ::c_int = 32; + +pub const NLM_F_REQUEST: ::c_int = 1; +pub const NLM_F_MULTI: ::c_int = 2; +pub const NLM_F_ACK: ::c_int = 4; +pub const NLM_F_ECHO: ::c_int = 8; +pub const NLM_F_DUMP_INTR: ::c_int = 16; +pub const NLM_F_DUMP_FILTERED: ::c_int = 32; + +pub const NLM_F_ROOT: ::c_int = 0x100; +pub const NLM_F_MATCH: ::c_int = 0x200; +pub const NLM_F_ATOMIC: ::c_int = 0x400; +pub const NLM_F_DUMP: ::c_int = NLM_F_ROOT | NLM_F_MATCH; + +pub const NLM_F_REPLACE: ::c_int = 0x100; +pub const NLM_F_EXCL: ::c_int = 0x200; +pub const NLM_F_CREATE: ::c_int = 0x400; +pub const NLM_F_APPEND: ::c_int = 0x800; + +pub const NETLINK_ADD_MEMBERSHIP: ::c_int = 1; +pub const NETLINK_DROP_MEMBERSHIP: ::c_int = 2; +pub const NETLINK_PKTINFO: ::c_int = 3; +pub const NETLINK_BROADCAST_ERROR: ::c_int = 4; +pub const NETLINK_NO_ENOBUFS: ::c_int = 5; +pub const NETLINK_RX_RING: ::c_int = 6; +pub const NETLINK_TX_RING: ::c_int = 7; +pub const NETLINK_LISTEN_ALL_NSID: ::c_int = 8; +pub const NETLINK_LIST_MEMBERSHIPS: ::c_int = 9; +pub const NETLINK_CAP_ACK: ::c_int = 10; + +pub const NLA_F_NESTED: ::c_int = 1 << 15; +pub const NLA_F_NET_BYTEORDER: ::c_int = 1 << 14; +pub const NLA_TYPE_MASK: ::c_int = !(NLA_F_NESTED | NLA_F_NET_BYTEORDER); + +pub const NLA_ALIGNTO: ::c_int = 4; + +pub const GENL_UNS_ADMIN_PERM: ::c_int = 0x10; + +pub const GENL_ID_VFS_DQUOT: ::c_int = ::NLMSG_MIN_TYPE + 1; +pub const GENL_ID_PMCRAID: ::c_int = ::NLMSG_MIN_TYPE + 2; + +pub const TIOCM_LE: ::c_int = 0x001; +pub const TIOCM_DTR: ::c_int = 0x002; +pub const TIOCM_RTS: ::c_int = 0x004; +pub const TIOCM_ST: ::c_int = 0x008; +pub const TIOCM_SR: ::c_int = 0x010; +pub const TIOCM_CTS: ::c_int = 0x020; +pub const TIOCM_CAR: ::c_int = 0x040; +pub const TIOCM_RNG: ::c_int = 0x080; +pub const TIOCM_DSR: ::c_int = 0x100; +pub const TIOCM_CD: ::c_int = TIOCM_CAR; +pub const TIOCM_RI: ::c_int = TIOCM_RNG; + +pub const NF_NETDEV_INGRESS: ::c_int = 0; +pub const NF_NETDEV_NUMHOOKS: ::c_int = 1; + +pub const NFPROTO_INET: ::c_int = 1; +pub const NFPROTO_NETDEV: ::c_int = 5; + +// linux/netfilter/nf_tables.h +cfg_if!{ + if #[cfg(any(target_arch = "arm", target_arch = "powerpc", + target_arch = "powerpc64", target_arch = "aarch64"))] { + pub const NFT_TABLE_MAXNAMELEN: ::c_int = 32; + pub const NFT_CHAIN_MAXNAMELEN: ::c_int = 32; + pub const NFT_SET_MAXNAMELEN: ::c_int = 32; + pub const NFT_OBJ_MAXNAMELEN: ::c_int = 32; + } else if #[cfg(target_arch = "sparc64")] { + pub const NFT_TABLE_MAXNAMELEN: ::c_int = 32; + pub const NFT_CHAIN_MAXNAMELEN: ::c_int = 32; + pub const NFT_SET_MAXNAMELEN: ::c_int = 32; + } else { + pub const NFT_TABLE_MAXNAMELEN: ::c_int = 256; + pub const NFT_CHAIN_MAXNAMELEN: ::c_int = 256; + pub const NFT_SET_MAXNAMELEN: ::c_int = 256; + pub const NFT_OBJ_MAXNAMELEN: ::c_int = 256; + } +} +pub const NFT_USERDATA_MAXLEN: ::c_int = 256; + +pub const NFT_REG_VERDICT: ::c_int = 0; +pub const NFT_REG_1: ::c_int = 1; +pub const NFT_REG_2: ::c_int = 2; +pub const NFT_REG_3: ::c_int = 3; +pub const NFT_REG_4: ::c_int = 4; +pub const __NFT_REG_MAX: ::c_int = 5; +pub const NFT_REG32_00: ::c_int = 8; +pub const NFT_REG32_01: ::c_int = 9; +pub const NFT_REG32_02: ::c_int = 10; +pub const NFT_REG32_03: ::c_int = 11; +pub const NFT_REG32_04: ::c_int = 12; +pub const NFT_REG32_05: ::c_int = 13; +pub const NFT_REG32_06: ::c_int = 14; +pub const NFT_REG32_07: ::c_int = 15; +pub const NFT_REG32_08: ::c_int = 16; +pub const NFT_REG32_09: ::c_int = 17; +pub const NFT_REG32_10: ::c_int = 18; +pub const NFT_REG32_11: ::c_int = 19; +pub const NFT_REG32_12: ::c_int = 20; +pub const NFT_REG32_13: ::c_int = 21; +pub const NFT_REG32_14: ::c_int = 22; +pub const NFT_REG32_15: ::c_int = 23; + +pub const NFT_REG_SIZE: ::c_int = 16; +pub const NFT_REG32_SIZE: ::c_int = 4; + +pub const NFT_CONTINUE: ::c_int = -1; +pub const NFT_BREAK: ::c_int = -2; +pub const NFT_JUMP: ::c_int = -3; +pub const NFT_GOTO: ::c_int = -4; +pub const NFT_RETURN: ::c_int = -5; + +pub const NFT_MSG_NEWTABLE: ::c_int = 0; +pub const NFT_MSG_GETTABLE: ::c_int = 1; +pub const NFT_MSG_DELTABLE: ::c_int = 2; +pub const NFT_MSG_NEWCHAIN: ::c_int = 3; +pub const NFT_MSG_GETCHAIN: ::c_int = 4; +pub const NFT_MSG_DELCHAIN: ::c_int = 5; +pub const NFT_MSG_NEWRULE: ::c_int = 6; +pub const NFT_MSG_GETRULE: ::c_int = 7; +pub const NFT_MSG_DELRULE: ::c_int = 8; +pub const NFT_MSG_NEWSET: ::c_int = 9; +pub const NFT_MSG_GETSET: ::c_int = 10; +pub const NFT_MSG_DELSET: ::c_int = 11; +pub const NFT_MSG_NEWSETELEM: ::c_int = 12; +pub const NFT_MSG_GETSETELEM: ::c_int = 13; +pub const NFT_MSG_DELSETELEM: ::c_int = 14; +pub const NFT_MSG_NEWGEN: ::c_int = 15; +pub const NFT_MSG_GETGEN: ::c_int = 16; +pub const NFT_MSG_TRACE: ::c_int = 17; +cfg_if! { + if #[cfg(not(target_arch = "sparc64"))] { + pub const NFT_MSG_NEWOBJ: ::c_int = 18; + pub const NFT_MSG_GETOBJ: ::c_int = 19; + pub const NFT_MSG_DELOBJ: ::c_int = 20; + pub const NFT_MSG_GETOBJ_RESET: ::c_int = 21; + pub const NFT_MSG_MAX: ::c_int = 22; + } else { + pub const NFT_MSG_MAX: ::c_int = 18; + } +} + +pub const NFT_SET_ANONYMOUS: ::c_int = 0x1; +pub const NFT_SET_CONSTANT: ::c_int = 0x2; +pub const NFT_SET_INTERVAL: ::c_int = 0x4; +pub const NFT_SET_MAP: ::c_int = 0x8; +pub const NFT_SET_TIMEOUT: ::c_int = 0x10; +pub const NFT_SET_EVAL: ::c_int = 0x20; + +pub const NFT_SET_POL_PERFORMANCE: ::c_int = 0; +pub const NFT_SET_POL_MEMORY: ::c_int = 1; + +pub const NFT_SET_ELEM_INTERVAL_END: ::c_int = 0x1; + +pub const NFT_DATA_VALUE: ::c_uint = 0; +pub const NFT_DATA_VERDICT: ::c_uint = 0xffffff00; + +pub const NFT_DATA_RESERVED_MASK: ::c_uint = 0xffffff00; + +pub const NFT_DATA_VALUE_MAXLEN: ::c_int = 64; + +pub const NFT_BYTEORDER_NTOH: ::c_int = 0; +pub const NFT_BYTEORDER_HTON: ::c_int = 1; + +pub const NFT_CMP_EQ: ::c_int = 0; +pub const NFT_CMP_NEQ: ::c_int = 1; +pub const NFT_CMP_LT: ::c_int = 2; +pub const NFT_CMP_LTE: ::c_int = 3; +pub const NFT_CMP_GT: ::c_int = 4; +pub const NFT_CMP_GTE: ::c_int = 5; + +pub const NFT_RANGE_EQ: ::c_int = 0; +pub const NFT_RANGE_NEQ: ::c_int = 1; + +pub const NFT_LOOKUP_F_INV: ::c_int = (1 << 0); + +pub const NFT_DYNSET_OP_ADD: ::c_int = 0; +pub const NFT_DYNSET_OP_UPDATE: ::c_int = 1; + +pub const NFT_DYNSET_F_INV: ::c_int = (1 << 0); + +pub const NFT_PAYLOAD_LL_HEADER: ::c_int = 0; +pub const NFT_PAYLOAD_NETWORK_HEADER: ::c_int = 1; +pub const NFT_PAYLOAD_TRANSPORT_HEADER: ::c_int = 2; + +pub const NFT_PAYLOAD_CSUM_NONE: ::c_int = 0; +pub const NFT_PAYLOAD_CSUM_INET: ::c_int = 1; + +pub const NFT_META_LEN: ::c_int = 0; +pub const NFT_META_PROTOCOL: ::c_int = 1; +pub const NFT_META_PRIORITY: ::c_int = 2; +pub const NFT_META_MARK: ::c_int = 3; +pub const NFT_META_IIF: ::c_int = 4; +pub const NFT_META_OIF: ::c_int = 5; +pub const NFT_META_IIFNAME: ::c_int = 6; +pub const NFT_META_OIFNAME: ::c_int = 7; +pub const NFT_META_IIFTYPE: ::c_int = 8; +pub const NFT_META_OIFTYPE: ::c_int = 9; +pub const NFT_META_SKUID: ::c_int = 10; +pub const NFT_META_SKGID: ::c_int = 11; +pub const NFT_META_NFTRACE: ::c_int = 12; +pub const NFT_META_RTCLASSID: ::c_int = 13; +pub const NFT_META_SECMARK: ::c_int = 14; +pub const NFT_META_NFPROTO: ::c_int = 15; +pub const NFT_META_L4PROTO: ::c_int = 16; +pub const NFT_META_BRI_IIFNAME: ::c_int = 17; +pub const NFT_META_BRI_OIFNAME: ::c_int = 18; +pub const NFT_META_PKTTYPE: ::c_int = 19; +pub const NFT_META_CPU: ::c_int = 20; +pub const NFT_META_IIFGROUP: ::c_int = 21; +pub const NFT_META_OIFGROUP: ::c_int = 22; +pub const NFT_META_CGROUP: ::c_int = 23; +pub const NFT_META_PRANDOM: ::c_int = 24; + +pub const NFT_CT_STATE: ::c_int = 0; +pub const NFT_CT_DIRECTION: ::c_int = 1; +pub const NFT_CT_STATUS: ::c_int = 2; +pub const NFT_CT_MARK: ::c_int = 3; +pub const NFT_CT_SECMARK: ::c_int = 4; +pub const NFT_CT_EXPIRATION: ::c_int = 5; +pub const NFT_CT_HELPER: ::c_int = 6; +pub const NFT_CT_L3PROTOCOL: ::c_int = 7; +pub const NFT_CT_SRC: ::c_int = 8; +pub const NFT_CT_DST: ::c_int = 9; +pub const NFT_CT_PROTOCOL: ::c_int = 10; +pub const NFT_CT_PROTO_SRC: ::c_int = 11; +pub const NFT_CT_PROTO_DST: ::c_int = 12; +pub const NFT_CT_LABELS: ::c_int = 13; +pub const NFT_CT_PKTS: ::c_int = 14; +pub const NFT_CT_BYTES: ::c_int = 15; + +pub const NFT_LIMIT_PKTS: ::c_int = 0; +pub const NFT_LIMIT_PKT_BYTES: ::c_int = 1; + +pub const NFT_LIMIT_F_INV: ::c_int = (1 << 0); + +pub const NFT_QUEUE_FLAG_BYPASS: ::c_int = 0x01; +pub const NFT_QUEUE_FLAG_CPU_FANOUT: ::c_int = 0x02; +pub const NFT_QUEUE_FLAG_MASK: ::c_int = 0x03; + +pub const NFT_QUOTA_F_INV: ::c_int = (1 << 0); + +pub const NFT_REJECT_ICMP_UNREACH: ::c_int = 0; +pub const NFT_REJECT_TCP_RST: ::c_int = 1; +pub const NFT_REJECT_ICMPX_UNREACH: ::c_int = 2; + +pub const NFT_REJECT_ICMPX_NO_ROUTE: ::c_int = 0; +pub const NFT_REJECT_ICMPX_PORT_UNREACH: ::c_int = 1; +pub const NFT_REJECT_ICMPX_HOST_UNREACH: ::c_int = 2; +pub const NFT_REJECT_ICMPX_ADMIN_PROHIBITED: ::c_int = 3; + +pub const NFT_NAT_SNAT: ::c_int = 0; +pub const NFT_NAT_DNAT: ::c_int = 1; + +pub const NFT_TRACETYPE_UNSPEC: ::c_int = 0; +pub const NFT_TRACETYPE_POLICY: ::c_int = 1; +pub const NFT_TRACETYPE_RETURN: ::c_int = 2; +pub const NFT_TRACETYPE_RULE: ::c_int = 3; + +pub const NFT_NG_INCREMENTAL: ::c_int = 0; +pub const NFT_NG_RANDOM: ::c_int = 1; + +#[doc(hidden)] +pub const AF_MAX: ::c_int = 42; +#[doc(hidden)] +pub const PF_MAX: ::c_int = AF_MAX; + +cfg_if! { + if #[cfg(any(target_arch = "arm", target_arch = "x86", + target_arch = "x86_64"))] { + pub const PTHREAD_STACK_MIN: ::size_t = 16384; + } else if #[cfg(target_arch = "sparc64")] { + pub const PTHREAD_STACK_MIN: ::size_t = 0x6000; + } else { + pub const PTHREAD_STACK_MIN: ::size_t = 131072; + } +} + +f! { + pub fn NLA_ALIGN(len: ::c_int) -> ::c_int { + return ((len) + NLA_ALIGNTO - 1) & !(NLA_ALIGNTO - 1) + } +} + +extern { + pub fn utmpxname(file: *const ::c_char) -> ::c_int; + pub fn getutxent() -> *mut utmpx; + pub fn getutxid(ut: *const utmpx) -> *mut utmpx; + pub fn getutxline(ut: *const utmpx) -> *mut utmpx; + pub fn pututxline(ut: *const utmpx) -> *mut utmpx; + pub fn setutxent(); + pub fn endutxent(); + pub fn getpt() -> ::c_int; +} + +#[link(name = "util")] +extern { + pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; + pub fn backtrace(buf: *mut *mut ::c_void, + sz: ::c_int) -> ::c_int; + pub fn glob64(pattern: *const ::c_char, + flags: ::c_int, + errfunc: ::dox::Option ::c_int>, + pglob: *mut glob64_t) -> ::c_int; + pub fn globfree64(pglob: *mut glob64_t); + pub fn ptrace(request: ::c_uint, ...) -> ::c_long; + pub fn pthread_attr_getaffinity_np(attr: *const ::pthread_attr_t, + cpusetsize: ::size_t, + cpuset: *mut ::cpu_set_t) -> ::c_int; + pub fn pthread_attr_setaffinity_np(attr: *mut ::pthread_attr_t, + cpusetsize: ::size_t, + cpuset: *const ::cpu_set_t) -> ::c_int; + pub fn getpriority(which: ::__priority_which_t, who: ::id_t) -> ::c_int; + pub fn setpriority(which: ::__priority_which_t, who: ::id_t, + prio: ::c_int) -> ::c_int; + pub fn pthread_getaffinity_np(thread: ::pthread_t, + cpusetsize: ::size_t, + cpuset: *mut ::cpu_set_t) -> ::c_int; + pub fn pthread_setaffinity_np(thread: ::pthread_t, + cpusetsize: ::size_t, + cpuset: *const ::cpu_set_t) -> ::c_int; + pub fn pthread_rwlockattr_getkind_np(attr: *const ::pthread_rwlockattr_t, + val: *mut ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_setkind_np(attr: *mut ::pthread_rwlockattr_t, + val: ::c_int) -> ::c_int; + pub fn sched_getcpu() -> ::c_int; + pub fn mallinfo() -> ::mallinfo; + pub fn malloc_usable_size(ptr: *mut ::c_void) -> ::size_t; + pub fn getauxval(type_: ::c_ulong) -> ::c_ulong; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwent_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwent_r")] + pub fn getpwent_r(pwd: *mut ::unix::notbsd::linux::passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::unix::notbsd + ::linux::passwd) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getgrent_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrent_r")] + pub fn getgrent_r(grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; +} + +cfg_if! { + if #[cfg(any(target_arch = "x86", + target_arch = "arm", + target_arch = "powerpc"))] { + mod b32; + pub use self::b32::*; + } else if #[cfg(any(target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "powerpc64", + target_arch = "sparc64"))] { + mod b64; + pub use self::b64::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/s390x.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/s390x.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/linux/s390x.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/linux/s390x.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1286 @@ +pub type blkcnt_t = i64; +pub type blksize_t = i64; +pub type c_char = u8; +pub type c_long = i64; +pub type c_ulong = u64; +pub type fsblkcnt_t = u64; +pub type fsfilcnt_t = u64; +pub type ino_t = u64; +pub type nlink_t = u64; +pub type off_t = i64; +pub type rlim_t = u64; +pub type suseconds_t = i64; +pub type time_t = i64; +pub type wchar_t = i32; +pub type greg_t = u64; +pub type clock_t = i64; +pub type shmatt_t = ::c_ulong; +pub type msgqnum_t = ::c_ulong; +pub type msglen_t = ::c_ulong; +pub type __fsword_t = ::c_long; +pub type __priority_which_t = ::c_uint; +pub type __u64 = u64; + +s! { + pub struct aiocb { + pub aio_fildes: ::c_int, + pub aio_lio_opcode: ::c_int, + pub aio_reqprio: ::c_int, + pub aio_buf: *mut ::c_void, + pub aio_nbytes: ::size_t, + pub aio_sigevent: ::sigevent, + __next_prio: *mut aiocb, + __abs_prio: ::c_int, + __policy: ::c_int, + __error_code: ::c_int, + __return_value: ::ssize_t, + pub aio_offset: off_t, + #[cfg(target_pointer_width = "32")] + __unused1: [::c_char; 4], + __glibc_reserved: [::c_char; 32] + } + + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + st_pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + __glibc_reserved: [::c_long; 3], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + pub st_ino: ::ino64_t, + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + st_pad0: ::c_int, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt64_t, + __glibc_reserved: [::c_long; 3], + } + + pub struct pthread_attr_t { + __size: [::c_ulong; 7] + } + + pub struct sigaction { + pub sa_sigaction: ::sighandler_t, + __glibc_reserved0: ::c_int, + pub sa_flags: ::c_int, + pub sa_restorer: ::dox::Option, + pub sa_mask: sigset_t, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_flags: ::c_int, + pub ss_size: ::size_t, + } + + pub struct sigset_t { + __size: [::c_ulong; 16], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_errno: ::c_int, + pub si_code: ::c_int, + _pad: ::c_int, + _pad2: [::c_long; 14], + } + + pub struct ipc_perm { + pub __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::mode_t, + pub __seq: ::c_ushort, + __pad1: ::c_ushort, + __unused1: ::c_ulong, + __unused2: ::c_ulong + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __unused4: ::c_ulong, + __unused5: ::c_ulong + } + + pub struct statfs { + pub f_type: ::c_uint, + pub f_bsize: ::c_uint, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_uint, + pub f_frsize: ::c_uint, + pub f_flags: ::c_uint, + f_spare: [::c_uint; 4], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::size_t, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::size_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::size_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; ::NCCS], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } + + pub struct termios2 { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; 19], + pub c_ispeed: ::speed_t, + pub c_ospeed: ::speed_t, + } + + pub struct sysinfo { + pub uptime: ::c_long, + pub loads: [::c_ulong; 3], + pub totalram: ::c_ulong, + pub freeram: ::c_ulong, + pub sharedram: ::c_ulong, + pub bufferram: ::c_ulong, + pub totalswap: ::c_ulong, + pub freeswap: ::c_ulong, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: ::c_ulong, + pub freehigh: ::c_ulong, + pub mem_unit: ::c_uint, + pub _f: [::c_char; 0], + } + + pub struct glob64_t { + pub gl_pathc: ::size_t, + pub gl_pathv: *mut *mut ::c_char, + pub gl_offs: ::size_t, + pub gl_flags: ::c_int, + + __unused1: *mut ::c_void, + __unused2: *mut ::c_void, + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + } + + pub struct flock { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_pid: ::pid_t, + } + + // FIXME this is actually a union + pub struct sem_t { + __size: [::c_char; 32], + __align: [::c_long; 0], + } + + pub struct __psw_t { + pub mask: u64, + pub addr: u64, + } + + // FIXME: This is actually a union. + pub struct fpreg_t { + pub d: ::c_double, + // f: ::c_float, + } + + pub struct fpregset_t { + pub fpc: u32, + __pad: u32, + pub fprs: [fpreg_t; 16], + } + + pub struct mcontext_t { + pub psw: __psw_t, + pub gregs: [u64; 16], + pub aregs: [u32; 16], + pub fpregs: fpregset_t, + } + + pub struct ucontext_t { + pub uc_flags: ::c_ulong, + pub uc_link: *mut ucontext_t, + pub uc_stack: ::stack_t, + pub uc_mcontext: mcontext_t, + pub uc_sigmask: ::sigset_t, + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_stime: ::time_t, + pub msg_rtime: ::time_t, + pub msg_ctime: ::time_t, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __glibc_reserved4: ::c_ulong, + __glibc_reserved5: ::c_ulong, + } + + pub struct statfs64 { + pub f_type: ::c_uint, + pub f_bsize: ::c_uint, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_fsid: ::fsid_t, + pub f_namelen: ::c_uint, + pub f_frsize: ::c_uint, + pub f_flags: ::c_uint, + pub f_spare: [::c_uint; 4], + } + + pub struct statvfs64 { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: u64, + pub f_bfree: u64, + pub f_bavail: u64, + pub f_files: u64, + pub f_ffree: u64, + pub f_favail: u64, + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } +} + +pub const SFD_CLOEXEC: ::c_int = 0x080000; + +pub const NCCS: usize = 32; + +pub const O_TRUNC: ::c_int = 512; +pub const O_LARGEFILE: ::c_int = 0; +pub const O_NOATIME: ::c_int = 0o1000000; +pub const O_CLOEXEC: ::c_int = 0x80000; +pub const O_PATH: ::c_int = 0o10000000; +pub const O_TMPFILE: ::c_int = 0o20000000 | O_DIRECTORY; + +pub const EBFONT: ::c_int = 59; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const EDOTDOT: ::c_int = 73; + +pub const SA_NODEFER: ::c_int = 0x40000000; +pub const SA_RESETHAND: ::c_int = 0x80000000; +pub const SA_RESTART: ::c_int = 0x10000000; +pub const SA_NOCLDSTOP: ::c_int = 0x00000001; + +pub const EPOLL_CLOEXEC: ::c_int = 0x80000; + +pub const EFD_CLOEXEC: ::c_int = 0x80000; + +pub const POSIX_FADV_DONTNEED: ::c_int = 6; +pub const POSIX_FADV_NOREUSE: ::c_int = 7; + +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; +pub const __SIZEOF_PTHREAD_RWLOCKATTR_T: usize = 8; + +pub const EADDRINUSE: ::c_int = 98; +pub const EADDRNOTAVAIL: ::c_int = 99; +pub const ECONNABORTED: ::c_int = 103; +pub const ECONNREFUSED: ::c_int = 111; +pub const ECONNRESET: ::c_int = 104; +pub const EDEADLK: ::c_int = 35; +pub const ENOSYS: ::c_int = 38; +pub const ENOTCONN: ::c_int = 107; +pub const ETIMEDOUT: ::c_int = 110; +pub const FIOCLEX: ::c_ulong = 0x5451; +pub const FIONBIO: ::c_ulong = 0x5421; +pub const MAP_ANON: ::c_int = 0x20; +pub const O_ACCMODE: ::c_int = 3; +pub const O_APPEND: ::c_int = 1024; +pub const O_CREAT: ::c_int = 64; +pub const O_EXCL: ::c_int = 128; +pub const O_NONBLOCK: ::c_int = 2048; +pub const PTHREAD_STACK_MIN: ::size_t = 16384; +pub const RLIM_INFINITY: ::rlim_t = 0xffffffffffffffff; +pub const SA_NOCLDWAIT: ::c_int = 2; +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 4; +pub const SIGBUS: ::c_int = 7; +pub const SIGSTKSZ: ::size_t = 0x2000; +pub const MINSIGSTKSZ: ::size_t = 2048; +pub const SIG_SETMASK: ::c_int = 2; +pub const SOCK_DGRAM: ::c_int = 2; +pub const SOCK_STREAM: ::c_int = 1; +pub const SOL_SOCKET: ::c_int = 1; +pub const SO_BROADCAST: ::c_int = 6; +pub const SO_ERROR: ::c_int = 4; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_REUSEADDR: ::c_int = 2; +pub const SO_SNDTIMEO: ::c_int = 21; +pub const SO_BINDTODEVICE: ::c_int = 25; +pub const SO_TIMESTAMP: ::c_int = 29; +pub const SO_MARK: ::c_int = 36; +pub const SO_PROTOCOL: ::c_int = 38; +pub const SO_DOMAIN: ::c_int = 39; +pub const SO_RXQ_OVFL: ::c_int = 40; +pub const SO_PEEK_OFF: ::c_int = 42; +pub const SO_BUSY_POLL: ::c_int = 46; + +pub const RLIMIT_RSS: ::c_int = 5; +pub const RLIMIT_NOFILE: ::c_int = 7; +pub const RLIMIT_AS: ::c_int = 9; +pub const RLIMIT_NPROC: ::c_int = 6; +pub const RLIMIT_MEMLOCK: ::c_int = 8; +pub const RLIMIT_RTTIME: ::c_int = 15; +pub const RLIMIT_NLIMITS: ::c_int = 16; + +pub const O_NOCTTY: ::c_int = 256; +pub const O_SYNC: ::c_int = 1052672; +pub const O_RSYNC: ::c_int = 1052672; +pub const O_DSYNC: ::c_int = 4096; +pub const O_FSYNC: ::c_int = 0x101000; +pub const O_DIRECT: ::c_int = 0x4000; +pub const O_DIRECTORY: ::c_int = 0x10000; +pub const O_NOFOLLOW: ::c_int = 0x20000; + +pub const SOCK_NONBLOCK: ::c_int = O_NONBLOCK; + +pub const LC_PAPER: ::c_int = 7; +pub const LC_NAME: ::c_int = 8; +pub const LC_ADDRESS: ::c_int = 9; +pub const LC_TELEPHONE: ::c_int = 10; +pub const LC_MEASUREMENT: ::c_int = 11; +pub const LC_IDENTIFICATION: ::c_int = 12; +pub const LC_PAPER_MASK: ::c_int = (1 << LC_PAPER); +pub const LC_NAME_MASK: ::c_int = (1 << LC_NAME); +pub const LC_ADDRESS_MASK: ::c_int = (1 << LC_ADDRESS); +pub const LC_TELEPHONE_MASK: ::c_int = (1 << LC_TELEPHONE); +pub const LC_MEASUREMENT_MASK: ::c_int = (1 << LC_MEASUREMENT); +pub const LC_IDENTIFICATION_MASK: ::c_int = (1 << LC_IDENTIFICATION); +pub const LC_ALL_MASK: ::c_int = ::LC_CTYPE_MASK + | ::LC_NUMERIC_MASK + | ::LC_TIME_MASK + | ::LC_COLLATE_MASK + | ::LC_MONETARY_MASK + | ::LC_MESSAGES_MASK + | LC_PAPER_MASK + | LC_NAME_MASK + | LC_ADDRESS_MASK + | LC_TELEPHONE_MASK + | LC_MEASUREMENT_MASK + | LC_IDENTIFICATION_MASK; + +pub const MAP_ANONYMOUS: ::c_int = 0x0020; +pub const MAP_GROWSDOWN: ::c_int = 0x0100; +pub const MAP_DENYWRITE: ::c_int = 0x0800; +pub const MAP_EXECUTABLE: ::c_int = 0x01000; +pub const MAP_LOCKED: ::c_int = 0x02000; +pub const MAP_NORESERVE: ::c_int = 0x04000; +pub const MAP_POPULATE: ::c_int = 0x08000; +pub const MAP_NONBLOCK: ::c_int = 0x010000; +pub const MAP_STACK: ::c_int = 0x020000; + +pub const EDEADLOCK: ::c_int = 35; +pub const ENAMETOOLONG: ::c_int = 36; +pub const ENOLCK: ::c_int = 37; +pub const ENOTEMPTY: ::c_int = 39; +pub const ELOOP: ::c_int = 40; +pub const ENOMSG: ::c_int = 42; +pub const EIDRM: ::c_int = 43; +pub const ECHRNG: ::c_int = 44; +pub const EL2NSYNC: ::c_int = 45; +pub const EL3HLT: ::c_int = 46; +pub const EL3RST: ::c_int = 47; +pub const ELNRNG: ::c_int = 48; +pub const EUNATCH: ::c_int = 49; +pub const ENOCSI: ::c_int = 50; +pub const EL2HLT: ::c_int = 51; +pub const EBADE: ::c_int = 52; +pub const EBADR: ::c_int = 53; +pub const EXFULL: ::c_int = 54; +pub const ENOANO: ::c_int = 55; +pub const EBADRQC: ::c_int = 56; +pub const EBADSLT: ::c_int = 57; +pub const EMULTIHOP: ::c_int = 72; +pub const EOVERFLOW: ::c_int = 75; +pub const ENOTUNIQ: ::c_int = 76; +pub const EBADFD: ::c_int = 77; +pub const EBADMSG: ::c_int = 74; +pub const EREMCHG: ::c_int = 78; +pub const ELIBACC: ::c_int = 79; +pub const ELIBBAD: ::c_int = 80; +pub const ELIBSCN: ::c_int = 81; +pub const ELIBMAX: ::c_int = 82; +pub const ELIBEXEC: ::c_int = 83; +pub const EILSEQ: ::c_int = 84; +pub const ERESTART: ::c_int = 85; +pub const ESTRPIPE: ::c_int = 86; +pub const EUSERS: ::c_int = 87; +pub const ENOTSOCK: ::c_int = 88; +pub const EDESTADDRREQ: ::c_int = 89; +pub const EMSGSIZE: ::c_int = 90; +pub const EPROTOTYPE: ::c_int = 91; +pub const ENOPROTOOPT: ::c_int = 92; +pub const EPROTONOSUPPORT: ::c_int = 93; +pub const ESOCKTNOSUPPORT: ::c_int = 94; +pub const EOPNOTSUPP: ::c_int = 95; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; +pub const EPFNOSUPPORT: ::c_int = 96; +pub const EAFNOSUPPORT: ::c_int = 97; +pub const ENETDOWN: ::c_int = 100; +pub const ENETUNREACH: ::c_int = 101; +pub const ENETRESET: ::c_int = 102; +pub const ENOBUFS: ::c_int = 105; +pub const EISCONN: ::c_int = 106; +pub const ESHUTDOWN: ::c_int = 108; +pub const ETOOMANYREFS: ::c_int = 109; +pub const EHOSTDOWN: ::c_int = 112; +pub const EHOSTUNREACH: ::c_int = 113; +pub const EALREADY: ::c_int = 114; +pub const EINPROGRESS: ::c_int = 115; +pub const ESTALE: ::c_int = 116; +pub const EUCLEAN: ::c_int = 117; +pub const ENOTNAM: ::c_int = 118; +pub const ENAVAIL: ::c_int = 119; +pub const EISNAM: ::c_int = 120; +pub const EREMOTEIO: ::c_int = 121; +pub const EDQUOT: ::c_int = 122; +pub const ENOMEDIUM: ::c_int = 123; +pub const EMEDIUMTYPE: ::c_int = 124; +pub const ECANCELED: ::c_int = 125; +pub const ENOKEY: ::c_int = 126; +pub const EKEYEXPIRED: ::c_int = 127; +pub const EKEYREVOKED: ::c_int = 128; +pub const EKEYREJECTED: ::c_int = 129; +pub const EOWNERDEAD: ::c_int = 130; +pub const ENOTRECOVERABLE: ::c_int = 131; +pub const EHWPOISON: ::c_int = 133; +pub const ERFKILL: ::c_int = 132; + +pub const SOCK_SEQPACKET: ::c_int = 5; + +pub const SO_TYPE: ::c_int = 3; +pub const SO_DONTROUTE: ::c_int = 5; +pub const SO_SNDBUF: ::c_int = 7; +pub const SO_RCVBUF: ::c_int = 8; +pub const SO_KEEPALIVE: ::c_int = 9; +pub const SO_OOBINLINE: ::c_int = 10; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_LINGER: ::c_int = 13; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_REUSEPORT: ::c_int = 15; +pub const SO_PASSCRED: ::c_int = 16; +pub const SO_PEERCRED: ::c_int = 17; +pub const SO_RCVLOWAT: ::c_int = 18; +pub const SO_SNDLOWAT: ::c_int = 19; +pub const SO_ACCEPTCONN: ::c_int = 30; +pub const SO_SNDBUFFORCE: ::c_int = 32; +pub const SO_RCVBUFFORCE: ::c_int = 33; + +pub const TCP_COOKIE_TRANSACTIONS: ::c_int = 15; +pub const TCP_THIN_LINEAR_TIMEOUTS: ::c_int = 16; +pub const TCP_THIN_DUPACK: ::c_int = 17; +pub const TCP_USER_TIMEOUT: ::c_int = 18; +pub const TCP_REPAIR: ::c_int = 19; +pub const TCP_REPAIR_QUEUE: ::c_int = 20; +pub const TCP_QUEUE_SEQ: ::c_int = 21; +pub const TCP_REPAIR_OPTIONS: ::c_int = 22; +pub const TCP_FASTOPEN: ::c_int = 23; +pub const TCP_TIMESTAMP: ::c_int = 24; + +pub const SIGCHLD: ::c_int = 17; +pub const SIGUSR1: ::c_int = 10; +pub const SIGUSR2: ::c_int = 12; +pub const SIGCONT: ::c_int = 18; +pub const SIGSTOP: ::c_int = 19; +pub const SIGTSTP: ::c_int = 20; +pub const SIGURG: ::c_int = 23; +pub const SIGIO: ::c_int = 29; +pub const SIGSYS: ::c_int = 31; +pub const SIGSTKFLT: ::c_int = 16; +pub const SIGUNUSED: ::c_int = 31; +pub const SIGTTIN: ::c_int = 21; +pub const SIGTTOU: ::c_int = 22; +pub const SIGXCPU: ::c_int = 24; +pub const SIGXFSZ: ::c_int = 25; +pub const SIGVTALRM: ::c_int = 26; +pub const SIGPROF: ::c_int = 27; +pub const SIGWINCH: ::c_int = 28; +pub const SIGPOLL: ::c_int = 29; +pub const SIGPWR: ::c_int = 30; +pub const SIG_BLOCK: ::c_int = 0x000000; +pub const SIG_UNBLOCK: ::c_int = 0x01; + +pub const BUFSIZ: ::c_uint = 8192; +pub const TMP_MAX: ::c_uint = 238328; +pub const FOPEN_MAX: ::c_uint = 16; +pub const POSIX_MADV_DONTNEED: ::c_int = 4; +pub const _SC_EQUIV_CLASS_MAX: ::c_int = 41; +pub const _SC_CHARCLASS_NAME_MAX: ::c_int = 45; +pub const _SC_PII: ::c_int = 53; +pub const _SC_PII_XTI: ::c_int = 54; +pub const _SC_PII_SOCKET: ::c_int = 55; +pub const _SC_PII_INTERNET: ::c_int = 56; +pub const _SC_PII_OSI: ::c_int = 57; +pub const _SC_POLL: ::c_int = 58; +pub const _SC_SELECT: ::c_int = 59; +pub const _SC_PII_INTERNET_STREAM: ::c_int = 61; +pub const _SC_PII_INTERNET_DGRAM: ::c_int = 62; +pub const _SC_PII_OSI_COTS: ::c_int = 63; +pub const _SC_PII_OSI_CLTS: ::c_int = 64; +pub const _SC_PII_OSI_M: ::c_int = 65; +pub const _SC_T_IOV_MAX: ::c_int = 66; +pub const _SC_2_C_VERSION: ::c_int = 96; +pub const _SC_CHAR_BIT: ::c_int = 101; +pub const _SC_CHAR_MAX: ::c_int = 102; +pub const _SC_CHAR_MIN: ::c_int = 103; +pub const _SC_INT_MAX: ::c_int = 104; +pub const _SC_INT_MIN: ::c_int = 105; +pub const _SC_LONG_BIT: ::c_int = 106; +pub const _SC_WORD_BIT: ::c_int = 107; +pub const _SC_MB_LEN_MAX: ::c_int = 108; +pub const _SC_SSIZE_MAX: ::c_int = 110; +pub const _SC_SCHAR_MAX: ::c_int = 111; +pub const _SC_SCHAR_MIN: ::c_int = 112; +pub const _SC_SHRT_MAX: ::c_int = 113; +pub const _SC_SHRT_MIN: ::c_int = 114; +pub const _SC_UCHAR_MAX: ::c_int = 115; +pub const _SC_UINT_MAX: ::c_int = 116; +pub const _SC_ULONG_MAX: ::c_int = 117; +pub const _SC_USHRT_MAX: ::c_int = 118; +pub const _SC_NL_ARGMAX: ::c_int = 119; +pub const _SC_NL_LANGMAX: ::c_int = 120; +pub const _SC_NL_MSGMAX: ::c_int = 121; +pub const _SC_NL_NMAX: ::c_int = 122; +pub const _SC_NL_SETMAX: ::c_int = 123; +pub const _SC_NL_TEXTMAX: ::c_int = 124; +pub const _SC_BASE: ::c_int = 134; +pub const _SC_C_LANG_SUPPORT: ::c_int = 135; +pub const _SC_C_LANG_SUPPORT_R: ::c_int = 136; +pub const _SC_DEVICE_IO: ::c_int = 140; +pub const _SC_DEVICE_SPECIFIC: ::c_int = 141; +pub const _SC_DEVICE_SPECIFIC_R: ::c_int = 142; +pub const _SC_FD_MGMT: ::c_int = 143; +pub const _SC_FIFO: ::c_int = 144; +pub const _SC_PIPE: ::c_int = 145; +pub const _SC_FILE_ATTRIBUTES: ::c_int = 146; +pub const _SC_FILE_LOCKING: ::c_int = 147; +pub const _SC_FILE_SYSTEM: ::c_int = 148; +pub const _SC_MULTI_PROCESS: ::c_int = 150; +pub const _SC_SINGLE_PROCESS: ::c_int = 151; +pub const _SC_NETWORKING: ::c_int = 152; +pub const _SC_REGEX_VERSION: ::c_int = 156; +pub const _SC_SIGNALS: ::c_int = 158; +pub const _SC_SYSTEM_DATABASE: ::c_int = 162; +pub const _SC_SYSTEM_DATABASE_R: ::c_int = 163; +pub const _SC_USER_GROUPS: ::c_int = 166; +pub const _SC_USER_GROUPS_R: ::c_int = 167; +pub const _SC_LEVEL1_ICACHE_SIZE: ::c_int = 185; +pub const _SC_LEVEL1_ICACHE_ASSOC: ::c_int = 186; +pub const _SC_LEVEL1_ICACHE_LINESIZE: ::c_int = 187; +pub const _SC_LEVEL1_DCACHE_SIZE: ::c_int = 188; +pub const _SC_LEVEL1_DCACHE_ASSOC: ::c_int = 189; +pub const _SC_LEVEL1_DCACHE_LINESIZE: ::c_int = 190; +pub const _SC_LEVEL2_CACHE_SIZE: ::c_int = 191; +pub const _SC_LEVEL2_CACHE_ASSOC: ::c_int = 192; +pub const _SC_LEVEL2_CACHE_LINESIZE: ::c_int = 193; +pub const _SC_LEVEL3_CACHE_SIZE: ::c_int = 194; +pub const _SC_LEVEL3_CACHE_ASSOC: ::c_int = 195; +pub const _SC_LEVEL3_CACHE_LINESIZE: ::c_int = 196; +pub const _SC_LEVEL4_CACHE_SIZE: ::c_int = 197; +pub const _SC_LEVEL4_CACHE_ASSOC: ::c_int = 198; +pub const _SC_LEVEL4_CACHE_LINESIZE: ::c_int = 199; +pub const O_ASYNC: ::c_int = 0x2000; +pub const O_NDELAY: ::c_int = 0x800; +pub const ST_RELATIME: ::c_ulong = 4096; +pub const NI_MAXHOST: ::socklen_t = 1025; + +pub const ADFS_SUPER_MAGIC: ::c_int = 0x0000adf5; +pub const AFFS_SUPER_MAGIC: ::c_int = 0x0000adff; +pub const CODA_SUPER_MAGIC: ::c_int = 0x73757245; +pub const CRAMFS_MAGIC: ::c_int = 0x28cd3d45; +pub const EFS_SUPER_MAGIC: ::c_int = 0x00414a53; +pub const EXT2_SUPER_MAGIC: ::c_int = 0x0000ef53; +pub const EXT3_SUPER_MAGIC: ::c_int = 0x0000ef53; +pub const EXT4_SUPER_MAGIC: ::c_int = 0x0000ef53; +pub const HPFS_SUPER_MAGIC: ::c_int = 0xf995e849; +pub const HUGETLBFS_MAGIC: ::c_int = 0x958458f6; +pub const ISOFS_SUPER_MAGIC: ::c_int = 0x00009660; +pub const JFFS2_SUPER_MAGIC: ::c_int = 0x000072b6; +pub const MINIX_SUPER_MAGIC: ::c_int = 0x0000137f; +pub const MINIX_SUPER_MAGIC2: ::c_int = 0x0000138f; +pub const MINIX2_SUPER_MAGIC: ::c_int = 0x00002468; +pub const MINIX2_SUPER_MAGIC2: ::c_int = 0x00002478; +pub const MSDOS_SUPER_MAGIC: ::c_int = 0x00004d44; +pub const NCP_SUPER_MAGIC: ::c_int = 0x0000564c; +pub const NFS_SUPER_MAGIC: ::c_int = 0x00006969; +pub const OPENPROM_SUPER_MAGIC: ::c_int = 0x00009fa1; +pub const PROC_SUPER_MAGIC: ::c_int = 0x00009fa0; +pub const QNX4_SUPER_MAGIC: ::c_int = 0x0000002f; +pub const REISERFS_SUPER_MAGIC: ::c_int = 0x52654973; +pub const SMB_SUPER_MAGIC: ::c_int = 0x0000517b; +pub const TMPFS_MAGIC: ::c_int = 0x01021994; +pub const USBDEVICE_SUPER_MAGIC: ::c_int = 0x00009fa2; + +pub const VEOF: usize = 4; +pub const VEOL: usize = 11; +pub const VEOL2: usize = 16; +pub const VMIN: usize = 6; +pub const IEXTEN: ::tcflag_t = 0x00008000; +pub const TOSTOP: ::tcflag_t = 0x00000100; +pub const FLUSHO: ::tcflag_t = 0x00001000; + +pub const CPU_SETSIZE: ::c_int = 0x400; + +pub const EXTPROC: ::tcflag_t = 0x00010000; + +pub const PTRACE_TRACEME: ::c_uint = 0; +pub const PTRACE_PEEKTEXT: ::c_uint = 1; +pub const PTRACE_PEEKDATA: ::c_uint = 2; +pub const PTRACE_PEEKUSER: ::c_uint = 3; +pub const PTRACE_POKETEXT: ::c_uint = 4; +pub const PTRACE_POKEDATA: ::c_uint = 5; +pub const PTRACE_POKEUSER: ::c_uint = 6; +pub const PTRACE_CONT: ::c_uint = 7; +pub const PTRACE_KILL: ::c_uint = 8; +pub const PTRACE_SINGLESTEP: ::c_uint = 9; +pub const PTRACE_GETREGS: ::c_uint = 12; +pub const PTRACE_SETREGS: ::c_uint = 13; +pub const PTRACE_GETFPREGS: ::c_uint = 14; +pub const PTRACE_SETFPREGS: ::c_uint = 15; +pub const PTRACE_ATTACH: ::c_uint = 16; +pub const PTRACE_DETACH: ::c_uint = 17; +pub const PTRACE_SYSCALL: ::c_uint = 24; +pub const PTRACE_SETOPTIONS: ::c_uint = 0x4200; +pub const PTRACE_GETEVENTMSG: ::c_uint = 0x4201; +pub const PTRACE_GETSIGINFO: ::c_uint = 0x4202; +pub const PTRACE_SETSIGINFO: ::c_uint = 0x4203; +pub const PTRACE_GETREGSET: ::c_uint = 0x4204; +pub const PTRACE_SETREGSET: ::c_uint = 0x4205; +pub const PTRACE_SEIZE: ::c_uint = 0x4206; +pub const PTRACE_INTERRUPT: ::c_uint = 0x4207; +pub const PTRACE_LISTEN: ::c_uint = 0x4208; +pub const PTRACE_PEEKSIGINFO: ::c_uint = 0x4209; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const EPOLLWAKEUP: ::c_int = 0x20000000; + +pub const MAP_HUGETLB: ::c_int = 0x040000; + +pub const EFD_NONBLOCK: ::c_int = 0x800; + +pub const F_GETLK: ::c_int = 5; +pub const F_GETOWN: ::c_int = 9; +pub const F_SETOWN: ::c_int = 8; +pub const F_SETLK: ::c_int = 6; +pub const F_SETLKW: ::c_int = 7; + +pub const SEEK_DATA: ::c_int = 3; +pub const SEEK_HOLE: ::c_int = 4; + +pub const SFD_NONBLOCK: ::c_int = 0x0800; + +pub const TCSANOW: ::c_int = 0; +pub const TCSADRAIN: ::c_int = 1; +pub const TCSAFLUSH: ::c_int = 2; + +pub const TCGETS: ::c_ulong = 0x5401; +pub const TCSETS: ::c_ulong = 0x5402; +pub const TCSETSW: ::c_ulong = 0x5403; +pub const TCSETSF: ::c_ulong = 0x5404; +pub const TCGETA: ::c_ulong = 0x5405; +pub const TCSETA: ::c_ulong = 0x5406; +pub const TCSETAW: ::c_ulong = 0x5407; +pub const TCSETAF: ::c_ulong = 0x5408; +pub const TCSBRK: ::c_ulong = 0x5409; +pub const TCXONC: ::c_ulong = 0x540A; +pub const TCFLSH: ::c_ulong = 0x540B; +pub const TIOCGSOFTCAR: ::c_ulong = 0x5419; +pub const TIOCSSOFTCAR: ::c_ulong = 0x541A; +pub const TIOCINQ: ::c_ulong = 0x541B; +pub const TIOCLINUX: ::c_ulong = 0x541C; +pub const TIOCGSERIAL: ::c_ulong = 0x541E; +pub const TIOCEXCL: ::c_ulong = 0x540C; +pub const TIOCNXCL: ::c_ulong = 0x540D; +pub const TIOCSCTTY: ::c_ulong = 0x540E; +pub const TIOCGPGRP: ::c_ulong = 0x540F; +pub const TIOCSPGRP: ::c_ulong = 0x5410; +pub const TIOCOUTQ: ::c_ulong = 0x5411; +pub const TIOCSTI: ::c_ulong = 0x5412; +pub const TIOCGWINSZ: ::c_ulong = 0x5413; +pub const TIOCSWINSZ: ::c_ulong = 0x5414; +pub const TIOCMGET: ::c_ulong = 0x5415; +pub const TIOCMBIS: ::c_ulong = 0x5416; +pub const TIOCMBIC: ::c_ulong = 0x5417; +pub const TIOCMSET: ::c_ulong = 0x5418; +pub const FIONREAD: ::c_ulong = 0x541B; +pub const TIOCCONS: ::c_ulong = 0x541D; + +pub const RTLD_DEEPBIND: ::c_int = 0x8; +pub const RTLD_GLOBAL: ::c_int = 0x100; +pub const RTLD_NOLOAD: ::c_int = 0x4; + +pub const LINUX_REBOOT_MAGIC1: ::c_int = 0xfee1dead; +pub const LINUX_REBOOT_MAGIC2: ::c_int = 672274793; +pub const LINUX_REBOOT_MAGIC2A: ::c_int = 85072278; +pub const LINUX_REBOOT_MAGIC2B: ::c_int = 369367448; +pub const LINUX_REBOOT_MAGIC2C: ::c_int = 537993216; + +pub const LINUX_REBOOT_CMD_RESTART: ::c_int = 0x01234567; +pub const LINUX_REBOOT_CMD_HALT: ::c_int = 0xCDEF0123; +pub const LINUX_REBOOT_CMD_CAD_ON: ::c_int = 0x89ABCDEF; +pub const LINUX_REBOOT_CMD_CAD_OFF: ::c_int = 0x00000000; +pub const LINUX_REBOOT_CMD_POWER_OFF: ::c_int = 0x4321FEDC; +pub const LINUX_REBOOT_CMD_RESTART2: ::c_int = 0xA1B2C3D4; +pub const LINUX_REBOOT_CMD_SW_SUSPEND: ::c_int = 0xD000FCE2; +pub const LINUX_REBOOT_CMD_KEXEC: ::c_int = 0x45584543; + +pub const VTIME: usize = 5; +pub const VSWTC: usize = 7; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VSUSP: usize = 10; +pub const VREPRINT: usize = 12; +pub const VDISCARD: usize = 13; +pub const VWERASE: usize = 14; +pub const OLCUC: ::tcflag_t = 0o000002; +pub const ONLCR: ::tcflag_t = 0o000004; +pub const NLDLY: ::tcflag_t = 0o000400; +pub const CRDLY: ::tcflag_t = 0o003000; +pub const CR1: ::tcflag_t = 0x00000200; +pub const CR2: ::tcflag_t = 0x00000400; +pub const CR3: ::tcflag_t = 0x00000600; +pub const TABDLY: ::tcflag_t = 0o014000; +pub const TAB1: ::tcflag_t = 0x00000800; +pub const TAB2: ::tcflag_t = 0x00001000; +pub const TAB3: ::tcflag_t = 0x00001800; +pub const BSDLY: ::tcflag_t = 0o020000; +pub const BS1: ::tcflag_t = 0x00002000; +pub const FFDLY: ::tcflag_t = 0o100000; +pub const FF1: ::tcflag_t = 0x00008000; +pub const VTDLY: ::tcflag_t = 0o040000; +pub const VT1: ::tcflag_t = 0x00004000; +pub const XTABS: ::tcflag_t = 0o014000; + +pub const TIOCM_LE: ::c_int = 0x001; +pub const TIOCM_DTR: ::c_int = 0x002; +pub const TIOCM_RTS: ::c_int = 0x004; +pub const TIOCM_ST: ::c_int = 0x008; +pub const TIOCM_SR: ::c_int = 0x010; +pub const TIOCM_CTS: ::c_int = 0x020; +pub const TIOCM_CAR: ::c_int = 0x040; +pub const TIOCM_RNG: ::c_int = 0x080; +pub const TIOCM_DSR: ::c_int = 0x100; +pub const TIOCM_CD: ::c_int = TIOCM_CAR; +pub const TIOCM_RI: ::c_int = TIOCM_RNG; + +pub const SIGEV_THREAD_ID: ::c_int = 4; + +pub const CBAUD: ::speed_t = 0o010017; +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const CSIZE: ::tcflag_t = 0o000060; +pub const CS6: ::tcflag_t = 0o000020; +pub const CS7: ::tcflag_t = 0o000040; +pub const CS8: ::tcflag_t = 0o000060; +pub const CSTOPB: ::tcflag_t = 0o000100; +pub const CREAD: ::tcflag_t = 0o000200; +pub const PARENB: ::tcflag_t = 0o000400; +pub const PARODD: ::tcflag_t = 0o001000; +pub const HUPCL: ::tcflag_t = 0o002000; +pub const CLOCAL: ::tcflag_t = 0o004000; +pub const CBAUDEX: ::tcflag_t = 0o010000; +pub const BOTHER: ::speed_t = 0o010000; +pub const B57600: ::speed_t = 0o010001; +pub const B115200: ::speed_t = 0o010002; +pub const B230400: ::speed_t = 0o010003; +pub const B460800: ::speed_t = 0o010004; +pub const B500000: ::speed_t = 0o010005; +pub const B576000: ::speed_t = 0o010006; +pub const B921600: ::speed_t = 0o010007; +pub const B1000000: ::speed_t = 0o010010; +pub const B1152000: ::speed_t = 0o010011; +pub const B1500000: ::speed_t = 0o010012; +pub const B2000000: ::speed_t = 0o010013; +pub const B2500000: ::speed_t = 0o010014; +pub const B3000000: ::speed_t = 0o010015; +pub const B3500000: ::speed_t = 0o010016; +pub const B4000000: ::speed_t = 0o010017; +pub const CIBAUD: ::tcflag_t = 0o02003600000; + +pub const ISIG: ::tcflag_t = 0o000001; +pub const ICANON: ::tcflag_t = 0o000002; +pub const XCASE: ::tcflag_t = 0o000004; +pub const ECHOE: ::tcflag_t = 0o000020; +pub const ECHOK: ::tcflag_t = 0o000040; +pub const ECHONL: ::tcflag_t = 0o000100; +pub const NOFLSH: ::tcflag_t = 0o000200; +pub const ECHOCTL: ::tcflag_t = 0o001000; +pub const ECHOPRT: ::tcflag_t = 0o002000; +pub const ECHOKE: ::tcflag_t = 0o004000; +pub const PENDIN: ::tcflag_t = 0o040000; + +pub const POLLWRNORM: ::c_short = 0x100; +pub const POLLWRBAND: ::c_short = 0x200; + +pub const IXON: ::tcflag_t = 0o002000; +pub const IXOFF: ::tcflag_t = 0o010000; + +pub const SYS_exit: ::c_long = 1; +pub const SYS_fork: ::c_long = 2; +pub const SYS_read: ::c_long = 3; +pub const SYS_write: ::c_long = 4; +pub const SYS_open: ::c_long = 5; +pub const SYS_close: ::c_long = 6; +pub const SYS_restart_syscall: ::c_long = 7; +pub const SYS_creat: ::c_long = 8; +pub const SYS_link: ::c_long = 9; +pub const SYS_unlink: ::c_long = 10; +pub const SYS_execve: ::c_long = 11; +pub const SYS_chdir: ::c_long = 12; +pub const SYS_mknod: ::c_long = 14; +pub const SYS_chmod: ::c_long = 15; +pub const SYS_lseek: ::c_long = 19; +pub const SYS_getpid: ::c_long = 20; +pub const SYS_mount: ::c_long = 21; +pub const SYS_umount: ::c_long = 22; +pub const SYS_ptrace: ::c_long = 26; +pub const SYS_alarm: ::c_long = 27; +pub const SYS_pause: ::c_long = 29; +pub const SYS_utime: ::c_long = 30; +pub const SYS_access: ::c_long = 33; +pub const SYS_nice: ::c_long = 34; +pub const SYS_sync: ::c_long = 36; +pub const SYS_kill: ::c_long = 37; +pub const SYS_rename: ::c_long = 38; +pub const SYS_mkdir: ::c_long = 39; +pub const SYS_rmdir: ::c_long = 40; +pub const SYS_dup: ::c_long = 41; +pub const SYS_pipe: ::c_long = 42; +pub const SYS_times: ::c_long = 43; +pub const SYS_brk: ::c_long = 45; +pub const SYS_signal: ::c_long = 48; +pub const SYS_acct: ::c_long = 51; +pub const SYS_umount2: ::c_long = 52; +pub const SYS_ioctl: ::c_long = 54; +pub const SYS_fcntl: ::c_long = 55; +pub const SYS_setpgid: ::c_long = 57; +pub const SYS_umask: ::c_long = 60; +pub const SYS_chroot: ::c_long = 61; +pub const SYS_ustat: ::c_long = 62; +pub const SYS_dup2: ::c_long = 63; +pub const SYS_getppid: ::c_long = 64; +pub const SYS_getpgrp: ::c_long = 65; +pub const SYS_setsid: ::c_long = 66; +pub const SYS_sigaction: ::c_long = 67; +pub const SYS_sigsuspend: ::c_long = 72; +pub const SYS_sigpending: ::c_long = 73; +pub const SYS_sethostname: ::c_long = 74; +pub const SYS_setrlimit: ::c_long = 75; +pub const SYS_getrusage: ::c_long = 77; +pub const SYS_gettimeofday: ::c_long = 78; +pub const SYS_settimeofday: ::c_long = 79; +pub const SYS_symlink: ::c_long = 83; +pub const SYS_readlink: ::c_long = 85; +pub const SYS_uselib: ::c_long = 86; +pub const SYS_swapon: ::c_long = 87; +pub const SYS_reboot: ::c_long = 88; +pub const SYS_readdir: ::c_long = 89; +pub const SYS_mmap: ::c_long = 90; +pub const SYS_munmap: ::c_long = 91; +pub const SYS_truncate: ::c_long = 92; +pub const SYS_ftruncate: ::c_long = 93; +pub const SYS_fchmod: ::c_long = 94; +pub const SYS_getpriority: ::c_long = 96; +pub const SYS_setpriority: ::c_long = 97; +pub const SYS_statfs: ::c_long = 99; +pub const SYS_fstatfs: ::c_long = 100; +pub const SYS_socketcall: ::c_long = 102; +pub const SYS_syslog: ::c_long = 103; +pub const SYS_setitimer: ::c_long = 104; +pub const SYS_getitimer: ::c_long = 105; +pub const SYS_stat: ::c_long = 106; +pub const SYS_lstat: ::c_long = 107; +pub const SYS_fstat: ::c_long = 108; +pub const SYS_lookup_dcookie: ::c_long = 110; +pub const SYS_vhangup: ::c_long = 111; +pub const SYS_idle: ::c_long = 112; +pub const SYS_wait4: ::c_long = 114; +pub const SYS_swapoff: ::c_long = 115; +pub const SYS_sysinfo: ::c_long = 116; +pub const SYS_ipc: ::c_long = 117; +pub const SYS_fsync: ::c_long = 118; +pub const SYS_sigreturn: ::c_long = 119; +pub const SYS_clone: ::c_long = 120; +pub const SYS_setdomainname: ::c_long = 121; +pub const SYS_uname: ::c_long = 122; +pub const SYS_adjtimex: ::c_long = 124; +pub const SYS_mprotect: ::c_long = 125; +pub const SYS_sigprocmask: ::c_long = 126; +pub const SYS_create_module: ::c_long = 127; +pub const SYS_init_module: ::c_long = 128; +pub const SYS_delete_module: ::c_long = 129; +pub const SYS_get_kernel_syms: ::c_long = 130; +pub const SYS_quotactl: ::c_long = 131; +pub const SYS_getpgid: ::c_long = 132; +pub const SYS_fchdir: ::c_long = 133; +pub const SYS_bdflush: ::c_long = 134; +pub const SYS_sysfs: ::c_long = 135; +pub const SYS_personality: ::c_long = 136; +pub const SYS_afs_syscall: ::c_long = 137; /* Syscall for Andrew File System */ +pub const SYS_getdents: ::c_long = 141; +pub const SYS_flock: ::c_long = 143; +pub const SYS_msync: ::c_long = 144; +pub const SYS_readv: ::c_long = 145; +pub const SYS_writev: ::c_long = 146; +pub const SYS_getsid: ::c_long = 147; +pub const SYS_fdatasync: ::c_long = 148; +pub const SYS__sysctl: ::c_long = 149; +pub const SYS_mlock: ::c_long = 150; +pub const SYS_munlock: ::c_long = 151; +pub const SYS_mlockall: ::c_long = 152; +pub const SYS_munlockall: ::c_long = 153; +pub const SYS_sched_setparam: ::c_long = 154; +pub const SYS_sched_getparam: ::c_long = 155; +pub const SYS_sched_setscheduler: ::c_long = 156; +pub const SYS_sched_getscheduler: ::c_long = 157; +pub const SYS_sched_yield: ::c_long = 158; +pub const SYS_sched_get_priority_max: ::c_long = 159; +pub const SYS_sched_get_priority_min: ::c_long = 160; +pub const SYS_sched_rr_get_interval: ::c_long = 161; +pub const SYS_nanosleep: ::c_long = 162; +pub const SYS_mremap: ::c_long = 163; +pub const SYS_query_module: ::c_long = 167; +pub const SYS_poll: ::c_long = 168; +pub const SYS_nfsservctl: ::c_long = 169; +pub const SYS_prctl: ::c_long = 172; +pub const SYS_rt_sigreturn: ::c_long = 173; +pub const SYS_rt_sigaction: ::c_long = 174; +pub const SYS_rt_sigprocmask: ::c_long = 175; +pub const SYS_rt_sigpending: ::c_long = 176; +pub const SYS_rt_sigtimedwait: ::c_long = 177; +pub const SYS_rt_sigqueueinfo: ::c_long = 178; +pub const SYS_rt_sigsuspend: ::c_long = 179; +pub const SYS_pread64: ::c_long = 180; +pub const SYS_pwrite64: ::c_long = 181; +pub const SYS_getcwd: ::c_long = 183; +pub const SYS_capget: ::c_long = 184; +pub const SYS_capset: ::c_long = 185; +pub const SYS_sigaltstack: ::c_long = 186; +pub const SYS_sendfile: ::c_long = 187; +pub const SYS_getpmsg: ::c_long = 188; +pub const SYS_putpmsg: ::c_long = 189; +pub const SYS_vfork: ::c_long = 190; +pub const SYS_pivot_root: ::c_long = 217; +pub const SYS_mincore: ::c_long = 218; +pub const SYS_madvise: ::c_long = 219; +pub const SYS_getdents64: ::c_long = 220; +pub const SYS_readahead: ::c_long = 222; +pub const SYS_setxattr: ::c_long = 224; +pub const SYS_lsetxattr: ::c_long = 225; +pub const SYS_fsetxattr: ::c_long = 226; +pub const SYS_getxattr: ::c_long = 227; +pub const SYS_lgetxattr: ::c_long = 228; +pub const SYS_fgetxattr: ::c_long = 229; +pub const SYS_listxattr: ::c_long = 230; +pub const SYS_llistxattr: ::c_long = 231; +pub const SYS_flistxattr: ::c_long = 232; +pub const SYS_removexattr: ::c_long = 233; +pub const SYS_lremovexattr: ::c_long = 234; +pub const SYS_fremovexattr: ::c_long = 235; +pub const SYS_gettid: ::c_long = 236; +pub const SYS_tkill: ::c_long = 237; +pub const SYS_futex: ::c_long = 238; +pub const SYS_sched_setaffinity: ::c_long = 239; +pub const SYS_sched_getaffinity: ::c_long = 240; +pub const SYS_tgkill: ::c_long = 241; +pub const SYS_io_setup: ::c_long = 243; +pub const SYS_io_destroy: ::c_long = 244; +pub const SYS_io_getevents: ::c_long = 245; +pub const SYS_io_submit: ::c_long = 246; +pub const SYS_io_cancel: ::c_long = 247; +pub const SYS_exit_group: ::c_long = 248; +pub const SYS_epoll_create: ::c_long = 249; +pub const SYS_epoll_ctl: ::c_long = 250; +pub const SYS_epoll_wait: ::c_long = 251; +pub const SYS_set_tid_address: ::c_long = 252; +pub const SYS_fadvise64: ::c_long = 253; +pub const SYS_timer_create: ::c_long = 254; +pub const SYS_timer_settime: ::c_long = 255; +pub const SYS_timer_gettime: ::c_long = 256; +pub const SYS_timer_getoverrun: ::c_long = 257; +pub const SYS_timer_delete: ::c_long = 258; +pub const SYS_clock_settime: ::c_long = 259; +pub const SYS_clock_gettime: ::c_long = 260; +pub const SYS_clock_getres: ::c_long = 261; +pub const SYS_clock_nanosleep: ::c_long = 262; +pub const SYS_statfs64: ::c_long = 265; +pub const SYS_fstatfs64: ::c_long = 266; +pub const SYS_remap_file_pages: ::c_long = 267; +pub const SYS_mbind: ::c_long = 268; +pub const SYS_get_mempolicy: ::c_long = 269; +pub const SYS_set_mempolicy: ::c_long = 270; +pub const SYS_mq_open: ::c_long = 271; +pub const SYS_mq_unlink: ::c_long = 272; +pub const SYS_mq_timedsend: ::c_long = 273; +pub const SYS_mq_timedreceive: ::c_long = 274; +pub const SYS_mq_notify: ::c_long = 275; +pub const SYS_mq_getsetattr: ::c_long = 276; +pub const SYS_kexec_load: ::c_long = 277; +pub const SYS_add_key: ::c_long = 278; +pub const SYS_request_key: ::c_long = 279; +pub const SYS_keyctl: ::c_long = 280; +pub const SYS_waitid: ::c_long = 281; +pub const SYS_ioprio_set: ::c_long = 282; +pub const SYS_ioprio_get: ::c_long = 283; +pub const SYS_inotify_init: ::c_long = 284; +pub const SYS_inotify_add_watch: ::c_long = 285; +pub const SYS_inotify_rm_watch: ::c_long = 286; +pub const SYS_migrate_pages: ::c_long = 287; +pub const SYS_openat: ::c_long = 288; +pub const SYS_mkdirat: ::c_long = 289; +pub const SYS_mknodat: ::c_long = 290; +pub const SYS_fchownat: ::c_long = 291; +pub const SYS_futimesat: ::c_long = 292; +pub const SYS_unlinkat: ::c_long = 294; +pub const SYS_renameat: ::c_long = 295; +pub const SYS_linkat: ::c_long = 296; +pub const SYS_symlinkat: ::c_long = 297; +pub const SYS_readlinkat: ::c_long = 298; +pub const SYS_fchmodat: ::c_long = 299; +pub const SYS_faccessat: ::c_long = 300; +pub const SYS_pselect6: ::c_long = 301; +pub const SYS_ppoll: ::c_long = 302; +pub const SYS_unshare: ::c_long = 303; +pub const SYS_set_robust_list: ::c_long = 304; +pub const SYS_get_robust_list: ::c_long = 305; +pub const SYS_splice: ::c_long = 306; +pub const SYS_sync_file_range: ::c_long = 307; +pub const SYS_tee: ::c_long = 308; +pub const SYS_vmsplice: ::c_long = 309; +pub const SYS_move_pages: ::c_long = 310; +pub const SYS_getcpu: ::c_long = 311; +pub const SYS_epoll_pwait: ::c_long = 312; +pub const SYS_utimes: ::c_long = 313; +pub const SYS_fallocate: ::c_long = 314; +pub const SYS_utimensat: ::c_long = 315; +pub const SYS_signalfd: ::c_long = 316; +pub const SYS_timerfd: ::c_long = 317; +pub const SYS_eventfd: ::c_long = 318; +pub const SYS_timerfd_create: ::c_long = 319; +pub const SYS_timerfd_settime: ::c_long = 320; +pub const SYS_timerfd_gettime: ::c_long = 321; +pub const SYS_signalfd4: ::c_long = 322; +pub const SYS_eventfd2: ::c_long = 323; +pub const SYS_inotify_init1: ::c_long = 324; +pub const SYS_pipe2: ::c_long = 325; +pub const SYS_dup3: ::c_long = 326; +pub const SYS_epoll_create1: ::c_long = 327; +pub const SYS_preadv: ::c_long = 328; +pub const SYS_pwritev: ::c_long = 329; +pub const SYS_rt_tgsigqueueinfo: ::c_long = 330; +pub const SYS_perf_event_open: ::c_long = 331; +pub const SYS_fanotify_init: ::c_long = 332; +pub const SYS_fanotify_mark: ::c_long = 333; +pub const SYS_prlimit64: ::c_long = 334; +pub const SYS_name_to_handle_at: ::c_long = 335; +pub const SYS_open_by_handle_at: ::c_long = 336; +pub const SYS_clock_adjtime: ::c_long = 337; +pub const SYS_syncfs: ::c_long = 338; +pub const SYS_setns: ::c_long = 339; +pub const SYS_process_vm_readv: ::c_long = 340; +pub const SYS_process_vm_writev: ::c_long = 341; +pub const SYS_s390_runtime_instr: ::c_long = 342; +pub const SYS_kcmp: ::c_long = 343; +pub const SYS_finit_module: ::c_long = 344; +pub const SYS_sched_setattr: ::c_long = 345; +pub const SYS_sched_getattr: ::c_long = 346; +pub const SYS_renameat2: ::c_long = 347; +pub const SYS_seccomp: ::c_long = 348; +pub const SYS_getrandom: ::c_long = 349; +pub const SYS_memfd_create: ::c_long = 350; +pub const SYS_bpf: ::c_long = 351; +pub const SYS_s390_pci_mmio_write: ::c_long = 352; +pub const SYS_s390_pci_mmio_read: ::c_long = 353; +pub const SYS_execveat: ::c_long = 354; +pub const SYS_userfaultfd: ::c_long = 355; +pub const SYS_membarrier: ::c_long = 356; +pub const SYS_recvmmsg: ::c_long = 357; +pub const SYS_sendmmsg: ::c_long = 358; +pub const SYS_socket: ::c_long = 359; +pub const SYS_socketpair: ::c_long = 360; +pub const SYS_bind: ::c_long = 361; +pub const SYS_connect: ::c_long = 362; +pub const SYS_listen: ::c_long = 363; +pub const SYS_accept4: ::c_long = 364; +pub const SYS_getsockopt: ::c_long = 365; +pub const SYS_setsockopt: ::c_long = 366; +pub const SYS_getsockname: ::c_long = 367; +pub const SYS_getpeername: ::c_long = 368; +pub const SYS_sendto: ::c_long = 369; +pub const SYS_sendmsg: ::c_long = 370; +pub const SYS_recvfrom: ::c_long = 371; +pub const SYS_recvmsg: ::c_long = 372; +pub const SYS_shutdown: ::c_long = 373; +pub const SYS_mlock2: ::c_long = 374; +pub const SYS_copy_file_range: ::c_long = 375; +pub const SYS_preadv2: ::c_long = 376; +pub const SYS_pwritev2: ::c_long = 377; +pub const SYS_lchown: ::c_long = 198; +pub const SYS_setuid: ::c_long = 213; +pub const SYS_getuid: ::c_long = 199; +pub const SYS_setgid: ::c_long = 214; +pub const SYS_getgid: ::c_long = 200; +pub const SYS_geteuid: ::c_long = 201; +pub const SYS_setreuid: ::c_long = 203; +pub const SYS_setregid: ::c_long = 204; +pub const SYS_getrlimit: ::c_long = 191; +pub const SYS_getgroups: ::c_long = 205; +pub const SYS_fchown: ::c_long = 207; +pub const SYS_setresuid: ::c_long = 208; +pub const SYS_setresgid: ::c_long = 210; +pub const SYS_getresgid: ::c_long = 211; +pub const SYS_select: ::c_long = 142; +pub const SYS_getegid: ::c_long = 202; +pub const SYS_setgroups: ::c_long = 206; +pub const SYS_getresuid: ::c_long = 209; +pub const SYS_chown: ::c_long = 212; +pub const SYS_setfsuid: ::c_long = 215; +pub const SYS_setfsgid: ::c_long = 216; +pub const SYS_newfstatat: ::c_long = 293; + +#[link(name = "util")] +extern { + pub fn sysctl(name: *mut ::c_int, + namelen: ::c_int, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *mut ::c_void, + newlen: ::size_t) + -> ::c_int; + pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; + pub fn backtrace(buf: *mut *mut ::c_void, + sz: ::c_int) -> ::c_int; + pub fn glob64(pattern: *const ::c_char, + flags: ::c_int, + errfunc: ::dox::Option ::c_int>, + pglob: *mut glob64_t) -> ::c_int; + pub fn globfree64(pglob: *mut glob64_t); + pub fn ptrace(request: ::c_uint, ...) -> ::c_long; + pub fn pthread_attr_getaffinity_np(attr: *const ::pthread_attr_t, + cpusetsize: ::size_t, + cpuset: *mut ::cpu_set_t) -> ::c_int; + pub fn pthread_attr_setaffinity_np(attr: *mut ::pthread_attr_t, + cpusetsize: ::size_t, + cpuset: *const ::cpu_set_t) -> ::c_int; + pub fn getpriority(which: ::__priority_which_t, who: ::id_t) -> ::c_int; + pub fn setpriority(which: ::__priority_which_t, who: ::id_t, + prio: ::c_int) -> ::c_int; + pub fn pthread_getaffinity_np(thread: ::pthread_t, + cpusetsize: ::size_t, + cpuset: *mut ::cpu_set_t) -> ::c_int; + pub fn pthread_setaffinity_np(thread: ::pthread_t, + cpusetsize: ::size_t, + cpuset: *const ::cpu_set_t) -> ::c_int; + pub fn sched_getcpu() -> ::c_int; + pub fn getcontext(ucp: *mut ucontext_t) -> ::c_int; + pub fn setcontext(ucp: *const ucontext_t) -> ::c_int; + pub fn makecontext(ucp: *mut ucontext_t, + func: extern fn (), + argc: ::c_int, ...); + pub fn swapcontext(uocp: *mut ucontext_t, + ucp: *const ucontext_t) -> ::c_int; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/notbsd/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/notbsd/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1016 @@ +use dox::mem; + +pub type sa_family_t = u16; +pub type pthread_key_t = ::c_uint; +pub type speed_t = ::c_uint; +pub type tcflag_t = ::c_uint; +pub type clockid_t = ::c_int; +pub type key_t = ::c_int; +pub type id_t = ::c_uint; + +pub enum timezone {} + +s! { + pub struct sockaddr { + pub sa_family: sa_family_t, + pub sa_data: [::c_char; 14], + } + + pub struct sockaddr_in { + pub sin_family: sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + pub sin_zero: [u8; 8], + } + + pub struct sockaddr_in6 { + pub sin6_family: sa_family_t, + pub sin6_port: ::in_port_t, + pub sin6_flowinfo: u32, + pub sin6_addr: ::in6_addr, + pub sin6_scope_id: u32, + } + + pub struct sockaddr_un { + pub sun_family: sa_family_t, + pub sun_path: [::c_char; 108] + } + + pub struct sockaddr_storage { + pub ss_family: sa_family_t, + __ss_align: ::size_t, + #[cfg(target_pointer_width = "32")] + __ss_pad2: [u8; 128 - 2 * 4], + #[cfg(target_pointer_width = "64")] + __ss_pad2: [u8; 128 - 2 * 8], + } + + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + pub ai_addrlen: socklen_t, + + #[cfg(any(target_os = "linux", + target_os = "emscripten", + target_os = "fuchsia"))] + pub ai_addr: *mut ::sockaddr, + + pub ai_canonname: *mut c_char, + + #[cfg(target_os = "android")] + pub ai_addr: *mut ::sockaddr, + + pub ai_next: *mut addrinfo, + } + + pub struct sockaddr_nl { + pub nl_family: ::sa_family_t, + nl_pad: ::c_ushort, + pub nl_pid: u32, + pub nl_groups: u32 + } + + pub struct sockaddr_ll { + pub sll_family: ::c_ushort, + pub sll_protocol: ::c_ushort, + pub sll_ifindex: ::c_int, + pub sll_hatype: ::c_ushort, + pub sll_pkttype: ::c_uchar, + pub sll_halen: ::c_uchar, + pub sll_addr: [::c_uchar; 8] + } + + pub struct fd_set { + fds_bits: [::c_ulong; FD_SETSIZE / ULONG_SIZE], + } + + pub struct tm { + pub tm_sec: ::c_int, + pub tm_min: ::c_int, + pub tm_hour: ::c_int, + pub tm_mday: ::c_int, + pub tm_mon: ::c_int, + pub tm_year: ::c_int, + pub tm_wday: ::c_int, + pub tm_yday: ::c_int, + pub tm_isdst: ::c_int, + pub tm_gmtoff: ::c_long, + pub tm_zone: *const ::c_char, + } + + pub struct sched_param { + pub sched_priority: ::c_int, + #[cfg(any(target_env = "musl", target_os = "emscripten"))] + pub sched_ss_low_priority: ::c_int, + #[cfg(any(target_env = "musl", target_os = "emscripten"))] + pub sched_ss_repl_period: ::timespec, + #[cfg(any(target_env = "musl", target_os = "emscripten"))] + pub sched_ss_init_budget: ::timespec, + #[cfg(any(target_env = "musl", target_os = "emscripten"))] + pub sched_ss_max_repl: ::c_int, + } + + pub struct Dl_info { + pub dli_fname: *const ::c_char, + pub dli_fbase: *mut ::c_void, + pub dli_sname: *const ::c_char, + pub dli_saddr: *mut ::c_void, + } + + #[cfg_attr(any(all(target_arch = "x86", + not(target_env = "musl"), + not(target_os = "android")), + target_arch = "x86_64"), + repr(packed))] + pub struct epoll_event { + pub events: ::uint32_t, + pub u64: ::uint64_t, + } + + pub struct utsname { + pub sysname: [::c_char; 65], + pub nodename: [::c_char; 65], + pub release: [::c_char; 65], + pub version: [::c_char; 65], + pub machine: [::c_char; 65], + pub domainname: [::c_char; 65] + } + + pub struct lconv { + pub decimal_point: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + pub grouping: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub currency_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub int_frac_digits: ::c_char, + pub frac_digits: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + pub n_sign_posn: ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_n_cs_precedes: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + pub int_n_sign_posn: ::c_char, + } + + pub struct sigevent { + pub sigev_value: ::sigval, + pub sigev_signo: ::c_int, + pub sigev_notify: ::c_int, + // Actually a union. We only expose sigev_notify_thread_id because it's + // the most useful member + pub sigev_notify_thread_id: ::c_int, + #[cfg(target_pointer_width = "64")] + __unused1: [::c_int; 11], + #[cfg(target_pointer_width = "32")] + __unused1: [::c_int; 12] + } +} + +// intentionally not public, only used for fd_set +cfg_if! { + if #[cfg(target_pointer_width = "32")] { + const ULONG_SIZE: usize = 32; + } else if #[cfg(target_pointer_width = "64")] { + const ULONG_SIZE: usize = 64; + } else { + // Unknown target_pointer_width + } +} + +pub const EXIT_FAILURE: ::c_int = 1; +pub const EXIT_SUCCESS: ::c_int = 0; +pub const RAND_MAX: ::c_int = 2147483647; +pub const EOF: ::c_int = -1; +pub const SEEK_SET: ::c_int = 0; +pub const SEEK_CUR: ::c_int = 1; +pub const SEEK_END: ::c_int = 2; +pub const _IOFBF: ::c_int = 0; +pub const _IONBF: ::c_int = 2; +pub const _IOLBF: ::c_int = 1; + +pub const F_DUPFD: ::c_int = 0; +pub const F_GETFD: ::c_int = 1; +pub const F_SETFD: ::c_int = 2; +pub const F_GETFL: ::c_int = 3; +pub const F_SETFL: ::c_int = 4; + +// Linux-specific fcntls +pub const F_SETLEASE: ::c_int = 1024; +pub const F_GETLEASE: ::c_int = 1025; +pub const F_NOTIFY: ::c_int = 1026; +pub const F_CANCELLK: ::c_int = 1029; +pub const F_DUPFD_CLOEXEC: ::c_int = 1030; +pub const F_SETPIPE_SZ: ::c_int = 1031; +pub const F_GETPIPE_SZ: ::c_int = 1032; +pub const F_ADD_SEALS: ::c_int = 1033; +pub const F_GET_SEALS: ::c_int = 1034; + +pub const F_SEAL_SEAL: ::c_int = 0x0001; +pub const F_SEAL_SHRINK: ::c_int = 0x0002; +pub const F_SEAL_GROW: ::c_int = 0x0004; +pub const F_SEAL_WRITE: ::c_int = 0x0008; + +// TODO(#235): Include file sealing fcntls once we have a way to verify them. + +pub const SIGTRAP: ::c_int = 5; + +pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; +pub const PTHREAD_CREATE_DETACHED: ::c_int = 1; + +pub const CLOCK_REALTIME: ::clockid_t = 0; +pub const CLOCK_MONOTONIC: ::clockid_t = 1; +pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 2; +pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 3; +pub const CLOCK_MONOTONIC_RAW: ::clockid_t = 4; +pub const CLOCK_REALTIME_COARSE: ::clockid_t = 5; +pub const CLOCK_MONOTONIC_COARSE: ::clockid_t = 6; +pub const CLOCK_BOOTTIME: ::clockid_t = 7; +pub const CLOCK_REALTIME_ALARM: ::clockid_t = 8; +pub const CLOCK_BOOTTIME_ALARM: ::clockid_t = 9; +// TODO(#247) Someday our Travis shall have glibc 2.21 (released in Sep +// 2014.) See also musl/mod.rs +// pub const CLOCK_SGI_CYCLE: ::clockid_t = 10; +// pub const CLOCK_TAI: ::clockid_t = 11; +pub const TIMER_ABSTIME: ::c_int = 1; + +pub const RLIMIT_CPU: ::c_int = 0; +pub const RLIMIT_FSIZE: ::c_int = 1; +pub const RLIMIT_DATA: ::c_int = 2; +pub const RLIMIT_STACK: ::c_int = 3; +pub const RLIMIT_CORE: ::c_int = 4; +pub const RLIMIT_LOCKS: ::c_int = 10; +pub const RLIMIT_SIGPENDING: ::c_int = 11; +pub const RLIMIT_MSGQUEUE: ::c_int = 12; +pub const RLIMIT_NICE: ::c_int = 13; +pub const RLIMIT_RTPRIO: ::c_int = 14; + +pub const RUSAGE_SELF: ::c_int = 0; + +pub const O_RDONLY: ::c_int = 0; +pub const O_WRONLY: ::c_int = 1; +pub const O_RDWR: ::c_int = 2; + +pub const SOCK_CLOEXEC: ::c_int = O_CLOEXEC; + +pub const S_IFIFO: ::mode_t = 4096; +pub const S_IFCHR: ::mode_t = 8192; +pub const S_IFBLK: ::mode_t = 24576; +pub const S_IFDIR: ::mode_t = 16384; +pub const S_IFREG: ::mode_t = 32768; +pub const S_IFLNK: ::mode_t = 40960; +pub const S_IFSOCK: ::mode_t = 49152; +pub const S_IFMT: ::mode_t = 61440; +pub const S_IRWXU: ::mode_t = 448; +pub const S_IXUSR: ::mode_t = 64; +pub const S_IWUSR: ::mode_t = 128; +pub const S_IRUSR: ::mode_t = 256; +pub const S_IRWXG: ::mode_t = 56; +pub const S_IXGRP: ::mode_t = 8; +pub const S_IWGRP: ::mode_t = 16; +pub const S_IRGRP: ::mode_t = 32; +pub const S_IRWXO: ::mode_t = 7; +pub const S_IXOTH: ::mode_t = 1; +pub const S_IWOTH: ::mode_t = 2; +pub const S_IROTH: ::mode_t = 4; +pub const F_OK: ::c_int = 0; +pub const R_OK: ::c_int = 4; +pub const W_OK: ::c_int = 2; +pub const X_OK: ::c_int = 1; +pub const STDIN_FILENO: ::c_int = 0; +pub const STDOUT_FILENO: ::c_int = 1; +pub const STDERR_FILENO: ::c_int = 2; +pub const SIGHUP: ::c_int = 1; +pub const SIGINT: ::c_int = 2; +pub const SIGQUIT: ::c_int = 3; +pub const SIGILL: ::c_int = 4; +pub const SIGABRT: ::c_int = 6; +pub const SIGFPE: ::c_int = 8; +pub const SIGKILL: ::c_int = 9; +pub const SIGSEGV: ::c_int = 11; +pub const SIGPIPE: ::c_int = 13; +pub const SIGALRM: ::c_int = 14; +pub const SIGTERM: ::c_int = 15; + +pub const PROT_NONE: ::c_int = 0; +pub const PROT_READ: ::c_int = 1; +pub const PROT_WRITE: ::c_int = 2; +pub const PROT_EXEC: ::c_int = 4; + +pub const LC_CTYPE: ::c_int = 0; +pub const LC_NUMERIC: ::c_int = 1; +pub const LC_TIME: ::c_int = 2; +pub const LC_COLLATE: ::c_int = 3; +pub const LC_MONETARY: ::c_int = 4; +pub const LC_MESSAGES: ::c_int = 5; +pub const LC_ALL: ::c_int = 6; +pub const LC_CTYPE_MASK: ::c_int = (1 << LC_CTYPE); +pub const LC_NUMERIC_MASK: ::c_int = (1 << LC_NUMERIC); +pub const LC_TIME_MASK: ::c_int = (1 << LC_TIME); +pub const LC_COLLATE_MASK: ::c_int = (1 << LC_COLLATE); +pub const LC_MONETARY_MASK: ::c_int = (1 << LC_MONETARY); +pub const LC_MESSAGES_MASK: ::c_int = (1 << LC_MESSAGES); +// LC_ALL_MASK defined per platform + +pub const MAP_FILE: ::c_int = 0x0000; +pub const MAP_SHARED: ::c_int = 0x0001; +pub const MAP_PRIVATE: ::c_int = 0x0002; +pub const MAP_FIXED: ::c_int = 0x0010; + +pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; + +// MS_ flags for msync(2) +pub const MS_ASYNC: ::c_int = 0x0001; +pub const MS_INVALIDATE: ::c_int = 0x0002; +pub const MS_SYNC: ::c_int = 0x0004; + +// MS_ flags for mount(2) +pub const MS_RDONLY: ::c_ulong = 0x01; +pub const MS_NOSUID: ::c_ulong = 0x02; +pub const MS_NODEV: ::c_ulong = 0x04; +pub const MS_NOEXEC: ::c_ulong = 0x08; +pub const MS_SYNCHRONOUS: ::c_ulong = 0x10; +pub const MS_REMOUNT: ::c_ulong = 0x20; +pub const MS_MANDLOCK: ::c_ulong = 0x40; +pub const MS_DIRSYNC: ::c_ulong = 0x80; +pub const MS_NOATIME: ::c_ulong = 0x0400; +pub const MS_NODIRATIME: ::c_ulong = 0x0800; +pub const MS_BIND: ::c_ulong = 0x1000; +pub const MS_MOVE: ::c_ulong = 0x2000; +pub const MS_REC: ::c_ulong = 0x4000; +pub const MS_SILENT: ::c_ulong = 0x8000; +pub const MS_POSIXACL: ::c_ulong = 0x010000; +pub const MS_UNBINDABLE: ::c_ulong = 0x020000; +pub const MS_PRIVATE: ::c_ulong = 0x040000; +pub const MS_SLAVE: ::c_ulong = 0x080000; +pub const MS_SHARED: ::c_ulong = 0x100000; +pub const MS_RELATIME: ::c_ulong = 0x200000; +pub const MS_KERNMOUNT: ::c_ulong = 0x400000; +pub const MS_I_VERSION: ::c_ulong = 0x800000; +pub const MS_STRICTATIME: ::c_ulong = 0x1000000; +pub const MS_ACTIVE: ::c_ulong = 0x40000000; +pub const MS_NOUSER: ::c_ulong = 0x80000000; +pub const MS_MGC_VAL: ::c_ulong = 0xc0ed0000; +pub const MS_MGC_MSK: ::c_ulong = 0xffff0000; +pub const MS_RMT_MASK: ::c_ulong = 0x800051; + +pub const EPERM: ::c_int = 1; +pub const ENOENT: ::c_int = 2; +pub const ESRCH: ::c_int = 3; +pub const EINTR: ::c_int = 4; +pub const EIO: ::c_int = 5; +pub const ENXIO: ::c_int = 6; +pub const E2BIG: ::c_int = 7; +pub const ENOEXEC: ::c_int = 8; +pub const EBADF: ::c_int = 9; +pub const ECHILD: ::c_int = 10; +pub const EAGAIN: ::c_int = 11; +pub const ENOMEM: ::c_int = 12; +pub const EACCES: ::c_int = 13; +pub const EFAULT: ::c_int = 14; +pub const ENOTBLK: ::c_int = 15; +pub const EBUSY: ::c_int = 16; +pub const EEXIST: ::c_int = 17; +pub const EXDEV: ::c_int = 18; +pub const ENODEV: ::c_int = 19; +pub const ENOTDIR: ::c_int = 20; +pub const EISDIR: ::c_int = 21; +pub const EINVAL: ::c_int = 22; +pub const ENFILE: ::c_int = 23; +pub const EMFILE: ::c_int = 24; +pub const ENOTTY: ::c_int = 25; +pub const ETXTBSY: ::c_int = 26; +pub const EFBIG: ::c_int = 27; +pub const ENOSPC: ::c_int = 28; +pub const ESPIPE: ::c_int = 29; +pub const EROFS: ::c_int = 30; +pub const EMLINK: ::c_int = 31; +pub const EPIPE: ::c_int = 32; +pub const EDOM: ::c_int = 33; +pub const ERANGE: ::c_int = 34; +pub const EWOULDBLOCK: ::c_int = EAGAIN; + +pub const SCM_RIGHTS: ::c_int = 0x01; +pub const SCM_CREDENTIALS: ::c_int = 0x02; + +pub const PROT_GROWSDOWN: ::c_int = 0x1000000; +pub const PROT_GROWSUP: ::c_int = 0x2000000; + +pub const MAP_TYPE: ::c_int = 0x000f; + +pub const MADV_NORMAL: ::c_int = 0; +pub const MADV_RANDOM: ::c_int = 1; +pub const MADV_SEQUENTIAL: ::c_int = 2; +pub const MADV_WILLNEED: ::c_int = 3; +pub const MADV_DONTNEED: ::c_int = 4; +pub const MADV_FREE: ::c_int = 8; +pub const MADV_REMOVE: ::c_int = 9; +pub const MADV_DONTFORK: ::c_int = 10; +pub const MADV_DOFORK: ::c_int = 11; +pub const MADV_MERGEABLE: ::c_int = 12; +pub const MADV_UNMERGEABLE: ::c_int = 13; +pub const MADV_HUGEPAGE: ::c_int = 14; +pub const MADV_NOHUGEPAGE: ::c_int = 15; +pub const MADV_DONTDUMP: ::c_int = 16; +pub const MADV_DODUMP: ::c_int = 17; +pub const MADV_HWPOISON: ::c_int = 100; +pub const MADV_SOFT_OFFLINE: ::c_int = 101; + +pub const IFF_UP: ::c_int = 0x1; +pub const IFF_BROADCAST: ::c_int = 0x2; +pub const IFF_DEBUG: ::c_int = 0x4; +pub const IFF_LOOPBACK: ::c_int = 0x8; +pub const IFF_POINTOPOINT: ::c_int = 0x10; +pub const IFF_NOTRAILERS: ::c_int = 0x20; +pub const IFF_RUNNING: ::c_int = 0x40; +pub const IFF_NOARP: ::c_int = 0x80; +pub const IFF_PROMISC: ::c_int = 0x100; +pub const IFF_ALLMULTI: ::c_int = 0x200; +pub const IFF_MASTER: ::c_int = 0x400; +pub const IFF_SLAVE: ::c_int = 0x800; +pub const IFF_MULTICAST: ::c_int = 0x1000; +pub const IFF_PORTSEL: ::c_int = 0x2000; +pub const IFF_AUTOMEDIA: ::c_int = 0x4000; +pub const IFF_DYNAMIC: ::c_int = 0x8000; + +pub const SOL_IP: ::c_int = 0; +pub const SOL_TCP: ::c_int = 6; +pub const SOL_UDP: ::c_int = 17; +pub const SOL_IPV6: ::c_int = 41; +pub const SOL_ICMPV6: ::c_int = 58; +pub const SOL_RAW: ::c_int = 255; +pub const SOL_DECNET: ::c_int = 261; +pub const SOL_X25: ::c_int = 262; +pub const SOL_PACKET: ::c_int = 263; +pub const SOL_ATM: ::c_int = 264; +pub const SOL_AAL: ::c_int = 265; +pub const SOL_IRDA: ::c_int = 266; +pub const SOL_NETBEUI: ::c_int = 267; +pub const SOL_LLC: ::c_int = 268; +pub const SOL_DCCP: ::c_int = 269; +pub const SOL_NETLINK: ::c_int = 270; +pub const SOL_TIPC: ::c_int = 271; + +pub const AF_UNSPEC: ::c_int = 0; +pub const AF_UNIX: ::c_int = 1; +pub const AF_LOCAL: ::c_int = 1; +pub const AF_INET: ::c_int = 2; +pub const AF_AX25: ::c_int = 3; +pub const AF_IPX: ::c_int = 4; +pub const AF_APPLETALK: ::c_int = 5; +pub const AF_NETROM: ::c_int = 6; +pub const AF_BRIDGE: ::c_int = 7; +pub const AF_ATMPVC: ::c_int = 8; +pub const AF_X25: ::c_int = 9; +pub const AF_INET6: ::c_int = 10; +pub const AF_ROSE: ::c_int = 11; +pub const AF_DECnet: ::c_int = 12; +pub const AF_NETBEUI: ::c_int = 13; +pub const AF_SECURITY: ::c_int = 14; +pub const AF_KEY: ::c_int = 15; +pub const AF_NETLINK: ::c_int = 16; +pub const AF_ROUTE: ::c_int = AF_NETLINK; +pub const AF_PACKET: ::c_int = 17; +pub const AF_ASH: ::c_int = 18; +pub const AF_ECONET: ::c_int = 19; +pub const AF_ATMSVC: ::c_int = 20; +pub const AF_RDS: ::c_int = 21; +pub const AF_SNA: ::c_int = 22; +pub const AF_IRDA: ::c_int = 23; +pub const AF_PPPOX: ::c_int = 24; +pub const AF_WANPIPE: ::c_int = 25; +pub const AF_LLC: ::c_int = 26; +pub const AF_CAN: ::c_int = 29; +pub const AF_TIPC: ::c_int = 30; +pub const AF_BLUETOOTH: ::c_int = 31; +pub const AF_IUCV: ::c_int = 32; +pub const AF_RXRPC: ::c_int = 33; +pub const AF_ISDN: ::c_int = 34; +pub const AF_PHONET: ::c_int = 35; +pub const AF_IEEE802154: ::c_int = 36; +pub const AF_CAIF: ::c_int = 37; +pub const AF_ALG: ::c_int = 38; + +pub const PF_UNSPEC: ::c_int = AF_UNSPEC; +pub const PF_UNIX: ::c_int = AF_UNIX; +pub const PF_LOCAL: ::c_int = AF_LOCAL; +pub const PF_INET: ::c_int = AF_INET; +pub const PF_AX25: ::c_int = AF_AX25; +pub const PF_IPX: ::c_int = AF_IPX; +pub const PF_APPLETALK: ::c_int = AF_APPLETALK; +pub const PF_NETROM: ::c_int = AF_NETROM; +pub const PF_BRIDGE: ::c_int = AF_BRIDGE; +pub const PF_ATMPVC: ::c_int = AF_ATMPVC; +pub const PF_X25: ::c_int = AF_X25; +pub const PF_INET6: ::c_int = AF_INET6; +pub const PF_ROSE: ::c_int = AF_ROSE; +pub const PF_DECnet: ::c_int = AF_DECnet; +pub const PF_NETBEUI: ::c_int = AF_NETBEUI; +pub const PF_SECURITY: ::c_int = AF_SECURITY; +pub const PF_KEY: ::c_int = AF_KEY; +pub const PF_NETLINK: ::c_int = AF_NETLINK; +pub const PF_ROUTE: ::c_int = AF_ROUTE; +pub const PF_PACKET: ::c_int = AF_PACKET; +pub const PF_ASH: ::c_int = AF_ASH; +pub const PF_ECONET: ::c_int = AF_ECONET; +pub const PF_ATMSVC: ::c_int = AF_ATMSVC; +pub const PF_RDS: ::c_int = AF_RDS; +pub const PF_SNA: ::c_int = AF_SNA; +pub const PF_IRDA: ::c_int = AF_IRDA; +pub const PF_PPPOX: ::c_int = AF_PPPOX; +pub const PF_WANPIPE: ::c_int = AF_WANPIPE; +pub const PF_LLC: ::c_int = AF_LLC; +pub const PF_CAN: ::c_int = AF_CAN; +pub const PF_TIPC: ::c_int = AF_TIPC; +pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; +pub const PF_IUCV: ::c_int = AF_IUCV; +pub const PF_RXRPC: ::c_int = AF_RXRPC; +pub const PF_ISDN: ::c_int = AF_ISDN; +pub const PF_PHONET: ::c_int = AF_PHONET; +pub const PF_IEEE802154: ::c_int = AF_IEEE802154; +pub const PF_CAIF: ::c_int = AF_CAIF; +pub const PF_ALG: ::c_int = AF_ALG; + +pub const SOMAXCONN: ::c_int = 128; + +pub const MSG_OOB: ::c_int = 1; +pub const MSG_PEEK: ::c_int = 2; +pub const MSG_DONTROUTE: ::c_int = 4; +pub const MSG_CTRUNC: ::c_int = 8; +pub const MSG_TRUNC: ::c_int = 0x20; +pub const MSG_DONTWAIT: ::c_int = 0x40; +pub const MSG_EOR: ::c_int = 0x80; +pub const MSG_WAITALL: ::c_int = 0x100; +pub const MSG_FIN: ::c_int = 0x200; +pub const MSG_SYN: ::c_int = 0x400; +pub const MSG_CONFIRM: ::c_int = 0x800; +pub const MSG_RST: ::c_int = 0x1000; +pub const MSG_ERRQUEUE: ::c_int = 0x2000; +pub const MSG_NOSIGNAL: ::c_int = 0x4000; +pub const MSG_MORE: ::c_int = 0x8000; +pub const MSG_WAITFORONE: ::c_int = 0x10000; +pub const MSG_FASTOPEN: ::c_int = 0x20000000; +pub const MSG_CMSG_CLOEXEC: ::c_int = 0x40000000; + +pub const SCM_TIMESTAMP: ::c_int = SO_TIMESTAMP; + +pub const SOCK_RAW: ::c_int = 3; +pub const SOCK_RDM: ::c_int = 4; +pub const IP_MULTICAST_IF: ::c_int = 32; +pub const IP_MULTICAST_TTL: ::c_int = 33; +pub const IP_MULTICAST_LOOP: ::c_int = 34; +pub const IP_TTL: ::c_int = 2; +pub const IP_HDRINCL: ::c_int = 3; +pub const IP_ADD_MEMBERSHIP: ::c_int = 35; +pub const IP_DROP_MEMBERSHIP: ::c_int = 36; +pub const IP_TRANSPARENT: ::c_int = 19; +pub const IPV6_UNICAST_HOPS: ::c_int = 16; +pub const IPV6_MULTICAST_IF: ::c_int = 17; +pub const IPV6_MULTICAST_HOPS: ::c_int = 18; +pub const IPV6_MULTICAST_LOOP: ::c_int = 19; +pub const IPV6_ADD_MEMBERSHIP: ::c_int = 20; +pub const IPV6_DROP_MEMBERSHIP: ::c_int = 21; +pub const IPV6_V6ONLY: ::c_int = 26; + +pub const TCP_NODELAY: ::c_int = 1; +pub const TCP_MAXSEG: ::c_int = 2; +pub const TCP_CORK: ::c_int = 3; +pub const TCP_KEEPIDLE: ::c_int = 4; +pub const TCP_KEEPINTVL: ::c_int = 5; +pub const TCP_KEEPCNT: ::c_int = 6; +pub const TCP_SYNCNT: ::c_int = 7; +pub const TCP_LINGER2: ::c_int = 8; +pub const TCP_DEFER_ACCEPT: ::c_int = 9; +pub const TCP_WINDOW_CLAMP: ::c_int = 10; +pub const TCP_INFO: ::c_int = 11; +pub const TCP_QUICKACK: ::c_int = 12; +pub const TCP_CONGESTION: ::c_int = 13; + +pub const SO_DEBUG: ::c_int = 1; + +pub const SHUT_RD: ::c_int = 0; +pub const SHUT_WR: ::c_int = 1; +pub const SHUT_RDWR: ::c_int = 2; + +pub const LOCK_SH: ::c_int = 1; +pub const LOCK_EX: ::c_int = 2; +pub const LOCK_NB: ::c_int = 4; +pub const LOCK_UN: ::c_int = 8; + +pub const SS_ONSTACK: ::c_int = 1; +pub const SS_DISABLE: ::c_int = 2; + +pub const PATH_MAX: ::c_int = 4096; + +pub const FD_SETSIZE: usize = 1024; + +pub const EPOLLIN: ::c_int = 0x1; +pub const EPOLLPRI: ::c_int = 0x2; +pub const EPOLLOUT: ::c_int = 0x4; +pub const EPOLLRDNORM: ::c_int = 0x40; +pub const EPOLLRDBAND: ::c_int = 0x80; +pub const EPOLLWRNORM: ::c_int = 0x100; +pub const EPOLLWRBAND: ::c_int = 0x200; +pub const EPOLLMSG: ::c_int = 0x400; +pub const EPOLLERR: ::c_int = 0x8; +pub const EPOLLHUP: ::c_int = 0x10; +pub const EPOLLET: ::c_int = 0x80000000; + +pub const EPOLL_CTL_ADD: ::c_int = 1; +pub const EPOLL_CTL_MOD: ::c_int = 3; +pub const EPOLL_CTL_DEL: ::c_int = 2; + +pub const MNT_DETACH: ::c_int = 0x2; +pub const MNT_EXPIRE: ::c_int = 0x4; + +pub const Q_GETFMT: ::c_int = 0x800004; +pub const Q_GETINFO: ::c_int = 0x800005; +pub const Q_SETINFO: ::c_int = 0x800006; +pub const QIF_BLIMITS: ::uint32_t = 1; +pub const QIF_SPACE: ::uint32_t = 2; +pub const QIF_ILIMITS: ::uint32_t = 4; +pub const QIF_INODES: ::uint32_t = 8; +pub const QIF_BTIME: ::uint32_t = 16; +pub const QIF_ITIME: ::uint32_t = 32; +pub const QIF_LIMITS: ::uint32_t = 5; +pub const QIF_USAGE: ::uint32_t = 10; +pub const QIF_TIMES: ::uint32_t = 48; +pub const QIF_ALL: ::uint32_t = 63; + +pub const MNT_FORCE: ::c_int = 0x1; + +pub const Q_SYNC: ::c_int = 0x800001; +pub const Q_QUOTAON: ::c_int = 0x800002; +pub const Q_QUOTAOFF: ::c_int = 0x800003; +pub const Q_GETQUOTA: ::c_int = 0x800007; +pub const Q_SETQUOTA: ::c_int = 0x800008; + +pub const TCIOFF: ::c_int = 2; +pub const TCION: ::c_int = 3; +pub const TCOOFF: ::c_int = 0; +pub const TCOON: ::c_int = 1; +pub const TCIFLUSH: ::c_int = 0; +pub const TCOFLUSH: ::c_int = 1; +pub const TCIOFLUSH: ::c_int = 2; +pub const NL0: ::c_int = 0x00000000; +pub const NL1: ::c_int = 0x00000100; +pub const TAB0: ::c_int = 0x00000000; +pub const CR0: ::c_int = 0x00000000; +pub const FF0: ::c_int = 0x00000000; +pub const BS0: ::c_int = 0x00000000; +pub const VT0: ::c_int = 0x00000000; +pub const VERASE: usize = 2; +pub const VKILL: usize = 3; +pub const VINTR: usize = 0; +pub const VQUIT: usize = 1; +pub const VLNEXT: usize = 15; +pub const IGNBRK: ::tcflag_t = 0x00000001; +pub const BRKINT: ::tcflag_t = 0x00000002; +pub const IGNPAR: ::tcflag_t = 0x00000004; +pub const PARMRK: ::tcflag_t = 0x00000008; +pub const INPCK: ::tcflag_t = 0x00000010; +pub const ISTRIP: ::tcflag_t = 0x00000020; +pub const INLCR: ::tcflag_t = 0x00000040; +pub const IGNCR: ::tcflag_t = 0x00000080; +pub const ICRNL: ::tcflag_t = 0x00000100; +pub const IXANY: ::tcflag_t = 0x00000800; +pub const IMAXBEL: ::tcflag_t = 0x00002000; +pub const OPOST: ::tcflag_t = 0x1; +pub const CS5: ::tcflag_t = 0x00000000; +pub const CRTSCTS: ::tcflag_t = 0x80000000; +pub const ECHO: ::tcflag_t = 0x00000008; +pub const OCRNL: ::tcflag_t = 0o000010; +pub const ONOCR: ::tcflag_t = 0o000020; +pub const ONLRET: ::tcflag_t = 0o000040; +pub const OFILL: ::tcflag_t = 0o000100; +pub const OFDEL: ::tcflag_t = 0o000200; + +pub const CLONE_VM: ::c_int = 0x100; +pub const CLONE_FS: ::c_int = 0x200; +pub const CLONE_FILES: ::c_int = 0x400; +pub const CLONE_SIGHAND: ::c_int = 0x800; +pub const CLONE_PTRACE: ::c_int = 0x2000; +pub const CLONE_VFORK: ::c_int = 0x4000; +pub const CLONE_PARENT: ::c_int = 0x8000; +pub const CLONE_THREAD: ::c_int = 0x10000; +pub const CLONE_NEWNS: ::c_int = 0x20000; +pub const CLONE_SYSVSEM: ::c_int = 0x40000; +pub const CLONE_SETTLS: ::c_int = 0x80000; +pub const CLONE_PARENT_SETTID: ::c_int = 0x100000; +pub const CLONE_CHILD_CLEARTID: ::c_int = 0x200000; +pub const CLONE_DETACHED: ::c_int = 0x400000; +pub const CLONE_UNTRACED: ::c_int = 0x800000; +pub const CLONE_CHILD_SETTID: ::c_int = 0x01000000; +pub const CLONE_NEWUTS: ::c_int = 0x04000000; +pub const CLONE_NEWIPC: ::c_int = 0x08000000; +pub const CLONE_NEWUSER: ::c_int = 0x10000000; +pub const CLONE_NEWPID: ::c_int = 0x20000000; +pub const CLONE_NEWNET: ::c_int = 0x40000000; +pub const CLONE_IO: ::c_int = 0x80000000; +pub const CLONE_NEWCGROUP: ::c_int = 0x02000000; + +pub const WNOHANG: ::c_int = 0x00000001; +pub const WUNTRACED: ::c_int = 0x00000002; +pub const WSTOPPED: ::c_int = WUNTRACED; +pub const WEXITED: ::c_int = 0x00000004; +pub const WCONTINUED: ::c_int = 0x00000008; +pub const WNOWAIT: ::c_int = 0x01000000; + +// Options set using PTRACE_SETOPTIONS. +pub const PTRACE_O_TRACESYSGOOD: ::c_int = 0x00000001; +pub const PTRACE_O_TRACEFORK: ::c_int = 0x00000002; +pub const PTRACE_O_TRACEVFORK: ::c_int = 0x00000004; +pub const PTRACE_O_TRACECLONE: ::c_int = 0x00000008; +pub const PTRACE_O_TRACEEXEC: ::c_int = 0x00000010; +pub const PTRACE_O_TRACEVFORKDONE: ::c_int = 0x00000020; +pub const PTRACE_O_TRACEEXIT: ::c_int = 0x00000040; +pub const PTRACE_O_TRACESECCOMP: ::c_int = 0x00000080; +pub const PTRACE_O_EXITKILL: ::c_int = 0x00100000; +pub const PTRACE_O_SUSPEND_SECCOMP: ::c_int = 0x00200000; +pub const PTRACE_O_MASK: ::c_int = 0x003000ff; + +// Wait extended result codes for the above trace options. +pub const PTRACE_EVENT_FORK: ::c_int = 1; +pub const PTRACE_EVENT_VFORK: ::c_int = 2; +pub const PTRACE_EVENT_CLONE: ::c_int = 3; +pub const PTRACE_EVENT_EXEC: ::c_int = 4; +pub const PTRACE_EVENT_VFORK_DONE: ::c_int = 5; +pub const PTRACE_EVENT_EXIT: ::c_int = 6; +pub const PTRACE_EVENT_SECCOMP: ::c_int = 7; +// PTRACE_EVENT_STOP was added to glibc in 2.26 +// pub const PTRACE_EVENT_STOP: ::c_int = 128; + +pub const __WNOTHREAD: ::c_int = 0x20000000; +pub const __WALL: ::c_int = 0x40000000; +pub const __WCLONE: ::c_int = 0x80000000; + +pub const SPLICE_F_MOVE: ::c_uint = 0x01; +pub const SPLICE_F_NONBLOCK: ::c_uint = 0x02; +pub const SPLICE_F_MORE: ::c_uint = 0x04; +pub const SPLICE_F_GIFT: ::c_uint = 0x08; + +pub const RTLD_LOCAL: ::c_int = 0; +pub const RTLD_LAZY: ::c_int = 1; + +pub const POSIX_FADV_NORMAL: ::c_int = 0; +pub const POSIX_FADV_RANDOM: ::c_int = 1; +pub const POSIX_FADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_FADV_WILLNEED: ::c_int = 3; + +pub const AT_FDCWD: ::c_int = -100; +pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x100; +pub const AT_REMOVEDIR: ::c_int = 0x200; +pub const AT_SYMLINK_FOLLOW: ::c_int = 0x400; +pub const AT_NO_AUTOMOUNT: ::c_int = 0x800; +pub const AT_EMPTY_PATH: ::c_int = 0x1000; + +pub const LOG_CRON: ::c_int = 9 << 3; +pub const LOG_AUTHPRIV: ::c_int = 10 << 3; +pub const LOG_FTP: ::c_int = 11 << 3; +pub const LOG_PERROR: ::c_int = 0x20; + +pub const PIPE_BUF: usize = 4096; + +pub const SI_LOAD_SHIFT: ::c_uint = 16; + +pub const SIGEV_SIGNAL: ::c_int = 0; +pub const SIGEV_NONE: ::c_int = 1; +pub const SIGEV_THREAD: ::c_int = 2; + +pub const P_ALL: idtype_t = 0; +pub const P_PID: idtype_t = 1; +pub const P_PGID: idtype_t = 2; + +pub const UTIME_OMIT: c_long = 1073741822; +pub const UTIME_NOW: c_long = 1073741823; + +pub const POLLIN: ::c_short = 0x1; +pub const POLLPRI: ::c_short = 0x2; +pub const POLLOUT: ::c_short = 0x4; +pub const POLLERR: ::c_short = 0x8; +pub const POLLHUP: ::c_short = 0x10; +pub const POLLNVAL: ::c_short = 0x20; +pub const POLLRDNORM: ::c_short = 0x040; +pub const POLLRDBAND: ::c_short = 0x080; + +f! { + pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { + let fd = fd as usize; + let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; + (*set).fds_bits[fd / size] &= !(1 << (fd % size)); + return + } + + pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { + let fd = fd as usize; + let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; + return ((*set).fds_bits[fd / size] & (1 << (fd % size))) != 0 + } + + pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { + let fd = fd as usize; + let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; + (*set).fds_bits[fd / size] |= 1 << (fd % size); + return + } + + pub fn FD_ZERO(set: *mut fd_set) -> () { + for slot in (*set).fds_bits.iter_mut() { + *slot = 0; + } + } + + pub fn WIFSTOPPED(status: ::c_int) -> bool { + (status & 0xff) == 0x7f + } + + pub fn WSTOPSIG(status: ::c_int) -> ::c_int { + (status >> 8) & 0xff + } + + pub fn WIFCONTINUED(status: ::c_int) -> bool { + status == 0xffff + } + + pub fn WIFSIGNALED(status: ::c_int) -> bool { + ((status & 0x7f) + 1) as i8 >= 2 + } + + pub fn WTERMSIG(status: ::c_int) -> ::c_int { + status & 0x7f + } + + pub fn WIFEXITED(status: ::c_int) -> bool { + (status & 0x7f) == 0 + } + + pub fn WEXITSTATUS(status: ::c_int) -> ::c_int { + (status >> 8) & 0xff + } + + pub fn WCOREDUMP(status: ::c_int) -> bool { + (status & 0x80) != 0 + } + + pub fn QCMD(cmd: ::c_int, type_: ::c_int) -> ::c_int { + (cmd << 8) | (type_ & 0x00ff) + } +} + +extern { + pub fn fdatasync(fd: ::c_int) -> ::c_int; + pub fn mincore(addr: *mut ::c_void, len: ::size_t, + vec: *mut ::c_uchar) -> ::c_int; + pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; + pub fn dirfd(dirp: *mut ::DIR) -> ::c_int; + + pub fn pthread_getattr_np(native: ::pthread_t, + attr: *mut ::pthread_attr_t) -> ::c_int; + pub fn pthread_attr_getstack(attr: *const ::pthread_attr_t, + stackaddr: *mut *mut ::c_void, + stacksize: *mut ::size_t) -> ::c_int; + pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; + pub fn setgroups(ngroups: ::size_t, + ptr: *const ::gid_t) -> ::c_int; + pub fn pipe2(fds: *mut ::c_int, flags: ::c_int) -> ::c_int; + pub fn statfs(path: *const ::c_char, buf: *mut statfs) -> ::c_int; + pub fn statfs64(path: *const ::c_char, buf: *mut statfs64) -> ::c_int; + pub fn fstatfs(fd: ::c_int, buf: *mut statfs) -> ::c_int; + pub fn fstatfs64(fd: ::c_int, buf: *mut statfs64) -> ::c_int; + pub fn statvfs64(path: *const ::c_char, buf: *mut statvfs64) -> ::c_int; + pub fn fstatvfs64(fd: ::c_int, buf: *mut statvfs64) -> ::c_int; + pub fn memrchr(cx: *const ::c_void, + c: ::c_int, + n: ::size_t) -> *mut ::c_void; + + pub fn posix_fadvise(fd: ::c_int, offset: ::off_t, len: ::off_t, + advise: ::c_int) -> ::c_int; + pub fn futimens(fd: ::c_int, times: *const ::timespec) -> ::c_int; + pub fn utimensat(dirfd: ::c_int, path: *const ::c_char, + times: *const ::timespec, flag: ::c_int) -> ::c_int; + pub fn duplocale(base: ::locale_t) -> ::locale_t; + pub fn freelocale(loc: ::locale_t); + pub fn newlocale(mask: ::c_int, + locale: *const ::c_char, + base: ::locale_t) -> ::locale_t; + pub fn uselocale(loc: ::locale_t) -> ::locale_t; + pub fn creat64(path: *const c_char, mode: mode_t) -> ::c_int; + pub fn fstat64(fildes: ::c_int, buf: *mut stat64) -> ::c_int; + pub fn fstatat64(dirfd: ::c_int, pathname: *const c_char, + buf: *mut stat64, flags: ::c_int) -> ::c_int; + pub fn ftruncate64(fd: ::c_int, length: off64_t) -> ::c_int; + pub fn getrlimit64(resource: ::c_int, rlim: *mut rlimit64) -> ::c_int; + pub fn lseek64(fd: ::c_int, offset: off64_t, whence: ::c_int) -> off64_t; + pub fn lstat64(path: *const c_char, buf: *mut stat64) -> ::c_int; + pub fn mmap64(addr: *mut ::c_void, + len: ::size_t, + prot: ::c_int, + flags: ::c_int, + fd: ::c_int, + offset: off64_t) + -> *mut ::c_void; + pub fn open64(path: *const c_char, oflag: ::c_int, ...) -> ::c_int; + pub fn openat64(fd: ::c_int, + path: *const c_char, + oflag: ::c_int, ...) -> ::c_int; + pub fn pread64(fd: ::c_int, buf: *mut ::c_void, count: ::size_t, + offset: off64_t) -> ::ssize_t; + pub fn preadv64(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off64_t) -> ::ssize_t; + pub fn pwrite64(fd: ::c_int, buf: *const ::c_void, count: ::size_t, + offset: off64_t) -> ::ssize_t; + pub fn pwritev64(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int, + offset: ::off64_t) -> ::ssize_t; + pub fn readdir64(dirp: *mut ::DIR) -> *mut ::dirent64; + pub fn readdir64_r(dirp: *mut ::DIR, entry: *mut ::dirent64, + result: *mut *mut ::dirent64) -> ::c_int; + pub fn setrlimit64(resource: ::c_int, rlim: *const rlimit64) -> ::c_int; + pub fn stat64(path: *const c_char, buf: *mut stat64) -> ::c_int; + pub fn truncate64(path: *const c_char, length: off64_t) -> ::c_int; + + pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; + + pub fn mknodat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t, dev: dev_t) -> ::c_int; + pub fn pthread_condattr_getclock(attr: *const pthread_condattr_t, + clock_id: *mut clockid_t) -> ::c_int; + pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, + clock_id: ::clockid_t) -> ::c_int; + pub fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, + pshared: ::c_int) -> ::c_int; + pub fn accept4(fd: ::c_int, addr: *mut ::sockaddr, len: *mut ::socklen_t, + flg: ::c_int) -> ::c_int; + pub fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, + pshared: ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, + val: *mut ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, + val: ::c_int) -> ::c_int; + pub fn ptsname_r(fd: ::c_int, + buf: *mut ::c_char, + buflen: ::size_t) -> ::c_int; + pub fn clearenv() -> ::c_int; + pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, + options: ::c_int) -> ::c_int; + pub fn setreuid(ruid: ::uid_t, euid: ::uid_t) -> ::c_int; + pub fn setregid(rgid: ::gid_t, egid: ::gid_t) -> ::c_int; + pub fn getresuid(ruid: *mut ::uid_t, euid: *mut ::uid_t, + suid: *mut ::uid_t) -> ::c_int; + pub fn getresgid(rgid: *mut ::gid_t, egid: *mut ::gid_t, + sgid: *mut ::gid_t) -> ::c_int; + pub fn acct(filename: *const ::c_char) -> ::c_int; + pub fn brk(addr: *mut ::c_void) -> ::c_int; + pub fn sbrk(increment: ::intptr_t) -> *mut ::c_void; + pub fn vfork() -> ::pid_t; + pub fn setresgid(rgid: ::gid_t, egid: ::gid_t, sgid: ::gid_t) -> ::c_int; + pub fn setresuid(ruid: ::uid_t, euid: ::uid_t, suid: ::uid_t) -> ::c_int; + pub fn wait4(pid: ::pid_t, status: *mut ::c_int, options: ::c_int, + rusage: *mut ::rusage) -> ::pid_t; + pub fn openpty(amaster: *mut ::c_int, + aslave: *mut ::c_int, + name: *mut ::c_char, + termp: *const termios, + winp: *const ::winsize) -> ::c_int; + pub fn execvpe(file: *const ::c_char, argv: *const *const ::c_char, + envp: *const *const ::c_char) -> ::c_int; + pub fn fexecve(fd: ::c_int, argv: *const *const ::c_char, + envp: *const *const ::c_char) + -> ::c_int; +} + +cfg_if! { + if #[cfg(target_os = "emscripten")] { + mod emscripten; + pub use self::emscripten::*; + } else if #[cfg(any(target_os = "linux", target_os = "fuchsia"))] { + mod linux; + pub use self::linux::*; + } else if #[cfg(target_os = "android")] { + mod android; + pub use self::android::*; + } else { + // Unknown target_os + } +} + // pub fn forkpty(amaster: *mut ::c_int, + // name: *mut ::c_char, + // termp: *const termios, + // winp: *const ::winsize) -> ::pid_t; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/solaris/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/solaris/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/solaris/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/solaris/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1457 @@ +use dox::{mem, Option}; + +pub type c_char = i8; +pub type c_long = i64; +pub type c_ulong = u64; + +pub type clockid_t = ::c_int; +pub type blkcnt_t = ::c_long; +pub type clock_t = ::c_long; +pub type daddr_t = ::c_long; +pub type dev_t = ::c_ulong; +pub type fsblkcnt_t = ::c_ulong; +pub type fsfilcnt_t = ::c_ulong; +pub type ino_t = ::c_ulong; +pub type key_t = ::c_int; +pub type major_t = ::c_uint; +pub type minor_t = ::c_uint; +pub type mode_t = ::c_uint; +pub type nlink_t = ::c_uint; +pub type rlim_t = ::c_ulong; +pub type speed_t = ::c_uint; +pub type tcflag_t = ::c_uint; +pub type time_t = ::c_long; +pub type wchar_t = ::c_int; +pub type nfds_t = ::c_ulong; + +pub type suseconds_t = ::c_long; +pub type off_t = ::c_long; +pub type useconds_t = ::c_uint; +pub type socklen_t = ::c_uint; +pub type sa_family_t = u16; +pub type pthread_t = ::c_uint; +pub type pthread_key_t = ::c_uint; +pub type blksize_t = ::c_int; +pub type nl_item = ::c_int; +pub type id_t = ::c_int; +pub type idtype_t = ::c_uint; + +pub enum timezone {} + +s! { + pub struct sockaddr { + pub sa_family: sa_family_t, + pub sa_data: [::c_char; 14], + } + + pub struct sockaddr_in { + pub sin_family: sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + pub sin_zero: [::c_char; 8] + } + + pub struct sockaddr_in6 { + pub sin6_family: sa_family_t, + pub sin6_port: ::in_port_t, + pub sin6_flowinfo: u32, + pub sin6_addr: ::in6_addr, + pub sin6_scope_id: u32, + pub __sin6_src_id: u32 + } + + pub struct sockaddr_un { + pub sun_family: sa_family_t, + pub sun_path: [c_char; 108] + } + + pub struct passwd { + pub pw_name: *mut ::c_char, + pub pw_passwd: *mut ::c_char, + pub pw_uid: ::uid_t, + pub pw_gid: ::gid_t, + pub pw_age: *mut ::c_char, + pub pw_comment: *mut ::c_char, + pub pw_gecos: *mut ::c_char, + pub pw_dir: *mut ::c_char, + pub pw_shell: *mut ::c_char + } + + pub struct ifaddrs { + pub ifa_next: *mut ifaddrs, + pub ifa_name: *mut ::c_char, + pub ifa_flags: ::c_ulong, + pub ifa_addr: *mut ::sockaddr, + pub ifa_netmask: *mut ::sockaddr, + pub ifa_dstaddr: *mut ::sockaddr, + pub ifa_data: *mut ::c_void + } + + pub struct tm { + pub tm_sec: ::c_int, + pub tm_min: ::c_int, + pub tm_hour: ::c_int, + pub tm_mday: ::c_int, + pub tm_mon: ::c_int, + pub tm_year: ::c_int, + pub tm_wday: ::c_int, + pub tm_yday: ::c_int, + pub tm_isdst: ::c_int + } + + pub struct utsname { + pub sysname: [::c_char; 257], + pub nodename: [::c_char; 257], + pub release: [::c_char; 257], + pub version: [::c_char; 257], + pub machine: [::c_char; 257], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::c_int, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::socklen_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::socklen_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct fd_set { + #[cfg(target_pointer_width = "64")] + fds_bits: [i64; FD_SETSIZE / 64], + #[cfg(target_pointer_width = "32")] + fds_bits: [i32; FD_SETSIZE / 32], + } + + pub struct pthread_attr_t { + __pthread_attrp: *mut ::c_void + } + + pub struct pthread_mutex_t { + __pthread_mutex_flag1: u16, + __pthread_mutex_flag2: u8, + __pthread_mutex_ceiling: u8, + __pthread_mutex_type: u16, + __pthread_mutex_magic: u16, + __pthread_mutex_lock: u64, + __pthread_mutex_data: u64 + } + + pub struct pthread_mutexattr_t { + __pthread_mutexattrp: *mut ::c_void + } + + pub struct pthread_cond_t { + __pthread_cond_flag: [u8; 4], + __pthread_cond_type: u16, + __pthread_cond_magic: u16, + __pthread_cond_data: u64 + } + + pub struct pthread_condattr_t { + __pthread_condattrp: *mut ::c_void, + } + + pub struct pthread_rwlock_t { + __pthread_rwlock_readers: i32, + __pthread_rwlock_type: u16, + __pthread_rwlock_magic: u16, + __pthread_rwlock_mutex: ::pthread_mutex_t, + __pthread_rwlock_readercv: ::pthread_cond_t, + __pthread_rwlock_writercv: ::pthread_cond_t + } + + pub struct pthread_rwlockattr_t { + __pthread_rwlockattrp: *mut ::c_void, + } + + pub struct dirent { + pub d_ino: ::ino_t, + pub d_off: ::off_t, + pub d_reclen: u16, + pub d_name: [::c_char; 3] + } + + pub struct glob_t { + pub gl_pathc: ::size_t, + pub gl_pathv: *mut *mut ::c_char, + pub gl_offs: ::size_t, + __unused1: *mut ::c_void, + __unused2: ::c_int, + __unused3: ::c_int, + __unused4: ::c_int, + __unused5: *mut ::c_void, + __unused6: *mut ::c_void, + __unused7: *mut ::c_void, + __unused8: *mut ::c_void, + __unused9: *mut ::c_void, + __unused10: *mut ::c_void, + } + + pub struct sockaddr_storage { + pub ss_family: ::sa_family_t, + __ss_pad1: [u8; 6], + __ss_align: i64, + __ss_pad2: [u8; 240], + } + + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + #[cfg(target_arch = "sparc64")] + __sparcv9_pad: ::c_int, + pub ai_addrlen: ::socklen_t, + pub ai_canonname: *mut ::c_char, + pub ai_addr: *mut ::sockaddr, + pub ai_next: *mut addrinfo, + } + + pub struct sigset_t { + bits: [u32; 4], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_code: ::c_int, + pub si_errno: ::c_int, + pub si_pad: ::c_int, + pub si_addr: *mut ::c_void, + __pad: [u8; 232], + } + + pub struct sigaction { + pub sa_flags: ::c_int, + pub sa_sigaction: ::sighandler_t, + pub sa_mask: sigset_t, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_size: ::size_t, + pub ss_flags: ::c_int, + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + pub f_fsid: ::c_ulong, + pub f_basetype: [::c_char; 16], + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + pub f_fstr: [::c_char; 32] + } + + pub struct sched_param { + pub sched_priority: ::c_int, + sched_pad: [::c_int; 8] + } + + pub struct Dl_info { + pub dli_fname: *const ::c_char, + pub dli_fbase: *mut ::c_void, + pub dli_sname: *const ::c_char, + pub dli_saddr: *mut ::c_void, + } + + pub struct stat { + pub st_dev: ::dev_t, + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + pub st_size: ::off_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + __unused: [::c_char; 16] + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_cc: [::cc_t; ::NCCS] + } + + pub struct lconv { + pub decimal_point: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + pub grouping: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub currency_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub int_frac_digits: ::c_char, + pub frac_digits: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + pub n_sign_posn: ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_n_cs_precedes: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + pub int_n_sign_posn: ::c_char, + } + + pub struct sem_t { + pub sem_count: u32, + pub sem_type: u16, + pub sem_magic: u16, + pub sem_pad1: [u64; 3], + pub sem_pad2: [u64; 2] + } + + pub struct flock { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_sysid: ::c_int, + pub l_pid: ::pid_t, + pub l_pad: [::c_long; 4] + } + + pub struct if_nameindex { + pub if_index: ::c_uint, + pub if_name: *mut ::c_char, + } + + pub struct port_event { + pub portev_events: ::c_int, + pub portev_source: ::c_ushort, + pub portev_pad: ::c_ushort, + pub portev_object: ::uintptr_t, + pub portev_user: *mut ::c_void, + } + + pub struct epoll_event { + pub events: ::uint32_t, + pub u64: ::uint64_t, + } +} + +pub const LC_CTYPE: ::c_int = 0; +pub const LC_NUMERIC: ::c_int = 1; +pub const LC_TIME: ::c_int = 2; +pub const LC_COLLATE: ::c_int = 3; +pub const LC_MONETARY: ::c_int = 4; +pub const LC_MESSAGES: ::c_int = 5; +pub const LC_ALL: ::c_int = 6; +pub const LC_CTYPE_MASK: ::c_int = (1 << LC_CTYPE); +pub const LC_NUMERIC_MASK: ::c_int = (1 << LC_NUMERIC); +pub const LC_TIME_MASK: ::c_int = (1 << LC_TIME); +pub const LC_COLLATE_MASK: ::c_int = (1 << LC_COLLATE); +pub const LC_MONETARY_MASK: ::c_int = (1 << LC_MONETARY); +pub const LC_MESSAGES_MASK: ::c_int = (1 << LC_MESSAGES); +pub const LC_ALL_MASK: ::c_int = LC_CTYPE_MASK + | LC_NUMERIC_MASK + | LC_TIME_MASK + | LC_COLLATE_MASK + | LC_MONETARY_MASK + | LC_MESSAGES_MASK; + +pub const DAY_1: ::nl_item = 1; +pub const DAY_2: ::nl_item = 2; +pub const DAY_3: ::nl_item = 3; +pub const DAY_4: ::nl_item = 4; +pub const DAY_5: ::nl_item = 5; +pub const DAY_6: ::nl_item = 6; +pub const DAY_7: ::nl_item = 7; + +pub const ABDAY_1: ::nl_item = 8; +pub const ABDAY_2: ::nl_item = 9; +pub const ABDAY_3: ::nl_item = 10; +pub const ABDAY_4: ::nl_item = 11; +pub const ABDAY_5: ::nl_item = 12; +pub const ABDAY_6: ::nl_item = 13; +pub const ABDAY_7: ::nl_item = 14; + +pub const MON_1: ::nl_item = 15; +pub const MON_2: ::nl_item = 16; +pub const MON_3: ::nl_item = 17; +pub const MON_4: ::nl_item = 18; +pub const MON_5: ::nl_item = 19; +pub const MON_6: ::nl_item = 20; +pub const MON_7: ::nl_item = 21; +pub const MON_8: ::nl_item = 22; +pub const MON_9: ::nl_item = 23; +pub const MON_10: ::nl_item = 24; +pub const MON_11: ::nl_item = 25; +pub const MON_12: ::nl_item = 26; + +pub const ABMON_1: ::nl_item = 27; +pub const ABMON_2: ::nl_item = 28; +pub const ABMON_3: ::nl_item = 29; +pub const ABMON_4: ::nl_item = 30; +pub const ABMON_5: ::nl_item = 31; +pub const ABMON_6: ::nl_item = 32; +pub const ABMON_7: ::nl_item = 33; +pub const ABMON_8: ::nl_item = 34; +pub const ABMON_9: ::nl_item = 35; +pub const ABMON_10: ::nl_item = 36; +pub const ABMON_11: ::nl_item = 37; +pub const ABMON_12: ::nl_item = 38; + +pub const RADIXCHAR: ::nl_item = 39; +pub const THOUSEP: ::nl_item = 40; +pub const YESSTR: ::nl_item = 41; +pub const NOSTR: ::nl_item = 42; +pub const CRNCYSTR: ::nl_item = 43; + +pub const D_T_FMT: ::nl_item = 44; +pub const D_FMT: ::nl_item = 45; +pub const T_FMT: ::nl_item = 46; +pub const AM_STR: ::nl_item = 47; +pub const PM_STR: ::nl_item = 48; + +pub const CODESET: ::nl_item = 49; +pub const T_FMT_AMPM: ::nl_item = 50; +pub const ERA: ::nl_item = 51; +pub const ERA_D_FMT: ::nl_item = 52; +pub const ERA_D_T_FMT: ::nl_item = 53; +pub const ERA_T_FMT: ::nl_item = 54; +pub const ALT_DIGITS: ::nl_item = 55; +pub const YESEXPR: ::nl_item = 56; +pub const NOEXPR: ::nl_item = 57; +pub const _DATE_FMT: ::nl_item = 58; +pub const MAXSTRMSG: ::nl_item = 58; + +pub const PATH_MAX: ::c_int = 1024; + +pub const SA_ONSTACK: ::c_int = 0x00000001; +pub const SA_RESETHAND: ::c_int = 0x00000002; +pub const SA_RESTART: ::c_int = 0x00000004; +pub const SA_SIGINFO: ::c_int = 0x00000008; +pub const SA_NODEFER: ::c_int = 0x00000010; +pub const SA_NOCLDWAIT: ::c_int = 0x00010000; +pub const SA_NOCLDSTOP: ::c_int = 0x00020000; + +pub const SS_ONSTACK: ::c_int = 1; +pub const SS_DISABLE: ::c_int = 2; + +pub const FIOCLEX: ::c_int = 0x20006601; +pub const FIONCLEX: ::c_int = 0x20006602; +pub const FIONREAD: ::c_int = 0x4004667f; +pub const FIONBIO: ::c_int = 0x8004667e; +pub const FIOASYNC: ::c_int = 0x8004667d; +pub const FIOSETOWN: ::c_int = 0x8004667c; +pub const FIOGETOWN: ::c_int = 0x4004667b; + +pub const SIGCHLD: ::c_int = 18; +pub const SIGBUS: ::c_int = 10; +pub const SIGINFO: ::c_int = 41; +pub const SIG_BLOCK: ::c_int = 1; +pub const SIG_UNBLOCK: ::c_int = 2; +pub const SIG_SETMASK: ::c_int = 3; + +pub const IPV6_UNICAST_HOPS: ::c_int = 0x5; +pub const IPV6_MULTICAST_IF: ::c_int = 0x6; +pub const IPV6_MULTICAST_HOPS: ::c_int = 0x7; +pub const IPV6_MULTICAST_LOOP: ::c_int = 0x8; +pub const IPV6_V6ONLY: ::c_int = 0x27; + +cfg_if! { + if #[cfg(target_pointer_width = "64")] { + pub const FD_SETSIZE: usize = 65536; + } else { + pub const FD_SETSIZE: usize = 1024; + } +} + +pub const ST_RDONLY: ::c_ulong = 1; +pub const ST_NOSUID: ::c_ulong = 2; + +pub const NI_MAXHOST: ::socklen_t = 1025; + +pub const EXIT_FAILURE: ::c_int = 1; +pub const EXIT_SUCCESS: ::c_int = 0; +pub const RAND_MAX: ::c_int = 32767; +pub const EOF: ::c_int = -1; +pub const SEEK_SET: ::c_int = 0; +pub const SEEK_CUR: ::c_int = 1; +pub const SEEK_END: ::c_int = 2; +pub const _IOFBF: ::c_int = 0; +pub const _IONBF: ::c_int = 4; +pub const _IOLBF: ::c_int = 64; +pub const BUFSIZ: ::c_uint = 1024; +pub const FOPEN_MAX: ::c_uint = 20; +pub const FILENAME_MAX: ::c_uint = 1024; +pub const L_tmpnam: ::c_uint = 25; +pub const TMP_MAX: ::c_uint = 17576; + +pub const O_RDONLY: ::c_int = 0; +pub const O_WRONLY: ::c_int = 1; +pub const O_RDWR: ::c_int = 2; +pub const O_SEARCH: ::c_int = 0x200000; +pub const O_EXEC: ::c_int = 0x400000; +pub const O_APPEND: ::c_int = 8; +pub const O_CREAT: ::c_int = 256; +pub const O_EXCL: ::c_int = 1024; +pub const O_NOCTTY: ::c_int = 2048; +pub const O_TRUNC: ::c_int = 512; +pub const O_CLOEXEC: ::c_int = 0x800000; +pub const O_ACCMODE: ::c_int = 0x600003; +pub const S_IFIFO: mode_t = 4096; +pub const S_IFCHR: mode_t = 8192; +pub const S_IFBLK: mode_t = 24576; +pub const S_IFDIR: mode_t = 16384; +pub const S_IFREG: mode_t = 32768; +pub const S_IFLNK: mode_t = 40960; +pub const S_IFSOCK: mode_t = 49152; +pub const S_IFMT: mode_t = 61440; +pub const S_IEXEC: mode_t = 64; +pub const S_IWRITE: mode_t = 128; +pub const S_IREAD: mode_t = 256; +pub const S_IRWXU: mode_t = 448; +pub const S_IXUSR: mode_t = 64; +pub const S_IWUSR: mode_t = 128; +pub const S_IRUSR: mode_t = 256; +pub const S_IRWXG: mode_t = 56; +pub const S_IXGRP: mode_t = 8; +pub const S_IWGRP: mode_t = 16; +pub const S_IRGRP: mode_t = 32; +pub const S_IRWXO: mode_t = 7; +pub const S_IXOTH: mode_t = 1; +pub const S_IWOTH: mode_t = 2; +pub const S_IROTH: mode_t = 4; +pub const F_OK: ::c_int = 0; +pub const R_OK: ::c_int = 4; +pub const W_OK: ::c_int = 2; +pub const X_OK: ::c_int = 1; +pub const STDIN_FILENO: ::c_int = 0; +pub const STDOUT_FILENO: ::c_int = 1; +pub const STDERR_FILENO: ::c_int = 2; +pub const F_LOCK: ::c_int = 1; +pub const F_TEST: ::c_int = 3; +pub const F_TLOCK: ::c_int = 2; +pub const F_ULOCK: ::c_int = 0; +pub const F_DUPFD_CLOEXEC: ::c_int = 37; +pub const F_SETLK: ::c_int = 6; +pub const F_SETLKW: ::c_int = 7; +pub const F_GETLK: ::c_int = 14; +pub const SIGHUP: ::c_int = 1; +pub const SIGINT: ::c_int = 2; +pub const SIGQUIT: ::c_int = 3; +pub const SIGILL: ::c_int = 4; +pub const SIGABRT: ::c_int = 6; +pub const SIGEMT: ::c_int = 7; +pub const SIGFPE: ::c_int = 8; +pub const SIGKILL: ::c_int = 9; +pub const SIGSEGV: ::c_int = 11; +pub const SIGSYS: ::c_int = 12; +pub const SIGPIPE: ::c_int = 13; +pub const SIGALRM: ::c_int = 14; +pub const SIGTERM: ::c_int = 15; +pub const SIGUSR1: ::c_int = 16; +pub const SIGUSR2: ::c_int = 17; +pub const SIGPWR: ::c_int = 19; +pub const SIGWINCH: ::c_int = 20; +pub const SIGURG: ::c_int = 21; +pub const SIGPOLL: ::c_int = 22; +pub const SIGIO: ::c_int = SIGPOLL; +pub const SIGSTOP: ::c_int = 23; +pub const SIGTSTP: ::c_int = 24; +pub const SIGCONT: ::c_int = 25; +pub const SIGTTIN: ::c_int = 26; +pub const SIGTTOU: ::c_int = 27; +pub const SIGVTALRM: ::c_int = 28; +pub const SIGPROF: ::c_int = 29; +pub const SIGXCPU: ::c_int = 30; +pub const SIGXFSZ: ::c_int = 31; + +pub const WNOHANG: ::c_int = 0x40; +pub const WUNTRACED: ::c_int = 0x04; + +pub const WEXITED: ::c_int = 0x01; +pub const WTRAPPED: ::c_int = 0x02; +pub const WSTOPPED: ::c_int = WUNTRACED; +pub const WCONTINUED: ::c_int = 0x08; +pub const WNOWAIT: ::c_int = 0x80; + +pub const AT_FDCWD: ::c_int = 0xffd19553; +pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x1000; + +// Solaris defines a great many more of these; we only expose the +// standardized ones. +pub const P_PID: idtype_t = 0; +pub const P_PGID: idtype_t = 2; +pub const P_ALL: idtype_t = 7; + +pub const PROT_NONE: ::c_int = 0; +pub const PROT_READ: ::c_int = 1; +pub const PROT_WRITE: ::c_int = 2; +pub const PROT_EXEC: ::c_int = 4; + +pub const MAP_SHARED: ::c_int = 0x0001; +pub const MAP_PRIVATE: ::c_int = 0x0002; +pub const MAP_FIXED: ::c_int = 0x0010; +pub const MAP_NORESERVE: ::c_int = 0x40; +pub const MAP_ANON: ::c_int = 0x0100; +pub const MAP_RENAME: ::c_int = 0x20; +pub const MAP_ALIGN: ::c_int = 0x200; +pub const MAP_TEXT: ::c_int = 0x400; +pub const MAP_INITDATA: ::c_int = 0x800; +pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const MS_SYNC: ::c_int = 0x0004; +pub const MS_ASYNC: ::c_int = 0x0001; +pub const MS_INVALIDATE: ::c_int = 0x0002; +pub const MS_INVALCURPROC: ::c_int = 0x0008; + +pub const EPERM: ::c_int = 1; +pub const ENOENT: ::c_int = 2; +pub const ESRCH: ::c_int = 3; +pub const EINTR: ::c_int = 4; +pub const EIO: ::c_int = 5; +pub const ENXIO: ::c_int = 6; +pub const E2BIG: ::c_int = 7; +pub const ENOEXEC: ::c_int = 8; +pub const EBADF: ::c_int = 9; +pub const ECHILD: ::c_int = 10; +pub const EAGAIN: ::c_int = 11; +pub const ENOMEM: ::c_int = 12; +pub const EACCES: ::c_int = 13; +pub const EFAULT: ::c_int = 14; +pub const ENOTBLK: ::c_int = 15; +pub const EBUSY: ::c_int = 16; +pub const EEXIST: ::c_int = 17; +pub const EXDEV: ::c_int = 18; +pub const ENODEV: ::c_int = 19; +pub const ENOTDIR: ::c_int = 20; +pub const EISDIR: ::c_int = 21; +pub const EINVAL: ::c_int = 22; +pub const ENFILE: ::c_int = 23; +pub const EMFILE: ::c_int = 24; +pub const ENOTTY: ::c_int = 25; +pub const ETXTBSY: ::c_int = 26; +pub const EFBIG: ::c_int = 27; +pub const ENOSPC: ::c_int = 28; +pub const ESPIPE: ::c_int = 29; +pub const EROFS: ::c_int = 30; +pub const EMLINK: ::c_int = 31; +pub const EPIPE: ::c_int = 32; +pub const EDOM: ::c_int = 33; +pub const ERANGE: ::c_int = 34; +pub const ENOMSG: ::c_int = 35; +pub const EIDRM: ::c_int = 36; +pub const ECHRNG: ::c_int = 37; +pub const EL2NSYNC: ::c_int = 38; +pub const EL3HLT: ::c_int = 39; +pub const EL3RST: ::c_int = 40; +pub const ELNRNG: ::c_int = 41; +pub const EUNATCH: ::c_int = 42; +pub const ENOCSI: ::c_int = 43; +pub const EL2HLT: ::c_int = 44; +pub const EDEADLK: ::c_int = 45; +pub const ENOLCK: ::c_int = 46; +pub const ECANCELED: ::c_int = 47; +pub const ENOTSUP: ::c_int = 48; +pub const EDQUOT: ::c_int = 49; +pub const EBADE: ::c_int = 50; +pub const EBADR: ::c_int = 51; +pub const EXFULL: ::c_int = 52; +pub const ENOANO: ::c_int = 53; +pub const EBADRQC: ::c_int = 54; +pub const EBADSLT: ::c_int = 55; +pub const EDEADLOCK: ::c_int = 56; +pub const EBFONT: ::c_int = 57; +pub const EOWNERDEAD: ::c_int = 58; +pub const ENOTRECOVERABLE: ::c_int = 59; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const ELOCKUNMAPPED: ::c_int = 72; +pub const ENOTACTIVE: ::c_int = 73; +pub const EMULTIHOP: ::c_int = 74; +pub const EADI: ::c_int = 75; +pub const EBADMSG: ::c_int = 77; +pub const ENAMETOOLONG: ::c_int = 78; +pub const EOVERFLOW: ::c_int = 79; +pub const ENOTUNIQ: ::c_int = 80; +pub const EBADFD: ::c_int = 81; +pub const EREMCHG: ::c_int = 82; +pub const ELIBACC: ::c_int = 83; +pub const ELIBBAD: ::c_int = 84; +pub const ELIBSCN: ::c_int = 85; +pub const ELIBMAX: ::c_int = 86; +pub const ELIBEXEC: ::c_int = 87; +pub const EILSEQ: ::c_int = 88; +pub const ENOSYS: ::c_int = 89; +pub const ELOOP: ::c_int = 90; +pub const ERESTART: ::c_int = 91; +pub const ESTRPIPE: ::c_int = 92; +pub const ENOTEMPTY: ::c_int = 93; +pub const EUSERS: ::c_int = 94; +pub const ENOTSOCK: ::c_int = 95; +pub const EDESTADDRREQ: ::c_int = 96; +pub const EMSGSIZE: ::c_int = 97; +pub const EPROTOTYPE: ::c_int = 98; +pub const ENOPROTOOPT: ::c_int = 99; +pub const EPROTONOSUPPORT: ::c_int = 120; +pub const ESOCKTNOSUPPORT: ::c_int = 121; +pub const EOPNOTSUPP: ::c_int = 122; +pub const EPFNOSUPPORT: ::c_int = 123; +pub const EAFNOSUPPORT: ::c_int = 124; +pub const EADDRINUSE: ::c_int = 125; +pub const EADDRNOTAVAIL: ::c_int = 126; +pub const ENETDOWN: ::c_int = 127; +pub const ENETUNREACH: ::c_int = 128; +pub const ENETRESET: ::c_int = 129; +pub const ECONNABORTED: ::c_int = 130; +pub const ECONNRESET: ::c_int = 131; +pub const ENOBUFS: ::c_int = 132; +pub const EISCONN: ::c_int = 133; +pub const ENOTCONN: ::c_int = 134; +pub const ESHUTDOWN: ::c_int = 143; +pub const ETOOMANYREFS: ::c_int = 144; +pub const ETIMEDOUT: ::c_int = 145; +pub const ECONNREFUSED: ::c_int = 146; +pub const EHOSTDOWN: ::c_int = 147; +pub const EHOSTUNREACH: ::c_int = 148; +pub const EWOULDBLOCK: ::c_int = EAGAIN; +pub const EALREADY: ::c_int = 149; +pub const EINPROGRESS: ::c_int = 150; + +pub const EAI_AGAIN: ::c_int = 2; +pub const EAI_BADFLAGS: ::c_int = 3; +pub const EAI_FAIL: ::c_int = 4; +pub const EAI_FAMILY: ::c_int = 5; +pub const EAI_MEMORY: ::c_int = 6; +pub const EAI_NODATA: ::c_int = 7; +pub const EAI_NONAME: ::c_int = 8; +pub const EAI_SERVICE: ::c_int = 9; +pub const EAI_SOCKTYPE: ::c_int = 10; +pub const EAI_SYSTEM: ::c_int = 11; +pub const EAI_OVERFLOW: ::c_int = 12; + +pub const F_DUPFD: ::c_int = 0; +pub const F_GETFD: ::c_int = 1; +pub const F_SETFD: ::c_int = 2; +pub const F_GETFL: ::c_int = 3; +pub const F_SETFL: ::c_int = 4; + +pub const SIGTRAP: ::c_int = 5; + +pub const GLOB_APPEND : ::c_int = 32; +pub const GLOB_DOOFFS : ::c_int = 16; +pub const GLOB_ERR : ::c_int = 1; +pub const GLOB_MARK : ::c_int = 2; +pub const GLOB_NOCHECK : ::c_int = 8; +pub const GLOB_NOSORT : ::c_int = 4; +pub const GLOB_NOESCAPE: ::c_int = 64; + +pub const GLOB_NOSPACE : ::c_int = -2; +pub const GLOB_ABORTED : ::c_int = -1; +pub const GLOB_NOMATCH : ::c_int = -3; + +pub const POLLIN: ::c_short = 0x1; +pub const POLLPRI: ::c_short = 0x2; +pub const POLLOUT: ::c_short = 0x4; +pub const POLLERR: ::c_short = 0x8; +pub const POLLHUP: ::c_short = 0x10; +pub const POLLNVAL: ::c_short = 0x20; + +pub const POSIX_MADV_NORMAL: ::c_int = 0; +pub const POSIX_MADV_RANDOM: ::c_int = 1; +pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_MADV_WILLNEED: ::c_int = 3; +pub const POSIX_MADV_DONTNEED: ::c_int = 4; + +pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; +pub const PTHREAD_CREATE_DETACHED: ::c_int = 0x40; +pub const PTHREAD_PROCESS_SHARED: ::c_int = 1; +pub const PTHREAD_PROCESS_PRIVATE: ::c_ushort = 0; +pub const PTHREAD_STACK_MIN: ::size_t = 4096; + +pub const SIGSTKSZ: ::size_t = 8192; + +// https://illumos.org/man/3c/clock_gettime +// https://github.com/illumos/illumos-gate/ +// blob/HEAD/usr/src/lib/libc/amd64/sys/__clock_gettime.s +// clock_gettime(3c) doesn't seem to accept anything other than CLOCK_REALTIME +// or __CLOCK_REALTIME0 +// +// https://github.com/illumos/illumos-gate/ +// blob/HEAD/usr/src/uts/common/sys/time_impl.h +// Confusing! CLOCK_HIGHRES==CLOCK_MONOTONIC==4 +// __CLOCK_REALTIME0==0 is an obsoleted version of CLOCK_REALTIME==3 +pub const CLOCK_REALTIME: ::clockid_t = 3; +pub const CLOCK_MONOTONIC: ::clockid_t = 4; +pub const TIMER_RELTIME: ::c_int = 0; +pub const TIMER_ABSTIME: ::c_int = 1; + +pub const RLIMIT_CPU: ::c_int = 0; +pub const RLIMIT_FSIZE: ::c_int = 1; +pub const RLIMIT_DATA: ::c_int = 2; +pub const RLIMIT_STACK: ::c_int = 3; +pub const RLIMIT_CORE: ::c_int = 4; +pub const RLIMIT_NOFILE: ::c_int = 5; +pub const RLIMIT_VMEM: ::c_int = 6; +pub const RLIMIT_AS: ::c_int = RLIMIT_VMEM; + +pub const RLIM_NLIMITS: rlim_t = 7; +pub const RLIM_INFINITY: rlim_t = 0x7fffffff; + +pub const RUSAGE_SELF: ::c_int = 0; +pub const RUSAGE_CHILDREN: ::c_int = -1; + +pub const MADV_NORMAL: ::c_int = 0; +pub const MADV_RANDOM: ::c_int = 1; +pub const MADV_SEQUENTIAL: ::c_int = 2; +pub const MADV_WILLNEED: ::c_int = 3; +pub const MADV_DONTNEED: ::c_int = 4; +pub const MADV_FREE: ::c_int = 5; + +pub const AF_INET: ::c_int = 2; +pub const AF_INET6: ::c_int = 26; +pub const AF_UNIX: ::c_int = 1; +pub const SOCK_DGRAM: ::c_int = 1; +pub const SOCK_STREAM: ::c_int = 2; +pub const SOCK_RAW: ::c_int = 4; +pub const SOCK_RDM: ::c_int = 5; +pub const SOCK_SEQPACKET: ::c_int = 6; +pub const IP_MULTICAST_IF: ::c_int = 16; +pub const IP_MULTICAST_TTL: ::c_int = 17; +pub const IP_MULTICAST_LOOP: ::c_int = 18; +pub const IP_TTL: ::c_int = 4; +pub const IP_HDRINCL: ::c_int = 2; +pub const IP_ADD_MEMBERSHIP: ::c_int = 19; +pub const IP_DROP_MEMBERSHIP: ::c_int = 20; +pub const IPV6_JOIN_GROUP: ::c_int = 9; +pub const IPV6_LEAVE_GROUP: ::c_int = 10; + +pub const TCP_NODELAY: ::c_int = 1; +pub const TCP_KEEPIDLE: ::c_int = 34; +pub const SOL_SOCKET: ::c_int = 0xffff; +pub const SO_DEBUG: ::c_int = 0x01; +pub const SO_ACCEPTCONN: ::c_int = 0x0002; +pub const SO_REUSEADDR: ::c_int = 0x0004; +pub const SO_KEEPALIVE: ::c_int = 0x0008; +pub const SO_DONTROUTE: ::c_int = 0x0010; +pub const SO_BROADCAST: ::c_int = 0x0020; +pub const SO_USELOOPBACK: ::c_int = 0x0040; +pub const SO_LINGER: ::c_int = 0x0080; +pub const SO_OOBINLINE: ::c_int = 0x0100; +pub const SO_SNDBUF: ::c_int = 0x1001; +pub const SO_RCVBUF: ::c_int = 0x1002; +pub const SO_SNDLOWAT: ::c_int = 0x1003; +pub const SO_RCVLOWAT: ::c_int = 0x1004; +pub const SO_SNDTIMEO: ::c_int = 0x1005; +pub const SO_RCVTIMEO: ::c_int = 0x1006; +pub const SO_ERROR: ::c_int = 0x1007; +pub const SO_TYPE: ::c_int = 0x1008; + +pub const MSG_PEEK: ::c_int = 0x2; + +// https://docs.oracle.com/cd/E23824_01/html/821-1475/if-7p.html +pub const IFF_UP: ::c_int = 0x0000000001; // Address is up +pub const IFF_BROADCAST: ::c_int = 0x0000000002; // Broadcast address valid +pub const IFF_DEBUG: ::c_int = 0x0000000004; // Turn on debugging +pub const IFF_LOOPBACK: ::c_int = 0x0000000008; // Loopback net +pub const IFF_POINTOPOINT: ::c_int = 0x0000000010; // Interface is p-to-p +pub const IFF_NOTRAILERS: ::c_int = 0x0000000020; // Avoid use of trailers +pub const IFF_RUNNING: ::c_int = 0x0000000040; // Resources allocated +pub const IFF_NOARP: ::c_int = 0x0000000080; // No address res. protocol +pub const IFF_PROMISC: ::c_int = 0x0000000100; // Receive all packets +pub const IFF_ALLMULTI: ::c_int = 0x0000000200; // Receive all multicast pkts +pub const IFF_INTELLIGENT: ::c_int = 0x0000000400; // Protocol code on board +pub const IFF_MULTICAST: ::c_int = 0x0000000800; // Supports multicast +// Multicast using broadcst. add. +pub const IFF_MULTI_BCAST: ::c_int = 0x0000001000; +pub const IFF_UNNUMBERED: ::c_int = 0x0000002000; // Non-unique address +pub const IFF_DHCPRUNNING: ::c_int = 0x0000004000; // DHCP controls interface +pub const IFF_PRIVATE: ::c_int = 0x0000008000; // Do not advertise +pub const IFF_NOXMIT: ::c_int = 0x0000010000; // Do not transmit pkts +// No address - just on-link subnet +pub const IFF_NOLOCAL: ::c_int = 0x0000020000; +pub const IFF_DEPRECATED: ::c_int = 0x0000040000; // Address is deprecated +pub const IFF_ADDRCONF: ::c_int = 0x0000080000; // Addr. from stateless addrconf +pub const IFF_ROUTER: ::c_int = 0x0000100000; // Router on interface +pub const IFF_NONUD: ::c_int = 0x0000200000; // No NUD on interface +pub const IFF_ANYCAST: ::c_int = 0x0000400000; // Anycast address +pub const IFF_NORTEXCH: ::c_int = 0x0000800000; // Don't xchange rout. info +pub const IFF_IPV4: ::c_int = 0x0001000000; // IPv4 interface +pub const IFF_IPV6: ::c_int = 0x0002000000; // IPv6 interface +pub const IFF_NOFAILOVER: ::c_int = 0x0008000000; // in.mpathd test address +pub const IFF_FAILED: ::c_int = 0x0010000000; // Interface has failed +pub const IFF_STANDBY: ::c_int = 0x0020000000; // Interface is a hot-spare +pub const IFF_INACTIVE: ::c_int = 0x0040000000; // Functioning but not used +pub const IFF_OFFLINE: ::c_int = 0x0080000000; // Interface is offline +// If CoS marking is supported +pub const IFF_COS_ENABLED: ::c_longlong = 0x0200000000; +pub const IFF_PREFERRED: ::c_longlong = 0x0400000000; // Prefer as source addr. +pub const IFF_TEMPORARY: ::c_longlong = 0x0800000000; // RFC3041 +pub const IFF_FIXEDMTU: ::c_longlong = 0x1000000000; // MTU set with SIOCSLIFMTU +pub const IFF_VIRTUAL: ::c_longlong = 0x2000000000; // Cannot send/receive pkts +pub const IFF_DUPLICATE: ::c_longlong = 0x4000000000; // Local address in use +pub const IFF_IPMP: ::c_longlong = 0x8000000000; // IPMP IP interface + +pub const SHUT_RD: ::c_int = 0; +pub const SHUT_WR: ::c_int = 1; +pub const SHUT_RDWR: ::c_int = 2; + +pub const LOCK_SH: ::c_int = 1; +pub const LOCK_EX: ::c_int = 2; +pub const LOCK_NB: ::c_int = 4; +pub const LOCK_UN: ::c_int = 8; + +pub const F_RDLCK: ::c_short = 1; +pub const F_WRLCK: ::c_short = 2; +pub const F_UNLCK: ::c_short = 3; + +pub const O_SYNC: ::c_int = 16; +pub const O_NONBLOCK: ::c_int = 128; + +pub const IPPROTO_RAW: ::c_int = 255; + +pub const _PC_LINK_MAX: ::c_int = 1; +pub const _PC_MAX_CANON: ::c_int = 2; +pub const _PC_MAX_INPUT: ::c_int = 3; +pub const _PC_NAME_MAX: ::c_int = 4; +pub const _PC_PATH_MAX: ::c_int = 5; +pub const _PC_PIPE_BUF: ::c_int = 6; +pub const _PC_NO_TRUNC: ::c_int = 7; +pub const _PC_VDISABLE: ::c_int = 8; +pub const _PC_CHOWN_RESTRICTED: ::c_int = 9; +pub const _PC_ASYNC_IO: ::c_int = 10; +pub const _PC_PRIO_IO: ::c_int = 11; +pub const _PC_SYNC_IO: ::c_int = 12; +pub const _PC_ALLOC_SIZE_MIN: ::c_int = 13; +pub const _PC_REC_INCR_XFER_SIZE: ::c_int = 14; +pub const _PC_REC_MAX_XFER_SIZE: ::c_int = 15; +pub const _PC_REC_MIN_XFER_SIZE: ::c_int = 16; +pub const _PC_REC_XFER_ALIGN: ::c_int = 17; +pub const _PC_SYMLINK_MAX: ::c_int = 18; +pub const _PC_2_SYMLINKS: ::c_int = 19; +pub const _PC_ACL_ENABLED: ::c_int = 20; +pub const _PC_MIN_HOLE_SIZE: ::c_int = 21; +pub const _PC_CASE_BEHAVIOR: ::c_int = 22; +pub const _PC_SATTR_ENABLED: ::c_int = 23; +pub const _PC_SATTR_EXISTS: ::c_int = 24; +pub const _PC_ACCESS_FILTERING: ::c_int = 25; +pub const _PC_TIMESTAMP_RESOLUTION: ::c_int = 26; +pub const _PC_FILESIZEBITS: ::c_int = 67; +pub const _PC_XATTR_ENABLED: ::c_int = 100; +pub const _PC_LAST: ::c_int = 101; +pub const _PC_XATTR_EXISTS: ::c_int = 101; + +pub const _SC_ARG_MAX: ::c_int = 1; +pub const _SC_CHILD_MAX: ::c_int = 2; +pub const _SC_CLK_TCK: ::c_int = 3; +pub const _SC_NGROUPS_MAX: ::c_int = 4; +pub const _SC_OPEN_MAX: ::c_int = 5; +pub const _SC_JOB_CONTROL: ::c_int = 6; +pub const _SC_SAVED_IDS: ::c_int = 7; +pub const _SC_VERSION: ::c_int = 8; +pub const _SC_PASS_MAX: ::c_int = 9; +pub const _SC_LOGNAME_MAX: ::c_int = 10; +pub const _SC_PAGESIZE: ::c_int = 11; +pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; +pub const _SC_XOPEN_VERSION: ::c_int = 12; +pub const _SC_NPROCESSORS_CONF: ::c_int = 14; +pub const _SC_NPROCESSORS_ONLN: ::c_int = 15; +pub const _SC_STREAM_MAX: ::c_int = 16; +pub const _SC_TZNAME_MAX: ::c_int = 17; +pub const _SC_AIO_LISTIO_MAX: ::c_int = 18; +pub const _SC_AIO_MAX: ::c_int = 19; +pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 20; +pub const _SC_ASYNCHRONOUS_IO: ::c_int = 21; +pub const _SC_DELAYTIMER_MAX: ::c_int = 22; +pub const _SC_FSYNC: ::c_int = 23; +pub const _SC_MAPPED_FILES: ::c_int = 24; +pub const _SC_MEMLOCK: ::c_int = 25; +pub const _SC_MEMLOCK_RANGE: ::c_int = 26; +pub const _SC_MEMORY_PROTECTION: ::c_int = 27; +pub const _SC_MESSAGE_PASSING: ::c_int = 28; +pub const _SC_MQ_OPEN_MAX: ::c_int = 29; +pub const _SC_MQ_PRIO_MAX: ::c_int = 30; +pub const _SC_PRIORITIZED_IO: ::c_int = 31; +pub const _SC_PRIORITY_SCHEDULING: ::c_int = 32; +pub const _SC_REALTIME_SIGNALS: ::c_int = 33; +pub const _SC_RTSIG_MAX: ::c_int = 34; +pub const _SC_SEMAPHORES: ::c_int = 35; +pub const _SC_SEM_NSEMS_MAX: ::c_int = 36; +pub const _SC_SEM_VALUE_MAX: ::c_int = 37; +pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 38; +pub const _SC_SIGQUEUE_MAX: ::c_int = 39; +pub const _SC_SIGRT_MIN: ::c_int = 40; +pub const _SC_SIGRT_MAX: ::c_int = 41; +pub const _SC_SYNCHRONIZED_IO: ::c_int = 42; +pub const _SC_TIMERS: ::c_int = 43; +pub const _SC_TIMER_MAX: ::c_int = 44; +pub const _SC_2_C_BIND: ::c_int = 45; +pub const _SC_2_C_DEV: ::c_int = 46; +pub const _SC_2_C_VERSION: ::c_int = 47; +pub const _SC_2_FORT_DEV: ::c_int = 48; +pub const _SC_2_FORT_RUN: ::c_int = 49; +pub const _SC_2_LOCALEDEF: ::c_int = 50; +pub const _SC_2_SW_DEV: ::c_int = 51; +pub const _SC_2_UPE: ::c_int = 52; +pub const _SC_2_VERSION: ::c_int = 53; +pub const _SC_BC_BASE_MAX: ::c_int = 54; +pub const _SC_BC_DIM_MAX: ::c_int = 55; +pub const _SC_BC_SCALE_MAX: ::c_int = 56; +pub const _SC_BC_STRING_MAX: ::c_int = 57; +pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 58; +pub const _SC_EXPR_NEST_MAX: ::c_int = 59; +pub const _SC_LINE_MAX: ::c_int = 60; +pub const _SC_RE_DUP_MAX: ::c_int = 61; +pub const _SC_XOPEN_CRYPT: ::c_int = 62; +pub const _SC_XOPEN_ENH_I18N: ::c_int = 63; +pub const _SC_XOPEN_SHM: ::c_int = 64; +pub const _SC_2_CHAR_TERM: ::c_int = 66; +pub const _SC_XOPEN_XCU_VERSION: ::c_int = 67; +pub const _SC_ATEXIT_MAX: ::c_int = 76; +pub const _SC_IOV_MAX: ::c_int = 77; +pub const _SC_XOPEN_UNIX: ::c_int = 78; +pub const _SC_T_IOV_MAX: ::c_int = 79; +pub const _SC_PHYS_PAGES: ::c_int = 500; +pub const _SC_AVPHYS_PAGES: ::c_int = 501; +pub const _SC_COHER_BLKSZ: ::c_int = 503; +pub const _SC_SPLIT_CACHE: ::c_int = 504; +pub const _SC_ICACHE_SZ: ::c_int = 505; +pub const _SC_DCACHE_SZ: ::c_int = 506; +pub const _SC_ICACHE_LINESZ: ::c_int = 507; +pub const _SC_DCACHE_LINESZ: ::c_int = 508; +pub const _SC_ICACHE_BLKSZ: ::c_int = 509; +pub const _SC_DCACHE_BLKSZ: ::c_int = 510; +pub const _SC_DCACHE_TBLKSZ: ::c_int = 511; +pub const _SC_ICACHE_ASSOC: ::c_int = 512; +pub const _SC_DCACHE_ASSOC: ::c_int = 513; +pub const _SC_MAXPID: ::c_int = 514; +pub const _SC_STACK_PROT: ::c_int = 515; +pub const _SC_NPROCESSORS_MAX: ::c_int = 516; +pub const _SC_CPUID_MAX: ::c_int = 517; +pub const _SC_EPHID_MAX: ::c_int = 518; +pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 568; +pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 569; +pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 570; +pub const _SC_LOGIN_NAME_MAX: ::c_int = 571; +pub const _SC_THREAD_KEYS_MAX: ::c_int = 572; +pub const _SC_THREAD_STACK_MIN: ::c_int = 573; +pub const _SC_THREAD_THREADS_MAX: ::c_int = 574; +pub const _SC_TTY_NAME_MAX: ::c_int = 575; +pub const _SC_THREADS: ::c_int = 576; +pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 577; +pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 578; +pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 579; +pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 580; +pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 581; +pub const _SC_THREAD_PROCESS_SHARED: ::c_int = 582; +pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 583; +pub const _SC_XOPEN_LEGACY: ::c_int = 717; +pub const _SC_XOPEN_REALTIME: ::c_int = 718; +pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 719; +pub const _SC_XBS5_ILP32_OFF32: ::c_int = 720; +pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 721; +pub const _SC_XBS5_LP64_OFF64: ::c_int = 722; +pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 723; +pub const _SC_2_PBS: ::c_int = 724; +pub const _SC_2_PBS_ACCOUNTING: ::c_int = 725; +pub const _SC_2_PBS_CHECKPOINT: ::c_int = 726; +pub const _SC_2_PBS_LOCATE: ::c_int = 728; +pub const _SC_2_PBS_MESSAGE: ::c_int = 729; +pub const _SC_2_PBS_TRACK: ::c_int = 730; +pub const _SC_ADVISORY_INFO: ::c_int = 731; +pub const _SC_BARRIERS: ::c_int = 732; +pub const _SC_CLOCK_SELECTION: ::c_int = 733; +pub const _SC_CPUTIME: ::c_int = 734; +pub const _SC_HOST_NAME_MAX: ::c_int = 735; +pub const _SC_MONOTONIC_CLOCK: ::c_int = 736; +pub const _SC_READER_WRITER_LOCKS: ::c_int = 737; +pub const _SC_REGEXP: ::c_int = 738; +pub const _SC_SHELL: ::c_int = 739; +pub const _SC_SPAWN: ::c_int = 740; +pub const _SC_SPIN_LOCKS: ::c_int = 741; +pub const _SC_SPORADIC_SERVER: ::c_int = 742; +pub const _SC_SS_REPL_MAX: ::c_int = 743; +pub const _SC_SYMLOOP_MAX: ::c_int = 744; +pub const _SC_THREAD_CPUTIME: ::c_int = 745; +pub const _SC_THREAD_SPORADIC_SERVER: ::c_int = 746; +pub const _SC_TIMEOUTS: ::c_int = 747; +pub const _SC_TRACE: ::c_int = 748; +pub const _SC_TRACE_EVENT_FILTER: ::c_int = 749; +pub const _SC_TRACE_EVENT_NAME_MAX: ::c_int = 750; +pub const _SC_TRACE_INHERIT: ::c_int = 751; +pub const _SC_TRACE_LOG: ::c_int = 752; +pub const _SC_TRACE_NAME_MAX: ::c_int = 753; +pub const _SC_TRACE_SYS_MAX: ::c_int = 754; +pub const _SC_TRACE_USER_EVENT_MAX: ::c_int = 755; +pub const _SC_TYPED_MEMORY_OBJECTS: ::c_int = 756; +pub const _SC_V6_ILP32_OFF32: ::c_int = 757; +pub const _SC_V6_ILP32_OFFBIG: ::c_int = 758; +pub const _SC_V6_LP64_OFF64: ::c_int = 759; +pub const _SC_V6_LPBIG_OFFBIG: ::c_int = 760; +pub const _SC_XOPEN_STREAMS: ::c_int = 761; +pub const _SC_IPV6: ::c_int = 762; +pub const _SC_RAW_SOCKETS: ::c_int = 763; + +pub const _MUTEX_MAGIC: u16 = 0x4d58; // MX +pub const _COND_MAGIC: u16 = 0x4356; // CV +pub const _RWL_MAGIC: u16 = 0x5257; // RW + +pub const NCCS: usize = 19; + +pub const LOG_CRON: ::c_int = 15 << 3; + +pub const SYS_epoll_create: ::c_long = 213; +pub const SYS_epoll_create1: ::c_long = 291; + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + __pthread_mutex_flag1: 0, + __pthread_mutex_flag2: 0, + __pthread_mutex_ceiling: 0, + __pthread_mutex_type: PTHREAD_PROCESS_PRIVATE, + __pthread_mutex_magic: _MUTEX_MAGIC, + __pthread_mutex_lock: 0, + __pthread_mutex_data: 0 +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + __pthread_cond_flag: [0; 4], + __pthread_cond_type: PTHREAD_PROCESS_PRIVATE, + __pthread_cond_magic: _COND_MAGIC, + __pthread_cond_data: 0 +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + __pthread_rwlock_readers: 0, + __pthread_rwlock_type: PTHREAD_PROCESS_PRIVATE, + __pthread_rwlock_magic: _RWL_MAGIC, + __pthread_rwlock_mutex: PTHREAD_MUTEX_INITIALIZER, + __pthread_rwlock_readercv: PTHREAD_COND_INITIALIZER, + __pthread_rwlock_writercv: PTHREAD_COND_INITIALIZER +}; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 4; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; + +pub const RTLD_NEXT: *mut ::c_void = -1isize as *mut ::c_void; +pub const RTLD_DEFAULT: *mut ::c_void = -2isize as *mut ::c_void; +pub const RTLD_SELF: *mut ::c_void = -3isize as *mut ::c_void; +pub const RTLD_PROBE: *mut ::c_void = -4isize as *mut ::c_void; + +pub const RTLD_LAZY: ::c_int = 0x1; +pub const RTLD_NOW: ::c_int = 0x2; +pub const RTLD_NOLOAD: ::c_int = 0x4; +pub const RTLD_GLOBAL: ::c_int = 0x100; +pub const RTLD_LOCAL: ::c_int = 0x0; +pub const RTLD_PARENT: ::c_int = 0x200; +pub const RTLD_GROUP: ::c_int = 0x400; +pub const RTLD_WORLD: ::c_int = 0x800; +pub const RTLD_NODELETE: ::c_int = 0x1000; +pub const RTLD_FIRST: ::c_int = 0x2000; +pub const RTLD_CONFGEN: ::c_int = 0x10000; + +pub const PORT_SOURCE_AIO: ::c_int = 1; +pub const PORT_SOURCE_TIMER: ::c_int = 2; +pub const PORT_SOURCE_USER: ::c_int = 3; +pub const PORT_SOURCE_FD: ::c_int = 4; +pub const PORT_SOURCE_ALERT: ::c_int = 5; +pub const PORT_SOURCE_MQ: ::c_int = 6; +pub const PORT_SOURCE_FILE: ::c_int = 7; +pub const PORT_SOURCE_POSTWAIT: ::c_int = 8; +pub const PORT_SOURCE_SIGNAL: ::c_int = 9; + +pub const EPOLLIN: ::c_int = 0x1; +pub const EPOLLPRI: ::c_int = 0x2; +pub const EPOLLOUT: ::c_int = 0x4; +pub const EPOLLRDNORM: ::c_int = 0x40; +pub const EPOLLRDBAND: ::c_int = 0x80; +pub const EPOLLWRNORM: ::c_int = 0x100; +pub const EPOLLWRBAND: ::c_int = 0x200; +pub const EPOLLMSG: ::c_int = 0x400; +pub const EPOLLERR: ::c_int = 0x8; +pub const EPOLLHUP: ::c_int = 0x10; +pub const EPOLLET: ::c_int = 0x80000000; +pub const EPOLLRDHUP: ::c_int = 0x2000; +pub const EPOLLEXCLUSIVE: ::c_int = 0x10000000; +pub const EPOLLONESHOT: ::c_int = 0x40000000; +pub const EPOLL_CLOEXEC: ::c_int = 0x02000000; +pub const EPOLL_CTL_ADD: ::c_int = 1; +pub const EPOLL_CTL_MOD: ::c_int = 3; +pub const EPOLL_CTL_DEL: ::c_int = 2; + +f! { + pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { + let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; + let fd = fd as usize; + (*set).fds_bits[fd / bits] &= !(1 << (fd % bits)); + return + } + + pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { + let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; + let fd = fd as usize; + return ((*set).fds_bits[fd / bits] & (1 << (fd % bits))) != 0 + } + + pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { + let bits = mem::size_of_val(&(*set).fds_bits[0]) * 8; + let fd = fd as usize; + (*set).fds_bits[fd / bits] |= 1 << (fd % bits); + return + } + + pub fn FD_ZERO(set: *mut fd_set) -> () { + for slot in (*set).fds_bits.iter_mut() { + *slot = 0; + } + } + + pub fn WIFEXITED(status: ::c_int) -> bool { + (status & 0xFF) == 0 + } + + pub fn WEXITSTATUS(status: ::c_int) -> ::c_int { + (status >> 8) & 0xFF + } + + pub fn WTERMSIG(status: ::c_int) -> ::c_int { + status & 0x7F + } +} + +extern { + pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; + pub fn freeifaddrs(ifa: *mut ::ifaddrs); + + pub fn stack_getbounds(sp: *mut ::stack_t) -> ::c_int; + pub fn mincore(addr: *const ::c_void, len: ::size_t, + vec: *mut c_char) -> ::c_int; + pub fn setgroups(ngroups: ::c_int, + ptr: *const ::gid_t) -> ::c_int; + pub fn ioctl(fildes: ::c_int, request: ::c_int, ...) -> ::c_int; + pub fn mprotect(addr: *const ::c_void, len: ::size_t, prot: ::c_int) + -> ::c_int; + pub fn ___errno() -> *mut ::c_int; + pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_nanosleep(clk_id: ::clockid_t, + flags: ::c_int, + rqtp: *const ::timespec, + rmtp: *mut ::timespec) -> ::c_int; + pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; + pub fn getnameinfo(sa: *const ::sockaddr, + salen: ::socklen_t, + host: *mut ::c_char, + hostlen: ::socklen_t, + serv: *mut ::c_char, + sevlen: ::socklen_t, + flags: ::c_int) -> ::c_int; + pub fn setpwent(); + pub fn endpwent(); + pub fn getpwent() -> *mut passwd; + pub fn fdatasync(fd: ::c_int) -> ::c_int; + pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; + pub fn duplocale(base: ::locale_t) -> ::locale_t; + pub fn freelocale(loc: ::locale_t); + pub fn newlocale(mask: ::c_int, + locale: *const ::c_char, + base: ::locale_t) -> ::locale_t; + pub fn uselocale(loc: ::locale_t) -> ::locale_t; + pub fn getprogname() -> *const ::c_char; + pub fn setprogname(name: *const ::c_char); + pub fn getloadavg(loadavg: *mut ::c_double, nelem: ::c_int) -> ::c_int; + pub fn getpriority(which: ::c_int, who: ::c_int) -> ::c_int; + pub fn setpriority(which: ::c_int, who: ::c_int, prio: ::c_int) -> ::c_int; + + pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; + + pub fn mknodat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t, dev: dev_t) -> ::c_int; + pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t) -> ::c_int; + pub fn sethostname(name: *mut ::c_char, len: ::c_int) -> ::c_int; + pub fn if_nameindex() -> *mut if_nameindex; + pub fn if_freenameindex(ptr: *mut if_nameindex); + pub fn pthread_create(native: *mut ::pthread_t, + attr: *const ::pthread_attr_t, + f: extern fn(*mut ::c_void) -> *mut ::c_void, + value: *mut ::c_void) -> ::c_int; + pub fn pthread_condattr_getclock(attr: *const pthread_condattr_t, + clock_id: *mut clockid_t) -> ::c_int; + pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, + clock_id: ::clockid_t) -> ::c_int; + pub fn sem_timedwait(sem: *mut sem_t, + abstime: *const ::timespec) -> ::c_int; + pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, + abstime: *const ::timespec) -> ::c_int; + pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, + options: ::c_int) -> ::c_int; + + pub fn glob(pattern: *const ::c_char, + flags: ::c_int, + errfunc: Option ::c_int>, + pglob: *mut ::glob_t) -> ::c_int; + + pub fn globfree(pglob: *mut ::glob_t); + + pub fn posix_madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + pub fn shm_unlink(name: *const ::c_char) -> ::c_int; + + pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); + + pub fn telldir(dirp: *mut ::DIR) -> ::c_long; + pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; + + pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; + + pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, + flags: ::c_int, addr: *mut ::sockaddr, + addrlen: *mut ::socklen_t) -> ::ssize_t; + pub fn mkstemps(template: *mut ::c_char, suffixlen: ::c_int) -> ::c_int; + pub fn futimesat(fd: ::c_int, path: *const ::c_char, + times: *const ::timeval) -> ::c_int; + pub fn utimensat(dirfd: ::c_int, path: *const ::c_char, + times: *const ::timespec, flag: ::c_int) -> ::c_int; + pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; + + pub fn bind(socket: ::c_int, address: *const ::sockaddr, + address_len: ::socklen_t) -> ::c_int; + + pub fn writev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + pub fn readv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + + pub fn sendmsg(fd: ::c_int, + msg: *const ::msghdr, + flags: ::c_int) -> ::ssize_t; + pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) + -> ::ssize_t; + + pub fn port_create() -> ::c_int; + pub fn port_associate(port: ::c_int, source: ::c_int, object: ::uintptr_t, + events: ::c_int, user: *mut ::c_void) -> ::c_int; + pub fn port_dissociate(port: ::c_int, source: ::c_int, object: ::uintptr_t) + -> ::c_int; + pub fn port_get(port: ::c_int, pe: *mut port_event, + timeout: *mut ::timespec) -> ::c_int; + pub fn port_getn(port: ::c_int, pe_list: *mut port_event, max: ::c_uint, + nget: *mut ::c_uint, timeout: *mut ::timespec) + -> ::c_int; + pub fn fexecve(fd: ::c_int, argv: *const *const ::c_char, + envp: *const *const ::c_char) + -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] + pub fn getgrgid_r(uid: ::uid_t, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + pub fn sigaltstack(ss: *const stack_t, + oss: *mut stack_t) -> ::c_int; + pub fn sem_close(sem: *mut sem_t) -> ::c_int; + pub fn getdtablesize() -> ::c_int; + + pub fn epoll_pwait(epfd: ::c_int, + events: *mut ::epoll_event, + maxevents: ::c_int, + timeout: ::c_int, + sigmask: *const ::sigset_t) -> ::c_int; + pub fn epoll_create(size: ::c_int) -> ::c_int; + pub fn epoll_create1(flags: ::c_int) -> ::c_int; + pub fn epoll_wait(epfd: ::c_int, + events: *mut ::epoll_event, + maxevents: ::c_int, + timeout: ::c_int) -> ::c_int; + pub fn epoll_ctl(epfd: ::c_int, + op: ::c_int, + fd: ::c_int, + event: *mut ::epoll_event) -> ::c_int; + + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] + pub fn getgrnam_r(name: *const ::c_char, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, + oldset: *mut sigset_t) -> ::c_int; + pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; + pub fn getgrnam(name: *const ::c_char) -> *mut ::group; + pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; + pub fn sem_unlink(name: *const ::c_char) -> ::c_int; + pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] + pub fn getpwnam_r(name: *const ::c_char, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] + pub fn getpwuid_r(uid: ::uid_t, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwent_r")] + pub fn getpwent_r(pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrent_r")] + pub fn getgrent_r(grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] + pub fn sigwait(set: *const sigset_t, + sig: *mut ::c_int) -> ::c_int; + pub fn pthread_atfork(prepare: Option, + parent: Option, + child: Option) -> ::c_int; + pub fn getgrgid(gid: ::gid_t) -> *mut ::group; + pub fn popen(command: *const c_char, + mode: *const c_char) -> *mut ::FILE; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/mips/mips32.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/mips/mips32.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/mips/mips32.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/mips/mips32.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,269 @@ +pub type c_char = i8; +pub type c_long = i32; +pub type c_ulong = u32; +pub type clock_t = i32; +pub type time_t = i32; +pub type suseconds_t = i32; +pub type wchar_t = i32; +pub type off_t = i32; +pub type ino_t = u32; +pub type blkcnt_t = i32; +pub type blksize_t = i32; +pub type nlink_t = u32; +pub type fsblkcnt_t = ::c_ulong; +pub type fsfilcnt_t = ::c_ulong; +pub type rlim_t = c_ulong; + +s! { + pub struct stat { + pub st_dev: ::dev_t, + st_pad1: [::c_long; 2], + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + pub st_pad2: [::c_long; 1], + pub st_size: ::off_t, + st_pad3: ::c_long, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + st_pad5: [::c_long; 14], + } + + pub struct stat64 { + pub st_dev: ::dev_t, + st_pad1: [::c_long; 2], + pub st_ino: ::ino64_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::dev_t, + st_pad2: [::c_long; 2], + pub st_size: ::off64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + st_pad3: ::c_long, + pub st_blocks: ::blkcnt64_t, + st_pad5: [::c_long; 14], + } + + pub struct pthread_attr_t { + __size: [u32; 9] + } + + pub struct sigaction { + pub sa_flags: ::c_int, + pub sa_sigaction: ::sighandler_t, + pub sa_mask: sigset_t, + _restorer: *mut ::c_void, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_size: ::size_t, + pub ss_flags: ::c_int, + } + + pub struct sigset_t { + __val: [::c_ulong; 4], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_code: ::c_int, + pub si_errno: ::c_int, + pub _pad: [::c_int; 29], + } + + pub struct glob64_t { + pub gl_pathc: ::size_t, + pub gl_pathv: *mut *mut ::c_char, + pub gl_offs: ::size_t, + pub gl_flags: ::c_int, + + __unused1: *mut ::c_void, + __unused2: *mut ::c_void, + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + } + + pub struct ipc_perm { + pub __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::c_uint, + pub __seq: ::c_ushort, + __pad1: ::c_ushort, + __unused1: ::c_ulong, + __unused2: ::c_ulong + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __unused4: ::c_ulong, + __unused5: ::c_ulong + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + #[cfg(target_endian = "big")] + __glibc_reserved1: ::c_ulong, + pub msg_stime: ::time_t, + #[cfg(target_endian = "little")] + __glibc_reserved1: ::c_ulong, + #[cfg(target_endian = "big")] + __glibc_reserved2: ::c_ulong, + pub msg_rtime: ::time_t, + #[cfg(target_endian = "little")] + __glibc_reserved2: ::c_ulong, + #[cfg(target_endian = "big")] + __glibc_reserved3: ::c_ulong, + pub msg_ctime: ::time_t, + #[cfg(target_endian = "little")] + __glibc_reserved3: ::c_ulong, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __glibc_reserved4: ::c_ulong, + __glibc_reserved5: ::c_ulong, + } + + pub struct statfs { + pub f_type: ::c_long, + pub f_bsize: ::c_long, + pub f_frsize: ::c_long, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_files: ::fsblkcnt_t, + pub f_ffree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_fsid: ::fsid_t, + + pub f_namelen: ::c_long, + f_spare: [::c_long; 6], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::c_int, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::size_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::size_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; ::NCCS], + } + + pub struct flock { + pub l_type: ::c_short, + pub l_whence: ::c_short, + pub l_start: ::off_t, + pub l_len: ::off_t, + pub l_sysid: ::c_long, + pub l_pid: ::pid_t, + pad: [::c_long; 4], + } + + pub struct sysinfo { + pub uptime: ::c_long, + pub loads: [::c_ulong; 3], + pub totalram: ::c_ulong, + pub freeram: ::c_ulong, + pub sharedram: ::c_ulong, + pub bufferram: ::c_ulong, + pub totalswap: ::c_ulong, + pub freeswap: ::c_ulong, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: ::c_ulong, + pub freehigh: ::c_ulong, + pub mem_unit: ::c_uint, + pub _f: [::c_char; 8], + } + + // FIXME this is actually a union + pub struct sem_t { + #[cfg(target_pointer_width = "32")] + __size: [::c_char; 16], + #[cfg(target_pointer_width = "64")] + __size: [::c_char; 32], + __align: [::c_long; 0], + } +} + +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 24; +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 32; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; + +pub const RLIM_INFINITY: ::rlim_t = 0x7fffffff; + +pub const SYS_gettid: ::c_long = 4222; // Valid for O32 + +#[link(name = "util")] +extern { + pub fn sysctl(name: *mut ::c_int, + namelen: ::c_int, + oldp: *mut ::c_void, + oldlenp: *mut ::size_t, + newp: *mut ::c_void, + newlen: ::size_t) + -> ::c_int; + pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; + pub fn backtrace(buf: *mut *mut ::c_void, + sz: ::c_int) -> ::c_int; + pub fn glob64(pattern: *const ::c_char, + flags: ::c_int, + errfunc: ::dox::Option ::c_int>, + pglob: *mut glob64_t) -> ::c_int; + pub fn globfree64(pglob: *mut glob64_t); + pub fn ptrace(request: ::c_uint, ...) -> ::c_long; + pub fn pthread_attr_getaffinity_np(attr: *const ::pthread_attr_t, + cpusetsize: ::size_t, + cpuset: *mut ::cpu_set_t) -> ::c_int; + pub fn pthread_attr_setaffinity_np(attr: *mut ::pthread_attr_t, + cpusetsize: ::size_t, + cpuset: *const ::cpu_set_t) -> ::c_int; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/mips/mips64.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/mips/mips64.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/mips/mips64.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/mips/mips64.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,209 @@ +pub type blkcnt_t = i64; +pub type blksize_t = i64; +pub type c_char = i8; +pub type c_long = i64; +pub type c_ulong = u64; +pub type fsblkcnt_t = ::c_ulong; +pub type fsfilcnt_t = ::c_ulong; +pub type ino_t = u64; +pub type nlink_t = u64; +pub type off_t = i64; +pub type rlim_t = ::c_ulong; +pub type suseconds_t = i64; +pub type time_t = i64; +pub type wchar_t = i32; + +s! { + pub struct stat { + pub st_dev: ::c_ulong, + st_pad1: [::c_long; 2], + pub st_ino: ::ino_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::c_ulong, + st_pad2: [::c_ulong; 1], + pub st_size: ::off_t, + st_pad3: ::c_long, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + st_pad4: ::c_long, + pub st_blocks: ::blkcnt_t, + st_pad5: [::c_long; 7], + } + + pub struct stat64 { + pub st_dev: ::c_ulong, + st_pad1: [::c_long; 2], + pub st_ino: ::ino64_t, + pub st_mode: ::mode_t, + pub st_nlink: ::nlink_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::c_ulong, + st_pad2: [::c_long; 2], + pub st_size: ::off64_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_long, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_long, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_long, + pub st_blksize: ::blksize_t, + st_pad3: ::c_long, + pub st_blocks: ::blkcnt64_t, + st_pad5: [::c_long; 7], + } + + pub struct pthread_attr_t { + __size: [::c_ulong; 7] + } + + pub struct sigaction { + pub sa_flags: ::c_int, + pub sa_sigaction: ::sighandler_t, + pub sa_mask: sigset_t, + _restorer: *mut ::c_void, + } + + pub struct stack_t { + pub ss_sp: *mut ::c_void, + pub ss_size: ::size_t, + pub ss_flags: ::c_int, + } + + pub struct sigset_t { + __size: [::c_ulong; 16], + } + + pub struct siginfo_t { + pub si_signo: ::c_int, + pub si_code: ::c_int, + pub si_errno: ::c_int, + _pad: ::c_int, + _pad2: [::c_long; 14], + } + + pub struct ipc_perm { + pub __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::c_uint, + pub __seq: ::c_ushort, + __pad1: ::c_ushort, + __unused1: ::c_ulong, + __unused2: ::c_ulong + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, + pub shm_atime: ::time_t, + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __unused4: ::c_ulong, + __unused5: ::c_ulong + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_stime: ::time_t, + pub msg_rtime: ::time_t, + pub msg_ctime: ::time_t, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __glibc_reserved4: ::c_ulong, + __glibc_reserved5: ::c_ulong, + } + + pub struct statfs { + pub f_type: ::c_long, + pub f_bsize: ::c_long, + pub f_frsize: ::c_long, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_files: ::fsblkcnt_t, + pub f_ffree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_fsid: ::fsid_t, + + pub f_namelen: ::c_long, + f_spare: [::c_long; 6], + } + + pub struct msghdr { + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::size_t, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::size_t, + pub msg_flags: ::c_int, + } + + pub struct cmsghdr { + pub cmsg_len: ::size_t, + pub cmsg_level: ::c_int, + pub cmsg_type: ::c_int, + } + + pub struct termios { + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; ::NCCS], + } + + pub struct sysinfo { + pub uptime: ::c_long, + pub loads: [::c_ulong; 3], + pub totalram: ::c_ulong, + pub freeram: ::c_ulong, + pub sharedram: ::c_ulong, + pub bufferram: ::c_ulong, + pub totalswap: ::c_ulong, + pub freeswap: ::c_ulong, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: ::c_ulong, + pub freehigh: ::c_ulong, + pub mem_unit: ::c_uint, + pub _f: [::c_char; 0], + } + + // FIXME this is actually a union + pub struct sem_t { + __size: [::c_char; 32], + __align: [::c_long; 0], + } +} + +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; + +pub const RLIM_INFINITY: ::rlim_t = 0xffff_ffff_ffff_ffff; + +pub const SYS_gettid: ::c_long = 5178; // Valid for n64 + +#[link(name = "util")] +extern { + pub fn ioctl(fd: ::c_int, request: ::c_ulong, ...) -> ::c_int; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/mips/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/mips/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/mips/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/mips/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,478 @@ +pub type pthread_t = ::c_ulong; + +pub const SFD_CLOEXEC: ::c_int = 0x080000; + +pub const NCCS: usize = 32; + +pub const O_TRUNC: ::c_int = 512; + +pub const O_CLOEXEC: ::c_int = 0x80000; + +pub const EBFONT: ::c_int = 59; +pub const ENOSTR: ::c_int = 60; +pub const ENODATA: ::c_int = 61; +pub const ETIME: ::c_int = 62; +pub const ENOSR: ::c_int = 63; +pub const ENONET: ::c_int = 64; +pub const ENOPKG: ::c_int = 65; +pub const EREMOTE: ::c_int = 66; +pub const ENOLINK: ::c_int = 67; +pub const EADV: ::c_int = 68; +pub const ESRMNT: ::c_int = 69; +pub const ECOMM: ::c_int = 70; +pub const EPROTO: ::c_int = 71; +pub const EDOTDOT: ::c_int = 73; + +pub const SA_NODEFER: ::c_int = 0x40000000; +pub const SA_RESETHAND: ::c_int = 0x80000000; +pub const SA_RESTART: ::c_int = 0x10000000; +pub const SA_NOCLDSTOP: ::c_int = 0x00000001; + +pub const EPOLL_CLOEXEC: ::c_int = 0x80000; + +pub const EFD_CLOEXEC: ::c_int = 0x80000; + +pub const BUFSIZ: ::c_uint = 4096; +pub const TMP_MAX: ::c_uint = 238328; +pub const FOPEN_MAX: ::c_uint = 16; +pub const POSIX_FADV_DONTNEED: ::c_int = 4; +pub const POSIX_FADV_NOREUSE: ::c_int = 5; +pub const POSIX_MADV_DONTNEED: ::c_int = 4; +pub const _SC_2_C_VERSION: ::c_int = 96; +pub const O_ACCMODE: ::c_int = 3; +pub const O_DIRECT: ::c_int = 0x8000; +pub const O_DIRECTORY: ::c_int = 0x10000; +pub const O_NOFOLLOW: ::c_int = 0x20000; +pub const ST_RELATIME: ::c_ulong = 4096; +pub const NI_MAXHOST: ::socklen_t = 1025; + +pub const RLIMIT_NOFILE: ::c_int = 5; +pub const RLIMIT_AS: ::c_int = 6; +pub const RLIMIT_RSS: ::c_int = 7; +pub const RLIMIT_NPROC: ::c_int = 8; +pub const RLIMIT_MEMLOCK: ::c_int = 9; +pub const RLIMIT_NLIMITS: ::c_int = 15; + +pub const O_APPEND: ::c_int = 8; +pub const O_CREAT: ::c_int = 256; +pub const O_EXCL: ::c_int = 1024; +pub const O_NOCTTY: ::c_int = 2048; +pub const O_NONBLOCK: ::c_int = 128; +pub const O_SYNC: ::c_int = 0x10; +pub const O_RSYNC: ::c_int = 0x10; +pub const O_DSYNC: ::c_int = 0x10; +pub const O_FSYNC: ::c_int = 0x10; +pub const O_ASYNC: ::c_int = 0x1000; +pub const O_NDELAY: ::c_int = 0x80; + +pub const SOCK_NONBLOCK: ::c_int = 128; + +pub const EDEADLK: ::c_int = 45; +pub const ENAMETOOLONG: ::c_int = 78; +pub const ENOLCK: ::c_int = 46; +pub const ENOSYS: ::c_int = 89; +pub const ENOTEMPTY: ::c_int = 93; +pub const ELOOP: ::c_int = 90; +pub const ENOMSG: ::c_int = 35; +pub const EIDRM: ::c_int = 36; +pub const ECHRNG: ::c_int = 37; +pub const EL2NSYNC: ::c_int = 38; +pub const EL3HLT: ::c_int = 39; +pub const EL3RST: ::c_int = 40; +pub const ELNRNG: ::c_int = 41; +pub const EUNATCH: ::c_int = 42; +pub const ENOCSI: ::c_int = 43; +pub const EL2HLT: ::c_int = 44; +pub const EBADE: ::c_int = 50; +pub const EBADR: ::c_int = 51; +pub const EXFULL: ::c_int = 52; +pub const ENOANO: ::c_int = 53; +pub const EBADRQC: ::c_int = 54; +pub const EBADSLT: ::c_int = 55; +pub const EDEADLOCK: ::c_int = 56; +pub const EMULTIHOP: ::c_int = 74; +pub const EOVERFLOW: ::c_int = 79; +pub const ENOTUNIQ: ::c_int = 80; +pub const EBADFD: ::c_int = 81; +pub const EBADMSG: ::c_int = 77; +pub const EREMCHG: ::c_int = 82; +pub const ELIBACC: ::c_int = 83; +pub const ELIBBAD: ::c_int = 84; +pub const ELIBSCN: ::c_int = 85; +pub const ELIBMAX: ::c_int = 86; +pub const ELIBEXEC: ::c_int = 87; +pub const EILSEQ: ::c_int = 88; +pub const ERESTART: ::c_int = 91; +pub const ESTRPIPE: ::c_int = 92; +pub const EUSERS: ::c_int = 94; +pub const ENOTSOCK: ::c_int = 95; +pub const EDESTADDRREQ: ::c_int = 96; +pub const EMSGSIZE: ::c_int = 97; +pub const EPROTOTYPE: ::c_int = 98; +pub const ENOPROTOOPT: ::c_int = 99; +pub const EPROTONOSUPPORT: ::c_int = 120; +pub const ESOCKTNOSUPPORT: ::c_int = 121; +pub const EOPNOTSUPP: ::c_int = 122; +pub const ENOTSUP: ::c_int = EOPNOTSUPP; +pub const EPFNOSUPPORT: ::c_int = 123; +pub const EAFNOSUPPORT: ::c_int = 124; +pub const EADDRINUSE: ::c_int = 125; +pub const EADDRNOTAVAIL: ::c_int = 126; +pub const ENETDOWN: ::c_int = 127; +pub const ENETUNREACH: ::c_int = 128; +pub const ENETRESET: ::c_int = 129; +pub const ECONNABORTED: ::c_int = 130; +pub const ECONNRESET: ::c_int = 131; +pub const ENOBUFS: ::c_int = 132; +pub const EISCONN: ::c_int = 133; +pub const ENOTCONN: ::c_int = 134; +pub const ESHUTDOWN: ::c_int = 143; +pub const ETOOMANYREFS: ::c_int = 144; +pub const ETIMEDOUT: ::c_int = 145; +pub const ECONNREFUSED: ::c_int = 146; +pub const EHOSTDOWN: ::c_int = 147; +pub const EHOSTUNREACH: ::c_int = 148; +pub const EALREADY: ::c_int = 149; +pub const EINPROGRESS: ::c_int = 150; +pub const ESTALE: ::c_int = 151; +pub const EUCLEAN: ::c_int = 135; +pub const ENOTNAM: ::c_int = 137; +pub const ENAVAIL: ::c_int = 138; +pub const EISNAM: ::c_int = 139; +pub const EREMOTEIO: ::c_int = 140; +pub const EDQUOT: ::c_int = 1133; +pub const ENOMEDIUM: ::c_int = 159; +pub const EMEDIUMTYPE: ::c_int = 160; +pub const ECANCELED: ::c_int = 158; +pub const ENOKEY: ::c_int = 161; +pub const EKEYEXPIRED: ::c_int = 162; +pub const EKEYREVOKED: ::c_int = 163; +pub const EKEYREJECTED: ::c_int = 164; +pub const EOWNERDEAD: ::c_int = 165; +pub const ENOTRECOVERABLE: ::c_int = 166; +pub const ERFKILL: ::c_int = 167; + +pub const MAP_NORESERVE: ::c_int = 0x400; +pub const MAP_ANON: ::c_int = 0x800; +pub const MAP_ANONYMOUS: ::c_int = 0x800; +pub const MAP_GROWSDOWN: ::c_int = 0x1000; +pub const MAP_DENYWRITE: ::c_int = 0x2000; +pub const MAP_EXECUTABLE: ::c_int = 0x4000; +pub const MAP_LOCKED: ::c_int = 0x8000; +pub const MAP_POPULATE: ::c_int = 0x10000; +pub const MAP_NONBLOCK: ::c_int = 0x20000; +pub const MAP_STACK: ::c_int = 0x40000; + +pub const SOCK_STREAM: ::c_int = 2; +pub const SOCK_DGRAM: ::c_int = 1; +pub const SOCK_SEQPACKET: ::c_int = 5; + +pub const SOL_SOCKET: ::c_int = 0xffff; + +pub const SO_REUSEADDR: ::c_int = 0x0004; +pub const SO_KEEPALIVE: ::c_int = 0x0008; +pub const SO_DONTROUTE: ::c_int = 0x0010; +pub const SO_BROADCAST: ::c_int = 0x0020; +pub const SO_LINGER: ::c_int = 0x0080; +pub const SO_OOBINLINE: ::c_int = 0x0100; +pub const SO_REUSEPORT: ::c_int = 0x0200; +pub const SO_TYPE: ::c_int = 0x1008; +pub const SO_STYLE: ::c_int = SO_TYPE; +pub const SO_ERROR: ::c_int = 0x1007; +pub const SO_SNDBUF: ::c_int = 0x1001; +pub const SO_RCVBUF: ::c_int = 0x1002; +pub const SO_SNDLOWAT: ::c_int = 0x1003; +pub const SO_RCVLOWAT: ::c_int = 0x1004; +pub const SO_SNDTIMEO: ::c_int = 0x1005; +pub const SO_RCVTIMEO: ::c_int = 0x1006; +pub const SO_ACCEPTCONN: ::c_int = 0x1009; +pub const SO_PROTOCOL: ::c_int = 0x1028; +pub const SO_DOMAIN: ::c_int = 0x1029; +pub const SO_NO_CHECK: ::c_int = 11; +pub const SO_PRIORITY: ::c_int = 12; +pub const SO_BSDCOMPAT: ::c_int = 14; +pub const SO_PASSCRED: ::c_int = 17; +pub const SO_PEERCRED: ::c_int = 18; +pub const SO_SECURITY_AUTHENTICATION: ::c_int = 22; +pub const SO_SECURITY_ENCRYPTION_TRANSPORT: ::c_int = 23; +pub const SO_SECURITY_ENCRYPTION_NETWORK: ::c_int = 24; +pub const SO_BINDTODEVICE: ::c_int = 25; +pub const SO_ATTACH_FILTER: ::c_int = 26; +pub const SO_DETACH_FILTER: ::c_int = 27; +pub const SO_GET_FILTER: ::c_int = SO_ATTACH_FILTER; +pub const SO_PEERNAME: ::c_int = 28; +pub const SO_TIMESTAMP: ::c_int = 29; +pub const SCM_TIMESTAMP: ::c_int = SO_TIMESTAMP; +pub const SO_PEERSEC: ::c_int = 30; +pub const SO_SNDBUFFORCE: ::c_int = 31; +pub const SO_RCVBUFFORCE: ::c_int = 33; +pub const SO_PASSSEC: ::c_int = 34; +pub const SO_TIMESTAMPNS: ::c_int = 35; +pub const SCM_TIMESTAMPNS: ::c_int = SO_TIMESTAMPNS; +pub const SO_MARK: ::c_int = 36; +pub const SO_TIMESTAMPING: ::c_int = 37; +pub const SCM_TIMESTAMPING: ::c_int = SO_TIMESTAMPING; +pub const SO_RXQ_OVFL: ::c_int = 40; +pub const SO_WIFI_STATUS: ::c_int = 41; +pub const SCM_WIFI_STATUS: ::c_int = SO_WIFI_STATUS; +pub const SO_PEEK_OFF: ::c_int = 42; +pub const SO_NOFCS: ::c_int = 43; +pub const SO_LOCK_FILTER: ::c_int = 44; +pub const SO_SELECT_ERR_QUEUE: ::c_int = 45; +pub const SO_BUSY_POLL: ::c_int = 46; +pub const SO_MAX_PACING_RATE: ::c_int = 47; +pub const SO_BPF_EXTENSIONS: ::c_int = 48; + +pub const FIOCLEX: ::c_ulong = 0x6601; +pub const FIONBIO: ::c_ulong = 0x667e; + +pub const SA_ONSTACK: ::c_int = 0x08000000; +pub const SA_SIGINFO: ::c_int = 0x00000008; +pub const SA_NOCLDWAIT: ::c_int = 0x00010000; + +pub const SIGCHLD: ::c_int = 18; +pub const SIGBUS: ::c_int = 10; +pub const SIGTTIN: ::c_int = 26; +pub const SIGTTOU: ::c_int = 27; +pub const SIGXCPU: ::c_int = 30; +pub const SIGXFSZ: ::c_int = 31; +pub const SIGVTALRM: ::c_int = 28; +pub const SIGPROF: ::c_int = 29; +pub const SIGWINCH: ::c_int = 20; +pub const SIGUSR1: ::c_int = 16; +pub const SIGUSR2: ::c_int = 17; +pub const SIGCONT: ::c_int = 25; +pub const SIGSTOP: ::c_int = 23; +pub const SIGTSTP: ::c_int = 24; +pub const SIGURG: ::c_int = 21; +pub const SIGIO: ::c_int = 22; +pub const SIGSYS: ::c_int = 12; +pub const SIGPOLL: ::c_int = 22; +pub const SIGPWR: ::c_int = 19; +pub const SIG_SETMASK: ::c_int = 3; +pub const SIG_BLOCK: ::c_int = 0x1; +pub const SIG_UNBLOCK: ::c_int = 0x2; + +pub const POLLRDNORM: ::c_short = 0x040; +pub const POLLWRNORM: ::c_short = 0x004; +pub const POLLRDBAND: ::c_short = 0x080; +pub const POLLWRBAND: ::c_short = 0x100; + +pub const PTHREAD_STACK_MIN: ::size_t = 16384; + +pub const ADFS_SUPER_MAGIC: ::c_long = 0x0000adf5; +pub const AFFS_SUPER_MAGIC: ::c_long = 0x0000adff; +pub const CODA_SUPER_MAGIC: ::c_long = 0x73757245; +pub const CRAMFS_MAGIC: ::c_long = 0x28cd3d45; +pub const EFS_SUPER_MAGIC: ::c_long = 0x00414a53; +pub const EXT2_SUPER_MAGIC: ::c_long = 0x0000ef53; +pub const EXT3_SUPER_MAGIC: ::c_long = 0x0000ef53; +pub const EXT4_SUPER_MAGIC: ::c_long = 0x0000ef53; +pub const HPFS_SUPER_MAGIC: ::c_long = 0xf995e849; +pub const HUGETLBFS_MAGIC: ::c_long = 0x958458f6; +pub const ISOFS_SUPER_MAGIC: ::c_long = 0x00009660; +pub const JFFS2_SUPER_MAGIC: ::c_long = 0x000072b6; +pub const MINIX_SUPER_MAGIC: ::c_long = 0x0000137f; +pub const MINIX_SUPER_MAGIC2: ::c_long = 0x0000138f; +pub const MINIX2_SUPER_MAGIC: ::c_long = 0x00002468; +pub const MINIX2_SUPER_MAGIC2: ::c_long = 0x00002478; +pub const MSDOS_SUPER_MAGIC: ::c_long = 0x00004d44; +pub const NCP_SUPER_MAGIC: ::c_long = 0x0000564c; +pub const NFS_SUPER_MAGIC: ::c_long = 0x00006969; +pub const OPENPROM_SUPER_MAGIC: ::c_long = 0x00009fa1; +pub const PROC_SUPER_MAGIC: ::c_long = 0x00009fa0; +pub const QNX4_SUPER_MAGIC: ::c_long = 0x0000002f; +pub const REISERFS_SUPER_MAGIC: ::c_long = 0x52654973; +pub const SMB_SUPER_MAGIC: ::c_long = 0x0000517b; +pub const TMPFS_MAGIC: ::c_long = 0x01021994; +pub const USBDEVICE_SUPER_MAGIC: ::c_long = 0x00009fa2; + +pub const VEOF: usize = 16; +pub const VEOL: usize = 17; +pub const VEOL2: usize = 6; +pub const VMIN: usize = 4; +pub const IEXTEN: ::tcflag_t = 0x00000100; +pub const TOSTOP: ::tcflag_t = 0x00008000; +pub const FLUSHO: ::tcflag_t = 0x00002000; +pub const IUTF8: ::tcflag_t = 0x00004000; +pub const TCSANOW: ::c_int = 0x540e; +pub const TCSADRAIN: ::c_int = 0x540f; +pub const TCSAFLUSH: ::c_int = 0x5410; + +pub const CPU_SETSIZE: ::c_int = 0x400; + +pub const PTRACE_TRACEME: ::c_uint = 0; +pub const PTRACE_PEEKTEXT: ::c_uint = 1; +pub const PTRACE_PEEKDATA: ::c_uint = 2; +pub const PTRACE_PEEKUSER: ::c_uint = 3; +pub const PTRACE_POKETEXT: ::c_uint = 4; +pub const PTRACE_POKEDATA: ::c_uint = 5; +pub const PTRACE_POKEUSER: ::c_uint = 6; +pub const PTRACE_CONT: ::c_uint = 7; +pub const PTRACE_KILL: ::c_uint = 8; +pub const PTRACE_SINGLESTEP: ::c_uint = 9; +pub const PTRACE_ATTACH: ::c_uint = 16; +pub const PTRACE_DETACH: ::c_uint = 17; +pub const PTRACE_SYSCALL: ::c_uint = 24; +pub const PTRACE_SETOPTIONS: ::c_uint = 0x4200; +pub const PTRACE_GETEVENTMSG: ::c_uint = 0x4201; +pub const PTRACE_GETSIGINFO: ::c_uint = 0x4202; +pub const PTRACE_SETSIGINFO: ::c_uint = 0x4203; +pub const PTRACE_GETFPREGS: ::c_uint = 14; +pub const PTRACE_SETFPREGS: ::c_uint = 15; +pub const PTRACE_GETFPXREGS: ::c_uint = 18; +pub const PTRACE_SETFPXREGS: ::c_uint = 19; +pub const PTRACE_GETREGS: ::c_uint = 12; +pub const PTRACE_SETREGS: ::c_uint = 13; + +pub const EFD_NONBLOCK: ::c_int = 0x80; + +pub const F_GETLK: ::c_int = 14; +pub const F_GETOWN: ::c_int = 23; +pub const F_SETOWN: ::c_int = 24; +pub const F_SETLK: ::c_int = 6; +pub const F_SETLKW: ::c_int = 7; + +pub const SFD_NONBLOCK: ::c_int = 0x80; + +pub const TCGETS: ::c_ulong = 0x540d; +pub const TCSETS: ::c_ulong = 0x540e; +pub const TCSETSW: ::c_ulong = 0x540f; +pub const TCSETSF: ::c_ulong = 0x5410; +pub const TCGETA: ::c_ulong = 0x5401; +pub const TCSETA: ::c_ulong = 0x5402; +pub const TCSETAW: ::c_ulong = 0x5403; +pub const TCSETAF: ::c_ulong = 0x5404; +pub const TCSBRK: ::c_ulong = 0x5405; +pub const TCXONC: ::c_ulong = 0x5406; +pub const TCFLSH: ::c_ulong = 0x5407; +pub const TIOCGSOFTCAR: ::c_ulong = 0x5481; +pub const TIOCSSOFTCAR: ::c_ulong = 0x5482; +pub const TIOCINQ: ::c_ulong = 0x467f; +pub const TIOCLINUX: ::c_ulong = 0x5483; +pub const TIOCGSERIAL: ::c_ulong = 0x5484; +pub const TIOCEXCL: ::c_ulong = 0x740d; +pub const TIOCNXCL: ::c_ulong = 0x740e; +pub const TIOCSCTTY: ::c_ulong = 0x5480; +pub const TIOCGPGRP: ::c_ulong = 0x40047477; +pub const TIOCSPGRP: ::c_ulong = 0x80047476; +pub const TIOCOUTQ: ::c_ulong = 0x7472; +pub const TIOCSTI: ::c_ulong = 0x5472; +pub const TIOCGWINSZ: ::c_ulong = 0x40087468; +pub const TIOCSWINSZ: ::c_ulong = 0x80087467; +pub const TIOCMGET: ::c_ulong = 0x741d; +pub const TIOCMBIS: ::c_ulong = 0x741b; +pub const TIOCMBIC: ::c_ulong = 0x741c; +pub const TIOCMSET: ::c_ulong = 0x741a; +pub const FIONREAD: ::c_ulong = 0x467f; +pub const TIOCCONS: ::c_ulong = 0x80047478; + +pub const RTLD_DEEPBIND: ::c_int = 0x10; +pub const RTLD_GLOBAL: ::c_int = 0x4; +pub const RTLD_NOLOAD: ::c_int = 0x8; + +pub const LINUX_REBOOT_MAGIC1: ::c_int = 0xfee1dead; +pub const LINUX_REBOOT_MAGIC2: ::c_int = 672274793; +pub const LINUX_REBOOT_MAGIC2A: ::c_int = 85072278; +pub const LINUX_REBOOT_MAGIC2B: ::c_int = 369367448; +pub const LINUX_REBOOT_MAGIC2C: ::c_int = 537993216; + +pub const LINUX_REBOOT_CMD_RESTART: ::c_int = 0x01234567; +pub const LINUX_REBOOT_CMD_HALT: ::c_int = 0xCDEF0123; +pub const LINUX_REBOOT_CMD_CAD_ON: ::c_int = 0x89ABCDEF; +pub const LINUX_REBOOT_CMD_CAD_OFF: ::c_int = 0x00000000; +pub const LINUX_REBOOT_CMD_POWER_OFF: ::c_int = 0x4321FEDC; +pub const LINUX_REBOOT_CMD_RESTART2: ::c_int = 0xA1B2C3D4; +pub const LINUX_REBOOT_CMD_SW_SUSPEND: ::c_int = 0xD000FCE2; +pub const LINUX_REBOOT_CMD_KEXEC: ::c_int = 0x45584543; + +pub const MCL_CURRENT: ::c_int = 0x0001; +pub const MCL_FUTURE: ::c_int = 0x0002; + +pub const SIGSTKSZ: ::size_t = 8192; +pub const CBAUD: ::tcflag_t = 0o0010017; +pub const TAB1: ::c_int = 0x00000800; +pub const TAB2: ::c_int = 0x00001000; +pub const TAB3: ::c_int = 0x00001800; +pub const CR1: ::c_int = 0x00000200; +pub const CR2: ::c_int = 0x00000400; +pub const CR3: ::c_int = 0x00000600; +pub const FF1: ::c_int = 0x00008000; +pub const BS1: ::c_int = 0x00002000; +pub const VT1: ::c_int = 0x00004000; +pub const VWERASE: usize = 14; +pub const VREPRINT: usize = 12; +pub const VSUSP: usize = 10; +pub const VSTART: usize = 8; +pub const VSTOP: usize = 9; +pub const VDISCARD: usize = 13; +pub const VTIME: usize = 5; +pub const IXON: ::tcflag_t = 0x00000400; +pub const IXOFF: ::tcflag_t = 0x00001000; +pub const ONLCR: ::tcflag_t = 0x4; +pub const CSIZE: ::tcflag_t = 0x00000030; +pub const CS6: ::tcflag_t = 0x00000010; +pub const CS7: ::tcflag_t = 0x00000020; +pub const CS8: ::tcflag_t = 0x00000030; +pub const CSTOPB: ::tcflag_t = 0x00000040; +pub const CREAD: ::tcflag_t = 0x00000080; +pub const PARENB: ::tcflag_t = 0x00000100; +pub const PARODD: ::tcflag_t = 0x00000200; +pub const HUPCL: ::tcflag_t = 0x00000400; +pub const CLOCAL: ::tcflag_t = 0x00000800; +pub const ECHOKE: ::tcflag_t = 0x00000800; +pub const ECHOE: ::tcflag_t = 0x00000010; +pub const ECHOK: ::tcflag_t = 0x00000020; +pub const ECHONL: ::tcflag_t = 0x00000040; +pub const ECHOPRT: ::tcflag_t = 0x00000400; +pub const ECHOCTL: ::tcflag_t = 0x00000200; +pub const ISIG: ::tcflag_t = 0x00000001; +pub const ICANON: ::tcflag_t = 0x00000002; +pub const PENDIN: ::tcflag_t = 0x00004000; +pub const NOFLSH: ::tcflag_t = 0x00000080; + +pub const B0: ::speed_t = 0o000000; +pub const B50: ::speed_t = 0o000001; +pub const B75: ::speed_t = 0o000002; +pub const B110: ::speed_t = 0o000003; +pub const B134: ::speed_t = 0o000004; +pub const B150: ::speed_t = 0o000005; +pub const B200: ::speed_t = 0o000006; +pub const B300: ::speed_t = 0o000007; +pub const B600: ::speed_t = 0o000010; +pub const B1200: ::speed_t = 0o000011; +pub const B1800: ::speed_t = 0o000012; +pub const B2400: ::speed_t = 0o000013; +pub const B4800: ::speed_t = 0o000014; +pub const B9600: ::speed_t = 0o000015; +pub const B19200: ::speed_t = 0o000016; +pub const B38400: ::speed_t = 0o000017; +pub const EXTA: ::speed_t = B19200; +pub const EXTB: ::speed_t = B38400; +pub const B57600: ::speed_t = 0o010001; +pub const B115200: ::speed_t = 0o010002; +pub const B230400: ::speed_t = 0o010003; +pub const B460800: ::speed_t = 0o010004; +pub const B500000: ::speed_t = 0o010005; +pub const B576000: ::speed_t = 0o010006; +pub const B921600: ::speed_t = 0o010007; +pub const B1000000: ::speed_t = 0o010010; +pub const B1152000: ::speed_t = 0o010011; +pub const B1500000: ::speed_t = 0o010012; +pub const B2000000: ::speed_t = 0o010013; +pub const B2500000: ::speed_t = 0o010014; +pub const B3000000: ::speed_t = 0o010015; +pub const B3500000: ::speed_t = 0o010016; +pub const B4000000: ::speed_t = 0o010017; + +cfg_if! { + if #[cfg(target_arch = "mips")] { + mod mips32; + pub use self::mips32::*; + } else if #[cfg(target_arch = "mips64")] { + mod mips64; + pub use self::mips64::*; + } else { + // Unknown target_arch + } +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1902 @@ +use dox::{mem, Option}; + +pub type sa_family_t = u16; +pub type pthread_key_t = ::c_uint; +pub type speed_t = ::c_uint; +pub type tcflag_t = ::c_uint; +pub type loff_t = ::c_longlong; +pub type clockid_t = ::c_int; +pub type key_t = ::c_int; +pub type id_t = ::c_uint; +pub type useconds_t = u32; +pub type dev_t = u64; +pub type socklen_t = u32; +pub type mode_t = u32; +pub type ino64_t = u64; +pub type off64_t = i64; +pub type blkcnt64_t = i64; +pub type rlim64_t = u64; +pub type shmatt_t = ::c_ulong; +pub type mqd_t = ::c_int; +pub type msgqnum_t = ::c_ulong; +pub type msglen_t = ::c_ulong; +pub type nfds_t = ::c_ulong; +pub type nl_item = ::c_int; +pub type idtype_t = ::c_uint; + +pub enum fpos64_t {} // TODO: fill this out with a struct + +pub enum timezone {} + +s! { + pub struct sockaddr { + pub sa_family: sa_family_t, + pub sa_data: [::c_char; 14], + } + + pub struct sockaddr_in { + pub sin_family: sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + pub sin_zero: [u8; 8], + } + + pub struct sockaddr_in6 { + pub sin6_family: sa_family_t, + pub sin6_port: ::in_port_t, + pub sin6_flowinfo: u32, + pub sin6_addr: ::in6_addr, + pub sin6_scope_id: u32, + } + + pub struct sockaddr_un { + pub sun_family: sa_family_t, + pub sun_path: [::c_char; 108] + } + + pub struct sockaddr_storage { + pub ss_family: sa_family_t, + __ss_align: ::size_t, + #[cfg(target_pointer_width = "32")] + __ss_pad2: [u8; 128 - 2 * 4], + #[cfg(target_pointer_width = "64")] + __ss_pad2: [u8; 128 - 2 * 8], + } + + pub struct addrinfo { + pub ai_flags: ::c_int, + pub ai_family: ::c_int, + pub ai_socktype: ::c_int, + pub ai_protocol: ::c_int, + pub ai_addrlen: socklen_t, + + pub ai_addr: *mut ::sockaddr, + + pub ai_canonname: *mut c_char, + + pub ai_next: *mut addrinfo, + } + + pub struct sockaddr_nl { + pub nl_family: ::sa_family_t, + nl_pad: ::c_ushort, + pub nl_pid: u32, + pub nl_groups: u32 + } + + pub struct sockaddr_ll { + pub sll_family: ::c_ushort, + pub sll_protocol: ::c_ushort, + pub sll_ifindex: ::c_int, + pub sll_hatype: ::c_ushort, + pub sll_pkttype: ::c_uchar, + pub sll_halen: ::c_uchar, + pub sll_addr: [::c_uchar; 8] + } + + pub struct fd_set { + fds_bits: [::c_ulong; FD_SETSIZE / ULONG_SIZE], + } + + pub struct tm { + pub tm_sec: ::c_int, + pub tm_min: ::c_int, + pub tm_hour: ::c_int, + pub tm_mday: ::c_int, + pub tm_mon: ::c_int, + pub tm_year: ::c_int, + pub tm_wday: ::c_int, + pub tm_yday: ::c_int, + pub tm_isdst: ::c_int, + pub tm_gmtoff: ::c_long, + pub tm_zone: *const ::c_char, + } + + pub struct sched_param { + pub sched_priority: ::c_int, + } + + pub struct Dl_info { + pub dli_fname: *const ::c_char, + pub dli_fbase: *mut ::c_void, + pub dli_sname: *const ::c_char, + pub dli_saddr: *mut ::c_void, + } + + #[cfg_attr(any(all(target_arch = "x86", + target_arch = "x86_64")), + repr(packed))] + pub struct epoll_event { + pub events: ::uint32_t, + pub u64: ::uint64_t, + } + + pub struct utsname { + pub sysname: [::c_char; 65], + pub nodename: [::c_char; 65], + pub release: [::c_char; 65], + pub version: [::c_char; 65], + pub machine: [::c_char; 65], + pub domainname: [::c_char; 65] + } + + pub struct lconv { + pub decimal_point: *mut ::c_char, + pub thousands_sep: *mut ::c_char, + pub grouping: *mut ::c_char, + pub int_curr_symbol: *mut ::c_char, + pub currency_symbol: *mut ::c_char, + pub mon_decimal_point: *mut ::c_char, + pub mon_thousands_sep: *mut ::c_char, + pub mon_grouping: *mut ::c_char, + pub positive_sign: *mut ::c_char, + pub negative_sign: *mut ::c_char, + pub int_frac_digits: ::c_char, + pub frac_digits: ::c_char, + pub p_cs_precedes: ::c_char, + pub p_sep_by_space: ::c_char, + pub n_cs_precedes: ::c_char, + pub n_sep_by_space: ::c_char, + pub p_sign_posn: ::c_char, + pub n_sign_posn: ::c_char, + pub int_p_cs_precedes: ::c_char, + pub int_p_sep_by_space: ::c_char, + pub int_n_cs_precedes: ::c_char, + pub int_n_sep_by_space: ::c_char, + pub int_p_sign_posn: ::c_char, + pub int_n_sign_posn: ::c_char, + } + + pub struct sigevent { + pub sigev_value: ::sigval, + pub sigev_signo: ::c_int, + pub sigev_notify: ::c_int, + // Actually a union. We only expose sigev_notify_thread_id because it's + // the most useful member + pub sigev_notify_thread_id: ::c_int, + #[cfg(target_pointer_width = "64")] + __unused1: [::c_int; 11], + #[cfg(target_pointer_width = "32")] + __unused1: [::c_int; 12] + } + + pub struct dirent { + pub d_ino: ::ino_t, + pub d_off: ::off_t, + pub d_reclen: ::c_ushort, + pub d_type: ::c_uchar, + pub d_name: [::c_char; 256], + } + + pub struct dirent64 { + pub d_ino: ::ino64_t, + pub d_off: ::off64_t, + pub d_reclen: ::c_ushort, + pub d_type: ::c_uchar, + pub d_name: [::c_char; 256], + } + + pub struct rlimit64 { + pub rlim_cur: rlim64_t, + pub rlim_max: rlim64_t, + } + + pub struct glob_t { + pub gl_pathc: ::size_t, + pub gl_pathv: *mut *mut c_char, + pub gl_offs: ::size_t, + pub gl_flags: ::c_int, + + __unused1: *mut ::c_void, + __unused2: *mut ::c_void, + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + } + + pub struct ifaddrs { + pub ifa_next: *mut ifaddrs, + pub ifa_name: *mut c_char, + pub ifa_flags: ::c_uint, + pub ifa_addr: *mut ::sockaddr, + pub ifa_netmask: *mut ::sockaddr, + pub ifa_ifu: *mut ::sockaddr, // FIXME This should be a union + pub ifa_data: *mut ::c_void + } + + pub struct pthread_mutex_t { + #[cfg(any(target_arch = "mips", target_arch = "arm", + target_arch = "powerpc"))] + __align: [::c_long; 0], + #[cfg(not(any(target_arch = "mips", target_arch = "arm", + target_arch = "powerpc")))] + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_MUTEX_T], + } + + pub struct pthread_rwlock_t { + #[cfg(any(target_arch = "mips", target_arch = "arm", + target_arch = "powerpc"))] + __align: [::c_long; 0], + #[cfg(not(any(target_arch = "mips", target_arch = "arm", + target_arch = "powerpc")))] + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_RWLOCK_T], + } + + pub struct pthread_mutexattr_t { + #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", + target_arch = "mips64", target_arch = "s390x", + target_arch = "sparc64"))] + __align: [::c_int; 0], + #[cfg(not(any(target_arch = "x86_64", target_arch = "powerpc64", + target_arch = "mips64", target_arch = "s390x", + target_arch = "sparc64")))] + __align: [::c_long; 0], + size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T], + } + + pub struct pthread_rwlockattr_t { + __lockkind: ::c_int, + __pshared: ::c_int, + } + + pub struct pthread_cond_t { + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_COND_T], + } + + pub struct pthread_condattr_t { + __align: [::c_int; 0], + size: [u8; __SIZEOF_PTHREAD_CONDATTR_T], + } + + pub struct passwd { + pub pw_name: *mut ::c_char, + pub pw_passwd: *mut ::c_char, + pub pw_uid: ::uid_t, + pub pw_gid: ::gid_t, + pub pw_gecos: *mut ::c_char, + pub pw_dir: *mut ::c_char, + pub pw_shell: *mut ::c_char, + } + + pub struct spwd { + pub sp_namp: *mut ::c_char, + pub sp_pwdp: *mut ::c_char, + pub sp_lstchg: ::c_long, + pub sp_min: ::c_long, + pub sp_max: ::c_long, + pub sp_warn: ::c_long, + pub sp_inact: ::c_long, + pub sp_expire: ::c_long, + pub sp_flag: ::c_ulong, + } + + pub struct statvfs { + pub f_bsize: ::c_ulong, + pub f_frsize: ::c_ulong, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_favail: ::fsfilcnt_t, + #[cfg(target_endian = "little")] + pub f_fsid: ::c_ulong, + #[cfg(target_pointer_width = "32")] + __f_unused: ::c_int, + #[cfg(target_endian = "big")] + pub f_fsid: ::c_ulong, + pub f_flag: ::c_ulong, + pub f_namemax: ::c_ulong, + __f_spare: [::c_int; 6], + } + + pub struct dqblk { + pub dqb_bhardlimit: ::uint32_t, + pub dqb_bsoftlimit: ::uint32_t, + pub dqb_curblocks: ::uint32_t, + pub dqb_ihardlimit: ::uint32_t, + pub dqb_isoftlimit: ::uint32_t, + pub dqb_curinodes: ::uint32_t, + pub dqb_btime: ::time_t, + pub dqb_itime: ::time_t, + } + + pub struct signalfd_siginfo { + pub ssi_signo: ::uint32_t, + pub ssi_errno: ::int32_t, + pub ssi_code: ::int32_t, + pub ssi_pid: ::uint32_t, + pub ssi_uid: ::uint32_t, + pub ssi_fd: ::int32_t, + pub ssi_tid: ::uint32_t, + pub ssi_band: ::uint32_t, + pub ssi_overrun: ::uint32_t, + pub ssi_trapno: ::uint32_t, + pub ssi_status: ::int32_t, + pub ssi_int: ::int32_t, + pub ssi_ptr: ::uint64_t, + pub ssi_utime: ::uint64_t, + pub ssi_stime: ::uint64_t, + pub ssi_addr: ::uint64_t, + _pad: [::uint8_t; 48], + } + + pub struct fsid_t { + __val: [::c_int; 2], + } + + pub struct mq_attr { + pub mq_flags: ::c_long, + pub mq_maxmsg: ::c_long, + pub mq_msgsize: ::c_long, + pub mq_curmsgs: ::c_long, + pad: [::c_long; 4] + } + + pub struct cpu_set_t { + #[cfg(target_pointer_width = "32")] + bits: [u32; 32], + #[cfg(target_pointer_width = "64")] + bits: [u64; 16], + } + + pub struct if_nameindex { + pub if_index: ::c_uint, + pub if_name: *mut ::c_char, + } + + // System V IPC + pub struct msginfo { + pub msgpool: ::c_int, + pub msgmap: ::c_int, + pub msgmax: ::c_int, + pub msgmnb: ::c_int, + pub msgmni: ::c_int, + pub msgssz: ::c_int, + pub msgtql: ::c_int, + pub msgseg: ::c_ushort, + } +} + +// intentionally not public, only used for fd_set +cfg_if! { + if #[cfg(target_pointer_width = "32")] { + const ULONG_SIZE: usize = 32; + } else if #[cfg(target_pointer_width = "64")] { + const ULONG_SIZE: usize = 64; + } else { + // Unknown target_pointer_width + } +} + +pub const EXIT_FAILURE: ::c_int = 1; +pub const EXIT_SUCCESS: ::c_int = 0; +pub const RAND_MAX: ::c_int = 2147483647; +pub const EOF: ::c_int = -1; +pub const SEEK_SET: ::c_int = 0; +pub const SEEK_CUR: ::c_int = 1; +pub const SEEK_END: ::c_int = 2; +pub const _IOFBF: ::c_int = 0; +pub const _IONBF: ::c_int = 2; +pub const _IOLBF: ::c_int = 1; + +pub const F_DUPFD: ::c_int = 0; +pub const F_GETFD: ::c_int = 1; +pub const F_SETFD: ::c_int = 2; +pub const F_GETFL: ::c_int = 3; +pub const F_SETFL: ::c_int = 4; + +// Linux-specific fcntls +pub const F_SETLEASE: ::c_int = 1024; +pub const F_GETLEASE: ::c_int = 1025; +pub const F_NOTIFY: ::c_int = 1026; +pub const F_DUPFD_CLOEXEC: ::c_int = 1030; + +// TODO(#235): Include file sealing fcntls once we have a way to verify them. + +pub const SIGTRAP: ::c_int = 5; + +pub const PTHREAD_CREATE_JOINABLE: ::c_int = 0; +pub const PTHREAD_CREATE_DETACHED: ::c_int = 1; + +pub const CLOCK_REALTIME: ::clockid_t = 0; +pub const CLOCK_MONOTONIC: ::clockid_t = 1; +pub const CLOCK_PROCESS_CPUTIME_ID: ::clockid_t = 2; +pub const CLOCK_THREAD_CPUTIME_ID: ::clockid_t = 3; +// TODO(#247) Someday our Travis shall have glibc 2.21 (released in Sep +// 2014.) See also musl/mod.rs +// pub const CLOCK_SGI_CYCLE: ::clockid_t = 10; +// pub const CLOCK_TAI: ::clockid_t = 11; +pub const TIMER_ABSTIME: ::c_int = 1; + +pub const RLIMIT_CPU: ::c_int = 0; +pub const RLIMIT_FSIZE: ::c_int = 1; +pub const RLIMIT_DATA: ::c_int = 2; +pub const RLIMIT_STACK: ::c_int = 3; +pub const RLIMIT_CORE: ::c_int = 4; +pub const RLIMIT_LOCKS: ::c_int = 10; +pub const RLIMIT_SIGPENDING: ::c_int = 11; +pub const RLIMIT_MSGQUEUE: ::c_int = 12; +pub const RLIMIT_NICE: ::c_int = 13; +pub const RLIMIT_RTPRIO: ::c_int = 14; + +pub const RUSAGE_SELF: ::c_int = 0; + +pub const O_RDONLY: ::c_int = 0; +pub const O_WRONLY: ::c_int = 1; +pub const O_RDWR: ::c_int = 2; + +pub const SOCK_CLOEXEC: ::c_int = O_CLOEXEC; + +pub const S_IFIFO: ::mode_t = 4096; +pub const S_IFCHR: ::mode_t = 8192; +pub const S_IFBLK: ::mode_t = 24576; +pub const S_IFDIR: ::mode_t = 16384; +pub const S_IFREG: ::mode_t = 32768; +pub const S_IFLNK: ::mode_t = 40960; +pub const S_IFSOCK: ::mode_t = 49152; +pub const S_IFMT: ::mode_t = 61440; +pub const S_IRWXU: ::mode_t = 448; +pub const S_IXUSR: ::mode_t = 64; +pub const S_IWUSR: ::mode_t = 128; +pub const S_IRUSR: ::mode_t = 256; +pub const S_IRWXG: ::mode_t = 56; +pub const S_IXGRP: ::mode_t = 8; +pub const S_IWGRP: ::mode_t = 16; +pub const S_IRGRP: ::mode_t = 32; +pub const S_IRWXO: ::mode_t = 7; +pub const S_IXOTH: ::mode_t = 1; +pub const S_IWOTH: ::mode_t = 2; +pub const S_IROTH: ::mode_t = 4; +pub const F_OK: ::c_int = 0; +pub const R_OK: ::c_int = 4; +pub const W_OK: ::c_int = 2; +pub const X_OK: ::c_int = 1; +pub const STDIN_FILENO: ::c_int = 0; +pub const STDOUT_FILENO: ::c_int = 1; +pub const STDERR_FILENO: ::c_int = 2; +pub const SIGHUP: ::c_int = 1; +pub const SIGINT: ::c_int = 2; +pub const SIGQUIT: ::c_int = 3; +pub const SIGILL: ::c_int = 4; +pub const SIGABRT: ::c_int = 6; +pub const SIGFPE: ::c_int = 8; +pub const SIGKILL: ::c_int = 9; +pub const SIGSEGV: ::c_int = 11; +pub const SIGPIPE: ::c_int = 13; +pub const SIGALRM: ::c_int = 14; +pub const SIGTERM: ::c_int = 15; + +pub const PROT_NONE: ::c_int = 0; +pub const PROT_READ: ::c_int = 1; +pub const PROT_WRITE: ::c_int = 2; +pub const PROT_EXEC: ::c_int = 4; + +pub const LC_CTYPE: ::c_int = 0; +pub const LC_NUMERIC: ::c_int = 1; +pub const LC_MONETARY: ::c_int = 2; +pub const LC_TIME: ::c_int = 3; +pub const LC_COLLATE: ::c_int = 4; +pub const LC_MESSAGES: ::c_int = 5; +pub const LC_ALL: ::c_int = 6; +pub const LC_CTYPE_MASK: ::c_int = (1 << LC_CTYPE); +pub const LC_NUMERIC_MASK: ::c_int = (1 << LC_NUMERIC); +pub const LC_TIME_MASK: ::c_int = (1 << LC_TIME); +pub const LC_COLLATE_MASK: ::c_int = (1 << LC_COLLATE); +pub const LC_MONETARY_MASK: ::c_int = (1 << LC_MONETARY); +pub const LC_MESSAGES_MASK: ::c_int = (1 << LC_MESSAGES); +// LC_ALL_MASK defined per platform + +pub const MAP_FILE: ::c_int = 0x0000; +pub const MAP_SHARED: ::c_int = 0x0001; +pub const MAP_PRIVATE: ::c_int = 0x0002; +pub const MAP_FIXED: ::c_int = 0x0010; + +pub const MAP_FAILED: *mut ::c_void = !0 as *mut ::c_void; + +// MS_ flags for msync(2) +pub const MS_ASYNC: ::c_int = 0x0001; +pub const MS_INVALIDATE: ::c_int = 0x0002; +pub const MS_SYNC: ::c_int = 0x0004; + +// MS_ flags for mount(2) +pub const MS_RDONLY: ::c_ulong = 0x01; +pub const MS_NOSUID: ::c_ulong = 0x02; +pub const MS_NODEV: ::c_ulong = 0x04; +pub const MS_NOEXEC: ::c_ulong = 0x08; +pub const MS_SYNCHRONOUS: ::c_ulong = 0x10; +pub const MS_REMOUNT: ::c_ulong = 0x20; +pub const MS_MANDLOCK: ::c_ulong = 0x40; +pub const MS_NOATIME: ::c_ulong = 0x0400; +pub const MS_NODIRATIME: ::c_ulong = 0x0800; +pub const MS_BIND: ::c_ulong = 0x1000; +pub const MS_NOUSER: ::c_ulong = 0x80000000; +pub const MS_MGC_VAL: ::c_ulong = 0xc0ed0000; +pub const MS_MGC_MSK: ::c_ulong = 0xffff0000; +pub const MS_RMT_MASK: ::c_ulong = 0x800051; + +pub const EPERM: ::c_int = 1; +pub const ENOENT: ::c_int = 2; +pub const ESRCH: ::c_int = 3; +pub const EINTR: ::c_int = 4; +pub const EIO: ::c_int = 5; +pub const ENXIO: ::c_int = 6; +pub const E2BIG: ::c_int = 7; +pub const ENOEXEC: ::c_int = 8; +pub const EBADF: ::c_int = 9; +pub const ECHILD: ::c_int = 10; +pub const EAGAIN: ::c_int = 11; +pub const ENOMEM: ::c_int = 12; +pub const EACCES: ::c_int = 13; +pub const EFAULT: ::c_int = 14; +pub const ENOTBLK: ::c_int = 15; +pub const EBUSY: ::c_int = 16; +pub const EEXIST: ::c_int = 17; +pub const EXDEV: ::c_int = 18; +pub const ENODEV: ::c_int = 19; +pub const ENOTDIR: ::c_int = 20; +pub const EISDIR: ::c_int = 21; +pub const EINVAL: ::c_int = 22; +pub const ENFILE: ::c_int = 23; +pub const EMFILE: ::c_int = 24; +pub const ENOTTY: ::c_int = 25; +pub const ETXTBSY: ::c_int = 26; +pub const EFBIG: ::c_int = 27; +pub const ENOSPC: ::c_int = 28; +pub const ESPIPE: ::c_int = 29; +pub const EROFS: ::c_int = 30; +pub const EMLINK: ::c_int = 31; +pub const EPIPE: ::c_int = 32; +pub const EDOM: ::c_int = 33; +pub const ERANGE: ::c_int = 34; +pub const EWOULDBLOCK: ::c_int = EAGAIN; + +pub const SCM_RIGHTS: ::c_int = 0x01; +pub const SCM_CREDENTIALS: ::c_int = 0x02; + +// netinet/in.h +// NOTE: These are in addition to the constants defined in src/unix/mod.rs + +// IPPROTO_IP defined in src/unix/mod.rs +/// Hop-by-hop option header +pub const IPPROTO_HOPOPTS: ::c_int = 0; +// IPPROTO_ICMP defined in src/unix/mod.rs +/// group mgmt protocol +pub const IPPROTO_IGMP: ::c_int = 2; +/// for compatibility +pub const IPPROTO_IPIP: ::c_int = 4; +// IPPROTO_TCP defined in src/unix/mod.rs +/// exterior gateway protocol +pub const IPPROTO_EGP: ::c_int = 8; +/// pup +pub const IPPROTO_PUP: ::c_int = 12; +// IPPROTO_UDP defined in src/unix/mod.rs +/// xns idp +pub const IPPROTO_IDP: ::c_int = 22; +/// tp-4 w/ class negotiation +pub const IPPROTO_TP: ::c_int = 29; +/// DCCP +pub const IPPROTO_DCCP: ::c_int = 33; +// IPPROTO_IPV6 defined in src/unix/mod.rs +/// IP6 routing header +pub const IPPROTO_ROUTING: ::c_int = 43; +/// IP6 fragmentation header +pub const IPPROTO_FRAGMENT: ::c_int = 44; +/// resource reservation +pub const IPPROTO_RSVP: ::c_int = 46; +/// General Routing Encap. +pub const IPPROTO_GRE: ::c_int = 47; +/// IP6 Encap Sec. Payload +pub const IPPROTO_ESP: ::c_int = 50; +/// IP6 Auth Header +pub const IPPROTO_AH: ::c_int = 51; +// IPPROTO_ICMPV6 defined in src/unix/mod.rs +/// IP6 no next header +pub const IPPROTO_NONE: ::c_int = 59; +/// IP6 destination option +pub const IPPROTO_DSTOPTS: ::c_int = 60; +pub const IPPROTO_MTP: ::c_int = 92; +pub const IPPROTO_BEETPH: ::c_int = 94; +/// encapsulation header +pub const IPPROTO_ENCAP: ::c_int = 98; +/// Protocol indep. multicast +pub const IPPROTO_PIM: ::c_int = 103; +/// IP Payload Comp. Protocol +pub const IPPROTO_COMP: ::c_int = 108; +/// SCTP +pub const IPPROTO_SCTP: ::c_int = 132; +pub const IPPROTO_MH: ::c_int = 135; +pub const IPPROTO_UDPLITE: ::c_int = 136; +pub const IPPROTO_MPLS: ::c_int = 137; +/// raw IP packet +pub const IPPROTO_RAW: ::c_int = 255; +pub const IPPROTO_MAX: ::c_int = 256; + +pub const PROT_GROWSDOWN: ::c_int = 0x1000000; +pub const PROT_GROWSUP: ::c_int = 0x2000000; + +pub const MAP_TYPE: ::c_int = 0x000f; + +pub const MADV_NORMAL: ::c_int = 0; +pub const MADV_RANDOM: ::c_int = 1; +pub const MADV_SEQUENTIAL: ::c_int = 2; +pub const MADV_WILLNEED: ::c_int = 3; +pub const MADV_DONTNEED: ::c_int = 4; +pub const MADV_REMOVE: ::c_int = 9; +pub const MADV_DONTFORK: ::c_int = 10; +pub const MADV_DOFORK: ::c_int = 11; +pub const MADV_MERGEABLE: ::c_int = 12; +pub const MADV_UNMERGEABLE: ::c_int = 13; +pub const MADV_HWPOISON: ::c_int = 100; + +// https://github.com/kraj/uClibc/blob/master/include/net/if.h#L44 +pub const IFF_UP: ::c_int = 0x1; // Interface is up. +pub const IFF_BROADCAST: ::c_int = 0x2; // Broadcast address valid. +pub const IFF_DEBUG: ::c_int = 0x4; // Turn on debugging. +pub const IFF_LOOPBACK: ::c_int = 0x8; // Is a loopback net. +pub const IFF_POINTOPOINT: ::c_int = 0x10; // Interface is point-to-point link. +pub const IFF_NOTRAILERS: ::c_int = 0x20; // Avoid use of trailers. +pub const IFF_RUNNING: ::c_int = 0x40; // Resources allocated. +pub const IFF_NOARP: ::c_int = 0x80; // No address resolution protocol. +pub const IFF_PROMISC: ::c_int = 0x100; // Receive all packets. +// Not supported +pub const IFF_ALLMULTI: ::c_int = 0x200; // Receive all multicast packets. +pub const IFF_MASTER: ::c_int = 0x400; // Master of a load balancer. +pub const IFF_SLAVE: ::c_int = 0x800; // Slave of a load balancer. +pub const IFF_MULTICAST: ::c_int = 0x1000; // Supports multicast. +pub const IFF_PORTSEL: ::c_int = 0x2000; // Can set media type. +pub const IFF_AUTOMEDIA: ::c_int = 0x4000; // Auto media select active. +// Dialup device with changing addresses. +pub const IFF_DYNAMIC: ::c_int = 0x8000; + +pub const SOL_IP: ::c_int = 0; +pub const SOL_TCP: ::c_int = 6; +pub const SOL_IPV6: ::c_int = 41; +pub const SOL_ICMPV6: ::c_int = 58; +pub const SOL_RAW: ::c_int = 255; +pub const SOL_DECNET: ::c_int = 261; +pub const SOL_X25: ::c_int = 262; +pub const SOL_PACKET: ::c_int = 263; +pub const SOL_ATM: ::c_int = 264; +pub const SOL_AAL: ::c_int = 265; +pub const SOL_IRDA: ::c_int = 266; + +pub const AF_UNSPEC: ::c_int = 0; +pub const AF_UNIX: ::c_int = 1; +pub const AF_LOCAL: ::c_int = 1; +pub const AF_INET: ::c_int = 2; +pub const AF_AX25: ::c_int = 3; +pub const AF_IPX: ::c_int = 4; +pub const AF_APPLETALK: ::c_int = 5; +pub const AF_NETROM: ::c_int = 6; +pub const AF_BRIDGE: ::c_int = 7; +pub const AF_ATMPVC: ::c_int = 8; +pub const AF_X25: ::c_int = 9; +pub const AF_INET6: ::c_int = 10; +pub const AF_ROSE: ::c_int = 11; +pub const AF_DECnet: ::c_int = 12; +pub const AF_NETBEUI: ::c_int = 13; +pub const AF_SECURITY: ::c_int = 14; +pub const AF_KEY: ::c_int = 15; +pub const AF_NETLINK: ::c_int = 16; +pub const AF_ROUTE: ::c_int = AF_NETLINK; +pub const AF_PACKET: ::c_int = 17; +pub const AF_ASH: ::c_int = 18; +pub const AF_ECONET: ::c_int = 19; +pub const AF_ATMSVC: ::c_int = 20; +pub const AF_SNA: ::c_int = 22; +pub const AF_IRDA: ::c_int = 23; +pub const AF_PPPOX: ::c_int = 24; +pub const AF_WANPIPE: ::c_int = 25; +pub const AF_LLC: ::c_int = 26; +pub const AF_CAN: ::c_int = 29; +pub const AF_TIPC: ::c_int = 30; +pub const AF_BLUETOOTH: ::c_int = 31; +pub const AF_IUCV: ::c_int = 32; +pub const AF_RXRPC: ::c_int = 33; +pub const AF_ISDN: ::c_int = 34; +pub const AF_PHONET: ::c_int = 35; +pub const AF_IEEE802154: ::c_int = 36; +pub const AF_CAIF: ::c_int = 37; +pub const AF_ALG: ::c_int = 38; + +pub const PF_UNSPEC: ::c_int = AF_UNSPEC; +pub const PF_UNIX: ::c_int = AF_UNIX; +pub const PF_LOCAL: ::c_int = AF_LOCAL; +pub const PF_INET: ::c_int = AF_INET; +pub const PF_AX25: ::c_int = AF_AX25; +pub const PF_IPX: ::c_int = AF_IPX; +pub const PF_APPLETALK: ::c_int = AF_APPLETALK; +pub const PF_NETROM: ::c_int = AF_NETROM; +pub const PF_BRIDGE: ::c_int = AF_BRIDGE; +pub const PF_ATMPVC: ::c_int = AF_ATMPVC; +pub const PF_X25: ::c_int = AF_X25; +pub const PF_INET6: ::c_int = AF_INET6; +pub const PF_ROSE: ::c_int = AF_ROSE; +pub const PF_DECnet: ::c_int = AF_DECnet; +pub const PF_NETBEUI: ::c_int = AF_NETBEUI; +pub const PF_SECURITY: ::c_int = AF_SECURITY; +pub const PF_KEY: ::c_int = AF_KEY; +pub const PF_NETLINK: ::c_int = AF_NETLINK; +pub const PF_ROUTE: ::c_int = AF_ROUTE; +pub const PF_PACKET: ::c_int = AF_PACKET; +pub const PF_ASH: ::c_int = AF_ASH; +pub const PF_ECONET: ::c_int = AF_ECONET; +pub const PF_ATMSVC: ::c_int = AF_ATMSVC; +pub const PF_SNA: ::c_int = AF_SNA; +pub const PF_IRDA: ::c_int = AF_IRDA; +pub const PF_PPPOX: ::c_int = AF_PPPOX; +pub const PF_WANPIPE: ::c_int = AF_WANPIPE; +pub const PF_LLC: ::c_int = AF_LLC; +pub const PF_CAN: ::c_int = AF_CAN; +pub const PF_TIPC: ::c_int = AF_TIPC; +pub const PF_BLUETOOTH: ::c_int = AF_BLUETOOTH; +pub const PF_IUCV: ::c_int = AF_IUCV; +pub const PF_RXRPC: ::c_int = AF_RXRPC; +pub const PF_ISDN: ::c_int = AF_ISDN; +pub const PF_PHONET: ::c_int = AF_PHONET; +pub const PF_IEEE802154: ::c_int = AF_IEEE802154; +pub const PF_CAIF: ::c_int = AF_CAIF; +pub const PF_ALG: ::c_int = AF_ALG; + +pub const SOMAXCONN: ::c_int = 128; + +pub const MSG_OOB: ::c_int = 1; +pub const MSG_PEEK: ::c_int = 2; +pub const MSG_DONTROUTE: ::c_int = 4; +pub const MSG_CTRUNC: ::c_int = 8; +pub const MSG_TRUNC: ::c_int = 0x20; +pub const MSG_DONTWAIT: ::c_int = 0x40; +pub const MSG_EOR: ::c_int = 0x80; +pub const MSG_WAITALL: ::c_int = 0x100; +pub const MSG_FIN: ::c_int = 0x200; +pub const MSG_SYN: ::c_int = 0x400; +pub const MSG_CONFIRM: ::c_int = 0x800; +pub const MSG_RST: ::c_int = 0x1000; +pub const MSG_ERRQUEUE: ::c_int = 0x2000; +pub const MSG_NOSIGNAL: ::c_int = 0x4000; +pub const MSG_MORE: ::c_int = 0x8000; +pub const MSG_WAITFORONE: ::c_int = 0x10000; +pub const MSG_CMSG_CLOEXEC: ::c_int = 0x40000000; + +pub const SOCK_RAW: ::c_int = 3; +pub const IP_MULTICAST_TTL: ::c_int = 33; +pub const IP_MULTICAST_LOOP: ::c_int = 34; +pub const IP_TTL: ::c_int = 2; +pub const IP_HDRINCL: ::c_int = 3; +pub const IP_ADD_MEMBERSHIP: ::c_int = 35; +pub const IP_DROP_MEMBERSHIP: ::c_int = 36; +pub const IPV6_ADD_MEMBERSHIP: ::c_int = 20; +pub const IPV6_DROP_MEMBERSHIP: ::c_int = 21; + +pub const IPV6_JOIN_GROUP: ::c_int = 20; +pub const IPV6_LEAVE_GROUP: ::c_int = 21; + +pub const TCP_NODELAY: ::c_int = 1; +pub const TCP_MAXSEG: ::c_int = 2; +pub const TCP_CORK: ::c_int = 3; +pub const TCP_KEEPIDLE: ::c_int = 4; +pub const TCP_KEEPINTVL: ::c_int = 5; +pub const TCP_KEEPCNT: ::c_int = 6; +pub const TCP_SYNCNT: ::c_int = 7; +pub const TCP_LINGER2: ::c_int = 8; +pub const TCP_DEFER_ACCEPT: ::c_int = 9; +pub const TCP_WINDOW_CLAMP: ::c_int = 10; +pub const TCP_INFO: ::c_int = 11; +pub const TCP_QUICKACK: ::c_int = 12; +pub const TCP_CONGESTION: ::c_int = 13; + +pub const IPV6_MULTICAST_LOOP: ::c_int = 19; +pub const IPV6_V6ONLY: ::c_int = 26; + +pub const SO_DEBUG: ::c_int = 1; + +pub const SHUT_RD: ::c_int = 0; +pub const SHUT_WR: ::c_int = 1; +pub const SHUT_RDWR: ::c_int = 2; + +pub const LOCK_SH: ::c_int = 1; +pub const LOCK_EX: ::c_int = 2; +pub const LOCK_NB: ::c_int = 4; +pub const LOCK_UN: ::c_int = 8; + +pub const SS_ONSTACK: ::c_int = 1; +pub const SS_DISABLE: ::c_int = 2; + +pub const PATH_MAX: ::c_int = 4096; + +pub const FD_SETSIZE: usize = 1024; + +pub const EPOLLIN: ::c_int = 0x1; +pub const EPOLLPRI: ::c_int = 0x2; +pub const EPOLLOUT: ::c_int = 0x4; +pub const EPOLLRDNORM: ::c_int = 0x40; +pub const EPOLLRDBAND: ::c_int = 0x80; +pub const EPOLLWRNORM: ::c_int = 0x100; +pub const EPOLLWRBAND: ::c_int = 0x200; +pub const EPOLLMSG: ::c_int = 0x400; +pub const EPOLLERR: ::c_int = 0x8; +pub const EPOLLHUP: ::c_int = 0x10; +pub const EPOLLET: ::c_int = 0x80000000; + +pub const EPOLL_CTL_ADD: ::c_int = 1; +pub const EPOLL_CTL_MOD: ::c_int = 3; +pub const EPOLL_CTL_DEL: ::c_int = 2; + +pub const MNT_DETACH: ::c_int = 0x2; +pub const MNT_EXPIRE: ::c_int = 0x4; + +pub const MNT_FORCE: ::c_int = 0x1; + +pub const Q_SYNC: ::c_int = 0x600; +pub const Q_QUOTAON: ::c_int = 0x100; +pub const Q_QUOTAOFF: ::c_int = 0x200; +pub const Q_GETQUOTA: ::c_int = 0x300; +pub const Q_SETQUOTA: ::c_int = 0x400; + +pub const TCIOFF: ::c_int = 2; +pub const TCION: ::c_int = 3; +pub const TCOOFF: ::c_int = 0; +pub const TCOON: ::c_int = 1; +pub const TCIFLUSH: ::c_int = 0; +pub const TCOFLUSH: ::c_int = 1; +pub const TCIOFLUSH: ::c_int = 2; +pub const NL0: ::c_int = 0x00000000; +pub const NL1: ::c_int = 0x00000100; +pub const TAB0: ::c_int = 0x00000000; +pub const CR0: ::c_int = 0x00000000; +pub const FF0: ::c_int = 0x00000000; +pub const BS0: ::c_int = 0x00000000; +pub const VT0: ::c_int = 0x00000000; +pub const VERASE: usize = 2; +pub const VKILL: usize = 3; +pub const VINTR: usize = 0; +pub const VQUIT: usize = 1; +pub const VLNEXT: usize = 15; +pub const IGNBRK: ::tcflag_t = 0x00000001; +pub const BRKINT: ::tcflag_t = 0x00000002; +pub const IGNPAR: ::tcflag_t = 0x00000004; +pub const PARMRK: ::tcflag_t = 0x00000008; +pub const INPCK: ::tcflag_t = 0x00000010; +pub const ISTRIP: ::tcflag_t = 0x00000020; +pub const INLCR: ::tcflag_t = 0x00000040; +pub const IGNCR: ::tcflag_t = 0x00000080; +pub const ICRNL: ::tcflag_t = 0x00000100; +pub const IXANY: ::tcflag_t = 0x00000800; +pub const IMAXBEL: ::tcflag_t = 0x00002000; +pub const OPOST: ::tcflag_t = 0x1; +pub const CS5: ::tcflag_t = 0x00000000; +pub const CRTSCTS: ::tcflag_t = 0x80000000; +pub const ECHO: ::tcflag_t = 0x00000008; + +pub const CLONE_VM: ::c_int = 0x100; +pub const CLONE_FS: ::c_int = 0x200; +pub const CLONE_FILES: ::c_int = 0x400; +pub const CLONE_SIGHAND: ::c_int = 0x800; +pub const CLONE_PTRACE: ::c_int = 0x2000; +pub const CLONE_VFORK: ::c_int = 0x4000; +pub const CLONE_PARENT: ::c_int = 0x8000; +pub const CLONE_THREAD: ::c_int = 0x10000; +pub const CLONE_NEWNS: ::c_int = 0x20000; +pub const CLONE_SYSVSEM: ::c_int = 0x40000; +pub const CLONE_SETTLS: ::c_int = 0x80000; +pub const CLONE_PARENT_SETTID: ::c_int = 0x100000; +pub const CLONE_CHILD_CLEARTID: ::c_int = 0x200000; +pub const CLONE_DETACHED: ::c_int = 0x400000; +pub const CLONE_UNTRACED: ::c_int = 0x800000; +pub const CLONE_CHILD_SETTID: ::c_int = 0x01000000; +pub const CLONE_NEWUTS: ::c_int = 0x04000000; +pub const CLONE_NEWIPC: ::c_int = 0x08000000; +pub const CLONE_NEWUSER: ::c_int = 0x10000000; +pub const CLONE_NEWPID: ::c_int = 0x20000000; +pub const CLONE_NEWNET: ::c_int = 0x40000000; +pub const CLONE_IO: ::c_int = 0x80000000; + +pub const WNOHANG: ::c_int = 0x00000001; +pub const WUNTRACED: ::c_int = 0x00000002; +pub const WSTOPPED: ::c_int = WUNTRACED; +pub const WEXITED: ::c_int = 0x00000004; +pub const WCONTINUED: ::c_int = 0x00000008; +pub const WNOWAIT: ::c_int = 0x01000000; + +pub const __WNOTHREAD: ::c_int = 0x20000000; +pub const __WALL: ::c_int = 0x40000000; +pub const __WCLONE: ::c_int = 0x80000000; + +pub const SPLICE_F_MOVE: ::c_uint = 0x01; +pub const SPLICE_F_NONBLOCK: ::c_uint = 0x02; +pub const SPLICE_F_MORE: ::c_uint = 0x04; +pub const SPLICE_F_GIFT: ::c_uint = 0x08; + +pub const RTLD_LOCAL: ::c_int = 0; +pub const RTLD_LAZY: ::c_int = 1; + +pub const POSIX_FADV_NORMAL: ::c_int = 0; +pub const POSIX_FADV_RANDOM: ::c_int = 1; +pub const POSIX_FADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_FADV_WILLNEED: ::c_int = 3; + +pub const AT_FDCWD: ::c_int = -100; +pub const AT_SYMLINK_NOFOLLOW: ::c_int = 0x100; +pub const AT_REMOVEDIR: ::c_int = 0x200; +pub const AT_SYMLINK_FOLLOW: ::c_int = 0x400; + +pub const LOG_CRON: ::c_int = 9 << 3; +pub const LOG_AUTHPRIV: ::c_int = 10 << 3; +pub const LOG_FTP: ::c_int = 11 << 3; +pub const LOG_PERROR: ::c_int = 0x20; + +pub const POLLIN: ::c_short = 0x1; +pub const POLLPRI: ::c_short = 0x2; +pub const POLLOUT: ::c_short = 0x4; +pub const POLLERR: ::c_short = 0x8; +pub const POLLHUP: ::c_short = 0x10; +pub const POLLNVAL: ::c_short = 0x20; + +pub const PIPE_BUF: usize = 4096; + +pub const SI_LOAD_SHIFT: ::c_uint = 16; + +pub const SIGEV_SIGNAL: ::c_int = 0; +pub const SIGEV_NONE: ::c_int = 1; +pub const SIGEV_THREAD: ::c_int = 2; + +pub const P_ALL: idtype_t = 0; +pub const P_PID: idtype_t = 1; +pub const P_PGID: idtype_t = 2; + +pub const UTIME_OMIT: c_long = 1073741822; +pub const UTIME_NOW: c_long = 1073741823; + +pub const L_tmpnam: ::c_uint = 20; +pub const _PC_LINK_MAX: ::c_int = 0; +pub const _PC_MAX_CANON: ::c_int = 1; +pub const _PC_MAX_INPUT: ::c_int = 2; +pub const _PC_NAME_MAX: ::c_int = 3; +pub const _PC_PATH_MAX: ::c_int = 4; +pub const _PC_PIPE_BUF: ::c_int = 5; +pub const _PC_CHOWN_RESTRICTED: ::c_int = 6; +pub const _PC_NO_TRUNC: ::c_int = 7; +pub const _PC_VDISABLE: ::c_int = 8; + +pub const _SC_ARG_MAX: ::c_int = 0; +pub const _SC_CHILD_MAX: ::c_int = 1; +pub const _SC_CLK_TCK: ::c_int = 2; +pub const _SC_NGROUPS_MAX: ::c_int = 3; +pub const _SC_OPEN_MAX: ::c_int = 4; +pub const _SC_STREAM_MAX: ::c_int = 5; +pub const _SC_TZNAME_MAX: ::c_int = 6; +pub const _SC_JOB_CONTROL: ::c_int = 7; +pub const _SC_SAVED_IDS: ::c_int = 8; +pub const _SC_REALTIME_SIGNALS: ::c_int = 9; +pub const _SC_PRIORITY_SCHEDULING: ::c_int = 10; +pub const _SC_TIMERS: ::c_int = 11; +pub const _SC_ASYNCHRONOUS_IO: ::c_int = 12; +pub const _SC_PRIORITIZED_IO: ::c_int = 13; +pub const _SC_SYNCHRONIZED_IO: ::c_int = 14; +pub const _SC_FSYNC: ::c_int = 15; +pub const _SC_MAPPED_FILES: ::c_int = 16; +pub const _SC_MEMLOCK: ::c_int = 17; +pub const _SC_MEMLOCK_RANGE: ::c_int = 18; +pub const _SC_MEMORY_PROTECTION: ::c_int = 19; +pub const _SC_MESSAGE_PASSING: ::c_int = 20; +pub const _SC_SEMAPHORES: ::c_int = 21; +pub const _SC_SHARED_MEMORY_OBJECTS: ::c_int = 22; +pub const _SC_AIO_LISTIO_MAX: ::c_int = 23; +pub const _SC_AIO_MAX: ::c_int = 24; +pub const _SC_AIO_PRIO_DELTA_MAX: ::c_int = 25; +pub const _SC_DELAYTIMER_MAX: ::c_int = 26; +pub const _SC_MQ_OPEN_MAX: ::c_int = 27; +pub const _SC_MQ_PRIO_MAX: ::c_int = 28; +pub const _SC_VERSION: ::c_int = 29; +pub const _SC_PAGESIZE: ::c_int = 30; +pub const _SC_PAGE_SIZE: ::c_int = _SC_PAGESIZE; +pub const _SC_RTSIG_MAX: ::c_int = 31; +pub const _SC_SEM_NSEMS_MAX: ::c_int = 32; +pub const _SC_SEM_VALUE_MAX: ::c_int = 33; +pub const _SC_SIGQUEUE_MAX: ::c_int = 34; +pub const _SC_TIMER_MAX: ::c_int = 35; +pub const _SC_BC_BASE_MAX: ::c_int = 36; +pub const _SC_BC_DIM_MAX: ::c_int = 37; +pub const _SC_BC_SCALE_MAX: ::c_int = 38; +pub const _SC_BC_STRING_MAX: ::c_int = 39; +pub const _SC_COLL_WEIGHTS_MAX: ::c_int = 40; +pub const _SC_EXPR_NEST_MAX: ::c_int = 42; +pub const _SC_LINE_MAX: ::c_int = 43; +pub const _SC_RE_DUP_MAX: ::c_int = 44; +pub const _SC_2_VERSION: ::c_int = 46; +pub const _SC_2_C_BIND: ::c_int = 47; +pub const _SC_2_C_DEV: ::c_int = 48; +pub const _SC_2_FORT_DEV: ::c_int = 49; +pub const _SC_2_FORT_RUN: ::c_int = 50; +pub const _SC_2_SW_DEV: ::c_int = 51; +pub const _SC_2_LOCALEDEF: ::c_int = 52; +pub const _SC_IOV_MAX: ::c_int = 60; +pub const _SC_THREADS: ::c_int = 67; +pub const _SC_THREAD_SAFE_FUNCTIONS: ::c_int = 68; +pub const _SC_GETGR_R_SIZE_MAX: ::c_int = 69; +pub const _SC_GETPW_R_SIZE_MAX: ::c_int = 70; +pub const _SC_LOGIN_NAME_MAX: ::c_int = 71; +pub const _SC_TTY_NAME_MAX: ::c_int = 72; +pub const _SC_THREAD_DESTRUCTOR_ITERATIONS: ::c_int = 73; +pub const _SC_THREAD_KEYS_MAX: ::c_int = 74; +pub const _SC_THREAD_STACK_MIN: ::c_int = 75; +pub const _SC_THREAD_THREADS_MAX: ::c_int = 76; +pub const _SC_THREAD_ATTR_STACKADDR: ::c_int = 77; +pub const _SC_THREAD_ATTR_STACKSIZE: ::c_int = 78; +pub const _SC_THREAD_PRIORITY_SCHEDULING: ::c_int = 79; +pub const _SC_THREAD_PRIO_INHERIT: ::c_int = 80; +pub const _SC_THREAD_PRIO_PROTECT: ::c_int = 81; +pub const _SC_NPROCESSORS_ONLN: ::c_int = 84; +pub const _SC_ATEXIT_MAX: ::c_int = 87; +pub const _SC_XOPEN_VERSION: ::c_int = 89; +pub const _SC_XOPEN_XCU_VERSION: ::c_int = 90; +pub const _SC_XOPEN_UNIX: ::c_int = 91; +pub const _SC_XOPEN_CRYPT: ::c_int = 92; +pub const _SC_XOPEN_ENH_I18N: ::c_int = 93; +pub const _SC_XOPEN_SHM: ::c_int = 94; +pub const _SC_2_CHAR_TERM: ::c_int = 95; +pub const _SC_2_UPE: ::c_int = 97; +pub const _SC_XBS5_ILP32_OFF32: ::c_int = 125; +pub const _SC_XBS5_ILP32_OFFBIG: ::c_int = 126; +pub const _SC_XBS5_LPBIG_OFFBIG: ::c_int = 128; +pub const _SC_XOPEN_LEGACY: ::c_int = 129; +pub const _SC_XOPEN_REALTIME: ::c_int = 130; +pub const _SC_XOPEN_REALTIME_THREADS: ::c_int = 131; +pub const _SC_HOST_NAME_MAX: ::c_int = 180; + +pub const RLIM_SAVED_MAX: ::rlim_t = RLIM_INFINITY; +pub const RLIM_SAVED_CUR: ::rlim_t = RLIM_INFINITY; + +pub const GLOB_ERR: ::c_int = 1 << 0; +pub const GLOB_MARK: ::c_int = 1 << 1; +pub const GLOB_NOSORT: ::c_int = 1 << 2; +pub const GLOB_DOOFFS: ::c_int = 1 << 3; +pub const GLOB_NOCHECK: ::c_int = 1 << 4; +pub const GLOB_APPEND: ::c_int = 1 << 5; +pub const GLOB_NOESCAPE: ::c_int = 1 << 6; + +pub const GLOB_NOSPACE: ::c_int = 1; +pub const GLOB_ABORTED: ::c_int = 2; +pub const GLOB_NOMATCH: ::c_int = 3; + +pub const POSIX_MADV_NORMAL: ::c_int = 0; +pub const POSIX_MADV_RANDOM: ::c_int = 1; +pub const POSIX_MADV_SEQUENTIAL: ::c_int = 2; +pub const POSIX_MADV_WILLNEED: ::c_int = 3; + +pub const S_IEXEC: mode_t = 64; +pub const S_IWRITE: mode_t = 128; +pub const S_IREAD: mode_t = 256; + +pub const F_LOCK: ::c_int = 1; +pub const F_TEST: ::c_int = 3; +pub const F_TLOCK: ::c_int = 2; +pub const F_ULOCK: ::c_int = 0; + +pub const ST_RDONLY: ::c_ulong = 1; +pub const ST_NOSUID: ::c_ulong = 2; +pub const ST_NODEV: ::c_ulong = 4; +pub const ST_NOEXEC: ::c_ulong = 8; +pub const ST_SYNCHRONOUS: ::c_ulong = 16; +pub const ST_MANDLOCK: ::c_ulong = 64; +pub const ST_WRITE: ::c_ulong = 128; +pub const ST_APPEND: ::c_ulong = 256; +pub const ST_IMMUTABLE: ::c_ulong = 512; +pub const ST_NOATIME: ::c_ulong = 1024; +pub const ST_NODIRATIME: ::c_ulong = 2048; + +pub const RTLD_NEXT: *mut ::c_void = -1i64 as *mut ::c_void; +pub const RTLD_DEFAULT: *mut ::c_void = 0i64 as *mut ::c_void; +pub const RTLD_NODELETE: ::c_int = 0x1000; +pub const RTLD_NOW: ::c_int = 0x2; + +pub const TCP_MD5SIG: ::c_int = 14; + +pub const PTHREAD_MUTEX_INITIALIZER: pthread_mutex_t = pthread_mutex_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_MUTEX_T], +}; +pub const PTHREAD_COND_INITIALIZER: pthread_cond_t = pthread_cond_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_COND_T], +}; +pub const PTHREAD_RWLOCK_INITIALIZER: pthread_rwlock_t = pthread_rwlock_t { + __align: [], + size: [0; __SIZEOF_PTHREAD_RWLOCK_T], +}; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; +pub const __SIZEOF_PTHREAD_COND_T: usize = 48; + +pub const SCHED_OTHER: ::c_int = 0; +pub const SCHED_FIFO: ::c_int = 1; +pub const SCHED_RR: ::c_int = 2; +pub const SCHED_BATCH: ::c_int = 3; +pub const SCHED_IDLE: ::c_int = 5; + +// System V IPC +pub const IPC_PRIVATE: ::key_t = 0; + +pub const IPC_CREAT: ::c_int = 0o1000; +pub const IPC_EXCL: ::c_int = 0o2000; +pub const IPC_NOWAIT: ::c_int = 0o4000; + +pub const IPC_RMID: ::c_int = 0; +pub const IPC_SET: ::c_int = 1; +pub const IPC_STAT: ::c_int = 2; +pub const IPC_INFO: ::c_int = 3; +pub const MSG_STAT: ::c_int = 11; +pub const MSG_INFO: ::c_int = 12; + +pub const MSG_NOERROR: ::c_int = 0o10000; +pub const MSG_EXCEPT: ::c_int = 0o20000; + +pub const SHM_R: ::c_int = 0o400; +pub const SHM_W: ::c_int = 0o200; + +pub const SHM_RDONLY: ::c_int = 0o10000; +pub const SHM_RND: ::c_int = 0o20000; +pub const SHM_REMAP: ::c_int = 0o40000; + +pub const SHM_LOCK: ::c_int = 11; +pub const SHM_UNLOCK: ::c_int = 12; + +pub const SHM_HUGETLB: ::c_int = 0o4000; +pub const SHM_NORESERVE: ::c_int = 0o10000; + +pub const EPOLLRDHUP: ::c_int = 0x2000; +pub const EPOLLONESHOT: ::c_int = 0x40000000; + +pub const QFMT_VFS_OLD: ::c_int = 1; +pub const QFMT_VFS_V0: ::c_int = 2; + +pub const EFD_SEMAPHORE: ::c_int = 0x1; + +pub const LOG_NFACILITIES: ::c_int = 24; + +pub const SEM_FAILED: *mut ::sem_t = 0 as *mut sem_t; + +pub const RB_AUTOBOOT: ::c_int = 0x01234567u32 as i32; +pub const RB_HALT_SYSTEM: ::c_int = 0xcdef0123u32 as i32; +pub const RB_ENABLE_CAD: ::c_int = 0x89abcdefu32 as i32; +pub const RB_DISABLE_CAD: ::c_int = 0x00000000u32 as i32; +pub const RB_POWER_OFF: ::c_int = 0x4321fedcu32 as i32; + +pub const AI_PASSIVE: ::c_int = 0x0001; +pub const AI_CANONNAME: ::c_int = 0x0002; +pub const AI_NUMERICHOST: ::c_int = 0x0004; +pub const AI_V4MAPPED: ::c_int = 0x0008; +pub const AI_ALL: ::c_int = 0x0010; +pub const AI_ADDRCONFIG: ::c_int = 0x0020; + +pub const AI_NUMERICSERV: ::c_int = 0x0400; + +pub const EAI_BADFLAGS: ::c_int = -1; +pub const EAI_NONAME: ::c_int = -2; +pub const EAI_AGAIN: ::c_int = -3; +pub const EAI_FAIL: ::c_int = -4; +pub const EAI_FAMILY: ::c_int = -6; +pub const EAI_SOCKTYPE: ::c_int = -7; +pub const EAI_SERVICE: ::c_int = -8; +pub const EAI_MEMORY: ::c_int = -10; +pub const EAI_OVERFLOW: ::c_int = -12; + +pub const NI_NUMERICHOST: ::c_int = 1; +pub const NI_NUMERICSERV: ::c_int = 2; +pub const NI_NOFQDN: ::c_int = 4; +pub const NI_NAMEREQD: ::c_int = 8; +pub const NI_DGRAM: ::c_int = 16; + +pub const SYNC_FILE_RANGE_WAIT_BEFORE: ::c_uint = 1; +pub const SYNC_FILE_RANGE_WRITE: ::c_uint = 2; +pub const SYNC_FILE_RANGE_WAIT_AFTER: ::c_uint = 4; + +pub const EAI_SYSTEM: ::c_int = -11; + +pub const MREMAP_MAYMOVE: ::c_int = 1; +pub const MREMAP_FIXED: ::c_int = 2; + +pub const PR_SET_PDEATHSIG: ::c_int = 1; +pub const PR_GET_PDEATHSIG: ::c_int = 2; + +pub const PR_GET_DUMPABLE: ::c_int = 3; +pub const PR_SET_DUMPABLE: ::c_int = 4; + +pub const PR_GET_UNALIGN: ::c_int = 5; +pub const PR_SET_UNALIGN: ::c_int = 6; +pub const PR_UNALIGN_NOPRINT: ::c_int = 1; +pub const PR_UNALIGN_SIGBUS: ::c_int = 2; + +pub const PR_GET_KEEPCAPS: ::c_int = 7; +pub const PR_SET_KEEPCAPS: ::c_int = 8; + +pub const PR_GET_FPEMU: ::c_int = 9; +pub const PR_SET_FPEMU: ::c_int = 10; +pub const PR_FPEMU_NOPRINT: ::c_int = 1; +pub const PR_FPEMU_SIGFPE: ::c_int = 2; + +pub const PR_GET_FPEXC: ::c_int = 11; +pub const PR_SET_FPEXC: ::c_int = 12; +pub const PR_FP_EXC_SW_ENABLE: ::c_int = 0x80; +pub const PR_FP_EXC_DIV: ::c_int = 0x010000; +pub const PR_FP_EXC_OVF: ::c_int = 0x020000; +pub const PR_FP_EXC_UND: ::c_int = 0x040000; +pub const PR_FP_EXC_RES: ::c_int = 0x080000; +pub const PR_FP_EXC_INV: ::c_int = 0x100000; +pub const PR_FP_EXC_DISABLED: ::c_int = 0; +pub const PR_FP_EXC_NONRECOV: ::c_int = 1; +pub const PR_FP_EXC_ASYNC: ::c_int = 2; +pub const PR_FP_EXC_PRECISE: ::c_int = 3; + +pub const PR_GET_TIMING: ::c_int = 13; +pub const PR_SET_TIMING: ::c_int = 14; +pub const PR_TIMING_STATISTICAL: ::c_int = 0; +pub const PR_TIMING_TIMESTAMP: ::c_int = 1; + +pub const PR_SET_NAME: ::c_int = 15; +pub const PR_GET_NAME: ::c_int = 16; + +pub const PR_GET_ENDIAN: ::c_int = 19; +pub const PR_SET_ENDIAN: ::c_int = 20; +pub const PR_ENDIAN_BIG: ::c_int = 0; +pub const PR_ENDIAN_LITTLE: ::c_int = 1; +pub const PR_ENDIAN_PPC_LITTLE: ::c_int = 2; + +pub const PR_GET_SECCOMP: ::c_int = 21; +pub const PR_SET_SECCOMP: ::c_int = 22; + +pub const PR_CAPBSET_READ: ::c_int = 23; +pub const PR_CAPBSET_DROP: ::c_int = 24; + +pub const PR_GET_TSC: ::c_int = 25; +pub const PR_SET_TSC: ::c_int = 26; +pub const PR_TSC_ENABLE: ::c_int = 1; +pub const PR_TSC_SIGSEGV: ::c_int = 2; + +pub const PR_GET_SECUREBITS: ::c_int = 27; +pub const PR_SET_SECUREBITS: ::c_int = 28; + +pub const PR_SET_TIMERSLACK: ::c_int = 29; +pub const PR_GET_TIMERSLACK: ::c_int = 30; + +pub const PR_TASK_PERF_EVENTS_DISABLE: ::c_int = 31; +pub const PR_TASK_PERF_EVENTS_ENABLE: ::c_int = 32; + +pub const PR_MCE_KILL: ::c_int = 33; +pub const PR_MCE_KILL_CLEAR: ::c_int = 0; +pub const PR_MCE_KILL_SET: ::c_int = 1; + +pub const PR_MCE_KILL_LATE: ::c_int = 0; +pub const PR_MCE_KILL_EARLY: ::c_int = 1; +pub const PR_MCE_KILL_DEFAULT: ::c_int = 2; + +pub const PR_MCE_KILL_GET: ::c_int = 34; + +pub const PR_SET_MM: ::c_int = 35; +pub const PR_SET_MM_START_CODE: ::c_int = 1; +pub const PR_SET_MM_END_CODE: ::c_int = 2; +pub const PR_SET_MM_START_DATA: ::c_int = 3; +pub const PR_SET_MM_END_DATA: ::c_int = 4; +pub const PR_SET_MM_START_STACK: ::c_int = 5; +pub const PR_SET_MM_START_BRK: ::c_int = 6; +pub const PR_SET_MM_BRK: ::c_int = 7; +pub const PR_SET_MM_ARG_START: ::c_int = 8; +pub const PR_SET_MM_ARG_END: ::c_int = 9; +pub const PR_SET_MM_ENV_START: ::c_int = 10; +pub const PR_SET_MM_ENV_END: ::c_int = 11; +pub const PR_SET_MM_AUXV: ::c_int = 12; +pub const PR_SET_MM_EXE_FILE: ::c_int = 13; +pub const PR_SET_MM_MAP: ::c_int = 14; +pub const PR_SET_MM_MAP_SIZE: ::c_int = 15; + +pub const PR_SET_PTRACER: ::c_int = 0x59616d61; + +pub const PR_SET_CHILD_SUBREAPER: ::c_int = 36; +pub const PR_GET_CHILD_SUBREAPER: ::c_int = 37; + +pub const PR_SET_NO_NEW_PRIVS: ::c_int = 38; +pub const PR_GET_NO_NEW_PRIVS: ::c_int = 39; + +pub const PR_GET_TID_ADDRESS: ::c_int = 40; + +pub const PR_SET_THP_DISABLE: ::c_int = 41; +pub const PR_GET_THP_DISABLE: ::c_int = 42; + +pub const ABDAY_1: ::nl_item = 0x300; +pub const ABDAY_2: ::nl_item = 0x301; +pub const ABDAY_3: ::nl_item = 0x302; +pub const ABDAY_4: ::nl_item = 0x303; +pub const ABDAY_5: ::nl_item = 0x304; +pub const ABDAY_6: ::nl_item = 0x305; +pub const ABDAY_7: ::nl_item = 0x306; + +pub const DAY_1: ::nl_item = 0x307; +pub const DAY_2: ::nl_item = 0x308; +pub const DAY_3: ::nl_item = 0x309; +pub const DAY_4: ::nl_item = 0x30A; +pub const DAY_5: ::nl_item = 0x30B; +pub const DAY_6: ::nl_item = 0x30C; +pub const DAY_7: ::nl_item = 0x30D; + +pub const ABMON_1: ::nl_item = 0x30E; +pub const ABMON_2: ::nl_item = 0x30F; +pub const ABMON_3: ::nl_item = 0x310; +pub const ABMON_4: ::nl_item = 0x311; +pub const ABMON_5: ::nl_item = 0x312; +pub const ABMON_6: ::nl_item = 0x313; +pub const ABMON_7: ::nl_item = 0x314; +pub const ABMON_8: ::nl_item = 0x315; +pub const ABMON_9: ::nl_item = 0x316; +pub const ABMON_10: ::nl_item = 0x317; +pub const ABMON_11: ::nl_item = 0x318; +pub const ABMON_12: ::nl_item = 0x319; + +pub const MON_1: ::nl_item = 0x31A; +pub const MON_2: ::nl_item = 0x31B; +pub const MON_3: ::nl_item = 0x31C; +pub const MON_4: ::nl_item = 0x31D; +pub const MON_5: ::nl_item = 0x31E; +pub const MON_6: ::nl_item = 0x31F; +pub const MON_7: ::nl_item = 0x320; +pub const MON_8: ::nl_item = 0x321; +pub const MON_9: ::nl_item = 0x322; +pub const MON_10: ::nl_item = 0x323; +pub const MON_11: ::nl_item = 0x324; +pub const MON_12: ::nl_item = 0x325; + +pub const AM_STR: ::nl_item = 0x326; +pub const PM_STR: ::nl_item = 0x327; + +pub const D_T_FMT: ::nl_item = 0x328; +pub const D_FMT: ::nl_item = 0x329; +pub const T_FMT: ::nl_item = 0x32A; +pub const T_FMT_AMPM: ::nl_item = 0x32B; + +pub const ERA: ::nl_item = 0x32C; +pub const ERA_D_FMT: ::nl_item = 0x32E; +pub const ALT_DIGITS: ::nl_item = 0x32F; +pub const ERA_D_T_FMT: ::nl_item = 0x330; +pub const ERA_T_FMT: ::nl_item = 0x331; + +pub const CODESET: ::nl_item = 10; + +pub const CRNCYSTR: ::nl_item = 0x215; + +pub const RADIXCHAR: ::nl_item = 0x100; +pub const THOUSEP: ::nl_item = 0x101; + +pub const NOEXPR: ::nl_item = 0x501; +pub const YESSTR: ::nl_item = 0x502; +pub const NOSTR: ::nl_item = 0x503; + +pub const FILENAME_MAX: ::c_uint = 4095; + +pub const AF_MAX: ::c_int = 39; + +f! { + pub fn FD_CLR(fd: ::c_int, set: *mut fd_set) -> () { + let fd = fd as usize; + let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; + (*set).fds_bits[fd / size] &= !(1 << (fd % size)); + return + } + + pub fn FD_ISSET(fd: ::c_int, set: *mut fd_set) -> bool { + let fd = fd as usize; + let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; + return ((*set).fds_bits[fd / size] & (1 << (fd % size))) != 0 + } + + pub fn FD_SET(fd: ::c_int, set: *mut fd_set) -> () { + let fd = fd as usize; + let size = mem::size_of_val(&(*set).fds_bits[0]) * 8; + (*set).fds_bits[fd / size] |= 1 << (fd % size); + return + } + + pub fn FD_ZERO(set: *mut fd_set) -> () { + for slot in (*set).fds_bits.iter_mut() { + *slot = 0; + } + } + + pub fn WIFSTOPPED(status: ::c_int) -> bool { + (status & 0xff) == 0x7f + } + + pub fn WSTOPSIG(status: ::c_int) -> ::c_int { + (status >> 8) & 0xff + } + + pub fn WIFCONTINUED(status: ::c_int) -> bool { + status == 0xffff + } + + pub fn WIFSIGNALED(status: ::c_int) -> bool { + ((status & 0x7f) + 1) as i8 >= 2 + } + + pub fn WTERMSIG(status: ::c_int) -> ::c_int { + status & 0x7f + } + + pub fn WIFEXITED(status: ::c_int) -> bool { + (status & 0x7f) == 0 + } + + pub fn WEXITSTATUS(status: ::c_int) -> ::c_int { + (status >> 8) & 0xff + } + + pub fn WCOREDUMP(status: ::c_int) -> bool { + (status & 0x80) != 0 + } + + pub fn CPU_ZERO(cpuset: &mut cpu_set_t) -> () { + for slot in cpuset.bits.iter_mut() { + *slot = 0; + } + } + + pub fn CPU_SET(cpu: usize, cpuset: &mut cpu_set_t) -> () { + let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc + let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); + cpuset.bits[idx] |= 1 << offset; + () + } + + pub fn CPU_CLR(cpu: usize, cpuset: &mut cpu_set_t) -> () { + let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); // 32, 64 etc + let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); + cpuset.bits[idx] &= !(1 << offset); + () + } + + pub fn CPU_ISSET(cpu: usize, cpuset: &cpu_set_t) -> bool { + let size_in_bits = 8 * mem::size_of_val(&cpuset.bits[0]); + let (idx, offset) = (cpu / size_in_bits, cpu % size_in_bits); + 0 != (cpuset.bits[idx] & (1 << offset)) + } + + pub fn CPU_EQUAL(set1: &cpu_set_t, set2: &cpu_set_t) -> bool { + set1.bits == set2.bits + } + + pub fn QCMD(cmd: ::c_int, type_: ::c_int) -> ::c_int { + (cmd << 8) | (type_ & 0x00ff) + } +} + +extern { + pub fn fdatasync(fd: ::c_int) -> ::c_int; + pub fn mincore(addr: *mut ::c_void, len: ::size_t, + vec: *mut ::c_uchar) -> ::c_int; + pub fn clock_getres(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_gettime(clk_id: ::clockid_t, tp: *mut ::timespec) -> ::c_int; + pub fn clock_nanosleep(clk_id: ::clockid_t, + flags: ::c_int, + rqtp: *const ::timespec, + rmtp: *mut ::timespec) -> ::c_int; + pub fn clock_settime(clk_id: ::clockid_t, tp: *const ::timespec) -> ::c_int; + pub fn prctl(option: ::c_int, ...) -> ::c_int; + pub fn pthread_getattr_np(native: ::pthread_t, + attr: *mut ::pthread_attr_t) -> ::c_int; + pub fn pthread_attr_getguardsize(attr: *const ::pthread_attr_t, + guardsize: *mut ::size_t) -> ::c_int; + pub fn pthread_attr_getstack(attr: *const ::pthread_attr_t, + stackaddr: *mut *mut ::c_void, + stacksize: *mut ::size_t) -> ::c_int; + pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; + pub fn setgroups(ngroups: ::size_t, + ptr: *const ::gid_t) -> ::c_int; + pub fn initgroups(user: *const ::c_char, group: ::gid_t) -> ::c_int; + pub fn sched_setscheduler(pid: ::pid_t, + policy: ::c_int, + param: *const ::sched_param) -> ::c_int; + pub fn sched_getscheduler(pid: ::pid_t) -> ::c_int; + pub fn sched_get_priority_max(policy: ::c_int) -> ::c_int; + pub fn sched_get_priority_min(policy: ::c_int) -> ::c_int; + pub fn epoll_create(size: ::c_int) -> ::c_int; + pub fn epoll_create1(flags: ::c_int) -> ::c_int; + pub fn epoll_ctl(epfd: ::c_int, + op: ::c_int, + fd: ::c_int, + event: *mut ::epoll_event) -> ::c_int; + pub fn epoll_wait(epfd: ::c_int, + events: *mut ::epoll_event, + maxevents: ::c_int, + timeout: ::c_int) -> ::c_int; + pub fn pipe2(fds: *mut ::c_int, flags: ::c_int) -> ::c_int; + pub fn mount(src: *const ::c_char, + target: *const ::c_char, + fstype: *const ::c_char, + flags: ::c_ulong, + data: *const ::c_void) -> ::c_int; + pub fn umount(target: *const ::c_char) -> ::c_int; + pub fn umount2(target: *const ::c_char, flags: ::c_int) -> ::c_int; + pub fn clone(cb: extern fn(*mut ::c_void) -> ::c_int, + child_stack: *mut ::c_void, + flags: ::c_int, + arg: *mut ::c_void, ...) -> ::c_int; + pub fn statfs(path: *const ::c_char, buf: *mut statfs) -> ::c_int; + pub fn fstatfs(fd: ::c_int, buf: *mut statfs) -> ::c_int; + pub fn memrchr(cx: *const ::c_void, + c: ::c_int, + n: ::size_t) -> *mut ::c_void; + pub fn syscall(num: ::c_long, ...) -> ::c_long; + pub fn sendfile(out_fd: ::c_int, + in_fd: ::c_int, + offset: *mut off_t, + count: ::size_t) -> ::ssize_t; + pub fn splice(fd_in: ::c_int, + off_in: *mut ::loff_t, + fd_out: ::c_int, + off_out: *mut ::loff_t, + len: ::size_t, + flags: ::c_uint) -> ::ssize_t; + pub fn tee(fd_in: ::c_int, + fd_out: ::c_int, + len: ::size_t, + flags: ::c_uint) -> ::ssize_t; + pub fn vmsplice(fd: ::c_int, + iov: *const ::iovec, + nr_segs: ::size_t, + flags: ::c_uint) -> ::ssize_t; + + pub fn posix_fadvise(fd: ::c_int, offset: ::off_t, len: ::off_t, + advise: ::c_int) -> ::c_int; + pub fn futimens(fd: ::c_int, times: *const ::timespec) -> ::c_int; + pub fn utimensat(dirfd: ::c_int, path: *const ::c_char, + times: *const ::timespec, flag: ::c_int) -> ::c_int; + pub fn duplocale(base: ::locale_t) -> ::locale_t; + pub fn freelocale(loc: ::locale_t); + pub fn newlocale(mask: ::c_int, + locale: *const ::c_char, + base: ::locale_t) -> ::locale_t; + pub fn uselocale(loc: ::locale_t) -> ::locale_t; + pub fn creat64(path: *const c_char, mode: mode_t) -> ::c_int; + pub fn fstat64(fildes: ::c_int, buf: *mut stat64) -> ::c_int; + pub fn ftruncate64(fd: ::c_int, length: off64_t) -> ::c_int; + pub fn getrlimit64(resource: ::c_int, rlim: *mut rlimit64) -> ::c_int; + pub fn lseek64(fd: ::c_int, offset: off64_t, whence: ::c_int) -> off64_t; + pub fn lstat64(path: *const c_char, buf: *mut stat64) -> ::c_int; + pub fn mmap64(addr: *mut ::c_void, + len: ::size_t, + prot: ::c_int, + flags: ::c_int, + fd: ::c_int, + offset: off64_t) + -> *mut ::c_void; + pub fn open64(path: *const c_char, oflag: ::c_int, ...) -> ::c_int; + pub fn openat64(fd: ::c_int, + path: *const c_char, + oflag: ::c_int, ...) -> ::c_int; + pub fn pread64(fd: ::c_int, buf: *mut ::c_void, count: ::size_t, + offset: off64_t) -> ::ssize_t; + pub fn pwrite64(fd: ::c_int, buf: *const ::c_void, count: ::size_t, + offset: off64_t) -> ::ssize_t; + pub fn readdir64(dirp: *mut ::DIR) -> *mut ::dirent64; + pub fn readdir64_r(dirp: *mut ::DIR, entry: *mut ::dirent64, + result: *mut *mut ::dirent64) -> ::c_int; + pub fn setrlimit64(resource: ::c_int, rlim: *const rlimit64) -> ::c_int; + pub fn stat64(path: *const c_char, buf: *mut stat64) -> ::c_int; + pub fn truncate64(path: *const c_char, length: off64_t) -> ::c_int; + pub fn eventfd(init: ::c_uint, flags: ::c_int) -> ::c_int; + + pub fn fdopendir(fd: ::c_int) -> *mut ::DIR; + + pub fn mknodat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t, dev: dev_t) -> ::c_int; + pub fn ppoll(fds: *mut ::pollfd, + nfds: nfds_t, + timeout: *const ::timespec, + sigmask: *const sigset_t) -> ::c_int; + pub fn pthread_condattr_getclock(attr: *const pthread_condattr_t, + clock_id: *mut clockid_t) -> ::c_int; + pub fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, + clock_id: ::clockid_t) -> ::c_int; + pub fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, + pshared: ::c_int) -> ::c_int; + pub fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, + pshared: *mut ::c_int) -> ::c_int; + pub fn sched_getaffinity(pid: ::pid_t, + cpusetsize: ::size_t, + cpuset: *mut cpu_set_t) -> ::c_int; + pub fn sched_setaffinity(pid: ::pid_t, + cpusetsize: ::size_t, + cpuset: *const cpu_set_t) -> ::c_int; + pub fn unshare(flags: ::c_int) -> ::c_int; + pub fn sem_timedwait(sem: *mut sem_t, + abstime: *const ::timespec) -> ::c_int; + pub fn accept4(fd: ::c_int, addr: *mut ::sockaddr, len: *mut ::socklen_t, + flg: ::c_int) -> ::c_int; + pub fn pthread_mutex_timedlock(lock: *mut pthread_mutex_t, + abstime: *const ::timespec) -> ::c_int; + pub fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, + pshared: ::c_int) -> ::c_int; + pub fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, + pshared: *mut ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_getkind_np(attr: *const pthread_rwlockattr_t, + val: *mut ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_setkind_np(attr: *mut pthread_rwlockattr_t, + val: ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, + val: *mut ::c_int) -> ::c_int; + pub fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, + val: ::c_int) -> ::c_int; + pub fn ptsname_r(fd: ::c_int, + buf: *mut ::c_char, + buflen: ::size_t) -> ::c_int; + pub fn clearenv() -> ::c_int; + pub fn waitid(idtype: idtype_t, id: id_t, infop: *mut ::siginfo_t, + options: ::c_int) -> ::c_int; + + pub fn lutimes(file: *const ::c_char, times: *const ::timeval) -> ::c_int; + + pub fn setpwent(); + pub fn endpwent(); + pub fn getpwent() -> *mut passwd; + pub fn setspent(); + pub fn endspent(); + pub fn getspent() -> *mut spwd; + pub fn getspnam(__name: *const ::c_char) -> *mut spwd; + + pub fn shm_open(name: *const c_char, oflag: ::c_int, + mode: mode_t) -> ::c_int; + + // System V IPC + pub fn shmget(key: ::key_t, size: ::size_t, shmflg: ::c_int) -> ::c_int; + pub fn shmat(shmid: ::c_int, + shmaddr: *const ::c_void, + shmflg: ::c_int) -> *mut ::c_void; + pub fn shmdt(shmaddr: *const ::c_void) -> ::c_int; + pub fn shmctl(shmid: ::c_int, + cmd: ::c_int, + buf: *mut ::shmid_ds) -> ::c_int; + pub fn ftok(pathname: *const ::c_char, proj_id: ::c_int) -> ::key_t; + pub fn msgctl(msqid: ::c_int, cmd: ::c_int, buf: *mut msqid_ds) -> ::c_int; + pub fn msgget(key: ::key_t, msgflg: ::c_int) -> ::c_int; + pub fn msgrcv(msqid: ::c_int, msgp: *mut ::c_void, msgsz: ::size_t, + msgtyp: ::c_long, msgflg: ::c_int) -> ::ssize_t; + pub fn msgsnd(msqid: ::c_int, msgp: *const ::c_void, msgsz: ::size_t, + msgflg: ::c_int) -> ::c_int; + + pub fn mprotect(addr: *mut ::c_void, len: ::size_t, prot: ::c_int) + -> ::c_int; + pub fn __errno_location() -> *mut ::c_int; + + pub fn fopen64(filename: *const c_char, + mode: *const c_char) -> *mut ::FILE; + pub fn freopen64(filename: *const c_char, mode: *const c_char, + file: *mut ::FILE) -> *mut ::FILE; + pub fn tmpfile64() -> *mut ::FILE; + pub fn fgetpos64(stream: *mut ::FILE, ptr: *mut fpos64_t) -> ::c_int; + pub fn fsetpos64(stream: *mut ::FILE, ptr: *const fpos64_t) -> ::c_int; + pub fn fseeko64(stream: *mut ::FILE, + offset: ::off64_t, + whence: ::c_int) -> ::c_int; + pub fn ftello64(stream: *mut ::FILE) -> ::off64_t; + pub fn readahead(fd: ::c_int, offset: ::off64_t, + count: ::size_t) -> ::ssize_t; + pub fn getxattr(path: *const c_char, name: *const c_char, + value: *mut ::c_void, size: ::size_t) -> ::ssize_t; + pub fn lgetxattr(path: *const c_char, name: *const c_char, + value: *mut ::c_void, size: ::size_t) -> ::ssize_t; + pub fn fgetxattr(filedes: ::c_int, name: *const c_char, + value: *mut ::c_void, size: ::size_t) -> ::ssize_t; + pub fn setxattr(path: *const c_char, name: *const c_char, + value: *const ::c_void, size: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn lsetxattr(path: *const c_char, name: *const c_char, + value: *const ::c_void, size: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn fsetxattr(filedes: ::c_int, name: *const c_char, + value: *const ::c_void, size: ::size_t, + flags: ::c_int) -> ::c_int; + pub fn listxattr(path: *const c_char, list: *mut c_char, + size: ::size_t) -> ::ssize_t; + pub fn llistxattr(path: *const c_char, list: *mut c_char, + size: ::size_t) -> ::ssize_t; + pub fn flistxattr(filedes: ::c_int, list: *mut c_char, + size: ::size_t) -> ::ssize_t; + pub fn removexattr(path: *const c_char, name: *const c_char) -> ::c_int; + pub fn lremovexattr(path: *const c_char, name: *const c_char) -> ::c_int; + pub fn fremovexattr(filedes: ::c_int, name: *const c_char) -> ::c_int; + pub fn signalfd(fd: ::c_int, + mask: *const ::sigset_t, + flags: ::c_int) -> ::c_int; + pub fn quotactl(cmd: ::c_int, + special: *const ::c_char, + id: ::c_int, + data: *mut ::c_char) -> ::c_int; + pub fn mq_open(name: *const ::c_char, oflag: ::c_int, ...) -> ::mqd_t; + pub fn mq_close(mqd: ::mqd_t) -> ::c_int; + pub fn mq_unlink(name: *const ::c_char) -> ::c_int; + pub fn mq_receive(mqd: ::mqd_t, + msg_ptr: *mut ::c_char, + msg_len: ::size_t, + msq_prio: *mut ::c_uint) -> ::ssize_t; + pub fn mq_send(mqd: ::mqd_t, + msg_ptr: *const ::c_char, + msg_len: ::size_t, + msq_prio: ::c_uint) -> ::c_int; + pub fn mq_getattr(mqd: ::mqd_t, attr: *mut ::mq_attr) -> ::c_int; + pub fn mq_setattr(mqd: ::mqd_t, + newattr: *const ::mq_attr, + oldattr: *mut ::mq_attr) -> ::c_int; + pub fn epoll_pwait(epfd: ::c_int, + events: *mut ::epoll_event, + maxevents: ::c_int, + timeout: ::c_int, + sigmask: *const ::sigset_t) -> ::c_int; + pub fn sethostname(name: *const ::c_char, len: ::size_t) -> ::c_int; + pub fn sigtimedwait(set: *const sigset_t, + info: *mut siginfo_t, + timeout: *const ::timespec) -> ::c_int; + pub fn sigwaitinfo(set: *const sigset_t, + info: *mut siginfo_t) -> ::c_int; + pub fn nl_langinfo_l(item: ::nl_item, locale: ::locale_t) -> *mut ::c_char; + pub fn prlimit(pid: ::pid_t, resource: ::c_int, new_limit: *const ::rlimit, + old_limit: *mut ::rlimit) -> ::c_int; + pub fn prlimit64(pid: ::pid_t, + resource: ::c_int, + new_limit: *const ::rlimit64, + old_limit: *mut ::rlimit64) -> ::c_int; + pub fn reboot(how_to: ::c_int) -> ::c_int; + pub fn setfsgid(gid: ::gid_t) -> ::c_int; + pub fn setfsuid(uid: ::uid_t) -> ::c_int; + pub fn setresgid(rgid: ::gid_t, egid: ::gid_t, sgid: ::gid_t) -> ::c_int; + pub fn setresuid(ruid: ::uid_t, euid: ::uid_t, suid: ::uid_t) -> ::c_int; + + // Not available now on Android + pub fn mkfifoat(dirfd: ::c_int, pathname: *const ::c_char, + mode: ::mode_t) -> ::c_int; + pub fn if_nameindex() -> *mut if_nameindex; + pub fn if_freenameindex(ptr: *mut if_nameindex); + pub fn sync_file_range(fd: ::c_int, offset: ::off64_t, + nbytes: ::off64_t, flags: ::c_uint) -> ::c_int; + pub fn getifaddrs(ifap: *mut *mut ::ifaddrs) -> ::c_int; + pub fn freeifaddrs(ifa: *mut ::ifaddrs); + + pub fn mremap(addr: *mut ::c_void, + len: ::size_t, + new_len: ::size_t, + flags: ::c_int, + ...) -> *mut ::c_void; + + pub fn glob(pattern: *const c_char, + flags: ::c_int, + errfunc: Option ::c_int>, + pglob: *mut ::glob_t) -> ::c_int; + pub fn globfree(pglob: *mut ::glob_t); + + pub fn shm_unlink(name: *const ::c_char) -> ::c_int; + + pub fn seekdir(dirp: *mut ::DIR, loc: ::c_long); + + pub fn telldir(dirp: *mut ::DIR) -> ::c_long; + pub fn madvise(addr: *mut ::c_void, len: ::size_t, advice: ::c_int) + -> ::c_int; + + pub fn msync(addr: *mut ::c_void, len: ::size_t, flags: ::c_int) -> ::c_int; + + pub fn recvfrom(socket: ::c_int, buf: *mut ::c_void, len: ::size_t, + flags: ::c_int, addr: *mut ::sockaddr, + addrlen: *mut ::socklen_t) -> ::ssize_t; + pub fn nl_langinfo(item: ::nl_item) -> *mut ::c_char; + + pub fn bind(socket: ::c_int, address: *const ::sockaddr, + address_len: ::socklen_t) -> ::c_int; + + pub fn writev(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + pub fn readv(fd: ::c_int, + iov: *const ::iovec, + iovcnt: ::c_int) -> ::ssize_t; + + pub fn sendmsg(fd: ::c_int, + msg: *const ::msghdr, + flags: ::c_int) -> ::ssize_t; + pub fn recvmsg(fd: ::c_int, msg: *mut ::msghdr, flags: ::c_int) + -> ::ssize_t; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrgid_r")] + pub fn getgrgid_r(uid: ::uid_t, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "sigaltstack$UNIX2003")] + #[cfg_attr(target_os = "netbsd", link_name = "__sigaltstack14")] + pub fn sigaltstack(ss: *const stack_t, + oss: *mut stack_t) -> ::c_int; + pub fn sem_close(sem: *mut sem_t) -> ::c_int; + pub fn getdtablesize() -> ::c_int; + #[cfg_attr(target_os = "solaris", link_name = "__posix_getgrnam_r")] + pub fn getgrnam_r(name: *const ::c_char, + grp: *mut ::group, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut ::group) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "pthread_sigmask$UNIX2003")] + pub fn pthread_sigmask(how: ::c_int, set: *const sigset_t, + oldset: *mut sigset_t) -> ::c_int; + pub fn sem_open(name: *const ::c_char, oflag: ::c_int, ...) -> *mut sem_t; + pub fn getgrnam(name: *const ::c_char) -> *mut ::group; + pub fn pthread_kill(thread: ::pthread_t, sig: ::c_int) -> ::c_int; + pub fn sem_unlink(name: *const ::c_char) -> ::c_int; + pub fn daemon(nochdir: ::c_int, noclose: ::c_int) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwnam_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwnam_r")] + pub fn getpwnam_r(name: *const ::c_char, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(target_os = "netbsd", link_name = "__getpwuid_r50")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_getpwuid_r")] + pub fn getpwuid_r(uid: ::uid_t, + pwd: *mut passwd, + buf: *mut ::c_char, + buflen: ::size_t, + result: *mut *mut passwd) -> ::c_int; + #[cfg_attr(all(target_os = "macos", target_arch ="x86"), + link_name = "sigwait$UNIX2003")] + #[cfg_attr(target_os = "solaris", link_name = "__posix_sigwait")] + pub fn sigwait(set: *const sigset_t, + sig: *mut ::c_int) -> ::c_int; + pub fn pthread_atfork(prepare: Option, + parent: Option, + child: Option) -> ::c_int; + pub fn pthread_create(native: *mut ::pthread_t, + attr: *const ::pthread_attr_t, + f: extern fn(*mut ::c_void) -> *mut ::c_void, + value: *mut ::c_void) -> ::c_int; + pub fn getgrgid(gid: ::gid_t) -> *mut ::group; + #[cfg_attr(all(target_os = "macos", target_arch = "x86"), + link_name = "popen$UNIX2003")] + pub fn popen(command: *const c_char, + mode: *const c_char) -> *mut ::FILE; +} + +cfg_if! { + if #[cfg(target_arch = "mips")] { + mod mips; + pub use self::mips::*; + } else if #[cfg(target_arch = "x86_64")] { + mod x86_64; + pub use self::x86_64::*; + } else { + pub use unsupported_target; + } +} + diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/x86_64/l4re.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/x86_64/l4re.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/x86_64/l4re.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/x86_64/l4re.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,47 @@ +/// L4Re specifics +/// This module contains definitions required by various L4Re libc backends. +/// Some of them are formally not part of the libc, but are a dependency of the +/// libc and hence we should provide them here. + +pub type l4_umword_t = ::c_ulong; // Unsigned machine word. +pub type pthread_t = *mut ::c_void; + +s! { + /// CPU sets. + pub struct l4_sched_cpu_set_t { + // from the L4Re docs + /// Combination of granularity and offset. + /// + /// The granularity defines how many CPUs each bit in map describes. + /// The offset is the numer of the first CPU described by the first + /// bit in the bitmap. + /// offset must be a multiple of 2^graularity. + /// + /// | MSB | LSB | + /// | ---------------- | ------------------- | + /// | 8bit granularity | 24bit offset .. | + gran_offset: l4_umword_t , + /// Bitmap of CPUs. + map: l4_umword_t , + } +} + +#[cfg(target_os = "l4re")] +pub struct pthread_attr_t { + pub __detachstate: ::c_int, + pub __schedpolicy: ::c_int, + pub __schedparam: super::__sched_param, + pub __inheritsched: ::c_int, + pub __scope: ::c_int, + pub __guardsize: ::size_t, + pub __stackaddr_set: ::c_int, + pub __stackaddr: *mut ::c_void, // better don't use it + pub __stacksize: ::size_t, + // L4Re specifics + pub affinity: l4_sched_cpu_set_t, + pub create_flags: ::c_uint, +} + +// L4Re requires a min stack size of 64k; that isn't defined in uClibc, but +// somewhere in the core libraries. uClibc wants 16k, but that's not enough. +pub const PTHREAD_STACK_MIN: usize = 65536; diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/x86_64/mod.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/x86_64/mod.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/x86_64/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/x86_64/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,360 @@ +//! Definitions for uclibc on 64bit systems +//! +pub type blkcnt_t = i64; +pub type blksize_t = i64; +pub type clock_t = i64; +pub type c_char = u8; +pub type c_long = i64; +pub type c_ulong = u64; +pub type fsblkcnt_t = ::c_ulong; +pub type fsfilcnt_t = ::c_ulong; +pub type fsword_t = ::c_long; +pub type ino_t = ::c_ulong; +pub type nlink_t = ::c_uint; +pub type off_t = ::c_long; +pub type rlim_t = c_ulong; +pub type rlim64_t = u64; +// [uClibc docs] Note stat64 has the same shape as stat for x86-64. +pub type stat64 = stat; +pub type suseconds_t = ::c_long; +pub type time_t = ::c_int; +pub type wchar_t = ::c_int; + +pub type nfds_t = ::c_ulong; + +s! { + pub struct dirent { + pub d_ino: ::ino64_t, + pub d_off: ::off64_t, + pub d_reclen: u16, + pub d_type: u8, + pub d_name: [::c_char; 256], + } + + pub struct dirent64 { + pub d_ino: ::ino64_t, + pub d_off: ::off64_t, + pub d_reclen: u16, + pub d_type: u8, + pub d_name: [::c_char; 256], + } + + pub struct ipc_perm { + pub __key: ::key_t, + pub uid: ::uid_t, + pub gid: ::gid_t, + pub cuid: ::uid_t, + pub cgid: ::gid_t, + pub mode: ::c_ushort, // read / write + __pad1: ::c_ushort, + pub __seq: ::c_ushort, + __pad2: ::c_ushort, + __unused1: ::c_ulong, + __unused2: ::c_ulong + } + + #[cfg(not(target_os = "l4re"))] + pub struct pthread_attr_t { + __detachstate: ::c_int, + __schedpolicy: ::c_int, + __schedparam: __sched_param, + __inheritsched: ::c_int, + __scope: ::c_int, + __guardsize: ::size_t, + __stackaddr_set: ::c_int, + __stackaddr: *mut ::c_void, // better don't use it + __stacksize: ::size_t, + } + + pub struct __sched_param { + __sched_priority: ::c_int, + } + + pub struct siginfo_t { + si_signo: ::c_int, // signal number + si_errno: ::c_int, // if not zero: error value of signal, see errno.h + si_code: ::c_int, // signal code + pub _pad: [::c_int; 28], // unported union + _align: [usize; 0], + } + + pub struct shmid_ds { + pub shm_perm: ::ipc_perm, + pub shm_segsz: ::size_t, // segment size in bytes + pub shm_atime: ::time_t, // time of last shmat() + pub shm_dtime: ::time_t, + pub shm_ctime: ::time_t, + pub shm_cpid: ::pid_t, + pub shm_lpid: ::pid_t, + pub shm_nattch: ::shmatt_t, + __unused1: ::c_ulong, + __unused2: ::c_ulong + } + + pub struct msqid_ds { + pub msg_perm: ::ipc_perm, + pub msg_stime: ::time_t, + pub msg_rtime: ::time_t, + pub msg_ctime: ::time_t, + __msg_cbytes: ::c_ulong, + pub msg_qnum: ::msgqnum_t, + pub msg_qbytes: ::msglen_t, + pub msg_lspid: ::pid_t, + pub msg_lrpid: ::pid_t, + __ignored1: ::c_ulong, + __ignored2: ::c_ulong, + } + + pub struct sockaddr { + pub sa_family: ::sa_family_t, + pub sa_data: [::c_char; 14], + } + + pub struct sockaddr_in { + pub sin_family: ::sa_family_t, + pub sin_port: ::in_port_t, + pub sin_addr: ::in_addr, + pub sin_zero: [u8; 8], + } + + pub struct sockaddr_in6 { + pub sin6_family: ::sa_family_t, + pub sin6_port: ::in_port_t, + pub sin6_flowinfo: u32, + pub sin6_addr: ::in6_addr, + pub sin6_scope_id: u32, + } + + // ------------------------------------------------------------ + // definitions below are *unverified* and might **break** the software +// pub struct in_addr { +// pub s_addr: in_addr_t, +// } +// +// pub struct in6_addr { +// pub s6_addr: [u8; 16], +// __align: [u32; 0], +// } + + pub struct stat { + pub st_dev: ::c_ulong, + pub st_ino: ::ino_t, + // According to uclibc/libc/sysdeps/linux/x86_64/bits/stat.h, order of + // nlink and mode are swapped on 64 bit systems. + pub st_nlink: ::nlink_t, + pub st_mode: ::mode_t, + pub st_uid: ::uid_t, + pub st_gid: ::gid_t, + pub st_rdev: ::c_ulong, // dev_t + pub st_size: off_t, // file size + pub st_blksize: ::blksize_t, + pub st_blocks: ::blkcnt_t, + pub st_atime: ::time_t, + pub st_atime_nsec: ::c_ulong, + pub st_mtime: ::time_t, + pub st_mtime_nsec: ::c_ulong, + pub st_ctime: ::time_t, + pub st_ctime_nsec: ::c_ulong, + st_pad4: [::c_long; 3] + } + + pub struct sigaction { + pub sa_handler: ::sighandler_t, + pub sa_flags: ::c_ulong, + pub sa_restorer: *mut ::c_void, + pub sa_mask: ::sigset_t, + } + + pub struct stack_t { // ToDo + pub ss_sp: *mut ::c_void, + pub ss_flags: ::c_int, + pub ss_size: ::size_t + } + + pub struct statfs { // ToDo + pub f_type: fsword_t, + pub f_bsize: fsword_t, + pub f_blocks: ::fsblkcnt_t, + pub f_bfree: ::fsblkcnt_t, + pub f_bavail: ::fsblkcnt_t, + pub f_files: ::fsfilcnt_t, + pub f_ffree: ::fsfilcnt_t, + pub f_fsid: ::fsid_t, + pub f_namelen: fsword_t, + pub f_frsize: fsword_t, + f_spare: [fsword_t; 5], + } + + pub struct msghdr { // ToDo + pub msg_name: *mut ::c_void, + pub msg_namelen: ::socklen_t, + pub msg_iov: *mut ::iovec, + pub msg_iovlen: ::size_t, + pub msg_control: *mut ::c_void, + pub msg_controllen: ::size_t, + pub msg_flags: ::c_int, + } + + pub struct termios { // ToDo + pub c_iflag: ::tcflag_t, + pub c_oflag: ::tcflag_t, + pub c_cflag: ::tcflag_t, + pub c_lflag: ::tcflag_t, + pub c_line: ::cc_t, + pub c_cc: [::cc_t; ::NCCS], + } + + pub struct sem_t { // ToDo + #[cfg(target_pointer_width = "32")] + __size: [::c_char; 16], + #[cfg(target_pointer_width = "64")] + __size: [::c_char; 32], + __align: [::c_long; 0], + } + + pub struct pthread_mutex_t { // ToDo + #[cfg(any(target_arch = "mips", target_arch = "arm", + target_arch = "powerpc"))] + __align: [::c_long; 0], + #[cfg(not(any(target_arch = "mips", target_arch = "arm", + target_arch = "powerpc")))] + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_MUTEX_T], + } + + pub struct pthread_mutexattr_t { // ToDo + #[cfg(any(target_arch = "x86_64", target_arch = "powerpc64", + target_arch = "mips64", target_arch = "s390x", + target_arch = "sparc64"))] + __align: [::c_int; 0], + #[cfg(not(any(target_arch = "x86_64", target_arch = "powerpc64", + target_arch = "mips64", target_arch = "s390x", + target_arch = "sparc64")))] + __align: [::c_long; 0], + size: [u8; __SIZEOF_PTHREAD_MUTEXATTR_T], + } + + pub struct pthread_cond_t { // ToDo + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_COND_T], + } + + pub struct pthread_condattr_t { // ToDo + __align: [::c_int; 0], + size: [u8; __SIZEOF_PTHREAD_CONDATTR_T], + } + + pub struct pthread_rwlock_t { // ToDo + #[cfg(any(target_arch = "mips", target_arch = "arm", + target_arch = "powerpc"))] + __align: [::c_long; 0], + #[cfg(not(any(target_arch = "mips", target_arch = "arm", + target_arch = "powerpc")))] + __align: [::c_longlong; 0], + size: [u8; __SIZEOF_PTHREAD_RWLOCK_T], + } + + pub struct sigset_t { // ToDo + __val: [::c_ulong; 16], + } + + pub struct sysinfo { // ToDo + pub uptime: ::c_long, + pub loads: [::c_ulong; 3], + pub totalram: ::c_ulong, + pub freeram: ::c_ulong, + pub sharedram: ::c_ulong, + pub bufferram: ::c_ulong, + pub totalswap: ::c_ulong, + pub freeswap: ::c_ulong, + pub procs: ::c_ushort, + pub pad: ::c_ushort, + pub totalhigh: ::c_ulong, + pub freehigh: ::c_ulong, + pub mem_unit: ::c_uint, + pub _f: [::c_char; 0], + } + + pub struct glob_t { // ToDo + pub gl_pathc: ::size_t, + pub gl_pathv: *mut *mut c_char, + pub gl_offs: ::size_t, + pub gl_flags: ::c_int, + __unused1: *mut ::c_void, + __unused2: *mut ::c_void, + __unused3: *mut ::c_void, + __unused4: *mut ::c_void, + __unused5: *mut ::c_void, + } + + pub struct rlimit64 { // ToDo + pub rlim_cur: rlim64_t, + pub rlim_max: rlim64_t, + } + + pub struct cpu_set_t { // ToDo + #[cfg(target_pointer_width = "32")] + bits: [u32; 32], + #[cfg(target_pointer_width = "64")] + bits: [u64; 16], + } + + pub struct fsid_t { // ToDo + __val: [::c_int; 2], + } +} + +// constants +pub const EADDRINUSE: ::c_int = 98; // Address already in use +pub const EADDRNOTAVAIL: ::c_int = 99; // Cannot assign requested address +pub const ECONNABORTED: ::c_int = 103; // Software caused connection abort +pub const ECONNREFUSED: ::c_int = 111; // Connection refused +pub const ECONNRESET: ::c_int = 104; // Connection reset by peer +pub const EDEADLK: ::c_int = 35; // Resource deadlock would occur +pub const ENOSYS: ::c_int = 38; // Function not implemented +pub const ENOTCONN: ::c_int = 107; // Transport endpoint is not connected +pub const ETIMEDOUT: ::c_int = 110; // connection timed out +pub const O_APPEND: ::c_int = 02000; +pub const O_ACCMODE: ::c_int = 0003; +pub const O_CLOEXEC: ::c_int = 0x80000; +pub const O_CREAT: ::c_int = 0100; +pub const O_DIRECTORY: ::c_int = 0200000; +pub const O_EXCL: ::c_int = 0200; +pub const O_NONBLOCK: ::c_int = 04000; +pub const O_TRUNC: ::c_int = 01000; +pub const NCCS: usize = 32; +pub const SIG_SETMASK: ::c_int = 2; // Set the set of blocked signals +pub const PTHREAD_STACK_MIN: usize = 16384; +pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; +pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; +pub const SO_BROADCAST: ::c_int = 6; +pub const SOCK_DGRAM: ::c_int = 2; // connectionless, unreliable datagrams +pub const SOCK_STREAM: ::c_int = 1; // …/common/bits/socket_type.h +pub const SO_ERROR: ::c_int = 4; +pub const SOL_SOCKET: ::c_int = 1; +pub const SO_RCVTIMEO: ::c_int = 20; +pub const SO_REUSEADDR: ::c_int = 2; +pub const SO_SNDTIMEO: ::c_int = 21; +pub const PTHREAD_MUTEX_NORMAL: ::c_int = 0; +pub const PTHREAD_MUTEX_RECURSIVE: ::c_int = 1; +pub const PTHREAD_MUTEX_ERRORCHECK: ::c_int = 2; +pub const PTHREAD_MUTEX_DEFAULT: ::c_int = PTHREAD_MUTEX_NORMAL; +pub const RLIM_INFINITY: u64 = 0xffffffffffffffff; +pub const __SIZEOF_PTHREAD_COND_T: usize = 48; +pub const __SIZEOF_PTHREAD_CONDATTR_T: usize = 4; +pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 56; + +extern { + pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void; +} + +cfg_if! { + if #[cfg(target_os = "l4re")] { + mod l4re; + pub use self::l4re::*; + } else { + mod other; + pub use other::*; + } +} + diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/x86_64/other.rs cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/x86_64/other.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/unix/uclibc/x86_64/other.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/unix/uclibc/x86_64/other.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,4 @@ +// Thestyle checker discourages the use of #[cfg], so this has to go into a +// separate module +pub type pthread_t = ::c_ulong; + diff -Nru cargo-0.25.0/vendor/libc-0.2.40/src/windows.rs cargo-0.26.0/vendor/libc-0.2.40/src/windows.rs --- cargo-0.25.0/vendor/libc-0.2.40/src/windows.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/src/windows.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,248 @@ +//! Windows CRT definitions + +pub type c_char = i8; +pub type c_long = i32; +pub type c_ulong = u32; +pub type wchar_t = u16; + +pub type clock_t = i32; + +cfg_if! { + if #[cfg(all(target_arch = "x86", target_env = "gnu"))] { + pub type time_t = i32; + } else { + pub type time_t = i64; + } +} + +pub type off_t = i32; +pub type dev_t = u32; +pub type ino_t = u16; +pub enum timezone {} +pub type time64_t = i64; + +s! { + // note this is the struct called stat64 in Windows. Not stat, nor stati64. + pub struct stat { + pub st_dev: dev_t, + pub st_ino: ino_t, + pub st_mode: u16, + pub st_nlink: ::c_short, + pub st_uid: ::c_short, + pub st_gid: ::c_short, + pub st_rdev: dev_t, + pub st_size: i64, + pub st_atime: time64_t, + pub st_mtime: time64_t, + pub st_ctime: time64_t, + } + + // note that this is called utimbuf64 in Windows + pub struct utimbuf { + pub actime: time64_t, + pub modtime: time64_t, + } + + pub struct tm { + tm_sec: ::c_int, + tm_min: ::c_int, + tm_hour: ::c_int, + tm_mday: ::c_int, + tm_mon: ::c_int, + tm_year: ::c_int, + tm_wday: ::c_int, + tm_yday: ::c_int, + tm_isdst: ::c_int, + } + + pub struct timeval { + pub tv_sec: c_long, + pub tv_usec: c_long, + } + + pub struct timespec { + pub tv_sec: time_t, + pub tv_nsec: c_long, + } +} + +pub const EXIT_FAILURE: ::c_int = 1; +pub const EXIT_SUCCESS: ::c_int = 0; +pub const RAND_MAX: ::c_int = 32767; +pub const EOF: ::c_int = -1; +pub const SEEK_SET: ::c_int = 0; +pub const SEEK_CUR: ::c_int = 1; +pub const SEEK_END: ::c_int = 2; +pub const _IOFBF: ::c_int = 0; +pub const _IONBF: ::c_int = 4; +pub const _IOLBF: ::c_int = 64; +pub const BUFSIZ: ::c_uint = 512; +pub const FOPEN_MAX: ::c_uint = 20; +pub const FILENAME_MAX: ::c_uint = 260; + +cfg_if! { + if #[cfg(all(target_env = "gnu"))] { + pub const L_tmpnam: ::c_uint = 14; + pub const TMP_MAX: ::c_uint = 0x7fff; + } else if #[cfg(all(target_env = "msvc"))] { + pub const L_tmpnam: ::c_uint = 260; + pub const TMP_MAX: ::c_uint = 0x7fff_ffff; + } else { + // Unknown target_env + } +} + +pub const O_RDONLY: ::c_int = 0; +pub const O_WRONLY: ::c_int = 1; +pub const O_RDWR: ::c_int = 2; +pub const O_APPEND: ::c_int = 8; +pub const O_CREAT: ::c_int = 256; +pub const O_EXCL: ::c_int = 1024; +pub const O_TEXT: ::c_int = 16384; +pub const O_BINARY: ::c_int = 32768; +pub const O_NOINHERIT: ::c_int = 128; +pub const O_TRUNC: ::c_int = 512; +pub const S_IFCHR: ::c_int = 8192; +pub const S_IFDIR: ::c_int = 16384; +pub const S_IFREG: ::c_int = 32768; +pub const S_IFMT: ::c_int = 61440; +pub const S_IEXEC: ::c_int = 64; +pub const S_IWRITE: ::c_int = 128; +pub const S_IREAD: ::c_int = 256; + +pub const LC_ALL: ::c_int = 0; +pub const LC_COLLATE: ::c_int = 1; +pub const LC_CTYPE: ::c_int = 2; +pub const LC_MONETARY: ::c_int = 3; +pub const LC_NUMERIC: ::c_int = 4; +pub const LC_TIME: ::c_int = 5; + +pub const EPERM: ::c_int = 1; +pub const ENOENT: ::c_int = 2; +pub const ESRCH: ::c_int = 3; +pub const EINTR: ::c_int = 4; +pub const EIO: ::c_int = 5; +pub const ENXIO: ::c_int = 6; +pub const E2BIG: ::c_int = 7; +pub const ENOEXEC: ::c_int = 8; +pub const EBADF: ::c_int = 9; +pub const ECHILD: ::c_int = 10; +pub const EAGAIN: ::c_int = 11; +pub const ENOMEM: ::c_int = 12; +pub const EACCES: ::c_int = 13; +pub const EFAULT: ::c_int = 14; +pub const EBUSY: ::c_int = 16; +pub const EEXIST: ::c_int = 17; +pub const EXDEV: ::c_int = 18; +pub const ENODEV: ::c_int = 19; +pub const ENOTDIR: ::c_int = 20; +pub const EISDIR: ::c_int = 21; +pub const EINVAL: ::c_int = 22; +pub const ENFILE: ::c_int = 23; +pub const EMFILE: ::c_int = 24; +pub const ENOTTY: ::c_int = 25; +pub const EFBIG: ::c_int = 27; +pub const ENOSPC: ::c_int = 28; +pub const ESPIPE: ::c_int = 29; +pub const EROFS: ::c_int = 30; +pub const EMLINK: ::c_int = 31; +pub const EPIPE: ::c_int = 32; +pub const EDOM: ::c_int = 33; +pub const ERANGE: ::c_int = 34; +pub const EDEADLK: ::c_int = 36; +pub const EDEADLOCK: ::c_int = 36; +pub const ENAMETOOLONG: ::c_int = 38; +pub const ENOLCK: ::c_int = 39; +pub const ENOSYS: ::c_int = 40; +pub const ENOTEMPTY: ::c_int = 41; +pub const EILSEQ: ::c_int = 42; +pub const STRUNCATE: ::c_int = 80; + +// inline comment below appeases style checker +#[cfg(all(target_env = "msvc", feature = "stdbuild"))] // " if " +#[link(name = "msvcrt", cfg(not(target_feature = "crt-static")))] +#[link(name = "libcmt", cfg(target_feature = "crt-static"))] +extern {} + +extern { + #[link_name = "_chmod"] + pub fn chmod(path: *const c_char, mode: ::c_int) -> ::c_int; + #[link_name = "_wchmod"] + pub fn wchmod(path: *const wchar_t, mode: ::c_int) -> ::c_int; + #[link_name = "_mkdir"] + pub fn mkdir(path: *const c_char) -> ::c_int; + #[link_name = "_wrmdir"] + pub fn wrmdir(path: *const wchar_t) -> ::c_int; + #[link_name = "_fstat64"] + pub fn fstat(fildes: ::c_int, buf: *mut stat) -> ::c_int; + #[link_name = "_stat64"] + pub fn stat(path: *const c_char, buf: *mut stat) -> ::c_int; + #[link_name = "_wstat64"] + pub fn wstat(path: *const wchar_t, buf: *mut stat) -> ::c_int; + #[link_name = "_wutime64"] + pub fn wutime(file: *const wchar_t, buf: *mut utimbuf) -> ::c_int; + #[link_name = "_popen"] + pub fn popen(command: *const c_char, mode: *const c_char) -> *mut ::FILE; + #[link_name = "_pclose"] + pub fn pclose(stream: *mut ::FILE) -> ::c_int; + #[link_name = "_fdopen"] + pub fn fdopen(fd: ::c_int, mode: *const c_char) -> *mut ::FILE; + #[link_name = "_fileno"] + pub fn fileno(stream: *mut ::FILE) -> ::c_int; + #[link_name = "_open"] + pub fn open(path: *const c_char, oflag: ::c_int, ...) -> ::c_int; + #[link_name = "_wopen"] + pub fn wopen(path: *const wchar_t, oflag: ::c_int, ...) -> ::c_int; + #[link_name = "_creat"] + pub fn creat(path: *const c_char, mode: ::c_int) -> ::c_int; + #[link_name = "_access"] + pub fn access(path: *const c_char, amode: ::c_int) -> ::c_int; + #[link_name = "_chdir"] + pub fn chdir(dir: *const c_char) -> ::c_int; + #[link_name = "_close"] + pub fn close(fd: ::c_int) -> ::c_int; + #[link_name = "_dup"] + pub fn dup(fd: ::c_int) -> ::c_int; + #[link_name = "_dup2"] + pub fn dup2(src: ::c_int, dst: ::c_int) -> ::c_int; + #[link_name = "_execv"] + pub fn execv(prog: *const c_char, argv: *const *const c_char) -> ::intptr_t; + #[link_name = "_execve"] + pub fn execve(prog: *const c_char, argv: *const *const c_char, + envp: *const *const c_char) -> ::c_int; + #[link_name = "_execvp"] + pub fn execvp(c: *const c_char, argv: *const *const c_char) -> ::c_int; + #[link_name = "_execvpe"] + pub fn execvpe(c: *const c_char, argv: *const *const c_char, + envp: *const *const c_char) -> ::c_int; + #[link_name = "_getcwd"] + pub fn getcwd(buf: *mut c_char, size: ::c_int) -> *mut c_char; + #[link_name = "_getpid"] + pub fn getpid() -> ::c_int; + #[link_name = "_isatty"] + pub fn isatty(fd: ::c_int) -> ::c_int; + #[link_name = "_lseek"] + pub fn lseek(fd: ::c_int, offset: c_long, origin: ::c_int) -> c_long; + #[link_name = "_pipe"] + pub fn pipe(fds: *mut ::c_int, + psize: ::c_uint, + textmode: ::c_int) -> ::c_int; + #[link_name = "_read"] + pub fn read(fd: ::c_int, buf: *mut ::c_void, count: ::c_uint) -> ::c_int; + #[link_name = "_rmdir"] + pub fn rmdir(path: *const c_char) -> ::c_int; + #[link_name = "_unlink"] + pub fn unlink(c: *const c_char) -> ::c_int; + #[link_name = "_write"] + pub fn write(fd: ::c_int, buf: *const ::c_void, count: ::c_uint) -> ::c_int; + #[link_name = "_commit"] + pub fn commit(fd: ::c_int) -> ::c_int; + #[link_name = "_get_osfhandle"] + pub fn get_osfhandle(fd: ::c_int) -> ::intptr_t; + #[link_name = "_open_osfhandle"] + pub fn open_osfhandle(osfhandle: ::intptr_t, flags: ::c_int) -> ::c_int; + pub fn setlocale(category: ::c_int, locale: *const c_char) -> *mut c_char; + #[link_name = "_wsetlocale"] + pub fn wsetlocale(category: ::c_int, + locale: *const wchar_t) -> *mut wchar_t; +} diff -Nru cargo-0.25.0/vendor/libc-0.2.40/.travis.yml cargo-0.26.0/vendor/libc-0.2.40/.travis.yml --- cargo-0.25.0/vendor/libc-0.2.40/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/libc-0.2.40/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,113 @@ +language: rust +rust: stable +sudo: required +dist: trusty +services: + - docker +install: + - if [ -z "$NO_ADD" ]; then rustup target add $TARGET; fi +script: + - cargo build $OPT + - cargo build $OPT --no-default-features + - cargo generate-lockfile --manifest-path libc-test/Cargo.toml + - if [[ $TRAVIS_OS_NAME = "linux" ]]; then + sh ci/run-docker.sh $TARGET; + else + export CARGO_TARGET_DIR=`pwd`/target; + sh ci/run.sh $TARGET; + fi + - rustc ci/style.rs && ./style src +env: + global: + secure: "e2/3QjgRN9atOuSHp22TrYG7QVKcYUWY48Hi9b60w+r1+BhPkTseIJLte7WefRhdXtqpjjUJTooKDhnurFOeHaCT+nmBgiv+FPU893sBl4bhesY4m0vgUJVbNZcs6lTImYekWVb+aqjGdgV/XAgCw7c3kPmrZV0MzGDWL64Xaps=" +matrix: + include: + # 1.0.0 compat + - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 + rust: 1.0.0 + script: rm -f Cargo.lock && cargo build + install: + + # build documentation + - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 + rust: nightly + script: sh ci/dox.sh + + # stable compat + - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 + - env: TARGET=i686-unknown-linux-gnu + - os: osx + env: TARGET=x86_64-apple-darwin NO_ADD=1 + osx_image: xcode8.3 + - os: osx + env: TARGET=i686-apple-darwin + osx_image: xcode8.3 + - env: TARGET=arm-linux-androideabi + - env: TARGET=aarch64-linux-android + # FIXME(#826) should reenable + #- env: TARGET=i686-linux-android + - env: TARGET=x86_64-linux-android + - env: TARGET=x86_64-unknown-linux-musl + - env: TARGET=i686-unknown-linux-musl + - env: TARGET=arm-unknown-linux-gnueabihf + - env: TARGET=arm-unknown-linux-musleabihf + - env: TARGET=aarch64-unknown-linux-gnu + - env: TARGET=aarch64-unknown-linux-musl + # FIXME(#856) + rust: 1.22.1 + - os: osx + osx_image: xcode8.2 + env: TARGET=i386-apple-ios + CARGO_TARGET_I386_APPLE_IOS_RUNNER=$HOME/runtest + RUSTFLAGS=-Clink-arg=-mios-simulator-version-min=7.0 + before_install: + rustc ./ci/ios/deploy_and_run_on_ios_simulator.rs -o $HOME/runtest + - os: osx + osx_image: xcode8.2 + env: TARGET=x86_64-apple-ios + CARGO_TARGET_X86_64_APPLE_IOS_RUNNER=$HOME/runtest + RUSTFLAGS=-Clink-arg=-mios-simulator-version-min=7.0 + before_install: + rustc ./ci/ios/deploy_and_run_on_ios_simulator.rs -o $HOME/runtest + - env: TARGET=x86_64-rumprun-netbsd + - env: TARGET=powerpc-unknown-linux-gnu + - env: TARGET=powerpc64-unknown-linux-gnu + - env: TARGET=powerpc64le-unknown-linux-gnu + - env: TARGET=mips-unknown-linux-musl + - env: TARGET=mipsel-unknown-linux-musl + - env: TARGET=mips64-unknown-linux-gnuabi64 + - env: TARGET=mips64el-unknown-linux-gnuabi64 + - env: TARGET=mips-unknown-linux-gnu + - env: TARGET=s390x-unknown-linux-gnu + - env: TARGET=sparc64-unknown-linux-gnu + - env: TARGET=asmjs-unknown-emscripten + - env: TARGET=wasm32-unknown-emscripten + + # beta + - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 + rust: beta + - os: osx + env: TARGET=x86_64-apple-darwin NO_ADD=1 + osx_image: xcode8.3 + rust: beta + + # nightly + - env: TARGET=x86_64-unknown-linux-gnu NO_ADD=1 + rust: nightly + - os: osx + env: TARGET=x86_64-apple-darwin NO_ADD=1 + osx_image: xcode8.3 + rust: nightly + # not available on stable + # without --release the build fails + # see https://github.com/rust-lang/rust/issues/45417 + - env: TARGET=x86_64-unknown-linux-gnux32 OPT="--release" + rust: nightly + + # QEMU based targets that compile in an emulator + - env: TARGET=x86_64-unknown-freebsd + +notifications: + email: + on_success: never + webhooks: https://buildbot.rust-lang.org/homu/travis diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/appveyor.yml cargo-0.26.0/vendor/memchr-1.0.2/appveyor.yml --- cargo-0.25.0/vendor/memchr-1.0.2/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -environment: - matrix: - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc - - TARGET: i686-pc-windows-gnu -install: - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" - - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - - SET PATH=%PATH%;C:\MinGW\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo build --verbose - - cargo test --verbose - - cargo bench --verbose diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/benches/bench.rs cargo-0.26.0/vendor/memchr-1.0.2/benches/bench.rs --- cargo-0.25.0/vendor/memchr-1.0.2/benches/bench.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/benches/bench.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,117 +0,0 @@ -#![feature(test)] - -extern crate memchr; -extern crate test; - -use std::iter; - -fn bench_data() -> Vec { iter::repeat(b'z').take(10000).collect() } - -#[bench] -fn iterator_memchr(b: &mut test::Bencher) { - let haystack = bench_data(); - let needle = b'a'; - b.iter(|| { - assert!(haystack.iter().position(|&b| b == needle).is_none()); - }); - b.bytes = haystack.len() as u64; -} - -#[bench] -fn optimized_memchr(b: &mut test::Bencher) { - let haystack = bench_data(); - let needle = b'a'; - b.iter(|| { - assert!(memchr::memchr(needle, &haystack).is_none()); - }); - b.bytes = haystack.len() as u64; -} - -#[bench] -fn iterator_memrchr(b: &mut test::Bencher) { - let haystack = bench_data(); - let needle = b'a'; - b.iter(|| { - assert!(haystack.iter().rposition(|&b| b == needle).is_none()); - }); - b.bytes = haystack.len() as u64; -} - -#[bench] -fn optimized_memrchr(b: &mut test::Bencher) { - let haystack = bench_data(); - let needle = b'a'; - b.iter(|| { - assert!(memchr::memrchr(needle, &haystack).is_none()); - }); - b.bytes = haystack.len() as u64; -} - -#[bench] -fn iterator_memchr2(b: &mut test::Bencher) { - let haystack = bench_data(); - let (needle1, needle2) = (b'a', b'b'); - b.iter(|| { - assert!(haystack.iter().position(|&b| { - b == needle1 || b == needle2 - }).is_none()); - }); - b.bytes = haystack.len() as u64; -} - -#[bench] -fn manual_memchr2(b: &mut test::Bencher) { - fn find_singles( - sparse: &[bool], - text: &[u8], - ) -> Option<(usize, usize)> { - for (hi, &b) in text.iter().enumerate() { - if sparse[b as usize] { - return Some((hi, hi+1)); - } - } - None - } - - let haystack = bench_data(); - let mut sparse = vec![false; 256]; - sparse[b'a' as usize] = true; - sparse[b'b' as usize] = true; - b.iter(|| { - assert!(find_singles(&sparse, &haystack).is_none()); - }); - b.bytes = haystack.len() as u64; -} - -#[bench] -fn optimized_memchr2(b: &mut test::Bencher) { - let haystack = bench_data(); - let (needle1, needle2) = (b'a', b'b'); - b.iter(|| { - assert!(memchr::memchr2(needle1, needle2, &haystack).is_none()); - }); - b.bytes = haystack.len() as u64; -} - -#[bench] -fn iterator_memchr3(b: &mut test::Bencher) { - let haystack = bench_data(); - let (needle1, needle2, needle3) = (b'a', b'b', b'c'); - b.iter(|| { - assert!(haystack.iter().position(|&b| { - b == needle1 || b == needle2 || b == needle3 - }).is_none()); - }); - b.bytes = haystack.len() as u64; -} - -#[bench] -fn optimized_memchr3(b: &mut test::Bencher) { - let haystack = bench_data(); - let (needle1, needle2, needle3) = (b'a', b'b', b'c'); - b.iter(|| { - assert!(memchr::memchr3( - needle1, needle2, needle3, &haystack).is_none()); - }); - b.bytes = haystack.len() as u64; -} diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/.cargo-checksum.json cargo-0.26.0/vendor/memchr-1.0.2/.cargo-checksum.json --- cargo-0.25.0/vendor/memchr-1.0.2/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"148fab2e51b4f1cfc66da2a7c32981d1d3c083a803978268bb11fe4b86925e7a"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/Cargo.toml cargo-0.26.0/vendor/memchr-1.0.2/Cargo.toml --- cargo-0.25.0/vendor/memchr-1.0.2/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "memchr" -version = "1.0.2" -authors = ["Andrew Gallant ", "bluss"] -description = "Safe interface to memchr." -homepage = "https://github.com/BurntSushi/rust-memchr" -documentation = "https://docs.rs/memchr/" -readme = "README.md" -keywords = ["memchr", "char", "scan", "strchr", "string"] -license = "Unlicense/MIT" -repository = "https://github.com/BurntSushi/rust-memchr" -[profile.test] -opt-level = 3 - -[lib] -name = "memchr" -bench = false -[dependencies.libc] -version = "0.2.18" -optional = true -default-features = false -[dev-dependencies.quickcheck] -version = "0.4.1" - -[features] -default = ["use_std", "libc"] -use_std = ["libc", "libc/use_std"] -[badges.appveyor] -repository = "BurntSushi/rust-memchr" - -[badges.travis-ci] -repository = "BurntSushi/rust-memchr" diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/COPYING cargo-0.26.0/vendor/memchr-1.0.2/COPYING --- cargo-0.25.0/vendor/memchr-1.0.2/COPYING 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/COPYING 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -This project is dual-licensed under the Unlicense and MIT licenses. - -You may use this code under the terms of either license. diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/ctags.rust cargo-0.26.0/vendor/memchr-1.0.2/ctags.rust --- cargo-0.25.0/vendor/memchr-1.0.2/ctags.rust 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/ctags.rust 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ ---langdef=Rust ---langmap=Rust:.rs ---regex-Rust=/^[ \t]*(#\[[^\]]\][ \t]*)*(pub[ \t]+)?(extern[ \t]+)?("[^"]+"[ \t]+)?(unsafe[ \t]+)?fn[ \t]+([a-zA-Z0-9_]+)/\6/f,functions,function definitions/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?type[ \t]+([a-zA-Z0-9_]+)/\2/T,types,type definitions/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?enum[ \t]+([a-zA-Z0-9_]+)/\2/g,enum,enumeration names/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?struct[ \t]+([a-zA-Z0-9_]+)/\2/s,structure names/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?mod[ \t]+([a-zA-Z0-9_]+)/\2/m,modules,module names/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?static[ \t]+([a-zA-Z0-9_]+)/\2/c,consts,static constants/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?trait[ \t]+([a-zA-Z0-9_]+)/\2/t,traits,traits/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?impl([ \t\n]+<.*>)?[ \t]+([a-zA-Z0-9_]+)/\3/i,impls,trait implementations/ ---regex-Rust=/^[ \t]*macro_rules![ \t]+([a-zA-Z0-9_]+)/\1/d,macros,macro definitions/ diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/LICENSE-MIT cargo-0.26.0/vendor/memchr-1.0.2/LICENSE-MIT --- cargo-0.25.0/vendor/memchr-1.0.2/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Andrew Gallant - -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. diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/Makefile cargo-0.26.0/vendor/memchr-1.0.2/Makefile --- cargo-0.25.0/vendor/memchr-1.0.2/Makefile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/Makefile 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -all: - echo Nothing to do... - -ctags: - ctags --recurse --options=ctags.rust --languages=Rust - -docs: - cargo doc - in-dir ./target/doc fix-perms - rscp ./target/doc/* gopher:~/www/burntsushi.net/rustdoc/ - -push: - git push origin master - git push github master diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/README.md cargo-0.26.0/vendor/memchr-1.0.2/README.md --- cargo-0.25.0/vendor/memchr-1.0.2/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,36 +0,0 @@ -This crate provides a safe interface `libc`'s `memchr` and `memrchr`. -This crate also provides fallback implementations when either function is -unavailable. - -[![Build status](https://api.travis-ci.org/BurntSushi/rust-memchr.png)](https://travis-ci.org/BurntSushi/rust-memchr) -[![Build status](https://ci.appveyor.com/api/projects/status/8i9484t8l4w7uql0/branch/master?svg=true)](https://ci.appveyor.com/project/BurntSushi/rust-memchr/branch/master) -[![](http://meritbadge.herokuapp.com/memchr)](https://crates.io/crates/memchr) - -Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). - - -### Documentation - -[https://docs.rs/memchr](https://docs.rs/memchr) - -### no_std - -memchr links to the standard library by default, but you can disable the -`use_std` feature if you want to use it in a `#![no_std]` crate: - -```toml -[dependencies] -memchr = { version = "1.0", default-features = false } -``` - -### Performance - -On my system (Linux/amd64), `memchr` is about an order of magnitude faster than -the more idiomatic `haystack.iter().position(|&b| b == needle)`: - -``` -test iterator ... bench: 5,280 ns/iter (+/- 13) = 1893 MB/s -test iterator_reversed ... bench: 5,271 ns/iter (+/- 7) = 1897 MB/s -test libc_memchr ... bench: 202 ns/iter (+/- 0) = 49504 MB/s -test libc_memrchr ... bench: 197 ns/iter (+/- 1) = 50761 MB/s -``` diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/session.vim cargo-0.26.0/vendor/memchr-1.0.2/session.vim --- cargo-0.25.0/vendor/memchr-1.0.2/session.vim 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/session.vim 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -au BufWritePost *.rs silent!make ctags > /dev/null 2>&1 diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/src/lib.rs cargo-0.26.0/vendor/memchr-1.0.2/src/lib.rs --- cargo-0.25.0/vendor/memchr-1.0.2/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,881 +0,0 @@ -/*! -This crate defines two functions, `memchr` and `memrchr`, which expose a safe interface -to the corresponding functions in `libc`. -*/ - -#![deny(missing_docs)] -#![allow(unused_imports)] - -#![cfg_attr(not(feature = "use_std"), no_std)] - -#[cfg(all(test, not(feature = "use_std")))] -#[macro_use] -extern crate std; - -#[cfg(feature = "libc")] -extern crate libc; - -#[cfg(feature = "libc")] -use libc::c_void; -#[cfg(feature = "libc")] -use libc::{c_int, size_t}; - -#[cfg(feature = "use_std")] -use std::cmp; -#[cfg(not(feature = "use_std"))] -use core::cmp; - -const LO_U64: u64 = 0x0101010101010101; -const HI_U64: u64 = 0x8080808080808080; - -// use truncation -const LO_USIZE: usize = LO_U64 as usize; -const HI_USIZE: usize = HI_U64 as usize; - -#[cfg(target_pointer_width = "32")] -const USIZE_BYTES: usize = 4; -#[cfg(target_pointer_width = "64")] -const USIZE_BYTES: usize = 8; - -/// Return `true` if `x` contains any zero byte. -/// -/// From *Matters Computational*, J. Arndt -/// -/// "The idea is to subtract one from each of the bytes and then look for -/// bytes where the borrow propagated all the way to the most significant -/// bit." -#[inline] -fn contains_zero_byte(x: usize) -> bool { - x.wrapping_sub(LO_USIZE) & !x & HI_USIZE != 0 -} - -#[cfg(target_pointer_width = "32")] -#[inline] -fn repeat_byte(b: u8) -> usize { - let mut rep = (b as usize) << 8 | b as usize; - rep = rep << 16 | rep; - rep -} - -#[cfg(target_pointer_width = "64")] -#[inline] -fn repeat_byte(b: u8) -> usize { - let mut rep = (b as usize) << 8 | b as usize; - rep = rep << 16 | rep; - rep = rep << 32 | rep; - rep -} - -/// An iterator for memchr -pub struct Memchr<'a> { - needle: u8, - // The haystack to iterate over - haystack: &'a [u8], - // The index - position: usize, -} - -impl<'a> Memchr<'a> { - /// Creates a new iterator that yields all positions of needle in haystack. - pub fn new(needle: u8, haystack: &[u8]) -> Memchr { - Memchr { - needle: needle, - haystack: haystack, - position: 0, - } - } -} - -impl<'a> Iterator for Memchr<'a> { - type Item = usize; - - fn next(&mut self) -> Option { - let search_result = memchr(self.needle, &self.haystack); - match search_result { - Some(index) => { - // Move our internal position - self.haystack = self.haystack.split_at(index + 1).1; - self.position = self.position + index + 1; - Some(self.position) - } - None => None, - } - } -} - -impl<'a> DoubleEndedIterator for Memchr<'a> { - fn next_back(&mut self) -> Option { - let search_result = memrchr(self.needle, &self.haystack); - match search_result { - Some(index) => { - // Move our internal position - self.haystack = self.haystack.split_at(index).0; - Some(self.position + index + 1) - } - None => None, - } - } -} - -/// A safe interface to `memchr`. -/// -/// Returns the index corresponding to the first occurrence of `needle` in -/// `haystack`, or `None` if one is not found. -/// -/// memchr reduces to super-optimized machine code at around an order of -/// magnitude faster than `haystack.iter().position(|&b| b == needle)`. -/// (See benchmarks.) -/// -/// # Example -/// -/// This shows how to find the first position of a byte in a byte string. -/// -/// ```rust -/// use memchr::memchr; -/// -/// let haystack = b"the quick brown fox"; -/// assert_eq!(memchr(b'k', haystack), Some(8)); -/// ``` -#[inline(always)] // reduces constant overhead -pub fn memchr(needle: u8, haystack: &[u8]) -> Option { - // libc memchr - #[cfg(all(feature = "libc", - any(not(target_os = "windows"), - not(any(target_pointer_width = "32", - target_pointer_width = "64")))))] - #[inline(always)] // reduces constant overhead - fn memchr_specific(needle: u8, haystack: &[u8]) -> Option { - use libc::memchr as libc_memchr; - - let p = unsafe { - libc_memchr(haystack.as_ptr() as *const c_void, - needle as c_int, - haystack.len() as size_t) - }; - if p.is_null() { - None - } else { - Some(p as usize - (haystack.as_ptr() as usize)) - } - } - - // use fallback on windows, since it's faster - #[cfg(all(any(not(feature = "libc"), target_os = "windows"), - any(target_pointer_width = "32", - target_pointer_width = "64")))] - fn memchr_specific(needle: u8, haystack: &[u8]) -> Option { - fallback::memchr(needle, haystack) - } - - // For the rare case of neither 32 bit nor 64-bit platform. - #[cfg(all(any(not(feature = "libc"), target_os = "windows"), - not(target_pointer_width = "32"), - not(target_pointer_width = "64")))] - fn memchr_specific(needle: u8, haystack: &[u8]) -> Option { - haystack.iter().position(|&b| b == needle) - } - - memchr_specific(needle, haystack) -} - -/// A safe interface to `memrchr`. -/// -/// Returns the index corresponding to the last occurrence of `needle` in -/// `haystack`, or `None` if one is not found. -/// -/// # Example -/// -/// This shows how to find the last position of a byte in a byte string. -/// -/// ```rust -/// use memchr::memrchr; -/// -/// let haystack = b"the quick brown fox"; -/// assert_eq!(memrchr(b'o', haystack), Some(17)); -/// ``` -#[inline(always)] // reduces constant overhead -pub fn memrchr(needle: u8, haystack: &[u8]) -> Option { - - #[cfg(all(feature = "libc", target_os = "linux"))] - #[inline(always)] // reduces constant overhead - fn memrchr_specific(needle: u8, haystack: &[u8]) -> Option { - // GNU's memrchr() will - unlike memchr() - error if haystack is empty. - if haystack.is_empty() { - return None; - } - let p = unsafe { - libc::memrchr(haystack.as_ptr() as *const c_void, - needle as c_int, - haystack.len() as size_t) - }; - if p.is_null() { - None - } else { - Some(p as usize - (haystack.as_ptr() as usize)) - } - } - - #[cfg(all(not(all(feature = "libc", target_os = "linux")), - any(target_pointer_width = "32", target_pointer_width = "64")))] - fn memrchr_specific(needle: u8, haystack: &[u8]) -> Option { - fallback::memrchr(needle, haystack) - } - - // For the rare case of neither 32 bit nor 64-bit platform. - #[cfg(all(not(all(feature = "libc", target_os = "linux")), - not(target_pointer_width = "32"), - not(target_pointer_width = "64")))] - fn memrchr_specific(needle: u8, haystack: &[u8]) -> Option { - haystack.iter().rposition(|&b| b == needle) - } - - memrchr_specific(needle, haystack) -} - -/// An iterator for Memchr2 -pub struct Memchr2<'a> { - needle1: u8, - needle2: u8, - // The haystack to iterate over - haystack: &'a [u8], - // The index - position: usize, -} - -impl<'a> Memchr2<'a> { - /// Creates a new iterator that yields all positions of needle in haystack. - pub fn new(needle1: u8, needle2: u8, haystack: &[u8]) -> Memchr2 { - Memchr2 { - needle1: needle1, - needle2: needle2, - haystack: haystack, - position: 0, - } - } -} - -impl<'a> Iterator for Memchr2<'a> { - type Item = usize; - - fn next(&mut self) -> Option { - let search_result = memchr2(self.needle1, self.needle2, &self.haystack); - match search_result { - Some(index) => { - // Move our internal position - self.haystack = self.haystack.split_at(index + 1).1; - self.position = self.position + index + 1; - Some(self.position) - } - None => None, - } - } -} - - -/// Like `memchr`, but searches for two bytes instead of one. -pub fn memchr2(needle1: u8, needle2: u8, haystack: &[u8]) -> Option { - fn slow(b1: u8, b2: u8, haystack: &[u8]) -> Option { - haystack.iter().position(|&b| b == b1 || b == b2) - } - - let len = haystack.len(); - let ptr = haystack.as_ptr(); - let align = (ptr as usize) & (USIZE_BYTES - 1); - let mut i = 0; - if align > 0 { - i = cmp::min(USIZE_BYTES - align, len); - if let Some(found) = slow(needle1, needle2, &haystack[..i]) { - return Some(found); - } - } - let repeated_b1 = repeat_byte(needle1); - let repeated_b2 = repeat_byte(needle2); - if len >= USIZE_BYTES { - while i <= len - USIZE_BYTES { - unsafe { - let u = *(ptr.offset(i as isize) as *const usize); - let found_ub1 = contains_zero_byte(u ^ repeated_b1); - let found_ub2 = contains_zero_byte(u ^ repeated_b2); - if found_ub1 || found_ub2 { - break; - } - } - i += USIZE_BYTES; - } - } - slow(needle1, needle2, &haystack[i..]).map(|pos| i + pos) -} - -/// An iterator for Memchr3 -pub struct Memchr3<'a> { - needle1: u8, - needle2: u8, - needle3: u8, - // The haystack to iterate over - haystack: &'a [u8], - // The index - position: usize, -} - -impl<'a> Memchr3<'a> { - /// Create a new Memchr2 that's initalized to zero with a haystack - pub fn new(needle1: u8, needle2: u8, needle3: u8, haystack: &[u8]) -> Memchr3 { - Memchr3 { - needle1: needle1, - needle2: needle2, - needle3: needle3, - haystack: haystack, - position: 0, - } - } -} - -impl<'a> Iterator for Memchr3<'a> { - type Item = usize; - - fn next(&mut self) -> Option { - let search_result = memchr3(self.needle1, self.needle2, self.needle3, &self.haystack); - match search_result { - Some(index) => { - // Move our internal position - self.haystack = self.haystack.split_at(index + 1).1; - self.position = self.position + index + 1; - Some(self.position) - } - None => None, - } - } -} - -/// Like `memchr`, but searches for three bytes instead of one. -pub fn memchr3(needle1: u8, needle2: u8, needle3: u8, haystack: &[u8]) -> Option { - fn slow(b1: u8, b2: u8, b3: u8, haystack: &[u8]) -> Option { - haystack.iter().position(|&b| b == b1 || b == b2 || b == b3) - } - - let len = haystack.len(); - let ptr = haystack.as_ptr(); - let align = (ptr as usize) & (USIZE_BYTES - 1); - let mut i = 0; - if align > 0 { - i = cmp::min(USIZE_BYTES - align, len); - if let Some(found) = slow(needle1, needle2, needle3, &haystack[..i]) { - return Some(found); - } - } - let repeated_b1 = repeat_byte(needle1); - let repeated_b2 = repeat_byte(needle2); - let repeated_b3 = repeat_byte(needle3); - if len >= USIZE_BYTES { - while i <= len - USIZE_BYTES { - unsafe { - let u = *(ptr.offset(i as isize) as *const usize); - let found_ub1 = contains_zero_byte(u ^ repeated_b1); - let found_ub2 = contains_zero_byte(u ^ repeated_b2); - let found_ub3 = contains_zero_byte(u ^ repeated_b3); - if found_ub1 || found_ub2 || found_ub3 { - break; - } - } - i += USIZE_BYTES; - } - } - slow(needle1, needle2, needle3, &haystack[i..]).map(|pos| i + pos) -} - -#[allow(dead_code)] -#[cfg(any(test, not(feature = "libc"), all(not(target_os = "linux"), - any(target_pointer_width = "32", target_pointer_width = "64"))))] -mod fallback { - #[cfg(feature = "use_std")] - use std::cmp; - #[cfg(not(feature = "use_std"))] - use core::cmp; - - use super::{LO_U64, HI_U64, LO_USIZE, HI_USIZE, USIZE_BYTES, contains_zero_byte, repeat_byte}; - - /// Return the first index matching the byte `a` in `text`. - pub fn memchr(x: u8, text: &[u8]) -> Option { - // Scan for a single byte value by reading two `usize` words at a time. - // - // Split `text` in three parts - // - unaligned inital part, before the first word aligned address in text - // - body, scan by 2 words at a time - // - the last remaining part, < 2 word size - let len = text.len(); - let ptr = text.as_ptr(); - - // search up to an aligned boundary - let align = (ptr as usize) & (USIZE_BYTES - 1); - let mut offset; - if align > 0 { - offset = cmp::min(USIZE_BYTES - align, len); - if let Some(index) = text[..offset].iter().position(|elt| *elt == x) { - return Some(index); - } - } else { - offset = 0; - } - - // search the body of the text - let repeated_x = repeat_byte(x); - - if len >= 2 * USIZE_BYTES { - while offset <= len - 2 * USIZE_BYTES { - debug_assert_eq!((ptr as usize + offset) % USIZE_BYTES, 0); - unsafe { - let u = *(ptr.offset(offset as isize) as *const usize); - let v = *(ptr.offset((offset + USIZE_BYTES) as isize) as *const usize); - - // break if there is a matching byte - let zu = contains_zero_byte(u ^ repeated_x); - let zv = contains_zero_byte(v ^ repeated_x); - if zu || zv { - break; - } - } - offset += USIZE_BYTES * 2; - } - } - - // find the byte after the point the body loop stopped - text[offset..].iter().position(|elt| *elt == x).map(|i| offset + i) - } - - /// Return the last index matching the byte `a` in `text`. - pub fn memrchr(x: u8, text: &[u8]) -> Option { - // Scan for a single byte value by reading two `usize` words at a time. - // - // Split `text` in three parts - // - unaligned tail, after the last word aligned address in text - // - body, scan by 2 words at a time - // - the first remaining bytes, < 2 word size - let len = text.len(); - let ptr = text.as_ptr(); - - // search to an aligned boundary - let end_align = (ptr as usize + len) & (USIZE_BYTES - 1); - let mut offset; - if end_align > 0 { - offset = if end_align >= len { 0 } else { len - end_align }; - if let Some(index) = text[offset..].iter().rposition(|elt| *elt == x) { - return Some(offset + index); - } - } else { - offset = len; - } - - // search the body of the text - let repeated_x = repeat_byte(x); - - while offset >= 2 * USIZE_BYTES { - debug_assert_eq!((ptr as usize + offset) % USIZE_BYTES, 0); - unsafe { - let u = *(ptr.offset(offset as isize - 2 * USIZE_BYTES as isize) as *const usize); - let v = *(ptr.offset(offset as isize - USIZE_BYTES as isize) as *const usize); - - // break if there is a matching byte - let zu = contains_zero_byte(u ^ repeated_x); - let zv = contains_zero_byte(v ^ repeated_x); - if zu || zv { - break; - } - } - offset -= 2 * USIZE_BYTES; - } - - // find the byte before the point the body loop stopped - text[..offset].iter().rposition(|elt| *elt == x) - } -} - -#[cfg(test)] -mod tests { - extern crate quickcheck; - use std::prelude::v1::*; - - use super::{memchr, memrchr, memchr2, memchr3, Memchr, Memchr2, Memchr3}; - // Use a macro to test both native and fallback impls on all configurations - macro_rules! memchr_tests { - ($mod_name:ident, $memchr:path, $memrchr:path) => { - mod $mod_name { - use std::prelude::v1::*; - use super::quickcheck; - #[test] - fn matches_one() { - assert_eq!(Some(0), $memchr(b'a', b"a")); - } - - #[test] - fn matches_begin() { - assert_eq!(Some(0), $memchr(b'a', b"aaaa")); - } - - #[test] - fn matches_end() { - assert_eq!(Some(4), $memchr(b'z', b"aaaaz")); - } - - #[test] - fn matches_nul() { - assert_eq!(Some(4), $memchr(b'\x00', b"aaaa\x00")); - } - - #[test] - fn matches_past_nul() { - assert_eq!(Some(5), $memchr(b'z', b"aaaa\x00z")); - } - - #[test] - fn no_match_empty() { - assert_eq!(None, $memchr(b'a', b"")); - } - - #[test] - fn no_match() { - assert_eq!(None, $memchr(b'a', b"xyz")); - } - - #[test] - fn qc_never_fail() { - fn prop(needle: u8, haystack: Vec) -> bool { - $memchr(needle, &haystack); true - } - quickcheck::quickcheck(prop as fn(u8, Vec) -> bool); - } - - #[test] - fn matches_one_reversed() { - assert_eq!(Some(0), $memrchr(b'a', b"a")); - } - - #[test] - fn matches_begin_reversed() { - assert_eq!(Some(3), $memrchr(b'a', b"aaaa")); - } - - #[test] - fn matches_end_reversed() { - assert_eq!(Some(0), $memrchr(b'z', b"zaaaa")); - } - - #[test] - fn matches_nul_reversed() { - assert_eq!(Some(4), $memrchr(b'\x00', b"aaaa\x00")); - } - - #[test] - fn matches_past_nul_reversed() { - assert_eq!(Some(0), $memrchr(b'z', b"z\x00aaaa")); - } - - #[test] - fn no_match_empty_reversed() { - assert_eq!(None, $memrchr(b'a', b"")); - } - - #[test] - fn no_match_reversed() { - assert_eq!(None, $memrchr(b'a', b"xyz")); - } - - #[test] - fn qc_never_fail_reversed() { - fn prop(needle: u8, haystack: Vec) -> bool { - $memrchr(needle, &haystack); true - } - quickcheck::quickcheck(prop as fn(u8, Vec) -> bool); - } - - #[test] - fn qc_correct_memchr() { - fn prop(v: Vec, offset: u8) -> bool { - // test all pointer alignments - let uoffset = (offset & 0xF) as usize; - let data = if uoffset <= v.len() { - &v[uoffset..] - } else { - &v[..] - }; - for byte in 0..256u32 { - let byte = byte as u8; - if $memchr(byte, &data) != data.iter().position(|elt| *elt == byte) { - return false; - } - } - true - } - quickcheck::quickcheck(prop as fn(Vec, u8) -> bool); - } - - #[test] - fn qc_correct_memrchr() { - fn prop(v: Vec, offset: u8) -> bool { - // test all pointer alignments - let uoffset = (offset & 0xF) as usize; - let data = if uoffset <= v.len() { - &v[uoffset..] - } else { - &v[..] - }; - for byte in 0..256u32 { - let byte = byte as u8; - if $memrchr(byte, &data) != data.iter().rposition(|elt| *elt == byte) { - return false; - } - } - true - } - quickcheck::quickcheck(prop as fn(Vec, u8) -> bool); - } - } - } - } - - memchr_tests! { native, ::memchr, ::memrchr } - memchr_tests! { fallback, ::fallback::memchr, ::fallback::memrchr } - - #[test] - fn memchr2_matches_one() { - assert_eq!(Some(0), memchr2(b'a', b'b', b"a")); - assert_eq!(Some(0), memchr2(b'a', b'b', b"b")); - assert_eq!(Some(0), memchr2(b'b', b'a', b"a")); - assert_eq!(Some(0), memchr2(b'b', b'a', b"b")); - } - - #[test] - fn memchr2_matches_begin() { - assert_eq!(Some(0), memchr2(b'a', b'b', b"aaaa")); - assert_eq!(Some(0), memchr2(b'a', b'b', b"bbbb")); - } - - #[test] - fn memchr2_matches_end() { - assert_eq!(Some(4), memchr2(b'z', b'y', b"aaaaz")); - assert_eq!(Some(4), memchr2(b'z', b'y', b"aaaay")); - } - - #[test] - fn memchr2_matches_nul() { - assert_eq!(Some(4), memchr2(b'\x00', b'z', b"aaaa\x00")); - assert_eq!(Some(4), memchr2(b'z', b'\x00', b"aaaa\x00")); - } - - #[test] - fn memchr2_matches_past_nul() { - assert_eq!(Some(5), memchr2(b'z', b'y', b"aaaa\x00z")); - assert_eq!(Some(5), memchr2(b'y', b'z', b"aaaa\x00z")); - } - - #[test] - fn memchr2_no_match_empty() { - assert_eq!(None, memchr2(b'a', b'b', b"")); - assert_eq!(None, memchr2(b'b', b'a', b"")); - } - - #[test] - fn memchr2_no_match() { - assert_eq!(None, memchr2(b'a', b'b', b"xyz")); - } - - #[test] - fn qc_never_fail_memchr2() { - fn prop(needle1: u8, needle2: u8, haystack: Vec) -> bool { - memchr2(needle1, needle2, &haystack); - true - } - quickcheck::quickcheck(prop as fn(u8, u8, Vec) -> bool); - } - - #[test] - fn memchr3_matches_one() { - assert_eq!(Some(0), memchr3(b'a', b'b', b'c', b"a")); - assert_eq!(Some(0), memchr3(b'a', b'b', b'c', b"b")); - assert_eq!(Some(0), memchr3(b'a', b'b', b'c', b"c")); - } - - #[test] - fn memchr3_matches_begin() { - assert_eq!(Some(0), memchr3(b'a', b'b', b'c', b"aaaa")); - assert_eq!(Some(0), memchr3(b'a', b'b', b'c', b"bbbb")); - assert_eq!(Some(0), memchr3(b'a', b'b', b'c', b"cccc")); - } - - #[test] - fn memchr3_matches_end() { - assert_eq!(Some(4), memchr3(b'z', b'y', b'x', b"aaaaz")); - assert_eq!(Some(4), memchr3(b'z', b'y', b'x', b"aaaay")); - assert_eq!(Some(4), memchr3(b'z', b'y', b'x', b"aaaax")); - } - - #[test] - fn memchr3_matches_nul() { - assert_eq!(Some(4), memchr3(b'\x00', b'z', b'y', b"aaaa\x00")); - assert_eq!(Some(4), memchr3(b'z', b'\x00', b'y', b"aaaa\x00")); - assert_eq!(Some(4), memchr3(b'z', b'y', b'\x00', b"aaaa\x00")); - } - - #[test] - fn memchr3_matches_past_nul() { - assert_eq!(Some(5), memchr3(b'z', b'y', b'x', b"aaaa\x00z")); - assert_eq!(Some(5), memchr3(b'y', b'z', b'x', b"aaaa\x00z")); - assert_eq!(Some(5), memchr3(b'y', b'x', b'z', b"aaaa\x00z")); - } - - #[test] - fn memchr3_no_match_empty() { - assert_eq!(None, memchr3(b'a', b'b', b'c', b"")); - assert_eq!(None, memchr3(b'b', b'a', b'c', b"")); - assert_eq!(None, memchr3(b'c', b'b', b'a', b"")); - } - - #[test] - fn memchr3_no_match() { - assert_eq!(None, memchr3(b'a', b'b', b'c', b"xyz")); - } - - #[test] - fn memchr_iter() { - let haystack = b"aaaabaaaab"; - let mut memchr_iter = Memchr::new(b'b', haystack); - let first = memchr_iter.next(); - let second = memchr_iter.next(); - let third = memchr_iter.next(); - assert_eq!(Some(5), first); - assert_eq!(Some(10), second); - assert_eq!(None, third); - } - - #[test] - fn memchr2_iter() { - let haystack = b"ab"; - let mut memchr_iter = Memchr2::new(b'a', b'b', haystack); - let first = memchr_iter.next(); - let second = memchr_iter.next(); - let third = memchr_iter.next(); - assert_eq!(Some(1), first); - assert_eq!(Some(2), second); - assert_eq!(None, third); - } - - #[test] - fn memchr3_iter() { - let haystack = b"abc"; - let mut memchr_iter = Memchr3::new(b'a', b'b', b'c', haystack); - let first = memchr_iter.next(); - let second = memchr_iter.next(); - let third = memchr_iter.next(); - let fourth = memchr_iter.next(); - assert_eq!(Some(1), first); - assert_eq!(Some(2), second); - assert_eq!(Some(3), third); - assert_eq!(None, fourth); - } - - #[test] - fn memchr_reverse_iter() { - let haystack = b"aaaabaaaabaaaab"; - let mut memchr_iter = Memchr::new(b'b', haystack); - let first = memchr_iter.next(); - let second = memchr_iter.next_back(); - let third = memchr_iter.next(); - let fourth = memchr_iter.next_back(); - - assert_eq!(Some(5), first); - assert_eq!(Some(15), second); - assert_eq!(Some(10), third); - assert_eq!(None, fourth); - } - - #[test] - fn memrchr_iter(){ - let haystack = b"aaaabaaaabaaaab"; - let mut memchr_iter = Memchr::new(b'b', haystack); - let first = memchr_iter.next_back(); - let second = memchr_iter.next_back(); - let third = memchr_iter.next_back(); - let fourth = memchr_iter.next_back(); - - assert_eq!(Some(15), first); - assert_eq!(Some(10), second); - assert_eq!(Some(5), third); - assert_eq!(None, fourth); - - } - - #[test] - fn qc_never_fail_memchr3() { - fn prop(needle1: u8, needle2: u8, needle3: u8, haystack: Vec) -> bool { - memchr3(needle1, needle2, needle3, &haystack); - true - } - quickcheck::quickcheck(prop as fn(u8, u8, u8, Vec) -> bool); - } - - #[test] - fn qc_correct_memchr() { - fn prop(v: Vec, offset: u8) -> bool { - // test all pointer alignments - let uoffset = (offset & 0xF) as usize; - let data = if uoffset <= v.len() { - &v[uoffset..] - } else { - &v[..] - }; - for byte in 0..256u32 { - let byte = byte as u8; - if memchr(byte, &data) != data.iter().position(|elt| *elt == byte) { - return false; - } - } - true - } - quickcheck::quickcheck(prop as fn(Vec, u8) -> bool); - } - - #[test] - fn qc_correct_memrchr() { - fn prop(v: Vec, offset: u8) -> bool { - // test all pointer alignments - let uoffset = (offset & 0xF) as usize; - let data = if uoffset <= v.len() { - &v[uoffset..] - } else { - &v[..] - }; - for byte in 0..256u32 { - let byte = byte as u8; - if memrchr(byte, &data) != data.iter().rposition(|elt| *elt == byte) { - return false; - } - } - true - } - quickcheck::quickcheck(prop as fn(Vec, u8) -> bool); - } - - #[test] - fn qc_correct_memchr2() { - fn prop(v: Vec, offset: u8) -> bool { - // test all pointer alignments - let uoffset = (offset & 0xF) as usize; - let data = if uoffset <= v.len() { - &v[uoffset..] - } else { - &v[..] - }; - for b1 in 0..256u32 { - for b2 in 0..256u32 { - let (b1, b2) = (b1 as u8, b2 as u8); - let expected = data.iter().position(|&b| b == b1 || b == b2); - let got = memchr2(b1, b2, &data); - if expected != got { - return false; - } - } - } - true - } - quickcheck::quickcheck(prop as fn(Vec, u8) -> bool); - } -} diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/.travis.yml cargo-0.26.0/vendor/memchr-1.0.2/.travis.yml --- cargo-0.25.0/vendor/memchr-1.0.2/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -language: rust -rust: - - 1.12.0 - - stable - - beta - - nightly -script: - - cargo build --verbose --no-default-features - - cargo build --verbose - - cargo test --verbose - - cargo doc - - if [ "$TRAVIS_RUST_VERSION" = "nightly" ]; then - cargo bench --verbose; - fi diff -Nru cargo-0.25.0/vendor/memchr-1.0.2/UNLICENSE cargo-0.26.0/vendor/memchr-1.0.2/UNLICENSE --- cargo-0.25.0/vendor/memchr-1.0.2/UNLICENSE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/memchr-1.0.2/UNLICENSE 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -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 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. - -For more information, please refer to diff -Nru cargo-0.25.0/vendor/num-complex-0.1.42/bors.toml cargo-0.26.0/vendor/num-complex-0.1.42/bors.toml --- cargo-0.25.0/vendor/num-complex-0.1.42/bors.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.42/bors.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -status = [ - "continuous-integration/travis-ci/push", -] diff -Nru cargo-0.25.0/vendor/num-complex-0.1.42/.cargo-checksum.json cargo-0.26.0/vendor/num-complex-0.1.42/.cargo-checksum.json --- cargo-0.25.0/vendor/num-complex-0.1.42/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.42/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"26ff8edeab9f1d8cf6b595e35138c2a389ea29f4f57a0e6bc44abf406e4b0077"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/num-complex-0.1.42/Cargo.toml cargo-0.26.0/vendor/num-complex-0.1.42/Cargo.toml --- cargo-0.25.0/vendor/num-complex-0.1.42/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.42/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "num-complex" -version = "0.1.42" -authors = ["The Rust Project Developers"] -description = "Complex numbers implementation for Rust" -homepage = "https://github.com/rust-num/num-complex" -documentation = "https://docs.rs/num-complex" -readme = "README.md" -keywords = ["mathematics", "numerics"] -categories = ["algorithms", "data-structures", "science"] -license = "MIT/Apache-2.0" -repository = "https://github.com/rust-num/num-complex" -[dependencies.num-traits] -version = "0.2.0" -features = ["std"] -default-features = false - -[dependencies.rustc-serialize] -version = "0.3.19" -optional = true - -[dependencies.serde] -version = ">= 0.7.0, < 0.9.0" -optional = true - -[features] -default = ["rustc-serialize"] -unstable = [] diff -Nru cargo-0.25.0/vendor/num-complex-0.1.42/ci/rustup.sh cargo-0.26.0/vendor/num-complex-0.1.42/ci/rustup.sh --- cargo-0.25.0/vendor/num-complex-0.1.42/ci/rustup.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.42/ci/rustup.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -#!/bin/sh -# Use rustup to locally run the same suite of tests as .travis.yml. -# (You should first install/update 1.8.0, stable, beta, and nightly.) - -set -ex - -export TRAVIS_RUST_VERSION -for TRAVIS_RUST_VERSION in 1.8.0 stable beta nightly; do - run="rustup run $TRAVIS_RUST_VERSION" - $run cargo build --verbose - $run $PWD/ci/test_full.sh -done diff -Nru cargo-0.25.0/vendor/num-complex-0.1.42/ci/test_full.sh cargo-0.26.0/vendor/num-complex-0.1.42/ci/test_full.sh --- cargo-0.25.0/vendor/num-complex-0.1.42/ci/test_full.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.42/ci/test_full.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -#!/bin/bash - -set -ex - -echo Testing num-complex on rustc ${TRAVIS_RUST_VERSION} - -# num-complex should build and test everywhere. -cargo build --verbose -cargo test --verbose - -# It should build with minimal features too. -cargo build --no-default-features -cargo test --no-default-features - -# Each isolated feature should also work everywhere. -for feature in rustc-serialize serde; do - cargo build --verbose --no-default-features --features="$feature" - cargo test --verbose --no-default-features --features="$feature" -done - -# Downgrade serde and build test the 0.7.0 channel as well -cargo update -p serde --precise 0.7.0 -cargo build --verbose --no-default-features --features "serde" diff -Nru cargo-0.25.0/vendor/num-complex-0.1.42/LICENSE-APACHE cargo-0.26.0/vendor/num-complex-0.1.42/LICENSE-APACHE --- cargo-0.25.0/vendor/num-complex-0.1.42/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.42/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/num-complex-0.1.42/LICENSE-MIT cargo-0.26.0/vendor/num-complex-0.1.42/LICENSE-MIT --- cargo-0.25.0/vendor/num-complex-0.1.42/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.42/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/num-complex-0.1.42/README.md cargo-0.26.0/vendor/num-complex-0.1.42/README.md --- cargo-0.25.0/vendor/num-complex-0.1.42/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.42/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -# num-complex - -[![crate](https://img.shields.io/crates/v/num-complex.svg)](https://crates.io/crates/num-complex) -[![documentation](https://docs.rs/num-complex/badge.svg)](https://docs.rs/num-complex) -![minimum rustc 1.8](https://img.shields.io/badge/rustc-1.8+-red.svg) -[![Travis status](https://travis-ci.org/rust-num/num-complex.svg?branch=master)](https://travis-ci.org/rust-num/num-complex) - -`Complex` numbers for Rust. - -## Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -num-complex = "0.1" -``` - -and this to your crate root: - -```rust -extern crate num_compex; -``` - -## Releases - -Release notes are available in [RELEASES.md](RELEASES.md). - -## Compatibility - -The `num-complex` crate is tested for rustc 1.8 and greater. diff -Nru cargo-0.25.0/vendor/num-complex-0.1.42/RELEASES.md cargo-0.26.0/vendor/num-complex-0.1.42/RELEASES.md --- cargo-0.25.0/vendor/num-complex-0.1.42/RELEASES.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.42/RELEASES.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -# Release 0.1.42 - -- [num-complex now has its own source repository][num-356] at [rust-num/num-complex][home]. - -**Contributors**: @cuviper - -[home]: https://github.com/rust-num/num-complex -[num-356]: https://github.com/rust-num/num/pull/356 - - -# Prior releases - -No prior release notes were kept. Thanks all the same to the many -contributors that have made this crate what it is! - diff -Nru cargo-0.25.0/vendor/num-complex-0.1.42/src/lib.rs cargo-0.26.0/vendor/num-complex-0.1.42/src/lib.rs --- cargo-0.25.0/vendor/num-complex-0.1.42/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.42/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1901 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Complex numbers. -//! -//! ## Compatibility -//! -//! The `num-complex` crate is tested for rustc 1.8 and greater. - -#![doc(html_root_url = "https://docs.rs/num-complex/0.1")] - -extern crate num_traits as traits; - -#[cfg(feature = "rustc-serialize")] -extern crate rustc_serialize; - -#[cfg(feature = "serde")] -extern crate serde; - -use std::error::Error; -use std::fmt; -#[cfg(test)] -use std::hash; -use std::ops::{Add, Div, Mul, Neg, Sub, Rem}; -use std::str::FromStr; - -use traits::{Zero, One, Num, Float}; - -// FIXME #1284: handle complex NaN & infinity etc. This -// probably doesn't map to C's _Complex correctly. - -/// A complex number in Cartesian form. -/// -/// ## Representation and Foreign Function Interface Compatibility -/// -/// `Complex` is memory layout compatible with an array `[T; 2]`. -/// -/// Note that `Complex` where F is a floating point type is **only** memory -/// layout compatible with C's complex types, **not** necessarily calling -/// convention compatible. This means that for FFI you can only pass -/// `Complex` behind a pointer, not as a value. -/// -/// ## Examples -/// -/// Example of extern function declaration. -/// -/// ``` -/// use num_complex::Complex; -/// use std::os::raw::c_int; -/// -/// extern "C" { -/// fn zaxpy_(n: *const c_int, alpha: *const Complex, -/// x: *const Complex, incx: *const c_int, -/// y: *mut Complex, incy: *const c_int); -/// } -/// ``` -#[derive(PartialEq, Eq, Copy, Clone, Hash, Debug, Default)] -#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))] -#[repr(C)] -pub struct Complex { - /// Real portion of the complex number - pub re: T, - /// Imaginary portion of the complex number - pub im: T -} - -pub type Complex32 = Complex; -pub type Complex64 = Complex; - -impl Complex { - /// Create a new Complex - #[inline] - pub fn new(re: T, im: T) -> Complex { - Complex { re: re, im: im } - } - - /// Returns imaginary unit - #[inline] - pub fn i() -> Complex { - Self::new(T::zero(), T::one()) - } - - /// Returns the square of the norm (since `T` doesn't necessarily - /// have a sqrt function), i.e. `re^2 + im^2`. - #[inline] - pub fn norm_sqr(&self) -> T { - self.re.clone() * self.re.clone() + self.im.clone() * self.im.clone() - } - - /// Multiplies `self` by the scalar `t`. - #[inline] - pub fn scale(&self, t: T) -> Complex { - Complex::new(self.re.clone() * t.clone(), self.im.clone() * t) - } - - /// Divides `self` by the scalar `t`. - #[inline] - pub fn unscale(&self, t: T) -> Complex { - Complex::new(self.re.clone() / t.clone(), self.im.clone() / t) - } -} - -impl> Complex { - /// Returns the complex conjugate. i.e. `re - i im` - #[inline] - pub fn conj(&self) -> Complex { - Complex::new(self.re.clone(), -self.im.clone()) - } - - /// Returns `1/self` - #[inline] - pub fn inv(&self) -> Complex { - let norm_sqr = self.norm_sqr(); - Complex::new(self.re.clone() / norm_sqr.clone(), - -self.im.clone() / norm_sqr) - } -} - -impl Complex { - /// Calculate |self| - #[inline] - pub fn norm(&self) -> T { - self.re.hypot(self.im) - } - /// Calculate the principal Arg of self. - #[inline] - pub fn arg(&self) -> T { - self.im.atan2(self.re) - } - /// Convert to polar form (r, theta), such that - /// `self = r * exp(i * theta)` - #[inline] - pub fn to_polar(&self) -> (T, T) { - (self.norm(), self.arg()) - } - /// Convert a polar representation into a complex number. - #[inline] - pub fn from_polar(r: &T, theta: &T) -> Complex { - Complex::new(*r * theta.cos(), *r * theta.sin()) - } - - /// Computes `e^(self)`, where `e` is the base of the natural logarithm. - #[inline] - pub fn exp(&self) -> Complex { - // formula: e^(a + bi) = e^a (cos(b) + i*sin(b)) - // = from_polar(e^a, b) - Complex::from_polar(&self.re.exp(), &self.im) - } - - /// Computes the principal value of natural logarithm of `self`. - /// - /// This function has one branch cut: - /// - /// * `(-∞, 0]`, continuous from above. - /// - /// The branch satisfies `-π ≤ arg(ln(z)) ≤ π`. - #[inline] - pub fn ln(&self) -> Complex { - // formula: ln(z) = ln|z| + i*arg(z) - let (r, theta) = self.to_polar(); - Complex::new(r.ln(), theta) - } - - /// Computes the principal value of the square root of `self`. - /// - /// This function has one branch cut: - /// - /// * `(-∞, 0)`, continuous from above. - /// - /// The branch satisfies `-π/2 ≤ arg(sqrt(z)) ≤ π/2`. - #[inline] - pub fn sqrt(&self) -> Complex { - // formula: sqrt(r e^(it)) = sqrt(r) e^(it/2) - let two = T::one() + T::one(); - let (r, theta) = self.to_polar(); - Complex::from_polar(&(r.sqrt()), &(theta/two)) - } - - /// Raises `self` to a floating point power. - #[inline] - pub fn powf(&self, exp: T) -> Complex { - // formula: x^y = (ρ e^(i θ))^y = ρ^y e^(i θ y) - // = from_polar(ρ^y, θ y) - let (r, theta) = self.to_polar(); - Complex::from_polar(&r.powf(exp), &(theta*exp)) - } - - /// Returns the logarithm of `self` with respect to an arbitrary base. - #[inline] - pub fn log(&self, base: T) -> Complex { - // formula: log_y(x) = log_y(ρ e^(i θ)) - // = log_y(ρ) + log_y(e^(i θ)) = log_y(ρ) + ln(e^(i θ)) / ln(y) - // = log_y(ρ) + i θ / ln(y) - let (r, theta) = self.to_polar(); - Complex::new(r.log(base), theta / base.ln()) - } - - /// Raises `self` to a complex power. - #[inline] - pub fn powc(&self, exp: Complex) -> Complex { - // formula: x^y = (a + i b)^(c + i d) - // = (ρ e^(i θ))^c (ρ e^(i θ))^(i d) - // where ρ=|x| and θ=arg(x) - // = ρ^c e^(−d θ) e^(i c θ) ρ^(i d) - // = p^c e^(−d θ) (cos(c θ) - // + i sin(c θ)) (cos(d ln(ρ)) + i sin(d ln(ρ))) - // = p^c e^(−d θ) ( - // cos(c θ) cos(d ln(ρ)) − sin(c θ) sin(d ln(ρ)) - // + i(cos(c θ) sin(d ln(ρ)) + sin(c θ) cos(d ln(ρ)))) - // = p^c e^(−d θ) (cos(c θ + d ln(ρ)) + i sin(c θ + d ln(ρ))) - // = from_polar(p^c e^(−d θ), c θ + d ln(ρ)) - let (r, theta) = self.to_polar(); - Complex::from_polar( - &(r.powf(exp.re) * (-exp.im * theta).exp()), - &(exp.re * theta + exp.im * r.ln())) - } - - /// Raises a floating point number to the complex power `self`. - #[inline] - pub fn expf(&self, base: T) -> Complex { - // formula: x^(a+bi) = x^a x^bi = x^a e^(b ln(x) i) - // = from_polar(x^a, b ln(x)) - Complex::from_polar(&base.powf(self.re), &(self.im * base.ln())) - } - - /// Computes the sine of `self`. - #[inline] - pub fn sin(&self) -> Complex { - // formula: sin(a + bi) = sin(a)cosh(b) + i*cos(a)sinh(b) - Complex::new(self.re.sin() * self.im.cosh(), self.re.cos() * self.im.sinh()) - } - - /// Computes the cosine of `self`. - #[inline] - pub fn cos(&self) -> Complex { - // formula: cos(a + bi) = cos(a)cosh(b) - i*sin(a)sinh(b) - Complex::new(self.re.cos() * self.im.cosh(), -self.re.sin() * self.im.sinh()) - } - - /// Computes the tangent of `self`. - #[inline] - pub fn tan(&self) -> Complex { - // formula: tan(a + bi) = (sin(2a) + i*sinh(2b))/(cos(2a) + cosh(2b)) - let (two_re, two_im) = (self.re + self.re, self.im + self.im); - Complex::new(two_re.sin(), two_im.sinh()).unscale(two_re.cos() + two_im.cosh()) - } - - /// Computes the principal value of the inverse sine of `self`. - /// - /// This function has two branch cuts: - /// - /// * `(-∞, -1)`, continuous from above. - /// * `(1, ∞)`, continuous from below. - /// - /// The branch satisfies `-π/2 ≤ Re(asin(z)) ≤ π/2`. - #[inline] - pub fn asin(&self) -> Complex { - // formula: arcsin(z) = -i ln(sqrt(1-z^2) + iz) - let i = Complex::::i(); - -i*((Complex::::one() - self*self).sqrt() + i*self).ln() - } - - /// Computes the principal value of the inverse cosine of `self`. - /// - /// This function has two branch cuts: - /// - /// * `(-∞, -1)`, continuous from above. - /// * `(1, ∞)`, continuous from below. - /// - /// The branch satisfies `0 ≤ Re(acos(z)) ≤ π`. - #[inline] - pub fn acos(&self) -> Complex { - // formula: arccos(z) = -i ln(i sqrt(1-z^2) + z) - let i = Complex::::i(); - -i*(i*(Complex::::one() - self*self).sqrt() + self).ln() - } - - /// Computes the principal value of the inverse tangent of `self`. - /// - /// This function has two branch cuts: - /// - /// * `(-∞i, -i]`, continuous from the left. - /// * `[i, ∞i)`, continuous from the right. - /// - /// The branch satisfies `-π/2 ≤ Re(atan(z)) ≤ π/2`. - #[inline] - pub fn atan(&self) -> Complex { - // formula: arctan(z) = (ln(1+iz) - ln(1-iz))/(2i) - let i = Complex::::i(); - let one = Complex::::one(); - let two = one + one; - if *self == i { - return Complex::new(T::zero(), T::infinity()); - } - else if *self == -i { - return Complex::new(T::zero(), -T::infinity()); - } - ((one + i * self).ln() - (one - i * self).ln()) / (two * i) - } - - /// Computes the hyperbolic sine of `self`. - #[inline] - pub fn sinh(&self) -> Complex { - // formula: sinh(a + bi) = sinh(a)cos(b) + i*cosh(a)sin(b) - Complex::new(self.re.sinh() * self.im.cos(), self.re.cosh() * self.im.sin()) - } - - /// Computes the hyperbolic cosine of `self`. - #[inline] - pub fn cosh(&self) -> Complex { - // formula: cosh(a + bi) = cosh(a)cos(b) + i*sinh(a)sin(b) - Complex::new(self.re.cosh() * self.im.cos(), self.re.sinh() * self.im.sin()) - } - - /// Computes the hyperbolic tangent of `self`. - #[inline] - pub fn tanh(&self) -> Complex { - // formula: tanh(a + bi) = (sinh(2a) + i*sin(2b))/(cosh(2a) + cos(2b)) - let (two_re, two_im) = (self.re + self.re, self.im + self.im); - Complex::new(two_re.sinh(), two_im.sin()).unscale(two_re.cosh() + two_im.cos()) - } - - /// Computes the principal value of inverse hyperbolic sine of `self`. - /// - /// This function has two branch cuts: - /// - /// * `(-∞i, -i)`, continuous from the left. - /// * `(i, ∞i)`, continuous from the right. - /// - /// The branch satisfies `-π/2 ≤ Im(asinh(z)) ≤ π/2`. - #[inline] - pub fn asinh(&self) -> Complex { - // formula: arcsinh(z) = ln(z + sqrt(1+z^2)) - let one = Complex::::one(); - (self + (one + self * self).sqrt()).ln() - } - - /// Computes the principal value of inverse hyperbolic cosine of `self`. - /// - /// This function has one branch cut: - /// - /// * `(-∞, 1)`, continuous from above. - /// - /// The branch satisfies `-π ≤ Im(acosh(z)) ≤ π` and `0 ≤ Re(acosh(z)) < ∞`. - #[inline] - pub fn acosh(&self) -> Complex { - // formula: arccosh(z) = 2 ln(sqrt((z+1)/2) + sqrt((z-1)/2)) - let one = Complex::one(); - let two = one + one; - two * (((self + one)/two).sqrt() + ((self - one)/two).sqrt()).ln() - } - - /// Computes the principal value of inverse hyperbolic tangent of `self`. - /// - /// This function has two branch cuts: - /// - /// * `(-∞, -1]`, continuous from above. - /// * `[1, ∞)`, continuous from below. - /// - /// The branch satisfies `-π/2 ≤ Im(atanh(z)) ≤ π/2`. - #[inline] - pub fn atanh(&self) -> Complex { - // formula: arctanh(z) = (ln(1+z) - ln(1-z))/2 - let one = Complex::one(); - let two = one + one; - if *self == one { - return Complex::new(T::infinity(), T::zero()); - } - else if *self == -one { - return Complex::new(-T::infinity(), T::zero()); - } - ((one + self).ln() - (one - self).ln()) / two - } - - /// Checks if the given complex number is NaN - #[inline] - pub fn is_nan(self) -> bool { - self.re.is_nan() || self.im.is_nan() - } - - /// Checks if the given complex number is infinite - #[inline] - pub fn is_infinite(self) -> bool { - !self.is_nan() && (self.re.is_infinite() || self.im.is_infinite()) - } - - /// Checks if the given complex number is finite - #[inline] - pub fn is_finite(self) -> bool { - self.re.is_finite() && self.im.is_finite() - } - - /// Checks if the given complex number is normal - #[inline] - pub fn is_normal(self) -> bool { - self.re.is_normal() && self.im.is_normal() - } -} - -impl From for Complex { - #[inline] - fn from(re: T) -> Complex { - Complex { re: re, im: T::zero() } - } -} - -impl<'a, T: Clone + Num> From<&'a T> for Complex { - #[inline] - fn from(re: &T) -> Complex { - From::from(re.clone()) - } -} - -macro_rules! forward_ref_ref_binop { - (impl $imp:ident, $method:ident) => { - impl<'a, 'b, T: Clone + Num> $imp<&'b Complex> for &'a Complex { - type Output = Complex; - - #[inline] - fn $method(self, other: &Complex) -> Complex { - self.clone().$method(other.clone()) - } - } - } -} - -macro_rules! forward_ref_val_binop { - (impl $imp:ident, $method:ident) => { - impl<'a, T: Clone + Num> $imp> for &'a Complex { - type Output = Complex; - - #[inline] - fn $method(self, other: Complex) -> Complex { - self.clone().$method(other) - } - } - } -} - -macro_rules! forward_val_ref_binop { - (impl $imp:ident, $method:ident) => { - impl<'a, T: Clone + Num> $imp<&'a Complex> for Complex { - type Output = Complex; - - #[inline] - fn $method(self, other: &Complex) -> Complex { - self.$method(other.clone()) - } - } - } -} - -macro_rules! forward_all_binop { - (impl $imp:ident, $method:ident) => { - forward_ref_ref_binop!(impl $imp, $method); - forward_ref_val_binop!(impl $imp, $method); - forward_val_ref_binop!(impl $imp, $method); - }; -} - -/* arithmetic */ -forward_all_binop!(impl Add, add); - -// (a + i b) + (c + i d) == (a + c) + i (b + d) -impl Add> for Complex { - type Output = Complex; - - #[inline] - fn add(self, other: Complex) -> Complex { - Complex::new(self.re + other.re, self.im + other.im) - } -} - -forward_all_binop!(impl Sub, sub); - -// (a + i b) - (c + i d) == (a - c) + i (b - d) -impl Sub> for Complex { - type Output = Complex; - - #[inline] - fn sub(self, other: Complex) -> Complex { - Complex::new(self.re - other.re, self.im - other.im) - } -} - -forward_all_binop!(impl Mul, mul); - -// (a + i b) * (c + i d) == (a*c - b*d) + i (a*d + b*c) -impl Mul> for Complex { - type Output = Complex; - - #[inline] - fn mul(self, other: Complex) -> Complex { - let re = self.re.clone() * other.re.clone() - self.im.clone() * other.im.clone(); - let im = self.re * other.im + self.im * other.re; - Complex::new(re, im) - } -} - -forward_all_binop!(impl Div, div); - -// (a + i b) / (c + i d) == [(a + i b) * (c - i d)] / (c*c + d*d) -// == [(a*c + b*d) / (c*c + d*d)] + i [(b*c - a*d) / (c*c + d*d)] -impl Div> for Complex { - type Output = Complex; - - #[inline] - fn div(self, other: Complex) -> Complex { - let norm_sqr = other.norm_sqr(); - let re = self.re.clone() * other.re.clone() + self.im.clone() * other.im.clone(); - let im = self.im * other.re - self.re * other.im; - Complex::new(re / norm_sqr.clone(), im / norm_sqr) - } -} - -forward_all_binop!(impl Rem, rem); - -// Attempts to identify the gaussian integer whose product with `modulus` -// is closest to `self`. -impl Rem> for Complex { - type Output = Complex; - - #[inline] - fn rem(self, modulus: Complex) -> Self { - let Complex { re, im } = self.clone() / modulus.clone(); - // This is the gaussian integer corresponding to the true ratio - // rounded towards zero. - let (re0, im0) = (re.clone() - re % T::one(), im.clone() - im % T::one()); - self - modulus * Complex::new(re0, im0) - } -} - -// Op Assign - -mod opassign { - use std::ops::{AddAssign, SubAssign, MulAssign, DivAssign, RemAssign}; - - use traits::NumAssign; - - use Complex; - - impl AddAssign for Complex { - fn add_assign(&mut self, other: Complex) { - self.re += other.re; - self.im += other.im; - } - } - - impl SubAssign for Complex { - fn sub_assign(&mut self, other: Complex) { - self.re -= other.re; - self.im -= other.im; - } - } - - impl MulAssign for Complex { - fn mul_assign(&mut self, other: Complex) { - *self = self.clone() * other; - } - } - - impl DivAssign for Complex { - fn div_assign(&mut self, other: Complex) { - *self = self.clone() / other; - } - } - - impl RemAssign for Complex { - fn rem_assign(&mut self, other: Complex) { - *self = self.clone() % other; - } - } - - impl AddAssign for Complex { - fn add_assign(&mut self, other: T) { - self.re += other; - } - } - - impl SubAssign for Complex { - fn sub_assign(&mut self, other: T) { - self.re -= other; - } - } - - impl MulAssign for Complex { - fn mul_assign(&mut self, other: T) { - self.re *= other.clone(); - self.im *= other; - } - } - - impl DivAssign for Complex { - fn div_assign(&mut self, other: T) { - self.re /= other.clone(); - self.im /= other; - } - } - - impl RemAssign for Complex { - fn rem_assign(&mut self, other: T) { - *self = self.clone() % other; - } - } - - macro_rules! forward_op_assign { - (impl $imp:ident, $method:ident) => { - impl<'a, T: Clone + NumAssign> $imp<&'a Complex> for Complex { - #[inline] - fn $method(&mut self, other: &Complex) { - self.$method(other.clone()) - } - } - impl<'a, T: Clone + NumAssign> $imp<&'a T> for Complex { - #[inline] - fn $method(&mut self, other: &T) { - self.$method(other.clone()) - } - } - } - } - - forward_op_assign!(impl AddAssign, add_assign); - forward_op_assign!(impl SubAssign, sub_assign); - forward_op_assign!(impl MulAssign, mul_assign); - forward_op_assign!(impl DivAssign, div_assign); - - impl<'a, T: Clone + NumAssign> RemAssign<&'a Complex> for Complex { - #[inline] - fn rem_assign(&mut self, other: &Complex) { - self.rem_assign(other.clone()) - } - } - impl<'a, T: Clone + NumAssign> RemAssign<&'a T> for Complex { - #[inline] - fn rem_assign(&mut self, other: &T) { - self.rem_assign(other.clone()) - } - } -} - -impl> Neg for Complex { - type Output = Complex; - - #[inline] - fn neg(self) -> Complex { - Complex::new(-self.re, -self.im) - } -} - -impl<'a, T: Clone + Num + Neg> Neg for &'a Complex { - type Output = Complex; - - #[inline] - fn neg(self) -> Complex { - -self.clone() - } -} - -macro_rules! real_arithmetic { - (@forward $imp:ident::$method:ident for $($real:ident),*) => ( - impl<'a, T: Clone + Num> $imp<&'a T> for Complex { - type Output = Complex; - - #[inline] - fn $method(self, other: &T) -> Complex { - self.$method(other.clone()) - } - } - impl<'a, T: Clone + Num> $imp for &'a Complex { - type Output = Complex; - - #[inline] - fn $method(self, other: T) -> Complex { - self.clone().$method(other) - } - } - impl<'a, 'b, T: Clone + Num> $imp<&'a T> for &'b Complex { - type Output = Complex; - - #[inline] - fn $method(self, other: &T) -> Complex { - self.clone().$method(other.clone()) - } - } - $( - impl<'a> $imp<&'a Complex<$real>> for $real { - type Output = Complex<$real>; - - #[inline] - fn $method(self, other: &Complex<$real>) -> Complex<$real> { - self.$method(other.clone()) - } - } - impl<'a> $imp> for &'a $real { - type Output = Complex<$real>; - - #[inline] - fn $method(self, other: Complex<$real>) -> Complex<$real> { - self.clone().$method(other) - } - } - impl<'a, 'b> $imp<&'a Complex<$real>> for &'b $real { - type Output = Complex<$real>; - - #[inline] - fn $method(self, other: &Complex<$real>) -> Complex<$real> { - self.clone().$method(other.clone()) - } - } - )* - ); - ($($real:ident),*) => ( - real_arithmetic!(@forward Add::add for $($real),*); - real_arithmetic!(@forward Sub::sub for $($real),*); - real_arithmetic!(@forward Mul::mul for $($real),*); - real_arithmetic!(@forward Div::div for $($real),*); - real_arithmetic!(@forward Rem::rem for $($real),*); - - $( - impl Add> for $real { - type Output = Complex<$real>; - - #[inline] - fn add(self, other: Complex<$real>) -> Complex<$real> { - Complex::new(self + other.re, other.im) - } - } - - impl Sub> for $real { - type Output = Complex<$real>; - - #[inline] - fn sub(self, other: Complex<$real>) -> Complex<$real> { - Complex::new(self - other.re, $real::zero() - other.im) - } - } - - impl Mul> for $real { - type Output = Complex<$real>; - - #[inline] - fn mul(self, other: Complex<$real>) -> Complex<$real> { - Complex::new(self * other.re, self * other.im) - } - } - - impl Div> for $real { - type Output = Complex<$real>; - - #[inline] - fn div(self, other: Complex<$real>) -> Complex<$real> { - // a / (c + i d) == [a * (c - i d)] / (c*c + d*d) - let norm_sqr = other.norm_sqr(); - Complex::new(self * other.re / norm_sqr.clone(), - $real::zero() - self * other.im / norm_sqr) - } - } - - impl Rem> for $real { - type Output = Complex<$real>; - - #[inline] - fn rem(self, other: Complex<$real>) -> Complex<$real> { - Complex::new(self, Self::zero()) % other - } - } - )* - ); -} - -impl Add for Complex { - type Output = Complex; - - #[inline] - fn add(self, other: T) -> Complex { - Complex::new(self.re + other, self.im) - } -} - -impl Sub for Complex { - type Output = Complex; - - #[inline] - fn sub(self, other: T) -> Complex { - Complex::new(self.re - other, self.im) - } -} - -impl Mul for Complex { - type Output = Complex; - - #[inline] - fn mul(self, other: T) -> Complex { - Complex::new(self.re * other.clone(), self.im * other) - } -} - -impl Div for Complex { - type Output = Complex; - - #[inline] - fn div(self, other: T) -> Complex { - Complex::new(self.re / other.clone(), self.im / other) - } -} - -impl Rem for Complex { - type Output = Complex; - - #[inline] - fn rem(self, other: T) -> Complex { - self % Complex::new(other, T::zero()) - } -} - -real_arithmetic!(usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32, f64); - -/* constants */ -impl Zero for Complex { - #[inline] - fn zero() -> Complex { - Complex::new(Zero::zero(), Zero::zero()) - } - - #[inline] - fn is_zero(&self) -> bool { - self.re.is_zero() && self.im.is_zero() - } -} - -impl One for Complex { - #[inline] - fn one() -> Complex { - Complex::new(One::one(), Zero::zero()) - } -} - -macro_rules! write_complex { - ($f:ident, $t:expr, $prefix:expr, $re:expr, $im:expr, $T:ident) => {{ - let abs_re = if $re < Zero::zero() { $T::zero() - $re.clone() } else { $re.clone() }; - let abs_im = if $im < Zero::zero() { $T::zero() - $im.clone() } else { $im.clone() }; - - let real: String; - let imag: String; - - if let Some(prec) = $f.precision() { - real = format!(concat!("{:.1$", $t, "}"), abs_re, prec); - imag = format!(concat!("{:.1$", $t, "}"), abs_im, prec); - } - else { - real = format!(concat!("{:", $t, "}"), abs_re); - imag = format!(concat!("{:", $t, "}"), abs_im); - } - - let prefix = if $f.alternate() { $prefix } else { "" }; - let sign = if $re < Zero::zero() { - "-" - } else if $f.sign_plus() { - "+" - } else { - "" - }; - - let complex = if $im < Zero::zero() { - format!("{}{pre}{re}-{pre}{im}i", sign, re=real, im=imag, pre=prefix) - } - else { - format!("{}{pre}{re}+{pre}{im}i", sign, re=real, im=imag, pre=prefix) - }; - - if let Some(width) = $f.width() { - write!($f, "{0: >1$}", complex, width) - } - else { - write!($f, "{}", complex) - } - }} -} - -/* string conversions */ -impl fmt::Display for Complex where - T: fmt::Display + Num + PartialOrd + Clone -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write_complex!(f, "", "", self.re, self.im, T) - } -} - -impl fmt::LowerExp for Complex where - T: fmt::LowerExp + Num + PartialOrd + Clone -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write_complex!(f, "e", "", self.re, self.im, T) - } -} - -impl fmt::UpperExp for Complex where - T: fmt::UpperExp + Num + PartialOrd + Clone -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write_complex!(f, "E", "", self.re, self.im, T) - } -} - -impl fmt::LowerHex for Complex where - T: fmt::LowerHex + Num + PartialOrd + Clone -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write_complex!(f, "x", "0x", self.re, self.im, T) - } -} - -impl fmt::UpperHex for Complex where - T: fmt::UpperHex + Num + PartialOrd + Clone -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write_complex!(f, "X", "0x", self.re, self.im, T) - } -} - -impl fmt::Octal for Complex where - T: fmt::Octal + Num + PartialOrd + Clone -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write_complex!(f, "o", "0o", self.re, self.im, T) - } -} - -impl fmt::Binary for Complex where - T: fmt::Binary + Num + PartialOrd + Clone -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write_complex!(f, "b", "0b", self.re, self.im, T) - } -} - -fn from_str_generic(s: &str, from: F) -> Result, ParseComplexError> - where F: Fn(&str) -> Result, T: Clone + Num -{ - let imag = match s.rfind('j') { - None => 'i', - _ => 'j' - }; - - let mut b = String::with_capacity(s.len()); - let mut first = true; - - let char_indices = s.char_indices(); - let mut pc = ' '; - let mut split_index = s.len(); - - for (i, cc) in char_indices { - if cc == '+' && pc != 'e' && pc != 'E' && i > 0 { - // ignore '+' if part of an exponent - if first { - split_index = i; - first = false; - } - // don't carry '+' over into b - pc = ' '; - continue; - } else if cc == '-' && pc != 'e' && pc != 'E' && i > 0 { - // ignore '-' if part of an exponent or begins the string - if first { - split_index = i; - first = false; - } - // DO carry '-' over into b - } - - if pc == '-' && cc == ' ' && !first { - // ignore whitespace between minus sign and next number - continue; - } - - if !first { - b.push(cc); - } - pc = cc; - } - - // split off real and imaginary parts, trim whitespace - let (a, _) = s.split_at(split_index); - let a = a.trim_right(); - let mut b = b.trim_left(); - // input was either pure real or pure imaginary - if b.is_empty() { - b = match a.ends_with(imag) { - false => "0i", - true => "0" - }; - } - - let re; - let im; - if a.ends_with(imag) { - im = a; re = b; - } else if b.ends_with(imag) { - re = a; im = b; - } else { - return Err(ParseComplexError::new()); - } - - // parse re - let re = try!(from(re).map_err(ParseComplexError::from_error)); - - // pop imaginary unit off - let mut im = &im[..im.len()-1]; - // handle im == "i" or im == "-i" - if im.is_empty() || im == "+" { - im = "1"; - } else if im == "-" { - im = "-1"; - } - - // parse im - let im = try!(from(im).map_err(ParseComplexError::from_error)); - - Ok(Complex::new(re, im)) -} - -impl FromStr for Complex where - T: FromStr + Num + Clone -{ - type Err = ParseComplexError; - - /// Parses `a +/- bi`; `ai +/- b`; `a`; or `bi` where `a` and `b` are of type `T` - fn from_str(s: &str) -> Result - { - from_str_generic(s, T::from_str) - } -} - -impl Num for Complex { - type FromStrRadixErr = ParseComplexError; - - /// Parses `a +/- bi`; `ai +/- b`; `a`; or `bi` where `a` and `b` are of type `T` - fn from_str_radix(s: &str, radix: u32) -> Result - { - from_str_generic(s, |x| -> Result { - T::from_str_radix(x, radix) }) - } -} - -#[cfg(feature = "serde")] -impl serde::Serialize for Complex - where T: serde::Serialize -{ - fn serialize(&self, serializer: &mut S) -> Result<(), S::Error> where - S: serde::Serializer - { - (&self.re, &self.im).serialize(serializer) - } -} - -#[cfg(feature = "serde")] -impl serde::Deserialize for Complex where - T: serde::Deserialize + Num + Clone -{ - fn deserialize(deserializer: &mut D) -> Result where - D: serde::Deserializer, - { - let (re, im) = try!(serde::Deserialize::deserialize(deserializer)); - Ok(Complex::new(re, im)) - } -} - -#[derive(Debug, PartialEq)] -pub struct ParseComplexError -{ - kind: ComplexErrorKind, -} - -#[derive(Debug, PartialEq)] -enum ComplexErrorKind -{ - ParseError(E), - ExprError -} - -impl ParseComplexError -{ - fn new() -> Self { - ParseComplexError { - kind: ComplexErrorKind::ExprError, - } - } - - fn from_error(error: E) -> Self { - ParseComplexError { - kind: ComplexErrorKind::ParseError(error), - } - } -} - -impl Error for ParseComplexError -{ - fn description(&self) -> &str { - match self.kind { - ComplexErrorKind::ParseError(ref e) => e.description(), - ComplexErrorKind::ExprError => "invalid or unsupported complex expression" - } - } -} - -impl fmt::Display for ParseComplexError -{ - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.description().fmt(f) - } -} - -#[cfg(test)] -fn hash(x: &T) -> u64 { - use std::hash::{BuildHasher, Hasher}; - use std::collections::hash_map::RandomState; - let mut hasher = ::Hasher::new(); - x.hash(&mut hasher); - hasher.finish() -} - -#[cfg(test)] -mod test { - #![allow(non_upper_case_globals)] - - use super::{Complex64, Complex}; - use std::f64; - use std::str::FromStr; - - use traits::{Zero, One, Float, Num}; - - pub const _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 }; - pub const _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 }; - pub const _1_1i : Complex64 = Complex { re: 1.0, im: 1.0 }; - pub const _0_1i : Complex64 = Complex { re: 0.0, im: 1.0 }; - pub const _neg1_1i : Complex64 = Complex { re: -1.0, im: 1.0 }; - pub const _05_05i : Complex64 = Complex { re: 0.5, im: 0.5 }; - pub const all_consts : [Complex64; 5] = [_0_0i, _1_0i, _1_1i, _neg1_1i, _05_05i]; - pub const _4_2i : Complex64 = Complex { re: 4.0, im: 2.0 }; - - #[test] - fn test_consts() { - // check our constants are what Complex::new creates - fn test(c : Complex64, r : f64, i: f64) { - assert_eq!(c, Complex::new(r,i)); - } - test(_0_0i, 0.0, 0.0); - test(_1_0i, 1.0, 0.0); - test(_1_1i, 1.0, 1.0); - test(_neg1_1i, -1.0, 1.0); - test(_05_05i, 0.5, 0.5); - - assert_eq!(_0_0i, Zero::zero()); - assert_eq!(_1_0i, One::one()); - } - - #[test] - #[cfg_attr(target_arch = "x86", ignore)] - // FIXME #7158: (maybe?) currently failing on x86. - fn test_norm() { - fn test(c: Complex64, ns: f64) { - assert_eq!(c.norm_sqr(), ns); - assert_eq!(c.norm(), ns.sqrt()) - } - test(_0_0i, 0.0); - test(_1_0i, 1.0); - test(_1_1i, 2.0); - test(_neg1_1i, 2.0); - test(_05_05i, 0.5); - } - - #[test] - fn test_scale_unscale() { - assert_eq!(_05_05i.scale(2.0), _1_1i); - assert_eq!(_1_1i.unscale(2.0), _05_05i); - for &c in all_consts.iter() { - assert_eq!(c.scale(2.0).unscale(2.0), c); - } - } - - #[test] - fn test_conj() { - for &c in all_consts.iter() { - assert_eq!(c.conj(), Complex::new(c.re, -c.im)); - assert_eq!(c.conj().conj(), c); - } - } - - #[test] - fn test_inv() { - assert_eq!(_1_1i.inv(), _05_05i.conj()); - assert_eq!(_1_0i.inv(), _1_0i.inv()); - } - - #[test] - #[should_panic] - fn test_divide_by_zero_natural() { - let n = Complex::new(2, 3); - let d = Complex::new(0, 0); - let _x = n / d; - } - - #[test] - fn test_inv_zero() { - // FIXME #20: should this really fail, or just NaN? - assert!(_0_0i.inv().is_nan()); - } - - #[test] - fn test_arg() { - fn test(c: Complex64, arg: f64) { - assert!((c.arg() - arg).abs() < 1.0e-6) - } - test(_1_0i, 0.0); - test(_1_1i, 0.25 * f64::consts::PI); - test(_neg1_1i, 0.75 * f64::consts::PI); - test(_05_05i, 0.25 * f64::consts::PI); - } - - #[test] - fn test_polar_conv() { - fn test(c: Complex64) { - let (r, theta) = c.to_polar(); - assert!((c - Complex::from_polar(&r, &theta)).norm() < 1e-6); - } - for &c in all_consts.iter() { test(c); } - } - - fn close(a: Complex64, b: Complex64) -> bool { - close_to_tol(a, b, 1e-10) - } - - fn close_to_tol(a: Complex64, b: Complex64, tol: f64) -> bool { - // returns true if a and b are reasonably close - (a == b) || (a-b).norm() < tol - } - - #[test] - fn test_exp() { - assert!(close(_1_0i.exp(), _1_0i.scale(f64::consts::E))); - assert!(close(_0_0i.exp(), _1_0i)); - assert!(close(_0_1i.exp(), Complex::new(1.0.cos(), 1.0.sin()))); - assert!(close(_05_05i.exp()*_05_05i.exp(), _1_1i.exp())); - assert!(close(_0_1i.scale(-f64::consts::PI).exp(), _1_0i.scale(-1.0))); - for &c in all_consts.iter() { - // e^conj(z) = conj(e^z) - assert!(close(c.conj().exp(), c.exp().conj())); - // e^(z + 2 pi i) = e^z - assert!(close(c.exp(), (c + _0_1i.scale(f64::consts::PI*2.0)).exp())); - } - } - - #[test] - fn test_ln() { - assert!(close(_1_0i.ln(), _0_0i)); - assert!(close(_0_1i.ln(), _0_1i.scale(f64::consts::PI/2.0))); - assert!(close(_0_0i.ln(), Complex::new(f64::neg_infinity(), 0.0))); - assert!(close((_neg1_1i * _05_05i).ln(), _neg1_1i.ln() + _05_05i.ln())); - for &c in all_consts.iter() { - // ln(conj(z() = conj(ln(z)) - assert!(close(c.conj().ln(), c.ln().conj())); - // for this branch, -pi <= arg(ln(z)) <= pi - assert!(-f64::consts::PI <= c.ln().arg() && c.ln().arg() <= f64::consts::PI); - } - } - - #[test] - fn test_powc() - { - let a = Complex::new(2.0, -3.0); - let b = Complex::new(3.0, 0.0); - assert!(close(a.powc(b), a.powf(b.re))); - assert!(close(b.powc(a), a.expf(b.re))); - let c = Complex::new(1.0 / 3.0, 0.1); - assert!(close_to_tol(a.powc(c), Complex::new(1.65826, -0.33502), 1e-5)); - } - - #[test] - fn test_powf() - { - let c = Complex::new(2.0, -1.0); - let r = c.powf(3.5); - assert!(close_to_tol(r, Complex::new(-0.8684746, -16.695934), 1e-5)); - } - - #[test] - fn test_log() - { - let c = Complex::new(2.0, -1.0); - let r = c.log(10.0); - assert!(close_to_tol(r, Complex::new(0.349485, -0.20135958), 1e-5)); - } - - #[test] - fn test_some_expf_cases() - { - let c = Complex::new(2.0, -1.0); - let r = c.expf(10.0); - assert!(close_to_tol(r, Complex::new(-66.82015, -74.39803), 1e-5)); - - let c = Complex::new(5.0, -2.0); - let r = c.expf(3.4); - assert!(close_to_tol(r, Complex::new(-349.25, -290.63), 1e-2)); - - let c = Complex::new(-1.5, 2.0 / 3.0); - let r = c.expf(1.0 / 3.0); - assert!(close_to_tol(r, Complex::new(3.8637, -3.4745), 1e-2)); - } - - #[test] - fn test_sqrt() { - assert!(close(_0_0i.sqrt(), _0_0i)); - assert!(close(_1_0i.sqrt(), _1_0i)); - assert!(close(Complex::new(-1.0, 0.0).sqrt(), _0_1i)); - assert!(close(Complex::new(-1.0, -0.0).sqrt(), _0_1i.scale(-1.0))); - assert!(close(_0_1i.sqrt(), _05_05i.scale(2.0.sqrt()))); - for &c in all_consts.iter() { - // sqrt(conj(z() = conj(sqrt(z)) - assert!(close(c.conj().sqrt(), c.sqrt().conj())); - // for this branch, -pi/2 <= arg(sqrt(z)) <= pi/2 - assert!(-f64::consts::PI/2.0 <= c.sqrt().arg() && c.sqrt().arg() <= f64::consts::PI/2.0); - // sqrt(z) * sqrt(z) = z - assert!(close(c.sqrt()*c.sqrt(), c)); - } - } - - #[test] - fn test_sin() { - assert!(close(_0_0i.sin(), _0_0i)); - assert!(close(_1_0i.scale(f64::consts::PI*2.0).sin(), _0_0i)); - assert!(close(_0_1i.sin(), _0_1i.scale(1.0.sinh()))); - for &c in all_consts.iter() { - // sin(conj(z)) = conj(sin(z)) - assert!(close(c.conj().sin(), c.sin().conj())); - // sin(-z) = -sin(z) - assert!(close(c.scale(-1.0).sin(), c.sin().scale(-1.0))); - } - } - - #[test] - fn test_cos() { - assert!(close(_0_0i.cos(), _1_0i)); - assert!(close(_1_0i.scale(f64::consts::PI*2.0).cos(), _1_0i)); - assert!(close(_0_1i.cos(), _1_0i.scale(1.0.cosh()))); - for &c in all_consts.iter() { - // cos(conj(z)) = conj(cos(z)) - assert!(close(c.conj().cos(), c.cos().conj())); - // cos(-z) = cos(z) - assert!(close(c.scale(-1.0).cos(), c.cos())); - } - } - - #[test] - fn test_tan() { - assert!(close(_0_0i.tan(), _0_0i)); - assert!(close(_1_0i.scale(f64::consts::PI/4.0).tan(), _1_0i)); - assert!(close(_1_0i.scale(f64::consts::PI).tan(), _0_0i)); - for &c in all_consts.iter() { - // tan(conj(z)) = conj(tan(z)) - assert!(close(c.conj().tan(), c.tan().conj())); - // tan(-z) = -tan(z) - assert!(close(c.scale(-1.0).tan(), c.tan().scale(-1.0))); - } - } - - #[test] - fn test_asin() { - assert!(close(_0_0i.asin(), _0_0i)); - assert!(close(_1_0i.asin(), _1_0i.scale(f64::consts::PI/2.0))); - assert!(close(_1_0i.scale(-1.0).asin(), _1_0i.scale(-f64::consts::PI/2.0))); - assert!(close(_0_1i.asin(), _0_1i.scale((1.0 + 2.0.sqrt()).ln()))); - for &c in all_consts.iter() { - // asin(conj(z)) = conj(asin(z)) - assert!(close(c.conj().asin(), c.asin().conj())); - // asin(-z) = -asin(z) - assert!(close(c.scale(-1.0).asin(), c.asin().scale(-1.0))); - // for this branch, -pi/2 <= asin(z).re <= pi/2 - assert!(-f64::consts::PI/2.0 <= c.asin().re && c.asin().re <= f64::consts::PI/2.0); - } - } - - #[test] - fn test_acos() { - assert!(close(_0_0i.acos(), _1_0i.scale(f64::consts::PI/2.0))); - assert!(close(_1_0i.acos(), _0_0i)); - assert!(close(_1_0i.scale(-1.0).acos(), _1_0i.scale(f64::consts::PI))); - assert!(close(_0_1i.acos(), Complex::new(f64::consts::PI/2.0, (2.0.sqrt() - 1.0).ln()))); - for &c in all_consts.iter() { - // acos(conj(z)) = conj(acos(z)) - assert!(close(c.conj().acos(), c.acos().conj())); - // for this branch, 0 <= acos(z).re <= pi - assert!(0.0 <= c.acos().re && c.acos().re <= f64::consts::PI); - } - } - - #[test] - fn test_atan() { - assert!(close(_0_0i.atan(), _0_0i)); - assert!(close(_1_0i.atan(), _1_0i.scale(f64::consts::PI/4.0))); - assert!(close(_1_0i.scale(-1.0).atan(), _1_0i.scale(-f64::consts::PI/4.0))); - assert!(close(_0_1i.atan(), Complex::new(0.0, f64::infinity()))); - for &c in all_consts.iter() { - // atan(conj(z)) = conj(atan(z)) - assert!(close(c.conj().atan(), c.atan().conj())); - // atan(-z) = -atan(z) - assert!(close(c.scale(-1.0).atan(), c.atan().scale(-1.0))); - // for this branch, -pi/2 <= atan(z).re <= pi/2 - assert!(-f64::consts::PI/2.0 <= c.atan().re && c.atan().re <= f64::consts::PI/2.0); - } - } - - #[test] - fn test_sinh() { - assert!(close(_0_0i.sinh(), _0_0i)); - assert!(close(_1_0i.sinh(), _1_0i.scale((f64::consts::E - 1.0/f64::consts::E)/2.0))); - assert!(close(_0_1i.sinh(), _0_1i.scale(1.0.sin()))); - for &c in all_consts.iter() { - // sinh(conj(z)) = conj(sinh(z)) - assert!(close(c.conj().sinh(), c.sinh().conj())); - // sinh(-z) = -sinh(z) - assert!(close(c.scale(-1.0).sinh(), c.sinh().scale(-1.0))); - } - } - - #[test] - fn test_cosh() { - assert!(close(_0_0i.cosh(), _1_0i)); - assert!(close(_1_0i.cosh(), _1_0i.scale((f64::consts::E + 1.0/f64::consts::E)/2.0))); - assert!(close(_0_1i.cosh(), _1_0i.scale(1.0.cos()))); - for &c in all_consts.iter() { - // cosh(conj(z)) = conj(cosh(z)) - assert!(close(c.conj().cosh(), c.cosh().conj())); - // cosh(-z) = cosh(z) - assert!(close(c.scale(-1.0).cosh(), c.cosh())); - } - } - - #[test] - fn test_tanh() { - assert!(close(_0_0i.tanh(), _0_0i)); - assert!(close(_1_0i.tanh(), _1_0i.scale((f64::consts::E.powi(2) - 1.0)/(f64::consts::E.powi(2) + 1.0)))); - assert!(close(_0_1i.tanh(), _0_1i.scale(1.0.tan()))); - for &c in all_consts.iter() { - // tanh(conj(z)) = conj(tanh(z)) - assert!(close(c.conj().tanh(), c.conj().tanh())); - // tanh(-z) = -tanh(z) - assert!(close(c.scale(-1.0).tanh(), c.tanh().scale(-1.0))); - } - } - - #[test] - fn test_asinh() { - assert!(close(_0_0i.asinh(), _0_0i)); - assert!(close(_1_0i.asinh(), _1_0i.scale(1.0 + 2.0.sqrt()).ln())); - assert!(close(_0_1i.asinh(), _0_1i.scale(f64::consts::PI/2.0))); - assert!(close(_0_1i.asinh().scale(-1.0), _0_1i.scale(-f64::consts::PI/2.0))); - for &c in all_consts.iter() { - // asinh(conj(z)) = conj(asinh(z)) - assert!(close(c.conj().asinh(), c.conj().asinh())); - // asinh(-z) = -asinh(z) - assert!(close(c.scale(-1.0).asinh(), c.asinh().scale(-1.0))); - // for this branch, -pi/2 <= asinh(z).im <= pi/2 - assert!(-f64::consts::PI/2.0 <= c.asinh().im && c.asinh().im <= f64::consts::PI/2.0); - } - } - - #[test] - fn test_acosh() { - assert!(close(_0_0i.acosh(), _0_1i.scale(f64::consts::PI/2.0))); - assert!(close(_1_0i.acosh(), _0_0i)); - assert!(close(_1_0i.scale(-1.0).acosh(), _0_1i.scale(f64::consts::PI))); - for &c in all_consts.iter() { - // acosh(conj(z)) = conj(acosh(z)) - assert!(close(c.conj().acosh(), c.conj().acosh())); - // for this branch, -pi <= acosh(z).im <= pi and 0 <= acosh(z).re - assert!(-f64::consts::PI <= c.acosh().im && c.acosh().im <= f64::consts::PI && 0.0 <= c.cosh().re); - } - } - - #[test] - fn test_atanh() { - assert!(close(_0_0i.atanh(), _0_0i)); - assert!(close(_0_1i.atanh(), _0_1i.scale(f64::consts::PI/4.0))); - assert!(close(_1_0i.atanh(), Complex::new(f64::infinity(), 0.0))); - for &c in all_consts.iter() { - // atanh(conj(z)) = conj(atanh(z)) - assert!(close(c.conj().atanh(), c.conj().atanh())); - // atanh(-z) = -atanh(z) - assert!(close(c.scale(-1.0).atanh(), c.atanh().scale(-1.0))); - // for this branch, -pi/2 <= atanh(z).im <= pi/2 - assert!(-f64::consts::PI/2.0 <= c.atanh().im && c.atanh().im <= f64::consts::PI/2.0); - } - } - - #[test] - fn test_exp_ln() { - for &c in all_consts.iter() { - // e^ln(z) = z - assert!(close(c.ln().exp(), c)); - } - } - - #[test] - fn test_trig_to_hyperbolic() { - for &c in all_consts.iter() { - // sin(iz) = i sinh(z) - assert!(close((_0_1i * c).sin(), _0_1i * c.sinh())); - // cos(iz) = cosh(z) - assert!(close((_0_1i * c).cos(), c.cosh())); - // tan(iz) = i tanh(z) - assert!(close((_0_1i * c).tan(), _0_1i * c.tanh())); - } - } - - #[test] - fn test_trig_identities() { - for &c in all_consts.iter() { - // tan(z) = sin(z)/cos(z) - assert!(close(c.tan(), c.sin()/c.cos())); - // sin(z)^2 + cos(z)^2 = 1 - assert!(close(c.sin()*c.sin() + c.cos()*c.cos(), _1_0i)); - - // sin(asin(z)) = z - assert!(close(c.asin().sin(), c)); - // cos(acos(z)) = z - assert!(close(c.acos().cos(), c)); - // tan(atan(z)) = z - // i and -i are branch points - if c != _0_1i && c != _0_1i.scale(-1.0) { - assert!(close(c.atan().tan(), c)); - } - - // sin(z) = (e^(iz) - e^(-iz))/(2i) - assert!(close(((_0_1i*c).exp() - (_0_1i*c).exp().inv())/_0_1i.scale(2.0), c.sin())); - // cos(z) = (e^(iz) + e^(-iz))/2 - assert!(close(((_0_1i*c).exp() + (_0_1i*c).exp().inv()).unscale(2.0), c.cos())); - // tan(z) = i (1 - e^(2iz))/(1 + e^(2iz)) - assert!(close(_0_1i * (_1_0i - (_0_1i*c).scale(2.0).exp())/(_1_0i + (_0_1i*c).scale(2.0).exp()), c.tan())); - } - } - - #[test] - fn test_hyperbolic_identites() { - for &c in all_consts.iter() { - // tanh(z) = sinh(z)/cosh(z) - assert!(close(c.tanh(), c.sinh()/c.cosh())); - // cosh(z)^2 - sinh(z)^2 = 1 - assert!(close(c.cosh()*c.cosh() - c.sinh()*c.sinh(), _1_0i)); - - // sinh(asinh(z)) = z - assert!(close(c.asinh().sinh(), c)); - // cosh(acosh(z)) = z - assert!(close(c.acosh().cosh(), c)); - // tanh(atanh(z)) = z - // 1 and -1 are branch points - if c != _1_0i && c != _1_0i.scale(-1.0) { - assert!(close(c.atanh().tanh(), c)); - } - - // sinh(z) = (e^z - e^(-z))/2 - assert!(close((c.exp() - c.exp().inv()).unscale(2.0), c.sinh())); - // cosh(z) = (e^z + e^(-z))/2 - assert!(close((c.exp() + c.exp().inv()).unscale(2.0), c.cosh())); - // tanh(z) = ( e^(2z) - 1)/(e^(2z) + 1) - assert!(close((c.scale(2.0).exp() - _1_0i)/(c.scale(2.0).exp() + _1_0i), c.tanh())); - } - } - - // Test both a + b and a += b - macro_rules! test_a_op_b { - ($a:ident + $b:expr, $answer:expr) => { - assert_eq!($a + $b, $answer); - assert_eq!({ let mut x = $a; x += $b; x}, $answer); - }; - ($a:ident - $b:expr, $answer:expr) => { - assert_eq!($a - $b, $answer); - assert_eq!({ let mut x = $a; x -= $b; x}, $answer); - }; - ($a:ident * $b:expr, $answer:expr) => { - assert_eq!($a * $b, $answer); - assert_eq!({ let mut x = $a; x *= $b; x}, $answer); - }; - ($a:ident / $b:expr, $answer:expr) => { - assert_eq!($a / $b, $answer); - assert_eq!({ let mut x = $a; x /= $b; x}, $answer); - }; - ($a:ident % $b:expr, $answer:expr) => { - assert_eq!($a % $b, $answer); - assert_eq!({ let mut x = $a; x %= $b; x}, $answer); - } - } - - // Test both a + b and a + &b - macro_rules! test_op { - ($a:ident $op:tt $b:expr, $answer:expr) => { - test_a_op_b!($a $op $b, $answer); - test_a_op_b!($a $op &$b, $answer); - } - } - - mod complex_arithmetic { - use super::{_0_0i, _1_0i, _1_1i, _0_1i, _neg1_1i, _05_05i, _4_2i, all_consts}; - use traits::Zero; - - #[test] - fn test_add() { - test_op!(_05_05i + _05_05i, _1_1i); - test_op!(_0_1i + _1_0i, _1_1i); - test_op!(_1_0i + _neg1_1i, _0_1i); - - for &c in all_consts.iter() { - test_op!(_0_0i + c, c); - test_op!(c + _0_0i, c); - } - } - - #[test] - fn test_sub() { - test_op!(_05_05i - _05_05i, _0_0i); - test_op!(_0_1i - _1_0i, _neg1_1i); - test_op!(_0_1i - _neg1_1i, _1_0i); - - for &c in all_consts.iter() { - test_op!(c - _0_0i, c); - test_op!(c - c, _0_0i); - } - } - - #[test] - fn test_mul() { - test_op!(_05_05i * _05_05i, _0_1i.unscale(2.0)); - test_op!(_1_1i * _0_1i, _neg1_1i); - - // i^2 & i^4 - test_op!(_0_1i * _0_1i, -_1_0i); - assert_eq!(_0_1i * _0_1i * _0_1i * _0_1i, _1_0i); - - for &c in all_consts.iter() { - test_op!(c * _1_0i, c); - test_op!(_1_0i * c, c); - } - } - - #[test] - fn test_div() { - test_op!(_neg1_1i / _0_1i, _1_1i); - for &c in all_consts.iter() { - if c != Zero::zero() { - test_op!(c / c, _1_0i); - } - } - } - - #[test] - fn test_rem() { - test_op!(_neg1_1i % _0_1i, _0_0i); - test_op!(_4_2i % _0_1i, _0_0i); - test_op!(_05_05i % _0_1i, _05_05i); - test_op!(_05_05i % _1_1i, _05_05i); - assert_eq!((_4_2i + _05_05i) % _0_1i, _05_05i); - assert_eq!((_4_2i + _05_05i) % _1_1i, _05_05i); - } - - #[test] - fn test_neg() { - assert_eq!(-_1_0i + _0_1i, _neg1_1i); - assert_eq!((-_0_1i) * _0_1i, _1_0i); - for &c in all_consts.iter() { - assert_eq!(-(-c), c); - } - } - } - - mod real_arithmetic { - use super::super::Complex; - use super::{_4_2i, _neg1_1i}; - - #[test] - fn test_add() { - test_op!(_4_2i + 0.5, Complex::new(4.5, 2.0)); - assert_eq!(0.5 + _4_2i, Complex::new(4.5, 2.0)); - } - - #[test] - fn test_sub() { - test_op!(_4_2i - 0.5, Complex::new(3.5, 2.0)); - assert_eq!(0.5 - _4_2i, Complex::new(-3.5, -2.0)); - } - - #[test] - fn test_mul() { - assert_eq!(_4_2i * 0.5, Complex::new(2.0, 1.0)); - assert_eq!(0.5 * _4_2i, Complex::new(2.0, 1.0)); - } - - #[test] - fn test_div() { - assert_eq!(_4_2i / 0.5, Complex::new(8.0, 4.0)); - assert_eq!(0.5 / _4_2i, Complex::new(0.1, -0.05)); - } - - #[test] - fn test_rem() { - assert_eq!(_4_2i % 2.0, Complex::new(0.0, 0.0)); - assert_eq!(_4_2i % 3.0, Complex::new(1.0, 2.0)); - assert_eq!(3.0 % _4_2i, Complex::new(3.0, 0.0)); - assert_eq!(_neg1_1i % 2.0, _neg1_1i); - assert_eq!(-_4_2i % 3.0, Complex::new(-1.0, -2.0)); - } - } - - #[test] - fn test_to_string() { - fn test(c : Complex64, s: String) { - assert_eq!(c.to_string(), s); - } - test(_0_0i, "0+0i".to_string()); - test(_1_0i, "1+0i".to_string()); - test(_0_1i, "0+1i".to_string()); - test(_1_1i, "1+1i".to_string()); - test(_neg1_1i, "-1+1i".to_string()); - test(-_neg1_1i, "1-1i".to_string()); - test(_05_05i, "0.5+0.5i".to_string()); - } - - #[test] - fn test_string_formatting() { - let a = Complex::new(1.23456, 123.456); - assert_eq!(format!("{}", a), "1.23456+123.456i"); - assert_eq!(format!("{:.2}", a), "1.23+123.46i"); - assert_eq!(format!("{:.2e}", a), "1.23e0+1.23e2i"); - assert_eq!(format!("{:+20.2E}", a), " +1.23E0+1.23E2i"); - - let b = Complex::new(0x80, 0xff); - assert_eq!(format!("{:X}", b), "80+FFi"); - assert_eq!(format!("{:#x}", b), "0x80+0xffi"); - assert_eq!(format!("{:+#b}", b), "+0b10000000+0b11111111i"); - assert_eq!(format!("{:+#16o}", b), " +0o200+0o377i"); - - let c = Complex::new(-10, -10000); - assert_eq!(format!("{}", c), "-10-10000i"); - assert_eq!(format!("{:16}", c), " -10-10000i"); - } - - #[test] - fn test_hash() { - let a = Complex::new(0i32, 0i32); - let b = Complex::new(1i32, 0i32); - let c = Complex::new(0i32, 1i32); - assert!(::hash(&a) != ::hash(&b)); - assert!(::hash(&b) != ::hash(&c)); - assert!(::hash(&c) != ::hash(&a)); - } - - #[test] - fn test_hashset() { - use std::collections::HashSet; - let a = Complex::new(0i32, 0i32); - let b = Complex::new(1i32, 0i32); - let c = Complex::new(0i32, 1i32); - - let set: HashSet<_> = [a, b, c].iter().cloned().collect(); - assert!(set.contains(&a)); - assert!(set.contains(&b)); - assert!(set.contains(&c)); - assert!(!set.contains(&(a + b + c))); - } - - #[test] - fn test_is_nan() { - assert!(!_1_1i.is_nan()); - let a = Complex::new(f64::NAN, f64::NAN); - assert!(a.is_nan()); - } - - #[test] - fn test_is_nan_special_cases() { - let a = Complex::new(0f64, f64::NAN); - let b = Complex::new(f64::NAN, 0f64); - assert!(a.is_nan()); - assert!(b.is_nan()); - } - - #[test] - fn test_is_infinite() { - let a = Complex::new(2f64, f64::INFINITY); - assert!(a.is_infinite()); - } - - #[test] - fn test_is_finite() { - assert!(_1_1i.is_finite()) - } - - #[test] - fn test_is_normal() { - let a = Complex::new(0f64, f64::NAN); - let b = Complex::new(2f64, f64::INFINITY); - assert!(!a.is_normal()); - assert!(!b.is_normal()); - assert!(_1_1i.is_normal()); - } - - #[test] - fn test_from_str() { - fn test(z: Complex64, s: &str) { - assert_eq!(FromStr::from_str(s), Ok(z)); - } - test(_0_0i, "0 + 0i"); - test(_0_0i, "0+0j"); - test(_0_0i, "0 - 0j"); - test(_0_0i, "0-0i"); - test(_0_0i, "0i + 0"); - test(_0_0i, "0"); - test(_0_0i, "-0"); - test(_0_0i, "0i"); - test(_0_0i, "0j"); - test(_0_0i, "+0j"); - test(_0_0i, "-0i"); - - test(_1_0i, "1 + 0i"); - test(_1_0i, "1+0j"); - test(_1_0i, "1 - 0j"); - test(_1_0i, "+1-0i"); - test(_1_0i, "-0j+1"); - test(_1_0i, "1"); - - test(_1_1i, "1 + i"); - test(_1_1i, "1+j"); - test(_1_1i, "1 + 1j"); - test(_1_1i, "1+1i"); - test(_1_1i, "i + 1"); - test(_1_1i, "1i+1"); - test(_1_1i, "+j+1"); - - test(_0_1i, "0 + i"); - test(_0_1i, "0+j"); - test(_0_1i, "-0 + j"); - test(_0_1i, "-0+i"); - test(_0_1i, "0 + 1i"); - test(_0_1i, "0+1j"); - test(_0_1i, "-0 + 1j"); - test(_0_1i, "-0+1i"); - test(_0_1i, "j + 0"); - test(_0_1i, "i"); - test(_0_1i, "j"); - test(_0_1i, "1j"); - - test(_neg1_1i, "-1 + i"); - test(_neg1_1i, "-1+j"); - test(_neg1_1i, "-1 + 1j"); - test(_neg1_1i, "-1+1i"); - test(_neg1_1i, "1i-1"); - test(_neg1_1i, "j + -1"); - - test(_05_05i, "0.5 + 0.5i"); - test(_05_05i, "0.5+0.5j"); - test(_05_05i, "5e-1+0.5j"); - test(_05_05i, "5E-1 + 0.5j"); - test(_05_05i, "5E-1i + 0.5"); - test(_05_05i, "0.05e+1j + 50E-2"); - } - - #[test] - fn test_from_str_radix() { - fn test(z: Complex64, s: &str, radix: u32) { - let res: Result::FromStrRadixErr> - = Num::from_str_radix(s, radix); - assert_eq!(res.unwrap(), z) - } - test(_4_2i, "4+2i", 10); - test(Complex::new(15.0, 32.0), "F+20i", 16); - test(Complex::new(15.0, 32.0), "1111+100000i", 2); - test(Complex::new(-15.0, -32.0), "-F-20i", 16); - test(Complex::new(-15.0, -32.0), "-1111-100000i", 2); - } - - #[test] - fn test_from_str_fail() { - fn test(s: &str) { - let complex: Result = FromStr::from_str(s); - assert!(complex.is_err()); - } - test("foo"); - test("6E"); - test("0 + 2.718"); - test("1 - -2i"); - test("314e-2ij"); - test("4.3j - i"); - test("1i - 2i"); - test("+ 1 - 3.0i"); - } -} diff -Nru cargo-0.25.0/vendor/num-complex-0.1.42/.travis.yml cargo-0.26.0/vendor/num-complex-0.1.42/.travis.yml --- cargo-0.25.0/vendor/num-complex-0.1.42/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.42/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -language: rust -rust: - - 1.8.0 - - stable - - beta - - nightly -sudo: false -script: - - cargo build --verbose - - ./ci/test_full.sh -notifications: - email: - on_success: never -branches: - only: - - master - - next - - staging - - trying diff -Nru cargo-0.25.0/vendor/num-complex-0.1.43/bors.toml cargo-0.26.0/vendor/num-complex-0.1.43/bors.toml --- cargo-0.25.0/vendor/num-complex-0.1.43/bors.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.43/bors.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3 @@ +status = [ + "continuous-integration/travis-ci/push", +] diff -Nru cargo-0.25.0/vendor/num-complex-0.1.43/.cargo-checksum.json cargo-0.26.0/vendor/num-complex-0.1.43/.cargo-checksum.json --- cargo-0.25.0/vendor/num-complex-0.1.43/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.43/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"b288631d7878aaf59442cffd36910ea604ecd7745c36054328595114001c9656"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/num-complex-0.1.43/Cargo.toml cargo-0.26.0/vendor/num-complex-0.1.43/Cargo.toml --- cargo-0.25.0/vendor/num-complex-0.1.43/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.43/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,40 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "num-complex" +version = "0.1.43" +authors = ["The Rust Project Developers"] +description = "Complex numbers implementation for Rust" +homepage = "https://github.com/rust-num/num-complex" +documentation = "https://docs.rs/num-complex" +readme = "README.md" +keywords = ["mathematics", "numerics"] +categories = ["algorithms", "data-structures", "science"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-num/num-complex" +[dependencies.num-traits] +version = "0.2.0" +features = ["std"] +default-features = false + +[dependencies.rustc-serialize] +version = "0.3.19" +optional = true + +[dependencies.serde] +version = ">= 0.7.0, < 0.9.0" +optional = true + +[features] +default = ["rustc-serialize"] +unstable = [] diff -Nru cargo-0.25.0/vendor/num-complex-0.1.43/ci/rustup.sh cargo-0.26.0/vendor/num-complex-0.1.43/ci/rustup.sh --- cargo-0.25.0/vendor/num-complex-0.1.43/ci/rustup.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.43/ci/rustup.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,12 @@ +#!/bin/sh +# Use rustup to locally run the same suite of tests as .travis.yml. +# (You should first install/update 1.8.0, stable, beta, and nightly.) + +set -ex + +export TRAVIS_RUST_VERSION +for TRAVIS_RUST_VERSION in 1.8.0 stable beta nightly; do + run="rustup run $TRAVIS_RUST_VERSION" + $run cargo build --verbose + $run $PWD/ci/test_full.sh +done diff -Nru cargo-0.25.0/vendor/num-complex-0.1.43/ci/test_full.sh cargo-0.26.0/vendor/num-complex-0.1.43/ci/test_full.sh --- cargo-0.25.0/vendor/num-complex-0.1.43/ci/test_full.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.43/ci/test_full.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,23 @@ +#!/bin/bash + +set -ex + +echo Testing num-complex on rustc ${TRAVIS_RUST_VERSION} + +# num-complex should build and test everywhere. +cargo build --verbose +cargo test --verbose + +# It should build with minimal features too. +cargo build --no-default-features +cargo test --no-default-features + +# Each isolated feature should also work everywhere. +for feature in rustc-serialize serde; do + cargo build --verbose --no-default-features --features="$feature" + cargo test --verbose --no-default-features --features="$feature" +done + +# Downgrade serde and build test the 0.7.0 channel as well +cargo update -p serde --precise 0.7.0 +cargo build --verbose --no-default-features --features "serde" diff -Nru cargo-0.25.0/vendor/num-complex-0.1.43/LICENSE-APACHE cargo-0.26.0/vendor/num-complex-0.1.43/LICENSE-APACHE --- cargo-0.25.0/vendor/num-complex-0.1.43/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.43/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/num-complex-0.1.43/LICENSE-MIT cargo-0.26.0/vendor/num-complex-0.1.43/LICENSE-MIT --- cargo-0.25.0/vendor/num-complex-0.1.43/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.43/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/num-complex-0.1.43/README.md cargo-0.26.0/vendor/num-complex-0.1.43/README.md --- cargo-0.25.0/vendor/num-complex-0.1.43/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.43/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,31 @@ +# num-complex + +[![crate](https://img.shields.io/crates/v/num-complex.svg)](https://crates.io/crates/num-complex) +[![documentation](https://docs.rs/num-complex/badge.svg)](https://docs.rs/num-complex) +![minimum rustc 1.8](https://img.shields.io/badge/rustc-1.8+-red.svg) +[![Travis status](https://travis-ci.org/rust-num/num-complex.svg?branch=master)](https://travis-ci.org/rust-num/num-complex) + +`Complex` numbers for Rust. + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +num-complex = "0.1" +``` + +and this to your crate root: + +```rust +extern crate num_complex; +``` + +## Releases + +Release notes are available in [RELEASES.md](RELEASES.md). + +## Compatibility + +The `num-complex` crate is tested for rustc 1.8 and greater. diff -Nru cargo-0.25.0/vendor/num-complex-0.1.43/RELEASES.md cargo-0.26.0/vendor/num-complex-0.1.43/RELEASES.md --- cargo-0.25.0/vendor/num-complex-0.1.43/RELEASES.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.43/RELEASES.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,24 @@ +# Release 0.1.43 + +- [Fix a usage typo in README.md][20]. + +**Contributors**: @shingtaklam1324 + +[20]: https://github.com/rust-num/num-complex/pull/20 + + +# Release 0.1.42 + +- [num-complex now has its own source repository][num-356] at [rust-num/num-complex][home]. + +**Contributors**: @cuviper + +[home]: https://github.com/rust-num/num-complex +[num-356]: https://github.com/rust-num/num/pull/356 + + +# Prior releases + +No prior release notes were kept. Thanks all the same to the many +contributors that have made this crate what it is! + diff -Nru cargo-0.25.0/vendor/num-complex-0.1.43/src/lib.rs cargo-0.26.0/vendor/num-complex-0.1.43/src/lib.rs --- cargo-0.25.0/vendor/num-complex-0.1.43/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.43/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1901 @@ +// Copyright 2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Complex numbers. +//! +//! ## Compatibility +//! +//! The `num-complex` crate is tested for rustc 1.8 and greater. + +#![doc(html_root_url = "https://docs.rs/num-complex/0.1")] + +extern crate num_traits as traits; + +#[cfg(feature = "rustc-serialize")] +extern crate rustc_serialize; + +#[cfg(feature = "serde")] +extern crate serde; + +use std::error::Error; +use std::fmt; +#[cfg(test)] +use std::hash; +use std::ops::{Add, Div, Mul, Neg, Sub, Rem}; +use std::str::FromStr; + +use traits::{Zero, One, Num, Float}; + +// FIXME #1284: handle complex NaN & infinity etc. This +// probably doesn't map to C's _Complex correctly. + +/// A complex number in Cartesian form. +/// +/// ## Representation and Foreign Function Interface Compatibility +/// +/// `Complex` is memory layout compatible with an array `[T; 2]`. +/// +/// Note that `Complex` where F is a floating point type is **only** memory +/// layout compatible with C's complex types, **not** necessarily calling +/// convention compatible. This means that for FFI you can only pass +/// `Complex` behind a pointer, not as a value. +/// +/// ## Examples +/// +/// Example of extern function declaration. +/// +/// ``` +/// use num_complex::Complex; +/// use std::os::raw::c_int; +/// +/// extern "C" { +/// fn zaxpy_(n: *const c_int, alpha: *const Complex, +/// x: *const Complex, incx: *const c_int, +/// y: *mut Complex, incy: *const c_int); +/// } +/// ``` +#[derive(PartialEq, Eq, Copy, Clone, Hash, Debug, Default)] +#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))] +#[repr(C)] +pub struct Complex { + /// Real portion of the complex number + pub re: T, + /// Imaginary portion of the complex number + pub im: T +} + +pub type Complex32 = Complex; +pub type Complex64 = Complex; + +impl Complex { + /// Create a new Complex + #[inline] + pub fn new(re: T, im: T) -> Complex { + Complex { re: re, im: im } + } + + /// Returns imaginary unit + #[inline] + pub fn i() -> Complex { + Self::new(T::zero(), T::one()) + } + + /// Returns the square of the norm (since `T` doesn't necessarily + /// have a sqrt function), i.e. `re^2 + im^2`. + #[inline] + pub fn norm_sqr(&self) -> T { + self.re.clone() * self.re.clone() + self.im.clone() * self.im.clone() + } + + /// Multiplies `self` by the scalar `t`. + #[inline] + pub fn scale(&self, t: T) -> Complex { + Complex::new(self.re.clone() * t.clone(), self.im.clone() * t) + } + + /// Divides `self` by the scalar `t`. + #[inline] + pub fn unscale(&self, t: T) -> Complex { + Complex::new(self.re.clone() / t.clone(), self.im.clone() / t) + } +} + +impl> Complex { + /// Returns the complex conjugate. i.e. `re - i im` + #[inline] + pub fn conj(&self) -> Complex { + Complex::new(self.re.clone(), -self.im.clone()) + } + + /// Returns `1/self` + #[inline] + pub fn inv(&self) -> Complex { + let norm_sqr = self.norm_sqr(); + Complex::new(self.re.clone() / norm_sqr.clone(), + -self.im.clone() / norm_sqr) + } +} + +impl Complex { + /// Calculate |self| + #[inline] + pub fn norm(&self) -> T { + self.re.hypot(self.im) + } + /// Calculate the principal Arg of self. + #[inline] + pub fn arg(&self) -> T { + self.im.atan2(self.re) + } + /// Convert to polar form (r, theta), such that + /// `self = r * exp(i * theta)` + #[inline] + pub fn to_polar(&self) -> (T, T) { + (self.norm(), self.arg()) + } + /// Convert a polar representation into a complex number. + #[inline] + pub fn from_polar(r: &T, theta: &T) -> Complex { + Complex::new(*r * theta.cos(), *r * theta.sin()) + } + + /// Computes `e^(self)`, where `e` is the base of the natural logarithm. + #[inline] + pub fn exp(&self) -> Complex { + // formula: e^(a + bi) = e^a (cos(b) + i*sin(b)) + // = from_polar(e^a, b) + Complex::from_polar(&self.re.exp(), &self.im) + } + + /// Computes the principal value of natural logarithm of `self`. + /// + /// This function has one branch cut: + /// + /// * `(-∞, 0]`, continuous from above. + /// + /// The branch satisfies `-π ≤ arg(ln(z)) ≤ π`. + #[inline] + pub fn ln(&self) -> Complex { + // formula: ln(z) = ln|z| + i*arg(z) + let (r, theta) = self.to_polar(); + Complex::new(r.ln(), theta) + } + + /// Computes the principal value of the square root of `self`. + /// + /// This function has one branch cut: + /// + /// * `(-∞, 0)`, continuous from above. + /// + /// The branch satisfies `-π/2 ≤ arg(sqrt(z)) ≤ π/2`. + #[inline] + pub fn sqrt(&self) -> Complex { + // formula: sqrt(r e^(it)) = sqrt(r) e^(it/2) + let two = T::one() + T::one(); + let (r, theta) = self.to_polar(); + Complex::from_polar(&(r.sqrt()), &(theta/two)) + } + + /// Raises `self` to a floating point power. + #[inline] + pub fn powf(&self, exp: T) -> Complex { + // formula: x^y = (ρ e^(i θ))^y = ρ^y e^(i θ y) + // = from_polar(ρ^y, θ y) + let (r, theta) = self.to_polar(); + Complex::from_polar(&r.powf(exp), &(theta*exp)) + } + + /// Returns the logarithm of `self` with respect to an arbitrary base. + #[inline] + pub fn log(&self, base: T) -> Complex { + // formula: log_y(x) = log_y(ρ e^(i θ)) + // = log_y(ρ) + log_y(e^(i θ)) = log_y(ρ) + ln(e^(i θ)) / ln(y) + // = log_y(ρ) + i θ / ln(y) + let (r, theta) = self.to_polar(); + Complex::new(r.log(base), theta / base.ln()) + } + + /// Raises `self` to a complex power. + #[inline] + pub fn powc(&self, exp: Complex) -> Complex { + // formula: x^y = (a + i b)^(c + i d) + // = (ρ e^(i θ))^c (ρ e^(i θ))^(i d) + // where ρ=|x| and θ=arg(x) + // = ρ^c e^(−d θ) e^(i c θ) ρ^(i d) + // = p^c e^(−d θ) (cos(c θ) + // + i sin(c θ)) (cos(d ln(ρ)) + i sin(d ln(ρ))) + // = p^c e^(−d θ) ( + // cos(c θ) cos(d ln(ρ)) − sin(c θ) sin(d ln(ρ)) + // + i(cos(c θ) sin(d ln(ρ)) + sin(c θ) cos(d ln(ρ)))) + // = p^c e^(−d θ) (cos(c θ + d ln(ρ)) + i sin(c θ + d ln(ρ))) + // = from_polar(p^c e^(−d θ), c θ + d ln(ρ)) + let (r, theta) = self.to_polar(); + Complex::from_polar( + &(r.powf(exp.re) * (-exp.im * theta).exp()), + &(exp.re * theta + exp.im * r.ln())) + } + + /// Raises a floating point number to the complex power `self`. + #[inline] + pub fn expf(&self, base: T) -> Complex { + // formula: x^(a+bi) = x^a x^bi = x^a e^(b ln(x) i) + // = from_polar(x^a, b ln(x)) + Complex::from_polar(&base.powf(self.re), &(self.im * base.ln())) + } + + /// Computes the sine of `self`. + #[inline] + pub fn sin(&self) -> Complex { + // formula: sin(a + bi) = sin(a)cosh(b) + i*cos(a)sinh(b) + Complex::new(self.re.sin() * self.im.cosh(), self.re.cos() * self.im.sinh()) + } + + /// Computes the cosine of `self`. + #[inline] + pub fn cos(&self) -> Complex { + // formula: cos(a + bi) = cos(a)cosh(b) - i*sin(a)sinh(b) + Complex::new(self.re.cos() * self.im.cosh(), -self.re.sin() * self.im.sinh()) + } + + /// Computes the tangent of `self`. + #[inline] + pub fn tan(&self) -> Complex { + // formula: tan(a + bi) = (sin(2a) + i*sinh(2b))/(cos(2a) + cosh(2b)) + let (two_re, two_im) = (self.re + self.re, self.im + self.im); + Complex::new(two_re.sin(), two_im.sinh()).unscale(two_re.cos() + two_im.cosh()) + } + + /// Computes the principal value of the inverse sine of `self`. + /// + /// This function has two branch cuts: + /// + /// * `(-∞, -1)`, continuous from above. + /// * `(1, ∞)`, continuous from below. + /// + /// The branch satisfies `-π/2 ≤ Re(asin(z)) ≤ π/2`. + #[inline] + pub fn asin(&self) -> Complex { + // formula: arcsin(z) = -i ln(sqrt(1-z^2) + iz) + let i = Complex::::i(); + -i*((Complex::::one() - self*self).sqrt() + i*self).ln() + } + + /// Computes the principal value of the inverse cosine of `self`. + /// + /// This function has two branch cuts: + /// + /// * `(-∞, -1)`, continuous from above. + /// * `(1, ∞)`, continuous from below. + /// + /// The branch satisfies `0 ≤ Re(acos(z)) ≤ π`. + #[inline] + pub fn acos(&self) -> Complex { + // formula: arccos(z) = -i ln(i sqrt(1-z^2) + z) + let i = Complex::::i(); + -i*(i*(Complex::::one() - self*self).sqrt() + self).ln() + } + + /// Computes the principal value of the inverse tangent of `self`. + /// + /// This function has two branch cuts: + /// + /// * `(-∞i, -i]`, continuous from the left. + /// * `[i, ∞i)`, continuous from the right. + /// + /// The branch satisfies `-π/2 ≤ Re(atan(z)) ≤ π/2`. + #[inline] + pub fn atan(&self) -> Complex { + // formula: arctan(z) = (ln(1+iz) - ln(1-iz))/(2i) + let i = Complex::::i(); + let one = Complex::::one(); + let two = one + one; + if *self == i { + return Complex::new(T::zero(), T::infinity()); + } + else if *self == -i { + return Complex::new(T::zero(), -T::infinity()); + } + ((one + i * self).ln() - (one - i * self).ln()) / (two * i) + } + + /// Computes the hyperbolic sine of `self`. + #[inline] + pub fn sinh(&self) -> Complex { + // formula: sinh(a + bi) = sinh(a)cos(b) + i*cosh(a)sin(b) + Complex::new(self.re.sinh() * self.im.cos(), self.re.cosh() * self.im.sin()) + } + + /// Computes the hyperbolic cosine of `self`. + #[inline] + pub fn cosh(&self) -> Complex { + // formula: cosh(a + bi) = cosh(a)cos(b) + i*sinh(a)sin(b) + Complex::new(self.re.cosh() * self.im.cos(), self.re.sinh() * self.im.sin()) + } + + /// Computes the hyperbolic tangent of `self`. + #[inline] + pub fn tanh(&self) -> Complex { + // formula: tanh(a + bi) = (sinh(2a) + i*sin(2b))/(cosh(2a) + cos(2b)) + let (two_re, two_im) = (self.re + self.re, self.im + self.im); + Complex::new(two_re.sinh(), two_im.sin()).unscale(two_re.cosh() + two_im.cos()) + } + + /// Computes the principal value of inverse hyperbolic sine of `self`. + /// + /// This function has two branch cuts: + /// + /// * `(-∞i, -i)`, continuous from the left. + /// * `(i, ∞i)`, continuous from the right. + /// + /// The branch satisfies `-π/2 ≤ Im(asinh(z)) ≤ π/2`. + #[inline] + pub fn asinh(&self) -> Complex { + // formula: arcsinh(z) = ln(z + sqrt(1+z^2)) + let one = Complex::::one(); + (self + (one + self * self).sqrt()).ln() + } + + /// Computes the principal value of inverse hyperbolic cosine of `self`. + /// + /// This function has one branch cut: + /// + /// * `(-∞, 1)`, continuous from above. + /// + /// The branch satisfies `-π ≤ Im(acosh(z)) ≤ π` and `0 ≤ Re(acosh(z)) < ∞`. + #[inline] + pub fn acosh(&self) -> Complex { + // formula: arccosh(z) = 2 ln(sqrt((z+1)/2) + sqrt((z-1)/2)) + let one = Complex::one(); + let two = one + one; + two * (((self + one)/two).sqrt() + ((self - one)/two).sqrt()).ln() + } + + /// Computes the principal value of inverse hyperbolic tangent of `self`. + /// + /// This function has two branch cuts: + /// + /// * `(-∞, -1]`, continuous from above. + /// * `[1, ∞)`, continuous from below. + /// + /// The branch satisfies `-π/2 ≤ Im(atanh(z)) ≤ π/2`. + #[inline] + pub fn atanh(&self) -> Complex { + // formula: arctanh(z) = (ln(1+z) - ln(1-z))/2 + let one = Complex::one(); + let two = one + one; + if *self == one { + return Complex::new(T::infinity(), T::zero()); + } + else if *self == -one { + return Complex::new(-T::infinity(), T::zero()); + } + ((one + self).ln() - (one - self).ln()) / two + } + + /// Checks if the given complex number is NaN + #[inline] + pub fn is_nan(self) -> bool { + self.re.is_nan() || self.im.is_nan() + } + + /// Checks if the given complex number is infinite + #[inline] + pub fn is_infinite(self) -> bool { + !self.is_nan() && (self.re.is_infinite() || self.im.is_infinite()) + } + + /// Checks if the given complex number is finite + #[inline] + pub fn is_finite(self) -> bool { + self.re.is_finite() && self.im.is_finite() + } + + /// Checks if the given complex number is normal + #[inline] + pub fn is_normal(self) -> bool { + self.re.is_normal() && self.im.is_normal() + } +} + +impl From for Complex { + #[inline] + fn from(re: T) -> Complex { + Complex { re: re, im: T::zero() } + } +} + +impl<'a, T: Clone + Num> From<&'a T> for Complex { + #[inline] + fn from(re: &T) -> Complex { + From::from(re.clone()) + } +} + +macro_rules! forward_ref_ref_binop { + (impl $imp:ident, $method:ident) => { + impl<'a, 'b, T: Clone + Num> $imp<&'b Complex> for &'a Complex { + type Output = Complex; + + #[inline] + fn $method(self, other: &Complex) -> Complex { + self.clone().$method(other.clone()) + } + } + } +} + +macro_rules! forward_ref_val_binop { + (impl $imp:ident, $method:ident) => { + impl<'a, T: Clone + Num> $imp> for &'a Complex { + type Output = Complex; + + #[inline] + fn $method(self, other: Complex) -> Complex { + self.clone().$method(other) + } + } + } +} + +macro_rules! forward_val_ref_binop { + (impl $imp:ident, $method:ident) => { + impl<'a, T: Clone + Num> $imp<&'a Complex> for Complex { + type Output = Complex; + + #[inline] + fn $method(self, other: &Complex) -> Complex { + self.$method(other.clone()) + } + } + } +} + +macro_rules! forward_all_binop { + (impl $imp:ident, $method:ident) => { + forward_ref_ref_binop!(impl $imp, $method); + forward_ref_val_binop!(impl $imp, $method); + forward_val_ref_binop!(impl $imp, $method); + }; +} + +/* arithmetic */ +forward_all_binop!(impl Add, add); + +// (a + i b) + (c + i d) == (a + c) + i (b + d) +impl Add> for Complex { + type Output = Complex; + + #[inline] + fn add(self, other: Complex) -> Complex { + Complex::new(self.re + other.re, self.im + other.im) + } +} + +forward_all_binop!(impl Sub, sub); + +// (a + i b) - (c + i d) == (a - c) + i (b - d) +impl Sub> for Complex { + type Output = Complex; + + #[inline] + fn sub(self, other: Complex) -> Complex { + Complex::new(self.re - other.re, self.im - other.im) + } +} + +forward_all_binop!(impl Mul, mul); + +// (a + i b) * (c + i d) == (a*c - b*d) + i (a*d + b*c) +impl Mul> for Complex { + type Output = Complex; + + #[inline] + fn mul(self, other: Complex) -> Complex { + let re = self.re.clone() * other.re.clone() - self.im.clone() * other.im.clone(); + let im = self.re * other.im + self.im * other.re; + Complex::new(re, im) + } +} + +forward_all_binop!(impl Div, div); + +// (a + i b) / (c + i d) == [(a + i b) * (c - i d)] / (c*c + d*d) +// == [(a*c + b*d) / (c*c + d*d)] + i [(b*c - a*d) / (c*c + d*d)] +impl Div> for Complex { + type Output = Complex; + + #[inline] + fn div(self, other: Complex) -> Complex { + let norm_sqr = other.norm_sqr(); + let re = self.re.clone() * other.re.clone() + self.im.clone() * other.im.clone(); + let im = self.im * other.re - self.re * other.im; + Complex::new(re / norm_sqr.clone(), im / norm_sqr) + } +} + +forward_all_binop!(impl Rem, rem); + +// Attempts to identify the gaussian integer whose product with `modulus` +// is closest to `self`. +impl Rem> for Complex { + type Output = Complex; + + #[inline] + fn rem(self, modulus: Complex) -> Self { + let Complex { re, im } = self.clone() / modulus.clone(); + // This is the gaussian integer corresponding to the true ratio + // rounded towards zero. + let (re0, im0) = (re.clone() - re % T::one(), im.clone() - im % T::one()); + self - modulus * Complex::new(re0, im0) + } +} + +// Op Assign + +mod opassign { + use std::ops::{AddAssign, SubAssign, MulAssign, DivAssign, RemAssign}; + + use traits::NumAssign; + + use Complex; + + impl AddAssign for Complex { + fn add_assign(&mut self, other: Complex) { + self.re += other.re; + self.im += other.im; + } + } + + impl SubAssign for Complex { + fn sub_assign(&mut self, other: Complex) { + self.re -= other.re; + self.im -= other.im; + } + } + + impl MulAssign for Complex { + fn mul_assign(&mut self, other: Complex) { + *self = self.clone() * other; + } + } + + impl DivAssign for Complex { + fn div_assign(&mut self, other: Complex) { + *self = self.clone() / other; + } + } + + impl RemAssign for Complex { + fn rem_assign(&mut self, other: Complex) { + *self = self.clone() % other; + } + } + + impl AddAssign for Complex { + fn add_assign(&mut self, other: T) { + self.re += other; + } + } + + impl SubAssign for Complex { + fn sub_assign(&mut self, other: T) { + self.re -= other; + } + } + + impl MulAssign for Complex { + fn mul_assign(&mut self, other: T) { + self.re *= other.clone(); + self.im *= other; + } + } + + impl DivAssign for Complex { + fn div_assign(&mut self, other: T) { + self.re /= other.clone(); + self.im /= other; + } + } + + impl RemAssign for Complex { + fn rem_assign(&mut self, other: T) { + *self = self.clone() % other; + } + } + + macro_rules! forward_op_assign { + (impl $imp:ident, $method:ident) => { + impl<'a, T: Clone + NumAssign> $imp<&'a Complex> for Complex { + #[inline] + fn $method(&mut self, other: &Complex) { + self.$method(other.clone()) + } + } + impl<'a, T: Clone + NumAssign> $imp<&'a T> for Complex { + #[inline] + fn $method(&mut self, other: &T) { + self.$method(other.clone()) + } + } + } + } + + forward_op_assign!(impl AddAssign, add_assign); + forward_op_assign!(impl SubAssign, sub_assign); + forward_op_assign!(impl MulAssign, mul_assign); + forward_op_assign!(impl DivAssign, div_assign); + + impl<'a, T: Clone + NumAssign> RemAssign<&'a Complex> for Complex { + #[inline] + fn rem_assign(&mut self, other: &Complex) { + self.rem_assign(other.clone()) + } + } + impl<'a, T: Clone + NumAssign> RemAssign<&'a T> for Complex { + #[inline] + fn rem_assign(&mut self, other: &T) { + self.rem_assign(other.clone()) + } + } +} + +impl> Neg for Complex { + type Output = Complex; + + #[inline] + fn neg(self) -> Complex { + Complex::new(-self.re, -self.im) + } +} + +impl<'a, T: Clone + Num + Neg> Neg for &'a Complex { + type Output = Complex; + + #[inline] + fn neg(self) -> Complex { + -self.clone() + } +} + +macro_rules! real_arithmetic { + (@forward $imp:ident::$method:ident for $($real:ident),*) => ( + impl<'a, T: Clone + Num> $imp<&'a T> for Complex { + type Output = Complex; + + #[inline] + fn $method(self, other: &T) -> Complex { + self.$method(other.clone()) + } + } + impl<'a, T: Clone + Num> $imp for &'a Complex { + type Output = Complex; + + #[inline] + fn $method(self, other: T) -> Complex { + self.clone().$method(other) + } + } + impl<'a, 'b, T: Clone + Num> $imp<&'a T> for &'b Complex { + type Output = Complex; + + #[inline] + fn $method(self, other: &T) -> Complex { + self.clone().$method(other.clone()) + } + } + $( + impl<'a> $imp<&'a Complex<$real>> for $real { + type Output = Complex<$real>; + + #[inline] + fn $method(self, other: &Complex<$real>) -> Complex<$real> { + self.$method(other.clone()) + } + } + impl<'a> $imp> for &'a $real { + type Output = Complex<$real>; + + #[inline] + fn $method(self, other: Complex<$real>) -> Complex<$real> { + self.clone().$method(other) + } + } + impl<'a, 'b> $imp<&'a Complex<$real>> for &'b $real { + type Output = Complex<$real>; + + #[inline] + fn $method(self, other: &Complex<$real>) -> Complex<$real> { + self.clone().$method(other.clone()) + } + } + )* + ); + ($($real:ident),*) => ( + real_arithmetic!(@forward Add::add for $($real),*); + real_arithmetic!(@forward Sub::sub for $($real),*); + real_arithmetic!(@forward Mul::mul for $($real),*); + real_arithmetic!(@forward Div::div for $($real),*); + real_arithmetic!(@forward Rem::rem for $($real),*); + + $( + impl Add> for $real { + type Output = Complex<$real>; + + #[inline] + fn add(self, other: Complex<$real>) -> Complex<$real> { + Complex::new(self + other.re, other.im) + } + } + + impl Sub> for $real { + type Output = Complex<$real>; + + #[inline] + fn sub(self, other: Complex<$real>) -> Complex<$real> { + Complex::new(self - other.re, $real::zero() - other.im) + } + } + + impl Mul> for $real { + type Output = Complex<$real>; + + #[inline] + fn mul(self, other: Complex<$real>) -> Complex<$real> { + Complex::new(self * other.re, self * other.im) + } + } + + impl Div> for $real { + type Output = Complex<$real>; + + #[inline] + fn div(self, other: Complex<$real>) -> Complex<$real> { + // a / (c + i d) == [a * (c - i d)] / (c*c + d*d) + let norm_sqr = other.norm_sqr(); + Complex::new(self * other.re / norm_sqr.clone(), + $real::zero() - self * other.im / norm_sqr) + } + } + + impl Rem> for $real { + type Output = Complex<$real>; + + #[inline] + fn rem(self, other: Complex<$real>) -> Complex<$real> { + Complex::new(self, Self::zero()) % other + } + } + )* + ); +} + +impl Add for Complex { + type Output = Complex; + + #[inline] + fn add(self, other: T) -> Complex { + Complex::new(self.re + other, self.im) + } +} + +impl Sub for Complex { + type Output = Complex; + + #[inline] + fn sub(self, other: T) -> Complex { + Complex::new(self.re - other, self.im) + } +} + +impl Mul for Complex { + type Output = Complex; + + #[inline] + fn mul(self, other: T) -> Complex { + Complex::new(self.re * other.clone(), self.im * other) + } +} + +impl Div for Complex { + type Output = Complex; + + #[inline] + fn div(self, other: T) -> Complex { + Complex::new(self.re / other.clone(), self.im / other) + } +} + +impl Rem for Complex { + type Output = Complex; + + #[inline] + fn rem(self, other: T) -> Complex { + self % Complex::new(other, T::zero()) + } +} + +real_arithmetic!(usize, u8, u16, u32, u64, isize, i8, i16, i32, i64, f32, f64); + +/* constants */ +impl Zero for Complex { + #[inline] + fn zero() -> Complex { + Complex::new(Zero::zero(), Zero::zero()) + } + + #[inline] + fn is_zero(&self) -> bool { + self.re.is_zero() && self.im.is_zero() + } +} + +impl One for Complex { + #[inline] + fn one() -> Complex { + Complex::new(One::one(), Zero::zero()) + } +} + +macro_rules! write_complex { + ($f:ident, $t:expr, $prefix:expr, $re:expr, $im:expr, $T:ident) => {{ + let abs_re = if $re < Zero::zero() { $T::zero() - $re.clone() } else { $re.clone() }; + let abs_im = if $im < Zero::zero() { $T::zero() - $im.clone() } else { $im.clone() }; + + let real: String; + let imag: String; + + if let Some(prec) = $f.precision() { + real = format!(concat!("{:.1$", $t, "}"), abs_re, prec); + imag = format!(concat!("{:.1$", $t, "}"), abs_im, prec); + } + else { + real = format!(concat!("{:", $t, "}"), abs_re); + imag = format!(concat!("{:", $t, "}"), abs_im); + } + + let prefix = if $f.alternate() { $prefix } else { "" }; + let sign = if $re < Zero::zero() { + "-" + } else if $f.sign_plus() { + "+" + } else { + "" + }; + + let complex = if $im < Zero::zero() { + format!("{}{pre}{re}-{pre}{im}i", sign, re=real, im=imag, pre=prefix) + } + else { + format!("{}{pre}{re}+{pre}{im}i", sign, re=real, im=imag, pre=prefix) + }; + + if let Some(width) = $f.width() { + write!($f, "{0: >1$}", complex, width) + } + else { + write!($f, "{}", complex) + } + }} +} + +/* string conversions */ +impl fmt::Display for Complex where + T: fmt::Display + Num + PartialOrd + Clone +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write_complex!(f, "", "", self.re, self.im, T) + } +} + +impl fmt::LowerExp for Complex where + T: fmt::LowerExp + Num + PartialOrd + Clone +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write_complex!(f, "e", "", self.re, self.im, T) + } +} + +impl fmt::UpperExp for Complex where + T: fmt::UpperExp + Num + PartialOrd + Clone +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write_complex!(f, "E", "", self.re, self.im, T) + } +} + +impl fmt::LowerHex for Complex where + T: fmt::LowerHex + Num + PartialOrd + Clone +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write_complex!(f, "x", "0x", self.re, self.im, T) + } +} + +impl fmt::UpperHex for Complex where + T: fmt::UpperHex + Num + PartialOrd + Clone +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write_complex!(f, "X", "0x", self.re, self.im, T) + } +} + +impl fmt::Octal for Complex where + T: fmt::Octal + Num + PartialOrd + Clone +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write_complex!(f, "o", "0o", self.re, self.im, T) + } +} + +impl fmt::Binary for Complex where + T: fmt::Binary + Num + PartialOrd + Clone +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write_complex!(f, "b", "0b", self.re, self.im, T) + } +} + +fn from_str_generic(s: &str, from: F) -> Result, ParseComplexError> + where F: Fn(&str) -> Result, T: Clone + Num +{ + let imag = match s.rfind('j') { + None => 'i', + _ => 'j' + }; + + let mut b = String::with_capacity(s.len()); + let mut first = true; + + let char_indices = s.char_indices(); + let mut pc = ' '; + let mut split_index = s.len(); + + for (i, cc) in char_indices { + if cc == '+' && pc != 'e' && pc != 'E' && i > 0 { + // ignore '+' if part of an exponent + if first { + split_index = i; + first = false; + } + // don't carry '+' over into b + pc = ' '; + continue; + } else if cc == '-' && pc != 'e' && pc != 'E' && i > 0 { + // ignore '-' if part of an exponent or begins the string + if first { + split_index = i; + first = false; + } + // DO carry '-' over into b + } + + if pc == '-' && cc == ' ' && !first { + // ignore whitespace between minus sign and next number + continue; + } + + if !first { + b.push(cc); + } + pc = cc; + } + + // split off real and imaginary parts, trim whitespace + let (a, _) = s.split_at(split_index); + let a = a.trim_right(); + let mut b = b.trim_left(); + // input was either pure real or pure imaginary + if b.is_empty() { + b = match a.ends_with(imag) { + false => "0i", + true => "0" + }; + } + + let re; + let im; + if a.ends_with(imag) { + im = a; re = b; + } else if b.ends_with(imag) { + re = a; im = b; + } else { + return Err(ParseComplexError::new()); + } + + // parse re + let re = try!(from(re).map_err(ParseComplexError::from_error)); + + // pop imaginary unit off + let mut im = &im[..im.len()-1]; + // handle im == "i" or im == "-i" + if im.is_empty() || im == "+" { + im = "1"; + } else if im == "-" { + im = "-1"; + } + + // parse im + let im = try!(from(im).map_err(ParseComplexError::from_error)); + + Ok(Complex::new(re, im)) +} + +impl FromStr for Complex where + T: FromStr + Num + Clone +{ + type Err = ParseComplexError; + + /// Parses `a +/- bi`; `ai +/- b`; `a`; or `bi` where `a` and `b` are of type `T` + fn from_str(s: &str) -> Result + { + from_str_generic(s, T::from_str) + } +} + +impl Num for Complex { + type FromStrRadixErr = ParseComplexError; + + /// Parses `a +/- bi`; `ai +/- b`; `a`; or `bi` where `a` and `b` are of type `T` + fn from_str_radix(s: &str, radix: u32) -> Result + { + from_str_generic(s, |x| -> Result { + T::from_str_radix(x, radix) }) + } +} + +#[cfg(feature = "serde")] +impl serde::Serialize for Complex + where T: serde::Serialize +{ + fn serialize(&self, serializer: &mut S) -> Result<(), S::Error> where + S: serde::Serializer + { + (&self.re, &self.im).serialize(serializer) + } +} + +#[cfg(feature = "serde")] +impl serde::Deserialize for Complex where + T: serde::Deserialize + Num + Clone +{ + fn deserialize(deserializer: &mut D) -> Result where + D: serde::Deserializer, + { + let (re, im) = try!(serde::Deserialize::deserialize(deserializer)); + Ok(Complex::new(re, im)) + } +} + +#[derive(Debug, PartialEq)] +pub struct ParseComplexError +{ + kind: ComplexErrorKind, +} + +#[derive(Debug, PartialEq)] +enum ComplexErrorKind +{ + ParseError(E), + ExprError +} + +impl ParseComplexError +{ + fn new() -> Self { + ParseComplexError { + kind: ComplexErrorKind::ExprError, + } + } + + fn from_error(error: E) -> Self { + ParseComplexError { + kind: ComplexErrorKind::ParseError(error), + } + } +} + +impl Error for ParseComplexError +{ + fn description(&self) -> &str { + match self.kind { + ComplexErrorKind::ParseError(ref e) => e.description(), + ComplexErrorKind::ExprError => "invalid or unsupported complex expression" + } + } +} + +impl fmt::Display for ParseComplexError +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.description().fmt(f) + } +} + +#[cfg(test)] +fn hash(x: &T) -> u64 { + use std::hash::{BuildHasher, Hasher}; + use std::collections::hash_map::RandomState; + let mut hasher = ::Hasher::new(); + x.hash(&mut hasher); + hasher.finish() +} + +#[cfg(test)] +mod test { + #![allow(non_upper_case_globals)] + + use super::{Complex64, Complex}; + use std::f64; + use std::str::FromStr; + + use traits::{Zero, One, Float, Num}; + + pub const _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 }; + pub const _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 }; + pub const _1_1i : Complex64 = Complex { re: 1.0, im: 1.0 }; + pub const _0_1i : Complex64 = Complex { re: 0.0, im: 1.0 }; + pub const _neg1_1i : Complex64 = Complex { re: -1.0, im: 1.0 }; + pub const _05_05i : Complex64 = Complex { re: 0.5, im: 0.5 }; + pub const all_consts : [Complex64; 5] = [_0_0i, _1_0i, _1_1i, _neg1_1i, _05_05i]; + pub const _4_2i : Complex64 = Complex { re: 4.0, im: 2.0 }; + + #[test] + fn test_consts() { + // check our constants are what Complex::new creates + fn test(c : Complex64, r : f64, i: f64) { + assert_eq!(c, Complex::new(r,i)); + } + test(_0_0i, 0.0, 0.0); + test(_1_0i, 1.0, 0.0); + test(_1_1i, 1.0, 1.0); + test(_neg1_1i, -1.0, 1.0); + test(_05_05i, 0.5, 0.5); + + assert_eq!(_0_0i, Zero::zero()); + assert_eq!(_1_0i, One::one()); + } + + #[test] + #[cfg_attr(target_arch = "x86", ignore)] + // FIXME #7158: (maybe?) currently failing on x86. + fn test_norm() { + fn test(c: Complex64, ns: f64) { + assert_eq!(c.norm_sqr(), ns); + assert_eq!(c.norm(), ns.sqrt()) + } + test(_0_0i, 0.0); + test(_1_0i, 1.0); + test(_1_1i, 2.0); + test(_neg1_1i, 2.0); + test(_05_05i, 0.5); + } + + #[test] + fn test_scale_unscale() { + assert_eq!(_05_05i.scale(2.0), _1_1i); + assert_eq!(_1_1i.unscale(2.0), _05_05i); + for &c in all_consts.iter() { + assert_eq!(c.scale(2.0).unscale(2.0), c); + } + } + + #[test] + fn test_conj() { + for &c in all_consts.iter() { + assert_eq!(c.conj(), Complex::new(c.re, -c.im)); + assert_eq!(c.conj().conj(), c); + } + } + + #[test] + fn test_inv() { + assert_eq!(_1_1i.inv(), _05_05i.conj()); + assert_eq!(_1_0i.inv(), _1_0i.inv()); + } + + #[test] + #[should_panic] + fn test_divide_by_zero_natural() { + let n = Complex::new(2, 3); + let d = Complex::new(0, 0); + let _x = n / d; + } + + #[test] + fn test_inv_zero() { + // FIXME #20: should this really fail, or just NaN? + assert!(_0_0i.inv().is_nan()); + } + + #[test] + fn test_arg() { + fn test(c: Complex64, arg: f64) { + assert!((c.arg() - arg).abs() < 1.0e-6) + } + test(_1_0i, 0.0); + test(_1_1i, 0.25 * f64::consts::PI); + test(_neg1_1i, 0.75 * f64::consts::PI); + test(_05_05i, 0.25 * f64::consts::PI); + } + + #[test] + fn test_polar_conv() { + fn test(c: Complex64) { + let (r, theta) = c.to_polar(); + assert!((c - Complex::from_polar(&r, &theta)).norm() < 1e-6); + } + for &c in all_consts.iter() { test(c); } + } + + fn close(a: Complex64, b: Complex64) -> bool { + close_to_tol(a, b, 1e-10) + } + + fn close_to_tol(a: Complex64, b: Complex64, tol: f64) -> bool { + // returns true if a and b are reasonably close + (a == b) || (a-b).norm() < tol + } + + #[test] + fn test_exp() { + assert!(close(_1_0i.exp(), _1_0i.scale(f64::consts::E))); + assert!(close(_0_0i.exp(), _1_0i)); + assert!(close(_0_1i.exp(), Complex::new(1.0.cos(), 1.0.sin()))); + assert!(close(_05_05i.exp()*_05_05i.exp(), _1_1i.exp())); + assert!(close(_0_1i.scale(-f64::consts::PI).exp(), _1_0i.scale(-1.0))); + for &c in all_consts.iter() { + // e^conj(z) = conj(e^z) + assert!(close(c.conj().exp(), c.exp().conj())); + // e^(z + 2 pi i) = e^z + assert!(close(c.exp(), (c + _0_1i.scale(f64::consts::PI*2.0)).exp())); + } + } + + #[test] + fn test_ln() { + assert!(close(_1_0i.ln(), _0_0i)); + assert!(close(_0_1i.ln(), _0_1i.scale(f64::consts::PI/2.0))); + assert!(close(_0_0i.ln(), Complex::new(f64::neg_infinity(), 0.0))); + assert!(close((_neg1_1i * _05_05i).ln(), _neg1_1i.ln() + _05_05i.ln())); + for &c in all_consts.iter() { + // ln(conj(z() = conj(ln(z)) + assert!(close(c.conj().ln(), c.ln().conj())); + // for this branch, -pi <= arg(ln(z)) <= pi + assert!(-f64::consts::PI <= c.ln().arg() && c.ln().arg() <= f64::consts::PI); + } + } + + #[test] + fn test_powc() + { + let a = Complex::new(2.0, -3.0); + let b = Complex::new(3.0, 0.0); + assert!(close(a.powc(b), a.powf(b.re))); + assert!(close(b.powc(a), a.expf(b.re))); + let c = Complex::new(1.0 / 3.0, 0.1); + assert!(close_to_tol(a.powc(c), Complex::new(1.65826, -0.33502), 1e-5)); + } + + #[test] + fn test_powf() + { + let c = Complex::new(2.0, -1.0); + let r = c.powf(3.5); + assert!(close_to_tol(r, Complex::new(-0.8684746, -16.695934), 1e-5)); + } + + #[test] + fn test_log() + { + let c = Complex::new(2.0, -1.0); + let r = c.log(10.0); + assert!(close_to_tol(r, Complex::new(0.349485, -0.20135958), 1e-5)); + } + + #[test] + fn test_some_expf_cases() + { + let c = Complex::new(2.0, -1.0); + let r = c.expf(10.0); + assert!(close_to_tol(r, Complex::new(-66.82015, -74.39803), 1e-5)); + + let c = Complex::new(5.0, -2.0); + let r = c.expf(3.4); + assert!(close_to_tol(r, Complex::new(-349.25, -290.63), 1e-2)); + + let c = Complex::new(-1.5, 2.0 / 3.0); + let r = c.expf(1.0 / 3.0); + assert!(close_to_tol(r, Complex::new(3.8637, -3.4745), 1e-2)); + } + + #[test] + fn test_sqrt() { + assert!(close(_0_0i.sqrt(), _0_0i)); + assert!(close(_1_0i.sqrt(), _1_0i)); + assert!(close(Complex::new(-1.0, 0.0).sqrt(), _0_1i)); + assert!(close(Complex::new(-1.0, -0.0).sqrt(), _0_1i.scale(-1.0))); + assert!(close(_0_1i.sqrt(), _05_05i.scale(2.0.sqrt()))); + for &c in all_consts.iter() { + // sqrt(conj(z() = conj(sqrt(z)) + assert!(close(c.conj().sqrt(), c.sqrt().conj())); + // for this branch, -pi/2 <= arg(sqrt(z)) <= pi/2 + assert!(-f64::consts::PI/2.0 <= c.sqrt().arg() && c.sqrt().arg() <= f64::consts::PI/2.0); + // sqrt(z) * sqrt(z) = z + assert!(close(c.sqrt()*c.sqrt(), c)); + } + } + + #[test] + fn test_sin() { + assert!(close(_0_0i.sin(), _0_0i)); + assert!(close(_1_0i.scale(f64::consts::PI*2.0).sin(), _0_0i)); + assert!(close(_0_1i.sin(), _0_1i.scale(1.0.sinh()))); + for &c in all_consts.iter() { + // sin(conj(z)) = conj(sin(z)) + assert!(close(c.conj().sin(), c.sin().conj())); + // sin(-z) = -sin(z) + assert!(close(c.scale(-1.0).sin(), c.sin().scale(-1.0))); + } + } + + #[test] + fn test_cos() { + assert!(close(_0_0i.cos(), _1_0i)); + assert!(close(_1_0i.scale(f64::consts::PI*2.0).cos(), _1_0i)); + assert!(close(_0_1i.cos(), _1_0i.scale(1.0.cosh()))); + for &c in all_consts.iter() { + // cos(conj(z)) = conj(cos(z)) + assert!(close(c.conj().cos(), c.cos().conj())); + // cos(-z) = cos(z) + assert!(close(c.scale(-1.0).cos(), c.cos())); + } + } + + #[test] + fn test_tan() { + assert!(close(_0_0i.tan(), _0_0i)); + assert!(close(_1_0i.scale(f64::consts::PI/4.0).tan(), _1_0i)); + assert!(close(_1_0i.scale(f64::consts::PI).tan(), _0_0i)); + for &c in all_consts.iter() { + // tan(conj(z)) = conj(tan(z)) + assert!(close(c.conj().tan(), c.tan().conj())); + // tan(-z) = -tan(z) + assert!(close(c.scale(-1.0).tan(), c.tan().scale(-1.0))); + } + } + + #[test] + fn test_asin() { + assert!(close(_0_0i.asin(), _0_0i)); + assert!(close(_1_0i.asin(), _1_0i.scale(f64::consts::PI/2.0))); + assert!(close(_1_0i.scale(-1.0).asin(), _1_0i.scale(-f64::consts::PI/2.0))); + assert!(close(_0_1i.asin(), _0_1i.scale((1.0 + 2.0.sqrt()).ln()))); + for &c in all_consts.iter() { + // asin(conj(z)) = conj(asin(z)) + assert!(close(c.conj().asin(), c.asin().conj())); + // asin(-z) = -asin(z) + assert!(close(c.scale(-1.0).asin(), c.asin().scale(-1.0))); + // for this branch, -pi/2 <= asin(z).re <= pi/2 + assert!(-f64::consts::PI/2.0 <= c.asin().re && c.asin().re <= f64::consts::PI/2.0); + } + } + + #[test] + fn test_acos() { + assert!(close(_0_0i.acos(), _1_0i.scale(f64::consts::PI/2.0))); + assert!(close(_1_0i.acos(), _0_0i)); + assert!(close(_1_0i.scale(-1.0).acos(), _1_0i.scale(f64::consts::PI))); + assert!(close(_0_1i.acos(), Complex::new(f64::consts::PI/2.0, (2.0.sqrt() - 1.0).ln()))); + for &c in all_consts.iter() { + // acos(conj(z)) = conj(acos(z)) + assert!(close(c.conj().acos(), c.acos().conj())); + // for this branch, 0 <= acos(z).re <= pi + assert!(0.0 <= c.acos().re && c.acos().re <= f64::consts::PI); + } + } + + #[test] + fn test_atan() { + assert!(close(_0_0i.atan(), _0_0i)); + assert!(close(_1_0i.atan(), _1_0i.scale(f64::consts::PI/4.0))); + assert!(close(_1_0i.scale(-1.0).atan(), _1_0i.scale(-f64::consts::PI/4.0))); + assert!(close(_0_1i.atan(), Complex::new(0.0, f64::infinity()))); + for &c in all_consts.iter() { + // atan(conj(z)) = conj(atan(z)) + assert!(close(c.conj().atan(), c.atan().conj())); + // atan(-z) = -atan(z) + assert!(close(c.scale(-1.0).atan(), c.atan().scale(-1.0))); + // for this branch, -pi/2 <= atan(z).re <= pi/2 + assert!(-f64::consts::PI/2.0 <= c.atan().re && c.atan().re <= f64::consts::PI/2.0); + } + } + + #[test] + fn test_sinh() { + assert!(close(_0_0i.sinh(), _0_0i)); + assert!(close(_1_0i.sinh(), _1_0i.scale((f64::consts::E - 1.0/f64::consts::E)/2.0))); + assert!(close(_0_1i.sinh(), _0_1i.scale(1.0.sin()))); + for &c in all_consts.iter() { + // sinh(conj(z)) = conj(sinh(z)) + assert!(close(c.conj().sinh(), c.sinh().conj())); + // sinh(-z) = -sinh(z) + assert!(close(c.scale(-1.0).sinh(), c.sinh().scale(-1.0))); + } + } + + #[test] + fn test_cosh() { + assert!(close(_0_0i.cosh(), _1_0i)); + assert!(close(_1_0i.cosh(), _1_0i.scale((f64::consts::E + 1.0/f64::consts::E)/2.0))); + assert!(close(_0_1i.cosh(), _1_0i.scale(1.0.cos()))); + for &c in all_consts.iter() { + // cosh(conj(z)) = conj(cosh(z)) + assert!(close(c.conj().cosh(), c.cosh().conj())); + // cosh(-z) = cosh(z) + assert!(close(c.scale(-1.0).cosh(), c.cosh())); + } + } + + #[test] + fn test_tanh() { + assert!(close(_0_0i.tanh(), _0_0i)); + assert!(close(_1_0i.tanh(), _1_0i.scale((f64::consts::E.powi(2) - 1.0)/(f64::consts::E.powi(2) + 1.0)))); + assert!(close(_0_1i.tanh(), _0_1i.scale(1.0.tan()))); + for &c in all_consts.iter() { + // tanh(conj(z)) = conj(tanh(z)) + assert!(close(c.conj().tanh(), c.conj().tanh())); + // tanh(-z) = -tanh(z) + assert!(close(c.scale(-1.0).tanh(), c.tanh().scale(-1.0))); + } + } + + #[test] + fn test_asinh() { + assert!(close(_0_0i.asinh(), _0_0i)); + assert!(close(_1_0i.asinh(), _1_0i.scale(1.0 + 2.0.sqrt()).ln())); + assert!(close(_0_1i.asinh(), _0_1i.scale(f64::consts::PI/2.0))); + assert!(close(_0_1i.asinh().scale(-1.0), _0_1i.scale(-f64::consts::PI/2.0))); + for &c in all_consts.iter() { + // asinh(conj(z)) = conj(asinh(z)) + assert!(close(c.conj().asinh(), c.conj().asinh())); + // asinh(-z) = -asinh(z) + assert!(close(c.scale(-1.0).asinh(), c.asinh().scale(-1.0))); + // for this branch, -pi/2 <= asinh(z).im <= pi/2 + assert!(-f64::consts::PI/2.0 <= c.asinh().im && c.asinh().im <= f64::consts::PI/2.0); + } + } + + #[test] + fn test_acosh() { + assert!(close(_0_0i.acosh(), _0_1i.scale(f64::consts::PI/2.0))); + assert!(close(_1_0i.acosh(), _0_0i)); + assert!(close(_1_0i.scale(-1.0).acosh(), _0_1i.scale(f64::consts::PI))); + for &c in all_consts.iter() { + // acosh(conj(z)) = conj(acosh(z)) + assert!(close(c.conj().acosh(), c.conj().acosh())); + // for this branch, -pi <= acosh(z).im <= pi and 0 <= acosh(z).re + assert!(-f64::consts::PI <= c.acosh().im && c.acosh().im <= f64::consts::PI && 0.0 <= c.cosh().re); + } + } + + #[test] + fn test_atanh() { + assert!(close(_0_0i.atanh(), _0_0i)); + assert!(close(_0_1i.atanh(), _0_1i.scale(f64::consts::PI/4.0))); + assert!(close(_1_0i.atanh(), Complex::new(f64::infinity(), 0.0))); + for &c in all_consts.iter() { + // atanh(conj(z)) = conj(atanh(z)) + assert!(close(c.conj().atanh(), c.conj().atanh())); + // atanh(-z) = -atanh(z) + assert!(close(c.scale(-1.0).atanh(), c.atanh().scale(-1.0))); + // for this branch, -pi/2 <= atanh(z).im <= pi/2 + assert!(-f64::consts::PI/2.0 <= c.atanh().im && c.atanh().im <= f64::consts::PI/2.0); + } + } + + #[test] + fn test_exp_ln() { + for &c in all_consts.iter() { + // e^ln(z) = z + assert!(close(c.ln().exp(), c)); + } + } + + #[test] + fn test_trig_to_hyperbolic() { + for &c in all_consts.iter() { + // sin(iz) = i sinh(z) + assert!(close((_0_1i * c).sin(), _0_1i * c.sinh())); + // cos(iz) = cosh(z) + assert!(close((_0_1i * c).cos(), c.cosh())); + // tan(iz) = i tanh(z) + assert!(close((_0_1i * c).tan(), _0_1i * c.tanh())); + } + } + + #[test] + fn test_trig_identities() { + for &c in all_consts.iter() { + // tan(z) = sin(z)/cos(z) + assert!(close(c.tan(), c.sin()/c.cos())); + // sin(z)^2 + cos(z)^2 = 1 + assert!(close(c.sin()*c.sin() + c.cos()*c.cos(), _1_0i)); + + // sin(asin(z)) = z + assert!(close(c.asin().sin(), c)); + // cos(acos(z)) = z + assert!(close(c.acos().cos(), c)); + // tan(atan(z)) = z + // i and -i are branch points + if c != _0_1i && c != _0_1i.scale(-1.0) { + assert!(close(c.atan().tan(), c)); + } + + // sin(z) = (e^(iz) - e^(-iz))/(2i) + assert!(close(((_0_1i*c).exp() - (_0_1i*c).exp().inv())/_0_1i.scale(2.0), c.sin())); + // cos(z) = (e^(iz) + e^(-iz))/2 + assert!(close(((_0_1i*c).exp() + (_0_1i*c).exp().inv()).unscale(2.0), c.cos())); + // tan(z) = i (1 - e^(2iz))/(1 + e^(2iz)) + assert!(close(_0_1i * (_1_0i - (_0_1i*c).scale(2.0).exp())/(_1_0i + (_0_1i*c).scale(2.0).exp()), c.tan())); + } + } + + #[test] + fn test_hyperbolic_identites() { + for &c in all_consts.iter() { + // tanh(z) = sinh(z)/cosh(z) + assert!(close(c.tanh(), c.sinh()/c.cosh())); + // cosh(z)^2 - sinh(z)^2 = 1 + assert!(close(c.cosh()*c.cosh() - c.sinh()*c.sinh(), _1_0i)); + + // sinh(asinh(z)) = z + assert!(close(c.asinh().sinh(), c)); + // cosh(acosh(z)) = z + assert!(close(c.acosh().cosh(), c)); + // tanh(atanh(z)) = z + // 1 and -1 are branch points + if c != _1_0i && c != _1_0i.scale(-1.0) { + assert!(close(c.atanh().tanh(), c)); + } + + // sinh(z) = (e^z - e^(-z))/2 + assert!(close((c.exp() - c.exp().inv()).unscale(2.0), c.sinh())); + // cosh(z) = (e^z + e^(-z))/2 + assert!(close((c.exp() + c.exp().inv()).unscale(2.0), c.cosh())); + // tanh(z) = ( e^(2z) - 1)/(e^(2z) + 1) + assert!(close((c.scale(2.0).exp() - _1_0i)/(c.scale(2.0).exp() + _1_0i), c.tanh())); + } + } + + // Test both a + b and a += b + macro_rules! test_a_op_b { + ($a:ident + $b:expr, $answer:expr) => { + assert_eq!($a + $b, $answer); + assert_eq!({ let mut x = $a; x += $b; x}, $answer); + }; + ($a:ident - $b:expr, $answer:expr) => { + assert_eq!($a - $b, $answer); + assert_eq!({ let mut x = $a; x -= $b; x}, $answer); + }; + ($a:ident * $b:expr, $answer:expr) => { + assert_eq!($a * $b, $answer); + assert_eq!({ let mut x = $a; x *= $b; x}, $answer); + }; + ($a:ident / $b:expr, $answer:expr) => { + assert_eq!($a / $b, $answer); + assert_eq!({ let mut x = $a; x /= $b; x}, $answer); + }; + ($a:ident % $b:expr, $answer:expr) => { + assert_eq!($a % $b, $answer); + assert_eq!({ let mut x = $a; x %= $b; x}, $answer); + } + } + + // Test both a + b and a + &b + macro_rules! test_op { + ($a:ident $op:tt $b:expr, $answer:expr) => { + test_a_op_b!($a $op $b, $answer); + test_a_op_b!($a $op &$b, $answer); + } + } + + mod complex_arithmetic { + use super::{_0_0i, _1_0i, _1_1i, _0_1i, _neg1_1i, _05_05i, _4_2i, all_consts}; + use traits::Zero; + + #[test] + fn test_add() { + test_op!(_05_05i + _05_05i, _1_1i); + test_op!(_0_1i + _1_0i, _1_1i); + test_op!(_1_0i + _neg1_1i, _0_1i); + + for &c in all_consts.iter() { + test_op!(_0_0i + c, c); + test_op!(c + _0_0i, c); + } + } + + #[test] + fn test_sub() { + test_op!(_05_05i - _05_05i, _0_0i); + test_op!(_0_1i - _1_0i, _neg1_1i); + test_op!(_0_1i - _neg1_1i, _1_0i); + + for &c in all_consts.iter() { + test_op!(c - _0_0i, c); + test_op!(c - c, _0_0i); + } + } + + #[test] + fn test_mul() { + test_op!(_05_05i * _05_05i, _0_1i.unscale(2.0)); + test_op!(_1_1i * _0_1i, _neg1_1i); + + // i^2 & i^4 + test_op!(_0_1i * _0_1i, -_1_0i); + assert_eq!(_0_1i * _0_1i * _0_1i * _0_1i, _1_0i); + + for &c in all_consts.iter() { + test_op!(c * _1_0i, c); + test_op!(_1_0i * c, c); + } + } + + #[test] + fn test_div() { + test_op!(_neg1_1i / _0_1i, _1_1i); + for &c in all_consts.iter() { + if c != Zero::zero() { + test_op!(c / c, _1_0i); + } + } + } + + #[test] + fn test_rem() { + test_op!(_neg1_1i % _0_1i, _0_0i); + test_op!(_4_2i % _0_1i, _0_0i); + test_op!(_05_05i % _0_1i, _05_05i); + test_op!(_05_05i % _1_1i, _05_05i); + assert_eq!((_4_2i + _05_05i) % _0_1i, _05_05i); + assert_eq!((_4_2i + _05_05i) % _1_1i, _05_05i); + } + + #[test] + fn test_neg() { + assert_eq!(-_1_0i + _0_1i, _neg1_1i); + assert_eq!((-_0_1i) * _0_1i, _1_0i); + for &c in all_consts.iter() { + assert_eq!(-(-c), c); + } + } + } + + mod real_arithmetic { + use super::super::Complex; + use super::{_4_2i, _neg1_1i}; + + #[test] + fn test_add() { + test_op!(_4_2i + 0.5, Complex::new(4.5, 2.0)); + assert_eq!(0.5 + _4_2i, Complex::new(4.5, 2.0)); + } + + #[test] + fn test_sub() { + test_op!(_4_2i - 0.5, Complex::new(3.5, 2.0)); + assert_eq!(0.5 - _4_2i, Complex::new(-3.5, -2.0)); + } + + #[test] + fn test_mul() { + assert_eq!(_4_2i * 0.5, Complex::new(2.0, 1.0)); + assert_eq!(0.5 * _4_2i, Complex::new(2.0, 1.0)); + } + + #[test] + fn test_div() { + assert_eq!(_4_2i / 0.5, Complex::new(8.0, 4.0)); + assert_eq!(0.5 / _4_2i, Complex::new(0.1, -0.05)); + } + + #[test] + fn test_rem() { + assert_eq!(_4_2i % 2.0, Complex::new(0.0, 0.0)); + assert_eq!(_4_2i % 3.0, Complex::new(1.0, 2.0)); + assert_eq!(3.0 % _4_2i, Complex::new(3.0, 0.0)); + assert_eq!(_neg1_1i % 2.0, _neg1_1i); + assert_eq!(-_4_2i % 3.0, Complex::new(-1.0, -2.0)); + } + } + + #[test] + fn test_to_string() { + fn test(c : Complex64, s: String) { + assert_eq!(c.to_string(), s); + } + test(_0_0i, "0+0i".to_string()); + test(_1_0i, "1+0i".to_string()); + test(_0_1i, "0+1i".to_string()); + test(_1_1i, "1+1i".to_string()); + test(_neg1_1i, "-1+1i".to_string()); + test(-_neg1_1i, "1-1i".to_string()); + test(_05_05i, "0.5+0.5i".to_string()); + } + + #[test] + fn test_string_formatting() { + let a = Complex::new(1.23456, 123.456); + assert_eq!(format!("{}", a), "1.23456+123.456i"); + assert_eq!(format!("{:.2}", a), "1.23+123.46i"); + assert_eq!(format!("{:.2e}", a), "1.23e0+1.23e2i"); + assert_eq!(format!("{:+20.2E}", a), " +1.23E0+1.23E2i"); + + let b = Complex::new(0x80, 0xff); + assert_eq!(format!("{:X}", b), "80+FFi"); + assert_eq!(format!("{:#x}", b), "0x80+0xffi"); + assert_eq!(format!("{:+#b}", b), "+0b10000000+0b11111111i"); + assert_eq!(format!("{:+#16o}", b), " +0o200+0o377i"); + + let c = Complex::new(-10, -10000); + assert_eq!(format!("{}", c), "-10-10000i"); + assert_eq!(format!("{:16}", c), " -10-10000i"); + } + + #[test] + fn test_hash() { + let a = Complex::new(0i32, 0i32); + let b = Complex::new(1i32, 0i32); + let c = Complex::new(0i32, 1i32); + assert!(::hash(&a) != ::hash(&b)); + assert!(::hash(&b) != ::hash(&c)); + assert!(::hash(&c) != ::hash(&a)); + } + + #[test] + fn test_hashset() { + use std::collections::HashSet; + let a = Complex::new(0i32, 0i32); + let b = Complex::new(1i32, 0i32); + let c = Complex::new(0i32, 1i32); + + let set: HashSet<_> = [a, b, c].iter().cloned().collect(); + assert!(set.contains(&a)); + assert!(set.contains(&b)); + assert!(set.contains(&c)); + assert!(!set.contains(&(a + b + c))); + } + + #[test] + fn test_is_nan() { + assert!(!_1_1i.is_nan()); + let a = Complex::new(f64::NAN, f64::NAN); + assert!(a.is_nan()); + } + + #[test] + fn test_is_nan_special_cases() { + let a = Complex::new(0f64, f64::NAN); + let b = Complex::new(f64::NAN, 0f64); + assert!(a.is_nan()); + assert!(b.is_nan()); + } + + #[test] + fn test_is_infinite() { + let a = Complex::new(2f64, f64::INFINITY); + assert!(a.is_infinite()); + } + + #[test] + fn test_is_finite() { + assert!(_1_1i.is_finite()) + } + + #[test] + fn test_is_normal() { + let a = Complex::new(0f64, f64::NAN); + let b = Complex::new(2f64, f64::INFINITY); + assert!(!a.is_normal()); + assert!(!b.is_normal()); + assert!(_1_1i.is_normal()); + } + + #[test] + fn test_from_str() { + fn test(z: Complex64, s: &str) { + assert_eq!(FromStr::from_str(s), Ok(z)); + } + test(_0_0i, "0 + 0i"); + test(_0_0i, "0+0j"); + test(_0_0i, "0 - 0j"); + test(_0_0i, "0-0i"); + test(_0_0i, "0i + 0"); + test(_0_0i, "0"); + test(_0_0i, "-0"); + test(_0_0i, "0i"); + test(_0_0i, "0j"); + test(_0_0i, "+0j"); + test(_0_0i, "-0i"); + + test(_1_0i, "1 + 0i"); + test(_1_0i, "1+0j"); + test(_1_0i, "1 - 0j"); + test(_1_0i, "+1-0i"); + test(_1_0i, "-0j+1"); + test(_1_0i, "1"); + + test(_1_1i, "1 + i"); + test(_1_1i, "1+j"); + test(_1_1i, "1 + 1j"); + test(_1_1i, "1+1i"); + test(_1_1i, "i + 1"); + test(_1_1i, "1i+1"); + test(_1_1i, "+j+1"); + + test(_0_1i, "0 + i"); + test(_0_1i, "0+j"); + test(_0_1i, "-0 + j"); + test(_0_1i, "-0+i"); + test(_0_1i, "0 + 1i"); + test(_0_1i, "0+1j"); + test(_0_1i, "-0 + 1j"); + test(_0_1i, "-0+1i"); + test(_0_1i, "j + 0"); + test(_0_1i, "i"); + test(_0_1i, "j"); + test(_0_1i, "1j"); + + test(_neg1_1i, "-1 + i"); + test(_neg1_1i, "-1+j"); + test(_neg1_1i, "-1 + 1j"); + test(_neg1_1i, "-1+1i"); + test(_neg1_1i, "1i-1"); + test(_neg1_1i, "j + -1"); + + test(_05_05i, "0.5 + 0.5i"); + test(_05_05i, "0.5+0.5j"); + test(_05_05i, "5e-1+0.5j"); + test(_05_05i, "5E-1 + 0.5j"); + test(_05_05i, "5E-1i + 0.5"); + test(_05_05i, "0.05e+1j + 50E-2"); + } + + #[test] + fn test_from_str_radix() { + fn test(z: Complex64, s: &str, radix: u32) { + let res: Result::FromStrRadixErr> + = Num::from_str_radix(s, radix); + assert_eq!(res.unwrap(), z) + } + test(_4_2i, "4+2i", 10); + test(Complex::new(15.0, 32.0), "F+20i", 16); + test(Complex::new(15.0, 32.0), "1111+100000i", 2); + test(Complex::new(-15.0, -32.0), "-F-20i", 16); + test(Complex::new(-15.0, -32.0), "-1111-100000i", 2); + } + + #[test] + fn test_from_str_fail() { + fn test(s: &str) { + let complex: Result = FromStr::from_str(s); + assert!(complex.is_err()); + } + test("foo"); + test("6E"); + test("0 + 2.718"); + test("1 - -2i"); + test("314e-2ij"); + test("4.3j - i"); + test("1i - 2i"); + test("+ 1 - 3.0i"); + } +} diff -Nru cargo-0.25.0/vendor/num-complex-0.1.43/.travis.yml cargo-0.26.0/vendor/num-complex-0.1.43/.travis.yml --- cargo-0.25.0/vendor/num-complex-0.1.43/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-complex-0.1.43/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,19 @@ +language: rust +rust: + - 1.8.0 + - stable + - beta + - nightly +sudo: false +script: + - cargo build --verbose + - ./ci/test_full.sh +notifications: + email: + on_success: never +branches: + only: + - master + - next + - staging + - trying diff -Nru cargo-0.25.0/vendor/num-traits-0.1.43/bors.toml cargo-0.26.0/vendor/num-traits-0.1.43/bors.toml --- cargo-0.25.0/vendor/num-traits-0.1.43/bors.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.1.43/bors.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -status = [ - "continuous-integration/travis-ci/push", -] diff -Nru cargo-0.25.0/vendor/num-traits-0.1.43/.cargo-checksum.json cargo-0.26.0/vendor/num-traits-0.1.43/.cargo-checksum.json --- cargo-0.25.0/vendor/num-traits-0.1.43/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.1.43/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"92e5113e9fd4cc14ded8e499429f396a20f98c772a47cc8622a736e1ec843c31"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/num-traits-0.1.43/Cargo.toml cargo-0.26.0/vendor/num-traits-0.1.43/Cargo.toml --- cargo-0.25.0/vendor/num-traits-0.1.43/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.1.43/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "num-traits" -version = "0.1.43" -authors = ["The Rust Project Developers"] -description = "Numeric traits for generic mathematics" -homepage = "https://github.com/rust-num/num-traits" -documentation = "https://docs.rs/num-traits" -readme = "README.md" -keywords = ["mathematics", "numerics"] -categories = ["algorithms", "science"] -license = "MIT/Apache-2.0" -repository = "https://github.com/rust-num/num-traits" - -[lib] -doctest = false -[dependencies.num-traits] -version = "0.2.0" diff -Nru cargo-0.25.0/vendor/num-traits-0.1.43/ci/rustup.sh cargo-0.26.0/vendor/num-traits-0.1.43/ci/rustup.sh --- cargo-0.25.0/vendor/num-traits-0.1.43/ci/rustup.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.1.43/ci/rustup.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -#!/bin/sh -# Use rustup to locally run the same suite of tests as .travis.yml. -# (You should first install/update 1.8.0, stable, beta, and nightly.) - -set -ex - -export TRAVIS_RUST_VERSION -for TRAVIS_RUST_VERSION in 1.8.0 stable beta nightly; do - run="rustup run $TRAVIS_RUST_VERSION" - $run cargo build --verbose - $run $PWD/ci/test_full.sh -done diff -Nru cargo-0.25.0/vendor/num-traits-0.1.43/ci/test_full.sh cargo-0.26.0/vendor/num-traits-0.1.43/ci/test_full.sh --- cargo-0.25.0/vendor/num-traits-0.1.43/ci/test_full.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.1.43/ci/test_full.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -#!/bin/bash - -set -ex - -echo Testing num-traits on rustc ${TRAVIS_RUST_VERSION} - -# num-integer should build and test everywhere. -cargo build --verbose -cargo test --verbose - -# We have no features to test... diff -Nru cargo-0.25.0/vendor/num-traits-0.1.43/LICENSE-APACHE cargo-0.26.0/vendor/num-traits-0.1.43/LICENSE-APACHE --- cargo-0.25.0/vendor/num-traits-0.1.43/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.1.43/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/num-traits-0.1.43/LICENSE-MIT cargo-0.26.0/vendor/num-traits-0.1.43/LICENSE-MIT --- cargo-0.25.0/vendor/num-traits-0.1.43/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.1.43/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/num-traits-0.1.43/README.md cargo-0.26.0/vendor/num-traits-0.1.43/README.md --- cargo-0.25.0/vendor/num-traits-0.1.43/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.1.43/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -# num-traits - -[![crate](https://img.shields.io/crates/v/num-traits.svg)](https://crates.io/crates/num-traits) -[![documentation](https://docs.rs/num-traits/badge.svg)](https://docs.rs/num-traits) -[![Travis status](https://travis-ci.org/rust-num/num-traits.svg?branch=master)](https://travis-ci.org/rust-num/num-traits) - -Numeric traits for generic mathematics in Rust. - -This version of the crate only exists to re-export compatible -items from `num-traits` 0.2. Please consider updating! - -## Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -num-traits = "0.1" -``` - -and this to your crate root: - -```rust -extern crate num_traits; -``` - -## Releases - -Release notes are available in [RELEASES.md](RELEASES.md). - -## Compatibility - -The `num-traits` crate is tested for rustc 1.8 and greater. diff -Nru cargo-0.25.0/vendor/num-traits-0.1.43/RELEASES.md cargo-0.26.0/vendor/num-traits-0.1.43/RELEASES.md --- cargo-0.25.0/vendor/num-traits-0.1.43/RELEASES.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.1.43/RELEASES.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -# Release 0.2.0 - -- **breaking change**: There is now a `std` feature, enabled by default, along - with the implication that building *without* this feature makes this a - `#[no_std]` crate. - - The `Float` and `Real` traits are only available when `std` is enabled. - - Otherwise, the API is unchanged, and num-traits 0.1.43 now re-exports its - items from num-traits 0.2 for compatibility (the [semver-trick]). - -**Contributors**: @cuviper, @termoshtt, @vks - -[semver-trick]: https://github.com/dtolnay/semver-trick - -# Release 0.1.43 - -- All items are now re-exported from num-traits 0.2 for compatibility. - -# Release 0.1.42 - -- [num-traits now has its own source repository][num-356] at [rust-num/num-traits][home]. -- [`ParseFloatError` now implements `Display`][22]. -- [The new `AsPrimitive` trait][17] implements generic casting with the `as` operator. -- [The new `CheckedShl` and `CheckedShr` traits][21] implement generic - support for the `checked_shl` and `checked_shr` methods on primitive integers. -- [The new `Real` trait][23] offers a subset of `Float` functionality that may be applicable to more - types, with a blanket implementation for all existing `T: Float` types. - -Thanks to @cuviper, @Enet4, @fabianschuiki, @svartalf, and @yoanlcq for their contributions! - -[home]: https://github.com/rust-num/num-traits -[num-356]: https://github.com/rust-num/num/pull/356 -[17]: https://github.com/rust-num/num-traits/pull/17 -[21]: https://github.com/rust-num/num-traits/pull/21 -[22]: https://github.com/rust-num/num-traits/pull/22 -[23]: https://github.com/rust-num/num-traits/pull/23 - - -# Prior releases - -No prior release notes were kept. Thanks all the same to the many -contributors that have made this crate what it is! diff -Nru cargo-0.25.0/vendor/num-traits-0.1.43/src/lib.rs cargo-0.26.0/vendor/num-traits-0.1.43/src/lib.rs --- cargo-0.25.0/vendor/num-traits-0.1.43/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.1.43/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,88 +0,0 @@ -// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Numeric traits for generic mathematics -//! -//! This version of the crate only exists to re-export compatible -//! items from num-traits 0.2. Please consider updating! - -#![doc(html_root_url = "https://docs.rs/num-traits/0.1")] - -extern crate num_traits; - -pub use bounds::Bounded; -pub use float::{Float, FloatConst}; -// pub use real::Real; // NOTE: Don't do this, it breaks `use num_traits::*;`. -pub use identities::{Zero, One, zero, one}; -pub use ops::checked::{CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, CheckedShl, CheckedShr}; -pub use ops::wrapping::{WrappingAdd, WrappingMul, WrappingSub}; -pub use ops::saturating::Saturating; -pub use sign::{Signed, Unsigned, abs, abs_sub, signum}; -pub use cast::{AsPrimitive, FromPrimitive, ToPrimitive, NumCast, cast}; -pub use int::PrimInt; -pub use pow::{pow, checked_pow}; - - -// Re-exports from num-traits 0.2! - -pub use num_traits::{Num, NumOps, NumRef, RefNum}; -pub use num_traits::{NumAssignOps, NumAssign, NumAssignRef}; -pub use num_traits::{FloatErrorKind, ParseFloatError}; -pub use num_traits::clamp; - -// Note: the module structure is explicitly re-created, rather than re-exporting en masse, -// so we won't expose any items that may be added later in the new version. - -pub mod identities { - pub use num_traits::identities::{Zero, One, zero, one}; -} - -pub mod sign { - pub use num_traits::sign::{Signed, Unsigned, abs, abs_sub, signum}; -} - -pub mod ops { - pub mod saturating { - pub use num_traits::ops::saturating::Saturating; - } - - pub mod checked { - pub use num_traits::ops::checked::{CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, - CheckedShl, CheckedShr}; - } - - pub mod wrapping { - pub use num_traits::ops::wrapping::{WrappingAdd, WrappingMul, WrappingSub}; - } -} - -pub mod bounds { - pub use num_traits::bounds::Bounded; -} - -pub mod float { - pub use num_traits::float::{Float, FloatConst}; -} - -pub mod real { - pub use num_traits::real::Real; -} - -pub mod cast { - pub use num_traits::cast::{AsPrimitive, FromPrimitive, ToPrimitive, NumCast, cast}; -} - -pub mod int { - pub use num_traits::int::PrimInt; -} - -pub mod pow { - pub use num_traits::pow::{pow, checked_pow}; -} diff -Nru cargo-0.25.0/vendor/num-traits-0.1.43/.travis.yml cargo-0.26.0/vendor/num-traits-0.1.43/.travis.yml --- cargo-0.25.0/vendor/num-traits-0.1.43/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.1.43/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -language: rust -rust: - - 1.8.0 - - stable - - beta - - nightly -sudo: false -script: - - cargo build --verbose - - ./ci/test_full.sh -notifications: - email: - on_success: never -branches: - only: - - master - - num-traits-0.1.x - - next - - staging - - trying diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/bors.toml cargo-0.26.0/vendor/num-traits-0.2.0/bors.toml --- cargo-0.25.0/vendor/num-traits-0.2.0/bors.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/bors.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -status = [ - "continuous-integration/travis-ci/push", -] diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/.cargo-checksum.json cargo-0.26.0/vendor/num-traits-0.2.0/.cargo-checksum.json --- cargo-0.25.0/vendor/num-traits-0.2.0/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"e7de20f146db9d920c45ee8ed8f71681fd9ade71909b48c3acbd766aa504cf10"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/Cargo.toml cargo-0.26.0/vendor/num-traits-0.2.0/Cargo.toml --- cargo-0.25.0/vendor/num-traits-0.2.0/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "num-traits" -version = "0.2.0" -authors = ["The Rust Project Developers"] -description = "Numeric traits for generic mathematics" -homepage = "https://github.com/rust-num/num-traits" -documentation = "https://docs.rs/num-traits" -readme = "README.md" -keywords = ["mathematics", "numerics"] -categories = ["algorithms", "science"] -license = "MIT/Apache-2.0" -repository = "https://github.com/rust-num/num-traits" - -[dependencies] - -[features] -default = ["std"] -std = [] diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/ci/rustup.sh cargo-0.26.0/vendor/num-traits-0.2.0/ci/rustup.sh --- cargo-0.25.0/vendor/num-traits-0.2.0/ci/rustup.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/ci/rustup.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -#!/bin/sh -# Use rustup to locally run the same suite of tests as .travis.yml. -# (You should first install/update 1.8.0, stable, beta, and nightly.) - -set -ex - -export TRAVIS_RUST_VERSION -for TRAVIS_RUST_VERSION in 1.8.0 stable beta nightly; do - run="rustup run $TRAVIS_RUST_VERSION" - $run cargo build --verbose - $run $PWD/ci/test_full.sh -done diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/ci/test_full.sh cargo-0.26.0/vendor/num-traits-0.2.0/ci/test_full.sh --- cargo-0.25.0/vendor/num-traits-0.2.0/ci/test_full.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/ci/test_full.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -#!/bin/bash - -set -ex - -echo Testing num-traits on rustc ${TRAVIS_RUST_VERSION} - -# num-traits should build and test everywhere. -cargo build --verbose -cargo test --verbose - -# test `no_std` -cargo build --verbose --no-default-features -cargo test --verbose --no-default-features diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/LICENSE-APACHE cargo-0.26.0/vendor/num-traits-0.2.0/LICENSE-APACHE --- cargo-0.25.0/vendor/num-traits-0.2.0/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/LICENSE-MIT cargo-0.26.0/vendor/num-traits-0.2.0/LICENSE-MIT --- cargo-0.25.0/vendor/num-traits-0.2.0/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/README.md cargo-0.26.0/vendor/num-traits-0.2.0/README.md --- cargo-0.25.0/vendor/num-traits-0.2.0/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -# num-traits - -[![crate](https://img.shields.io/crates/v/num-traits.svg)](https://crates.io/crates/num-traits) -[![documentation](https://docs.rs/num-traits/badge.svg)](https://docs.rs/num-traits) -![minimum rustc 1.8](https://img.shields.io/badge/rustc-1.8+-red.svg) -[![Travis status](https://travis-ci.org/rust-num/num-traits.svg?branch=master)](https://travis-ci.org/rust-num/num-traits) - -Numeric traits for generic mathematics in Rust. - -## Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -num-traits = "0.2" -``` - -and this to your crate root: - -```rust -extern crate num_traits; -``` - -## Features - -This crate can be used without the standard library (`#![no_std]`) by disabling -the default `std` feature. Use this in `Cargo.toml`: - -```toml -[dependencies.num-traits] -version = "0.2" -default-features = false -``` - -The `Float` and `Real` traits are only available when `std` is enabled. - -## Releases - -Release notes are available in [RELEASES.md](RELEASES.md). - -## Compatibility - -The `num-traits` crate is tested for rustc 1.8 and greater. diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/RELEASES.md cargo-0.26.0/vendor/num-traits-0.2.0/RELEASES.md --- cargo-0.25.0/vendor/num-traits-0.2.0/RELEASES.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/RELEASES.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -# Release 0.2.0 - -- **breaking change**: There is now a `std` feature, enabled by default, along - with the implication that building *without* this feature makes this a - `#[no_std]` crate. - - The `Float` and `Real` traits are only available when `std` is enabled. - - Otherwise, the API is unchanged, and num-traits 0.1.43 now re-exports its - items from num-traits 0.2 for compatibility (the [semver-trick]). - -**Contributors**: @cuviper, @termoshtt, @vks - -[semver-trick]: https://github.com/dtolnay/semver-trick - -# Release 0.1.43 - -- All items are now re-exported from num-traits 0.2 for compatibility. - -# Release 0.1.42 - -- [num-traits now has its own source repository][num-356] at [rust-num/num-traits][home]. -- [`ParseFloatError` now implements `Display`][22]. -- [The new `AsPrimitive` trait][17] implements generic casting with the `as` operator. -- [The new `CheckedShl` and `CheckedShr` traits][21] implement generic - support for the `checked_shl` and `checked_shr` methods on primitive integers. -- [The new `Real` trait][23] offers a subset of `Float` functionality that may be applicable to more - types, with a blanket implementation for all existing `T: Float` types. - -Thanks to @cuviper, @Enet4, @fabianschuiki, @svartalf, and @yoanlcq for their contributions! - -[home]: https://github.com/rust-num/num-traits -[num-356]: https://github.com/rust-num/num/pull/356 -[17]: https://github.com/rust-num/num-traits/pull/17 -[21]: https://github.com/rust-num/num-traits/pull/21 -[22]: https://github.com/rust-num/num-traits/pull/22 -[23]: https://github.com/rust-num/num-traits/pull/23 - - -# Prior releases - -No prior release notes were kept. Thanks all the same to the many -contributors that have made this crate what it is! diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/bounds.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/bounds.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/bounds.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/bounds.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,99 +0,0 @@ -use core::{usize, u8, u16, u32, u64}; -use core::{isize, i8, i16, i32, i64}; -use core::{f32, f64}; -use core::num::Wrapping; - -/// Numbers which have upper and lower bounds -pub trait Bounded { - // FIXME (#5527): These should be associated constants - /// returns the smallest finite number this type can represent - fn min_value() -> Self; - /// returns the largest finite number this type can represent - fn max_value() -> Self; -} - -macro_rules! bounded_impl { - ($t:ty, $min:expr, $max:expr) => { - impl Bounded for $t { - #[inline] - fn min_value() -> $t { $min } - - #[inline] - fn max_value() -> $t { $max } - } - } -} - -bounded_impl!(usize, usize::MIN, usize::MAX); -bounded_impl!(u8, u8::MIN, u8::MAX); -bounded_impl!(u16, u16::MIN, u16::MAX); -bounded_impl!(u32, u32::MIN, u32::MAX); -bounded_impl!(u64, u64::MIN, u64::MAX); - -bounded_impl!(isize, isize::MIN, isize::MAX); -bounded_impl!(i8, i8::MIN, i8::MAX); -bounded_impl!(i16, i16::MIN, i16::MAX); -bounded_impl!(i32, i32::MIN, i32::MAX); -bounded_impl!(i64, i64::MIN, i64::MAX); - -impl Bounded for Wrapping { - fn min_value() -> Self { Wrapping(T::min_value()) } - fn max_value() -> Self { Wrapping(T::max_value()) } -} - -bounded_impl!(f32, f32::MIN, f32::MAX); - -macro_rules! for_each_tuple_ { - ( $m:ident !! ) => ( - $m! { } - ); - ( $m:ident !! $h:ident, $($t:ident,)* ) => ( - $m! { $h $($t)* } - for_each_tuple_! { $m !! $($t,)* } - ); -} -macro_rules! for_each_tuple { - ( $m:ident ) => ( - for_each_tuple_! { $m !! A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, } - ); -} - -macro_rules! bounded_tuple { - ( $($name:ident)* ) => ( - impl<$($name: Bounded,)*> Bounded for ($($name,)*) { - #[inline] - fn min_value() -> Self { - ($($name::min_value(),)*) - } - #[inline] - fn max_value() -> Self { - ($($name::max_value(),)*) - } - } - ); -} - -for_each_tuple!(bounded_tuple); -bounded_impl!(f64, f64::MIN, f64::MAX); - - -#[test] -fn wrapping_bounded() { - macro_rules! test_wrapping_bounded { - ($($t:ty)+) => { - $( - assert_eq!(Wrapping::<$t>::min_value().0, <$t>::min_value()); - assert_eq!(Wrapping::<$t>::max_value().0, <$t>::max_value()); - )+ - }; - } - - test_wrapping_bounded!(usize u8 u16 u32 u64 isize i8 i16 i32 i64); -} - -#[test] -fn wrapping_is_bounded() { - fn require_bounded(_: &T) {} - require_bounded(&Wrapping(42_u32)); - require_bounded(&Wrapping(-42)); -} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/cast.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/cast.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/cast.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/cast.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,594 +0,0 @@ -use core::f64; -use core::mem::size_of; -use core::num::Wrapping; - -use identities::Zero; -use bounds::Bounded; - -/// A generic trait for converting a value to a number. -pub trait ToPrimitive { - /// Converts the value of `self` to an `isize`. - #[inline] - fn to_isize(&self) -> Option { - self.to_i64().and_then(|x| x.to_isize()) - } - - /// Converts the value of `self` to an `i8`. - #[inline] - fn to_i8(&self) -> Option { - self.to_i64().and_then(|x| x.to_i8()) - } - - /// Converts the value of `self` to an `i16`. - #[inline] - fn to_i16(&self) -> Option { - self.to_i64().and_then(|x| x.to_i16()) - } - - /// Converts the value of `self` to an `i32`. - #[inline] - fn to_i32(&self) -> Option { - self.to_i64().and_then(|x| x.to_i32()) - } - - /// Converts the value of `self` to an `i64`. - fn to_i64(&self) -> Option; - - /// Converts the value of `self` to a `usize`. - #[inline] - fn to_usize(&self) -> Option { - self.to_u64().and_then(|x| x.to_usize()) - } - - /// Converts the value of `self` to an `u8`. - #[inline] - fn to_u8(&self) -> Option { - self.to_u64().and_then(|x| x.to_u8()) - } - - /// Converts the value of `self` to an `u16`. - #[inline] - fn to_u16(&self) -> Option { - self.to_u64().and_then(|x| x.to_u16()) - } - - /// Converts the value of `self` to an `u32`. - #[inline] - fn to_u32(&self) -> Option { - self.to_u64().and_then(|x| x.to_u32()) - } - - /// Converts the value of `self` to an `u64`. - #[inline] - fn to_u64(&self) -> Option; - - /// Converts the value of `self` to an `f32`. - #[inline] - fn to_f32(&self) -> Option { - self.to_f64().and_then(|x| x.to_f32()) - } - - /// Converts the value of `self` to an `f64`. - #[inline] - fn to_f64(&self) -> Option { - self.to_i64().and_then(|x| x.to_f64()) - } -} - -macro_rules! impl_to_primitive_int_to_int { - ($SrcT:ty, $DstT:ty, $slf:expr) => ( - { - if size_of::<$SrcT>() <= size_of::<$DstT>() { - Some($slf as $DstT) - } else { - let n = $slf as i64; - let min_value: $DstT = Bounded::min_value(); - let max_value: $DstT = Bounded::max_value(); - if min_value as i64 <= n && n <= max_value as i64 { - Some($slf as $DstT) - } else { - None - } - } - } - ) -} - -macro_rules! impl_to_primitive_int_to_uint { - ($SrcT:ty, $DstT:ty, $slf:expr) => ( - { - let zero: $SrcT = Zero::zero(); - let max_value: $DstT = Bounded::max_value(); - if zero <= $slf && $slf as u64 <= max_value as u64 { - Some($slf as $DstT) - } else { - None - } - } - ) -} - -macro_rules! impl_to_primitive_int { - ($T:ty) => ( - impl ToPrimitive for $T { - #[inline] - fn to_isize(&self) -> Option { impl_to_primitive_int_to_int!($T, isize, *self) } - #[inline] - fn to_i8(&self) -> Option { impl_to_primitive_int_to_int!($T, i8, *self) } - #[inline] - fn to_i16(&self) -> Option { impl_to_primitive_int_to_int!($T, i16, *self) } - #[inline] - fn to_i32(&self) -> Option { impl_to_primitive_int_to_int!($T, i32, *self) } - #[inline] - fn to_i64(&self) -> Option { impl_to_primitive_int_to_int!($T, i64, *self) } - - #[inline] - fn to_usize(&self) -> Option { impl_to_primitive_int_to_uint!($T, usize, *self) } - #[inline] - fn to_u8(&self) -> Option { impl_to_primitive_int_to_uint!($T, u8, *self) } - #[inline] - fn to_u16(&self) -> Option { impl_to_primitive_int_to_uint!($T, u16, *self) } - #[inline] - fn to_u32(&self) -> Option { impl_to_primitive_int_to_uint!($T, u32, *self) } - #[inline] - fn to_u64(&self) -> Option { impl_to_primitive_int_to_uint!($T, u64, *self) } - - #[inline] - fn to_f32(&self) -> Option { Some(*self as f32) } - #[inline] - fn to_f64(&self) -> Option { Some(*self as f64) } - } - ) -} - -impl_to_primitive_int!(isize); -impl_to_primitive_int!(i8); -impl_to_primitive_int!(i16); -impl_to_primitive_int!(i32); -impl_to_primitive_int!(i64); - -macro_rules! impl_to_primitive_uint_to_int { - ($DstT:ty, $slf:expr) => ( - { - let max_value: $DstT = Bounded::max_value(); - if $slf as u64 <= max_value as u64 { - Some($slf as $DstT) - } else { - None - } - } - ) -} - -macro_rules! impl_to_primitive_uint_to_uint { - ($SrcT:ty, $DstT:ty, $slf:expr) => ( - { - if size_of::<$SrcT>() <= size_of::<$DstT>() { - Some($slf as $DstT) - } else { - let zero: $SrcT = Zero::zero(); - let max_value: $DstT = Bounded::max_value(); - if zero <= $slf && $slf as u64 <= max_value as u64 { - Some($slf as $DstT) - } else { - None - } - } - } - ) -} - -macro_rules! impl_to_primitive_uint { - ($T:ty) => ( - impl ToPrimitive for $T { - #[inline] - fn to_isize(&self) -> Option { impl_to_primitive_uint_to_int!(isize, *self) } - #[inline] - fn to_i8(&self) -> Option { impl_to_primitive_uint_to_int!(i8, *self) } - #[inline] - fn to_i16(&self) -> Option { impl_to_primitive_uint_to_int!(i16, *self) } - #[inline] - fn to_i32(&self) -> Option { impl_to_primitive_uint_to_int!(i32, *self) } - #[inline] - fn to_i64(&self) -> Option { impl_to_primitive_uint_to_int!(i64, *self) } - - #[inline] - fn to_usize(&self) -> Option { - impl_to_primitive_uint_to_uint!($T, usize, *self) - } - #[inline] - fn to_u8(&self) -> Option { impl_to_primitive_uint_to_uint!($T, u8, *self) } - #[inline] - fn to_u16(&self) -> Option { impl_to_primitive_uint_to_uint!($T, u16, *self) } - #[inline] - fn to_u32(&self) -> Option { impl_to_primitive_uint_to_uint!($T, u32, *self) } - #[inline] - fn to_u64(&self) -> Option { impl_to_primitive_uint_to_uint!($T, u64, *self) } - - #[inline] - fn to_f32(&self) -> Option { Some(*self as f32) } - #[inline] - fn to_f64(&self) -> Option { Some(*self as f64) } - } - ) -} - -impl_to_primitive_uint!(usize); -impl_to_primitive_uint!(u8); -impl_to_primitive_uint!(u16); -impl_to_primitive_uint!(u32); -impl_to_primitive_uint!(u64); - -macro_rules! impl_to_primitive_float_to_float { - ($SrcT:ident, $DstT:ident, $slf:expr) => ( - if size_of::<$SrcT>() <= size_of::<$DstT>() { - Some($slf as $DstT) - } else { - // Make sure the value is in range for the cast. - // NaN and +-inf are cast as they are. - let n = $slf as f64; - let max_value: $DstT = ::core::$DstT::MAX; - if n != n || n == f64::INFINITY || n == f64::NEG_INFINITY - || (-max_value as f64 <= n && n <= max_value as f64) - { - Some($slf as $DstT) - } else { - None - } - } - ) -} - -macro_rules! impl_to_primitive_float { - ($T:ident) => ( - impl ToPrimitive for $T { - #[inline] - fn to_isize(&self) -> Option { Some(*self as isize) } - #[inline] - fn to_i8(&self) -> Option { Some(*self as i8) } - #[inline] - fn to_i16(&self) -> Option { Some(*self as i16) } - #[inline] - fn to_i32(&self) -> Option { Some(*self as i32) } - #[inline] - fn to_i64(&self) -> Option { Some(*self as i64) } - - #[inline] - fn to_usize(&self) -> Option { Some(*self as usize) } - #[inline] - fn to_u8(&self) -> Option { Some(*self as u8) } - #[inline] - fn to_u16(&self) -> Option { Some(*self as u16) } - #[inline] - fn to_u32(&self) -> Option { Some(*self as u32) } - #[inline] - fn to_u64(&self) -> Option { Some(*self as u64) } - - #[inline] - fn to_f32(&self) -> Option { impl_to_primitive_float_to_float!($T, f32, *self) } - #[inline] - fn to_f64(&self) -> Option { impl_to_primitive_float_to_float!($T, f64, *self) } - } - ) -} - -impl_to_primitive_float!(f32); -impl_to_primitive_float!(f64); - -/// A generic trait for converting a number to a value. -pub trait FromPrimitive: Sized { - /// Convert an `isize` to return an optional value of this type. If the - /// value cannot be represented by this value, the `None` is returned. - #[inline] - fn from_isize(n: isize) -> Option { - FromPrimitive::from_i64(n as i64) - } - - /// Convert an `i8` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_i8(n: i8) -> Option { - FromPrimitive::from_i64(n as i64) - } - - /// Convert an `i16` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_i16(n: i16) -> Option { - FromPrimitive::from_i64(n as i64) - } - - /// Convert an `i32` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_i32(n: i32) -> Option { - FromPrimitive::from_i64(n as i64) - } - - /// Convert an `i64` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - fn from_i64(n: i64) -> Option; - - /// Convert a `usize` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_usize(n: usize) -> Option { - FromPrimitive::from_u64(n as u64) - } - - /// Convert an `u8` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_u8(n: u8) -> Option { - FromPrimitive::from_u64(n as u64) - } - - /// Convert an `u16` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_u16(n: u16) -> Option { - FromPrimitive::from_u64(n as u64) - } - - /// Convert an `u32` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_u32(n: u32) -> Option { - FromPrimitive::from_u64(n as u64) - } - - /// Convert an `u64` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - fn from_u64(n: u64) -> Option; - - /// Convert a `f32` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_f32(n: f32) -> Option { - FromPrimitive::from_f64(n as f64) - } - - /// Convert a `f64` to return an optional value of this type. If the - /// type cannot be represented by this value, the `None` is returned. - #[inline] - fn from_f64(n: f64) -> Option { - FromPrimitive::from_i64(n as i64) - } -} - -macro_rules! impl_from_primitive { - ($T:ty, $to_ty:ident) => ( - #[allow(deprecated)] - impl FromPrimitive for $T { - #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() } - #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() } - #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() } - #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() } - - #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() } - #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() } - #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() } - #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() } - - #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() } - #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() } - } - ) -} - -impl_from_primitive!(isize, to_isize); -impl_from_primitive!(i8, to_i8); -impl_from_primitive!(i16, to_i16); -impl_from_primitive!(i32, to_i32); -impl_from_primitive!(i64, to_i64); -impl_from_primitive!(usize, to_usize); -impl_from_primitive!(u8, to_u8); -impl_from_primitive!(u16, to_u16); -impl_from_primitive!(u32, to_u32); -impl_from_primitive!(u64, to_u64); -impl_from_primitive!(f32, to_f32); -impl_from_primitive!(f64, to_f64); - - -impl ToPrimitive for Wrapping { - fn to_i64(&self) -> Option { self.0.to_i64() } - fn to_u64(&self) -> Option { self.0.to_u64() } -} -impl FromPrimitive for Wrapping { - fn from_u64(n: u64) -> Option { T::from_u64(n).map(Wrapping) } - fn from_i64(n: i64) -> Option { T::from_i64(n).map(Wrapping) } -} - - -/// Cast from one machine scalar to another. -/// -/// # Examples -/// -/// ``` -/// # use num_traits as num; -/// let twenty: f32 = num::cast(0x14).unwrap(); -/// assert_eq!(twenty, 20f32); -/// ``` -/// -#[inline] -pub fn cast(n: T) -> Option { - NumCast::from(n) -} - -/// An interface for casting between machine scalars. -pub trait NumCast: Sized + ToPrimitive { - /// Creates a number from another value that can be converted into - /// a primitive via the `ToPrimitive` trait. - fn from(n: T) -> Option; -} - -macro_rules! impl_num_cast { - ($T:ty, $conv:ident) => ( - impl NumCast for $T { - #[inline] - #[allow(deprecated)] - fn from(n: N) -> Option<$T> { - // `$conv` could be generated using `concat_idents!`, but that - // macro seems to be broken at the moment - n.$conv() - } - } - ) -} - -impl_num_cast!(u8, to_u8); -impl_num_cast!(u16, to_u16); -impl_num_cast!(u32, to_u32); -impl_num_cast!(u64, to_u64); -impl_num_cast!(usize, to_usize); -impl_num_cast!(i8, to_i8); -impl_num_cast!(i16, to_i16); -impl_num_cast!(i32, to_i32); -impl_num_cast!(i64, to_i64); -impl_num_cast!(isize, to_isize); -impl_num_cast!(f32, to_f32); -impl_num_cast!(f64, to_f64); - -impl NumCast for Wrapping { - fn from(n: U) -> Option { - T::from(n).map(Wrapping) - } -} - -/// A generic interface for casting between machine scalars with the -/// `as` operator, which admits narrowing and precision loss. -/// Implementers of this trait AsPrimitive should behave like a primitive -/// numeric type (e.g. a newtype around another primitive), and the -/// intended conversion must never fail. -/// -/// # Examples -/// -/// ``` -/// # use num_traits::AsPrimitive; -/// let three: i32 = (3.14159265f32).as_(); -/// assert_eq!(three, 3); -/// ``` -/// -/// # Safety -/// -/// Currently, some uses of the `as` operator are not entirely safe. -/// In particular, it is undefined behavior if: -/// -/// - A truncated floating point value cannot fit in the target integer -/// type ([#10184](https://github.com/rust-lang/rust/issues/10184)); -/// -/// ```ignore -/// # use num_traits::AsPrimitive; -/// let x: u8 = (1.04E+17).as_(); // UB -/// ``` -/// -/// - Or a floating point value does not fit in another floating -/// point type ([#15536](https://github.com/rust-lang/rust/issues/15536)). -/// -/// ```ignore -/// # use num_traits::AsPrimitive; -/// let x: f32 = (1e300f64).as_(); // UB -/// ``` -/// -pub trait AsPrimitive: 'static + Copy -where - T: 'static + Copy -{ - /// Convert a value to another, using the `as` operator. - fn as_(self) -> T; -} - -macro_rules! impl_as_primitive { - ($T: ty => $( $U: ty ),* ) => { - $( - impl AsPrimitive<$U> for $T { - #[inline] fn as_(self) -> $U { self as $U } - } - )* - }; -} - -impl_as_primitive!(u8 => char, u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); -impl_as_primitive!(i8 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); -impl_as_primitive!(u16 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); -impl_as_primitive!(i16 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); -impl_as_primitive!(u32 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); -impl_as_primitive!(i32 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); -impl_as_primitive!(u64 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); -impl_as_primitive!(i64 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); -impl_as_primitive!(usize => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); -impl_as_primitive!(isize => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); -impl_as_primitive!(f32 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); -impl_as_primitive!(f64 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); -impl_as_primitive!(char => char, u8, i8, u16, i16, u32, i32, u64, isize, usize, i64); -impl_as_primitive!(bool => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64); - -#[test] -fn to_primitive_float() { - use core::f32; - use core::f64; - - let f32_toolarge = 1e39f64; - assert_eq!(f32_toolarge.to_f32(), None); - assert_eq!((f32::MAX as f64).to_f32(), Some(f32::MAX)); - assert_eq!((-f32::MAX as f64).to_f32(), Some(-f32::MAX)); - assert_eq!(f64::INFINITY.to_f32(), Some(f32::INFINITY)); - assert_eq!((f64::NEG_INFINITY).to_f32(), Some(f32::NEG_INFINITY)); - assert!((f64::NAN).to_f32().map_or(false, |f| f.is_nan())); -} - -#[test] -fn wrapping_to_primitive() { - macro_rules! test_wrapping_to_primitive { - ($($t:ty)+) => { - $({ - let i: $t = 0; - let w = Wrapping(i); - assert_eq!(i.to_u8(), w.to_u8()); - assert_eq!(i.to_u16(), w.to_u16()); - assert_eq!(i.to_u32(), w.to_u32()); - assert_eq!(i.to_u64(), w.to_u64()); - assert_eq!(i.to_usize(), w.to_usize()); - assert_eq!(i.to_i8(), w.to_i8()); - assert_eq!(i.to_i16(), w.to_i16()); - assert_eq!(i.to_i32(), w.to_i32()); - assert_eq!(i.to_i64(), w.to_i64()); - assert_eq!(i.to_isize(), w.to_isize()); - assert_eq!(i.to_f32(), w.to_f32()); - assert_eq!(i.to_f64(), w.to_f64()); - })+ - }; - } - - test_wrapping_to_primitive!(usize u8 u16 u32 u64 isize i8 i16 i32 i64); -} - -#[test] -fn wrapping_is_toprimitive() { - fn require_toprimitive(_: &T) {} - require_toprimitive(&Wrapping(42)); -} - -#[test] -fn wrapping_is_fromprimitive() { - fn require_fromprimitive(_: &T) {} - require_fromprimitive(&Wrapping(42)); -} - -#[test] -fn wrapping_is_numcast() { - fn require_numcast(_: &T) {} - require_numcast(&Wrapping(42)); -} - -#[test] -fn as_primitive() { - let x: f32 = (1.625f64).as_(); - assert_eq!(x, 1.625f32); - - let x: f32 = (3.14159265358979323846f64).as_(); - assert_eq!(x, 3.1415927f32); - - let x: u8 = (768i16).as_(); - assert_eq!(x, 0); -} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/float.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/float.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/float.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/float.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1358 +0,0 @@ -#[cfg(feature = "std")] -use std::mem; -#[cfg(feature = "std")] -use std::ops::Neg; -#[cfg(feature = "std")] -use std::num::FpCategory; - -// Used for default implementation of `epsilon` -#[cfg(feature = "std")] -use std::f32; - -#[cfg(feature = "std")] -use {Num, NumCast}; - -// FIXME: these doctests aren't actually helpful, because they're using and -// testing the inherent methods directly, not going through `Float`. - -/// Generic trait for floating point numbers -/// -/// This trait is only available with the `std` feature. -#[cfg(feature = "std")] -pub trait Float - : Num - + Copy - + NumCast - + PartialOrd - + Neg -{ - /// Returns the `NaN` value. - /// - /// ``` - /// use num_traits::Float; - /// - /// let nan: f32 = Float::nan(); - /// - /// assert!(nan.is_nan()); - /// ``` - fn nan() -> Self; - /// Returns the infinite value. - /// - /// ``` - /// use num_traits::Float; - /// use std::f32; - /// - /// let infinity: f32 = Float::infinity(); - /// - /// assert!(infinity.is_infinite()); - /// assert!(!infinity.is_finite()); - /// assert!(infinity > f32::MAX); - /// ``` - fn infinity() -> Self; - /// Returns the negative infinite value. - /// - /// ``` - /// use num_traits::Float; - /// use std::f32; - /// - /// let neg_infinity: f32 = Float::neg_infinity(); - /// - /// assert!(neg_infinity.is_infinite()); - /// assert!(!neg_infinity.is_finite()); - /// assert!(neg_infinity < f32::MIN); - /// ``` - fn neg_infinity() -> Self; - /// Returns `-0.0`. - /// - /// ``` - /// use num_traits::{Zero, Float}; - /// - /// let inf: f32 = Float::infinity(); - /// let zero: f32 = Zero::zero(); - /// let neg_zero: f32 = Float::neg_zero(); - /// - /// assert_eq!(zero, neg_zero); - /// assert_eq!(7.0f32/inf, zero); - /// assert_eq!(zero * 10.0, zero); - /// ``` - fn neg_zero() -> Self; - - /// Returns the smallest finite value that this type can represent. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let x: f64 = Float::min_value(); - /// - /// assert_eq!(x, f64::MIN); - /// ``` - fn min_value() -> Self; - - /// Returns the smallest positive, normalized value that this type can represent. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let x: f64 = Float::min_positive_value(); - /// - /// assert_eq!(x, f64::MIN_POSITIVE); - /// ``` - fn min_positive_value() -> Self; - - /// Returns epsilon, a small positive value. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let x: f64 = Float::epsilon(); - /// - /// assert_eq!(x, f64::EPSILON); - /// ``` - /// - /// # Panics - /// - /// The default implementation will panic if `f32::EPSILON` cannot - /// be cast to `Self`. - fn epsilon() -> Self { - Self::from(f32::EPSILON).expect("Unable to cast from f32::EPSILON") - } - - /// Returns the largest finite value that this type can represent. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let x: f64 = Float::max_value(); - /// assert_eq!(x, f64::MAX); - /// ``` - fn max_value() -> Self; - - /// Returns `true` if this value is `NaN` and false otherwise. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let nan = f64::NAN; - /// let f = 7.0; - /// - /// assert!(nan.is_nan()); - /// assert!(!f.is_nan()); - /// ``` - fn is_nan(self) -> bool; - - /// Returns `true` if this value is positive infinity or negative infinity and - /// false otherwise. - /// - /// ``` - /// use num_traits::Float; - /// use std::f32; - /// - /// let f = 7.0f32; - /// let inf: f32 = Float::infinity(); - /// let neg_inf: f32 = Float::neg_infinity(); - /// let nan: f32 = f32::NAN; - /// - /// assert!(!f.is_infinite()); - /// assert!(!nan.is_infinite()); - /// - /// assert!(inf.is_infinite()); - /// assert!(neg_inf.is_infinite()); - /// ``` - fn is_infinite(self) -> bool; - - /// Returns `true` if this number is neither infinite nor `NaN`. - /// - /// ``` - /// use num_traits::Float; - /// use std::f32; - /// - /// let f = 7.0f32; - /// let inf: f32 = Float::infinity(); - /// let neg_inf: f32 = Float::neg_infinity(); - /// let nan: f32 = f32::NAN; - /// - /// assert!(f.is_finite()); - /// - /// assert!(!nan.is_finite()); - /// assert!(!inf.is_finite()); - /// assert!(!neg_inf.is_finite()); - /// ``` - fn is_finite(self) -> bool; - - /// Returns `true` if the number is neither zero, infinite, - /// [subnormal][subnormal], or `NaN`. - /// - /// ``` - /// use num_traits::Float; - /// use std::f32; - /// - /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32 - /// let max = f32::MAX; - /// let lower_than_min = 1.0e-40_f32; - /// let zero = 0.0f32; - /// - /// assert!(min.is_normal()); - /// assert!(max.is_normal()); - /// - /// assert!(!zero.is_normal()); - /// assert!(!f32::NAN.is_normal()); - /// assert!(!f32::INFINITY.is_normal()); - /// // Values between `0` and `min` are Subnormal. - /// assert!(!lower_than_min.is_normal()); - /// ``` - /// [subnormal]: http://en.wikipedia.org/wiki/Denormal_number - fn is_normal(self) -> bool; - - /// Returns the floating point category of the number. If only one property - /// is going to be tested, it is generally faster to use the specific - /// predicate instead. - /// - /// ``` - /// use num_traits::Float; - /// use std::num::FpCategory; - /// use std::f32; - /// - /// let num = 12.4f32; - /// let inf = f32::INFINITY; - /// - /// assert_eq!(num.classify(), FpCategory::Normal); - /// assert_eq!(inf.classify(), FpCategory::Infinite); - /// ``` - fn classify(self) -> FpCategory; - - /// Returns the largest integer less than or equal to a number. - /// - /// ``` - /// use num_traits::Float; - /// - /// let f = 3.99; - /// let g = 3.0; - /// - /// assert_eq!(f.floor(), 3.0); - /// assert_eq!(g.floor(), 3.0); - /// ``` - fn floor(self) -> Self; - - /// Returns the smallest integer greater than or equal to a number. - /// - /// ``` - /// use num_traits::Float; - /// - /// let f = 3.01; - /// let g = 4.0; - /// - /// assert_eq!(f.ceil(), 4.0); - /// assert_eq!(g.ceil(), 4.0); - /// ``` - fn ceil(self) -> Self; - - /// Returns the nearest integer to a number. Round half-way cases away from - /// `0.0`. - /// - /// ``` - /// use num_traits::Float; - /// - /// let f = 3.3; - /// let g = -3.3; - /// - /// assert_eq!(f.round(), 3.0); - /// assert_eq!(g.round(), -3.0); - /// ``` - fn round(self) -> Self; - - /// Return the integer part of a number. - /// - /// ``` - /// use num_traits::Float; - /// - /// let f = 3.3; - /// let g = -3.7; - /// - /// assert_eq!(f.trunc(), 3.0); - /// assert_eq!(g.trunc(), -3.0); - /// ``` - fn trunc(self) -> Self; - - /// Returns the fractional part of a number. - /// - /// ``` - /// use num_traits::Float; - /// - /// let x = 3.5; - /// let y = -3.5; - /// let abs_difference_x = (x.fract() - 0.5).abs(); - /// let abs_difference_y = (y.fract() - (-0.5)).abs(); - /// - /// assert!(abs_difference_x < 1e-10); - /// assert!(abs_difference_y < 1e-10); - /// ``` - fn fract(self) -> Self; - - /// Computes the absolute value of `self`. Returns `Float::nan()` if the - /// number is `Float::nan()`. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let x = 3.5; - /// let y = -3.5; - /// - /// let abs_difference_x = (x.abs() - x).abs(); - /// let abs_difference_y = (y.abs() - (-y)).abs(); - /// - /// assert!(abs_difference_x < 1e-10); - /// assert!(abs_difference_y < 1e-10); - /// - /// assert!(f64::NAN.abs().is_nan()); - /// ``` - fn abs(self) -> Self; - - /// Returns a number that represents the sign of `self`. - /// - /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` - /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` - /// - `Float::nan()` if the number is `Float::nan()` - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let f = 3.5; - /// - /// assert_eq!(f.signum(), 1.0); - /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0); - /// - /// assert!(f64::NAN.signum().is_nan()); - /// ``` - fn signum(self) -> Self; - - /// Returns `true` if `self` is positive, including `+0.0`, - /// `Float::infinity()`, and with newer versions of Rust `f64::NAN`. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let neg_nan: f64 = -f64::NAN; - /// - /// let f = 7.0; - /// let g = -7.0; - /// - /// assert!(f.is_sign_positive()); - /// assert!(!g.is_sign_positive()); - /// assert!(!neg_nan.is_sign_positive()); - /// ``` - fn is_sign_positive(self) -> bool; - - /// Returns `true` if `self` is negative, including `-0.0`, - /// `Float::neg_infinity()`, and with newer versions of Rust `-f64::NAN`. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let nan: f64 = f64::NAN; - /// - /// let f = 7.0; - /// let g = -7.0; - /// - /// assert!(!f.is_sign_negative()); - /// assert!(g.is_sign_negative()); - /// assert!(!nan.is_sign_negative()); - /// ``` - fn is_sign_negative(self) -> bool; - - /// Fused multiply-add. Computes `(self * a) + b` with only one rounding - /// error. This produces a more accurate result with better performance than - /// a separate multiplication operation followed by an add. - /// - /// ``` - /// use num_traits::Float; - /// - /// let m = 10.0; - /// let x = 4.0; - /// let b = 60.0; - /// - /// // 100.0 - /// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn mul_add(self, a: Self, b: Self) -> Self; - /// Take the reciprocal (inverse) of a number, `1/x`. - /// - /// ``` - /// use num_traits::Float; - /// - /// let x = 2.0; - /// let abs_difference = (x.recip() - (1.0/x)).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn recip(self) -> Self; - - /// Raise a number to an integer power. - /// - /// Using this function is generally faster than using `powf` - /// - /// ``` - /// use num_traits::Float; - /// - /// let x = 2.0; - /// let abs_difference = (x.powi(2) - x*x).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn powi(self, n: i32) -> Self; - - /// Raise a number to a floating point power. - /// - /// ``` - /// use num_traits::Float; - /// - /// let x = 2.0; - /// let abs_difference = (x.powf(2.0) - x*x).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn powf(self, n: Self) -> Self; - - /// Take the square root of a number. - /// - /// Returns NaN if `self` is a negative number. - /// - /// ``` - /// use num_traits::Float; - /// - /// let positive = 4.0; - /// let negative = -4.0; - /// - /// let abs_difference = (positive.sqrt() - 2.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// assert!(negative.sqrt().is_nan()); - /// ``` - fn sqrt(self) -> Self; - - /// Returns `e^(self)`, (the exponential function). - /// - /// ``` - /// use num_traits::Float; - /// - /// let one = 1.0; - /// // e^1 - /// let e = one.exp(); - /// - /// // ln(e) - 1 == 0 - /// let abs_difference = (e.ln() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn exp(self) -> Self; - - /// Returns `2^(self)`. - /// - /// ``` - /// use num_traits::Float; - /// - /// let f = 2.0; - /// - /// // 2^2 - 4 == 0 - /// let abs_difference = (f.exp2() - 4.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn exp2(self) -> Self; - - /// Returns the natural logarithm of the number. - /// - /// ``` - /// use num_traits::Float; - /// - /// let one = 1.0; - /// // e^1 - /// let e = one.exp(); - /// - /// // ln(e) - 1 == 0 - /// let abs_difference = (e.ln() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn ln(self) -> Self; - - /// Returns the logarithm of the number with respect to an arbitrary base. - /// - /// ``` - /// use num_traits::Float; - /// - /// let ten = 10.0; - /// let two = 2.0; - /// - /// // log10(10) - 1 == 0 - /// let abs_difference_10 = (ten.log(10.0) - 1.0).abs(); - /// - /// // log2(2) - 1 == 0 - /// let abs_difference_2 = (two.log(2.0) - 1.0).abs(); - /// - /// assert!(abs_difference_10 < 1e-10); - /// assert!(abs_difference_2 < 1e-10); - /// ``` - fn log(self, base: Self) -> Self; - - /// Returns the base 2 logarithm of the number. - /// - /// ``` - /// use num_traits::Float; - /// - /// let two = 2.0; - /// - /// // log2(2) - 1 == 0 - /// let abs_difference = (two.log2() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn log2(self) -> Self; - - /// Returns the base 10 logarithm of the number. - /// - /// ``` - /// use num_traits::Float; - /// - /// let ten = 10.0; - /// - /// // log10(10) - 1 == 0 - /// let abs_difference = (ten.log10() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn log10(self) -> Self; - - /// Converts radians to degrees. - /// - /// ``` - /// use std::f64::consts; - /// - /// let angle = consts::PI; - /// - /// let abs_difference = (angle.to_degrees() - 180.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - #[inline] - fn to_degrees(self) -> Self { - let halfpi = Self::zero().acos(); - let ninety = Self::from(90u8).unwrap(); - self * ninety / halfpi - } - - /// Converts degrees to radians. - /// - /// ``` - /// use std::f64::consts; - /// - /// let angle = 180.0_f64; - /// - /// let abs_difference = (angle.to_radians() - consts::PI).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - #[inline] - fn to_radians(self) -> Self { - let halfpi = Self::zero().acos(); - let ninety = Self::from(90u8).unwrap(); - self * halfpi / ninety - } - - /// Returns the maximum of the two numbers. - /// - /// ``` - /// use num_traits::Float; - /// - /// let x = 1.0; - /// let y = 2.0; - /// - /// assert_eq!(x.max(y), y); - /// ``` - fn max(self, other: Self) -> Self; - - /// Returns the minimum of the two numbers. - /// - /// ``` - /// use num_traits::Float; - /// - /// let x = 1.0; - /// let y = 2.0; - /// - /// assert_eq!(x.min(y), x); - /// ``` - fn min(self, other: Self) -> Self; - - /// The positive difference of two numbers. - /// - /// * If `self <= other`: `0:0` - /// * Else: `self - other` - /// - /// ``` - /// use num_traits::Float; - /// - /// let x = 3.0; - /// let y = -3.0; - /// - /// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs(); - /// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs(); - /// - /// assert!(abs_difference_x < 1e-10); - /// assert!(abs_difference_y < 1e-10); - /// ``` - fn abs_sub(self, other: Self) -> Self; - - /// Take the cubic root of a number. - /// - /// ``` - /// use num_traits::Float; - /// - /// let x = 8.0; - /// - /// // x^(1/3) - 2 == 0 - /// let abs_difference = (x.cbrt() - 2.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn cbrt(self) -> Self; - - /// Calculate the length of the hypotenuse of a right-angle triangle given - /// legs of length `x` and `y`. - /// - /// ``` - /// use num_traits::Float; - /// - /// let x = 2.0; - /// let y = 3.0; - /// - /// // sqrt(x^2 + y^2) - /// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn hypot(self, other: Self) -> Self; - - /// Computes the sine of a number (in radians). - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let x = f64::consts::PI/2.0; - /// - /// let abs_difference = (x.sin() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn sin(self) -> Self; - - /// Computes the cosine of a number (in radians). - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let x = 2.0*f64::consts::PI; - /// - /// let abs_difference = (x.cos() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn cos(self) -> Self; - - /// Computes the tangent of a number (in radians). - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let x = f64::consts::PI/4.0; - /// let abs_difference = (x.tan() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-14); - /// ``` - fn tan(self) -> Self; - - /// Computes the arcsine of a number. Return value is in radians in - /// the range [-pi/2, pi/2] or NaN if the number is outside the range - /// [-1, 1]. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let f = f64::consts::PI / 2.0; - /// - /// // asin(sin(pi/2)) - /// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn asin(self) -> Self; - - /// Computes the arccosine of a number. Return value is in radians in - /// the range [0, pi] or NaN if the number is outside the range - /// [-1, 1]. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let f = f64::consts::PI / 4.0; - /// - /// // acos(cos(pi/4)) - /// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn acos(self) -> Self; - - /// Computes the arctangent of a number. Return value is in radians in the - /// range [-pi/2, pi/2]; - /// - /// ``` - /// use num_traits::Float; - /// - /// let f = 1.0; - /// - /// // atan(tan(1)) - /// let abs_difference = (f.tan().atan() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn atan(self) -> Self; - - /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`). - /// - /// * `x = 0`, `y = 0`: `0` - /// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]` - /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]` - /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)` - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let pi = f64::consts::PI; - /// // All angles from horizontal right (+x) - /// // 45 deg counter-clockwise - /// let x1 = 3.0; - /// let y1 = -3.0; - /// - /// // 135 deg clockwise - /// let x2 = -3.0; - /// let y2 = 3.0; - /// - /// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs(); - /// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs(); - /// - /// assert!(abs_difference_1 < 1e-10); - /// assert!(abs_difference_2 < 1e-10); - /// ``` - fn atan2(self, other: Self) -> Self; - - /// Simultaneously computes the sine and cosine of the number, `x`. Returns - /// `(sin(x), cos(x))`. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let x = f64::consts::PI/4.0; - /// let f = x.sin_cos(); - /// - /// let abs_difference_0 = (f.0 - x.sin()).abs(); - /// let abs_difference_1 = (f.1 - x.cos()).abs(); - /// - /// assert!(abs_difference_0 < 1e-10); - /// assert!(abs_difference_0 < 1e-10); - /// ``` - fn sin_cos(self) -> (Self, Self); - - /// Returns `e^(self) - 1` in a way that is accurate even if the - /// number is close to zero. - /// - /// ``` - /// use num_traits::Float; - /// - /// let x = 7.0; - /// - /// // e^(ln(7)) - 1 - /// let abs_difference = (x.ln().exp_m1() - 6.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn exp_m1(self) -> Self; - - /// Returns `ln(1+n)` (natural logarithm) more accurately than if - /// the operations were performed separately. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let x = f64::consts::E - 1.0; - /// - /// // ln(1 + (e - 1)) == ln(e) == 1 - /// let abs_difference = (x.ln_1p() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn ln_1p(self) -> Self; - - /// Hyperbolic sine function. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let e = f64::consts::E; - /// let x = 1.0; - /// - /// let f = x.sinh(); - /// // Solving sinh() at 1 gives `(e^2-1)/(2e)` - /// let g = (e*e - 1.0)/(2.0*e); - /// let abs_difference = (f - g).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn sinh(self) -> Self; - - /// Hyperbolic cosine function. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let e = f64::consts::E; - /// let x = 1.0; - /// let f = x.cosh(); - /// // Solving cosh() at 1 gives this result - /// let g = (e*e + 1.0)/(2.0*e); - /// let abs_difference = (f - g).abs(); - /// - /// // Same result - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn cosh(self) -> Self; - - /// Hyperbolic tangent function. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let e = f64::consts::E; - /// let x = 1.0; - /// - /// let f = x.tanh(); - /// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))` - /// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2)); - /// let abs_difference = (f - g).abs(); - /// - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn tanh(self) -> Self; - - /// Inverse hyperbolic sine function. - /// - /// ``` - /// use num_traits::Float; - /// - /// let x = 1.0; - /// let f = x.sinh().asinh(); - /// - /// let abs_difference = (f - x).abs(); - /// - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn asinh(self) -> Self; - - /// Inverse hyperbolic cosine function. - /// - /// ``` - /// use num_traits::Float; - /// - /// let x = 1.0; - /// let f = x.cosh().acosh(); - /// - /// let abs_difference = (f - x).abs(); - /// - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn acosh(self) -> Self; - - /// Inverse hyperbolic tangent function. - /// - /// ``` - /// use num_traits::Float; - /// use std::f64; - /// - /// let e = f64::consts::E; - /// let f = e.tanh().atanh(); - /// - /// let abs_difference = (f - e).abs(); - /// - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn atanh(self) -> Self; - - - /// Returns the mantissa, base 2 exponent, and sign as integers, respectively. - /// The original number can be recovered by `sign * mantissa * 2 ^ exponent`. - /// The floating point encoding is documented in the [Reference][floating-point]. - /// - /// ``` - /// use num_traits::Float; - /// - /// let num = 2.0f32; - /// - /// // (8388608, -22, 1) - /// let (mantissa, exponent, sign) = Float::integer_decode(num); - /// let sign_f = sign as f32; - /// let mantissa_f = mantissa as f32; - /// let exponent_f = num.powf(exponent as f32); - /// - /// // 1 * 8388608 * 2^(-22) == 2 - /// let abs_difference = (sign_f * mantissa_f * exponent_f - num).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - /// [floating-point]: ../../../../../reference.html#machine-types - fn integer_decode(self) -> (u64, i16, i8); -} - -#[cfg(feature = "std")] -macro_rules! float_impl { - ($T:ident $decode:ident) => ( - impl Float for $T { - #[inline] - fn nan() -> Self { - ::std::$T::NAN - } - - #[inline] - fn infinity() -> Self { - ::std::$T::INFINITY - } - - #[inline] - fn neg_infinity() -> Self { - ::std::$T::NEG_INFINITY - } - - #[inline] - fn neg_zero() -> Self { - -0.0 - } - - #[inline] - fn min_value() -> Self { - ::std::$T::MIN - } - - #[inline] - fn min_positive_value() -> Self { - ::std::$T::MIN_POSITIVE - } - - #[inline] - fn epsilon() -> Self { - ::std::$T::EPSILON - } - - #[inline] - fn max_value() -> Self { - ::std::$T::MAX - } - - #[inline] - fn is_nan(self) -> bool { - <$T>::is_nan(self) - } - - #[inline] - fn is_infinite(self) -> bool { - <$T>::is_infinite(self) - } - - #[inline] - fn is_finite(self) -> bool { - <$T>::is_finite(self) - } - - #[inline] - fn is_normal(self) -> bool { - <$T>::is_normal(self) - } - - #[inline] - fn classify(self) -> FpCategory { - <$T>::classify(self) - } - - #[inline] - fn floor(self) -> Self { - <$T>::floor(self) - } - - #[inline] - fn ceil(self) -> Self { - <$T>::ceil(self) - } - - #[inline] - fn round(self) -> Self { - <$T>::round(self) - } - - #[inline] - fn trunc(self) -> Self { - <$T>::trunc(self) - } - - #[inline] - fn fract(self) -> Self { - <$T>::fract(self) - } - - #[inline] - fn abs(self) -> Self { - <$T>::abs(self) - } - - #[inline] - fn signum(self) -> Self { - <$T>::signum(self) - } - - #[inline] - fn is_sign_positive(self) -> bool { - <$T>::is_sign_positive(self) - } - - #[inline] - fn is_sign_negative(self) -> bool { - <$T>::is_sign_negative(self) - } - - #[inline] - fn mul_add(self, a: Self, b: Self) -> Self { - <$T>::mul_add(self, a, b) - } - - #[inline] - fn recip(self) -> Self { - <$T>::recip(self) - } - - #[inline] - fn powi(self, n: i32) -> Self { - <$T>::powi(self, n) - } - - #[inline] - fn powf(self, n: Self) -> Self { - <$T>::powf(self, n) - } - - #[inline] - fn sqrt(self) -> Self { - <$T>::sqrt(self) - } - - #[inline] - fn exp(self) -> Self { - <$T>::exp(self) - } - - #[inline] - fn exp2(self) -> Self { - <$T>::exp2(self) - } - - #[inline] - fn ln(self) -> Self { - <$T>::ln(self) - } - - #[inline] - fn log(self, base: Self) -> Self { - <$T>::log(self, base) - } - - #[inline] - fn log2(self) -> Self { - <$T>::log2(self) - } - - #[inline] - fn log10(self) -> Self { - <$T>::log10(self) - } - - #[inline] - fn to_degrees(self) -> Self { - // NB: `f32` didn't stabilize this until 1.7 - // <$T>::to_degrees(self) - self * (180. / ::std::$T::consts::PI) - } - - #[inline] - fn to_radians(self) -> Self { - // NB: `f32` didn't stabilize this until 1.7 - // <$T>::to_radians(self) - self * (::std::$T::consts::PI / 180.) - } - - #[inline] - fn max(self, other: Self) -> Self { - <$T>::max(self, other) - } - - #[inline] - fn min(self, other: Self) -> Self { - <$T>::min(self, other) - } - - #[inline] - #[allow(deprecated)] - fn abs_sub(self, other: Self) -> Self { - <$T>::abs_sub(self, other) - } - - #[inline] - fn cbrt(self) -> Self { - <$T>::cbrt(self) - } - - #[inline] - fn hypot(self, other: Self) -> Self { - <$T>::hypot(self, other) - } - - #[inline] - fn sin(self) -> Self { - <$T>::sin(self) - } - - #[inline] - fn cos(self) -> Self { - <$T>::cos(self) - } - - #[inline] - fn tan(self) -> Self { - <$T>::tan(self) - } - - #[inline] - fn asin(self) -> Self { - <$T>::asin(self) - } - - #[inline] - fn acos(self) -> Self { - <$T>::acos(self) - } - - #[inline] - fn atan(self) -> Self { - <$T>::atan(self) - } - - #[inline] - fn atan2(self, other: Self) -> Self { - <$T>::atan2(self, other) - } - - #[inline] - fn sin_cos(self) -> (Self, Self) { - <$T>::sin_cos(self) - } - - #[inline] - fn exp_m1(self) -> Self { - <$T>::exp_m1(self) - } - - #[inline] - fn ln_1p(self) -> Self { - <$T>::ln_1p(self) - } - - #[inline] - fn sinh(self) -> Self { - <$T>::sinh(self) - } - - #[inline] - fn cosh(self) -> Self { - <$T>::cosh(self) - } - - #[inline] - fn tanh(self) -> Self { - <$T>::tanh(self) - } - - #[inline] - fn asinh(self) -> Self { - <$T>::asinh(self) - } - - #[inline] - fn acosh(self) -> Self { - <$T>::acosh(self) - } - - #[inline] - fn atanh(self) -> Self { - <$T>::atanh(self) - } - - #[inline] - fn integer_decode(self) -> (u64, i16, i8) { - $decode(self) - } - } - ) -} - -#[cfg(feature = "std")] -fn integer_decode_f32(f: f32) -> (u64, i16, i8) { - let bits: u32 = unsafe { mem::transmute(f) }; - let sign: i8 = if bits >> 31 == 0 { - 1 - } else { - -1 - }; - let mut exponent: i16 = ((bits >> 23) & 0xff) as i16; - let mantissa = if exponent == 0 { - (bits & 0x7fffff) << 1 - } else { - (bits & 0x7fffff) | 0x800000 - }; - // Exponent bias + mantissa shift - exponent -= 127 + 23; - (mantissa as u64, exponent, sign) -} - -#[cfg(feature = "std")] -fn integer_decode_f64(f: f64) -> (u64, i16, i8) { - let bits: u64 = unsafe { mem::transmute(f) }; - let sign: i8 = if bits >> 63 == 0 { - 1 - } else { - -1 - }; - let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; - let mantissa = if exponent == 0 { - (bits & 0xfffffffffffff) << 1 - } else { - (bits & 0xfffffffffffff) | 0x10000000000000 - }; - // Exponent bias + mantissa shift - exponent -= 1023 + 52; - (mantissa, exponent, sign) -} - -#[cfg(feature = "std")] -float_impl!(f32 integer_decode_f32); -#[cfg(feature = "std")] -float_impl!(f64 integer_decode_f64); - -macro_rules! float_const_impl { - ($(#[$doc:meta] $constant:ident,)+) => ( - #[allow(non_snake_case)] - pub trait FloatConst { - $(#[$doc] fn $constant() -> Self;)+ - } - float_const_impl! { @float f32, $($constant,)+ } - float_const_impl! { @float f64, $($constant,)+ } - ); - (@float $T:ident, $($constant:ident,)+) => ( - impl FloatConst for $T { - $( - #[inline] - fn $constant() -> Self { - ::core::$T::consts::$constant - } - )+ - } - ); -} - -float_const_impl! { - #[doc = "Return Euler’s number."] - E, - #[doc = "Return `1.0 / π`."] - FRAC_1_PI, - #[doc = "Return `1.0 / sqrt(2.0)`."] - FRAC_1_SQRT_2, - #[doc = "Return `2.0 / π`."] - FRAC_2_PI, - #[doc = "Return `2.0 / sqrt(π)`."] - FRAC_2_SQRT_PI, - #[doc = "Return `π / 2.0`."] - FRAC_PI_2, - #[doc = "Return `π / 3.0`."] - FRAC_PI_3, - #[doc = "Return `π / 4.0`."] - FRAC_PI_4, - #[doc = "Return `π / 6.0`."] - FRAC_PI_6, - #[doc = "Return `π / 8.0`."] - FRAC_PI_8, - #[doc = "Return `ln(10.0)`."] - LN_10, - #[doc = "Return `ln(2.0)`."] - LN_2, - #[doc = "Return `log10(e)`."] - LOG10_E, - #[doc = "Return `log2(e)`."] - LOG2_E, - #[doc = "Return Archimedes’ constant."] - PI, - #[doc = "Return `sqrt(2.0)`."] - SQRT_2, -} - -#[cfg(all(test, feature = "std"))] -mod tests { - use Float; - - #[test] - fn convert_deg_rad() { - use core::f64::consts; - - const DEG_RAD_PAIRS: [(f64, f64); 7] = [ - (0.0, 0.), - (22.5, consts::FRAC_PI_8), - (30.0, consts::FRAC_PI_6), - (45.0, consts::FRAC_PI_4), - (60.0, consts::FRAC_PI_3), - (90.0, consts::FRAC_PI_2), - (180.0, consts::PI), - ]; - - for &(deg, rad) in &DEG_RAD_PAIRS { - assert!((Float::to_degrees(rad) - deg).abs() < 1e-6); - assert!((Float::to_radians(deg) - rad).abs() < 1e-6); - - let (deg, rad) = (deg as f32, rad as f32); - assert!((Float::to_degrees(rad) - deg).abs() < 1e-6); - assert!((Float::to_radians(deg) - rad).abs() < 1e-6); - } - } -} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/identities.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/identities.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/identities.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/identities.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,148 +0,0 @@ -use core::ops::{Add, Mul}; -use core::num::Wrapping; - -/// Defines an additive identity element for `Self`. -pub trait Zero: Sized + Add { - /// Returns the additive identity element of `Self`, `0`. - /// - /// # Laws - /// - /// ```{.text} - /// a + 0 = a ∀ a ∈ Self - /// 0 + a = a ∀ a ∈ Self - /// ``` - /// - /// # Purity - /// - /// This function should return the same result at all times regardless of - /// external mutable state, for example values stored in TLS or in - /// `static mut`s. - // FIXME (#5527): This should be an associated constant - fn zero() -> Self; - - /// Returns `true` if `self` is equal to the additive identity. - #[inline] - fn is_zero(&self) -> bool; -} - -macro_rules! zero_impl { - ($t:ty, $v:expr) => { - impl Zero for $t { - #[inline] - fn zero() -> $t { $v } - #[inline] - fn is_zero(&self) -> bool { *self == $v } - } - } -} - -zero_impl!(usize, 0usize); -zero_impl!(u8, 0u8); -zero_impl!(u16, 0u16); -zero_impl!(u32, 0u32); -zero_impl!(u64, 0u64); - -zero_impl!(isize, 0isize); -zero_impl!(i8, 0i8); -zero_impl!(i16, 0i16); -zero_impl!(i32, 0i32); -zero_impl!(i64, 0i64); - -zero_impl!(f32, 0.0f32); -zero_impl!(f64, 0.0f64); - -impl Zero for Wrapping where Wrapping: Add> { - fn is_zero(&self) -> bool { - self.0.is_zero() - } - fn zero() -> Self { - Wrapping(T::zero()) - } -} - - -/// Defines a multiplicative identity element for `Self`. -pub trait One: Sized + Mul { - /// Returns the multiplicative identity element of `Self`, `1`. - /// - /// # Laws - /// - /// ```{.text} - /// a * 1 = a ∀ a ∈ Self - /// 1 * a = a ∀ a ∈ Self - /// ``` - /// - /// # Purity - /// - /// This function should return the same result at all times regardless of - /// external mutable state, for example values stored in TLS or in - /// `static mut`s. - // FIXME (#5527): This should be an associated constant - fn one() -> Self; -} - -macro_rules! one_impl { - ($t:ty, $v:expr) => { - impl One for $t { - #[inline] - fn one() -> $t { $v } - } - } -} - -one_impl!(usize, 1usize); -one_impl!(u8, 1u8); -one_impl!(u16, 1u16); -one_impl!(u32, 1u32); -one_impl!(u64, 1u64); - -one_impl!(isize, 1isize); -one_impl!(i8, 1i8); -one_impl!(i16, 1i16); -one_impl!(i32, 1i32); -one_impl!(i64, 1i64); - -one_impl!(f32, 1.0f32); -one_impl!(f64, 1.0f64); - -impl One for Wrapping where Wrapping: Mul> { - fn one() -> Self { - Wrapping(T::one()) - } -} - -// Some helper functions provided for backwards compatibility. - -/// Returns the additive identity, `0`. -#[inline(always)] pub fn zero() -> T { Zero::zero() } - -/// Returns the multiplicative identity, `1`. -#[inline(always)] pub fn one() -> T { One::one() } - - -#[test] -fn wrapping_identities() { - macro_rules! test_wrapping_identities { - ($($t:ty)+) => { - $( - assert_eq!(zero::<$t>(), zero::>().0); - assert_eq!(one::<$t>(), one::>().0); - assert_eq!((0 as $t).is_zero(), Wrapping(0 as $t).is_zero()); - assert_eq!((1 as $t).is_zero(), Wrapping(1 as $t).is_zero()); - )+ - }; - } - - test_wrapping_identities!(isize i8 i16 i32 i64 usize u8 u16 u32 u64); -} - -#[test] -fn wrapping_is_zero() { - fn require_zero(_: &T) {} - require_zero(&Wrapping(42)); -} -#[test] -fn wrapping_is_one() { - fn require_one(_: &T) {} - require_one(&Wrapping(42)); -} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/int.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/int.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/int.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/int.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,376 +0,0 @@ -use core::ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr}; - -use {Num, NumCast}; -use bounds::Bounded; -use ops::checked::*; -use ops::saturating::Saturating; - -pub trait PrimInt - : Sized - + Copy - + Num + NumCast - + Bounded - + PartialOrd + Ord + Eq - + Not - + BitAnd - + BitOr - + BitXor - + Shl - + Shr - + CheckedAdd - + CheckedSub - + CheckedMul - + CheckedDiv - + Saturating -{ - /// Returns the number of ones in the binary representation of `self`. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0b01001100u8; - /// - /// assert_eq!(n.count_ones(), 3); - /// ``` - fn count_ones(self) -> u32; - - /// Returns the number of zeros in the binary representation of `self`. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0b01001100u8; - /// - /// assert_eq!(n.count_zeros(), 5); - /// ``` - fn count_zeros(self) -> u32; - - /// Returns the number of leading zeros in the binary representation - /// of `self`. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0b0101000u16; - /// - /// assert_eq!(n.leading_zeros(), 10); - /// ``` - fn leading_zeros(self) -> u32; - - /// Returns the number of trailing zeros in the binary representation - /// of `self`. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0b0101000u16; - /// - /// assert_eq!(n.trailing_zeros(), 3); - /// ``` - fn trailing_zeros(self) -> u32; - - /// Shifts the bits to the left by a specified amount amount, `n`, wrapping - /// the truncated bits to the end of the resulting integer. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// let m = 0x3456789ABCDEF012u64; - /// - /// assert_eq!(n.rotate_left(12), m); - /// ``` - fn rotate_left(self, n: u32) -> Self; - - /// Shifts the bits to the right by a specified amount amount, `n`, wrapping - /// the truncated bits to the beginning of the resulting integer. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// let m = 0xDEF0123456789ABCu64; - /// - /// assert_eq!(n.rotate_right(12), m); - /// ``` - fn rotate_right(self, n: u32) -> Self; - - /// Shifts the bits to the left by a specified amount amount, `n`, filling - /// zeros in the least significant bits. - /// - /// This is bitwise equivalent to signed `Shl`. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// let m = 0x3456789ABCDEF000u64; - /// - /// assert_eq!(n.signed_shl(12), m); - /// ``` - fn signed_shl(self, n: u32) -> Self; - - /// Shifts the bits to the right by a specified amount amount, `n`, copying - /// the "sign bit" in the most significant bits even for unsigned types. - /// - /// This is bitwise equivalent to signed `Shr`. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0xFEDCBA9876543210u64; - /// let m = 0xFFFFEDCBA9876543u64; - /// - /// assert_eq!(n.signed_shr(12), m); - /// ``` - fn signed_shr(self, n: u32) -> Self; - - /// Shifts the bits to the left by a specified amount amount, `n`, filling - /// zeros in the least significant bits. - /// - /// This is bitwise equivalent to unsigned `Shl`. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFi64; - /// let m = 0x3456789ABCDEF000i64; - /// - /// assert_eq!(n.unsigned_shl(12), m); - /// ``` - fn unsigned_shl(self, n: u32) -> Self; - - /// Shifts the bits to the right by a specified amount amount, `n`, filling - /// zeros in the most significant bits. - /// - /// This is bitwise equivalent to unsigned `Shr`. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0xFEDCBA9876543210i64; - /// let m = 0x000FEDCBA9876543i64; - /// - /// assert_eq!(n.unsigned_shr(12), m); - /// ``` - fn unsigned_shr(self, n: u32) -> Self; - - /// Reverses the byte order of the integer. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// let m = 0xEFCDAB8967452301u64; - /// - /// assert_eq!(n.swap_bytes(), m); - /// ``` - fn swap_bytes(self) -> Self; - - /// Convert an integer from big endian to the target's endianness. - /// - /// On big endian this is a no-op. On little endian the bytes are swapped. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// - /// if cfg!(target_endian = "big") { - /// assert_eq!(u64::from_be(n), n) - /// } else { - /// assert_eq!(u64::from_be(n), n.swap_bytes()) - /// } - /// ``` - fn from_be(x: Self) -> Self; - - /// Convert an integer from little endian to the target's endianness. - /// - /// On little endian this is a no-op. On big endian the bytes are swapped. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// - /// if cfg!(target_endian = "little") { - /// assert_eq!(u64::from_le(n), n) - /// } else { - /// assert_eq!(u64::from_le(n), n.swap_bytes()) - /// } - /// ``` - fn from_le(x: Self) -> Self; - - /// Convert `self` to big endian from the target's endianness. - /// - /// On big endian this is a no-op. On little endian the bytes are swapped. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// - /// if cfg!(target_endian = "big") { - /// assert_eq!(n.to_be(), n) - /// } else { - /// assert_eq!(n.to_be(), n.swap_bytes()) - /// } - /// ``` - fn to_be(self) -> Self; - - /// Convert `self` to little endian from the target's endianness. - /// - /// On little endian this is a no-op. On big endian the bytes are swapped. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// let n = 0x0123456789ABCDEFu64; - /// - /// if cfg!(target_endian = "little") { - /// assert_eq!(n.to_le(), n) - /// } else { - /// assert_eq!(n.to_le(), n.swap_bytes()) - /// } - /// ``` - fn to_le(self) -> Self; - - /// Raises self to the power of `exp`, using exponentiation by squaring. - /// - /// # Examples - /// - /// ``` - /// use num_traits::PrimInt; - /// - /// assert_eq!(2i32.pow(4), 16); - /// ``` - fn pow(self, exp: u32) -> Self; -} - -macro_rules! prim_int_impl { - ($T:ty, $S:ty, $U:ty) => ( - impl PrimInt for $T { - #[inline] - fn count_ones(self) -> u32 { - <$T>::count_ones(self) - } - - #[inline] - fn count_zeros(self) -> u32 { - <$T>::count_zeros(self) - } - - #[inline] - fn leading_zeros(self) -> u32 { - <$T>::leading_zeros(self) - } - - #[inline] - fn trailing_zeros(self) -> u32 { - <$T>::trailing_zeros(self) - } - - #[inline] - fn rotate_left(self, n: u32) -> Self { - <$T>::rotate_left(self, n) - } - - #[inline] - fn rotate_right(self, n: u32) -> Self { - <$T>::rotate_right(self, n) - } - - #[inline] - fn signed_shl(self, n: u32) -> Self { - ((self as $S) << n) as $T - } - - #[inline] - fn signed_shr(self, n: u32) -> Self { - ((self as $S) >> n) as $T - } - - #[inline] - fn unsigned_shl(self, n: u32) -> Self { - ((self as $U) << n) as $T - } - - #[inline] - fn unsigned_shr(self, n: u32) -> Self { - ((self as $U) >> n) as $T - } - - #[inline] - fn swap_bytes(self) -> Self { - <$T>::swap_bytes(self) - } - - #[inline] - fn from_be(x: Self) -> Self { - <$T>::from_be(x) - } - - #[inline] - fn from_le(x: Self) -> Self { - <$T>::from_le(x) - } - - #[inline] - fn to_be(self) -> Self { - <$T>::to_be(self) - } - - #[inline] - fn to_le(self) -> Self { - <$T>::to_le(self) - } - - #[inline] - fn pow(self, exp: u32) -> Self { - <$T>::pow(self, exp) - } - } - ) -} - -// prim_int_impl!(type, signed, unsigned); -prim_int_impl!(u8, i8, u8); -prim_int_impl!(u16, i16, u16); -prim_int_impl!(u32, i32, u32); -prim_int_impl!(u64, i64, u64); -prim_int_impl!(usize, isize, usize); -prim_int_impl!(i8, i8, u8); -prim_int_impl!(i16, i16, u16); -prim_int_impl!(i32, i32, u32); -prim_int_impl!(i64, i64, u64); -prim_int_impl!(isize, isize, usize); diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/lib.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/lib.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,468 +0,0 @@ -// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Numeric traits for generic mathematics -//! -//! ## Compatibility -//! -//! The `num-traits` crate is tested for rustc 1.8 and greater. - -#![doc(html_root_url = "https://docs.rs/num-traits/0.2")] - -#![deny(unconditional_recursion)] - -#![cfg_attr(not(feature = "std"), no_std)] -#[cfg(feature = "std")] -extern crate core; - -use core::ops::{Add, Sub, Mul, Div, Rem}; -use core::ops::{AddAssign, SubAssign, MulAssign, DivAssign, RemAssign}; -use core::num::Wrapping; -use core::fmt; - -pub use bounds::Bounded; -#[cfg(feature = "std")] -pub use float::Float; -pub use float::FloatConst; -// pub use real::Real; // NOTE: Don't do this, it breaks `use num_traits::*;`. -pub use identities::{Zero, One, zero, one}; -pub use ops::checked::{CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, CheckedShl, CheckedShr}; -pub use ops::wrapping::{WrappingAdd, WrappingMul, WrappingSub}; -pub use ops::saturating::Saturating; -pub use sign::{Signed, Unsigned, abs, abs_sub, signum}; -pub use cast::{AsPrimitive, FromPrimitive, ToPrimitive, NumCast, cast}; -pub use int::PrimInt; -pub use pow::{pow, checked_pow}; - -pub mod identities; -pub mod sign; -pub mod ops; -pub mod bounds; -pub mod float; -#[cfg(feature = "std")] -pub mod real; -pub mod cast; -pub mod int; -pub mod pow; - -/// The base trait for numeric types, covering `0` and `1` values, -/// comparisons, basic numeric operations, and string conversion. -pub trait Num: PartialEq + Zero + One + NumOps -{ - type FromStrRadixErr; - - /// Convert from a string and radix <= 36. - /// - /// # Examples - /// - /// ```rust - /// use num_traits::Num; - /// - /// let result = ::from_str_radix("27", 10); - /// assert_eq!(result, Ok(27)); - /// - /// let result = ::from_str_radix("foo", 10); - /// assert!(result.is_err()); - /// ``` - fn from_str_radix(str: &str, radix: u32) -> Result; -} - -/// The trait for types implementing basic numeric operations -/// -/// This is automatically implemented for types which implement the operators. -pub trait NumOps - : Add - + Sub - + Mul - + Div - + Rem -{} - -impl NumOps for T -where T: Add - + Sub - + Mul - + Div - + Rem -{} - -/// The trait for `Num` types which also implement numeric operations taking -/// the second operand by reference. -/// -/// This is automatically implemented for types which implement the operators. -pub trait NumRef: Num + for<'r> NumOps<&'r Self> {} -impl NumRef for T where T: Num + for<'r> NumOps<&'r T> {} - -/// The trait for references which implement numeric operations, taking the -/// second operand either by value or by reference. -/// -/// This is automatically implemented for types which implement the operators. -pub trait RefNum: NumOps + for<'r> NumOps<&'r Base, Base> {} -impl RefNum for T where T: NumOps + for<'r> NumOps<&'r Base, Base> {} - -/// The trait for types implementing numeric assignment operators (like `+=`). -/// -/// This is automatically implemented for types which implement the operators. -pub trait NumAssignOps - : AddAssign - + SubAssign - + MulAssign - + DivAssign - + RemAssign -{} - -impl NumAssignOps for T -where T: AddAssign - + SubAssign - + MulAssign - + DivAssign - + RemAssign -{} - -/// The trait for `Num` types which also implement assignment operators. -/// -/// This is automatically implemented for types which implement the operators. -pub trait NumAssign: Num + NumAssignOps {} -impl NumAssign for T where T: Num + NumAssignOps {} - -/// The trait for `NumAssign` types which also implement assignment operations -/// taking the second operand by reference. -/// -/// This is automatically implemented for types which implement the operators. -pub trait NumAssignRef: NumAssign + for<'r> NumAssignOps<&'r Self> {} -impl NumAssignRef for T where T: NumAssign + for<'r> NumAssignOps<&'r T> {} - - -macro_rules! int_trait_impl { - ($name:ident for $($t:ty)*) => ($( - impl $name for $t { - type FromStrRadixErr = ::core::num::ParseIntError; - #[inline] - fn from_str_radix(s: &str, radix: u32) - -> Result - { - <$t>::from_str_radix(s, radix) - } - } - )*) -} -int_trait_impl!(Num for usize u8 u16 u32 u64 isize i8 i16 i32 i64); - -impl Num for Wrapping - where Wrapping: - Add> + Sub> - + Mul> + Div> + Rem> -{ - type FromStrRadixErr = T::FromStrRadixErr; - fn from_str_radix(str: &str, radix: u32) -> Result { - T::from_str_radix(str, radix).map(Wrapping) - } -} - - -#[derive(Debug)] -pub enum FloatErrorKind { - Empty, - Invalid, -} -// FIXME: core::num::ParseFloatError is stable in 1.0, but opaque to us, -// so there's not really any way for us to reuse it. -#[derive(Debug)] -pub struct ParseFloatError { - pub kind: FloatErrorKind, -} - -impl fmt::Display for ParseFloatError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let description = match self.kind { - FloatErrorKind::Empty => "cannot parse float from empty string", - FloatErrorKind::Invalid => "invalid float literal", - }; - - description.fmt(f) - } -} - -// FIXME: The standard library from_str_radix on floats was deprecated, so we're stuck -// with this implementation ourselves until we want to make a breaking change. -// (would have to drop it from `Num` though) -macro_rules! float_trait_impl { - ($name:ident for $($t:ident)*) => ($( - impl $name for $t { - type FromStrRadixErr = ParseFloatError; - - fn from_str_radix(src: &str, radix: u32) - -> Result - { - use self::FloatErrorKind::*; - use self::ParseFloatError as PFE; - - // Special values - match src { - "inf" => return Ok(core::$t::INFINITY), - "-inf" => return Ok(core::$t::NEG_INFINITY), - "NaN" => return Ok(core::$t::NAN), - _ => {}, - } - - fn slice_shift_char(src: &str) -> Option<(char, &str)> { - src.chars().nth(0).map(|ch| (ch, &src[1..])) - } - - let (is_positive, src) = match slice_shift_char(src) { - None => return Err(PFE { kind: Empty }), - Some(('-', "")) => return Err(PFE { kind: Empty }), - Some(('-', src)) => (false, src), - Some((_, _)) => (true, src), - }; - - // The significand to accumulate - let mut sig = if is_positive { 0.0 } else { -0.0 }; - // Necessary to detect overflow - let mut prev_sig = sig; - let mut cs = src.chars().enumerate(); - // Exponent prefix and exponent index offset - let mut exp_info = None::<(char, usize)>; - - // Parse the integer part of the significand - for (i, c) in cs.by_ref() { - match c.to_digit(radix) { - Some(digit) => { - // shift significand one digit left - sig = sig * (radix as $t); - - // add/subtract current digit depending on sign - if is_positive { - sig = sig + ((digit as isize) as $t); - } else { - sig = sig - ((digit as isize) as $t); - } - - // Detect overflow by comparing to last value, except - // if we've not seen any non-zero digits. - if prev_sig != 0.0 { - if is_positive && sig <= prev_sig - { return Ok(core::$t::INFINITY); } - if !is_positive && sig >= prev_sig - { return Ok(core::$t::NEG_INFINITY); } - - // Detect overflow by reversing the shift-and-add process - if is_positive && (prev_sig != (sig - digit as $t) / radix as $t) - { return Ok(core::$t::INFINITY); } - if !is_positive && (prev_sig != (sig + digit as $t) / radix as $t) - { return Ok(core::$t::NEG_INFINITY); } - } - prev_sig = sig; - }, - None => match c { - 'e' | 'E' | 'p' | 'P' => { - exp_info = Some((c, i + 1)); - break; // start of exponent - }, - '.' => { - break; // start of fractional part - }, - _ => { - return Err(PFE { kind: Invalid }); - }, - }, - } - } - - // If we are not yet at the exponent parse the fractional - // part of the significand - if exp_info.is_none() { - let mut power = 1.0; - for (i, c) in cs.by_ref() { - match c.to_digit(radix) { - Some(digit) => { - // Decrease power one order of magnitude - power = power / (radix as $t); - // add/subtract current digit depending on sign - sig = if is_positive { - sig + (digit as $t) * power - } else { - sig - (digit as $t) * power - }; - // Detect overflow by comparing to last value - if is_positive && sig < prev_sig - { return Ok(core::$t::INFINITY); } - if !is_positive && sig > prev_sig - { return Ok(core::$t::NEG_INFINITY); } - prev_sig = sig; - }, - None => match c { - 'e' | 'E' | 'p' | 'P' => { - exp_info = Some((c, i + 1)); - break; // start of exponent - }, - _ => { - return Err(PFE { kind: Invalid }); - }, - }, - } - } - } - - // Parse and calculate the exponent - let exp = match exp_info { - Some((c, offset)) => { - let base = match c { - 'E' | 'e' if radix == 10 => 10.0, - 'P' | 'p' if radix == 16 => 2.0, - _ => return Err(PFE { kind: Invalid }), - }; - - // Parse the exponent as decimal integer - let src = &src[offset..]; - let (is_positive, exp) = match slice_shift_char(src) { - Some(('-', src)) => (false, src.parse::()), - Some(('+', src)) => (true, src.parse::()), - Some((_, _)) => (true, src.parse::()), - None => return Err(PFE { kind: Invalid }), - }; - - #[cfg(feature = "std")] - fn pow(base: $t, exp: usize) -> $t { - Float::powi(base, exp as i32) - } - // otherwise uses the generic `pow` from the root - - match (is_positive, exp) { - (true, Ok(exp)) => pow(base, exp), - (false, Ok(exp)) => 1.0 / pow(base, exp), - (_, Err(_)) => return Err(PFE { kind: Invalid }), - } - }, - None => 1.0, // no exponent - }; - - Ok(sig * exp) - } - } - )*) -} -float_trait_impl!(Num for f32 f64); - -/// A value bounded by a minimum and a maximum -/// -/// If input is less than min then this returns min. -/// If input is greater than max then this returns max. -/// Otherwise this returns input. -#[inline] -pub fn clamp(input: T, min: T, max: T) -> T { - debug_assert!(min <= max, "min must be less than or equal to max"); - if input < min { - min - } else if input > max { - max - } else { - input - } -} - -#[test] -fn clamp_test() { - // Int test - assert_eq!(1, clamp(1, -1, 2)); - assert_eq!(-1, clamp(-2, -1, 2)); - assert_eq!(2, clamp(3, -1, 2)); - - // Float test - assert_eq!(1.0, clamp(1.0, -1.0, 2.0)); - assert_eq!(-1.0, clamp(-2.0, -1.0, 2.0)); - assert_eq!(2.0, clamp(3.0, -1.0, 2.0)); -} - -#[test] -fn from_str_radix_unwrap() { - // The Result error must impl Debug to allow unwrap() - - let i: i32 = Num::from_str_radix("0", 10).unwrap(); - assert_eq!(i, 0); - - let f: f32 = Num::from_str_radix("0.0", 10).unwrap(); - assert_eq!(f, 0.0); -} - -#[test] -fn wrapping_is_num() { - fn require_num(_: &T) {} - require_num(&Wrapping(42_u32)); - require_num(&Wrapping(-42)); -} - -#[test] -fn wrapping_from_str_radix() { - macro_rules! test_wrapping_from_str_radix { - ($($t:ty)+) => { - $( - for &(s, r) in &[("42", 10), ("42", 2), ("-13.0", 10), ("foo", 10)] { - let w = Wrapping::<$t>::from_str_radix(s, r).map(|w| w.0); - assert_eq!(w, <$t as Num>::from_str_radix(s, r)); - } - )+ - }; - } - - test_wrapping_from_str_radix!(usize u8 u16 u32 u64 isize i8 i16 i32 i64); -} - -#[test] -fn check_num_ops() { - fn compute(x: T, y: T) -> T { - x * y / y % y + y - y - } - assert_eq!(compute(1, 2), 1) -} - -#[test] -fn check_numref_ops() { - fn compute(x: T, y: &T) -> T { - x * y / y % y + y - y - } - assert_eq!(compute(1, &2), 1) -} - -#[test] -fn check_refnum_ops() { - fn compute(x: &T, y: T) -> T - where for<'a> &'a T: RefNum - { - &(&(&(&(x * y) / y) % y) + y) - y - } - assert_eq!(compute(&1, 2), 1) -} - -#[test] -fn check_refref_ops() { - fn compute(x: &T, y: &T) -> T - where for<'a> &'a T: RefNum - { - &(&(&(&(x * y) / y) % y) + y) - y - } - assert_eq!(compute(&1, &2), 1) -} - -#[test] -fn check_numassign_ops() { - fn compute(mut x: T, y: T) -> T { - x *= y; - x /= y; - x %= y; - x += y; - x -= y; - x - } - assert_eq!(compute(1, 2), 1) -} - -// TODO test `NumAssignRef`, but even the standard numeric types don't -// implement this yet. (see rust pr41336) diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/ops/checked.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/ops/checked.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/ops/checked.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/ops/checked.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,162 +0,0 @@ -use core::ops::{Add, Sub, Mul, Div, Shl, Shr}; - -/// Performs addition that returns `None` instead of wrapping around on -/// overflow. -pub trait CheckedAdd: Sized + Add { - /// Adds two numbers, checking for overflow. If overflow happens, `None` is - /// returned. - fn checked_add(&self, v: &Self) -> Option; -} - -macro_rules! checked_impl { - ($trait_name:ident, $method:ident, $t:ty) => { - impl $trait_name for $t { - #[inline] - fn $method(&self, v: &$t) -> Option<$t> { - <$t>::$method(*self, *v) - } - } - } -} - -checked_impl!(CheckedAdd, checked_add, u8); -checked_impl!(CheckedAdd, checked_add, u16); -checked_impl!(CheckedAdd, checked_add, u32); -checked_impl!(CheckedAdd, checked_add, u64); -checked_impl!(CheckedAdd, checked_add, usize); - -checked_impl!(CheckedAdd, checked_add, i8); -checked_impl!(CheckedAdd, checked_add, i16); -checked_impl!(CheckedAdd, checked_add, i32); -checked_impl!(CheckedAdd, checked_add, i64); -checked_impl!(CheckedAdd, checked_add, isize); - -/// Performs subtraction that returns `None` instead of wrapping around on underflow. -pub trait CheckedSub: Sized + Sub { - /// Subtracts two numbers, checking for underflow. If underflow happens, - /// `None` is returned. - fn checked_sub(&self, v: &Self) -> Option; -} - -checked_impl!(CheckedSub, checked_sub, u8); -checked_impl!(CheckedSub, checked_sub, u16); -checked_impl!(CheckedSub, checked_sub, u32); -checked_impl!(CheckedSub, checked_sub, u64); -checked_impl!(CheckedSub, checked_sub, usize); - -checked_impl!(CheckedSub, checked_sub, i8); -checked_impl!(CheckedSub, checked_sub, i16); -checked_impl!(CheckedSub, checked_sub, i32); -checked_impl!(CheckedSub, checked_sub, i64); -checked_impl!(CheckedSub, checked_sub, isize); - -/// Performs multiplication that returns `None` instead of wrapping around on underflow or -/// overflow. -pub trait CheckedMul: Sized + Mul { - /// Multiplies two numbers, checking for underflow or overflow. If underflow - /// or overflow happens, `None` is returned. - fn checked_mul(&self, v: &Self) -> Option; -} - -checked_impl!(CheckedMul, checked_mul, u8); -checked_impl!(CheckedMul, checked_mul, u16); -checked_impl!(CheckedMul, checked_mul, u32); -checked_impl!(CheckedMul, checked_mul, u64); -checked_impl!(CheckedMul, checked_mul, usize); - -checked_impl!(CheckedMul, checked_mul, i8); -checked_impl!(CheckedMul, checked_mul, i16); -checked_impl!(CheckedMul, checked_mul, i32); -checked_impl!(CheckedMul, checked_mul, i64); -checked_impl!(CheckedMul, checked_mul, isize); - -/// Performs division that returns `None` instead of panicking on division by zero and instead of -/// wrapping around on underflow and overflow. -pub trait CheckedDiv: Sized + Div { - /// Divides two numbers, checking for underflow, overflow and division by - /// zero. If any of that happens, `None` is returned. - fn checked_div(&self, v: &Self) -> Option; -} - -checked_impl!(CheckedDiv, checked_div, u8); -checked_impl!(CheckedDiv, checked_div, u16); -checked_impl!(CheckedDiv, checked_div, u32); -checked_impl!(CheckedDiv, checked_div, u64); -checked_impl!(CheckedDiv, checked_div, usize); - -checked_impl!(CheckedDiv, checked_div, i8); -checked_impl!(CheckedDiv, checked_div, i16); -checked_impl!(CheckedDiv, checked_div, i32); -checked_impl!(CheckedDiv, checked_div, i64); -checked_impl!(CheckedDiv, checked_div, isize); - -/// Performs a left shift that returns `None` on overflow. -pub trait CheckedShl: Sized + Shl { - /// Shifts a number to the left, checking for overflow. If overflow happens, - /// `None` is returned. - /// - /// ``` - /// use num_traits::CheckedShl; - /// - /// let x: u16 = 0x0001; - /// - /// assert_eq!(CheckedShl::checked_shl(&x, 0), Some(0x0001)); - /// assert_eq!(CheckedShl::checked_shl(&x, 1), Some(0x0002)); - /// assert_eq!(CheckedShl::checked_shl(&x, 15), Some(0x8000)); - /// assert_eq!(CheckedShl::checked_shl(&x, 16), None); - /// ``` - fn checked_shl(&self, rhs: u32) -> Option; -} - -macro_rules! checked_shift_impl { - ($trait_name:ident, $method:ident, $t:ty) => { - impl $trait_name for $t { - #[inline] - fn $method(&self, rhs: u32) -> Option<$t> { - <$t>::$method(*self, rhs) - } - } - } -} - -checked_shift_impl!(CheckedShl, checked_shl, u8); -checked_shift_impl!(CheckedShl, checked_shl, u16); -checked_shift_impl!(CheckedShl, checked_shl, u32); -checked_shift_impl!(CheckedShl, checked_shl, u64); -checked_shift_impl!(CheckedShl, checked_shl, usize); - -checked_shift_impl!(CheckedShl, checked_shl, i8); -checked_shift_impl!(CheckedShl, checked_shl, i16); -checked_shift_impl!(CheckedShl, checked_shl, i32); -checked_shift_impl!(CheckedShl, checked_shl, i64); -checked_shift_impl!(CheckedShl, checked_shl, isize); - -/// Performs a right shift that returns `None` on overflow. -pub trait CheckedShr: Sized + Shr { - /// Shifts a number to the left, checking for overflow. If overflow happens, - /// `None` is returned. - /// - /// ``` - /// use num_traits::CheckedShr; - /// - /// let x: u16 = 0x8000; - /// - /// assert_eq!(CheckedShr::checked_shr(&x, 0), Some(0x8000)); - /// assert_eq!(CheckedShr::checked_shr(&x, 1), Some(0x4000)); - /// assert_eq!(CheckedShr::checked_shr(&x, 15), Some(0x0001)); - /// assert_eq!(CheckedShr::checked_shr(&x, 16), None); - /// ``` - fn checked_shr(&self, rhs: u32) -> Option; -} - -checked_shift_impl!(CheckedShr, checked_shr, u8); -checked_shift_impl!(CheckedShr, checked_shr, u16); -checked_shift_impl!(CheckedShr, checked_shr, u32); -checked_shift_impl!(CheckedShr, checked_shr, u64); -checked_shift_impl!(CheckedShr, checked_shr, usize); - -checked_shift_impl!(CheckedShr, checked_shr, i8); -checked_shift_impl!(CheckedShr, checked_shr, i16); -checked_shift_impl!(CheckedShr, checked_shr, i32); -checked_shift_impl!(CheckedShr, checked_shr, i64); -checked_shift_impl!(CheckedShr, checked_shr, isize); diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/ops/mod.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/ops/mod.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/ops/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/ops/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -pub mod saturating; -pub mod checked; -pub mod wrapping; diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/ops/saturating.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/ops/saturating.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/ops/saturating.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/ops/saturating.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -/// Saturating math operations -pub trait Saturating { - /// Saturating addition operator. - /// Returns a+b, saturating at the numeric bounds instead of overflowing. - fn saturating_add(self, v: Self) -> Self; - - /// Saturating subtraction operator. - /// Returns a-b, saturating at the numeric bounds instead of overflowing. - fn saturating_sub(self, v: Self) -> Self; -} - -macro_rules! saturating_impl { - ($trait_name:ident for $($t:ty)*) => {$( - impl $trait_name for $t { - #[inline] - fn saturating_add(self, v: Self) -> Self { - Self::saturating_add(self, v) - } - - #[inline] - fn saturating_sub(self, v: Self) -> Self { - Self::saturating_sub(self, v) - } - } - )*} -} - -saturating_impl!(Saturating for isize usize i8 u8 i16 u16 i32 u32 i64 u64); diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/ops/wrapping.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/ops/wrapping.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/ops/wrapping.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/ops/wrapping.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,127 +0,0 @@ -use core::ops::{Add, Sub, Mul}; -use core::num::Wrapping; - -macro_rules! wrapping_impl { - ($trait_name:ident, $method:ident, $t:ty) => { - impl $trait_name for $t { - #[inline] - fn $method(&self, v: &Self) -> Self { - <$t>::$method(*self, *v) - } - } - }; - ($trait_name:ident, $method:ident, $t:ty, $rhs:ty) => { - impl $trait_name<$rhs> for $t { - #[inline] - fn $method(&self, v: &$rhs) -> Self { - <$t>::$method(*self, *v) - } - } - } -} - -/// Performs addition that wraps around on overflow. -pub trait WrappingAdd: Sized + Add { - /// Wrapping (modular) addition. Computes `self + other`, wrapping around at the boundary of - /// the type. - fn wrapping_add(&self, v: &Self) -> Self; -} - -wrapping_impl!(WrappingAdd, wrapping_add, u8); -wrapping_impl!(WrappingAdd, wrapping_add, u16); -wrapping_impl!(WrappingAdd, wrapping_add, u32); -wrapping_impl!(WrappingAdd, wrapping_add, u64); -wrapping_impl!(WrappingAdd, wrapping_add, usize); - -wrapping_impl!(WrappingAdd, wrapping_add, i8); -wrapping_impl!(WrappingAdd, wrapping_add, i16); -wrapping_impl!(WrappingAdd, wrapping_add, i32); -wrapping_impl!(WrappingAdd, wrapping_add, i64); -wrapping_impl!(WrappingAdd, wrapping_add, isize); - -/// Performs subtraction that wraps around on overflow. -pub trait WrappingSub: Sized + Sub { - /// Wrapping (modular) subtraction. Computes `self - other`, wrapping around at the boundary - /// of the type. - fn wrapping_sub(&self, v: &Self) -> Self; -} - -wrapping_impl!(WrappingSub, wrapping_sub, u8); -wrapping_impl!(WrappingSub, wrapping_sub, u16); -wrapping_impl!(WrappingSub, wrapping_sub, u32); -wrapping_impl!(WrappingSub, wrapping_sub, u64); -wrapping_impl!(WrappingSub, wrapping_sub, usize); - -wrapping_impl!(WrappingSub, wrapping_sub, i8); -wrapping_impl!(WrappingSub, wrapping_sub, i16); -wrapping_impl!(WrappingSub, wrapping_sub, i32); -wrapping_impl!(WrappingSub, wrapping_sub, i64); -wrapping_impl!(WrappingSub, wrapping_sub, isize); - -/// Performs multiplication that wraps around on overflow. -pub trait WrappingMul: Sized + Mul { - /// Wrapping (modular) multiplication. Computes `self * other`, wrapping around at the boundary - /// of the type. - fn wrapping_mul(&self, v: &Self) -> Self; -} - -wrapping_impl!(WrappingMul, wrapping_mul, u8); -wrapping_impl!(WrappingMul, wrapping_mul, u16); -wrapping_impl!(WrappingMul, wrapping_mul, u32); -wrapping_impl!(WrappingMul, wrapping_mul, u64); -wrapping_impl!(WrappingMul, wrapping_mul, usize); - -wrapping_impl!(WrappingMul, wrapping_mul, i8); -wrapping_impl!(WrappingMul, wrapping_mul, i16); -wrapping_impl!(WrappingMul, wrapping_mul, i32); -wrapping_impl!(WrappingMul, wrapping_mul, i64); -wrapping_impl!(WrappingMul, wrapping_mul, isize); - -// Well this is a bit funny, but all the more appropriate. -impl WrappingAdd for Wrapping where Wrapping: Add> { - fn wrapping_add(&self, v: &Self) -> Self { - Wrapping(self.0.wrapping_add(&v.0)) - } -} -impl WrappingSub for Wrapping where Wrapping: Sub> { - fn wrapping_sub(&self, v: &Self) -> Self { - Wrapping(self.0.wrapping_sub(&v.0)) - } -} -impl WrappingMul for Wrapping where Wrapping: Mul> { - fn wrapping_mul(&self, v: &Self) -> Self { - Wrapping(self.0.wrapping_mul(&v.0)) - } -} - - -#[test] -fn test_wrapping_traits() { - fn wrapping_add(a: T, b: T) -> T { a.wrapping_add(&b) } - fn wrapping_sub(a: T, b: T) -> T { a.wrapping_sub(&b) } - fn wrapping_mul(a: T, b: T) -> T { a.wrapping_mul(&b) } - assert_eq!(wrapping_add(255, 1), 0u8); - assert_eq!(wrapping_sub(0, 1), 255u8); - assert_eq!(wrapping_mul(255, 2), 254u8); - assert_eq!(wrapping_add(255, 1), (Wrapping(255u8) + Wrapping(1u8)).0); - assert_eq!(wrapping_sub(0, 1), (Wrapping(0u8) - Wrapping(1u8)).0); - assert_eq!(wrapping_mul(255, 2), (Wrapping(255u8) * Wrapping(2u8)).0); -} - -#[test] -fn wrapping_is_wrappingadd() { - fn require_wrappingadd(_: &T) {} - require_wrappingadd(&Wrapping(42)); -} - -#[test] -fn wrapping_is_wrappingsub() { - fn require_wrappingsub(_: &T) {} - require_wrappingsub(&Wrapping(42)); -} - -#[test] -fn wrapping_is_wrappingmul() { - fn require_wrappingmul(_: &T) {} - require_wrappingmul(&Wrapping(42)); -} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/pow.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/pow.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/pow.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/pow.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -use core::ops::Mul; -use {One, CheckedMul}; - -/// Raises a value to the power of exp, using exponentiation by squaring. -/// -/// # Example -/// -/// ```rust -/// use num_traits::pow; -/// -/// assert_eq!(pow(2i8, 4), 16); -/// assert_eq!(pow(6u8, 3), 216); -/// ``` -#[inline] -pub fn pow>(mut base: T, mut exp: usize) -> T { - if exp == 0 { return T::one() } - - while exp & 1 == 0 { - base = base.clone() * base; - exp >>= 1; - } - if exp == 1 { return base } - - let mut acc = base.clone(); - while exp > 1 { - exp >>= 1; - base = base.clone() * base; - if exp & 1 == 1 { - acc = acc * base.clone(); - } - } - acc -} - -/// Raises a value to the power of exp, returning `None` if an overflow occurred. -/// -/// Otherwise same as the `pow` function. -/// -/// # Example -/// -/// ```rust -/// use num_traits::checked_pow; -/// -/// assert_eq!(checked_pow(2i8, 4), Some(16)); -/// assert_eq!(checked_pow(7i8, 8), None); -/// assert_eq!(checked_pow(7u32, 8), Some(5_764_801)); -/// ``` -#[inline] -pub fn checked_pow(mut base: T, mut exp: usize) -> Option { - if exp == 0 { return Some(T::one()) } - - macro_rules! optry { - ( $ expr : expr ) => { - if let Some(val) = $expr { val } else { return None } - } - } - - while exp & 1 == 0 { - base = optry!(base.checked_mul(&base)); - exp >>= 1; - } - if exp == 1 { return Some(base) } - - let mut acc = base.clone(); - while exp > 1 { - exp >>= 1; - base = optry!(base.checked_mul(&base)); - if exp & 1 == 1 { - acc = optry!(acc.checked_mul(&base)); - } - } - Some(acc) -} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/real.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/real.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/real.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/real.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,926 +0,0 @@ -use std::ops::Neg; - -use {Num, NumCast, Float}; - -// NOTE: These doctests have the same issue as those in src/float.rs. -// They're testing the inherent methods directly, and not those of `Real`. - -/// A trait for real number types that do not necessarily have -/// floating-point-specific characteristics such as NaN and infinity. -/// -/// See [this Wikipedia article](https://en.wikipedia.org/wiki/Real_data_type) -/// for a list of data types that could meaningfully implement this trait. -/// -/// This trait is only available with the `std` feature. -pub trait Real - : Num - + Copy - + NumCast - + PartialOrd - + Neg -{ - /// Returns the smallest finite value that this type can represent. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let x: f64 = Real::min_value(); - /// - /// assert_eq!(x, f64::MIN); - /// ``` - fn min_value() -> Self; - - /// Returns the smallest positive, normalized value that this type can represent. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let x: f64 = Real::min_positive_value(); - /// - /// assert_eq!(x, f64::MIN_POSITIVE); - /// ``` - fn min_positive_value() -> Self; - - /// Returns epsilon, a small positive value. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let x: f64 = Real::epsilon(); - /// - /// assert_eq!(x, f64::EPSILON); - /// ``` - /// - /// # Panics - /// - /// The default implementation will panic if `f32::EPSILON` cannot - /// be cast to `Self`. - fn epsilon() -> Self; - - /// Returns the largest finite value that this type can represent. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let x: f64 = Real::max_value(); - /// assert_eq!(x, f64::MAX); - /// ``` - fn max_value() -> Self; - - /// Returns the largest integer less than or equal to a number. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let f = 3.99; - /// let g = 3.0; - /// - /// assert_eq!(f.floor(), 3.0); - /// assert_eq!(g.floor(), 3.0); - /// ``` - fn floor(self) -> Self; - - /// Returns the smallest integer greater than or equal to a number. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let f = 3.01; - /// let g = 4.0; - /// - /// assert_eq!(f.ceil(), 4.0); - /// assert_eq!(g.ceil(), 4.0); - /// ``` - fn ceil(self) -> Self; - - /// Returns the nearest integer to a number. Round half-way cases away from - /// `0.0`. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let f = 3.3; - /// let g = -3.3; - /// - /// assert_eq!(f.round(), 3.0); - /// assert_eq!(g.round(), -3.0); - /// ``` - fn round(self) -> Self; - - /// Return the integer part of a number. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let f = 3.3; - /// let g = -3.7; - /// - /// assert_eq!(f.trunc(), 3.0); - /// assert_eq!(g.trunc(), -3.0); - /// ``` - fn trunc(self) -> Self; - - /// Returns the fractional part of a number. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let x = 3.5; - /// let y = -3.5; - /// let abs_difference_x = (x.fract() - 0.5).abs(); - /// let abs_difference_y = (y.fract() - (-0.5)).abs(); - /// - /// assert!(abs_difference_x < 1e-10); - /// assert!(abs_difference_y < 1e-10); - /// ``` - fn fract(self) -> Self; - - /// Computes the absolute value of `self`. Returns `Float::nan()` if the - /// number is `Float::nan()`. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let x = 3.5; - /// let y = -3.5; - /// - /// let abs_difference_x = (x.abs() - x).abs(); - /// let abs_difference_y = (y.abs() - (-y)).abs(); - /// - /// assert!(abs_difference_x < 1e-10); - /// assert!(abs_difference_y < 1e-10); - /// - /// assert!(::num_traits::Float::is_nan(f64::NAN.abs())); - /// ``` - fn abs(self) -> Self; - - /// Returns a number that represents the sign of `self`. - /// - /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` - /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` - /// - `Float::nan()` if the number is `Float::nan()` - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let f = 3.5; - /// - /// assert_eq!(f.signum(), 1.0); - /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0); - /// - /// assert!(f64::NAN.signum().is_nan()); - /// ``` - fn signum(self) -> Self; - - /// Returns `true` if `self` is positive, including `+0.0`, - /// `Float::infinity()`, and with newer versions of Rust `f64::NAN`. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let neg_nan: f64 = -f64::NAN; - /// - /// let f = 7.0; - /// let g = -7.0; - /// - /// assert!(f.is_sign_positive()); - /// assert!(!g.is_sign_positive()); - /// assert!(!neg_nan.is_sign_positive()); - /// ``` - fn is_sign_positive(self) -> bool; - - /// Returns `true` if `self` is negative, including `-0.0`, - /// `Float::neg_infinity()`, and with newer versions of Rust `-f64::NAN`. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let nan: f64 = f64::NAN; - /// - /// let f = 7.0; - /// let g = -7.0; - /// - /// assert!(!f.is_sign_negative()); - /// assert!(g.is_sign_negative()); - /// assert!(!nan.is_sign_negative()); - /// ``` - fn is_sign_negative(self) -> bool; - - /// Fused multiply-add. Computes `(self * a) + b` with only one rounding - /// error. This produces a more accurate result with better performance than - /// a separate multiplication operation followed by an add. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let m = 10.0; - /// let x = 4.0; - /// let b = 60.0; - /// - /// // 100.0 - /// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn mul_add(self, a: Self, b: Self) -> Self; - - /// Take the reciprocal (inverse) of a number, `1/x`. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let x = 2.0; - /// let abs_difference = (x.recip() - (1.0/x)).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn recip(self) -> Self; - - /// Raise a number to an integer power. - /// - /// Using this function is generally faster than using `powf` - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let x = 2.0; - /// let abs_difference = (x.powi(2) - x*x).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn powi(self, n: i32) -> Self; - - /// Raise a number to a real number power. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let x = 2.0; - /// let abs_difference = (x.powf(2.0) - x*x).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn powf(self, n: Self) -> Self; - - /// Take the square root of a number. - /// - /// Returns NaN if `self` is a negative floating-point number. - /// - /// # Panics - /// - /// If the implementing type doesn't support NaN, this method should panic if `self < 0`. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let positive = 4.0; - /// let negative = -4.0; - /// - /// let abs_difference = (positive.sqrt() - 2.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// assert!(::num_traits::Float::is_nan(negative.sqrt())); - /// ``` - fn sqrt(self) -> Self; - - /// Returns `e^(self)`, (the exponential function). - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let one = 1.0; - /// // e^1 - /// let e = one.exp(); - /// - /// // ln(e) - 1 == 0 - /// let abs_difference = (e.ln() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn exp(self) -> Self; - - /// Returns `2^(self)`. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let f = 2.0; - /// - /// // 2^2 - 4 == 0 - /// let abs_difference = (f.exp2() - 4.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn exp2(self) -> Self; - - /// Returns the natural logarithm of the number. - /// - /// # Panics - /// - /// If `self <= 0` and this type does not support a NaN representation, this function should panic. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let one = 1.0; - /// // e^1 - /// let e = one.exp(); - /// - /// // ln(e) - 1 == 0 - /// let abs_difference = (e.ln() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn ln(self) -> Self; - - /// Returns the logarithm of the number with respect to an arbitrary base. - /// - /// # Panics - /// - /// If `self <= 0` and this type does not support a NaN representation, this function should panic. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let ten = 10.0; - /// let two = 2.0; - /// - /// // log10(10) - 1 == 0 - /// let abs_difference_10 = (ten.log(10.0) - 1.0).abs(); - /// - /// // log2(2) - 1 == 0 - /// let abs_difference_2 = (two.log(2.0) - 1.0).abs(); - /// - /// assert!(abs_difference_10 < 1e-10); - /// assert!(abs_difference_2 < 1e-10); - /// ``` - fn log(self, base: Self) -> Self; - - /// Returns the base 2 logarithm of the number. - /// - /// # Panics - /// - /// If `self <= 0` and this type does not support a NaN representation, this function should panic. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let two = 2.0; - /// - /// // log2(2) - 1 == 0 - /// let abs_difference = (two.log2() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn log2(self) -> Self; - - /// Returns the base 10 logarithm of the number. - /// - /// # Panics - /// - /// If `self <= 0` and this type does not support a NaN representation, this function should panic. - /// - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let ten = 10.0; - /// - /// // log10(10) - 1 == 0 - /// let abs_difference = (ten.log10() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn log10(self) -> Self; - - /// Converts radians to degrees. - /// - /// ``` - /// use std::f64::consts; - /// - /// let angle = consts::PI; - /// - /// let abs_difference = (angle.to_degrees() - 180.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn to_degrees(self) -> Self; - - /// Converts degrees to radians. - /// - /// ``` - /// use std::f64::consts; - /// - /// let angle = 180.0_f64; - /// - /// let abs_difference = (angle.to_radians() - consts::PI).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn to_radians(self) -> Self; - - /// Returns the maximum of the two numbers. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let x = 1.0; - /// let y = 2.0; - /// - /// assert_eq!(x.max(y), y); - /// ``` - fn max(self, other: Self) -> Self; - - /// Returns the minimum of the two numbers. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let x = 1.0; - /// let y = 2.0; - /// - /// assert_eq!(x.min(y), x); - /// ``` - fn min(self, other: Self) -> Self; - - /// The positive difference of two numbers. - /// - /// * If `self <= other`: `0:0` - /// * Else: `self - other` - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let x = 3.0; - /// let y = -3.0; - /// - /// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs(); - /// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs(); - /// - /// assert!(abs_difference_x < 1e-10); - /// assert!(abs_difference_y < 1e-10); - /// ``` - fn abs_sub(self, other: Self) -> Self; - - /// Take the cubic root of a number. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let x = 8.0; - /// - /// // x^(1/3) - 2 == 0 - /// let abs_difference = (x.cbrt() - 2.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn cbrt(self) -> Self; - - /// Calculate the length of the hypotenuse of a right-angle triangle given - /// legs of length `x` and `y`. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let x = 2.0; - /// let y = 3.0; - /// - /// // sqrt(x^2 + y^2) - /// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn hypot(self, other: Self) -> Self; - - /// Computes the sine of a number (in radians). - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let x = f64::consts::PI/2.0; - /// - /// let abs_difference = (x.sin() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn sin(self) -> Self; - - /// Computes the cosine of a number (in radians). - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let x = 2.0*f64::consts::PI; - /// - /// let abs_difference = (x.cos() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn cos(self) -> Self; - - /// Computes the tangent of a number (in radians). - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let x = f64::consts::PI/4.0; - /// let abs_difference = (x.tan() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-14); - /// ``` - fn tan(self) -> Self; - - /// Computes the arcsine of a number. Return value is in radians in - /// the range [-pi/2, pi/2] or NaN if the number is outside the range - /// [-1, 1]. - /// - /// # Panics - /// - /// If this type does not support a NaN representation, this function should panic - /// if the number is outside the range [-1, 1]. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let f = f64::consts::PI / 2.0; - /// - /// // asin(sin(pi/2)) - /// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn asin(self) -> Self; - - /// Computes the arccosine of a number. Return value is in radians in - /// the range [0, pi] or NaN if the number is outside the range - /// [-1, 1]. - /// - /// # Panics - /// - /// If this type does not support a NaN representation, this function should panic - /// if the number is outside the range [-1, 1]. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let f = f64::consts::PI / 4.0; - /// - /// // acos(cos(pi/4)) - /// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn acos(self) -> Self; - - /// Computes the arctangent of a number. Return value is in radians in the - /// range [-pi/2, pi/2]; - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let f = 1.0; - /// - /// // atan(tan(1)) - /// let abs_difference = (f.tan().atan() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn atan(self) -> Self; - - /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`). - /// - /// * `x = 0`, `y = 0`: `0` - /// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]` - /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]` - /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)` - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let pi = f64::consts::PI; - /// // All angles from horizontal right (+x) - /// // 45 deg counter-clockwise - /// let x1 = 3.0; - /// let y1 = -3.0; - /// - /// // 135 deg clockwise - /// let x2 = -3.0; - /// let y2 = 3.0; - /// - /// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs(); - /// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs(); - /// - /// assert!(abs_difference_1 < 1e-10); - /// assert!(abs_difference_2 < 1e-10); - /// ``` - fn atan2(self, other: Self) -> Self; - - /// Simultaneously computes the sine and cosine of the number, `x`. Returns - /// `(sin(x), cos(x))`. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let x = f64::consts::PI/4.0; - /// let f = x.sin_cos(); - /// - /// let abs_difference_0 = (f.0 - x.sin()).abs(); - /// let abs_difference_1 = (f.1 - x.cos()).abs(); - /// - /// assert!(abs_difference_0 < 1e-10); - /// assert!(abs_difference_0 < 1e-10); - /// ``` - fn sin_cos(self) -> (Self, Self); - - /// Returns `e^(self) - 1` in a way that is accurate even if the - /// number is close to zero. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let x = 7.0; - /// - /// // e^(ln(7)) - 1 - /// let abs_difference = (x.ln().exp_m1() - 6.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn exp_m1(self) -> Self; - - /// Returns `ln(1+n)` (natural logarithm) more accurately than if - /// the operations were performed separately. - /// - /// # Panics - /// - /// If this type does not support a NaN representation, this function should panic - /// if `self-1 <= 0`. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let x = f64::consts::E - 1.0; - /// - /// // ln(1 + (e - 1)) == ln(e) == 1 - /// let abs_difference = (x.ln_1p() - 1.0).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn ln_1p(self) -> Self; - - /// Hyperbolic sine function. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let e = f64::consts::E; - /// let x = 1.0; - /// - /// let f = x.sinh(); - /// // Solving sinh() at 1 gives `(e^2-1)/(2e)` - /// let g = (e*e - 1.0)/(2.0*e); - /// let abs_difference = (f - g).abs(); - /// - /// assert!(abs_difference < 1e-10); - /// ``` - fn sinh(self) -> Self; - - /// Hyperbolic cosine function. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let e = f64::consts::E; - /// let x = 1.0; - /// let f = x.cosh(); - /// // Solving cosh() at 1 gives this result - /// let g = (e*e + 1.0)/(2.0*e); - /// let abs_difference = (f - g).abs(); - /// - /// // Same result - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn cosh(self) -> Self; - - /// Hyperbolic tangent function. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let e = f64::consts::E; - /// let x = 1.0; - /// - /// let f = x.tanh(); - /// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))` - /// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2)); - /// let abs_difference = (f - g).abs(); - /// - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn tanh(self) -> Self; - - /// Inverse hyperbolic sine function. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let x = 1.0; - /// let f = x.sinh().asinh(); - /// - /// let abs_difference = (f - x).abs(); - /// - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn asinh(self) -> Self; - - /// Inverse hyperbolic cosine function. - /// - /// ``` - /// use num_traits::real::Real; - /// - /// let x = 1.0; - /// let f = x.cosh().acosh(); - /// - /// let abs_difference = (f - x).abs(); - /// - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn acosh(self) -> Self; - - /// Inverse hyperbolic tangent function. - /// - /// ``` - /// use num_traits::real::Real; - /// use std::f64; - /// - /// let e = f64::consts::E; - /// let f = e.tanh().atanh(); - /// - /// let abs_difference = (f - e).abs(); - /// - /// assert!(abs_difference < 1.0e-10); - /// ``` - fn atanh(self) -> Self; -} - -impl Real for T { - fn min_value() -> Self { - Self::min_value() - } - fn min_positive_value() -> Self { - Self::min_positive_value() - } - fn epsilon() -> Self { - Self::epsilon() - } - fn max_value() -> Self { - Self::max_value() - } - fn floor(self) -> Self { - self.floor() - } - fn ceil(self) -> Self { - self.ceil() - } - fn round(self) -> Self { - self.round() - } - fn trunc(self) -> Self { - self.trunc() - } - fn fract(self) -> Self { - self.fract() - } - fn abs(self) -> Self { - self.abs() - } - fn signum(self) -> Self { - self.signum() - } - fn is_sign_positive(self) -> bool { - self.is_sign_positive() - } - fn is_sign_negative(self) -> bool { - self.is_sign_negative() - } - fn mul_add(self, a: Self, b: Self) -> Self { - self.mul_add(a, b) - } - fn recip(self) -> Self { - self.recip() - } - fn powi(self, n: i32) -> Self { - self.powi(n) - } - fn powf(self, n: Self) -> Self { - self.powf(n) - } - fn sqrt(self) -> Self { - self.sqrt() - } - fn exp(self) -> Self { - self.exp() - } - fn exp2(self) -> Self { - self.exp2() - } - fn ln(self) -> Self { - self.ln() - } - fn log(self, base: Self) -> Self { - self.log(base) - } - fn log2(self) -> Self { - self.log2() - } - fn log10(self) -> Self { - self.log10() - } - fn to_degrees(self) -> Self { - self.to_degrees() - } - fn to_radians(self) -> Self { - self.to_radians() - } - fn max(self, other: Self) -> Self { - self.max(other) - } - fn min(self, other: Self) -> Self { - self.min(other) - } - fn abs_sub(self, other: Self) -> Self { - self.abs_sub(other) - } - fn cbrt(self) -> Self { - self.cbrt() - } - fn hypot(self, other: Self) -> Self { - self.hypot(other) - } - fn sin(self) -> Self { - self.sin() - } - fn cos(self) -> Self { - self.cos() - } - fn tan(self) -> Self { - self.tan() - } - fn asin(self) -> Self { - self.asin() - } - fn acos(self) -> Self { - self.acos() - } - fn atan(self) -> Self { - self.atan() - } - fn atan2(self, other: Self) -> Self { - self.atan2(other) - } - fn sin_cos(self) -> (Self, Self) { - self.sin_cos() - } - fn exp_m1(self) -> Self { - self.exp_m1() - } - fn ln_1p(self) -> Self { - self.ln_1p() - } - fn sinh(self) -> Self { - self.sinh() - } - fn cosh(self) -> Self { - self.cosh() - } - fn tanh(self) -> Self { - self.tanh() - } - fn asinh(self) -> Self { - self.asinh() - } - fn acosh(self) -> Self { - self.acosh() - } - fn atanh(self) -> Self { - self.atanh() - } -} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/src/sign.rs cargo-0.26.0/vendor/num-traits-0.2.0/src/sign.rs --- cargo-0.25.0/vendor/num-traits-0.2.0/src/sign.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/src/sign.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,236 +0,0 @@ -use core::ops::Neg; -use core::{f32, f64}; -use core::num::Wrapping; - -use Num; - -/// Useful functions for signed numbers (i.e. numbers that can be negative). -pub trait Signed: Sized + Num + Neg { - /// Computes the absolute value. - /// - /// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`. - /// - /// For signed integers, `::MIN` will be returned if the number is `::MIN`. - fn abs(&self) -> Self; - - /// The positive difference of two numbers. - /// - /// Returns `zero` if the number is less than or equal to `other`, otherwise the difference - /// between `self` and `other` is returned. - fn abs_sub(&self, other: &Self) -> Self; - - /// Returns the sign of the number. - /// - /// For `f32` and `f64`: - /// - /// * `1.0` if the number is positive, `+0.0` or `INFINITY` - /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` - /// * `NaN` if the number is `NaN` - /// - /// For signed integers: - /// - /// * `0` if the number is zero - /// * `1` if the number is positive - /// * `-1` if the number is negative - fn signum(&self) -> Self; - - /// Returns true if the number is positive and false if the number is zero or negative. - fn is_positive(&self) -> bool; - - /// Returns true if the number is negative and false if the number is zero or positive. - fn is_negative(&self) -> bool; -} - -macro_rules! signed_impl { - ($($t:ty)*) => ($( - impl Signed for $t { - #[inline] - fn abs(&self) -> $t { - if self.is_negative() { -*self } else { *self } - } - - #[inline] - fn abs_sub(&self, other: &$t) -> $t { - if *self <= *other { 0 } else { *self - *other } - } - - #[inline] - fn signum(&self) -> $t { - match *self { - n if n > 0 => 1, - 0 => 0, - _ => -1, - } - } - - #[inline] - fn is_positive(&self) -> bool { *self > 0 } - - #[inline] - fn is_negative(&self) -> bool { *self < 0 } - } - )*) -} - -signed_impl!(isize i8 i16 i32 i64); - -impl Signed for Wrapping where Wrapping: Num + Neg> -{ - #[inline] - fn abs(&self) -> Self { - Wrapping(self.0.abs()) - } - - #[inline] - fn abs_sub(&self, other: &Self) -> Self { - Wrapping(self.0.abs_sub(&other.0)) - } - - #[inline] - fn signum(&self) -> Self { - Wrapping(self.0.signum()) - } - - #[inline] - fn is_positive(&self) -> bool { self.0.is_positive() } - - #[inline] - fn is_negative(&self) -> bool { self.0.is_negative() } -} - -macro_rules! signed_float_impl { - ($t:ty, $nan:expr, $inf:expr, $neg_inf:expr) => { - impl Signed for $t { - /// Computes the absolute value. Returns `NAN` if the number is `NAN`. - #[inline] - #[cfg(feature = "std")] - fn abs(&self) -> $t { - (*self).abs() - } - - /// Computes the absolute value. Returns `NAN` if the number is `NAN`. - #[inline] - #[cfg(not(feature = "std"))] - fn abs(&self) -> $t { - if self.is_positive() { - *self - } else if self.is_negative() { - -*self - } else { - $nan - } - } - - /// The positive difference of two numbers. Returns `0.0` if the number is - /// less than or equal to `other`, otherwise the difference between`self` - /// and `other` is returned. - #[inline] - fn abs_sub(&self, other: &$t) -> $t { - if *self <= *other { 0. } else { *self - *other } - } - - /// # Returns - /// - /// - `1.0` if the number is positive, `+0.0` or `INFINITY` - /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` - /// - `NAN` if the number is NaN - #[inline] - #[cfg(feature = "std")] - fn signum(&self) -> $t { - use Float; - Float::signum(*self) - } - - /// # Returns - /// - /// - `1.0` if the number is positive, `+0.0` or `INFINITY` - /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` - /// - `NAN` if the number is NaN - #[inline] - #[cfg(not(feature = "std"))] - fn signum(&self) -> $t { - if self.is_positive() { - 1.0 - } else if self.is_negative() { - -1.0 - } else { - $nan - } - } - - /// Returns `true` if the number is positive, including `+0.0` and `INFINITY` - #[inline] - fn is_positive(&self) -> bool { *self > 0.0 || (1.0 / *self) == $inf } - - /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY` - #[inline] - fn is_negative(&self) -> bool { *self < 0.0 || (1.0 / *self) == $neg_inf } - } - } -} - -signed_float_impl!(f32, f32::NAN, f32::INFINITY, f32::NEG_INFINITY); -signed_float_impl!(f64, f64::NAN, f64::INFINITY, f64::NEG_INFINITY); - -/// Computes the absolute value. -/// -/// For `f32` and `f64`, `NaN` will be returned if the number is `NaN` -/// -/// For signed integers, `::MIN` will be returned if the number is `::MIN`. -#[inline(always)] -pub fn abs(value: T) -> T { - value.abs() -} - -/// The positive difference of two numbers. -/// -/// Returns zero if `x` is less than or equal to `y`, otherwise the difference -/// between `x` and `y` is returned. -#[inline(always)] -pub fn abs_sub(x: T, y: T) -> T { - x.abs_sub(&y) -} - -/// Returns the sign of the number. -/// -/// For `f32` and `f64`: -/// -/// * `1.0` if the number is positive, `+0.0` or `INFINITY` -/// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` -/// * `NaN` if the number is `NaN` -/// -/// For signed integers: -/// -/// * `0` if the number is zero -/// * `1` if the number is positive -/// * `-1` if the number is negative -#[inline(always)] pub fn signum(value: T) -> T { value.signum() } - -/// A trait for values which cannot be negative -pub trait Unsigned: Num {} - -macro_rules! empty_trait_impl { - ($name:ident for $($t:ty)*) => ($( - impl $name for $t {} - )*) -} - -empty_trait_impl!(Unsigned for usize u8 u16 u32 u64); - -impl Unsigned for Wrapping where Wrapping: Num {} - -#[test] -fn unsigned_wrapping_is_unsigned() { - fn require_unsigned(_: &T) {} - require_unsigned(&Wrapping(42_u32)); -} -/* -// Commenting this out since it doesn't compile on Rust 1.8, -// because on this version Wrapping doesn't implement Neg and therefore can't -// implement Signed. -#[test] -fn signed_wrapping_is_signed() { - fn require_signed(_: &T) {} - require_signed(&Wrapping(-42)); -} -*/ diff -Nru cargo-0.25.0/vendor/num-traits-0.2.0/.travis.yml cargo-0.26.0/vendor/num-traits-0.2.0/.travis.yml --- cargo-0.25.0/vendor/num-traits-0.2.0/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.0/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -language: rust -rust: - - 1.8.0 - - stable - - beta - - nightly -sudo: false -script: - - cargo build --verbose - - ./ci/test_full.sh -notifications: - email: - on_success: never -branches: - only: - - master - - next - - staging - - trying diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/bors.toml cargo-0.26.0/vendor/num-traits-0.2.2/bors.toml --- cargo-0.25.0/vendor/num-traits-0.2.2/bors.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/bors.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3 @@ +status = [ + "continuous-integration/travis-ci/push", +] diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/.cargo-checksum.json cargo-0.26.0/vendor/num-traits-0.2.2/.cargo-checksum.json --- cargo-0.25.0/vendor/num-traits-0.2.2/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"dee092fcdf725aee04dd7da1d21debff559237d49ef1cb3e69bcb8ece44c7364"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/Cargo.toml cargo-0.26.0/vendor/num-traits-0.2.2/Cargo.toml --- cargo-0.25.0/vendor/num-traits-0.2.2/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,30 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "num-traits" +version = "0.2.2" +authors = ["The Rust Project Developers"] +description = "Numeric traits for generic mathematics" +homepage = "https://github.com/rust-num/num-traits" +documentation = "https://docs.rs/num-traits" +readme = "README.md" +keywords = ["mathematics", "numerics"] +categories = ["algorithms", "science"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-num/num-traits" + +[dependencies] + +[features] +default = ["std"] +std = [] diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/ci/rustup.sh cargo-0.26.0/vendor/num-traits-0.2.2/ci/rustup.sh --- cargo-0.25.0/vendor/num-traits-0.2.2/ci/rustup.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/ci/rustup.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,12 @@ +#!/bin/sh +# Use rustup to locally run the same suite of tests as .travis.yml. +# (You should first install/update 1.8.0, stable, beta, and nightly.) + +set -ex + +export TRAVIS_RUST_VERSION +for TRAVIS_RUST_VERSION in 1.8.0 stable beta nightly; do + run="rustup run $TRAVIS_RUST_VERSION" + $run cargo build --verbose + $run $PWD/ci/test_full.sh +done diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/ci/test_full.sh cargo-0.26.0/vendor/num-traits-0.2.2/ci/test_full.sh --- cargo-0.25.0/vendor/num-traits-0.2.2/ci/test_full.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/ci/test_full.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,13 @@ +#!/bin/bash + +set -ex + +echo Testing num-traits on rustc ${TRAVIS_RUST_VERSION} + +# num-traits should build and test everywhere. +cargo build --verbose +cargo test --verbose + +# test `no_std` +cargo build --verbose --no-default-features +cargo test --verbose --no-default-features diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/LICENSE-APACHE cargo-0.26.0/vendor/num-traits-0.2.2/LICENSE-APACHE --- cargo-0.25.0/vendor/num-traits-0.2.2/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/LICENSE-MIT cargo-0.26.0/vendor/num-traits-0.2.2/LICENSE-MIT --- cargo-0.25.0/vendor/num-traits-0.2.2/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/README.md cargo-0.26.0/vendor/num-traits-0.2.2/README.md --- cargo-0.25.0/vendor/num-traits-0.2.2/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,45 @@ +# num-traits + +[![crate](https://img.shields.io/crates/v/num-traits.svg)](https://crates.io/crates/num-traits) +[![documentation](https://docs.rs/num-traits/badge.svg)](https://docs.rs/num-traits) +![minimum rustc 1.8](https://img.shields.io/badge/rustc-1.8+-red.svg) +[![Travis status](https://travis-ci.org/rust-num/num-traits.svg?branch=master)](https://travis-ci.org/rust-num/num-traits) + +Numeric traits for generic mathematics in Rust. + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +num-traits = "0.2" +``` + +and this to your crate root: + +```rust +extern crate num_traits; +``` + +## Features + +This crate can be used without the standard library (`#![no_std]`) by disabling +the default `std` feature. Use this in `Cargo.toml`: + +```toml +[dependencies.num-traits] +version = "0.2" +default-features = false +``` + +The `Float` and `Real` traits are only available when `std` is enabled. The +`FloatCore` trait is always available. + +## Releases + +Release notes are available in [RELEASES.md](RELEASES.md). + +## Compatibility + +The `num-traits` crate is tested for rustc 1.8 and greater. diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/RELEASES.md cargo-0.26.0/vendor/num-traits-0.2.2/RELEASES.md --- cargo-0.25.0/vendor/num-traits-0.2.2/RELEASES.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/RELEASES.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,77 @@ +# Release 0.2.2 + +- [Casting from floating point to integers now returns `None` on overflow][52], + avoiding [rustc's undefined behavior][rust-10184]. This applies to the `cast` + function and the traits `NumCast`, `FromPrimitive`, and `ToPrimitive`. + +**Contributors**: @apopiak, @cuviper, @dbarella + +[52]: https://github.com/rust-num/num-traits/pull/52 +[rust-10184]: https://github.com/rust-lang/rust/issues/10184 + + +# Release 0.2.1 + +- [The new `FloatCore` trait][32] offers a subset of `Float` for `#![no_std]` use. + [This includes everything][41] except the transcendental functions and FMA. +- [The new `Inv` trait][37] returns the multiplicative inverse, or reciprocal. +- [The new `Pow` trait][37] performs exponentiation, much like the existing `pow` + function, but with generic exponent types. +- [The new `One::is_one` method][39] tests if a value equals 1. Implementers + should override this method if there's a more efficient way to check for 1, + rather than comparing with a temporary `one()`. + +**Contributors**: @clarcharr, @cuviper, @vks + +[32]: https://github.com/rust-num/num-traits/pull/32 +[37]: https://github.com/rust-num/num-traits/pull/37 +[39]: https://github.com/rust-num/num-traits/pull/39 +[41]: https://github.com/rust-num/num-traits/pull/41 + + +# Release 0.2.0 + +- **breaking change**: [There is now a `std` feature][30], enabled by default, along + with the implication that building *without* this feature makes this a + `#![no_std]` crate. + - The `Float` and `Real` traits are only available when `std` is enabled. + - Otherwise, the API is unchanged, and num-traits 0.1.43 now re-exports its + items from num-traits 0.2 for compatibility (the [semver-trick]). + +**Contributors**: @cuviper, @termoshtt, @vks + +[semver-trick]: https://github.com/dtolnay/semver-trick +[30]: https://github.com/rust-num/num-traits/pull/30 + + +# Release 0.1.43 + +- All items are now [re-exported from num-traits 0.2][31] for compatibility. + +[31]: https://github.com/rust-num/num-traits/pull/31 + + +# Release 0.1.42 + +- [num-traits now has its own source repository][num-356] at [rust-num/num-traits][home]. +- [`ParseFloatError` now implements `Display`][22]. +- [The new `AsPrimitive` trait][17] implements generic casting with the `as` operator. +- [The new `CheckedShl` and `CheckedShr` traits][21] implement generic + support for the `checked_shl` and `checked_shr` methods on primitive integers. +- [The new `Real` trait][23] offers a subset of `Float` functionality that may be applicable to more + types, with a blanket implementation for all existing `T: Float` types. + +Thanks to @cuviper, @Enet4, @fabianschuiki, @svartalf, and @yoanlcq for their contributions! + +[home]: https://github.com/rust-num/num-traits +[num-356]: https://github.com/rust-num/num/pull/356 +[17]: https://github.com/rust-num/num-traits/pull/17 +[21]: https://github.com/rust-num/num-traits/pull/21 +[22]: https://github.com/rust-num/num-traits/pull/22 +[23]: https://github.com/rust-num/num-traits/pull/23 + + +# Prior releases + +No prior release notes were kept. Thanks all the same to the many +contributors that have made this crate what it is! diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/bounds.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/bounds.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/bounds.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/bounds.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,99 @@ +use core::{usize, u8, u16, u32, u64}; +use core::{isize, i8, i16, i32, i64}; +use core::{f32, f64}; +use core::num::Wrapping; + +/// Numbers which have upper and lower bounds +pub trait Bounded { + // FIXME (#5527): These should be associated constants + /// returns the smallest finite number this type can represent + fn min_value() -> Self; + /// returns the largest finite number this type can represent + fn max_value() -> Self; +} + +macro_rules! bounded_impl { + ($t:ty, $min:expr, $max:expr) => { + impl Bounded for $t { + #[inline] + fn min_value() -> $t { $min } + + #[inline] + fn max_value() -> $t { $max } + } + } +} + +bounded_impl!(usize, usize::MIN, usize::MAX); +bounded_impl!(u8, u8::MIN, u8::MAX); +bounded_impl!(u16, u16::MIN, u16::MAX); +bounded_impl!(u32, u32::MIN, u32::MAX); +bounded_impl!(u64, u64::MIN, u64::MAX); + +bounded_impl!(isize, isize::MIN, isize::MAX); +bounded_impl!(i8, i8::MIN, i8::MAX); +bounded_impl!(i16, i16::MIN, i16::MAX); +bounded_impl!(i32, i32::MIN, i32::MAX); +bounded_impl!(i64, i64::MIN, i64::MAX); + +impl Bounded for Wrapping { + fn min_value() -> Self { Wrapping(T::min_value()) } + fn max_value() -> Self { Wrapping(T::max_value()) } +} + +bounded_impl!(f32, f32::MIN, f32::MAX); + +macro_rules! for_each_tuple_ { + ( $m:ident !! ) => ( + $m! { } + ); + ( $m:ident !! $h:ident, $($t:ident,)* ) => ( + $m! { $h $($t)* } + for_each_tuple_! { $m !! $($t,)* } + ); +} +macro_rules! for_each_tuple { + ( $m:ident ) => ( + for_each_tuple_! { $m !! A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, } + ); +} + +macro_rules! bounded_tuple { + ( $($name:ident)* ) => ( + impl<$($name: Bounded,)*> Bounded for ($($name,)*) { + #[inline] + fn min_value() -> Self { + ($($name::min_value(),)*) + } + #[inline] + fn max_value() -> Self { + ($($name::max_value(),)*) + } + } + ); +} + +for_each_tuple!(bounded_tuple); +bounded_impl!(f64, f64::MIN, f64::MAX); + + +#[test] +fn wrapping_bounded() { + macro_rules! test_wrapping_bounded { + ($($t:ty)+) => { + $( + assert_eq!(Wrapping::<$t>::min_value().0, <$t>::min_value()); + assert_eq!(Wrapping::<$t>::max_value().0, <$t>::max_value()); + )+ + }; + } + + test_wrapping_bounded!(usize u8 u16 u32 u64 isize i8 i16 i32 i64); +} + +#[test] +fn wrapping_is_bounded() { + fn require_bounded(_: &T) {} + require_bounded(&Wrapping(42_u32)); + require_bounded(&Wrapping(-42)); +} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/cast.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/cast.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/cast.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/cast.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,807 @@ +use core::{i8, i16, i32, i64, isize}; +use core::{u8, u16, u32, u64, usize}; +use core::{f32, f64}; +use core::mem::size_of; +use core::num::Wrapping; + +use float::FloatCore; + +/// A generic trait for converting a value to a number. +pub trait ToPrimitive { + /// Converts the value of `self` to an `isize`. + #[inline] + fn to_isize(&self) -> Option { + self.to_i64().and_then(|x| x.to_isize()) + } + + /// Converts the value of `self` to an `i8`. + #[inline] + fn to_i8(&self) -> Option { + self.to_i64().and_then(|x| x.to_i8()) + } + + /// Converts the value of `self` to an `i16`. + #[inline] + fn to_i16(&self) -> Option { + self.to_i64().and_then(|x| x.to_i16()) + } + + /// Converts the value of `self` to an `i32`. + #[inline] + fn to_i32(&self) -> Option { + self.to_i64().and_then(|x| x.to_i32()) + } + + /// Converts the value of `self` to an `i64`. + fn to_i64(&self) -> Option; + + /// Converts the value of `self` to a `usize`. + #[inline] + fn to_usize(&self) -> Option { + self.to_u64().and_then(|x| x.to_usize()) + } + + /// Converts the value of `self` to an `u8`. + #[inline] + fn to_u8(&self) -> Option { + self.to_u64().and_then(|x| x.to_u8()) + } + + /// Converts the value of `self` to an `u16`. + #[inline] + fn to_u16(&self) -> Option { + self.to_u64().and_then(|x| x.to_u16()) + } + + /// Converts the value of `self` to an `u32`. + #[inline] + fn to_u32(&self) -> Option { + self.to_u64().and_then(|x| x.to_u32()) + } + + /// Converts the value of `self` to an `u64`. + #[inline] + fn to_u64(&self) -> Option; + + /// Converts the value of `self` to an `f32`. + #[inline] + fn to_f32(&self) -> Option { + self.to_f64().and_then(|x| x.to_f32()) + } + + /// Converts the value of `self` to an `f64`. + #[inline] + fn to_f64(&self) -> Option { + self.to_i64().and_then(|x| x.to_f64()) + } +} + +macro_rules! impl_to_primitive_int_to_int { + ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$( + #[inline] + fn $method(&self) -> Option<$DstT> { + let min = $DstT::MIN as $SrcT; + let max = $DstT::MAX as $SrcT; + if size_of::<$SrcT>() <= size_of::<$DstT>() || (min <= *self && *self <= max) { + Some(*self as $DstT) + } else { + None + } + } + )*} +} + +macro_rules! impl_to_primitive_int_to_uint { + ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$( + #[inline] + fn $method(&self) -> Option<$DstT> { + let max = $DstT::MAX as u64; + if 0 <= *self && (size_of::<$SrcT>() < size_of::<$DstT>() || *self as u64 <= max) { + Some(*self as $DstT) + } else { + None + } + } + )*} +} + +macro_rules! impl_to_primitive_int { + ($T:ident) => ( + impl ToPrimitive for $T { + impl_to_primitive_int_to_int! { $T: + fn to_isize -> isize; + fn to_i8 -> i8; + fn to_i16 -> i16; + fn to_i32 -> i32; + fn to_i64 -> i64; + } + + impl_to_primitive_int_to_uint! { $T: + fn to_usize -> usize; + fn to_u8 -> u8; + fn to_u16 -> u16; + fn to_u32 -> u32; + fn to_u64 -> u64; + } + + #[inline] + fn to_f32(&self) -> Option { Some(*self as f32) } + #[inline] + fn to_f64(&self) -> Option { Some(*self as f64) } + } + ) +} + +impl_to_primitive_int!(isize); +impl_to_primitive_int!(i8); +impl_to_primitive_int!(i16); +impl_to_primitive_int!(i32); +impl_to_primitive_int!(i64); + +macro_rules! impl_to_primitive_uint_to_int { + ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$( + #[inline] + fn $method(&self) -> Option<$DstT> { + let max = $DstT::MAX as u64; + if size_of::<$SrcT>() < size_of::<$DstT>() || *self as u64 <= max { + Some(*self as $DstT) + } else { + None + } + } + )*} +} + +macro_rules! impl_to_primitive_uint_to_uint { + ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$( + #[inline] + fn $method(&self) -> Option<$DstT> { + let max = $DstT::MAX as $SrcT; + if size_of::<$SrcT>() <= size_of::<$DstT>() || *self <= max { + Some(*self as $DstT) + } else { + None + } + } + )*} +} + +macro_rules! impl_to_primitive_uint { + ($T:ident) => ( + impl ToPrimitive for $T { + impl_to_primitive_uint_to_int! { $T: + fn to_isize -> isize; + fn to_i8 -> i8; + fn to_i16 -> i16; + fn to_i32 -> i32; + fn to_i64 -> i64; + } + + impl_to_primitive_uint_to_uint! { $T: + fn to_usize -> usize; + fn to_u8 -> u8; + fn to_u16 -> u16; + fn to_u32 -> u32; + fn to_u64 -> u64; + } + + #[inline] + fn to_f32(&self) -> Option { Some(*self as f32) } + #[inline] + fn to_f64(&self) -> Option { Some(*self as f64) } + } + ) +} + +impl_to_primitive_uint!(usize); +impl_to_primitive_uint!(u8); +impl_to_primitive_uint!(u16); +impl_to_primitive_uint!(u32); +impl_to_primitive_uint!(u64); + +macro_rules! impl_to_primitive_float_to_float { + ($SrcT:ident : $( fn $method:ident -> $DstT:ident ; )*) => {$( + #[inline] + fn $method(&self) -> Option<$DstT> { + // Only finite values that are reducing size need to worry about overflow. + if size_of::<$SrcT>() > size_of::<$DstT>() && FloatCore::is_finite(*self) { + let n = *self as f64; + if n < $DstT::MIN as f64 || n > $DstT::MAX as f64 { + return None; + } + } + // We can safely cast NaN, +-inf, and finite values in range. + Some(*self as $DstT) + } + )*} +} + +macro_rules! impl_to_primitive_float_to_signed_int { + ($f:ident : $( fn $method:ident -> $i:ident ; )*) => {$( + #[inline] + fn $method(&self) -> Option<$i> { + // Float as int truncates toward zero, so we want to allow values + // in the exclusive range `(MIN-1, MAX+1)`. + if size_of::<$f>() > size_of::<$i>() { + // With a larger size, we can represent the range exactly. + const MIN_M1: $f = $i::MIN as $f - 1.0; + const MAX_P1: $f = $i::MAX as $f + 1.0; + if *self > MIN_M1 && *self < MAX_P1 { + return Some(*self as $i); + } + } else { + // We can't represent `MIN-1` exactly, but there's no fractional part + // at this magnitude, so we can just use a `MIN` inclusive boundary. + const MIN: $f = $i::MIN as $f; + // We can't represent `MAX` exactly, but it will round up to exactly + // `MAX+1` (a power of two) when we cast it. + const MAX_P1: $f = $i::MAX as $f; + if *self >= MIN && *self < MAX_P1 { + return Some(*self as $i); + } + } + None + } + )*} +} + +macro_rules! impl_to_primitive_float_to_unsigned_int { + ($f:ident : $( fn $method:ident -> $u:ident ; )*) => {$( + #[inline] + fn $method(&self) -> Option<$u> { + // Float as int truncates toward zero, so we want to allow values + // in the exclusive range `(-1, MAX+1)`. + if size_of::<$f>() > size_of::<$u>() { + // With a larger size, we can represent the range exactly. + const MAX_P1: $f = $u::MAX as $f + 1.0; + if *self > -1.0 && *self < MAX_P1 { + return Some(*self as $u); + } + } else { + // We can't represent `MAX` exactly, but it will round up to exactly + // `MAX+1` (a power of two) when we cast it. + const MAX_P1: $f = $u::MAX as $f; + if *self > -1.0 && *self < MAX_P1 { + return Some(*self as $u); + } + } + None + } + )*} +} + +macro_rules! impl_to_primitive_float { + ($T:ident) => ( + impl ToPrimitive for $T { + impl_to_primitive_float_to_signed_int! { $T: + fn to_isize -> isize; + fn to_i8 -> i8; + fn to_i16 -> i16; + fn to_i32 -> i32; + fn to_i64 -> i64; + } + + impl_to_primitive_float_to_unsigned_int! { $T: + fn to_usize -> usize; + fn to_u8 -> u8; + fn to_u16 -> u16; + fn to_u32 -> u32; + fn to_u64 -> u64; + } + + impl_to_primitive_float_to_float! { $T: + fn to_f32 -> f32; + fn to_f64 -> f64; + } + } + ) +} + +impl_to_primitive_float!(f32); +impl_to_primitive_float!(f64); + +/// A generic trait for converting a number to a value. +pub trait FromPrimitive: Sized { + /// Convert an `isize` to return an optional value of this type. If the + /// value cannot be represented by this value, the `None` is returned. + #[inline] + fn from_isize(n: isize) -> Option { + FromPrimitive::from_i64(n as i64) + } + + /// Convert an `i8` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_i8(n: i8) -> Option { + FromPrimitive::from_i64(n as i64) + } + + /// Convert an `i16` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_i16(n: i16) -> Option { + FromPrimitive::from_i64(n as i64) + } + + /// Convert an `i32` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_i32(n: i32) -> Option { + FromPrimitive::from_i64(n as i64) + } + + /// Convert an `i64` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + fn from_i64(n: i64) -> Option; + + /// Convert a `usize` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_usize(n: usize) -> Option { + FromPrimitive::from_u64(n as u64) + } + + /// Convert an `u8` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_u8(n: u8) -> Option { + FromPrimitive::from_u64(n as u64) + } + + /// Convert an `u16` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_u16(n: u16) -> Option { + FromPrimitive::from_u64(n as u64) + } + + /// Convert an `u32` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_u32(n: u32) -> Option { + FromPrimitive::from_u64(n as u64) + } + + /// Convert an `u64` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + fn from_u64(n: u64) -> Option; + + /// Convert a `f32` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_f32(n: f32) -> Option { + FromPrimitive::from_f64(n as f64) + } + + /// Convert a `f64` to return an optional value of this type. If the + /// type cannot be represented by this value, the `None` is returned. + #[inline] + fn from_f64(n: f64) -> Option { + FromPrimitive::from_i64(n as i64) + } +} + +macro_rules! impl_from_primitive { + ($T:ty, $to_ty:ident) => ( + #[allow(deprecated)] + impl FromPrimitive for $T { + #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() } + #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() } + + #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() } + #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() } + + #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() } + #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() } + } + ) +} + +impl_from_primitive!(isize, to_isize); +impl_from_primitive!(i8, to_i8); +impl_from_primitive!(i16, to_i16); +impl_from_primitive!(i32, to_i32); +impl_from_primitive!(i64, to_i64); +impl_from_primitive!(usize, to_usize); +impl_from_primitive!(u8, to_u8); +impl_from_primitive!(u16, to_u16); +impl_from_primitive!(u32, to_u32); +impl_from_primitive!(u64, to_u64); +impl_from_primitive!(f32, to_f32); +impl_from_primitive!(f64, to_f64); + + +impl ToPrimitive for Wrapping { + fn to_i64(&self) -> Option { self.0.to_i64() } + fn to_u64(&self) -> Option { self.0.to_u64() } +} +impl FromPrimitive for Wrapping { + fn from_u64(n: u64) -> Option { T::from_u64(n).map(Wrapping) } + fn from_i64(n: i64) -> Option { T::from_i64(n).map(Wrapping) } +} + + +/// Cast from one machine scalar to another. +/// +/// # Examples +/// +/// ``` +/// # use num_traits as num; +/// let twenty: f32 = num::cast(0x14).unwrap(); +/// assert_eq!(twenty, 20f32); +/// ``` +/// +#[inline] +pub fn cast(n: T) -> Option { + NumCast::from(n) +} + +/// An interface for casting between machine scalars. +pub trait NumCast: Sized + ToPrimitive { + /// Creates a number from another value that can be converted into + /// a primitive via the `ToPrimitive` trait. + fn from(n: T) -> Option; +} + +macro_rules! impl_num_cast { + ($T:ty, $conv:ident) => ( + impl NumCast for $T { + #[inline] + #[allow(deprecated)] + fn from(n: N) -> Option<$T> { + // `$conv` could be generated using `concat_idents!`, but that + // macro seems to be broken at the moment + n.$conv() + } + } + ) +} + +impl_num_cast!(u8, to_u8); +impl_num_cast!(u16, to_u16); +impl_num_cast!(u32, to_u32); +impl_num_cast!(u64, to_u64); +impl_num_cast!(usize, to_usize); +impl_num_cast!(i8, to_i8); +impl_num_cast!(i16, to_i16); +impl_num_cast!(i32, to_i32); +impl_num_cast!(i64, to_i64); +impl_num_cast!(isize, to_isize); +impl_num_cast!(f32, to_f32); +impl_num_cast!(f64, to_f64); + +impl NumCast for Wrapping { + fn from(n: U) -> Option { + T::from(n).map(Wrapping) + } +} + +/// A generic interface for casting between machine scalars with the +/// `as` operator, which admits narrowing and precision loss. +/// Implementers of this trait AsPrimitive should behave like a primitive +/// numeric type (e.g. a newtype around another primitive), and the +/// intended conversion must never fail. +/// +/// # Examples +/// +/// ``` +/// # use num_traits::AsPrimitive; +/// let three: i32 = (3.14159265f32).as_(); +/// assert_eq!(three, 3); +/// ``` +/// +/// # Safety +/// +/// Currently, some uses of the `as` operator are not entirely safe. +/// In particular, it is undefined behavior if: +/// +/// - A truncated floating point value cannot fit in the target integer +/// type ([#10184](https://github.com/rust-lang/rust/issues/10184)); +/// +/// ```ignore +/// # use num_traits::AsPrimitive; +/// let x: u8 = (1.04E+17).as_(); // UB +/// ``` +/// +/// - Or a floating point value does not fit in another floating +/// point type ([#15536](https://github.com/rust-lang/rust/issues/15536)). +/// +/// ```ignore +/// # use num_traits::AsPrimitive; +/// let x: f32 = (1e300f64).as_(); // UB +/// ``` +/// +pub trait AsPrimitive: 'static + Copy +where + T: 'static + Copy +{ + /// Convert a value to another, using the `as` operator. + fn as_(self) -> T; +} + +macro_rules! impl_as_primitive { + ($T: ty => $( $U: ty ),* ) => { + $( + impl AsPrimitive<$U> for $T { + #[inline] fn as_(self) -> $U { self as $U } + } + )* + }; +} + +impl_as_primitive!(u8 => char, u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); +impl_as_primitive!(i8 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); +impl_as_primitive!(u16 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); +impl_as_primitive!(i16 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); +impl_as_primitive!(u32 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); +impl_as_primitive!(i32 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); +impl_as_primitive!(u64 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); +impl_as_primitive!(i64 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); +impl_as_primitive!(usize => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); +impl_as_primitive!(isize => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); +impl_as_primitive!(f32 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); +impl_as_primitive!(f64 => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64, f32, f64); +impl_as_primitive!(char => char, u8, i8, u16, i16, u32, i32, u64, isize, usize, i64); +impl_as_primitive!(bool => u8, i8, u16, i16, u32, i32, u64, isize, usize, i64); + +#[test] +fn to_primitive_float() { + use core::f32; + use core::f64; + + let f32_toolarge = 1e39f64; + assert_eq!(f32_toolarge.to_f32(), None); + assert_eq!((f32::MAX as f64).to_f32(), Some(f32::MAX)); + assert_eq!((-f32::MAX as f64).to_f32(), Some(-f32::MAX)); + assert_eq!(f64::INFINITY.to_f32(), Some(f32::INFINITY)); + assert_eq!((f64::NEG_INFINITY).to_f32(), Some(f32::NEG_INFINITY)); + assert!((f64::NAN).to_f32().map_or(false, |f| f.is_nan())); +} + +#[test] +fn wrapping_to_primitive() { + macro_rules! test_wrapping_to_primitive { + ($($t:ty)+) => { + $({ + let i: $t = 0; + let w = Wrapping(i); + assert_eq!(i.to_u8(), w.to_u8()); + assert_eq!(i.to_u16(), w.to_u16()); + assert_eq!(i.to_u32(), w.to_u32()); + assert_eq!(i.to_u64(), w.to_u64()); + assert_eq!(i.to_usize(), w.to_usize()); + assert_eq!(i.to_i8(), w.to_i8()); + assert_eq!(i.to_i16(), w.to_i16()); + assert_eq!(i.to_i32(), w.to_i32()); + assert_eq!(i.to_i64(), w.to_i64()); + assert_eq!(i.to_isize(), w.to_isize()); + assert_eq!(i.to_f32(), w.to_f32()); + assert_eq!(i.to_f64(), w.to_f64()); + })+ + }; + } + + test_wrapping_to_primitive!(usize u8 u16 u32 u64 isize i8 i16 i32 i64); +} + +#[test] +fn wrapping_is_toprimitive() { + fn require_toprimitive(_: &T) {} + require_toprimitive(&Wrapping(42)); +} + +#[test] +fn wrapping_is_fromprimitive() { + fn require_fromprimitive(_: &T) {} + require_fromprimitive(&Wrapping(42)); +} + +#[test] +fn wrapping_is_numcast() { + fn require_numcast(_: &T) {} + require_numcast(&Wrapping(42)); +} + +#[test] +fn as_primitive() { + let x: f32 = (1.625f64).as_(); + assert_eq!(x, 1.625f32); + + let x: f32 = (3.14159265358979323846f64).as_(); + assert_eq!(x, 3.1415927f32); + + let x: u8 = (768i16).as_(); + assert_eq!(x, 0); +} + +#[test] +fn float_to_integer_checks_overflow() { + // This will overflow an i32 + let source: f64 = 1.0e+123f64; + + // Expect the overflow to be caught + assert_eq!(cast::(source), None); +} + +#[test] +fn cast_to_int_checks_overflow() { + let big_f: f64 = 1.0e123; + let normal_f: f64 = 1.0; + let small_f: f64 = -1.0e123; + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + + assert_eq!(Some(normal_f as isize), cast::(normal_f)); + assert_eq!(Some(normal_f as i8), cast::(normal_f)); + assert_eq!(Some(normal_f as i16), cast::(normal_f)); + assert_eq!(Some(normal_f as i32), cast::(normal_f)); + assert_eq!(Some(normal_f as i64), cast::(normal_f)); + + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); +} + +#[test] +fn cast_to_unsigned_int_checks_overflow() { + let big_f: f64 = 1.0e123; + let normal_f: f64 = 1.0; + let small_f: f64 = -1.0e123; + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + assert_eq!(None, cast::(big_f)); + + assert_eq!(Some(normal_f as usize), cast::(normal_f)); + assert_eq!(Some(normal_f as u8), cast::(normal_f)); + assert_eq!(Some(normal_f as u16), cast::(normal_f)); + assert_eq!(Some(normal_f as u32), cast::(normal_f)); + assert_eq!(Some(normal_f as u64), cast::(normal_f)); + + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); + assert_eq!(None, cast::(small_f)); +} + +#[cfg(all(test, feature = "std"))] +fn dbg(args: ::core::fmt::Arguments) { + println!("{}", args); +} + +#[cfg(all(test, not(feature = "std")))] +fn dbg(_: ::core::fmt::Arguments) {} + +// Rust 1.8 doesn't handle cfg on macros correctly +// #[cfg(test)] +#[allow(unused)] +macro_rules! dbg { ($($tok:tt)*) => { dbg(format_args!($($tok)*)) } } + +#[test] +fn cast_float_to_int_edge_cases() { + use core::mem::transmute; + + trait RawOffset: Sized { + type Raw; + fn raw_offset(self, offset: Self::Raw) -> Self; + } + impl RawOffset for f32 { + type Raw = i32; + fn raw_offset(self, offset: Self::Raw) -> Self { + unsafe { + let raw: Self::Raw = transmute(self); + transmute(raw + offset) + } + } + } + impl RawOffset for f64 { + type Raw = i64; + fn raw_offset(self, offset: Self::Raw) -> Self { + unsafe { + let raw: Self::Raw = transmute(self); + transmute(raw + offset) + } + } + } + + macro_rules! test_edge { + ($f:ident -> $($t:ident)+) => { $({ + dbg!("testing cast edge cases for {} -> {}", stringify!($f), stringify!($t)); + + let small = if $t::MIN == 0 || size_of::<$t>() < size_of::<$f>() { + $t::MIN as $f - 1.0 + } else { + ($t::MIN as $f).raw_offset(1).floor() + }; + let fmin = small.raw_offset(-1); + dbg!(" testing min {}\n\tvs. {:.16}\n\tand {:.16}", $t::MIN, fmin, small); + assert_eq!(Some($t::MIN), cast::<$f, $t>($t::MIN as $f)); + assert_eq!(Some($t::MIN), cast::<$f, $t>(fmin)); + assert_eq!(None, cast::<$f, $t>(small)); + + let (max, large) = if size_of::<$t>() < size_of::<$f>() { + ($t::MAX, $t::MAX as $f + 1.0) + } else { + let large = $t::MAX as $f; // rounds up! + let max = large.raw_offset(-1) as $t; // the next smallest possible + assert_eq!(max.count_ones(), $f::MANTISSA_DIGITS); + (max, large) + }; + let fmax = large.raw_offset(-1); + dbg!(" testing max {}\n\tvs. {:.16}\n\tand {:.16}", max, fmax, large); + assert_eq!(Some(max), cast::<$f, $t>(max as $f)); + assert_eq!(Some(max), cast::<$f, $t>(fmax)); + assert_eq!(None, cast::<$f, $t>(large)); + + dbg!(" testing non-finite values"); + assert_eq!(None, cast::<$f, $t>($f::NAN)); + assert_eq!(None, cast::<$f, $t>($f::INFINITY)); + assert_eq!(None, cast::<$f, $t>($f::NEG_INFINITY)); + })+} + } + + test_edge!(f32 -> isize i8 i16 i32 i64); + test_edge!(f32 -> usize u8 u16 u32 u64); + test_edge!(f64 -> isize i8 i16 i32 i64); + test_edge!(f64 -> usize u8 u16 u32 u64); +} + +#[test] +fn cast_int_to_int_edge_cases() { + use core::cmp::Ordering::*; + + macro_rules! test_edge { + ($f:ident -> $($t:ident)+) => { $({ + fn test_edge() { + dbg!("testing cast edge cases for {} -> {}", stringify!($f), stringify!($t)); + + match ($f::MIN as i64).cmp(&($t::MIN as i64)) { + Greater => { + assert_eq!(Some($f::MIN as $t), cast::<$f, $t>($f::MIN)); + } + Equal => { + assert_eq!(Some($t::MIN), cast::<$f, $t>($f::MIN)); + } + Less => { + let min = $t::MIN as $f; + assert_eq!(Some($t::MIN), cast::<$f, $t>(min)); + assert_eq!(None, cast::<$f, $t>(min - 1)); + } + } + + match ($f::MAX as u64).cmp(&($t::MAX as u64)) { + Greater => { + let max = $t::MAX as $f; + assert_eq!(Some($t::MAX), cast::<$f, $t>(max)); + assert_eq!(None, cast::<$f, $t>(max + 1)); + } + Equal => { + assert_eq!(Some($t::MAX), cast::<$f, $t>($f::MAX)); + } + Less => { + assert_eq!(Some($f::MAX as $t), cast::<$f, $t>($f::MAX)); + } + } + } + test_edge(); + })+}; + ($( $from:ident )+) => { $({ + test_edge!($from -> isize i8 i16 i32 i64); + test_edge!($from -> usize u8 u16 u32 u64); + })+} + } + + test_edge!(isize i8 i16 i32 i64); + test_edge!(usize u8 u16 u32 u64); +} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/float.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/float.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/float.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/float.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2011 @@ +use core::mem; +use core::ops::Neg; +use core::num::FpCategory; + +use core::f32; +use core::f64; + +use {Num, NumCast, ToPrimitive}; + +/// Generic trait for floating point numbers that works with `no_std`. +/// +/// This trait implements a subset of the `Float` trait. +pub trait FloatCore: Num + NumCast + Neg + PartialOrd + Copy { + /// Returns positive infinity. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T) { + /// assert!(T::infinity() == x); + /// } + /// + /// check(f32::INFINITY); + /// check(f64::INFINITY); + /// ``` + fn infinity() -> Self; + + /// Returns negative infinity. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T) { + /// assert!(T::neg_infinity() == x); + /// } + /// + /// check(f32::NEG_INFINITY); + /// check(f64::NEG_INFINITY); + /// ``` + fn neg_infinity() -> Self; + + /// Returns NaN. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// + /// fn check() { + /// let n = T::nan(); + /// assert!(n != n); + /// } + /// + /// check::(); + /// check::(); + /// ``` + fn nan() -> Self; + + /// Returns `-0.0`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(n: T) { + /// let z = T::neg_zero(); + /// assert!(z.is_zero()); + /// assert!(T::one() / z == n); + /// } + /// + /// check(f32::NEG_INFINITY); + /// check(f64::NEG_INFINITY); + /// ``` + fn neg_zero() -> Self; + + /// Returns the smallest finite value that this type can represent. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T) { + /// assert!(T::min_value() == x); + /// } + /// + /// check(f32::MIN); + /// check(f64::MIN); + /// ``` + fn min_value() -> Self; + + /// Returns the smallest positive, normalized value that this type can represent. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T) { + /// assert!(T::min_positive_value() == x); + /// } + /// + /// check(f32::MIN_POSITIVE); + /// check(f64::MIN_POSITIVE); + /// ``` + fn min_positive_value() -> Self; + + /// Returns epsilon, a small positive value. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T) { + /// assert!(T::epsilon() == x); + /// } + /// + /// check(f32::EPSILON); + /// check(f64::EPSILON); + /// ``` + fn epsilon() -> Self; + + /// Returns the largest finite value that this type can represent. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T) { + /// assert!(T::max_value() == x); + /// } + /// + /// check(f32::MAX); + /// check(f64::MAX); + /// ``` + fn max_value() -> Self; + + /// Returns `true` if the number is NaN. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, p: bool) { + /// assert!(x.is_nan() == p); + /// } + /// + /// check(f32::NAN, true); + /// check(f32::INFINITY, false); + /// check(f64::NAN, true); + /// check(0.0f64, false); + /// ``` + #[inline] + fn is_nan(self) -> bool { + self != self + } + + /// Returns `true` if the number is infinite. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, p: bool) { + /// assert!(x.is_infinite() == p); + /// } + /// + /// check(f32::INFINITY, true); + /// check(f32::NEG_INFINITY, true); + /// check(f32::NAN, false); + /// check(f64::INFINITY, true); + /// check(f64::NEG_INFINITY, true); + /// check(0.0f64, false); + /// ``` + #[inline] + fn is_infinite(self) -> bool { + self == Self::infinity() || self == Self::neg_infinity() + } + + /// Returns `true` if the number is neither infinite or NaN. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, p: bool) { + /// assert!(x.is_finite() == p); + /// } + /// + /// check(f32::INFINITY, false); + /// check(f32::MAX, true); + /// check(f64::NEG_INFINITY, false); + /// check(f64::MIN_POSITIVE, true); + /// check(f64::NAN, false); + /// ``` + #[inline] + fn is_finite(self) -> bool { + !(self.is_nan() || self.is_infinite()) + } + + /// Returns `true` if the number is neither zero, infinite, subnormal or NaN. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, p: bool) { + /// assert!(x.is_normal() == p); + /// } + /// + /// check(f32::INFINITY, false); + /// check(f32::MAX, true); + /// check(f64::NEG_INFINITY, false); + /// check(f64::MIN_POSITIVE, true); + /// check(0.0f64, false); + /// ``` + #[inline] + fn is_normal(self) -> bool { + self.classify() == FpCategory::Normal + } + + /// Returns the floating point category of the number. If only one property + /// is going to be tested, it is generally faster to use the specific + /// predicate instead. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// use std::num::FpCategory; + /// + /// fn check(x: T, c: FpCategory) { + /// assert!(x.classify() == c); + /// } + /// + /// check(f32::INFINITY, FpCategory::Infinite); + /// check(f32::MAX, FpCategory::Normal); + /// check(f64::NAN, FpCategory::Nan); + /// check(f64::MIN_POSITIVE, FpCategory::Normal); + /// check(f64::MIN_POSITIVE / 2.0, FpCategory::Subnormal); + /// check(0.0f64, FpCategory::Zero); + /// ``` + fn classify(self) -> FpCategory; + + /// Returns the largest integer less than or equal to a number. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.floor() == y); + /// } + /// + /// check(f32::INFINITY, f32::INFINITY); + /// check(0.9f32, 0.0); + /// check(1.0f32, 1.0); + /// check(1.1f32, 1.0); + /// check(-0.0f64, 0.0); + /// check(-0.9f64, -1.0); + /// check(-1.0f64, -1.0); + /// check(-1.1f64, -2.0); + /// check(f64::MIN, f64::MIN); + /// ``` + #[inline] + fn floor(self) -> Self { + let f = self.fract(); + if f.is_nan() || f.is_zero() { + self + } else if self < Self::zero() { + self - f - Self::one() + } else { + self - f + } + } + + /// Returns the smallest integer greater than or equal to a number. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.ceil() == y); + /// } + /// + /// check(f32::INFINITY, f32::INFINITY); + /// check(0.9f32, 1.0); + /// check(1.0f32, 1.0); + /// check(1.1f32, 2.0); + /// check(-0.0f64, 0.0); + /// check(-0.9f64, -0.0); + /// check(-1.0f64, -1.0); + /// check(-1.1f64, -1.0); + /// check(f64::MIN, f64::MIN); + /// ``` + #[inline] + fn ceil(self) -> Self { + let f = self.fract(); + if f.is_nan() || f.is_zero() { + self + } else if self > Self::zero() { + self - f + Self::one() + } else { + self - f + } + } + + /// Returns the nearest integer to a number. Round half-way cases away from `0.0`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.round() == y); + /// } + /// + /// check(f32::INFINITY, f32::INFINITY); + /// check(0.4f32, 0.0); + /// check(0.5f32, 1.0); + /// check(0.6f32, 1.0); + /// check(-0.4f64, 0.0); + /// check(-0.5f64, -1.0); + /// check(-0.6f64, -1.0); + /// check(f64::MIN, f64::MIN); + /// ``` + #[inline] + fn round(self) -> Self { + let one = Self::one(); + let h = Self::from(0.5).expect("Unable to cast from 0.5"); + let f = self.fract(); + if f.is_nan() || f.is_zero() { + self + } else if self > Self::zero() { + if f < h { + self - f + } else { + self - f + one + } + } else { + if -f < h { + self - f + } else { + self - f - one + } + } + } + + /// Return the integer part of a number. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.trunc() == y); + /// } + /// + /// check(f32::INFINITY, f32::INFINITY); + /// check(0.9f32, 0.0); + /// check(1.0f32, 1.0); + /// check(1.1f32, 1.0); + /// check(-0.0f64, 0.0); + /// check(-0.9f64, -0.0); + /// check(-1.0f64, -1.0); + /// check(-1.1f64, -1.0); + /// check(f64::MIN, f64::MIN); + /// ``` + #[inline] + fn trunc(self) -> Self { + let f = self.fract(); + if f.is_nan() { + self + } else { + self - f + } + } + + /// Returns the fractional part of a number. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.fract() == y); + /// } + /// + /// check(f32::MAX, 0.0); + /// check(0.75f32, 0.75); + /// check(1.0f32, 0.0); + /// check(1.25f32, 0.25); + /// check(-0.0f64, 0.0); + /// check(-0.75f64, -0.75); + /// check(-1.0f64, 0.0); + /// check(-1.25f64, -0.25); + /// check(f64::MIN, 0.0); + /// ``` + #[inline] + fn fract(self) -> Self { + if self.is_zero() { + Self::zero() + } else { + self % Self::one() + } + } + + /// Computes the absolute value of `self`. Returns `FloatCore::nan()` if the + /// number is `FloatCore::nan()`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.abs() == y); + /// } + /// + /// check(f32::INFINITY, f32::INFINITY); + /// check(1.0f32, 1.0); + /// check(0.0f64, 0.0); + /// check(-0.0f64, 0.0); + /// check(-1.0f64, 1.0); + /// check(f64::MIN, f64::MAX); + /// ``` + #[inline] + fn abs(self) -> Self { + if self.is_sign_positive() { + return self; + } + if self.is_sign_negative() { + return -self; + } + Self::nan() + } + + /// Returns a number that represents the sign of `self`. + /// + /// - `1.0` if the number is positive, `+0.0` or `FloatCore::infinity()` + /// - `-1.0` if the number is negative, `-0.0` or `FloatCore::neg_infinity()` + /// - `FloatCore::nan()` if the number is `FloatCore::nan()` + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.signum() == y); + /// } + /// + /// check(f32::INFINITY, 1.0); + /// check(3.0f32, 1.0); + /// check(0.0f32, 1.0); + /// check(-0.0f64, -1.0); + /// check(-3.0f64, -1.0); + /// check(f64::MIN, -1.0); + /// ``` + #[inline] + fn signum(self) -> Self { + if self.is_nan() { + Self::nan() + } else if self.is_sign_negative() { + -Self::one() + } else { + Self::one() + } + } + + /// Returns `true` if `self` is positive, including `+0.0` and + /// `FloatCore::infinity()`, and since Rust 1.20 also + /// `FloatCore::nan()`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, p: bool) { + /// assert!(x.is_sign_positive() == p); + /// } + /// + /// check(f32::INFINITY, true); + /// check(f32::MAX, true); + /// check(0.0f32, true); + /// check(-0.0f64, false); + /// check(f64::NEG_INFINITY, false); + /// check(f64::MIN_POSITIVE, true); + /// check(-f64::NAN, false); + /// ``` + #[inline] + fn is_sign_positive(self) -> bool { + !self.is_sign_negative() + } + + /// Returns `true` if `self` is negative, including `-0.0` and + /// `FloatCore::neg_infinity()`, and since Rust 1.20 also + /// `-FloatCore::nan()`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, p: bool) { + /// assert!(x.is_sign_negative() == p); + /// } + /// + /// check(f32::INFINITY, false); + /// check(f32::MAX, false); + /// check(0.0f32, false); + /// check(-0.0f64, true); + /// check(f64::NEG_INFINITY, true); + /// check(f64::MIN_POSITIVE, false); + /// check(f64::NAN, false); + /// ``` + #[inline] + fn is_sign_negative(self) -> bool { + let (_, _, sign) = self.integer_decode(); + sign < 0 + } + + /// Returns the minimum of the two numbers. + /// + /// If one of the arguments is NaN, then the other argument is returned. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T, min: T) { + /// assert!(x.min(y) == min); + /// } + /// + /// check(1.0f32, 2.0, 1.0); + /// check(f32::NAN, 2.0, 2.0); + /// check(1.0f64, -2.0, -2.0); + /// check(1.0f64, f64::NAN, 1.0); + /// ``` + #[inline] + fn min(self, other: Self) -> Self { + if self.is_nan() { + return other; + } + if other.is_nan() { + return self; + } + if self < other { self } else { other } + } + + /// Returns the maximum of the two numbers. + /// + /// If one of the arguments is NaN, then the other argument is returned. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T, min: T) { + /// assert!(x.max(y) == min); + /// } + /// + /// check(1.0f32, 2.0, 2.0); + /// check(1.0f32, f32::NAN, 1.0); + /// check(-1.0f64, 2.0, 2.0); + /// check(-1.0f64, f64::NAN, -1.0); + /// ``` + #[inline] + fn max(self, other: Self) -> Self { + if self.is_nan() { + return other; + } + if other.is_nan() { + return self; + } + if self > other { self } else { other } + } + + /// Returns the reciprocal (multiplicative inverse) of the number. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, y: T) { + /// assert!(x.recip() == y); + /// assert!(y.recip() == x); + /// } + /// + /// check(f32::INFINITY, 0.0); + /// check(2.0f32, 0.5); + /// check(-0.25f64, -4.0); + /// check(-0.0f64, f64::NEG_INFINITY); + /// ``` + #[inline] + fn recip(self) -> Self { + Self::one() / self + } + + /// Raise a number to an integer power. + /// + /// Using this function is generally faster than using `powf` + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// + /// fn check(x: T, exp: i32, powi: T) { + /// assert!(x.powi(exp) == powi); + /// } + /// + /// check(9.0f32, 2, 81.0); + /// check(1.0f32, -2, 1.0); + /// check(10.0f64, 20, 1e20); + /// check(4.0f64, -2, 0.0625); + /// check(-1.0f64, std::i32::MIN, 1.0); + /// ``` + #[inline] + fn powi(mut self, mut exp: i32) -> Self { + if exp < 0 { + exp = exp.wrapping_neg(); + self = self.recip(); + } + // It should always be possible to convert a positive `i32` to a `usize`. + // Note, `i32::MIN` will wrap and still be negative, so we need to convert + // to `u32` without sign-extension before growing to `usize`. + super::pow(self, (exp as u32).to_usize().unwrap()) + } + + /// Converts to degrees, assuming the number is in radians. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(rad: T, deg: T) { + /// assert!(rad.to_degrees() == deg); + /// } + /// + /// check(0.0f32, 0.0); + /// check(f32::consts::PI, 180.0); + /// check(f64::consts::FRAC_PI_4, 45.0); + /// check(f64::INFINITY, f64::INFINITY); + /// ``` + fn to_degrees(self) -> Self; + + /// Converts to radians, assuming the number is in degrees. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(deg: T, rad: T) { + /// assert!(deg.to_radians() == rad); + /// } + /// + /// check(0.0f32, 0.0); + /// check(180.0, f32::consts::PI); + /// check(45.0, f64::consts::FRAC_PI_4); + /// check(f64::INFINITY, f64::INFINITY); + /// ``` + fn to_radians(self) -> Self; + + /// Returns the mantissa, base 2 exponent, and sign as integers, respectively. + /// The original number can be recovered by `sign * mantissa * 2 ^ exponent`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::float::FloatCore; + /// use std::{f32, f64}; + /// + /// fn check(x: T, m: u64, e: i16, s:i8) { + /// let (mantissa, exponent, sign) = x.integer_decode(); + /// assert_eq!(mantissa, m); + /// assert_eq!(exponent, e); + /// assert_eq!(sign, s); + /// } + /// + /// check(2.0f32, 1 << 23, -22, 1); + /// check(-2.0f32, 1 << 23, -22, -1); + /// check(f32::INFINITY, 1 << 23, 105, 1); + /// check(f64::NEG_INFINITY, 1 << 52, 972, -1); + /// ``` + fn integer_decode(self) -> (u64, i16, i8); +} + +impl FloatCore for f32 { + constant! { + infinity() -> f32::INFINITY; + neg_infinity() -> f32::NEG_INFINITY; + nan() -> f32::NAN; + neg_zero() -> -0.0; + min_value() -> f32::MIN; + min_positive_value() -> f32::MIN_POSITIVE; + epsilon() -> f32::EPSILON; + max_value() -> f32::MAX; + } + + #[inline] + fn integer_decode(self) -> (u64, i16, i8) { + integer_decode_f32(self) + } + + #[inline] + #[cfg(not(feature = "std"))] + fn classify(self) -> FpCategory { + const EXP_MASK: u32 = 0x7f800000; + const MAN_MASK: u32 = 0x007fffff; + + let bits: u32 = unsafe { mem::transmute(self) }; + match (bits & MAN_MASK, bits & EXP_MASK) { + (0, 0) => FpCategory::Zero, + (_, 0) => FpCategory::Subnormal, + (0, EXP_MASK) => FpCategory::Infinite, + (_, EXP_MASK) => FpCategory::Nan, + _ => FpCategory::Normal, + } + } + + #[inline] + #[cfg(not(feature = "std"))] + fn to_degrees(self) -> Self { + self * (180.0 / f32::consts::PI) + } + + #[inline] + #[cfg(not(feature = "std"))] + fn to_radians(self) -> Self { + self * (f32::consts::PI / 180.0) + } + + #[cfg(feature = "std")] + forward! { + Self::is_nan(self) -> bool; + Self::is_infinite(self) -> bool; + Self::is_finite(self) -> bool; + Self::is_normal(self) -> bool; + Self::classify(self) -> FpCategory; + Self::floor(self) -> Self; + Self::ceil(self) -> Self; + Self::round(self) -> Self; + Self::trunc(self) -> Self; + Self::fract(self) -> Self; + Self::abs(self) -> Self; + Self::signum(self) -> Self; + Self::is_sign_positive(self) -> bool; + Self::is_sign_negative(self) -> bool; + Self::min(self, other: Self) -> Self; + Self::max(self, other: Self) -> Self; + Self::recip(self) -> Self; + Self::powi(self, n: i32) -> Self; + Self::to_degrees(self) -> Self; + Self::to_radians(self) -> Self; + } +} + +impl FloatCore for f64 { + constant! { + infinity() -> f64::INFINITY; + neg_infinity() -> f64::NEG_INFINITY; + nan() -> f64::NAN; + neg_zero() -> -0.0; + min_value() -> f64::MIN; + min_positive_value() -> f64::MIN_POSITIVE; + epsilon() -> f64::EPSILON; + max_value() -> f64::MAX; + } + + #[inline] + fn integer_decode(self) -> (u64, i16, i8) { + integer_decode_f64(self) + } + + #[inline] + #[cfg(not(feature = "std"))] + fn classify(self) -> FpCategory { + const EXP_MASK: u64 = 0x7ff0000000000000; + const MAN_MASK: u64 = 0x000fffffffffffff; + + let bits: u64 = unsafe { mem::transmute(self) }; + match (bits & MAN_MASK, bits & EXP_MASK) { + (0, 0) => FpCategory::Zero, + (_, 0) => FpCategory::Subnormal, + (0, EXP_MASK) => FpCategory::Infinite, + (_, EXP_MASK) => FpCategory::Nan, + _ => FpCategory::Normal, + } + } + + #[inline] + #[cfg(not(feature = "std"))] + fn to_degrees(self) -> Self { + self * (180.0 / f64::consts::PI) + } + + #[inline] + #[cfg(not(feature = "std"))] + fn to_radians(self) -> Self { + self * (f64::consts::PI / 180.0) + } + + #[cfg(feature = "std")] + forward! { + Self::is_nan(self) -> bool; + Self::is_infinite(self) -> bool; + Self::is_finite(self) -> bool; + Self::is_normal(self) -> bool; + Self::classify(self) -> FpCategory; + Self::floor(self) -> Self; + Self::ceil(self) -> Self; + Self::round(self) -> Self; + Self::trunc(self) -> Self; + Self::fract(self) -> Self; + Self::abs(self) -> Self; + Self::signum(self) -> Self; + Self::is_sign_positive(self) -> bool; + Self::is_sign_negative(self) -> bool; + Self::min(self, other: Self) -> Self; + Self::max(self, other: Self) -> Self; + Self::recip(self) -> Self; + Self::powi(self, n: i32) -> Self; + Self::to_degrees(self) -> Self; + Self::to_radians(self) -> Self; + } +} + +// FIXME: these doctests aren't actually helpful, because they're using and +// testing the inherent methods directly, not going through `Float`. + +/// Generic trait for floating point numbers +/// +/// This trait is only available with the `std` feature. +#[cfg(feature = "std")] +pub trait Float + : Num + + Copy + + NumCast + + PartialOrd + + Neg +{ + /// Returns the `NaN` value. + /// + /// ``` + /// use num_traits::Float; + /// + /// let nan: f32 = Float::nan(); + /// + /// assert!(nan.is_nan()); + /// ``` + fn nan() -> Self; + /// Returns the infinite value. + /// + /// ``` + /// use num_traits::Float; + /// use std::f32; + /// + /// let infinity: f32 = Float::infinity(); + /// + /// assert!(infinity.is_infinite()); + /// assert!(!infinity.is_finite()); + /// assert!(infinity > f32::MAX); + /// ``` + fn infinity() -> Self; + /// Returns the negative infinite value. + /// + /// ``` + /// use num_traits::Float; + /// use std::f32; + /// + /// let neg_infinity: f32 = Float::neg_infinity(); + /// + /// assert!(neg_infinity.is_infinite()); + /// assert!(!neg_infinity.is_finite()); + /// assert!(neg_infinity < f32::MIN); + /// ``` + fn neg_infinity() -> Self; + /// Returns `-0.0`. + /// + /// ``` + /// use num_traits::{Zero, Float}; + /// + /// let inf: f32 = Float::infinity(); + /// let zero: f32 = Zero::zero(); + /// let neg_zero: f32 = Float::neg_zero(); + /// + /// assert_eq!(zero, neg_zero); + /// assert_eq!(7.0f32/inf, zero); + /// assert_eq!(zero * 10.0, zero); + /// ``` + fn neg_zero() -> Self; + + /// Returns the smallest finite value that this type can represent. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x: f64 = Float::min_value(); + /// + /// assert_eq!(x, f64::MIN); + /// ``` + fn min_value() -> Self; + + /// Returns the smallest positive, normalized value that this type can represent. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x: f64 = Float::min_positive_value(); + /// + /// assert_eq!(x, f64::MIN_POSITIVE); + /// ``` + fn min_positive_value() -> Self; + + /// Returns epsilon, a small positive value. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x: f64 = Float::epsilon(); + /// + /// assert_eq!(x, f64::EPSILON); + /// ``` + /// + /// # Panics + /// + /// The default implementation will panic if `f32::EPSILON` cannot + /// be cast to `Self`. + fn epsilon() -> Self { + Self::from(f32::EPSILON).expect("Unable to cast from f32::EPSILON") + } + + /// Returns the largest finite value that this type can represent. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x: f64 = Float::max_value(); + /// assert_eq!(x, f64::MAX); + /// ``` + fn max_value() -> Self; + + /// Returns `true` if this value is `NaN` and false otherwise. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let nan = f64::NAN; + /// let f = 7.0; + /// + /// assert!(nan.is_nan()); + /// assert!(!f.is_nan()); + /// ``` + fn is_nan(self) -> bool; + + /// Returns `true` if this value is positive infinity or negative infinity and + /// false otherwise. + /// + /// ``` + /// use num_traits::Float; + /// use std::f32; + /// + /// let f = 7.0f32; + /// let inf: f32 = Float::infinity(); + /// let neg_inf: f32 = Float::neg_infinity(); + /// let nan: f32 = f32::NAN; + /// + /// assert!(!f.is_infinite()); + /// assert!(!nan.is_infinite()); + /// + /// assert!(inf.is_infinite()); + /// assert!(neg_inf.is_infinite()); + /// ``` + fn is_infinite(self) -> bool; + + /// Returns `true` if this number is neither infinite nor `NaN`. + /// + /// ``` + /// use num_traits::Float; + /// use std::f32; + /// + /// let f = 7.0f32; + /// let inf: f32 = Float::infinity(); + /// let neg_inf: f32 = Float::neg_infinity(); + /// let nan: f32 = f32::NAN; + /// + /// assert!(f.is_finite()); + /// + /// assert!(!nan.is_finite()); + /// assert!(!inf.is_finite()); + /// assert!(!neg_inf.is_finite()); + /// ``` + fn is_finite(self) -> bool; + + /// Returns `true` if the number is neither zero, infinite, + /// [subnormal][subnormal], or `NaN`. + /// + /// ``` + /// use num_traits::Float; + /// use std::f32; + /// + /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32 + /// let max = f32::MAX; + /// let lower_than_min = 1.0e-40_f32; + /// let zero = 0.0f32; + /// + /// assert!(min.is_normal()); + /// assert!(max.is_normal()); + /// + /// assert!(!zero.is_normal()); + /// assert!(!f32::NAN.is_normal()); + /// assert!(!f32::INFINITY.is_normal()); + /// // Values between `0` and `min` are Subnormal. + /// assert!(!lower_than_min.is_normal()); + /// ``` + /// [subnormal]: http://en.wikipedia.org/wiki/Denormal_number + fn is_normal(self) -> bool; + + /// Returns the floating point category of the number. If only one property + /// is going to be tested, it is generally faster to use the specific + /// predicate instead. + /// + /// ``` + /// use num_traits::Float; + /// use std::num::FpCategory; + /// use std::f32; + /// + /// let num = 12.4f32; + /// let inf = f32::INFINITY; + /// + /// assert_eq!(num.classify(), FpCategory::Normal); + /// assert_eq!(inf.classify(), FpCategory::Infinite); + /// ``` + fn classify(self) -> FpCategory; + + /// Returns the largest integer less than or equal to a number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 3.99; + /// let g = 3.0; + /// + /// assert_eq!(f.floor(), 3.0); + /// assert_eq!(g.floor(), 3.0); + /// ``` + fn floor(self) -> Self; + + /// Returns the smallest integer greater than or equal to a number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 3.01; + /// let g = 4.0; + /// + /// assert_eq!(f.ceil(), 4.0); + /// assert_eq!(g.ceil(), 4.0); + /// ``` + fn ceil(self) -> Self; + + /// Returns the nearest integer to a number. Round half-way cases away from + /// `0.0`. + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 3.3; + /// let g = -3.3; + /// + /// assert_eq!(f.round(), 3.0); + /// assert_eq!(g.round(), -3.0); + /// ``` + fn round(self) -> Self; + + /// Return the integer part of a number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 3.3; + /// let g = -3.7; + /// + /// assert_eq!(f.trunc(), 3.0); + /// assert_eq!(g.trunc(), -3.0); + /// ``` + fn trunc(self) -> Self; + + /// Returns the fractional part of a number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 3.5; + /// let y = -3.5; + /// let abs_difference_x = (x.fract() - 0.5).abs(); + /// let abs_difference_y = (y.fract() - (-0.5)).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// ``` + fn fract(self) -> Self; + + /// Computes the absolute value of `self`. Returns `Float::nan()` if the + /// number is `Float::nan()`. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x = 3.5; + /// let y = -3.5; + /// + /// let abs_difference_x = (x.abs() - x).abs(); + /// let abs_difference_y = (y.abs() - (-y)).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// + /// assert!(f64::NAN.abs().is_nan()); + /// ``` + fn abs(self) -> Self; + + /// Returns a number that represents the sign of `self`. + /// + /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` + /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` + /// - `Float::nan()` if the number is `Float::nan()` + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let f = 3.5; + /// + /// assert_eq!(f.signum(), 1.0); + /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0); + /// + /// assert!(f64::NAN.signum().is_nan()); + /// ``` + fn signum(self) -> Self; + + /// Returns `true` if `self` is positive, including `+0.0`, + /// `Float::infinity()`, and since Rust 1.20 also `Float::nan()`. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let neg_nan: f64 = -f64::NAN; + /// + /// let f = 7.0; + /// let g = -7.0; + /// + /// assert!(f.is_sign_positive()); + /// assert!(!g.is_sign_positive()); + /// assert!(!neg_nan.is_sign_positive()); + /// ``` + fn is_sign_positive(self) -> bool; + + /// Returns `true` if `self` is negative, including `-0.0`, + /// `Float::neg_infinity()`, and since Rust 1.20 also `-Float::nan()`. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let nan: f64 = f64::NAN; + /// + /// let f = 7.0; + /// let g = -7.0; + /// + /// assert!(!f.is_sign_negative()); + /// assert!(g.is_sign_negative()); + /// assert!(!nan.is_sign_negative()); + /// ``` + fn is_sign_negative(self) -> bool; + + /// Fused multiply-add. Computes `(self * a) + b` with only one rounding + /// error. This produces a more accurate result with better performance than + /// a separate multiplication operation followed by an add. + /// + /// ``` + /// use num_traits::Float; + /// + /// let m = 10.0; + /// let x = 4.0; + /// let b = 60.0; + /// + /// // 100.0 + /// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn mul_add(self, a: Self, b: Self) -> Self; + /// Take the reciprocal (inverse) of a number, `1/x`. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 2.0; + /// let abs_difference = (x.recip() - (1.0/x)).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn recip(self) -> Self; + + /// Raise a number to an integer power. + /// + /// Using this function is generally faster than using `powf` + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 2.0; + /// let abs_difference = (x.powi(2) - x*x).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn powi(self, n: i32) -> Self; + + /// Raise a number to a floating point power. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 2.0; + /// let abs_difference = (x.powf(2.0) - x*x).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn powf(self, n: Self) -> Self; + + /// Take the square root of a number. + /// + /// Returns NaN if `self` is a negative number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let positive = 4.0; + /// let negative = -4.0; + /// + /// let abs_difference = (positive.sqrt() - 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// assert!(negative.sqrt().is_nan()); + /// ``` + fn sqrt(self) -> Self; + + /// Returns `e^(self)`, (the exponential function). + /// + /// ``` + /// use num_traits::Float; + /// + /// let one = 1.0; + /// // e^1 + /// let e = one.exp(); + /// + /// // ln(e) - 1 == 0 + /// let abs_difference = (e.ln() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp(self) -> Self; + + /// Returns `2^(self)`. + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 2.0; + /// + /// // 2^2 - 4 == 0 + /// let abs_difference = (f.exp2() - 4.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp2(self) -> Self; + + /// Returns the natural logarithm of the number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let one = 1.0; + /// // e^1 + /// let e = one.exp(); + /// + /// // ln(e) - 1 == 0 + /// let abs_difference = (e.ln() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn ln(self) -> Self; + + /// Returns the logarithm of the number with respect to an arbitrary base. + /// + /// ``` + /// use num_traits::Float; + /// + /// let ten = 10.0; + /// let two = 2.0; + /// + /// // log10(10) - 1 == 0 + /// let abs_difference_10 = (ten.log(10.0) - 1.0).abs(); + /// + /// // log2(2) - 1 == 0 + /// let abs_difference_2 = (two.log(2.0) - 1.0).abs(); + /// + /// assert!(abs_difference_10 < 1e-10); + /// assert!(abs_difference_2 < 1e-10); + /// ``` + fn log(self, base: Self) -> Self; + + /// Returns the base 2 logarithm of the number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let two = 2.0; + /// + /// // log2(2) - 1 == 0 + /// let abs_difference = (two.log2() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn log2(self) -> Self; + + /// Returns the base 10 logarithm of the number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let ten = 10.0; + /// + /// // log10(10) - 1 == 0 + /// let abs_difference = (ten.log10() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn log10(self) -> Self; + + /// Converts radians to degrees. + /// + /// ``` + /// use std::f64::consts; + /// + /// let angle = consts::PI; + /// + /// let abs_difference = (angle.to_degrees() - 180.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + #[inline] + fn to_degrees(self) -> Self { + let halfpi = Self::zero().acos(); + let ninety = Self::from(90u8).unwrap(); + self * ninety / halfpi + } + + /// Converts degrees to radians. + /// + /// ``` + /// use std::f64::consts; + /// + /// let angle = 180.0_f64; + /// + /// let abs_difference = (angle.to_radians() - consts::PI).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + #[inline] + fn to_radians(self) -> Self { + let halfpi = Self::zero().acos(); + let ninety = Self::from(90u8).unwrap(); + self * halfpi / ninety + } + + /// Returns the maximum of the two numbers. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 1.0; + /// let y = 2.0; + /// + /// assert_eq!(x.max(y), y); + /// ``` + fn max(self, other: Self) -> Self; + + /// Returns the minimum of the two numbers. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 1.0; + /// let y = 2.0; + /// + /// assert_eq!(x.min(y), x); + /// ``` + fn min(self, other: Self) -> Self; + + /// The positive difference of two numbers. + /// + /// * If `self <= other`: `0:0` + /// * Else: `self - other` + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 3.0; + /// let y = -3.0; + /// + /// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs(); + /// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// ``` + fn abs_sub(self, other: Self) -> Self; + + /// Take the cubic root of a number. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 8.0; + /// + /// // x^(1/3) - 2 == 0 + /// let abs_difference = (x.cbrt() - 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn cbrt(self) -> Self; + + /// Calculate the length of the hypotenuse of a right-angle triangle given + /// legs of length `x` and `y`. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 2.0; + /// let y = 3.0; + /// + /// // sqrt(x^2 + y^2) + /// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn hypot(self, other: Self) -> Self; + + /// Computes the sine of a number (in radians). + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x = f64::consts::PI/2.0; + /// + /// let abs_difference = (x.sin() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn sin(self) -> Self; + + /// Computes the cosine of a number (in radians). + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x = 2.0*f64::consts::PI; + /// + /// let abs_difference = (x.cos() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn cos(self) -> Self; + + /// Computes the tangent of a number (in radians). + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x = f64::consts::PI/4.0; + /// let abs_difference = (x.tan() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-14); + /// ``` + fn tan(self) -> Self; + + /// Computes the arcsine of a number. Return value is in radians in + /// the range [-pi/2, pi/2] or NaN if the number is outside the range + /// [-1, 1]. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let f = f64::consts::PI / 2.0; + /// + /// // asin(sin(pi/2)) + /// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn asin(self) -> Self; + + /// Computes the arccosine of a number. Return value is in radians in + /// the range [0, pi] or NaN if the number is outside the range + /// [-1, 1]. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let f = f64::consts::PI / 4.0; + /// + /// // acos(cos(pi/4)) + /// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn acos(self) -> Self; + + /// Computes the arctangent of a number. Return value is in radians in the + /// range [-pi/2, pi/2]; + /// + /// ``` + /// use num_traits::Float; + /// + /// let f = 1.0; + /// + /// // atan(tan(1)) + /// let abs_difference = (f.tan().atan() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn atan(self) -> Self; + + /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`). + /// + /// * `x = 0`, `y = 0`: `0` + /// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]` + /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]` + /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)` + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let pi = f64::consts::PI; + /// // All angles from horizontal right (+x) + /// // 45 deg counter-clockwise + /// let x1 = 3.0; + /// let y1 = -3.0; + /// + /// // 135 deg clockwise + /// let x2 = -3.0; + /// let y2 = 3.0; + /// + /// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs(); + /// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs(); + /// + /// assert!(abs_difference_1 < 1e-10); + /// assert!(abs_difference_2 < 1e-10); + /// ``` + fn atan2(self, other: Self) -> Self; + + /// Simultaneously computes the sine and cosine of the number, `x`. Returns + /// `(sin(x), cos(x))`. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x = f64::consts::PI/4.0; + /// let f = x.sin_cos(); + /// + /// let abs_difference_0 = (f.0 - x.sin()).abs(); + /// let abs_difference_1 = (f.1 - x.cos()).abs(); + /// + /// assert!(abs_difference_0 < 1e-10); + /// assert!(abs_difference_0 < 1e-10); + /// ``` + fn sin_cos(self) -> (Self, Self); + + /// Returns `e^(self) - 1` in a way that is accurate even if the + /// number is close to zero. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 7.0; + /// + /// // e^(ln(7)) - 1 + /// let abs_difference = (x.ln().exp_m1() - 6.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp_m1(self) -> Self; + + /// Returns `ln(1+n)` (natural logarithm) more accurately than if + /// the operations were performed separately. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x = f64::consts::E - 1.0; + /// + /// // ln(1 + (e - 1)) == ln(e) == 1 + /// let abs_difference = (x.ln_1p() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn ln_1p(self) -> Self; + + /// Hyperbolic sine function. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// + /// let f = x.sinh(); + /// // Solving sinh() at 1 gives `(e^2-1)/(2e)` + /// let g = (e*e - 1.0)/(2.0*e); + /// let abs_difference = (f - g).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn sinh(self) -> Self; + + /// Hyperbolic cosine function. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// let f = x.cosh(); + /// // Solving cosh() at 1 gives this result + /// let g = (e*e + 1.0)/(2.0*e); + /// let abs_difference = (f - g).abs(); + /// + /// // Same result + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn cosh(self) -> Self; + + /// Hyperbolic tangent function. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// + /// let f = x.tanh(); + /// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))` + /// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2)); + /// let abs_difference = (f - g).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn tanh(self) -> Self; + + /// Inverse hyperbolic sine function. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 1.0; + /// let f = x.sinh().asinh(); + /// + /// let abs_difference = (f - x).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn asinh(self) -> Self; + + /// Inverse hyperbolic cosine function. + /// + /// ``` + /// use num_traits::Float; + /// + /// let x = 1.0; + /// let f = x.cosh().acosh(); + /// + /// let abs_difference = (f - x).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn acosh(self) -> Self; + + /// Inverse hyperbolic tangent function. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let f = e.tanh().atanh(); + /// + /// let abs_difference = (f - e).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn atanh(self) -> Self; + + + /// Returns the mantissa, base 2 exponent, and sign as integers, respectively. + /// The original number can be recovered by `sign * mantissa * 2 ^ exponent`. + /// + /// ``` + /// use num_traits::Float; + /// + /// let num = 2.0f32; + /// + /// // (8388608, -22, 1) + /// let (mantissa, exponent, sign) = Float::integer_decode(num); + /// let sign_f = sign as f32; + /// let mantissa_f = mantissa as f32; + /// let exponent_f = num.powf(exponent as f32); + /// + /// // 1 * 8388608 * 2^(-22) == 2 + /// let abs_difference = (sign_f * mantissa_f * exponent_f - num).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn integer_decode(self) -> (u64, i16, i8); +} + +#[cfg(feature = "std")] +macro_rules! float_impl { + ($T:ident $decode:ident) => ( + impl Float for $T { + constant! { + nan() -> $T::NAN; + infinity() -> $T::INFINITY; + neg_infinity() -> $T::NEG_INFINITY; + neg_zero() -> -0.0; + min_value() -> $T::MIN; + min_positive_value() -> $T::MIN_POSITIVE; + epsilon() -> $T::EPSILON; + max_value() -> $T::MAX; + } + + #[inline] + #[allow(deprecated)] + fn abs_sub(self, other: Self) -> Self { + <$T>::abs_sub(self, other) + } + + #[inline] + fn integer_decode(self) -> (u64, i16, i8) { + $decode(self) + } + + forward! { + Self::is_nan(self) -> bool; + Self::is_infinite(self) -> bool; + Self::is_finite(self) -> bool; + Self::is_normal(self) -> bool; + Self::classify(self) -> FpCategory; + Self::floor(self) -> Self; + Self::ceil(self) -> Self; + Self::round(self) -> Self; + Self::trunc(self) -> Self; + Self::fract(self) -> Self; + Self::abs(self) -> Self; + Self::signum(self) -> Self; + Self::is_sign_positive(self) -> bool; + Self::is_sign_negative(self) -> bool; + Self::mul_add(self, a: Self, b: Self) -> Self; + Self::recip(self) -> Self; + Self::powi(self, n: i32) -> Self; + Self::powf(self, n: Self) -> Self; + Self::sqrt(self) -> Self; + Self::exp(self) -> Self; + Self::exp2(self) -> Self; + Self::ln(self) -> Self; + Self::log(self, base: Self) -> Self; + Self::log2(self) -> Self; + Self::log10(self) -> Self; + Self::to_degrees(self) -> Self; + Self::to_radians(self) -> Self; + Self::max(self, other: Self) -> Self; + Self::min(self, other: Self) -> Self; + Self::cbrt(self) -> Self; + Self::hypot(self, other: Self) -> Self; + Self::sin(self) -> Self; + Self::cos(self) -> Self; + Self::tan(self) -> Self; + Self::asin(self) -> Self; + Self::acos(self) -> Self; + Self::atan(self) -> Self; + Self::atan2(self, other: Self) -> Self; + Self::sin_cos(self) -> (Self, Self); + Self::exp_m1(self) -> Self; + Self::ln_1p(self) -> Self; + Self::sinh(self) -> Self; + Self::cosh(self) -> Self; + Self::tanh(self) -> Self; + Self::asinh(self) -> Self; + Self::acosh(self) -> Self; + Self::atanh(self) -> Self; + } + } + ) +} + +fn integer_decode_f32(f: f32) -> (u64, i16, i8) { + let bits: u32 = unsafe { mem::transmute(f) }; + let sign: i8 = if bits >> 31 == 0 { + 1 + } else { + -1 + }; + let mut exponent: i16 = ((bits >> 23) & 0xff) as i16; + let mantissa = if exponent == 0 { + (bits & 0x7fffff) << 1 + } else { + (bits & 0x7fffff) | 0x800000 + }; + // Exponent bias + mantissa shift + exponent -= 127 + 23; + (mantissa as u64, exponent, sign) +} + +fn integer_decode_f64(f: f64) -> (u64, i16, i8) { + let bits: u64 = unsafe { mem::transmute(f) }; + let sign: i8 = if bits >> 63 == 0 { + 1 + } else { + -1 + }; + let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16; + let mantissa = if exponent == 0 { + (bits & 0xfffffffffffff) << 1 + } else { + (bits & 0xfffffffffffff) | 0x10000000000000 + }; + // Exponent bias + mantissa shift + exponent -= 1023 + 52; + (mantissa, exponent, sign) +} + +#[cfg(feature = "std")] +float_impl!(f32 integer_decode_f32); +#[cfg(feature = "std")] +float_impl!(f64 integer_decode_f64); + +macro_rules! float_const_impl { + ($(#[$doc:meta] $constant:ident,)+) => ( + #[allow(non_snake_case)] + pub trait FloatConst { + $(#[$doc] fn $constant() -> Self;)+ + } + float_const_impl! { @float f32, $($constant,)+ } + float_const_impl! { @float f64, $($constant,)+ } + ); + (@float $T:ident, $($constant:ident,)+) => ( + impl FloatConst for $T { + constant! { + $( $constant() -> $T::consts::$constant; )+ + } + } + ); +} + +float_const_impl! { + #[doc = "Return Euler’s number."] + E, + #[doc = "Return `1.0 / π`."] + FRAC_1_PI, + #[doc = "Return `1.0 / sqrt(2.0)`."] + FRAC_1_SQRT_2, + #[doc = "Return `2.0 / π`."] + FRAC_2_PI, + #[doc = "Return `2.0 / sqrt(π)`."] + FRAC_2_SQRT_PI, + #[doc = "Return `π / 2.0`."] + FRAC_PI_2, + #[doc = "Return `π / 3.0`."] + FRAC_PI_3, + #[doc = "Return `π / 4.0`."] + FRAC_PI_4, + #[doc = "Return `π / 6.0`."] + FRAC_PI_6, + #[doc = "Return `π / 8.0`."] + FRAC_PI_8, + #[doc = "Return `ln(10.0)`."] + LN_10, + #[doc = "Return `ln(2.0)`."] + LN_2, + #[doc = "Return `log10(e)`."] + LOG10_E, + #[doc = "Return `log2(e)`."] + LOG2_E, + #[doc = "Return Archimedes’ constant."] + PI, + #[doc = "Return `sqrt(2.0)`."] + SQRT_2, +} + +#[cfg(test)] +mod tests { + use core::f64::consts; + + const DEG_RAD_PAIRS: [(f64, f64); 7] = [ + (0.0, 0.), + (22.5, consts::FRAC_PI_8), + (30.0, consts::FRAC_PI_6), + (45.0, consts::FRAC_PI_4), + (60.0, consts::FRAC_PI_3), + (90.0, consts::FRAC_PI_2), + (180.0, consts::PI), + ]; + + #[test] + fn convert_deg_rad() { + use float::FloatCore; + + for &(deg, rad) in &DEG_RAD_PAIRS { + assert!((FloatCore::to_degrees(rad) - deg).abs() < 1e-6); + assert!((FloatCore::to_radians(deg) - rad).abs() < 1e-6); + + let (deg, rad) = (deg as f32, rad as f32); + assert!((FloatCore::to_degrees(rad) - deg).abs() < 1e-5); + assert!((FloatCore::to_radians(deg) - rad).abs() < 1e-5); + } + } + + #[cfg(feature = "std")] + #[test] + fn convert_deg_rad_std() { + for &(deg, rad) in &DEG_RAD_PAIRS { + use Float; + + assert!((Float::to_degrees(rad) - deg).abs() < 1e-6); + assert!((Float::to_radians(deg) - rad).abs() < 1e-6); + + let (deg, rad) = (deg as f32, rad as f32); + assert!((Float::to_degrees(rad) - deg).abs() < 1e-5); + assert!((Float::to_radians(deg) - rad).abs() < 1e-5); + } + } +} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/identities.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/identities.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/identities.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/identities.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,158 @@ +use core::ops::{Add, Mul}; +use core::num::Wrapping; + +/// Defines an additive identity element for `Self`. +pub trait Zero: Sized + Add { + /// Returns the additive identity element of `Self`, `0`. + /// + /// # Laws + /// + /// ```{.text} + /// a + 0 = a ∀ a ∈ Self + /// 0 + a = a ∀ a ∈ Self + /// ``` + /// + /// # Purity + /// + /// This function should return the same result at all times regardless of + /// external mutable state, for example values stored in TLS or in + /// `static mut`s. + // FIXME (#5527): This should be an associated constant + fn zero() -> Self; + + /// Returns `true` if `self` is equal to the additive identity. + #[inline] + fn is_zero(&self) -> bool; +} + +macro_rules! zero_impl { + ($t:ty, $v:expr) => { + impl Zero for $t { + #[inline] + fn zero() -> $t { $v } + #[inline] + fn is_zero(&self) -> bool { *self == $v } + } + } +} + +zero_impl!(usize, 0usize); +zero_impl!(u8, 0u8); +zero_impl!(u16, 0u16); +zero_impl!(u32, 0u32); +zero_impl!(u64, 0u64); + +zero_impl!(isize, 0isize); +zero_impl!(i8, 0i8); +zero_impl!(i16, 0i16); +zero_impl!(i32, 0i32); +zero_impl!(i64, 0i64); + +zero_impl!(f32, 0.0f32); +zero_impl!(f64, 0.0f64); + +impl Zero for Wrapping where Wrapping: Add> { + fn is_zero(&self) -> bool { + self.0.is_zero() + } + fn zero() -> Self { + Wrapping(T::zero()) + } +} + + +/// Defines a multiplicative identity element for `Self`. +pub trait One: Sized + Mul { + /// Returns the multiplicative identity element of `Self`, `1`. + /// + /// # Laws + /// + /// ```{.text} + /// a * 1 = a ∀ a ∈ Self + /// 1 * a = a ∀ a ∈ Self + /// ``` + /// + /// # Purity + /// + /// This function should return the same result at all times regardless of + /// external mutable state, for example values stored in TLS or in + /// `static mut`s. + // FIXME (#5527): This should be an associated constant + fn one() -> Self; + + /// Returns `true` if `self` is equal to the multiplicative identity. + /// + /// For performance reasons, it's best to implement this manually. + /// After a semver bump, this method will be required, and the + /// `where Self: PartialEq` bound will be removed. + #[inline] + fn is_one(&self) -> bool where Self: PartialEq { + *self == Self::one() + } +} + +macro_rules! one_impl { + ($t:ty, $v:expr) => { + impl One for $t { + #[inline] + fn one() -> $t { $v } + } + } +} + +one_impl!(usize, 1usize); +one_impl!(u8, 1u8); +one_impl!(u16, 1u16); +one_impl!(u32, 1u32); +one_impl!(u64, 1u64); + +one_impl!(isize, 1isize); +one_impl!(i8, 1i8); +one_impl!(i16, 1i16); +one_impl!(i32, 1i32); +one_impl!(i64, 1i64); + +one_impl!(f32, 1.0f32); +one_impl!(f64, 1.0f64); + +impl One for Wrapping where Wrapping: Mul> { + fn one() -> Self { + Wrapping(T::one()) + } +} + +// Some helper functions provided for backwards compatibility. + +/// Returns the additive identity, `0`. +#[inline(always)] pub fn zero() -> T { Zero::zero() } + +/// Returns the multiplicative identity, `1`. +#[inline(always)] pub fn one() -> T { One::one() } + + +#[test] +fn wrapping_identities() { + macro_rules! test_wrapping_identities { + ($($t:ty)+) => { + $( + assert_eq!(zero::<$t>(), zero::>().0); + assert_eq!(one::<$t>(), one::>().0); + assert_eq!((0 as $t).is_zero(), Wrapping(0 as $t).is_zero()); + assert_eq!((1 as $t).is_zero(), Wrapping(1 as $t).is_zero()); + )+ + }; + } + + test_wrapping_identities!(isize i8 i16 i32 i64 usize u8 u16 u32 u64); +} + +#[test] +fn wrapping_is_zero() { + fn require_zero(_: &T) {} + require_zero(&Wrapping(42)); +} +#[test] +fn wrapping_is_one() { + fn require_one(_: &T) {} + require_one(&Wrapping(42)); +} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/int.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/int.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/int.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/int.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,376 @@ +use core::ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr}; + +use {Num, NumCast}; +use bounds::Bounded; +use ops::checked::*; +use ops::saturating::Saturating; + +pub trait PrimInt + : Sized + + Copy + + Num + NumCast + + Bounded + + PartialOrd + Ord + Eq + + Not + + BitAnd + + BitOr + + BitXor + + Shl + + Shr + + CheckedAdd + + CheckedSub + + CheckedMul + + CheckedDiv + + Saturating +{ + /// Returns the number of ones in the binary representation of `self`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0b01001100u8; + /// + /// assert_eq!(n.count_ones(), 3); + /// ``` + fn count_ones(self) -> u32; + + /// Returns the number of zeros in the binary representation of `self`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0b01001100u8; + /// + /// assert_eq!(n.count_zeros(), 5); + /// ``` + fn count_zeros(self) -> u32; + + /// Returns the number of leading zeros in the binary representation + /// of `self`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0b0101000u16; + /// + /// assert_eq!(n.leading_zeros(), 10); + /// ``` + fn leading_zeros(self) -> u32; + + /// Returns the number of trailing zeros in the binary representation + /// of `self`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0b0101000u16; + /// + /// assert_eq!(n.trailing_zeros(), 3); + /// ``` + fn trailing_zeros(self) -> u32; + + /// Shifts the bits to the left by a specified amount amount, `n`, wrapping + /// the truncated bits to the end of the resulting integer. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// let m = 0x3456789ABCDEF012u64; + /// + /// assert_eq!(n.rotate_left(12), m); + /// ``` + fn rotate_left(self, n: u32) -> Self; + + /// Shifts the bits to the right by a specified amount amount, `n`, wrapping + /// the truncated bits to the beginning of the resulting integer. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// let m = 0xDEF0123456789ABCu64; + /// + /// assert_eq!(n.rotate_right(12), m); + /// ``` + fn rotate_right(self, n: u32) -> Self; + + /// Shifts the bits to the left by a specified amount amount, `n`, filling + /// zeros in the least significant bits. + /// + /// This is bitwise equivalent to signed `Shl`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// let m = 0x3456789ABCDEF000u64; + /// + /// assert_eq!(n.signed_shl(12), m); + /// ``` + fn signed_shl(self, n: u32) -> Self; + + /// Shifts the bits to the right by a specified amount amount, `n`, copying + /// the "sign bit" in the most significant bits even for unsigned types. + /// + /// This is bitwise equivalent to signed `Shr`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0xFEDCBA9876543210u64; + /// let m = 0xFFFFEDCBA9876543u64; + /// + /// assert_eq!(n.signed_shr(12), m); + /// ``` + fn signed_shr(self, n: u32) -> Self; + + /// Shifts the bits to the left by a specified amount amount, `n`, filling + /// zeros in the least significant bits. + /// + /// This is bitwise equivalent to unsigned `Shl`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFi64; + /// let m = 0x3456789ABCDEF000i64; + /// + /// assert_eq!(n.unsigned_shl(12), m); + /// ``` + fn unsigned_shl(self, n: u32) -> Self; + + /// Shifts the bits to the right by a specified amount amount, `n`, filling + /// zeros in the most significant bits. + /// + /// This is bitwise equivalent to unsigned `Shr`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0xFEDCBA9876543210i64; + /// let m = 0x000FEDCBA9876543i64; + /// + /// assert_eq!(n.unsigned_shr(12), m); + /// ``` + fn unsigned_shr(self, n: u32) -> Self; + + /// Reverses the byte order of the integer. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// let m = 0xEFCDAB8967452301u64; + /// + /// assert_eq!(n.swap_bytes(), m); + /// ``` + fn swap_bytes(self) -> Self; + + /// Convert an integer from big endian to the target's endianness. + /// + /// On big endian this is a no-op. On little endian the bytes are swapped. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// + /// if cfg!(target_endian = "big") { + /// assert_eq!(u64::from_be(n), n) + /// } else { + /// assert_eq!(u64::from_be(n), n.swap_bytes()) + /// } + /// ``` + fn from_be(x: Self) -> Self; + + /// Convert an integer from little endian to the target's endianness. + /// + /// On little endian this is a no-op. On big endian the bytes are swapped. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// + /// if cfg!(target_endian = "little") { + /// assert_eq!(u64::from_le(n), n) + /// } else { + /// assert_eq!(u64::from_le(n), n.swap_bytes()) + /// } + /// ``` + fn from_le(x: Self) -> Self; + + /// Convert `self` to big endian from the target's endianness. + /// + /// On big endian this is a no-op. On little endian the bytes are swapped. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// + /// if cfg!(target_endian = "big") { + /// assert_eq!(n.to_be(), n) + /// } else { + /// assert_eq!(n.to_be(), n.swap_bytes()) + /// } + /// ``` + fn to_be(self) -> Self; + + /// Convert `self` to little endian from the target's endianness. + /// + /// On little endian this is a no-op. On big endian the bytes are swapped. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// let n = 0x0123456789ABCDEFu64; + /// + /// if cfg!(target_endian = "little") { + /// assert_eq!(n.to_le(), n) + /// } else { + /// assert_eq!(n.to_le(), n.swap_bytes()) + /// } + /// ``` + fn to_le(self) -> Self; + + /// Raises self to the power of `exp`, using exponentiation by squaring. + /// + /// # Examples + /// + /// ``` + /// use num_traits::PrimInt; + /// + /// assert_eq!(2i32.pow(4), 16); + /// ``` + fn pow(self, exp: u32) -> Self; +} + +macro_rules! prim_int_impl { + ($T:ty, $S:ty, $U:ty) => ( + impl PrimInt for $T { + #[inline] + fn count_ones(self) -> u32 { + <$T>::count_ones(self) + } + + #[inline] + fn count_zeros(self) -> u32 { + <$T>::count_zeros(self) + } + + #[inline] + fn leading_zeros(self) -> u32 { + <$T>::leading_zeros(self) + } + + #[inline] + fn trailing_zeros(self) -> u32 { + <$T>::trailing_zeros(self) + } + + #[inline] + fn rotate_left(self, n: u32) -> Self { + <$T>::rotate_left(self, n) + } + + #[inline] + fn rotate_right(self, n: u32) -> Self { + <$T>::rotate_right(self, n) + } + + #[inline] + fn signed_shl(self, n: u32) -> Self { + ((self as $S) << n) as $T + } + + #[inline] + fn signed_shr(self, n: u32) -> Self { + ((self as $S) >> n) as $T + } + + #[inline] + fn unsigned_shl(self, n: u32) -> Self { + ((self as $U) << n) as $T + } + + #[inline] + fn unsigned_shr(self, n: u32) -> Self { + ((self as $U) >> n) as $T + } + + #[inline] + fn swap_bytes(self) -> Self { + <$T>::swap_bytes(self) + } + + #[inline] + fn from_be(x: Self) -> Self { + <$T>::from_be(x) + } + + #[inline] + fn from_le(x: Self) -> Self { + <$T>::from_le(x) + } + + #[inline] + fn to_be(self) -> Self { + <$T>::to_be(self) + } + + #[inline] + fn to_le(self) -> Self { + <$T>::to_le(self) + } + + #[inline] + fn pow(self, exp: u32) -> Self { + <$T>::pow(self, exp) + } + } + ) +} + +// prim_int_impl!(type, signed, unsigned); +prim_int_impl!(u8, i8, u8); +prim_int_impl!(u16, i16, u16); +prim_int_impl!(u32, i32, u32); +prim_int_impl!(u64, i64, u64); +prim_int_impl!(usize, isize, usize); +prim_int_impl!(i8, i8, u8); +prim_int_impl!(i16, i16, u16); +prim_int_impl!(i32, i32, u32); +prim_int_impl!(i64, i64, u64); +prim_int_impl!(isize, isize, usize); diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/lib.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/lib.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,472 @@ +// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Numeric traits for generic mathematics +//! +//! ## Compatibility +//! +//! The `num-traits` crate is tested for rustc 1.8 and greater. + +#![doc(html_root_url = "https://docs.rs/num-traits/0.2")] + +#![deny(unconditional_recursion)] + +#![cfg_attr(not(feature = "std"), no_std)] +#[cfg(feature = "std")] +extern crate core; + +use core::ops::{Add, Sub, Mul, Div, Rem}; +use core::ops::{AddAssign, SubAssign, MulAssign, DivAssign, RemAssign}; +use core::num::Wrapping; +use core::fmt; + +pub use bounds::Bounded; +#[cfg(feature = "std")] +pub use float::Float; +pub use float::FloatConst; +// pub use real::{FloatCore, Real}; // NOTE: Don't do this, it breaks `use num_traits::*;`. +pub use identities::{Zero, One, zero, one}; +pub use ops::inv::Inv; +pub use ops::checked::{CheckedAdd, CheckedSub, CheckedMul, CheckedDiv, CheckedShl, CheckedShr}; +pub use ops::wrapping::{WrappingAdd, WrappingMul, WrappingSub}; +pub use ops::saturating::Saturating; +pub use sign::{Signed, Unsigned, abs, abs_sub, signum}; +pub use cast::{AsPrimitive, FromPrimitive, ToPrimitive, NumCast, cast}; +pub use int::PrimInt; +pub use pow::{Pow, pow, checked_pow}; + +#[macro_use] +mod macros; + +pub mod identities; +pub mod sign; +pub mod ops; +pub mod bounds; +pub mod float; +#[cfg(feature = "std")] +pub mod real; +pub mod cast; +pub mod int; +pub mod pow; + +/// The base trait for numeric types, covering `0` and `1` values, +/// comparisons, basic numeric operations, and string conversion. +pub trait Num: PartialEq + Zero + One + NumOps +{ + type FromStrRadixErr; + + /// Convert from a string and radix <= 36. + /// + /// # Examples + /// + /// ```rust + /// use num_traits::Num; + /// + /// let result = ::from_str_radix("27", 10); + /// assert_eq!(result, Ok(27)); + /// + /// let result = ::from_str_radix("foo", 10); + /// assert!(result.is_err()); + /// ``` + fn from_str_radix(str: &str, radix: u32) -> Result; +} + +/// The trait for types implementing basic numeric operations +/// +/// This is automatically implemented for types which implement the operators. +pub trait NumOps + : Add + + Sub + + Mul + + Div + + Rem +{} + +impl NumOps for T +where T: Add + + Sub + + Mul + + Div + + Rem +{} + +/// The trait for `Num` types which also implement numeric operations taking +/// the second operand by reference. +/// +/// This is automatically implemented for types which implement the operators. +pub trait NumRef: Num + for<'r> NumOps<&'r Self> {} +impl NumRef for T where T: Num + for<'r> NumOps<&'r T> {} + +/// The trait for references which implement numeric operations, taking the +/// second operand either by value or by reference. +/// +/// This is automatically implemented for types which implement the operators. +pub trait RefNum: NumOps + for<'r> NumOps<&'r Base, Base> {} +impl RefNum for T where T: NumOps + for<'r> NumOps<&'r Base, Base> {} + +/// The trait for types implementing numeric assignment operators (like `+=`). +/// +/// This is automatically implemented for types which implement the operators. +pub trait NumAssignOps + : AddAssign + + SubAssign + + MulAssign + + DivAssign + + RemAssign +{} + +impl NumAssignOps for T +where T: AddAssign + + SubAssign + + MulAssign + + DivAssign + + RemAssign +{} + +/// The trait for `Num` types which also implement assignment operators. +/// +/// This is automatically implemented for types which implement the operators. +pub trait NumAssign: Num + NumAssignOps {} +impl NumAssign for T where T: Num + NumAssignOps {} + +/// The trait for `NumAssign` types which also implement assignment operations +/// taking the second operand by reference. +/// +/// This is automatically implemented for types which implement the operators. +pub trait NumAssignRef: NumAssign + for<'r> NumAssignOps<&'r Self> {} +impl NumAssignRef for T where T: NumAssign + for<'r> NumAssignOps<&'r T> {} + + +macro_rules! int_trait_impl { + ($name:ident for $($t:ty)*) => ($( + impl $name for $t { + type FromStrRadixErr = ::core::num::ParseIntError; + #[inline] + fn from_str_radix(s: &str, radix: u32) + -> Result + { + <$t>::from_str_radix(s, radix) + } + } + )*) +} +int_trait_impl!(Num for usize u8 u16 u32 u64 isize i8 i16 i32 i64); + +impl Num for Wrapping + where Wrapping: + Add> + Sub> + + Mul> + Div> + Rem> +{ + type FromStrRadixErr = T::FromStrRadixErr; + fn from_str_radix(str: &str, radix: u32) -> Result { + T::from_str_radix(str, radix).map(Wrapping) + } +} + + +#[derive(Debug)] +pub enum FloatErrorKind { + Empty, + Invalid, +} +// FIXME: core::num::ParseFloatError is stable in 1.0, but opaque to us, +// so there's not really any way for us to reuse it. +#[derive(Debug)] +pub struct ParseFloatError { + pub kind: FloatErrorKind, +} + +impl fmt::Display for ParseFloatError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let description = match self.kind { + FloatErrorKind::Empty => "cannot parse float from empty string", + FloatErrorKind::Invalid => "invalid float literal", + }; + + description.fmt(f) + } +} + +// FIXME: The standard library from_str_radix on floats was deprecated, so we're stuck +// with this implementation ourselves until we want to make a breaking change. +// (would have to drop it from `Num` though) +macro_rules! float_trait_impl { + ($name:ident for $($t:ident)*) => ($( + impl $name for $t { + type FromStrRadixErr = ParseFloatError; + + fn from_str_radix(src: &str, radix: u32) + -> Result + { + use self::FloatErrorKind::*; + use self::ParseFloatError as PFE; + + // Special values + match src { + "inf" => return Ok(core::$t::INFINITY), + "-inf" => return Ok(core::$t::NEG_INFINITY), + "NaN" => return Ok(core::$t::NAN), + _ => {}, + } + + fn slice_shift_char(src: &str) -> Option<(char, &str)> { + src.chars().nth(0).map(|ch| (ch, &src[1..])) + } + + let (is_positive, src) = match slice_shift_char(src) { + None => return Err(PFE { kind: Empty }), + Some(('-', "")) => return Err(PFE { kind: Empty }), + Some(('-', src)) => (false, src), + Some((_, _)) => (true, src), + }; + + // The significand to accumulate + let mut sig = if is_positive { 0.0 } else { -0.0 }; + // Necessary to detect overflow + let mut prev_sig = sig; + let mut cs = src.chars().enumerate(); + // Exponent prefix and exponent index offset + let mut exp_info = None::<(char, usize)>; + + // Parse the integer part of the significand + for (i, c) in cs.by_ref() { + match c.to_digit(radix) { + Some(digit) => { + // shift significand one digit left + sig = sig * (radix as $t); + + // add/subtract current digit depending on sign + if is_positive { + sig = sig + ((digit as isize) as $t); + } else { + sig = sig - ((digit as isize) as $t); + } + + // Detect overflow by comparing to last value, except + // if we've not seen any non-zero digits. + if prev_sig != 0.0 { + if is_positive && sig <= prev_sig + { return Ok(core::$t::INFINITY); } + if !is_positive && sig >= prev_sig + { return Ok(core::$t::NEG_INFINITY); } + + // Detect overflow by reversing the shift-and-add process + if is_positive && (prev_sig != (sig - digit as $t) / radix as $t) + { return Ok(core::$t::INFINITY); } + if !is_positive && (prev_sig != (sig + digit as $t) / radix as $t) + { return Ok(core::$t::NEG_INFINITY); } + } + prev_sig = sig; + }, + None => match c { + 'e' | 'E' | 'p' | 'P' => { + exp_info = Some((c, i + 1)); + break; // start of exponent + }, + '.' => { + break; // start of fractional part + }, + _ => { + return Err(PFE { kind: Invalid }); + }, + }, + } + } + + // If we are not yet at the exponent parse the fractional + // part of the significand + if exp_info.is_none() { + let mut power = 1.0; + for (i, c) in cs.by_ref() { + match c.to_digit(radix) { + Some(digit) => { + // Decrease power one order of magnitude + power = power / (radix as $t); + // add/subtract current digit depending on sign + sig = if is_positive { + sig + (digit as $t) * power + } else { + sig - (digit as $t) * power + }; + // Detect overflow by comparing to last value + if is_positive && sig < prev_sig + { return Ok(core::$t::INFINITY); } + if !is_positive && sig > prev_sig + { return Ok(core::$t::NEG_INFINITY); } + prev_sig = sig; + }, + None => match c { + 'e' | 'E' | 'p' | 'P' => { + exp_info = Some((c, i + 1)); + break; // start of exponent + }, + _ => { + return Err(PFE { kind: Invalid }); + }, + }, + } + } + } + + // Parse and calculate the exponent + let exp = match exp_info { + Some((c, offset)) => { + let base = match c { + 'E' | 'e' if radix == 10 => 10.0, + 'P' | 'p' if radix == 16 => 2.0, + _ => return Err(PFE { kind: Invalid }), + }; + + // Parse the exponent as decimal integer + let src = &src[offset..]; + let (is_positive, exp) = match slice_shift_char(src) { + Some(('-', src)) => (false, src.parse::()), + Some(('+', src)) => (true, src.parse::()), + Some((_, _)) => (true, src.parse::()), + None => return Err(PFE { kind: Invalid }), + }; + + #[cfg(feature = "std")] + fn pow(base: $t, exp: usize) -> $t { + Float::powi(base, exp as i32) + } + // otherwise uses the generic `pow` from the root + + match (is_positive, exp) { + (true, Ok(exp)) => pow(base, exp), + (false, Ok(exp)) => 1.0 / pow(base, exp), + (_, Err(_)) => return Err(PFE { kind: Invalid }), + } + }, + None => 1.0, // no exponent + }; + + Ok(sig * exp) + } + } + )*) +} +float_trait_impl!(Num for f32 f64); + +/// A value bounded by a minimum and a maximum +/// +/// If input is less than min then this returns min. +/// If input is greater than max then this returns max. +/// Otherwise this returns input. +#[inline] +pub fn clamp(input: T, min: T, max: T) -> T { + debug_assert!(min <= max, "min must be less than or equal to max"); + if input < min { + min + } else if input > max { + max + } else { + input + } +} + +#[test] +fn clamp_test() { + // Int test + assert_eq!(1, clamp(1, -1, 2)); + assert_eq!(-1, clamp(-2, -1, 2)); + assert_eq!(2, clamp(3, -1, 2)); + + // Float test + assert_eq!(1.0, clamp(1.0, -1.0, 2.0)); + assert_eq!(-1.0, clamp(-2.0, -1.0, 2.0)); + assert_eq!(2.0, clamp(3.0, -1.0, 2.0)); +} + +#[test] +fn from_str_radix_unwrap() { + // The Result error must impl Debug to allow unwrap() + + let i: i32 = Num::from_str_radix("0", 10).unwrap(); + assert_eq!(i, 0); + + let f: f32 = Num::from_str_radix("0.0", 10).unwrap(); + assert_eq!(f, 0.0); +} + +#[test] +fn wrapping_is_num() { + fn require_num(_: &T) {} + require_num(&Wrapping(42_u32)); + require_num(&Wrapping(-42)); +} + +#[test] +fn wrapping_from_str_radix() { + macro_rules! test_wrapping_from_str_radix { + ($($t:ty)+) => { + $( + for &(s, r) in &[("42", 10), ("42", 2), ("-13.0", 10), ("foo", 10)] { + let w = Wrapping::<$t>::from_str_radix(s, r).map(|w| w.0); + assert_eq!(w, <$t as Num>::from_str_radix(s, r)); + } + )+ + }; + } + + test_wrapping_from_str_radix!(usize u8 u16 u32 u64 isize i8 i16 i32 i64); +} + +#[test] +fn check_num_ops() { + fn compute(x: T, y: T) -> T { + x * y / y % y + y - y + } + assert_eq!(compute(1, 2), 1) +} + +#[test] +fn check_numref_ops() { + fn compute(x: T, y: &T) -> T { + x * y / y % y + y - y + } + assert_eq!(compute(1, &2), 1) +} + +#[test] +fn check_refnum_ops() { + fn compute(x: &T, y: T) -> T + where for<'a> &'a T: RefNum + { + &(&(&(&(x * y) / y) % y) + y) - y + } + assert_eq!(compute(&1, 2), 1) +} + +#[test] +fn check_refref_ops() { + fn compute(x: &T, y: &T) -> T + where for<'a> &'a T: RefNum + { + &(&(&(&(x * y) / y) % y) + y) - y + } + assert_eq!(compute(&1, &2), 1) +} + +#[test] +fn check_numassign_ops() { + fn compute(mut x: T, y: T) -> T { + x *= y; + x /= y; + x %= y; + x += y; + x -= y; + x + } + assert_eq!(compute(1, 2), 1) +} + +// TODO test `NumAssignRef`, but even the standard numeric types don't +// implement this yet. (see rust pr41336) diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/macros.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/macros.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/macros.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/macros.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,37 @@ +// not all are used in all features configurations +#![allow(unused)] + +/// Forward a method to an inherent method or a base trait method. +macro_rules! forward { + ($( Self :: $method:ident ( self $( , $arg:ident : $ty:ty )* ) -> $ret:ty ; )*) + => {$( + #[inline] + fn $method(self $( , $arg : $ty )* ) -> $ret { + Self::$method(self $( , $arg )* ) + } + )*}; + ($( $base:ident :: $method:ident ( self $( , $arg:ident : $ty:ty )* ) -> $ret:ty ; )*) + => {$( + #[inline] + fn $method(self $( , $arg : $ty )* ) -> $ret { + ::$method(self $( , $arg )* ) + } + )*}; + ($( $base:ident :: $method:ident ( $( $arg:ident : $ty:ty ),* ) -> $ret:ty ; )*) + => {$( + #[inline] + fn $method( $( $arg : $ty ),* ) -> $ret { + ::$method( $( $arg ),* ) + } + )*} +} + +macro_rules! constant { + ($( $method:ident () -> $ret:expr ; )*) + => {$( + #[inline] + fn $method() -> Self { + $ret + } + )*}; +} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/ops/checked.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/ops/checked.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/ops/checked.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/ops/checked.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,162 @@ +use core::ops::{Add, Sub, Mul, Div, Shl, Shr}; + +/// Performs addition that returns `None` instead of wrapping around on +/// overflow. +pub trait CheckedAdd: Sized + Add { + /// Adds two numbers, checking for overflow. If overflow happens, `None` is + /// returned. + fn checked_add(&self, v: &Self) -> Option; +} + +macro_rules! checked_impl { + ($trait_name:ident, $method:ident, $t:ty) => { + impl $trait_name for $t { + #[inline] + fn $method(&self, v: &$t) -> Option<$t> { + <$t>::$method(*self, *v) + } + } + } +} + +checked_impl!(CheckedAdd, checked_add, u8); +checked_impl!(CheckedAdd, checked_add, u16); +checked_impl!(CheckedAdd, checked_add, u32); +checked_impl!(CheckedAdd, checked_add, u64); +checked_impl!(CheckedAdd, checked_add, usize); + +checked_impl!(CheckedAdd, checked_add, i8); +checked_impl!(CheckedAdd, checked_add, i16); +checked_impl!(CheckedAdd, checked_add, i32); +checked_impl!(CheckedAdd, checked_add, i64); +checked_impl!(CheckedAdd, checked_add, isize); + +/// Performs subtraction that returns `None` instead of wrapping around on underflow. +pub trait CheckedSub: Sized + Sub { + /// Subtracts two numbers, checking for underflow. If underflow happens, + /// `None` is returned. + fn checked_sub(&self, v: &Self) -> Option; +} + +checked_impl!(CheckedSub, checked_sub, u8); +checked_impl!(CheckedSub, checked_sub, u16); +checked_impl!(CheckedSub, checked_sub, u32); +checked_impl!(CheckedSub, checked_sub, u64); +checked_impl!(CheckedSub, checked_sub, usize); + +checked_impl!(CheckedSub, checked_sub, i8); +checked_impl!(CheckedSub, checked_sub, i16); +checked_impl!(CheckedSub, checked_sub, i32); +checked_impl!(CheckedSub, checked_sub, i64); +checked_impl!(CheckedSub, checked_sub, isize); + +/// Performs multiplication that returns `None` instead of wrapping around on underflow or +/// overflow. +pub trait CheckedMul: Sized + Mul { + /// Multiplies two numbers, checking for underflow or overflow. If underflow + /// or overflow happens, `None` is returned. + fn checked_mul(&self, v: &Self) -> Option; +} + +checked_impl!(CheckedMul, checked_mul, u8); +checked_impl!(CheckedMul, checked_mul, u16); +checked_impl!(CheckedMul, checked_mul, u32); +checked_impl!(CheckedMul, checked_mul, u64); +checked_impl!(CheckedMul, checked_mul, usize); + +checked_impl!(CheckedMul, checked_mul, i8); +checked_impl!(CheckedMul, checked_mul, i16); +checked_impl!(CheckedMul, checked_mul, i32); +checked_impl!(CheckedMul, checked_mul, i64); +checked_impl!(CheckedMul, checked_mul, isize); + +/// Performs division that returns `None` instead of panicking on division by zero and instead of +/// wrapping around on underflow and overflow. +pub trait CheckedDiv: Sized + Div { + /// Divides two numbers, checking for underflow, overflow and division by + /// zero. If any of that happens, `None` is returned. + fn checked_div(&self, v: &Self) -> Option; +} + +checked_impl!(CheckedDiv, checked_div, u8); +checked_impl!(CheckedDiv, checked_div, u16); +checked_impl!(CheckedDiv, checked_div, u32); +checked_impl!(CheckedDiv, checked_div, u64); +checked_impl!(CheckedDiv, checked_div, usize); + +checked_impl!(CheckedDiv, checked_div, i8); +checked_impl!(CheckedDiv, checked_div, i16); +checked_impl!(CheckedDiv, checked_div, i32); +checked_impl!(CheckedDiv, checked_div, i64); +checked_impl!(CheckedDiv, checked_div, isize); + +/// Performs a left shift that returns `None` on overflow. +pub trait CheckedShl: Sized + Shl { + /// Shifts a number to the left, checking for overflow. If overflow happens, + /// `None` is returned. + /// + /// ``` + /// use num_traits::CheckedShl; + /// + /// let x: u16 = 0x0001; + /// + /// assert_eq!(CheckedShl::checked_shl(&x, 0), Some(0x0001)); + /// assert_eq!(CheckedShl::checked_shl(&x, 1), Some(0x0002)); + /// assert_eq!(CheckedShl::checked_shl(&x, 15), Some(0x8000)); + /// assert_eq!(CheckedShl::checked_shl(&x, 16), None); + /// ``` + fn checked_shl(&self, rhs: u32) -> Option; +} + +macro_rules! checked_shift_impl { + ($trait_name:ident, $method:ident, $t:ty) => { + impl $trait_name for $t { + #[inline] + fn $method(&self, rhs: u32) -> Option<$t> { + <$t>::$method(*self, rhs) + } + } + } +} + +checked_shift_impl!(CheckedShl, checked_shl, u8); +checked_shift_impl!(CheckedShl, checked_shl, u16); +checked_shift_impl!(CheckedShl, checked_shl, u32); +checked_shift_impl!(CheckedShl, checked_shl, u64); +checked_shift_impl!(CheckedShl, checked_shl, usize); + +checked_shift_impl!(CheckedShl, checked_shl, i8); +checked_shift_impl!(CheckedShl, checked_shl, i16); +checked_shift_impl!(CheckedShl, checked_shl, i32); +checked_shift_impl!(CheckedShl, checked_shl, i64); +checked_shift_impl!(CheckedShl, checked_shl, isize); + +/// Performs a right shift that returns `None` on overflow. +pub trait CheckedShr: Sized + Shr { + /// Shifts a number to the left, checking for overflow. If overflow happens, + /// `None` is returned. + /// + /// ``` + /// use num_traits::CheckedShr; + /// + /// let x: u16 = 0x8000; + /// + /// assert_eq!(CheckedShr::checked_shr(&x, 0), Some(0x8000)); + /// assert_eq!(CheckedShr::checked_shr(&x, 1), Some(0x4000)); + /// assert_eq!(CheckedShr::checked_shr(&x, 15), Some(0x0001)); + /// assert_eq!(CheckedShr::checked_shr(&x, 16), None); + /// ``` + fn checked_shr(&self, rhs: u32) -> Option; +} + +checked_shift_impl!(CheckedShr, checked_shr, u8); +checked_shift_impl!(CheckedShr, checked_shr, u16); +checked_shift_impl!(CheckedShr, checked_shr, u32); +checked_shift_impl!(CheckedShr, checked_shr, u64); +checked_shift_impl!(CheckedShr, checked_shr, usize); + +checked_shift_impl!(CheckedShr, checked_shr, i8); +checked_shift_impl!(CheckedShr, checked_shr, i16); +checked_shift_impl!(CheckedShr, checked_shr, i32); +checked_shift_impl!(CheckedShr, checked_shr, i64); +checked_shift_impl!(CheckedShr, checked_shr, isize); diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/ops/inv.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/ops/inv.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/ops/inv.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/ops/inv.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,39 @@ +/// Unary operator for retrieving the multiplicative inverse, or reciprocal, of a value. +pub trait Inv { + /// The result after applying the operator. + type Output; + + /// Returns the multiplicative inverse of `self`. + /// + /// # Examples + /// + /// ``` + /// use std::f64::INFINITY; + /// use num_traits::Inv; + /// + /// assert_eq!(7.0.inv() * 7.0, 1.0); + /// assert_eq!((-0.0).inv(), -INFINITY); + /// ``` + fn inv(self) -> Self::Output; +} + +impl Inv for f32 { + type Output = f32; + #[inline] + fn inv(self) -> f32 { 1.0 / self } +} +impl Inv for f64 { + type Output = f64; + #[inline] + fn inv(self) -> f64 { 1.0 / self } +} +impl<'a> Inv for &'a f32 { + type Output = f32; + #[inline] + fn inv(self) -> f32 { 1.0 / *self } +} +impl<'a> Inv for &'a f64 { + type Output = f64; + #[inline] + fn inv(self) -> f64 { 1.0 / *self } +} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/ops/mod.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/ops/mod.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/ops/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/ops/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,4 @@ +pub mod saturating; +pub mod checked; +pub mod wrapping; +pub mod inv; diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/ops/saturating.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/ops/saturating.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/ops/saturating.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/ops/saturating.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,28 @@ +/// Saturating math operations +pub trait Saturating { + /// Saturating addition operator. + /// Returns a+b, saturating at the numeric bounds instead of overflowing. + fn saturating_add(self, v: Self) -> Self; + + /// Saturating subtraction operator. + /// Returns a-b, saturating at the numeric bounds instead of overflowing. + fn saturating_sub(self, v: Self) -> Self; +} + +macro_rules! saturating_impl { + ($trait_name:ident for $($t:ty)*) => {$( + impl $trait_name for $t { + #[inline] + fn saturating_add(self, v: Self) -> Self { + Self::saturating_add(self, v) + } + + #[inline] + fn saturating_sub(self, v: Self) -> Self { + Self::saturating_sub(self, v) + } + } + )*} +} + +saturating_impl!(Saturating for isize usize i8 u8 i16 u16 i32 u32 i64 u64); diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/ops/wrapping.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/ops/wrapping.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/ops/wrapping.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/ops/wrapping.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,127 @@ +use core::ops::{Add, Sub, Mul}; +use core::num::Wrapping; + +macro_rules! wrapping_impl { + ($trait_name:ident, $method:ident, $t:ty) => { + impl $trait_name for $t { + #[inline] + fn $method(&self, v: &Self) -> Self { + <$t>::$method(*self, *v) + } + } + }; + ($trait_name:ident, $method:ident, $t:ty, $rhs:ty) => { + impl $trait_name<$rhs> for $t { + #[inline] + fn $method(&self, v: &$rhs) -> Self { + <$t>::$method(*self, *v) + } + } + } +} + +/// Performs addition that wraps around on overflow. +pub trait WrappingAdd: Sized + Add { + /// Wrapping (modular) addition. Computes `self + other`, wrapping around at the boundary of + /// the type. + fn wrapping_add(&self, v: &Self) -> Self; +} + +wrapping_impl!(WrappingAdd, wrapping_add, u8); +wrapping_impl!(WrappingAdd, wrapping_add, u16); +wrapping_impl!(WrappingAdd, wrapping_add, u32); +wrapping_impl!(WrappingAdd, wrapping_add, u64); +wrapping_impl!(WrappingAdd, wrapping_add, usize); + +wrapping_impl!(WrappingAdd, wrapping_add, i8); +wrapping_impl!(WrappingAdd, wrapping_add, i16); +wrapping_impl!(WrappingAdd, wrapping_add, i32); +wrapping_impl!(WrappingAdd, wrapping_add, i64); +wrapping_impl!(WrappingAdd, wrapping_add, isize); + +/// Performs subtraction that wraps around on overflow. +pub trait WrappingSub: Sized + Sub { + /// Wrapping (modular) subtraction. Computes `self - other`, wrapping around at the boundary + /// of the type. + fn wrapping_sub(&self, v: &Self) -> Self; +} + +wrapping_impl!(WrappingSub, wrapping_sub, u8); +wrapping_impl!(WrappingSub, wrapping_sub, u16); +wrapping_impl!(WrappingSub, wrapping_sub, u32); +wrapping_impl!(WrappingSub, wrapping_sub, u64); +wrapping_impl!(WrappingSub, wrapping_sub, usize); + +wrapping_impl!(WrappingSub, wrapping_sub, i8); +wrapping_impl!(WrappingSub, wrapping_sub, i16); +wrapping_impl!(WrappingSub, wrapping_sub, i32); +wrapping_impl!(WrappingSub, wrapping_sub, i64); +wrapping_impl!(WrappingSub, wrapping_sub, isize); + +/// Performs multiplication that wraps around on overflow. +pub trait WrappingMul: Sized + Mul { + /// Wrapping (modular) multiplication. Computes `self * other`, wrapping around at the boundary + /// of the type. + fn wrapping_mul(&self, v: &Self) -> Self; +} + +wrapping_impl!(WrappingMul, wrapping_mul, u8); +wrapping_impl!(WrappingMul, wrapping_mul, u16); +wrapping_impl!(WrappingMul, wrapping_mul, u32); +wrapping_impl!(WrappingMul, wrapping_mul, u64); +wrapping_impl!(WrappingMul, wrapping_mul, usize); + +wrapping_impl!(WrappingMul, wrapping_mul, i8); +wrapping_impl!(WrappingMul, wrapping_mul, i16); +wrapping_impl!(WrappingMul, wrapping_mul, i32); +wrapping_impl!(WrappingMul, wrapping_mul, i64); +wrapping_impl!(WrappingMul, wrapping_mul, isize); + +// Well this is a bit funny, but all the more appropriate. +impl WrappingAdd for Wrapping where Wrapping: Add> { + fn wrapping_add(&self, v: &Self) -> Self { + Wrapping(self.0.wrapping_add(&v.0)) + } +} +impl WrappingSub for Wrapping where Wrapping: Sub> { + fn wrapping_sub(&self, v: &Self) -> Self { + Wrapping(self.0.wrapping_sub(&v.0)) + } +} +impl WrappingMul for Wrapping where Wrapping: Mul> { + fn wrapping_mul(&self, v: &Self) -> Self { + Wrapping(self.0.wrapping_mul(&v.0)) + } +} + + +#[test] +fn test_wrapping_traits() { + fn wrapping_add(a: T, b: T) -> T { a.wrapping_add(&b) } + fn wrapping_sub(a: T, b: T) -> T { a.wrapping_sub(&b) } + fn wrapping_mul(a: T, b: T) -> T { a.wrapping_mul(&b) } + assert_eq!(wrapping_add(255, 1), 0u8); + assert_eq!(wrapping_sub(0, 1), 255u8); + assert_eq!(wrapping_mul(255, 2), 254u8); + assert_eq!(wrapping_add(255, 1), (Wrapping(255u8) + Wrapping(1u8)).0); + assert_eq!(wrapping_sub(0, 1), (Wrapping(0u8) - Wrapping(1u8)).0); + assert_eq!(wrapping_mul(255, 2), (Wrapping(255u8) * Wrapping(2u8)).0); +} + +#[test] +fn wrapping_is_wrappingadd() { + fn require_wrappingadd(_: &T) {} + require_wrappingadd(&Wrapping(42)); +} + +#[test] +fn wrapping_is_wrappingsub() { + fn require_wrappingsub(_: &T) {} + require_wrappingsub(&Wrapping(42)); +} + +#[test] +fn wrapping_is_wrappingmul() { + fn require_wrappingmul(_: &T) {} + require_wrappingmul(&Wrapping(42)); +} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/pow.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/pow.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/pow.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/pow.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,220 @@ +use core::ops::Mul; +use core::num::Wrapping; +use {One, CheckedMul}; + +/// Binary operator for raising a value to a power. +pub trait Pow { + /// The result after applying the operator. + type Output; + + /// Returns `self` to the power `rhs`. + /// + /// # Examples + /// + /// ``` + /// use num_traits::Pow; + /// assert_eq!(Pow::pow(10u32, 2u32), 100); + /// ``` + fn pow(self, rhs: RHS) -> Self::Output; +} + +macro_rules! pow_impl { + ($t:ty) => { + pow_impl!($t, u8); + pow_impl!($t, usize); + + // FIXME: these should be possible + // pow_impl!($t, u16); + // pow_impl!($t, u32); + // pow_impl!($t, u64); + }; + ($t:ty, $rhs:ty) => { + pow_impl!($t, $rhs, usize, pow); + }; + ($t:ty, $rhs:ty, $desired_rhs:ty, $method:expr) => { + impl Pow<$rhs> for $t { + type Output = $t; + #[inline] + fn pow(self, rhs: $rhs) -> $t { + ($method)(self, <$desired_rhs>::from(rhs)) + } + } + + impl<'a> Pow<&'a $rhs> for $t { + type Output = $t; + #[inline] + fn pow(self, rhs: &'a $rhs) -> $t { + ($method)(self, <$desired_rhs>::from(*rhs)) + } + } + + impl<'a> Pow<$rhs> for &'a $t { + type Output = $t; + #[inline] + fn pow(self, rhs: $rhs) -> $t { + ($method)(*self, <$desired_rhs>::from(rhs)) + } + } + + impl<'a, 'b> Pow<&'a $rhs> for &'b $t { + type Output = $t; + #[inline] + fn pow(self, rhs: &'a $rhs) -> $t { + ($method)(*self, <$desired_rhs>::from(*rhs)) + } + } + }; +} + +pow_impl!(u8, u8, u32, u8::pow); +pow_impl!(u8, u16, u32, u8::pow); +pow_impl!(u8, u32, u32, u8::pow); +pow_impl!(u8, usize); +pow_impl!(i8, u8, u32, i8::pow); +pow_impl!(i8, u16, u32, i8::pow); +pow_impl!(i8, u32, u32, i8::pow); +pow_impl!(i8, usize); +pow_impl!(u16, u8, u32, u16::pow); +pow_impl!(u16, u16, u32, u16::pow); +pow_impl!(u16, u32, u32, u16::pow); +pow_impl!(u16, usize); +pow_impl!(i16, u8, u32, i16::pow); +pow_impl!(i16, u16, u32, i16::pow); +pow_impl!(i16, u32, u32, i16::pow); +pow_impl!(i16, usize); +pow_impl!(u32, u8, u32, u32::pow); +pow_impl!(u32, u16, u32, u32::pow); +pow_impl!(u32, u32, u32, u32::pow); +pow_impl!(u32, usize); +pow_impl!(i32, u8, u32, i32::pow); +pow_impl!(i32, u16, u32, i32::pow); +pow_impl!(i32, u32, u32, i32::pow); +pow_impl!(i32, usize); +pow_impl!(u64, u8, u32, u64::pow); +pow_impl!(u64, u16, u32, u64::pow); +pow_impl!(u64, u32, u32, u64::pow); +pow_impl!(u64, usize); +pow_impl!(i64, u8, u32, i64::pow); +pow_impl!(i64, u16, u32, i64::pow); +pow_impl!(i64, u32, u32, i64::pow); +pow_impl!(i64, usize); +pow_impl!(usize, u8, u32, usize::pow); +pow_impl!(usize, u16, u32, usize::pow); +pow_impl!(usize, u32, u32, usize::pow); +pow_impl!(usize, usize); +pow_impl!(isize, u8, u32, isize::pow); +pow_impl!(isize, u16, u32, isize::pow); +pow_impl!(isize, u32, u32, isize::pow); +pow_impl!(isize, usize); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); +pow_impl!(Wrapping); + +// FIXME: these should be possible +// pow_impl!(u8, u64); +// pow_impl!(i16, u64); +// pow_impl!(i8, u64); +// pow_impl!(u16, u64); +// pow_impl!(u32, u64); +// pow_impl!(i32, u64); +// pow_impl!(u64, u64); +// pow_impl!(i64, u64); +// pow_impl!(usize, u64); +// pow_impl!(isize, u64); + +#[cfg(feature = "std")] +mod float_impls { + use super::Pow; + + pow_impl!(f32, i8, i32, f32::powi); + pow_impl!(f32, u8, i32, f32::powi); + pow_impl!(f32, i16, i32, f32::powi); + pow_impl!(f32, u16, i32, f32::powi); + pow_impl!(f32, i32, i32, f32::powi); + pow_impl!(f64, i8, i32, f64::powi); + pow_impl!(f64, u8, i32, f64::powi); + pow_impl!(f64, i16, i32, f64::powi); + pow_impl!(f64, u16, i32, f64::powi); + pow_impl!(f64, i32, i32, f64::powi); + pow_impl!(f32, f32, f32, f32::powf); + pow_impl!(f64, f32, f64, f64::powf); + pow_impl!(f64, f64, f64, f64::powf); +} + +/// Raises a value to the power of exp, using exponentiation by squaring. +/// +/// # Example +/// +/// ```rust +/// use num_traits::pow; +/// +/// assert_eq!(pow(2i8, 4), 16); +/// assert_eq!(pow(6u8, 3), 216); +/// ``` +#[inline] +pub fn pow>(mut base: T, mut exp: usize) -> T { + if exp == 0 { return T::one() } + + while exp & 1 == 0 { + base = base.clone() * base; + exp >>= 1; + } + if exp == 1 { return base } + + let mut acc = base.clone(); + while exp > 1 { + exp >>= 1; + base = base.clone() * base; + if exp & 1 == 1 { + acc = acc * base.clone(); + } + } + acc +} + +/// Raises a value to the power of exp, returning `None` if an overflow occurred. +/// +/// Otherwise same as the `pow` function. +/// +/// # Example +/// +/// ```rust +/// use num_traits::checked_pow; +/// +/// assert_eq!(checked_pow(2i8, 4), Some(16)); +/// assert_eq!(checked_pow(7i8, 8), None); +/// assert_eq!(checked_pow(7u32, 8), Some(5_764_801)); +/// ``` +#[inline] +pub fn checked_pow(mut base: T, mut exp: usize) -> Option { + if exp == 0 { return Some(T::one()) } + + macro_rules! optry { + ( $ expr : expr ) => { + if let Some(val) = $expr { val } else { return None } + } + } + + while exp & 1 == 0 { + base = optry!(base.checked_mul(&base)); + exp >>= 1; + } + if exp == 1 { return Some(base) } + + let mut acc = base.clone(); + while exp > 1 { + exp >>= 1; + base = optry!(base.checked_mul(&base)); + if exp & 1 == 1 { + acc = optry!(acc.checked_mul(&base)); + } + } + Some(acc) +} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/real.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/real.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/real.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/real.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,836 @@ +use std::ops::Neg; + +use {Num, NumCast, Float}; + +// NOTE: These doctests have the same issue as those in src/float.rs. +// They're testing the inherent methods directly, and not those of `Real`. + +/// A trait for real number types that do not necessarily have +/// floating-point-specific characteristics such as NaN and infinity. +/// +/// See [this Wikipedia article](https://en.wikipedia.org/wiki/Real_data_type) +/// for a list of data types that could meaningfully implement this trait. +/// +/// This trait is only available with the `std` feature. +pub trait Real + : Num + + Copy + + NumCast + + PartialOrd + + Neg +{ + /// Returns the smallest finite value that this type can represent. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x: f64 = Real::min_value(); + /// + /// assert_eq!(x, f64::MIN); + /// ``` + fn min_value() -> Self; + + /// Returns the smallest positive, normalized value that this type can represent. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x: f64 = Real::min_positive_value(); + /// + /// assert_eq!(x, f64::MIN_POSITIVE); + /// ``` + fn min_positive_value() -> Self; + + /// Returns epsilon, a small positive value. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x: f64 = Real::epsilon(); + /// + /// assert_eq!(x, f64::EPSILON); + /// ``` + /// + /// # Panics + /// + /// The default implementation will panic if `f32::EPSILON` cannot + /// be cast to `Self`. + fn epsilon() -> Self; + + /// Returns the largest finite value that this type can represent. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x: f64 = Real::max_value(); + /// assert_eq!(x, f64::MAX); + /// ``` + fn max_value() -> Self; + + /// Returns the largest integer less than or equal to a number. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let f = 3.99; + /// let g = 3.0; + /// + /// assert_eq!(f.floor(), 3.0); + /// assert_eq!(g.floor(), 3.0); + /// ``` + fn floor(self) -> Self; + + /// Returns the smallest integer greater than or equal to a number. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let f = 3.01; + /// let g = 4.0; + /// + /// assert_eq!(f.ceil(), 4.0); + /// assert_eq!(g.ceil(), 4.0); + /// ``` + fn ceil(self) -> Self; + + /// Returns the nearest integer to a number. Round half-way cases away from + /// `0.0`. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let f = 3.3; + /// let g = -3.3; + /// + /// assert_eq!(f.round(), 3.0); + /// assert_eq!(g.round(), -3.0); + /// ``` + fn round(self) -> Self; + + /// Return the integer part of a number. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let f = 3.3; + /// let g = -3.7; + /// + /// assert_eq!(f.trunc(), 3.0); + /// assert_eq!(g.trunc(), -3.0); + /// ``` + fn trunc(self) -> Self; + + /// Returns the fractional part of a number. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 3.5; + /// let y = -3.5; + /// let abs_difference_x = (x.fract() - 0.5).abs(); + /// let abs_difference_y = (y.fract() - (-0.5)).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// ``` + fn fract(self) -> Self; + + /// Computes the absolute value of `self`. Returns `Float::nan()` if the + /// number is `Float::nan()`. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x = 3.5; + /// let y = -3.5; + /// + /// let abs_difference_x = (x.abs() - x).abs(); + /// let abs_difference_y = (y.abs() - (-y)).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// + /// assert!(::num_traits::Float::is_nan(f64::NAN.abs())); + /// ``` + fn abs(self) -> Self; + + /// Returns a number that represents the sign of `self`. + /// + /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()` + /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()` + /// - `Float::nan()` if the number is `Float::nan()` + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let f = 3.5; + /// + /// assert_eq!(f.signum(), 1.0); + /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0); + /// + /// assert!(f64::NAN.signum().is_nan()); + /// ``` + fn signum(self) -> Self; + + /// Returns `true` if `self` is positive, including `+0.0`, + /// `Float::infinity()`, and with newer versions of Rust `f64::NAN`. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let neg_nan: f64 = -f64::NAN; + /// + /// let f = 7.0; + /// let g = -7.0; + /// + /// assert!(f.is_sign_positive()); + /// assert!(!g.is_sign_positive()); + /// assert!(!neg_nan.is_sign_positive()); + /// ``` + fn is_sign_positive(self) -> bool; + + /// Returns `true` if `self` is negative, including `-0.0`, + /// `Float::neg_infinity()`, and with newer versions of Rust `-f64::NAN`. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let nan: f64 = f64::NAN; + /// + /// let f = 7.0; + /// let g = -7.0; + /// + /// assert!(!f.is_sign_negative()); + /// assert!(g.is_sign_negative()); + /// assert!(!nan.is_sign_negative()); + /// ``` + fn is_sign_negative(self) -> bool; + + /// Fused multiply-add. Computes `(self * a) + b` with only one rounding + /// error. This produces a more accurate result with better performance than + /// a separate multiplication operation followed by an add. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let m = 10.0; + /// let x = 4.0; + /// let b = 60.0; + /// + /// // 100.0 + /// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn mul_add(self, a: Self, b: Self) -> Self; + + /// Take the reciprocal (inverse) of a number, `1/x`. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 2.0; + /// let abs_difference = (x.recip() - (1.0/x)).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn recip(self) -> Self; + + /// Raise a number to an integer power. + /// + /// Using this function is generally faster than using `powf` + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 2.0; + /// let abs_difference = (x.powi(2) - x*x).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn powi(self, n: i32) -> Self; + + /// Raise a number to a real number power. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 2.0; + /// let abs_difference = (x.powf(2.0) - x*x).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn powf(self, n: Self) -> Self; + + /// Take the square root of a number. + /// + /// Returns NaN if `self` is a negative floating-point number. + /// + /// # Panics + /// + /// If the implementing type doesn't support NaN, this method should panic if `self < 0`. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let positive = 4.0; + /// let negative = -4.0; + /// + /// let abs_difference = (positive.sqrt() - 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// assert!(::num_traits::Float::is_nan(negative.sqrt())); + /// ``` + fn sqrt(self) -> Self; + + /// Returns `e^(self)`, (the exponential function). + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let one = 1.0; + /// // e^1 + /// let e = one.exp(); + /// + /// // ln(e) - 1 == 0 + /// let abs_difference = (e.ln() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp(self) -> Self; + + /// Returns `2^(self)`. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let f = 2.0; + /// + /// // 2^2 - 4 == 0 + /// let abs_difference = (f.exp2() - 4.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp2(self) -> Self; + + /// Returns the natural logarithm of the number. + /// + /// # Panics + /// + /// If `self <= 0` and this type does not support a NaN representation, this function should panic. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let one = 1.0; + /// // e^1 + /// let e = one.exp(); + /// + /// // ln(e) - 1 == 0 + /// let abs_difference = (e.ln() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn ln(self) -> Self; + + /// Returns the logarithm of the number with respect to an arbitrary base. + /// + /// # Panics + /// + /// If `self <= 0` and this type does not support a NaN representation, this function should panic. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let ten = 10.0; + /// let two = 2.0; + /// + /// // log10(10) - 1 == 0 + /// let abs_difference_10 = (ten.log(10.0) - 1.0).abs(); + /// + /// // log2(2) - 1 == 0 + /// let abs_difference_2 = (two.log(2.0) - 1.0).abs(); + /// + /// assert!(abs_difference_10 < 1e-10); + /// assert!(abs_difference_2 < 1e-10); + /// ``` + fn log(self, base: Self) -> Self; + + /// Returns the base 2 logarithm of the number. + /// + /// # Panics + /// + /// If `self <= 0` and this type does not support a NaN representation, this function should panic. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let two = 2.0; + /// + /// // log2(2) - 1 == 0 + /// let abs_difference = (two.log2() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn log2(self) -> Self; + + /// Returns the base 10 logarithm of the number. + /// + /// # Panics + /// + /// If `self <= 0` and this type does not support a NaN representation, this function should panic. + /// + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let ten = 10.0; + /// + /// // log10(10) - 1 == 0 + /// let abs_difference = (ten.log10() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn log10(self) -> Self; + + /// Converts radians to degrees. + /// + /// ``` + /// use std::f64::consts; + /// + /// let angle = consts::PI; + /// + /// let abs_difference = (angle.to_degrees() - 180.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn to_degrees(self) -> Self; + + /// Converts degrees to radians. + /// + /// ``` + /// use std::f64::consts; + /// + /// let angle = 180.0_f64; + /// + /// let abs_difference = (angle.to_radians() - consts::PI).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn to_radians(self) -> Self; + + /// Returns the maximum of the two numbers. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 1.0; + /// let y = 2.0; + /// + /// assert_eq!(x.max(y), y); + /// ``` + fn max(self, other: Self) -> Self; + + /// Returns the minimum of the two numbers. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 1.0; + /// let y = 2.0; + /// + /// assert_eq!(x.min(y), x); + /// ``` + fn min(self, other: Self) -> Self; + + /// The positive difference of two numbers. + /// + /// * If `self <= other`: `0:0` + /// * Else: `self - other` + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 3.0; + /// let y = -3.0; + /// + /// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs(); + /// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs(); + /// + /// assert!(abs_difference_x < 1e-10); + /// assert!(abs_difference_y < 1e-10); + /// ``` + fn abs_sub(self, other: Self) -> Self; + + /// Take the cubic root of a number. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 8.0; + /// + /// // x^(1/3) - 2 == 0 + /// let abs_difference = (x.cbrt() - 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn cbrt(self) -> Self; + + /// Calculate the length of the hypotenuse of a right-angle triangle given + /// legs of length `x` and `y`. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 2.0; + /// let y = 3.0; + /// + /// // sqrt(x^2 + y^2) + /// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn hypot(self, other: Self) -> Self; + + /// Computes the sine of a number (in radians). + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x = f64::consts::PI/2.0; + /// + /// let abs_difference = (x.sin() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn sin(self) -> Self; + + /// Computes the cosine of a number (in radians). + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x = 2.0*f64::consts::PI; + /// + /// let abs_difference = (x.cos() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn cos(self) -> Self; + + /// Computes the tangent of a number (in radians). + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x = f64::consts::PI/4.0; + /// let abs_difference = (x.tan() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-14); + /// ``` + fn tan(self) -> Self; + + /// Computes the arcsine of a number. Return value is in radians in + /// the range [-pi/2, pi/2] or NaN if the number is outside the range + /// [-1, 1]. + /// + /// # Panics + /// + /// If this type does not support a NaN representation, this function should panic + /// if the number is outside the range [-1, 1]. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let f = f64::consts::PI / 2.0; + /// + /// // asin(sin(pi/2)) + /// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn asin(self) -> Self; + + /// Computes the arccosine of a number. Return value is in radians in + /// the range [0, pi] or NaN if the number is outside the range + /// [-1, 1]. + /// + /// # Panics + /// + /// If this type does not support a NaN representation, this function should panic + /// if the number is outside the range [-1, 1]. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let f = f64::consts::PI / 4.0; + /// + /// // acos(cos(pi/4)) + /// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn acos(self) -> Self; + + /// Computes the arctangent of a number. Return value is in radians in the + /// range [-pi/2, pi/2]; + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let f = 1.0; + /// + /// // atan(tan(1)) + /// let abs_difference = (f.tan().atan() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn atan(self) -> Self; + + /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`). + /// + /// * `x = 0`, `y = 0`: `0` + /// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]` + /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]` + /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)` + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let pi = f64::consts::PI; + /// // All angles from horizontal right (+x) + /// // 45 deg counter-clockwise + /// let x1 = 3.0; + /// let y1 = -3.0; + /// + /// // 135 deg clockwise + /// let x2 = -3.0; + /// let y2 = 3.0; + /// + /// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs(); + /// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs(); + /// + /// assert!(abs_difference_1 < 1e-10); + /// assert!(abs_difference_2 < 1e-10); + /// ``` + fn atan2(self, other: Self) -> Self; + + /// Simultaneously computes the sine and cosine of the number, `x`. Returns + /// `(sin(x), cos(x))`. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x = f64::consts::PI/4.0; + /// let f = x.sin_cos(); + /// + /// let abs_difference_0 = (f.0 - x.sin()).abs(); + /// let abs_difference_1 = (f.1 - x.cos()).abs(); + /// + /// assert!(abs_difference_0 < 1e-10); + /// assert!(abs_difference_0 < 1e-10); + /// ``` + fn sin_cos(self) -> (Self, Self); + + /// Returns `e^(self) - 1` in a way that is accurate even if the + /// number is close to zero. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 7.0; + /// + /// // e^(ln(7)) - 1 + /// let abs_difference = (x.ln().exp_m1() - 6.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn exp_m1(self) -> Self; + + /// Returns `ln(1+n)` (natural logarithm) more accurately than if + /// the operations were performed separately. + /// + /// # Panics + /// + /// If this type does not support a NaN representation, this function should panic + /// if `self-1 <= 0`. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let x = f64::consts::E - 1.0; + /// + /// // ln(1 + (e - 1)) == ln(e) == 1 + /// let abs_difference = (x.ln_1p() - 1.0).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn ln_1p(self) -> Self; + + /// Hyperbolic sine function. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// + /// let f = x.sinh(); + /// // Solving sinh() at 1 gives `(e^2-1)/(2e)` + /// let g = (e*e - 1.0)/(2.0*e); + /// let abs_difference = (f - g).abs(); + /// + /// assert!(abs_difference < 1e-10); + /// ``` + fn sinh(self) -> Self; + + /// Hyperbolic cosine function. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// let f = x.cosh(); + /// // Solving cosh() at 1 gives this result + /// let g = (e*e + 1.0)/(2.0*e); + /// let abs_difference = (f - g).abs(); + /// + /// // Same result + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn cosh(self) -> Self; + + /// Hyperbolic tangent function. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let x = 1.0; + /// + /// let f = x.tanh(); + /// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))` + /// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2)); + /// let abs_difference = (f - g).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn tanh(self) -> Self; + + /// Inverse hyperbolic sine function. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 1.0; + /// let f = x.sinh().asinh(); + /// + /// let abs_difference = (f - x).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn asinh(self) -> Self; + + /// Inverse hyperbolic cosine function. + /// + /// ``` + /// use num_traits::real::Real; + /// + /// let x = 1.0; + /// let f = x.cosh().acosh(); + /// + /// let abs_difference = (f - x).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn acosh(self) -> Self; + + /// Inverse hyperbolic tangent function. + /// + /// ``` + /// use num_traits::real::Real; + /// use std::f64; + /// + /// let e = f64::consts::E; + /// let f = e.tanh().atanh(); + /// + /// let abs_difference = (f - e).abs(); + /// + /// assert!(abs_difference < 1.0e-10); + /// ``` + fn atanh(self) -> Self; +} + +impl Real for T { + forward! { + Float::min_value() -> Self; + Float::min_positive_value() -> Self; + Float::epsilon() -> Self; + Float::max_value() -> Self; + } + forward! { + Float::floor(self) -> Self; + Float::ceil(self) -> Self; + Float::round(self) -> Self; + Float::trunc(self) -> Self; + Float::fract(self) -> Self; + Float::abs(self) -> Self; + Float::signum(self) -> Self; + Float::is_sign_positive(self) -> bool; + Float::is_sign_negative(self) -> bool; + Float::mul_add(self, a: Self, b: Self) -> Self; + Float::recip(self) -> Self; + Float::powi(self, n: i32) -> Self; + Float::powf(self, n: Self) -> Self; + Float::sqrt(self) -> Self; + Float::exp(self) -> Self; + Float::exp2(self) -> Self; + Float::ln(self) -> Self; + Float::log(self, base: Self) -> Self; + Float::log2(self) -> Self; + Float::log10(self) -> Self; + Float::to_degrees(self) -> Self; + Float::to_radians(self) -> Self; + Float::max(self, other: Self) -> Self; + Float::min(self, other: Self) -> Self; + Float::abs_sub(self, other: Self) -> Self; + Float::cbrt(self) -> Self; + Float::hypot(self, other: Self) -> Self; + Float::sin(self) -> Self; + Float::cos(self) -> Self; + Float::tan(self) -> Self; + Float::asin(self) -> Self; + Float::acos(self) -> Self; + Float::atan(self) -> Self; + Float::atan2(self, other: Self) -> Self; + Float::sin_cos(self) -> (Self, Self); + Float::exp_m1(self) -> Self; + Float::ln_1p(self) -> Self; + Float::sinh(self) -> Self; + Float::cosh(self) -> Self; + Float::tanh(self) -> Self; + Float::asinh(self) -> Self; + Float::acosh(self) -> Self; + Float::atanh(self) -> Self; + } +} diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/src/sign.rs cargo-0.26.0/vendor/num-traits-0.2.2/src/sign.rs --- cargo-0.25.0/vendor/num-traits-0.2.2/src/sign.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/src/sign.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,203 @@ +use core::ops::Neg; +use core::num::Wrapping; + +use Num; +use float::FloatCore; + +/// Useful functions for signed numbers (i.e. numbers that can be negative). +pub trait Signed: Sized + Num + Neg { + /// Computes the absolute value. + /// + /// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`. + /// + /// For signed integers, `::MIN` will be returned if the number is `::MIN`. + fn abs(&self) -> Self; + + /// The positive difference of two numbers. + /// + /// Returns `zero` if the number is less than or equal to `other`, otherwise the difference + /// between `self` and `other` is returned. + fn abs_sub(&self, other: &Self) -> Self; + + /// Returns the sign of the number. + /// + /// For `f32` and `f64`: + /// + /// * `1.0` if the number is positive, `+0.0` or `INFINITY` + /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` + /// * `NaN` if the number is `NaN` + /// + /// For signed integers: + /// + /// * `0` if the number is zero + /// * `1` if the number is positive + /// * `-1` if the number is negative + fn signum(&self) -> Self; + + /// Returns true if the number is positive and false if the number is zero or negative. + fn is_positive(&self) -> bool; + + /// Returns true if the number is negative and false if the number is zero or positive. + fn is_negative(&self) -> bool; +} + +macro_rules! signed_impl { + ($($t:ty)*) => ($( + impl Signed for $t { + #[inline] + fn abs(&self) -> $t { + if self.is_negative() { -*self } else { *self } + } + + #[inline] + fn abs_sub(&self, other: &$t) -> $t { + if *self <= *other { 0 } else { *self - *other } + } + + #[inline] + fn signum(&self) -> $t { + match *self { + n if n > 0 => 1, + 0 => 0, + _ => -1, + } + } + + #[inline] + fn is_positive(&self) -> bool { *self > 0 } + + #[inline] + fn is_negative(&self) -> bool { *self < 0 } + } + )*) +} + +signed_impl!(isize i8 i16 i32 i64); + +impl Signed for Wrapping where Wrapping: Num + Neg> +{ + #[inline] + fn abs(&self) -> Self { + Wrapping(self.0.abs()) + } + + #[inline] + fn abs_sub(&self, other: &Self) -> Self { + Wrapping(self.0.abs_sub(&other.0)) + } + + #[inline] + fn signum(&self) -> Self { + Wrapping(self.0.signum()) + } + + #[inline] + fn is_positive(&self) -> bool { self.0.is_positive() } + + #[inline] + fn is_negative(&self) -> bool { self.0.is_negative() } +} + +macro_rules! signed_float_impl { + ($t:ty) => { + impl Signed for $t { + /// Computes the absolute value. Returns `NAN` if the number is `NAN`. + #[inline] + fn abs(&self) -> $t { + FloatCore::abs(*self) + } + + /// The positive difference of two numbers. Returns `0.0` if the number is + /// less than or equal to `other`, otherwise the difference between`self` + /// and `other` is returned. + #[inline] + fn abs_sub(&self, other: &$t) -> $t { + if *self <= *other { 0. } else { *self - *other } + } + + /// # Returns + /// + /// - `1.0` if the number is positive, `+0.0` or `INFINITY` + /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` + /// - `NAN` if the number is NaN + #[inline] + fn signum(&self) -> $t { + FloatCore::signum(*self) + } + + /// Returns `true` if the number is positive, including `+0.0` and `INFINITY` + #[inline] + fn is_positive(&self) -> bool { FloatCore::is_sign_positive(*self) } + + /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY` + #[inline] + fn is_negative(&self) -> bool { FloatCore::is_sign_negative(*self) } + } + } +} + +signed_float_impl!(f32); +signed_float_impl!(f64); + +/// Computes the absolute value. +/// +/// For `f32` and `f64`, `NaN` will be returned if the number is `NaN` +/// +/// For signed integers, `::MIN` will be returned if the number is `::MIN`. +#[inline(always)] +pub fn abs(value: T) -> T { + value.abs() +} + +/// The positive difference of two numbers. +/// +/// Returns zero if `x` is less than or equal to `y`, otherwise the difference +/// between `x` and `y` is returned. +#[inline(always)] +pub fn abs_sub(x: T, y: T) -> T { + x.abs_sub(&y) +} + +/// Returns the sign of the number. +/// +/// For `f32` and `f64`: +/// +/// * `1.0` if the number is positive, `+0.0` or `INFINITY` +/// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` +/// * `NaN` if the number is `NaN` +/// +/// For signed integers: +/// +/// * `0` if the number is zero +/// * `1` if the number is positive +/// * `-1` if the number is negative +#[inline(always)] pub fn signum(value: T) -> T { value.signum() } + +/// A trait for values which cannot be negative +pub trait Unsigned: Num {} + +macro_rules! empty_trait_impl { + ($name:ident for $($t:ty)*) => ($( + impl $name for $t {} + )*) +} + +empty_trait_impl!(Unsigned for usize u8 u16 u32 u64); + +impl Unsigned for Wrapping where Wrapping: Num {} + +#[test] +fn unsigned_wrapping_is_unsigned() { + fn require_unsigned(_: &T) {} + require_unsigned(&Wrapping(42_u32)); +} +/* +// Commenting this out since it doesn't compile on Rust 1.8, +// because on this version Wrapping doesn't implement Neg and therefore can't +// implement Signed. +#[test] +fn signed_wrapping_is_signed() { + fn require_signed(_: &T) {} + require_signed(&Wrapping(-42)); +} +*/ diff -Nru cargo-0.25.0/vendor/num-traits-0.2.2/.travis.yml cargo-0.26.0/vendor/num-traits-0.2.2/.travis.yml --- cargo-0.25.0/vendor/num-traits-0.2.2/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/num-traits-0.2.2/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,19 @@ +language: rust +rust: + - 1.8.0 + - stable + - beta + - nightly +sudo: false +script: + - cargo build --verbose + - ./ci/test_full.sh +notifications: + email: + on_success: never +branches: + only: + - master + - next + - staging + - trying diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/build.rs cargo-0.26.0/vendor/openssl-0.10.6/build.rs --- cargo-0.25.0/vendor/openssl-0.10.6/build.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/build.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,36 @@ +use std::env; + +fn main() { + match env::var("DEP_OPENSSL_VERSION") { + Ok(ref v) if v == "101" => { + println!("cargo:rustc-cfg=ossl101"); + println!("cargo:rustc-cfg=ossl10x"); + } + Ok(ref v) if v == "102" => { + println!("cargo:rustc-cfg=ossl102"); + println!("cargo:rustc-cfg=ossl10x"); + } + Ok(ref v) if v == "110" => { + println!("cargo:rustc-cfg=ossl110"); + } + Ok(ref v) if v == "111" => { + println!("cargo:rustc-cfg=ossl110"); + println!("cargo:rustc-cfg=ossl111"); + } + _ => panic!("Unable to detect OpenSSL version"), + } + + if let Ok(_) = env::var("DEP_OPENSSL_LIBRESSL") { + println!("cargo:rustc-cfg=libressl"); + } + + if let Ok(v) = env::var("DEP_OPENSSL_LIBRESSL_VERSION") { + println!("cargo:rustc-cfg=libressl{}", v); + } + + if let Ok(vars) = env::var("DEP_OPENSSL_CONF") { + for var in vars.split(",") { + println!("cargo:rustc-cfg=osslconf=\"{}\"", var); + } + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/.cargo-checksum.json cargo-0.26.0/vendor/openssl-0.10.6/.cargo-checksum.json --- cargo-0.25.0/vendor/openssl-0.10.6/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"63246f69962e8d5ef865f82a65241d6483c8a2905a1801e2f7feb5d187d51320"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/Cargo.toml cargo-0.26.0/vendor/openssl-0.10.6/Cargo.toml --- cargo-0.25.0/vendor/openssl-0.10.6/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,50 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "openssl" +version = "0.10.6" +authors = ["Steven Fackler "] +description = "OpenSSL bindings" +readme = "README.md" +keywords = ["crypto", "tls", "ssl", "dtls"] +categories = ["cryptography", "api-bindings"] +license = "Apache-2.0" +repository = "https://github.com/sfackler/rust-openssl" +[dependencies.bitflags] +version = "1.0" + +[dependencies.foreign-types] +version = "0.3.1" + +[dependencies.lazy_static] +version = "1" + +[dependencies.libc] +version = "0.2" + +[dependencies.openssl-sys] +version = "0.9.28" +[dev-dependencies.data-encoding] +version = "2.0" + +[dev-dependencies.hex] +version = "0.3" + +[dev-dependencies.tempdir] +version = "0.3" + +[features] +v101 = [] +v102 = [] +v110 = [] +v111 = [] diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/examples/mk_certs.rs cargo-0.26.0/vendor/openssl-0.10.6/examples/mk_certs.rs --- cargo-0.25.0/vendor/openssl-0.10.6/examples/mk_certs.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/examples/mk_certs.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,154 @@ +//! A program that generates ca certs, certs verified by the ca, and public +//! and private keys. + +extern crate openssl; + +use openssl::asn1::Asn1Time; +use openssl::bn::{BigNum, MsbOption}; +use openssl::error::ErrorStack; +use openssl::hash::MessageDigest; +use openssl::pkey::{PKey, PKeyRef, Private}; +use openssl::rsa::Rsa; +use openssl::x509::{X509, X509NameBuilder, X509Ref, X509Req, X509ReqBuilder, X509VerifyResult}; +use openssl::x509::extension::{AuthorityKeyIdentifier, BasicConstraints, KeyUsage, + SubjectAlternativeName, SubjectKeyIdentifier}; + +/// Make a CA certificate and private key +fn mk_ca_cert() -> Result<(X509, PKey), ErrorStack> { + let rsa = Rsa::generate(2048)?; + let privkey = PKey::from_rsa(rsa)?; + + let mut x509_name = X509NameBuilder::new()?; + x509_name.append_entry_by_text("C", "US")?; + x509_name.append_entry_by_text("ST", "TX")?; + x509_name.append_entry_by_text("O", "Some CA organization")?; + x509_name.append_entry_by_text("CN", "ca test")?; + let x509_name = x509_name.build(); + + let mut cert_builder = X509::builder()?; + cert_builder.set_version(2)?; + let serial_number = { + let mut serial = BigNum::new()?; + serial.rand(159, MsbOption::MAYBE_ZERO, false)?; + serial.to_asn1_integer()? + }; + cert_builder.set_serial_number(&serial_number)?; + cert_builder.set_subject_name(&x509_name)?; + cert_builder.set_issuer_name(&x509_name)?; + cert_builder.set_pubkey(&privkey)?; + let not_before = Asn1Time::days_from_now(0)?; + cert_builder.set_not_before(¬_before)?; + let not_after = Asn1Time::days_from_now(365)?; + cert_builder.set_not_after(¬_after)?; + + cert_builder.append_extension(BasicConstraints::new().critical().ca().build()?)?; + cert_builder.append_extension(KeyUsage::new() + .critical() + .key_cert_sign() + .crl_sign() + .build()?)?; + + let subject_key_identifier = + SubjectKeyIdentifier::new().build(&cert_builder.x509v3_context(None, None))?; + cert_builder.append_extension(subject_key_identifier)?; + + cert_builder.sign(&privkey, MessageDigest::sha256())?; + let cert = cert_builder.build(); + + Ok((cert, privkey)) +} + +/// Make a X509 request with the given private key +fn mk_request(privkey: &PKey) -> Result { + let mut req_builder = X509ReqBuilder::new()?; + req_builder.set_pubkey(&privkey)?; + + let mut x509_name = X509NameBuilder::new()?; + x509_name.append_entry_by_text("C", "US")?; + x509_name.append_entry_by_text("ST", "TX")?; + x509_name.append_entry_by_text("O", "Some organization")?; + x509_name.append_entry_by_text("CN", "www.example.com")?; + let x509_name = x509_name.build(); + req_builder.set_subject_name(&x509_name)?; + + req_builder.sign(&privkey, MessageDigest::sha256())?; + let req = req_builder.build(); + Ok(req) +} + +/// Make a certificate and private key signed by the given CA cert and private key +fn mk_ca_signed_cert( + ca_cert: &X509Ref, + ca_privkey: &PKeyRef, +) -> Result<(X509, PKey), ErrorStack> { + let rsa = Rsa::generate(2048)?; + let privkey = PKey::from_rsa(rsa)?; + + let req = mk_request(&privkey)?; + + let mut cert_builder = X509::builder()?; + cert_builder.set_version(2)?; + let serial_number = { + let mut serial = BigNum::new()?; + serial.rand(159, MsbOption::MAYBE_ZERO, false)?; + serial.to_asn1_integer()? + }; + cert_builder.set_serial_number(&serial_number)?; + cert_builder.set_subject_name(req.subject_name())?; + cert_builder.set_issuer_name(ca_cert.subject_name())?; + cert_builder.set_pubkey(&privkey)?; + let not_before = Asn1Time::days_from_now(0)?; + cert_builder.set_not_before(¬_before)?; + let not_after = Asn1Time::days_from_now(365)?; + cert_builder.set_not_after(¬_after)?; + + cert_builder.append_extension(BasicConstraints::new().build()?)?; + + cert_builder.append_extension(KeyUsage::new() + .critical() + .non_repudiation() + .digital_signature() + .key_encipherment() + .build()?)?; + + let subject_key_identifier = + SubjectKeyIdentifier::new().build(&cert_builder.x509v3_context(Some(ca_cert), None))?; + cert_builder.append_extension(subject_key_identifier)?; + + let auth_key_identifier = AuthorityKeyIdentifier::new() + .keyid(false) + .issuer(false) + .build(&cert_builder.x509v3_context(Some(ca_cert), None))?; + cert_builder.append_extension(auth_key_identifier)?; + + let subject_alt_name = SubjectAlternativeName::new() + .dns("*.example.com") + .dns("hello.com") + .build(&cert_builder.x509v3_context(Some(ca_cert), None))?; + cert_builder.append_extension(subject_alt_name)?; + + cert_builder.sign(&ca_privkey, MessageDigest::sha256())?; + let cert = cert_builder.build(); + + Ok((cert, privkey)) +} + +fn real_main() -> Result<(), ErrorStack> { + let (ca_cert, ca_privkey) = mk_ca_cert()?; + let (cert, _privkey) = mk_ca_signed_cert(&ca_cert, &ca_privkey)?; + + // Verify that this cert was issued by this ca + match ca_cert.issued(&cert) { + X509VerifyResult::OK => println!("Certificate verified!"), + ver_err => println!("Failed to verify certificate: {}", ver_err), + }; + + Ok(()) +} + +fn main() { + match real_main() { + Ok(()) => println!("Finished."), + Err(e) => println!("Error: {}", e), + }; +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/LICENSE cargo-0.26.0/vendor/openssl-0.10.6/LICENSE --- cargo-0.25.0/vendor/openssl-0.10.6/LICENSE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/LICENSE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,15 @@ +Copyright 2011-2017 Google Inc. + 2013 Jack Lloyd + 2013-2014 Steven Fackler + +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. diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/README.md cargo-0.26.0/vendor/openssl-0.10.6/README.md --- cargo-0.25.0/vendor/openssl-0.10.6/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,180 @@ +# rust-openssl + +[![CircleCI](https://circleci.com/gh/sfackler/rust-openssl.svg?style=shield)](https://circleci.com/gh/sfackler/rust-openssl) [![Build status](https://ci.appveyor.com/api/projects/status/d1knobws948pyynk/branch/master?svg=true)](https://ci.appveyor.com/project/sfackler/rust-openssl/branch/master) [![crates.io](https://img.shields.io/crates/v/openssl.svg)](https://crates.io/crates/openssl) + +[Documentation](https://docs.rs/openssl). + +## Warning + +This README does not correspond to rust-openssl 0.7.x or 0.8.x. See +[here](https://github.com/sfackler/rust-openssl/blob/b8fb29db5c246175a096260eacca38180cd77dd0/README.md) +for that README. + +## Building + +rust-openssl depends on OpenSSL version 1.0.1 or above, or LibreSSL. Both the +libraries and headers need to be present in the build environment before this +crate is compiled, and some instructions of how to do this are in the sections +below. + +### Linux + +On Linux, you can typically install OpenSSL via your package manager. The +headers are sometimes provided in a separate package than the runtime libraries +- look for something like `openssl-devel` or `libssl-dev`. You will also need the +regular development utilities, like `pkg-config`, as the custom build script relies +on them. + +```bash +# On Debian and Ubuntu +sudo apt-get install pkg-config libssl-dev +# On Arch Linux +sudo pacman -S openssl +# On Fedora +sudo dnf install openssl-devel +``` + +If installation via a package manager is not possible, or if you're cross +compiling to a separate target, you'll typically need to compile OpenSSL from +source. That can normally be done with: + +``` +curl -O https://www.openssl.org/source/openssl-1.1.0g.tar.gz +tar xf openssl-1.1.0g.tar.gz +cd openssl-1.1.0g +export CC=... +./Configure --prefix=... linux-x86_64 -fPIC +make -j$(nproc) +make install +``` + +### OSX + +Although OpenSSL 0.9.8 is preinstalled on OSX this library is being phased out +of OSX and this crate also does not support that version of OpenSSL. To use this +crate on OSX you'll need to install OpenSSL via some alternate means, typically +Homebrew: + +```bash +brew install openssl +``` + +Occasionally an update of XCode or MacOS will cause the linker to fail after compilation, to rectify this you may want to try and run: + +```bash +xcode-select --install +``` + +If Homebrew is installed to the default location of `/usr/local`, OpenSSL will be +automatically detected. + +### Windows MSVC + +On MSVC it's unfortunately not always a trivial process acquiring OpenSSL. A couple of possibilities +are downloading precompiled binaries for OpenSSL 1.1.0, or installing OpenSSL 1.0.2 using vcpkg. + +#### Installing OpenSSL 1.1.0 using precompiled binaries + +Perhaps the easiest way to do this right now is to download [precompiled +binaries] and install them on your system. Currently it's recommended to +install the 1.1.0 (non-light) installation if you're choosing this route. + +[precompiled binaries]: http://slproweb.com/products/Win32OpenSSL.html + +Once a precompiled binary is installed you can configure this crate to find the +installation via an environment variable: + +``` +set OPENSSL_DIR=C:\OpenSSL-Win64 +``` + +During the installation process if you select "Copy OpenSSL DLLs to: The OpenSSL binaries (/bin) +directory", you will need to add them to the `PATH` environment variable: + +``` +set PATH=%PATH%;C:\OpenSSL-Win64\bin +``` + +Now you will need to [install root certificates.](#acquiring-root-certificates) + +#### Installing OpenSSL 1.0.2 using vcpkg + +Install [vcpkg](https://github.com/Microsoft/vcpkg), and install the OpenSSL port like this: + +```Batchfile +vcpkg install openssl:x64-windows +set VCPKG_ROOT=c:\path\to\vcpkg\installation +cargo build +``` + +For more information see the vcpkg build helper [documentation](http://docs.rs/vcpkg). +To finish setting up OpenSSL you will need to [install root certificates.](#acquiring-root-certificates) + +#### Acquiring Root Certificates + +Neither of the above OpenSSL distributions ship with any root certificates. +So to make requests to servers on the internet, you have to install them +manually. Download the [cacert.pem file from here], copy it somewhere safe +(`C:\OpenSSL-Win64\certs` is a good place) and point the `SSL_CERT_FILE` +environment variable there: + +``` +set SSL_CERT_FILE=C:\OpenSSL-Win64\certs\cacert.pem +``` + +[cacert.pem file from here]: https://curl.haxx.se/docs/caextract.html + +After that, you're just a `cargo build` away! + +### Windows GNU (MinGW) + +The easiest way to acquire OpenSSL when working with MinGW is to ensure you're +using [MSYS2](http://msys2.github.io) and to then execute: + +``` +# 32-bit +pacman -S mingw-w64-i686-openssl + +# 64-bit +pacman -S mingw-w64-x86_64-openssl +``` + +And after that, a `cargo build` should be all you need! + +### Manual configuration + +rust-openssl's build script will by default attempt to locate OpenSSL via +pkg-config or other system-specific mechanisms. This will not work in some +situations however, for example cross compiling or when using a copy of OpenSSL +other than the normal system install. + +The build script can be configured via environment variables: + +* `OPENSSL_DIR` - If specified, a directory that will be used to find + OpenSSL installation. It's expected that under this directory the `include` + folder has header files and a `lib` folder has the runtime libraries. +* `OPENSSL_LIB_DIR` - If specified, a directory that will be used to find + OpenSSL libraries. Overrides the `lib` folder implied by `OPENSSL_DIR` + (if specified). +* `OPENSSL_INCLUDE_DIR` - If specified, a directory that will be used to find + OpenSSL header files. Overrides the `include` folder implied by `OPENSSL_DIR` + (if specified). +* `OPENSSL_STATIC` - If specified, OpenSSL libraries will be statically rather + than dynamically linked. +* `OPENSSL_LIBS` - If specified, the names of the OpenSSL libraries that will be + linked, e.g. `ssl:crypto`. + +If `OPENSSL_DIR` or `OPENSSL_LIB_DIR` and `OPENSSL_INCLUDE_DIR` is specified, +then the build script will skip the pkg-config step. + +For target-specific configuration, each of these environment variables can be +prefixed by an upper-cased target, for example, +`X86_64_UNKNOWN_LINUX_GNU_OPENSSL_DIR`. This can be useful in cross compilation +contexts. + +### 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 under the terms of both the Apache License, +Version 2.0 and the MIT license without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/aes.rs cargo-0.26.0/vendor/openssl-0.10.6/src/aes.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/aes.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/aes.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,180 @@ +//! Low level AES IGE functionality +//! +//! AES ECB, CBC, XTS, CTR, CFB, GCM and other conventional symmetric encryption +//! modes are found in [`symm`]. This is the implementation of AES IGE. +//! +//! Advanced Encryption Standard (AES) provides symmetric key cipher that +//! the same key is used to encrypt and decrypt data. This implementation +//! uses 128, 192, or 256 bit keys. This module provides functions to +//! create a new key with [`new_encrypt`] and perform an encryption/decryption +//! using that key with [`aes_ige`]. +//! +//! [`new_encrypt`]: struct.AesKey.html#method.new_encrypt +//! [`aes_ige`]: fn.aes_ige.html +//! +//! The [`symm`] module should be used in preference to this module in most cases. +//! The IGE block cypher is a non-traditional cipher mode. More traditional AES +//! encryption methods are found in the [`Crypter`] and [`Cipher`] structs. +//! +//! [`symm`]: ../symm/index.html +//! [`Crypter`]: ../symm/struct.Crypter.html +//! [`Cipher`]: ../symm/struct.Cipher.html +//! +//! # Examples +//! +//! ```rust +//! # extern crate openssl; +//! extern crate hex; +//! use openssl::aes::{AesKey, KeyError, aes_ige}; +//! use openssl::symm::Mode; +//! use hex::FromHex; +//! +//! fn decrypt() -> Result<(), KeyError> { +//! let raw_key = "000102030405060708090A0B0C0D0E0F"; +//! let hex_cipher = "12345678901234561234567890123456"; +//! let randomness = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"; +//! if let (Ok(key_as_u8), Ok(cipher_as_u8), Ok(mut iv_as_u8)) = +//! (Vec::from_hex(raw_key), Vec::from_hex(hex_cipher), Vec::from_hex(randomness)) { +//! let key = AesKey::new_encrypt(&key_as_u8)?; +//! let mut output = vec![0u8; cipher_as_u8.len()]; +//! aes_ige(&cipher_as_u8, &mut output, &key, &mut iv_as_u8, Mode::Encrypt); +//! assert_eq!(hex::encode(output), "a6ad974d5cea1d36d2f367980907ed32"); +//! } +//! Ok(()) +//! } +//! +//! # fn main() { +//! # decrypt(); +//! # } +use ffi; +use std::mem; +use libc::c_int; + +use symm::Mode; + +/// Provides Error handling for parsing keys. +#[derive(Debug)] +pub struct KeyError(()); + +/// The key used to encrypt or decrypt cipher blocks. +pub struct AesKey(ffi::AES_KEY); + +impl AesKey { + /// Prepares a key for encryption. + /// + /// # Failure + /// + /// Returns an error if the key is not 128, 192, or 256 bits. + pub fn new_encrypt(key: &[u8]) -> Result { + unsafe { + assert!(key.len() <= c_int::max_value() as usize / 8); + + let mut aes_key = mem::uninitialized(); + let r = ffi::AES_set_encrypt_key( + key.as_ptr() as *const _, + key.len() as c_int * 8, + &mut aes_key, + ); + if r == 0 { + Ok(AesKey(aes_key)) + } else { + Err(KeyError(())) + } + } + } + + /// Prepares a key for decryption. + /// + /// # Failure + /// + /// Returns an error if the key is not 128, 192, or 256 bits. + pub fn new_decrypt(key: &[u8]) -> Result { + unsafe { + assert!(key.len() <= c_int::max_value() as usize / 8); + + let mut aes_key = mem::uninitialized(); + let r = ffi::AES_set_decrypt_key( + key.as_ptr() as *const _, + key.len() as c_int * 8, + &mut aes_key, + ); + + if r == 0 { + Ok(AesKey(aes_key)) + } else { + Err(KeyError(())) + } + } + } +} + +/// Performs AES IGE encryption or decryption +/// +/// AES IGE (Infinite Garble Extension) is a form of AES block cipher utilized in +/// OpenSSL. Infinite Garble referes to propogating forward errors. IGE, like other +/// block ciphers implemented for AES requires an initalization vector. The IGE mode +/// allows a stream of blocks to be encrypted or decrypted without having the entire +/// plaintext available. For more information, visit [AES IGE Encryption]. +/// +/// This block cipher uses 16 byte blocks. The rust implmentation will panic +/// if the input or output does not meet this 16-byte boundry. Attention must +/// be made in this low level implementation to pad the value to the 128-bit boundry. +/// +/// [AES IGE Encryption]: http://www.links.org/files/openssl-ige.pdf +/// +/// # Panics +/// +/// Panics if `in_` is not the same length as `out`, if that length is not a multiple of 16, or if +/// `iv` is not at least 32 bytes. +pub fn aes_ige(in_: &[u8], out: &mut [u8], key: &AesKey, iv: &mut [u8], mode: Mode) { + unsafe { + assert!(in_.len() == out.len()); + assert!(in_.len() % ffi::AES_BLOCK_SIZE as usize == 0); + assert!(iv.len() >= ffi::AES_BLOCK_SIZE as usize * 2); + + let mode = match mode { + Mode::Encrypt => ffi::AES_ENCRYPT, + Mode::Decrypt => ffi::AES_DECRYPT, + }; + ffi::AES_ige_encrypt( + in_.as_ptr() as *const _, + out.as_mut_ptr() as *mut _, + in_.len(), + &key.0, + iv.as_mut_ptr() as *mut _, + mode, + ); + } +} + +#[cfg(test)] +mod test { + use hex::FromHex; + + use symm::Mode; + use super::*; + + // From https://www.mgp25.com/AESIGE/ + #[test] + fn ige_vector_1() { + let raw_key = "000102030405060708090A0B0C0D0E0F"; + let raw_iv = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"; + let raw_pt = "0000000000000000000000000000000000000000000000000000000000000000"; + let raw_ct = "1A8519A6557BE652E9DA8E43DA4EF4453CF456B4CA488AA383C79C98B34797CB"; + + let key = AesKey::new_encrypt(&Vec::from_hex(raw_key).unwrap()).unwrap(); + let mut iv = Vec::from_hex(raw_iv).unwrap(); + let pt = Vec::from_hex(raw_pt).unwrap(); + let ct = Vec::from_hex(raw_ct).unwrap(); + + let mut ct_actual = vec![0; ct.len()]; + aes_ige(&pt, &mut ct_actual, &key, &mut iv, Mode::Encrypt); + assert_eq!(ct_actual, ct); + + let key = AesKey::new_decrypt(&Vec::from_hex(raw_key).unwrap()).unwrap(); + let mut iv = Vec::from_hex(raw_iv).unwrap(); + let mut pt_actual = vec![0; pt.len()]; + aes_ige(&ct, &mut pt_actual, &key, &mut iv, Mode::Decrypt); + assert_eq!(pt_actual, pt); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/asn1.rs cargo-0.26.0/vendor/openssl-0.10.6/src/asn1.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/asn1.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/asn1.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,306 @@ +#![deny(missing_docs)] + +//! Defines the format of certificiates +//! +//! This module is used by [`x509`] and other certificate building functions +//! to describe time, strings, and objects. +//! +//! Abstract Syntax Notation One is an interface description language. +//! The specification comes from [X.208] by OSI, and rewritten in X.680. +//! ASN.1 describes properties of an object with a type set. Those types +//! can be atomic, structured, choice, and other (CHOICE and ANY). These +//! types are expressed as a number and the assignment operator ::= gives +//! the type a name. +//! +//! The implementation here provides a subset of the ASN.1 types that OpenSSL +//! uses, especially in the properties of a certificate used in HTTPS. +//! +//! [X.208]: https://www.itu.int/rec/T-REC-X.208-198811-W/en +//! [`x509`]: ../x509/struct.X509Builder.html +//! +//! ## Examples +//! +//! ``` +//! use openssl::asn1::Asn1Time; +//! let tomorrow = Asn1Time::days_from_now(1); +//! ``` +use ffi; +use foreign_types::{ForeignType, ForeignTypeRef}; +use libc::{c_char, c_int, c_long}; +use std::fmt; +use std::ptr; +use std::slice; +use std::str; + +use {cvt, cvt_p}; +use bio::MemBio; +use bn::BigNum; +use error::ErrorStack; +use nid::Nid; +use string::OpensslString; + +foreign_type_and_impl_send_sync! { + type CType = ffi::ASN1_GENERALIZEDTIME; + fn drop = ffi::ASN1_GENERALIZEDTIME_free; + + /// Non-UTC representation of time + /// + /// If a time can be represented by UTCTime, UTCTime is used + /// otherwise, ASN1_GENERALIZEDTIME is used. This would be, for + /// example outside the year range of 1950-2049. + /// + /// [ASN1_GENERALIZEDTIME_set] documentation from OpenSSL provides + /// further details of implmentation. Note: these docs are from the master + /// branch as documentation on the 1.1.0 branch did not include this page. + /// + /// [ASN1_GENERALIZEDTIME_set]: https://www.openssl.org/docs/manmaster/man3/ASN1_GENERALIZEDTIME_set.html + pub struct Asn1GeneralizedTime; + /// Reference to a [`Asn1GeneralizedTime`] + /// + /// [`Asn1GeneralizedTime`]: struct.Asn1GeneralizedTime.html + pub struct Asn1GeneralizedTimeRef; +} + +impl fmt::Display for Asn1GeneralizedTimeRef { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + unsafe { + let mem_bio = MemBio::new()?; + cvt(ffi::ASN1_GENERALIZEDTIME_print( + mem_bio.as_ptr(), + self.as_ptr(), + ))?; + write!(f, "{}", str::from_utf8_unchecked(mem_bio.get_buf())) + } + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::ASN1_TIME; + fn drop = ffi::ASN1_TIME_free; + /// Time storage and comparison + /// + /// Asn1Time should be used to store and share time information + /// using certificates. If Asn1Time is set using a string, it must + /// be in either YYMMDDHHMMSSZ, YYYYMMDDHHMMSSZ, or another ASN.1 format. + /// + /// [ASN_TIME_set] documentation at OpenSSL explains the ASN.1 implementaiton + /// used by OpenSSL. + /// + /// [ASN_TIME_set]: https://www.openssl.org/docs/man1.1.0/crypto/ASN1_TIME_set.html + pub struct Asn1Time; + /// Reference to an [`Asn1Time`] + /// + /// [`Asn1Time`]: struct.Asn1Time.html + pub struct Asn1TimeRef; +} + +impl fmt::Display for Asn1TimeRef { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + unsafe { + let mem_bio = MemBio::new()?; + cvt(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.as_ptr()))?; + write!(f, "{}", str::from_utf8_unchecked(mem_bio.get_buf())) + } + } +} + +impl Asn1Time { + fn from_period(period: c_long) -> Result { + ffi::init(); + + unsafe { + let handle = cvt_p(ffi::X509_gmtime_adj(ptr::null_mut(), period))?; + Ok(Asn1Time::from_ptr(handle)) + } + } + + /// Creates a new time on specified interval in days from now + pub fn days_from_now(days: u32) -> Result { + Asn1Time::from_period(days as c_long * 60 * 60 * 24) + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::ASN1_STRING; + fn drop = ffi::ASN1_STRING_free; + /// Primary ASN.1 type used by OpenSSL + /// + /// Almost all ASN.1 types in OpenSSL are represented by ASN1_STRING + /// structures. This implementation uses [ASN1_STRING-to_UTF8] to preserve + /// compatibility with Rust's String. + /// + /// [ASN1_STRING-to_UTF8]: https://www.openssl.org/docs/man1.1.0/crypto/ASN1_STRING_to_UTF8.html + pub struct Asn1String; + /// Reference to [`Asn1String`] + /// + /// [`Asn1String`]: struct.Asn1String.html + pub struct Asn1StringRef; +} + +impl Asn1StringRef { + /// Converts the ASN.1 underlying format to UTF8 + /// + /// ASN.1 strings may utilize UTF-16, ASCII, BMP, or UTF8. This is important to + /// consume the string in a meaningful way without knowing the underlying + /// format. + pub fn as_utf8(&self) -> Result { + unsafe { + let mut ptr = ptr::null_mut(); + let len = ffi::ASN1_STRING_to_UTF8(&mut ptr, self.as_ptr()); + if len < 0 { + return Err(ErrorStack::get()); + } + + Ok(OpensslString::from_ptr(ptr as *mut c_char)) + } + } + + /// Return the string as an array of bytes + /// + /// The bytes do not directly corespond to UTF-8 encoding. To interact with + /// strings in rust, it is preferable to use [`as_utf8`] + /// + /// [`as_utf8`]: struct.Asn1String.html#method.as_utf8 + pub fn as_slice(&self) -> &[u8] { + unsafe { slice::from_raw_parts(ASN1_STRING_data(self.as_ptr()), self.len()) } + } + + /// Return the length of the Asn1String (number of bytes) + pub fn len(&self) -> usize { + unsafe { ffi::ASN1_STRING_length(self.as_ptr()) as usize } + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::ASN1_INTEGER; + fn drop = ffi::ASN1_INTEGER_free; + + /// Numeric representation + /// + /// Integers in ASN.1 may include BigNum, int64 or uint64. BigNum implementation + /// can be found within [`bn`] module. + /// + /// OpenSSL documentation includes [`ASN1_INTEGER_set`]. + /// + /// [`bn`]: ../bn/index.html + /// [`ASN1_INTEGER_set`]: https://www.openssl.org/docs/man1.1.0/crypto/ASN1_INTEGER_set.html + pub struct Asn1Integer; + /// Reference to [`Asn1Integer`] + /// + /// [`Asn1Integer`]: struct.Asn1Integer.html + pub struct Asn1IntegerRef; +} + +impl Asn1IntegerRef { + #[allow(missing_docs)] + #[deprecated(since = "0.10.6", note = "use to_bn instead")] + pub fn get(&self) -> i64 { + unsafe { ::ffi::ASN1_INTEGER_get(self.as_ptr()) as i64 } + } + + /// Converts the integer to a `BigNum`. + /// + /// This corresponds to [`ASN1_INTEGER_to_BN`]. + /// + /// [`ASN1_INTEGER_to_BN`]: https://www.openssl.org/docs/man1.1.0/crypto/ASN1_INTEGER_get.html + pub fn to_bn(&self) -> Result { + unsafe { + cvt_p(::ffi::ASN1_INTEGER_to_BN(self.as_ptr(), ptr::null_mut())) + .map(|p| BigNum::from_ptr(p)) + } + } + + /// Sets the ASN.1 value to the value of a signed 32-bit integer, for larger numbers + /// see [`bn`]. + /// + /// OpenSSL documentation at [`ASN1_INTEGER_set`] + /// + /// [`bn`]: ../bn/struct.BigNumRef.html#method.to_asn1_integer + /// [`ASN1_INTEGER_set`]: https://www.openssl.org/docs/man1.1.0/crypto/ASN1_INTEGER_set.html + pub fn set(&mut self, value: i32) -> Result<(), ErrorStack> { + unsafe { cvt(::ffi::ASN1_INTEGER_set(self.as_ptr(), value as c_long)).map(|_| ()) } + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::ASN1_BIT_STRING; + fn drop = ffi::ASN1_BIT_STRING_free; + /// Sequence of bytes + /// + /// Asn1BitString is used in [`x509`] certificates for the signature. + /// The bit string acts as a collection of bytes. + /// + /// [`x509`]: ../x509/struct.X509.html#method.signature + pub struct Asn1BitString; + /// Reference to [`Asn1BitString`] + /// + /// [`Asn1BitString`]: struct.Asn1BitString.html + pub struct Asn1BitStringRef; +} + +impl Asn1BitStringRef { + /// Returns the Asn1BitString as a slice + pub fn as_slice(&self) -> &[u8] { + unsafe { slice::from_raw_parts(ASN1_STRING_data(self.as_ptr() as *mut _), self.len()) } + } + /// Length of Asn1BitString in number of bytes. + pub fn len(&self) -> usize { + unsafe { ffi::ASN1_STRING_length(self.as_ptr() as *mut _) as usize } + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::ASN1_OBJECT; + fn drop = ffi::ASN1_OBJECT_free; + + /// Object Identifier + /// + /// Represents an ASN.1 Object. Typically, NIDs, or numeric identifiers + /// are stored as a table within the [`Nid`] module. These constants are + /// used to determine attributes of a certificate, such as mapping the + /// attribute "CommonName" to "CN" which is represented as the OID of 13. + /// This attribute is a constant in the [`nid::COMMONNAME`]. + /// + /// OpenSSL documentation at [`OBJ_nid2obj`] + /// + /// [`Nid`]: ../nid/index.html + /// [`nid::COMMONNAME`]: ../nid/constant.COMMONNAME.html + /// [`OBJ_nid2obj`]: https://www.openssl.org/docs/man1.1.0/crypto/OBJ_obj2nid.html + pub struct Asn1Object; + /// Reference to [`Asn1Object`] + /// + /// [`Asn1Object`]: struct.Asn1Object.html + pub struct Asn1ObjectRef; +} + +impl Asn1ObjectRef { + /// Returns the NID associated with this OID. + pub fn nid(&self) -> Nid { + unsafe { Nid::from_raw(ffi::OBJ_obj2nid(self.as_ptr())) } + } +} + +impl fmt::Display for Asn1ObjectRef { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + unsafe { + let mut buf = [0; 80]; + let len = ffi::OBJ_obj2txt( + buf.as_mut_ptr() as *mut _, + buf.len() as c_int, + self.as_ptr(), + 0, + ); + let s = str::from_utf8(&buf[..len as usize]).map_err(|_| fmt::Error)?; + fmt.write_str(s) + } + } +} + +#[cfg(any(ossl101, ossl102))] +use ffi::ASN1_STRING_data; + +#[cfg(ossl110)] +#[allow(bad_style)] +unsafe fn ASN1_STRING_data(s: *mut ffi::ASN1_STRING) -> *mut ::libc::c_uchar { + ffi::ASN1_STRING_get0_data(s) as *mut _ +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/bio.rs cargo-0.26.0/vendor/openssl-0.10.6/src/bio.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/bio.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/bio.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,78 @@ +use std::marker::PhantomData; +use std::ptr; +use std::slice; +use libc::c_int; +use ffi; + +use cvt_p; +use error::ErrorStack; + +pub struct MemBioSlice<'a>(*mut ffi::BIO, PhantomData<&'a [u8]>); + +impl<'a> Drop for MemBioSlice<'a> { + fn drop(&mut self) { + unsafe { + ffi::BIO_free_all(self.0); + } + } +} + +impl<'a> MemBioSlice<'a> { + pub fn new(buf: &'a [u8]) -> Result, ErrorStack> { + ffi::init(); + + assert!(buf.len() <= c_int::max_value() as usize); + let bio = unsafe { + cvt_p(BIO_new_mem_buf( + buf.as_ptr() as *const _, + buf.len() as c_int, + ))? + }; + + Ok(MemBioSlice(bio, PhantomData)) + } + + pub fn as_ptr(&self) -> *mut ffi::BIO { + self.0 + } +} + +pub struct MemBio(*mut ffi::BIO); + +impl Drop for MemBio { + fn drop(&mut self) { + unsafe { + ffi::BIO_free_all(self.0); + } + } +} + +impl MemBio { + pub fn new() -> Result { + ffi::init(); + + let bio = unsafe { cvt_p(ffi::BIO_new(ffi::BIO_s_mem()))? }; + Ok(MemBio(bio)) + } + + pub fn as_ptr(&self) -> *mut ffi::BIO { + self.0 + } + + pub fn get_buf(&self) -> &[u8] { + unsafe { + let mut ptr = ptr::null_mut(); + let len = ffi::BIO_get_mem_data(self.0, &mut ptr); + slice::from_raw_parts(ptr as *const _ as *const _, len as usize) + } + } +} + +#[cfg(not(ossl101))] +use ffi::BIO_new_mem_buf; + +#[cfg(ossl101)] +#[allow(bad_style)] +unsafe fn BIO_new_mem_buf(buf: *const ::libc::c_void, len: ::libc::c_int) -> *mut ffi::BIO { + ffi::BIO_new_mem_buf(buf as *mut _, len) +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/bn.rs cargo-0.26.0/vendor/openssl-0.10.6/src/bn.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/bn.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/bn.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1404 @@ +//! BigNum implementation +//! +//! Large numbers are important for a cryptographic library. OpenSSL implementation +//! of BigNum uses dynamically assigned memory to store an array of bit chunks. This +//! allows numbers of any size to be compared and mathematical functions performed. +//! +//! OpenSSL wiki describes the [`BIGNUM`] data structure. +//! +//! # Examples +//! +//! ``` +//! use openssl::bn::BigNum; +//! use openssl::error::ErrorStack; +//! +//! fn bignums() -> Result<(), ErrorStack> { +//! let a = BigNum::new()?; // a = 0 +//! let b = BigNum::from_dec_str("1234567890123456789012345")?; +//! let c = &a * &b; +//! assert_eq!(a, c); +//! Ok(()) +//! } +//! # fn main() { +//! # bignums(); +//! # } +//! ``` +//! +//! [`BIGNUM`]: https://wiki.openssl.org/index.php/Manual:Bn_internal(3) +use ffi; +use foreign_types::{ForeignType, ForeignTypeRef}; +use libc::c_int; +use std::cmp::Ordering; +use std::ffi::CString; +use std::{fmt, ptr}; +use std::ops::{Add, Deref, Div, Mul, Neg, Rem, Shl, Shr, Sub}; + +use {cvt, cvt_n, cvt_p}; +use asn1::Asn1Integer; +use error::ErrorStack; +use string::OpensslString; + +#[cfg(ossl10x)] +use ffi::{get_rfc2409_prime_1024 as BN_get_rfc2409_prime_1024, + get_rfc2409_prime_768 as BN_get_rfc2409_prime_768, + get_rfc3526_prime_1536 as BN_get_rfc3526_prime_1536, + get_rfc3526_prime_2048 as BN_get_rfc3526_prime_2048, + get_rfc3526_prime_3072 as BN_get_rfc3526_prime_3072, + get_rfc3526_prime_4096 as BN_get_rfc3526_prime_4096, + get_rfc3526_prime_6144 as BN_get_rfc3526_prime_6144, + get_rfc3526_prime_8192 as BN_get_rfc3526_prime_8192}; + +#[cfg(ossl110)] +use ffi::{BN_get_rfc2409_prime_1024, BN_get_rfc2409_prime_768, BN_get_rfc3526_prime_1536, + BN_get_rfc3526_prime_2048, BN_get_rfc3526_prime_3072, BN_get_rfc3526_prime_4096, + BN_get_rfc3526_prime_6144, BN_get_rfc3526_prime_8192}; + +/// Options for the most significant bits of a randomly generated `BigNum`. +pub struct MsbOption(c_int); + +impl MsbOption { + /// The most significant bit of the number may be 0. + pub const MAYBE_ZERO: MsbOption = MsbOption(-1); + + /// The most significant bit of the number must be 1. + pub const ONE: MsbOption = MsbOption(0); + + /// The most significant two bits of the number must be 1. + /// + /// The number of bits in the product of two such numbers will always be exactly twice the + /// number of bits in the original numbers. + pub const TWO_ONES: MsbOption = MsbOption(1); +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::BN_CTX; + fn drop = ffi::BN_CTX_free; + + /// Temporary storage for BigNums on the secure heap + /// + /// BigNum values are stored dynamically and therefore can be expensive + /// to allocate. BigNumContext and the OpenSSL [`BN_CTX`] structure are used + /// internally when passing BigNum values between subroutines. + /// + /// [`BN_CTX`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_CTX_new.html + pub struct BigNumContext; + /// Reference to [`BigNumContext`] + /// + /// [`BigNumContext`]: struct.BigNumContext.html + pub struct BigNumContextRef; +} + +impl BigNumContext { + /// Returns a new `BigNumContext`. + /// + /// See OpenSSL documentation at [`BN_CTX_new`]. + /// + /// [`BN_CTX_new`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_CTX_new.html + pub fn new() -> Result { + unsafe { + ffi::init(); + cvt_p(ffi::BN_CTX_new()).map(BigNumContext) + } + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::BIGNUM; + fn drop = ffi::BN_free; + + /// Dynamically sized large number impelementation + /// + /// Perform large number mathematics. Create a new BigNum + /// with [`new`]. Perform stanard mathematics on large numbers using + /// methods from [`Dref`] + /// + /// OpenSSL documenation at [`BN_new`]. + /// + /// [`new`]: struct.BigNum.html#method.new + /// [`Dref`]: struct.BigNum.html#deref-methods + /// [`BN_new`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_new.html + /// + /// # Examples + /// ``` + /// use openssl::bn::BigNum; + /// # use openssl::error::ErrorStack; + /// # fn bignums() -> Result< (), ErrorStack > { + /// let little_big = BigNum::from_u32(std::u32::MAX)?; + /// assert_eq!(*&little_big.num_bytes(), 4); + /// # Ok(()) + /// # } + /// # fn main () { bignums(); } + /// ``` + pub struct BigNum; + /// Reference to a [`BigNum`] + /// + /// [`BigNum`]: struct.BigNum.html + pub struct BigNumRef; +} + +impl BigNumRef { + /// Erases the memory used by this `BigNum`, resetting its value to 0. + /// + /// This can be used to destroy sensitive data such as keys when they are no longer needed. + /// + /// OpenSSL documentation at [`BN_clear`] + /// + /// [`BN_clear`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_clear.html + pub fn clear(&mut self) { + unsafe { ffi::BN_clear(self.as_ptr()) } + } + + /// Adds a `u32` to `self`. + /// + /// OpenSSL documentation at [`BN_add_word`] + /// + /// [`BN_add_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_add_word.html + pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_add_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } + } + + /// Subtracts a `u32` from `self`. + /// + /// OpenSSL documentation at [`BN_sub_word`] + /// + /// [`BN_sub_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_sub_word.html + pub fn sub_word(&mut self, w: u32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_sub_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } + } + + /// Multiplies a `u32` by `self`. + /// + /// OpenSSL documentation at [`BN_mul_word`] + /// + /// [`BN_mul_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mul_word.html + pub fn mul_word(&mut self, w: u32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_mul_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } + } + + /// Divides `self` by a `u32`, returning the remainder. + /// + /// OpenSSL documentation at [`BN_div_word`] + /// + /// [`BN_div_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div_word.html + pub fn div_word(&mut self, w: u32) -> Result { + unsafe { + let r = ffi::BN_div_word(self.as_ptr(), w.into()); + if r == ffi::BN_ULONG::max_value() { + Err(ErrorStack::get()) + } else { + Ok(r.into()) + } + } + } + + /// Returns the result of `self` modulo `w`. + /// + /// OpenSSL documentation at [`BN_mod_word`] + /// + /// [`BN_mod_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_word.html + pub fn mod_word(&self, w: u32) -> Result { + unsafe { + let r = ffi::BN_mod_word(self.as_ptr(), w.into()); + if r == ffi::BN_ULONG::max_value() { + Err(ErrorStack::get()) + } else { + Ok(r.into()) + } + } + } + + /// Places a cryptographically-secure pseudo-random nonnegative + /// number less than `self` in `rnd`. + /// + /// OpenSSL documentation at [`BN_rand_range`] + /// + /// [`BN_rand_range`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rand_range.html + pub fn rand_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_rand_range(rnd.as_ptr(), self.as_ptr())).map(|_| ()) } + } + + /// The cryptographically weak counterpart to `rand_in_range`. + /// + /// OpenSSL documentation at [`BN_pseudo_rand_range`] + /// + /// [`BN_pseudo_rand_range`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_pseudo_rand_range.html + pub fn pseudo_rand_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_pseudo_rand_range(rnd.as_ptr(), self.as_ptr())).map(|_| ()) } + } + + /// Sets bit `n`. Equivalent to `self |= (1 << n)`. + /// + /// When setting a bit outside of `self`, it is expanded. + /// + /// OpenSSL documentation at [`BN_set_bit`] + /// + /// [`BN_set_bit`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_set_bit.html + pub fn set_bit(&mut self, n: i32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_set_bit(self.as_ptr(), n.into())).map(|_| ()) } + } + + /// Clears bit `n`, setting it to 0. Equivalent to `self &= ~(1 << n)`. + /// + /// When clearing a bit outside of `self`, an error is returned. + /// + /// OpenSSL documentation at [`BN_clear_bit`] + /// + /// [`BN_clear_bit`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_clear_bit.html + pub fn clear_bit(&mut self, n: i32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_clear_bit(self.as_ptr(), n.into())).map(|_| ()) } + } + + /// Returns `true` if the `n`th bit of `self` is set to 1, `false` otherwise. + /// + /// OpenSSL documentation at [`BN_is_bit_set`] + /// + /// [`BN_is_bit_set`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_is_bit_set.html + pub fn is_bit_set(&self, n: i32) -> bool { + unsafe { ffi::BN_is_bit_set(self.as_ptr(), n.into()) == 1 } + } + + /// Truncates `self` to the lowest `n` bits. + /// + /// An error occurs if `self` is already shorter than `n` bits. + /// + /// OpenSSL documentation at [`BN_mask_bits`] + /// + /// [`BN_mask_bits`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mask_bits.html + pub fn mask_bits(&mut self, n: i32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_mask_bits(self.as_ptr(), n.into())).map(|_| ()) } + } + + /// Places `a << 1` in `self`. Equivalent to `self * 2`. + /// + /// OpenSSL documentation at [`BN_lshift1`] + /// + /// [`BN_lshift1`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_lshift1.html + pub fn lshift1(&mut self, a: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_lshift1(self.as_ptr(), a.as_ptr())).map(|_| ()) } + } + + /// Places `a >> 1` in `self`. Equivalent to `self / 2`. + /// + /// OpenSSL documentation at [`BN_rshift1`] + /// + /// [`BN_rshift1`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rshift1.html + pub fn rshift1(&mut self, a: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_rshift1(self.as_ptr(), a.as_ptr())).map(|_| ()) } + } + + /// Places `a + b` in `self`. [`core::ops::Add`] is also implemented for `BigNumRef`. + /// + /// OpenSSL documentation at [`BN_add`] + /// + /// [`core::ops::Add`]: struct.BigNumRef.html#method.add + /// [`BN_add`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_add.html + pub fn checked_add(&mut self, a: &BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_add(self.as_ptr(), a.as_ptr(), b.as_ptr())).map(|_| ()) } + } + + /// Places `a - b` in `self`. [`core::ops::Sub`] is also implemented for `BigNumRef`. + /// + /// OpenSSL documentation at [`BN_sub`] + /// + /// [`core::ops::Sub`]: struct.BigNumRef.html#method.sub + /// [`BN_sub`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_sub.html + pub fn checked_sub(&mut self, a: &BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_sub(self.as_ptr(), a.as_ptr(), b.as_ptr())).map(|_| ()) } + } + + /// Places `a << n` in `self`. Equivalent to `a * 2 ^ n`. + /// + /// OpenSSL documentation at [`BN_lshift`] + /// + /// [`BN_lshift`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_lshift.html + pub fn lshift(&mut self, a: &BigNumRef, n: i32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_lshift(self.as_ptr(), a.as_ptr(), n.into())).map(|_| ()) } + } + + /// Places `a >> n` in `self`. Equivalent to `a / 2 ^ n`. + /// + /// OpenSSL documentation at [`BN_rshift`] + /// + /// [`BN_rshift`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rshift.html + pub fn rshift(&mut self, a: &BigNumRef, n: i32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_rshift(self.as_ptr(), a.as_ptr(), n.into())).map(|_| ()) } + } + + /// Creates a new BigNum with the same value. + /// + /// OpenSSL documentation at [`BN_dup`] + /// + /// [`BN_dup`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_dup.html + pub fn to_owned(&self) -> Result { + unsafe { cvt_p(ffi::BN_dup(self.as_ptr())).map(|b| BigNum::from_ptr(b)) } + } + + /// Sets the sign of `self`. Pass true to set `self` to a negative. False sets + /// `self` positive. + pub fn set_negative(&mut self, negative: bool) { + unsafe { ffi::BN_set_negative(self.as_ptr(), negative as c_int) } + } + + /// Compare the absolute values of `self` and `oth`. + /// + /// OpenSSL documentation at [`BN_ucmp`] + /// + /// [`BN_ucmp`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_ucmp.html + /// + /// # Examples + /// + /// ``` + /// # use openssl::bn::BigNum; + /// # use std::cmp::Ordering; + /// let s = -BigNum::from_u32(8).unwrap(); + /// let o = BigNum::from_u32(8).unwrap(); + /// + /// assert_eq!(s.ucmp(&o), Ordering::Equal); + /// ``` + pub fn ucmp(&self, oth: &BigNumRef) -> Ordering { + unsafe { ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } + } + + /// Returns `true` if `self` is negative. + pub fn is_negative(&self) -> bool { + self._is_negative() + } + + #[cfg(ossl10x)] + fn _is_negative(&self) -> bool { + unsafe { (*self.as_ptr()).neg == 1 } + } + + #[cfg(ossl110)] + fn _is_negative(&self) -> bool { + unsafe { ffi::BN_is_negative(self.as_ptr()) == 1 } + } + + /// Returns the number of significant bits in `self`. + /// + /// OpenSSL documentation at [`BN_num_bits`] + /// + /// [`BN_num_bits`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_num_bits.html + pub fn num_bits(&self) -> i32 { + unsafe { ffi::BN_num_bits(self.as_ptr()) as i32 } + } + + /// Returns the size of `self` in bytes. Implemented natively. + pub fn num_bytes(&self) -> i32 { + (self.num_bits() + 7) / 8 + } + + /// Generates a cryptographically strong pseudo-random `BigNum`, placing it in `self`. + /// + /// # Parameters + /// + /// * `bits`: Length of the number in bits. + /// * `msb`: The desired properties of the most significant bit. See [`constants`]. + /// * `odd`: If `true`, the generated number will be odd. + /// + /// # Examples + /// + /// ``` + /// use openssl::bn::{BigNum, MsbOption}; + /// use openssl::error::ErrorStack; + /// + /// fn generate_random() -> Result< BigNum, ErrorStack > { + /// let mut big = BigNum::new()?; + /// + /// // Generates a 128-bit odd random number + /// big.rand(128, MsbOption::MAYBE_ZERO, true); + /// Ok((big)) + /// } + /// ``` + /// + /// OpenSSL documentation at [`BN_rand`] + /// + /// [`constants`]: index.html#constants + /// [`BN_rand`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rand.html + pub fn rand(&mut self, bits: i32, msb: MsbOption, odd: bool) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_rand( + self.as_ptr(), + bits.into(), + msb.0, + odd as c_int, + )).map(|_| ()) + } + } + + /// The cryptographically weak counterpart to `rand`. Not suitable for key generation. + /// + /// OpenSSL documentation at [`BN_psuedo_rand`] + /// + /// [`BN_psuedo_rand`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_pseudo_rand.html + pub fn pseudo_rand(&mut self, bits: i32, msb: MsbOption, odd: bool) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_pseudo_rand( + self.as_ptr(), + bits.into(), + msb.0, + odd as c_int, + )).map(|_| ()) + } + } + + /// Generates a prime number, placing it in `self`. + /// + /// # Parameters + /// + /// * `bits`: The length of the prime in bits (lower bound). + /// * `safe`: If true, returns a "safe" prime `p` so that `(p-1)/2` is also prime. + /// * `add`/`rem`: If `add` is set to `Some(add)`, `p % add == rem` will hold, where `p` is the + /// generated prime and `rem` is `1` if not specified (`None`). + /// + /// # Examples + /// + /// ``` + /// use openssl::bn::BigNum; + /// use openssl::error::ErrorStack; + /// + /// fn generate_weak_prime() -> Result< BigNum, ErrorStack > { + /// let mut big = BigNum::new()?; + /// + /// // Generates a 128-bit simple prime number + /// big.generate_prime(128, false, None, None); + /// Ok((big)) + /// } + /// ``` + /// + /// OpenSSL documentation at [`BN_generate_prime_ex`] + /// + /// [`BN_generate_prime_ex`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_generate_prime_ex.html + pub fn generate_prime( + &mut self, + bits: i32, + safe: bool, + add: Option<&BigNumRef>, + rem: Option<&BigNumRef>, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_generate_prime_ex( + self.as_ptr(), + bits as c_int, + safe as c_int, + add.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()), + rem.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()), + ptr::null_mut(), + )).map(|_| ()) + } + } + + /// Places the result of `a * b` in `self`. + /// [`core::ops::Mul`] is also implemented for `BigNumRef`. + /// + /// OpenSSL documentation at [`BN_mul`] + /// + /// [`core::ops::Mul`]: struct.BigNumRef.html#method.mul + /// [`BN_mul`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mul.html + pub fn checked_mul( + &mut self, + a: &BigNumRef, + b: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mul( + self.as_ptr(), + a.as_ptr(), + b.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the result of `a / b` in `self`. The remainder is discarded. + /// [`core::ops::Div`] is also implemented for `BigNumRef`. + /// + /// OpenSSL documentation at [`BN_div`] + /// + /// [`core::ops::Div`]: struct.BigNumRef.html#method.div + /// [`BN_div`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div.html + pub fn checked_div( + &mut self, + a: &BigNumRef, + b: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_div( + self.as_ptr(), + ptr::null_mut(), + a.as_ptr(), + b.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the result of `a % b` in `self`. + /// + /// OpenSSL documentation at [`BN_div`] + /// + /// [`BN_div`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div.html + pub fn checked_rem( + &mut self, + a: &BigNumRef, + b: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_div( + ptr::null_mut(), + self.as_ptr(), + a.as_ptr(), + b.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the result of `a / b` in `self` and `a % b` in `rem`. + /// + /// OpenSSL documentation at [`BN_div`] + /// + /// [`BN_div`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div.html + pub fn div_rem( + &mut self, + rem: &mut BigNumRef, + a: &BigNumRef, + b: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_div( + self.as_ptr(), + rem.as_ptr(), + a.as_ptr(), + b.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the result of `a²` in `self`. + /// + /// OpenSSL documentation at [`BN_sqr`] + /// + /// [`BN_sqr`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_sqr.html + pub fn sqr(&mut self, a: &BigNumRef, ctx: &mut BigNumContextRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::BN_sqr(self.as_ptr(), a.as_ptr(), ctx.as_ptr())).map(|_| ()) } + } + + /// Places the result of `a mod m` in `self`. As opposed to `div_rem` + /// the result is non-negative. + /// + /// OpenSSL documentation at [`BN_nnmod`] + /// + /// [`BN_nnmod`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_nnmod.html + pub fn nnmod( + &mut self, + a: &BigNumRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_nnmod( + self.as_ptr(), + a.as_ptr(), + m.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the result of `(a + b) mod m` in `self`. + /// + /// OpenSSL documentation at [`BN_mod_add`] + /// + /// [`BN_mod_add`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_add.html + pub fn mod_add( + &mut self, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_add( + self.as_ptr(), + a.as_ptr(), + b.as_ptr(), + m.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the result of `(a - b) mod m` in `self`. + /// + /// OpenSSL documentation at [`BN_mod_sub`] + /// + /// [`BN_mod_sub`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_sub.html + pub fn mod_sub( + &mut self, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_sub( + self.as_ptr(), + a.as_ptr(), + b.as_ptr(), + m.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the result of `(a * b) mod m` in `self`. + /// + /// OpenSSL documentation at [`BN_mod_mul`] + /// + /// [`BN_mod_mul`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_mul.html + pub fn mod_mul( + &mut self, + a: &BigNumRef, + b: &BigNumRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_mul( + self.as_ptr(), + a.as_ptr(), + b.as_ptr(), + m.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the result of `a² mod m` in `self`. + /// + /// OpenSSL documentation at [`BN_mod_sqr`] + /// + /// [`BN_mod_sqr`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_sqr.html + pub fn mod_sqr( + &mut self, + a: &BigNumRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_sqr( + self.as_ptr(), + a.as_ptr(), + m.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the result of `a^p` in `self`. + /// + /// OpenSSL documentation at [`BN_exp`] + /// + /// [`BN_exp`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_exp.html + pub fn exp( + &mut self, + a: &BigNumRef, + p: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_exp( + self.as_ptr(), + a.as_ptr(), + p.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the result of `a^p mod m` in `self`. + /// + /// OpenSSL documentation at [`BN_mod_exp`] + /// + /// [`BN_mod_exp`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_exp.html + pub fn mod_exp( + &mut self, + a: &BigNumRef, + p: &BigNumRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_mod_exp( + self.as_ptr(), + a.as_ptr(), + p.as_ptr(), + m.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the inverse of `a` modulo `n` in `self`. + pub fn mod_inverse( + &mut self, + a: &BigNumRef, + n: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt_p(ffi::BN_mod_inverse( + self.as_ptr(), + a.as_ptr(), + n.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the greatest common denominator of `a` and `b` in `self`. + /// + /// OpenSSL documentation at [`BN_gcd`] + /// + /// [`BN_gcd`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_gcd.html + pub fn gcd( + &mut self, + a: &BigNumRef, + b: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::BN_gcd( + self.as_ptr(), + a.as_ptr(), + b.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Checks whether `self` is prime. + /// + /// Performs a Miller-Rabin probabilistic primality test with `checks` iterations. + /// + /// OpenSSL documentation at [`BN_is_prime_ex`] + /// + /// [`BN_is_prime_ex`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_is_prime_ex.html + /// + /// # Return Value + /// + /// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`. + + pub fn is_prime(&self, checks: i32, ctx: &mut BigNumContextRef) -> Result { + unsafe { + cvt_n(ffi::BN_is_prime_ex( + self.as_ptr(), + checks.into(), + ctx.as_ptr(), + ptr::null_mut(), + )).map(|r| r != 0) + } + } + + /// Checks whether `self` is prime with optional trial division. + /// + /// If `do_trial_division` is `true`, first performs trial division by a number of small primes. + /// Then, like `is_prime`, performs a Miller-Rabin probabilistic primality test with `checks` + /// iterations. + /// + /// OpenSSL documentation at [`BN_is_prime_fasttest_ex`] + /// + /// [`BN_is_prime_fasttest_ex`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_is_prime_fasttest_ex.html + /// + /// # Return Value + /// + /// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`. + pub fn is_prime_fasttest( + &self, + checks: i32, + ctx: &mut BigNumContextRef, + do_trial_division: bool, + ) -> Result { + unsafe { + cvt_n(ffi::BN_is_prime_fasttest_ex( + self.as_ptr(), + checks.into(), + ctx.as_ptr(), + do_trial_division as c_int, + ptr::null_mut(), + )).map(|r| r != 0) + } + } + + /// Returns a big-endian byte vector representation of the absolute value of `self`. + /// + /// `self` can be recreated by using `from_slice`. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let s = -BigNum::from_u32(4543).unwrap(); + /// let r = BigNum::from_u32(4543).unwrap(); + /// + /// let s_vec = s.to_vec(); + /// assert_eq!(BigNum::from_slice(&s_vec).unwrap(), r); + /// ``` + pub fn to_vec(&self) -> Vec { + let size = self.num_bytes() as usize; + let mut v = Vec::with_capacity(size); + unsafe { + ffi::BN_bn2bin(self.as_ptr(), v.as_mut_ptr()); + v.set_len(size); + } + v + } + + /// Returns a decimal string representation of `self`. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let s = -BigNum::from_u32(12345).unwrap(); + /// + /// assert_eq!(&**s.to_dec_str().unwrap(), "-12345"); + /// ``` + pub fn to_dec_str(&self) -> Result { + unsafe { + let buf = cvt_p(ffi::BN_bn2dec(self.as_ptr()))?; + Ok(OpensslString::from_ptr(buf)) + } + } + + /// Returns a hexadecimal string representation of `self`. + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let s = -BigNum::from_u32(0x99ff).unwrap(); + /// + /// assert_eq!(&**s.to_hex_str().unwrap(), "-99FF"); + /// ``` + pub fn to_hex_str(&self) -> Result { + unsafe { + let buf = cvt_p(ffi::BN_bn2hex(self.as_ptr()))?; + Ok(OpensslString::from_ptr(buf)) + } + } + + /// Returns an `Asn1Integer` containing the value of `self`. + pub fn to_asn1_integer(&self) -> Result { + unsafe { + cvt_p(ffi::BN_to_ASN1_INTEGER(self.as_ptr(), ptr::null_mut())) + .map(|p| Asn1Integer::from_ptr(p)) + } + } +} + +impl BigNum { + /// Creates a new `BigNum` with the value 0. + pub fn new() -> Result { + unsafe { + ffi::init(); + let v = cvt_p(ffi::BN_new())?; + Ok(BigNum::from_ptr(v)) + } + } + + /// Creates a new `BigNum` with the given value. + /// + /// OpenSSL documentation at [`BN_set_word`] + /// + /// [`BN_set_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_set_word.html + pub fn from_u32(n: u32) -> Result { + BigNum::new().and_then(|v| unsafe { + cvt(ffi::BN_set_word(v.as_ptr(), n as ffi::BN_ULONG)).map(|_| v) + }) + } + + /// Creates a `BigNum` from a decimal string. + /// + /// OpenSSL documentation at [`BN_dec2bn`] + /// + /// [`BN_dec2bn`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_dec2bn.html + pub fn from_dec_str(s: &str) -> Result { + unsafe { + ffi::init(); + let c_str = CString::new(s.as_bytes()).unwrap(); + let mut bn = ptr::null_mut(); + cvt(ffi::BN_dec2bn(&mut bn, c_str.as_ptr() as *const _))?; + Ok(BigNum::from_ptr(bn)) + } + } + + /// Creates a `BigNum` from a hexadecimal string. + /// + /// OpenSSL documentation at [`BN_hex2bn`] + /// + /// [`BN_hex2bn`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_hex2bn.html + pub fn from_hex_str(s: &str) -> Result { + unsafe { + ffi::init(); + let c_str = CString::new(s.as_bytes()).unwrap(); + let mut bn = ptr::null_mut(); + cvt(ffi::BN_hex2bn(&mut bn, c_str.as_ptr() as *const _))?; + Ok(BigNum::from_ptr(bn)) + } + } + + /// Returns a constant used in IKE as defined in [`RFC 2409`]. This prime number is in + /// the order of magnitude of `2 ^ 768`. This number is used during calculated key + /// exchanges such as Diffie-Hellman. This number is labeled Oakley group id 1. + /// + /// OpenSSL documentation at [`BN_get_rfc2409_prime_768`] + /// + /// [`RFC 2409`]: https://tools.ietf.org/html/rfc2409#page-21 + /// [`BN_get_rfc2409_prime_768`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc2409_prime_768.html + pub fn get_rfc2409_prime_768() -> Result { + unsafe { + ffi::init(); + cvt_p(BN_get_rfc2409_prime_768(ptr::null_mut())).map(BigNum) + } + } + + /// Returns a constant used in IKE as defined in [`RFC 2409`]. This prime number is in + /// the order of magnitude of `2 ^ 1024`. This number is used during calculated key + /// exchanges such as Diffie-Hellman. This number is labeled Oakly group 2. + /// + /// OpenSSL documentation at [`BN_get_rfc2409_prime_1024`] + /// + /// [`RFC 2409`]: https://tools.ietf.org/html/rfc2409#page-21 + /// [`BN_get_rfc2409_prime_1024`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc2409_prime_1024.html + pub fn get_rfc2409_prime_1024() -> Result { + unsafe { + ffi::init(); + cvt_p(BN_get_rfc2409_prime_1024(ptr::null_mut())).map(BigNum) + } + } + + /// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order + /// of magnitude of `2 ^ 1536`. This number is used during calculated key + /// exchanges such as Diffie-Hellman. This number is labeled MODP group 5. + /// + /// OpenSSL documentation at [`BN_get_rfc3526_prime_1536`] + /// + /// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-3 + /// [`BN_get_rfc3526_prime_1536`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_1536.html + pub fn get_rfc3526_prime_1536() -> Result { + unsafe { + ffi::init(); + cvt_p(BN_get_rfc3526_prime_1536(ptr::null_mut())).map(BigNum) + } + } + + /// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order + /// of magnitude of `2 ^ 2048`. This number is used during calculated key + /// exchanges such as Diffie-Hellman. This number is labeled MODP group 14. + /// + /// OpenSSL documentation at [`BN_get_rfc3526_prime_2048`] + /// + /// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-3 + /// [`BN_get_rfc3526_prime_2048`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_2048.html + pub fn get_rfc3526_prime_2048() -> Result { + unsafe { + ffi::init(); + cvt_p(BN_get_rfc3526_prime_2048(ptr::null_mut())).map(BigNum) + } + } + + /// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order + /// of magnitude of `2 ^ 3072`. This number is used during calculated key + /// exchanges such as Diffie-Hellman. This number is labeled MODP group 15. + /// + /// OpenSSL documentation at [`BN_get_rfc3526_prime_3072`] + /// + /// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-4 + /// [`BN_get_rfc3526_prime_3072`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_3072.html + pub fn get_rfc3526_prime_3072() -> Result { + unsafe { + ffi::init(); + cvt_p(BN_get_rfc3526_prime_3072(ptr::null_mut())).map(BigNum) + } + } + + /// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order + /// of magnitude of `2 ^ 4096`. This number is used during calculated key + /// exchanges such as Diffie-Hellman. This number is labeled MODP group 16. + /// + /// OpenSSL documentation at [`BN_get_rfc3526_prime_4096`] + /// + /// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-4 + /// [`BN_get_rfc3526_prime_4096`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_4096.html + pub fn get_rfc3526_prime_4096() -> Result { + unsafe { + ffi::init(); + cvt_p(BN_get_rfc3526_prime_4096(ptr::null_mut())).map(BigNum) + } + } + + /// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order + /// of magnitude of `2 ^ 6144`. This number is used during calculated key + /// exchanges such as Diffie-Hellman. This number is labeled MODP group 17. + /// + /// OpenSSL documentation at [`BN_get_rfc3526_prime_6144`] + /// + /// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-6 + /// [`BN_get_rfc3526_prime_6144`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_6144.html + pub fn get_rfc3526_prime_6144() -> Result { + unsafe { + ffi::init(); + cvt_p(BN_get_rfc3526_prime_6144(ptr::null_mut())).map(BigNum) + } + } + + /// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order + /// of magnitude of `2 ^ 8192`. This number is used during calculated key + /// exchanges such as Diffie-Hellman. This number is labeled MODP group 18. + /// + /// OpenSSL documentation at [`BN_get_rfc3526_prime_8192`] + /// + /// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-6 + /// [`BN_get_rfc3526_prime_8192`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_8192.html + pub fn get_rfc3526_prime_8192() -> Result { + unsafe { + ffi::init(); + cvt_p(BN_get_rfc3526_prime_8192(ptr::null_mut())).map(BigNum) + } + } + + /// Creates a new `BigNum` from an unsigned, big-endian encoded number of arbitrary length. + /// + /// OpenSSL documentation at [`BN_bin2bn`] + /// + /// [`BN_bin2bn`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_bin2bn.html + /// + /// ``` + /// # use openssl::bn::BigNum; + /// let bignum = BigNum::from_slice(&[0x12, 0x00, 0x34]).unwrap(); + /// + /// assert_eq!(bignum, BigNum::from_u32(0x120034).unwrap()); + /// ``` + pub fn from_slice(n: &[u8]) -> Result { + unsafe { + ffi::init(); + assert!(n.len() <= c_int::max_value() as usize); + cvt_p(ffi::BN_bin2bn( + n.as_ptr(), + n.len() as c_int, + ptr::null_mut(), + )).map(|p| BigNum::from_ptr(p)) + } + } +} + +impl fmt::Debug for BigNumRef { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.to_dec_str() { + Ok(s) => f.write_str(&s), + Err(e) => Err(e.into()), + } + } +} + +impl fmt::Debug for BigNum { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.to_dec_str() { + Ok(s) => f.write_str(&s), + Err(e) => Err(e.into()), + } + } +} + +impl fmt::Display for BigNumRef { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.to_dec_str() { + Ok(s) => f.write_str(&s), + Err(e) => Err(e.into()), + } + } +} + +impl fmt::Display for BigNum { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.to_dec_str() { + Ok(s) => f.write_str(&s), + Err(e) => Err(e.into()), + } + } +} + +impl PartialEq for BigNumRef { + fn eq(&self, oth: &BigNumRef) -> bool { + self.cmp(oth) == Ordering::Equal + } +} + +impl PartialEq for BigNumRef { + fn eq(&self, oth: &BigNum) -> bool { + self.eq(oth.deref()) + } +} + +impl Eq for BigNumRef {} + +impl PartialEq for BigNum { + fn eq(&self, oth: &BigNum) -> bool { + self.deref().eq(oth) + } +} + +impl PartialEq for BigNum { + fn eq(&self, oth: &BigNumRef) -> bool { + self.deref().eq(oth) + } +} + +impl Eq for BigNum {} + +impl PartialOrd for BigNumRef { + fn partial_cmp(&self, oth: &BigNumRef) -> Option { + Some(self.cmp(oth)) + } +} + +impl PartialOrd for BigNumRef { + fn partial_cmp(&self, oth: &BigNum) -> Option { + Some(self.cmp(oth.deref())) + } +} + +impl Ord for BigNumRef { + fn cmp(&self, oth: &BigNumRef) -> Ordering { + unsafe { ffi::BN_cmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } + } +} + +impl PartialOrd for BigNum { + fn partial_cmp(&self, oth: &BigNum) -> Option { + self.deref().partial_cmp(oth.deref()) + } +} + +impl PartialOrd for BigNum { + fn partial_cmp(&self, oth: &BigNumRef) -> Option { + self.deref().partial_cmp(oth) + } +} + +impl Ord for BigNum { + fn cmp(&self, oth: &BigNum) -> Ordering { + self.deref().cmp(oth.deref()) + } +} + +macro_rules! delegate { + ($t:ident, $m:ident) => { + impl<'a, 'b> $t<&'b BigNum> for &'a BigNumRef { + type Output = BigNum; + + fn $m(self, oth: &BigNum) -> BigNum { + $t::$m(self, oth.deref()) + } + } + + impl<'a, 'b> $t<&'b BigNumRef> for &'a BigNum { + type Output = BigNum; + + fn $m(self, oth: &BigNumRef) -> BigNum { + $t::$m(self.deref(), oth) + } + } + + impl<'a, 'b> $t<&'b BigNum> for &'a BigNum { + type Output = BigNum; + + fn $m(self, oth: &BigNum) -> BigNum { + $t::$m(self.deref(), oth.deref()) + } + } + } +} + +impl<'a, 'b> Add<&'b BigNumRef> for &'a BigNumRef { + type Output = BigNum; + + fn add(self, oth: &BigNumRef) -> BigNum { + let mut r = BigNum::new().unwrap(); + r.checked_add(self, oth).unwrap(); + r + } +} + +delegate!(Add, add); + +impl<'a, 'b> Sub<&'b BigNumRef> for &'a BigNumRef { + type Output = BigNum; + + fn sub(self, oth: &BigNumRef) -> BigNum { + let mut r = BigNum::new().unwrap(); + r.checked_sub(self, oth).unwrap(); + r + } +} + +delegate!(Sub, sub); + +impl<'a, 'b> Mul<&'b BigNumRef> for &'a BigNumRef { + type Output = BigNum; + + fn mul(self, oth: &BigNumRef) -> BigNum { + let mut ctx = BigNumContext::new().unwrap(); + let mut r = BigNum::new().unwrap(); + r.checked_mul(self, oth, &mut ctx).unwrap(); + r + } +} + +delegate!(Mul, mul); + +impl<'a, 'b> Div<&'b BigNumRef> for &'a BigNumRef { + type Output = BigNum; + + fn div(self, oth: &'b BigNumRef) -> BigNum { + let mut ctx = BigNumContext::new().unwrap(); + let mut r = BigNum::new().unwrap(); + r.checked_div(self, oth, &mut ctx).unwrap(); + r + } +} + +delegate!(Div, div); + +impl<'a, 'b> Rem<&'b BigNumRef> for &'a BigNumRef { + type Output = BigNum; + + fn rem(self, oth: &'b BigNumRef) -> BigNum { + let mut ctx = BigNumContext::new().unwrap(); + let mut r = BigNum::new().unwrap(); + r.checked_rem(self, oth, &mut ctx).unwrap(); + r + } +} + +delegate!(Rem, rem); + +impl<'a> Shl for &'a BigNumRef { + type Output = BigNum; + + fn shl(self, n: i32) -> BigNum { + let mut r = BigNum::new().unwrap(); + r.lshift(self, n).unwrap(); + r + } +} + +impl<'a> Shl for &'a BigNum { + type Output = BigNum; + + fn shl(self, n: i32) -> BigNum { + self.deref().shl(n) + } +} + +impl<'a> Shr for &'a BigNumRef { + type Output = BigNum; + + fn shr(self, n: i32) -> BigNum { + let mut r = BigNum::new().unwrap(); + r.rshift(self, n).unwrap(); + r + } +} + +impl<'a> Shr for &'a BigNum { + type Output = BigNum; + + fn shr(self, n: i32) -> BigNum { + self.deref().shr(n) + } +} + +impl<'a> Neg for &'a BigNumRef { + type Output = BigNum; + + fn neg(self) -> BigNum { + self.to_owned().unwrap().neg() + } +} + +impl<'a> Neg for &'a BigNum { + type Output = BigNum; + + fn neg(self) -> BigNum { + self.deref().neg() + } +} + +impl Neg for BigNum { + type Output = BigNum; + + fn neg(mut self) -> BigNum { + let negative = self.is_negative(); + self.set_negative(!negative); + self + } +} + +#[cfg(test)] +mod tests { + use bn::{BigNum, BigNumContext}; + + #[test] + fn test_to_from_slice() { + let v0 = BigNum::from_u32(10203004).unwrap(); + let vec = v0.to_vec(); + let v1 = BigNum::from_slice(&vec).unwrap(); + + assert!(v0 == v1); + } + + #[test] + fn test_negation() { + let a = BigNum::from_u32(909829283).unwrap(); + + assert!(!a.is_negative()); + assert!((-a).is_negative()); + } + + #[test] + fn test_shift() { + let a = BigNum::from_u32(909829283).unwrap(); + use std::ops::{Shl, Shr}; + + assert!(a == a.shl(1).shr(1)); + } + + #[test] + fn test_rand_range() { + let range = BigNum::from_u32(909829283).unwrap(); + let mut result = BigNum::from_dec_str(&range.to_dec_str().unwrap()).unwrap(); + range.rand_range(&mut result).unwrap(); + assert!(result >= BigNum::from_u32(0).unwrap() && result < range); + } + + #[test] + fn test_pseudo_rand_range() { + let range = BigNum::from_u32(909829283).unwrap(); + let mut result = BigNum::from_dec_str(&range.to_dec_str().unwrap()).unwrap(); + range.pseudo_rand_range(&mut result).unwrap(); + assert!(result >= BigNum::from_u32(0).unwrap() && result < range); + } + + #[test] + fn test_prime_numbers() { + let a = BigNum::from_u32(19029017).unwrap(); + let mut p = BigNum::new().unwrap(); + p.generate_prime(128, true, None, Some(&a)).unwrap(); + + let mut ctx = BigNumContext::new().unwrap(); + assert!(p.is_prime(100, &mut ctx).unwrap()); + assert!(p.is_prime_fasttest(100, &mut ctx, true).unwrap()); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/cms.rs cargo-0.26.0/vendor/openssl-0.10.6/src/cms.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/cms.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/cms.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,83 @@ +//! SMIME implementation using CMS +//! +//! CMS (PKCS#7) is an encyption standard. It allows signing and ecrypting data using +//! X.509 certificates. The OpenSSL implementation of CMS is used in email encryption +//! generated from a `Vec` of bytes. This `Vec` follows the smime protocol standards. +//! Data accepted by this module will be smime type `enveloped-data`. + +use ffi; +use foreign_types::{ForeignType, ForeignTypeRef}; +use std::ptr; + +use {cvt, cvt_p}; +use bio::{MemBio, MemBioSlice}; +use error::ErrorStack; +use pkey::{HasPrivate, PKeyRef}; +use x509::X509; + +foreign_type_and_impl_send_sync! { + type CType = ffi::CMS_ContentInfo; + fn drop = ffi::CMS_ContentInfo_free; + + /// High level CMS wrapper + /// + /// CMS supports nesting various types of data, including signatures, certificates, + /// encrypted data, smime messages (encrypted email), and data digest. The ContentInfo + /// content type is the encapsulation of all those content types. [`RFC 5652`] describes + /// CMS and OpenSSL follows this RFC's implmentation. + /// + /// [`RFC 5652`]: https://tools.ietf.org/html/rfc5652#page-6 + pub struct CmsContentInfo; + /// Reference to [`CMSContentInfo`] + /// + /// [`CMSContentInfo`]:struct.CmsContentInfo.html + pub struct CmsContentInfoRef; +} + +impl CmsContentInfoRef { + /// Given the sender's private key, `pkey` and the recipient's certificiate, `cert`, + /// decrypt the data in `self`. + /// + /// OpenSSL documentation at [`CMS_decrypt`] + /// + /// [`CMS_decrypt`]: https://www.openssl.org/docs/man1.1.0/crypto/CMS_decrypt.html + pub fn decrypt(&self, pkey: &PKeyRef, cert: &X509) -> Result, ErrorStack> + where + T: HasPrivate, + { + unsafe { + let pkey = pkey.as_ptr(); + let cert = cert.as_ptr(); + let out = MemBio::new()?; + let flags: u32 = 0; + + cvt(ffi::CMS_decrypt( + self.as_ptr(), + pkey, + cert, + ptr::null_mut(), + out.as_ptr(), + flags.into(), + ))?; + + Ok(out.get_buf().to_owned()) + } + } +} + +impl CmsContentInfo { + /// Parses a smime formatted `vec` of bytes into a `CmsContentInfo`. + /// + /// OpenSSL documentation at [`SMIME_read_CMS`] + /// + /// [`SMIME_read_CMS`]: https://www.openssl.org/docs/man1.0.2/crypto/SMIME_read_CMS.html + pub fn smime_read_cms(smime: &[u8]) -> Result { + unsafe { + let bio = MemBioSlice::new(smime)?; + + let cms = cvt_p(ffi::SMIME_read_CMS(bio.as_ptr(), ptr::null_mut()))?; + + Ok(CmsContentInfo::from_ptr(cms)) + } + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/conf.rs cargo-0.26.0/vendor/openssl-0.10.6/src/conf.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/conf.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/conf.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,52 @@ +//! Interface for processing OpenSSL configuration files. +use ffi; + +use cvt_p; +use error::ErrorStack; + +pub struct ConfMethod(*mut ffi::CONF_METHOD); + +impl ConfMethod { + /// Retrieve handle to the default OpenSSL configuration file processing function. + pub fn default() -> ConfMethod { + unsafe { + ffi::init(); + // `NCONF` stands for "New Conf", as described in crypto/conf/conf_lib.c. This is + // a newer API than the "CONF classic" functions. + ConfMethod(ffi::NCONF_default()) + } + } + + /// Construct from raw pointer. + pub unsafe fn from_ptr(ptr: *mut ffi::CONF_METHOD) -> ConfMethod { + ConfMethod(ptr) + } + + /// Convert to raw pointer. + pub fn as_ptr(&self) -> *mut ffi::CONF_METHOD { + self.0 + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::CONF; + fn drop = ffi::NCONF_free; + + pub struct Conf; + pub struct ConfRef; +} + +impl Conf { + /// Create a configuration parser. + /// + /// # Examples + /// + /// ``` + /// use openssl::conf::{Conf, ConfMethod}; + /// + /// let conf = Conf::new(ConfMethod::default()); + /// ``` + pub fn new(method: ConfMethod) -> Result { + unsafe { cvt_p(ffi::NCONF_new(method.as_ptr())).map(Conf) } + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/derive.rs cargo-0.26.0/vendor/openssl-0.10.6/src/derive.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/derive.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/derive.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,123 @@ +//! Shared secret derivation. +use ffi; +use std::marker::PhantomData; +use std::ptr; +use foreign_types::ForeignTypeRef; + +use {cvt, cvt_p}; +use error::ErrorStack; +use pkey::{HasPrivate, HasPublic, PKeyRef}; + +/// A type used to derive a shared secret between two keys. +pub struct Deriver<'a>(*mut ffi::EVP_PKEY_CTX, PhantomData<&'a ()>); + +unsafe impl<'a> Sync for Deriver<'a> {} +unsafe impl<'a> Send for Deriver<'a> {} + +impl<'a> Deriver<'a> { + /// Creates a new `Deriver` using the provided private key. + /// + /// This corresponds to [`EVP_PKEY_derive_init`]. + /// + /// [`EVP_PKEY_derive_init`]: https://www.openssl.org/docs/man1.0.2/crypto/EVP_PKEY_derive_init.html + pub fn new(key: &'a PKeyRef) -> Result, ErrorStack> + where + T: HasPrivate, + { + unsafe { + cvt_p(ffi::EVP_PKEY_CTX_new(key.as_ptr(), ptr::null_mut())) + .map(|p| Deriver(p, PhantomData)) + .and_then(|ctx| cvt(ffi::EVP_PKEY_derive_init(ctx.0)).map(|_| ctx)) + } + } + + /// Sets the peer key used for secret derivation. + /// + /// This corresponds to [`EVP_PKEY_derive_set_peer`]: + /// + /// [`EVP_PKEY_derive_set_peer`]: https://www.openssl.org/docs/man1.0.2/crypto/EVP_PKEY_derive_init.html + pub fn set_peer(&mut self, key: &'a PKeyRef) -> Result<(), ErrorStack> + where + T: HasPublic, + { + unsafe { cvt(ffi::EVP_PKEY_derive_set_peer(self.0, key.as_ptr())).map(|_| ()) } + } + + /// Returns the size of the shared secret. + /// + /// It can be used to size the buffer passed to [`Deriver::derive`]. + /// + /// This corresponds to [`EVP_PKEY_derive`]. + /// + /// [`Deriver::derive`]: #method.derive + /// [`EVP_PKEY_derive`]: https://www.openssl.org/docs/man1.0.2/crypto/EVP_PKEY_derive_init.html + pub fn len(&mut self) -> Result { + unsafe { + let mut len = 0; + cvt(ffi::EVP_PKEY_derive(self.0, ptr::null_mut(), &mut len)).map(|_| len) + } + } + + /// Derives a shared secret between the two keys, writing it into the buffer. + /// + /// Returns the number of bytes written. + /// + /// This corresponds to [`EVP_PKEY_derive`]. + /// + /// [`EVP_PKEY_derive`]: https://www.openssl.org/docs/man1.0.2/crypto/EVP_PKEY_derive_init.html + pub fn derive(&mut self, buf: &mut [u8]) -> Result { + let mut len = buf.len(); + unsafe { + cvt(ffi::EVP_PKEY_derive( + self.0, + buf.as_mut_ptr() as *mut _, + &mut len, + )).map(|_| len) + } + } + + /// A convenience function which derives a shared secret and returns it in a new buffer. + /// + /// This simply wraps [`Deriver::len`] and [`Deriver::derive`]. + /// + /// [`Deriver::len`]: #method.len + /// [`Deriver::derive`]: #method.derive + pub fn derive_to_vec(&mut self) -> Result, ErrorStack> { + let len = self.len()?; + let mut buf = vec![0; len]; + let len = self.derive(&mut buf)?; + buf.truncate(len); + Ok(buf) + } +} + +#[cfg(test)] +mod test { + use super::*; + + use ec::{EcGroup, EcKey}; + use nid::Nid; + use pkey::PKey; + + #[test] + fn derive_without_peer() { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + let ec_key = EcKey::generate(&group).unwrap(); + let pkey = PKey::from_ec_key(ec_key).unwrap(); + let mut deriver = Deriver::new(&pkey).unwrap(); + deriver.derive_to_vec().unwrap_err(); + } + + #[test] + fn test_ec_key_derive() { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + let ec_key = EcKey::generate(&group).unwrap(); + let ec_key2 = EcKey::generate(&group).unwrap(); + let pkey = PKey::from_ec_key(ec_key).unwrap(); + let pkey2 = PKey::from_ec_key(ec_key2).unwrap(); + let mut deriver = Deriver::new(&pkey).unwrap(); + deriver.set_peer(&pkey2).unwrap(); + let shared = deriver.derive_to_vec().unwrap(); + assert!(!shared.is_empty()); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/dh.rs cargo-0.26.0/vendor/openssl-0.10.6/src/dh.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/dh.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/dh.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,197 @@ +use error::ErrorStack; +use ffi; +use foreign_types::{ForeignType, ForeignTypeRef}; +use std::mem; +use std::ptr; + +use {cvt, cvt_p}; +use bn::BigNum; +use pkey::{HasParams, Params}; + +generic_foreign_type_and_impl_send_sync! { + type CType = ffi::DH; + fn drop = ffi::DH_free; + + pub struct Dh; + + pub struct DhRef; +} + +impl DhRef +where + T: HasParams, +{ + to_pem! { + /// Serializes the parameters into a PEM-encoded PKCS#3 DHparameter structure. + /// + /// The output will have a header of `-----BEGIN DH PARAMETERS-----`. + /// + /// This corresponds to [`PEM_write_bio_DHparams`]. + /// + /// [`PEM_write_bio_DHparams`]: https://www.openssl.org/docs/manmaster/man3/PEM_write_bio_DHparams.html + params_to_pem, + ffi::PEM_write_bio_DHparams + } + + to_der! { + /// Serializes the parameters into a DER-encoded PKCS#3 DHparameter structure. + /// + /// This corresponds to [`i2d_DHparams`]. + /// + /// [`i2d_DHparams`]: https://www.openssl.org/docs/man1.1.0/crypto/i2d_DHparams.html + params_to_der, + ffi::i2d_DHparams + } +} + +impl Dh { + pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result, ErrorStack> { + unsafe { + let dh = Dh::from_ptr(cvt_p(ffi::DH_new())?); + cvt(compat::DH_set0_pqg( + dh.0, + p.as_ptr(), + q.as_ptr(), + g.as_ptr(), + ))?; + mem::forget((p, g, q)); + Ok(dh) + } + } + + from_pem! { + /// Deserializes a PEM-encoded PKCS#3 DHpararameters structure. + /// + /// The input should have a header of `-----BEGIN DH PARAMETERS-----`. + /// + /// This corresponds to [`PEM_read_bio_DHparams`]. + /// + /// [`PEM_read_bio_DHparams`]: https://www.openssl.org/docs/man1.0.2/crypto/PEM_read_bio_DHparams.html + params_from_pem, + Dh, + ffi::PEM_read_bio_DHparams + } + + from_der! { + /// Deserializes a DER-encoded PKCS#3 DHparameters structure. + /// + /// This corresponds to [`d2i_DHparams`]. + /// + /// [`d2i_DHparams`]: https://www.openssl.org/docs/man1.1.0/crypto/d2i_DHparams.html + params_from_der, + Dh, + ffi::d2i_DHparams + } + + /// Requires OpenSSL 1.0.2 or newer. + #[cfg(any(ossl102, ossl110))] + pub fn get_1024_160() -> Result, ErrorStack> { + unsafe { + ffi::init(); + cvt_p(ffi::DH_get_1024_160()).map(|p| Dh::from_ptr(p)) + } + } + + /// Requires OpenSSL 1.0.2 or newer. + #[cfg(any(ossl102, ossl110))] + pub fn get_2048_224() -> Result, ErrorStack> { + unsafe { + ffi::init(); + cvt_p(ffi::DH_get_2048_224()).map(|p| Dh::from_ptr(p)) + } + } + + /// Requires OpenSSL 1.0.2 or newer. + #[cfg(any(ossl102, ossl110))] + pub fn get_2048_256() -> Result, ErrorStack> { + unsafe { + ffi::init(); + cvt_p(ffi::DH_get_2048_256()).map(|p| Dh::from_ptr(p)) + } + } +} + +#[cfg(ossl110)] +mod compat { + pub use ffi::DH_set0_pqg; +} + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use ffi; + use libc::c_int; + + pub unsafe fn DH_set0_pqg( + dh: *mut ffi::DH, + p: *mut ffi::BIGNUM, + q: *mut ffi::BIGNUM, + g: *mut ffi::BIGNUM, + ) -> c_int { + (*dh).p = p; + (*dh).q = q; + (*dh).g = g; + 1 + } +} + +#[cfg(test)] +mod tests { + use dh::Dh; + use bn::BigNum; + use ssl::{SslContext, SslMethod}; + + #[test] + #[cfg(any(ossl102, ossl110))] + fn test_dh_rfc5114() { + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let dh1 = Dh::get_1024_160().unwrap(); + ctx.set_tmp_dh(&dh1).unwrap(); + let dh2 = Dh::get_2048_224().unwrap(); + ctx.set_tmp_dh(&dh2).unwrap(); + let dh3 = Dh::get_2048_256().unwrap(); + ctx.set_tmp_dh(&dh3).unwrap(); + } + + #[test] + fn test_dh() { + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let p = BigNum::from_hex_str( + "87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF\ + 4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B47\ + 58C022E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF12307F5C4FDB70C581B23F76B6\ + 3ACAE1CAA6B7902D52526735488A0EF13C6D9A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5\ + 140564251CCACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE621C3A3960A54E710\ + C375F26375D7014103A4B54330C198AF126116D2276E11715F693877FAD7EF09CADB094AE91E1A1597", + ).unwrap(); + let g = BigNum::from_hex_str( + "3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0BA12510DBC15077BE463FFF4FED\ + 4AAC0BB555BE3A6C1B0C6B47B1BC3773BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A\ + 57F2DDF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428EBC831D14348F6F2F9193B5\ + 045AF2767164E1DFC967C1FB3F2E55A4BD1BFFE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E\ + 052588B9B7D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92B52C7891428CDC67E\ + B6184B523D1DB246C32F63078490F00EF8D647D148D47954515E2327CFEF98C582664B4C0F6CC41659", + ).unwrap(); + let q = BigNum::from_hex_str( + "8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F5FBD3", + ).unwrap(); + let dh = Dh::from_params(p, g, q).unwrap(); + ctx.set_tmp_dh(&dh).unwrap(); + } + + #[test] + fn test_dh_from_pem() { + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let params = include_bytes!("../test/dhparams.pem"); + let dh = Dh::params_from_pem(params).unwrap(); + ctx.set_tmp_dh(&dh).unwrap(); + } + + #[test] + fn test_dh_from_der() { + let params = include_bytes!("../test/dhparams.pem"); + let dh = Dh::params_from_pem(params).unwrap(); + let der = dh.params_to_der().unwrap(); + Dh::params_from_der(&der).unwrap(); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/dsa.rs cargo-0.26.0/vendor/openssl-0.10.6/src/dsa.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/dsa.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/dsa.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,216 @@ +//! Digital Signatures +//! +//! DSA ensures a message originated from a known sender, and was not modified. +//! DSA uses asymetrical keys and an algorithm to output a signature of the message +//! using the private key that can be validated with the public key but not be generated +//! without the private key. + +use ffi; +use foreign_types::{ForeignType, ForeignTypeRef}; +use libc::c_int; +use std::fmt; +use std::ptr; + +use {cvt, cvt_p}; +use bn::BigNumRef; +use error::ErrorStack; +use pkey::{HasParams, HasPublic, Private, Public}; + +generic_foreign_type_and_impl_send_sync! { + type CType = ffi::DSA; + fn drop = ffi::DSA_free; + + /// Object representing DSA keys. + /// + /// A DSA object contains the parameters p, q, and g. There is a private + /// and public key. The values p, g, and q are: + /// + /// * `p`: DSA prime parameter + /// * `q`: DSA sub-prime parameter + /// * `g`: DSA base parameter + /// + /// These values are used to calculate a pair of asymetrical keys used for + /// signing. + /// + /// OpenSSL documentation at [`DSA_new`] + /// + /// [`DSA_new`]: https://www.openssl.org/docs/man1.1.0/crypto/DSA_new.html + /// + /// # Examples + /// + /// ``` + /// use openssl::dsa::Dsa; + /// use openssl::error::ErrorStack; + /// use openssl::pkey::Private; + /// + /// fn create_dsa() -> Result, ErrorStack> { + /// let sign = Dsa::generate(2048)?; + /// Ok(sign) + /// } + /// # fn main() { + /// # create_dsa(); + /// # } + /// ``` + pub struct Dsa; + /// Reference to [`Dsa`]. + /// + /// [`Dsa`]: struct.Dsa.html + pub struct DsaRef; +} + +impl DsaRef +where + T: HasPublic, +{ + to_pem! { + /// Serialies the public key into a PEM-encoded SubjectPublicKeyInfo structure. + /// + /// The output will have a header of `-----BEGIN PUBLIC KEY-----`. + /// + /// This corresponds to [`PEM_write_bio_DSA_PUBKEY`]. + /// + /// [`PEM_write_bio_DSA_PUBKEY`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_write_bio_DSA_PUBKEY.html + public_key_to_pem, + ffi::PEM_write_bio_DSA_PUBKEY + } + + to_der! { + /// Serializes the public key into a DER-encoded SubjectPublicKeyInfo structure. + /// + /// This corresponds to [`i2d_DSA_PUBKEY`]. + /// + /// [`i2d_DSA_PUBKEY`]: https://www.openssl.org/docs/man1.1.0/crypto/i2d_DSA_PUBKEY.html + public_key_to_der, + ffi::i2d_DSA_PUBKEY + } +} + +impl DsaRef +where + T: HasParams, +{ + /// Returns the maximum size of the signature output by `self` in bytes. + /// + /// OpenSSL documentation at [`DSA_size`] + /// + /// [`DSA_size`]: https://www.openssl.org/docs/man1.1.0/crypto/DSA_size.html + pub fn size(&self) -> u32 { + unsafe { ffi::DSA_size(self.as_ptr()) as u32 } + } + + /// Returns the DSA prime parameter of `self`. + pub fn p(&self) -> &BigNumRef { + unsafe { + let p = compat::pqg(self.as_ptr())[0]; + BigNumRef::from_ptr(p as *mut _) + } + } + + /// Returns the DSA sub-prime parameter of `self`. + pub fn q(&self) -> &BigNumRef { + unsafe { + let q = compat::pqg(self.as_ptr())[1]; + BigNumRef::from_ptr(q as *mut _) + } + } + + /// Returns the DSA base parameter of `self`. + pub fn g(&self) -> &BigNumRef { + unsafe { + let g = compat::pqg(self.as_ptr())[2]; + BigNumRef::from_ptr(g as *mut _) + } + } +} + +impl Dsa { + /// Generate a DSA key pair. + /// + /// Calls [`DSA_generate_parameters_ex`] to populate the `p`, `g`, and `q` values. + /// These values are used to generate the key pair with [`DSA_generate_key`]. + /// + /// The `bits` parameter coresponds to the length of the prime `p`. + /// + /// [`DSA_generate_parameters_ex`]: https://www.openssl.org/docs/man1.1.0/crypto/DSA_generate_parameters_ex.html + /// [`DSA_generate_key`]: https://www.openssl.org/docs/man1.1.0/crypto/DSA_generate_key.html + pub fn generate(bits: u32) -> Result, ErrorStack> { + ffi::init(); + unsafe { + let dsa = Dsa::from_ptr(cvt_p(ffi::DSA_new())?); + cvt(ffi::DSA_generate_parameters_ex( + dsa.0, + bits as c_int, + ptr::null(), + 0, + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + ))?; + cvt(ffi::DSA_generate_key(dsa.0))?; + Ok(dsa) + } + } +} + +impl Dsa { + from_pem! { + /// Decodes a PEM-encoded SubjectPublicKeyInfo structure containing a DSA key. + /// + /// The input should have a header of `-----BEGIN PUBLIC KEY-----`. + /// + /// This corresponds to [`PEM_read_bio_DSA_PUBKEY`]. + /// + /// [`PEM_read_bio_DSA_PUBKEY`]: https://www.openssl.org/docs/man1.0.2/crypto/PEM_read_bio_DSA_PUBKEY.html + public_key_from_pem, + Dsa, + ffi::PEM_read_bio_DSA_PUBKEY + } + + from_der! { + /// Decodes a DER-encoded SubjectPublicKeyInfo structure containing a DSA key. + /// + /// This corresponds to [`d2i_DSA_PUBKEY`]. + /// + /// [`d2i_DSA_PUBKEY`]: https://www.openssl.org/docs/man1.0.2/crypto/d2i_DSA_PUBKEY.html + public_key_from_der, + Dsa, + ffi::d2i_DSA_PUBKEY + } +} + +impl fmt::Debug for Dsa { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "DSA") + } +} + +#[cfg(ossl110)] +mod compat { + use std::ptr; + use ffi::{self, BIGNUM, DSA}; + + pub unsafe fn pqg(d: *const DSA) -> [*const BIGNUM; 3] { + let (mut p, mut q, mut g) = (ptr::null(), ptr::null(), ptr::null()); + ffi::DSA_get0_pqg(d, &mut p, &mut q, &mut g); + [p, q, g] + } +} + +#[cfg(ossl10x)] +mod compat { + use ffi::{BIGNUM, DSA}; + + pub unsafe fn pqg(d: *const DSA) -> [*const BIGNUM; 3] { + [(*d).p, (*d).q, (*d).g] + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + pub fn test_generate() { + Dsa::generate(1024).unwrap(); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/ecdsa.rs cargo-0.26.0/vendor/openssl-0.10.6/src/ecdsa.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/ecdsa.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/ecdsa.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ +//! Low level Elliptic Curve Digital Signature Algorithm (ECDSA) functions. +use ffi; +use foreign_types::{ForeignType, ForeignTypeRef}; +use libc::c_int; +use std::mem; + +use bn::{BigNum, BigNumRef}; +use {cvt, cvt_n, cvt_p}; +use ec::EcKeyRef; +use error::ErrorStack; +use pkey::{Private, Public}; + +foreign_type_and_impl_send_sync! { + type CType = ffi::ECDSA_SIG; + fn drop = ffi::ECDSA_SIG_free; + + /// A low level interface to ECDSA + /// + /// OpenSSL documentation at [`ECDSA_sign`] + /// + /// [`ECDSA_sign`]: https://www.openssl.org/docs/man1.1.0/crypto/ECDSA_sign.html + pub struct EcdsaSig; + /// Reference to [`EcdsaSig`] + /// + /// [`EcdsaSig`]: struct.EcdsaSig.html + pub struct EcdsaSigRef; +} + +impl EcdsaSig { + /// Computes a digital signature of the hash value `data` using the private EC key eckey. + /// + /// OpenSSL documentation at [`ECDSA_do_sign`] + /// + /// [`ECDSA_do_sign`]: https://www.openssl.org/docs/man1.1.0/crypto/ECDSA_do_sign.html + pub fn sign(data: &[u8], eckey: &EcKeyRef) -> Result { + unsafe { + assert!(data.len() <= c_int::max_value() as usize); + let sig = cvt_p(ffi::ECDSA_do_sign( + data.as_ptr(), + data.len() as c_int, + eckey.as_ptr(), + ))?; + Ok(EcdsaSig::from_ptr(sig as *mut _)) + } + } + + /// Returns a new `EcdsaSig` by setting the `r` and `s` values associated with a + /// ECDSA signature. + /// + /// OpenSSL documentation at [`ECDSA_SIG_set0`] + /// + /// [`ECDSA_SIG_set0`]: https://www.openssl.org/docs/man1.1.0/crypto/ECDSA_SIG_set0.html + pub fn from_private_components(r: BigNum, s: BigNum) -> Result { + unsafe { + let sig = cvt_p(ffi::ECDSA_SIG_new())?; + cvt(compat::set_numbers(sig, r.as_ptr(), s.as_ptr()))?; + mem::forget((r, s)); + Ok(EcdsaSig::from_ptr(sig as *mut _)) + } + } + + /// Verifies if the signature is a valid ECDSA signature using the given public key. + /// + /// OpenSSL documentation at [`ECDSA_do_verify`] + /// + /// [`ECDSA_do_verify`]: https://www.openssl.org/docs/man1.1.0/crypto/ECDSA_do_verify.html + pub fn verify(&self, data: &[u8], eckey: &EcKeyRef) -> Result { + unsafe { + assert!(data.len() <= c_int::max_value() as usize); + cvt_n(ffi::ECDSA_do_verify( + data.as_ptr(), + data.len() as c_int, + self.as_ptr(), + eckey.as_ptr(), + )).map(|x| x == 1) + } + } + + /// Returns internal component: `r` of a `EcdsaSig`. (See X9.62 or FIPS 186-2) + /// + /// OpenSSL documentation at [`ECDSA_SIG_get0`] + /// + /// [`ECDSA_SIG_get0`]: https://www.openssl.org/docs/man1.1.0/crypto/ECDSA_SIG_get0.html + pub fn r(&self) -> &BigNumRef { + unsafe { + let xs = compat::get_numbers(self.as_ptr()); + BigNumRef::from_ptr(xs[0] as *mut _) + } + } + + /// Returns internal components: `s` of a `EcdsaSig`. (See X9.62 or FIPS 186-2) + /// + /// OpenSSL documentation at [`ECDSA_SIG_get0`] + /// + /// [`ECDSA_SIG_get0`]: https://www.openssl.org/docs/man1.1.0/crypto/ECDSA_SIG_get0.html + pub fn s(&self) -> &BigNumRef { + unsafe { + let xs = compat::get_numbers(self.as_ptr()); + BigNumRef::from_ptr(xs[1] as *mut _) + } + } +} + +#[cfg(ossl110)] +mod compat { + use std::ptr; + + use libc::c_int; + use ffi::{self, BIGNUM, ECDSA_SIG}; + + pub unsafe fn set_numbers(sig: *mut ECDSA_SIG, r: *mut BIGNUM, s: *mut BIGNUM) -> c_int { + ffi::ECDSA_SIG_set0(sig, r, s) + } + + pub unsafe fn get_numbers(sig: *mut ECDSA_SIG) -> [*const BIGNUM; 2] { + let (mut r, mut s) = (ptr::null(), ptr::null()); + ffi::ECDSA_SIG_get0(sig, &mut r, &mut s); + [r, s] + } +} + +#[cfg(ossl10x)] +mod compat { + use libc::c_int; + use ffi::{BIGNUM, ECDSA_SIG}; + + pub unsafe fn set_numbers(sig: *mut ECDSA_SIG, r: *mut BIGNUM, s: *mut BIGNUM) -> c_int { + (*sig).r = r; + (*sig).s = s; + 1 + } + + pub unsafe fn get_numbers(sig: *mut ECDSA_SIG) -> [*const BIGNUM; 2] { + [(*sig).r, (*sig).s] + } + +} + +#[cfg(test)] +mod test { + use nid::Nid; + use ec::EcGroup; + use ec::EcKey; + use super::*; + + #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] + static CURVE_IDENTIFER: Nid = Nid::X9_62_PRIME192V1; + + #[cfg(osslconf = "OPENSSL_NO_EC2M")] + static CURVE_IDENTIFER: Nid = Nid::X9_62_C2TNB191V1; + + fn get_public_key(group: &EcGroup, x: &EcKey) -> Result, ErrorStack> { + let public_key_point = x.public_key(); + Ok(EcKey::from_public_key(group, public_key_point)?) + } + + #[test] + fn sign_and_verify() { + let group = EcGroup::from_curve_name(CURVE_IDENTIFER).unwrap(); + let private_key = EcKey::generate(&group).unwrap(); + let public_key = get_public_key(&group, &private_key).unwrap(); + + let private_key2 = EcKey::generate(&group).unwrap(); + let public_key2 = get_public_key(&group, &private_key2).unwrap(); + + let data = String::from("hello"); + let res = EcdsaSig::sign(data.as_bytes(), &private_key).unwrap(); + + // Signature can be verified using the correct data & correct public key + let verification = res.verify(data.as_bytes(), &public_key).unwrap(); + assert!(verification); + + // Signature will not be verified using the incorrect data but the correct public key + let verification2 = res.verify(String::from("hello2").as_bytes(), &public_key) + .unwrap(); + assert!(verification2 == false); + + // Signature will not be verified using the correct data but the incorrect public key + let verification3 = res.verify(data.as_bytes(), &public_key2).unwrap(); + assert!(verification3 == false); + } + + #[test] + fn check_private_components() { + let group = EcGroup::from_curve_name(CURVE_IDENTIFER).unwrap(); + let private_key = EcKey::generate(&group).unwrap(); + let public_key = get_public_key(&group, &private_key).unwrap(); + let data = String::from("hello"); + let res = EcdsaSig::sign(data.as_bytes(), &private_key).unwrap(); + + let verification = res.verify(data.as_bytes(), &public_key).unwrap(); + assert!(verification); + + let r = res.r().to_owned().unwrap(); + let s = res.s().to_owned().unwrap(); + + let res2 = EcdsaSig::from_private_components(r, s).unwrap(); + let verification2 = res2.verify(data.as_bytes(), &public_key).unwrap(); + assert!(verification2); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/ec.rs cargo-0.26.0/vendor/openssl-0.10.6/src/ec.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/ec.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/ec.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,929 @@ +//! Elliptic Curve +//! +//! Cryptology relies on the difficulty of solving mathematical problems, such as the factor +//! of large integers composed of two large prime numbers and the discrete logarithm of a +//! random eliptic curve. This module provides low-level features of the latter. +//! Elliptic Curve protocols can provide the same security with smaller keys. +//! +//! There are 2 forms of elliptic curves, `Fp` and `F2^m`. These curves use irreducible +//! trinomial or pentanomial . Being a generic interface to a wide range of algorithms, +//! the cuves are generally referenced by [`EcGroup`]. There are many built in groups +//! found in [`Nid`]. +//! +//! OpenSSL Wiki explains the fields and curves in detail at [Eliptic Curve Cryptography]. +//! +//! [`EcGroup`]: struct.EcGroup.html +//! [`Nid`]: ../nid/struct.Nid.html +//! [Eliptic Curve Cryptography]: https://wiki.openssl.org/index.php/Elliptic_Curve_Cryptography +//! +//! # Examples +//! +//! ``` +//! use openssl::ec::{EcGroup, EcPoint}; +//! use openssl::nid::Nid; +//! use openssl::error::ErrorStack; +//! fn get_ec_point() -> Result { +//! let group = EcGroup::from_curve_name(Nid::SECP224R1)?; +//! let point = EcPoint::new(&group)?; +//! Ok(point) +//! } +//! # fn main() { +//! # let _ = get_ec_point(); +//! # } +//! ``` +use ffi; +use foreign_types::{ForeignType, ForeignTypeRef}; +use std::ptr; +use libc::c_int; + +use {cvt, cvt_n, cvt_p, init}; +use bn::{BigNumContextRef, BigNumRef}; +use error::ErrorStack; +use nid::Nid; +use pkey::{HasParams, HasPrivate, HasPublic, Params, Private, Public}; + +/// Compressed or Uncompressed conversion +/// +/// Conversion from the binary value of the point on the curve is performed in one of +/// compressed, uncompressed, or hybrid conversions. The default is compressed, except +/// for binary curves. +/// +/// Further documentation is available in the [X9.62] standard. +/// +/// [X9.62]: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.202.2977&rep=rep1&type=pdf +#[derive(Copy, Clone)] +pub struct PointConversionForm(ffi::point_conversion_form_t); + +impl PointConversionForm { + /// Compressed conversion from point value. + pub const COMPRESSED: PointConversionForm = + PointConversionForm(ffi::point_conversion_form_t::POINT_CONVERSION_COMPRESSED); + + /// Uncompressed conversion from point value. + pub const UNCOMPRESSED: PointConversionForm = + PointConversionForm(ffi::point_conversion_form_t::POINT_CONVERSION_UNCOMPRESSED); + + /// Performs both compressed and uncompressed conversions. + pub const HYBRID: PointConversionForm = + PointConversionForm(ffi::point_conversion_form_t::POINT_CONVERSION_HYBRID); +} + +/// Named Curve or Explicit +/// +/// This type acts as a boolean as to whether the `EcGroup` is named or explicit. +#[derive(Copy, Clone)] +pub struct Asn1Flag(c_int); + +impl Asn1Flag { + /// Curve defined using polynomial parameters + /// + /// Most applications use a named EC_GROUP curve, however, support + /// is included to explicitly define the curve used to calculate keys + /// This information would need to be known by both endpoint to make communication + /// effective. + /// + /// OPENSSL_EC_EXPLICIT_CURVE, but that was only added in 1.1. + /// Man page documents that 0 can be used in older versions. + /// + /// OpenSSL documentation at [`EC_GROUP`] + /// + /// [`EC_GROUP`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_seed_len.html + pub const EXPLICIT_CURVE: Asn1Flag = Asn1Flag(0); + + /// Standard Curves + /// + /// Curves that make up the typical encryption use cases. The collection of curves + /// are well known but extensible. + /// + /// OpenSSL documentation at [`EC_GROUP`] + /// + /// [`EC_GROUP`]: https://www.openssl.org/docs/manmaster/man3/EC_GROUP_order_bits.html + pub const NAMED_CURVE: Asn1Flag = Asn1Flag(ffi::OPENSSL_EC_NAMED_CURVE); +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::EC_GROUP; + fn drop = ffi::EC_GROUP_free; + + /// Describes the curve + /// + /// A curve can be of the named curve type. These curves can be discovered + /// using openssl binary `openssl ecparam -list_curves`. Other operations + /// are available in the [wiki]. These named curves are available in the + /// [`Nid`] module. + /// + /// Curves can also be generated using prime field parameters or a binary field. + /// + /// Prime fields use the formula `y^2 mod p = x^3 + ax + b mod p`. Binary + /// fields use the formula `y^2 + xy = x^3 + ax^2 + b`. Named curves have + /// assured security. To prevent accidental vulnerabilities, they should + /// be prefered. + /// + /// [wiki]: https://wiki.openssl.org/index.php/Command_Line_Elliptic_Curve_Operations + /// [`Nid`]: ../nid/index.html + pub struct EcGroup; + /// Reference to [`EcGroup`] + /// + /// [`EcGroup`]: struct.EcGroup.html + pub struct EcGroupRef; +} + +impl EcGroup { + /// Returns the group of a standard named curve. + /// + /// OpenSSL documentation at [`EC_GROUP_new`]. + /// + /// [`EC_GROUP_new`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_new.html + pub fn from_curve_name(nid: Nid) -> Result { + unsafe { + init(); + cvt_p(ffi::EC_GROUP_new_by_curve_name(nid.as_raw())).map(EcGroup) + } + } +} + +impl EcGroupRef { + /// Places the components of a curve over a prime field in the provided `BigNum`s. + /// The components make up the formula `y^2 mod p = x^3 + ax + b mod p`. + /// + /// OpenSSL documentation available at [`EC_GROUP_get_curve_GFp`] + /// + /// [`EC_GROUP_get_curve_GFp`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_curve_GFp.html + pub fn components_gfp( + &self, + p: &mut BigNumRef, + a: &mut BigNumRef, + b: &mut BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EC_GROUP_get_curve_GFp( + self.as_ptr(), + p.as_ptr(), + a.as_ptr(), + b.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Places the components of a curve over a binary field in the provided `BigNum`s. + /// The components make up the formula `y^2 + xy = x^3 + ax^2 + b`. + /// + /// In this form `p` relates to the irreducible polynomial. Each bit represents + /// a term in the polynomial. It will be set to 3 `1`s or 5 `1`s depending on + /// using a trinomial or pentanomial. + /// + /// OpenSSL documentation at [`EC_GROUP_get_curve_GF2m`]. + /// + /// [`EC_GROUP_get_curve_GF2m`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_curve_GF2m.html + #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] + pub fn components_gf2m( + &self, + p: &mut BigNumRef, + a: &mut BigNumRef, + b: &mut BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EC_GROUP_get_curve_GF2m( + self.as_ptr(), + p.as_ptr(), + a.as_ptr(), + b.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Returns the degree of the curve. + /// + /// OpenSSL documentation at [`EC_GROUP_get_degree`] + /// + /// [`EC_GROUP_get_degree`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_degree.html + pub fn degree(&self) -> u32 { + unsafe { ffi::EC_GROUP_get_degree(self.as_ptr()) as u32 } + } + + /// Places the order of the curve in the provided `BigNum`. + /// + /// OpenSSL documentation at [`EC_GROUP_get_order`] + /// + /// [`EC_GROUP_get_order`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_order.html + pub fn order( + &self, + order: &mut BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EC_GROUP_get_order( + self.as_ptr(), + order.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Sets the flag determining if the group corresponds to a named curve or must be explicitly + /// parameterized. + /// + /// This defaults to `EXPLICIT_CURVE` in OpenSSL 1.0.1 and 1.0.2, but `NAMED_CURVE` in OpenSSL + /// 1.1.0. + pub fn set_asn1_flag(&mut self, flag: Asn1Flag) { + unsafe { + ffi::EC_GROUP_set_asn1_flag(self.as_ptr(), flag.0); + } + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::EC_POINT; + fn drop = ffi::EC_POINT_free; + + /// Represents a point on the curve + /// + /// OpenSSL documentation at [`EC_POINT_new`] + /// + /// [`EC_POINT_new`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_new.html + pub struct EcPoint; + /// Reference to [`EcPoint`] + /// + /// [`EcPoint`]: struct.EcPoint.html + pub struct EcPointRef; +} + +impl EcPointRef { + /// Computes `a + b`, storing the result in `self`. + /// + /// OpenSSL documentation at [`EC_POINT_add`] + /// + /// [`EC_POINT_add`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_add.html + pub fn add( + &mut self, + group: &EcGroupRef, + a: &EcPointRef, + b: &EcPointRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EC_POINT_add( + group.as_ptr(), + self.as_ptr(), + a.as_ptr(), + b.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Computes `q * m`, storing the result in `self`. + /// + /// OpenSSL documentation at [`EC_POINT_mul`] + /// + /// [`EC_POINT_mul`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_mul.html + pub fn mul( + &mut self, + group: &EcGroupRef, + q: &EcPointRef, + m: &BigNumRef, + ctx: &BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EC_POINT_mul( + group.as_ptr(), + self.as_ptr(), + ptr::null(), + q.as_ptr(), + m.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Computes `generator * n`, storing the result ing `self`. + pub fn mul_generator( + &mut self, + group: &EcGroupRef, + n: &BigNumRef, + ctx: &BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EC_POINT_mul( + group.as_ptr(), + self.as_ptr(), + n.as_ptr(), + ptr::null(), + ptr::null(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Computes `generator * n + q * m`, storing the result in `self`. + pub fn mul_full( + &mut self, + group: &EcGroupRef, + n: &BigNumRef, + q: &EcPointRef, + m: &BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EC_POINT_mul( + group.as_ptr(), + self.as_ptr(), + n.as_ptr(), + q.as_ptr(), + m.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Inverts `self`. + /// + /// OpenSSL documentation at [`EC_POINT_invert`] + /// + /// [`EC_POINT_invert`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_invert.html + pub fn invert(&mut self, group: &EcGroupRef, ctx: &BigNumContextRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EC_POINT_invert( + group.as_ptr(), + self.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Serializes the point to a binary representation. + /// + /// OpenSSL documentation at [`EC_POINT_point2oct`] + /// + /// [`EC_POINT_point2oct`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_point2oct.html + pub fn to_bytes( + &self, + group: &EcGroupRef, + form: PointConversionForm, + ctx: &mut BigNumContextRef, + ) -> Result, ErrorStack> { + unsafe { + let len = ffi::EC_POINT_point2oct( + group.as_ptr(), + self.as_ptr(), + form.0, + ptr::null_mut(), + 0, + ctx.as_ptr(), + ); + if len == 0 { + return Err(ErrorStack::get()); + } + let mut buf = vec![0; len]; + let len = ffi::EC_POINT_point2oct( + group.as_ptr(), + self.as_ptr(), + form.0, + buf.as_mut_ptr(), + len, + ctx.as_ptr(), + ); + if len == 0 { + Err(ErrorStack::get()) + } else { + Ok(buf) + } + } + } + + /// Determines if this point is equal to another. + /// + /// OpenSSL doucmentation at [`EC_POINT_cmp`] + /// + /// [`EC_POINT_cmp`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_cmp.html + pub fn eq( + &self, + group: &EcGroupRef, + other: &EcPointRef, + ctx: &mut BigNumContextRef, + ) -> Result { + unsafe { + let res = cvt_n(ffi::EC_POINT_cmp( + group.as_ptr(), + self.as_ptr(), + other.as_ptr(), + ctx.as_ptr(), + ))?; + Ok(res == 0) + } + } + + /// Place affine coordinates of a curve over a prime field in the provided + /// `x` and `y` `BigNum`s + /// + /// OpenSSL documentation at [`EC_POINT_get_affine_coordinates_GFp`] + /// + /// [`EC_POINT_get_affine_coordinates_GFp`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_get_affine_coordinates_GFp.html + pub fn affine_coordinates_gfp( + &self, + group: &EcGroupRef, + x: &mut BigNumRef, + y: &mut BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EC_POINT_get_affine_coordinates_GFp( + group.as_ptr(), + self.as_ptr(), + x.as_ptr(), + y.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } + + /// Place affine coordinates of a curve over a binary field in the provided + /// `x` and `y` `BigNum`s + /// + /// OpenSSL documentation at [`EC_POINT_get_affine_coordinates_GF2m`] + /// + /// [`EC_POINT_get_affine_coordinates_GF2m`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_get_affine_coordinates_GF2m.html + #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] + pub fn affine_coordinates_gf2m( + &self, + group: &EcGroupRef, + x: &mut BigNumRef, + y: &mut BigNumRef, + ctx: &mut BigNumContextRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EC_POINT_get_affine_coordinates_GF2m( + group.as_ptr(), + self.as_ptr(), + x.as_ptr(), + y.as_ptr(), + ctx.as_ptr(), + )).map(|_| ()) + } + } +} + +impl EcPoint { + /// Creates a new point on the specified curve. + /// + /// OpenSSL documentation at [`EC_POINT_new`] + /// + /// [`EC_POINT_new`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_new.html + pub fn new(group: &EcGroupRef) -> Result { + unsafe { cvt_p(ffi::EC_POINT_new(group.as_ptr())).map(EcPoint) } + } + + /// Creates point from a binary representation + /// + /// OpenSSL documentation at [`EC_POINT_oct2point`] + /// + /// [`EC_POINT_oct2point`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_oct2point.html + pub fn from_bytes( + group: &EcGroupRef, + buf: &[u8], + ctx: &mut BigNumContextRef, + ) -> Result { + let point = EcPoint::new(group)?; + unsafe { + cvt(ffi::EC_POINT_oct2point( + group.as_ptr(), + point.as_ptr(), + buf.as_ptr(), + buf.len(), + ctx.as_ptr(), + ))?; + } + Ok(point) + } +} + +generic_foreign_type_and_impl_send_sync! { + type CType = ffi::EC_KEY; + fn drop = ffi::EC_KEY_free; + + /// Public and optional Private key on the given curve + /// + /// OpenSSL documentation at [`EC_KEY_new`] + /// + /// [`EC_KEY_new`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_new.html + pub struct EcKey; + + /// Reference to [`EcKey`] + /// + /// [`EcKey`]: struct.EcKey.html + pub struct EcKeyRef; +} + +impl EcKeyRef +where + T: HasPrivate, +{ + private_key_to_pem! { + /// Serializes the private key to a PEM-encoded ECPrivateKey structure. + /// + /// The output will have a header of `-----BEGIN EC PRIVATE KEY-----`. + /// + /// This corresponds to [`PEM_write_bio_ECPrivateKey`]. + /// + /// [`PEM_write_bio_ECPrivateKey`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_write_bio_ECPrivateKey.html + private_key_to_pem, + /// Serializes the private key to a PEM-encoded encrypted ECPrivateKey structure. + /// + /// The output will have a header of `-----BEGIN EC PRIVATE KEY-----`. + /// + /// This corresponds to [`PEM_write_bio_ECPrivateKey`]. + /// + /// [`PEM_write_bio_ECPrivateKey`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_write_bio_ECPrivateKey.html + private_key_to_pem_passphrase, + ffi::PEM_write_bio_ECPrivateKey + } + + to_der! { + /// Serializes the private key into a DER-encoded ECPrivateKey structure. + /// + /// This corresponds to [`i2d_ECPrivateKey`]. + /// + /// [`i2d_ECPrivateKey`]: https://www.openssl.org/docs/man1.0.2/crypto/d2i_ECPrivate_key.html + private_key_to_der, + ffi::i2d_ECPrivateKey + } + + /// Return [`EcPoint`] associated with the private key + /// + /// OpenSSL documentation at [`EC_KEY_get0_private_key`] + /// + /// [`EC_KEY_get0_private_key`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_get0_private_key.html + pub fn private_key(&self) -> &BigNumRef { + unsafe { + let ptr = ffi::EC_KEY_get0_private_key(self.as_ptr()); + BigNumRef::from_ptr(ptr as *mut _) + } + } +} + +impl EcKeyRef +where + T: HasPublic, +{ + /// Returns the public key. + /// + /// OpenSSL documentation at [`EC_KEY_get0_pubic_key`] + /// + /// [`EC_KEY_get0_pubic_key`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_get0_public_key.html + pub fn public_key(&self) -> &EcPointRef { + unsafe { + let ptr = ffi::EC_KEY_get0_public_key(self.as_ptr()); + EcPointRef::from_ptr(ptr as *mut _) + } + } +} + +impl EcKeyRef +where + T: HasParams, +{ + /// Return [`EcGroup`] of the `EcKey` + /// + /// OpenSSL documentation at [`EC_KEY_get0_group`] + /// + /// [`EC_KEY_get0_group`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_get0_group.html + pub fn group(&self) -> &EcGroupRef { + unsafe { + let ptr = ffi::EC_KEY_get0_group(self.as_ptr()); + EcGroupRef::from_ptr(ptr as *mut _) + } + } + + /// Checks the key for validity. + /// + /// OpenSSL documenation at [`EC_KEY_check_key`] + /// + /// [`EC_KEY_check_key`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_check_key.html + pub fn check_key(&self) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::EC_KEY_check_key(self.as_ptr())).map(|_| ()) } + } +} + +impl ToOwned for EcKeyRef { + type Owned = EcKey; + + fn to_owned(&self) -> EcKey { + unsafe { + let r = ffi::EC_KEY_up_ref(self.as_ptr()); + assert!(r == 1); + EcKey::from_ptr(self.as_ptr()) + } + } +} + +impl EcKey { + /// Constructs an `EcKey` corresponding to a known curve. + /// + /// It will not have an associated public or private key. This kind of key is primarily useful + /// to be provided to the `set_tmp_ecdh` methods on `Ssl` and `SslContextBuilder`. + /// + /// OpenSSL documenation at [`EC_KEY_new_by_curve_name`] + /// + /// [`EC_KEY_new_by_curve_name`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_new_by_curve_name.html + pub fn from_curve_name(nid: Nid) -> Result, ErrorStack> { + unsafe { + init(); + cvt_p(ffi::EC_KEY_new_by_curve_name(nid.as_raw())).map(|p| EcKey::from_ptr(p)) + } + } + + /// Constructs an `EcKey` corresponding to a curve. + /// + /// This corresponds to [`EC_KEY_set_group`]. + /// + /// [`EC_KEY_set_group`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_new.html + pub fn from_group(group: &EcGroupRef) -> Result, ErrorStack> { + unsafe { + cvt_p(ffi::EC_KEY_new()) + .map(|p| EcKey::from_ptr(p)) + .and_then(|key| { + cvt(ffi::EC_KEY_set_group(key.as_ptr(), group.as_ptr())).map(|_| key) + }) + } + } +} + +impl EcKey { + /// Constructs an `EcKey` from the specified group with the associated `EcPoint`, public_key. + /// + /// This will only have the associated public_key. + /// + /// # Example + /// + /// ```no_run + /// use openssl::bn::BigNumContext; + /// use openssl::ec::*; + /// use openssl::nid::Nid; + /// use openssl::pkey::PKey; + /// + /// // get bytes from somewhere, i.e. this will not produce a valid key + /// let public_key: Vec = vec![]; + /// + /// // create an EcKey from the binary form of a EcPoint + /// let group = EcGroup::from_curve_name(Nid::SECP256K1).unwrap(); + /// let mut ctx = BigNumContext::new().unwrap(); + /// let point = EcPoint::from_bytes(&group, &public_key, &mut ctx).unwrap(); + /// let key = EcKey::from_public_key(&group, &point); + /// ``` + pub fn from_public_key( + group: &EcGroupRef, + public_key: &EcPointRef, + ) -> Result, ErrorStack> { + unsafe { + cvt_p(ffi::EC_KEY_new()) + .map(|p| EcKey::from_ptr(p)) + .and_then(|key| { + cvt(ffi::EC_KEY_set_group(key.as_ptr(), group.as_ptr())).map(|_| key) + }) + .and_then(|key| { + cvt(ffi::EC_KEY_set_public_key( + key.as_ptr(), + public_key.as_ptr(), + )).map(|_| key) + }) + } + } + + /// Constructs a public key from its affine coordinates. + pub fn from_public_key_affine_coordinates( + group: &EcGroupRef, + x: &BigNumRef, + y: &BigNumRef, + ) -> Result, ErrorStack> { + unsafe { + cvt_p(ffi::EC_KEY_new()) + .map(|p| EcKey::from_ptr(p)) + .and_then(|key| { + cvt(ffi::EC_KEY_set_group(key.as_ptr(), group.as_ptr())).map(|_| key) + }) + .and_then(|key| { + cvt(ffi::EC_KEY_set_public_key_affine_coordinates( + key.as_ptr(), + x.as_ptr(), + y.as_ptr(), + )).map(|_| key) + }) + } + } +} + +impl EcKey { + /// Generates a new public/private key pair on the specified curve. + pub fn generate(group: &EcGroupRef) -> Result, ErrorStack> { + unsafe { + cvt_p(ffi::EC_KEY_new()) + .map(|p| EcKey::from_ptr(p)) + .and_then(|key| { + cvt(ffi::EC_KEY_set_group(key.as_ptr(), group.as_ptr())).map(|_| key) + }) + .and_then(|key| cvt(ffi::EC_KEY_generate_key(key.as_ptr())).map(|_| key)) + } + } + + /// Constructs an public/private key pair given a curve, a private key and a public key point. + pub fn from_private_components( + group: &EcGroupRef, + private_number: &BigNumRef, + public_key: &EcPointRef, + ) -> Result, ErrorStack> { + unsafe { + cvt_p(ffi::EC_KEY_new()) + .map(|p| EcKey::from_ptr(p)) + .and_then(|key| { + cvt(ffi::EC_KEY_set_group(key.as_ptr(), group.as_ptr())).map(|_| key) + }) + .and_then(|key| { + cvt(ffi::EC_KEY_set_private_key( + key.as_ptr(), + private_number.as_ptr(), + )).map(|_| key) + }) + .and_then(|key| { + cvt(ffi::EC_KEY_set_public_key( + key.as_ptr(), + public_key.as_ptr(), + )).map(|_| key) + }) + } + } + + private_key_from_pem! { + /// Deserializes a private key from a PEM-encoded ECPrivateKey structure. + /// + /// The input should have a header of `-----BEGIN EC PRIVATE KEY-----`. + /// + /// This corresponds to `PEM_read_bio_ECPrivateKey`. + private_key_from_pem, + + /// Deserializes a private key from a PEM-encoded encrypted ECPrivateKey structure. + /// + /// The input should have a header of `-----BEGIN EC PRIVATE KEY-----`. + /// + /// This corresponds to `PEM_read_bio_ECPrivateKey`. + private_key_from_pem_passphrase, + + /// Deserializes a private key from a PEM-encoded encrypted ECPrivateKey structure. + /// + /// The callback should fill the password into the provided buffer and return its length. + /// + /// The input should have a header of `-----BEGIN EC PRIVATE KEY-----`. + /// + /// This corresponds to `PEM_read_bio_ECPrivateKey`. + private_key_from_pem_callback, + EcKey, + ffi::PEM_read_bio_ECPrivateKey + } + + from_der! { + /// Decodes a DER-encoded elliptic curve private key structure. + /// + /// This corresponds to [`d2i_ECPrivateKey`]. + /// + /// [`d2i_ECPrivateKey`]: https://www.openssl.org/docs/man1.0.2/crypto/d2i_ECPrivate_key.html + private_key_from_der, + EcKey, + ffi::d2i_ECPrivateKey + } +} + +impl Clone for EcKey { + fn clone(&self) -> EcKey { + (**self).to_owned() + } +} + +#[cfg(test)] +mod test { + use bn::{BigNum, BigNumContext}; + use nid::Nid; + use data_encoding::BASE64URL_NOPAD; + use super::*; + + #[test] + fn key_new_by_curve_name() { + EcKey::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + } + + #[test] + fn generate() { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + EcKey::generate(&group).unwrap(); + } + + #[test] + fn dup() { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + let key = EcKey::generate(&group).unwrap(); + key.clone(); + } + + #[test] + fn point_new() { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + EcPoint::new(&group).unwrap(); + } + + #[test] + fn point_bytes() { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + let key = EcKey::generate(&group).unwrap(); + let point = key.public_key(); + let mut ctx = BigNumContext::new().unwrap(); + let bytes = point + .to_bytes(&group, PointConversionForm::COMPRESSED, &mut ctx) + .unwrap(); + let point2 = EcPoint::from_bytes(&group, &bytes, &mut ctx).unwrap(); + assert!(point.eq(&group, &point2, &mut ctx).unwrap()); + } + + #[test] + fn mul_generator() { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + let key = EcKey::generate(&group).unwrap(); + let mut ctx = BigNumContext::new().unwrap(); + let mut public_key = EcPoint::new(&group).unwrap(); + public_key + .mul_generator(&group, key.private_key(), &mut ctx) + .unwrap(); + assert!(public_key.eq(&group, key.public_key(), &mut ctx).unwrap()); + } + + #[test] + fn key_from_public_key() { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + let key = EcKey::generate(&group).unwrap(); + let mut ctx = BigNumContext::new().unwrap(); + let bytes = key.public_key() + .to_bytes(&group, PointConversionForm::COMPRESSED, &mut ctx) + .unwrap(); + + drop(key); + let public_key = EcPoint::from_bytes(&group, &bytes, &mut ctx).unwrap(); + let ec_key = EcKey::from_public_key(&group, &public_key).unwrap(); + assert!(ec_key.check_key().is_ok()); + } + + #[test] + fn key_from_private_components() { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + let key = EcKey::generate(&group).unwrap(); + + let dup_key = EcKey::from_private_components(&group, key.private_key(), key.public_key()).unwrap(); + let res = dup_key.check_key().unwrap(); + + assert!(res == ()); + assert!(key.private_key() == dup_key.private_key()); + } + + #[test] + fn key_from_affine_coordinates() { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + let x = BASE64URL_NOPAD + .decode("MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4".as_bytes()) + .unwrap(); + let y = BASE64URL_NOPAD + .decode("4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM".as_bytes()) + .unwrap(); + + let xbn = BigNum::from_slice(&x).unwrap(); + let ybn = BigNum::from_slice(&y).unwrap(); + + let ec_key = EcKey::from_public_key_affine_coordinates(&group, &xbn, &ybn).unwrap(); + assert!(ec_key.check_key().is_ok()); + } + + #[test] + fn get_affine_coordinates() { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + let x = BASE64URL_NOPAD + .decode("MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4".as_bytes()) + .unwrap(); + let y = BASE64URL_NOPAD + .decode("4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM".as_bytes()) + .unwrap(); + + let xbn = BigNum::from_slice(&x).unwrap(); + let ybn = BigNum::from_slice(&y).unwrap(); + + let ec_key = EcKey::from_public_key_affine_coordinates(&group, &xbn, &ybn).unwrap(); + + let mut xbn2 = BigNum::new().unwrap(); + let mut ybn2 = BigNum::new().unwrap(); + let mut ctx = BigNumContext::new().unwrap(); + let ec_key_pk = ec_key.public_key(); + ec_key_pk + .affine_coordinates_gfp(&group, &mut xbn2, &mut ybn2, &mut ctx) + .unwrap(); + assert_eq!(xbn2, xbn); + assert_eq!(ybn2, ybn); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/error.rs cargo-0.26.0/vendor/openssl-0.10.6/src/error.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/error.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/error.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,292 @@ +//! Errors returned by OpenSSL library. +//! +//! OpenSSL errors are stored in an `ErrorStack`. Most methods in the crate +//! returns a `Result` type. +//! +//! # Examples +//! +//! ``` +//! use openssl::error::ErrorStack; +//! use openssl::bn::BigNum; +//! +//! let an_error = BigNum::from_dec_str("Cannot parse letters"); +//! match an_error { +//! Ok(_) => (), +//! Err(e) => println!("Parsing Error: {:?}", e), +//! } +//! ``` +use libc::{c_char, c_int, c_ulong}; +use std::fmt; +use std::error; +use std::ffi::CStr; +use std::io; +use std::str; +use std::ptr; +use std::borrow::Cow; + +use ffi; + +/// Collection of [`Error`]s from OpenSSL. +/// +/// [`Error`]: struct.Error.html +#[derive(Debug, Clone)] +pub struct ErrorStack(Vec); + +impl ErrorStack { + /// Returns the contents of the OpenSSL error stack. + pub fn get() -> ErrorStack { + let mut vec = vec![]; + while let Some(err) = Error::get() { + vec.push(err); + } + ErrorStack(vec) + } + + /// Pushes the errors back onto the OpenSSL error stack. + pub fn put(&self) { + for error in self.errors() { + error.put(); + } + } +} + +impl ErrorStack { + /// Returns the errors in the stack. + pub fn errors(&self) -> &[Error] { + &self.0 + } +} + +impl fmt::Display for ErrorStack { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + if self.0.is_empty() { + return fmt.write_str("OpenSSL error"); + } + + let mut first = true; + for err in &self.0 { + if !first { + fmt.write_str(", ")?; + } + write!(fmt, "{}", err)?; + first = false; + } + Ok(()) + } +} + +impl error::Error for ErrorStack { + fn description(&self) -> &str { + "An OpenSSL error stack" + } +} + +impl From for io::Error { + fn from(e: ErrorStack) -> io::Error { + io::Error::new(io::ErrorKind::Other, e) + } +} + +impl From for fmt::Error { + fn from(_: ErrorStack) -> fmt::Error { + fmt::Error + } +} + +/// An error reported from OpenSSL. +#[derive(Clone)] +pub struct Error { + code: c_ulong, + file: *const c_char, + line: c_int, + data: Option>, +} + +unsafe impl Sync for Error {} +unsafe impl Send for Error {} + +impl Error { + /// Returns the first error on the OpenSSL error stack. + pub fn get() -> Option { + unsafe { + ffi::init(); + + let mut file = ptr::null(); + let mut line = 0; + let mut data = ptr::null(); + let mut flags = 0; + match ffi::ERR_get_error_line_data(&mut file, &mut line, &mut data, &mut flags) { + 0 => None, + code => { + // The memory referenced by data is only valid until that slot is overwritten + // in the error stack, so we'll need to copy it off if it's dynamic + let data = if flags & ffi::ERR_TXT_STRING != 0 { + let bytes = CStr::from_ptr(data as *const _).to_bytes(); + let data = str::from_utf8(bytes).unwrap(); + let data = if flags & ffi::ERR_TXT_MALLOCED != 0 { + Cow::Owned(data.to_string()) + } else { + Cow::Borrowed(data) + }; + Some(data) + } else { + None + }; + Some(Error { + code, + file, + line, + data, + }) + } + } + } + } + + /// Pushes the error back onto the OpenSSL error stack. + pub fn put(&self) { + unsafe { + ffi::ERR_put_error( + ffi::ERR_GET_LIB(self.code), + ffi::ERR_GET_FUNC(self.code), + ffi::ERR_GET_REASON(self.code), + self.file, + self.line, + ); + let data = match self.data { + Some(Cow::Borrowed(data)) => Some((data.as_ptr() as *mut c_char, 0)), + Some(Cow::Owned(ref data)) => { + let ptr = ffi::CRYPTO_malloc( + (data.len() + 1) as _, + concat!(file!(), "\0").as_ptr() as _, + line!() as _, + ) as *mut c_char; + if ptr.is_null() { + None + } else { + ptr::copy_nonoverlapping(data.as_ptr(), ptr as *mut u8, data.len()); + *ptr.offset(data.len() as isize) = 0; + Some((ptr, ffi::ERR_TXT_MALLOCED)) + } + } + None => None, + }; + if let Some((ptr, flags)) = data { + ffi::ERR_set_error_data(ptr, flags | ffi::ERR_TXT_STRING); + } + } + } + + /// Returns the raw OpenSSL error code for this error. + pub fn code(&self) -> c_ulong { + self.code + } + + /// Returns the name of the library reporting the error, if available. + pub fn library(&self) -> Option<&'static str> { + unsafe { + let cstr = ffi::ERR_lib_error_string(self.code); + if cstr.is_null() { + return None; + } + let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); + Some(str::from_utf8(bytes).unwrap()) + } + } + + /// Returns the name of the function reporting the error. + pub fn function(&self) -> Option<&'static str> { + unsafe { + let cstr = ffi::ERR_func_error_string(self.code); + if cstr.is_null() { + return None; + } + let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); + Some(str::from_utf8(bytes).unwrap()) + } + } + + /// Returns the reason for the error. + pub fn reason(&self) -> Option<&'static str> { + unsafe { + let cstr = ffi::ERR_reason_error_string(self.code); + if cstr.is_null() { + return None; + } + let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); + Some(str::from_utf8(bytes).unwrap()) + } + } + + /// Returns the name of the source file which encountered the error. + pub fn file(&self) -> &'static str { + unsafe { + assert!(!self.file.is_null()); + let bytes = CStr::from_ptr(self.file as *const _).to_bytes(); + str::from_utf8(bytes).unwrap() + } + } + + /// Returns the line in the source file which encountered the error. + pub fn line(&self) -> u32 { + self.line as u32 + } + + /// Returns additional data describing the error. + pub fn data(&self) -> Option<&str> { + self.data.as_ref().map(|s| &**s) + } +} + +impl fmt::Debug for Error { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + let mut builder = fmt.debug_struct("Error"); + builder.field("code", &self.code()); + if let Some(library) = self.library() { + builder.field("library", &library); + } + if let Some(function) = self.function() { + builder.field("function", &function); + } + if let Some(reason) = self.reason() { + builder.field("reason", &reason); + } + builder.field("file", &self.file()); + builder.field("line", &self.line()); + if let Some(data) = self.data() { + builder.field("data", &data); + } + builder.finish() + } +} + +impl fmt::Display for Error { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "error:{:08X}", self.code())?; + match self.library() { + Some(l) => write!(fmt, ":{}", l)?, + None => write!(fmt, ":lib({})", ffi::ERR_GET_LIB(self.code()))?, + } + match self.function() { + Some(f) => write!(fmt, ":{}", f)?, + None => write!(fmt, ":func({})", ffi::ERR_GET_FUNC(self.code()))?, + } + match self.reason() { + Some(r) => write!(fmt, ":{}", r)?, + None => write!(fmt, ":reason({})", ffi::ERR_GET_FUNC(self.code()))?, + } + write!( + fmt, + ":{}:{}:{}", + self.file(), + self.line(), + self.data().unwrap_or("") + ) + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + "an OpenSSL error" + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/ex_data.rs cargo-0.26.0/vendor/openssl-0.10.6/src/ex_data.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/ex_data.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/ex_data.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,26 @@ +use libc::c_int; +use std::marker::PhantomData; + +/// A slot in a type's "extra data" structure. +/// +/// It is parameterized over the type containing the extra data as well as the +/// type of the data in the slot. +pub struct Index(c_int, PhantomData<(T, U)>); + +impl Copy for Index {} + +impl Clone for Index { + fn clone(&self) -> Index { + *self + } +} + +impl Index { + pub unsafe fn from_raw(idx: c_int) -> Index { + Index(idx, PhantomData) + } + + pub fn as_raw(&self) -> c_int { + self.0 + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/fips.rs cargo-0.26.0/vendor/openssl-0.10.6/src/fips.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/fips.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/fips.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,22 @@ +//! FIPS 140-2 support. +//! +//! See [OpenSSL's documentation] for details. +//! +//! [OpenSSL's documentation]: https://www.openssl.org/docs/fips/UserGuide-2.0.pdf +use cvt; +use error::ErrorStack; +use ffi; + +/// Moves the library into or out of the FIPS 140-2 mode of operation. +/// +/// This corresponds to `FIPS_mode_set`. +pub fn enable(enabled: bool) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::FIPS_mode_set(enabled as _)).map(|_| ()) } +} + +/// Determines if the library is running in the FIPS 140-2 mode of operation. +/// +/// This corresponds to `FIPS_mode`. +pub fn enabled() -> bool { + unsafe { ffi::FIPS_mode() != 0 } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/hash.rs cargo-0.26.0/vendor/openssl-0.10.6/src/hash.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/hash.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/hash.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,405 @@ +use std::io::prelude::*; +use std::io; +use std::ops::{Deref, DerefMut}; +use std::fmt; +use ffi; + +#[cfg(ossl110)] +use ffi::{EVP_MD_CTX_free, EVP_MD_CTX_new}; +#[cfg(any(ossl101, ossl102))] +use ffi::{EVP_MD_CTX_create as EVP_MD_CTX_new, EVP_MD_CTX_destroy as EVP_MD_CTX_free}; + +use {cvt, cvt_p}; +use error::ErrorStack; + +#[derive(Copy, Clone)] +pub struct MessageDigest(*const ffi::EVP_MD); + +impl MessageDigest { + pub unsafe fn from_ptr(x: *const ffi::EVP_MD) -> Self { MessageDigest(x) } + + pub fn md5() -> MessageDigest { + unsafe { MessageDigest(ffi::EVP_md5()) } + } + + pub fn sha1() -> MessageDigest { + unsafe { MessageDigest(ffi::EVP_sha1()) } + } + + pub fn sha224() -> MessageDigest { + unsafe { MessageDigest(ffi::EVP_sha224()) } + } + + pub fn sha256() -> MessageDigest { + unsafe { MessageDigest(ffi::EVP_sha256()) } + } + + pub fn sha384() -> MessageDigest { + unsafe { MessageDigest(ffi::EVP_sha384()) } + } + + pub fn sha512() -> MessageDigest { + unsafe { MessageDigest(ffi::EVP_sha512()) } + } + + pub fn ripemd160() -> MessageDigest { + unsafe { MessageDigest(ffi::EVP_ripemd160()) } + } + + pub fn as_ptr(&self) -> *const ffi::EVP_MD { + self.0 + } + + /// The size of the digest in bytes + pub fn size(&self) -> usize { + unsafe { ffi::EVP_MD_size(self.0) as usize } + } +} + +unsafe impl Sync for MessageDigest {} +unsafe impl Send for MessageDigest {} + +#[derive(PartialEq, Copy, Clone)] +enum State { + Reset, + Updated, + Finalized, +} + +use self::State::*; + +/// Provides message digest (hash) computation. +/// +/// # Examples +/// +/// Calculate a hash in one go: +/// +/// ``` +/// use openssl::hash::{hash, MessageDigest}; +/// +/// let data = b"\x42\xF4\x97\xE0"; +/// let spec = b"\x7c\x43\x0f\x17\x8a\xef\xdf\x14\x87\xfe\xe7\x14\x4e\x96\x41\xe2"; +/// let res = hash(MessageDigest::md5(), data).unwrap(); +/// assert_eq!(&*res, spec); +/// ``` +/// +/// Supply the input in chunks: +/// +/// ``` +/// use openssl::hash::{Hasher, MessageDigest}; +/// +/// let data = [b"\x42\xF4", b"\x97\xE0"]; +/// let spec = b"\x7c\x43\x0f\x17\x8a\xef\xdf\x14\x87\xfe\xe7\x14\x4e\x96\x41\xe2"; +/// let mut h = Hasher::new(MessageDigest::md5()).unwrap(); +/// h.update(data[0]).unwrap(); +/// h.update(data[1]).unwrap(); +/// let res = h.finish().unwrap(); +/// assert_eq!(&*res, spec); +/// ``` +/// +/// # Warning +/// +/// Don't actually use MD5 and SHA-1 hashes, they're not secure anymore. +/// +/// Don't ever hash passwords, use the functions in the `pkcs5` module or bcrypt/scrypt instead. +pub struct Hasher { + ctx: *mut ffi::EVP_MD_CTX, + md: *const ffi::EVP_MD, + type_: MessageDigest, + state: State, +} + +unsafe impl Sync for Hasher {} +unsafe impl Send for Hasher {} + +impl Hasher { + /// Creates a new `Hasher` with the specified hash type. + pub fn new(ty: MessageDigest) -> Result { + ffi::init(); + + let ctx = unsafe { cvt_p(EVP_MD_CTX_new())? }; + + let mut h = Hasher { + ctx: ctx, + md: ty.as_ptr(), + type_: ty, + state: Finalized, + }; + h.init()?; + Ok(h) + } + + fn init(&mut self) -> Result<(), ErrorStack> { + match self.state { + Reset => return Ok(()), + Updated => { + self.finish()?; + } + Finalized => (), + } + unsafe { + cvt(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _))?; + } + self.state = Reset; + Ok(()) + } + + /// Feeds data into the hasher. + pub fn update(&mut self, data: &[u8]) -> Result<(), ErrorStack> { + if self.state == Finalized { + self.init()?; + } + unsafe { + cvt(ffi::EVP_DigestUpdate( + self.ctx, + data.as_ptr() as *mut _, + data.len(), + ))?; + } + self.state = Updated; + Ok(()) + } + + /// Returns the hash of the data written and resets the hasher. + pub fn finish(&mut self) -> Result { + if self.state == Finalized { + self.init()?; + } + unsafe { + let mut len = ffi::EVP_MAX_MD_SIZE; + let mut buf = [0; ffi::EVP_MAX_MD_SIZE as usize]; + cvt(ffi::EVP_DigestFinal_ex( + self.ctx, + buf.as_mut_ptr(), + &mut len, + ))?; + self.state = Finalized; + Ok(DigestBytes { + buf: buf, + len: len as usize, + }) + } + } +} + +impl Write for Hasher { + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result { + self.update(buf)?; + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl Clone for Hasher { + fn clone(&self) -> Hasher { + let ctx = unsafe { + let ctx = EVP_MD_CTX_new(); + assert!(!ctx.is_null()); + let r = ffi::EVP_MD_CTX_copy_ex(ctx, self.ctx); + assert_eq!(r, 1); + ctx + }; + Hasher { + ctx: ctx, + md: self.md, + type_: self.type_, + state: self.state, + } + } +} + +impl Drop for Hasher { + fn drop(&mut self) { + unsafe { + if self.state != Finalized { + drop(self.finish()); + } + EVP_MD_CTX_free(self.ctx); + } + } +} + +/// The resulting bytes of a digest. +/// +/// This type derefs to a byte slice - it exists to avoid allocating memory to +/// store the digest data. +#[derive(Copy)] +pub struct DigestBytes { + buf: [u8; ffi::EVP_MAX_MD_SIZE as usize], + len: usize, +} + +impl Clone for DigestBytes { + #[inline] + fn clone(&self) -> DigestBytes { + *self + } +} + +impl Deref for DigestBytes { + type Target = [u8]; + + #[inline] + fn deref(&self) -> &[u8] { + &self.buf[..self.len] + } +} + +impl DerefMut for DigestBytes { + #[inline] + fn deref_mut(&mut self) -> &mut [u8] { + &mut self.buf[..self.len] + } +} + +impl AsRef<[u8]> for DigestBytes { + #[inline] + fn as_ref(&self) -> &[u8] { + self.deref() + } +} + +impl fmt::Debug for DigestBytes { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&**self, fmt) + } +} + +/// Computes the hash of the `data` with the hash `t`. +pub fn hash(t: MessageDigest, data: &[u8]) -> Result { + let mut h = Hasher::new(t)?; + h.update(data)?; + h.finish() +} + +#[cfg(test)] +mod tests { + use hex::{self, FromHex}; + use std::io::prelude::*; + + use super::*; + + fn hash_test(hashtype: MessageDigest, hashtest: &(&str, &str)) { + let res = hash(hashtype, &Vec::from_hex(hashtest.0).unwrap()).unwrap(); + assert_eq!(hex::encode(res), hashtest.1); + } + + fn hash_recycle_test(h: &mut Hasher, hashtest: &(&str, &str)) { + let _ = h.write_all(&Vec::from_hex(hashtest.0).unwrap()).unwrap(); + let res = h.finish().unwrap(); + assert_eq!(hex::encode(res), hashtest.1); + } + + // Test vectors from http://www.nsrl.nist.gov/testdata/ + #[allow(non_upper_case_globals)] + const md5_tests: [(&'static str, &'static str); 13] = [ + ("", "d41d8cd98f00b204e9800998ecf8427e"), + ("7F", "83acb6e67e50e31db6ed341dd2de1595"), + ("EC9C", "0b07f0d4ca797d8ac58874f887cb0b68"), + ("FEE57A", "e0d583171eb06d56198fc0ef22173907"), + ("42F497E0", "7c430f178aefdf1487fee7144e9641e2"), + ("C53B777F1C", "75ef141d64cb37ec423da2d9d440c925"), + ("89D5B576327B", "ebbaf15eb0ed784c6faa9dc32831bf33"), + ("5D4CCE781EB190", "ce175c4b08172019f05e6b5279889f2c"), + ("81901FE94932D7B9", "cd4d2f62b8cdb3a0cf968a735a239281"), + ("C9FFDEE7788EFB4EC9", "e0841a231ab698db30c6c0f3f246c014"), + ("66AC4B7EBA95E53DC10B", "a3b3cea71910d9af56742aa0bb2fe329"), + ("A510CD18F7A56852EB0319", "577e216843dd11573574d3fb209b97d8"), + ( + "AAED18DBE8938C19ED734A8D", + "6f80fb775f27e0a4ce5c2f42fc72c5f1", + ), + ]; + + #[test] + fn test_md5() { + for test in md5_tests.iter() { + hash_test(MessageDigest::md5(), test); + } + } + + #[test] + fn test_md5_recycle() { + let mut h = Hasher::new(MessageDigest::md5()).unwrap(); + for test in md5_tests.iter() { + hash_recycle_test(&mut h, test); + } + } + + #[test] + fn test_finish_twice() { + let mut h = Hasher::new(MessageDigest::md5()).unwrap(); + h.write_all(&Vec::from_hex(md5_tests[6].0).unwrap()) + .unwrap(); + h.finish().unwrap(); + let res = h.finish().unwrap(); + let null = hash(MessageDigest::md5(), &[]).unwrap(); + assert_eq!(&*res, &*null); + } + + #[test] + fn test_clone() { + let i = 7; + let inp = Vec::from_hex(md5_tests[i].0).unwrap(); + assert!(inp.len() > 2); + let p = inp.len() / 2; + let h0 = Hasher::new(MessageDigest::md5()).unwrap(); + + println!("Clone a new hasher"); + let mut h1 = h0.clone(); + h1.write_all(&inp[..p]).unwrap(); + { + println!("Clone an updated hasher"); + let mut h2 = h1.clone(); + h2.write_all(&inp[p..]).unwrap(); + let res = h2.finish().unwrap(); + assert_eq!(hex::encode(res), md5_tests[i].1); + } + h1.write_all(&inp[p..]).unwrap(); + let res = h1.finish().unwrap(); + assert_eq!(hex::encode(res), md5_tests[i].1); + + println!("Clone a finished hasher"); + let mut h3 = h1.clone(); + h3.write_all(&Vec::from_hex(md5_tests[i + 1].0).unwrap()) + .unwrap(); + let res = h3.finish().unwrap(); + assert_eq!(hex::encode(res), md5_tests[i + 1].1); + } + + #[test] + fn test_sha1() { + let tests = [("616263", "a9993e364706816aba3e25717850c26c9cd0d89d")]; + + for test in tests.iter() { + hash_test(MessageDigest::sha1(), test); + } + } + + #[test] + fn test_sha256() { + let tests = [ + ( + "616263", + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + ), + ]; + + for test in tests.iter() { + hash_test(MessageDigest::sha256(), test); + } + } + + #[test] + fn test_ripemd160() { + let tests = [("616263", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc")]; + + for test in tests.iter() { + hash_test(MessageDigest::ripemd160(), test); + } + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/lib.rs cargo-0.26.0/vendor/openssl-0.10.6/src/lib.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,87 @@ +#![doc(html_root_url = "https://docs.rs/openssl/0.10")] + +#[macro_use] +extern crate bitflags; +#[macro_use] +extern crate foreign_types; +#[macro_use] +extern crate lazy_static; +extern crate libc; +extern crate openssl_sys as ffi; + +#[cfg(test)] +extern crate data_encoding; +#[cfg(test)] +extern crate hex; +#[cfg(test)] +extern crate tempdir; + +#[doc(inline)] +pub use ffi::init; + +use libc::c_int; + +use error::ErrorStack; + +#[macro_use] +mod macros; + +mod bio; +#[macro_use] +mod util; +pub mod aes; +pub mod asn1; +pub mod bn; +#[cfg(not(libressl))] +pub mod cms; +pub mod conf; +pub mod derive; +pub mod dh; +pub mod dsa; +pub mod ec; +pub mod ecdsa; +pub mod error; +pub mod ex_data; +#[cfg(not(libressl))] +pub mod fips; +pub mod hash; +pub mod memcmp; +pub mod nid; +pub mod ocsp; +pub mod pkcs12; +pub mod pkcs5; +pub mod pkey; +pub mod rand; +pub mod rsa; +pub mod sign; +pub mod sha; +pub mod ssl; +pub mod stack; +pub mod string; +pub mod symm; +pub mod version; +pub mod x509; + +fn cvt_p(r: *mut T) -> Result<*mut T, ErrorStack> { + if r.is_null() { + Err(ErrorStack::get()) + } else { + Ok(r) + } +} + +fn cvt(r: c_int) -> Result { + if r <= 0 { + Err(ErrorStack::get()) + } else { + Ok(r) + } +} + +fn cvt_n(r: c_int) -> Result { + if r < 0 { + Err(ErrorStack::get()) + } else { + Ok(r) + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/macros.rs cargo-0.26.0/vendor/openssl-0.10.6/src/macros.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/macros.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/macros.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,269 @@ +macro_rules! private_key_from_pem { + ($(#[$m:meta])* $n:ident, $(#[$m2:meta])* $n2:ident, $(#[$m3:meta])* $n3:ident, $t:ty, $f:path) => { + from_pem!($(#[$m])* $n, $t, $f); + + $(#[$m2])* + pub fn $n2(pem: &[u8], passphrase: &[u8]) -> Result<$t, ::error::ErrorStack> { + unsafe { + ffi::init(); + let bio = try!(::bio::MemBioSlice::new(pem)); + let passphrase = ::std::ffi::CString::new(passphrase).unwrap(); + cvt_p($f(bio.as_ptr(), + ptr::null_mut(), + None, + passphrase.as_ptr() as *const _ as *mut _)) + .map(|p| ::foreign_types::ForeignType::from_ptr(p)) + } + } + + $(#[$m3])* + pub fn $n3(pem: &[u8], callback: F) -> Result<$t, ::error::ErrorStack> + where F: FnOnce(&mut [u8]) -> Result + { + unsafe { + ffi::init(); + let mut cb = ::util::CallbackState::new(callback); + let bio = try!(::bio::MemBioSlice::new(pem)); + cvt_p($f(bio.as_ptr(), + ptr::null_mut(), + Some(::util::invoke_passwd_cb::), + &mut cb as *mut _ as *mut _)) + .map(|p| ::foreign_types::ForeignType::from_ptr(p)) + } + } + } +} + +macro_rules! private_key_to_pem { + ($(#[$m:meta])* $n:ident, $(#[$m2:meta])* $n2:ident, $f:path) => { + $(#[$m])* + pub fn $n(&self) -> Result, ::error::ErrorStack> { + unsafe { + let bio = try!(::bio::MemBio::new()); + try!(cvt($f(bio.as_ptr(), + self.as_ptr(), + ptr::null(), + ptr::null_mut(), + -1, + None, + ptr::null_mut()))); + Ok(bio.get_buf().to_owned()) + } + } + + $(#[$m2])* + pub fn $n2( + &self, + cipher: ::symm::Cipher, + passphrase: &[u8] + ) -> Result, ::error::ErrorStack> { + unsafe { + let bio = try!(::bio::MemBio::new()); + assert!(passphrase.len() <= ::libc::c_int::max_value() as usize); + try!(cvt($f(bio.as_ptr(), + self.as_ptr(), + cipher.as_ptr(), + passphrase.as_ptr() as *const _ as *mut _, + passphrase.len() as ::libc::c_int, + None, + ptr::null_mut()))); + Ok(bio.get_buf().to_owned()) + } + } + } +} + +macro_rules! to_pem { + ($(#[$m:meta])* $n:ident, $f:path) => { + $(#[$m])* + pub fn $n(&self) -> Result, ::error::ErrorStack> { + unsafe { + let bio = try!(::bio::MemBio::new()); + try!(cvt($f(bio.as_ptr(), self.as_ptr()))); + Ok(bio.get_buf().to_owned()) + } + } + } +} + +macro_rules! to_der { + ($(#[$m:meta])* $n:ident, $f:path) => { + $(#[$m])* + pub fn $n(&self) -> Result, ::error::ErrorStack> { + unsafe { + let len = try!(::cvt($f(::foreign_types::ForeignTypeRef::as_ptr(self), + ptr::null_mut()))); + let mut buf = vec![0; len as usize]; + try!(::cvt($f(::foreign_types::ForeignTypeRef::as_ptr(self), + &mut buf.as_mut_ptr()))); + Ok(buf) + } + } + }; +} + +macro_rules! from_der { + ($(#[$m:meta])* $n:ident, $t:ty, $f:path) => { + $(#[$m])* + pub fn $n(der: &[u8]) -> Result<$t, ::error::ErrorStack> { + unsafe { + ::ffi::init(); + let len = ::std::cmp::min(der.len(), ::libc::c_long::max_value() as usize) as ::libc::c_long; + ::cvt_p($f(::std::ptr::null_mut(), &mut der.as_ptr(), len)) + .map(|p| ::foreign_types::ForeignType::from_ptr(p)) + } + } + } +} + +macro_rules! from_pem { + ($(#[$m:meta])* $n:ident, $t:ty, $f:path) => { + $(#[$m])* + pub fn $n(pem: &[u8]) -> Result<$t, ::error::ErrorStack> { + unsafe { + ::init(); + let bio = try!(::bio::MemBioSlice::new(pem)); + cvt_p($f(bio.as_ptr(), ::std::ptr::null_mut(), None, ::std::ptr::null_mut())) + .map(|p| ::foreign_types::ForeignType::from_ptr(p)) + } + } + } +} + +macro_rules! foreign_type_and_impl_send_sync { + ( + $(#[$impl_attr:meta])* + type CType = $ctype:ty; + fn drop = $drop:expr; + $(fn clone = $clone:expr;)* + + $(#[$owned_attr:meta])* + pub struct $owned:ident; + $(#[$borrowed_attr:meta])* + pub struct $borrowed:ident; + ) + => { + foreign_type! { + $(#[$impl_attr])* + type CType = $ctype; + fn drop = $drop; + $(fn clone = $clone;)* + $(#[$owned_attr])* + pub struct $owned; + $(#[$borrowed_attr])* + pub struct $borrowed; + } + + unsafe impl Send for $owned{} + unsafe impl Send for $borrowed{} + unsafe impl Sync for $owned{} + unsafe impl Sync for $borrowed{} + }; +} + +macro_rules! generic_foreign_type_and_impl_send_sync { + ( + $(#[$impl_attr:meta])* + type CType = $ctype:ty; + fn drop = $drop:expr; + $(fn clone = $clone:expr;)* + + $(#[$owned_attr:meta])* + pub struct $owned:ident; + $(#[$borrowed_attr:meta])* + pub struct $borrowed:ident; + ) => { + $(#[$owned_attr])* + pub struct $owned(*mut $ctype, ::std::marker::PhantomData); + + $(#[$impl_attr])* + impl ::foreign_types::ForeignType for $owned { + type CType = $ctype; + type Ref = $borrowed; + + #[inline] + unsafe fn from_ptr(ptr: *mut $ctype) -> $owned { + $owned(ptr, ::std::marker::PhantomData) + } + + #[inline] + fn as_ptr(&self) -> *mut $ctype { + self.0 + } + } + + impl Drop for $owned { + #[inline] + fn drop(&mut self) { + unsafe { $drop(self.0) } + } + } + + $( + impl Clone for $owned { + #[inline] + fn clone(&self) -> $owned { + unsafe { + let handle: *mut $ctype = $clone(self.0); + ::foreign_types::ForeignType::from_ptr(handle) + } + } + } + + impl ::std::borrow::ToOwned for $borrowed { + type Owned = $owned; + #[inline] + fn to_owned(&self) -> $owned { + unsafe { + let handle: *mut $ctype = + $clone(::foreign_types::ForeignTypeRef::as_ptr(self)); + $crate::ForeignType::from_ptr(handle) + } + } + } + )* + + impl ::std::ops::Deref for $owned { + type Target = $borrowed; + + #[inline] + fn deref(&self) -> &$borrowed { + unsafe { ::foreign_types::ForeignTypeRef::from_ptr(self.0) } + } + } + + impl ::std::ops::DerefMut for $owned { + #[inline] + fn deref_mut(&mut self) -> &mut $borrowed { + unsafe { ::foreign_types::ForeignTypeRef::from_ptr_mut(self.0) } + } + } + + impl ::std::borrow::Borrow<$borrowed> for $owned { + #[inline] + fn borrow(&self) -> &$borrowed { + &**self + } + } + + impl ::std::convert::AsRef<$borrowed> for $owned { + #[inline] + fn as_ref(&self) -> &$borrowed { + &**self + } + } + + $(#[$borrowed_attr])* + pub struct $borrowed(::foreign_types::Opaque, ::std::marker::PhantomData); + + $(#[$impl_attr])* + impl ::foreign_types::ForeignTypeRef for $borrowed { + type CType = $ctype; + } + + unsafe impl Send for $owned{} + unsafe impl Send for $borrowed{} + unsafe impl Sync for $owned{} + unsafe impl Sync for $borrowed{} + }; +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/memcmp.rs cargo-0.26.0/vendor/openssl-0.10.6/src/memcmp.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/memcmp.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/memcmp.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,92 @@ +//! Utilities to safely compare cryptographic values. +//! +//! Extra care must be taken when comparing values in +//! cryptographic code. If done incorrectly, it can lead +//! to a [timing attack](https://en.wikipedia.org/wiki/Timing_attack). +//! By analyzing the time taken to execute parts of a cryptographic +//! algorithm, and attacker can attempt to compromise the +//! cryptosystem. +//! +//! The utilities in this module are designed to be resistant +//! to this type of attack. +//! +//! # Examples +//! +//! To perform a constant-time comparision of two arrays of the same length but different +//! values: +//! +//! ``` +//! use openssl::memcmp::eq; +//! +//! // We want to compare `a` to `b` and `c`, without giving +//! // away through timing analysis that `c` is more similar to `a` +//! // than `b`. +//! let a = [0, 0, 0]; +//! let b = [1, 1, 1]; +//! let c = [0, 0, 1]; +//! +//! // These statements will execute in the same amount of time. +//! assert!(!eq(&a, &b)); +//! assert!(!eq(&a, &c)); +//! ``` +use libc::size_t; +use ffi; + +/// Returns `true` iff `a` and `b` contain the same bytes. +/// +/// This operation takes an amount of time dependent on the length of the two +/// arrays given, but is independent of the contents of a and b. +/// +/// # Panics +/// +/// This function will panic the current task if `a` and `b` do not have the same +/// length. +/// +/// # Examples +/// +/// To perform a constant-time comparision of two arrays of the same length but different +/// values: +/// +/// ``` +/// use openssl::memcmp::eq; +/// +/// // We want to compare `a` to `b` and `c`, without giving +/// // away through timing analysis that `c` is more similar to `a` +/// // than `b`. +/// let a = [0, 0, 0]; +/// let b = [1, 1, 1]; +/// let c = [0, 0, 1]; +/// +/// // These statements will execute in the same amount of time. +/// assert!(!eq(&a, &b)); +/// assert!(!eq(&a, &c)); +/// ``` +pub fn eq(a: &[u8], b: &[u8]) -> bool { + assert!(a.len() == b.len()); + let ret = unsafe { + ffi::CRYPTO_memcmp( + a.as_ptr() as *const _, + b.as_ptr() as *const _, + a.len() as size_t, + ) + }; + ret == 0 +} + +#[cfg(test)] +mod tests { + use super::eq; + + #[test] + fn test_eq() { + assert!(eq(&[], &[])); + assert!(eq(&[1], &[1])); + assert!(!eq(&[1, 2, 3], &[1, 2, 4])); + } + + #[test] + #[should_panic] + fn test_diff_lens() { + eq(&[], &[1]); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/nid.rs cargo-0.26.0/vendor/openssl-0.10.6/src/nid.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/nid.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/nid.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,993 @@ +//! A collection of numerical identifiers for OpenSSL objects. +use ffi; +use libc::c_int; + +/// A numerical identifier for an OpenSSL object. +/// +/// Objects in OpenSSL can have a short name, a long name, and +/// a numerical identifier (NID). For convenience, objects +/// are usually represented in source code using these numeric +/// identifiers. +/// +/// Users should generally not need to create new `Nid`s. +/// +/// # Examples +/// +/// To view the integer representation of a `Nid`: +/// +/// ``` +/// use openssl::nid::Nid; +/// +/// assert!(Nid::AES_256_GCM.as_raw() == 901); +/// ``` +/// +/// # External Documentation +/// +/// The following documentation provides context about `Nid`s and their usage +/// in OpenSSL. +/// +/// - [Obj_nid2obj](https://www.openssl.org/docs/man1.1.0/crypto/OBJ_create.html) +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub struct Nid(c_int); + +#[allow(non_snake_case)] +impl Nid { + /// Create a `Nid` from an integer representation. + pub fn from_raw(raw: c_int) -> Nid { + Nid(raw) + } + + /// Return the integer representation of a `Nid`. + pub fn as_raw(&self) -> c_int { + self.0 + } + + pub const UNDEF: Nid = Nid(ffi::NID_undef); + pub const ITU_T: Nid = Nid(ffi::NID_itu_t); + pub const CCITT: Nid = Nid(ffi::NID_ccitt); + pub const ISO: Nid = Nid(ffi::NID_iso); + pub const JOINT_ISO_ITU_T: Nid = Nid(ffi::NID_joint_iso_itu_t); + pub const JOINT_ISO_CCITT: Nid = Nid(ffi::NID_joint_iso_ccitt); + pub const MEMBER_BODY: Nid = Nid(ffi::NID_member_body); + pub const IDENTIFIED_ORGANIZATION: Nid = Nid(ffi::NID_identified_organization); + pub const HMAC_MD5: Nid = Nid(ffi::NID_hmac_md5); + pub const HMAC_SHA1: Nid = Nid(ffi::NID_hmac_sha1); + pub const CERTICOM_ARC: Nid = Nid(ffi::NID_certicom_arc); + pub const INTERNATIONAL_ORGANIZATIONS: Nid = Nid(ffi::NID_international_organizations); + pub const WAP: Nid = Nid(ffi::NID_wap); + pub const WAP_WSG: Nid = Nid(ffi::NID_wap_wsg); + pub const SELECTED_ATTRIBUTE_TYPES: Nid = Nid(ffi::NID_selected_attribute_types); + pub const CLEARANCE: Nid = Nid(ffi::NID_clearance); + pub const ISO_US: Nid = Nid(ffi::NID_ISO_US); + pub const X9_57: Nid = Nid(ffi::NID_X9_57); + pub const X9CM: Nid = Nid(ffi::NID_X9cm); + pub const DSA: Nid = Nid(ffi::NID_dsa); + pub const DSAWITHSHA1: Nid = Nid(ffi::NID_dsaWithSHA1); + pub const ANSI_X9_62: Nid = Nid(ffi::NID_ansi_X9_62); + pub const X9_62_PRIME_FIELD: Nid = Nid(ffi::NID_X9_62_prime_field); + pub const X9_62_CHARACTERISTIC_TWO_FIELD: Nid = Nid(ffi::NID_X9_62_characteristic_two_field); + pub const X9_62_ID_CHARACTERISTIC_TWO_BASIS: Nid = + Nid(ffi::NID_X9_62_id_characteristic_two_basis); + pub const X9_62_ONBASIS: Nid = Nid(ffi::NID_X9_62_onBasis); + pub const X9_62_TPBASIS: Nid = Nid(ffi::NID_X9_62_tpBasis); + pub const X9_62_PPBASIS: Nid = Nid(ffi::NID_X9_62_ppBasis); + pub const X9_62_ID_ECPUBLICKEY: Nid = Nid(ffi::NID_X9_62_id_ecPublicKey); + pub const X9_62_C2PNB163V1: Nid = Nid(ffi::NID_X9_62_c2pnb163v1); + pub const X9_62_C2PNB163V2: Nid = Nid(ffi::NID_X9_62_c2pnb163v2); + pub const X9_62_C2PNB163V3: Nid = Nid(ffi::NID_X9_62_c2pnb163v3); + pub const X9_62_C2PNB176V1: Nid = Nid(ffi::NID_X9_62_c2pnb176v1); + pub const X9_62_C2TNB191V1: Nid = Nid(ffi::NID_X9_62_c2tnb191v1); + pub const X9_62_C2TNB191V2: Nid = Nid(ffi::NID_X9_62_c2tnb191v2); + pub const X9_62_C2TNB191V3: Nid = Nid(ffi::NID_X9_62_c2tnb191v3); + pub const X9_62_C2ONB191V4: Nid = Nid(ffi::NID_X9_62_c2onb191v4); + pub const X9_62_C2ONB191V5: Nid = Nid(ffi::NID_X9_62_c2onb191v5); + pub const X9_62_C2PNB208W1: Nid = Nid(ffi::NID_X9_62_c2pnb208w1); + pub const X9_62_C2TNB239V1: Nid = Nid(ffi::NID_X9_62_c2tnb239v1); + pub const X9_62_C2TNB239V2: Nid = Nid(ffi::NID_X9_62_c2tnb239v2); + pub const X9_62_C2TNB239V3: Nid = Nid(ffi::NID_X9_62_c2tnb239v3); + pub const X9_62_C2ONB239V4: Nid = Nid(ffi::NID_X9_62_c2onb239v4); + pub const X9_62_C2ONB239V5: Nid = Nid(ffi::NID_X9_62_c2onb239v5); + pub const X9_62_C2PNB272W1: Nid = Nid(ffi::NID_X9_62_c2pnb272w1); + pub const X9_62_C2PNB304W1: Nid = Nid(ffi::NID_X9_62_c2pnb304w1); + pub const X9_62_C2TNB359V1: Nid = Nid(ffi::NID_X9_62_c2tnb359v1); + pub const X9_62_C2PNB368W1: Nid = Nid(ffi::NID_X9_62_c2pnb368w1); + pub const X9_62_C2TNB431R1: Nid = Nid(ffi::NID_X9_62_c2tnb431r1); + pub const X9_62_PRIME192V1: Nid = Nid(ffi::NID_X9_62_prime192v1); + pub const X9_62_PRIME192V2: Nid = Nid(ffi::NID_X9_62_prime192v2); + pub const X9_62_PRIME192V3: Nid = Nid(ffi::NID_X9_62_prime192v3); + pub const X9_62_PRIME239V1: Nid = Nid(ffi::NID_X9_62_prime239v1); + pub const X9_62_PRIME239V2: Nid = Nid(ffi::NID_X9_62_prime239v2); + pub const X9_62_PRIME239V3: Nid = Nid(ffi::NID_X9_62_prime239v3); + pub const X9_62_PRIME256V1: Nid = Nid(ffi::NID_X9_62_prime256v1); + pub const ECDSA_WITH_SHA1: Nid = Nid(ffi::NID_ecdsa_with_SHA1); + pub const ECDSA_WITH_RECOMMENDED: Nid = Nid(ffi::NID_ecdsa_with_Recommended); + pub const ECDSA_WITH_SPECIFIED: Nid = Nid(ffi::NID_ecdsa_with_Specified); + pub const ECDSA_WITH_SHA224: Nid = Nid(ffi::NID_ecdsa_with_SHA224); + pub const ECDSA_WITH_SHA256: Nid = Nid(ffi::NID_ecdsa_with_SHA256); + pub const ECDSA_WITH_SHA384: Nid = Nid(ffi::NID_ecdsa_with_SHA384); + pub const ECDSA_WITH_SHA512: Nid = Nid(ffi::NID_ecdsa_with_SHA512); + pub const SECP112R1: Nid = Nid(ffi::NID_secp112r1); + pub const SECP112R2: Nid = Nid(ffi::NID_secp112r2); + pub const SECP128R1: Nid = Nid(ffi::NID_secp128r1); + pub const SECP128R2: Nid = Nid(ffi::NID_secp128r2); + pub const SECP160K1: Nid = Nid(ffi::NID_secp160k1); + pub const SECP160R1: Nid = Nid(ffi::NID_secp160r1); + pub const SECP160R2: Nid = Nid(ffi::NID_secp160r2); + pub const SECP192K1: Nid = Nid(ffi::NID_secp192k1); + pub const SECP224K1: Nid = Nid(ffi::NID_secp224k1); + pub const SECP224R1: Nid = Nid(ffi::NID_secp224r1); + pub const SECP256K1: Nid = Nid(ffi::NID_secp256k1); + pub const SECP384R1: Nid = Nid(ffi::NID_secp384r1); + pub const SECP521R1: Nid = Nid(ffi::NID_secp521r1); + pub const SECT113R1: Nid = Nid(ffi::NID_sect113r1); + pub const SECT113R2: Nid = Nid(ffi::NID_sect113r2); + pub const SECT131R1: Nid = Nid(ffi::NID_sect131r1); + pub const SECT131R2: Nid = Nid(ffi::NID_sect131r2); + pub const SECT163K1: Nid = Nid(ffi::NID_sect163k1); + pub const SECT163R1: Nid = Nid(ffi::NID_sect163r1); + pub const SECT163R2: Nid = Nid(ffi::NID_sect163r2); + pub const SECT193R1: Nid = Nid(ffi::NID_sect193r1); + pub const SECT193R2: Nid = Nid(ffi::NID_sect193r2); + pub const SECT233K1: Nid = Nid(ffi::NID_sect233k1); + pub const SECT233R1: Nid = Nid(ffi::NID_sect233r1); + pub const SECT239K1: Nid = Nid(ffi::NID_sect239k1); + pub const SECT283K1: Nid = Nid(ffi::NID_sect283k1); + pub const SECT283R1: Nid = Nid(ffi::NID_sect283r1); + pub const SECT409K1: Nid = Nid(ffi::NID_sect409k1); + pub const SECT409R1: Nid = Nid(ffi::NID_sect409r1); + pub const SECT571K1: Nid = Nid(ffi::NID_sect571k1); + pub const SECT571R1: Nid = Nid(ffi::NID_sect571r1); + pub const WAP_WSG_IDM_ECID_WTLS1: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls1); + pub const WAP_WSG_IDM_ECID_WTLS3: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls3); + pub const WAP_WSG_IDM_ECID_WTLS4: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls4); + pub const WAP_WSG_IDM_ECID_WTLS5: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls5); + pub const WAP_WSG_IDM_ECID_WTLS6: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls6); + pub const WAP_WSG_IDM_ECID_WTLS7: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls7); + pub const WAP_WSG_IDM_ECID_WTLS8: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls8); + pub const WAP_WSG_IDM_ECID_WTLS9: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls9); + pub const WAP_WSG_IDM_ECID_WTLS10: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls10); + pub const WAP_WSG_IDM_ECID_WTLS11: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls11); + pub const WAP_WSG_IDM_ECID_WTLS12: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls12); + pub const CAST5_CBC: Nid = Nid(ffi::NID_cast5_cbc); + pub const CAST5_ECB: Nid = Nid(ffi::NID_cast5_ecb); + pub const CAST5_CFB64: Nid = Nid(ffi::NID_cast5_cfb64); + pub const CAST5_OFB64: Nid = Nid(ffi::NID_cast5_ofb64); + pub const PBEWITHMD5ANDCAST5_CBC: Nid = Nid(ffi::NID_pbeWithMD5AndCast5_CBC); + pub const ID_PASSWORDBASEDMAC: Nid = Nid(ffi::NID_id_PasswordBasedMAC); + pub const ID_DHBASEDMAC: Nid = Nid(ffi::NID_id_DHBasedMac); + pub const RSADSI: Nid = Nid(ffi::NID_rsadsi); + pub const PKCS: Nid = Nid(ffi::NID_pkcs); + pub const PKCS1: Nid = Nid(ffi::NID_pkcs1); + pub const RSAENCRYPTION: Nid = Nid(ffi::NID_rsaEncryption); + pub const MD2WITHRSAENCRYPTION: Nid = Nid(ffi::NID_md2WithRSAEncryption); + pub const MD4WITHRSAENCRYPTION: Nid = Nid(ffi::NID_md4WithRSAEncryption); + pub const MD5WITHRSAENCRYPTION: Nid = Nid(ffi::NID_md5WithRSAEncryption); + pub const SHA1WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha1WithRSAEncryption); + pub const RSAESOAEP: Nid = Nid(ffi::NID_rsaesOaep); + pub const MGF1: Nid = Nid(ffi::NID_mgf1); + pub const RSASSAPSS: Nid = Nid(ffi::NID_rsassaPss); + pub const SHA256WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha256WithRSAEncryption); + pub const SHA384WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha384WithRSAEncryption); + pub const SHA512WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha512WithRSAEncryption); + pub const SHA224WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha224WithRSAEncryption); + pub const PKCS3: Nid = Nid(ffi::NID_pkcs3); + pub const DHKEYAGREEMENT: Nid = Nid(ffi::NID_dhKeyAgreement); + pub const PKCS5: Nid = Nid(ffi::NID_pkcs5); + pub const PBEWITHMD2ANDDES_CBC: Nid = Nid(ffi::NID_pbeWithMD2AndDES_CBC); + pub const PBEWITHMD5ANDDES_CBC: Nid = Nid(ffi::NID_pbeWithMD5AndDES_CBC); + pub const PBEWITHMD2ANDRC2_CBC: Nid = Nid(ffi::NID_pbeWithMD2AndRC2_CBC); + pub const PBEWITHMD5ANDRC2_CBC: Nid = Nid(ffi::NID_pbeWithMD5AndRC2_CBC); + pub const PBEWITHSHA1ANDDES_CBC: Nid = Nid(ffi::NID_pbeWithSHA1AndDES_CBC); + pub const PBEWITHSHA1ANDRC2_CBC: Nid = Nid(ffi::NID_pbeWithSHA1AndRC2_CBC); + pub const ID_PBKDF2: Nid = Nid(ffi::NID_id_pbkdf2); + pub const PBES2: Nid = Nid(ffi::NID_pbes2); + pub const PBMAC1: Nid = Nid(ffi::NID_pbmac1); + pub const PKCS7: Nid = Nid(ffi::NID_pkcs7); + pub const PKCS7_DATA: Nid = Nid(ffi::NID_pkcs7_data); + pub const PKCS7_SIGNED: Nid = Nid(ffi::NID_pkcs7_signed); + pub const PKCS7_ENVELOPED: Nid = Nid(ffi::NID_pkcs7_enveloped); + pub const PKCS7_SIGNEDANDENVELOPED: Nid = Nid(ffi::NID_pkcs7_signedAndEnveloped); + pub const PKCS7_DIGEST: Nid = Nid(ffi::NID_pkcs7_digest); + pub const PKCS7_ENCRYPTED: Nid = Nid(ffi::NID_pkcs7_encrypted); + pub const PKCS9: Nid = Nid(ffi::NID_pkcs9); + pub const PKCS9_EMAILADDRESS: Nid = Nid(ffi::NID_pkcs9_emailAddress); + pub const PKCS9_UNSTRUCTUREDNAME: Nid = Nid(ffi::NID_pkcs9_unstructuredName); + pub const PKCS9_CONTENTTYPE: Nid = Nid(ffi::NID_pkcs9_contentType); + pub const PKCS9_MESSAGEDIGEST: Nid = Nid(ffi::NID_pkcs9_messageDigest); + pub const PKCS9_SIGNINGTIME: Nid = Nid(ffi::NID_pkcs9_signingTime); + pub const PKCS9_COUNTERSIGNATURE: Nid = Nid(ffi::NID_pkcs9_countersignature); + pub const PKCS9_CHALLENGEPASSWORD: Nid = Nid(ffi::NID_pkcs9_challengePassword); + pub const PKCS9_UNSTRUCTUREDADDRESS: Nid = Nid(ffi::NID_pkcs9_unstructuredAddress); + pub const PKCS9_EXTCERTATTRIBUTES: Nid = Nid(ffi::NID_pkcs9_extCertAttributes); + pub const EXT_REQ: Nid = Nid(ffi::NID_ext_req); + pub const SMIMECAPABILITIES: Nid = Nid(ffi::NID_SMIMECapabilities); + pub const SMIME: Nid = Nid(ffi::NID_SMIME); + pub const ID_SMIME_MOD: Nid = Nid(ffi::NID_id_smime_mod); + pub const ID_SMIME_CT: Nid = Nid(ffi::NID_id_smime_ct); + pub const ID_SMIME_AA: Nid = Nid(ffi::NID_id_smime_aa); + pub const ID_SMIME_ALG: Nid = Nid(ffi::NID_id_smime_alg); + pub const ID_SMIME_CD: Nid = Nid(ffi::NID_id_smime_cd); + pub const ID_SMIME_SPQ: Nid = Nid(ffi::NID_id_smime_spq); + pub const ID_SMIME_CTI: Nid = Nid(ffi::NID_id_smime_cti); + pub const ID_SMIME_MOD_CMS: Nid = Nid(ffi::NID_id_smime_mod_cms); + pub const ID_SMIME_MOD_ESS: Nid = Nid(ffi::NID_id_smime_mod_ess); + pub const ID_SMIME_MOD_OID: Nid = Nid(ffi::NID_id_smime_mod_oid); + pub const ID_SMIME_MOD_MSG_V3: Nid = Nid(ffi::NID_id_smime_mod_msg_v3); + pub const ID_SMIME_MOD_ETS_ESIGNATURE_88: Nid = Nid(ffi::NID_id_smime_mod_ets_eSignature_88); + pub const ID_SMIME_MOD_ETS_ESIGNATURE_97: Nid = Nid(ffi::NID_id_smime_mod_ets_eSignature_97); + pub const ID_SMIME_MOD_ETS_ESIGPOLICY_88: Nid = Nid(ffi::NID_id_smime_mod_ets_eSigPolicy_88); + pub const ID_SMIME_MOD_ETS_ESIGPOLICY_97: Nid = Nid(ffi::NID_id_smime_mod_ets_eSigPolicy_97); + pub const ID_SMIME_CT_RECEIPT: Nid = Nid(ffi::NID_id_smime_ct_receipt); + pub const ID_SMIME_CT_AUTHDATA: Nid = Nid(ffi::NID_id_smime_ct_authData); + pub const ID_SMIME_CT_PUBLISHCERT: Nid = Nid(ffi::NID_id_smime_ct_publishCert); + pub const ID_SMIME_CT_TSTINFO: Nid = Nid(ffi::NID_id_smime_ct_TSTInfo); + pub const ID_SMIME_CT_TDTINFO: Nid = Nid(ffi::NID_id_smime_ct_TDTInfo); + pub const ID_SMIME_CT_CONTENTINFO: Nid = Nid(ffi::NID_id_smime_ct_contentInfo); + pub const ID_SMIME_CT_DVCSREQUESTDATA: Nid = Nid(ffi::NID_id_smime_ct_DVCSRequestData); + pub const ID_SMIME_CT_DVCSRESPONSEDATA: Nid = Nid(ffi::NID_id_smime_ct_DVCSResponseData); + pub const ID_SMIME_CT_COMPRESSEDDATA: Nid = Nid(ffi::NID_id_smime_ct_compressedData); + pub const ID_CT_ASCIITEXTWITHCRLF: Nid = Nid(ffi::NID_id_ct_asciiTextWithCRLF); + pub const ID_SMIME_AA_RECEIPTREQUEST: Nid = Nid(ffi::NID_id_smime_aa_receiptRequest); + pub const ID_SMIME_AA_SECURITYLABEL: Nid = Nid(ffi::NID_id_smime_aa_securityLabel); + pub const ID_SMIME_AA_MLEXPANDHISTORY: Nid = Nid(ffi::NID_id_smime_aa_mlExpandHistory); + pub const ID_SMIME_AA_CONTENTHINT: Nid = Nid(ffi::NID_id_smime_aa_contentHint); + pub const ID_SMIME_AA_MSGSIGDIGEST: Nid = Nid(ffi::NID_id_smime_aa_msgSigDigest); + pub const ID_SMIME_AA_ENCAPCONTENTTYPE: Nid = Nid(ffi::NID_id_smime_aa_encapContentType); + pub const ID_SMIME_AA_CONTENTIDENTIFIER: Nid = Nid(ffi::NID_id_smime_aa_contentIdentifier); + pub const ID_SMIME_AA_MACVALUE: Nid = Nid(ffi::NID_id_smime_aa_macValue); + pub const ID_SMIME_AA_EQUIVALENTLABELS: Nid = Nid(ffi::NID_id_smime_aa_equivalentLabels); + pub const ID_SMIME_AA_CONTENTREFERENCE: Nid = Nid(ffi::NID_id_smime_aa_contentReference); + pub const ID_SMIME_AA_ENCRYPKEYPREF: Nid = Nid(ffi::NID_id_smime_aa_encrypKeyPref); + pub const ID_SMIME_AA_SIGNINGCERTIFICATE: Nid = Nid(ffi::NID_id_smime_aa_signingCertificate); + pub const ID_SMIME_AA_SMIMEENCRYPTCERTS: Nid = Nid(ffi::NID_id_smime_aa_smimeEncryptCerts); + pub const ID_SMIME_AA_TIMESTAMPTOKEN: Nid = Nid(ffi::NID_id_smime_aa_timeStampToken); + pub const ID_SMIME_AA_ETS_SIGPOLICYID: Nid = Nid(ffi::NID_id_smime_aa_ets_sigPolicyId); + pub const ID_SMIME_AA_ETS_COMMITMENTTYPE: Nid = Nid(ffi::NID_id_smime_aa_ets_commitmentType); + pub const ID_SMIME_AA_ETS_SIGNERLOCATION: Nid = Nid(ffi::NID_id_smime_aa_ets_signerLocation); + pub const ID_SMIME_AA_ETS_SIGNERATTR: Nid = Nid(ffi::NID_id_smime_aa_ets_signerAttr); + pub const ID_SMIME_AA_ETS_OTHERSIGCERT: Nid = Nid(ffi::NID_id_smime_aa_ets_otherSigCert); + pub const ID_SMIME_AA_ETS_CONTENTTIMESTAMP: Nid = + Nid(ffi::NID_id_smime_aa_ets_contentTimestamp); + pub const ID_SMIME_AA_ETS_CERTIFICATEREFS: Nid = Nid(ffi::NID_id_smime_aa_ets_CertificateRefs); + pub const ID_SMIME_AA_ETS_REVOCATIONREFS: Nid = Nid(ffi::NID_id_smime_aa_ets_RevocationRefs); + pub const ID_SMIME_AA_ETS_CERTVALUES: Nid = Nid(ffi::NID_id_smime_aa_ets_certValues); + pub const ID_SMIME_AA_ETS_REVOCATIONVALUES: Nid = + Nid(ffi::NID_id_smime_aa_ets_revocationValues); + pub const ID_SMIME_AA_ETS_ESCTIMESTAMP: Nid = Nid(ffi::NID_id_smime_aa_ets_escTimeStamp); + pub const ID_SMIME_AA_ETS_CERTCRLTIMESTAMP: Nid = + Nid(ffi::NID_id_smime_aa_ets_certCRLTimestamp); + pub const ID_SMIME_AA_ETS_ARCHIVETIMESTAMP: Nid = + Nid(ffi::NID_id_smime_aa_ets_archiveTimeStamp); + pub const ID_SMIME_AA_SIGNATURETYPE: Nid = Nid(ffi::NID_id_smime_aa_signatureType); + pub const ID_SMIME_AA_DVCS_DVC: Nid = Nid(ffi::NID_id_smime_aa_dvcs_dvc); + pub const ID_SMIME_ALG_ESDHWITH3DES: Nid = Nid(ffi::NID_id_smime_alg_ESDHwith3DES); + pub const ID_SMIME_ALG_ESDHWITHRC2: Nid = Nid(ffi::NID_id_smime_alg_ESDHwithRC2); + pub const ID_SMIME_ALG_3DESWRAP: Nid = Nid(ffi::NID_id_smime_alg_3DESwrap); + pub const ID_SMIME_ALG_RC2WRAP: Nid = Nid(ffi::NID_id_smime_alg_RC2wrap); + pub const ID_SMIME_ALG_ESDH: Nid = Nid(ffi::NID_id_smime_alg_ESDH); + pub const ID_SMIME_ALG_CMS3DESWRAP: Nid = Nid(ffi::NID_id_smime_alg_CMS3DESwrap); + pub const ID_SMIME_ALG_CMSRC2WRAP: Nid = Nid(ffi::NID_id_smime_alg_CMSRC2wrap); + pub const ID_ALG_PWRI_KEK: Nid = Nid(ffi::NID_id_alg_PWRI_KEK); + pub const ID_SMIME_CD_LDAP: Nid = Nid(ffi::NID_id_smime_cd_ldap); + pub const ID_SMIME_SPQ_ETS_SQT_URI: Nid = Nid(ffi::NID_id_smime_spq_ets_sqt_uri); + pub const ID_SMIME_SPQ_ETS_SQT_UNOTICE: Nid = Nid(ffi::NID_id_smime_spq_ets_sqt_unotice); + pub const ID_SMIME_CTI_ETS_PROOFOFORIGIN: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfOrigin); + pub const ID_SMIME_CTI_ETS_PROOFOFRECEIPT: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfReceipt); + pub const ID_SMIME_CTI_ETS_PROOFOFDELIVERY: Nid = + Nid(ffi::NID_id_smime_cti_ets_proofOfDelivery); + pub const ID_SMIME_CTI_ETS_PROOFOFSENDER: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfSender); + pub const ID_SMIME_CTI_ETS_PROOFOFAPPROVAL: Nid = + Nid(ffi::NID_id_smime_cti_ets_proofOfApproval); + pub const ID_SMIME_CTI_ETS_PROOFOFCREATION: Nid = + Nid(ffi::NID_id_smime_cti_ets_proofOfCreation); + pub const FRIENDLYNAME: Nid = Nid(ffi::NID_friendlyName); + pub const LOCALKEYID: Nid = Nid(ffi::NID_localKeyID); + pub const MS_CSP_NAME: Nid = Nid(ffi::NID_ms_csp_name); + pub const LOCALKEYSET: Nid = Nid(ffi::NID_LocalKeySet); + pub const X509CERTIFICATE: Nid = Nid(ffi::NID_x509Certificate); + pub const SDSICERTIFICATE: Nid = Nid(ffi::NID_sdsiCertificate); + pub const X509CRL: Nid = Nid(ffi::NID_x509Crl); + pub const PBE_WITHSHA1AND128BITRC4: Nid = Nid(ffi::NID_pbe_WithSHA1And128BitRC4); + pub const PBE_WITHSHA1AND40BITRC4: Nid = Nid(ffi::NID_pbe_WithSHA1And40BitRC4); + pub const PBE_WITHSHA1AND3_KEY_TRIPLEDES_CBC: Nid = + Nid(ffi::NID_pbe_WithSHA1And3_Key_TripleDES_CBC); + pub const PBE_WITHSHA1AND2_KEY_TRIPLEDES_CBC: Nid = + Nid(ffi::NID_pbe_WithSHA1And2_Key_TripleDES_CBC); + pub const PBE_WITHSHA1AND128BITRC2_CBC: Nid = Nid(ffi::NID_pbe_WithSHA1And128BitRC2_CBC); + pub const PBE_WITHSHA1AND40BITRC2_CBC: Nid = Nid(ffi::NID_pbe_WithSHA1And40BitRC2_CBC); + pub const KEYBAG: Nid = Nid(ffi::NID_keyBag); + pub const PKCS8SHROUDEDKEYBAG: Nid = Nid(ffi::NID_pkcs8ShroudedKeyBag); + pub const CERTBAG: Nid = Nid(ffi::NID_certBag); + pub const CRLBAG: Nid = Nid(ffi::NID_crlBag); + pub const SECRETBAG: Nid = Nid(ffi::NID_secretBag); + pub const SAFECONTENTSBAG: Nid = Nid(ffi::NID_safeContentsBag); + pub const MD2: Nid = Nid(ffi::NID_md2); + pub const MD4: Nid = Nid(ffi::NID_md4); + pub const MD5: Nid = Nid(ffi::NID_md5); + pub const MD5_SHA1: Nid = Nid(ffi::NID_md5_sha1); + pub const HMACWITHMD5: Nid = Nid(ffi::NID_hmacWithMD5); + pub const HMACWITHSHA1: Nid = Nid(ffi::NID_hmacWithSHA1); + pub const HMACWITHSHA224: Nid = Nid(ffi::NID_hmacWithSHA224); + pub const HMACWITHSHA256: Nid = Nid(ffi::NID_hmacWithSHA256); + pub const HMACWITHSHA384: Nid = Nid(ffi::NID_hmacWithSHA384); + pub const HMACWITHSHA512: Nid = Nid(ffi::NID_hmacWithSHA512); + pub const RC2_CBC: Nid = Nid(ffi::NID_rc2_cbc); + pub const RC2_ECB: Nid = Nid(ffi::NID_rc2_ecb); + pub const RC2_CFB64: Nid = Nid(ffi::NID_rc2_cfb64); + pub const RC2_OFB64: Nid = Nid(ffi::NID_rc2_ofb64); + pub const RC2_40_CBC: Nid = Nid(ffi::NID_rc2_40_cbc); + pub const RC2_64_CBC: Nid = Nid(ffi::NID_rc2_64_cbc); + pub const RC4: Nid = Nid(ffi::NID_rc4); + pub const RC4_40: Nid = Nid(ffi::NID_rc4_40); + pub const DES_EDE3_CBC: Nid = Nid(ffi::NID_des_ede3_cbc); + pub const RC5_CBC: Nid = Nid(ffi::NID_rc5_cbc); + pub const RC5_ECB: Nid = Nid(ffi::NID_rc5_ecb); + pub const RC5_CFB64: Nid = Nid(ffi::NID_rc5_cfb64); + pub const RC5_OFB64: Nid = Nid(ffi::NID_rc5_ofb64); + pub const MS_EXT_REQ: Nid = Nid(ffi::NID_ms_ext_req); + pub const MS_CODE_IND: Nid = Nid(ffi::NID_ms_code_ind); + pub const MS_CODE_COM: Nid = Nid(ffi::NID_ms_code_com); + pub const MS_CTL_SIGN: Nid = Nid(ffi::NID_ms_ctl_sign); + pub const MS_SGC: Nid = Nid(ffi::NID_ms_sgc); + pub const MS_EFS: Nid = Nid(ffi::NID_ms_efs); + pub const MS_SMARTCARD_LOGIN: Nid = Nid(ffi::NID_ms_smartcard_login); + pub const MS_UPN: Nid = Nid(ffi::NID_ms_upn); + pub const IDEA_CBC: Nid = Nid(ffi::NID_idea_cbc); + pub const IDEA_ECB: Nid = Nid(ffi::NID_idea_ecb); + pub const IDEA_CFB64: Nid = Nid(ffi::NID_idea_cfb64); + pub const IDEA_OFB64: Nid = Nid(ffi::NID_idea_ofb64); + pub const BF_CBC: Nid = Nid(ffi::NID_bf_cbc); + pub const BF_ECB: Nid = Nid(ffi::NID_bf_ecb); + pub const BF_CFB64: Nid = Nid(ffi::NID_bf_cfb64); + pub const BF_OFB64: Nid = Nid(ffi::NID_bf_ofb64); + pub const ID_PKIX: Nid = Nid(ffi::NID_id_pkix); + pub const ID_PKIX_MOD: Nid = Nid(ffi::NID_id_pkix_mod); + pub const ID_PE: Nid = Nid(ffi::NID_id_pe); + pub const ID_QT: Nid = Nid(ffi::NID_id_qt); + pub const ID_KP: Nid = Nid(ffi::NID_id_kp); + pub const ID_IT: Nid = Nid(ffi::NID_id_it); + pub const ID_PKIP: Nid = Nid(ffi::NID_id_pkip); + pub const ID_ALG: Nid = Nid(ffi::NID_id_alg); + pub const ID_CMC: Nid = Nid(ffi::NID_id_cmc); + pub const ID_ON: Nid = Nid(ffi::NID_id_on); + pub const ID_PDA: Nid = Nid(ffi::NID_id_pda); + pub const ID_ACA: Nid = Nid(ffi::NID_id_aca); + pub const ID_QCS: Nid = Nid(ffi::NID_id_qcs); + pub const ID_CCT: Nid = Nid(ffi::NID_id_cct); + pub const ID_PPL: Nid = Nid(ffi::NID_id_ppl); + pub const ID_AD: Nid = Nid(ffi::NID_id_ad); + pub const ID_PKIX1_EXPLICIT_88: Nid = Nid(ffi::NID_id_pkix1_explicit_88); + pub const ID_PKIX1_IMPLICIT_88: Nid = Nid(ffi::NID_id_pkix1_implicit_88); + pub const ID_PKIX1_EXPLICIT_93: Nid = Nid(ffi::NID_id_pkix1_explicit_93); + pub const ID_PKIX1_IMPLICIT_93: Nid = Nid(ffi::NID_id_pkix1_implicit_93); + pub const ID_MOD_CRMF: Nid = Nid(ffi::NID_id_mod_crmf); + pub const ID_MOD_CMC: Nid = Nid(ffi::NID_id_mod_cmc); + pub const ID_MOD_KEA_PROFILE_88: Nid = Nid(ffi::NID_id_mod_kea_profile_88); + pub const ID_MOD_KEA_PROFILE_93: Nid = Nid(ffi::NID_id_mod_kea_profile_93); + pub const ID_MOD_CMP: Nid = Nid(ffi::NID_id_mod_cmp); + pub const ID_MOD_QUALIFIED_CERT_88: Nid = Nid(ffi::NID_id_mod_qualified_cert_88); + pub const ID_MOD_QUALIFIED_CERT_93: Nid = Nid(ffi::NID_id_mod_qualified_cert_93); + pub const ID_MOD_ATTRIBUTE_CERT: Nid = Nid(ffi::NID_id_mod_attribute_cert); + pub const ID_MOD_TIMESTAMP_PROTOCOL: Nid = Nid(ffi::NID_id_mod_timestamp_protocol); + pub const ID_MOD_OCSP: Nid = Nid(ffi::NID_id_mod_ocsp); + pub const ID_MOD_DVCS: Nid = Nid(ffi::NID_id_mod_dvcs); + pub const ID_MOD_CMP2000: Nid = Nid(ffi::NID_id_mod_cmp2000); + pub const INFO_ACCESS: Nid = Nid(ffi::NID_info_access); + pub const BIOMETRICINFO: Nid = Nid(ffi::NID_biometricInfo); + pub const QCSTATEMENTS: Nid = Nid(ffi::NID_qcStatements); + pub const AC_AUDITENTITY: Nid = Nid(ffi::NID_ac_auditEntity); + pub const AC_TARGETING: Nid = Nid(ffi::NID_ac_targeting); + pub const AACONTROLS: Nid = Nid(ffi::NID_aaControls); + pub const SBGP_IPADDRBLOCK: Nid = Nid(ffi::NID_sbgp_ipAddrBlock); + pub const SBGP_AUTONOMOUSSYSNUM: Nid = Nid(ffi::NID_sbgp_autonomousSysNum); + pub const SBGP_ROUTERIDENTIFIER: Nid = Nid(ffi::NID_sbgp_routerIdentifier); + pub const AC_PROXYING: Nid = Nid(ffi::NID_ac_proxying); + pub const SINFO_ACCESS: Nid = Nid(ffi::NID_sinfo_access); + pub const PROXYCERTINFO: Nid = Nid(ffi::NID_proxyCertInfo); + pub const ID_QT_CPS: Nid = Nid(ffi::NID_id_qt_cps); + pub const ID_QT_UNOTICE: Nid = Nid(ffi::NID_id_qt_unotice); + pub const TEXTNOTICE: Nid = Nid(ffi::NID_textNotice); + pub const SERVER_AUTH: Nid = Nid(ffi::NID_server_auth); + pub const CLIENT_AUTH: Nid = Nid(ffi::NID_client_auth); + pub const CODE_SIGN: Nid = Nid(ffi::NID_code_sign); + pub const EMAIL_PROTECT: Nid = Nid(ffi::NID_email_protect); + pub const IPSECENDSYSTEM: Nid = Nid(ffi::NID_ipsecEndSystem); + pub const IPSECTUNNEL: Nid = Nid(ffi::NID_ipsecTunnel); + pub const IPSECUSER: Nid = Nid(ffi::NID_ipsecUser); + pub const TIME_STAMP: Nid = Nid(ffi::NID_time_stamp); + pub const OCSP_SIGN: Nid = Nid(ffi::NID_OCSP_sign); + pub const DVCS: Nid = Nid(ffi::NID_dvcs); + pub const ID_IT_CAPROTENCCERT: Nid = Nid(ffi::NID_id_it_caProtEncCert); + pub const ID_IT_SIGNKEYPAIRTYPES: Nid = Nid(ffi::NID_id_it_signKeyPairTypes); + pub const ID_IT_ENCKEYPAIRTYPES: Nid = Nid(ffi::NID_id_it_encKeyPairTypes); + pub const ID_IT_PREFERREDSYMMALG: Nid = Nid(ffi::NID_id_it_preferredSymmAlg); + pub const ID_IT_CAKEYUPDATEINFO: Nid = Nid(ffi::NID_id_it_caKeyUpdateInfo); + pub const ID_IT_CURRENTCRL: Nid = Nid(ffi::NID_id_it_currentCRL); + pub const ID_IT_UNSUPPORTEDOIDS: Nid = Nid(ffi::NID_id_it_unsupportedOIDs); + pub const ID_IT_SUBSCRIPTIONREQUEST: Nid = Nid(ffi::NID_id_it_subscriptionRequest); + pub const ID_IT_SUBSCRIPTIONRESPONSE: Nid = Nid(ffi::NID_id_it_subscriptionResponse); + pub const ID_IT_KEYPAIRPARAMREQ: Nid = Nid(ffi::NID_id_it_keyPairParamReq); + pub const ID_IT_KEYPAIRPARAMREP: Nid = Nid(ffi::NID_id_it_keyPairParamRep); + pub const ID_IT_REVPASSPHRASE: Nid = Nid(ffi::NID_id_it_revPassphrase); + pub const ID_IT_IMPLICITCONFIRM: Nid = Nid(ffi::NID_id_it_implicitConfirm); + pub const ID_IT_CONFIRMWAITTIME: Nid = Nid(ffi::NID_id_it_confirmWaitTime); + pub const ID_IT_ORIGPKIMESSAGE: Nid = Nid(ffi::NID_id_it_origPKIMessage); + pub const ID_IT_SUPPLANGTAGS: Nid = Nid(ffi::NID_id_it_suppLangTags); + pub const ID_REGCTRL: Nid = Nid(ffi::NID_id_regCtrl); + pub const ID_REGINFO: Nid = Nid(ffi::NID_id_regInfo); + pub const ID_REGCTRL_REGTOKEN: Nid = Nid(ffi::NID_id_regCtrl_regToken); + pub const ID_REGCTRL_AUTHENTICATOR: Nid = Nid(ffi::NID_id_regCtrl_authenticator); + pub const ID_REGCTRL_PKIPUBLICATIONINFO: Nid = Nid(ffi::NID_id_regCtrl_pkiPublicationInfo); + pub const ID_REGCTRL_PKIARCHIVEOPTIONS: Nid = Nid(ffi::NID_id_regCtrl_pkiArchiveOptions); + pub const ID_REGCTRL_OLDCERTID: Nid = Nid(ffi::NID_id_regCtrl_oldCertID); + pub const ID_REGCTRL_PROTOCOLENCRKEY: Nid = Nid(ffi::NID_id_regCtrl_protocolEncrKey); + pub const ID_REGINFO_UTF8PAIRS: Nid = Nid(ffi::NID_id_regInfo_utf8Pairs); + pub const ID_REGINFO_CERTREQ: Nid = Nid(ffi::NID_id_regInfo_certReq); + pub const ID_ALG_DES40: Nid = Nid(ffi::NID_id_alg_des40); + pub const ID_ALG_NOSIGNATURE: Nid = Nid(ffi::NID_id_alg_noSignature); + pub const ID_ALG_DH_SIG_HMAC_SHA1: Nid = Nid(ffi::NID_id_alg_dh_sig_hmac_sha1); + pub const ID_ALG_DH_POP: Nid = Nid(ffi::NID_id_alg_dh_pop); + pub const ID_CMC_STATUSINFO: Nid = Nid(ffi::NID_id_cmc_statusInfo); + pub const ID_CMC_IDENTIFICATION: Nid = Nid(ffi::NID_id_cmc_identification); + pub const ID_CMC_IDENTITYPROOF: Nid = Nid(ffi::NID_id_cmc_identityProof); + pub const ID_CMC_DATARETURN: Nid = Nid(ffi::NID_id_cmc_dataReturn); + pub const ID_CMC_TRANSACTIONID: Nid = Nid(ffi::NID_id_cmc_transactionId); + pub const ID_CMC_SENDERNONCE: Nid = Nid(ffi::NID_id_cmc_senderNonce); + pub const ID_CMC_RECIPIENTNONCE: Nid = Nid(ffi::NID_id_cmc_recipientNonce); + pub const ID_CMC_ADDEXTENSIONS: Nid = Nid(ffi::NID_id_cmc_addExtensions); + pub const ID_CMC_ENCRYPTEDPOP: Nid = Nid(ffi::NID_id_cmc_encryptedPOP); + pub const ID_CMC_DECRYPTEDPOP: Nid = Nid(ffi::NID_id_cmc_decryptedPOP); + pub const ID_CMC_LRAPOPWITNESS: Nid = Nid(ffi::NID_id_cmc_lraPOPWitness); + pub const ID_CMC_GETCERT: Nid = Nid(ffi::NID_id_cmc_getCert); + pub const ID_CMC_GETCRL: Nid = Nid(ffi::NID_id_cmc_getCRL); + pub const ID_CMC_REVOKEREQUEST: Nid = Nid(ffi::NID_id_cmc_revokeRequest); + pub const ID_CMC_REGINFO: Nid = Nid(ffi::NID_id_cmc_regInfo); + pub const ID_CMC_RESPONSEINFO: Nid = Nid(ffi::NID_id_cmc_responseInfo); + pub const ID_CMC_QUERYPENDING: Nid = Nid(ffi::NID_id_cmc_queryPending); + pub const ID_CMC_POPLINKRANDOM: Nid = Nid(ffi::NID_id_cmc_popLinkRandom); + pub const ID_CMC_POPLINKWITNESS: Nid = Nid(ffi::NID_id_cmc_popLinkWitness); + pub const ID_CMC_CONFIRMCERTACCEPTANCE: Nid = Nid(ffi::NID_id_cmc_confirmCertAcceptance); + pub const ID_ON_PERSONALDATA: Nid = Nid(ffi::NID_id_on_personalData); + pub const ID_ON_PERMANENTIDENTIFIER: Nid = Nid(ffi::NID_id_on_permanentIdentifier); + pub const ID_PDA_DATEOFBIRTH: Nid = Nid(ffi::NID_id_pda_dateOfBirth); + pub const ID_PDA_PLACEOFBIRTH: Nid = Nid(ffi::NID_id_pda_placeOfBirth); + pub const ID_PDA_GENDER: Nid = Nid(ffi::NID_id_pda_gender); + pub const ID_PDA_COUNTRYOFCITIZENSHIP: Nid = Nid(ffi::NID_id_pda_countryOfCitizenship); + pub const ID_PDA_COUNTRYOFRESIDENCE: Nid = Nid(ffi::NID_id_pda_countryOfResidence); + pub const ID_ACA_AUTHENTICATIONINFO: Nid = Nid(ffi::NID_id_aca_authenticationInfo); + pub const ID_ACA_ACCESSIDENTITY: Nid = Nid(ffi::NID_id_aca_accessIdentity); + pub const ID_ACA_CHARGINGIDENTITY: Nid = Nid(ffi::NID_id_aca_chargingIdentity); + pub const ID_ACA_GROUP: Nid = Nid(ffi::NID_id_aca_group); + pub const ID_ACA_ROLE: Nid = Nid(ffi::NID_id_aca_role); + pub const ID_ACA_ENCATTRS: Nid = Nid(ffi::NID_id_aca_encAttrs); + pub const ID_QCS_PKIXQCSYNTAX_V1: Nid = Nid(ffi::NID_id_qcs_pkixQCSyntax_v1); + pub const ID_CCT_CRS: Nid = Nid(ffi::NID_id_cct_crs); + pub const ID_CCT_PKIDATA: Nid = Nid(ffi::NID_id_cct_PKIData); + pub const ID_CCT_PKIRESPONSE: Nid = Nid(ffi::NID_id_cct_PKIResponse); + pub const ID_PPL_ANYLANGUAGE: Nid = Nid(ffi::NID_id_ppl_anyLanguage); + pub const ID_PPL_INHERITALL: Nid = Nid(ffi::NID_id_ppl_inheritAll); + pub const INDEPENDENT: Nid = Nid(ffi::NID_Independent); + pub const AD_OCSP: Nid = Nid(ffi::NID_ad_OCSP); + pub const AD_CA_ISSUERS: Nid = Nid(ffi::NID_ad_ca_issuers); + pub const AD_TIMESTAMPING: Nid = Nid(ffi::NID_ad_timeStamping); + pub const AD_DVCS: Nid = Nid(ffi::NID_ad_dvcs); + pub const CAREPOSITORY: Nid = Nid(ffi::NID_caRepository); + pub const ID_PKIX_OCSP_BASIC: Nid = Nid(ffi::NID_id_pkix_OCSP_basic); + pub const ID_PKIX_OCSP_NONCE: Nid = Nid(ffi::NID_id_pkix_OCSP_Nonce); + pub const ID_PKIX_OCSP_CRLID: Nid = Nid(ffi::NID_id_pkix_OCSP_CrlID); + pub const ID_PKIX_OCSP_ACCEPTABLERESPONSES: Nid = + Nid(ffi::NID_id_pkix_OCSP_acceptableResponses); + pub const ID_PKIX_OCSP_NOCHECK: Nid = Nid(ffi::NID_id_pkix_OCSP_noCheck); + pub const ID_PKIX_OCSP_ARCHIVECUTOFF: Nid = Nid(ffi::NID_id_pkix_OCSP_archiveCutoff); + pub const ID_PKIX_OCSP_SERVICELOCATOR: Nid = Nid(ffi::NID_id_pkix_OCSP_serviceLocator); + pub const ID_PKIX_OCSP_EXTENDEDSTATUS: Nid = Nid(ffi::NID_id_pkix_OCSP_extendedStatus); + pub const ID_PKIX_OCSP_VALID: Nid = Nid(ffi::NID_id_pkix_OCSP_valid); + pub const ID_PKIX_OCSP_PATH: Nid = Nid(ffi::NID_id_pkix_OCSP_path); + pub const ID_PKIX_OCSP_TRUSTROOT: Nid = Nid(ffi::NID_id_pkix_OCSP_trustRoot); + pub const ALGORITHM: Nid = Nid(ffi::NID_algorithm); + pub const MD5WITHRSA: Nid = Nid(ffi::NID_md5WithRSA); + pub const DES_ECB: Nid = Nid(ffi::NID_des_ecb); + pub const DES_CBC: Nid = Nid(ffi::NID_des_cbc); + pub const DES_OFB64: Nid = Nid(ffi::NID_des_ofb64); + pub const DES_CFB64: Nid = Nid(ffi::NID_des_cfb64); + pub const RSASIGNATURE: Nid = Nid(ffi::NID_rsaSignature); + pub const DSA_2: Nid = Nid(ffi::NID_dsa_2); + pub const DSAWITHSHA: Nid = Nid(ffi::NID_dsaWithSHA); + pub const SHAWITHRSAENCRYPTION: Nid = Nid(ffi::NID_shaWithRSAEncryption); + pub const DES_EDE_ECB: Nid = Nid(ffi::NID_des_ede_ecb); + pub const DES_EDE3_ECB: Nid = Nid(ffi::NID_des_ede3_ecb); + pub const DES_EDE_CBC: Nid = Nid(ffi::NID_des_ede_cbc); + pub const DES_EDE_CFB64: Nid = Nid(ffi::NID_des_ede_cfb64); + pub const DES_EDE3_CFB64: Nid = Nid(ffi::NID_des_ede3_cfb64); + pub const DES_EDE_OFB64: Nid = Nid(ffi::NID_des_ede_ofb64); + pub const DES_EDE3_OFB64: Nid = Nid(ffi::NID_des_ede3_ofb64); + pub const DESX_CBC: Nid = Nid(ffi::NID_desx_cbc); + pub const SHA: Nid = Nid(ffi::NID_sha); + pub const SHA1: Nid = Nid(ffi::NID_sha1); + pub const DSAWITHSHA1_2: Nid = Nid(ffi::NID_dsaWithSHA1_2); + pub const SHA1WITHRSA: Nid = Nid(ffi::NID_sha1WithRSA); + pub const RIPEMD160: Nid = Nid(ffi::NID_ripemd160); + pub const RIPEMD160WITHRSA: Nid = Nid(ffi::NID_ripemd160WithRSA); + pub const SXNET: Nid = Nid(ffi::NID_sxnet); + pub const X500: Nid = Nid(ffi::NID_X500); + pub const X509: Nid = Nid(ffi::NID_X509); + pub const COMMONNAME: Nid = Nid(ffi::NID_commonName); + pub const SURNAME: Nid = Nid(ffi::NID_surname); + pub const SERIALNUMBER: Nid = Nid(ffi::NID_serialNumber); + pub const COUNTRYNAME: Nid = Nid(ffi::NID_countryName); + pub const LOCALITYNAME: Nid = Nid(ffi::NID_localityName); + pub const STATEORPROVINCENAME: Nid = Nid(ffi::NID_stateOrProvinceName); + pub const STREETADDRESS: Nid = Nid(ffi::NID_streetAddress); + pub const ORGANIZATIONNAME: Nid = Nid(ffi::NID_organizationName); + pub const ORGANIZATIONALUNITNAME: Nid = Nid(ffi::NID_organizationalUnitName); + pub const TITLE: Nid = Nid(ffi::NID_title); + pub const DESCRIPTION: Nid = Nid(ffi::NID_description); + pub const SEARCHGUIDE: Nid = Nid(ffi::NID_searchGuide); + pub const BUSINESSCATEGORY: Nid = Nid(ffi::NID_businessCategory); + pub const POSTALADDRESS: Nid = Nid(ffi::NID_postalAddress); + pub const POSTALCODE: Nid = Nid(ffi::NID_postalCode); + pub const POSTOFFICEBOX: Nid = Nid(ffi::NID_postOfficeBox); + pub const PHYSICALDELIVERYOFFICENAME: Nid = Nid(ffi::NID_physicalDeliveryOfficeName); + pub const TELEPHONENUMBER: Nid = Nid(ffi::NID_telephoneNumber); + pub const TELEXNUMBER: Nid = Nid(ffi::NID_telexNumber); + pub const TELETEXTERMINALIDENTIFIER: Nid = Nid(ffi::NID_teletexTerminalIdentifier); + pub const FACSIMILETELEPHONENUMBER: Nid = Nid(ffi::NID_facsimileTelephoneNumber); + pub const X121ADDRESS: Nid = Nid(ffi::NID_x121Address); + pub const INTERNATIONALISDNNUMBER: Nid = Nid(ffi::NID_internationaliSDNNumber); + pub const REGISTEREDADDRESS: Nid = Nid(ffi::NID_registeredAddress); + pub const DESTINATIONINDICATOR: Nid = Nid(ffi::NID_destinationIndicator); + pub const PREFERREDDELIVERYMETHOD: Nid = Nid(ffi::NID_preferredDeliveryMethod); + pub const PRESENTATIONADDRESS: Nid = Nid(ffi::NID_presentationAddress); + pub const SUPPORTEDAPPLICATIONCONTEXT: Nid = Nid(ffi::NID_supportedApplicationContext); + pub const MEMBER: Nid = Nid(ffi::NID_member); + pub const OWNER: Nid = Nid(ffi::NID_owner); + pub const ROLEOCCUPANT: Nid = Nid(ffi::NID_roleOccupant); + pub const SEEALSO: Nid = Nid(ffi::NID_seeAlso); + pub const USERPASSWORD: Nid = Nid(ffi::NID_userPassword); + pub const USERCERTIFICATE: Nid = Nid(ffi::NID_userCertificate); + pub const CACERTIFICATE: Nid = Nid(ffi::NID_cACertificate); + pub const AUTHORITYREVOCATIONLIST: Nid = Nid(ffi::NID_authorityRevocationList); + pub const CERTIFICATEREVOCATIONLIST: Nid = Nid(ffi::NID_certificateRevocationList); + pub const CROSSCERTIFICATEPAIR: Nid = Nid(ffi::NID_crossCertificatePair); + pub const NAME: Nid = Nid(ffi::NID_name); + pub const GIVENNAME: Nid = Nid(ffi::NID_givenName); + pub const INITIALS: Nid = Nid(ffi::NID_initials); + pub const GENERATIONQUALIFIER: Nid = Nid(ffi::NID_generationQualifier); + pub const X500UNIQUEIDENTIFIER: Nid = Nid(ffi::NID_x500UniqueIdentifier); + pub const DNQUALIFIER: Nid = Nid(ffi::NID_dnQualifier); + pub const ENHANCEDSEARCHGUIDE: Nid = Nid(ffi::NID_enhancedSearchGuide); + pub const PROTOCOLINFORMATION: Nid = Nid(ffi::NID_protocolInformation); + pub const DISTINGUISHEDNAME: Nid = Nid(ffi::NID_distinguishedName); + pub const UNIQUEMEMBER: Nid = Nid(ffi::NID_uniqueMember); + pub const HOUSEIDENTIFIER: Nid = Nid(ffi::NID_houseIdentifier); + pub const SUPPORTEDALGORITHMS: Nid = Nid(ffi::NID_supportedAlgorithms); + pub const DELTAREVOCATIONLIST: Nid = Nid(ffi::NID_deltaRevocationList); + pub const DMDNAME: Nid = Nid(ffi::NID_dmdName); + pub const PSEUDONYM: Nid = Nid(ffi::NID_pseudonym); + pub const ROLE: Nid = Nid(ffi::NID_role); + pub const X500ALGORITHMS: Nid = Nid(ffi::NID_X500algorithms); + pub const RSA: Nid = Nid(ffi::NID_rsa); + pub const MDC2WITHRSA: Nid = Nid(ffi::NID_mdc2WithRSA); + pub const MDC2: Nid = Nid(ffi::NID_mdc2); + pub const ID_CE: Nid = Nid(ffi::NID_id_ce); + pub const SUBJECT_DIRECTORY_ATTRIBUTES: Nid = Nid(ffi::NID_subject_directory_attributes); + pub const SUBJECT_KEY_IDENTIFIER: Nid = Nid(ffi::NID_subject_key_identifier); + pub const KEY_USAGE: Nid = Nid(ffi::NID_key_usage); + pub const PRIVATE_KEY_USAGE_PERIOD: Nid = Nid(ffi::NID_private_key_usage_period); + pub const SUBJECT_ALT_NAME: Nid = Nid(ffi::NID_subject_alt_name); + pub const ISSUER_ALT_NAME: Nid = Nid(ffi::NID_issuer_alt_name); + pub const BASIC_CONSTRAINTS: Nid = Nid(ffi::NID_basic_constraints); + pub const CRL_NUMBER: Nid = Nid(ffi::NID_crl_number); + pub const CRL_REASON: Nid = Nid(ffi::NID_crl_reason); + pub const INVALIDITY_DATE: Nid = Nid(ffi::NID_invalidity_date); + pub const DELTA_CRL: Nid = Nid(ffi::NID_delta_crl); + pub const ISSUING_DISTRIBUTION_POINT: Nid = Nid(ffi::NID_issuing_distribution_point); + pub const CERTIFICATE_ISSUER: Nid = Nid(ffi::NID_certificate_issuer); + pub const NAME_CONSTRAINTS: Nid = Nid(ffi::NID_name_constraints); + pub const CRL_DISTRIBUTION_POINTS: Nid = Nid(ffi::NID_crl_distribution_points); + pub const CERTIFICATE_POLICIES: Nid = Nid(ffi::NID_certificate_policies); + pub const ANY_POLICY: Nid = Nid(ffi::NID_any_policy); + pub const POLICY_MAPPINGS: Nid = Nid(ffi::NID_policy_mappings); + pub const AUTHORITY_KEY_IDENTIFIER: Nid = Nid(ffi::NID_authority_key_identifier); + pub const POLICY_CONSTRAINTS: Nid = Nid(ffi::NID_policy_constraints); + pub const EXT_KEY_USAGE: Nid = Nid(ffi::NID_ext_key_usage); + pub const FRESHEST_CRL: Nid = Nid(ffi::NID_freshest_crl); + pub const INHIBIT_ANY_POLICY: Nid = Nid(ffi::NID_inhibit_any_policy); + pub const TARGET_INFORMATION: Nid = Nid(ffi::NID_target_information); + pub const NO_REV_AVAIL: Nid = Nid(ffi::NID_no_rev_avail); + pub const ANYEXTENDEDKEYUSAGE: Nid = Nid(ffi::NID_anyExtendedKeyUsage); + pub const NETSCAPE: Nid = Nid(ffi::NID_netscape); + pub const NETSCAPE_CERT_EXTENSION: Nid = Nid(ffi::NID_netscape_cert_extension); + pub const NETSCAPE_DATA_TYPE: Nid = Nid(ffi::NID_netscape_data_type); + pub const NETSCAPE_CERT_TYPE: Nid = Nid(ffi::NID_netscape_cert_type); + pub const NETSCAPE_BASE_URL: Nid = Nid(ffi::NID_netscape_base_url); + pub const NETSCAPE_REVOCATION_URL: Nid = Nid(ffi::NID_netscape_revocation_url); + pub const NETSCAPE_CA_REVOCATION_URL: Nid = Nid(ffi::NID_netscape_ca_revocation_url); + pub const NETSCAPE_RENEWAL_URL: Nid = Nid(ffi::NID_netscape_renewal_url); + pub const NETSCAPE_CA_POLICY_URL: Nid = Nid(ffi::NID_netscape_ca_policy_url); + pub const NETSCAPE_SSL_SERVER_NAME: Nid = Nid(ffi::NID_netscape_ssl_server_name); + pub const NETSCAPE_COMMENT: Nid = Nid(ffi::NID_netscape_comment); + pub const NETSCAPE_CERT_SEQUENCE: Nid = Nid(ffi::NID_netscape_cert_sequence); + pub const NS_SGC: Nid = Nid(ffi::NID_ns_sgc); + pub const ORG: Nid = Nid(ffi::NID_org); + pub const DOD: Nid = Nid(ffi::NID_dod); + pub const IANA: Nid = Nid(ffi::NID_iana); + pub const DIRECTORY: Nid = Nid(ffi::NID_Directory); + pub const MANAGEMENT: Nid = Nid(ffi::NID_Management); + pub const EXPERIMENTAL: Nid = Nid(ffi::NID_Experimental); + pub const PRIVATE: Nid = Nid(ffi::NID_Private); + pub const SECURITY: Nid = Nid(ffi::NID_Security); + pub const SNMPV2: Nid = Nid(ffi::NID_SNMPv2); + pub const MAIL: Nid = Nid(ffi::NID_Mail); + pub const ENTERPRISES: Nid = Nid(ffi::NID_Enterprises); + pub const DCOBJECT: Nid = Nid(ffi::NID_dcObject); + pub const MIME_MHS: Nid = Nid(ffi::NID_mime_mhs); + pub const MIME_MHS_HEADINGS: Nid = Nid(ffi::NID_mime_mhs_headings); + pub const MIME_MHS_BODIES: Nid = Nid(ffi::NID_mime_mhs_bodies); + pub const ID_HEX_PARTIAL_MESSAGE: Nid = Nid(ffi::NID_id_hex_partial_message); + pub const ID_HEX_MULTIPART_MESSAGE: Nid = Nid(ffi::NID_id_hex_multipart_message); + pub const ZLIB_COMPRESSION: Nid = Nid(ffi::NID_zlib_compression); + pub const AES_128_ECB: Nid = Nid(ffi::NID_aes_128_ecb); + pub const AES_128_CBC: Nid = Nid(ffi::NID_aes_128_cbc); + pub const AES_128_OFB128: Nid = Nid(ffi::NID_aes_128_ofb128); + pub const AES_128_CFB128: Nid = Nid(ffi::NID_aes_128_cfb128); + pub const ID_AES128_WRAP: Nid = Nid(ffi::NID_id_aes128_wrap); + pub const AES_128_GCM: Nid = Nid(ffi::NID_aes_128_gcm); + pub const AES_128_CCM: Nid = Nid(ffi::NID_aes_128_ccm); + pub const ID_AES128_WRAP_PAD: Nid = Nid(ffi::NID_id_aes128_wrap_pad); + pub const AES_192_ECB: Nid = Nid(ffi::NID_aes_192_ecb); + pub const AES_192_CBC: Nid = Nid(ffi::NID_aes_192_cbc); + pub const AES_192_OFB128: Nid = Nid(ffi::NID_aes_192_ofb128); + pub const AES_192_CFB128: Nid = Nid(ffi::NID_aes_192_cfb128); + pub const ID_AES192_WRAP: Nid = Nid(ffi::NID_id_aes192_wrap); + pub const AES_192_GCM: Nid = Nid(ffi::NID_aes_192_gcm); + pub const AES_192_CCM: Nid = Nid(ffi::NID_aes_192_ccm); + pub const ID_AES192_WRAP_PAD: Nid = Nid(ffi::NID_id_aes192_wrap_pad); + pub const AES_256_ECB: Nid = Nid(ffi::NID_aes_256_ecb); + pub const AES_256_CBC: Nid = Nid(ffi::NID_aes_256_cbc); + pub const AES_256_OFB128: Nid = Nid(ffi::NID_aes_256_ofb128); + pub const AES_256_CFB128: Nid = Nid(ffi::NID_aes_256_cfb128); + pub const ID_AES256_WRAP: Nid = Nid(ffi::NID_id_aes256_wrap); + pub const AES_256_GCM: Nid = Nid(ffi::NID_aes_256_gcm); + pub const AES_256_CCM: Nid = Nid(ffi::NID_aes_256_ccm); + pub const ID_AES256_WRAP_PAD: Nid = Nid(ffi::NID_id_aes256_wrap_pad); + pub const AES_128_CFB1: Nid = Nid(ffi::NID_aes_128_cfb1); + pub const AES_192_CFB1: Nid = Nid(ffi::NID_aes_192_cfb1); + pub const AES_256_CFB1: Nid = Nid(ffi::NID_aes_256_cfb1); + pub const AES_128_CFB8: Nid = Nid(ffi::NID_aes_128_cfb8); + pub const AES_192_CFB8: Nid = Nid(ffi::NID_aes_192_cfb8); + pub const AES_256_CFB8: Nid = Nid(ffi::NID_aes_256_cfb8); + pub const AES_128_CTR: Nid = Nid(ffi::NID_aes_128_ctr); + pub const AES_192_CTR: Nid = Nid(ffi::NID_aes_192_ctr); + pub const AES_256_CTR: Nid = Nid(ffi::NID_aes_256_ctr); + pub const AES_128_XTS: Nid = Nid(ffi::NID_aes_128_xts); + pub const AES_256_XTS: Nid = Nid(ffi::NID_aes_256_xts); + pub const DES_CFB1: Nid = Nid(ffi::NID_des_cfb1); + pub const DES_CFB8: Nid = Nid(ffi::NID_des_cfb8); + pub const DES_EDE3_CFB1: Nid = Nid(ffi::NID_des_ede3_cfb1); + pub const DES_EDE3_CFB8: Nid = Nid(ffi::NID_des_ede3_cfb8); + pub const SHA256: Nid = Nid(ffi::NID_sha256); + pub const SHA384: Nid = Nid(ffi::NID_sha384); + pub const SHA512: Nid = Nid(ffi::NID_sha512); + pub const SHA224: Nid = Nid(ffi::NID_sha224); + pub const DSA_WITH_SHA224: Nid = Nid(ffi::NID_dsa_with_SHA224); + pub const DSA_WITH_SHA256: Nid = Nid(ffi::NID_dsa_with_SHA256); + pub const HOLD_INSTRUCTION_CODE: Nid = Nid(ffi::NID_hold_instruction_code); + pub const HOLD_INSTRUCTION_NONE: Nid = Nid(ffi::NID_hold_instruction_none); + pub const HOLD_INSTRUCTION_CALL_ISSUER: Nid = Nid(ffi::NID_hold_instruction_call_issuer); + pub const HOLD_INSTRUCTION_REJECT: Nid = Nid(ffi::NID_hold_instruction_reject); + pub const DATA: Nid = Nid(ffi::NID_data); + pub const PSS: Nid = Nid(ffi::NID_pss); + pub const UCL: Nid = Nid(ffi::NID_ucl); + pub const PILOT: Nid = Nid(ffi::NID_pilot); + pub const PILOTATTRIBUTETYPE: Nid = Nid(ffi::NID_pilotAttributeType); + pub const PILOTATTRIBUTESYNTAX: Nid = Nid(ffi::NID_pilotAttributeSyntax); + pub const PILOTOBJECTCLASS: Nid = Nid(ffi::NID_pilotObjectClass); + pub const PILOTGROUPS: Nid = Nid(ffi::NID_pilotGroups); + pub const IA5STRINGSYNTAX: Nid = Nid(ffi::NID_iA5StringSyntax); + pub const CASEIGNOREIA5STRINGSYNTAX: Nid = Nid(ffi::NID_caseIgnoreIA5StringSyntax); + pub const PILOTOBJECT: Nid = Nid(ffi::NID_pilotObject); + pub const PILOTPERSON: Nid = Nid(ffi::NID_pilotPerson); + pub const ACCOUNT: Nid = Nid(ffi::NID_account); + pub const DOCUMENT: Nid = Nid(ffi::NID_document); + pub const ROOM: Nid = Nid(ffi::NID_room); + pub const DOCUMENTSERIES: Nid = Nid(ffi::NID_documentSeries); + pub const DOMAIN: Nid = Nid(ffi::NID_Domain); + pub const RFC822LOCALPART: Nid = Nid(ffi::NID_rFC822localPart); + pub const DNSDOMAIN: Nid = Nid(ffi::NID_dNSDomain); + pub const DOMAINRELATEDOBJECT: Nid = Nid(ffi::NID_domainRelatedObject); + pub const FRIENDLYCOUNTRY: Nid = Nid(ffi::NID_friendlyCountry); + pub const SIMPLESECURITYOBJECT: Nid = Nid(ffi::NID_simpleSecurityObject); + pub const PILOTORGANIZATION: Nid = Nid(ffi::NID_pilotOrganization); + pub const PILOTDSA: Nid = Nid(ffi::NID_pilotDSA); + pub const QUALITYLABELLEDDATA: Nid = Nid(ffi::NID_qualityLabelledData); + pub const USERID: Nid = Nid(ffi::NID_userId); + pub const TEXTENCODEDORADDRESS: Nid = Nid(ffi::NID_textEncodedORAddress); + pub const RFC822MAILBOX: Nid = Nid(ffi::NID_rfc822Mailbox); + pub const INFO: Nid = Nid(ffi::NID_info); + pub const FAVOURITEDRINK: Nid = Nid(ffi::NID_favouriteDrink); + pub const ROOMNUMBER: Nid = Nid(ffi::NID_roomNumber); + pub const PHOTO: Nid = Nid(ffi::NID_photo); + pub const USERCLASS: Nid = Nid(ffi::NID_userClass); + pub const HOST: Nid = Nid(ffi::NID_host); + pub const MANAGER: Nid = Nid(ffi::NID_manager); + pub const DOCUMENTIDENTIFIER: Nid = Nid(ffi::NID_documentIdentifier); + pub const DOCUMENTTITLE: Nid = Nid(ffi::NID_documentTitle); + pub const DOCUMENTVERSION: Nid = Nid(ffi::NID_documentVersion); + pub const DOCUMENTAUTHOR: Nid = Nid(ffi::NID_documentAuthor); + pub const DOCUMENTLOCATION: Nid = Nid(ffi::NID_documentLocation); + pub const HOMETELEPHONENUMBER: Nid = Nid(ffi::NID_homeTelephoneNumber); + pub const SECRETARY: Nid = Nid(ffi::NID_secretary); + pub const OTHERMAILBOX: Nid = Nid(ffi::NID_otherMailbox); + pub const LASTMODIFIEDTIME: Nid = Nid(ffi::NID_lastModifiedTime); + pub const LASTMODIFIEDBY: Nid = Nid(ffi::NID_lastModifiedBy); + pub const DOMAINCOMPONENT: Nid = Nid(ffi::NID_domainComponent); + pub const ARECORD: Nid = Nid(ffi::NID_aRecord); + pub const PILOTATTRIBUTETYPE27: Nid = Nid(ffi::NID_pilotAttributeType27); + pub const MXRECORD: Nid = Nid(ffi::NID_mXRecord); + pub const NSRECORD: Nid = Nid(ffi::NID_nSRecord); + pub const SOARECORD: Nid = Nid(ffi::NID_sOARecord); + pub const CNAMERECORD: Nid = Nid(ffi::NID_cNAMERecord); + pub const ASSOCIATEDDOMAIN: Nid = Nid(ffi::NID_associatedDomain); + pub const ASSOCIATEDNAME: Nid = Nid(ffi::NID_associatedName); + pub const HOMEPOSTALADDRESS: Nid = Nid(ffi::NID_homePostalAddress); + pub const PERSONALTITLE: Nid = Nid(ffi::NID_personalTitle); + pub const MOBILETELEPHONENUMBER: Nid = Nid(ffi::NID_mobileTelephoneNumber); + pub const PAGERTELEPHONENUMBER: Nid = Nid(ffi::NID_pagerTelephoneNumber); + pub const FRIENDLYCOUNTRYNAME: Nid = Nid(ffi::NID_friendlyCountryName); + pub const ORGANIZATIONALSTATUS: Nid = Nid(ffi::NID_organizationalStatus); + pub const JANETMAILBOX: Nid = Nid(ffi::NID_janetMailbox); + pub const MAILPREFERENCEOPTION: Nid = Nid(ffi::NID_mailPreferenceOption); + pub const BUILDINGNAME: Nid = Nid(ffi::NID_buildingName); + pub const DSAQUALITY: Nid = Nid(ffi::NID_dSAQuality); + pub const SINGLELEVELQUALITY: Nid = Nid(ffi::NID_singleLevelQuality); + pub const SUBTREEMINIMUMQUALITY: Nid = Nid(ffi::NID_subtreeMinimumQuality); + pub const SUBTREEMAXIMUMQUALITY: Nid = Nid(ffi::NID_subtreeMaximumQuality); + pub const PERSONALSIGNATURE: Nid = Nid(ffi::NID_personalSignature); + pub const DITREDIRECT: Nid = Nid(ffi::NID_dITRedirect); + pub const AUDIO: Nid = Nid(ffi::NID_audio); + pub const DOCUMENTPUBLISHER: Nid = Nid(ffi::NID_documentPublisher); + pub const ID_SET: Nid = Nid(ffi::NID_id_set); + pub const SET_CTYPE: Nid = Nid(ffi::NID_set_ctype); + pub const SET_MSGEXT: Nid = Nid(ffi::NID_set_msgExt); + pub const SET_ATTR: Nid = Nid(ffi::NID_set_attr); + pub const SET_POLICY: Nid = Nid(ffi::NID_set_policy); + pub const SET_CERTEXT: Nid = Nid(ffi::NID_set_certExt); + pub const SET_BRAND: Nid = Nid(ffi::NID_set_brand); + pub const SETCT_PANDATA: Nid = Nid(ffi::NID_setct_PANData); + pub const SETCT_PANTOKEN: Nid = Nid(ffi::NID_setct_PANToken); + pub const SETCT_PANONLY: Nid = Nid(ffi::NID_setct_PANOnly); + pub const SETCT_OIDATA: Nid = Nid(ffi::NID_setct_OIData); + pub const SETCT_PI: Nid = Nid(ffi::NID_setct_PI); + pub const SETCT_PIDATA: Nid = Nid(ffi::NID_setct_PIData); + pub const SETCT_PIDATAUNSIGNED: Nid = Nid(ffi::NID_setct_PIDataUnsigned); + pub const SETCT_HODINPUT: Nid = Nid(ffi::NID_setct_HODInput); + pub const SETCT_AUTHRESBAGGAGE: Nid = Nid(ffi::NID_setct_AuthResBaggage); + pub const SETCT_AUTHREVREQBAGGAGE: Nid = Nid(ffi::NID_setct_AuthRevReqBaggage); + pub const SETCT_AUTHREVRESBAGGAGE: Nid = Nid(ffi::NID_setct_AuthRevResBaggage); + pub const SETCT_CAPTOKENSEQ: Nid = Nid(ffi::NID_setct_CapTokenSeq); + pub const SETCT_PINITRESDATA: Nid = Nid(ffi::NID_setct_PInitResData); + pub const SETCT_PI_TBS: Nid = Nid(ffi::NID_setct_PI_TBS); + pub const SETCT_PRESDATA: Nid = Nid(ffi::NID_setct_PResData); + pub const SETCT_AUTHREQTBS: Nid = Nid(ffi::NID_setct_AuthReqTBS); + pub const SETCT_AUTHRESTBS: Nid = Nid(ffi::NID_setct_AuthResTBS); + pub const SETCT_AUTHRESTBSX: Nid = Nid(ffi::NID_setct_AuthResTBSX); + pub const SETCT_AUTHTOKENTBS: Nid = Nid(ffi::NID_setct_AuthTokenTBS); + pub const SETCT_CAPTOKENDATA: Nid = Nid(ffi::NID_setct_CapTokenData); + pub const SETCT_CAPTOKENTBS: Nid = Nid(ffi::NID_setct_CapTokenTBS); + pub const SETCT_ACQCARDCODEMSG: Nid = Nid(ffi::NID_setct_AcqCardCodeMsg); + pub const SETCT_AUTHREVREQTBS: Nid = Nid(ffi::NID_setct_AuthRevReqTBS); + pub const SETCT_AUTHREVRESDATA: Nid = Nid(ffi::NID_setct_AuthRevResData); + pub const SETCT_AUTHREVRESTBS: Nid = Nid(ffi::NID_setct_AuthRevResTBS); + pub const SETCT_CAPREQTBS: Nid = Nid(ffi::NID_setct_CapReqTBS); + pub const SETCT_CAPREQTBSX: Nid = Nid(ffi::NID_setct_CapReqTBSX); + pub const SETCT_CAPRESDATA: Nid = Nid(ffi::NID_setct_CapResData); + pub const SETCT_CAPREVREQTBS: Nid = Nid(ffi::NID_setct_CapRevReqTBS); + pub const SETCT_CAPREVREQTBSX: Nid = Nid(ffi::NID_setct_CapRevReqTBSX); + pub const SETCT_CAPREVRESDATA: Nid = Nid(ffi::NID_setct_CapRevResData); + pub const SETCT_CREDREQTBS: Nid = Nid(ffi::NID_setct_CredReqTBS); + pub const SETCT_CREDREQTBSX: Nid = Nid(ffi::NID_setct_CredReqTBSX); + pub const SETCT_CREDRESDATA: Nid = Nid(ffi::NID_setct_CredResData); + pub const SETCT_CREDREVREQTBS: Nid = Nid(ffi::NID_setct_CredRevReqTBS); + pub const SETCT_CREDREVREQTBSX: Nid = Nid(ffi::NID_setct_CredRevReqTBSX); + pub const SETCT_CREDREVRESDATA: Nid = Nid(ffi::NID_setct_CredRevResData); + pub const SETCT_PCERTREQDATA: Nid = Nid(ffi::NID_setct_PCertReqData); + pub const SETCT_PCERTRESTBS: Nid = Nid(ffi::NID_setct_PCertResTBS); + pub const SETCT_BATCHADMINREQDATA: Nid = Nid(ffi::NID_setct_BatchAdminReqData); + pub const SETCT_BATCHADMINRESDATA: Nid = Nid(ffi::NID_setct_BatchAdminResData); + pub const SETCT_CARDCINITRESTBS: Nid = Nid(ffi::NID_setct_CardCInitResTBS); + pub const SETCT_MEAQCINITRESTBS: Nid = Nid(ffi::NID_setct_MeAqCInitResTBS); + pub const SETCT_REGFORMRESTBS: Nid = Nid(ffi::NID_setct_RegFormResTBS); + pub const SETCT_CERTREQDATA: Nid = Nid(ffi::NID_setct_CertReqData); + pub const SETCT_CERTREQTBS: Nid = Nid(ffi::NID_setct_CertReqTBS); + pub const SETCT_CERTRESDATA: Nid = Nid(ffi::NID_setct_CertResData); + pub const SETCT_CERTINQREQTBS: Nid = Nid(ffi::NID_setct_CertInqReqTBS); + pub const SETCT_ERRORTBS: Nid = Nid(ffi::NID_setct_ErrorTBS); + pub const SETCT_PIDUALSIGNEDTBE: Nid = Nid(ffi::NID_setct_PIDualSignedTBE); + pub const SETCT_PIUNSIGNEDTBE: Nid = Nid(ffi::NID_setct_PIUnsignedTBE); + pub const SETCT_AUTHREQTBE: Nid = Nid(ffi::NID_setct_AuthReqTBE); + pub const SETCT_AUTHRESTBE: Nid = Nid(ffi::NID_setct_AuthResTBE); + pub const SETCT_AUTHRESTBEX: Nid = Nid(ffi::NID_setct_AuthResTBEX); + pub const SETCT_AUTHTOKENTBE: Nid = Nid(ffi::NID_setct_AuthTokenTBE); + pub const SETCT_CAPTOKENTBE: Nid = Nid(ffi::NID_setct_CapTokenTBE); + pub const SETCT_CAPTOKENTBEX: Nid = Nid(ffi::NID_setct_CapTokenTBEX); + pub const SETCT_ACQCARDCODEMSGTBE: Nid = Nid(ffi::NID_setct_AcqCardCodeMsgTBE); + pub const SETCT_AUTHREVREQTBE: Nid = Nid(ffi::NID_setct_AuthRevReqTBE); + pub const SETCT_AUTHREVRESTBE: Nid = Nid(ffi::NID_setct_AuthRevResTBE); + pub const SETCT_AUTHREVRESTBEB: Nid = Nid(ffi::NID_setct_AuthRevResTBEB); + pub const SETCT_CAPREQTBE: Nid = Nid(ffi::NID_setct_CapReqTBE); + pub const SETCT_CAPREQTBEX: Nid = Nid(ffi::NID_setct_CapReqTBEX); + pub const SETCT_CAPRESTBE: Nid = Nid(ffi::NID_setct_CapResTBE); + pub const SETCT_CAPREVREQTBE: Nid = Nid(ffi::NID_setct_CapRevReqTBE); + pub const SETCT_CAPREVREQTBEX: Nid = Nid(ffi::NID_setct_CapRevReqTBEX); + pub const SETCT_CAPREVRESTBE: Nid = Nid(ffi::NID_setct_CapRevResTBE); + pub const SETCT_CREDREQTBE: Nid = Nid(ffi::NID_setct_CredReqTBE); + pub const SETCT_CREDREQTBEX: Nid = Nid(ffi::NID_setct_CredReqTBEX); + pub const SETCT_CREDRESTBE: Nid = Nid(ffi::NID_setct_CredResTBE); + pub const SETCT_CREDREVREQTBE: Nid = Nid(ffi::NID_setct_CredRevReqTBE); + pub const SETCT_CREDREVREQTBEX: Nid = Nid(ffi::NID_setct_CredRevReqTBEX); + pub const SETCT_CREDREVRESTBE: Nid = Nid(ffi::NID_setct_CredRevResTBE); + pub const SETCT_BATCHADMINREQTBE: Nid = Nid(ffi::NID_setct_BatchAdminReqTBE); + pub const SETCT_BATCHADMINRESTBE: Nid = Nid(ffi::NID_setct_BatchAdminResTBE); + pub const SETCT_REGFORMREQTBE: Nid = Nid(ffi::NID_setct_RegFormReqTBE); + pub const SETCT_CERTREQTBE: Nid = Nid(ffi::NID_setct_CertReqTBE); + pub const SETCT_CERTREQTBEX: Nid = Nid(ffi::NID_setct_CertReqTBEX); + pub const SETCT_CERTRESTBE: Nid = Nid(ffi::NID_setct_CertResTBE); + pub const SETCT_CRLNOTIFICATIONTBS: Nid = Nid(ffi::NID_setct_CRLNotificationTBS); + pub const SETCT_CRLNOTIFICATIONRESTBS: Nid = Nid(ffi::NID_setct_CRLNotificationResTBS); + pub const SETCT_BCIDISTRIBUTIONTBS: Nid = Nid(ffi::NID_setct_BCIDistributionTBS); + pub const SETEXT_GENCRYPT: Nid = Nid(ffi::NID_setext_genCrypt); + pub const SETEXT_MIAUTH: Nid = Nid(ffi::NID_setext_miAuth); + pub const SETEXT_PINSECURE: Nid = Nid(ffi::NID_setext_pinSecure); + pub const SETEXT_PINANY: Nid = Nid(ffi::NID_setext_pinAny); + pub const SETEXT_TRACK2: Nid = Nid(ffi::NID_setext_track2); + pub const SETEXT_CV: Nid = Nid(ffi::NID_setext_cv); + pub const SET_POLICY_ROOT: Nid = Nid(ffi::NID_set_policy_root); + pub const SETCEXT_HASHEDROOT: Nid = Nid(ffi::NID_setCext_hashedRoot); + pub const SETCEXT_CERTTYPE: Nid = Nid(ffi::NID_setCext_certType); + pub const SETCEXT_MERCHDATA: Nid = Nid(ffi::NID_setCext_merchData); + pub const SETCEXT_CCERTREQUIRED: Nid = Nid(ffi::NID_setCext_cCertRequired); + pub const SETCEXT_TUNNELING: Nid = Nid(ffi::NID_setCext_tunneling); + pub const SETCEXT_SETEXT: Nid = Nid(ffi::NID_setCext_setExt); + pub const SETCEXT_SETQUALF: Nid = Nid(ffi::NID_setCext_setQualf); + pub const SETCEXT_PGWYCAPABILITIES: Nid = Nid(ffi::NID_setCext_PGWYcapabilities); + pub const SETCEXT_TOKENIDENTIFIER: Nid = Nid(ffi::NID_setCext_TokenIdentifier); + pub const SETCEXT_TRACK2DATA: Nid = Nid(ffi::NID_setCext_Track2Data); + pub const SETCEXT_TOKENTYPE: Nid = Nid(ffi::NID_setCext_TokenType); + pub const SETCEXT_ISSUERCAPABILITIES: Nid = Nid(ffi::NID_setCext_IssuerCapabilities); + pub const SETATTR_CERT: Nid = Nid(ffi::NID_setAttr_Cert); + pub const SETATTR_PGWYCAP: Nid = Nid(ffi::NID_setAttr_PGWYcap); + pub const SETATTR_TOKENTYPE: Nid = Nid(ffi::NID_setAttr_TokenType); + pub const SETATTR_ISSCAP: Nid = Nid(ffi::NID_setAttr_IssCap); + pub const SET_ROOTKEYTHUMB: Nid = Nid(ffi::NID_set_rootKeyThumb); + pub const SET_ADDPOLICY: Nid = Nid(ffi::NID_set_addPolicy); + pub const SETATTR_TOKEN_EMV: Nid = Nid(ffi::NID_setAttr_Token_EMV); + pub const SETATTR_TOKEN_B0PRIME: Nid = Nid(ffi::NID_setAttr_Token_B0Prime); + pub const SETATTR_ISSCAP_CVM: Nid = Nid(ffi::NID_setAttr_IssCap_CVM); + pub const SETATTR_ISSCAP_T2: Nid = Nid(ffi::NID_setAttr_IssCap_T2); + pub const SETATTR_ISSCAP_SIG: Nid = Nid(ffi::NID_setAttr_IssCap_Sig); + pub const SETATTR_GENCRYPTGRM: Nid = Nid(ffi::NID_setAttr_GenCryptgrm); + pub const SETATTR_T2ENC: Nid = Nid(ffi::NID_setAttr_T2Enc); + pub const SETATTR_T2CLEARTXT: Nid = Nid(ffi::NID_setAttr_T2cleartxt); + pub const SETATTR_TOKICCSIG: Nid = Nid(ffi::NID_setAttr_TokICCsig); + pub const SETATTR_SECDEVSIG: Nid = Nid(ffi::NID_setAttr_SecDevSig); + pub const SET_BRAND_IATA_ATA: Nid = Nid(ffi::NID_set_brand_IATA_ATA); + pub const SET_BRAND_DINERS: Nid = Nid(ffi::NID_set_brand_Diners); + pub const SET_BRAND_AMERICANEXPRESS: Nid = Nid(ffi::NID_set_brand_AmericanExpress); + pub const SET_BRAND_JCB: Nid = Nid(ffi::NID_set_brand_JCB); + pub const SET_BRAND_VISA: Nid = Nid(ffi::NID_set_brand_Visa); + pub const SET_BRAND_MASTERCARD: Nid = Nid(ffi::NID_set_brand_MasterCard); + pub const SET_BRAND_NOVUS: Nid = Nid(ffi::NID_set_brand_Novus); + pub const DES_CDMF: Nid = Nid(ffi::NID_des_cdmf); + pub const RSAOAEPENCRYPTIONSET: Nid = Nid(ffi::NID_rsaOAEPEncryptionSET); + pub const IPSEC3: Nid = Nid(ffi::NID_ipsec3); + pub const IPSEC4: Nid = Nid(ffi::NID_ipsec4); + pub const WHIRLPOOL: Nid = Nid(ffi::NID_whirlpool); + pub const CRYPTOPRO: Nid = Nid(ffi::NID_cryptopro); + pub const CRYPTOCOM: Nid = Nid(ffi::NID_cryptocom); + pub const ID_GOSTR3411_94_WITH_GOSTR3410_2001: Nid = + Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001); + pub const ID_GOSTR3411_94_WITH_GOSTR3410_94: Nid = + Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94); + pub const ID_GOSTR3411_94: Nid = Nid(ffi::NID_id_GostR3411_94); + pub const ID_HMACGOSTR3411_94: Nid = Nid(ffi::NID_id_HMACGostR3411_94); + pub const ID_GOSTR3410_2001: Nid = Nid(ffi::NID_id_GostR3410_2001); + pub const ID_GOSTR3410_94: Nid = Nid(ffi::NID_id_GostR3410_94); + pub const ID_GOST28147_89: Nid = Nid(ffi::NID_id_Gost28147_89); + pub const GOST89_CNT: Nid = Nid(ffi::NID_gost89_cnt); + pub const ID_GOST28147_89_MAC: Nid = Nid(ffi::NID_id_Gost28147_89_MAC); + pub const ID_GOSTR3411_94_PRF: Nid = Nid(ffi::NID_id_GostR3411_94_prf); + pub const ID_GOSTR3410_2001DH: Nid = Nid(ffi::NID_id_GostR3410_2001DH); + pub const ID_GOSTR3410_94DH: Nid = Nid(ffi::NID_id_GostR3410_94DH); + pub const ID_GOST28147_89_CRYPTOPRO_KEYMESHING: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_KeyMeshing); + pub const ID_GOST28147_89_NONE_KEYMESHING: Nid = Nid(ffi::NID_id_Gost28147_89_None_KeyMeshing); + pub const ID_GOSTR3411_94_TESTPARAMSET: Nid = Nid(ffi::NID_id_GostR3411_94_TestParamSet); + pub const ID_GOSTR3411_94_CRYPTOPROPARAMSET: Nid = + Nid(ffi::NID_id_GostR3411_94_CryptoProParamSet); + pub const ID_GOST28147_89_TESTPARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_TestParamSet); + pub const ID_GOST28147_89_CRYPTOPRO_A_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_A_ParamSet); + pub const ID_GOST28147_89_CRYPTOPRO_B_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_B_ParamSet); + pub const ID_GOST28147_89_CRYPTOPRO_C_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_C_ParamSet); + pub const ID_GOST28147_89_CRYPTOPRO_D_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_D_ParamSet); + pub const ID_GOST28147_89_CRYPTOPRO_OSCAR_1_1_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet); + pub const ID_GOST28147_89_CRYPTOPRO_OSCAR_1_0_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet); + pub const ID_GOST28147_89_CRYPTOPRO_RIC_1_PARAMSET: Nid = + Nid(ffi::NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet); + pub const ID_GOSTR3410_94_TESTPARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_TestParamSet); + pub const ID_GOSTR3410_94_CRYPTOPRO_A_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_A_ParamSet); + pub const ID_GOSTR3410_94_CRYPTOPRO_B_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_B_ParamSet); + pub const ID_GOSTR3410_94_CRYPTOPRO_C_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_C_ParamSet); + pub const ID_GOSTR3410_94_CRYPTOPRO_D_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_D_ParamSet); + pub const ID_GOSTR3410_94_CRYPTOPRO_XCHA_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchA_ParamSet); + pub const ID_GOSTR3410_94_CRYPTOPRO_XCHB_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchB_ParamSet); + pub const ID_GOSTR3410_94_CRYPTOPRO_XCHC_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchC_ParamSet); + pub const ID_GOSTR3410_2001_TESTPARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_TestParamSet); + pub const ID_GOSTR3410_2001_CRYPTOPRO_A_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_A_ParamSet); + pub const ID_GOSTR3410_2001_CRYPTOPRO_B_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_B_ParamSet); + pub const ID_GOSTR3410_2001_CRYPTOPRO_C_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_C_ParamSet); + pub const ID_GOSTR3410_2001_CRYPTOPRO_XCHA_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet); + pub const ID_GOSTR3410_2001_CRYPTOPRO_XCHB_PARAMSET: Nid = + Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet); + pub const ID_GOSTR3410_94_A: Nid = Nid(ffi::NID_id_GostR3410_94_a); + pub const ID_GOSTR3410_94_ABIS: Nid = Nid(ffi::NID_id_GostR3410_94_aBis); + pub const ID_GOSTR3410_94_B: Nid = Nid(ffi::NID_id_GostR3410_94_b); + pub const ID_GOSTR3410_94_BBIS: Nid = Nid(ffi::NID_id_GostR3410_94_bBis); + pub const ID_GOST28147_89_CC: Nid = Nid(ffi::NID_id_Gost28147_89_cc); + pub const ID_GOSTR3410_94_CC: Nid = Nid(ffi::NID_id_GostR3410_94_cc); + pub const ID_GOSTR3410_2001_CC: Nid = Nid(ffi::NID_id_GostR3410_2001_cc); + pub const ID_GOSTR3411_94_WITH_GOSTR3410_94_CC: Nid = + Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94_cc); + pub const ID_GOSTR3411_94_WITH_GOSTR3410_2001_CC: Nid = + Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001_cc); + pub const ID_GOSTR3410_2001_PARAMSET_CC: Nid = Nid(ffi::NID_id_GostR3410_2001_ParamSet_cc); + pub const CAMELLIA_128_CBC: Nid = Nid(ffi::NID_camellia_128_cbc); + pub const CAMELLIA_192_CBC: Nid = Nid(ffi::NID_camellia_192_cbc); + pub const CAMELLIA_256_CBC: Nid = Nid(ffi::NID_camellia_256_cbc); + pub const ID_CAMELLIA128_WRAP: Nid = Nid(ffi::NID_id_camellia128_wrap); + pub const ID_CAMELLIA192_WRAP: Nid = Nid(ffi::NID_id_camellia192_wrap); + pub const ID_CAMELLIA256_WRAP: Nid = Nid(ffi::NID_id_camellia256_wrap); + pub const CAMELLIA_128_ECB: Nid = Nid(ffi::NID_camellia_128_ecb); + pub const CAMELLIA_128_OFB128: Nid = Nid(ffi::NID_camellia_128_ofb128); + pub const CAMELLIA_128_CFB128: Nid = Nid(ffi::NID_camellia_128_cfb128); + pub const CAMELLIA_192_ECB: Nid = Nid(ffi::NID_camellia_192_ecb); + pub const CAMELLIA_192_OFB128: Nid = Nid(ffi::NID_camellia_192_ofb128); + pub const CAMELLIA_192_CFB128: Nid = Nid(ffi::NID_camellia_192_cfb128); + pub const CAMELLIA_256_ECB: Nid = Nid(ffi::NID_camellia_256_ecb); + pub const CAMELLIA_256_OFB128: Nid = Nid(ffi::NID_camellia_256_ofb128); + pub const CAMELLIA_256_CFB128: Nid = Nid(ffi::NID_camellia_256_cfb128); + pub const CAMELLIA_128_CFB1: Nid = Nid(ffi::NID_camellia_128_cfb1); + pub const CAMELLIA_192_CFB1: Nid = Nid(ffi::NID_camellia_192_cfb1); + pub const CAMELLIA_256_CFB1: Nid = Nid(ffi::NID_camellia_256_cfb1); + pub const CAMELLIA_128_CFB8: Nid = Nid(ffi::NID_camellia_128_cfb8); + pub const CAMELLIA_192_CFB8: Nid = Nid(ffi::NID_camellia_192_cfb8); + pub const CAMELLIA_256_CFB8: Nid = Nid(ffi::NID_camellia_256_cfb8); + pub const KISA: Nid = Nid(ffi::NID_kisa); + pub const SEED_ECB: Nid = Nid(ffi::NID_seed_ecb); + pub const SEED_CBC: Nid = Nid(ffi::NID_seed_cbc); + pub const SEED_CFB128: Nid = Nid(ffi::NID_seed_cfb128); + pub const SEED_OFB128: Nid = Nid(ffi::NID_seed_ofb128); + pub const HMAC: Nid = Nid(ffi::NID_hmac); + pub const CMAC: Nid = Nid(ffi::NID_cmac); + pub const RC4_HMAC_MD5: Nid = Nid(ffi::NID_rc4_hmac_md5); + pub const AES_128_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_128_cbc_hmac_sha1); + pub const AES_192_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_192_cbc_hmac_sha1); + pub const AES_256_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_256_cbc_hmac_sha1); +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/ocsp.rs cargo-0.26.0/vendor/openssl-0.10.6/src/ocsp.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/ocsp.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/ocsp.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,347 @@ +use ffi; +use foreign_types::ForeignTypeRef; +use libc::{c_int, c_long, c_ulong}; +use std::ptr; +use std::mem; + +use {cvt, cvt_p}; +use asn1::Asn1GeneralizedTimeRef; +use error::ErrorStack; +use hash::MessageDigest; +use stack::StackRef; +use x509::store::X509StoreRef; +use x509::{X509, X509Ref}; + +bitflags! { + pub struct OcspFlag: c_ulong { + const NO_CERTS = ffi::OCSP_NOCERTS; + const NO_INTERN = ffi::OCSP_NOINTERN; + const NO_CHAIN = ffi::OCSP_NOCHAIN; + const NO_VERIFY = ffi::OCSP_NOVERIFY; + const NO_EXPLICIT = ffi::OCSP_NOEXPLICIT; + const NO_CA_SIGN = ffi::OCSP_NOCASIGN; + const NO_DELEGATED = ffi::OCSP_NODELEGATED; + const NO_CHECKS = ffi::OCSP_NOCHECKS; + const TRUST_OTHER = ffi::OCSP_TRUSTOTHER; + const RESPID_KEY = ffi::OCSP_RESPID_KEY; + const NO_TIME = ffi::OCSP_NOTIME; + } +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct OcspResponseStatus(c_int); + +impl OcspResponseStatus { + pub fn from_raw(raw: c_int) -> OcspResponseStatus { + OcspResponseStatus(raw) + } + + pub fn as_raw(&self) -> c_int { + self.0 + } + + pub const SUCCESSFUL: OcspResponseStatus = + OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_SUCCESSFUL); + pub const MALFORMED_REQUEST: OcspResponseStatus = + OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_MALFORMEDREQUEST); + pub const INTERNAL_ERROR: OcspResponseStatus = + OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_INTERNALERROR); + pub const TRY_LATER: OcspResponseStatus = + OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_TRYLATER); + pub const SIG_REQUIRED: OcspResponseStatus = + OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_SIGREQUIRED); + pub const UNAUTHORIZED: OcspResponseStatus = + OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_UNAUTHORIZED); +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct OcspCertStatus(c_int); + +impl OcspCertStatus { + pub fn from_raw(raw: c_int) -> OcspCertStatus { + OcspCertStatus(raw) + } + + pub fn as_raw(&self) -> c_int { + self.0 + } + + pub const GOOD: OcspCertStatus = OcspCertStatus(ffi::V_OCSP_CERTSTATUS_GOOD); + pub const REVOKED: OcspCertStatus = OcspCertStatus(ffi::V_OCSP_CERTSTATUS_REVOKED); + pub const UNKNOWN: OcspCertStatus = OcspCertStatus(ffi::V_OCSP_CERTSTATUS_UNKNOWN); +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct OcspRevokedStatus(c_int); + +impl OcspRevokedStatus { + pub fn from_raw(raw: c_int) -> OcspRevokedStatus { + OcspRevokedStatus(raw) + } + + pub fn as_raw(&self) -> c_int { + self.0 + } + + pub const NO_STATUS: OcspRevokedStatus = OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_NOSTATUS); + pub const UNSPECIFIED: OcspRevokedStatus = + OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_UNSPECIFIED); + pub const KEY_COMPROMISE: OcspRevokedStatus = + OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_KEYCOMPROMISE); + pub const CA_COMPROMISE: OcspRevokedStatus = + OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_CACOMPROMISE); + pub const AFFILIATION_CHANGED: OcspRevokedStatus = + OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_AFFILIATIONCHANGED); + pub const STATUS_SUPERSEDED: OcspRevokedStatus = + OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_SUPERSEDED); + pub const STATUS_CESSATION_OF_OPERATION: OcspRevokedStatus = + OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_CESSATIONOFOPERATION); + pub const STATUS_CERTIFICATE_HOLD: OcspRevokedStatus = + OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_CERTIFICATEHOLD); + pub const REMOVE_FROM_CRL: OcspRevokedStatus = + OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_REMOVEFROMCRL); +} + +pub struct OcspStatus<'a> { + /// The overall status of the response. + pub status: OcspCertStatus, + /// If `status` is `CERT_STATUS_REVOKED`, the reason for the revocation. + pub reason: OcspRevokedStatus, + /// If `status` is `CERT_STATUS_REVOKED`, the time at which the certificate was revoked. + pub revocation_time: Option<&'a Asn1GeneralizedTimeRef>, + /// The time that this revocation check was performed. + pub this_update: &'a Asn1GeneralizedTimeRef, + /// The time at which this revocation check expires. + pub next_update: &'a Asn1GeneralizedTimeRef, +} + +impl<'a> OcspStatus<'a> { + /// Checks validity of the `this_update` and `next_update` fields. + /// + /// The `nsec` parameter specifies an amount of slack time that will be used when comparing + /// those times with the current time to account for delays and clock skew. + /// + /// The `maxsec` parameter limits the maximum age of the `this_update` parameter to prohibit + /// very old responses. + pub fn check_validity(&self, nsec: u32, maxsec: Option) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::OCSP_check_validity( + self.this_update.as_ptr(), + self.next_update.as_ptr(), + nsec as c_long, + maxsec.map(|n| n as c_long).unwrap_or(-1), + )).map(|_| ()) + } + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::OCSP_BASICRESP; + fn drop = ffi::OCSP_BASICRESP_free; + + pub struct OcspBasicResponse; + pub struct OcspBasicResponseRef; +} + +impl OcspBasicResponseRef { + /// Verifies the validity of the response. + /// + /// The `certs` parameter contains a set of certificates that will be searched when locating the + /// OCSP response signing certificate. Some responders do not include this in the response. + pub fn verify( + &self, + certs: &StackRef, + store: &X509StoreRef, + flags: OcspFlag, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::OCSP_basic_verify( + self.as_ptr(), + certs.as_ptr(), + store.as_ptr(), + flags.bits(), + )).map(|_| ()) + } + } + + /// Looks up the status for the specified certificate ID. + pub fn find_status<'a>(&'a self, id: &OcspCertIdRef) -> Option> { + unsafe { + let mut status = ffi::V_OCSP_CERTSTATUS_UNKNOWN; + let mut reason = ffi::OCSP_REVOKED_STATUS_NOSTATUS; + let mut revocation_time = ptr::null_mut(); + let mut this_update = ptr::null_mut(); + let mut next_update = ptr::null_mut(); + + let r = ffi::OCSP_resp_find_status( + self.as_ptr(), + id.as_ptr(), + &mut status, + &mut reason, + &mut revocation_time, + &mut this_update, + &mut next_update, + ); + if r == 1 { + let revocation_time = if revocation_time.is_null() { + None + } else { + Some(Asn1GeneralizedTimeRef::from_ptr(revocation_time)) + }; + Some(OcspStatus { + status: OcspCertStatus(status), + reason: OcspRevokedStatus(status), + revocation_time: revocation_time, + this_update: Asn1GeneralizedTimeRef::from_ptr(this_update), + next_update: Asn1GeneralizedTimeRef::from_ptr(next_update), + }) + } else { + None + } + } + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::OCSP_CERTID; + fn drop = ffi::OCSP_CERTID_free; + + pub struct OcspCertId; + pub struct OcspCertIdRef; +} + +impl OcspCertId { + /// Constructs a certificate ID for certificate `subject`. + pub fn from_cert( + digest: MessageDigest, + subject: &X509Ref, + issuer: &X509Ref, + ) -> Result { + unsafe { + cvt_p(ffi::OCSP_cert_to_id( + digest.as_ptr(), + subject.as_ptr(), + issuer.as_ptr(), + )).map(OcspCertId) + } + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::OCSP_RESPONSE; + fn drop = ffi::OCSP_RESPONSE_free; + + pub struct OcspResponse; + pub struct OcspResponseRef; +} + +impl OcspResponse { + /// Creates an OCSP response from the status and optional body. + /// + /// A body should only be provided if `status` is `RESPONSE_STATUS_SUCCESSFUL`. + pub fn create( + status: OcspResponseStatus, + body: Option<&OcspBasicResponseRef>, + ) -> Result { + unsafe { + ffi::init(); + + cvt_p(ffi::OCSP_response_create( + status.as_raw(), + body.map(|r| r.as_ptr()).unwrap_or(ptr::null_mut()), + )).map(OcspResponse) + } + } + + from_der! { + /// Deserializes a DER-encoded OCSP response. + /// + /// This corresponds to [`d2i_OCSP_RESPONSE`]. + /// + /// [`d2i_OCSP_RESPONSE`]: https://www.openssl.org/docs/man1.1.0/crypto/d2i_OCSP_RESPONSE.html + from_der, + OcspResponse, + ffi::d2i_OCSP_RESPONSE + } +} + +impl OcspResponseRef { + to_der! { + /// Serializes the response to its standard DER encoding. + /// + /// This corresponds to [`i2d_OCSP_RESPONSE`]. + /// + /// [`i2d_OCSP_RESPONSE`]: https://www.openssl.org/docs/man1.1.0/crypto/i2d_OCSP_RESPONSE.html + to_der, + ffi::i2d_OCSP_RESPONSE + } + + /// Returns the status of the response. + pub fn status(&self) -> OcspResponseStatus { + unsafe { OcspResponseStatus(ffi::OCSP_response_status(self.as_ptr())) } + } + + /// Returns the basic response. + /// + /// This will only succeed if `status()` returns `RESPONSE_STATUS_SUCCESSFUL`. + pub fn basic(&self) -> Result { + unsafe { cvt_p(ffi::OCSP_response_get1_basic(self.as_ptr())).map(OcspBasicResponse) } + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::OCSP_REQUEST; + fn drop = ffi::OCSP_REQUEST_free; + + pub struct OcspRequest; + pub struct OcspRequestRef; +} + +impl OcspRequest { + pub fn new() -> Result { + unsafe { + ffi::init(); + + cvt_p(ffi::OCSP_REQUEST_new()).map(OcspRequest) + } + } + + from_der! { + /// Deserializes a DER-encoded OCSP request. + /// + /// This corresponds to [`d2i_OCSP_REQUEST`]. + /// + /// [`d2i_OCSP_REQUEST`]: https://www.openssl.org/docs/man1.1.0/crypto/d2i_OCSP_REQUEST.html + from_der, + OcspRequest, + ffi::d2i_OCSP_REQUEST + } +} + +impl OcspRequestRef { + to_der! { + /// Serializes the request to its standard DER encoding. + /// + /// This corresponds to [`i2d_OCSP_REQUEST`]. + /// + /// [`i2d_OCSP_REQUEST`]: https://www.openssl.org/docs/man1.1.0/crypto/i2d_OCSP_REQUEST.html + to_der, + ffi::i2d_OCSP_REQUEST + } + + pub fn add_id(&mut self, id: OcspCertId) -> Result<&mut OcspOneReqRef, ErrorStack> { + unsafe { + let ptr = cvt_p(ffi::OCSP_request_add0_id(self.as_ptr(), id.as_ptr()))?; + mem::forget(id); + Ok(OcspOneReqRef::from_ptr_mut(ptr)) + } + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::OCSP_ONEREQ; + fn drop = ffi::OCSP_ONEREQ_free; + + pub struct OcspOneReq; + pub struct OcspOneReqRef; +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/pkcs12.rs cargo-0.26.0/vendor/openssl-0.10.6/src/pkcs12.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/pkcs12.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/pkcs12.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,287 @@ +//! PKCS #12 archives. + +use ffi; +use foreign_types::{ForeignType, ForeignTypeRef}; +use libc::c_int; +use std::ptr; +use std::ffi::CString; + +use {cvt, cvt_p}; +use pkey::{HasPrivate, PKey, PKeyRef, Private}; +use error::ErrorStack; +use x509::{X509, X509Ref}; +use stack::Stack; +use nid::Nid; + +foreign_type_and_impl_send_sync! { + type CType = ffi::PKCS12; + fn drop = ffi::PKCS12_free; + + pub struct Pkcs12; + pub struct Pkcs12Ref; +} + +impl Pkcs12Ref { + to_der! { + /// Serializes the `Pkcs12` to its standard DER encoding. + /// + /// This corresponds to [`i2d_PKCS12`]. + /// + /// [`i2d_PKCS12`]: https://www.openssl.org/docs/manmaster/man3/i2d_PKCS12.html + to_der, + ffi::i2d_PKCS12 + } + + /// Extracts the contents of the `Pkcs12`. + pub fn parse(&self, pass: &str) -> Result { + unsafe { + let pass = CString::new(pass.as_bytes()).unwrap(); + + let mut pkey = ptr::null_mut(); + let mut cert = ptr::null_mut(); + let mut chain = ptr::null_mut(); + + cvt(ffi::PKCS12_parse( + self.as_ptr(), + pass.as_ptr(), + &mut pkey, + &mut cert, + &mut chain, + ))?; + + let pkey = PKey::from_ptr(pkey); + let cert = X509::from_ptr(cert); + + let chain = if chain.is_null() { + None + } else { + Some(Stack::from_ptr(chain)) + }; + + Ok(ParsedPkcs12 { + pkey: pkey, + cert: cert, + chain: chain, + }) + } + } +} + +impl Pkcs12 { + from_der! { + /// Deserializes a DER-encoded PKCS#12 archive. + /// + /// This corresponds to [`d2i_PKCS12`]. + /// + /// [`d2i_PKCS12`]: https://www.openssl.org/docs/man1.1.0/crypto/d2i_PKCS12.html + from_der, + Pkcs12, + ffi::d2i_PKCS12 + } + + /// Creates a new builder for a protected pkcs12 certificate. + /// + /// This uses the defaults from the OpenSSL library: + /// + /// * `nid_key` - `nid::PBE_WITHSHA1AND3_KEY_TRIPLEDES_CBC` + /// * `nid_cert` - `nid::PBE_WITHSHA1AND40BITRC2_CBC` + /// * `iter` - `2048` + /// * `mac_iter` - `2048` + pub fn builder() -> Pkcs12Builder { + ffi::init(); + + Pkcs12Builder { + nid_key: Nid::UNDEF, //nid::PBE_WITHSHA1AND3_KEY_TRIPLEDES_CBC, + nid_cert: Nid::UNDEF, //nid::PBE_WITHSHA1AND40BITRC2_CBC, + iter: ffi::PKCS12_DEFAULT_ITER, + mac_iter: ffi::PKCS12_DEFAULT_ITER, + ca: None, + } + } +} + +pub struct ParsedPkcs12 { + pub pkey: PKey, + pub cert: X509, + pub chain: Option>, +} + +pub struct Pkcs12Builder { + nid_key: Nid, + nid_cert: Nid, + iter: c_int, + mac_iter: c_int, + ca: Option>, +} + +impl Pkcs12Builder { + /// The encryption algorithm that should be used for the key + pub fn key_algorithm(&mut self, nid: Nid) -> &mut Self { + self.nid_key = nid; + self + } + + /// The encryption algorithm that should be used for the cert + pub fn cert_algorithm(&mut self, nid: Nid) -> &mut Self { + self.nid_cert = nid; + self + } + + /// Key iteration count, default is 2048 as of this writing + pub fn key_iter(&mut self, iter: u32) -> &mut Self { + self.iter = iter as c_int; + self + } + + /// MAC iteration count, default is the same as key_iter. + /// + /// Old implementations don't understand MAC iterations greater than 1, (pre 1.0.1?), if such + /// compatibility is required this should be set to 1. + pub fn mac_iter(&mut self, mac_iter: u32) -> &mut Self { + self.mac_iter = mac_iter as c_int; + self + } + + /// An additional set of certificates to include in the archive beyond the one provided to + /// `build`. + pub fn ca(&mut self, ca: Stack) -> &mut Self { + self.ca = Some(ca); + self + } + + /// Builds the PKCS #12 object + /// + /// # Arguments + /// + /// * `password` - the password used to encrypt the key and certificate + /// * `friendly_name` - user defined name for the certificate + /// * `pkey` - key to store + /// * `cert` - certificate to store + pub fn build( + self, + password: &str, + friendly_name: &str, + pkey: &PKeyRef, + cert: &X509Ref, + ) -> Result + where + T: HasPrivate, + { + unsafe { + let pass = CString::new(password).unwrap(); + let friendly_name = CString::new(friendly_name).unwrap(); + let pkey = pkey.as_ptr(); + let cert = cert.as_ptr(); + let ca = self.ca + .as_ref() + .map(|ca| ca.as_ptr()) + .unwrap_or(ptr::null_mut()); + let nid_key = self.nid_key.as_raw(); + let nid_cert = self.nid_cert.as_raw(); + + // According to the OpenSSL docs, keytype is a non-standard extension for MSIE, + // It's values are KEY_SIG or KEY_EX, see the OpenSSL docs for more information: + // https://www.openssl.org/docs/man1.0.2/crypto/PKCS12_create.html + let keytype = 0; + + cvt_p(ffi::PKCS12_create( + pass.as_ptr() as *const _ as *mut _, + friendly_name.as_ptr() as *const _ as *mut _, + pkey, + cert, + ca, + nid_key, + nid_cert, + self.iter, + self.mac_iter, + keytype, + )).map(Pkcs12) + } + } +} + +#[cfg(test)] +mod test { + use hash::MessageDigest; + use hex; + + use asn1::Asn1Time; + use rsa::Rsa; + use pkey::PKey; + use nid::Nid; + use x509::{X509, X509Name}; + use x509::extension::KeyUsage; + + use super::*; + + #[test] + fn parse() { + let der = include_bytes!("../test/identity.p12"); + let pkcs12 = Pkcs12::from_der(der).unwrap(); + let parsed = pkcs12.parse("mypass").unwrap(); + + assert_eq!( + hex::encode(parsed.cert.fingerprint(MessageDigest::sha1()).unwrap()), + "59172d9313e84459bcff27f967e79e6e9217e584" + ); + + let chain = parsed.chain.unwrap(); + assert_eq!(chain.len(), 1); + assert_eq!( + hex::encode(chain[0].fingerprint(MessageDigest::sha1()).unwrap()), + "c0cbdf7cdd03c9773e5468e1f6d2da7d5cbb1875" + ); + } + + #[test] + fn parse_empty_chain() { + let der = include_bytes!("../test/keystore-empty-chain.p12"); + let pkcs12 = Pkcs12::from_der(der).unwrap(); + let parsed = pkcs12.parse("cassandra").unwrap(); + assert!(parsed.chain.is_none()); + } + + #[test] + fn create() { + let subject_name = "ns.example.com"; + let rsa = Rsa::generate(2048).unwrap(); + let pkey = PKey::from_rsa(rsa).unwrap(); + + let mut name = X509Name::builder().unwrap(); + name.append_entry_by_nid(Nid::COMMONNAME, subject_name) + .unwrap(); + let name = name.build(); + + let key_usage = KeyUsage::new().digital_signature().build().unwrap(); + + let mut builder = X509::builder().unwrap(); + builder.set_version(2).unwrap(); + builder + .set_not_before(&Asn1Time::days_from_now(0).unwrap()) + .unwrap(); + builder + .set_not_after(&Asn1Time::days_from_now(365).unwrap()) + .unwrap(); + builder.set_subject_name(&name).unwrap(); + builder.set_issuer_name(&name).unwrap(); + builder.append_extension(key_usage).unwrap(); + builder.set_pubkey(&pkey).unwrap(); + builder.sign(&pkey, MessageDigest::sha256()).unwrap(); + let cert = builder.build(); + + let pkcs12_builder = Pkcs12::builder(); + let pkcs12 = pkcs12_builder + .build("mypass", subject_name, &pkey, &cert) + .unwrap(); + let der = pkcs12.to_der().unwrap(); + + let pkcs12 = Pkcs12::from_der(&der).unwrap(); + let parsed = pkcs12.parse("mypass").unwrap(); + + assert_eq!( + parsed.cert.fingerprint(MessageDigest::sha1()).unwrap(), + cert.fingerprint(MessageDigest::sha1()).unwrap() + ); + assert!(parsed.pkey.public_eq(&pkey)); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/pkcs5.rs cargo-0.26.0/vendor/openssl-0.10.6/src/pkcs5.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/pkcs5.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/pkcs5.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,296 @@ +use libc::c_int; +use std::ptr; +use ffi; + +use cvt; +use hash::MessageDigest; +use symm::Cipher; +use error::ErrorStack; + +#[derive(Clone, Eq, PartialEq, Hash, Debug)] +pub struct KeyIvPair { + pub key: Vec, + pub iv: Option>, +} + +/// Derives a key and an IV from various parameters. +/// +/// If specified, `salt` must be 8 bytes in length. +/// +/// If the total key and IV length is less than 16 bytes and MD5 is used then +/// the algorithm is compatible with the key derivation algorithm from PKCS#5 +/// v1.5 or PBKDF1 from PKCS#5 v2.0. +/// +/// New applications should not use this and instead use +/// `pbkdf2_hmac` or another more modern key derivation algorithm. +pub fn bytes_to_key( + cipher: Cipher, + digest: MessageDigest, + data: &[u8], + salt: Option<&[u8]>, + count: i32, +) -> Result { + unsafe { + assert!(data.len() <= c_int::max_value() as usize); + let salt_ptr = match salt { + Some(salt) => { + assert_eq!(salt.len(), ffi::PKCS5_SALT_LEN as usize); + salt.as_ptr() + } + None => ptr::null(), + }; + + ffi::init(); + + let mut iv = cipher.iv_len().map(|l| vec![0; l]); + + let cipher = cipher.as_ptr(); + let digest = digest.as_ptr(); + + let len = cvt(ffi::EVP_BytesToKey( + cipher, + digest, + salt_ptr, + ptr::null(), + data.len() as c_int, + count.into(), + ptr::null_mut(), + ptr::null_mut(), + ))?; + + let mut key = vec![0; len as usize]; + let iv_ptr = iv.as_mut() + .map(|v| v.as_mut_ptr()) + .unwrap_or(ptr::null_mut()); + + cvt(ffi::EVP_BytesToKey( + cipher, + digest, + salt_ptr, + data.as_ptr(), + data.len() as c_int, + count as c_int, + key.as_mut_ptr(), + iv_ptr, + ))?; + + Ok(KeyIvPair { key: key, iv: iv }) + } +} + +/// Derives a key from a password and salt using the PBKDF2-HMAC algorithm with a digest function. +pub fn pbkdf2_hmac( + pass: &[u8], + salt: &[u8], + iter: usize, + hash: MessageDigest, + key: &mut [u8], +) -> Result<(), ErrorStack> { + unsafe { + assert!(pass.len() <= c_int::max_value() as usize); + assert!(salt.len() <= c_int::max_value() as usize); + assert!(key.len() <= c_int::max_value() as usize); + + ffi::init(); + cvt(ffi::PKCS5_PBKDF2_HMAC( + pass.as_ptr() as *const _, + pass.len() as c_int, + salt.as_ptr(), + salt.len() as c_int, + iter as c_int, + hash.as_ptr(), + key.len() as c_int, + key.as_mut_ptr(), + )).map(|_| ()) + } +} + +/// Derives a key from a password and salt using the scrypt algorithm. +/// +/// Requires OpenSSL 1.1.0 or newer. +#[cfg(any(ossl110))] +pub fn scrypt( + pass: &[u8], + salt: &[u8], + n: u64, + r: u64, + p: u64, + maxmem: u64, + key: &mut [u8], +) -> Result<(), ErrorStack> { + unsafe { + ffi::init(); + cvt(ffi::EVP_PBE_scrypt( + pass.as_ptr() as *const _, + pass.len(), + salt.as_ptr() as *const _, + salt.len(), + n, + r, + p, + maxmem, + key.as_mut_ptr() as *mut _, + key.len(), + )).map(|_| ()) + } +} + +#[cfg(test)] +mod tests { + use hash::MessageDigest; + use symm::Cipher; + + // Test vectors from + // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c + #[test] + fn pbkdf2_hmac_sha256() { + let mut buf = [0; 16]; + + super::pbkdf2_hmac(b"passwd", b"salt", 1, MessageDigest::sha256(), &mut buf).unwrap(); + assert_eq!( + buf, + &[ + 0x55_u8, 0xac_u8, 0x04_u8, 0x6e_u8, 0x56_u8, 0xe3_u8, 0x08_u8, 0x9f_u8, 0xec_u8, + 0x16_u8, 0x91_u8, 0xc2_u8, 0x25_u8, 0x44_u8, 0xb6_u8, 0x05_u8, + ][..] + ); + + super::pbkdf2_hmac( + b"Password", + b"NaCl", + 80000, + MessageDigest::sha256(), + &mut buf, + ).unwrap(); + assert_eq!( + buf, + &[ + 0x4d_u8, 0xdc_u8, 0xd8_u8, 0xf6_u8, 0x0b_u8, 0x98_u8, 0xbe_u8, 0x21_u8, 0x83_u8, + 0x0c_u8, 0xee_u8, 0x5e_u8, 0xf2_u8, 0x27_u8, 0x01_u8, 0xf9_u8, + ][..] + ); + } + + // Test vectors from + // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c + #[test] + fn pbkdf2_hmac_sha512() { + let mut buf = [0; 64]; + + super::pbkdf2_hmac(b"password", b"NaCL", 1, MessageDigest::sha512(), &mut buf).unwrap(); + assert_eq!( + &buf[..], + &[ + 0x73_u8, 0xde_u8, 0xcf_u8, 0xa5_u8, 0x8a_u8, 0xa2_u8, 0xe8_u8, 0x4f_u8, 0x94_u8, + 0x77_u8, 0x1a_u8, 0x75_u8, 0x73_u8, 0x6b_u8, 0xb8_u8, 0x8b_u8, 0xd3_u8, 0xc7_u8, + 0xb3_u8, 0x82_u8, 0x70_u8, 0xcf_u8, 0xb5_u8, 0x0c_u8, 0xb3_u8, 0x90_u8, 0xed_u8, + 0x78_u8, 0xb3_u8, 0x05_u8, 0x65_u8, 0x6a_u8, 0xf8_u8, 0x14_u8, 0x8e_u8, 0x52_u8, + 0x45_u8, 0x2b_u8, 0x22_u8, 0x16_u8, 0xb2_u8, 0xb8_u8, 0x09_u8, 0x8b_u8, 0x76_u8, + 0x1f_u8, 0xc6_u8, 0x33_u8, 0x60_u8, 0x60_u8, 0xa0_u8, 0x9f_u8, 0x76_u8, 0x41_u8, + 0x5e_u8, 0x9f_u8, 0x71_u8, 0xea_u8, 0x47_u8, 0xf9_u8, 0xe9_u8, 0x06_u8, 0x43_u8, + 0x06_u8, + ][..] + ); + + super::pbkdf2_hmac( + b"pass\0word", + b"sa\0lt", + 1, + MessageDigest::sha512(), + &mut buf, + ).unwrap(); + assert_eq!( + &buf[..], + &[ + 0x71_u8, 0xa0_u8, 0xec_u8, 0x84_u8, 0x2a_u8, 0xbd_u8, 0x5c_u8, 0x67_u8, 0x8b_u8, + 0xcf_u8, 0xd1_u8, 0x45_u8, 0xf0_u8, 0x9d_u8, 0x83_u8, 0x52_u8, 0x2f_u8, 0x93_u8, + 0x36_u8, 0x15_u8, 0x60_u8, 0x56_u8, 0x3c_u8, 0x4d_u8, 0x0d_u8, 0x63_u8, 0xb8_u8, + 0x83_u8, 0x29_u8, 0x87_u8, 0x10_u8, 0x90_u8, 0xe7_u8, 0x66_u8, 0x04_u8, 0xa4_u8, + 0x9a_u8, 0xf0_u8, 0x8f_u8, 0xe7_u8, 0xc9_u8, 0xf5_u8, 0x71_u8, 0x56_u8, 0xc8_u8, + 0x79_u8, 0x09_u8, 0x96_u8, 0xb2_u8, 0x0f_u8, 0x06_u8, 0xbc_u8, 0x53_u8, 0x5e_u8, + 0x5a_u8, 0xb5_u8, 0x44_u8, 0x0d_u8, 0xf7_u8, 0xe8_u8, 0x78_u8, 0x29_u8, 0x6f_u8, + 0xa7_u8, + ][..] + ); + + super::pbkdf2_hmac( + b"passwordPASSWORDpassword", + b"salt\0\0\0", + 50, + MessageDigest::sha512(), + &mut buf, + ).unwrap(); + assert_eq!( + &buf[..], + &[ + 0x01_u8, 0x68_u8, 0x71_u8, 0xa4_u8, 0xc4_u8, 0xb7_u8, 0x5f_u8, 0x96_u8, 0x85_u8, + 0x7f_u8, 0xd2_u8, 0xb9_u8, 0xf8_u8, 0xca_u8, 0x28_u8, 0x02_u8, 0x3b_u8, 0x30_u8, + 0xee_u8, 0x2a_u8, 0x39_u8, 0xf5_u8, 0xad_u8, 0xca_u8, 0xc8_u8, 0xc9_u8, 0x37_u8, + 0x5f_u8, 0x9b_u8, 0xda_u8, 0x1c_u8, 0xcd_u8, 0x1b_u8, 0x6f_u8, 0x0b_u8, 0x2f_u8, + 0xc3_u8, 0xad_u8, 0xda_u8, 0x50_u8, 0x54_u8, 0x12_u8, 0xe7_u8, 0x9d_u8, 0x89_u8, + 0x00_u8, 0x56_u8, 0xc6_u8, 0x2e_u8, 0x52_u8, 0x4c_u8, 0x7d_u8, 0x51_u8, 0x15_u8, + 0x4b_u8, 0x1a_u8, 0x85_u8, 0x34_u8, 0x57_u8, 0x5b_u8, 0xd0_u8, 0x2d_u8, 0xee_u8, + 0x39_u8, + ][..] + ); + } + + #[test] + fn bytes_to_key() { + let salt = [16_u8, 34_u8, 19_u8, 23_u8, 141_u8, 4_u8, 207_u8, 221_u8]; + + let data = [ + 143_u8, 210_u8, 75_u8, 63_u8, 214_u8, 179_u8, 155_u8, 241_u8, 242_u8, 31_u8, 154_u8, + 56_u8, 198_u8, 145_u8, 192_u8, 64_u8, 2_u8, 245_u8, 167_u8, 220_u8, 55_u8, 119_u8, + 233_u8, 136_u8, 139_u8, 27_u8, 71_u8, 242_u8, 119_u8, 175_u8, 65_u8, 207_u8, + ]; + + let expected_key = vec![ + 249_u8, 115_u8, 114_u8, 97_u8, 32_u8, 213_u8, 165_u8, 146_u8, 58_u8, 87_u8, 234_u8, + 3_u8, 43_u8, 250_u8, 97_u8, 114_u8, 26_u8, 98_u8, 245_u8, 246_u8, 238_u8, 177_u8, + 229_u8, 161_u8, 183_u8, 224_u8, 174_u8, 3_u8, 6_u8, 244_u8, 236_u8, 255_u8, + ]; + let expected_iv = vec![ + 4_u8, 223_u8, 153_u8, 219_u8, 28_u8, 142_u8, 234_u8, 68_u8, 227_u8, 69_u8, 98_u8, + 107_u8, 208_u8, 14_u8, 236_u8, 60_u8, + ]; + + assert_eq!( + super::bytes_to_key( + Cipher::aes_256_cbc(), + MessageDigest::sha1(), + &data, + Some(&salt), + 1, + ).unwrap(), + super::KeyIvPair { + key: expected_key, + iv: Some(expected_iv), + } + ); + } + + #[test] + #[cfg(any(ossl110))] + fn scrypt() { + use hex; + + let pass = "pleaseletmein"; + let salt = "SodiumChloride"; + let expected = + "7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613\ + f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887"; + + let mut actual = [0; 64]; + super::scrypt( + pass.as_bytes(), + salt.as_bytes(), + 16384, + 8, + 1, + 0, + &mut actual, + ).unwrap(); + assert_eq!(hex::encode(&actual[..]), expected); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/pkey.rs cargo-0.26.0/vendor/openssl-0.10.6/src/pkey.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/pkey.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/pkey.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,658 @@ +//! Public/private key processing. +//! +//! Asymmetric public key algorithms solve the problem of establishing and sharing +//! secret keys to securely send and receive messages. +//! This system uses a pair of keys: a public key, which can be freely +//! distributed, and a private key, which is kept to oneself. An entity may +//! encrypt information using a user's public key. The encrypted information can +//! only be deciphered using that user's private key. +//! +//! This module offers support for five popular algorithms: +//! +//! * RSA +//! +//! * DSA +//! +//! * Diffie-Hellman +//! +//! * Elliptic Curves +//! +//! * HMAC +//! +//! These algorithms rely on hard mathematical problems - namely integer factorization, +//! discrete logarithms, and elliptic curve relationships - that currently do not +//! yield efficient solutions. This property ensures the security of these +//! cryptographic algorithms. +//! +//! # Example +//! +//! Generate a 2048-bit RSA public/private key pair and print the public key. +//! +//! ```rust +//! +//! extern crate openssl; +//! +//! use openssl::rsa::Rsa; +//! use openssl::pkey::PKey; +//! use std::str; +//! +//! fn main() { +//! let rsa = Rsa::generate(2048).unwrap(); +//! let pkey = PKey::from_rsa(rsa).unwrap(); +//! +//! let pub_key: Vec = pkey.public_key_to_pem().unwrap(); +//! println!("{:?}", str::from_utf8(pub_key.as_slice()).unwrap()); +//! } +//! ``` + +use libc::c_int; +use std::ptr; +use std::mem; +use std::ffi::CString; +use ffi; +use foreign_types::{ForeignType, ForeignTypeRef}; + +use {cvt, cvt_p}; +use bio::MemBioSlice; +use dh::Dh; +use dsa::Dsa; +use ec::EcKey; +use rsa::Rsa; +use error::ErrorStack; +use util::{invoke_passwd_cb, CallbackState}; + +/// A tag type indicating that a key only has parameters. +pub enum Params {} + +/// A tag type indicating that a key only has public components. +pub enum Public {} + +/// A tag type indicating that a key has private components. +pub enum Private {} + +/// An identifier of a kind of key. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct Id(c_int); + +impl Id { + /// Creates a `Id` from an integer representation. + pub fn from_raw(value: c_int) -> Id { + Id(value) + } + + /// Returns the integer representation of the `Id`. + pub fn as_raw(&self) -> c_int { + self.0 + } + + pub const RSA: Id = Id(ffi::EVP_PKEY_RSA); + pub const HMAC: Id = Id(ffi::EVP_PKEY_HMAC); + pub const DSA: Id = Id(ffi::EVP_PKEY_DSA); + pub const DH: Id = Id(ffi::EVP_PKEY_DH); + pub const EC: Id = Id(ffi::EVP_PKEY_EC); +} + +/// A trait indicating that a key has parameters. +pub unsafe trait HasParams {} + +unsafe impl HasParams for Params {} + +unsafe impl HasParams for T +where + T: HasPublic, +{ +} + +/// A trait indicating that a key has public components. +pub unsafe trait HasPublic {} + +unsafe impl HasPublic for Public {} + +unsafe impl HasPublic for T +where + T: HasPrivate, +{ +} + +/// A trait indicating that a key has private components. +pub unsafe trait HasPrivate {} + +unsafe impl HasPrivate for Private {} + +generic_foreign_type_and_impl_send_sync! { + type CType = ffi::EVP_PKEY; + fn drop = ffi::EVP_PKEY_free; + + /// A public or private key. + pub struct PKey; + /// Reference to `PKey`. + pub struct PKeyRef; +} + +impl PKeyRef { + /// Returns a copy of the internal RSA key. + /// + /// This corresponds to [`EVP_PKEY_get1_RSA`]. + /// + /// [`EVP_PKEY_get1_RSA`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_get1_RSA.html + pub fn rsa(&self) -> Result, ErrorStack> { + unsafe { + let rsa = cvt_p(ffi::EVP_PKEY_get1_RSA(self.as_ptr()))?; + Ok(Rsa::from_ptr(rsa)) + } + } + + /// Returns a copy of the internal DSA key. + /// + /// This corresponds to [`EVP_PKEY_get1_DSA`]. + /// + /// [`EVP_PKEY_get1_DSA`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_get1_DSA.html + pub fn dsa(&self) -> Result, ErrorStack> { + unsafe { + let dsa = cvt_p(ffi::EVP_PKEY_get1_DSA(self.as_ptr()))?; + Ok(Dsa::from_ptr(dsa)) + } + } + + /// Returns a copy of the internal DH key. + /// + /// This corresponds to [`EVP_PKEY_get1_DH`]. + /// + /// [`EVP_PKEY_get1_DH`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_get1_DH.html + pub fn dh(&self) -> Result, ErrorStack> { + unsafe { + let dh = cvt_p(ffi::EVP_PKEY_get1_DH(self.as_ptr()))?; + Ok(Dh::from_ptr(dh)) + } + } + + /// Returns a copy of the internal elliptic curve key. + /// + /// This corresponds to [`EVP_PKEY_get1_EC_KEY`]. + /// + /// [`EVP_PKEY_get1_EC_KEY`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_get1_EC_KEY.html + pub fn ec_key(&self) -> Result, ErrorStack> { + unsafe { + let ec_key = cvt_p(ffi::EVP_PKEY_get1_EC_KEY(self.as_ptr()))?; + Ok(EcKey::from_ptr(ec_key)) + } + } + + /// Returns the `Id` that represents the type of this key. + /// + /// This corresponds to [`EVP_PKEY_id`]. + /// + /// [`EVP_PKEY_id`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_id.html + pub fn id(&self) -> Id { + unsafe { Id::from_raw(ffi::EVP_PKEY_id(self.as_ptr())) } + } +} + +impl PKeyRef +where + T: HasPublic, +{ + to_pem! { + /// Serializes the public key into a PEM-encoded SubjectPublicKeyInfo structure. + /// + /// The output will have a header of `-----BEGIN PUBLIC KEY-----`. + /// + /// This corresponds to [`PEM_write_bio_PUBKEY`]. + /// + /// [`PEM_write_bio_PUBKEY`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_write_bio_PUBKEY.html + public_key_to_pem, + ffi::PEM_write_bio_PUBKEY + } + + to_der! { + /// Serializes the public key into a DER-encoded SubjectPublicKeyInfo structure. + /// + /// This corresponds to [`i2d_PUBKEY`]. + /// + /// [`i2d_PUBKEY`]: https://www.openssl.org/docs/man1.1.0/crypto/i2d_PUBKEY.html + public_key_to_der, + ffi::i2d_PUBKEY + } + + /// Returns the size of the key. + /// + /// This corresponds to the bit length of the modulus of an RSA key, and the bit length of the + /// group order for an elliptic curve key, for example. + pub fn bits(&self) -> u32 { + unsafe { ffi::EVP_PKEY_bits(self.as_ptr()) as u32 } + } + + /// Compares the public component of this key with another. + pub fn public_eq(&self, other: &PKeyRef) -> bool + where + U: HasPublic, + { + unsafe { ffi::EVP_PKEY_cmp(self.as_ptr(), other.as_ptr()) == 1 } + } +} + +impl PKeyRef +where + T: HasPrivate, +{ + private_key_to_pem! { + /// Serializes the private key to a PEM-encoded PKCS#8 PrivateKeyInfo structure. + /// + /// The output will have a header of `-----BEGIN PRIVATE KEY-----`. + /// + /// This corresponds to [`PEM_write_bio_PKCS8PrivateKey`]. + /// + /// [`PEM_write_bio_PKCS8PrivateKey`]: https://www.openssl.org/docs/man1.0.2/crypto/PEM_write_bio_PKCS8PrivateKey.html + private_key_to_pem_pkcs8, + /// Serializes the private key to a PEM-encoded PKCS#8 EncryptedPrivateKeyInfo structure. + /// + /// The output will have a header of `-----BEGIN ENCRYPTED PRIVATE KEY-----`. + /// + /// This corresponds to [`PEM_write_bio_PKCS8PrivateKey`]. + /// + /// [`PEM_write_bio_PKCS8PrivateKey`]: https://www.openssl.org/docs/man1.0.2/crypto/PEM_write_bio_PKCS8PrivateKey.html + private_key_to_pem_pkcs8_passphrase, + ffi::PEM_write_bio_PKCS8PrivateKey + } + + to_der! { + /// Serializes the private key to a DER-encoded key type specific format. + /// + /// This corresponds to [`i2d_PrivateKey`]. + /// + /// [`i2d_PrivateKey`]: https://www.openssl.org/docs/man1.0.2/crypto/i2d_PrivateKey.html + private_key_to_der, + ffi::i2d_PrivateKey + } +} + +impl PKey { + /// Creates a new `PKey` containing an RSA key. + /// + /// This corresponds to [`EVP_PKEY_assign_RSA`]. + /// + /// [`EVP_PKEY_assign_RSA`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_assign_RSA.html + pub fn from_rsa(rsa: Rsa) -> Result, ErrorStack> { + unsafe { + let evp = cvt_p(ffi::EVP_PKEY_new())?; + let pkey = PKey::from_ptr(evp); + cvt(ffi::EVP_PKEY_assign( + pkey.0, + ffi::EVP_PKEY_RSA, + rsa.as_ptr() as *mut _, + ))?; + mem::forget(rsa); + Ok(pkey) + } + } + + /// Creates a new `PKey` containing a DSA key. + /// + /// This corresponds to [`EVP_PKEY_assign_DSA`]. + /// + /// [`EVP_PKEY_assign_DSA`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_assign_DSA.html + pub fn from_dsa(dsa: Dsa) -> Result, ErrorStack> { + unsafe { + let evp = cvt_p(ffi::EVP_PKEY_new())?; + let pkey = PKey::from_ptr(evp); + cvt(ffi::EVP_PKEY_assign( + pkey.0, + ffi::EVP_PKEY_DSA, + dsa.as_ptr() as *mut _, + ))?; + mem::forget(dsa); + Ok(pkey) + } + } + + /// Creates a new `PKey` containing a Diffie-Hellman key. + /// + /// This corresponds to [`EVP_PKEY_assign_DH`]. + /// + /// [`EVP_PKEY_assign_DH`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_assign_DH.html + pub fn from_dh(dh: Dh) -> Result, ErrorStack> { + unsafe { + let evp = cvt_p(ffi::EVP_PKEY_new())?; + let pkey = PKey::from_ptr(evp); + cvt(ffi::EVP_PKEY_assign( + pkey.0, + ffi::EVP_PKEY_DH, + dh.as_ptr() as *mut _, + ))?; + mem::forget(dh); + Ok(pkey) + } + } + + /// Creates a new `PKey` containing an elliptic curve key. + /// + /// This corresponds to [`EVP_PKEY_assign_EC_KEY`]. + /// + /// [`EVP_PKEY_assign_EC_KEY`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_assign_EC_KEY.html + pub fn from_ec_key(ec_key: EcKey) -> Result, ErrorStack> { + unsafe { + let evp = cvt_p(ffi::EVP_PKEY_new())?; + let pkey = PKey::from_ptr(evp); + cvt(ffi::EVP_PKEY_assign( + pkey.0, + ffi::EVP_PKEY_EC, + ec_key.as_ptr() as *mut _, + ))?; + mem::forget(ec_key); + Ok(pkey) + } + } +} + +impl PKey { + /// Creates a new `PKey` containing an HMAC key. + /// + /// # Note + /// + /// To compute HMAC values, use the `sign` module. + pub fn hmac(key: &[u8]) -> Result, ErrorStack> { + unsafe { + assert!(key.len() <= c_int::max_value() as usize); + let key = cvt_p(ffi::EVP_PKEY_new_mac_key( + ffi::EVP_PKEY_HMAC, + ptr::null_mut(), + key.as_ptr() as *const _, + key.len() as c_int, + ))?; + Ok(PKey::from_ptr(key)) + } + } + + /// Creates a new `PKey` containing a CMAC key. + /// + /// Requires OpenSSL 1.1.0 or newer. + /// + /// # Note + /// + /// To compute CMAC values, use the `sign` module. + #[cfg(ossl110)] + pub fn cmac(cipher: &::symm::Cipher, key: &[u8]) -> Result, ErrorStack> { + unsafe { + assert!(key.len() <= c_int::max_value() as usize); + let kctx = cvt_p(ffi::EVP_PKEY_CTX_new_id( + ffi::EVP_PKEY_CMAC, + ptr::null_mut(), + ))?; + + let ret = (|| { + cvt(ffi::EVP_PKEY_keygen_init(kctx))?; + + // Set cipher for cmac + cvt(ffi::EVP_PKEY_CTX_ctrl( + kctx, + -1, + ffi::EVP_PKEY_OP_KEYGEN, + ffi::EVP_PKEY_CTRL_CIPHER, + 0, + cipher.as_ptr() as *mut _, + ))?; + + // Set the key data + cvt(ffi::EVP_PKEY_CTX_ctrl( + kctx, + -1, + ffi::EVP_PKEY_OP_KEYGEN, + ffi::EVP_PKEY_CTRL_SET_MAC_KEY, + key.len() as c_int, + key.as_ptr() as *mut _, + ))?; + Ok(()) + })(); + + if let Err(e) = ret { + // Free memory + ffi::EVP_PKEY_CTX_free(kctx); + return Err(e); + } + + // Generate key + let mut key = ptr::null_mut(); + let ret = cvt(ffi::EVP_PKEY_keygen(kctx, &mut key)); + + // Free memory + ffi::EVP_PKEY_CTX_free(kctx); + + if let Err(e) = ret { + return Err(e); + } + + Ok(PKey::from_ptr(key)) + } + } + + private_key_from_pem! { + /// Deserializes a private key from a PEM-encoded key type specific format. + /// + /// This corresponds to [`PEM_read_bio_PrivateKey`]. + /// + /// [`PEM_read_bio_PrivateKey`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_read_bio_PrivateKey.html + private_key_from_pem, + + /// Deserializes a private key from a PEM-encoded encrypted key type specific format. + /// + /// This corresponds to [`PEM_read_bio_PrivateKey`]. + /// + /// [`PEM_read_bio_PrivateKey`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_read_bio_PrivateKey.html + private_key_from_pem_passphrase, + + /// Deserializes a private key from a PEM-encoded encrypted key type specific format. + /// + /// The callback should fill the password into the provided buffer and return its length. + /// + /// This corresponds to [`PEM_read_bio_PrivateKey`]. + /// + /// [`PEM_read_bio_PrivateKey`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_read_bio_PrivateKey.html + private_key_from_pem_callback, + PKey, + ffi::PEM_read_bio_PrivateKey + } + + from_der! { + /// Decodes a DER-encoded private key. + /// + /// This function will automatically attempt to detect the underlying key format, and + /// supports the unencrypted PKCS#8 PrivateKeyInfo structures as well as key type specific + /// formats. + /// + /// This corresponds to [`d2i_AutoPrivateKey`]. + /// + /// [`d2i_AutoPrivateKey`]: https://www.openssl.org/docs/man1.0.2/crypto/d2i_AutoPrivateKey.html + private_key_from_der, + PKey, + ffi::d2i_AutoPrivateKey + } + + /// Deserializes a DER-formatted PKCS#8 private key, using a callback to retrieve the password + /// if the key is encrpyted. + /// + /// The callback should copy the password into the provided buffer and return the number of + /// bytes written. + pub fn private_key_from_pkcs8_callback( + der: &[u8], + callback: F, + ) -> Result, ErrorStack> + where + F: FnOnce(&mut [u8]) -> Result, + { + unsafe { + ffi::init(); + let mut cb = CallbackState::new(callback); + let bio = MemBioSlice::new(der)?; + cvt_p(ffi::d2i_PKCS8PrivateKey_bio( + bio.as_ptr(), + ptr::null_mut(), + Some(invoke_passwd_cb::), + &mut cb as *mut _ as *mut _, + )).map(|p| PKey::from_ptr(p)) + } + } + + /// Deserializes a DER-formatted PKCS#8 private key, using the supplied password if the key is + /// encrypted. + /// + /// # Panics + /// + /// Panics if `passphrase` contains an embedded null. + pub fn private_key_from_pkcs8_passphrase( + der: &[u8], + passphrase: &[u8], + ) -> Result, ErrorStack> { + unsafe { + ffi::init(); + let bio = MemBioSlice::new(der)?; + let passphrase = CString::new(passphrase).unwrap(); + cvt_p(ffi::d2i_PKCS8PrivateKey_bio( + bio.as_ptr(), + ptr::null_mut(), + None, + passphrase.as_ptr() as *const _ as *mut _, + )).map(|p| PKey::from_ptr(p)) + } + } +} + +impl PKey { + from_pem! { + /// Decodes a PEM-encoded SubjectPublicKeyInfo structure. + /// + /// The input should have a header of `-----BEGIN PUBLIC KEY-----`. + /// + /// This corresponds to [`PEM_read_bio_PUBKEY`]. + /// + /// [`PEM_read_bio_PUBKEY`]: https://www.openssl.org/docs/man1.0.2/crypto/PEM_read_bio_PUBKEY.html + public_key_from_pem, + PKey, + ffi::PEM_read_bio_PUBKEY + } + + from_der! { + /// Decodes a DER-encoded SubjectPublicKeyInfo structure. + /// + /// This corresponds to [`d2i_PUBKEY`]. + /// + /// [`d2i_PUBKEY`]: https://www.openssl.org/docs/man1.1.0/crypto/d2i_PUBKEY.html + public_key_from_der, + PKey, + ffi::d2i_PUBKEY + } +} + +#[cfg(test)] +mod tests { + use symm::Cipher; + use dh::Dh; + use dsa::Dsa; + use ec::EcKey; + use rsa::Rsa; + use nid::Nid; + + use super::*; + + #[test] + fn test_to_password() { + let rsa = Rsa::generate(2048).unwrap(); + let pkey = PKey::from_rsa(rsa).unwrap(); + let pem = pkey.private_key_to_pem_pkcs8_passphrase(Cipher::aes_128_cbc(), b"foobar") + .unwrap(); + PKey::private_key_from_pem_passphrase(&pem, b"foobar").unwrap(); + assert!(PKey::private_key_from_pem_passphrase(&pem, b"fizzbuzz").is_err()); + } + + #[test] + fn test_encrypted_pkcs8_passphrase() { + let key = include_bytes!("../test/pkcs8.der"); + PKey::private_key_from_pkcs8_passphrase(key, b"mypass").unwrap(); + } + + #[test] + fn test_encrypted_pkcs8_callback() { + let mut password_queried = false; + let key = include_bytes!("../test/pkcs8.der"); + PKey::private_key_from_pkcs8_callback(key, |password| { + password_queried = true; + password[..6].copy_from_slice(b"mypass"); + Ok(6) + }).unwrap(); + assert!(password_queried); + } + + #[test] + fn test_private_key_from_pem() { + let key = include_bytes!("../test/key.pem"); + PKey::private_key_from_pem(key).unwrap(); + } + + #[test] + fn test_public_key_from_pem() { + let key = include_bytes!("../test/key.pem.pub"); + PKey::public_key_from_pem(key).unwrap(); + } + + #[test] + fn test_public_key_from_der() { + let key = include_bytes!("../test/key.der.pub"); + PKey::public_key_from_der(key).unwrap(); + } + + #[test] + fn test_private_key_from_der() { + let key = include_bytes!("../test/key.der"); + PKey::private_key_from_der(key).unwrap(); + } + + #[test] + fn test_pem() { + let key = include_bytes!("../test/key.pem"); + let key = PKey::private_key_from_pem(key).unwrap(); + + let priv_key = key.private_key_to_pem_pkcs8().unwrap(); + let pub_key = key.public_key_to_pem().unwrap(); + + // As a super-simple verification, just check that the buffers contain + // the `PRIVATE KEY` or `PUBLIC KEY` strings. + assert!(priv_key.windows(11).any(|s| s == b"PRIVATE KEY")); + assert!(pub_key.windows(10).any(|s| s == b"PUBLIC KEY")); + } + + #[test] + fn test_rsa_accessor() { + let rsa = Rsa::generate(2048).unwrap(); + let pkey = PKey::from_rsa(rsa).unwrap(); + pkey.rsa().unwrap(); + assert_eq!(pkey.id(), Id::RSA); + assert!(pkey.dsa().is_err()); + } + + #[test] + fn test_dsa_accessor() { + let dsa = Dsa::generate(2048).unwrap(); + let pkey = PKey::from_dsa(dsa).unwrap(); + pkey.dsa().unwrap(); + assert_eq!(pkey.id(), Id::DSA); + assert!(pkey.rsa().is_err()); + } + + #[test] + fn test_dh_accessor() { + let dh = include_bytes!("../test/dhparams.pem"); + let dh = Dh::params_from_pem(dh).unwrap(); + let pkey = PKey::from_dh(dh).unwrap(); + pkey.dh().unwrap(); + assert_eq!(pkey.id(), Id::DH); + assert!(pkey.rsa().is_err()); + } + + #[test] + fn test_ec_key_accessor() { + let ec_key = EcKey::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + let pkey = PKey::from_ec_key(ec_key).unwrap(); + pkey.ec_key().unwrap(); + assert_eq!(pkey.id(), Id::EC); + assert!(pkey.rsa().is_err()); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/rand.rs cargo-0.26.0/vendor/openssl-0.10.6/src/rand.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/rand.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/rand.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,52 @@ +//! Utilities for secure random number generation. +//! +//! # Examples +//! +//! To generate a buffer with cryptographically strong bytes: +//! +//! ``` +//! use openssl::rand::rand_bytes; +//! +//! let mut buf = [0; 256]; +//! rand_bytes(&mut buf).unwrap(); +//! ``` +use libc::c_int; +use ffi; + +use cvt; +use error::ErrorStack; + +/// Fill buffer with cryptographically strong pseudo-random bytes. +/// +/// # Examples +/// +/// To generate a buffer with cryptographically strong bytes: +/// +/// ``` +/// use openssl::rand::rand_bytes; +/// +/// let mut buf = [0; 256]; +/// rand_bytes(&mut buf).unwrap(); +/// ``` +/// +/// # External OpenSSL Documentation +/// +/// [RAND_bytes](https://www.openssl.org/docs/man1.1.0/crypto/RAND_bytes.html) +pub fn rand_bytes(buf: &mut [u8]) -> Result<(), ErrorStack> { + unsafe { + ffi::init(); + assert!(buf.len() <= c_int::max_value() as usize); + cvt(ffi::RAND_bytes(buf.as_mut_ptr(), buf.len() as c_int)).map(|_| ()) + } +} + +#[cfg(test)] +mod tests { + use super::rand_bytes; + + #[test] + fn test_rand_bytes() { + let mut buf = [0; 32]; + rand_bytes(&mut buf).unwrap(); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/rsa.rs cargo-0.26.0/vendor/openssl-0.10.6/src/rsa.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/rsa.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/rsa.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,809 @@ +//! Rivest–Shamir–Adleman cryptosystem +//! +//! RSA is one of the earliest asymmetric public key encryption schemes. +//! Like many other cryptosystems, RSA relies on the presumed difficulty of a hard +//! mathematical problem, namely factorization of the product of two large prime +//! numbers. At the moment there does exist an algorithm that can factor such +//! large numbers in reasonable time. RSA is used in a wide variety of +//! applications including digital signatures and key exchanges such as +//! establishing a TLS/SSL connection. +//! +//! The RSA acronym is derived from the first letters of the surnames of the +//! algorithm's founding trio. +//! +//! # Example +//! +//! Generate a 2048-bit RSA key pair and use the public key to encrypt some data. +//! +//! ```rust +//! +//! extern crate openssl; +//! +//! use openssl::rsa::{Rsa, Padding}; +//! +//! fn main() { +//! let rsa = Rsa::generate(2048).unwrap(); +//! let data: Vec = String::from("foobar").into_bytes(); +//! let mut encrypted_data: Vec = vec![0; 512]; +//! let padding = Padding::PKCS1; +//! let _ = rsa.public_encrypt(&data, encrypted_data.as_mut_slice(), padding).unwrap(); +//! } +//! ``` +use ffi; +use std::fmt; +use std::ptr; +use std::mem; +use libc::c_int; +use foreign_types::{ForeignType, ForeignTypeRef}; + +use {cvt, cvt_n, cvt_p}; +use bn::{BigNum, BigNumRef}; +use error::ErrorStack; +use pkey::{HasPrivate, HasPublic, Private, Public}; + +/// Type of encryption padding to use. +/// +/// Random length padding is primarily used to prevent attackers from +/// predicting or knowing the exact length of a plaintext message that +/// can possibly lead to breaking encryption. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct Padding(c_int); + +impl Padding { + /// Creates a `Padding` from an integer representation. + pub fn from_raw(value: c_int) -> Padding { + Padding(value) + } + + /// Returns the integer representation of `Padding`. + pub fn as_raw(&self) -> c_int { + self.0 + } + + pub const NONE: Padding = Padding(ffi::RSA_NO_PADDING); + pub const PKCS1: Padding = Padding(ffi::RSA_PKCS1_PADDING); + pub const PKCS1_OAEP: Padding = Padding(ffi::RSA_PKCS1_OAEP_PADDING); + pub const PKCS1_PSS: Padding = Padding(ffi::RSA_PKCS1_PSS_PADDING); +} + +generic_foreign_type_and_impl_send_sync! { + type CType = ffi::RSA; + fn drop = ffi::RSA_free; + + /// An RSA key. + pub struct Rsa; + + /// Reference to `RSA` + pub struct RsaRef; +} + +impl RsaRef +where + T: HasPrivate, +{ + private_key_to_pem! { + /// Serializes the private key to a PEM-encoded PKCS#1 RSAPrivateKey structure. + /// + /// The output will have a header of `-----BEGIN RSA PRIVATE KEY-----`. + /// + /// This corresponds to [`PEM_write_bio_RSAPrivateKey`]. + /// + /// [`PEM_write_bio_RSAPrivateKey`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_write_bio_RSAPrivateKey.html + private_key_to_pem, + /// Serializes the private key to a PEM-encoded encrypted PKCS#1 RSAPrivateKey structure. + /// + /// The output will have a header of `-----BEGIN RSA PRIVATE KEY-----`. + /// + /// This corresponds to [`PEM_write_bio_RSAPrivateKey`]. + /// + /// [`PEM_write_bio_RSAPrivateKey`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_write_bio_RSAPrivateKey.html + private_key_to_pem_passphrase, + ffi::PEM_write_bio_RSAPrivateKey + } + + to_der! { + /// Serializes the private key to a DER-encoded PKCS#1 RSAPrivateKey structure. + /// + /// This corresponds to [`i2d_RSAPrivateKey`]. + /// + /// [`i2d_RSAPrivateKey`]: https://www.openssl.org/docs/man1.0.2/crypto/i2d_RSAPrivateKey.html + private_key_to_der, + ffi::i2d_RSAPrivateKey + } + + /// Decrypts data using the private key, returning the number of decrypted bytes. + /// + /// # Panics + /// + /// Panics if `self` has no private components, or if `to` is smaller + /// than `self.size()`. + pub fn private_decrypt( + &self, + from: &[u8], + to: &mut [u8], + padding: Padding, + ) -> Result { + assert!(from.len() <= i32::max_value() as usize); + assert!(to.len() >= self.size() as usize); + + unsafe { + let len = cvt_n(ffi::RSA_private_decrypt( + from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.as_ptr(), + padding.0, + ))?; + Ok(len as usize) + } + } + + /// Encrypts data using the private key, returning the number of encrypted bytes. + /// + /// # Panics + /// + /// Panics if `self` has no private components, or if `to` is smaller + /// than `self.size()`. + pub fn private_encrypt( + &self, + from: &[u8], + to: &mut [u8], + padding: Padding, + ) -> Result { + assert!(from.len() <= i32::max_value() as usize); + assert!(to.len() >= self.size() as usize); + + unsafe { + let len = cvt_n(ffi::RSA_private_encrypt( + from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.as_ptr(), + padding.0, + ))?; + Ok(len as usize) + } + } + + /// Returns a reference to the private exponent of the key. + /// + /// This corresponds to [`RSA_get0_key`]. + /// + /// [`RSA_get0_key`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_get0_key.html + pub fn d(&self) -> &BigNumRef { + unsafe { + let d = compat::key(self.as_ptr())[2]; + BigNumRef::from_ptr(d as *mut _) + } + } + + /// Returns a reference to the first factor of the exponent of the key. + /// + /// This corresponds to [`RSA_get0_factors`]. + /// + /// [`RSA_get0_factors`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_get0_key.html + pub fn p(&self) -> Option<&BigNumRef> { + unsafe { + let p = compat::factors(self.as_ptr())[0]; + if p.is_null() { + None + } else { + Some(BigNumRef::from_ptr(p as *mut _)) + } + } + } + + /// Returns a reference to the second factor of the exponent of the key. + /// + /// This corresponds to [`RSA_get0_factors`]. + /// + /// [`RSA_get0_factors`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_get0_key.html + pub fn q(&self) -> Option<&BigNumRef> { + unsafe { + let q = compat::factors(self.as_ptr())[1]; + if q.is_null() { + None + } else { + Some(BigNumRef::from_ptr(q as *mut _)) + } + } + } + + /// Returns a reference to the first exponent used for CRT calculations. + /// + /// This corresponds to [`RSA_get0_crt_params`]. + /// + /// [`RSA_get0_crt_params`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_get0_key.html + pub fn dmp1(&self) -> Option<&BigNumRef> { + unsafe { + let dp = compat::crt_params(self.as_ptr())[0]; + if dp.is_null() { + None + } else { + Some(BigNumRef::from_ptr(dp as *mut _)) + } + } + } + + /// Returns a reference to the second exponent used for CRT calculations. + /// + /// This corresponds to [`RSA_get0_crt_params`]. + /// + /// [`RSA_get0_crt_params`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_get0_key.html + pub fn dmq1(&self) -> Option<&BigNumRef> { + unsafe { + let dq = compat::crt_params(self.as_ptr())[1]; + if dq.is_null() { + None + } else { + Some(BigNumRef::from_ptr(dq as *mut _)) + } + } + } + + /// Returns a reference to the coefficient used for CRT calculations. + /// + /// This corresponds to [`RSA_get0_crt_params`]. + /// + /// [`RSA_get0_crt_params`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_get0_key.html + pub fn iqmp(&self) -> Option<&BigNumRef> { + unsafe { + let qi = compat::crt_params(self.as_ptr())[2]; + if qi.is_null() { + None + } else { + Some(BigNumRef::from_ptr(qi as *mut _)) + } + } + } +} + +impl RsaRef +where + T: HasPublic, +{ + to_pem! { + /// Serializes the public key into a PEM-encoded SubjectPublicKeyInfo structure. + /// + /// The output will have a header of `-----BEGIN PUBLIC KEY-----`. + /// + /// This corresponds to [`PEM_write_bio_RSA_PUBKEY`]. + /// + /// [`PEM_write_bio_RSA_PUBKEY`]: https://www.openssl.org/docs/man1.0.2/crypto/pem.html + public_key_to_pem, + ffi::PEM_write_bio_RSA_PUBKEY + } + + to_der! { + /// Serializes the public key into a DER-encoded SubjectPublicKeyInfo structure. + /// + /// This corresponds to [`i2d_RSA_PUBKEY`]. + /// + /// [`i2d_RSA_PUBKEY`]: https://www.openssl.org/docs/man1.1.0/crypto/i2d_RSA_PUBKEY.html + public_key_to_der, + ffi::i2d_RSA_PUBKEY + } + + to_pem! { + /// Serializes the public key into a PEM-encoded PKCS#1 RSAPublicKey structure. + /// + /// The output will have a header of `-----BEGIN RSA PUBLIC KEY-----`. + /// + /// This corresponds to [`PEM_write_bio_RSAPublicKey`]. + /// + /// [`PEM_write_bio_RSAPublicKey`]: https://www.openssl.org/docs/man1.0.2/crypto/pem.html + public_key_to_pem_pkcs1, + ffi::PEM_write_bio_RSAPublicKey + } + + to_der! { + /// Serializes the public key into a DER-encoded PKCS#1 RSAPublicKey structure. + /// + /// This corresponds to [`i2d_RSAPublicKey`]. + /// + /// [`i2d_RSAPublicKey`]: https://www.openssl.org/docs/man1.0.2/crypto/i2d_RSAPublicKey.html + public_key_to_der_pkcs1, + ffi::i2d_RSAPublicKey + } + + /// Returns the size of the modulus in bytes. + /// + /// This corresponds to [`RSA_size`]. + /// + /// [`RSA_size`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_size.html + pub fn size(&self) -> u32 { + unsafe { ffi::RSA_size(self.as_ptr()) as u32 } + } + + /// Decrypts data using the public key, returning the number of decrypted bytes. + /// + /// # Panics + /// + /// Panics if `to` is smaller than `self.size()`. + pub fn public_decrypt( + &self, + from: &[u8], + to: &mut [u8], + padding: Padding, + ) -> Result { + assert!(from.len() <= i32::max_value() as usize); + assert!(to.len() >= self.size() as usize); + + unsafe { + let len = cvt_n(ffi::RSA_public_decrypt( + from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.as_ptr(), + padding.0, + ))?; + Ok(len as usize) + } + } + + /// Encrypts data using the public key, returning the number of encrypted bytes. + /// + /// # Panics + /// + /// Panics if `to` is smaller than `self.size()`. + pub fn public_encrypt( + &self, + from: &[u8], + to: &mut [u8], + padding: Padding, + ) -> Result { + assert!(from.len() <= i32::max_value() as usize); + assert!(to.len() >= self.size() as usize); + + unsafe { + let len = cvt_n(ffi::RSA_public_encrypt( + from.len() as c_int, + from.as_ptr(), + to.as_mut_ptr(), + self.as_ptr(), + padding.0, + ))?; + Ok(len as usize) + } + } + + /// Returns a reference to the modulus of the key. + /// + /// This corresponds to [`RSA_get0_key`]. + /// + /// [`RSA_get0_key`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_get0_key.html + pub fn n(&self) -> &BigNumRef { + unsafe { + let n = compat::key(self.as_ptr())[0]; + BigNumRef::from_ptr(n as *mut _) + } + } + + /// Returns a reference to the public exponent of the key. + /// + /// This corresponds to [`RSA_get0_key`]. + /// + /// [`RSA_get0_key`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_get0_key.html + pub fn e(&self) -> &BigNumRef { + unsafe { + let e = compat::key(self.as_ptr())[1]; + BigNumRef::from_ptr(e as *mut _) + } + } +} + +impl Rsa { + /// Creates a new RSA key with only public components. + /// + /// `n` is the modulus common to both public and private key. + /// `e` is the public exponent. + /// + /// This corresponds to [`RSA_new`] and uses [`RSA_set0_key`]. + /// + /// [`RSA_new`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_new.html + /// [`RSA_set0_key`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_set0_key.html + pub fn from_public_components(n: BigNum, e: BigNum) -> Result, ErrorStack> { + unsafe { + let rsa = Rsa::from_ptr(cvt_p(ffi::RSA_new())?); + cvt(compat::set_key( + rsa.0, + n.as_ptr(), + e.as_ptr(), + ptr::null_mut(), + ))?; + mem::forget((n, e)); + Ok(rsa) + } + } + + from_pem! { + /// Decodes a PEM-encoded SubjectPublicKeyInfo structure containing an RSA key. + /// + /// The input should have a header of `-----BEGIN PUBLIC KEY-----`. + /// + /// This corresponds to [`PEM_read_bio_RSA_PUBKEY`]. + /// + /// [`PEM_read_bio_RSA_PUBKEY`]: https://www.openssl.org/docs/man1.0.2/crypto/PEM_read_bio_RSA_PUBKEY.html + public_key_from_pem, + Rsa, + ffi::PEM_read_bio_RSA_PUBKEY + } + + from_pem! { + /// Decodes a PEM-encoded PKCS#1 RSAPublicKey structure. + /// + /// The input should have a header of `-----BEGIN RSA PUBLIC KEY-----`. + /// + /// This corresponds to [`PEM_read_bio_RSAPublicKey`]. + /// + /// [`PEM_read_bio_RSAPublicKey`]: https://www.openssl.org/docs/man1.0.2/crypto/PEM_read_bio_RSAPublicKey.html + public_key_from_pem_pkcs1, + Rsa, + ffi::PEM_read_bio_RSAPublicKey + } + + from_der! { + /// Decodes a DER-encoded SubjectPublicKeyInfo structure containing an RSA key. + /// + /// This corresponds to [`d2i_RSA_PUBKEY`]. + /// + /// [`d2i_RSA_PUBKEY`]: https://www.openssl.org/docs/man1.0.2/crypto/d2i_RSA_PUBKEY.html + public_key_from_der, + Rsa, + ffi::d2i_RSA_PUBKEY + } + + from_der! { + /// Decodes a DER-encoded PKCS#1 RSAPublicKey structure. + /// + /// This corresponds to [`d2i_RSAPublicKey`]. + /// + /// [`d2i_RSAPublicKey`]: https://www.openssl.org/docs/man1.0.2/crypto/d2i_RSA_PUBKEY.html + public_key_from_der_pkcs1, + Rsa, + ffi::d2i_RSAPublicKey + } +} + +impl Rsa { + /// Creates a new RSA key with private components (public components are assumed). + /// + /// `n` is the modulus common to both public and private key. + /// `e` is the public exponent and `d` is the private exponent. + /// `p` and `q` are the first and second factors of `n`. + /// `dmp1`, `dmq1`, and `iqmp` are the exponents and coefficient for + /// Chinese Remainder Theorem calculations which is used to speed up RSA operations. + /// + /// This corresponds to [`RSA_new`] and uses [`RSA_set0_key`], + /// [`RSA_set0_factors`], and [`RSA_set0_crt_params`]. + /// + /// [`RSA_new`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_new.html + /// [`RSA_set0_key`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_set0_key.html + /// [`RSA_set0_factors`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_set0_factors.html + /// [`RSA_set0_crt_params`]: https://www.openssl.org/docs/man1.1.0/crypto/RSA_set0_crt_params.html + pub fn from_private_components( + n: BigNum, + e: BigNum, + d: BigNum, + p: BigNum, + q: BigNum, + dmp1: BigNum, + dmq1: BigNum, + iqmp: BigNum, + ) -> Result, ErrorStack> { + unsafe { + let rsa = Rsa::from_ptr(cvt_p(ffi::RSA_new())?); + cvt(compat::set_key(rsa.0, n.as_ptr(), e.as_ptr(), d.as_ptr()))?; + mem::forget((n, e, d)); + cvt(compat::set_factors(rsa.0, p.as_ptr(), q.as_ptr()))?; + mem::forget((p, q)); + cvt(compat::set_crt_params( + rsa.0, + dmp1.as_ptr(), + dmq1.as_ptr(), + iqmp.as_ptr(), + ))?; + mem::forget((dmp1, dmq1, iqmp)); + Ok(rsa) + } + } + + /// Generates a public/private key pair with the specified size. + /// + /// The public exponent will be 65537. + pub fn generate(bits: u32) -> Result, ErrorStack> { + ffi::init(); + unsafe { + let rsa = Rsa::from_ptr(cvt_p(ffi::RSA_new())?); + let e = BigNum::from_u32(ffi::RSA_F4 as u32)?; + cvt(ffi::RSA_generate_key_ex( + rsa.0, + bits as c_int, + e.as_ptr(), + ptr::null_mut(), + ))?; + Ok(rsa) + } + } + + // FIXME these need to identify input formats + private_key_from_pem! { + /// Deserializes a private key from a PEM-encoded PKCS#1 RSAPrivateKey structure. + /// + /// This corresponds to [`PEM_read_bio_RSAPrivateKey`]. + /// + /// [`PEM_read_bio_RSAPrivateKey`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_read_bio_RSAPrivateKey.html + private_key_from_pem, + + /// Deserializes a private key from a PEM-encoded encrypted PKCS#1 RSAPrivateKey structure. + /// + /// This corresponds to [`PEM_read_bio_RSAPrivateKey`]. + /// + /// [`PEM_read_bio_RSAPrivateKey`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_read_bio_RSAPrivateKey.html + private_key_from_pem_passphrase, + + /// Deserializes a private key from a PEM-encoded encrypted PKCS#1 RSAPrivateKey structure. + /// + /// The callback should fill the password into the provided buffer and return its length. + /// + /// This corresponds to [`PEM_read_bio_RSAPrivateKey`]. + /// + /// [`PEM_read_bio_RSAPrivateKey`]: https://www.openssl.org/docs/man1.1.0/crypto/PEM_read_bio_RSAPrivateKey.html + private_key_from_pem_callback, + Rsa, + ffi::PEM_read_bio_RSAPrivateKey + } + + from_der! { + /// Decodes a DER-encoded PKCS#1 RSAPrivateKey structure. + /// + /// This corresponds to [`d2i_RSAPrivateKey`]. + /// + /// [`d2i_RSAPrivateKey`]: https://www.openssl.org/docs/man1.0.2/crypto/d2i_RSA_PUBKEY.html + private_key_from_der, + Rsa, + ffi::d2i_RSAPrivateKey + } +} + +impl fmt::Debug for Rsa { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Rsa") + } +} + +#[cfg(ossl110)] +mod compat { + use std::ptr; + + use ffi::{self, BIGNUM, RSA}; + use libc::c_int; + + pub unsafe fn key(r: *const RSA) -> [*const BIGNUM; 3] { + let (mut n, mut e, mut d) = (ptr::null(), ptr::null(), ptr::null()); + ffi::RSA_get0_key(r, &mut n, &mut e, &mut d); + [n, e, d] + } + + pub unsafe fn factors(r: *const RSA) -> [*const BIGNUM; 2] { + let (mut p, mut q) = (ptr::null(), ptr::null()); + ffi::RSA_get0_factors(r, &mut p, &mut q); + [p, q] + } + + pub unsafe fn crt_params(r: *const RSA) -> [*const BIGNUM; 3] { + let (mut dp, mut dq, mut qi) = (ptr::null(), ptr::null(), ptr::null()); + ffi::RSA_get0_crt_params(r, &mut dp, &mut dq, &mut qi); + [dp, dq, qi] + } + + pub unsafe fn set_key(r: *mut RSA, n: *mut BIGNUM, e: *mut BIGNUM, d: *mut BIGNUM) -> c_int { + ffi::RSA_set0_key(r, n, e, d) + } + + pub unsafe fn set_factors(r: *mut RSA, p: *mut BIGNUM, q: *mut BIGNUM) -> c_int { + ffi::RSA_set0_factors(r, p, q) + } + + pub unsafe fn set_crt_params( + r: *mut RSA, + dmp1: *mut BIGNUM, + dmq1: *mut BIGNUM, + iqmp: *mut BIGNUM, + ) -> c_int { + ffi::RSA_set0_crt_params(r, dmp1, dmq1, iqmp) + } +} + +#[cfg(ossl10x)] +mod compat { + use libc::c_int; + use ffi::{BIGNUM, RSA}; + + pub unsafe fn key(r: *const RSA) -> [*const BIGNUM; 3] { + [(*r).n, (*r).e, (*r).d] + } + + pub unsafe fn factors(r: *const RSA) -> [*const BIGNUM; 2] { + [(*r).p, (*r).q] + } + + pub unsafe fn crt_params(r: *const RSA) -> [*const BIGNUM; 3] { + [(*r).dmp1, (*r).dmq1, (*r).iqmp] + } + + pub unsafe fn set_key(r: *mut RSA, n: *mut BIGNUM, e: *mut BIGNUM, d: *mut BIGNUM) -> c_int { + (*r).n = n; + (*r).e = e; + (*r).d = d; + 1 // TODO: is this right? should it be 0? what's success? + } + + pub unsafe fn set_factors(r: *mut RSA, p: *mut BIGNUM, q: *mut BIGNUM) -> c_int { + (*r).p = p; + (*r).q = q; + 1 // TODO: is this right? should it be 0? what's success? + } + + pub unsafe fn set_crt_params( + r: *mut RSA, + dmp1: *mut BIGNUM, + dmq1: *mut BIGNUM, + iqmp: *mut BIGNUM, + ) -> c_int { + (*r).dmp1 = dmp1; + (*r).dmq1 = dmq1; + (*r).iqmp = iqmp; + 1 // TODO: is this right? should it be 0? what's success? + } +} + +#[cfg(test)] +mod test { + use symm::Cipher; + + use super::*; + + #[test] + fn test_from_password() { + let key = include_bytes!("../test/rsa-encrypted.pem"); + Rsa::private_key_from_pem_passphrase(key, b"mypass").unwrap(); + } + + #[test] + fn test_from_password_callback() { + let mut password_queried = false; + let key = include_bytes!("../test/rsa-encrypted.pem"); + Rsa::private_key_from_pem_callback(key, |password| { + password_queried = true; + password[..6].copy_from_slice(b"mypass"); + Ok(6) + }).unwrap(); + + assert!(password_queried); + } + + #[test] + fn test_to_password() { + let key = Rsa::generate(2048).unwrap(); + let pem = key.private_key_to_pem_passphrase(Cipher::aes_128_cbc(), b"foobar") + .unwrap(); + Rsa::private_key_from_pem_passphrase(&pem, b"foobar").unwrap(); + assert!(Rsa::private_key_from_pem_passphrase(&pem, b"fizzbuzz").is_err()); + } + + #[test] + fn test_public_encrypt_private_decrypt_with_padding() { + let key = include_bytes!("../test/rsa.pem.pub"); + let public_key = Rsa::public_key_from_pem(key).unwrap(); + + let mut result = vec![0; public_key.size() as usize]; + let original_data = b"This is test"; + let len = public_key + .public_encrypt(original_data, &mut result, Padding::PKCS1) + .unwrap(); + assert_eq!(len, 256); + + let pkey = include_bytes!("../test/rsa.pem"); + let private_key = Rsa::private_key_from_pem(pkey).unwrap(); + let mut dec_result = vec![0; private_key.size() as usize]; + let len = private_key + .private_decrypt(&result, &mut dec_result, Padding::PKCS1) + .unwrap(); + + assert_eq!(&dec_result[..len], original_data); + } + + #[test] + fn test_private_encrypt() { + let k0 = super::Rsa::generate(512).unwrap(); + let k0pkey = k0.public_key_to_pem().unwrap(); + let k1 = super::Rsa::public_key_from_pem(&k0pkey).unwrap(); + + let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; + + let mut emesg = vec![0; k0.size() as usize]; + k0.private_encrypt(&msg, &mut emesg, Padding::PKCS1) + .unwrap(); + let mut dmesg = vec![0; k1.size() as usize]; + let len = k1.public_decrypt(&emesg, &mut dmesg, Padding::PKCS1) + .unwrap(); + assert_eq!(msg, &dmesg[..len]); + } + + #[test] + fn test_public_encrypt() { + let k0 = super::Rsa::generate(512).unwrap(); + let k0pkey = k0.private_key_to_pem().unwrap(); + let k1 = super::Rsa::private_key_from_pem(&k0pkey).unwrap(); + + let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; + + let mut emesg = vec![0; k0.size() as usize]; + k0.public_encrypt(&msg, &mut emesg, Padding::PKCS1).unwrap(); + let mut dmesg = vec![0; k1.size() as usize]; + let len = k1.private_decrypt(&emesg, &mut dmesg, Padding::PKCS1) + .unwrap(); + assert_eq!(msg, &dmesg[..len]); + } + + #[test] + fn test_public_key_from_pem_pkcs1() { + let key = include_bytes!("../test/pkcs1.pem.pub"); + Rsa::public_key_from_pem_pkcs1(key).unwrap(); + } + + #[test] + #[should_panic] + fn test_public_key_from_pem_pkcs1_file_panic() { + let key = include_bytes!("../test/key.pem.pub"); + Rsa::public_key_from_pem_pkcs1(key).unwrap(); + } + + #[test] + fn test_public_key_to_pem_pkcs1() { + let keypair = super::Rsa::generate(512).unwrap(); + let pubkey_pem = keypair.public_key_to_pem_pkcs1().unwrap(); + super::Rsa::public_key_from_pem_pkcs1(&pubkey_pem).unwrap(); + } + + #[test] + #[should_panic] + fn test_public_key_from_pem_pkcs1_generate_panic() { + let keypair = super::Rsa::generate(512).unwrap(); + let pubkey_pem = keypair.public_key_to_pem().unwrap(); + super::Rsa::public_key_from_pem_pkcs1(&pubkey_pem).unwrap(); + } + + #[test] + fn test_pem_pkcs1_encrypt() { + let keypair = super::Rsa::generate(2048).unwrap(); + let pubkey_pem = keypair.public_key_to_pem_pkcs1().unwrap(); + let pubkey = super::Rsa::public_key_from_pem_pkcs1(&pubkey_pem).unwrap(); + let msg = "Hello, world!".as_bytes(); + + let mut encrypted = vec![0; pubkey.size() as usize]; + let len = pubkey.public_encrypt(&msg, &mut encrypted, Padding::PKCS1).unwrap(); + assert!(len > msg.len()); + let mut decrypted = vec![0; keypair.size() as usize]; + let len = keypair.private_decrypt(&encrypted, &mut decrypted, Padding::PKCS1).unwrap(); + assert_eq!(len, msg.len()); + assert_eq!("Hello, world!", String::from_utf8_lossy(&decrypted[..len])); + } + + #[test] + fn test_pem_pkcs1_padding() { + let keypair = super::Rsa::generate(512).unwrap(); + let pubkey_pem = keypair.public_key_to_pem_pkcs1().unwrap(); + let pubkey = super::Rsa::public_key_from_pem_pkcs1(&pubkey_pem).unwrap(); + let msg = "foo".as_bytes(); + + let mut encrypted1 = vec![0; pubkey.size() as usize]; + let mut encrypted2 = vec![0; pubkey.size() as usize]; + let len1 = pubkey.public_encrypt(&msg, &mut encrypted1, Padding::PKCS1).unwrap(); + let len2 = pubkey.public_encrypt(&msg, &mut encrypted2, Padding::PKCS1).unwrap(); + assert!(len1 > (msg.len() + 1)); + assert_eq!(len1, len2); + assert_ne!(encrypted1, encrypted2); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/sha.rs cargo-0.26.0/vendor/openssl-0.10.6/src/sha.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/sha.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/sha.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,386 @@ +//! The SHA family of hashes. +//! +//! SHA, or Secure Hash Algorithms, are a family of cryptographic hashing algorithms published by +//! the National Institute of Standards and Technology (NIST). Hash algorithms such as those in +//! the SHA family are used to map data of an arbitrary size to a fixed-size string of bytes. +//! As cryptographic hashing algorithms, these mappings have the property of being irreversable. +//! This property makes hash algorithms like these excellent for uses such as verifying the +//! contents of a file- if you know the hash you expect beforehand, then you can verify that the +//! data you have is correct if it hashes to the same value. +//! +//! # Examples +//! +//! When dealing with data that becomes available in chunks, such as while buffering data from IO, +//! you can create a hasher that you can repeatedly update to add bytes to. +//! +//! ```rust +//! extern crate openssl; +//! extern crate hex; +//! +//! use openssl::sha; +//! +//! fn main() { +//! let mut hasher = sha::Sha256::new(); +//! +//! hasher.update(b"Hello, "); +//! hasher.update(b"world"); +//! +//! let hash = hasher.finish(); +//! println!("Hashed \"Hello, world\" to {}", hex::encode(hash)); +//! } +//! ``` +//! +//! On the other hand, if you already have access to all of the data you woud like to hash, you +//! may prefer to use the slightly simpler method of simply calling the hash function corresponding +//! to the algorithm you want to use. +//! +//! ```rust +//! extern crate openssl; +//! extern crate hex; +//! +//! use openssl::sha::sha256; +//! +//! fn main() { +//! let hash = sha256(b"your data or message"); +//! println!("Hash = {}", hex::encode(hash)); +//! } +//! ``` +use libc::c_void; +use ffi; +use std::mem; + +/// Computes the SHA1 hash of some data. +/// +/// # Warning +/// +/// SHA1 is known to be insecure - it should not be used unless required for +/// compatibility with existing systems. +#[inline] +pub fn sha1(data: &[u8]) -> [u8; 20] { + unsafe { + let mut hash: [u8; 20] = mem::uninitialized(); + ffi::SHA1(data.as_ptr(), data.len(), hash.as_mut_ptr()); + hash + } +} + +/// Computes the SHA224 hash of some data. +#[inline] +pub fn sha224(data: &[u8]) -> [u8; 28] { + unsafe { + let mut hash: [u8; 28] = mem::uninitialized(); + ffi::SHA224(data.as_ptr(), data.len(), hash.as_mut_ptr()); + hash + } +} + +/// Computes the SHA256 hash of some data. +#[inline] +pub fn sha256(data: &[u8]) -> [u8; 32] { + unsafe { + let mut hash: [u8; 32] = mem::uninitialized(); + ffi::SHA256(data.as_ptr(), data.len(), hash.as_mut_ptr()); + hash + } +} + +/// Computes the SHA384 hash of some data. +#[inline] +pub fn sha384(data: &[u8]) -> [u8; 48] { + unsafe { + let mut hash: [u8; 48] = mem::uninitialized(); + ffi::SHA384(data.as_ptr(), data.len(), hash.as_mut_ptr()); + hash + } +} + +/// Computes the SHA512 hash of some data. +#[inline] +pub fn sha512(data: &[u8]) -> [u8; 64] { + unsafe { + let mut hash: [u8; 64] = mem::uninitialized(); + ffi::SHA512(data.as_ptr(), data.len(), hash.as_mut_ptr()); + hash + } +} + +/// An object which calculates a SHA1 hash of some data. +/// +/// # Warning +/// +/// SHA1 is known to be insecure - it should not be used unless required for +/// compatibility with existing systems. +pub struct Sha1(ffi::SHA_CTX); + +impl Sha1 { + /// Creates a new hasher. + #[inline] + pub fn new() -> Sha1 { + unsafe { + let mut ctx = mem::uninitialized(); + ffi::SHA1_Init(&mut ctx); + Sha1(ctx) + } + } + + /// Feeds some data into the hasher. + /// + /// This can be called multiple times. + #[inline] + pub fn update(&mut self, buf: &[u8]) { + unsafe { + ffi::SHA1_Update(&mut self.0, buf.as_ptr() as *const c_void, buf.len()); + } + } + + /// Returns the hash of the data. + #[inline] + pub fn finish(mut self) -> [u8; 20] { + unsafe { + let mut hash: [u8; 20] = mem::uninitialized(); + ffi::SHA1_Final(hash.as_mut_ptr(), &mut self.0); + hash + } + } +} + +/// An object which calculates a SHA224 hash of some data. +pub struct Sha224(ffi::SHA256_CTX); + +impl Sha224 { + /// Creates a new hasher. + #[inline] + pub fn new() -> Sha224 { + unsafe { + let mut ctx = mem::uninitialized(); + ffi::SHA224_Init(&mut ctx); + Sha224(ctx) + } + } + + /// Feeds some data into the hasher. + /// + /// This can be called multiple times. + #[inline] + pub fn update(&mut self, buf: &[u8]) { + unsafe { + ffi::SHA224_Update(&mut self.0, buf.as_ptr() as *const c_void, buf.len()); + } + } + + /// Returns the hash of the data. + #[inline] + pub fn finish(mut self) -> [u8; 28] { + unsafe { + let mut hash: [u8; 28] = mem::uninitialized(); + ffi::SHA224_Final(hash.as_mut_ptr(), &mut self.0); + hash + } + } +} + +/// An object which calculates a SHA256 hash of some data. +pub struct Sha256(ffi::SHA256_CTX); + +impl Sha256 { + /// Creates a new hasher. + #[inline] + pub fn new() -> Sha256 { + unsafe { + let mut ctx = mem::uninitialized(); + ffi::SHA256_Init(&mut ctx); + Sha256(ctx) + } + } + + /// Feeds some data into the hasher. + /// + /// This can be called multiple times. + #[inline] + pub fn update(&mut self, buf: &[u8]) { + unsafe { + ffi::SHA256_Update(&mut self.0, buf.as_ptr() as *const c_void, buf.len()); + } + } + + /// Returns the hash of the data. + #[inline] + pub fn finish(mut self) -> [u8; 32] { + unsafe { + let mut hash: [u8; 32] = mem::uninitialized(); + ffi::SHA256_Final(hash.as_mut_ptr(), &mut self.0); + hash + } + } +} + +/// An object which calculates a SHA384 hash of some data. +pub struct Sha384(ffi::SHA512_CTX); + +impl Sha384 { + /// Creates a new hasher. + #[inline] + pub fn new() -> Sha384 { + unsafe { + let mut ctx = mem::uninitialized(); + ffi::SHA384_Init(&mut ctx); + Sha384(ctx) + } + } + + /// Feeds some data into the hasher. + /// + /// This can be called multiple times. + #[inline] + pub fn update(&mut self, buf: &[u8]) { + unsafe { + ffi::SHA384_Update(&mut self.0, buf.as_ptr() as *const c_void, buf.len()); + } + } + + /// Returns the hash of the data. + #[inline] + pub fn finish(mut self) -> [u8; 48] { + unsafe { + let mut hash: [u8; 48] = mem::uninitialized(); + ffi::SHA384_Final(hash.as_mut_ptr(), &mut self.0); + hash + } + } +} + +/// An object which calculates a SHA512 hash of some data. +pub struct Sha512(ffi::SHA512_CTX); + +impl Sha512 { + /// Creates a new hasher. + #[inline] + pub fn new() -> Sha512 { + unsafe { + let mut ctx = mem::uninitialized(); + ffi::SHA512_Init(&mut ctx); + Sha512(ctx) + } + } + + /// Feeds some data into the hasher. + /// + /// This can be called multiple times. + #[inline] + pub fn update(&mut self, buf: &[u8]) { + unsafe { + ffi::SHA512_Update(&mut self.0, buf.as_ptr() as *const c_void, buf.len()); + } + } + + /// Returns the hash of the data. + #[inline] + pub fn finish(mut self) -> [u8; 64] { + unsafe { + let mut hash: [u8; 64] = mem::uninitialized(); + ffi::SHA512_Final(hash.as_mut_ptr(), &mut self.0); + hash + } + } +} + +#[cfg(test)] +mod test { + use hex; + + use super::*; + + #[test] + fn standalone_1() { + let data = b"abc"; + let expected = "a9993e364706816aba3e25717850c26c9cd0d89d"; + + assert_eq!(hex::encode(sha1(data)), expected); + } + + #[test] + fn struct_1() { + let expected = "a9993e364706816aba3e25717850c26c9cd0d89d"; + + let mut hasher = Sha1::new(); + hasher.update(b"a"); + hasher.update(b"bc"); + assert_eq!(hex::encode(hasher.finish()), expected); + } + + #[test] + fn standalone_224() { + let data = b"abc"; + let expected = "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7"; + + assert_eq!(hex::encode(sha224(data)), expected); + } + + #[test] + fn struct_224() { + let expected = "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7"; + + let mut hasher = Sha224::new(); + hasher.update(b"a"); + hasher.update(b"bc"); + assert_eq!(hex::encode(hasher.finish()), expected); + } + + #[test] + fn standalone_256() { + let data = b"abc"; + let expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + + assert_eq!(hex::encode(sha256(data)), expected); + } + + #[test] + fn struct_256() { + let expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; + + let mut hasher = Sha256::new(); + hasher.update(b"a"); + hasher.update(b"bc"); + assert_eq!(hex::encode(hasher.finish()), expected); + } + + #[test] + fn standalone_384() { + let data = b"abc"; + let expected = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e\ + 7cc2358baeca134c825a7"; + + assert_eq!(hex::encode(&sha384(data)[..]), expected); + } + + #[test] + fn struct_384() { + let expected = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e\ + 7cc2358baeca134c825a7"; + + let mut hasher = Sha384::new(); + hasher.update(b"a"); + hasher.update(b"bc"); + assert_eq!(hex::encode(&hasher.finish()[..]), expected); + } + + #[test] + fn standalone_512() { + let data = b"abc"; + let expected = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274\ + fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"; + + assert_eq!(hex::encode(&sha512(data)[..]), expected); + } + + #[test] + fn struct_512() { + let expected = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274\ + fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"; + + let mut hasher = Sha512::new(); + hasher.update(b"a"); + hasher.update(b"bc"); + assert_eq!(hex::encode(&hasher.finish()[..]), expected); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/sign.rs cargo-0.26.0/vendor/openssl-0.10.6/src/sign.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/sign.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/sign.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,721 @@ +//! Message signatures. +//! +//! The `Signer` allows for the computation of cryptographic signatures of +//! data given a private key. The `Verifier` can then be used with the +//! corresponding public key to verify the integrity and authenticity of that +//! data given the signature. +//! +//! # Examples +//! +//! Sign and verify data given an RSA keypair: +//! +//! ```rust +//! use openssl::sign::{Signer, Verifier}; +//! use openssl::rsa::Rsa; +//! use openssl::pkey::PKey; +//! use openssl::hash::MessageDigest; +//! +//! // Generate a keypair +//! let keypair = Rsa::generate(2048).unwrap(); +//! let keypair = PKey::from_rsa(keypair).unwrap(); +//! +//! let data = b"hello, world!"; +//! let data2 = b"hola, mundo!"; +//! +//! // Sign the data +//! let mut signer = Signer::new(MessageDigest::sha256(), &keypair).unwrap(); +//! signer.update(data).unwrap(); +//! signer.update(data2).unwrap(); +//! let signature = signer.sign_to_vec().unwrap(); +//! +//! // Verify the data +//! let mut verifier = Verifier::new(MessageDigest::sha256(), &keypair).unwrap(); +//! verifier.update(data).unwrap(); +//! verifier.update(data2).unwrap(); +//! assert!(verifier.verify(&signature).unwrap()); +//! ``` +//! +//! Compute an HMAC: +//! +//! ```rust +//! use openssl::hash::MessageDigest; +//! use openssl::memcmp; +//! use openssl::pkey::PKey; +//! use openssl::sign::Signer; +//! +//! // Create a PKey +//! let key = PKey::hmac(b"my secret").unwrap(); +//! +//! let data = b"hello, world!"; +//! let data2 = b"hola, mundo!"; +//! +//! // Compute the HMAC +//! let mut signer = Signer::new(MessageDigest::sha256(), &key).unwrap(); +//! signer.update(data).unwrap(); +//! signer.update(data2).unwrap(); +//! let hmac = signer.sign_to_vec().unwrap(); +//! +//! // `Verifier` cannot be used with HMACs; use the `memcmp::eq` function instead +//! // +//! // Do not simply check for equality with `==`! +//! # let target = hmac.clone(); +//! assert!(memcmp::eq(&hmac, &target)); +//! ``` +use ffi; +use foreign_types::ForeignTypeRef; +use std::io::{self, Write}; +use std::marker::PhantomData; +use std::ptr; +use libc::c_int; + +use {cvt, cvt_p}; +use hash::MessageDigest; +use pkey::{HasPrivate, HasPublic, PKeyRef}; +use error::ErrorStack; +use rsa::Padding; + +#[cfg(ossl110)] +use ffi::{EVP_MD_CTX_free, EVP_MD_CTX_new}; +#[cfg(any(ossl101, ossl102))] +use ffi::{EVP_MD_CTX_create as EVP_MD_CTX_new, EVP_MD_CTX_destroy as EVP_MD_CTX_free}; + +/// Salt lengths that must be used with `set_rsa_pss_saltlen`. +pub struct RsaPssSaltlen(c_int); + +impl RsaPssSaltlen { + /// Returns the integer representation of `RsaPssSaltlen`. + fn as_raw(&self) -> c_int { + self.0 + } + + /// Sets the salt length to the given value. + pub fn custom(val: c_int) -> RsaPssSaltlen { + RsaPssSaltlen(val) + } + + /// The salt length is set to the digest length. + /// Corresponds to the special value `-1`. + pub const DIGEST_LENGTH: RsaPssSaltlen = RsaPssSaltlen(-1); + /// The salt length is set to the maximum permissible value. + /// Corresponds to the special value `-2`. + pub const MAXIMUM_LENGTH: RsaPssSaltlen = RsaPssSaltlen(-2); +} + +/// A type which computes cryptographic signatures of data. +pub struct Signer<'a> { + md_ctx: *mut ffi::EVP_MD_CTX, + pctx: *mut ffi::EVP_PKEY_CTX, + _p: PhantomData<&'a ()>, +} + +unsafe impl<'a> Sync for Signer<'a> {} +unsafe impl<'a> Send for Signer<'a> {} + +impl<'a> Drop for Signer<'a> { + fn drop(&mut self) { + // pkey_ctx is owned by the md_ctx, so no need to explicitly free it. + unsafe { + EVP_MD_CTX_free(self.md_ctx); + } + } +} + +impl<'a> Signer<'a> { + /// Creates a new `Signer`. + /// + /// OpenSSL documentation at [`EVP_DigestSignInit`]. + /// + /// [`EVP_DigestSignInit`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestSignInit.html + pub fn new(type_: MessageDigest, pkey: &'a PKeyRef) -> Result, ErrorStack> + where + T: HasPrivate, + { + Self::new_intern(Some(type_), pkey) + } + + /// Creates a new `Signer` without a digest. + /// + /// This can be used to create a CMAC. + /// OpenSSL documentation at [`EVP_DigestSignInit`]. + /// + /// [`EVP_DigestSignInit`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestSignInit.html + pub fn new_without_digest(pkey: &'a PKeyRef) -> Result, ErrorStack> + where + T: HasPrivate, + { + Self::new_intern(None, pkey) + } + + pub fn new_intern( + type_: Option, + pkey: &'a PKeyRef, + ) -> Result, ErrorStack> + where + T: HasPrivate, + { + unsafe { + ffi::init(); + + let ctx = cvt_p(EVP_MD_CTX_new())?; + let mut pctx: *mut ffi::EVP_PKEY_CTX = ptr::null_mut(); + let r = ffi::EVP_DigestSignInit( + ctx, + &mut pctx, + type_.map(|t| t.as_ptr()).unwrap_or(ptr::null()), + ptr::null_mut(), + pkey.as_ptr(), + ); + if r != 1 { + EVP_MD_CTX_free(ctx); + return Err(ErrorStack::get()); + } + + assert!(!pctx.is_null()); + + Ok(Signer { + md_ctx: ctx, + pctx, + _p: PhantomData, + }) + } + } + + /// Returns the RSA padding mode in use. + /// + /// This is only useful for RSA keys. + /// + /// This corresponds to `EVP_PKEY_CTX_get_rsa_padding`. + pub fn rsa_padding(&self) -> Result { + unsafe { + let mut pad = 0; + cvt(ffi::EVP_PKEY_CTX_get_rsa_padding(self.pctx, &mut pad)) + .map(|_| Padding::from_raw(pad)) + } + } + + /// Sets the RSA padding mode. + /// + /// This is only useful for RSA keys. + /// + /// This corresponds to [`EVP_PKEY_CTX_set_rsa_padding`]. + /// + /// [`EVP_PKEY_CTX_set_rsa_padding`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_CTX_set_rsa_padding.html + pub fn set_rsa_padding(&mut self, padding: Padding) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EVP_PKEY_CTX_set_rsa_padding( + self.pctx, + padding.as_raw(), + )).map(|_| ()) + } + } + + /// Sets the RSA PSS salt length. + /// + /// This is only useful for RSA keys. + /// + /// This corresponds to [`EVP_PKEY_CTX_set_rsa_pss_saltlen`]. + /// + /// [`EVP_PKEY_CTX_set_rsa_pss_saltlen`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_CTX_set_rsa_pss_saltlen.html + pub fn set_rsa_pss_saltlen(&mut self, len: RsaPssSaltlen) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EVP_PKEY_CTX_set_rsa_pss_saltlen( + self.pctx, + len.as_raw(), + )).map(|_| ()) + } + } + + /// Sets the RSA MGF1 algorithm. + /// + /// This is only useful for RSA keys. + /// + /// This corresponds to [`EVP_PKEY_CTX_set_rsa_mgf1_md`]. + /// + /// [`EVP_PKEY_CTX_set_rsa_mgf1_md`]: https://www.openssl.org/docs/manmaster/man7/RSA-PSS.html + pub fn set_rsa_mgf1_md(&mut self, md: MessageDigest) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EVP_PKEY_CTX_set_rsa_mgf1_md( + self.pctx, + md.as_ptr() as *mut _, + )).map(|_| ()) + } + } + + /// Feeds more data into the `Signer`. + /// + /// OpenSSL documentation at [`EVP_DigestUpdate`]. + /// + /// [`EVP_DigestUpdate`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestInit.html + pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EVP_DigestUpdate( + self.md_ctx, + buf.as_ptr() as *const _, + buf.len(), + )).map(|_| ()) + } + } + + /// Computes an upper bound on the signature length. + /// + /// The actual signature may be shorter than this value. Check the return value of + /// `sign` to get the exact length. + /// + /// OpenSSL documentation at [`EVP_DigestSignFinal`]. + /// + /// [`EVP_DigestSignFinal`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_DigestSignFinal.html + pub fn len(&self) -> Result { + unsafe { + let mut len = 0; + cvt(ffi::EVP_DigestSignFinal( + self.md_ctx, + ptr::null_mut(), + &mut len, + ))?; + Ok(len) + } + } + + /// Writes the signature into the provided buffer, returning the number of bytes written. + /// + /// This method will fail if the buffer is not large enough for the signature. Use the `len` + /// method to get an upper bound on the required size. + /// + /// OpenSSL documentation at [`EVP_DigestSignFinal`]. + /// + /// [`EVP_DigestSignFinal`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_DigestSignFinal.html + pub fn sign(&self, buf: &mut [u8]) -> Result { + unsafe { + let mut len = buf.len(); + cvt(ffi::EVP_DigestSignFinal( + self.md_ctx, + buf.as_mut_ptr() as *mut _, + &mut len, + ))?; + Ok(len) + } + } + + /// Returns the signature. + /// + /// This is a simple convenience wrapper over `len` and `sign`. + pub fn sign_to_vec(&self) -> Result, ErrorStack> { + let mut buf = vec![0; self.len()?]; + let len = self.sign(&mut buf)?; + // The advertised length is not always equal to the real length for things like DSA + buf.truncate(len); + Ok(buf) + } +} + +impl<'a> Write for Signer<'a> { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.update(buf)?; + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +pub struct Verifier<'a> { + md_ctx: *mut ffi::EVP_MD_CTX, + pctx: *mut ffi::EVP_PKEY_CTX, + pkey_pd: PhantomData<&'a ()>, +} + +unsafe impl<'a> Sync for Verifier<'a> {} +unsafe impl<'a> Send for Verifier<'a> {} + +impl<'a> Drop for Verifier<'a> { + fn drop(&mut self) { + // pkey_ctx is owned by the md_ctx, so no need to explicitly free it. + unsafe { + EVP_MD_CTX_free(self.md_ctx); + } + } +} + +/// A type which verifies cryptographic signatures of data. +impl<'a> Verifier<'a> { + /// Creates a new `Verifier`. + /// + /// OpenSSL documentation at [`EVP_DigestVerifyInit`]. + /// + /// [`EVP_DigestVerifyInit`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestVerifyInit.html + pub fn new(type_: MessageDigest, pkey: &'a PKeyRef) -> Result, ErrorStack> + where + T: HasPublic, + { + unsafe { + ffi::init(); + + let ctx = cvt_p(EVP_MD_CTX_new())?; + let mut pctx: *mut ffi::EVP_PKEY_CTX = ptr::null_mut(); + let r = ffi::EVP_DigestVerifyInit( + ctx, + &mut pctx, + type_.as_ptr(), + ptr::null_mut(), + pkey.as_ptr(), + ); + if r != 1 { + EVP_MD_CTX_free(ctx); + return Err(ErrorStack::get()); + } + + assert!(!pctx.is_null()); + + Ok(Verifier { + md_ctx: ctx, + pctx, + pkey_pd: PhantomData, + }) + } + } + + /// Returns the RSA padding mode in use. + /// + /// This is only useful for RSA keys. + /// + /// This corresponds to `EVP_PKEY_CTX_get_rsa_padding`. + pub fn rsa_padding(&self) -> Result { + unsafe { + let mut pad = 0; + cvt(ffi::EVP_PKEY_CTX_get_rsa_padding(self.pctx, &mut pad)) + .map(|_| Padding::from_raw(pad)) + } + } + + /// Sets the RSA padding mode. + /// + /// This is only useful for RSA keys. + /// + /// This corresponds to [`EVP_PKEY_CTX_set_rsa_padding`]. + /// + /// [`EVP_PKEY_CTX_set_rsa_padding`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_CTX_set_rsa_padding.html + pub fn set_rsa_padding(&mut self, padding: Padding) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EVP_PKEY_CTX_set_rsa_padding( + self.pctx, + padding.as_raw(), + )).map(|_| ()) + } + } + + /// Sets the RSA PSS salt length. + /// + /// This is only useful for RSA keys. + /// + /// This corresponds to [`EVP_PKEY_CTX_set_rsa_pss_saltlen`]. + /// + /// [`EVP_PKEY_CTX_set_rsa_pss_saltlen`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_CTX_set_rsa_pss_saltlen.html + pub fn set_rsa_pss_saltlen(&mut self, len: RsaPssSaltlen) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EVP_PKEY_CTX_set_rsa_pss_saltlen( + self.pctx, + len.as_raw(), + )).map(|_| ()) + } + } + + /// Sets the RSA MGF1 algorithm. + /// + /// This is only useful for RSA keys. + /// + /// This corresponds to [`EVP_PKEY_CTX_set_rsa_mgf1_md`]. + /// + /// [`EVP_PKEY_CTX_set_rsa_mgf1_md`]: https://www.openssl.org/docs/manmaster/man7/RSA-PSS.html + pub fn set_rsa_mgf1_md(&mut self, md: MessageDigest) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EVP_PKEY_CTX_set_rsa_mgf1_md( + self.pctx, + md.as_ptr() as *mut _, + )).map(|_| ()) + } + } + + /// Feeds more data into the `Verifier`. + /// + /// OpenSSL documentation at [`EVP_DigestUpdate`]. + /// + /// [`EVP_DigestUpdate`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestInit.html + pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::EVP_DigestUpdate( + self.md_ctx, + buf.as_ptr() as *const _, + buf.len(), + )).map(|_| ()) + } + } + + /// Determines if the data fed into the `Verifier` matches the provided signature. + /// + /// OpenSSL documentation at [`EVP_DigestVerifyFinal`]. + /// + /// [`EVP_DigestVerifyFinal`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestVerifyFinal.html + pub fn verify(&self, signature: &[u8]) -> Result { + unsafe { + let r = + EVP_DigestVerifyFinal(self.md_ctx, signature.as_ptr() as *const _, signature.len()); + match r { + 1 => Ok(true), + 0 => { + ErrorStack::get(); // discard error stack + Ok(false) + } + _ => Err(ErrorStack::get()), + } + } + } +} + +impl<'a> Write for Verifier<'a> { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.update(buf)?; + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[cfg(not(ossl101))] +use ffi::EVP_DigestVerifyFinal; + +#[cfg(ossl101)] +#[allow(bad_style)] +unsafe fn EVP_DigestVerifyFinal( + ctx: *mut ffi::EVP_MD_CTX, + sigret: *const ::libc::c_uchar, + siglen: ::libc::size_t, +) -> ::libc::c_int { + ffi::EVP_DigestVerifyFinal(ctx, sigret as *mut _, siglen) +} + +#[cfg(test)] +mod test { + use hex::{self, FromHex}; + use std::iter; + + use hash::MessageDigest; + use sign::{RsaPssSaltlen, Signer, Verifier}; + use ec::{EcGroup, EcKey}; + use nid::Nid; + use rsa::{Padding, Rsa}; + use pkey::PKey; + + const INPUT: &'static str = + "65794a68624763694f694a53557a49314e694a392e65794a7063334d694f694a71623255694c41304b49434a6c\ + 654841694f6a457a4d4441344d546b7a4f44417344516f67496d6830644841364c79396c654746746347786c4c\ + 6d4e76625339706331397962323930496a7030636e566c6651"; + + const SIGNATURE: &'static str = + "702e218943e88fd11eb5d82dbf7845f34106ae1b81fff7731116add1717d83656d420afd3c96eedd73a2663e51\ + 66687b000b87226e0187ed1073f945e582adfcef16d85a798ee8c66ddb3db8975b17d09402beedd5d9d9700710\ + 8db28160d5f8040ca7445762b81fbe7ff9d92e0ae76f24f25b33bbe6f44ae61eb1040acb20044d3ef9128ed401\ + 30795bd4bd3b41eecad066ab651981fde48df77f372dc38b9fafdd3befb18b5da3cc3c2eb02f9e3a41d612caad\ + 15911273a05f23b9e838faaf849d698429ef5a1e88798236c3d40e604522a544c8f27a7a2db80663d16cf7caea\ + 56de405cb2215a45b2c25566b55ac1a748a070dfc8a32a469543d019eefb47"; + + #[test] + fn rsa_sign() { + let key = include_bytes!("../test/rsa.pem"); + let private_key = Rsa::private_key_from_pem(key).unwrap(); + let pkey = PKey::from_rsa(private_key).unwrap(); + + let mut signer = Signer::new(MessageDigest::sha256(), &pkey).unwrap(); + assert_eq!(signer.rsa_padding().unwrap(), Padding::PKCS1); + signer.set_rsa_padding(Padding::PKCS1).unwrap(); + signer.update(&Vec::from_hex(INPUT).unwrap()).unwrap(); + let result = signer.sign_to_vec().unwrap(); + + assert_eq!(hex::encode(result), SIGNATURE); + } + + #[test] + fn rsa_verify_ok() { + let key = include_bytes!("../test/rsa.pem"); + let private_key = Rsa::private_key_from_pem(key).unwrap(); + let pkey = PKey::from_rsa(private_key).unwrap(); + + let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey).unwrap(); + assert_eq!(verifier.rsa_padding().unwrap(), Padding::PKCS1); + verifier.update(&Vec::from_hex(INPUT).unwrap()).unwrap(); + assert!(verifier.verify(&Vec::from_hex(SIGNATURE).unwrap()).unwrap()); + } + + #[test] + fn rsa_verify_invalid() { + let key = include_bytes!("../test/rsa.pem"); + let private_key = Rsa::private_key_from_pem(key).unwrap(); + let pkey = PKey::from_rsa(private_key).unwrap(); + + let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey).unwrap(); + verifier.update(&Vec::from_hex(INPUT).unwrap()).unwrap(); + verifier.update(b"foobar").unwrap(); + assert!(!verifier.verify(&Vec::from_hex(SIGNATURE).unwrap()).unwrap()); + } + + fn test_hmac(ty: MessageDigest, tests: &[(Vec, Vec, Vec)]) { + for &(ref key, ref data, ref res) in tests.iter() { + let pkey = PKey::hmac(key).unwrap(); + let mut signer = Signer::new(ty, &pkey).unwrap(); + signer.update(data).unwrap(); + assert_eq!(signer.sign_to_vec().unwrap(), *res); + } + } + + #[test] + fn hmac_md5() { + // test vectors from RFC 2202 + let tests: [(Vec, Vec, Vec); 7] = [ + ( + iter::repeat(0x0b_u8).take(16).collect(), + b"Hi There".to_vec(), + Vec::from_hex("9294727a3638bb1c13f48ef8158bfc9d").unwrap(), + ), + ( + b"Jefe".to_vec(), + b"what do ya want for nothing?".to_vec(), + Vec::from_hex("750c783e6ab0b503eaa86e310a5db738").unwrap(), + ), + ( + iter::repeat(0xaa_u8).take(16).collect(), + iter::repeat(0xdd_u8).take(50).collect(), + Vec::from_hex("56be34521d144c88dbb8c733f0e8b3f6").unwrap(), + ), + ( + Vec::from_hex("0102030405060708090a0b0c0d0e0f10111213141516171819").unwrap(), + iter::repeat(0xcd_u8).take(50).collect(), + Vec::from_hex("697eaf0aca3a3aea3a75164746ffaa79").unwrap(), + ), + ( + iter::repeat(0x0c_u8).take(16).collect(), + b"Test With Truncation".to_vec(), + Vec::from_hex("56461ef2342edc00f9bab995690efd4c").unwrap(), + ), + ( + iter::repeat(0xaa_u8).take(80).collect(), + b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), + Vec::from_hex("6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd").unwrap(), + ), + ( + iter::repeat(0xaa_u8).take(80).collect(), + b"Test Using Larger Than Block-Size Key \ + and Larger Than One Block-Size Data" + .to_vec(), + Vec::from_hex("6f630fad67cda0ee1fb1f562db3aa53e").unwrap(), + ), + ]; + + test_hmac(MessageDigest::md5(), &tests); + } + + #[test] + fn hmac_sha1() { + // test vectors from RFC 2202 + let tests: [(Vec, Vec, Vec); 7] = [ + ( + iter::repeat(0x0b_u8).take(20).collect(), + b"Hi There".to_vec(), + Vec::from_hex("b617318655057264e28bc0b6fb378c8ef146be00").unwrap(), + ), + ( + b"Jefe".to_vec(), + b"what do ya want for nothing?".to_vec(), + Vec::from_hex("effcdf6ae5eb2fa2d27416d5f184df9c259a7c79").unwrap(), + ), + ( + iter::repeat(0xaa_u8).take(20).collect(), + iter::repeat(0xdd_u8).take(50).collect(), + Vec::from_hex("125d7342b9ac11cd91a39af48aa17b4f63f175d3").unwrap(), + ), + ( + Vec::from_hex("0102030405060708090a0b0c0d0e0f10111213141516171819").unwrap(), + iter::repeat(0xcd_u8).take(50).collect(), + Vec::from_hex("4c9007f4026250c6bc8414f9bf50c86c2d7235da").unwrap(), + ), + ( + iter::repeat(0x0c_u8).take(20).collect(), + b"Test With Truncation".to_vec(), + Vec::from_hex("4c1a03424b55e07fe7f27be1d58bb9324a9a5a04").unwrap(), + ), + ( + iter::repeat(0xaa_u8).take(80).collect(), + b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), + Vec::from_hex("aa4ae5e15272d00e95705637ce8a3b55ed402112").unwrap(), + ), + ( + iter::repeat(0xaa_u8).take(80).collect(), + b"Test Using Larger Than Block-Size Key \ + and Larger Than One Block-Size Data" + .to_vec(), + Vec::from_hex("e8e99d0f45237d786d6bbaa7965c7808bbff1a91").unwrap(), + ), + ]; + + test_hmac(MessageDigest::sha1(), &tests); + } + + #[test] + #[cfg(ossl110)] + fn test_cmac() { + let cipher = ::symm::Cipher::aes_128_cbc(); + let key = Vec::from_hex("9294727a3638bb1c13f48ef8158bfc9d").unwrap(); + let pkey = PKey::cmac(&cipher, &key).unwrap(); + let mut signer = Signer::new_without_digest(&pkey).unwrap(); + + let data = b"Hi There"; + signer.update(data as &[u8]).unwrap(); + + let expected = vec![ + 136, 101, 61, 167, 61, 30, 248, 234, 124, 166, 196, 157, 203, 52, 171, 19 + ]; + assert_eq!(signer.sign_to_vec().unwrap(), expected); + } + + #[test] + fn ec() { + let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap(); + let key = EcKey::generate(&group).unwrap(); + let key = PKey::from_ec_key(key).unwrap(); + + let mut signer = Signer::new(MessageDigest::sha256(), &key).unwrap(); + signer.update(b"hello world").unwrap(); + let signature = signer.sign_to_vec().unwrap(); + + let mut verifier = Verifier::new(MessageDigest::sha256(), &key).unwrap(); + verifier.update(b"hello world").unwrap(); + assert!(verifier.verify(&signature).unwrap()); + } + + #[test] + fn rsa_sign_verify() { + let key = include_bytes!("../test/rsa.pem"); + let private_key = Rsa::private_key_from_pem(key).unwrap(); + let pkey = PKey::from_rsa(private_key).unwrap(); + + let mut signer = Signer::new(MessageDigest::sha256(), &pkey).unwrap(); + signer.set_rsa_padding(Padding::PKCS1_PSS).unwrap(); + assert_eq!(signer.rsa_padding().unwrap(), Padding::PKCS1_PSS); + signer + .set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH) + .unwrap(); + signer.set_rsa_mgf1_md(MessageDigest::sha256()).unwrap(); + signer.update(&Vec::from_hex(INPUT).unwrap()).unwrap(); + let signature = signer.sign_to_vec().unwrap(); + + let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey).unwrap(); + verifier.set_rsa_padding(Padding::PKCS1_PSS).unwrap(); + verifier + .set_rsa_pss_saltlen(RsaPssSaltlen::DIGEST_LENGTH) + .unwrap(); + verifier.set_rsa_mgf1_md(MessageDigest::sha256()).unwrap(); + verifier.update(&Vec::from_hex(INPUT).unwrap()).unwrap(); + assert!(verifier.verify(&signature).unwrap()); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/ssl/bio.rs cargo-0.26.0/vendor/openssl-0.10.6/src/ssl/bio.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/ssl/bio.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/ssl/bio.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,279 @@ +use libc::{c_char, c_int, c_long, c_void, strlen}; +use ffi::{BIO, BIO_CTRL_FLUSH, BIO_new, BIO_clear_retry_flags, BIO_set_retry_read, + BIO_set_retry_write}; +use std::any::Any; +use std::io; +use std::io::prelude::*; +use std::mem; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::ptr; +use std::slice; + +use cvt_p; +use error::ErrorStack; + +pub struct StreamState { + pub stream: S, + pub error: Option, + pub panic: Option>, +} + +/// Safe wrapper for BIO_METHOD +pub struct BioMethod(compat::BIO_METHOD); + +impl BioMethod { + fn new() -> BioMethod { + BioMethod(compat::BIO_METHOD::new::()) + } +} + +unsafe impl Sync for BioMethod {} +unsafe impl Send for BioMethod {} + +pub fn new(stream: S) -> Result<(*mut BIO, BioMethod), ErrorStack> { + let method = BioMethod::new::(); + + let state = Box::new(StreamState { + stream: stream, + error: None, + panic: None, + }); + + unsafe { + let bio = cvt_p(BIO_new(method.0.get()))?; + compat::BIO_set_data(bio, Box::into_raw(state) as *mut _); + compat::BIO_set_init(bio, 1); + + return Ok((bio, method)); + } +} + +pub unsafe fn take_error(bio: *mut BIO) -> Option { + let state = state::(bio); + state.error.take() +} + +pub unsafe fn take_panic(bio: *mut BIO) -> Option> { + let state = state::(bio); + state.panic.take() +} + +pub unsafe fn get_ref<'a, S: 'a>(bio: *mut BIO) -> &'a S { + let state: &'a StreamState = mem::transmute(compat::BIO_get_data(bio)); + &state.stream +} + +pub unsafe fn get_mut<'a, S: 'a>(bio: *mut BIO) -> &'a mut S { + &mut state(bio).stream +} + +unsafe fn state<'a, S: 'a>(bio: *mut BIO) -> &'a mut StreamState { + &mut *(compat::BIO_get_data(bio) as *mut _) +} + +unsafe extern "C" fn bwrite(bio: *mut BIO, buf: *const c_char, len: c_int) -> c_int { + BIO_clear_retry_flags(bio); + + let state = state::(bio); + let buf = slice::from_raw_parts(buf as *const _, len as usize); + + match catch_unwind(AssertUnwindSafe(|| state.stream.write(buf))) { + Ok(Ok(len)) => len as c_int, + Ok(Err(err)) => { + if retriable_error(&err) { + BIO_set_retry_write(bio); + } + state.error = Some(err); + -1 + } + Err(err) => { + state.panic = Some(err); + -1 + } + } +} + +unsafe extern "C" fn bread(bio: *mut BIO, buf: *mut c_char, len: c_int) -> c_int { + BIO_clear_retry_flags(bio); + + let state = state::(bio); + let buf = slice::from_raw_parts_mut(buf as *mut _, len as usize); + + match catch_unwind(AssertUnwindSafe(|| state.stream.read(buf))) { + Ok(Ok(len)) => len as c_int, + Ok(Err(err)) => { + if retriable_error(&err) { + BIO_set_retry_read(bio); + } + state.error = Some(err); + -1 + } + Err(err) => { + state.panic = Some(err); + -1 + } + } +} + +fn retriable_error(err: &io::Error) -> bool { + match err.kind() { + io::ErrorKind::WouldBlock | + io::ErrorKind::NotConnected => true, + _ => false, + } +} + +unsafe extern "C" fn bputs(bio: *mut BIO, s: *const c_char) -> c_int { + bwrite::(bio, s, strlen(s) as c_int) +} + +unsafe extern "C" fn ctrl( + bio: *mut BIO, + cmd: c_int, + _num: c_long, + _ptr: *mut c_void, +) -> c_long { + if cmd == BIO_CTRL_FLUSH { + let state = state::(bio); + + match catch_unwind(AssertUnwindSafe(|| state.stream.flush())) { + Ok(Ok(())) => 1, + Ok(Err(err)) => { + state.error = Some(err); + 0 + } + Err(err) => { + state.panic = Some(err); + 0 + } + } + } else { + 0 + } +} + +unsafe extern "C" fn create(bio: *mut BIO) -> c_int { + compat::BIO_set_init(bio, 0); + compat::BIO_set_num(bio, 0); + compat::BIO_set_data(bio, ptr::null_mut()); + compat::BIO_set_flags(bio, 0); + 1 +} + +unsafe extern "C" fn destroy(bio: *mut BIO) -> c_int { + if bio.is_null() { + return 0; + } + + let data = compat::BIO_get_data(bio); + assert!(!data.is_null()); + Box::>::from_raw(data as *mut _); + compat::BIO_set_data(bio, ptr::null_mut()); + compat::BIO_set_init(bio, 0); + 1 +} + +#[cfg(ossl110)] +#[allow(bad_style)] +mod compat { + use std::io::{Read, Write}; + + use libc::c_int; + use ffi; + pub use ffi::{BIO_set_init, BIO_set_flags, BIO_set_data, BIO_get_data}; + + pub unsafe fn BIO_set_num(_bio: *mut ffi::BIO, _num: c_int) {} + + pub struct BIO_METHOD(*mut ffi::BIO_METHOD); + + impl BIO_METHOD { + pub fn new() -> BIO_METHOD { + unsafe { + let ptr = ffi::BIO_meth_new(ffi::BIO_TYPE_NONE, b"rust\0".as_ptr() as *const _); + assert!(!ptr.is_null()); + let ret = BIO_METHOD(ptr); + assert!(ffi::BIO_meth_set_write(ptr, super::bwrite::) != 0); + assert!(ffi::BIO_meth_set_read(ptr, super::bread::) != 0); + assert!(ffi::BIO_meth_set_puts(ptr, super::bputs::) != 0); + assert!(ffi::BIO_meth_set_ctrl(ptr, super::ctrl::) != 0); + assert!(ffi::BIO_meth_set_create(ptr, super::create) != 0); + assert!(ffi::BIO_meth_set_destroy(ptr, super::destroy::) != 0); + return ret; + } + } + + pub fn get(&self) -> *mut ffi::BIO_METHOD { + self.0 + } + } + + impl Drop for BIO_METHOD { + fn drop(&mut self) { + unsafe { + ffi::BIO_meth_free(self.0); + } + } + } +} + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use std::io::{Read, Write}; + + use ffi; + use libc::{c_int, c_void}; + + pub struct BIO_METHOD(*mut ffi::BIO_METHOD); + + impl BIO_METHOD { + pub fn new() -> BIO_METHOD { + let ptr = Box::new(ffi::BIO_METHOD { + type_: ffi::BIO_TYPE_NONE, + name: b"rust\0".as_ptr() as *const _, + bwrite: Some(super::bwrite::), + bread: Some(super::bread::), + bputs: Some(super::bputs::), + bgets: None, + ctrl: Some(super::ctrl::), + create: Some(super::create), + destroy: Some(super::destroy::), + callback_ctrl: None, + }); + + BIO_METHOD(Box::into_raw(ptr)) + } + + pub fn get(&self) -> *mut ffi::BIO_METHOD { + self.0 + } + } + + impl Drop for BIO_METHOD { + fn drop(&mut self) { + unsafe { + Box::::from_raw(self.0); + } + } + } + + pub unsafe fn BIO_set_init(bio: *mut ffi::BIO, init: c_int) { + (*bio).init = init; + } + + pub unsafe fn BIO_set_flags(bio: *mut ffi::BIO, flags: c_int) { + (*bio).flags = flags; + } + + pub unsafe fn BIO_get_data(bio: *mut ffi::BIO) -> *mut c_void { + (*bio).ptr + } + + pub unsafe fn BIO_set_data(bio: *mut ffi::BIO, data: *mut c_void) { + (*bio).ptr = data; + } + + pub unsafe fn BIO_set_num(bio: *mut ffi::BIO, num: c_int) { + (*bio).num = num; + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/ssl/callbacks.rs cargo-0.26.0/vendor/openssl-0.10.6/src/ssl/callbacks.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/ssl/callbacks.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/ssl/callbacks.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,583 @@ +use ffi; +use libc::{c_char, c_int, c_uchar, c_uint, c_void}; +#[cfg(ossl111)] +use libc::size_t; +use std::ffi::CStr; +use std::ptr; +use std::slice; +use std::mem; +#[cfg(ossl111)] +use std::str; +use foreign_types::ForeignTypeRef; +use foreign_types::ForeignType; + +use error::ErrorStack; +use dh::Dh; +#[cfg(any(ossl101, ossl102))] +use ec::EcKey; +use pkey::Params; +use ssl::{get_callback_idx, get_ssl_callback_idx, SniError, SslAlert, SslContextRef, SslRef, + SslSession, SslSessionRef}; +#[cfg(any(ossl102, ossl110))] +use ssl::AlpnError; +use x509::X509StoreContextRef; +#[cfg(ossl111)] +use ssl::ExtensionContext; +#[cfg(ossl111)] +use x509::X509Ref; + +pub extern "C" fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int +where + F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send, +{ + unsafe { + let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); + let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx); + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let verify = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); + let verify: &F = &*(verify as *mut F); + + let ctx = X509StoreContextRef::from_ptr_mut(x509_ctx); + + verify(preverify_ok != 0, ctx) as c_int + } +} + +#[cfg(not(osslconf = "OPENSSL_NO_PSK"))] +pub extern "C" fn raw_psk( + ssl: *mut ffi::SSL, + hint: *const c_char, + identity: *mut c_char, + max_identity_len: c_uint, + psk: *mut c_uchar, + max_psk_len: c_uint, +) -> c_uint +where + F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result + + 'static + + Sync + + Send, +{ + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); + let ssl = SslRef::from_ptr_mut(ssl); + let callback = &*(callback as *mut F); + let hint = if hint != ptr::null() { + Some(CStr::from_ptr(hint).to_bytes()) + } else { + None + }; + // Give the callback mutable slices into which it can write the identity and psk. + let identity_sl = slice::from_raw_parts_mut(identity as *mut u8, max_identity_len as usize); + let psk_sl = slice::from_raw_parts_mut(psk as *mut u8, max_psk_len as usize); + match callback(ssl, hint, identity_sl, psk_sl) { + Ok(psk_len) => psk_len as u32, + _ => 0, + } + } +} + +pub extern "C" fn ssl_raw_verify( + preverify_ok: c_int, + x509_ctx: *mut ffi::X509_STORE_CTX, +) -> c_int +where + F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send, +{ + unsafe { + let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); + let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx); + let verify = ffi::SSL_get_ex_data(ssl as *const _, get_ssl_callback_idx::()); + let verify: &F = &*(verify as *mut F); + + let ctx = X509StoreContextRef::from_ptr_mut(x509_ctx); + + verify(preverify_ok != 0, ctx) as c_int + } +} + +pub extern "C" fn raw_sni(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) -> c_int +where + F: Fn(&mut SslRef, &mut SslAlert) -> Result<(), SniError> + 'static + Sync + Send, +{ + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); + let callback: &F = &*(callback as *mut F); + let ssl = SslRef::from_ptr_mut(ssl); + let mut alert = SslAlert(*al); + + let r = callback(ssl, &mut alert); + *al = alert.0; + match r { + Ok(()) => ffi::SSL_TLSEXT_ERR_OK, + Err(e) => e.0, + } + } +} + +#[cfg(any(ossl102, ossl110))] +pub extern "C" fn raw_alpn_select( + ssl: *mut ffi::SSL, + out: *mut *const c_uchar, + outlen: *mut c_uchar, + inbuf: *const c_uchar, + inlen: c_uint, + _arg: *mut c_void, +) -> c_int +where + F: for<'a> Fn(&mut SslRef, &'a [u8]) -> Result<&'a [u8], AlpnError> + 'static + Sync + Send, +{ + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); + let callback: &F = &*(callback as *mut F); + let ssl = SslRef::from_ptr_mut(ssl); + let protos = slice::from_raw_parts(inbuf as *const u8, inlen as usize); + + match callback(ssl, protos) { + Ok(proto) => { + *out = proto.as_ptr() as *const c_uchar; + *outlen = proto.len() as c_uchar; + ffi::SSL_TLSEXT_ERR_OK + } + Err(e) => e.0, + } + } +} + +pub unsafe extern "C" fn raw_tmp_dh( + ssl: *mut ffi::SSL, + is_export: c_int, + keylength: c_int, +) -> *mut ffi::DH +where + F: Fn(&mut SslRef, bool, u32) -> Result, ErrorStack> + 'static + Sync + Send, +{ + let ctx = ffi::SSL_get_SSL_CTX(ssl); + let callback = ffi::SSL_CTX_get_ex_data(ctx, get_callback_idx::()); + let callback = &*(callback as *mut F); + + let ssl = SslRef::from_ptr_mut(ssl); + match callback(ssl, is_export != 0, keylength as u32) { + Ok(dh) => { + let ptr = dh.as_ptr(); + mem::forget(dh); + ptr + } + Err(e) => { + e.put(); + ptr::null_mut() + } + } +} + +#[cfg(any(ossl101, ossl102))] +pub unsafe extern "C" fn raw_tmp_ecdh( + ssl: *mut ffi::SSL, + is_export: c_int, + keylength: c_int, +) -> *mut ffi::EC_KEY +where + F: Fn(&mut SslRef, bool, u32) -> Result, ErrorStack> + 'static + Sync + Send, +{ + let ctx = ffi::SSL_get_SSL_CTX(ssl); + let callback = ffi::SSL_CTX_get_ex_data(ctx, get_callback_idx::()); + let callback = &*(callback as *mut F); + + let ssl = SslRef::from_ptr_mut(ssl); + match callback(ssl, is_export != 0, keylength as u32) { + Ok(ec_key) => { + let ptr = ec_key.as_ptr(); + mem::forget(ec_key); + ptr + } + Err(e) => { + e.put(); + ptr::null_mut() + } + } +} + +pub unsafe extern "C" fn raw_tmp_dh_ssl( + ssl: *mut ffi::SSL, + is_export: c_int, + keylength: c_int, +) -> *mut ffi::DH +where + F: Fn(&mut SslRef, bool, u32) -> Result, ErrorStack> + 'static + Sync + Send, +{ + let callback = ffi::SSL_get_ex_data(ssl, get_ssl_callback_idx::()); + let callback = &*(callback as *mut F); + + let ssl = SslRef::from_ptr_mut(ssl); + match callback(ssl, is_export != 0, keylength as u32) { + Ok(dh) => { + let ptr = dh.as_ptr(); + mem::forget(dh); + ptr + } + Err(e) => { + e.put(); + ptr::null_mut() + } + } +} + +#[cfg(any(ossl101, ossl102))] +pub unsafe extern "C" fn raw_tmp_ecdh_ssl( + ssl: *mut ffi::SSL, + is_export: c_int, + keylength: c_int, +) -> *mut ffi::EC_KEY +where + F: Fn(&mut SslRef, bool, u32) -> Result, ErrorStack> + 'static + Sync + Send, +{ + let callback = ffi::SSL_get_ex_data(ssl, get_ssl_callback_idx::()); + let callback = &*(callback as *mut F); + + let ssl = SslRef::from_ptr_mut(ssl); + match callback(ssl, is_export != 0, keylength as u32) { + Ok(ec_key) => { + let ptr = ec_key.as_ptr(); + mem::forget(ec_key); + ptr + } + Err(e) => { + e.put(); + ptr::null_mut() + } + } +} + +pub unsafe extern "C" fn raw_tlsext_status(ssl: *mut ffi::SSL, _: *mut c_void) -> c_int +where + F: Fn(&mut SslRef) -> Result + 'static + Sync + Send, +{ + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); + let callback = &*(callback as *mut F); + + let ssl = SslRef::from_ptr_mut(ssl); + let ret = callback(ssl); + + if ssl.is_server() { + match ret { + Ok(true) => ffi::SSL_TLSEXT_ERR_OK, + Ok(false) => ffi::SSL_TLSEXT_ERR_NOACK, + Err(e) => { + e.put(); + ffi::SSL_TLSEXT_ERR_ALERT_FATAL + } + } + } else { + match ret { + Ok(true) => 1, + Ok(false) => 0, + Err(e) => { + e.put(); + -1 + } + } + } +} + +pub unsafe extern "C" fn raw_new_session( + ssl: *mut ffi::SSL, + session: *mut ffi::SSL_SESSION, +) -> c_int +where + F: Fn(&mut SslRef, SslSession) + 'static + Sync + Send, +{ + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); + let callback = &*(callback as *mut F); + + let ssl = SslRef::from_ptr_mut(ssl); + let session = SslSession::from_ptr(session); + + callback(ssl, session); + + // the return code doesn't indicate error vs success, but whether or not we consumed the session + 1 +} + +pub unsafe extern "C" fn raw_remove_session( + ctx: *mut ffi::SSL_CTX, + session: *mut ffi::SSL_SESSION, +) where + F: Fn(&SslContextRef, &SslSessionRef) + 'static + Sync + Send, +{ + let callback = ffi::SSL_CTX_get_ex_data(ctx, get_callback_idx::()); + let callback = &*(callback as *mut F); + + let ctx = SslContextRef::from_ptr(ctx); + let session = SslSessionRef::from_ptr(session); + + callback(ctx, session) +} + +#[cfg(any(ossl110))] +type DataPtr = *const c_uchar; +#[cfg(not(any(ossl110)))] +type DataPtr = *mut c_uchar; + +pub unsafe extern "C" fn raw_get_session( + ssl: *mut ffi::SSL, + data: DataPtr, + len: c_int, + copy: *mut c_int, +) -> *mut ffi::SSL_SESSION +where + F: Fn(&mut SslRef, &[u8]) -> Option + 'static + Sync + Send, +{ + let ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ctx, get_callback_idx::()); + let callback = &*(callback as *mut F); + + let ssl = SslRef::from_ptr_mut(ssl); + let data = slice::from_raw_parts(data as *const u8, len as usize); + + match callback(ssl, data) { + Some(session) => { + let p = session.as_ptr(); + mem::forget(p); + *copy = 0; + p + } + None => ptr::null_mut(), + } +} + +#[cfg(ossl111)] +pub unsafe extern "C" fn raw_keylog(ssl: *const ffi::SSL, line: *const c_char) +where + F: Fn(&SslRef, &str) + 'static + Sync + Send, +{ + let ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ctx, get_callback_idx::()); + let callback = &*(callback as *mut F); + + let ssl = SslRef::from_ptr(ssl as *mut _); + let line = CStr::from_ptr(line).to_bytes(); + let line = str::from_utf8_unchecked(line); + + callback(ssl, line); +} + +#[cfg(ossl111)] +pub extern "C" fn raw_stateless_cookie_generate( + ssl: *mut ffi::SSL, + cookie: *mut c_uchar, + cookie_len: *mut size_t, +) -> c_int +where + F: Fn(&mut SslRef, &mut [u8]) -> Result + 'static + Sync + Send, +{ + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); + let ssl = SslRef::from_ptr_mut(ssl); + let callback = &*(callback as *mut F); + let slice = + slice::from_raw_parts_mut(cookie as *mut u8, ffi::SSL_COOKIE_LENGTH as usize); + match callback(ssl, slice) { + Ok(len) => { + *cookie_len = len as size_t; + 1 + } + Err(e) => { + e.put(); + 0 + } + } + } +} + +#[cfg(ossl111)] +pub extern "C" fn raw_stateless_cookie_verify( + ssl: *mut ffi::SSL, + cookie: *const c_uchar, + cookie_len: size_t, +) -> c_int +where + F: Fn(&mut SslRef, &[u8]) -> bool + 'static + Sync + Send, +{ + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); + let ssl = SslRef::from_ptr_mut(ssl); + let callback = &*(callback as *mut F); + let slice = + slice::from_raw_parts(cookie as *const c_uchar as *const u8, cookie_len as usize); + callback(ssl, slice) as c_int + } +} + +pub extern "C" fn raw_cookie_generate( + ssl: *mut ffi::SSL, + cookie: *mut c_uchar, + cookie_len: *mut c_uint, +) -> c_int +where + F: Fn(&mut SslRef, &mut [u8]) -> Result + 'static + Sync + Send, +{ + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); + let ssl = SslRef::from_ptr_mut(ssl); + let callback = &*(callback as *mut F); + // We subtract 1 from DTLS1_COOKIE_LENGTH as the ostensible value, 256, is erroneous but retained for + // compatibility. See comments in dtls1.h. + let slice = + slice::from_raw_parts_mut(cookie as *mut u8, ffi::DTLS1_COOKIE_LENGTH as usize - 1); + match callback(ssl, slice) { + Ok(len) => { + *cookie_len = len as c_uint; + 1 + } + Err(e) => { + e.put(); + 0 + } + } + } +} + +#[cfg(ossl110)] +type CookiePtr = *const c_uchar; + +#[cfg(not(ossl110))] +type CookiePtr = *mut c_uchar; + +pub extern "C" fn raw_cookie_verify( + ssl: *mut ffi::SSL, + cookie: CookiePtr, + cookie_len: c_uint, +) -> c_int +where + F: Fn(&mut SslRef, &[u8]) -> bool + 'static + Sync + Send, +{ + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); + let ssl = SslRef::from_ptr_mut(ssl); + let callback = &*(callback as *mut F); + let slice = + slice::from_raw_parts(cookie as *const c_uchar as *const u8, cookie_len as usize); + callback(ssl, slice) as c_int + } +} + +#[cfg(ossl111)] +pub struct CustomExtAddState(Option); + +#[cfg(ossl111)] +pub extern "C" fn raw_custom_ext_add( + ssl: *mut ffi::SSL, + _: c_uint, + context: c_uint, + out: *mut *const c_uchar, + outlen: *mut size_t, + x: *mut ffi::X509, + chainidx: size_t, + al: *mut c_int, + _: *mut c_void, +) -> c_int +where + F: Fn(&mut SslRef, ExtensionContext, Option<(usize, &X509Ref)>) -> Result, SslAlert> + + 'static, + T: AsRef<[u8]> + 'static + Sync + Send, +{ + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); + let callback = &*(callback as *mut F); + let ssl = SslRef::from_ptr_mut(ssl); + let ectx = ExtensionContext::from_bits_truncate(context); + let cert = if ectx.contains(ExtensionContext::TLS1_3_CERTIFICATE) { + Some((chainidx, X509Ref::from_ptr(x))) + } else { + None + }; + match (callback)(ssl, ectx, cert) { + Ok(None) => 0, + Ok(Some(buf)) => { + *outlen = buf.as_ref().len() as size_t; + *out = buf.as_ref().as_ptr(); + + let idx = get_ssl_callback_idx::>(); + let ptr = ffi::SSL_get_ex_data(ssl.as_ptr(), idx); + if ptr.is_null() { + let x = Box::into_raw(Box::>::new(CustomExtAddState( + Some(buf), + ))) as *mut c_void; + ffi::SSL_set_ex_data(ssl.as_ptr(), idx, x); + } else { + *(ptr as *mut _) = CustomExtAddState(Some(buf)) + } + 1 + } + Err(alert) => { + *al = alert.0; + -1 + } + } + } +} + +#[cfg(ossl111)] +pub extern "C" fn raw_custom_ext_free( + ssl: *mut ffi::SSL, + _: c_uint, + _: c_uint, + _: *mut *const c_uchar, + _: *mut c_void, +) where + T: 'static + Sync + Send, +{ + unsafe { + let state = ffi::SSL_get_ex_data(ssl, get_ssl_callback_idx::>()); + let state = &mut (*(state as *mut CustomExtAddState)).0; + state.take(); + } +} + +#[cfg(ossl111)] +pub extern "C" fn raw_custom_ext_parse( + ssl: *mut ffi::SSL, + _: c_uint, + context: c_uint, + input: *const c_uchar, + inlen: size_t, + x: *mut ffi::X509, + chainidx: size_t, + al: *mut c_int, + _: *mut c_void, +) -> c_int +where + F: FnMut(&mut SslRef, ExtensionContext, &[u8], Option<(usize, &X509Ref)>) -> Result<(), SslAlert> + + 'static, +{ + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); + let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); + let ssl = SslRef::from_ptr_mut(ssl); + let callback = &mut *(callback as *mut F); + let ectx = ExtensionContext::from_bits_truncate(context); + let slice = slice::from_raw_parts(input as *const u8, inlen as usize); + let cert = if ectx.contains(ExtensionContext::TLS1_3_CERTIFICATE) { + Some((chainidx, X509Ref::from_ptr(x))) + } else { + None + }; + match callback(ssl, ectx, slice, cert) { + Ok(()) => 1, + Err(alert) => { + *al = alert.0; + 0 + } + } + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/ssl/connector.rs cargo-0.26.0/vendor/openssl-0.10.6/src/ssl/connector.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/ssl/connector.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/ssl/connector.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,502 @@ +use std::io::{Read, Write}; +use std::ops::{Deref, DerefMut}; + +use dh::Dh; +use error::ErrorStack; +use ssl::{HandshakeError, Ssl, SslContext, SslContextBuilder, SslMethod, SslMode, SslOptions, + SslRef, SslStream, SslVerifyMode}; +use version; + +fn ctx(method: SslMethod) -> Result { + let mut ctx = SslContextBuilder::new(method)?; + + let mut opts = SslOptions::ALL | SslOptions::NO_COMPRESSION | SslOptions::NO_SSLV2 + | SslOptions::NO_SSLV3 | SslOptions::SINGLE_DH_USE + | SslOptions::SINGLE_ECDH_USE | SslOptions::CIPHER_SERVER_PREFERENCE; + opts &= !SslOptions::DONT_INSERT_EMPTY_FRAGMENTS; + + ctx.set_options(opts); + + let mut mode = + SslMode::AUTO_RETRY | SslMode::ACCEPT_MOVING_WRITE_BUFFER | SslMode::ENABLE_PARTIAL_WRITE; + + // This is quite a useful optimization for saving memory, but historically + // caused CVEs in OpenSSL pre-1.0.1h, according to + // https://bugs.python.org/issue25672 + if version::number() >= 0x1000108f { + mode |= SslMode::RELEASE_BUFFERS; + } + + ctx.set_mode(mode); + + Ok(ctx) +} + +/// A type which wraps client-side streams in a TLS session. +/// +/// OpenSSL's default configuration is highly insecure. This connector manages the OpenSSL +/// structures, configuring cipher suites, session options, hostname verification, and more. +/// +/// OpenSSL's built in hostname verification is used when linking against OpenSSL 1.0.2 or 1.1.0, +/// and a custom implementation is used when linking against OpenSSL 1.0.1. +#[derive(Clone)] +pub struct SslConnector(SslContext); + +impl SslConnector { + /// Creates a new builder for TLS connections. + /// + /// The default configuration is subject to change, and is currently derived from Python. + pub fn builder(method: SslMethod) -> Result { + let mut ctx = ctx(method)?; + ctx.set_default_verify_paths()?; + ctx.set_cipher_list( + "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK", + )?; + setup_verify(&mut ctx); + + Ok(SslConnectorBuilder(ctx)) + } + + /// Initiates a client-side TLS session on a stream. + /// + /// The domain is used for SNI and hostname verification. + pub fn connect(&self, domain: &str, stream: S) -> Result, HandshakeError> + where + S: Read + Write, + { + self.configure()?.connect(domain, stream) + } + + /// Returns a structure allowing for configuration of a single TLS session before connection. + pub fn configure(&self) -> Result { + Ssl::new(&self.0).map(|ssl| ConnectConfiguration { + ssl, + sni: true, + verify_hostname: true, + }) + } +} + +/// A builder for `SslConnector`s. +pub struct SslConnectorBuilder(SslContextBuilder); + +impl SslConnectorBuilder { + /// Consumes the builder, returning an `SslConnector`. + pub fn build(self) -> SslConnector { + SslConnector(self.0.build()) + } +} + +impl Deref for SslConnectorBuilder { + type Target = SslContextBuilder; + + fn deref(&self) -> &SslContextBuilder { + &self.0 + } +} + +impl DerefMut for SslConnectorBuilder { + fn deref_mut(&mut self) -> &mut SslContextBuilder { + &mut self.0 + } +} + +/// A type which allows for configuration of a client-side TLS session before connection. +pub struct ConnectConfiguration { + ssl: Ssl, + sni: bool, + verify_hostname: bool, +} + +impl ConnectConfiguration { + /// A builder-style version of `set_use_server_name_indication`. + pub fn use_server_name_indication(mut self, use_sni: bool) -> ConnectConfiguration { + self.set_use_server_name_indication(use_sni); + self + } + + /// Configures the use of Server Name Indication (SNI) when connecting. + /// + /// Defaults to `true`. + pub fn set_use_server_name_indication(&mut self, use_sni: bool) { + self.sni = use_sni; + } + + /// A builder-style version of `set_verify_hostname`. + pub fn verify_hostname(mut self, verify_hostname: bool) -> ConnectConfiguration { + self.set_verify_hostname(verify_hostname); + self + } + + /// Configures the use of hostname verification when connecting. + /// + /// Defaults to `true`. + /// + /// # Warning + /// + /// You should think very carefully before you use this method. If hostname verification is not + /// used, *any* valid certificate for *any* site will be trusted for use from any other. This + /// introduces a significant vulnerability to man-in-the-middle attacks. + pub fn set_verify_hostname(&mut self, verify_hostname: bool) { + self.verify_hostname = verify_hostname; + } + + /// Initiates a client-side TLS session on a stream. + /// + /// The domain is used for SNI and hostname verification if enabled. + pub fn connect(mut self, domain: &str, stream: S) -> Result, HandshakeError> + where + S: Read + Write, + { + if self.sni { + self.ssl.set_hostname(domain)?; + } + + if self.verify_hostname { + setup_verify_hostname(&mut self.ssl, domain)?; + } + + self.ssl.connect(stream) + } +} + +impl Deref for ConnectConfiguration { + type Target = SslRef; + + fn deref(&self) -> &SslRef { + &self.ssl + } +} + +impl DerefMut for ConnectConfiguration { + fn deref_mut(&mut self) -> &mut SslRef { + &mut self.ssl + } +} + +/// A type which wraps server-side streams in a TLS session. +/// +/// OpenSSL's default configuration is highly insecure. This connector manages the OpenSSL +/// structures, configuring cipher suites, session options, and more. +#[derive(Clone)] +pub struct SslAcceptor(SslContext); + +impl SslAcceptor { + /// Creates a new builder configured to connect to non-legacy clients. This should generally be + /// considered a reasonable default choice. + /// + /// This corresponds to the intermediate configuration of Mozilla's server side TLS + /// recommendations. See its [documentation][docs] for more details on specifics. + /// + /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS + pub fn mozilla_intermediate(method: SslMethod) -> Result { + let mut ctx = ctx(method)?; + #[cfg(ossl111)] + ctx.set_options(SslOptions::NO_TLSV1_3); + let dh = Dh::params_from_pem( + b" +-----BEGIN DH PARAMETERS----- +MIIBCAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz ++8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a +87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7 +YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi +7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD +ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg== +-----END DH PARAMETERS----- +", + )?; + ctx.set_tmp_dh(&dh)?; + setup_curves(&mut ctx)?; + ctx.set_cipher_list( + "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ + ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:\ + ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\ + DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:\ + ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:\ + ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:\ + ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:\ + DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:\ + EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:\ + AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS", + )?; + Ok(SslAcceptorBuilder(ctx)) + } + + /// Creates a new builder configured to connect to modern clients. + /// + /// This corresponds to the modern configuration of Mozilla's server side TLS recommendations. + /// See its [documentation][docs] for more details on specifics. + /// + /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS + pub fn mozilla_modern(method: SslMethod) -> Result { + let mut ctx = ctx(method)?; + ctx.set_options(SslOptions::NO_TLSV1 | SslOptions::NO_TLSV1_1); + #[cfg(ossl111)] + ctx.set_options(SslOptions::NO_TLSV1_3); + setup_curves(&mut ctx)?; + ctx.set_cipher_list( + "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\ + ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ + ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:\ + ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256", + )?; + Ok(SslAcceptorBuilder(ctx)) + } + + /// Initiates a server-side TLS session on a stream. + pub fn accept(&self, stream: S) -> Result, HandshakeError> + where + S: Read + Write, + { + let ssl = Ssl::new(&self.0)?; + ssl.accept(stream) + } +} + +/// A builder for `SslAcceptor`s. +pub struct SslAcceptorBuilder(SslContextBuilder); + +impl SslAcceptorBuilder { + /// Consumes the builder, returning a `SslAcceptor`. + pub fn build(self) -> SslAcceptor { + SslAcceptor(self.0.build()) + } +} + +impl Deref for SslAcceptorBuilder { + type Target = SslContextBuilder; + + fn deref(&self) -> &SslContextBuilder { + &self.0 + } +} + +impl DerefMut for SslAcceptorBuilder { + fn deref_mut(&mut self) -> &mut SslContextBuilder { + &mut self.0 + } +} + +#[cfg(ossl101)] +fn setup_curves(ctx: &mut SslContextBuilder) -> Result<(), ErrorStack> { + use ec::EcKey; + use nid::Nid; + + let curve = EcKey::from_curve_name(Nid::X9_62_PRIME256V1)?; + ctx.set_tmp_ecdh(&curve) +} + +#[cfg(ossl102)] +fn setup_curves(ctx: &mut SslContextBuilder) -> Result<(), ErrorStack> { + ctx.set_ecdh_auto(true) +} + +#[cfg(ossl110)] +fn setup_curves(_: &mut SslContextBuilder) -> Result<(), ErrorStack> { + Ok(()) +} + +#[cfg(any(ossl102, ossl110))] +fn setup_verify(ctx: &mut SslContextBuilder) { + ctx.set_verify(SslVerifyMode::PEER); +} + +#[cfg(ossl101)] +fn setup_verify(ctx: &mut SslContextBuilder) { + ctx.set_verify_callback(SslVerifyMode::PEER, verify::verify_callback); +} + +#[cfg(any(ossl102, ossl110))] +fn setup_verify_hostname(ssl: &mut Ssl, domain: &str) -> Result<(), ErrorStack> { + use x509::verify::X509CheckFlags; + + let param = ssl.param_mut(); + param.set_hostflags(X509CheckFlags::NO_PARTIAL_WILDCARDS); + match domain.parse() { + Ok(ip) => param.set_ip(ip), + Err(_) => param.set_host(domain), + } +} + +#[cfg(ossl101)] +fn setup_verify_hostname(ssl: &mut Ssl, domain: &str) -> Result<(), ErrorStack> { + let domain = domain.to_string(); + ssl.set_ex_data(*verify::HOSTNAME_IDX, domain); + Ok(()) +} + +#[cfg(ossl101)] +mod verify { + use std::net::IpAddr; + use std::str; + + use ex_data::Index; + use nid::Nid; + use x509::{GeneralName, X509NameRef, X509Ref, X509StoreContext, X509StoreContextRef, + X509VerifyResult}; + use stack::Stack; + use ssl::Ssl; + + lazy_static! { + pub static ref HOSTNAME_IDX: Index = Ssl::new_ex_index().unwrap(); + } + + pub fn verify_callback(preverify_ok: bool, x509_ctx: &mut X509StoreContextRef) -> bool { + if !preverify_ok || x509_ctx.error_depth() != 0 { + return preverify_ok; + } + + let ok = match ( + x509_ctx.current_cert(), + X509StoreContext::ssl_idx() + .ok() + .and_then(|idx| x509_ctx.ex_data(idx)) + .and_then(|ssl| ssl.ex_data(*HOSTNAME_IDX)), + ) { + (Some(x509), Some(domain)) => verify_hostname(domain, &x509), + _ => true, + }; + + if !ok { + x509_ctx.set_error(X509VerifyResult::APPLICATION_VERIFICATION); + } + + ok + } + + fn verify_hostname(domain: &str, cert: &X509Ref) -> bool { + match cert.subject_alt_names() { + Some(names) => verify_subject_alt_names(domain, names), + None => verify_subject_name(domain, &cert.subject_name()), + } + } + + fn verify_subject_alt_names(domain: &str, names: Stack) -> bool { + let ip = domain.parse(); + + for name in &names { + match ip { + Ok(ip) => { + if let Some(actual) = name.ipaddress() { + if matches_ip(&ip, actual) { + return true; + } + } + } + Err(_) => { + if let Some(pattern) = name.dnsname() { + if matches_dns(pattern, domain) { + return true; + } + } + } + } + } + + false + } + + fn verify_subject_name(domain: &str, subject_name: &X509NameRef) -> bool { + match subject_name.entries_by_nid(Nid::COMMONNAME).next() { + Some(pattern) => { + let pattern = match str::from_utf8(pattern.data().as_slice()) { + Ok(pattern) => pattern, + Err(_) => return false, + }; + + // Unlike SANs, IP addresses in the subject name don't have a + // different encoding. + match domain.parse::() { + Ok(ip) => pattern + .parse::() + .ok() + .map_or(false, |pattern| pattern == ip), + Err(_) => matches_dns(pattern, domain), + } + } + None => false, + } + } + + fn matches_dns(mut pattern: &str, mut hostname: &str) -> bool { + // first strip trailing . off of pattern and hostname to normalize + if pattern.ends_with('.') { + pattern = &pattern[..pattern.len() - 1]; + } + if hostname.ends_with('.') { + hostname = &hostname[..hostname.len() - 1]; + } + + matches_wildcard(pattern, hostname).unwrap_or_else(|| pattern == hostname) + } + + fn matches_wildcard(pattern: &str, hostname: &str) -> Option { + // internationalized domains can't involved in wildcards + if pattern.starts_with("xn--") { + return None; + } + + let wildcard_location = match pattern.find('*') { + Some(l) => l, + None => return None, + }; + + let mut dot_idxs = pattern.match_indices('.').map(|(l, _)| l); + let wildcard_end = match dot_idxs.next() { + Some(l) => l, + None => return None, + }; + + // Never match wildcards if the pattern has less than 2 '.'s (no *.com) + // + // This is a bit dubious, as it doesn't disallow other TLDs like *.co.uk. + // Chrome has a black- and white-list for this, but Firefox (via NSS) does + // the same thing we do here. + // + // The Public Suffix (https://www.publicsuffix.org/) list could + // potentially be used here, but it's both huge and updated frequently + // enough that management would be a PITA. + if dot_idxs.next().is_none() { + return None; + } + + // Wildcards can only be in the first component + if wildcard_location > wildcard_end { + return None; + } + + let hostname_label_end = match hostname.find('.') { + Some(l) => l, + None => return None, + }; + + // check that the non-wildcard parts are identical + if pattern[wildcard_end..] != hostname[hostname_label_end..] { + return Some(false); + } + + let wildcard_prefix = &pattern[..wildcard_location]; + let wildcard_suffix = &pattern[wildcard_location + 1..wildcard_end]; + + let hostname_label = &hostname[..hostname_label_end]; + + // check the prefix of the first label + if !hostname_label.starts_with(wildcard_prefix) { + return Some(false); + } + + // and the suffix + if !hostname_label[wildcard_prefix.len()..].ends_with(wildcard_suffix) { + return Some(false); + } + + Some(true) + } + + fn matches_ip(expected: &IpAddr, actual: &[u8]) -> bool { + match *expected { + IpAddr::V4(ref addr) => actual == addr.octets(), + IpAddr::V6(ref addr) => actual == addr.octets(), + } + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/ssl/error.rs cargo-0.26.0/vendor/openssl-0.10.6/src/ssl/error.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/ssl/error.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/ssl/error.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,183 @@ +use ffi; +use libc::c_int; +use std::error; +use std::error::Error as StdError; +use std::fmt; +use std::io; + +use error::ErrorStack; +use ssl::MidHandshakeSslStream; +use x509::X509VerifyResult; + +/// An error code returned from SSL functions. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct ErrorCode(c_int); + +impl ErrorCode { + pub fn from_raw(raw: c_int) -> ErrorCode { + ErrorCode(raw) + } + + pub fn as_raw(&self) -> c_int { + self.0 + } + + /// The SSL session has been closed. + pub const ZERO_RETURN: ErrorCode = ErrorCode(ffi::SSL_ERROR_ZERO_RETURN); + + /// An attempt to read data from the underlying socket returned `WouldBlock`. + /// + /// Wait for read readiness and retry the operation. + pub const WANT_READ: ErrorCode = ErrorCode(ffi::SSL_ERROR_WANT_READ); + + /// An attempt to write data to the underlying socket returned `WouldBlock`. + /// + /// Wait for write readiness and retry the operation. + pub const WANT_WRITE: ErrorCode = ErrorCode(ffi::SSL_ERROR_WANT_WRITE); + + /// A non-recoverable IO error occurred. + pub const SYSCALL: ErrorCode = ErrorCode(ffi::SSL_ERROR_SYSCALL); + + /// An error occurred in the SSL library. + pub const SSL: ErrorCode = ErrorCode(ffi::SSL_ERROR_SSL); +} + +#[derive(Debug)] +pub(crate) enum InnerError { + Io(io::Error), + Ssl(ErrorStack), +} + +/// An SSL error. +#[derive(Debug)] +pub struct Error { + pub(crate) code: ErrorCode, + pub(crate) cause: Option, +} + +impl Error { + pub fn code(&self) -> ErrorCode { + self.code + } + + pub fn io_error(&self) -> Option<&io::Error> { + match self.cause { + Some(InnerError::Io(ref e)) => Some(e), + _ => None, + } + } + + pub fn into_io_error(self) -> Result { + match self.cause { + Some(InnerError::Io(e)) => Ok(e), + _ => Err(self), + } + } + + pub fn ssl_error(&self) -> Option<&ErrorStack> { + match self.cause { + Some(InnerError::Ssl(ref e)) => Some(e), + _ => None, + } + } +} + +impl From for Error { + fn from(e: ErrorStack) -> Error { + Error { + code: ErrorCode::SSL, + cause: Some(InnerError::Ssl(e)), + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + match self.code { + ErrorCode::ZERO_RETURN => fmt.write_str("the SSL session has been shut down"), + ErrorCode::WANT_READ => match self.io_error() { + Some(_) => fmt.write_str("a nonblocking read call would have blocked"), + None => fmt.write_str("the operation should be retried"), + }, + ErrorCode::SYSCALL => match self.io_error() { + Some(err) => write!(fmt, "the inner stream returned an error: {}", err), + None => fmt.write_str("unexpected EOF"), + }, + ErrorCode::SSL => { + fmt.write_str("OpenSSL error")?; + if let Some(ref err) = self.ssl_error() { + write!(fmt, ": {}", err)? + } + Ok(()) + } + ErrorCode(code) => write!(fmt, "unknown error code {}", code), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + "an OpenSSL error" + } + + fn cause(&self) -> Option<&error::Error> { + match self.cause { + Some(InnerError::Io(ref e)) => Some(e), + Some(InnerError::Ssl(ref e)) => Some(e), + None => None, + } + } +} + +/// An error or intermediate state after a TLS handshake attempt. +#[derive(Debug)] +pub enum HandshakeError { + /// Setup failed. + SetupFailure(ErrorStack), + /// The handshake failed. + Failure(MidHandshakeSslStream), + /// The handshake encountered a `WouldBlock` error midway through. + /// + /// This error will never be returned for blocking streams. + WouldBlock(MidHandshakeSslStream), +} + +impl StdError for HandshakeError { + fn description(&self) -> &str { + match *self { + HandshakeError::SetupFailure(_) => "stream setup failed", + HandshakeError::Failure(_) => "the handshake failed", + HandshakeError::WouldBlock(_) => "the handshake was interrupted", + } + } + + fn cause(&self) -> Option<&StdError> { + match *self { + HandshakeError::SetupFailure(ref e) => Some(e), + HandshakeError::Failure(ref s) | HandshakeError::WouldBlock(ref s) => Some(s.error()), + } + } +} + +impl fmt::Display for HandshakeError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(StdError::description(self))?; + match *self { + HandshakeError::SetupFailure(ref e) => write!(f, ": {}", e)?, + HandshakeError::Failure(ref s) | HandshakeError::WouldBlock(ref s) => { + write!(f, ": {}", s.error())?; + let verify = s.ssl().verify_result(); + if verify != X509VerifyResult::OK { + write!(f, ": {}", verify)?; + } + } + } + Ok(()) + } +} + +impl From for HandshakeError { + fn from(e: ErrorStack) -> HandshakeError { + HandshakeError::SetupFailure(e) + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/ssl/mod.rs cargo-0.26.0/vendor/openssl-0.10.6/src/ssl/mod.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/ssl/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/ssl/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3173 @@ +//! SSL/TLS support. +//! +//! `SslConnector` and `SslAcceptor` should be used in most cases - they handle +//! configuration of the OpenSSL primitives for you. +//! +//! # Examples +//! +//! To connect as a client to a remote server: +//! +//! ``` +//! use openssl::ssl::{SslMethod, SslConnector}; +//! use std::io::{Read, Write}; +//! use std::net::TcpStream; +//! +//! let connector = SslConnector::builder(SslMethod::tls()).unwrap().build(); +//! +//! let stream = TcpStream::connect("google.com:443").unwrap(); +//! let mut stream = connector.connect("google.com", stream).unwrap(); +//! +//! stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); +//! let mut res = vec![]; +//! stream.read_to_end(&mut res).unwrap(); +//! println!("{}", String::from_utf8_lossy(&res)); +//! ``` +//! +//! To accept connections as a server from remote clients: +//! +//! ```no_run +//! use openssl::ssl::{SslMethod, SslAcceptor, SslStream, SslFiletype}; +//! use std::net::{TcpListener, TcpStream}; +//! use std::sync::Arc; +//! use std::thread; +//! +//! +//! let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); +//! acceptor.set_private_key_file("key.pem", SslFiletype::PEM).unwrap(); +//! acceptor.set_certificate_chain_file("certs.pem").unwrap(); +//! acceptor.check_private_key().unwrap(); +//! let acceptor = Arc::new(acceptor.build()); +//! +//! let listener = TcpListener::bind("0.0.0.0:8443").unwrap(); +//! +//! fn handle_client(stream: SslStream) { +//! // ... +//! } +//! +//! for stream in listener.incoming() { +//! match stream { +//! Ok(stream) => { +//! let acceptor = acceptor.clone(); +//! thread::spawn(move || { +//! let stream = acceptor.accept(stream).unwrap(); +//! handle_client(stream); +//! }); +//! } +//! Err(e) => { /* connection failed */ } +//! } +//! } +//! ``` +use ffi; +use foreign_types::{ForeignType, ForeignTypeRef, Opaque}; +use libc::{c_char, c_int, c_long, c_uchar, c_uint, c_ulong, c_void}; +use std::any::TypeId; +use std::cmp; +use std::collections::HashMap; +use std::ffi::{CStr, CString}; +use std::fmt; +use std::io; +use std::io::prelude::*; +use std::marker::PhantomData; +use std::mem::{self, ManuallyDrop}; +use std::ops::{Deref, DerefMut}; +use std::panic::resume_unwind; +use std::path::Path; +use std::ptr; +use std::slice; +use std::str; +use std::sync::Mutex; + +use {cvt, cvt_n, cvt_p, init}; +use dh::{Dh, DhRef}; +use ec::EcKeyRef; +#[cfg(any(ossl101, ossl102))] +use ec::EcKey; +use x509::{X509, X509Name, X509Ref, X509StoreContextRef, X509VerifyResult}; +use x509::store::{X509StoreBuilderRef, X509StoreRef}; +#[cfg(any(ossl102, ossl110))] +use x509::store::X509Store; +#[cfg(any(ossl102, ossl110))] +use x509::verify::X509VerifyParamRef; +use pkey::{HasPrivate, PKeyRef, Params, Private}; +use error::ErrorStack; +use ex_data::Index; +use stack::{Stack, StackRef}; +use ssl::bio::BioMethod; +use ssl::error::InnerError; +use ssl::callbacks::*; +use nid::Nid; +#[cfg(ossl111)] +use hash::MessageDigest; + +pub use ssl::connector::{ConnectConfiguration, SslAcceptor, SslAcceptorBuilder, SslConnector, + SslConnectorBuilder}; +pub use ssl::error::{Error, ErrorCode, HandshakeError}; + +mod error; +mod callbacks; +mod connector; +mod bio; +#[cfg(test)] +mod test; + +bitflags! { + /// Options controlling the behavior of an `SslContext`. + pub struct SslOptions: c_ulong { + /// Disables a countermeasure against an SSLv3/TLSv1.0 vulnerability affecting CBC ciphers. + const DONT_INSERT_EMPTY_FRAGMENTS = ffi::SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; + + /// A "reasonable default" set of options which enables compatibility flags. + const ALL = ffi::SSL_OP_ALL; + + /// Do not query the MTU. + /// + /// Only affects DTLS connections. + const NO_QUERY_MTU = ffi::SSL_OP_NO_QUERY_MTU; + + /// Enables Cookie Exchange as described in [RFC 4347 Section 4.2.1]. + /// + /// Only affects DTLS connections. + /// + /// [RFC 4347 Section 4.2.1]: https://tools.ietf.org/html/rfc4347#section-4.2.1 + const COOKIE_EXCHANGE = ffi::SSL_OP_COOKIE_EXCHANGE; + + /// Disables the use of session tickets for session resumption. + const NO_TICKET = ffi::SSL_OP_NO_TICKET; + + /// Always start a new session when performing a renegotiation on the server side. + const NO_SESSION_RESUMPTION_ON_RENEGOTIATION = + ffi::SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION; + + /// Disables the use of TLS compression. + const NO_COMPRESSION = ffi::SSL_OP_NO_COMPRESSION; + + /// Allow legacy insecure renegotiation with servers or clients that do not support secure + /// renegotiation. + const ALLOW_UNSAFE_LEGACY_RENEGOTIATION = + ffi::SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION; + + /// Creates a new key for each session when using ECDHE. + /// + /// This is always enabled in OpenSSL 1.1.0. + const SINGLE_ECDH_USE = ffi::SSL_OP_SINGLE_ECDH_USE; + + /// Creates a new key for each session when using DHE. + /// + /// This is always enabled in OpenSSL 1.1.0. + const SINGLE_DH_USE = ffi::SSL_OP_SINGLE_DH_USE; + + /// Use the server's preferences rather than the client's when selecting a cipher. + /// + /// This has no effect on the client side. + const CIPHER_SERVER_PREFERENCE = ffi::SSL_OP_CIPHER_SERVER_PREFERENCE; + + /// Disables version rollback attach detection. + const TLS_ROLLBACK_BUG = ffi::SSL_OP_TLS_ROLLBACK_BUG; + + /// Disables the use of SSLv2. + const NO_SSLV2 = ffi::SSL_OP_NO_SSLv2; + + /// Disables the use of SSLv3. + const NO_SSLV3 = ffi::SSL_OP_NO_SSLv3; + + /// Disables the use of TLSv1.0. + const NO_TLSV1 = ffi::SSL_OP_NO_TLSv1; + + /// Disables the use of TLSv1.1. + const NO_TLSV1_1 = ffi::SSL_OP_NO_TLSv1_1; + + /// Disables the use of TLSv1.2. + const NO_TLSV1_2 = ffi::SSL_OP_NO_TLSv1_2; + + /// Disables the use of TLSv1.3. + /// + /// Requires OpenSSL 1.1.1 or newer. + #[cfg(ossl111)] + const NO_TLSV1_3 = ffi::SSL_OP_NO_TLSv1_3; + + /// Disables the use of DTLSv1.0 + /// + /// Requires OpenSSL 1.0.2 or newer. + #[cfg(any(ossl102, ossl110))] + const NO_DTLSV1 = ffi::SSL_OP_NO_DTLSv1; + + /// Disables the use of DTLSv1.2. + /// + /// Requires OpenSSL 1.0.2, or newer. + #[cfg(any(ossl102, ossl110))] + const NO_DTLSV1_2 = ffi::SSL_OP_NO_DTLSv1_2; + + /// Disables the use of all (D)TLS protocol versions. + /// + /// This can be used as a mask when whitelisting protocol versions. + /// + /// Requires OpenSSL 1.0.2 or newer. + /// + /// # Examples + /// + /// Only support TLSv1.2: + /// + /// ```rust + /// use openssl::ssl::SslOptions; + /// + /// let options = SslOptions::NO_SSL_MASK & !SslOptions::NO_TLSV1_2; + /// ``` + #[cfg(any(ossl102, ossl110))] + const NO_SSL_MASK = ffi::SSL_OP_NO_SSL_MASK; + + /// Enable TLSv1.3 Compatibility mode. + /// + /// Requires OpenSSL 1.1.1 or newer. This is on by default in 1.1.1, but a future version + /// may have this disabled by default. + #[cfg(ossl111)] + const ENABLE_MIDDLEBOX_COMPAT = ffi::SSL_OP_ENABLE_MIDDLEBOX_COMPAT; + } +} + +bitflags! { + /// Options controlling the behavior of an `SslContext`. + pub struct SslMode: c_long { + /// Enables "short writes". + /// + /// Normally, a write in OpenSSL will always write out all of the requested data, even if it + /// requires more than one TLS record or write to the underlying stream. This option will + /// cause a write to return after writing a single TLS record instead. + const ENABLE_PARTIAL_WRITE = ffi::SSL_MODE_ENABLE_PARTIAL_WRITE; + + /// Disables a check that the data buffer has not moved between calls when operating in a + /// nonblocking context. + const ACCEPT_MOVING_WRITE_BUFFER = ffi::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER; + + /// Enables automatic retries after TLS session events such as renegotiations or heartbeats. + /// + /// By default, OpenSSL will return a `WantRead` error after a renegotiation or heartbeat. + /// This option will cause OpenSSL to automatically continue processing the requested + /// operation instead. + /// + /// Note that `SslStream::read` and `SslStream::write` will automatically retry regardless + /// of the state of this option. It only affects `SslStream::ssl_read` and + /// `SslStream::ssl_write`. + const AUTO_RETRY = ffi::SSL_MODE_AUTO_RETRY; + + /// Disables automatic chain building when verifying a peer's certificate. + /// + /// TLS peers are responsible for sending the entire certificate chain from the leaf to a + /// trusted root, but some will incorrectly not do so. OpenSSL will try to build the chain + /// out of certificates it knows of, and this option will disable that behavior. + const NO_AUTO_CHAIN = ffi::SSL_MODE_NO_AUTO_CHAIN; + + /// Release memory buffers when the session does not need them. + /// + /// This saves ~34 KiB of memory for idle streams. + const RELEASE_BUFFERS = ffi::SSL_MODE_RELEASE_BUFFERS; + + /// Sends the fake `TLS_FALLBACK_SCSV` cipher suite in the ClientHello message of a + /// handshake. + /// + /// This should only be enabled if a client has failed to connect to a server which + /// attempted to downgrade the protocol version of the session. + /// + /// Do not use this unless you know what you're doing! + #[cfg(not(libressl))] + const SEND_FALLBACK_SCSV = ffi::SSL_MODE_SEND_FALLBACK_SCSV; + } +} + +/// A type specifying the kind of protocol an `SslContext` will speak. +#[derive(Copy, Clone)] +pub struct SslMethod(*const ffi::SSL_METHOD); + +impl SslMethod { + /// Support all versions of the TLS protocol. + /// + /// This corresponds to `TLS_method` on OpenSSL 1.1.0 and `SSLv23_method` + /// on OpenSSL 1.0.x. + pub fn tls() -> SslMethod { + SslMethod(compat::tls_method()) + } + + /// Support all versions of the DTLS protocol. + /// + /// This corresponds to `DTLS_method` on OpenSSL 1.1.0 and `DTLSv1_method` + /// on OpenSSL 1.0.x. + pub fn dtls() -> SslMethod { + SslMethod(compat::dtls_method()) + } + + /// Constructs an `SslMethod` from a pointer to the underlying OpenSSL value. + pub unsafe fn from_ptr(ptr: *const ffi::SSL_METHOD) -> SslMethod { + SslMethod(ptr) + } + + /// Returns a pointer to the underlying OpenSSL value. + pub fn as_ptr(&self) -> *const ffi::SSL_METHOD { + self.0 + } +} + +unsafe impl Sync for SslMethod {} +unsafe impl Send for SslMethod {} + +bitflags! { + /// Options controling the behavior of certificate verification. + pub struct SslVerifyMode: i32 { + /// Verifies that the peer's certificate is trusted. + /// + /// On the server side, this will cause OpenSSL to request a certificate from the client. + const PEER = ffi::SSL_VERIFY_PEER; + + /// Disables verification of the peer's certificate. + /// + /// On the server side, this will cause OpenSSL to not request a certificate from the + /// client. On the client side, the certificate will be checked for validity, but the + /// negotiation will continue regardless of the result of that check. + const NONE = ffi::SSL_VERIFY_NONE; + + /// On the server side, abort the handshake if the client did not send a certificate. + /// + /// This should be paired with `SSL_VERIFY_PEER`. It has no effect on the client side. + const FAIL_IF_NO_PEER_CERT = ffi::SSL_VERIFY_FAIL_IF_NO_PEER_CERT; + } +} + +bitflags! { + /// Options controlling the behavior of session caching. + pub struct SslSessionCacheMode: c_long { + /// No session caching for the client or server takes place. + const OFF = ffi::SSL_SESS_CACHE_OFF; + + /// Enable session caching on the client side. + /// + /// OpenSSL has no way of identifying the proper session to reuse automatically, so the + /// application is responsible for setting it explicitly via [`SslRef::set_session`]. + /// + /// [`SslRef::set_session`]: struct.SslRef.html#method.set_session + const CLIENT = ffi::SSL_SESS_CACHE_CLIENT; + + /// Enable session caching on the server side. + /// + /// This is the default mode. + const SERVER = ffi::SSL_SESS_CACHE_SERVER; + + /// Enable session caching on both the client and server side. + const BOTH = ffi::SSL_SESS_CACHE_BOTH; + + /// Disable automatic removal of expired sessions from the session cache. + const NO_AUTO_CLEAR = ffi::SSL_SESS_CACHE_NO_AUTO_CLEAR; + + /// Disable use of the internal session cache for session lookups. + const NO_INTERNAL_LOOKUP = ffi::SSL_SESS_CACHE_NO_INTERNAL_LOOKUP; + + /// Disable use of the internal session cache for session storage. + const NO_INTERNAL_STORE = ffi::SSL_SESS_CACHE_NO_INTERNAL_STORE; + + /// Disable use of the internal session cache for storage and lookup. + const NO_INTERNAL = ffi::SSL_SESS_CACHE_NO_INTERNAL; + } +} + +#[cfg(ossl111)] +bitflags! { + /// Which messages and under which conditions an extension should be added or expected. + pub struct ExtensionContext: c_uint { + /// This extension is only allowed in TLS + const TLS_ONLY = ffi::SSL_EXT_TLS_ONLY; + /// This extension is only allowed in DTLS + const DTLS_ONLY = ffi::SSL_EXT_DTLS_ONLY; + /// Some extensions may be allowed in DTLS but we don't implement them for it + const TLS_IMPLEMENTATION_ONLY = ffi::SSL_EXT_TLS_IMPLEMENTATION_ONLY; + /// Most extensions are not defined for SSLv3 but EXT_TYPE_renegotiate is + const SSL3_ALLOWED = ffi::SSL_EXT_SSL3_ALLOWED; + /// Extension is only defined for TLS1.2 and below + const TLS1_2_AND_BELOW_ONLY = ffi::SSL_EXT_TLS1_2_AND_BELOW_ONLY; + /// Extension is only defined for TLS1.3 and above + const TLS1_3_ONLY = ffi::SSL_EXT_TLS1_3_ONLY; + /// Ignore this extension during parsing if we are resuming + const IGNORE_ON_RESUMPTION = ffi::SSL_EXT_IGNORE_ON_RESUMPTION; + const CLIENT_HELLO = ffi::SSL_EXT_CLIENT_HELLO; + /// Really means TLS1.2 or below + const TLS1_2_SERVER_HELLO = ffi::SSL_EXT_TLS1_2_SERVER_HELLO; + const TLS1_3_SERVER_HELLO = ffi::SSL_EXT_TLS1_3_SERVER_HELLO; + const TLS1_3_ENCRYPTED_EXTENSIONS = ffi::SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS; + const TLS1_3_HELLO_RETRY_REQUEST = ffi::SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST; + const TLS1_3_CERTIFICATE = ffi::SSL_EXT_TLS1_3_CERTIFICATE; + const TLS1_3_NEW_SESSION_TICKET = ffi::SSL_EXT_TLS1_3_NEW_SESSION_TICKET; + const TLS1_3_CERTIFICATE_REQUEST = ffi::SSL_EXT_TLS1_3_CERTIFICATE_REQUEST; + } +} + +/// An identifier of the format of a certificate or key file. +#[derive(Copy, Clone)] +pub struct SslFiletype(c_int); + +impl SslFiletype { + /// Constructs an `SslFiletype` from a raw OpenSSL value. + pub fn from_raw(raw: c_int) -> SslFiletype { + SslFiletype(raw) + } + + /// Returns the raw OpenSSL value represented by this type. + pub fn as_raw(&self) -> c_int { + self.0 + } + + /// The PEM format. + /// + /// This corresponds to `SSL_FILETYPE_PEM`. + pub const PEM: SslFiletype = SslFiletype(ffi::SSL_FILETYPE_PEM); + + /// The ASN1 format. + /// + /// This corresponds to `SSL_FILETYPE_ASN1`. + pub const ASN1: SslFiletype = SslFiletype(ffi::SSL_FILETYPE_ASN1); +} + +/// An identifier of a certificate status type. +#[derive(Copy, Clone)] +pub struct StatusType(c_int); + +impl StatusType { + /// Constructs a `StatusType` from a raw OpenSSL value. + pub fn from_raw(raw: c_int) -> StatusType { + StatusType(raw) + } + + /// Returns the raw OpenSSL value represented by this type. + pub fn as_raw(&self) -> c_int { + self.0 + } + + /// An OSCP status. + pub const OCSP: StatusType = StatusType(ffi::TLSEXT_STATUSTYPE_ocsp); +} + +/// An identifier of a session name type. +#[derive(Copy, Clone)] +pub struct NameType(c_int); + +impl NameType { + /// Constructs a `StatusType` from a raw OpenSSL value. + pub fn from_raw(raw: c_int) -> StatusType { + StatusType(raw) + } + + /// Returns the raw OpenSSL value represented by this type. + pub fn as_raw(&self) -> c_int { + self.0 + } + + /// A host name. + pub const HOST_NAME: NameType = NameType(ffi::TLSEXT_NAMETYPE_host_name); +} + +lazy_static! { + static ref INDEXES: Mutex> = Mutex::new(HashMap::new()); + static ref SSL_INDEXES: Mutex> = Mutex::new(HashMap::new()); +} + +// Creates a static index for user data of type T +// Registers a destructor for the data which will be called +// when context is freed +fn get_callback_idx() -> c_int { + *INDEXES + .lock() + .unwrap() + .entry(TypeId::of::()) + .or_insert_with(|| get_new_idx::()) +} + +fn get_ssl_callback_idx() -> c_int { + *SSL_INDEXES + .lock() + .unwrap() + .entry(TypeId::of::()) + .or_insert_with(|| get_new_ssl_idx::()) +} + +unsafe extern "C" fn free_data_box( + _parent: *mut c_void, + ptr: *mut c_void, + _ad: *mut ffi::CRYPTO_EX_DATA, + _idx: c_int, + _argl: c_long, + _argp: *mut c_void, +) { + if !ptr.is_null() { + Box::::from_raw(ptr as *mut T); + } +} + +fn get_new_idx() -> c_int { + unsafe { + let idx = compat::get_new_idx(free_data_box::); + assert!(idx >= 0); + idx + } +} + +fn get_new_ssl_idx() -> c_int { + unsafe { + let idx = compat::get_new_ssl_idx(free_data_box::); + assert!(idx >= 0); + idx + } +} + +/// An error returned from the SNI callback. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct SniError(c_int); + +impl SniError { + /// Abort the handshake with a fatal alert. + pub const ALERT_FATAL: SniError = SniError(ffi::SSL_TLSEXT_ERR_ALERT_FATAL); + + /// Send a warning alert to the client and continue the handshake. + pub const ALERT_WARNING: SniError = SniError(ffi::SSL_TLSEXT_ERR_ALERT_WARNING); + + pub const NOACK: SniError = SniError(ffi::SSL_TLSEXT_ERR_NOACK); +} + +/// An SSL/TLS alert. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct SslAlert(c_int); + +impl SslAlert { + /// Alert 112 - `unrecognized_name`. + pub const UNRECOGNIZED_NAME: SslAlert = SslAlert(ffi::SSL_AD_UNRECOGNIZED_NAME); + pub const ILLEGAL_PARAMETER: SslAlert = SslAlert(ffi::SSL_AD_ILLEGAL_PARAMETER); + pub const DECODE_ERROR: SslAlert = SslAlert(ffi::SSL_AD_DECODE_ERROR); +} + +/// An error returned from an ALPN selection callback. +/// +/// Requires OpenSSL 1.0.2 or newer. +#[cfg(any(ossl102, ossl110))] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct AlpnError(c_int); + +#[cfg(any(ossl102, ossl110))] +impl AlpnError { + /// Terminate the handshake with a fatal alert. + /// + /// Requires OpenSSL 1.1.0 or newer. + #[cfg(any(ossl110))] + pub const ALERT_FATAL: AlpnError = AlpnError(ffi::SSL_TLSEXT_ERR_ALERT_FATAL); + + /// Do not select a protocol, but continue the handshake. + pub const NOACK: AlpnError = AlpnError(ffi::SSL_TLSEXT_ERR_NOACK); +} + +/// An SSL/TLS protocol version. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct SslVersion(c_int); + +impl SslVersion { + /// SSLv3 + pub const SSL3: SslVersion = SslVersion(ffi::SSL3_VERSION); + + /// TLSv1.0 + pub const TLS1: SslVersion = SslVersion(ffi::TLS1_VERSION); + + /// TLSv1.1 + pub const TLS1_1: SslVersion = SslVersion(ffi::TLS1_1_VERSION); + + /// TLSv1.2 + pub const TLS1_2: SslVersion = SslVersion(ffi::TLS1_2_VERSION); + + /// TLSv1.3 + /// + /// Requires OpenSSL 1.1.1 or newer. + #[cfg(ossl111)] + pub const TLS1_3: SslVersion = SslVersion(ffi::TLS1_3_VERSION); +} + +/// A standard implementation of protocol selection for Application Layer Protocol Negotiation +/// (ALPN). +/// +/// `server` should contain the server's list of supported protocols and `client` the client's. They +/// must both be in the ALPN wire format. See the documentation for +/// [`SslContextBuilder::set_alpn_protos`] for details. +/// +/// It will select the first protocol supported by the server which is also supported by the client. +/// +/// This corresponds to [`SSL_select_next_proto`]. +/// +/// [`SslContextBuilder::set_alpn_protos`]: struct.SslContextBuilder.html#method.set_alpn_protos +/// [`SSL_select_next_proto`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_alpn_protos.html +pub fn select_next_proto<'a>(server: &[u8], client: &'a [u8]) -> Option<&'a [u8]> { + unsafe { + let mut out = ptr::null_mut(); + let mut outlen = 0; + let r = ffi::SSL_select_next_proto( + &mut out, + &mut outlen, + server.as_ptr(), + server.len() as c_uint, + client.as_ptr(), + client.len() as c_uint, + ); + if r == ffi::OPENSSL_NPN_NEGOTIATED { + Some(slice::from_raw_parts(out as *const u8, outlen as usize)) + } else { + None + } + } +} + +/// A builder for `SslContext`s. +pub struct SslContextBuilder(SslContext); + +impl SslContextBuilder { + /// Creates a new `SslContextBuilder`. + /// + /// This corresponds to [`SSL_CTX_new`]. + /// + /// [`SSL_CTX_new`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_new.html + pub fn new(method: SslMethod) -> Result { + unsafe { + init(); + let ctx = cvt_p(ffi::SSL_CTX_new(method.as_ptr()))?; + + Ok(SslContextBuilder::from_ptr(ctx)) + } + } + + /// Creates an `SslContextBuilder` from a pointer to a raw OpenSSL value. + pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContextBuilder { + SslContextBuilder(SslContext::from_ptr(ctx)) + } + + /// Returns a pointer to the raw OpenSSL value. + pub fn as_ptr(&self) -> *mut ffi::SSL_CTX { + self.0.as_ptr() + } + + /// Configures the certificate verification method for new connections. + /// + /// This corresponds to [`SSL_CTX_set_verify`]. + /// + /// [`SSL_CTX_set_verify`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_verify.html + pub fn set_verify(&mut self, mode: SslVerifyMode) { + unsafe { + ffi::SSL_CTX_set_verify(self.as_ptr(), mode.bits as c_int, None); + } + } + + /// Configures the certificate verification method for new connections and + /// registers a verification callback. + /// + /// The callback is passed a boolean indicating if OpenSSL's internal verification succeeded as + /// well as a reference to the `X509StoreContext` which can be used to examine the certificate + /// chain. It should return a boolean indicating if verification succeeded. + /// + /// This corresponds to [`SSL_CTX_set_verify`]. + /// + /// [`SSL_CTX_set_verify`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_verify.html + pub fn set_verify_callback(&mut self, mode: SslVerifyMode, verify: F) + where + F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send, + { + unsafe { + let verify = Box::new(verify); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + mem::transmute(verify), + ); + ffi::SSL_CTX_set_verify(self.as_ptr(), mode.bits as c_int, Some(raw_verify::)); + } + } + + /// Configures the server name indication (SNI) callback for new connections. + /// + /// SNI is used to allow a single server to handle requests for multiple domains, each of which + /// has its own certificate chain and configuration. + /// + /// Obtain the server name with the `servername` method and then set the corresponding context + /// with `set_ssl_context` + /// + /// This corresponds to [`SSL_CTX_set_tlsext_servername_callback`]. + /// + /// [`SSL_CTX_set_tlsext_servername_callback`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_tlsext_servername_callback.html + pub fn set_servername_callback(&mut self, callback: F) + where + F: Fn(&mut SslRef, &mut SslAlert) -> Result<(), SniError> + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + mem::transmute(callback), + ); + let f: extern "C" fn(_, _, _) -> _ = raw_sni::; + let f: extern "C" fn() = mem::transmute(f); + ffi::SSL_CTX_set_tlsext_servername_callback(self.as_ptr(), Some(f)); + } + } + + /// Sets the certificate verification depth. + /// + /// If the peer's certificate chain is longer than this value, verification will fail. + /// + /// This corresponds to [`SSL_CTX_set_verify_depth`]. + /// + /// [`SSL_CTX_set_verify_depth`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_verify_depth.html + pub fn set_verify_depth(&mut self, depth: u32) { + unsafe { + ffi::SSL_CTX_set_verify_depth(self.as_ptr(), depth as c_int); + } + } + + /// Sets a custom certificate store for verifying peer certificates. + /// + /// Requires OpenSSL 1.0.2 or newer. + /// + /// This corresponds to [`SSL_CTX_set0_verify_cert_store`]. + /// + /// [`SSL_CTX_set0_verify_cert_store`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set0_verify_cert_store.html + #[cfg(any(ossl102, ossl110))] + pub fn set_verify_cert_store(&mut self, cert_store: X509Store) -> Result<(), ErrorStack> { + unsafe { + let ptr = cert_store.as_ptr(); + cvt(ffi::SSL_CTX_set0_verify_cert_store(self.as_ptr(), ptr) as c_int)?; + mem::forget(cert_store); + + Ok(()) + } + } + + /// Controls read ahead behavior. + /// + /// If enabled, OpenSSL will read as much data as is available from the underlying stream, + /// instead of a single record at a time. + /// + /// It has no effect when used with DTLS. + /// + /// This corresponds to [`SSL_CTX_set_read_ahead`]. + /// + /// [`SSL_CTX_set_read_ahead`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_read_ahead.html + pub fn set_read_ahead(&mut self, read_ahead: bool) { + unsafe { + ffi::SSL_CTX_set_read_ahead(self.as_ptr(), read_ahead as c_long); + } + } + + /// Sets the mode used by the context, returning the previous mode. + /// + /// This corresponds to [`SSL_CTX_set_mode`]. + /// + /// [`SSL_CTX_set_mode`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_mode.html + pub fn set_mode(&mut self, mode: SslMode) -> SslMode { + unsafe { + let bits = ffi::SSL_CTX_set_mode(self.as_ptr(), mode.bits()); + SslMode { bits } + } + } + + /// Sets the parameters to be used during ephemeral Diffie-Hellman key exchange. + /// + /// This corresponds to [`SSL_CTX_set_tmp_dh`]. + /// + /// [`SSL_CTX_set_tmp_dh`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_tmp_dh.html + pub fn set_tmp_dh(&mut self, dh: &DhRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) } + } + + /// Sets the callback which will generate parameters to be used during ephemeral Diffie-Hellman + /// key exchange. + /// + /// The callback is provided with a reference to the `Ssl` for the session, as well as a boolean + /// indicating if the selected cipher is export-grade, and the key length. The export and key + /// length options are archaic and should be ignored in almost all cases. + /// + /// This corresponds to [`SSL_CTX_set_tmp_dh_callback`]. + /// + /// [`SSL_CTX_set_tmp_dh_callback`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_tmp_dh.html + pub fn set_tmp_dh_callback(&mut self, callback: F) + where + F: Fn(&mut SslRef, bool, u32) -> Result, ErrorStack> + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(callback) as *mut c_void, + ); + let f: unsafe extern "C" fn(_, _, _) -> _ = raw_tmp_dh::; + ffi::SSL_CTX_set_tmp_dh_callback(self.as_ptr(), f); + } + } + + /// Sets the parameters to be used during ephemeral elliptic curve Diffie-Hellman key exchange. + /// + /// This corresponds to `SSL_CTX_set_tmp_ecdh`. + pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::SSL_CTX_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) } + } + + /// Sets the callback which will generate parameters to be used during ephemeral elliptic curve + /// Diffie-Hellman key exchange. + /// + /// The callback is provided with a reference to the `Ssl` for the session, as well as a boolean + /// indicating if the selected cipher is export-grade, and the key length. The export and key + /// length options are archaic and should be ignored in almost all cases. + /// + /// Requires OpenSSL 1.0.1 or 1.0.2. + /// + /// This corresponds to `SSL_CTX_set_tmp_ecdh_callback`. + #[cfg(any(ossl101, ossl102))] + pub fn set_tmp_ecdh_callback(&mut self, callback: F) + where + F: Fn(&mut SslRef, bool, u32) -> Result, ErrorStack> + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(callback) as *mut c_void, + ); + let f: unsafe extern "C" fn(_, _, _) -> _ = raw_tmp_ecdh::; + ffi::SSL_CTX_set_tmp_ecdh_callback(self.as_ptr(), f); + } + } + + /// Use the default locations of trusted certificates for verification. + /// + /// These locations are read from the `SSL_CERT_FILE` and `SSL_CERT_DIR` environment variables + /// if present, or defaults specified at OpenSSL build time otherwise. + /// + /// This corresponds to [`SSL_CTX_set_default_verify_paths`]. + /// + /// [`SSL_CTX_set_default_verify_paths`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_default_verify_paths.html + pub fn set_default_verify_paths(&mut self) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::SSL_CTX_set_default_verify_paths(self.as_ptr())).map(|_| ()) } + } + + /// Loads trusted root certificates from a file. + /// + /// The file should contain a sequence of PEM-formatted CA certificates. + /// + /// This corresponds to [`SSL_CTX_set_default_verify_file`]. + /// + /// [`SSL_CTX_set_default_verify_file`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_default_verify_paths.html + pub fn set_ca_file>(&mut self, file: P) -> Result<(), ErrorStack> { + let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); + unsafe { + cvt(ffi::SSL_CTX_load_verify_locations( + self.as_ptr(), + file.as_ptr() as *const _, + ptr::null(), + )).map(|_| ()) + } + } + + /// Sets the list of CA names sent to the client. + /// + /// The CA certificates must still be added to the trust root - they are not automatically set + /// as trusted by this method. + /// + /// This corresponds to [`SSL_CTX_set_client_CA_list`]. + /// + /// [`SSL_CTX_set_client_CA_list`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_client_CA_list.html + pub fn set_client_ca_list(&mut self, list: Stack) { + unsafe { + ffi::SSL_CTX_set_client_CA_list(self.as_ptr(), list.as_ptr()); + mem::forget(list); + } + } + + /// Set the context identifier for sessions. + /// + /// This value identifies the server's session cache to clients, telling them when they're + /// able to reuse sessions. It should be be set to a unique value per server, unless multiple + /// servers share a session cache. + /// + /// This value should be set when using client certificates, or each request will fail its + /// handshake and need to be restarted. + /// + /// This corresponds to [`SSL_CTX_set_session_id_context`]. + /// + /// [`SSL_CTX_set_session_id_context`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_session_id_context.html + pub fn set_session_id_context(&mut self, sid_ctx: &[u8]) -> Result<(), ErrorStack> { + unsafe { + assert!(sid_ctx.len() <= c_uint::max_value() as usize); + cvt(ffi::SSL_CTX_set_session_id_context( + self.as_ptr(), + sid_ctx.as_ptr(), + sid_ctx.len() as c_uint, + )).map(|_| ()) + } + } + + /// Loads a leaf certificate from a file. + /// + /// Only a single certificate will be loaded - use `add_extra_chain_cert` to add the remainder + /// of the certificate chain, or `set_certificate_chain_file` to load the entire chain from a + /// single file. + /// + /// This corresponds to [`SSL_CTX_use_certificate_file`]. + /// + /// [`SSL_CTX_use_certificate_file`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_use_certificate_file.html + pub fn set_certificate_file>( + &mut self, + file: P, + file_type: SslFiletype, + ) -> Result<(), ErrorStack> { + let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); + unsafe { + cvt(ffi::SSL_CTX_use_certificate_file( + self.as_ptr(), + file.as_ptr() as *const _, + file_type.as_raw(), + )).map(|_| ()) + } + } + + /// Loads a certificate chain from a file. + /// + /// The file should contain a sequence of PEM-formatted certificates, the first being the leaf + /// certificate, and the remainder forming the chain of certificates up to and including the + /// trusted root certificate. + /// + /// This corresponds to [`SSL_CTX_use_certificate_chain_file`]. + /// + /// [`SSL_CTX_use_certificate_chain_file`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_use_certificate_file.html + pub fn set_certificate_chain_file>( + &mut self, + file: P, + ) -> Result<(), ErrorStack> { + let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); + unsafe { + cvt(ffi::SSL_CTX_use_certificate_chain_file( + self.as_ptr(), + file.as_ptr() as *const _, + )).map(|_| ()) + } + } + + /// Sets the leaf certificate. + /// + /// Use `add_extra_chain_cert` to add the remainder of the certificate chain. + /// + /// This corresponds to [`SSL_CTX_use_certificate`]. + /// + /// [`SSL_CTX_use_certificate`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_use_certificate_file.html + pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::SSL_CTX_use_certificate(self.as_ptr(), cert.as_ptr())).map(|_| ()) } + } + + /// Appends a certificate to the certificate chain. + /// + /// This chain should contain all certificates necessary to go from the certificate specified by + /// `set_certificate` to a trusted root. + /// + /// This corresponds to [`SSL_CTX_add_extra_chain_cert`]. + /// + /// [`SSL_CTX_add_extra_chain_cert`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_add_extra_chain_cert.html + pub fn add_extra_chain_cert(&mut self, cert: X509) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::SSL_CTX_add_extra_chain_cert(self.as_ptr(), cert.as_ptr()) as c_int)?; + mem::forget(cert); + Ok(()) + } + } + + /// Loads the private key from a file. + /// + /// This corresponds to [`SSL_CTX_use_PrivateKey_file`]. + /// + /// [`SSL_CTX_use_PrivateKey_file`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_use_PrivateKey_file.html + pub fn set_private_key_file>( + &mut self, + file: P, + file_type: SslFiletype, + ) -> Result<(), ErrorStack> { + let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); + unsafe { + cvt(ffi::SSL_CTX_use_PrivateKey_file( + self.as_ptr(), + file.as_ptr() as *const _, + file_type.as_raw(), + )).map(|_| ()) + } + } + + /// Sets the private key. + /// + /// This corresponds to [`SSL_CTX_use_PrivateKey`]. + /// + /// [`SSL_CTX_use_PrivateKey`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_use_PrivateKey_file.html + pub fn set_private_key(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> + where + T: HasPrivate, + { + unsafe { cvt(ffi::SSL_CTX_use_PrivateKey(self.as_ptr(), key.as_ptr())).map(|_| ()) } + } + + /// Sets the list of supported ciphers. + /// + /// See [`ciphers`] for details on the format. + /// + /// This corresponds to [`SSL_CTX_set_cipher_list`]. + /// + /// [`ciphers`]: https://www.openssl.org/docs/man1.1.0/apps/ciphers.html + /// [`SSL_CTX_set_cipher_list`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_client_ciphers.html + pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack> { + let cipher_list = CString::new(cipher_list).unwrap(); + unsafe { + cvt(ffi::SSL_CTX_set_cipher_list( + self.as_ptr(), + cipher_list.as_ptr() as *const _, + )).map(|_| ()) + } + } + + /// Enables ECDHE key exchange with an automatically chosen curve list. + /// + /// Requires OpenSSL 1.0.2. + /// + /// This corresponds to [`SSL_CTX_set_ecdh_auto`]. + /// + /// [`SSL_CTX_set_ecdh_auto`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_ecdh_auto.html + #[cfg(any(ossl102, libressl))] + pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::SSL_CTX_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) } + } + + /// Sets the options used by the context, returning the old set. + /// + /// This corresponds to [`SSL_CTX_set_options`]. + /// + /// # Note + /// + /// This *enables* the specified options, but does not disable unspecified options. Use + /// `clear_options` for that. + /// + /// [`SSL_CTX_set_options`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_options.html + pub fn set_options(&mut self, option: SslOptions) -> SslOptions { + let bits = unsafe { compat::SSL_CTX_set_options(self.as_ptr(), option.bits()) }; + SslOptions { bits } + } + + /// Returns the options used by the context. + /// + /// This corresponds to [`SSL_CTX_get_options`]. + /// + /// [`SSL_CTX_get_options`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_options.html + pub fn options(&self) -> SslOptions { + let bits = unsafe { compat::SSL_CTX_get_options(self.as_ptr()) }; + SslOptions { bits } + } + + /// Clears the options used by the context, returning the old set. + /// + /// This corresponds to [`SSL_CTX_clear_options`]. + /// + /// [`SSL_CTX_clear_options`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_options.html + pub fn clear_options(&mut self, option: SslOptions) -> SslOptions { + let bits = unsafe { compat::SSL_CTX_clear_options(self.as_ptr(), option.bits()) }; + SslOptions { bits } + } + + /// Sets the minimum supported protocol version. + /// + /// A value of `None` will enable protocol versions down the the lowest version supported by + /// OpenSSL. + /// + /// This corresponds to [`SSL_CTX_set_min_proto_version`]. + /// + /// Requires OpenSSL 1.1.0 or newer. + /// + /// [`SSL_CTX_set_min_proto_version`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_min_proto_version.html + #[cfg(any(ossl110))] + pub fn set_min_proto_version(&mut self, version: Option) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::SSL_CTX_set_min_proto_version( + self.as_ptr(), + version.map_or(0, |v| v.0), + )).map(|_| ()) + } + } + + /// Sets the maximum supported protocol version. + /// + /// A value of `None` will enable protocol versions down the the highest version supported by + /// OpenSSL. + /// + /// This corresponds to [`SSL_CTX_set_max_proto_version`]. + /// + /// Requires OpenSSL 1.1.0 or newer. + /// + /// [`SSL_CTX_set_max_proto_version`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_min_proto_version.html + #[cfg(any(ossl110))] + pub fn set_max_proto_version(&mut self, version: Option) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::SSL_CTX_set_max_proto_version( + self.as_ptr(), + version.map_or(0, |v| v.0), + )).map(|_| ()) + } + } + + /// Gets the minimum supported protocol version. + /// + /// A value of `None` indicates that all versions down the the lowest version supported by + /// OpenSSL are enabled. + /// + /// This corresponds to [`SSL_CTX_get_min_proto_version`]. + /// + /// Requires OpenSSL 1.1.0 or newer. + /// + /// [`SSL_CTX_get_min_proto_version`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_min_proto_version.html + #[cfg(any(ossl110))] + pub fn min_proto_version(&mut self) -> Option { + unsafe { + let r = ffi::SSL_CTX_get_min_proto_version(self.as_ptr()); + if r == 0 { + None + } else { + Some(SslVersion(r)) + } + } + } + + /// Gets the maximum supported protocol version. + /// + /// A value of `None` indicates that all versions down the the highest version supported by + /// OpenSSL are enabled. + /// + /// This corresponds to [`SSL_CTX_get_max_proto_version`]. + /// + /// Requires OpenSSL 1.1.0 or newer. + /// + /// [`SSL_CTX_get_max_proto_version`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_min_proto_version.html + #[cfg(any(ossl110))] + pub fn max_proto_version(&mut self) -> Option { + unsafe { + let r = ffi::SSL_CTX_get_max_proto_version(self.as_ptr()); + if r == 0 { + None + } else { + Some(SslVersion(r)) + } + } + } + + /// Sets the protocols to sent to the server for Application Layer Protocol Negotiation (ALPN). + /// + /// The input must be in ALPN "wire format". It consists of a sequence of supported protocol + /// names prefixed by their byte length. For example, the protocol list consisting of `spdy/1` + /// and `http/1.1` is encoded as `b"\x06spdy/1\x08http/1.1"`. The protocols are ordered by + /// preference. + /// + /// This corresponds to [`SSL_CTX_set_alpn_protos`]. + /// + /// Requires OpenSSL 1.0.2 or newer. + /// + /// [`SSL_CTX_set_alpn_protos`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_alpn_protos.html + #[cfg(any(ossl102, ossl110))] + pub fn set_alpn_protos(&mut self, protocols: &[u8]) -> Result<(), ErrorStack> { + unsafe { + assert!(protocols.len() <= c_uint::max_value() as usize); + let r = ffi::SSL_CTX_set_alpn_protos( + self.as_ptr(), + protocols.as_ptr(), + protocols.len() as c_uint, + ); + // fun fact, SSL_CTX_set_alpn_protos has a reversed return code D: + if r == 0 { + Ok(()) + } else { + Err(ErrorStack::get()) + } + } + } + + /// Sets the callback used by a server to select a protocol for Application Layer Protocol + /// Negotiation (ALPN). + /// + /// The callback is provided with the client's protocol list in ALPN wire format. See the + /// documentation for [`SslContextBuilder::set_alpn_protos`] for details. It should return one + /// of those protocols on success. The [`select_next_proto`] function implements the standard + /// protocol selection algorithm. + /// + /// This corresponds to [`SSL_CTX_set_alpn_select_cb`]. + /// + /// Requires OpenSSL 1.0.2 or newer. + /// + /// [`SslContextBuilder::set_alpn_protos`]: struct.SslContextBuilder.html#method.set_alpn_protos + /// [`select_next_proto`]: fn.select_next_proto.html + /// [`SSL_CTX_set_alpn_select_cb`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_alpn_protos.html + #[cfg(any(ossl102, ossl110))] + pub fn set_alpn_select_callback(&mut self, callback: F) + where + F: for<'a> Fn(&mut SslRef, &'a [u8]) -> Result<&'a [u8], AlpnError> + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(callback) as *mut c_void, + ); + ffi::SSL_CTX_set_alpn_select_cb( + self.as_ptr(), + callbacks::raw_alpn_select::, + ptr::null_mut(), + ); + } + } + + /// Checks for consistency between the private key and certificate. + /// + /// This corresponds to [`SSL_CTX_check_private_key`]. + /// + /// [`SSL_CTX_check_private_key`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_check_private_key.html + pub fn check_private_key(&self) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::SSL_CTX_check_private_key(self.as_ptr())).map(|_| ()) } + } + + /// Returns a shared reference to the context's certificate store. + /// + /// This corresponds to [`SSL_CTX_get_cert_store`]. + /// + /// [`SSL_CTX_get_cert_store`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_get_cert_store.html + pub fn cert_store(&self) -> &X509StoreBuilderRef { + unsafe { X509StoreBuilderRef::from_ptr(ffi::SSL_CTX_get_cert_store(self.as_ptr())) } + } + + /// Returns a mutable reference to the context's certificate store. + /// + /// This corresponds to [`SSL_CTX_get_cert_store`]. + /// + /// [`SSL_CTX_get_cert_store`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_get_cert_store.html + pub fn cert_store_mut(&mut self) -> &mut X509StoreBuilderRef { + unsafe { X509StoreBuilderRef::from_ptr_mut(ffi::SSL_CTX_get_cert_store(self.as_ptr())) } + } + + /// Sets the callback dealing with OCSP stapling. + /// + /// On the client side, this callback is responsible for validating the OCSP status response + /// returned by the server. The status may be retrieved with the `SslRef::ocsp_status` method. + /// A response of `Ok(true)` indicates that the OCSP status is valid, and a response of + /// `Ok(false)` indicates that the OCSP status is invalid and the handshake should be + /// terminated. + /// + /// On the server side, this callback is resopnsible for setting the OCSP status response to be + /// returned to clients. The status may be set with the `SslRef::set_ocsp_status` method. A + /// response of `Ok(true)` indicates that the OCSP status should be returned to the client, and + /// `Ok(false)` indicates that the status should not be returned to the client. + /// + /// This corresponds to [`SSL_CTX_set_tlsext_status_cb`]. + /// + /// [`SSL_CTX_set_tlsext_status_cb`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_tlsext_status_cb.html + pub fn set_status_callback(&mut self, callback: F) -> Result<(), ErrorStack> + where + F: Fn(&mut SslRef) -> Result + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(callback) as *mut c_void, + ); + let f: unsafe extern "C" fn(_, _) -> _ = raw_tlsext_status::; + cvt(ffi::SSL_CTX_set_tlsext_status_cb(self.as_ptr(), Some(f)) as c_int).map(|_| ()) + } + } + + /// Sets the callback for providing an identity and pre-shared key for a TLS-PSK client. + /// + /// The callback will be called with the SSL context, an identity hint if one was provided + /// by the server, a mutable slice for each of the identity and pre-shared key bytes. The + /// identity must be written as a null-terminated C string. + /// + /// This corresponds to [`SSL_CTX_set_psk_client_callback`]. + /// + /// [`SSL_CTX_set_psk_client_callback`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_psk_client_callback.html + #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] + pub fn set_psk_callback(&mut self, callback: F) + where + F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result + + 'static + + Sync + + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + mem::transmute(callback), + ); + ffi::SSL_CTX_set_psk_client_callback(self.as_ptr(), Some(raw_psk::)) + } + } + + /// Sets the callback which is called when new sessions are negotiated. + /// + /// This can be used by clients to implement session caching. While in TLSv1.2 the session is + /// available to access via [`SslRef::session`] immediately after the handshake completes, this + /// is not the case for TLSv1.3. There, a session is not generally available immediately, and + /// the server may provide multiple session tokens to the client over a single session. The new + /// session callback is a portable way to deal with both cases. + /// + /// Note that session caching must be enabled for the callback to be invoked, and it defaults + /// off for clients. [`set_session_cache_mode`] controls that behavior. + /// + /// This corresponds to [`SSL_CTX_sess_set_new_cb`]. + /// + /// [`SslRef::session`]: struct.SslRef.html#method.session + /// [`set_session_cache_mode`]: #method.set_session_cache_mode + /// [`SSL_CTX_sess_set_new_cb`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_sess_set_new_cb.html + pub fn set_new_session_callback(&mut self, callback: F) + where + F: Fn(&mut SslRef, SslSession) + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(callback) as *mut _, + ); + ffi::SSL_CTX_sess_set_new_cb(self.as_ptr(), Some(callbacks::raw_new_session::)); + } + } + + /// Sets the callback which is called when sessions are removed from the context. + /// + /// Sessions can be removed because they have timed out or because they are considered faulty. + /// + /// This corresponds to [`SSL_CTX_sess_set_remove_cb`]. + /// + /// [`SSL_CTX_sess_set_remove_cb`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_sess_set_new_cb.html + pub fn set_remove_session_callback(&mut self, callback: F) + where + F: Fn(&SslContextRef, &SslSessionRef) + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(callback) as *mut _, + ); + ffi::SSL_CTX_sess_set_remove_cb( + self.as_ptr(), + Some(callbacks::raw_remove_session::), + ); + } + } + + /// Sets the callback which is called when a client proposed to resume a session but it was not + /// found in the internal cache. + /// + /// The callback is passed a reference to the session ID provided by the client. It should + /// return the session corresponding to that ID if available. This is only used for servers, not + /// clients. + /// + /// This corresponds to [`SSL_CTX_sess_set_get_cb`]. + /// + /// # Safety + /// + /// The returned `SslSession` must not be associated with a different `SslContext`. + /// + /// [`SSL_CTX_sess_set_get_cb`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_sess_set_new_cb.html + pub unsafe fn set_get_session_callback(&mut self, callback: F) + where + F: Fn(&mut SslRef, &[u8]) -> Option + 'static + Sync + Send, + { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(callback) as *mut _, + ); + ffi::SSL_CTX_sess_set_get_cb(self.as_ptr(), Some(callbacks::raw_get_session::)); + } + + /// Sets the TLS key logging callback. + /// + /// The callback is invoked whenever TLS key material is generated, and is passed a line of NSS + /// SSLKEYLOGFILE-formatted text. This can be used by tools like Wireshark to decrypt message + /// traffic. The line does not contain a trailing newline. + /// + /// Requires OpenSSL 1.1.1 or newer. + /// + /// This corresponds to [`SSL_CTX_set_keylog_callback`]. + /// + /// [`SSL_CTX_set_keylog_callback`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_keylog_callback.html + #[cfg(ossl111)] + pub fn set_keylog_callback(&mut self, callback: F) + where + F: Fn(&SslRef, &str) + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(callback) as *mut _, + ); + ffi::SSL_CTX_set_keylog_callback(self.as_ptr(), Some(callbacks::raw_keylog::)); + } + } + + /// Sets the session caching mode use for connections made with the context. + /// + /// Returns the previous session caching mode. + /// + /// This corresponds to [`SSL_CTX_set_session_cache_mode`]. + /// + /// [`SSL_CTX_set_session_cache_mode`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_get_session_cache_mode.html + pub fn set_session_cache_mode(&mut self, mode: SslSessionCacheMode) -> SslSessionCacheMode { + unsafe { + let bits = ffi::SSL_CTX_set_session_cache_mode(self.as_ptr(), mode.bits()); + SslSessionCacheMode { bits } + } + } + + /// Sets the callback for generating an application cookie for TLS1.3 + /// stateless handshakes. + /// + /// The callback will be called with the SSL context and a slice into which the cookie + /// should be written. The callback should return the number of bytes written. + /// + /// This corresponds to `SSL_CTX_set_stateless_cookie_generate_cb`. + #[cfg(ossl111)] + pub fn set_stateless_cookie_generate_cb(&mut self, callback: F) + where + F: Fn(&mut SslRef, &mut [u8]) -> Result + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(callback) as *mut _, + ); + ffi::SSL_CTX_set_stateless_cookie_generate_cb(self.as_ptr(), Some(raw_stateless_cookie_generate::)) + } + } + + /// Sets the callback for verifying an application cookie for TLS1.3 + /// stateless handshakes. + /// + /// The callback will be called with the SSL context and the cookie supplied by the + /// client. It should return true if and only if the cookie is valid. + /// + /// Note that the OpenSSL implementation independently verifies the integrity of + /// application cookies using an HMAC before invoking the supplied callback. + /// + /// This corresponds to `SSL_CTX_set_stateless_cookie_verify_cb`. + #[cfg(ossl111)] + pub fn set_stateless_cookie_verify_cb(&mut self, callback: F) + where + F: Fn(&mut SslRef, &[u8]) -> bool + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(callback) as *mut _, + ); + ffi::SSL_CTX_set_stateless_cookie_verify_cb(self.as_ptr(), Some(raw_stateless_cookie_verify::)) + } + } + + /// Sets the callback for generating a DTLSv1 cookie + /// + /// The callback will be called with the SSL context and a slice into which the cookie + /// should be written. The callback should return the number of bytes written. + /// + /// This corresponds to `SSL_CTX_set_cookie_generate_cb`. + pub fn set_cookie_generate_cb(&mut self, callback: F) + where + F: Fn(&mut SslRef, &mut [u8]) -> Result + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(callback) as *mut _, + ); + ffi::SSL_CTX_set_cookie_generate_cb(self.as_ptr(), Some(raw_cookie_generate::)) + } + } + + /// Sets the callback for verifying a DTLSv1 cookie + /// + /// The callback will be called with the SSL context and the cookie supplied by the + /// client. It should return true if and only if the cookie is valid. + /// + /// This corresponds to `SSL_CTX_set_cookie_verify_cb`. + pub fn set_cookie_verify_cb(&mut self, callback: F) + where + F: Fn(&mut SslRef, &[u8]) -> bool + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(callback) as *mut _, + ); + ffi::SSL_CTX_set_cookie_verify_cb(self.as_ptr(), Some(raw_cookie_verify::)) + } + } + + /// Sets the extra data at the specified index. + /// + /// This can be used to provide data to callbacks registered with the context. Use the + /// `SslContext::new_ex_index` method to create an `Index`. + /// + /// This corresponds to [`SSL_CTX_set_ex_data`]. + /// + /// [`SSL_CTX_set_ex_data`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_ex_data.html + pub fn set_ex_data(&mut self, index: Index, data: T) { + unsafe { + let data = Box::new(data); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + index.as_raw(), + Box::into_raw(data) as *mut c_void, + ); + } + } + + /// Adds a custom extension for a TLS/DTLS client or server for all supported protocol versions. + /// + /// Requires OpenSSL 1.1.1 or newer. + /// + /// This corresponds to [`SSL_CTX_add_custom_ext`]. + /// + /// [`SSL_CTX_add_custom_ext`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_add_custom_ext.html + #[cfg(ossl111)] + pub fn add_custom_ext( + &mut self, + ext_type: u16, + context: ExtensionContext, + add_cb: AddFn, + parse_cb: ParseFn, + ) -> Result<(), ErrorStack> + where + AddFn: Fn(&mut SslRef, ExtensionContext, Option<(usize, &X509Ref)>) + -> Result, SslAlert> + + 'static + + Sync + + Send, + T: AsRef<[u8]> + 'static + Sync + Send, + ParseFn: Fn(&mut SslRef, ExtensionContext, &[u8], Option<(usize, &X509Ref)>) + -> Result<(), SslAlert> + + 'static + + Sync + + Send, + { + let ret = unsafe { + let add_cb = Box::new(add_cb); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(add_cb) as *mut _, + ); + + let parse_cb = Box::new(parse_cb); + ffi::SSL_CTX_set_ex_data( + self.as_ptr(), + get_callback_idx::(), + Box::into_raw(parse_cb) as *mut _, + ); + + ffi::SSL_CTX_add_custom_ext( + self.as_ptr(), + ext_type as c_uint, + context.bits(), + Some(raw_custom_ext_add::), + Some(raw_custom_ext_free::), + ptr::null_mut(), + Some(raw_custom_ext_parse::), + ptr::null_mut(), + ) + }; + if ret == 1 { + Ok(()) + } else { + Err(ErrorStack::get()) + } + } + + /// Consumes the builder, returning a new `SslContext`. + pub fn build(self) -> SslContext { + self.0 + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::SSL_CTX; + fn drop = ffi::SSL_CTX_free; + + /// A context object for TLS streams. + /// + /// Applications commonly configure a single `SslContext` that is shared by all of its + /// `SslStreams`. + pub struct SslContext; + + /// Reference to [`SslContext`] + /// + /// [`SslContext`]: struct.SslContext.html + pub struct SslContextRef; +} + +impl Clone for SslContext { + fn clone(&self) -> Self { + unsafe { + compat::SSL_CTX_up_ref(self.as_ptr()); + SslContext::from_ptr(self.as_ptr()) + } + } +} + +// TODO: add useful info here +impl fmt::Debug for SslContext { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "SslContext") + } +} + +impl SslContext { + /// Creates a new builder object for an `SslContext`. + pub fn builder(method: SslMethod) -> Result { + SslContextBuilder::new(method) + } + + /// Returns a new extra data index. + /// + /// Each invocation of this function is guaranteed to return a distinct index. These can be used + /// to store data in the context that can be retrieved later by callbacks, for example. + /// + /// This corresponds to [`SSL_CTX_get_ex_new_index`]. + /// + /// [`SSL_CTX_get_ex_new_index`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_get_ex_new_index.html + pub fn new_ex_index() -> Result, ErrorStack> + where + T: 'static + Sync + Send, + { + unsafe { + ffi::init(); + let idx = cvt_n(compat::get_new_idx(free_data_box::))?; + Ok(Index::from_raw(idx)) + } + } +} + +impl SslContextRef { + /// Returns the certificate associated with this `SslContext`, if present. + /// + /// Requires OpenSSL 1.0.2 or newer. + /// + /// This corresponds to [`SSL_CTX_get0_certificate`]. + /// + /// [`SSL_CTX_get0_certificate`]: https://www.openssl.org/docs/man1.1.0/ssl/ssl.html + #[cfg(any(ossl102, ossl110))] + pub fn certificate(&self) -> Option<&X509Ref> { + unsafe { + let ptr = ffi::SSL_CTX_get0_certificate(self.as_ptr()); + if ptr.is_null() { + None + } else { + Some(X509Ref::from_ptr(ptr)) + } + } + } + + /// Returns the private key associated with this `SslContext`, if present. + /// + /// Requires OpenSSL 1.0.2 or newer. + /// + /// This corresponds to [`SSL_CTX_get0_privatekey`]. + /// + /// [`SSL_CTX_get0_privatekey`]: https://www.openssl.org/docs/man1.1.0/ssl/ssl.html + #[cfg(any(ossl102, ossl110))] + pub fn private_key(&self) -> Option<&PKeyRef> { + unsafe { + let ptr = ffi::SSL_CTX_get0_privatekey(self.as_ptr()); + if ptr.is_null() { + None + } else { + Some(PKeyRef::from_ptr(ptr)) + } + } + } + + /// Returns a shared reference to the certificate store used for verification. + /// + /// This corresponds to [`SSL_CTX_get_cert_store`]. + /// + /// [`SSL_CTX_get_cert_store`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_get_cert_store.html + pub fn cert_store(&self) -> &X509StoreRef { + unsafe { X509StoreRef::from_ptr(ffi::SSL_CTX_get_cert_store(self.as_ptr())) } + } + + /// Returns a shared reference to the stack of certificates making up the chain from the leaf. + /// + /// This corresponds to `SSL_CTX_get_extra_chain_certs`. + pub fn extra_chain_certs(&self) -> &StackRef { + unsafe { + let mut chain = ptr::null_mut(); + ffi::SSL_CTX_get_extra_chain_certs(self.as_ptr(), &mut chain); + assert!(!chain.is_null()); + StackRef::from_ptr(chain) + } + } + + /// Returns a reference to the extra data at the specified index. + /// + /// This corresponds to [`SSL_CTX_get_ex_data`]. + /// + /// [`SSL_CTX_get_ex_data`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_get_ex_data.html + pub fn ex_data(&self, index: Index) -> Option<&T> { + unsafe { + let data = ffi::SSL_CTX_get_ex_data(self.as_ptr(), index.as_raw()); + if data.is_null() { + None + } else { + Some(&*(data as *const T)) + } + } + } +} + +/// Information about the state of a cipher. +pub struct CipherBits { + /// The number of secret bits used for the cipher. + pub secret: i32, + + /// The number of bits processed by the chosen algorithm. + pub algorithm: i32, +} + +/// Information about a cipher. +pub struct SslCipher(*mut ffi::SSL_CIPHER); + +impl ForeignType for SslCipher { + type CType = ffi::SSL_CIPHER; + type Ref = SslCipherRef; + + #[inline] + unsafe fn from_ptr(ptr: *mut ffi::SSL_CIPHER) -> SslCipher { + SslCipher(ptr) + } + + #[inline] + fn as_ptr(&self) -> *mut ffi::SSL_CIPHER { + self.0 + } +} + +impl Deref for SslCipher { + type Target = SslCipherRef; + + fn deref(&self) -> &SslCipherRef { + unsafe { SslCipherRef::from_ptr(self.0) } + } +} + +impl DerefMut for SslCipher { + fn deref_mut(&mut self) -> &mut SslCipherRef { + unsafe { SslCipherRef::from_ptr_mut(self.0) } + } +} + +/// Reference to an [`SslCipher`]. +/// +/// [`SslCipher`]: struct.SslCipher.html +pub struct SslCipherRef(Opaque); + +impl ForeignTypeRef for SslCipherRef { + type CType = ffi::SSL_CIPHER; +} + +impl SslCipherRef { + /// Returns the name of the cipher. + /// + /// This corresponds to [`SSL_CIPHER_get_name`]. + /// + /// [`SSL_CIPHER_get_name`]: https://www.openssl.org/docs/manmaster/man3/SSL_CIPHER_get_name.html + pub fn name(&self) -> &str { + let name = unsafe { + let ptr = ffi::SSL_CIPHER_get_name(self.as_ptr()); + CStr::from_ptr(ptr as *const _) + }; + + str::from_utf8(name.to_bytes()).unwrap() + } + + /// Returns the SSL/TLS protocol version that first defined the cipher. + /// + /// This corresponds to [`SSL_CIPHER_get_version`]. + /// + /// [`SSL_CIPHER_get_version`]: https://www.openssl.org/docs/manmaster/man3/SSL_CIPHER_get_name.html + pub fn version(&self) -> &str { + let version = unsafe { + let ptr = ffi::SSL_CIPHER_get_version(self.as_ptr()); + CStr::from_ptr(ptr as *const _) + }; + + str::from_utf8(version.to_bytes()).unwrap() + } + + /// Returns the number of bits used for the cipher. + /// + /// This corresponds to [`SSL_CIPHER_get_bits`]. + /// + /// [`SSL_CIPHER_get_bits`]: https://www.openssl.org/docs/manmaster/man3/SSL_CIPHER_get_name.html + pub fn bits(&self) -> CipherBits { + unsafe { + let mut algo_bits = 0; + let secret_bits = ffi::SSL_CIPHER_get_bits(self.as_ptr(), &mut algo_bits); + CipherBits { + secret: secret_bits.into(), + algorithm: algo_bits.into(), + } + } + } + + /// Returns a textual description of the cipher. + /// + /// This corresponds to [`SSL_CIPHER_description`]. + /// + /// [`SSL_CIPHER_description`]: https://www.openssl.org/docs/manmaster/man3/SSL_CIPHER_get_name.html + pub fn description(&self) -> String { + unsafe { + // SSL_CIPHER_description requires a buffer of at least 128 bytes. + let mut buf = [0; 128]; + let ptr = ffi::SSL_CIPHER_description(self.as_ptr(), buf.as_mut_ptr(), 128); + String::from_utf8(CStr::from_ptr(ptr as *const _).to_bytes().to_vec()).unwrap() + } + } + + /// Returns the handshake digest of the cipher. + /// + /// Requires OpenSSL 1.1.1 or newer. + /// + /// This corresponds to [`SSL_CIPHER_get_handshake_digest`]. + /// + /// [`SSL_CIPHER_get_handshake_digest`]: https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_handshake_digest.html + #[cfg(ossl111)] + pub fn handshake_digest(&self) -> Option { + unsafe { + let ptr = ffi::SSL_CIPHER_get_handshake_digest(self.as_ptr()); + if ptr.is_null() { + None + } else { + Some(MessageDigest::from_ptr(ptr)) + } + } + } + + /// Returns the NID corresponding to the cipher. + /// + /// Requires OpenSSL 1.1.0 or newer. + /// + /// This corresponds to [`SSL_CIPHER_get_cipher_nid`]. + /// + /// [`SSL_CIPHER_get_cipher_nid`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CIPHER_get_cipher_nid.html + #[cfg(any(ossl110))] + pub fn cipher_nid(&self) -> Option { + let n = unsafe { ffi::SSL_CIPHER_get_cipher_nid(self.as_ptr()) }; + if n == 0 { + None + } else { + Some(Nid::from_raw(n)) + } + } +} + +foreign_type! { + type CType = ffi::SSL_SESSION; + fn drop = ffi::SSL_SESSION_free; + + /// An encoded SSL session. + /// + /// These can be cached to share sessions across connections. + pub struct SslSession; + + /// Reference to [`SslSession`]. + /// + /// [`SslSession`]: struct.SslSession.html + pub struct SslSessionRef; +} + +unsafe impl Sync for SslSession {} +unsafe impl Send for SslSession {} + +impl Clone for SslSession { + fn clone(&self) -> SslSession { + SslSessionRef::to_owned(self) + } +} + +impl ToOwned for SslSessionRef { + type Owned = SslSession; + + fn to_owned(&self) -> SslSession { + unsafe { + compat::SSL_SESSION_up_ref(self.as_ptr()); + SslSession(self.as_ptr()) + } + } +} + +impl SslSessionRef { + /// Returns the SSL session ID. + /// + /// This corresponds to [`SSL_SESSION_get_id`]. + /// + /// [`SSL_SESSION_get_id`]: https://www.openssl.org/docs/manmaster/man3/SSL_SESSION_get_id.html + pub fn id(&self) -> &[u8] { + unsafe { + let mut len = 0; + let p = ffi::SSL_SESSION_get_id(self.as_ptr(), &mut len); + slice::from_raw_parts(p as *const u8, len as usize) + } + } + + /// Returns the length of the master key. + /// + /// This corresponds to [`SSL_SESSION_get_master_key`]. + /// + /// [`SSL_SESSION_get_master_key`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_SESSION_get_master_key.html + pub fn master_key_len(&self) -> usize { + unsafe { compat::SSL_SESSION_get_master_key(self.as_ptr(), ptr::null_mut(), 0) } + } + + /// Copies the master key into the provided buffer. + /// + /// Returns the number of bytes written, or the size of the master key if the buffer is empty. + /// + /// This corresponds to [`SSL_SESSION_get_master_key`]. + /// + /// [`SSL_SESSION_get_master_key`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_SESSION_get_master_key.html + pub fn master_key(&self, buf: &mut [u8]) -> usize { + unsafe { compat::SSL_SESSION_get_master_key(self.as_ptr(), buf.as_mut_ptr(), buf.len()) } + } +} + +foreign_type! { + type CType = ffi::SSL; + fn drop = ffi::SSL_free; + + /// The state of an SSL/TLS session. + /// + /// `Ssl` objects are created from an [`SslContext`], which provides configuration defaults. + /// These defaults can be overridden on a per-`Ssl` basis, however. + /// + /// [`SslContext`]: struct.SslContext.html + pub struct Ssl; + + /// Reference to an [`Ssl`]. + /// + /// [`Ssl`]: struct.Ssl.html + pub struct SslRef; +} + +impl Ssl { + /// Returns a new extra data index. + /// + /// Each invocation of this function is guaranteed to return a distinct index. These can be used + /// to store data in the context that can be retrieved later by callbacks, for example. + /// + /// This corresponds to [`SSL_get_ex_new_index`]. + /// + /// [`SSL_get_ex_new_index`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_ex_new_index.html + pub fn new_ex_index() -> Result, ErrorStack> + where + T: 'static + Sync + Send, + { + unsafe { + ffi::init(); + let idx = cvt_n(compat::get_new_ssl_idx(free_data_box::))?; + Ok(Index::from_raw(idx)) + } + } +} + +impl fmt::Debug for SslRef { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("Ssl") + .field("state", &self.state_string_long()) + .field("verify_result", &self.verify_result()) + .finish() + } +} + +impl SslRef { + fn get_raw_rbio(&self) -> *mut ffi::BIO { + unsafe { ffi::SSL_get_rbio(self.as_ptr()) } + } + + fn read(&mut self, buf: &mut [u8]) -> c_int { + let len = cmp::min(c_int::max_value() as usize, buf.len()) as c_int; + unsafe { ffi::SSL_read(self.as_ptr(), buf.as_ptr() as *mut c_void, len) } + } + + fn write(&mut self, buf: &[u8]) -> c_int { + let len = cmp::min(c_int::max_value() as usize, buf.len()) as c_int; + unsafe { ffi::SSL_write(self.as_ptr(), buf.as_ptr() as *const c_void, len) } + } + + fn get_error(&self, ret: c_int) -> ErrorCode { + unsafe { ErrorCode::from_raw(ffi::SSL_get_error(self.as_ptr(), ret)) } + } + + /// Like [`SslContextBuilder::set_verify`]. + /// + /// This corresponds to [`SSL_set_verify`]. + /// + /// [`SslContextBuilder::set_verify`]: struct.SslContextBuilder.html#method.set_verify + /// [`SSL_set_verify`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_verify.html + pub fn set_verify(&mut self, mode: SslVerifyMode) { + unsafe { ffi::SSL_set_verify(self.as_ptr(), mode.bits as c_int, None) } + } + + /// Like [`SslContextBuilder::set_verify_callback`]. + /// + /// This corresponds to [`SSL_set_verify`]. + /// + /// [`SslContextBuilder::set_verify_callback`]: struct.SslContextBuilder.html#method.set_verify_callback + /// [`SSL_set_verify`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_verify.html + pub fn set_verify_callback(&mut self, mode: SslVerifyMode, verify: F) + where + F: Fn(bool, &mut X509StoreContextRef) -> bool + 'static + Sync + Send, + { + unsafe { + let verify = Box::new(verify); + ffi::SSL_set_ex_data( + self.as_ptr(), + get_ssl_callback_idx::(), + mem::transmute(verify), + ); + ffi::SSL_set_verify(self.as_ptr(), mode.bits as c_int, Some(ssl_raw_verify::)); + } + } + + /// Like [`SslContextBuilder::set_tmp_dh`]. + /// + /// This corresponds to [`SSL_set_tmp_dh`]. + /// + /// [`SslContextBuilder::set_tmp_dh`]: struct.SslContextBuilder.html#method.set_tmp_dh + /// [`SSL_set_tmp_dh`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tmp_dh.html + pub fn set_tmp_dh(&mut self, dh: &DhRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::SSL_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) } + } + + /// Like [`SslContextBuilder::set_tmp_dh_callback`]. + /// + /// This corresponds to [`SSL_set_tmp_dh_callback`]. + /// + /// [`SslContextBuilder::set_tmp_dh_callback`]: struct.SslContextBuilder.html#method.set_tmp_dh_callback + /// [`SSL_set_tmp_dh_callback`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tmp_dh.html + pub fn set_tmp_dh_callback(&mut self, callback: F) + where + F: Fn(&mut SslRef, bool, u32) -> Result, ErrorStack> + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_set_ex_data( + self.as_ptr(), + get_ssl_callback_idx::(), + Box::into_raw(callback) as *mut c_void, + ); + let f: unsafe extern "C" fn(_, _, _) -> _ = raw_tmp_dh_ssl::; + ffi::SSL_set_tmp_dh_callback(self.as_ptr(), f); + } + } + + /// Like [`SslContextBuilder::set_tmp_ecdh`]. + /// + /// This corresponds to `SSL_set_tmp_ecdh`. + /// + /// [`SslContextBuilder::set_tmp_ecdh`]: struct.SslContextBuilder.html#method.set_tmp_ecdh + pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::SSL_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) } + } + + /// Like [`SslContextBuilder::set_tmp_ecdh_callback`]. + /// + /// Requires OpenSSL 1.0.1 or 1.0.2. + /// + /// This corresponds to `SSL_set_tmp_ecdh_callback`. + /// + /// [`SslContextBuilder::set_tmp_ecdh_callback`]: struct.SslContextBuilder.html#method.set_tmp_ecdh_callback + #[cfg(any(ossl101, ossl102))] + pub fn set_tmp_ecdh_callback(&mut self, callback: F) + where + F: Fn(&mut SslRef, bool, u32) -> Result, ErrorStack> + 'static + Sync + Send, + { + unsafe { + let callback = Box::new(callback); + ffi::SSL_set_ex_data( + self.as_ptr(), + get_ssl_callback_idx::(), + Box::into_raw(callback) as *mut c_void, + ); + let f: unsafe extern "C" fn(_, _, _) -> _ = raw_tmp_ecdh_ssl::; + ffi::SSL_set_tmp_ecdh_callback(self.as_ptr(), f); + } + } + + /// Like [`SslContextBuilder::set_ecdh_auto`]. + /// + /// Requires OpenSSL 1.0.2. + /// + /// This corresponds to [`SSL_set_ecdh_auto`]. + /// + /// [`SslContextBuilder::set_tmp_ecdh`]: struct.SslContextBuilder.html#method.set_tmp_ecdh + /// [`SSL_set_ecdh_auto`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_ecdh_auto.html + #[cfg(ossl102)] + pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::SSL_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) } + } + + /// Returns the current cipher if the session is active. + /// + /// This corresponds to [`SSL_get_current_cipher`]. + /// + /// [`SSL_get_current_cipher`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_current_cipher.html + pub fn current_cipher(&self) -> Option<&SslCipherRef> { + unsafe { + let ptr = ffi::SSL_get_current_cipher(self.as_ptr()); + + if ptr.is_null() { + None + } else { + Some(SslCipherRef::from_ptr(ptr as *mut _)) + } + } + } + + /// Returns a short string describing the state of the session. + /// + /// This corresponds to [`SSL_state_string`]. + /// + /// [`SSL_state_string`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_state_string.html + pub fn state_string(&self) -> &'static str { + let state = unsafe { + let ptr = ffi::SSL_state_string(self.as_ptr()); + CStr::from_ptr(ptr as *const _) + }; + + str::from_utf8(state.to_bytes()).unwrap() + } + + /// Returns a longer string describing the state of the session. + /// + /// This corresponds to [`SSL_state_string_long`]. + /// + /// [`SSL_state_string_long`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_state_string_long.html + pub fn state_string_long(&self) -> &'static str { + let state = unsafe { + let ptr = ffi::SSL_state_string_long(self.as_ptr()); + CStr::from_ptr(ptr as *const _) + }; + + str::from_utf8(state.to_bytes()).unwrap() + } + + /// Sets the host name to be sent to the server for Server Name Indication (SNI). + /// + /// It has no effect for a server-side connection. + /// + /// This corresponds to [`SSL_set_tlsext_host_name`]. + /// + /// [`SSL_set_tlsext_host_name`]: https://www.openssl.org/docs/manmaster/man3/SSL_get_servername_type.html + pub fn set_hostname(&mut self, hostname: &str) -> Result<(), ErrorStack> { + let cstr = CString::new(hostname).unwrap(); + unsafe { + cvt(ffi::SSL_set_tlsext_host_name(self.as_ptr(), cstr.as_ptr() as *mut _) as c_int) + .map(|_| ()) + } + } + + /// Returns the peer's certificate, if present. + /// + /// This corresponds to [`SSL_get_peer_certificate`]. + /// + /// [`SSL_get_peer_certificate`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_peer_certificate.html + pub fn peer_certificate(&self) -> Option { + unsafe { + let ptr = ffi::SSL_get_peer_certificate(self.as_ptr()); + if ptr.is_null() { + None + } else { + Some(X509::from_ptr(ptr)) + } + } + } + + /// Returns the certificate chain of the peer, if present. + /// + /// On the client side, the chain includes the leaf certificate, but on the server side it does + /// not. Fun! + /// + /// This corresponds to [`SSL_get_peer_cert_chain`]. + /// + /// [`SSL_get_peer_cert_chain`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_peer_cert_chain.html + pub fn peer_cert_chain(&self) -> Option<&StackRef> { + unsafe { + let ptr = ffi::SSL_get_peer_cert_chain(self.as_ptr()); + if ptr.is_null() { + None + } else { + Some(StackRef::from_ptr(ptr)) + } + } + } + + /// Like [`SslContext::certificate`]. + /// + /// This corresponds to `SSL_get_certificate`. + /// + /// [`SslContext::certificate`]: struct.SslContext.html#method.certificate + pub fn certificate(&self) -> Option<&X509Ref> { + unsafe { + let ptr = ffi::SSL_get_certificate(self.as_ptr()); + if ptr.is_null() { + None + } else { + Some(X509Ref::from_ptr(ptr)) + } + } + } + + /// Like [`SslContext::private_key`]. + /// + /// This corresponds to `SSL_get_privatekey`. + /// + /// [`SslContext::private_key`]: struct.SslContext.html#method.private_key + pub fn private_key(&self) -> Option<&PKeyRef> { + unsafe { + let ptr = ffi::SSL_get_privatekey(self.as_ptr()); + if ptr.is_null() { + None + } else { + Some(PKeyRef::from_ptr(ptr)) + } + } + } + + #[deprecated(since = "0.10.5", note = "renamed to `version_str`")] + pub fn version(&self) -> &str { + self.version_str() + } + + /// Returns the protocol version of the session. + /// + /// This corresponds to [`SSL_version`]. + /// + /// [`SSL_version`]: https://www.openssl.org/docs/manmaster/man3/SSL_version.html + pub fn version2(&self) -> Option { + unsafe { + let r = ffi::SSL_version(self.as_ptr()); + if r == 0 { + None + } else { + Some(SslVersion(r)) + } + } + } + + /// Returns a string describing the protocol version of the session. + /// + /// This corresponds to [`SSL_get_version`]. + /// + /// [`SSL_get_version`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_version.html + pub fn version_str(&self) -> &'static str { + let version = unsafe { + let ptr = ffi::SSL_get_version(self.as_ptr()); + CStr::from_ptr(ptr as *const _) + }; + + str::from_utf8(version.to_bytes()).unwrap() + } + + /// Returns the protocol selected via Application Layer Protocol Negotiation (ALPN). + /// + /// The protocol's name is returned is an opaque sequence of bytes. It is up to the client + /// to interpret it. + /// + /// Requires OpenSSL 1.0.2 or newer. + /// + /// This corresponds to [`SSL_get0_alpn_selected`]. + /// + /// [`SSL_get0_alpn_selected`]: https://www.openssl.org/docs/manmaster/man3/SSL_get0_next_proto_negotiated.html + #[cfg(any(ossl102, ossl110))] + pub fn selected_alpn_protocol(&self) -> Option<&[u8]> { + unsafe { + let mut data: *const c_uchar = ptr::null(); + let mut len: c_uint = 0; + // Get the negotiated protocol from the SSL instance. + // `data` will point at a `c_uchar` array; `len` will contain the length of this array. + ffi::SSL_get0_alpn_selected(self.as_ptr(), &mut data, &mut len); + + if data.is_null() { + None + } else { + Some(slice::from_raw_parts(data, len as usize)) + } + } + } + + /// Returns the number of bytes remaining in the currently processed TLS record. + /// + /// If this is greater than 0, the next call to `read` will not call down to the underlying + /// stream. + /// + /// This corresponds to [`SSL_pending`]. + /// + /// [`SSL_pending`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_pending.html + pub fn pending(&self) -> usize { + unsafe { ffi::SSL_pending(self.as_ptr()) as usize } + } + + /// Returns the servername sent by the client via Server Name Indication (SNI). + /// + /// It is only useful on the server side. + /// + /// This corresponds to [`SSL_get_servername`]. + /// + /// [`SSL_get_servername`]: https://www.openssl.org/docs/manmaster/man3/SSL_get_servername.html + pub fn servername(&self, type_: NameType) -> Option<&str> { + unsafe { + let name = ffi::SSL_get_servername(self.as_ptr(), type_.0); + if name == ptr::null() { + None + } else { + Some(str::from_utf8(CStr::from_ptr(name as *const _).to_bytes()).unwrap()) + } + } + } + + /// Changes the context corresponding to the current connection. + /// + /// It is most commonly used in the Server Name Indication (SNI) callback. + /// + /// This corresponds to `SSL_set_SSL_CTX`. + pub fn set_ssl_context(&mut self, ctx: &SslContextRef) -> Result<(), ErrorStack> { + unsafe { cvt_p(ffi::SSL_set_SSL_CTX(self.as_ptr(), ctx.as_ptr())).map(|_| ()) } + } + + /// Returns the context corresponding to the current connection. + /// + /// This corresponds to [`SSL_get_SSL_CTX`]. + /// + /// [`SSL_get_SSL_CTX`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_SSL_CTX.html + pub fn ssl_context(&self) -> &SslContextRef { + unsafe { + let ssl_ctx = ffi::SSL_get_SSL_CTX(self.as_ptr()); + SslContextRef::from_ptr(ssl_ctx) + } + } + + /// Returns a mutable reference to the X509 verification configuration. + /// + /// Requires OpenSSL 1.0.2 or newer. + /// + /// This corresponds to [`SSL_get0_param`]. + /// + /// [`SSL_get0_param`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_get0_param.html + #[cfg(any(ossl102, ossl110))] + pub fn param_mut(&mut self) -> &mut X509VerifyParamRef { + unsafe { X509VerifyParamRef::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr())) } + } + + /// Returns the certificate verification result. + /// + /// This corresponds to [`SSL_get_verify_result`]. + /// + /// [`SSL_get_verify_result`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_verify_result.html + pub fn verify_result(&self) -> X509VerifyResult { + unsafe { X509VerifyResult::from_raw(ffi::SSL_get_verify_result(self.as_ptr()) as c_int) } + } + + /// Returns a shared reference to the SSL session. + /// + /// This corresponds to [`SSL_get_session`]. + /// + /// [`SSL_get_session`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_session.html + pub fn session(&self) -> Option<&SslSessionRef> { + unsafe { + let p = ffi::SSL_get_session(self.as_ptr()); + if p.is_null() { + None + } else { + Some(SslSessionRef::from_ptr(p)) + } + } + } + + /// Copies the client_random value sent by the client in the TLS handshake into a buffer. + /// + /// Returns the number of bytes copied, or if the buffer is empty, the size of the client_random + /// value. + /// + /// Requires OpenSSL 1.1.0 or newer. + /// + /// This corresponds to [`SSL_get_client_random`]. + /// + /// [`SSL_get_client_random`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_client_random.html + #[cfg(any(ossl110))] + pub fn client_random(&self, buf: &mut [u8]) -> usize { + unsafe { + ffi::SSL_get_client_random(self.as_ptr(), buf.as_mut_ptr() as *mut c_uchar, buf.len()) + } + } + + /// Copies the server_random value sent by the server in the TLS handshake into a buffer. + /// + /// Returns the number of bytes copied, or if the buffer is empty, the size of the server_random + /// value. + /// + /// Requires OpenSSL 1.1.0 or newer. + /// + /// This corresponds to [`SSL_get_server_random`]. + /// + /// [`SSL_get_server_random`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_client_random.html + #[cfg(any(ossl110))] + pub fn server_random(&self, buf: &mut [u8]) -> usize { + unsafe { + ffi::SSL_get_server_random(self.as_ptr(), buf.as_mut_ptr() as *mut c_uchar, buf.len()) + } + } + + /// Derives keying material for application use in accordance to RFC 5705. + /// + /// This corresponds to [`SSL_export_keying_material`]. + /// + /// [`SSL_export_keying_material`]: https://www.openssl.org/docs/manmaster/man3/SSL_export_keying_material.html + pub fn export_keying_material( + &self, + out: &mut [u8], + label: &str, + context: Option<&[u8]>, + ) -> Result<(), ErrorStack> { + unsafe { + let (context, contextlen, use_context) = match context { + Some(context) => (context.as_ptr() as *const c_uchar, context.len(), 1), + None => (ptr::null(), 0, 0), + }; + cvt(ffi::SSL_export_keying_material( + self.as_ptr(), + out.as_mut_ptr() as *mut c_uchar, + out.len(), + label.as_ptr() as *const c_char, + label.len(), + context, + contextlen, + use_context, + )).map(|_| ()) + } + } + + /// Sets the session to be used. + /// + /// This should be called before the handshake to attempt to reuse a previously established + /// session. If the server is not willing to reuse the session, a new one will be transparently + /// negotiated. + /// + /// This corresponds to [`SSL_set_session`]. + /// + /// # Safety + /// + /// The caller of this method is responsible for ensuring that the session is associated + /// with the same `SslContext` as this `Ssl`. + /// + /// [`SSL_set_session`]: https://www.openssl.org/docs/manmaster/man3/SSL_set_session.html + pub unsafe fn set_session(&mut self, session: &SslSessionRef) -> Result<(), ErrorStack> { + cvt(ffi::SSL_set_session(self.as_ptr(), session.as_ptr())).map(|_| ()) + } + + /// Determines if the session provided to `set_session` was successfully reused. + /// + /// This corresponds to [`SSL_session_reused`]. + /// + /// [`SSL_session_reused`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_session_reused.html + pub fn session_reused(&self) -> bool { + unsafe { ffi::SSL_session_reused(self.as_ptr()) != 0 } + } + + /// Sets the status response a client wishes the server to reply with. + /// + /// This corresponds to [`SSL_set_tlsext_status_type`]. + /// + /// [`SSL_set_tlsext_status_type`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tlsext_status_type.html + pub fn set_status_type(&mut self, type_: StatusType) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::SSL_set_tlsext_status_type(self.as_ptr(), type_.as_raw()) as c_int).map(|_| ()) + } + } + + /// Returns the server's OCSP response, if present. + /// + /// This corresponds to [`SSL_get_tlsext_status_ocsp_resp`]. + /// + /// [`SSL_get_tlsext_status_ocsp_resp`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tlsext_status_type.html + pub fn ocsp_status(&self) -> Option<&[u8]> { + unsafe { + let mut p = ptr::null_mut(); + let len = ffi::SSL_get_tlsext_status_ocsp_resp(self.as_ptr(), &mut p); + + if len < 0 { + None + } else { + Some(slice::from_raw_parts(p as *const u8, len as usize)) + } + } + } + + /// Sets the OCSP response to be returned to the client. + /// + /// This corresponds to [`SSL_set_tlsext_status_ocsp_resp`]. + /// + /// [`SSL_set_tlsext_status_ocsp_resp`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tlsext_status_type.html + pub fn set_ocsp_status(&mut self, response: &[u8]) -> Result<(), ErrorStack> { + unsafe { + assert!(response.len() <= c_int::max_value() as usize); + let p = cvt_p(ffi::CRYPTO_malloc( + response.len() as _, + concat!(file!(), "\0").as_ptr() as *const _, + line!() as c_int, + ))?; + ptr::copy_nonoverlapping(response.as_ptr(), p as *mut u8, response.len()); + cvt(ffi::SSL_set_tlsext_status_ocsp_resp( + self.as_ptr(), + p as *mut c_uchar, + response.len() as c_long, + ) as c_int) + .map(|_| ()) + } + } + + /// Determines if this `Ssl` is configured for server-side or client-side use. + /// + /// This corresponds to [`SSL_is_server`]. + /// + /// [`SSL_is_server`]: https://www.openssl.org/docs/manmaster/man3/SSL_is_server.html + pub fn is_server(&self) -> bool { + unsafe { compat::SSL_is_server(self.as_ptr()) != 0 } + } + + /// Sets the extra data at the specified index. + /// + /// This can be used to provide data to callbacks registered with the context. Use the + /// `Ssl::new_ex_index` method to create an `Index`. + /// + /// This corresponds to [`SSL_set_ex_data`]. + /// + /// [`SSL_set_ex_data`]: https://www.openssl.org/docs/manmaster/man3/SSL_set_ex_data.html + pub fn set_ex_data(&mut self, index: Index, data: T) { + unsafe { + let data = Box::new(data); + ffi::SSL_set_ex_data( + self.as_ptr(), + index.as_raw(), + Box::into_raw(data) as *mut c_void, + ); + } + } + + /// Returns a reference to the extra data at the specified index. + /// + /// This corresponds to [`SSL_get_ex_data`]. + /// + /// [`SSL_get_ex_data`]: https://www.openssl.org/docs/manmaster/man3/SSL_set_ex_data.html + pub fn ex_data(&self, index: Index) -> Option<&T> { + unsafe { + let data = ffi::SSL_get_ex_data(self.as_ptr(), index.as_raw()); + if data.is_null() { + None + } else { + Some(&*(data as *const T)) + } + } + } +} + +unsafe impl Sync for Ssl {} +unsafe impl Send for Ssl {} + +impl fmt::Debug for Ssl { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&**self, fmt) + } +} + +impl Ssl { + /// Creates a new `Ssl`. + /// + /// This corresponds to [`SSL_new`]. + /// + /// [`SSL_new`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_new.html + pub fn new(ctx: &SslContext) -> Result { + unsafe { + let ssl = cvt_p(ffi::SSL_new(ctx.as_ptr()))?; + Ok(Ssl::from_ptr(ssl)) + } + } + + /// Initiates a client-side TLS handshake. + /// + /// This corresponds to [`SSL_connect`]. + /// + /// # Warning + /// + /// OpenSSL's default configuration is insecure. It is highly recommended to use + /// `SslConnector` rather than `Ssl` directly, as it manages that configuration. + /// + /// [`SSL_connect`]: https://www.openssl.org/docs/manmaster/man3/SSL_connect.html + pub fn connect(self, stream: S) -> Result, HandshakeError> + where + S: Read + Write, + { + SslStreamBuilder::new(self, stream).connect() + } + + /// Initiates a server-side TLS handshake. + /// + /// This corresponds to [`SSL_accept`]. + /// + /// # Warning + /// + /// OpenSSL's default configuration is insecure. It is highly recommended to use + /// `SslAcceptor` rather than `Ssl` directly, as it manages that configuration. + /// + /// [`SSL_accept`]: https://www.openssl.org/docs/manmaster/man3/SSL_accept.html + pub fn accept(self, stream: S) -> Result, HandshakeError> + where + S: Read + Write, + { + SslStreamBuilder::new(self, stream).accept() + } +} + +/// An SSL stream midway through the handshake process. +#[derive(Debug)] +pub struct MidHandshakeSslStream { + stream: SslStream, + error: Error, +} + +impl MidHandshakeSslStream { + /// Returns a shared reference to the inner stream. + pub fn get_ref(&self) -> &S { + self.stream.get_ref() + } + + /// Returns a mutable reference to the inner stream. + pub fn get_mut(&mut self) -> &mut S { + self.stream.get_mut() + } + + /// Returns a shared reference to the `Ssl` of the stream. + pub fn ssl(&self) -> &SslRef { + self.stream.ssl() + } + + /// Returns the underlying error which interrupted this handshake. + pub fn error(&self) -> &Error { + &self.error + } + + /// Consumes `self`, returning its error. + pub fn into_error(self) -> Error { + self.error + } + + /// Restarts the handshake process. + /// + /// This corresponds to [`SSL_do_handshake`]. + /// + /// [`SSL_do_handshake`]: https://www.openssl.org/docs/manmaster/man3/SSL_do_handshake.html + pub fn handshake(mut self) -> Result, HandshakeError> { + let ret = unsafe { ffi::SSL_do_handshake(self.stream.ssl.as_ptr()) }; + if ret > 0 { + Ok(self.stream) + } else { + self.error = self.stream.make_error(ret); + match self.error.code() { + ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => { + Err(HandshakeError::WouldBlock(self)) + } + _ => Err(HandshakeError::Failure(self)), + } + } + } +} + +/// A TLS session over a stream. +pub struct SslStream { + ssl: ManuallyDrop, + method: ManuallyDrop, + _p: PhantomData, +} + +impl Drop for SslStream { + fn drop(&mut self) { + // ssl holds a reference to method internally so it has to drop first + unsafe { + ManuallyDrop::drop(&mut self.ssl); + ManuallyDrop::drop(&mut self.method); + } + } +} + +impl fmt::Debug for SslStream +where + S: fmt::Debug, +{ + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("SslStream") + .field("stream", &self.get_ref()) + .field("ssl", &self.ssl()) + .finish() + } +} + +impl SslStream { + fn new_base(ssl: Ssl, stream: S) -> Self { + unsafe { + let (bio, method) = bio::new(stream).unwrap(); + ffi::SSL_set_bio(ssl.as_ptr(), bio, bio); + + SslStream { + ssl: ManuallyDrop::new(ssl), + method: ManuallyDrop::new(method), + _p: PhantomData, + } + } + } + + /// Like `read`, but returns an `ssl::Error` rather than an `io::Error`. + /// + /// It is particularly useful with a nonblocking socket, where the error value will identify if + /// OpenSSL is waiting on read or write readiness. + /// + /// This corresponds to [`SSL_read`]. + /// + /// [`SSL_read`]: https://www.openssl.org/docs/manmaster/man3/SSL_read.html + pub fn ssl_read(&mut self, buf: &mut [u8]) -> Result { + // The intepretation of the return code here is a little odd with a + // zero-length write. OpenSSL will likely correctly report back to us + // that it read zero bytes, but zero is also the sentinel for "error". + // To avoid that confusion short-circuit that logic and return quickly + // if `buf` has a length of zero. + if buf.len() == 0 { + return Ok(0); + } + + let ret = self.ssl.read(buf); + if ret > 0 { + Ok(ret as usize) + } else { + Err(self.make_error(ret)) + } + } + + /// Like `write`, but returns an `ssl::Error` rather than an `io::Error`. + /// + /// It is particularly useful with a nonblocking socket, where the error value will identify if + /// OpenSSL is waiting on read or write readiness. + /// + /// This corresponds to [`SSL_write`]. + /// + /// [`SSL_write`]: https://www.openssl.org/docs/manmaster/man3/SSL_write.html + pub fn ssl_write(&mut self, buf: &[u8]) -> Result { + // See above for why we short-circuit on zero-length buffers + if buf.len() == 0 { + return Ok(0); + } + + let ret = self.ssl.write(buf); + if ret > 0 { + Ok(ret as usize) + } else { + Err(self.make_error(ret)) + } + } + + /// Shuts down the session. + /// + /// The shutdown process consists of two steps. The first step sends a close notify message to + /// the peer, after which `ShutdownResult::Sent` is returned. The second step awaits the receipt + /// of a close notify message from the peer, after which `ShutdownResult::Received` is returned. + /// + /// While the connection may be closed after the first step, it is recommended to fully shut the + /// session down. In particular, it must be fully shut down if the connection is to be used for + /// further communication in the future. + /// + /// This corresponds to [`SSL_shutdown`]. + /// + /// [`SSL_shutdown`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_shutdown.html + pub fn shutdown(&mut self) -> Result { + match unsafe { ffi::SSL_shutdown(self.ssl.as_ptr()) } { + 0 => Ok(ShutdownResult::Sent), + 1 => Ok(ShutdownResult::Received), + n => Err(self.make_error(n)), + } + } +} + +impl SslStream { + fn make_error(&mut self, ret: c_int) -> Error { + self.check_panic(); + + let code = self.ssl.get_error(ret); + + let cause = match code { + ErrorCode::SSL => Some(InnerError::Ssl(ErrorStack::get())), + ErrorCode::SYSCALL => { + let errs = ErrorStack::get(); + if errs.errors().is_empty() { + self.get_bio_error().map(InnerError::Io) + } else { + Some(InnerError::Ssl(errs)) + } + } + ErrorCode::ZERO_RETURN => None, + ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => { + self.get_bio_error().map(InnerError::Io) + } + _ => None, + }; + + Error { code, cause } + } + + fn check_panic(&mut self) { + if let Some(err) = unsafe { bio::take_panic::(self.ssl.get_raw_rbio()) } { + resume_unwind(err) + } + } + + fn get_bio_error(&mut self) -> Option { + unsafe { bio::take_error::(self.ssl.get_raw_rbio()) } + } + + /// Returns a shared reference to the underlying stream. + pub fn get_ref(&self) -> &S { + unsafe { + let bio = self.ssl.get_raw_rbio(); + bio::get_ref(bio) + } + } + + /// Returns a mutable reference to the underlying stream. + /// + /// # Warning + /// + /// It is inadvisable to read from or write to the underlying stream as it + /// will most likely corrupt the SSL session. + pub fn get_mut(&mut self) -> &mut S { + unsafe { + let bio = self.ssl.get_raw_rbio(); + bio::get_mut(bio) + } + } + + /// Returns a shared reference to the `Ssl` object associated with this stream. + pub fn ssl(&self) -> &SslRef { + &self.ssl + } +} + +impl Read for SslStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + loop { + match self.ssl_read(buf) { + Ok(n) => return Ok(n), + Err(ref e) if e.code() == ErrorCode::ZERO_RETURN => return Ok(0), + Err(ref e) if e.code() == ErrorCode::SYSCALL && e.io_error().is_none() => { + return Ok(0) + } + Err(ref e) if e.code() == ErrorCode::WANT_READ && e.io_error().is_none() => {} + Err(e) => { + return Err(e.into_io_error() + .unwrap_or_else(|e| io::Error::new(io::ErrorKind::Other, e))) + } + } + } + } +} + +impl Write for SslStream { + fn write(&mut self, buf: &[u8]) -> io::Result { + loop { + match self.ssl_write(buf) { + Ok(n) => return Ok(n), + Err(ref e) if e.code() == ErrorCode::WANT_READ && e.io_error().is_none() => {} + Err(e) => { + return Err(e.into_io_error() + .unwrap_or_else(|e| io::Error::new(io::ErrorKind::Other, e))) + } + } + } + } + + fn flush(&mut self) -> io::Result<()> { + self.get_mut().flush() + } +} + +/// A partially constructed `SslStream`, useful for unusual handshakes. +pub struct SslStreamBuilder { + inner: SslStream +} + +impl SslStreamBuilder + where S: Read + Write +{ + /// Begin creating an `SslStream` atop `stream` + pub fn new(ssl: Ssl, stream: S) -> Self { + Self { + inner: SslStream::new_base(ssl, stream), + } + } + + /// Perform a stateless server-side handshake + /// + /// Requires that cookie generation and verification callbacks were + /// set on the SSL context. + /// + /// Returns `Ok(true)` if a complete ClientHello containing a valid cookie + /// was read, in which case the handshake should be continued via + /// `accept`. If a HelloRetryRequest containing a fresh cookie was + /// transmitted, `Ok(false)` is returned instead. If the handshake cannot + /// proceed at all, `Err` is returned. + /// + /// This corresponds to [`SSL_stateless`] + /// + /// [`SSL_stateless`]: https://www.openssl.org/docs/manmaster/man3/SSL_stateless.html + #[cfg(ossl111)] + pub fn stateless(&mut self) -> Result { + match unsafe { ffi::SSL_stateless(self.inner.ssl.as_ptr()) } { + 1 => Ok(true), + 0 => Ok(false), + -1 => Err(ErrorStack::get()), + _ => unreachable!(), + } + } + + /// See `Ssl::connect` + pub fn connect(self) -> Result, HandshakeError> { + let mut stream = self.inner; + let ret = unsafe { ffi::SSL_connect(stream.ssl.as_ptr()) }; + if ret > 0 { + Ok(stream) + } else { + let error = stream.make_error(ret); + match error.code() { + ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => Err(HandshakeError::WouldBlock( + MidHandshakeSslStream { stream, error }, + )), + _ => Err(HandshakeError::Failure(MidHandshakeSslStream { + stream, + error, + })), + } + } + } + + /// See `Ssl::accept` + pub fn accept(self) -> Result, HandshakeError> { + let mut stream = self.inner; + let ret = unsafe { ffi::SSL_accept(stream.ssl.as_ptr()) }; + if ret > 0 { + Ok(stream) + } else { + let error = stream.make_error(ret); + match error.code() { + ErrorCode::WANT_READ | ErrorCode::WANT_WRITE => Err(HandshakeError::WouldBlock( + MidHandshakeSslStream { stream, error }, + )), + _ => Err(HandshakeError::Failure(MidHandshakeSslStream { + stream, + error, + })), + } + } + } + + // Future work: early IO methods +} + +impl SslStreamBuilder { + /// Returns a shared reference to the underlying stream. + pub fn get_ref(&self) -> &S { + unsafe { + let bio = self.inner.ssl.get_raw_rbio(); + bio::get_ref(bio) + } + } + + /// Returns a mutable reference to the underlying stream. + /// + /// # Warning + /// + /// It is inadvisable to read from or write to the underlying stream as it + /// will most likely corrupt the SSL session. + pub fn get_mut(&mut self) -> &mut S { + unsafe { + let bio = self.inner.ssl.get_raw_rbio(); + bio::get_mut(bio) + } + } + + /// Returns a shared reference to the `Ssl` object associated with this builder. + pub fn ssl(&self) -> &SslRef { &self.inner.ssl } +} + +/// The result of a shutdown request. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum ShutdownResult { + /// A close notify message has been sent to the peer. + Sent, + + /// A close notify response message has been received from the peer. + Received, +} + +#[cfg(ossl110)] +mod compat { + use std::ptr; + + use ffi; + use libc::c_int; + + pub use ffi::{SSL_CTX_clear_options, SSL_CTX_get_options, SSL_CTX_set_options, SSL_CTX_up_ref, + SSL_SESSION_get_master_key, SSL_SESSION_up_ref, SSL_is_server}; + + pub unsafe fn get_new_idx(f: ffi::CRYPTO_EX_free) -> c_int { + ffi::CRYPTO_get_ex_new_index( + ffi::CRYPTO_EX_INDEX_SSL_CTX, + 0, + ptr::null_mut(), + None, + None, + Some(f), + ) + } + + pub unsafe fn get_new_ssl_idx(f: ffi::CRYPTO_EX_free) -> c_int { + ffi::CRYPTO_get_ex_new_index( + ffi::CRYPTO_EX_INDEX_SSL, + 0, + ptr::null_mut(), + None, + None, + Some(f), + ) + } + + pub fn tls_method() -> *const ffi::SSL_METHOD { + unsafe { ffi::TLS_method() } + } + + pub fn dtls_method() -> *const ffi::SSL_METHOD { + unsafe { ffi::DTLS_method() } + } +} + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use std::ptr; + + use ffi; + use libc::{self, c_int, c_long, c_uchar, c_ulong, size_t}; + + pub unsafe fn SSL_CTX_get_options(ctx: *const ffi::SSL_CTX) -> c_ulong { + ffi::SSL_CTX_ctrl(ctx as *mut _, ffi::SSL_CTRL_OPTIONS, 0, ptr::null_mut()) as c_ulong + } + + pub unsafe fn SSL_CTX_set_options(ctx: *const ffi::SSL_CTX, op: c_ulong) -> c_ulong { + ffi::SSL_CTX_ctrl( + ctx as *mut _, + ffi::SSL_CTRL_OPTIONS, + op as c_long, + ptr::null_mut(), + ) as c_ulong + } + + pub unsafe fn SSL_CTX_clear_options(ctx: *const ffi::SSL_CTX, op: c_ulong) -> c_ulong { + ffi::SSL_CTX_ctrl( + ctx as *mut _, + ffi::SSL_CTRL_CLEAR_OPTIONS, + op as c_long, + ptr::null_mut(), + ) as c_ulong + } + + pub unsafe fn get_new_idx(f: ffi::CRYPTO_EX_free) -> c_int { + ffi::SSL_CTX_get_ex_new_index(0, ptr::null_mut(), None, None, Some(f)) + } + + pub unsafe fn get_new_ssl_idx(f: ffi::CRYPTO_EX_free) -> c_int { + ffi::SSL_get_ex_new_index(0, ptr::null_mut(), None, None, Some(f)) + } + + pub unsafe fn SSL_CTX_up_ref(ssl: *mut ffi::SSL_CTX) -> libc::c_int { + ffi::CRYPTO_add_lock( + &mut (*ssl).references, + 1, + ffi::CRYPTO_LOCK_SSL_CTX, + "mod.rs\0".as_ptr() as *const _, + line!() as libc::c_int, + ); + 0 + } + + pub unsafe fn SSL_SESSION_get_master_key( + session: *const ffi::SSL_SESSION, + out: *mut c_uchar, + mut outlen: size_t, + ) -> size_t { + if outlen == 0 { + return (*session).master_key_length as size_t; + } + if outlen > (*session).master_key_length as size_t { + outlen = (*session).master_key_length as size_t; + } + ptr::copy_nonoverlapping((*session).master_key.as_ptr(), out, outlen); + outlen + } + + pub fn tls_method() -> *const ffi::SSL_METHOD { + unsafe { ffi::SSLv23_method() } + } + + pub fn dtls_method() -> *const ffi::SSL_METHOD { + unsafe { ffi::DTLSv1_method() } + } + + pub unsafe fn SSL_is_server(s: *mut ffi::SSL) -> c_int { + (*s).server + } + + pub unsafe fn SSL_SESSION_up_ref(ses: *mut ffi::SSL_SESSION) -> c_int { + ffi::CRYPTO_add_lock( + &mut (*ses).references, + 1, + ffi::CRYPTO_LOCK_SSL_CTX, + "mod.rs\0".as_ptr() as *const _, + line!() as libc::c_int, + ); + 0 + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/ssl/test.rs cargo-0.26.0/vendor/openssl-0.10.6/src/ssl/test.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/ssl/test.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/ssl/test.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1508 @@ +#![allow(unused_imports)] + +use std::env; +use std::fs::File; +use std::io::prelude::*; +use std::io::{self, BufReader}; +use std::iter; +use std::mem; +use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::path::Path; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; +use std::thread; +use std::time::Duration; +use tempdir::TempDir; + +use dh::Dh; +use hash::MessageDigest; +use ocsp::{OcspResponse, OcspResponseStatus}; +use ssl; +use ssl::{Error, HandshakeError, ShutdownResult, Ssl, SslAcceptor, SslConnector, SslContext, + SslFiletype, SslMethod, SslSessionCacheMode, SslStream, MidHandshakeSslStream, + SslVerifyMode, StatusType}; +#[cfg(any(ossl110, ossl111))] +use ssl::SslVersion; +use x509::{X509, X509Name, X509StoreContext, X509VerifyResult}; +#[cfg(any(ossl102, ossl110))] +use x509::verify::X509CheckFlags; +use pkey::PKey; + +use std::net::UdpSocket; + +static ROOT_CERT: &'static [u8] = include_bytes!("../../test/root-ca.pem"); +static CERT: &'static [u8] = include_bytes!("../../test/cert.pem"); +static KEY: &'static [u8] = include_bytes!("../../test/key.pem"); + +fn next_addr() -> SocketAddr { + use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; + static PORT: AtomicUsize = ATOMIC_USIZE_INIT; + let port = 15411 + PORT.fetch_add(1, Ordering::SeqCst); + + format!("127.0.0.1:{}", port).parse().unwrap() +} + +struct Server { + p: Child, + _temp: TempDir, +} + +impl Server { + fn spawn(args: &[&str], input: Option>) -> (Server, SocketAddr) { + let td = TempDir::new("openssl").unwrap(); + let cert = td.path().join("cert.pem"); + let key = td.path().join("key.pem"); + File::create(&cert).unwrap().write_all(CERT).unwrap(); + File::create(&key).unwrap().write_all(KEY).unwrap(); + + let addr = next_addr(); + let mut child = Command::new("openssl") + .arg("s_server") + .arg("-accept") + .arg(addr.port().to_string()) + .args(args) + .arg("-cert") + .arg(&cert) + .arg("-key") + .arg(&key) + .arg("-no_dhe") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .stdin(Stdio::piped()) + .spawn() + .unwrap(); + let stdin = child.stdin.take().unwrap(); + if let Some(mut input) = input { + thread::spawn(move || input(stdin)); + } + ( + Server { + p: child, + _temp: td, + }, + addr, + ) + } + + fn new_tcp(args: &[&str]) -> (Server, TcpStream) { + let (mut server, addr) = Server::spawn(args, None); + for _ in 0..20 { + match TcpStream::connect(&addr) { + Ok(s) => return (server, s), + Err(ref e) if e.kind() == io::ErrorKind::ConnectionRefused => { + if let Some(exit_status) = server.p.try_wait().expect("try_wait") { + panic!("server exited: {}", exit_status); + } + thread::sleep(Duration::from_millis(100)); + } + Err(e) => panic!("wut: {}", e), + } + } + panic!("server never came online"); + } + + fn new() -> (Server, TcpStream) { + Server::new_tcp(&["-www"]) + } + + #[allow(dead_code)] + fn new_alpn() -> (Server, TcpStream) { + Server::new_tcp(&[ + "-www", + "-nextprotoneg", + "http/1.1,spdy/3.1", + "-alpn", + "http/1.1,spdy/3.1", + ]) + } +} + +impl Drop for Server { + fn drop(&mut self) { + let _ = self.p.kill(); + let _ = self.p.wait(); + } +} + +macro_rules! run_test( + ($module:ident, $blk:expr) => ( + #[cfg(test)] + mod $module { + use std::io; + use std::io::prelude::*; + use std::path::Path; + use std::net::UdpSocket; + use std::net::TcpStream; + use ssl; + use ssl::SslMethod; + use ssl::{SslContext, Ssl, SslStream, SslVerifyMode, SslOptions}; + use hash::MessageDigest; + use x509::{X509StoreContext, X509VerifyResult}; + #[cfg(any(ossl102, ossl110))] + use x509::X509; + #[cfg(any(ossl102, ossl110))] + use x509::store::X509StoreBuilder; + use hex::FromHex; + use foreign_types::ForeignTypeRef; + use super::Server; + #[cfg(any(ossl102, ossl110))] + use super::ROOT_CERT; + + #[test] + fn sslv23() { + let (_s, stream) = Server::new(); + $blk(SslMethod::tls(), stream); + } + } + ); +); + +run_test!(new_ctx, |method, _| { + SslContext::builder(method).unwrap(); +}); + +run_test!(verify_untrusted, |method, stream| { + let mut ctx = SslContext::builder(method).unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + + match Ssl::new(&ctx.build()).unwrap().connect(stream) { + Ok(_) => panic!("expected failure"), + Err(err) => println!("error {:?}", err), + } +}); + +run_test!(verify_trusted, |method, stream| { + let mut ctx = SslContext::builder(method).unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { + Ok(_) => {} + Err(err) => panic!("Unexpected error {:?}", err), + } + match Ssl::new(&ctx.build()).unwrap().connect(stream) { + Ok(_) => (), + Err(err) => panic!("Expected success, got {:?}", err), + } +}); + +#[cfg(any(ossl102, ossl110))] +run_test!(verify_trusted_with_set_cert, |method, stream| { + let x509 = X509::from_pem(ROOT_CERT).unwrap(); + let mut store = X509StoreBuilder::new().unwrap(); + store.add_cert(x509).unwrap(); + + let mut ctx = SslContext::builder(method).unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + + match ctx.set_verify_cert_store(store.build()) { + Ok(_) => {} + Err(err) => panic!("Unexpected error {:?}", err), + } + match Ssl::new(&ctx.build()).unwrap().connect(stream) { + Ok(_) => (), + Err(err) => panic!("Expected success, got {:?}", err), + } +}); + +run_test!(verify_untrusted_callback_override_ok, |method, stream| { + let mut ctx = SslContext::builder(method).unwrap(); + ctx.set_verify_callback(SslVerifyMode::PEER, |_, _| true); + + match Ssl::new(&ctx.build()).unwrap().connect(stream) { + Ok(_) => (), + Err(err) => panic!("Expected success, got {:?}", err), + } +}); + +run_test!(verify_untrusted_callback_override_bad, |method, stream| { + let mut ctx = SslContext::builder(method).unwrap(); + ctx.set_verify_callback(SslVerifyMode::PEER, |_, _| false); + + assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err()); +}); + +run_test!(verify_trusted_callback_override_ok, |method, stream| { + let mut ctx = SslContext::builder(method).unwrap(); + ctx.set_verify_callback(SslVerifyMode::PEER, |_, _| true); + + match ctx.set_ca_file(&Path::new("test/cert.pem")) { + Ok(_) => {} + Err(err) => panic!("Unexpected error {:?}", err), + } + match Ssl::new(&ctx.build()).unwrap().connect(stream) { + Ok(_) => (), + Err(err) => panic!("Expected success, got {:?}", err), + } +}); + +run_test!(verify_trusted_callback_override_bad, |method, stream| { + let mut ctx = SslContext::builder(method).unwrap(); + ctx.set_verify_callback(SslVerifyMode::PEER, |_, _| false); + + match ctx.set_ca_file(&Path::new("test/cert.pem")) { + Ok(_) => {} + Err(err) => panic!("Unexpected error {:?}", err), + } + assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err()); +}); + +run_test!(verify_callback_load_certs, |method, stream| { + let mut ctx = SslContext::builder(method).unwrap(); + ctx.set_verify_callback(SslVerifyMode::PEER, |_, x509_ctx| { + assert!(x509_ctx.current_cert().is_some()); + true + }); + + assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_ok()); +}); + +run_test!(verify_trusted_get_error_ok, |method, stream| { + let mut ctx = SslContext::builder(method).unwrap(); + ctx.set_verify_callback(SslVerifyMode::PEER, |_, x509_ctx| { + assert!(x509_ctx.error() == X509VerifyResult::OK); + true + }); + + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { + Ok(_) => {} + Err(err) => panic!("Unexpected error {:?}", err), + } + assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_ok()); +}); + +run_test!(verify_trusted_get_error_err, |method, stream| { + let mut ctx = SslContext::builder(method).unwrap(); + ctx.set_verify_callback(SslVerifyMode::PEER, |_, x509_ctx| { + assert_ne!(x509_ctx.error(), X509VerifyResult::OK); + false + }); + + assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err()); +}); + +run_test!(verify_callback_data, |method, stream| { + let mut ctx = SslContext::builder(method).unwrap(); + + // Node id was generated as SHA256 hash of certificate "test/cert.pem" + // in DER format. + // Command: openssl x509 -in test/cert.pem -outform DER | openssl dgst -sha256 + // Please update if "test/cert.pem" will ever change + let node_hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; + let node_id = Vec::from_hex(node_hash_str).unwrap(); + ctx.set_verify_callback(SslVerifyMode::PEER, move |_preverify_ok, x509_ctx| { + let cert = x509_ctx.current_cert(); + match cert { + None => false, + Some(cert) => { + let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); + fingerprint == node_id + } + } + }); + ctx.set_verify_depth(1); + + match Ssl::new(&ctx.build()).unwrap().connect(stream) { + Ok(_) => (), + Err(err) => panic!("Expected success, got {:?}", err), + } +}); + +run_test!(ssl_verify_callback, |method, stream| { + use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; + + static CHECKED: AtomicUsize = ATOMIC_USIZE_INIT; + + let ctx = SslContext::builder(method).unwrap(); + let mut ssl = Ssl::new(&ctx.build()).unwrap(); + + let node_hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; + let node_id = Vec::from_hex(node_hash_str).unwrap(); + ssl.set_verify_callback(SslVerifyMode::PEER, move |_, x509| { + CHECKED.store(1, Ordering::SeqCst); + match x509.current_cert() { + None => false, + Some(cert) => { + let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); + fingerprint == node_id + } + } + }); + + match ssl.connect(stream) { + Ok(_) => (), + Err(err) => panic!("Expected success, got {:?}", err), + } + + assert_eq!(CHECKED.load(Ordering::SeqCst), 1); +}); + +// Make sure every write call translates to a write call to the underlying socket. +#[test] +fn test_write_hits_stream() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + + let guard = thread::spawn(move || { + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let stream = TcpStream::connect(addr).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); + + stream.write_all(b"hello").unwrap(); + stream + }); + + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + let stream = listener.accept().unwrap().0; + let mut stream = Ssl::new(&ctx.build()).unwrap().accept(stream).unwrap(); + + let mut buf = [0; 5]; + assert_eq!(5, stream.read(&mut buf).unwrap()); + assert_eq!(&b"hello"[..], &buf[..]); + guard.join().unwrap(); +} + +#[test] +fn test_set_certificate_and_private_key() { + let key = include_bytes!("../../test/key.pem"); + let key = PKey::private_key_from_pem(key).unwrap(); + let cert = include_bytes!("../../test/cert.pem"); + let cert = X509::from_pem(cert).unwrap(); + + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_private_key(&key).unwrap(); + ctx.set_certificate(&cert).unwrap(); + + assert!(ctx.check_private_key().is_ok()); +} + +run_test!(get_ctx_options, |method, _| { + let ctx = SslContext::builder(method).unwrap(); + ctx.options(); +}); + +run_test!(set_ctx_options, |method, _| { + let mut ctx = SslContext::builder(method).unwrap(); + let opts = ctx.set_options(SslOptions::NO_TICKET); + assert!(opts.contains(SslOptions::NO_TICKET)); +}); + +run_test!(clear_ctx_options, |method, _| { + let mut ctx = SslContext::builder(method).unwrap(); + ctx.set_options(SslOptions::ALL); + let opts = ctx.clear_options(SslOptions::ALL); + assert!(!opts.contains(SslOptions::ALL)); +}); + +#[test] +fn test_write() { + let (_s, stream) = Server::new(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); + stream.write_all("hello".as_bytes()).unwrap(); + stream.flush().unwrap(); + stream.write_all(" there".as_bytes()).unwrap(); + stream.flush().unwrap(); +} + +#[test] +fn zero_length_buffers() { + let (_s, stream) = Server::new(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); + + assert_eq!(stream.write(b"").unwrap(), 0); + assert_eq!(stream.read(&mut []).unwrap(), 0); +} + +run_test!(get_peer_certificate, |method, stream| { + let ctx = SslContext::builder(method).unwrap(); + let stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); + let cert = stream.ssl().peer_certificate().unwrap(); + let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); + let node_hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; + let node_id = Vec::from_hex(node_hash_str).unwrap(); + assert_eq!(node_id, fingerprint) +}); + +#[test] +fn test_read() { + let (_s, tcp) = Server::new(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().connect(tcp).unwrap(); + stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); + stream.flush().unwrap(); + io::copy(&mut stream, &mut io::sink()) + .ok() + .expect("read error"); +} + +#[test] +fn test_pending() { + let (_s, tcp) = Server::new(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx.build()).unwrap().connect(tcp).unwrap(); + stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); + stream.flush().unwrap(); + + // wait for the response and read first byte... + let mut buf = [0u8; 16 * 1024]; + stream.read(&mut buf[..1]).unwrap(); + + let pending = stream.ssl().pending(); + let len = stream.read(&mut buf[1..]).unwrap(); + + assert_eq!(pending, len); + + stream.read(&mut buf[..1]).unwrap(); + + let pending = stream.ssl().pending(); + let len = stream.read(&mut buf[1..]).unwrap(); + assert_eq!(pending, len); +} + +#[test] +fn test_state() { + let (_s, tcp) = Server::new(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let stream = Ssl::new(&ctx.build()).unwrap().connect(tcp).unwrap(); + assert_eq!(stream.ssl().state_string(), "SSLOK "); + assert_eq!( + stream.ssl().state_string_long(), + "SSL negotiation finished successfully" + ); +} + +/// Tests that connecting with the client using ALPN, but the server not does not +/// break the existing connection behavior. +#[test] +#[cfg(any(ossl102, ossl110))] +fn test_connect_with_unilateral_alpn() { + let (_s, stream) = Server::new(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + ctx.set_alpn_protos(b"\x08http/1.1\x08spdy/3.1").unwrap(); + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { + Ok(_) => {} + Err(err) => panic!("Unexpected error {:?}", err), + } + let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { + Ok(stream) => stream, + Err(err) => panic!("Expected success, got {:?}", err), + }; + // Since the socket to which we connected is not configured to use ALPN, + // there should be no selected protocol... + assert!(stream.ssl().selected_alpn_protocol().is_none()); +} + +/// Tests that when both the client as well as the server use ALPN and their +/// lists of supported protocols have an overlap, the correct protocol is chosen. +#[test] +#[cfg(any(ossl102, ossl110))] +fn test_connect_with_alpn_successful_multiple_matching() { + let (_s, stream) = Server::new_alpn(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + ctx.set_alpn_protos(b"\x08http/1.1\x08spdy/3.1").unwrap(); + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { + Ok(_) => {} + Err(err) => panic!("Unexpected error {:?}", err), + } + let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { + Ok(stream) => stream, + Err(err) => panic!("Expected success, got {:?}", err), + }; + // The server prefers "http/1.1", so that is chosen, even though the client + // would prefer "spdy/3.1" + assert_eq!(b"http/1.1", stream.ssl().selected_alpn_protocol().unwrap()); +} + +/// Tests that when both the client as well as the server use ALPN and their +/// lists of supported protocols have an overlap -- with only ONE protocol +/// being valid for both. +#[test] +#[cfg(any(ossl102, ossl110))] +fn test_connect_with_alpn_successful_single_match() { + let (_s, stream) = Server::new_alpn(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + ctx.set_alpn_protos(b"\x08spdy/3.1").unwrap(); + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { + Ok(_) => {} + Err(err) => panic!("Unexpected error {:?}", err), + } + let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { + Ok(stream) => stream, + Err(err) => panic!("Expected success, got {:?}", err), + }; + // The client now only supports one of the server's protocols, so that one + // is used. + assert_eq!(b"spdy/3.1", stream.ssl().selected_alpn_protocol().unwrap()); +} + +/// Tests that when the `SslStream` is created as a server stream, the protocols +/// are correctly advertised to the client. +#[test] +#[cfg(any(ossl102, ossl110))] +fn test_alpn_server_advertise_multiple() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let localhost = listener.local_addr().unwrap(); + // We create a different context instance for the server... + let listener_ctx = { + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_alpn_select_callback(|_, client| { + ssl::select_next_proto(b"\x08http/1.1\x08spdy/3.1", client).ok_or(ssl::AlpnError::NOACK) + }); + assert!( + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .is_ok() + ); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + ctx.build() + }; + // Have the listener wait on the connection in a different thread. + thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + Ssl::new(&listener_ctx).unwrap().accept(stream).unwrap(); + }); + + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + ctx.set_alpn_protos(b"\x08spdy/3.1").unwrap(); + match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { + Ok(_) => {} + Err(err) => panic!("Unexpected error {:?}", err), + } + // Now connect to the socket and make sure the protocol negotiation works... + let stream = TcpStream::connect(localhost).unwrap(); + let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { + Ok(stream) => stream, + Err(err) => panic!("Expected success, got {:?}", err), + }; + // SPDY is selected since that's the only thing the client supports. + assert_eq!(b"spdy/3.1", stream.ssl().selected_alpn_protocol().unwrap()); +} + +#[test] +#[cfg(any(ossl110))] +fn test_alpn_server_select_none_fatal() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let localhost = listener.local_addr().unwrap(); + // We create a different context instance for the server... + let listener_ctx = { + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_alpn_select_callback(|_, client| { + ssl::select_next_proto(b"\x08http/1.1\x08spdy/3.1", client) + .ok_or(ssl::AlpnError::ALERT_FATAL) + }); + assert!( + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .is_ok() + ); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + ctx.build() + }; + // Have the listener wait on the connection in a different thread. + thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + Ssl::new(&listener_ctx).unwrap().accept(stream).unwrap_err(); + }); + + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + ctx.set_alpn_protos(b"\x06http/2").unwrap(); + ctx.set_ca_file(&Path::new("test/root-ca.pem")).unwrap(); + let stream = TcpStream::connect(localhost).unwrap(); + Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap_err(); +} + +#[test] +#[cfg(any(ossl102, ossl110))] +fn test_alpn_server_select_none() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let localhost = listener.local_addr().unwrap(); + // We create a different context instance for the server... + let listener_ctx = { + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_alpn_select_callback(|_, client| { + ssl::select_next_proto(b"\x08http/1.1\x08spdy/3.1", client).ok_or(ssl::AlpnError::NOACK) + }); + assert!( + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .is_ok() + ); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + ctx.build() + }; + // Have the listener wait on the connection in a different thread. + thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + Ssl::new(&listener_ctx).unwrap().accept(stream).unwrap(); + }); + + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + ctx.set_alpn_protos(b"\x06http/2").unwrap(); + ctx.set_ca_file(&Path::new("test/root-ca.pem")).unwrap(); + // Now connect to the socket and make sure the protocol negotiation works... + let stream = TcpStream::connect(localhost).unwrap(); + let stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); + + // Since the protocols from the server and client don't overlap at all, no protocol is selected + assert_eq!(None, stream.ssl().selected_alpn_protocol()); +} + +#[test] +#[should_panic(expected = "blammo")] +fn write_panic() { + struct ExplodingStream(TcpStream); + + impl Read for ExplodingStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.0.read(buf) + } + } + + impl Write for ExplodingStream { + fn write(&mut self, _: &[u8]) -> io::Result { + panic!("blammo"); + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } + } + + let (_s, stream) = Server::new(); + let stream = ExplodingStream(stream); + + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let _ = Ssl::new(&ctx.build()).unwrap().connect(stream); +} + +#[test] +#[should_panic(expected = "blammo")] +fn read_panic() { + struct ExplodingStream(TcpStream); + + impl Read for ExplodingStream { + fn read(&mut self, _: &mut [u8]) -> io::Result { + panic!("blammo"); + } + } + + impl Write for ExplodingStream { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } + } + + let (_s, stream) = Server::new(); + let stream = ExplodingStream(stream); + + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let _ = Ssl::new(&ctx.build()).unwrap().connect(stream); +} + +#[test] +#[should_panic(expected = "blammo")] +fn flush_panic() { + struct ExplodingStream(TcpStream); + + impl Read for ExplodingStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.0.read(buf) + } + } + + impl Write for ExplodingStream { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + panic!("blammo"); + } + } + + let (_s, stream) = Server::new(); + let stream = ExplodingStream(stream); + + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let mut stream = Ssl::new(&ctx.build()) + .unwrap() + .connect(stream) + .ok() + .unwrap(); + let _ = stream.flush(); +} + +#[test] +fn refcount_ssl_context() { + let mut ssl = { + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ssl::Ssl::new(&ctx.build()).unwrap() + }; + + { + let new_ctx_a = SslContext::builder(SslMethod::tls()).unwrap().build(); + let _new_ctx_b = ssl.set_ssl_context(&new_ctx_a); + } +} + +#[test] +fn default_verify_paths() { + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_default_verify_paths().unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + let ctx = ctx.build(); + let s = TcpStream::connect("google.com:443").unwrap(); + let mut ssl = Ssl::new(&ctx).unwrap(); + ssl.set_hostname("google.com").unwrap(); + let mut socket = ssl.connect(s).unwrap(); + + socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); + let mut result = vec![]; + socket.read_to_end(&mut result).unwrap(); + + println!("{}", String::from_utf8_lossy(&result)); + assert!(result.starts_with(b"HTTP/1.0")); + assert!(result.ends_with(b"\r\n") || result.ends_with(b"")); +} + +#[test] +fn add_extra_chain_cert() { + let cert = include_bytes!("../../test/cert.pem"); + let cert = X509::from_pem(cert).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.add_extra_chain_cert(cert).unwrap(); +} + +#[test] +#[cfg(any(ossl102, ossl110))] +fn verify_valid_hostname() { + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_default_verify_paths().unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + + let mut ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.param_mut() + .set_hostflags(X509CheckFlags::NO_PARTIAL_WILDCARDS); + ssl.param_mut().set_host("google.com").unwrap(); + ssl.set_hostname("google.com").unwrap(); + + let s = TcpStream::connect("google.com:443").unwrap(); + let mut socket = ssl.connect(s).unwrap(); + + socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); + let mut result = vec![]; + socket.read_to_end(&mut result).unwrap(); + + println!("{}", String::from_utf8_lossy(&result)); + assert!(result.starts_with(b"HTTP/1.0")); + assert!(result.ends_with(b"\r\n") || result.ends_with(b"")); +} + +#[test] +#[cfg(any(ossl102, ossl110))] +fn verify_invalid_hostname() { + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_default_verify_paths().unwrap(); + ctx.set_verify(SslVerifyMode::PEER); + + let mut ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.param_mut() + .set_hostflags(X509CheckFlags::NO_PARTIAL_WILDCARDS); + ssl.param_mut().set_host("foobar.com").unwrap(); + + let s = TcpStream::connect("google.com:443").unwrap(); + assert!(ssl.connect(s).is_err()); +} + +#[test] +fn connector_valid_hostname() { + let connector = SslConnector::builder(SslMethod::tls()).unwrap().build(); + + let s = TcpStream::connect("google.com:443").unwrap(); + let mut socket = connector.connect("google.com", s).unwrap(); + + socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); + let mut result = vec![]; + socket.read_to_end(&mut result).unwrap(); + + println!("{}", String::from_utf8_lossy(&result)); + assert!(result.starts_with(b"HTTP/1.0")); + assert!(result.ends_with(b"\r\n") || result.ends_with(b"")); +} + +#[test] +fn connector_invalid_hostname() { + let connector = SslConnector::builder(SslMethod::tls()).unwrap().build(); + + let s = TcpStream::connect("google.com:443").unwrap(); + assert!(connector.connect("foobar.com", s).is_err()); +} + +#[test] +fn connector_invalid_no_hostname_verification() { + let connector = SslConnector::builder(SslMethod::tls()).unwrap().build(); + + let s = TcpStream::connect("google.com:443").unwrap(); + connector + .configure() + .unwrap() + .verify_hostname(false) + .connect("foobar.com", s) + .unwrap(); +} + +#[test] +fn connector_no_hostname_still_verifies() { + let (_s, tcp) = Server::new(); + + let connector = SslConnector::builder(SslMethod::tls()).unwrap().build(); + + assert!( + connector + .configure() + .unwrap() + .verify_hostname(false) + .connect("fizzbuzz.com", tcp) + .is_err() + ); +} + +#[test] +fn connector_no_hostname_can_disable_verify() { + let (_s, tcp) = Server::new(); + + let mut connector = SslConnector::builder(SslMethod::tls()).unwrap(); + connector.set_verify(SslVerifyMode::NONE); + let connector = connector.build(); + + connector + .configure() + .unwrap() + .verify_hostname(false) + .connect("foobar.com", tcp) + .unwrap(); +} + +#[test] +fn connector_client_server_mozilla_intermediate() { + let listener = TcpListener::bind("127.0.0.1:1234").unwrap(); + let port = listener.local_addr().unwrap().port(); + + let t = thread::spawn(move || { + let key = PKey::private_key_from_pem(KEY).unwrap(); + let cert = X509::from_pem(CERT).unwrap(); + let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); + acceptor.set_private_key(&key).unwrap(); + acceptor.set_certificate(&cert).unwrap(); + let acceptor = acceptor.build(); + let stream = listener.accept().unwrap().0; + let mut stream = acceptor.accept(stream).unwrap(); + + stream.write_all(b"hello").unwrap(); + }); + + let mut connector = SslConnector::builder(SslMethod::tls()).unwrap(); + connector.set_ca_file("test/root-ca.pem").unwrap(); + let connector = connector.build(); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut stream = connector.connect("foobar.com", stream).unwrap(); + + let mut buf = [0; 5]; + stream.read_exact(&mut buf).unwrap(); + assert_eq!(b"hello", &buf); + + t.join().unwrap(); +} + +#[test] +fn connector_client_server_mozilla_modern() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + let t = thread::spawn(move || { + let key = PKey::private_key_from_pem(KEY).unwrap(); + let cert = X509::from_pem(CERT).unwrap(); + let mut acceptor = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); + acceptor.set_private_key(&key).unwrap(); + acceptor.set_certificate(&cert).unwrap(); + let acceptor = acceptor.build(); + let stream = listener.accept().unwrap().0; + let mut stream = acceptor.accept(stream).unwrap(); + + stream.write_all(b"hello").unwrap(); + }); + + let mut connector = SslConnector::builder(SslMethod::tls()).unwrap(); + connector.set_ca_file("test/root-ca.pem").unwrap(); + let connector = connector.build(); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut stream = connector.connect("foobar.com", stream).unwrap(); + + let mut buf = [0; 5]; + stream.read_exact(&mut buf).unwrap(); + assert_eq!(b"hello", &buf); + + t.join().unwrap(); +} + +#[test] +fn shutdown() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + thread::spawn(move || { + let stream = listener.accept().unwrap().0; + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + let mut stream = ssl.accept(stream).unwrap(); + + stream.write_all(b"hello").unwrap(); + let mut buf = [0; 1]; + assert_eq!(stream.read(&mut buf).unwrap(), 0); + assert_eq!(stream.shutdown().unwrap(), ShutdownResult::Received); + }); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + let mut stream = ssl.connect(stream).unwrap(); + + let mut buf = [0; 5]; + stream.read_exact(&mut buf).unwrap(); + assert_eq!(b"hello", &buf); + + assert_eq!(stream.shutdown().unwrap(), ShutdownResult::Sent); + assert_eq!(stream.shutdown().unwrap(), ShutdownResult::Received); +} + +#[test] +fn client_ca_list() { + let names = X509Name::load_client_ca_file("test/root-ca.pem").unwrap(); + assert_eq!(names.len(), 1); + + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_client_ca_list(names); +} + +#[test] +fn cert_store() { + let (_s, tcp) = Server::new(); + + let cert = X509::from_pem(ROOT_CERT).unwrap(); + + let mut ctx = SslConnector::builder(SslMethod::tls()).unwrap(); + ctx.cert_store_mut().add_cert(cert).unwrap(); + let ctx = ctx.build(); + + ctx.connect("foobar.com", tcp).unwrap(); +} + +#[test] +fn tmp_dh_callback() { + static CALLED_BACK: AtomicBool = ATOMIC_BOOL_INIT; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + thread::spawn(move || { + let stream = listener.accept().unwrap().0; + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_tmp_dh_callback(|_, _, _| { + CALLED_BACK.store(true, Ordering::SeqCst); + let dh = include_bytes!("../../test/dhparams.pem"); + Dh::params_from_pem(dh) + }); + let ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.accept(stream).unwrap(); + }); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + // TLS 1.3 has no DH suites, and openssl isn't happy if the max version has no suites :( + #[cfg(ossl111)] + { + ctx.set_options(super::SslOptions { + bits: ::ffi::SSL_OP_NO_TLSv1_3, + }); + } + ctx.set_cipher_list("EDH").unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.connect(stream).unwrap(); + + assert!(CALLED_BACK.load(Ordering::SeqCst)); +} + +#[test] +#[cfg(any(all(ossl101, not(libressl)), ossl102))] +fn tmp_ecdh_callback() { + use ec::EcKey; + use nid::Nid; + + static CALLED_BACK: AtomicBool = ATOMIC_BOOL_INIT; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + thread::spawn(move || { + let stream = listener.accept().unwrap().0; + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_tmp_ecdh_callback(|_, _, _| { + CALLED_BACK.store(true, Ordering::SeqCst); + EcKey::from_curve_name(Nid::X9_62_PRIME256V1) + }); + let ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.accept(stream).unwrap(); + }); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_cipher_list("ECDH").unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.connect(stream).unwrap(); + + assert!(CALLED_BACK.load(Ordering::SeqCst)); +} + +#[test] +fn tmp_dh_callback_ssl() { + static CALLED_BACK: AtomicBool = ATOMIC_BOOL_INIT; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + thread::spawn(move || { + let stream = listener.accept().unwrap().0; + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + let mut ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.set_tmp_dh_callback(|_, _, _| { + CALLED_BACK.store(true, Ordering::SeqCst); + let dh = include_bytes!("../../test/dhparams.pem"); + Dh::params_from_pem(dh) + }); + ssl.accept(stream).unwrap(); + }); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + // TLS 1.3 has no DH suites, and openssl isn't happy if the max version has no suites :( + #[cfg(ossl111)] + { + ctx.set_options(super::SslOptions { + bits: ::ffi::SSL_OP_NO_TLSv1_3, + }); + } + ctx.set_cipher_list("EDH").unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.connect(stream).unwrap(); + + assert!(CALLED_BACK.load(Ordering::SeqCst)); +} + +#[test] +#[cfg(any(all(ossl101, not(libressl)), ossl102))] +fn tmp_ecdh_callback_ssl() { + use ec::EcKey; + use nid::Nid; + + static CALLED_BACK: AtomicBool = ATOMIC_BOOL_INIT; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + thread::spawn(move || { + let stream = listener.accept().unwrap().0; + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + let mut ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.set_tmp_ecdh_callback(|_, _, _| { + CALLED_BACK.store(true, Ordering::SeqCst); + EcKey::from_curve_name(Nid::X9_62_PRIME256V1) + }); + ssl.accept(stream).unwrap(); + }); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_cipher_list("ECDH").unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.connect(stream).unwrap(); + + assert!(CALLED_BACK.load(Ordering::SeqCst)); +} + +#[test] +fn idle_session() { + let ctx = SslContext::builder(SslMethod::tls()).unwrap().build(); + let ssl = Ssl::new(&ctx).unwrap(); + assert!(ssl.session().is_none()); +} + +#[test] +fn active_session() { + let connector = SslConnector::builder(SslMethod::tls()).unwrap().build(); + + let s = TcpStream::connect("google.com:443").unwrap(); + let socket = connector.connect("google.com", s).unwrap(); + let session = socket.ssl().session().unwrap(); + let len = session.master_key_len(); + let mut buf = vec![0; len - 1]; + let copied = session.master_key(&mut buf); + assert_eq!(copied, buf.len()); + let mut buf = vec![0; len + 1]; + let copied = session.master_key(&mut buf); + assert_eq!(copied, len); +} + +#[test] +fn status_callbacks() { + static CALLED_BACK_SERVER: AtomicBool = ATOMIC_BOOL_INIT; + static CALLED_BACK_CLIENT: AtomicBool = ATOMIC_BOOL_INIT; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + let guard = thread::spawn(move || { + let stream = listener.accept().unwrap().0; + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_status_callback(|ssl| { + CALLED_BACK_SERVER.store(true, Ordering::SeqCst); + let response = OcspResponse::create(OcspResponseStatus::UNAUTHORIZED, None).unwrap(); + let response = response.to_der().unwrap(); + ssl.set_ocsp_status(&response).unwrap(); + Ok(true) + }).unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.accept(stream).unwrap(); + }); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_status_callback(|ssl| { + CALLED_BACK_CLIENT.store(true, Ordering::SeqCst); + let response = OcspResponse::from_der(ssl.ocsp_status().unwrap()).unwrap(); + assert_eq!(response.status(), OcspResponseStatus::UNAUTHORIZED); + Ok(true) + }).unwrap(); + let mut ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.set_status_type(StatusType::OCSP).unwrap(); + ssl.connect(stream).unwrap(); + + assert!(CALLED_BACK_SERVER.load(Ordering::SeqCst)); + assert!(CALLED_BACK_CLIENT.load(Ordering::SeqCst)); + + guard.join().unwrap(); +} + +#[test] +fn new_session_callback() { + static CALLED_BACK: AtomicBool = ATOMIC_BOOL_INIT; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + + thread::spawn(move || { + let stream = listener.accept().unwrap().0; + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_session_id_context(b"foo").unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + let mut stream = ssl.accept(stream).unwrap(); + stream.write_all(&[0]).unwrap(); + }); + + let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_session_cache_mode(SslSessionCacheMode::CLIENT | SslSessionCacheMode::NO_INTERNAL); + ctx.set_new_session_callback(|_, _| CALLED_BACK.store(true, Ordering::SeqCst)); + let ssl = Ssl::new(&ctx.build()).unwrap(); + let mut stream = ssl.connect(stream).unwrap(); + // read 1 byte to make sure the session is received for TLSv1.3 + let mut buf = [0]; + stream.read_exact(&mut buf).unwrap(); + + assert!(CALLED_BACK.load(Ordering::SeqCst)); +} + +#[test] +fn keying_export() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + + let label = "EXPERIMENTAL test"; + let context = b"my context"; + + let guard = thread::spawn(move || { + let stream = listener.accept().unwrap().0; + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + let stream = ssl.accept(stream).unwrap(); + + let mut buf = [0; 32]; + stream + .ssl() + .export_keying_material(&mut buf, label, Some(context)) + .unwrap(); + buf + }); + + let stream = TcpStream::connect(addr).unwrap(); + let ctx = SslContext::builder(SslMethod::tls()).unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + let stream = ssl.connect(stream).unwrap(); + + let mut buf = [1; 32]; + stream + .ssl() + .export_keying_material(&mut buf, label, Some(context)) + .unwrap(); + + let buf2 = guard.join().unwrap(); + + assert_eq!(buf, buf2); +} + +#[test] +#[cfg(any(ossl110))] +fn no_version_overlap() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + + let guard = thread::spawn(move || { + let stream = listener.accept().unwrap().0; + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_max_proto_version(Some(SslVersion::TLS1_1)).unwrap(); + assert_eq!(ctx.min_proto_version(), None); + assert_eq!(ctx.max_proto_version(), Some(SslVersion::TLS1_1)); + let ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.accept(stream).unwrap_err(); + }); + + let stream = TcpStream::connect(addr).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_min_proto_version(Some(SslVersion::TLS1_2)).unwrap(); + assert_eq!(ctx.min_proto_version(), Some(SslVersion::TLS1_2)); + assert_eq!(ctx.max_proto_version(), None); + let ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.connect(stream).unwrap_err(); + + guard.join().unwrap(); +} + +#[test] +#[cfg(ossl111)] +fn custom_extensions() { + static FOUND_EXTENSION: AtomicBool = ATOMIC_BOOL_INIT; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + + let guard = thread::spawn(move || { + let stream = listener.accept().unwrap().0; + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + ctx.add_custom_ext( + 12345, + ssl::ExtensionContext::CLIENT_HELLO, + |_, _, _| -> Result, _> { unreachable!() }, + |_, _, data, _| { + FOUND_EXTENSION.store(data == b"hello", Ordering::SeqCst); + Ok(()) + }, + ).unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.accept(stream).unwrap(); + }); + + let stream = TcpStream::connect(addr).unwrap(); + let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); + ctx.add_custom_ext( + 12345, + ssl::ExtensionContext::CLIENT_HELLO, + |_, _, _| Ok(Some(b"hello")), + |_, _, _, _| unreachable!(), + ).unwrap(); + let ssl = Ssl::new(&ctx.build()).unwrap(); + ssl.connect(stream).unwrap(); + + guard.join().unwrap(); + assert!(FOUND_EXTENSION.load(Ordering::SeqCst)); +} + +fn _check_kinds() { + fn is_send() {} + fn is_sync() {} + + is_send::>(); + is_sync::>(); +} + +#[derive(Debug)] +struct MemoryStream { + incoming: io::Cursor>, + outgoing: Vec, +} + +impl MemoryStream { + pub fn new() -> Self { Self { + incoming: io::Cursor::new(Vec::new()), + outgoing: Vec::new(), + }} + + pub fn extend_incoming(&mut self, data: &[u8]) { + self.incoming.get_mut().extend_from_slice(data); + } + + pub fn take_outgoing(&mut self) -> Outgoing { Outgoing(&mut self.outgoing) } +} + +impl Read for MemoryStream { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let n = self.incoming.read(buf)?; + if self.incoming.position() == self.incoming.get_ref().len() as u64 { + self.incoming.set_position(0); + self.incoming.get_mut().clear(); + } + if n == 0 { + return Err(io::Error::new(io::ErrorKind::WouldBlock, "no data available")); + } + Ok(n) + } +} + +impl Write for MemoryStream { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.outgoing.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { Ok(()) } +} + +pub struct Outgoing<'a>(&'a mut Vec); + +impl<'a> Drop for Outgoing<'a> { + fn drop(&mut self) { + self.0.clear(); + } +} + +impl<'a> ::std::ops::Deref for Outgoing<'a> { + type Target = [u8]; + fn deref(&self) -> &[u8] { &self.0 } +} + +impl<'a> AsRef<[u8]> for Outgoing<'a> { + fn as_ref(&self) -> &[u8] { &self.0 } +} + +fn send(from: &mut MemoryStream, to: &mut MemoryStream) { + to.extend_incoming(&from.take_outgoing()); +} + +#[test] +#[cfg(ossl111)] +fn stateless() { + use super::SslOptions; + + fn hs(stream: Result, HandshakeError>) -> Result, MidHandshakeSslStream> { + match stream { + Ok(stream) => Ok(stream), + Err(HandshakeError::WouldBlock(stream)) => Err(stream), + Err(e) => panic!("unexpected error: {:?}", e), + } + } + + // + // Setup + // + + let mut client_ctx = SslContext::builder(SslMethod::tls()).unwrap(); + client_ctx.clear_options(SslOptions::ENABLE_MIDDLEBOX_COMPAT); + let client_stream = Ssl::new(&client_ctx.build()).unwrap(); + + let mut server_ctx = SslContext::builder(SslMethod::tls()).unwrap(); + server_ctx.set_certificate_file(&Path::new("test/cert.pem"), SslFiletype::PEM) + .unwrap(); + server_ctx.set_private_key_file(&Path::new("test/key.pem"), SslFiletype::PEM) + .unwrap(); + const COOKIE: &[u8] = b"chocolate chip"; + server_ctx.set_stateless_cookie_generate_cb(|_tls, buf| { buf[0..COOKIE.len()].copy_from_slice(COOKIE); Ok(COOKIE.len()) }); + server_ctx.set_stateless_cookie_verify_cb(|_tls, buf| buf == COOKIE); + let mut server_stream = ssl::SslStreamBuilder::new(Ssl::new(&server_ctx.build()).unwrap(), MemoryStream::new()); + + // + // Handshake + // + + // Initial ClientHello + let mut client_stream = hs(client_stream.connect(MemoryStream::new())).unwrap_err(); + send(client_stream.get_mut(), server_stream.get_mut()); + // HelloRetryRequest + assert!(!server_stream.stateless().unwrap()); + send(server_stream.get_mut(), client_stream.get_mut()); + // Second ClientHello + let mut client_stream = hs(client_stream.handshake()).unwrap_err(); + send(client_stream.get_mut(), server_stream.get_mut()); + // ServerHello + assert!(server_stream.stateless().unwrap()); + let mut server_stream = hs(server_stream.accept()).unwrap_err(); + send(server_stream.get_mut(), client_stream.get_mut()); + // Finished + let mut client_stream = hs(client_stream.handshake()).unwrap(); + send(client_stream.get_mut(), server_stream.get_mut()); + hs(server_stream.handshake()).unwrap(); +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/stack.rs cargo-0.26.0/vendor/openssl-0.10.6/src/stack.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/stack.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/stack.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,360 @@ +use foreign_types::{ForeignTypeRef, ForeignType, Opaque}; +use libc::c_int; +use std::borrow::Borrow; +use std::convert::AsRef; +use std::iter; +use std::marker::PhantomData; +use std::mem; +use ffi; + +use {cvt, cvt_p}; +use error::ErrorStack; +use std::ops::{Deref, DerefMut, Index, IndexMut}; + +#[cfg(ossl10x)] +use ffi::{sk_pop as OPENSSL_sk_pop, sk_free as OPENSSL_sk_free, sk_num as OPENSSL_sk_num, + sk_value as OPENSSL_sk_value, _STACK as OPENSSL_STACK, + sk_new_null as OPENSSL_sk_new_null, sk_push as OPENSSL_sk_push}; +#[cfg(ossl110)] +use ffi::{OPENSSL_sk_pop, OPENSSL_sk_free, OPENSSL_sk_num, OPENSSL_sk_value, OPENSSL_STACK, + OPENSSL_sk_new_null, OPENSSL_sk_push}; + +/// Trait implemented by types which can be placed in a stack. +/// +/// It should not be implemented for any type outside of this crate. +pub trait Stackable: ForeignType { + /// The C stack type for this element. + /// + /// Generally called `stack_st_{ELEMENT_TYPE}`, normally hidden by the + /// `STACK_OF(ELEMENT_TYPE)` macro in the OpenSSL API. + type StackType; +} + +/// An owned stack of `T`. +pub struct Stack(*mut T::StackType); + +impl Stack { + pub fn new() -> Result, ErrorStack> { + unsafe { + ffi::init(); + let ptr = cvt_p(OPENSSL_sk_new_null())?; + Ok(Stack(ptr as *mut _)) + } + } +} + +impl Drop for Stack { + fn drop(&mut self) { + unsafe { + while let Some(_) = self.pop() {} + OPENSSL_sk_free(self.0 as *mut _); + } + } +} + +impl iter::IntoIterator for Stack { + type IntoIter = IntoIter; + type Item = T; + + fn into_iter(self) -> IntoIter { + let it = IntoIter { + stack: self.0, + idx: 0, + }; + mem::forget(self); + it + } +} + +impl AsRef> for Stack { + fn as_ref(&self) -> &StackRef { + &*self + } +} + +impl Borrow> for Stack { + fn borrow(&self) -> &StackRef { + &*self + } +} + +impl ForeignType for Stack { + type CType = T::StackType; + type Ref = StackRef; + + #[inline] + unsafe fn from_ptr(ptr: *mut T::StackType) -> Stack { + assert!( + !ptr.is_null(), + "Must not instantiate a Stack from a null-ptr - use Stack::new() in \ + that case" + ); + Stack(ptr) + } + + #[inline] + fn as_ptr(&self) -> *mut T::StackType { + self.0 + } +} + +impl Deref for Stack { + type Target = StackRef; + + fn deref(&self) -> &StackRef { + unsafe { StackRef::from_ptr(self.0) } + } +} + +impl DerefMut for Stack { + fn deref_mut(&mut self) -> &mut StackRef { + unsafe { StackRef::from_ptr_mut(self.0) } + } +} + +pub struct IntoIter { + stack: *mut T::StackType, + idx: c_int, +} + +impl IntoIter { + fn stack_len(&self) -> c_int { + unsafe { OPENSSL_sk_num(self.stack as *mut _) } + } +} + +impl Drop for IntoIter { + fn drop(&mut self) { + unsafe { + while let Some(_) = self.next() {} + OPENSSL_sk_free(self.stack as *mut _); + } + } +} + +impl Iterator for IntoIter { + type Item = T; + + fn next(&mut self) -> Option { + unsafe { + if self.idx == self.stack_len() { + None + } else { + let ptr = OPENSSL_sk_value(self.stack as *mut _, self.idx); + self.idx += 1; + Some(T::from_ptr(ptr as *mut _)) + } + } + } + + fn size_hint(&self) -> (usize, Option) { + let size = (self.stack_len() - self.idx) as usize; + (size, Some(size)) + } +} + +impl ExactSizeIterator for IntoIter {} + +pub struct StackRef(Opaque, PhantomData); + +impl ForeignTypeRef for StackRef { + type CType = T::StackType; +} + +impl StackRef { + fn as_stack(&self) -> *mut OPENSSL_STACK { + self.as_ptr() as *mut _ + } + + /// Returns the number of items in the stack + pub fn len(&self) -> usize { + unsafe { OPENSSL_sk_num(self.as_stack()) as usize } + } + + pub fn iter(&self) -> Iter { + // Unfortunately we can't simply convert the stack into a + // slice and use that because OpenSSL 1.1.0 doesn't directly + // expose the stack data (we have to use `OPENSSL_sk_value` + // instead). We have to rewrite the entire iteration framework + // instead. + + Iter { + stack: self, + pos: 0, + } + } + + pub fn iter_mut(&mut self) -> IterMut { + IterMut { + stack: self, + pos: 0, + } + } + + /// Returns a reference to the element at the given index in the + /// stack or `None` if the index is out of bounds + pub fn get(&self, idx: usize) -> Option<&T::Ref> { + unsafe { + if idx >= self.len() { + return None; + } + + Some(T::Ref::from_ptr(self._get(idx))) + } + } + + /// Returns a mutable reference to the element at the given index in the + /// stack or `None` if the index is out of bounds + pub fn get_mut(&mut self, idx: usize) -> Option<&mut T::Ref> { + unsafe { + if idx >= self.len() { + return None; + } + + Some(T::Ref::from_ptr_mut(self._get(idx))) + } + } + + /// Pushes a value onto the top of the stack. + pub fn push(&mut self, data: T) -> Result<(), ErrorStack> { + unsafe { + cvt( + OPENSSL_sk_push(self.as_stack(), data.as_ptr() as *mut _), + )?; + mem::forget(data); + Ok(()) + } + } + + /// Removes the last element from the stack and returns it. + pub fn pop(&mut self) -> Option { + unsafe { + let ptr = OPENSSL_sk_pop(self.as_stack()); + if ptr.is_null() { + None + } else { + Some(T::from_ptr(ptr as *mut _)) + } + } + } + + unsafe fn _get(&self, idx: usize) -> *mut T::CType { + OPENSSL_sk_value(self.as_stack(), idx as c_int) as *mut _ + } +} + +impl Index for StackRef { + type Output = T::Ref; + + fn index(&self, index: usize) -> &T::Ref { + self.get(index).unwrap() + } +} + +impl IndexMut for StackRef { + fn index_mut(&mut self, index: usize) -> &mut T::Ref { + self.get_mut(index).unwrap() + } +} + +impl<'a, T: Stackable> iter::IntoIterator for &'a StackRef { + type Item = &'a T::Ref; + type IntoIter = Iter<'a, T>; + + fn into_iter(self) -> Iter<'a, T> { + self.iter() + } +} + +impl<'a, T: Stackable> iter::IntoIterator for &'a mut StackRef { + type Item = &'a mut T::Ref; + type IntoIter = IterMut<'a, T>; + + fn into_iter(self) -> IterMut<'a, T> { + self.iter_mut() + } +} + +impl<'a, T: Stackable> iter::IntoIterator for &'a Stack { + type Item = &'a T::Ref; + type IntoIter = Iter<'a, T>; + + fn into_iter(self) -> Iter<'a, T> { + self.iter() + } +} + +impl<'a, T: Stackable> iter::IntoIterator for &'a mut Stack { + type Item = &'a mut T::Ref; + type IntoIter = IterMut<'a, T>; + + fn into_iter(self) -> IterMut<'a, T> { + self.iter_mut() + } +} + +/// An iterator over the stack's contents. +pub struct Iter<'a, T: Stackable> +where + T: 'a, +{ + stack: &'a StackRef, + pos: usize, +} + +impl<'a, T: Stackable> iter::Iterator for Iter<'a, T> { + type Item = &'a T::Ref; + + fn next(&mut self) -> Option<&'a T::Ref> { + let n = self.stack.get(self.pos); + + if n.is_some() { + self.pos += 1; + } + + n + } + + fn size_hint(&self) -> (usize, Option) { + let rem = self.stack.len() - self.pos; + + (rem, Some(rem)) + } +} + +impl<'a, T: Stackable> iter::ExactSizeIterator for Iter<'a, T> {} + +/// A mutable iterator over the stack's contents. +pub struct IterMut<'a, T: Stackable + 'a> { + stack: &'a mut StackRef, + pos: usize, +} + +impl<'a, T: Stackable> iter::Iterator for IterMut<'a, T> { + type Item = &'a mut T::Ref; + + fn next(&mut self) -> Option<&'a mut T::Ref> { + if self.pos >= self.stack.len() { + None + } else { + // Rust won't allow us to get a mutable reference into + // `stack` in this situation since it can't statically + // guarantee that we won't return several references to + // the same object, so we have to use unsafe code for + // mutable iterators. + let n = unsafe { Some(T::Ref::from_ptr_mut(self.stack._get(self.pos))) }; + + self.pos += 1; + + n + } + } + + fn size_hint(&self) -> (usize, Option) { + let rem = self.stack.len() - self.pos; + + (rem, Some(rem)) + } +} + +impl<'a, T: Stackable> iter::ExactSizeIterator for IterMut<'a, T> {} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/string.rs cargo-0.26.0/vendor/openssl-0.10.6/src/string.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/string.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/string.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,70 @@ +use ffi; +use foreign_types::ForeignTypeRef; +use libc::{c_char, c_void}; +use std::fmt; +use std::ffi::CStr; +use std::ops::Deref; +use std::str; + +use stack::Stackable; + +foreign_type_and_impl_send_sync! { + type CType = c_char; + fn drop = free; + + pub struct OpensslString; + pub struct OpensslStringRef; +} + +impl fmt::Display for OpensslString { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +impl fmt::Debug for OpensslString { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +impl Stackable for OpensslString { + type StackType = ffi::stack_st_OPENSSL_STRING; +} + +impl Deref for OpensslStringRef { + type Target = str; + + fn deref(&self) -> &str { + unsafe { + let slice = CStr::from_ptr(self.as_ptr()).to_bytes(); + str::from_utf8_unchecked(slice) + } + } +} + +impl fmt::Display for OpensslStringRef { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +impl fmt::Debug for OpensslStringRef { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +#[cfg(not(ossl110))] +unsafe fn free(buf: *mut c_char) { + ::ffi::CRYPTO_free(buf as *mut c_void); +} + +#[cfg(ossl110)] +unsafe fn free(buf: *mut c_char) { + ::ffi::CRYPTO_free( + buf as *mut c_void, + concat!(file!(), "\0").as_ptr() as *const c_char, + line!() as ::libc::c_int, + ); +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/symm.rs cargo-0.26.0/vendor/openssl-0.10.6/src/symm.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/symm.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/symm.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1262 @@ +//! High level interface to certain symmetric ciphers. +//! +//! # Examples +//! +//! Encrypt data in AES128 CBC mode +//! +//! ``` +//! use openssl::symm::{encrypt, Cipher}; +//! +//! let cipher = Cipher::aes_128_cbc(); +//! let data = b"Some Crypto Text"; +//! let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"; +//! let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07"; +//! let ciphertext = encrypt( +//! cipher, +//! key, +//! Some(iv), +//! data).unwrap(); +//! +//! assert_eq!( +//! b"\xB4\xB9\xE7\x30\xD6\xD6\xF7\xDE\x77\x3F\x1C\xFF\xB3\x3E\x44\x5A\x91\xD7\x27\x62\x87\x4D\ +//! \xFB\x3C\x5E\xC4\x59\x72\x4A\xF4\x7C\xA1", +//! &ciphertext[..]); +//! ``` +//! +//! Encrypting an assymetric key with a symmetric cipher +//! +//! ``` +//! use openssl::rsa::{Padding, Rsa}; +//! use openssl::symm::Cipher; +//! +//! // Generate keypair and encrypt private key: +//! let keypair = Rsa::generate(2048).unwrap(); +//! let cipher = Cipher::aes_256_cbc(); +//! let pubkey_pem = keypair.public_key_to_pem_pkcs1().unwrap(); +//! let privkey_pem = keypair.private_key_to_pem_passphrase(cipher, b"Rust").unwrap(); +//! // pubkey_pem and privkey_pem could be written to file here. +//! +//! // Load private and public key from string: +//! let pubkey = Rsa::public_key_from_pem_pkcs1(&pubkey_pem).unwrap(); +//! let privkey = Rsa::private_key_from_pem_passphrase(&privkey_pem, b"Rust").unwrap(); +//! +//! // Use the asymmetric keys to encrypt and decrypt a short message: +//! let msg = b"Foo bar"; +//! let mut encrypted = vec![0; pubkey.size() as usize]; +//! let mut decrypted = vec![0; privkey.size() as usize]; +//! let len = pubkey.public_encrypt(msg, &mut encrypted, Padding::PKCS1).unwrap(); +//! assert!(len > msg.len()); +//! let len = privkey.private_decrypt(&encrypted, &mut decrypted, Padding::PKCS1).unwrap(); +//! let output_string = String::from_utf8(decrypted[..len].to_vec()).unwrap(); +//! assert_eq!("Foo bar", output_string); +//! println!("Decrypted: '{}'", output_string); +//! ``` + +use std::cmp; +use std::ptr; +use libc::c_int; +use ffi; + +use {cvt, cvt_p}; +use error::ErrorStack; +use nid::Nid; + +#[derive(Copy, Clone)] +pub enum Mode { + Encrypt, + Decrypt, +} + +/// Represents a particular cipher algorithm. +/// +/// See OpenSSL doc at [`EVP_EncryptInit`] for more information on each algorithms. +/// +/// [`EVP_EncryptInit`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_EncryptInit.html +#[derive(Copy, Clone, PartialEq, Eq)] +pub struct Cipher(*const ffi::EVP_CIPHER); + +impl Cipher { + /// Looks up the cipher for a certain nid. + /// + /// This corresponds to [`EVP_get_cipherbynid`] + /// + /// [`EVP_get_cipherbynid`]: https://www.openssl.org/docs/man1.0.2/crypto/EVP_get_cipherbyname.html + pub fn from_nid(nid: Nid) -> Option { + let ptr = unsafe { ffi::EVP_get_cipherbyname(ffi::OBJ_nid2sn(nid.as_raw())) }; + if ptr.is_null() { + None + } else { + Some(Cipher(ptr)) + } + } + + pub fn aes_128_ecb() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_128_ecb()) } + } + + pub fn aes_128_cbc() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_128_cbc()) } + } + + pub fn aes_128_xts() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_128_xts()) } + } + + pub fn aes_128_ctr() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_128_ctr()) } + } + + pub fn aes_128_cfb1() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_128_cfb1()) } + } + + pub fn aes_128_cfb128() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_128_cfb128()) } + } + + pub fn aes_128_cfb8() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_128_cfb8()) } + } + + pub fn aes_128_gcm() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_128_gcm()) } + } + + pub fn aes_128_ccm() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_128_ccm()) } + } + + pub fn aes_256_ecb() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_256_ecb()) } + } + + pub fn aes_256_cbc() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_256_cbc()) } + } + + pub fn aes_256_xts() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_256_xts()) } + } + + pub fn aes_256_ctr() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_256_ctr()) } + } + + pub fn aes_256_cfb1() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_256_cfb1()) } + } + + pub fn aes_256_cfb128() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_256_cfb128()) } + } + + pub fn aes_256_cfb8() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_256_cfb8()) } + } + + pub fn aes_256_gcm() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_256_gcm()) } + } + + pub fn aes_256_ccm() -> Cipher { + unsafe { Cipher(ffi::EVP_aes_256_ccm()) } + } + + pub fn bf_cbc() -> Cipher { + unsafe { Cipher(ffi::EVP_bf_cbc()) } + } + + pub fn bf_ecb() -> Cipher { + unsafe { Cipher(ffi::EVP_bf_ecb()) } + } + + pub fn bf_cfb64() -> Cipher { + unsafe { Cipher(ffi::EVP_bf_cfb64()) } + } + + pub fn bf_ofb() -> Cipher { + unsafe { Cipher(ffi::EVP_bf_ofb()) } + } + + pub fn des_cbc() -> Cipher { + unsafe { Cipher(ffi::EVP_des_cbc()) } + } + + pub fn des_ecb() -> Cipher { + unsafe { Cipher(ffi::EVP_des_ecb()) } + } + + pub fn des_ede3() -> Cipher { + unsafe { Cipher(ffi::EVP_des_ede3()) } + } + + pub fn des_ede3_cbc() -> Cipher { + unsafe { Cipher(ffi::EVP_des_ede3_cbc()) } + } + + pub fn rc4() -> Cipher { + unsafe { Cipher(ffi::EVP_rc4()) } + } + + /// Requires OpenSSL 1.1.0 or newer. + #[cfg(any(ossl110))] + pub fn chacha20() -> Cipher { + unsafe { Cipher(ffi::EVP_chacha20()) } + } + + /// Requires OpenSSL 1.1.0 or newer. + #[cfg(any(ossl110))] + pub fn chacha20_poly1305() -> Cipher { + unsafe { Cipher(ffi::EVP_chacha20_poly1305()) } + } + + pub unsafe fn from_ptr(ptr: *const ffi::EVP_CIPHER) -> Cipher { + Cipher(ptr) + } + + pub fn as_ptr(&self) -> *const ffi::EVP_CIPHER { + self.0 + } + + /// Returns the length of keys used with this cipher. + pub fn key_len(&self) -> usize { + unsafe { EVP_CIPHER_key_length(self.0) as usize } + } + + /// Returns the length of the IV used with this cipher, or `None` if the + /// cipher does not use an IV. + pub fn iv_len(&self) -> Option { + unsafe { + let len = EVP_CIPHER_iv_length(self.0) as usize; + if len == 0 { + None + } else { + Some(len) + } + } + } + + /// Returns the block size of the cipher. + /// + /// # Note + /// + /// Stream ciphers such as RC4 have a block size of 1. + pub fn block_size(&self) -> usize { + unsafe { EVP_CIPHER_block_size(self.0) as usize } + } + + /// Determines whether the cipher is using CCM mode + fn is_ccm(&self) -> bool { + // NOTE: OpenSSL returns pointers to static structs, which makes this work as expected + *self == Cipher::aes_128_ccm() || *self == Cipher::aes_256_ccm() + } +} + +unsafe impl Sync for Cipher {} +unsafe impl Send for Cipher {} + +/// Represents a symmetric cipher context. +/// +/// Padding is enabled by default. +/// +/// # Examples +/// +/// Encrypt some plaintext in chunks, then decrypt the ciphertext back into plaintext, in AES 128 +/// CBC mode. +/// +/// ``` +/// use openssl::symm::{Cipher, Mode, Crypter}; +/// +/// let plaintexts: [&[u8]; 2] = [b"Some Stream of", b" Crypto Text"]; +/// let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"; +/// let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07"; +/// let data_len = plaintexts.iter().fold(0, |sum, x| sum + x.len()); +/// +/// // Create a cipher context for encryption. +/// let mut encrypter = Crypter::new( +/// Cipher::aes_128_cbc(), +/// Mode::Encrypt, +/// key, +/// Some(iv)).unwrap(); +/// +/// let block_size = Cipher::aes_128_cbc().block_size(); +/// let mut ciphertext = vec![0; data_len + block_size]; +/// +/// // Encrypt 2 chunks of plaintexts successively. +/// let mut count = encrypter.update(plaintexts[0], &mut ciphertext).unwrap(); +/// count += encrypter.update(plaintexts[1], &mut ciphertext[count..]).unwrap(); +/// count += encrypter.finalize(&mut ciphertext[count..]).unwrap(); +/// ciphertext.truncate(count); +/// +/// assert_eq!( +/// b"\x0F\x21\x83\x7E\xB2\x88\x04\xAF\xD9\xCC\xE2\x03\x49\xB4\x88\xF6\xC4\x61\x0E\x32\x1C\xF9\ +/// \x0D\x66\xB1\xE6\x2C\x77\x76\x18\x8D\x99", +/// &ciphertext[..] +/// ); +/// +/// +/// // Let's pretend we don't know the plaintext, and now decrypt the ciphertext. +/// let data_len = ciphertext.len(); +/// let ciphertexts = [&ciphertext[..9], &ciphertext[9..]]; +/// +/// // Create a cipher context for decryption. +/// let mut decrypter = Crypter::new( +/// Cipher::aes_128_cbc(), +/// Mode::Decrypt, +/// key, +/// Some(iv)).unwrap(); +/// let mut plaintext = vec![0; data_len + block_size]; +/// +/// // Decrypt 2 chunks of ciphertexts successively. +/// let mut count = decrypter.update(ciphertexts[0], &mut plaintext).unwrap(); +/// count += decrypter.update(ciphertexts[1], &mut plaintext[count..]).unwrap(); +/// count += decrypter.finalize(&mut plaintext[count..]).unwrap(); +/// plaintext.truncate(count); +/// +/// assert_eq!(b"Some Stream of Crypto Text", &plaintext[..]); +/// ``` +pub struct Crypter { + ctx: *mut ffi::EVP_CIPHER_CTX, + block_size: usize, +} + +unsafe impl Sync for Crypter {} +unsafe impl Send for Crypter {} + +impl Crypter { + /// Creates a new `Crypter`. The initialisation vector, `iv`, is not necesarry for certain + /// types of `Cipher`. + /// + /// # Panics + /// + /// Panics if an IV is required by the cipher but not provided. Also make sure that the key + /// and IV size are appropriate for your cipher. + pub fn new( + t: Cipher, + mode: Mode, + key: &[u8], + iv: Option<&[u8]>, + ) -> Result { + ffi::init(); + + unsafe { + let ctx = cvt_p(ffi::EVP_CIPHER_CTX_new())?; + let crypter = Crypter { + ctx: ctx, + block_size: t.block_size(), + }; + + let mode = match mode { + Mode::Encrypt => 1, + Mode::Decrypt => 0, + }; + + cvt(ffi::EVP_CipherInit_ex( + crypter.ctx, + t.as_ptr(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + mode, + ))?; + + assert!(key.len() <= c_int::max_value() as usize); + cvt(ffi::EVP_CIPHER_CTX_set_key_length( + crypter.ctx, + key.len() as c_int, + ))?; + + let key = key.as_ptr() as *mut _; + let iv = match (iv, t.iv_len()) { + (Some(iv), Some(len)) => { + if iv.len() != len { + assert!(iv.len() <= c_int::max_value() as usize); + cvt(ffi::EVP_CIPHER_CTX_ctrl( + crypter.ctx, + ffi::EVP_CTRL_GCM_SET_IVLEN, + iv.len() as c_int, + ptr::null_mut(), + ))?; + } + iv.as_ptr() as *mut _ + } + (Some(_), None) | (None, None) => ptr::null_mut(), + (None, Some(_)) => panic!("an IV is required for this cipher"), + }; + cvt(ffi::EVP_CipherInit_ex( + crypter.ctx, + ptr::null(), + ptr::null_mut(), + key, + iv, + mode, + ))?; + + Ok(crypter) + } + } + + /// Enables or disables padding. + /// + /// If padding is disabled, total amount of data encrypted/decrypted must + /// be a multiple of the cipher's block size. + pub fn pad(&mut self, padding: bool) { + unsafe { + ffi::EVP_CIPHER_CTX_set_padding(self.ctx, padding as c_int); + } + } + + /// Sets the tag used to authenticate ciphertext in AEAD ciphers such as AES GCM. + /// + /// When decrypting cipher text using an AEAD cipher, this must be called before `finalize`. + pub fn set_tag(&mut self, tag: &[u8]) -> Result<(), ErrorStack> { + unsafe { + assert!(tag.len() <= c_int::max_value() as usize); + // NB: this constant is actually more general than just GCM. + cvt(ffi::EVP_CIPHER_CTX_ctrl( + self.ctx, + ffi::EVP_CTRL_GCM_SET_TAG, + tag.len() as c_int, + tag.as_ptr() as *mut _, + )).map(|_| ()) + } + } + + /// Sets the length of the authentication tag to generate in AES CCM. + /// + /// When encrypting with AES CCM, the tag length needs to be explicitly set in order + /// to use a value different than the default 12 bytes. + pub fn set_tag_len(&mut self, tag_len: usize) -> Result<(), ErrorStack> { + unsafe { + assert!(tag_len <= c_int::max_value() as usize); + // NB: this constant is actually more general than just GCM. + cvt(ffi::EVP_CIPHER_CTX_ctrl( + self.ctx, + ffi::EVP_CTRL_GCM_SET_TAG, + tag_len as c_int, + ptr::null_mut(), + )).map(|_| ()) + } + } + + /// Feeds total plaintext length to the cipher. + /// + /// The total plaintext or ciphertext length MUST be passed to the cipher when it operates in + /// CCM mode. + pub fn set_data_len(&mut self, data_len: usize) -> Result<(), ErrorStack> { + unsafe { + assert!(data_len <= c_int::max_value() as usize); + let mut len = 0; + cvt(ffi::EVP_CipherUpdate( + self.ctx, + ptr::null_mut(), + &mut len, + ptr::null_mut(), + data_len as c_int, + )).map(|_| ()) + } + } + + /// Feeds Additional Authenticated Data (AAD) through the cipher. + /// + /// This can only be used with AEAD ciphers such as AES GCM. Data fed in is not encrypted, but + /// is factored into the authentication tag. It must be called before the first call to + /// `update`. + pub fn aad_update(&mut self, input: &[u8]) -> Result<(), ErrorStack> { + unsafe { + assert!(input.len() <= c_int::max_value() as usize); + let mut len = 0; + cvt(ffi::EVP_CipherUpdate( + self.ctx, + ptr::null_mut(), + &mut len, + input.as_ptr(), + input.len() as c_int, + )).map(|_| ()) + } + } + + /// Feeds data from `input` through the cipher, writing encrypted/decrypted + /// bytes into `output`. + /// + /// The number of bytes written to `output` is returned. Note that this may + /// not be equal to the length of `input`. + /// + /// # Panics + /// + /// Panics if `output.len() < input.len() + block_size` where + /// `block_size` is the block size of the cipher (see `Cipher::block_size`), + /// or if `output.len() > c_int::max_value()`. + pub fn update(&mut self, input: &[u8], output: &mut [u8]) -> Result { + unsafe { + assert!(output.len() >= input.len() + self.block_size); + assert!(output.len() <= c_int::max_value() as usize); + let mut outl = output.len() as c_int; + let inl = input.len() as c_int; + + cvt(ffi::EVP_CipherUpdate( + self.ctx, + output.as_mut_ptr(), + &mut outl, + input.as_ptr(), + inl, + ))?; + + Ok(outl as usize) + } + } + + /// Finishes the encryption/decryption process, writing any remaining data + /// to `output`. + /// + /// The number of bytes written to `output` is returned. + /// + /// `update` should not be called after this method. + /// + /// # Panics + /// + /// Panics if `output` is less than the cipher's block size. + pub fn finalize(&mut self, output: &mut [u8]) -> Result { + unsafe { + assert!(output.len() >= self.block_size); + let mut outl = cmp::min(output.len(), c_int::max_value() as usize) as c_int; + + cvt(ffi::EVP_CipherFinal( + self.ctx, + output.as_mut_ptr(), + &mut outl, + ))?; + + Ok(outl as usize) + } + } + + /// Retrieves the authentication tag used to authenticate ciphertext in AEAD ciphers such + /// as AES GCM. + /// + /// When encrypting data with an AEAD cipher, this must be called after `finalize`. + /// + /// The size of the buffer indicates the required size of the tag. While some ciphers support a + /// range of tag sizes, it is recommended to pick the maximum size. For AES GCM, this is 16 + /// bytes, for example. + pub fn get_tag(&self, tag: &mut [u8]) -> Result<(), ErrorStack> { + unsafe { + assert!(tag.len() <= c_int::max_value() as usize); + cvt(ffi::EVP_CIPHER_CTX_ctrl( + self.ctx, + ffi::EVP_CTRL_GCM_GET_TAG, + tag.len() as c_int, + tag.as_mut_ptr() as *mut _, + )).map(|_| ()) + } + } +} + +impl Drop for Crypter { + fn drop(&mut self) { + unsafe { + ffi::EVP_CIPHER_CTX_free(self.ctx); + } + } +} + +/// Encrypts data in one go, and returns the encrypted data. +/// +/// Data is encrypted using the specified cipher type `t` in encrypt mode with the specified `key` +/// and initailization vector `iv`. +/// +/// This is a convenient interface to `Crypter` to encrypt all data in one go. To encrypt a stream +/// of data increamentally , use `Crypter` instead. +/// +/// # Examples +/// +/// Encrypt data in AES128 CBC mode +/// +/// ``` +/// use openssl::symm::{encrypt, Cipher}; +/// +/// let cipher = Cipher::aes_128_cbc(); +/// let data = b"Some Crypto Text"; +/// let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"; +/// let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07"; +/// let ciphertext = encrypt( +/// cipher, +/// key, +/// Some(iv), +/// data).unwrap(); +/// +/// assert_eq!( +/// b"\xB4\xB9\xE7\x30\xD6\xD6\xF7\xDE\x77\x3F\x1C\xFF\xB3\x3E\x44\x5A\x91\xD7\x27\x62\x87\x4D\ +/// \xFB\x3C\x5E\xC4\x59\x72\x4A\xF4\x7C\xA1", +/// &ciphertext[..]); +/// ``` +pub fn encrypt( + t: Cipher, + key: &[u8], + iv: Option<&[u8]>, + data: &[u8], +) -> Result, ErrorStack> { + cipher(t, Mode::Encrypt, key, iv, data) +} + +/// Decrypts data in one go, and returns the decrypted data. +/// +/// Data is decrypted using the specified cipher type `t` in decrypt mode with the specified `key` +/// and initailization vector `iv`. +/// +/// This is a convenient interface to `Crypter` to decrypt all data in one go. To decrypt a stream +/// of data increamentally , use `Crypter` instead. +/// +/// # Examples +/// +/// Decrypt data in AES128 CBC mode +/// +/// ``` +/// use openssl::symm::{decrypt, Cipher}; +/// +/// let cipher = Cipher::aes_128_cbc(); +/// let data = b"\xB4\xB9\xE7\x30\xD6\xD6\xF7\xDE\x77\x3F\x1C\xFF\xB3\x3E\x44\x5A\x91\xD7\x27\x62\ +/// \x87\x4D\xFB\x3C\x5E\xC4\x59\x72\x4A\xF4\x7C\xA1"; +/// let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"; +/// let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07"; +/// let ciphertext = decrypt( +/// cipher, +/// key, +/// Some(iv), +/// data).unwrap(); +/// +/// assert_eq!( +/// b"Some Crypto Text", +/// &ciphertext[..]); +/// ``` +pub fn decrypt( + t: Cipher, + key: &[u8], + iv: Option<&[u8]>, + data: &[u8], +) -> Result, ErrorStack> { + cipher(t, Mode::Decrypt, key, iv, data) +} + +fn cipher( + t: Cipher, + mode: Mode, + key: &[u8], + iv: Option<&[u8]>, + data: &[u8], +) -> Result, ErrorStack> { + let mut c = Crypter::new(t, mode, key, iv)?; + let mut out = vec![0; data.len() + t.block_size()]; + let count = c.update(data, &mut out)?; + let rest = c.finalize(&mut out[count..])?; + out.truncate(count + rest); + Ok(out) +} + +/// Like `encrypt`, but for AEAD ciphers such as AES GCM. +/// +/// Additional Authenticated Data can be provided in the `aad` field, and the authentication tag +/// will be copied into the `tag` field. +/// +/// The size of the `tag` buffer indicates the required size of the tag. While some ciphers support +/// a range of tag sizes, it is recommended to pick the maximum size. For AES GCM, this is 16 bytes, +/// for example. +pub fn encrypt_aead( + t: Cipher, + key: &[u8], + iv: Option<&[u8]>, + aad: &[u8], + data: &[u8], + tag: &mut [u8], +) -> Result, ErrorStack> { + let mut c = Crypter::new(t, Mode::Encrypt, key, iv)?; + let mut out = vec![0; data.len() + t.block_size()]; + + if t.is_ccm() { + c.set_tag_len(tag.len())?; + c.set_data_len(data.len())?; + } + + c.aad_update(aad)?; + let count = c.update(data, &mut out)?; + let rest = c.finalize(&mut out[count..])?; + c.get_tag(tag)?; + out.truncate(count + rest); + Ok(out) +} + +/// Like `decrypt`, but for AEAD ciphers such as AES GCM. +/// +/// Additional Authenticated Data can be provided in the `aad` field, and the authentication tag +/// should be provided in the `tag` field. +pub fn decrypt_aead( + t: Cipher, + key: &[u8], + iv: Option<&[u8]>, + aad: &[u8], + data: &[u8], + tag: &[u8], +) -> Result, ErrorStack> { + let mut c = Crypter::new(t, Mode::Decrypt, key, iv)?; + let mut out = vec![0; data.len() + t.block_size()]; + + if t.is_ccm() { + c.set_tag(tag)?; + c.set_data_len(data.len())?; + } + + c.aad_update(aad)?; + let count = c.update(data, &mut out)?; + let mut rest = 0; + + if !t.is_ccm() { + c.set_tag(tag)?; + rest = c.finalize(&mut out[count..])?; + } + + out.truncate(count + rest); + Ok(out) +} + +#[cfg(ossl110)] +use ffi::{EVP_CIPHER_block_size, EVP_CIPHER_iv_length, EVP_CIPHER_key_length}; + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use libc::c_int; + use ffi::EVP_CIPHER; + + pub unsafe fn EVP_CIPHER_iv_length(ptr: *const EVP_CIPHER) -> c_int { + (*ptr).iv_len + } + + pub unsafe fn EVP_CIPHER_block_size(ptr: *const EVP_CIPHER) -> c_int { + (*ptr).block_size + } + + pub unsafe fn EVP_CIPHER_key_length(ptr: *const EVP_CIPHER) -> c_int { + (*ptr).key_len + } +} +#[cfg(ossl10x)] +use self::compat::*; + +#[cfg(test)] +mod tests { + use hex::{self, FromHex}; + use super::*; + + // Test vectors from FIPS-197: + // http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf + #[test] + fn test_aes_256_ecb() { + let k0 = [ + 0x00u8, 0x01u8, 0x02u8, 0x03u8, 0x04u8, 0x05u8, 0x06u8, 0x07u8, 0x08u8, 0x09u8, 0x0au8, + 0x0bu8, 0x0cu8, 0x0du8, 0x0eu8, 0x0fu8, 0x10u8, 0x11u8, 0x12u8, 0x13u8, 0x14u8, 0x15u8, + 0x16u8, 0x17u8, 0x18u8, 0x19u8, 0x1au8, 0x1bu8, 0x1cu8, 0x1du8, 0x1eu8, 0x1fu8, + ]; + let p0 = [ + 0x00u8, 0x11u8, 0x22u8, 0x33u8, 0x44u8, 0x55u8, 0x66u8, 0x77u8, 0x88u8, 0x99u8, 0xaau8, + 0xbbu8, 0xccu8, 0xddu8, 0xeeu8, 0xffu8, + ]; + let c0 = [ + 0x8eu8, 0xa2u8, 0xb7u8, 0xcau8, 0x51u8, 0x67u8, 0x45u8, 0xbfu8, 0xeau8, 0xfcu8, 0x49u8, + 0x90u8, 0x4bu8, 0x49u8, 0x60u8, 0x89u8, + ]; + let mut c = super::Crypter::new( + super::Cipher::aes_256_ecb(), + super::Mode::Encrypt, + &k0, + None, + ).unwrap(); + c.pad(false); + let mut r0 = vec![0; c0.len() + super::Cipher::aes_256_ecb().block_size()]; + let count = c.update(&p0, &mut r0).unwrap(); + let rest = c.finalize(&mut r0[count..]).unwrap(); + r0.truncate(count + rest); + assert_eq!(hex::encode(&r0), hex::encode(c0)); + + let mut c = super::Crypter::new( + super::Cipher::aes_256_ecb(), + super::Mode::Decrypt, + &k0, + None, + ).unwrap(); + c.pad(false); + let mut p1 = vec![0; r0.len() + super::Cipher::aes_256_ecb().block_size()]; + let count = c.update(&r0, &mut p1).unwrap(); + let rest = c.finalize(&mut p1[count..]).unwrap(); + p1.truncate(count + rest); + assert_eq!(hex::encode(p1), hex::encode(p0)); + } + + #[test] + fn test_aes_256_cbc_decrypt() { + let iv = [ + 4_u8, 223_u8, 153_u8, 219_u8, 28_u8, 142_u8, 234_u8, 68_u8, 227_u8, 69_u8, 98_u8, + 107_u8, 208_u8, 14_u8, 236_u8, 60_u8, + ]; + let data = [ + 143_u8, 210_u8, 75_u8, 63_u8, 214_u8, 179_u8, 155_u8, 241_u8, 242_u8, 31_u8, 154_u8, + 56_u8, 198_u8, 145_u8, 192_u8, 64_u8, 2_u8, 245_u8, 167_u8, 220_u8, 55_u8, 119_u8, + 233_u8, 136_u8, 139_u8, 27_u8, 71_u8, 242_u8, 119_u8, 175_u8, 65_u8, 207_u8, + ]; + let ciphered_data = [ + 0x4a_u8, 0x2e_u8, 0xe5_u8, 0x6_u8, 0xbf_u8, 0xcf_u8, 0xf2_u8, 0xd7_u8, 0xea_u8, + 0x2d_u8, 0xb1_u8, 0x85_u8, 0x6c_u8, 0x93_u8, 0x65_u8, 0x6f_u8, + ]; + let mut cr = super::Crypter::new( + super::Cipher::aes_256_cbc(), + super::Mode::Decrypt, + &data, + Some(&iv), + ).unwrap(); + cr.pad(false); + let mut unciphered_data = vec![0; data.len() + super::Cipher::aes_256_cbc().block_size()]; + let count = cr.update(&ciphered_data, &mut unciphered_data).unwrap(); + let rest = cr.finalize(&mut unciphered_data[count..]).unwrap(); + unciphered_data.truncate(count + rest); + + let expected_unciphered_data = b"I love turtles.\x01"; + + assert_eq!(&unciphered_data, expected_unciphered_data); + } + + fn cipher_test(ciphertype: super::Cipher, pt: &str, ct: &str, key: &str, iv: &str) { + let pt = Vec::from_hex(pt).unwrap(); + let ct = Vec::from_hex(ct).unwrap(); + let key = Vec::from_hex(key).unwrap(); + let iv = Vec::from_hex(iv).unwrap(); + + let computed = super::decrypt(ciphertype, &key, Some(&iv), &ct).unwrap(); + let expected = pt; + + if computed != expected { + println!("Computed: {}", hex::encode(&computed)); + println!("Expected: {}", hex::encode(&expected)); + if computed.len() != expected.len() { + println!( + "Lengths differ: {} in computed vs {} expected", + computed.len(), + expected.len() + ); + } + panic!("test failure"); + } + } + + fn cipher_test_nopad(ciphertype: super::Cipher, pt: &str, ct: &str, key: &str, iv: &str) { + let pt = Vec::from_hex(pt).unwrap(); + let ct = Vec::from_hex(ct).unwrap(); + let key = Vec::from_hex(key).unwrap(); + let iv = Vec::from_hex(iv).unwrap(); + + let computed = { + let mut c = Crypter::new(ciphertype, Mode::Decrypt, &key, Some(&iv)).unwrap(); + c.pad(false); + let mut out = vec![0; ct.len() + ciphertype.block_size()]; + let count = c.update(&ct, &mut out).unwrap(); + let rest = c.finalize(&mut out[count..]).unwrap(); + out.truncate(count + rest); + out + }; + let expected = pt; + + if computed != expected { + println!("Computed: {}", hex::encode(&computed)); + println!("Expected: {}", hex::encode(&expected)); + if computed.len() != expected.len() { + println!( + "Lengths differ: {} in computed vs {} expected", + computed.len(), + expected.len() + ); + } + panic!("test failure"); + } + } + + #[test] + fn test_rc4() { + let pt = "0000000000000000000000000000000000000000000000000000000000000000000000000000"; + let ct = "A68686B04D686AA107BD8D4CAB191A3EEC0A6294BC78B60F65C25CB47BD7BB3A48EFC4D26BE4"; + let key = "97CD440324DA5FD1F7955C1C13B6B466"; + let iv = ""; + + cipher_test(super::Cipher::rc4(), pt, ct, key, iv); + } + + #[test] + fn test_aes256_xts() { + // Test case 174 from + // http://csrc.nist.gov/groups/STM/cavp/documents/aes/XTSTestVectors.zip + let pt = "77f4ef63d734ebd028508da66c22cdebdd52ecd6ee2ab0a50bc8ad0cfd692ca5fcd4e6dedc45df7f\ + 6503f462611dc542"; + let ct = "ce7d905a7776ac72f240d22aafed5e4eb7566cdc7211220e970da634ce015f131a5ecb8d400bc9e8\ + 4f0b81d8725dbbc7"; + let key = "b6bfef891f83b5ff073f2231267be51eb084b791fa19a154399c0684c8b2dfcb37de77d28bbda3b\ + 4180026ad640b74243b3133e7b9fae629403f6733423dae28"; + let iv = "db200efb7eaaa737dbdf40babb68953f"; + + cipher_test(super::Cipher::aes_256_xts(), pt, ct, key, iv); + } + + #[test] + fn test_aes128_ctr() { + let pt = "6BC1BEE22E409F96E93D7E117393172AAE2D8A571E03AC9C9EB76FAC45AF8E5130C81C46A35CE411\ + E5FBC1191A0A52EFF69F2445DF4F9B17AD2B417BE66C3710"; + let ct = "874D6191B620E3261BEF6864990DB6CE9806F66B7970FDFF8617187BB9FFFDFF5AE4DF3EDBD5D35E\ + 5B4F09020DB03EAB1E031DDA2FBE03D1792170A0F3009CEE"; + let key = "2B7E151628AED2A6ABF7158809CF4F3C"; + let iv = "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"; + + cipher_test(super::Cipher::aes_128_ctr(), pt, ct, key, iv); + } + + #[test] + fn test_aes128_cfb1() { + // Lifted from http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf + + let pt = "6bc1"; + let ct = "68b3"; + let key = "2b7e151628aed2a6abf7158809cf4f3c"; + let iv = "000102030405060708090a0b0c0d0e0f"; + + cipher_test(super::Cipher::aes_128_cfb1(), pt, ct, key, iv); + } + + #[test] + fn test_aes128_cfb128() { + let pt = "6bc1bee22e409f96e93d7e117393172a"; + let ct = "3b3fd92eb72dad20333449f8e83cfb4a"; + let key = "2b7e151628aed2a6abf7158809cf4f3c"; + let iv = "000102030405060708090a0b0c0d0e0f"; + + cipher_test(super::Cipher::aes_128_cfb128(), pt, ct, key, iv); + } + + #[test] + fn test_aes128_cfb8() { + let pt = "6bc1bee22e409f96e93d7e117393172aae2d"; + let ct = "3b79424c9c0dd436bace9e0ed4586a4f32b9"; + let key = "2b7e151628aed2a6abf7158809cf4f3c"; + let iv = "000102030405060708090a0b0c0d0e0f"; + + cipher_test(super::Cipher::aes_128_cfb8(), pt, ct, key, iv); + } + + #[test] + fn test_aes256_cfb1() { + let pt = "6bc1"; + let ct = "9029"; + let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; + let iv = "000102030405060708090a0b0c0d0e0f"; + + cipher_test(super::Cipher::aes_256_cfb1(), pt, ct, key, iv); + } + + #[test] + fn test_aes256_cfb128() { + let pt = "6bc1bee22e409f96e93d7e117393172a"; + let ct = "dc7e84bfda79164b7ecd8486985d3860"; + let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; + let iv = "000102030405060708090a0b0c0d0e0f"; + + cipher_test(super::Cipher::aes_256_cfb128(), pt, ct, key, iv); + } + + #[test] + fn test_aes256_cfb8() { + let pt = "6bc1bee22e409f96e93d7e117393172aae2d"; + let ct = "dc1f1a8520a64db55fcc8ac554844e889700"; + let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; + let iv = "000102030405060708090a0b0c0d0e0f"; + + cipher_test(super::Cipher::aes_256_cfb8(), pt, ct, key, iv); + } + + #[test] + fn test_bf_cbc() { + // https://www.schneier.com/code/vectors.txt + + let pt = "37363534333231204E6F77206973207468652074696D6520666F722000000000"; + let ct = "6B77B4D63006DEE605B156E27403979358DEB9E7154616D959F1652BD5FF92CC"; + let key = "0123456789ABCDEFF0E1D2C3B4A59687"; + let iv = "FEDCBA9876543210"; + + cipher_test_nopad(super::Cipher::bf_cbc(), pt, ct, key, iv); + } + + #[test] + fn test_bf_ecb() { + let pt = "5CD54CA83DEF57DA"; + let ct = "B1B8CC0B250F09A0"; + let key = "0131D9619DC1376E"; + let iv = "0000000000000000"; + + cipher_test_nopad(super::Cipher::bf_ecb(), pt, ct, key, iv); + } + + #[test] + fn test_bf_cfb64() { + let pt = "37363534333231204E6F77206973207468652074696D6520666F722000"; + let ct = "E73214A2822139CAF26ECF6D2EB9E76E3DA3DE04D1517200519D57A6C3"; + let key = "0123456789ABCDEFF0E1D2C3B4A59687"; + let iv = "FEDCBA9876543210"; + + cipher_test_nopad(super::Cipher::bf_cfb64(), pt, ct, key, iv); + } + + #[test] + fn test_bf_ofb() { + let pt = "37363534333231204E6F77206973207468652074696D6520666F722000"; + let ct = "E73214A2822139CA62B343CC5B65587310DD908D0C241B2263C2CF80DA"; + let key = "0123456789ABCDEFF0E1D2C3B4A59687"; + let iv = "FEDCBA9876543210"; + + cipher_test_nopad(super::Cipher::bf_ofb(), pt, ct, key, iv); + } + + #[test] + fn test_des_cbc() { + let pt = "54686973206973206120746573742e"; + let ct = "6f2867cfefda048a4046ef7e556c7132"; + let key = "7cb66337f3d3c0fe"; + let iv = "0001020304050607"; + + cipher_test(super::Cipher::des_cbc(), pt, ct, key, iv); + } + + #[test] + fn test_des_ecb() { + let pt = "54686973206973206120746573742e"; + let ct = "0050ab8aecec758843fe157b4dde938c"; + let key = "7cb66337f3d3c0fe"; + let iv = "0001020304050607"; + + cipher_test(super::Cipher::des_ecb(), pt, ct, key, iv); + } + + #[test] + fn test_des_ede3() { + let pt = "9994f4c69d40ae4f34ff403b5cf39d4c8207ea5d3e19a5fd"; + let ct = "9e5c4297d60582f81071ac8ab7d0698d4c79de8b94c519858207ea5d3e19a5fd"; + let key = "010203040506070801020304050607080102030405060708"; + let iv = "5cc118306dc702e4"; + + cipher_test(super::Cipher::des_ede3(), pt, ct, key, iv); + } + + #[test] + fn test_des_ede3_cbc() { + let pt = "54686973206973206120746573742e"; + let ct = "6f2867cfefda048a4046ef7e556c7132"; + let key = "7cb66337f3d3c0fe7cb66337f3d3c0fe7cb66337f3d3c0fe"; + let iv = "0001020304050607"; + + cipher_test(super::Cipher::des_ede3_cbc(), pt, ct, key, iv); + } + + #[test] + fn test_aes128_gcm() { + let key = "0e00c76561d2bd9b40c3c15427e2b08f"; + let iv = "492cadaccd3ca3fbc9cf9f06eb3325c4e159850b0dbe98199b89b7af528806610b6f63998e1eae80c348e7\ + 4cbb921d8326631631fc6a5d304f39166daf7ea15fa1977f101819adb510b50fe9932e12c5a85aa3fd1e73\ + d8d760af218be829903a77c63359d75edd91b4f6ed5465a72662f5055999e059e7654a8edc921aa0d496"; + let pt = "fef03c2d7fb15bf0d2df18007d99f967c878ad59359034f7bb2c19af120685d78e32f6b8b83b032019956c\ + a9c0195721476b85"; + let aad = "d8f1163d8c840292a2b2dacf4ac7c36aff8733f18fabb4fa5594544125e03d1e6e5d6d0fd61656c8d8f327\ + c92839ae5539bb469c9257f109ebff85aad7bd220fdaa95c022dbd0c7bb2d878ad504122c943045d3c5eba\ + 8f1f56c0"; + let ct = "4f6cf471be7cbd2575cd5a1747aea8fe9dea83e51936beac3e68f66206922060c697ffa7af80ad6bb68f2c\ + f4fc97416ee52abe"; + let tag = "e20b6655"; + + // this tag is smaller than you'd normally want, but I pulled this test from the part of + // the NIST test vectors that cover 4 byte tags. + let mut actual_tag = [0; 4]; + let out = encrypt_aead( + Cipher::aes_128_gcm(), + &Vec::from_hex(key).unwrap(), + Some(&Vec::from_hex(iv).unwrap()), + &Vec::from_hex(aad).unwrap(), + &Vec::from_hex(pt).unwrap(), + &mut actual_tag, + ).unwrap(); + assert_eq!(ct, hex::encode(out)); + assert_eq!(tag, hex::encode(actual_tag)); + + let out = decrypt_aead( + Cipher::aes_128_gcm(), + &Vec::from_hex(key).unwrap(), + Some(&Vec::from_hex(iv).unwrap()), + &Vec::from_hex(aad).unwrap(), + &Vec::from_hex(ct).unwrap(), + &Vec::from_hex(tag).unwrap(), + ).unwrap(); + assert_eq!(pt, hex::encode(out)); + } + + #[test] + fn test_aes128_ccm() { + let key = "3ee186594f110fb788a8bf8aa8be5d4a"; + let nonce = "44f705d52acf27b7f17196aa9b"; + let aad = "2c16724296ff85e079627be3053ea95adf35722c21886baba343bd6c79b5cb57"; + + let pt = "d71864877f2578db092daba2d6a1f9f4698a9c356c7830a1"; + let ct = "b4dd74e7a0cc51aea45dfb401a41d5822c96901a83247ea0"; + let tag = "d6965f5aa6e31302a9cc2b36"; + + let mut actual_tag = [0; 12]; + let out = encrypt_aead( + Cipher::aes_128_ccm(), + &Vec::from_hex(key).unwrap(), + Some(&Vec::from_hex(nonce).unwrap()), + &Vec::from_hex(aad).unwrap(), + &Vec::from_hex(pt).unwrap(), + &mut actual_tag, + ).unwrap(); + + assert_eq!(ct, hex::encode(out)); + assert_eq!(tag, hex::encode(actual_tag)); + + let out = decrypt_aead( + Cipher::aes_128_ccm(), + &Vec::from_hex(key).unwrap(), + Some(&Vec::from_hex(nonce).unwrap()), + &Vec::from_hex(aad).unwrap(), + &Vec::from_hex(ct).unwrap(), + &Vec::from_hex(tag).unwrap(), + ).unwrap(); + assert_eq!(pt, hex::encode(out)); + } + + #[test] + fn test_aes128_ccm_verify_fail() { + let key = "3ee186594f110fb788a8bf8aa8be5d4a"; + let nonce = "44f705d52acf27b7f17196aa9b"; + let aad = "2c16724296ff85e079627be3053ea95adf35722c21886baba343bd6c79b5cb57"; + + let ct = "b4dd74e7a0cc51aea45dfb401a41d5822c96901a83247ea0"; + let tag = "00005f5aa6e31302a9cc2b36"; + + let out = decrypt_aead( + Cipher::aes_128_ccm(), + &Vec::from_hex(key).unwrap(), + Some(&Vec::from_hex(nonce).unwrap()), + &Vec::from_hex(aad).unwrap(), + &Vec::from_hex(ct).unwrap(), + &Vec::from_hex(tag).unwrap(), + ); + assert!(out.is_err()); + } + + #[test] + fn test_aes256_ccm() { + let key = "7f4af6765cad1d511db07e33aaafd57646ec279db629048aa6770af24849aa0d"; + let nonce = "dde2a362ce81b2b6913abc3095"; + let aad = "404f5df97ece7431987bc098cce994fc3c063b519ffa47b0365226a0015ef695"; + + let pt = "7ebef26bf4ecf6f0ebb2eb860edbf900f27b75b4a6340fdb"; + let ct = "353022db9c568bd7183a13c40b1ba30fcc768c54264aa2cd"; + let tag = "2927a053c9244d3217a7ad05"; + + let mut actual_tag = [0; 12]; + let out = encrypt_aead( + Cipher::aes_256_ccm(), + &Vec::from_hex(key).unwrap(), + Some(&Vec::from_hex(nonce).unwrap()), + &Vec::from_hex(aad).unwrap(), + &Vec::from_hex(pt).unwrap(), + &mut actual_tag, + ).unwrap(); + + assert_eq!(ct, hex::encode(out)); + assert_eq!(tag, hex::encode(actual_tag)); + + let out = decrypt_aead( + Cipher::aes_256_ccm(), + &Vec::from_hex(key).unwrap(), + Some(&Vec::from_hex(nonce).unwrap()), + &Vec::from_hex(aad).unwrap(), + &Vec::from_hex(ct).unwrap(), + &Vec::from_hex(tag).unwrap(), + ).unwrap(); + assert_eq!(pt, hex::encode(out)); + } + + #[test] + fn test_aes256_ccm_verify_fail() { + let key = "7f4af6765cad1d511db07e33aaafd57646ec279db629048aa6770af24849aa0d"; + let nonce = "dde2a362ce81b2b6913abc3095"; + let aad = "404f5df97ece7431987bc098cce994fc3c063b519ffa47b0365226a0015ef695"; + + let ct = "353022db9c568bd7183a13c40b1ba30fcc768c54264aa2cd"; + let tag = "0000a053c9244d3217a7ad05"; + + let out = decrypt_aead( + Cipher::aes_256_ccm(), + &Vec::from_hex(key).unwrap(), + Some(&Vec::from_hex(nonce).unwrap()), + &Vec::from_hex(aad).unwrap(), + &Vec::from_hex(ct).unwrap(), + &Vec::from_hex(tag).unwrap(), + ); + assert!(out.is_err()); + } + + #[test] + #[cfg(any(ossl110))] + fn test_chacha20() { + let key = "0000000000000000000000000000000000000000000000000000000000000000"; + let iv = "00000000000000000000000000000000"; + let pt = + "000000000000000000000000000000000000000000000000000000000000000000000000000000000\ + 00000000000000000000000000000000000000000000000"; + let ct = + "76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7\ + 724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"; + + cipher_test(Cipher::chacha20(), pt, ct, key, iv); + } + + #[test] + #[cfg(any(ossl110))] + fn test_chacha20_poly1305() { + let key = "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f"; + let iv = "070000004041424344454647"; + let aad = "50515253c0c1c2c3c4c5c6c7"; + let pt = + "4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393\ + a204966204920636f756c64206f6666657220796f75206f6e6c79206f6e652074697020666f722074\ + 6865206675747572652c2073756e73637265656e20776f756c642062652069742e"; + let ct = + "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca967128\ + 2fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fa\ + b324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b6116"; + let tag = "1ae10b594f09e26a7e902ecbd0600691"; + + let mut actual_tag = [0; 16]; + let out = encrypt_aead( + Cipher::chacha20_poly1305(), + &Vec::from_hex(key).unwrap(), + Some(&Vec::from_hex(iv).unwrap()), + &Vec::from_hex(aad).unwrap(), + &Vec::from_hex(pt).unwrap(), + &mut actual_tag, + ).unwrap(); + assert_eq!(ct, hex::encode(out)); + assert_eq!(tag, hex::encode(actual_tag)); + + let out = decrypt_aead( + Cipher::chacha20_poly1305(), + &Vec::from_hex(key).unwrap(), + Some(&Vec::from_hex(iv).unwrap()), + &Vec::from_hex(aad).unwrap(), + &Vec::from_hex(ct).unwrap(), + &Vec::from_hex(tag).unwrap(), + ).unwrap(); + assert_eq!(pt, hex::encode(out)); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/util.rs cargo-0.26.0/vendor/openssl-0.10.6/src/util.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/util.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/util.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,67 @@ +use libc::{c_char, c_int, c_void}; +use std::any::Any; +use std::panic::{self, AssertUnwindSafe}; +use std::slice; + +use error::ErrorStack; + +/// Wraps a user-supplied callback and a slot for panics thrown inside the callback (while FFI +/// frames are on the stack). +/// +/// When dropped, checks if the callback has panicked, and resumes unwinding if so. +pub struct CallbackState { + /// The user callback. Taken out of the `Option` when called. + cb: Option, + /// If the callback panics, we place the panic object here, to be re-thrown once OpenSSL + /// returns. + panic: Option>, +} + +impl CallbackState { + pub fn new(callback: F) -> Self { + CallbackState { + cb: Some(callback), + panic: None, + } + } +} + +impl Drop for CallbackState { + fn drop(&mut self) { + if let Some(panic) = self.panic.take() { + panic::resume_unwind(panic); + } + } +} + +/// Password callback function, passed to private key loading functions. +/// +/// `cb_state` is expected to be a pointer to a `CallbackState`. +pub unsafe extern "C" fn invoke_passwd_cb( + buf: *mut c_char, + size: c_int, + _rwflag: c_int, + cb_state: *mut c_void, +) -> c_int +where + F: FnOnce(&mut [u8]) -> Result, +{ + let callback = &mut *(cb_state as *mut CallbackState); + + let result = panic::catch_unwind(AssertUnwindSafe(|| { + let pass_slice = slice::from_raw_parts_mut(buf as *mut u8, size as usize); + callback.cb.take().unwrap()(pass_slice) + })); + + match result { + Ok(Ok(len)) => len as c_int, + Ok(Err(_)) => { + // FIXME restore error stack + 0 + } + Err(err) => { + callback.panic = Some(err); + 0 + } + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/version.rs cargo-0.26.0/vendor/openssl-0.10.6/src/version.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/version.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/version.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,126 @@ +// 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. +// + +use std::ffi::CStr; + +#[cfg(ossl10x)] +use ffi::{SSLEAY_VERSION as OPENSSL_VERSION, SSLEAY_CFLAGS as OPENSSL_CFLAGS, + SSLEAY_BUILT_ON as OPENSSL_BUILT_ON, SSLEAY_PLATFORM as OPENSSL_PLATFORM, + SSLEAY_DIR as OPENSSL_DIR, SSLeay as OpenSSL_version_num, + SSLeay_version as OpenSSL_version}; + +#[cfg(ossl110)] +use ffi::{OPENSSL_VERSION, OPENSSL_CFLAGS, OPENSSL_BUILT_ON, OPENSSL_PLATFORM, OPENSSL_DIR, + OpenSSL_version_num, OpenSSL_version}; + +/// OPENSSL_VERSION_NUMBER is a numeric release version identifier: +/// +/// `MNNFFPPS: major minor fix patch status` +/// +/// The status nibble has one of the values 0 for development, 1 to e for betas 1 to 14, and f for release. +/// +/// for example +/// +/// `0x000906000 == 0.9.6 dev` +/// `0x000906023 == 0.9.6b beta 3` +/// `0x00090605f == 0.9.6e release` +/// +/// Versions prior to 0.9.3 have identifiers < 0x0930. Versions between 0.9.3 and 0.9.5 had a version identifier with this interpretation: +/// +/// `MMNNFFRBB major minor fix final beta/patch` +/// +/// for example +/// +/// `0x000904100 == 0.9.4 release` +/// `0x000905000 == 0.9.5 dev` +/// +/// Version 0.9.5a had an interim interpretation that is like the current one, except the patch level got the highest bit set, to keep continuity. The number was therefore 0x0090581f +/// +/// The return value of this function can be compared to the macro to make sure that the correct version of the library has been loaded, especially when using DLLs on Windows systems. +pub fn number() -> i64 { + unsafe { OpenSSL_version_num() as i64 } +} + + +/// The text variant of the version number and the release date. For example, "OpenSSL 0.9.5a 1 Apr 2000". +pub fn version() -> &'static str { + unsafe { + CStr::from_ptr(OpenSSL_version(OPENSSL_VERSION)) + .to_str() + .unwrap() + } +} + +/// The compiler flags set for the compilation process in the form "compiler: ..." if available or +/// "compiler: information not available" otherwise. +pub fn c_flags() -> &'static str { + unsafe { + CStr::from_ptr(OpenSSL_version(OPENSSL_CFLAGS)) + .to_str() + .unwrap() + } +} + +/// The date of the build process in the form "built on: ..." if available or "built on: date not available" otherwise. +pub fn built_on() -> &'static str { + unsafe { + CStr::from_ptr(OpenSSL_version(OPENSSL_BUILT_ON)) + .to_str() + .unwrap() + } +} + +/// The "Configure" target of the library build in the form "platform: ..." if available or "platform: information not available" otherwise. +pub fn platform() -> &'static str { + unsafe { + CStr::from_ptr(OpenSSL_version(OPENSSL_PLATFORM)) + .to_str() + .unwrap() + } +} + +/// The "OPENSSLDIR" setting of the library build in the form "OPENSSLDIR: "..."" if available or "OPENSSLDIR: N/A" otherwise. +pub fn dir() -> &'static str { + unsafe { + CStr::from_ptr(OpenSSL_version(OPENSSL_DIR)) + .to_str() + .unwrap() + } +} + +/// This test ensures that we do not segfault when calling the functions of this module +/// and that the strings respect a reasonable format. +#[test] +fn test_versions() { + println!("Number: '{}'", number()); + println!("Version: '{}'", version()); + println!("C flags: '{}'", c_flags()); + println!("Built on: '{}'", built_on()); + println!("Platform: '{}'", platform()); + println!("Dir: '{}'", dir()); + + #[cfg(not(libressl))] + fn expected_name() -> &'static str { + "OpenSSL" + } + #[cfg(libressl)] + fn expected_name() -> &'static str { + "LibreSSL" + } + + assert!(number() > 0); + assert!(version().starts_with(expected_name())); + assert!(c_flags().starts_with("compiler:")); + assert!(built_on().starts_with("built on:")); + assert!(dir().starts_with("OPENSSLDIR:")); +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/x509/extension.rs cargo-0.26.0/vendor/openssl-0.10.6/src/x509/extension.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/x509/extension.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/x509/extension.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,520 @@ +//! Add extensions to an `X509` certificate or certificate request. +//! +//! The extensions defined for X.509 v3 certificates provide methods for +//! associating additional attributes with users or public keys and for +//! managing relationships between CAs. The extensions created using this +//! module can be used with `X509v3Context` objects. +//! +//! # Example +//! +//! ```rust +//! extern crate openssl; +//! +//! use openssl::x509::extension::BasicConstraints; +//! use openssl::x509::X509Extension; +//! +//! fn main() { +//! let mut bc = BasicConstraints::new(); +//! let bc = bc.critical().ca().pathlen(1); +//! +//! let extension: X509Extension = bc.build().unwrap(); +//! } +//! ``` +use std::fmt::Write; + +use error::ErrorStack; +use nid::Nid; +use x509::{X509Extension, X509v3Context}; + +/// An extension which indicates whether a certificate is a CA certificate. +pub struct BasicConstraints { + critical: bool, + ca: bool, + pathlen: Option, +} + +impl BasicConstraints { + /// Construct a new `BasicConstraints` extension. + pub fn new() -> BasicConstraints { + BasicConstraints { + critical: false, + ca: false, + pathlen: None, + } + } + + /// Sets the `critical` flag to `true`. The extension will be critical. + pub fn critical(&mut self) -> &mut BasicConstraints { + self.critical = true; + self + } + + /// Sets the `ca` flag to `true`. + pub fn ca(&mut self) -> &mut BasicConstraints { + self.ca = true; + self + } + + /// Sets the pathlen to an optional non-negative value. The pathlen is the + /// maximum number of CAs that can appear below this one in a chain. + pub fn pathlen(&mut self, pathlen: u32) -> &mut BasicConstraints { + self.pathlen = Some(pathlen); + self + } + + /// Return the `BasicConstraints` extension as an `X509Extension`. + pub fn build(&self) -> Result { + let mut value = String::new(); + if self.critical { + value.push_str("critical,"); + } + value.push_str("CA:"); + if self.ca { + value.push_str("TRUE"); + } else { + value.push_str("FALSE"); + } + if let Some(pathlen) = self.pathlen { + write!(value, ",pathlen:{}", pathlen).unwrap(); + } + X509Extension::new_nid(None, None, Nid::BASIC_CONSTRAINTS, &value) + } +} + +/// An extension consisting of a list of names of the permitted key usages. +pub struct KeyUsage { + critical: bool, + digital_signature: bool, + non_repudiation: bool, + key_encipherment: bool, + data_encipherment: bool, + key_agreement: bool, + key_cert_sign: bool, + crl_sign: bool, + encipher_only: bool, + decipher_only: bool, +} + +impl KeyUsage { + /// Construct a new `KeyUsage` extension. + pub fn new() -> KeyUsage { + KeyUsage { + critical: false, + digital_signature: false, + non_repudiation: false, + key_encipherment: false, + data_encipherment: false, + key_agreement: false, + key_cert_sign: false, + crl_sign: false, + encipher_only: false, + decipher_only: false, + } + } + + /// Sets the `critical` flag to `true`. The extension will be critical. + pub fn critical(&mut self) -> &mut KeyUsage { + self.critical = true; + self + } + + /// Sets the `digitalSignature` flag to `true`. + pub fn digital_signature(&mut self) -> &mut KeyUsage { + self.digital_signature = true; + self + } + + /// Sets the `nonRepudiation` flag to `true`. + pub fn non_repudiation(&mut self) -> &mut KeyUsage { + self.non_repudiation = true; + self + } + + /// Sets the `keyEncipherment` flag to `true`. + pub fn key_encipherment(&mut self) -> &mut KeyUsage { + self.key_encipherment = true; + self + } + + /// Sets the `dataEncipherment` flag to `true`. + pub fn data_encipherment(&mut self) -> &mut KeyUsage { + self.data_encipherment = true; + self + } + + /// Sets the `keyAgreement` flag to `true`. + pub fn key_agreement(&mut self) -> &mut KeyUsage { + self.key_agreement = true; + self + } + + /// Sets the `keyCertSign` flag to `true`. + pub fn key_cert_sign(&mut self) -> &mut KeyUsage { + self.key_cert_sign = true; + self + } + + /// Sets the `cRLSign` flag to `true`. + pub fn crl_sign(&mut self) -> &mut KeyUsage { + self.crl_sign = true; + self + } + + /// Sets the `encipherOnly` flag to `true`. + pub fn encipher_only(&mut self) -> &mut KeyUsage { + self.encipher_only = true; + self + } + + /// Sets the `decipherOnly` flag to `true`. + pub fn decipher_only(&mut self) -> &mut KeyUsage { + self.decipher_only = true; + self + } + + /// Return the `KeyUsage` extension as an `X509Extension`. + pub fn build(&self) -> Result { + let mut value = String::new(); + let mut first = true; + append(&mut value, &mut first, self.critical, "critical"); + append( + &mut value, + &mut first, + self.digital_signature, + "digitalSignature", + ); + append( + &mut value, + &mut first, + self.non_repudiation, + "nonRepudiation", + ); + append( + &mut value, + &mut first, + self.key_encipherment, + "keyEncipherment", + ); + append( + &mut value, + &mut first, + self.data_encipherment, + "dataEncipherment", + ); + append(&mut value, &mut first, self.key_agreement, "keyAgreement"); + append(&mut value, &mut first, self.key_cert_sign, "keyCertSign"); + append(&mut value, &mut first, self.crl_sign, "cRLSign"); + append(&mut value, &mut first, self.encipher_only, "encipherOnly"); + append(&mut value, &mut first, self.decipher_only, "decipherOnly"); + X509Extension::new_nid(None, None, Nid::KEY_USAGE, &value) + } +} + +/// An extension consisting of a list of usages indicating purposes +/// for which the certificate public key can be used for. +pub struct ExtendedKeyUsage { + critical: bool, + server_auth: bool, + client_auth: bool, + code_signing: bool, + email_protection: bool, + time_stamping: bool, + ms_code_ind: bool, + ms_code_com: bool, + ms_ctl_sign: bool, + ms_sgc: bool, + ms_efs: bool, + ns_sgc: bool, + other: Vec, +} + +impl ExtendedKeyUsage { + /// Construct a new `ExtendedKeyUsage` extension. + pub fn new() -> ExtendedKeyUsage { + ExtendedKeyUsage { + critical: false, + server_auth: false, + client_auth: false, + code_signing: false, + email_protection: false, + time_stamping: false, + ms_code_ind: false, + ms_code_com: false, + ms_ctl_sign: false, + ms_sgc: false, + ms_efs: false, + ns_sgc: false, + other: vec![], + } + } + + /// Sets the `critical` flag to `true`. The extension will be critical. + pub fn critical(&mut self) -> &mut ExtendedKeyUsage { + self.critical = true; + self + } + + /// Sets the `serverAuth` flag to `true`. + pub fn server_auth(&mut self) -> &mut ExtendedKeyUsage { + self.server_auth = true; + self + } + + /// Sets the `clientAuth` flag to `true`. + pub fn client_auth(&mut self) -> &mut ExtendedKeyUsage { + self.client_auth = true; + self + } + + /// Sets the `codeSigning` flag to `true`. + pub fn code_signing(&mut self) -> &mut ExtendedKeyUsage { + self.code_signing = true; + self + } + + /// Sets the `timeStamping` flag to `true`. + pub fn time_stamping(&mut self) -> &mut ExtendedKeyUsage { + self.time_stamping = true; + self + } + + /// Sets the `msCodeInd` flag to `true`. + pub fn ms_code_ind(&mut self) -> &mut ExtendedKeyUsage { + self.ms_code_ind = true; + self + } + + /// Sets the `msCodeCom` flag to `true`. + pub fn ms_code_com(&mut self) -> &mut ExtendedKeyUsage { + self.ms_code_com = true; + self + } + + /// Sets the `msCTLSign` flag to `true`. + pub fn ms_ctl_sign(&mut self) -> &mut ExtendedKeyUsage { + self.ms_ctl_sign = true; + self + } + + /// Sets the `msSGC` flag to `true`. + pub fn ms_sgc(&mut self) -> &mut ExtendedKeyUsage { + self.ms_sgc = true; + self + } + + /// Sets the `msEFS` flag to `true`. + pub fn ms_efs(&mut self) -> &mut ExtendedKeyUsage { + self.ms_efs = true; + self + } + + /// Sets the `nsSGC` flag to `true`. + pub fn ns_sgc(&mut self) -> &mut ExtendedKeyUsage { + self.ns_sgc = true; + self + } + + /// Sets a flag not already defined. + pub fn other(&mut self, other: &str) -> &mut ExtendedKeyUsage { + self.other.push(other.to_owned()); + self + } + + /// Return the `ExtendedKeyUsage` extension as an `X509Extension`. + pub fn build(&self) -> Result { + let mut value = String::new(); + let mut first = true; + append(&mut value, &mut first, self.critical, "critical"); + append(&mut value, &mut first, self.server_auth, "serverAuth"); + append(&mut value, &mut first, self.client_auth, "clientAuth"); + append(&mut value, &mut first, self.code_signing, "codeSigning"); + append( + &mut value, + &mut first, + self.email_protection, + "emailProtection", + ); + append(&mut value, &mut first, self.time_stamping, "timeStamping"); + append(&mut value, &mut first, self.ms_code_ind, "msCodeInd"); + append(&mut value, &mut first, self.ms_code_com, "msCodeCom"); + append(&mut value, &mut first, self.ms_ctl_sign, "msCTLSign"); + append(&mut value, &mut first, self.ms_sgc, "msSGC"); + append(&mut value, &mut first, self.ms_efs, "msEFS"); + append(&mut value, &mut first, self.ns_sgc, "nsSGC"); + for other in &self.other { + append(&mut value, &mut first, true, other); + } + X509Extension::new_nid(None, None, Nid::EXT_KEY_USAGE, &value) + } +} + +/// An extension that provides a means of identifying certificates that contain a +/// particular public key. +pub struct SubjectKeyIdentifier { + critical: bool, +} + +impl SubjectKeyIdentifier { + /// Construct a new `SubjectKeyIdentifier` extension. + pub fn new() -> SubjectKeyIdentifier { + SubjectKeyIdentifier { critical: false } + } + + /// Sets the `critical` flag to `true`. The extension will be critical. + pub fn critical(&mut self) -> &mut SubjectKeyIdentifier { + self.critical = true; + self + } + + /// Return a `SubjectKeyIdentifier` extension as an `X509Extension`. + pub fn build(&self, ctx: &X509v3Context) -> Result { + let mut value = String::new(); + let mut first = true; + append(&mut value, &mut first, self.critical, "critical"); + append(&mut value, &mut first, true, "hash"); + X509Extension::new_nid(None, Some(ctx), Nid::SUBJECT_KEY_IDENTIFIER, &value) + } +} + +/// An extension that provides a means of identifying the public key corresponding +/// to the private key used to sign a CRL. +pub struct AuthorityKeyIdentifier { + critical: bool, + keyid: Option, + issuer: Option, +} + +impl AuthorityKeyIdentifier { + /// Construct a new `AuthorityKeyIdentifier` extension. + pub fn new() -> AuthorityKeyIdentifier { + AuthorityKeyIdentifier { + critical: false, + keyid: None, + issuer: None, + } + } + + /// Sets the `critical` flag to `true`. The extension will be critical. + pub fn critical(&mut self) -> &mut AuthorityKeyIdentifier { + self.critical = true; + self + } + + /// Sets the `keyid` flag. + pub fn keyid(&mut self, always: bool) -> &mut AuthorityKeyIdentifier { + self.keyid = Some(always); + self + } + + /// Sets the `issuer` flag. + pub fn issuer(&mut self, always: bool) -> &mut AuthorityKeyIdentifier { + self.issuer = Some(always); + self + } + + /// Return a `AuthorityKeyIdentifier` extension as an `X509Extension`. + pub fn build(&self, ctx: &X509v3Context) -> Result { + let mut value = String::new(); + let mut first = true; + append(&mut value, &mut first, self.critical, "critical"); + match self.keyid { + Some(true) => append(&mut value, &mut first, true, "keyid:always"), + Some(false) => append(&mut value, &mut first, true, "keyid"), + None => {} + } + match self.issuer { + Some(true) => append(&mut value, &mut first, true, "issuer:always"), + Some(false) => append(&mut value, &mut first, true, "issuer"), + None => {} + } + X509Extension::new_nid(None, Some(ctx), Nid::AUTHORITY_KEY_IDENTIFIER, &value) + } +} + +/// An extension that allows additional identities to be bound to the subject +/// of the certificate. +pub struct SubjectAlternativeName { + critical: bool, + names: Vec, +} + +impl SubjectAlternativeName { + /// Construct a new `SubjectAlternativeName` extension. + pub fn new() -> SubjectAlternativeName { + SubjectAlternativeName { + critical: false, + names: vec![], + } + } + + /// Sets the `critical` flag to `true`. The extension will be critical. + pub fn critical(&mut self) -> &mut SubjectAlternativeName { + self.critical = true; + self + } + + /// Sets the `email` flag. + pub fn email(&mut self, email: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("email:{}", email)); + self + } + + /// Sets the `uri` flag. + pub fn uri(&mut self, uri: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("URI:{}", uri)); + self + } + + /// Sets the `dns` flag. + pub fn dns(&mut self, dns: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("DNS:{}", dns)); + self + } + + /// Sets the `rid` flag. + pub fn rid(&mut self, rid: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("RID:{}", rid)); + self + } + + /// Sets the `ip` flag. + pub fn ip(&mut self, ip: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("IP:{}", ip)); + self + } + + /// Sets the `dirName` flag. + pub fn dir_name(&mut self, dir_name: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("dirName:{}", dir_name)); + self + } + + /// Sets the `otherName` flag. + pub fn other_name(&mut self, other_name: &str) -> &mut SubjectAlternativeName { + self.names.push(format!("otherName:{}", other_name)); + self + } + + /// Return a `SubjectAlternativeName` extension as an `X509Extension`. + pub fn build(&self, ctx: &X509v3Context) -> Result { + let mut value = String::new(); + let mut first = true; + append(&mut value, &mut first, self.critical, "critical"); + for name in &self.names { + append(&mut value, &mut first, true, name); + } + X509Extension::new_nid(None, Some(ctx), Nid::SUBJECT_ALT_NAME, &value) + } +} + +fn append(value: &mut String, first: &mut bool, should: bool, element: &str) { + if !should { + return; + } + + if !*first { + value.push(','); + } + *first = false; + value.push_str(element); +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/x509/mod.rs cargo-0.26.0/vendor/openssl-0.10.6/src/x509/mod.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/x509/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/x509/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1288 @@ +//! The standard defining the format of public key certificates. +//! +//! An `X509` certificate binds an identity to a public key, and is either +//! signed by a certificate authority (CA) or self-signed. An entity that gets +//! a hold of a certificate can both verify your identity (via a CA) and encrypt +//! data with the included public key. `X509` certificates are used in many +//! Internet protocols, including SSL/TLS, which is the basis for HTTPS, +//! the secure protocol for browsing the web. + +use libc::{c_int, c_long}; +use ffi; +use foreign_types::{ForeignType, ForeignTypeRef}; +use std::error::Error; +use std::ffi::{CStr, CString}; +use std::fmt; +use std::marker::PhantomData; +use std::mem; +use std::path::Path; +use std::ptr; +use std::slice; +use std::str; + +use {cvt, cvt_n, cvt_p}; +use asn1::{Asn1BitStringRef, Asn1IntegerRef, Asn1ObjectRef, Asn1StringRef, Asn1TimeRef}; +use bio::MemBioSlice; +use conf::ConfRef; +use error::ErrorStack; +use ex_data::Index; +use hash::MessageDigest; +use nid::Nid; +use pkey::{HasPrivate, HasPublic, PKey, PKeyRef, Public}; +use stack::{Stack, StackRef, Stackable}; +use string::OpensslString; +use ssl::SslRef; + +#[cfg(ossl10x)] +use ffi::{ASN1_STRING_data, X509_STORE_CTX_get_chain, X509_set_notAfter, X509_set_notBefore}; +#[cfg(ossl110)] +use ffi::{ASN1_STRING_get0_data as ASN1_STRING_data, + X509_STORE_CTX_get0_chain as X509_STORE_CTX_get_chain, + X509_set1_notAfter as X509_set_notAfter, X509_set1_notBefore as X509_set_notBefore}; + +#[cfg(any(ossl102, ossl110))] +pub mod verify; + +pub mod extension; +pub mod store; + +#[cfg(test)] +mod tests; + +foreign_type_and_impl_send_sync! { + type CType = ffi::X509_STORE_CTX; + fn drop = ffi::X509_STORE_CTX_free; + + /// An `X509` certificate store context. + pub struct X509StoreContext; + + /// Reference to `X509StoreContext`. + pub struct X509StoreContextRef; +} + +impl X509StoreContext { + /// Returns the index which can be used to obtain a reference to the `Ssl` associated with a + /// context. + pub fn ssl_idx() -> Result, ErrorStack> { + unsafe { cvt_n(ffi::SSL_get_ex_data_X509_STORE_CTX_idx()).map(|idx| Index::from_raw(idx)) } + } + + /// Creates a new `X509StoreContext` instance. + /// + /// This corresponds to [`X509_STORE_CTX_new`]. + /// + /// [`X509_STORE_CTX_new`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_STORE_CTX_new.html + pub fn new() -> Result { + unsafe { + ffi::init(); + cvt_p(ffi::X509_STORE_CTX_new()).map(|p| X509StoreContext(p)) + } + } +} + +impl X509StoreContextRef { + /// Returns application data pertaining to an `X509` store context. + /// + /// This corresponds to [`X509_STORE_CTX_get_ex_data`]. + /// + /// [`X509_STORE_CTX_get_ex_data`]: https://www.openssl.org/docs/man1.0.2/crypto/X509_STORE_CTX_get_ex_data.html + pub fn ex_data(&self, index: Index) -> Option<&T> { + unsafe { + let data = ffi::X509_STORE_CTX_get_ex_data(self.as_ptr(), index.as_raw()); + if data.is_null() { + None + } else { + Some(&*(data as *const T)) + } + } + } + + /// Returns the error code of the context. + /// + /// This corresponds to [`X509_STORE_CTX_get_error`]. + /// + /// [`X509_STORE_CTX_get_error`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_STORE_CTX_get_error.html + pub fn error(&self) -> X509VerifyResult { + unsafe { X509VerifyResult::from_raw(ffi::X509_STORE_CTX_get_error(self.as_ptr())) } + } + + /// Initializes this context with the given certificate, certificates chain and certificate + /// store. After initializing the context, the `with_context` closure is called with the prepared + /// context. As long as the closure is running, the context stays initialized and can be used + /// to e.g. verify a certificate. The context will be cleaned up, after the closure finished. + /// + /// * `trust` - The certificate store with the trusted certificates. + /// * `cert` - The certificate that should be verified. + /// * `cert_chain` - The certificates chain. + /// * `with_context` - The closure that is called with the initialized context. + /// + /// This corresponds to [`X509_STORE_CTX_init`] before calling `with_context` and to + /// [`X509_STORE_CTX_cleanup`] after calling `with_context`. + /// + /// [`X509_STORE_CTX_init`]: https://www.openssl.org/docs/man1.0.2/crypto/X509_STORE_CTX_init.html + /// [`X509_STORE_CTX_cleanup`]: https://www.openssl.org/docs/man1.0.2/crypto/X509_STORE_CTX_cleanup.html + pub fn init( + &mut self, + trust: &store::X509StoreRef, + cert: &X509Ref, + cert_chain: &StackRef, + with_context: F, + ) -> Result + where + F: FnOnce(&mut X509StoreContextRef) -> Result, + { + struct Cleanup<'a>(&'a mut X509StoreContextRef); + + impl<'a> Drop for Cleanup<'a> { + fn drop(&mut self) { + unsafe { + ffi::X509_STORE_CTX_cleanup(self.0.as_ptr()); + } + } + } + + unsafe { + cvt(ffi::X509_STORE_CTX_init( + self.as_ptr(), + trust.as_ptr(), + cert.as_ptr(), + cert_chain.as_ptr(), + ))?; + + let cleanup = Cleanup(self); + with_context(cleanup.0) + } + } + + /// Verifies the stored certificate. + /// + /// Returns `true` if verification succeeds. The `error` method will return the specific + /// validation error if the certificate was not valid. + /// + /// This will only work inside of a call to `init`. + /// + /// This corresponds to [`X509_verify_cert`]. + /// + /// [`X509_verify_cert`]: https://www.openssl.org/docs/man1.0.2/crypto/X509_verify_cert.html + pub fn verify_cert(&mut self) -> Result { + unsafe { cvt_n(ffi::X509_verify_cert(self.as_ptr())).map(|n| n != 0) } + } + + /// Set the error code of the context. + /// + /// This corresponds to [`X509_STORE_CTX_set_error`]. + /// + /// [`X509_STORE_CTX_set_error`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_STORE_CTX_set_error.html + pub fn set_error(&mut self, result: X509VerifyResult) { + unsafe { + ffi::X509_STORE_CTX_set_error(self.as_ptr(), result.as_raw()); + } + } + + /// Returns a reference to the certificate which caused the error or None if + /// no certificate is relevant to the error. + /// + /// This corresponds to [`X509_STORE_CTX_get_current_cert`]. + /// + /// [`X509_STORE_CTX_get_current_cert`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_STORE_CTX_get_current_cert.html + pub fn current_cert(&self) -> Option<&X509Ref> { + unsafe { + let ptr = ffi::X509_STORE_CTX_get_current_cert(self.as_ptr()); + if ptr.is_null() { + None + } else { + Some(X509Ref::from_ptr(ptr)) + } + } + } + + /// Returns a non-negative integer representing the depth in the certificate + /// chain where the error occurred. If it is zero it occurred in the end + /// entity certificate, one if it is the certificate which signed the end + /// entity certificate and so on. + /// + /// This corresponds to [`X509_STORE_CTX_get_error_depth`]. + /// + /// [`X509_STORE_CTX_get_error_depth`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_STORE_CTX_get_error_depth.html + pub fn error_depth(&self) -> u32 { + unsafe { ffi::X509_STORE_CTX_get_error_depth(self.as_ptr()) as u32 } + } + + /// Returns a reference to a complete valid `X509` certificate chain. + /// + /// This corresponds to [`X509_STORE_CTX_get0_chain`]. + /// + /// [`X509_STORE_CTX_get0_chain`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_STORE_CTX_get0_chain.html + pub fn chain(&self) -> Option<&StackRef> { + unsafe { + let chain = X509_STORE_CTX_get_chain(self.as_ptr()); + + if chain.is_null() { + None + } else { + Some(StackRef::from_ptr(chain)) + } + } + } +} + +/// A builder used to construct an `X509`. +pub struct X509Builder(X509); + +impl X509Builder { + /// Creates a new builder. + pub fn new() -> Result { + unsafe { + ffi::init(); + cvt_p(ffi::X509_new()).map(|p| X509Builder(X509(p))) + } + } + + /// Sets the notAfter constraint on the certificate. + pub fn set_not_after(&mut self, not_after: &Asn1TimeRef) -> Result<(), ErrorStack> { + unsafe { cvt(X509_set_notAfter(self.0.as_ptr(), not_after.as_ptr())).map(|_| ()) } + } + + /// Sets the notBefore constraint on the certificate. + pub fn set_not_before(&mut self, not_before: &Asn1TimeRef) -> Result<(), ErrorStack> { + unsafe { cvt(X509_set_notBefore(self.0.as_ptr(), not_before.as_ptr())).map(|_| ()) } + } + + /// Sets the version of the certificate. + /// + /// Note that the version is zero-indexed; that is, a certificate corresponding to version 3 of + /// the X.509 standard should pass `2` to this method. + pub fn set_version(&mut self, version: i32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::X509_set_version(self.0.as_ptr(), version.into())).map(|_| ()) } + } + + /// Sets the serial number of the certificate. + pub fn set_serial_number(&mut self, serial_number: &Asn1IntegerRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::X509_set_serialNumber( + self.0.as_ptr(), + serial_number.as_ptr(), + )).map(|_| ()) + } + } + + /// Sets the issuer name of the certificate. + pub fn set_issuer_name(&mut self, issuer_name: &X509NameRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::X509_set_issuer_name( + self.0.as_ptr(), + issuer_name.as_ptr(), + )).map(|_| ()) + } + } + + /// Sets the subject name of the certificate. + /// + /// When building certificates, the `C`, `ST`, and `O` options are common when using the openssl command line tools. + /// The `CN` field is used for the common name, such as a DNS name. + /// + /// ``` + /// use openssl::x509::{X509, X509NameBuilder}; + /// + /// let mut x509_name = openssl::x509::X509NameBuilder::new().unwrap(); + /// x509_name.append_entry_by_text("C", "US").unwrap(); + /// x509_name.append_entry_by_text("ST", "CA").unwrap(); + /// x509_name.append_entry_by_text("O", "Some organization").unwrap(); + /// x509_name.append_entry_by_text("CN", "www.example.com").unwrap(); + /// let x509_name = x509_name.build(); + /// + /// let mut x509 = openssl::x509::X509::builder().unwrap(); + /// x509.set_subject_name(&x509_name).unwrap(); + /// ``` + pub fn set_subject_name(&mut self, subject_name: &X509NameRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::X509_set_subject_name( + self.0.as_ptr(), + subject_name.as_ptr(), + )).map(|_| ()) + } + } + + /// Sets the public key associated with the certificate. + pub fn set_pubkey(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> + where + T: HasPublic, + { + unsafe { cvt(ffi::X509_set_pubkey(self.0.as_ptr(), key.as_ptr())).map(|_| ()) } + } + + /// Returns a context object which is needed to create certain X509 extension values. + /// + /// Set `issuer` to `None` if the certificate will be self-signed. + pub fn x509v3_context<'a>( + &'a self, + issuer: Option<&'a X509Ref>, + conf: Option<&'a ConfRef>, + ) -> X509v3Context<'a> { + unsafe { + let mut ctx = mem::zeroed(); + + let issuer = match issuer { + Some(issuer) => issuer.as_ptr(), + None => self.0.as_ptr(), + }; + let subject = self.0.as_ptr(); + ffi::X509V3_set_ctx( + &mut ctx, + issuer, + subject, + ptr::null_mut(), + ptr::null_mut(), + 0, + ); + + // nodb case taken care of since we zeroed ctx above + if let Some(conf) = conf { + ffi::X509V3_set_nconf(&mut ctx, conf.as_ptr()); + } + + X509v3Context(ctx, PhantomData) + } + } + + /// Adds an X509 extension value to the certificate. + pub fn append_extension(&mut self, extension: X509Extension) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::X509_add_ext(self.0.as_ptr(), extension.as_ptr(), -1))?; + mem::forget(extension); + Ok(()) + } + } + + /// Signs the certificate with a private key. + pub fn sign(&mut self, key: &PKeyRef, hash: MessageDigest) -> Result<(), ErrorStack> + where + T: HasPrivate, + { + unsafe { cvt(ffi::X509_sign(self.0.as_ptr(), key.as_ptr(), hash.as_ptr())).map(|_| ()) } + } + + /// Consumes the builder, returning the certificate. + pub fn build(self) -> X509 { + self.0 + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::X509; + fn drop = ffi::X509_free; + + /// An `X509` public key certificate. + pub struct X509; + /// Reference to `X509`. + pub struct X509Ref; +} + +impl X509Ref { + /// Returns this certificate's subject name. + /// + /// This corresponds to [`X509_get_subject_name`]. + /// + /// [`X509_get_subject_name`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_get_subject_name.html + pub fn subject_name(&self) -> &X509NameRef { + unsafe { + let name = ffi::X509_get_subject_name(self.as_ptr()); + assert!(!name.is_null()); + X509NameRef::from_ptr(name) + } + } + + /// Returns this certificate's issuer name. + /// + /// This corresponds to [`X509_get_issuer_name`]. + /// + /// [`X509_get_issuer_name`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_get_subject_name.html + pub fn issuer_name(&self) -> &X509NameRef { + unsafe { + let name = ffi::X509_get_issuer_name(self.as_ptr()); + assert!(!name.is_null()); + X509NameRef::from_ptr(name) + } + } + + /// Returns this certificate's subject alternative name entries, if they exist. + /// + /// This corresponds to [`X509_get_ext_d2i`] called with `NID_subject_alt_name`. + /// + /// [`X509_get_ext_d2i`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_get_ext_d2i.html + pub fn subject_alt_names(&self) -> Option> { + unsafe { + let stack = ffi::X509_get_ext_d2i( + self.as_ptr(), + ffi::NID_subject_alt_name, + ptr::null_mut(), + ptr::null_mut(), + ); + if stack.is_null() { + None + } else { + Some(Stack::from_ptr(stack as *mut _)) + } + } + } + + /// Returns this certificate's issuer alternative name entries, if they exist. + /// + /// This corresponds to [`X509_get_ext_d2i`] called with `NID_issuer_alt_name`. + /// + /// [`X509_get_ext_d2i`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_get_ext_d2i.html + pub fn issuer_alt_names(&self) -> Option> { + unsafe { + let stack = ffi::X509_get_ext_d2i( + self.as_ptr(), + ffi::NID_issuer_alt_name, + ptr::null_mut(), + ptr::null_mut(), + ); + if stack.is_null() { + None + } else { + Some(Stack::from_ptr(stack as *mut _)) + } + } + } + + pub fn public_key(&self) -> Result, ErrorStack> { + unsafe { + let pkey = cvt_p(ffi::X509_get_pubkey(self.as_ptr()))?; + Ok(PKey::from_ptr(pkey)) + } + } + + /// Returns certificate fingerprint calculated using provided hash + pub fn fingerprint(&self, hash_type: MessageDigest) -> Result, ErrorStack> { + unsafe { + let evp = hash_type.as_ptr(); + let mut len = ffi::EVP_MAX_MD_SIZE; + let mut buf = vec![0u8; len as usize]; + cvt(ffi::X509_digest( + self.as_ptr(), + evp, + buf.as_mut_ptr() as *mut _, + &mut len, + ))?; + buf.truncate(len as usize); + Ok(buf) + } + } + + /// Returns the certificate's Not After validity period. + pub fn not_after(&self) -> &Asn1TimeRef { + unsafe { + let date = compat::X509_get_notAfter(self.as_ptr()); + assert!(!date.is_null()); + Asn1TimeRef::from_ptr(date) + } + } + + /// Returns the certificate's Not Before validity period. + pub fn not_before(&self) -> &Asn1TimeRef { + unsafe { + let date = compat::X509_get_notBefore(self.as_ptr()); + assert!(!date.is_null()); + Asn1TimeRef::from_ptr(date) + } + } + + /// Returns the certificate's signature + pub fn signature(&self) -> &Asn1BitStringRef { + unsafe { + let mut signature = ptr::null(); + compat::X509_get0_signature(&mut signature, ptr::null_mut(), self.as_ptr()); + assert!(!signature.is_null()); + Asn1BitStringRef::from_ptr(signature as *mut _) + } + } + + /// Returns the certificate's signature algorithm. + pub fn signature_algorithm(&self) -> &X509AlgorithmRef { + unsafe { + let mut algor = ptr::null(); + compat::X509_get0_signature(ptr::null_mut(), &mut algor, self.as_ptr()); + assert!(!algor.is_null()); + X509AlgorithmRef::from_ptr(algor as *mut _) + } + } + + /// Returns the list of OCSP responder URLs specified in the certificate's Authority Information + /// Access field. + pub fn ocsp_responders(&self) -> Result, ErrorStack> { + unsafe { cvt_p(ffi::X509_get1_ocsp(self.as_ptr())).map(|p| Stack::from_ptr(p)) } + } + + /// Checks that this certificate issued `subject`. + pub fn issued(&self, subject: &X509Ref) -> X509VerifyResult { + unsafe { + let r = ffi::X509_check_issued(self.as_ptr(), subject.as_ptr()); + X509VerifyResult::from_raw(r) + } + } + + /// Returns this certificate's serial number. + /// + /// This corresponds to [`X509_get_serialNumber`]. + /// + /// [`X509_get_serialNumber`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_get_serialNumber.html + pub fn serial_number(&self) -> &Asn1IntegerRef { + unsafe { + let r = ffi::X509_get_serialNumber(self.as_ptr()); + assert!(!r.is_null()); + Asn1IntegerRef::from_ptr(r) + } + } + + to_pem! { + /// Serializes the certificate into a PEM-encoded X509 structure. + /// + /// The output will have a header of `-----BEGIN CERTIFICATE-----`. + /// + /// This corresponds to [`PEM_write_bio_X509`]. + /// + /// [`PEM_write_bio_X509`]: https://www.openssl.org/docs/man1.0.2/crypto/PEM_write_bio_X509.html + to_pem, + ffi::PEM_write_bio_X509 + } + + to_der! { + /// Serializes the certificate into a DER-encoded X509 structure. + /// + /// This corresponds to [`i2d_X509`]. + /// + /// [`i2d_X509`]: https://www.openssl.org/docs/man1.1.0/crypto/i2d_X509.html + to_der, + ffi::i2d_X509 + } +} + +impl ToOwned for X509Ref { + type Owned = X509; + + fn to_owned(&self) -> X509 { + unsafe { + compat::X509_up_ref(self.as_ptr()); + X509::from_ptr(self.as_ptr()) + } + } +} + +impl X509 { + /// Returns a new builder. + pub fn builder() -> Result { + X509Builder::new() + } + + from_pem! { + /// Deserializes a PEM-encoded X509 structure. + /// + /// The input should have a header of `-----BEGIN CERTIFICATE-----`. + /// + /// This corresponds to [`PEM_read_bio_X509`]. + /// + /// [`PEM_read_bio_X509`]: https://www.openssl.org/docs/man1.0.2/crypto/PEM_read_bio_X509.html + from_pem, + X509, + ffi::PEM_read_bio_X509 + } + + from_der! { + /// Deserializes a DER-encoded X509 structure. + /// + /// This corresponds to [`d2i_X509`]. + /// + /// [`d2i_X509`]: https://www.openssl.org/docs/manmaster/man3/d2i_X509.html + from_der, + X509, + ffi::d2i_X509 + } + + /// Deserializes a list of PEM-formatted certificates. + pub fn stack_from_pem(pem: &[u8]) -> Result, ErrorStack> { + unsafe { + ffi::init(); + let bio = MemBioSlice::new(pem)?; + + let mut certs = vec![]; + loop { + let r = + ffi::PEM_read_bio_X509(bio.as_ptr(), ptr::null_mut(), None, ptr::null_mut()); + if r.is_null() { + let err = ffi::ERR_peek_last_error(); + if ffi::ERR_GET_LIB(err) == ffi::ERR_LIB_PEM + && ffi::ERR_GET_REASON(err) == ffi::PEM_R_NO_START_LINE + { + ffi::ERR_clear_error(); + break; + } + + return Err(ErrorStack::get()); + } else { + certs.push(X509(r)); + } + } + + Ok(certs) + } + } +} + +impl Clone for X509 { + fn clone(&self) -> X509 { + X509Ref::to_owned(self) + } +} + +impl AsRef for X509Ref { + fn as_ref(&self) -> &X509Ref { + self + } +} + +impl Stackable for X509 { + type StackType = ffi::stack_st_X509; +} + +/// A context object required to construct certain `X509` extension values. +pub struct X509v3Context<'a>(ffi::X509V3_CTX, PhantomData<(&'a X509Ref, &'a ConfRef)>); + +impl<'a> X509v3Context<'a> { + pub fn as_ptr(&self) -> *mut ffi::X509V3_CTX { + &self.0 as *const _ as *mut _ + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::X509_EXTENSION; + fn drop = ffi::X509_EXTENSION_free; + + /// Permit additional fields to be added to an `X509` v3 certificate. + pub struct X509Extension; + /// Reference to `X509Extension`. + pub struct X509ExtensionRef; +} + +impl Stackable for X509Extension { + type StackType = ffi::stack_st_X509_EXTENSION; +} + +impl X509Extension { + /// Constructs an X509 extension value. See `man x509v3_config` for information on supported + /// names and their value formats. + /// + /// Some extension types, such as `subjectAlternativeName`, require an `X509v3Context` to be + /// provided. + /// + /// See the extension module for builder types which will construct certain common extensions. + pub fn new( + conf: Option<&ConfRef>, + context: Option<&X509v3Context>, + name: &str, + value: &str, + ) -> Result { + let name = CString::new(name).unwrap(); + let value = CString::new(value).unwrap(); + unsafe { + ffi::init(); + let conf = conf.map_or(ptr::null_mut(), ConfRef::as_ptr); + let context = context.map_or(ptr::null_mut(), X509v3Context::as_ptr); + let name = name.as_ptr() as *mut _; + let value = value.as_ptr() as *mut _; + + cvt_p(ffi::X509V3_EXT_nconf(conf, context, name, value)).map(X509Extension) + } + } + + /// Constructs an X509 extension value. See `man x509v3_config` for information on supported + /// extensions and their value formats. + /// + /// Some extension types, such as `nid::SUBJECT_ALTERNATIVE_NAME`, require an `X509v3Context` to + /// be provided. + /// + /// See the extension module for builder types which will construct certain common extensions. + pub fn new_nid( + conf: Option<&ConfRef>, + context: Option<&X509v3Context>, + name: Nid, + value: &str, + ) -> Result { + let value = CString::new(value).unwrap(); + unsafe { + ffi::init(); + let conf = conf.map_or(ptr::null_mut(), ConfRef::as_ptr); + let context = context.map_or(ptr::null_mut(), X509v3Context::as_ptr); + let name = name.as_raw(); + let value = value.as_ptr() as *mut _; + + cvt_p(ffi::X509V3_EXT_nconf_nid(conf, context, name, value)).map(X509Extension) + } + } +} + +/// A builder used to construct an `X509Name`. +pub struct X509NameBuilder(X509Name); + +impl X509NameBuilder { + /// Creates a new builder. + pub fn new() -> Result { + unsafe { + ffi::init(); + cvt_p(ffi::X509_NAME_new()).map(|p| X509NameBuilder(X509Name(p))) + } + } + + /// Add a field entry by str. + /// + /// This corresponds to [`X509_NAME_add_entry_by_txt`]. + /// + /// [`X509_NAME_add_entry_by_txt`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_NAME_add_entry_by_txt.html + pub fn append_entry_by_text(&mut self, field: &str, value: &str) -> Result<(), ErrorStack> { + unsafe { + let field = CString::new(field).unwrap(); + assert!(value.len() <= c_int::max_value() as usize); + cvt(ffi::X509_NAME_add_entry_by_txt( + self.0.as_ptr(), + field.as_ptr() as *mut _, + ffi::MBSTRING_UTF8, + value.as_ptr(), + value.len() as c_int, + -1, + 0, + )).map(|_| ()) + } + } + + /// Add a field entry by NID. + /// + /// This corresponds to [`X509_NAME_add_entry_by_NID`]. + /// + /// [`X509_NAME_add_entry_by_NID`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_NAME_add_entry_by_NID.html + pub fn append_entry_by_nid(&mut self, field: Nid, value: &str) -> Result<(), ErrorStack> { + unsafe { + assert!(value.len() <= c_int::max_value() as usize); + cvt(ffi::X509_NAME_add_entry_by_NID( + self.0.as_ptr(), + field.as_raw(), + ffi::MBSTRING_UTF8, + value.as_ptr() as *mut _, + value.len() as c_int, + -1, + 0, + )).map(|_| ()) + } + } + + /// Return an `X509Name`. + pub fn build(self) -> X509Name { + self.0 + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::X509_NAME; + fn drop = ffi::X509_NAME_free; + + /// The names of an `X509` certificate. + pub struct X509Name; + /// Reference to `X509Name`. + pub struct X509NameRef; +} + +impl X509Name { + /// Returns a new builder. + pub fn builder() -> Result { + X509NameBuilder::new() + } + + /// Loads subject names from a file containing PEM-formatted certificates. + /// + /// This is commonly used in conjunction with `SslContextBuilder::set_client_ca_list`. + pub fn load_client_ca_file>(file: P) -> Result, ErrorStack> { + let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); + unsafe { cvt_p(ffi::SSL_load_client_CA_file(file.as_ptr())).map(|p| Stack::from_ptr(p)) } + } +} + +impl Stackable for X509Name { + type StackType = ffi::stack_st_X509_NAME; +} + +impl X509NameRef { + /// Returns the name entries by the nid. + pub fn entries_by_nid<'a>(&'a self, nid: Nid) -> X509NameEntries<'a> { + X509NameEntries { + name: self, + nid: nid, + loc: -1, + } + } +} + +/// A type to destructure and examine an `X509Name`. +pub struct X509NameEntries<'a> { + name: &'a X509NameRef, + nid: Nid, + loc: c_int, +} + +impl<'a> Iterator for X509NameEntries<'a> { + type Item = &'a X509NameEntryRef; + + fn next(&mut self) -> Option<&'a X509NameEntryRef> { + unsafe { + self.loc = + ffi::X509_NAME_get_index_by_NID(self.name.as_ptr(), self.nid.as_raw(), self.loc); + + if self.loc == -1 { + return None; + } + + let entry = ffi::X509_NAME_get_entry(self.name.as_ptr(), self.loc); + assert!(!entry.is_null()); + + Some(X509NameEntryRef::from_ptr(entry)) + } + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::X509_NAME_ENTRY; + fn drop = ffi::X509_NAME_ENTRY_free; + + /// A name entry associated with a `X509Name`. + pub struct X509NameEntry; + /// Reference to `X509NameEntry`. + pub struct X509NameEntryRef; +} + +impl X509NameEntryRef { + /// Returns the field value of an `X509NameEntry`. + /// + /// This corresponds to [`X509_NAME_ENTRY_get_data`]. + /// + /// [`X509_NAME_ENTRY_get_data`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_NAME_ENTRY_get_data.html + pub fn data(&self) -> &Asn1StringRef { + unsafe { + let data = ffi::X509_NAME_ENTRY_get_data(self.as_ptr()); + Asn1StringRef::from_ptr(data) + } + } +} + +/// A builder used to construct an `X509Req`. +pub struct X509ReqBuilder(X509Req); + +impl X509ReqBuilder { + /// Returns a builder for a certificate request. + /// + /// This corresponds to [`X509_REQ_new`]. + /// + ///[`X509_REQ_new`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_REQ_new.html + pub fn new() -> Result { + unsafe { + ffi::init(); + cvt_p(ffi::X509_REQ_new()).map(|p| X509ReqBuilder(X509Req(p))) + } + } + + /// Set the numerical value of the version field. + /// + /// This corresponds to [`X509_REQ_set_version`]. + /// + ///[`X509_REQ_set_version`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_REQ_set_version.html + pub fn set_version(&mut self, version: i32) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::X509_REQ_set_version(self.0.as_ptr(), version.into())).map(|_| ()) } + } + + /// Set the issuer name. + /// + /// This corresponds to [`X509_REQ_set_subject_name`]. + /// + /// [`X509_REQ_set_subject_name`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_REQ_set_subject_name.html + pub fn set_subject_name(&mut self, subject_name: &X509NameRef) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::X509_REQ_set_subject_name( + self.0.as_ptr(), + subject_name.as_ptr(), + )).map(|_| ()) + } + } + + /// Set the public key. + /// + /// This corresponds to [`X509_REQ_set_pubkey`]. + /// + /// [`X509_REQ_set_pubkey`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_REQ_set_pubkey.html + pub fn set_pubkey(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> + where + T: HasPublic, + { + unsafe { cvt(ffi::X509_REQ_set_pubkey(self.0.as_ptr(), key.as_ptr())).map(|_| ()) } + } + + /// Return an `X509v3Context`. This context object can be used to construct + /// certain `X509` extensions. + pub fn x509v3_context<'a>(&'a self, conf: Option<&'a ConfRef>) -> X509v3Context<'a> { + unsafe { + let mut ctx = mem::zeroed(); + + ffi::X509V3_set_ctx( + &mut ctx, + ptr::null_mut(), + ptr::null_mut(), + self.0.as_ptr(), + ptr::null_mut(), + 0, + ); + + // nodb case taken care of since we zeroed ctx above + if let Some(conf) = conf { + ffi::X509V3_set_nconf(&mut ctx, conf.as_ptr()); + } + + X509v3Context(ctx, PhantomData) + } + } + + /// Permits any number of extension fields to be added to the certificate. + pub fn add_extensions( + &mut self, + extensions: &StackRef, + ) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::X509_REQ_add_extensions( + self.0.as_ptr(), + extensions.as_ptr(), + )).map(|_| ()) + } + } + + /// Sign the request using a private key. + /// + /// This corresponds to [`X509_REQ_sign`]. + /// + /// [`X509_REQ_sign`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_REQ_sign.html + pub fn sign(&mut self, key: &PKeyRef, hash: MessageDigest) -> Result<(), ErrorStack> + where + T: HasPrivate, + { + unsafe { + cvt(ffi::X509_REQ_sign( + self.0.as_ptr(), + key.as_ptr(), + hash.as_ptr(), + )).map(|_| ()) + } + } + + /// Returns the `X509Req`. + pub fn build(self) -> X509Req { + self.0 + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::X509_REQ; + fn drop = ffi::X509_REQ_free; + + /// An `X509` certificate request. + pub struct X509Req; + /// Reference to `X509Req`. + pub struct X509ReqRef; +} + +impl X509Req { + /// A builder for `X509Req`. + pub fn builder() -> Result { + X509ReqBuilder::new() + } + + from_pem! { + /// Deserializes a PEM-encoded PKCS#10 certificate request structure. + /// + /// The input should have a header of `-----BEGIN CERTIFICATE REQUEST-----`. + /// + /// This corresponds to [`PEM_read_bio_X509_REQ`]. + /// + /// [`PEM_read_bio_X509_REQ`]: https://www.openssl.org/docs/man1.0.2/crypto/PEM_read_bio_X509_REQ.html + from_pem, + X509Req, + ffi::PEM_read_bio_X509_REQ + } + + from_der! { + /// Deserializes a DER-encoded PKCS#10 certificate request structure. + /// + /// This corresponds to [`d2i_X509_REQ`]. + /// + /// [`d2i_X509_REQ`]: https://www.openssl.org/docs/man1.1.0/crypto/d2i_X509_REQ.html + from_der, + X509Req, + ffi::d2i_X509_REQ + } +} + +impl X509ReqRef { + to_pem! { + /// Serializes the certificate request to a PEM-encoded PKCS#10 structure. + /// + /// The output will have a header of `-----BEGIN CERTIFICATE REQUEST-----`. + /// + /// This corresponds to [`PEM_write_bio_X509_REQ`]. + /// + /// [`PEM_write_bio_X509_REQ`]: https://www.openssl.org/docs/man1.0.2/crypto/PEM_write_bio_X509_REQ.html + to_pem, + ffi::PEM_write_bio_X509_REQ + } + + to_der! { + /// Serializes the certificate request to a DER-encoded PKCS#10 structure. + /// + /// This corresponds to [`i2d_X509_REQ`]. + /// + /// [`i2d_X509_REQ`]: https://www.openssl.org/docs/man1.0.2/crypto/i2d_X509_REQ.html + to_der, + ffi::i2d_X509_REQ + } + + /// Returns the numerical value of the version field of the certificate request. + /// + /// This corresponds to [`X509_REQ_get_version`] + /// + /// [`X509_REQ_get_version`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_REQ_get_version.html + pub fn version(&self) -> i32 { + unsafe { compat::X509_REQ_get_version(self.as_ptr()) as i32 } + } + + /// Returns the subject name of the certificate request. + /// + /// This corresponds to [`X509_REQ_get_subject_name`] + /// + /// [`X509_REQ_get_subject_name`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_REQ_get_subject_name.html + pub fn subject_name(&self) -> &X509NameRef { + unsafe { + let name = compat::X509_REQ_get_subject_name(self.as_ptr()); + assert!(!name.is_null()); + X509NameRef::from_ptr(name) + } + } +} + +/// The result of peer certificate verification. +#[derive(Copy, Clone, PartialEq, Eq)] +pub struct X509VerifyResult(c_int); + +impl fmt::Debug for X509VerifyResult { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("X509VerifyResult") + .field("code", &self.0) + .field("error", &self.error_string()) + .finish() + } +} + +impl fmt::Display for X509VerifyResult { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str(self.error_string()) + } +} + +impl Error for X509VerifyResult { + fn description(&self) -> &str { + "an X509 validation error" + } +} + +impl X509VerifyResult { + /// Creates an `X509VerifyResult` from a raw error number. + /// + /// # Safety + /// + /// Some methods on `X509VerifyResult` are not thread safe if the error + /// number is invalid. + pub unsafe fn from_raw(err: c_int) -> X509VerifyResult { + X509VerifyResult(err) + } + + /// Return the integer representation of an `X509VerifyResult`. + pub fn as_raw(&self) -> c_int { + self.0 + } + + /// Return a human readable error string from the verification error. + /// + /// This corresponds to [`X509_verify_cert_error_string`]. + /// + /// [`X509_verify_cert_error_string`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_verify_cert_error_string.html + pub fn error_string(&self) -> &'static str { + ffi::init(); + + unsafe { + let s = ffi::X509_verify_cert_error_string(self.0 as c_long); + str::from_utf8(CStr::from_ptr(s).to_bytes()).unwrap() + } + } + + /// Successful peer certifiate verification. + pub const OK: X509VerifyResult = X509VerifyResult(ffi::X509_V_OK); + /// Application verification failure. + pub const APPLICATION_VERIFICATION: X509VerifyResult = + X509VerifyResult(ffi::X509_V_ERR_APPLICATION_VERIFICATION); +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::GENERAL_NAME; + fn drop = ffi::GENERAL_NAME_free; + + /// An `X509` certificate alternative names. + pub struct GeneralName; + /// Reference to `GeneralName`. + pub struct GeneralNameRef; +} + +impl GeneralNameRef { + fn ia5_string(&self, ffi_type: c_int) -> Option<&str> { + unsafe { + if (*self.as_ptr()).type_ != ffi_type { + return None; + } + + let ptr = ASN1_STRING_data((*self.as_ptr()).d as *mut _); + let len = ffi::ASN1_STRING_length((*self.as_ptr()).d as *mut _); + + let slice = slice::from_raw_parts(ptr as *const u8, len as usize); + // IA5Strings are stated to be ASCII (specifically IA5). Hopefully + // OpenSSL checks that when loading a certificate but if not we'll + // use this instead of from_utf8_unchecked just in case. + str::from_utf8(slice).ok() + } + } + + /// Returns the contents of this `GeneralName` if it is an `rfc822Name`. + pub fn email(&self) -> Option<&str> { + self.ia5_string(ffi::GEN_EMAIL) + } + + /// Returns the contents of this `GeneralName` if it is a `dNSName`. + pub fn dnsname(&self) -> Option<&str> { + self.ia5_string(ffi::GEN_DNS) + } + + /// Returns the contents of this `GeneralName` if it is an `uniformResourceIdentifier`. + pub fn uri(&self) -> Option<&str> { + self.ia5_string(ffi::GEN_URI) + } + + /// Returns the contents of this `GeneralName` if it is an `iPAddress`. + pub fn ipaddress(&self) -> Option<&[u8]> { + unsafe { + if (*self.as_ptr()).type_ != ffi::GEN_IPADD { + return None; + } + + let ptr = ASN1_STRING_data((*self.as_ptr()).d as *mut _); + let len = ffi::ASN1_STRING_length((*self.as_ptr()).d as *mut _); + + Some(slice::from_raw_parts(ptr as *const u8, len as usize)) + } + } +} + +impl Stackable for GeneralName { + type StackType = ffi::stack_st_GENERAL_NAME; +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::X509_ALGOR; + fn drop = ffi::X509_ALGOR_free; + + /// An `X509` certificate signature algorithm. + pub struct X509Algorithm; + /// Reference to `X509Algorithm`. + pub struct X509AlgorithmRef; +} + +impl X509AlgorithmRef { + /// Returns the ASN.1 OID of this algorithm. + pub fn object(&self) -> &Asn1ObjectRef { + unsafe { + let mut oid = ptr::null(); + compat::X509_ALGOR_get0(&mut oid, ptr::null_mut(), ptr::null_mut(), self.as_ptr()); + assert!(!oid.is_null()); + Asn1ObjectRef::from_ptr(oid as *mut _) + } + } +} + +#[cfg(ossl110)] +mod compat { + pub use ffi::X509_getm_notAfter as X509_get_notAfter; + pub use ffi::X509_getm_notBefore as X509_get_notBefore; + pub use ffi::X509_up_ref; + pub use ffi::X509_REQ_get_version; + pub use ffi::X509_REQ_get_subject_name; + pub use ffi::X509_get0_signature; + pub use ffi::X509_ALGOR_get0; +} + +#[cfg(ossl10x)] +#[allow(bad_style)] +mod compat { + use libc::{c_int, c_void}; + use ffi; + + pub unsafe fn X509_get_notAfter(x: *mut ffi::X509) -> *mut ffi::ASN1_TIME { + (*(*(*x).cert_info).validity).notAfter + } + + pub unsafe fn X509_get_notBefore(x: *mut ffi::X509) -> *mut ffi::ASN1_TIME { + (*(*(*x).cert_info).validity).notBefore + } + + pub unsafe fn X509_up_ref(x: *mut ffi::X509) { + ffi::CRYPTO_add_lock( + &mut (*x).references, + 1, + ffi::CRYPTO_LOCK_X509, + "mod.rs\0".as_ptr() as *const _, + line!() as c_int, + ); + } + + pub unsafe fn X509_REQ_get_version(x: *mut ffi::X509_REQ) -> ::libc::c_long { + ::ffi::ASN1_INTEGER_get((*(*x).req_info).version) + } + + pub unsafe fn X509_REQ_get_subject_name(x: *mut ffi::X509_REQ) -> *mut ::ffi::X509_NAME { + (*(*x).req_info).subject + } + + pub unsafe fn X509_get0_signature( + psig: *mut *const ffi::ASN1_BIT_STRING, + palg: *mut *const ffi::X509_ALGOR, + x: *const ffi::X509, + ) { + if !psig.is_null() { + *psig = (*x).signature; + } + if !palg.is_null() { + *palg = (*x).sig_alg; + } + } + + pub unsafe fn X509_ALGOR_get0( + paobj: *mut *const ffi::ASN1_OBJECT, + pptype: *mut c_int, + pval: *mut *mut c_void, + alg: *const ffi::X509_ALGOR, + ) { + if !paobj.is_null() { + *paobj = (*alg).algorithm; + } + assert!(pptype.is_null()); + assert!(pval.is_null()); + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/x509/store.rs cargo-0.26.0/vendor/openssl-0.10.6/src/x509/store.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/x509/store.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/x509/store.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,108 @@ +//! Describe a context in which to verify an `X509` certificate. +//! +//! The `X509` certificate store holds trusted CA certificates used to verify +//! peer certificates. +//! +//! # Example +//! +//! ```rust +//! +//! extern crate openssl; +//! +//! use openssl::x509::store::{X509StoreBuilder, X509Store}; +//! use openssl::x509::{X509, X509Name}; +//! use openssl::pkey::PKey; +//! use openssl::hash::MessageDigest; +//! use openssl::rsa::Rsa; +//! use openssl::nid::Nid; +//! +//! fn main() { +//! let rsa = Rsa::generate(2048).unwrap(); +//! let pkey = PKey::from_rsa(rsa).unwrap(); +//! +//! let mut name = X509Name::builder().unwrap(); +//! name.append_entry_by_nid(Nid::COMMONNAME, "foobar.com").unwrap(); +//! let name = name.build(); +//! +//! let mut builder = X509::builder().unwrap(); +//! builder.set_version(2).unwrap(); +//! builder.set_subject_name(&name).unwrap(); +//! builder.set_issuer_name(&name).unwrap(); +//! builder.set_pubkey(&pkey).unwrap(); +//! builder.sign(&pkey, MessageDigest::sha256()).unwrap(); +//! +//! let certificate: X509 = builder.build(); +//! +//! let mut builder = X509StoreBuilder::new().unwrap(); +//! let _ = builder.add_cert(certificate); +//! +//! let store: X509Store = builder.build(); +//! } +//! ``` + +use ffi; +use foreign_types::ForeignTypeRef; +use std::mem; + +use {cvt, cvt_p}; +use error::ErrorStack; +use x509::X509; + +foreign_type! { + type CType = ffi::X509_STORE; + fn drop = ffi::X509_STORE_free; + + /// A builder type used to construct an `X509Store`. + pub struct X509StoreBuilder; + /// Reference to an `X509StoreBuilder`. + pub struct X509StoreBuilderRef; +} + +impl X509StoreBuilder { + /// Returns a builder for a certificate store. + /// + /// The store is initially empty. + pub fn new() -> Result { + unsafe { + ffi::init(); + + cvt_p(ffi::X509_STORE_new()).map(X509StoreBuilder) + } + } + + /// Constructs the `X509Store`. + pub fn build(self) -> X509Store { + let store = X509Store(self.0); + mem::forget(self); + store + } +} + +impl X509StoreBuilderRef { + /// Adds a certificate to the certificate store. + // FIXME should take an &X509Ref + pub fn add_cert(&mut self, cert: X509) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::X509_STORE_add_cert(self.as_ptr(), cert.as_ptr())).map(|_| ()) + } + } + + /// Load certificates from their default locations. + /// + /// These locations are read from the `SSL_CERT_FILE` and `SSL_CERT_DIR` + /// environment variables if present, or defaults specified at OpenSSL + /// build time otherwise. + pub fn set_default_paths(&mut self) -> Result<(), ErrorStack> { + unsafe { cvt(ffi::X509_STORE_set_default_paths(self.as_ptr())).map(|_| ()) } + } +} + +foreign_type! { + type CType = ffi::X509_STORE; + fn drop = ffi::X509_STORE_free; + + /// A certificate store to hold trusted `X509` certificates. + pub struct X509Store; + /// Reference to an `X509Store`. + pub struct X509StoreRef; +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/x509/tests.rs cargo-0.26.0/vendor/openssl-0.10.6/src/x509/tests.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/x509/tests.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/x509/tests.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,334 @@ +use hex::{self, FromHex}; + +use asn1::Asn1Time; +use bn::{BigNum, MsbOption}; +use hash::MessageDigest; +use nid::Nid; +use pkey::{PKey, Private}; +use rsa::Rsa; +use stack::Stack; +use x509::{X509, X509Name, X509Req, X509StoreContext, X509VerifyResult}; +use x509::extension::{AuthorityKeyIdentifier, BasicConstraints, ExtendedKeyUsage, KeyUsage, + SubjectAlternativeName, SubjectKeyIdentifier}; +use x509::store::X509StoreBuilder; + +fn pkey() -> PKey { + let rsa = Rsa::generate(2048).unwrap(); + PKey::from_rsa(rsa).unwrap() +} + +#[test] +fn test_cert_loading() { + let cert = include_bytes!("../../test/cert.pem"); + let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); + let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); + + let hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; + let hash_vec = Vec::from_hex(hash_str).unwrap(); + + assert_eq!(fingerprint, hash_vec); +} + +#[test] +fn test_cert_issue_validity() { + let cert = include_bytes!("../../test/cert.pem"); + let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); + let not_before = cert.not_before().to_string(); + let not_after = cert.not_after().to_string(); + + assert_eq!(not_before, "Aug 14 17:00:03 2016 GMT"); + assert_eq!(not_after, "Aug 12 17:00:03 2026 GMT"); +} + +#[test] +fn test_save_der() { + let cert = include_bytes!("../../test/cert.pem"); + let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); + + let der = cert.to_der().unwrap(); + assert!(!der.is_empty()); +} + +#[test] +fn test_subject_read_cn() { + let cert = include_bytes!("../../test/cert.pem"); + let cert = X509::from_pem(cert).unwrap(); + let subject = cert.subject_name(); + let cn = subject.entries_by_nid(Nid::COMMONNAME).next().unwrap(); + assert_eq!(cn.data().as_slice(), b"foobar.com") +} + +#[test] +fn test_nid_values() { + let cert = include_bytes!("../../test/nid_test_cert.pem"); + let cert = X509::from_pem(cert).unwrap(); + let subject = cert.subject_name(); + + let cn = subject.entries_by_nid(Nid::COMMONNAME).next().unwrap(); + assert_eq!(cn.data().as_slice(), b"example.com"); + + let email = subject + .entries_by_nid(Nid::PKCS9_EMAILADDRESS) + .next() + .unwrap(); + assert_eq!(email.data().as_slice(), b"test@example.com"); + + let friendly = subject.entries_by_nid(Nid::FRIENDLYNAME).next().unwrap(); + assert_eq!(&**friendly.data().as_utf8().unwrap(), "Example"); +} + +#[test] +fn test_nid_uid_value() { + let cert = include_bytes!("../../test/nid_uid_test_cert.pem"); + let cert = X509::from_pem(cert).unwrap(); + let subject = cert.subject_name(); + + let cn = subject.entries_by_nid(Nid::USERID).next().unwrap(); + assert_eq!(cn.data().as_slice(), b"this is the userId"); +} + +#[test] +fn test_subject_alt_name() { + let cert = include_bytes!("../../test/alt_name_cert.pem"); + let cert = X509::from_pem(cert).unwrap(); + + let subject_alt_names = cert.subject_alt_names().unwrap(); + assert_eq!(5, subject_alt_names.len()); + assert_eq!(Some("example.com"), subject_alt_names[0].dnsname()); + assert_eq!(subject_alt_names[1].ipaddress(), Some(&[127, 0, 0, 1][..])); + assert_eq!( + subject_alt_names[2].ipaddress(), + Some(&b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01"[..]) + ); + assert_eq!(Some("test@example.com"), subject_alt_names[3].email()); + assert_eq!(Some("http://www.example.com"), subject_alt_names[4].uri()); +} + +#[test] +fn test_subject_alt_name_iter() { + let cert = include_bytes!("../../test/alt_name_cert.pem"); + let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); + + let subject_alt_names = cert.subject_alt_names().unwrap(); + let mut subject_alt_names_iter = subject_alt_names.iter(); + assert_eq!( + subject_alt_names_iter.next().unwrap().dnsname(), + Some("example.com") + ); + assert_eq!( + subject_alt_names_iter.next().unwrap().ipaddress(), + Some(&[127, 0, 0, 1][..]) + ); + assert_eq!( + subject_alt_names_iter.next().unwrap().ipaddress(), + Some(&b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01"[..]) + ); + assert_eq!( + subject_alt_names_iter.next().unwrap().email(), + Some("test@example.com") + ); + assert_eq!( + subject_alt_names_iter.next().unwrap().uri(), + Some("http://www.example.com") + ); + assert!(subject_alt_names_iter.next().is_none()); +} + +#[test] +fn x509_builder() { + let pkey = pkey(); + + let mut name = X509Name::builder().unwrap(); + name.append_entry_by_nid(Nid::COMMONNAME, "foobar.com") + .unwrap(); + let name = name.build(); + + let mut builder = X509::builder().unwrap(); + builder.set_version(2).unwrap(); + builder.set_subject_name(&name).unwrap(); + builder.set_issuer_name(&name).unwrap(); + builder + .set_not_before(&Asn1Time::days_from_now(0).unwrap()) + .unwrap(); + builder + .set_not_after(&Asn1Time::days_from_now(365).unwrap()) + .unwrap(); + builder.set_pubkey(&pkey).unwrap(); + + let mut serial = BigNum::new().unwrap(); + serial.rand(128, MsbOption::MAYBE_ZERO, false).unwrap(); + builder + .set_serial_number(&serial.to_asn1_integer().unwrap()) + .unwrap(); + + let basic_constraints = BasicConstraints::new().critical().ca().build().unwrap(); + builder.append_extension(basic_constraints).unwrap(); + let key_usage = KeyUsage::new() + .digital_signature() + .key_encipherment() + .build() + .unwrap(); + builder.append_extension(key_usage).unwrap(); + let ext_key_usage = ExtendedKeyUsage::new() + .client_auth() + .server_auth() + .other("2.999.1") + .build() + .unwrap(); + builder.append_extension(ext_key_usage).unwrap(); + let subject_key_identifier = SubjectKeyIdentifier::new() + .build(&builder.x509v3_context(None, None)) + .unwrap(); + builder.append_extension(subject_key_identifier).unwrap(); + let authority_key_identifier = AuthorityKeyIdentifier::new() + .keyid(true) + .build(&builder.x509v3_context(None, None)) + .unwrap(); + builder.append_extension(authority_key_identifier).unwrap(); + let subject_alternative_name = SubjectAlternativeName::new() + .dns("example.com") + .build(&builder.x509v3_context(None, None)) + .unwrap(); + builder.append_extension(subject_alternative_name).unwrap(); + + builder.sign(&pkey, MessageDigest::sha256()).unwrap(); + + let x509 = builder.build(); + + assert!(pkey.public_eq(&x509.public_key().unwrap())); + + let cn = x509.subject_name() + .entries_by_nid(Nid::COMMONNAME) + .next() + .unwrap(); + assert_eq!("foobar.com".as_bytes(), cn.data().as_slice()); + assert_eq!(serial, x509.serial_number().to_bn().unwrap()); +} + +#[test] +fn x509_req_builder() { + let pkey = pkey(); + + let mut name = X509Name::builder().unwrap(); + name.append_entry_by_nid(Nid::COMMONNAME, "foobar.com") + .unwrap(); + let name = name.build(); + + let mut builder = X509Req::builder().unwrap(); + builder.set_version(2).unwrap(); + builder.set_subject_name(&name).unwrap(); + builder.set_pubkey(&pkey).unwrap(); + + let mut extensions = Stack::new().unwrap(); + let key_usage = KeyUsage::new() + .digital_signature() + .key_encipherment() + .build() + .unwrap(); + extensions.push(key_usage).unwrap(); + let subject_alternative_name = SubjectAlternativeName::new() + .dns("example.com") + .build(&builder.x509v3_context(None)) + .unwrap(); + extensions.push(subject_alternative_name).unwrap(); + builder.add_extensions(&extensions).unwrap(); + + builder.sign(&pkey, MessageDigest::sha256()).unwrap(); +} + +#[test] +fn test_stack_from_pem() { + let certs = include_bytes!("../../test/certs.pem"); + let certs = X509::stack_from_pem(certs).unwrap(); + + assert_eq!(certs.len(), 2); + assert_eq!( + hex::encode(certs[0].fingerprint(MessageDigest::sha1()).unwrap()), + "59172d9313e84459bcff27f967e79e6e9217e584" + ); + assert_eq!( + hex::encode(certs[1].fingerprint(MessageDigest::sha1()).unwrap()), + "c0cbdf7cdd03c9773e5468e1f6d2da7d5cbb1875" + ); +} + +#[test] +fn issued() { + let cert = include_bytes!("../../test/cert.pem"); + let cert = X509::from_pem(cert).unwrap(); + let ca = include_bytes!("../../test/root-ca.pem"); + let ca = X509::from_pem(ca).unwrap(); + + assert_eq!(ca.issued(&cert), X509VerifyResult::OK); + assert_ne!(cert.issued(&cert), X509VerifyResult::OK); +} + +#[test] +fn signature() { + let cert = include_bytes!("../../test/cert.pem"); + let cert = X509::from_pem(cert).unwrap(); + let signature = cert.signature(); + assert_eq!( + hex::encode(signature.as_slice()), + "4af607b889790b43470442cfa551cdb8b6d0b0340d2958f76b9e3ef6ad4992230cead6842587f0ecad5\ + 78e6e11a221521e940187e3d6652de14e84e82f6671f097cc47932e022add3c0cb54a26bf27fa84c107\ + 4971caa6bee2e42d34a5b066c427f2d452038082b8073993399548088429de034fdd589dcfb0dd33be7\ + ebdfdf698a28d628a89568881d658151276bde333600969502c4e62e1d3470a683364dfb241f78d310a\ + 89c119297df093eb36b7fd7540224f488806780305d1e79ffc938fe2275441726522ab36d88348e6c51\ + f13dcc46b5e1cdac23c974fd5ef86aa41e91c9311655090a52333bc79687c748d833595d4c5f987508f\ + e121997410d37c" + ); + let algorithm = cert.signature_algorithm(); + assert_eq!(algorithm.object().nid(), Nid::SHA256WITHRSAENCRYPTION); + assert_eq!(algorithm.object().to_string(), "sha256WithRSAEncryption"); +} + +#[test] +fn clone_x509() { + let cert = include_bytes!("../../test/cert.pem"); + let cert = X509::from_pem(cert).unwrap(); + cert.clone(); +} + +#[test] +fn test_verify_cert() { + let cert = include_bytes!("../../test/cert.pem"); + let cert = X509::from_pem(cert).unwrap(); + let ca = include_bytes!("../../test/root-ca.pem"); + let ca = X509::from_pem(ca).unwrap(); + let chain = Stack::new().unwrap(); + + let mut store_bldr = X509StoreBuilder::new().unwrap(); + store_bldr.add_cert(ca).unwrap(); + let store = store_bldr.build(); + + let mut context = X509StoreContext::new().unwrap(); + assert!( + context + .init(&store, &cert, &chain, |c| c.verify_cert()) + .unwrap() + ); + assert!( + context + .init(&store, &cert, &chain, |c| c.verify_cert()) + .unwrap() + ); +} + +#[test] +fn test_verify_fails() { + let cert = include_bytes!("../../test/cert.pem"); + let cert = X509::from_pem(cert).unwrap(); + let ca = include_bytes!("../../test/alt_name_cert.pem"); + let ca = X509::from_pem(ca).unwrap(); + let chain = Stack::new().unwrap(); + + let mut store_bldr = X509StoreBuilder::new().unwrap(); + store_bldr.add_cert(ca).unwrap(); + let store = store_bldr.build(); + + let mut context = X509StoreContext::new().unwrap(); + assert!(!context + .init(&store, &cert, &chain, |c| c.verify_cert()) + .unwrap()); +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/src/x509/verify.rs cargo-0.26.0/vendor/openssl-0.10.6/src/x509/verify.rs --- cargo-0.25.0/vendor/openssl-0.10.6/src/x509/verify.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/src/x509/verify.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,88 @@ +use libc::c_uint; +use ffi; +use foreign_types::ForeignTypeRef; +use std::net::IpAddr; + +use cvt; +use error::ErrorStack; + +bitflags! { + /// Flags used to check an `X509` certificate. + pub struct X509CheckFlags: c_uint { + const ALWAYS_CHECK_SUBJECT = ffi::X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT; + const NO_WILDCARDS = ffi::X509_CHECK_FLAG_NO_WILDCARDS; + const NO_PARTIAL_WILDCARDS = ffi::X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS; + const MULTI_LABEL_WILDCARDS = ffi::X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS; + const SINGLE_LABEL_SUBDOMAINS = ffi::X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS; + /// Requires OpenSSL 1.1.0 or newer. + #[cfg(any(ossl110))] + const NEVER_CHECK_SUBJECT = ffi::X509_CHECK_FLAG_NEVER_CHECK_SUBJECT; + + #[deprecated(since = "0.10.6", note = "renamed to NO_WILDCARDS")] + const FLAG_NO_WILDCARDS = ffi::X509_CHECK_FLAG_NO_WILDCARDS; + } +} + +foreign_type_and_impl_send_sync! { + type CType = ffi::X509_VERIFY_PARAM; + fn drop = ffi::X509_VERIFY_PARAM_free; + + /// Adjust parameters associated with certificate verification. + pub struct X509VerifyParam; + /// Reference to `X509VerifyParam`. + pub struct X509VerifyParamRef; +} + +impl X509VerifyParamRef { + /// Set the host flags. + /// + /// This corresponds to [`X509_VERIFY_PARAM_set_hostflags`]. + /// + /// [`X509_VERIFY_PARAM_set_hostflags`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_VERIFY_PARAM_set_hostflags.html + pub fn set_hostflags(&mut self, hostflags: X509CheckFlags) { + unsafe { + ffi::X509_VERIFY_PARAM_set_hostflags(self.as_ptr(), hostflags.bits); + } + } + + /// Set the expected DNS hostname. + /// + /// This corresponds to [`X509_VERIFY_PARAM_set1_host`]. + /// + /// [`X509_VERIFY_PARAM_set1_host`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_VERIFY_PARAM_set1_host.html + pub fn set_host(&mut self, host: &str) -> Result<(), ErrorStack> { + unsafe { + cvt(ffi::X509_VERIFY_PARAM_set1_host( + self.as_ptr(), + host.as_ptr() as *const _, + host.len(), + )).map(|_| ()) + } + } + + /// Set the expected IPv4 or IPv6 address. + /// + /// This corresponds to [`X509_VERIFY_PARAM_set1_ip`]. + /// + /// [`X509_VERIFY_PARAM_set1_ip`]: https://www.openssl.org/docs/man1.1.0/crypto/X509_VERIFY_PARAM_set1_ip.html + pub fn set_ip(&mut self, ip: IpAddr) -> Result<(), ErrorStack> { + unsafe { + let mut buf = [0; 16]; + let len = match ip { + IpAddr::V4(addr) => { + buf[..4].copy_from_slice(&addr.octets()); + 4 + } + IpAddr::V6(addr) => { + buf.copy_from_slice(&addr.octets()); + 16 + } + }; + cvt(ffi::X509_VERIFY_PARAM_set1_ip( + self.as_ptr(), + buf.as_ptr() as *const _, + len, + )).map(|_| ()) + } + } +} diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/alt_name_cert.pem cargo-0.26.0/vendor/openssl-0.10.6/test/alt_name_cert.pem --- cargo-0.25.0/vendor/openssl-0.10.6/test/alt_name_cert.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/alt_name_cert.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDsDCCApigAwIBAgIBATANBgkqhkiG9w0BAQsFADBFMQswCQYDVQQGEwJBVTET +MBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQ +dHkgTHRkMB4XDTE4MDExNTExMDcwM1oXDTI4MDExMzExMDcwM1owfDELMAkGA1UE +BhMCVVMxCzAJBgNVBAgMAk5ZMREwDwYDVQQHDAhOZXcgWW9yazEVMBMGA1UECgwM +RXhhbXBsZSwgTExDMTYwNAYDVQQDDC1FeGFtcGxlIENvbXBhbnkvZW1haWxBZGRy +ZXNzPXRlc3RAZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK +AoIBAQCo9CWMRLMXo1CF/iORh9B4NhtJF/8tR9PlG95sNvyWuQQ/8jfev+8zErpl +xfLkt0pJqcoiZG8g9NU0kU6o5T+/1QgZclCAoZaS0Jqxmoo2Yk/1Qsj16pnMBc10 +uSDk6V9aJSX1vKwONVNSwiHA1MhX+i7Wf7/K0niq+k7hOkhleFkWgZtUq41gXh1V +fOugka7UktYnk9mrBbAMjmaloZNn2pMMAQxVg4ThiLm3zvuWqvXASWzUZc7IAd1G +bN4AtDuhs252eqE9E4iTHk7F14wAS1JWqv666hReGHrmZJGx0xQTM9vPD1HN5t2U +3KTfhO/mTlAUWVyg9tCtOzboKgs1AgMBAAGjdDByMAkGA1UdEwQCMAAwCwYDVR0P +BAQDAgWgMFgGA1UdEQRRME+CC2V4YW1wbGUuY29thwR/AAABhxAAAAAAAAAAAAAA +AAAAAAABgRB0ZXN0QGV4YW1wbGUuY29thhZodHRwOi8vd3d3LmV4YW1wbGUuY29t +MA0GCSqGSIb3DQEBCwUAA4IBAQAx14G99z/MnSbs8h5jSos+dgLvhc2IQB/3CChE +hPyELc7iyw1iteRs7bS1m2NZx6gv6TZ6VydDrK1dnWSatQ7sskXTO+zfC6qjMwXl +IV+u7T8EREwciniIA82d8GWs60BGyBL3zp2iUOr5ULG4+c/S6OLdlyJv+fDKv+Xo +fKv1UGDi5rcvUBikeNkpEPTN9UsE9/A8XJfDyq+4RKuDW19EtzOOeVx4xpHOMnAy +VVAQVMKJzhoXtLF4k2j409na+f6FIcZSBet+plmzfB+WZNIgUUi/7MQIXOFQRkj4 +zH3SnsPm/IYpJzlH2vHhlqIBdaSoTWpGVWPq7D+H8OS3mmXF +-----END CERTIFICATE----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/cert.pem cargo-0.26.0/vendor/openssl-0.10.6/test/cert.pem --- cargo-0.25.0/vendor/openssl-0.10.6/test/cert.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/cert.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDGzCCAgMCCQCHcfe97pgvpTANBgkqhkiG9w0BAQsFADBFMQswCQYDVQQGEwJB +VTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0 +cyBQdHkgTHRkMB4XDTE2MDgxNDE3MDAwM1oXDTI2MDgxMjE3MDAwM1owWjELMAkG +A1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0 +IFdpZGdpdHMgUHR5IEx0ZDETMBEGA1UEAwwKZm9vYmFyLmNvbTCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAKj0JYxEsxejUIX+I5GH0Hg2G0kX/y1H0+Ub +3mw2/Ja5BD/yN96/7zMSumXF8uS3SkmpyiJkbyD01TSRTqjlP7/VCBlyUIChlpLQ +mrGaijZiT/VCyPXqmcwFzXS5IOTpX1olJfW8rA41U1LCIcDUyFf6LtZ/v8rSeKr6 +TuE6SGV4WRaBm1SrjWBeHVV866CRrtSS1ieT2asFsAyOZqWhk2fakwwBDFWDhOGI +ubfO+5aq9cBJbNRlzsgB3UZs3gC0O6GzbnZ6oT0TiJMeTsXXjABLUlaq/rrqFF4Y +euZkkbHTFBMz288PUc3m3ZTcpN+E7+ZOUBRZXKD20K07NugqCzUCAwEAATANBgkq +hkiG9w0BAQsFAAOCAQEASvYHuIl5C0NHBELPpVHNuLbQsDQNKVj3a54+9q1JkiMM +6taEJYfw7K1Xjm4RoiFSHpQBh+PWZS3hToToL2Zx8JfMR5MuAirdPAy1Sia/J/qE +wQdJccqmvuLkLTSlsGbEJ/LUUgOAgrgHOZM5lUgIhCneA0/dWJ3PsN0zvn69/faY +oo1iiolWiIHWWBUSdr3jM2AJaVAsTmLh00cKaDNk37JB940xConBGSl98JPrNrf9 +dUAiT0iIBngDBdHnn/yTj+InVEFyZSKrNtiDSObFHxPcxGteHNrCPJdP1e+GqkHp +HJMRZVCQpSMzvHlofHSNgzWV1MX5h1CP4SGZdBDTfA== +-----END CERTIFICATE----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/certs.pem cargo-0.26.0/vendor/openssl-0.10.6/test/certs.pem --- cargo-0.25.0/vendor/openssl-0.10.6/test/certs.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/certs.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,40 @@ +-----BEGIN CERTIFICATE----- +MIIDGzCCAgMCCQCHcfe97pgvpTANBgkqhkiG9w0BAQsFADBFMQswCQYDVQQGEwJB +VTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0 +cyBQdHkgTHRkMB4XDTE2MDgxNDE3MDAwM1oXDTI2MDgxMjE3MDAwM1owWjELMAkG +A1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0 +IFdpZGdpdHMgUHR5IEx0ZDETMBEGA1UEAwwKZm9vYmFyLmNvbTCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAKj0JYxEsxejUIX+I5GH0Hg2G0kX/y1H0+Ub +3mw2/Ja5BD/yN96/7zMSumXF8uS3SkmpyiJkbyD01TSRTqjlP7/VCBlyUIChlpLQ +mrGaijZiT/VCyPXqmcwFzXS5IOTpX1olJfW8rA41U1LCIcDUyFf6LtZ/v8rSeKr6 +TuE6SGV4WRaBm1SrjWBeHVV866CRrtSS1ieT2asFsAyOZqWhk2fakwwBDFWDhOGI +ubfO+5aq9cBJbNRlzsgB3UZs3gC0O6GzbnZ6oT0TiJMeTsXXjABLUlaq/rrqFF4Y +euZkkbHTFBMz288PUc3m3ZTcpN+E7+ZOUBRZXKD20K07NugqCzUCAwEAATANBgkq +hkiG9w0BAQsFAAOCAQEASvYHuIl5C0NHBELPpVHNuLbQsDQNKVj3a54+9q1JkiMM +6taEJYfw7K1Xjm4RoiFSHpQBh+PWZS3hToToL2Zx8JfMR5MuAirdPAy1Sia/J/qE +wQdJccqmvuLkLTSlsGbEJ/LUUgOAgrgHOZM5lUgIhCneA0/dWJ3PsN0zvn69/faY +oo1iiolWiIHWWBUSdr3jM2AJaVAsTmLh00cKaDNk37JB940xConBGSl98JPrNrf9 +dUAiT0iIBngDBdHnn/yTj+InVEFyZSKrNtiDSObFHxPcxGteHNrCPJdP1e+GqkHp +HJMRZVCQpSMzvHlofHSNgzWV1MX5h1CP4SGZdBDTfA== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDXTCCAkWgAwIBAgIJAOIvDiVb18eVMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQwHhcNMTYwODE0MTY1NjExWhcNMjYwODEyMTY1NjExWjBF +MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 +ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEArVHWFn52Lbl1l59exduZntVSZyDYpzDND+S2LUcO6fRBWhV/1Kzox+2G +ZptbuMGmfI3iAnb0CFT4uC3kBkQQlXonGATSVyaFTFR+jq/lc0SP+9Bd7SBXieIV +eIXlY1TvlwIvj3Ntw9zX+scTA4SXxH6M0rKv9gTOub2vCMSHeF16X8DQr4XsZuQr +7Cp7j1I4aqOJyap5JTl5ijmG8cnu0n+8UcRlBzy99dLWJG0AfI3VRJdWpGTNVZ92 +aFff3RpK3F/WI2gp3qV1ynRAKuvmncGC3LDvYfcc2dgsc1N6Ffq8GIrkgRob6eBc +klDHp1d023Lwre+VaVDSo1//Y72UFwIDAQABo1AwTjAdBgNVHQ4EFgQUbNOlA6sN +XyzJjYqciKeId7g3/ZowHwYDVR0jBBgwFoAUbNOlA6sNXyzJjYqciKeId7g3/Zow +DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAVVaR5QWLZIRR4Dw6TSBn +BQiLpBSXN6oAxdDw6n4PtwW6CzydaA+creiK6LfwEsiifUfQe9f+T+TBSpdIYtMv +Z2H2tjlFX8VrjUFvPrvn5c28CuLI0foBgY8XGSkR2YMYzWw2jPEq3Th/KM5Catn3 +AFm3bGKWMtGPR4v+90chEN0jzaAmJYRrVUh9vea27bOCn31Nse6XXQPmSI6Gyncy +OAPUsvPClF3IjeL1tmBotWqSGn1cYxLo+Lwjk22A9h6vjcNQRyZF2VLVvtwYrNU3 +mwJ6GCLsLHpwW/yjyvn8iEltnJvByM/eeRnfXV6WDObyiZsE/n6DxIRJodQzFqy9 +GA== +-----END CERTIFICATE----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/dhparams.pem cargo-0.26.0/vendor/openssl-0.10.6/test/dhparams.pem --- cargo-0.25.0/vendor/openssl-0.10.6/test/dhparams.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/dhparams.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,8 @@ +-----BEGIN DH PARAMETERS----- +MIIBCAKCAQEAh3Betv+hf5jNsOmGXU8oxuABD2B8r0yU8FVgjnCZBSVo61qJ0A2d +J6r8rYKbjtolnrZN/V4IPSzYvxurHbu8nbiFVyhOySPchI2Fu+YT/HsSe/0MH9bW +gJTNzmutWoy9VxtWLCmXnOSZHep3MZ1ZNimno6Kh2qQ7VJr0+KF8GbxUKOPv4SqK +NBwouIQXFc0pE9kGhcGKbr7TnHhyJFCRLNP1OVDQZbcoKjk1Vh+5sy7vM2VUTQmM +yOToT2LEZVAUJXNumcYMki9MIwfYCwYZbNt0ZEolyHzUEesuyHfU1eJd6+sKEjUz +5GteQIR7AehxZIS+cytu7BXO7B0owLJ2awIBAg== +-----END DH PARAMETERS----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/dsaparam.pem cargo-0.26.0/vendor/openssl-0.10.6/test/dsaparam.pem --- cargo-0.25.0/vendor/openssl-0.10.6/test/dsaparam.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/dsaparam.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,9 @@ +-----BEGIN DSA PARAMETERS----- +MIIBHgKBgQCkKe/jtYKJNQafaE7kg2aaJOEPUV0Doi451jkXHp5UfLh6+t42eabS +GkE9WBAlILgaB8yHckLe9+zozN39+SUDp94kb2r38/8w/9Ffhbsep9uiyOj2ZRQu +r6SkpKQDKcnAd6IMZXZcvdSgPC90A6qraYUZKq7Csjn63gbC+IvXHwIVAIgSPE43 +lXD8/rGYxos4cxCgGGAxAoGASMV56WhLvVQtWMVI36WSIxbZnC2EsnNIKeVWyXnP +/OmPJ2mdezG7i1alcwsO2TnSLbvjvGPlyzIqZzHvWC8EmDqsfbU+n8we/Ealsm5n +loC8m9ECWpbTzbNdvrAAj9UPVWjcDwg7grAGGysh6lGbBv5P+4zL/niq1UiELnKc +ifg= +-----END DSA PARAMETERS----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/dsa.pem cargo-0.26.0/vendor/openssl-0.10.6/test/dsa.pem --- cargo-0.25.0/vendor/openssl-0.10.6/test/dsa.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/dsa.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,12 @@ +-----BEGIN DSA PRIVATE KEY----- +MIIBuwIBAAKBgQCkKe/jtYKJNQafaE7kg2aaJOEPUV0Doi451jkXHp5UfLh6+t42 +eabSGkE9WBAlILgaB8yHckLe9+zozN39+SUDp94kb2r38/8w/9Ffhbsep9uiyOj2 +ZRQur6SkpKQDKcnAd6IMZXZcvdSgPC90A6qraYUZKq7Csjn63gbC+IvXHwIVAIgS +PE43lXD8/rGYxos4cxCgGGAxAoGASMV56WhLvVQtWMVI36WSIxbZnC2EsnNIKeVW +yXnP/OmPJ2mdezG7i1alcwsO2TnSLbvjvGPlyzIqZzHvWC8EmDqsfbU+n8we/Eal +sm5nloC8m9ECWpbTzbNdvrAAj9UPVWjcDwg7grAGGysh6lGbBv5P+4zL/niq1UiE +LnKcifgCgYEAo6mAasO0+MVcu8shxxUXXNeTLsZ8NB/BIx9EZ/dzE23ivNW8dq1A +eecAAYhssI2m/CspQvyKw+seCvg4FccxJgB3+mGOe+blFHwO3eAwoyRn/t3DZDHh +FjxKKRsQdy4BkZv+vhTyIYYCw0iPZ5Wfln+pyGGTveIDED1MPG+J6c8CFCJAUlEl +4nHvbC15xLXXpd46zycY +-----END DSA PRIVATE KEY----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/dsa.pem.pub cargo-0.26.0/vendor/openssl-0.10.6/test/dsa.pem.pub --- cargo-0.25.0/vendor/openssl-0.10.6/test/dsa.pem.pub 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/dsa.pem.pub 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,12 @@ +-----BEGIN PUBLIC KEY----- +MIIBtzCCASsGByqGSM44BAEwggEeAoGBAKQp7+O1gok1Bp9oTuSDZpok4Q9RXQOi +LjnWORcenlR8uHr63jZ5ptIaQT1YECUguBoHzIdyQt737OjM3f35JQOn3iRvavfz +/zD/0V+Fux6n26LI6PZlFC6vpKSkpAMpycB3ogxldly91KA8L3QDqqtphRkqrsKy +OfreBsL4i9cfAhUAiBI8TjeVcPz+sZjGizhzEKAYYDECgYBIxXnpaEu9VC1YxUjf +pZIjFtmcLYSyc0gp5VbJec/86Y8naZ17MbuLVqVzCw7ZOdItu+O8Y+XLMipnMe9Y +LwSYOqx9tT6fzB78RqWybmeWgLyb0QJaltPNs12+sACP1Q9VaNwPCDuCsAYbKyHq +UZsG/k/7jMv+eKrVSIQucpyJ+AOBhQACgYEAo6mAasO0+MVcu8shxxUXXNeTLsZ8 +NB/BIx9EZ/dzE23ivNW8dq1AeecAAYhssI2m/CspQvyKw+seCvg4FccxJgB3+mGO +e+blFHwO3eAwoyRn/t3DZDHhFjxKKRsQdy4BkZv+vhTyIYYCw0iPZ5Wfln+pyGGT +veIDED1MPG+J6c8= +-----END PUBLIC KEY----- Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/openssl-0.10.6/test/identity.p12 and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/openssl-0.10.6/test/identity.p12 differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/openssl-0.10.6/test/key.der and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/openssl-0.10.6/test/key.der differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/openssl-0.10.6/test/key.der.pub and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/openssl-0.10.6/test/key.der.pub differ diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/key.pem cargo-0.26.0/vendor/openssl-0.10.6/test/key.pem --- cargo-0.25.0/vendor/openssl-0.10.6/test/key.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/key.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCo9CWMRLMXo1CF +/iORh9B4NhtJF/8tR9PlG95sNvyWuQQ/8jfev+8zErplxfLkt0pJqcoiZG8g9NU0 +kU6o5T+/1QgZclCAoZaS0Jqxmoo2Yk/1Qsj16pnMBc10uSDk6V9aJSX1vKwONVNS +wiHA1MhX+i7Wf7/K0niq+k7hOkhleFkWgZtUq41gXh1VfOugka7UktYnk9mrBbAM +jmaloZNn2pMMAQxVg4ThiLm3zvuWqvXASWzUZc7IAd1GbN4AtDuhs252eqE9E4iT +Hk7F14wAS1JWqv666hReGHrmZJGx0xQTM9vPD1HN5t2U3KTfhO/mTlAUWVyg9tCt +OzboKgs1AgMBAAECggEBAKLj6IOJBKXolczpzb8UkyAjAkGBektcseV07gelJ/fk +3z0LuWPv5p12E/HlXB24vU2x/ikUbbP3eMsawRzDEahQqmNmPEkYAYUAy/Qpi9GN +DYvn3LqDec4jVgeQKS+p9H2DzUpTogp8zR2//yzbuWBg2+F//xh7vU0S0RQCziPM +x7RSBgbhxSfChfEJbS2sDnzfh0jRQmoY95iFv7puet1FJtzdZ4fgCd1RqmC2lFM5 +H0eZtN/Cz19lieVs0b996DErdEBqClVZO00eYbRozCDaBzRU3ybB/dMrGJxhkkXm +wb3kWMtziH9qOYsostuHIFu8eKFLloKxFnq2R4DGxOECgYEA2KUIZISOeGJSBcLJ +JAUK2gvgXPNo4HHWIwOA9xeN3ZJlsnPlffXQNnm6t1st1V2gfMm9I2n0m/F0y2B/ +n/XGSa8bghfPA9l0c2h58lkL3JQJR/paa8ycTz+YZPrznEyN7Qa0RrJXUvZv9lQL +Hc3+FHcSHgMqDV2f2bHAEu9YGi0CgYEAx6VEIPNvrHFgjo/jk1RTuk+m0xEWQsZL +Cs+izQMr2TaeJn8LG+93AvFuYn0J0nT3WuStLPrUg8i4IhSS6lf1tId5ivIZPm4r +YwMyblBJXhnHbk7Uqodjfw/3s6V2HAu++B7hTdyVr9DFuST9uv4m8bkPV8rfX1jE +I2rAPVWvgikCgYB+wNAQP547wQrMZBLbCDg5KwmyWJfb+b6X7czexOEz6humNTjo +YZHYzY/5B1fhpk3ntQD8X1nGg5caBvOk21+QbOtjShrM3cXMYCw5JvBRtitX+Zo9 +yBEMLOE0877ki8XeEDYZxu5gk98d+D4oygUGZEQtWxyXhVepPt5qNa8OYQKBgQDH +RVgZI6KFlqzv3wMh3PutbS9wYQ+9GrtwUQuIYe/0YSW9+vSVr5E0qNKrD28sV39F +hBauXLady0yvB6YUrjMbPFW+sCMuQzyfGWPO4+g3OrfqjFiM1ZIkE0YEU9Tt7XNx +qTDtTI1D7bhNMnTnniI1B6ge0und+3XafAThs5L48QKBgQCTTpfqMt8kU3tcI9sf +0MK03y7kA76d5uw0pZbWFy7KI4qnzWutCzb+FMPWWsoFtLJLPZy//u/ZCUVFVa4d +0Y/ASNQIESVPXFLAltlLo4MSmsg1vCBsbviEEaPeEjvMrgki93pYtd/aOSgkYC1T +mEq154s5rmqh+h+XRIf7Au0SLw== +-----END PRIVATE KEY----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/key.pem.pub cargo-0.26.0/vendor/openssl-0.10.6/test/key.pem.pub --- cargo-0.25.0/vendor/openssl-0.10.6/test/key.pem.pub 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/key.pem.pub 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr1bXMptaIgOL9PVL8a7W +KG/C8+IbxP018eMBQZT0SnPQmXp0Q8Aai/F+AEDE7b5sO5U7WdxU4GRYw0wqkQNF +si78KNfoj2ZMlx6NRfl4UKuzrpGTPgQxuKDYedngPpWcbmW4P3zEL2Y7b18n9NJr +atRUzH1Zh/ReRO525Xadu58aviPw1Mzgse7cKyzb03Gll9noLnYNIIpO8jL+QyrD +8qNmfacmR20U0a6XDTtmsmk7AitGETICbTT0KRf+oAP0yIHoonllPpNLUEPZQjrp +ClS/S/wKdj7gaq9TaMbHULhFMjbCV8cuPu//rUAuWp3riaznZGOVQyn3Dp2CB3ad +yQIDAQAB +-----END PUBLIC KEY----- Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/openssl-0.10.6/test/keystore-empty-chain.p12 and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/openssl-0.10.6/test/keystore-empty-chain.p12 differ diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/nid_test_cert.pem cargo-0.26.0/vendor/openssl-0.10.6/test/nid_test_cert.pem --- cargo-0.25.0/vendor/openssl-0.10.6/test/nid_test_cert.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/nid_test_cert.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIB1DCCAX6gAwIBAgIJAMzXWZGWHleWMA0GCSqGSIb3DQEBCwUAMFYxHzAdBgkq +hkiG9w0BCQEWEHRlc3RAZXhhbXBsZS5jb20xFDASBgNVBAMMC2V4YW1wbGUuY29t +MR0wGwYJKoZIhvcNAQkUHg4ARQB4AGEAbQBwAGwAZTAeFw0xNTA3MDEwNjQ3NDRa +Fw0xNTA3MzEwNjQ3NDRaMFYxHzAdBgkqhkiG9w0BCQEWEHRlc3RAZXhhbXBsZS5j +b20xFDASBgNVBAMMC2V4YW1wbGUuY29tMR0wGwYJKoZIhvcNAQkUHg4ARQB4AGEA +bQBwAGwAZTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCmejzp4+o35FD0hAnx2trL +08h07X5jZca9DgZH35hWXPh7fMucLt/IPXIRnz2zKEa/Mo6D2V/fx03Mqo0epid7 +AgMBAAGjLzAtMB0GA1UdDgQWBBRQa57tXz3rZNRz+fTbo3w3jQJMBTAMBgNVHRME +BTADAQH/MA0GCSqGSIb3DQEBCwUAA0EAm0iY9cr+gvC+vcQIebdofpQ4GcDW8U6W +Bxs8ZXinLl69P0jYLum3+XITNFRiyQqcivaxdxthxDNOX7P+aKwkJA== +-----END CERTIFICATE----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/nid_uid_test_cert.pem cargo-0.26.0/vendor/openssl-0.10.6/test/nid_uid_test_cert.pem --- cargo-0.25.0/vendor/openssl-0.10.6/test/nid_uid_test_cert.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/nid_uid_test_cert.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,24 @@ +-----BEGIN CERTIFICATE----- +MIIEGTCCAwGgAwIBAgIJAItKTzcGfL1lMA0GCSqGSIb3DQEBCwUAMIGiMSIwIAYK +CZImiZPyLGQBAQwSdGhpcyBpcyB0aGUgdXNlcklkMQswCQYDVQQGEwJVUzETMBEG +A1UECAwKQ2FsaWZvcm5pYTESMBAGA1UEBwwJU3Vubnl2YWxlMRUwEwYDVQQKDAxS +dXN0IE9wZW5TU0wxDDAKBgNVBAsMA09TUzEhMB8GA1UEAwwYcnVzdC1vcGVuc3Ns +LmV4YW1wbGUuY29tMB4XDTE2MDIwMjE3MjIwMVoXDTE2MDMwMzE3MjIwMVowgaIx +IjAgBgoJkiaJk/IsZAEBDBJ0aGlzIGlzIHRoZSB1c2VySWQxCzAJBgNVBAYTAlVT +MRMwEQYDVQQIDApDYWxpZm9ybmlhMRIwEAYDVQQHDAlTdW5ueXZhbGUxFTATBgNV +BAoMDFJ1c3QgT3BlblNTTDEMMAoGA1UECwwDT1NTMSEwHwYDVQQDDBhydXN0LW9w +ZW5zc2wuZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB +AQDa3Gc+IE5DOhTv1m5DZW8qKiyNLd7v4DaAYLXSsDuLs+9wJ+Bs+wlBfrg+PT0t +EJlPaLL9IfD5eR3WpFu62TUexYhnJh+3vhCGsFHOXcTjtM+wy/dzZtOVh2wTzvqE +/FHBGw1eG3Ww+RkSFbwYmtm8JhIN8ffYxGn2O0yQpxypf5hNPYrC81zX+52X2w1h +jDYLpYt55w+e6q+iRRFk0tKiWHEqqh/r6UQQRpj2EeS+xTloZlO6h0nl2NPkVF3r +CXBoT8Ittxr7sqcYqf8TAA0I4qZRYXKYehFmv/VkSt85CcURJ/zXeoJ1TpxSvQie +2R9cRDkYROrIOAFbB/0mmHLBAgMBAAGjUDBOMB0GA1UdDgQWBBRKfPqtgrbdbTmH +XR6RC/p8t/65GjAfBgNVHSMEGDAWgBRKfPqtgrbdbTmHXR6RC/p8t/65GjAMBgNV +HRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCKfeGRduGsIwKNiGcDUNkNrc7Z +f8SWAmb/R6xiDfgjbhrtfBDowIZ5natEkTgf6kQPMJKyjg2NEM2uJWBc55rLOHIv +es1wQOlYjfEUmFD3lTIt2TM/IUgXn2j+zV1CRkJthQLVFChXsidd0Bqq2fBjd3ad +Yjzrxf3uOTBAs27koh2INNHfcUZCRsx8hP739zz2kw/r5NB/9iyENEyJKQvxo0jb +oN0JK2joGZrWetDukQrqf032TsdkboW5JresYybbAD3326Ljp+hlT/3WINc+3nZJ +Dn+pPMdpuZ5BUZ+u+XyNEPum3k3P3K19AF+zWYGooX0J1cmuCBrrqce20Lwy +-----END CERTIFICATE----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/pkcs1.pem.pub cargo-0.26.0/vendor/openssl-0.10.6/test/pkcs1.pem.pub --- cargo-0.25.0/vendor/openssl-0.10.6/test/pkcs1.pem.pub 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/pkcs1.pem.pub 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,8 @@ +-----BEGIN RSA PUBLIC KEY----- +MIIBCgKCAQEAyrcf7lv42BCoiDd3LYmF8eaGO4rhmGzGgi+NSZowkEuLhibHGQle +FkZC7h1VKsxKFgy7Fx+GYHkv9OLm9H5fdp3HhYlo19bZVGvSJ66OJe/Bc4S02bBb +Y8vwpc/N5O77m5J/nHLuL7XJtpfSKkX+3NPiX1X2L99iipt7F0a7hNws3G3Lxg6t +P3Yc55TPjXzXvDIgjt/fag6iF8L/bR3augJJdDhLzNucR8A5HcvPtIVo51R631Zq +MCh+dZvgz9zGCXwsvSky/iOJTHN3wnpsWuCAzS1iJMfjR783Tfv6sWFs19FH7pHP +xBA3b2enPM9KBzINGOly0eM4h0fh+VBltQIDAQAB +-----END RSA PUBLIC KEY----- Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/openssl-0.10.6/test/pkcs8.der and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/openssl-0.10.6/test/pkcs8.der differ diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/root-ca.key cargo-0.26.0/vendor/openssl-0.10.6/test/root-ca.key --- cargo-0.25.0/vendor/openssl-0.10.6/test/root-ca.key 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/root-ca.key 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpQIBAAKCAQEArVHWFn52Lbl1l59exduZntVSZyDYpzDND+S2LUcO6fRBWhV/ +1Kzox+2GZptbuMGmfI3iAnb0CFT4uC3kBkQQlXonGATSVyaFTFR+jq/lc0SP+9Bd +7SBXieIVeIXlY1TvlwIvj3Ntw9zX+scTA4SXxH6M0rKv9gTOub2vCMSHeF16X8DQ +r4XsZuQr7Cp7j1I4aqOJyap5JTl5ijmG8cnu0n+8UcRlBzy99dLWJG0AfI3VRJdW +pGTNVZ92aFff3RpK3F/WI2gp3qV1ynRAKuvmncGC3LDvYfcc2dgsc1N6Ffq8GIrk +gRob6eBcklDHp1d023Lwre+VaVDSo1//Y72UFwIDAQABAoIBAGZrnd/dC2kp11uq +Sg8SHk3GMdPPjTf/lq51sVJAU4fdV2Eso0XCiCzdKDcqR6F+jiu8jHp4YO0riW8N +b1pkjohGjyOaddIaaVsZ80/OkgDz20Ird9XQ7uoEODvopA12+755BDH5PDwqHVeM +nKfPiwAK6Jz6CxGO9bq9ZNoBiSyO1uofaB4Cpp8t74XVeAuPiI/Bb6WJ8TW5K5dt +x0Jihdo46QgZR+z4PnyWIoACkhSoQmtTb9NUrpKceBcxdCrZ/kEmYpnPq/PuSw6g +6HthjYP/H9Xulz69UR5Ez6z+1pU1rKFmQ46qK7X3zVHg233MlGekMzxdmShEjzCP +BMGYpQECgYEA5tqTZsUJwx3HDhkaZ/XOtaQqwOnZm9wPwTjGbV1t4+NUJzsl5gjP +ho+I8ZSGZ6MnNSh+ClpYhUHYBq0rTuAAYL2arcMOuOs1GrMmiZJbXm8zq8M7gYr5 +V99H/7akSx66WV/agPkLIvh/BWxlWgQcoVAIzZibbLUxr7Ye50pCLfECgYEAwDLn +mFz0mFMvGtaSp8RnTDTFCz9czCeDt0GujCxG1epdvtuxlg/S1QH+mGzA/AHkiu7z +uzCwGKWozNTdRkqVwYoJTB+AYHseSkuGP+a1zr39w+xBW/vESb2oP95GIwprXcG2 +b/qdeQVzuLQhYoqWI2u8CBwlHFfpQO4Bp2ea+ocCgYEAurIgLSfCqlpFpiAlG9hN +8NYwgU1d4E+LKj+JMd8yRO+PGh8amjub4X3pST5NqDjpN3Nk42iHWFWUqGmZsbM0 +ewg7tLUgDeqiStKBoxaK8AdMqWc9k5lZ53e6mZISsnHKUQdVBaLjH8gJqdAs8yyK +HudEB0mYwMSUxz6pJXIHrXECgYEAhJkaCpXm8chB8UQj/baUhZDKeI4IWZjRWHbq +Ey7g1+hPMMOk6yCTlf1ARqyRH8u2ftuIL5bRhs+Te21IE5yVYOb4rxn0mZuXNC6S +ujdTKwUMtESkeu9hZnaAQz/4J2ii1hY05WCDj+DhC4bKmY9/MYS8PuQb/kfwVqld +Xr8tvrUCgYEAmslHocXBUFXyRDkEOx/aKo+t9fPBr95PBZzFUt9ejrTP4PXsLa46 +3/PNOCGdrQxh5qHHcvLwR4bPL++Dj+qMUTJXANrArKPDpE2WqH6pqWIC6yaZvzUk +17QbpXR6bHcdJV045pWpw40UCStTocVynY1lBfOw8VqxBIBlpVBBzew= +-----END RSA PRIVATE KEY----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/root-ca.pem cargo-0.26.0/vendor/openssl-0.10.6/test/root-ca.pem --- cargo-0.25.0/vendor/openssl-0.10.6/test/root-ca.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/root-ca.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,21 @@ +-----BEGIN CERTIFICATE----- +MIIDXTCCAkWgAwIBAgIJAOIvDiVb18eVMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV +BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX +aWRnaXRzIFB0eSBMdGQwHhcNMTYwODE0MTY1NjExWhcNMjYwODEyMTY1NjExWjBF +MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 +ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEArVHWFn52Lbl1l59exduZntVSZyDYpzDND+S2LUcO6fRBWhV/1Kzox+2G +ZptbuMGmfI3iAnb0CFT4uC3kBkQQlXonGATSVyaFTFR+jq/lc0SP+9Bd7SBXieIV +eIXlY1TvlwIvj3Ntw9zX+scTA4SXxH6M0rKv9gTOub2vCMSHeF16X8DQr4XsZuQr +7Cp7j1I4aqOJyap5JTl5ijmG8cnu0n+8UcRlBzy99dLWJG0AfI3VRJdWpGTNVZ92 +aFff3RpK3F/WI2gp3qV1ynRAKuvmncGC3LDvYfcc2dgsc1N6Ffq8GIrkgRob6eBc +klDHp1d023Lwre+VaVDSo1//Y72UFwIDAQABo1AwTjAdBgNVHQ4EFgQUbNOlA6sN +XyzJjYqciKeId7g3/ZowHwYDVR0jBBgwFoAUbNOlA6sNXyzJjYqciKeId7g3/Zow +DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAVVaR5QWLZIRR4Dw6TSBn +BQiLpBSXN6oAxdDw6n4PtwW6CzydaA+creiK6LfwEsiifUfQe9f+T+TBSpdIYtMv +Z2H2tjlFX8VrjUFvPrvn5c28CuLI0foBgY8XGSkR2YMYzWw2jPEq3Th/KM5Catn3 +AFm3bGKWMtGPR4v+90chEN0jzaAmJYRrVUh9vea27bOCn31Nse6XXQPmSI6Gyncy +OAPUsvPClF3IjeL1tmBotWqSGn1cYxLo+Lwjk22A9h6vjcNQRyZF2VLVvtwYrNU3 +mwJ6GCLsLHpwW/yjyvn8iEltnJvByM/eeRnfXV6WDObyiZsE/n6DxIRJodQzFqy9 +GA== +-----END CERTIFICATE----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/rsa-encrypted.pem cargo-0.26.0/vendor/openssl-0.10.6/test/rsa-encrypted.pem --- cargo-0.25.0/vendor/openssl-0.10.6/test/rsa-encrypted.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/rsa-encrypted.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,30 @@ +-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-128-CBC,E2F16153E2BA3D617285A68C896BA6AF + +vO9SnhtGjGe8pG1pN//vsONnvJr+DjU+lFCiSqGMPT7tezDnbehLfS+9kus2HV7r +HmI14JvVG9O7NpF7zMyBRlHYdWcCCWED9Yar0NsWN9419e5pMe/bqIXAzAiJbtT4 +OB9U5XF3m+349zjN1dVXPPLGRmMC1pcHAlofeb5nIUFTvUi5xcsbe1itGjgkkvHb +Bt8NioHTBun8kKrlsFQOuB55ylBU/eWG8DQBtvFOmQ7iWp0RnGQfh8k5e5rcZNpQ +fD9ygc7UVISl0xTrIG4IH15g34H+nrBauKtIPOpNPuXQPOMHCZv3XH8wnhrWHHwT +ZFnQBdXbSpQtMsRh0phG2G+VIlyCgSn4+CxjCJ+TgFtsoK/tU0unmRYc59QnTxxb +qkHYsPs3E0NApQAgH1ENEGl1M+FGLYQH7gftjc3ophBTeRA17sRmD7Y4QBInggsq +Gv6tImPVBdekAjz/Ls/EyMwjAvvrL5eAokqrIsAarGo+zmbJKHzknw2KUz2En0+k +YYaxB4oy9u7bzuQlvio6xYHJEb4K197bby4Dldmqv7YCCJBJwhOBAInMD687viKv +vcUwL8YuS6cW5E8MbvEENlY4+lvKKj3M8Bnyb79cYIPQe92EuCwXU9DZXPRMLwwM +oFEJpF5E/PmNJzu+B52ahHtDrh83WSx71fWqjdTqwkPZhAYo3ztsfFkb/UqUcq8u +rBSebeUjZh0XZ9B04eshZQ5vJUcXGtYIe/77beV3Pv89/fw+zTZjpiP9Q3sZALzf +Qt0YGp0/6qBuqR1tcqdu65AS2hun7yFw7uRavqYKvww4axRiz2do+xWmZFuoCAwD +EWktaUujltpvAc1lo7lg4C6nByefJB9Xqk22N/vpqOsWr1NbAntT42Qj/HF9BVWR +osvN3yMnKYWYe6oSTVnNBDM5obWAIHd3I9gcxTOTb1KsEwt2RrDs5EpB5ptS3Fjo +JfBRhNZQ3cXttrIIhsHgDn9BDNg865/xpIgktKj0gEd60Abx0PqkAIm6IZTh4Efg +7uZwfzxB+saOcddbrW2gNdzVZMC0s2Ye3sqHhtLbAJ3BlXYTxE4CAvTg54Ny+5hF +IjvjlOKgXceSG1cSfk21/wyp9RY3Ft0AEYvvp0kZScWZaoA2aSFDUrchXVhgrEbn +lJ7UptjefwRFIreAlwbKSbIDDNWnyzvIWyHfQ2aYqgnb7W7XqNPSgH9cALCfzirI +dlRHjha0bMUtrjPCC/YfMXzJBVniy0gG6Pd5uC7vz/Awn6/6HRQVNaTQASphPBQ7 +bJuz+JTfzI9OUVCMRMdnb6b35U4P9tibFmnPvzTIPe+3WUmf8aRsLS3NN3G1Webd +PMYVZpMycPaAI0Ht87axhsOzlxCWHYWjdHa+WoNNc1J90TxLCmAHquh5BDaWvjMK +0DySftJZjV7Tf1p2KosmU83LRl39B5NHMbZb1xOEZl9IWwhT/PVKTVZ25xdxWLfb +hF4l8rfvKehIp5r4t8zW1bvI2Hl6vrUvmcUVWt3BfKjxlgwRVD0vvwonMt1INesF +204vUBeXbDsUUicLwOyUgaFvJ3XU3dOyvL9MhOgM5OgoFRRhG+4AS8a5JCD8iLtq +-----END RSA PRIVATE KEY----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/rsa.pem cargo-0.26.0/vendor/openssl-0.10.6/test/rsa.pem --- cargo-0.25.0/vendor/openssl-0.10.6/test/rsa.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/rsa.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd/wWJcyQoTbji9k0 +l8W26mPddxHmfHQp+Vaw+4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL+yRT+SFd2lZS+pC +gNMsD1W/YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb/7OMg0LOL+bSf63kpaSHSX +ndS5z5rexMdbBYUsLA9e+KXBdQOS+UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uD +Zlxvb3qCo5ZwKh9kG4LT6/I5IhlJH7aGhyxXFvUK+DWNmoudF8NAco9/h9iaGNj8 +q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQIDAQABAoIBABKucaRpzQorw35S +bEUAVx8dYXUdZOlJcHtiWQ+dC6V8ljxAHj/PLyzTveyI5QO/xkObCyjIL303l2cf +UhPu2MFaJdjVzqACXuOrLot/eSFvxjvqVidTtAZExqFRJ9mylUVAoLvhowVWmC1O +n95fZCXxTUtxNEG1Xcc7m0rtzJKs45J+N/V9DP1edYH6USyPSWGp6wuA+KgHRnKK +Vf9GRx80JQY7nVNkL17eHoTWEwga+lwi0FEoW9Y7lDtWXYmKBWhUE+U8PGxlJf8f +40493HDw1WRQ/aSLoS4QTp3rn7gYgeHEvfJdkkf0UMhlknlo53M09EFPdadQ4TlU +bjqKc50CgYEA4BzEEOtIpmVdVEZNCqS7baC4crd0pqnRH/5IB3jw3bcxGn6QLvnE +tfdUdiYrqBdss1l58BQ3KhooKeQTa9AB0Hw/Py5PJdTJNPY8cQn7ouZ2KKDcmnPG +BY5t7yLc1QlQ5xHdwW1VhvKn+nXqhJTBgIPgtldC+KDV5z+y2XDwGUcCgYEAuQPE +fgmVtjL0Uyyx88GZFF1fOunH3+7cepKmtH4pxhtCoHqpWmT8YAmZxaewHgHAjLYs +p1ZSe7zFYHj7C6ul7TjeLQeZD/YwD66t62wDmpe/HlB+TnBA+njbglfIsRLtXlnD +zQkv5dTltRJ11BKBBypeeF6689rjcJIDEz9RWdcCgYAHAp9XcCSrn8wVkMVkKdb7 +DOX4IKjzdahm+ctDAJN4O/y7OW5FKebvUjdAIt2GuoTZ71iTG+7F0F+lP88jtjP4 +U4qe7VHoewl4MKOfXZKTe+YCS1XbNvfgwJ3Ltyl1OH9hWvu2yza7q+d5PCsDzqtm +27kxuvULVeya+TEdAB1ijQKBgQCH/3r6YrVH/uCWGy6bzV1nGNOdjKc9tmkfOJmN +54dxdixdpozCQ6U4OxZrsj3FcOhHBsqAHvX2uuYjagqvo3cOj1TRqNocX40omfCC +Mx3bD1yPPf/6TI2XECva/ggqEY2mYzmIiA5LVVmc5nrybr+lssFKneeyxN2Wq93S +0iJMdQKBgCGHewxzoa1r8ZMD0LETNrToK423K377UCYqXfg5XMclbrjPbEC3YI1Z +NqMtuhdBJqUnBi6tjKMF+34Xf0CUN8ncuXGO2CAYvO8PdyCixHX52ybaDjy1FtCE +6yUXjoKNXKvUm7MWGsAYH6f4IegOetN5NvmUMFStCSkh7ixZLkN1 +-----END RSA PRIVATE KEY----- diff -Nru cargo-0.25.0/vendor/openssl-0.10.6/test/rsa.pem.pub cargo-0.26.0/vendor/openssl-0.10.6/test/rsa.pem.pub --- cargo-0.25.0/vendor/openssl-0.10.6/test/rsa.pem.pub 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.10.6/test/rsa.pem.pub 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAofgWCuLjybRlzo0tZWJj +NiuSfb4p4fAkd/wWJcyQoTbji9k0l8W26mPddxHmfHQp+Vaw+4qPCJrcS2mJPMEz +P1Pt0Bm4d4QlL+yRT+SFd2lZS+pCgNMsD1W/YpRPEwOWvG6b32690r2jZ47soMZo +9wGzjb/7OMg0LOL+bSf63kpaSHSXndS5z5rexMdbBYUsLA9e+KXBdQOS+UTo7WTB +EMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6/I5IhlJH7aGhyxX +FvUK+DWNmoudF8NAco9/h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXp +oQIDAQAB +-----END PUBLIC KEY----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/build.rs cargo-0.26.0/vendor/openssl-0.9.24/build.rs --- cargo-0.25.0/vendor/openssl-0.9.24/build.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/build.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -use std::env; - -fn main() { - match env::var("DEP_OPENSSL_VERSION") { - Ok(ref v) if v == "101" => { - println!("cargo:rustc-cfg=ossl101"); - println!("cargo:rustc-cfg=ossl10x"); - } - Ok(ref v) if v == "102" => { - println!("cargo:rustc-cfg=ossl102"); - println!("cargo:rustc-cfg=ossl10x"); - } - Ok(ref v) if v == "110" => { - println!("cargo:rustc-cfg=ossl110"); - } - _ => panic!("Unable to detect OpenSSL version"), - } - - if let Ok(_) = env::var("DEP_OPENSSL_LIBRESSL") { - println!("cargo:rustc-cfg=libressl"); - } - - if let Ok(v) = env::var("DEP_OPENSSL_LIBRESSL_VERSION") { - println!("cargo:rustc-cfg=libressl{}", v); - } - - if let Ok(vars) = env::var("DEP_OPENSSL_CONF") { - for var in vars.split(",") { - println!("cargo:rustc-cfg=osslconf=\"{}\"", var); - } - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/.cargo-checksum.json cargo-0.26.0/vendor/openssl-0.9.24/.cargo-checksum.json --- cargo-0.25.0/vendor/openssl-0.9.24/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"a3605c298474a3aa69de92d21139fb5e2a81688d308262359d85cdd0d12a7985"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/Cargo.toml cargo-0.26.0/vendor/openssl-0.9.24/Cargo.toml --- cargo-0.25.0/vendor/openssl-0.9.24/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "openssl" -version = "0.9.24" -authors = ["Steven Fackler "] -build = "build.rs" -description = "OpenSSL bindings" -readme = "README.md" -keywords = ["crypto", "tls", "ssl", "dtls"] -categories = ["cryptography", "api-bindings"] -license = "Apache-2.0" -repository = "https://github.com/sfackler/rust-openssl" -[package.metadata.docs.rs] -all-features = true -[dependencies.bitflags] -version = "0.9" - -[dependencies.foreign-types] -version = "0.3.1" - -[dependencies.lazy_static] -version = "1" - -[dependencies.libc] -version = "0.2" - -[dependencies.openssl-sys] -version = "0.9.23" -[dev-dependencies.data-encoding] -version = "2.0" - -[dev-dependencies.hex] -version = "0.2" - -[dev-dependencies.tempdir] -version = "0.3" - -[dev-dependencies.winapi] -version = "0.2" - -[dev-dependencies.ws2_32-sys] -version = "0.2" - -[features] -v101 = [] -v102 = [] -v110 = [] diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/examples/mk_certs.rs cargo-0.26.0/vendor/openssl-0.9.24/examples/mk_certs.rs --- cargo-0.25.0/vendor/openssl-0.9.24/examples/mk_certs.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/examples/mk_certs.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,152 +0,0 @@ -//! A program that generates ca certs, certs verified by the ca, and public -//! and private keys. - -extern crate openssl; - -use openssl::asn1::Asn1Time; -use openssl::bn::{BigNum, MSB_MAYBE_ZERO}; -use openssl::error::ErrorStack; -use openssl::hash::MessageDigest; -use openssl::pkey::{PKey, PKeyRef}; -use openssl::rsa::Rsa; -use openssl::x509::{X509, X509Ref}; -use openssl::x509::{X509NameBuilder, X509Req, X509ReqBuilder}; -use openssl::x509::extension::{AuthorityKeyIdentifier, BasicConstraints, KeyUsage, - SubjectAlternativeName, SubjectKeyIdentifier}; - -/// Make a CA certificate and private key -fn mk_ca_cert() -> Result<(X509, PKey), ErrorStack> { - let rsa = Rsa::generate(2048)?; - let privkey = PKey::from_rsa(rsa)?; - - let mut x509_name = X509NameBuilder::new()?; - x509_name.append_entry_by_text("C", "US")?; - x509_name.append_entry_by_text("ST", "TX")?; - x509_name.append_entry_by_text("O", "Some CA organization")?; - x509_name.append_entry_by_text("CN", "ca test")?; - let x509_name = x509_name.build(); - - let mut cert_builder = X509::builder()?; - cert_builder.set_version(2)?; - let serial_number = { - let mut serial = BigNum::new()?; - serial.rand(159, MSB_MAYBE_ZERO, false)?; - serial.to_asn1_integer()? - }; - cert_builder.set_serial_number(&serial_number)?; - cert_builder.set_subject_name(&x509_name)?; - cert_builder.set_issuer_name(&x509_name)?; - cert_builder.set_pubkey(&privkey)?; - let not_before = Asn1Time::days_from_now(0)?; - cert_builder.set_not_before(¬_before)?; - let not_after = Asn1Time::days_from_now(365)?; - cert_builder.set_not_after(¬_after)?; - - cert_builder.append_extension(BasicConstraints::new().critical().ca().build()?)?; - cert_builder.append_extension(KeyUsage::new() - .critical() - .key_cert_sign() - .crl_sign() - .build()?)?; - - let subject_key_identifier = - SubjectKeyIdentifier::new().build(&cert_builder.x509v3_context(None, None))?; - cert_builder.append_extension(subject_key_identifier)?; - - cert_builder.sign(&privkey, MessageDigest::sha256())?; - let cert = cert_builder.build(); - - Ok((cert, privkey)) -} - -/// Make a X509 request with the given private key -fn mk_request(privkey: &PKey) -> Result<(X509Req), ErrorStack> { - let mut req_builder = X509ReqBuilder::new()?; - req_builder.set_pubkey(&privkey)?; - - let mut x509_name = X509NameBuilder::new()?; - x509_name.append_entry_by_text("C", "US")?; - x509_name.append_entry_by_text("ST", "TX")?; - x509_name.append_entry_by_text("O", "Some organization")?; - x509_name.append_entry_by_text("CN", "www.example.com")?; - let x509_name = x509_name.build(); - req_builder.set_subject_name(&x509_name)?; - - req_builder.sign(&privkey, MessageDigest::sha256())?; - let req = req_builder.build(); - Ok(req) -} - -/// Make a certificate and private key signed by the given CA cert and private key -fn mk_ca_signed_cert(ca_cert: &X509Ref, ca_privkey: &PKeyRef) -> Result<(X509, PKey), ErrorStack> { - let rsa = Rsa::generate(2048)?; - let privkey = PKey::from_rsa(rsa)?; - - let req = mk_request(&privkey)?; - - let mut cert_builder = X509::builder()?; - cert_builder.set_version(2)?; - let serial_number = { - let mut serial = BigNum::new()?; - serial.rand(159, MSB_MAYBE_ZERO, false)?; - serial.to_asn1_integer()? - }; - cert_builder.set_serial_number(&serial_number)?; - cert_builder.set_subject_name(req.subject_name())?; - cert_builder.set_issuer_name(ca_cert.subject_name())?; - cert_builder.set_pubkey(&privkey)?; - let not_before = Asn1Time::days_from_now(0)?; - cert_builder.set_not_before(¬_before)?; - let not_after = Asn1Time::days_from_now(365)?; - cert_builder.set_not_after(¬_after)?; - - cert_builder.append_extension(BasicConstraints::new().build()?)?; - - cert_builder.append_extension(KeyUsage::new() - .critical() - .non_repudiation() - .digital_signature() - .key_encipherment() - .build()?)?; - - let subject_key_identifier = SubjectKeyIdentifier::new() - .build(&cert_builder.x509v3_context(Some(ca_cert), None))?; - cert_builder.append_extension(subject_key_identifier)?; - - let auth_key_identifier = AuthorityKeyIdentifier::new() - .keyid(false) - .issuer(false) - .build(&cert_builder.x509v3_context(Some(ca_cert), None))?; - cert_builder.append_extension(auth_key_identifier)?; - - let subject_alt_name = SubjectAlternativeName::new() - .dns("*.example.com") - .dns("hello.com") - .build(&cert_builder.x509v3_context(Some(ca_cert), None))?; - cert_builder.append_extension(subject_alt_name)?; - - cert_builder.sign(&ca_privkey, MessageDigest::sha256())?; - let cert = cert_builder.build(); - - Ok((cert, privkey)) -} - -fn real_main() -> Result<(), ErrorStack> { - let (ca_cert, ca_privkey) = mk_ca_cert()?; - let (cert, _privkey) = mk_ca_signed_cert(&ca_cert, &ca_privkey)?; - - // Verify that this cert was issued by this ca - match ca_cert.issued(&cert) { - Err(ver_err) => println!("Failed to verify certificate: {}", ver_err), - Ok(()) => println!("Certificate verified!"), - }; - - Ok(()) -} - -fn main() { - match real_main() { - Ok(()) => println!("Finished."), - Err(e) => println!("Error: {}", e), - }; -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/LICENSE cargo-0.26.0/vendor/openssl-0.9.24/LICENSE --- cargo-0.25.0/vendor/openssl-0.9.24/LICENSE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/LICENSE 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -Copyright 2011-2017 Google Inc. - 2013 Jack Lloyd - 2013-2014 Steven Fackler - -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. diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/README.md cargo-0.26.0/vendor/openssl-0.9.24/README.md --- cargo-0.25.0/vendor/openssl-0.9.24/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,180 +0,0 @@ -# rust-openssl - -[![CircleCI](https://circleci.com/gh/sfackler/rust-openssl.svg?style=shield)](https://circleci.com/gh/sfackler/rust-openssl) [![Build status](https://ci.appveyor.com/api/projects/status/d1knobws948pyynk/branch/master?svg=true)](https://ci.appveyor.com/project/sfackler/rust-openssl/branch/master) - -[Documentation](https://docs.rs/openssl). - -## Warning - -This README does not correspond to rust-openssl 0.7.x or 0.8.x. See -[here](https://github.com/sfackler/rust-openssl/blob/b8fb29db5c246175a096260eacca38180cd77dd0/README.md) -for that README. - -## Building - -rust-openssl depends on OpenSSL version 1.0.1 or above, or LibreSSL. Both the -libraries and headers need to be present in the build environment before this -crate is compiled, and some instructions of how to do this are in the sections -below. - -### Linux - -On Linux, you can typically install OpenSSL via your package manager. The -headers are sometimes provided in a separate package than the runtime libraries -- look for something like `openssl-devel` or `libssl-dev`. You will also need the -regular development utilities, like `pkg-config`, as the custom build script relies -on them. - -```bash -# On Debian and Ubuntu -sudo apt-get install pkg-config libssl-dev -# On Arch Linux -sudo pacman -S openssl -# On Fedora -sudo dnf install openssl-devel -``` - -If installation via a package manager is not possible, or if you're cross -compiling to a separate target, you'll typically need to compile OpenSSL from -source. That can normally be done with: - -``` -curl -O https://www.openssl.org/source/openssl-1.1.0f.tar.gz -tar xf openssl-1.1.0f.tar.gz -cd openssl-1.1.0f -export CC=... -./Configure --prefix=... linux-x86_64 -fPIC -make -j$(nproc) -make install -``` - -### OSX - -Although OpenSSL 0.9.8 is preinstalled on OSX this library is being phased out -of OSX and this crate also does not support that version of OpenSSL. To use this -crate on OSX you'll need to install OpenSSL via some alternate means, typically -Homebrew: - -```bash -brew install openssl -``` - -Occasionally an update of XCode or MacOS will cause the linker to fail after compilation, to rectify this you may want to try and run: - -```bash -xcode-select --install -``` - -If Homebrew is installed to the default location of `/usr/local`, OpenSSL will be -automatically detected. - -### Windows MSVC - -On MSVC it's unfortunately not always a trivial process acquiring OpenSSL. A couple of possibilities -are downloading precompiled binaries for OpenSSL 1.1.0, or installing OpenSSL 1.0.2 using vcpkg. - -#### Installing OpenSSL 1.1.0 using precompiled binaries - -Perhaps the easiest way to do this right now is to download [precompiled -binaries] and install them on your system. Currently it's recommended to -install the 1.1.0 (non-light) installation if you're choosing this route. - -[precompiled binaries]: http://slproweb.com/products/Win32OpenSSL.html - -Once a precompiled binary is installed you can configure this crate to find the -installation via an environment variable: - -``` -set OPENSSL_DIR=C:\OpenSSL-Win64 -``` - -During the installation process if you select "Copy OpenSSL DLLs to: The OpenSSL binaries (/bin) -directory", you will need to add them to the `PATH` environment variable: - -``` -set PATH=%PATH%;C:\OpenSSL-Win64\bin -``` - -Now you will need to [install root certificates.](#acquiring-root-certificates) - -#### Installing OpenSSL 1.0.2 using vcpkg - -Install [vcpkg](https://github.com/Microsoft/vcpkg), and install the OpenSSL port like this: - -```Batchfile -vcpkg install openssl:x64-windows -set VCPKG_ROOT=c:\path\to\vcpkg\installation -cargo build -``` - -For more information see the vcpkg build helper [documentation](http://docs.rs/vcpkg). -To finsh setting up OpenSSL you will need to [install root certificates.](#acquiring-root-certificates) - -#### Acquiring Root Certificates - -Neither of the above OpenSSL distributions ship with any root certificates. -So to make requests to servers on the internet, you have to install them -manually. Download the [cacert.pem file from here], copy it somewhere safe -(`C:\OpenSSL-Win64\certs` is a good place) and point the `SSL_CERT_FILE` -environment variable there: - -``` -set SSL_CERT_FILE=C:\OpenSSL-Win64\certs\cacert.pem -``` - -[cacert.pem file from here]: https://curl.haxx.se/docs/caextract.html - -After that, you're just a `cargo build` away! - -### Windows GNU (MinGW) - -The easiest way to acquire OpenSSL when working with MinGW is to ensure you're -using [MSYS2](http://msys2.github.io) and to then execute: - -``` -# 32-bit -pacman -S mingw-w64-i686-openssl - -# 64-bit -pacman -S mingw-w64-x86_64-openssl -``` - -And after that, a `cargo build` should be all you need! - -### Manual configuration - -rust-openssl's build script will by default attempt to locate OpenSSL via -pkg-config or other system-specific mechanisms. This will not work in some -situations however, for example cross compiling or when using a copy of OpenSSL -other than the normal system install. - -The build script can be configured via environment variables: - -* `OPENSSL_DIR` - If specified, a directory that will be used to find - OpenSSL installation. It's expected that under this directory the `include` - folder has header files and a `lib` folder has the runtime libraries. -* `OPENSSL_LIB_DIR` - If specified, a directory that will be used to find - OpenSSL libraries. Overrides the `lib` folder implied by `OPENSSL_DIR` - (if specified). -* `OPENSSL_INCLUDE_DIR` - If specified, a directory that will be used to find - OpenSSL header files. Overrides the `include` folder implied by `OPENSSL_DIR` - (if specified). -* `OPENSSL_STATIC` - If specified, OpenSSL libraries will be statically rather - than dynamically linked. -* `OPENSSL_LIBS` - If specified, the names of the OpenSSL libraries that will be - linked, e.g. `ssl:crypto`. - -If `OPENSSL_DIR` or `OPENSSL_LIB_DIR` and `OPENSSL_INCLUDE_DIR` is specified, -then the build script will skip the pkg-config step. - -For target-specific configuration, each of these environment variables can be -prefixed by an upper-cased target, for example, -`X86_64_UNKNOWN_LINUX_GNU_OPENSSL_DIR`. This can be useful in cross compilation -contexts. - -### 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 under the terms of both the Apache License, -Version 2.0 and the MIT license without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/aes.rs cargo-0.26.0/vendor/openssl-0.9.24/src/aes.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/aes.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/aes.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,180 +0,0 @@ -//! Low level AES IGE functionality -//! -//! AES ECB, CBC, XTS, CTR, CFB, GCM and other conventional symmetric encryption -//! modes are found in [`symm`]. This is the implementation of AES IGE. -//! -//! Advanced Encryption Standard (AES) provides symmetric key cipher that -//! the same key is used to encrypt and decrypt data. This implementation -//! uses 128, 192, or 256 bit keys. This module provides functions to -//! create a new key with [`new_encrypt`] and perform an encryption/decryption -//! using that key with [`aes_ige`]. -//! -//! [`new_encrypt`]: struct.AesKey.html#method.new_encrypt -//! [`aes_ige`]: fn.aes_ige.html -//! -//! The [`symm`] module should be used in preference to this module in most cases. -//! The IGE block cypher is a non-traditional cipher mode. More traditional AES -//! encryption methods are found in the [`Crypter`] and [`Cipher`] structs. -//! -//! [`symm`]: ../symm/index.html -//! [`Crypter`]: ../symm/struct.Crypter.html -//! [`Cipher`]: ../symm/struct.Cipher.html -//! -//! # Examples -//! -//! ```rust -//! # extern crate openssl; -//! extern crate hex; -//! use openssl::aes::{AesKey, KeyError, aes_ige}; -//! use openssl::symm::Mode; -//! use hex::{FromHex, ToHex}; -//! -//! fn decrypt() -> Result<(), KeyError> { -//! let raw_key = "000102030405060708090A0B0C0D0E0F"; -//! let hex_cipher = "12345678901234561234567890123456"; -//! let randomness = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"; -//! if let (Ok(key_as_u8), Ok(cipher_as_u8), Ok(mut iv_as_u8)) = -//! (Vec::from_hex(raw_key), Vec::from_hex(hex_cipher), Vec::from_hex(randomness)) { -//! let key = AesKey::new_encrypt(&key_as_u8)?; -//! let mut output = vec![0u8; cipher_as_u8.len()]; -//! aes_ige(&cipher_as_u8, &mut output, &key, &mut iv_as_u8, Mode::Encrypt); -//! assert_eq!(output.to_hex(), "a6ad974d5cea1d36d2f367980907ed32"); -//! } -//! Ok(()) -//! } -//! -//! # fn main() { -//! # decrypt(); -//! # } -use ffi; -use std::mem; -use libc::c_int; - -use symm::Mode; - -/// Provides Error handling for parsing keys. -#[derive(Debug)] -pub struct KeyError(()); - -/// The key used to encrypt or decrypt cipher blocks. -pub struct AesKey(ffi::AES_KEY); - -impl AesKey { - /// Prepares a key for encryption. - /// - /// # Failure - /// - /// Returns an error if the key is not 128, 192, or 256 bits. - pub fn new_encrypt(key: &[u8]) -> Result { - unsafe { - assert!(key.len() <= c_int::max_value() as usize / 8); - - let mut aes_key = mem::uninitialized(); - let r = ffi::AES_set_encrypt_key( - key.as_ptr() as *const _, - key.len() as c_int * 8, - &mut aes_key, - ); - if r == 0 { - Ok(AesKey(aes_key)) - } else { - Err(KeyError(())) - } - } - } - - /// Prepares a key for decryption. - /// - /// # Failure - /// - /// Returns an error if the key is not 128, 192, or 256 bits. - pub fn new_decrypt(key: &[u8]) -> Result { - unsafe { - assert!(key.len() <= c_int::max_value() as usize / 8); - - let mut aes_key = mem::uninitialized(); - let r = ffi::AES_set_decrypt_key( - key.as_ptr() as *const _, - key.len() as c_int * 8, - &mut aes_key, - ); - - if r == 0 { - Ok(AesKey(aes_key)) - } else { - Err(KeyError(())) - } - } - } -} - -/// Performs AES IGE encryption or decryption -/// -/// AES IGE (Infinite Garble Extension) is a form of AES block cipher utilized in -/// OpenSSL. Infinite Garble referes to propogating forward errors. IGE, like other -/// block ciphers implemented for AES requires an initalization vector. The IGE mode -/// allows a stream of blocks to be encrypted or decrypted without having the entire -/// plaintext available. For more information, visit [AES IGE Encryption]. -/// -/// This block cipher uses 16 byte blocks. The rust implmentation will panic -/// if the input or output does not meet this 16-byte boundry. Attention must -/// be made in this low level implementation to pad the value to the 128-bit boundry. -/// -/// [AES IGE Encryption]: http://www.links.org/files/openssl-ige.pdf -/// -/// # Panics -/// -/// Panics if `in_` is not the same length as `out`, if that length is not a multiple of 16, or if -/// `iv` is not at least 32 bytes. -pub fn aes_ige(in_: &[u8], out: &mut [u8], key: &AesKey, iv: &mut [u8], mode: Mode) { - unsafe { - assert!(in_.len() == out.len()); - assert!(in_.len() % ffi::AES_BLOCK_SIZE as usize == 0); - assert!(iv.len() >= ffi::AES_BLOCK_SIZE as usize * 2); - - let mode = match mode { - Mode::Encrypt => ffi::AES_ENCRYPT, - Mode::Decrypt => ffi::AES_DECRYPT, - }; - ffi::AES_ige_encrypt( - in_.as_ptr() as *const _, - out.as_mut_ptr() as *mut _, - in_.len(), - &key.0, - iv.as_mut_ptr() as *mut _, - mode, - ); - } -} - -#[cfg(test)] -mod test { - use hex::FromHex; - - use symm::Mode; - use super::*; - - // From https://www.mgp25.com/AESIGE/ - #[test] - fn ige_vector_1() { - let raw_key = "000102030405060708090A0B0C0D0E0F"; - let raw_iv = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"; - let raw_pt = "0000000000000000000000000000000000000000000000000000000000000000"; - let raw_ct = "1A8519A6557BE652E9DA8E43DA4EF4453CF456B4CA488AA383C79C98B34797CB"; - - let key = AesKey::new_encrypt(&Vec::from_hex(raw_key).unwrap()).unwrap(); - let mut iv = Vec::from_hex(raw_iv).unwrap(); - let pt = Vec::from_hex(raw_pt).unwrap(); - let ct = Vec::from_hex(raw_ct).unwrap(); - - let mut ct_actual = vec![0; ct.len()]; - aes_ige(&pt, &mut ct_actual, &key, &mut iv, Mode::Encrypt); - assert_eq!(ct_actual, ct); - - let key = AesKey::new_decrypt(&Vec::from_hex(raw_key).unwrap()).unwrap(); - let mut iv = Vec::from_hex(raw_iv).unwrap(); - let mut pt_actual = vec![0; pt.len()]; - aes_ige(&ct, &mut pt_actual, &key, &mut iv, Mode::Decrypt); - assert_eq!(pt_actual, pt); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/asn1.rs cargo-0.26.0/vendor/openssl-0.9.24/src/asn1.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/asn1.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/asn1.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,295 +0,0 @@ -#![deny(missing_docs)] - -//! Defines the format of certificiates -//! -//! This module is used by [`x509`] and other certificate building functions -//! to describe time, strings, and objects. -//! -//! Abstract Syntax Notation One is an interface description language. -//! The specification comes from [X.208] by OSI, and rewritten in X.680. -//! ASN.1 describes properties of an object with a type set. Those types -//! can be atomic, structured, choice, and other (CHOICE and ANY). These -//! types are expressed as a number and the assignment operator ::= gives -//! the type a name. -//! -//! The implementation here provides a subset of the ASN.1 types that OpenSSL -//! uses, especially in the properties of a certificate used in HTTPS. -//! -//! [X.208]: https://www.itu.int/rec/T-REC-X.208-198811-W/en -//! [`x509`]: ../x509/struct.X509Builder.html -//! -//! ## Examples -//! -//! ``` -//! use openssl::asn1::Asn1Time; -//! let tomorrow = Asn1Time::days_from_now(1); -//! ``` -use ffi; -use foreign_types::{ForeignType, ForeignTypeRef}; -use libc::{c_long, c_char, c_int}; -use std::fmt; -use std::ptr; -use std::slice; -use std::str; - -use {cvt, cvt_p}; -use bio::MemBio; -use error::ErrorStack; -use nid::Nid; -use string::OpensslString; - -foreign_type_and_impl_send_sync! { - type CType = ffi::ASN1_GENERALIZEDTIME; - fn drop = ffi::ASN1_GENERALIZEDTIME_free; - - /// Non-UTC representation of time - /// - /// If a time can be represented by UTCTime, UTCTime is used - /// otherwise, ASN1_GENERALIZEDTIME is used. This would be, for - /// example outside the year range of 1950-2049. - /// - /// [ASN1_GENERALIZEDTIME_set] documentation from OpenSSL provides - /// further details of implmentation. Note: these docs are from the master - /// branch as documentation on the 1.1.0 branch did not include this page. - /// - /// [ASN1_GENERALIZEDTIME_set]: https://www.openssl.org/docs/manmaster/man3/ASN1_GENERALIZEDTIME_set.html - pub struct Asn1GeneralizedTime; - /// Reference to a [`Asn1GeneralizedTime`] - /// - /// [`Asn1GeneralizedTime`]: struct.Asn1GeneralizedTime.html - pub struct Asn1GeneralizedTimeRef; -} - -impl fmt::Display for Asn1GeneralizedTimeRef { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - unsafe { - let mem_bio = MemBio::new()?; - cvt(ffi::ASN1_GENERALIZEDTIME_print( - mem_bio.as_ptr(), - self.as_ptr(), - ))?; - write!(f, "{}", str::from_utf8_unchecked(mem_bio.get_buf())) - } - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::ASN1_TIME; - fn drop = ffi::ASN1_TIME_free; - /// Time storage and comparison - /// - /// Asn1Time should be used to store and share time information - /// using certificates. If Asn1Time is set using a string, it must - /// be in either YYMMDDHHMMSSZ, YYYYMMDDHHMMSSZ, or another ASN.1 format. - /// - /// [ASN_TIME_set] documentation at OpenSSL explains the ASN.1 implementaiton - /// used by OpenSSL. - /// - /// [ASN_TIME_set]: https://www.openssl.org/docs/man1.1.0/crypto/ASN1_TIME_set.html - pub struct Asn1Time; - /// Reference to an [`Asn1Time`] - /// - /// [`Asn1Time`]: struct.Asn1Time.html - pub struct Asn1TimeRef; -} - -impl fmt::Display for Asn1TimeRef { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - unsafe { - let mem_bio = MemBio::new()?; - cvt(ffi::ASN1_TIME_print(mem_bio.as_ptr(), self.as_ptr()))?; - write!(f, "{}", str::from_utf8_unchecked(mem_bio.get_buf())) - } - } -} - -impl Asn1Time { - fn from_period(period: c_long) -> Result { - ffi::init(); - - unsafe { - let handle = cvt_p(ffi::X509_gmtime_adj(ptr::null_mut(), period))?; - Ok(Asn1Time::from_ptr(handle)) - } - } - - /// Creates a new time on specified interval in days from now - pub fn days_from_now(days: u32) -> Result { - Asn1Time::from_period(days as c_long * 60 * 60 * 24) - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::ASN1_STRING; - fn drop = ffi::ASN1_STRING_free; - /// Primary ASN.1 type used by OpenSSL - /// - /// Almost all ASN.1 types in OpenSSL are represented by ASN1_STRING - /// structures. This implementation uses [ASN1_STRING-to_UTF8] to preserve - /// compatibility with Rust's String. - /// - /// [ASN1_STRING-to_UTF8]: https://www.openssl.org/docs/man1.1.0/crypto/ASN1_STRING_to_UTF8.html - pub struct Asn1String; - /// Reference to [`Asn1String`] - /// - /// [`Asn1String`]: struct.Asn1String.html - pub struct Asn1StringRef; -} - -impl Asn1StringRef { - /// Converts the ASN.1 underlying format to UTF8 - /// - /// ASN.1 strings may utilize UTF-16, ASCII, BMP, or UTF8. This is important to - /// consume the string in a meaningful way without knowing the underlying - /// format. - pub fn as_utf8(&self) -> Result { - unsafe { - let mut ptr = ptr::null_mut(); - let len = ffi::ASN1_STRING_to_UTF8(&mut ptr, self.as_ptr()); - if len < 0 { - return Err(ErrorStack::get()); - } - - Ok(OpensslString::from_ptr(ptr as *mut c_char)) - } - } - - /// Return the string as an array of bytes - /// - /// The bytes do not directly corespond to UTF-8 encoding. To interact with - /// strings in rust, it is preferable to use [`as_utf8`] - /// - /// [`as_utf8`]: struct.Asn1String.html#method.as_utf8 - pub fn as_slice(&self) -> &[u8] { - unsafe { slice::from_raw_parts(ASN1_STRING_data(self.as_ptr()), self.len()) } - } - - /// Return the length of the Asn1String (number of bytes) - pub fn len(&self) -> usize { - unsafe { ffi::ASN1_STRING_length(self.as_ptr()) as usize } - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::ASN1_INTEGER; - fn drop = ffi::ASN1_INTEGER_free; - - /// Numeric representation - /// - /// Integers in ASN.1 may include BigNum, int64 or uint64. BigNum implementation - /// can be found within [`bn`] module. - /// - /// OpenSSL documentation includes [`ASN1_INTEGER_set`]. - /// - /// [`bn`]: ../bn/index.html - /// [`ASN1_INTEGER_set`]: https://www.openssl.org/docs/man1.1.0/crypto/ASN1_INTEGER_set.html - pub struct Asn1Integer; - /// Reference to [`Asn1Integer`] - /// - /// [`Asn1Integer`]: struct.Asn1Integer.html - pub struct Asn1IntegerRef; -} - -impl Asn1IntegerRef { - /// Returns value of ASN.1 integer, or -1 if there is an error, and 0 if the integer is Null. - /// - /// OpenSSL documentation at [`ASN1_INTEGER_get`]. - /// - /// [`ASN1_INTEGER_get`]: https://www.openssl.org/docs/man1.1.0/crypto/ASN1_INTEGER_get.html - pub fn get(&self) -> i64 { - unsafe { ::ffi::ASN1_INTEGER_get(self.as_ptr()) as i64 } - } - /// Sets the ASN.1 value to the value of a signed 32-bit integer, for larger numbers - /// see [`bn`]. - /// - /// OpenSSL documentation at [`ASN1_INTEGER_set`] - /// - /// [`bn`]: ../bn/struct.BigNumRef.html#method.to_asn1_integer - /// [`ASN1_INTEGER_set`]: https://www.openssl.org/docs/man1.1.0/crypto/ASN1_INTEGER_set.html - pub fn set(&mut self, value: i32) -> Result<(), ErrorStack> { - unsafe { cvt(::ffi::ASN1_INTEGER_set(self.as_ptr(), value as c_long)).map(|_| ()) } - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::ASN1_BIT_STRING; - fn drop = ffi::ASN1_BIT_STRING_free; - /// Sequence of bytes - /// - /// Asn1BitString is used in [`x509`] certificates for the signature. - /// The bit string acts as a collection of bytes. - /// - /// [`x509`]: ../x509/struct.X509.html#method.signature - pub struct Asn1BitString; - /// Reference to [`Asn1BitString`] - /// - /// [`Asn1BitString`]: struct.Asn1BitString.html - pub struct Asn1BitStringRef; -} - -impl Asn1BitStringRef { - /// Returns the Asn1BitString as a slice - pub fn as_slice(&self) -> &[u8] { - unsafe { slice::from_raw_parts(ASN1_STRING_data(self.as_ptr() as *mut _), self.len()) } - } - /// Length of Asn1BitString in number of bytes. - pub fn len(&self) -> usize { - unsafe { ffi::ASN1_STRING_length(self.as_ptr() as *mut _) as usize } - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::ASN1_OBJECT; - fn drop = ffi::ASN1_OBJECT_free; - - /// Object Identifier - /// - /// Represents an ASN.1 Object. Typically, NIDs, or numeric identifiers - /// are stored as a table within the [`Nid`] module. These constants are - /// used to determine attributes of a certificate, such as mapping the - /// attribute "CommonName" to "CN" which is represented as the OID of 13. - /// This attribute is a constant in the [`nid::COMMONNAME`]. - /// - /// OpenSSL documentation at [`OBJ_nid2obj`] - /// - /// [`Nid`]: ../nid/index.html - /// [`nid::COMMONNAME`]: ../nid/constant.COMMONNAME.html - /// [`OBJ_nid2obj`]: https://www.openssl.org/docs/man1.1.0/crypto/OBJ_obj2nid.html - pub struct Asn1Object; - /// Reference to [`Asn1Object`] - /// - /// [`Asn1Object`]: struct.Asn1Object.html - pub struct Asn1ObjectRef; -} - -impl Asn1ObjectRef { - /// Returns the NID associated with this OID. - pub fn nid(&self) -> Nid { - unsafe { Nid::from_raw(ffi::OBJ_obj2nid(self.as_ptr())) } - } -} - -impl fmt::Display for Asn1ObjectRef { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - unsafe { - let mut buf = [0; 80]; - let len = ffi::OBJ_obj2txt( - buf.as_mut_ptr() as *mut _, - buf.len() as c_int, - self.as_ptr(), - 0, - ); - let s = str::from_utf8(&buf[..len as usize]).map_err(|_| fmt::Error)?; - fmt.write_str(s) - } - } -} - -#[cfg(any(ossl101, ossl102))] -use ffi::ASN1_STRING_data; - -#[cfg(ossl110)] -#[allow(bad_style)] -unsafe fn ASN1_STRING_data(s: *mut ffi::ASN1_STRING) -> *mut ::libc::c_uchar { - ffi::ASN1_STRING_get0_data(s) as *mut _ -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/bio.rs cargo-0.26.0/vendor/openssl-0.9.24/src/bio.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/bio.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/bio.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -use std::marker::PhantomData; -use std::ptr; -use std::slice; -use libc::c_int; -use ffi; - -use cvt_p; -use error::ErrorStack; - -pub struct MemBioSlice<'a>(*mut ffi::BIO, PhantomData<&'a [u8]>); - -impl<'a> Drop for MemBioSlice<'a> { - fn drop(&mut self) { - unsafe { - ffi::BIO_free_all(self.0); - } - } -} - -impl<'a> MemBioSlice<'a> { - pub fn new(buf: &'a [u8]) -> Result, ErrorStack> { - ffi::init(); - - assert!(buf.len() <= c_int::max_value() as usize); - let bio = unsafe { - cvt_p(BIO_new_mem_buf( - buf.as_ptr() as *const _, - buf.len() as c_int, - ))? - }; - - Ok(MemBioSlice(bio, PhantomData)) - } - - pub fn as_ptr(&self) -> *mut ffi::BIO { - self.0 - } -} - -pub struct MemBio(*mut ffi::BIO); - -impl Drop for MemBio { - fn drop(&mut self) { - unsafe { - ffi::BIO_free_all(self.0); - } - } -} - -impl MemBio { - pub fn new() -> Result { - ffi::init(); - - let bio = unsafe { cvt_p(ffi::BIO_new(ffi::BIO_s_mem()))? }; - Ok(MemBio(bio)) - } - - pub fn as_ptr(&self) -> *mut ffi::BIO { - self.0 - } - - pub fn get_buf(&self) -> &[u8] { - unsafe { - let mut ptr = ptr::null_mut(); - let len = ffi::BIO_get_mem_data(self.0, &mut ptr); - slice::from_raw_parts(ptr as *const _ as *const _, len as usize) - } - } -} - -#[cfg(not(ossl101))] -use ffi::BIO_new_mem_buf; - -#[cfg(ossl101)] -#[allow(bad_style)] -unsafe fn BIO_new_mem_buf(buf: *const ::libc::c_void, len: ::libc::c_int) -> *mut ffi::BIO { - ffi::BIO_new_mem_buf(buf as *mut _, len) -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/bn.rs cargo-0.26.0/vendor/openssl-0.9.24/src/bn.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/bn.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/bn.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1401 +0,0 @@ -//! BigNum implementation -//! -//! Large numbers are important for a cryptographic library. OpenSSL implementation -//! of BigNum uses dynamically assigned memory to store an array of bit chunks. This -//! allows numbers of any size to be compared and mathematical functions performed. -//! -//! OpenSSL wiki describes the [`BIGNUM`] data structure. -//! -//! # Examples -//! -//! ``` -//! use openssl::bn::BigNum; -//! use openssl::error::ErrorStack; -//! -//! fn bignums() -> Result< (), ErrorStack > { -//! let a = BigNum::new()?; // a = 0 -//! let b = BigNum::from_dec_str("1234567890123456789012345")?; -//! let c = &a * &b; -//! assert_eq!(a,c); -//! Ok(()) -//! } -//! # fn main() { -//! # bignums(); -//! # } -//! -//! [`BIGNUM`]: https://wiki.openssl.org/index.php/Manual:Bn_internal(3) -use ffi; -use foreign_types::{ForeignType, ForeignTypeRef}; -use libc::c_int; -use std::cmp::Ordering; -use std::ffi::CString; -use std::{fmt, ptr}; -use std::ops::{Add, Div, Mul, Neg, Rem, Shl, Shr, Sub, Deref}; - -use {cvt, cvt_p, cvt_n}; -use asn1::Asn1Integer; -use error::ErrorStack; -use string::OpensslString; - -#[cfg(ossl10x)] -use ffi::{get_rfc2409_prime_768 as BN_get_rfc2409_prime_768, - get_rfc2409_prime_1024 as BN_get_rfc2409_prime_1024, - get_rfc3526_prime_1536 as BN_get_rfc3526_prime_1536, - get_rfc3526_prime_2048 as BN_get_rfc3526_prime_2048, - get_rfc3526_prime_3072 as BN_get_rfc3526_prime_3072, - get_rfc3526_prime_4096 as BN_get_rfc3526_prime_4096, - get_rfc3526_prime_6144 as BN_get_rfc3526_prime_6144, - get_rfc3526_prime_8192 as BN_get_rfc3526_prime_8192}; - -#[cfg(ossl110)] -use ffi::{BN_get_rfc2409_prime_768, BN_get_rfc2409_prime_1024, BN_get_rfc3526_prime_1536, - BN_get_rfc3526_prime_2048, BN_get_rfc3526_prime_3072, BN_get_rfc3526_prime_4096, - BN_get_rfc3526_prime_6144, BN_get_rfc3526_prime_8192}; - -/// Options for the most significant bits of a randomly generated `BigNum`. -pub struct MsbOption(c_int); - -/// The most significant bit of the number may be 0. -pub const MSB_MAYBE_ZERO: MsbOption = MsbOption(-1); - -/// The most significant bit of the number must be 1. -pub const MSB_ONE: MsbOption = MsbOption(0); - -/// The most significant two bits of the number must be 1. -/// -/// The number of bits in the product of two such numbers will always be exactly twice the number -/// of bits in the original numbers. -pub const TWO_MSB_ONE: MsbOption = MsbOption(1); - -foreign_type_and_impl_send_sync! { - type CType = ffi::BN_CTX; - fn drop = ffi::BN_CTX_free; - - /// Temporary storage for BigNums on the secure heap - /// - /// BigNum values are stored dynamically and therefore can be expensive - /// to allocate. BigNumContext and the OpenSSL [`BN_CTX`] structure are used - /// internally when passing BigNum values between subroutines. - /// - /// [`BN_CTX`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_CTX_new.html - pub struct BigNumContext; - /// Reference to [`BigNumContext`] - /// - /// [`BigNumContext`]: struct.BigNumContext.html - pub struct BigNumContextRef; -} - -impl BigNumContext { - /// Returns a new `BigNumContext`. - /// - /// See OpenSSL documentation at [`BN_CTX_new`]. - /// - /// [`BN_CTX_new`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_CTX_new.html - pub fn new() -> Result { - unsafe { - ffi::init(); - cvt_p(ffi::BN_CTX_new()).map(BigNumContext) - } - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::BIGNUM; - fn drop = ffi::BN_free; - - /// Dynamically sized large number impelementation - /// - /// Perform large number mathematics. Create a new BigNum - /// with [`new`]. Perform stanard mathematics on large numbers using - /// methods from [`Dref`] - /// - /// OpenSSL documenation at [`BN_new`]. - /// - /// [`new`]: struct.BigNum.html#method.new - /// [`Dref`]: struct.BigNum.html#deref-methods - /// [`BN_new`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_new.html - /// - /// # Examples - /// ``` - /// use openssl::bn::BigNum; - /// # use openssl::error::ErrorStack; - /// # fn bignums() -> Result< (), ErrorStack > { - /// let little_big = BigNum::from_u32(std::u32::MAX)?; - /// assert_eq!(*&little_big.num_bytes(), 4); - /// # Ok(()) - /// # } - /// # fn main () { bignums(); } - /// ``` - pub struct BigNum; - /// Reference to a [`BigNum`] - /// - /// [`BigNum`]: struct.BigNum.html - pub struct BigNumRef; -} - -impl BigNumRef { - /// Erases the memory used by this `BigNum`, resetting its value to 0. - /// - /// This can be used to destroy sensitive data such as keys when they are no longer needed. - /// - /// OpenSSL documentation at [`BN_clear`] - /// - /// [`BN_clear`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_clear.html - pub fn clear(&mut self) { - unsafe { ffi::BN_clear(self.as_ptr()) } - } - - /// Adds a `u32` to `self`. - /// - /// OpenSSL documentation at [`BN_add_word`] - /// - /// [`BN_add_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_add_word.html - pub fn add_word(&mut self, w: u32) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_add_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } - } - - /// Subtracts a `u32` from `self`. - /// - /// OpenSSL documentation at [`BN_sub_word`] - /// - /// [`BN_sub_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_sub_word.html - pub fn sub_word(&mut self, w: u32) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_sub_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } - } - - /// Multiplies a `u32` by `self`. - /// - /// OpenSSL documentation at [`BN_mul_word`] - /// - /// [`BN_mul_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mul_word.html - pub fn mul_word(&mut self, w: u32) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_mul_word(self.as_ptr(), w as ffi::BN_ULONG)).map(|_| ()) } - } - - /// Divides `self` by a `u32`, returning the remainder. - /// - /// OpenSSL documentation at [`BN_div_word`] - /// - /// [`BN_div_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div_word.html - pub fn div_word(&mut self, w: u32) -> Result { - unsafe { - let r = ffi::BN_div_word(self.as_ptr(), w.into()); - if r == ffi::BN_ULONG::max_value() { - Err(ErrorStack::get()) - } else { - Ok(r.into()) - } - } - } - - /// Returns the result of `self` modulo `w`. - /// - /// OpenSSL documentation at [`BN_mod_word`] - /// - /// [`BN_mod_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_word.html - pub fn mod_word(&self, w: u32) -> Result { - unsafe { - let r = ffi::BN_mod_word(self.as_ptr(), w.into()); - if r == ffi::BN_ULONG::max_value() { - Err(ErrorStack::get()) - } else { - Ok(r.into()) - } - } - } - - /// Places a cryptographically-secure pseudo-random nonnegative - /// number less than `self` in `rnd`. - /// - /// OpenSSL documentation at [`BN_rand_range`] - /// - /// [`BN_rand_range`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rand_range.html - pub fn rand_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_rand_range(rnd.as_ptr(), self.as_ptr())).map(|_| ()) } - } - - /// The cryptographically weak counterpart to `rand_in_range`. - /// - /// OpenSSL documentation at [`BN_pseudo_rand_range`] - /// - /// [`BN_pseudo_rand_range`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_pseudo_rand_range.html - pub fn pseudo_rand_range(&self, rnd: &mut BigNumRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_pseudo_rand_range(rnd.as_ptr(), self.as_ptr())).map(|_| ()) } - } - - /// Sets bit `n`. Equivalent to `self |= (1 << n)`. - /// - /// When setting a bit outside of `self`, it is expanded. - /// - /// OpenSSL documentation at [`BN_set_bit`] - /// - /// [`BN_set_bit`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_set_bit.html - pub fn set_bit(&mut self, n: i32) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_set_bit(self.as_ptr(), n.into())).map(|_| ()) } - } - - /// Clears bit `n`, setting it to 0. Equivalent to `self &= ~(1 << n)`. - /// - /// When clearing a bit outside of `self`, an error is returned. - /// - /// OpenSSL documentation at [`BN_clear_bit`] - /// - /// [`BN_clear_bit`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_clear_bit.html - pub fn clear_bit(&mut self, n: i32) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_clear_bit(self.as_ptr(), n.into())).map(|_| ()) } - } - - /// Returns `true` if the `n`th bit of `self` is set to 1, `false` otherwise. - /// - /// OpenSSL documentation at [`BN_is_bit_set`] - /// - /// [`BN_is_bit_set`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_is_bit_set.html - pub fn is_bit_set(&self, n: i32) -> bool { - unsafe { ffi::BN_is_bit_set(self.as_ptr(), n.into()) == 1 } - } - - /// Truncates `self` to the lowest `n` bits. - /// - /// An error occurs if `self` is already shorter than `n` bits. - /// - /// OpenSSL documentation at [`BN_mask_bits`] - /// - /// [`BN_mask_bits`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mask_bits.html - pub fn mask_bits(&mut self, n: i32) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_mask_bits(self.as_ptr(), n.into())).map(|_| ()) } - } - - /// Places `a << 1` in `self`. Equivalent to `self * 2`. - /// - /// OpenSSL documentation at [`BN_lshift1`] - /// - /// [`BN_lshift1`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_lshift1.html - pub fn lshift1(&mut self, a: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_lshift1(self.as_ptr(), a.as_ptr())).map(|_| ()) } - } - - /// Places `a >> 1` in `self`. Equivalent to `self / 2`. - /// - /// OpenSSL documentation at [`BN_rshift1`] - /// - /// [`BN_rshift1`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rshift1.html - pub fn rshift1(&mut self, a: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_rshift1(self.as_ptr(), a.as_ptr())).map(|_| ()) } - } - - /// Places `a + b` in `self`. [`core::ops::Add`] is also implemented for `BigNumRef`. - /// - /// OpenSSL documentation at [`BN_add`] - /// - /// [`core::ops::Add`]: struct.BigNumRef.html#method.add - /// [`BN_add`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_add.html - pub fn checked_add(&mut self, a: &BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_add(self.as_ptr(), a.as_ptr(), b.as_ptr())).map(|_| ()) } - } - - /// Places `a - b` in `self`. [`core::ops::Sub`] is also implemented for `BigNumRef`. - /// - /// OpenSSL documentation at [`BN_sub`] - /// - /// [`core::ops::Sub`]: struct.BigNumRef.html#method.sub - /// [`BN_sub`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_sub.html - pub fn checked_sub(&mut self, a: &BigNumRef, b: &BigNumRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_sub(self.as_ptr(), a.as_ptr(), b.as_ptr())).map(|_| ()) } - } - - /// Places `a << n` in `self`. Equivalent to `a * 2 ^ n`. - /// - /// OpenSSL documentation at [`BN_lshift`] - /// - /// [`BN_lshift`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_lshift.html - pub fn lshift(&mut self, a: &BigNumRef, n: i32) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_lshift(self.as_ptr(), a.as_ptr(), n.into())).map(|_| ()) } - } - - /// Places `a >> n` in `self`. Equivalent to `a / 2 ^ n`. - /// - /// OpenSSL documentation at [`BN_rshift`] - /// - /// [`BN_rshift`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rshift.html - pub fn rshift(&mut self, a: &BigNumRef, n: i32) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_rshift(self.as_ptr(), a.as_ptr(), n.into())).map(|_| ()) } - } - - /// Creates a new BigNum with the same value. - /// - /// OpenSSL documentation at [`BN_dup`] - /// - /// [`BN_dup`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_dup.html - pub fn to_owned(&self) -> Result { - unsafe { cvt_p(ffi::BN_dup(self.as_ptr())).map(|b| BigNum::from_ptr(b)) } - } - - /// Sets the sign of `self`. Pass true to set `self` to a negative. False sets - /// `self` positive. - pub fn set_negative(&mut self, negative: bool) { - unsafe { ffi::BN_set_negative(self.as_ptr(), negative as c_int) } - } - - /// Compare the absolute values of `self` and `oth`. - /// - /// OpenSSL documentation at [`BN_ucmp`] - /// - /// [`BN_ucmp`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_ucmp.html - /// - /// # Examples - /// - /// ``` - /// # use openssl::bn::BigNum; - /// # use std::cmp::Ordering; - /// let s = -BigNum::from_u32(8).unwrap(); - /// let o = BigNum::from_u32(8).unwrap(); - /// - /// assert_eq!(s.ucmp(&o), Ordering::Equal); - /// ``` - pub fn ucmp(&self, oth: &BigNumRef) -> Ordering { - unsafe { ffi::BN_ucmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } - } - - /// Returns `true` if `self` is negative. - pub fn is_negative(&self) -> bool { - self._is_negative() - } - - #[cfg(ossl10x)] - fn _is_negative(&self) -> bool { - unsafe { (*self.as_ptr()).neg == 1 } - } - - #[cfg(ossl110)] - fn _is_negative(&self) -> bool { - unsafe { ffi::BN_is_negative(self.as_ptr()) == 1 } - } - - /// Returns the number of significant bits in `self`. - /// - /// OpenSSL documentation at [`BN_num_bits`] - /// - /// [`BN_num_bits`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_num_bits.html - pub fn num_bits(&self) -> i32 { - unsafe { ffi::BN_num_bits(self.as_ptr()) as i32 } - } - - /// Returns the size of `self` in bytes. Implemented natively. - pub fn num_bytes(&self) -> i32 { - (self.num_bits() + 7) / 8 - } - - /// Generates a cryptographically strong pseudo-random `BigNum`, placing it in `self`. - /// - /// # Parameters - /// - /// * `bits`: Length of the number in bits. - /// * `msb`: The desired properties of the most significant bit. See [`constants`]. - /// * `odd`: If `true`, the generated number will be odd. - /// - /// # Examples - /// - /// ``` - /// use openssl::bn::{BigNum,MSB_MAYBE_ZERO}; - /// use openssl::error::ErrorStack; - /// - /// fn generate_random() -> Result< BigNum, ErrorStack > { - /// let mut big = BigNum::new()?; - /// - /// // Generates a 128-bit odd random number - /// big.rand(128, MSB_MAYBE_ZERO, true); - /// Ok((big)) - /// } - /// ``` - /// - /// OpenSSL documentation at [`BN_rand`] - /// - /// [`constants`]: index.html#constants - /// [`BN_rand`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_rand.html - pub fn rand(&mut self, bits: i32, msb: MsbOption, odd: bool) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_rand( - self.as_ptr(), - bits.into(), - msb.0, - odd as c_int, - )).map(|_| ()) - } - } - - /// The cryptographically weak counterpart to `rand`. Not suitable for key generation. - /// - /// OpenSSL documentation at [`BN_psuedo_rand`] - /// - /// [`BN_psuedo_rand`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_pseudo_rand.html - pub fn pseudo_rand(&mut self, bits: i32, msb: MsbOption, odd: bool) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_pseudo_rand( - self.as_ptr(), - bits.into(), - msb.0, - odd as c_int, - )).map(|_| ()) - } - } - - /// Generates a prime number, placing it in `self`. - /// - /// # Parameters - /// - /// * `bits`: The length of the prime in bits (lower bound). - /// * `safe`: If true, returns a "safe" prime `p` so that `(p-1)/2` is also prime. - /// * `add`/`rem`: If `add` is set to `Some(add)`, `p % add == rem` will hold, where `p` is the - /// generated prime and `rem` is `1` if not specified (`None`). - /// - /// # Examples - /// - /// ``` - /// use openssl::bn::BigNum; - /// use openssl::error::ErrorStack; - /// - /// fn generate_weak_prime() -> Result< BigNum, ErrorStack > { - /// let mut big = BigNum::new()?; - /// - /// // Generates a 128-bit simple prime number - /// big.generate_prime(128, false, None, None); - /// Ok((big)) - /// } - /// ``` - /// - /// OpenSSL documentation at [`BN_generate_prime_ex`] - /// - /// [`BN_generate_prime_ex`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_generate_prime_ex.html - pub fn generate_prime( - &mut self, - bits: i32, - safe: bool, - add: Option<&BigNumRef>, - rem: Option<&BigNumRef>, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_generate_prime_ex( - self.as_ptr(), - bits as c_int, - safe as c_int, - add.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()), - rem.map(|n| n.as_ptr()).unwrap_or(ptr::null_mut()), - ptr::null_mut(), - )).map(|_| ()) - } - } - - /// Places the result of `a * b` in `self`. - /// [`core::ops::Mul`] is also implemented for `BigNumRef`. - /// - /// OpenSSL documentation at [`BN_mul`] - /// - /// [`core::ops::Mul`]: struct.BigNumRef.html#method.mul - /// [`BN_mul`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mul.html - pub fn checked_mul( - &mut self, - a: &BigNumRef, - b: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mul( - self.as_ptr(), - a.as_ptr(), - b.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the result of `a / b` in `self`. The remainder is discarded. - /// [`core::ops::Div`] is also implemented for `BigNumRef`. - /// - /// OpenSSL documentation at [`BN_div`] - /// - /// [`core::ops::Div`]: struct.BigNumRef.html#method.div - /// [`BN_div`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div.html - pub fn checked_div( - &mut self, - a: &BigNumRef, - b: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_div( - self.as_ptr(), - ptr::null_mut(), - a.as_ptr(), - b.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the result of `a % b` in `self`. - /// - /// OpenSSL documentation at [`BN_div`] - /// - /// [`BN_div`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div.html - pub fn checked_rem( - &mut self, - a: &BigNumRef, - b: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_div( - ptr::null_mut(), - self.as_ptr(), - a.as_ptr(), - b.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the result of `a / b` in `self` and `a % b` in `rem`. - /// - /// OpenSSL documentation at [`BN_div`] - /// - /// [`BN_div`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_div.html - pub fn div_rem( - &mut self, - rem: &mut BigNumRef, - a: &BigNumRef, - b: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_div( - self.as_ptr(), - rem.as_ptr(), - a.as_ptr(), - b.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the result of `a²` in `self`. - /// - /// OpenSSL documentation at [`BN_sqr`] - /// - /// [`BN_sqr`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_sqr.html - pub fn sqr(&mut self, a: &BigNumRef, ctx: &mut BigNumContextRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::BN_sqr(self.as_ptr(), a.as_ptr(), ctx.as_ptr())).map(|_| ()) } - } - - /// Places the result of `a mod m` in `self`. As opposed to `div_rem` - /// the result is non-negative. - /// - /// OpenSSL documentation at [`BN_nnmod`] - /// - /// [`BN_nnmod`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_nnmod.html - pub fn nnmod( - &mut self, - a: &BigNumRef, - m: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_nnmod( - self.as_ptr(), - a.as_ptr(), - m.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the result of `(a + b) mod m` in `self`. - /// - /// OpenSSL documentation at [`BN_mod_add`] - /// - /// [`BN_mod_add`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_add.html - pub fn mod_add( - &mut self, - a: &BigNumRef, - b: &BigNumRef, - m: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mod_add( - self.as_ptr(), - a.as_ptr(), - b.as_ptr(), - m.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the result of `(a - b) mod m` in `self`. - /// - /// OpenSSL documentation at [`BN_mod_sub`] - /// - /// [`BN_mod_sub`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_sub.html - pub fn mod_sub( - &mut self, - a: &BigNumRef, - b: &BigNumRef, - m: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mod_sub( - self.as_ptr(), - a.as_ptr(), - b.as_ptr(), - m.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the result of `(a * b) mod m` in `self`. - /// - /// OpenSSL documentation at [`BN_mod_mul`] - /// - /// [`BN_mod_mul`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_mul.html - pub fn mod_mul( - &mut self, - a: &BigNumRef, - b: &BigNumRef, - m: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mod_mul( - self.as_ptr(), - a.as_ptr(), - b.as_ptr(), - m.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the result of `a² mod m` in `self`. - /// - /// OpenSSL documentation at [`BN_mod_sqr`] - /// - /// [`BN_mod_sqr`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_sqr.html - pub fn mod_sqr( - &mut self, - a: &BigNumRef, - m: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mod_sqr( - self.as_ptr(), - a.as_ptr(), - m.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the result of `a^p` in `self`. - /// - /// OpenSSL documentation at [`BN_exp`] - /// - /// [`BN_exp`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_exp.html - pub fn exp( - &mut self, - a: &BigNumRef, - p: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_exp( - self.as_ptr(), - a.as_ptr(), - p.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the result of `a^p mod m` in `self`. - /// - /// OpenSSL documentation at [`BN_mod_exp`] - /// - /// [`BN_mod_exp`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_mod_exp.html - pub fn mod_exp( - &mut self, - a: &BigNumRef, - p: &BigNumRef, - m: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_mod_exp( - self.as_ptr(), - a.as_ptr(), - p.as_ptr(), - m.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the inverse of `a` modulo `n` in `self`. - pub fn mod_inverse( - &mut self, - a: &BigNumRef, - n: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt_p(ffi::BN_mod_inverse( - self.as_ptr(), - a.as_ptr(), - n.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the greatest common denominator of `a` and `b` in `self`. - /// - /// OpenSSL documentation at [`BN_gcd`] - /// - /// [`BN_gcd`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_gcd.html - pub fn gcd( - &mut self, - a: &BigNumRef, - b: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::BN_gcd( - self.as_ptr(), - a.as_ptr(), - b.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Checks whether `self` is prime. - /// - /// Performs a Miller-Rabin probabilistic primality test with `checks` iterations. - /// - /// OpenSSL documentation at [`BN_is_prime_ex`] - /// - /// [`BN_is_prime_ex`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_is_prime_ex.html - /// - /// # Return Value - /// - /// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`. - - pub fn is_prime(&self, checks: i32, ctx: &mut BigNumContextRef) -> Result { - unsafe { - cvt_n(ffi::BN_is_prime_ex( - self.as_ptr(), - checks.into(), - ctx.as_ptr(), - ptr::null_mut(), - )).map(|r| r != 0) - } - } - - /// Checks whether `self` is prime with optional trial division. - /// - /// If `do_trial_division` is `true`, first performs trial division by a number of small primes. - /// Then, like `is_prime`, performs a Miller-Rabin probabilistic primality test with `checks` - /// iterations. - /// - /// OpenSSL documentation at [`BN_is_prime_fasttest_ex`] - /// - /// [`BN_is_prime_fasttest_ex`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_is_prime_fasttest_ex.html - /// - /// # Return Value - /// - /// Returns `true` if `self` is prime with an error probability of less than `0.25 ^ checks`. - pub fn is_prime_fasttest( - &self, - checks: i32, - ctx: &mut BigNumContextRef, - do_trial_division: bool, - ) -> Result { - unsafe { - cvt_n(ffi::BN_is_prime_fasttest_ex( - self.as_ptr(), - checks.into(), - ctx.as_ptr(), - do_trial_division as c_int, - ptr::null_mut(), - )).map(|r| r != 0) - } - } - - /// Returns a big-endian byte vector representation of the absolute value of `self`. - /// - /// `self` can be recreated by using `from_slice`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let s = -BigNum::from_u32(4543).unwrap(); - /// let r = BigNum::from_u32(4543).unwrap(); - /// - /// let s_vec = s.to_vec(); - /// assert_eq!(BigNum::from_slice(&s_vec).unwrap(), r); - /// ``` - pub fn to_vec(&self) -> Vec { - let size = self.num_bytes() as usize; - let mut v = Vec::with_capacity(size); - unsafe { - ffi::BN_bn2bin(self.as_ptr(), v.as_mut_ptr()); - v.set_len(size); - } - v - } - - /// Returns a decimal string representation of `self`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let s = -BigNum::from_u32(12345).unwrap(); - /// - /// assert_eq!(&**s.to_dec_str().unwrap(), "-12345"); - /// ``` - pub fn to_dec_str(&self) -> Result { - unsafe { - let buf = cvt_p(ffi::BN_bn2dec(self.as_ptr()))?; - Ok(OpensslString::from_ptr(buf)) - } - } - - /// Returns a hexadecimal string representation of `self`. - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let s = -BigNum::from_u32(0x99ff).unwrap(); - /// - /// assert_eq!(&**s.to_hex_str().unwrap(), "-99FF"); - /// ``` - pub fn to_hex_str(&self) -> Result { - unsafe { - let buf = cvt_p(ffi::BN_bn2hex(self.as_ptr()))?; - Ok(OpensslString::from_ptr(buf)) - } - } - - /// Returns an `Asn1Integer` containing the value of `self`. - pub fn to_asn1_integer(&self) -> Result { - unsafe { - cvt_p(ffi::BN_to_ASN1_INTEGER(self.as_ptr(), ptr::null_mut())) - .map(|p| Asn1Integer::from_ptr(p)) - } - } -} - -impl BigNum { - /// Creates a new `BigNum` with the value 0. - pub fn new() -> Result { - unsafe { - ffi::init(); - let v = cvt_p(ffi::BN_new())?; - Ok(BigNum::from_ptr(v)) - } - } - - /// Creates a new `BigNum` with the given value. - /// - /// OpenSSL documentation at [`BN_set_word`] - /// - /// [`BN_set_word`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_set_word.html - pub fn from_u32(n: u32) -> Result { - BigNum::new().and_then(|v| unsafe { - cvt(ffi::BN_set_word(v.as_ptr(), n as ffi::BN_ULONG)).map(|_| v) - }) - } - - /// Creates a `BigNum` from a decimal string. - /// - /// OpenSSL documentation at [`BN_dec2bn`] - /// - /// [`BN_dec2bn`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_dec2bn.html - pub fn from_dec_str(s: &str) -> Result { - unsafe { - ffi::init(); - let c_str = CString::new(s.as_bytes()).unwrap(); - let mut bn = ptr::null_mut(); - cvt(ffi::BN_dec2bn(&mut bn, c_str.as_ptr() as *const _))?; - Ok(BigNum::from_ptr(bn)) - } - } - - /// Creates a `BigNum` from a hexadecimal string. - /// - /// OpenSSL documentation at [`BN_hex2bn`] - /// - /// [`BN_hex2bn`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_hex2bn.html - pub fn from_hex_str(s: &str) -> Result { - unsafe { - ffi::init(); - let c_str = CString::new(s.as_bytes()).unwrap(); - let mut bn = ptr::null_mut(); - cvt(ffi::BN_hex2bn(&mut bn, c_str.as_ptr() as *const _))?; - Ok(BigNum::from_ptr(bn)) - } - } - - /// Returns a constant used in IKE as defined in [`RFC 2409`]. This prime number is in - /// the order of magnitude of `2 ^ 768`. This number is used during calculated key - /// exchanges such as Diffie-Hellman. This number is labeled Oakley group id 1. - /// - /// OpenSSL documentation at [`BN_get_rfc2409_prime_768`] - /// - /// [`RFC 2409`]: https://tools.ietf.org/html/rfc2409#page-21 - /// [`BN_get_rfc2409_prime_768`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc2409_prime_768.html - pub fn get_rfc2409_prime_768() -> Result { - unsafe { - ffi::init(); - cvt_p(BN_get_rfc2409_prime_768(ptr::null_mut())).map(BigNum) - } - } - - /// Returns a constant used in IKE as defined in [`RFC 2409`]. This prime number is in - /// the order of magnitude of `2 ^ 1024`. This number is used during calculated key - /// exchanges such as Diffie-Hellman. This number is labeled Oakly group 2. - /// - /// OpenSSL documentation at [`BN_get_rfc2409_prime_1024`] - /// - /// [`RFC 2409`]: https://tools.ietf.org/html/rfc2409#page-21 - /// [`BN_get_rfc2409_prime_1024`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc2409_prime_1024.html - pub fn get_rfc2409_prime_1024() -> Result { - unsafe { - ffi::init(); - cvt_p(BN_get_rfc2409_prime_1024(ptr::null_mut())).map(BigNum) - } - } - - /// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order - /// of magnitude of `2 ^ 1536`. This number is used during calculated key - /// exchanges such as Diffie-Hellman. This number is labeled MODP group 5. - /// - /// OpenSSL documentation at [`BN_get_rfc3526_prime_1536`] - /// - /// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-3 - /// [`BN_get_rfc3526_prime_1536`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_1536.html - pub fn get_rfc3526_prime_1536() -> Result { - unsafe { - ffi::init(); - cvt_p(BN_get_rfc3526_prime_1536(ptr::null_mut())).map(BigNum) - } - } - - /// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order - /// of magnitude of `2 ^ 2048`. This number is used during calculated key - /// exchanges such as Diffie-Hellman. This number is labeled MODP group 14. - /// - /// OpenSSL documentation at [`BN_get_rfc3526_prime_2048`] - /// - /// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-3 - /// [`BN_get_rfc3526_prime_2048`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_2048.html - pub fn get_rfc3526_prime_2048() -> Result { - unsafe { - ffi::init(); - cvt_p(BN_get_rfc3526_prime_2048(ptr::null_mut())).map(BigNum) - } - } - - /// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order - /// of magnitude of `2 ^ 3072`. This number is used during calculated key - /// exchanges such as Diffie-Hellman. This number is labeled MODP group 15. - /// - /// OpenSSL documentation at [`BN_get_rfc3526_prime_3072`] - /// - /// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-4 - /// [`BN_get_rfc3526_prime_3072`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_3072.html - pub fn get_rfc3526_prime_3072() -> Result { - unsafe { - ffi::init(); - cvt_p(BN_get_rfc3526_prime_3072(ptr::null_mut())).map(BigNum) - } - } - - /// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order - /// of magnitude of `2 ^ 4096`. This number is used during calculated key - /// exchanges such as Diffie-Hellman. This number is labeled MODP group 16. - /// - /// OpenSSL documentation at [`BN_get_rfc3526_prime_4096`] - /// - /// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-4 - /// [`BN_get_rfc3526_prime_4096`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_4096.html - pub fn get_rfc3526_prime_4096() -> Result { - unsafe { - ffi::init(); - cvt_p(BN_get_rfc3526_prime_4096(ptr::null_mut())).map(BigNum) - } - } - - /// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order - /// of magnitude of `2 ^ 6144`. This number is used during calculated key - /// exchanges such as Diffie-Hellman. This number is labeled MODP group 17. - /// - /// OpenSSL documentation at [`BN_get_rfc3526_prime_6144`] - /// - /// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-6 - /// [`BN_get_rfc3526_prime_6144`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_6144.html - pub fn get_rfc3526_prime_6144() -> Result { - unsafe { - ffi::init(); - cvt_p(BN_get_rfc3526_prime_6144(ptr::null_mut())).map(BigNum) - } - } - - /// Returns a constant used in IKE as defined in [`RFC 3526`]. The prime is in the order - /// of magnitude of `2 ^ 8192`. This number is used during calculated key - /// exchanges such as Diffie-Hellman. This number is labeled MODP group 18. - /// - /// OpenSSL documentation at [`BN_get_rfc3526_prime_8192`] - /// - /// [`RFC 3526`]: https://tools.ietf.org/html/rfc3526#page-6 - /// [`BN_get_rfc3526_prime_8192`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_get_rfc3526_prime_8192.html - pub fn get_rfc3526_prime_8192() -> Result { - unsafe { - ffi::init(); - cvt_p(BN_get_rfc3526_prime_8192(ptr::null_mut())).map(BigNum) - } - } - - /// Creates a new `BigNum` from an unsigned, big-endian encoded number of arbitrary length. - /// - /// OpenSSL documentation at [`BN_bin2bn`] - /// - /// [`BN_bin2bn`]: https://www.openssl.org/docs/man1.1.0/crypto/BN_bin2bn.html - /// - /// ``` - /// # use openssl::bn::BigNum; - /// let bignum = BigNum::from_slice(&[0x12, 0x00, 0x34]).unwrap(); - /// - /// assert_eq!(bignum, BigNum::from_u32(0x120034).unwrap()); - /// ``` - pub fn from_slice(n: &[u8]) -> Result { - unsafe { - ffi::init(); - assert!(n.len() <= c_int::max_value() as usize); - cvt_p(ffi::BN_bin2bn( - n.as_ptr(), - n.len() as c_int, - ptr::null_mut(), - )).map(|p| BigNum::from_ptr(p)) - } - } -} - -impl fmt::Debug for BigNumRef { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.to_dec_str() { - Ok(s) => f.write_str(&s), - Err(e) => Err(e.into()), - } - } -} - -impl fmt::Debug for BigNum { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.to_dec_str() { - Ok(s) => f.write_str(&s), - Err(e) => Err(e.into()), - } - } -} - -impl fmt::Display for BigNumRef { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.to_dec_str() { - Ok(s) => f.write_str(&s), - Err(e) => Err(e.into()), - } - } -} - -impl fmt::Display for BigNum { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.to_dec_str() { - Ok(s) => f.write_str(&s), - Err(e) => Err(e.into()), - } - } -} - -impl PartialEq for BigNumRef { - fn eq(&self, oth: &BigNumRef) -> bool { - self.cmp(oth) == Ordering::Equal - } -} - -impl PartialEq for BigNumRef { - fn eq(&self, oth: &BigNum) -> bool { - self.eq(oth.deref()) - } -} - -impl Eq for BigNumRef {} - -impl PartialEq for BigNum { - fn eq(&self, oth: &BigNum) -> bool { - self.deref().eq(oth) - } -} - -impl PartialEq for BigNum { - fn eq(&self, oth: &BigNumRef) -> bool { - self.deref().eq(oth) - } -} - -impl Eq for BigNum {} - -impl PartialOrd for BigNumRef { - fn partial_cmp(&self, oth: &BigNumRef) -> Option { - Some(self.cmp(oth)) - } -} - -impl PartialOrd for BigNumRef { - fn partial_cmp(&self, oth: &BigNum) -> Option { - Some(self.cmp(oth.deref())) - } -} - -impl Ord for BigNumRef { - fn cmp(&self, oth: &BigNumRef) -> Ordering { - unsafe { ffi::BN_cmp(self.as_ptr(), oth.as_ptr()).cmp(&0) } - } -} - -impl PartialOrd for BigNum { - fn partial_cmp(&self, oth: &BigNum) -> Option { - self.deref().partial_cmp(oth.deref()) - } -} - -impl PartialOrd for BigNum { - fn partial_cmp(&self, oth: &BigNumRef) -> Option { - self.deref().partial_cmp(oth) - } -} - -impl Ord for BigNum { - fn cmp(&self, oth: &BigNum) -> Ordering { - self.deref().cmp(oth.deref()) - } -} - -macro_rules! delegate { - ($t:ident, $m:ident) => { - impl<'a, 'b> $t<&'b BigNum> for &'a BigNumRef { - type Output = BigNum; - - fn $m(self, oth: &BigNum) -> BigNum { - $t::$m(self, oth.deref()) - } - } - - impl<'a, 'b> $t<&'b BigNumRef> for &'a BigNum { - type Output = BigNum; - - fn $m(self, oth: &BigNumRef) -> BigNum { - $t::$m(self.deref(), oth) - } - } - - impl<'a, 'b> $t<&'b BigNum> for &'a BigNum { - type Output = BigNum; - - fn $m(self, oth: &BigNum) -> BigNum { - $t::$m(self.deref(), oth.deref()) - } - } - } -} - -impl<'a, 'b> Add<&'b BigNumRef> for &'a BigNumRef { - type Output = BigNum; - - fn add(self, oth: &BigNumRef) -> BigNum { - let mut r = BigNum::new().unwrap(); - r.checked_add(self, oth).unwrap(); - r - } -} - -delegate!(Add, add); - -impl<'a, 'b> Sub<&'b BigNumRef> for &'a BigNumRef { - type Output = BigNum; - - fn sub(self, oth: &BigNumRef) -> BigNum { - let mut r = BigNum::new().unwrap(); - r.checked_sub(self, oth).unwrap(); - r - } -} - -delegate!(Sub, sub); - -impl<'a, 'b> Mul<&'b BigNumRef> for &'a BigNumRef { - type Output = BigNum; - - fn mul(self, oth: &BigNumRef) -> BigNum { - let mut ctx = BigNumContext::new().unwrap(); - let mut r = BigNum::new().unwrap(); - r.checked_mul(self, oth, &mut ctx).unwrap(); - r - } -} - -delegate!(Mul, mul); - -impl<'a, 'b> Div<&'b BigNumRef> for &'a BigNumRef { - type Output = BigNum; - - fn div(self, oth: &'b BigNumRef) -> BigNum { - let mut ctx = BigNumContext::new().unwrap(); - let mut r = BigNum::new().unwrap(); - r.checked_div(self, oth, &mut ctx).unwrap(); - r - } -} - -delegate!(Div, div); - -impl<'a, 'b> Rem<&'b BigNumRef> for &'a BigNumRef { - type Output = BigNum; - - fn rem(self, oth: &'b BigNumRef) -> BigNum { - let mut ctx = BigNumContext::new().unwrap(); - let mut r = BigNum::new().unwrap(); - r.checked_rem(self, oth, &mut ctx).unwrap(); - r - } -} - -delegate!(Rem, rem); - -impl<'a> Shl for &'a BigNumRef { - type Output = BigNum; - - fn shl(self, n: i32) -> BigNum { - let mut r = BigNum::new().unwrap(); - r.lshift(self, n).unwrap(); - r - } -} - -impl<'a> Shl for &'a BigNum { - type Output = BigNum; - - fn shl(self, n: i32) -> BigNum { - self.deref().shl(n) - } -} - -impl<'a> Shr for &'a BigNumRef { - type Output = BigNum; - - fn shr(self, n: i32) -> BigNum { - let mut r = BigNum::new().unwrap(); - r.rshift(self, n).unwrap(); - r - } -} - -impl<'a> Shr for &'a BigNum { - type Output = BigNum; - - fn shr(self, n: i32) -> BigNum { - self.deref().shr(n) - } -} - -impl<'a> Neg for &'a BigNumRef { - type Output = BigNum; - - fn neg(self) -> BigNum { - self.to_owned().unwrap().neg() - } -} - -impl<'a> Neg for &'a BigNum { - type Output = BigNum; - - fn neg(self) -> BigNum { - self.deref().neg() - } -} - -impl Neg for BigNum { - type Output = BigNum; - - fn neg(mut self) -> BigNum { - let negative = self.is_negative(); - self.set_negative(!negative); - self - } -} - -#[cfg(test)] -mod tests { - use bn::{BigNumContext, BigNum}; - - #[test] - fn test_to_from_slice() { - let v0 = BigNum::from_u32(10203004).unwrap(); - let vec = v0.to_vec(); - let v1 = BigNum::from_slice(&vec).unwrap(); - - assert!(v0 == v1); - } - - #[test] - fn test_negation() { - let a = BigNum::from_u32(909829283).unwrap(); - - assert!(!a.is_negative()); - assert!((-a).is_negative()); - } - - #[test] - fn test_shift() { - let a = BigNum::from_u32(909829283).unwrap(); - use std::ops::{Shl, Shr}; - - assert!(a == a.shl(1).shr(1)); - } - - #[test] - fn test_rand_range() { - let range = BigNum::from_u32(909829283).unwrap(); - let mut result = BigNum::from_dec_str(&range.to_dec_str().unwrap()).unwrap(); - range.rand_range(&mut result).unwrap(); - assert!(result >= BigNum::from_u32(0).unwrap() && result < range); - } - - #[test] - fn test_pseudo_rand_range() { - let range = BigNum::from_u32(909829283).unwrap(); - let mut result = BigNum::from_dec_str(&range.to_dec_str().unwrap()).unwrap(); - range.pseudo_rand_range(&mut result).unwrap(); - assert!(result >= BigNum::from_u32(0).unwrap() && result < range); - } - - #[test] - fn test_prime_numbers() { - let a = BigNum::from_u32(19029017).unwrap(); - let mut p = BigNum::new().unwrap(); - p.generate_prime(128, true, None, Some(&a)).unwrap(); - - let mut ctx = BigNumContext::new().unwrap(); - assert!(p.is_prime(100, &mut ctx).unwrap()); - assert!(p.is_prime_fasttest(100, &mut ctx, true).unwrap()); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/cms.rs cargo-0.26.0/vendor/openssl-0.9.24/src/cms.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/cms.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/cms.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,87 +0,0 @@ -//! SMIME implementation using CMS -//! -//! CMS (PKCS#7) is an encyption standard. It allows signing and ecrypting data using -//! X.509 certificates. The OpenSSL implementation of CMS is used in email encryption -//! generated from a `Vec` of bytes. This `Vec` follows the smime protocol standards. -//! Data accepted by this module will be smime type `enveloped-data`. - -use ffi; -use foreign_types::{ForeignType, ForeignTypeRef}; -use std::ptr; -use error::ErrorStack; - -use bio::{MemBio, MemBioSlice}; - -use x509::X509; -use pkey::PKeyRef; - -use cvt; -use cvt_p; - -foreign_type_and_impl_send_sync! { - type CType = ffi::CMS_ContentInfo; - fn drop = ffi::CMS_ContentInfo_free; - - /// High level CMS wrapper - /// - /// CMS supports nesting various types of data, including signatures, certificates, - /// encrypted data, smime messages (encrypted email), and data digest. The ContentInfo - /// content type is the encapsulation of all those content types. [`RFC 5652`] describes - /// CMS and OpenSSL follows this RFC's implmentation. - /// - /// [`RFC 5652`]: https://tools.ietf.org/html/rfc5652#page-6 - pub struct CmsContentInfo; - /// Reference to [`CMSContentInfo`] - /// - /// [`CMSContentInfo`]:struct.CmsContentInfo.html - pub struct CmsContentInfoRef; -} - -impl CmsContentInfoRef { - /// Given the sender's private key, `pkey` and the recipient's certificiate, `cert`, - /// decrypt the data in `self`. - /// - /// OpenSSL documentation at [`CMS_decrypt`] - /// - /// [`CMS_decrypt`]: https://www.openssl.org/docs/man1.1.0/crypto/CMS_decrypt.html - pub fn decrypt(&self, pkey: &PKeyRef, cert: &X509) -> Result, ErrorStack> { - unsafe { - let pkey = pkey.as_ptr(); - let cert = cert.as_ptr(); - let out = MemBio::new()?; - let flags: u32 = 0; - - cvt(ffi::CMS_decrypt( - self.as_ptr(), - pkey, - cert, - ptr::null_mut(), - out.as_ptr(), - flags.into(), - ))?; - - Ok(out.get_buf().to_owned()) - } - } - -} - -impl CmsContentInfo { - /// Parses a smime formatted `vec` of bytes into a `CmsContentInfo`. - /// - /// OpenSSL documentation at [`SMIME_read_CMS`] - /// - /// [`SMIME_read_CMS`]: https://www.openssl.org/docs/man1.0.2/crypto/SMIME_read_CMS.html - pub fn smime_read_cms(smime: &[u8]) -> Result { - unsafe { - let bio = MemBioSlice::new(smime)?; - - let cms = cvt_p(ffi::SMIME_read_CMS( - bio.as_ptr(), - ptr::null_mut(), - ))?; - - Ok(CmsContentInfo::from_ptr(cms)) - } - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/conf.rs cargo-0.26.0/vendor/openssl-0.9.24/src/conf.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/conf.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/conf.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,52 +0,0 @@ -//! Interface for processing OpenSSL configuration files. -use ffi; - -use cvt_p; -use error::ErrorStack; - -pub struct ConfMethod(*mut ffi::CONF_METHOD); - -impl ConfMethod { - /// Retrieve handle to the default OpenSSL configuration file processing function. - pub fn default() -> ConfMethod { - unsafe { - ffi::init(); - // `NCONF` stands for "New Conf", as described in crypto/conf/conf_lib.c. This is - // a newer API than the "CONF classic" functions. - ConfMethod(ffi::NCONF_default()) - } - } - - /// Construct from raw pointer. - pub unsafe fn from_ptr(ptr: *mut ffi::CONF_METHOD) -> ConfMethod { - ConfMethod(ptr) - } - - /// Convert to raw pointer. - pub fn as_ptr(&self) -> *mut ffi::CONF_METHOD { - self.0 - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::CONF; - fn drop = ffi::NCONF_free; - - pub struct Conf; - pub struct ConfRef; -} - -impl Conf { - /// Create a configuration parser. - /// - /// # Examples - /// - /// ``` - /// use openssl::conf::{Conf, ConfMethod}; - /// - /// let conf = Conf::new(ConfMethod::default()); - /// ``` - pub fn new(method: ConfMethod) -> Result { - unsafe { cvt_p(ffi::NCONF_new(method.as_ptr())).map(Conf) } - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/crypto.rs cargo-0.26.0/vendor/openssl-0.9.24/src/crypto.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/crypto.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/crypto.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -#![doc(hidden)] -#![deprecated(since = "0.9.20")] -use string::OpensslString; - -#[deprecated(note = "renamed to OpensslString", since = "0.9.7")] -pub type CryptoString = OpensslString; diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/dh.rs cargo-0.26.0/vendor/openssl-0.9.24/src/dh.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/dh.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/dh.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,160 +0,0 @@ -use error::ErrorStack; -use ffi; -use foreign_types::ForeignTypeRef; -use std::mem; -use std::ptr; - -use {cvt, cvt_p}; -use bn::BigNum; - -foreign_type_and_impl_send_sync! { - type CType = ffi::DH; - fn drop = ffi::DH_free; - - pub struct Dh; - - pub struct DhRef; -} - -impl DhRef { - to_pem!(ffi::PEM_write_bio_DHparams); - to_der!(ffi::i2d_DHparams); -} - -impl Dh { - pub fn from_params(p: BigNum, g: BigNum, q: BigNum) -> Result { - unsafe { - let dh = Dh(cvt_p(ffi::DH_new())?); - cvt(compat::DH_set0_pqg( - dh.0, - p.as_ptr(), - q.as_ptr(), - g.as_ptr(), - ))?; - mem::forget((p, g, q)); - Ok(dh) - } - } - - from_pem!(Dh, ffi::PEM_read_bio_DHparams); - from_der!(Dh, ffi::d2i_DHparams); - - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn get_1024_160() -> Result { - unsafe { - ffi::init(); - cvt_p(ffi::DH_get_1024_160()).map(Dh) - } - } - - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn get_2048_224() -> Result { - unsafe { - ffi::init(); - cvt_p(ffi::DH_get_2048_224()).map(Dh) - } - } - - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn get_2048_256() -> Result { - unsafe { - ffi::init(); - cvt_p(ffi::DH_get_2048_256()).map(Dh) - } - } -} - -#[cfg(ossl110)] -mod compat { - pub use ffi::DH_set0_pqg; -} - -#[cfg(ossl10x)] -#[allow(bad_style)] -mod compat { - use ffi; - use libc::c_int; - - pub unsafe fn DH_set0_pqg( - dh: *mut ffi::DH, - p: *mut ffi::BIGNUM, - q: *mut ffi::BIGNUM, - g: *mut ffi::BIGNUM, - ) -> c_int { - (*dh).p = p; - (*dh).q = q; - (*dh).g = g; - 1 - } -} - -#[cfg(test)] -mod tests { - use dh::Dh; - use bn::BigNum; - use ssl::{SslMethod, SslContext}; - - #[test] - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - fn test_dh_rfc5114() { - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let dh1 = Dh::get_1024_160().unwrap(); - ctx.set_tmp_dh(&dh1).unwrap(); - let dh2 = Dh::get_2048_224().unwrap(); - ctx.set_tmp_dh(&dh2).unwrap(); - let dh3 = Dh::get_2048_256().unwrap(); - ctx.set_tmp_dh(&dh3).unwrap(); - } - - #[test] - fn test_dh() { - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let p = BigNum::from_hex_str( - "87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435\ - E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF429\ - 6D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4758C02\ - 2E0B1EF4275BF7B6C5BFC11D45F9088B941F54EB1E59BB8BC39A0BF1230\ - 7F5C4FDB70C581B23F76B63ACAE1CAA6B7902D52526735488A0EF13C6D9\ - A51BFA4AB3AD8347796524D8EF6A167B5A41825D967E144E5140564251C\ - CACB83E6B486F6B3CA3F7971506026C0B857F689962856DED4010ABD0BE\ - 621C3A3960A54E710C375F26375D7014103A4B54330C198AF126116D227\ - 6E11715F693877FAD7EF09CADB094AE91E1A1597", - ).unwrap(); - let g = BigNum::from_hex_str( - "3FB32C9B73134D0B2E77506660EDBD484CA7B18F21EF205407F4793A1A0\ - BA12510DBC15077BE463FFF4FED4AAC0BB555BE3A6C1B0C6B47B1BC3773\ - BF7E8C6F62901228F8C28CBB18A55AE31341000A650196F931C77A57F2D\ - DF463E5E9EC144B777DE62AAAB8A8628AC376D282D6ED3864E67982428E\ - BC831D14348F6F2F9193B5045AF2767164E1DFC967C1FB3F2E55A4BD1BF\ - FE83B9C80D052B985D182EA0ADB2A3B7313D3FE14C8484B1E052588B9B7\ - D2BBD2DF016199ECD06E1557CD0915B3353BBB64E0EC377FD028370DF92\ - B52C7891428CDC67EB6184B523D1DB246C32F63078490F00EF8D647D148\ - D47954515E2327CFEF98C582664B4C0F6CC41659", - ).unwrap(); - let q = BigNum::from_hex_str( - "8CF83642A709A097B447997640129DA299B1A47D1EB3750BA308B0FE64F\ - 5FBD3", - ).unwrap(); - let dh = Dh::from_params(p, g, q).unwrap(); - ctx.set_tmp_dh(&dh).unwrap(); - } - - #[test] - fn test_dh_from_pem() { - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let params = include_bytes!("../test/dhparams.pem"); - let dh = Dh::from_pem(params).unwrap(); - ctx.set_tmp_dh(&dh).unwrap(); - } - - #[test] - fn test_dh_from_der() { - let params = include_bytes!("../test/dhparams.pem"); - let dh = Dh::from_pem(params).unwrap(); - let der = dh.to_der().unwrap(); - Dh::from_der(&der).unwrap(); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/dsa.rs cargo-0.26.0/vendor/openssl-0.9.24/src/dsa.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/dsa.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/dsa.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,261 +0,0 @@ -//! Digital Signatures -//! -//! DSA ensures a message originated from a known sender, and was not modified. -//! DSA uses asymetrical keys and an algorithm to output a signature of the message -//! using the private key that can be validated with the public key but not be generated -//! without the private key. - -use ffi; -use foreign_types::ForeignTypeRef; -use libc::{c_int, c_char, c_void}; -use std::fmt; -use std::ptr; - -use {cvt, cvt_p}; -use bio::MemBioSlice; -use bn::BigNumRef; -use error::ErrorStack; -use util::{CallbackState, invoke_passwd_cb_old}; - -foreign_type_and_impl_send_sync! { - type CType = ffi::DSA; - fn drop = ffi::DSA_free; - - /// Object representing DSA keys. - /// - /// A DSA object contains the parameters p, q, and g. There is a private - /// and public key. The values p, g, and q are: - /// - /// * `p`: DSA prime parameter - /// * `q`: DSA sub-prime parameter - /// * `g`: DSA base parameter - /// - /// These values are used to calculate a pair of asymetrical keys used for - /// signing. - /// - /// OpenSSL documentation at [`DSA_new`] - /// - /// [`DSA_new`]: https://www.openssl.org/docs/man1.1.0/crypto/DSA_new.html - /// - /// # Examples - /// - /// ``` - /// use openssl::dsa::Dsa; - /// use openssl::error::ErrorStack; - /// fn create_dsa() -> Result< Dsa, ErrorStack > { - /// let sign = Dsa::generate(2048)?; - /// Ok(sign) - /// } - /// # fn main() { - /// # create_dsa(); - /// # } - /// ``` - pub struct Dsa; - /// Reference to [`Dsa`]. - /// - /// [`Dsa`]: struct.Dsa.html - pub struct DsaRef; -} - -impl DsaRef { - private_key_to_pem!(ffi::PEM_write_bio_DSAPrivateKey); - public_key_to_pem!(ffi::PEM_write_bio_DSA_PUBKEY); - - private_key_to_der!(ffi::i2d_DSAPrivateKey); - public_key_to_der!(ffi::i2d_DSAPublicKey); - - /// Returns the maximum size of the signature output by `self` in bytes. Returns - /// None if the keys are uninitialized. - /// - /// OpenSSL documentation at [`DSA_size`] - /// - /// [`DSA_size`]: https://www.openssl.org/docs/man1.1.0/crypto/DSA_size.html - // FIXME should return u32 - pub fn size(&self) -> Option { - if self.q().is_some() { - unsafe { Some(ffi::DSA_size(self.as_ptr()) as u32) } - } else { - None - } - } - - /// Returns the DSA prime parameter of `self`. - pub fn p(&self) -> Option<&BigNumRef> { - unsafe { - let p = compat::pqg(self.as_ptr())[0]; - if p.is_null() { - None - } else { - Some(BigNumRef::from_ptr(p as *mut _)) - } - } - } - - /// Returns the DSA sub-prime parameter of `self`. - pub fn q(&self) -> Option<&BigNumRef> { - unsafe { - let q = compat::pqg(self.as_ptr())[1]; - if q.is_null() { - None - } else { - Some(BigNumRef::from_ptr(q as *mut _)) - } - } - } - - /// Returns the DSA base parameter of `self`. - pub fn g(&self) -> Option<&BigNumRef> { - unsafe { - let g = compat::pqg(self.as_ptr())[2]; - if g.is_null() { - None - } else { - Some(BigNumRef::from_ptr(g as *mut _)) - } - } - } - - /// Returns whether the DSA includes a public key, used to confirm the authenticity - /// of the message. - pub fn has_public_key(&self) -> bool { - unsafe { !compat::keys(self.as_ptr())[0].is_null() } - } - - /// Returns whether the DSA includes a private key, used to prove the authenticity - /// of a message. - pub fn has_private_key(&self) -> bool { - unsafe { !compat::keys(self.as_ptr())[1].is_null() } - } -} - -impl Dsa { - /// Generate a DSA key pair. - /// - /// Calls [`DSA_generate_parameters_ex`] to populate the `p`, `g`, and `q` values. - /// These values are used to generate the key pair with [`DSA_generate_key`]. - /// - /// The `bits` parameter coresponds to the length of the prime `p`. - /// - /// [`DSA_generate_parameters_ex`]: https://www.openssl.org/docs/man1.1.0/crypto/DSA_generate_parameters_ex.html - /// [`DSA_generate_key`]: https://www.openssl.org/docs/man1.1.0/crypto/DSA_generate_key.html - pub fn generate(bits: u32) -> Result { - ffi::init(); - unsafe { - let dsa = Dsa(cvt_p(ffi::DSA_new())?); - cvt(ffi::DSA_generate_parameters_ex( - dsa.0, - bits as c_int, - ptr::null(), - 0, - ptr::null_mut(), - ptr::null_mut(), - ptr::null_mut(), - ))?; - cvt(ffi::DSA_generate_key(dsa.0))?; - Ok(dsa) - } - } - - private_key_from_pem!(Dsa, ffi::PEM_read_bio_DSAPrivateKey); - private_key_from_der!(Dsa, ffi::d2i_DSAPrivateKey); - public_key_from_pem!(Dsa, ffi::PEM_read_bio_DSA_PUBKEY); - public_key_from_der!(Dsa, ffi::d2i_DSAPublicKey); - - #[deprecated(since = "0.9.2", note = "use private_key_from_pem_callback")] - pub fn private_key_from_pem_cb(buf: &[u8], pass_cb: F) -> Result - where - F: FnOnce(&mut [c_char]) -> usize, - { - ffi::init(); - let mut cb = CallbackState::new(pass_cb); - let mem_bio = MemBioSlice::new(buf)?; - - unsafe { - let cb_ptr = &mut cb as *mut _ as *mut c_void; - let dsa = cvt_p(ffi::PEM_read_bio_DSAPrivateKey( - mem_bio.as_ptr(), - ptr::null_mut(), - Some(invoke_passwd_cb_old::), - cb_ptr, - ))?; - Ok(Dsa(dsa)) - } - } -} - -impl fmt::Debug for Dsa { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "DSA") - } -} - -#[cfg(ossl110)] -mod compat { - use std::ptr; - use ffi::{self, BIGNUM, DSA}; - - pub unsafe fn pqg(d: *const DSA) -> [*const BIGNUM; 3] { - let (mut p, mut q, mut g) = (ptr::null(), ptr::null(), ptr::null()); - ffi::DSA_get0_pqg(d, &mut p, &mut q, &mut g); - [p, q, g] - } - - pub unsafe fn keys(d: *const DSA) -> [*const BIGNUM; 2] { - let (mut pub_key, mut priv_key) = (ptr::null(), ptr::null()); - ffi::DSA_get0_key(d, &mut pub_key, &mut priv_key); - [pub_key, priv_key] - } -} - -#[cfg(ossl10x)] -mod compat { - use ffi::{BIGNUM, DSA}; - - pub unsafe fn pqg(d: *const DSA) -> [*const BIGNUM; 3] { - [(*d).p, (*d).q, (*d).g] - } - - pub unsafe fn keys(d: *const DSA) -> [*const BIGNUM; 2] { - [(*d).pub_key, (*d).priv_key] - } -} - -#[cfg(test)] -mod test { - use symm::Cipher; - - use super::*; - - #[test] - pub fn test_generate() { - Dsa::generate(1024).unwrap(); - } - - #[test] - pub fn test_password() { - let key = include_bytes!("../test/dsa-encrypted.pem"); - Dsa::private_key_from_pem_passphrase(key, b"mypass").unwrap(); - } - - #[test] - fn test_to_password() { - let key = Dsa::generate(2048).unwrap(); - let pem = key.private_key_to_pem_passphrase(Cipher::aes_128_cbc(), b"foobar") - .unwrap(); - Dsa::private_key_from_pem_passphrase(&pem, b"foobar").unwrap(); - assert!(Dsa::private_key_from_pem_passphrase(&pem, b"fizzbuzz").is_err()); - } - - #[test] - pub fn test_password_callback() { - let mut password_queried = false; - let key = include_bytes!("../test/dsa-encrypted.pem"); - Dsa::private_key_from_pem_callback(key, |password| { - password_queried = true; - password[..6].copy_from_slice(b"mypass"); - Ok(6) - }).unwrap(); - - assert!(password_queried); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/ec_key.rs cargo-0.26.0/vendor/openssl-0.9.24/src/ec_key.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/ec_key.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/ec_key.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -#![doc(hidden)] -#![deprecated(since = "0.9.2", note = "renamed to `ec`")] - -pub use ec::{EcKey, EcKeyRef}; diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/ec.rs cargo-0.26.0/vendor/openssl-0.9.24/src/ec.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/ec.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/ec.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,883 +0,0 @@ -//! Elliptic Curve -//! -//! Cryptology relies on the difficulty of solving mathematical problems, such as the factor -//! of large integers composed of two large prime numbers and the discrete logarithm of a -//! random eliptic curve. This module provides low-level features of the latter. -//! Elliptic Curve protocols can provide the same security with smaller keys. -//! -//! There are 2 forms of elliptic curves, `Fp` and `F2^m`. These curves use irreducible -//! trinomial or pentanomial . Being a generic interface to a wide range of algorithms, -//! the cuves are generally referenced by [`EcGroup`]. There are many built in groups -//! found in [`Nid`]. -//! -//! OpenSSL Wiki explains the fields and curves in detail at [Eliptic Curve Cryptography]. -//! -//! [`EcGroup`]: struct.EcGroup.html -//! [`Nid`]: ../nid/struct.Nid.html -//! [Eliptic Curve Cryptography]: https://wiki.openssl.org/index.php/Elliptic_Curve_Cryptography -//! -//! # Examples -//! -//! ``` -//! use openssl::ec::{EcGroup, EcPoint}; -//! use openssl::nid; -//! use openssl::error::ErrorStack; -//! fn get_ec_point() -> Result< EcPoint, ErrorStack > { -//! let group = EcGroup::from_curve_name(nid::SECP224R1)?; -//! let point = EcPoint::new(&group)?; -//! Ok(point) -//! } -//! # fn main() { -//! # let _ = get_ec_point(); -//! # } -//! ``` -use ffi; -use foreign_types::{ForeignType, ForeignTypeRef}; -use std::ptr; -use std::mem; -use libc::c_int; - -use {cvt, cvt_n, cvt_p, init}; -use bn::{BigNumRef, BigNumContextRef}; -use error::ErrorStack; -use nid::Nid; - -/// Compressed conversion from point value (Default) -pub const POINT_CONVERSION_COMPRESSED: PointConversionForm = - PointConversionForm(ffi::point_conversion_form_t::POINT_CONVERSION_COMPRESSED); - -/// Uncompressed conversion from point value (Binary curve default) -pub const POINT_CONVERSION_UNCOMPRESSED: PointConversionForm = - PointConversionForm(ffi::point_conversion_form_t::POINT_CONVERSION_UNCOMPRESSED); - -/// Performs both compressed and uncompressed conversions -pub const POINT_CONVERSION_HYBRID: PointConversionForm = - PointConversionForm(ffi::point_conversion_form_t::POINT_CONVERSION_HYBRID); - -/// Curve defined using polynomial parameters -/// -/// Most applications use a named EC_GROUP curve, however, support -/// is included to explicitly define the curve used to calculate keys -/// This information would need to be known by both endpoint to make communication -/// effective. -/// -/// OPENSSL_EC_EXPLICIT_CURVE, but that was only added in 1.1. -/// Man page documents that 0 can be used in older versions. -/// -/// OpenSSL documentation at [`EC_GROUP`] -/// -/// [`EC_GROUP`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_seed_len.html -pub const EXPLICIT_CURVE: Asn1Flag = Asn1Flag(0); - -/// Standard Curves -/// -/// Curves that make up the typical encryption use cases. The collection of curves -/// are well known but extensible. -/// -/// OpenSSL documentation at [`EC_GROUP`] -/// -/// [`EC_GROUP`]: https://www.openssl.org/docs/manmaster/man3/EC_GROUP_order_bits.html -pub const NAMED_CURVE: Asn1Flag = Asn1Flag(ffi::OPENSSL_EC_NAMED_CURVE); - -/// Compressed or Uncompressed conversion -/// -/// Conversion from the binary value of the point on the curve is performed in one of -/// compressed, uncompressed, or hybrid conversions. The default is compressed, except -/// for binary curves. -/// -/// Further documentation is available in the [X9.62] standard. -/// -/// [X9.62]: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.202.2977&rep=rep1&type=pdf -#[derive(Copy, Clone)] -pub struct PointConversionForm(ffi::point_conversion_form_t); - -/// Named Curve or Explicit -/// -/// This type acts as a boolean as to whether the EC_Group is named or -/// explicit. -#[derive(Copy, Clone)] -pub struct Asn1Flag(c_int); - -foreign_type_and_impl_send_sync! { - type CType = ffi::EC_GROUP; - fn drop = ffi::EC_GROUP_free; - - /// Describes the curve - /// - /// A curve can be of the named curve type. These curves can be discovered - /// using openssl binary `openssl ecparam -list_curves`. Other operations - /// are available in the [wiki]. These named curves are available in the - /// [`Nid`] module. - /// - /// Curves can also be generated using prime field parameters or a binary field. - /// - /// Prime fields use the formula `y^2 mod p = x^3 + ax + b mod p`. Binary - /// fields use the formula `y^2 + xy = x^3 + ax^2 + b`. Named curves have - /// assured security. To prevent accidental vulnerabilities, they should - /// be prefered. - /// - /// [wiki]: https://wiki.openssl.org/index.php/Command_Line_Elliptic_Curve_Operations - /// [`Nid`]: ../nid/index.html - pub struct EcGroup; - /// Reference to [`EcGroup`] - /// - /// [`EcGroup`]: struct.EcGroup.html - pub struct EcGroupRef; -} - -impl EcGroup { - /// Returns the group of a standard named curve. - /// - /// OpenSSL documentation at [`EC_GROUP_new`]. - /// - /// [`EC_GROUP_new`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_new.html - pub fn from_curve_name(nid: Nid) -> Result { - unsafe { - init(); - cvt_p(ffi::EC_GROUP_new_by_curve_name(nid.as_raw())).map(EcGroup) - } - } -} - -impl EcGroupRef { - /// Places the components of a curve over a prime field in the provided `BigNum`s. - /// The components make up the formula `y^2 mod p = x^3 + ax + b mod p`. - /// - /// OpenSSL documentation available at [`EC_GROUP_get_curve_GFp`] - /// - /// [`EC_GROUP_get_curve_GFp`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_curve_GFp.html - pub fn components_gfp( - &self, - p: &mut BigNumRef, - a: &mut BigNumRef, - b: &mut BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EC_GROUP_get_curve_GFp( - self.as_ptr(), - p.as_ptr(), - a.as_ptr(), - b.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Places the components of a curve over a binary field in the provided `BigNum`s. - /// The components make up the formula `y^2 + xy = x^3 + ax^2 + b`. - /// - /// In this form `p` relates to the irreducible polynomial. Each bit represents - /// a term in the polynomial. It will be set to 3 `1`s or 5 `1`s depending on - /// using a trinomial or pentanomial. - /// - /// OpenSSL documentation at [`EC_GROUP_get_curve_GF2m`]. - /// - /// [`EC_GROUP_get_curve_GF2m`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_curve_GF2m.html - #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] - pub fn components_gf2m( - &self, - p: &mut BigNumRef, - a: &mut BigNumRef, - b: &mut BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EC_GROUP_get_curve_GF2m( - self.as_ptr(), - p.as_ptr(), - a.as_ptr(), - b.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Returns the degree of the curve. - /// - /// OpenSSL documentation at [`EC_GROUP_get_degree`] - /// - /// [`EC_GROUP_get_degree`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_degree.html - pub fn degree(&self) -> u32 { - unsafe { ffi::EC_GROUP_get_degree(self.as_ptr()) as u32 } - } - - /// Places the order of the curve in the provided `BigNum`. - /// - /// OpenSSL documentation at [`EC_GROUP_get_order`] - /// - /// [`EC_GROUP_get_order`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_GROUP_get_order.html - pub fn order( - &self, - order: &mut BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EC_GROUP_get_order( - self.as_ptr(), - order.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Sets the flag determining if the group corresponds to a named curve or must be explicitly - /// parameterized. - /// - /// This defaults to `EXPLICIT_CURVE` in OpenSSL 1.0.1 and 1.0.2, but `NAMED_CURVE` in OpenSSL - /// 1.1.0. - pub fn set_asn1_flag(&mut self, flag: Asn1Flag) { - unsafe { - ffi::EC_GROUP_set_asn1_flag(self.as_ptr(), flag.0); - } - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::EC_POINT; - fn drop = ffi::EC_POINT_free; - - /// Represents a point on the curve - /// - /// OpenSSL documentation at [`EC_POINT_new`] - /// - /// [`EC_POINT_new`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_new.html - pub struct EcPoint; - /// Reference to [`EcPoint`] - /// - /// [`EcPoint`]: struct.EcPoint.html - pub struct EcPointRef; -} - -impl EcPointRef { - /// Computes `a + b`, storing the result in `self`. - /// - /// OpenSSL documentation at [`EC_POINT_add`] - /// - /// [`EC_POINT_add`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_add.html - pub fn add( - &mut self, - group: &EcGroupRef, - a: &EcPointRef, - b: &EcPointRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EC_POINT_add( - group.as_ptr(), - self.as_ptr(), - a.as_ptr(), - b.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Computes `q * m`, storing the result in `self`. - /// - /// OpenSSL documentation at [`EC_POINT_mul`] - /// - /// [`EC_POINT_mul`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_mul.html - pub fn mul( - &mut self, - group: &EcGroupRef, - q: &EcPointRef, - m: &BigNumRef, - ctx: &BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EC_POINT_mul( - group.as_ptr(), - self.as_ptr(), - ptr::null(), - q.as_ptr(), - m.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Computes `generator * n`, storing the result ing `self`. - pub fn mul_generator( - &mut self, - group: &EcGroupRef, - n: &BigNumRef, - ctx: &BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EC_POINT_mul( - group.as_ptr(), - self.as_ptr(), - n.as_ptr(), - ptr::null(), - ptr::null(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Computes `generator * n + q * m`, storing the result in `self`. - pub fn mul_full( - &mut self, - group: &EcGroupRef, - n: &BigNumRef, - q: &EcPointRef, - m: &BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EC_POINT_mul( - group.as_ptr(), - self.as_ptr(), - n.as_ptr(), - q.as_ptr(), - m.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Inverts `self`. - /// - /// OpenSSL documentation at [`EC_POINT_invert`] - /// - /// [`EC_POINT_invert`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_invert.html - pub fn invert(&mut self, group: &EcGroupRef, ctx: &BigNumContextRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EC_POINT_invert( - group.as_ptr(), - self.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Serializes the point to a binary representation. - /// - /// OpenSSL documentation at [`EC_POINT_point2oct`] - /// - /// [`EC_POINT_point2oct`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_point2oct.html - pub fn to_bytes( - &self, - group: &EcGroupRef, - form: PointConversionForm, - ctx: &mut BigNumContextRef, - ) -> Result, ErrorStack> { - unsafe { - let len = ffi::EC_POINT_point2oct( - group.as_ptr(), - self.as_ptr(), - form.0, - ptr::null_mut(), - 0, - ctx.as_ptr(), - ); - if len == 0 { - return Err(ErrorStack::get()); - } - let mut buf = vec![0; len]; - let len = ffi::EC_POINT_point2oct( - group.as_ptr(), - self.as_ptr(), - form.0, - buf.as_mut_ptr(), - len, - ctx.as_ptr(), - ); - if len == 0 { - Err(ErrorStack::get()) - } else { - Ok(buf) - } - } - } - - /// Determines if this point is equal to another. - /// - /// OpenSSL doucmentation at [`EC_POINT_cmp`] - /// - /// [`EC_POINT_cmp`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_cmp.html - pub fn eq( - &self, - group: &EcGroupRef, - other: &EcPointRef, - ctx: &mut BigNumContextRef, - ) -> Result { - unsafe { - let res = cvt_n(ffi::EC_POINT_cmp( - group.as_ptr(), - self.as_ptr(), - other.as_ptr(), - ctx.as_ptr(), - ))?; - Ok(res == 0) - } - } - - /// Place affine coordinates of a curve over a prime field in the provided - /// `x` and `y` `BigNum`s - /// - /// OpenSSL documentation at [`EC_POINT_get_affine_coordinates_GFp`] - /// - /// [`EC_POINT_get_affine_coordinates_GFp`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_get_affine_coordinates_GFp.html - pub fn affine_coordinates_gfp( - &self, - group: &EcGroupRef, - x: &mut BigNumRef, - y: &mut BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EC_POINT_get_affine_coordinates_GFp( - group.as_ptr(), - self.as_ptr(), - x.as_ptr(), - y.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } - - /// Place affine coordinates of a curve over a binary field in the provided - /// `x` and `y` `BigNum`s - /// - /// OpenSSL documentation at [`EC_POINT_get_affine_coordinates_GF2m`] - /// - /// [`EC_POINT_get_affine_coordinates_GF2m`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_get_affine_coordinates_GF2m.html - #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] - pub fn affine_coordinates_gf2m( - &self, - group: &EcGroupRef, - x: &mut BigNumRef, - y: &mut BigNumRef, - ctx: &mut BigNumContextRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EC_POINT_get_affine_coordinates_GF2m( - group.as_ptr(), - self.as_ptr(), - x.as_ptr(), - y.as_ptr(), - ctx.as_ptr(), - )).map(|_| ()) - } - } -} - -impl EcPoint { - /// Creates a new point on the specified curve. - /// - /// OpenSSL documentation at [`EC_POINT_new`] - /// - /// [`EC_POINT_new`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_new.html - pub fn new(group: &EcGroupRef) -> Result { - unsafe { cvt_p(ffi::EC_POINT_new(group.as_ptr())).map(EcPoint) } - } - - /// Creates point from a binary representation - /// - /// OpenSSL documentation at [`EC_POINT_oct2point`] - /// - /// [`EC_POINT_oct2point`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_POINT_oct2point.html - pub fn from_bytes( - group: &EcGroupRef, - buf: &[u8], - ctx: &mut BigNumContextRef, - ) -> Result { - let point = EcPoint::new(group)?; - unsafe { - cvt(ffi::EC_POINT_oct2point( - group.as_ptr(), - point.as_ptr(), - buf.as_ptr(), - buf.len(), - ctx.as_ptr(), - ))?; - } - Ok(point) - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::EC_KEY; - fn drop = ffi::EC_KEY_free; - - /// Public and optional Private key on the given curve - /// - /// OpenSSL documentation at [`EC_KEY_new`] - /// - /// [`EC_KEY_new`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_new.html - pub struct EcKey; - /// Reference to [`EcKey`] - /// - /// [`EcKey`]: struct.EcKey.html - pub struct EcKeyRef; -} - -impl EcKeyRef { - private_key_to_pem!(ffi::PEM_write_bio_ECPrivateKey); - private_key_to_der!(ffi::i2d_ECPrivateKey); - - /// Return [`EcGroup`] of the `EcKey` - /// - /// OpenSSL documentation at [`EC_KEY_get0_group`] - /// - /// [`EC_KEY_get0_group`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_get0_group.html - pub fn group(&self) -> Option<&EcGroupRef> { - unsafe { - let ptr = ffi::EC_KEY_get0_group(self.as_ptr()); - if ptr.is_null() { - None - } else { - Some(EcGroupRef::from_ptr(ptr as *mut _)) - } - } - } - - /// Return [`EcPoint`] associated with the public key - /// - /// OpenSSL documentation at [`EC_KEY_get0_pubic_key`] - /// - /// [`EC_KEY_get0_pubic_key`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_get0_public_key.html - pub fn public_key(&self) -> Option<&EcPointRef> { - unsafe { - let ptr = ffi::EC_KEY_get0_public_key(self.as_ptr()); - if ptr.is_null() { - None - } else { - Some(EcPointRef::from_ptr(ptr as *mut _)) - } - } - } - - /// Return [`EcPoint`] associated with the private key - /// - /// OpenSSL documentation at [`EC_KEY_get0_private_key`] - /// - /// [`EC_KEY_get0_private_key`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_get0_private_key.html - pub fn private_key(&self) -> Option<&BigNumRef> { - unsafe { - let ptr = ffi::EC_KEY_get0_private_key(self.as_ptr()); - if ptr.is_null() { - None - } else { - Some(BigNumRef::from_ptr(ptr as *mut _)) - } - } - } - - /// Checks the key for validity. - /// - /// OpenSSL documenation at [`EC_KEY_check_key`] - /// - /// [`EC_KEY_check_key`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_check_key.html - pub fn check_key(&self) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::EC_KEY_check_key(self.as_ptr())).map(|_| ()) } - } - - /// Create a copy of the `EcKey` to allow modification - pub fn to_owned(&self) -> Result { - unsafe { cvt_p(ffi::EC_KEY_dup(self.as_ptr())).map(EcKey) } - } -} - -impl EcKey { - /// Constructs an `EcKey` corresponding to a known curve. - /// - /// It will not have an associated public or private key. This kind of key is primarily useful - /// to be provided to the `set_tmp_ecdh` methods on `Ssl` and `SslContextBuilder`. - /// - /// OpenSSL documenation at [`EC_KEY_new_by_curve_name`] - /// - /// [`EC_KEY_new_by_curve_name`]: https://www.openssl.org/docs/man1.1.0/crypto/EC_KEY_new_by_curve_name.html - pub fn from_curve_name(nid: Nid) -> Result { - unsafe { - init(); - cvt_p(ffi::EC_KEY_new_by_curve_name(nid.as_raw())).map(EcKey) - } - } - - /// Constructs an `EcKey` from the specified group with the associated `EcPoint`, public_key. - /// - /// This will only have the associated public_key. - /// - /// # Example - /// - /// ```no_run - /// use openssl::bn::BigNumContext; - /// use openssl::ec::*; - /// use openssl::nid; - /// use openssl::pkey::PKey; - /// - /// // get bytes from somewhere, i.e. this will not produce a valid key - /// let public_key: Vec = vec![]; - /// - /// // create an EcKey from the binary form of a EcPoint - /// let group = EcGroup::from_curve_name(nid::SECP256K1).unwrap(); - /// let mut ctx = BigNumContext::new().unwrap(); - /// let point = EcPoint::from_bytes(&group, &public_key, &mut ctx).unwrap(); - /// let key = EcKey::from_public_key(&group, &point); - /// ``` - pub fn from_public_key( - group: &EcGroupRef, - public_key: &EcPointRef, - ) -> Result { - let mut builder = EcKeyBuilder::new()?; - builder.set_group(group)?; - builder.set_public_key(public_key)?; - Ok(builder.build()) - } - - /// Generates a new public/private key pair on the specified curve. - pub fn generate(group: &EcGroupRef) -> Result { - let mut builder = EcKeyBuilder::new()?; - builder.set_group(group)?; - builder.generate_key()?; - Ok(builder.build()) - } - - #[deprecated(since = "0.9.2", note = "use from_curve_name")] - pub fn new_by_curve_name(nid: Nid) -> Result { - EcKey::from_curve_name(nid) - } - - private_key_from_pem!(EcKey, ffi::PEM_read_bio_ECPrivateKey); - private_key_from_der!(EcKey, ffi::d2i_ECPrivateKey); -} - - -foreign_type_and_impl_send_sync! { - type CType = ffi::EC_KEY; - fn drop = ffi::EC_KEY_free; - - /// Builder pattern for key generation - /// - /// Returns a `EcKeyBuilder` to be consumed by `build` - pub struct EcKeyBuilder; - /// Reference to [`EcKeyBuilder`] - /// - /// [`EcKeyBuilder`]: struct.EcKeyBuilder.html - pub struct EcKeyBuilderRef; -} - -impl EcKeyBuilder { - /// Creates an empty `EcKeyBuilder` to be chained with additonal methods - pub fn new() -> Result { - unsafe { - init(); - cvt_p(ffi::EC_KEY_new()).map(EcKeyBuilder) - } - } - - /// Consume the `EcKeyBuilder` and return [`EcKey`] - /// - /// [`EcKey`]: struct.EcKey.html - pub fn build(self) -> EcKey { - unsafe { - let key = EcKey::from_ptr(self.as_ptr()); - mem::forget(self); - key - } - } -} - -impl EcKeyBuilderRef { - /// Set the [`EcGroup`] explicitly - /// - /// [`EcGroup`]: struct.EcGroup.html - pub fn set_group(&mut self, group: &EcGroupRef) -> Result<&mut EcKeyBuilderRef, ErrorStack> { - unsafe { cvt(ffi::EC_KEY_set_group(self.as_ptr(), group.as_ptr())).map(|_| self) } - } - - /// Set public key to given `EcPoint` - pub fn set_public_key( - &mut self, - public_key: &EcPointRef, - ) -> Result<&mut EcKeyBuilderRef, ErrorStack> { - unsafe { - cvt(ffi::EC_KEY_set_public_key( - self.as_ptr(), - public_key.as_ptr(), - )).map(|_| self) - } - } - - /// Generate public and private keys. - pub fn generate_key(&mut self) -> Result<&mut EcKeyBuilderRef, ErrorStack> { - unsafe { cvt(ffi::EC_KEY_generate_key(self.as_ptr())).map(|_| self) } - } - - /// Sets the public key based on affine coordinates. - pub fn set_public_key_affine_coordinates( - &mut self, - x: &BigNumRef, - y: &BigNumRef, - ) -> Result<&mut EcKeyBuilderRef, ErrorStack> { - unsafe { - cvt(ffi::EC_KEY_set_public_key_affine_coordinates( - self.as_ptr(), - x.as_ptr(), - y.as_ptr(), - )).map(|_| self) - } - } - - /// Sets the private key. - pub fn set_private_key(&mut self, key: &BigNumRef) -> Result<&mut EcKeyBuilderRef, ErrorStack> { - unsafe { cvt(ffi::EC_KEY_set_private_key(self.as_ptr(), key.as_ptr())).map(|_| self) } - } -} - -#[cfg(test)] -mod test { - use bn::{BigNum, BigNumContext}; - use nid; - use data_encoding::BASE64URL_NOPAD; - use super::*; - - #[test] - fn key_new_by_curve_name() { - EcKey::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - } - - #[test] - fn generate() { - let group = EcGroup::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - let key = EcKey::generate(&group).unwrap(); - key.public_key().unwrap(); - key.private_key().unwrap(); - } - - #[test] - fn dup() { - let group = EcGroup::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - let key = EcKey::generate(&group).unwrap(); - key.to_owned().unwrap(); - } - - #[test] - fn point_new() { - let group = EcGroup::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - EcPoint::new(&group).unwrap(); - } - - #[test] - fn point_bytes() { - let group = EcGroup::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - let key = EcKey::generate(&group).unwrap(); - let point = key.public_key().unwrap(); - let mut ctx = BigNumContext::new().unwrap(); - let bytes = point - .to_bytes(&group, POINT_CONVERSION_COMPRESSED, &mut ctx) - .unwrap(); - let point2 = EcPoint::from_bytes(&group, &bytes, &mut ctx).unwrap(); - assert!(point.eq(&group, &point2, &mut ctx).unwrap()); - } - - #[test] - fn mul_generator() { - let group = EcGroup::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - let key = EcKey::generate(&group).unwrap(); - let mut ctx = BigNumContext::new().unwrap(); - let mut public_key = EcPoint::new(&group).unwrap(); - public_key - .mul_generator(&group, key.private_key().unwrap(), &mut ctx) - .unwrap(); - assert!( - public_key - .eq(&group, key.public_key().unwrap(), &mut ctx) - .unwrap() - ); - } - - #[test] - fn key_from_public_key() { - let group = EcGroup::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - let key = EcKey::generate(&group).unwrap(); - let mut ctx = BigNumContext::new().unwrap(); - let bytes = key.public_key() - .unwrap() - .to_bytes(&group, POINT_CONVERSION_COMPRESSED, &mut ctx) - .unwrap(); - - drop(key); - let public_key = EcPoint::from_bytes(&group, &bytes, &mut ctx).unwrap(); - let ec_key = EcKey::from_public_key(&group, &public_key).unwrap(); - assert!(ec_key.check_key().is_ok()); - assert!(ec_key.public_key().is_some()); - assert!(ec_key.private_key().is_none()); - } - - #[test] - fn key_from_affine_coordinates() { - let group = EcGroup::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - let x = BASE64URL_NOPAD.decode( - "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4".as_bytes(), - ).unwrap(); - let y = BASE64URL_NOPAD.decode( - "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM".as_bytes(), - ).unwrap(); - - let xbn = BigNum::from_slice(&x).unwrap(); - let ybn = BigNum::from_slice(&y).unwrap(); - - let mut builder = EcKeyBuilder::new().unwrap(); - builder.set_group(&group).unwrap(); - builder - .set_public_key_affine_coordinates(&xbn, &ybn) - .unwrap(); - - let ec_key = builder.build(); - assert!(ec_key.check_key().is_ok()); - assert!(ec_key.public_key().is_some()); - } - - #[test] - fn set_private_key() { - let group = EcGroup::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - let d = BASE64URL_NOPAD.decode( - "870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE".as_bytes(), - ).unwrap(); - - let dbn = BigNum::from_slice(&d).unwrap(); - - let mut builder = EcKeyBuilder::new().unwrap(); - builder.set_group(&group).unwrap(); - builder.set_private_key(&dbn).unwrap(); - - let ec_key = builder.build(); - assert!(ec_key.private_key().is_some()); - } - - #[test] - fn get_affine_coordinates() { - let group = EcGroup::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - let x = BASE64URL_NOPAD.decode( - "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4".as_bytes(), - ).unwrap(); - let y = BASE64URL_NOPAD.decode( - "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM".as_bytes(), - ).unwrap(); - - let xbn = BigNum::from_slice(&x).unwrap(); - let ybn = BigNum::from_slice(&y).unwrap(); - - let mut builder = EcKeyBuilder::new().unwrap(); - builder.set_group(&group).unwrap(); - builder - .set_public_key_affine_coordinates(&xbn, &ybn) - .unwrap(); - - let ec_key = builder.build(); - - let mut xbn2 = BigNum::new().unwrap(); - let mut ybn2 = BigNum::new().unwrap(); - let mut ctx = BigNumContext::new().unwrap(); - let ec_key_pk = ec_key.public_key().unwrap(); - ec_key_pk - .affine_coordinates_gfp(&group, &mut xbn2, &mut ybn2, &mut ctx) - .unwrap(); - assert_eq!(xbn2, xbn); - assert_eq!(ybn2, ybn); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/error.rs cargo-0.26.0/vendor/openssl-0.9.24/src/error.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/error.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/error.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,247 +0,0 @@ -//! Errors returned by OpenSSL library. -//! -//! OpenSSL errors are stored in an `ErrorStack`. Most methods in the crate -//! returns a `Result` type. -//! -//! # Examples -//! -//! ``` -//! use openssl::error::ErrorStack; -//! use openssl::bn::BigNum; -//! -//! let an_error = BigNum::from_dec_str("Cannot parse letters"); -//! match an_error { -//! Ok(_) => (), -//! Err(e) => println!("Parsing Error: {:?}", e), -//! } -//! ``` -use libc::{c_ulong, c_char, c_int}; -use std::fmt; -use std::error; -use std::ffi::CStr; -use std::io; -use std::str; -use std::ptr; -use std::borrow::Cow; - -use ffi; - -/// Collection of [`Error`]s from OpenSSL. -/// -/// [`Error`]: struct.Error.html -#[derive(Debug, Clone)] -pub struct ErrorStack(Vec); - -impl ErrorStack { - /// Returns the contents of the OpenSSL error stack. - pub fn get() -> ErrorStack { - let mut vec = vec![]; - while let Some(err) = Error::get() { - vec.push(err); - } - ErrorStack(vec) - } -} - -impl ErrorStack { - /// Returns the errors in the stack. - pub fn errors(&self) -> &[Error] { - &self.0 - } -} - -impl fmt::Display for ErrorStack { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - let mut first = true; - for err in &self.0 { - if !first { - fmt.write_str(", ")?; - } - write!(fmt, "{}", err)?; - first = false; - } - Ok(()) - } -} - -impl error::Error for ErrorStack { - fn description(&self) -> &str { - "An OpenSSL error stack" - } -} - -impl From for io::Error { - fn from(e: ErrorStack) -> io::Error { - io::Error::new(io::ErrorKind::Other, e) - } -} - -impl From for fmt::Error { - fn from(_: ErrorStack) -> fmt::Error { - fmt::Error - } -} - -/// An error reported from OpenSSL. -#[derive(Clone)] -pub struct Error { - code: c_ulong, - file: *const c_char, - line: c_int, - data: Option>, -} - -unsafe impl Sync for Error {} -unsafe impl Send for Error {} - -impl Error { - /// Returns the first error on the OpenSSL error stack. - pub fn get() -> Option { - unsafe { - ffi::init(); - - let mut file = ptr::null(); - let mut line = 0; - let mut data = ptr::null(); - let mut flags = 0; - match ffi::ERR_get_error_line_data(&mut file, &mut line, &mut data, &mut flags) { - 0 => None, - code => { - // The memory referenced by data is only valid until that slot is overwritten - // in the error stack, so we'll need to copy it off if it's dynamic - let data = if flags & ffi::ERR_TXT_STRING != 0 { - let bytes = CStr::from_ptr(data as *const _).to_bytes(); - let data = str::from_utf8(bytes).unwrap(); - let data = if flags & ffi::ERR_TXT_MALLOCED != 0 { - Cow::Owned(data.to_string()) - } else { - Cow::Borrowed(data) - }; - Some(data) - } else { - None - }; - Some(Error { - code: code, - file: file, - line: line, - data: data, - }) - } - } - } - } - - /// Returns the raw OpenSSL error code for this error. - pub fn code(&self) -> c_ulong { - self.code - } - - /// Returns the name of the library reporting the error, if available. - pub fn library(&self) -> Option<&'static str> { - unsafe { - let cstr = ffi::ERR_lib_error_string(self.code); - if cstr.is_null() { - return None; - } - let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); - Some(str::from_utf8(bytes).unwrap()) - } - } - - /// Returns the name of the function reporting the error. - pub fn function(&self) -> Option<&'static str> { - unsafe { - let cstr = ffi::ERR_func_error_string(self.code); - if cstr.is_null() { - return None; - } - let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); - Some(str::from_utf8(bytes).unwrap()) - } - } - - /// Returns the reason for the error. - pub fn reason(&self) -> Option<&'static str> { - unsafe { - let cstr = ffi::ERR_reason_error_string(self.code); - if cstr.is_null() { - return None; - } - let bytes = CStr::from_ptr(cstr as *const _).to_bytes(); - Some(str::from_utf8(bytes).unwrap()) - } - } - - /// Returns the name of the source file which encountered the error. - pub fn file(&self) -> &'static str { - unsafe { - assert!(!self.file.is_null()); - let bytes = CStr::from_ptr(self.file as *const _).to_bytes(); - str::from_utf8(bytes).unwrap() - } - } - - /// Returns the line in the source file which encountered the error. - pub fn line(&self) -> c_int { - self.line - } - - /// Returns additional data describing the error. - pub fn data(&self) -> Option<&str> { - self.data.as_ref().map(|s| &**s) - } -} - -impl fmt::Debug for Error { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - let mut builder = fmt.debug_struct("Error"); - builder.field("code", &self.code()); - if let Some(library) = self.library() { - builder.field("library", &library); - } - if let Some(function) = self.function() { - builder.field("function", &function); - } - if let Some(reason) = self.reason() { - builder.field("reason", &reason); - } - builder.field("file", &self.file()); - builder.field("line", &self.line()); - if let Some(data) = self.data() { - builder.field("data", &data); - } - builder.finish() - } -} - -impl fmt::Display for Error { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!(fmt, "error:{:08X}", self.code())?; - match self.library() { - Some(l) => write!(fmt, ":{}", l)?, - None => write!(fmt, ":lib({})", ffi::ERR_GET_LIB(self.code()))?, - } - match self.function() { - Some(f) => write!(fmt, ":{}", f)?, - None => write!(fmt, ":func({})", ffi::ERR_GET_FUNC(self.code()))?, - } - match self.reason() { - Some(r) => write!(fmt, ":{}", r)?, - None => write!(fmt, ":reason({})", ffi::ERR_GET_FUNC(self.code()))?, - } - write!( - fmt, - ":{}:{}:{}", - self.file(), - self.line(), - self.data().unwrap_or("") - ) - } -} - -impl error::Error for Error { - fn description(&self) -> &str { - "an OpenSSL error" - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/ex_data.rs cargo-0.26.0/vendor/openssl-0.9.24/src/ex_data.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/ex_data.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/ex_data.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -use libc::c_int; -use std::marker::PhantomData; - -/// A slot in a type's "extra data" structure. -/// -/// It is parameterized over the type containing the extra data as well as the -/// type of the data in the slot. -pub struct Index(c_int, PhantomData<(T, U)>); - -impl Copy for Index {} - -impl Clone for Index { - fn clone(&self) -> Index { - *self - } -} - -impl Index { - pub unsafe fn from_raw(idx: c_int) -> Index { - Index(idx, PhantomData) - } - - pub fn as_raw(&self) -> c_int { - self.0 - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/hash.rs cargo-0.26.0/vendor/openssl-0.9.24/src/hash.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/hash.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/hash.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,407 +0,0 @@ -use std::io::prelude::*; -use std::io; -use std::ops::{Deref, DerefMut}; -use std::fmt; -use ffi; - -#[cfg(ossl110)] -use ffi::{EVP_MD_CTX_new, EVP_MD_CTX_free}; -#[cfg(any(ossl101, ossl102))] -use ffi::{EVP_MD_CTX_create as EVP_MD_CTX_new, EVP_MD_CTX_destroy as EVP_MD_CTX_free}; - -use {cvt, cvt_p}; -use error::ErrorStack; - -#[derive(Copy, Clone)] -pub struct MessageDigest(*const ffi::EVP_MD); - -impl MessageDigest { - pub fn md5() -> MessageDigest { - unsafe { MessageDigest(ffi::EVP_md5()) } - } - - pub fn sha1() -> MessageDigest { - unsafe { MessageDigest(ffi::EVP_sha1()) } - } - - pub fn sha224() -> MessageDigest { - unsafe { MessageDigest(ffi::EVP_sha224()) } - } - - pub fn sha256() -> MessageDigest { - unsafe { MessageDigest(ffi::EVP_sha256()) } - } - - pub fn sha384() -> MessageDigest { - unsafe { MessageDigest(ffi::EVP_sha384()) } - } - - pub fn sha512() -> MessageDigest { - unsafe { MessageDigest(ffi::EVP_sha512()) } - } - - pub fn ripemd160() -> MessageDigest { - unsafe { MessageDigest(ffi::EVP_ripemd160()) } - } - - pub fn as_ptr(&self) -> *const ffi::EVP_MD { - self.0 - } -} - -#[derive(PartialEq, Copy, Clone)] -enum State { - Reset, - Updated, - Finalized, -} - -use self::State::*; - -/// Provides message digest (hash) computation. -/// -/// # Examples -/// -/// Calculate a hash in one go: -/// -/// ``` -/// use openssl::hash::{hash, MessageDigest}; -/// -/// let data = b"\x42\xF4\x97\xE0"; -/// let spec = b"\x7c\x43\x0f\x17\x8a\xef\xdf\x14\x87\xfe\xe7\x14\x4e\x96\x41\xe2"; -/// let res = hash(MessageDigest::md5(), data).unwrap(); -/// assert_eq!(res, spec); -/// ``` -/// -/// Supply the input in chunks: -/// -/// ``` -/// use openssl::hash::{Hasher, MessageDigest}; -/// -/// let data = [b"\x42\xF4", b"\x97\xE0"]; -/// let spec = b"\x7c\x43\x0f\x17\x8a\xef\xdf\x14\x87\xfe\xe7\x14\x4e\x96\x41\xe2"; -/// let mut h = Hasher::new(MessageDigest::md5()).unwrap(); -/// h.update(data[0]).unwrap(); -/// h.update(data[1]).unwrap(); -/// let res = h.finish().unwrap(); -/// assert_eq!(res, spec); -/// ``` -/// -/// # Warning -/// -/// Don't actually use MD5 and SHA-1 hashes, they're not secure anymore. -/// -/// Don't ever hash passwords, use the functions in the `pkcs5` module or bcrypt/scrypt instead. -pub struct Hasher { - ctx: *mut ffi::EVP_MD_CTX, - md: *const ffi::EVP_MD, - type_: MessageDigest, - state: State, -} - -impl Hasher { - /// Creates a new `Hasher` with the specified hash type. - pub fn new(ty: MessageDigest) -> Result { - ffi::init(); - - let ctx = unsafe { cvt_p(EVP_MD_CTX_new())? }; - - let mut h = Hasher { - ctx: ctx, - md: ty.as_ptr(), - type_: ty, - state: Finalized, - }; - h.init()?; - Ok(h) - } - - fn init(&mut self) -> Result<(), ErrorStack> { - match self.state { - Reset => return Ok(()), - Updated => { - self.finish2()?; - } - Finalized => (), - } - unsafe { - cvt(ffi::EVP_DigestInit_ex(self.ctx, self.md, 0 as *mut _))?; - } - self.state = Reset; - Ok(()) - } - - /// Feeds data into the hasher. - pub fn update(&mut self, data: &[u8]) -> Result<(), ErrorStack> { - if self.state == Finalized { - self.init()?; - } - unsafe { - cvt(ffi::EVP_DigestUpdate( - self.ctx, - data.as_ptr() as *mut _, - data.len(), - ))?; - } - self.state = Updated; - Ok(()) - } - - #[deprecated(note = "use finish2 instead", since = "0.9.11")] - pub fn finish(&mut self) -> Result, ErrorStack> { - self.finish2().map(|b| b.to_vec()) - } - - /// Returns the hash of the data written and resets the hasher. - /// - /// Unlike `finish`, this method does not allocate. - pub fn finish2(&mut self) -> Result { - if self.state == Finalized { - self.init()?; - } - unsafe { - let mut len = ffi::EVP_MAX_MD_SIZE; - let mut buf = [0; ffi::EVP_MAX_MD_SIZE as usize]; - cvt(ffi::EVP_DigestFinal_ex( - self.ctx, - buf.as_mut_ptr(), - &mut len, - ))?; - self.state = Finalized; - Ok(DigestBytes { - buf: buf, - len: len as usize, - }) - } - } -} - -impl Write for Hasher { - #[inline] - fn write(&mut self, buf: &[u8]) -> io::Result { - self.update(buf)?; - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -impl Clone for Hasher { - fn clone(&self) -> Hasher { - let ctx = unsafe { - let ctx = EVP_MD_CTX_new(); - assert!(!ctx.is_null()); - let r = ffi::EVP_MD_CTX_copy_ex(ctx, self.ctx); - assert_eq!(r, 1); - ctx - }; - Hasher { - ctx: ctx, - md: self.md, - type_: self.type_, - state: self.state, - } - } -} - -impl Drop for Hasher { - fn drop(&mut self) { - unsafe { - if self.state != Finalized { - drop(self.finish2()); - } - EVP_MD_CTX_free(self.ctx); - } - } -} - -/// The resulting bytes of a digest. -/// -/// This type derefs to a byte slice - it exists to avoid allocating memory to -/// store the digest data. -#[derive(Copy)] -pub struct DigestBytes { - buf: [u8; ffi::EVP_MAX_MD_SIZE as usize], - len: usize, -} - -impl Clone for DigestBytes { - #[inline] - fn clone(&self) -> DigestBytes { - *self - } -} - -impl Deref for DigestBytes { - type Target = [u8]; - - #[inline] - fn deref(&self) -> &[u8] { - &self.buf[..self.len] - } -} - -impl DerefMut for DigestBytes { - #[inline] - fn deref_mut(&mut self) -> &mut [u8] { - &mut self.buf[..self.len] - } -} - -impl AsRef<[u8]> for DigestBytes { - #[inline] - fn as_ref(&self) -> &[u8] { - self.deref() - } -} - -impl fmt::Debug for DigestBytes { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(&**self, fmt) - } -} - -#[deprecated(note = "use hash2 instead", since = "0.9.11")] -pub fn hash(t: MessageDigest, data: &[u8]) -> Result, ErrorStack> { - hash2(t, data).map(|b| b.to_vec()) -} - -/// Computes the hash of the `data` with the hash `t`. -/// -/// Unlike `hash`, this function does not allocate the return value. -pub fn hash2(t: MessageDigest, data: &[u8]) -> Result { - let mut h = Hasher::new(t)?; - h.update(data)?; - h.finish2() -} - -#[cfg(test)] -mod tests { - use hex::{FromHex, ToHex}; - use std::io::prelude::*; - - use super::*; - - fn hash_test(hashtype: MessageDigest, hashtest: &(&str, &str)) { - let res = hash2(hashtype, &Vec::from_hex(hashtest.0).unwrap()).unwrap(); - assert_eq!(res.to_hex(), hashtest.1); - } - - fn hash_recycle_test(h: &mut Hasher, hashtest: &(&str, &str)) { - let _ = h.write_all(&Vec::from_hex(hashtest.0).unwrap()).unwrap(); - let res = h.finish2().unwrap(); - assert_eq!(res.to_hex(), hashtest.1); - } - - // Test vectors from http://www.nsrl.nist.gov/testdata/ - #[allow(non_upper_case_globals)] - const md5_tests: [(&'static str, &'static str); 13] = - [ - ("", "d41d8cd98f00b204e9800998ecf8427e"), - ("7F", "83acb6e67e50e31db6ed341dd2de1595"), - ("EC9C", "0b07f0d4ca797d8ac58874f887cb0b68"), - ("FEE57A", "e0d583171eb06d56198fc0ef22173907"), - ("42F497E0", "7c430f178aefdf1487fee7144e9641e2"), - ("C53B777F1C", "75ef141d64cb37ec423da2d9d440c925"), - ("89D5B576327B", "ebbaf15eb0ed784c6faa9dc32831bf33"), - ("5D4CCE781EB190", "ce175c4b08172019f05e6b5279889f2c"), - ("81901FE94932D7B9", "cd4d2f62b8cdb3a0cf968a735a239281"), - ("C9FFDEE7788EFB4EC9", "e0841a231ab698db30c6c0f3f246c014"), - ("66AC4B7EBA95E53DC10B", "a3b3cea71910d9af56742aa0bb2fe329"), - ("A510CD18F7A56852EB0319", "577e216843dd11573574d3fb209b97d8"), - ( - "AAED18DBE8938C19ED734A8D", - "6f80fb775f27e0a4ce5c2f42fc72c5f1", - ), - ]; - - #[test] - fn test_md5() { - for test in md5_tests.iter() { - hash_test(MessageDigest::md5(), test); - } - } - - #[test] - fn test_md5_recycle() { - let mut h = Hasher::new(MessageDigest::md5()).unwrap(); - for test in md5_tests.iter() { - hash_recycle_test(&mut h, test); - } - } - - #[test] - fn test_finish_twice() { - let mut h = Hasher::new(MessageDigest::md5()).unwrap(); - h.write_all(&Vec::from_hex(md5_tests[6].0).unwrap()) - .unwrap(); - h.finish2().unwrap(); - let res = h.finish2().unwrap(); - let null = hash2(MessageDigest::md5(), &[]).unwrap(); - assert_eq!(&*res, &*null); - } - - #[test] - fn test_clone() { - let i = 7; - let inp = Vec::from_hex(md5_tests[i].0).unwrap(); - assert!(inp.len() > 2); - let p = inp.len() / 2; - let h0 = Hasher::new(MessageDigest::md5()).unwrap(); - - println!("Clone a new hasher"); - let mut h1 = h0.clone(); - h1.write_all(&inp[..p]).unwrap(); - { - println!("Clone an updated hasher"); - let mut h2 = h1.clone(); - h2.write_all(&inp[p..]).unwrap(); - let res = h2.finish2().unwrap(); - assert_eq!(res.to_hex(), md5_tests[i].1); - } - h1.write_all(&inp[p..]).unwrap(); - let res = h1.finish2().unwrap(); - assert_eq!(res.to_hex(), md5_tests[i].1); - - println!("Clone a finished hasher"); - let mut h3 = h1.clone(); - h3.write_all(&Vec::from_hex(md5_tests[i + 1].0).unwrap()) - .unwrap(); - let res = h3.finish2().unwrap(); - assert_eq!(res.to_hex(), md5_tests[i + 1].1); - } - - #[test] - fn test_sha1() { - let tests = [("616263", "a9993e364706816aba3e25717850c26c9cd0d89d")]; - - for test in tests.iter() { - hash_test(MessageDigest::sha1(), test); - } - } - - #[test] - fn test_sha256() { - let tests = [ - ( - "616263", - "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", - ), - ]; - - for test in tests.iter() { - hash_test(MessageDigest::sha256(), test); - } - } - - #[test] - fn test_ripemd160() { - let tests = [("616263", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc")]; - - for test in tests.iter() { - hash_test(MessageDigest::ripemd160(), test); - } - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/lib.rs cargo-0.26.0/vendor/openssl-0.9.24/src/lib.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,84 +0,0 @@ -#![doc(html_root_url="https://docs.rs/openssl/0.9")] - -#[macro_use] -extern crate bitflags; -#[macro_use] -extern crate foreign_types; -extern crate libc; -#[macro_use] -extern crate lazy_static; -extern crate openssl_sys as ffi; - -#[cfg(test)] -extern crate hex; -#[cfg(test)] -extern crate tempdir; -#[cfg(test)] -extern crate data_encoding; - -#[doc(inline)] -pub use ffi::init; - -use libc::c_int; - -use error::ErrorStack; - -#[macro_use] -mod macros; - -mod bio; -#[macro_use] -mod util; -pub mod aes; -pub mod asn1; -pub mod bn; -#[cfg(not(libressl))] -pub mod cms; -pub mod conf; -pub mod crypto; -pub mod dh; -pub mod dsa; -pub mod ec; -pub mod ec_key; -pub mod error; -pub mod ex_data; -pub mod hash; -pub mod memcmp; -pub mod nid; -pub mod ocsp; -pub mod pkcs12; -pub mod pkcs5; -pub mod pkey; -pub mod rand; -pub mod rsa; -pub mod sign; -pub mod sha; -pub mod ssl; -pub mod stack; -pub mod string; -pub mod symm; -pub mod types; -pub mod version; -pub mod x509; -#[cfg(any(ossl102, ossl110))] -mod verify; - -fn cvt_p(r: *mut T) -> Result<*mut T, ErrorStack> { - if r.is_null() { - Err(ErrorStack::get()) - } else { - Ok(r) - } -} - -fn cvt(r: c_int) -> Result { - if r <= 0 { - Err(ErrorStack::get()) - } else { - Ok(r) - } -} - -fn cvt_n(r: c_int) -> Result { - if r < 0 { Err(ErrorStack::get()) } else { Ok(r) } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/macros.rs cargo-0.26.0/vendor/openssl-0.9.24/src/macros.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/macros.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/macros.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,248 +0,0 @@ - -macro_rules! private_key_from_pem { - ($t:ident, $f:path) => { - from_pem_inner!(/// Deserializes a PEM-formatted private key. - private_key_from_pem, $t, $f); - - /// Deserializes a PEM-formatted private key, using the supplied password if the key is - /// encrypted. - /// - /// # Panics - /// - /// Panics if `passphrase` contains an embedded null. - pub fn private_key_from_pem_passphrase(pem: &[u8], - passphrase: &[u8]) - -> Result<$t, ::error::ErrorStack> { - unsafe { - ffi::init(); - let bio = try!(::bio::MemBioSlice::new(pem)); - let passphrase = ::std::ffi::CString::new(passphrase).unwrap(); - cvt_p($f(bio.as_ptr(), - ptr::null_mut(), - None, - passphrase.as_ptr() as *const _ as *mut _)) - .map($t) - } - } - - /// Deserializes a PEM-formatted private key, using a callback to retrieve a password if the - /// key is encrypted. - /// - /// The callback should copy the password into the provided buffer and return the number of - /// bytes written. - pub fn private_key_from_pem_callback(pem: &[u8], - callback: F) - -> Result<$t, ::error::ErrorStack> - where F: FnOnce(&mut [u8]) -> Result - { - unsafe { - ffi::init(); - let mut cb = ::util::CallbackState::new(callback); - let bio = try!(::bio::MemBioSlice::new(pem)); - cvt_p($f(bio.as_ptr(), - ptr::null_mut(), - Some(::util::invoke_passwd_cb::), - &mut cb as *mut _ as *mut _)) - .map($t) - } - } - } -} - -macro_rules! private_key_to_pem { - ($f:path) => { - /// Serializes the private key to PEM. - pub fn private_key_to_pem(&self) -> Result, ::error::ErrorStack> { - unsafe { - let bio = try!(::bio::MemBio::new()); - try!(cvt($f(bio.as_ptr(), - self.as_ptr(), - ptr::null(), - ptr::null_mut(), - -1, - None, - ptr::null_mut()))); - Ok(bio.get_buf().to_owned()) - } - } - - /// Serializes the private key to PEM, encrypting it with the specified symmetric cipher and - /// passphrase. - pub fn private_key_to_pem_passphrase(&self, - cipher: ::symm::Cipher, - passphrase: &[u8]) - -> Result, ::error::ErrorStack> { - unsafe { - let bio = try!(::bio::MemBio::new()); - assert!(passphrase.len() <= ::libc::c_int::max_value() as usize); - try!(cvt($f(bio.as_ptr(), - self.as_ptr(), - cipher.as_ptr(), - passphrase.as_ptr() as *const _ as *mut _, - passphrase.len() as ::libc::c_int, - None, - ptr::null_mut()))); - Ok(bio.get_buf().to_owned()) - } - } - } -} - -macro_rules! to_pem_inner { - (#[$m:meta] $n:ident, $f:path) => { - #[$m] - pub fn $n(&self) -> Result, ::error::ErrorStack> { - unsafe { - let bio = try!(::bio::MemBio::new()); - try!(cvt($f(bio.as_ptr(), self.as_ptr()))); - Ok(bio.get_buf().to_owned()) - } - } - } -} - -macro_rules! public_key_to_pem { - ($f:path) => { - to_pem_inner!(/// Serializes a public key to PEM. - public_key_to_pem, $f); - } -} - -macro_rules! to_pem { - ($f:path) => { - to_pem_inner!(/// Serializes this value to PEM. - to_pem, $f); - } -} - -macro_rules! to_der_inner { - (#[$m:meta] $n:ident, $f:path) => { - #[$m] - pub fn $n(&self) -> Result, ::error::ErrorStack> { - unsafe { - let len = try!(::cvt($f(::foreign_types::ForeignTypeRef::as_ptr(self), - ptr::null_mut()))); - let mut buf = vec![0; len as usize]; - try!(::cvt($f(::foreign_types::ForeignTypeRef::as_ptr(self), - &mut buf.as_mut_ptr()))); - Ok(buf) - } - } - }; -} - -macro_rules! to_der { - ($f:path) => { - to_der_inner!(/// Serializes this value to DER. - to_der, $f); - } -} - -macro_rules! private_key_to_der { - ($f:path) => { - to_der_inner!(/// Serializes the private key to DER. - private_key_to_der, $f); - } -} - -macro_rules! public_key_to_der { - ($f:path) => { - to_der_inner!(/// Serializes the public key to DER. - public_key_to_der, $f); - } -} - -macro_rules! from_der_inner { - (#[$m:meta] $n:ident, $t:ident, $f:path) => { - #[$m] - pub fn $n(der: &[u8]) -> Result<$t, ::error::ErrorStack> { - unsafe { - ::ffi::init(); - let len = ::std::cmp::min(der.len(), ::libc::c_long::max_value() as usize) as ::libc::c_long; - ::cvt_p($f(::std::ptr::null_mut(), &mut der.as_ptr(), len)) - .map($t) - } - } - } -} - -macro_rules! from_der { - ($t:ident, $f:path) => { - from_der_inner!(/// Deserializes a value from DER-formatted data. - from_der, $t, $f); - } -} - -macro_rules! private_key_from_der { - ($t:ident, $f:path) => { - from_der_inner!(/// Deserializes a private key from DER-formatted data. - private_key_from_der, $t, $f); - } -} - -macro_rules! public_key_from_der { - ($t:ident, $f:path) => { - from_der_inner!(/// Deserializes a public key from DER-formatted data. - public_key_from_der, $t, $f); - } -} - -macro_rules! from_pem_inner { - (#[$m:meta] $n:ident, $t:ident, $f:path) => { - #[$m] - pub fn $n(pem: &[u8]) -> Result<$t, ::error::ErrorStack> { - unsafe { - ::init(); - let bio = try!(::bio::MemBioSlice::new(pem)); - cvt_p($f(bio.as_ptr(), ::std::ptr::null_mut(), None, ::std::ptr::null_mut())) - .map($t) - } - } - } -} - -macro_rules! public_key_from_pem { - ($t:ident, $f:path) => { - from_pem_inner!(/// Deserializes a public key from PEM-formatted data. - public_key_from_pem, $t, $f); - } -} - -macro_rules! from_pem { - ($t:ident, $f:path) => { - from_pem_inner!(/// Deserializes a value from PEM-formatted data. - from_pem, $t, $f); - } -} - - -macro_rules! foreign_type_and_impl_send_sync { - ( - $(#[$impl_attr:meta])* - type CType = $ctype:ty; - fn drop = $drop:expr; - $(fn clone = $clone:expr;)* - - $(#[$owned_attr:meta])* - pub struct $owned:ident; - $(#[$borrowed_attr:meta])* - pub struct $borrowed:ident; - ) - => { - foreign_type! { - $(#[$impl_attr])* - type CType = $ctype; - fn drop = $drop; - $(fn clone = $clone;)* - $(#[$owned_attr])* - pub struct $owned; - $(#[$borrowed_attr])* - pub struct $borrowed; - } - - unsafe impl Send for $owned{} - unsafe impl Send for $borrowed{} - unsafe impl Sync for $owned{} - unsafe impl Sync for $borrowed{} - }; -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/memcmp.rs cargo-0.26.0/vendor/openssl-0.9.24/src/memcmp.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/memcmp.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/memcmp.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,92 +0,0 @@ -//! Utilities to safely compare cryptographic values. -//! -//! Extra care must be taken when comparing values in -//! cryptographic code. If done incorrectly, it can lead -//! to a [timing attack](https://en.wikipedia.org/wiki/Timing_attack). -//! By analyzing the time taken to execute parts of a cryptographic -//! algorithm, and attacker can attempt to compromise the -//! cryptosystem. -//! -//! The utilities in this module are designed to be resistant -//! to this type of attack. -//! -//! # Examples -//! -//! To perform a constant-time comparision of two arrays of the same length but different -//! values: -//! -//! ``` -//! use openssl::memcmp::eq; -//! -//! // We want to compare `a` to `b` and `c`, without giving -//! // away through timing analysis that `c` is more similar to `a` -//! // than `b`. -//! let a = [0, 0, 0]; -//! let b = [1, 1, 1]; -//! let c = [0, 0, 1]; -//! -//! // These statements will execute in the same amount of time. -//! assert!(!eq(&a, &b)); -//! assert!(!eq(&a, &c)); -//! ``` -use libc::size_t; -use ffi; - -/// Returns `true` iff `a` and `b` contain the same bytes. -/// -/// This operation takes an amount of time dependent on the length of the two -/// arrays given, but is independent of the contents of a and b. -/// -/// # Panics -/// -/// This function will panic the current task if `a` and `b` do not have the same -/// length. -/// -/// # Examples -/// -/// To perform a constant-time comparision of two arrays of the same length but different -/// values: -/// -/// ``` -/// use openssl::memcmp::eq; -/// -/// // We want to compare `a` to `b` and `c`, without giving -/// // away through timing analysis that `c` is more similar to `a` -/// // than `b`. -/// let a = [0, 0, 0]; -/// let b = [1, 1, 1]; -/// let c = [0, 0, 1]; -/// -/// // These statements will execute in the same amount of time. -/// assert!(!eq(&a, &b)); -/// assert!(!eq(&a, &c)); -/// ``` -pub fn eq(a: &[u8], b: &[u8]) -> bool { - assert!(a.len() == b.len()); - let ret = unsafe { - ffi::CRYPTO_memcmp( - a.as_ptr() as *const _, - b.as_ptr() as *const _, - a.len() as size_t, - ) - }; - ret == 0 -} - -#[cfg(test)] -mod tests { - use super::eq; - - #[test] - fn test_eq() { - assert!(eq(&[], &[])); - assert!(eq(&[1], &[1])); - assert!(!eq(&[1, 2, 3], &[1, 2, 4])); - } - - #[test] - #[should_panic] - fn test_diff_lens() { - eq(&[], &[1]); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/nid.rs cargo-0.26.0/vendor/openssl-0.9.24/src/nid.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/nid.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/nid.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,982 +0,0 @@ -//! A collection of numerical identifiers for OpenSSL objects. -use ffi; -use libc::c_int; - -/// A numerical identifier for an OpenSSL object. -/// -/// Objects in OpenSSL can have a short name, a long name, and -/// a numerical identifier (NID). For convenience, objects -/// are usually represented in source code using these numeric -/// identifiers. -/// -/// Users should generally not need to create new `Nid`s. -/// -/// # Examples -/// -/// To view the integer representation of a `Nid`: -/// -/// ``` -/// use openssl::nid; -/// -/// assert!(nid::AES_256_GCM.as_raw() == 901); -/// ``` -/// -/// # External Documentation -/// -/// The following documentation provides context about `Nid`s and their usage -/// in OpenSSL. -/// -/// - [Obj_nid2obj](https://www.openssl.org/docs/man1.1.0/crypto/OBJ_create.html) -#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -pub struct Nid(c_int); - -#[allow(non_snake_case)] -impl Nid { - /// Create a `Nid` from an integer representation. - pub fn from_raw(raw: c_int) -> Nid { - Nid(raw) - } - - /// Return the integer representation of a `Nid`. - pub fn as_raw(&self) -> c_int { - self.0 - } -} - -pub const UNDEF: Nid = Nid(ffi::NID_undef); -pub const ITU_T: Nid = Nid(ffi::NID_itu_t); -pub const CCITT: Nid = Nid(ffi::NID_ccitt); -pub const ISO: Nid = Nid(ffi::NID_iso); -pub const JOINT_ISO_ITU_T: Nid = Nid(ffi::NID_joint_iso_itu_t); -pub const JOINT_ISO_CCITT: Nid = Nid(ffi::NID_joint_iso_ccitt); -pub const MEMBER_BODY: Nid = Nid(ffi::NID_member_body); -pub const IDENTIFIED_ORGANIZATION: Nid = Nid(ffi::NID_identified_organization); -pub const HMAC_MD5: Nid = Nid(ffi::NID_hmac_md5); -pub const HMAC_SHA1: Nid = Nid(ffi::NID_hmac_sha1); -pub const CERTICOM_ARC: Nid = Nid(ffi::NID_certicom_arc); -pub const INTERNATIONAL_ORGANIZATIONS: Nid = Nid(ffi::NID_international_organizations); -pub const WAP: Nid = Nid(ffi::NID_wap); -pub const WAP_WSG: Nid = Nid(ffi::NID_wap_wsg); -pub const SELECTED_ATTRIBUTE_TYPES: Nid = Nid(ffi::NID_selected_attribute_types); -pub const CLEARANCE: Nid = Nid(ffi::NID_clearance); -pub const ISO_US: Nid = Nid(ffi::NID_ISO_US); -pub const X9_57: Nid = Nid(ffi::NID_X9_57); -pub const X9CM: Nid = Nid(ffi::NID_X9cm); -pub const DSA: Nid = Nid(ffi::NID_dsa); -pub const DSAWITHSHA1: Nid = Nid(ffi::NID_dsaWithSHA1); -pub const ANSI_X9_62: Nid = Nid(ffi::NID_ansi_X9_62); -pub const X9_62_PRIME_FIELD: Nid = Nid(ffi::NID_X9_62_prime_field); -pub const X9_62_CHARACTERISTIC_TWO_FIELD: Nid = Nid(ffi::NID_X9_62_characteristic_two_field); -pub const X9_62_ID_CHARACTERISTIC_TWO_BASIS: Nid = Nid(ffi::NID_X9_62_id_characteristic_two_basis); -pub const X9_62_ONBASIS: Nid = Nid(ffi::NID_X9_62_onBasis); -pub const X9_62_TPBASIS: Nid = Nid(ffi::NID_X9_62_tpBasis); -pub const X9_62_PPBASIS: Nid = Nid(ffi::NID_X9_62_ppBasis); -pub const X9_62_ID_ECPUBLICKEY: Nid = Nid(ffi::NID_X9_62_id_ecPublicKey); -pub const X9_62_C2PNB163V1: Nid = Nid(ffi::NID_X9_62_c2pnb163v1); -pub const X9_62_C2PNB163V2: Nid = Nid(ffi::NID_X9_62_c2pnb163v2); -pub const X9_62_C2PNB163V3: Nid = Nid(ffi::NID_X9_62_c2pnb163v3); -pub const X9_62_C2PNB176V1: Nid = Nid(ffi::NID_X9_62_c2pnb176v1); -pub const X9_62_C2TNB191V1: Nid = Nid(ffi::NID_X9_62_c2tnb191v1); -pub const X9_62_C2TNB191V2: Nid = Nid(ffi::NID_X9_62_c2tnb191v2); -pub const X9_62_C2TNB191V3: Nid = Nid(ffi::NID_X9_62_c2tnb191v3); -pub const X9_62_C2ONB191V4: Nid = Nid(ffi::NID_X9_62_c2onb191v4); -pub const X9_62_C2ONB191V5: Nid = Nid(ffi::NID_X9_62_c2onb191v5); -pub const X9_62_C2PNB208W1: Nid = Nid(ffi::NID_X9_62_c2pnb208w1); -pub const X9_62_C2TNB239V1: Nid = Nid(ffi::NID_X9_62_c2tnb239v1); -pub const X9_62_C2TNB239V2: Nid = Nid(ffi::NID_X9_62_c2tnb239v2); -pub const X9_62_C2TNB239V3: Nid = Nid(ffi::NID_X9_62_c2tnb239v3); -pub const X9_62_C2ONB239V4: Nid = Nid(ffi::NID_X9_62_c2onb239v4); -pub const X9_62_C2ONB239V5: Nid = Nid(ffi::NID_X9_62_c2onb239v5); -pub const X9_62_C2PNB272W1: Nid = Nid(ffi::NID_X9_62_c2pnb272w1); -pub const X9_62_C2PNB304W1: Nid = Nid(ffi::NID_X9_62_c2pnb304w1); -pub const X9_62_C2TNB359V1: Nid = Nid(ffi::NID_X9_62_c2tnb359v1); -pub const X9_62_C2PNB368W1: Nid = Nid(ffi::NID_X9_62_c2pnb368w1); -pub const X9_62_C2TNB431R1: Nid = Nid(ffi::NID_X9_62_c2tnb431r1); -pub const X9_62_PRIME192V1: Nid = Nid(ffi::NID_X9_62_prime192v1); -pub const X9_62_PRIME192V2: Nid = Nid(ffi::NID_X9_62_prime192v2); -pub const X9_62_PRIME192V3: Nid = Nid(ffi::NID_X9_62_prime192v3); -pub const X9_62_PRIME239V1: Nid = Nid(ffi::NID_X9_62_prime239v1); -pub const X9_62_PRIME239V2: Nid = Nid(ffi::NID_X9_62_prime239v2); -pub const X9_62_PRIME239V3: Nid = Nid(ffi::NID_X9_62_prime239v3); -pub const X9_62_PRIME256V1: Nid = Nid(ffi::NID_X9_62_prime256v1); -pub const ECDSA_WITH_SHA1: Nid = Nid(ffi::NID_ecdsa_with_SHA1); -pub const ECDSA_WITH_RECOMMENDED: Nid = Nid(ffi::NID_ecdsa_with_Recommended); -pub const ECDSA_WITH_SPECIFIED: Nid = Nid(ffi::NID_ecdsa_with_Specified); -pub const ECDSA_WITH_SHA224: Nid = Nid(ffi::NID_ecdsa_with_SHA224); -pub const ECDSA_WITH_SHA256: Nid = Nid(ffi::NID_ecdsa_with_SHA256); -pub const ECDSA_WITH_SHA384: Nid = Nid(ffi::NID_ecdsa_with_SHA384); -pub const ECDSA_WITH_SHA512: Nid = Nid(ffi::NID_ecdsa_with_SHA512); -pub const SECP112R1: Nid = Nid(ffi::NID_secp112r1); -pub const SECP112R2: Nid = Nid(ffi::NID_secp112r2); -pub const SECP128R1: Nid = Nid(ffi::NID_secp128r1); -pub const SECP128R2: Nid = Nid(ffi::NID_secp128r2); -pub const SECP160K1: Nid = Nid(ffi::NID_secp160k1); -pub const SECP160R1: Nid = Nid(ffi::NID_secp160r1); -pub const SECP160R2: Nid = Nid(ffi::NID_secp160r2); -pub const SECP192K1: Nid = Nid(ffi::NID_secp192k1); -pub const SECP224K1: Nid = Nid(ffi::NID_secp224k1); -pub const SECP224R1: Nid = Nid(ffi::NID_secp224r1); -pub const SECP256K1: Nid = Nid(ffi::NID_secp256k1); -pub const SECP384R1: Nid = Nid(ffi::NID_secp384r1); -pub const SECP521R1: Nid = Nid(ffi::NID_secp521r1); -pub const SECT113R1: Nid = Nid(ffi::NID_sect113r1); -pub const SECT113R2: Nid = Nid(ffi::NID_sect113r2); -pub const SECT131R1: Nid = Nid(ffi::NID_sect131r1); -pub const SECT131R2: Nid = Nid(ffi::NID_sect131r2); -pub const SECT163K1: Nid = Nid(ffi::NID_sect163k1); -pub const SECT163R1: Nid = Nid(ffi::NID_sect163r1); -pub const SECT163R2: Nid = Nid(ffi::NID_sect163r2); -pub const SECT193R1: Nid = Nid(ffi::NID_sect193r1); -pub const SECT193R2: Nid = Nid(ffi::NID_sect193r2); -pub const SECT233K1: Nid = Nid(ffi::NID_sect233k1); -pub const SECT233R1: Nid = Nid(ffi::NID_sect233r1); -pub const SECT239K1: Nid = Nid(ffi::NID_sect239k1); -pub const SECT283K1: Nid = Nid(ffi::NID_sect283k1); -pub const SECT283R1: Nid = Nid(ffi::NID_sect283r1); -pub const SECT409K1: Nid = Nid(ffi::NID_sect409k1); -pub const SECT409R1: Nid = Nid(ffi::NID_sect409r1); -pub const SECT571K1: Nid = Nid(ffi::NID_sect571k1); -pub const SECT571R1: Nid = Nid(ffi::NID_sect571r1); -pub const WAP_WSG_IDM_ECID_WTLS1: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls1); -pub const WAP_WSG_IDM_ECID_WTLS3: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls3); -pub const WAP_WSG_IDM_ECID_WTLS4: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls4); -pub const WAP_WSG_IDM_ECID_WTLS5: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls5); -pub const WAP_WSG_IDM_ECID_WTLS6: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls6); -pub const WAP_WSG_IDM_ECID_WTLS7: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls7); -pub const WAP_WSG_IDM_ECID_WTLS8: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls8); -pub const WAP_WSG_IDM_ECID_WTLS9: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls9); -pub const WAP_WSG_IDM_ECID_WTLS10: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls10); -pub const WAP_WSG_IDM_ECID_WTLS11: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls11); -pub const WAP_WSG_IDM_ECID_WTLS12: Nid = Nid(ffi::NID_wap_wsg_idm_ecid_wtls12); -pub const CAST5_CBC: Nid = Nid(ffi::NID_cast5_cbc); -pub const CAST5_ECB: Nid = Nid(ffi::NID_cast5_ecb); -pub const CAST5_CFB64: Nid = Nid(ffi::NID_cast5_cfb64); -pub const CAST5_OFB64: Nid = Nid(ffi::NID_cast5_ofb64); -pub const PBEWITHMD5ANDCAST5_CBC: Nid = Nid(ffi::NID_pbeWithMD5AndCast5_CBC); -pub const ID_PASSWORDBASEDMAC: Nid = Nid(ffi::NID_id_PasswordBasedMAC); -pub const ID_DHBASEDMAC: Nid = Nid(ffi::NID_id_DHBasedMac); -pub const RSADSI: Nid = Nid(ffi::NID_rsadsi); -pub const PKCS: Nid = Nid(ffi::NID_pkcs); -pub const PKCS1: Nid = Nid(ffi::NID_pkcs1); -pub const RSAENCRYPTION: Nid = Nid(ffi::NID_rsaEncryption); -pub const MD2WITHRSAENCRYPTION: Nid = Nid(ffi::NID_md2WithRSAEncryption); -pub const MD4WITHRSAENCRYPTION: Nid = Nid(ffi::NID_md4WithRSAEncryption); -pub const MD5WITHRSAENCRYPTION: Nid = Nid(ffi::NID_md5WithRSAEncryption); -pub const SHA1WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha1WithRSAEncryption); -pub const RSAESOAEP: Nid = Nid(ffi::NID_rsaesOaep); -pub const MGF1: Nid = Nid(ffi::NID_mgf1); -pub const RSASSAPSS: Nid = Nid(ffi::NID_rsassaPss); -pub const SHA256WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha256WithRSAEncryption); -pub const SHA384WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha384WithRSAEncryption); -pub const SHA512WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha512WithRSAEncryption); -pub const SHA224WITHRSAENCRYPTION: Nid = Nid(ffi::NID_sha224WithRSAEncryption); -pub const PKCS3: Nid = Nid(ffi::NID_pkcs3); -pub const DHKEYAGREEMENT: Nid = Nid(ffi::NID_dhKeyAgreement); -pub const PKCS5: Nid = Nid(ffi::NID_pkcs5); -pub const PBEWITHMD2ANDDES_CBC: Nid = Nid(ffi::NID_pbeWithMD2AndDES_CBC); -pub const PBEWITHMD5ANDDES_CBC: Nid = Nid(ffi::NID_pbeWithMD5AndDES_CBC); -pub const PBEWITHMD2ANDRC2_CBC: Nid = Nid(ffi::NID_pbeWithMD2AndRC2_CBC); -pub const PBEWITHMD5ANDRC2_CBC: Nid = Nid(ffi::NID_pbeWithMD5AndRC2_CBC); -pub const PBEWITHSHA1ANDDES_CBC: Nid = Nid(ffi::NID_pbeWithSHA1AndDES_CBC); -pub const PBEWITHSHA1ANDRC2_CBC: Nid = Nid(ffi::NID_pbeWithSHA1AndRC2_CBC); -pub const ID_PBKDF2: Nid = Nid(ffi::NID_id_pbkdf2); -pub const PBES2: Nid = Nid(ffi::NID_pbes2); -pub const PBMAC1: Nid = Nid(ffi::NID_pbmac1); -pub const PKCS7: Nid = Nid(ffi::NID_pkcs7); -pub const PKCS7_DATA: Nid = Nid(ffi::NID_pkcs7_data); -pub const PKCS7_SIGNED: Nid = Nid(ffi::NID_pkcs7_signed); -pub const PKCS7_ENVELOPED: Nid = Nid(ffi::NID_pkcs7_enveloped); -pub const PKCS7_SIGNEDANDENVELOPED: Nid = Nid(ffi::NID_pkcs7_signedAndEnveloped); -pub const PKCS7_DIGEST: Nid = Nid(ffi::NID_pkcs7_digest); -pub const PKCS7_ENCRYPTED: Nid = Nid(ffi::NID_pkcs7_encrypted); -pub const PKCS9: Nid = Nid(ffi::NID_pkcs9); -pub const PKCS9_EMAILADDRESS: Nid = Nid(ffi::NID_pkcs9_emailAddress); -pub const PKCS9_UNSTRUCTUREDNAME: Nid = Nid(ffi::NID_pkcs9_unstructuredName); -pub const PKCS9_CONTENTTYPE: Nid = Nid(ffi::NID_pkcs9_contentType); -pub const PKCS9_MESSAGEDIGEST: Nid = Nid(ffi::NID_pkcs9_messageDigest); -pub const PKCS9_SIGNINGTIME: Nid = Nid(ffi::NID_pkcs9_signingTime); -pub const PKCS9_COUNTERSIGNATURE: Nid = Nid(ffi::NID_pkcs9_countersignature); -pub const PKCS9_CHALLENGEPASSWORD: Nid = Nid(ffi::NID_pkcs9_challengePassword); -pub const PKCS9_UNSTRUCTUREDADDRESS: Nid = Nid(ffi::NID_pkcs9_unstructuredAddress); -pub const PKCS9_EXTCERTATTRIBUTES: Nid = Nid(ffi::NID_pkcs9_extCertAttributes); -pub const EXT_REQ: Nid = Nid(ffi::NID_ext_req); -pub const SMIMECAPABILITIES: Nid = Nid(ffi::NID_SMIMECapabilities); -pub const SMIME: Nid = Nid(ffi::NID_SMIME); -pub const ID_SMIME_MOD: Nid = Nid(ffi::NID_id_smime_mod); -pub const ID_SMIME_CT: Nid = Nid(ffi::NID_id_smime_ct); -pub const ID_SMIME_AA: Nid = Nid(ffi::NID_id_smime_aa); -pub const ID_SMIME_ALG: Nid = Nid(ffi::NID_id_smime_alg); -pub const ID_SMIME_CD: Nid = Nid(ffi::NID_id_smime_cd); -pub const ID_SMIME_SPQ: Nid = Nid(ffi::NID_id_smime_spq); -pub const ID_SMIME_CTI: Nid = Nid(ffi::NID_id_smime_cti); -pub const ID_SMIME_MOD_CMS: Nid = Nid(ffi::NID_id_smime_mod_cms); -pub const ID_SMIME_MOD_ESS: Nid = Nid(ffi::NID_id_smime_mod_ess); -pub const ID_SMIME_MOD_OID: Nid = Nid(ffi::NID_id_smime_mod_oid); -pub const ID_SMIME_MOD_MSG_V3: Nid = Nid(ffi::NID_id_smime_mod_msg_v3); -pub const ID_SMIME_MOD_ETS_ESIGNATURE_88: Nid = Nid(ffi::NID_id_smime_mod_ets_eSignature_88); -pub const ID_SMIME_MOD_ETS_ESIGNATURE_97: Nid = Nid(ffi::NID_id_smime_mod_ets_eSignature_97); -pub const ID_SMIME_MOD_ETS_ESIGPOLICY_88: Nid = Nid(ffi::NID_id_smime_mod_ets_eSigPolicy_88); -pub const ID_SMIME_MOD_ETS_ESIGPOLICY_97: Nid = Nid(ffi::NID_id_smime_mod_ets_eSigPolicy_97); -pub const ID_SMIME_CT_RECEIPT: Nid = Nid(ffi::NID_id_smime_ct_receipt); -pub const ID_SMIME_CT_AUTHDATA: Nid = Nid(ffi::NID_id_smime_ct_authData); -pub const ID_SMIME_CT_PUBLISHCERT: Nid = Nid(ffi::NID_id_smime_ct_publishCert); -pub const ID_SMIME_CT_TSTINFO: Nid = Nid(ffi::NID_id_smime_ct_TSTInfo); -pub const ID_SMIME_CT_TDTINFO: Nid = Nid(ffi::NID_id_smime_ct_TDTInfo); -pub const ID_SMIME_CT_CONTENTINFO: Nid = Nid(ffi::NID_id_smime_ct_contentInfo); -pub const ID_SMIME_CT_DVCSREQUESTDATA: Nid = Nid(ffi::NID_id_smime_ct_DVCSRequestData); -pub const ID_SMIME_CT_DVCSRESPONSEDATA: Nid = Nid(ffi::NID_id_smime_ct_DVCSResponseData); -pub const ID_SMIME_CT_COMPRESSEDDATA: Nid = Nid(ffi::NID_id_smime_ct_compressedData); -pub const ID_CT_ASCIITEXTWITHCRLF: Nid = Nid(ffi::NID_id_ct_asciiTextWithCRLF); -pub const ID_SMIME_AA_RECEIPTREQUEST: Nid = Nid(ffi::NID_id_smime_aa_receiptRequest); -pub const ID_SMIME_AA_SECURITYLABEL: Nid = Nid(ffi::NID_id_smime_aa_securityLabel); -pub const ID_SMIME_AA_MLEXPANDHISTORY: Nid = Nid(ffi::NID_id_smime_aa_mlExpandHistory); -pub const ID_SMIME_AA_CONTENTHINT: Nid = Nid(ffi::NID_id_smime_aa_contentHint); -pub const ID_SMIME_AA_MSGSIGDIGEST: Nid = Nid(ffi::NID_id_smime_aa_msgSigDigest); -pub const ID_SMIME_AA_ENCAPCONTENTTYPE: Nid = Nid(ffi::NID_id_smime_aa_encapContentType); -pub const ID_SMIME_AA_CONTENTIDENTIFIER: Nid = Nid(ffi::NID_id_smime_aa_contentIdentifier); -pub const ID_SMIME_AA_MACVALUE: Nid = Nid(ffi::NID_id_smime_aa_macValue); -pub const ID_SMIME_AA_EQUIVALENTLABELS: Nid = Nid(ffi::NID_id_smime_aa_equivalentLabels); -pub const ID_SMIME_AA_CONTENTREFERENCE: Nid = Nid(ffi::NID_id_smime_aa_contentReference); -pub const ID_SMIME_AA_ENCRYPKEYPREF: Nid = Nid(ffi::NID_id_smime_aa_encrypKeyPref); -pub const ID_SMIME_AA_SIGNINGCERTIFICATE: Nid = Nid(ffi::NID_id_smime_aa_signingCertificate); -pub const ID_SMIME_AA_SMIMEENCRYPTCERTS: Nid = Nid(ffi::NID_id_smime_aa_smimeEncryptCerts); -pub const ID_SMIME_AA_TIMESTAMPTOKEN: Nid = Nid(ffi::NID_id_smime_aa_timeStampToken); -pub const ID_SMIME_AA_ETS_SIGPOLICYID: Nid = Nid(ffi::NID_id_smime_aa_ets_sigPolicyId); -pub const ID_SMIME_AA_ETS_COMMITMENTTYPE: Nid = Nid(ffi::NID_id_smime_aa_ets_commitmentType); -pub const ID_SMIME_AA_ETS_SIGNERLOCATION: Nid = Nid(ffi::NID_id_smime_aa_ets_signerLocation); -pub const ID_SMIME_AA_ETS_SIGNERATTR: Nid = Nid(ffi::NID_id_smime_aa_ets_signerAttr); -pub const ID_SMIME_AA_ETS_OTHERSIGCERT: Nid = Nid(ffi::NID_id_smime_aa_ets_otherSigCert); -pub const ID_SMIME_AA_ETS_CONTENTTIMESTAMP: Nid = Nid(ffi::NID_id_smime_aa_ets_contentTimestamp); -pub const ID_SMIME_AA_ETS_CERTIFICATEREFS: Nid = Nid(ffi::NID_id_smime_aa_ets_CertificateRefs); -pub const ID_SMIME_AA_ETS_REVOCATIONREFS: Nid = Nid(ffi::NID_id_smime_aa_ets_RevocationRefs); -pub const ID_SMIME_AA_ETS_CERTVALUES: Nid = Nid(ffi::NID_id_smime_aa_ets_certValues); -pub const ID_SMIME_AA_ETS_REVOCATIONVALUES: Nid = Nid(ffi::NID_id_smime_aa_ets_revocationValues); -pub const ID_SMIME_AA_ETS_ESCTIMESTAMP: Nid = Nid(ffi::NID_id_smime_aa_ets_escTimeStamp); -pub const ID_SMIME_AA_ETS_CERTCRLTIMESTAMP: Nid = Nid(ffi::NID_id_smime_aa_ets_certCRLTimestamp); -pub const ID_SMIME_AA_ETS_ARCHIVETIMESTAMP: Nid = Nid(ffi::NID_id_smime_aa_ets_archiveTimeStamp); -pub const ID_SMIME_AA_SIGNATURETYPE: Nid = Nid(ffi::NID_id_smime_aa_signatureType); -pub const ID_SMIME_AA_DVCS_DVC: Nid = Nid(ffi::NID_id_smime_aa_dvcs_dvc); -pub const ID_SMIME_ALG_ESDHWITH3DES: Nid = Nid(ffi::NID_id_smime_alg_ESDHwith3DES); -pub const ID_SMIME_ALG_ESDHWITHRC2: Nid = Nid(ffi::NID_id_smime_alg_ESDHwithRC2); -pub const ID_SMIME_ALG_3DESWRAP: Nid = Nid(ffi::NID_id_smime_alg_3DESwrap); -pub const ID_SMIME_ALG_RC2WRAP: Nid = Nid(ffi::NID_id_smime_alg_RC2wrap); -pub const ID_SMIME_ALG_ESDH: Nid = Nid(ffi::NID_id_smime_alg_ESDH); -pub const ID_SMIME_ALG_CMS3DESWRAP: Nid = Nid(ffi::NID_id_smime_alg_CMS3DESwrap); -pub const ID_SMIME_ALG_CMSRC2WRAP: Nid = Nid(ffi::NID_id_smime_alg_CMSRC2wrap); -pub const ID_ALG_PWRI_KEK: Nid = Nid(ffi::NID_id_alg_PWRI_KEK); -pub const ID_SMIME_CD_LDAP: Nid = Nid(ffi::NID_id_smime_cd_ldap); -pub const ID_SMIME_SPQ_ETS_SQT_URI: Nid = Nid(ffi::NID_id_smime_spq_ets_sqt_uri); -pub const ID_SMIME_SPQ_ETS_SQT_UNOTICE: Nid = Nid(ffi::NID_id_smime_spq_ets_sqt_unotice); -pub const ID_SMIME_CTI_ETS_PROOFOFORIGIN: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfOrigin); -pub const ID_SMIME_CTI_ETS_PROOFOFRECEIPT: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfReceipt); -pub const ID_SMIME_CTI_ETS_PROOFOFDELIVERY: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfDelivery); -pub const ID_SMIME_CTI_ETS_PROOFOFSENDER: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfSender); -pub const ID_SMIME_CTI_ETS_PROOFOFAPPROVAL: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfApproval); -pub const ID_SMIME_CTI_ETS_PROOFOFCREATION: Nid = Nid(ffi::NID_id_smime_cti_ets_proofOfCreation); -pub const FRIENDLYNAME: Nid = Nid(ffi::NID_friendlyName); -pub const LOCALKEYID: Nid = Nid(ffi::NID_localKeyID); -pub const MS_CSP_NAME: Nid = Nid(ffi::NID_ms_csp_name); -pub const LOCALKEYSET: Nid = Nid(ffi::NID_LocalKeySet); -pub const X509CERTIFICATE: Nid = Nid(ffi::NID_x509Certificate); -pub const SDSICERTIFICATE: Nid = Nid(ffi::NID_sdsiCertificate); -pub const X509CRL: Nid = Nid(ffi::NID_x509Crl); -pub const PBE_WITHSHA1AND128BITRC4: Nid = Nid(ffi::NID_pbe_WithSHA1And128BitRC4); -pub const PBE_WITHSHA1AND40BITRC4: Nid = Nid(ffi::NID_pbe_WithSHA1And40BitRC4); -pub const PBE_WITHSHA1AND3_KEY_TRIPLEDES_CBC: Nid = - Nid(ffi::NID_pbe_WithSHA1And3_Key_TripleDES_CBC); -pub const PBE_WITHSHA1AND2_KEY_TRIPLEDES_CBC: Nid = - Nid(ffi::NID_pbe_WithSHA1And2_Key_TripleDES_CBC); -pub const PBE_WITHSHA1AND128BITRC2_CBC: Nid = Nid(ffi::NID_pbe_WithSHA1And128BitRC2_CBC); -pub const PBE_WITHSHA1AND40BITRC2_CBC: Nid = Nid(ffi::NID_pbe_WithSHA1And40BitRC2_CBC); -pub const KEYBAG: Nid = Nid(ffi::NID_keyBag); -pub const PKCS8SHROUDEDKEYBAG: Nid = Nid(ffi::NID_pkcs8ShroudedKeyBag); -pub const CERTBAG: Nid = Nid(ffi::NID_certBag); -pub const CRLBAG: Nid = Nid(ffi::NID_crlBag); -pub const SECRETBAG: Nid = Nid(ffi::NID_secretBag); -pub const SAFECONTENTSBAG: Nid = Nid(ffi::NID_safeContentsBag); -pub const MD2: Nid = Nid(ffi::NID_md2); -pub const MD4: Nid = Nid(ffi::NID_md4); -pub const MD5: Nid = Nid(ffi::NID_md5); -pub const MD5_SHA1: Nid = Nid(ffi::NID_md5_sha1); -pub const HMACWITHMD5: Nid = Nid(ffi::NID_hmacWithMD5); -pub const HMACWITHSHA1: Nid = Nid(ffi::NID_hmacWithSHA1); -pub const HMACWITHSHA224: Nid = Nid(ffi::NID_hmacWithSHA224); -pub const HMACWITHSHA256: Nid = Nid(ffi::NID_hmacWithSHA256); -pub const HMACWITHSHA384: Nid = Nid(ffi::NID_hmacWithSHA384); -pub const HMACWITHSHA512: Nid = Nid(ffi::NID_hmacWithSHA512); -pub const RC2_CBC: Nid = Nid(ffi::NID_rc2_cbc); -pub const RC2_ECB: Nid = Nid(ffi::NID_rc2_ecb); -pub const RC2_CFB64: Nid = Nid(ffi::NID_rc2_cfb64); -pub const RC2_OFB64: Nid = Nid(ffi::NID_rc2_ofb64); -pub const RC2_40_CBC: Nid = Nid(ffi::NID_rc2_40_cbc); -pub const RC2_64_CBC: Nid = Nid(ffi::NID_rc2_64_cbc); -pub const RC4: Nid = Nid(ffi::NID_rc4); -pub const RC4_40: Nid = Nid(ffi::NID_rc4_40); -pub const DES_EDE3_CBC: Nid = Nid(ffi::NID_des_ede3_cbc); -pub const RC5_CBC: Nid = Nid(ffi::NID_rc5_cbc); -pub const RC5_ECB: Nid = Nid(ffi::NID_rc5_ecb); -pub const RC5_CFB64: Nid = Nid(ffi::NID_rc5_cfb64); -pub const RC5_OFB64: Nid = Nid(ffi::NID_rc5_ofb64); -pub const MS_EXT_REQ: Nid = Nid(ffi::NID_ms_ext_req); -pub const MS_CODE_IND: Nid = Nid(ffi::NID_ms_code_ind); -pub const MS_CODE_COM: Nid = Nid(ffi::NID_ms_code_com); -pub const MS_CTL_SIGN: Nid = Nid(ffi::NID_ms_ctl_sign); -pub const MS_SGC: Nid = Nid(ffi::NID_ms_sgc); -pub const MS_EFS: Nid = Nid(ffi::NID_ms_efs); -pub const MS_SMARTCARD_LOGIN: Nid = Nid(ffi::NID_ms_smartcard_login); -pub const MS_UPN: Nid = Nid(ffi::NID_ms_upn); -pub const IDEA_CBC: Nid = Nid(ffi::NID_idea_cbc); -pub const IDEA_ECB: Nid = Nid(ffi::NID_idea_ecb); -pub const IDEA_CFB64: Nid = Nid(ffi::NID_idea_cfb64); -pub const IDEA_OFB64: Nid = Nid(ffi::NID_idea_ofb64); -pub const BF_CBC: Nid = Nid(ffi::NID_bf_cbc); -pub const BF_ECB: Nid = Nid(ffi::NID_bf_ecb); -pub const BF_CFB64: Nid = Nid(ffi::NID_bf_cfb64); -pub const BF_OFB64: Nid = Nid(ffi::NID_bf_ofb64); -pub const ID_PKIX: Nid = Nid(ffi::NID_id_pkix); -pub const ID_PKIX_MOD: Nid = Nid(ffi::NID_id_pkix_mod); -pub const ID_PE: Nid = Nid(ffi::NID_id_pe); -pub const ID_QT: Nid = Nid(ffi::NID_id_qt); -pub const ID_KP: Nid = Nid(ffi::NID_id_kp); -pub const ID_IT: Nid = Nid(ffi::NID_id_it); -pub const ID_PKIP: Nid = Nid(ffi::NID_id_pkip); -pub const ID_ALG: Nid = Nid(ffi::NID_id_alg); -pub const ID_CMC: Nid = Nid(ffi::NID_id_cmc); -pub const ID_ON: Nid = Nid(ffi::NID_id_on); -pub const ID_PDA: Nid = Nid(ffi::NID_id_pda); -pub const ID_ACA: Nid = Nid(ffi::NID_id_aca); -pub const ID_QCS: Nid = Nid(ffi::NID_id_qcs); -pub const ID_CCT: Nid = Nid(ffi::NID_id_cct); -pub const ID_PPL: Nid = Nid(ffi::NID_id_ppl); -pub const ID_AD: Nid = Nid(ffi::NID_id_ad); -pub const ID_PKIX1_EXPLICIT_88: Nid = Nid(ffi::NID_id_pkix1_explicit_88); -pub const ID_PKIX1_IMPLICIT_88: Nid = Nid(ffi::NID_id_pkix1_implicit_88); -pub const ID_PKIX1_EXPLICIT_93: Nid = Nid(ffi::NID_id_pkix1_explicit_93); -pub const ID_PKIX1_IMPLICIT_93: Nid = Nid(ffi::NID_id_pkix1_implicit_93); -pub const ID_MOD_CRMF: Nid = Nid(ffi::NID_id_mod_crmf); -pub const ID_MOD_CMC: Nid = Nid(ffi::NID_id_mod_cmc); -pub const ID_MOD_KEA_PROFILE_88: Nid = Nid(ffi::NID_id_mod_kea_profile_88); -pub const ID_MOD_KEA_PROFILE_93: Nid = Nid(ffi::NID_id_mod_kea_profile_93); -pub const ID_MOD_CMP: Nid = Nid(ffi::NID_id_mod_cmp); -pub const ID_MOD_QUALIFIED_CERT_88: Nid = Nid(ffi::NID_id_mod_qualified_cert_88); -pub const ID_MOD_QUALIFIED_CERT_93: Nid = Nid(ffi::NID_id_mod_qualified_cert_93); -pub const ID_MOD_ATTRIBUTE_CERT: Nid = Nid(ffi::NID_id_mod_attribute_cert); -pub const ID_MOD_TIMESTAMP_PROTOCOL: Nid = Nid(ffi::NID_id_mod_timestamp_protocol); -pub const ID_MOD_OCSP: Nid = Nid(ffi::NID_id_mod_ocsp); -pub const ID_MOD_DVCS: Nid = Nid(ffi::NID_id_mod_dvcs); -pub const ID_MOD_CMP2000: Nid = Nid(ffi::NID_id_mod_cmp2000); -pub const INFO_ACCESS: Nid = Nid(ffi::NID_info_access); -pub const BIOMETRICINFO: Nid = Nid(ffi::NID_biometricInfo); -pub const QCSTATEMENTS: Nid = Nid(ffi::NID_qcStatements); -pub const AC_AUDITENTITY: Nid = Nid(ffi::NID_ac_auditEntity); -pub const AC_TARGETING: Nid = Nid(ffi::NID_ac_targeting); -pub const AACONTROLS: Nid = Nid(ffi::NID_aaControls); -pub const SBGP_IPADDRBLOCK: Nid = Nid(ffi::NID_sbgp_ipAddrBlock); -pub const SBGP_AUTONOMOUSSYSNUM: Nid = Nid(ffi::NID_sbgp_autonomousSysNum); -pub const SBGP_ROUTERIDENTIFIER: Nid = Nid(ffi::NID_sbgp_routerIdentifier); -pub const AC_PROXYING: Nid = Nid(ffi::NID_ac_proxying); -pub const SINFO_ACCESS: Nid = Nid(ffi::NID_sinfo_access); -pub const PROXYCERTINFO: Nid = Nid(ffi::NID_proxyCertInfo); -pub const ID_QT_CPS: Nid = Nid(ffi::NID_id_qt_cps); -pub const ID_QT_UNOTICE: Nid = Nid(ffi::NID_id_qt_unotice); -pub const TEXTNOTICE: Nid = Nid(ffi::NID_textNotice); -pub const SERVER_AUTH: Nid = Nid(ffi::NID_server_auth); -pub const CLIENT_AUTH: Nid = Nid(ffi::NID_client_auth); -pub const CODE_SIGN: Nid = Nid(ffi::NID_code_sign); -pub const EMAIL_PROTECT: Nid = Nid(ffi::NID_email_protect); -pub const IPSECENDSYSTEM: Nid = Nid(ffi::NID_ipsecEndSystem); -pub const IPSECTUNNEL: Nid = Nid(ffi::NID_ipsecTunnel); -pub const IPSECUSER: Nid = Nid(ffi::NID_ipsecUser); -pub const TIME_STAMP: Nid = Nid(ffi::NID_time_stamp); -pub const OCSP_SIGN: Nid = Nid(ffi::NID_OCSP_sign); -pub const DVCS: Nid = Nid(ffi::NID_dvcs); -pub const ID_IT_CAPROTENCCERT: Nid = Nid(ffi::NID_id_it_caProtEncCert); -pub const ID_IT_SIGNKEYPAIRTYPES: Nid = Nid(ffi::NID_id_it_signKeyPairTypes); -pub const ID_IT_ENCKEYPAIRTYPES: Nid = Nid(ffi::NID_id_it_encKeyPairTypes); -pub const ID_IT_PREFERREDSYMMALG: Nid = Nid(ffi::NID_id_it_preferredSymmAlg); -pub const ID_IT_CAKEYUPDATEINFO: Nid = Nid(ffi::NID_id_it_caKeyUpdateInfo); -pub const ID_IT_CURRENTCRL: Nid = Nid(ffi::NID_id_it_currentCRL); -pub const ID_IT_UNSUPPORTEDOIDS: Nid = Nid(ffi::NID_id_it_unsupportedOIDs); -pub const ID_IT_SUBSCRIPTIONREQUEST: Nid = Nid(ffi::NID_id_it_subscriptionRequest); -pub const ID_IT_SUBSCRIPTIONRESPONSE: Nid = Nid(ffi::NID_id_it_subscriptionResponse); -pub const ID_IT_KEYPAIRPARAMREQ: Nid = Nid(ffi::NID_id_it_keyPairParamReq); -pub const ID_IT_KEYPAIRPARAMREP: Nid = Nid(ffi::NID_id_it_keyPairParamRep); -pub const ID_IT_REVPASSPHRASE: Nid = Nid(ffi::NID_id_it_revPassphrase); -pub const ID_IT_IMPLICITCONFIRM: Nid = Nid(ffi::NID_id_it_implicitConfirm); -pub const ID_IT_CONFIRMWAITTIME: Nid = Nid(ffi::NID_id_it_confirmWaitTime); -pub const ID_IT_ORIGPKIMESSAGE: Nid = Nid(ffi::NID_id_it_origPKIMessage); -pub const ID_IT_SUPPLANGTAGS: Nid = Nid(ffi::NID_id_it_suppLangTags); -pub const ID_REGCTRL: Nid = Nid(ffi::NID_id_regCtrl); -pub const ID_REGINFO: Nid = Nid(ffi::NID_id_regInfo); -pub const ID_REGCTRL_REGTOKEN: Nid = Nid(ffi::NID_id_regCtrl_regToken); -pub const ID_REGCTRL_AUTHENTICATOR: Nid = Nid(ffi::NID_id_regCtrl_authenticator); -pub const ID_REGCTRL_PKIPUBLICATIONINFO: Nid = Nid(ffi::NID_id_regCtrl_pkiPublicationInfo); -pub const ID_REGCTRL_PKIARCHIVEOPTIONS: Nid = Nid(ffi::NID_id_regCtrl_pkiArchiveOptions); -pub const ID_REGCTRL_OLDCERTID: Nid = Nid(ffi::NID_id_regCtrl_oldCertID); -pub const ID_REGCTRL_PROTOCOLENCRKEY: Nid = Nid(ffi::NID_id_regCtrl_protocolEncrKey); -pub const ID_REGINFO_UTF8PAIRS: Nid = Nid(ffi::NID_id_regInfo_utf8Pairs); -pub const ID_REGINFO_CERTREQ: Nid = Nid(ffi::NID_id_regInfo_certReq); -pub const ID_ALG_DES40: Nid = Nid(ffi::NID_id_alg_des40); -pub const ID_ALG_NOSIGNATURE: Nid = Nid(ffi::NID_id_alg_noSignature); -pub const ID_ALG_DH_SIG_HMAC_SHA1: Nid = Nid(ffi::NID_id_alg_dh_sig_hmac_sha1); -pub const ID_ALG_DH_POP: Nid = Nid(ffi::NID_id_alg_dh_pop); -pub const ID_CMC_STATUSINFO: Nid = Nid(ffi::NID_id_cmc_statusInfo); -pub const ID_CMC_IDENTIFICATION: Nid = Nid(ffi::NID_id_cmc_identification); -pub const ID_CMC_IDENTITYPROOF: Nid = Nid(ffi::NID_id_cmc_identityProof); -pub const ID_CMC_DATARETURN: Nid = Nid(ffi::NID_id_cmc_dataReturn); -pub const ID_CMC_TRANSACTIONID: Nid = Nid(ffi::NID_id_cmc_transactionId); -pub const ID_CMC_SENDERNONCE: Nid = Nid(ffi::NID_id_cmc_senderNonce); -pub const ID_CMC_RECIPIENTNONCE: Nid = Nid(ffi::NID_id_cmc_recipientNonce); -pub const ID_CMC_ADDEXTENSIONS: Nid = Nid(ffi::NID_id_cmc_addExtensions); -pub const ID_CMC_ENCRYPTEDPOP: Nid = Nid(ffi::NID_id_cmc_encryptedPOP); -pub const ID_CMC_DECRYPTEDPOP: Nid = Nid(ffi::NID_id_cmc_decryptedPOP); -pub const ID_CMC_LRAPOPWITNESS: Nid = Nid(ffi::NID_id_cmc_lraPOPWitness); -pub const ID_CMC_GETCERT: Nid = Nid(ffi::NID_id_cmc_getCert); -pub const ID_CMC_GETCRL: Nid = Nid(ffi::NID_id_cmc_getCRL); -pub const ID_CMC_REVOKEREQUEST: Nid = Nid(ffi::NID_id_cmc_revokeRequest); -pub const ID_CMC_REGINFO: Nid = Nid(ffi::NID_id_cmc_regInfo); -pub const ID_CMC_RESPONSEINFO: Nid = Nid(ffi::NID_id_cmc_responseInfo); -pub const ID_CMC_QUERYPENDING: Nid = Nid(ffi::NID_id_cmc_queryPending); -pub const ID_CMC_POPLINKRANDOM: Nid = Nid(ffi::NID_id_cmc_popLinkRandom); -pub const ID_CMC_POPLINKWITNESS: Nid = Nid(ffi::NID_id_cmc_popLinkWitness); -pub const ID_CMC_CONFIRMCERTACCEPTANCE: Nid = Nid(ffi::NID_id_cmc_confirmCertAcceptance); -pub const ID_ON_PERSONALDATA: Nid = Nid(ffi::NID_id_on_personalData); -pub const ID_ON_PERMANENTIDENTIFIER: Nid = Nid(ffi::NID_id_on_permanentIdentifier); -pub const ID_PDA_DATEOFBIRTH: Nid = Nid(ffi::NID_id_pda_dateOfBirth); -pub const ID_PDA_PLACEOFBIRTH: Nid = Nid(ffi::NID_id_pda_placeOfBirth); -pub const ID_PDA_GENDER: Nid = Nid(ffi::NID_id_pda_gender); -pub const ID_PDA_COUNTRYOFCITIZENSHIP: Nid = Nid(ffi::NID_id_pda_countryOfCitizenship); -pub const ID_PDA_COUNTRYOFRESIDENCE: Nid = Nid(ffi::NID_id_pda_countryOfResidence); -pub const ID_ACA_AUTHENTICATIONINFO: Nid = Nid(ffi::NID_id_aca_authenticationInfo); -pub const ID_ACA_ACCESSIDENTITY: Nid = Nid(ffi::NID_id_aca_accessIdentity); -pub const ID_ACA_CHARGINGIDENTITY: Nid = Nid(ffi::NID_id_aca_chargingIdentity); -pub const ID_ACA_GROUP: Nid = Nid(ffi::NID_id_aca_group); -pub const ID_ACA_ROLE: Nid = Nid(ffi::NID_id_aca_role); -pub const ID_ACA_ENCATTRS: Nid = Nid(ffi::NID_id_aca_encAttrs); -pub const ID_QCS_PKIXQCSYNTAX_V1: Nid = Nid(ffi::NID_id_qcs_pkixQCSyntax_v1); -pub const ID_CCT_CRS: Nid = Nid(ffi::NID_id_cct_crs); -pub const ID_CCT_PKIDATA: Nid = Nid(ffi::NID_id_cct_PKIData); -pub const ID_CCT_PKIRESPONSE: Nid = Nid(ffi::NID_id_cct_PKIResponse); -pub const ID_PPL_ANYLANGUAGE: Nid = Nid(ffi::NID_id_ppl_anyLanguage); -pub const ID_PPL_INHERITALL: Nid = Nid(ffi::NID_id_ppl_inheritAll); -pub const INDEPENDENT: Nid = Nid(ffi::NID_Independent); -pub const AD_OCSP: Nid = Nid(ffi::NID_ad_OCSP); -pub const AD_CA_ISSUERS: Nid = Nid(ffi::NID_ad_ca_issuers); -pub const AD_TIMESTAMPING: Nid = Nid(ffi::NID_ad_timeStamping); -pub const AD_DVCS: Nid = Nid(ffi::NID_ad_dvcs); -pub const CAREPOSITORY: Nid = Nid(ffi::NID_caRepository); -pub const ID_PKIX_OCSP_BASIC: Nid = Nid(ffi::NID_id_pkix_OCSP_basic); -pub const ID_PKIX_OCSP_NONCE: Nid = Nid(ffi::NID_id_pkix_OCSP_Nonce); -pub const ID_PKIX_OCSP_CRLID: Nid = Nid(ffi::NID_id_pkix_OCSP_CrlID); -pub const ID_PKIX_OCSP_ACCEPTABLERESPONSES: Nid = Nid(ffi::NID_id_pkix_OCSP_acceptableResponses); -pub const ID_PKIX_OCSP_NOCHECK: Nid = Nid(ffi::NID_id_pkix_OCSP_noCheck); -pub const ID_PKIX_OCSP_ARCHIVECUTOFF: Nid = Nid(ffi::NID_id_pkix_OCSP_archiveCutoff); -pub const ID_PKIX_OCSP_SERVICELOCATOR: Nid = Nid(ffi::NID_id_pkix_OCSP_serviceLocator); -pub const ID_PKIX_OCSP_EXTENDEDSTATUS: Nid = Nid(ffi::NID_id_pkix_OCSP_extendedStatus); -pub const ID_PKIX_OCSP_VALID: Nid = Nid(ffi::NID_id_pkix_OCSP_valid); -pub const ID_PKIX_OCSP_PATH: Nid = Nid(ffi::NID_id_pkix_OCSP_path); -pub const ID_PKIX_OCSP_TRUSTROOT: Nid = Nid(ffi::NID_id_pkix_OCSP_trustRoot); -pub const ALGORITHM: Nid = Nid(ffi::NID_algorithm); -pub const MD5WITHRSA: Nid = Nid(ffi::NID_md5WithRSA); -pub const DES_ECB: Nid = Nid(ffi::NID_des_ecb); -pub const DES_CBC: Nid = Nid(ffi::NID_des_cbc); -pub const DES_OFB64: Nid = Nid(ffi::NID_des_ofb64); -pub const DES_CFB64: Nid = Nid(ffi::NID_des_cfb64); -pub const RSASIGNATURE: Nid = Nid(ffi::NID_rsaSignature); -pub const DSA_2: Nid = Nid(ffi::NID_dsa_2); -pub const DSAWITHSHA: Nid = Nid(ffi::NID_dsaWithSHA); -pub const SHAWITHRSAENCRYPTION: Nid = Nid(ffi::NID_shaWithRSAEncryption); -pub const DES_EDE_ECB: Nid = Nid(ffi::NID_des_ede_ecb); -pub const DES_EDE3_ECB: Nid = Nid(ffi::NID_des_ede3_ecb); -pub const DES_EDE_CBC: Nid = Nid(ffi::NID_des_ede_cbc); -pub const DES_EDE_CFB64: Nid = Nid(ffi::NID_des_ede_cfb64); -pub const DES_EDE3_CFB64: Nid = Nid(ffi::NID_des_ede3_cfb64); -pub const DES_EDE_OFB64: Nid = Nid(ffi::NID_des_ede_ofb64); -pub const DES_EDE3_OFB64: Nid = Nid(ffi::NID_des_ede3_ofb64); -pub const DESX_CBC: Nid = Nid(ffi::NID_desx_cbc); -pub const SHA: Nid = Nid(ffi::NID_sha); -pub const SHA1: Nid = Nid(ffi::NID_sha1); -pub const DSAWITHSHA1_2: Nid = Nid(ffi::NID_dsaWithSHA1_2); -pub const SHA1WITHRSA: Nid = Nid(ffi::NID_sha1WithRSA); -pub const RIPEMD160: Nid = Nid(ffi::NID_ripemd160); -pub const RIPEMD160WITHRSA: Nid = Nid(ffi::NID_ripemd160WithRSA); -pub const SXNET: Nid = Nid(ffi::NID_sxnet); -pub const X500: Nid = Nid(ffi::NID_X500); -pub const X509: Nid = Nid(ffi::NID_X509); -pub const COMMONNAME: Nid = Nid(ffi::NID_commonName); -pub const SURNAME: Nid = Nid(ffi::NID_surname); -pub const SERIALNUMBER: Nid = Nid(ffi::NID_serialNumber); -pub const COUNTRYNAME: Nid = Nid(ffi::NID_countryName); -pub const LOCALITYNAME: Nid = Nid(ffi::NID_localityName); -pub const STATEORPROVINCENAME: Nid = Nid(ffi::NID_stateOrProvinceName); -pub const STREETADDRESS: Nid = Nid(ffi::NID_streetAddress); -pub const ORGANIZATIONNAME: Nid = Nid(ffi::NID_organizationName); -pub const ORGANIZATIONALUNITNAME: Nid = Nid(ffi::NID_organizationalUnitName); -pub const TITLE: Nid = Nid(ffi::NID_title); -pub const DESCRIPTION: Nid = Nid(ffi::NID_description); -pub const SEARCHGUIDE: Nid = Nid(ffi::NID_searchGuide); -pub const BUSINESSCATEGORY: Nid = Nid(ffi::NID_businessCategory); -pub const POSTALADDRESS: Nid = Nid(ffi::NID_postalAddress); -pub const POSTALCODE: Nid = Nid(ffi::NID_postalCode); -pub const POSTOFFICEBOX: Nid = Nid(ffi::NID_postOfficeBox); -pub const PHYSICALDELIVERYOFFICENAME: Nid = Nid(ffi::NID_physicalDeliveryOfficeName); -pub const TELEPHONENUMBER: Nid = Nid(ffi::NID_telephoneNumber); -pub const TELEXNUMBER: Nid = Nid(ffi::NID_telexNumber); -pub const TELETEXTERMINALIDENTIFIER: Nid = Nid(ffi::NID_teletexTerminalIdentifier); -pub const FACSIMILETELEPHONENUMBER: Nid = Nid(ffi::NID_facsimileTelephoneNumber); -pub const X121ADDRESS: Nid = Nid(ffi::NID_x121Address); -pub const INTERNATIONALISDNNUMBER: Nid = Nid(ffi::NID_internationaliSDNNumber); -pub const REGISTEREDADDRESS: Nid = Nid(ffi::NID_registeredAddress); -pub const DESTINATIONINDICATOR: Nid = Nid(ffi::NID_destinationIndicator); -pub const PREFERREDDELIVERYMETHOD: Nid = Nid(ffi::NID_preferredDeliveryMethod); -pub const PRESENTATIONADDRESS: Nid = Nid(ffi::NID_presentationAddress); -pub const SUPPORTEDAPPLICATIONCONTEXT: Nid = Nid(ffi::NID_supportedApplicationContext); -pub const MEMBER: Nid = Nid(ffi::NID_member); -pub const OWNER: Nid = Nid(ffi::NID_owner); -pub const ROLEOCCUPANT: Nid = Nid(ffi::NID_roleOccupant); -pub const SEEALSO: Nid = Nid(ffi::NID_seeAlso); -pub const USERPASSWORD: Nid = Nid(ffi::NID_userPassword); -pub const USERCERTIFICATE: Nid = Nid(ffi::NID_userCertificate); -pub const CACERTIFICATE: Nid = Nid(ffi::NID_cACertificate); -pub const AUTHORITYREVOCATIONLIST: Nid = Nid(ffi::NID_authorityRevocationList); -pub const CERTIFICATEREVOCATIONLIST: Nid = Nid(ffi::NID_certificateRevocationList); -pub const CROSSCERTIFICATEPAIR: Nid = Nid(ffi::NID_crossCertificatePair); -pub const NAME: Nid = Nid(ffi::NID_name); -pub const GIVENNAME: Nid = Nid(ffi::NID_givenName); -pub const INITIALS: Nid = Nid(ffi::NID_initials); -pub const GENERATIONQUALIFIER: Nid = Nid(ffi::NID_generationQualifier); -pub const X500UNIQUEIDENTIFIER: Nid = Nid(ffi::NID_x500UniqueIdentifier); -pub const DNQUALIFIER: Nid = Nid(ffi::NID_dnQualifier); -pub const ENHANCEDSEARCHGUIDE: Nid = Nid(ffi::NID_enhancedSearchGuide); -pub const PROTOCOLINFORMATION: Nid = Nid(ffi::NID_protocolInformation); -pub const DISTINGUISHEDNAME: Nid = Nid(ffi::NID_distinguishedName); -pub const UNIQUEMEMBER: Nid = Nid(ffi::NID_uniqueMember); -pub const HOUSEIDENTIFIER: Nid = Nid(ffi::NID_houseIdentifier); -pub const SUPPORTEDALGORITHMS: Nid = Nid(ffi::NID_supportedAlgorithms); -pub const DELTAREVOCATIONLIST: Nid = Nid(ffi::NID_deltaRevocationList); -pub const DMDNAME: Nid = Nid(ffi::NID_dmdName); -pub const PSEUDONYM: Nid = Nid(ffi::NID_pseudonym); -pub const ROLE: Nid = Nid(ffi::NID_role); -pub const X500ALGORITHMS: Nid = Nid(ffi::NID_X500algorithms); -pub const RSA: Nid = Nid(ffi::NID_rsa); -pub const MDC2WITHRSA: Nid = Nid(ffi::NID_mdc2WithRSA); -pub const MDC2: Nid = Nid(ffi::NID_mdc2); -pub const ID_CE: Nid = Nid(ffi::NID_id_ce); -pub const SUBJECT_DIRECTORY_ATTRIBUTES: Nid = Nid(ffi::NID_subject_directory_attributes); -pub const SUBJECT_KEY_IDENTIFIER: Nid = Nid(ffi::NID_subject_key_identifier); -pub const KEY_USAGE: Nid = Nid(ffi::NID_key_usage); -pub const PRIVATE_KEY_USAGE_PERIOD: Nid = Nid(ffi::NID_private_key_usage_period); -pub const SUBJECT_ALT_NAME: Nid = Nid(ffi::NID_subject_alt_name); -pub const ISSUER_ALT_NAME: Nid = Nid(ffi::NID_issuer_alt_name); -pub const BASIC_CONSTRAINTS: Nid = Nid(ffi::NID_basic_constraints); -pub const CRL_NUMBER: Nid = Nid(ffi::NID_crl_number); -pub const CRL_REASON: Nid = Nid(ffi::NID_crl_reason); -pub const INVALIDITY_DATE: Nid = Nid(ffi::NID_invalidity_date); -pub const DELTA_CRL: Nid = Nid(ffi::NID_delta_crl); -pub const ISSUING_DISTRIBUTION_POINT: Nid = Nid(ffi::NID_issuing_distribution_point); -pub const CERTIFICATE_ISSUER: Nid = Nid(ffi::NID_certificate_issuer); -pub const NAME_CONSTRAINTS: Nid = Nid(ffi::NID_name_constraints); -pub const CRL_DISTRIBUTION_POINTS: Nid = Nid(ffi::NID_crl_distribution_points); -pub const CERTIFICATE_POLICIES: Nid = Nid(ffi::NID_certificate_policies); -pub const ANY_POLICY: Nid = Nid(ffi::NID_any_policy); -pub const POLICY_MAPPINGS: Nid = Nid(ffi::NID_policy_mappings); -pub const AUTHORITY_KEY_IDENTIFIER: Nid = Nid(ffi::NID_authority_key_identifier); -pub const POLICY_CONSTRAINTS: Nid = Nid(ffi::NID_policy_constraints); -pub const EXT_KEY_USAGE: Nid = Nid(ffi::NID_ext_key_usage); -pub const FRESHEST_CRL: Nid = Nid(ffi::NID_freshest_crl); -pub const INHIBIT_ANY_POLICY: Nid = Nid(ffi::NID_inhibit_any_policy); -pub const TARGET_INFORMATION: Nid = Nid(ffi::NID_target_information); -pub const NO_REV_AVAIL: Nid = Nid(ffi::NID_no_rev_avail); -pub const ANYEXTENDEDKEYUSAGE: Nid = Nid(ffi::NID_anyExtendedKeyUsage); -pub const NETSCAPE: Nid = Nid(ffi::NID_netscape); -pub const NETSCAPE_CERT_EXTENSION: Nid = Nid(ffi::NID_netscape_cert_extension); -pub const NETSCAPE_DATA_TYPE: Nid = Nid(ffi::NID_netscape_data_type); -pub const NETSCAPE_CERT_TYPE: Nid = Nid(ffi::NID_netscape_cert_type); -pub const NETSCAPE_BASE_URL: Nid = Nid(ffi::NID_netscape_base_url); -pub const NETSCAPE_REVOCATION_URL: Nid = Nid(ffi::NID_netscape_revocation_url); -pub const NETSCAPE_CA_REVOCATION_URL: Nid = Nid(ffi::NID_netscape_ca_revocation_url); -pub const NETSCAPE_RENEWAL_URL: Nid = Nid(ffi::NID_netscape_renewal_url); -pub const NETSCAPE_CA_POLICY_URL: Nid = Nid(ffi::NID_netscape_ca_policy_url); -pub const NETSCAPE_SSL_SERVER_NAME: Nid = Nid(ffi::NID_netscape_ssl_server_name); -pub const NETSCAPE_COMMENT: Nid = Nid(ffi::NID_netscape_comment); -pub const NETSCAPE_CERT_SEQUENCE: Nid = Nid(ffi::NID_netscape_cert_sequence); -pub const NS_SGC: Nid = Nid(ffi::NID_ns_sgc); -pub const ORG: Nid = Nid(ffi::NID_org); -pub const DOD: Nid = Nid(ffi::NID_dod); -pub const IANA: Nid = Nid(ffi::NID_iana); -pub const DIRECTORY: Nid = Nid(ffi::NID_Directory); -pub const MANAGEMENT: Nid = Nid(ffi::NID_Management); -pub const EXPERIMENTAL: Nid = Nid(ffi::NID_Experimental); -pub const PRIVATE: Nid = Nid(ffi::NID_Private); -pub const SECURITY: Nid = Nid(ffi::NID_Security); -pub const SNMPV2: Nid = Nid(ffi::NID_SNMPv2); -pub const MAIL: Nid = Nid(ffi::NID_Mail); -pub const ENTERPRISES: Nid = Nid(ffi::NID_Enterprises); -pub const DCOBJECT: Nid = Nid(ffi::NID_dcObject); -pub const MIME_MHS: Nid = Nid(ffi::NID_mime_mhs); -pub const MIME_MHS_HEADINGS: Nid = Nid(ffi::NID_mime_mhs_headings); -pub const MIME_MHS_BODIES: Nid = Nid(ffi::NID_mime_mhs_bodies); -pub const ID_HEX_PARTIAL_MESSAGE: Nid = Nid(ffi::NID_id_hex_partial_message); -pub const ID_HEX_MULTIPART_MESSAGE: Nid = Nid(ffi::NID_id_hex_multipart_message); -pub const ZLIB_COMPRESSION: Nid = Nid(ffi::NID_zlib_compression); -pub const AES_128_ECB: Nid = Nid(ffi::NID_aes_128_ecb); -pub const AES_128_CBC: Nid = Nid(ffi::NID_aes_128_cbc); -pub const AES_128_OFB128: Nid = Nid(ffi::NID_aes_128_ofb128); -pub const AES_128_CFB128: Nid = Nid(ffi::NID_aes_128_cfb128); -pub const ID_AES128_WRAP: Nid = Nid(ffi::NID_id_aes128_wrap); -pub const AES_128_GCM: Nid = Nid(ffi::NID_aes_128_gcm); -pub const AES_128_CCM: Nid = Nid(ffi::NID_aes_128_ccm); -pub const ID_AES128_WRAP_PAD: Nid = Nid(ffi::NID_id_aes128_wrap_pad); -pub const AES_192_ECB: Nid = Nid(ffi::NID_aes_192_ecb); -pub const AES_192_CBC: Nid = Nid(ffi::NID_aes_192_cbc); -pub const AES_192_OFB128: Nid = Nid(ffi::NID_aes_192_ofb128); -pub const AES_192_CFB128: Nid = Nid(ffi::NID_aes_192_cfb128); -pub const ID_AES192_WRAP: Nid = Nid(ffi::NID_id_aes192_wrap); -pub const AES_192_GCM: Nid = Nid(ffi::NID_aes_192_gcm); -pub const AES_192_CCM: Nid = Nid(ffi::NID_aes_192_ccm); -pub const ID_AES192_WRAP_PAD: Nid = Nid(ffi::NID_id_aes192_wrap_pad); -pub const AES_256_ECB: Nid = Nid(ffi::NID_aes_256_ecb); -pub const AES_256_CBC: Nid = Nid(ffi::NID_aes_256_cbc); -pub const AES_256_OFB128: Nid = Nid(ffi::NID_aes_256_ofb128); -pub const AES_256_CFB128: Nid = Nid(ffi::NID_aes_256_cfb128); -pub const ID_AES256_WRAP: Nid = Nid(ffi::NID_id_aes256_wrap); -pub const AES_256_GCM: Nid = Nid(ffi::NID_aes_256_gcm); -pub const AES_256_CCM: Nid = Nid(ffi::NID_aes_256_ccm); -pub const ID_AES256_WRAP_PAD: Nid = Nid(ffi::NID_id_aes256_wrap_pad); -pub const AES_128_CFB1: Nid = Nid(ffi::NID_aes_128_cfb1); -pub const AES_192_CFB1: Nid = Nid(ffi::NID_aes_192_cfb1); -pub const AES_256_CFB1: Nid = Nid(ffi::NID_aes_256_cfb1); -pub const AES_128_CFB8: Nid = Nid(ffi::NID_aes_128_cfb8); -pub const AES_192_CFB8: Nid = Nid(ffi::NID_aes_192_cfb8); -pub const AES_256_CFB8: Nid = Nid(ffi::NID_aes_256_cfb8); -pub const AES_128_CTR: Nid = Nid(ffi::NID_aes_128_ctr); -pub const AES_192_CTR: Nid = Nid(ffi::NID_aes_192_ctr); -pub const AES_256_CTR: Nid = Nid(ffi::NID_aes_256_ctr); -pub const AES_128_XTS: Nid = Nid(ffi::NID_aes_128_xts); -pub const AES_256_XTS: Nid = Nid(ffi::NID_aes_256_xts); -pub const DES_CFB1: Nid = Nid(ffi::NID_des_cfb1); -pub const DES_CFB8: Nid = Nid(ffi::NID_des_cfb8); -pub const DES_EDE3_CFB1: Nid = Nid(ffi::NID_des_ede3_cfb1); -pub const DES_EDE3_CFB8: Nid = Nid(ffi::NID_des_ede3_cfb8); -pub const SHA256: Nid = Nid(ffi::NID_sha256); -pub const SHA384: Nid = Nid(ffi::NID_sha384); -pub const SHA512: Nid = Nid(ffi::NID_sha512); -pub const SHA224: Nid = Nid(ffi::NID_sha224); -pub const DSA_WITH_SHA224: Nid = Nid(ffi::NID_dsa_with_SHA224); -pub const DSA_WITH_SHA256: Nid = Nid(ffi::NID_dsa_with_SHA256); -pub const HOLD_INSTRUCTION_CODE: Nid = Nid(ffi::NID_hold_instruction_code); -pub const HOLD_INSTRUCTION_NONE: Nid = Nid(ffi::NID_hold_instruction_none); -pub const HOLD_INSTRUCTION_CALL_ISSUER: Nid = Nid(ffi::NID_hold_instruction_call_issuer); -pub const HOLD_INSTRUCTION_REJECT: Nid = Nid(ffi::NID_hold_instruction_reject); -pub const DATA: Nid = Nid(ffi::NID_data); -pub const PSS: Nid = Nid(ffi::NID_pss); -pub const UCL: Nid = Nid(ffi::NID_ucl); -pub const PILOT: Nid = Nid(ffi::NID_pilot); -pub const PILOTATTRIBUTETYPE: Nid = Nid(ffi::NID_pilotAttributeType); -pub const PILOTATTRIBUTESYNTAX: Nid = Nid(ffi::NID_pilotAttributeSyntax); -pub const PILOTOBJECTCLASS: Nid = Nid(ffi::NID_pilotObjectClass); -pub const PILOTGROUPS: Nid = Nid(ffi::NID_pilotGroups); -pub const IA5STRINGSYNTAX: Nid = Nid(ffi::NID_iA5StringSyntax); -pub const CASEIGNOREIA5STRINGSYNTAX: Nid = Nid(ffi::NID_caseIgnoreIA5StringSyntax); -pub const PILOTOBJECT: Nid = Nid(ffi::NID_pilotObject); -pub const PILOTPERSON: Nid = Nid(ffi::NID_pilotPerson); -pub const ACCOUNT: Nid = Nid(ffi::NID_account); -pub const DOCUMENT: Nid = Nid(ffi::NID_document); -pub const ROOM: Nid = Nid(ffi::NID_room); -pub const DOCUMENTSERIES: Nid = Nid(ffi::NID_documentSeries); -pub const DOMAIN: Nid = Nid(ffi::NID_Domain); -pub const RFC822LOCALPART: Nid = Nid(ffi::NID_rFC822localPart); -pub const DNSDOMAIN: Nid = Nid(ffi::NID_dNSDomain); -pub const DOMAINRELATEDOBJECT: Nid = Nid(ffi::NID_domainRelatedObject); -pub const FRIENDLYCOUNTRY: Nid = Nid(ffi::NID_friendlyCountry); -pub const SIMPLESECURITYOBJECT: Nid = Nid(ffi::NID_simpleSecurityObject); -pub const PILOTORGANIZATION: Nid = Nid(ffi::NID_pilotOrganization); -pub const PILOTDSA: Nid = Nid(ffi::NID_pilotDSA); -pub const QUALITYLABELLEDDATA: Nid = Nid(ffi::NID_qualityLabelledData); -pub const USERID: Nid = Nid(ffi::NID_userId); -pub const TEXTENCODEDORADDRESS: Nid = Nid(ffi::NID_textEncodedORAddress); -pub const RFC822MAILBOX: Nid = Nid(ffi::NID_rfc822Mailbox); -pub const INFO: Nid = Nid(ffi::NID_info); -pub const FAVOURITEDRINK: Nid = Nid(ffi::NID_favouriteDrink); -pub const ROOMNUMBER: Nid = Nid(ffi::NID_roomNumber); -pub const PHOTO: Nid = Nid(ffi::NID_photo); -pub const USERCLASS: Nid = Nid(ffi::NID_userClass); -pub const HOST: Nid = Nid(ffi::NID_host); -pub const MANAGER: Nid = Nid(ffi::NID_manager); -pub const DOCUMENTIDENTIFIER: Nid = Nid(ffi::NID_documentIdentifier); -pub const DOCUMENTTITLE: Nid = Nid(ffi::NID_documentTitle); -pub const DOCUMENTVERSION: Nid = Nid(ffi::NID_documentVersion); -pub const DOCUMENTAUTHOR: Nid = Nid(ffi::NID_documentAuthor); -pub const DOCUMENTLOCATION: Nid = Nid(ffi::NID_documentLocation); -pub const HOMETELEPHONENUMBER: Nid = Nid(ffi::NID_homeTelephoneNumber); -pub const SECRETARY: Nid = Nid(ffi::NID_secretary); -pub const OTHERMAILBOX: Nid = Nid(ffi::NID_otherMailbox); -pub const LASTMODIFIEDTIME: Nid = Nid(ffi::NID_lastModifiedTime); -pub const LASTMODIFIEDBY: Nid = Nid(ffi::NID_lastModifiedBy); -pub const DOMAINCOMPONENT: Nid = Nid(ffi::NID_domainComponent); -pub const ARECORD: Nid = Nid(ffi::NID_aRecord); -pub const PILOTATTRIBUTETYPE27: Nid = Nid(ffi::NID_pilotAttributeType27); -pub const MXRECORD: Nid = Nid(ffi::NID_mXRecord); -pub const NSRECORD: Nid = Nid(ffi::NID_nSRecord); -pub const SOARECORD: Nid = Nid(ffi::NID_sOARecord); -pub const CNAMERECORD: Nid = Nid(ffi::NID_cNAMERecord); -pub const ASSOCIATEDDOMAIN: Nid = Nid(ffi::NID_associatedDomain); -pub const ASSOCIATEDNAME: Nid = Nid(ffi::NID_associatedName); -pub const HOMEPOSTALADDRESS: Nid = Nid(ffi::NID_homePostalAddress); -pub const PERSONALTITLE: Nid = Nid(ffi::NID_personalTitle); -pub const MOBILETELEPHONENUMBER: Nid = Nid(ffi::NID_mobileTelephoneNumber); -pub const PAGERTELEPHONENUMBER: Nid = Nid(ffi::NID_pagerTelephoneNumber); -pub const FRIENDLYCOUNTRYNAME: Nid = Nid(ffi::NID_friendlyCountryName); -pub const ORGANIZATIONALSTATUS: Nid = Nid(ffi::NID_organizationalStatus); -pub const JANETMAILBOX: Nid = Nid(ffi::NID_janetMailbox); -pub const MAILPREFERENCEOPTION: Nid = Nid(ffi::NID_mailPreferenceOption); -pub const BUILDINGNAME: Nid = Nid(ffi::NID_buildingName); -pub const DSAQUALITY: Nid = Nid(ffi::NID_dSAQuality); -pub const SINGLELEVELQUALITY: Nid = Nid(ffi::NID_singleLevelQuality); -pub const SUBTREEMINIMUMQUALITY: Nid = Nid(ffi::NID_subtreeMinimumQuality); -pub const SUBTREEMAXIMUMQUALITY: Nid = Nid(ffi::NID_subtreeMaximumQuality); -pub const PERSONALSIGNATURE: Nid = Nid(ffi::NID_personalSignature); -pub const DITREDIRECT: Nid = Nid(ffi::NID_dITRedirect); -pub const AUDIO: Nid = Nid(ffi::NID_audio); -pub const DOCUMENTPUBLISHER: Nid = Nid(ffi::NID_documentPublisher); -pub const ID_SET: Nid = Nid(ffi::NID_id_set); -pub const SET_CTYPE: Nid = Nid(ffi::NID_set_ctype); -pub const SET_MSGEXT: Nid = Nid(ffi::NID_set_msgExt); -pub const SET_ATTR: Nid = Nid(ffi::NID_set_attr); -pub const SET_POLICY: Nid = Nid(ffi::NID_set_policy); -pub const SET_CERTEXT: Nid = Nid(ffi::NID_set_certExt); -pub const SET_BRAND: Nid = Nid(ffi::NID_set_brand); -pub const SETCT_PANDATA: Nid = Nid(ffi::NID_setct_PANData); -pub const SETCT_PANTOKEN: Nid = Nid(ffi::NID_setct_PANToken); -pub const SETCT_PANONLY: Nid = Nid(ffi::NID_setct_PANOnly); -pub const SETCT_OIDATA: Nid = Nid(ffi::NID_setct_OIData); -pub const SETCT_PI: Nid = Nid(ffi::NID_setct_PI); -pub const SETCT_PIDATA: Nid = Nid(ffi::NID_setct_PIData); -pub const SETCT_PIDATAUNSIGNED: Nid = Nid(ffi::NID_setct_PIDataUnsigned); -pub const SETCT_HODINPUT: Nid = Nid(ffi::NID_setct_HODInput); -pub const SETCT_AUTHRESBAGGAGE: Nid = Nid(ffi::NID_setct_AuthResBaggage); -pub const SETCT_AUTHREVREQBAGGAGE: Nid = Nid(ffi::NID_setct_AuthRevReqBaggage); -pub const SETCT_AUTHREVRESBAGGAGE: Nid = Nid(ffi::NID_setct_AuthRevResBaggage); -pub const SETCT_CAPTOKENSEQ: Nid = Nid(ffi::NID_setct_CapTokenSeq); -pub const SETCT_PINITRESDATA: Nid = Nid(ffi::NID_setct_PInitResData); -pub const SETCT_PI_TBS: Nid = Nid(ffi::NID_setct_PI_TBS); -pub const SETCT_PRESDATA: Nid = Nid(ffi::NID_setct_PResData); -pub const SETCT_AUTHREQTBS: Nid = Nid(ffi::NID_setct_AuthReqTBS); -pub const SETCT_AUTHRESTBS: Nid = Nid(ffi::NID_setct_AuthResTBS); -pub const SETCT_AUTHRESTBSX: Nid = Nid(ffi::NID_setct_AuthResTBSX); -pub const SETCT_AUTHTOKENTBS: Nid = Nid(ffi::NID_setct_AuthTokenTBS); -pub const SETCT_CAPTOKENDATA: Nid = Nid(ffi::NID_setct_CapTokenData); -pub const SETCT_CAPTOKENTBS: Nid = Nid(ffi::NID_setct_CapTokenTBS); -pub const SETCT_ACQCARDCODEMSG: Nid = Nid(ffi::NID_setct_AcqCardCodeMsg); -pub const SETCT_AUTHREVREQTBS: Nid = Nid(ffi::NID_setct_AuthRevReqTBS); -pub const SETCT_AUTHREVRESDATA: Nid = Nid(ffi::NID_setct_AuthRevResData); -pub const SETCT_AUTHREVRESTBS: Nid = Nid(ffi::NID_setct_AuthRevResTBS); -pub const SETCT_CAPREQTBS: Nid = Nid(ffi::NID_setct_CapReqTBS); -pub const SETCT_CAPREQTBSX: Nid = Nid(ffi::NID_setct_CapReqTBSX); -pub const SETCT_CAPRESDATA: Nid = Nid(ffi::NID_setct_CapResData); -pub const SETCT_CAPREVREQTBS: Nid = Nid(ffi::NID_setct_CapRevReqTBS); -pub const SETCT_CAPREVREQTBSX: Nid = Nid(ffi::NID_setct_CapRevReqTBSX); -pub const SETCT_CAPREVRESDATA: Nid = Nid(ffi::NID_setct_CapRevResData); -pub const SETCT_CREDREQTBS: Nid = Nid(ffi::NID_setct_CredReqTBS); -pub const SETCT_CREDREQTBSX: Nid = Nid(ffi::NID_setct_CredReqTBSX); -pub const SETCT_CREDRESDATA: Nid = Nid(ffi::NID_setct_CredResData); -pub const SETCT_CREDREVREQTBS: Nid = Nid(ffi::NID_setct_CredRevReqTBS); -pub const SETCT_CREDREVREQTBSX: Nid = Nid(ffi::NID_setct_CredRevReqTBSX); -pub const SETCT_CREDREVRESDATA: Nid = Nid(ffi::NID_setct_CredRevResData); -pub const SETCT_PCERTREQDATA: Nid = Nid(ffi::NID_setct_PCertReqData); -pub const SETCT_PCERTRESTBS: Nid = Nid(ffi::NID_setct_PCertResTBS); -pub const SETCT_BATCHADMINREQDATA: Nid = Nid(ffi::NID_setct_BatchAdminReqData); -pub const SETCT_BATCHADMINRESDATA: Nid = Nid(ffi::NID_setct_BatchAdminResData); -pub const SETCT_CARDCINITRESTBS: Nid = Nid(ffi::NID_setct_CardCInitResTBS); -pub const SETCT_MEAQCINITRESTBS: Nid = Nid(ffi::NID_setct_MeAqCInitResTBS); -pub const SETCT_REGFORMRESTBS: Nid = Nid(ffi::NID_setct_RegFormResTBS); -pub const SETCT_CERTREQDATA: Nid = Nid(ffi::NID_setct_CertReqData); -pub const SETCT_CERTREQTBS: Nid = Nid(ffi::NID_setct_CertReqTBS); -pub const SETCT_CERTRESDATA: Nid = Nid(ffi::NID_setct_CertResData); -pub const SETCT_CERTINQREQTBS: Nid = Nid(ffi::NID_setct_CertInqReqTBS); -pub const SETCT_ERRORTBS: Nid = Nid(ffi::NID_setct_ErrorTBS); -pub const SETCT_PIDUALSIGNEDTBE: Nid = Nid(ffi::NID_setct_PIDualSignedTBE); -pub const SETCT_PIUNSIGNEDTBE: Nid = Nid(ffi::NID_setct_PIUnsignedTBE); -pub const SETCT_AUTHREQTBE: Nid = Nid(ffi::NID_setct_AuthReqTBE); -pub const SETCT_AUTHRESTBE: Nid = Nid(ffi::NID_setct_AuthResTBE); -pub const SETCT_AUTHRESTBEX: Nid = Nid(ffi::NID_setct_AuthResTBEX); -pub const SETCT_AUTHTOKENTBE: Nid = Nid(ffi::NID_setct_AuthTokenTBE); -pub const SETCT_CAPTOKENTBE: Nid = Nid(ffi::NID_setct_CapTokenTBE); -pub const SETCT_CAPTOKENTBEX: Nid = Nid(ffi::NID_setct_CapTokenTBEX); -pub const SETCT_ACQCARDCODEMSGTBE: Nid = Nid(ffi::NID_setct_AcqCardCodeMsgTBE); -pub const SETCT_AUTHREVREQTBE: Nid = Nid(ffi::NID_setct_AuthRevReqTBE); -pub const SETCT_AUTHREVRESTBE: Nid = Nid(ffi::NID_setct_AuthRevResTBE); -pub const SETCT_AUTHREVRESTBEB: Nid = Nid(ffi::NID_setct_AuthRevResTBEB); -pub const SETCT_CAPREQTBE: Nid = Nid(ffi::NID_setct_CapReqTBE); -pub const SETCT_CAPREQTBEX: Nid = Nid(ffi::NID_setct_CapReqTBEX); -pub const SETCT_CAPRESTBE: Nid = Nid(ffi::NID_setct_CapResTBE); -pub const SETCT_CAPREVREQTBE: Nid = Nid(ffi::NID_setct_CapRevReqTBE); -pub const SETCT_CAPREVREQTBEX: Nid = Nid(ffi::NID_setct_CapRevReqTBEX); -pub const SETCT_CAPREVRESTBE: Nid = Nid(ffi::NID_setct_CapRevResTBE); -pub const SETCT_CREDREQTBE: Nid = Nid(ffi::NID_setct_CredReqTBE); -pub const SETCT_CREDREQTBEX: Nid = Nid(ffi::NID_setct_CredReqTBEX); -pub const SETCT_CREDRESTBE: Nid = Nid(ffi::NID_setct_CredResTBE); -pub const SETCT_CREDREVREQTBE: Nid = Nid(ffi::NID_setct_CredRevReqTBE); -pub const SETCT_CREDREVREQTBEX: Nid = Nid(ffi::NID_setct_CredRevReqTBEX); -pub const SETCT_CREDREVRESTBE: Nid = Nid(ffi::NID_setct_CredRevResTBE); -pub const SETCT_BATCHADMINREQTBE: Nid = Nid(ffi::NID_setct_BatchAdminReqTBE); -pub const SETCT_BATCHADMINRESTBE: Nid = Nid(ffi::NID_setct_BatchAdminResTBE); -pub const SETCT_REGFORMREQTBE: Nid = Nid(ffi::NID_setct_RegFormReqTBE); -pub const SETCT_CERTREQTBE: Nid = Nid(ffi::NID_setct_CertReqTBE); -pub const SETCT_CERTREQTBEX: Nid = Nid(ffi::NID_setct_CertReqTBEX); -pub const SETCT_CERTRESTBE: Nid = Nid(ffi::NID_setct_CertResTBE); -pub const SETCT_CRLNOTIFICATIONTBS: Nid = Nid(ffi::NID_setct_CRLNotificationTBS); -pub const SETCT_CRLNOTIFICATIONRESTBS: Nid = Nid(ffi::NID_setct_CRLNotificationResTBS); -pub const SETCT_BCIDISTRIBUTIONTBS: Nid = Nid(ffi::NID_setct_BCIDistributionTBS); -pub const SETEXT_GENCRYPT: Nid = Nid(ffi::NID_setext_genCrypt); -pub const SETEXT_MIAUTH: Nid = Nid(ffi::NID_setext_miAuth); -pub const SETEXT_PINSECURE: Nid = Nid(ffi::NID_setext_pinSecure); -pub const SETEXT_PINANY: Nid = Nid(ffi::NID_setext_pinAny); -pub const SETEXT_TRACK2: Nid = Nid(ffi::NID_setext_track2); -pub const SETEXT_CV: Nid = Nid(ffi::NID_setext_cv); -pub const SET_POLICY_ROOT: Nid = Nid(ffi::NID_set_policy_root); -pub const SETCEXT_HASHEDROOT: Nid = Nid(ffi::NID_setCext_hashedRoot); -pub const SETCEXT_CERTTYPE: Nid = Nid(ffi::NID_setCext_certType); -pub const SETCEXT_MERCHDATA: Nid = Nid(ffi::NID_setCext_merchData); -pub const SETCEXT_CCERTREQUIRED: Nid = Nid(ffi::NID_setCext_cCertRequired); -pub const SETCEXT_TUNNELING: Nid = Nid(ffi::NID_setCext_tunneling); -pub const SETCEXT_SETEXT: Nid = Nid(ffi::NID_setCext_setExt); -pub const SETCEXT_SETQUALF: Nid = Nid(ffi::NID_setCext_setQualf); -pub const SETCEXT_PGWYCAPABILITIES: Nid = Nid(ffi::NID_setCext_PGWYcapabilities); -pub const SETCEXT_TOKENIDENTIFIER: Nid = Nid(ffi::NID_setCext_TokenIdentifier); -pub const SETCEXT_TRACK2DATA: Nid = Nid(ffi::NID_setCext_Track2Data); -pub const SETCEXT_TOKENTYPE: Nid = Nid(ffi::NID_setCext_TokenType); -pub const SETCEXT_ISSUERCAPABILITIES: Nid = Nid(ffi::NID_setCext_IssuerCapabilities); -pub const SETATTR_CERT: Nid = Nid(ffi::NID_setAttr_Cert); -pub const SETATTR_PGWYCAP: Nid = Nid(ffi::NID_setAttr_PGWYcap); -pub const SETATTR_TOKENTYPE: Nid = Nid(ffi::NID_setAttr_TokenType); -pub const SETATTR_ISSCAP: Nid = Nid(ffi::NID_setAttr_IssCap); -pub const SET_ROOTKEYTHUMB: Nid = Nid(ffi::NID_set_rootKeyThumb); -pub const SET_ADDPOLICY: Nid = Nid(ffi::NID_set_addPolicy); -pub const SETATTR_TOKEN_EMV: Nid = Nid(ffi::NID_setAttr_Token_EMV); -pub const SETATTR_TOKEN_B0PRIME: Nid = Nid(ffi::NID_setAttr_Token_B0Prime); -pub const SETATTR_ISSCAP_CVM: Nid = Nid(ffi::NID_setAttr_IssCap_CVM); -pub const SETATTR_ISSCAP_T2: Nid = Nid(ffi::NID_setAttr_IssCap_T2); -pub const SETATTR_ISSCAP_SIG: Nid = Nid(ffi::NID_setAttr_IssCap_Sig); -pub const SETATTR_GENCRYPTGRM: Nid = Nid(ffi::NID_setAttr_GenCryptgrm); -pub const SETATTR_T2ENC: Nid = Nid(ffi::NID_setAttr_T2Enc); -pub const SETATTR_T2CLEARTXT: Nid = Nid(ffi::NID_setAttr_T2cleartxt); -pub const SETATTR_TOKICCSIG: Nid = Nid(ffi::NID_setAttr_TokICCsig); -pub const SETATTR_SECDEVSIG: Nid = Nid(ffi::NID_setAttr_SecDevSig); -pub const SET_BRAND_IATA_ATA: Nid = Nid(ffi::NID_set_brand_IATA_ATA); -pub const SET_BRAND_DINERS: Nid = Nid(ffi::NID_set_brand_Diners); -pub const SET_BRAND_AMERICANEXPRESS: Nid = Nid(ffi::NID_set_brand_AmericanExpress); -pub const SET_BRAND_JCB: Nid = Nid(ffi::NID_set_brand_JCB); -pub const SET_BRAND_VISA: Nid = Nid(ffi::NID_set_brand_Visa); -pub const SET_BRAND_MASTERCARD: Nid = Nid(ffi::NID_set_brand_MasterCard); -pub const SET_BRAND_NOVUS: Nid = Nid(ffi::NID_set_brand_Novus); -pub const DES_CDMF: Nid = Nid(ffi::NID_des_cdmf); -pub const RSAOAEPENCRYPTIONSET: Nid = Nid(ffi::NID_rsaOAEPEncryptionSET); -pub const IPSEC3: Nid = Nid(ffi::NID_ipsec3); -pub const IPSEC4: Nid = Nid(ffi::NID_ipsec4); -pub const WHIRLPOOL: Nid = Nid(ffi::NID_whirlpool); -pub const CRYPTOPRO: Nid = Nid(ffi::NID_cryptopro); -pub const CRYPTOCOM: Nid = Nid(ffi::NID_cryptocom); -pub const ID_GOSTR3411_94_WITH_GOSTR3410_2001: Nid = - Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001); -pub const ID_GOSTR3411_94_WITH_GOSTR3410_94: Nid = Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94); -pub const ID_GOSTR3411_94: Nid = Nid(ffi::NID_id_GostR3411_94); -pub const ID_HMACGOSTR3411_94: Nid = Nid(ffi::NID_id_HMACGostR3411_94); -pub const ID_GOSTR3410_2001: Nid = Nid(ffi::NID_id_GostR3410_2001); -pub const ID_GOSTR3410_94: Nid = Nid(ffi::NID_id_GostR3410_94); -pub const ID_GOST28147_89: Nid = Nid(ffi::NID_id_Gost28147_89); -pub const GOST89_CNT: Nid = Nid(ffi::NID_gost89_cnt); -pub const ID_GOST28147_89_MAC: Nid = Nid(ffi::NID_id_Gost28147_89_MAC); -pub const ID_GOSTR3411_94_PRF: Nid = Nid(ffi::NID_id_GostR3411_94_prf); -pub const ID_GOSTR3410_2001DH: Nid = Nid(ffi::NID_id_GostR3410_2001DH); -pub const ID_GOSTR3410_94DH: Nid = Nid(ffi::NID_id_GostR3410_94DH); -pub const ID_GOST28147_89_CRYPTOPRO_KEYMESHING: Nid = - Nid(ffi::NID_id_Gost28147_89_CryptoPro_KeyMeshing); -pub const ID_GOST28147_89_NONE_KEYMESHING: Nid = Nid(ffi::NID_id_Gost28147_89_None_KeyMeshing); -pub const ID_GOSTR3411_94_TESTPARAMSET: Nid = Nid(ffi::NID_id_GostR3411_94_TestParamSet); -pub const ID_GOSTR3411_94_CRYPTOPROPARAMSET: Nid = Nid(ffi::NID_id_GostR3411_94_CryptoProParamSet); -pub const ID_GOST28147_89_TESTPARAMSET: Nid = Nid(ffi::NID_id_Gost28147_89_TestParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_A_PARAMSET: Nid = - Nid(ffi::NID_id_Gost28147_89_CryptoPro_A_ParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_B_PARAMSET: Nid = - Nid(ffi::NID_id_Gost28147_89_CryptoPro_B_ParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_C_PARAMSET: Nid = - Nid(ffi::NID_id_Gost28147_89_CryptoPro_C_ParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_D_PARAMSET: Nid = - Nid(ffi::NID_id_Gost28147_89_CryptoPro_D_ParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_OSCAR_1_1_PARAMSET: Nid = - Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_OSCAR_1_0_PARAMSET: Nid = - Nid(ffi::NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet); -pub const ID_GOST28147_89_CRYPTOPRO_RIC_1_PARAMSET: Nid = - Nid(ffi::NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet); -pub const ID_GOSTR3410_94_TESTPARAMSET: Nid = Nid(ffi::NID_id_GostR3410_94_TestParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_A_PARAMSET: Nid = - Nid(ffi::NID_id_GostR3410_94_CryptoPro_A_ParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_B_PARAMSET: Nid = - Nid(ffi::NID_id_GostR3410_94_CryptoPro_B_ParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_C_PARAMSET: Nid = - Nid(ffi::NID_id_GostR3410_94_CryptoPro_C_ParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_D_PARAMSET: Nid = - Nid(ffi::NID_id_GostR3410_94_CryptoPro_D_ParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_XCHA_PARAMSET: Nid = - Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchA_ParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_XCHB_PARAMSET: Nid = - Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchB_ParamSet); -pub const ID_GOSTR3410_94_CRYPTOPRO_XCHC_PARAMSET: Nid = - Nid(ffi::NID_id_GostR3410_94_CryptoPro_XchC_ParamSet); -pub const ID_GOSTR3410_2001_TESTPARAMSET: Nid = Nid(ffi::NID_id_GostR3410_2001_TestParamSet); -pub const ID_GOSTR3410_2001_CRYPTOPRO_A_PARAMSET: Nid = - Nid(ffi::NID_id_GostR3410_2001_CryptoPro_A_ParamSet); -pub const ID_GOSTR3410_2001_CRYPTOPRO_B_PARAMSET: Nid = - Nid(ffi::NID_id_GostR3410_2001_CryptoPro_B_ParamSet); -pub const ID_GOSTR3410_2001_CRYPTOPRO_C_PARAMSET: Nid = - Nid(ffi::NID_id_GostR3410_2001_CryptoPro_C_ParamSet); -pub const ID_GOSTR3410_2001_CRYPTOPRO_XCHA_PARAMSET: Nid = - Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet); -pub const ID_GOSTR3410_2001_CRYPTOPRO_XCHB_PARAMSET: Nid = - Nid(ffi::NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet); -pub const ID_GOSTR3410_94_A: Nid = Nid(ffi::NID_id_GostR3410_94_a); -pub const ID_GOSTR3410_94_ABIS: Nid = Nid(ffi::NID_id_GostR3410_94_aBis); -pub const ID_GOSTR3410_94_B: Nid = Nid(ffi::NID_id_GostR3410_94_b); -pub const ID_GOSTR3410_94_BBIS: Nid = Nid(ffi::NID_id_GostR3410_94_bBis); -pub const ID_GOST28147_89_CC: Nid = Nid(ffi::NID_id_Gost28147_89_cc); -pub const ID_GOSTR3410_94_CC: Nid = Nid(ffi::NID_id_GostR3410_94_cc); -pub const ID_GOSTR3410_2001_CC: Nid = Nid(ffi::NID_id_GostR3410_2001_cc); -pub const ID_GOSTR3411_94_WITH_GOSTR3410_94_CC: Nid = - Nid(ffi::NID_id_GostR3411_94_with_GostR3410_94_cc); -pub const ID_GOSTR3411_94_WITH_GOSTR3410_2001_CC: Nid = - Nid(ffi::NID_id_GostR3411_94_with_GostR3410_2001_cc); -pub const ID_GOSTR3410_2001_PARAMSET_CC: Nid = Nid(ffi::NID_id_GostR3410_2001_ParamSet_cc); -pub const CAMELLIA_128_CBC: Nid = Nid(ffi::NID_camellia_128_cbc); -pub const CAMELLIA_192_CBC: Nid = Nid(ffi::NID_camellia_192_cbc); -pub const CAMELLIA_256_CBC: Nid = Nid(ffi::NID_camellia_256_cbc); -pub const ID_CAMELLIA128_WRAP: Nid = Nid(ffi::NID_id_camellia128_wrap); -pub const ID_CAMELLIA192_WRAP: Nid = Nid(ffi::NID_id_camellia192_wrap); -pub const ID_CAMELLIA256_WRAP: Nid = Nid(ffi::NID_id_camellia256_wrap); -pub const CAMELLIA_128_ECB: Nid = Nid(ffi::NID_camellia_128_ecb); -pub const CAMELLIA_128_OFB128: Nid = Nid(ffi::NID_camellia_128_ofb128); -pub const CAMELLIA_128_CFB128: Nid = Nid(ffi::NID_camellia_128_cfb128); -pub const CAMELLIA_192_ECB: Nid = Nid(ffi::NID_camellia_192_ecb); -pub const CAMELLIA_192_OFB128: Nid = Nid(ffi::NID_camellia_192_ofb128); -pub const CAMELLIA_192_CFB128: Nid = Nid(ffi::NID_camellia_192_cfb128); -pub const CAMELLIA_256_ECB: Nid = Nid(ffi::NID_camellia_256_ecb); -pub const CAMELLIA_256_OFB128: Nid = Nid(ffi::NID_camellia_256_ofb128); -pub const CAMELLIA_256_CFB128: Nid = Nid(ffi::NID_camellia_256_cfb128); -pub const CAMELLIA_128_CFB1: Nid = Nid(ffi::NID_camellia_128_cfb1); -pub const CAMELLIA_192_CFB1: Nid = Nid(ffi::NID_camellia_192_cfb1); -pub const CAMELLIA_256_CFB1: Nid = Nid(ffi::NID_camellia_256_cfb1); -pub const CAMELLIA_128_CFB8: Nid = Nid(ffi::NID_camellia_128_cfb8); -pub const CAMELLIA_192_CFB8: Nid = Nid(ffi::NID_camellia_192_cfb8); -pub const CAMELLIA_256_CFB8: Nid = Nid(ffi::NID_camellia_256_cfb8); -pub const KISA: Nid = Nid(ffi::NID_kisa); -pub const SEED_ECB: Nid = Nid(ffi::NID_seed_ecb); -pub const SEED_CBC: Nid = Nid(ffi::NID_seed_cbc); -pub const SEED_CFB128: Nid = Nid(ffi::NID_seed_cfb128); -pub const SEED_OFB128: Nid = Nid(ffi::NID_seed_ofb128); -pub const HMAC: Nid = Nid(ffi::NID_hmac); -pub const CMAC: Nid = Nid(ffi::NID_cmac); -pub const RC4_HMAC_MD5: Nid = Nid(ffi::NID_rc4_hmac_md5); -pub const AES_128_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_128_cbc_hmac_sha1); -pub const AES_192_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_192_cbc_hmac_sha1); -pub const AES_256_CBC_HMAC_SHA1: Nid = Nid(ffi::NID_aes_256_cbc_hmac_sha1); diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/ocsp.rs cargo-0.26.0/vendor/openssl-0.9.24/src/ocsp.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/ocsp.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/ocsp.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,314 +0,0 @@ -use ffi; -use foreign_types::ForeignTypeRef; -use libc::{c_int, c_long, c_ulong}; -use std::ptr; -use std::mem; - -use {cvt, cvt_p}; -use asn1::Asn1GeneralizedTimeRef; -use error::ErrorStack; -use hash::MessageDigest; -use stack::StackRef; -use x509::store::X509StoreRef; -use x509::{X509, X509Ref}; - -bitflags! { - pub struct Flag: c_ulong { - const FLAG_NO_CERTS = ffi::OCSP_NOCERTS; - const FLAG_NO_INTERN = ffi::OCSP_NOINTERN; - const FLAG_NO_CHAIN = ffi::OCSP_NOCHAIN; - const FLAG_NO_VERIFY = ffi::OCSP_NOVERIFY; - const FLAG_NO_EXPLICIT = ffi::OCSP_NOEXPLICIT; - const FLAG_NO_CA_SIGN = ffi::OCSP_NOCASIGN; - const FLAG_NO_DELEGATED = ffi::OCSP_NODELEGATED; - const FLAG_NO_CHECKS = ffi::OCSP_NOCHECKS; - const FLAG_TRUST_OTHER = ffi::OCSP_TRUSTOTHER; - const FLAG_RESPID_KEY = ffi::OCSP_RESPID_KEY; - const FLAG_NO_TIME = ffi::OCSP_NOTIME; - } -} - -pub const RESPONSE_STATUS_SUCCESSFUL: OcspResponseStatus = - OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_SUCCESSFUL); -pub const RESPONSE_STATUS_MALFORMED_REQUEST: OcspResponseStatus = - OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_MALFORMEDREQUEST); -pub const RESPONSE_STATUS_INTERNAL_ERROR: OcspResponseStatus = - OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_INTERNALERROR); -pub const RESPONSE_STATUS_TRY_LATER: OcspResponseStatus = - OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_TRYLATER); -pub const RESPONSE_STATUS_SIG_REQUIRED: OcspResponseStatus = - OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_SIGREQUIRED); -pub const RESPONSE_STATUS_UNAUTHORIZED: OcspResponseStatus = - OcspResponseStatus(ffi::OCSP_RESPONSE_STATUS_UNAUTHORIZED); - -pub const CERT_STATUS_GOOD: OcspCertStatus = OcspCertStatus(ffi::V_OCSP_CERTSTATUS_GOOD); -pub const CERT_STATUS_REVOKED: OcspCertStatus = OcspCertStatus(ffi::V_OCSP_CERTSTATUS_REVOKED); -pub const CERT_STATUS_UNKNOWN: OcspCertStatus = OcspCertStatus(ffi::V_OCSP_CERTSTATUS_UNKNOWN); - -pub const REVOKED_STATUS_NO_STATUS: OcspRevokedStatus = - OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_NOSTATUS); -pub const REVOKED_STATUS_UNSPECIFIED: OcspRevokedStatus = - OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_UNSPECIFIED); -pub const REVOKED_STATUS_KEY_COMPROMISE: OcspRevokedStatus = - OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_KEYCOMPROMISE); -pub const REVOKED_STATUS_CA_COMPROMISE: OcspRevokedStatus = - OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_CACOMPROMISE); -pub const REVOKED_STATUS_AFFILIATION_CHANGED: OcspRevokedStatus = - OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_AFFILIATIONCHANGED); -pub const REVOKED_STATUS_SUPERSEDED: OcspRevokedStatus = - OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_SUPERSEDED); -pub const REVOKED_STATUS_CESSATION_OF_OPERATION: OcspRevokedStatus = - OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_CESSATIONOFOPERATION); -pub const REVOKED_STATUS_CERTIFICATE_HOLD: OcspRevokedStatus = - OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_CERTIFICATEHOLD); -pub const REVOKED_STATUS_REMOVE_FROM_CRL: OcspRevokedStatus = - OcspRevokedStatus(ffi::OCSP_REVOKED_STATUS_REMOVEFROMCRL); - -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub struct OcspResponseStatus(c_int); - -impl OcspResponseStatus { - pub fn from_raw(raw: c_int) -> OcspResponseStatus { - OcspResponseStatus(raw) - } - - pub fn as_raw(&self) -> c_int { - self.0 - } -} - -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub struct OcspCertStatus(c_int); - -impl OcspCertStatus { - pub fn from_raw(raw: c_int) -> OcspCertStatus { - OcspCertStatus(raw) - } - - pub fn as_raw(&self) -> c_int { - self.0 - } -} - -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub struct OcspRevokedStatus(c_int); - -impl OcspRevokedStatus { - pub fn from_raw(raw: c_int) -> OcspRevokedStatus { - OcspRevokedStatus(raw) - } - - pub fn as_raw(&self) -> c_int { - self.0 - } -} - -pub struct Status<'a> { - /// The overall status of the response. - pub status: OcspCertStatus, - /// If `status` is `CERT_STATUS_REVOKED`, the reason for the revocation. - pub reason: OcspRevokedStatus, - /// If `status` is `CERT_STATUS_REVOKED`, the time at which the certificate was revoked. - pub revocation_time: Option<&'a Asn1GeneralizedTimeRef>, - /// The time that this revocation check was performed. - pub this_update: &'a Asn1GeneralizedTimeRef, - /// The time at which this revocation check expires. - pub next_update: &'a Asn1GeneralizedTimeRef, -} - -impl<'a> Status<'a> { - /// Checks validity of the `this_update` and `next_update` fields. - /// - /// The `nsec` parameter specifies an amount of slack time that will be used when comparing - /// those times with the current time to account for delays and clock skew. - /// - /// The `maxsec` parameter limits the maximum age of the `this_update` parameter to prohibit - /// very old responses. - pub fn check_validity(&self, nsec: u32, maxsec: Option) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::OCSP_check_validity( - self.this_update.as_ptr(), - self.next_update.as_ptr(), - nsec as c_long, - maxsec.map(|n| n as c_long).unwrap_or(-1), - )).map(|_| ()) - } - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::OCSP_BASICRESP; - fn drop = ffi::OCSP_BASICRESP_free; - - pub struct OcspBasicResponse; - pub struct OcspBasicResponseRef; -} - -impl OcspBasicResponseRef { - /// Verifies the validity of the response. - /// - /// The `certs` parameter contains a set of certificates that will be searched when locating the - /// OCSP response signing certificate. Some responders do not include this in the response. - pub fn verify( - &self, - certs: &StackRef, - store: &X509StoreRef, - flags: Flag, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::OCSP_basic_verify( - self.as_ptr(), - certs.as_ptr(), - store.as_ptr(), - flags.bits(), - )).map(|_| ()) - } - } - - /// Looks up the status for the specified certificate ID. - pub fn find_status<'a>(&'a self, id: &OcspCertIdRef) -> Option> { - unsafe { - let mut status = ffi::V_OCSP_CERTSTATUS_UNKNOWN; - let mut reason = ffi::OCSP_REVOKED_STATUS_NOSTATUS; - let mut revocation_time = ptr::null_mut(); - let mut this_update = ptr::null_mut(); - let mut next_update = ptr::null_mut(); - - let r = ffi::OCSP_resp_find_status( - self.as_ptr(), - id.as_ptr(), - &mut status, - &mut reason, - &mut revocation_time, - &mut this_update, - &mut next_update, - ); - if r == 1 { - let revocation_time = if revocation_time.is_null() { - None - } else { - Some(Asn1GeneralizedTimeRef::from_ptr(revocation_time)) - }; - Some(Status { - status: OcspCertStatus(status), - reason: OcspRevokedStatus(status), - revocation_time: revocation_time, - this_update: Asn1GeneralizedTimeRef::from_ptr(this_update), - next_update: Asn1GeneralizedTimeRef::from_ptr(next_update), - }) - } else { - None - } - } - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::OCSP_CERTID; - fn drop = ffi::OCSP_CERTID_free; - - pub struct OcspCertId; - pub struct OcspCertIdRef; -} - -impl OcspCertId { - /// Constructs a certificate ID for certificate `subject`. - pub fn from_cert( - digest: MessageDigest, - subject: &X509Ref, - issuer: &X509Ref, - ) -> Result { - unsafe { - cvt_p(ffi::OCSP_cert_to_id( - digest.as_ptr(), - subject.as_ptr(), - issuer.as_ptr(), - )).map(OcspCertId) - } - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::OCSP_RESPONSE; - fn drop = ffi::OCSP_RESPONSE_free; - - pub struct OcspResponse; - pub struct OcspResponseRef; -} - -impl OcspResponse { - /// Creates an OCSP response from the status and optional body. - /// - /// A body should only be provided if `status` is `RESPONSE_STATUS_SUCCESSFUL`. - pub fn create( - status: OcspResponseStatus, - body: Option<&OcspBasicResponseRef>, - ) -> Result { - unsafe { - ffi::init(); - - cvt_p(ffi::OCSP_response_create( - status.as_raw(), - body.map(|r| r.as_ptr()).unwrap_or(ptr::null_mut()), - )).map(OcspResponse) - } - } - - from_der!(OcspResponse, ffi::d2i_OCSP_RESPONSE); -} - -impl OcspResponseRef { - to_der!(ffi::i2d_OCSP_RESPONSE); - - /// Returns the status of the response. - pub fn status(&self) -> OcspResponseStatus { - unsafe { OcspResponseStatus(ffi::OCSP_response_status(self.as_ptr())) } - } - - /// Returns the basic response. - /// - /// This will only succeed if `status()` returns `RESPONSE_STATUS_SUCCESSFUL`. - pub fn basic(&self) -> Result { - unsafe { cvt_p(ffi::OCSP_response_get1_basic(self.as_ptr())).map(OcspBasicResponse) } - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::OCSP_REQUEST; - fn drop = ffi::OCSP_REQUEST_free; - - pub struct OcspRequest; - pub struct OcspRequestRef; -} - -impl OcspRequest { - pub fn new() -> Result { - unsafe { - ffi::init(); - - cvt_p(ffi::OCSP_REQUEST_new()).map(OcspRequest) - } - } - - from_der!(OcspRequest, ffi::d2i_OCSP_REQUEST); -} - -impl OcspRequestRef { - to_der!(ffi::i2d_OCSP_REQUEST); - - pub fn add_id(&mut self, id: OcspCertId) -> Result<&mut OcspOneReqRef, ErrorStack> { - unsafe { - let ptr = cvt_p(ffi::OCSP_request_add0_id(self.as_ptr(), id.as_ptr()))?; - mem::forget(id); - Ok(OcspOneReqRef::from_ptr_mut(ptr)) - } - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::OCSP_ONEREQ; - fn drop = ffi::OCSP_ONEREQ_free; - - pub struct OcspOneReq; - pub struct OcspOneReqRef; -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/pkcs12.rs cargo-0.26.0/vendor/openssl-0.9.24/src/pkcs12.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/pkcs12.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/pkcs12.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,276 +0,0 @@ -//! PKCS #12 archives. - -use ffi; -use foreign_types::{ForeignType, ForeignTypeRef}; -use libc::c_int; -use std::ptr; -use std::ffi::CString; - -use {cvt, cvt_p}; -use pkey::{PKey, PKeyRef}; -use error::ErrorStack; -use x509::X509; -use stack::Stack; -use nid; - -foreign_type_and_impl_send_sync! { - type CType = ffi::PKCS12; - fn drop = ffi::PKCS12_free; - - pub struct Pkcs12; - pub struct Pkcs12Ref; -} - -impl Pkcs12Ref { - to_der!(ffi::i2d_PKCS12); - - /// Extracts the contents of the `Pkcs12`. - // FIXME should take an &[u8] - pub fn parse(&self, pass: &str) -> Result { - unsafe { - let pass = CString::new(pass).unwrap(); - - let mut pkey = ptr::null_mut(); - let mut cert = ptr::null_mut(); - let mut chain = ptr::null_mut(); - - cvt(ffi::PKCS12_parse( - self.as_ptr(), - pass.as_ptr(), - &mut pkey, - &mut cert, - &mut chain, - ))?; - - let pkey = PKey::from_ptr(pkey); - let cert = X509::from_ptr(cert); - - let chain = if chain.is_null() { - Stack::new()? - } else { - Stack::from_ptr(chain) - }; - - Ok(ParsedPkcs12 { - pkey: pkey, - cert: cert, - chain: chain, - }) - } - } -} - -impl Pkcs12 { - from_der!(Pkcs12, ffi::d2i_PKCS12); - - /// Creates a new builder for a protected pkcs12 certificate. - /// - /// This uses the defaults from the OpenSSL library: - /// - /// * `nid_key` - `nid::PBE_WITHSHA1AND3_KEY_TRIPLEDES_CBC` - /// * `nid_cert` - `nid::PBE_WITHSHA1AND40BITRC2_CBC` - /// * `iter` - `2048` - /// * `mac_iter` - `2048` - pub fn builder() -> Pkcs12Builder { - ffi::init(); - - Pkcs12Builder { - nid_key: nid::UNDEF, //nid::PBE_WITHSHA1AND3_KEY_TRIPLEDES_CBC, - nid_cert: nid::UNDEF, //nid::PBE_WITHSHA1AND40BITRC2_CBC, - iter: ffi::PKCS12_DEFAULT_ITER, - mac_iter: ffi::PKCS12_DEFAULT_ITER, - ca: None, - } - } -} - -pub struct ParsedPkcs12 { - pub pkey: PKey, - pub cert: X509, - // FIXME Make this Option in the next breaking release - pub chain: Stack, -} - -pub struct Pkcs12Builder { - nid_key: nid::Nid, - nid_cert: nid::Nid, - iter: c_int, - mac_iter: c_int, - ca: Option>, -} - -impl Pkcs12Builder { - /// The encryption algorithm that should be used for the key - pub fn key_algorithm(&mut self, nid: nid::Nid) -> &mut Self { - self.nid_key = nid; - self - } - - /// The encryption algorithm that should be used for the cert - pub fn cert_algorithm(&mut self, nid: nid::Nid) -> &mut Self { - self.nid_cert = nid; - self - } - - /// Key iteration count, default is 2048 as of this writing - pub fn key_iter(&mut self, iter: u32) -> &mut Self { - self.iter = iter as c_int; - self - } - - /// MAC iteration count, default is the same as key_iter. - /// - /// Old implementations don't understand MAC iterations greater than 1, (pre 1.0.1?), if such - /// compatibility is required this should be set to 1. - pub fn mac_iter(&mut self, mac_iter: u32) -> &mut Self { - self.mac_iter = mac_iter as c_int; - self - } - - /// An additional set of certificates to include in the archive beyond the one provided to - /// `build`. - pub fn ca(&mut self, ca: Stack) -> &mut Self { - self.ca = Some(ca); - self - } - - /// Builds the PKCS #12 object - /// - /// # Arguments - /// - /// * `password` - the password used to encrypt the key and certificate - /// * `friendly_name` - user defined name for the certificate - /// * `pkey` - key to store - /// * `cert` - certificate to store - pub fn build( - self, - password: &str, - friendly_name: &str, - pkey: &PKeyRef, - cert: &X509, - ) -> Result { - unsafe { - let pass = CString::new(password).unwrap(); - let friendly_name = CString::new(friendly_name).unwrap(); - let pkey = pkey.as_ptr(); - let cert = cert.as_ptr(); - let ca = self.ca.as_ref().map(|ca| ca.as_ptr()).unwrap_or( - ptr::null_mut(), - ); - let nid_key = self.nid_key.as_raw(); - let nid_cert = self.nid_cert.as_raw(); - - // According to the OpenSSL docs, keytype is a non-standard extension for MSIE, - // It's values are KEY_SIG or KEY_EX, see the OpenSSL docs for more information: - // https://www.openssl.org/docs/man1.0.2/crypto/PKCS12_create.html - let keytype = 0; - - cvt_p(ffi::PKCS12_create( - pass.as_ptr() as *const _ as *mut _, - friendly_name.as_ptr() as *const _ as *mut _, - pkey, - cert, - ca, - nid_key, - nid_cert, - self.iter, - self.mac_iter, - keytype, - )).map(Pkcs12) - } - } -} - -#[cfg(test)] -mod test { - use hash::MessageDigest; - use hex::ToHex; - - use asn1::Asn1Time; - use rsa::Rsa; - use pkey::PKey; - use nid; - use x509::{X509, X509Name}; - use x509::extension::KeyUsage; - - use super::*; - - #[test] - fn parse() { - let der = include_bytes!("../test/identity.p12"); - let pkcs12 = Pkcs12::from_der(der).unwrap(); - let parsed = pkcs12.parse("mypass").unwrap(); - - assert_eq!( - parsed - .cert - .fingerprint(MessageDigest::sha1()) - .unwrap() - .to_hex(), - "59172d9313e84459bcff27f967e79e6e9217e584" - ); - - assert_eq!(parsed.chain.len(), 1); - assert_eq!( - parsed.chain[0] - .fingerprint(MessageDigest::sha1()) - .unwrap() - .to_hex(), - "c0cbdf7cdd03c9773e5468e1f6d2da7d5cbb1875" - ); - } - - #[test] - fn parse_empty_chain() { - let der = include_bytes!("../test/keystore-empty-chain.p12"); - let pkcs12 = Pkcs12::from_der(der).unwrap(); - let parsed = pkcs12.parse("cassandra").unwrap(); - - assert_eq!(parsed.chain.len(), 0); - assert_eq!(parsed.chain.into_iter().collect::>().len(), 0); - } - - #[test] - fn create() { - let subject_name = "ns.example.com"; - let rsa = Rsa::generate(2048).unwrap(); - let pkey = PKey::from_rsa(rsa).unwrap(); - - let mut name = X509Name::builder().unwrap(); - name.append_entry_by_nid(nid::COMMONNAME, subject_name) - .unwrap(); - let name = name.build(); - - let key_usage = KeyUsage::new().digital_signature().build().unwrap(); - - let mut builder = X509::builder().unwrap(); - builder.set_version(2).unwrap(); - builder - .set_not_before(&Asn1Time::days_from_now(0).unwrap()) - .unwrap(); - builder - .set_not_after(&Asn1Time::days_from_now(365).unwrap()) - .unwrap(); - builder.set_subject_name(&name).unwrap(); - builder.set_issuer_name(&name).unwrap(); - builder.append_extension(key_usage).unwrap(); - builder.set_pubkey(&pkey).unwrap(); - builder.sign(&pkey, MessageDigest::sha256()).unwrap(); - let cert = builder.build(); - - let pkcs12_builder = Pkcs12::builder(); - let pkcs12 = pkcs12_builder - .build("mypass", subject_name, &pkey, &cert) - .unwrap(); - let der = pkcs12.to_der().unwrap(); - - let pkcs12 = Pkcs12::from_der(&der).unwrap(); - let parsed = pkcs12.parse("mypass").unwrap(); - - assert_eq!( - parsed.cert.fingerprint(MessageDigest::sha1()).unwrap(), - cert.fingerprint(MessageDigest::sha1()).unwrap() - ); - assert!(parsed.pkey.public_eq(&pkey)); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/pkcs5.rs cargo-0.26.0/vendor/openssl-0.9.24/src/pkcs5.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/pkcs5.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/pkcs5.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,570 +0,0 @@ -use libc::c_int; -use std::ptr; -use ffi; - -use cvt; -use hash::MessageDigest; -use symm::Cipher; -use error::ErrorStack; - -#[derive(Clone, Eq, PartialEq, Hash, Debug)] -pub struct KeyIvPair { - pub key: Vec, - pub iv: Option>, -} - -/// Derives a key and an IV from various parameters. -/// -/// If specified, `salt` must be 8 bytes in length. -/// -/// If the total key and IV length is less than 16 bytes and MD5 is used then -/// the algorithm is compatible with the key derivation algorithm from PKCS#5 -/// v1.5 or PBKDF1 from PKCS#5 v2.0. -/// -/// New applications should not use this and instead use -/// `pbkdf2_hmac` or another more modern key derivation algorithm. -pub fn bytes_to_key( - cipher: Cipher, - digest: MessageDigest, - data: &[u8], - salt: Option<&[u8]>, - count: i32, -) -> Result { - unsafe { - assert!(data.len() <= c_int::max_value() as usize); - let salt_ptr = match salt { - Some(salt) => { - assert_eq!(salt.len(), ffi::PKCS5_SALT_LEN as usize); - salt.as_ptr() - } - None => ptr::null(), - }; - - ffi::init(); - - let mut iv = cipher.iv_len().map(|l| vec![0; l]); - - let cipher = cipher.as_ptr(); - let digest = digest.as_ptr(); - - let len = cvt(ffi::EVP_BytesToKey( - cipher, - digest, - salt_ptr, - ptr::null(), - data.len() as c_int, - count.into(), - ptr::null_mut(), - ptr::null_mut(), - ))?; - - let mut key = vec![0; len as usize]; - let iv_ptr = iv.as_mut().map(|v| v.as_mut_ptr()).unwrap_or( - ptr::null_mut(), - ); - - cvt(ffi::EVP_BytesToKey( - cipher, - digest, - salt_ptr, - data.as_ptr(), - data.len() as c_int, - count as c_int, - key.as_mut_ptr(), - iv_ptr, - ))?; - - Ok(KeyIvPair { key: key, iv: iv }) - } -} - -/// Derives a key from a password and salt using the PBKDF2-HMAC algorithm with a digest function. -pub fn pbkdf2_hmac( - pass: &[u8], - salt: &[u8], - iter: usize, - hash: MessageDigest, - key: &mut [u8], -) -> Result<(), ErrorStack> { - unsafe { - assert!(pass.len() <= c_int::max_value() as usize); - assert!(salt.len() <= c_int::max_value() as usize); - assert!(key.len() <= c_int::max_value() as usize); - - ffi::init(); - cvt(ffi::PKCS5_PBKDF2_HMAC( - pass.as_ptr() as *const _, - pass.len() as c_int, - salt.as_ptr(), - salt.len() as c_int, - iter as c_int, - hash.as_ptr(), - key.len() as c_int, - key.as_mut_ptr(), - )).map(|_| ()) - } -} - -/// Derives a key from a password and salt using the scrypt algorithm. -/// -/// Requires the `v110` feature and OpenSSL 1.1.0. -#[cfg(all(feature = "v110", ossl110))] -pub fn scrypt( - pass: &[u8], - salt: &[u8], - n: u64, - r: u64, - p: u64, - maxmem: u64, - key: &mut [u8], -) -> Result<(), ErrorStack> { - unsafe { - ffi::init(); - cvt(ffi::EVP_PBE_scrypt( - pass.as_ptr() as *const _, - pass.len(), - salt.as_ptr() as *const _, - salt.len(), - n, - r, - p, - maxmem, - key.as_mut_ptr() as *mut _, - key.len(), - )).map(|_| ()) - } -} - -#[cfg(test)] -mod tests { - use hash::MessageDigest; - use symm::Cipher; - - // Test vectors from - // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c - #[test] - fn pbkdf2_hmac_sha256() { - let mut buf = [0; 16]; - - super::pbkdf2_hmac(b"passwd", b"salt", 1, MessageDigest::sha256(), &mut buf).unwrap(); - assert_eq!( - buf, - &[ - 0x55_u8, - 0xac_u8, - 0x04_u8, - 0x6e_u8, - 0x56_u8, - 0xe3_u8, - 0x08_u8, - 0x9f_u8, - 0xec_u8, - 0x16_u8, - 0x91_u8, - 0xc2_u8, - 0x25_u8, - 0x44_u8, - 0xb6_u8, - 0x05_u8, - ] - [..] - ); - - super::pbkdf2_hmac( - b"Password", - b"NaCl", - 80000, - MessageDigest::sha256(), - &mut buf, - ).unwrap(); - assert_eq!( - buf, - &[ - 0x4d_u8, - 0xdc_u8, - 0xd8_u8, - 0xf6_u8, - 0x0b_u8, - 0x98_u8, - 0xbe_u8, - 0x21_u8, - 0x83_u8, - 0x0c_u8, - 0xee_u8, - 0x5e_u8, - 0xf2_u8, - 0x27_u8, - 0x01_u8, - 0xf9_u8, - ] - [..] - ); - } - - // Test vectors from - // https://git.lysator.liu.se/nettle/nettle/blob/nettle_3.1.1_release_20150424/testsuite/pbkdf2-test.c - #[test] - fn pbkdf2_hmac_sha512() { - let mut buf = [0; 64]; - - super::pbkdf2_hmac(b"password", b"NaCL", 1, MessageDigest::sha512(), &mut buf).unwrap(); - assert_eq!( - &buf[..], - &[ - 0x73_u8, - 0xde_u8, - 0xcf_u8, - 0xa5_u8, - 0x8a_u8, - 0xa2_u8, - 0xe8_u8, - 0x4f_u8, - 0x94_u8, - 0x77_u8, - 0x1a_u8, - 0x75_u8, - 0x73_u8, - 0x6b_u8, - 0xb8_u8, - 0x8b_u8, - 0xd3_u8, - 0xc7_u8, - 0xb3_u8, - 0x82_u8, - 0x70_u8, - 0xcf_u8, - 0xb5_u8, - 0x0c_u8, - 0xb3_u8, - 0x90_u8, - 0xed_u8, - 0x78_u8, - 0xb3_u8, - 0x05_u8, - 0x65_u8, - 0x6a_u8, - 0xf8_u8, - 0x14_u8, - 0x8e_u8, - 0x52_u8, - 0x45_u8, - 0x2b_u8, - 0x22_u8, - 0x16_u8, - 0xb2_u8, - 0xb8_u8, - 0x09_u8, - 0x8b_u8, - 0x76_u8, - 0x1f_u8, - 0xc6_u8, - 0x33_u8, - 0x60_u8, - 0x60_u8, - 0xa0_u8, - 0x9f_u8, - 0x76_u8, - 0x41_u8, - 0x5e_u8, - 0x9f_u8, - 0x71_u8, - 0xea_u8, - 0x47_u8, - 0xf9_u8, - 0xe9_u8, - 0x06_u8, - 0x43_u8, - 0x06_u8, - ] - [..] - ); - - super::pbkdf2_hmac( - b"pass\0word", - b"sa\0lt", - 1, - MessageDigest::sha512(), - &mut buf, - ).unwrap(); - assert_eq!( - &buf[..], - &[ - 0x71_u8, - 0xa0_u8, - 0xec_u8, - 0x84_u8, - 0x2a_u8, - 0xbd_u8, - 0x5c_u8, - 0x67_u8, - 0x8b_u8, - 0xcf_u8, - 0xd1_u8, - 0x45_u8, - 0xf0_u8, - 0x9d_u8, - 0x83_u8, - 0x52_u8, - 0x2f_u8, - 0x93_u8, - 0x36_u8, - 0x15_u8, - 0x60_u8, - 0x56_u8, - 0x3c_u8, - 0x4d_u8, - 0x0d_u8, - 0x63_u8, - 0xb8_u8, - 0x83_u8, - 0x29_u8, - 0x87_u8, - 0x10_u8, - 0x90_u8, - 0xe7_u8, - 0x66_u8, - 0x04_u8, - 0xa4_u8, - 0x9a_u8, - 0xf0_u8, - 0x8f_u8, - 0xe7_u8, - 0xc9_u8, - 0xf5_u8, - 0x71_u8, - 0x56_u8, - 0xc8_u8, - 0x79_u8, - 0x09_u8, - 0x96_u8, - 0xb2_u8, - 0x0f_u8, - 0x06_u8, - 0xbc_u8, - 0x53_u8, - 0x5e_u8, - 0x5a_u8, - 0xb5_u8, - 0x44_u8, - 0x0d_u8, - 0xf7_u8, - 0xe8_u8, - 0x78_u8, - 0x29_u8, - 0x6f_u8, - 0xa7_u8, - ] - [..] - ); - - super::pbkdf2_hmac( - b"passwordPASSWORDpassword", - b"salt\0\0\0", - 50, - MessageDigest::sha512(), - &mut buf, - ).unwrap(); - assert_eq!( - &buf[..], - &[ - 0x01_u8, - 0x68_u8, - 0x71_u8, - 0xa4_u8, - 0xc4_u8, - 0xb7_u8, - 0x5f_u8, - 0x96_u8, - 0x85_u8, - 0x7f_u8, - 0xd2_u8, - 0xb9_u8, - 0xf8_u8, - 0xca_u8, - 0x28_u8, - 0x02_u8, - 0x3b_u8, - 0x30_u8, - 0xee_u8, - 0x2a_u8, - 0x39_u8, - 0xf5_u8, - 0xad_u8, - 0xca_u8, - 0xc8_u8, - 0xc9_u8, - 0x37_u8, - 0x5f_u8, - 0x9b_u8, - 0xda_u8, - 0x1c_u8, - 0xcd_u8, - 0x1b_u8, - 0x6f_u8, - 0x0b_u8, - 0x2f_u8, - 0xc3_u8, - 0xad_u8, - 0xda_u8, - 0x50_u8, - 0x54_u8, - 0x12_u8, - 0xe7_u8, - 0x9d_u8, - 0x89_u8, - 0x00_u8, - 0x56_u8, - 0xc6_u8, - 0x2e_u8, - 0x52_u8, - 0x4c_u8, - 0x7d_u8, - 0x51_u8, - 0x15_u8, - 0x4b_u8, - 0x1a_u8, - 0x85_u8, - 0x34_u8, - 0x57_u8, - 0x5b_u8, - 0xd0_u8, - 0x2d_u8, - 0xee_u8, - 0x39_u8, - ] - [..] - ); - } - - #[test] - fn bytes_to_key() { - let salt = [16_u8, 34_u8, 19_u8, 23_u8, 141_u8, 4_u8, 207_u8, 221_u8]; - - let data = [ - 143_u8, - 210_u8, - 75_u8, - 63_u8, - 214_u8, - 179_u8, - 155_u8, - 241_u8, - 242_u8, - 31_u8, - 154_u8, - 56_u8, - 198_u8, - 145_u8, - 192_u8, - 64_u8, - 2_u8, - 245_u8, - 167_u8, - 220_u8, - 55_u8, - 119_u8, - 233_u8, - 136_u8, - 139_u8, - 27_u8, - 71_u8, - 242_u8, - 119_u8, - 175_u8, - 65_u8, - 207_u8, - ]; - - - - let expected_key = vec![ - 249_u8, - 115_u8, - 114_u8, - 97_u8, - 32_u8, - 213_u8, - 165_u8, - 146_u8, - 58_u8, - 87_u8, - 234_u8, - 3_u8, - 43_u8, - 250_u8, - 97_u8, - 114_u8, - 26_u8, - 98_u8, - 245_u8, - 246_u8, - 238_u8, - 177_u8, - 229_u8, - 161_u8, - 183_u8, - 224_u8, - 174_u8, - 3_u8, - 6_u8, - 244_u8, - 236_u8, - 255_u8, - ]; - let expected_iv = vec![ - 4_u8, - 223_u8, - 153_u8, - 219_u8, - 28_u8, - 142_u8, - 234_u8, - 68_u8, - 227_u8, - 69_u8, - 98_u8, - 107_u8, - 208_u8, - 14_u8, - 236_u8, - 60_u8, - ]; - - assert_eq!( - super::bytes_to_key( - Cipher::aes_256_cbc(), - MessageDigest::sha1(), - &data, - Some(&salt), - 1, - ).unwrap(), - super::KeyIvPair { - key: expected_key, - iv: Some(expected_iv), - } - ); - } - - #[test] - #[cfg(all(feature = "v110", ossl110))] - fn scrypt() { - use hex::ToHex; - - let pass = "pleaseletmein"; - let salt = "SodiumChloride"; - let expected = "7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613\ - f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887"; - - let mut actual = [0; 64]; - super::scrypt( - pass.as_bytes(), - salt.as_bytes(), - 16384, - 8, - 1, - 0, - &mut actual, - ).unwrap(); - assert_eq!((&actual[..]).to_hex(), expected); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/pkey.rs cargo-0.26.0/vendor/openssl-0.9.24/src/pkey.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/pkey.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/pkey.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,425 +0,0 @@ -use libc::{c_void, c_char, c_int, size_t}; -use std::ptr; -use std::mem; -use std::ffi::CString; -use ffi; -use foreign_types::{ForeignType, ForeignTypeRef}; - -use {cvt, cvt_p}; -use bio::MemBioSlice; -use dh::Dh; -use dsa::Dsa; -use ec::EcKey; -use rsa::{Rsa, Padding}; -use error::ErrorStack; -use util::{CallbackState, invoke_passwd_cb, invoke_passwd_cb_old}; - -foreign_type_and_impl_send_sync! { - type CType = ffi::EVP_PKEY; - fn drop = ffi::EVP_PKEY_free; - - pub struct PKey; - pub struct PKeyRef; -} - -impl PKeyRef { - /// Returns a copy of the internal RSA key. - pub fn rsa(&self) -> Result { - unsafe { - let rsa = cvt_p(ffi::EVP_PKEY_get1_RSA(self.as_ptr()))?; - Ok(Rsa::from_ptr(rsa)) - } - } - - /// Returns a copy of the internal DSA key. - pub fn dsa(&self) -> Result { - unsafe { - let dsa = cvt_p(ffi::EVP_PKEY_get1_DSA(self.as_ptr()))?; - Ok(Dsa::from_ptr(dsa)) - } - } - - /// Returns a copy of the internal DH key. - pub fn dh(&self) -> Result { - unsafe { - let dh = cvt_p(ffi::EVP_PKEY_get1_DH(self.as_ptr()))?; - Ok(Dh::from_ptr(dh)) - } - } - - /// Returns a copy of the internal elliptic curve key. - pub fn ec_key(&self) -> Result { - unsafe { - let ec_key = cvt_p(ffi::EVP_PKEY_get1_EC_KEY(self.as_ptr()))?; - Ok(EcKey::from_ptr(ec_key)) - } - } - - public_key_to_pem!(ffi::PEM_write_bio_PUBKEY); - private_key_to_pem!(ffi::PEM_write_bio_PKCS8PrivateKey); - - private_key_to_der!(ffi::i2d_PrivateKey); - public_key_to_der!(ffi::i2d_PUBKEY); - - /// Returns the size of the key. - /// - /// This corresponds to the bit length of the modulus of an RSA key, and the bit length of the - /// group order for an elliptic curve key, for example. - pub fn bits(&self) -> u32 { - unsafe { ffi::EVP_PKEY_bits(self.as_ptr()) as u32 } - } - - /// Compares the public component of this key with another. - pub fn public_eq(&self, other: &PKeyRef) -> bool { - unsafe { ffi::EVP_PKEY_cmp(self.as_ptr(), other.as_ptr()) == 1 } - } -} - -impl PKey { - /// Creates a new `PKey` containing an RSA key. - pub fn from_rsa(rsa: Rsa) -> Result { - unsafe { - let evp = cvt_p(ffi::EVP_PKEY_new())?; - let pkey = PKey(evp); - cvt(ffi::EVP_PKEY_assign( - pkey.0, - ffi::EVP_PKEY_RSA, - rsa.as_ptr() as *mut _, - ))?; - mem::forget(rsa); - Ok(pkey) - } - } - - /// Creates a new `PKey` containing a DSA key. - pub fn from_dsa(dsa: Dsa) -> Result { - unsafe { - let evp = cvt_p(ffi::EVP_PKEY_new())?; - let pkey = PKey(evp); - cvt(ffi::EVP_PKEY_assign( - pkey.0, - ffi::EVP_PKEY_DSA, - dsa.as_ptr() as *mut _, - ))?; - mem::forget(dsa); - Ok(pkey) - } - } - - /// Creates a new `PKey` containing a Diffie-Hellman key. - pub fn from_dh(dh: Dh) -> Result { - unsafe { - let evp = cvt_p(ffi::EVP_PKEY_new())?; - let pkey = PKey(evp); - cvt(ffi::EVP_PKEY_assign( - pkey.0, - ffi::EVP_PKEY_DH, - dh.as_ptr() as *mut _, - ))?; - mem::forget(dh); - Ok(pkey) - } - } - - /// Creates a new `PKey` containing an elliptic curve key. - pub fn from_ec_key(ec_key: EcKey) -> Result { - unsafe { - let evp = cvt_p(ffi::EVP_PKEY_new())?; - let pkey = PKey(evp); - cvt(ffi::EVP_PKEY_assign( - pkey.0, - ffi::EVP_PKEY_EC, - ec_key.as_ptr() as *mut _, - ))?; - mem::forget(ec_key); - Ok(pkey) - } - } - - /// Creates a new `PKey` containing an HMAC key. - /// - /// # Note - /// To compute HMAC values, use the `sign` module. - pub fn hmac(key: &[u8]) -> Result { - unsafe { - assert!(key.len() <= c_int::max_value() as usize); - let key = cvt_p(ffi::EVP_PKEY_new_mac_key( - ffi::EVP_PKEY_HMAC, - ptr::null_mut(), - key.as_ptr() as *const _, - key.len() as c_int, - ))?; - Ok(PKey(key)) - } - } - - private_key_from_pem!(PKey, ffi::PEM_read_bio_PrivateKey); - public_key_from_pem!(PKey, ffi::PEM_read_bio_PUBKEY); - public_key_from_der!(PKey, ffi::d2i_PUBKEY); - private_key_from_der!(PKey, ffi::d2i_AutoPrivateKey); - - /// Deserializes a DER-formatted PKCS#8 private key, using a callback to retrieve the password - /// if the key is encrpyted. - /// - /// The callback should copy the password into the provided buffer and return the number of - /// bytes written. - pub fn private_key_from_pkcs8_callback(der: &[u8], callback: F) -> Result - where - F: FnOnce(&mut [u8]) -> Result, - { - unsafe { - ffi::init(); - let mut cb = CallbackState::new(callback); - let bio = MemBioSlice::new(der)?; - cvt_p(ffi::d2i_PKCS8PrivateKey_bio( - bio.as_ptr(), - ptr::null_mut(), - Some(invoke_passwd_cb::), - &mut cb as *mut _ as *mut _, - )).map(PKey) - } - } - - /// Deserializes a DER-formatted PKCS#8 private key, using the supplied password if the key is - /// encrypted. - /// - /// # Panics - /// - /// Panics if `passphrase` contains an embedded null. - pub fn private_key_from_pkcs8_passphrase( - der: &[u8], - passphrase: &[u8], - ) -> Result { - unsafe { - ffi::init(); - let bio = MemBioSlice::new(der)?; - let passphrase = CString::new(passphrase).unwrap(); - cvt_p(ffi::d2i_PKCS8PrivateKey_bio( - bio.as_ptr(), - ptr::null_mut(), - None, - passphrase.as_ptr() as *const _ as *mut _, - )).map(PKey) - } - } - - #[deprecated(since = "0.9.2", note = "use private_key_from_pem_callback")] - pub fn private_key_from_pem_cb(buf: &[u8], pass_cb: F) -> Result - where - F: FnOnce(&mut [c_char]) -> usize, - { - ffi::init(); - let mut cb = CallbackState::new(pass_cb); - let mem_bio = MemBioSlice::new(buf)?; - unsafe { - let evp = cvt_p(ffi::PEM_read_bio_PrivateKey( - mem_bio.as_ptr(), - ptr::null_mut(), - Some(invoke_passwd_cb_old::), - &mut cb as *mut _ as *mut c_void, - ))?; - Ok(PKey::from_ptr(evp)) - } - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::EVP_PKEY_CTX; - fn drop = ffi::EVP_PKEY_CTX_free; - - pub struct PKeyCtx; - pub struct PKeyCtxRef; -} - -impl PKeyCtx { - pub fn from_pkey(pkey: &PKeyRef) -> Result { - unsafe { - let evp = cvt_p(ffi::EVP_PKEY_CTX_new(pkey.as_ptr(), ptr::null_mut()))?; - Ok(PKeyCtx(evp)) - } - } -} - -impl PKeyCtxRef { - pub fn set_rsa_padding(&mut self, pad: Padding) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EVP_PKEY_CTX_set_rsa_padding( - self.as_ptr(), - pad.as_raw(), - ))?; - } - Ok(()) - } - - pub fn rsa_padding(&self) -> Result { - let mut pad: c_int = 0; - unsafe { - cvt( - ffi::EVP_PKEY_CTX_get_rsa_padding(self.as_ptr(), &mut pad), - )?; - }; - Ok(Padding::from_raw(pad)) - } - - pub fn derive_init(&mut self) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EVP_PKEY_derive_init(self.as_ptr()))?; - } - Ok(()) - } - - pub fn derive_set_peer(&mut self, peer: &PKeyRef) -> Result<(), ErrorStack> { - unsafe { - cvt( - ffi::EVP_PKEY_derive_set_peer(self.as_ptr(), peer.as_ptr()), - )?; - } - Ok(()) - } - - pub fn derive(&mut self) -> Result, ErrorStack> { - let mut len: size_t = 0; - unsafe { - cvt(ffi::EVP_PKEY_derive( - self.as_ptr(), - ptr::null_mut(), - &mut len, - ))?; - } - - let mut key = vec![0u8; len]; - unsafe { - cvt(ffi::EVP_PKEY_derive( - self.as_ptr(), - key.as_mut_ptr(), - &mut len, - ))?; - } - Ok(key) - } -} - -#[cfg(test)] -mod tests { - use symm::Cipher; - use dh::Dh; - use dsa::Dsa; - use ec::{EcGroup, EcKey}; - use rsa::Rsa; - use nid; - - use super::*; - - #[test] - fn test_to_password() { - let rsa = Rsa::generate(2048).unwrap(); - let pkey = PKey::from_rsa(rsa).unwrap(); - let pem = pkey.private_key_to_pem_passphrase(Cipher::aes_128_cbc(), b"foobar") - .unwrap(); - PKey::private_key_from_pem_passphrase(&pem, b"foobar").unwrap(); - assert!(PKey::private_key_from_pem_passphrase(&pem, b"fizzbuzz").is_err()); - } - - #[test] - fn test_encrypted_pkcs8_passphrase() { - let key = include_bytes!("../test/pkcs8.der"); - PKey::private_key_from_pkcs8_passphrase(key, b"mypass").unwrap(); - } - - #[test] - fn test_encrypted_pkcs8_callback() { - let mut password_queried = false; - let key = include_bytes!("../test/pkcs8.der"); - PKey::private_key_from_pkcs8_callback(key, |password| { - password_queried = true; - password[..6].copy_from_slice(b"mypass"); - Ok(6) - }).unwrap(); - assert!(password_queried); - } - - #[test] - fn test_private_key_from_pem() { - let key = include_bytes!("../test/key.pem"); - PKey::private_key_from_pem(key).unwrap(); - } - - #[test] - fn test_public_key_from_pem() { - let key = include_bytes!("../test/key.pem.pub"); - PKey::public_key_from_pem(key).unwrap(); - } - - #[test] - fn test_public_key_from_der() { - let key = include_bytes!("../test/key.der.pub"); - PKey::public_key_from_der(key).unwrap(); - } - - #[test] - fn test_private_key_from_der() { - let key = include_bytes!("../test/key.der"); - PKey::private_key_from_der(key).unwrap(); - } - - #[test] - fn test_pem() { - let key = include_bytes!("../test/key.pem"); - let key = PKey::private_key_from_pem(key).unwrap(); - - let priv_key = key.private_key_to_pem().unwrap(); - let pub_key = key.public_key_to_pem().unwrap(); - - // As a super-simple verification, just check that the buffers contain - // the `PRIVATE KEY` or `PUBLIC KEY` strings. - assert!(priv_key.windows(11).any(|s| s == b"PRIVATE KEY")); - assert!(pub_key.windows(10).any(|s| s == b"PUBLIC KEY")); - } - - #[test] - fn test_rsa_accessor() { - let rsa = Rsa::generate(2048).unwrap(); - let pkey = PKey::from_rsa(rsa).unwrap(); - pkey.rsa().unwrap(); - assert!(pkey.dsa().is_err()); - } - - #[test] - fn test_dsa_accessor() { - let dsa = Dsa::generate(2048).unwrap(); - let pkey = PKey::from_dsa(dsa).unwrap(); - pkey.dsa().unwrap(); - assert!(pkey.rsa().is_err()); - } - - #[test] - fn test_dh_accessor() { - let dh = include_bytes!("../test/dhparams.pem"); - let dh = Dh::from_pem(dh).unwrap(); - let pkey = PKey::from_dh(dh).unwrap(); - pkey.dh().unwrap(); - assert!(pkey.rsa().is_err()); - } - - #[test] - fn test_ec_key_accessor() { - let ec_key = EcKey::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - let pkey = PKey::from_ec_key(ec_key).unwrap(); - pkey.ec_key().unwrap(); - assert!(pkey.rsa().is_err()); - } - - #[test] - fn test_ec_key_derive() { - let group = EcGroup::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - let ec_key = EcKey::generate(&group).unwrap(); - let ec_key2 = EcKey::generate(&group).unwrap(); - let pkey = PKey::from_ec_key(ec_key).unwrap(); - let pkey2 = PKey::from_ec_key(ec_key2).unwrap(); - let mut pkey_ctx = PKeyCtx::from_pkey(&pkey).unwrap(); - pkey_ctx.derive_init().unwrap(); - pkey_ctx.derive_set_peer(&pkey2).unwrap(); - let shared = pkey_ctx.derive().unwrap(); - assert!(!shared.is_empty()); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/rand.rs cargo-0.26.0/vendor/openssl-0.9.24/src/rand.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/rand.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/rand.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,52 +0,0 @@ -//! Utilities for secure random number generation. -//! -//! # Examples -//! -//! To generate a buffer with cryptographically strong bytes: -//! -//! ``` -//! use openssl::rand::rand_bytes; -//! -//! let mut buf = [0; 256]; -//! rand_bytes(&mut buf).unwrap(); -//! ``` -use libc::c_int; -use ffi; - -use cvt; -use error::ErrorStack; - -/// Fill buffer with cryptographically strong pseudo-random bytes. -/// -/// # Examples -/// -/// To generate a buffer with cryptographically strong bytes: -/// -/// ``` -/// use openssl::rand::rand_bytes; -/// -/// let mut buf = [0; 256]; -/// rand_bytes(&mut buf).unwrap(); -/// ``` -/// -/// # External OpenSSL Documentation -/// -/// [RAND_bytes](https://www.openssl.org/docs/man1.1.0/crypto/RAND_bytes.html) -pub fn rand_bytes(buf: &mut [u8]) -> Result<(), ErrorStack> { - unsafe { - ffi::init(); - assert!(buf.len() <= c_int::max_value() as usize); - cvt(ffi::RAND_bytes(buf.as_mut_ptr(), buf.len() as c_int)).map(|_| ()) - } -} - -#[cfg(test)] -mod tests { - use super::rand_bytes; - - #[test] - fn test_rand_bytes() { - let mut buf = [0; 32]; - rand_bytes(&mut buf).unwrap(); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/rsa.rs cargo-0.26.0/vendor/openssl-0.9.24/src/rsa.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/rsa.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/rsa.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,538 +0,0 @@ -use ffi; -use std::fmt; -use std::ptr; -use std::mem; -use libc::{c_int, c_void, c_char}; -use foreign_types::ForeignTypeRef; - -use {cvt, cvt_p, cvt_n}; -use bn::{BigNum, BigNumRef}; -use bio::MemBioSlice; -use error::ErrorStack; -use util::{CallbackState, invoke_passwd_cb_old}; - -/// Type of encryption padding to use. -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub struct Padding(c_int); - -impl Padding { - pub fn from_raw(value: c_int) -> Padding { - Padding(value) - } - - pub fn as_raw(&self) -> c_int { - self.0 - } -} - -pub const NO_PADDING: Padding = Padding(ffi::RSA_NO_PADDING); -pub const PKCS1_PADDING: Padding = Padding(ffi::RSA_PKCS1_PADDING); -pub const PKCS1_OAEP_PADDING: Padding = Padding(ffi::RSA_PKCS1_OAEP_PADDING); - -foreign_type_and_impl_send_sync! { - type CType = ffi::RSA; - fn drop = ffi::RSA_free; - - pub struct Rsa; - pub struct RsaRef; -} - -impl RsaRef { - // FIXME these need to specify output format - private_key_to_pem!(ffi::PEM_write_bio_RSAPrivateKey); - public_key_to_pem!(ffi::PEM_write_bio_RSA_PUBKEY); - - private_key_to_der!(ffi::i2d_RSAPrivateKey); - public_key_to_der!(ffi::i2d_RSA_PUBKEY); - - to_der_inner!( - /// Serializes the public key to DER-encoded PKCS#1. - public_key_to_der_pkcs1, - ffi::i2d_RSAPublicKey - ); - - // FIXME should return u32 - pub fn size(&self) -> usize { - unsafe { - assert!(self.n().is_some()); - - ffi::RSA_size(self.as_ptr()) as usize - } - } - - /// Decrypts data using the private key, returning the number of decrypted bytes. - /// - /// # Panics - /// - /// Panics if `self` has no private components, or if `to` is smaller - /// than `self.size()`. - pub fn private_decrypt( - &self, - from: &[u8], - to: &mut [u8], - padding: Padding, - ) -> Result { - assert!(self.d().is_some(), "private components missing"); - assert!(from.len() <= i32::max_value() as usize); - assert!(to.len() >= self.size()); - - unsafe { - let len = cvt_n(ffi::RSA_private_decrypt( - from.len() as c_int, - from.as_ptr(), - to.as_mut_ptr(), - self.as_ptr(), - padding.0, - ))?; - Ok(len as usize) - } - } - - /// Encrypts data using the private key, returning the number of encrypted bytes. - /// - /// # Panics - /// - /// Panics if `self` has no private components, or if `to` is smaller - /// than `self.size()`. - pub fn private_encrypt( - &self, - from: &[u8], - to: &mut [u8], - padding: Padding, - ) -> Result { - assert!(self.d().is_some(), "private components missing"); - assert!(from.len() <= i32::max_value() as usize); - assert!(to.len() >= self.size()); - - unsafe { - let len = cvt_n(ffi::RSA_private_encrypt( - from.len() as c_int, - from.as_ptr(), - to.as_mut_ptr(), - self.as_ptr(), - padding.0, - ))?; - Ok(len as usize) - } - } - - /// Decrypts data using the public key, returning the number of decrypted bytes. - /// - /// # Panics - /// - /// Panics if `to` is smaller than `self.size()`. - pub fn public_decrypt( - &self, - from: &[u8], - to: &mut [u8], - padding: Padding, - ) -> Result { - assert!(from.len() <= i32::max_value() as usize); - assert!(to.len() >= self.size()); - - unsafe { - let len = cvt_n(ffi::RSA_public_decrypt( - from.len() as c_int, - from.as_ptr(), - to.as_mut_ptr(), - self.as_ptr(), - padding.0, - ))?; - Ok(len as usize) - } - } - - /// Encrypts data using the public key, returning the number of encrypted bytes. - /// - /// # Panics - /// - /// Panics if `to` is smaller than `self.size()`. - pub fn public_encrypt( - &self, - from: &[u8], - to: &mut [u8], - padding: Padding, - ) -> Result { - assert!(from.len() <= i32::max_value() as usize); - assert!(to.len() >= self.size()); - - unsafe { - let len = cvt_n(ffi::RSA_public_encrypt( - from.len() as c_int, - from.as_ptr(), - to.as_mut_ptr(), - self.as_ptr(), - padding.0, - ))?; - Ok(len as usize) - } - } - - pub fn n(&self) -> Option<&BigNumRef> { - unsafe { - let n = compat::key(self.as_ptr())[0]; - if n.is_null() { - None - } else { - Some(BigNumRef::from_ptr(n as *mut _)) - } - } - } - - pub fn d(&self) -> Option<&BigNumRef> { - unsafe { - let d = compat::key(self.as_ptr())[2]; - if d.is_null() { - None - } else { - Some(BigNumRef::from_ptr(d as *mut _)) - } - } - } - - pub fn e(&self) -> Option<&BigNumRef> { - unsafe { - let e = compat::key(self.as_ptr())[1]; - if e.is_null() { - None - } else { - Some(BigNumRef::from_ptr(e as *mut _)) - } - } - } - - pub fn p(&self) -> Option<&BigNumRef> { - unsafe { - let p = compat::factors(self.as_ptr())[0]; - if p.is_null() { - None - } else { - Some(BigNumRef::from_ptr(p as *mut _)) - } - } - } - - pub fn q(&self) -> Option<&BigNumRef> { - unsafe { - let q = compat::factors(self.as_ptr())[1]; - if q.is_null() { - None - } else { - Some(BigNumRef::from_ptr(q as *mut _)) - } - } - } - - pub fn dp(&self) -> Option<&BigNumRef> { - unsafe { - let dp = compat::crt_params(self.as_ptr())[0]; - if dp.is_null() { - None - } else { - Some(BigNumRef::from_ptr(dp as *mut _)) - } - } - } - - pub fn dq(&self) -> Option<&BigNumRef> { - unsafe { - let dq = compat::crt_params(self.as_ptr())[1]; - if dq.is_null() { - None - } else { - Some(BigNumRef::from_ptr(dq as *mut _)) - } - } - } - - pub fn qi(&self) -> Option<&BigNumRef> { - unsafe { - let qi = compat::crt_params(self.as_ptr())[2]; - if qi.is_null() { - None - } else { - Some(BigNumRef::from_ptr(qi as *mut _)) - } - } - } -} - -impl Rsa { - /// only useful for associating the key material directly with the key, it's safer to use - /// the supplied load and save methods for DER formatted keys. - pub fn from_public_components(n: BigNum, e: BigNum) -> Result { - unsafe { - let rsa = Rsa(cvt_p(ffi::RSA_new())?); - cvt(compat::set_key( - rsa.0, - n.as_ptr(), - e.as_ptr(), - ptr::null_mut(), - ))?; - mem::forget((n, e)); - Ok(rsa) - } - } - - pub fn from_private_components( - n: BigNum, - e: BigNum, - d: BigNum, - p: BigNum, - q: BigNum, - dp: BigNum, - dq: BigNum, - qi: BigNum, - ) -> Result { - unsafe { - let rsa = Rsa(cvt_p(ffi::RSA_new())?); - cvt( - compat::set_key(rsa.0, n.as_ptr(), e.as_ptr(), d.as_ptr()), - )?; - mem::forget((n, e, d)); - cvt(compat::set_factors(rsa.0, p.as_ptr(), q.as_ptr()))?; - mem::forget((p, q)); - cvt(compat::set_crt_params( - rsa.0, - dp.as_ptr(), - dq.as_ptr(), - qi.as_ptr(), - ))?; - mem::forget((dp, dq, qi)); - Ok(rsa) - } - } - - /// Generates a public/private key pair with the specified size. - /// - /// The public exponent will be 65537. - pub fn generate(bits: u32) -> Result { - ffi::init(); - unsafe { - let rsa = Rsa(cvt_p(ffi::RSA_new())?); - let e = BigNum::from_u32(ffi::RSA_F4 as u32)?; - cvt(ffi::RSA_generate_key_ex( - rsa.0, - bits as c_int, - e.as_ptr(), - ptr::null_mut(), - ))?; - Ok(rsa) - } - } - - // FIXME these need to identify input formats - private_key_from_pem!(Rsa, ffi::PEM_read_bio_RSAPrivateKey); - private_key_from_der!(Rsa, ffi::d2i_RSAPrivateKey); - public_key_from_pem!(Rsa, ffi::PEM_read_bio_RSA_PUBKEY); - public_key_from_der!(Rsa, ffi::d2i_RSA_PUBKEY); - - from_der_inner!( - /// Deserializes a public key from DER-encoded PKCS#1 data. - public_key_from_der_pkcs1, - Rsa, - ffi::d2i_RSAPublicKey - ); - - #[deprecated(since = "0.9.2", note = "use private_key_from_pem_callback")] - pub fn private_key_from_pem_cb(buf: &[u8], pass_cb: F) -> Result - where - F: FnOnce(&mut [c_char]) -> usize, - { - ffi::init(); - let mut cb = CallbackState::new(pass_cb); - let mem_bio = MemBioSlice::new(buf)?; - - unsafe { - let cb_ptr = &mut cb as *mut _ as *mut c_void; - let rsa = cvt_p(ffi::PEM_read_bio_RSAPrivateKey( - mem_bio.as_ptr(), - ptr::null_mut(), - Some(invoke_passwd_cb_old::), - cb_ptr, - ))?; - Ok(Rsa(rsa)) - } - } -} - -impl fmt::Debug for Rsa { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Rsa") - } -} - -#[cfg(ossl110)] -mod compat { - use std::ptr; - - use ffi::{self, BIGNUM, RSA}; - use libc::c_int; - - pub unsafe fn key(r: *const RSA) -> [*const BIGNUM; 3] { - let (mut n, mut e, mut d) = (ptr::null(), ptr::null(), ptr::null()); - ffi::RSA_get0_key(r, &mut n, &mut e, &mut d); - [n, e, d] - } - - pub unsafe fn factors(r: *const RSA) -> [*const BIGNUM; 2] { - let (mut p, mut q) = (ptr::null(), ptr::null()); - ffi::RSA_get0_factors(r, &mut p, &mut q); - [p, q] - } - - pub unsafe fn crt_params(r: *const RSA) -> [*const BIGNUM; 3] { - let (mut dp, mut dq, mut qi) = (ptr::null(), ptr::null(), ptr::null()); - ffi::RSA_get0_crt_params(r, &mut dp, &mut dq, &mut qi); - [dp, dq, qi] - } - - pub unsafe fn set_key(r: *mut RSA, n: *mut BIGNUM, e: *mut BIGNUM, d: *mut BIGNUM) -> c_int { - ffi::RSA_set0_key(r, n, e, d) - } - - pub unsafe fn set_factors(r: *mut RSA, p: *mut BIGNUM, q: *mut BIGNUM) -> c_int { - ffi::RSA_set0_factors(r, p, q) - } - - pub unsafe fn set_crt_params( - r: *mut RSA, - dmp1: *mut BIGNUM, - dmq1: *mut BIGNUM, - iqmp: *mut BIGNUM, - ) -> c_int { - ffi::RSA_set0_crt_params(r, dmp1, dmq1, iqmp) - } -} - -#[cfg(ossl10x)] -mod compat { - use libc::c_int; - use ffi::{BIGNUM, RSA}; - - pub unsafe fn key(r: *const RSA) -> [*const BIGNUM; 3] { - [(*r).n, (*r).e, (*r).d] - } - - pub unsafe fn factors(r: *const RSA) -> [*const BIGNUM; 2] { - [(*r).p, (*r).q] - } - - pub unsafe fn crt_params(r: *const RSA) -> [*const BIGNUM; 3] { - [(*r).dmp1, (*r).dmq1, (*r).iqmp] - } - - pub unsafe fn set_key(r: *mut RSA, n: *mut BIGNUM, e: *mut BIGNUM, d: *mut BIGNUM) -> c_int { - (*r).n = n; - (*r).e = e; - (*r).d = d; - 1 // TODO: is this right? should it be 0? what's success? - } - - pub unsafe fn set_factors(r: *mut RSA, p: *mut BIGNUM, q: *mut BIGNUM) -> c_int { - (*r).p = p; - (*r).q = q; - 1 // TODO: is this right? should it be 0? what's success? - } - - pub unsafe fn set_crt_params( - r: *mut RSA, - dmp1: *mut BIGNUM, - dmq1: *mut BIGNUM, - iqmp: *mut BIGNUM, - ) -> c_int { - (*r).dmp1 = dmp1; - (*r).dmq1 = dmq1; - (*r).iqmp = iqmp; - 1 // TODO: is this right? should it be 0? what's success? - } -} - -#[cfg(test)] -mod test { - use symm::Cipher; - - use super::*; - - #[test] - fn test_from_password() { - let key = include_bytes!("../test/rsa-encrypted.pem"); - Rsa::private_key_from_pem_passphrase(key, b"mypass").unwrap(); - } - - #[test] - fn test_from_password_callback() { - let mut password_queried = false; - let key = include_bytes!("../test/rsa-encrypted.pem"); - Rsa::private_key_from_pem_callback(key, |password| { - password_queried = true; - password[..6].copy_from_slice(b"mypass"); - Ok(6) - }).unwrap(); - - assert!(password_queried); - } - - #[test] - fn test_to_password() { - let key = Rsa::generate(2048).unwrap(); - let pem = key.private_key_to_pem_passphrase(Cipher::aes_128_cbc(), b"foobar") - .unwrap(); - Rsa::private_key_from_pem_passphrase(&pem, b"foobar").unwrap(); - assert!(Rsa::private_key_from_pem_passphrase(&pem, b"fizzbuzz").is_err()); - } - - #[test] - fn test_public_encrypt_private_decrypt_with_padding() { - let key = include_bytes!("../test/rsa.pem.pub"); - let public_key = Rsa::public_key_from_pem(key).unwrap(); - - let mut result = vec![0; public_key.size()]; - let original_data = b"This is test"; - let len = public_key - .public_encrypt(original_data, &mut result, PKCS1_PADDING) - .unwrap(); - assert_eq!(len, 256); - - let pkey = include_bytes!("../test/rsa.pem"); - let private_key = Rsa::private_key_from_pem(pkey).unwrap(); - let mut dec_result = vec![0; private_key.size()]; - let len = private_key - .private_decrypt(&result, &mut dec_result, PKCS1_PADDING) - .unwrap(); - - assert_eq!(&dec_result[..len], original_data); - } - - #[test] - fn test_private_encrypt() { - let k0 = super::Rsa::generate(512).unwrap(); - let k0pkey = k0.public_key_to_pem().unwrap(); - let k1 = super::Rsa::public_key_from_pem(&k0pkey).unwrap(); - - let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; - - let mut emesg = vec![0; k0.size()]; - k0.private_encrypt(&msg, &mut emesg, PKCS1_PADDING).unwrap(); - let mut dmesg = vec![0; k1.size()]; - let len = k1.public_decrypt(&emesg, &mut dmesg, PKCS1_PADDING) - .unwrap(); - assert_eq!(msg, &dmesg[..len]); - } - - #[test] - fn test_public_encrypt() { - let k0 = super::Rsa::generate(512).unwrap(); - let k0pkey = k0.private_key_to_pem().unwrap(); - let k1 = super::Rsa::private_key_from_pem(&k0pkey).unwrap(); - - let msg = vec![0xdeu8, 0xadu8, 0xd0u8, 0x0du8]; - - let mut emesg = vec![0; k0.size()]; - k0.public_encrypt(&msg, &mut emesg, PKCS1_PADDING).unwrap(); - let mut dmesg = vec![0; k1.size()]; - let len = k1.private_decrypt(&emesg, &mut dmesg, PKCS1_PADDING) - .unwrap(); - assert_eq!(msg, &dmesg[..len]); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/sha.rs cargo-0.26.0/vendor/openssl-0.9.24/src/sha.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/sha.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/sha.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,388 +0,0 @@ -//! The SHA family of hashes. -//! -//! SHA, or Secure Hash Algorithms, are a family of cryptographic hashing algorithms published by -//! the National Institute of Standards and Technology (NIST). Hash algorithms such as those in -//! the SHA family are used to map data of an arbitrary size to a fixed-size string of bytes. -//! As cryptographic hashing algorithms, these mappings have the property of being irreversable. -//! This property makes hash algorithms like these excellent for uses such as verifying the -//! contents of a file- if you know the hash you expect beforehand, then you can verify that the -//! data you have is correct if it hashes to the same value. -//! -//! # Examples -//! -//! When dealing with data that becomes available in chunks, such as while buffering data from IO, -//! you can create a hasher that you can repeatedly update to add bytes to. -//! -//! ```rust -//! extern crate openssl; -//! extern crate hex; -//! -//! use openssl::sha; -//! use hex::ToHex; -//! -//! fn main() { -//! let mut hasher = sha::Sha256::new(); -//! -//! hasher.update(b"Hello, "); -//! hasher.update(b"world"); -//! -//! let hash = hasher.finish(); -//! println!("Hashed \"Hello, world\" to {}", hash.to_hex()); -//! } -//! ``` -//! -//! On the other hand, if you already have access to all of the data you woud like to hash, you -//! may prefer to use the slightly simpler method of simply calling the hash function corresponding -//! to the algorithm you want to use. -//! -//! ```rust -//! extern crate openssl; -//! extern crate hex; -//! -//! use openssl::sha::sha256; -//! use hex::ToHex; -//! -//! fn main() { -//! let hash = sha256(b"your data or message"); -//! println!("Hash = {}", hash.to_hex()); -//! } -//! ``` -use libc::c_void; -use ffi; -use std::mem; - -/// Computes the SHA1 hash of some data. -/// -/// # Warning -/// -/// SHA1 is known to be insecure - it should not be used unless required for -/// compatibility with existing systems. -#[inline] -pub fn sha1(data: &[u8]) -> [u8; 20] { - unsafe { - let mut hash: [u8; 20] = mem::uninitialized(); - ffi::SHA1(data.as_ptr(), data.len(), hash.as_mut_ptr()); - hash - } -} - -/// Computes the SHA224 hash of some data. -#[inline] -pub fn sha224(data: &[u8]) -> [u8; 28] { - unsafe { - let mut hash: [u8; 28] = mem::uninitialized(); - ffi::SHA224(data.as_ptr(), data.len(), hash.as_mut_ptr()); - hash - } -} - -/// Computes the SHA256 hash of some data. -#[inline] -pub fn sha256(data: &[u8]) -> [u8; 32] { - unsafe { - let mut hash: [u8; 32] = mem::uninitialized(); - ffi::SHA256(data.as_ptr(), data.len(), hash.as_mut_ptr()); - hash - } -} - -/// Computes the SHA384 hash of some data. -#[inline] -pub fn sha384(data: &[u8]) -> [u8; 48] { - unsafe { - let mut hash: [u8; 48] = mem::uninitialized(); - ffi::SHA384(data.as_ptr(), data.len(), hash.as_mut_ptr()); - hash - } -} - -/// Computes the SHA512 hash of some data. -#[inline] -pub fn sha512(data: &[u8]) -> [u8; 64] { - unsafe { - let mut hash: [u8; 64] = mem::uninitialized(); - ffi::SHA512(data.as_ptr(), data.len(), hash.as_mut_ptr()); - hash - } -} - -/// An object which calculates a SHA1 hash of some data. -/// -/// # Warning -/// -/// SHA1 is known to be insecure - it should not be used unless required for -/// compatibility with existing systems. -pub struct Sha1(ffi::SHA_CTX); - -impl Sha1 { - /// Creates a new hasher. - #[inline] - pub fn new() -> Sha1 { - unsafe { - let mut ctx = mem::uninitialized(); - ffi::SHA1_Init(&mut ctx); - Sha1(ctx) - } - } - - /// Feeds some data into the hasher. - /// - /// This can be called multiple times. - #[inline] - pub fn update(&mut self, buf: &[u8]) { - unsafe { - ffi::SHA1_Update(&mut self.0, buf.as_ptr() as *const c_void, buf.len()); - } - } - - /// Returns the hash of the data. - #[inline] - pub fn finish(mut self) -> [u8; 20] { - unsafe { - let mut hash: [u8; 20] = mem::uninitialized(); - ffi::SHA1_Final(hash.as_mut_ptr(), &mut self.0); - hash - } - } -} - -/// An object which calculates a SHA224 hash of some data. -pub struct Sha224(ffi::SHA256_CTX); - -impl Sha224 { - /// Creates a new hasher. - #[inline] - pub fn new() -> Sha224 { - unsafe { - let mut ctx = mem::uninitialized(); - ffi::SHA224_Init(&mut ctx); - Sha224(ctx) - } - } - - /// Feeds some data into the hasher. - /// - /// This can be called multiple times. - #[inline] - pub fn update(&mut self, buf: &[u8]) { - unsafe { - ffi::SHA224_Update(&mut self.0, buf.as_ptr() as *const c_void, buf.len()); - } - } - - /// Returns the hash of the data. - #[inline] - pub fn finish(mut self) -> [u8; 28] { - unsafe { - let mut hash: [u8; 28] = mem::uninitialized(); - ffi::SHA224_Final(hash.as_mut_ptr(), &mut self.0); - hash - } - } -} - -/// An object which calculates a SHA256 hash of some data. -pub struct Sha256(ffi::SHA256_CTX); - -impl Sha256 { - /// Creates a new hasher. - #[inline] - pub fn new() -> Sha256 { - unsafe { - let mut ctx = mem::uninitialized(); - ffi::SHA256_Init(&mut ctx); - Sha256(ctx) - } - } - - /// Feeds some data into the hasher. - /// - /// This can be called multiple times. - #[inline] - pub fn update(&mut self, buf: &[u8]) { - unsafe { - ffi::SHA256_Update(&mut self.0, buf.as_ptr() as *const c_void, buf.len()); - } - } - - /// Returns the hash of the data. - #[inline] - pub fn finish(mut self) -> [u8; 32] { - unsafe { - let mut hash: [u8; 32] = mem::uninitialized(); - ffi::SHA256_Final(hash.as_mut_ptr(), &mut self.0); - hash - } - } -} - -/// An object which calculates a SHA384 hash of some data. -pub struct Sha384(ffi::SHA512_CTX); - -impl Sha384 { - /// Creates a new hasher. - #[inline] - pub fn new() -> Sha384 { - unsafe { - let mut ctx = mem::uninitialized(); - ffi::SHA384_Init(&mut ctx); - Sha384(ctx) - } - } - - /// Feeds some data into the hasher. - /// - /// This can be called multiple times. - #[inline] - pub fn update(&mut self, buf: &[u8]) { - unsafe { - ffi::SHA384_Update(&mut self.0, buf.as_ptr() as *const c_void, buf.len()); - } - } - - /// Returns the hash of the data. - #[inline] - pub fn finish(mut self) -> [u8; 48] { - unsafe { - let mut hash: [u8; 48] = mem::uninitialized(); - ffi::SHA384_Final(hash.as_mut_ptr(), &mut self.0); - hash - } - } -} - -/// An object which calculates a SHA512 hash of some data. -pub struct Sha512(ffi::SHA512_CTX); - -impl Sha512 { - /// Creates a new hasher. - #[inline] - pub fn new() -> Sha512 { - unsafe { - let mut ctx = mem::uninitialized(); - ffi::SHA512_Init(&mut ctx); - Sha512(ctx) - } - } - - /// Feeds some data into the hasher. - /// - /// This can be called multiple times. - #[inline] - pub fn update(&mut self, buf: &[u8]) { - unsafe { - ffi::SHA512_Update(&mut self.0, buf.as_ptr() as *const c_void, buf.len()); - } - } - - /// Returns the hash of the data. - #[inline] - pub fn finish(mut self) -> [u8; 64] { - unsafe { - let mut hash: [u8; 64] = mem::uninitialized(); - ffi::SHA512_Final(hash.as_mut_ptr(), &mut self.0); - hash - } - } -} - -#[cfg(test)] -mod test { - use hex::ToHex; - - use super::*; - - #[test] - fn standalone_1() { - let data = b"abc"; - let expected = "a9993e364706816aba3e25717850c26c9cd0d89d"; - - assert_eq!(sha1(data).to_hex(), expected); - } - - #[test] - fn struct_1() { - let expected = "a9993e364706816aba3e25717850c26c9cd0d89d"; - - let mut hasher = Sha1::new(); - hasher.update(b"a"); - hasher.update(b"bc"); - assert_eq!(hasher.finish().to_hex(), expected); - } - - #[test] - fn standalone_224() { - let data = b"abc"; - let expected = "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7"; - - assert_eq!(sha224(data).to_hex(), expected); - } - - #[test] - fn struct_224() { - let expected = "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7"; - - let mut hasher = Sha224::new(); - hasher.update(b"a"); - hasher.update(b"bc"); - assert_eq!(hasher.finish().to_hex(), expected); - } - - #[test] - fn standalone_256() { - let data = b"abc"; - let expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; - - assert_eq!(sha256(data).to_hex(), expected); - } - - #[test] - fn struct_256() { - let expected = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"; - - let mut hasher = Sha256::new(); - hasher.update(b"a"); - hasher.update(b"bc"); - assert_eq!(hasher.finish().to_hex(), expected); - } - - #[test] - fn standalone_384() { - let data = b"abc"; - let expected = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e\ - 7cc2358baeca134c825a7"; - - assert_eq!((&sha384(data)[..]).to_hex(), expected); - } - - #[test] - fn struct_384() { - let expected = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e\ - 7cc2358baeca134c825a7"; - - let mut hasher = Sha384::new(); - hasher.update(b"a"); - hasher.update(b"bc"); - assert_eq!((&hasher.finish()[..]).to_hex(), expected); - } - - #[test] - fn standalone_512() { - let data = b"abc"; - let expected = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274\ - fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"; - - assert_eq!((&sha512(data)[..]).to_hex(), expected); - } - - #[test] - fn struct_512() { - let expected = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274\ - fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"; - - let mut hasher = Sha512::new(); - hasher.update(b"a"); - hasher.update(b"bc"); - assert_eq!((&hasher.finish()[..]).to_hex(), expected); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/sign.rs cargo-0.26.0/vendor/openssl-0.9.24/src/sign.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/sign.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/sign.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,584 +0,0 @@ -//! Message signatures. -//! -//! The `Signer` allows for the computation of cryptographic signatures of -//! data given a private key. The `Verifier` can then be used with the -//! corresponding public key to verify the integrity and authenticity of that -//! data given the signature. -//! -//! # Examples -//! -//! Sign and verify data given an RSA keypair: -//! -//! ```rust -//! use openssl::sign::{Signer, Verifier}; -//! use openssl::rsa::Rsa; -//! use openssl::pkey::PKey; -//! use openssl::hash::MessageDigest; -//! -//! // Generate a keypair -//! let keypair = Rsa::generate(2048).unwrap(); -//! let keypair = PKey::from_rsa(keypair).unwrap(); -//! -//! let data = b"hello, world!"; -//! let data2 = b"hola, mundo!"; -//! -//! // Sign the data -//! let mut signer = Signer::new(MessageDigest::sha256(), &keypair).unwrap(); -//! signer.update(data).unwrap(); -//! signer.update(data2).unwrap(); -//! let signature = signer.finish().unwrap(); -//! -//! // Verify the data -//! let mut verifier = Verifier::new(MessageDigest::sha256(), &keypair).unwrap(); -//! verifier.update(data).unwrap(); -//! verifier.update(data2).unwrap(); -//! assert!(verifier.verify(&signature).unwrap()); -//! ``` -//! -//! Compute an HMAC: -//! -//! ```rust -//! use openssl::hash::MessageDigest; -//! use openssl::memcmp; -//! use openssl::pkey::PKey; -//! use openssl::sign::Signer; -//! -//! // Create a PKey -//! let key = PKey::hmac(b"my secret").unwrap(); -//! -//! let data = b"hello, world!"; -//! let data2 = b"hola, mundo!"; -//! -//! // Compute the HMAC -//! let mut signer = Signer::new(MessageDigest::sha256(), &key).unwrap(); -//! signer.update(data).unwrap(); -//! signer.update(data2).unwrap(); -//! let hmac = signer.sign_to_vec().unwrap(); -//! -//! // `Verifier` cannot be used with HMACs; use the `memcmp::eq` function instead -//! // -//! // Do not simply check for equality with `==`! -//! # let target = hmac.clone(); -//! assert!(memcmp::eq(&hmac, &target)); -//! ``` -use ffi; -use foreign_types::ForeignTypeRef; -use std::io::{self, Write}; -use std::marker::PhantomData; -use std::ptr; - -use {cvt, cvt_p}; -use hash::MessageDigest; -use pkey::{PKeyCtxRef, PKeyRef}; -use error::ErrorStack; - -#[cfg(ossl110)] -use ffi::{EVP_MD_CTX_free, EVP_MD_CTX_new}; -#[cfg(any(ossl101, ossl102))] -use ffi::{EVP_MD_CTX_create as EVP_MD_CTX_new, EVP_MD_CTX_destroy as EVP_MD_CTX_free}; - -/// A type which computes cryptographic signatures of data. -pub struct Signer<'a> { - md_ctx: *mut ffi::EVP_MD_CTX, - pkey_ctx: *mut ffi::EVP_PKEY_CTX, - pkey_pd: PhantomData<&'a PKeyRef>, -} - -impl<'a> Drop for Signer<'a> { - fn drop(&mut self) { - // pkey_ctx is owned by the md_ctx, so no need to explicitly free it. - unsafe { - EVP_MD_CTX_free(self.md_ctx); - } - } -} - -impl<'a> Signer<'a> { - /// Creates a new `Signer`. - /// - /// OpenSSL documentation at [`EVP_DigestSignInit`]. - /// - /// [`EVP_DigestSignInit`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestSignInit.html - pub fn new(type_: MessageDigest, pkey: &'a PKeyRef) -> Result, ErrorStack> { - unsafe { - ffi::init(); - - let ctx = cvt_p(EVP_MD_CTX_new())?; - let mut pctx: *mut ffi::EVP_PKEY_CTX = ptr::null_mut(); - let r = ffi::EVP_DigestSignInit( - ctx, - &mut pctx, - type_.as_ptr(), - ptr::null_mut(), - pkey.as_ptr(), - ); - if r != 1 { - EVP_MD_CTX_free(ctx); - return Err(ErrorStack::get()); - } - - assert!(!pctx.is_null()); - - Ok(Signer { - md_ctx: ctx, - pkey_ctx: pctx, - pkey_pd: PhantomData, - }) - } - } - - /// Returns a shared reference to the `PKeyCtx` associated with the `Signer`. - pub fn pkey_ctx(&self) -> &PKeyCtxRef { - unsafe { PKeyCtxRef::from_ptr(self.pkey_ctx) } - } - - /// Returns a mutable reference to the `PKeyCtx` associated with the `Signer`. - pub fn pkey_ctx_mut(&mut self) -> &mut PKeyCtxRef { - unsafe { PKeyCtxRef::from_ptr_mut(self.pkey_ctx) } - } - - /// Feeds more data into the `Signer`. - /// - /// OpenSSL documentation at [`EVP_DigestUpdate`]. - /// - /// [`EVP_DigestUpdate`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestInit.html - pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EVP_DigestUpdate( - self.md_ctx, - buf.as_ptr() as *const _, - buf.len(), - )).map(|_| ()) - } - } - - /// Computes an upper bound on the signature length. - /// - /// The actual signature may be shorter than this value. Check the return value of - /// `sign` to get the exact length. - /// - /// OpenSSL documentation at [`EVP_DigestSignFinal`]. - /// - /// [`EVP_DigestSignFinal`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_DigestSignFinal.html - pub fn len(&self) -> Result { - unsafe { - let mut len = 0; - cvt(ffi::EVP_DigestSignFinal( - self.md_ctx, - ptr::null_mut(), - &mut len, - ))?; - Ok(len) - } - } - - /// Writes the signature into the provided buffer, returning the number of bytes written. - /// - /// This method will fail if the buffer is not large enough for the signature. Use the `len` - /// method to get an upper bound on the required size. - /// - /// OpenSSL documentation at [`EVP_DigestSignFinal`]. - /// - /// [`EVP_DigestSignFinal`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_DigestSignFinal.html - pub fn sign(&self, buf: &mut [u8]) -> Result { - unsafe { - let mut len = buf.len(); - cvt(ffi::EVP_DigestSignFinal( - self.md_ctx, - buf.as_mut_ptr() as *mut _, - &mut len, - ))?; - Ok(len) - } - } - - /// Returns the signature. - /// - /// This is a simple convenience wrapper over `len` and `sign`. - pub fn sign_to_vec(&self) -> Result, ErrorStack> { - let mut buf = vec![0; self.len()?]; - let len = self.sign(&mut buf)?; - // The advertised length is not always equal to the real length for things like DSA - buf.truncate(len); - Ok(buf) - } - - #[deprecated(since = "0.9.23", note = "renamed to sign_to_vec")] - pub fn finish(&self) -> Result, ErrorStack> { - self.sign_to_vec() - } -} - -impl<'a> Write for Signer<'a> { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.update(buf)?; - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -pub struct Verifier<'a> { - md_ctx: *mut ffi::EVP_MD_CTX, - pkey_ctx: *mut ffi::EVP_PKEY_CTX, - pkey_pd: PhantomData<&'a PKeyRef>, -} - -impl<'a> Drop for Verifier<'a> { - fn drop(&mut self) { - // pkey_ctx is owned by the md_ctx, so no need to explicitly free it. - unsafe { - EVP_MD_CTX_free(self.md_ctx); - } - } -} - -/// A type which verifies cryptographic signatures of data. -impl<'a> Verifier<'a> { - /// Creates a new `Verifier`. - /// - /// OpenSSL documentation at [`EVP_DigestVerifyInit`]. - /// - /// [`EVP_DigestVerifyInit`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestVerifyInit.html - pub fn new(type_: MessageDigest, pkey: &'a PKeyRef) -> Result, ErrorStack> { - unsafe { - ffi::init(); - - let ctx = cvt_p(EVP_MD_CTX_new())?; - let mut pctx: *mut ffi::EVP_PKEY_CTX = ptr::null_mut(); - let r = ffi::EVP_DigestVerifyInit( - ctx, - &mut pctx, - type_.as_ptr(), - ptr::null_mut(), - pkey.as_ptr(), - ); - if r != 1 { - EVP_MD_CTX_free(ctx); - return Err(ErrorStack::get()); - } - - assert!(!pctx.is_null()); - - Ok(Verifier { - md_ctx: ctx, - pkey_ctx: pctx, - pkey_pd: PhantomData, - }) - } - } - - /// Returns a shared reference to the `PKeyCtx` associated with the `Verifier`. - pub fn pkey_ctx(&self) -> &PKeyCtxRef { - unsafe { PKeyCtxRef::from_ptr(self.pkey_ctx) } - } - - /// Returns a mutable reference to the `PKeyCtx` associated with the `Verifier`. - pub fn pkey_ctx_mut(&mut self) -> &mut PKeyCtxRef { - unsafe { PKeyCtxRef::from_ptr_mut(self.pkey_ctx) } - } - - /// Feeds more data into the `Verifier`. - /// - /// OpenSSL documentation at [`EVP_DigestUpdate`]. - /// - /// [`EVP_DigestUpdate`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestInit.html - pub fn update(&mut self, buf: &[u8]) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::EVP_DigestUpdate( - self.md_ctx, - buf.as_ptr() as *const _, - buf.len(), - )).map(|_| ()) - } - } - - /// Determines if the data fed into the `Verifier` matches the provided signature. - /// - /// OpenSSL documentation at [`EVP_DigestVerifyFinal`]. - /// - /// [`EVP_DigestVerifyFinal`]: https://www.openssl.org/docs/manmaster/man3/EVP_DigestVerifyFinal.html - pub fn verify(&self, signature: &[u8]) -> Result { - unsafe { - let r = - EVP_DigestVerifyFinal(self.md_ctx, signature.as_ptr() as *const _, signature.len()); - match r { - 1 => Ok(true), - 0 => { - ErrorStack::get(); // discard error stack - Ok(false) - } - _ => Err(ErrorStack::get()), - } - } - } - - #[deprecated(since = "0.9.23", note = "renamed to `verify`")] - pub fn finish(&self, signature: &[u8]) -> Result { - self.verify(signature) - } -} - -impl<'a> Write for Verifier<'a> { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.update(buf)?; - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -#[cfg(not(ossl101))] -use ffi::EVP_DigestVerifyFinal; - -#[cfg(ossl101)] -#[allow(bad_style)] -unsafe fn EVP_DigestVerifyFinal( - ctx: *mut ffi::EVP_MD_CTX, - sigret: *const ::libc::c_uchar, - siglen: ::libc::size_t, -) -> ::libc::c_int { - ffi::EVP_DigestVerifyFinal(ctx, sigret as *mut _, siglen) -} - -#[cfg(test)] -mod test { - use hex::{FromHex, ToHex}; - use std::iter; - - use hash::MessageDigest; - use sign::{Signer, Verifier}; - use ec::{EcGroup, EcKey}; - use nid; - use rsa::{PKCS1_PADDING, Rsa}; - use dsa::Dsa; - use pkey::PKey; - - const INPUT: &'static str = - "65794a68624763694f694a53557a49314e694a392e65794a7063334d694f694a71623255694c41304b49434a6c\ - 654841694f6a457a4d4441344d546b7a4f44417344516f67496d6830644841364c79396c654746746347786c4c\ - 6d4e76625339706331397962323930496a7030636e566c6651"; - - const SIGNATURE: &'static str = - "702e218943e88fd11eb5d82dbf7845f34106ae1b81fff7731116add1717d83656d420afd3c96eedd73a2663e51\ - 66687b000b87226e0187ed1073f945e582adfcef16d85a798ee8c66ddb3db8975b17d09402beedd5d9d9700710\ - 8db28160d5f8040ca7445762b81fbe7ff9d92e0ae76f24f25b33bbe6f44ae61eb1040acb20044d3ef9128ed401\ - 30795bd4bd3b41eecad066ab651981fde48df77f372dc38b9fafdd3befb18b5da3cc3c2eb02f9e3a41d612caad\ - 15911273a05f23b9e838faaf849d698429ef5a1e88798236c3d40e604522a544c8f27a7a2db80663d16cf7caea\ - 56de405cb2215a45b2c25566b55ac1a748a070dfc8a32a469543d019eefb47"; - - #[test] - fn rsa_sign() { - let key = include_bytes!("../test/rsa.pem"); - let private_key = Rsa::private_key_from_pem(key).unwrap(); - let pkey = PKey::from_rsa(private_key).unwrap(); - - let mut signer = Signer::new(MessageDigest::sha256(), &pkey).unwrap(); - assert_eq!(signer.pkey_ctx_mut().rsa_padding().unwrap(), PKCS1_PADDING); - signer - .pkey_ctx_mut() - .set_rsa_padding(PKCS1_PADDING) - .unwrap(); - signer.update(&Vec::from_hex(INPUT).unwrap()).unwrap(); - let result = signer.sign_to_vec().unwrap(); - - assert_eq!(result.to_hex(), SIGNATURE); - } - - #[test] - fn rsa_verify_ok() { - let key = include_bytes!("../test/rsa.pem"); - let private_key = Rsa::private_key_from_pem(key).unwrap(); - let pkey = PKey::from_rsa(private_key).unwrap(); - - let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey).unwrap(); - assert_eq!( - verifier.pkey_ctx_mut().rsa_padding().unwrap(), - PKCS1_PADDING - ); - verifier.update(&Vec::from_hex(INPUT).unwrap()).unwrap(); - assert!(verifier.verify(&Vec::from_hex(SIGNATURE).unwrap()).unwrap()); - } - - #[test] - fn rsa_verify_invalid() { - let key = include_bytes!("../test/rsa.pem"); - let private_key = Rsa::private_key_from_pem(key).unwrap(); - let pkey = PKey::from_rsa(private_key).unwrap(); - - let mut verifier = Verifier::new(MessageDigest::sha256(), &pkey).unwrap(); - verifier.update(&Vec::from_hex(INPUT).unwrap()).unwrap(); - verifier.update(b"foobar").unwrap(); - assert!(!verifier.verify(&Vec::from_hex(SIGNATURE).unwrap()).unwrap()); - } - - #[test] - pub fn dsa_sign_verify() { - let input: Vec = (0..25).cycle().take(1024).collect(); - - let private_key = { - let key = include_bytes!("../test/dsa.pem"); - PKey::from_dsa(Dsa::private_key_from_pem(key).unwrap()).unwrap() - }; - - let public_key = { - let key = include_bytes!("../test/dsa.pem.pub"); - PKey::from_dsa(Dsa::public_key_from_pem(key).unwrap()).unwrap() - }; - - let mut signer = Signer::new(MessageDigest::sha1(), &private_key).unwrap(); - signer.update(&input).unwrap(); - let sig = signer.sign_to_vec().unwrap(); - - let mut verifier = Verifier::new(MessageDigest::sha1(), &public_key).unwrap(); - verifier.update(&input).unwrap(); - assert!(verifier.verify(&sig).unwrap()); - } - - #[test] - pub fn dsa_sign_verify_fail() { - let input: Vec = (0..25).cycle().take(1024).collect(); - - let private_key = { - let key = include_bytes!("../test/dsa.pem"); - PKey::from_dsa(Dsa::private_key_from_pem(key).unwrap()).unwrap() - }; - - let public_key = { - let key = include_bytes!("../test/dsa.pem.pub"); - PKey::from_dsa(Dsa::public_key_from_pem(key).unwrap()).unwrap() - }; - - let mut signer = Signer::new(MessageDigest::sha1(), &private_key).unwrap(); - signer.update(&input).unwrap(); - let mut sig = signer.sign_to_vec().unwrap(); - sig[0] -= 1; - - let mut verifier = Verifier::new(MessageDigest::sha1(), &public_key).unwrap(); - verifier.update(&input).unwrap(); - match verifier.verify(&sig) { - Ok(true) => panic!("unexpected success"), - Ok(false) | Err(_) => {} - } - } - - fn test_hmac(ty: MessageDigest, tests: &[(Vec, Vec, Vec)]) { - for &(ref key, ref data, ref res) in tests.iter() { - let pkey = PKey::hmac(key).unwrap(); - let mut signer = Signer::new(ty, &pkey).unwrap(); - signer.update(data).unwrap(); - assert_eq!(signer.sign_to_vec().unwrap(), *res); - } - } - - #[test] - fn hmac_md5() { - // test vectors from RFC 2202 - let tests: [(Vec, Vec, Vec); 7] = [ - ( - iter::repeat(0x0b_u8).take(16).collect(), - b"Hi There".to_vec(), - Vec::from_hex("9294727a3638bb1c13f48ef8158bfc9d").unwrap(), - ), - ( - b"Jefe".to_vec(), - b"what do ya want for nothing?".to_vec(), - Vec::from_hex("750c783e6ab0b503eaa86e310a5db738").unwrap(), - ), - ( - iter::repeat(0xaa_u8).take(16).collect(), - iter::repeat(0xdd_u8).take(50).collect(), - Vec::from_hex("56be34521d144c88dbb8c733f0e8b3f6").unwrap(), - ), - ( - Vec::from_hex("0102030405060708090a0b0c0d0e0f10111213141516171819").unwrap(), - iter::repeat(0xcd_u8).take(50).collect(), - Vec::from_hex("697eaf0aca3a3aea3a75164746ffaa79").unwrap(), - ), - ( - iter::repeat(0x0c_u8).take(16).collect(), - b"Test With Truncation".to_vec(), - Vec::from_hex("56461ef2342edc00f9bab995690efd4c").unwrap(), - ), - ( - iter::repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), - Vec::from_hex("6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd").unwrap(), - ), - ( - iter::repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key \ - and Larger Than One Block-Size Data" - .to_vec(), - Vec::from_hex("6f630fad67cda0ee1fb1f562db3aa53e").unwrap(), - ), - ]; - - test_hmac(MessageDigest::md5(), &tests); - } - - #[test] - fn hmac_sha1() { - // test vectors from RFC 2202 - let tests: [(Vec, Vec, Vec); 7] = [ - ( - iter::repeat(0x0b_u8).take(20).collect(), - b"Hi There".to_vec(), - Vec::from_hex("b617318655057264e28bc0b6fb378c8ef146be00").unwrap(), - ), - ( - b"Jefe".to_vec(), - b"what do ya want for nothing?".to_vec(), - Vec::from_hex("effcdf6ae5eb2fa2d27416d5f184df9c259a7c79").unwrap(), - ), - ( - iter::repeat(0xaa_u8).take(20).collect(), - iter::repeat(0xdd_u8).take(50).collect(), - Vec::from_hex("125d7342b9ac11cd91a39af48aa17b4f63f175d3").unwrap(), - ), - ( - Vec::from_hex("0102030405060708090a0b0c0d0e0f10111213141516171819").unwrap(), - iter::repeat(0xcd_u8).take(50).collect(), - Vec::from_hex("4c9007f4026250c6bc8414f9bf50c86c2d7235da").unwrap(), - ), - ( - iter::repeat(0x0c_u8).take(20).collect(), - b"Test With Truncation".to_vec(), - Vec::from_hex("4c1a03424b55e07fe7f27be1d58bb9324a9a5a04").unwrap(), - ), - ( - iter::repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key - Hash Key First".to_vec(), - Vec::from_hex("aa4ae5e15272d00e95705637ce8a3b55ed402112").unwrap(), - ), - ( - iter::repeat(0xaa_u8).take(80).collect(), - b"Test Using Larger Than Block-Size Key \ - and Larger Than One Block-Size Data" - .to_vec(), - Vec::from_hex("e8e99d0f45237d786d6bbaa7965c7808bbff1a91").unwrap(), - ), - ]; - - test_hmac(MessageDigest::sha1(), &tests); - } - - #[test] - fn ec() { - let group = EcGroup::from_curve_name(nid::X9_62_PRIME256V1).unwrap(); - let key = EcKey::generate(&group).unwrap(); - let key = PKey::from_ec_key(key).unwrap(); - - let mut signer = Signer::new(MessageDigest::sha256(), &key).unwrap(); - signer.update(b"hello world").unwrap(); - let signature = signer.sign_to_vec().unwrap(); - - let mut verifier = Verifier::new(MessageDigest::sha256(), &key).unwrap(); - verifier.update(b"hello world").unwrap(); - assert!(verifier.verify(&signature).unwrap()); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/bio.rs cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/bio.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/bio.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/bio.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,279 +0,0 @@ -use libc::{c_char, c_int, c_long, c_void, strlen}; -use ffi::{BIO, BIO_CTRL_FLUSH, BIO_new, BIO_clear_retry_flags, BIO_set_retry_read, - BIO_set_retry_write}; -use std::any::Any; -use std::io; -use std::io::prelude::*; -use std::mem; -use std::panic::{AssertUnwindSafe, catch_unwind}; -use std::ptr; -use std::slice; - -use cvt_p; -use error::ErrorStack; - -pub struct StreamState { - pub stream: S, - pub error: Option, - pub panic: Option>, -} - -/// Safe wrapper for BIO_METHOD -pub struct BioMethod(compat::BIO_METHOD); - -impl BioMethod { - fn new() -> BioMethod { - BioMethod(compat::BIO_METHOD::new::()) - } -} - -unsafe impl Sync for BioMethod {} -unsafe impl Send for BioMethod {} - -pub fn new(stream: S) -> Result<(*mut BIO, BioMethod), ErrorStack> { - let method = BioMethod::new::(); - - let state = Box::new(StreamState { - stream: stream, - error: None, - panic: None, - }); - - unsafe { - let bio = cvt_p(BIO_new(method.0.get()))?; - compat::BIO_set_data(bio, Box::into_raw(state) as *mut _); - compat::BIO_set_init(bio, 1); - - return Ok((bio, method)); - } -} - -pub unsafe fn take_error(bio: *mut BIO) -> Option { - let state = state::(bio); - state.error.take() -} - -pub unsafe fn take_panic(bio: *mut BIO) -> Option> { - let state = state::(bio); - state.panic.take() -} - -pub unsafe fn get_ref<'a, S: 'a>(bio: *mut BIO) -> &'a S { - let state: &'a StreamState = mem::transmute(compat::BIO_get_data(bio)); - &state.stream -} - -pub unsafe fn get_mut<'a, S: 'a>(bio: *mut BIO) -> &'a mut S { - &mut state(bio).stream -} - -unsafe fn state<'a, S: 'a>(bio: *mut BIO) -> &'a mut StreamState { - &mut *(compat::BIO_get_data(bio) as *mut _) -} - -unsafe extern "C" fn bwrite(bio: *mut BIO, buf: *const c_char, len: c_int) -> c_int { - BIO_clear_retry_flags(bio); - - let state = state::(bio); - let buf = slice::from_raw_parts(buf as *const _, len as usize); - - match catch_unwind(AssertUnwindSafe(|| state.stream.write(buf))) { - Ok(Ok(len)) => len as c_int, - Ok(Err(err)) => { - if retriable_error(&err) { - BIO_set_retry_write(bio); - } - state.error = Some(err); - -1 - } - Err(err) => { - state.panic = Some(err); - -1 - } - } -} - -unsafe extern "C" fn bread(bio: *mut BIO, buf: *mut c_char, len: c_int) -> c_int { - BIO_clear_retry_flags(bio); - - let state = state::(bio); - let buf = slice::from_raw_parts_mut(buf as *mut _, len as usize); - - match catch_unwind(AssertUnwindSafe(|| state.stream.read(buf))) { - Ok(Ok(len)) => len as c_int, - Ok(Err(err)) => { - if retriable_error(&err) { - BIO_set_retry_read(bio); - } - state.error = Some(err); - -1 - } - Err(err) => { - state.panic = Some(err); - -1 - } - } -} - -fn retriable_error(err: &io::Error) -> bool { - match err.kind() { - io::ErrorKind::WouldBlock | - io::ErrorKind::NotConnected => true, - _ => false, - } -} - -unsafe extern "C" fn bputs(bio: *mut BIO, s: *const c_char) -> c_int { - bwrite::(bio, s, strlen(s) as c_int) -} - -unsafe extern "C" fn ctrl( - bio: *mut BIO, - cmd: c_int, - _num: c_long, - _ptr: *mut c_void, -) -> c_long { - if cmd == BIO_CTRL_FLUSH { - let state = state::(bio); - - match catch_unwind(AssertUnwindSafe(|| state.stream.flush())) { - Ok(Ok(())) => 1, - Ok(Err(err)) => { - state.error = Some(err); - 0 - } - Err(err) => { - state.panic = Some(err); - 0 - } - } - } else { - 0 - } -} - -unsafe extern "C" fn create(bio: *mut BIO) -> c_int { - compat::BIO_set_init(bio, 0); - compat::BIO_set_num(bio, 0); - compat::BIO_set_data(bio, ptr::null_mut()); - compat::BIO_set_flags(bio, 0); - 1 -} - -unsafe extern "C" fn destroy(bio: *mut BIO) -> c_int { - if bio.is_null() { - return 0; - } - - let data = compat::BIO_get_data(bio); - assert!(!data.is_null()); - Box::>::from_raw(data as *mut _); - compat::BIO_set_data(bio, ptr::null_mut()); - compat::BIO_set_init(bio, 0); - 1 -} - -#[cfg(ossl110)] -#[allow(bad_style)] -mod compat { - use std::io::{Read, Write}; - - use libc::c_int; - use ffi; - pub use ffi::{BIO_set_init, BIO_set_flags, BIO_set_data, BIO_get_data}; - - pub unsafe fn BIO_set_num(_bio: *mut ffi::BIO, _num: c_int) {} - - pub struct BIO_METHOD(*mut ffi::BIO_METHOD); - - impl BIO_METHOD { - pub fn new() -> BIO_METHOD { - unsafe { - let ptr = ffi::BIO_meth_new(ffi::BIO_TYPE_NONE, b"rust\0".as_ptr() as *const _); - assert!(!ptr.is_null()); - let ret = BIO_METHOD(ptr); - assert!(ffi::BIO_meth_set_write(ptr, super::bwrite::) != 0); - assert!(ffi::BIO_meth_set_read(ptr, super::bread::) != 0); - assert!(ffi::BIO_meth_set_puts(ptr, super::bputs::) != 0); - assert!(ffi::BIO_meth_set_ctrl(ptr, super::ctrl::) != 0); - assert!(ffi::BIO_meth_set_create(ptr, super::create) != 0); - assert!(ffi::BIO_meth_set_destroy(ptr, super::destroy::) != 0); - return ret; - } - } - - pub fn get(&self) -> *mut ffi::BIO_METHOD { - self.0 - } - } - - impl Drop for BIO_METHOD { - fn drop(&mut self) { - unsafe { - ffi::BIO_meth_free(self.0); - } - } - } -} - -#[cfg(ossl10x)] -#[allow(bad_style)] -mod compat { - use std::io::{Read, Write}; - - use ffi; - use libc::{c_int, c_void}; - - pub struct BIO_METHOD(*mut ffi::BIO_METHOD); - - impl BIO_METHOD { - pub fn new() -> BIO_METHOD { - let ptr = Box::new(ffi::BIO_METHOD { - type_: ffi::BIO_TYPE_NONE, - name: b"rust\0".as_ptr() as *const _, - bwrite: Some(super::bwrite::), - bread: Some(super::bread::), - bputs: Some(super::bputs::), - bgets: None, - ctrl: Some(super::ctrl::), - create: Some(super::create), - destroy: Some(super::destroy::), - callback_ctrl: None, - }); - - BIO_METHOD(Box::into_raw(ptr)) - } - - pub fn get(&self) -> *mut ffi::BIO_METHOD { - self.0 - } - } - - impl Drop for BIO_METHOD { - fn drop(&mut self) { - unsafe { - Box::::from_raw(self.0); - } - } - } - - pub unsafe fn BIO_set_init(bio: *mut ffi::BIO, init: c_int) { - (*bio).init = init; - } - - pub unsafe fn BIO_set_flags(bio: *mut ffi::BIO, flags: c_int) { - (*bio).flags = flags; - } - - pub unsafe fn BIO_get_data(bio: *mut ffi::BIO) -> *mut c_void { - (*bio).ptr - } - - pub unsafe fn BIO_set_data(bio: *mut ffi::BIO, data: *mut c_void) { - (*bio).ptr = data; - } - - pub unsafe fn BIO_set_num(bio: *mut ffi::BIO, num: c_int) { - (*bio).num = num; - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/callbacks.rs cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/callbacks.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/callbacks.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/callbacks.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,339 +0,0 @@ -use ffi; -use libc::{c_int, c_uint, c_char, c_uchar, c_void}; -use std::any::Any; -use std::ffi::CStr; -use std::ptr; -use std::slice; -use std::mem; -use foreign_types::ForeignTypeRef; - -use error::ErrorStack; -use dh::Dh; -#[cfg(any(all(feature = "v101", ossl101), all(feature = "v102", ossl102)))] -use ec_key::EcKey; -use ssl::{get_callback_idx, get_ssl_callback_idx, SslRef, SniError, NPN_PROTOS_IDX}; -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -use ssl::ALPN_PROTOS_IDX; -use x509::X509StoreContextRef; - -pub extern "C" fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int -where - F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send, -{ - unsafe { - let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); - let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx); - let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); - let verify = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); - let verify: &F = &*(verify as *mut F); - - let ctx = X509StoreContextRef::from_ptr(x509_ctx); - - verify(preverify_ok != 0, ctx) as c_int - } -} - -#[cfg(not(osslconf = "OPENSSL_NO_PSK"))] -pub extern "C" fn raw_psk( - ssl: *mut ffi::SSL, - hint: *const c_char, - identity: *mut c_char, - max_identity_len: c_uint, - psk: *mut c_uchar, - max_psk_len: c_uint, -) -> c_uint -where - F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result - + Any - + 'static - + Sync - + Send, -{ - unsafe { - let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); - let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); - let ssl = SslRef::from_ptr_mut(ssl); - let callback = &*(callback as *mut F); - let hint = if hint != ptr::null() { - Some(CStr::from_ptr(hint).to_bytes()) - } else { - None - }; - // Give the callback mutable slices into which it can write the identity and psk. - let identity_sl = slice::from_raw_parts_mut(identity as *mut u8, max_identity_len as usize); - let psk_sl = slice::from_raw_parts_mut(psk as *mut u8, max_psk_len as usize); - match callback(ssl, hint, identity_sl, psk_sl) { - Ok(psk_len) => psk_len as u32, - _ => 0, - } - } -} - -pub extern "C" fn ssl_raw_verify( - preverify_ok: c_int, - x509_ctx: *mut ffi::X509_STORE_CTX, -) -> c_int -where - F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send, -{ - unsafe { - let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx(); - let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx); - let verify = ffi::SSL_get_ex_data(ssl as *const _, get_ssl_callback_idx::()); - let verify: &F = &*(verify as *mut F); - - let ctx = X509StoreContextRef::from_ptr(x509_ctx); - - verify(preverify_ok != 0, ctx) as c_int - } -} - -pub extern "C" fn raw_sni(ssl: *mut ffi::SSL, al: *mut c_int, _arg: *mut c_void) -> c_int -where - F: Fn(&mut SslRef) -> Result<(), SniError> + Any + 'static + Sync + Send, -{ - unsafe { - let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); - let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); - let callback: &F = &*(callback as *mut F); - let ssl = SslRef::from_ptr_mut(ssl); - - match callback(ssl) { - Ok(()) => ffi::SSL_TLSEXT_ERR_OK, - Err(SniError::Fatal(e)) => { - *al = e; - ffi::SSL_TLSEXT_ERR_ALERT_FATAL - } - Err(SniError::Warning(e)) => { - *al = e; - ffi::SSL_TLSEXT_ERR_ALERT_WARNING - } - Err(SniError::NoAck) => ffi::SSL_TLSEXT_ERR_NOACK, - } - } -} - -pub unsafe fn select_proto_using( - ssl: *mut ffi::SSL, - out: *mut *mut c_uchar, - outlen: *mut c_uchar, - inbuf: *const c_uchar, - inlen: c_uint, - ex_data: c_int, -) -> c_int { - - // First, get the list of protocols (that the client should support) saved in the context - // extra data. - let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); - let protocols = ffi::SSL_CTX_get_ex_data(ssl_ctx, ex_data); - let protocols: &Vec = &*(protocols as *mut Vec); - // Prepare the client list parameters to be passed to the OpenSSL function... - let client = protocols.as_ptr(); - let client_len = protocols.len() as c_uint; - // Finally, let OpenSSL find a protocol to be used, by matching the given server and - // client lists. - if ffi::SSL_select_next_proto(out, outlen, inbuf, inlen, client, client_len) != - ffi::OPENSSL_NPN_NEGOTIATED - { - ffi::SSL_TLSEXT_ERR_NOACK - } else { - ffi::SSL_TLSEXT_ERR_OK - } -} - -/// The function is given as the callback to `SSL_CTX_set_next_proto_select_cb`. -/// -/// It chooses the protocol that the client wishes to use, out of the given list of protocols -/// supported by the server. It achieves this by delegating to the `SSL_select_next_proto` -/// function. The list of protocols supported by the client is found in the extra data of the -/// OpenSSL context. -pub extern "C" fn raw_next_proto_select_cb( - ssl: *mut ffi::SSL, - out: *mut *mut c_uchar, - outlen: *mut c_uchar, - inbuf: *const c_uchar, - inlen: c_uint, - _arg: *mut c_void, -) -> c_int { - unsafe { select_proto_using(ssl, out, outlen, inbuf, inlen, *NPN_PROTOS_IDX) } -} - -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -pub extern "C" fn raw_alpn_select_cb( - ssl: *mut ffi::SSL, - out: *mut *const c_uchar, - outlen: *mut c_uchar, - inbuf: *const c_uchar, - inlen: c_uint, - _arg: *mut c_void, -) -> c_int { - unsafe { select_proto_using(ssl, out as *mut _, outlen, inbuf, inlen, *ALPN_PROTOS_IDX) } -} - -pub unsafe extern "C" fn raw_tmp_dh( - ssl: *mut ffi::SSL, - is_export: c_int, - keylength: c_int, -) -> *mut ffi::DH -where - F: Fn(&mut SslRef, bool, u32) -> Result + Any + 'static + Sync + Send, -{ - let ctx = ffi::SSL_get_SSL_CTX(ssl); - let callback = ffi::SSL_CTX_get_ex_data(ctx, get_callback_idx::()); - let callback = &*(callback as *mut F); - - let ssl = SslRef::from_ptr_mut(ssl); - match callback(ssl, is_export != 0, keylength as u32) { - Ok(dh) => { - let ptr = dh.as_ptr(); - mem::forget(dh); - ptr - } - Err(_) => { - // FIXME reset error stack - ptr::null_mut() - } - } -} - -#[cfg(any(all(feature = "v101", ossl101), all(feature = "v102", ossl102)))] -pub unsafe extern "C" fn raw_tmp_ecdh( - ssl: *mut ffi::SSL, - is_export: c_int, - keylength: c_int, -) -> *mut ffi::EC_KEY -where - F: Fn(&mut SslRef, bool, u32) -> Result + Any + 'static + Sync + Send, -{ - let ctx = ffi::SSL_get_SSL_CTX(ssl); - let callback = ffi::SSL_CTX_get_ex_data(ctx, get_callback_idx::()); - let callback = &*(callback as *mut F); - - let ssl = SslRef::from_ptr_mut(ssl); - match callback(ssl, is_export != 0, keylength as u32) { - Ok(ec_key) => { - let ptr = ec_key.as_ptr(); - mem::forget(ec_key); - ptr - } - Err(_) => { - // FIXME reset error stack - ptr::null_mut() - } - } -} - -pub unsafe extern "C" fn raw_tmp_dh_ssl( - ssl: *mut ffi::SSL, - is_export: c_int, - keylength: c_int, -) -> *mut ffi::DH -where - F: Fn(&mut SslRef, bool, u32) -> Result + Any + 'static + Sync + Send, -{ - let callback = ffi::SSL_get_ex_data(ssl, get_ssl_callback_idx::()); - let callback = &*(callback as *mut F); - - let ssl = SslRef::from_ptr_mut(ssl); - match callback(ssl, is_export != 0, keylength as u32) { - Ok(dh) => { - let ptr = dh.as_ptr(); - mem::forget(dh); - ptr - } - Err(_) => { - // FIXME reset error stack - ptr::null_mut() - } - } -} - -#[cfg(any(all(feature = "v101", ossl101), all(feature = "v102", ossl102)))] -pub unsafe extern "C" fn raw_tmp_ecdh_ssl( - ssl: *mut ffi::SSL, - is_export: c_int, - keylength: c_int, -) -> *mut ffi::EC_KEY -where - F: Fn(&mut SslRef, bool, u32) -> Result + Any + 'static + Sync + Send, -{ - let callback = ffi::SSL_get_ex_data(ssl, get_ssl_callback_idx::()); - let callback = &*(callback as *mut F); - - let ssl = SslRef::from_ptr_mut(ssl); - match callback(ssl, is_export != 0, keylength as u32) { - Ok(ec_key) => { - let ptr = ec_key.as_ptr(); - mem::forget(ec_key); - ptr - } - Err(_) => { - // FIXME reset error stack - ptr::null_mut() - } - } -} - -pub unsafe extern "C" fn raw_tlsext_status(ssl: *mut ffi::SSL, _: *mut c_void) -> c_int -where - F: Fn(&mut SslRef) -> Result + Any + 'static + Sync + Send, -{ - let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl as *const _); - let callback = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_callback_idx::()); - let callback = &*(callback as *mut F); - - let ssl = SslRef::from_ptr_mut(ssl); - let ret = callback(ssl); - - if ssl.is_server() { - match ret { - Ok(true) => ffi::SSL_TLSEXT_ERR_OK, - Ok(false) => ffi::SSL_TLSEXT_ERR_NOACK, - Err(_) => { - // FIXME reset error stack - ffi::SSL_TLSEXT_ERR_ALERT_FATAL - } - } - } else { - match ret { - Ok(true) => 1, - Ok(false) => 0, - Err(_) => { - // FIXME reset error stack - -1 - } - } - } -} - -/// The function is given as the callback to `SSL_CTX_set_next_protos_advertised_cb`. -/// -/// It causes the parameter `out` to point at a `*const c_uchar` instance that -/// represents the list of protocols that the server should advertise as those -/// that it supports. -/// The list of supported protocols is found in the extra data of the OpenSSL -/// context. -pub extern "C" fn raw_next_protos_advertise_cb( - ssl: *mut ffi::SSL, - out: *mut *const c_uchar, - outlen: *mut c_uint, - _arg: *mut c_void, -) -> c_int { - unsafe { - // First, get the list of (supported) protocols saved in the context extra data. - let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl); - let protocols = ffi::SSL_CTX_get_ex_data(ssl_ctx, *NPN_PROTOS_IDX); - if protocols.is_null() { - *out = b"".as_ptr(); - *outlen = 0; - } else { - // If the pointer is valid, put the pointer to the actual byte array into the - // output parameter `out`, as well as its length into `outlen`. - let protocols: &Vec = &*(protocols as *mut Vec); - *out = protocols.as_ptr(); - *outlen = protocols.len() as c_uint; - } - } - - ffi::SSL_TLSEXT_ERR_OK -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/connector.rs cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/connector.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/connector.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/connector.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,599 +0,0 @@ -use std::io::{Read, Write}; -use std::ops::{Deref, DerefMut}; - -use dh::Dh; -use error::ErrorStack; -use ssl::{self, HandshakeError, Ssl, SslRef, SslContext, SslContextBuilder, SslMethod, SslStream, - SSL_VERIFY_PEER}; -use pkey::PKeyRef; -use version; -use x509::X509Ref; - -#[cfg(ossl101)] -lazy_static! { - static ref HOSTNAME_IDX: ::ex_data::Index = Ssl::new_ex_index().unwrap(); -} - -// ffdhe2048 from https://wiki.mozilla.org/Security/Server_Side_TLS#ffdhe2048 -const DHPARAM_PEM: &'static str = " ------BEGIN DH PARAMETERS----- -MIIBCAKCAQEA//////////+t+FRYortKmq/cViAnPTzx2LnFg84tNpWp4TZBFGQz -+8yTnc4kmz75fS/jY2MMddj2gbICrsRhetPfHtXV/WVhJDP1H18GbtCFY2VVPe0a -87VXE15/V8k1mE8McODmi3fipona8+/och3xWKE2rec1MKzKT0g6eXq8CrGCsyT7 -YdEIqUuyyOP7uWrat2DX9GgdT0Kj3jlN9K5W7edjcrsZCwenyO4KbXCeAvzhzffi -7MA0BM0oNC9hkXL+nOmFg/+OTxIy7vKBg8P+OxtMb61zO7X8vC7CIAXFjvGDfRaD -ssbzSibBsu/6iGtCOGEoXJf//////////wIBAg== ------END DH PARAMETERS----- -"; - -fn ctx(method: SslMethod) -> Result { - let mut ctx = SslContextBuilder::new(method)?; - - let mut opts = ssl::SSL_OP_ALL; - opts &= !ssl::SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; - opts &= !ssl::SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; - opts |= ssl::SSL_OP_NO_TICKET; - opts |= ssl::SSL_OP_NO_COMPRESSION; - opts |= ssl::SSL_OP_NO_SSLV2; - opts |= ssl::SSL_OP_NO_SSLV3; - opts |= ssl::SSL_OP_SINGLE_DH_USE; - opts |= ssl::SSL_OP_SINGLE_ECDH_USE; - opts |= ssl::SSL_OP_CIPHER_SERVER_PREFERENCE; - ctx.set_options(opts); - - let mut mode = ssl::SSL_MODE_AUTO_RETRY | ssl::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER - | ssl::SSL_MODE_ENABLE_PARTIAL_WRITE; - - // This is quite a useful optimization for saving memory, but historically - // caused CVEs in OpenSSL pre-1.0.1h, according to - // https://bugs.python.org/issue25672 - if version::number() >= 0x1000108f { - mode |= ssl::SSL_MODE_RELEASE_BUFFERS; - } - - ctx.set_mode(mode); - - Ok(ctx) -} - -/// A builder for `SslConnector`s. -pub struct SslConnectorBuilder(SslContextBuilder); - -impl SslConnectorBuilder { - /// Creates a new builder for TLS connections. - /// - /// The default configuration is subject to change, and is currently derived from Python. - pub fn new(method: SslMethod) -> Result { - let mut ctx = ctx(method)?; - ctx.set_default_verify_paths()?; - // From https://github.com/python/cpython/blob/a170fa162dc03f0a014373349e548954fff2e567/Lib/ssl.py#L193 - ctx.set_cipher_list( - "TLS13-AES-256-GCM-SHA384:TLS13-CHACHA20-POLY1305-SHA256:\ - TLS13-AES-128-GCM-SHA256:\ - ECDH+AESGCM:ECDH+CHACHA20:DH+AESGCM:DH+CHACHA20:ECDH+AES256:DH+AES256:\ - ECDH+AES128:DH+AES:ECDH+HIGH:DH+HIGH:RSA+AESGCM:RSA+AES:RSA+HIGH:\ - !aNULL:!eNULL:!MD5:!3DES", - )?; - setup_verify(&mut ctx); - - Ok(SslConnectorBuilder(ctx)) - } - - #[deprecated(since = "0.9.23", - note = "SslConnectorBuilder now implements Deref")] - pub fn builder(&self) -> &SslContextBuilder { - self - } - - #[deprecated(since = "0.9.23", - note = "SslConnectorBuilder now implements DerefMut")] - pub fn builder_mut(&mut self) -> &mut SslContextBuilder { - self - } - - /// Consumes the builder, returning an `SslConnector`. - pub fn build(self) -> SslConnector { - SslConnector(self.0.build()) - } -} - -impl Deref for SslConnectorBuilder { - type Target = SslContextBuilder; - - fn deref(&self) -> &SslContextBuilder { - &self.0 - } -} - -impl DerefMut for SslConnectorBuilder { - fn deref_mut(&mut self) -> &mut SslContextBuilder { - &mut self.0 - } -} - -/// A type which wraps client-side streams in a TLS session. -/// -/// OpenSSL's default configuration is highly insecure. This connector manages the OpenSSL -/// structures, configuring cipher suites, session options, hostname verification, and more. -/// -/// OpenSSL's built in hostname verification is used when linking against OpenSSL 1.0.2 or 1.1.0, -/// and a custom implementation is used when linking against OpenSSL 1.0.1. -#[derive(Clone)] -pub struct SslConnector(SslContext); - -impl SslConnector { - /// Initiates a client-side TLS session on a stream. - /// - /// The domain is used for SNI and hostname verification. - pub fn connect(&self, domain: &str, stream: S) -> Result, HandshakeError> - where - S: Read + Write, - { - self.configure()?.connect(domain, stream) - } - - /// Initiates a client-side TLS session on a stream without performing hostname verification. - /// - /// # Warning - /// - /// You should think very carefully before you use this method. If hostname verification is not - /// used, *any* valid certificate for *any* site will be trusted for use from any other. This - /// introduces a significant vulnerability to man-in-the-middle attacks. - pub fn danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication< - S, - >( - &self, - stream: S, - ) -> Result, HandshakeError> - where - S: Read + Write, - { - self.configure()? - .danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication(stream) - } - - /// Returns a structure allowing for configuration of a single TLS session before connection. - pub fn configure(&self) -> Result { - Ssl::new(&self.0).map(ConnectConfiguration) - } -} - -/// A type which allows for configuration of a client-side TLS session before connection. -pub struct ConnectConfiguration(Ssl); - -impl ConnectConfiguration { - #[deprecated(since = "0.9.23", - note = "ConnectConfiguration now implements Deref")] - pub fn ssl(&self) -> &Ssl { - &self.0 - } - - #[deprecated(since = "0.9.23", - note = "ConnectConfiguration now implements DerefMut")] - pub fn ssl_mut(&mut self) -> &mut Ssl { - &mut self.0 - } - - /// Initiates a client-side TLS session on a stream. - /// - /// The domain is used for SNI and hostname verification. - pub fn connect(mut self, domain: &str, stream: S) -> Result, HandshakeError> - where - S: Read + Write, - { - self.0.set_hostname(domain)?; - setup_verify_hostname(&mut self.0, domain)?; - - self.0.connect(stream) - } - - /// Initiates a client-side TLS session on a stream without performing hostname verification. - /// - /// The verification configuration of the connector's `SslContext` is not overridden. - /// - /// # Warning - /// - /// You should think very carefully before you use this method. If hostname verification is not - /// used, *any* valid certificate for *any* site will be trusted for use from any other. This - /// introduces a significant vulnerability to man-in-the-middle attacks. - pub fn danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication< - S, - >( - self, - stream: S, - ) -> Result, HandshakeError> - where - S: Read + Write, - { - self.0.connect(stream) - } -} - -impl Deref for ConnectConfiguration { - type Target = SslRef; - - fn deref(&self) -> &SslRef { - &self.0 - } -} - -impl DerefMut for ConnectConfiguration { - fn deref_mut(&mut self) -> &mut SslRef { - &mut self.0 - } -} - -/// A builder for `SslAcceptor`s. -pub struct SslAcceptorBuilder(SslContextBuilder); - -impl SslAcceptorBuilder { - /// Creates a new builder configured to connect to non-legacy clients. This should generally be - /// considered a reasonable default choice. - /// - /// This corresponds to the intermediate configuration of Mozilla's server side TLS - /// recommendations. See its [documentation][docs] for more details on specifics. - /// - /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS - pub fn mozilla_intermediate( - method: SslMethod, - private_key: &PKeyRef, - certificate: &X509Ref, - chain: I, - ) -> Result - where - I: IntoIterator, - I::Item: AsRef, - { - let builder = SslAcceptorBuilder::mozilla_intermediate_raw(method)?; - builder.finish_setup(private_key, certificate, chain) - } - - /// Creates a new builder configured to connect to modern clients. - /// - /// This corresponds to the modern configuration of Mozilla's server side TLS recommendations. - /// See its [documentation][docs] for more details on specifics. - /// - /// [docs]: https://wiki.mozilla.org/Security/Server_Side_TLS - pub fn mozilla_modern( - method: SslMethod, - private_key: &PKeyRef, - certificate: &X509Ref, - chain: I, - ) -> Result - where - I: IntoIterator, - I::Item: AsRef, - { - let builder = SslAcceptorBuilder::mozilla_modern_raw(method)?; - builder.finish_setup(private_key, certificate, chain) - } - - /// Like `mozilla_intermediate`, but does not load the certificate chain and private key. - pub fn mozilla_intermediate_raw(method: SslMethod) -> Result { - let mut ctx = ctx(method)?; - let dh = Dh::from_pem(DHPARAM_PEM.as_bytes())?; - ctx.set_tmp_dh(&dh)?; - setup_curves(&mut ctx)?; - ctx.set_cipher_list( - "ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ - ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:\ - ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\ - DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-SHA256:\ - ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:\ - ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA:\ - ECDHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-RSA-AES256-SHA256:\ - DHE-RSA-AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:ECDHE-RSA-DES-CBC3-SHA:\ - EDH-RSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:\ - AES128-SHA:AES256-SHA:DES-CBC3-SHA:!DSS", - )?; - Ok(SslAcceptorBuilder(ctx)) - } - - /// Like `mozilla_modern`, but does not load the certificate chain and private key. - pub fn mozilla_modern_raw(method: SslMethod) -> Result { - let mut ctx = ctx(method)?; - setup_curves(&mut ctx)?; - ctx.set_cipher_list( - "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:\ - ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:\ - ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:\ - ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256", - )?; - Ok(SslAcceptorBuilder(ctx)) - } - - fn finish_setup( - mut self, - private_key: &PKeyRef, - certificate: &X509Ref, - chain: I, - ) -> Result - where - I: IntoIterator, - I::Item: AsRef, - { - self.0.set_private_key(private_key)?; - self.0.set_certificate(certificate)?; - self.0.check_private_key()?; - for cert in chain { - self.0.add_extra_chain_cert(cert.as_ref().to_owned())?; - } - Ok(self) - } - - #[deprecated(since = "0.9.23", - note = "SslAcceptorBuilder now implements Deref")] - pub fn builder(&self) -> &SslContextBuilder { - self - } - - #[deprecated(since = "0.9.23", - note = "SslAcceptorBuilder now implements DerefMut")] - pub fn builder_mut(&mut self) -> &mut SslContextBuilder { - self - } - - /// Consumes the builder, returning a `SslAcceptor`. - pub fn build(self) -> SslAcceptor { - SslAcceptor(self.0.build()) - } -} - -impl Deref for SslAcceptorBuilder { - type Target = SslContextBuilder; - - fn deref(&self) -> &SslContextBuilder { - &self.0 - } -} - -impl DerefMut for SslAcceptorBuilder { - fn deref_mut(&mut self) -> &mut SslContextBuilder { - &mut self.0 - } -} - -#[cfg(ossl101)] -fn setup_curves(ctx: &mut SslContextBuilder) -> Result<(), ErrorStack> { - use ec::EcKey; - use nid; - - let curve = EcKey::from_curve_name(nid::X9_62_PRIME256V1)?; - ctx.set_tmp_ecdh(&curve) -} - -#[cfg(ossl102)] -fn setup_curves(ctx: &mut SslContextBuilder) -> Result<(), ErrorStack> { - ctx._set_ecdh_auto(true) -} - -#[cfg(ossl110)] -fn setup_curves(_: &mut SslContextBuilder) -> Result<(), ErrorStack> { - Ok(()) -} - -/// A type which wraps server-side streams in a TLS session. -/// -/// OpenSSL's default configuration is highly insecure. This connector manages the OpenSSL -/// structures, configuring cipher suites, session options, and more. -#[derive(Clone)] -pub struct SslAcceptor(SslContext); - -impl SslAcceptor { - /// Initiates a server-side TLS session on a stream. - pub fn accept(&self, stream: S) -> Result, HandshakeError> - where - S: Read + Write, - { - let ssl = Ssl::new(&self.0)?; - ssl.accept(stream) - } -} - -#[cfg(any(ossl102, ossl110))] -fn setup_verify(ctx: &mut SslContextBuilder) { - ctx.set_verify(SSL_VERIFY_PEER); -} - -#[cfg(ossl101)] -fn setup_verify(ctx: &mut SslContextBuilder) { - ctx.set_verify_callback(SSL_VERIFY_PEER, |p, x509| { - let hostname = match x509.ssl() { - Ok(Some(ssl)) => ssl.ex_data(*HOSTNAME_IDX), - _ => None, - }; - match hostname { - Some(hostname) => verify::verify_callback(hostname, p, x509), - None => p, - } - }); -} - -#[cfg(any(ossl102, ossl110))] -fn setup_verify_hostname(ssl: &mut Ssl, domain: &str) -> Result<(), ErrorStack> { - let param = ssl._param_mut(); - param.set_hostflags(::verify::X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); - match domain.parse() { - Ok(ip) => param.set_ip(ip), - Err(_) => param.set_host(domain), - } -} - -#[cfg(ossl101)] -fn setup_verify_hostname(ssl: &mut Ssl, domain: &str) -> Result<(), ErrorStack> { - let domain = domain.to_string(); - ssl.set_ex_data(*HOSTNAME_IDX, domain); - Ok(()) -} - -#[cfg(ossl101)] -mod verify { - use std::net::IpAddr; - use std::str; - - use nid; - use x509::{GeneralName, X509NameRef, X509Ref, X509StoreContextRef}; - use stack::Stack; - - pub fn verify_callback( - domain: &str, - preverify_ok: bool, - x509_ctx: &X509StoreContextRef, - ) -> bool { - if !preverify_ok || x509_ctx.error_depth() != 0 { - return preverify_ok; - } - - match x509_ctx.current_cert() { - Some(x509) => verify_hostname(domain, &x509), - None => true, - } - } - - fn verify_hostname(domain: &str, cert: &X509Ref) -> bool { - match cert.subject_alt_names() { - Some(names) => verify_subject_alt_names(domain, names), - None => verify_subject_name(domain, &cert.subject_name()), - } - } - - fn verify_subject_alt_names(domain: &str, names: Stack) -> bool { - let ip = domain.parse(); - - for name in &names { - match ip { - Ok(ip) => { - if let Some(actual) = name.ipaddress() { - if matches_ip(&ip, actual) { - return true; - } - } - } - Err(_) => { - if let Some(pattern) = name.dnsname() { - if matches_dns(pattern, domain, false) { - return true; - } - } - } - } - } - - false - } - - fn verify_subject_name(domain: &str, subject_name: &X509NameRef) -> bool { - if let Some(pattern) = subject_name.entries_by_nid(nid::COMMONNAME).next() { - let pattern = match str::from_utf8(pattern.data().as_slice()) { - Ok(pattern) => pattern, - Err(_) => return false, - }; - - // Unlike with SANs, IP addresses in the subject name don't have a - // different encoding. We need to pass this down to matches_dns to - // disallow wildcard matches with bogus patterns like *.0.0.1 - let is_ip = domain.parse::().is_ok(); - - if matches_dns(&pattern, domain, is_ip) { - return true; - } - } - - false - } - - fn matches_dns(mut pattern: &str, mut hostname: &str, is_ip: bool) -> bool { - // first strip trailing . off of pattern and hostname to normalize - if pattern.ends_with('.') { - pattern = &pattern[..pattern.len() - 1]; - } - if hostname.ends_with('.') { - hostname = &hostname[..hostname.len() - 1]; - } - - matches_wildcard(pattern, hostname, is_ip).unwrap_or_else(|| pattern == hostname) - } - - fn matches_wildcard(pattern: &str, hostname: &str, is_ip: bool) -> Option { - // IP addresses and internationalized domains can't involved in wildcards - if is_ip || pattern.starts_with("xn--") { - return None; - } - - let wildcard_location = match pattern.find('*') { - Some(l) => l, - None => return None, - }; - - let mut dot_idxs = pattern.match_indices('.').map(|(l, _)| l); - let wildcard_end = match dot_idxs.next() { - Some(l) => l, - None => return None, - }; - - // Never match wildcards if the pattern has less than 2 '.'s (no *.com) - // - // This is a bit dubious, as it doesn't disallow other TLDs like *.co.uk. - // Chrome has a black- and white-list for this, but Firefox (via NSS) does - // the same thing we do here. - // - // The Public Suffix (https://www.publicsuffix.org/) list could - // potentially be used here, but it's both huge and updated frequently - // enough that management would be a PITA. - if dot_idxs.next().is_none() { - return None; - } - - // Wildcards can only be in the first component - if wildcard_location > wildcard_end { - return None; - } - - let hostname_label_end = match hostname.find('.') { - Some(l) => l, - None => return None, - }; - - // check that the non-wildcard parts are identical - if pattern[wildcard_end..] != hostname[hostname_label_end..] { - return Some(false); - } - - let wildcard_prefix = &pattern[..wildcard_location]; - let wildcard_suffix = &pattern[wildcard_location + 1..wildcard_end]; - - let hostname_label = &hostname[..hostname_label_end]; - - // check the prefix of the first label - if !hostname_label.starts_with(wildcard_prefix) { - return Some(false); - } - - // and the suffix - if !hostname_label[wildcard_prefix.len()..].ends_with(wildcard_suffix) { - return Some(false); - } - - Some(true) - } - - fn matches_ip(expected: &IpAddr, actual: &[u8]) -> bool { - match (expected, actual.len()) { - (&IpAddr::V4(ref addr), 4) => actual == addr.octets(), - (&IpAddr::V6(ref addr), 16) => { - let segments = [ - ((actual[0] as u16) << 8) | actual[1] as u16, - ((actual[2] as u16) << 8) | actual[3] as u16, - ((actual[4] as u16) << 8) | actual[5] as u16, - ((actual[6] as u16) << 8) | actual[7] as u16, - ((actual[8] as u16) << 8) | actual[9] as u16, - ((actual[10] as u16) << 8) | actual[11] as u16, - ((actual[12] as u16) << 8) | actual[13] as u16, - ((actual[14] as u16) << 8) | actual[15] as u16, - ]; - segments == addr.segments() - } - _ => false, - } - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/error.rs cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/error.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/error.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/error.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,150 +0,0 @@ -use std::any::Any; -use std::error; -use std::error::Error as StdError; -use std::fmt; -use std::io; - -use error::ErrorStack; -use ssl::MidHandshakeSslStream; - -/// An SSL error. -// FIXME this is missing variants -#[derive(Debug)] -pub enum Error { - /// The SSL session has been closed by the other end - ZeroReturn, - /// An attempt to read data from the underlying socket returned - /// `WouldBlock`. Wait for read readiness and reattempt the operation. - WantRead(io::Error), - /// An attempt to write data from the underlying socket returned - /// `WouldBlock`. Wait for write readiness and reattempt the operation. - WantWrite(io::Error), - /// The client certificate callback requested to be called again. - WantX509Lookup, - /// An error reported by the underlying stream. - Stream(io::Error), - /// An error in the OpenSSL library. - Ssl(ErrorStack), -} - -impl fmt::Display for Error { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.write_str(self.description())?; - if let Some(err) = self.cause() { - write!(fmt, ": {}", err) - } else { - Ok(()) - } - } -} - -impl error::Error for Error { - fn description(&self) -> &str { - match *self { - Error::ZeroReturn => "The SSL session was closed by the other end", - Error::WantRead(_) => "A read attempt returned a `WouldBlock` error", - Error::WantWrite(_) => "A write attempt returned a `WouldBlock` error", - Error::WantX509Lookup => "The client certificate callback requested to be called again", - Error::Stream(_) => "The underlying stream reported an error", - Error::Ssl(_) => "The OpenSSL library reported an error", - } - } - - fn cause(&self) -> Option<&error::Error> { - match *self { - Error::WantRead(ref err) => Some(err), - Error::WantWrite(ref err) => Some(err), - Error::Stream(ref err) => Some(err), - Error::Ssl(ref err) => Some(err), - _ => None, - } - } -} - -impl From for Error { - fn from(e: ErrorStack) -> Error { - Error::Ssl(e) - } -} - -/// An error indicating that the operation can be immediately retried. -/// -/// OpenSSL's [`SSL_read`] and [`SSL_write`] functions can return `SSL_ERROR_WANT_READ` even when -/// the underlying socket is performing blocking IO in certain cases. When this happens, the -/// the operation can be immediately retried. -/// -/// To signal this event, the `io::Error` inside of [`Error::WantRead`] will be constructed around -/// a `RetryError`. -/// -/// [`SSL_read`]: https://www.openssl.org/docs/manmaster/man3/SSL_read.html -/// [`SSL_write`]: https://www.openssl.org/docs/manmaster/man3/SSL_write.html -/// [`Error::WantRead`]: enum.Error.html#variant.WantRead -#[derive(Debug)] -pub struct RetryError; - -impl fmt::Display for RetryError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.write_str(error::Error::description(self)) - } -} - -impl error::Error for RetryError { - fn description(&self) -> &str { - "operation must be retried" - } -} - -/// An error or intermediate state after a TLS handshake attempt. -#[derive(Debug)] -pub enum HandshakeError { - /// Setup failed. - SetupFailure(ErrorStack), - /// The handshake failed. - Failure(MidHandshakeSslStream), - /// The handshake was interrupted midway through. - /// - /// This error will never be returned for blocking streams. - // FIXME change to WouldBlock - Interrupted(MidHandshakeSslStream), -} - -impl StdError for HandshakeError { - fn description(&self) -> &str { - match *self { - HandshakeError::SetupFailure(_) => "stream setup failed", - HandshakeError::Failure(_) => "the handshake failed", - HandshakeError::Interrupted(_) => "the handshake was interrupted", - } - } - - fn cause(&self) -> Option<&StdError> { - match *self { - HandshakeError::SetupFailure(ref e) => Some(e), - HandshakeError::Failure(ref s) | - HandshakeError::Interrupted(ref s) => Some(s.error()), - } - } -} - -impl fmt::Display for HandshakeError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str(StdError::description(self))?; - match *self { - HandshakeError::SetupFailure(ref e) => write!(f, ": {}", e)?, - HandshakeError::Failure(ref s) | - HandshakeError::Interrupted(ref s) => { - write!(f, ": {}", s.error())?; - if let Some(err) = s.ssl().verify_result() { - write!(f, ": {}", err)?; - } - } - } - Ok(()) - } -} - -impl From for HandshakeError { - fn from(e: ErrorStack) -> HandshakeError { - HandshakeError::SetupFailure(e) - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/mod.rs cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/mod.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2567 +0,0 @@ -//! SSL/TLS support. -//! -//! `SslConnector` and `SslAcceptor` should be used in most cases - they handle -//! configuration of the OpenSSL primitives for you. -//! -//! # Examples -//! -//! To connect as a client to a remote server: -//! -//! ``` -//! use openssl::ssl::{SslMethod, SslConnectorBuilder}; -//! use std::io::{Read, Write}; -//! use std::net::TcpStream; -//! -//! let connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap().build(); -//! -//! let stream = TcpStream::connect("google.com:443").unwrap(); -//! let mut stream = connector.connect("google.com", stream).unwrap(); -//! -//! stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); -//! let mut res = vec![]; -//! stream.read_to_end(&mut res).unwrap(); -//! println!("{}", String::from_utf8_lossy(&res)); -//! ``` -//! -//! To accept connections as a server from remote clients: -//! -//! ```no_run -//! use openssl::pkcs12::Pkcs12; -//! use openssl::ssl::{SslMethod, SslAcceptorBuilder, SslStream}; -//! use std::fs::File; -//! use std::io::{Read, Write}; -//! use std::net::{TcpListener, TcpStream}; -//! use std::sync::Arc; -//! use std::thread; -//! -//! // In this example we retrieve our keypair and certificate chain from a PKCS #12 archive, -//! // but but they can also be retrieved from, for example, individual PEM- or DER-formatted -//! // files. See the documentation for the `PKey` and `X509` types for more details. -//! let mut file = File::open("identity.pfx").unwrap(); -//! let mut pkcs12 = vec![]; -//! file.read_to_end(&mut pkcs12).unwrap(); -//! let pkcs12 = Pkcs12::from_der(&pkcs12).unwrap(); -//! let identity = pkcs12.parse("password123").unwrap(); -//! -//! let acceptor = SslAcceptorBuilder::mozilla_intermediate(SslMethod::tls(), -//! &identity.pkey, -//! &identity.cert, -//! &identity.chain) -//! .unwrap() -//! .build(); -//! let acceptor = Arc::new(acceptor); -//! -//! let listener = TcpListener::bind("0.0.0.0:8443").unwrap(); -//! -//! fn handle_client(stream: SslStream) { -//! // ... -//! } -//! -//! for stream in listener.incoming() { -//! match stream { -//! Ok(stream) => { -//! let acceptor = acceptor.clone(); -//! thread::spawn(move || { -//! let stream = acceptor.accept(stream).unwrap(); -//! handle_client(stream); -//! }); -//! } -//! Err(e) => { /* connection failed */ } -//! } -//! } -//! ``` -use ffi; -use foreign_types::{ForeignType, ForeignTypeRef, Opaque}; -use libc::{c_int, c_long, c_ulong, c_void}; -use libc::{c_uchar, c_uint}; -use std::any::Any; -use std::any::TypeId; -use std::cmp; -use std::collections::HashMap; -use std::ffi::{CStr, CString}; -use std::fmt; -use std::io; -use std::io::prelude::*; -use std::marker::PhantomData; -use std::mem; -use std::ops::{Deref, DerefMut}; -use std::panic::resume_unwind; -use std::path::Path; -use std::ptr; -use std::slice; -use std::str; -use std::sync::Mutex; - -use {cvt, cvt_n, cvt_p, init}; -use dh::{Dh, DhRef}; -use ec::EcKeyRef; -#[cfg(any(all(feature = "v101", ossl101), all(feature = "v102", ossl102)))] -use ec::EcKey; -use x509::{X509, X509FileType, X509Name, X509Ref, X509StoreContextRef, X509VerifyError}; -use x509::store::{X509StoreBuilderRef, X509StoreRef}; -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -use x509::store::X509Store; -#[cfg(any(ossl102, ossl110))] -use verify::X509VerifyParamRef; -use pkey::PKeyRef; -use error::ErrorStack; -use ex_data::Index; -use stack::{Stack, StackRef}; -use ssl::bio::BioMethod; -use ssl::callbacks::*; - -pub use ssl::connector::{ConnectConfiguration, SslAcceptor, SslAcceptorBuilder, SslConnector, - SslConnectorBuilder}; -pub use ssl::error::{Error, HandshakeError, RetryError}; - -mod error; -mod callbacks; -mod connector; -mod bio; -#[cfg(test)] -mod tests; - -// FIXME drop SSL_ prefix -// FIXME remvove flags not used in OpenSSL 1.1 -bitflags! { - /// Options controlling the behavior of an `SslContext`. - pub struct SslOption: c_ulong { - // FIXME remove - const SSL_OP_MICROSOFT_SESS_ID_BUG = ffi::SSL_OP_MICROSOFT_SESS_ID_BUG; - // FIXME remove - const SSL_OP_NETSCAPE_CHALLENGE_BUG = ffi::SSL_OP_NETSCAPE_CHALLENGE_BUG; - // FIXME remove - const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = - ffi::SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG; - // FIXME remove - const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER = ffi::SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER; - // FIXME remove - const SSL_OP_SSLEAY_080_CLIENT_DH_BUG = ffi::SSL_OP_SSLEAY_080_CLIENT_DH_BUG; - // FIXME remove - const SSL_OP_TLS_D5_BUG = ffi::SSL_OP_TLS_D5_BUG; - // FIXME remove - const SSL_OP_TLS_BLOCK_PADDING_BUG = ffi::SSL_OP_TLS_BLOCK_PADDING_BUG; - - // FIXME remove? not documented anywhere - const SSL_OP_CISCO_ANYCONNECT = ffi::SSL_OP_CISCO_ANYCONNECT; - - /// Disables a countermeasure against an SSLv3/TLSv1.0 vulnerability affecting CBC ciphers. - const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS = ffi::SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS; - - /// A "reasonable default" set of options which enables compatibility flags. - const SSL_OP_ALL = ffi::SSL_OP_ALL; - - /// Do not query the MTU. - /// - /// Only affects DTLS connections. - const SSL_OP_NO_QUERY_MTU = ffi::SSL_OP_NO_QUERY_MTU; - - /// Enables Cookie Exchange as described in [RFC 4347 Section 4.2.1]. - /// - /// Only affects DTLS connections. - /// - /// [RFC 4347 Section 4.2.1]: https://tools.ietf.org/html/rfc4347#section-4.2.1 - const SSL_OP_COOKIE_EXCHANGE = ffi::SSL_OP_COOKIE_EXCHANGE; - - /// Disables the use of session tickets for session resumption. - const SSL_OP_NO_TICKET = ffi::SSL_OP_NO_TICKET; - - /// Always start a new session when performing a renegotiation on the server side. - const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = - ffi::SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION; - - /// Disables the use of TLS compression. - const SSL_OP_NO_COMPRESSION = ffi::SSL_OP_NO_COMPRESSION; - - /// Allow legacy insecure renegotiation with servers or clients that do not support secure - /// renegotiation. - const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION = - ffi::SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION; - - /// Creates a new key for each session when using ECDHE. - /// - /// This is always enabled in OpenSSL 1.1.0. - const SSL_OP_SINGLE_ECDH_USE = ffi::SSL_OP_SINGLE_ECDH_USE; - - /// Creates a new key for each session when using DHE. - /// - /// This is always enabled in OpenSSL 1.1.0. - const SSL_OP_SINGLE_DH_USE = ffi::SSL_OP_SINGLE_DH_USE; - - /// Use the server's preferences rather than the client's when selecting a cipher. - /// - /// This has no effect on the client side. - const SSL_OP_CIPHER_SERVER_PREFERENCE = ffi::SSL_OP_CIPHER_SERVER_PREFERENCE; - - /// Disables version rollback attach detection. - const SSL_OP_TLS_ROLLBACK_BUG = ffi::SSL_OP_TLS_ROLLBACK_BUG; - - /// Disables the use of SSLv2. - const SSL_OP_NO_SSLV2 = ffi::SSL_OP_NO_SSLv2; - - /// Disables the use of SSLv3. - const SSL_OP_NO_SSLV3 = ffi::SSL_OP_NO_SSLv3; - - /// Disables the use of TLSv1.0. - const SSL_OP_NO_TLSV1 = ffi::SSL_OP_NO_TLSv1; - - /// Disables the use of TLSv1.1. - const SSL_OP_NO_TLSV1_1 = ffi::SSL_OP_NO_TLSv1_1; - - /// Disables the use of TLSv1.2. - const SSL_OP_NO_TLSV1_2 = ffi::SSL_OP_NO_TLSv1_2; - - /// Disables the use of DTLSv1.0 - /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - const SSL_OP_NO_DTLSV1 = ffi::SSL_OP_NO_DTLSv1; - - /// Disables the use of DTLSv1.2. - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - const SSL_OP_NO_DTLSV1_2 = ffi::SSL_OP_NO_DTLSv1_2; - - /// Disables the use of all (D)TLS protocol versions. - /// - /// This can be used as a mask when whitelisting protocol versions. - /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. - /// - /// # Examples - /// - /// Only support TLSv1.2: - /// - /// ```rust - /// use openssl::ssl::{SSL_OP_NO_SSL_MASK, SSL_OP_NO_TLSV1_2}; - /// - /// let options = SSL_OP_NO_SSL_MASK & !SSL_OP_NO_TLSV1_2; - /// ``` - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - const SSL_OP_NO_SSL_MASK = ffi::SSL_OP_NO_SSL_MASK; - } -} - -bitflags! { - /// Options controlling the behavior of an `SslContext`. - pub struct SslMode: c_long { - /// Enables "short writes". - /// - /// Normally, a write in OpenSSL will always write out all of the requested data, even if it - /// requires more than one TLS record or write to the underlying stream. This option will - /// cause a write to return after writing a single TLS record instead. - const SSL_MODE_ENABLE_PARTIAL_WRITE = ffi::SSL_MODE_ENABLE_PARTIAL_WRITE; - - /// Disables a check that the data buffer has not moved between calls when operating in a - /// nonblocking context. - const SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER = ffi::SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER; - - /// Enables automatic retries after TLS session events such as renegotiations or heartbeats. - /// - /// By default, OpenSSL will return a `WantRead` error after a renegotiation or heartbeat. - /// This option will cause OpenSSL to automatically continue processing the requested - /// operation instead. - /// - /// Note that `SslStream::read` and `SslStream::write` will automatically retry regardless - /// of the state of this option. It only affects `SslStream::ssl_read` and - /// `SslStream::ssl_write`. - const SSL_MODE_AUTO_RETRY = ffi::SSL_MODE_AUTO_RETRY; - - /// Disables automatic chain building when verifying a peer's certificate. - /// - /// TLS peers are responsible for sending the entire certificate chain from the leaf to a - /// trusted root, but some will incorrectly not do so. OpenSSL will try to build the chain - /// out of certificates it knows of, and this option will disable that behavior. - const SSL_MODE_NO_AUTO_CHAIN = ffi::SSL_MODE_NO_AUTO_CHAIN; - - /// Release memory buffers when the session does not need them. - /// - /// This saves ~34 KiB of memory for idle streams. - const SSL_MODE_RELEASE_BUFFERS = ffi::SSL_MODE_RELEASE_BUFFERS; - - // FIXME remove - #[cfg(not(libressl))] - const SSL_MODE_SEND_CLIENTHELLO_TIME = ffi::SSL_MODE_SEND_CLIENTHELLO_TIME; - #[cfg(not(libressl))] - const SSL_MODE_SEND_SERVERHELLO_TIME = ffi::SSL_MODE_SEND_SERVERHELLO_TIME; - - /// Sends the fake `TLS_FALLBACK_SCSV` cipher suite in the ClientHello message of a - /// handshake. - /// - /// This should only be enabled if a client has failed to connect to a server which - /// attempted to downgrade the protocol version of the session. - /// - /// Do not use this unless you know what you're doing! - #[cfg(not(libressl))] - const SSL_MODE_SEND_FALLBACK_SCSV = ffi::SSL_MODE_SEND_FALLBACK_SCSV; - } -} - -/// A type specifying the kind of protocol an `SslContext` will speak. -#[derive(Copy, Clone)] -pub struct SslMethod(*const ffi::SSL_METHOD); - -impl SslMethod { - /// Support all versions of the TLS protocol. - /// - /// This corresponds to `TLS_method` on OpenSSL 1.1.0 and `SSLv23_method` - /// on OpenSSL 1.0.x. - pub fn tls() -> SslMethod { - SslMethod(compat::tls_method()) - } - - /// Support all versions of the DTLS protocol. - /// - /// This corresponds to `DTLS_method` on OpenSSL 1.1.0 and `DTLSv1_method` - /// on OpenSSL 1.0.x. - pub fn dtls() -> SslMethod { - SslMethod(compat::dtls_method()) - } - - /// Constructs an `SslMethod` from a pointer to the underlying OpenSSL value. - pub unsafe fn from_ptr(ptr: *const ffi::SSL_METHOD) -> SslMethod { - SslMethod(ptr) - } - - /// Returns a pointer to the underlying OpenSSL value. - pub fn as_ptr(&self) -> *const ffi::SSL_METHOD { - self.0 - } -} - -bitflags! { - /// Options controling the behavior of certificate verification. - pub struct SslVerifyMode: i32 { - /// Verifies that the peer's certificate is trusted. - /// - /// On the server side, this will cause OpenSSL to request a certificate from the client. - const SSL_VERIFY_PEER = ::ffi::SSL_VERIFY_PEER; - - /// Disables verification of the peer's certificate. - /// - /// On the server side, this will cause OpenSSL to not request a certificate from the - /// client. On the client side, the certificate will be checked for validity, but the - /// negotiation will continue regardless of the result of that check. - const SSL_VERIFY_NONE = ::ffi::SSL_VERIFY_NONE; - - /// On the server side, abort the handshake if the client did not send a certificate. - /// - /// This should be paired with `SSL_VERIFY_PEER`. It has no effect on the client side. - const SSL_VERIFY_FAIL_IF_NO_PEER_CERT = ::ffi::SSL_VERIFY_FAIL_IF_NO_PEER_CERT; - } -} - -/// An identifier of a certificate status type. -#[derive(Copy, Clone)] -pub struct StatusType(c_int); - -impl StatusType { - /// Constructs a `StatusType` from a raw OpenSSL value. - pub fn from_raw(raw: c_int) -> StatusType { - StatusType(raw) - } - - /// Returns the raw OpenSSL value represented by this type. - pub fn as_raw(&self) -> c_int { - self.0 - } -} - -/// An OSCP status. -pub const STATUS_TYPE_OCSP: StatusType = StatusType(ffi::TLSEXT_STATUSTYPE_ocsp); - -lazy_static! { - static ref INDEXES: Mutex> = Mutex::new(HashMap::new()); - static ref SSL_INDEXES: Mutex> = Mutex::new(HashMap::new()); -} - -// Creates a static index for user data of type T -// Registers a destructor for the data which will be called -// when context is freed -fn get_callback_idx() -> c_int { - *INDEXES - .lock() - .unwrap() - .entry(TypeId::of::()) - .or_insert_with(|| get_new_idx::()) -} - -fn get_ssl_callback_idx() -> c_int { - *SSL_INDEXES - .lock() - .unwrap() - .entry(TypeId::of::()) - .or_insert_with(|| get_new_ssl_idx::()) -} - -lazy_static! { - static ref NPN_PROTOS_IDX: c_int = get_new_idx::>(); -} - -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -lazy_static! { - static ref ALPN_PROTOS_IDX: c_int = get_new_idx::>(); -} - -unsafe extern "C" fn free_data_box( - _parent: *mut c_void, - ptr: *mut c_void, - _ad: *mut ffi::CRYPTO_EX_DATA, - _idx: c_int, - _argl: c_long, - _argp: *mut c_void, -) { - if !ptr.is_null() { - Box::::from_raw(ptr as *mut T); - } -} - -fn get_new_idx() -> c_int { - unsafe { - let idx = compat::get_new_idx(free_data_box::); - assert!(idx >= 0); - idx - } -} - -fn get_new_ssl_idx() -> c_int { - unsafe { - let idx = compat::get_new_ssl_idx(free_data_box::); - assert!(idx >= 0); - idx - } -} - -/// Convert a set of byte slices into a series of byte strings encoded for SSL. Encoding is a byte -/// containing the length followed by the string. -fn ssl_encode_byte_strings(strings: &[&[u8]]) -> Vec { - let mut enc = Vec::new(); - for string in strings { - let len = string.len() as u8; - if len as usize != string.len() { - // If the item does not fit, discard it - continue; - } - enc.push(len); - enc.extend(string[..len as usize].to_vec()); - } - enc -} - -// FIXME look into this -/// An error returned from an SNI callback. -pub enum SniError { - Fatal(c_int), - Warning(c_int), - NoAck, -} - -/// A builder for `SslContext`s. -pub struct SslContextBuilder(*mut ffi::SSL_CTX); - -unsafe impl Sync for SslContextBuilder {} -unsafe impl Send for SslContextBuilder {} - -impl Drop for SslContextBuilder { - fn drop(&mut self) { - unsafe { ffi::SSL_CTX_free(self.as_ptr()) } - } -} - -impl SslContextBuilder { - /// Creates a new `SslContextBuilder`. - /// - /// This corresponds to [`SSL_CTX_new`]. - /// - /// [`SSL_CTX_new`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_new.html - pub fn new(method: SslMethod) -> Result { - unsafe { - init(); - let ctx = cvt_p(ffi::SSL_CTX_new(method.as_ptr()))?; - - Ok(SslContextBuilder::from_ptr(ctx)) - } - } - - /// Creates an `SslContextBuilder` from a pointer to a raw OpenSSL value. - pub unsafe fn from_ptr(ctx: *mut ffi::SSL_CTX) -> SslContextBuilder { - SslContextBuilder(ctx) - } - - /// Returns a pointer to the raw OpenSSL value. - pub fn as_ptr(&self) -> *mut ffi::SSL_CTX { - self.0 - } - - /// Configures the certificate verification method for new connections. - /// - /// This corresponds to [`SSL_CTX_set_verify`]. - /// - /// [`SSL_CTX_set_verify`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_verify.html - pub fn set_verify(&mut self, mode: SslVerifyMode) { - unsafe { - ffi::SSL_CTX_set_verify(self.as_ptr(), mode.bits as c_int, None); - } - } - - /// Configures the certificate verification method for new connections and - /// registers a verification callback. - /// - /// The callback is passed a boolean indicating if OpenSSL's internal verification succeeded as - /// well as a reference to the `X509StoreContext` which can be used to examine the certificate - /// chain. It should return a boolean indicating if verification succeeded. - /// - /// This corresponds to [`SSL_CTX_set_verify`]. - /// - /// [`SSL_CTX_set_verify`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_verify.html - pub fn set_verify_callback(&mut self, mode: SslVerifyMode, verify: F) - where - // FIXME should take a mutable reference to the store - F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send, - { - unsafe { - let verify = Box::new(verify); - ffi::SSL_CTX_set_ex_data( - self.as_ptr(), - get_callback_idx::(), - mem::transmute(verify), - ); - ffi::SSL_CTX_set_verify(self.as_ptr(), mode.bits as c_int, Some(raw_verify::)); - } - } - - /// Configures the server name indication (SNI) callback for new connections. - /// - /// SNI is used to allow a single server to handle requests for multiple domains, each of which - /// has its own certificate chain and configuration. - /// - /// Obtain the server name with the `servername` method and then set the corresponding context - /// with `set_ssl_context` - /// - /// This corresponds to [`SSL_CTX_set_tlsext_servername_callback`]. - /// - /// [`SSL_CTX_set_tlsext_servername_callback`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_tlsext_servername_callback.html - pub fn set_servername_callback(&mut self, callback: F) - where - F: Fn(&mut SslRef) -> Result<(), SniError> + Any + 'static + Sync + Send, - { - unsafe { - let callback = Box::new(callback); - ffi::SSL_CTX_set_ex_data( - self.as_ptr(), - get_callback_idx::(), - mem::transmute(callback), - ); - let f: extern "C" fn(_, _, _) -> _ = raw_sni::; - let f: extern "C" fn() = mem::transmute(f); - ffi::SSL_CTX_set_tlsext_servername_callback(self.as_ptr(), Some(f)); - } - } - - /// Sets the certificate verification depth. - /// - /// If the peer's certificate chain is longer than this value, verification will fail. - /// - /// This corresponds to [`SSL_CTX_set_verify_depth`]. - /// - /// [`SSL_CTX_set_verify_depth`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_verify_depth.html - pub fn set_verify_depth(&mut self, depth: u32) { - unsafe { - ffi::SSL_CTX_set_verify_depth(self.as_ptr(), depth as c_int); - } - } - - /// Sets a custom certificate store for verifying peer certificates. - /// - /// Requires the `v102` feature and OpenSSL 1.0.2, or the `v110` feature and OpenSSL 1.1.0. - /// - /// This corresponds to [`SSL_CTX_set0_verify_cert_store`]. - /// - /// [`SSL_CTX_set0_verify_cert_store`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set0_verify_cert_store.html - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn set_verify_cert_store(&mut self, cert_store: X509Store) -> Result<(), ErrorStack> { - unsafe { - let ptr = cert_store.as_ptr(); - cvt(ffi::SSL_CTX_set0_verify_cert_store(self.as_ptr(), ptr) - as c_int)?; - mem::forget(cert_store); - - Ok(()) - } - } - - /// Controls read ahead behavior. - /// - /// If enabled, OpenSSL will read as much data as is available from the underlying stream, - /// instead of a single record at a time. - /// - /// It has no effect when used with DTLS. - /// - /// This corresponds to [`SSL_CTX_set_read_ahead`]. - /// - /// [`SSL_CTX_set_read_ahead`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_read_ahead.html - pub fn set_read_ahead(&mut self, read_ahead: bool) { - unsafe { - ffi::SSL_CTX_set_read_ahead(self.as_ptr(), read_ahead as c_long); - } - } - - /// Sets the mode used by the context, returning the previous mode. - /// - /// This corresponds to [`SSL_CTX_set_mode`]. - /// - /// [`SSL_CTX_set_mode`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_mode.html - pub fn set_mode(&mut self, mode: SslMode) -> SslMode { - unsafe { - let mode = ffi::SSL_CTX_set_mode(self.as_ptr(), mode.bits()); - SslMode::from_bits(mode).unwrap() - } - } - - /// Sets the parameters to be used during ephemeral Diffie-Hellman key exchange. - /// - /// This corresponds to [`SSL_CTX_set_tmp_dh`]. - /// - /// [`SSL_CTX_set_tmp_dh`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_tmp_dh.html - pub fn set_tmp_dh(&mut self, dh: &DhRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::SSL_CTX_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) } - } - - /// Sets the callback which will generate parameters to be used during ephemeral Diffie-Hellman - /// key exchange. - /// - /// The callback is provided with a reference to the `Ssl` for the session, as well as a boolean - /// indicating if the selected cipher is export-grade, and the key length. The export and key - /// length options are archaic and should be ignored in almost all cases. - /// - /// This corresponds to [`SSL_CTX_set_tmp_dh_callback`]. - /// - /// [`SSL_CTX_set_tmp_dh_callback`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_tmp_dh.html - pub fn set_tmp_dh_callback(&mut self, callback: F) - where - F: Fn(&mut SslRef, bool, u32) -> Result + Any + 'static + Sync + Send, - { - unsafe { - let callback = Box::new(callback); - ffi::SSL_CTX_set_ex_data( - self.as_ptr(), - get_callback_idx::(), - Box::into_raw(callback) as *mut c_void, - ); - let f: unsafe extern "C" fn(_, _, _) -> _ = raw_tmp_dh::; - ffi::SSL_CTX_set_tmp_dh_callback(self.as_ptr(), f); - } - } - - /// Sets the parameters to be used during ephemeral elliptic curve Diffie-Hellman key exchange. - /// - /// This corresponds to `SSL_CTX_set_tmp_ecdh`. - pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::SSL_CTX_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) - as c_int) - .map(|_| ()) - } - } - - /// Sets the callback which will generate parameters to be used during ephemeral elliptic curve - /// Diffie-Hellman key exchange. - /// - /// The callback is provided with a reference to the `Ssl` for the session, as well as a boolean - /// indicating if the selected cipher is export-grade, and the key length. The export and key - /// length options are archaic and should be ignored in almost all cases. - /// - /// Requires the `v101` feature and OpenSSL 1.0.1, or the `v102` feature and OpenSSL 1.0.2. - /// - /// This corresponds to `SSL_CTX_set_tmp_ecdh_callback`. - #[cfg(any(all(feature = "v101", ossl101), all(feature = "v102", ossl102)))] - pub fn set_tmp_ecdh_callback(&mut self, callback: F) - where - F: Fn(&mut SslRef, bool, u32) -> Result + Any + 'static + Sync + Send, - { - unsafe { - let callback = Box::new(callback); - ffi::SSL_CTX_set_ex_data( - self.as_ptr(), - get_callback_idx::(), - Box::into_raw(callback) as *mut c_void, - ); - let f: unsafe extern "C" fn(_, _, _) -> _ = raw_tmp_ecdh::; - ffi::SSL_CTX_set_tmp_ecdh_callback(self.as_ptr(), f); - } - } - - /// Use the default locations of trusted certificates for verification. - /// - /// These locations are read from the `SSL_CERT_FILE` and `SSL_CERT_DIR` environment variables - /// if present, or defaults specified at OpenSSL build time otherwise. - /// - /// This corresponds to [`SSL_CTX_set_default_verify_paths`]. - /// - /// [`SSL_CTX_set_default_verify_paths`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_default_verify_paths.html - pub fn set_default_verify_paths(&mut self) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::SSL_CTX_set_default_verify_paths(self.as_ptr())).map(|_| ()) } - } - - /// Loads trusted root certificates from a file. - /// - /// The file should contain a sequence of PEM-formatted CA certificates. - /// - /// This corresponds to [`SSL_CTX_set_default_verify_file`]. - /// - /// [`SSL_CTX_set_default_verify_file`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_set_default_verify_paths.html - pub fn set_ca_file>(&mut self, file: P) -> Result<(), ErrorStack> { - let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); - unsafe { - cvt(ffi::SSL_CTX_load_verify_locations( - self.as_ptr(), - file.as_ptr() as *const _, - ptr::null(), - )).map(|_| ()) - } - } - - /// Sets the list of CA names sent to the client. - /// - /// The CA certificates must still be added to the trust root - they are not automatically set - /// as trusted by this method. - /// - /// This corresponds to [`SSL_CTX_set_client_CA_list`]. - /// - /// [`SSL_CTX_set_client_CA_list`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_client_CA_list.html - pub fn set_client_ca_list(&mut self, list: Stack) { - unsafe { - ffi::SSL_CTX_set_client_CA_list(self.as_ptr(), list.as_ptr()); - mem::forget(list); - } - } - - /// Set the context identifier for sessions. - /// - /// This value identifies the server's session cache to clients, telling them when they're - /// able to reuse sessions. It should be be set to a unique value per server, unless multiple - /// servers share a session cache. - /// - /// This value should be set when using client certificates, or each request will fail its - /// handshake and need to be restarted. - /// - /// This corresponds to [`SSL_CTX_set_session_id_context`]. - /// - /// [`SSL_CTX_set_session_id_context`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_session_id_context.html - pub fn set_session_id_context(&mut self, sid_ctx: &[u8]) -> Result<(), ErrorStack> { - unsafe { - assert!(sid_ctx.len() <= c_uint::max_value() as usize); - cvt(ffi::SSL_CTX_set_session_id_context( - self.as_ptr(), - sid_ctx.as_ptr(), - sid_ctx.len() as c_uint, - )).map(|_| ()) - } - } - - /// Loads a leaf certificate from a file. - /// - /// Only a single certificate will be loaded - use `add_extra_chain_cert` to add the remainder - /// of the certificate chain, or `set_certificate_chain_file` to load the entire chain from a - /// single file. - /// - /// This corresponds to [`SSL_CTX_use_certificate_file`]. - /// - /// [`SSL_CTX_use_certificate_file`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_use_certificate_file.html - pub fn set_certificate_file>( - &mut self, - file: P, - file_type: X509FileType, - ) -> Result<(), ErrorStack> { - let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); - unsafe { - cvt(ffi::SSL_CTX_use_certificate_file( - self.as_ptr(), - file.as_ptr() as *const _, - file_type.as_raw(), - )).map(|_| ()) - } - } - - /// Loads a certificate chain from a file. - /// - /// The file should contain a sequence of PEM-formatted certificates, the first being the leaf - /// certificate, and the remainder forming the chain of certificates up to and including the - /// trusted root certificate. - /// - /// This corresponds to [`SSL_CTX_use_certificate_chain_file`]. - /// - /// [`SSL_CTX_use_certificate_chain_file`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_use_certificate_file.html - pub fn set_certificate_chain_file>( - &mut self, - file: P, - ) -> Result<(), ErrorStack> { - let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); - unsafe { - cvt(ffi::SSL_CTX_use_certificate_chain_file( - self.as_ptr(), - file.as_ptr() as *const _, - )).map(|_| ()) - } - } - - /// Sets the leaf certificate. - /// - /// Use `add_extra_chain_cert` to add the remainder of the certificate chain. - /// - /// This corresponds to [`SSL_CTX_use_certificate`]. - /// - /// [`SSL_CTX_use_certificate`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_use_certificate_file.html - pub fn set_certificate(&mut self, cert: &X509Ref) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::SSL_CTX_use_certificate(self.as_ptr(), cert.as_ptr())).map(|_| ()) } - } - - /// Appends a certificate to the certificate chain. - /// - /// This chain should contain all certificates necessary to go from the certificate specified by - /// `set_certificate` to a trusted root. - /// - /// This corresponds to [`SSL_CTX_add_extra_chain_cert`]. - /// - /// [`SSL_CTX_add_extra_chain_cert`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_add_extra_chain_cert.html - pub fn add_extra_chain_cert(&mut self, cert: X509) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::SSL_CTX_add_extra_chain_cert(self.as_ptr(), cert.as_ptr()) as c_int)?; - mem::forget(cert); - Ok(()) - } - } - - /// Loads the private key from a file. - /// - /// This corresponds to [`SSL_CTX_use_PrivateKey_file`]. - /// - /// [`SSL_CTX_use_PrivateKey_file`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_use_PrivateKey_file.html - pub fn set_private_key_file>( - &mut self, - file: P, - file_type: X509FileType, - ) -> Result<(), ErrorStack> { - let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); - unsafe { - cvt(ffi::SSL_CTX_use_PrivateKey_file( - self.as_ptr(), - file.as_ptr() as *const _, - file_type.as_raw(), - )).map(|_| ()) - } - } - - /// Sets the private key. - /// - /// This corresponds to [`SSL_CTX_use_PrivateKey`]. - /// - /// [`SSL_CTX_use_PrivateKey`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_use_PrivateKey_file.html - pub fn set_private_key(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::SSL_CTX_use_PrivateKey(self.as_ptr(), key.as_ptr())).map(|_| ()) } - } - - /// Sets the list of supported ciphers. - /// - /// See `man 1 ciphers` for details on the format. - /// - /// This corresponds to [`SSL_CTX_set_cipher_list`]. - /// - /// [`SSL_CTX_set_cipher_list`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_client_ciphers.html - pub fn set_cipher_list(&mut self, cipher_list: &str) -> Result<(), ErrorStack> { - let cipher_list = CString::new(cipher_list).unwrap(); - unsafe { - cvt(ffi::SSL_CTX_set_cipher_list( - self.as_ptr(), - cipher_list.as_ptr() as *const _, - )).map(|_| ()) - } - } - - /// Enables ECDHE key exchange with an automatically chosen curve list. - /// - /// Requires the `v102` feature and OpenSSL 1.0.2. - /// - /// This corresponds to [`SSL_CTX_set_ecdh_auto`]. - /// - /// [`SSL_CTX_set_ecdh_auto`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_ecdh_auto.html - #[cfg(all(feature = "v102", any(ossl102, libressl)))] - pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { - self._set_ecdh_auto(onoff) - } - - #[cfg(any(ossl102, libressl))] - fn _set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::SSL_CTX_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) } - } - - /// Sets the options used by the context, returning the old set. - /// - /// This corresponds to [`SSL_CTX_set_options`]. - /// - /// [`SSL_CTX_set_options`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_options.html - pub fn set_options(&mut self, option: SslOption) -> SslOption { - let ret = unsafe { compat::SSL_CTX_set_options(self.as_ptr(), option.bits()) }; - SslOption::from_bits(ret).unwrap() - } - - /// Returns the options used by the context. - /// - /// This corresponds to [`SSL_CTX_get_options`]. - /// - /// [`SSL_CTX_get_options`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_options.html - pub fn options(&self) -> SslOption { - let ret = unsafe { compat::SSL_CTX_get_options(self.as_ptr()) }; - SslOption::from_bits(ret).unwrap() - } - - /// Clears the options used by the context, returning the old set. - /// - /// This corresponds to [`SSL_CTX_clear_options`]. - /// - /// [`SSL_CTX_clear_options`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set_options.html - pub fn clear_options(&mut self, option: SslOption) -> SslOption { - let ret = unsafe { compat::SSL_CTX_clear_options(self.as_ptr(), option.bits()) }; - SslOption::from_bits(ret).unwrap() - } - - /// Set the protocols to be used during Next Protocol Negotiation (the protocols - /// supported by the application). - // FIXME overhaul - #[cfg(not(any(libressl261, libressl262, libressl26x)))] - pub fn set_npn_protocols(&mut self, protocols: &[&[u8]]) -> Result<(), ErrorStack> { - // Firstly, convert the list of protocols to a byte-array that can be passed to OpenSSL - // APIs -- a list of length-prefixed strings. - let protocols: Box> = Box::new(ssl_encode_byte_strings(protocols)); - - unsafe { - // Attach the protocol list to the OpenSSL context structure, - // so that we can refer to it within the callback. - cvt(ffi::SSL_CTX_set_ex_data( - self.as_ptr(), - *NPN_PROTOS_IDX, - Box::into_raw(protocols) as *mut c_void, - ))?; - // Now register the callback that performs the default protocol - // matching based on the client-supported list of protocols that - // has been saved. - ffi::SSL_CTX_set_next_proto_select_cb( - self.as_ptr(), - raw_next_proto_select_cb, - ptr::null_mut(), - ); - // Also register the callback to advertise these protocols, if a server socket is - // created with the context. - ffi::SSL_CTX_set_next_protos_advertised_cb( - self.as_ptr(), - raw_next_protos_advertise_cb, - ptr::null_mut(), - ); - Ok(()) - } - } - - /// Set the protocols to be used during ALPN (application layer protocol negotiation). - /// If this is a server, these are the protocols we report to the client. - /// If this is a client, these are the protocols we try to match with those reported by the - /// server. - /// - /// Note that ordering of the protocols controls the priority with which they are chosen. - /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. - // FIXME overhaul - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn set_alpn_protocols(&mut self, protocols: &[&[u8]]) -> Result<(), ErrorStack> { - let protocols: Box> = Box::new(ssl_encode_byte_strings(protocols)); - unsafe { - // Set the context's internal protocol list for use if we are a server - let r = ffi::SSL_CTX_set_alpn_protos( - self.as_ptr(), - protocols.as_ptr(), - protocols.len() as c_uint, - ); - // fun fact, SSL_CTX_set_alpn_protos has a reversed return code D: - if r != 0 { - return Err(ErrorStack::get()); - } - - // Rather than use the argument to the callback to contain our data, store it in the - // ssl ctx's ex_data so that we can configure a function to free it later. In the - // future, it might make sense to pull this into our internal struct Ssl instead of - // leaning on openssl and using function pointers. - cvt(ffi::SSL_CTX_set_ex_data( - self.as_ptr(), - *ALPN_PROTOS_IDX, - Box::into_raw(protocols) as *mut c_void, - ))?; - - // Now register the callback that performs the default protocol - // matching based on the client-supported list of protocols that - // has been saved. - ffi::SSL_CTX_set_alpn_select_cb(self.as_ptr(), raw_alpn_select_cb, ptr::null_mut()); - - Ok(()) - } - } - - /// Checks for consistency between the private key and certificate. - /// - /// This corresponds to [`SSL_CTX_check_private_key`]. - /// - /// [`SSL_CTX_check_private_key`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_check_private_key.html - pub fn check_private_key(&self) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::SSL_CTX_check_private_key(self.as_ptr())).map(|_| ()) } - } - - /// Returns a shared reference to the context's certificate store. - /// - /// This corresponds to [`SSL_CTX_get_cert_store`]. - /// - /// [`SSL_CTX_get_cert_store`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_get_cert_store.html - pub fn cert_store(&self) -> &X509StoreBuilderRef { - unsafe { X509StoreBuilderRef::from_ptr(ffi::SSL_CTX_get_cert_store(self.as_ptr())) } - } - - /// Returns a mutable reference to the context's certificate store. - /// - /// This corresponds to [`SSL_CTX_get_cert_store`]. - /// - /// [`SSL_CTX_get_cert_store`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_get_cert_store.html - pub fn cert_store_mut(&mut self) -> &mut X509StoreBuilderRef { - unsafe { X509StoreBuilderRef::from_ptr_mut(ffi::SSL_CTX_get_cert_store(self.as_ptr())) } - } - - /// Sets the callback dealing with OCSP stapling. - /// - /// On the client side, this callback is responsible for validating the OCSP status response - /// returned by the server. The status may be retrieved with the `SslRef::ocsp_status` method. - /// A response of `Ok(true)` indicates that the OCSP status is valid, and a response of - /// `Ok(false)` indicates that the OCSP status is invalid and the handshake should be - /// terminated. - /// - /// On the server side, this callback is resopnsible for setting the OCSP status response to be - /// returned to clients. The status may be set with the `SslRef::set_ocsp_status` method. A - /// response of `Ok(true)` indicates that the OCSP status should be returned to the client, and - /// `Ok(false)` indicates that the status should not be returned to the client. - /// - /// This corresponds to [`SSL_CTX_set_tlsext_status_cb`]. - /// - /// [`SSL_CTX_set_tlsext_status_cb`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_tlsext_status_cb.html - pub fn set_status_callback(&mut self, callback: F) -> Result<(), ErrorStack> - where - F: Fn(&mut SslRef) -> Result + Any + 'static + Sync + Send, - { - unsafe { - let callback = Box::new(callback); - ffi::SSL_CTX_set_ex_data( - self.as_ptr(), - get_callback_idx::(), - Box::into_raw(callback) as *mut c_void, - ); - let f: unsafe extern "C" fn(_, _) -> _ = raw_tlsext_status::; - cvt(ffi::SSL_CTX_set_tlsext_status_cb(self.as_ptr(), Some(f)) - as c_int) - .map(|_| ()) - } - } - - /// Sets the callback for providing an identity and pre-shared key for a TLS-PSK client. - /// - /// The callback will be called with the SSL context, an identity hint if one was provided - /// by the server, a mutable slice for each of the identity and pre-shared key bytes. The - /// identity must be written as a null-terminated C string. - /// - /// This corresponds to [`SSL_CTX_set_psk_client_callback`]. - /// - /// [`SSL_CTX_set_psk_client_callback`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_psk_client_callback.html - #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] - pub fn set_psk_callback(&mut self, callback: F) - where - F: Fn(&mut SslRef, Option<&[u8]>, &mut [u8], &mut [u8]) -> Result - + Any - + 'static - + Sync - + Send, - { - unsafe { - let callback = Box::new(callback); - ffi::SSL_CTX_set_ex_data( - self.as_ptr(), - get_callback_idx::(), - mem::transmute(callback), - ); - ffi::SSL_CTX_set_psk_client_callback(self.as_ptr(), Some(raw_psk::)) - } - } - - /// Sets the extra data at the specified index. - /// - /// This can be used to provide data to callbacks registered with the context. Use the - /// `SslContext::new_ex_index` method to create an `Index`. - /// - /// This corresponds to [`SSL_CTX_set_ex_data`]. - /// - /// [`SSL_CTX_set_ex_data`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_ex_data.html - pub fn set_ex_data(&mut self, index: Index, data: T) { - unsafe { - let data = Box::new(data); - ffi::SSL_CTX_set_ex_data( - self.as_ptr(), - index.as_raw(), - Box::into_raw(data) as *mut c_void, - ); - } - } - - /// Consumes the builder, returning a new `SslContext`. - pub fn build(self) -> SslContext { - let ctx = SslContext(self.0); - mem::forget(self); - ctx - } -} - -foreign_type! { - type CType = ffi::SSL_CTX; - fn drop = ffi::SSL_CTX_free; - - /// A context object for TLS streams. - /// - /// Applications commonly configure a single `SslContext` that is shared by all of its - /// `SslStreams`. - pub struct SslContext; - - /// Reference to [`SslContext`] - /// - /// [`SslContext`]: struct.SslContext.html - pub struct SslContextRef; -} - -unsafe impl Send for SslContext {} -unsafe impl Sync for SslContext {} - -impl Clone for SslContext { - fn clone(&self) -> Self { - unsafe { - compat::SSL_CTX_up_ref(self.as_ptr()); - SslContext::from_ptr(self.as_ptr()) - } - } -} - -// TODO: add useful info here -impl fmt::Debug for SslContext { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!(fmt, "SslContext") - } -} - -impl SslContext { - /// Creates a new builder object for an `SslContext`. - pub fn builder(method: SslMethod) -> Result { - SslContextBuilder::new(method) - } - - /// Returns a new extra data index. - /// - /// Each invocation of this function is guaranteed to return a distinct index. These can be used - /// to store data in the context that can be retrieved later by callbacks, for example. - /// - /// This corresponds to [`SSL_CTX_get_ex_new_index`]. - /// - /// [`SSL_CTX_get_ex_new_index`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_get_ex_new_index.html - pub fn new_ex_index() -> Result, ErrorStack> - where - T: 'static + Sync + Send, - { - unsafe { - ffi::init(); - let idx = cvt_n(compat::get_new_idx(free_data_box::))?; - Ok(Index::from_raw(idx)) - } - } -} - -impl SslContextRef { - /// Returns the certificate associated with this `SslContext`, if present. - /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. - /// - /// This corresponds to [`SSL_CTX_get0_certificate`]. - /// - /// [`SSL_CTX_get0_certificate`]: https://www.openssl.org/docs/man1.1.0/ssl/ssl.html - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn certificate(&self) -> Option<&X509Ref> { - unsafe { - let ptr = ffi::SSL_CTX_get0_certificate(self.as_ptr()); - if ptr.is_null() { - None - } else { - Some(X509Ref::from_ptr(ptr)) - } - } - } - - /// Returns the private key associated with this `SslContext`, if present. - /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. - /// - /// This corresponds to [`SSL_CTX_get0_privatekey`]. - /// - /// [`SSL_CTX_get0_privatekey`]: https://www.openssl.org/docs/man1.1.0/ssl/ssl.html - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn private_key(&self) -> Option<&PKeyRef> { - unsafe { - let ptr = ffi::SSL_CTX_get0_privatekey(self.as_ptr()); - if ptr.is_null() { - None - } else { - Some(PKeyRef::from_ptr(ptr)) - } - } - } - - /// Returns a shared reference to the certificate store used for verification. - /// - /// This corresponds to [`SSL_CTX_get_cert_store`]. - /// - /// [`SSL_CTX_get_cert_store`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_get_cert_store.html - pub fn cert_store(&self) -> &X509StoreRef { - unsafe { X509StoreRef::from_ptr(ffi::SSL_CTX_get_cert_store(self.as_ptr())) } - } - - /// Returns a shared reference to the stack of certificates making up the chain from the leaf. - /// - /// This corresponds to `SSL_CTX_get_extra_chain_certs`. - pub fn extra_chain_certs(&self) -> &StackRef { - unsafe { - let mut chain = ptr::null_mut(); - ffi::SSL_CTX_get_extra_chain_certs(self.as_ptr(), &mut chain); - assert!(!chain.is_null()); - StackRef::from_ptr(chain) - } - } - - /// Returns a reference to the extra data at the specified index. - /// - /// This corresponds to [`SSL_CTX_get_ex_data`]. - /// - /// [`SSL_CTX_get_ex_data`]: https://www.openssl.org/docs/manmaster/man3/SSL_CTX_get_ex_data.html - pub fn ex_data(&self, index: Index) -> Option<&T> { - unsafe { - let data = ffi::SSL_CTX_get_ex_data(self.as_ptr(), index.as_raw()); - if data.is_null() { - None - } else { - Some(&*(data as *const T)) - } - } - } -} - -/// Information about the state of a cipher. -pub struct CipherBits { - /// The number of secret bits used for the cipher. - pub secret: i32, - - /// The number of bits processed by the chosen algorithm. - pub algorithm: i32, -} - -/// Information about a cipher. -pub struct SslCipher(*mut ffi::SSL_CIPHER); - -impl ForeignType for SslCipher { - type CType = ffi::SSL_CIPHER; - type Ref = SslCipherRef; - - #[inline] - unsafe fn from_ptr(ptr: *mut ffi::SSL_CIPHER) -> SslCipher { - SslCipher(ptr) - } - - #[inline] - fn as_ptr(&self) -> *mut ffi::SSL_CIPHER { - self.0 - } -} - -impl Deref for SslCipher { - type Target = SslCipherRef; - - fn deref(&self) -> &SslCipherRef { - unsafe { SslCipherRef::from_ptr(self.0) } - } -} - -impl DerefMut for SslCipher { - fn deref_mut(&mut self) -> &mut SslCipherRef { - unsafe { SslCipherRef::from_ptr_mut(self.0) } - } -} - -/// Reference to an [`SslCipher`]. -/// -/// [`SslCipher`]: struct.SslCipher.html -pub struct SslCipherRef(Opaque); - -impl ForeignTypeRef for SslCipherRef { - type CType = ffi::SSL_CIPHER; -} - -impl SslCipherRef { - /// Returns the name of the cipher. - /// - /// This corresponds to [`SSL_CIPHER_get_name`]. - /// - /// [`SSL_CIPHER_get_name`]: https://www.openssl.org/docs/manmaster/man3/SSL_CIPHER_get_name.html - pub fn name(&self) -> &str { - let name = unsafe { - let ptr = ffi::SSL_CIPHER_get_name(self.as_ptr()); - CStr::from_ptr(ptr as *const _) - }; - - str::from_utf8(name.to_bytes()).unwrap() - } - - /// Returns the SSL/TLS protocol version that first defined the cipher. - /// - /// This corresponds to [`SSL_CIPHER_get_version`]. - /// - /// [`SSL_CIPHER_get_version`]: https://www.openssl.org/docs/manmaster/man3/SSL_CIPHER_get_name.html - pub fn version(&self) -> &str { - let version = unsafe { - let ptr = ffi::SSL_CIPHER_get_version(self.as_ptr()); - CStr::from_ptr(ptr as *const _) - }; - - str::from_utf8(version.to_bytes()).unwrap() - } - - /// Returns the number of bits used for the cipher. - /// - /// This corresponds to [`SSL_CIPHER_get_bits`]. - /// - /// [`SSL_CIPHER_get_bits`]: https://www.openssl.org/docs/manmaster/man3/SSL_CIPHER_get_name.html - pub fn bits(&self) -> CipherBits { - unsafe { - let mut algo_bits = 0; - let secret_bits = ffi::SSL_CIPHER_get_bits(self.as_ptr(), &mut algo_bits); - CipherBits { - secret: secret_bits.into(), - algorithm: algo_bits.into(), - } - } - } - - /// Returns a textual description of the cipher. - /// - /// This corresponds to [`SSL_CIPHER_description`]. - /// - /// [`SSL_CIPHER_description`]: https://www.openssl.org/docs/manmaster/man3/SSL_CIPHER_get_name.html - pub fn description(&self) -> String { - unsafe { - // SSL_CIPHER_description requires a buffer of at least 128 bytes. - let mut buf = [0; 128]; - let ptr = ffi::SSL_CIPHER_description(self.as_ptr(), buf.as_mut_ptr(), 128); - String::from_utf8(CStr::from_ptr(ptr as *const _).to_bytes().to_vec()).unwrap() - } - } -} - -foreign_type! { - type CType = ffi::SSL_SESSION; - fn drop = ffi::SSL_SESSION_free; - - /// An encoded SSL session. - /// - /// These can be cached to share sessions across connections. - pub struct SslSession; - - /// Reference to [`SslSession]`. - /// - /// [`SslSession`]: struct.SslSession.html - pub struct SslSessionRef; -} - -unsafe impl Sync for SslSession {} -unsafe impl Send for SslSession {} - -impl Clone for SslSession { - fn clone(&self) -> SslSession { - self.to_owned() - } -} - -impl ToOwned for SslSessionRef { - type Owned = SslSession; - - fn to_owned(&self) -> SslSession { - unsafe { - compat::SSL_SESSION_up_ref(self.as_ptr()); - SslSession(self.as_ptr()) - } - } -} - -impl SslSessionRef { - /// Returns the SSL session ID. - /// - /// This corresponds to [`SSL_SESSION_get_id`]. - /// - /// [`SSL_SESSION_get_id`]: https://www.openssl.org/docs/manmaster/man3/SSL_SESSION_get_id.html - pub fn id(&self) -> &[u8] { - unsafe { - let mut len = 0; - let p = ffi::SSL_SESSION_get_id(self.as_ptr(), &mut len); - slice::from_raw_parts(p as *const u8, len as usize) - } - } - - /// Returns the length of the master key. - /// - /// This corresponds to [`SSL_SESSION_get_master_key`]. - /// - /// [`SSL_SESSION_get_master_key`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_SESSION_get_master_key.html - pub fn master_key_len(&self) -> usize { - unsafe { compat::SSL_SESSION_get_master_key(self.as_ptr(), ptr::null_mut(), 0) } - } - - /// Copies the master key into the provided buffer. - /// - /// Returns the number of bytes written. - /// - /// This corresponds to [`SSL_SESSION_get_master_key`]. - /// - /// [`SSL_SESSION_get_master_key`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_SESSION_get_master_key.html - pub fn master_key(&self, buf: &mut [u8]) -> usize { - unsafe { compat::SSL_SESSION_get_master_key(self.as_ptr(), buf.as_mut_ptr(), buf.len()) } - } -} - -foreign_type! { - type CType = ffi::SSL; - fn drop = ffi::SSL_free; - - /// The state of an SSL/TLS session. - /// - /// `Ssl` objects are created from an [`SslContext`], which provides configuration defaults. - /// These defaults can be overridden on a per-`Ssl` basis, however. - /// - /// [`SslContext`]: struct.SslContext.html - pub struct Ssl; - - /// Reference to an [`Ssl`]. - /// - /// [`Ssl`]: struct.Ssl.html - pub struct SslRef; -} - -impl Ssl { - /// Returns a new extra data index. - /// - /// Each invocation of this function is guaranteed to return a distinct index. These can be used - /// to store data in the context that can be retrieved later by callbacks, for example. - /// - /// This corresponds to [`SSL_get_ex_new_index`]. - /// - /// [`SSL_get_ex_new_index`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_ex_new_index.html - pub fn new_ex_index() -> Result, ErrorStack> - where - T: 'static + Sync + Send, - { - unsafe { - ffi::init(); - let idx = cvt_n(compat::get_new_ssl_idx(free_data_box::))?; - Ok(Index::from_raw(idx)) - } - } -} - -impl fmt::Debug for SslRef { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - let mut builder = fmt.debug_struct("Ssl"); - builder.field("state", &self.state_string_long()); - if let Some(err) = self.verify_result() { - builder.field("verify_result", &err); - } - builder.finish() - } -} - -impl SslRef { - fn get_raw_rbio(&self) -> *mut ffi::BIO { - unsafe { ffi::SSL_get_rbio(self.as_ptr()) } - } - - fn read(&mut self, buf: &mut [u8]) -> c_int { - let len = cmp::min(c_int::max_value() as usize, buf.len()) as c_int; - unsafe { ffi::SSL_read(self.as_ptr(), buf.as_ptr() as *mut c_void, len) } - } - - fn write(&mut self, buf: &[u8]) -> c_int { - let len = cmp::min(c_int::max_value() as usize, buf.len()) as c_int; - unsafe { ffi::SSL_write(self.as_ptr(), buf.as_ptr() as *const c_void, len) } - } - - fn get_error(&self, ret: c_int) -> c_int { - unsafe { ffi::SSL_get_error(self.as_ptr(), ret) } - } - - /// Like [`SslContextBuilder::set_verify`]. - /// - /// This corresponds to [`SSL_set_verify`]. - /// - /// [`SslContextBuilder::set_verify`]: struct.SslContextBuilder.html#method.set_verify - /// [`SSL_set_verify`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_verify.html - pub fn set_verify(&mut self, mode: SslVerifyMode) { - unsafe { ffi::SSL_set_verify(self.as_ptr(), mode.bits as c_int, None) } - } - - /// Like [`SslContextBuilder::set_verify_callback`]. - /// - /// This corresponds to [`SSL_set_verify`]. - /// - /// [`SslContextBuilder::set_verify_callback`]: struct.SslContextBuilder.html#method.set_verify_callback - /// [`SSL_set_verify`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_verify.html - pub fn set_verify_callback(&mut self, mode: SslVerifyMode, verify: F) - where - // FIXME should take a mutable reference to the x509 store - F: Fn(bool, &X509StoreContextRef) -> bool + Any + 'static + Sync + Send, - { - unsafe { - let verify = Box::new(verify); - ffi::SSL_set_ex_data( - self.as_ptr(), - get_ssl_callback_idx::(), - mem::transmute(verify), - ); - ffi::SSL_set_verify(self.as_ptr(), mode.bits as c_int, Some(ssl_raw_verify::)); - } - } - - /// Like [`SslContextBuilder::set_tmp_dh`]. - /// - /// This corresponds to [`SSL_set_tmp_dh`]. - /// - /// [`SslContextBuilder::set_tmp_dh`]: struct.SslContextBuilder.html#method.set_tmp_dh - /// [`SSL_set_tmp_dh`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tmp_dh.html - pub fn set_tmp_dh(&mut self, dh: &DhRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::SSL_set_tmp_dh(self.as_ptr(), dh.as_ptr()) as c_int).map(|_| ()) } - } - - /// Like [`SslContextBuilder::set_tmp_dh_callback`]. - /// - /// This corresponds to [`SSL_set_tmp_dh_callback`]. - /// - /// [`SslContextBuilder::set_tmp_dh_callback`]: struct.SslContextBuilder.html#method.set_tmp_dh_callback - /// [`SSL_set_tmp_dh_callback`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tmp_dh.html - pub fn set_tmp_dh_callback(&mut self, callback: F) - where - F: Fn(&mut SslRef, bool, u32) -> Result + Any + 'static + Sync + Send, - { - unsafe { - let callback = Box::new(callback); - ffi::SSL_set_ex_data( - self.as_ptr(), - get_ssl_callback_idx::(), - Box::into_raw(callback) as *mut c_void, - ); - let f: unsafe extern "C" fn(_, _, _) -> _ = raw_tmp_dh_ssl::; - ffi::SSL_set_tmp_dh_callback(self.as_ptr(), f); - } - } - - /// Like [`SslContextBuilder::set_tmp_ecdh`]. - /// - /// This corresponds to `SSL_set_tmp_ecdh`. - /// - /// [`SslContextBuilder::set_tmp_ecdh`]: struct.SslContextBuilder.html#method.set_tmp_ecdh - pub fn set_tmp_ecdh(&mut self, key: &EcKeyRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::SSL_set_tmp_ecdh(self.as_ptr(), key.as_ptr()) as c_int).map(|_| ()) } - } - - /// Like [`SslContextBuilder::set_tmp_ecdh_callback`]. - /// - /// Requires the `v101` feature and OpenSSL 1.0.1, or the `v102` feature and OpenSSL 1.0.2. - /// - /// This corresponds to `SSL_set_tmp_ecdh_callback`. - /// - /// [`SslContextBuilder::set_tmp_ecdh_callback`]: struct.SslContextBuilder.html#method.set_tmp_ecdh_callback - #[cfg(any(all(feature = "v101", ossl101), all(feature = "v102", ossl102)))] - pub fn set_tmp_ecdh_callback(&mut self, callback: F) - where - F: Fn(&mut SslRef, bool, u32) -> Result + Any + 'static + Sync + Send, - { - unsafe { - let callback = Box::new(callback); - ffi::SSL_set_ex_data( - self.as_ptr(), - get_ssl_callback_idx::(), - Box::into_raw(callback) as *mut c_void, - ); - let f: unsafe extern "C" fn(_, _, _) -> _ = raw_tmp_ecdh_ssl::; - ffi::SSL_set_tmp_ecdh_callback(self.as_ptr(), f); - } - } - - /// Like [`SslContextBuilder::set_ecdh_auto`]. - /// - /// Requires the `v102` feature and OpenSSL 1.0.2. - /// - /// This corresponds to [`SSL_set_ecdh_auto`]. - /// - /// [`SslContextBuilder::set_tmp_ecdh`]: struct.SslContextBuilder.html#method.set_tmp_ecdh - /// [`SSL_set_ecdh_auto`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_ecdh_auto.html - #[cfg(all(feature = "v102", ossl102))] - pub fn set_ecdh_auto(&mut self, onoff: bool) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::SSL_set_ecdh_auto(self.as_ptr(), onoff as c_int)).map(|_| ()) } - } - - /// Returns the current cipher if the session is active. - /// - /// This corresponds to [`SSL_get_current_cipher`]. - /// - /// [`SSL_get_current_cipher`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_current_cipher.html - pub fn current_cipher(&self) -> Option<&SslCipherRef> { - unsafe { - let ptr = ffi::SSL_get_current_cipher(self.as_ptr()); - - if ptr.is_null() { - None - } else { - Some(SslCipherRef::from_ptr(ptr as *mut _)) - } - } - } - - /// Returns a short string describing the state of the session. - /// - /// This corresponds to [`SSL_state_string`]. - /// - /// [`SSL_state_string`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_state_string.html - pub fn state_string(&self) -> &'static str { - let state = unsafe { - let ptr = ffi::SSL_state_string(self.as_ptr()); - CStr::from_ptr(ptr as *const _) - }; - - str::from_utf8(state.to_bytes()).unwrap() - } - - /// Returns a longer string describing the state of the session. - /// - /// This corresponds to [`SSL_state_string_long`]. - /// - /// [`SSL_state_string_long`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_state_string_long.html - pub fn state_string_long(&self) -> &'static str { - let state = unsafe { - let ptr = ffi::SSL_state_string_long(self.as_ptr()); - CStr::from_ptr(ptr as *const _) - }; - - str::from_utf8(state.to_bytes()).unwrap() - } - - /// Sets the host name to be sent to the server for Server Name Indication (SNI). - /// - /// It has no effect for a server-side connection. - /// - /// This corresponds to [`SSL_set_tlsext_host_name`]. - /// - /// [`SSL_set_tlsext_host_name`]: https://www.openssl.org/docs/manmaster/man3/SSL_get_servername_type.html - pub fn set_hostname(&mut self, hostname: &str) -> Result<(), ErrorStack> { - let cstr = CString::new(hostname).unwrap(); - unsafe { - cvt(ffi::SSL_set_tlsext_host_name(self.as_ptr(), cstr.as_ptr() as *mut _) as c_int) - .map(|_| ()) - } - } - - /// Returns the peer's certificate, if present. - /// - /// This corresponds to [`SSL_get_peer_certificate`]. - /// - /// [`SSL_get_peer_certificate`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_peer_certificate.html - pub fn peer_certificate(&self) -> Option { - unsafe { - let ptr = ffi::SSL_get_peer_certificate(self.as_ptr()); - if ptr.is_null() { - None - } else { - Some(X509::from_ptr(ptr)) - } - } - } - - /// Returns the certificate chain of the peer, if present. - /// - /// On the client side, the chain includes the leaf certificate, but on the server side it does - /// not. Fun! - /// - /// This corresponds to [`SSL_get_peer_cert_chain`]. - /// - /// [`SSL_get_peer_cert_chain`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_peer_cert_chain.html - pub fn peer_cert_chain(&self) -> Option<&StackRef> { - unsafe { - let ptr = ffi::SSL_get_peer_cert_chain(self.as_ptr()); - if ptr.is_null() { - None - } else { - Some(StackRef::from_ptr(ptr)) - } - } - } - - /// Like [`SslContext::certificate`]. - /// - /// This corresponds to `SSL_get_certificate`. - /// - /// [`SslContext::certificate`]: struct.SslContext.html#method.certificate - pub fn certificate(&self) -> Option<&X509Ref> { - unsafe { - let ptr = ffi::SSL_get_certificate(self.as_ptr()); - if ptr.is_null() { - None - } else { - Some(X509Ref::from_ptr(ptr)) - } - } - } - - /// Like [`SslContext::private_key`]. - /// - /// This corresponds to `SSL_get_privatekey`. - /// - /// [`SslContext::private_key`]: struct.SslContext.html#method.private_key - pub fn private_key(&self) -> Option<&PKeyRef> { - unsafe { - let ptr = ffi::SSL_get_privatekey(self.as_ptr()); - if ptr.is_null() { - None - } else { - Some(PKeyRef::from_ptr(ptr)) - } - } - } - - /// Returns a string describing the protocol version of the session. - /// - /// This corresponds to [`SSL_get_version`]. - /// - /// [`SSL_get_version`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_version.html - pub fn version(&self) -> &'static str { - let version = unsafe { - let ptr = ffi::SSL_get_version(self.as_ptr()); - CStr::from_ptr(ptr as *const _) - }; - - str::from_utf8(version.to_bytes()).unwrap() - } - - /// Returns the protocol selected by performing Next Protocol Negotiation, if any. - /// - /// The protocol's name is returned is an opaque sequence of bytes. It is up to the client - /// to interpret it. - /// - /// This corresponds to [`SSL_get0_next_proto_negotiated`]. - /// - /// [`SSL_get0_next_proto_negotiated`]: https://www.openssl.org/docs/manmaster/man3/SSL_get0_next_proto_negotiated.html - #[cfg(not(any(libressl261, libressl262, libressl26x)))] - pub fn selected_npn_protocol(&self) -> Option<&[u8]> { - unsafe { - let mut data: *const c_uchar = ptr::null(); - let mut len: c_uint = 0; - // Get the negotiated protocol from the SSL instance. - // `data` will point at a `c_uchar` array; `len` will contain the length of this array. - ffi::SSL_get0_next_proto_negotiated(self.as_ptr(), &mut data, &mut len); - - if data.is_null() { - None - } else { - Some(slice::from_raw_parts(data, len as usize)) - } - } - } - - /// Returns the protocol selected by performing ALPN, if any. - /// - /// The protocol's name is returned is an opaque sequence of bytes. It is up to the client - /// to interpret it. - /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or OpenSSL 1.1.0. - /// - /// This corresponds to [`SSL_get0_alpn_selected`]. - /// - /// [`SSL_get0_alpn_selected`]: https://www.openssl.org/docs/manmaster/man3/SSL_get0_next_proto_negotiated.html - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn selected_alpn_protocol(&self) -> Option<&[u8]> { - unsafe { - let mut data: *const c_uchar = ptr::null(); - let mut len: c_uint = 0; - // Get the negotiated protocol from the SSL instance. - // `data` will point at a `c_uchar` array; `len` will contain the length of this array. - ffi::SSL_get0_alpn_selected(self.as_ptr(), &mut data, &mut len); - - if data.is_null() { - None - } else { - Some(slice::from_raw_parts(data, len as usize)) - } - } - } - - /// Returns the number of bytes remaining in the currently processed TLS record. - /// - /// If this is greater than 0, the next call to `read` will not call down to the underlying - /// stream. - /// - /// This corresponds to [`SSL_pending]`. - /// - /// [`SSL_pending`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_pending.html - pub fn pending(&self) -> usize { - unsafe { ffi::SSL_pending(self.as_ptr()) as usize } - } - - /// Returns the compression method currently in use. - /// - /// This corresponds to `SSL_get_current_compression`. - pub fn compression(&self) -> Option<&str> { - self._compression() - } - - #[cfg(not(osslconf = "OPENSSL_NO_COMP"))] - fn _compression(&self) -> Option<&str> { - unsafe { - let ptr = ffi::SSL_get_current_compression(self.as_ptr()); - if ptr == ptr::null() { - return None; - } - let meth = ffi::SSL_COMP_get_name(ptr); - Some(str::from_utf8(CStr::from_ptr(meth as *const _).to_bytes()).unwrap()) - } - } - - #[cfg(osslconf = "OPENSSL_NO_COMP")] - fn _compression(&self) -> Option<&str> { - None - } - - /// Returns the servername sent by the client via Server Name Indication (SNI). - /// - /// It is only useful on the server side. - /// - /// This corresponds to [`SSL_get_servername`]. - /// - /// [`SSL_get_servername`]: https://www.openssl.org/docs/manmaster/man3/SSL_get_servername.html - // FIXME add name parameter - pub fn servername(&self) -> Option<&str> { - unsafe { - let name = ffi::SSL_get_servername(self.as_ptr(), ffi::TLSEXT_NAMETYPE_host_name); - if name == ptr::null() { - return None; - } - - Some(str::from_utf8(CStr::from_ptr(name as *const _).to_bytes()).unwrap()) - } - } - - /// Changes the context corresponding to the current connection. - /// - /// It is most commonly used in the Server Name Indication (SNI) callback. - /// - /// This corresponds to `SSL_set_SSL_CTX`. - pub fn set_ssl_context(&mut self, ctx: &SslContextRef) -> Result<(), ErrorStack> { - unsafe { cvt_p(ffi::SSL_set_SSL_CTX(self.as_ptr(), ctx.as_ptr())).map(|_| ()) } - } - - /// Returns the context corresponding to the current connection. - /// - /// This corresponds to [`SSL_get_SSL_CTX`]. - /// - /// [`SSL_get_SSL_CTX`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_SSL_CTX.html - pub fn ssl_context(&self) -> &SslContextRef { - unsafe { - let ssl_ctx = ffi::SSL_get_SSL_CTX(self.as_ptr()); - SslContextRef::from_ptr(ssl_ctx) - } - } - - /// Returns a mutable reference to the X509 verification configuration. - /// - /// Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. - /// - /// This corresponds to [`SSL_get0_param`]. - /// - /// [`SSL_get0_param`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_get0_param.html - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - pub fn param_mut(&mut self) -> &mut X509VerifyParamRef { - self._param_mut() - } - - #[cfg(any(ossl102, ossl110))] - fn _param_mut(&mut self) -> &mut X509VerifyParamRef { - unsafe { X509VerifyParamRef::from_ptr_mut(ffi::SSL_get0_param(self.as_ptr())) } - } - - /// Returns the certificate verification result. - /// - /// This corresponds to [`SSL_get_verify_result`]. - /// - /// [`SSL_get_verify_result`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_verify_result.html - pub fn verify_result(&self) -> Option { - unsafe { X509VerifyError::from_raw(ffi::SSL_get_verify_result(self.as_ptr())) } - } - - /// Returns a shared reference to the SSL session. - /// - /// This corresponds to [`SSL_get_session`]. - /// - /// [`SSL_get_session`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_get_session.html - pub fn session(&self) -> Option<&SslSessionRef> { - unsafe { - let p = ffi::SSL_get_session(self.as_ptr()); - if p.is_null() { - None - } else { - Some(SslSessionRef::from_ptr(p)) - } - } - } - - /// Sets the session to be used. - /// - /// This should be called before the handshake to attempt to reuse a previously established - /// session. If the server is not willing to reuse the session, a new one will be transparently - /// negotiated. - /// - /// This corresponds to [`SSL_set_session`]. - /// - /// # Safety - /// - /// The caller of this method is responsible for ensuring that the session is associated - /// with the same `SslContext` as this `Ssl`. - /// - /// [`SSL_set_session`]: https://www.openssl.org/docs/manmaster/man3/SSL_set_session.html - pub unsafe fn set_session(&mut self, session: &SslSessionRef) -> Result<(), ErrorStack> { - cvt(ffi::SSL_set_session(self.as_ptr(), session.as_ptr())).map(|_| ()) - } - - /// Determines if the session provided to `set_session` was successfully reused. - /// - /// This corresponds to [`SSL_session_reused`]. - /// - /// [`SSL_session_reused`]: https://www.openssl.org/docs/man1.1.0/ssl/SSL_session_reused.html - pub fn session_reused(&self) -> bool { - unsafe { ffi::SSL_session_reused(self.as_ptr()) != 0 } - } - - /// Sets the status response a client wishes the server to reply with. - /// - /// This corresponds to [`SSL_set_tlsext_status_type`]. - /// - /// [`SSL_set_tlsext_status_type`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tlsext_status_type.html - pub fn set_status_type(&mut self, type_: StatusType) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::SSL_set_tlsext_status_type(self.as_ptr(), type_.as_raw()) as c_int).map(|_| ()) - } - } - - /// Returns the server's OCSP response, if present. - /// - /// This corresponds to [`SSL_get_tlsext_status_oscp_resp`]. - /// - /// [`SSL_get_tlsext_status_ocsp_resp`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tlsext_status_type.html - pub fn ocsp_status(&self) -> Option<&[u8]> { - unsafe { - let mut p = ptr::null_mut(); - let len = ffi::SSL_get_tlsext_status_ocsp_resp(self.as_ptr(), &mut p); - - if len < 0 { - None - } else { - Some(slice::from_raw_parts(p as *const u8, len as usize)) - } - } - } - - /// Sets the OCSP response to be returned to the client. - /// - /// This corresponds to [`SSL_set_tlsext_status_oscp_resp`]. - /// - /// [`SSL_set_tlsext_status_ocsp_resp`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_set_tlsext_status_type.html - pub fn set_ocsp_status(&mut self, response: &[u8]) -> Result<(), ErrorStack> { - unsafe { - assert!(response.len() <= c_int::max_value() as usize); - let p = cvt_p(ffi::CRYPTO_malloc( - response.len() as _, - concat!(file!(), "\0").as_ptr() as *const _, - line!() as c_int, - ))?; - ptr::copy_nonoverlapping(response.as_ptr(), p as *mut u8, response.len()); - cvt(ffi::SSL_set_tlsext_status_ocsp_resp( - self.as_ptr(), - p as *mut c_uchar, - response.len() as c_long, - ) as c_int) - .map(|_| ()) - } - } - - /// Determines if this `Ssl` is configured for server-side or client-side use. - /// - /// This corresponds to [`SSL_is_server`]. - /// - /// [`SSL_is_server`]: https://www.openssl.org/docs/manmaster/man3/SSL_is_server.html - pub fn is_server(&self) -> bool { - unsafe { compat::SSL_is_server(self.as_ptr()) != 0 } - } - - /// Sets the extra data at the specified index. - /// - /// This can be used to provide data to callbacks registered with the context. Use the - /// `Ssl::new_ex_index` method to create an `Index`. - /// - /// This corresponds to [`SSL_set_ex_data`]. - /// - /// [`SSL_set_ex_data`]: https://www.openssl.org/docs/manmaster/man3/SSL_set_ex_data.html - pub fn set_ex_data(&mut self, index: Index, data: T) { - unsafe { - let data = Box::new(data); - ffi::SSL_set_ex_data( - self.as_ptr(), - index.as_raw(), - Box::into_raw(data) as *mut c_void, - ); - } - } - - /// Returns a reference to the extra data at the specified index. - /// - /// This corresponds to [`SSL_get_ex_data`]. - /// - /// [`SSL_get_ex_data`]: https://www.openssl.org/docs/manmaster/man3/SSL_set_ex_data.html - pub fn ex_data(&self, index: Index) -> Option<&T> { - unsafe { - let data = ffi::SSL_get_ex_data(self.as_ptr(), index.as_raw()); - if data.is_null() { - None - } else { - Some(&*(data as *const T)) - } - } - } -} - -unsafe impl Sync for Ssl {} -unsafe impl Send for Ssl {} - -impl fmt::Debug for Ssl { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(&**self, fmt) - } -} - -impl Ssl { - /// Creates a new `Ssl`. - /// - /// This corresponds to [`SSL_new`]. - /// - /// [`SSL_new`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_new.html - pub fn new(ctx: &SslContext) -> Result { - unsafe { - let ssl = cvt_p(ffi::SSL_new(ctx.as_ptr()))?; - Ok(Ssl::from_ptr(ssl)) - } - } - - /// Initiates a client-side TLS handshake. - /// - /// This corresponds to [`SSL_connect`]. - /// - /// # Warning - /// - /// OpenSSL's default configuration is insecure. It is highly recommended to use - /// `SslConnector` rather than `Ssl` directly, as it manages that configuration. - /// - /// [`SSL_connect`]: https://www.openssl.org/docs/manmaster/man3/SSL_connect.html - pub fn connect(self, stream: S) -> Result, HandshakeError> - where - S: Read + Write, - { - let mut stream = SslStream::new_base(self, stream); - let ret = unsafe { ffi::SSL_connect(stream.ssl.as_ptr()) }; - if ret > 0 { - Ok(stream) - } else { - match stream.make_error(ret) { - e @ Error::WantWrite(_) | e @ Error::WantRead(_) => { - Err(HandshakeError::Interrupted(MidHandshakeSslStream { - stream: stream, - error: e, - })) - } - err => Err(HandshakeError::Failure(MidHandshakeSslStream { - stream: stream, - error: err, - })), - } - } - } - - /// Initiates a server-side TLS handshake. - /// - /// This corresponds to [`SSL_accept`]. - /// - /// # Warning - /// - /// OpenSSL's default configuration is insecure. It is highly recommended to use - /// `SslAcceptor` rather than `Ssl` directly, as it manages that configuration. - /// - /// [`SSL_accept`]: https://www.openssl.org/docs/manmaster/man3/SSL_accept.html - pub fn accept(self, stream: S) -> Result, HandshakeError> - where - S: Read + Write, - { - let mut stream = SslStream::new_base(self, stream); - let ret = unsafe { ffi::SSL_accept(stream.ssl.as_ptr()) }; - if ret > 0 { - Ok(stream) - } else { - match stream.make_error(ret) { - e @ Error::WantWrite(_) | e @ Error::WantRead(_) => { - Err(HandshakeError::Interrupted(MidHandshakeSslStream { - stream: stream, - error: e, - })) - } - err => Err(HandshakeError::Failure(MidHandshakeSslStream { - stream: stream, - error: err, - })), - } - } - } -} - -/// An SSL stream midway through the handshake process. -#[derive(Debug)] -pub struct MidHandshakeSslStream { - stream: SslStream, - error: Error, -} - -impl MidHandshakeSslStream { - /// Returns a shared reference to the inner stream. - pub fn get_ref(&self) -> &S { - self.stream.get_ref() - } - - /// Returns a mutable reference to the inner stream. - pub fn get_mut(&mut self) -> &mut S { - self.stream.get_mut() - } - - /// Returns a shared reference to the `Ssl` of the stream. - pub fn ssl(&self) -> &SslRef { - self.stream.ssl() - } - - /// Returns the underlying error which interrupted this handshake. - pub fn error(&self) -> &Error { - &self.error - } - - /// Consumes `self`, returning its error. - pub fn into_error(self) -> Error { - self.error - } - - /// Restarts the handshake process. - /// - /// This corresponds to [`SSL_do_handshake`]. - /// - /// [`SSL_do_handshake`]: https://www.openssl.org/docs/manmaster/man3/SSL_do_handshake.html - pub fn handshake(mut self) -> Result, HandshakeError> { - let ret = unsafe { ffi::SSL_do_handshake(self.stream.ssl.as_ptr()) }; - if ret > 0 { - Ok(self.stream) - } else { - match self.stream.make_error(ret) { - e @ Error::WantWrite(_) | e @ Error::WantRead(_) => { - self.error = e; - Err(HandshakeError::Interrupted(self)) - } - err => { - self.error = err; - Err(HandshakeError::Failure(self)) - } - } - } - } -} - -/// A TLS session over a stream. -pub struct SslStream { - // FIXME use ManuallyDrop - ssl: Ssl, - _method: BioMethod, // NOTE: this *must* be after the Ssl field so things drop right - _p: PhantomData, -} - -impl fmt::Debug for SslStream -where - S: fmt::Debug, -{ - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("SslStream") - .field("stream", &self.get_ref()) - .field("ssl", &self.ssl()) - .finish() - } -} - -impl SslStream { - fn new_base(ssl: Ssl, stream: S) -> Self { - unsafe { - let (bio, method) = bio::new(stream).unwrap(); - ffi::SSL_set_bio(ssl.as_ptr(), bio, bio); - - SslStream { - ssl: ssl, - _method: method, - _p: PhantomData, - } - } - } - - /// Like `read`, but returns an `ssl::Error` rather than an `io::Error`. - /// - /// It is particularly useful with a nonblocking socket, where the error value will identify if - /// OpenSSL is waiting on read or write readiness. - /// - /// This corresponds to [`SSL_read`]. - /// - /// [`SSL_read`]: https://www.openssl.org/docs/manmaster/man3/SSL_read.html - pub fn ssl_read(&mut self, buf: &mut [u8]) -> Result { - // The intepretation of the return code here is a little odd with a - // zero-length write. OpenSSL will likely correctly report back to us - // that it read zero bytes, but zero is also the sentinel for "error". - // To avoid that confusion short-circuit that logic and return quickly - // if `buf` has a length of zero. - if buf.len() == 0 { - return Ok(0); - } - - let ret = self.ssl.read(buf); - if ret > 0 { - Ok(ret as usize) - } else { - match self.make_error(ret) { - // FIXME only do this in read - // Don't treat unexpected EOFs as errors when reading - Error::Stream(ref e) if e.kind() == io::ErrorKind::ConnectionAborted => Ok(0), - e => Err(e), - } - } - } - - /// Like `write`, but returns an `ssl::Error` rather than an `io::Error`. - /// - /// It is particularly useful with a nonblocking socket, where the error value will identify if - /// OpenSSL is waiting on read or write readiness. - /// - /// This corresponds to [`SSL_write`]. - /// - /// [`SSL_write`]: https://www.openssl.org/docs/manmaster/man3/SSL_write.html - pub fn ssl_write(&mut self, buf: &[u8]) -> Result { - // See above for why we short-circuit on zero-length buffers - if buf.len() == 0 { - return Ok(0); - } - - let ret = self.ssl.write(buf); - if ret > 0 { - Ok(ret as usize) - } else { - Err(self.make_error(ret)) - } - } - - /// Shuts down the session. - /// - /// The shutdown process consists of two steps. The first step sends a close notify message to - /// the peer, after which `ShutdownResult::Sent` is returned. The second step awaits the receipt - /// of a close notify message from the peer, after which `ShutdownResult::Received` is returned. - /// - /// While the connection may be closed after the first step, it is recommended to fully shut the - /// session down. In particular, it must be fully shut down if the connection is to be used for - /// further communication in the future. - /// - /// This corresponds to [`SSL_shutdown`]: https://www.openssl.org/docs/man1.0.2/ssl/SSL_shutdown.html - pub fn shutdown(&mut self) -> Result { - match unsafe { ffi::SSL_shutdown(self.ssl.as_ptr()) } { - 0 => Ok(ShutdownResult::Sent), - 1 => Ok(ShutdownResult::Received), - n => Err(self.make_error(n)), - } - } -} - -impl SslStream { - fn make_error(&mut self, ret: c_int) -> Error { - self.check_panic(); - - match self.ssl.get_error(ret) { - ffi::SSL_ERROR_SSL => Error::Ssl(ErrorStack::get()), - ffi::SSL_ERROR_SYSCALL => { - let errs = ErrorStack::get(); - if errs.errors().is_empty() { - match self.get_bio_error() { - Some(err) => Error::Stream(err), - None => Error::Stream(io::Error::new( - io::ErrorKind::ConnectionAborted, - "unexpected EOF observed", - )), - } - } else { - Error::Ssl(errs) - } - } - ffi::SSL_ERROR_ZERO_RETURN => Error::ZeroReturn, - ffi::SSL_ERROR_WANT_WRITE => { - let err = match self.get_bio_error() { - Some(err) => err, - None => io::Error::new( - io::ErrorKind::Other, - "BUG: got an SSL_ERROR_WANT_WRITE with no error in the BIO", - ), - }; - Error::WantWrite(err) - } - ffi::SSL_ERROR_WANT_READ => { - let err = match self.get_bio_error() { - Some(err) => err, - None => io::Error::new(io::ErrorKind::Other, RetryError), - }; - Error::WantRead(err) - } - err => Error::Stream(io::Error::new( - io::ErrorKind::InvalidData, - format!("unexpected error {}", err), - )), - } - } - - fn check_panic(&mut self) { - if let Some(err) = unsafe { bio::take_panic::(self.ssl.get_raw_rbio()) } { - resume_unwind(err) - } - } - - fn get_bio_error(&mut self) -> Option { - unsafe { bio::take_error::(self.ssl.get_raw_rbio()) } - } - - /// Returns a shared reference to the underlying stream. - pub fn get_ref(&self) -> &S { - unsafe { - let bio = self.ssl.get_raw_rbio(); - bio::get_ref(bio) - } - } - - /// Returns a mutable reference to the underlying stream. - /// - /// # Warning - /// - /// It is inadvisable to read from or write to the underlying stream as it - /// will most likely corrupt the SSL session. - pub fn get_mut(&mut self) -> &mut S { - unsafe { - let bio = self.ssl.get_raw_rbio(); - bio::get_mut(bio) - } - } - - /// Returns a shared reference to the `Ssl` object associated with this stream. - pub fn ssl(&self) -> &SslRef { - &self.ssl - } -} - -impl Read for SslStream { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - loop { - match self.ssl_read(buf) { - Ok(n) => return Ok(n), - Err(Error::ZeroReturn) => return Ok(0), - Err(Error::WantRead(ref e)) - if e.get_ref().map_or(false, |e| e.is::()) => {} - Err(Error::Stream(e)) | Err(Error::WantRead(e)) | Err(Error::WantWrite(e)) => { - return Err(e); - } - Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)), - } - } - } -} - -impl Write for SslStream { - fn write(&mut self, buf: &[u8]) -> io::Result { - loop { - match self.ssl_write(buf) { - Ok(n) => return Ok(n), - Err(Error::WantRead(ref e)) - if e.get_ref().map_or(false, |e| e.is::()) => {} - Err(Error::Stream(e)) | Err(Error::WantRead(e)) | Err(Error::WantWrite(e)) => { - return Err(e); - } - Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)), - } - } - } - - fn flush(&mut self) -> io::Result<()> { - self.get_mut().flush() - } -} - -/// The result of a shutdown request. -#[derive(Copy, Clone, Debug, PartialEq, Eq)] -pub enum ShutdownResult { - /// A close notify message has been sent to the peer. - Sent, - - /// A close notify response message has been received from the peer. - Received, -} - -#[cfg(ossl110)] -mod compat { - use std::ptr; - - use ffi; - use libc::c_int; - - pub use ffi::{SSL_CTX_clear_options, SSL_CTX_get_options, SSL_CTX_set_options, SSL_CTX_up_ref, - SSL_SESSION_get_master_key, SSL_SESSION_up_ref, SSL_is_server}; - - pub unsafe fn get_new_idx(f: ffi::CRYPTO_EX_free) -> c_int { - ffi::CRYPTO_get_ex_new_index( - ffi::CRYPTO_EX_INDEX_SSL_CTX, - 0, - ptr::null_mut(), - None, - None, - Some(f), - ) - } - - pub unsafe fn get_new_ssl_idx(f: ffi::CRYPTO_EX_free) -> c_int { - ffi::CRYPTO_get_ex_new_index( - ffi::CRYPTO_EX_INDEX_SSL, - 0, - ptr::null_mut(), - None, - None, - Some(f), - ) - } - - pub fn tls_method() -> *const ffi::SSL_METHOD { - unsafe { ffi::TLS_method() } - } - - pub fn dtls_method() -> *const ffi::SSL_METHOD { - unsafe { ffi::DTLS_method() } - } -} - -#[cfg(ossl10x)] -#[allow(bad_style)] -mod compat { - use std::ptr; - - use ffi; - use libc::{self, c_int, c_long, c_uchar, c_ulong, size_t}; - - pub unsafe fn SSL_CTX_get_options(ctx: *const ffi::SSL_CTX) -> c_ulong { - ffi::SSL_CTX_ctrl(ctx as *mut _, ffi::SSL_CTRL_OPTIONS, 0, ptr::null_mut()) as c_ulong - } - - pub unsafe fn SSL_CTX_set_options(ctx: *const ffi::SSL_CTX, op: c_ulong) -> c_ulong { - ffi::SSL_CTX_ctrl( - ctx as *mut _, - ffi::SSL_CTRL_OPTIONS, - op as c_long, - ptr::null_mut(), - ) as c_ulong - } - - pub unsafe fn SSL_CTX_clear_options(ctx: *const ffi::SSL_CTX, op: c_ulong) -> c_ulong { - ffi::SSL_CTX_ctrl( - ctx as *mut _, - ffi::SSL_CTRL_CLEAR_OPTIONS, - op as c_long, - ptr::null_mut(), - ) as c_ulong - } - - pub unsafe fn get_new_idx(f: ffi::CRYPTO_EX_free) -> c_int { - ffi::SSL_CTX_get_ex_new_index(0, ptr::null_mut(), None, None, Some(f)) - } - - pub unsafe fn get_new_ssl_idx(f: ffi::CRYPTO_EX_free) -> c_int { - ffi::SSL_get_ex_new_index(0, ptr::null_mut(), None, None, Some(f)) - } - - pub unsafe fn SSL_CTX_up_ref(ssl: *mut ffi::SSL_CTX) -> libc::c_int { - ffi::CRYPTO_add_lock( - &mut (*ssl).references, - 1, - ffi::CRYPTO_LOCK_SSL_CTX, - "mod.rs\0".as_ptr() as *const _, - line!() as libc::c_int, - ); - 0 - } - - pub unsafe fn SSL_SESSION_get_master_key( - session: *const ffi::SSL_SESSION, - out: *mut c_uchar, - mut outlen: size_t, - ) -> size_t { - if outlen == 0 { - return (*session).master_key_length as size_t; - } - if outlen > (*session).master_key_length as size_t { - outlen = (*session).master_key_length as size_t; - } - ptr::copy_nonoverlapping((*session).master_key.as_ptr(), out, outlen); - outlen - } - - pub fn tls_method() -> *const ffi::SSL_METHOD { - unsafe { ffi::SSLv23_method() } - } - - pub fn dtls_method() -> *const ffi::SSL_METHOD { - unsafe { ffi::DTLSv1_method() } - } - - pub unsafe fn SSL_is_server(s: *mut ffi::SSL) -> c_int { - (*s).server - } - - pub unsafe fn SSL_SESSION_up_ref(ses: *mut ffi::SSL_SESSION) -> c_int { - ffi::CRYPTO_add_lock( - &mut (*ses).references, - 1, - ffi::CRYPTO_LOCK_SSL_CTX, - "mod.rs\0".as_ptr() as *const _, - line!() as libc::c_int, - ); - 0 - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/tests/mod.rs cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/tests/mod.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/tests/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/tests/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1416 +0,0 @@ -#![allow(unused_imports)] - -use std::env; -use std::fs::File; -use std::io::prelude::*; -use std::io::{self, BufReader}; -use std::iter; -use std::mem; -use std::net::{TcpStream, TcpListener, SocketAddr}; -use std::path::Path; -use std::process::{Command, Child, Stdio, ChildStdin}; -use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; -use std::thread; -use std::time::Duration; -use tempdir::TempDir; - -use dh::Dh; -use hash::MessageDigest; -use ocsp::{OcspResponse, RESPONSE_STATUS_UNAUTHORIZED}; -use ssl; -use ssl::{SslMethod, HandshakeError, SslContext, SslStream, Ssl, ShutdownResult, - SslConnectorBuilder, SslAcceptorBuilder, Error, SSL_VERIFY_PEER, SSL_VERIFY_NONE, - STATUS_TYPE_OCSP}; -use x509::{X509StoreContext, X509, X509Name, X509_FILETYPE_PEM}; -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -use x509::verify::X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS; -use pkey::PKey; - -use std::net::UdpSocket; - -mod select; - -static ROOT_CERT: &'static [u8] = include_bytes!("../../../test/root-ca.pem"); -static CERT: &'static [u8] = include_bytes!("../../../test/cert.pem"); -static KEY: &'static [u8] = include_bytes!("../../../test/key.pem"); - -fn next_addr() -> SocketAddr { - use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; - static PORT: AtomicUsize = ATOMIC_USIZE_INIT; - let port = 15411 + PORT.fetch_add(1, Ordering::SeqCst); - - format!("127.0.0.1:{}", port).parse().unwrap() -} - -struct Server { - p: Child, - _temp: TempDir, -} - -impl Server { - fn spawn(args: &[&str], input: Option>) -> (Server, SocketAddr) { - let td = TempDir::new("openssl").unwrap(); - let cert = td.path().join("cert.pem"); - let key = td.path().join("key.pem"); - File::create(&cert).unwrap().write_all(CERT).unwrap(); - File::create(&key).unwrap().write_all(KEY).unwrap(); - - let addr = next_addr(); - let mut child = Command::new("openssl") - .arg("s_server") - .arg("-accept") - .arg(addr.port().to_string()) - .args(args) - .arg("-cert") - .arg(&cert) - .arg("-key") - .arg(&key) - .arg("-no_dhe") - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .stdin(Stdio::piped()) - .spawn() - .unwrap(); - let stdin = child.stdin.take().unwrap(); - if let Some(mut input) = input { - thread::spawn(move || input(stdin)); - } - ( - Server { - p: child, - _temp: td, - }, - addr, - ) - } - - fn new_tcp(args: &[&str]) -> (Server, TcpStream) { - let (server, addr) = Server::spawn(args, None); - for _ in 0..20 { - match TcpStream::connect(&addr) { - Ok(s) => return (server, s), - Err(ref e) if e.kind() == io::ErrorKind::ConnectionRefused => { - thread::sleep(Duration::from_millis(100)); - } - Err(e) => panic!("wut: {}", e), - } - } - panic!("server never came online"); - } - - fn new() -> (Server, TcpStream) { - Server::new_tcp(&["-www"]) - } - - #[allow(dead_code)] - fn new_alpn() -> (Server, TcpStream) { - Server::new_tcp( - &[ - "-www", - "-nextprotoneg", - "http/1.1,spdy/3.1", - "-alpn", - "http/1.1,spdy/3.1", - ], - ) - } -} - -impl Drop for Server { - fn drop(&mut self) { - let _ = self.p.kill(); - let _ = self.p.wait(); - } -} - -macro_rules! run_test( - ($module:ident, $blk:expr) => ( - #[cfg(test)] - mod $module { - use std::io; - use std::io::prelude::*; - use std::path::Path; - use std::net::UdpSocket; - use std::net::TcpStream; - use ssl; - use ssl::SslMethod; - use ssl::{SslContext, Ssl, SslStream}; - use ssl::SSL_VERIFY_PEER; - use hash::MessageDigest; - use x509::X509StoreContext; - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - use x509::X509; - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - use x509::store::X509StoreBuilder; - use hex::FromHex; - use foreign_types::ForeignTypeRef; - use super::Server; - #[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] - use super::ROOT_CERT; - - #[test] - fn sslv23() { - let (_s, stream) = Server::new(); - $blk(SslMethod::tls(), stream); - } - } - ); -); - -run_test!( - new_ctx, - |method, _| { SslContext::builder(method).unwrap(); } -); - -run_test!(verify_untrusted, |method, stream| { - let mut ctx = SslContext::builder(method).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - - match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(_) => panic!("expected failure"), - Err(err) => println!("error {:?}", err), - } -}); - -run_test!(verify_trusted, |method, stream| { - let mut ctx = SslContext::builder(method).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - - match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(_) => (), - Err(err) => panic!("Expected success, got {:?}", err), - } -}); - -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -run_test!(verify_trusted_with_set_cert, |method, stream| { - let x509 = X509::from_pem(ROOT_CERT).unwrap(); - let mut store = X509StoreBuilder::new().unwrap(); - store.add_cert(x509).unwrap(); - - let mut ctx = SslContext::builder(method).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - - match ctx.set_verify_cert_store(store.build()) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(_) => (), - Err(err) => panic!("Expected success, got {:?}", err), - } -}); - -run_test!(verify_untrusted_callback_override_ok, |method, stream| { - let mut ctx = SslContext::builder(method).unwrap(); - ctx.set_verify_callback(SSL_VERIFY_PEER, |_, _| true); - - match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(_) => (), - Err(err) => panic!("Expected success, got {:?}", err), - } -}); - -run_test!(verify_untrusted_callback_override_bad, |method, stream| { - let mut ctx = SslContext::builder(method).unwrap(); - ctx.set_verify_callback(SSL_VERIFY_PEER, |_, _| false); - - assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err()); -}); - -run_test!(verify_trusted_callback_override_ok, |method, stream| { - let mut ctx = SslContext::builder(method).unwrap(); - ctx.set_verify_callback(SSL_VERIFY_PEER, |_, _| true); - - match ctx.set_ca_file(&Path::new("test/cert.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(_) => (), - Err(err) => panic!("Expected success, got {:?}", err), - } -}); - -run_test!(verify_trusted_callback_override_bad, |method, stream| { - let mut ctx = SslContext::builder(method).unwrap(); - ctx.set_verify_callback(SSL_VERIFY_PEER, |_, _| false); - - match ctx.set_ca_file(&Path::new("test/cert.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err()); -}); - -run_test!(verify_callback_load_certs, |method, stream| { - let mut ctx = SslContext::builder(method).unwrap(); - ctx.set_verify_callback(SSL_VERIFY_PEER, |_, x509_ctx| { - assert!(x509_ctx.current_cert().is_some()); - true - }); - - assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_ok()); -}); - -run_test!(verify_trusted_get_error_ok, |method, stream| { - let mut ctx = SslContext::builder(method).unwrap(); - ctx.set_verify_callback(SSL_VERIFY_PEER, |_, x509_ctx| { - assert!(x509_ctx.error().is_none()); - true - }); - - match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_ok()); -}); - -run_test!(verify_trusted_get_error_err, |method, stream| { - let mut ctx = SslContext::builder(method).unwrap(); - ctx.set_verify_callback(SSL_VERIFY_PEER, |_, x509_ctx| { - assert!(x509_ctx.error().is_some()); - false - }); - - assert!(Ssl::new(&ctx.build()).unwrap().connect(stream).is_err()); -}); - -run_test!(verify_callback_data, |method, stream| { - let mut ctx = SslContext::builder(method).unwrap(); - - // Node id was generated as SHA256 hash of certificate "test/cert.pem" - // in DER format. - // Command: openssl x509 -in test/cert.pem -outform DER | openssl dgst -sha256 - // Please update if "test/cert.pem" will ever change - let node_hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; - let node_id = Vec::from_hex(node_hash_str).unwrap(); - ctx.set_verify_callback(SSL_VERIFY_PEER, move |_preverify_ok, x509_ctx| { - let cert = x509_ctx.current_cert(); - match cert { - None => false, - Some(cert) => { - let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); - fingerprint == node_id - } - } - }); - ctx.set_verify_depth(1); - - match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(_) => (), - Err(err) => panic!("Expected success, got {:?}", err), - } -}); - -run_test!(ssl_verify_callback, |method, stream| { - use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; - - static CHECKED: AtomicUsize = ATOMIC_USIZE_INIT; - - let ctx = SslContext::builder(method).unwrap(); - let mut ssl = Ssl::new(&ctx.build()).unwrap(); - - let node_hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; - let node_id = Vec::from_hex(node_hash_str).unwrap(); - ssl.set_verify_callback(SSL_VERIFY_PEER, move |_, x509| { - CHECKED.store(1, Ordering::SeqCst); - match x509.current_cert() { - None => false, - Some(cert) => { - let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); - fingerprint == node_id - } - } - }); - - match ssl.connect(stream) { - Ok(_) => (), - Err(err) => panic!("Expected success, got {:?}", err), - } - - assert_eq!(CHECKED.load(Ordering::SeqCst), 1); -}); - -// Make sure every write call translates to a write call to the underlying socket. -#[test] -fn test_write_hits_stream() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - - let guard = thread::spawn(move || { - let ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let stream = TcpStream::connect(addr).unwrap(); - let mut stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); - - stream.write_all(b"hello").unwrap(); - stream - }); - - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) - .unwrap(); - let stream = listener.accept().unwrap().0; - let mut stream = Ssl::new(&ctx.build()).unwrap().accept(stream).unwrap(); - - let mut buf = [0; 5]; - assert_eq!(5, stream.read(&mut buf).unwrap()); - assert_eq!(&b"hello"[..], &buf[..]); - guard.join().unwrap(); -} - -#[test] -fn test_set_certificate_and_private_key() { - let key = include_bytes!("../../../test/key.pem"); - let key = PKey::private_key_from_pem(key).unwrap(); - let cert = include_bytes!("../../../test/cert.pem"); - let cert = X509::from_pem(cert).unwrap(); - - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_private_key(&key).unwrap(); - ctx.set_certificate(&cert).unwrap(); - - assert!(ctx.check_private_key().is_ok()); -} - -run_test!(get_ctx_options, |method, _| { - let ctx = SslContext::builder(method).unwrap(); - ctx.options(); -}); - -run_test!(set_ctx_options, |method, _| { - let mut ctx = SslContext::builder(method).unwrap(); - let opts = ctx.set_options(ssl::SSL_OP_NO_TICKET); - assert!(opts.contains(ssl::SSL_OP_NO_TICKET)); -}); - -run_test!(clear_ctx_options, |method, _| { - let mut ctx = SslContext::builder(method).unwrap(); - ctx.set_options(ssl::SSL_OP_ALL); - let opts = ctx.clear_options(ssl::SSL_OP_ALL); - assert!(!opts.contains(ssl::SSL_OP_ALL)); -}); - -#[test] -fn test_write() { - let (_s, stream) = Server::new(); - let ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let mut stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); - stream.write_all("hello".as_bytes()).unwrap(); - stream.flush().unwrap(); - stream.write_all(" there".as_bytes()).unwrap(); - stream.flush().unwrap(); -} - -#[test] -fn zero_length_buffers() { - let (_s, stream) = Server::new(); - let ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let mut stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); - - assert_eq!(stream.write(b"").unwrap(), 0); - assert_eq!(stream.read(&mut []).unwrap(), 0); -} - -run_test!(get_peer_certificate, |method, stream| { - let ctx = SslContext::builder(method).unwrap(); - let stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); - let cert = stream.ssl().peer_certificate().unwrap(); - let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); - let node_hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; - let node_id = Vec::from_hex(node_hash_str).unwrap(); - assert_eq!(node_id, fingerprint) -}); - -#[test] -fn test_read() { - let (_s, tcp) = Server::new(); - let ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let mut stream = Ssl::new(&ctx.build()).unwrap().connect(tcp).unwrap(); - stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); - stream.flush().unwrap(); - io::copy(&mut stream, &mut io::sink()).ok().expect( - "read error", - ); -} - -#[test] -fn test_pending() { - let (_s, tcp) = Server::new(); - let ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let mut stream = Ssl::new(&ctx.build()).unwrap().connect(tcp).unwrap(); - stream.write_all("GET /\r\n\r\n".as_bytes()).unwrap(); - stream.flush().unwrap(); - - // wait for the response and read first byte... - let mut buf = [0u8; 16 * 1024]; - stream.read(&mut buf[..1]).unwrap(); - - let pending = stream.ssl().pending(); - let len = stream.read(&mut buf[1..]).unwrap(); - - assert_eq!(pending, len); - - stream.read(&mut buf[..1]).unwrap(); - - let pending = stream.ssl().pending(); - let len = stream.read(&mut buf[1..]).unwrap(); - assert_eq!(pending, len); -} - -#[test] -fn test_state() { - let (_s, tcp) = Server::new(); - let ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let stream = Ssl::new(&ctx.build()).unwrap().connect(tcp).unwrap(); - assert_eq!(stream.ssl().state_string(), "SSLOK "); - assert_eq!( - stream.ssl().state_string_long(), - "SSL negotiation finished successfully" - ); -} - -/// Tests that connecting with the client using ALPN, but the server not does not -/// break the existing connection behavior. -#[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -fn test_connect_with_unilateral_alpn() { - let (_s, stream) = Server::new(); - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); - match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(stream) => stream, - Err(err) => panic!("Expected success, got {:?}", err), - }; - // Since the socket to which we connected is not configured to use ALPN, - // there should be no selected protocol... - assert!(stream.ssl().selected_alpn_protocol().is_none()); -} - -/// Tests that connecting with the client using NPN, but the server not does not -/// break the existing connection behavior. -#[test] -#[cfg(not(any(libressl261, libressl262, libressl26x)))] -fn test_connect_with_unilateral_npn() { - let (_s, stream) = Server::new(); - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); - match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(stream) => stream, - Err(err) => panic!("Expected success, got {:?}", err), - }; - // Since the socket to which we connected is not configured to use NPN, - // there should be no selected protocol... - assert!(stream.ssl().selected_npn_protocol().is_none()); -} - -/// Tests that when both the client as well as the server use ALPN and their -/// lists of supported protocols have an overlap, the correct protocol is chosen. -#[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -fn test_connect_with_alpn_successful_multiple_matching() { - let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"spdy/3.1", b"http/1.1"]).unwrap(); - match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(stream) => stream, - Err(err) => panic!("Expected success, got {:?}", err), - }; - // The server prefers "http/1.1", so that is chosen, even though the client - // would prefer "spdy/3.1" - assert_eq!(b"http/1.1", stream.ssl().selected_alpn_protocol().unwrap()); -} - -/// Tests that when both the client as well as the server use NPN and their -/// lists of supported protocols have an overlap, the correct protocol is chosen. -#[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -fn test_connect_with_npn_successful_multiple_matching() { - let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_npn_protocols(&[b"spdy/3.1", b"http/1.1"]).unwrap(); - match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(stream) => stream, - Err(err) => panic!("Expected success, got {:?}", err), - }; - // The server prefers "http/1.1", so that is chosen, even though the client - // would prefer "spdy/3.1" - assert_eq!(b"http/1.1", stream.ssl().selected_npn_protocol().unwrap()); -} - -/// Tests that when both the client as well as the server use ALPN and their -/// lists of supported protocols have an overlap -- with only ONE protocol -/// being valid for both. -#[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -fn test_connect_with_alpn_successful_single_match() { - let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"spdy/3.1"]).unwrap(); - match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(stream) => stream, - Err(err) => panic!("Expected success, got {:?}", err), - }; - // The client now only supports one of the server's protocols, so that one - // is used. - assert_eq!(b"spdy/3.1", stream.ssl().selected_alpn_protocol().unwrap()); -} - - -/// Tests that when both the client as well as the server use NPN and their -/// lists of supported protocols have an overlap -- with only ONE protocol -/// being valid for both. -#[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -fn test_connect_with_npn_successful_single_match() { - let (_s, stream) = Server::new_alpn(); - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_npn_protocols(&[b"spdy/3.1"]).unwrap(); - match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(stream) => stream, - Err(err) => panic!("Expected success, got {:?}", err), - }; - // The client now only supports one of the server's protocols, so that one - // is used. - assert_eq!(b"spdy/3.1", stream.ssl().selected_npn_protocol().unwrap()); -} - -/// Tests that when the `SslStream` is created as a server stream, the protocols -/// are correctly advertised to the client. -#[test] -#[cfg(not(any(libressl261, libressl262, libressl26x)))] -fn test_npn_server_advertise_multiple() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let localhost = listener.local_addr().unwrap(); - // We create a different context instance for the server... - let listener_ctx = { - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_npn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); - assert!( - ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) - .is_ok() - ); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.build() - }; - // Have the listener wait on the connection in a different thread. - thread::spawn(move || { - let (stream, _) = listener.accept().unwrap(); - Ssl::new(&listener_ctx).unwrap().accept(stream).unwrap(); - }); - - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_npn_protocols(&[b"spdy/3.1"]).unwrap(); - match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - // Now connect to the socket and make sure the protocol negotiation works... - let stream = TcpStream::connect(localhost).unwrap(); - let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(stream) => stream, - Err(err) => panic!("Expected success, got {:?}", err), - }; - // SPDY is selected since that's the only thing the client supports. - assert_eq!(b"spdy/3.1", stream.ssl().selected_npn_protocol().unwrap()); -} - -/// Tests that when the `SslStream` is created as a server stream, the protocols -/// are correctly advertised to the client. -#[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -fn test_alpn_server_advertise_multiple() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let localhost = listener.local_addr().unwrap(); - // We create a different context instance for the server... - let listener_ctx = { - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); - assert!( - ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) - .is_ok() - ); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.build() - }; - // Have the listener wait on the connection in a different thread. - thread::spawn(move || { - let (stream, _) = listener.accept().unwrap(); - Ssl::new(&listener_ctx).unwrap().accept(stream).unwrap(); - }); - - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"spdy/3.1"]).unwrap(); - match ctx.set_ca_file(&Path::new("test/root-ca.pem")) { - Ok(_) => {} - Err(err) => panic!("Unexpected error {:?}", err), - } - // Now connect to the socket and make sure the protocol negotiation works... - let stream = TcpStream::connect(localhost).unwrap(); - let stream = match Ssl::new(&ctx.build()).unwrap().connect(stream) { - Ok(stream) => stream, - Err(err) => panic!("Expected success, got {:?}", err), - }; - // SPDY is selected since that's the only thing the client supports. - assert_eq!(b"spdy/3.1", stream.ssl().selected_alpn_protocol().unwrap()); -} - -/// Test that Servers supporting ALPN don't report a protocol when none of their protocols match -/// the client's reported protocol. -#[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -fn test_alpn_server_select_none() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let localhost = listener.local_addr().unwrap(); - // We create a different context instance for the server... - let listener_ctx = { - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"http/1.1", b"spdy/3.1"]).unwrap(); - assert!( - ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) - .is_ok() - ); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.build() - }; - // Have the listener wait on the connection in a different thread. - thread::spawn(move || { - let (stream, _) = listener.accept().unwrap(); - Ssl::new(&listener_ctx).unwrap().accept(stream).unwrap(); - }); - - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - ctx.set_alpn_protocols(&[b"http/2"]).unwrap(); - ctx.set_ca_file(&Path::new("test/root-ca.pem")).unwrap(); - // Now connect to the socket and make sure the protocol negotiation works... - let stream = TcpStream::connect(localhost).unwrap(); - let stream = Ssl::new(&ctx.build()).unwrap().connect(stream).unwrap(); - - // Since the protocols from the server and client don't overlap at all, no protocol is selected - assert_eq!(None, stream.ssl().selected_alpn_protocol()); -} - -fn wait_io(stream: &TcpStream, read: bool, timeout_ms: u32) -> bool { - unsafe { - let mut set: select::fd_set = mem::zeroed(); - select::fd_set(&mut set, stream); - - let write = if read { - 0 as *mut _ - } else { - &mut set as *mut _ - }; - let read = if !read { - 0 as *mut _ - } else { - &mut set as *mut _ - }; - select::select(stream, read, write, 0 as *mut _, timeout_ms).unwrap() - } -} - -fn handshake(res: Result, HandshakeError>) -> SslStream { - match res { - Ok(s) => s, - Err(HandshakeError::Interrupted(s)) => { - wait_io(s.get_ref(), true, 1_000); - handshake(s.handshake()) - } - Err(err) => panic!("error on handshake {:?}", err), - } -} - -#[test] -fn test_write_nonblocking() { - let (_s, stream) = Server::new(); - stream.set_nonblocking(true).unwrap(); - let cx = SslContext::builder(SslMethod::tls()).unwrap().build(); - let mut stream = handshake(Ssl::new(&cx).unwrap().connect(stream)); - - let mut iterations = 0; - loop { - iterations += 1; - if iterations > 7 { - // Probably a safe assumption for the foreseeable future of - // openssl. - panic!("Too many read/write round trips in handshake!!"); - } - let result = stream.ssl_write(b"hello"); - match result { - Ok(_) => { - break; - } - Err(Error::WantRead(_)) => { - assert!(wait_io(stream.get_ref(), true, 1000)); - } - Err(Error::WantWrite(_)) => { - assert!(wait_io(stream.get_ref(), false, 1000)); - } - Err(other) => { - panic!("Unexpected SSL Error: {:?}", other); - } - } - } - - // Second write should succeed immediately--plenty of space in kernel - // buffer, and handshake just completed. - stream.write(" there".as_bytes()).unwrap(); -} - -#[test] -#[cfg_attr(any(libressl, windows, target_arch = "arm"), ignore)] // FIXME(#467) -fn test_read_nonblocking() { - let (_s, stream) = Server::new(); - stream.set_nonblocking(true).unwrap(); - let cx = SslContext::builder(SslMethod::tls()).unwrap().build(); - let mut stream = handshake(Ssl::new(&cx).unwrap().connect(stream)); - - let mut iterations = 0; - loop { - iterations += 1; - if iterations > 7 { - // Probably a safe assumption for the foreseeable future of - // openssl. - panic!("Too many read/write round trips in handshake!!"); - } - let result = stream.ssl_write(b"GET /\r\n\r\n"); - match result { - Ok(n) => { - assert_eq!(n, 9); - break; - } - Err(Error::WantRead(..)) => { - assert!(wait_io(stream.get_ref(), true, 1000)); - } - Err(Error::WantWrite(..)) => { - assert!(wait_io(stream.get_ref(), false, 1000)); - } - Err(other) => { - panic!("Unexpected SSL Error: {:?}", other); - } - } - } - let mut input_buffer = [0u8; 1500]; - let result = stream.ssl_read(&mut input_buffer); - let bytes_read = match result { - Ok(n) => { - // This branch is unlikely, but on an overloaded VM with - // unlucky context switching, the response could actually - // be in the receive buffer before we issue the read() syscall... - n - } - Err(Error::WantRead(..)) => { - assert!(wait_io(stream.get_ref(), true, 3000)); - // Second read should return application data. - stream.read(&mut input_buffer).unwrap() - } - Err(other) => { - panic!("Unexpected SSL Error: {:?}", other); - } - }; - assert!(bytes_read >= 5); - assert_eq!(&input_buffer[..5], b"HTTP/"); -} - -#[test] -#[should_panic(expected = "blammo")] -fn write_panic() { - struct ExplodingStream(TcpStream); - - impl Read for ExplodingStream { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.0.read(buf) - } - } - - impl Write for ExplodingStream { - fn write(&mut self, _: &[u8]) -> io::Result { - panic!("blammo"); - } - - fn flush(&mut self) -> io::Result<()> { - self.0.flush() - } - } - - let (_s, stream) = Server::new(); - let stream = ExplodingStream(stream); - - let ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let _ = Ssl::new(&ctx.build()).unwrap().connect(stream); -} - -#[test] -#[should_panic(expected = "blammo")] -fn read_panic() { - struct ExplodingStream(TcpStream); - - impl Read for ExplodingStream { - fn read(&mut self, _: &mut [u8]) -> io::Result { - panic!("blammo"); - } - } - - impl Write for ExplodingStream { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.0.write(buf) - } - - fn flush(&mut self) -> io::Result<()> { - self.0.flush() - } - } - - let (_s, stream) = Server::new(); - let stream = ExplodingStream(stream); - - let ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let _ = Ssl::new(&ctx.build()).unwrap().connect(stream); -} - -#[test] -#[should_panic(expected = "blammo")] -fn flush_panic() { - struct ExplodingStream(TcpStream); - - impl Read for ExplodingStream { - fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.0.read(buf) - } - } - - impl Write for ExplodingStream { - fn write(&mut self, buf: &[u8]) -> io::Result { - self.0.write(buf) - } - - fn flush(&mut self) -> io::Result<()> { - panic!("blammo"); - } - } - - let (_s, stream) = Server::new(); - let stream = ExplodingStream(stream); - - let ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let mut stream = Ssl::new(&ctx.build()) - .unwrap() - .connect(stream) - .ok() - .unwrap(); - let _ = stream.flush(); -} - -#[test] -fn refcount_ssl_context() { - let mut ssl = { - let ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ssl::Ssl::new(&ctx.build()).unwrap() - }; - - { - let new_ctx_a = SslContext::builder(SslMethod::tls()).unwrap().build(); - let _new_ctx_b = ssl.set_ssl_context(&new_ctx_a); - } -} - -#[test] -fn default_verify_paths() { - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_default_verify_paths().unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - let s = TcpStream::connect("google.com:443").unwrap(); - let mut socket = Ssl::new(&ctx.build()).unwrap().connect(s).unwrap(); - - socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); - let mut result = vec![]; - socket.read_to_end(&mut result).unwrap(); - - println!("{}", String::from_utf8_lossy(&result)); - assert!(result.starts_with(b"HTTP/1.0")); - assert!(result.ends_with(b"\r\n") || result.ends_with(b"")); -} - -#[test] -fn add_extra_chain_cert() { - let cert = include_bytes!("../../../test/cert.pem"); - let cert = X509::from_pem(cert).unwrap(); - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.add_extra_chain_cert(cert).unwrap(); -} - -#[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -fn verify_valid_hostname() { - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_default_verify_paths().unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - - let mut ssl = Ssl::new(&ctx.build()).unwrap(); - ssl.param_mut().set_hostflags( - X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS, - ); - ssl.param_mut().set_host("google.com").unwrap(); - - let s = TcpStream::connect("google.com:443").unwrap(); - let mut socket = ssl.connect(s).unwrap(); - - socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); - let mut result = vec![]; - socket.read_to_end(&mut result).unwrap(); - - println!("{}", String::from_utf8_lossy(&result)); - assert!(result.starts_with(b"HTTP/1.0")); - assert!(result.ends_with(b"\r\n") || result.ends_with(b"")); -} - -#[test] -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -fn verify_invalid_hostname() { - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_default_verify_paths().unwrap(); - ctx.set_verify(SSL_VERIFY_PEER); - - let mut ssl = Ssl::new(&ctx.build()).unwrap(); - ssl.param_mut().set_hostflags( - X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS, - ); - ssl.param_mut().set_host("foobar.com").unwrap(); - - let s = TcpStream::connect("google.com:443").unwrap(); - assert!(ssl.connect(s).is_err()); -} - -#[test] -fn connector_valid_hostname() { - let connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap().build(); - - let s = TcpStream::connect("google.com:443").unwrap(); - let mut socket = connector.connect("google.com", s).unwrap(); - - socket.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); - let mut result = vec![]; - socket.read_to_end(&mut result).unwrap(); - - println!("{}", String::from_utf8_lossy(&result)); - assert!(result.starts_with(b"HTTP/1.0")); - assert!(result.ends_with(b"\r\n") || result.ends_with(b"")); -} - -#[test] -fn connector_invalid_hostname() { - let connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap().build(); - - let s = TcpStream::connect("google.com:443").unwrap(); - assert!(connector.connect("foobar.com", s).is_err()); -} - -#[test] -fn connector_invalid_no_hostname_verification() { - let connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap().build(); - - let s = TcpStream::connect("google.com:443").unwrap(); - connector.danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication(s) - .unwrap(); -} - -#[test] -fn connector_no_hostname_still_verifies() { - let (_s, tcp) = Server::new(); - - let connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap().build(); - - assert!(connector.danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication(tcp) - .is_err()); -} - -#[test] -fn connector_no_hostname_can_disable_verify() { - let (_s, tcp) = Server::new(); - - let mut connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap(); - connector.set_verify(SSL_VERIFY_NONE); - let connector = connector.build(); - - connector.danger_connect_without_providing_domain_for_certificate_verification_and_server_name_indication(tcp).unwrap(); -} - -#[test] -fn connector_client_server_mozilla_intermediate() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - - let t = thread::spawn(move || { - let key = PKey::private_key_from_pem(KEY).unwrap(); - let cert = X509::from_pem(CERT).unwrap(); - let connector = - SslAcceptorBuilder::mozilla_intermediate(SslMethod::tls(), &key, &cert, None::) - .unwrap() - .build(); - let stream = listener.accept().unwrap().0; - let mut stream = connector.accept(stream).unwrap(); - - stream.write_all(b"hello").unwrap(); - }); - - let mut connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap(); - connector - .set_ca_file("test/root-ca.pem") - .unwrap(); - let connector = connector.build(); - - let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); - let mut stream = connector.connect("foobar.com", stream).unwrap(); - - let mut buf = [0; 5]; - stream.read_exact(&mut buf).unwrap(); - assert_eq!(b"hello", &buf); - - t.join().unwrap(); -} - -#[test] -fn connector_client_server_mozilla_modern() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - - let t = thread::spawn(move || { - let key = PKey::private_key_from_pem(KEY).unwrap(); - let cert = X509::from_pem(CERT).unwrap(); - let connector = - SslAcceptorBuilder::mozilla_modern(SslMethod::tls(), &key, &cert, None::) - .unwrap() - .build(); - let stream = listener.accept().unwrap().0; - let mut stream = connector.accept(stream).unwrap(); - - stream.write_all(b"hello").unwrap(); - }); - - let mut connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap(); - connector - .set_ca_file("test/root-ca.pem") - .unwrap(); - let connector = connector.build(); - - let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); - let mut stream = connector.connect("foobar.com", stream).unwrap(); - - let mut buf = [0; 5]; - stream.read_exact(&mut buf).unwrap(); - assert_eq!(b"hello", &buf); - - t.join().unwrap(); -} - -#[test] -fn shutdown() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - - thread::spawn(move || { - let stream = listener.accept().unwrap().0; - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) - .unwrap(); - let ssl = Ssl::new(&ctx.build()).unwrap(); - let mut stream = ssl.accept(stream).unwrap(); - - stream.write_all(b"hello").unwrap(); - let mut buf = [0; 1]; - assert_eq!(stream.read(&mut buf).unwrap(), 0); - assert_eq!(stream.shutdown().unwrap(), ShutdownResult::Received); - }); - - let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); - let ctx = SslContext::builder(SslMethod::tls()).unwrap(); - let ssl = Ssl::new(&ctx.build()).unwrap(); - let mut stream = ssl.connect(stream).unwrap(); - - let mut buf = [0; 5]; - stream.read_exact(&mut buf).unwrap(); - assert_eq!(b"hello", &buf); - - assert_eq!(stream.shutdown().unwrap(), ShutdownResult::Sent); - assert_eq!(stream.shutdown().unwrap(), ShutdownResult::Received); -} - -#[test] -fn client_ca_list() { - let names = X509Name::load_client_ca_file("test/root-ca.pem").unwrap(); - assert_eq!(names.len(), 1); - - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_client_ca_list(names); -} - -#[test] -fn cert_store() { - let (_s, tcp) = Server::new(); - - let cert = X509::from_pem(ROOT_CERT).unwrap(); - - let mut ctx = SslConnectorBuilder::new(SslMethod::tls()).unwrap(); - ctx.cert_store_mut().add_cert(cert).unwrap(); - let ctx = ctx.build(); - - ctx.connect("foobar.com", tcp).unwrap(); -} - -#[test] -fn tmp_dh_callback() { - static CALLED_BACK: AtomicBool = ATOMIC_BOOL_INIT; - - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - - thread::spawn(move || { - let stream = listener.accept().unwrap().0; - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.set_tmp_dh_callback(|_, _, _| { - CALLED_BACK.store(true, Ordering::SeqCst); - let dh = include_bytes!("../../../test/dhparams.pem"); - Dh::from_pem(dh) - }); - let ssl = Ssl::new(&ctx.build()).unwrap(); - ssl.accept(stream).unwrap(); - }); - - let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_cipher_list("EDH").unwrap(); - let ssl = Ssl::new(&ctx.build()).unwrap(); - ssl.connect(stream).unwrap(); - - assert!(CALLED_BACK.load(Ordering::SeqCst)); -} - -#[test] -#[cfg(any(all(feature = "v101", ossl101, not(any(libressl261, libressl262, libressl26x))), all(feature = "v102", ossl102)))] -fn tmp_ecdh_callback() { - use ec::EcKey; - use nid; - - static CALLED_BACK: AtomicBool = ATOMIC_BOOL_INIT; - - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - - thread::spawn(move || { - let stream = listener.accept().unwrap().0; - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.set_tmp_ecdh_callback(|_, _, _| { - CALLED_BACK.store(true, Ordering::SeqCst); - EcKey::new_by_curve_name(nid::X9_62_PRIME256V1) - }); - let ssl = Ssl::new(&ctx.build()).unwrap(); - ssl.accept(stream).unwrap(); - }); - - let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_cipher_list("ECDH").unwrap(); - let ssl = Ssl::new(&ctx.build()).unwrap(); - ssl.connect(stream).unwrap(); - - assert!(CALLED_BACK.load(Ordering::SeqCst)); -} - -#[test] -fn tmp_dh_callback_ssl() { - static CALLED_BACK: AtomicBool = ATOMIC_BOOL_INIT; - - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - - thread::spawn(move || { - let stream = listener.accept().unwrap().0; - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) - .unwrap(); - let mut ssl = Ssl::new(&ctx.build()).unwrap(); - ssl.set_tmp_dh_callback(|_, _, _| { - CALLED_BACK.store(true, Ordering::SeqCst); - let dh = include_bytes!("../../../test/dhparams.pem"); - Dh::from_pem(dh) - }); - ssl.accept(stream).unwrap(); - }); - - let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_cipher_list("EDH").unwrap(); - let ssl = Ssl::new(&ctx.build()).unwrap(); - ssl.connect(stream).unwrap(); - - assert!(CALLED_BACK.load(Ordering::SeqCst)); -} - -#[test] -#[cfg(any(all(feature = "v101", ossl101, not(any(libressl261, libressl262, libressl26x))), all(feature = "v102", ossl102)))] -fn tmp_ecdh_callback_ssl() { - use ec::EcKey; - use nid; - - static CALLED_BACK: AtomicBool = ATOMIC_BOOL_INIT; - - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - - thread::spawn(move || { - let stream = listener.accept().unwrap().0; - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) - .unwrap(); - let mut ssl = Ssl::new(&ctx.build()).unwrap(); - ssl.set_tmp_ecdh_callback(|_, _, _| { - CALLED_BACK.store(true, Ordering::SeqCst); - EcKey::new_by_curve_name(nid::X9_62_PRIME256V1) - }); - ssl.accept(stream).unwrap(); - }); - - let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_cipher_list("ECDH").unwrap(); - let ssl = Ssl::new(&ctx.build()).unwrap(); - ssl.connect(stream).unwrap(); - - assert!(CALLED_BACK.load(Ordering::SeqCst)); -} - -#[test] -fn idle_session() { - let ctx = SslContext::builder(SslMethod::tls()).unwrap().build(); - let ssl = Ssl::new(&ctx).unwrap(); - assert!(ssl.session().is_none()); -} - -#[test] -fn active_session() { - let connector = SslConnectorBuilder::new(SslMethod::tls()).unwrap().build(); - - let s = TcpStream::connect("google.com:443").unwrap(); - let socket = connector.connect("google.com", s).unwrap(); - let session = socket.ssl().session().unwrap(); - let len = session.master_key_len(); - let mut buf = vec![0; len - 1]; - let copied = session.master_key(&mut buf); - assert_eq!(copied, buf.len()); - let mut buf = vec![0; len + 1]; - let copied = session.master_key(&mut buf); - assert_eq!(copied, len); -} - -#[test] -fn status_callbacks() { - static CALLED_BACK_SERVER: AtomicBool = ATOMIC_BOOL_INIT; - static CALLED_BACK_CLIENT: AtomicBool = ATOMIC_BOOL_INIT; - - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - - let guard = thread::spawn(move || { - let stream = listener.accept().unwrap().0; - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_certificate_file(&Path::new("test/cert.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.set_private_key_file(&Path::new("test/key.pem"), X509_FILETYPE_PEM) - .unwrap(); - ctx.set_status_callback(|ssl| { - CALLED_BACK_SERVER.store(true, Ordering::SeqCst); - let response = OcspResponse::create(RESPONSE_STATUS_UNAUTHORIZED, None).unwrap(); - let response = response.to_der().unwrap(); - ssl.set_ocsp_status(&response).unwrap(); - Ok(true) - }).unwrap(); - let ssl = Ssl::new(&ctx.build()).unwrap(); - ssl.accept(stream).unwrap(); - }); - - let stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); - let mut ctx = SslContext::builder(SslMethod::tls()).unwrap(); - ctx.set_status_callback(|ssl| { - CALLED_BACK_CLIENT.store(true, Ordering::SeqCst); - let response = OcspResponse::from_der(ssl.ocsp_status().unwrap()).unwrap(); - assert_eq!(response.status(), RESPONSE_STATUS_UNAUTHORIZED); - Ok(true) - }).unwrap(); - let mut ssl = Ssl::new(&ctx.build()).unwrap(); - ssl.set_status_type(STATUS_TYPE_OCSP).unwrap(); - ssl.connect(stream).unwrap(); - - assert!(CALLED_BACK_SERVER.load(Ordering::SeqCst)); - assert!(CALLED_BACK_CLIENT.load(Ordering::SeqCst)); - - guard.join().unwrap(); -} - -fn _check_kinds() { - fn is_send() {} - fn is_sync() {} - - is_send::>(); - is_sync::>(); -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/tests/select.rs cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/tests/select.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/ssl/tests/select.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/ssl/tests/select.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,74 +0,0 @@ -use libc; -pub use self::imp::*; - -#[cfg(unix)] -mod imp { - use std::os::unix::prelude::*; - use std::io; - use libc; - - pub use libc::fd_set; - - pub fn fd_set(set: &mut fd_set, f: &F) { - unsafe { - libc::FD_SET(f.as_raw_fd(), set); - } - } - - pub unsafe fn select( - max: &F, - read: *mut fd_set, - write: *mut fd_set, - error: *mut fd_set, - timeout_ms: u32, - ) -> io::Result { - let mut timeout = libc::timeval { - tv_sec: (timeout_ms / 1000) as libc::time_t, - tv_usec: (timeout_ms % 1000 * 1000) as libc::suseconds_t, - }; - let rc = libc::select(max.as_raw_fd() + 1, read, write, error, &mut timeout); - if rc < 0 { - Err(io::Error::last_os_error()) - } else { - Ok(rc != 0) - } - } -} - -#[cfg(windows)] -mod imp { - extern crate winapi; - extern crate ws2_32; - - use std::os::windows::prelude::*; - use std::io; - use libc::{c_uint, c_long}; - use self::winapi::SOCKET; - use self::winapi::winsock2; - - pub use self::winapi::winsock2::fd_set; - - pub fn fd_set(set: &mut fd_set, f: &F) { - set.fd_array[set.fd_count as usize] = f.as_raw_socket(); - set.fd_count += 1; - } - - pub unsafe fn select( - _max: &F, - read: *mut fd_set, - write: *mut fd_set, - error: *mut fd_set, - timeout_ms: u32, - ) -> io::Result { - let mut timeout = winsock2::timeval { - tv_sec: (timeout_ms / 1000) as c_long, - tv_usec: (timeout_ms % 1000 * 1000) as c_long, - }; - let rc = ws2_32::select(1, read, write, error, &mut timeout); - if rc < 0 { - Err(io::Error::last_os_error()) - } else { - Ok(rc != 0) - } - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/stack.rs cargo-0.26.0/vendor/openssl-0.9.24/src/stack.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/stack.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/stack.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,360 +0,0 @@ -use foreign_types::{ForeignTypeRef, ForeignType, Opaque}; -use libc::c_int; -use std::borrow::Borrow; -use std::convert::AsRef; -use std::iter; -use std::marker::PhantomData; -use std::mem; -use ffi; - -use {cvt, cvt_p}; -use error::ErrorStack; -use std::ops::{Deref, DerefMut, Index, IndexMut}; - -#[cfg(ossl10x)] -use ffi::{sk_pop as OPENSSL_sk_pop, sk_free as OPENSSL_sk_free, sk_num as OPENSSL_sk_num, - sk_value as OPENSSL_sk_value, _STACK as OPENSSL_STACK, - sk_new_null as OPENSSL_sk_new_null, sk_push as OPENSSL_sk_push}; -#[cfg(ossl110)] -use ffi::{OPENSSL_sk_pop, OPENSSL_sk_free, OPENSSL_sk_num, OPENSSL_sk_value, OPENSSL_STACK, - OPENSSL_sk_new_null, OPENSSL_sk_push}; - -/// Trait implemented by types which can be placed in a stack. -/// -/// It should not be implemented for any type outside of this crate. -pub trait Stackable: ForeignType { - /// The C stack type for this element. - /// - /// Generally called `stack_st_{ELEMENT_TYPE}`, normally hidden by the - /// `STACK_OF(ELEMENT_TYPE)` macro in the OpenSSL API. - type StackType; -} - -/// An owned stack of `T`. -pub struct Stack(*mut T::StackType); - -impl Stack { - pub fn new() -> Result, ErrorStack> { - unsafe { - ffi::init(); - let ptr = cvt_p(OPENSSL_sk_new_null())?; - Ok(Stack(ptr as *mut _)) - } - } -} - -impl Drop for Stack { - fn drop(&mut self) { - unsafe { - while let Some(_) = self.pop() {} - OPENSSL_sk_free(self.0 as *mut _); - } - } -} - -impl iter::IntoIterator for Stack { - type IntoIter = IntoIter; - type Item = T; - - fn into_iter(self) -> IntoIter { - let it = IntoIter { - stack: self.0, - idx: 0, - }; - mem::forget(self); - it - } -} - -impl AsRef> for Stack { - fn as_ref(&self) -> &StackRef { - &*self - } -} - -impl Borrow> for Stack { - fn borrow(&self) -> &StackRef { - &*self - } -} - -impl ForeignType for Stack { - type CType = T::StackType; - type Ref = StackRef; - - #[inline] - unsafe fn from_ptr(ptr: *mut T::StackType) -> Stack { - assert!( - !ptr.is_null(), - "Must not instantiate a Stack from a null-ptr - use Stack::new() in \ - that case" - ); - Stack(ptr) - } - - #[inline] - fn as_ptr(&self) -> *mut T::StackType { - self.0 - } -} - -impl Deref for Stack { - type Target = StackRef; - - fn deref(&self) -> &StackRef { - unsafe { StackRef::from_ptr(self.0) } - } -} - -impl DerefMut for Stack { - fn deref_mut(&mut self) -> &mut StackRef { - unsafe { StackRef::from_ptr_mut(self.0) } - } -} - -pub struct IntoIter { - stack: *mut T::StackType, - idx: c_int, -} - -impl IntoIter { - fn stack_len(&self) -> c_int { - unsafe { OPENSSL_sk_num(self.stack as *mut _) } - } -} - -impl Drop for IntoIter { - fn drop(&mut self) { - unsafe { - while let Some(_) = self.next() {} - OPENSSL_sk_free(self.stack as *mut _); - } - } -} - -impl Iterator for IntoIter { - type Item = T; - - fn next(&mut self) -> Option { - unsafe { - if self.idx == self.stack_len() { - None - } else { - let ptr = OPENSSL_sk_value(self.stack as *mut _, self.idx); - self.idx += 1; - Some(T::from_ptr(ptr as *mut _)) - } - } - } - - fn size_hint(&self) -> (usize, Option) { - let size = (self.stack_len() - self.idx) as usize; - (size, Some(size)) - } -} - -impl ExactSizeIterator for IntoIter {} - -pub struct StackRef(Opaque, PhantomData); - -impl ForeignTypeRef for StackRef { - type CType = T::StackType; -} - -impl StackRef { - fn as_stack(&self) -> *mut OPENSSL_STACK { - self.as_ptr() as *mut _ - } - - /// Returns the number of items in the stack - pub fn len(&self) -> usize { - unsafe { OPENSSL_sk_num(self.as_stack()) as usize } - } - - pub fn iter(&self) -> Iter { - // Unfortunately we can't simply convert the stack into a - // slice and use that because OpenSSL 1.1.0 doesn't directly - // expose the stack data (we have to use `OPENSSL_sk_value` - // instead). We have to rewrite the entire iteration framework - // instead. - - Iter { - stack: self, - pos: 0, - } - } - - pub fn iter_mut(&mut self) -> IterMut { - IterMut { - stack: self, - pos: 0, - } - } - - /// Returns a reference to the element at the given index in the - /// stack or `None` if the index is out of bounds - pub fn get(&self, idx: usize) -> Option<&T::Ref> { - unsafe { - if idx >= self.len() { - return None; - } - - Some(T::Ref::from_ptr(self._get(idx))) - } - } - - /// Returns a mutable reference to the element at the given index in the - /// stack or `None` if the index is out of bounds - pub fn get_mut(&mut self, idx: usize) -> Option<&mut T::Ref> { - unsafe { - if idx >= self.len() { - return None; - } - - Some(T::Ref::from_ptr_mut(self._get(idx))) - } - } - - /// Pushes a value onto the top of the stack. - pub fn push(&mut self, data: T) -> Result<(), ErrorStack> { - unsafe { - cvt( - OPENSSL_sk_push(self.as_stack(), data.as_ptr() as *mut _), - )?; - mem::forget(data); - Ok(()) - } - } - - /// Removes the last element from the stack and returns it. - pub fn pop(&mut self) -> Option { - unsafe { - let ptr = OPENSSL_sk_pop(self.as_stack()); - if ptr.is_null() { - None - } else { - Some(T::from_ptr(ptr as *mut _)) - } - } - } - - unsafe fn _get(&self, idx: usize) -> *mut T::CType { - OPENSSL_sk_value(self.as_stack(), idx as c_int) as *mut _ - } -} - -impl Index for StackRef { - type Output = T::Ref; - - fn index(&self, index: usize) -> &T::Ref { - self.get(index).unwrap() - } -} - -impl IndexMut for StackRef { - fn index_mut(&mut self, index: usize) -> &mut T::Ref { - self.get_mut(index).unwrap() - } -} - -impl<'a, T: Stackable> iter::IntoIterator for &'a StackRef { - type Item = &'a T::Ref; - type IntoIter = Iter<'a, T>; - - fn into_iter(self) -> Iter<'a, T> { - self.iter() - } -} - -impl<'a, T: Stackable> iter::IntoIterator for &'a mut StackRef { - type Item = &'a mut T::Ref; - type IntoIter = IterMut<'a, T>; - - fn into_iter(self) -> IterMut<'a, T> { - self.iter_mut() - } -} - -impl<'a, T: Stackable> iter::IntoIterator for &'a Stack { - type Item = &'a T::Ref; - type IntoIter = Iter<'a, T>; - - fn into_iter(self) -> Iter<'a, T> { - self.iter() - } -} - -impl<'a, T: Stackable> iter::IntoIterator for &'a mut Stack { - type Item = &'a mut T::Ref; - type IntoIter = IterMut<'a, T>; - - fn into_iter(self) -> IterMut<'a, T> { - self.iter_mut() - } -} - -/// An iterator over the stack's contents. -pub struct Iter<'a, T: Stackable> -where - T: 'a, -{ - stack: &'a StackRef, - pos: usize, -} - -impl<'a, T: Stackable> iter::Iterator for Iter<'a, T> { - type Item = &'a T::Ref; - - fn next(&mut self) -> Option<&'a T::Ref> { - let n = self.stack.get(self.pos); - - if n.is_some() { - self.pos += 1; - } - - n - } - - fn size_hint(&self) -> (usize, Option) { - let rem = self.stack.len() - self.pos; - - (rem, Some(rem)) - } -} - -impl<'a, T: Stackable> iter::ExactSizeIterator for Iter<'a, T> {} - -/// A mutable iterator over the stack's contents. -pub struct IterMut<'a, T: Stackable + 'a> { - stack: &'a mut StackRef, - pos: usize, -} - -impl<'a, T: Stackable> iter::Iterator for IterMut<'a, T> { - type Item = &'a mut T::Ref; - - fn next(&mut self) -> Option<&'a mut T::Ref> { - if self.pos >= self.stack.len() { - None - } else { - // Rust won't allow us to get a mutable reference into - // `stack` in this situation since it can't statically - // guarantee that we won't return several references to - // the same object, so we have to use unsafe code for - // mutable iterators. - let n = unsafe { Some(T::Ref::from_ptr_mut(self.stack._get(self.pos))) }; - - self.pos += 1; - - n - } - } - - fn size_hint(&self) -> (usize, Option) { - let rem = self.stack.len() - self.pos; - - (rem, Some(rem)) - } -} - -impl<'a, T: Stackable> iter::ExactSizeIterator for IterMut<'a, T> {} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/string.rs cargo-0.26.0/vendor/openssl-0.9.24/src/string.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/string.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/string.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,82 +0,0 @@ -use ffi; -use foreign_types::{ForeignType, ForeignTypeRef}; -use libc::{c_char, c_void}; -use std::fmt; -use std::ffi::CStr; -use std::ops::Deref; -use std::str; - -use stack::Stackable; - -foreign_type_and_impl_send_sync! { - type CType = c_char; - fn drop = free; - - pub struct OpensslString; - pub struct OpensslStringRef; -} - -impl OpensslString { - #[deprecated(note = "use from_ptr", since = "0.9.7")] - pub unsafe fn from_raw_parts(buf: *mut u8, _: usize) -> OpensslString { - OpensslString::from_ptr(buf as *mut c_char) - } - - #[deprecated(note = "use from_ptr", since = "0.9.7")] - pub unsafe fn from_null_terminated(buf: *mut c_char) -> OpensslString { - OpensslString::from_ptr(buf) - } -} - -impl fmt::Display for OpensslString { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&**self, f) - } -} - -impl fmt::Debug for OpensslString { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(&**self, f) - } -} - -impl Stackable for OpensslString { - type StackType = ffi::stack_st_OPENSSL_STRING; -} - -impl Deref for OpensslStringRef { - type Target = str; - - fn deref(&self) -> &str { - unsafe { - let slice = CStr::from_ptr(self.as_ptr()).to_bytes(); - str::from_utf8_unchecked(slice) - } - } -} - -impl fmt::Display for OpensslStringRef { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&**self, f) - } -} - -impl fmt::Debug for OpensslStringRef { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Debug::fmt(&**self, f) - } -} - -#[cfg(not(ossl110))] -unsafe fn free(buf: *mut c_char) { - ::ffi::CRYPTO_free(buf as *mut c_void); -} - -#[cfg(ossl110)] -unsafe fn free(buf: *mut c_char) { - ::ffi::CRYPTO_free( - buf as *mut c_void, - concat!(file!(), "\0").as_ptr() as *const c_char, - line!() as ::libc::c_int, - ); -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/symm.rs cargo-0.26.0/vendor/openssl-0.9.24/src/symm.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/symm.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/symm.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1127 +0,0 @@ -//! High level interface to certain symmetric ciphers. -//! -//! # Examples -//! -//! Encrypt data in AES128 CBC mode -//! -//! ``` -//! use openssl::symm::{encrypt, Cipher}; -//! -//! let cipher = Cipher::aes_128_cbc(); -//! let data = b"Some Crypto Text"; -//! let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"; -//! let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07"; -//! let ciphertext = encrypt( -//! cipher, -//! key, -//! Some(iv), -//! data).unwrap(); -//! -//! assert_eq!( -//! b"\xB4\xB9\xE7\x30\xD6\xD6\xF7\xDE\x77\x3F\x1C\xFF\xB3\x3E\x44\x5A\x91\xD7\x27\x62\x87\x4D\ -//! \xFB\x3C\x5E\xC4\x59\x72\x4A\xF4\x7C\xA1", -//! &ciphertext[..]); -//! ``` -use std::cmp; -use std::ptr; -use libc::c_int; -use ffi; - -use {cvt, cvt_p}; -use error::ErrorStack; - -#[derive(Copy, Clone)] -pub enum Mode { - Encrypt, - Decrypt, -} - -/// Represents a particular cipher algorithm. -/// -/// See OpenSSL doc at [`EVP_EncryptInit`] for more information on each algorithms. -/// -/// [`EVP_EncryptInit`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_EncryptInit.html -#[derive(Copy, Clone)] -pub struct Cipher(*const ffi::EVP_CIPHER); - -impl Cipher { - pub fn aes_128_ecb() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_128_ecb()) } - } - - pub fn aes_128_cbc() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_128_cbc()) } - } - - pub fn aes_128_xts() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_128_xts()) } - } - - pub fn aes_128_ctr() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_128_ctr()) } - } - - pub fn aes_128_cfb1() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_128_cfb1()) } - } - - pub fn aes_128_cfb128() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_128_cfb128()) } - } - - pub fn aes_128_cfb8() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_128_cfb8()) } - } - - pub fn aes_128_gcm() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_128_gcm()) } - } - - pub fn aes_256_ecb() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_256_ecb()) } - } - - pub fn aes_256_cbc() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_256_cbc()) } - } - - pub fn aes_256_xts() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_256_xts()) } - } - - pub fn aes_256_ctr() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_256_ctr()) } - } - - pub fn aes_256_cfb1() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_256_cfb1()) } - } - - pub fn aes_256_cfb128() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_256_cfb128()) } - } - - pub fn aes_256_cfb8() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_256_cfb8()) } - } - - pub fn aes_256_gcm() -> Cipher { - unsafe { Cipher(ffi::EVP_aes_256_gcm()) } - } - - pub fn bf_cbc() -> Cipher { - unsafe { Cipher(ffi::EVP_bf_cbc()) } - } - - pub fn bf_ecb() -> Cipher { - unsafe { Cipher(ffi::EVP_bf_ecb()) } - } - - pub fn bf_cfb64() -> Cipher { - unsafe { Cipher(ffi::EVP_bf_cfb64()) } - } - - pub fn bf_ofb() -> Cipher { - unsafe { Cipher(ffi::EVP_bf_ofb()) } - } - - pub fn des_cbc() -> Cipher { - unsafe { Cipher(ffi::EVP_des_cbc()) } - } - - pub fn des_ecb() -> Cipher { - unsafe { Cipher(ffi::EVP_des_ecb()) } - } - - pub fn rc4() -> Cipher { - unsafe { Cipher(ffi::EVP_rc4()) } - } - - /// Requires the `v110` feature and OpenSSL 1.1.0. - #[cfg(all(ossl110, feature = "v110"))] - pub fn chacha20() -> Cipher { - unsafe { Cipher(ffi::EVP_chacha20()) } - } - - /// Requires the `v110` feature and OpenSSL 1.1.0. - #[cfg(all(ossl110, feature = "v110"))] - pub fn chacha20_poly1305() -> Cipher { - unsafe { Cipher(ffi::EVP_chacha20_poly1305()) } - } - - pub unsafe fn from_ptr(ptr: *const ffi::EVP_CIPHER) -> Cipher { - Cipher(ptr) - } - - pub fn as_ptr(&self) -> *const ffi::EVP_CIPHER { - self.0 - } - - /// Returns the length of keys used with this cipher. - pub fn key_len(&self) -> usize { - unsafe { EVP_CIPHER_key_length(self.0) as usize } - } - - /// Returns the length of the IV used with this cipher, or `None` if the - /// cipher does not use an IV. - pub fn iv_len(&self) -> Option { - unsafe { - let len = EVP_CIPHER_iv_length(self.0) as usize; - if len == 0 { None } else { Some(len) } - } - } - - /// Returns the block size of the cipher. - /// - /// # Note - /// - /// Stream ciphers such as RC4 have a block size of 1. - pub fn block_size(&self) -> usize { - unsafe { EVP_CIPHER_block_size(self.0) as usize } - } -} - -/// Represents a symmetric cipher context. -/// -/// Padding is enabled by default. -/// -/// # Examples -/// -/// Encrypt some plaintext in chunks, then decrypt the ciphertext back into plaintext, in AES 128 -/// CBC mode. -/// -/// ``` -/// use openssl::symm::{Cipher, Mode, Crypter}; -/// -/// let plaintexts: [&[u8]; 2] = [b"Some Stream of", b" Crypto Text"]; -/// let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"; -/// let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07"; -/// let data_len = plaintexts.iter().fold(0, |sum, x| sum + x.len()); -/// -/// // Create a cipher context for encryption. -/// let mut encrypter = Crypter::new( -/// Cipher::aes_128_cbc(), -/// Mode::Encrypt, -/// key, -/// Some(iv)).unwrap(); -/// -/// let block_size = Cipher::aes_128_cbc().block_size(); -/// let mut ciphertext = vec![0; data_len + block_size]; -/// -/// // Encrypt 2 chunks of plaintexts successively. -/// let mut count = encrypter.update(plaintexts[0], &mut ciphertext).unwrap(); -/// count += encrypter.update(plaintexts[1], &mut ciphertext[count..]).unwrap(); -/// count += encrypter.finalize(&mut ciphertext[count..]).unwrap(); -/// ciphertext.truncate(count); -/// -/// assert_eq!( -/// b"\x0F\x21\x83\x7E\xB2\x88\x04\xAF\xD9\xCC\xE2\x03\x49\xB4\x88\xF6\xC4\x61\x0E\x32\x1C\xF9\ -/// \x0D\x66\xB1\xE6\x2C\x77\x76\x18\x8D\x99", -/// &ciphertext[..] -/// ); -/// -/// -/// // Let's pretend we don't know the plaintext, and now decrypt the ciphertext. -/// let data_len = ciphertext.len(); -/// let ciphertexts = [&ciphertext[..9], &ciphertext[9..]]; -/// -/// // Create a cipher context for decryption. -/// let mut decrypter = Crypter::new( -/// Cipher::aes_128_cbc(), -/// Mode::Decrypt, -/// key, -/// Some(iv)).unwrap(); -/// let mut plaintext = vec![0; data_len + block_size]; -/// -/// // Decrypt 2 chunks of ciphertexts successively. -/// let mut count = decrypter.update(ciphertexts[0], &mut plaintext).unwrap(); -/// count += decrypter.update(ciphertexts[1], &mut plaintext[count..]).unwrap(); -/// count += decrypter.finalize(&mut plaintext[count..]).unwrap(); -/// plaintext.truncate(count); -/// -/// assert_eq!(b"Some Stream of Crypto Text", &plaintext[..]); -/// ``` -pub struct Crypter { - ctx: *mut ffi::EVP_CIPHER_CTX, - block_size: usize, -} - -impl Crypter { - /// Creates a new `Crypter`. The initialisation vector, `iv`, is not necesarry for certain - /// types of `Cipher`. - /// - /// # Panics - /// - /// Panics if an IV is required by the cipher but not provided. Also make sure that the key - /// and IV size are appropriate for your cipher. - pub fn new( - t: Cipher, - mode: Mode, - key: &[u8], - iv: Option<&[u8]>, - ) -> Result { - ffi::init(); - - unsafe { - let ctx = cvt_p(ffi::EVP_CIPHER_CTX_new())?; - let crypter = Crypter { - ctx: ctx, - block_size: t.block_size(), - }; - - let mode = match mode { - Mode::Encrypt => 1, - Mode::Decrypt => 0, - }; - - cvt(ffi::EVP_CipherInit_ex( - crypter.ctx, - t.as_ptr(), - ptr::null_mut(), - ptr::null_mut(), - ptr::null_mut(), - mode, - ))?; - - assert!(key.len() <= c_int::max_value() as usize); - cvt(ffi::EVP_CIPHER_CTX_set_key_length( - crypter.ctx, - key.len() as c_int, - ))?; - - let key = key.as_ptr() as *mut _; - let iv = match (iv, t.iv_len()) { - (Some(iv), Some(len)) => { - if iv.len() != len { - assert!(iv.len() <= c_int::max_value() as usize); - cvt(ffi::EVP_CIPHER_CTX_ctrl( - crypter.ctx, - ffi::EVP_CTRL_GCM_SET_IVLEN, - iv.len() as c_int, - ptr::null_mut(), - ))?; - } - iv.as_ptr() as *mut _ - } - (Some(_), None) | (None, None) => ptr::null_mut(), - (None, Some(_)) => panic!("an IV is required for this cipher"), - }; - cvt(ffi::EVP_CipherInit_ex( - crypter.ctx, - ptr::null(), - ptr::null_mut(), - key, - iv, - mode, - ))?; - - Ok(crypter) - } - } - - /// Enables or disables padding. - /// - /// If padding is disabled, total amount of data encrypted/decrypted must - /// be a multiple of the cipher's block size. - pub fn pad(&mut self, padding: bool) { - unsafe { - ffi::EVP_CIPHER_CTX_set_padding(self.ctx, padding as c_int); - } - } - - /// Sets the tag used to authenticate ciphertext in AEAD ciphers such as AES GCM. - /// - /// When decrypting cipher text using an AEAD cipher, this must be called before `finalize`. - pub fn set_tag(&mut self, tag: &[u8]) -> Result<(), ErrorStack> { - unsafe { - assert!(tag.len() <= c_int::max_value() as usize); - // NB: this constant is actually more general than just GCM. - cvt(ffi::EVP_CIPHER_CTX_ctrl( - self.ctx, - ffi::EVP_CTRL_GCM_SET_TAG, - tag.len() as c_int, - tag.as_ptr() as *mut _, - )).map(|_| ()) - } - } - - /// Feeds Additional Authenticated Data (AAD) through the cipher. - /// - /// This can only be used with AEAD ciphers such as AES GCM. Data fed in is not encrypted, but - /// is factored into the authentication tag. It must be called before the first call to - /// `update`. - pub fn aad_update(&mut self, input: &[u8]) -> Result<(), ErrorStack> { - unsafe { - assert!(input.len() <= c_int::max_value() as usize); - let mut len = 0; - cvt(ffi::EVP_CipherUpdate( - self.ctx, - ptr::null_mut(), - &mut len, - input.as_ptr(), - input.len() as c_int, - )).map(|_| ()) - } - } - - /// Feeds data from `input` through the cipher, writing encrypted/decrypted - /// bytes into `output`. - /// - /// The number of bytes written to `output` is returned. Note that this may - /// not be equal to the length of `input`. - /// - /// # Panics - /// - /// Panics if `output.len() < input.len() + block_size` where - /// `block_size` is the block size of the cipher (see `Cipher::block_size`), - /// or if `output.len() > c_int::max_value()`. - pub fn update(&mut self, input: &[u8], output: &mut [u8]) -> Result { - unsafe { - assert!(output.len() >= input.len() + self.block_size); - assert!(output.len() <= c_int::max_value() as usize); - let mut outl = output.len() as c_int; - let inl = input.len() as c_int; - - cvt(ffi::EVP_CipherUpdate( - self.ctx, - output.as_mut_ptr(), - &mut outl, - input.as_ptr(), - inl, - ))?; - - Ok(outl as usize) - } - } - - /// Finishes the encryption/decryption process, writing any remaining data - /// to `output`. - /// - /// The number of bytes written to `output` is returned. - /// - /// `update` should not be called after this method. - /// - /// # Panics - /// - /// Panics if `output` is less than the cipher's block size. - pub fn finalize(&mut self, output: &mut [u8]) -> Result { - unsafe { - assert!(output.len() >= self.block_size); - let mut outl = cmp::min(output.len(), c_int::max_value() as usize) as c_int; - - cvt(ffi::EVP_CipherFinal( - self.ctx, - output.as_mut_ptr(), - &mut outl, - ))?; - - Ok(outl as usize) - } - } - - /// Retrieves the authentication tag used to authenticate ciphertext in AEAD ciphers such - /// as AES GCM. - /// - /// When encrypting data with an AEAD cipher, this must be called after `finalize`. - /// - /// The size of the buffer indicates the required size of the tag. While some ciphers support a - /// range of tag sizes, it is recommended to pick the maximum size. For AES GCM, this is 16 - /// bytes, for example. - pub fn get_tag(&self, tag: &mut [u8]) -> Result<(), ErrorStack> { - unsafe { - assert!(tag.len() <= c_int::max_value() as usize); - cvt(ffi::EVP_CIPHER_CTX_ctrl( - self.ctx, - ffi::EVP_CTRL_GCM_GET_TAG, - tag.len() as c_int, - tag.as_mut_ptr() as *mut _, - )).map(|_| ()) - } - } -} - -impl Drop for Crypter { - fn drop(&mut self) { - unsafe { - ffi::EVP_CIPHER_CTX_free(self.ctx); - } - } -} - -/// Encrypts data in one go, and returns the encrypted data. -/// -/// Data is encrypted using the specified cipher type `t` in encrypt mode with the specified `key` -/// and initailization vector `iv`. -/// -/// This is a convenient interface to `Crypter` to encrypt all data in one go. To encrypt a stream -/// of data increamentally , use `Crypter` instead. -/// -/// # Examples -/// -/// Encrypt data in AES128 CBC mode -/// -/// ``` -/// use openssl::symm::{encrypt, Cipher}; -/// -/// let cipher = Cipher::aes_128_cbc(); -/// let data = b"Some Crypto Text"; -/// let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"; -/// let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07"; -/// let ciphertext = encrypt( -/// cipher, -/// key, -/// Some(iv), -/// data).unwrap(); -/// -/// assert_eq!( -/// b"\xB4\xB9\xE7\x30\xD6\xD6\xF7\xDE\x77\x3F\x1C\xFF\xB3\x3E\x44\x5A\x91\xD7\x27\x62\x87\x4D\ -/// \xFB\x3C\x5E\xC4\x59\x72\x4A\xF4\x7C\xA1", -/// &ciphertext[..]); -/// ``` -pub fn encrypt( - t: Cipher, - key: &[u8], - iv: Option<&[u8]>, - data: &[u8], -) -> Result, ErrorStack> { - cipher(t, Mode::Encrypt, key, iv, data) -} - -/// Decrypts data in one go, and returns the decrypted data. -/// -/// Data is decrypted using the specified cipher type `t` in decrypt mode with the specified `key` -/// and initailization vector `iv`. -/// -/// This is a convenient interface to `Crypter` to decrypt all data in one go. To decrypt a stream -/// of data increamentally , use `Crypter` instead. -/// -/// # Examples -/// -/// Decrypt data in AES256 ECB mode -/// -/// ``` -/// use openssl::symm::{decrypt, Cipher}; -/// -/// let cipher = Cipher::aes_128_cbc(); -/// let data = b"\xB4\xB9\xE7\x30\xD6\xD6\xF7\xDE\x77\x3F\x1C\xFF\xB3\x3E\x44\x5A\x91\xD7\x27\x62\ -/// \x87\x4D\xFB\x3C\x5E\xC4\x59\x72\x4A\xF4\x7C\xA1"; -/// let key = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F"; -/// let iv = b"\x00\x01\x02\x03\x04\x05\x06\x07\x00\x01\x02\x03\x04\x05\x06\x07"; -/// let ciphertext = decrypt( -/// cipher, -/// key, -/// Some(iv), -/// data).unwrap(); -/// -/// assert_eq!( -/// b"Some Crypto Text", -/// &ciphertext[..]); -/// ``` -pub fn decrypt( - t: Cipher, - key: &[u8], - iv: Option<&[u8]>, - data: &[u8], -) -> Result, ErrorStack> { - cipher(t, Mode::Decrypt, key, iv, data) -} - -fn cipher( - t: Cipher, - mode: Mode, - key: &[u8], - iv: Option<&[u8]>, - data: &[u8], -) -> Result, ErrorStack> { - let mut c = Crypter::new(t, mode, key, iv)?; - let mut out = vec![0; data.len() + t.block_size()]; - let count = c.update(data, &mut out)?; - let rest = c.finalize(&mut out[count..])?; - out.truncate(count + rest); - Ok(out) -} - -/// Like `encrypt`, but for AEAD ciphers such as AES GCM. -/// -/// Additional Authenticated Data can be provided in the `aad` field, and the authentication tag -/// will be copied into the `tag` field. -/// -/// The size of the `tag` buffer indicates the required size of the tag. While some ciphers support -/// a range of tag sizes, it is recommended to pick the maximum size. For AES GCM, this is 16 bytes, -/// for example. -pub fn encrypt_aead( - t: Cipher, - key: &[u8], - iv: Option<&[u8]>, - aad: &[u8], - data: &[u8], - tag: &mut [u8], -) -> Result, ErrorStack> { - let mut c = Crypter::new(t, Mode::Encrypt, key, iv)?; - let mut out = vec![0; data.len() + t.block_size()]; - c.aad_update(aad)?; - let count = c.update(data, &mut out)?; - let rest = c.finalize(&mut out[count..])?; - c.get_tag(tag)?; - out.truncate(count + rest); - Ok(out) -} - -/// Like `decrypt`, but for AEAD ciphers such as AES GCM. -/// -/// Additional Authenticated Data can be provided in the `aad` field, and the authentication tag -/// should be provided in the `tag` field. -pub fn decrypt_aead( - t: Cipher, - key: &[u8], - iv: Option<&[u8]>, - aad: &[u8], - data: &[u8], - tag: &[u8], -) -> Result, ErrorStack> { - let mut c = Crypter::new(t, Mode::Decrypt, key, iv)?; - let mut out = vec![0; data.len() + t.block_size()]; - c.aad_update(aad)?; - let count = c.update(data, &mut out)?; - c.set_tag(tag)?; - let rest = c.finalize(&mut out[count..])?; - out.truncate(count + rest); - Ok(out) -} - -#[cfg(ossl110)] -use ffi::{EVP_CIPHER_iv_length, EVP_CIPHER_block_size, EVP_CIPHER_key_length}; - -#[cfg(ossl10x)] -#[allow(bad_style)] -mod compat { - use libc::c_int; - use ffi::EVP_CIPHER; - - pub unsafe fn EVP_CIPHER_iv_length(ptr: *const EVP_CIPHER) -> c_int { - (*ptr).iv_len - } - - pub unsafe fn EVP_CIPHER_block_size(ptr: *const EVP_CIPHER) -> c_int { - (*ptr).block_size - } - - pub unsafe fn EVP_CIPHER_key_length(ptr: *const EVP_CIPHER) -> c_int { - (*ptr).key_len - } -} -#[cfg(ossl10x)] -use self::compat::*; - -#[cfg(test)] -mod tests { - use hex::{FromHex, ToHex}; - use super::*; - - // Test vectors from FIPS-197: - // http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf - #[test] - fn test_aes_256_ecb() { - let k0 = [ - 0x00u8, - 0x01u8, - 0x02u8, - 0x03u8, - 0x04u8, - 0x05u8, - 0x06u8, - 0x07u8, - 0x08u8, - 0x09u8, - 0x0au8, - 0x0bu8, - 0x0cu8, - 0x0du8, - 0x0eu8, - 0x0fu8, - 0x10u8, - 0x11u8, - 0x12u8, - 0x13u8, - 0x14u8, - 0x15u8, - 0x16u8, - 0x17u8, - 0x18u8, - 0x19u8, - 0x1au8, - 0x1bu8, - 0x1cu8, - 0x1du8, - 0x1eu8, - 0x1fu8, - ]; - let p0 = [ - 0x00u8, - 0x11u8, - 0x22u8, - 0x33u8, - 0x44u8, - 0x55u8, - 0x66u8, - 0x77u8, - 0x88u8, - 0x99u8, - 0xaau8, - 0xbbu8, - 0xccu8, - 0xddu8, - 0xeeu8, - 0xffu8, - ]; - let c0 = [ - 0x8eu8, - 0xa2u8, - 0xb7u8, - 0xcau8, - 0x51u8, - 0x67u8, - 0x45u8, - 0xbfu8, - 0xeau8, - 0xfcu8, - 0x49u8, - 0x90u8, - 0x4bu8, - 0x49u8, - 0x60u8, - 0x89u8, - ]; - let mut c = super::Crypter::new( - super::Cipher::aes_256_ecb(), - super::Mode::Encrypt, - &k0, - None, - ).unwrap(); - c.pad(false); - let mut r0 = vec![0; c0.len() + super::Cipher::aes_256_ecb().block_size()]; - let count = c.update(&p0, &mut r0).unwrap(); - let rest = c.finalize(&mut r0[count..]).unwrap(); - r0.truncate(count + rest); - assert_eq!(r0.to_hex(), c0.to_hex()); - - let mut c = super::Crypter::new( - super::Cipher::aes_256_ecb(), - super::Mode::Decrypt, - &k0, - None, - ).unwrap(); - c.pad(false); - let mut p1 = vec![0; r0.len() + super::Cipher::aes_256_ecb().block_size()]; - let count = c.update(&r0, &mut p1).unwrap(); - let rest = c.finalize(&mut p1[count..]).unwrap(); - p1.truncate(count + rest); - assert_eq!(p1.to_hex(), p0.to_hex()); - } - - #[test] - fn test_aes_256_cbc_decrypt() { - let iv = [ - 4_u8, - 223_u8, - 153_u8, - 219_u8, - 28_u8, - 142_u8, - 234_u8, - 68_u8, - 227_u8, - 69_u8, - 98_u8, - 107_u8, - 208_u8, - 14_u8, - 236_u8, - 60_u8, - ]; - let data = [ - 143_u8, - 210_u8, - 75_u8, - 63_u8, - 214_u8, - 179_u8, - 155_u8, - 241_u8, - 242_u8, - 31_u8, - 154_u8, - 56_u8, - 198_u8, - 145_u8, - 192_u8, - 64_u8, - 2_u8, - 245_u8, - 167_u8, - 220_u8, - 55_u8, - 119_u8, - 233_u8, - 136_u8, - 139_u8, - 27_u8, - 71_u8, - 242_u8, - 119_u8, - 175_u8, - 65_u8, - 207_u8, - ]; - let ciphered_data = [ - 0x4a_u8, - 0x2e_u8, - 0xe5_u8, - 0x6_u8, - 0xbf_u8, - 0xcf_u8, - 0xf2_u8, - 0xd7_u8, - 0xea_u8, - 0x2d_u8, - 0xb1_u8, - 0x85_u8, - 0x6c_u8, - 0x93_u8, - 0x65_u8, - 0x6f_u8, - ]; - let mut cr = super::Crypter::new( - super::Cipher::aes_256_cbc(), - super::Mode::Decrypt, - &data, - Some(&iv), - ).unwrap(); - cr.pad(false); - let mut unciphered_data = vec![0; data.len() + super::Cipher::aes_256_cbc().block_size()]; - let count = cr.update(&ciphered_data, &mut unciphered_data).unwrap(); - let rest = cr.finalize(&mut unciphered_data[count..]).unwrap(); - unciphered_data.truncate(count + rest); - - let expected_unciphered_data = b"I love turtles.\x01"; - - assert_eq!(&unciphered_data, expected_unciphered_data); - } - - fn cipher_test(ciphertype: super::Cipher, pt: &str, ct: &str, key: &str, iv: &str) { - let pt = Vec::from_hex(pt).unwrap(); - let ct = Vec::from_hex(ct).unwrap(); - let key = Vec::from_hex(key).unwrap(); - let iv = Vec::from_hex(iv).unwrap(); - - let computed = super::decrypt(ciphertype, &key, Some(&iv), &ct).unwrap(); - let expected = pt; - - if computed != expected { - println!("Computed: {}", computed.to_hex()); - println!("Expected: {}", expected.to_hex()); - if computed.len() != expected.len() { - println!( - "Lengths differ: {} in computed vs {} expected", - computed.len(), - expected.len() - ); - } - panic!("test failure"); - } - } - - fn cipher_test_nopad(ciphertype: super::Cipher, pt: &str, ct: &str, key: &str, iv: &str) { - let pt = Vec::from_hex(pt).unwrap(); - let ct = Vec::from_hex(ct).unwrap(); - let key = Vec::from_hex(key).unwrap(); - let iv = Vec::from_hex(iv).unwrap(); - - let computed = { - let mut c = Crypter::new(ciphertype, Mode::Decrypt, &key, Some(&iv)).unwrap(); - c.pad(false); - let mut out = vec![0; ct.len() + ciphertype.block_size()]; - let count = c.update(&ct, &mut out).unwrap(); - let rest = c.finalize(&mut out[count..]).unwrap(); - out.truncate(count + rest); - out - }; - let expected = pt; - - if computed != expected { - println!("Computed: {}", computed.to_hex()); - println!("Expected: {}", expected.to_hex()); - if computed.len() != expected.len() { - println!( - "Lengths differ: {} in computed vs {} expected", - computed.len(), - expected.len() - ); - } - panic!("test failure"); - } - } - - #[test] - fn test_rc4() { - - let pt = "0000000000000000000000000000000000000000000000000000000000000000000000000000"; - let ct = "A68686B04D686AA107BD8D4CAB191A3EEC0A6294BC78B60F65C25CB47BD7BB3A48EFC4D26BE4"; - let key = "97CD440324DA5FD1F7955C1C13B6B466"; - let iv = ""; - - cipher_test(super::Cipher::rc4(), pt, ct, key, iv); - } - - #[test] - fn test_aes256_xts() { - // Test case 174 from - // http://csrc.nist.gov/groups/STM/cavp/documents/aes/XTSTestVectors.zip - let pt = "77f4ef63d734ebd028508da66c22cdebdd52ecd6ee2ab0a50bc8ad0cfd692ca5fcd4e6dedc45df7f\ - 6503f462611dc542"; - let ct = "ce7d905a7776ac72f240d22aafed5e4eb7566cdc7211220e970da634ce015f131a5ecb8d400bc9e8\ - 4f0b81d8725dbbc7"; - let key = "b6bfef891f83b5ff073f2231267be51eb084b791fa19a154399c0684c8b2dfcb37de77d28bbda3b\ - 4180026ad640b74243b3133e7b9fae629403f6733423dae28"; - let iv = "db200efb7eaaa737dbdf40babb68953f"; - - cipher_test(super::Cipher::aes_256_xts(), pt, ct, key, iv); - } - - #[test] - fn test_aes128_ctr() { - - let pt = "6BC1BEE22E409F96E93D7E117393172AAE2D8A571E03AC9C9EB76FAC45AF8E5130C81C46A35CE411\ - E5FBC1191A0A52EFF69F2445DF4F9B17AD2B417BE66C3710"; - let ct = "874D6191B620E3261BEF6864990DB6CE9806F66B7970FDFF8617187BB9FFFDFF5AE4DF3EDBD5D35E\ - 5B4F09020DB03EAB1E031DDA2FBE03D1792170A0F3009CEE"; - let key = "2B7E151628AED2A6ABF7158809CF4F3C"; - let iv = "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"; - - cipher_test(super::Cipher::aes_128_ctr(), pt, ct, key, iv); - } - - #[test] - fn test_aes128_cfb1() { - // Lifted from http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf - - let pt = "6bc1"; - let ct = "68b3"; - let key = "2b7e151628aed2a6abf7158809cf4f3c"; - let iv = "000102030405060708090a0b0c0d0e0f"; - - cipher_test(super::Cipher::aes_128_cfb1(), pt, ct, key, iv); - } - - #[test] - fn test_aes128_cfb128() { - - let pt = "6bc1bee22e409f96e93d7e117393172a"; - let ct = "3b3fd92eb72dad20333449f8e83cfb4a"; - let key = "2b7e151628aed2a6abf7158809cf4f3c"; - let iv = "000102030405060708090a0b0c0d0e0f"; - - cipher_test(super::Cipher::aes_128_cfb128(), pt, ct, key, iv); - } - - #[test] - fn test_aes128_cfb8() { - - let pt = "6bc1bee22e409f96e93d7e117393172aae2d"; - let ct = "3b79424c9c0dd436bace9e0ed4586a4f32b9"; - let key = "2b7e151628aed2a6abf7158809cf4f3c"; - let iv = "000102030405060708090a0b0c0d0e0f"; - - cipher_test(super::Cipher::aes_128_cfb8(), pt, ct, key, iv); - } - - #[test] - fn test_aes256_cfb1() { - - let pt = "6bc1"; - let ct = "9029"; - let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; - let iv = "000102030405060708090a0b0c0d0e0f"; - - cipher_test(super::Cipher::aes_256_cfb1(), pt, ct, key, iv); - } - - #[test] - fn test_aes256_cfb128() { - - let pt = "6bc1bee22e409f96e93d7e117393172a"; - let ct = "dc7e84bfda79164b7ecd8486985d3860"; - let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; - let iv = "000102030405060708090a0b0c0d0e0f"; - - cipher_test(super::Cipher::aes_256_cfb128(), pt, ct, key, iv); - } - - #[test] - fn test_aes256_cfb8() { - - let pt = "6bc1bee22e409f96e93d7e117393172aae2d"; - let ct = "dc1f1a8520a64db55fcc8ac554844e889700"; - let key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4"; - let iv = "000102030405060708090a0b0c0d0e0f"; - - cipher_test(super::Cipher::aes_256_cfb8(), pt, ct, key, iv); - } - - #[test] - fn test_bf_cbc() { - // https://www.schneier.com/code/vectors.txt - - let pt = "37363534333231204E6F77206973207468652074696D6520666F722000000000"; - let ct = "6B77B4D63006DEE605B156E27403979358DEB9E7154616D959F1652BD5FF92CC"; - let key = "0123456789ABCDEFF0E1D2C3B4A59687"; - let iv = "FEDCBA9876543210"; - - cipher_test_nopad(super::Cipher::bf_cbc(), pt, ct, key, iv); - } - - #[test] - fn test_bf_ecb() { - - let pt = "5CD54CA83DEF57DA"; - let ct = "B1B8CC0B250F09A0"; - let key = "0131D9619DC1376E"; - let iv = "0000000000000000"; - - cipher_test_nopad(super::Cipher::bf_ecb(), pt, ct, key, iv); - } - - #[test] - fn test_bf_cfb64() { - - let pt = "37363534333231204E6F77206973207468652074696D6520666F722000"; - let ct = "E73214A2822139CAF26ECF6D2EB9E76E3DA3DE04D1517200519D57A6C3"; - let key = "0123456789ABCDEFF0E1D2C3B4A59687"; - let iv = "FEDCBA9876543210"; - - cipher_test_nopad(super::Cipher::bf_cfb64(), pt, ct, key, iv); - } - - #[test] - fn test_bf_ofb() { - - let pt = "37363534333231204E6F77206973207468652074696D6520666F722000"; - let ct = "E73214A2822139CA62B343CC5B65587310DD908D0C241B2263C2CF80DA"; - let key = "0123456789ABCDEFF0E1D2C3B4A59687"; - let iv = "FEDCBA9876543210"; - - cipher_test_nopad(super::Cipher::bf_ofb(), pt, ct, key, iv); - } - - #[test] - fn test_des_cbc() { - - let pt = "54686973206973206120746573742e"; - let ct = "6f2867cfefda048a4046ef7e556c7132"; - let key = "7cb66337f3d3c0fe"; - let iv = "0001020304050607"; - - cipher_test(super::Cipher::des_cbc(), pt, ct, key, iv); - } - - #[test] - fn test_des_ecb() { - - let pt = "54686973206973206120746573742e"; - let ct = "0050ab8aecec758843fe157b4dde938c"; - let key = "7cb66337f3d3c0fe"; - let iv = "0001020304050607"; - - cipher_test(super::Cipher::des_ecb(), pt, ct, key, iv); - } - - #[test] - fn test_aes128_gcm() { - let key = "0e00c76561d2bd9b40c3c15427e2b08f"; - let iv = "492cadaccd3ca3fbc9cf9f06eb3325c4e159850b0dbe98199b89b7af528806610b6f63998e1eae80c348e7\ - 4cbb921d8326631631fc6a5d304f39166daf7ea15fa1977f101819adb510b50fe9932e12c5a85aa3fd1e73\ - d8d760af218be829903a77c63359d75edd91b4f6ed5465a72662f5055999e059e7654a8edc921aa0d496"; - let pt = "fef03c2d7fb15bf0d2df18007d99f967c878ad59359034f7bb2c19af120685d78e32f6b8b83b032019956c\ - a9c0195721476b85"; - let aad = "d8f1163d8c840292a2b2dacf4ac7c36aff8733f18fabb4fa5594544125e03d1e6e5d6d0fd61656c8d8f327\ - c92839ae5539bb469c9257f109ebff85aad7bd220fdaa95c022dbd0c7bb2d878ad504122c943045d3c5eba\ - 8f1f56c0"; - let ct = "4f6cf471be7cbd2575cd5a1747aea8fe9dea83e51936beac3e68f66206922060c697ffa7af80ad6bb68f2c\ - f4fc97416ee52abe"; - let tag = "e20b6655"; - - // this tag is smaller than you'd normally want, but I pulled this test from the part of - // the NIST test vectors that cover 4 byte tags. - let mut actual_tag = [0; 4]; - let out = encrypt_aead( - Cipher::aes_128_gcm(), - &Vec::from_hex(key).unwrap(), - Some(&Vec::from_hex(iv).unwrap()), - &Vec::from_hex(aad).unwrap(), - &Vec::from_hex(pt).unwrap(), - &mut actual_tag, - ).unwrap(); - assert_eq!(ct, out.to_hex()); - assert_eq!(tag, actual_tag.to_hex()); - - let out = decrypt_aead( - Cipher::aes_128_gcm(), - &Vec::from_hex(key).unwrap(), - Some(&Vec::from_hex(iv).unwrap()), - &Vec::from_hex(aad).unwrap(), - &Vec::from_hex(ct).unwrap(), - &Vec::from_hex(tag).unwrap(), - ).unwrap(); - assert_eq!(pt, out.to_hex()); - } - - #[test] - #[cfg(all(ossl110, feature = "v110"))] - fn test_chacha20() { - let key = "0000000000000000000000000000000000000000000000000000000000000000"; - let iv = "00000000000000000000000000000000"; - let pt = "000000000000000000000000000000000000000000000000000000000000000000000000000000000\ - 00000000000000000000000000000000000000000000000"; - let ct = "76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7\ - 724e03fb8d84a376a43b8f41518a11cc387b669b2ee6586"; - - cipher_test(Cipher::chacha20(), pt, ct, key, iv); - } - - #[test] - #[cfg(all(ossl110, feature = "v110"))] - fn test_chacha20_poly1305() { - let key = "808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f"; - let iv = "070000004041424344454647"; - let aad = "50515253c0c1c2c3c4c5c6c7"; - let pt = "4c616469657320616e642047656e746c656d656e206f662074686520636c617373206f66202739393\ - a204966204920636f756c64206f6666657220796f75206f6e6c79206f6e652074697020666f722074\ - 6865206675747572652c2073756e73637265656e20776f756c642062652069742e"; - let ct = "d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca967128\ - 2fafb69da92728b1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fa\ - b324e4fad675945585808b4831d7bc3ff4def08e4b7a9de576d26586cec64b6116"; - let tag = "1ae10b594f09e26a7e902ecbd0600691"; - - let mut actual_tag = [0; 16]; - let out = encrypt_aead( - Cipher::chacha20_poly1305(), - &Vec::from_hex(key).unwrap(), - Some(&Vec::from_hex(iv).unwrap()), - &Vec::from_hex(aad).unwrap(), - &Vec::from_hex(pt).unwrap(), - &mut actual_tag, - ).unwrap(); - assert_eq!(ct, out.to_hex()); - assert_eq!(tag, actual_tag.to_hex()); - - let out = decrypt_aead( - Cipher::chacha20_poly1305(), - &Vec::from_hex(key).unwrap(), - Some(&Vec::from_hex(iv).unwrap()), - &Vec::from_hex(aad).unwrap(), - &Vec::from_hex(ct).unwrap(), - &Vec::from_hex(tag).unwrap(), - ).unwrap(); - assert_eq!(pt, out.to_hex()); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/types.rs cargo-0.26.0/vendor/openssl-0.9.24/src/types.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/types.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/types.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -#[deprecated(note = "use foreign_types instead", since = "0.9.7")] -pub use foreign_types::ForeignType as OpenSslType; - -#[deprecated(note = "use foreign_types instead", since = "0.9.7")] -pub use foreign_types::ForeignTypeRef as OpenSslTypeRef; diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/util.rs cargo-0.26.0/vendor/openssl-0.9.24/src/util.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/util.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/util.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,92 +0,0 @@ -use libc::{c_int, c_char, c_void}; -use std::any::Any; -use std::panic::{self, AssertUnwindSafe}; -use std::slice; - -use error::ErrorStack; - -/// Wraps a user-supplied callback and a slot for panics thrown inside the callback (while FFI -/// frames are on the stack). -/// -/// When dropped, checks if the callback has panicked, and resumes unwinding if so. -pub struct CallbackState { - /// The user callback. Taken out of the `Option` when called. - cb: Option, - /// If the callback panics, we place the panic object here, to be re-thrown once OpenSSL - /// returns. - panic: Option>, -} - -impl CallbackState { - pub fn new(callback: F) -> Self { - CallbackState { - cb: Some(callback), - panic: None, - } - } -} - -impl Drop for CallbackState { - fn drop(&mut self) { - if let Some(panic) = self.panic.take() { - panic::resume_unwind(panic); - } - } -} - -pub unsafe extern "C" fn invoke_passwd_cb_old( - buf: *mut c_char, - size: c_int, - _rwflag: c_int, - cb_state: *mut c_void, -) -> c_int -where - F: FnOnce(&mut [c_char]) -> usize, -{ - let callback = &mut *(cb_state as *mut CallbackState); - - let result = panic::catch_unwind(AssertUnwindSafe(|| { - let pass_slice = slice::from_raw_parts_mut(buf, size as usize); - callback.cb.take().unwrap()(pass_slice) - })); - - match result { - Ok(len) => len as c_int, - Err(err) => { - callback.panic = Some(err); - 0 - } - } -} - -/// Password callback function, passed to private key loading functions. -/// -/// `cb_state` is expected to be a pointer to a `CallbackState`. -pub unsafe extern "C" fn invoke_passwd_cb( - buf: *mut c_char, - size: c_int, - _rwflag: c_int, - cb_state: *mut c_void, -) -> c_int -where - F: FnOnce(&mut [u8]) -> Result, -{ - let callback = &mut *(cb_state as *mut CallbackState); - - let result = panic::catch_unwind(AssertUnwindSafe(|| { - let pass_slice = slice::from_raw_parts_mut(buf as *mut u8, size as usize); - callback.cb.take().unwrap()(pass_slice) - })); - - match result { - Ok(Ok(len)) => len as c_int, - Ok(Err(_)) => { - // FIXME restore error stack - 0 - } - Err(err) => { - callback.panic = Some(err); - 0 - } - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/verify.rs cargo-0.26.0/vendor/openssl-0.9.24/src/verify.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/verify.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/verify.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,68 +0,0 @@ -use libc::c_uint; -use ffi; -use foreign_types::ForeignTypeRef; -use std::net::IpAddr; - -use cvt; -use error::ErrorStack; - -bitflags! { - pub struct X509CheckFlags: c_uint { - const X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT = ffi::X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT; - const X509_CHECK_FLAG_NO_WILDCARDS = ffi::X509_CHECK_FLAG_NO_WILDCARDS; - const X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS = ffi::X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS; - const X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS = ffi::X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS; - const X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS - = ffi::X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS; - /// Requires the `v110` feature and OpenSSL 1.1.0. - #[cfg(all(feature = "v110", ossl110))] - const X509_CHECK_FLAG_NEVER_CHECK_SUBJECT = ffi::X509_CHECK_FLAG_NEVER_CHECK_SUBJECT; - } -} - -foreign_type_and_impl_send_sync! { - type CType = ffi::X509_VERIFY_PARAM; - fn drop = ffi::X509_VERIFY_PARAM_free; - - pub struct X509VerifyParam; - pub struct X509VerifyParamRef; -} - -impl X509VerifyParamRef { - pub fn set_hostflags(&mut self, hostflags: X509CheckFlags) { - unsafe { - ffi::X509_VERIFY_PARAM_set_hostflags(self.as_ptr(), hostflags.bits); - } - } - - pub fn set_host(&mut self, host: &str) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::X509_VERIFY_PARAM_set1_host( - self.as_ptr(), - host.as_ptr() as *const _, - host.len(), - )).map(|_| ()) - } - } - - pub fn set_ip(&mut self, ip: IpAddr) -> Result<(), ErrorStack> { - unsafe { - let mut buf = [0; 16]; - let len = match ip { - IpAddr::V4(addr) => { - buf[..4].copy_from_slice(&addr.octets()); - 4 - } - IpAddr::V6(addr) => { - buf.copy_from_slice(&addr.octets()); - 16 - } - }; - cvt(ffi::X509_VERIFY_PARAM_set1_ip( - self.as_ptr(), - buf.as_ptr() as *const _, - len, - )).map(|_| ()) - } - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/version.rs cargo-0.26.0/vendor/openssl-0.9.24/src/version.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/version.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/version.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,126 +0,0 @@ -// 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. -// - -use std::ffi::CStr; - -#[cfg(ossl10x)] -use ffi::{SSLEAY_VERSION as OPENSSL_VERSION, SSLEAY_CFLAGS as OPENSSL_CFLAGS, - SSLEAY_BUILT_ON as OPENSSL_BUILT_ON, SSLEAY_PLATFORM as OPENSSL_PLATFORM, - SSLEAY_DIR as OPENSSL_DIR, SSLeay as OpenSSL_version_num, - SSLeay_version as OpenSSL_version}; - -#[cfg(ossl110)] -use ffi::{OPENSSL_VERSION, OPENSSL_CFLAGS, OPENSSL_BUILT_ON, OPENSSL_PLATFORM, OPENSSL_DIR, - OpenSSL_version_num, OpenSSL_version}; - -/// OPENSSL_VERSION_NUMBER is a numeric release version identifier: -/// -/// `MNNFFPPS: major minor fix patch status` -/// -/// The status nibble has one of the values 0 for development, 1 to e for betas 1 to 14, and f for release. -/// -/// for example -/// -/// `0x000906000 == 0.9.6 dev` -/// `0x000906023 == 0.9.6b beta 3` -/// `0x00090605f == 0.9.6e release` -/// -/// Versions prior to 0.9.3 have identifiers < 0x0930. Versions between 0.9.3 and 0.9.5 had a version identifier with this interpretation: -/// -/// `MMNNFFRBB major minor fix final beta/patch` -/// -/// for example -/// -/// `0x000904100 == 0.9.4 release` -/// `0x000905000 == 0.9.5 dev` -/// -/// Version 0.9.5a had an interim interpretation that is like the current one, except the patch level got the highest bit set, to keep continuity. The number was therefore 0x0090581f -/// -/// The return value of this function can be compared to the macro to make sure that the correct version of the library has been loaded, especially when using DLLs on Windows systems. -pub fn number() -> i64 { - unsafe { OpenSSL_version_num() as i64 } -} - - -/// The text variant of the version number and the release date. For example, "OpenSSL 0.9.5a 1 Apr 2000". -pub fn version() -> &'static str { - unsafe { - CStr::from_ptr(OpenSSL_version(OPENSSL_VERSION)) - .to_str() - .unwrap() - } -} - -/// The compiler flags set for the compilation process in the form "compiler: ..." if available or -/// "compiler: information not available" otherwise. -pub fn c_flags() -> &'static str { - unsafe { - CStr::from_ptr(OpenSSL_version(OPENSSL_CFLAGS)) - .to_str() - .unwrap() - } -} - -/// The date of the build process in the form "built on: ..." if available or "built on: date not available" otherwise. -pub fn built_on() -> &'static str { - unsafe { - CStr::from_ptr(OpenSSL_version(OPENSSL_BUILT_ON)) - .to_str() - .unwrap() - } -} - -/// The "Configure" target of the library build in the form "platform: ..." if available or "platform: information not available" otherwise. -pub fn platform() -> &'static str { - unsafe { - CStr::from_ptr(OpenSSL_version(OPENSSL_PLATFORM)) - .to_str() - .unwrap() - } -} - -/// The "OPENSSLDIR" setting of the library build in the form "OPENSSLDIR: "..."" if available or "OPENSSLDIR: N/A" otherwise. -pub fn dir() -> &'static str { - unsafe { - CStr::from_ptr(OpenSSL_version(OPENSSL_DIR)) - .to_str() - .unwrap() - } -} - -/// This test ensures that we do not segfault when calling the functions of this module -/// and that the strings respect a reasonable format. -#[test] -fn test_versions() { - println!("Number: '{}'", number()); - println!("Version: '{}'", version()); - println!("C flags: '{}'", c_flags()); - println!("Built on: '{}'", built_on()); - println!("Platform: '{}'", platform()); - println!("Dir: '{}'", dir()); - - #[cfg(not(libressl))] - fn expected_name() -> &'static str { - "OpenSSL" - } - #[cfg(libressl)] - fn expected_name() -> &'static str { - "LibreSSL" - } - - assert!(number() > 0); - assert!(version().starts_with(expected_name())); - assert!(c_flags().starts_with("compiler:")); - assert!(built_on().starts_with("built on:")); - assert!(dir().starts_with("OPENSSLDIR:")); -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/x509/extension.rs cargo-0.26.0/vendor/openssl-0.9.24/src/x509/extension.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/x509/extension.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/x509/extension.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,672 +0,0 @@ -use std::fmt::{self, Write}; - -use error::ErrorStack; -use nid::{self, Nid}; -use x509::{X509v3Context, X509Extension}; - -/// Type-only version of the `Extension` enum. -/// -/// See the `Extension` documentation for more information on the different -/// variants. -#[derive(Clone, Hash, PartialEq, Eq)] -#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] -pub enum ExtensionType { - KeyUsage, - ExtKeyUsage, - SubjectAltName, - IssuerAltName, - OtherNid(Nid), - OtherStr(String), -} - -/// A X.509 v3 certificate extension. -/// -/// Only one extension of each type is allow in a certificate. -/// See RFC 3280 for more information about extensions. -#[derive(Clone)] -#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] -pub enum Extension { - /// The purposes of the key contained in the certificate - KeyUsage(Vec), - /// The extended purposes of the key contained in the certificate - ExtKeyUsage(Vec), - /// Subject Alternative Names - SubjectAltName(Vec<(AltNameOption, String)>), - /// Issuer Alternative Names - IssuerAltName(Vec<(AltNameOption, String)>), - /// Arbitrary extensions by NID. See `man x509v3_config` for value syntax. - /// - /// You must not use this to add extensions which this enum can express directly. - /// - /// ``` - /// use openssl::x509::extension::Extension::*; - /// use openssl::nid; - /// - /// # let generator = openssl::x509::X509Generator::new(); - /// generator.add_extension(OtherNid(nid::BASIC_CONSTRAINTS,"critical,CA:TRUE".to_owned())); - /// ``` - OtherNid(Nid, String), - /// Arbitrary extensions by OID string. See `man ASN1_generate_nconf` for value syntax. - /// - /// You must not use this to add extensions which this enum can express directly. - /// - /// ``` - /// use openssl::x509::extension::Extension::*; - /// - /// # let generator = openssl::x509::X509Generator::new(); - /// generator.add_extension(OtherStr("2.999.2".to_owned(),"ASN1:UTF8:example value".to_owned())); - /// ``` - OtherStr(String, String), -} - -impl Extension { - #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] - pub fn get_type(&self) -> ExtensionType { - match self { - &Extension::KeyUsage(_) => ExtensionType::KeyUsage, - &Extension::ExtKeyUsage(_) => ExtensionType::ExtKeyUsage, - &Extension::SubjectAltName(_) => ExtensionType::SubjectAltName, - &Extension::IssuerAltName(_) => ExtensionType::IssuerAltName, - &Extension::OtherNid(nid, _) => ExtensionType::OtherNid(nid), - &Extension::OtherStr(ref s, _) => ExtensionType::OtherStr(s.clone()), - } - } -} - -impl ExtensionType { - #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] - pub fn get_nid(&self) -> Option { - match self { - &ExtensionType::KeyUsage => Some(nid::KEY_USAGE), - &ExtensionType::ExtKeyUsage => Some(nid::EXT_KEY_USAGE), - &ExtensionType::SubjectAltName => Some(nid::SUBJECT_ALT_NAME), - &ExtensionType::IssuerAltName => Some(nid::ISSUER_ALT_NAME), - &ExtensionType::OtherNid(nid) => Some(nid), - &ExtensionType::OtherStr(_) => None, - } - } - - #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] - pub fn get_name(&self) -> Option<&str> { - match self { - &ExtensionType::OtherStr(ref s) => Some(s), - _ => None, - } - } -} - -// FIXME: This would be nicer as a method on Iterator. This can -// eventually be replaced by the successor to std::slice::SliceConcatExt.connect -fn join, T: ToString>(iter: I, sep: &str) -> String { - iter.enumerate().fold(String::new(), |mut acc, (idx, v)| { - if idx > 0 { - acc.push_str(sep) - }; - acc.push_str(&v.to_string()); - acc - }) -} - -impl ToString for Extension { - fn to_string(&self) -> String { - match self { - &Extension::KeyUsage(ref purposes) => join(purposes.iter(), ","), - &Extension::ExtKeyUsage(ref purposes) => join(purposes.iter(), ","), - &Extension::SubjectAltName(ref names) => { - join( - names.iter().map(|&(ref opt, ref val)| { - opt.to_string() + ":" + &val - }), - ",", - ) - } - &Extension::IssuerAltName(ref names) => { - join( - names.iter().map(|&(ref opt, ref val)| { - opt.to_string() + ":" + &val - }), - ",", - ) - } - &Extension::OtherNid(_, ref value) => value.clone(), - &Extension::OtherStr(_, ref value) => value.clone(), - } - } -} - -#[derive(Clone, Copy)] -#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] -pub enum KeyUsageOption { - DigitalSignature, - NonRepudiation, - KeyEncipherment, - DataEncipherment, - KeyAgreement, - KeyCertSign, - CRLSign, - EncipherOnly, - DecipherOnly, -} - -impl fmt::Display for KeyUsageOption { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - f.pad(match self { - &KeyUsageOption::DigitalSignature => "digitalSignature", - &KeyUsageOption::NonRepudiation => "nonRepudiation", - &KeyUsageOption::KeyEncipherment => "keyEncipherment", - &KeyUsageOption::DataEncipherment => "dataEncipherment", - &KeyUsageOption::KeyAgreement => "keyAgreement", - &KeyUsageOption::KeyCertSign => "keyCertSign", - &KeyUsageOption::CRLSign => "cRLSign", - &KeyUsageOption::EncipherOnly => "encipherOnly", - &KeyUsageOption::DecipherOnly => "decipherOnly", - }) - } -} - -#[derive(Clone)] -#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] -pub enum ExtKeyUsageOption { - ServerAuth, - ClientAuth, - CodeSigning, - EmailProtection, - TimeStamping, - MsCodeInd, - MsCodeCom, - MsCtlSign, - MsSgc, - MsEfs, - NsSgc, - /// An arbitrary key usage by OID. - Other(String), -} - -impl fmt::Display for ExtKeyUsageOption { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - f.pad(match self { - &ExtKeyUsageOption::ServerAuth => "serverAuth", - &ExtKeyUsageOption::ClientAuth => "clientAuth", - &ExtKeyUsageOption::CodeSigning => "codeSigning", - &ExtKeyUsageOption::EmailProtection => "emailProtection", - &ExtKeyUsageOption::TimeStamping => "timeStamping", - &ExtKeyUsageOption::MsCodeInd => "msCodeInd", - &ExtKeyUsageOption::MsCodeCom => "msCodeCom", - &ExtKeyUsageOption::MsCtlSign => "msCTLSign", - &ExtKeyUsageOption::MsSgc => "msSGC", - &ExtKeyUsageOption::MsEfs => "msEFS", - &ExtKeyUsageOption::NsSgc => "nsSGC", - &ExtKeyUsageOption::Other(ref s) => &s[..], - }) - } -} - -#[derive(Clone, Copy)] -#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] -pub enum AltNameOption { - /// The value is specified as OID;content. See `man ASN1_generate_nconf` for more information on the content syntax. - /// - /// ``` - /// use openssl::x509::extension::Extension::*; - /// use openssl::x509::extension::AltNameOption::Other as OtherName; - /// - /// # let generator = openssl::x509::X509Generator::new(); - /// generator.add_extension(SubjectAltName(vec![(OtherName,"2.999.3;ASN1:UTF8:some other name".to_owned())])); - /// ``` - Other, - Email, - DNS, - // X400, // Not supported by OpenSSL - Directory, - // EDIParty, // Not supported by OpenSSL - URI, - IPAddress, - RegisteredID, -} - -impl fmt::Display for AltNameOption { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - f.pad(match self { - &AltNameOption::Other => "otherName", - &AltNameOption::Email => "email", - &AltNameOption::DNS => "DNS", - &AltNameOption::Directory => "dirName", - &AltNameOption::URI => "URI", - &AltNameOption::IPAddress => "IP", - &AltNameOption::RegisteredID => "RID", - }) - } -} - -pub struct BasicConstraints { - critical: bool, - ca: bool, - pathlen: Option, -} - -impl BasicConstraints { - pub fn new() -> BasicConstraints { - BasicConstraints { - critical: false, - ca: false, - pathlen: None, - } - } - - pub fn critical(&mut self) -> &mut BasicConstraints { - self.critical = true; - self - } - - pub fn ca(&mut self) -> &mut BasicConstraints { - self.ca = true; - self - } - - pub fn pathlen(&mut self, pathlen: u32) -> &mut BasicConstraints { - self.pathlen = Some(pathlen); - self - } - - pub fn build(&self) -> Result { - let mut value = String::new(); - if self.critical { - value.push_str("critical,"); - } - value.push_str("CA:"); - if self.ca { - value.push_str("TRUE"); - } else { - value.push_str("FALSE"); - } - if let Some(pathlen) = self.pathlen { - write!(value, ",pathlen:{}", pathlen).unwrap(); - } - X509Extension::new_nid(None, None, nid::BASIC_CONSTRAINTS, &value) - } -} - -pub struct KeyUsage { - critical: bool, - digital_signature: bool, - non_repudiation: bool, - key_encipherment: bool, - data_encipherment: bool, - key_agreement: bool, - key_cert_sign: bool, - crl_sign: bool, - encipher_only: bool, - decipher_only: bool, -} - -impl KeyUsage { - pub fn new() -> KeyUsage { - KeyUsage { - critical: false, - digital_signature: false, - non_repudiation: false, - key_encipherment: false, - data_encipherment: false, - key_agreement: false, - key_cert_sign: false, - crl_sign: false, - encipher_only: false, - decipher_only: false, - } - } - - pub fn critical(&mut self) -> &mut KeyUsage { - self.critical = true; - self - } - - pub fn digital_signature(&mut self) -> &mut KeyUsage { - self.digital_signature = true; - self - } - - pub fn non_repudiation(&mut self) -> &mut KeyUsage { - self.non_repudiation = true; - self - } - - pub fn key_encipherment(&mut self) -> &mut KeyUsage { - self.key_encipherment = true; - self - } - - pub fn data_encipherment(&mut self) -> &mut KeyUsage { - self.data_encipherment = true; - self - } - - pub fn key_agreement(&mut self) -> &mut KeyUsage { - self.key_agreement = true; - self - } - - pub fn key_cert_sign(&mut self) -> &mut KeyUsage { - self.key_cert_sign = true; - self - } - - pub fn crl_sign(&mut self) -> &mut KeyUsage { - self.crl_sign = true; - self - } - - pub fn encipher_only(&mut self) -> &mut KeyUsage { - self.encipher_only = true; - self - } - - pub fn decipher_only(&mut self) -> &mut KeyUsage { - self.decipher_only = true; - self - } - - pub fn build(&self) -> Result { - let mut value = String::new(); - let mut first = true; - append(&mut value, &mut first, self.critical, "critical"); - append( - &mut value, - &mut first, - self.digital_signature, - "digitalSignature", - ); - append( - &mut value, - &mut first, - self.non_repudiation, - "nonRepudiation", - ); - append( - &mut value, - &mut first, - self.key_encipherment, - "keyEncipherment", - ); - append( - &mut value, - &mut first, - self.data_encipherment, - "dataEncipherment", - ); - append(&mut value, &mut first, self.key_agreement, "keyAgreement"); - append(&mut value, &mut first, self.key_cert_sign, "keyCertSign"); - append(&mut value, &mut first, self.crl_sign, "cRLSign"); - append(&mut value, &mut first, self.encipher_only, "encipherOnly"); - append(&mut value, &mut first, self.decipher_only, "decipherOnly"); - X509Extension::new_nid(None, None, nid::KEY_USAGE, &value) - } -} - -pub struct ExtendedKeyUsage { - critical: bool, - server_auth: bool, - client_auth: bool, - code_signing: bool, - email_protection: bool, - time_stamping: bool, - ms_code_ind: bool, - ms_code_com: bool, - ms_ctl_sign: bool, - ms_sgc: bool, - ms_efs: bool, - ns_sgc: bool, - other: Vec, -} - -impl ExtendedKeyUsage { - pub fn new() -> ExtendedKeyUsage { - ExtendedKeyUsage { - critical: false, - server_auth: false, - client_auth: false, - code_signing: false, - email_protection: false, - time_stamping: false, - ms_code_ind: false, - ms_code_com: false, - ms_ctl_sign: false, - ms_sgc: false, - ms_efs: false, - ns_sgc: false, - other: vec![], - } - } - - pub fn critical(&mut self) -> &mut ExtendedKeyUsage { - self.critical = true; - self - } - - pub fn server_auth(&mut self) -> &mut ExtendedKeyUsage { - self.server_auth = true; - self - } - - pub fn client_auth(&mut self) -> &mut ExtendedKeyUsage { - self.client_auth = true; - self - } - - pub fn code_signing(&mut self) -> &mut ExtendedKeyUsage { - self.code_signing = true; - self - } - - pub fn time_stamping(&mut self) -> &mut ExtendedKeyUsage { - self.time_stamping = true; - self - } - - pub fn ms_code_ind(&mut self) -> &mut ExtendedKeyUsage { - self.ms_code_ind = true; - self - } - - pub fn ms_code_com(&mut self) -> &mut ExtendedKeyUsage { - self.ms_code_com = true; - self - } - - pub fn ms_ctl_sign(&mut self) -> &mut ExtendedKeyUsage { - self.ms_ctl_sign = true; - self - } - - pub fn ms_sgc(&mut self) -> &mut ExtendedKeyUsage { - self.ms_sgc = true; - self - } - - pub fn ms_efs(&mut self) -> &mut ExtendedKeyUsage { - self.ms_efs = true; - self - } - - pub fn ns_sgc(&mut self) -> &mut ExtendedKeyUsage { - self.ns_sgc = true; - self - } - - pub fn other(&mut self, other: &str) -> &mut ExtendedKeyUsage { - self.other.push(other.to_owned()); - self - } - - pub fn build(&self) -> Result { - let mut value = String::new(); - let mut first = true; - append(&mut value, &mut first, self.critical, "critical"); - append(&mut value, &mut first, self.server_auth, "serverAuth"); - append(&mut value, &mut first, self.client_auth, "clientAuth"); - append(&mut value, &mut first, self.code_signing, "codeSigning"); - append( - &mut value, - &mut first, - self.email_protection, - "emailProtection", - ); - append(&mut value, &mut first, self.time_stamping, "timeStamping"); - append(&mut value, &mut first, self.ms_code_ind, "msCodeInd"); - append(&mut value, &mut first, self.ms_code_com, "msCodeCom"); - append(&mut value, &mut first, self.ms_ctl_sign, "msCTLSign"); - append(&mut value, &mut first, self.ms_sgc, "msSGC"); - append(&mut value, &mut first, self.ms_efs, "msEFS"); - append(&mut value, &mut first, self.ns_sgc, "nsSGC"); - for other in &self.other { - append(&mut value, &mut first, true, other); - } - X509Extension::new_nid(None, None, nid::EXT_KEY_USAGE, &value) - } -} - -pub struct SubjectKeyIdentifier { - critical: bool, -} - -impl SubjectKeyIdentifier { - pub fn new() -> SubjectKeyIdentifier { - SubjectKeyIdentifier { critical: false } - } - - pub fn critical(&mut self) -> &mut SubjectKeyIdentifier { - self.critical = true; - self - } - - pub fn build(&self, ctx: &X509v3Context) -> Result { - let mut value = String::new(); - let mut first = true; - append(&mut value, &mut first, self.critical, "critical"); - append(&mut value, &mut first, true, "hash"); - X509Extension::new_nid(None, Some(ctx), nid::SUBJECT_KEY_IDENTIFIER, &value) - } -} - -pub struct AuthorityKeyIdentifier { - critical: bool, - keyid: Option, - issuer: Option, -} - -impl AuthorityKeyIdentifier { - pub fn new() -> AuthorityKeyIdentifier { - AuthorityKeyIdentifier { - critical: false, - keyid: None, - issuer: None, - } - } - - pub fn critical(&mut self) -> &mut AuthorityKeyIdentifier { - self.critical = true; - self - } - - pub fn keyid(&mut self, always: bool) -> &mut AuthorityKeyIdentifier { - self.keyid = Some(always); - self - } - - pub fn issuer(&mut self, always: bool) -> &mut AuthorityKeyIdentifier { - self.issuer = Some(always); - self - } - - pub fn build(&self, ctx: &X509v3Context) -> Result { - let mut value = String::new(); - let mut first = true; - append(&mut value, &mut first, self.critical, "critical"); - match self.keyid { - Some(true) => append(&mut value, &mut first, true, "keyid:always"), - Some(false) => append(&mut value, &mut first, true, "keyid"), - None => {} - } - match self.issuer { - Some(true) => append(&mut value, &mut first, true, "issuer:always"), - Some(false) => append(&mut value, &mut first, true, "issuer"), - None => {} - } - X509Extension::new_nid(None, Some(ctx), nid::AUTHORITY_KEY_IDENTIFIER, &value) - } -} - -pub struct SubjectAlternativeName { - critical: bool, - names: Vec, -} - -impl SubjectAlternativeName { - pub fn new() -> SubjectAlternativeName { - SubjectAlternativeName { - critical: false, - names: vec![], - } - } - - pub fn critical(&mut self) -> &mut SubjectAlternativeName { - self.critical = true; - self - } - - pub fn email(&mut self, email: &str) -> &mut SubjectAlternativeName { - self.names.push(format!("email:{}", email)); - self - } - - pub fn uri(&mut self, uri: &str) -> &mut SubjectAlternativeName { - self.names.push(format!("URI:{}", uri)); - self - } - - pub fn dns(&mut self, dns: &str) -> &mut SubjectAlternativeName { - self.names.push(format!("DNS:{}", dns)); - self - } - - pub fn rid(&mut self, rid: &str) -> &mut SubjectAlternativeName { - self.names.push(format!("RID:{}", rid)); - self - } - - pub fn ip(&mut self, ip: &str) -> &mut SubjectAlternativeName { - self.names.push(format!("IP:{}", ip)); - self - } - - pub fn dir_name(&mut self, dir_name: &str) -> &mut SubjectAlternativeName { - self.names.push(format!("dirName:{}", dir_name)); - self - } - - pub fn other_name(&mut self, other_name: &str) -> &mut SubjectAlternativeName { - self.names.push(format!("otherName:{}", other_name)); - self - } - - pub fn build(&self, ctx: &X509v3Context) -> Result { - let mut value = String::new(); - let mut first = true; - append(&mut value, &mut first, self.critical, "critical"); - for name in &self.names { - append(&mut value, &mut first, true, name); - } - X509Extension::new_nid(None, Some(ctx), nid::SUBJECT_ALT_NAME, &value) - } -} - -fn append(value: &mut String, first: &mut bool, should: bool, element: &str) { - if !should { - return; - } - - if !*first { - value.push(','); - } - *first = false; - value.push_str(element); -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/x509/mod.rs cargo-0.26.0/vendor/openssl-0.9.24/src/x509/mod.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/x509/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/x509/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1225 +0,0 @@ -#![allow(deprecated)] -use libc::{c_int, c_long}; -use ffi; -use foreign_types::{ForeignType, ForeignTypeRef}; -use std::collections::HashMap; -use std::error::Error; -use std::ffi::{CStr, CString}; -use std::fmt; -use std::marker::PhantomData; -use std::mem; -use std::path::Path; -use std::ptr; -use std::slice; -use std::str; - -use {cvt, cvt_p, cvt_n}; -use asn1::{Asn1StringRef, Asn1Time, Asn1TimeRef, Asn1BitStringRef, Asn1IntegerRef, Asn1ObjectRef}; -use bio::MemBioSlice; -use bn::{BigNum, MSB_MAYBE_ZERO}; -use conf::ConfRef; -use error::ErrorStack; -use hash::MessageDigest; -use nid::{self, Nid}; -use pkey::{PKey, PKeyRef}; -use stack::{Stack, StackRef, Stackable}; -use string::OpensslString; -use ssl::SslRef; - -#[cfg(ossl10x)] -use ffi::{X509_set_notBefore, X509_set_notAfter, ASN1_STRING_data, X509_STORE_CTX_get_chain}; -#[cfg(ossl110)] -use ffi::{X509_set1_notBefore as X509_set_notBefore, X509_set1_notAfter as X509_set_notAfter, - ASN1_STRING_get0_data as ASN1_STRING_data, - X509_STORE_CTX_get0_chain as X509_STORE_CTX_get_chain}; - -#[cfg(any(all(feature = "v102", ossl102), all(feature = "v110", ossl110)))] -pub mod verify; - -use x509::extension::{ExtensionType, Extension}; - -pub mod extension; -pub mod store; - -#[cfg(test)] -mod tests; - -pub struct X509FileType(c_int); - -impl X509FileType { - pub fn as_raw(&self) -> c_int { - self.0 - } -} - -pub const X509_FILETYPE_PEM: X509FileType = X509FileType(ffi::X509_FILETYPE_PEM); -pub const X509_FILETYPE_ASN1: X509FileType = X509FileType(ffi::X509_FILETYPE_ASN1); -pub const X509_FILETYPE_DEFAULT: X509FileType = X509FileType(ffi::X509_FILETYPE_DEFAULT); - -foreign_type! { - type CType = ffi::X509_STORE_CTX; - fn drop = ffi::X509_STORE_CTX_free; - - pub struct X509StoreContext; - pub struct X509StoreContextRef; -} - -impl X509StoreContextRef { - pub fn error(&self) -> Option { - unsafe { X509VerifyError::from_raw(ffi::X509_STORE_CTX_get_error(self.as_ptr()) as c_long) } - } - - pub fn current_cert(&self) -> Option<&X509Ref> { - unsafe { - let ptr = ffi::X509_STORE_CTX_get_current_cert(self.as_ptr()); - if ptr.is_null() { - None - } else { - Some(X509Ref::from_ptr(ptr)) - } - } - } - - pub fn error_depth(&self) -> u32 { - unsafe { ffi::X509_STORE_CTX_get_error_depth(self.as_ptr()) as u32 } - } - - pub fn chain(&self) -> Option<&StackRef> { - unsafe { - let chain = X509_STORE_CTX_get_chain(self.as_ptr()); - - if chain.is_null() { - return None; - } - - Some(StackRef::from_ptr(chain)) - } - } - - /// Returns a reference to the `Ssl` associated with this context. - pub fn ssl(&self) -> Result, ErrorStack> { - unsafe { - let idx = cvt_n(ffi::SSL_get_ex_data_X509_STORE_CTX_idx())?; - let ssl = ffi::X509_STORE_CTX_get_ex_data(self.as_ptr(), idx); - if ssl.is_null() { - Ok(None) - } else { - Ok(Some(SslRef::from_ptr(ssl as *mut ffi::SSL))) - } - } - } -} - -#[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] -pub struct X509Generator { - days: u32, - names: Vec<(String, String)>, - extensions: Extensions, - hash_type: MessageDigest, -} - -#[allow(deprecated)] -impl X509Generator { - /// Creates a new generator with the following defaults: - /// - /// validity period: 365 days - /// - /// CN: "rust-openssl" - /// - /// hash: SHA1 - #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] - pub fn new() -> X509Generator { - X509Generator { - days: 365, - names: vec![], - extensions: Extensions::new(), - hash_type: MessageDigest::sha1(), - } - } - - /// Sets certificate validity period in days since today - #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] - pub fn set_valid_period(mut self, days: u32) -> X509Generator { - self.days = days; - self - } - - /// Add attribute to the name of the certificate - /// - /// ``` - /// # let generator = openssl::x509::X509Generator::new(); - /// generator.add_name("CN".to_string(),"example.com".to_string()); - /// ``` - #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] - pub fn add_name(mut self, attr_type: String, attr_value: String) -> X509Generator { - self.names.push((attr_type, attr_value)); - self - } - - /// Add multiple attributes to the name of the certificate - /// - /// ``` - /// # let generator = openssl::x509::X509Generator::new(); - /// generator.add_names(vec![("CN".to_string(),"example.com".to_string())]); - /// ``` - #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] - pub fn add_names(mut self, attrs: I) -> X509Generator - where - I: IntoIterator, - { - self.names.extend(attrs); - self - } - - /// Add an extension to a certificate - /// - /// If the extension already exists, it will be replaced. - /// - /// ``` - /// use openssl::x509::extension::Extension::*; - /// use openssl::x509::extension::KeyUsageOption::*; - /// - /// # let generator = openssl::x509::X509Generator::new(); - /// generator.add_extension(KeyUsage(vec![DigitalSignature, KeyEncipherment])); - /// ``` - #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] - pub fn add_extension(mut self, ext: extension::Extension) -> X509Generator { - self.extensions.add(ext); - self - } - - /// Add multiple extensions to a certificate - /// - /// If any of the extensions already exist, they will be replaced. - /// - /// ``` - /// use openssl::x509::extension::Extension::*; - /// use openssl::x509::extension::KeyUsageOption::*; - /// - /// # let generator = openssl::x509::X509Generator::new(); - /// generator.add_extensions(vec![KeyUsage(vec![DigitalSignature, KeyEncipherment])]); - /// ``` - #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] - pub fn add_extensions(mut self, exts: I) -> X509Generator - where - I: IntoIterator, - { - for ext in exts { - self.extensions.add(ext); - } - - self - } - - #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] - pub fn set_sign_hash(mut self, hash_type: MessageDigest) -> X509Generator { - self.hash_type = hash_type; - self - } - - /// Sets the certificate public-key, then self-sign and return it - #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] - pub fn sign(&self, p_key: &PKeyRef) -> Result { - let mut builder = X509::builder()?; - builder.set_version(2)?; - - let mut serial = BigNum::new()?; - serial.rand(128, MSB_MAYBE_ZERO, false)?; - let serial = serial.to_asn1_integer()?; - builder.set_serial_number(&serial)?; - - let not_before = Asn1Time::days_from_now(0)?; - builder.set_not_before(¬_before)?; - let not_after = Asn1Time::days_from_now(self.days)?; - builder.set_not_after(¬_after)?; - - builder.set_pubkey(p_key)?; - - let mut name = X509Name::builder()?; - if self.names.is_empty() { - name.append_entry_by_nid(nid::COMMONNAME, "rust-openssl")?; - } else { - for &(ref key, ref value) in &self.names { - name.append_entry_by_text(key, value)?; - } - } - let name = name.build(); - - builder.set_subject_name(&name)?; - builder.set_issuer_name(&name)?; - - for (exttype, ext) in self.extensions.iter() { - let extension = match exttype.get_nid() { - Some(nid) => { - let ctx = builder.x509v3_context(None, None); - X509Extension::new_nid( - None, - Some(&ctx), - nid, - &ext.to_string(), - )? - } - None => { - let ctx = builder.x509v3_context(None, None); - X509Extension::new( - None, - Some(&ctx), - &exttype.get_name().unwrap(), - &ext.to_string(), - )? - } - }; - builder.append_extension(extension)?; - } - - builder.sign(p_key, self.hash_type)?; - Ok(builder.build()) - } - - /// Obtain a certificate signing request (CSR) - #[deprecated(since = "0.9.7", note = "use X509Builder and X509ReqBuilder instead")] - pub fn request(&self, p_key: &PKeyRef) -> Result { - let cert = match self.sign(p_key) { - Ok(c) => c, - Err(x) => return Err(x), - }; - - unsafe { - let req = cvt_p(ffi::X509_to_X509_REQ( - cert.as_ptr(), - ptr::null_mut(), - ptr::null(), - ))?; - let req = X509Req::from_ptr(req); - - let exts = compat::X509_get0_extensions(cert.as_ptr()); - if exts != ptr::null_mut() { - cvt( - ffi::X509_REQ_add_extensions(req.as_ptr(), exts as *mut _), - )?; - } - - let hash_fn = self.hash_type.as_ptr(); - cvt( - ffi::X509_REQ_sign(req.as_ptr(), p_key.as_ptr(), hash_fn), - )?; - - Ok(req) - } - } -} - -/// A builder type which can create `X509` objects. -pub struct X509Builder(X509); - -impl X509Builder { - /// Creates a new builder. - pub fn new() -> Result { - unsafe { - ffi::init(); - cvt_p(ffi::X509_new()).map(|p| X509Builder(X509(p))) - } - } - - /// Sets the notAfter constraint on the certificate. - pub fn set_not_after(&mut self, not_after: &Asn1TimeRef) -> Result<(), ErrorStack> { - unsafe { cvt(X509_set_notAfter(self.0.as_ptr(), not_after.as_ptr())).map(|_| ()) } - } - - /// Sets the notBefore constraint on the certificate. - pub fn set_not_before(&mut self, not_before: &Asn1TimeRef) -> Result<(), ErrorStack> { - unsafe { cvt(X509_set_notBefore(self.0.as_ptr(), not_before.as_ptr())).map(|_| ()) } - } - - /// Sets the version of the certificate. - /// - /// Note that the version is zero-indexed; that is, a certificate corresponding to version 3 of - /// the X.509 standard should pass `2` to this method. - pub fn set_version(&mut self, version: i32) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::X509_set_version(self.0.as_ptr(), version.into())).map(|_| ()) } - } - - /// Sets the serial number of the certificate. - pub fn set_serial_number(&mut self, serial_number: &Asn1IntegerRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::X509_set_serialNumber( - self.0.as_ptr(), - serial_number.as_ptr(), - )).map(|_| ()) - } - } - - /// Sets the issuer name of the certificate. - pub fn set_issuer_name(&mut self, issuer_name: &X509NameRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::X509_set_issuer_name( - self.0.as_ptr(), - issuer_name.as_ptr(), - )).map(|_| ()) - } - } - - /// Sets the subject name of the certificate. - /// - /// When building certificates, the `C`, `ST`, and `O` options are common when using the openssl command line tools. - /// The `CN` field is used for the common name, such as a DNS name. - /// - /// ``` - /// use openssl::x509::{X509, X509NameBuilder}; - /// - /// let mut x509_name = openssl::x509::X509NameBuilder::new().unwrap(); - /// x509_name.append_entry_by_text("C", "US").unwrap(); - /// x509_name.append_entry_by_text("ST", "CA").unwrap(); - /// x509_name.append_entry_by_text("O", "Some organization").unwrap(); - /// x509_name.append_entry_by_text("CN", "www.example.com").unwrap(); - /// let x509_name = x509_name.build(); - /// - /// let mut x509 = openssl::x509::X509::builder().unwrap(); - /// x509.set_subject_name(&x509_name).unwrap(); - /// ``` - pub fn set_subject_name(&mut self, subject_name: &X509NameRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::X509_set_subject_name( - self.0.as_ptr(), - subject_name.as_ptr(), - )).map(|_| ()) - } - } - - /// Sets the public key associated with the certificate. - pub fn set_pubkey(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::X509_set_pubkey(self.0.as_ptr(), key.as_ptr())).map(|_| ()) } - } - - /// Returns a context object which is needed to create certain X509 extension values. - /// - /// Set `issuer` to `None` if the certificate will be self-signed. - pub fn x509v3_context<'a>( - &'a self, - issuer: Option<&'a X509Ref>, - conf: Option<&'a ConfRef>, - ) -> X509v3Context<'a> { - unsafe { - let mut ctx = mem::zeroed(); - - let issuer = match issuer { - Some(issuer) => issuer.as_ptr(), - None => self.0.as_ptr(), - }; - let subject = self.0.as_ptr(); - ffi::X509V3_set_ctx( - &mut ctx, - issuer, - subject, - ptr::null_mut(), - ptr::null_mut(), - 0, - ); - - // nodb case taken care of since we zeroed ctx above - if let Some(conf) = conf { - ffi::X509V3_set_nconf(&mut ctx, conf.as_ptr()); - } - - X509v3Context(ctx, PhantomData) - } - } - - /// Adds an X509 extension value to the certificate. - pub fn append_extension(&mut self, extension: X509Extension) -> Result<(), ErrorStack> { - unsafe { - cvt( - ffi::X509_add_ext(self.0.as_ptr(), extension.as_ptr(), -1), - )?; - mem::forget(extension); - Ok(()) - } - } - - /// Signs the certificate with a private key. - pub fn sign(&mut self, key: &PKeyRef, hash: MessageDigest) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::X509_sign(self.0.as_ptr(), key.as_ptr(), hash.as_ptr())).map(|_| ()) } - } - - /// Consumes the builder, returning the certificate. - pub fn build(self) -> X509 { - self.0 - } -} - -foreign_type! { - type CType = ffi::X509; - fn drop = ffi::X509_free; - - pub struct X509; - pub struct X509Ref; -} - -impl X509Ref { - pub fn subject_name(&self) -> &X509NameRef { - unsafe { - let name = ffi::X509_get_subject_name(self.as_ptr()); - X509NameRef::from_ptr(name) - } - } - - /// Returns this certificate's SAN entries, if they exist. - pub fn subject_alt_names(&self) -> Option> { - unsafe { - let stack = ffi::X509_get_ext_d2i( - self.as_ptr(), - ffi::NID_subject_alt_name, - ptr::null_mut(), - ptr::null_mut(), - ); - if stack.is_null() { - return None; - } - - Some(Stack::from_ptr(stack as *mut _)) - } - } - - pub fn public_key(&self) -> Result { - unsafe { - let pkey = cvt_p(ffi::X509_get_pubkey(self.as_ptr()))?; - Ok(PKey::from_ptr(pkey)) - } - } - - /// Returns certificate fingerprint calculated using provided hash - pub fn fingerprint(&self, hash_type: MessageDigest) -> Result, ErrorStack> { - unsafe { - let evp = hash_type.as_ptr(); - let mut len = ffi::EVP_MAX_MD_SIZE; - let mut buf = vec![0u8; len as usize]; - cvt(ffi::X509_digest( - self.as_ptr(), - evp, - buf.as_mut_ptr() as *mut _, - &mut len, - ))?; - buf.truncate(len as usize); - Ok(buf) - } - } - - /// Returns the certificate's Not After validity period. - pub fn not_after(&self) -> &Asn1TimeRef { - unsafe { - let date = compat::X509_get_notAfter(self.as_ptr()); - assert!(!date.is_null()); - Asn1TimeRef::from_ptr(date) - } - } - - /// Returns the certificate's Not Before validity period. - pub fn not_before(&self) -> &Asn1TimeRef { - unsafe { - let date = compat::X509_get_notBefore(self.as_ptr()); - assert!(!date.is_null()); - Asn1TimeRef::from_ptr(date) - } - } - - /// Returns the certificate's signature - pub fn signature(&self) -> &Asn1BitStringRef { - unsafe { - let mut signature = ptr::null(); - compat::X509_get0_signature(&mut signature, ptr::null_mut(), self.as_ptr()); - assert!(!signature.is_null()); - Asn1BitStringRef::from_ptr(signature as *mut _) - } - } - - /// Returns the certificate's signature algorithm. - pub fn signature_algorithm(&self) -> &X509AlgorithmRef { - unsafe { - let mut algor = ptr::null(); - compat::X509_get0_signature(ptr::null_mut(), &mut algor, self.as_ptr()); - assert!(!algor.is_null()); - X509AlgorithmRef::from_ptr(algor as *mut _) - } - } - - /// Returns the list of OCSP responder URLs specified in the certificate's Authority Information - /// Access field. - pub fn ocsp_responders(&self) -> Result, ErrorStack> { - unsafe { cvt_p(ffi::X509_get1_ocsp(self.as_ptr())).map(|p| Stack::from_ptr(p)) } - } - - /// Checks that this certificate issued `subject`. - pub fn issued(&self, subject: &X509Ref) -> Result<(), X509VerifyError> { - unsafe { - let r = ffi::X509_check_issued(self.as_ptr(), subject.as_ptr()); - match X509VerifyError::from_raw(r as c_long) { - Some(e) => Err(e), - None => Ok(()), - } - } - } - - to_pem!(ffi::PEM_write_bio_X509); - to_der!(ffi::i2d_X509); -} - -impl ToOwned for X509Ref { - type Owned = X509; - - fn to_owned(&self) -> X509 { - unsafe { - compat::X509_up_ref(self.as_ptr()); - X509::from_ptr(self.as_ptr()) - } - } -} - -impl X509 { - /// Returns a new builder. - pub fn builder() -> Result { - X509Builder::new() - } - - from_pem!(X509, ffi::PEM_read_bio_X509); - from_der!(X509, ffi::d2i_X509); - - /// Deserializes a list of PEM-formatted certificates. - pub fn stack_from_pem(pem: &[u8]) -> Result, ErrorStack> { - unsafe { - ffi::init(); - let bio = MemBioSlice::new(pem)?; - - let mut certs = vec![]; - loop { - let r = - ffi::PEM_read_bio_X509(bio.as_ptr(), ptr::null_mut(), None, ptr::null_mut()); - if r.is_null() { - let err = ffi::ERR_peek_last_error(); - if ffi::ERR_GET_LIB(err) == ffi::ERR_LIB_PEM && - ffi::ERR_GET_REASON(err) == ffi::PEM_R_NO_START_LINE - { - ffi::ERR_clear_error(); - break; - } - - return Err(ErrorStack::get()); - } else { - certs.push(X509(r)); - } - } - - Ok(certs) - } - } -} - -impl Clone for X509 { - fn clone(&self) -> X509 { - X509Ref::to_owned(self) - } -} - -impl AsRef for X509Ref { - fn as_ref(&self) -> &X509Ref { - self - } -} - -impl Stackable for X509 { - type StackType = ffi::stack_st_X509; -} - -/// A context object required to construct certain X509 extension values. -pub struct X509v3Context<'a>(ffi::X509V3_CTX, PhantomData<(&'a X509Ref, &'a ConfRef)>); - -impl<'a> X509v3Context<'a> { - pub fn as_ptr(&self) -> *mut ffi::X509V3_CTX { - &self.0 as *const _ as *mut _ - } -} - -foreign_type! { - type CType = ffi::X509_EXTENSION; - fn drop = ffi::X509_EXTENSION_free; - - pub struct X509Extension; - pub struct X509ExtensionRef; -} - -impl Stackable for X509Extension { - type StackType = ffi::stack_st_X509_EXTENSION; -} - -impl X509Extension { - /// Constructs an X509 extension value. See `man x509v3_config` for information on supported - /// names and their value formats. - /// - /// Some extension types, such as `subjectAlternativeName`, require an `X509v3Context` to be - /// provided. - /// - /// See the extension module for builder types which will construct certain common extensions. - pub fn new( - conf: Option<&ConfRef>, - context: Option<&X509v3Context>, - name: &str, - value: &str, - ) -> Result { - let name = CString::new(name).unwrap(); - let value = CString::new(value).unwrap(); - unsafe { - ffi::init(); - let conf = conf.map_or(ptr::null_mut(), ConfRef::as_ptr); - let context = context.map_or(ptr::null_mut(), X509v3Context::as_ptr); - let name = name.as_ptr() as *mut _; - let value = value.as_ptr() as *mut _; - - cvt_p(ffi::X509V3_EXT_nconf(conf, context, name, value)).map(X509Extension) - } - } - - /// Constructs an X509 extension value. See `man x509v3_config` for information on supported - /// extensions and their value formats. - /// - /// Some extension types, such as `nid::SUBJECT_ALTERNATIVE_NAME`, require an `X509v3Context` to - /// be provided. - /// - /// See the extension module for builder types which will construct certain common extensions. - pub fn new_nid( - conf: Option<&ConfRef>, - context: Option<&X509v3Context>, - name: Nid, - value: &str, - ) -> Result { - let value = CString::new(value).unwrap(); - unsafe { - ffi::init(); - let conf = conf.map_or(ptr::null_mut(), ConfRef::as_ptr); - let context = context.map_or(ptr::null_mut(), X509v3Context::as_ptr); - let name = name.as_raw(); - let value = value.as_ptr() as *mut _; - - cvt_p(ffi::X509V3_EXT_nconf_nid(conf, context, name, value)).map(X509Extension) - } - } -} - -pub struct X509NameBuilder(X509Name); - -impl X509NameBuilder { - pub fn new() -> Result { - unsafe { - ffi::init(); - cvt_p(ffi::X509_NAME_new()).map(|p| X509NameBuilder(X509Name(p))) - } - } - - pub fn append_entry_by_text(&mut self, field: &str, value: &str) -> Result<(), ErrorStack> { - unsafe { - let field = CString::new(field).unwrap(); - assert!(value.len() <= c_int::max_value() as usize); - cvt(ffi::X509_NAME_add_entry_by_txt( - self.0.as_ptr(), - field.as_ptr() as *mut _, - ffi::MBSTRING_UTF8, - value.as_ptr(), - value.len() as c_int, - -1, - 0, - )).map(|_| ()) - } - } - - pub fn append_entry_by_nid(&mut self, field: Nid, value: &str) -> Result<(), ErrorStack> { - unsafe { - assert!(value.len() <= c_int::max_value() as usize); - cvt(ffi::X509_NAME_add_entry_by_NID( - self.0.as_ptr(), - field.as_raw(), - ffi::MBSTRING_UTF8, - value.as_ptr() as *mut _, - value.len() as c_int, - -1, - 0, - )).map(|_| ()) - } - } - - pub fn build(self) -> X509Name { - self.0 - } -} - -foreign_type! { - type CType = ffi::X509_NAME; - fn drop = ffi::X509_NAME_free; - - pub struct X509Name; - pub struct X509NameRef; -} - -impl X509Name { - /// Returns a new builder. - pub fn builder() -> Result { - X509NameBuilder::new() - } - - /// Loads subject names from a file containing PEM-formatted certificates. - /// - /// This is commonly used in conjunction with `SslContextBuilder::set_client_ca_list`. - pub fn load_client_ca_file>(file: P) -> Result, ErrorStack> { - let file = CString::new(file.as_ref().as_os_str().to_str().unwrap()).unwrap(); - unsafe { cvt_p(ffi::SSL_load_client_CA_file(file.as_ptr())).map(|p| Stack::from_ptr(p)) } - } -} - -impl Stackable for X509Name { - type StackType = ffi::stack_st_X509_NAME; -} - -impl X509NameRef { - pub fn entries_by_nid<'a>(&'a self, nid: Nid) -> X509NameEntries<'a> { - X509NameEntries { - name: self, - nid: nid, - loc: -1, - } - } -} - -pub struct X509NameEntries<'a> { - name: &'a X509NameRef, - nid: Nid, - loc: c_int, -} - -impl<'a> Iterator for X509NameEntries<'a> { - type Item = &'a X509NameEntryRef; - - fn next(&mut self) -> Option<&'a X509NameEntryRef> { - unsafe { - self.loc = - ffi::X509_NAME_get_index_by_NID(self.name.as_ptr(), self.nid.as_raw(), self.loc); - - if self.loc == -1 { - return None; - } - - let entry = ffi::X509_NAME_get_entry(self.name.as_ptr(), self.loc); - assert!(!entry.is_null()); - - Some(X509NameEntryRef::from_ptr(entry)) - } - } -} - -foreign_type! { - type CType = ffi::X509_NAME_ENTRY; - fn drop = ffi::X509_NAME_ENTRY_free; - - pub struct X509NameEntry; - pub struct X509NameEntryRef; -} - -impl X509NameEntryRef { - pub fn data(&self) -> &Asn1StringRef { - unsafe { - let data = ffi::X509_NAME_ENTRY_get_data(self.as_ptr()); - Asn1StringRef::from_ptr(data) - } - } -} - -pub struct X509ReqBuilder(X509Req); - -impl X509ReqBuilder { - pub fn new() -> Result { - unsafe { - ffi::init(); - cvt_p(ffi::X509_REQ_new()).map(|p| X509ReqBuilder(X509Req(p))) - } - - } - - pub fn set_version(&mut self, version: i32) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::X509_REQ_set_version(self.0.as_ptr(), version.into())).map(|_| ()) } - } - - pub fn set_subject_name(&mut self, subject_name: &X509NameRef) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::X509_REQ_set_subject_name( - self.0.as_ptr(), - subject_name.as_ptr(), - )).map(|_| ()) - } - } - - pub fn set_pubkey(&mut self, key: &PKeyRef) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::X509_REQ_set_pubkey(self.0.as_ptr(), key.as_ptr())).map(|_| ()) } - } - - pub fn x509v3_context<'a>(&'a self, conf: Option<&'a ConfRef>) -> X509v3Context<'a> { - unsafe { - let mut ctx = mem::zeroed(); - - ffi::X509V3_set_ctx( - &mut ctx, - ptr::null_mut(), - ptr::null_mut(), - self.0.as_ptr(), - ptr::null_mut(), - 0, - ); - - // nodb case taken care of since we zeroed ctx above - if let Some(conf) = conf { - ffi::X509V3_set_nconf(&mut ctx, conf.as_ptr()); - } - - X509v3Context(ctx, PhantomData) - } - } - - pub fn add_extensions( - &mut self, - extensions: &StackRef, - ) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::X509_REQ_add_extensions( - self.0.as_ptr(), - extensions.as_ptr(), - )).map(|_| ()) - } - } - - pub fn sign(&mut self, key: &PKeyRef, hash: MessageDigest) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::X509_REQ_sign( - self.0.as_ptr(), - key.as_ptr(), - hash.as_ptr(), - )).map(|_| ()) - } - } - - pub fn build(self) -> X509Req { - self.0 - } -} - -foreign_type! { - type CType = ffi::X509_REQ; - fn drop = ffi::X509_REQ_free; - - pub struct X509Req; - pub struct X509ReqRef; -} - -impl X509Req { - pub fn builder() -> Result { - X509ReqBuilder::new() - } - - /// Reads CSR from PEM - pub fn from_pem(buf: &[u8]) -> Result { - let mem_bio = MemBioSlice::new(buf)?; - unsafe { - let handle = cvt_p(ffi::PEM_read_bio_X509_REQ( - mem_bio.as_ptr(), - ptr::null_mut(), - None, - ptr::null_mut(), - ))?; - Ok(X509Req::from_ptr(handle)) - } - } - - from_der!(X509Req, ffi::d2i_X509_REQ); -} - -impl X509ReqRef { - to_pem!(ffi::PEM_write_bio_X509_REQ); - to_der!(ffi::i2d_X509_REQ); - - pub fn version(&self) -> i32 { - unsafe { compat::X509_REQ_get_version(self.as_ptr()) as i32 } - } - - pub fn subject_name(&self) -> &X509NameRef { - unsafe { - let name = compat::X509_REQ_get_subject_name(self.as_ptr()); - assert!(!name.is_null()); - X509NameRef::from_ptr(name) - } - } -} - -/// A collection of X.509 extensions. -/// -/// Upholds the invariant that a certificate MUST NOT include more than one -/// instance of a particular extension, according to RFC 3280 §4.2. Also -/// ensures that extensions are added to the certificate during signing -/// in the order they were inserted, which is required for certain -/// extensions like SubjectKeyIdentifier and AuthorityKeyIdentifier. -struct Extensions { - /// The extensions contained in the collection. - extensions: Vec, - /// A map of used to keep track of added extensions and their indexes in `self.extensions`. - indexes: HashMap, -} - -impl Extensions { - /// Creates a new `Extensions`. - pub fn new() -> Extensions { - Extensions { - extensions: vec![], - indexes: HashMap::new(), - } - } - - /// Adds a new `Extension`, replacing any existing one of the same - /// `ExtensionType`. - pub fn add(&mut self, ext: Extension) { - let ext_type = ext.get_type(); - - if let Some(index) = self.indexes.get(&ext_type) { - self.extensions[*index] = ext; - return; - } - - self.extensions.push(ext); - self.indexes.insert(ext_type, self.extensions.len() - 1); - } - - /// Returns an `ExtensionsIter` for the collection. - pub fn iter(&self) -> ExtensionsIter { - ExtensionsIter { - current: 0, - extensions: &self.extensions, - } - } -} - -/// An iterator that iterates over `(ExtensionType, Extension)` for each -/// extension in the collection. -struct ExtensionsIter<'a> { - current: usize, - extensions: &'a Vec, -} - -impl<'a> Iterator for ExtensionsIter<'a> { - type Item = (ExtensionType, &'a Extension); - - fn next(&mut self) -> Option { - if self.current < self.extensions.len() { - let ext = &self.extensions[self.current]; - - self.current += 1; - - Some((ext.get_type(), ext)) - } else { - None - } - } -} - -pub struct X509VerifyError(c_long); - -impl fmt::Debug for X509VerifyError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("X509VerifyError") - .field("code", &self.0) - .field("error", &self.error_string()) - .finish() - } -} - -impl fmt::Display for X509VerifyError { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.write_str(self.error_string()) - } -} - -impl Error for X509VerifyError { - fn description(&self) -> &str { - "an X509 validation error" - } -} - -impl X509VerifyError { - /// Creates an `X509VerifyError` from a raw error number. - /// - /// `None` will be returned if `err` is `X509_V_OK`. - /// - /// # Safety - /// - /// Some methods on `X509VerifyError` are not thread safe if the error - /// number is invalid. - pub unsafe fn from_raw(err: c_long) -> Option { - if err == ffi::X509_V_OK as c_long { - None - } else { - Some(X509VerifyError(err)) - } - } - - pub fn as_raw(&self) -> c_long { - self.0 - } - - pub fn error_string(&self) -> &'static str { - ffi::init(); - - unsafe { - let s = ffi::X509_verify_cert_error_string(self.0); - str::from_utf8(CStr::from_ptr(s).to_bytes()).unwrap() - } - } -} - -foreign_type! { - type CType = ffi::GENERAL_NAME; - fn drop = ffi::GENERAL_NAME_free; - - pub struct GeneralName; - pub struct GeneralNameRef; -} - -impl GeneralNameRef { - /// Returns the contents of this `GeneralName` if it is a `dNSName`. - pub fn dnsname(&self) -> Option<&str> { - unsafe { - if (*self.as_ptr()).type_ != ffi::GEN_DNS { - return None; - } - - let ptr = ASN1_STRING_data((*self.as_ptr()).d as *mut _); - let len = ffi::ASN1_STRING_length((*self.as_ptr()).d as *mut _); - - let slice = slice::from_raw_parts(ptr as *const u8, len as usize); - // dNSNames are stated to be ASCII (specifically IA5). Hopefully - // OpenSSL checks that when loading a certificate but if not we'll - // use this instead of from_utf8_unchecked just in case. - str::from_utf8(slice).ok() - } - } - - /// Returns the contents of this `GeneralName` if it is an `iPAddress`. - pub fn ipaddress(&self) -> Option<&[u8]> { - unsafe { - if (*self.as_ptr()).type_ != ffi::GEN_IPADD { - return None; - } - - let ptr = ASN1_STRING_data((*self.as_ptr()).d as *mut _); - let len = ffi::ASN1_STRING_length((*self.as_ptr()).d as *mut _); - - Some(slice::from_raw_parts(ptr as *const u8, len as usize)) - } - } -} - -impl Stackable for GeneralName { - type StackType = ffi::stack_st_GENERAL_NAME; -} - -foreign_type! { - type CType = ffi::X509_ALGOR; - fn drop = ffi::X509_ALGOR_free; - - pub struct X509Algorithm; - pub struct X509AlgorithmRef; -} - -impl X509AlgorithmRef { - /// Returns the ASN.1 OID of this algorithm. - pub fn object(&self) -> &Asn1ObjectRef { - unsafe { - let mut oid = ptr::null(); - compat::X509_ALGOR_get0(&mut oid, ptr::null_mut(), ptr::null_mut(), self.as_ptr()); - assert!(!oid.is_null()); - Asn1ObjectRef::from_ptr(oid as *mut _) - } - } -} - -#[cfg(ossl110)] -mod compat { - pub use ffi::X509_getm_notAfter as X509_get_notAfter; - pub use ffi::X509_getm_notBefore as X509_get_notBefore; - pub use ffi::X509_up_ref; - pub use ffi::X509_get0_extensions; - pub use ffi::X509_REQ_get_version; - pub use ffi::X509_REQ_get_subject_name; - pub use ffi::X509_get0_signature; - pub use ffi::X509_ALGOR_get0; -} - -#[cfg(ossl10x)] -#[allow(bad_style)] -mod compat { - use libc::{c_int, c_void}; - use ffi; - - pub unsafe fn X509_get_notAfter(x: *mut ffi::X509) -> *mut ffi::ASN1_TIME { - (*(*(*x).cert_info).validity).notAfter - } - - pub unsafe fn X509_get_notBefore(x: *mut ffi::X509) -> *mut ffi::ASN1_TIME { - (*(*(*x).cert_info).validity).notBefore - } - - pub unsafe fn X509_up_ref(x: *mut ffi::X509) { - ffi::CRYPTO_add_lock( - &mut (*x).references, - 1, - ffi::CRYPTO_LOCK_X509, - "mod.rs\0".as_ptr() as *const _, - line!() as c_int, - ); - } - - pub unsafe fn X509_get0_extensions( - cert: *const ffi::X509, - ) -> *const ffi::stack_st_X509_EXTENSION { - let info = (*cert).cert_info; - if info.is_null() { - 0 as *mut _ - } else { - (*info).extensions - } - } - - pub unsafe fn X509_REQ_get_version(x: *mut ffi::X509_REQ) -> ::libc::c_long { - ::ffi::ASN1_INTEGER_get((*(*x).req_info).version) - } - - pub unsafe fn X509_REQ_get_subject_name(x: *mut ffi::X509_REQ) -> *mut ::ffi::X509_NAME { - (*(*x).req_info).subject - } - - pub unsafe fn X509_get0_signature( - psig: *mut *const ffi::ASN1_BIT_STRING, - palg: *mut *const ffi::X509_ALGOR, - x: *const ffi::X509, - ) { - if !psig.is_null() { - *psig = (*x).signature; - } - if !palg.is_null() { - *palg = (*x).sig_alg; - } - } - - pub unsafe fn X509_ALGOR_get0( - paobj: *mut *const ffi::ASN1_OBJECT, - pptype: *mut c_int, - pval: *mut *mut c_void, - alg: *const ffi::X509_ALGOR, - ) { - if !paobj.is_null() { - *paobj = (*alg).algorithm; - } - assert!(pptype.is_null()); - assert!(pval.is_null()); - } -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/x509/store.rs cargo-0.26.0/vendor/openssl-0.9.24/src/x509/store.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/x509/store.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/x509/store.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -use ffi; -use foreign_types::ForeignTypeRef; -use std::mem; - -use {cvt, cvt_p}; -use error::ErrorStack; -use x509::X509; - -foreign_type! { - type CType = ffi::X509_STORE; - fn drop = ffi::X509_STORE_free; - - pub struct X509StoreBuilder; - pub struct X509StoreBuilderRef; -} - -impl X509StoreBuilder { - /// Returns a builder for a certificate store. - /// - /// The store is initially empty. - pub fn new() -> Result { - unsafe { - ffi::init(); - - cvt_p(ffi::X509_STORE_new()).map(X509StoreBuilder) - } - } - - /// Constructs the `X509Store`. - pub fn build(self) -> X509Store { - let store = X509Store(self.0); - mem::forget(self); - store - } -} - -impl X509StoreBuilderRef { - /// Adds a certificate to the certificate store. - // FIXME should take an &X509Ref - pub fn add_cert(&mut self, cert: X509) -> Result<(), ErrorStack> { - unsafe { - cvt(ffi::X509_STORE_add_cert(self.as_ptr(), cert.as_ptr())).map(|_| ()) - } - } - - /// Load certificates from their default locations. - /// - /// These locations are read from the `SSL_CERT_FILE` and `SSL_CERT_DIR` - /// environment variables if present, or defaults specified at OpenSSL - /// build time otherwise. - pub fn set_default_paths(&mut self) -> Result<(), ErrorStack> { - unsafe { cvt(ffi::X509_STORE_set_default_paths(self.as_ptr())).map(|_| ()) } - } -} - -foreign_type! { - type CType = ffi::X509_STORE; - fn drop = ffi::X509_STORE_free; - - pub struct X509Store; - pub struct X509StoreRef; -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/x509/tests.rs cargo-0.26.0/vendor/openssl-0.9.24/src/x509/tests.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/x509/tests.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/x509/tests.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,407 +0,0 @@ -use hex::{FromHex, ToHex}; - -use asn1::Asn1Time; -use bn::{BigNum, MSB_MAYBE_ZERO}; -use ec::{NAMED_CURVE, EcGroup, EcKey}; -use hash::MessageDigest; -use nid::X9_62_PRIME256V1; -use pkey::PKey; -use rsa::Rsa; -use stack::Stack; -use x509::{X509, X509Generator, X509Name, X509Req}; -use x509::extension::{Extension, BasicConstraints, KeyUsage, ExtendedKeyUsage, - SubjectKeyIdentifier, AuthorityKeyIdentifier, SubjectAlternativeName}; -use ssl::{SslMethod, SslContextBuilder}; -use x509::extension::AltNameOption as SAN; -use x509::extension::KeyUsageOption::{DigitalSignature, KeyEncipherment}; -use x509::extension::ExtKeyUsageOption::{self, ClientAuth, ServerAuth}; -use nid; - -fn get_generator() -> X509Generator { - X509Generator::new() - .set_valid_period(365 * 2) - .add_name("CN".to_string(), "test_me".to_string()) - .set_sign_hash(MessageDigest::sha1()) - .add_extension(Extension::KeyUsage(vec![DigitalSignature, KeyEncipherment])) - .add_extension(Extension::ExtKeyUsage(vec![ - ClientAuth, - ServerAuth, - ExtKeyUsageOption::Other("2.999.1".to_owned()), - ])) - .add_extension(Extension::SubjectAltName( - vec![(SAN::DNS, "example.com".to_owned())], - )) - .add_extension(Extension::OtherNid( - nid::BASIC_CONSTRAINTS, - "critical,CA:TRUE".to_owned(), - )) - .add_extension(Extension::OtherStr( - "2.999.2".to_owned(), - "ASN1:UTF8:example value".to_owned(), - )) -} - -fn pkey() -> PKey { - let rsa = Rsa::generate(2048).unwrap(); - PKey::from_rsa(rsa).unwrap() -} - -#[test] -fn test_cert_gen() { - let pkey = pkey(); - let cert = get_generator().sign(&pkey).unwrap(); - - // FIXME: check data in result to be correct, needs implementation - // of X509 getters - - assert_eq!( - pkey.public_key_to_pem().unwrap(), - cert.public_key().unwrap().public_key_to_pem().unwrap() - ); -} - -/// SubjectKeyIdentifier must be added before AuthorityKeyIdentifier or OpenSSL -/// is "unable to get issuer keyid." This test ensures the order of insertion -/// for extensions is preserved when the cert is signed. -#[test] -fn test_cert_gen_extension_ordering() { - let pkey = pkey(); - get_generator() - .add_extension(Extension::OtherNid( - nid::SUBJECT_KEY_IDENTIFIER, - "hash".to_owned(), - )) - .add_extension(Extension::OtherNid( - nid::AUTHORITY_KEY_IDENTIFIER, - "keyid:always".to_owned(), - )) - .sign(&pkey) - .expect("Failed to generate cert with order-dependent extensions"); -} - -/// Proves that a passing result from `test_cert_gen_extension_ordering` is -/// deterministic by reversing the order of extensions and asserting failure. -#[test] -fn test_cert_gen_extension_bad_ordering() { - let pkey = pkey(); - let result = get_generator() - .add_extension(Extension::OtherNid( - nid::AUTHORITY_KEY_IDENTIFIER, - "keyid:always".to_owned(), - )) - .add_extension(Extension::OtherNid( - nid::SUBJECT_KEY_IDENTIFIER, - "hash".to_owned(), - )) - .sign(&pkey); - - assert!(result.is_err()); -} - -#[test] -fn test_req_gen() { - let pkey = pkey(); - - let req = get_generator().request(&pkey).unwrap(); - let reqpem = req.to_pem().unwrap(); - - let req = X509Req::from_pem(&reqpem).ok().expect("Failed to load PEM"); - let cn = (*req) - .subject_name() - .entries_by_nid(nid::COMMONNAME) - .next() - .unwrap(); - assert_eq!(0, (*req).version()); - assert_eq!(cn.data().as_slice(), b"test_me"); - - // FIXME: check data in result to be correct, needs implementation - // of X509_REQ getters -} - -#[test] -fn test_cert_loading() { - let cert = include_bytes!("../../test/cert.pem"); - let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); - let fingerprint = cert.fingerprint(MessageDigest::sha1()).unwrap(); - - let hash_str = "59172d9313e84459bcff27f967e79e6e9217e584"; - let hash_vec = Vec::from_hex(hash_str).unwrap(); - - assert_eq!(fingerprint, hash_vec); -} - -#[test] -fn test_cert_issue_validity() { - let cert = include_bytes!("../../test/cert.pem"); - let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); - let not_before = cert.not_before().to_string(); - let not_after = cert.not_after().to_string(); - - assert_eq!(not_before, "Aug 14 17:00:03 2016 GMT"); - assert_eq!(not_after, "Aug 12 17:00:03 2026 GMT"); -} - -#[test] -fn test_save_der() { - let cert = include_bytes!("../../test/cert.pem"); - let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); - - let der = cert.to_der().unwrap(); - assert!(!der.is_empty()); -} - -#[test] -fn test_subject_read_cn() { - let cert = include_bytes!("../../test/cert.pem"); - let cert = X509::from_pem(cert).unwrap(); - let subject = cert.subject_name(); - let cn = subject.entries_by_nid(nid::COMMONNAME).next().unwrap(); - assert_eq!(cn.data().as_slice(), b"foobar.com") -} - -#[test] -fn test_nid_values() { - let cert = include_bytes!("../../test/nid_test_cert.pem"); - let cert = X509::from_pem(cert).unwrap(); - let subject = cert.subject_name(); - - let cn = subject.entries_by_nid(nid::COMMONNAME).next().unwrap(); - assert_eq!(cn.data().as_slice(), b"example.com"); - - let email = subject - .entries_by_nid(nid::PKCS9_EMAILADDRESS) - .next() - .unwrap(); - assert_eq!(email.data().as_slice(), b"test@example.com"); - - let friendly = subject.entries_by_nid(nid::FRIENDLYNAME).next().unwrap(); - assert_eq!(&**friendly.data().as_utf8().unwrap(), "Example"); -} - -#[test] -fn test_nid_uid_value() { - let cert = include_bytes!("../../test/nid_uid_test_cert.pem"); - let cert = X509::from_pem(cert).unwrap(); - let subject = cert.subject_name(); - - let cn = subject.entries_by_nid(nid::USERID).next().unwrap(); - assert_eq!(cn.data().as_slice(), b"this is the userId"); -} - -#[test] -fn test_subject_alt_name() { - let cert = include_bytes!("../../test/alt_name_cert.pem"); - let cert = X509::from_pem(cert).unwrap(); - - let subject_alt_names = cert.subject_alt_names().unwrap(); - assert_eq!(3, subject_alt_names.len()); - assert_eq!(Some("foobar.com"), subject_alt_names[0].dnsname()); - assert_eq!(subject_alt_names[1].ipaddress(), Some(&[127, 0, 0, 1][..])); - assert_eq!( - subject_alt_names[2].ipaddress(), - Some(&b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01"[..]) - ); -} - -#[test] -fn test_subject_alt_name_iter() { - let cert = include_bytes!("../../test/alt_name_cert.pem"); - let cert = X509::from_pem(cert).ok().expect("Failed to load PEM"); - - let subject_alt_names = cert.subject_alt_names().unwrap(); - let mut subject_alt_names_iter = subject_alt_names.iter(); - assert_eq!( - subject_alt_names_iter.next().unwrap().dnsname(), - Some("foobar.com") - ); - assert_eq!( - subject_alt_names_iter.next().unwrap().ipaddress(), - Some(&[127, 0, 0, 1][..]) - ); - assert_eq!( - subject_alt_names_iter.next().unwrap().ipaddress(), - Some(&b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01"[..]) - ); - assert!(subject_alt_names_iter.next().is_none()); -} - -#[test] -fn x509_builder() { - let pkey = pkey(); - - let mut name = X509Name::builder().unwrap(); - name.append_entry_by_nid(nid::COMMONNAME, "foobar.com") - .unwrap(); - let name = name.build(); - - let mut builder = X509::builder().unwrap(); - builder.set_version(2).unwrap(); - builder.set_subject_name(&name).unwrap(); - builder.set_issuer_name(&name).unwrap(); - builder - .set_not_before(&Asn1Time::days_from_now(0).unwrap()) - .unwrap(); - builder - .set_not_after(&Asn1Time::days_from_now(365).unwrap()) - .unwrap(); - builder.set_pubkey(&pkey).unwrap(); - - let mut serial = BigNum::new().unwrap(); - serial.rand(128, MSB_MAYBE_ZERO, false).unwrap(); - builder - .set_serial_number(&serial.to_asn1_integer().unwrap()) - .unwrap(); - - let basic_constraints = BasicConstraints::new().critical().ca().build().unwrap(); - builder.append_extension(basic_constraints).unwrap(); - let key_usage = KeyUsage::new() - .digital_signature() - .key_encipherment() - .build() - .unwrap(); - builder.append_extension(key_usage).unwrap(); - let ext_key_usage = ExtendedKeyUsage::new() - .client_auth() - .server_auth() - .other("2.999.1") - .build() - .unwrap(); - builder.append_extension(ext_key_usage).unwrap(); - let subject_key_identifier = SubjectKeyIdentifier::new() - .build(&builder.x509v3_context(None, None)) - .unwrap(); - builder.append_extension(subject_key_identifier).unwrap(); - let authority_key_identifier = AuthorityKeyIdentifier::new() - .keyid(true) - .build(&builder.x509v3_context(None, None)) - .unwrap(); - builder.append_extension(authority_key_identifier).unwrap(); - let subject_alternative_name = SubjectAlternativeName::new() - .dns("example.com") - .build(&builder.x509v3_context(None, None)) - .unwrap(); - builder.append_extension(subject_alternative_name).unwrap(); - - builder.sign(&pkey, MessageDigest::sha256()).unwrap(); - - let x509 = builder.build(); - - assert!(pkey.public_eq(&x509.public_key().unwrap())); - - let cn = x509.subject_name() - .entries_by_nid(nid::COMMONNAME) - .next() - .unwrap(); - assert_eq!("foobar.com".as_bytes(), cn.data().as_slice()); -} - -#[test] -fn x509_req_builder() { - let pkey = pkey(); - - let mut name = X509Name::builder().unwrap(); - name.append_entry_by_nid(nid::COMMONNAME, "foobar.com") - .unwrap(); - let name = name.build(); - - let mut builder = X509Req::builder().unwrap(); - builder.set_version(2).unwrap(); - builder.set_subject_name(&name).unwrap(); - builder.set_pubkey(&pkey).unwrap(); - - let mut extensions = Stack::new().unwrap(); - let key_usage = KeyUsage::new() - .digital_signature() - .key_encipherment() - .build() - .unwrap(); - extensions.push(key_usage).unwrap(); - let subject_alternative_name = SubjectAlternativeName::new() - .dns("example.com") - .build(&builder.x509v3_context(None)) - .unwrap(); - extensions.push(subject_alternative_name).unwrap(); - builder.add_extensions(&extensions).unwrap(); - - builder.sign(&pkey, MessageDigest::sha256()).unwrap(); -} - -#[test] -fn test_stack_from_pem() { - let certs = include_bytes!("../../test/certs.pem"); - let certs = X509::stack_from_pem(certs).unwrap(); - - assert_eq!(certs.len(), 2); - assert_eq!( - certs[0] - .fingerprint(MessageDigest::sha1()) - .unwrap() - .to_hex(), - "59172d9313e84459bcff27f967e79e6e9217e584" - ); - assert_eq!( - certs[1] - .fingerprint(MessageDigest::sha1()) - .unwrap() - .to_hex(), - "c0cbdf7cdd03c9773e5468e1f6d2da7d5cbb1875" - ); -} - -#[test] -fn issued() { - let cert = include_bytes!("../../test/cert.pem"); - let cert = X509::from_pem(cert).unwrap(); - let ca = include_bytes!("../../test/root-ca.pem"); - let ca = X509::from_pem(ca).unwrap(); - - ca.issued(&cert).unwrap(); - cert.issued(&cert).err().unwrap(); -} - -#[test] -fn ecdsa_cert() { - let mut group = EcGroup::from_curve_name(X9_62_PRIME256V1).unwrap(); - group.set_asn1_flag(NAMED_CURVE); - let key = EcKey::generate(&group).unwrap(); - let key = PKey::from_ec_key(key).unwrap(); - - let cert = X509Generator::new() - .set_valid_period(365) - .add_name("CN".to_owned(), "TestServer".to_owned()) - .set_sign_hash(MessageDigest::sha256()) - .sign(&key) - .unwrap(); - - let mut ctx = SslContextBuilder::new(SslMethod::tls()).unwrap(); - ctx.set_certificate(&cert).unwrap(); - ctx.set_private_key(&key).unwrap(); - ctx.check_private_key().unwrap(); -} - -#[test] -fn signature() { - let cert = include_bytes!("../../test/cert.pem"); - let cert = X509::from_pem(cert).unwrap(); - let signature = cert.signature(); - assert_eq!( - signature.as_slice().to_hex(), - "4af607b889790b43470442cfa551cdb8b6d0b0340d2958f76b9e3ef6ad4992230cead6842587f0ecad5\ - 78e6e11a221521e940187e3d6652de14e84e82f6671f097cc47932e022add3c0cb54a26bf27fa84c107\ - 4971caa6bee2e42d34a5b066c427f2d452038082b8073993399548088429de034fdd589dcfb0dd33be7\ - ebdfdf698a28d628a89568881d658151276bde333600969502c4e62e1d3470a683364dfb241f78d310a\ - 89c119297df093eb36b7fd7540224f488806780305d1e79ffc938fe2275441726522ab36d88348e6c51\ - f13dcc46b5e1cdac23c974fd5ef86aa41e91c9311655090a52333bc79687c748d833595d4c5f987508f\ - e121997410d37c" - ); - let algorithm = cert.signature_algorithm(); - assert_eq!(algorithm.object().nid(), nid::SHA256WITHRSAENCRYPTION); - assert_eq!(algorithm.object().to_string(), "sha256WithRSAEncryption"); -} - -#[test] -fn clone_x509() { - let cert = include_bytes!("../../test/cert.pem"); - let cert = X509::from_pem(cert).unwrap(); - cert.clone(); -} diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/src/x509/verify.rs cargo-0.26.0/vendor/openssl-0.9.24/src/x509/verify.rs --- cargo-0.25.0/vendor/openssl-0.9.24/src/x509/verify.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/src/x509/verify.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -//! X509 certificate verification -//! -//! Requires the `v102` or `v110` features and OpenSSL 1.0.2 or 1.1.0. - -pub use verify::*; diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/alt_name_cert.pem cargo-0.26.0/vendor/openssl-0.9.24/test/alt_name_cert.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/alt_name_cert.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/alt_name_cert.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIEOjCCAyKgAwIBAgIJAJz42fzGUJGeMA0GCSqGSIb3DQEBCwUAMH8xCzAJBgNV -BAYTAlVTMQswCQYDVQQIDAJOWTERMA8GA1UEBwwITmV3IFlvcmsxFTATBgNVBAoM -DEV4YW1wbGUsIExMQzEYMBYGA1UEAwwPRXhhbXBsZSBDb21wYW55MR8wHQYJKoZI -hvcNAQkBFhB0ZXN0QGV4YW1wbGUuY29tMB4XDTE2MDQzMDA0MDg1NloXDTE3MDQz -MDA0MDg1NlowfzELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAk5ZMREwDwYDVQQHDAhO -ZXcgWW9yazEVMBMGA1UECgwMRXhhbXBsZSwgTExDMRgwFgYDVQQDDA9FeGFtcGxl -IENvbXBhbnkxHzAdBgkqhkiG9w0BCQEWEHRlc3RAZXhhbXBsZS5jb20wggEiMA0G -CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDggl2TbtO5Ewi/q8kV56xK6HBpwsj9 -wBoqGi6hkKm/8lhLTkuUG6WbEUepi7n9d7tjI9hwYN7MKtppAnS+d+Zh6sKMgLJn -hONkbQBJkYWwuIxRVXORCdyZDNzXP1rlb6ynmj6mItuPTRVNNMaZP+24fgXtwGk8 -P2nqA1ONbmyaP27txV+Rd8fmQvW3vSmq7iDob661TOtLZRqqVRpnLDGpLXTCptYz -dLN1nDWKjBUFpPGDxvfcSE3Yf9LaQM2uDHRygSgTFusbwarAGrAk8krsm/Tiaumx -Ls74MY6OEoLnPbEi5epWLqPmoE1nxrvYLtaWh3TTET3H72yL0+1PZTkpAgMBAAGj -gbgwgbUwHQYDVR0OBBYEFAIcHhTPUqVdK85u47vo8z0viJGPMB8GA1UdIwQYMBaA -FAIcHhTPUqVdK85u47vo8z0viJGPMAkGA1UdEwQCMAAwCwYDVR0PBAQDAgWgMC0G -A1UdEQQmMCSCCmZvb2Jhci5jb22HBH8AAAGHEAAAAAAAAAAAAAAAAAAAAAEwLAYJ -YIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMA0GCSqG -SIb3DQEBCwUAA4IBAQDeYsuJaxbnxR2wDRSbxMpPp2b6fHPxC1vArKTSrQ/X+5s7 -YcQ29jkzD8FbET8iPsCOn/IECBiDKOpckkO6dBWM05ma9HHzWjQOJ7Lo6gEsvk4d -+M/jJz5IaJ7hOxp1hGqwNQ+PJQOZMmlruNcOzPU36qaWJ03+NYOKar5VpIrRxCNc -uehTArmJqDLQPfgETEhMYfpkqf3s/cGb1uyeCpzgIRPpf4Ki1Oys5cV/BqIn7n5g -7sUrhXboYL4+eYt5V4rcc4rLI5J5IP/a1Z+Z6UVH+Mbiyl0iD8aRr/bo9WvKih3C -2LBO0Apl0tkXUOMWp7G0UYHVEndwPjZnVoM42f11 ------END CERTIFICATE----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/cert.pem cargo-0.26.0/vendor/openssl-0.9.24/test/cert.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/cert.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/cert.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDGzCCAgMCCQCHcfe97pgvpTANBgkqhkiG9w0BAQsFADBFMQswCQYDVQQGEwJB -VTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0 -cyBQdHkgTHRkMB4XDTE2MDgxNDE3MDAwM1oXDTI2MDgxMjE3MDAwM1owWjELMAkG -A1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0 -IFdpZGdpdHMgUHR5IEx0ZDETMBEGA1UEAwwKZm9vYmFyLmNvbTCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAKj0JYxEsxejUIX+I5GH0Hg2G0kX/y1H0+Ub -3mw2/Ja5BD/yN96/7zMSumXF8uS3SkmpyiJkbyD01TSRTqjlP7/VCBlyUIChlpLQ -mrGaijZiT/VCyPXqmcwFzXS5IOTpX1olJfW8rA41U1LCIcDUyFf6LtZ/v8rSeKr6 -TuE6SGV4WRaBm1SrjWBeHVV866CRrtSS1ieT2asFsAyOZqWhk2fakwwBDFWDhOGI -ubfO+5aq9cBJbNRlzsgB3UZs3gC0O6GzbnZ6oT0TiJMeTsXXjABLUlaq/rrqFF4Y -euZkkbHTFBMz288PUc3m3ZTcpN+E7+ZOUBRZXKD20K07NugqCzUCAwEAATANBgkq -hkiG9w0BAQsFAAOCAQEASvYHuIl5C0NHBELPpVHNuLbQsDQNKVj3a54+9q1JkiMM -6taEJYfw7K1Xjm4RoiFSHpQBh+PWZS3hToToL2Zx8JfMR5MuAirdPAy1Sia/J/qE -wQdJccqmvuLkLTSlsGbEJ/LUUgOAgrgHOZM5lUgIhCneA0/dWJ3PsN0zvn69/faY -oo1iiolWiIHWWBUSdr3jM2AJaVAsTmLh00cKaDNk37JB940xConBGSl98JPrNrf9 -dUAiT0iIBngDBdHnn/yTj+InVEFyZSKrNtiDSObFHxPcxGteHNrCPJdP1e+GqkHp -HJMRZVCQpSMzvHlofHSNgzWV1MX5h1CP4SGZdBDTfA== ------END CERTIFICATE----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/certs.pem cargo-0.26.0/vendor/openssl-0.9.24/test/certs.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/certs.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/certs.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDGzCCAgMCCQCHcfe97pgvpTANBgkqhkiG9w0BAQsFADBFMQswCQYDVQQGEwJB -VTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0 -cyBQdHkgTHRkMB4XDTE2MDgxNDE3MDAwM1oXDTI2MDgxMjE3MDAwM1owWjELMAkG -A1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0 -IFdpZGdpdHMgUHR5IEx0ZDETMBEGA1UEAwwKZm9vYmFyLmNvbTCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAKj0JYxEsxejUIX+I5GH0Hg2G0kX/y1H0+Ub -3mw2/Ja5BD/yN96/7zMSumXF8uS3SkmpyiJkbyD01TSRTqjlP7/VCBlyUIChlpLQ -mrGaijZiT/VCyPXqmcwFzXS5IOTpX1olJfW8rA41U1LCIcDUyFf6LtZ/v8rSeKr6 -TuE6SGV4WRaBm1SrjWBeHVV866CRrtSS1ieT2asFsAyOZqWhk2fakwwBDFWDhOGI -ubfO+5aq9cBJbNRlzsgB3UZs3gC0O6GzbnZ6oT0TiJMeTsXXjABLUlaq/rrqFF4Y -euZkkbHTFBMz288PUc3m3ZTcpN+E7+ZOUBRZXKD20K07NugqCzUCAwEAATANBgkq -hkiG9w0BAQsFAAOCAQEASvYHuIl5C0NHBELPpVHNuLbQsDQNKVj3a54+9q1JkiMM -6taEJYfw7K1Xjm4RoiFSHpQBh+PWZS3hToToL2Zx8JfMR5MuAirdPAy1Sia/J/qE -wQdJccqmvuLkLTSlsGbEJ/LUUgOAgrgHOZM5lUgIhCneA0/dWJ3PsN0zvn69/faY -oo1iiolWiIHWWBUSdr3jM2AJaVAsTmLh00cKaDNk37JB940xConBGSl98JPrNrf9 -dUAiT0iIBngDBdHnn/yTj+InVEFyZSKrNtiDSObFHxPcxGteHNrCPJdP1e+GqkHp -HJMRZVCQpSMzvHlofHSNgzWV1MX5h1CP4SGZdBDTfA== ------END CERTIFICATE----- ------BEGIN CERTIFICATE----- -MIIDXTCCAkWgAwIBAgIJAOIvDiVb18eVMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV -BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX -aWRnaXRzIFB0eSBMdGQwHhcNMTYwODE0MTY1NjExWhcNMjYwODEyMTY1NjExWjBF -MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 -ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB -CgKCAQEArVHWFn52Lbl1l59exduZntVSZyDYpzDND+S2LUcO6fRBWhV/1Kzox+2G -ZptbuMGmfI3iAnb0CFT4uC3kBkQQlXonGATSVyaFTFR+jq/lc0SP+9Bd7SBXieIV -eIXlY1TvlwIvj3Ntw9zX+scTA4SXxH6M0rKv9gTOub2vCMSHeF16X8DQr4XsZuQr -7Cp7j1I4aqOJyap5JTl5ijmG8cnu0n+8UcRlBzy99dLWJG0AfI3VRJdWpGTNVZ92 -aFff3RpK3F/WI2gp3qV1ynRAKuvmncGC3LDvYfcc2dgsc1N6Ffq8GIrkgRob6eBc -klDHp1d023Lwre+VaVDSo1//Y72UFwIDAQABo1AwTjAdBgNVHQ4EFgQUbNOlA6sN -XyzJjYqciKeId7g3/ZowHwYDVR0jBBgwFoAUbNOlA6sNXyzJjYqciKeId7g3/Zow -DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAVVaR5QWLZIRR4Dw6TSBn -BQiLpBSXN6oAxdDw6n4PtwW6CzydaA+creiK6LfwEsiifUfQe9f+T+TBSpdIYtMv -Z2H2tjlFX8VrjUFvPrvn5c28CuLI0foBgY8XGSkR2YMYzWw2jPEq3Th/KM5Catn3 -AFm3bGKWMtGPR4v+90chEN0jzaAmJYRrVUh9vea27bOCn31Nse6XXQPmSI6Gyncy -OAPUsvPClF3IjeL1tmBotWqSGn1cYxLo+Lwjk22A9h6vjcNQRyZF2VLVvtwYrNU3 -mwJ6GCLsLHpwW/yjyvn8iEltnJvByM/eeRnfXV6WDObyiZsE/n6DxIRJodQzFqy9 -GA== ------END CERTIFICATE----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/dhparams.pem cargo-0.26.0/vendor/openssl-0.9.24/test/dhparams.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/dhparams.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/dhparams.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ ------BEGIN DH PARAMETERS----- -MIIBCAKCAQEAh3Betv+hf5jNsOmGXU8oxuABD2B8r0yU8FVgjnCZBSVo61qJ0A2d -J6r8rYKbjtolnrZN/V4IPSzYvxurHbu8nbiFVyhOySPchI2Fu+YT/HsSe/0MH9bW -gJTNzmutWoy9VxtWLCmXnOSZHep3MZ1ZNimno6Kh2qQ7VJr0+KF8GbxUKOPv4SqK -NBwouIQXFc0pE9kGhcGKbr7TnHhyJFCRLNP1OVDQZbcoKjk1Vh+5sy7vM2VUTQmM -yOToT2LEZVAUJXNumcYMki9MIwfYCwYZbNt0ZEolyHzUEesuyHfU1eJd6+sKEjUz -5GteQIR7AehxZIS+cytu7BXO7B0owLJ2awIBAg== ------END DH PARAMETERS----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/dsa-encrypted.pem cargo-0.26.0/vendor/openssl-0.9.24/test/dsa-encrypted.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/dsa-encrypted.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/dsa-encrypted.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ ------BEGIN DSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: DES-EDE3-CBC,5B99FC62C376CA1F - -5nN039tLa3AHnSaQ0lk+Zsguu1EE+EyUlW1GHKs7ls2gOsZH1kR0+A+MiwNKlP24 -Syy8KYyAbgsirhtwN5IOSsA97feR/vHTY4xQ8nEef8tB7VeRJzOFLHGgS0hwIxOM -Tb8gb4y0FtoWdAgorieP4c1emu8VwTTkHd44AArDXsP1Y7s+a3IEMcHcc3tW+qBk -xuVnqBEETL1t0I5rKy+AYvPmGgEZ0dGRRnUlVMC5jMTozJFcStdSzKUY27prUBz2 -FREOJOA/dIjVn1UGijI64Io5sPCAbDPPmG2k4kywbEbd7Ee/MxEvRNcAyv4boyA8 -GnHZTILKi/WY5+SNlHE3YepCFo1XU+59SovB1lDhRmi43L4vfdGc/6y8L/+rbLuU -Y58DxLdOZLTjpf9GLLf9WcpHhNZhwFfBFA8HuT8FtKDPqlf2t65z+1AVV8JTH2wM -BrRHXTrBKn8YgafXD5MisKFmajoAtNZTvhYGm0D8BLIiNwOwLsGfXZ0hYAie0eoI -Xl6MbHp1n/e+R+XKJ3M9DPM8mzWntlltAhS5+Az0Zi4aBdzqQaTpqvEku21sygq8 -Hwm0fpAq7y4bMnjNbMqQVw== ------END DSA PRIVATE KEY----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/dsaparam.pem cargo-0.26.0/vendor/openssl-0.9.24/test/dsaparam.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/dsaparam.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/dsaparam.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ ------BEGIN DSA PARAMETERS----- -MIIBHgKBgQCkKe/jtYKJNQafaE7kg2aaJOEPUV0Doi451jkXHp5UfLh6+t42eabS -GkE9WBAlILgaB8yHckLe9+zozN39+SUDp94kb2r38/8w/9Ffhbsep9uiyOj2ZRQu -r6SkpKQDKcnAd6IMZXZcvdSgPC90A6qraYUZKq7Csjn63gbC+IvXHwIVAIgSPE43 -lXD8/rGYxos4cxCgGGAxAoGASMV56WhLvVQtWMVI36WSIxbZnC2EsnNIKeVWyXnP -/OmPJ2mdezG7i1alcwsO2TnSLbvjvGPlyzIqZzHvWC8EmDqsfbU+n8we/Ealsm5n -loC8m9ECWpbTzbNdvrAAj9UPVWjcDwg7grAGGysh6lGbBv5P+4zL/niq1UiELnKc -ifg= ------END DSA PARAMETERS----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/dsa.pem cargo-0.26.0/vendor/openssl-0.9.24/test/dsa.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/dsa.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/dsa.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ ------BEGIN DSA PRIVATE KEY----- -MIIBuwIBAAKBgQCkKe/jtYKJNQafaE7kg2aaJOEPUV0Doi451jkXHp5UfLh6+t42 -eabSGkE9WBAlILgaB8yHckLe9+zozN39+SUDp94kb2r38/8w/9Ffhbsep9uiyOj2 -ZRQur6SkpKQDKcnAd6IMZXZcvdSgPC90A6qraYUZKq7Csjn63gbC+IvXHwIVAIgS -PE43lXD8/rGYxos4cxCgGGAxAoGASMV56WhLvVQtWMVI36WSIxbZnC2EsnNIKeVW -yXnP/OmPJ2mdezG7i1alcwsO2TnSLbvjvGPlyzIqZzHvWC8EmDqsfbU+n8we/Eal -sm5nloC8m9ECWpbTzbNdvrAAj9UPVWjcDwg7grAGGysh6lGbBv5P+4zL/niq1UiE -LnKcifgCgYEAo6mAasO0+MVcu8shxxUXXNeTLsZ8NB/BIx9EZ/dzE23ivNW8dq1A -eecAAYhssI2m/CspQvyKw+seCvg4FccxJgB3+mGOe+blFHwO3eAwoyRn/t3DZDHh -FjxKKRsQdy4BkZv+vhTyIYYCw0iPZ5Wfln+pyGGTveIDED1MPG+J6c8CFCJAUlEl -4nHvbC15xLXXpd46zycY ------END DSA PRIVATE KEY----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/dsa.pem.pub cargo-0.26.0/vendor/openssl-0.9.24/test/dsa.pem.pub --- cargo-0.25.0/vendor/openssl-0.9.24/test/dsa.pem.pub 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/dsa.pem.pub 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIIBtzCCASsGByqGSM44BAEwggEeAoGBAKQp7+O1gok1Bp9oTuSDZpok4Q9RXQOi -LjnWORcenlR8uHr63jZ5ptIaQT1YECUguBoHzIdyQt737OjM3f35JQOn3iRvavfz -/zD/0V+Fux6n26LI6PZlFC6vpKSkpAMpycB3ogxldly91KA8L3QDqqtphRkqrsKy -OfreBsL4i9cfAhUAiBI8TjeVcPz+sZjGizhzEKAYYDECgYBIxXnpaEu9VC1YxUjf -pZIjFtmcLYSyc0gp5VbJec/86Y8naZ17MbuLVqVzCw7ZOdItu+O8Y+XLMipnMe9Y -LwSYOqx9tT6fzB78RqWybmeWgLyb0QJaltPNs12+sACP1Q9VaNwPCDuCsAYbKyHq -UZsG/k/7jMv+eKrVSIQucpyJ+AOBhQACgYEAo6mAasO0+MVcu8shxxUXXNeTLsZ8 -NB/BIx9EZ/dzE23ivNW8dq1AeecAAYhssI2m/CspQvyKw+seCvg4FccxJgB3+mGO -e+blFHwO3eAwoyRn/t3DZDHhFjxKKRsQdy4BkZv+vhTyIYYCw0iPZ5Wfln+pyGGT -veIDED1MPG+J6c8= ------END PUBLIC KEY----- Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/openssl-0.9.24/test/identity.p12 and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/openssl-0.9.24/test/identity.p12 differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/openssl-0.9.24/test/key.der and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/openssl-0.9.24/test/key.der differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/openssl-0.9.24/test/key.der.pub and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/openssl-0.9.24/test/key.der.pub differ diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/key.pem cargo-0.26.0/vendor/openssl-0.9.24/test/key.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/key.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/key.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCo9CWMRLMXo1CF -/iORh9B4NhtJF/8tR9PlG95sNvyWuQQ/8jfev+8zErplxfLkt0pJqcoiZG8g9NU0 -kU6o5T+/1QgZclCAoZaS0Jqxmoo2Yk/1Qsj16pnMBc10uSDk6V9aJSX1vKwONVNS -wiHA1MhX+i7Wf7/K0niq+k7hOkhleFkWgZtUq41gXh1VfOugka7UktYnk9mrBbAM -jmaloZNn2pMMAQxVg4ThiLm3zvuWqvXASWzUZc7IAd1GbN4AtDuhs252eqE9E4iT -Hk7F14wAS1JWqv666hReGHrmZJGx0xQTM9vPD1HN5t2U3KTfhO/mTlAUWVyg9tCt -OzboKgs1AgMBAAECggEBAKLj6IOJBKXolczpzb8UkyAjAkGBektcseV07gelJ/fk -3z0LuWPv5p12E/HlXB24vU2x/ikUbbP3eMsawRzDEahQqmNmPEkYAYUAy/Qpi9GN -DYvn3LqDec4jVgeQKS+p9H2DzUpTogp8zR2//yzbuWBg2+F//xh7vU0S0RQCziPM -x7RSBgbhxSfChfEJbS2sDnzfh0jRQmoY95iFv7puet1FJtzdZ4fgCd1RqmC2lFM5 -H0eZtN/Cz19lieVs0b996DErdEBqClVZO00eYbRozCDaBzRU3ybB/dMrGJxhkkXm -wb3kWMtziH9qOYsostuHIFu8eKFLloKxFnq2R4DGxOECgYEA2KUIZISOeGJSBcLJ -JAUK2gvgXPNo4HHWIwOA9xeN3ZJlsnPlffXQNnm6t1st1V2gfMm9I2n0m/F0y2B/ -n/XGSa8bghfPA9l0c2h58lkL3JQJR/paa8ycTz+YZPrznEyN7Qa0RrJXUvZv9lQL -Hc3+FHcSHgMqDV2f2bHAEu9YGi0CgYEAx6VEIPNvrHFgjo/jk1RTuk+m0xEWQsZL -Cs+izQMr2TaeJn8LG+93AvFuYn0J0nT3WuStLPrUg8i4IhSS6lf1tId5ivIZPm4r -YwMyblBJXhnHbk7Uqodjfw/3s6V2HAu++B7hTdyVr9DFuST9uv4m8bkPV8rfX1jE -I2rAPVWvgikCgYB+wNAQP547wQrMZBLbCDg5KwmyWJfb+b6X7czexOEz6humNTjo -YZHYzY/5B1fhpk3ntQD8X1nGg5caBvOk21+QbOtjShrM3cXMYCw5JvBRtitX+Zo9 -yBEMLOE0877ki8XeEDYZxu5gk98d+D4oygUGZEQtWxyXhVepPt5qNa8OYQKBgQDH -RVgZI6KFlqzv3wMh3PutbS9wYQ+9GrtwUQuIYe/0YSW9+vSVr5E0qNKrD28sV39F -hBauXLady0yvB6YUrjMbPFW+sCMuQzyfGWPO4+g3OrfqjFiM1ZIkE0YEU9Tt7XNx -qTDtTI1D7bhNMnTnniI1B6ge0und+3XafAThs5L48QKBgQCTTpfqMt8kU3tcI9sf -0MK03y7kA76d5uw0pZbWFy7KI4qnzWutCzb+FMPWWsoFtLJLPZy//u/ZCUVFVa4d -0Y/ASNQIESVPXFLAltlLo4MSmsg1vCBsbviEEaPeEjvMrgki93pYtd/aOSgkYC1T -mEq154s5rmqh+h+XRIf7Au0SLw== ------END PRIVATE KEY----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/key.pem.pub cargo-0.26.0/vendor/openssl-0.9.24/test/key.pem.pub --- cargo-0.25.0/vendor/openssl-0.9.24/test/key.pem.pub 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/key.pem.pub 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr1bXMptaIgOL9PVL8a7W -KG/C8+IbxP018eMBQZT0SnPQmXp0Q8Aai/F+AEDE7b5sO5U7WdxU4GRYw0wqkQNF -si78KNfoj2ZMlx6NRfl4UKuzrpGTPgQxuKDYedngPpWcbmW4P3zEL2Y7b18n9NJr -atRUzH1Zh/ReRO525Xadu58aviPw1Mzgse7cKyzb03Gll9noLnYNIIpO8jL+QyrD -8qNmfacmR20U0a6XDTtmsmk7AitGETICbTT0KRf+oAP0yIHoonllPpNLUEPZQjrp -ClS/S/wKdj7gaq9TaMbHULhFMjbCV8cuPu//rUAuWp3riaznZGOVQyn3Dp2CB3ad -yQIDAQAB ------END PUBLIC KEY----- Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/openssl-0.9.24/test/keystore-empty-chain.p12 and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/openssl-0.9.24/test/keystore-empty-chain.p12 differ diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/nid_test_cert.pem cargo-0.26.0/vendor/openssl-0.9.24/test/nid_test_cert.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/nid_test_cert.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/nid_test_cert.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIB1DCCAX6gAwIBAgIJAMzXWZGWHleWMA0GCSqGSIb3DQEBCwUAMFYxHzAdBgkq -hkiG9w0BCQEWEHRlc3RAZXhhbXBsZS5jb20xFDASBgNVBAMMC2V4YW1wbGUuY29t -MR0wGwYJKoZIhvcNAQkUHg4ARQB4AGEAbQBwAGwAZTAeFw0xNTA3MDEwNjQ3NDRa -Fw0xNTA3MzEwNjQ3NDRaMFYxHzAdBgkqhkiG9w0BCQEWEHRlc3RAZXhhbXBsZS5j -b20xFDASBgNVBAMMC2V4YW1wbGUuY29tMR0wGwYJKoZIhvcNAQkUHg4ARQB4AGEA -bQBwAGwAZTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCmejzp4+o35FD0hAnx2trL -08h07X5jZca9DgZH35hWXPh7fMucLt/IPXIRnz2zKEa/Mo6D2V/fx03Mqo0epid7 -AgMBAAGjLzAtMB0GA1UdDgQWBBRQa57tXz3rZNRz+fTbo3w3jQJMBTAMBgNVHRME -BTADAQH/MA0GCSqGSIb3DQEBCwUAA0EAm0iY9cr+gvC+vcQIebdofpQ4GcDW8U6W -Bxs8ZXinLl69P0jYLum3+XITNFRiyQqcivaxdxthxDNOX7P+aKwkJA== ------END CERTIFICATE----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/nid_uid_test_cert.pem cargo-0.26.0/vendor/openssl-0.9.24/test/nid_uid_test_cert.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/nid_uid_test_cert.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/nid_uid_test_cert.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIEGTCCAwGgAwIBAgIJAItKTzcGfL1lMA0GCSqGSIb3DQEBCwUAMIGiMSIwIAYK -CZImiZPyLGQBAQwSdGhpcyBpcyB0aGUgdXNlcklkMQswCQYDVQQGEwJVUzETMBEG -A1UECAwKQ2FsaWZvcm5pYTESMBAGA1UEBwwJU3Vubnl2YWxlMRUwEwYDVQQKDAxS -dXN0IE9wZW5TU0wxDDAKBgNVBAsMA09TUzEhMB8GA1UEAwwYcnVzdC1vcGVuc3Ns -LmV4YW1wbGUuY29tMB4XDTE2MDIwMjE3MjIwMVoXDTE2MDMwMzE3MjIwMVowgaIx -IjAgBgoJkiaJk/IsZAEBDBJ0aGlzIGlzIHRoZSB1c2VySWQxCzAJBgNVBAYTAlVT -MRMwEQYDVQQIDApDYWxpZm9ybmlhMRIwEAYDVQQHDAlTdW5ueXZhbGUxFTATBgNV -BAoMDFJ1c3QgT3BlblNTTDEMMAoGA1UECwwDT1NTMSEwHwYDVQQDDBhydXN0LW9w -ZW5zc2wuZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB -AQDa3Gc+IE5DOhTv1m5DZW8qKiyNLd7v4DaAYLXSsDuLs+9wJ+Bs+wlBfrg+PT0t -EJlPaLL9IfD5eR3WpFu62TUexYhnJh+3vhCGsFHOXcTjtM+wy/dzZtOVh2wTzvqE -/FHBGw1eG3Ww+RkSFbwYmtm8JhIN8ffYxGn2O0yQpxypf5hNPYrC81zX+52X2w1h -jDYLpYt55w+e6q+iRRFk0tKiWHEqqh/r6UQQRpj2EeS+xTloZlO6h0nl2NPkVF3r -CXBoT8Ittxr7sqcYqf8TAA0I4qZRYXKYehFmv/VkSt85CcURJ/zXeoJ1TpxSvQie -2R9cRDkYROrIOAFbB/0mmHLBAgMBAAGjUDBOMB0GA1UdDgQWBBRKfPqtgrbdbTmH -XR6RC/p8t/65GjAfBgNVHSMEGDAWgBRKfPqtgrbdbTmHXR6RC/p8t/65GjAMBgNV -HRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQCKfeGRduGsIwKNiGcDUNkNrc7Z -f8SWAmb/R6xiDfgjbhrtfBDowIZ5natEkTgf6kQPMJKyjg2NEM2uJWBc55rLOHIv -es1wQOlYjfEUmFD3lTIt2TM/IUgXn2j+zV1CRkJthQLVFChXsidd0Bqq2fBjd3ad -Yjzrxf3uOTBAs27koh2INNHfcUZCRsx8hP739zz2kw/r5NB/9iyENEyJKQvxo0jb -oN0JK2joGZrWetDukQrqf032TsdkboW5JresYybbAD3326Ljp+hlT/3WINc+3nZJ -Dn+pPMdpuZ5BUZ+u+XyNEPum3k3P3K19AF+zWYGooX0J1cmuCBrrqce20Lwy ------END CERTIFICATE----- Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/openssl-0.9.24/test/pkcs8.der and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/openssl-0.9.24/test/pkcs8.der differ diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/root-ca.key cargo-0.26.0/vendor/openssl-0.9.24/test/root-ca.key --- cargo-0.25.0/vendor/openssl-0.9.24/test/root-ca.key 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/root-ca.key 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpQIBAAKCAQEArVHWFn52Lbl1l59exduZntVSZyDYpzDND+S2LUcO6fRBWhV/ -1Kzox+2GZptbuMGmfI3iAnb0CFT4uC3kBkQQlXonGATSVyaFTFR+jq/lc0SP+9Bd -7SBXieIVeIXlY1TvlwIvj3Ntw9zX+scTA4SXxH6M0rKv9gTOub2vCMSHeF16X8DQ -r4XsZuQr7Cp7j1I4aqOJyap5JTl5ijmG8cnu0n+8UcRlBzy99dLWJG0AfI3VRJdW -pGTNVZ92aFff3RpK3F/WI2gp3qV1ynRAKuvmncGC3LDvYfcc2dgsc1N6Ffq8GIrk -gRob6eBcklDHp1d023Lwre+VaVDSo1//Y72UFwIDAQABAoIBAGZrnd/dC2kp11uq -Sg8SHk3GMdPPjTf/lq51sVJAU4fdV2Eso0XCiCzdKDcqR6F+jiu8jHp4YO0riW8N -b1pkjohGjyOaddIaaVsZ80/OkgDz20Ird9XQ7uoEODvopA12+755BDH5PDwqHVeM -nKfPiwAK6Jz6CxGO9bq9ZNoBiSyO1uofaB4Cpp8t74XVeAuPiI/Bb6WJ8TW5K5dt -x0Jihdo46QgZR+z4PnyWIoACkhSoQmtTb9NUrpKceBcxdCrZ/kEmYpnPq/PuSw6g -6HthjYP/H9Xulz69UR5Ez6z+1pU1rKFmQ46qK7X3zVHg233MlGekMzxdmShEjzCP -BMGYpQECgYEA5tqTZsUJwx3HDhkaZ/XOtaQqwOnZm9wPwTjGbV1t4+NUJzsl5gjP -ho+I8ZSGZ6MnNSh+ClpYhUHYBq0rTuAAYL2arcMOuOs1GrMmiZJbXm8zq8M7gYr5 -V99H/7akSx66WV/agPkLIvh/BWxlWgQcoVAIzZibbLUxr7Ye50pCLfECgYEAwDLn -mFz0mFMvGtaSp8RnTDTFCz9czCeDt0GujCxG1epdvtuxlg/S1QH+mGzA/AHkiu7z -uzCwGKWozNTdRkqVwYoJTB+AYHseSkuGP+a1zr39w+xBW/vESb2oP95GIwprXcG2 -b/qdeQVzuLQhYoqWI2u8CBwlHFfpQO4Bp2ea+ocCgYEAurIgLSfCqlpFpiAlG9hN -8NYwgU1d4E+LKj+JMd8yRO+PGh8amjub4X3pST5NqDjpN3Nk42iHWFWUqGmZsbM0 -ewg7tLUgDeqiStKBoxaK8AdMqWc9k5lZ53e6mZISsnHKUQdVBaLjH8gJqdAs8yyK -HudEB0mYwMSUxz6pJXIHrXECgYEAhJkaCpXm8chB8UQj/baUhZDKeI4IWZjRWHbq -Ey7g1+hPMMOk6yCTlf1ARqyRH8u2ftuIL5bRhs+Te21IE5yVYOb4rxn0mZuXNC6S -ujdTKwUMtESkeu9hZnaAQz/4J2ii1hY05WCDj+DhC4bKmY9/MYS8PuQb/kfwVqld -Xr8tvrUCgYEAmslHocXBUFXyRDkEOx/aKo+t9fPBr95PBZzFUt9ejrTP4PXsLa46 -3/PNOCGdrQxh5qHHcvLwR4bPL++Dj+qMUTJXANrArKPDpE2WqH6pqWIC6yaZvzUk -17QbpXR6bHcdJV045pWpw40UCStTocVynY1lBfOw8VqxBIBlpVBBzew= ------END RSA PRIVATE KEY----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/root-ca.pem cargo-0.26.0/vendor/openssl-0.9.24/test/root-ca.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/root-ca.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/root-ca.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDXTCCAkWgAwIBAgIJAOIvDiVb18eVMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV -BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX -aWRnaXRzIFB0eSBMdGQwHhcNMTYwODE0MTY1NjExWhcNMjYwODEyMTY1NjExWjBF -MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 -ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB -CgKCAQEArVHWFn52Lbl1l59exduZntVSZyDYpzDND+S2LUcO6fRBWhV/1Kzox+2G -ZptbuMGmfI3iAnb0CFT4uC3kBkQQlXonGATSVyaFTFR+jq/lc0SP+9Bd7SBXieIV -eIXlY1TvlwIvj3Ntw9zX+scTA4SXxH6M0rKv9gTOub2vCMSHeF16X8DQr4XsZuQr -7Cp7j1I4aqOJyap5JTl5ijmG8cnu0n+8UcRlBzy99dLWJG0AfI3VRJdWpGTNVZ92 -aFff3RpK3F/WI2gp3qV1ynRAKuvmncGC3LDvYfcc2dgsc1N6Ffq8GIrkgRob6eBc -klDHp1d023Lwre+VaVDSo1//Y72UFwIDAQABo1AwTjAdBgNVHQ4EFgQUbNOlA6sN -XyzJjYqciKeId7g3/ZowHwYDVR0jBBgwFoAUbNOlA6sNXyzJjYqciKeId7g3/Zow -DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAVVaR5QWLZIRR4Dw6TSBn -BQiLpBSXN6oAxdDw6n4PtwW6CzydaA+creiK6LfwEsiifUfQe9f+T+TBSpdIYtMv -Z2H2tjlFX8VrjUFvPrvn5c28CuLI0foBgY8XGSkR2YMYzWw2jPEq3Th/KM5Catn3 -AFm3bGKWMtGPR4v+90chEN0jzaAmJYRrVUh9vea27bOCn31Nse6XXQPmSI6Gyncy -OAPUsvPClF3IjeL1tmBotWqSGn1cYxLo+Lwjk22A9h6vjcNQRyZF2VLVvtwYrNU3 -mwJ6GCLsLHpwW/yjyvn8iEltnJvByM/eeRnfXV6WDObyiZsE/n6DxIRJodQzFqy9 -GA== ------END CERTIFICATE----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/rsa-encrypted.pem cargo-0.26.0/vendor/openssl-0.9.24/test/rsa-encrypted.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/rsa-encrypted.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/rsa-encrypted.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,E2F16153E2BA3D617285A68C896BA6AF - -vO9SnhtGjGe8pG1pN//vsONnvJr+DjU+lFCiSqGMPT7tezDnbehLfS+9kus2HV7r -HmI14JvVG9O7NpF7zMyBRlHYdWcCCWED9Yar0NsWN9419e5pMe/bqIXAzAiJbtT4 -OB9U5XF3m+349zjN1dVXPPLGRmMC1pcHAlofeb5nIUFTvUi5xcsbe1itGjgkkvHb -Bt8NioHTBun8kKrlsFQOuB55ylBU/eWG8DQBtvFOmQ7iWp0RnGQfh8k5e5rcZNpQ -fD9ygc7UVISl0xTrIG4IH15g34H+nrBauKtIPOpNPuXQPOMHCZv3XH8wnhrWHHwT -ZFnQBdXbSpQtMsRh0phG2G+VIlyCgSn4+CxjCJ+TgFtsoK/tU0unmRYc59QnTxxb -qkHYsPs3E0NApQAgH1ENEGl1M+FGLYQH7gftjc3ophBTeRA17sRmD7Y4QBInggsq -Gv6tImPVBdekAjz/Ls/EyMwjAvvrL5eAokqrIsAarGo+zmbJKHzknw2KUz2En0+k -YYaxB4oy9u7bzuQlvio6xYHJEb4K197bby4Dldmqv7YCCJBJwhOBAInMD687viKv -vcUwL8YuS6cW5E8MbvEENlY4+lvKKj3M8Bnyb79cYIPQe92EuCwXU9DZXPRMLwwM -oFEJpF5E/PmNJzu+B52ahHtDrh83WSx71fWqjdTqwkPZhAYo3ztsfFkb/UqUcq8u -rBSebeUjZh0XZ9B04eshZQ5vJUcXGtYIe/77beV3Pv89/fw+zTZjpiP9Q3sZALzf -Qt0YGp0/6qBuqR1tcqdu65AS2hun7yFw7uRavqYKvww4axRiz2do+xWmZFuoCAwD -EWktaUujltpvAc1lo7lg4C6nByefJB9Xqk22N/vpqOsWr1NbAntT42Qj/HF9BVWR -osvN3yMnKYWYe6oSTVnNBDM5obWAIHd3I9gcxTOTb1KsEwt2RrDs5EpB5ptS3Fjo -JfBRhNZQ3cXttrIIhsHgDn9BDNg865/xpIgktKj0gEd60Abx0PqkAIm6IZTh4Efg -7uZwfzxB+saOcddbrW2gNdzVZMC0s2Ye3sqHhtLbAJ3BlXYTxE4CAvTg54Ny+5hF -IjvjlOKgXceSG1cSfk21/wyp9RY3Ft0AEYvvp0kZScWZaoA2aSFDUrchXVhgrEbn -lJ7UptjefwRFIreAlwbKSbIDDNWnyzvIWyHfQ2aYqgnb7W7XqNPSgH9cALCfzirI -dlRHjha0bMUtrjPCC/YfMXzJBVniy0gG6Pd5uC7vz/Awn6/6HRQVNaTQASphPBQ7 -bJuz+JTfzI9OUVCMRMdnb6b35U4P9tibFmnPvzTIPe+3WUmf8aRsLS3NN3G1Webd -PMYVZpMycPaAI0Ht87axhsOzlxCWHYWjdHa+WoNNc1J90TxLCmAHquh5BDaWvjMK -0DySftJZjV7Tf1p2KosmU83LRl39B5NHMbZb1xOEZl9IWwhT/PVKTVZ25xdxWLfb -hF4l8rfvKehIp5r4t8zW1bvI2Hl6vrUvmcUVWt3BfKjxlgwRVD0vvwonMt1INesF -204vUBeXbDsUUicLwOyUgaFvJ3XU3dOyvL9MhOgM5OgoFRRhG+4AS8a5JCD8iLtq ------END RSA PRIVATE KEY----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/rsa.pem cargo-0.26.0/vendor/openssl-0.9.24/test/rsa.pem --- cargo-0.25.0/vendor/openssl-0.9.24/test/rsa.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/rsa.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEowIBAAKCAQEAofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd/wWJcyQoTbji9k0 -l8W26mPddxHmfHQp+Vaw+4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL+yRT+SFd2lZS+pC -gNMsD1W/YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb/7OMg0LOL+bSf63kpaSHSX -ndS5z5rexMdbBYUsLA9e+KXBdQOS+UTo7WTBEMa2R2CapHg665xsmtdVMTBQY4uD -Zlxvb3qCo5ZwKh9kG4LT6/I5IhlJH7aGhyxXFvUK+DWNmoudF8NAco9/h9iaGNj8 -q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQIDAQABAoIBABKucaRpzQorw35S -bEUAVx8dYXUdZOlJcHtiWQ+dC6V8ljxAHj/PLyzTveyI5QO/xkObCyjIL303l2cf -UhPu2MFaJdjVzqACXuOrLot/eSFvxjvqVidTtAZExqFRJ9mylUVAoLvhowVWmC1O -n95fZCXxTUtxNEG1Xcc7m0rtzJKs45J+N/V9DP1edYH6USyPSWGp6wuA+KgHRnKK -Vf9GRx80JQY7nVNkL17eHoTWEwga+lwi0FEoW9Y7lDtWXYmKBWhUE+U8PGxlJf8f -40493HDw1WRQ/aSLoS4QTp3rn7gYgeHEvfJdkkf0UMhlknlo53M09EFPdadQ4TlU -bjqKc50CgYEA4BzEEOtIpmVdVEZNCqS7baC4crd0pqnRH/5IB3jw3bcxGn6QLvnE -tfdUdiYrqBdss1l58BQ3KhooKeQTa9AB0Hw/Py5PJdTJNPY8cQn7ouZ2KKDcmnPG -BY5t7yLc1QlQ5xHdwW1VhvKn+nXqhJTBgIPgtldC+KDV5z+y2XDwGUcCgYEAuQPE -fgmVtjL0Uyyx88GZFF1fOunH3+7cepKmtH4pxhtCoHqpWmT8YAmZxaewHgHAjLYs -p1ZSe7zFYHj7C6ul7TjeLQeZD/YwD66t62wDmpe/HlB+TnBA+njbglfIsRLtXlnD -zQkv5dTltRJ11BKBBypeeF6689rjcJIDEz9RWdcCgYAHAp9XcCSrn8wVkMVkKdb7 -DOX4IKjzdahm+ctDAJN4O/y7OW5FKebvUjdAIt2GuoTZ71iTG+7F0F+lP88jtjP4 -U4qe7VHoewl4MKOfXZKTe+YCS1XbNvfgwJ3Ltyl1OH9hWvu2yza7q+d5PCsDzqtm -27kxuvULVeya+TEdAB1ijQKBgQCH/3r6YrVH/uCWGy6bzV1nGNOdjKc9tmkfOJmN -54dxdixdpozCQ6U4OxZrsj3FcOhHBsqAHvX2uuYjagqvo3cOj1TRqNocX40omfCC -Mx3bD1yPPf/6TI2XECva/ggqEY2mYzmIiA5LVVmc5nrybr+lssFKneeyxN2Wq93S -0iJMdQKBgCGHewxzoa1r8ZMD0LETNrToK423K377UCYqXfg5XMclbrjPbEC3YI1Z -NqMtuhdBJqUnBi6tjKMF+34Xf0CUN8ncuXGO2CAYvO8PdyCixHX52ybaDjy1FtCE -6yUXjoKNXKvUm7MWGsAYH6f4IegOetN5NvmUMFStCSkh7ixZLkN1 ------END RSA PRIVATE KEY----- diff -Nru cargo-0.25.0/vendor/openssl-0.9.24/test/rsa.pem.pub cargo-0.26.0/vendor/openssl-0.9.24/test/rsa.pem.pub --- cargo-0.25.0/vendor/openssl-0.9.24/test/rsa.pem.pub 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-0.9.24/test/rsa.pem.pub 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAofgWCuLjybRlzo0tZWJj -NiuSfb4p4fAkd/wWJcyQoTbji9k0l8W26mPddxHmfHQp+Vaw+4qPCJrcS2mJPMEz -P1Pt0Bm4d4QlL+yRT+SFd2lZS+pCgNMsD1W/YpRPEwOWvG6b32690r2jZ47soMZo -9wGzjb/7OMg0LOL+bSf63kpaSHSXndS5z5rexMdbBYUsLA9e+KXBdQOS+UTo7WTB -EMa2R2CapHg665xsmtdVMTBQY4uDZlxvb3qCo5ZwKh9kG4LT6/I5IhlJH7aGhyxX -FvUK+DWNmoudF8NAco9/h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXp -oQIDAQAB ------END PUBLIC KEY----- diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.26/build.rs cargo-0.26.0/vendor/openssl-sys-0.9.26/build.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.26/build.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.26/build.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,556 +0,0 @@ -extern crate cc; -extern crate pkg_config; -#[cfg(target_env = "msvc")] -extern crate vcpkg; - -use std::collections::HashSet; -use std::env; -use std::ffi::OsString; -use std::fs::File; -use std::io::{BufWriter, Write}; -use std::path::{Path, PathBuf}; -use std::panic::{self, AssertUnwindSafe}; -use std::process::Command; - -// The set of `OPENSSL_NO_`s that we care about. -const DEFINES: &'static [&'static str] = &[ - "OPENSSL_NO_BUF_FREELISTS", - "OPENSSL_NO_COMP", - "OPENSSL_NO_EC", - "OPENSSL_NO_EC2M", - "OPENSSL_NO_ENGINE", - "OPENSSL_NO_KRB5", - "OPENSSL_NO_NEXTPROTONEG", - "OPENSSL_NO_PSK", - "OPENSSL_NO_RFC3779", - "OPENSSL_NO_SHA", - "OPENSSL_NO_SRP", - "OPENSSL_NO_SSL3_METHOD", - "OPENSSL_NO_TLSEXT", -]; - -enum Version { - Openssl110, - Openssl102, - Openssl101, - Libressl, -} - -fn env(name: &str) -> Option { - let prefix = env::var("TARGET").unwrap().to_uppercase().replace("-", "_"); - let prefixed = format!("{}_{}", prefix, name); - println!("cargo:rerun-if-env-changed={}", prefixed); - - if let Some(var) = env::var_os(&prefixed) { - return Some(var); - } - - println!("cargo:rerun-if-env-changed={}", name); - env::var_os(name) -} - -fn main() { - let target = env::var("TARGET").unwrap(); - - let lib_dir = env("OPENSSL_LIB_DIR").map(PathBuf::from); - let include_dir = env("OPENSSL_INCLUDE_DIR").map(PathBuf::from); - - let (lib_dir, include_dir) = if lib_dir.is_none() || include_dir.is_none() { - let openssl_dir = env("OPENSSL_DIR").unwrap_or_else(|| find_openssl_dir(&target)); - let openssl_dir = Path::new(&openssl_dir); - let lib_dir = lib_dir.unwrap_or_else(|| openssl_dir.join("lib")); - let include_dir = include_dir.unwrap_or_else(|| openssl_dir.join("include")); - (lib_dir, include_dir) - } else { - (lib_dir.unwrap(), include_dir.unwrap()) - }; - - if !Path::new(&lib_dir).exists() { - panic!( - "OpenSSL library directory does not exist: {}", - lib_dir.to_string_lossy() - ); - } - if !Path::new(&include_dir).exists() { - panic!( - "OpenSSL include directory does not exist: {}", - include_dir.to_string_lossy() - ); - } - - println!( - "cargo:rustc-link-search=native={}", - lib_dir.to_string_lossy() - ); - println!("cargo:include={}", include_dir.to_string_lossy()); - - let version = validate_headers(&[include_dir.clone().into()]); - - let libs_env = env("OPENSSL_LIBS"); - let libs = match libs_env.as_ref().and_then(|s| s.to_str()) { - Some(ref v) => v.split(":").collect(), - None => match version { - Version::Openssl101 | Version::Openssl102 if target.contains("windows") => { - vec!["ssleay32", "libeay32"] - } - Version::Openssl110 if target.contains("windows") => vec!["libssl", "libcrypto"], - _ => vec!["ssl", "crypto"], - }, - }; - - let kind = determine_mode(Path::new(&lib_dir), &libs); - for lib in libs.into_iter() { - println!("cargo:rustc-link-lib={}={}", kind, lib); - } -} - -fn find_openssl_dir(target: &str) -> OsString { - let host = env::var("HOST").unwrap(); - - if host == target && target.contains("apple-darwin") { - let homebrew = Path::new("/usr/local/opt/openssl@1.1"); - if homebrew.exists() { - return homebrew.to_path_buf().into(); - } - let homebrew = Path::new("/usr/local/opt/openssl"); - if homebrew.exists() { - return homebrew.to_path_buf().into(); - } - } - - try_pkg_config(); - try_vcpkg(); - - // FreeBSD ships with OpenSSL but doesn't include a pkg-config file :( - if host == target && target.contains("freebsd") { - return OsString::from("/usr"); - } - - let mut msg = format!( - " - -Could not find directory of OpenSSL installation, and this `-sys` crate cannot -proceed without this knowledge. If OpenSSL is installed and this crate had -trouble finding it, you can set the `OPENSSL_DIR` environment variable for the -compilation process. - -If you're in a situation where you think the directory *should* be found -automatically, please open a bug at https://github.com/sfackler/rust-openssl -and include information about your system as well as this message. - - $HOST = {} - $TARGET = {} - openssl-sys = {} - -", - host, - target, - env!("CARGO_PKG_VERSION") - ); - - if host.contains("apple-darwin") && target.contains("apple-darwin") { - let system = Path::new("/usr/lib/libssl.0.9.8.dylib"); - if system.exists() { - msg.push_str(&format!( - " - -It looks like you're compiling on macOS, where the system contains a version of -OpenSSL 0.9.8. This crate no longer supports OpenSSL 0.9.8. - -As a consumer of this crate, you can fix this error by using Homebrew to -install the `openssl` package, or as a maintainer you can use the openssl-sys -0.7 crate for support with OpenSSL 0.9.8. - -Unfortunately though the compile cannot continue, so aborting. - -" - )); - } - } - - if host.contains("unknown-linux") && target.contains("unknown-linux-gnu") { - if Command::new("pkg-config").output().is_err() { - msg.push_str(&format!( - " -It looks like you're compiling on Linux and also targeting Linux. Currently this -requires the `pkg-config` utility to find OpenSSL but unfortunately `pkg-config` -could not be found. If you have OpenSSL installed you can likely fix this by -installing `pkg-config`. - -" - )); - } - } - - if host.contains("windows") && target.contains("windows-gnu") { - msg.push_str(&format!( - " -It looks like you're compiling for MinGW but you may not have either OpenSSL or -pkg-config installed. You can install these two dependencies with: - - pacman -S openssl-devel pkg-config - -and try building this crate again. - -" - )); - } - - if host.contains("windows") && target.contains("windows-msvc") { - msg.push_str(&format!( - " -It looks like you're compiling for MSVC but we couldn't detect an OpenSSL -installation. If there isn't one installed then you can try the rust-openssl -README for more information about how to download precompiled binaries of -OpenSSL: - - https://github.com/sfackler/rust-openssl#windows - -" - )); - } - - panic!(msg); -} - -/// Attempt to find OpenSSL through pkg-config. -/// -/// Note that if this succeeds then the function does not return as pkg-config -/// typically tells us all the information that we need. -fn try_pkg_config() { - let target = env::var("TARGET").unwrap(); - let host = env::var("HOST").unwrap(); - - // If we're going to windows-gnu we can use pkg-config, but only so long as - // we're coming from a windows host. - // - // Otherwise if we're going to windows we probably can't use pkg-config. - if target.contains("windows-gnu") && host.contains("windows") { - env::set_var("PKG_CONFIG_ALLOW_CROSS", "1"); - } else if target.contains("windows") { - return; - } - - let lib = match pkg_config::Config::new() - .print_system_libs(false) - .find("openssl") - { - Ok(lib) => lib, - Err(e) => { - println!("run pkg_config fail: {:?}", e); - return; - } - }; - - validate_headers(&lib.include_paths); - - for include in lib.include_paths.iter() { - println!("cargo:include={}", include.display()); - } - - std::process::exit(0); -} - -/// Attempt to find OpenSSL through vcpkg. -/// -/// Note that if this succeeds then the function does not return as vcpkg -/// should emit all of the cargo metadata that we need. -#[cfg(target_env = "msvc")] -fn try_vcpkg() { - // vcpkg will not emit any metadata if it can not find libraries - // appropriate for the target triple with the desired linkage. - - let mut lib = vcpkg::Config::new() - .emit_includes(true) - .lib_name("libcrypto") - .lib_name("libssl") - .probe("openssl"); - - if let Err(e) = lib { - println!( - "note: vcpkg did not find openssl as libcrypto and libssl : {:?}", - e - ); - lib = vcpkg::Config::new() - .emit_includes(true) - .lib_name("libeay32") - .lib_name("ssleay32") - .probe("openssl"); - } - if let Err(e) = lib { - println!( - "note: vcpkg did not find openssl as ssleay32 and libeay32: {:?}", - e - ); - return; - } - - let lib = lib.unwrap(); - validate_headers(&lib.include_paths); - - println!("cargo:rustc-link-lib=user32"); - println!("cargo:rustc-link-lib=gdi32"); - println!("cargo:rustc-link-lib=crypt32"); - - std::process::exit(0); -} - -#[cfg(not(target_env = "msvc"))] -fn try_vcpkg() {} - -/// Validates the header files found in `include_dir` and then returns the -/// version string of OpenSSL. -fn validate_headers(include_dirs: &[PathBuf]) -> Version { - // This `*-sys` crate only works with OpenSSL 1.0.1, 1.0.2, and 1.1.0. To - // correctly expose the right API from this crate, take a look at - // `opensslv.h` to see what version OpenSSL claims to be. - // - // OpenSSL has a number of build-time configuration options which affect - // various structs and such. Since OpenSSL 1.1.0 this isn't really a problem - // as the library is much more FFI-friendly, but 1.0.{1,2} suffer this problem. - // - // To handle all this conditional compilation we slurp up the configuration - // file of OpenSSL, `opensslconf.h`, and then dump out everything it defines - // as our own #[cfg] directives. That way the `ossl10x.rs` bindings can - // account for compile differences and such. - let mut path = PathBuf::from(env::var_os("OUT_DIR").unwrap()); - path.push("expando.c"); - let mut file = BufWriter::new(File::create(&path).unwrap()); - - write!( - file, - "\ -#include -#include - -#if LIBRESSL_VERSION_NUMBER >= 0x20700000 -RUST_LIBRESSL_NEW -#elif LIBRESSL_VERSION_NUMBER >= 0x20603000 -RUST_LIBRESSL_26X -#elif LIBRESSL_VERSION_NUMBER >= 0x20602000 -RUST_LIBRESSL_262 -#elif LIBRESSL_VERSION_NUMBER >= 0x20601000 -RUST_LIBRESSL_261 -#elif LIBRESSL_VERSION_NUMBER >= 0x20600000 -RUST_LIBRESSL_260 -#elif LIBRESSL_VERSION_NUMBER >= 0x20503000 -RUST_LIBRESSL_25X -#elif LIBRESSL_VERSION_NUMBER >= 0x20502000 -RUST_LIBRESSL_252 -#elif LIBRESSL_VERSION_NUMBER >= 0x20501000 -RUST_LIBRESSL_251 -#elif LIBRESSL_VERSION_NUMBER >= 0x20500000 -RUST_LIBRESSL_250 -#elif defined (LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20500000 -RUST_LIBRESSL_OLD -#elif OPENSSL_VERSION_NUMBER >= 0x10102000 -RUST_OPENSSL_NEW -#elif OPENSSL_VERSION_NUMBER >= 0x10101000 -RUST_OPENSSL_111 -#elif OPENSSL_VERSION_NUMBER >= 0x10100060 -RUST_OPENSSL_110F -#elif OPENSSL_VERSION_NUMBER >= 0x10100000 -RUST_OPENSSL_110 -#elif OPENSSL_VERSION_NUMBER >= 0x10002000 -RUST_OPENSSL_102 -#elif OPENSSL_VERSION_NUMBER >= 0x10001000 -RUST_OPENSSL_101 -#else -RUST_OPENSSL_OLD -#endif -" - ).unwrap(); - - for define in DEFINES { - write!( - file, - "\ -#ifdef {define} -RUST_{define}_RUST -#endif -", - define = define - ).unwrap(); - } - - file.flush().unwrap(); - drop(file); - - let mut gcc = cc::Build::new(); - for include_dir in include_dirs { - gcc.include(include_dir); - } - // https://github.com/alexcrichton/gcc-rs/issues/133 - let expanded = match panic::catch_unwind(AssertUnwindSafe(|| gcc.file(&path).expand())) { - Ok(expanded) => expanded, - Err(_) => { - panic!( - " -Failed to find OpenSSL development headers. - -You can try fixing this setting the `OPENSSL_DIR` environment variable -pointing to your OpenSSL installation or installing OpenSSL headers package -specific to your distribution: - - # On Ubuntu - sudo apt-get install libssl-dev - # On Arch Linux - sudo pacman -S openssl - # On Fedora - sudo dnf install openssl-devel - -See rust-openssl README for more information: - - https://github.com/sfackler/rust-openssl#linux -" - ); - } - }; - let expanded = String::from_utf8(expanded).unwrap(); - - let mut enabled = vec![]; - for &define in DEFINES { - if expanded.contains(&format!("RUST_{}_RUST", define)) { - println!("cargo:rustc-cfg=osslconf=\"{}\"", define); - enabled.push(define); - } - } - println!("cargo:conf={}", enabled.join(",")); - - if expanded.contains("RUST_LIBRESSL_250") { - println!("cargo:rustc-cfg=libressl"); - println!("cargo:rustc-cfg=libressl250"); - println!("cargo:libressl=true"); - println!("cargo:libressl_version=250"); - println!("cargo:version=101"); - Version::Libressl - } else if expanded.contains("RUST_LIBRESSL_251") { - println!("cargo:rustc-cfg=libressl"); - println!("cargo:rustc-cfg=libressl251"); - println!("cargo:libressl=true"); - println!("cargo:libressl_version=251"); - println!("cargo:version=101"); - Version::Libressl - } else if expanded.contains("RUST_LIBRESSL_252") { - println!("cargo:rustc-cfg=libressl"); - println!("cargo:rustc-cfg=libressl252"); - println!("cargo:libressl=true"); - println!("cargo:libressl_version=252"); - println!("cargo:version=101"); - Version::Libressl - } else if expanded.contains("RUST_LIBRESSL_25X") { - println!("cargo:rustc-cfg=libressl"); - println!("cargo:rustc-cfg=libressl25x"); - println!("cargo:libressl=true"); - println!("cargo:libressl_version=25x"); - println!("cargo:version=101"); - Version::Libressl - } else if expanded.contains("RUST_LIBRESSL_260") { - println!("cargo:rustc-cfg=libressl"); - println!("cargo:rustc-cfg=libressl260"); - println!("cargo:libressl=true"); - println!("cargo:libressl_version=260"); - println!("cargo:version=101"); - Version::Libressl - } else if expanded.contains("RUST_LIBRESSL_261") { - println!("cargo:rustc-cfg=libressl"); - println!("cargo:rustc-cfg=libressl261"); - println!("cargo:libressl=true"); - println!("cargo:libressl_version=261"); - println!("cargo:version=101"); - Version::Libressl - } else if expanded.contains("RUST_LIBRESSL_262") { - println!("cargo:rustc-cfg=libressl"); - println!("cargo:rustc-cfg=libressl262"); - println!("cargo:libressl=true"); - println!("cargo:libressl_version=262"); - println!("cargo:version=101"); - Version::Libressl - } else if expanded.contains("RUST_LIBRESSL_26X") { - println!("cargo:rustc-cfg=libressl"); - println!("cargo:rustc-cfg=libressl26x"); - println!("cargo:libressl=true"); - println!("cargo:libressl_version=26x"); - println!("cargo:version=101"); - Version::Libressl - } else if expanded.contains("RUST_OPENSSL_111") { - println!("cargo:rustc-cfg=ossl111"); - println!("cargo:rustc-cfg=ossl110"); - println!("cargo:version=111"); - Version::Openssl110 - } else if expanded.contains("RUST_OPENSSL_110F") { - println!("cargo:rustc-cfg=ossl110"); - println!("cargo:rustc-cfg=ossl110f"); - println!("cargo:version=110"); - println!("cargo:patch=f"); - Version::Openssl110 - } else if expanded.contains("RUST_OPENSSL_110") { - println!("cargo:rustc-cfg=ossl110"); - println!("cargo:version=110"); - Version::Openssl110 - } else if expanded.contains("RUST_OPENSSL_102") { - println!("cargo:rustc-cfg=ossl102"); - println!("cargo:version=102"); - Version::Openssl102 - } else if expanded.contains("RUST_OPENSSL_101") { - println!("cargo:rustc-cfg=ossl101"); - println!("cargo:version=101"); - Version::Openssl101 - } else { - panic!( - " - -This crate is only compatible with OpenSSL 1.0.1 through 1.1.1, or LibreSSL 2.5 -and 2.6, but a different version of OpenSSL was found. The build is now aborting -due to this version mismatch. - -" - ); - } -} - -/// Given a libdir for OpenSSL (where artifacts are located) as well as the name -/// of the libraries we're linking to, figure out whether we should link them -/// statically or dynamically. -fn determine_mode(libdir: &Path, libs: &[&str]) -> &'static str { - // First see if a mode was explicitly requested - let kind = env("OPENSSL_STATIC"); - match kind.as_ref().and_then(|s| s.to_str()).map(|s| &s[..]) { - Some("0") => return "dylib", - Some(_) => return "static", - None => {} - } - - // Next, see what files we actually have to link against, and see what our - // possibilities even are. - let files = libdir - .read_dir() - .unwrap() - .map(|e| e.unwrap()) - .map(|e| e.file_name()) - .filter_map(|e| e.into_string().ok()) - .collect::>(); - let can_static = libs.iter() - .all(|l| files.contains(&format!("lib{}.a", l)) || files.contains(&format!("{}.lib", l))); - let can_dylib = libs.iter().all(|l| { - files.contains(&format!("lib{}.so", l)) || files.contains(&format!("{}.dll", l)) - || files.contains(&format!("lib{}.dylib", l)) - }); - match (can_static, can_dylib) { - (true, false) => return "static", - (false, true) => return "dylib", - (false, false) => { - panic!( - "OpenSSL libdir at `{}` does not contain the required files \ - to either statically or dynamically link OpenSSL", - libdir.display() - ); - } - (true, true) => {} - } - - // Ok, we've got not explicit preference and can *either* link statically or - // link dynamically. In the interest of "security upgrades" and/or "best - // practices with security libs", let's link dynamically. - "dylib" -} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.26/.cargo-checksum.json cargo-0.26.0/vendor/openssl-sys-0.9.26/.cargo-checksum.json --- cargo-0.25.0/vendor/openssl-sys-0.9.26/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.26/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"a5a41ce2f5f2d939c80decde8fcfcf5837c203ca6c06a553510a2fcb84fa3ef1"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.26/Cargo.toml cargo-0.26.0/vendor/openssl-sys-0.9.26/Cargo.toml --- cargo-0.25.0/vendor/openssl-sys-0.9.26/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.26/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "openssl-sys" -version = "0.9.26" -authors = ["Alex Crichton ", "Steven Fackler "] -build = "build.rs" -links = "openssl" -description = "FFI bindings to OpenSSL" -readme = "README.md" -categories = ["cryptography", "external-ffi-bindings"] -license = "MIT" -repository = "https://github.com/sfackler/rust-openssl" -[package.metadata.pkg-config] -openssl = "1.0.1" -[dependencies.libc] -version = "0.2" -[build-dependencies.cc] -version = "1.0" - -[build-dependencies.pkg-config] -version = "0.3.9" -[target."cfg(target_env = \"msvc\")".build-dependencies.vcpkg] -version = "0.2" diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.26/LICENSE-MIT cargo-0.26.0/vendor/openssl-sys-0.9.26/LICENSE-MIT --- cargo-0.25.0/vendor/openssl-sys-0.9.26/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.26/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 Alex Crichton - -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. diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.26/README.md cargo-0.26.0/vendor/openssl-sys-0.9.26/README.md --- cargo-0.25.0/vendor/openssl-sys-0.9.26/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.26/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,180 +0,0 @@ -# rust-openssl - -[![CircleCI](https://circleci.com/gh/sfackler/rust-openssl.svg?style=shield)](https://circleci.com/gh/sfackler/rust-openssl) [![Build status](https://ci.appveyor.com/api/projects/status/d1knobws948pyynk/branch/master?svg=true)](https://ci.appveyor.com/project/sfackler/rust-openssl/branch/master) [![crates.io](https://img.shields.io/crates/v/openssl.svg)](https://crates.io/crates/openssl) - -[Documentation](https://docs.rs/openssl). - -## Warning - -This README does not correspond to rust-openssl 0.7.x or 0.8.x. See -[here](https://github.com/sfackler/rust-openssl/blob/b8fb29db5c246175a096260eacca38180cd77dd0/README.md) -for that README. - -## Building - -rust-openssl depends on OpenSSL version 1.0.1 or above, or LibreSSL. Both the -libraries and headers need to be present in the build environment before this -crate is compiled, and some instructions of how to do this are in the sections -below. - -### Linux - -On Linux, you can typically install OpenSSL via your package manager. The -headers are sometimes provided in a separate package than the runtime libraries -- look for something like `openssl-devel` or `libssl-dev`. You will also need the -regular development utilities, like `pkg-config`, as the custom build script relies -on them. - -```bash -# On Debian and Ubuntu -sudo apt-get install pkg-config libssl-dev -# On Arch Linux -sudo pacman -S openssl -# On Fedora -sudo dnf install openssl-devel -``` - -If installation via a package manager is not possible, or if you're cross -compiling to a separate target, you'll typically need to compile OpenSSL from -source. That can normally be done with: - -``` -curl -O https://www.openssl.org/source/openssl-1.1.0g.tar.gz -tar xf openssl-1.1.0g.tar.gz -cd openssl-1.1.0g -export CC=... -./Configure --prefix=... linux-x86_64 -fPIC -make -j$(nproc) -make install -``` - -### OSX - -Although OpenSSL 0.9.8 is preinstalled on OSX this library is being phased out -of OSX and this crate also does not support that version of OpenSSL. To use this -crate on OSX you'll need to install OpenSSL via some alternate means, typically -Homebrew: - -```bash -brew install openssl -``` - -Occasionally an update of XCode or MacOS will cause the linker to fail after compilation, to rectify this you may want to try and run: - -```bash -xcode-select --install -``` - -If Homebrew is installed to the default location of `/usr/local`, OpenSSL will be -automatically detected. - -### Windows MSVC - -On MSVC it's unfortunately not always a trivial process acquiring OpenSSL. A couple of possibilities -are downloading precompiled binaries for OpenSSL 1.1.0, or installing OpenSSL 1.0.2 using vcpkg. - -#### Installing OpenSSL 1.1.0 using precompiled binaries - -Perhaps the easiest way to do this right now is to download [precompiled -binaries] and install them on your system. Currently it's recommended to -install the 1.1.0 (non-light) installation if you're choosing this route. - -[precompiled binaries]: http://slproweb.com/products/Win32OpenSSL.html - -Once a precompiled binary is installed you can configure this crate to find the -installation via an environment variable: - -``` -set OPENSSL_DIR=C:\OpenSSL-Win64 -``` - -During the installation process if you select "Copy OpenSSL DLLs to: The OpenSSL binaries (/bin) -directory", you will need to add them to the `PATH` environment variable: - -``` -set PATH=%PATH%;C:\OpenSSL-Win64\bin -``` - -Now you will need to [install root certificates.](#acquiring-root-certificates) - -#### Installing OpenSSL 1.0.2 using vcpkg - -Install [vcpkg](https://github.com/Microsoft/vcpkg), and install the OpenSSL port like this: - -```Batchfile -vcpkg install openssl:x64-windows -set VCPKG_ROOT=c:\path\to\vcpkg\installation -cargo build -``` - -For more information see the vcpkg build helper [documentation](http://docs.rs/vcpkg). -To finsh setting up OpenSSL you will need to [install root certificates.](#acquiring-root-certificates) - -#### Acquiring Root Certificates - -Neither of the above OpenSSL distributions ship with any root certificates. -So to make requests to servers on the internet, you have to install them -manually. Download the [cacert.pem file from here], copy it somewhere safe -(`C:\OpenSSL-Win64\certs` is a good place) and point the `SSL_CERT_FILE` -environment variable there: - -``` -set SSL_CERT_FILE=C:\OpenSSL-Win64\certs\cacert.pem -``` - -[cacert.pem file from here]: https://curl.haxx.se/docs/caextract.html - -After that, you're just a `cargo build` away! - -### Windows GNU (MinGW) - -The easiest way to acquire OpenSSL when working with MinGW is to ensure you're -using [MSYS2](http://msys2.github.io) and to then execute: - -``` -# 32-bit -pacman -S mingw-w64-i686-openssl - -# 64-bit -pacman -S mingw-w64-x86_64-openssl -``` - -And after that, a `cargo build` should be all you need! - -### Manual configuration - -rust-openssl's build script will by default attempt to locate OpenSSL via -pkg-config or other system-specific mechanisms. This will not work in some -situations however, for example cross compiling or when using a copy of OpenSSL -other than the normal system install. - -The build script can be configured via environment variables: - -* `OPENSSL_DIR` - If specified, a directory that will be used to find - OpenSSL installation. It's expected that under this directory the `include` - folder has header files and a `lib` folder has the runtime libraries. -* `OPENSSL_LIB_DIR` - If specified, a directory that will be used to find - OpenSSL libraries. Overrides the `lib` folder implied by `OPENSSL_DIR` - (if specified). -* `OPENSSL_INCLUDE_DIR` - If specified, a directory that will be used to find - OpenSSL header files. Overrides the `include` folder implied by `OPENSSL_DIR` - (if specified). -* `OPENSSL_STATIC` - If specified, OpenSSL libraries will be statically rather - than dynamically linked. -* `OPENSSL_LIBS` - If specified, the names of the OpenSSL libraries that will be - linked, e.g. `ssl:crypto`. - -If `OPENSSL_DIR` or `OPENSSL_LIB_DIR` and `OPENSSL_INCLUDE_DIR` is specified, -then the build script will skip the pkg-config step. - -For target-specific configuration, each of these environment variables can be -prefixed by an upper-cased target, for example, -`X86_64_UNKNOWN_LINUX_GNU_OPENSSL_DIR`. This can be useful in cross compilation -contexts. - -### 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 under the terms of both the Apache License, -Version 2.0 and the MIT license without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.26/src/libressl/mod.rs cargo-0.26.0/vendor/openssl-sys-0.9.26/src/libressl/mod.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.26/src/libressl/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.26/src/libressl/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,594 +0,0 @@ -use std::sync::{Mutex, MutexGuard}; -use std::sync::{Once, ONCE_INIT}; -use std::mem; -use std::ptr; - -#[cfg(libressl250)] -pub use libressl::v250::*; -#[cfg(not(libressl250))] -pub use libressl::v25x::*; - -use libc::{c_char, c_int, c_long, c_uchar, c_uint, c_ulong, c_void, size_t}; - -#[cfg(libressl250)] -mod v250; -#[cfg(not(libressl250))] -mod v25x; - -#[repr(C)] -pub struct stack_st_ASN1_OBJECT { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_X509 { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_X509_NAME { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_X509_ATTRIBUTE { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_X509_EXTENSION { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_GENERAL_NAME { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_void { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_SSL_CIPHER { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_OPENSSL_STRING { - pub stack: _STACK, -} - -#[repr(C)] -pub struct _STACK { - pub num: c_int, - pub data: *mut *mut c_char, - pub sorted: c_int, - pub num_alloc: c_int, - pub comp: Option c_int>, -} - -#[repr(C)] -pub struct BIO_METHOD { - pub type_: c_int, - pub name: *const c_char, - pub bwrite: Option c_int>, - pub bread: Option c_int>, - pub bputs: Option c_int>, - pub bgets: Option c_int>, - pub ctrl: Option c_long>, - pub create: Option c_int>, - pub destroy: Option c_int>, - pub callback_ctrl: Option c_long>, -} - -#[repr(C)] -pub struct RSA { - pub pad: c_int, - pub version: c_long, - pub meth: *const ::RSA_METHOD, - - pub engine: *mut ::ENGINE, - pub n: *mut ::BIGNUM, - pub e: *mut ::BIGNUM, - pub d: *mut ::BIGNUM, - pub p: *mut ::BIGNUM, - pub q: *mut ::BIGNUM, - pub dmp1: *mut ::BIGNUM, - pub dmq1: *mut ::BIGNUM, - pub iqmp: *mut ::BIGNUM, - - pub ex_data: ::CRYPTO_EX_DATA, - pub references: c_int, - pub flags: c_int, - - pub _method_mod_n: *mut ::BN_MONT_CTX, - pub _method_mod_p: *mut ::BN_MONT_CTX, - pub _method_mod_q: *mut ::BN_MONT_CTX, - - pub blinding: *mut ::BN_BLINDING, - pub mt_blinding: *mut ::BN_BLINDING, -} - -#[repr(C)] -pub struct DSA { - pub pad: c_int, - pub version: c_long, - pub write_params: c_int, - - pub p: *mut ::BIGNUM, - pub q: *mut ::BIGNUM, - pub g: *mut ::BIGNUM, - pub pub_key: *mut ::BIGNUM, - pub priv_key: *mut ::BIGNUM, - pub kinv: *mut ::BIGNUM, - pub r: *mut ::BIGNUM, - - pub flags: c_int, - pub method_mont_p: *mut ::BN_MONT_CTX, - pub references: c_int, - pub ex_data: ::CRYPTO_EX_DATA, - pub meth: *const ::DSA_METHOD, - pub engine: *mut ::ENGINE, -} - -#[repr(C)] -pub struct EVP_PKEY { - pub type_: c_int, - pub save_type: c_int, - pub references: c_int, - pub ameth: *const ::EVP_PKEY_ASN1_METHOD, - pub engine: *mut ::ENGINE, - pub pkey: *mut c_void, - pub save_parameters: c_int, - pub attributes: *mut stack_st_X509_ATTRIBUTE, -} - -#[repr(C)] -pub struct BIO { - pub method: *mut ::BIO_METHOD, - pub callback: Option< - unsafe extern "C" fn(*mut ::BIO, c_int, *const c_char, c_int, c_long, c_long) -> c_long, - >, - pub cb_arg: *mut c_char, - pub init: c_int, - pub shutdown: c_int, - pub flags: c_int, - pub retry_reason: c_int, - pub num: c_int, - pub ptr: *mut c_void, - pub next_bio: *mut ::BIO, - pub prev_bio: *mut ::BIO, - pub references: c_int, - pub num_read: c_ulong, - pub num_write: c_ulong, - pub ex_data: ::CRYPTO_EX_DATA, -} - -#[repr(C)] -pub struct CRYPTO_EX_DATA { - pub sk: *mut ::stack_st_void, -} - -#[repr(C)] -pub struct EVP_MD_CTX { - digest: *mut ::EVP_MD, - engine: *mut ::ENGINE, - flags: c_ulong, - md_data: *mut c_void, - pctx: *mut ::EVP_PKEY_CTX, - update: *mut c_void, -} - -#[repr(C)] -pub struct EVP_CIPHER { - pub nid: c_int, - pub block_size: c_int, - pub key_len: c_int, - pub iv_len: c_int, - pub flags: c_ulong, - pub init: Option< - unsafe extern "C" fn(*mut ::EVP_CIPHER_CTX, *const c_uchar, *const c_uchar, c_int) -> c_int, - >, - pub do_cipher: Option< - unsafe extern "C" fn(*mut ::EVP_CIPHER_CTX, *mut c_uchar, *const c_uchar, size_t) -> c_int, - >, - pub cleanup: Option c_int>, - pub ctx_size: c_int, - pub set_asn1_parameters: - Option c_int>, - pub get_asn1_parameters: - Option c_int>, - pub ctrl: - Option c_int>, - pub app_data: *mut c_void, -} - -#[repr(C)] -pub struct HMAC_CTX { - md: *mut ::EVP_MD, - md_ctx: ::EVP_MD_CTX, - i_ctx: ::EVP_MD_CTX, - o_ctx: ::EVP_MD_CTX, - key_length: c_uint, - key: [c_uchar; 128], -} - -#[repr(C)] -pub struct BIGNUM { - pub d: *mut ::BN_ULONG, - pub top: c_int, - pub dmax: c_int, - pub neg: c_int, - pub flags: c_int, -} - -#[repr(C)] -pub struct DH { - pub pad: c_int, - pub version: c_int, - pub p: *mut ::BIGNUM, - pub g: *mut ::BIGNUM, - pub length: c_long, - pub pub_key: *mut ::BIGNUM, - pub priv_key: *mut ::BIGNUM, - pub flags: c_int, - pub method_mont_p: *mut ::BN_MONT_CTX, - pub q: *mut ::BIGNUM, - pub j: *mut ::BIGNUM, - pub seed: *mut c_uchar, - pub seedlen: c_int, - pub counter: *mut ::BIGNUM, - pub references: c_int, - pub ex_data: ::CRYPTO_EX_DATA, - pub meth: *const ::DH_METHOD, - pub engine: *mut ::ENGINE, -} - -#[repr(C)] -pub struct X509 { - pub cert_info: *mut X509_CINF, - pub sig_alg: *mut ::X509_ALGOR, - pub signature: *mut ::ASN1_BIT_STRING, - pub valid: c_int, - pub references: c_int, - pub name: *mut c_char, - pub ex_data: ::CRYPTO_EX_DATA, - pub ex_pathlen: c_long, - pub ex_pcpathlen: c_long, - pub ex_flags: c_ulong, - pub ex_kusage: c_ulong, - pub ex_xkusage: c_ulong, - pub ex_nscert: c_ulong, - skid: *mut c_void, - akid: *mut c_void, - policy_cache: *mut c_void, - crldp: *mut c_void, - altname: *mut c_void, - nc: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_SHA"))] - sha1_hash: [c_uchar; 20], - aux: *mut c_void, -} - -#[repr(C)] -pub struct X509_CINF { - version: *mut c_void, - serialNumber: *mut c_void, - signature: *mut c_void, - issuer: *mut c_void, - pub validity: *mut X509_VAL, - subject: *mut c_void, - key: *mut c_void, - issuerUID: *mut c_void, - subjectUID: *mut c_void, - pub extensions: *mut stack_st_X509_EXTENSION, - enc: ASN1_ENCODING, -} - -#[repr(C)] -pub struct X509_ALGOR { - pub algorithm: *mut ::ASN1_OBJECT, - parameter: *mut c_void, -} - -#[repr(C)] -pub struct ASN1_ENCODING { - pub enc: *mut c_uchar, - pub len: c_long, - pub modified: c_int, -} - -#[repr(C)] -pub struct X509_VAL { - pub notBefore: *mut ::ASN1_TIME, - pub notAfter: *mut ::ASN1_TIME, -} - -#[repr(C)] -pub struct X509_REQ_INFO { - pub enc: ASN1_ENCODING, - pub version: *mut ::ASN1_INTEGER, - pub subject: *mut ::X509_NAME, - pubkey: *mut c_void, - pub attributes: *mut stack_st_X509_ATTRIBUTE, -} - -#[repr(C)] -pub struct X509_REQ { - pub req_info: *mut X509_REQ_INFO, - sig_alg: *mut c_void, - signature: *mut c_void, - references: c_int, -} - -pub enum X509_VERIFY_PARAM_ID {} -pub enum PKCS12 {} - -pub const SSL_CTRL_GET_SESSION_REUSED: c_int = 8; -pub const SSL_CTRL_OPTIONS: c_int = 32; -pub const SSL_CTRL_CLEAR_OPTIONS: c_int = 77; -pub const SSL_CTRL_SET_ECDH_AUTO: c_int = 94; - -#[cfg(any(libressl261, libressl262, libressl26x))] -pub const SSL_OP_ALL: c_ulong = 0x4; -#[cfg(not(any(libressl261, libressl262, libressl26x)))] -pub const SSL_OP_ALL: c_ulong = 0x80000014; -pub const SSL_OP_CISCO_ANYCONNECT: c_ulong = 0x0; -pub const SSL_OP_NO_COMPRESSION: c_ulong = 0x0; -pub const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: c_ulong = 0x0; -pub const SSL_OP_NO_SSLv3: c_ulong = 0x0; -pub const SSL_OP_MICROSOFT_SESS_ID_BUG: c_ulong = 0x0; -pub const SSL_OP_NETSCAPE_CHALLENGE_BUG: c_ulong = 0x0; -pub const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: c_ulong = 0x0; -pub const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: c_ulong = 0x0; -pub const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: c_ulong = 0x0; -pub const SSL_OP_TLS_D5_BUG: c_ulong = 0x0; -pub const SSL_OP_TLS_BLOCK_PADDING_BUG: c_ulong = 0x0; -#[cfg(any(libressl261, libressl262, libressl26x))] -pub const SSL_OP_SINGLE_ECDH_USE: c_ulong = 0x0; -#[cfg(not(any(libressl261, libressl262, libressl26x)))] -pub const SSL_OP_SINGLE_ECDH_USE: c_ulong = 0x00080000; -pub const SSL_OP_SINGLE_DH_USE: c_ulong = 0x00100000; -pub const SSL_OP_NO_SSLv2: c_ulong = 0x0; - -pub const SSL_MAX_SSL_SESSION_ID_LENGTH: c_int = 32; -pub const SSL_MAX_SID_CTX_LENGTH: c_int = 32; -pub const SSL_MAX_MASTER_KEY_LENGTH: c_int = 48; - -pub const SSLEAY_VERSION: c_int = 0; -pub const SSLEAY_CFLAGS: c_int = 2; -pub const SSLEAY_BUILT_ON: c_int = 3; -pub const SSLEAY_PLATFORM: c_int = 4; -pub const SSLEAY_DIR: c_int = 5; - -pub const CRYPTO_LOCK_X509: c_int = 3; -pub const CRYPTO_LOCK_SSL_CTX: c_int = 12; -pub const CRYPTO_LOCK_SSL_SESSION: c_int = 14; - -static mut MUTEXES: *mut Vec> = 0 as *mut Vec>; -static mut GUARDS: *mut Vec>> = - 0 as *mut Vec>>; - -unsafe extern "C" fn locking_function(mode: c_int, n: c_int, _file: *const c_char, _line: c_int) { - let mutex = &(*MUTEXES)[n as usize]; - - if mode & ::CRYPTO_LOCK != 0 { - (*GUARDS)[n as usize] = Some(mutex.lock().unwrap()); - } else { - &(*GUARDS)[n as usize].take().expect("lock already unlocked"); - } -} - -pub fn init() { - static INIT: Once = ONCE_INIT; - - INIT.call_once(|| unsafe { - SSL_library_init(); - SSL_load_error_strings(); - OPENSSL_add_all_algorithms_noconf(); - - let num_locks = ::CRYPTO_num_locks(); - let mut mutexes = Box::new(Vec::new()); - for _ in 0..num_locks { - mutexes.push(Mutex::new(())); - } - MUTEXES = mem::transmute(mutexes); - let guards: Box>>> = - Box::new((0..num_locks).map(|_| None).collect()); - GUARDS = mem::transmute(guards); - - CRYPTO_set_locking_callback(locking_function); - set_id_callback(); - }) -} - -#[cfg(unix)] -fn set_id_callback() { - unsafe extern "C" fn thread_id() -> c_ulong { - ::libc::pthread_self() as c_ulong - } - - unsafe { - CRYPTO_set_id_callback(thread_id); - } -} - -#[cfg(not(unix))] -fn set_id_callback() {} - -// macros - -pub unsafe fn SSL_CTX_set_ecdh_auto(ctx: *mut SSL_CTX, onoff: c_int) -> c_int { - ::SSL_CTX_ctrl( - ctx, - SSL_CTRL_SET_ECDH_AUTO, - onoff as c_long, - ptr::null_mut(), - ) as c_int -} - -pub unsafe fn SSL_set_ecdh_auto(ssl: *mut ::SSL, onoff: c_int) -> c_int { - ::SSL_ctrl( - ssl, - SSL_CTRL_SET_ECDH_AUTO, - onoff as c_long, - ptr::null_mut(), - ) as c_int -} - -pub unsafe fn SSL_session_reused(ssl: *mut ::SSL) -> c_int { - ::SSL_ctrl(ssl, SSL_CTRL_GET_SESSION_REUSED, 0, ptr::null_mut()) as c_int -} - -extern "C" { - pub fn BIO_new(type_: *mut BIO_METHOD) -> *mut BIO; - pub fn BIO_s_file() -> *mut BIO_METHOD; - pub fn BIO_s_mem() -> *mut BIO_METHOD; - - pub fn get_rfc2409_prime_768(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc2409_prime_1024(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc3526_prime_1536(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc3526_prime_2048(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc3526_prime_3072(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc3526_prime_4096(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc3526_prime_6144(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc3526_prime_8192(bn: *mut BIGNUM) -> *mut BIGNUM; - - pub fn CRYPTO_malloc(num: c_int, file: *const c_char, line: c_int) -> *mut c_void; - pub fn CRYPTO_free(buf: *mut c_void); - pub fn CRYPTO_num_locks() -> c_int; - pub fn CRYPTO_set_locking_callback( - func: unsafe extern "C" fn(mode: c_int, n: c_int, file: *const c_char, line: c_int), - ); - pub fn CRYPTO_set_id_callback(func: unsafe extern "C" fn() -> c_ulong); - - pub fn ERR_load_crypto_strings(); - - pub fn RSA_generate_key( - modsz: c_int, - e: c_ulong, - cb: Option, - cbarg: *mut c_void, - ) -> *mut RSA; - - pub fn OCSP_cert_to_id( - dgst: *const ::EVP_MD, - subject: *mut ::X509, - issuer: *mut ::X509, - ) -> *mut ::OCSP_CERTID; - - pub fn PKCS12_create( - pass: *mut c_char, - friendly_name: *mut c_char, - pkey: *mut EVP_PKEY, - cert: *mut X509, - ca: *mut stack_st_X509, - nid_key: c_int, - nid_cert: c_int, - iter: c_int, - mac_iter: c_int, - keytype: c_int, - ) -> *mut PKCS12; - - pub fn SSL_library_init() -> c_int; - pub fn SSL_load_error_strings(); - pub fn OPENSSL_add_all_algorithms_noconf(); - pub fn HMAC_CTX_init(ctx: *mut ::HMAC_CTX); - pub fn HMAC_CTX_cleanup(ctx: *mut ::HMAC_CTX); - pub fn TLSv1_method() -> *const ::SSL_METHOD; - pub fn SSLv23_method() -> *const ::SSL_METHOD; - pub fn TLSv1_1_method() -> *const ::SSL_METHOD; - pub fn TLSv1_2_method() -> *const ::SSL_METHOD; - pub fn DTLSv1_method() -> *const ::SSL_METHOD; - pub fn SSL_get_ex_new_index( - argl: c_long, - argp: *mut c_void, - new_func: Option<::CRYPTO_EX_new>, - dup_func: Option<::CRYPTO_EX_dup>, - free_func: Option<::CRYPTO_EX_free>, - ) -> c_int; - pub fn SSL_set_tmp_ecdh_callback( - ssl: *mut ::SSL, - ecdh: unsafe extern "C" fn(ssl: *mut ::SSL, is_export: c_int, keylength: c_int) - -> *mut ::EC_KEY, - ); - pub fn SSL_CIPHER_get_version(cipher: *const ::SSL_CIPHER) -> *mut c_char; - pub fn SSL_CTX_get_ex_new_index( - argl: c_long, - argp: *mut c_void, - new_func: Option<::CRYPTO_EX_new>, - dup_func: Option<::CRYPTO_EX_dup>, - free_func: Option<::CRYPTO_EX_free>, - ) -> c_int; - // FIXME should take an option - pub fn SSL_CTX_set_tmp_ecdh_callback( - ctx: *mut ::SSL_CTX, - ecdh: unsafe extern "C" fn(ssl: *mut ::SSL, is_export: c_int, keylength: c_int) - -> *mut ::EC_KEY, - ); - pub fn SSL_CTX_sess_set_get_cb( - ctx: *mut ::SSL_CTX, - get_session_cb: Option< - unsafe extern "C" fn(*mut ::SSL, *mut c_uchar, c_int, *mut c_int) -> *mut SSL_SESSION, - >, - ); - pub fn X509_get_subject_name(x: *mut ::X509) -> *mut ::X509_NAME; - pub fn X509_get_issuer_name(x: *mut ::X509) -> *mut ::X509_NAME; - pub fn X509_set_notAfter(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; - pub fn X509_set_notBefore(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; - pub fn X509_get_ext_d2i( - x: *mut ::X509, - nid: c_int, - crit: *mut c_int, - idx: *mut c_int, - ) -> *mut c_void; - pub fn X509_NAME_add_entry_by_NID( - x: *mut ::X509_NAME, - field: c_int, - ty: c_int, - bytes: *mut c_uchar, - len: c_int, - loc: c_int, - set: c_int, - ) -> c_int; - pub fn X509_NAME_get_entry(n: *mut ::X509_NAME, loc: c_int) -> *mut ::X509_NAME_ENTRY; - pub fn X509_NAME_ENTRY_get_data(ne: *mut ::X509_NAME_ENTRY) -> *mut ::ASN1_STRING; - pub fn X509_STORE_CTX_get_chain(ctx: *mut ::X509_STORE_CTX) -> *mut stack_st_X509; - pub fn X509V3_EXT_nconf_nid( - conf: *mut ::CONF, - ctx: *mut ::X509V3_CTX, - ext_nid: c_int, - value: *mut c_char, - ) -> *mut ::X509_EXTENSION; - pub fn X509V3_EXT_nconf( - conf: *mut ::CONF, - ctx: *mut ::X509V3_CTX, - name: *mut c_char, - value: *mut c_char, - ) -> *mut ::X509_EXTENSION; - pub fn ASN1_STRING_to_UTF8(out: *mut *mut c_uchar, s: *mut ::ASN1_STRING) -> c_int; - pub fn ASN1_STRING_data(x: *mut ::ASN1_STRING) -> *mut c_uchar; - pub fn CRYPTO_add_lock( - pointer: *mut c_int, - amount: c_int, - type_: c_int, - file: *const c_char, - line: c_int, - ) -> c_int; - pub fn EVP_MD_CTX_create() -> *mut EVP_MD_CTX; - pub fn EVP_MD_CTX_destroy(ctx: *mut EVP_MD_CTX); - pub fn EVP_PKEY_bits(key: *mut EVP_PKEY) -> c_int; - - pub fn sk_new_null() -> *mut _STACK; - pub fn sk_num(st: *const _STACK) -> c_int; - pub fn sk_value(st: *const _STACK, n: c_int) -> *mut c_void; - pub fn sk_free(st: *mut _STACK); - pub fn sk_push(st: *mut _STACK, data: *mut c_void) -> c_int; - pub fn sk_pop_free(st: *mut _STACK, free: Option); - pub fn sk_pop(st: *mut _STACK) -> *mut c_void; - - pub fn SSLeay() -> c_ulong; - pub fn SSLeay_version(key: c_int) -> *const c_char; -} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.26/src/libressl/v250.rs cargo-0.26.0/vendor/openssl-sys-0.9.26/src/libressl/v250.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.26/src/libressl/v250.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.26/src/libressl/v250.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,221 +0,0 @@ -use libc::{c_int, c_char, c_void, c_long, c_uchar, size_t, c_uint, c_ulong, time_t}; - -use super::*; - -#[repr(C)] -pub struct SSL { - version: c_int, - type_: c_int, - method: *const ::SSL_METHOD, - rbio: *mut c_void, - wbio: *mut c_void, - bbio: *mut c_void, - rwstate: c_int, - in_handshake: c_int, - handshake_func: Option c_int>, - pub server: c_int, - new_session: c_int, - quiet_shutdown: c_int, - shutdown: c_int, - state: c_int, - rstate: c_int, - init_buf: *mut c_void, - init_msg: *mut c_void, - init_num: c_int, - init_off: c_int, - packet: *mut c_uchar, - packet_length: c_uint, - s3: *mut c_void, - d1: *mut c_void, - read_ahead: c_int, - msg_callback: Option< - unsafe extern "C" fn(c_int, - c_int, - c_int, - *const c_void, - size_t, - *mut SSL, - *mut c_void), - >, - msg_callback_arg: *mut c_void, - hit: c_int, - param: *mut c_void, - cipher_list: *mut stack_st_SSL_CIPHER, - cipher_list_by_id: *mut stack_st_SSL_CIPHER, - mac_flags: c_int, - aead_read_ctx: *mut c_void, - enc_read_ctx: *mut ::EVP_CIPHER_CTX, - read_hash: *mut ::EVP_MD_CTX, - aead_write_ctx: *mut c_void, - enc_write_ctx: *mut ::EVP_CIPHER_CTX, - write_hash: *mut ::EVP_MD_CTX, - cert: *mut c_void, - sid_ctx_length: c_uint, - sid_ctx: [c_uchar; ::SSL_MAX_SID_CTX_LENGTH as usize], - session: *mut ::SSL_SESSION, - generate_session_id: ::GEN_SESSION_CB, - verify_mode: c_int, - verify_callback: Option c_int>, - info_callback: Option, - error: c_int, - error_code: c_int, - ctx: *mut ::SSL_CTX, - debug: c_int, - verify_result: c_long, - ex_data: ::CRYPTO_EX_DATA, - client_CA: *mut stack_st_X509_NAME, - references: c_int, - options: c_ulong, - mode: c_ulong, - max_cert_list: c_long, - first_packet: c_int, - client_version: c_int, - max_send_fragment: c_uint, - tlsext_debug_cb: - Option, - tlsext_debug_arg: *mut c_void, - tlsext_hostname: *mut c_char, - servername_done: c_int, - tlsext_status_type: c_int, - tlsext_status_expected: c_int, - tlsext_ocsp_ids: *mut c_void, - tlsext_ocsp_exts: *mut c_void, - tlsext_ocsp_resp: *mut c_uchar, - tlsext_ocsp_resplen: c_int, - tlsext_ticket_expected: c_int, - tlsext_ecpointformatlist_length: size_t, - tlsext_ecpointformatlist: *mut c_uchar, - tlsext_ellipticcurvelist_length: size_t, - tlsext_ellipticcurvelist: *mut c_uchar, - tlsext_session_ticket: *mut c_void, - tlsext_session_ticket_ext_cb: ::tls_session_ticket_ext_cb_fn, - tls_session_ticket_ext_cb_arg: *mut c_void, - tls_session_secret_cb: ::tls_session_secret_cb_fn, - tls_session_secret_cb_arg: *mut c_void, - initial_ctx: *mut ::SSL_CTX, - next_proto_negotiated: *mut c_uchar, - next_proto_negotiated_len: c_uchar, - srtp_profiles: *mut c_void, - srtp_profile: *mut c_void, - tlsext_heartbeat: c_uint, - tlsext_hb_pending: c_uint, - tlsext_hb_seq: c_uint, - alpn_client_proto_list: *mut c_uchar, - alpn_client_proto_list_len: c_uint, - renegotiate: c_int, -} - -#[repr(C)] -pub struct SSL_CTX { - method: *mut c_void, - cipher_list: *mut c_void, - cipher_list_by_id: *mut c_void, - cert_store: *mut c_void, - sessions: *mut c_void, - session_cache_size: c_ulong, - session_cache_head: *mut c_void, - session_cache_tail: *mut c_void, - session_cache_mode: c_int, - session_timeout: c_long, - new_session_cb: *mut c_void, - remove_session_cb: *mut c_void, - get_session_cb: *mut c_void, - stats: [c_int; 11], - pub references: c_int, - app_verify_callback: *mut c_void, - app_verify_arg: *mut c_void, - default_passwd_callback: *mut c_void, - default_passwd_callback_userdata: *mut c_void, - client_cert_cb: *mut c_void, - app_gen_cookie_cb: *mut c_void, - app_verify_cookie_cb: *mut c_void, - ex_dat: ::CRYPTO_EX_DATA, - rsa_md5: *mut c_void, - md5: *mut c_void, - sha1: *mut c_void, - extra_certs: *mut c_void, - comp_methods: *mut c_void, - info_callback: *mut c_void, - client_CA: *mut c_void, - options: c_ulong, - mode: c_ulong, - max_cert_list: c_long, - cert: *mut c_void, - read_ahead: c_int, - msg_callback: *mut c_void, - msg_callback_arg: *mut c_void, - verify_mode: c_int, - sid_ctx_length: c_uint, - sid_ctx: [c_uchar; 32], - default_verify_callback: *mut c_void, - generate_session_id: *mut c_void, - param: *mut c_void, - quiet_shutdown: c_int, - max_send_fragment: c_uint, - - #[cfg(not(osslconf = "OPENSSL_NO_ENGINE"))] - client_cert_engine: *mut c_void, - - tlsext_servername_callback: *mut c_void, - tlsect_servername_arg: *mut c_void, - tlsext_tick_key_name: [c_uchar; 16], - tlsext_tick_hmac_key: [c_uchar; 16], - tlsext_tick_aes_key: [c_uchar; 16], - tlsext_ticket_key_cb: *mut c_void, - tlsext_status_cb: *mut c_void, - tlsext_status_arg: *mut c_void, - tlsext_opaque_prf_input_callback: *mut c_void, - tlsext_opaque_prf_input_callback_arg: *mut c_void, - - next_protos_advertised_cb: *mut c_void, - next_protos_advertised_cb_arg: *mut c_void, - next_proto_select_cb: *mut c_void, - next_proto_select_cb_arg: *mut c_void, - - srtp_profiles: *mut c_void, -} - -#[repr(C)] -pub struct SSL_SESSION { - ssl_version: c_int, - pub master_key_length: c_int, - pub master_key: [c_uchar; 48], - session_id_length: c_uint, - session_id: [c_uchar; SSL_MAX_SSL_SESSION_ID_LENGTH as usize], - sid_ctx_length: c_uint, - sid_ctx: [c_uchar; SSL_MAX_SID_CTX_LENGTH as usize], - not_resumable: c_int, - sess_cert: *mut c_void, - peer: *mut X509, - verify_result: c_long, - timeout: c_long, - time: time_t, - pub references: c_int, - cipher: *const c_void, - cipher_id: c_ulong, - ciphers: *mut c_void, - ex_data: ::CRYPTO_EX_DATA, - prev: *mut c_void, - next: *mut c_void, - tlsext_hostname: *mut c_char, - tlsext_ecpointformatlist_length: size_t, - tlsext_ecpointformatlist: *mut u8, - tlsext_ellipticcurvelist_length: size_t, - tlsext_ellipticcurvelist: *mut u16, - tlsext_tick: *mut c_uchar, - tlsext_ticklen: size_t, - tlsext_tick_lifetime_hint: c_long, -} - -#[repr(C)] -pub struct X509_VERIFY_PARAM { - pub name: *mut c_char, - pub check_time: time_t, - pub inh_flags: c_ulong, - pub flags: c_ulong, - pub purpose: c_int, - pub trust: c_int, - pub depth: c_int, - pub policies: *mut stack_st_ASN1_OBJECT, - //pub id: *mut X509_VERIFY_PARAM_ID, -} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.26/src/libressl/v25x.rs cargo-0.26.0/vendor/openssl-sys-0.9.26/src/libressl/v25x.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.26/src/libressl/v25x.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.26/src/libressl/v25x.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,89 +0,0 @@ -use libc::{c_int, c_char, c_void, c_long, c_uchar, size_t, c_uint, c_ulong, time_t}; - -use super::*; - -#[repr(C)] -pub struct SSL { - version: c_int, - method: *const ::SSL_METHOD, - rbio: *mut ::BIO, - wbio: *mut ::BIO, - bbio: *mut ::BIO, - pub server: c_int, - s3: *mut c_void, - d1: *mut c_void, - param: *mut c_void, - cipher_list: *mut stack_st_SSL_CIPHER, - cert: *mut c_void, - sid_ctx_length: c_uint, - sid_ctx: [c_uchar; ::SSL_MAX_SID_CTX_LENGTH as usize], - session: *mut ::SSL_SESSION, - verify_mode: c_int, - error: c_int, - error_code: c_int, - ctx: *mut ::SSL_CTX, - verify_result: c_long, - references: c_int, - client_version: c_int, - max_send_fragment: c_uint, - tlsext_hostname: *mut c_char, - tlsext_status_type: c_int, - initial_ctx: *mut ::SSL_CTX, - enc_read_ctx: *mut ::EVP_CIPHER_CTX, - read_hash: *mut EVP_MD_CTX, - internal: *mut c_void, -} - -#[repr(C)] -pub struct SSL_CTX { - method: *const ::SSL_METHOD, - cipher_list: *mut stack_st_SSL_CIPHER, - cert_store: *mut c_void, - session_timeout: c_long, - pub references: c_int, - extra_certs: *mut stack_st_X509, - verify_mode: c_int, - sid_ctx_length: c_uint, - sid_ctx: [c_uchar; ::SSL_MAX_SID_CTX_LENGTH as usize], - param: *mut ::X509_VERIFY_PARAM, - default_passwd_callback: *mut c_void, - default_passwd_callback_userdata: *mut c_void, - internal: *mut c_void, -} - -#[repr(C)] -pub struct SSL_SESSION { - ssl_version: c_int, - pub master_key_length: c_int, - pub master_key: [c_uchar; 48], - session_id_length: c_uint, - session_id: [c_uchar; ::SSL_MAX_SSL_SESSION_ID_LENGTH as usize], - sid_ctx_length: c_uint, - sid_ctx: [c_uchar; ::SSL_MAX_SID_CTX_LENGTH as usize], - peer: *mut ::X509, - verify_result: c_long, - timeout: c_long, - time: time_t, - pub references: c_int, - cipher: *const ::SSL_CIPHER, - cipher_id: c_long, - ciphers: *mut stack_st_SSL_CIPHER, - tlsext_hostname: *mut c_char, - tlsext_tick: *mut c_uchar, - tlsext_ticklen: size_t, - tlsext_tick_lifetime_int: c_long, - internal: *mut c_void, -} - -#[repr(C)] -pub struct X509_VERIFY_PARAM { - pub name: *mut c_char, - pub check_time: time_t, - pub inh_flags: c_ulong, - pub flags: c_ulong, - pub purpose: c_int, - pub trust: c_int, - pub depth: c_int, - policies: *mut stack_st_ASN1_OBJECT, - id: *mut c_void, -} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.26/src/lib.rs cargo-0.26.0/vendor/openssl-sys-0.9.26/src/lib.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.26/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.26/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2752 +0,0 @@ -#![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)] -#![allow(dead_code, overflowing_literals)] -#![doc(html_root_url = "https://docs.rs/openssl-sys/0.9")] - -extern crate libc; - -use libc::{c_char, c_int, c_long, c_uchar, c_uint, c_ulong, c_void, size_t, FILE}; -use std::ptr; -use std::mem; - -#[cfg(any(ossl101, ossl102))] -mod ossl10x; -#[cfg(any(ossl101, ossl102))] -pub use ossl10x::*; - -#[cfg(ossl110)] -mod ossl110; -#[cfg(ossl110)] -pub use ossl110::*; - -#[cfg(libressl)] -mod libressl; -#[cfg(libressl)] -pub use libressl::*; - -pub enum ASN1_INTEGER {} -pub enum ASN1_GENERALIZEDTIME {} -pub enum ASN1_STRING {} -pub enum ASN1_BIT_STRING {} -pub enum ASN1_TIME {} -pub enum ASN1_TYPE {} -pub enum ASN1_OBJECT {} -pub enum BN_CTX {} -pub enum BN_GENCB {} -pub enum CMS_ContentInfo {} -pub enum CONF {} -pub enum CONF_METHOD {} -pub enum COMP_METHOD {} -pub enum EC_KEY {} -pub enum EC_GROUP {} -pub enum EC_METHOD {} -pub enum EC_POINT {} -pub enum ENGINE {} -pub enum EVP_CIPHER_CTX {} -pub enum EVP_MD {} -pub enum EVP_PKEY_CTX {} -pub enum OCSP_BASICRESP {} -pub enum OCSP_CERTID {} -pub enum OCSP_RESPONSE {} -pub enum OCSP_REQUEST {} -pub enum OCSP_ONEREQ {} -pub enum SSL_CIPHER {} -pub enum SSL_METHOD {} -pub enum X509_CRL {} -pub enum X509_EXTENSION {} -pub enum X509_NAME {} -pub enum X509_NAME_ENTRY {} -pub enum X509_STORE {} -pub enum X509_STORE_CTX {} -pub enum bio_st {} -pub enum DH_METHOD {} -pub enum RSA_METHOD {} -pub enum BN_MONT_CTX {} -pub enum BN_BLINDING {} -pub enum DSA_METHOD {} -pub enum EVP_PKEY_ASN1_METHOD {} - -pub type bio_info_cb = - Option; -pub type GEN_SESSION_CB = - Option c_int>; -pub type tls_session_ticket_ext_cb_fn = - Option c_int>; -pub type tls_session_secret_cb_fn = Option< - unsafe extern "C" fn( - *mut SSL, - *mut c_void, - *mut c_int, - *mut stack_st_SSL_CIPHER, - *mut *mut SSL_CIPHER, - *mut c_void, - ) -> c_int, ->; - -#[repr(C)] -#[derive(Copy, Clone)] -pub enum point_conversion_form_t { - POINT_CONVERSION_COMPRESSED = 2, - POINT_CONVERSION_UNCOMPRESSED = 4, - POINT_CONVERSION_HYBRID = 6, -} - -#[repr(C)] -pub struct AES_KEY { - // There is some business with AES_LONG which is there to ensure the values here are 32 bits - rd_key: [u32; 4 * (AES_MAXNR as usize + 1)], - rounds: c_int, -} - -#[repr(C)] -pub struct GENERAL_NAME { - pub type_: c_int, - pub d: *mut c_void, -} - -#[repr(C)] -pub struct X509V3_CTX { - flags: c_int, - issuer_cert: *mut c_void, - subject_cert: *mut c_void, - subject_req: *mut c_void, - crl: *mut c_void, - db_meth: *mut c_void, - db: *mut c_void, - // I like the last comment line, it is copied from OpenSSL sources: - // Maybe more here -} - -#[repr(C)] -pub struct SHA_CTX { - pub h0: SHA_LONG, - pub h1: SHA_LONG, - pub h2: SHA_LONG, - pub h3: SHA_LONG, - pub h4: SHA_LONG, - pub Nl: SHA_LONG, - pub Nh: SHA_LONG, - pub data: [SHA_LONG; SHA_LBLOCK as usize], - pub num: c_uint, -} - -#[repr(C)] -pub struct SHA256_CTX { - pub h: [SHA_LONG; 8], - pub Nl: SHA_LONG, - pub Nh: SHA_LONG, - pub data: [SHA_LONG; SHA_LBLOCK as usize], - pub num: c_uint, - pub md_len: c_uint, -} - -#[repr(C)] -pub struct SHA512_CTX { - pub h: [SHA_LONG64; 8], - pub Nl: SHA_LONG64, - pub Nh: SHA_LONG64, - // this is a union but we don't want to require 1.19 - u: [SHA_LONG64; SHA_LBLOCK as usize], - pub num: c_uint, - pub md_len: c_uint, -} - -#[cfg(target_pointer_width = "64")] -pub type BN_ULONG = libc::c_ulonglong; -#[cfg(target_pointer_width = "32")] -pub type BN_ULONG = c_uint; - -pub type CRYPTO_EX_new = unsafe extern "C" fn( - parent: *mut c_void, - ptr: *mut c_void, - ad: *const CRYPTO_EX_DATA, - idx: c_int, - argl: c_long, - argp: *const c_void, -) -> c_int; -pub type CRYPTO_EX_dup = unsafe extern "C" fn( - to: *mut CRYPTO_EX_DATA, - from: *mut CRYPTO_EX_DATA, - from_d: *mut c_void, - idx: c_int, - argl: c_long, - argp: *mut c_void, -) -> c_int; -pub type CRYPTO_EX_free = unsafe extern "C" fn( - parent: *mut c_void, - ptr: *mut c_void, - ad: *mut CRYPTO_EX_DATA, - idx: c_int, - argl: c_long, - argp: *mut c_void, -); -pub type PasswordCallback = - unsafe extern "C" fn(buf: *mut c_char, size: c_int, rwflag: c_int, user_data: *mut c_void) - -> c_int; - -pub type SHA_LONG = c_uint; -pub type SHA_LONG64 = u64; - -pub const AES_ENCRYPT: c_int = 1; -pub const AES_DECRYPT: c_int = 0; - -pub const AES_MAXNR: c_int = 14; -pub const AES_BLOCK_SIZE: c_int = 16; - -pub const BIO_TYPE_NONE: c_int = 0; - -pub const BIO_CTRL_EOF: c_int = 2; -pub const BIO_CTRL_INFO: c_int = 3; -pub const BIO_CTRL_FLUSH: c_int = 11; -pub const BIO_C_SET_BUF_MEM_EOF_RETURN: c_int = 130; - -pub const BIO_FLAGS_READ: c_int = 0x01; -pub const BIO_FLAGS_WRITE: c_int = 0x02; -pub const BIO_FLAGS_IO_SPECIAL: c_int = 0x04; -pub const BIO_FLAGS_RWS: c_int = BIO_FLAGS_READ | BIO_FLAGS_WRITE | BIO_FLAGS_IO_SPECIAL; -pub const BIO_FLAGS_SHOULD_RETRY: c_int = 0x08; - -pub const CRYPTO_LOCK: c_int = 1; - -pub const ERR_TXT_MALLOCED: c_int = 0x01; -pub const ERR_TXT_STRING: c_int = 0x02; - -pub const ERR_LIB_PEM: c_int = 9; -pub const PEM_R_NO_START_LINE: c_int = 108; - -pub const EVP_MAX_MD_SIZE: c_uint = 64; -pub const EVP_PKEY_RSA: c_int = NID_rsaEncryption; -pub const EVP_PKEY_HMAC: c_int = NID_hmac; -pub const EVP_PKEY_DSA: c_int = NID_dsa; -pub const EVP_PKEY_DH: c_int = NID_dhKeyAgreement; -pub const EVP_PKEY_EC: c_int = NID_X9_62_id_ecPublicKey; - -pub const EVP_PKEY_ALG_CTRL: c_int = 0x1000; - -pub const EVP_PKEY_CTRL_RSA_PADDING: c_int = EVP_PKEY_ALG_CTRL + 1; - -pub const EVP_PKEY_CTRL_GET_RSA_PADDING: c_int = EVP_PKEY_ALG_CTRL + 6; - -pub const EVP_CTRL_GCM_SET_IVLEN: c_int = 0x9; -pub const EVP_CTRL_GCM_GET_TAG: c_int = 0x10; -pub const EVP_CTRL_GCM_SET_TAG: c_int = 0x11; - -pub const MBSTRING_ASC: c_int = MBSTRING_FLAG | 1; -pub const MBSTRING_BMP: c_int = MBSTRING_FLAG | 2; -pub const MBSTRING_FLAG: c_int = 0x1000; -pub const MBSTRING_UNIV: c_int = MBSTRING_FLAG | 4; -pub const MBSTRING_UTF8: c_int = MBSTRING_FLAG; - -pub const NID_undef: c_int = 0; -pub const NID_itu_t: c_int = 645; -pub const NID_ccitt: c_int = 404; -pub const NID_iso: c_int = 181; -pub const NID_joint_iso_itu_t: c_int = 646; -pub const NID_joint_iso_ccitt: c_int = 393; -pub const NID_member_body: c_int = 182; -pub const NID_identified_organization: c_int = 676; -pub const NID_hmac_md5: c_int = 780; -pub const NID_hmac_sha1: c_int = 781; -pub const NID_certicom_arc: c_int = 677; -pub const NID_international_organizations: c_int = 647; -pub const NID_wap: c_int = 678; -pub const NID_wap_wsg: c_int = 679; -pub const NID_selected_attribute_types: c_int = 394; -pub const NID_clearance: c_int = 395; -pub const NID_ISO_US: c_int = 183; -pub const NID_X9_57: c_int = 184; -pub const NID_X9cm: c_int = 185; -pub const NID_dsa: c_int = 116; -pub const NID_dsaWithSHA1: c_int = 113; -pub const NID_ansi_X9_62: c_int = 405; -pub const NID_X9_62_prime_field: c_int = 406; -pub const NID_X9_62_characteristic_two_field: c_int = 407; -pub const NID_X9_62_id_characteristic_two_basis: c_int = 680; -pub const NID_X9_62_onBasis: c_int = 681; -pub const NID_X9_62_tpBasis: c_int = 682; -pub const NID_X9_62_ppBasis: c_int = 683; -pub const NID_X9_62_id_ecPublicKey: c_int = 408; -pub const NID_X9_62_c2pnb163v1: c_int = 684; -pub const NID_X9_62_c2pnb163v2: c_int = 685; -pub const NID_X9_62_c2pnb163v3: c_int = 686; -pub const NID_X9_62_c2pnb176v1: c_int = 687; -pub const NID_X9_62_c2tnb191v1: c_int = 688; -pub const NID_X9_62_c2tnb191v2: c_int = 689; -pub const NID_X9_62_c2tnb191v3: c_int = 690; -pub const NID_X9_62_c2onb191v4: c_int = 691; -pub const NID_X9_62_c2onb191v5: c_int = 692; -pub const NID_X9_62_c2pnb208w1: c_int = 693; -pub const NID_X9_62_c2tnb239v1: c_int = 694; -pub const NID_X9_62_c2tnb239v2: c_int = 695; -pub const NID_X9_62_c2tnb239v3: c_int = 696; -pub const NID_X9_62_c2onb239v4: c_int = 697; -pub const NID_X9_62_c2onb239v5: c_int = 698; -pub const NID_X9_62_c2pnb272w1: c_int = 699; -pub const NID_X9_62_c2pnb304w1: c_int = 700; -pub const NID_X9_62_c2tnb359v1: c_int = 701; -pub const NID_X9_62_c2pnb368w1: c_int = 702; -pub const NID_X9_62_c2tnb431r1: c_int = 703; -pub const NID_X9_62_prime192v1: c_int = 409; -pub const NID_X9_62_prime192v2: c_int = 410; -pub const NID_X9_62_prime192v3: c_int = 411; -pub const NID_X9_62_prime239v1: c_int = 412; -pub const NID_X9_62_prime239v2: c_int = 413; -pub const NID_X9_62_prime239v3: c_int = 414; -pub const NID_X9_62_prime256v1: c_int = 415; -pub const NID_ecdsa_with_SHA1: c_int = 416; -pub const NID_ecdsa_with_Recommended: c_int = 791; -pub const NID_ecdsa_with_Specified: c_int = 792; -pub const NID_ecdsa_with_SHA224: c_int = 793; -pub const NID_ecdsa_with_SHA256: c_int = 794; -pub const NID_ecdsa_with_SHA384: c_int = 795; -pub const NID_ecdsa_with_SHA512: c_int = 796; -pub const NID_secp112r1: c_int = 704; -pub const NID_secp112r2: c_int = 705; -pub const NID_secp128r1: c_int = 706; -pub const NID_secp128r2: c_int = 707; -pub const NID_secp160k1: c_int = 708; -pub const NID_secp160r1: c_int = 709; -pub const NID_secp160r2: c_int = 710; -pub const NID_secp192k1: c_int = 711; -pub const NID_secp224k1: c_int = 712; -pub const NID_secp224r1: c_int = 713; -pub const NID_secp256k1: c_int = 714; -pub const NID_secp384r1: c_int = 715; -pub const NID_secp521r1: c_int = 716; -pub const NID_sect113r1: c_int = 717; -pub const NID_sect113r2: c_int = 718; -pub const NID_sect131r1: c_int = 719; -pub const NID_sect131r2: c_int = 720; -pub const NID_sect163k1: c_int = 721; -pub const NID_sect163r1: c_int = 722; -pub const NID_sect163r2: c_int = 723; -pub const NID_sect193r1: c_int = 724; -pub const NID_sect193r2: c_int = 725; -pub const NID_sect233k1: c_int = 726; -pub const NID_sect233r1: c_int = 727; -pub const NID_sect239k1: c_int = 728; -pub const NID_sect283k1: c_int = 729; -pub const NID_sect283r1: c_int = 730; -pub const NID_sect409k1: c_int = 731; -pub const NID_sect409r1: c_int = 732; -pub const NID_sect571k1: c_int = 733; -pub const NID_sect571r1: c_int = 734; -pub const NID_wap_wsg_idm_ecid_wtls1: c_int = 735; -pub const NID_wap_wsg_idm_ecid_wtls3: c_int = 736; -pub const NID_wap_wsg_idm_ecid_wtls4: c_int = 737; -pub const NID_wap_wsg_idm_ecid_wtls5: c_int = 738; -pub const NID_wap_wsg_idm_ecid_wtls6: c_int = 739; -pub const NID_wap_wsg_idm_ecid_wtls7: c_int = 740; -pub const NID_wap_wsg_idm_ecid_wtls8: c_int = 741; -pub const NID_wap_wsg_idm_ecid_wtls9: c_int = 742; -pub const NID_wap_wsg_idm_ecid_wtls10: c_int = 743; -pub const NID_wap_wsg_idm_ecid_wtls11: c_int = 744; -pub const NID_wap_wsg_idm_ecid_wtls12: c_int = 745; -pub const NID_cast5_cbc: c_int = 108; -pub const NID_cast5_ecb: c_int = 109; -pub const NID_cast5_cfb64: c_int = 110; -pub const NID_cast5_ofb64: c_int = 111; -pub const NID_pbeWithMD5AndCast5_CBC: c_int = 112; -pub const NID_id_PasswordBasedMAC: c_int = 782; -pub const NID_id_DHBasedMac: c_int = 783; -pub const NID_rsadsi: c_int = 1; -pub const NID_pkcs: c_int = 2; -pub const NID_pkcs1: c_int = 186; -pub const NID_rsaEncryption: c_int = 6; -pub const NID_md2WithRSAEncryption: c_int = 7; -pub const NID_md4WithRSAEncryption: c_int = 396; -pub const NID_md5WithRSAEncryption: c_int = 8; -pub const NID_sha1WithRSAEncryption: c_int = 65; -pub const NID_rsaesOaep: c_int = 919; -pub const NID_mgf1: c_int = 911; -pub const NID_rsassaPss: c_int = 912; -pub const NID_sha256WithRSAEncryption: c_int = 668; -pub const NID_sha384WithRSAEncryption: c_int = 669; -pub const NID_sha512WithRSAEncryption: c_int = 670; -pub const NID_sha224WithRSAEncryption: c_int = 671; -pub const NID_pkcs3: c_int = 27; -pub const NID_dhKeyAgreement: c_int = 28; -pub const NID_pkcs5: c_int = 187; -pub const NID_pbeWithMD2AndDES_CBC: c_int = 9; -pub const NID_pbeWithMD5AndDES_CBC: c_int = 10; -pub const NID_pbeWithMD2AndRC2_CBC: c_int = 168; -pub const NID_pbeWithMD5AndRC2_CBC: c_int = 169; -pub const NID_pbeWithSHA1AndDES_CBC: c_int = 170; -pub const NID_pbeWithSHA1AndRC2_CBC: c_int = 68; -pub const NID_id_pbkdf2: c_int = 69; -pub const NID_pbes2: c_int = 161; -pub const NID_pbmac1: c_int = 162; -pub const NID_pkcs7: c_int = 20; -pub const NID_pkcs7_data: c_int = 21; -pub const NID_pkcs7_signed: c_int = 22; -pub const NID_pkcs7_enveloped: c_int = 23; -pub const NID_pkcs7_signedAndEnveloped: c_int = 24; -pub const NID_pkcs7_digest: c_int = 25; -pub const NID_pkcs7_encrypted: c_int = 26; -pub const NID_pkcs9: c_int = 47; -pub const NID_pkcs9_emailAddress: c_int = 48; -pub const NID_pkcs9_unstructuredName: c_int = 49; -pub const NID_pkcs9_contentType: c_int = 50; -pub const NID_pkcs9_messageDigest: c_int = 51; -pub const NID_pkcs9_signingTime: c_int = 52; -pub const NID_pkcs9_countersignature: c_int = 53; -pub const NID_pkcs9_challengePassword: c_int = 54; -pub const NID_pkcs9_unstructuredAddress: c_int = 55; -pub const NID_pkcs9_extCertAttributes: c_int = 56; -pub const NID_ext_req: c_int = 172; -pub const NID_SMIMECapabilities: c_int = 167; -pub const NID_SMIME: c_int = 188; -pub const NID_id_smime_mod: c_int = 189; -pub const NID_id_smime_ct: c_int = 190; -pub const NID_id_smime_aa: c_int = 191; -pub const NID_id_smime_alg: c_int = 192; -pub const NID_id_smime_cd: c_int = 193; -pub const NID_id_smime_spq: c_int = 194; -pub const NID_id_smime_cti: c_int = 195; -pub const NID_id_smime_mod_cms: c_int = 196; -pub const NID_id_smime_mod_ess: c_int = 197; -pub const NID_id_smime_mod_oid: c_int = 198; -pub const NID_id_smime_mod_msg_v3: c_int = 199; -pub const NID_id_smime_mod_ets_eSignature_88: c_int = 200; -pub const NID_id_smime_mod_ets_eSignature_97: c_int = 201; -pub const NID_id_smime_mod_ets_eSigPolicy_88: c_int = 202; -pub const NID_id_smime_mod_ets_eSigPolicy_97: c_int = 203; -pub const NID_id_smime_ct_receipt: c_int = 204; -pub const NID_id_smime_ct_authData: c_int = 205; -pub const NID_id_smime_ct_publishCert: c_int = 206; -pub const NID_id_smime_ct_TSTInfo: c_int = 207; -pub const NID_id_smime_ct_TDTInfo: c_int = 208; -pub const NID_id_smime_ct_contentInfo: c_int = 209; -pub const NID_id_smime_ct_DVCSRequestData: c_int = 210; -pub const NID_id_smime_ct_DVCSResponseData: c_int = 211; -pub const NID_id_smime_ct_compressedData: c_int = 786; -pub const NID_id_ct_asciiTextWithCRLF: c_int = 787; -pub const NID_id_smime_aa_receiptRequest: c_int = 212; -pub const NID_id_smime_aa_securityLabel: c_int = 213; -pub const NID_id_smime_aa_mlExpandHistory: c_int = 214; -pub const NID_id_smime_aa_contentHint: c_int = 215; -pub const NID_id_smime_aa_msgSigDigest: c_int = 216; -pub const NID_id_smime_aa_encapContentType: c_int = 217; -pub const NID_id_smime_aa_contentIdentifier: c_int = 218; -pub const NID_id_smime_aa_macValue: c_int = 219; -pub const NID_id_smime_aa_equivalentLabels: c_int = 220; -pub const NID_id_smime_aa_contentReference: c_int = 221; -pub const NID_id_smime_aa_encrypKeyPref: c_int = 222; -pub const NID_id_smime_aa_signingCertificate: c_int = 223; -pub const NID_id_smime_aa_smimeEncryptCerts: c_int = 224; -pub const NID_id_smime_aa_timeStampToken: c_int = 225; -pub const NID_id_smime_aa_ets_sigPolicyId: c_int = 226; -pub const NID_id_smime_aa_ets_commitmentType: c_int = 227; -pub const NID_id_smime_aa_ets_signerLocation: c_int = 228; -pub const NID_id_smime_aa_ets_signerAttr: c_int = 229; -pub const NID_id_smime_aa_ets_otherSigCert: c_int = 230; -pub const NID_id_smime_aa_ets_contentTimestamp: c_int = 231; -pub const NID_id_smime_aa_ets_CertificateRefs: c_int = 232; -pub const NID_id_smime_aa_ets_RevocationRefs: c_int = 233; -pub const NID_id_smime_aa_ets_certValues: c_int = 234; -pub const NID_id_smime_aa_ets_revocationValues: c_int = 235; -pub const NID_id_smime_aa_ets_escTimeStamp: c_int = 236; -pub const NID_id_smime_aa_ets_certCRLTimestamp: c_int = 237; -pub const NID_id_smime_aa_ets_archiveTimeStamp: c_int = 238; -pub const NID_id_smime_aa_signatureType: c_int = 239; -pub const NID_id_smime_aa_dvcs_dvc: c_int = 240; -pub const NID_id_smime_alg_ESDHwith3DES: c_int = 241; -pub const NID_id_smime_alg_ESDHwithRC2: c_int = 242; -pub const NID_id_smime_alg_3DESwrap: c_int = 243; -pub const NID_id_smime_alg_RC2wrap: c_int = 244; -pub const NID_id_smime_alg_ESDH: c_int = 245; -pub const NID_id_smime_alg_CMS3DESwrap: c_int = 246; -pub const NID_id_smime_alg_CMSRC2wrap: c_int = 247; -pub const NID_id_alg_PWRI_KEK: c_int = 893; -pub const NID_id_smime_cd_ldap: c_int = 248; -pub const NID_id_smime_spq_ets_sqt_uri: c_int = 249; -pub const NID_id_smime_spq_ets_sqt_unotice: c_int = 250; -pub const NID_id_smime_cti_ets_proofOfOrigin: c_int = 251; -pub const NID_id_smime_cti_ets_proofOfReceipt: c_int = 252; -pub const NID_id_smime_cti_ets_proofOfDelivery: c_int = 253; -pub const NID_id_smime_cti_ets_proofOfSender: c_int = 254; -pub const NID_id_smime_cti_ets_proofOfApproval: c_int = 255; -pub const NID_id_smime_cti_ets_proofOfCreation: c_int = 256; -pub const NID_friendlyName: c_int = 156; -pub const NID_localKeyID: c_int = 157; -pub const NID_ms_csp_name: c_int = 417; -pub const NID_LocalKeySet: c_int = 856; -pub const NID_x509Certificate: c_int = 158; -pub const NID_sdsiCertificate: c_int = 159; -pub const NID_x509Crl: c_int = 160; -pub const NID_pbe_WithSHA1And128BitRC4: c_int = 144; -pub const NID_pbe_WithSHA1And40BitRC4: c_int = 145; -pub const NID_pbe_WithSHA1And3_Key_TripleDES_CBC: c_int = 146; -pub const NID_pbe_WithSHA1And2_Key_TripleDES_CBC: c_int = 147; -pub const NID_pbe_WithSHA1And128BitRC2_CBC: c_int = 148; -pub const NID_pbe_WithSHA1And40BitRC2_CBC: c_int = 149; -pub const NID_keyBag: c_int = 150; -pub const NID_pkcs8ShroudedKeyBag: c_int = 151; -pub const NID_certBag: c_int = 152; -pub const NID_crlBag: c_int = 153; -pub const NID_secretBag: c_int = 154; -pub const NID_safeContentsBag: c_int = 155; -pub const NID_md2: c_int = 3; -pub const NID_md4: c_int = 257; -pub const NID_md5: c_int = 4; -pub const NID_md5_sha1: c_int = 114; -pub const NID_hmacWithMD5: c_int = 797; -pub const NID_hmacWithSHA1: c_int = 163; -pub const NID_hmacWithSHA224: c_int = 798; -pub const NID_hmacWithSHA256: c_int = 799; -pub const NID_hmacWithSHA384: c_int = 800; -pub const NID_hmacWithSHA512: c_int = 801; -pub const NID_rc2_cbc: c_int = 37; -pub const NID_rc2_ecb: c_int = 38; -pub const NID_rc2_cfb64: c_int = 39; -pub const NID_rc2_ofb64: c_int = 40; -pub const NID_rc2_40_cbc: c_int = 98; -pub const NID_rc2_64_cbc: c_int = 166; -pub const NID_rc4: c_int = 5; -pub const NID_rc4_40: c_int = 97; -pub const NID_des_ede3_cbc: c_int = 44; -pub const NID_rc5_cbc: c_int = 120; -pub const NID_rc5_ecb: c_int = 121; -pub const NID_rc5_cfb64: c_int = 122; -pub const NID_rc5_ofb64: c_int = 123; -pub const NID_ms_ext_req: c_int = 171; -pub const NID_ms_code_ind: c_int = 134; -pub const NID_ms_code_com: c_int = 135; -pub const NID_ms_ctl_sign: c_int = 136; -pub const NID_ms_sgc: c_int = 137; -pub const NID_ms_efs: c_int = 138; -pub const NID_ms_smartcard_login: c_int = 648; -pub const NID_ms_upn: c_int = 649; -pub const NID_idea_cbc: c_int = 34; -pub const NID_idea_ecb: c_int = 36; -pub const NID_idea_cfb64: c_int = 35; -pub const NID_idea_ofb64: c_int = 46; -pub const NID_bf_cbc: c_int = 91; -pub const NID_bf_ecb: c_int = 92; -pub const NID_bf_cfb64: c_int = 93; -pub const NID_bf_ofb64: c_int = 94; -pub const NID_id_pkix: c_int = 127; -pub const NID_id_pkix_mod: c_int = 258; -pub const NID_id_pe: c_int = 175; -pub const NID_id_qt: c_int = 259; -pub const NID_id_kp: c_int = 128; -pub const NID_id_it: c_int = 260; -pub const NID_id_pkip: c_int = 261; -pub const NID_id_alg: c_int = 262; -pub const NID_id_cmc: c_int = 263; -pub const NID_id_on: c_int = 264; -pub const NID_id_pda: c_int = 265; -pub const NID_id_aca: c_int = 266; -pub const NID_id_qcs: c_int = 267; -pub const NID_id_cct: c_int = 268; -pub const NID_id_ppl: c_int = 662; -pub const NID_id_ad: c_int = 176; -pub const NID_id_pkix1_explicit_88: c_int = 269; -pub const NID_id_pkix1_implicit_88: c_int = 270; -pub const NID_id_pkix1_explicit_93: c_int = 271; -pub const NID_id_pkix1_implicit_93: c_int = 272; -pub const NID_id_mod_crmf: c_int = 273; -pub const NID_id_mod_cmc: c_int = 274; -pub const NID_id_mod_kea_profile_88: c_int = 275; -pub const NID_id_mod_kea_profile_93: c_int = 276; -pub const NID_id_mod_cmp: c_int = 277; -pub const NID_id_mod_qualified_cert_88: c_int = 278; -pub const NID_id_mod_qualified_cert_93: c_int = 279; -pub const NID_id_mod_attribute_cert: c_int = 280; -pub const NID_id_mod_timestamp_protocol: c_int = 281; -pub const NID_id_mod_ocsp: c_int = 282; -pub const NID_id_mod_dvcs: c_int = 283; -pub const NID_id_mod_cmp2000: c_int = 284; -pub const NID_info_access: c_int = 177; -pub const NID_biometricInfo: c_int = 285; -pub const NID_qcStatements: c_int = 286; -pub const NID_ac_auditEntity: c_int = 287; -pub const NID_ac_targeting: c_int = 288; -pub const NID_aaControls: c_int = 289; -pub const NID_sbgp_ipAddrBlock: c_int = 290; -pub const NID_sbgp_autonomousSysNum: c_int = 291; -pub const NID_sbgp_routerIdentifier: c_int = 292; -pub const NID_ac_proxying: c_int = 397; -pub const NID_sinfo_access: c_int = 398; -pub const NID_proxyCertInfo: c_int = 663; -pub const NID_id_qt_cps: c_int = 164; -pub const NID_id_qt_unotice: c_int = 165; -pub const NID_textNotice: c_int = 293; -pub const NID_server_auth: c_int = 129; -pub const NID_client_auth: c_int = 130; -pub const NID_code_sign: c_int = 131; -pub const NID_email_protect: c_int = 132; -pub const NID_ipsecEndSystem: c_int = 294; -pub const NID_ipsecTunnel: c_int = 295; -pub const NID_ipsecUser: c_int = 296; -pub const NID_time_stamp: c_int = 133; -pub const NID_OCSP_sign: c_int = 180; -pub const NID_dvcs: c_int = 297; -pub const NID_id_it_caProtEncCert: c_int = 298; -pub const NID_id_it_signKeyPairTypes: c_int = 299; -pub const NID_id_it_encKeyPairTypes: c_int = 300; -pub const NID_id_it_preferredSymmAlg: c_int = 301; -pub const NID_id_it_caKeyUpdateInfo: c_int = 302; -pub const NID_id_it_currentCRL: c_int = 303; -pub const NID_id_it_unsupportedOIDs: c_int = 304; -pub const NID_id_it_subscriptionRequest: c_int = 305; -pub const NID_id_it_subscriptionResponse: c_int = 306; -pub const NID_id_it_keyPairParamReq: c_int = 307; -pub const NID_id_it_keyPairParamRep: c_int = 308; -pub const NID_id_it_revPassphrase: c_int = 309; -pub const NID_id_it_implicitConfirm: c_int = 310; -pub const NID_id_it_confirmWaitTime: c_int = 311; -pub const NID_id_it_origPKIMessage: c_int = 312; -pub const NID_id_it_suppLangTags: c_int = 784; -pub const NID_id_regCtrl: c_int = 313; -pub const NID_id_regInfo: c_int = 314; -pub const NID_id_regCtrl_regToken: c_int = 315; -pub const NID_id_regCtrl_authenticator: c_int = 316; -pub const NID_id_regCtrl_pkiPublicationInfo: c_int = 317; -pub const NID_id_regCtrl_pkiArchiveOptions: c_int = 318; -pub const NID_id_regCtrl_oldCertID: c_int = 319; -pub const NID_id_regCtrl_protocolEncrKey: c_int = 320; -pub const NID_id_regInfo_utf8Pairs: c_int = 321; -pub const NID_id_regInfo_certReq: c_int = 322; -pub const NID_id_alg_des40: c_int = 323; -pub const NID_id_alg_noSignature: c_int = 324; -pub const NID_id_alg_dh_sig_hmac_sha1: c_int = 325; -pub const NID_id_alg_dh_pop: c_int = 326; -pub const NID_id_cmc_statusInfo: c_int = 327; -pub const NID_id_cmc_identification: c_int = 328; -pub const NID_id_cmc_identityProof: c_int = 329; -pub const NID_id_cmc_dataReturn: c_int = 330; -pub const NID_id_cmc_transactionId: c_int = 331; -pub const NID_id_cmc_senderNonce: c_int = 332; -pub const NID_id_cmc_recipientNonce: c_int = 333; -pub const NID_id_cmc_addExtensions: c_int = 334; -pub const NID_id_cmc_encryptedPOP: c_int = 335; -pub const NID_id_cmc_decryptedPOP: c_int = 336; -pub const NID_id_cmc_lraPOPWitness: c_int = 337; -pub const NID_id_cmc_getCert: c_int = 338; -pub const NID_id_cmc_getCRL: c_int = 339; -pub const NID_id_cmc_revokeRequest: c_int = 340; -pub const NID_id_cmc_regInfo: c_int = 341; -pub const NID_id_cmc_responseInfo: c_int = 342; -pub const NID_id_cmc_queryPending: c_int = 343; -pub const NID_id_cmc_popLinkRandom: c_int = 344; -pub const NID_id_cmc_popLinkWitness: c_int = 345; -pub const NID_id_cmc_confirmCertAcceptance: c_int = 346; -pub const NID_id_on_personalData: c_int = 347; -pub const NID_id_on_permanentIdentifier: c_int = 858; -pub const NID_id_pda_dateOfBirth: c_int = 348; -pub const NID_id_pda_placeOfBirth: c_int = 349; -pub const NID_id_pda_gender: c_int = 351; -pub const NID_id_pda_countryOfCitizenship: c_int = 352; -pub const NID_id_pda_countryOfResidence: c_int = 353; -pub const NID_id_aca_authenticationInfo: c_int = 354; -pub const NID_id_aca_accessIdentity: c_int = 355; -pub const NID_id_aca_chargingIdentity: c_int = 356; -pub const NID_id_aca_group: c_int = 357; -pub const NID_id_aca_role: c_int = 358; -pub const NID_id_aca_encAttrs: c_int = 399; -pub const NID_id_qcs_pkixQCSyntax_v1: c_int = 359; -pub const NID_id_cct_crs: c_int = 360; -pub const NID_id_cct_PKIData: c_int = 361; -pub const NID_id_cct_PKIResponse: c_int = 362; -pub const NID_id_ppl_anyLanguage: c_int = 664; -pub const NID_id_ppl_inheritAll: c_int = 665; -pub const NID_Independent: c_int = 667; -pub const NID_ad_OCSP: c_int = 178; -pub const NID_ad_ca_issuers: c_int = 179; -pub const NID_ad_timeStamping: c_int = 363; -pub const NID_ad_dvcs: c_int = 364; -pub const NID_caRepository: c_int = 785; -pub const NID_id_pkix_OCSP_basic: c_int = 365; -pub const NID_id_pkix_OCSP_Nonce: c_int = 366; -pub const NID_id_pkix_OCSP_CrlID: c_int = 367; -pub const NID_id_pkix_OCSP_acceptableResponses: c_int = 368; -pub const NID_id_pkix_OCSP_noCheck: c_int = 369; -pub const NID_id_pkix_OCSP_archiveCutoff: c_int = 370; -pub const NID_id_pkix_OCSP_serviceLocator: c_int = 371; -pub const NID_id_pkix_OCSP_extendedStatus: c_int = 372; -pub const NID_id_pkix_OCSP_valid: c_int = 373; -pub const NID_id_pkix_OCSP_path: c_int = 374; -pub const NID_id_pkix_OCSP_trustRoot: c_int = 375; -pub const NID_algorithm: c_int = 376; -pub const NID_md5WithRSA: c_int = 104; -pub const NID_des_ecb: c_int = 29; -pub const NID_des_cbc: c_int = 31; -pub const NID_des_ofb64: c_int = 45; -pub const NID_des_cfb64: c_int = 30; -pub const NID_rsaSignature: c_int = 377; -pub const NID_dsa_2: c_int = 67; -pub const NID_dsaWithSHA: c_int = 66; -pub const NID_shaWithRSAEncryption: c_int = 42; -pub const NID_des_ede_ecb: c_int = 32; -pub const NID_des_ede3_ecb: c_int = 33; -pub const NID_des_ede_cbc: c_int = 43; -pub const NID_des_ede_cfb64: c_int = 60; -pub const NID_des_ede3_cfb64: c_int = 61; -pub const NID_des_ede_ofb64: c_int = 62; -pub const NID_des_ede3_ofb64: c_int = 63; -pub const NID_desx_cbc: c_int = 80; -pub const NID_sha: c_int = 41; -pub const NID_sha1: c_int = 64; -pub const NID_dsaWithSHA1_2: c_int = 70; -pub const NID_sha1WithRSA: c_int = 115; -pub const NID_ripemd160: c_int = 117; -pub const NID_ripemd160WithRSA: c_int = 119; -pub const NID_sxnet: c_int = 143; -pub const NID_X500: c_int = 11; -pub const NID_X509: c_int = 12; -pub const NID_commonName: c_int = 13; -pub const NID_surname: c_int = 100; -pub const NID_serialNumber: c_int = 105; -pub const NID_countryName: c_int = 14; -pub const NID_localityName: c_int = 15; -pub const NID_stateOrProvinceName: c_int = 16; -pub const NID_streetAddress: c_int = 660; -pub const NID_organizationName: c_int = 17; -pub const NID_organizationalUnitName: c_int = 18; -pub const NID_title: c_int = 106; -pub const NID_description: c_int = 107; -pub const NID_searchGuide: c_int = 859; -pub const NID_businessCategory: c_int = 860; -pub const NID_postalAddress: c_int = 861; -pub const NID_postalCode: c_int = 661; -pub const NID_postOfficeBox: c_int = 862; -pub const NID_physicalDeliveryOfficeName: c_int = 863; -pub const NID_telephoneNumber: c_int = 864; -pub const NID_telexNumber: c_int = 865; -pub const NID_teletexTerminalIdentifier: c_int = 866; -pub const NID_facsimileTelephoneNumber: c_int = 867; -pub const NID_x121Address: c_int = 868; -pub const NID_internationaliSDNNumber: c_int = 869; -pub const NID_registeredAddress: c_int = 870; -pub const NID_destinationIndicator: c_int = 871; -pub const NID_preferredDeliveryMethod: c_int = 872; -pub const NID_presentationAddress: c_int = 873; -pub const NID_supportedApplicationContext: c_int = 874; -pub const NID_member: c_int = 875; -pub const NID_owner: c_int = 876; -pub const NID_roleOccupant: c_int = 877; -pub const NID_seeAlso: c_int = 878; -pub const NID_userPassword: c_int = 879; -pub const NID_userCertificate: c_int = 880; -pub const NID_cACertificate: c_int = 881; -pub const NID_authorityRevocationList: c_int = 882; -pub const NID_certificateRevocationList: c_int = 883; -pub const NID_crossCertificatePair: c_int = 884; -pub const NID_name: c_int = 173; -pub const NID_givenName: c_int = 99; -pub const NID_initials: c_int = 101; -pub const NID_generationQualifier: c_int = 509; -pub const NID_x500UniqueIdentifier: c_int = 503; -pub const NID_dnQualifier: c_int = 174; -pub const NID_enhancedSearchGuide: c_int = 885; -pub const NID_protocolInformation: c_int = 886; -pub const NID_distinguishedName: c_int = 887; -pub const NID_uniqueMember: c_int = 888; -pub const NID_houseIdentifier: c_int = 889; -pub const NID_supportedAlgorithms: c_int = 890; -pub const NID_deltaRevocationList: c_int = 891; -pub const NID_dmdName: c_int = 892; -pub const NID_pseudonym: c_int = 510; -pub const NID_role: c_int = 400; -pub const NID_X500algorithms: c_int = 378; -pub const NID_rsa: c_int = 19; -pub const NID_mdc2WithRSA: c_int = 96; -pub const NID_mdc2: c_int = 95; -pub const NID_id_ce: c_int = 81; -pub const NID_subject_directory_attributes: c_int = 769; -pub const NID_subject_key_identifier: c_int = 82; -pub const NID_key_usage: c_int = 83; -pub const NID_private_key_usage_period: c_int = 84; -pub const NID_subject_alt_name: c_int = 85; -pub const NID_issuer_alt_name: c_int = 86; -pub const NID_basic_constraints: c_int = 87; -pub const NID_crl_number: c_int = 88; -pub const NID_crl_reason: c_int = 141; -pub const NID_invalidity_date: c_int = 142; -pub const NID_delta_crl: c_int = 140; -pub const NID_issuing_distribution_point: c_int = 770; -pub const NID_certificate_issuer: c_int = 771; -pub const NID_name_constraints: c_int = 666; -pub const NID_crl_distribution_points: c_int = 103; -pub const NID_certificate_policies: c_int = 89; -pub const NID_any_policy: c_int = 746; -pub const NID_policy_mappings: c_int = 747; -pub const NID_authority_key_identifier: c_int = 90; -pub const NID_policy_constraints: c_int = 401; -pub const NID_ext_key_usage: c_int = 126; -pub const NID_freshest_crl: c_int = 857; -pub const NID_inhibit_any_policy: c_int = 748; -pub const NID_target_information: c_int = 402; -pub const NID_no_rev_avail: c_int = 403; -pub const NID_anyExtendedKeyUsage: c_int = 910; -pub const NID_netscape: c_int = 57; -pub const NID_netscape_cert_extension: c_int = 58; -pub const NID_netscape_data_type: c_int = 59; -pub const NID_netscape_cert_type: c_int = 71; -pub const NID_netscape_base_url: c_int = 72; -pub const NID_netscape_revocation_url: c_int = 73; -pub const NID_netscape_ca_revocation_url: c_int = 74; -pub const NID_netscape_renewal_url: c_int = 75; -pub const NID_netscape_ca_policy_url: c_int = 76; -pub const NID_netscape_ssl_server_name: c_int = 77; -pub const NID_netscape_comment: c_int = 78; -pub const NID_netscape_cert_sequence: c_int = 79; -pub const NID_ns_sgc: c_int = 139; -pub const NID_org: c_int = 379; -pub const NID_dod: c_int = 380; -pub const NID_iana: c_int = 381; -pub const NID_Directory: c_int = 382; -pub const NID_Management: c_int = 383; -pub const NID_Experimental: c_int = 384; -pub const NID_Private: c_int = 385; -pub const NID_Security: c_int = 386; -pub const NID_SNMPv2: c_int = 387; -pub const NID_Mail: c_int = 388; -pub const NID_Enterprises: c_int = 389; -pub const NID_dcObject: c_int = 390; -pub const NID_mime_mhs: c_int = 504; -pub const NID_mime_mhs_headings: c_int = 505; -pub const NID_mime_mhs_bodies: c_int = 506; -pub const NID_id_hex_partial_message: c_int = 507; -pub const NID_id_hex_multipart_message: c_int = 508; -pub const NID_zlib_compression: c_int = 125; -pub const NID_aes_128_ecb: c_int = 418; -pub const NID_aes_128_cbc: c_int = 419; -pub const NID_aes_128_ofb128: c_int = 420; -pub const NID_aes_128_cfb128: c_int = 421; -pub const NID_id_aes128_wrap: c_int = 788; -pub const NID_aes_128_gcm: c_int = 895; -pub const NID_aes_128_ccm: c_int = 896; -pub const NID_id_aes128_wrap_pad: c_int = 897; -pub const NID_aes_192_ecb: c_int = 422; -pub const NID_aes_192_cbc: c_int = 423; -pub const NID_aes_192_ofb128: c_int = 424; -pub const NID_aes_192_cfb128: c_int = 425; -pub const NID_id_aes192_wrap: c_int = 789; -pub const NID_aes_192_gcm: c_int = 898; -pub const NID_aes_192_ccm: c_int = 899; -pub const NID_id_aes192_wrap_pad: c_int = 900; -pub const NID_aes_256_ecb: c_int = 426; -pub const NID_aes_256_cbc: c_int = 427; -pub const NID_aes_256_ofb128: c_int = 428; -pub const NID_aes_256_cfb128: c_int = 429; -pub const NID_id_aes256_wrap: c_int = 790; -pub const NID_aes_256_gcm: c_int = 901; -pub const NID_aes_256_ccm: c_int = 902; -pub const NID_id_aes256_wrap_pad: c_int = 903; -pub const NID_aes_128_cfb1: c_int = 650; -pub const NID_aes_192_cfb1: c_int = 651; -pub const NID_aes_256_cfb1: c_int = 652; -pub const NID_aes_128_cfb8: c_int = 653; -pub const NID_aes_192_cfb8: c_int = 654; -pub const NID_aes_256_cfb8: c_int = 655; -pub const NID_aes_128_ctr: c_int = 904; -pub const NID_aes_192_ctr: c_int = 905; -pub const NID_aes_256_ctr: c_int = 906; -pub const NID_aes_128_xts: c_int = 913; -pub const NID_aes_256_xts: c_int = 914; -pub const NID_des_cfb1: c_int = 656; -pub const NID_des_cfb8: c_int = 657; -pub const NID_des_ede3_cfb1: c_int = 658; -pub const NID_des_ede3_cfb8: c_int = 659; -pub const NID_sha256: c_int = 672; -pub const NID_sha384: c_int = 673; -pub const NID_sha512: c_int = 674; -pub const NID_sha224: c_int = 675; -pub const NID_dsa_with_SHA224: c_int = 802; -pub const NID_dsa_with_SHA256: c_int = 803; -pub const NID_hold_instruction_code: c_int = 430; -pub const NID_hold_instruction_none: c_int = 431; -pub const NID_hold_instruction_call_issuer: c_int = 432; -pub const NID_hold_instruction_reject: c_int = 433; -pub const NID_data: c_int = 434; -pub const NID_pss: c_int = 435; -pub const NID_ucl: c_int = 436; -pub const NID_pilot: c_int = 437; -pub const NID_pilotAttributeType: c_int = 438; -pub const NID_pilotAttributeSyntax: c_int = 439; -pub const NID_pilotObjectClass: c_int = 440; -pub const NID_pilotGroups: c_int = 441; -pub const NID_iA5StringSyntax: c_int = 442; -pub const NID_caseIgnoreIA5StringSyntax: c_int = 443; -pub const NID_pilotObject: c_int = 444; -pub const NID_pilotPerson: c_int = 445; -pub const NID_account: c_int = 446; -pub const NID_document: c_int = 447; -pub const NID_room: c_int = 448; -pub const NID_documentSeries: c_int = 449; -pub const NID_Domain: c_int = 392; -pub const NID_rFC822localPart: c_int = 450; -pub const NID_dNSDomain: c_int = 451; -pub const NID_domainRelatedObject: c_int = 452; -pub const NID_friendlyCountry: c_int = 453; -pub const NID_simpleSecurityObject: c_int = 454; -pub const NID_pilotOrganization: c_int = 455; -pub const NID_pilotDSA: c_int = 456; -pub const NID_qualityLabelledData: c_int = 457; -pub const NID_userId: c_int = 458; -pub const NID_textEncodedORAddress: c_int = 459; -pub const NID_rfc822Mailbox: c_int = 460; -pub const NID_info: c_int = 461; -pub const NID_favouriteDrink: c_int = 462; -pub const NID_roomNumber: c_int = 463; -pub const NID_photo: c_int = 464; -pub const NID_userClass: c_int = 465; -pub const NID_host: c_int = 466; -pub const NID_manager: c_int = 467; -pub const NID_documentIdentifier: c_int = 468; -pub const NID_documentTitle: c_int = 469; -pub const NID_documentVersion: c_int = 470; -pub const NID_documentAuthor: c_int = 471; -pub const NID_documentLocation: c_int = 472; -pub const NID_homeTelephoneNumber: c_int = 473; -pub const NID_secretary: c_int = 474; -pub const NID_otherMailbox: c_int = 475; -pub const NID_lastModifiedTime: c_int = 476; -pub const NID_lastModifiedBy: c_int = 477; -pub const NID_domainComponent: c_int = 391; -pub const NID_aRecord: c_int = 478; -pub const NID_pilotAttributeType27: c_int = 479; -pub const NID_mXRecord: c_int = 480; -pub const NID_nSRecord: c_int = 481; -pub const NID_sOARecord: c_int = 482; -pub const NID_cNAMERecord: c_int = 483; -pub const NID_associatedDomain: c_int = 484; -pub const NID_associatedName: c_int = 485; -pub const NID_homePostalAddress: c_int = 486; -pub const NID_personalTitle: c_int = 487; -pub const NID_mobileTelephoneNumber: c_int = 488; -pub const NID_pagerTelephoneNumber: c_int = 489; -pub const NID_friendlyCountryName: c_int = 490; -pub const NID_organizationalStatus: c_int = 491; -pub const NID_janetMailbox: c_int = 492; -pub const NID_mailPreferenceOption: c_int = 493; -pub const NID_buildingName: c_int = 494; -pub const NID_dSAQuality: c_int = 495; -pub const NID_singleLevelQuality: c_int = 496; -pub const NID_subtreeMinimumQuality: c_int = 497; -pub const NID_subtreeMaximumQuality: c_int = 498; -pub const NID_personalSignature: c_int = 499; -pub const NID_dITRedirect: c_int = 500; -pub const NID_audio: c_int = 501; -pub const NID_documentPublisher: c_int = 502; -pub const NID_id_set: c_int = 512; -pub const NID_set_ctype: c_int = 513; -pub const NID_set_msgExt: c_int = 514; -pub const NID_set_attr: c_int = 515; -pub const NID_set_policy: c_int = 516; -pub const NID_set_certExt: c_int = 517; -pub const NID_set_brand: c_int = 518; -pub const NID_setct_PANData: c_int = 519; -pub const NID_setct_PANToken: c_int = 520; -pub const NID_setct_PANOnly: c_int = 521; -pub const NID_setct_OIData: c_int = 522; -pub const NID_setct_PI: c_int = 523; -pub const NID_setct_PIData: c_int = 524; -pub const NID_setct_PIDataUnsigned: c_int = 525; -pub const NID_setct_HODInput: c_int = 526; -pub const NID_setct_AuthResBaggage: c_int = 527; -pub const NID_setct_AuthRevReqBaggage: c_int = 528; -pub const NID_setct_AuthRevResBaggage: c_int = 529; -pub const NID_setct_CapTokenSeq: c_int = 530; -pub const NID_setct_PInitResData: c_int = 531; -pub const NID_setct_PI_TBS: c_int = 532; -pub const NID_setct_PResData: c_int = 533; -pub const NID_setct_AuthReqTBS: c_int = 534; -pub const NID_setct_AuthResTBS: c_int = 535; -pub const NID_setct_AuthResTBSX: c_int = 536; -pub const NID_setct_AuthTokenTBS: c_int = 537; -pub const NID_setct_CapTokenData: c_int = 538; -pub const NID_setct_CapTokenTBS: c_int = 539; -pub const NID_setct_AcqCardCodeMsg: c_int = 540; -pub const NID_setct_AuthRevReqTBS: c_int = 541; -pub const NID_setct_AuthRevResData: c_int = 542; -pub const NID_setct_AuthRevResTBS: c_int = 543; -pub const NID_setct_CapReqTBS: c_int = 544; -pub const NID_setct_CapReqTBSX: c_int = 545; -pub const NID_setct_CapResData: c_int = 546; -pub const NID_setct_CapRevReqTBS: c_int = 547; -pub const NID_setct_CapRevReqTBSX: c_int = 548; -pub const NID_setct_CapRevResData: c_int = 549; -pub const NID_setct_CredReqTBS: c_int = 550; -pub const NID_setct_CredReqTBSX: c_int = 551; -pub const NID_setct_CredResData: c_int = 552; -pub const NID_setct_CredRevReqTBS: c_int = 553; -pub const NID_setct_CredRevReqTBSX: c_int = 554; -pub const NID_setct_CredRevResData: c_int = 555; -pub const NID_setct_PCertReqData: c_int = 556; -pub const NID_setct_PCertResTBS: c_int = 557; -pub const NID_setct_BatchAdminReqData: c_int = 558; -pub const NID_setct_BatchAdminResData: c_int = 559; -pub const NID_setct_CardCInitResTBS: c_int = 560; -pub const NID_setct_MeAqCInitResTBS: c_int = 561; -pub const NID_setct_RegFormResTBS: c_int = 562; -pub const NID_setct_CertReqData: c_int = 563; -pub const NID_setct_CertReqTBS: c_int = 564; -pub const NID_setct_CertResData: c_int = 565; -pub const NID_setct_CertInqReqTBS: c_int = 566; -pub const NID_setct_ErrorTBS: c_int = 567; -pub const NID_setct_PIDualSignedTBE: c_int = 568; -pub const NID_setct_PIUnsignedTBE: c_int = 569; -pub const NID_setct_AuthReqTBE: c_int = 570; -pub const NID_setct_AuthResTBE: c_int = 571; -pub const NID_setct_AuthResTBEX: c_int = 572; -pub const NID_setct_AuthTokenTBE: c_int = 573; -pub const NID_setct_CapTokenTBE: c_int = 574; -pub const NID_setct_CapTokenTBEX: c_int = 575; -pub const NID_setct_AcqCardCodeMsgTBE: c_int = 576; -pub const NID_setct_AuthRevReqTBE: c_int = 577; -pub const NID_setct_AuthRevResTBE: c_int = 578; -pub const NID_setct_AuthRevResTBEB: c_int = 579; -pub const NID_setct_CapReqTBE: c_int = 580; -pub const NID_setct_CapReqTBEX: c_int = 581; -pub const NID_setct_CapResTBE: c_int = 582; -pub const NID_setct_CapRevReqTBE: c_int = 583; -pub const NID_setct_CapRevReqTBEX: c_int = 584; -pub const NID_setct_CapRevResTBE: c_int = 585; -pub const NID_setct_CredReqTBE: c_int = 586; -pub const NID_setct_CredReqTBEX: c_int = 587; -pub const NID_setct_CredResTBE: c_int = 588; -pub const NID_setct_CredRevReqTBE: c_int = 589; -pub const NID_setct_CredRevReqTBEX: c_int = 590; -pub const NID_setct_CredRevResTBE: c_int = 591; -pub const NID_setct_BatchAdminReqTBE: c_int = 592; -pub const NID_setct_BatchAdminResTBE: c_int = 593; -pub const NID_setct_RegFormReqTBE: c_int = 594; -pub const NID_setct_CertReqTBE: c_int = 595; -pub const NID_setct_CertReqTBEX: c_int = 596; -pub const NID_setct_CertResTBE: c_int = 597; -pub const NID_setct_CRLNotificationTBS: c_int = 598; -pub const NID_setct_CRLNotificationResTBS: c_int = 599; -pub const NID_setct_BCIDistributionTBS: c_int = 600; -pub const NID_setext_genCrypt: c_int = 601; -pub const NID_setext_miAuth: c_int = 602; -pub const NID_setext_pinSecure: c_int = 603; -pub const NID_setext_pinAny: c_int = 604; -pub const NID_setext_track2: c_int = 605; -pub const NID_setext_cv: c_int = 606; -pub const NID_set_policy_root: c_int = 607; -pub const NID_setCext_hashedRoot: c_int = 608; -pub const NID_setCext_certType: c_int = 609; -pub const NID_setCext_merchData: c_int = 610; -pub const NID_setCext_cCertRequired: c_int = 611; -pub const NID_setCext_tunneling: c_int = 612; -pub const NID_setCext_setExt: c_int = 613; -pub const NID_setCext_setQualf: c_int = 614; -pub const NID_setCext_PGWYcapabilities: c_int = 615; -pub const NID_setCext_TokenIdentifier: c_int = 616; -pub const NID_setCext_Track2Data: c_int = 617; -pub const NID_setCext_TokenType: c_int = 618; -pub const NID_setCext_IssuerCapabilities: c_int = 619; -pub const NID_setAttr_Cert: c_int = 620; -pub const NID_setAttr_PGWYcap: c_int = 621; -pub const NID_setAttr_TokenType: c_int = 622; -pub const NID_setAttr_IssCap: c_int = 623; -pub const NID_set_rootKeyThumb: c_int = 624; -pub const NID_set_addPolicy: c_int = 625; -pub const NID_setAttr_Token_EMV: c_int = 626; -pub const NID_setAttr_Token_B0Prime: c_int = 627; -pub const NID_setAttr_IssCap_CVM: c_int = 628; -pub const NID_setAttr_IssCap_T2: c_int = 629; -pub const NID_setAttr_IssCap_Sig: c_int = 630; -pub const NID_setAttr_GenCryptgrm: c_int = 631; -pub const NID_setAttr_T2Enc: c_int = 632; -pub const NID_setAttr_T2cleartxt: c_int = 633; -pub const NID_setAttr_TokICCsig: c_int = 634; -pub const NID_setAttr_SecDevSig: c_int = 635; -pub const NID_set_brand_IATA_ATA: c_int = 636; -pub const NID_set_brand_Diners: c_int = 637; -pub const NID_set_brand_AmericanExpress: c_int = 638; -pub const NID_set_brand_JCB: c_int = 639; -pub const NID_set_brand_Visa: c_int = 640; -pub const NID_set_brand_MasterCard: c_int = 641; -pub const NID_set_brand_Novus: c_int = 642; -pub const NID_des_cdmf: c_int = 643; -pub const NID_rsaOAEPEncryptionSET: c_int = 644; -pub const NID_ipsec3: c_int = 749; -pub const NID_ipsec4: c_int = 750; -pub const NID_whirlpool: c_int = 804; -pub const NID_cryptopro: c_int = 805; -pub const NID_cryptocom: c_int = 806; -pub const NID_id_GostR3411_94_with_GostR3410_2001: c_int = 807; -pub const NID_id_GostR3411_94_with_GostR3410_94: c_int = 808; -pub const NID_id_GostR3411_94: c_int = 809; -pub const NID_id_HMACGostR3411_94: c_int = 810; -pub const NID_id_GostR3410_2001: c_int = 811; -pub const NID_id_GostR3410_94: c_int = 812; -pub const NID_id_Gost28147_89: c_int = 813; -pub const NID_gost89_cnt: c_int = 814; -pub const NID_id_Gost28147_89_MAC: c_int = 815; -pub const NID_id_GostR3411_94_prf: c_int = 816; -pub const NID_id_GostR3410_2001DH: c_int = 817; -pub const NID_id_GostR3410_94DH: c_int = 818; -pub const NID_id_Gost28147_89_CryptoPro_KeyMeshing: c_int = 819; -pub const NID_id_Gost28147_89_None_KeyMeshing: c_int = 820; -pub const NID_id_GostR3411_94_TestParamSet: c_int = 821; -pub const NID_id_GostR3411_94_CryptoProParamSet: c_int = 822; -pub const NID_id_Gost28147_89_TestParamSet: c_int = 823; -pub const NID_id_Gost28147_89_CryptoPro_A_ParamSet: c_int = 824; -pub const NID_id_Gost28147_89_CryptoPro_B_ParamSet: c_int = 825; -pub const NID_id_Gost28147_89_CryptoPro_C_ParamSet: c_int = 826; -pub const NID_id_Gost28147_89_CryptoPro_D_ParamSet: c_int = 827; -pub const NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet: c_int = 828; -pub const NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet: c_int = 829; -pub const NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet: c_int = 830; -pub const NID_id_GostR3410_94_TestParamSet: c_int = 831; -pub const NID_id_GostR3410_94_CryptoPro_A_ParamSet: c_int = 832; -pub const NID_id_GostR3410_94_CryptoPro_B_ParamSet: c_int = 833; -pub const NID_id_GostR3410_94_CryptoPro_C_ParamSet: c_int = 834; -pub const NID_id_GostR3410_94_CryptoPro_D_ParamSet: c_int = 835; -pub const NID_id_GostR3410_94_CryptoPro_XchA_ParamSet: c_int = 836; -pub const NID_id_GostR3410_94_CryptoPro_XchB_ParamSet: c_int = 837; -pub const NID_id_GostR3410_94_CryptoPro_XchC_ParamSet: c_int = 838; -pub const NID_id_GostR3410_2001_TestParamSet: c_int = 839; -pub const NID_id_GostR3410_2001_CryptoPro_A_ParamSet: c_int = 840; -pub const NID_id_GostR3410_2001_CryptoPro_B_ParamSet: c_int = 841; -pub const NID_id_GostR3410_2001_CryptoPro_C_ParamSet: c_int = 842; -pub const NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet: c_int = 843; -pub const NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet: c_int = 844; -pub const NID_id_GostR3410_94_a: c_int = 845; -pub const NID_id_GostR3410_94_aBis: c_int = 846; -pub const NID_id_GostR3410_94_b: c_int = 847; -pub const NID_id_GostR3410_94_bBis: c_int = 848; -pub const NID_id_Gost28147_89_cc: c_int = 849; -pub const NID_id_GostR3410_94_cc: c_int = 850; -pub const NID_id_GostR3410_2001_cc: c_int = 851; -pub const NID_id_GostR3411_94_with_GostR3410_94_cc: c_int = 852; -pub const NID_id_GostR3411_94_with_GostR3410_2001_cc: c_int = 853; -pub const NID_id_GostR3410_2001_ParamSet_cc: c_int = 854; -pub const NID_camellia_128_cbc: c_int = 751; -pub const NID_camellia_192_cbc: c_int = 752; -pub const NID_camellia_256_cbc: c_int = 753; -pub const NID_id_camellia128_wrap: c_int = 907; -pub const NID_id_camellia192_wrap: c_int = 908; -pub const NID_id_camellia256_wrap: c_int = 909; -pub const NID_camellia_128_ecb: c_int = 754; -pub const NID_camellia_128_ofb128: c_int = 766; -pub const NID_camellia_128_cfb128: c_int = 757; -pub const NID_camellia_192_ecb: c_int = 755; -pub const NID_camellia_192_ofb128: c_int = 767; -pub const NID_camellia_192_cfb128: c_int = 758; -pub const NID_camellia_256_ecb: c_int = 756; -pub const NID_camellia_256_ofb128: c_int = 768; -pub const NID_camellia_256_cfb128: c_int = 759; -pub const NID_camellia_128_cfb1: c_int = 760; -pub const NID_camellia_192_cfb1: c_int = 761; -pub const NID_camellia_256_cfb1: c_int = 762; -pub const NID_camellia_128_cfb8: c_int = 763; -pub const NID_camellia_192_cfb8: c_int = 764; -pub const NID_camellia_256_cfb8: c_int = 765; -pub const NID_kisa: c_int = 773; -pub const NID_seed_ecb: c_int = 776; -pub const NID_seed_cbc: c_int = 777; -pub const NID_seed_cfb128: c_int = 779; -pub const NID_seed_ofb128: c_int = 778; -pub const NID_hmac: c_int = 855; -pub const NID_cmac: c_int = 894; -pub const NID_rc4_hmac_md5: c_int = 915; -pub const NID_aes_128_cbc_hmac_sha1: c_int = 916; -pub const NID_aes_192_cbc_hmac_sha1: c_int = 917; -pub const NID_aes_256_cbc_hmac_sha1: c_int = 918; - -pub const OCSP_NOCERTS: c_ulong = 0x1; -pub const OCSP_NOINTERN: c_ulong = 0x2; -pub const OCSP_NOSIGS: c_ulong = 0x4; -pub const OCSP_NOCHAIN: c_ulong = 0x8; -pub const OCSP_NOVERIFY: c_ulong = 0x10; -pub const OCSP_NOEXPLICIT: c_ulong = 0x20; -pub const OCSP_NOCASIGN: c_ulong = 0x40; -pub const OCSP_NODELEGATED: c_ulong = 0x80; -pub const OCSP_NOCHECKS: c_ulong = 0x100; -pub const OCSP_TRUSTOTHER: c_ulong = 0x200; -pub const OCSP_RESPID_KEY: c_ulong = 0x400; -pub const OCSP_NOTIME: c_ulong = 0x800; - -pub const V_OCSP_CERTSTATUS_GOOD: c_int = 0; -pub const V_OCSP_CERTSTATUS_REVOKED: c_int = 1; -pub const V_OCSP_CERTSTATUS_UNKNOWN: c_int = 2; - -pub const OCSP_REVOKED_STATUS_NOSTATUS: c_int = -1; -pub const OCSP_REVOKED_STATUS_UNSPECIFIED: c_int = 0; -pub const OCSP_REVOKED_STATUS_KEYCOMPROMISE: c_int = 1; -pub const OCSP_REVOKED_STATUS_CACOMPROMISE: c_int = 2; -pub const OCSP_REVOKED_STATUS_AFFILIATIONCHANGED: c_int = 3; -pub const OCSP_REVOKED_STATUS_SUPERSEDED: c_int = 4; -pub const OCSP_REVOKED_STATUS_CESSATIONOFOPERATION: c_int = 5; -pub const OCSP_REVOKED_STATUS_CERTIFICATEHOLD: c_int = 6; -pub const OCSP_REVOKED_STATUS_REMOVEFROMCRL: c_int = 8; - -pub const OCSP_RESPONSE_STATUS_SUCCESSFUL: c_int = 0; -pub const OCSP_RESPONSE_STATUS_MALFORMEDREQUEST: c_int = 1; -pub const OCSP_RESPONSE_STATUS_INTERNALERROR: c_int = 2; -pub const OCSP_RESPONSE_STATUS_TRYLATER: c_int = 3; -pub const OCSP_RESPONSE_STATUS_SIGREQUIRED: c_int = 5; -pub const OCSP_RESPONSE_STATUS_UNAUTHORIZED: c_int = 6; - -pub const OPENSSL_EC_NAMED_CURVE: c_int = 1; - -pub const PKCS5_SALT_LEN: c_int = 8; -pub const PKCS12_DEFAULT_ITER: c_int = 2048; - -pub const RSA_F4: c_long = 0x10001; - -pub const RSA_PKCS1_PADDING: c_int = 1; -pub const RSA_SSLV23_PADDING: c_int = 2; -pub const RSA_NO_PADDING: c_int = 3; -pub const RSA_PKCS1_OAEP_PADDING: c_int = 4; -pub const RSA_X931_PADDING: c_int = 5; - -pub const SHA_LBLOCK: c_int = 16; - -pub const TLS1_AD_UNRECOGNIZED_NAME: c_int = 112; -pub const SSL_AD_UNRECOGNIZED_NAME: c_int = TLS1_AD_UNRECOGNIZED_NAME; - -pub const SSL_CTRL_SET_TMP_DH: c_int = 3; -pub const SSL_CTRL_SET_TMP_ECDH: c_int = 4; -pub const SSL_CTRL_EXTRA_CHAIN_CERT: c_int = 14; -pub const SSL_CTRL_MODE: c_int = 33; -pub const SSL_CTRL_SET_READ_AHEAD: c_int = 41; -pub const SSL_CTRL_SET_SESS_CACHE_MODE: c_int = 44; -pub const SSL_CTRL_SET_TLSEXT_SERVERNAME_CB: c_int = 53; -pub const SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG: c_int = 54; -pub const SSL_CTRL_SET_TLSEXT_HOSTNAME: c_int = 55; -pub const SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB: c_int = 63; -pub const SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG: c_int = 64; -pub const SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE: c_int = 65; -pub const SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP: c_int = 70; -pub const SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP: c_int = 71; -pub const SSL_CTRL_GET_EXTRA_CHAIN_CERTS: c_int = 82; -#[cfg(not(any(ossl101, libressl)))] -pub const SSL_CTRL_SET_VERIFY_CERT_STORE: c_int = 106; - -pub const SSL_MODE_ENABLE_PARTIAL_WRITE: c_long = 0x1; -pub const SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER: c_long = 0x2; -pub const SSL_MODE_AUTO_RETRY: c_long = 0x4; -pub const SSL_MODE_NO_AUTO_CHAIN: c_long = 0x8; -pub const SSL_MODE_RELEASE_BUFFERS: c_long = 0x10; -#[cfg(not(libressl))] -pub const SSL_MODE_SEND_CLIENTHELLO_TIME: c_long = 0x20; -#[cfg(not(libressl))] -pub const SSL_MODE_SEND_SERVERHELLO_TIME: c_long = 0x40; -#[cfg(not(libressl))] -pub const SSL_MODE_SEND_FALLBACK_SCSV: c_long = 0x80; - -pub const SSL_ERROR_NONE: c_int = 0; -pub const SSL_ERROR_SSL: c_int = 1; -pub const SSL_ERROR_SYSCALL: c_int = 5; -pub const SSL_ERROR_WANT_ACCEPT: c_int = 8; -pub const SSL_ERROR_WANT_CONNECT: c_int = 7; -pub const SSL_ERROR_WANT_READ: c_int = 2; -pub const SSL_ERROR_WANT_WRITE: c_int = 3; -pub const SSL_ERROR_WANT_X509_LOOKUP: c_int = 4; -pub const SSL_ERROR_ZERO_RETURN: c_int = 6; -pub const SSL_VERIFY_NONE: c_int = 0; -pub const SSL_VERIFY_PEER: c_int = 1; -pub const SSL_VERIFY_FAIL_IF_NO_PEER_CERT: c_int = 2; - -#[cfg(not(any(libressl261, libressl262, libressl26x, ossl101)))] -pub const SSL_OP_TLSEXT_PADDING: c_ulong = 0x00000010; -#[cfg(any(libressl261, libressl262, libressl26x))] -pub const SSL_OP_TLSEXT_PADDING: c_ulong = 0x0; -pub const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: c_ulong = 0x00000800; -#[cfg(not(any(libressl261, libressl262, libressl26x)))] -pub const SSL_OP_CRYPTOPRO_TLSEXT_BUG: c_ulong = 0x80000000; -#[cfg(any(libressl261, libressl262, libressl26x))] -pub const SSL_OP_CRYPTOPRO_TLSEXT_BUG: c_ulong = 0x0; -pub const SSL_OP_LEGACY_SERVER_CONNECT: c_ulong = 0x00000004; -#[cfg(not(libressl))] -pub const SSL_OP_SAFARI_ECDHE_ECDSA_BUG: c_ulong = 0x00000040; -#[cfg(not(any(libressl, ossl110f, ossl111)))] -pub const SSL_OP_ALL: c_ulong = 0x80000BFF; -#[cfg(any(ossl110f, ossl111))] -pub const SSL_OP_ALL: c_ulong = SSL_OP_CRYPTOPRO_TLSEXT_BUG | SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS - | SSL_OP_LEGACY_SERVER_CONNECT | SSL_OP_TLSEXT_PADDING - | SSL_OP_SAFARI_ECDHE_ECDSA_BUG; -pub const SSL_OP_NO_QUERY_MTU: c_ulong = 0x00001000; -pub const SSL_OP_COOKIE_EXCHANGE: c_ulong = 0x00002000; -pub const SSL_OP_NO_TICKET: c_ulong = 0x00004000; -#[cfg(not(libressl))] -pub const SSL_OP_CISCO_ANYCONNECT: c_ulong = 0x00008000; -pub const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: c_ulong = 0x00010000; -#[cfg(not(libressl))] -pub const SSL_OP_NO_COMPRESSION: c_ulong = 0x00020000; -#[cfg(not(libressl))] -pub const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: c_ulong = 0x00040000; -pub const SSL_OP_CIPHER_SERVER_PREFERENCE: c_ulong = 0x00400000; -pub const SSL_OP_TLS_ROLLBACK_BUG: c_ulong = 0x00800000; -#[cfg(not(libressl))] -pub const SSL_OP_NO_SSLv3: c_ulong = 0x02000000; -pub const SSL_OP_NO_TLSv1: c_ulong = 0x04000000; -pub const SSL_OP_NO_TLSv1_1: c_ulong = 0x10000000; -pub const SSL_OP_NO_TLSv1_2: c_ulong = 0x08000000; -#[cfg(ossl111)] -pub const SSL_OP_NO_TLSv1_3: c_ulong = 0x20000000; - -#[cfg(not(any(ossl101, libressl)))] -pub const SSL_OP_NO_DTLSv1: c_ulong = 0x04000000; -#[cfg(not(any(ossl101, libressl)))] -pub const SSL_OP_NO_DTLSv1_2: c_ulong = 0x08000000; -#[cfg(not(any(ossl101, libressl, ossl111)))] -pub const SSL_OP_NO_SSL_MASK: c_ulong = - SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2; -#[cfg(ossl111)] -pub const SSL_OP_NO_SSL_MASK: c_ulong = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 - | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 - | SSL_OP_NO_TLSv1_3; - -pub const SSL_FILETYPE_PEM: c_int = X509_FILETYPE_PEM; -pub const SSL_FILETYPE_ASN1: c_int = X509_FILETYPE_ASN1; - -pub const SSL_SESS_CACHE_OFF: c_long = 0; -pub const SSL_SESS_CACHE_CLIENT: c_long = 0x1; -pub const SSL_SESS_CACHE_SERVER: c_long = 0x2; -pub const SSL_SESS_CACHE_BOTH: c_long = SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_SERVER; -pub const SSL_SESS_CACHE_NO_AUTO_CLEAR: c_long = 0x80; -pub const SSL_SESS_CACHE_NO_INTERNAL_LOOKUP: c_long = 0x100; -pub const SSL_SESS_CACHE_NO_INTERNAL_STORE: c_long = 0x200; -pub const SSL_SESS_CACHE_NO_INTERNAL: c_long = - SSL_SESS_CACHE_NO_INTERNAL_LOOKUP | SSL_SESS_CACHE_NO_INTERNAL_STORE; - -pub const SSL3_VERSION: c_int = 0x300; -pub const TLS1_VERSION: c_int = 0x301; -pub const TLS1_1_VERSION: c_int = 0x302; -pub const TLS1_2_VERSION: c_int = 0x303; - -pub const TLSEXT_NAMETYPE_host_name: c_int = 0; - -pub const TLSEXT_STATUSTYPE_ocsp: c_int = 1; - -pub const SSL_TLSEXT_ERR_OK: c_int = 0; -pub const SSL_TLSEXT_ERR_ALERT_WARNING: c_int = 1; -pub const SSL_TLSEXT_ERR_ALERT_FATAL: c_int = 2; -pub const SSL_TLSEXT_ERR_NOACK: c_int = 3; - -pub const OPENSSL_NPN_UNSUPPORTED: c_int = 0; -pub const OPENSSL_NPN_NEGOTIATED: c_int = 1; -pub const OPENSSL_NPN_NO_OVERLAP: c_int = 2; - -pub const V_ASN1_GENERALIZEDTIME: c_int = 24; -pub const V_ASN1_UTCTIME: c_int = 23; - -pub const X509_FILETYPE_ASN1: c_int = 2; -pub const X509_FILETYPE_DEFAULT: c_int = 3; -pub const X509_FILETYPE_PEM: c_int = 1; - -pub const X509_V_OK: c_int = 0; -#[cfg(not(libressl))] -pub const X509_V_ERR_UNSPECIFIED: c_int = 1; -pub const X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: c_int = 2; -pub const X509_V_ERR_UNABLE_TO_GET_CRL: c_int = 3; -pub const X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: c_int = 4; -pub const X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: c_int = 5; -pub const X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: c_int = 6; -pub const X509_V_ERR_CERT_SIGNATURE_FAILURE: c_int = 7; -pub const X509_V_ERR_CRL_SIGNATURE_FAILURE: c_int = 8; -pub const X509_V_ERR_CERT_NOT_YET_VALID: c_int = 9; -pub const X509_V_ERR_CERT_HAS_EXPIRED: c_int = 10; -pub const X509_V_ERR_CRL_NOT_YET_VALID: c_int = 11; -pub const X509_V_ERR_CRL_HAS_EXPIRED: c_int = 12; -pub const X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: c_int = 13; -pub const X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: c_int = 14; -pub const X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: c_int = 15; -pub const X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: c_int = 16; -pub const X509_V_ERR_OUT_OF_MEM: c_int = 17; -pub const X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: c_int = 18; -pub const X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: c_int = 19; -pub const X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: c_int = 20; -pub const X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: c_int = 21; -pub const X509_V_ERR_CERT_CHAIN_TOO_LONG: c_int = 22; -pub const X509_V_ERR_CERT_REVOKED: c_int = 23; -pub const X509_V_ERR_INVALID_CA: c_int = 24; -pub const X509_V_ERR_PATH_LENGTH_EXCEEDED: c_int = 25; -pub const X509_V_ERR_INVALID_PURPOSE: c_int = 26; -pub const X509_V_ERR_CERT_UNTRUSTED: c_int = 27; -pub const X509_V_ERR_CERT_REJECTED: c_int = 28; -pub const X509_V_ERR_SUBJECT_ISSUER_MISMATCH: c_int = 29; -pub const X509_V_ERR_AKID_SKID_MISMATCH: c_int = 30; -pub const X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: c_int = 31; -pub const X509_V_ERR_KEYUSAGE_NO_CERTSIGN: c_int = 32; -pub const X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: c_int = 33; -pub const X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: c_int = 34; -pub const X509_V_ERR_KEYUSAGE_NO_CRL_SIGN: c_int = 35; -pub const X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION: c_int = 36; -pub const X509_V_ERR_INVALID_NON_CA: c_int = 37; -pub const X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED: c_int = 38; -pub const X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: c_int = 39; -pub const X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED: c_int = 40; -pub const X509_V_ERR_INVALID_EXTENSION: c_int = 41; -pub const X509_V_ERR_INVALID_POLICY_EXTENSION: c_int = 42; -pub const X509_V_ERR_NO_EXPLICIT_POLICY: c_int = 43; -pub const X509_V_ERR_DIFFERENT_CRL_SCOPE: c_int = 44; -pub const X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE: c_int = 45; -pub const X509_V_ERR_UNNESTED_RESOURCE: c_int = 46; -pub const X509_V_ERR_PERMITTED_VIOLATION: c_int = 47; -pub const X509_V_ERR_EXCLUDED_VIOLATION: c_int = 48; -pub const X509_V_ERR_SUBTREE_MINMAX: c_int = 49; -pub const X509_V_ERR_APPLICATION_VERIFICATION: c_int = 50; -pub const X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: c_int = 51; -pub const X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: c_int = 52; -pub const X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: c_int = 53; -pub const X509_V_ERR_CRL_PATH_VALIDATION_ERROR: c_int = 54; - -#[cfg(not(any(ossl101, libressl)))] -pub const X509_V_ERR_SUITE_B_INVALID_VERSION: c_int = 56; -#[cfg(not(any(ossl101, libressl)))] -pub const X509_V_ERR_SUITE_B_INVALID_ALGORITHM: c_int = 57; -#[cfg(not(any(ossl101, libressl)))] -pub const X509_V_ERR_SUITE_B_INVALID_CURVE: c_int = 58; -#[cfg(not(any(ossl101, libressl)))] -pub const X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM: c_int = 59; -#[cfg(not(any(ossl101, libressl)))] -pub const X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED: c_int = 60; -#[cfg(not(any(ossl101, libressl)))] -pub const X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256: c_int = 61; - -#[cfg(not(any(ossl101, libressl)))] -pub const X509_V_ERR_HOSTNAME_MISMATCH: c_int = 62; -#[cfg(not(any(ossl101, libressl)))] -pub const X509_V_ERR_EMAIL_MISMATCH: c_int = 63; -#[cfg(not(any(ossl101, libressl)))] -pub const X509_V_ERR_IP_ADDRESS_MISMATCH: c_int = 64; - -#[cfg(not(any(ossl101, libressl)))] -pub const X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT: c_uint = 0x1; -#[cfg(not(any(ossl101, libressl)))] -pub const X509_CHECK_FLAG_NO_WILDCARDS: c_uint = 0x2; -#[cfg(not(any(ossl101, libressl)))] -pub const X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS: c_uint = 0x4; -#[cfg(not(any(ossl101, libressl)))] -pub const X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS: c_uint = 0x8; -#[cfg(not(any(ossl101, libressl)))] -pub const X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS: c_uint = 0x10; - -pub const GEN_OTHERNAME: c_int = 0; -pub const GEN_EMAIL: c_int = 1; -pub const GEN_DNS: c_int = 2; -pub const GEN_X400: c_int = 3; -pub const GEN_DIRNAME: c_int = 4; -pub const GEN_EDIPARTY: c_int = 5; -pub const GEN_URI: c_int = 6; -pub const GEN_IPADD: c_int = 7; -pub const GEN_RID: c_int = 8; - -// macros -pub unsafe fn BIO_get_mem_data(b: *mut BIO, pp: *mut *mut c_char) -> c_long { - BIO_ctrl(b, BIO_CTRL_INFO, 0, pp as *mut c_void) -} - -pub unsafe fn BIO_clear_retry_flags(b: *mut BIO) { - BIO_clear_flags(b, BIO_FLAGS_RWS | BIO_FLAGS_SHOULD_RETRY) -} - -pub unsafe fn BIO_set_retry_read(b: *mut BIO) { - BIO_set_flags(b, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY) -} - -pub unsafe fn BIO_set_retry_write(b: *mut BIO) { - BIO_set_flags(b, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY) -} - -// EVP_PKEY_CTX_ctrl macros -pub unsafe fn EVP_PKEY_CTX_set_rsa_padding(ctx: *mut EVP_PKEY_CTX, pad: c_int) -> c_int { - EVP_PKEY_CTX_ctrl( - ctx, - EVP_PKEY_RSA, - -1, - EVP_PKEY_CTRL_RSA_PADDING, - pad, - ptr::null_mut(), - ) -} - -pub unsafe fn EVP_PKEY_CTX_get_rsa_padding(ctx: *mut EVP_PKEY_CTX, ppad: *mut c_int) -> c_int { - EVP_PKEY_CTX_ctrl( - ctx, - EVP_PKEY_RSA, - -1, - EVP_PKEY_CTRL_GET_RSA_PADDING, - 0, - ppad as *mut c_void, - ) -} - -pub unsafe fn SSL_CTX_set_mode(ctx: *mut SSL_CTX, op: c_long) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_MODE, op, ptr::null_mut()) -} - -pub unsafe fn SSL_CTX_set_read_ahead(ctx: *mut SSL_CTX, m: c_long) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_READ_AHEAD, m, ptr::null_mut()) -} - -pub unsafe fn SSL_CTX_set_tmp_dh(ctx: *mut SSL_CTX, dh: *mut DH) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TMP_DH, 0, dh as *mut c_void) -} - -pub unsafe fn SSL_CTX_set_tmp_ecdh(ctx: *mut SSL_CTX, key: *mut EC_KEY) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TMP_ECDH, 0, key as *mut c_void) -} - -pub unsafe fn SSL_set_tmp_dh(ssl: *mut SSL, dh: *mut DH) -> c_long { - SSL_ctrl(ssl, SSL_CTRL_SET_TMP_DH, 0, dh as *mut c_void) -} - -pub unsafe fn SSL_set_tmp_ecdh(ssl: *mut SSL, key: *mut EC_KEY) -> c_long { - SSL_ctrl(ssl, SSL_CTRL_SET_TMP_ECDH, 0, key as *mut c_void) -} - -pub unsafe fn SSL_CTX_add_extra_chain_cert(ctx: *mut SSL_CTX, x509: *mut X509) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_EXTRA_CHAIN_CERT, 0, x509 as *mut c_void) -} - -#[cfg(not(any(ossl101, libressl)))] -pub unsafe fn SSL_CTX_set0_verify_cert_store(ctx: *mut SSL_CTX, st: *mut X509_STORE) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_VERIFY_CERT_STORE, 0, st as *mut c_void) -} - -pub unsafe fn SSL_CTX_set_tlsext_servername_callback( - ctx: *mut SSL_CTX, - cb: Option, -) -> c_long { - SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, cb) -} - -pub unsafe fn SSL_set_tlsext_host_name(s: *mut SSL, name: *mut c_char) -> c_long { - SSL_ctrl( - s, - SSL_CTRL_SET_TLSEXT_HOSTNAME, - TLSEXT_NAMETYPE_host_name as c_long, - name as *mut c_void, - ) -} - -pub unsafe fn SSL_set_tlsext_status_type(s: *mut SSL, type_: c_int) -> c_long { - SSL_ctrl( - s, - SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE, - type_ as c_long, - ptr::null_mut(), - ) -} - -pub unsafe fn SSL_CTX_set_tlsext_status_cb( - ctx: *mut SSL_CTX, - cb: Option c_int>, -) -> c_long { - SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB, mem::transmute(cb)) -} - -pub unsafe fn SSL_CTX_set_tlsext_status_arg(ctx: *mut SSL_CTX, arg: *mut c_void) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG, 0, arg) -} - -pub unsafe fn SSL_CTX_get_extra_chain_certs( - ctx: *mut SSL_CTX, - chain: *mut *mut stack_st_X509, -) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_GET_EXTRA_CHAIN_CERTS, 0, chain as *mut c_void) -} - -pub unsafe fn SSL_CTX_set_session_cache_mode(ctx: *mut SSL_CTX, m: c_long) -> c_long { - SSL_CTX_ctrl(ctx, SSL_CTRL_SET_SESS_CACHE_MODE, m, ptr::null_mut()) -} - -pub unsafe fn SSL_get_tlsext_status_ocsp_resp(ssl: *mut SSL, resp: *mut *mut c_uchar) -> c_long { - SSL_ctrl( - ssl, - SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP, - 0, - resp as *mut c_void, - ) -} - -pub unsafe fn SSL_set_tlsext_status_ocsp_resp( - ssl: *mut SSL, - resp: *mut c_uchar, - len: c_long, -) -> c_long { - SSL_ctrl( - ssl, - SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP, - len, - resp as *mut c_void, - ) -} - -pub fn ERR_GET_LIB(l: c_ulong) -> c_int { - ((l >> 24) & 0x0FF) as c_int -} - -pub fn ERR_GET_FUNC(l: c_ulong) -> c_int { - ((l >> 12) & 0xFFF) as c_int -} - -pub fn ERR_GET_REASON(l: c_ulong) -> c_int { - (l & 0xFFF) as c_int -} - -extern "C" { - pub fn AES_set_encrypt_key(userKey: *const c_uchar, bits: c_int, key: *mut AES_KEY) -> c_int; - pub fn AES_set_decrypt_key(userKey: *const c_uchar, bits: c_int, key: *mut AES_KEY) -> c_int; - pub fn AES_ige_encrypt( - in_: *const c_uchar, - out: *mut c_uchar, - length: size_t, - key: *const AES_KEY, - ivec: *mut c_uchar, - enc: c_int, - ); - - pub fn ASN1_INTEGER_get(dest: *const ASN1_INTEGER) -> c_long; - pub fn ASN1_INTEGER_set(dest: *mut ASN1_INTEGER, value: c_long) -> c_int; - pub fn ASN1_GENERALIZEDTIME_free(tm: *mut ASN1_GENERALIZEDTIME); - pub fn ASN1_GENERALIZEDTIME_print(b: *mut BIO, tm: *const ASN1_GENERALIZEDTIME) -> c_int; - pub fn ASN1_STRING_type_new(ty: c_int) -> *mut ASN1_STRING; - pub fn ASN1_TIME_free(tm: *mut ASN1_TIME); - pub fn ASN1_TIME_print(b: *mut BIO, tm: *const ASN1_TIME) -> c_int; - pub fn ASN1_BIT_STRING_free(x: *mut ASN1_BIT_STRING); - pub fn ASN1_OBJECT_free(x: *mut ASN1_OBJECT); - - pub fn BIO_ctrl(b: *mut BIO, cmd: c_int, larg: c_long, parg: *mut c_void) -> c_long; - pub fn BIO_free_all(b: *mut BIO); - pub fn BIO_new_fp(stream: *mut FILE, close_flag: c_int) -> *mut BIO; - pub fn BIO_new_socket(sock: c_int, close_flag: c_int) -> *mut BIO; - pub fn BIO_read(b: *mut BIO, buf: *mut c_void, len: c_int) -> c_int; - pub fn BIO_write(b: *mut BIO, buf: *const c_void, len: c_int) -> c_int; - #[cfg(any(ossl101, libressl))] - pub fn BIO_new_mem_buf(buf: *mut c_void, len: c_int) -> *mut BIO; - #[cfg(not(any(ossl101, libressl)))] - pub fn BIO_new_mem_buf(buf: *const c_void, len: c_int) -> *mut BIO; - pub fn BIO_set_flags(b: *mut BIO, flags: c_int); - pub fn BIO_clear_flags(b: *mut BIO, flags: c_int); - - pub fn BN_CTX_new() -> *mut BN_CTX; - pub fn BN_CTX_free(ctx: *mut BN_CTX); - - pub fn BN_new() -> *mut BIGNUM; - pub fn BN_dup(n: *const BIGNUM) -> *mut BIGNUM; - pub fn BN_clear(bn: *mut BIGNUM); - pub fn BN_free(bn: *mut BIGNUM); - pub fn BN_clear_free(bn: *mut BIGNUM); - pub fn BN_num_bits(bn: *const BIGNUM) -> c_int; - pub fn BN_set_negative(bn: *mut BIGNUM, n: c_int); - pub fn BN_set_word(bn: *mut BIGNUM, n: BN_ULONG) -> c_int; - pub fn BN_add(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM) -> c_int; - pub fn BN_div( - dv: *mut BIGNUM, - rem: *mut BIGNUM, - a: *const BIGNUM, - b: *const BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn BN_exp(r: *mut BIGNUM, a: *const BIGNUM, p: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_gcd(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_mod_add( - r: *mut BIGNUM, - a: *const BIGNUM, - b: *const BIGNUM, - m: *const BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn BN_mod_exp( - r: *mut BIGNUM, - a: *const BIGNUM, - p: *const BIGNUM, - m: *const BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn BN_mod_inverse( - r: *mut BIGNUM, - a: *const BIGNUM, - n: *const BIGNUM, - ctx: *mut BN_CTX, - ) -> *mut BIGNUM; - pub fn BN_mod_mul( - r: *mut BIGNUM, - a: *const BIGNUM, - b: *const BIGNUM, - m: *const BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn BN_mod_sqr( - r: *mut BIGNUM, - a: *const BIGNUM, - m: *const BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn BN_mod_sub( - r: *mut BIGNUM, - a: *const BIGNUM, - b: *const BIGNUM, - m: *const BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn BN_mul(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_nnmod( - rem: *mut BIGNUM, - a: *const BIGNUM, - m: *const BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn BN_add_word(r: *mut BIGNUM, w: BN_ULONG) -> c_int; - pub fn BN_sub_word(r: *mut BIGNUM, w: BN_ULONG) -> c_int; - pub fn BN_mul_word(r: *mut BIGNUM, w: BN_ULONG) -> c_int; - pub fn BN_div_word(r: *mut BIGNUM, w: BN_ULONG) -> BN_ULONG; - pub fn BN_mod_word(r: *const BIGNUM, w: BN_ULONG) -> BN_ULONG; - pub fn BN_sqr(r: *mut BIGNUM, a: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; - pub fn BN_sub(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM) -> c_int; - pub fn BN_clear_bit(a: *mut BIGNUM, n: c_int) -> c_int; - pub fn BN_is_bit_set(a: *const BIGNUM, n: c_int) -> c_int; - pub fn BN_lshift(r: *mut BIGNUM, a: *const BIGNUM, n: c_int) -> c_int; - pub fn BN_lshift1(r: *mut BIGNUM, a: *const BIGNUM) -> c_int; - pub fn BN_mask_bits(a: *mut BIGNUM, n: c_int) -> c_int; - pub fn BN_rshift(r: *mut BIGNUM, a: *const BIGNUM, n: c_int) -> c_int; - pub fn BN_set_bit(a: *mut BIGNUM, n: c_int) -> c_int; - pub fn BN_rshift1(r: *mut BIGNUM, a: *const BIGNUM) -> c_int; - pub fn BN_cmp(a: *const BIGNUM, b: *const BIGNUM) -> c_int; - pub fn BN_ucmp(a: *const BIGNUM, b: *const BIGNUM) -> c_int; - pub fn BN_generate_prime_ex( - r: *mut BIGNUM, - bits: c_int, - safe: c_int, - add: *const BIGNUM, - rem: *const BIGNUM, - cb: *mut BN_GENCB, - ) -> c_int; - pub fn BN_is_prime_ex( - p: *const BIGNUM, - checks: c_int, - ctx: *mut BN_CTX, - cb: *mut BN_GENCB, - ) -> c_int; - pub fn BN_is_prime_fasttest_ex( - p: *const BIGNUM, - checks: c_int, - ctx: *mut BN_CTX, - do_trial_division: c_int, - cb: *mut BN_GENCB, - ) -> c_int; - pub fn BN_rand(r: *mut BIGNUM, bits: c_int, top: c_int, bottom: c_int) -> c_int; - pub fn BN_pseudo_rand(r: *mut BIGNUM, bits: c_int, top: c_int, bottom: c_int) -> c_int; - pub fn BN_rand_range(r: *mut BIGNUM, range: *const BIGNUM) -> c_int; - pub fn BN_pseudo_rand_range(r: *mut BIGNUM, range: *const BIGNUM) -> c_int; - pub fn BN_bin2bn(s: *const u8, size: c_int, ret: *mut BIGNUM) -> *mut BIGNUM; - pub fn BN_bn2bin(a: *const BIGNUM, to: *mut u8) -> c_int; - pub fn BN_dec2bn(a: *mut *mut BIGNUM, s: *const c_char) -> c_int; - pub fn BN_bn2dec(a: *const BIGNUM) -> *mut c_char; - pub fn BN_hex2bn(a: *mut *mut BIGNUM, s: *const c_char) -> c_int; - pub fn BN_bn2hex(a: *const BIGNUM) -> *mut c_char; - pub fn BN_to_ASN1_INTEGER(bn: *const BIGNUM, ai: *mut ASN1_INTEGER) -> *mut ASN1_INTEGER; - - pub fn NCONF_default() -> *mut CONF_METHOD; - pub fn NCONF_new(meth: *mut CONF_METHOD) -> *mut CONF; - pub fn NCONF_free(conf: *mut CONF); - - pub fn CRYPTO_memcmp(a: *const c_void, b: *const c_void, len: size_t) -> c_int; - - pub fn DH_new() -> *mut DH; - pub fn DH_free(dh: *mut DH); - #[cfg(not(any(ossl101, libressl)))] - pub fn DH_get_1024_160() -> *mut DH; - #[cfg(not(any(ossl101, libressl)))] - pub fn DH_get_2048_224() -> *mut DH; - #[cfg(not(any(ossl101, libressl)))] - pub fn DH_get_2048_256() -> *mut DH; - - pub fn EC_KEY_new() -> *mut EC_KEY; - pub fn EC_KEY_new_by_curve_name(nid: c_int) -> *mut EC_KEY; - pub fn EC_KEY_dup(key: *const EC_KEY) -> *mut EC_KEY; - pub fn EC_KEY_up_ref(key: *mut EC_KEY) -> c_int; - pub fn EC_KEY_set_group(key: *mut EC_KEY, group: *const EC_GROUP) -> c_int; - pub fn EC_KEY_get0_group(key: *const EC_KEY) -> *const EC_GROUP; - pub fn EC_KEY_set_public_key(key: *mut EC_KEY, key: *const EC_POINT) -> c_int; - pub fn EC_KEY_get0_public_key(key: *const EC_KEY) -> *const EC_POINT; - pub fn EC_KEY_set_private_key(key: *mut EC_KEY, key: *const BIGNUM) -> c_int; - pub fn EC_KEY_get0_private_key(key: *const EC_KEY) -> *const BIGNUM; - pub fn EC_KEY_generate_key(key: *mut EC_KEY) -> c_int; - pub fn EC_KEY_check_key(key: *const EC_KEY) -> c_int; - pub fn EC_KEY_free(key: *mut EC_KEY); - pub fn EC_KEY_set_public_key_affine_coordinates( - key: *mut EC_KEY, - x: *mut BIGNUM, - y: *mut BIGNUM, - ) -> c_int; - - #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] - pub fn EC_GF2m_simple_method() -> *const EC_METHOD; - - pub fn EC_GROUP_new(meth: *const EC_METHOD) -> *mut EC_GROUP; - pub fn EC_GROUP_new_curve_GFp( - p: *const BIGNUM, - a: *const BIGNUM, - b: *const BIGNUM, - ctx: *mut BN_CTX, - ) -> *mut EC_GROUP; - #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] - pub fn EC_GROUP_new_curve_GF2m( - p: *const BIGNUM, - a: *const BIGNUM, - b: *const BIGNUM, - ctx: *mut BN_CTX, - ) -> *mut EC_GROUP; - pub fn EC_GROUP_new_by_curve_name(nid: c_int) -> *mut EC_GROUP; - pub fn EC_GROUP_get_curve_GFp( - group: *const EC_GROUP, - p: *mut BIGNUM, - a: *mut BIGNUM, - b: *mut BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] - pub fn EC_GROUP_get_curve_GF2m( - group: *const EC_GROUP, - p: *mut BIGNUM, - a: *mut BIGNUM, - b: *mut BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn EC_GROUP_get_degree(group: *const EC_GROUP) -> c_int; - pub fn EC_GROUP_get_order( - group: *const EC_GROUP, - order: *mut BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn EC_GROUP_set_asn1_flag(key: *mut EC_GROUP, flag: c_int); - - pub fn EC_GROUP_free(group: *mut EC_GROUP); - - pub fn EC_POINT_new(group: *const EC_GROUP) -> *mut EC_POINT; - pub fn EC_POINT_add( - group: *const EC_GROUP, - r: *mut EC_POINT, - a: *const EC_POINT, - b: *const EC_POINT, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn EC_POINT_mul( - group: *const EC_GROUP, - r: *mut EC_POINT, - n: *const BIGNUM, - q: *const EC_POINT, - m: *const BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn EC_POINT_invert(group: *const EC_GROUP, r: *mut EC_POINT, ctx: *mut BN_CTX) -> c_int; - pub fn EC_POINT_point2oct( - group: *const EC_GROUP, - p: *const EC_POINT, - form: point_conversion_form_t, - buf: *mut c_uchar, - len: size_t, - ctx: *mut BN_CTX, - ) -> size_t; - pub fn EC_POINT_oct2point( - group: *const EC_GROUP, - p: *mut EC_POINT, - buf: *const c_uchar, - len: size_t, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn EC_POINT_cmp( - group: *const EC_GROUP, - a: *const EC_POINT, - b: *const EC_POINT, - ctx: *mut BN_CTX, - ) -> c_int; - pub fn EC_POINT_free(point: *mut EC_POINT); - pub fn EC_POINT_get_affine_coordinates_GFp( - group: *const EC_GROUP, - p: *const EC_POINT, - x: *mut BIGNUM, - y: *mut BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] - pub fn EC_POINT_get_affine_coordinates_GF2m( - group: *const EC_GROUP, - p: *const EC_POINT, - x: *mut BIGNUM, - y: *mut BIGNUM, - ctx: *mut BN_CTX, - ) -> c_int; - - pub fn ERR_peek_last_error() -> c_ulong; - pub fn ERR_get_error() -> c_ulong; - pub fn ERR_get_error_line_data( - file: *mut *const c_char, - line: *mut c_int, - data: *mut *const c_char, - flags: *mut c_int, - ) -> c_ulong; - pub fn ERR_lib_error_string(err: c_ulong) -> *const c_char; - pub fn ERR_func_error_string(err: c_ulong) -> *const c_char; - pub fn ERR_reason_error_string(err: c_ulong) -> *const c_char; - pub fn ERR_clear_error(); - - pub fn EVP_md5() -> *const EVP_MD; - pub fn EVP_ripemd160() -> *const EVP_MD; - pub fn EVP_sha1() -> *const EVP_MD; - pub fn EVP_sha224() -> *const EVP_MD; - pub fn EVP_sha256() -> *const EVP_MD; - pub fn EVP_sha384() -> *const EVP_MD; - pub fn EVP_sha512() -> *const EVP_MD; - - pub fn EVP_aes_128_cbc() -> *const EVP_CIPHER; - pub fn EVP_aes_128_ecb() -> *const EVP_CIPHER; - pub fn EVP_aes_128_xts() -> *const EVP_CIPHER; - pub fn EVP_aes_128_ctr() -> *const EVP_CIPHER; - pub fn EVP_aes_128_gcm() -> *const EVP_CIPHER; - pub fn EVP_aes_128_cfb1() -> *const EVP_CIPHER; - pub fn EVP_aes_128_cfb128() -> *const EVP_CIPHER; - pub fn EVP_aes_128_cfb8() -> *const EVP_CIPHER; - pub fn EVP_aes_256_cbc() -> *const EVP_CIPHER; - pub fn EVP_aes_256_ecb() -> *const EVP_CIPHER; - pub fn EVP_aes_256_xts() -> *const EVP_CIPHER; - pub fn EVP_aes_256_ctr() -> *const EVP_CIPHER; - pub fn EVP_aes_256_gcm() -> *const EVP_CIPHER; - pub fn EVP_aes_256_cfb1() -> *const EVP_CIPHER; - pub fn EVP_aes_256_cfb128() -> *const EVP_CIPHER; - pub fn EVP_aes_256_cfb8() -> *const EVP_CIPHER; - pub fn EVP_bf_cbc() -> *const EVP_CIPHER; - pub fn EVP_bf_ecb() -> *const EVP_CIPHER; - pub fn EVP_bf_cfb64() -> *const EVP_CIPHER; - pub fn EVP_bf_ofb() -> *const EVP_CIPHER; - pub fn EVP_rc4() -> *const EVP_CIPHER; - - pub fn EVP_des_cbc() -> *const EVP_CIPHER; - pub fn EVP_des_ecb() -> *const EVP_CIPHER; - pub fn EVP_des_ede3() -> *const EVP_CIPHER; - - pub fn EVP_BytesToKey( - typ: *const EVP_CIPHER, - md: *const EVP_MD, - salt: *const u8, - data: *const u8, - datalen: c_int, - count: c_int, - key: *mut u8, - iv: *mut u8, - ) -> c_int; - - pub fn EVP_CIPHER_CTX_new() -> *mut EVP_CIPHER_CTX; - pub fn EVP_CIPHER_CTX_set_padding(ctx: *mut EVP_CIPHER_CTX, padding: c_int) -> c_int; - pub fn EVP_CIPHER_CTX_set_key_length(ctx: *mut EVP_CIPHER_CTX, keylen: c_int) -> c_int; - pub fn EVP_CIPHER_CTX_ctrl( - ctx: *mut EVP_CIPHER_CTX, - type_: c_int, - arg: c_int, - ptr: *mut c_void, - ) -> c_int; - pub fn EVP_CIPHER_CTX_free(ctx: *mut EVP_CIPHER_CTX); - - pub fn EVP_CipherInit( - ctx: *mut EVP_CIPHER_CTX, - evp: *const EVP_CIPHER, - key: *const u8, - iv: *const u8, - mode: c_int, - ) -> c_int; - pub fn EVP_CipherInit_ex( - ctx: *mut EVP_CIPHER_CTX, - type_: *const EVP_CIPHER, - impl_: *mut ENGINE, - key: *const c_uchar, - iv: *const c_uchar, - enc: c_int, - ) -> c_int; - pub fn EVP_CipherUpdate( - ctx: *mut EVP_CIPHER_CTX, - outbuf: *mut u8, - outlen: *mut c_int, - inbuf: *const u8, - inlen: c_int, - ) -> c_int; - pub fn EVP_CipherFinal(ctx: *mut EVP_CIPHER_CTX, res: *mut u8, len: *mut c_int) -> c_int; - - pub fn EVP_DigestInit(ctx: *mut EVP_MD_CTX, typ: *const EVP_MD) -> c_int; - pub fn EVP_DigestInit_ex(ctx: *mut EVP_MD_CTX, typ: *const EVP_MD, imple: *mut ENGINE) - -> c_int; - pub fn EVP_DigestUpdate(ctx: *mut EVP_MD_CTX, data: *const c_void, n: size_t) -> c_int; - pub fn EVP_DigestFinal(ctx: *mut EVP_MD_CTX, res: *mut u8, n: *mut u32) -> c_int; - pub fn EVP_DigestFinal_ex(ctx: *mut EVP_MD_CTX, res: *mut u8, n: *mut u32) -> c_int; - - pub fn EVP_DigestSignInit( - ctx: *mut EVP_MD_CTX, - pctx: *mut *mut EVP_PKEY_CTX, - type_: *const EVP_MD, - e: *mut ENGINE, - pkey: *mut EVP_PKEY, - ) -> c_int; - pub fn EVP_DigestSignFinal( - ctx: *mut EVP_MD_CTX, - sig: *mut c_uchar, - siglen: *mut size_t, - ) -> c_int; - pub fn EVP_DigestVerifyInit( - ctx: *mut EVP_MD_CTX, - pctx: *mut *mut EVP_PKEY_CTX, - type_: *const EVP_MD, - e: *mut ENGINE, - pkey: *mut EVP_PKEY, - ) -> c_int; - #[cfg(any(ossl101, libressl))] - pub fn EVP_DigestVerifyFinal( - ctx: *mut EVP_MD_CTX, - sigret: *mut c_uchar, - siglen: size_t, - ) -> c_int; - #[cfg(not(any(ossl101, libressl)))] - pub fn EVP_DigestVerifyFinal( - ctx: *mut EVP_MD_CTX, - sigret: *const c_uchar, - siglen: size_t, - ) -> c_int; - - pub fn EVP_MD_CTX_copy_ex(dst: *mut EVP_MD_CTX, src: *const EVP_MD_CTX) -> c_int; - - pub fn EVP_PKEY_new() -> *mut EVP_PKEY; - pub fn EVP_PKEY_free(k: *mut EVP_PKEY); - pub fn EVP_PKEY_assign(pkey: *mut EVP_PKEY, typ: c_int, key: *mut c_void) -> c_int; - pub fn EVP_PKEY_copy_parameters(to: *mut EVP_PKEY, from: *const EVP_PKEY) -> c_int; - pub fn EVP_PKEY_get1_RSA(k: *mut EVP_PKEY) -> *mut RSA; - pub fn EVP_PKEY_set1_RSA(k: *mut EVP_PKEY, r: *mut RSA) -> c_int; - pub fn EVP_PKEY_get1_DSA(k: *mut EVP_PKEY) -> *mut DSA; - pub fn EVP_PKEY_get1_DH(k: *mut EVP_PKEY) -> *mut DH; - pub fn EVP_PKEY_get1_EC_KEY(k: *mut EVP_PKEY) -> *mut EC_KEY; - pub fn EVP_PKEY_cmp(a: *const EVP_PKEY, b: *const EVP_PKEY) -> c_int; - pub fn EVP_PKEY_new_mac_key( - type_: c_int, - e: *mut ENGINE, - key: *const c_uchar, - keylen: c_int, - ) -> *mut EVP_PKEY; - pub fn EVP_PKEY_derive_init(ctx: *mut EVP_PKEY_CTX) -> c_int; - pub fn EVP_PKEY_derive_set_peer(ctx: *mut EVP_PKEY_CTX, peer: *mut EVP_PKEY) -> c_int; - pub fn EVP_PKEY_derive(ctx: *mut EVP_PKEY_CTX, key: *mut c_uchar, size: *mut size_t) -> c_int; - pub fn d2i_PKCS8PrivateKey_bio( - bp: *mut BIO, - x: *mut *mut EVP_PKEY, - cb: Option, - u: *mut c_void, - ) -> *mut EVP_PKEY; - - pub fn EVP_PKEY_CTX_new(k: *mut EVP_PKEY, e: *mut ENGINE) -> *mut EVP_PKEY_CTX; - pub fn EVP_PKEY_CTX_free(ctx: *mut EVP_PKEY_CTX); - pub fn EVP_PKEY_CTX_ctrl( - ctx: *mut EVP_PKEY_CTX, - keytype: c_int, - optype: c_int, - cmd: c_int, - p1: c_int, - p2: *mut c_void, - ) -> c_int; - - pub fn HMAC_CTX_copy(dst: *mut HMAC_CTX, src: *mut HMAC_CTX) -> c_int; - - pub fn OBJ_obj2nid(o: *const ASN1_OBJECT) -> c_int; - pub fn OBJ_obj2txt( - buf: *mut c_char, - buf_len: c_int, - a: *const ASN1_OBJECT, - no_name: c_int, - ) -> c_int; - - pub fn OCSP_BASICRESP_new() -> *mut OCSP_BASICRESP; - pub fn OCSP_BASICRESP_free(r: *mut OCSP_BASICRESP); - pub fn OCSP_basic_verify( - bs: *mut OCSP_BASICRESP, - certs: *mut stack_st_X509, - st: *mut X509_STORE, - flags: c_ulong, - ) -> c_int; - pub fn OCSP_resp_find_status( - bs: *mut OCSP_BASICRESP, - id: *mut OCSP_CERTID, - status: *mut c_int, - reason: *mut c_int, - revtime: *mut *mut ASN1_GENERALIZEDTIME, - thisupd: *mut *mut ASN1_GENERALIZEDTIME, - nextupd: *mut *mut ASN1_GENERALIZEDTIME, - ) -> c_int; - pub fn OCSP_check_validity( - thisupd: *mut ASN1_GENERALIZEDTIME, - nextupd: *mut ASN1_GENERALIZEDTIME, - sec: c_long, - maxsec: c_long, - ) -> c_int; - - pub fn OCSP_CERTID_free(id: *mut OCSP_CERTID); - - pub fn OCSP_RESPONSE_new() -> *mut OCSP_RESPONSE; - pub fn OCSP_RESPONSE_free(r: *mut OCSP_RESPONSE); - pub fn i2d_OCSP_RESPONSE(a: *mut OCSP_RESPONSE, pp: *mut *mut c_uchar) -> c_int; - pub fn d2i_OCSP_RESPONSE( - a: *mut *mut OCSP_RESPONSE, - pp: *mut *const c_uchar, - length: c_long, - ) -> *mut OCSP_RESPONSE; - pub fn OCSP_response_create(status: c_int, bs: *mut OCSP_BASICRESP) -> *mut OCSP_RESPONSE; - pub fn OCSP_response_status(resp: *mut OCSP_RESPONSE) -> c_int; - pub fn OCSP_response_get1_basic(resp: *mut OCSP_RESPONSE) -> *mut OCSP_BASICRESP; - - pub fn OCSP_REQUEST_new() -> *mut OCSP_REQUEST; - pub fn OCSP_REQUEST_free(r: *mut OCSP_REQUEST); - pub fn i2d_OCSP_REQUEST(a: *mut OCSP_REQUEST, pp: *mut *mut c_uchar) -> c_int; - pub fn d2i_OCSP_REQUEST( - a: *mut *mut OCSP_REQUEST, - pp: *mut *const c_uchar, - length: c_long, - ) -> *mut OCSP_REQUEST; - pub fn OCSP_request_add0_id(r: *mut OCSP_REQUEST, id: *mut OCSP_CERTID) -> *mut OCSP_ONEREQ; - - pub fn OCSP_ONEREQ_free(r: *mut OCSP_ONEREQ); - - pub fn PEM_read_bio_DHparams( - bio: *mut BIO, - out: *mut *mut DH, - callback: Option, - user_data: *mut c_void, - ) -> *mut DH; - pub fn PEM_read_bio_X509( - bio: *mut BIO, - out: *mut *mut X509, - callback: Option, - user_data: *mut c_void, - ) -> *mut X509; - pub fn PEM_read_bio_X509_REQ( - bio: *mut BIO, - out: *mut *mut X509_REQ, - callback: Option, - user_data: *mut c_void, - ) -> *mut X509_REQ; - pub fn PEM_read_bio_PrivateKey( - bio: *mut BIO, - out: *mut *mut EVP_PKEY, - callback: Option, - user_data: *mut c_void, - ) -> *mut EVP_PKEY; - pub fn PEM_read_bio_PUBKEY( - bio: *mut BIO, - out: *mut *mut EVP_PKEY, - callback: Option, - user_data: *mut c_void, - ) -> *mut EVP_PKEY; - - pub fn PEM_read_bio_RSAPrivateKey( - bio: *mut BIO, - rsa: *mut *mut RSA, - callback: Option, - user_data: *mut c_void, - ) -> *mut RSA; - - pub fn PEM_read_bio_RSAPublicKey( - bio: *mut BIO, - rsa: *mut *mut RSA, - callback: Option, - user_data: *mut c_void, - ) -> *mut RSA; - - pub fn PEM_read_bio_RSA_PUBKEY( - bio: *mut BIO, - rsa: *mut *mut RSA, - callback: Option, - user_data: *mut c_void, - ) -> *mut RSA; - - pub fn PEM_write_bio_DHparams(bio: *mut BIO, x: *const DH) -> c_int; - pub fn PEM_write_bio_PrivateKey( - bio: *mut BIO, - pkey: *mut EVP_PKEY, - cipher: *const EVP_CIPHER, - kstr: *mut c_uchar, - klen: c_int, - callback: Option, - user_data: *mut c_void, - ) -> c_int; - pub fn PEM_write_bio_PKCS8PrivateKey( - bio: *mut BIO, - pkey: *mut EVP_PKEY, - cipher: *const EVP_CIPHER, - kstr: *mut c_char, - klen: c_int, - callback: Option, - user_data: *mut c_void, - ) -> c_int; - pub fn PEM_write_bio_PUBKEY(bp: *mut BIO, x: *mut EVP_PKEY) -> c_int; - pub fn PEM_write_bio_RSAPrivateKey( - bp: *mut BIO, - rsa: *mut RSA, - cipher: *const EVP_CIPHER, - kstr: *mut c_uchar, - klen: c_int, - callback: Option, - user_data: *mut c_void, - ) -> c_int; - pub fn PEM_write_bio_RSAPublicKey(bp: *mut BIO, rsa: *const RSA) -> c_int; - pub fn PEM_write_bio_RSA_PUBKEY(bp: *mut BIO, rsa: *mut RSA) -> c_int; - - pub fn PEM_read_bio_DSAPrivateKey( - bp: *mut BIO, - dsa: *mut *mut DSA, - callback: Option, - user_data: *mut c_void, - ) -> *mut DSA; - pub fn PEM_read_bio_DSA_PUBKEY( - bp: *mut BIO, - dsa: *mut *mut DSA, - callback: Option, - user_data: *mut c_void, - ) -> *mut DSA; - pub fn PEM_write_bio_DSAPrivateKey( - bp: *mut BIO, - dsa: *mut DSA, - cipher: *const EVP_CIPHER, - kstr: *mut c_uchar, - klen: c_int, - callback: Option, - user_data: *mut c_void, - ) -> c_int; - pub fn PEM_write_bio_DSA_PUBKEY(bp: *mut BIO, dsa: *mut DSA) -> c_int; - - pub fn PEM_write_bio_X509(bio: *mut BIO, x509: *mut X509) -> c_int; - pub fn PEM_write_bio_X509_REQ(bio: *mut BIO, x509: *mut X509_REQ) -> c_int; - - pub fn PEM_write_bio_ECPrivateKey( - bio: *mut BIO, - key: *mut EC_KEY, - cipher: *const EVP_CIPHER, - kstr: *mut c_uchar, - klen: c_int, - callback: Option, - user_data: *mut c_void, - ) -> c_int; - pub fn PEM_read_bio_ECPrivateKey( - bio: *mut BIO, - key: *mut *mut EC_KEY, - callback: Option, - user_data: *mut c_void, - ) -> *mut EC_KEY; - - pub fn PKCS5_PBKDF2_HMAC_SHA1( - pass: *const c_char, - passlen: c_int, - salt: *const u8, - saltlen: c_int, - iter: c_int, - keylen: c_int, - out: *mut u8, - ) -> c_int; - pub fn PKCS5_PBKDF2_HMAC( - pass: *const c_char, - passlen: c_int, - salt: *const c_uchar, - saltlen: c_int, - iter: c_int, - digest: *const EVP_MD, - keylen: c_int, - out: *mut u8, - ) -> c_int; - - pub fn RAND_bytes(buf: *mut u8, num: c_int) -> c_int; - pub fn RAND_status() -> c_int; - - pub fn RSA_new() -> *mut RSA; - pub fn RSA_free(rsa: *mut RSA); - pub fn RSA_generate_key_ex( - rsa: *mut RSA, - bits: c_int, - e: *mut BIGNUM, - cb: *mut BN_GENCB, - ) -> c_int; - pub fn RSA_private_decrypt( - flen: c_int, - from: *const u8, - to: *mut u8, - k: *mut RSA, - pad: c_int, - ) -> c_int; - pub fn RSA_public_decrypt( - flen: c_int, - from: *const u8, - to: *mut u8, - k: *mut RSA, - pad: c_int, - ) -> c_int; - pub fn RSA_private_encrypt( - flen: c_int, - from: *const u8, - to: *mut u8, - k: *mut RSA, - pad: c_int, - ) -> c_int; - pub fn RSA_public_encrypt( - flen: c_int, - from: *const u8, - to: *mut u8, - k: *mut RSA, - pad: c_int, - ) -> c_int; - pub fn RSA_sign( - t: c_int, - m: *const u8, - mlen: c_uint, - sig: *mut u8, - siglen: *mut c_uint, - k: *mut RSA, - ) -> c_int; - pub fn RSA_size(k: *const RSA) -> c_int; - pub fn RSA_verify( - t: c_int, - m: *const u8, - mlen: c_uint, - sig: *const u8, - siglen: c_uint, - k: *mut RSA, - ) -> c_int; - - pub fn DSA_new() -> *mut DSA; - pub fn DSA_free(dsa: *mut DSA); - pub fn DSA_size(dsa: *const DSA) -> c_int; - pub fn DSA_generate_parameters_ex( - dsa: *mut DSA, - bits: c_int, - seed: *const c_uchar, - seed_len: c_int, - counter_ref: *mut c_int, - h_ret: *mut c_ulong, - cb: *mut BN_GENCB, - ) -> c_int; - pub fn DSA_generate_key(dsa: *mut DSA) -> c_int; - pub fn DSA_sign( - dummy: c_int, - dgst: *const c_uchar, - len: c_int, - sigret: *mut c_uchar, - siglen: *mut c_uint, - dsa: *mut DSA, - ) -> c_int; - pub fn DSA_verify( - dummy: c_int, - dgst: *const c_uchar, - len: c_int, - sigbuf: *const c_uchar, - siglen: c_int, - dsa: *mut DSA, - ) -> c_int; - - pub fn SHA1(d: *const c_uchar, n: size_t, md: *mut c_uchar) -> *mut c_uchar; - pub fn SHA224(d: *const c_uchar, n: size_t, md: *mut c_uchar) -> *mut c_uchar; - pub fn SHA256(d: *const c_uchar, n: size_t, md: *mut c_uchar) -> *mut c_uchar; - pub fn SHA384(d: *const c_uchar, n: size_t, md: *mut c_uchar) -> *mut c_uchar; - pub fn SHA512(d: *const c_uchar, n: size_t, md: *mut c_uchar) -> *mut c_uchar; - - pub fn SHA1_Init(c: *mut SHA_CTX) -> c_int; - pub fn SHA1_Update(c: *mut SHA_CTX, data: *const c_void, len: size_t) -> c_int; - pub fn SHA1_Final(md: *mut c_uchar, c: *mut SHA_CTX) -> c_int; - pub fn SHA256_Init(c: *mut SHA256_CTX) -> c_int; - pub fn SHA256_Update(c: *mut SHA256_CTX, data: *const c_void, len: size_t) -> c_int; - pub fn SHA256_Final(md: *mut c_uchar, c: *mut SHA256_CTX) -> c_int; - pub fn SHA224_Init(c: *mut SHA256_CTX) -> c_int; - pub fn SHA224_Update(c: *mut SHA256_CTX, data: *const c_void, len: size_t) -> c_int; - pub fn SHA224_Final(md: *mut c_uchar, c: *mut SHA256_CTX) -> c_int; - pub fn SHA384_Init(c: *mut SHA512_CTX) -> c_int; - pub fn SHA384_Update(c: *mut SHA512_CTX, data: *const c_void, len: size_t) -> c_int; - pub fn SHA384_Final(md: *mut c_uchar, c: *mut SHA512_CTX) -> c_int; - pub fn SHA512_Init(c: *mut SHA512_CTX) -> c_int; - pub fn SHA512_Update(c: *mut SHA512_CTX, data: *const c_void, len: size_t) -> c_int; - pub fn SHA512_Final(md: *mut c_uchar, c: *mut SHA512_CTX) -> c_int; - - pub fn SSL_new(ctx: *mut SSL_CTX) -> *mut SSL; - pub fn SSL_pending(ssl: *const SSL) -> c_int; - pub fn SSL_free(ssl: *mut SSL); - pub fn SSL_set_bio(ssl: *mut SSL, rbio: *mut BIO, wbio: *mut BIO); - pub fn SSL_get_rbio(ssl: *const SSL) -> *mut BIO; - pub fn SSL_get_wbio(ssl: *const SSL) -> *mut BIO; - pub fn SSL_accept(ssl: *mut SSL) -> c_int; - pub fn SSL_connect(ssl: *mut SSL) -> c_int; - pub fn SSL_do_handshake(ssl: *mut SSL) -> c_int; - pub fn SSL_ctrl(ssl: *mut SSL, cmd: c_int, larg: c_long, parg: *mut c_void) -> c_long; - pub fn SSL_get_error(ssl: *const SSL, ret: c_int) -> c_int; - pub fn SSL_read(ssl: *mut SSL, buf: *mut c_void, num: c_int) -> c_int; - pub fn SSL_write(ssl: *mut SSL, buf: *const c_void, num: c_int) -> c_int; - pub fn SSL_get_ex_data_X509_STORE_CTX_idx() -> c_int; - pub fn SSL_get_SSL_CTX(ssl: *const SSL) -> *mut SSL_CTX; - pub fn SSL_set_SSL_CTX(ssl: *mut SSL, ctx: *mut SSL_CTX) -> *mut SSL_CTX; - #[cfg(not(any(osslconf = "OPENSSL_NO_COMP", libressl)))] - pub fn SSL_get_current_compression(ssl: *mut SSL) -> *const COMP_METHOD; - #[cfg(libressl)] - pub fn SSL_get_current_compression(ssl: *mut SSL) -> *const libc::c_void; - pub fn SSL_get_peer_certificate(ssl: *const SSL) -> *mut X509; - pub fn SSL_get_peer_cert_chain(ssl: *const SSL) -> *mut stack_st_X509; - pub fn SSL_get_ssl_method(ssl: *mut SSL) -> *const SSL_METHOD; - pub fn SSL_get_version(ssl: *const SSL) -> *const c_char; - pub fn SSL_version(ssl: *const SSL) -> c_int; - pub fn SSL_state_string(ssl: *const SSL) -> *const c_char; - pub fn SSL_state_string_long(ssl: *const SSL) -> *const c_char; - pub fn SSL_set_verify( - ssl: *mut SSL, - mode: c_int, - verify_callback: Option c_int>, - ); - pub fn SSL_set_ex_data(ssl: *mut SSL, idx: c_int, data: *mut c_void) -> c_int; - pub fn SSL_get_ex_data(ssl: *const SSL, idx: c_int) -> *mut c_void; - pub fn SSL_get_servername(ssl: *const SSL, name_type: c_int) -> *const c_char; - pub fn SSL_get_current_cipher(ssl: *const SSL) -> *const SSL_CIPHER; - #[cfg(not(any(ossl101, libressl)))] - pub fn SSL_get0_param(ssl: *mut SSL) -> *mut X509_VERIFY_PARAM; - pub fn SSL_get_verify_result(ssl: *const SSL) -> c_long; - pub fn SSL_shutdown(ssl: *mut SSL) -> c_int; - pub fn SSL_get_certificate(ssl: *const SSL) -> *mut X509; - #[cfg(any(ossl101, libressl))] - pub fn SSL_get_privatekey(ssl: *mut SSL) -> *mut EVP_PKEY; - #[cfg(not(any(ossl101, libressl)))] - pub fn SSL_get_privatekey(ssl: *const SSL) -> *mut EVP_PKEY; - pub fn SSL_load_client_CA_file(file: *const c_char) -> *mut stack_st_X509_NAME; - pub fn SSL_set_tmp_dh_callback( - ctx: *mut SSL, - dh: unsafe extern "C" fn(ssl: *mut SSL, is_export: c_int, keylength: c_int) -> *mut DH, - ); - - #[cfg(not(any(osslconf = "OPENSSL_NO_COMP", libressl)))] - pub fn SSL_COMP_get_name(comp: *const COMP_METHOD) -> *const c_char; - #[cfg(libressl)] - pub fn SSL_COMP_get_name(comp: *const libc::c_void) -> *const c_char; - - pub fn SSL_CIPHER_get_name(cipher: *const SSL_CIPHER) -> *const c_char; - pub fn SSL_CIPHER_get_bits(cipher: *const SSL_CIPHER, alg_bits: *mut c_int) -> c_int; - pub fn SSL_CIPHER_description( - cipher: *const SSL_CIPHER, - buf: *mut c_char, - size: c_int, - ) -> *mut c_char; - - pub fn SSL_CTX_new(method: *const SSL_METHOD) -> *mut SSL_CTX; - pub fn SSL_CTX_free(ctx: *mut SSL_CTX); - pub fn SSL_CTX_ctrl(ctx: *mut SSL_CTX, cmd: c_int, larg: c_long, parg: *mut c_void) -> c_long; - pub fn SSL_CTX_callback_ctrl( - ctx: *mut SSL_CTX, - cmd: c_int, - fp: Option, - ) -> c_long; - pub fn SSL_CTX_set_verify( - ctx: *mut SSL_CTX, - mode: c_int, - verify_callback: Option c_int>, - ); - pub fn SSL_CTX_set_verify_depth(ctx: *mut SSL_CTX, depth: c_int); - pub fn SSL_CTX_load_verify_locations( - ctx: *mut SSL_CTX, - CAfile: *const c_char, - CApath: *const c_char, - ) -> c_int; - pub fn SSL_CTX_set_default_verify_paths(ctx: *mut SSL_CTX) -> c_int; - pub fn SSL_CTX_set_ex_data(ctx: *mut SSL_CTX, idx: c_int, data: *mut c_void) -> c_int; - pub fn SSL_CTX_get_ex_data(ctx: *const SSL_CTX, idx: c_int) -> *mut c_void; - pub fn SSL_CTX_set_session_id_context( - ssl: *mut SSL_CTX, - sid_ctx: *const c_uchar, - sid_ctx_len: c_uint, - ) -> c_int; - - pub fn SSL_CTX_use_certificate_file( - ctx: *mut SSL_CTX, - cert_file: *const c_char, - file_type: c_int, - ) -> c_int; - pub fn SSL_CTX_use_certificate_chain_file( - ctx: *mut SSL_CTX, - cert_chain_file: *const c_char, - ) -> c_int; - pub fn SSL_CTX_use_certificate(ctx: *mut SSL_CTX, cert: *mut X509) -> c_int; - - pub fn SSL_CTX_use_PrivateKey_file( - ctx: *mut SSL_CTX, - key_file: *const c_char, - file_type: c_int, - ) -> c_int; - pub fn SSL_CTX_use_PrivateKey(ctx: *mut SSL_CTX, key: *mut EVP_PKEY) -> c_int; - pub fn SSL_CTX_check_private_key(ctx: *const SSL_CTX) -> c_int; - pub fn SSL_CTX_set_client_CA_list(ctx: *mut SSL_CTX, list: *mut stack_st_X509_NAME); - pub fn SSL_CTX_get_cert_store(ctx: *const SSL_CTX) -> *mut X509_STORE; - // FIXME should take an option - pub fn SSL_CTX_set_tmp_dh_callback( - ctx: *mut SSL_CTX, - dh: unsafe extern "C" fn(ssl: *mut SSL, is_export: c_int, keylength: c_int) -> *mut DH, - ); - pub fn SSL_CTX_sess_set_new_cb( - ctx: *mut SSL_CTX, - new_session_cb: Option c_int>, - ); - pub fn SSL_CTX_sess_set_remove_cb( - ctx: *mut SSL_CTX, - remove_session_cb: Option, - ); - - #[cfg(not(any(ossl101, libressl)))] - pub fn SSL_CTX_get0_certificate(ctx: *const SSL_CTX) -> *mut X509; - #[cfg(not(any(ossl101, libressl)))] - pub fn SSL_CTX_get0_privatekey(ctx: *const SSL_CTX) -> *mut EVP_PKEY; - - pub fn SSL_CTX_set_cipher_list(ssl: *mut SSL_CTX, s: *const c_char) -> c_int; - - pub fn SSL_CTX_set_next_protos_advertised_cb( - ssl: *mut SSL_CTX, - cb: extern "C" fn( - ssl: *mut SSL, - out: *mut *const c_uchar, - outlen: *mut c_uint, - arg: *mut c_void, - ) -> c_int, - arg: *mut c_void, - ); - pub fn SSL_CTX_set_next_proto_select_cb( - ssl: *mut SSL_CTX, - cb: extern "C" fn( - ssl: *mut SSL, - out: *mut *mut c_uchar, - outlen: *mut c_uchar, - inbuf: *const c_uchar, - inlen: c_uint, - arg: *mut c_void, - ) -> c_int, - arg: *mut c_void, - ); - #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] - pub fn SSL_CTX_set_psk_client_callback( - ssl: *mut SSL_CTX, - psk_client_cb: Option< - extern "C" fn(*mut SSL, *const c_char, *mut c_char, c_uint, *mut c_uchar, c_uint) - -> c_uint, - >, - ); - - pub fn SSL_select_next_proto( - out: *mut *mut c_uchar, - outlen: *mut c_uchar, - inbuf: *const c_uchar, - inlen: c_uint, - client: *const c_uchar, - client_len: c_uint, - ) -> c_int; - pub fn SSL_get0_next_proto_negotiated( - s: *const SSL, - data: *mut *const c_uchar, - len: *mut c_uint, - ); - pub fn SSL_get_session(s: *const SSL) -> *mut SSL_SESSION; - pub fn SSL_set_session(ssl: *mut SSL, session: *mut SSL_SESSION) -> c_int; - #[cfg(not(any(ossl101, libressl, ossl110f, ossl111)))] - pub fn SSL_is_server(s: *mut SSL) -> c_int; - #[cfg(any(ossl110f, ossl111))] - pub fn SSL_is_server(s: *const SSL) -> c_int; - - pub fn SSL_SESSION_free(s: *mut SSL_SESSION); - pub fn SSL_SESSION_get_id(s: *const SSL_SESSION, len: *mut c_uint) -> *const c_uchar; - - #[cfg(not(ossl101))] - pub fn SSL_CTX_set_alpn_protos(s: *mut SSL_CTX, data: *const c_uchar, len: c_uint) -> c_int; - - #[cfg(not(ossl101))] - pub fn SSL_set_alpn_protos(s: *mut SSL, data: *const c_uchar, len: c_uint) -> c_int; - - // FIXME should take an Option - #[cfg(not(ossl101))] - pub fn SSL_CTX_set_alpn_select_cb( - ssl: *mut SSL_CTX, - cb: extern "C" fn( - ssl: *mut SSL, - out: *mut *const c_uchar, - outlen: *mut c_uchar, - inbuf: *const c_uchar, - inlen: c_uint, - arg: *mut c_void, - ) -> c_int, - arg: *mut c_void, - ); - #[cfg(not(ossl101))] - pub fn SSL_get0_alpn_selected(s: *const SSL, data: *mut *const c_uchar, len: *mut c_uint); - - pub fn X509_add_ext(x: *mut X509, ext: *mut X509_EXTENSION, loc: c_int) -> c_int; - pub fn X509_digest( - x: *const X509, - digest: *const EVP_MD, - buf: *mut c_uchar, - len: *mut c_uint, - ) -> c_int; - pub fn X509_free(x: *mut X509); - pub fn X509_REQ_free(x: *mut X509_REQ); - pub fn X509_get_serialNumber(x: *mut X509) -> *mut ASN1_INTEGER; - pub fn X509_gmtime_adj(time: *mut ASN1_TIME, adj: c_long) -> *mut ASN1_TIME; - pub fn X509_new() -> *mut X509; - pub fn X509_set_issuer_name(x: *mut X509, name: *mut X509_NAME) -> c_int; - pub fn X509_set_subject_name(x: *mut X509, name: *mut X509_NAME) -> c_int; - pub fn X509_set_serialNumber(x: *mut X509, sn: *mut ASN1_INTEGER) -> c_int; - pub fn X509_set_version(x: *mut X509, version: c_long) -> c_int; - pub fn X509_set_pubkey(x: *mut X509, pkey: *mut EVP_PKEY) -> c_int; - pub fn X509_sign(x: *mut X509, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> c_int; - pub fn X509_get_pubkey(x: *mut X509) -> *mut EVP_PKEY; - pub fn X509_to_X509_REQ(x: *mut X509, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> *mut X509_REQ; - pub fn X509_verify_cert_error_string(n: c_long) -> *const c_char; - pub fn X509_get1_ocsp(x: *mut X509) -> *mut stack_st_OPENSSL_STRING; - pub fn X509_check_issued(issuer: *mut X509, subject: *mut X509) -> c_int; - - pub fn X509_ALGOR_free(x: *mut X509_ALGOR); - - pub fn X509_EXTENSION_free(ext: *mut X509_EXTENSION); - - pub fn X509_NAME_new() -> *mut X509_NAME; - pub fn X509_NAME_free(x: *mut X509_NAME); - pub fn X509_NAME_add_entry_by_txt( - x: *mut X509_NAME, - field: *const c_char, - ty: c_int, - bytes: *const c_uchar, - len: c_int, - loc: c_int, - set: c_int, - ) -> c_int; - pub fn X509_NAME_get_index_by_NID(n: *mut X509_NAME, nid: c_int, last_pos: c_int) -> c_int; - - pub fn X509_NAME_ENTRY_free(x: *mut X509_NAME_ENTRY); - - pub fn ASN1_STRING_free(x: *mut ASN1_STRING); - pub fn ASN1_STRING_length(x: *const ASN1_STRING) -> c_int; - - pub fn ASN1_INTEGER_free(x: *mut ASN1_INTEGER); - - pub fn X509_STORE_new() -> *mut X509_STORE; - pub fn X509_STORE_free(store: *mut X509_STORE); - pub fn X509_STORE_add_cert(store: *mut X509_STORE, x: *mut X509) -> c_int; - pub fn X509_STORE_set_default_paths(store: *mut X509_STORE) -> c_int; - - pub fn X509_STORE_CTX_free(ctx: *mut X509_STORE_CTX); - pub fn X509_STORE_CTX_get_current_cert(ctx: *mut X509_STORE_CTX) -> *mut X509; - pub fn X509_STORE_CTX_get_error(ctx: *mut X509_STORE_CTX) -> c_int; - pub fn X509_STORE_CTX_set_error(ctx: *mut X509_STORE_CTX, error: c_int); - pub fn X509_STORE_CTX_get_ex_data(ctx: *mut X509_STORE_CTX, idx: c_int) -> *mut c_void; - pub fn X509_STORE_CTX_get_error_depth(ctx: *mut X509_STORE_CTX) -> c_int; - - pub fn X509V3_set_ctx( - ctx: *mut X509V3_CTX, - issuer: *mut X509, - subject: *mut X509, - req: *mut X509_REQ, - crl: *mut X509_CRL, - flags: c_int, - ); - pub fn X509V3_set_nconf(ctx: *mut X509V3_CTX, conf: *mut CONF); - - pub fn X509_REQ_new() -> *mut X509_REQ; - pub fn X509_REQ_set_version(req: *mut X509_REQ, version: c_long) -> c_int; - pub fn X509_REQ_set_subject_name(req: *mut X509_REQ, name: *mut X509_NAME) -> c_int; - pub fn X509_REQ_set_pubkey(req: *mut X509_REQ, pkey: *mut EVP_PKEY) -> c_int; - pub fn X509_REQ_add_extensions(req: *mut X509_REQ, exts: *mut stack_st_X509_EXTENSION) - -> c_int; - pub fn X509_REQ_sign(x: *mut X509_REQ, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> c_int; - - #[cfg(not(ossl101))] - pub fn X509_VERIFY_PARAM_free(param: *mut X509_VERIFY_PARAM); - #[cfg(not(any(ossl101, libressl)))] - pub fn X509_VERIFY_PARAM_set_hostflags(param: *mut X509_VERIFY_PARAM, flags: c_uint); - #[cfg(not(any(ossl101, libressl)))] - pub fn X509_VERIFY_PARAM_set1_host( - param: *mut X509_VERIFY_PARAM, - name: *const c_char, - namelen: size_t, - ) -> c_int; - #[cfg(not(any(ossl101, libressl)))] - pub fn X509_VERIFY_PARAM_set1_ip( - param: *mut X509_VERIFY_PARAM, - ip: *const c_uchar, - iplen: size_t, - ) -> c_int; - - pub fn d2i_DHparams(k: *mut *mut DH, pp: *mut *const c_uchar, length: c_long) -> *mut DH; - pub fn i2d_DHparams(dh: *const DH, pp: *mut *mut c_uchar) -> c_int; - - pub fn d2i_DSAPublicKey(a: *mut *mut DSA, pp: *mut *const c_uchar, length: c_long) -> *mut DSA; - pub fn i2d_DSAPublicKey(a: *const DSA, pp: *mut *mut c_uchar) -> c_int; - pub fn d2i_DSAPrivateKey(a: *mut *mut DSA, pp: *mut *const c_uchar, length: c_long) - -> *mut DSA; - pub fn i2d_DSAPrivateKey(a: *const DSA, pp: *mut *mut c_uchar) -> c_int; - pub fn d2i_DSA_PUBKEY(k: *mut *mut DSA, pp: *mut *const c_uchar, length: c_long) -> *mut DSA; - pub fn i2d_DSA_PUBKEY(a: *mut DSA, pp: *mut *mut c_uchar) -> c_int; - - pub fn d2i_ECPrivateKey( - k: *mut *mut EC_KEY, - pp: *mut *const c_uchar, - length: c_long, - ) -> *mut EC_KEY; - pub fn i2d_ECPrivateKey(ec_key: *mut EC_KEY, pp: *mut *mut c_uchar) -> c_int; - - pub fn d2i_X509(a: *mut *mut X509, pp: *mut *const c_uchar, length: c_long) -> *mut X509; - pub fn d2i_X509_REQ( - a: *mut *mut X509_REQ, - pp: *mut *const c_uchar, - length: c_long, - ) -> *mut X509_REQ; - pub fn i2d_X509_bio(b: *mut BIO, x: *mut X509) -> c_int; - pub fn i2d_X509(x: *mut X509, buf: *mut *mut u8) -> c_int; - pub fn i2d_X509_REQ_bio(b: *mut BIO, x: *mut X509_REQ) -> c_int; - pub fn i2d_X509_REQ(x: *mut X509_REQ, buf: *mut *mut u8) -> c_int; - - pub fn d2i_AutoPrivateKey( - a: *mut *mut EVP_PKEY, - pp: *mut *const c_uchar, - length: c_long, - ) -> *mut EVP_PKEY; - pub fn d2i_PUBKEY(k: *mut *mut EVP_PKEY, buf: *mut *const u8, len: c_long) -> *mut EVP_PKEY; - pub fn i2d_PUBKEY_bio(b: *mut BIO, x: *mut EVP_PKEY) -> c_int; - pub fn i2d_PrivateKey_bio(b: *mut BIO, x: *mut EVP_PKEY) -> c_int; - pub fn i2d_PUBKEY(k: *mut EVP_PKEY, buf: *mut *mut u8) -> c_int; - pub fn i2d_PrivateKey(k: *mut EVP_PKEY, buf: *mut *mut u8) -> c_int; - - pub fn i2d_RSA_PUBKEY(k: *mut RSA, buf: *mut *mut u8) -> c_int; - pub fn d2i_RSA_PUBKEY(k: *mut *mut RSA, buf: *mut *const u8, len: c_long) -> *mut RSA; - pub fn i2d_RSAPublicKey(k: *const RSA, buf: *mut *mut u8) -> c_int; - pub fn d2i_RSAPublicKey(k: *mut *mut RSA, buf: *mut *const u8, len: c_long) -> *mut RSA; - pub fn i2d_RSAPrivateKey(k: *const RSA, buf: *mut *mut u8) -> c_int; - pub fn d2i_RSAPrivateKey(k: *mut *mut RSA, buf: *mut *const u8, len: c_long) -> *mut RSA; - - pub fn i2d_PKCS12_bio(b: *mut BIO, a: *mut PKCS12) -> c_int; - pub fn i2d_PKCS12(a: *mut PKCS12, buf: *mut *mut u8) -> c_int; - pub fn d2i_PKCS12(a: *mut *mut PKCS12, pp: *mut *const u8, length: c_long) -> *mut PKCS12; - pub fn PKCS12_parse( - p12: *mut PKCS12, - pass: *const c_char, - pkey: *mut *mut EVP_PKEY, - cert: *mut *mut X509, - ca: *mut *mut stack_st_X509, - ) -> c_int; - pub fn PKCS12_free(p12: *mut PKCS12); - - pub fn GENERAL_NAME_free(name: *mut GENERAL_NAME); - - pub fn HMAC_Init_ex( - ctx: *mut HMAC_CTX, - key: *const c_void, - len: c_int, - md: *const EVP_MD, - impl_: *mut ENGINE, - ) -> c_int; - pub fn HMAC_Update(ctx: *mut HMAC_CTX, data: *const c_uchar, len: size_t) -> c_int; - pub fn HMAC_Final(ctx: *mut HMAC_CTX, md: *mut c_uchar, len: *mut c_uint) -> c_int; - - #[cfg(not(libressl))] - pub fn CMS_decrypt( - cms: *mut CMS_ContentInfo, - pkey: *mut EVP_PKEY, - cert: *mut X509, - dcont: *mut BIO, - out: *mut BIO, - flags: c_uint, - ) -> c_int; - #[cfg(not(libressl))] - pub fn SMIME_read_CMS(bio: *mut BIO, bcont: *mut *mut BIO) -> *mut CMS_ContentInfo; - #[cfg(not(libressl))] - pub fn CMS_ContentInfo_free(cms: *mut CMS_ContentInfo); - - #[cfg(not(libressl))] - pub fn FIPS_mode_set(onoff: c_int) -> c_int; - #[cfg(not(libressl))] - pub fn FIPS_mode() -> c_int; -} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.26/src/ossl10x.rs cargo-0.26.0/vendor/openssl-sys-0.9.26/src/ossl10x.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.26/src/ossl10x.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.26/src/ossl10x.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,972 +0,0 @@ -use std::sync::{Mutex, MutexGuard}; -use std::sync::{Once, ONCE_INIT}; -use std::mem; -use std::ptr; -use std::process; -use std::io::{self, Write}; - -use libc::{c_char, c_int, c_long, c_uchar, c_uint, c_ulong, c_void, size_t}; -#[cfg(not(ossl101))] -use libc::time_t; - -#[repr(C)] -pub struct stack_st_ASN1_OBJECT { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_X509 { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_X509_NAME { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_X509_ATTRIBUTE { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_X509_EXTENSION { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_GENERAL_NAME { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_void { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_SSL_CIPHER { - pub stack: _STACK, -} - -#[repr(C)] -pub struct stack_st_OPENSSL_STRING { - pub stack: _STACK, -} - -#[repr(C)] -pub struct _STACK { - pub num: c_int, - pub data: *mut *mut c_char, - pub sorted: c_int, - pub num_alloc: c_int, - pub comp: Option c_int>, -} - -#[repr(C)] -pub struct BIO_METHOD { - pub type_: c_int, - pub name: *const c_char, - pub bwrite: Option c_int>, - pub bread: Option c_int>, - pub bputs: Option c_int>, - pub bgets: Option c_int>, - pub ctrl: Option c_long>, - pub create: Option c_int>, - pub destroy: Option c_int>, - pub callback_ctrl: Option c_long>, -} - -#[repr(C)] -pub struct RSA { - pub pad: c_int, - pub version: c_long, - pub meth: *const ::RSA_METHOD, - - pub engine: *mut ::ENGINE, - pub n: *mut ::BIGNUM, - pub e: *mut ::BIGNUM, - pub d: *mut ::BIGNUM, - pub p: *mut ::BIGNUM, - pub q: *mut ::BIGNUM, - pub dmp1: *mut ::BIGNUM, - pub dmq1: *mut ::BIGNUM, - pub iqmp: *mut ::BIGNUM, - - pub ex_data: ::CRYPTO_EX_DATA, - pub references: c_int, - pub flags: c_int, - - pub _method_mod_n: *mut ::BN_MONT_CTX, - pub _method_mod_p: *mut ::BN_MONT_CTX, - pub _method_mod_q: *mut ::BN_MONT_CTX, - - pub bignum_data: *mut c_char, - pub blinding: *mut ::BN_BLINDING, - pub mt_blinding: *mut ::BN_BLINDING, -} - -#[repr(C)] -pub struct DSA { - pub pad: c_int, - pub version: c_long, - pub write_params: c_int, - - pub p: *mut ::BIGNUM, - pub q: *mut ::BIGNUM, - pub g: *mut ::BIGNUM, - pub pub_key: *mut ::BIGNUM, - pub priv_key: *mut ::BIGNUM, - pub kinv: *mut ::BIGNUM, - pub r: *mut ::BIGNUM, - - pub flags: c_int, - pub method_mont_p: *mut ::BN_MONT_CTX, - pub references: c_int, - pub ex_data: ::CRYPTO_EX_DATA, - pub meth: *const ::DSA_METHOD, - pub engine: *mut ::ENGINE, -} - -#[repr(C)] -pub struct EVP_PKEY { - pub type_: c_int, - pub save_type: c_int, - pub references: c_int, - pub ameth: *const ::EVP_PKEY_ASN1_METHOD, - pub engine: *mut ::ENGINE, - pub pkey: *mut c_void, - pub save_parameters: c_int, - pub attributes: *mut stack_st_X509_ATTRIBUTE, -} - -#[repr(C)] -pub struct BIO { - pub method: *mut ::BIO_METHOD, - pub callback: Option< - unsafe extern "C" fn(*mut ::BIO, c_int, *const c_char, c_int, c_long, c_long) -> c_long, - >, - pub cb_arg: *mut c_char, - pub init: c_int, - pub shutdown: c_int, - pub flags: c_int, - pub retry_reason: c_int, - pub num: c_int, - pub ptr: *mut c_void, - pub next_bio: *mut ::BIO, - pub prev_bio: *mut ::BIO, - pub references: c_int, - pub num_read: c_ulong, - pub num_write: c_ulong, - pub ex_data: ::CRYPTO_EX_DATA, -} - -#[repr(C)] -pub struct CRYPTO_EX_DATA { - pub sk: *mut ::stack_st_void, - pub dummy: c_int, -} - -#[repr(C)] -pub struct EVP_MD_CTX { - digest: *mut ::EVP_MD, - engine: *mut ::ENGINE, - flags: c_ulong, - md_data: *mut c_void, - pctx: *mut ::EVP_PKEY_CTX, - update: *mut c_void, -} - -#[repr(C)] -pub struct EVP_CIPHER { - pub nid: c_int, - pub block_size: c_int, - pub key_len: c_int, - pub iv_len: c_int, - pub flags: c_ulong, - pub init: Option< - unsafe extern "C" fn(*mut ::EVP_CIPHER_CTX, *const c_uchar, *const c_uchar, c_int) -> c_int, - >, - pub do_cipher: Option< - unsafe extern "C" fn(*mut ::EVP_CIPHER_CTX, *mut c_uchar, *const c_uchar, size_t) -> c_int, - >, - pub cleanup: Option c_int>, - pub ctx_size: c_int, - pub set_asn1_parameters: - Option c_int>, - pub get_asn1_parameters: - Option c_int>, - pub ctrl: - Option c_int>, - pub app_data: *mut c_void, -} - -#[repr(C)] -pub struct HMAC_CTX { - md: *mut ::EVP_MD, - md_ctx: ::EVP_MD_CTX, - i_ctx: ::EVP_MD_CTX, - o_ctx: ::EVP_MD_CTX, - key_length: c_uint, - key: [c_uchar; 128], -} - -#[repr(C)] -pub struct BIGNUM { - pub d: *mut ::BN_ULONG, - pub top: c_int, - pub dmax: c_int, - pub neg: c_int, - pub flags: c_int, -} - -#[repr(C)] -pub struct DH { - pub pad: c_int, - pub version: c_int, - pub p: *mut ::BIGNUM, - pub g: *mut ::BIGNUM, - pub length: c_long, - pub pub_key: *mut ::BIGNUM, - pub priv_key: *mut ::BIGNUM, - pub flags: c_int, - pub method_mont_p: *mut ::BN_MONT_CTX, - pub q: *mut ::BIGNUM, - pub j: *mut ::BIGNUM, - pub seed: *mut c_uchar, - pub seedlen: c_int, - pub counter: *mut ::BIGNUM, - pub references: c_int, - pub ex_data: ::CRYPTO_EX_DATA, - pub meth: *const ::DH_METHOD, - pub engine: *mut ::ENGINE, -} - -#[repr(C)] -pub struct X509 { - pub cert_info: *mut X509_CINF, - pub sig_alg: *mut ::X509_ALGOR, - pub signature: *mut ::ASN1_BIT_STRING, - pub valid: c_int, - pub references: c_int, - pub name: *mut c_char, - pub ex_data: ::CRYPTO_EX_DATA, - pub ex_pathlen: c_long, - pub ex_pcpathlen: c_long, - pub ex_flags: c_ulong, - pub ex_kusage: c_ulong, - pub ex_xkusage: c_ulong, - pub ex_nscert: c_ulong, - skid: *mut c_void, - akid: *mut c_void, - policy_cache: *mut c_void, - crldp: *mut c_void, - altname: *mut c_void, - nc: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_RFC3779"))] - rfc3779_addr: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_RFC3779"))] - rfc3779_asid: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_SHA"))] - sha1_hash: [c_uchar; 20], - aux: *mut c_void, -} - -#[repr(C)] -pub struct X509_CINF { - version: *mut c_void, - serialNumber: *mut c_void, - signature: *mut c_void, - issuer: *mut c_void, - pub validity: *mut X509_VAL, - subject: *mut c_void, - key: *mut c_void, - issuerUID: *mut c_void, - subjectUID: *mut c_void, - pub extensions: *mut stack_st_X509_EXTENSION, - enc: ASN1_ENCODING, -} - -#[repr(C)] -pub struct X509_ALGOR { - pub algorithm: *mut ::ASN1_OBJECT, - parameter: *mut c_void, -} - -#[repr(C)] -pub struct ASN1_ENCODING { - pub enc: *mut c_uchar, - pub len: c_long, - pub modified: c_int, -} - -#[repr(C)] -pub struct X509_VAL { - pub notBefore: *mut ::ASN1_TIME, - pub notAfter: *mut ::ASN1_TIME, -} - -#[repr(C)] -pub struct X509_REQ_INFO { - pub enc: ASN1_ENCODING, - pub version: *mut ::ASN1_INTEGER, - pub subject: *mut ::X509_NAME, - pubkey: *mut c_void, - pub attributes: *mut stack_st_X509_ATTRIBUTE, -} - -#[repr(C)] -pub struct X509_REQ { - pub req_info: *mut X509_REQ_INFO, - sig_alg: *mut c_void, - signature: *mut c_void, - references: c_int, -} - -#[repr(C)] -pub struct SSL { - version: c_int, - type_: c_int, - method: *const ::SSL_METHOD, - rbio: *mut c_void, - wbio: *mut c_void, - bbio: *mut c_void, - rwstate: c_int, - in_handshake: c_int, - handshake_func: Option c_int>, - pub server: c_int, - new_session: c_int, - quiet_session: c_int, - shutdown: c_int, - state: c_int, - rstate: c_int, - init_buf: *mut c_void, - init_msg: *mut c_void, - init_num: c_int, - init_off: c_int, - packet: *mut c_uchar, - packet_length: c_uint, - s2: *mut c_void, - s3: *mut c_void, - d1: *mut c_void, - read_ahead: c_int, - msg_callback: Option< - unsafe extern "C" fn(c_int, c_int, c_int, *const c_void, size_t, *mut SSL, *mut c_void), - >, - msg_callback_arg: *mut c_void, - hit: c_int, - param: *mut c_void, - cipher_list: *mut stack_st_SSL_CIPHER, - cipher_list_by_id: *mut stack_st_SSL_CIPHER, - mac_flags: c_int, - enc_read_ctx: *mut ::EVP_CIPHER_CTX, - read_hash: *mut ::EVP_MD_CTX, - expand: *mut c_void, - enc_write_ctx: *mut ::EVP_CIPHER_CTX, - write_hash: *mut ::EVP_MD_CTX, - compress: *mut c_void, - cert: *mut c_void, - sid_ctx_length: c_uint, - sid_ctx: [c_uchar; ::SSL_MAX_SID_CTX_LENGTH as usize], - session: *mut ::SSL_SESSION, - generate_session_id: ::GEN_SESSION_CB, - verify_mode: c_int, - verify_callback: Option c_int>, - info_callback: Option, - error: c_int, - error_code: c_int, - #[cfg(not(osslconf = "OPENSSL_NO_KRB5"))] - kssl_ctx: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] - psk_client_callback: Option< - unsafe extern "C" fn(*mut SSL, *const c_char, *mut c_char, c_uint, *mut c_uchar, c_uint) - -> c_uint, - >, - #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] - psk_server_callback: - Option c_uint>, - ctx: *mut ::SSL_CTX, - debug: c_int, - verify_result: c_long, - ex_data: ::CRYPTO_EX_DATA, - client_CA: *mut stack_st_X509_NAME, - references: c_int, - options: c_ulong, - mode: c_ulong, - max_cert_list: c_long, - first_packet: c_int, - client_version: c_int, - max_send_fragment: c_uint, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_debug_cb: - Option, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_debug_arg: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_hostname: *mut c_char, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - servername_done: c_int, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_status_type: c_int, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_status_expected: c_int, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_ocsp_ids: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_ocsp_exts: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_ocsp_resp: *mut c_uchar, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_ocsp_resplen: c_int, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_ticket_expected: c_int, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] - tlsext_ecpointformatlist_length: size_t, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] - tlsext_ecpointformatlist: *mut c_uchar, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] - tlsext_ellipticcurvelist_length: size_t, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] - tlsext_ellipticcurvelist: *mut c_uchar, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_opaque_prf_input: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_opaque_prf_input_len: size_t, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_session_ticket: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_session_ticket_ext_cb: ::tls_session_ticket_ext_cb_fn, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tls_session_ticket_ext_cb_arg: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tls_session_secret_cb: ::tls_session_secret_cb_fn, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tls_session_secret_cb_arg: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - initial_ctx: *mut ::SSL_CTX, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] - next_proto_negotiated: *mut c_uchar, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] - next_proto_negotiated_len: c_uchar, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - srtp_profiles: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - srtp_profile: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_heartbeat: c_uint, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_hb_pending: c_uint, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_hb_seq: c_uint, - renegotiate: c_int, - #[cfg(not(osslconf = "OPENSSL_NO_SRP"))] - srp_ctx: ::SRP_CTX, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] - alpn_client_proto_list: *mut c_uchar, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] - alpn_client_proto_list_len: c_uint, -} - -#[repr(C)] -pub struct SSL_CTX { - method: *mut c_void, - cipher_list: *mut c_void, - cipher_list_by_id: *mut c_void, - cert_store: *mut c_void, - sessions: *mut c_void, - session_cache_size: c_ulong, - session_cache_head: *mut c_void, - session_cache_tail: *mut c_void, - session_cache_mode: c_int, - session_timeout: c_long, - new_session_cb: *mut c_void, - remove_session_cb: *mut c_void, - get_session_cb: *mut c_void, - stats: [c_int; 11], - pub references: c_int, - app_verify_callback: *mut c_void, - app_verify_arg: *mut c_void, - default_passwd_callback: *mut c_void, - default_passwd_callback_userdata: *mut c_void, - client_cert_cb: *mut c_void, - app_gen_cookie_cb: *mut c_void, - app_verify_cookie_cb: *mut c_void, - ex_dat: ::CRYPTO_EX_DATA, - rsa_md5: *mut c_void, - md5: *mut c_void, - sha1: *mut c_void, - extra_certs: *mut c_void, - comp_methods: *mut c_void, - info_callback: *mut c_void, - client_CA: *mut c_void, - options: c_ulong, - mode: c_ulong, - max_cert_list: c_long, - cert: *mut c_void, - read_ahead: c_int, - msg_callback: *mut c_void, - msg_callback_arg: *mut c_void, - verify_mode: c_int, - sid_ctx_length: c_uint, - sid_ctx: [c_uchar; 32], - default_verify_callback: *mut c_void, - generate_session_id: *mut c_void, - param: *mut c_void, - quiet_shutdown: c_int, - max_send_fragment: c_uint, - - #[cfg(not(osslconf = "OPENSSL_NO_ENGINE"))] - client_cert_engine: *mut c_void, - - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_servername_callback: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsect_servername_arg: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_tick_key_name: [c_uchar; 16], - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_tick_hmac_key: [c_uchar; 16], - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_tick_aes_key: [c_uchar; 16], - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_ticket_key_cb: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_status_cb: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_status_arg: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_opaque_prf_input_callback: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_opaque_prf_input_callback_arg: *mut c_void, - - #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] - psk_identity_hint: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] - psk_client_callback: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] - psk_server_callback: *mut c_void, - - #[cfg(not(osslconf = "OPENSSL_NO_BUF_FREELISTS"))] - freelist_max_len: c_uint, - #[cfg(not(osslconf = "OPENSSL_NO_BUF_FREELISTS"))] - wbuf_freelist: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_BUF_FREELISTS"))] - rbuf_freelist: *mut c_void, - - #[cfg(not(osslconf = "OPENSSL_NO_SRP"))] - srp_ctx: SRP_CTX, - - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] - next_protos_advertised_cb: *mut c_void, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] - next_protos_advertised_cb_arg: *mut c_void, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] - next_proto_select_cb: *mut c_void, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] - next_proto_select_cb_arg: *mut c_void, - - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl101))] - srtp_profiles: *mut c_void, - - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] - srtp_profiles: *mut c_void, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] - alpn_select_cb: *mut c_void, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] - alpn_select_cb_arg: *mut c_void, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] - alpn_client_proto_list: *mut c_void, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] - alpn_client_proto_list_len: c_uint, - - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC"), ossl102))] - tlsext_ecpointformatlist_length: size_t, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC"), ossl102))] - tlsext_ecpointformatlist: *mut c_uchar, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC"), ossl102))] - tlsext_ellipticcurvelist_length: size_t, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC"), ossl102))] - tlsext_ellipticcurvelist: *mut c_uchar, -} - -#[repr(C)] -pub struct SSL_SESSION { - ssl_version: c_int, - key_arg_length: c_uint, - key_arg: [c_uchar; SSL_MAX_KEY_ARG_LENGTH as usize], - pub master_key_length: c_int, - pub master_key: [c_uchar; 48], - session_id_length: c_uint, - session_id: [c_uchar; SSL_MAX_SSL_SESSION_ID_LENGTH as usize], - sid_ctx_length: c_uint, - sid_ctx: [c_uchar; SSL_MAX_SID_CTX_LENGTH as usize], - #[cfg(not(osslconf = "OPENSSL_NO_KRB5"))] - krb5_client_princ_len: c_uint, - #[cfg(not(osslconf = "OPENSSL_NO_KRB5"))] - krb5_client_princ: [c_uchar; SSL_MAX_KRB5_PRINCIPAL_LENGTH as usize], - #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] - psk_identity_hint: *mut c_char, - #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] - psk_identity: *mut c_char, - not_resumable: c_int, - sess_cert: *mut c_void, - peer: *mut X509, - verify_result: c_long, - pub references: c_int, - timeout: c_long, - time: c_long, - compress_meth: c_uint, - cipher: *const c_void, - cipher_id: c_ulong, - ciphers: *mut c_void, - ex_data: ::CRYPTO_EX_DATA, - prev: *mut c_void, - next: *mut c_void, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_hostname: *mut c_char, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] - tlsext_ecpointformatlist_length: size_t, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] - tlsext_ecpointformatlist: *mut c_uchar, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] - tlsext_ellipticcurvelist_length: size_t, - #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] - tlsext_ellipticcurvelist: *mut c_uchar, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_tick: *mut c_uchar, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_ticklen: size_t, - #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] - tlsext_tick_lifetime_hint: c_long, - #[cfg(not(osslconf = "OPENSSL_NO_SRP"))] - srp_username: *mut c_char, -} - -#[repr(C)] -pub struct SRP_CTX { - SRP_cb_arg: *mut c_void, - TLS_ext_srp_username_callback: *mut c_void, - SRP_verify_param_callback: *mut c_void, - SRP_give_srp_client_pwd_callback: *mut c_void, - login: *mut c_void, - N: *mut c_void, - g: *mut c_void, - s: *mut c_void, - B: *mut c_void, - A: *mut c_void, - a: *mut c_void, - b: *mut c_void, - v: *mut c_void, - info: *mut c_void, - stringth: c_int, - srp_Mask: c_ulong, -} - -#[repr(C)] -#[cfg(not(ossl101))] -pub struct X509_VERIFY_PARAM { - pub name: *mut c_char, - pub check_time: time_t, - pub inh_flags: c_ulong, - pub flags: c_ulong, - pub purpose: c_int, - pub trust: c_int, - pub depth: c_int, - pub policies: *mut stack_st_ASN1_OBJECT, - pub id: *mut X509_VERIFY_PARAM_ID, -} - -#[cfg(not(ossl101))] -pub enum X509_VERIFY_PARAM_ID {} -pub enum PKCS12 {} - -pub const SSL_CTRL_GET_SESSION_REUSED: c_int = 8; -pub const SSL_CTRL_OPTIONS: c_int = 32; -pub const SSL_CTRL_CLEAR_OPTIONS: c_int = 77; -#[cfg(ossl102)] -pub const SSL_CTRL_SET_ECDH_AUTO: c_int = 94; - -pub const SSL_OP_MICROSOFT_SESS_ID_BUG: c_ulong = 0x00000001; -pub const SSL_OP_NETSCAPE_CHALLENGE_BUG: c_ulong = 0x00000002; -pub const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: c_ulong = 0x00000008; -pub const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: c_ulong = 0x00000020; -pub const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: c_ulong = 0x00000080; -pub const SSL_OP_TLS_D5_BUG: c_ulong = 0x00000100; -pub const SSL_OP_TLS_BLOCK_PADDING_BUG: c_ulong = 0x00000200; -pub const SSL_OP_SINGLE_ECDH_USE: c_ulong = 0x00080000; -pub const SSL_OP_SINGLE_DH_USE: c_ulong = 0x00100000; -pub const SSL_OP_NO_SSLv2: c_ulong = 0x01000000; - -pub const SSL_MAX_SSL_SESSION_ID_LENGTH: c_int = 32; -pub const SSL_MAX_SID_CTX_LENGTH: c_int = 32; -pub const SSL_MAX_KEY_ARG_LENGTH: c_int = 8; -pub const SSL_MAX_MASTER_KEY_LENGTH: c_int = 48; -pub const SSL_MAX_KRB5_PRINCIPAL_LENGTH: c_int = 256; - -pub const SSLEAY_VERSION: c_int = 0; -pub const SSLEAY_CFLAGS: c_int = 2; -pub const SSLEAY_BUILT_ON: c_int = 3; -pub const SSLEAY_PLATFORM: c_int = 4; -pub const SSLEAY_DIR: c_int = 5; - -pub const CRYPTO_LOCK_X509: c_int = 3; -pub const CRYPTO_LOCK_SSL_CTX: c_int = 12; -pub const CRYPTO_LOCK_SSL_SESSION: c_int = 14; - -pub const X509_V_ERR_INVALID_CALL: c_int = 65; -pub const X509_V_ERR_STORE_LOOKUP: c_int = 66; -pub const X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION: c_int = 67; - -static mut MUTEXES: *mut Vec> = 0 as *mut Vec>; -static mut GUARDS: *mut Vec>> = - 0 as *mut Vec>>; - -unsafe extern "C" fn locking_function(mode: c_int, n: c_int, _file: *const c_char, _line: c_int) { - let mutex = &(*MUTEXES)[n as usize]; - - if mode & ::CRYPTO_LOCK != 0 { - (*GUARDS)[n as usize] = Some(mutex.lock().unwrap()); - } else { - if let None = (*GUARDS)[n as usize].take() { - let _ = writeln!( - io::stderr(), - "BUG: rust-openssl lock {} already unlocked, aborting", - n - ); - process::abort(); - } - } -} - -pub fn init() { - static INIT: Once = ONCE_INIT; - - INIT.call_once(|| unsafe { - SSL_library_init(); - SSL_load_error_strings(); - OPENSSL_add_all_algorithms_noconf(); - - let num_locks = ::CRYPTO_num_locks(); - let mut mutexes = Box::new(Vec::new()); - for _ in 0..num_locks { - mutexes.push(Mutex::new(())); - } - MUTEXES = mem::transmute(mutexes); - let guards: Box>>> = - Box::new((0..num_locks).map(|_| None).collect()); - GUARDS = mem::transmute(guards); - - CRYPTO_set_locking_callback(locking_function); - set_id_callback(); - }) -} - -#[cfg(unix)] -fn set_id_callback() { - unsafe extern "C" fn thread_id() -> c_ulong { - ::libc::pthread_self() as c_ulong - } - - unsafe { - CRYPTO_set_id_callback(thread_id); - } -} - -#[cfg(not(unix))] -fn set_id_callback() {} - -// macros - -#[cfg(ossl102)] -pub unsafe fn SSL_CTX_set_ecdh_auto(ctx: *mut SSL_CTX, onoff: c_int) -> c_int { - ::SSL_CTX_ctrl( - ctx, - SSL_CTRL_SET_ECDH_AUTO, - onoff as c_long, - ptr::null_mut(), - ) as c_int -} - -#[cfg(ossl102)] -pub unsafe fn SSL_set_ecdh_auto(ssl: *mut ::SSL, onoff: c_int) -> c_int { - ::SSL_ctrl( - ssl, - SSL_CTRL_SET_ECDH_AUTO, - onoff as c_long, - ptr::null_mut(), - ) as c_int -} - -pub unsafe fn SSL_session_reused(ssl: *mut ::SSL) -> c_int { - ::SSL_ctrl(ssl, SSL_CTRL_GET_SESSION_REUSED, 0, ptr::null_mut()) as c_int -} - -extern "C" { - pub fn BIO_new(type_: *mut BIO_METHOD) -> *mut BIO; - pub fn BIO_s_file() -> *mut BIO_METHOD; - pub fn BIO_s_mem() -> *mut BIO_METHOD; - - pub fn get_rfc2409_prime_768(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc2409_prime_1024(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc3526_prime_1536(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc3526_prime_2048(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc3526_prime_3072(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc3526_prime_4096(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc3526_prime_6144(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn get_rfc3526_prime_8192(bn: *mut BIGNUM) -> *mut BIGNUM; - - pub fn CRYPTO_malloc(num: c_int, file: *const c_char, line: c_int) -> *mut c_void; - pub fn CRYPTO_free(buf: *mut c_void); - pub fn CRYPTO_num_locks() -> c_int; - pub fn CRYPTO_set_locking_callback( - func: unsafe extern "C" fn(mode: c_int, n: c_int, file: *const c_char, line: c_int), - ); - pub fn CRYPTO_set_id_callback(func: unsafe extern "C" fn() -> c_ulong); - - pub fn ERR_load_crypto_strings(); - - pub fn RSA_generate_key( - modsz: c_int, - e: c_ulong, - cb: Option, - cbarg: *mut c_void, - ) -> *mut RSA; - - pub fn OCSP_cert_to_id( - dgst: *const ::EVP_MD, - subject: *mut ::X509, - issuer: *mut ::X509, - ) -> *mut ::OCSP_CERTID; - - pub fn PKCS12_create( - pass: *mut c_char, - friendly_name: *mut c_char, - pkey: *mut EVP_PKEY, - cert: *mut X509, - ca: *mut stack_st_X509, - nid_key: c_int, - nid_cert: c_int, - iter: c_int, - mac_iter: c_int, - keytype: c_int, - ) -> *mut PKCS12; - - pub fn SSL_library_init() -> c_int; - pub fn SSL_load_error_strings(); - pub fn OPENSSL_add_all_algorithms_noconf(); - pub fn HMAC_CTX_init(ctx: *mut ::HMAC_CTX); - pub fn HMAC_CTX_cleanup(ctx: *mut ::HMAC_CTX); - #[cfg(not(osslconf = "OPENSSL_NO_SSL3_METHOD"))] - pub fn SSLv3_method() -> *const ::SSL_METHOD; - pub fn TLSv1_method() -> *const ::SSL_METHOD; - pub fn SSLv23_method() -> *const ::SSL_METHOD; - pub fn TLSv1_1_method() -> *const ::SSL_METHOD; - pub fn TLSv1_2_method() -> *const ::SSL_METHOD; - pub fn DTLSv1_method() -> *const ::SSL_METHOD; - #[cfg(ossl102)] - pub fn DTLSv1_2_method() -> *const ::SSL_METHOD; - pub fn SSL_get_ex_new_index( - argl: c_long, - argp: *mut c_void, - new_func: Option<::CRYPTO_EX_new>, - dup_func: Option<::CRYPTO_EX_dup>, - free_func: Option<::CRYPTO_EX_free>, - ) -> c_int; - pub fn SSL_set_tmp_ecdh_callback( - ssl: *mut ::SSL, - ecdh: unsafe extern "C" fn(ssl: *mut ::SSL, is_export: c_int, keylength: c_int) - -> *mut ::EC_KEY, - ); - pub fn SSL_CIPHER_get_version(cipher: *const ::SSL_CIPHER) -> *mut c_char; - pub fn SSL_CTX_get_ex_new_index( - argl: c_long, - argp: *mut c_void, - new_func: Option<::CRYPTO_EX_new>, - dup_func: Option<::CRYPTO_EX_dup>, - free_func: Option<::CRYPTO_EX_free>, - ) -> c_int; - // FIXME should take an option - pub fn SSL_CTX_set_tmp_ecdh_callback( - ctx: *mut ::SSL_CTX, - ecdh: unsafe extern "C" fn(ssl: *mut ::SSL, is_export: c_int, keylength: c_int) - -> *mut ::EC_KEY, - ); - pub fn SSL_CTX_sess_set_get_cb( - ctx: *mut ::SSL_CTX, - get_session_cb: Option< - unsafe extern "C" fn(*mut ::SSL, *mut c_uchar, c_int, *mut c_int) -> *mut SSL_SESSION, - >, - ); - pub fn X509_get_subject_name(x: *mut ::X509) -> *mut ::X509_NAME; - pub fn X509_get_issuer_name(x: *mut ::X509) -> *mut ::X509_NAME; - pub fn X509_set_notAfter(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; - pub fn X509_set_notBefore(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; - pub fn X509_get_ext_d2i( - x: *mut ::X509, - nid: c_int, - crit: *mut c_int, - idx: *mut c_int, - ) -> *mut c_void; - pub fn X509_NAME_add_entry_by_NID( - x: *mut ::X509_NAME, - field: c_int, - ty: c_int, - bytes: *mut c_uchar, - len: c_int, - loc: c_int, - set: c_int, - ) -> c_int; - #[cfg(not(ossl101))] - pub fn X509_get0_signature( - psig: *mut *mut ::ASN1_BIT_STRING, - palg: *mut *mut ::X509_ALGOR, - x: *const ::X509, - ); - #[cfg(not(ossl101))] - pub fn X509_get_signature_nid(x: *const X509) -> c_int; - #[cfg(not(ossl101))] - pub fn X509_ALGOR_get0( - paobj: *mut *mut ::ASN1_OBJECT, - pptype: *mut c_int, - ppval: *mut *mut c_void, - alg: *mut ::X509_ALGOR, - ); - pub fn X509_NAME_get_entry(n: *mut ::X509_NAME, loc: c_int) -> *mut ::X509_NAME_ENTRY; - pub fn X509_NAME_ENTRY_get_data(ne: *mut ::X509_NAME_ENTRY) -> *mut ::ASN1_STRING; - pub fn X509_STORE_CTX_get_chain(ctx: *mut ::X509_STORE_CTX) -> *mut stack_st_X509; - pub fn X509V3_EXT_nconf_nid( - conf: *mut ::CONF, - ctx: *mut ::X509V3_CTX, - ext_nid: c_int, - value: *mut c_char, - ) -> *mut ::X509_EXTENSION; - pub fn X509V3_EXT_nconf( - conf: *mut ::CONF, - ctx: *mut ::X509V3_CTX, - name: *mut c_char, - value: *mut c_char, - ) -> *mut ::X509_EXTENSION; - pub fn ASN1_STRING_to_UTF8(out: *mut *mut c_uchar, s: *mut ::ASN1_STRING) -> c_int; - pub fn ASN1_STRING_data(x: *mut ::ASN1_STRING) -> *mut c_uchar; - pub fn CRYPTO_add_lock( - pointer: *mut c_int, - amount: c_int, - type_: c_int, - file: *const c_char, - line: c_int, - ) -> c_int; - pub fn EVP_MD_CTX_create() -> *mut EVP_MD_CTX; - pub fn EVP_MD_CTX_destroy(ctx: *mut EVP_MD_CTX); - pub fn EVP_PKEY_bits(key: *mut EVP_PKEY) -> c_int; - - pub fn sk_new_null() -> *mut _STACK; - pub fn sk_num(st: *const _STACK) -> c_int; - pub fn sk_value(st: *const _STACK, n: c_int) -> *mut c_void; - pub fn sk_free(st: *mut _STACK); - pub fn sk_push(st: *mut _STACK, data: *mut c_void) -> c_int; - pub fn sk_pop_free(st: *mut _STACK, free: Option); - pub fn sk_pop(st: *mut _STACK) -> *mut c_void; - - pub fn SSLeay() -> c_ulong; - pub fn SSLeay_version(key: c_int) -> *const c_char; -} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.26/src/ossl110.rs cargo-0.26.0/vendor/openssl-sys-0.9.26/src/ossl110.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.26/src/ossl110.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.26/src/ossl110.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,318 +0,0 @@ -use libc::{c_char, c_int, c_long, c_uchar, c_uint, c_ulong, c_void, size_t}; -use std::sync::{Once, ONCE_INIT}; -use std::ptr; - -pub enum BIGNUM {} -pub enum BIO {} -pub enum BIO_METHOD {} -pub enum CRYPTO_EX_DATA {} -pub enum DH {} -pub enum DSA {} -pub enum EVP_CIPHER {} -pub enum EVP_MD_CTX {} -pub enum EVP_PKEY {} -pub enum HMAC_CTX {} -pub enum OPENSSL_STACK {} -pub enum PKCS12 {} -pub enum RSA {} -pub enum SSL {} -pub enum SSL_CTX {} -pub enum SSL_SESSION {} -pub enum stack_st_ASN1_OBJECT {} -pub enum stack_st_GENERAL_NAME {} -pub enum stack_st_OPENSSL_STRING {} -pub enum stack_st_void {} -pub enum stack_st_X509 {} -pub enum stack_st_X509_NAME {} -pub enum stack_st_X509_ATTRIBUTE {} -pub enum stack_st_X509_EXTENSION {} -pub enum stack_st_SSL_CIPHER {} -pub enum OPENSSL_INIT_SETTINGS {} -pub enum X509 {} -pub enum X509_ALGOR {} -pub enum X509_VERIFY_PARAM {} -pub enum X509_REQ {} - -#[cfg(ossl111)] -pub type SSL_CTX_keylog_cb_func = - Option; - -pub const SSL_OP_MICROSOFT_SESS_ID_BUG: c_ulong = 0x00000000; -pub const SSL_OP_NETSCAPE_CHALLENGE_BUG: c_ulong = 0x00000000; -pub const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: c_ulong = 0x00000000; -pub const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: c_ulong = 0x00000000; -pub const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: c_ulong = 0x00000000; -pub const SSL_OP_TLS_D5_BUG: c_ulong = 0x00000000; -pub const SSL_OP_TLS_BLOCK_PADDING_BUG: c_ulong = 0x00000000; -pub const SSL_OP_SINGLE_ECDH_USE: c_ulong = 0x00000000; -pub const SSL_OP_SINGLE_DH_USE: c_ulong = 0x00000000; -pub const SSL_OP_NO_SSLv2: c_ulong = 0x00000000; - -#[cfg(ossl111)] -pub const TLS1_3_VERSION: c_int = 0x304; - -pub const OPENSSL_VERSION: c_int = 0; -pub const OPENSSL_CFLAGS: c_int = 1; -pub const OPENSSL_BUILT_ON: c_int = 2; -pub const OPENSSL_PLATFORM: c_int = 3; -pub const OPENSSL_DIR: c_int = 4; - -pub const CRYPTO_EX_INDEX_SSL: c_int = 0; -pub const CRYPTO_EX_INDEX_SSL_CTX: c_int = 1; - -pub const OPENSSL_INIT_LOAD_SSL_STRINGS: u64 = 0x00200000; - -pub const X509_V_ERR_DANE_NO_MATCH: c_int = 65; -pub const X509_V_ERR_EE_KEY_TOO_SMALL: c_int = 66; -pub const X509_V_ERR_CA_KEY_TOO_SMALL: c_int = 67; -pub const X509_V_ERR_CA_MD_TOO_WEAK: c_int = 68; -pub const X509_V_ERR_INVALID_CALL: c_int = 69; -pub const X509_V_ERR_STORE_LOOKUP: c_int = 70; -pub const X509_V_ERR_NO_VALID_SCTS: c_int = 71; - -pub const X509_CHECK_FLAG_NEVER_CHECK_SUBJECT: c_uint = 0x20; - -pub fn init() { - // explicitly initialize to work around https://github.com/openssl/openssl/issues/3505 - static INIT: Once = ONCE_INIT; - - INIT.call_once(|| unsafe { - OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, ptr::null_mut()); - }) -} - -extern "C" { - pub fn BIO_new(type_: *const BIO_METHOD) -> *mut BIO; - pub fn BIO_s_file() -> *const BIO_METHOD; - pub fn BIO_s_mem() -> *const BIO_METHOD; - - pub fn BN_get_rfc2409_prime_768(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn BN_get_rfc2409_prime_1024(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn BN_get_rfc3526_prime_1536(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn BN_get_rfc3526_prime_2048(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn BN_get_rfc3526_prime_3072(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn BN_get_rfc3526_prime_4096(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn BN_get_rfc3526_prime_6144(bn: *mut BIGNUM) -> *mut BIGNUM; - pub fn BN_get_rfc3526_prime_8192(bn: *mut BIGNUM) -> *mut BIGNUM; - - pub fn CRYPTO_malloc(num: size_t, file: *const c_char, line: c_int) -> *mut c_void; - pub fn CRYPTO_free(buf: *mut c_void, file: *const c_char, line: c_int); - - pub fn EVP_chacha20() -> *const ::EVP_CIPHER; - pub fn EVP_chacha20_poly1305() -> *const ::EVP_CIPHER; - - pub fn HMAC_CTX_new() -> *mut HMAC_CTX; - pub fn HMAC_CTX_free(ctx: *mut HMAC_CTX); - - pub fn OCSP_cert_to_id( - dgst: *const ::EVP_MD, - subject: *const ::X509, - issuer: *const ::X509, - ) -> *mut ::OCSP_CERTID; - - pub fn TLS_method() -> *const ::SSL_METHOD; - pub fn DTLS_method() -> *const ::SSL_METHOD; - pub fn SSL_CIPHER_get_version(cipher: *const ::SSL_CIPHER) -> *const c_char; - pub fn X509_get_subject_name(x: *const ::X509) -> *mut ::X509_NAME; - pub fn X509_get_issuer_name(x: *const ::X509) -> *mut ::X509_NAME; - pub fn X509_set1_notAfter(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; - pub fn X509_set1_notBefore(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; - pub fn X509_get_ext_d2i( - x: *const ::X509, - nid: c_int, - crit: *mut c_int, - idx: *mut c_int, - ) -> *mut c_void; - pub fn X509_NAME_add_entry_by_NID( - x: *mut ::X509_NAME, - field: c_int, - ty: c_int, - bytes: *const c_uchar, - len: c_int, - loc: c_int, - set: c_int, - ) -> c_int; - pub fn X509_get_signature_nid(x: *const X509) -> c_int; - pub fn X509_ALGOR_get0( - paobj: *mut *const ::ASN1_OBJECT, - pptype: *mut c_int, - ppval: *mut *const c_void, - alg: *const ::X509_ALGOR, - ); - pub fn X509_NAME_get_entry(n: *const ::X509_NAME, loc: c_int) -> *mut ::X509_NAME_ENTRY; - pub fn X509_NAME_ENTRY_get_data(ne: *const ::X509_NAME_ENTRY) -> *mut ::ASN1_STRING; - pub fn X509V3_EXT_nconf_nid( - conf: *mut ::CONF, - ctx: *mut ::X509V3_CTX, - ext_nid: c_int, - value: *const c_char, - ) -> *mut ::X509_EXTENSION; - pub fn X509V3_EXT_nconf( - conf: *mut ::CONF, - ctx: *mut ::X509V3_CTX, - name: *const c_char, - value: *const c_char, - ) -> *mut ::X509_EXTENSION; - pub fn ASN1_STRING_to_UTF8(out: *mut *mut c_uchar, s: *const ::ASN1_STRING) -> c_int; - pub fn BN_is_negative(b: *const ::BIGNUM) -> c_int; - pub fn EVP_CIPHER_key_length(cipher: *const EVP_CIPHER) -> c_int; - pub fn EVP_CIPHER_block_size(cipher: *const EVP_CIPHER) -> c_int; - pub fn EVP_CIPHER_iv_length(cipher: *const EVP_CIPHER) -> c_int; - pub fn EVP_PBE_scrypt( - pass: *const c_char, - passlen: size_t, - salt: *const c_uchar, - saltlen: size_t, - N: u64, - r: u64, - p: u64, - maxmem: u64, - key: *mut c_uchar, - keylen: size_t, - ) -> c_int; - pub fn DSA_get0_pqg( - d: *const ::DSA, - p: *mut *const ::BIGNUM, - q: *mut *const ::BIGNUM, - q: *mut *const ::BIGNUM, - ); - pub fn DSA_get0_key( - d: *const ::DSA, - pub_key: *mut *const ::BIGNUM, - priv_key: *mut *const ::BIGNUM, - ); - pub fn RSA_get0_key( - r: *const ::RSA, - n: *mut *const ::BIGNUM, - e: *mut *const ::BIGNUM, - d: *mut *const ::BIGNUM, - ); - pub fn RSA_get0_factors(r: *const ::RSA, p: *mut *const ::BIGNUM, q: *mut *const ::BIGNUM); - pub fn RSA_get0_crt_params( - r: *const ::RSA, - dmp1: *mut *const ::BIGNUM, - dmq1: *mut *const ::BIGNUM, - iqmp: *mut *const ::BIGNUM, - ); - pub fn RSA_set0_key( - r: *mut ::RSA, - n: *mut ::BIGNUM, - e: *mut ::BIGNUM, - d: *mut ::BIGNUM, - ) -> c_int; - pub fn RSA_set0_factors(r: *mut ::RSA, p: *mut ::BIGNUM, q: *mut ::BIGNUM) -> c_int; - pub fn RSA_set0_crt_params( - r: *mut ::RSA, - dmp1: *mut ::BIGNUM, - dmq1: *mut ::BIGNUM, - iqmp: *mut ::BIGNUM, - ) -> c_int; - pub fn ASN1_STRING_get0_data(x: *const ::ASN1_STRING) -> *const c_uchar; - pub fn OPENSSL_sk_num(stack: *const ::OPENSSL_STACK) -> c_int; - pub fn OPENSSL_sk_value(stack: *const ::OPENSSL_STACK, idx: c_int) -> *mut c_void; - pub fn SSL_CTX_get_options(ctx: *const ::SSL_CTX) -> c_ulong; - pub fn SSL_CTX_set_options(ctx: *mut ::SSL_CTX, op: c_ulong) -> c_ulong; - pub fn SSL_CTX_clear_options(ctx: *mut ::SSL_CTX, op: c_ulong) -> c_ulong; - pub fn SSL_CTX_sess_set_get_cb( - ctx: *mut ::SSL_CTX, - get_session_cb: Option< - unsafe extern "C" fn(*mut ::SSL, *const c_uchar, c_int, *mut c_int) -> *mut SSL_SESSION, - >, - ); - pub fn SSL_get_client_random(ssl: *const SSL, out: *mut c_uchar, len: size_t) -> size_t; - pub fn SSL_get_server_random(ssl: *const SSL, out: *mut c_uchar, len: size_t) -> size_t; - #[cfg(ossl111)] - pub fn SSL_CTX_set_keylog_callback(ctx: *mut ::SSL_CTX, cb: SSL_CTX_keylog_cb_func); - pub fn X509_getm_notAfter(x: *const ::X509) -> *mut ::ASN1_TIME; - pub fn X509_getm_notBefore(x: *const ::X509) -> *mut ::ASN1_TIME; - pub fn X509_get0_signature( - psig: *mut *const ::ASN1_BIT_STRING, - palg: *mut *const ::X509_ALGOR, - x: *const ::X509, - ); - pub fn DH_set0_pqg( - dh: *mut ::DH, - p: *mut ::BIGNUM, - q: *mut ::BIGNUM, - g: *mut ::BIGNUM, - ) -> c_int; - pub fn BIO_set_init(a: *mut ::BIO, init: c_int); - pub fn BIO_set_data(a: *mut ::BIO, data: *mut c_void); - pub fn BIO_get_data(a: *mut ::BIO) -> *mut c_void; - pub fn BIO_meth_new(type_: c_int, name: *const c_char) -> *mut ::BIO_METHOD; - pub fn BIO_meth_free(biom: *mut ::BIO_METHOD); - // FIXME should wrap in Option - pub fn BIO_meth_set_write( - biom: *mut ::BIO_METHOD, - write: unsafe extern "C" fn(*mut ::BIO, *const c_char, c_int) -> c_int, - ) -> c_int; - pub fn BIO_meth_set_read( - biom: *mut ::BIO_METHOD, - read: unsafe extern "C" fn(*mut ::BIO, *mut c_char, c_int) -> c_int, - ) -> c_int; - pub fn BIO_meth_set_puts( - biom: *mut ::BIO_METHOD, - read: unsafe extern "C" fn(*mut ::BIO, *const c_char) -> c_int, - ) -> c_int; - pub fn BIO_meth_set_ctrl( - biom: *mut ::BIO_METHOD, - read: unsafe extern "C" fn(*mut ::BIO, c_int, c_long, *mut c_void) -> c_long, - ) -> c_int; - pub fn BIO_meth_set_create( - biom: *mut ::BIO_METHOD, - create: unsafe extern "C" fn(*mut ::BIO) -> c_int, - ) -> c_int; - pub fn BIO_meth_set_destroy( - biom: *mut ::BIO_METHOD, - destroy: unsafe extern "C" fn(*mut ::BIO) -> c_int, - ) -> c_int; - pub fn CRYPTO_get_ex_new_index( - class_index: c_int, - argl: c_long, - argp: *mut c_void, - new_func: Option<::CRYPTO_EX_new>, - dup_func: Option<::CRYPTO_EX_dup>, - free_func: Option<::CRYPTO_EX_free>, - ) -> c_int; - pub fn X509_up_ref(x: *mut X509) -> c_int; - pub fn SSL_CTX_up_ref(x: *mut SSL_CTX) -> c_int; - pub fn SSL_session_reused(ssl: *mut SSL) -> c_int; - pub fn SSL_SESSION_get_master_key( - session: *const SSL_SESSION, - out: *mut c_uchar, - outlen: size_t, - ) -> size_t; - pub fn SSL_SESSION_up_ref(ses: *mut SSL_SESSION) -> c_int; - pub fn X509_get0_extensions(req: *const ::X509) -> *const stack_st_X509_EXTENSION; - pub fn X509_STORE_CTX_get0_chain(ctx: *mut ::X509_STORE_CTX) -> *mut stack_st_X509; - pub fn EVP_MD_CTX_new() -> *mut EVP_MD_CTX; - pub fn EVP_MD_CTX_free(ctx: *mut EVP_MD_CTX); - pub fn EVP_PKEY_bits(key: *const EVP_PKEY) -> c_int; - - pub fn OpenSSL_version_num() -> c_ulong; - pub fn OpenSSL_version(key: c_int) -> *const c_char; - pub fn OPENSSL_init_ssl(opts: u64, settings: *const OPENSSL_INIT_SETTINGS) -> c_int; - pub fn OPENSSL_sk_new_null() -> *mut ::OPENSSL_STACK; - pub fn OPENSSL_sk_free(st: *mut ::OPENSSL_STACK); - pub fn OPENSSL_sk_pop_free( - st: *mut ::OPENSSL_STACK, - free: Option, - ); - pub fn OPENSSL_sk_push(st: *mut ::OPENSSL_STACK, data: *const c_void) -> c_int; - pub fn OPENSSL_sk_pop(st: *mut ::OPENSSL_STACK) -> *mut c_void; - - pub fn PKCS12_create( - pass: *const c_char, - friendly_name: *const c_char, - pkey: *mut EVP_PKEY, - cert: *mut X509, - ca: *mut stack_st_X509, - nid_key: c_int, - nid_cert: c_int, - iter: c_int, - mac_iter: c_int, - keytype: c_int, - ) -> *mut PKCS12; - pub fn X509_REQ_get_version(req: *const X509_REQ) -> c_long; - pub fn X509_REQ_get_subject_name(req: *const X509_REQ) -> *mut ::X509_NAME; -} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.28/build.rs cargo-0.26.0/vendor/openssl-sys-0.9.28/build.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.28/build.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.28/build.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,565 @@ +extern crate cc; +extern crate pkg_config; +#[cfg(target_env = "msvc")] +extern crate vcpkg; + +use std::collections::HashSet; +use std::env; +use std::ffi::OsString; +use std::fs::File; +use std::io::{BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::panic::{self, AssertUnwindSafe}; +use std::process::Command; + +// The set of `OPENSSL_NO_`s that we care about. +const DEFINES: &'static [&'static str] = &[ + "OPENSSL_NO_BUF_FREELISTS", + "OPENSSL_NO_COMP", + "OPENSSL_NO_EC", + "OPENSSL_NO_EC2M", + "OPENSSL_NO_ENGINE", + "OPENSSL_NO_KRB5", + "OPENSSL_NO_NEXTPROTONEG", + "OPENSSL_NO_PSK", + "OPENSSL_NO_RFC3779", + "OPENSSL_NO_SHA", + "OPENSSL_NO_SRP", + "OPENSSL_NO_SSL3_METHOD", + "OPENSSL_NO_TLSEXT", +]; + +enum Version { + Openssl110, + Openssl102, + Openssl101, + Libressl, +} + +fn env(name: &str) -> Option { + let prefix = env::var("TARGET").unwrap().to_uppercase().replace("-", "_"); + let prefixed = format!("{}_{}", prefix, name); + println!("cargo:rerun-if-env-changed={}", prefixed); + + if let Some(var) = env::var_os(&prefixed) { + return Some(var); + } + + println!("cargo:rerun-if-env-changed={}", name); + env::var_os(name) +} + +fn main() { + let target = env::var("TARGET").unwrap(); + + let lib_dir = env("OPENSSL_LIB_DIR").map(PathBuf::from); + let include_dir = env("OPENSSL_INCLUDE_DIR").map(PathBuf::from); + + let (lib_dir, include_dir) = if lib_dir.is_none() || include_dir.is_none() { + let openssl_dir = env("OPENSSL_DIR").unwrap_or_else(|| find_openssl_dir(&target)); + let openssl_dir = Path::new(&openssl_dir); + let lib_dir = lib_dir.unwrap_or_else(|| openssl_dir.join("lib")); + let include_dir = include_dir.unwrap_or_else(|| openssl_dir.join("include")); + (lib_dir, include_dir) + } else { + (lib_dir.unwrap(), include_dir.unwrap()) + }; + + if !Path::new(&lib_dir).exists() { + panic!( + "OpenSSL library directory does not exist: {}", + lib_dir.to_string_lossy() + ); + } + if !Path::new(&include_dir).exists() { + panic!( + "OpenSSL include directory does not exist: {}", + include_dir.to_string_lossy() + ); + } + + println!( + "cargo:rustc-link-search=native={}", + lib_dir.to_string_lossy() + ); + println!("cargo:include={}", include_dir.to_string_lossy()); + + let version = validate_headers(&[include_dir.clone().into()]); + + let libs_env = env("OPENSSL_LIBS"); + let libs = match libs_env.as_ref().and_then(|s| s.to_str()) { + Some(ref v) => v.split(":").collect(), + None => match version { + Version::Openssl101 | Version::Openssl102 if target.contains("windows") => { + vec!["ssleay32", "libeay32"] + } + Version::Openssl110 if target.contains("windows") => vec!["libssl", "libcrypto"], + _ => vec!["ssl", "crypto"], + }, + }; + + let kind = determine_mode(Path::new(&lib_dir), &libs); + for lib in libs.into_iter() { + println!("cargo:rustc-link-lib={}={}", kind, lib); + } +} + +fn find_openssl_dir(target: &str) -> OsString { + let host = env::var("HOST").unwrap(); + + if host == target && target.contains("apple-darwin") { + let homebrew = Path::new("/usr/local/opt/openssl@1.1"); + if homebrew.exists() { + return homebrew.to_path_buf().into(); + } + let homebrew = Path::new("/usr/local/opt/openssl"); + if homebrew.exists() { + return homebrew.to_path_buf().into(); + } + } + + try_pkg_config(); + try_vcpkg(); + + // FreeBSD ships with OpenSSL but doesn't include a pkg-config file :( + if host == target && target.contains("freebsd") { + return OsString::from("/usr"); + } + + let mut msg = format!( + " + +Could not find directory of OpenSSL installation, and this `-sys` crate cannot +proceed without this knowledge. If OpenSSL is installed and this crate had +trouble finding it, you can set the `OPENSSL_DIR` environment variable for the +compilation process. + +If you're in a situation where you think the directory *should* be found +automatically, please open a bug at https://github.com/sfackler/rust-openssl +and include information about your system as well as this message. + + $HOST = {} + $TARGET = {} + openssl-sys = {} + +", + host, + target, + env!("CARGO_PKG_VERSION") + ); + + if host.contains("apple-darwin") && target.contains("apple-darwin") { + let system = Path::new("/usr/lib/libssl.0.9.8.dylib"); + if system.exists() { + msg.push_str(&format!( + " + +It looks like you're compiling on macOS, where the system contains a version of +OpenSSL 0.9.8. This crate no longer supports OpenSSL 0.9.8. + +As a consumer of this crate, you can fix this error by using Homebrew to +install the `openssl` package, or as a maintainer you can use the openssl-sys +0.7 crate for support with OpenSSL 0.9.8. + +Unfortunately though the compile cannot continue, so aborting. + +" + )); + } + } + + if host.contains("unknown-linux") && target.contains("unknown-linux-gnu") { + if Command::new("pkg-config").output().is_err() { + msg.push_str(&format!( + " +It looks like you're compiling on Linux and also targeting Linux. Currently this +requires the `pkg-config` utility to find OpenSSL but unfortunately `pkg-config` +could not be found. If you have OpenSSL installed you can likely fix this by +installing `pkg-config`. + +" + )); + } + } + + if host.contains("windows") && target.contains("windows-gnu") { + msg.push_str(&format!( + " +It looks like you're compiling for MinGW but you may not have either OpenSSL or +pkg-config installed. You can install these two dependencies with: + + pacman -S openssl-devel pkg-config + +and try building this crate again. + +" + )); + } + + if host.contains("windows") && target.contains("windows-msvc") { + msg.push_str(&format!( + " +It looks like you're compiling for MSVC but we couldn't detect an OpenSSL +installation. If there isn't one installed then you can try the rust-openssl +README for more information about how to download precompiled binaries of +OpenSSL: + + https://github.com/sfackler/rust-openssl#windows + +" + )); + } + + panic!(msg); +} + +/// Attempt to find OpenSSL through pkg-config. +/// +/// Note that if this succeeds then the function does not return as pkg-config +/// typically tells us all the information that we need. +fn try_pkg_config() { + let target = env::var("TARGET").unwrap(); + let host = env::var("HOST").unwrap(); + + // If we're going to windows-gnu we can use pkg-config, but only so long as + // we're coming from a windows host. + // + // Otherwise if we're going to windows we probably can't use pkg-config. + if target.contains("windows-gnu") && host.contains("windows") { + env::set_var("PKG_CONFIG_ALLOW_CROSS", "1"); + } else if target.contains("windows") { + return; + } + + let lib = match pkg_config::Config::new() + .print_system_libs(false) + .find("openssl") + { + Ok(lib) => lib, + Err(e) => { + println!("run pkg_config fail: {:?}", e); + return; + } + }; + + validate_headers(&lib.include_paths); + + for include in lib.include_paths.iter() { + println!("cargo:include={}", include.display()); + } + + std::process::exit(0); +} + +/// Attempt to find OpenSSL through vcpkg. +/// +/// Note that if this succeeds then the function does not return as vcpkg +/// should emit all of the cargo metadata that we need. +#[cfg(target_env = "msvc")] +fn try_vcpkg() { + // vcpkg will not emit any metadata if it can not find libraries + // appropriate for the target triple with the desired linkage. + + let mut lib = vcpkg::Config::new() + .emit_includes(true) + .lib_name("libcrypto") + .lib_name("libssl") + .probe("openssl"); + + if let Err(e) = lib { + println!( + "note: vcpkg did not find openssl as libcrypto and libssl : {:?}", + e + ); + lib = vcpkg::Config::new() + .emit_includes(true) + .lib_name("libeay32") + .lib_name("ssleay32") + .probe("openssl"); + } + if let Err(e) = lib { + println!( + "note: vcpkg did not find openssl as ssleay32 and libeay32: {:?}", + e + ); + return; + } + + let lib = lib.unwrap(); + validate_headers(&lib.include_paths); + + println!("cargo:rustc-link-lib=user32"); + println!("cargo:rustc-link-lib=gdi32"); + println!("cargo:rustc-link-lib=crypt32"); + + std::process::exit(0); +} + +#[cfg(not(target_env = "msvc"))] +fn try_vcpkg() {} + +/// Validates the header files found in `include_dir` and then returns the +/// version string of OpenSSL. +fn validate_headers(include_dirs: &[PathBuf]) -> Version { + // This `*-sys` crate only works with OpenSSL 1.0.1, 1.0.2, and 1.1.0. To + // correctly expose the right API from this crate, take a look at + // `opensslv.h` to see what version OpenSSL claims to be. + // + // OpenSSL has a number of build-time configuration options which affect + // various structs and such. Since OpenSSL 1.1.0 this isn't really a problem + // as the library is much more FFI-friendly, but 1.0.{1,2} suffer this problem. + // + // To handle all this conditional compilation we slurp up the configuration + // file of OpenSSL, `opensslconf.h`, and then dump out everything it defines + // as our own #[cfg] directives. That way the `ossl10x.rs` bindings can + // account for compile differences and such. + let mut path = PathBuf::from(env::var_os("OUT_DIR").unwrap()); + path.push("expando.c"); + let mut file = BufWriter::new(File::create(&path).unwrap()); + + write!( + file, + "\ +#include +#include + +#if LIBRESSL_VERSION_NUMBER >= 0x20800000 +RUST_LIBRESSL_NEW +#elif LIBRESSL_VERSION_NUMBER >= 0x20700000 +RUST_LIBRESSL_27X +#elif LIBRESSL_VERSION_NUMBER >= 0x20603000 +RUST_LIBRESSL_26X +#elif LIBRESSL_VERSION_NUMBER >= 0x20602000 +RUST_LIBRESSL_262 +#elif LIBRESSL_VERSION_NUMBER >= 0x20601000 +RUST_LIBRESSL_261 +#elif LIBRESSL_VERSION_NUMBER >= 0x20600000 +RUST_LIBRESSL_260 +#elif LIBRESSL_VERSION_NUMBER >= 0x20503000 +RUST_LIBRESSL_25X +#elif LIBRESSL_VERSION_NUMBER >= 0x20502000 +RUST_LIBRESSL_252 +#elif LIBRESSL_VERSION_NUMBER >= 0x20501000 +RUST_LIBRESSL_251 +#elif LIBRESSL_VERSION_NUMBER >= 0x20500000 +RUST_LIBRESSL_250 +#elif defined (LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20500000 +RUST_LIBRESSL_OLD +#elif OPENSSL_VERSION_NUMBER >= 0x10102000 +RUST_OPENSSL_NEW +#elif OPENSSL_VERSION_NUMBER >= 0x10101000 +RUST_OPENSSL_111 +#elif OPENSSL_VERSION_NUMBER >= 0x10100060 +RUST_OPENSSL_110F +#elif OPENSSL_VERSION_NUMBER >= 0x10100000 +RUST_OPENSSL_110 +#elif OPENSSL_VERSION_NUMBER >= 0x10002000 +RUST_OPENSSL_102 +#elif OPENSSL_VERSION_NUMBER >= 0x10001000 +RUST_OPENSSL_101 +#else +RUST_OPENSSL_OLD +#endif +" + ).unwrap(); + + for define in DEFINES { + write!( + file, + "\ +#ifdef {define} +RUST_{define}_RUST +#endif +", + define = define + ).unwrap(); + } + + file.flush().unwrap(); + drop(file); + + let mut gcc = cc::Build::new(); + for include_dir in include_dirs { + gcc.include(include_dir); + } + // https://github.com/alexcrichton/gcc-rs/issues/133 + let expanded = match panic::catch_unwind(AssertUnwindSafe(|| gcc.file(&path).expand())) { + Ok(expanded) => expanded, + Err(_) => { + panic!( + " +Failed to find OpenSSL development headers. + +You can try fixing this setting the `OPENSSL_DIR` environment variable +pointing to your OpenSSL installation or installing OpenSSL headers package +specific to your distribution: + + # On Ubuntu + sudo apt-get install libssl-dev + # On Arch Linux + sudo pacman -S openssl + # On Fedora + sudo dnf install openssl-devel + +See rust-openssl README for more information: + + https://github.com/sfackler/rust-openssl#linux +" + ); + } + }; + let expanded = String::from_utf8(expanded).unwrap(); + + let mut enabled = vec![]; + for &define in DEFINES { + if expanded.contains(&format!("RUST_{}_RUST", define)) { + println!("cargo:rustc-cfg=osslconf=\"{}\"", define); + enabled.push(define); + } + } + println!("cargo:conf={}", enabled.join(",")); + + if expanded.contains("RUST_LIBRESSL_250") { + println!("cargo:rustc-cfg=libressl"); + println!("cargo:rustc-cfg=libressl250"); + println!("cargo:libressl=true"); + println!("cargo:libressl_version=250"); + println!("cargo:version=101"); + Version::Libressl + } else if expanded.contains("RUST_LIBRESSL_251") { + println!("cargo:rustc-cfg=libressl"); + println!("cargo:rustc-cfg=libressl251"); + println!("cargo:libressl=true"); + println!("cargo:libressl_version=251"); + println!("cargo:version=101"); + Version::Libressl + } else if expanded.contains("RUST_LIBRESSL_252") { + println!("cargo:rustc-cfg=libressl"); + println!("cargo:rustc-cfg=libressl252"); + println!("cargo:libressl=true"); + println!("cargo:libressl_version=252"); + println!("cargo:version=101"); + Version::Libressl + } else if expanded.contains("RUST_LIBRESSL_25X") { + println!("cargo:rustc-cfg=libressl"); + println!("cargo:rustc-cfg=libressl25x"); + println!("cargo:libressl=true"); + println!("cargo:libressl_version=25x"); + println!("cargo:version=101"); + Version::Libressl + } else if expanded.contains("RUST_LIBRESSL_260") { + println!("cargo:rustc-cfg=libressl"); + println!("cargo:rustc-cfg=libressl260"); + println!("cargo:libressl=true"); + println!("cargo:libressl_version=260"); + println!("cargo:version=101"); + Version::Libressl + } else if expanded.contains("RUST_LIBRESSL_261") { + println!("cargo:rustc-cfg=libressl"); + println!("cargo:rustc-cfg=libressl261"); + println!("cargo:libressl=true"); + println!("cargo:libressl_version=261"); + println!("cargo:version=101"); + Version::Libressl + } else if expanded.contains("RUST_LIBRESSL_262") { + println!("cargo:rustc-cfg=libressl"); + println!("cargo:rustc-cfg=libressl262"); + println!("cargo:libressl=true"); + println!("cargo:libressl_version=262"); + println!("cargo:version=101"); + Version::Libressl + } else if expanded.contains("RUST_LIBRESSL_26X") { + println!("cargo:rustc-cfg=libressl"); + println!("cargo:rustc-cfg=libressl26x"); + println!("cargo:libressl=true"); + println!("cargo:libressl_version=26x"); + println!("cargo:version=101"); + Version::Libressl + } else if expanded.contains("RUST_LIBRESSL_27X") { + println!("cargo:rustc-cfg=libressl"); + println!("cargo:rustc-cfg=libressl27"); + println!("cargo:libressl=true"); + println!("cargo:libressl_version=27x"); + println!("cargo:version=101"); + Version::Libressl + } else if expanded.contains("RUST_OPENSSL_111") { + println!("cargo:rustc-cfg=ossl111"); + println!("cargo:rustc-cfg=ossl110"); + println!("cargo:version=111"); + Version::Openssl110 + } else if expanded.contains("RUST_OPENSSL_110F") { + println!("cargo:rustc-cfg=ossl110"); + println!("cargo:rustc-cfg=ossl110f"); + println!("cargo:version=110"); + println!("cargo:patch=f"); + Version::Openssl110 + } else if expanded.contains("RUST_OPENSSL_110") { + println!("cargo:rustc-cfg=ossl110"); + println!("cargo:version=110"); + Version::Openssl110 + } else if expanded.contains("RUST_OPENSSL_102") { + println!("cargo:rustc-cfg=ossl102"); + println!("cargo:version=102"); + Version::Openssl102 + } else if expanded.contains("RUST_OPENSSL_101") { + println!("cargo:rustc-cfg=ossl101"); + println!("cargo:version=101"); + Version::Openssl101 + } else { + panic!( + " + +This crate is only compatible with OpenSSL 1.0.1 through 1.1.1, or LibreSSL 2.5 +through 2.7, but a different version of OpenSSL was found. The build is now aborting +due to this version mismatch. + +" + ); + } +} + +/// Given a libdir for OpenSSL (where artifacts are located) as well as the name +/// of the libraries we're linking to, figure out whether we should link them +/// statically or dynamically. +fn determine_mode(libdir: &Path, libs: &[&str]) -> &'static str { + // First see if a mode was explicitly requested + let kind = env("OPENSSL_STATIC"); + match kind.as_ref().and_then(|s| s.to_str()).map(|s| &s[..]) { + Some("0") => return "dylib", + Some(_) => return "static", + None => {} + } + + // Next, see what files we actually have to link against, and see what our + // possibilities even are. + let files = libdir + .read_dir() + .unwrap() + .map(|e| e.unwrap()) + .map(|e| e.file_name()) + .filter_map(|e| e.into_string().ok()) + .collect::>(); + let can_static = libs.iter() + .all(|l| files.contains(&format!("lib{}.a", l)) || files.contains(&format!("{}.lib", l))); + let can_dylib = libs.iter().all(|l| { + files.contains(&format!("lib{}.so", l)) || files.contains(&format!("{}.dll", l)) + || files.contains(&format!("lib{}.dylib", l)) + }); + match (can_static, can_dylib) { + (true, false) => return "static", + (false, true) => return "dylib", + (false, false) => { + panic!( + "OpenSSL libdir at `{}` does not contain the required files \ + to either statically or dynamically link OpenSSL", + libdir.display() + ); + } + (true, true) => {} + } + + // Ok, we've got not explicit preference and can *either* link statically or + // link dynamically. In the interest of "security upgrades" and/or "best + // practices with security libs", let's link dynamically. + "dylib" +} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.28/.cargo-checksum.json cargo-0.26.0/vendor/openssl-sys-0.9.28/.cargo-checksum.json --- cargo-0.25.0/vendor/openssl-sys-0.9.28/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.28/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"0bbd90640b148b46305c1691eed6039b5c8509bed16991e3562a01eeb76902a3"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.28/Cargo.toml cargo-0.26.0/vendor/openssl-sys-0.9.28/Cargo.toml --- cargo-0.25.0/vendor/openssl-sys-0.9.28/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.28/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,33 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "openssl-sys" +version = "0.9.28" +authors = ["Alex Crichton ", "Steven Fackler "] +links = "openssl" +description = "FFI bindings to OpenSSL" +readme = "README.md" +categories = ["cryptography", "external-ffi-bindings"] +license = "MIT" +repository = "https://github.com/sfackler/rust-openssl" +[package.metadata.pkg-config] +openssl = "1.0.1" +[dependencies.libc] +version = "0.2" +[build-dependencies.cc] +version = "1.0" + +[build-dependencies.pkg-config] +version = "0.3.9" +[target."cfg(target_env = \"msvc\")".build-dependencies.vcpkg] +version = "0.2" diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.28/LICENSE-MIT cargo-0.26.0/vendor/openssl-sys-0.9.28/LICENSE-MIT --- cargo-0.25.0/vendor/openssl-sys-0.9.28/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.28/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +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. diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.28/README.md cargo-0.26.0/vendor/openssl-sys-0.9.28/README.md --- cargo-0.25.0/vendor/openssl-sys-0.9.28/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.28/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,180 @@ +# rust-openssl + +[![CircleCI](https://circleci.com/gh/sfackler/rust-openssl.svg?style=shield)](https://circleci.com/gh/sfackler/rust-openssl) [![Build status](https://ci.appveyor.com/api/projects/status/d1knobws948pyynk/branch/master?svg=true)](https://ci.appveyor.com/project/sfackler/rust-openssl/branch/master) [![crates.io](https://img.shields.io/crates/v/openssl.svg)](https://crates.io/crates/openssl) + +[Documentation](https://docs.rs/openssl). + +## Warning + +This README does not correspond to rust-openssl 0.7.x or 0.8.x. See +[here](https://github.com/sfackler/rust-openssl/blob/b8fb29db5c246175a096260eacca38180cd77dd0/README.md) +for that README. + +## Building + +rust-openssl depends on OpenSSL version 1.0.1 or above, or LibreSSL. Both the +libraries and headers need to be present in the build environment before this +crate is compiled, and some instructions of how to do this are in the sections +below. + +### Linux + +On Linux, you can typically install OpenSSL via your package manager. The +headers are sometimes provided in a separate package than the runtime libraries +- look for something like `openssl-devel` or `libssl-dev`. You will also need the +regular development utilities, like `pkg-config`, as the custom build script relies +on them. + +```bash +# On Debian and Ubuntu +sudo apt-get install pkg-config libssl-dev +# On Arch Linux +sudo pacman -S openssl +# On Fedora +sudo dnf install openssl-devel +``` + +If installation via a package manager is not possible, or if you're cross +compiling to a separate target, you'll typically need to compile OpenSSL from +source. That can normally be done with: + +``` +curl -O https://www.openssl.org/source/openssl-1.1.0g.tar.gz +tar xf openssl-1.1.0g.tar.gz +cd openssl-1.1.0g +export CC=... +./Configure --prefix=... linux-x86_64 -fPIC +make -j$(nproc) +make install +``` + +### OSX + +Although OpenSSL 0.9.8 is preinstalled on OSX this library is being phased out +of OSX and this crate also does not support that version of OpenSSL. To use this +crate on OSX you'll need to install OpenSSL via some alternate means, typically +Homebrew: + +```bash +brew install openssl +``` + +Occasionally an update of XCode or MacOS will cause the linker to fail after compilation, to rectify this you may want to try and run: + +```bash +xcode-select --install +``` + +If Homebrew is installed to the default location of `/usr/local`, OpenSSL will be +automatically detected. + +### Windows MSVC + +On MSVC it's unfortunately not always a trivial process acquiring OpenSSL. A couple of possibilities +are downloading precompiled binaries for OpenSSL 1.1.0, or installing OpenSSL 1.0.2 using vcpkg. + +#### Installing OpenSSL 1.1.0 using precompiled binaries + +Perhaps the easiest way to do this right now is to download [precompiled +binaries] and install them on your system. Currently it's recommended to +install the 1.1.0 (non-light) installation if you're choosing this route. + +[precompiled binaries]: http://slproweb.com/products/Win32OpenSSL.html + +Once a precompiled binary is installed you can configure this crate to find the +installation via an environment variable: + +``` +set OPENSSL_DIR=C:\OpenSSL-Win64 +``` + +During the installation process if you select "Copy OpenSSL DLLs to: The OpenSSL binaries (/bin) +directory", you will need to add them to the `PATH` environment variable: + +``` +set PATH=%PATH%;C:\OpenSSL-Win64\bin +``` + +Now you will need to [install root certificates.](#acquiring-root-certificates) + +#### Installing OpenSSL 1.0.2 using vcpkg + +Install [vcpkg](https://github.com/Microsoft/vcpkg), and install the OpenSSL port like this: + +```Batchfile +vcpkg install openssl:x64-windows +set VCPKG_ROOT=c:\path\to\vcpkg\installation +cargo build +``` + +For more information see the vcpkg build helper [documentation](http://docs.rs/vcpkg). +To finish setting up OpenSSL you will need to [install root certificates.](#acquiring-root-certificates) + +#### Acquiring Root Certificates + +Neither of the above OpenSSL distributions ship with any root certificates. +So to make requests to servers on the internet, you have to install them +manually. Download the [cacert.pem file from here], copy it somewhere safe +(`C:\OpenSSL-Win64\certs` is a good place) and point the `SSL_CERT_FILE` +environment variable there: + +``` +set SSL_CERT_FILE=C:\OpenSSL-Win64\certs\cacert.pem +``` + +[cacert.pem file from here]: https://curl.haxx.se/docs/caextract.html + +After that, you're just a `cargo build` away! + +### Windows GNU (MinGW) + +The easiest way to acquire OpenSSL when working with MinGW is to ensure you're +using [MSYS2](http://msys2.github.io) and to then execute: + +``` +# 32-bit +pacman -S mingw-w64-i686-openssl + +# 64-bit +pacman -S mingw-w64-x86_64-openssl +``` + +And after that, a `cargo build` should be all you need! + +### Manual configuration + +rust-openssl's build script will by default attempt to locate OpenSSL via +pkg-config or other system-specific mechanisms. This will not work in some +situations however, for example cross compiling or when using a copy of OpenSSL +other than the normal system install. + +The build script can be configured via environment variables: + +* `OPENSSL_DIR` - If specified, a directory that will be used to find + OpenSSL installation. It's expected that under this directory the `include` + folder has header files and a `lib` folder has the runtime libraries. +* `OPENSSL_LIB_DIR` - If specified, a directory that will be used to find + OpenSSL libraries. Overrides the `lib` folder implied by `OPENSSL_DIR` + (if specified). +* `OPENSSL_INCLUDE_DIR` - If specified, a directory that will be used to find + OpenSSL header files. Overrides the `include` folder implied by `OPENSSL_DIR` + (if specified). +* `OPENSSL_STATIC` - If specified, OpenSSL libraries will be statically rather + than dynamically linked. +* `OPENSSL_LIBS` - If specified, the names of the OpenSSL libraries that will be + linked, e.g. `ssl:crypto`. + +If `OPENSSL_DIR` or `OPENSSL_LIB_DIR` and `OPENSSL_INCLUDE_DIR` is specified, +then the build script will skip the pkg-config step. + +For target-specific configuration, each of these environment variables can be +prefixed by an upper-cased target, for example, +`X86_64_UNKNOWN_LINUX_GNU_OPENSSL_DIR`. This can be useful in cross compilation +contexts. + +### 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 under the terms of both the Apache License, +Version 2.0 and the MIT license without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.28/src/libressl/mod.rs cargo-0.26.0/vendor/openssl-sys-0.9.28/src/libressl/mod.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.28/src/libressl/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.28/src/libressl/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,600 @@ +use std::sync::{Mutex, MutexGuard}; +use std::sync::{Once, ONCE_INIT}; +use std::mem; +use std::ptr; + +#[cfg(libressl250)] +pub use libressl::v250::*; +#[cfg(not(libressl250))] +pub use libressl::v25x::*; + +use libc::{c_char, c_int, c_long, c_uchar, c_uint, c_ulong, c_void, size_t}; + +#[cfg(libressl250)] +mod v250; +#[cfg(not(libressl250))] +mod v25x; + +#[repr(C)] +pub struct stack_st_ASN1_OBJECT { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_X509 { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_X509_NAME { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_X509_ATTRIBUTE { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_X509_EXTENSION { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_GENERAL_NAME { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_void { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_SSL_CIPHER { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_OPENSSL_STRING { + pub stack: _STACK, +} + +#[repr(C)] +pub struct _STACK { + pub num: c_int, + pub data: *mut *mut c_char, + pub sorted: c_int, + pub num_alloc: c_int, + pub comp: Option c_int>, +} + +#[repr(C)] +pub struct BIO_METHOD { + pub type_: c_int, + pub name: *const c_char, + pub bwrite: Option c_int>, + pub bread: Option c_int>, + pub bputs: Option c_int>, + pub bgets: Option c_int>, + pub ctrl: Option c_long>, + pub create: Option c_int>, + pub destroy: Option c_int>, + pub callback_ctrl: Option c_long>, +} + +#[repr(C)] +pub struct RSA { + pub pad: c_int, + pub version: c_long, + pub meth: *const ::RSA_METHOD, + + pub engine: *mut ::ENGINE, + pub n: *mut ::BIGNUM, + pub e: *mut ::BIGNUM, + pub d: *mut ::BIGNUM, + pub p: *mut ::BIGNUM, + pub q: *mut ::BIGNUM, + pub dmp1: *mut ::BIGNUM, + pub dmq1: *mut ::BIGNUM, + pub iqmp: *mut ::BIGNUM, + + pub ex_data: ::CRYPTO_EX_DATA, + pub references: c_int, + pub flags: c_int, + + pub _method_mod_n: *mut ::BN_MONT_CTX, + pub _method_mod_p: *mut ::BN_MONT_CTX, + pub _method_mod_q: *mut ::BN_MONT_CTX, + + pub blinding: *mut ::BN_BLINDING, + pub mt_blinding: *mut ::BN_BLINDING, +} + +#[repr(C)] +pub struct DSA { + pub pad: c_int, + pub version: c_long, + pub write_params: c_int, + + pub p: *mut ::BIGNUM, + pub q: *mut ::BIGNUM, + pub g: *mut ::BIGNUM, + pub pub_key: *mut ::BIGNUM, + pub priv_key: *mut ::BIGNUM, + pub kinv: *mut ::BIGNUM, + pub r: *mut ::BIGNUM, + + pub flags: c_int, + pub method_mont_p: *mut ::BN_MONT_CTX, + pub references: c_int, + pub ex_data: ::CRYPTO_EX_DATA, + pub meth: *const ::DSA_METHOD, + pub engine: *mut ::ENGINE, +} + +#[repr(C)] +pub struct ECDSA_SIG { + pub r: *mut ::BIGNUM, + pub s: *mut ::BIGNUM, +} + +#[repr(C)] +pub struct EVP_PKEY { + pub type_: c_int, + pub save_type: c_int, + pub references: c_int, + pub ameth: *const ::EVP_PKEY_ASN1_METHOD, + pub engine: *mut ::ENGINE, + pub pkey: *mut c_void, + pub save_parameters: c_int, + pub attributes: *mut stack_st_X509_ATTRIBUTE, +} + +#[repr(C)] +pub struct BIO { + pub method: *mut ::BIO_METHOD, + pub callback: Option< + unsafe extern "C" fn(*mut ::BIO, c_int, *const c_char, c_int, c_long, c_long) -> c_long, + >, + pub cb_arg: *mut c_char, + pub init: c_int, + pub shutdown: c_int, + pub flags: c_int, + pub retry_reason: c_int, + pub num: c_int, + pub ptr: *mut c_void, + pub next_bio: *mut ::BIO, + pub prev_bio: *mut ::BIO, + pub references: c_int, + pub num_read: c_ulong, + pub num_write: c_ulong, + pub ex_data: ::CRYPTO_EX_DATA, +} + +#[repr(C)] +pub struct CRYPTO_EX_DATA { + pub sk: *mut ::stack_st_void, +} + +#[repr(C)] +pub struct EVP_MD_CTX { + digest: *mut ::EVP_MD, + engine: *mut ::ENGINE, + flags: c_ulong, + md_data: *mut c_void, + pctx: *mut ::EVP_PKEY_CTX, + update: *mut c_void, +} + +#[repr(C)] +pub struct EVP_CIPHER { + pub nid: c_int, + pub block_size: c_int, + pub key_len: c_int, + pub iv_len: c_int, + pub flags: c_ulong, + pub init: Option< + unsafe extern "C" fn(*mut ::EVP_CIPHER_CTX, *const c_uchar, *const c_uchar, c_int) -> c_int, + >, + pub do_cipher: Option< + unsafe extern "C" fn(*mut ::EVP_CIPHER_CTX, *mut c_uchar, *const c_uchar, size_t) -> c_int, + >, + pub cleanup: Option c_int>, + pub ctx_size: c_int, + pub set_asn1_parameters: + Option c_int>, + pub get_asn1_parameters: + Option c_int>, + pub ctrl: + Option c_int>, + pub app_data: *mut c_void, +} + +#[repr(C)] +pub struct HMAC_CTX { + md: *mut ::EVP_MD, + md_ctx: ::EVP_MD_CTX, + i_ctx: ::EVP_MD_CTX, + o_ctx: ::EVP_MD_CTX, + key_length: c_uint, + key: [c_uchar; 128], +} + +#[repr(C)] +pub struct BIGNUM { + pub d: *mut ::BN_ULONG, + pub top: c_int, + pub dmax: c_int, + pub neg: c_int, + pub flags: c_int, +} + +#[repr(C)] +pub struct DH { + pub pad: c_int, + pub version: c_int, + pub p: *mut ::BIGNUM, + pub g: *mut ::BIGNUM, + pub length: c_long, + pub pub_key: *mut ::BIGNUM, + pub priv_key: *mut ::BIGNUM, + pub flags: c_int, + pub method_mont_p: *mut ::BN_MONT_CTX, + pub q: *mut ::BIGNUM, + pub j: *mut ::BIGNUM, + pub seed: *mut c_uchar, + pub seedlen: c_int, + pub counter: *mut ::BIGNUM, + pub references: c_int, + pub ex_data: ::CRYPTO_EX_DATA, + pub meth: *const ::DH_METHOD, + pub engine: *mut ::ENGINE, +} + +#[repr(C)] +pub struct X509 { + pub cert_info: *mut X509_CINF, + pub sig_alg: *mut ::X509_ALGOR, + pub signature: *mut ::ASN1_BIT_STRING, + pub valid: c_int, + pub references: c_int, + pub name: *mut c_char, + pub ex_data: ::CRYPTO_EX_DATA, + pub ex_pathlen: c_long, + pub ex_pcpathlen: c_long, + pub ex_flags: c_ulong, + pub ex_kusage: c_ulong, + pub ex_xkusage: c_ulong, + pub ex_nscert: c_ulong, + skid: *mut c_void, + akid: *mut c_void, + policy_cache: *mut c_void, + crldp: *mut c_void, + altname: *mut c_void, + nc: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_SHA"))] + sha1_hash: [c_uchar; 20], + aux: *mut c_void, +} + +#[repr(C)] +pub struct X509_CINF { + version: *mut c_void, + serialNumber: *mut c_void, + signature: *mut c_void, + issuer: *mut c_void, + pub validity: *mut X509_VAL, + subject: *mut c_void, + key: *mut c_void, + issuerUID: *mut c_void, + subjectUID: *mut c_void, + pub extensions: *mut stack_st_X509_EXTENSION, + enc: ASN1_ENCODING, +} + +#[repr(C)] +pub struct X509_ALGOR { + pub algorithm: *mut ::ASN1_OBJECT, + parameter: *mut c_void, +} + +#[repr(C)] +pub struct ASN1_ENCODING { + pub enc: *mut c_uchar, + pub len: c_long, + pub modified: c_int, +} + +#[repr(C)] +pub struct X509_VAL { + pub notBefore: *mut ::ASN1_TIME, + pub notAfter: *mut ::ASN1_TIME, +} + +#[repr(C)] +pub struct X509_REQ_INFO { + pub enc: ASN1_ENCODING, + pub version: *mut ::ASN1_INTEGER, + pub subject: *mut ::X509_NAME, + pubkey: *mut c_void, + pub attributes: *mut stack_st_X509_ATTRIBUTE, +} + +#[repr(C)] +pub struct X509_REQ { + pub req_info: *mut X509_REQ_INFO, + sig_alg: *mut c_void, + signature: *mut c_void, + references: c_int, +} + +pub enum X509_VERIFY_PARAM_ID {} +pub enum PKCS12 {} + +pub const SSL_CTRL_GET_SESSION_REUSED: c_int = 8; +pub const SSL_CTRL_OPTIONS: c_int = 32; +pub const SSL_CTRL_CLEAR_OPTIONS: c_int = 77; +pub const SSL_CTRL_SET_ECDH_AUTO: c_int = 94; + +#[cfg(any(libressl261, libressl262, libressl26x, libressl27))] +pub const SSL_OP_ALL: c_ulong = 0x4; +#[cfg(not(any(libressl261, libressl262, libressl26x, libressl27)))] +pub const SSL_OP_ALL: c_ulong = 0x80000014; +pub const SSL_OP_CISCO_ANYCONNECT: c_ulong = 0x0; +pub const SSL_OP_NO_COMPRESSION: c_ulong = 0x0; +pub const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: c_ulong = 0x0; +pub const SSL_OP_NO_SSLv3: c_ulong = 0x0; +pub const SSL_OP_MICROSOFT_SESS_ID_BUG: c_ulong = 0x0; +pub const SSL_OP_NETSCAPE_CHALLENGE_BUG: c_ulong = 0x0; +pub const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: c_ulong = 0x0; +pub const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: c_ulong = 0x0; +pub const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: c_ulong = 0x0; +pub const SSL_OP_TLS_D5_BUG: c_ulong = 0x0; +pub const SSL_OP_TLS_BLOCK_PADDING_BUG: c_ulong = 0x0; +#[cfg(any(libressl261, libressl262, libressl26x, libressl27))] +pub const SSL_OP_SINGLE_ECDH_USE: c_ulong = 0x0; +#[cfg(not(any(libressl261, libressl262, libressl26x, libressl27)))] +pub const SSL_OP_SINGLE_ECDH_USE: c_ulong = 0x00080000; +pub const SSL_OP_SINGLE_DH_USE: c_ulong = 0x00100000; +pub const SSL_OP_NO_SSLv2: c_ulong = 0x0; + +pub const SSL_MAX_SSL_SESSION_ID_LENGTH: c_int = 32; +pub const SSL_MAX_SID_CTX_LENGTH: c_int = 32; +pub const SSL_MAX_MASTER_KEY_LENGTH: c_int = 48; + +pub const SSLEAY_VERSION: c_int = 0; +pub const SSLEAY_CFLAGS: c_int = 2; +pub const SSLEAY_BUILT_ON: c_int = 3; +pub const SSLEAY_PLATFORM: c_int = 4; +pub const SSLEAY_DIR: c_int = 5; + +pub const CRYPTO_LOCK_X509: c_int = 3; +pub const CRYPTO_LOCK_SSL_CTX: c_int = 12; +pub const CRYPTO_LOCK_SSL_SESSION: c_int = 14; + +static mut MUTEXES: *mut Vec> = 0 as *mut Vec>; +static mut GUARDS: *mut Vec>> = + 0 as *mut Vec>>; + +unsafe extern "C" fn locking_function(mode: c_int, n: c_int, _file: *const c_char, _line: c_int) { + let mutex = &(*MUTEXES)[n as usize]; + + if mode & ::CRYPTO_LOCK != 0 { + (*GUARDS)[n as usize] = Some(mutex.lock().unwrap()); + } else { + &(*GUARDS)[n as usize].take().expect("lock already unlocked"); + } +} + +pub fn init() { + static INIT: Once = ONCE_INIT; + + INIT.call_once(|| unsafe { + SSL_library_init(); + SSL_load_error_strings(); + OPENSSL_add_all_algorithms_noconf(); + + let num_locks = ::CRYPTO_num_locks(); + let mut mutexes = Box::new(Vec::new()); + for _ in 0..num_locks { + mutexes.push(Mutex::new(())); + } + MUTEXES = mem::transmute(mutexes); + let guards: Box>>> = + Box::new((0..num_locks).map(|_| None).collect()); + GUARDS = mem::transmute(guards); + + CRYPTO_set_locking_callback(locking_function); + set_id_callback(); + }) +} + +#[cfg(unix)] +fn set_id_callback() { + unsafe extern "C" fn thread_id() -> c_ulong { + ::libc::pthread_self() as c_ulong + } + + unsafe { + CRYPTO_set_id_callback(thread_id); + } +} + +#[cfg(not(unix))] +fn set_id_callback() {} + +// macros + +pub unsafe fn SSL_CTX_set_ecdh_auto(ctx: *mut SSL_CTX, onoff: c_int) -> c_int { + ::SSL_CTX_ctrl( + ctx, + SSL_CTRL_SET_ECDH_AUTO, + onoff as c_long, + ptr::null_mut(), + ) as c_int +} + +pub unsafe fn SSL_set_ecdh_auto(ssl: *mut ::SSL, onoff: c_int) -> c_int { + ::SSL_ctrl( + ssl, + SSL_CTRL_SET_ECDH_AUTO, + onoff as c_long, + ptr::null_mut(), + ) as c_int +} + +pub unsafe fn SSL_session_reused(ssl: *mut ::SSL) -> c_int { + ::SSL_ctrl(ssl, SSL_CTRL_GET_SESSION_REUSED, 0, ptr::null_mut()) as c_int +} + +extern "C" { + pub fn BIO_new(type_: *mut BIO_METHOD) -> *mut BIO; + pub fn BIO_s_file() -> *mut BIO_METHOD; + pub fn BIO_s_mem() -> *mut BIO_METHOD; + + pub fn get_rfc2409_prime_768(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc2409_prime_1024(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc3526_prime_1536(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc3526_prime_2048(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc3526_prime_3072(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc3526_prime_4096(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc3526_prime_6144(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc3526_prime_8192(bn: *mut BIGNUM) -> *mut BIGNUM; + + pub fn CRYPTO_malloc(num: c_int, file: *const c_char, line: c_int) -> *mut c_void; + pub fn CRYPTO_free(buf: *mut c_void); + pub fn CRYPTO_num_locks() -> c_int; + pub fn CRYPTO_set_locking_callback( + func: unsafe extern "C" fn(mode: c_int, n: c_int, file: *const c_char, line: c_int), + ); + pub fn CRYPTO_set_id_callback(func: unsafe extern "C" fn() -> c_ulong); + + pub fn ERR_load_crypto_strings(); + + pub fn RSA_generate_key( + modsz: c_int, + e: c_ulong, + cb: Option, + cbarg: *mut c_void, + ) -> *mut RSA; + + pub fn OCSP_cert_to_id( + dgst: *const ::EVP_MD, + subject: *mut ::X509, + issuer: *mut ::X509, + ) -> *mut ::OCSP_CERTID; + + pub fn PKCS12_create( + pass: *mut c_char, + friendly_name: *mut c_char, + pkey: *mut EVP_PKEY, + cert: *mut X509, + ca: *mut stack_st_X509, + nid_key: c_int, + nid_cert: c_int, + iter: c_int, + mac_iter: c_int, + keytype: c_int, + ) -> *mut PKCS12; + + pub fn SSL_library_init() -> c_int; + pub fn SSL_load_error_strings(); + pub fn OPENSSL_add_all_algorithms_noconf(); + pub fn HMAC_CTX_init(ctx: *mut ::HMAC_CTX); + pub fn HMAC_CTX_cleanup(ctx: *mut ::HMAC_CTX); + pub fn TLSv1_method() -> *const ::SSL_METHOD; + pub fn SSLv23_method() -> *const ::SSL_METHOD; + pub fn TLSv1_1_method() -> *const ::SSL_METHOD; + pub fn TLSv1_2_method() -> *const ::SSL_METHOD; + pub fn DTLSv1_method() -> *const ::SSL_METHOD; + pub fn SSL_get_ex_new_index( + argl: c_long, + argp: *mut c_void, + new_func: Option<::CRYPTO_EX_new>, + dup_func: Option<::CRYPTO_EX_dup>, + free_func: Option<::CRYPTO_EX_free>, + ) -> c_int; + pub fn SSL_set_tmp_ecdh_callback( + ssl: *mut ::SSL, + ecdh: unsafe extern "C" fn(ssl: *mut ::SSL, is_export: c_int, keylength: c_int) + -> *mut ::EC_KEY, + ); + pub fn SSL_CIPHER_get_version(cipher: *const ::SSL_CIPHER) -> *mut c_char; + pub fn SSL_CTX_get_ex_new_index( + argl: c_long, + argp: *mut c_void, + new_func: Option<::CRYPTO_EX_new>, + dup_func: Option<::CRYPTO_EX_dup>, + free_func: Option<::CRYPTO_EX_free>, + ) -> c_int; + // FIXME should take an option + pub fn SSL_CTX_set_tmp_ecdh_callback( + ctx: *mut ::SSL_CTX, + ecdh: unsafe extern "C" fn(ssl: *mut ::SSL, is_export: c_int, keylength: c_int) + -> *mut ::EC_KEY, + ); + pub fn SSL_CTX_sess_set_get_cb( + ctx: *mut ::SSL_CTX, + get_session_cb: Option< + unsafe extern "C" fn(*mut ::SSL, *mut c_uchar, c_int, *mut c_int) -> *mut SSL_SESSION, + >, + ); + pub fn X509_get_subject_name(x: *mut ::X509) -> *mut ::X509_NAME; + pub fn X509_get_issuer_name(x: *mut ::X509) -> *mut ::X509_NAME; + pub fn X509_set_notAfter(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; + pub fn X509_set_notBefore(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; + pub fn X509_get_ext_d2i( + x: *mut ::X509, + nid: c_int, + crit: *mut c_int, + idx: *mut c_int, + ) -> *mut c_void; + pub fn X509_NAME_add_entry_by_NID( + x: *mut ::X509_NAME, + field: c_int, + ty: c_int, + bytes: *mut c_uchar, + len: c_int, + loc: c_int, + set: c_int, + ) -> c_int; + pub fn X509_NAME_get_entry(n: *mut ::X509_NAME, loc: c_int) -> *mut ::X509_NAME_ENTRY; + pub fn X509_NAME_ENTRY_get_data(ne: *mut ::X509_NAME_ENTRY) -> *mut ::ASN1_STRING; + pub fn X509_STORE_CTX_get_chain(ctx: *mut ::X509_STORE_CTX) -> *mut stack_st_X509; + pub fn X509V3_EXT_nconf_nid( + conf: *mut ::CONF, + ctx: *mut ::X509V3_CTX, + ext_nid: c_int, + value: *mut c_char, + ) -> *mut ::X509_EXTENSION; + pub fn X509V3_EXT_nconf( + conf: *mut ::CONF, + ctx: *mut ::X509V3_CTX, + name: *mut c_char, + value: *mut c_char, + ) -> *mut ::X509_EXTENSION; + pub fn ASN1_STRING_to_UTF8(out: *mut *mut c_uchar, s: *mut ::ASN1_STRING) -> c_int; + pub fn ASN1_STRING_data(x: *mut ::ASN1_STRING) -> *mut c_uchar; + pub fn CRYPTO_add_lock( + pointer: *mut c_int, + amount: c_int, + type_: c_int, + file: *const c_char, + line: c_int, + ) -> c_int; + pub fn EVP_MD_CTX_create() -> *mut EVP_MD_CTX; + pub fn EVP_MD_CTX_destroy(ctx: *mut EVP_MD_CTX); + pub fn EVP_PKEY_bits(key: *mut EVP_PKEY) -> c_int; + + pub fn sk_new_null() -> *mut _STACK; + pub fn sk_num(st: *const _STACK) -> c_int; + pub fn sk_value(st: *const _STACK, n: c_int) -> *mut c_void; + pub fn sk_free(st: *mut _STACK); + pub fn sk_push(st: *mut _STACK, data: *mut c_void) -> c_int; + pub fn sk_pop_free(st: *mut _STACK, free: Option); + pub fn sk_pop(st: *mut _STACK) -> *mut c_void; + + pub fn SSLeay() -> c_ulong; + pub fn SSLeay_version(key: c_int) -> *const c_char; +} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.28/src/libressl/v250.rs cargo-0.26.0/vendor/openssl-sys-0.9.28/src/libressl/v250.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.28/src/libressl/v250.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.28/src/libressl/v250.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,221 @@ +use libc::{c_int, c_char, c_void, c_long, c_uchar, size_t, c_uint, c_ulong, time_t}; + +use super::*; + +#[repr(C)] +pub struct SSL { + version: c_int, + type_: c_int, + method: *const ::SSL_METHOD, + rbio: *mut c_void, + wbio: *mut c_void, + bbio: *mut c_void, + rwstate: c_int, + in_handshake: c_int, + handshake_func: Option c_int>, + pub server: c_int, + new_session: c_int, + quiet_shutdown: c_int, + shutdown: c_int, + state: c_int, + rstate: c_int, + init_buf: *mut c_void, + init_msg: *mut c_void, + init_num: c_int, + init_off: c_int, + packet: *mut c_uchar, + packet_length: c_uint, + s3: *mut c_void, + d1: *mut c_void, + read_ahead: c_int, + msg_callback: Option< + unsafe extern "C" fn(c_int, + c_int, + c_int, + *const c_void, + size_t, + *mut SSL, + *mut c_void), + >, + msg_callback_arg: *mut c_void, + hit: c_int, + param: *mut c_void, + cipher_list: *mut stack_st_SSL_CIPHER, + cipher_list_by_id: *mut stack_st_SSL_CIPHER, + mac_flags: c_int, + aead_read_ctx: *mut c_void, + enc_read_ctx: *mut ::EVP_CIPHER_CTX, + read_hash: *mut ::EVP_MD_CTX, + aead_write_ctx: *mut c_void, + enc_write_ctx: *mut ::EVP_CIPHER_CTX, + write_hash: *mut ::EVP_MD_CTX, + cert: *mut c_void, + sid_ctx_length: c_uint, + sid_ctx: [c_uchar; ::SSL_MAX_SID_CTX_LENGTH as usize], + session: *mut ::SSL_SESSION, + generate_session_id: ::GEN_SESSION_CB, + verify_mode: c_int, + verify_callback: Option c_int>, + info_callback: Option, + error: c_int, + error_code: c_int, + ctx: *mut ::SSL_CTX, + debug: c_int, + verify_result: c_long, + ex_data: ::CRYPTO_EX_DATA, + client_CA: *mut stack_st_X509_NAME, + references: c_int, + options: c_ulong, + mode: c_ulong, + max_cert_list: c_long, + first_packet: c_int, + client_version: c_int, + max_send_fragment: c_uint, + tlsext_debug_cb: + Option, + tlsext_debug_arg: *mut c_void, + tlsext_hostname: *mut c_char, + servername_done: c_int, + tlsext_status_type: c_int, + tlsext_status_expected: c_int, + tlsext_ocsp_ids: *mut c_void, + tlsext_ocsp_exts: *mut c_void, + tlsext_ocsp_resp: *mut c_uchar, + tlsext_ocsp_resplen: c_int, + tlsext_ticket_expected: c_int, + tlsext_ecpointformatlist_length: size_t, + tlsext_ecpointformatlist: *mut c_uchar, + tlsext_ellipticcurvelist_length: size_t, + tlsext_ellipticcurvelist: *mut c_uchar, + tlsext_session_ticket: *mut c_void, + tlsext_session_ticket_ext_cb: ::tls_session_ticket_ext_cb_fn, + tls_session_ticket_ext_cb_arg: *mut c_void, + tls_session_secret_cb: ::tls_session_secret_cb_fn, + tls_session_secret_cb_arg: *mut c_void, + initial_ctx: *mut ::SSL_CTX, + next_proto_negotiated: *mut c_uchar, + next_proto_negotiated_len: c_uchar, + srtp_profiles: *mut c_void, + srtp_profile: *mut c_void, + tlsext_heartbeat: c_uint, + tlsext_hb_pending: c_uint, + tlsext_hb_seq: c_uint, + alpn_client_proto_list: *mut c_uchar, + alpn_client_proto_list_len: c_uint, + renegotiate: c_int, +} + +#[repr(C)] +pub struct SSL_CTX { + method: *mut c_void, + cipher_list: *mut c_void, + cipher_list_by_id: *mut c_void, + cert_store: *mut c_void, + sessions: *mut c_void, + session_cache_size: c_ulong, + session_cache_head: *mut c_void, + session_cache_tail: *mut c_void, + session_cache_mode: c_int, + session_timeout: c_long, + new_session_cb: *mut c_void, + remove_session_cb: *mut c_void, + get_session_cb: *mut c_void, + stats: [c_int; 11], + pub references: c_int, + app_verify_callback: *mut c_void, + app_verify_arg: *mut c_void, + default_passwd_callback: *mut c_void, + default_passwd_callback_userdata: *mut c_void, + client_cert_cb: *mut c_void, + app_gen_cookie_cb: *mut c_void, + app_verify_cookie_cb: *mut c_void, + ex_dat: ::CRYPTO_EX_DATA, + rsa_md5: *mut c_void, + md5: *mut c_void, + sha1: *mut c_void, + extra_certs: *mut c_void, + comp_methods: *mut c_void, + info_callback: *mut c_void, + client_CA: *mut c_void, + options: c_ulong, + mode: c_ulong, + max_cert_list: c_long, + cert: *mut c_void, + read_ahead: c_int, + msg_callback: *mut c_void, + msg_callback_arg: *mut c_void, + verify_mode: c_int, + sid_ctx_length: c_uint, + sid_ctx: [c_uchar; 32], + default_verify_callback: *mut c_void, + generate_session_id: *mut c_void, + param: *mut c_void, + quiet_shutdown: c_int, + max_send_fragment: c_uint, + + #[cfg(not(osslconf = "OPENSSL_NO_ENGINE"))] + client_cert_engine: *mut c_void, + + tlsext_servername_callback: *mut c_void, + tlsect_servername_arg: *mut c_void, + tlsext_tick_key_name: [c_uchar; 16], + tlsext_tick_hmac_key: [c_uchar; 16], + tlsext_tick_aes_key: [c_uchar; 16], + tlsext_ticket_key_cb: *mut c_void, + tlsext_status_cb: *mut c_void, + tlsext_status_arg: *mut c_void, + tlsext_opaque_prf_input_callback: *mut c_void, + tlsext_opaque_prf_input_callback_arg: *mut c_void, + + next_protos_advertised_cb: *mut c_void, + next_protos_advertised_cb_arg: *mut c_void, + next_proto_select_cb: *mut c_void, + next_proto_select_cb_arg: *mut c_void, + + srtp_profiles: *mut c_void, +} + +#[repr(C)] +pub struct SSL_SESSION { + ssl_version: c_int, + pub master_key_length: c_int, + pub master_key: [c_uchar; 48], + session_id_length: c_uint, + session_id: [c_uchar; SSL_MAX_SSL_SESSION_ID_LENGTH as usize], + sid_ctx_length: c_uint, + sid_ctx: [c_uchar; SSL_MAX_SID_CTX_LENGTH as usize], + not_resumable: c_int, + sess_cert: *mut c_void, + peer: *mut X509, + verify_result: c_long, + timeout: c_long, + time: time_t, + pub references: c_int, + cipher: *const c_void, + cipher_id: c_ulong, + ciphers: *mut c_void, + ex_data: ::CRYPTO_EX_DATA, + prev: *mut c_void, + next: *mut c_void, + tlsext_hostname: *mut c_char, + tlsext_ecpointformatlist_length: size_t, + tlsext_ecpointformatlist: *mut u8, + tlsext_ellipticcurvelist_length: size_t, + tlsext_ellipticcurvelist: *mut u16, + tlsext_tick: *mut c_uchar, + tlsext_ticklen: size_t, + tlsext_tick_lifetime_hint: c_long, +} + +#[repr(C)] +pub struct X509_VERIFY_PARAM { + pub name: *mut c_char, + pub check_time: time_t, + pub inh_flags: c_ulong, + pub flags: c_ulong, + pub purpose: c_int, + pub trust: c_int, + pub depth: c_int, + pub policies: *mut stack_st_ASN1_OBJECT, + //pub id: *mut X509_VERIFY_PARAM_ID, +} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.28/src/libressl/v25x.rs cargo-0.26.0/vendor/openssl-sys-0.9.28/src/libressl/v25x.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.28/src/libressl/v25x.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.28/src/libressl/v25x.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,89 @@ +use libc::{c_int, c_char, c_void, c_long, c_uchar, size_t, c_uint, c_ulong, time_t}; + +use super::*; + +#[repr(C)] +pub struct SSL { + version: c_int, + method: *const ::SSL_METHOD, + rbio: *mut ::BIO, + wbio: *mut ::BIO, + bbio: *mut ::BIO, + pub server: c_int, + s3: *mut c_void, + d1: *mut c_void, + param: *mut c_void, + cipher_list: *mut stack_st_SSL_CIPHER, + cert: *mut c_void, + sid_ctx_length: c_uint, + sid_ctx: [c_uchar; ::SSL_MAX_SID_CTX_LENGTH as usize], + session: *mut ::SSL_SESSION, + verify_mode: c_int, + error: c_int, + error_code: c_int, + ctx: *mut ::SSL_CTX, + verify_result: c_long, + references: c_int, + client_version: c_int, + max_send_fragment: c_uint, + tlsext_hostname: *mut c_char, + tlsext_status_type: c_int, + initial_ctx: *mut ::SSL_CTX, + enc_read_ctx: *mut ::EVP_CIPHER_CTX, + read_hash: *mut EVP_MD_CTX, + internal: *mut c_void, +} + +#[repr(C)] +pub struct SSL_CTX { + method: *const ::SSL_METHOD, + cipher_list: *mut stack_st_SSL_CIPHER, + cert_store: *mut c_void, + session_timeout: c_long, + pub references: c_int, + extra_certs: *mut stack_st_X509, + verify_mode: c_int, + sid_ctx_length: c_uint, + sid_ctx: [c_uchar; ::SSL_MAX_SID_CTX_LENGTH as usize], + param: *mut ::X509_VERIFY_PARAM, + default_passwd_callback: *mut c_void, + default_passwd_callback_userdata: *mut c_void, + internal: *mut c_void, +} + +#[repr(C)] +pub struct SSL_SESSION { + ssl_version: c_int, + pub master_key_length: c_int, + pub master_key: [c_uchar; 48], + session_id_length: c_uint, + session_id: [c_uchar; ::SSL_MAX_SSL_SESSION_ID_LENGTH as usize], + sid_ctx_length: c_uint, + sid_ctx: [c_uchar; ::SSL_MAX_SID_CTX_LENGTH as usize], + peer: *mut ::X509, + verify_result: c_long, + timeout: c_long, + time: time_t, + pub references: c_int, + cipher: *const ::SSL_CIPHER, + cipher_id: c_long, + ciphers: *mut stack_st_SSL_CIPHER, + tlsext_hostname: *mut c_char, + tlsext_tick: *mut c_uchar, + tlsext_ticklen: size_t, + tlsext_tick_lifetime_int: c_long, + internal: *mut c_void, +} + +#[repr(C)] +pub struct X509_VERIFY_PARAM { + pub name: *mut c_char, + pub check_time: time_t, + pub inh_flags: c_ulong, + pub flags: c_ulong, + pub purpose: c_int, + pub trust: c_int, + pub depth: c_int, + policies: *mut stack_st_ASN1_OBJECT, + id: *mut c_void, +} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.28/src/lib.rs cargo-0.26.0/vendor/openssl-sys-0.9.28/src/lib.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.28/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.28/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2878 @@ +#![allow(non_camel_case_types, non_upper_case_globals, non_snake_case)] +#![allow(dead_code, overflowing_literals)] +#![doc(html_root_url = "https://docs.rs/openssl-sys/0.9")] + +extern crate libc; + +use libc::{c_char, c_int, c_long, c_uchar, c_uint, c_ulong, c_void, size_t, FILE}; +use std::ptr; +use std::mem; + +#[cfg(any(ossl101, ossl102))] +mod ossl10x; +#[cfg(any(ossl101, ossl102))] +pub use ossl10x::*; + +#[cfg(ossl110)] +mod ossl110; +#[cfg(ossl110)] +pub use ossl110::*; + +#[cfg(ossl111)] +mod ossl111; +#[cfg(ossl111)] +pub use ossl111::*; + +#[cfg(libressl)] +mod libressl; +#[cfg(libressl)] +pub use libressl::*; + +pub enum ASN1_INTEGER {} +pub enum ASN1_GENERALIZEDTIME {} +pub enum ASN1_STRING {} +pub enum ASN1_BIT_STRING {} +pub enum ASN1_TIME {} +pub enum ASN1_TYPE {} +pub enum ASN1_OBJECT {} +pub enum BN_CTX {} +pub enum BN_GENCB {} +pub enum CMS_ContentInfo {} +pub enum CONF {} +pub enum CONF_METHOD {} +pub enum COMP_METHOD {} +pub enum EC_KEY {} +pub enum EC_GROUP {} +pub enum EC_METHOD {} +pub enum EC_POINT {} +pub enum ENGINE {} +pub enum EVP_CIPHER_CTX {} +pub enum EVP_MD {} +pub enum EVP_PKEY_CTX {} +pub enum OCSP_BASICRESP {} +pub enum OCSP_CERTID {} +pub enum OCSP_RESPONSE {} +pub enum OCSP_REQUEST {} +pub enum OCSP_ONEREQ {} +pub enum SSL_CIPHER {} +pub enum SSL_METHOD {} +pub enum X509_CRL {} +pub enum X509_EXTENSION {} +pub enum X509_NAME {} +pub enum X509_NAME_ENTRY {} +pub enum X509_STORE {} +pub enum X509_STORE_CTX {} +pub enum bio_st {} +pub enum DH_METHOD {} +pub enum RSA_METHOD {} +pub enum BN_MONT_CTX {} +pub enum BN_BLINDING {} +pub enum DSA_METHOD {} +pub enum EVP_PKEY_ASN1_METHOD {} + +pub type bio_info_cb = + Option; +pub type GEN_SESSION_CB = + Option c_int>; +pub type tls_session_ticket_ext_cb_fn = + Option c_int>; +pub type tls_session_secret_cb_fn = Option< + unsafe extern "C" fn( + *mut SSL, + *mut c_void, + *mut c_int, + *mut stack_st_SSL_CIPHER, + *mut *mut SSL_CIPHER, + *mut c_void, + ) -> c_int, +>; + +#[repr(C)] +#[derive(Copy, Clone)] +pub enum point_conversion_form_t { + POINT_CONVERSION_COMPRESSED = 2, + POINT_CONVERSION_UNCOMPRESSED = 4, + POINT_CONVERSION_HYBRID = 6, +} + +#[repr(C)] +pub struct AES_KEY { + // There is some business with AES_LONG which is there to ensure the values here are 32 bits + rd_key: [u32; 4 * (AES_MAXNR as usize + 1)], + rounds: c_int, +} + +#[repr(C)] +pub struct GENERAL_NAME { + pub type_: c_int, + pub d: *mut c_void, +} + +#[repr(C)] +pub struct X509V3_CTX { + flags: c_int, + issuer_cert: *mut c_void, + subject_cert: *mut c_void, + subject_req: *mut c_void, + crl: *mut c_void, + db_meth: *mut c_void, + db: *mut c_void, + // I like the last comment line, it is copied from OpenSSL sources: + // Maybe more here +} + +#[repr(C)] +pub struct SHA_CTX { + pub h0: SHA_LONG, + pub h1: SHA_LONG, + pub h2: SHA_LONG, + pub h3: SHA_LONG, + pub h4: SHA_LONG, + pub Nl: SHA_LONG, + pub Nh: SHA_LONG, + pub data: [SHA_LONG; SHA_LBLOCK as usize], + pub num: c_uint, +} + +#[repr(C)] +pub struct SHA256_CTX { + pub h: [SHA_LONG; 8], + pub Nl: SHA_LONG, + pub Nh: SHA_LONG, + pub data: [SHA_LONG; SHA_LBLOCK as usize], + pub num: c_uint, + pub md_len: c_uint, +} + +#[repr(C)] +pub struct SHA512_CTX { + pub h: [SHA_LONG64; 8], + pub Nl: SHA_LONG64, + pub Nh: SHA_LONG64, + // this is a union but we don't want to require 1.19 + u: [SHA_LONG64; SHA_LBLOCK as usize], + pub num: c_uint, + pub md_len: c_uint, +} + +#[cfg(target_pointer_width = "64")] +pub type BN_ULONG = libc::c_ulonglong; +#[cfg(target_pointer_width = "32")] +pub type BN_ULONG = c_uint; + +pub type CRYPTO_EX_new = unsafe extern "C" fn( + parent: *mut c_void, + ptr: *mut c_void, + ad: *const CRYPTO_EX_DATA, + idx: c_int, + argl: c_long, + argp: *const c_void, +) -> c_int; +pub type CRYPTO_EX_dup = unsafe extern "C" fn( + to: *mut CRYPTO_EX_DATA, + from: *mut CRYPTO_EX_DATA, + from_d: *mut c_void, + idx: c_int, + argl: c_long, + argp: *mut c_void, +) -> c_int; +pub type CRYPTO_EX_free = unsafe extern "C" fn( + parent: *mut c_void, + ptr: *mut c_void, + ad: *mut CRYPTO_EX_DATA, + idx: c_int, + argl: c_long, + argp: *mut c_void, +); +pub type PasswordCallback = + unsafe extern "C" fn(buf: *mut c_char, size: c_int, rwflag: c_int, user_data: *mut c_void) + -> c_int; + +pub type SHA_LONG = c_uint; +pub type SHA_LONG64 = u64; + +pub const AES_ENCRYPT: c_int = 1; +pub const AES_DECRYPT: c_int = 0; + +pub const AES_MAXNR: c_int = 14; +pub const AES_BLOCK_SIZE: c_int = 16; + +pub const BIO_TYPE_NONE: c_int = 0; + +pub const BIO_CTRL_EOF: c_int = 2; +pub const BIO_CTRL_INFO: c_int = 3; +pub const BIO_CTRL_FLUSH: c_int = 11; +pub const BIO_C_SET_BUF_MEM_EOF_RETURN: c_int = 130; + +pub const BIO_FLAGS_READ: c_int = 0x01; +pub const BIO_FLAGS_WRITE: c_int = 0x02; +pub const BIO_FLAGS_IO_SPECIAL: c_int = 0x04; +pub const BIO_FLAGS_RWS: c_int = BIO_FLAGS_READ | BIO_FLAGS_WRITE | BIO_FLAGS_IO_SPECIAL; +pub const BIO_FLAGS_SHOULD_RETRY: c_int = 0x08; + +pub const CRYPTO_LOCK: c_int = 1; + +pub const ERR_TXT_MALLOCED: c_int = 0x01; +pub const ERR_TXT_STRING: c_int = 0x02; + +pub const ERR_LIB_PEM: c_int = 9; +pub const PEM_R_NO_START_LINE: c_int = 108; + +pub const EVP_MAX_MD_SIZE: c_uint = 64; +pub const EVP_PKEY_RSA: c_int = NID_rsaEncryption; +pub const EVP_PKEY_HMAC: c_int = NID_hmac; +pub const EVP_PKEY_CMAC: c_int = NID_cmac; +pub const EVP_PKEY_DSA: c_int = NID_dsa; +pub const EVP_PKEY_DH: c_int = NID_dhKeyAgreement; +pub const EVP_PKEY_EC: c_int = NID_X9_62_id_ecPublicKey; + +pub const EVP_PKEY_ALG_CTRL: c_int = 0x1000; + +pub const EVP_PKEY_CTRL_RSA_PADDING: c_int = EVP_PKEY_ALG_CTRL + 1; +pub const EVP_PKEY_CTRL_RSA_PSS_SALTLEN: c_int = EVP_PKEY_ALG_CTRL + 2; + +pub const EVP_PKEY_CTRL_RSA_MGF1_MD: c_int = EVP_PKEY_ALG_CTRL + 5; +pub const EVP_PKEY_CTRL_GET_RSA_PADDING: c_int = EVP_PKEY_ALG_CTRL + 6; + +pub const EVP_PKEY_CTRL_SET_MAC_KEY: c_int = 6; +pub const EVP_PKEY_CTRL_CIPHER: c_int = 12; + +pub const EVP_PKEY_OP_KEYGEN: c_int = 1 << 2; +pub const EVP_PKEY_OP_SIGN: c_int = 1 << 3; +pub const EVP_PKEY_OP_VERIFY: c_int = 1 << 4; +pub const EVP_PKEY_OP_VERIFYRECOVER: c_int = 1 << 5; +pub const EVP_PKEY_OP_SIGNCTX: c_int = 1 << 6; +pub const EVP_PKEY_OP_VERIFYCTX: c_int = 1 << 7; +pub const EVP_PKEY_OP_ENCRYPT: c_int = 1 << 8; +pub const EVP_PKEY_OP_DECRYPT: c_int = 1 << 9; + +pub const EVP_PKEY_OP_TYPE_SIG: c_int = EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY + | EVP_PKEY_OP_VERIFYRECOVER | EVP_PKEY_OP_SIGNCTX + | EVP_PKEY_OP_VERIFYCTX; + +pub const EVP_PKEY_OP_TYPE_CRYPT: c_int = EVP_PKEY_OP_ENCRYPT | EVP_PKEY_OP_DECRYPT; + +pub const EVP_CTRL_GCM_SET_IVLEN: c_int = 0x9; +pub const EVP_CTRL_GCM_GET_TAG: c_int = 0x10; +pub const EVP_CTRL_GCM_SET_TAG: c_int = 0x11; + +pub const MBSTRING_ASC: c_int = MBSTRING_FLAG | 1; +pub const MBSTRING_BMP: c_int = MBSTRING_FLAG | 2; +pub const MBSTRING_FLAG: c_int = 0x1000; +pub const MBSTRING_UNIV: c_int = MBSTRING_FLAG | 4; +pub const MBSTRING_UTF8: c_int = MBSTRING_FLAG; + +pub const NID_undef: c_int = 0; +pub const NID_itu_t: c_int = 645; +pub const NID_ccitt: c_int = 404; +pub const NID_iso: c_int = 181; +pub const NID_joint_iso_itu_t: c_int = 646; +pub const NID_joint_iso_ccitt: c_int = 393; +pub const NID_member_body: c_int = 182; +pub const NID_identified_organization: c_int = 676; +pub const NID_hmac_md5: c_int = 780; +pub const NID_hmac_sha1: c_int = 781; +pub const NID_certicom_arc: c_int = 677; +pub const NID_international_organizations: c_int = 647; +pub const NID_wap: c_int = 678; +pub const NID_wap_wsg: c_int = 679; +pub const NID_selected_attribute_types: c_int = 394; +pub const NID_clearance: c_int = 395; +pub const NID_ISO_US: c_int = 183; +pub const NID_X9_57: c_int = 184; +pub const NID_X9cm: c_int = 185; +pub const NID_dsa: c_int = 116; +pub const NID_dsaWithSHA1: c_int = 113; +pub const NID_ansi_X9_62: c_int = 405; +pub const NID_X9_62_prime_field: c_int = 406; +pub const NID_X9_62_characteristic_two_field: c_int = 407; +pub const NID_X9_62_id_characteristic_two_basis: c_int = 680; +pub const NID_X9_62_onBasis: c_int = 681; +pub const NID_X9_62_tpBasis: c_int = 682; +pub const NID_X9_62_ppBasis: c_int = 683; +pub const NID_X9_62_id_ecPublicKey: c_int = 408; +pub const NID_X9_62_c2pnb163v1: c_int = 684; +pub const NID_X9_62_c2pnb163v2: c_int = 685; +pub const NID_X9_62_c2pnb163v3: c_int = 686; +pub const NID_X9_62_c2pnb176v1: c_int = 687; +pub const NID_X9_62_c2tnb191v1: c_int = 688; +pub const NID_X9_62_c2tnb191v2: c_int = 689; +pub const NID_X9_62_c2tnb191v3: c_int = 690; +pub const NID_X9_62_c2onb191v4: c_int = 691; +pub const NID_X9_62_c2onb191v5: c_int = 692; +pub const NID_X9_62_c2pnb208w1: c_int = 693; +pub const NID_X9_62_c2tnb239v1: c_int = 694; +pub const NID_X9_62_c2tnb239v2: c_int = 695; +pub const NID_X9_62_c2tnb239v3: c_int = 696; +pub const NID_X9_62_c2onb239v4: c_int = 697; +pub const NID_X9_62_c2onb239v5: c_int = 698; +pub const NID_X9_62_c2pnb272w1: c_int = 699; +pub const NID_X9_62_c2pnb304w1: c_int = 700; +pub const NID_X9_62_c2tnb359v1: c_int = 701; +pub const NID_X9_62_c2pnb368w1: c_int = 702; +pub const NID_X9_62_c2tnb431r1: c_int = 703; +pub const NID_X9_62_prime192v1: c_int = 409; +pub const NID_X9_62_prime192v2: c_int = 410; +pub const NID_X9_62_prime192v3: c_int = 411; +pub const NID_X9_62_prime239v1: c_int = 412; +pub const NID_X9_62_prime239v2: c_int = 413; +pub const NID_X9_62_prime239v3: c_int = 414; +pub const NID_X9_62_prime256v1: c_int = 415; +pub const NID_ecdsa_with_SHA1: c_int = 416; +pub const NID_ecdsa_with_Recommended: c_int = 791; +pub const NID_ecdsa_with_Specified: c_int = 792; +pub const NID_ecdsa_with_SHA224: c_int = 793; +pub const NID_ecdsa_with_SHA256: c_int = 794; +pub const NID_ecdsa_with_SHA384: c_int = 795; +pub const NID_ecdsa_with_SHA512: c_int = 796; +pub const NID_secp112r1: c_int = 704; +pub const NID_secp112r2: c_int = 705; +pub const NID_secp128r1: c_int = 706; +pub const NID_secp128r2: c_int = 707; +pub const NID_secp160k1: c_int = 708; +pub const NID_secp160r1: c_int = 709; +pub const NID_secp160r2: c_int = 710; +pub const NID_secp192k1: c_int = 711; +pub const NID_secp224k1: c_int = 712; +pub const NID_secp224r1: c_int = 713; +pub const NID_secp256k1: c_int = 714; +pub const NID_secp384r1: c_int = 715; +pub const NID_secp521r1: c_int = 716; +pub const NID_sect113r1: c_int = 717; +pub const NID_sect113r2: c_int = 718; +pub const NID_sect131r1: c_int = 719; +pub const NID_sect131r2: c_int = 720; +pub const NID_sect163k1: c_int = 721; +pub const NID_sect163r1: c_int = 722; +pub const NID_sect163r2: c_int = 723; +pub const NID_sect193r1: c_int = 724; +pub const NID_sect193r2: c_int = 725; +pub const NID_sect233k1: c_int = 726; +pub const NID_sect233r1: c_int = 727; +pub const NID_sect239k1: c_int = 728; +pub const NID_sect283k1: c_int = 729; +pub const NID_sect283r1: c_int = 730; +pub const NID_sect409k1: c_int = 731; +pub const NID_sect409r1: c_int = 732; +pub const NID_sect571k1: c_int = 733; +pub const NID_sect571r1: c_int = 734; +pub const NID_wap_wsg_idm_ecid_wtls1: c_int = 735; +pub const NID_wap_wsg_idm_ecid_wtls3: c_int = 736; +pub const NID_wap_wsg_idm_ecid_wtls4: c_int = 737; +pub const NID_wap_wsg_idm_ecid_wtls5: c_int = 738; +pub const NID_wap_wsg_idm_ecid_wtls6: c_int = 739; +pub const NID_wap_wsg_idm_ecid_wtls7: c_int = 740; +pub const NID_wap_wsg_idm_ecid_wtls8: c_int = 741; +pub const NID_wap_wsg_idm_ecid_wtls9: c_int = 742; +pub const NID_wap_wsg_idm_ecid_wtls10: c_int = 743; +pub const NID_wap_wsg_idm_ecid_wtls11: c_int = 744; +pub const NID_wap_wsg_idm_ecid_wtls12: c_int = 745; +pub const NID_cast5_cbc: c_int = 108; +pub const NID_cast5_ecb: c_int = 109; +pub const NID_cast5_cfb64: c_int = 110; +pub const NID_cast5_ofb64: c_int = 111; +pub const NID_pbeWithMD5AndCast5_CBC: c_int = 112; +pub const NID_id_PasswordBasedMAC: c_int = 782; +pub const NID_id_DHBasedMac: c_int = 783; +pub const NID_rsadsi: c_int = 1; +pub const NID_pkcs: c_int = 2; +pub const NID_pkcs1: c_int = 186; +pub const NID_rsaEncryption: c_int = 6; +pub const NID_md2WithRSAEncryption: c_int = 7; +pub const NID_md4WithRSAEncryption: c_int = 396; +pub const NID_md5WithRSAEncryption: c_int = 8; +pub const NID_sha1WithRSAEncryption: c_int = 65; +pub const NID_rsaesOaep: c_int = 919; +pub const NID_mgf1: c_int = 911; +pub const NID_rsassaPss: c_int = 912; +pub const NID_sha256WithRSAEncryption: c_int = 668; +pub const NID_sha384WithRSAEncryption: c_int = 669; +pub const NID_sha512WithRSAEncryption: c_int = 670; +pub const NID_sha224WithRSAEncryption: c_int = 671; +pub const NID_pkcs3: c_int = 27; +pub const NID_dhKeyAgreement: c_int = 28; +pub const NID_pkcs5: c_int = 187; +pub const NID_pbeWithMD2AndDES_CBC: c_int = 9; +pub const NID_pbeWithMD5AndDES_CBC: c_int = 10; +pub const NID_pbeWithMD2AndRC2_CBC: c_int = 168; +pub const NID_pbeWithMD5AndRC2_CBC: c_int = 169; +pub const NID_pbeWithSHA1AndDES_CBC: c_int = 170; +pub const NID_pbeWithSHA1AndRC2_CBC: c_int = 68; +pub const NID_id_pbkdf2: c_int = 69; +pub const NID_pbes2: c_int = 161; +pub const NID_pbmac1: c_int = 162; +pub const NID_pkcs7: c_int = 20; +pub const NID_pkcs7_data: c_int = 21; +pub const NID_pkcs7_signed: c_int = 22; +pub const NID_pkcs7_enveloped: c_int = 23; +pub const NID_pkcs7_signedAndEnveloped: c_int = 24; +pub const NID_pkcs7_digest: c_int = 25; +pub const NID_pkcs7_encrypted: c_int = 26; +pub const NID_pkcs9: c_int = 47; +pub const NID_pkcs9_emailAddress: c_int = 48; +pub const NID_pkcs9_unstructuredName: c_int = 49; +pub const NID_pkcs9_contentType: c_int = 50; +pub const NID_pkcs9_messageDigest: c_int = 51; +pub const NID_pkcs9_signingTime: c_int = 52; +pub const NID_pkcs9_countersignature: c_int = 53; +pub const NID_pkcs9_challengePassword: c_int = 54; +pub const NID_pkcs9_unstructuredAddress: c_int = 55; +pub const NID_pkcs9_extCertAttributes: c_int = 56; +pub const NID_ext_req: c_int = 172; +pub const NID_SMIMECapabilities: c_int = 167; +pub const NID_SMIME: c_int = 188; +pub const NID_id_smime_mod: c_int = 189; +pub const NID_id_smime_ct: c_int = 190; +pub const NID_id_smime_aa: c_int = 191; +pub const NID_id_smime_alg: c_int = 192; +pub const NID_id_smime_cd: c_int = 193; +pub const NID_id_smime_spq: c_int = 194; +pub const NID_id_smime_cti: c_int = 195; +pub const NID_id_smime_mod_cms: c_int = 196; +pub const NID_id_smime_mod_ess: c_int = 197; +pub const NID_id_smime_mod_oid: c_int = 198; +pub const NID_id_smime_mod_msg_v3: c_int = 199; +pub const NID_id_smime_mod_ets_eSignature_88: c_int = 200; +pub const NID_id_smime_mod_ets_eSignature_97: c_int = 201; +pub const NID_id_smime_mod_ets_eSigPolicy_88: c_int = 202; +pub const NID_id_smime_mod_ets_eSigPolicy_97: c_int = 203; +pub const NID_id_smime_ct_receipt: c_int = 204; +pub const NID_id_smime_ct_authData: c_int = 205; +pub const NID_id_smime_ct_publishCert: c_int = 206; +pub const NID_id_smime_ct_TSTInfo: c_int = 207; +pub const NID_id_smime_ct_TDTInfo: c_int = 208; +pub const NID_id_smime_ct_contentInfo: c_int = 209; +pub const NID_id_smime_ct_DVCSRequestData: c_int = 210; +pub const NID_id_smime_ct_DVCSResponseData: c_int = 211; +pub const NID_id_smime_ct_compressedData: c_int = 786; +pub const NID_id_ct_asciiTextWithCRLF: c_int = 787; +pub const NID_id_smime_aa_receiptRequest: c_int = 212; +pub const NID_id_smime_aa_securityLabel: c_int = 213; +pub const NID_id_smime_aa_mlExpandHistory: c_int = 214; +pub const NID_id_smime_aa_contentHint: c_int = 215; +pub const NID_id_smime_aa_msgSigDigest: c_int = 216; +pub const NID_id_smime_aa_encapContentType: c_int = 217; +pub const NID_id_smime_aa_contentIdentifier: c_int = 218; +pub const NID_id_smime_aa_macValue: c_int = 219; +pub const NID_id_smime_aa_equivalentLabels: c_int = 220; +pub const NID_id_smime_aa_contentReference: c_int = 221; +pub const NID_id_smime_aa_encrypKeyPref: c_int = 222; +pub const NID_id_smime_aa_signingCertificate: c_int = 223; +pub const NID_id_smime_aa_smimeEncryptCerts: c_int = 224; +pub const NID_id_smime_aa_timeStampToken: c_int = 225; +pub const NID_id_smime_aa_ets_sigPolicyId: c_int = 226; +pub const NID_id_smime_aa_ets_commitmentType: c_int = 227; +pub const NID_id_smime_aa_ets_signerLocation: c_int = 228; +pub const NID_id_smime_aa_ets_signerAttr: c_int = 229; +pub const NID_id_smime_aa_ets_otherSigCert: c_int = 230; +pub const NID_id_smime_aa_ets_contentTimestamp: c_int = 231; +pub const NID_id_smime_aa_ets_CertificateRefs: c_int = 232; +pub const NID_id_smime_aa_ets_RevocationRefs: c_int = 233; +pub const NID_id_smime_aa_ets_certValues: c_int = 234; +pub const NID_id_smime_aa_ets_revocationValues: c_int = 235; +pub const NID_id_smime_aa_ets_escTimeStamp: c_int = 236; +pub const NID_id_smime_aa_ets_certCRLTimestamp: c_int = 237; +pub const NID_id_smime_aa_ets_archiveTimeStamp: c_int = 238; +pub const NID_id_smime_aa_signatureType: c_int = 239; +pub const NID_id_smime_aa_dvcs_dvc: c_int = 240; +pub const NID_id_smime_alg_ESDHwith3DES: c_int = 241; +pub const NID_id_smime_alg_ESDHwithRC2: c_int = 242; +pub const NID_id_smime_alg_3DESwrap: c_int = 243; +pub const NID_id_smime_alg_RC2wrap: c_int = 244; +pub const NID_id_smime_alg_ESDH: c_int = 245; +pub const NID_id_smime_alg_CMS3DESwrap: c_int = 246; +pub const NID_id_smime_alg_CMSRC2wrap: c_int = 247; +pub const NID_id_alg_PWRI_KEK: c_int = 893; +pub const NID_id_smime_cd_ldap: c_int = 248; +pub const NID_id_smime_spq_ets_sqt_uri: c_int = 249; +pub const NID_id_smime_spq_ets_sqt_unotice: c_int = 250; +pub const NID_id_smime_cti_ets_proofOfOrigin: c_int = 251; +pub const NID_id_smime_cti_ets_proofOfReceipt: c_int = 252; +pub const NID_id_smime_cti_ets_proofOfDelivery: c_int = 253; +pub const NID_id_smime_cti_ets_proofOfSender: c_int = 254; +pub const NID_id_smime_cti_ets_proofOfApproval: c_int = 255; +pub const NID_id_smime_cti_ets_proofOfCreation: c_int = 256; +pub const NID_friendlyName: c_int = 156; +pub const NID_localKeyID: c_int = 157; +pub const NID_ms_csp_name: c_int = 417; +pub const NID_LocalKeySet: c_int = 856; +pub const NID_x509Certificate: c_int = 158; +pub const NID_sdsiCertificate: c_int = 159; +pub const NID_x509Crl: c_int = 160; +pub const NID_pbe_WithSHA1And128BitRC4: c_int = 144; +pub const NID_pbe_WithSHA1And40BitRC4: c_int = 145; +pub const NID_pbe_WithSHA1And3_Key_TripleDES_CBC: c_int = 146; +pub const NID_pbe_WithSHA1And2_Key_TripleDES_CBC: c_int = 147; +pub const NID_pbe_WithSHA1And128BitRC2_CBC: c_int = 148; +pub const NID_pbe_WithSHA1And40BitRC2_CBC: c_int = 149; +pub const NID_keyBag: c_int = 150; +pub const NID_pkcs8ShroudedKeyBag: c_int = 151; +pub const NID_certBag: c_int = 152; +pub const NID_crlBag: c_int = 153; +pub const NID_secretBag: c_int = 154; +pub const NID_safeContentsBag: c_int = 155; +pub const NID_md2: c_int = 3; +pub const NID_md4: c_int = 257; +pub const NID_md5: c_int = 4; +pub const NID_md5_sha1: c_int = 114; +pub const NID_hmacWithMD5: c_int = 797; +pub const NID_hmacWithSHA1: c_int = 163; +pub const NID_hmacWithSHA224: c_int = 798; +pub const NID_hmacWithSHA256: c_int = 799; +pub const NID_hmacWithSHA384: c_int = 800; +pub const NID_hmacWithSHA512: c_int = 801; +pub const NID_rc2_cbc: c_int = 37; +pub const NID_rc2_ecb: c_int = 38; +pub const NID_rc2_cfb64: c_int = 39; +pub const NID_rc2_ofb64: c_int = 40; +pub const NID_rc2_40_cbc: c_int = 98; +pub const NID_rc2_64_cbc: c_int = 166; +pub const NID_rc4: c_int = 5; +pub const NID_rc4_40: c_int = 97; +pub const NID_des_ede3_cbc: c_int = 44; +pub const NID_rc5_cbc: c_int = 120; +pub const NID_rc5_ecb: c_int = 121; +pub const NID_rc5_cfb64: c_int = 122; +pub const NID_rc5_ofb64: c_int = 123; +pub const NID_ms_ext_req: c_int = 171; +pub const NID_ms_code_ind: c_int = 134; +pub const NID_ms_code_com: c_int = 135; +pub const NID_ms_ctl_sign: c_int = 136; +pub const NID_ms_sgc: c_int = 137; +pub const NID_ms_efs: c_int = 138; +pub const NID_ms_smartcard_login: c_int = 648; +pub const NID_ms_upn: c_int = 649; +pub const NID_idea_cbc: c_int = 34; +pub const NID_idea_ecb: c_int = 36; +pub const NID_idea_cfb64: c_int = 35; +pub const NID_idea_ofb64: c_int = 46; +pub const NID_bf_cbc: c_int = 91; +pub const NID_bf_ecb: c_int = 92; +pub const NID_bf_cfb64: c_int = 93; +pub const NID_bf_ofb64: c_int = 94; +pub const NID_id_pkix: c_int = 127; +pub const NID_id_pkix_mod: c_int = 258; +pub const NID_id_pe: c_int = 175; +pub const NID_id_qt: c_int = 259; +pub const NID_id_kp: c_int = 128; +pub const NID_id_it: c_int = 260; +pub const NID_id_pkip: c_int = 261; +pub const NID_id_alg: c_int = 262; +pub const NID_id_cmc: c_int = 263; +pub const NID_id_on: c_int = 264; +pub const NID_id_pda: c_int = 265; +pub const NID_id_aca: c_int = 266; +pub const NID_id_qcs: c_int = 267; +pub const NID_id_cct: c_int = 268; +pub const NID_id_ppl: c_int = 662; +pub const NID_id_ad: c_int = 176; +pub const NID_id_pkix1_explicit_88: c_int = 269; +pub const NID_id_pkix1_implicit_88: c_int = 270; +pub const NID_id_pkix1_explicit_93: c_int = 271; +pub const NID_id_pkix1_implicit_93: c_int = 272; +pub const NID_id_mod_crmf: c_int = 273; +pub const NID_id_mod_cmc: c_int = 274; +pub const NID_id_mod_kea_profile_88: c_int = 275; +pub const NID_id_mod_kea_profile_93: c_int = 276; +pub const NID_id_mod_cmp: c_int = 277; +pub const NID_id_mod_qualified_cert_88: c_int = 278; +pub const NID_id_mod_qualified_cert_93: c_int = 279; +pub const NID_id_mod_attribute_cert: c_int = 280; +pub const NID_id_mod_timestamp_protocol: c_int = 281; +pub const NID_id_mod_ocsp: c_int = 282; +pub const NID_id_mod_dvcs: c_int = 283; +pub const NID_id_mod_cmp2000: c_int = 284; +pub const NID_info_access: c_int = 177; +pub const NID_biometricInfo: c_int = 285; +pub const NID_qcStatements: c_int = 286; +pub const NID_ac_auditEntity: c_int = 287; +pub const NID_ac_targeting: c_int = 288; +pub const NID_aaControls: c_int = 289; +pub const NID_sbgp_ipAddrBlock: c_int = 290; +pub const NID_sbgp_autonomousSysNum: c_int = 291; +pub const NID_sbgp_routerIdentifier: c_int = 292; +pub const NID_ac_proxying: c_int = 397; +pub const NID_sinfo_access: c_int = 398; +pub const NID_proxyCertInfo: c_int = 663; +pub const NID_id_qt_cps: c_int = 164; +pub const NID_id_qt_unotice: c_int = 165; +pub const NID_textNotice: c_int = 293; +pub const NID_server_auth: c_int = 129; +pub const NID_client_auth: c_int = 130; +pub const NID_code_sign: c_int = 131; +pub const NID_email_protect: c_int = 132; +pub const NID_ipsecEndSystem: c_int = 294; +pub const NID_ipsecTunnel: c_int = 295; +pub const NID_ipsecUser: c_int = 296; +pub const NID_time_stamp: c_int = 133; +pub const NID_OCSP_sign: c_int = 180; +pub const NID_dvcs: c_int = 297; +pub const NID_id_it_caProtEncCert: c_int = 298; +pub const NID_id_it_signKeyPairTypes: c_int = 299; +pub const NID_id_it_encKeyPairTypes: c_int = 300; +pub const NID_id_it_preferredSymmAlg: c_int = 301; +pub const NID_id_it_caKeyUpdateInfo: c_int = 302; +pub const NID_id_it_currentCRL: c_int = 303; +pub const NID_id_it_unsupportedOIDs: c_int = 304; +pub const NID_id_it_subscriptionRequest: c_int = 305; +pub const NID_id_it_subscriptionResponse: c_int = 306; +pub const NID_id_it_keyPairParamReq: c_int = 307; +pub const NID_id_it_keyPairParamRep: c_int = 308; +pub const NID_id_it_revPassphrase: c_int = 309; +pub const NID_id_it_implicitConfirm: c_int = 310; +pub const NID_id_it_confirmWaitTime: c_int = 311; +pub const NID_id_it_origPKIMessage: c_int = 312; +pub const NID_id_it_suppLangTags: c_int = 784; +pub const NID_id_regCtrl: c_int = 313; +pub const NID_id_regInfo: c_int = 314; +pub const NID_id_regCtrl_regToken: c_int = 315; +pub const NID_id_regCtrl_authenticator: c_int = 316; +pub const NID_id_regCtrl_pkiPublicationInfo: c_int = 317; +pub const NID_id_regCtrl_pkiArchiveOptions: c_int = 318; +pub const NID_id_regCtrl_oldCertID: c_int = 319; +pub const NID_id_regCtrl_protocolEncrKey: c_int = 320; +pub const NID_id_regInfo_utf8Pairs: c_int = 321; +pub const NID_id_regInfo_certReq: c_int = 322; +pub const NID_id_alg_des40: c_int = 323; +pub const NID_id_alg_noSignature: c_int = 324; +pub const NID_id_alg_dh_sig_hmac_sha1: c_int = 325; +pub const NID_id_alg_dh_pop: c_int = 326; +pub const NID_id_cmc_statusInfo: c_int = 327; +pub const NID_id_cmc_identification: c_int = 328; +pub const NID_id_cmc_identityProof: c_int = 329; +pub const NID_id_cmc_dataReturn: c_int = 330; +pub const NID_id_cmc_transactionId: c_int = 331; +pub const NID_id_cmc_senderNonce: c_int = 332; +pub const NID_id_cmc_recipientNonce: c_int = 333; +pub const NID_id_cmc_addExtensions: c_int = 334; +pub const NID_id_cmc_encryptedPOP: c_int = 335; +pub const NID_id_cmc_decryptedPOP: c_int = 336; +pub const NID_id_cmc_lraPOPWitness: c_int = 337; +pub const NID_id_cmc_getCert: c_int = 338; +pub const NID_id_cmc_getCRL: c_int = 339; +pub const NID_id_cmc_revokeRequest: c_int = 340; +pub const NID_id_cmc_regInfo: c_int = 341; +pub const NID_id_cmc_responseInfo: c_int = 342; +pub const NID_id_cmc_queryPending: c_int = 343; +pub const NID_id_cmc_popLinkRandom: c_int = 344; +pub const NID_id_cmc_popLinkWitness: c_int = 345; +pub const NID_id_cmc_confirmCertAcceptance: c_int = 346; +pub const NID_id_on_personalData: c_int = 347; +pub const NID_id_on_permanentIdentifier: c_int = 858; +pub const NID_id_pda_dateOfBirth: c_int = 348; +pub const NID_id_pda_placeOfBirth: c_int = 349; +pub const NID_id_pda_gender: c_int = 351; +pub const NID_id_pda_countryOfCitizenship: c_int = 352; +pub const NID_id_pda_countryOfResidence: c_int = 353; +pub const NID_id_aca_authenticationInfo: c_int = 354; +pub const NID_id_aca_accessIdentity: c_int = 355; +pub const NID_id_aca_chargingIdentity: c_int = 356; +pub const NID_id_aca_group: c_int = 357; +pub const NID_id_aca_role: c_int = 358; +pub const NID_id_aca_encAttrs: c_int = 399; +pub const NID_id_qcs_pkixQCSyntax_v1: c_int = 359; +pub const NID_id_cct_crs: c_int = 360; +pub const NID_id_cct_PKIData: c_int = 361; +pub const NID_id_cct_PKIResponse: c_int = 362; +pub const NID_id_ppl_anyLanguage: c_int = 664; +pub const NID_id_ppl_inheritAll: c_int = 665; +pub const NID_Independent: c_int = 667; +pub const NID_ad_OCSP: c_int = 178; +pub const NID_ad_ca_issuers: c_int = 179; +pub const NID_ad_timeStamping: c_int = 363; +pub const NID_ad_dvcs: c_int = 364; +pub const NID_caRepository: c_int = 785; +pub const NID_id_pkix_OCSP_basic: c_int = 365; +pub const NID_id_pkix_OCSP_Nonce: c_int = 366; +pub const NID_id_pkix_OCSP_CrlID: c_int = 367; +pub const NID_id_pkix_OCSP_acceptableResponses: c_int = 368; +pub const NID_id_pkix_OCSP_noCheck: c_int = 369; +pub const NID_id_pkix_OCSP_archiveCutoff: c_int = 370; +pub const NID_id_pkix_OCSP_serviceLocator: c_int = 371; +pub const NID_id_pkix_OCSP_extendedStatus: c_int = 372; +pub const NID_id_pkix_OCSP_valid: c_int = 373; +pub const NID_id_pkix_OCSP_path: c_int = 374; +pub const NID_id_pkix_OCSP_trustRoot: c_int = 375; +pub const NID_algorithm: c_int = 376; +pub const NID_md5WithRSA: c_int = 104; +pub const NID_des_ecb: c_int = 29; +pub const NID_des_cbc: c_int = 31; +pub const NID_des_ofb64: c_int = 45; +pub const NID_des_cfb64: c_int = 30; +pub const NID_rsaSignature: c_int = 377; +pub const NID_dsa_2: c_int = 67; +pub const NID_dsaWithSHA: c_int = 66; +pub const NID_shaWithRSAEncryption: c_int = 42; +pub const NID_des_ede_ecb: c_int = 32; +pub const NID_des_ede3_ecb: c_int = 33; +pub const NID_des_ede_cbc: c_int = 43; +pub const NID_des_ede_cfb64: c_int = 60; +pub const NID_des_ede3_cfb64: c_int = 61; +pub const NID_des_ede_ofb64: c_int = 62; +pub const NID_des_ede3_ofb64: c_int = 63; +pub const NID_desx_cbc: c_int = 80; +pub const NID_sha: c_int = 41; +pub const NID_sha1: c_int = 64; +pub const NID_dsaWithSHA1_2: c_int = 70; +pub const NID_sha1WithRSA: c_int = 115; +pub const NID_ripemd160: c_int = 117; +pub const NID_ripemd160WithRSA: c_int = 119; +pub const NID_sxnet: c_int = 143; +pub const NID_X500: c_int = 11; +pub const NID_X509: c_int = 12; +pub const NID_commonName: c_int = 13; +pub const NID_surname: c_int = 100; +pub const NID_serialNumber: c_int = 105; +pub const NID_countryName: c_int = 14; +pub const NID_localityName: c_int = 15; +pub const NID_stateOrProvinceName: c_int = 16; +pub const NID_streetAddress: c_int = 660; +pub const NID_organizationName: c_int = 17; +pub const NID_organizationalUnitName: c_int = 18; +pub const NID_title: c_int = 106; +pub const NID_description: c_int = 107; +pub const NID_searchGuide: c_int = 859; +pub const NID_businessCategory: c_int = 860; +pub const NID_postalAddress: c_int = 861; +pub const NID_postalCode: c_int = 661; +pub const NID_postOfficeBox: c_int = 862; +pub const NID_physicalDeliveryOfficeName: c_int = 863; +pub const NID_telephoneNumber: c_int = 864; +pub const NID_telexNumber: c_int = 865; +pub const NID_teletexTerminalIdentifier: c_int = 866; +pub const NID_facsimileTelephoneNumber: c_int = 867; +pub const NID_x121Address: c_int = 868; +pub const NID_internationaliSDNNumber: c_int = 869; +pub const NID_registeredAddress: c_int = 870; +pub const NID_destinationIndicator: c_int = 871; +pub const NID_preferredDeliveryMethod: c_int = 872; +pub const NID_presentationAddress: c_int = 873; +pub const NID_supportedApplicationContext: c_int = 874; +pub const NID_member: c_int = 875; +pub const NID_owner: c_int = 876; +pub const NID_roleOccupant: c_int = 877; +pub const NID_seeAlso: c_int = 878; +pub const NID_userPassword: c_int = 879; +pub const NID_userCertificate: c_int = 880; +pub const NID_cACertificate: c_int = 881; +pub const NID_authorityRevocationList: c_int = 882; +pub const NID_certificateRevocationList: c_int = 883; +pub const NID_crossCertificatePair: c_int = 884; +pub const NID_name: c_int = 173; +pub const NID_givenName: c_int = 99; +pub const NID_initials: c_int = 101; +pub const NID_generationQualifier: c_int = 509; +pub const NID_x500UniqueIdentifier: c_int = 503; +pub const NID_dnQualifier: c_int = 174; +pub const NID_enhancedSearchGuide: c_int = 885; +pub const NID_protocolInformation: c_int = 886; +pub const NID_distinguishedName: c_int = 887; +pub const NID_uniqueMember: c_int = 888; +pub const NID_houseIdentifier: c_int = 889; +pub const NID_supportedAlgorithms: c_int = 890; +pub const NID_deltaRevocationList: c_int = 891; +pub const NID_dmdName: c_int = 892; +pub const NID_pseudonym: c_int = 510; +pub const NID_role: c_int = 400; +pub const NID_X500algorithms: c_int = 378; +pub const NID_rsa: c_int = 19; +pub const NID_mdc2WithRSA: c_int = 96; +pub const NID_mdc2: c_int = 95; +pub const NID_id_ce: c_int = 81; +pub const NID_subject_directory_attributes: c_int = 769; +pub const NID_subject_key_identifier: c_int = 82; +pub const NID_key_usage: c_int = 83; +pub const NID_private_key_usage_period: c_int = 84; +pub const NID_subject_alt_name: c_int = 85; +pub const NID_issuer_alt_name: c_int = 86; +pub const NID_basic_constraints: c_int = 87; +pub const NID_crl_number: c_int = 88; +pub const NID_crl_reason: c_int = 141; +pub const NID_invalidity_date: c_int = 142; +pub const NID_delta_crl: c_int = 140; +pub const NID_issuing_distribution_point: c_int = 770; +pub const NID_certificate_issuer: c_int = 771; +pub const NID_name_constraints: c_int = 666; +pub const NID_crl_distribution_points: c_int = 103; +pub const NID_certificate_policies: c_int = 89; +pub const NID_any_policy: c_int = 746; +pub const NID_policy_mappings: c_int = 747; +pub const NID_authority_key_identifier: c_int = 90; +pub const NID_policy_constraints: c_int = 401; +pub const NID_ext_key_usage: c_int = 126; +pub const NID_freshest_crl: c_int = 857; +pub const NID_inhibit_any_policy: c_int = 748; +pub const NID_target_information: c_int = 402; +pub const NID_no_rev_avail: c_int = 403; +pub const NID_anyExtendedKeyUsage: c_int = 910; +pub const NID_netscape: c_int = 57; +pub const NID_netscape_cert_extension: c_int = 58; +pub const NID_netscape_data_type: c_int = 59; +pub const NID_netscape_cert_type: c_int = 71; +pub const NID_netscape_base_url: c_int = 72; +pub const NID_netscape_revocation_url: c_int = 73; +pub const NID_netscape_ca_revocation_url: c_int = 74; +pub const NID_netscape_renewal_url: c_int = 75; +pub const NID_netscape_ca_policy_url: c_int = 76; +pub const NID_netscape_ssl_server_name: c_int = 77; +pub const NID_netscape_comment: c_int = 78; +pub const NID_netscape_cert_sequence: c_int = 79; +pub const NID_ns_sgc: c_int = 139; +pub const NID_org: c_int = 379; +pub const NID_dod: c_int = 380; +pub const NID_iana: c_int = 381; +pub const NID_Directory: c_int = 382; +pub const NID_Management: c_int = 383; +pub const NID_Experimental: c_int = 384; +pub const NID_Private: c_int = 385; +pub const NID_Security: c_int = 386; +pub const NID_SNMPv2: c_int = 387; +pub const NID_Mail: c_int = 388; +pub const NID_Enterprises: c_int = 389; +pub const NID_dcObject: c_int = 390; +pub const NID_mime_mhs: c_int = 504; +pub const NID_mime_mhs_headings: c_int = 505; +pub const NID_mime_mhs_bodies: c_int = 506; +pub const NID_id_hex_partial_message: c_int = 507; +pub const NID_id_hex_multipart_message: c_int = 508; +pub const NID_zlib_compression: c_int = 125; +pub const NID_aes_128_ecb: c_int = 418; +pub const NID_aes_128_cbc: c_int = 419; +pub const NID_aes_128_ofb128: c_int = 420; +pub const NID_aes_128_cfb128: c_int = 421; +pub const NID_id_aes128_wrap: c_int = 788; +pub const NID_aes_128_gcm: c_int = 895; +pub const NID_aes_128_ccm: c_int = 896; +pub const NID_id_aes128_wrap_pad: c_int = 897; +pub const NID_aes_192_ecb: c_int = 422; +pub const NID_aes_192_cbc: c_int = 423; +pub const NID_aes_192_ofb128: c_int = 424; +pub const NID_aes_192_cfb128: c_int = 425; +pub const NID_id_aes192_wrap: c_int = 789; +pub const NID_aes_192_gcm: c_int = 898; +pub const NID_aes_192_ccm: c_int = 899; +pub const NID_id_aes192_wrap_pad: c_int = 900; +pub const NID_aes_256_ecb: c_int = 426; +pub const NID_aes_256_cbc: c_int = 427; +pub const NID_aes_256_ofb128: c_int = 428; +pub const NID_aes_256_cfb128: c_int = 429; +pub const NID_id_aes256_wrap: c_int = 790; +pub const NID_aes_256_gcm: c_int = 901; +pub const NID_aes_256_ccm: c_int = 902; +pub const NID_id_aes256_wrap_pad: c_int = 903; +pub const NID_aes_128_cfb1: c_int = 650; +pub const NID_aes_192_cfb1: c_int = 651; +pub const NID_aes_256_cfb1: c_int = 652; +pub const NID_aes_128_cfb8: c_int = 653; +pub const NID_aes_192_cfb8: c_int = 654; +pub const NID_aes_256_cfb8: c_int = 655; +pub const NID_aes_128_ctr: c_int = 904; +pub const NID_aes_192_ctr: c_int = 905; +pub const NID_aes_256_ctr: c_int = 906; +pub const NID_aes_128_xts: c_int = 913; +pub const NID_aes_256_xts: c_int = 914; +pub const NID_des_cfb1: c_int = 656; +pub const NID_des_cfb8: c_int = 657; +pub const NID_des_ede3_cfb1: c_int = 658; +pub const NID_des_ede3_cfb8: c_int = 659; +pub const NID_sha256: c_int = 672; +pub const NID_sha384: c_int = 673; +pub const NID_sha512: c_int = 674; +pub const NID_sha224: c_int = 675; +pub const NID_dsa_with_SHA224: c_int = 802; +pub const NID_dsa_with_SHA256: c_int = 803; +pub const NID_hold_instruction_code: c_int = 430; +pub const NID_hold_instruction_none: c_int = 431; +pub const NID_hold_instruction_call_issuer: c_int = 432; +pub const NID_hold_instruction_reject: c_int = 433; +pub const NID_data: c_int = 434; +pub const NID_pss: c_int = 435; +pub const NID_ucl: c_int = 436; +pub const NID_pilot: c_int = 437; +pub const NID_pilotAttributeType: c_int = 438; +pub const NID_pilotAttributeSyntax: c_int = 439; +pub const NID_pilotObjectClass: c_int = 440; +pub const NID_pilotGroups: c_int = 441; +pub const NID_iA5StringSyntax: c_int = 442; +pub const NID_caseIgnoreIA5StringSyntax: c_int = 443; +pub const NID_pilotObject: c_int = 444; +pub const NID_pilotPerson: c_int = 445; +pub const NID_account: c_int = 446; +pub const NID_document: c_int = 447; +pub const NID_room: c_int = 448; +pub const NID_documentSeries: c_int = 449; +pub const NID_Domain: c_int = 392; +pub const NID_rFC822localPart: c_int = 450; +pub const NID_dNSDomain: c_int = 451; +pub const NID_domainRelatedObject: c_int = 452; +pub const NID_friendlyCountry: c_int = 453; +pub const NID_simpleSecurityObject: c_int = 454; +pub const NID_pilotOrganization: c_int = 455; +pub const NID_pilotDSA: c_int = 456; +pub const NID_qualityLabelledData: c_int = 457; +pub const NID_userId: c_int = 458; +pub const NID_textEncodedORAddress: c_int = 459; +pub const NID_rfc822Mailbox: c_int = 460; +pub const NID_info: c_int = 461; +pub const NID_favouriteDrink: c_int = 462; +pub const NID_roomNumber: c_int = 463; +pub const NID_photo: c_int = 464; +pub const NID_userClass: c_int = 465; +pub const NID_host: c_int = 466; +pub const NID_manager: c_int = 467; +pub const NID_documentIdentifier: c_int = 468; +pub const NID_documentTitle: c_int = 469; +pub const NID_documentVersion: c_int = 470; +pub const NID_documentAuthor: c_int = 471; +pub const NID_documentLocation: c_int = 472; +pub const NID_homeTelephoneNumber: c_int = 473; +pub const NID_secretary: c_int = 474; +pub const NID_otherMailbox: c_int = 475; +pub const NID_lastModifiedTime: c_int = 476; +pub const NID_lastModifiedBy: c_int = 477; +pub const NID_domainComponent: c_int = 391; +pub const NID_aRecord: c_int = 478; +pub const NID_pilotAttributeType27: c_int = 479; +pub const NID_mXRecord: c_int = 480; +pub const NID_nSRecord: c_int = 481; +pub const NID_sOARecord: c_int = 482; +pub const NID_cNAMERecord: c_int = 483; +pub const NID_associatedDomain: c_int = 484; +pub const NID_associatedName: c_int = 485; +pub const NID_homePostalAddress: c_int = 486; +pub const NID_personalTitle: c_int = 487; +pub const NID_mobileTelephoneNumber: c_int = 488; +pub const NID_pagerTelephoneNumber: c_int = 489; +pub const NID_friendlyCountryName: c_int = 490; +pub const NID_organizationalStatus: c_int = 491; +pub const NID_janetMailbox: c_int = 492; +pub const NID_mailPreferenceOption: c_int = 493; +pub const NID_buildingName: c_int = 494; +pub const NID_dSAQuality: c_int = 495; +pub const NID_singleLevelQuality: c_int = 496; +pub const NID_subtreeMinimumQuality: c_int = 497; +pub const NID_subtreeMaximumQuality: c_int = 498; +pub const NID_personalSignature: c_int = 499; +pub const NID_dITRedirect: c_int = 500; +pub const NID_audio: c_int = 501; +pub const NID_documentPublisher: c_int = 502; +pub const NID_id_set: c_int = 512; +pub const NID_set_ctype: c_int = 513; +pub const NID_set_msgExt: c_int = 514; +pub const NID_set_attr: c_int = 515; +pub const NID_set_policy: c_int = 516; +pub const NID_set_certExt: c_int = 517; +pub const NID_set_brand: c_int = 518; +pub const NID_setct_PANData: c_int = 519; +pub const NID_setct_PANToken: c_int = 520; +pub const NID_setct_PANOnly: c_int = 521; +pub const NID_setct_OIData: c_int = 522; +pub const NID_setct_PI: c_int = 523; +pub const NID_setct_PIData: c_int = 524; +pub const NID_setct_PIDataUnsigned: c_int = 525; +pub const NID_setct_HODInput: c_int = 526; +pub const NID_setct_AuthResBaggage: c_int = 527; +pub const NID_setct_AuthRevReqBaggage: c_int = 528; +pub const NID_setct_AuthRevResBaggage: c_int = 529; +pub const NID_setct_CapTokenSeq: c_int = 530; +pub const NID_setct_PInitResData: c_int = 531; +pub const NID_setct_PI_TBS: c_int = 532; +pub const NID_setct_PResData: c_int = 533; +pub const NID_setct_AuthReqTBS: c_int = 534; +pub const NID_setct_AuthResTBS: c_int = 535; +pub const NID_setct_AuthResTBSX: c_int = 536; +pub const NID_setct_AuthTokenTBS: c_int = 537; +pub const NID_setct_CapTokenData: c_int = 538; +pub const NID_setct_CapTokenTBS: c_int = 539; +pub const NID_setct_AcqCardCodeMsg: c_int = 540; +pub const NID_setct_AuthRevReqTBS: c_int = 541; +pub const NID_setct_AuthRevResData: c_int = 542; +pub const NID_setct_AuthRevResTBS: c_int = 543; +pub const NID_setct_CapReqTBS: c_int = 544; +pub const NID_setct_CapReqTBSX: c_int = 545; +pub const NID_setct_CapResData: c_int = 546; +pub const NID_setct_CapRevReqTBS: c_int = 547; +pub const NID_setct_CapRevReqTBSX: c_int = 548; +pub const NID_setct_CapRevResData: c_int = 549; +pub const NID_setct_CredReqTBS: c_int = 550; +pub const NID_setct_CredReqTBSX: c_int = 551; +pub const NID_setct_CredResData: c_int = 552; +pub const NID_setct_CredRevReqTBS: c_int = 553; +pub const NID_setct_CredRevReqTBSX: c_int = 554; +pub const NID_setct_CredRevResData: c_int = 555; +pub const NID_setct_PCertReqData: c_int = 556; +pub const NID_setct_PCertResTBS: c_int = 557; +pub const NID_setct_BatchAdminReqData: c_int = 558; +pub const NID_setct_BatchAdminResData: c_int = 559; +pub const NID_setct_CardCInitResTBS: c_int = 560; +pub const NID_setct_MeAqCInitResTBS: c_int = 561; +pub const NID_setct_RegFormResTBS: c_int = 562; +pub const NID_setct_CertReqData: c_int = 563; +pub const NID_setct_CertReqTBS: c_int = 564; +pub const NID_setct_CertResData: c_int = 565; +pub const NID_setct_CertInqReqTBS: c_int = 566; +pub const NID_setct_ErrorTBS: c_int = 567; +pub const NID_setct_PIDualSignedTBE: c_int = 568; +pub const NID_setct_PIUnsignedTBE: c_int = 569; +pub const NID_setct_AuthReqTBE: c_int = 570; +pub const NID_setct_AuthResTBE: c_int = 571; +pub const NID_setct_AuthResTBEX: c_int = 572; +pub const NID_setct_AuthTokenTBE: c_int = 573; +pub const NID_setct_CapTokenTBE: c_int = 574; +pub const NID_setct_CapTokenTBEX: c_int = 575; +pub const NID_setct_AcqCardCodeMsgTBE: c_int = 576; +pub const NID_setct_AuthRevReqTBE: c_int = 577; +pub const NID_setct_AuthRevResTBE: c_int = 578; +pub const NID_setct_AuthRevResTBEB: c_int = 579; +pub const NID_setct_CapReqTBE: c_int = 580; +pub const NID_setct_CapReqTBEX: c_int = 581; +pub const NID_setct_CapResTBE: c_int = 582; +pub const NID_setct_CapRevReqTBE: c_int = 583; +pub const NID_setct_CapRevReqTBEX: c_int = 584; +pub const NID_setct_CapRevResTBE: c_int = 585; +pub const NID_setct_CredReqTBE: c_int = 586; +pub const NID_setct_CredReqTBEX: c_int = 587; +pub const NID_setct_CredResTBE: c_int = 588; +pub const NID_setct_CredRevReqTBE: c_int = 589; +pub const NID_setct_CredRevReqTBEX: c_int = 590; +pub const NID_setct_CredRevResTBE: c_int = 591; +pub const NID_setct_BatchAdminReqTBE: c_int = 592; +pub const NID_setct_BatchAdminResTBE: c_int = 593; +pub const NID_setct_RegFormReqTBE: c_int = 594; +pub const NID_setct_CertReqTBE: c_int = 595; +pub const NID_setct_CertReqTBEX: c_int = 596; +pub const NID_setct_CertResTBE: c_int = 597; +pub const NID_setct_CRLNotificationTBS: c_int = 598; +pub const NID_setct_CRLNotificationResTBS: c_int = 599; +pub const NID_setct_BCIDistributionTBS: c_int = 600; +pub const NID_setext_genCrypt: c_int = 601; +pub const NID_setext_miAuth: c_int = 602; +pub const NID_setext_pinSecure: c_int = 603; +pub const NID_setext_pinAny: c_int = 604; +pub const NID_setext_track2: c_int = 605; +pub const NID_setext_cv: c_int = 606; +pub const NID_set_policy_root: c_int = 607; +pub const NID_setCext_hashedRoot: c_int = 608; +pub const NID_setCext_certType: c_int = 609; +pub const NID_setCext_merchData: c_int = 610; +pub const NID_setCext_cCertRequired: c_int = 611; +pub const NID_setCext_tunneling: c_int = 612; +pub const NID_setCext_setExt: c_int = 613; +pub const NID_setCext_setQualf: c_int = 614; +pub const NID_setCext_PGWYcapabilities: c_int = 615; +pub const NID_setCext_TokenIdentifier: c_int = 616; +pub const NID_setCext_Track2Data: c_int = 617; +pub const NID_setCext_TokenType: c_int = 618; +pub const NID_setCext_IssuerCapabilities: c_int = 619; +pub const NID_setAttr_Cert: c_int = 620; +pub const NID_setAttr_PGWYcap: c_int = 621; +pub const NID_setAttr_TokenType: c_int = 622; +pub const NID_setAttr_IssCap: c_int = 623; +pub const NID_set_rootKeyThumb: c_int = 624; +pub const NID_set_addPolicy: c_int = 625; +pub const NID_setAttr_Token_EMV: c_int = 626; +pub const NID_setAttr_Token_B0Prime: c_int = 627; +pub const NID_setAttr_IssCap_CVM: c_int = 628; +pub const NID_setAttr_IssCap_T2: c_int = 629; +pub const NID_setAttr_IssCap_Sig: c_int = 630; +pub const NID_setAttr_GenCryptgrm: c_int = 631; +pub const NID_setAttr_T2Enc: c_int = 632; +pub const NID_setAttr_T2cleartxt: c_int = 633; +pub const NID_setAttr_TokICCsig: c_int = 634; +pub const NID_setAttr_SecDevSig: c_int = 635; +pub const NID_set_brand_IATA_ATA: c_int = 636; +pub const NID_set_brand_Diners: c_int = 637; +pub const NID_set_brand_AmericanExpress: c_int = 638; +pub const NID_set_brand_JCB: c_int = 639; +pub const NID_set_brand_Visa: c_int = 640; +pub const NID_set_brand_MasterCard: c_int = 641; +pub const NID_set_brand_Novus: c_int = 642; +pub const NID_des_cdmf: c_int = 643; +pub const NID_rsaOAEPEncryptionSET: c_int = 644; +pub const NID_ipsec3: c_int = 749; +pub const NID_ipsec4: c_int = 750; +pub const NID_whirlpool: c_int = 804; +pub const NID_cryptopro: c_int = 805; +pub const NID_cryptocom: c_int = 806; +pub const NID_id_GostR3411_94_with_GostR3410_2001: c_int = 807; +pub const NID_id_GostR3411_94_with_GostR3410_94: c_int = 808; +pub const NID_id_GostR3411_94: c_int = 809; +pub const NID_id_HMACGostR3411_94: c_int = 810; +pub const NID_id_GostR3410_2001: c_int = 811; +pub const NID_id_GostR3410_94: c_int = 812; +pub const NID_id_Gost28147_89: c_int = 813; +pub const NID_gost89_cnt: c_int = 814; +pub const NID_id_Gost28147_89_MAC: c_int = 815; +pub const NID_id_GostR3411_94_prf: c_int = 816; +pub const NID_id_GostR3410_2001DH: c_int = 817; +pub const NID_id_GostR3410_94DH: c_int = 818; +pub const NID_id_Gost28147_89_CryptoPro_KeyMeshing: c_int = 819; +pub const NID_id_Gost28147_89_None_KeyMeshing: c_int = 820; +pub const NID_id_GostR3411_94_TestParamSet: c_int = 821; +pub const NID_id_GostR3411_94_CryptoProParamSet: c_int = 822; +pub const NID_id_Gost28147_89_TestParamSet: c_int = 823; +pub const NID_id_Gost28147_89_CryptoPro_A_ParamSet: c_int = 824; +pub const NID_id_Gost28147_89_CryptoPro_B_ParamSet: c_int = 825; +pub const NID_id_Gost28147_89_CryptoPro_C_ParamSet: c_int = 826; +pub const NID_id_Gost28147_89_CryptoPro_D_ParamSet: c_int = 827; +pub const NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet: c_int = 828; +pub const NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet: c_int = 829; +pub const NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet: c_int = 830; +pub const NID_id_GostR3410_94_TestParamSet: c_int = 831; +pub const NID_id_GostR3410_94_CryptoPro_A_ParamSet: c_int = 832; +pub const NID_id_GostR3410_94_CryptoPro_B_ParamSet: c_int = 833; +pub const NID_id_GostR3410_94_CryptoPro_C_ParamSet: c_int = 834; +pub const NID_id_GostR3410_94_CryptoPro_D_ParamSet: c_int = 835; +pub const NID_id_GostR3410_94_CryptoPro_XchA_ParamSet: c_int = 836; +pub const NID_id_GostR3410_94_CryptoPro_XchB_ParamSet: c_int = 837; +pub const NID_id_GostR3410_94_CryptoPro_XchC_ParamSet: c_int = 838; +pub const NID_id_GostR3410_2001_TestParamSet: c_int = 839; +pub const NID_id_GostR3410_2001_CryptoPro_A_ParamSet: c_int = 840; +pub const NID_id_GostR3410_2001_CryptoPro_B_ParamSet: c_int = 841; +pub const NID_id_GostR3410_2001_CryptoPro_C_ParamSet: c_int = 842; +pub const NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet: c_int = 843; +pub const NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet: c_int = 844; +pub const NID_id_GostR3410_94_a: c_int = 845; +pub const NID_id_GostR3410_94_aBis: c_int = 846; +pub const NID_id_GostR3410_94_b: c_int = 847; +pub const NID_id_GostR3410_94_bBis: c_int = 848; +pub const NID_id_Gost28147_89_cc: c_int = 849; +pub const NID_id_GostR3410_94_cc: c_int = 850; +pub const NID_id_GostR3410_2001_cc: c_int = 851; +pub const NID_id_GostR3411_94_with_GostR3410_94_cc: c_int = 852; +pub const NID_id_GostR3411_94_with_GostR3410_2001_cc: c_int = 853; +pub const NID_id_GostR3410_2001_ParamSet_cc: c_int = 854; +pub const NID_camellia_128_cbc: c_int = 751; +pub const NID_camellia_192_cbc: c_int = 752; +pub const NID_camellia_256_cbc: c_int = 753; +pub const NID_id_camellia128_wrap: c_int = 907; +pub const NID_id_camellia192_wrap: c_int = 908; +pub const NID_id_camellia256_wrap: c_int = 909; +pub const NID_camellia_128_ecb: c_int = 754; +pub const NID_camellia_128_ofb128: c_int = 766; +pub const NID_camellia_128_cfb128: c_int = 757; +pub const NID_camellia_192_ecb: c_int = 755; +pub const NID_camellia_192_ofb128: c_int = 767; +pub const NID_camellia_192_cfb128: c_int = 758; +pub const NID_camellia_256_ecb: c_int = 756; +pub const NID_camellia_256_ofb128: c_int = 768; +pub const NID_camellia_256_cfb128: c_int = 759; +pub const NID_camellia_128_cfb1: c_int = 760; +pub const NID_camellia_192_cfb1: c_int = 761; +pub const NID_camellia_256_cfb1: c_int = 762; +pub const NID_camellia_128_cfb8: c_int = 763; +pub const NID_camellia_192_cfb8: c_int = 764; +pub const NID_camellia_256_cfb8: c_int = 765; +pub const NID_kisa: c_int = 773; +pub const NID_seed_ecb: c_int = 776; +pub const NID_seed_cbc: c_int = 777; +pub const NID_seed_cfb128: c_int = 779; +pub const NID_seed_ofb128: c_int = 778; +pub const NID_hmac: c_int = 855; +pub const NID_cmac: c_int = 894; +pub const NID_rc4_hmac_md5: c_int = 915; +pub const NID_aes_128_cbc_hmac_sha1: c_int = 916; +pub const NID_aes_192_cbc_hmac_sha1: c_int = 917; +pub const NID_aes_256_cbc_hmac_sha1: c_int = 918; + +pub const OCSP_NOCERTS: c_ulong = 0x1; +pub const OCSP_NOINTERN: c_ulong = 0x2; +pub const OCSP_NOSIGS: c_ulong = 0x4; +pub const OCSP_NOCHAIN: c_ulong = 0x8; +pub const OCSP_NOVERIFY: c_ulong = 0x10; +pub const OCSP_NOEXPLICIT: c_ulong = 0x20; +pub const OCSP_NOCASIGN: c_ulong = 0x40; +pub const OCSP_NODELEGATED: c_ulong = 0x80; +pub const OCSP_NOCHECKS: c_ulong = 0x100; +pub const OCSP_TRUSTOTHER: c_ulong = 0x200; +pub const OCSP_RESPID_KEY: c_ulong = 0x400; +pub const OCSP_NOTIME: c_ulong = 0x800; + +pub const V_OCSP_CERTSTATUS_GOOD: c_int = 0; +pub const V_OCSP_CERTSTATUS_REVOKED: c_int = 1; +pub const V_OCSP_CERTSTATUS_UNKNOWN: c_int = 2; + +pub const OCSP_REVOKED_STATUS_NOSTATUS: c_int = -1; +pub const OCSP_REVOKED_STATUS_UNSPECIFIED: c_int = 0; +pub const OCSP_REVOKED_STATUS_KEYCOMPROMISE: c_int = 1; +pub const OCSP_REVOKED_STATUS_CACOMPROMISE: c_int = 2; +pub const OCSP_REVOKED_STATUS_AFFILIATIONCHANGED: c_int = 3; +pub const OCSP_REVOKED_STATUS_SUPERSEDED: c_int = 4; +pub const OCSP_REVOKED_STATUS_CESSATIONOFOPERATION: c_int = 5; +pub const OCSP_REVOKED_STATUS_CERTIFICATEHOLD: c_int = 6; +pub const OCSP_REVOKED_STATUS_REMOVEFROMCRL: c_int = 8; + +pub const OCSP_RESPONSE_STATUS_SUCCESSFUL: c_int = 0; +pub const OCSP_RESPONSE_STATUS_MALFORMEDREQUEST: c_int = 1; +pub const OCSP_RESPONSE_STATUS_INTERNALERROR: c_int = 2; +pub const OCSP_RESPONSE_STATUS_TRYLATER: c_int = 3; +pub const OCSP_RESPONSE_STATUS_SIGREQUIRED: c_int = 5; +pub const OCSP_RESPONSE_STATUS_UNAUTHORIZED: c_int = 6; + +pub const OPENSSL_EC_NAMED_CURVE: c_int = 1; + +pub const PKCS5_SALT_LEN: c_int = 8; +pub const PKCS12_DEFAULT_ITER: c_int = 2048; + +pub const RSA_F4: c_long = 0x10001; + +pub const RSA_PKCS1_PADDING: c_int = 1; +pub const RSA_SSLV23_PADDING: c_int = 2; +pub const RSA_NO_PADDING: c_int = 3; +pub const RSA_PKCS1_OAEP_PADDING: c_int = 4; +pub const RSA_X931_PADDING: c_int = 5; +pub const RSA_PKCS1_PSS_PADDING: c_int = 6; + +pub const SHA_LBLOCK: c_int = 16; + +pub const SSL3_AD_ILLEGAL_PARAMETER: c_int = 47; +pub const SSL_AD_ILLEGAL_PARAMETER: c_int = SSL3_AD_ILLEGAL_PARAMETER; + +pub const TLS1_AD_DECODE_ERROR: c_int = 50; +pub const SSL_AD_DECODE_ERROR: c_int = TLS1_AD_DECODE_ERROR; + +pub const TLS1_AD_UNRECOGNIZED_NAME: c_int = 112; +pub const SSL_AD_UNRECOGNIZED_NAME: c_int = TLS1_AD_UNRECOGNIZED_NAME; + +pub const SSL_CTRL_SET_TMP_DH: c_int = 3; +pub const SSL_CTRL_SET_TMP_ECDH: c_int = 4; +pub const SSL_CTRL_EXTRA_CHAIN_CERT: c_int = 14; +pub const SSL_CTRL_MODE: c_int = 33; +pub const SSL_CTRL_SET_READ_AHEAD: c_int = 41; +pub const SSL_CTRL_SET_SESS_CACHE_MODE: c_int = 44; +pub const SSL_CTRL_SET_TLSEXT_SERVERNAME_CB: c_int = 53; +pub const SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG: c_int = 54; +pub const SSL_CTRL_SET_TLSEXT_HOSTNAME: c_int = 55; +pub const SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB: c_int = 63; +pub const SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG: c_int = 64; +pub const SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE: c_int = 65; +pub const SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP: c_int = 70; +pub const SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP: c_int = 71; +pub const SSL_CTRL_GET_EXTRA_CHAIN_CERTS: c_int = 82; +#[cfg(not(any(ossl101, libressl)))] +pub const SSL_CTRL_SET_VERIFY_CERT_STORE: c_int = 106; + +pub const SSL_MODE_ENABLE_PARTIAL_WRITE: c_long = 0x1; +pub const SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER: c_long = 0x2; +pub const SSL_MODE_AUTO_RETRY: c_long = 0x4; +pub const SSL_MODE_NO_AUTO_CHAIN: c_long = 0x8; +pub const SSL_MODE_RELEASE_BUFFERS: c_long = 0x10; +#[cfg(not(libressl))] +pub const SSL_MODE_SEND_CLIENTHELLO_TIME: c_long = 0x20; +#[cfg(not(libressl))] +pub const SSL_MODE_SEND_SERVERHELLO_TIME: c_long = 0x40; +#[cfg(not(libressl))] +pub const SSL_MODE_SEND_FALLBACK_SCSV: c_long = 0x80; + +pub const SSL_ERROR_NONE: c_int = 0; +pub const SSL_ERROR_SSL: c_int = 1; +pub const SSL_ERROR_SYSCALL: c_int = 5; +pub const SSL_ERROR_WANT_ACCEPT: c_int = 8; +pub const SSL_ERROR_WANT_CONNECT: c_int = 7; +pub const SSL_ERROR_WANT_READ: c_int = 2; +pub const SSL_ERROR_WANT_WRITE: c_int = 3; +pub const SSL_ERROR_WANT_X509_LOOKUP: c_int = 4; +pub const SSL_ERROR_ZERO_RETURN: c_int = 6; +pub const SSL_VERIFY_NONE: c_int = 0; +pub const SSL_VERIFY_PEER: c_int = 1; +pub const SSL_VERIFY_FAIL_IF_NO_PEER_CERT: c_int = 2; + +#[cfg(not(any(libressl261, libressl262, libressl26x, libressl27, ossl101)))] +pub const SSL_OP_TLSEXT_PADDING: c_ulong = 0x00000010; +#[cfg(any(libressl261, libressl262, libressl26x, libressl27))] +pub const SSL_OP_TLSEXT_PADDING: c_ulong = 0x0; +pub const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: c_ulong = 0x00000800; +#[cfg(not(any(libressl261, libressl262, libressl26x, libressl27)))] +pub const SSL_OP_CRYPTOPRO_TLSEXT_BUG: c_ulong = 0x80000000; +#[cfg(any(libressl261, libressl262, libressl26x, libressl27))] +pub const SSL_OP_CRYPTOPRO_TLSEXT_BUG: c_ulong = 0x0; +pub const SSL_OP_LEGACY_SERVER_CONNECT: c_ulong = 0x00000004; +#[cfg(not(libressl))] +pub const SSL_OP_SAFARI_ECDHE_ECDSA_BUG: c_ulong = 0x00000040; +#[cfg(not(any(libressl, ossl110f, ossl111)))] +pub const SSL_OP_ALL: c_ulong = 0x80000BFF; +#[cfg(any(ossl110f, ossl111))] +pub const SSL_OP_ALL: c_ulong = SSL_OP_CRYPTOPRO_TLSEXT_BUG | SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS + | SSL_OP_LEGACY_SERVER_CONNECT | SSL_OP_TLSEXT_PADDING + | SSL_OP_SAFARI_ECDHE_ECDSA_BUG; +pub const SSL_OP_NO_QUERY_MTU: c_ulong = 0x00001000; +pub const SSL_OP_COOKIE_EXCHANGE: c_ulong = 0x00002000; +pub const SSL_OP_NO_TICKET: c_ulong = 0x00004000; +#[cfg(not(libressl))] +pub const SSL_OP_CISCO_ANYCONNECT: c_ulong = 0x00008000; +pub const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: c_ulong = 0x00010000; +#[cfg(not(libressl))] +pub const SSL_OP_NO_COMPRESSION: c_ulong = 0x00020000; +#[cfg(not(libressl))] +pub const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: c_ulong = 0x00040000; +pub const SSL_OP_CIPHER_SERVER_PREFERENCE: c_ulong = 0x00400000; +pub const SSL_OP_TLS_ROLLBACK_BUG: c_ulong = 0x00800000; +#[cfg(not(libressl))] +pub const SSL_OP_NO_SSLv3: c_ulong = 0x02000000; +pub const SSL_OP_NO_TLSv1: c_ulong = 0x04000000; +pub const SSL_OP_NO_TLSv1_1: c_ulong = 0x10000000; +pub const SSL_OP_NO_TLSv1_2: c_ulong = 0x08000000; +#[cfg(ossl111)] +pub const SSL_OP_NO_TLSv1_3: c_ulong = 0x20000000; + +#[cfg(not(any(ossl101, libressl)))] +pub const SSL_OP_NO_DTLSv1: c_ulong = 0x04000000; +#[cfg(not(any(ossl101, libressl)))] +pub const SSL_OP_NO_DTLSv1_2: c_ulong = 0x08000000; +#[cfg(not(any(ossl101, libressl, ossl111)))] +pub const SSL_OP_NO_SSL_MASK: c_ulong = + SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2; +#[cfg(ossl111)] +pub const SSL_OP_NO_SSL_MASK: c_ulong = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 + | SSL_OP_NO_TLSv1_1 | SSL_OP_NO_TLSv1_2 + | SSL_OP_NO_TLSv1_3; + +pub const SSL_FILETYPE_PEM: c_int = X509_FILETYPE_PEM; +pub const SSL_FILETYPE_ASN1: c_int = X509_FILETYPE_ASN1; + +pub const SSL_SESS_CACHE_OFF: c_long = 0; +pub const SSL_SESS_CACHE_CLIENT: c_long = 0x1; +pub const SSL_SESS_CACHE_SERVER: c_long = 0x2; +pub const SSL_SESS_CACHE_BOTH: c_long = SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_SERVER; +pub const SSL_SESS_CACHE_NO_AUTO_CLEAR: c_long = 0x80; +pub const SSL_SESS_CACHE_NO_INTERNAL_LOOKUP: c_long = 0x100; +pub const SSL_SESS_CACHE_NO_INTERNAL_STORE: c_long = 0x200; +pub const SSL_SESS_CACHE_NO_INTERNAL: c_long = + SSL_SESS_CACHE_NO_INTERNAL_LOOKUP | SSL_SESS_CACHE_NO_INTERNAL_STORE; + +pub const SSL3_VERSION: c_int = 0x300; +pub const TLS1_VERSION: c_int = 0x301; +pub const TLS1_1_VERSION: c_int = 0x302; +pub const TLS1_2_VERSION: c_int = 0x303; + +pub const TLSEXT_NAMETYPE_host_name: c_int = 0; + +pub const TLSEXT_STATUSTYPE_ocsp: c_int = 1; + +pub const SSL_TLSEXT_ERR_OK: c_int = 0; +pub const SSL_TLSEXT_ERR_ALERT_WARNING: c_int = 1; +pub const SSL_TLSEXT_ERR_ALERT_FATAL: c_int = 2; +pub const SSL_TLSEXT_ERR_NOACK: c_int = 3; + +pub const OPENSSL_NPN_UNSUPPORTED: c_int = 0; +pub const OPENSSL_NPN_NEGOTIATED: c_int = 1; +pub const OPENSSL_NPN_NO_OVERLAP: c_int = 2; + +pub const V_ASN1_GENERALIZEDTIME: c_int = 24; +pub const V_ASN1_UTCTIME: c_int = 23; + +pub const X509_FILETYPE_ASN1: c_int = 2; +pub const X509_FILETYPE_DEFAULT: c_int = 3; +pub const X509_FILETYPE_PEM: c_int = 1; + +pub const X509_V_OK: c_int = 0; +#[cfg(not(libressl))] +pub const X509_V_ERR_UNSPECIFIED: c_int = 1; +pub const X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: c_int = 2; +pub const X509_V_ERR_UNABLE_TO_GET_CRL: c_int = 3; +pub const X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: c_int = 4; +pub const X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: c_int = 5; +pub const X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: c_int = 6; +pub const X509_V_ERR_CERT_SIGNATURE_FAILURE: c_int = 7; +pub const X509_V_ERR_CRL_SIGNATURE_FAILURE: c_int = 8; +pub const X509_V_ERR_CERT_NOT_YET_VALID: c_int = 9; +pub const X509_V_ERR_CERT_HAS_EXPIRED: c_int = 10; +pub const X509_V_ERR_CRL_NOT_YET_VALID: c_int = 11; +pub const X509_V_ERR_CRL_HAS_EXPIRED: c_int = 12; +pub const X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: c_int = 13; +pub const X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: c_int = 14; +pub const X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: c_int = 15; +pub const X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: c_int = 16; +pub const X509_V_ERR_OUT_OF_MEM: c_int = 17; +pub const X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: c_int = 18; +pub const X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: c_int = 19; +pub const X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: c_int = 20; +pub const X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: c_int = 21; +pub const X509_V_ERR_CERT_CHAIN_TOO_LONG: c_int = 22; +pub const X509_V_ERR_CERT_REVOKED: c_int = 23; +pub const X509_V_ERR_INVALID_CA: c_int = 24; +pub const X509_V_ERR_PATH_LENGTH_EXCEEDED: c_int = 25; +pub const X509_V_ERR_INVALID_PURPOSE: c_int = 26; +pub const X509_V_ERR_CERT_UNTRUSTED: c_int = 27; +pub const X509_V_ERR_CERT_REJECTED: c_int = 28; +pub const X509_V_ERR_SUBJECT_ISSUER_MISMATCH: c_int = 29; +pub const X509_V_ERR_AKID_SKID_MISMATCH: c_int = 30; +pub const X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: c_int = 31; +pub const X509_V_ERR_KEYUSAGE_NO_CERTSIGN: c_int = 32; +pub const X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: c_int = 33; +pub const X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: c_int = 34; +pub const X509_V_ERR_KEYUSAGE_NO_CRL_SIGN: c_int = 35; +pub const X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION: c_int = 36; +pub const X509_V_ERR_INVALID_NON_CA: c_int = 37; +pub const X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED: c_int = 38; +pub const X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: c_int = 39; +pub const X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED: c_int = 40; +pub const X509_V_ERR_INVALID_EXTENSION: c_int = 41; +pub const X509_V_ERR_INVALID_POLICY_EXTENSION: c_int = 42; +pub const X509_V_ERR_NO_EXPLICIT_POLICY: c_int = 43; +pub const X509_V_ERR_DIFFERENT_CRL_SCOPE: c_int = 44; +pub const X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE: c_int = 45; +pub const X509_V_ERR_UNNESTED_RESOURCE: c_int = 46; +pub const X509_V_ERR_PERMITTED_VIOLATION: c_int = 47; +pub const X509_V_ERR_EXCLUDED_VIOLATION: c_int = 48; +pub const X509_V_ERR_SUBTREE_MINMAX: c_int = 49; +pub const X509_V_ERR_APPLICATION_VERIFICATION: c_int = 50; +pub const X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: c_int = 51; +pub const X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: c_int = 52; +pub const X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: c_int = 53; +pub const X509_V_ERR_CRL_PATH_VALIDATION_ERROR: c_int = 54; + +#[cfg(not(any(ossl101, libressl)))] +pub const X509_V_ERR_SUITE_B_INVALID_VERSION: c_int = 56; +#[cfg(not(any(ossl101, libressl)))] +pub const X509_V_ERR_SUITE_B_INVALID_ALGORITHM: c_int = 57; +#[cfg(not(any(ossl101, libressl)))] +pub const X509_V_ERR_SUITE_B_INVALID_CURVE: c_int = 58; +#[cfg(not(any(ossl101, libressl)))] +pub const X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM: c_int = 59; +#[cfg(not(any(ossl101, libressl)))] +pub const X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED: c_int = 60; +#[cfg(not(any(ossl101, libressl)))] +pub const X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256: c_int = 61; + +#[cfg(not(any(ossl101, libressl)))] +pub const X509_V_ERR_HOSTNAME_MISMATCH: c_int = 62; +#[cfg(not(any(ossl101, libressl)))] +pub const X509_V_ERR_EMAIL_MISMATCH: c_int = 63; +#[cfg(not(any(ossl101, libressl)))] +pub const X509_V_ERR_IP_ADDRESS_MISMATCH: c_int = 64; + +#[cfg(not(any(ossl101, libressl)))] +pub const X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT: c_uint = 0x1; +#[cfg(not(any(ossl101, libressl)))] +pub const X509_CHECK_FLAG_NO_WILDCARDS: c_uint = 0x2; +#[cfg(not(any(ossl101, libressl)))] +pub const X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS: c_uint = 0x4; +#[cfg(not(any(ossl101, libressl)))] +pub const X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS: c_uint = 0x8; +#[cfg(not(any(ossl101, libressl)))] +pub const X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS: c_uint = 0x10; + +pub const GEN_OTHERNAME: c_int = 0; +pub const GEN_EMAIL: c_int = 1; +pub const GEN_DNS: c_int = 2; +pub const GEN_X400: c_int = 3; +pub const GEN_DIRNAME: c_int = 4; +pub const GEN_EDIPARTY: c_int = 5; +pub const GEN_URI: c_int = 6; +pub const GEN_IPADD: c_int = 7; +pub const GEN_RID: c_int = 8; + +pub const DTLS1_COOKIE_LENGTH: c_uint = 256; + +// macros +pub unsafe fn BIO_get_mem_data(b: *mut BIO, pp: *mut *mut c_char) -> c_long { + BIO_ctrl(b, BIO_CTRL_INFO, 0, pp as *mut c_void) +} + +pub unsafe fn BIO_clear_retry_flags(b: *mut BIO) { + BIO_clear_flags(b, BIO_FLAGS_RWS | BIO_FLAGS_SHOULD_RETRY) +} + +pub unsafe fn BIO_set_retry_read(b: *mut BIO) { + BIO_set_flags(b, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY) +} + +pub unsafe fn BIO_set_retry_write(b: *mut BIO) { + BIO_set_flags(b, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY) +} + +// EVP_PKEY_CTX_ctrl macros +pub unsafe fn EVP_PKEY_CTX_set_rsa_padding(ctx: *mut EVP_PKEY_CTX, pad: c_int) -> c_int { + EVP_PKEY_CTX_ctrl( + ctx, + EVP_PKEY_RSA, + -1, + EVP_PKEY_CTRL_RSA_PADDING, + pad, + ptr::null_mut(), + ) +} + +pub unsafe fn EVP_PKEY_CTX_get_rsa_padding(ctx: *mut EVP_PKEY_CTX, ppad: *mut c_int) -> c_int { + EVP_PKEY_CTX_ctrl( + ctx, + EVP_PKEY_RSA, + -1, + EVP_PKEY_CTRL_GET_RSA_PADDING, + 0, + ppad as *mut c_void, + ) +} + +pub unsafe fn EVP_PKEY_CTX_set_rsa_pss_saltlen(ctx: *mut EVP_PKEY_CTX, len: c_int) -> c_int { + EVP_PKEY_CTX_ctrl( + ctx, + EVP_PKEY_RSA, + EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY, + EVP_PKEY_CTRL_RSA_PSS_SALTLEN, + len, + ptr::null_mut(), + ) +} + +pub unsafe fn EVP_PKEY_CTX_set_rsa_mgf1_md(ctx: *mut EVP_PKEY_CTX, md: *mut EVP_MD) -> c_int { + EVP_PKEY_CTX_ctrl( + ctx, + EVP_PKEY_RSA, + EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT, + EVP_PKEY_CTRL_RSA_MGF1_MD, + 0, + md as *mut c_void, + ) +} + +pub unsafe fn SSL_CTX_set_mode(ctx: *mut SSL_CTX, op: c_long) -> c_long { + SSL_CTX_ctrl(ctx, SSL_CTRL_MODE, op, ptr::null_mut()) +} + +pub unsafe fn SSL_CTX_set_read_ahead(ctx: *mut SSL_CTX, m: c_long) -> c_long { + SSL_CTX_ctrl(ctx, SSL_CTRL_SET_READ_AHEAD, m, ptr::null_mut()) +} + +pub unsafe fn SSL_CTX_set_tmp_dh(ctx: *mut SSL_CTX, dh: *mut DH) -> c_long { + SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TMP_DH, 0, dh as *mut c_void) +} + +pub unsafe fn SSL_CTX_set_tmp_ecdh(ctx: *mut SSL_CTX, key: *mut EC_KEY) -> c_long { + SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TMP_ECDH, 0, key as *mut c_void) +} + +pub unsafe fn SSL_set_tmp_dh(ssl: *mut SSL, dh: *mut DH) -> c_long { + SSL_ctrl(ssl, SSL_CTRL_SET_TMP_DH, 0, dh as *mut c_void) +} + +pub unsafe fn SSL_set_tmp_ecdh(ssl: *mut SSL, key: *mut EC_KEY) -> c_long { + SSL_ctrl(ssl, SSL_CTRL_SET_TMP_ECDH, 0, key as *mut c_void) +} + +pub unsafe fn SSL_CTX_add_extra_chain_cert(ctx: *mut SSL_CTX, x509: *mut X509) -> c_long { + SSL_CTX_ctrl(ctx, SSL_CTRL_EXTRA_CHAIN_CERT, 0, x509 as *mut c_void) +} + +#[cfg(not(any(ossl101, libressl)))] +pub unsafe fn SSL_CTX_set0_verify_cert_store(ctx: *mut SSL_CTX, st: *mut X509_STORE) -> c_long { + SSL_CTX_ctrl(ctx, SSL_CTRL_SET_VERIFY_CERT_STORE, 0, st as *mut c_void) +} + +pub unsafe fn SSL_CTX_set_tlsext_servername_callback( + ctx: *mut SSL_CTX, + cb: Option, +) -> c_long { + SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, cb) +} + +pub unsafe fn SSL_set_tlsext_host_name(s: *mut SSL, name: *mut c_char) -> c_long { + SSL_ctrl( + s, + SSL_CTRL_SET_TLSEXT_HOSTNAME, + TLSEXT_NAMETYPE_host_name as c_long, + name as *mut c_void, + ) +} + +pub unsafe fn SSL_set_tlsext_status_type(s: *mut SSL, type_: c_int) -> c_long { + SSL_ctrl( + s, + SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE, + type_ as c_long, + ptr::null_mut(), + ) +} + +pub unsafe fn SSL_CTX_set_tlsext_status_cb( + ctx: *mut SSL_CTX, + cb: Option c_int>, +) -> c_long { + SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB, mem::transmute(cb)) +} + +pub unsafe fn SSL_CTX_set_tlsext_status_arg(ctx: *mut SSL_CTX, arg: *mut c_void) -> c_long { + SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG, 0, arg) +} + +pub unsafe fn SSL_CTX_get_extra_chain_certs( + ctx: *mut SSL_CTX, + chain: *mut *mut stack_st_X509, +) -> c_long { + SSL_CTX_ctrl(ctx, SSL_CTRL_GET_EXTRA_CHAIN_CERTS, 0, chain as *mut c_void) +} + +pub unsafe fn SSL_CTX_set_session_cache_mode(ctx: *mut SSL_CTX, m: c_long) -> c_long { + SSL_CTX_ctrl(ctx, SSL_CTRL_SET_SESS_CACHE_MODE, m, ptr::null_mut()) +} + +pub unsafe fn SSL_get_tlsext_status_ocsp_resp(ssl: *mut SSL, resp: *mut *mut c_uchar) -> c_long { + SSL_ctrl( + ssl, + SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP, + 0, + resp as *mut c_void, + ) +} + +pub unsafe fn SSL_set_tlsext_status_ocsp_resp( + ssl: *mut SSL, + resp: *mut c_uchar, + len: c_long, +) -> c_long { + SSL_ctrl( + ssl, + SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP, + len, + resp as *mut c_void, + ) +} + +pub fn ERR_GET_LIB(l: c_ulong) -> c_int { + ((l >> 24) & 0x0FF) as c_int +} + +pub fn ERR_GET_FUNC(l: c_ulong) -> c_int { + ((l >> 12) & 0xFFF) as c_int +} + +pub fn ERR_GET_REASON(l: c_ulong) -> c_int { + (l & 0xFFF) as c_int +} + +extern "C" { + pub fn AES_set_encrypt_key(userKey: *const c_uchar, bits: c_int, key: *mut AES_KEY) -> c_int; + pub fn AES_set_decrypt_key(userKey: *const c_uchar, bits: c_int, key: *mut AES_KEY) -> c_int; + pub fn AES_ige_encrypt( + in_: *const c_uchar, + out: *mut c_uchar, + length: size_t, + key: *const AES_KEY, + ivec: *mut c_uchar, + enc: c_int, + ); + + pub fn ASN1_INTEGER_get(dest: *const ASN1_INTEGER) -> c_long; + pub fn ASN1_INTEGER_set(dest: *mut ASN1_INTEGER, value: c_long) -> c_int; + pub fn ASN1_INTEGER_to_BN(ai: *const ASN1_INTEGER, bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn ASN1_GENERALIZEDTIME_free(tm: *mut ASN1_GENERALIZEDTIME); + pub fn ASN1_GENERALIZEDTIME_print(b: *mut BIO, tm: *const ASN1_GENERALIZEDTIME) -> c_int; + pub fn ASN1_STRING_type_new(ty: c_int) -> *mut ASN1_STRING; + pub fn ASN1_TIME_free(tm: *mut ASN1_TIME); + pub fn ASN1_TIME_print(b: *mut BIO, tm: *const ASN1_TIME) -> c_int; + pub fn ASN1_BIT_STRING_free(x: *mut ASN1_BIT_STRING); + pub fn ASN1_OBJECT_free(x: *mut ASN1_OBJECT); + + pub fn BIO_ctrl(b: *mut BIO, cmd: c_int, larg: c_long, parg: *mut c_void) -> c_long; + pub fn BIO_free_all(b: *mut BIO); + pub fn BIO_new_fp(stream: *mut FILE, close_flag: c_int) -> *mut BIO; + pub fn BIO_new_socket(sock: c_int, close_flag: c_int) -> *mut BIO; + pub fn BIO_read(b: *mut BIO, buf: *mut c_void, len: c_int) -> c_int; + pub fn BIO_write(b: *mut BIO, buf: *const c_void, len: c_int) -> c_int; + #[cfg(any(ossl101, libressl))] + pub fn BIO_new_mem_buf(buf: *mut c_void, len: c_int) -> *mut BIO; + #[cfg(not(any(ossl101, libressl)))] + pub fn BIO_new_mem_buf(buf: *const c_void, len: c_int) -> *mut BIO; + pub fn BIO_set_flags(b: *mut BIO, flags: c_int); + pub fn BIO_clear_flags(b: *mut BIO, flags: c_int); + + pub fn BN_CTX_new() -> *mut BN_CTX; + pub fn BN_CTX_free(ctx: *mut BN_CTX); + + pub fn BN_new() -> *mut BIGNUM; + pub fn BN_dup(n: *const BIGNUM) -> *mut BIGNUM; + pub fn BN_clear(bn: *mut BIGNUM); + pub fn BN_free(bn: *mut BIGNUM); + pub fn BN_clear_free(bn: *mut BIGNUM); + pub fn BN_num_bits(bn: *const BIGNUM) -> c_int; + pub fn BN_set_negative(bn: *mut BIGNUM, n: c_int); + pub fn BN_set_word(bn: *mut BIGNUM, n: BN_ULONG) -> c_int; + pub fn BN_add(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM) -> c_int; + pub fn BN_div( + dv: *mut BIGNUM, + rem: *mut BIGNUM, + a: *const BIGNUM, + b: *const BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn BN_exp(r: *mut BIGNUM, a: *const BIGNUM, p: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; + pub fn BN_gcd(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; + pub fn BN_mod_add( + r: *mut BIGNUM, + a: *const BIGNUM, + b: *const BIGNUM, + m: *const BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn BN_mod_exp( + r: *mut BIGNUM, + a: *const BIGNUM, + p: *const BIGNUM, + m: *const BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn BN_mod_inverse( + r: *mut BIGNUM, + a: *const BIGNUM, + n: *const BIGNUM, + ctx: *mut BN_CTX, + ) -> *mut BIGNUM; + pub fn BN_mod_mul( + r: *mut BIGNUM, + a: *const BIGNUM, + b: *const BIGNUM, + m: *const BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn BN_mod_sqr( + r: *mut BIGNUM, + a: *const BIGNUM, + m: *const BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn BN_mod_sub( + r: *mut BIGNUM, + a: *const BIGNUM, + b: *const BIGNUM, + m: *const BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn BN_mul(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; + pub fn BN_nnmod( + rem: *mut BIGNUM, + a: *const BIGNUM, + m: *const BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn BN_add_word(r: *mut BIGNUM, w: BN_ULONG) -> c_int; + pub fn BN_sub_word(r: *mut BIGNUM, w: BN_ULONG) -> c_int; + pub fn BN_mul_word(r: *mut BIGNUM, w: BN_ULONG) -> c_int; + pub fn BN_div_word(r: *mut BIGNUM, w: BN_ULONG) -> BN_ULONG; + pub fn BN_mod_word(r: *const BIGNUM, w: BN_ULONG) -> BN_ULONG; + pub fn BN_sqr(r: *mut BIGNUM, a: *const BIGNUM, ctx: *mut BN_CTX) -> c_int; + pub fn BN_sub(r: *mut BIGNUM, a: *const BIGNUM, b: *const BIGNUM) -> c_int; + pub fn BN_clear_bit(a: *mut BIGNUM, n: c_int) -> c_int; + pub fn BN_is_bit_set(a: *const BIGNUM, n: c_int) -> c_int; + pub fn BN_lshift(r: *mut BIGNUM, a: *const BIGNUM, n: c_int) -> c_int; + pub fn BN_lshift1(r: *mut BIGNUM, a: *const BIGNUM) -> c_int; + pub fn BN_mask_bits(a: *mut BIGNUM, n: c_int) -> c_int; + pub fn BN_rshift(r: *mut BIGNUM, a: *const BIGNUM, n: c_int) -> c_int; + pub fn BN_set_bit(a: *mut BIGNUM, n: c_int) -> c_int; + pub fn BN_rshift1(r: *mut BIGNUM, a: *const BIGNUM) -> c_int; + pub fn BN_cmp(a: *const BIGNUM, b: *const BIGNUM) -> c_int; + pub fn BN_ucmp(a: *const BIGNUM, b: *const BIGNUM) -> c_int; + pub fn BN_generate_prime_ex( + r: *mut BIGNUM, + bits: c_int, + safe: c_int, + add: *const BIGNUM, + rem: *const BIGNUM, + cb: *mut BN_GENCB, + ) -> c_int; + pub fn BN_is_prime_ex( + p: *const BIGNUM, + checks: c_int, + ctx: *mut BN_CTX, + cb: *mut BN_GENCB, + ) -> c_int; + pub fn BN_is_prime_fasttest_ex( + p: *const BIGNUM, + checks: c_int, + ctx: *mut BN_CTX, + do_trial_division: c_int, + cb: *mut BN_GENCB, + ) -> c_int; + pub fn BN_rand(r: *mut BIGNUM, bits: c_int, top: c_int, bottom: c_int) -> c_int; + pub fn BN_pseudo_rand(r: *mut BIGNUM, bits: c_int, top: c_int, bottom: c_int) -> c_int; + pub fn BN_rand_range(r: *mut BIGNUM, range: *const BIGNUM) -> c_int; + pub fn BN_pseudo_rand_range(r: *mut BIGNUM, range: *const BIGNUM) -> c_int; + pub fn BN_bin2bn(s: *const u8, size: c_int, ret: *mut BIGNUM) -> *mut BIGNUM; + pub fn BN_bn2bin(a: *const BIGNUM, to: *mut u8) -> c_int; + pub fn BN_dec2bn(a: *mut *mut BIGNUM, s: *const c_char) -> c_int; + pub fn BN_bn2dec(a: *const BIGNUM) -> *mut c_char; + pub fn BN_hex2bn(a: *mut *mut BIGNUM, s: *const c_char) -> c_int; + pub fn BN_bn2hex(a: *const BIGNUM) -> *mut c_char; + pub fn BN_to_ASN1_INTEGER(bn: *const BIGNUM, ai: *mut ASN1_INTEGER) -> *mut ASN1_INTEGER; + + pub fn NCONF_default() -> *mut CONF_METHOD; + pub fn NCONF_new(meth: *mut CONF_METHOD) -> *mut CONF; + pub fn NCONF_free(conf: *mut CONF); + + pub fn CRYPTO_memcmp(a: *const c_void, b: *const c_void, len: size_t) -> c_int; + + pub fn DH_new() -> *mut DH; + pub fn DH_free(dh: *mut DH); + #[cfg(not(any(ossl101, libressl)))] + pub fn DH_get_1024_160() -> *mut DH; + #[cfg(not(any(ossl101, libressl)))] + pub fn DH_get_2048_224() -> *mut DH; + #[cfg(not(any(ossl101, libressl)))] + pub fn DH_get_2048_256() -> *mut DH; + + pub fn EC_KEY_new() -> *mut EC_KEY; + pub fn EC_KEY_new_by_curve_name(nid: c_int) -> *mut EC_KEY; + pub fn EC_KEY_dup(key: *const EC_KEY) -> *mut EC_KEY; + pub fn EC_KEY_up_ref(key: *mut EC_KEY) -> c_int; + pub fn EC_KEY_set_group(key: *mut EC_KEY, group: *const EC_GROUP) -> c_int; + pub fn EC_KEY_get0_group(key: *const EC_KEY) -> *const EC_GROUP; + pub fn EC_KEY_set_public_key(key: *mut EC_KEY, key: *const EC_POINT) -> c_int; + pub fn EC_KEY_get0_public_key(key: *const EC_KEY) -> *const EC_POINT; + pub fn EC_KEY_set_private_key(key: *mut EC_KEY, key: *const BIGNUM) -> c_int; + pub fn EC_KEY_get0_private_key(key: *const EC_KEY) -> *const BIGNUM; + pub fn EC_KEY_generate_key(key: *mut EC_KEY) -> c_int; + pub fn EC_KEY_check_key(key: *const EC_KEY) -> c_int; + pub fn EC_KEY_free(key: *mut EC_KEY); + pub fn EC_KEY_set_public_key_affine_coordinates( + key: *mut EC_KEY, + x: *mut BIGNUM, + y: *mut BIGNUM, + ) -> c_int; + + #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] + pub fn EC_GF2m_simple_method() -> *const EC_METHOD; + + pub fn EC_GROUP_new(meth: *const EC_METHOD) -> *mut EC_GROUP; + pub fn EC_GROUP_new_curve_GFp( + p: *const BIGNUM, + a: *const BIGNUM, + b: *const BIGNUM, + ctx: *mut BN_CTX, + ) -> *mut EC_GROUP; + #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] + pub fn EC_GROUP_new_curve_GF2m( + p: *const BIGNUM, + a: *const BIGNUM, + b: *const BIGNUM, + ctx: *mut BN_CTX, + ) -> *mut EC_GROUP; + pub fn EC_GROUP_new_by_curve_name(nid: c_int) -> *mut EC_GROUP; + pub fn EC_GROUP_get_curve_GFp( + group: *const EC_GROUP, + p: *mut BIGNUM, + a: *mut BIGNUM, + b: *mut BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] + pub fn EC_GROUP_get_curve_GF2m( + group: *const EC_GROUP, + p: *mut BIGNUM, + a: *mut BIGNUM, + b: *mut BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn EC_GROUP_get_degree(group: *const EC_GROUP) -> c_int; + pub fn EC_GROUP_get_order( + group: *const EC_GROUP, + order: *mut BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn EC_GROUP_set_asn1_flag(key: *mut EC_GROUP, flag: c_int); + + pub fn EC_GROUP_free(group: *mut EC_GROUP); + + pub fn EC_POINT_new(group: *const EC_GROUP) -> *mut EC_POINT; + pub fn EC_POINT_add( + group: *const EC_GROUP, + r: *mut EC_POINT, + a: *const EC_POINT, + b: *const EC_POINT, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn EC_POINT_mul( + group: *const EC_GROUP, + r: *mut EC_POINT, + n: *const BIGNUM, + q: *const EC_POINT, + m: *const BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn EC_POINT_invert(group: *const EC_GROUP, r: *mut EC_POINT, ctx: *mut BN_CTX) -> c_int; + pub fn EC_POINT_point2oct( + group: *const EC_GROUP, + p: *const EC_POINT, + form: point_conversion_form_t, + buf: *mut c_uchar, + len: size_t, + ctx: *mut BN_CTX, + ) -> size_t; + pub fn EC_POINT_oct2point( + group: *const EC_GROUP, + p: *mut EC_POINT, + buf: *const c_uchar, + len: size_t, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn EC_POINT_cmp( + group: *const EC_GROUP, + a: *const EC_POINT, + b: *const EC_POINT, + ctx: *mut BN_CTX, + ) -> c_int; + pub fn EC_POINT_free(point: *mut EC_POINT); + pub fn EC_POINT_get_affine_coordinates_GFp( + group: *const EC_GROUP, + p: *const EC_POINT, + x: *mut BIGNUM, + y: *mut BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + #[cfg(not(osslconf = "OPENSSL_NO_EC2M"))] + pub fn EC_POINT_get_affine_coordinates_GF2m( + group: *const EC_GROUP, + p: *const EC_POINT, + x: *mut BIGNUM, + y: *mut BIGNUM, + ctx: *mut BN_CTX, + ) -> c_int; + + pub fn ECDSA_SIG_new() -> *mut ECDSA_SIG; + pub fn ECDSA_SIG_free(sig: *mut ECDSA_SIG); + pub fn ECDSA_do_verify( + dgst: *const c_uchar, + dgst_len: c_int, + sig: *const ECDSA_SIG, + eckey: *mut EC_KEY, + ) -> c_int; + pub fn ECDSA_do_sign( + dgst: *const c_uchar, + dgst_len: c_int, + eckey: *mut EC_KEY, + ) -> *mut ECDSA_SIG; + + pub fn ERR_peek_last_error() -> c_ulong; + pub fn ERR_get_error() -> c_ulong; + pub fn ERR_get_error_line_data( + file: *mut *const c_char, + line: *mut c_int, + data: *mut *const c_char, + flags: *mut c_int, + ) -> c_ulong; + pub fn ERR_lib_error_string(err: c_ulong) -> *const c_char; + pub fn ERR_func_error_string(err: c_ulong) -> *const c_char; + pub fn ERR_reason_error_string(err: c_ulong) -> *const c_char; + pub fn ERR_clear_error(); + pub fn ERR_put_error(lib: c_int, func: c_int, reason: c_int, file: *const c_char, line: c_int); + pub fn ERR_set_error_data(data: *mut c_char, flags: c_int); + + pub fn EVP_md5() -> *const EVP_MD; + pub fn EVP_ripemd160() -> *const EVP_MD; + pub fn EVP_sha1() -> *const EVP_MD; + pub fn EVP_sha224() -> *const EVP_MD; + pub fn EVP_sha256() -> *const EVP_MD; + pub fn EVP_sha384() -> *const EVP_MD; + pub fn EVP_sha512() -> *const EVP_MD; + + pub fn EVP_aes_128_cbc() -> *const EVP_CIPHER; + pub fn EVP_aes_128_ecb() -> *const EVP_CIPHER; + pub fn EVP_aes_128_xts() -> *const EVP_CIPHER; + pub fn EVP_aes_128_ctr() -> *const EVP_CIPHER; + pub fn EVP_aes_128_gcm() -> *const EVP_CIPHER; + pub fn EVP_aes_128_ccm() -> *const EVP_CIPHER; + pub fn EVP_aes_128_cfb1() -> *const EVP_CIPHER; + pub fn EVP_aes_128_cfb128() -> *const EVP_CIPHER; + pub fn EVP_aes_128_cfb8() -> *const EVP_CIPHER; + pub fn EVP_aes_256_cbc() -> *const EVP_CIPHER; + pub fn EVP_aes_256_ecb() -> *const EVP_CIPHER; + pub fn EVP_aes_256_xts() -> *const EVP_CIPHER; + pub fn EVP_aes_256_ctr() -> *const EVP_CIPHER; + pub fn EVP_aes_256_gcm() -> *const EVP_CIPHER; + pub fn EVP_aes_256_ccm() -> *const EVP_CIPHER; + pub fn EVP_aes_256_cfb1() -> *const EVP_CIPHER; + pub fn EVP_aes_256_cfb128() -> *const EVP_CIPHER; + pub fn EVP_aes_256_cfb8() -> *const EVP_CIPHER; + pub fn EVP_bf_cbc() -> *const EVP_CIPHER; + pub fn EVP_bf_ecb() -> *const EVP_CIPHER; + pub fn EVP_bf_cfb64() -> *const EVP_CIPHER; + pub fn EVP_bf_ofb() -> *const EVP_CIPHER; + pub fn EVP_rc4() -> *const EVP_CIPHER; + + pub fn EVP_des_cbc() -> *const EVP_CIPHER; + pub fn EVP_des_ecb() -> *const EVP_CIPHER; + pub fn EVP_des_ede3() -> *const EVP_CIPHER; + pub fn EVP_des_ede3_cbc() -> *const EVP_CIPHER; + + pub fn EVP_BytesToKey( + typ: *const EVP_CIPHER, + md: *const EVP_MD, + salt: *const u8, + data: *const u8, + datalen: c_int, + count: c_int, + key: *mut u8, + iv: *mut u8, + ) -> c_int; + + pub fn EVP_CIPHER_CTX_new() -> *mut EVP_CIPHER_CTX; + pub fn EVP_CIPHER_CTX_set_padding(ctx: *mut EVP_CIPHER_CTX, padding: c_int) -> c_int; + pub fn EVP_CIPHER_CTX_set_key_length(ctx: *mut EVP_CIPHER_CTX, keylen: c_int) -> c_int; + pub fn EVP_CIPHER_CTX_ctrl( + ctx: *mut EVP_CIPHER_CTX, + type_: c_int, + arg: c_int, + ptr: *mut c_void, + ) -> c_int; + pub fn EVP_CIPHER_CTX_free(ctx: *mut EVP_CIPHER_CTX); + + pub fn EVP_CipherInit( + ctx: *mut EVP_CIPHER_CTX, + evp: *const EVP_CIPHER, + key: *const u8, + iv: *const u8, + mode: c_int, + ) -> c_int; + pub fn EVP_CipherInit_ex( + ctx: *mut EVP_CIPHER_CTX, + type_: *const EVP_CIPHER, + impl_: *mut ENGINE, + key: *const c_uchar, + iv: *const c_uchar, + enc: c_int, + ) -> c_int; + pub fn EVP_CipherUpdate( + ctx: *mut EVP_CIPHER_CTX, + outbuf: *mut u8, + outlen: *mut c_int, + inbuf: *const u8, + inlen: c_int, + ) -> c_int; + pub fn EVP_CipherFinal(ctx: *mut EVP_CIPHER_CTX, res: *mut u8, len: *mut c_int) -> c_int; + + pub fn EVP_DigestInit(ctx: *mut EVP_MD_CTX, typ: *const EVP_MD) -> c_int; + pub fn EVP_DigestInit_ex(ctx: *mut EVP_MD_CTX, typ: *const EVP_MD, imple: *mut ENGINE) + -> c_int; + pub fn EVP_DigestUpdate(ctx: *mut EVP_MD_CTX, data: *const c_void, n: size_t) -> c_int; + pub fn EVP_DigestFinal(ctx: *mut EVP_MD_CTX, res: *mut u8, n: *mut u32) -> c_int; + pub fn EVP_DigestFinal_ex(ctx: *mut EVP_MD_CTX, res: *mut u8, n: *mut u32) -> c_int; + + pub fn EVP_DigestSignInit( + ctx: *mut EVP_MD_CTX, + pctx: *mut *mut EVP_PKEY_CTX, + type_: *const EVP_MD, + e: *mut ENGINE, + pkey: *mut EVP_PKEY, + ) -> c_int; + pub fn EVP_DigestSignFinal( + ctx: *mut EVP_MD_CTX, + sig: *mut c_uchar, + siglen: *mut size_t, + ) -> c_int; + pub fn EVP_DigestVerifyInit( + ctx: *mut EVP_MD_CTX, + pctx: *mut *mut EVP_PKEY_CTX, + type_: *const EVP_MD, + e: *mut ENGINE, + pkey: *mut EVP_PKEY, + ) -> c_int; + #[cfg(any(ossl101, libressl))] + pub fn EVP_DigestVerifyFinal( + ctx: *mut EVP_MD_CTX, + sigret: *mut c_uchar, + siglen: size_t, + ) -> c_int; + #[cfg(not(any(ossl101, libressl)))] + pub fn EVP_DigestVerifyFinal( + ctx: *mut EVP_MD_CTX, + sigret: *const c_uchar, + siglen: size_t, + ) -> c_int; + + pub fn EVP_MD_CTX_copy_ex(dst: *mut EVP_MD_CTX, src: *const EVP_MD_CTX) -> c_int; + + pub fn EVP_PKEY_new() -> *mut EVP_PKEY; + pub fn EVP_PKEY_free(k: *mut EVP_PKEY); + pub fn EVP_PKEY_assign(pkey: *mut EVP_PKEY, typ: c_int, key: *mut c_void) -> c_int; + pub fn EVP_PKEY_copy_parameters(to: *mut EVP_PKEY, from: *const EVP_PKEY) -> c_int; + pub fn EVP_PKEY_get1_RSA(k: *mut EVP_PKEY) -> *mut RSA; + pub fn EVP_PKEY_set1_RSA(k: *mut EVP_PKEY, r: *mut RSA) -> c_int; + pub fn EVP_PKEY_get1_DSA(k: *mut EVP_PKEY) -> *mut DSA; + pub fn EVP_PKEY_get1_DH(k: *mut EVP_PKEY) -> *mut DH; + pub fn EVP_PKEY_get1_EC_KEY(k: *mut EVP_PKEY) -> *mut EC_KEY; + pub fn EVP_PKEY_cmp(a: *const EVP_PKEY, b: *const EVP_PKEY) -> c_int; + pub fn EVP_PKEY_id(pkey: *const EVP_PKEY) -> c_int; + pub fn EVP_PKEY_new_mac_key( + type_: c_int, + e: *mut ENGINE, + key: *const c_uchar, + keylen: c_int, + ) -> *mut EVP_PKEY; + pub fn EVP_PKEY_derive_init(ctx: *mut EVP_PKEY_CTX) -> c_int; + pub fn EVP_PKEY_derive_set_peer(ctx: *mut EVP_PKEY_CTX, peer: *mut EVP_PKEY) -> c_int; + pub fn EVP_PKEY_derive(ctx: *mut EVP_PKEY_CTX, key: *mut c_uchar, size: *mut size_t) -> c_int; + pub fn d2i_PKCS8PrivateKey_bio( + bp: *mut BIO, + x: *mut *mut EVP_PKEY, + cb: Option, + u: *mut c_void, + ) -> *mut EVP_PKEY; + + pub fn EVP_PKEY_CTX_new(k: *mut EVP_PKEY, e: *mut ENGINE) -> *mut EVP_PKEY_CTX; + pub fn EVP_PKEY_CTX_new_id(id: c_int, e: *mut ENGINE) -> *mut EVP_PKEY_CTX; + pub fn EVP_PKEY_CTX_free(ctx: *mut EVP_PKEY_CTX); + pub fn EVP_PKEY_CTX_ctrl( + ctx: *mut EVP_PKEY_CTX, + keytype: c_int, + optype: c_int, + cmd: c_int, + p1: c_int, + p2: *mut c_void, + ) -> c_int; + + pub fn EVP_PKEY_keygen_init(ctx: *mut EVP_PKEY_CTX) -> c_int; + pub fn EVP_PKEY_keygen(ctx: *mut EVP_PKEY_CTX, key: *mut *mut EVP_PKEY) -> c_int; + + pub fn HMAC_CTX_copy(dst: *mut HMAC_CTX, src: *mut HMAC_CTX) -> c_int; + + pub fn OBJ_obj2nid(o: *const ASN1_OBJECT) -> c_int; + pub fn OBJ_obj2txt( + buf: *mut c_char, + buf_len: c_int, + a: *const ASN1_OBJECT, + no_name: c_int, + ) -> c_int; + pub fn OBJ_nid2sn(nid: c_int) -> *const c_char; + + pub fn OCSP_BASICRESP_new() -> *mut OCSP_BASICRESP; + pub fn OCSP_BASICRESP_free(r: *mut OCSP_BASICRESP); + pub fn OCSP_basic_verify( + bs: *mut OCSP_BASICRESP, + certs: *mut stack_st_X509, + st: *mut X509_STORE, + flags: c_ulong, + ) -> c_int; + pub fn OCSP_resp_find_status( + bs: *mut OCSP_BASICRESP, + id: *mut OCSP_CERTID, + status: *mut c_int, + reason: *mut c_int, + revtime: *mut *mut ASN1_GENERALIZEDTIME, + thisupd: *mut *mut ASN1_GENERALIZEDTIME, + nextupd: *mut *mut ASN1_GENERALIZEDTIME, + ) -> c_int; + pub fn OCSP_check_validity( + thisupd: *mut ASN1_GENERALIZEDTIME, + nextupd: *mut ASN1_GENERALIZEDTIME, + sec: c_long, + maxsec: c_long, + ) -> c_int; + + pub fn OCSP_CERTID_free(id: *mut OCSP_CERTID); + + pub fn OCSP_RESPONSE_new() -> *mut OCSP_RESPONSE; + pub fn OCSP_RESPONSE_free(r: *mut OCSP_RESPONSE); + pub fn i2d_OCSP_RESPONSE(a: *mut OCSP_RESPONSE, pp: *mut *mut c_uchar) -> c_int; + pub fn d2i_OCSP_RESPONSE( + a: *mut *mut OCSP_RESPONSE, + pp: *mut *const c_uchar, + length: c_long, + ) -> *mut OCSP_RESPONSE; + pub fn OCSP_response_create(status: c_int, bs: *mut OCSP_BASICRESP) -> *mut OCSP_RESPONSE; + pub fn OCSP_response_status(resp: *mut OCSP_RESPONSE) -> c_int; + pub fn OCSP_response_get1_basic(resp: *mut OCSP_RESPONSE) -> *mut OCSP_BASICRESP; + + pub fn OCSP_REQUEST_new() -> *mut OCSP_REQUEST; + pub fn OCSP_REQUEST_free(r: *mut OCSP_REQUEST); + pub fn i2d_OCSP_REQUEST(a: *mut OCSP_REQUEST, pp: *mut *mut c_uchar) -> c_int; + pub fn d2i_OCSP_REQUEST( + a: *mut *mut OCSP_REQUEST, + pp: *mut *const c_uchar, + length: c_long, + ) -> *mut OCSP_REQUEST; + pub fn OCSP_request_add0_id(r: *mut OCSP_REQUEST, id: *mut OCSP_CERTID) -> *mut OCSP_ONEREQ; + + pub fn OCSP_ONEREQ_free(r: *mut OCSP_ONEREQ); + + pub fn PEM_read_bio_DHparams( + bio: *mut BIO, + out: *mut *mut DH, + callback: Option, + user_data: *mut c_void, + ) -> *mut DH; + pub fn PEM_read_bio_X509( + bio: *mut BIO, + out: *mut *mut X509, + callback: Option, + user_data: *mut c_void, + ) -> *mut X509; + pub fn PEM_read_bio_X509_REQ( + bio: *mut BIO, + out: *mut *mut X509_REQ, + callback: Option, + user_data: *mut c_void, + ) -> *mut X509_REQ; + pub fn PEM_read_bio_PrivateKey( + bio: *mut BIO, + out: *mut *mut EVP_PKEY, + callback: Option, + user_data: *mut c_void, + ) -> *mut EVP_PKEY; + pub fn PEM_read_bio_PUBKEY( + bio: *mut BIO, + out: *mut *mut EVP_PKEY, + callback: Option, + user_data: *mut c_void, + ) -> *mut EVP_PKEY; + + pub fn PEM_read_bio_RSAPrivateKey( + bio: *mut BIO, + rsa: *mut *mut RSA, + callback: Option, + user_data: *mut c_void, + ) -> *mut RSA; + + pub fn PEM_read_bio_RSAPublicKey( + bio: *mut BIO, + rsa: *mut *mut RSA, + callback: Option, + user_data: *mut c_void, + ) -> *mut RSA; + + pub fn PEM_read_bio_RSA_PUBKEY( + bio: *mut BIO, + rsa: *mut *mut RSA, + callback: Option, + user_data: *mut c_void, + ) -> *mut RSA; + + pub fn PEM_write_bio_DHparams(bio: *mut BIO, x: *const DH) -> c_int; + pub fn PEM_write_bio_PrivateKey( + bio: *mut BIO, + pkey: *mut EVP_PKEY, + cipher: *const EVP_CIPHER, + kstr: *mut c_uchar, + klen: c_int, + callback: Option, + user_data: *mut c_void, + ) -> c_int; + pub fn PEM_write_bio_PKCS8PrivateKey( + bio: *mut BIO, + pkey: *mut EVP_PKEY, + cipher: *const EVP_CIPHER, + kstr: *mut c_char, + klen: c_int, + callback: Option, + user_data: *mut c_void, + ) -> c_int; + pub fn PEM_write_bio_PUBKEY(bp: *mut BIO, x: *mut EVP_PKEY) -> c_int; + pub fn PEM_write_bio_RSAPrivateKey( + bp: *mut BIO, + rsa: *mut RSA, + cipher: *const EVP_CIPHER, + kstr: *mut c_uchar, + klen: c_int, + callback: Option, + user_data: *mut c_void, + ) -> c_int; + pub fn PEM_write_bio_RSAPublicKey(bp: *mut BIO, rsa: *const RSA) -> c_int; + pub fn PEM_write_bio_RSA_PUBKEY(bp: *mut BIO, rsa: *mut RSA) -> c_int; + + pub fn PEM_read_bio_DSAPrivateKey( + bp: *mut BIO, + dsa: *mut *mut DSA, + callback: Option, + user_data: *mut c_void, + ) -> *mut DSA; + pub fn PEM_read_bio_DSA_PUBKEY( + bp: *mut BIO, + dsa: *mut *mut DSA, + callback: Option, + user_data: *mut c_void, + ) -> *mut DSA; + pub fn PEM_write_bio_DSAPrivateKey( + bp: *mut BIO, + dsa: *mut DSA, + cipher: *const EVP_CIPHER, + kstr: *mut c_uchar, + klen: c_int, + callback: Option, + user_data: *mut c_void, + ) -> c_int; + pub fn PEM_write_bio_DSA_PUBKEY(bp: *mut BIO, dsa: *mut DSA) -> c_int; + + pub fn PEM_write_bio_X509(bio: *mut BIO, x509: *mut X509) -> c_int; + pub fn PEM_write_bio_X509_REQ(bio: *mut BIO, x509: *mut X509_REQ) -> c_int; + + pub fn PEM_write_bio_ECPrivateKey( + bio: *mut BIO, + key: *mut EC_KEY, + cipher: *const EVP_CIPHER, + kstr: *mut c_uchar, + klen: c_int, + callback: Option, + user_data: *mut c_void, + ) -> c_int; + pub fn PEM_read_bio_ECPrivateKey( + bio: *mut BIO, + key: *mut *mut EC_KEY, + callback: Option, + user_data: *mut c_void, + ) -> *mut EC_KEY; + + pub fn PKCS5_PBKDF2_HMAC_SHA1( + pass: *const c_char, + passlen: c_int, + salt: *const u8, + saltlen: c_int, + iter: c_int, + keylen: c_int, + out: *mut u8, + ) -> c_int; + pub fn PKCS5_PBKDF2_HMAC( + pass: *const c_char, + passlen: c_int, + salt: *const c_uchar, + saltlen: c_int, + iter: c_int, + digest: *const EVP_MD, + keylen: c_int, + out: *mut u8, + ) -> c_int; + + pub fn RAND_bytes(buf: *mut u8, num: c_int) -> c_int; + pub fn RAND_status() -> c_int; + + pub fn RSA_new() -> *mut RSA; + pub fn RSA_free(rsa: *mut RSA); + pub fn RSA_generate_key_ex( + rsa: *mut RSA, + bits: c_int, + e: *mut BIGNUM, + cb: *mut BN_GENCB, + ) -> c_int; + pub fn RSA_private_decrypt( + flen: c_int, + from: *const u8, + to: *mut u8, + k: *mut RSA, + pad: c_int, + ) -> c_int; + pub fn RSA_public_decrypt( + flen: c_int, + from: *const u8, + to: *mut u8, + k: *mut RSA, + pad: c_int, + ) -> c_int; + pub fn RSA_private_encrypt( + flen: c_int, + from: *const u8, + to: *mut u8, + k: *mut RSA, + pad: c_int, + ) -> c_int; + pub fn RSA_public_encrypt( + flen: c_int, + from: *const u8, + to: *mut u8, + k: *mut RSA, + pad: c_int, + ) -> c_int; + pub fn RSA_sign( + t: c_int, + m: *const u8, + mlen: c_uint, + sig: *mut u8, + siglen: *mut c_uint, + k: *mut RSA, + ) -> c_int; + pub fn RSA_size(k: *const RSA) -> c_int; + pub fn RSA_verify( + t: c_int, + m: *const u8, + mlen: c_uint, + sig: *const u8, + siglen: c_uint, + k: *mut RSA, + ) -> c_int; + + pub fn DSA_new() -> *mut DSA; + pub fn DSA_free(dsa: *mut DSA); + pub fn DSA_size(dsa: *const DSA) -> c_int; + pub fn DSA_generate_parameters_ex( + dsa: *mut DSA, + bits: c_int, + seed: *const c_uchar, + seed_len: c_int, + counter_ref: *mut c_int, + h_ret: *mut c_ulong, + cb: *mut BN_GENCB, + ) -> c_int; + pub fn DSA_generate_key(dsa: *mut DSA) -> c_int; + pub fn DSA_sign( + dummy: c_int, + dgst: *const c_uchar, + len: c_int, + sigret: *mut c_uchar, + siglen: *mut c_uint, + dsa: *mut DSA, + ) -> c_int; + pub fn DSA_verify( + dummy: c_int, + dgst: *const c_uchar, + len: c_int, + sigbuf: *const c_uchar, + siglen: c_int, + dsa: *mut DSA, + ) -> c_int; + + pub fn SHA1(d: *const c_uchar, n: size_t, md: *mut c_uchar) -> *mut c_uchar; + pub fn SHA224(d: *const c_uchar, n: size_t, md: *mut c_uchar) -> *mut c_uchar; + pub fn SHA256(d: *const c_uchar, n: size_t, md: *mut c_uchar) -> *mut c_uchar; + pub fn SHA384(d: *const c_uchar, n: size_t, md: *mut c_uchar) -> *mut c_uchar; + pub fn SHA512(d: *const c_uchar, n: size_t, md: *mut c_uchar) -> *mut c_uchar; + + pub fn SHA1_Init(c: *mut SHA_CTX) -> c_int; + pub fn SHA1_Update(c: *mut SHA_CTX, data: *const c_void, len: size_t) -> c_int; + pub fn SHA1_Final(md: *mut c_uchar, c: *mut SHA_CTX) -> c_int; + pub fn SHA256_Init(c: *mut SHA256_CTX) -> c_int; + pub fn SHA256_Update(c: *mut SHA256_CTX, data: *const c_void, len: size_t) -> c_int; + pub fn SHA256_Final(md: *mut c_uchar, c: *mut SHA256_CTX) -> c_int; + pub fn SHA224_Init(c: *mut SHA256_CTX) -> c_int; + pub fn SHA224_Update(c: *mut SHA256_CTX, data: *const c_void, len: size_t) -> c_int; + pub fn SHA224_Final(md: *mut c_uchar, c: *mut SHA256_CTX) -> c_int; + pub fn SHA384_Init(c: *mut SHA512_CTX) -> c_int; + pub fn SHA384_Update(c: *mut SHA512_CTX, data: *const c_void, len: size_t) -> c_int; + pub fn SHA384_Final(md: *mut c_uchar, c: *mut SHA512_CTX) -> c_int; + pub fn SHA512_Init(c: *mut SHA512_CTX) -> c_int; + pub fn SHA512_Update(c: *mut SHA512_CTX, data: *const c_void, len: size_t) -> c_int; + pub fn SHA512_Final(md: *mut c_uchar, c: *mut SHA512_CTX) -> c_int; + + pub fn SSL_new(ctx: *mut SSL_CTX) -> *mut SSL; + pub fn SSL_pending(ssl: *const SSL) -> c_int; + pub fn SSL_free(ssl: *mut SSL); + pub fn SSL_set_bio(ssl: *mut SSL, rbio: *mut BIO, wbio: *mut BIO); + pub fn SSL_get_rbio(ssl: *const SSL) -> *mut BIO; + pub fn SSL_get_wbio(ssl: *const SSL) -> *mut BIO; + pub fn SSL_accept(ssl: *mut SSL) -> c_int; + pub fn SSL_connect(ssl: *mut SSL) -> c_int; + pub fn SSL_do_handshake(ssl: *mut SSL) -> c_int; + pub fn SSL_ctrl(ssl: *mut SSL, cmd: c_int, larg: c_long, parg: *mut c_void) -> c_long; + pub fn SSL_get_error(ssl: *const SSL, ret: c_int) -> c_int; + pub fn SSL_read(ssl: *mut SSL, buf: *mut c_void, num: c_int) -> c_int; + pub fn SSL_write(ssl: *mut SSL, buf: *const c_void, num: c_int) -> c_int; + pub fn SSL_get_ex_data_X509_STORE_CTX_idx() -> c_int; + pub fn SSL_get_SSL_CTX(ssl: *const SSL) -> *mut SSL_CTX; + pub fn SSL_set_SSL_CTX(ssl: *mut SSL, ctx: *mut SSL_CTX) -> *mut SSL_CTX; + #[cfg(not(any(osslconf = "OPENSSL_NO_COMP", libressl)))] + pub fn SSL_get_current_compression(ssl: *mut SSL) -> *const COMP_METHOD; + #[cfg(libressl)] + pub fn SSL_get_current_compression(ssl: *mut SSL) -> *const libc::c_void; + pub fn SSL_get_peer_certificate(ssl: *const SSL) -> *mut X509; + pub fn SSL_get_peer_cert_chain(ssl: *const SSL) -> *mut stack_st_X509; + pub fn SSL_get_ssl_method(ssl: *mut SSL) -> *const SSL_METHOD; + pub fn SSL_get_version(ssl: *const SSL) -> *const c_char; + pub fn SSL_version(ssl: *const SSL) -> c_int; + pub fn SSL_state_string(ssl: *const SSL) -> *const c_char; + pub fn SSL_state_string_long(ssl: *const SSL) -> *const c_char; + pub fn SSL_set_verify( + ssl: *mut SSL, + mode: c_int, + verify_callback: Option c_int>, + ); + pub fn SSL_set_ex_data(ssl: *mut SSL, idx: c_int, data: *mut c_void) -> c_int; + pub fn SSL_get_ex_data(ssl: *const SSL, idx: c_int) -> *mut c_void; + pub fn SSL_get_servername(ssl: *const SSL, name_type: c_int) -> *const c_char; + pub fn SSL_get_current_cipher(ssl: *const SSL) -> *const SSL_CIPHER; + #[cfg(not(any(ossl101, libressl)))] + pub fn SSL_get0_param(ssl: *mut SSL) -> *mut X509_VERIFY_PARAM; + pub fn SSL_get_verify_result(ssl: *const SSL) -> c_long; + pub fn SSL_shutdown(ssl: *mut SSL) -> c_int; + pub fn SSL_get_certificate(ssl: *const SSL) -> *mut X509; + #[cfg(any(ossl101, libressl))] + pub fn SSL_get_privatekey(ssl: *mut SSL) -> *mut EVP_PKEY; + #[cfg(not(any(ossl101, libressl)))] + pub fn SSL_get_privatekey(ssl: *const SSL) -> *mut EVP_PKEY; + pub fn SSL_load_client_CA_file(file: *const c_char) -> *mut stack_st_X509_NAME; + pub fn SSL_set_tmp_dh_callback( + ctx: *mut SSL, + dh: unsafe extern "C" fn(ssl: *mut SSL, is_export: c_int, keylength: c_int) -> *mut DH, + ); + pub fn SSL_export_keying_material( + s: *mut SSL, + out: *mut c_uchar, + olen: size_t, + label: *const c_char, + llen: size_t, + context: *const c_uchar, + contextlen: size_t, + use_context: c_int, + ) -> c_int; + + #[cfg(not(any(osslconf = "OPENSSL_NO_COMP", libressl)))] + pub fn SSL_COMP_get_name(comp: *const COMP_METHOD) -> *const c_char; + #[cfg(libressl)] + pub fn SSL_COMP_get_name(comp: *const libc::c_void) -> *const c_char; + + pub fn SSL_CIPHER_get_name(cipher: *const SSL_CIPHER) -> *const c_char; + pub fn SSL_CIPHER_get_bits(cipher: *const SSL_CIPHER, alg_bits: *mut c_int) -> c_int; + pub fn SSL_CIPHER_description( + cipher: *const SSL_CIPHER, + buf: *mut c_char, + size: c_int, + ) -> *mut c_char; + + pub fn SSL_CTX_new(method: *const SSL_METHOD) -> *mut SSL_CTX; + pub fn SSL_CTX_free(ctx: *mut SSL_CTX); + pub fn SSL_CTX_ctrl(ctx: *mut SSL_CTX, cmd: c_int, larg: c_long, parg: *mut c_void) -> c_long; + pub fn SSL_CTX_callback_ctrl( + ctx: *mut SSL_CTX, + cmd: c_int, + fp: Option, + ) -> c_long; + pub fn SSL_CTX_set_verify( + ctx: *mut SSL_CTX, + mode: c_int, + verify_callback: Option c_int>, + ); + pub fn SSL_CTX_set_verify_depth(ctx: *mut SSL_CTX, depth: c_int); + pub fn SSL_CTX_load_verify_locations( + ctx: *mut SSL_CTX, + CAfile: *const c_char, + CApath: *const c_char, + ) -> c_int; + pub fn SSL_CTX_set_default_verify_paths(ctx: *mut SSL_CTX) -> c_int; + pub fn SSL_CTX_set_ex_data(ctx: *mut SSL_CTX, idx: c_int, data: *mut c_void) -> c_int; + pub fn SSL_CTX_get_ex_data(ctx: *const SSL_CTX, idx: c_int) -> *mut c_void; + pub fn SSL_CTX_set_session_id_context( + ssl: *mut SSL_CTX, + sid_ctx: *const c_uchar, + sid_ctx_len: c_uint, + ) -> c_int; + + pub fn SSL_CTX_use_certificate_file( + ctx: *mut SSL_CTX, + cert_file: *const c_char, + file_type: c_int, + ) -> c_int; + pub fn SSL_CTX_use_certificate_chain_file( + ctx: *mut SSL_CTX, + cert_chain_file: *const c_char, + ) -> c_int; + pub fn SSL_CTX_use_certificate(ctx: *mut SSL_CTX, cert: *mut X509) -> c_int; + + pub fn SSL_CTX_use_PrivateKey_file( + ctx: *mut SSL_CTX, + key_file: *const c_char, + file_type: c_int, + ) -> c_int; + pub fn SSL_CTX_use_PrivateKey(ctx: *mut SSL_CTX, key: *mut EVP_PKEY) -> c_int; + pub fn SSL_CTX_check_private_key(ctx: *const SSL_CTX) -> c_int; + pub fn SSL_CTX_set_client_CA_list(ctx: *mut SSL_CTX, list: *mut stack_st_X509_NAME); + pub fn SSL_CTX_get_cert_store(ctx: *const SSL_CTX) -> *mut X509_STORE; + // FIXME should take an option + pub fn SSL_CTX_set_tmp_dh_callback( + ctx: *mut SSL_CTX, + dh: unsafe extern "C" fn(ssl: *mut SSL, is_export: c_int, keylength: c_int) -> *mut DH, + ); + pub fn SSL_CTX_sess_set_new_cb( + ctx: *mut SSL_CTX, + new_session_cb: Option c_int>, + ); + pub fn SSL_CTX_sess_set_remove_cb( + ctx: *mut SSL_CTX, + remove_session_cb: Option, + ); + + #[cfg(not(any(ossl101, libressl)))] + pub fn SSL_CTX_get0_certificate(ctx: *const SSL_CTX) -> *mut X509; + #[cfg(not(any(ossl101, libressl)))] + pub fn SSL_CTX_get0_privatekey(ctx: *const SSL_CTX) -> *mut EVP_PKEY; + + pub fn SSL_CTX_set_cipher_list(ssl: *mut SSL_CTX, s: *const c_char) -> c_int; + + pub fn SSL_CTX_set_next_protos_advertised_cb( + ssl: *mut SSL_CTX, + cb: extern "C" fn( + ssl: *mut SSL, + out: *mut *const c_uchar, + outlen: *mut c_uint, + arg: *mut c_void, + ) -> c_int, + arg: *mut c_void, + ); + pub fn SSL_CTX_set_next_proto_select_cb( + ssl: *mut SSL_CTX, + cb: extern "C" fn( + ssl: *mut SSL, + out: *mut *mut c_uchar, + outlen: *mut c_uchar, + inbuf: *const c_uchar, + inlen: c_uint, + arg: *mut c_void, + ) -> c_int, + arg: *mut c_void, + ); + #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] + pub fn SSL_CTX_set_psk_client_callback( + ssl: *mut SSL_CTX, + psk_client_cb: Option< + extern "C" fn(*mut SSL, *const c_char, *mut c_char, c_uint, *mut c_uchar, c_uint) + -> c_uint, + >, + ); + + pub fn SSL_select_next_proto( + out: *mut *mut c_uchar, + outlen: *mut c_uchar, + inbuf: *const c_uchar, + inlen: c_uint, + client: *const c_uchar, + client_len: c_uint, + ) -> c_int; + pub fn SSL_get0_next_proto_negotiated( + s: *const SSL, + data: *mut *const c_uchar, + len: *mut c_uint, + ); + pub fn SSL_get_session(s: *const SSL) -> *mut SSL_SESSION; + pub fn SSL_set_session(ssl: *mut SSL, session: *mut SSL_SESSION) -> c_int; + #[cfg(not(any(ossl101, libressl, ossl110f, ossl111)))] + pub fn SSL_is_server(s: *mut SSL) -> c_int; + #[cfg(any(ossl110f, ossl111))] + pub fn SSL_is_server(s: *const SSL) -> c_int; + + pub fn SSL_SESSION_free(s: *mut SSL_SESSION); + pub fn SSL_SESSION_get_id(s: *const SSL_SESSION, len: *mut c_uint) -> *const c_uchar; + + #[cfg(not(ossl101))] + pub fn SSL_CTX_set_alpn_protos(s: *mut SSL_CTX, data: *const c_uchar, len: c_uint) -> c_int; + + #[cfg(not(ossl101))] + pub fn SSL_set_alpn_protos(s: *mut SSL, data: *const c_uchar, len: c_uint) -> c_int; + + // FIXME should take an Option + #[cfg(not(ossl101))] + pub fn SSL_CTX_set_alpn_select_cb( + ssl: *mut SSL_CTX, + cb: extern "C" fn( + ssl: *mut SSL, + out: *mut *const c_uchar, + outlen: *mut c_uchar, + inbuf: *const c_uchar, + inlen: c_uint, + arg: *mut c_void, + ) -> c_int, + arg: *mut c_void, + ); + #[cfg(not(ossl101))] + pub fn SSL_get0_alpn_selected(s: *const SSL, data: *mut *const c_uchar, len: *mut c_uint); + + pub fn X509_add_ext(x: *mut X509, ext: *mut X509_EXTENSION, loc: c_int) -> c_int; + pub fn X509_digest( + x: *const X509, + digest: *const EVP_MD, + buf: *mut c_uchar, + len: *mut c_uint, + ) -> c_int; + pub fn X509_free(x: *mut X509); + pub fn X509_REQ_free(x: *mut X509_REQ); + pub fn X509_get_serialNumber(x: *mut X509) -> *mut ASN1_INTEGER; + pub fn X509_gmtime_adj(time: *mut ASN1_TIME, adj: c_long) -> *mut ASN1_TIME; + pub fn X509_new() -> *mut X509; + pub fn X509_set_issuer_name(x: *mut X509, name: *mut X509_NAME) -> c_int; + pub fn X509_set_subject_name(x: *mut X509, name: *mut X509_NAME) -> c_int; + pub fn X509_set_serialNumber(x: *mut X509, sn: *mut ASN1_INTEGER) -> c_int; + pub fn X509_set_version(x: *mut X509, version: c_long) -> c_int; + pub fn X509_set_pubkey(x: *mut X509, pkey: *mut EVP_PKEY) -> c_int; + pub fn X509_sign(x: *mut X509, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> c_int; + pub fn X509_get_pubkey(x: *mut X509) -> *mut EVP_PKEY; + pub fn X509_to_X509_REQ(x: *mut X509, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> *mut X509_REQ; + pub fn X509_verify_cert(ctx: *mut X509_STORE_CTX) -> c_int; + pub fn X509_verify_cert_error_string(n: c_long) -> *const c_char; + pub fn X509_get1_ocsp(x: *mut X509) -> *mut stack_st_OPENSSL_STRING; + pub fn X509_check_issued(issuer: *mut X509, subject: *mut X509) -> c_int; + + pub fn X509_ALGOR_free(x: *mut X509_ALGOR); + + pub fn X509_EXTENSION_free(ext: *mut X509_EXTENSION); + + pub fn X509_NAME_new() -> *mut X509_NAME; + pub fn X509_NAME_free(x: *mut X509_NAME); + pub fn X509_NAME_add_entry_by_txt( + x: *mut X509_NAME, + field: *const c_char, + ty: c_int, + bytes: *const c_uchar, + len: c_int, + loc: c_int, + set: c_int, + ) -> c_int; + pub fn X509_NAME_get_index_by_NID(n: *mut X509_NAME, nid: c_int, last_pos: c_int) -> c_int; + + pub fn X509_NAME_ENTRY_free(x: *mut X509_NAME_ENTRY); + + pub fn ASN1_STRING_free(x: *mut ASN1_STRING); + pub fn ASN1_STRING_length(x: *const ASN1_STRING) -> c_int; + + pub fn ASN1_INTEGER_free(x: *mut ASN1_INTEGER); + + pub fn X509_STORE_new() -> *mut X509_STORE; + pub fn X509_STORE_free(store: *mut X509_STORE); + pub fn X509_STORE_add_cert(store: *mut X509_STORE, x: *mut X509) -> c_int; + pub fn X509_STORE_set_default_paths(store: *mut X509_STORE) -> c_int; + + pub fn X509_STORE_CTX_new() -> *mut X509_STORE_CTX; + pub fn X509_STORE_CTX_cleanup(ctx: *mut X509_STORE_CTX); + pub fn X509_STORE_CTX_init( + ctx: *mut X509_STORE_CTX, + store: *mut X509_STORE, + x509: *mut X509, + chain: *mut stack_st_X509, + ) -> c_int; + pub fn X509_STORE_CTX_free(ctx: *mut X509_STORE_CTX); + pub fn X509_STORE_CTX_get_current_cert(ctx: *mut X509_STORE_CTX) -> *mut X509; + pub fn X509_STORE_CTX_get_error(ctx: *mut X509_STORE_CTX) -> c_int; + pub fn X509_STORE_CTX_set_error(ctx: *mut X509_STORE_CTX, error: c_int); + pub fn X509_STORE_CTX_get_ex_data(ctx: *mut X509_STORE_CTX, idx: c_int) -> *mut c_void; + pub fn X509_STORE_CTX_get_error_depth(ctx: *mut X509_STORE_CTX) -> c_int; + + pub fn X509V3_set_ctx( + ctx: *mut X509V3_CTX, + issuer: *mut X509, + subject: *mut X509, + req: *mut X509_REQ, + crl: *mut X509_CRL, + flags: c_int, + ); + pub fn X509V3_set_nconf(ctx: *mut X509V3_CTX, conf: *mut CONF); + + pub fn X509_REQ_new() -> *mut X509_REQ; + pub fn X509_REQ_set_version(req: *mut X509_REQ, version: c_long) -> c_int; + pub fn X509_REQ_set_subject_name(req: *mut X509_REQ, name: *mut X509_NAME) -> c_int; + pub fn X509_REQ_set_pubkey(req: *mut X509_REQ, pkey: *mut EVP_PKEY) -> c_int; + pub fn X509_REQ_add_extensions(req: *mut X509_REQ, exts: *mut stack_st_X509_EXTENSION) + -> c_int; + pub fn X509_REQ_sign(x: *mut X509_REQ, pkey: *mut EVP_PKEY, md: *const EVP_MD) -> c_int; + + #[cfg(not(ossl101))] + pub fn X509_VERIFY_PARAM_free(param: *mut X509_VERIFY_PARAM); + #[cfg(not(any(ossl101, libressl)))] + pub fn X509_VERIFY_PARAM_set_hostflags(param: *mut X509_VERIFY_PARAM, flags: c_uint); + #[cfg(not(any(ossl101, libressl)))] + pub fn X509_VERIFY_PARAM_set1_host( + param: *mut X509_VERIFY_PARAM, + name: *const c_char, + namelen: size_t, + ) -> c_int; + #[cfg(not(any(ossl101, libressl)))] + pub fn X509_VERIFY_PARAM_set1_ip( + param: *mut X509_VERIFY_PARAM, + ip: *const c_uchar, + iplen: size_t, + ) -> c_int; + + pub fn d2i_DHparams(k: *mut *mut DH, pp: *mut *const c_uchar, length: c_long) -> *mut DH; + pub fn i2d_DHparams(dh: *const DH, pp: *mut *mut c_uchar) -> c_int; + + pub fn d2i_DSAPublicKey(a: *mut *mut DSA, pp: *mut *const c_uchar, length: c_long) -> *mut DSA; + pub fn i2d_DSAPublicKey(a: *const DSA, pp: *mut *mut c_uchar) -> c_int; + pub fn d2i_DSAPrivateKey(a: *mut *mut DSA, pp: *mut *const c_uchar, length: c_long) + -> *mut DSA; + pub fn i2d_DSAPrivateKey(a: *const DSA, pp: *mut *mut c_uchar) -> c_int; + pub fn d2i_DSA_PUBKEY(k: *mut *mut DSA, pp: *mut *const c_uchar, length: c_long) -> *mut DSA; + pub fn i2d_DSA_PUBKEY(a: *mut DSA, pp: *mut *mut c_uchar) -> c_int; + + pub fn d2i_ECPrivateKey( + k: *mut *mut EC_KEY, + pp: *mut *const c_uchar, + length: c_long, + ) -> *mut EC_KEY; + pub fn i2d_ECPrivateKey(ec_key: *mut EC_KEY, pp: *mut *mut c_uchar) -> c_int; + + pub fn d2i_X509(a: *mut *mut X509, pp: *mut *const c_uchar, length: c_long) -> *mut X509; + pub fn d2i_X509_REQ( + a: *mut *mut X509_REQ, + pp: *mut *const c_uchar, + length: c_long, + ) -> *mut X509_REQ; + pub fn i2d_X509_bio(b: *mut BIO, x: *mut X509) -> c_int; + pub fn i2d_X509(x: *mut X509, buf: *mut *mut u8) -> c_int; + pub fn i2d_X509_REQ_bio(b: *mut BIO, x: *mut X509_REQ) -> c_int; + pub fn i2d_X509_REQ(x: *mut X509_REQ, buf: *mut *mut u8) -> c_int; + + pub fn d2i_AutoPrivateKey( + a: *mut *mut EVP_PKEY, + pp: *mut *const c_uchar, + length: c_long, + ) -> *mut EVP_PKEY; + pub fn d2i_PUBKEY(k: *mut *mut EVP_PKEY, buf: *mut *const u8, len: c_long) -> *mut EVP_PKEY; + pub fn i2d_PUBKEY_bio(b: *mut BIO, x: *mut EVP_PKEY) -> c_int; + pub fn i2d_PrivateKey_bio(b: *mut BIO, x: *mut EVP_PKEY) -> c_int; + pub fn i2d_PUBKEY(k: *mut EVP_PKEY, buf: *mut *mut u8) -> c_int; + pub fn i2d_PrivateKey(k: *mut EVP_PKEY, buf: *mut *mut u8) -> c_int; + + pub fn i2d_RSA_PUBKEY(k: *mut RSA, buf: *mut *mut u8) -> c_int; + pub fn d2i_RSA_PUBKEY(k: *mut *mut RSA, buf: *mut *const u8, len: c_long) -> *mut RSA; + pub fn i2d_RSAPublicKey(k: *const RSA, buf: *mut *mut u8) -> c_int; + pub fn d2i_RSAPublicKey(k: *mut *mut RSA, buf: *mut *const u8, len: c_long) -> *mut RSA; + pub fn i2d_RSAPrivateKey(k: *const RSA, buf: *mut *mut u8) -> c_int; + pub fn d2i_RSAPrivateKey(k: *mut *mut RSA, buf: *mut *const u8, len: c_long) -> *mut RSA; + + pub fn i2d_PKCS12_bio(b: *mut BIO, a: *mut PKCS12) -> c_int; + pub fn i2d_PKCS12(a: *mut PKCS12, buf: *mut *mut u8) -> c_int; + pub fn d2i_PKCS12(a: *mut *mut PKCS12, pp: *mut *const u8, length: c_long) -> *mut PKCS12; + pub fn PKCS12_parse( + p12: *mut PKCS12, + pass: *const c_char, + pkey: *mut *mut EVP_PKEY, + cert: *mut *mut X509, + ca: *mut *mut stack_st_X509, + ) -> c_int; + pub fn PKCS12_free(p12: *mut PKCS12); + + pub fn GENERAL_NAME_free(name: *mut GENERAL_NAME); + + pub fn HMAC_Init_ex( + ctx: *mut HMAC_CTX, + key: *const c_void, + len: c_int, + md: *const EVP_MD, + impl_: *mut ENGINE, + ) -> c_int; + pub fn HMAC_Update(ctx: *mut HMAC_CTX, data: *const c_uchar, len: size_t) -> c_int; + pub fn HMAC_Final(ctx: *mut HMAC_CTX, md: *mut c_uchar, len: *mut c_uint) -> c_int; + + #[cfg(not(libressl))] + pub fn CMS_decrypt( + cms: *mut CMS_ContentInfo, + pkey: *mut EVP_PKEY, + cert: *mut X509, + dcont: *mut BIO, + out: *mut BIO, + flags: c_uint, + ) -> c_int; + #[cfg(not(libressl))] + pub fn SMIME_read_CMS(bio: *mut BIO, bcont: *mut *mut BIO) -> *mut CMS_ContentInfo; + #[cfg(not(libressl))] + pub fn CMS_ContentInfo_free(cms: *mut CMS_ContentInfo); + + #[cfg(not(libressl))] + pub fn FIPS_mode_set(onoff: c_int) -> c_int; + #[cfg(not(libressl))] + pub fn FIPS_mode() -> c_int; + + pub fn SSL_CTX_set_cookie_generate_cb( + s: *mut SSL_CTX, + cb: Option< + extern "C" fn(ssl: *mut SSL, cookie: *mut c_uchar, cookie_len: *mut c_uint) -> c_int, + >, + ); + + #[cfg(ossl110)] + pub fn SSL_CTX_set_cookie_verify_cb( + s: *mut SSL_CTX, + cb: Option< + extern "C" fn(ssl: *mut SSL, cookie: *const c_uchar, cookie_len: c_uint) -> c_int, + >, + ); + + #[cfg(not(ossl110))] + pub fn SSL_CTX_set_cookie_verify_cb( + s: *mut SSL_CTX, + cb: Option c_int>, + ); + + pub fn EVP_MD_size(md: *const EVP_MD) -> c_int; + pub fn EVP_get_cipherbyname(name: *const c_char) -> *const EVP_CIPHER; +} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.28/src/ossl10x.rs cargo-0.26.0/vendor/openssl-sys-0.9.28/src/ossl10x.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.28/src/ossl10x.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.28/src/ossl10x.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,981 @@ +use std::sync::{Mutex, MutexGuard}; +use std::sync::{Once, ONCE_INIT}; +use std::mem; +use std::ptr; +use std::process; +use std::io::{self, Write}; + +use libc::{c_char, c_int, c_long, c_uchar, c_uint, c_ulong, c_void, size_t}; +#[cfg(not(ossl101))] +use libc::time_t; + +#[repr(C)] +pub struct stack_st_ASN1_OBJECT { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_X509 { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_X509_NAME { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_X509_ATTRIBUTE { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_X509_EXTENSION { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_GENERAL_NAME { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_void { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_SSL_CIPHER { + pub stack: _STACK, +} + +#[repr(C)] +pub struct stack_st_OPENSSL_STRING { + pub stack: _STACK, +} + +#[repr(C)] +pub struct _STACK { + pub num: c_int, + pub data: *mut *mut c_char, + pub sorted: c_int, + pub num_alloc: c_int, + pub comp: Option c_int>, +} + +#[repr(C)] +pub struct BIO_METHOD { + pub type_: c_int, + pub name: *const c_char, + pub bwrite: Option c_int>, + pub bread: Option c_int>, + pub bputs: Option c_int>, + pub bgets: Option c_int>, + pub ctrl: Option c_long>, + pub create: Option c_int>, + pub destroy: Option c_int>, + pub callback_ctrl: Option c_long>, +} + +#[repr(C)] +pub struct RSA { + pub pad: c_int, + pub version: c_long, + pub meth: *const ::RSA_METHOD, + + pub engine: *mut ::ENGINE, + pub n: *mut ::BIGNUM, + pub e: *mut ::BIGNUM, + pub d: *mut ::BIGNUM, + pub p: *mut ::BIGNUM, + pub q: *mut ::BIGNUM, + pub dmp1: *mut ::BIGNUM, + pub dmq1: *mut ::BIGNUM, + pub iqmp: *mut ::BIGNUM, + + pub ex_data: ::CRYPTO_EX_DATA, + pub references: c_int, + pub flags: c_int, + + pub _method_mod_n: *mut ::BN_MONT_CTX, + pub _method_mod_p: *mut ::BN_MONT_CTX, + pub _method_mod_q: *mut ::BN_MONT_CTX, + + pub bignum_data: *mut c_char, + pub blinding: *mut ::BN_BLINDING, + pub mt_blinding: *mut ::BN_BLINDING, +} + +#[repr(C)] +pub struct DSA { + pub pad: c_int, + pub version: c_long, + pub write_params: c_int, + + pub p: *mut ::BIGNUM, + pub q: *mut ::BIGNUM, + pub g: *mut ::BIGNUM, + pub pub_key: *mut ::BIGNUM, + pub priv_key: *mut ::BIGNUM, + pub kinv: *mut ::BIGNUM, + pub r: *mut ::BIGNUM, + + pub flags: c_int, + pub method_mont_p: *mut ::BN_MONT_CTX, + pub references: c_int, + pub ex_data: ::CRYPTO_EX_DATA, + pub meth: *const ::DSA_METHOD, + pub engine: *mut ::ENGINE, +} + +#[repr(C)] +pub struct ECDSA_SIG { + pub r: *mut BIGNUM, + pub s: *mut BIGNUM +} + +#[repr(C)] +pub struct EVP_PKEY { + pub type_: c_int, + pub save_type: c_int, + pub references: c_int, + pub ameth: *const ::EVP_PKEY_ASN1_METHOD, + pub engine: *mut ::ENGINE, + pub pkey: *mut c_void, + pub save_parameters: c_int, + pub attributes: *mut stack_st_X509_ATTRIBUTE, +} + +#[repr(C)] +pub struct BIO { + pub method: *mut ::BIO_METHOD, + pub callback: Option< + unsafe extern "C" fn(*mut ::BIO, c_int, *const c_char, c_int, c_long, c_long) -> c_long, + >, + pub cb_arg: *mut c_char, + pub init: c_int, + pub shutdown: c_int, + pub flags: c_int, + pub retry_reason: c_int, + pub num: c_int, + pub ptr: *mut c_void, + pub next_bio: *mut ::BIO, + pub prev_bio: *mut ::BIO, + pub references: c_int, + pub num_read: c_ulong, + pub num_write: c_ulong, + pub ex_data: ::CRYPTO_EX_DATA, +} + +#[repr(C)] +pub struct CRYPTO_EX_DATA { + pub sk: *mut ::stack_st_void, + pub dummy: c_int, +} + +#[repr(C)] +pub struct EVP_MD_CTX { + digest: *mut ::EVP_MD, + engine: *mut ::ENGINE, + flags: c_ulong, + md_data: *mut c_void, + pctx: *mut ::EVP_PKEY_CTX, + update: *mut c_void, +} + +#[repr(C)] +pub struct EVP_CIPHER { + pub nid: c_int, + pub block_size: c_int, + pub key_len: c_int, + pub iv_len: c_int, + pub flags: c_ulong, + pub init: Option< + unsafe extern "C" fn(*mut ::EVP_CIPHER_CTX, *const c_uchar, *const c_uchar, c_int) -> c_int, + >, + pub do_cipher: Option< + unsafe extern "C" fn(*mut ::EVP_CIPHER_CTX, *mut c_uchar, *const c_uchar, size_t) -> c_int, + >, + pub cleanup: Option c_int>, + pub ctx_size: c_int, + pub set_asn1_parameters: + Option c_int>, + pub get_asn1_parameters: + Option c_int>, + pub ctrl: + Option c_int>, + pub app_data: *mut c_void, +} + +#[repr(C)] +pub struct HMAC_CTX { + md: *mut ::EVP_MD, + md_ctx: ::EVP_MD_CTX, + i_ctx: ::EVP_MD_CTX, + o_ctx: ::EVP_MD_CTX, + key_length: c_uint, + key: [c_uchar; 128], +} + +#[repr(C)] +pub struct BIGNUM { + pub d: *mut ::BN_ULONG, + pub top: c_int, + pub dmax: c_int, + pub neg: c_int, + pub flags: c_int, +} + +#[repr(C)] +pub struct DH { + pub pad: c_int, + pub version: c_int, + pub p: *mut ::BIGNUM, + pub g: *mut ::BIGNUM, + pub length: c_long, + pub pub_key: *mut ::BIGNUM, + pub priv_key: *mut ::BIGNUM, + pub flags: c_int, + pub method_mont_p: *mut ::BN_MONT_CTX, + pub q: *mut ::BIGNUM, + pub j: *mut ::BIGNUM, + pub seed: *mut c_uchar, + pub seedlen: c_int, + pub counter: *mut ::BIGNUM, + pub references: c_int, + pub ex_data: ::CRYPTO_EX_DATA, + pub meth: *const ::DH_METHOD, + pub engine: *mut ::ENGINE, +} + +#[repr(C)] +pub struct X509 { + pub cert_info: *mut X509_CINF, + pub sig_alg: *mut ::X509_ALGOR, + pub signature: *mut ::ASN1_BIT_STRING, + pub valid: c_int, + pub references: c_int, + pub name: *mut c_char, + pub ex_data: ::CRYPTO_EX_DATA, + pub ex_pathlen: c_long, + pub ex_pcpathlen: c_long, + pub ex_flags: c_ulong, + pub ex_kusage: c_ulong, + pub ex_xkusage: c_ulong, + pub ex_nscert: c_ulong, + skid: *mut c_void, + akid: *mut c_void, + policy_cache: *mut c_void, + crldp: *mut c_void, + altname: *mut c_void, + nc: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_RFC3779"))] + rfc3779_addr: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_RFC3779"))] + rfc3779_asid: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_SHA"))] + sha1_hash: [c_uchar; 20], + aux: *mut c_void, +} + +#[repr(C)] +pub struct X509_CINF { + version: *mut c_void, + serialNumber: *mut c_void, + signature: *mut c_void, + issuer: *mut c_void, + pub validity: *mut X509_VAL, + subject: *mut c_void, + key: *mut c_void, + issuerUID: *mut c_void, + subjectUID: *mut c_void, + pub extensions: *mut stack_st_X509_EXTENSION, + enc: ASN1_ENCODING, +} + +#[repr(C)] +pub struct X509_ALGOR { + pub algorithm: *mut ::ASN1_OBJECT, + parameter: *mut c_void, +} + +#[repr(C)] +pub struct ASN1_ENCODING { + pub enc: *mut c_uchar, + pub len: c_long, + pub modified: c_int, +} + +#[repr(C)] +pub struct X509_VAL { + pub notBefore: *mut ::ASN1_TIME, + pub notAfter: *mut ::ASN1_TIME, +} + +#[repr(C)] +pub struct X509_REQ_INFO { + pub enc: ASN1_ENCODING, + pub version: *mut ::ASN1_INTEGER, + pub subject: *mut ::X509_NAME, + pubkey: *mut c_void, + pub attributes: *mut stack_st_X509_ATTRIBUTE, +} + +#[repr(C)] +pub struct X509_REQ { + pub req_info: *mut X509_REQ_INFO, + sig_alg: *mut c_void, + signature: *mut c_void, + references: c_int, +} + +#[repr(C)] +pub struct SSL { + version: c_int, + type_: c_int, + method: *const ::SSL_METHOD, + rbio: *mut c_void, + wbio: *mut c_void, + bbio: *mut c_void, + rwstate: c_int, + in_handshake: c_int, + handshake_func: Option c_int>, + pub server: c_int, + new_session: c_int, + quiet_session: c_int, + shutdown: c_int, + state: c_int, + rstate: c_int, + init_buf: *mut c_void, + init_msg: *mut c_void, + init_num: c_int, + init_off: c_int, + packet: *mut c_uchar, + packet_length: c_uint, + s2: *mut c_void, + s3: *mut c_void, + d1: *mut c_void, + read_ahead: c_int, + msg_callback: Option< + unsafe extern "C" fn(c_int, c_int, c_int, *const c_void, size_t, *mut SSL, *mut c_void), + >, + msg_callback_arg: *mut c_void, + hit: c_int, + param: *mut c_void, + cipher_list: *mut stack_st_SSL_CIPHER, + cipher_list_by_id: *mut stack_st_SSL_CIPHER, + mac_flags: c_int, + enc_read_ctx: *mut ::EVP_CIPHER_CTX, + read_hash: *mut ::EVP_MD_CTX, + expand: *mut c_void, + enc_write_ctx: *mut ::EVP_CIPHER_CTX, + write_hash: *mut ::EVP_MD_CTX, + compress: *mut c_void, + cert: *mut c_void, + sid_ctx_length: c_uint, + sid_ctx: [c_uchar; ::SSL_MAX_SID_CTX_LENGTH as usize], + session: *mut ::SSL_SESSION, + generate_session_id: ::GEN_SESSION_CB, + verify_mode: c_int, + verify_callback: Option c_int>, + info_callback: Option, + error: c_int, + error_code: c_int, + #[cfg(not(osslconf = "OPENSSL_NO_KRB5"))] + kssl_ctx: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] + psk_client_callback: Option< + unsafe extern "C" fn(*mut SSL, *const c_char, *mut c_char, c_uint, *mut c_uchar, c_uint) + -> c_uint, + >, + #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] + psk_server_callback: + Option c_uint>, + ctx: *mut ::SSL_CTX, + debug: c_int, + verify_result: c_long, + ex_data: ::CRYPTO_EX_DATA, + client_CA: *mut stack_st_X509_NAME, + references: c_int, + options: c_ulong, + mode: c_ulong, + max_cert_list: c_long, + first_packet: c_int, + client_version: c_int, + max_send_fragment: c_uint, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_debug_cb: + Option, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_debug_arg: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_hostname: *mut c_char, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + servername_done: c_int, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_status_type: c_int, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_status_expected: c_int, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_ocsp_ids: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_ocsp_exts: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_ocsp_resp: *mut c_uchar, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_ocsp_resplen: c_int, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_ticket_expected: c_int, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] + tlsext_ecpointformatlist_length: size_t, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] + tlsext_ecpointformatlist: *mut c_uchar, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] + tlsext_ellipticcurvelist_length: size_t, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] + tlsext_ellipticcurvelist: *mut c_uchar, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_opaque_prf_input: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_opaque_prf_input_len: size_t, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_session_ticket: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_session_ticket_ext_cb: ::tls_session_ticket_ext_cb_fn, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tls_session_ticket_ext_cb_arg: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tls_session_secret_cb: ::tls_session_secret_cb_fn, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tls_session_secret_cb_arg: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + initial_ctx: *mut ::SSL_CTX, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] + next_proto_negotiated: *mut c_uchar, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] + next_proto_negotiated_len: c_uchar, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + srtp_profiles: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + srtp_profile: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_heartbeat: c_uint, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_hb_pending: c_uint, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_hb_seq: c_uint, + renegotiate: c_int, + #[cfg(not(osslconf = "OPENSSL_NO_SRP"))] + srp_ctx: ::SRP_CTX, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] + alpn_client_proto_list: *mut c_uchar, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] + alpn_client_proto_list_len: c_uint, +} + +#[repr(C)] +pub struct SSL_CTX { + method: *mut c_void, + cipher_list: *mut c_void, + cipher_list_by_id: *mut c_void, + cert_store: *mut c_void, + sessions: *mut c_void, + session_cache_size: c_ulong, + session_cache_head: *mut c_void, + session_cache_tail: *mut c_void, + session_cache_mode: c_int, + session_timeout: c_long, + new_session_cb: *mut c_void, + remove_session_cb: *mut c_void, + get_session_cb: *mut c_void, + stats: [c_int; 11], + pub references: c_int, + app_verify_callback: *mut c_void, + app_verify_arg: *mut c_void, + default_passwd_callback: *mut c_void, + default_passwd_callback_userdata: *mut c_void, + client_cert_cb: *mut c_void, + app_gen_cookie_cb: *mut c_void, + app_verify_cookie_cb: *mut c_void, + ex_dat: ::CRYPTO_EX_DATA, + rsa_md5: *mut c_void, + md5: *mut c_void, + sha1: *mut c_void, + extra_certs: *mut c_void, + comp_methods: *mut c_void, + info_callback: *mut c_void, + client_CA: *mut c_void, + options: c_ulong, + mode: c_ulong, + max_cert_list: c_long, + cert: *mut c_void, + read_ahead: c_int, + msg_callback: *mut c_void, + msg_callback_arg: *mut c_void, + verify_mode: c_int, + sid_ctx_length: c_uint, + sid_ctx: [c_uchar; 32], + default_verify_callback: *mut c_void, + generate_session_id: *mut c_void, + param: *mut c_void, + quiet_shutdown: c_int, + max_send_fragment: c_uint, + + #[cfg(not(osslconf = "OPENSSL_NO_ENGINE"))] + client_cert_engine: *mut c_void, + + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_servername_callback: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsect_servername_arg: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_tick_key_name: [c_uchar; 16], + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_tick_hmac_key: [c_uchar; 16], + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_tick_aes_key: [c_uchar; 16], + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_ticket_key_cb: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_status_cb: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_status_arg: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_opaque_prf_input_callback: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_opaque_prf_input_callback_arg: *mut c_void, + + #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] + psk_identity_hint: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] + psk_client_callback: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] + psk_server_callback: *mut c_void, + + #[cfg(not(osslconf = "OPENSSL_NO_BUF_FREELISTS"))] + freelist_max_len: c_uint, + #[cfg(not(osslconf = "OPENSSL_NO_BUF_FREELISTS"))] + wbuf_freelist: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_BUF_FREELISTS"))] + rbuf_freelist: *mut c_void, + + #[cfg(not(osslconf = "OPENSSL_NO_SRP"))] + srp_ctx: SRP_CTX, + + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] + next_protos_advertised_cb: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] + next_protos_advertised_cb_arg: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] + next_proto_select_cb: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_NEXTPROTONEG")))] + next_proto_select_cb_arg: *mut c_void, + + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl101))] + srtp_profiles: *mut c_void, + + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] + srtp_profiles: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] + alpn_select_cb: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] + alpn_select_cb_arg: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] + alpn_client_proto_list: *mut c_void, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), ossl102))] + alpn_client_proto_list_len: c_uint, + + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC"), ossl102))] + tlsext_ecpointformatlist_length: size_t, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC"), ossl102))] + tlsext_ecpointformatlist: *mut c_uchar, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC"), ossl102))] + tlsext_ellipticcurvelist_length: size_t, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC"), ossl102))] + tlsext_ellipticcurvelist: *mut c_uchar, +} + +#[repr(C)] +pub struct SSL_SESSION { + ssl_version: c_int, + key_arg_length: c_uint, + key_arg: [c_uchar; SSL_MAX_KEY_ARG_LENGTH as usize], + pub master_key_length: c_int, + pub master_key: [c_uchar; 48], + session_id_length: c_uint, + session_id: [c_uchar; SSL_MAX_SSL_SESSION_ID_LENGTH as usize], + sid_ctx_length: c_uint, + sid_ctx: [c_uchar; SSL_MAX_SID_CTX_LENGTH as usize], + #[cfg(not(osslconf = "OPENSSL_NO_KRB5"))] + krb5_client_princ_len: c_uint, + #[cfg(not(osslconf = "OPENSSL_NO_KRB5"))] + krb5_client_princ: [c_uchar; SSL_MAX_KRB5_PRINCIPAL_LENGTH as usize], + #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] + psk_identity_hint: *mut c_char, + #[cfg(not(osslconf = "OPENSSL_NO_PSK"))] + psk_identity: *mut c_char, + not_resumable: c_int, + sess_cert: *mut c_void, + peer: *mut X509, + verify_result: c_long, + pub references: c_int, + timeout: c_long, + time: c_long, + compress_meth: c_uint, + cipher: *const c_void, + cipher_id: c_ulong, + ciphers: *mut c_void, + ex_data: ::CRYPTO_EX_DATA, + prev: *mut c_void, + next: *mut c_void, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_hostname: *mut c_char, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] + tlsext_ecpointformatlist_length: size_t, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] + tlsext_ecpointformatlist: *mut c_uchar, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] + tlsext_ellipticcurvelist_length: size_t, + #[cfg(all(not(osslconf = "OPENSSL_NO_TLSEXT"), not(osslconf = "OPENSSL_NO_EC")))] + tlsext_ellipticcurvelist: *mut c_uchar, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_tick: *mut c_uchar, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_ticklen: size_t, + #[cfg(not(osslconf = "OPENSSL_NO_TLSEXT"))] + tlsext_tick_lifetime_hint: c_long, + #[cfg(not(osslconf = "OPENSSL_NO_SRP"))] + srp_username: *mut c_char, +} + +#[repr(C)] +pub struct SRP_CTX { + SRP_cb_arg: *mut c_void, + TLS_ext_srp_username_callback: *mut c_void, + SRP_verify_param_callback: *mut c_void, + SRP_give_srp_client_pwd_callback: *mut c_void, + login: *mut c_void, + N: *mut c_void, + g: *mut c_void, + s: *mut c_void, + B: *mut c_void, + A: *mut c_void, + a: *mut c_void, + b: *mut c_void, + v: *mut c_void, + info: *mut c_void, + stringth: c_int, + srp_Mask: c_ulong, +} + +#[repr(C)] +#[cfg(not(ossl101))] +pub struct X509_VERIFY_PARAM { + pub name: *mut c_char, + pub check_time: time_t, + pub inh_flags: c_ulong, + pub flags: c_ulong, + pub purpose: c_int, + pub trust: c_int, + pub depth: c_int, + pub policies: *mut stack_st_ASN1_OBJECT, + pub id: *mut X509_VERIFY_PARAM_ID, +} + +#[cfg(not(ossl101))] +pub enum X509_VERIFY_PARAM_ID {} +pub enum PKCS12 {} + +pub const SSL_CTRL_GET_SESSION_REUSED: c_int = 8; +pub const SSL_CTRL_OPTIONS: c_int = 32; +pub const SSL_CTRL_CLEAR_OPTIONS: c_int = 77; +#[cfg(ossl102)] +pub const SSL_CTRL_SET_ECDH_AUTO: c_int = 94; + +pub const SSL_OP_MICROSOFT_SESS_ID_BUG: c_ulong = 0x00000001; +pub const SSL_OP_NETSCAPE_CHALLENGE_BUG: c_ulong = 0x00000002; +pub const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: c_ulong = 0x00000008; +pub const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: c_ulong = 0x00000020; +pub const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: c_ulong = 0x00000080; +pub const SSL_OP_TLS_D5_BUG: c_ulong = 0x00000100; +pub const SSL_OP_TLS_BLOCK_PADDING_BUG: c_ulong = 0x00000200; +pub const SSL_OP_SINGLE_ECDH_USE: c_ulong = 0x00080000; +pub const SSL_OP_SINGLE_DH_USE: c_ulong = 0x00100000; +pub const SSL_OP_NO_SSLv2: c_ulong = 0x01000000; + +pub const SSL_MAX_SSL_SESSION_ID_LENGTH: c_int = 32; +pub const SSL_MAX_SID_CTX_LENGTH: c_int = 32; +pub const SSL_MAX_KEY_ARG_LENGTH: c_int = 8; +pub const SSL_MAX_MASTER_KEY_LENGTH: c_int = 48; +pub const SSL_MAX_KRB5_PRINCIPAL_LENGTH: c_int = 256; + +pub const SSLEAY_VERSION: c_int = 0; +pub const SSLEAY_CFLAGS: c_int = 2; +pub const SSLEAY_BUILT_ON: c_int = 3; +pub const SSLEAY_PLATFORM: c_int = 4; +pub const SSLEAY_DIR: c_int = 5; + +pub const CRYPTO_LOCK_X509: c_int = 3; +pub const CRYPTO_LOCK_SSL_CTX: c_int = 12; +pub const CRYPTO_LOCK_SSL_SESSION: c_int = 14; + +pub const X509_V_ERR_INVALID_CALL: c_int = 65; +pub const X509_V_ERR_STORE_LOOKUP: c_int = 66; +pub const X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION: c_int = 67; + +static mut MUTEXES: *mut Vec> = 0 as *mut Vec>; +static mut GUARDS: *mut Vec>> = + 0 as *mut Vec>>; + +unsafe extern "C" fn locking_function(mode: c_int, n: c_int, _file: *const c_char, _line: c_int) { + let mutex = &(*MUTEXES)[n as usize]; + + if mode & ::CRYPTO_LOCK != 0 { + (*GUARDS)[n as usize] = Some(mutex.lock().unwrap()); + } else { + if let None = (*GUARDS)[n as usize].take() { + let _ = writeln!( + io::stderr(), + "BUG: rust-openssl lock {} already unlocked, aborting", + n + ); + process::abort(); + } + } +} + +pub fn init() { + static INIT: Once = ONCE_INIT; + + INIT.call_once(|| unsafe { + SSL_library_init(); + SSL_load_error_strings(); + OPENSSL_add_all_algorithms_noconf(); + + let num_locks = ::CRYPTO_num_locks(); + let mut mutexes = Box::new(Vec::new()); + for _ in 0..num_locks { + mutexes.push(Mutex::new(())); + } + MUTEXES = mem::transmute(mutexes); + let guards: Box>>> = + Box::new((0..num_locks).map(|_| None).collect()); + GUARDS = mem::transmute(guards); + + CRYPTO_set_locking_callback(locking_function); + set_id_callback(); + }) +} + +#[cfg(unix)] +fn set_id_callback() { + unsafe extern "C" fn thread_id() -> c_ulong { + ::libc::pthread_self() as c_ulong + } + + unsafe { + CRYPTO_set_id_callback(thread_id); + } +} + +#[cfg(not(unix))] +fn set_id_callback() {} + +// macros + +#[cfg(ossl102)] +pub unsafe fn SSL_CTX_set_ecdh_auto(ctx: *mut SSL_CTX, onoff: c_int) -> c_int { + ::SSL_CTX_ctrl( + ctx, + SSL_CTRL_SET_ECDH_AUTO, + onoff as c_long, + ptr::null_mut(), + ) as c_int +} + +#[cfg(ossl102)] +pub unsafe fn SSL_set_ecdh_auto(ssl: *mut ::SSL, onoff: c_int) -> c_int { + ::SSL_ctrl( + ssl, + SSL_CTRL_SET_ECDH_AUTO, + onoff as c_long, + ptr::null_mut(), + ) as c_int +} + +pub unsafe fn SSL_session_reused(ssl: *mut ::SSL) -> c_int { + ::SSL_ctrl(ssl, SSL_CTRL_GET_SESSION_REUSED, 0, ptr::null_mut()) as c_int +} + +extern "C" { + pub fn BIO_new(type_: *mut BIO_METHOD) -> *mut BIO; + pub fn BIO_s_file() -> *mut BIO_METHOD; + pub fn BIO_s_mem() -> *mut BIO_METHOD; + + pub fn get_rfc2409_prime_768(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc2409_prime_1024(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc3526_prime_1536(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc3526_prime_2048(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc3526_prime_3072(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc3526_prime_4096(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc3526_prime_6144(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn get_rfc3526_prime_8192(bn: *mut BIGNUM) -> *mut BIGNUM; + + pub fn CRYPTO_malloc(num: c_int, file: *const c_char, line: c_int) -> *mut c_void; + pub fn CRYPTO_free(buf: *mut c_void); + pub fn CRYPTO_num_locks() -> c_int; + pub fn CRYPTO_set_locking_callback( + func: unsafe extern "C" fn(mode: c_int, n: c_int, file: *const c_char, line: c_int), + ); + pub fn CRYPTO_set_id_callback(func: unsafe extern "C" fn() -> c_ulong); + + pub fn ERR_load_crypto_strings(); + + pub fn RSA_generate_key( + modsz: c_int, + e: c_ulong, + cb: Option, + cbarg: *mut c_void, + ) -> *mut RSA; + + pub fn OCSP_cert_to_id( + dgst: *const ::EVP_MD, + subject: *mut ::X509, + issuer: *mut ::X509, + ) -> *mut ::OCSP_CERTID; + + pub fn PKCS12_create( + pass: *mut c_char, + friendly_name: *mut c_char, + pkey: *mut EVP_PKEY, + cert: *mut X509, + ca: *mut stack_st_X509, + nid_key: c_int, + nid_cert: c_int, + iter: c_int, + mac_iter: c_int, + keytype: c_int, + ) -> *mut PKCS12; + + pub fn SSL_library_init() -> c_int; + pub fn SSL_load_error_strings(); + pub fn OPENSSL_add_all_algorithms_noconf(); + pub fn HMAC_CTX_init(ctx: *mut ::HMAC_CTX); + pub fn HMAC_CTX_cleanup(ctx: *mut ::HMAC_CTX); + #[cfg(not(osslconf = "OPENSSL_NO_SSL3_METHOD"))] + pub fn SSLv3_method() -> *const ::SSL_METHOD; + pub fn TLSv1_method() -> *const ::SSL_METHOD; + pub fn SSLv23_method() -> *const ::SSL_METHOD; + pub fn TLSv1_1_method() -> *const ::SSL_METHOD; + pub fn TLSv1_2_method() -> *const ::SSL_METHOD; + pub fn DTLSv1_method() -> *const ::SSL_METHOD; + #[cfg(ossl102)] + pub fn DTLSv1_2_method() -> *const ::SSL_METHOD; + pub fn SSL_get_ex_new_index( + argl: c_long, + argp: *mut c_void, + new_func: Option<::CRYPTO_EX_new>, + dup_func: Option<::CRYPTO_EX_dup>, + free_func: Option<::CRYPTO_EX_free>, + ) -> c_int; + pub fn SSL_set_tmp_ecdh_callback( + ssl: *mut ::SSL, + ecdh: unsafe extern "C" fn(ssl: *mut ::SSL, is_export: c_int, keylength: c_int) + -> *mut ::EC_KEY, + ); + pub fn SSL_CIPHER_get_version(cipher: *const ::SSL_CIPHER) -> *mut c_char; + pub fn SSL_CTX_get_ex_new_index( + argl: c_long, + argp: *mut c_void, + new_func: Option<::CRYPTO_EX_new>, + dup_func: Option<::CRYPTO_EX_dup>, + free_func: Option<::CRYPTO_EX_free>, + ) -> c_int; + // FIXME should take an option + pub fn SSL_CTX_set_tmp_ecdh_callback( + ctx: *mut ::SSL_CTX, + ecdh: unsafe extern "C" fn(ssl: *mut ::SSL, is_export: c_int, keylength: c_int) + -> *mut ::EC_KEY, + ); + pub fn SSL_CTX_sess_set_get_cb( + ctx: *mut ::SSL_CTX, + get_session_cb: Option< + unsafe extern "C" fn(*mut ::SSL, *mut c_uchar, c_int, *mut c_int) -> *mut SSL_SESSION, + >, + ); + pub fn X509_get_subject_name(x: *mut ::X509) -> *mut ::X509_NAME; + pub fn X509_get_issuer_name(x: *mut ::X509) -> *mut ::X509_NAME; + pub fn X509_set_notAfter(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; + pub fn X509_set_notBefore(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; + pub fn X509_get_ext_d2i( + x: *mut ::X509, + nid: c_int, + crit: *mut c_int, + idx: *mut c_int, + ) -> *mut c_void; + pub fn X509_NAME_add_entry_by_NID( + x: *mut ::X509_NAME, + field: c_int, + ty: c_int, + bytes: *mut c_uchar, + len: c_int, + loc: c_int, + set: c_int, + ) -> c_int; + #[cfg(not(ossl101))] + pub fn X509_get0_signature( + psig: *mut *mut ::ASN1_BIT_STRING, + palg: *mut *mut ::X509_ALGOR, + x: *const ::X509, + ); + #[cfg(not(ossl101))] + pub fn X509_get_signature_nid(x: *const X509) -> c_int; + #[cfg(not(ossl101))] + pub fn X509_ALGOR_get0( + paobj: *mut *mut ::ASN1_OBJECT, + pptype: *mut c_int, + ppval: *mut *mut c_void, + alg: *mut ::X509_ALGOR, + ); + pub fn X509_NAME_get_entry(n: *mut ::X509_NAME, loc: c_int) -> *mut ::X509_NAME_ENTRY; + pub fn X509_NAME_ENTRY_get_data(ne: *mut ::X509_NAME_ENTRY) -> *mut ::ASN1_STRING; + pub fn X509_STORE_CTX_get_chain(ctx: *mut ::X509_STORE_CTX) -> *mut stack_st_X509; + pub fn X509V3_EXT_nconf_nid( + conf: *mut ::CONF, + ctx: *mut ::X509V3_CTX, + ext_nid: c_int, + value: *mut c_char, + ) -> *mut ::X509_EXTENSION; + pub fn X509V3_EXT_nconf( + conf: *mut ::CONF, + ctx: *mut ::X509V3_CTX, + name: *mut c_char, + value: *mut c_char, + ) -> *mut ::X509_EXTENSION; + pub fn ASN1_STRING_to_UTF8(out: *mut *mut c_uchar, s: *mut ::ASN1_STRING) -> c_int; + pub fn ASN1_STRING_data(x: *mut ::ASN1_STRING) -> *mut c_uchar; + pub fn CRYPTO_add_lock( + pointer: *mut c_int, + amount: c_int, + type_: c_int, + file: *const c_char, + line: c_int, + ) -> c_int; + pub fn EVP_MD_CTX_create() -> *mut EVP_MD_CTX; + pub fn EVP_MD_CTX_destroy(ctx: *mut EVP_MD_CTX); + pub fn EVP_PKEY_bits(key: *mut EVP_PKEY) -> c_int; + + pub fn sk_new_null() -> *mut _STACK; + pub fn sk_num(st: *const _STACK) -> c_int; + pub fn sk_value(st: *const _STACK, n: c_int) -> *mut c_void; + pub fn sk_free(st: *mut _STACK); + pub fn sk_push(st: *mut _STACK, data: *mut c_void) -> c_int; + pub fn sk_pop_free(st: *mut _STACK, free: Option); + pub fn sk_pop(st: *mut _STACK) -> *mut c_void; + + pub fn SSLeay() -> c_ulong; + pub fn SSLeay_version(key: c_int) -> *const c_char; + + #[cfg(ossl102)] + pub fn SSL_extension_supported(ext_type: c_uint) -> c_int; +} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.28/src/ossl110.rs cargo-0.26.0/vendor/openssl-sys-0.9.28/src/ossl110.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.28/src/ossl110.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.28/src/ossl110.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,373 @@ +use libc::{c_char, c_int, c_long, c_uchar, c_uint, c_ulong, c_void, size_t}; +use std::sync::{Once, ONCE_INIT}; +use std::ptr; + +pub enum BIGNUM {} +pub enum BIO {} +pub enum BIO_METHOD {} +pub enum CRYPTO_EX_DATA {} +pub enum DH {} +pub enum DSA {} +pub enum ECDSA_SIG {} +pub enum EVP_CIPHER {} +pub enum EVP_MD_CTX {} +pub enum EVP_PKEY {} +pub enum HMAC_CTX {} +pub enum OPENSSL_STACK {} +pub enum PKCS12 {} +pub enum RSA {} +pub enum SSL {} +pub enum SSL_CTX {} +pub enum SSL_SESSION {} +pub enum stack_st_ASN1_OBJECT {} +pub enum stack_st_GENERAL_NAME {} +pub enum stack_st_OPENSSL_STRING {} +pub enum stack_st_void {} +pub enum stack_st_X509 {} +pub enum stack_st_X509_NAME {} +pub enum stack_st_X509_ATTRIBUTE {} +pub enum stack_st_X509_EXTENSION {} +pub enum stack_st_SSL_CIPHER {} +pub enum OPENSSL_INIT_SETTINGS {} +pub enum X509 {} +pub enum X509_ALGOR {} +pub enum X509_VERIFY_PARAM {} +pub enum X509_REQ {} + +pub const SSL_CTRL_SET_MIN_PROTO_VERSION: c_int = 123; +pub const SSL_CTRL_SET_MAX_PROTO_VERSION: c_int = 124; +pub const SSL_CTRL_GET_MIN_PROTO_VERSION: c_int = 130; +pub const SSL_CTRL_GET_MAX_PROTO_VERSION: c_int = 131; + +pub const SSL_OP_MICROSOFT_SESS_ID_BUG: c_ulong = 0x00000000; +pub const SSL_OP_NETSCAPE_CHALLENGE_BUG: c_ulong = 0x00000000; +pub const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: c_ulong = 0x00000000; +pub const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: c_ulong = 0x00000000; +pub const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: c_ulong = 0x00000000; +pub const SSL_OP_TLS_D5_BUG: c_ulong = 0x00000000; +pub const SSL_OP_TLS_BLOCK_PADDING_BUG: c_ulong = 0x00000000; +pub const SSL_OP_SINGLE_ECDH_USE: c_ulong = 0x00000000; +pub const SSL_OP_SINGLE_DH_USE: c_ulong = 0x00000000; +pub const SSL_OP_NO_SSLv2: c_ulong = 0x00000000; + +pub const OPENSSL_VERSION: c_int = 0; +pub const OPENSSL_CFLAGS: c_int = 1; +pub const OPENSSL_BUILT_ON: c_int = 2; +pub const OPENSSL_PLATFORM: c_int = 3; +pub const OPENSSL_DIR: c_int = 4; + +pub const CRYPTO_EX_INDEX_SSL: c_int = 0; +pub const CRYPTO_EX_INDEX_SSL_CTX: c_int = 1; + +pub const OPENSSL_INIT_LOAD_SSL_STRINGS: u64 = 0x00200000; + +pub const X509_V_ERR_DANE_NO_MATCH: c_int = 65; +pub const X509_V_ERR_EE_KEY_TOO_SMALL: c_int = 66; +pub const X509_V_ERR_CA_KEY_TOO_SMALL: c_int = 67; +pub const X509_V_ERR_CA_MD_TOO_WEAK: c_int = 68; +pub const X509_V_ERR_INVALID_CALL: c_int = 69; +pub const X509_V_ERR_STORE_LOOKUP: c_int = 70; +pub const X509_V_ERR_NO_VALID_SCTS: c_int = 71; + +pub const X509_CHECK_FLAG_NEVER_CHECK_SUBJECT: c_uint = 0x20; + +pub fn init() { + // explicitly initialize to work around https://github.com/openssl/openssl/issues/3505 + static INIT: Once = ONCE_INIT; + + INIT.call_once(|| unsafe { + OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, ptr::null_mut()); + }) +} + +pub unsafe fn SSL_CTX_set_min_proto_version(ctx: *mut ::SSL_CTX, version: c_int) -> c_int { + ::SSL_CTX_ctrl( + ctx, + SSL_CTRL_SET_MIN_PROTO_VERSION, + version as c_long, + ptr::null_mut(), + ) as c_int +} + +pub unsafe fn SSL_CTX_set_max_proto_version(ctx: *mut ::SSL_CTX, version: c_int) -> c_int { + ::SSL_CTX_ctrl( + ctx, + SSL_CTRL_SET_MAX_PROTO_VERSION, + version as c_long, + ptr::null_mut(), + ) as c_int +} + +pub unsafe fn SSL_CTX_get_min_proto_version(ctx: *mut ::SSL_CTX) -> c_int { + ::SSL_CTX_ctrl(ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, ptr::null_mut()) as c_int +} + +pub unsafe fn SSL_CTX_get_max_proto_version(ctx: *mut ::SSL_CTX) -> c_int { + ::SSL_CTX_ctrl(ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, ptr::null_mut()) as c_int +} + +pub unsafe fn SSL_set_min_proto_version(s: *mut ::SSL, version: c_int) -> c_int { + ::SSL_ctrl( + s, + SSL_CTRL_SET_MIN_PROTO_VERSION, + version as c_long, + ptr::null_mut(), + ) as c_int +} + +pub unsafe fn SSL_set_max_proto_version(s: *mut ::SSL, version: c_int) -> c_int { + ::SSL_ctrl( + s, + SSL_CTRL_SET_MAX_PROTO_VERSION, + version as c_long, + ptr::null_mut(), + ) as c_int +} + +pub unsafe fn SSL_get_min_proto_version(s: *mut ::SSL) -> c_int { + ::SSL_ctrl(s, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, ptr::null_mut()) as c_int +} + +pub unsafe fn SSL_get_max_proto_version(s: *mut ::SSL) -> c_int { + ::SSL_ctrl(s, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, ptr::null_mut()) as c_int +} + +extern "C" { + pub fn BIO_new(type_: *const BIO_METHOD) -> *mut BIO; + pub fn BIO_s_file() -> *const BIO_METHOD; + pub fn BIO_s_mem() -> *const BIO_METHOD; + + pub fn BN_get_rfc2409_prime_768(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn BN_get_rfc2409_prime_1024(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn BN_get_rfc3526_prime_1536(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn BN_get_rfc3526_prime_2048(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn BN_get_rfc3526_prime_3072(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn BN_get_rfc3526_prime_4096(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn BN_get_rfc3526_prime_6144(bn: *mut BIGNUM) -> *mut BIGNUM; + pub fn BN_get_rfc3526_prime_8192(bn: *mut BIGNUM) -> *mut BIGNUM; + + pub fn CRYPTO_malloc(num: size_t, file: *const c_char, line: c_int) -> *mut c_void; + pub fn CRYPTO_free(buf: *mut c_void, file: *const c_char, line: c_int); + + pub fn EVP_chacha20() -> *const ::EVP_CIPHER; + pub fn EVP_chacha20_poly1305() -> *const ::EVP_CIPHER; + + pub fn HMAC_CTX_new() -> *mut HMAC_CTX; + pub fn HMAC_CTX_free(ctx: *mut HMAC_CTX); + + pub fn OCSP_cert_to_id( + dgst: *const ::EVP_MD, + subject: *const ::X509, + issuer: *const ::X509, + ) -> *mut ::OCSP_CERTID; + + pub fn TLS_method() -> *const ::SSL_METHOD; + pub fn DTLS_method() -> *const ::SSL_METHOD; + pub fn SSL_CIPHER_get_version(cipher: *const ::SSL_CIPHER) -> *const c_char; + pub fn X509_get_subject_name(x: *const ::X509) -> *mut ::X509_NAME; + pub fn X509_get_issuer_name(x: *const ::X509) -> *mut ::X509_NAME; + pub fn X509_set1_notAfter(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; + pub fn X509_set1_notBefore(x: *mut ::X509, tm: *const ::ASN1_TIME) -> c_int; + pub fn X509_get_ext_d2i( + x: *const ::X509, + nid: c_int, + crit: *mut c_int, + idx: *mut c_int, + ) -> *mut c_void; + pub fn X509_NAME_add_entry_by_NID( + x: *mut ::X509_NAME, + field: c_int, + ty: c_int, + bytes: *const c_uchar, + len: c_int, + loc: c_int, + set: c_int, + ) -> c_int; + pub fn X509_get_signature_nid(x: *const X509) -> c_int; + pub fn X509_ALGOR_get0( + paobj: *mut *const ::ASN1_OBJECT, + pptype: *mut c_int, + ppval: *mut *const c_void, + alg: *const ::X509_ALGOR, + ); + pub fn X509_NAME_get_entry(n: *const ::X509_NAME, loc: c_int) -> *mut ::X509_NAME_ENTRY; + pub fn X509_NAME_ENTRY_get_data(ne: *const ::X509_NAME_ENTRY) -> *mut ::ASN1_STRING; + pub fn X509V3_EXT_nconf_nid( + conf: *mut ::CONF, + ctx: *mut ::X509V3_CTX, + ext_nid: c_int, + value: *const c_char, + ) -> *mut ::X509_EXTENSION; + pub fn X509V3_EXT_nconf( + conf: *mut ::CONF, + ctx: *mut ::X509V3_CTX, + name: *const c_char, + value: *const c_char, + ) -> *mut ::X509_EXTENSION; + pub fn ASN1_STRING_to_UTF8(out: *mut *mut c_uchar, s: *const ::ASN1_STRING) -> c_int; + pub fn BN_is_negative(b: *const ::BIGNUM) -> c_int; + pub fn EVP_CIPHER_key_length(cipher: *const EVP_CIPHER) -> c_int; + pub fn EVP_CIPHER_block_size(cipher: *const EVP_CIPHER) -> c_int; + pub fn EVP_CIPHER_iv_length(cipher: *const EVP_CIPHER) -> c_int; + pub fn EVP_PBE_scrypt( + pass: *const c_char, + passlen: size_t, + salt: *const c_uchar, + saltlen: size_t, + N: u64, + r: u64, + p: u64, + maxmem: u64, + key: *mut c_uchar, + keylen: size_t, + ) -> c_int; + pub fn DSA_get0_pqg( + d: *const ::DSA, + p: *mut *const ::BIGNUM, + q: *mut *const ::BIGNUM, + q: *mut *const ::BIGNUM, + ); + pub fn DSA_get0_key( + d: *const ::DSA, + pub_key: *mut *const ::BIGNUM, + priv_key: *mut *const ::BIGNUM, + ); + pub fn RSA_get0_key( + r: *const ::RSA, + n: *mut *const ::BIGNUM, + e: *mut *const ::BIGNUM, + d: *mut *const ::BIGNUM, + ); + pub fn RSA_get0_factors(r: *const ::RSA, p: *mut *const ::BIGNUM, q: *mut *const ::BIGNUM); + pub fn RSA_get0_crt_params( + r: *const ::RSA, + dmp1: *mut *const ::BIGNUM, + dmq1: *mut *const ::BIGNUM, + iqmp: *mut *const ::BIGNUM, + ); + pub fn RSA_set0_key( + r: *mut ::RSA, + n: *mut ::BIGNUM, + e: *mut ::BIGNUM, + d: *mut ::BIGNUM, + ) -> c_int; + pub fn RSA_set0_factors(r: *mut ::RSA, p: *mut ::BIGNUM, q: *mut ::BIGNUM) -> c_int; + pub fn RSA_set0_crt_params( + r: *mut ::RSA, + dmp1: *mut ::BIGNUM, + dmq1: *mut ::BIGNUM, + iqmp: *mut ::BIGNUM, + ) -> c_int; + pub fn ASN1_STRING_get0_data(x: *const ::ASN1_STRING) -> *const c_uchar; + pub fn OPENSSL_sk_num(stack: *const ::OPENSSL_STACK) -> c_int; + pub fn OPENSSL_sk_value(stack: *const ::OPENSSL_STACK, idx: c_int) -> *mut c_void; + pub fn SSL_CTX_get_options(ctx: *const ::SSL_CTX) -> c_ulong; + pub fn SSL_CTX_set_options(ctx: *mut ::SSL_CTX, op: c_ulong) -> c_ulong; + pub fn SSL_CTX_clear_options(ctx: *mut ::SSL_CTX, op: c_ulong) -> c_ulong; + pub fn SSL_CTX_sess_set_get_cb( + ctx: *mut ::SSL_CTX, + get_session_cb: Option< + unsafe extern "C" fn(*mut ::SSL, *const c_uchar, c_int, *mut c_int) -> *mut SSL_SESSION, + >, + ); + pub fn SSL_get_client_random(ssl: *const SSL, out: *mut c_uchar, len: size_t) -> size_t; + pub fn SSL_get_server_random(ssl: *const SSL, out: *mut c_uchar, len: size_t) -> size_t; + pub fn X509_getm_notAfter(x: *const ::X509) -> *mut ::ASN1_TIME; + pub fn X509_getm_notBefore(x: *const ::X509) -> *mut ::ASN1_TIME; + pub fn X509_get0_signature( + psig: *mut *const ::ASN1_BIT_STRING, + palg: *mut *const ::X509_ALGOR, + x: *const ::X509, + ); + pub fn DH_set0_pqg( + dh: *mut ::DH, + p: *mut ::BIGNUM, + q: *mut ::BIGNUM, + g: *mut ::BIGNUM, + ) -> c_int; + pub fn BIO_set_init(a: *mut ::BIO, init: c_int); + pub fn BIO_set_data(a: *mut ::BIO, data: *mut c_void); + pub fn BIO_get_data(a: *mut ::BIO) -> *mut c_void; + pub fn BIO_meth_new(type_: c_int, name: *const c_char) -> *mut ::BIO_METHOD; + pub fn BIO_meth_free(biom: *mut ::BIO_METHOD); + // FIXME should wrap in Option + pub fn BIO_meth_set_write( + biom: *mut ::BIO_METHOD, + write: unsafe extern "C" fn(*mut ::BIO, *const c_char, c_int) -> c_int, + ) -> c_int; + pub fn BIO_meth_set_read( + biom: *mut ::BIO_METHOD, + read: unsafe extern "C" fn(*mut ::BIO, *mut c_char, c_int) -> c_int, + ) -> c_int; + pub fn BIO_meth_set_puts( + biom: *mut ::BIO_METHOD, + read: unsafe extern "C" fn(*mut ::BIO, *const c_char) -> c_int, + ) -> c_int; + pub fn BIO_meth_set_ctrl( + biom: *mut ::BIO_METHOD, + read: unsafe extern "C" fn(*mut ::BIO, c_int, c_long, *mut c_void) -> c_long, + ) -> c_int; + pub fn BIO_meth_set_create( + biom: *mut ::BIO_METHOD, + create: unsafe extern "C" fn(*mut ::BIO) -> c_int, + ) -> c_int; + pub fn BIO_meth_set_destroy( + biom: *mut ::BIO_METHOD, + destroy: unsafe extern "C" fn(*mut ::BIO) -> c_int, + ) -> c_int; + pub fn CRYPTO_get_ex_new_index( + class_index: c_int, + argl: c_long, + argp: *mut c_void, + new_func: Option<::CRYPTO_EX_new>, + dup_func: Option<::CRYPTO_EX_dup>, + free_func: Option<::CRYPTO_EX_free>, + ) -> c_int; + pub fn X509_up_ref(x: *mut X509) -> c_int; + pub fn SSL_CTX_up_ref(x: *mut SSL_CTX) -> c_int; + pub fn SSL_session_reused(ssl: *mut SSL) -> c_int; + pub fn SSL_SESSION_get_master_key( + session: *const SSL_SESSION, + out: *mut c_uchar, + outlen: size_t, + ) -> size_t; + pub fn SSL_SESSION_up_ref(ses: *mut SSL_SESSION) -> c_int; + pub fn X509_get0_extensions(req: *const ::X509) -> *const stack_st_X509_EXTENSION; + pub fn X509_STORE_CTX_get0_chain(ctx: *mut ::X509_STORE_CTX) -> *mut stack_st_X509; + pub fn EVP_MD_CTX_new() -> *mut EVP_MD_CTX; + pub fn EVP_MD_CTX_free(ctx: *mut EVP_MD_CTX); + pub fn EVP_PKEY_bits(key: *const EVP_PKEY) -> c_int; + + pub fn OpenSSL_version_num() -> c_ulong; + pub fn OpenSSL_version(key: c_int) -> *const c_char; + pub fn OPENSSL_init_ssl(opts: u64, settings: *const OPENSSL_INIT_SETTINGS) -> c_int; + pub fn OPENSSL_sk_new_null() -> *mut ::OPENSSL_STACK; + pub fn OPENSSL_sk_free(st: *mut ::OPENSSL_STACK); + pub fn OPENSSL_sk_pop_free( + st: *mut ::OPENSSL_STACK, + free: Option, + ); + pub fn OPENSSL_sk_push(st: *mut ::OPENSSL_STACK, data: *const c_void) -> c_int; + pub fn OPENSSL_sk_pop(st: *mut ::OPENSSL_STACK) -> *mut c_void; + + pub fn PKCS12_create( + pass: *const c_char, + friendly_name: *const c_char, + pkey: *mut EVP_PKEY, + cert: *mut X509, + ca: *mut stack_st_X509, + nid_key: c_int, + nid_cert: c_int, + iter: c_int, + mac_iter: c_int, + keytype: c_int, + ) -> *mut PKCS12; + pub fn X509_REQ_get_version(req: *const X509_REQ) -> c_long; + pub fn X509_REQ_get_subject_name(req: *const X509_REQ) -> *mut ::X509_NAME; + pub fn SSL_extension_supported(ext_type: c_uint) -> c_int; + pub fn ECDSA_SIG_get0(sig: *const ECDSA_SIG, pr: *mut *const BIGNUM, ps: *mut *const BIGNUM); + pub fn ECDSA_SIG_set0(sig: *mut ECDSA_SIG, pr: *mut BIGNUM, ps: *mut BIGNUM) -> c_int; + + pub fn SSL_CIPHER_get_cipher_nid(c: *const ::SSL_CIPHER) -> c_int; + pub fn SSL_CIPHER_get_digest_nid(c: *const ::SSL_CIPHER) -> c_int; +} diff -Nru cargo-0.25.0/vendor/openssl-sys-0.9.28/src/ossl111.rs cargo-0.26.0/vendor/openssl-sys-0.9.28/src/ossl111.rs --- cargo-0.25.0/vendor/openssl-sys-0.9.28/src/ossl111.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/openssl-sys-0.9.28/src/ossl111.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,84 @@ +use libc::{c_char, c_uchar, c_int, c_uint, c_ulong, size_t, c_void}; + +pub type SSL_CTX_keylog_cb_func = + Option; + +pub type SSL_custom_ext_add_cb_ex = + Option c_int>; + +pub type SSL_custom_ext_free_cb_ex = + Option; + +pub type SSL_custom_ext_parse_cb_ex = + Option c_int>; + +pub const SSL_COOKIE_LENGTH: c_int = 4096; + +pub const SSL_OP_ENABLE_MIDDLEBOX_COMPAT: c_ulong = 0x00100000; + +pub const TLS1_3_VERSION: c_int = 0x304; + +pub const SSL_EXT_TLS_ONLY: c_uint = 0x0001; +/* This extension is only allowed in DTLS */ +pub const SSL_EXT_DTLS_ONLY: c_uint = 0x0002; +/* Some extensions may be allowed in DTLS but we don't implement them for it */ +pub const SSL_EXT_TLS_IMPLEMENTATION_ONLY: c_uint = 0x0004; +/* Most extensions are not defined for SSLv3 but EXT_TYPE_renegotiate is */ +pub const SSL_EXT_SSL3_ALLOWED: c_uint = 0x0008; +/* Extension is only defined for TLS1.2 and below */ +pub const SSL_EXT_TLS1_2_AND_BELOW_ONLY: c_uint = 0x0010; +/* Extension is only defined for TLS1.3 and above */ +pub const SSL_EXT_TLS1_3_ONLY: c_uint = 0x0020; +/* Ignore this extension during parsing if we are resuming */ +pub const SSL_EXT_IGNORE_ON_RESUMPTION: c_uint = 0x0040; +pub const SSL_EXT_CLIENT_HELLO: c_uint = 0x0080; +/* Really means TLS1.2 or below */ +pub const SSL_EXT_TLS1_2_SERVER_HELLO: c_uint = 0x0100; +pub const SSL_EXT_TLS1_3_SERVER_HELLO: c_uint = 0x0200; +pub const SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS: c_uint = 0x0400; +pub const SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST: c_uint = 0x0800; +pub const SSL_EXT_TLS1_3_CERTIFICATE: c_uint = 0x1000; +pub const SSL_EXT_TLS1_3_NEW_SESSION_TICKET: c_uint = 0x2000; +pub const SSL_EXT_TLS1_3_CERTIFICATE_REQUEST: c_uint = 0x4000; + + +extern "C" { + pub fn SSL_CTX_set_keylog_callback(ctx: *mut ::SSL_CTX, cb: SSL_CTX_keylog_cb_func); + pub fn SSL_CTX_add_custom_ext(ctx: *mut ::SSL_CTX, ext_type: c_uint, context: c_uint, + add_cb: SSL_custom_ext_add_cb_ex, + free_cb: SSL_custom_ext_free_cb_ex, + add_arg: *mut c_void, + parse_cb: SSL_custom_ext_parse_cb_ex, + parse_arg: *mut c_void) -> c_int; + pub fn SSL_stateless(s: *mut ::SSL) -> c_int; + pub fn SSL_CIPHER_get_handshake_digest(cipher: *const ::SSL_CIPHER) -> *const ::EVP_MD; + pub fn SSL_CTX_set_stateless_cookie_generate_cb( + s: *mut ::SSL_CTX, + cb: Option c_int> + ); + pub fn SSL_CTX_set_stateless_cookie_verify_cb( + s: *mut ::SSL_CTX, + cb: Option c_int> + ); +} diff -Nru cargo-0.25.0/vendor/proc-macro2-0.3.6/.cargo-checksum.json cargo-0.26.0/vendor/proc-macro2-0.3.6/.cargo-checksum.json --- cargo-0.25.0/vendor/proc-macro2-0.3.6/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/proc-macro2-0.3.6/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"49b6a521dc81b643e9a51e0d1cf05df46d5a2f3c0280ea72bcb68276ba64a118"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/proc-macro2-0.3.6/Cargo.toml cargo-0.26.0/vendor/proc-macro2-0.3.6/Cargo.toml --- cargo-0.25.0/vendor/proc-macro2-0.3.6/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/proc-macro2-0.3.6/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,33 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "proc-macro2" +version = "0.3.6" +authors = ["Alex Crichton "] +description = "A stable implementation of the upcoming new `proc_macro` API. Comes with an\noption, off by default, to also reimplement itself in terms of the upstream\nunstable API.\n" +homepage = "https://github.com/alexcrichton/proc-macro2" +documentation = "https://docs.rs/proc-macro2" +readme = "README.md" +keywords = ["macros"] +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/proc-macro2" + +[lib] +doctest = false +[dependencies.unicode-xid] +version = "0.1" + +[features] +default = ["proc-macro"] +nightly = ["proc-macro"] +proc-macro = [] diff -Nru cargo-0.25.0/vendor/proc-macro2-0.3.6/LICENSE-APACHE cargo-0.26.0/vendor/proc-macro2-0.3.6/LICENSE-APACHE --- cargo-0.25.0/vendor/proc-macro2-0.3.6/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/proc-macro2-0.3.6/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/proc-macro2-0.3.6/LICENSE-MIT cargo-0.26.0/vendor/proc-macro2-0.3.6/LICENSE-MIT --- cargo-0.25.0/vendor/proc-macro2-0.3.6/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/proc-macro2-0.3.6/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +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. diff -Nru cargo-0.25.0/vendor/proc-macro2-0.3.6/README.md cargo-0.26.0/vendor/proc-macro2-0.3.6/README.md --- cargo-0.25.0/vendor/proc-macro2-0.3.6/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/proc-macro2-0.3.6/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,98 @@ +# proc-macro2 + +[![Build Status](https://api.travis-ci.org/alexcrichton/proc-macro2.svg?branch=master)](https://travis-ci.org/alexcrichton/proc-macro2) +[![Latest Version](https://img.shields.io/crates/v/proc-macro2.svg)](https://crates.io/crates/proc-macro2) +[![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/proc-macro2) + +A small shim over the `proc_macro` crate in the compiler intended to multiplex +the current stable interface (as of 2017-07-05) and the [upcoming richer +interface][upcoming]. + +[upcoming]: https://github.com/rust-lang/rust/pull/40939 + +The upcoming support has features like: + +* Span information on tokens +* No need to go in/out through strings +* Structured input/output + +The hope is that libraries ported to `proc_macro2` will be trivial to port to +the real `proc_macro` crate once the support on nightly is stabilize. + +## Usage + +This crate by default compiles on the stable version of the compiler. It only +uses the stable surface area of the `proc_macro` crate upstream in the compiler +itself. Usage is done via: + +```toml +[dependencies] +proc-macro2 = "0.3" +``` + +followed by + +```rust +extern crate proc_macro; +extern crate proc_macro2; + +#[proc_macro_derive(MyDerive)] +pub fn my_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { + let input: proc_macro2::TokenStream = input.into(); + + let output: proc_macro2::TokenStream = { + /* transform input */ + }; + + output.into() +} +``` + +If you'd like you can enable the `nightly` feature in this crate. This will +cause it to compile against the **unstable and nightly-only** features of the +`proc_macro` crate. This in turn requires a nightly compiler. This should help +preserve span information, however, coming in from the compiler itself. + +You can enable this feature via: + +```toml +[dependencies] +proc-macro2 = { version = "0.3", features = ["nightly"] } +``` + + +## Unstable Features + +`proc-macro2` supports exporting some methods from `proc_macro` which are +currently highly unstable, and may not be stabilized in the first pass of +`proc_macro` stabilizations. These features are not exported by default. Minor +versions of `proc-macro2` may make breaking changes to them at any time. + +To enable these features, the `procmacro2_semver_exempt` config flag must be +passed to rustc. + +``` +RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build +``` + +Note that this must not only be done for your crate, but for any crate that +depends on your crate. This infectious nature is intentional, as it serves as a +reminder that you are outside of the normal semver guarantees. + + +# License + +This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/proc-macro2-0.3.6/src/lib.rs cargo-0.26.0/vendor/proc-macro2-0.3.6/src/lib.rs --- cargo-0.25.0/vendor/proc-macro2-0.3.6/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/proc-macro2-0.3.6/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,590 @@ +//! A "shim crate" intended to multiplex the [`proc_macro`] API on to stable +//! Rust. +//! +//! Procedural macros in Rust operate over the upstream +//! [`proc_macro::TokenStream`][ts] type. This type currently is quite +//! conservative and exposed no internal implementation details. Nightly +//! compilers, however, contain a much richer interface. This richer interface +//! allows fine-grained inspection of the token stream which avoids +//! stringification/re-lexing and also preserves span information. +//! +//! The upcoming APIs added to [`proc_macro`] upstream are the foundation for +//! productive procedural macros in the ecosystem. To help prepare the ecosystem +//! for using them this crate serves to both compile on stable and nightly and +//! mirrors the API-to-be. The intention is that procedural macros which switch +//! to use this crate will be trivially able to switch to the upstream +//! `proc_macro` crate once its API stabilizes. +//! +//! In the meantime this crate also has a `nightly` Cargo feature which +//! enables it to reimplement itself with the unstable API of [`proc_macro`]. +//! This'll allow immediate usage of the beneficial upstream API, particularly +//! around preserving span information. +//! +//! [`proc_macro`]: https://doc.rust-lang.org/proc_macro/ +//! [ts]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html + +// Proc-macro2 types in rustdoc of other crates get linked to here. +#![doc(html_root_url = "https://docs.rs/proc-macro2/0.3.6")] +#![cfg_attr(feature = "nightly", feature(proc_macro))] + +#[cfg(feature = "proc-macro")] +extern crate proc_macro; + +#[cfg(not(feature = "nightly"))] +extern crate unicode_xid; + +use std::fmt; +use std::iter::FromIterator; +use std::marker; +use std::rc::Rc; +use std::str::FromStr; + +#[macro_use] +#[cfg(not(feature = "nightly"))] +mod strnom; + +#[path = "stable.rs"] +#[cfg(not(feature = "nightly"))] +mod imp; +#[path = "unstable.rs"] +#[cfg(feature = "nightly")] +mod imp; + +#[derive(Clone)] +pub struct TokenStream { + inner: imp::TokenStream, + _marker: marker::PhantomData>, +} + +pub struct LexError { + inner: imp::LexError, + _marker: marker::PhantomData>, +} + +impl TokenStream { + fn _new(inner: imp::TokenStream) -> TokenStream { + TokenStream { + inner: inner, + _marker: marker::PhantomData, + } + } + + pub fn empty() -> TokenStream { + TokenStream::_new(imp::TokenStream::empty()) + } + + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } +} + +impl FromStr for TokenStream { + type Err = LexError; + + fn from_str(src: &str) -> Result { + let e = src.parse().map_err(|e| LexError { + inner: e, + _marker: marker::PhantomData, + })?; + Ok(TokenStream::_new(e)) + } +} + +#[cfg(feature = "proc-macro")] +impl From for TokenStream { + fn from(inner: proc_macro::TokenStream) -> TokenStream { + TokenStream::_new(inner.into()) + } +} + +#[cfg(feature = "proc-macro")] +impl From for proc_macro::TokenStream { + fn from(inner: TokenStream) -> proc_macro::TokenStream { + inner.inner.into() + } +} + +impl FromIterator for TokenStream { + fn from_iter>(streams: I) -> Self { + TokenStream::_new(streams.into_iter().collect()) + } +} + +impl fmt::Display for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} + +impl fmt::Debug for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} + +impl fmt::Debug for LexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} + +// Returned by reference, so we can't easily wrap it. +#[cfg(procmacro2_semver_exempt)] +pub use imp::FileName; + +#[cfg(procmacro2_semver_exempt)] +#[derive(Clone, PartialEq, Eq)] +pub struct SourceFile(imp::SourceFile); + +#[cfg(procmacro2_semver_exempt)] +impl SourceFile { + /// Get the path to this source file as a string. + pub fn path(&self) -> &FileName { + self.0.path() + } + + pub fn is_real(&self) -> bool { + self.0.is_real() + } +} + +#[cfg(procmacro2_semver_exempt)] +impl AsRef for SourceFile { + fn as_ref(&self) -> &FileName { + self.0.path() + } +} + +#[cfg(procmacro2_semver_exempt)] +impl fmt::Debug for SourceFile { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.fmt(f) + } +} + +#[cfg(procmacro2_semver_exempt)] +pub struct LineColumn { + pub line: usize, + pub column: usize, +} + +#[derive(Copy, Clone)] +pub struct Span { + inner: imp::Span, + _marker: marker::PhantomData>, +} + +impl Span { + fn _new(inner: imp::Span) -> Span { + Span { + inner: inner, + _marker: marker::PhantomData, + } + } + + pub fn call_site() -> Span { + Span::_new(imp::Span::call_site()) + } + + #[cfg(procmacro2_semver_exempt)] + pub fn def_site() -> Span { + Span::_new(imp::Span::def_site()) + } + + /// Creates a new span with the same line/column information as `self` but + /// that resolves symbols as though it were at `other`. + #[cfg(procmacro2_semver_exempt)] + pub fn resolved_at(&self, other: Span) -> Span { + Span::_new(self.inner.resolved_at(other.inner)) + } + + /// Creates a new span with the same name resolution behavior as `self` but + /// with the line/column information of `other`. + #[cfg(procmacro2_semver_exempt)] + pub fn located_at(&self, other: Span) -> Span { + Span::_new(self.inner.located_at(other.inner)) + } + + /// This method is only available when the `"nightly"` feature is enabled. + #[cfg(all(feature = "nightly", feature = "proc-macro"))] + pub fn unstable(self) -> proc_macro::Span { + self.inner.unstable() + } + + #[cfg(procmacro2_semver_exempt)] + pub fn source_file(&self) -> SourceFile { + SourceFile(self.inner.source_file()) + } + + #[cfg(procmacro2_semver_exempt)] + pub fn start(&self) -> LineColumn { + let imp::LineColumn { line, column } = self.inner.start(); + LineColumn { + line: line, + column: column, + } + } + + #[cfg(procmacro2_semver_exempt)] + pub fn end(&self) -> LineColumn { + let imp::LineColumn { line, column } = self.inner.end(); + LineColumn { + line: line, + column: column, + } + } + + #[cfg(procmacro2_semver_exempt)] + pub fn join(&self, other: Span) -> Option { + self.inner.join(other.inner).map(Span::_new) + } + + #[cfg(procmacro2_semver_exempt)] + pub fn eq(&self, other: &Span) -> bool { + self.inner.eq(&other.inner) + } +} + +impl fmt::Debug for Span { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} + +#[derive(Clone, Debug)] +pub enum TokenTree { + Group(Group), + Term(Term), + Op(Op), + Literal(Literal), +} + +impl TokenTree { + pub fn span(&self) -> Span { + match *self { + TokenTree::Group(ref t) => t.span(), + TokenTree::Term(ref t) => t.span(), + TokenTree::Op(ref t) => t.span(), + TokenTree::Literal(ref t) => t.span(), + } + } + + pub fn set_span(&mut self, span: Span) { + match *self { + TokenTree::Group(ref mut t) => t.set_span(span), + TokenTree::Term(ref mut t) => t.set_span(span), + TokenTree::Op(ref mut t) => t.set_span(span), + TokenTree::Literal(ref mut t) => t.set_span(span), + } + } +} + +impl From for TokenTree { + fn from(g: Group) -> TokenTree { + TokenTree::Group(g) + } +} + +impl From for TokenTree { + fn from(g: Term) -> TokenTree { + TokenTree::Term(g) + } +} + +impl From for TokenTree { + fn from(g: Op) -> TokenTree { + TokenTree::Op(g) + } +} + +impl From for TokenTree { + fn from(g: Literal) -> TokenTree { + TokenTree::Literal(g) + } +} + +impl fmt::Display for TokenTree { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + TokenTree::Group(ref t) => t.fmt(f), + TokenTree::Term(ref t) => t.fmt(f), + TokenTree::Op(ref t) => t.fmt(f), + TokenTree::Literal(ref t) => t.fmt(f), + } + } +} + +#[derive(Clone, Debug)] +pub struct Group { + delimiter: Delimiter, + stream: TokenStream, + span: Span, +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Delimiter { + Parenthesis, + Brace, + Bracket, + None, +} + +impl Group { + pub fn new(delimiter: Delimiter, stream: TokenStream) -> Group { + Group { + delimiter: delimiter, + stream: stream, + span: Span::call_site(), + } + } + + pub fn delimiter(&self) -> Delimiter { + self.delimiter + } + + pub fn stream(&self) -> TokenStream { + self.stream.clone() + } + + pub fn span(&self) -> Span { + self.span + } + + pub fn set_span(&mut self, span: Span) { + self.span = span; + } +} + +impl fmt::Display for Group { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.stream.fmt(f) + } +} + +#[derive(Copy, Clone, Debug)] +pub struct Op { + op: char, + spacing: Spacing, + span: Span, +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Spacing { + Alone, + Joint, +} + +impl Op { + pub fn new(op: char, spacing: Spacing) -> Op { + Op { + op: op, + spacing: spacing, + span: Span::call_site(), + } + } + + pub fn op(&self) -> char { + self.op + } + + pub fn spacing(&self) -> Spacing { + self.spacing + } + + pub fn span(&self) -> Span { + self.span + } + + pub fn set_span(&mut self, span: Span) { + self.span = span; + } +} + +impl fmt::Display for Op { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.op.fmt(f) + } +} + +#[derive(Copy, Clone)] +pub struct Term { + inner: imp::Term, + _marker: marker::PhantomData>, +} + +impl Term { + fn _new(inner: imp::Term) -> Term { + Term { + inner: inner, + _marker: marker::PhantomData, + } + } + + pub fn new(string: &str, span: Span) -> Term { + Term::_new(imp::Term::new(string, span.inner)) + } + + pub fn as_str(&self) -> &str { + self.inner.as_str() + } + + pub fn span(&self) -> Span { + Span::_new(self.inner.span()) + } + + pub fn set_span(&mut self, span: Span) { + self.inner.set_span(span.inner); + } +} + +impl fmt::Display for Term { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.as_str().fmt(f) + } +} + +impl fmt::Debug for Term { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} + +#[derive(Clone)] +pub struct Literal { + inner: imp::Literal, + _marker: marker::PhantomData>, +} + +macro_rules! int_literals { + ($($name:ident => $kind:ident,)*) => ($( + pub fn $name(n: $kind) -> Literal { + Literal::_new(imp::Literal::$name(n)) + } + )*) +} + +impl Literal { + fn _new(inner: imp::Literal) -> Literal { + Literal { + inner: inner, + _marker: marker::PhantomData, + } + } + + int_literals! { + u8_suffixed => u8, + u16_suffixed => u16, + u32_suffixed => u32, + u64_suffixed => u64, + usize_suffixed => usize, + i8_suffixed => i8, + i16_suffixed => i16, + i32_suffixed => i32, + i64_suffixed => i64, + isize_suffixed => isize, + + u8_unsuffixed => u8, + u16_unsuffixed => u16, + u32_unsuffixed => u32, + u64_unsuffixed => u64, + usize_unsuffixed => usize, + i8_unsuffixed => i8, + i16_unsuffixed => i16, + i32_unsuffixed => i32, + i64_unsuffixed => i64, + isize_unsuffixed => isize, + } + + pub fn f64_unsuffixed(f: f64) -> Literal { + assert!(f.is_finite()); + Literal::_new(imp::Literal::f64_unsuffixed(f)) + } + + pub fn f64_suffixed(f: f64) -> Literal { + assert!(f.is_finite()); + Literal::_new(imp::Literal::f64_suffixed(f)) + } + + pub fn f32_unsuffixed(f: f32) -> Literal { + assert!(f.is_finite()); + Literal::_new(imp::Literal::f32_unsuffixed(f)) + } + + pub fn f32_suffixed(f: f32) -> Literal { + assert!(f.is_finite()); + Literal::_new(imp::Literal::f32_suffixed(f)) + } + + pub fn string(string: &str) -> Literal { + Literal::_new(imp::Literal::string(string)) + } + + pub fn character(ch: char) -> Literal { + Literal::_new(imp::Literal::character(ch)) + } + + pub fn byte_string(s: &[u8]) -> Literal { + Literal::_new(imp::Literal::byte_string(s)) + } + + pub fn span(&self) -> Span { + Span::_new(self.inner.span()) + } + + pub fn set_span(&mut self, span: Span) { + self.inner.set_span(span.inner); + } +} + +impl fmt::Debug for Literal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} + +impl fmt::Display for Literal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} + +pub mod token_stream { + use std::fmt; + use std::marker; + use std::rc::Rc; + + pub use TokenStream; + use TokenTree; + use imp; + + pub struct IntoIter { + inner: imp::TokenTreeIter, + _marker: marker::PhantomData>, + } + + impl Iterator for IntoIter { + type Item = TokenTree; + + fn next(&mut self) -> Option { + self.inner.next() + } + } + + impl fmt::Debug for IntoIter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } + } + + impl IntoIterator for TokenStream { + type Item = TokenTree; + type IntoIter = IntoIter; + + fn into_iter(self) -> IntoIter { + IntoIter { + inner: self.inner.into_iter(), + _marker: marker::PhantomData, + } + } + } +} diff -Nru cargo-0.25.0/vendor/proc-macro2-0.3.6/src/stable.rs cargo-0.26.0/vendor/proc-macro2-0.3.6/src/stable.rs --- cargo-0.25.0/vendor/proc-macro2-0.3.6/src/stable.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/proc-macro2-0.3.6/src/stable.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1265 @@ +#![cfg_attr(not(procmacro2_semver_exempt), allow(dead_code))] + +use std::borrow::Borrow; +use std::cell::RefCell; +#[cfg(procmacro2_semver_exempt)] +use std::cmp; +use std::collections::HashMap; +use std::fmt; +use std::iter; +use std::rc::Rc; +use std::str::FromStr; +use std::vec; + +use strnom::{block_comment, skip_whitespace, whitespace, word_break, Cursor, PResult}; +use unicode_xid::UnicodeXID; + +use {Delimiter, Group, Op, Spacing, TokenTree}; + +#[derive(Clone, Debug)] +pub struct TokenStream { + inner: Vec, +} + +#[derive(Debug)] +pub struct LexError; + +impl TokenStream { + pub fn empty() -> TokenStream { + TokenStream { inner: Vec::new() } + } + + pub fn is_empty(&self) -> bool { + self.inner.len() == 0 + } +} + +#[cfg(procmacro2_semver_exempt)] +fn get_cursor(src: &str) -> Cursor { + // Create a dummy file & add it to the codemap + CODEMAP.with(|cm| { + let mut cm = cm.borrow_mut(); + let name = format!("", cm.files.len()); + let span = cm.add_file(&name, src); + Cursor { + rest: src, + off: span.lo, + } + }) +} + +#[cfg(not(procmacro2_semver_exempt))] +fn get_cursor(src: &str) -> Cursor { + Cursor { rest: src } +} + +impl FromStr for TokenStream { + type Err = LexError; + + fn from_str(src: &str) -> Result { + // Create a dummy file & add it to the codemap + let cursor = get_cursor(src); + + match token_stream(cursor) { + Ok((input, output)) => { + if skip_whitespace(input).len() != 0 { + Err(LexError) + } else { + Ok(output.inner) + } + } + Err(LexError) => Err(LexError), + } + } +} + +impl fmt::Display for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut joint = false; + for (i, tt) in self.inner.iter().enumerate() { + if i != 0 && !joint { + write!(f, " ")?; + } + joint = false; + match *tt { + TokenTree::Group(ref tt) => { + let (start, end) = match tt.delimiter() { + Delimiter::Parenthesis => ("(", ")"), + Delimiter::Brace => ("{", "}"), + Delimiter::Bracket => ("[", "]"), + Delimiter::None => ("", ""), + }; + if tt.stream().inner.inner.len() == 0 { + write!(f, "{} {}", start, end)? + } else { + write!(f, "{} {} {}", start, tt.stream(), end)? + } + } + TokenTree::Term(ref tt) => write!(f, "{}", tt.as_str())?, + TokenTree::Op(ref tt) => { + write!(f, "{}", tt.op())?; + match tt.spacing() { + Spacing::Alone => {} + Spacing::Joint => joint = true, + } + } + TokenTree::Literal(ref tt) => write!(f, "{}", tt)?, + } + } + + Ok(()) + } +} + +#[cfg(feature = "proc-macro")] +impl From<::proc_macro::TokenStream> for TokenStream { + fn from(inner: ::proc_macro::TokenStream) -> TokenStream { + inner + .to_string() + .parse() + .expect("compiler token stream parse failed") + } +} + +#[cfg(feature = "proc-macro")] +impl From for ::proc_macro::TokenStream { + fn from(inner: TokenStream) -> ::proc_macro::TokenStream { + inner + .to_string() + .parse() + .expect("failed to parse to compiler tokens") + } +} + +impl From for TokenStream { + fn from(tree: TokenTree) -> TokenStream { + TokenStream { inner: vec![tree] } + } +} + +impl iter::FromIterator for TokenStream { + fn from_iter>(streams: I) -> Self { + let mut v = Vec::new(); + + for token in streams.into_iter() { + v.push(token); + } + + TokenStream { inner: v } + } +} + +pub type TokenTreeIter = vec::IntoIter; + +impl IntoIterator for TokenStream { + type Item = TokenTree; + type IntoIter = TokenTreeIter; + + fn into_iter(self) -> TokenTreeIter { + self.inner.into_iter() + } +} + +#[cfg(procmacro2_semver_exempt)] +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct FileName(String); + +#[cfg(procmacro2_semver_exempt)] +impl fmt::Display for FileName { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.fmt(f) + } +} + +#[cfg(procmacro2_semver_exempt)] +#[derive(Clone, PartialEq, Eq)] +pub struct SourceFile { + name: FileName, +} + +#[cfg(procmacro2_semver_exempt)] +impl SourceFile { + /// Get the path to this source file as a string. + pub fn path(&self) -> &FileName { + &self.name + } + + pub fn is_real(&self) -> bool { + // XXX(nika): Support real files in the future? + false + } +} + +#[cfg(procmacro2_semver_exempt)] +impl AsRef for SourceFile { + fn as_ref(&self) -> &FileName { + self.path() + } +} + +#[cfg(procmacro2_semver_exempt)] +impl fmt::Debug for SourceFile { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("SourceFile") + .field("path", &self.path()) + .field("is_real", &self.is_real()) + .finish() + } +} + +#[cfg(procmacro2_semver_exempt)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct LineColumn { + pub line: usize, + pub column: usize, +} + +#[cfg(procmacro2_semver_exempt)] +thread_local! { + static CODEMAP: RefCell = RefCell::new(Codemap { + // NOTE: We start with a single dummy file which all call_site() and + // def_site() spans reference. + files: vec![FileInfo { + name: "".to_owned(), + span: Span { lo: 0, hi: 0 }, + lines: vec![0], + }], + }); +} + +#[cfg(procmacro2_semver_exempt)] +struct FileInfo { + name: String, + span: Span, + lines: Vec, +} + +#[cfg(procmacro2_semver_exempt)] +impl FileInfo { + fn offset_line_column(&self, offset: usize) -> LineColumn { + assert!(self.span_within(Span { + lo: offset as u32, + hi: offset as u32 + })); + let offset = offset - self.span.lo as usize; + match self.lines.binary_search(&offset) { + Ok(found) => LineColumn { + line: found + 1, + column: 0, + }, + Err(idx) => LineColumn { + line: idx, + column: offset - self.lines[idx - 1], + }, + } + } + + fn span_within(&self, span: Span) -> bool { + span.lo >= self.span.lo && span.hi <= self.span.hi + } +} + +/// Computesthe offsets of each line in the given source string. +#[cfg(procmacro2_semver_exempt)] +fn lines_offsets(s: &str) -> Vec { + let mut lines = vec![0]; + let mut prev = 0; + while let Some(len) = s[prev..].find('\n') { + prev += len + 1; + lines.push(prev); + } + lines +} + +#[cfg(procmacro2_semver_exempt)] +struct Codemap { + files: Vec, +} + +#[cfg(procmacro2_semver_exempt)] +impl Codemap { + fn next_start_pos(&self) -> u32 { + // Add 1 so there's always space between files. + // + // We'll always have at least 1 file, as we initialize our files list + // with a dummy file. + self.files.last().unwrap().span.hi + 1 + } + + fn add_file(&mut self, name: &str, src: &str) -> Span { + let lines = lines_offsets(src); + let lo = self.next_start_pos(); + // XXX(nika): Shouild we bother doing a checked cast or checked add here? + let span = Span { + lo: lo, + hi: lo + (src.len() as u32), + }; + + self.files.push(FileInfo { + name: name.to_owned(), + span: span, + lines: lines, + }); + + span + } + + fn fileinfo(&self, span: Span) -> &FileInfo { + for file in &self.files { + if file.span_within(span) { + return file; + } + } + panic!("Invalid span with no related FileInfo!"); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Span { + #[cfg(procmacro2_semver_exempt)] + lo: u32, + #[cfg(procmacro2_semver_exempt)] + hi: u32, +} + +impl Span { + #[cfg(not(procmacro2_semver_exempt))] + pub fn call_site() -> Span { + Span {} + } + + #[cfg(procmacro2_semver_exempt)] + pub fn call_site() -> Span { + Span { lo: 0, hi: 0 } + } + + pub fn def_site() -> Span { + Span::call_site() + } + + pub fn resolved_at(&self, _other: Span) -> Span { + // Stable spans consist only of line/column information, so + // `resolved_at` and `located_at` only select which span the + // caller wants line/column information from. + *self + } + + pub fn located_at(&self, other: Span) -> Span { + other + } + + #[cfg(procmacro2_semver_exempt)] + pub fn source_file(&self) -> SourceFile { + CODEMAP.with(|cm| { + let cm = cm.borrow(); + let fi = cm.fileinfo(*self); + SourceFile { + name: FileName(fi.name.clone()), + } + }) + } + + #[cfg(procmacro2_semver_exempt)] + pub fn start(&self) -> LineColumn { + CODEMAP.with(|cm| { + let cm = cm.borrow(); + let fi = cm.fileinfo(*self); + fi.offset_line_column(self.lo as usize) + }) + } + + #[cfg(procmacro2_semver_exempt)] + pub fn end(&self) -> LineColumn { + CODEMAP.with(|cm| { + let cm = cm.borrow(); + let fi = cm.fileinfo(*self); + fi.offset_line_column(self.hi as usize) + }) + } + + #[cfg(procmacro2_semver_exempt)] + pub fn join(&self, other: Span) -> Option { + CODEMAP.with(|cm| { + let cm = cm.borrow(); + // If `other` is not within the same FileInfo as us, return None. + if !cm.fileinfo(*self).span_within(other) { + return None; + } + Some(Span { + lo: cmp::min(self.lo, other.lo), + hi: cmp::max(self.hi, other.hi), + }) + }) + } +} + +#[derive(Copy, Clone)] +pub struct Term { + intern: usize, + span: Span, +} + +thread_local!(static SYMBOLS: RefCell = RefCell::new(Interner::new())); + +impl Term { + pub fn new(string: &str, span: Span) -> Term { + validate_term(string); + + Term { + intern: SYMBOLS.with(|s| s.borrow_mut().intern(string)), + span: span, + } + } + + pub fn as_str(&self) -> &str { + SYMBOLS.with(|interner| { + let interner = interner.borrow(); + let s = interner.get(self.intern); + unsafe { &*(s as *const str) } + }) + } + + pub fn span(&self) -> Span { + self.span + } + + pub fn set_span(&mut self, span: Span) { + self.span = span; + } +} + +fn validate_term(string: &str) { + let validate = if string.starts_with('\'') { + &string[1..] + } else if string.starts_with("r#") { + &string[2..] + } else { + string + }; + + if validate.is_empty() { + panic!("Term is not allowed to be empty; use Option"); + } + + if validate.bytes().all(|digit| digit >= b'0' && digit <= b'9') { + panic!("Term cannot be a number; use Literal instead"); + } + + fn xid_ok(string: &str) -> bool { + let mut chars = string.chars(); + let first = chars.next().unwrap(); + if !(UnicodeXID::is_xid_start(first) || first == '_') { + return false; + } + for ch in chars { + if !UnicodeXID::is_xid_continue(ch) { + return false; + } + } + true + } + + if !xid_ok(validate) { + panic!("{:?} is not a valid Term", string); + } +} + +impl fmt::Debug for Term { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_tuple("Term").field(&self.as_str()).finish() + } +} + +struct Interner { + string_to_index: HashMap, + index_to_string: Vec>, +} + +#[derive(Hash, Eq, PartialEq)] +struct MyRc(Rc); + +impl Borrow for MyRc { + fn borrow(&self) -> &str { + &self.0 + } +} + +impl Interner { + fn new() -> Interner { + Interner { + string_to_index: HashMap::new(), + index_to_string: Vec::new(), + } + } + + fn intern(&mut self, s: &str) -> usize { + if let Some(&idx) = self.string_to_index.get(s) { + return idx; + } + let s = Rc::new(s.to_string()); + self.index_to_string.push(s.clone()); + self.string_to_index + .insert(MyRc(s), self.index_to_string.len() - 1); + self.index_to_string.len() - 1 + } + + fn get(&self, idx: usize) -> &str { + &self.index_to_string[idx] + } +} + +#[derive(Clone, Debug)] +pub struct Literal { + text: String, + span: Span, +} + +macro_rules! suffixed_numbers { + ($($name:ident => $kind:ident,)*) => ($( + pub fn $name(n: $kind) -> Literal { + Literal::_new(format!(concat!("{}", stringify!($kind)), n)) + } + )*) +} + +macro_rules! unsuffixed_numbers { + ($($name:ident => $kind:ident,)*) => ($( + pub fn $name(n: $kind) -> Literal { + Literal::_new(n.to_string()) + } + )*) +} + +impl Literal { + fn _new(text: String) -> Literal { + Literal { + text: text, + span: Span::call_site(), + } + } + + suffixed_numbers! { + u8_suffixed => u8, + u16_suffixed => u16, + u32_suffixed => u32, + u64_suffixed => u64, + usize_suffixed => usize, + i8_suffixed => i8, + i16_suffixed => i16, + i32_suffixed => i32, + i64_suffixed => i64, + isize_suffixed => isize, + + f32_suffixed => f32, + f64_suffixed => f64, + } + + unsuffixed_numbers! { + u8_unsuffixed => u8, + u16_unsuffixed => u16, + u32_unsuffixed => u32, + u64_unsuffixed => u64, + usize_unsuffixed => usize, + i8_unsuffixed => i8, + i16_unsuffixed => i16, + i32_unsuffixed => i32, + i64_unsuffixed => i64, + isize_unsuffixed => isize, + } + + pub fn f32_unsuffixed(f: f32) -> Literal { + let mut s = f.to_string(); + if !s.contains(".") { + s.push_str(".0"); + } + Literal::_new(s) + } + + pub fn f64_unsuffixed(f: f64) -> Literal { + let mut s = f.to_string(); + if !s.contains(".") { + s.push_str(".0"); + } + Literal::_new(s) + } + + pub fn string(t: &str) -> Literal { + let mut s = t.chars() + .flat_map(|c| c.escape_default()) + .collect::(); + s.push('"'); + s.insert(0, '"'); + Literal::_new(s) + } + + pub fn character(t: char) -> Literal { + Literal::_new(format!("'{}'", t.escape_default().collect::())) + } + + pub fn byte_string(bytes: &[u8]) -> Literal { + let mut escaped = "b\"".to_string(); + for b in bytes { + match *b { + b'\0' => escaped.push_str(r"\0"), + b'\t' => escaped.push_str(r"\t"), + b'\n' => escaped.push_str(r"\n"), + b'\r' => escaped.push_str(r"\r"), + b'"' => escaped.push_str("\\\""), + b'\\' => escaped.push_str("\\\\"), + b'\x20'...b'\x7E' => escaped.push(*b as char), + _ => escaped.push_str(&format!("\\x{:02X}", b)), + } + } + escaped.push('"'); + Literal::_new(escaped) + } + + pub fn span(&self) -> Span { + self.span + } + + pub fn set_span(&mut self, span: Span) { + self.span = span; + } +} + +impl fmt::Display for Literal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.text.fmt(f) + } +} + +fn token_stream(mut input: Cursor) -> PResult<::TokenStream> { + let mut trees = Vec::new(); + loop { + let input_no_ws = skip_whitespace(input); + if input_no_ws.rest.len() == 0 { + break + } + if let Ok((a, tokens)) = doc_comment(input_no_ws) { + input = a; + trees.extend(tokens); + continue + } + + let (a, tt) = match token_tree(input_no_ws) { + Ok(p) => p, + Err(_) => break, + }; + trees.push(tt); + input = a; + } + Ok((input, ::TokenStream::_new(TokenStream { inner: trees }))) +} + +#[cfg(not(procmacro2_semver_exempt))] +fn spanned<'a, T>( + input: Cursor<'a>, + f: fn(Cursor<'a>) -> PResult<'a, T>, +) -> PResult<'a, (T, ::Span)> { + let (a, b) = f(skip_whitespace(input))?; + Ok((a, ((b, ::Span::_new(Span { }))))) +} + +#[cfg(procmacro2_semver_exempt)] +fn spanned<'a, T>( + input: Cursor<'a>, + f: fn(Cursor<'a>) -> PResult<'a, T>, +) -> PResult<'a, (T, ::Span)> { + let input = skip_whitespace(input); + let lo = input.off; + let (a, b) = f(input)?; + let hi = a.off; + let span = ::Span::_new(Span { lo: lo, hi: hi }); + Ok((a, (b, span))) +} + +fn token_tree(input: Cursor) -> PResult { + let (rest, (mut tt, span)) = spanned(input, token_kind)?; + tt.set_span(span); + Ok((rest, tt)) +} + +named!(token_kind -> TokenTree, alt!( + map!(group, TokenTree::Group) + | + map!(literal, TokenTree::Literal) // must be before symbol + | + symbol + | + map!(op, TokenTree::Op) +)); + +named!(group -> Group, alt!( + delimited!( + punct!("("), + token_stream, + punct!(")") + ) => { |ts| Group::new(Delimiter::Parenthesis, ts) } + | + delimited!( + punct!("["), + token_stream, + punct!("]") + ) => { |ts| Group::new(Delimiter::Bracket, ts) } + | + delimited!( + punct!("{"), + token_stream, + punct!("}") + ) => { |ts| Group::new(Delimiter::Brace, ts) } +)); + +fn symbol(mut input: Cursor) -> PResult { + input = skip_whitespace(input); + + let mut chars = input.char_indices(); + + let lifetime = input.starts_with("'"); + if lifetime { + chars.next(); + } + + let raw = !lifetime && input.starts_with("r#"); + if raw { + chars.next(); + chars.next(); + } + + match chars.next() { + Some((_, ch)) if UnicodeXID::is_xid_start(ch) || ch == '_' => {} + _ => return Err(LexError), + } + + let mut end = input.len(); + for (i, ch) in chars { + if !UnicodeXID::is_xid_continue(ch) { + end = i; + break; + } + } + + let a = &input.rest[..end]; + if a == "r#_" || lifetime && a != "'static" && KEYWORDS.contains(&&a[1..]) { + Err(LexError) + } else if a == "_" { + Ok((input.advance(end), Op::new('_', Spacing::Alone).into())) + } else { + Ok(( + input.advance(end), + ::Term::new(a, ::Span::call_site()).into(), + )) + } +} + +// From https://github.com/rust-lang/rust/blob/master/src/libsyntax_pos/symbol.rs +static KEYWORDS: &'static [&'static str] = &[ + "abstract", "alignof", "as", "become", "box", "break", "const", "continue", "crate", "do", + "else", "enum", "extern", "false", "final", "fn", "for", "if", "impl", "in", "let", "loop", + "macro", "match", "mod", "move", "mut", "offsetof", "override", "priv", "proc", "pub", "pure", + "ref", "return", "self", "Self", "sizeof", "static", "struct", "super", "trait", "true", + "type", "typeof", "unsafe", "unsized", "use", "virtual", "where", "while", "yield", +]; + +fn literal(input: Cursor) -> PResult<::Literal> { + let input_no_ws = skip_whitespace(input); + + match literal_nocapture(input_no_ws) { + Ok((a, ())) => { + let start = input.len() - input_no_ws.len(); + let len = input_no_ws.len() - a.len(); + let end = start + len; + Ok(( + a, + ::Literal::_new(Literal::_new(input.rest[start..end].to_string())), + )) + } + Err(LexError) => Err(LexError), + } +} + +named!(literal_nocapture -> (), alt!( + string + | + byte_string + | + byte + | + character + | + float + | + int +)); + +named!(string -> (), alt!( + quoted_string + | + preceded!( + punct!("r"), + raw_string + ) => { |_| () } +)); + +named!(quoted_string -> (), delimited!( + punct!("\""), + cooked_string, + tag!("\"") +)); + +fn cooked_string(input: Cursor) -> PResult<()> { + let mut chars = input.char_indices().peekable(); + while let Some((byte_offset, ch)) = chars.next() { + match ch { + '"' => { + return Ok((input.advance(byte_offset), ())); + } + '\r' => { + if let Some((_, '\n')) = chars.next() { + // ... + } else { + break; + } + } + '\\' => match chars.next() { + Some((_, 'x')) => { + if !backslash_x_char(&mut chars) { + break; + } + } + Some((_, 'n')) | Some((_, 'r')) | Some((_, 't')) | Some((_, '\\')) + | Some((_, '\'')) | Some((_, '"')) | Some((_, '0')) => {} + Some((_, 'u')) => { + if !backslash_u(&mut chars) { + break; + } + } + Some((_, '\n')) | Some((_, '\r')) => { + while let Some(&(_, ch)) = chars.peek() { + if ch.is_whitespace() { + chars.next(); + } else { + break; + } + } + } + _ => break, + }, + _ch => {} + } + } + Err(LexError) +} + +named!(byte_string -> (), alt!( + delimited!( + punct!("b\""), + cooked_byte_string, + tag!("\"") + ) => { |_| () } + | + preceded!( + punct!("br"), + raw_string + ) => { |_| () } +)); + +fn cooked_byte_string(mut input: Cursor) -> PResult<()> { + let mut bytes = input.bytes().enumerate(); + 'outer: while let Some((offset, b)) = bytes.next() { + match b { + b'"' => { + return Ok((input.advance(offset), ())); + } + b'\r' => { + if let Some((_, b'\n')) = bytes.next() { + // ... + } else { + break; + } + } + b'\\' => match bytes.next() { + Some((_, b'x')) => { + if !backslash_x_byte(&mut bytes) { + break; + } + } + Some((_, b'n')) | Some((_, b'r')) | Some((_, b't')) | Some((_, b'\\')) + | Some((_, b'0')) | Some((_, b'\'')) | Some((_, b'"')) => {} + Some((newline, b'\n')) | Some((newline, b'\r')) => { + let rest = input.advance(newline + 1); + for (offset, ch) in rest.char_indices() { + if !ch.is_whitespace() { + input = rest.advance(offset); + bytes = input.bytes().enumerate(); + continue 'outer; + } + } + break; + } + _ => break, + }, + b if b < 0x80 => {} + _ => break, + } + } + Err(LexError) +} + +fn raw_string(input: Cursor) -> PResult<()> { + let mut chars = input.char_indices(); + let mut n = 0; + while let Some((byte_offset, ch)) = chars.next() { + match ch { + '"' => { + n = byte_offset; + break; + } + '#' => {} + _ => return Err(LexError), + } + } + for (byte_offset, ch) in chars { + match ch { + '"' if input.advance(byte_offset + 1).starts_with(&input.rest[..n]) => { + let rest = input.advance(byte_offset + 1 + n); + return Ok((rest, ())); + } + '\r' => {} + _ => {} + } + } + Err(LexError) +} + +named!(byte -> (), do_parse!( + punct!("b") >> + tag!("'") >> + cooked_byte >> + tag!("'") >> + (()) +)); + +fn cooked_byte(input: Cursor) -> PResult<()> { + let mut bytes = input.bytes().enumerate(); + let ok = match bytes.next().map(|(_, b)| b) { + Some(b'\\') => match bytes.next().map(|(_, b)| b) { + Some(b'x') => backslash_x_byte(&mut bytes), + Some(b'n') | Some(b'r') | Some(b't') | Some(b'\\') | Some(b'0') | Some(b'\'') + | Some(b'"') => true, + _ => false, + }, + b => b.is_some(), + }; + if ok { + match bytes.next() { + Some((offset, _)) => { + if input.chars().as_str().is_char_boundary(offset) { + Ok((input.advance(offset), ())) + } else { + Err(LexError) + } + } + None => Ok((input.advance(input.len()), ())), + } + } else { + Err(LexError) + } +} + +named!(character -> (), do_parse!( + punct!("'") >> + cooked_char >> + tag!("'") >> + (()) +)); + +fn cooked_char(input: Cursor) -> PResult<()> { + let mut chars = input.char_indices(); + let ok = match chars.next().map(|(_, ch)| ch) { + Some('\\') => match chars.next().map(|(_, ch)| ch) { + Some('x') => backslash_x_char(&mut chars), + Some('u') => backslash_u(&mut chars), + Some('n') | Some('r') | Some('t') | Some('\\') | Some('0') | Some('\'') | Some('"') => { + true + } + _ => false, + }, + ch => ch.is_some(), + }; + if ok { + match chars.next() { + Some((idx, _)) => Ok((input.advance(idx), ())), + None => Ok((input.advance(input.len()), ())), + } + } else { + Err(LexError) + } +} + +macro_rules! next_ch { + ($chars:ident @ $pat:pat $(| $rest:pat)*) => { + match $chars.next() { + Some((_, ch)) => match ch { + $pat $(| $rest)* => ch, + _ => return false, + }, + None => return false + } + }; +} + +fn backslash_x_char(chars: &mut I) -> bool +where + I: Iterator, +{ + next_ch!(chars @ '0'...'7'); + next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F'); + true +} + +fn backslash_x_byte(chars: &mut I) -> bool +where + I: Iterator, +{ + next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F'); + next_ch!(chars @ b'0'...b'9' | b'a'...b'f' | b'A'...b'F'); + true +} + +fn backslash_u(chars: &mut I) -> bool +where + I: Iterator, +{ + next_ch!(chars @ '{'); + next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F'); + loop { + let c = next_ch!(chars @ '0'...'9' | 'a'...'f' | 'A'...'F' | '_' | '}'); + if c == '}' { + return true; + } + } +} + +fn float(input: Cursor) -> PResult<()> { + let (rest, ()) = float_digits(input)?; + for suffix in &["f32", "f64"] { + if rest.starts_with(suffix) { + return word_break(rest.advance(suffix.len())); + } + } + word_break(rest) +} + +fn float_digits(input: Cursor) -> PResult<()> { + let mut chars = input.chars().peekable(); + match chars.next() { + Some(ch) if ch >= '0' && ch <= '9' => {} + _ => return Err(LexError), + } + + let mut len = 1; + let mut has_dot = false; + let mut has_exp = false; + while let Some(&ch) = chars.peek() { + match ch { + '0'...'9' | '_' => { + chars.next(); + len += 1; + } + '.' => { + if has_dot { + break; + } + chars.next(); + if chars + .peek() + .map(|&ch| ch == '.' || UnicodeXID::is_xid_start(ch)) + .unwrap_or(false) + { + return Err(LexError); + } + len += 1; + has_dot = true; + } + 'e' | 'E' => { + chars.next(); + len += 1; + has_exp = true; + break; + } + _ => break, + } + } + + let rest = input.advance(len); + if !(has_dot || has_exp || rest.starts_with("f32") || rest.starts_with("f64")) { + return Err(LexError); + } + + if has_exp { + let mut has_exp_value = false; + while let Some(&ch) = chars.peek() { + match ch { + '+' | '-' => { + if has_exp_value { + break; + } + chars.next(); + len += 1; + } + '0'...'9' => { + chars.next(); + len += 1; + has_exp_value = true; + } + '_' => { + chars.next(); + len += 1; + } + _ => break, + } + } + if !has_exp_value { + return Err(LexError); + } + } + + Ok((input.advance(len), ())) +} + +fn int(input: Cursor) -> PResult<()> { + let (rest, ()) = digits(input)?; + for suffix in &[ + "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16", "u32", "u64", "u128" + ] { + if rest.starts_with(suffix) { + return word_break(rest.advance(suffix.len())); + } + } + word_break(rest) +} + +fn digits(mut input: Cursor) -> PResult<()> { + let base = if input.starts_with("0x") { + input = input.advance(2); + 16 + } else if input.starts_with("0o") { + input = input.advance(2); + 8 + } else if input.starts_with("0b") { + input = input.advance(2); + 2 + } else { + 10 + }; + + let mut len = 0; + let mut empty = true; + for b in input.bytes() { + let digit = match b { + b'0'...b'9' => (b - b'0') as u64, + b'a'...b'f' => 10 + (b - b'a') as u64, + b'A'...b'F' => 10 + (b - b'A') as u64, + b'_' => { + if empty && base == 10 { + return Err(LexError); + } + len += 1; + continue; + } + _ => break, + }; + if digit >= base { + return Err(LexError); + } + len += 1; + empty = false; + } + if empty { + Err(LexError) + } else { + Ok((input.advance(len), ())) + } +} + +fn op(input: Cursor) -> PResult { + let input = skip_whitespace(input); + match op_char(input) { + Ok((rest, ch)) => { + let kind = match op_char(rest) { + Ok(_) => Spacing::Joint, + Err(LexError) => Spacing::Alone, + }; + Ok((rest, Op::new(ch, kind))) + } + Err(LexError) => Err(LexError), + } +} + +fn op_char(input: Cursor) -> PResult { + let mut chars = input.chars(); + let first = match chars.next() { + Some(ch) => ch, + None => { + return Err(LexError); + } + }; + let recognized = "~!@#$%^&*-=+|;:,<.>/?"; + if recognized.contains(first) { + Ok((input.advance(first.len_utf8()), first)) + } else { + Err(LexError) + } +} + +fn doc_comment(input: Cursor) -> PResult> { + let mut trees = Vec::new(); + let (rest, ((comment, inner), span)) = spanned(input, doc_comment_contents)?; + trees.push(TokenTree::Op(Op::new('#', Spacing::Alone))); + if inner { + trees.push(Op::new('!', Spacing::Alone).into()); + } + let mut stream = vec![ + TokenTree::Term(::Term::new("doc", span)), + TokenTree::Op(Op::new('=', Spacing::Alone)), + TokenTree::Literal(::Literal::string(comment)), + ]; + for tt in stream.iter_mut() { + tt.set_span(span); + } + trees.push(Group::new(Delimiter::Bracket, stream.into_iter().collect()).into()); + for tt in trees.iter_mut() { + tt.set_span(span); + } + Ok((rest, trees)) +} + +named!(doc_comment_contents -> (&str, bool), alt!( + do_parse!( + punct!("//!") >> + s: take_until_newline_or_eof!() >> + ((s, true)) + ) + | + do_parse!( + option!(whitespace) >> + peek!(tag!("/*!")) >> + s: block_comment >> + ((s, true)) + ) + | + do_parse!( + punct!("///") >> + not!(tag!("/")) >> + s: take_until_newline_or_eof!() >> + ((s, false)) + ) + | + do_parse!( + option!(whitespace) >> + peek!(tuple!(tag!("/**"), not!(tag!("*")))) >> + s: block_comment >> + ((s, false)) + ) +)); diff -Nru cargo-0.25.0/vendor/proc-macro2-0.3.6/src/strnom.rs cargo-0.26.0/vendor/proc-macro2-0.3.6/src/strnom.rs --- cargo-0.25.0/vendor/proc-macro2-0.3.6/src/strnom.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/proc-macro2-0.3.6/src/strnom.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,391 @@ +//! Adapted from [`nom`](https://github.com/Geal/nom). + +use std::str::{Bytes, CharIndices, Chars}; + +use unicode_xid::UnicodeXID; + +use imp::LexError; + +#[derive(Copy, Clone, Eq, PartialEq)] +pub struct Cursor<'a> { + pub rest: &'a str, + #[cfg(procmacro2_semver_exempt)] + pub off: u32, +} + +impl<'a> Cursor<'a> { + #[cfg(not(procmacro2_semver_exempt))] + pub fn advance(&self, amt: usize) -> Cursor<'a> { + Cursor { + rest: &self.rest[amt..], + } + } + #[cfg(procmacro2_semver_exempt)] + pub fn advance(&self, amt: usize) -> Cursor<'a> { + Cursor { + rest: &self.rest[amt..], + off: self.off + (amt as u32), + } + } + + pub fn find(&self, p: char) -> Option { + self.rest.find(p) + } + + pub fn starts_with(&self, s: &str) -> bool { + self.rest.starts_with(s) + } + + pub fn is_empty(&self) -> bool { + self.rest.is_empty() + } + + pub fn len(&self) -> usize { + self.rest.len() + } + + pub fn as_bytes(&self) -> &'a [u8] { + self.rest.as_bytes() + } + + pub fn bytes(&self) -> Bytes<'a> { + self.rest.bytes() + } + + pub fn chars(&self) -> Chars<'a> { + self.rest.chars() + } + + pub fn char_indices(&self) -> CharIndices<'a> { + self.rest.char_indices() + } +} + +pub type PResult<'a, O> = Result<(Cursor<'a>, O), LexError>; + +pub fn whitespace(input: Cursor) -> PResult<()> { + if input.is_empty() { + return Err(LexError); + } + + let bytes = input.as_bytes(); + let mut i = 0; + while i < bytes.len() { + let s = input.advance(i); + if bytes[i] == b'/' { + if s.starts_with("//") && (!s.starts_with("///") || s.starts_with("////")) + && !s.starts_with("//!") + { + if let Some(len) = s.find('\n') { + i += len + 1; + continue; + } + break; + } else if s.starts_with("/**/") { + i += 4; + continue; + } else if s.starts_with("/*") && (!s.starts_with("/**") || s.starts_with("/***")) + && !s.starts_with("/*!") + { + let (_, com) = block_comment(s)?; + i += com.len(); + continue; + } + } + match bytes[i] { + b' ' | 0x09...0x0d => { + i += 1; + continue; + } + b if b <= 0x7f => {} + _ => { + let ch = s.chars().next().unwrap(); + if is_whitespace(ch) { + i += ch.len_utf8(); + continue; + } + } + } + return if i > 0 { Ok((s, ())) } else { Err(LexError) }; + } + Ok((input.advance(input.len()), ())) +} + +pub fn block_comment(input: Cursor) -> PResult<&str> { + if !input.starts_with("/*") { + return Err(LexError); + } + + let mut depth = 0; + let bytes = input.as_bytes(); + let mut i = 0; + let upper = bytes.len() - 1; + while i < upper { + if bytes[i] == b'/' && bytes[i + 1] == b'*' { + depth += 1; + i += 1; // eat '*' + } else if bytes[i] == b'*' && bytes[i + 1] == b'/' { + depth -= 1; + if depth == 0 { + return Ok((input.advance(i + 2), &input.rest[..i + 2])); + } + i += 1; // eat '/' + } + i += 1; + } + Err(LexError) +} + +pub fn skip_whitespace(input: Cursor) -> Cursor { + match whitespace(input) { + Ok((rest, _)) => rest, + Err(LexError) => input, + } +} + +fn is_whitespace(ch: char) -> bool { + // Rust treats left-to-right mark and right-to-left mark as whitespace + ch.is_whitespace() || ch == '\u{200e}' || ch == '\u{200f}' +} + +pub fn word_break(input: Cursor) -> PResult<()> { + match input.chars().next() { + Some(ch) if UnicodeXID::is_xid_continue(ch) => Err(LexError), + Some(_) | None => Ok((input, ())), + } +} + +macro_rules! named { + ($name:ident -> $o:ty, $submac:ident!( $($args:tt)* )) => { + fn $name<'a>(i: Cursor<'a>) -> $crate::strnom::PResult<'a, $o> { + $submac!(i, $($args)*) + } + }; +} + +macro_rules! alt { + ($i:expr, $e:ident | $($rest:tt)*) => { + alt!($i, call!($e) | $($rest)*) + }; + + ($i:expr, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => { + match $subrule!($i, $($args)*) { + res @ Ok(_) => res, + _ => alt!($i, $($rest)*) + } + }; + + ($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => { + match $subrule!($i, $($args)*) { + Ok((i, o)) => Ok((i, $gen(o))), + Err(LexError) => alt!($i, $($rest)*) + } + }; + + ($i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => { + alt!($i, call!($e) => { $gen } | $($rest)*) + }; + + ($i:expr, $e:ident => { $gen:expr }) => { + alt!($i, call!($e) => { $gen }) + }; + + ($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => { + match $subrule!($i, $($args)*) { + Ok((i, o)) => Ok((i, $gen(o))), + Err(LexError) => Err(LexError), + } + }; + + ($i:expr, $e:ident) => { + alt!($i, call!($e)) + }; + + ($i:expr, $subrule:ident!( $($args:tt)*)) => { + $subrule!($i, $($args)*) + }; +} + +macro_rules! do_parse { + ($i:expr, ( $($rest:expr),* )) => { + Ok(($i, ( $($rest),* ))) + }; + + ($i:expr, $e:ident >> $($rest:tt)*) => { + do_parse!($i, call!($e) >> $($rest)*) + }; + + ($i:expr, $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => { + match $submac!($i, $($args)*) { + Err(LexError) => Err(LexError), + Ok((i, _)) => do_parse!(i, $($rest)*), + } + }; + + ($i:expr, $field:ident : $e:ident >> $($rest:tt)*) => { + do_parse!($i, $field: call!($e) >> $($rest)*) + }; + + ($i:expr, $field:ident : $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => { + match $submac!($i, $($args)*) { + Err(LexError) => Err(LexError), + Ok((i, o)) => { + let $field = o; + do_parse!(i, $($rest)*) + }, + } + }; +} + +macro_rules! peek { + ($i:expr, $submac:ident!( $($args:tt)* )) => { + match $submac!($i, $($args)*) { + Ok((_, o)) => Ok(($i, o)), + Err(LexError) => Err(LexError), + } + }; +} + +macro_rules! call { + ($i:expr, $fun:expr $(, $args:expr)*) => { + $fun($i $(, $args)*) + }; +} + +macro_rules! option { + ($i:expr, $f:expr) => { + match $f($i) { + Ok((i, o)) => Ok((i, Some(o))), + Err(LexError) => Ok(($i, None)), + } + }; +} + +macro_rules! take_until_newline_or_eof { + ($i:expr,) => {{ + if $i.len() == 0 { + Ok(($i, "")) + } else { + match $i.find('\n') { + Some(i) => Ok(($i.advance(i), &$i.rest[..i])), + None => Ok(($i.advance($i.len()), &$i.rest[..$i.len()])), + } + } + }}; +} + +macro_rules! tuple { + ($i:expr, $($rest:tt)*) => { + tuple_parser!($i, (), $($rest)*) + }; +} + +/// Do not use directly. Use `tuple!`. +macro_rules! tuple_parser { + ($i:expr, ($($parsed:tt),*), $e:ident, $($rest:tt)*) => { + tuple_parser!($i, ($($parsed),*), call!($e), $($rest)*) + }; + + ($i:expr, (), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => { + match $submac!($i, $($args)*) { + Err(LexError) => Err(LexError), + Ok((i, o)) => tuple_parser!(i, (o), $($rest)*), + } + }; + + ($i:expr, ($($parsed:tt)*), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => { + match $submac!($i, $($args)*) { + Err(LexError) => Err(LexError), + Ok((i, o)) => tuple_parser!(i, ($($parsed)* , o), $($rest)*), + } + }; + + ($i:expr, ($($parsed:tt),*), $e:ident) => { + tuple_parser!($i, ($($parsed),*), call!($e)) + }; + + ($i:expr, (), $submac:ident!( $($args:tt)* )) => { + $submac!($i, $($args)*) + }; + + ($i:expr, ($($parsed:expr),*), $submac:ident!( $($args:tt)* )) => { + match $submac!($i, $($args)*) { + Err(LexError) => Err(LexError), + Ok((i, o)) => Ok((i, ($($parsed),*, o))) + } + }; + + ($i:expr, ($($parsed:expr),*)) => { + Ok(($i, ($($parsed),*))) + }; +} + +macro_rules! not { + ($i:expr, $submac:ident!( $($args:tt)* )) => { + match $submac!($i, $($args)*) { + Ok((_, _)) => Err(LexError), + Err(LexError) => Ok(($i, ())), + } + }; +} + +macro_rules! tag { + ($i:expr, $tag:expr) => { + if $i.starts_with($tag) { + Ok(($i.advance($tag.len()), &$i.rest[..$tag.len()])) + } else { + Err(LexError) + } + }; +} + +macro_rules! punct { + ($i:expr, $punct:expr) => { + $crate::strnom::punct($i, $punct) + }; +} + +/// Do not use directly. Use `punct!`. +pub fn punct<'a>(input: Cursor<'a>, token: &'static str) -> PResult<'a, &'a str> { + let input = skip_whitespace(input); + if input.starts_with(token) { + Ok((input.advance(token.len()), token)) + } else { + Err(LexError) + } +} + +macro_rules! preceded { + ($i:expr, $submac:ident!( $($args:tt)* ), $submac2:ident!( $($args2:tt)* )) => { + match tuple!($i, $submac!($($args)*), $submac2!($($args2)*)) { + Ok((remaining, (_, o))) => Ok((remaining, o)), + Err(LexError) => Err(LexError), + } + }; + + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => { + preceded!($i, $submac!($($args)*), call!($g)) + }; +} + +macro_rules! delimited { + ($i:expr, $submac:ident!( $($args:tt)* ), $($rest:tt)+) => { + match tuple_parser!($i, (), $submac!($($args)*), $($rest)*) { + Err(LexError) => Err(LexError), + Ok((i1, (_, o, _))) => Ok((i1, o)) + } + }; +} + +macro_rules! map { + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => { + match $submac!($i, $($args)*) { + Err(LexError) => Err(LexError), + Ok((i, o)) => Ok((i, call!(o, $g))) + } + }; + + ($i:expr, $f:expr, $g:expr) => { + map!($i, call!($f), $g) + }; +} diff -Nru cargo-0.25.0/vendor/proc-macro2-0.3.6/src/unstable.rs cargo-0.26.0/vendor/proc-macro2-0.3.6/src/unstable.rs --- cargo-0.25.0/vendor/proc-macro2-0.3.6/src/unstable.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/proc-macro2-0.3.6/src/unstable.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,399 @@ +#![cfg_attr(not(procmacro2_semver_exempt), allow(dead_code))] + +use std::fmt; +use std::iter; +use std::str::FromStr; + +use proc_macro; + +use {Delimiter, Group, Op, Spacing, TokenTree}; + +#[derive(Clone)] +pub struct TokenStream(proc_macro::TokenStream); + +pub struct LexError(proc_macro::LexError); + +impl TokenStream { + pub fn empty() -> TokenStream { + TokenStream(proc_macro::TokenStream::empty()) + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +impl FromStr for TokenStream { + type Err = LexError; + + fn from_str(src: &str) -> Result { + Ok(TokenStream(src.parse().map_err(LexError)?)) + } +} + +impl fmt::Display for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.fmt(f) + } +} + +impl From for TokenStream { + fn from(inner: proc_macro::TokenStream) -> TokenStream { + TokenStream(inner) + } +} + +impl From for proc_macro::TokenStream { + fn from(inner: TokenStream) -> proc_macro::TokenStream { + inner.0 + } +} + +impl From for TokenStream { + fn from(token: TokenTree) -> TokenStream { + let tt: proc_macro::TokenTree = match token { + TokenTree::Group(tt) => { + let delim = match tt.delimiter() { + Delimiter::Parenthesis => proc_macro::Delimiter::Parenthesis, + Delimiter::Bracket => proc_macro::Delimiter::Bracket, + Delimiter::Brace => proc_macro::Delimiter::Brace, + Delimiter::None => proc_macro::Delimiter::None, + }; + let span = tt.span(); + let mut group = proc_macro::Group::new(delim, tt.stream.inner.0); + group.set_span(span.inner.0); + group.into() + } + TokenTree::Op(tt) => { + let spacing = match tt.spacing() { + Spacing::Joint => proc_macro::Spacing::Joint, + Spacing::Alone => proc_macro::Spacing::Alone, + }; + let mut op = proc_macro::Op::new(tt.op(), spacing); + op.set_span(tt.span().inner.0); + op.into() + } + TokenTree::Term(tt) => tt.inner.term.into(), + TokenTree::Literal(tt) => tt.inner.lit.into(), + }; + TokenStream(tt.into()) + } +} + +impl iter::FromIterator for TokenStream { + fn from_iter>(streams: I) -> Self { + let streams = streams.into_iter().map(TokenStream::from) + .flat_map(|t| t.0); + TokenStream(streams.collect::()) + } +} + +impl fmt::Debug for TokenStream { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.fmt(f) + } +} + +impl fmt::Debug for LexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.fmt(f) + } +} + +pub struct TokenTreeIter(proc_macro::token_stream::IntoIter); + +impl IntoIterator for TokenStream { + type Item = TokenTree; + type IntoIter = TokenTreeIter; + + fn into_iter(self) -> TokenTreeIter { + TokenTreeIter(self.0.into_iter()) + } +} + +impl Iterator for TokenTreeIter { + type Item = TokenTree; + + fn next(&mut self) -> Option { + let token = self.0.next()?; + Some(match token { + proc_macro::TokenTree::Group(tt) => { + let delim = match tt.delimiter() { + proc_macro::Delimiter::Parenthesis => Delimiter::Parenthesis, + proc_macro::Delimiter::Bracket => Delimiter::Bracket, + proc_macro::Delimiter::Brace => Delimiter::Brace, + proc_macro::Delimiter::None => Delimiter::None, + }; + let stream = ::TokenStream::_new(TokenStream(tt.stream())); + let mut g = Group::new(delim, stream); + g.set_span(::Span::_new(Span(tt.span()))); + g.into() + } + proc_macro::TokenTree::Op(tt) => { + let spacing = match tt.spacing() { + proc_macro::Spacing::Joint => Spacing::Joint, + proc_macro::Spacing::Alone => Spacing::Alone, + }; + let mut o = Op::new(tt.op(), spacing); + o.set_span(::Span::_new(Span(tt.span()))); + o.into() + } + proc_macro::TokenTree::Term(s) => { + ::Term::_new(Term { + term: s, + }).into() + } + proc_macro::TokenTree::Literal(l) => { + ::Literal::_new(Literal { + lit: l, + }).into() + } + }) + } + + fn size_hint(&self) -> (usize, Option) { + self.0.size_hint() + } +} + +impl fmt::Debug for TokenTreeIter { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("TokenTreeIter").finish() + } +} + +#[derive(Clone, PartialEq, Eq)] +pub struct FileName(String); + +impl fmt::Display for FileName { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.fmt(f) + } +} + +// NOTE: We have to generate our own filename object here because we can't wrap +// the one provided by proc_macro. +#[derive(Clone, PartialEq, Eq)] +pub struct SourceFile(proc_macro::SourceFile, FileName); + +impl SourceFile { + fn new(sf: proc_macro::SourceFile) -> Self { + let filename = FileName(sf.path().to_string()); + SourceFile(sf, filename) + } + + /// Get the path to this source file as a string. + pub fn path(&self) -> &FileName { + &self.1 + } + + pub fn is_real(&self) -> bool { + self.0.is_real() + } +} + +impl AsRef for SourceFile { + fn as_ref(&self) -> &FileName { + self.path() + } +} + +impl fmt::Debug for SourceFile { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.fmt(f) + } +} + +pub struct LineColumn { + pub line: usize, + pub column: usize, +} + +#[derive(Copy, Clone)] +pub struct Span(proc_macro::Span); + +impl From for ::Span { + fn from(proc_span: proc_macro::Span) -> ::Span { + ::Span::_new(Span(proc_span)) + } +} + +impl Span { + pub fn call_site() -> Span { + Span(proc_macro::Span::call_site()) + } + + pub fn def_site() -> Span { + Span(proc_macro::Span::def_site()) + } + + pub fn resolved_at(&self, other: Span) -> Span { + Span(self.0.resolved_at(other.0)) + } + + pub fn located_at(&self, other: Span) -> Span { + Span(self.0.located_at(other.0)) + } + + pub fn unstable(self) -> proc_macro::Span { + self.0 + } + + pub fn source_file(&self) -> SourceFile { + SourceFile::new(self.0.source_file()) + } + + pub fn start(&self) -> LineColumn { + let proc_macro::LineColumn { line, column } = self.0.start(); + LineColumn { line, column } + } + + pub fn end(&self) -> LineColumn { + let proc_macro::LineColumn { line, column } = self.0.end(); + LineColumn { line, column } + } + + pub fn join(&self, other: Span) -> Option { + self.0.join(other.0).map(Span) + } + + pub fn eq(&self, other: &Span) -> bool { + self.0.eq(&other.0) + } +} + +impl fmt::Debug for Span { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.0.fmt(f) + } +} + +#[derive(Copy, Clone)] +pub struct Term { + term: proc_macro::Term, +} + +impl Term { + pub fn new(string: &str, span: Span) -> Term { + Term { + term: proc_macro::Term::new(string, span.0), + } + } + + pub fn as_str(&self) -> &str { + self.term.as_str() + } + + pub fn span(&self) -> Span { + Span(self.term.span()) + } + + pub fn set_span(&mut self, span: Span) { + self.term.set_span(span.0); + } +} + +impl fmt::Debug for Term { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.term.fmt(f) + } +} + +#[derive(Clone)] +pub struct Literal { + lit: proc_macro::Literal, +} + +macro_rules! suffixed_numbers { + ($($name:ident => $kind:ident,)*) => ($( + pub fn $name(n: $kind) -> Literal { + Literal::_new(proc_macro::Literal::$name(n)) + } + )*) +} + +macro_rules! unsuffixed_integers { + ($($name:ident => $kind:ident,)*) => ($( + pub fn $name(n: $kind) -> Literal { + Literal::_new(proc_macro::Literal::$name(n)) + } + )*) +} + +impl Literal { + fn _new(lit: proc_macro::Literal) -> Literal { + Literal { + lit, + } + } + + suffixed_numbers! { + u8_suffixed => u8, + u16_suffixed => u16, + u32_suffixed => u32, + u64_suffixed => u64, + usize_suffixed => usize, + i8_suffixed => i8, + i16_suffixed => i16, + i32_suffixed => i32, + i64_suffixed => i64, + isize_suffixed => isize, + + f32_suffixed => f32, + f64_suffixed => f64, + } + + unsuffixed_integers! { + u8_unsuffixed => u8, + u16_unsuffixed => u16, + u32_unsuffixed => u32, + u64_unsuffixed => u64, + usize_unsuffixed => usize, + i8_unsuffixed => i8, + i16_unsuffixed => i16, + i32_unsuffixed => i32, + i64_unsuffixed => i64, + isize_unsuffixed => isize, + } + + pub fn f32_unsuffixed(f: f32) -> Literal { + Literal::_new(proc_macro::Literal::f32_unsuffixed(f)) + } + + pub fn f64_unsuffixed(f: f64) -> Literal { + Literal::_new(proc_macro::Literal::f64_unsuffixed(f)) + } + + + pub fn string(t: &str) -> Literal { + Literal::_new(proc_macro::Literal::string(t)) + } + + pub fn character(t: char) -> Literal { + Literal::_new(proc_macro::Literal::character(t)) + } + + pub fn byte_string(bytes: &[u8]) -> Literal { + Literal::_new(proc_macro::Literal::byte_string(bytes)) + } + + pub fn span(&self) -> Span { + Span(self.lit.span()) + } + + pub fn set_span(&mut self, span: Span) { + self.lit.set_span(span.0); + } +} + +impl fmt::Display for Literal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.lit.fmt(f) + } +} + +impl fmt::Debug for Literal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.lit.fmt(f) + } +} diff -Nru cargo-0.25.0/vendor/proc-macro2-0.3.6/tests/test.rs cargo-0.26.0/vendor/proc-macro2-0.3.6/tests/test.rs --- cargo-0.25.0/vendor/proc-macro2-0.3.6/tests/test.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/proc-macro2-0.3.6/tests/test.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,304 @@ +extern crate proc_macro2; + +use std::str::{self, FromStr}; + +use proc_macro2::{Literal, Span, Term, TokenStream, TokenTree}; + +#[test] +fn terms() { + assert_eq!(Term::new("String", Span::call_site()).as_str(), "String"); + assert_eq!(Term::new("fn", Span::call_site()).as_str(), "fn"); + assert_eq!(Term::new("_", Span::call_site()).as_str(), "_"); +} + +#[test] +fn raw_terms() { + assert_eq!(Term::new("r#String", Span::call_site()).as_str(), "r#String"); + assert_eq!(Term::new("r#fn", Span::call_site()).as_str(), "r#fn"); + assert_eq!(Term::new("r#_", Span::call_site()).as_str(), "r#_"); +} + +#[test] +fn lifetimes() { + assert_eq!(Term::new("'a", Span::call_site()).as_str(), "'a"); + assert_eq!(Term::new("'static", Span::call_site()).as_str(), "'static"); + assert_eq!(Term::new("'_", Span::call_site()).as_str(), "'_"); +} + +#[test] +#[should_panic(expected = "Term is not allowed to be empty; use Option")] +fn term_empty() { + Term::new("", Span::call_site()); +} + +#[test] +#[should_panic(expected = "Term cannot be a number; use Literal instead")] +fn term_number() { + Term::new("255", Span::call_site()); +} + +#[test] +#[should_panic(expected = "\"a#\" is not a valid Term")] +fn term_invalid() { + Term::new("a#", Span::call_site()); +} + +#[test] +#[should_panic(expected = "Term is not allowed to be empty; use Option")] +fn raw_term_empty() { + Term::new("r#", Span::call_site()); +} + +#[test] +#[should_panic(expected = "Term cannot be a number; use Literal instead")] +fn raw_term_number() { + Term::new("r#255", Span::call_site()); +} + +#[test] +#[should_panic(expected = "\"r#a#\" is not a valid Term")] +fn raw_term_invalid() { + Term::new("r#a#", Span::call_site()); +} + +#[test] +#[should_panic(expected = "Term is not allowed to be empty; use Option")] +fn lifetime_empty() { + Term::new("'", Span::call_site()); +} + +#[test] +#[should_panic(expected = "Term cannot be a number; use Literal instead")] +fn lifetime_number() { + Term::new("'255", Span::call_site()); +} + +#[test] +#[should_panic(expected = r#""\'a#" is not a valid Term"#)] +fn lifetime_invalid() { + Term::new("'a#", Span::call_site()); +} + +#[test] +fn literals() { + assert_eq!(Literal::string("foo").to_string(), "\"foo\""); + assert_eq!(Literal::string("\"").to_string(), "\"\\\"\""); + assert_eq!(Literal::f32_unsuffixed(10.0).to_string(), "10.0"); +} + +#[test] +fn roundtrip() { + fn roundtrip(p: &str) { + println!("parse: {}", p); + let s = p.parse::().unwrap().to_string(); + println!("first: {}", s); + let s2 = s.to_string().parse::().unwrap().to_string(); + assert_eq!(s, s2); + } + roundtrip("a"); + roundtrip("<<"); + roundtrip("<<="); + roundtrip( + " + 1 + 1.0 + 1f32 + 2f64 + 1usize + 4isize + 4e10 + 1_000 + 1_0i32 + 8u8 + 9 + 0 + 0xffffffffffffffffffffffffffffffff + ", + ); + roundtrip("'a"); + roundtrip("'static"); + roundtrip("'\\u{10__FFFF}'"); + roundtrip("\"\\u{10_F0FF__}foo\\u{1_0_0_0__}\""); +} + +#[test] +fn fail() { + fn fail(p: &str) { + if p.parse::().is_ok() { + panic!("should have failed to parse: {}", p); + } + } + fail("1x"); + fail("1u80"); + fail("1f320"); + fail("' static"); + fail("'mut"); + fail("r#1"); + fail("r#_"); +} + +#[cfg(procmacro2_semver_exempt)] +#[test] +fn span_test() { + use proc_macro2::TokenTree; + + fn check_spans(p: &str, mut lines: &[(usize, usize, usize, usize)]) { + let ts = p.parse::().unwrap(); + check_spans_internal(ts, &mut lines); + } + + fn check_spans_internal(ts: TokenStream, lines: &mut &[(usize, usize, usize, usize)]) { + for i in ts { + if let Some((&(sline, scol, eline, ecol), rest)) = lines.split_first() { + *lines = rest; + + let start = i.span().start(); + assert_eq!(start.line, sline, "sline did not match for {}", i); + assert_eq!(start.column, scol, "scol did not match for {}", i); + + let end = i.span().end(); + assert_eq!(end.line, eline, "eline did not match for {}", i); + assert_eq!(end.column, ecol, "ecol did not match for {}", i); + + match i { + TokenTree::Group(ref g) => { + check_spans_internal(g.stream().clone(), lines); + } + _ => {} + } + } + } + } + + check_spans( + "\ +/// This is a document comment +testing 123 +{ + testing 234 +}", + &[ + (1, 0, 1, 30), // # + (1, 0, 1, 30), // [ ... ] + (1, 0, 1, 30), // doc + (1, 0, 1, 30), // = + (1, 0, 1, 30), // "This is..." + (2, 0, 2, 7), // testing + (2, 8, 2, 11), // 123 + (3, 0, 5, 1), // { ... } + (4, 2, 4, 9), // testing + (4, 10, 4, 13), // 234 + ], + ); +} + +#[cfg(procmacro2_semver_exempt)] +#[cfg(not(feature = "nightly"))] +#[test] +fn default_span() { + let start = Span::call_site().start(); + assert_eq!(start.line, 1); + assert_eq!(start.column, 0); + let end = Span::call_site().end(); + assert_eq!(end.line, 1); + assert_eq!(end.column, 0); + let source_file = Span::call_site().source_file(); + assert_eq!(source_file.path().to_string(), ""); + assert!(!source_file.is_real()); +} + +#[cfg(procmacro2_semver_exempt)] +#[test] +fn span_join() { + let source1 = "aaa\nbbb" + .parse::() + .unwrap() + .into_iter() + .collect::>(); + let source2 = "ccc\nddd" + .parse::() + .unwrap() + .into_iter() + .collect::>(); + + assert!(source1[0].span().source_file() != source2[0].span().source_file()); + assert_eq!( + source1[0].span().source_file(), + source1[1].span().source_file() + ); + + let joined1 = source1[0].span().join(source1[1].span()); + let joined2 = source1[0].span().join(source2[0].span()); + assert!(joined1.is_some()); + assert!(joined2.is_none()); + + let start = joined1.unwrap().start(); + let end = joined1.unwrap().end(); + assert_eq!(start.line, 1); + assert_eq!(start.column, 0); + assert_eq!(end.line, 2); + assert_eq!(end.column, 3); + + assert_eq!( + joined1.unwrap().source_file(), + source1[0].span().source_file() + ); +} + +#[test] +fn no_panic() { + let s = str::from_utf8(b"b\'\xc2\x86 \x00\x00\x00^\"").unwrap(); + assert!(s.parse::().is_err()); +} + +#[test] +fn tricky_doc_comment() { + let stream = "/**/".parse::().unwrap(); + let tokens = stream.into_iter().collect::>(); + assert!(tokens.is_empty(), "not empty -- {:?}", tokens); + + let stream = "/// doc".parse::().unwrap(); + let tokens = stream.into_iter().collect::>(); + assert!(tokens.len() == 2, "not length 2 -- {:?}", tokens); + match tokens[0] { + proc_macro2::TokenTree::Op(ref tt) => assert_eq!(tt.op(), '#'), + _ => panic!("wrong token {:?}", tokens[0]), + } + let mut tokens = match tokens[1] { + proc_macro2::TokenTree::Group(ref tt) => { + assert_eq!(tt.delimiter(), proc_macro2::Delimiter::Bracket); + tt.stream().into_iter() + } + _ => panic!("wrong token {:?}", tokens[0]), + }; + + match tokens.next().unwrap() { + proc_macro2::TokenTree::Term(ref tt) => assert_eq!(tt.as_str(), "doc"), + t => panic!("wrong token {:?}", t), + } + match tokens.next().unwrap() { + proc_macro2::TokenTree::Op(ref tt) => assert_eq!(tt.op(), '='), + t => panic!("wrong token {:?}", t), + } + match tokens.next().unwrap() { + proc_macro2::TokenTree::Literal(ref tt) => { + assert_eq!(tt.to_string(), "\" doc\""); + } + t => panic!("wrong token {:?}", t), + } + assert!(tokens.next().is_none()); + + let stream = "//! doc".parse::().unwrap(); + let tokens = stream.into_iter().collect::>(); + assert!(tokens.len() == 3, "not length 3 -- {:?}", tokens); +} + +#[test] +fn raw_identifier() { + let mut tts = TokenStream::from_str("r#dyn").unwrap().into_iter(); + match tts.next().unwrap() { + TokenTree::Term(raw) => assert_eq!("r#dyn", raw.as_str()), + wrong => panic!("wrong token {:?}", wrong), + } + assert!(tts.next().is_none()); +} diff -Nru cargo-0.25.0/vendor/proc-macro2-0.3.6/.travis.yml cargo-0.26.0/vendor/proc-macro2-0.3.6/.travis.yml --- cargo-0.25.0/vendor/proc-macro2-0.3.6/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/proc-macro2-0.3.6/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,32 @@ +language: rust +sudo: false + +matrix: + include: + - rust: 1.15.0 + - rust: stable + - rust: beta + - rust: nightly + before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH + script: + - cargo test + - cargo build --features nightly + - cargo build --no-default-features + - RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo test + - RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo build --features nightly + - RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo doc --no-deps + after_success: + - travis-cargo --only nightly doc-upload + +script: + - cargo test + - RUSTFLAGS='--cfg procmacro2_semver_exempt' cargo test +env: + global: + - TRAVIS_CARGO_NIGHTLY_FEATURE="" + - secure: "NAsZghAVTAksrm4WP4I66VmD2wW0eRbwB+ZKHUQfvbgUaCRvVdp4WBbWXGU/f/yHgDFWZwljWR4iPMiBwAK8nZsQFRuLFdHrOOHqbkj639LLdT9A07s1zLMB1GfR1fDttzrGhm903pbT2yxSyqqpahGYM7TaGDYYmKYIk4XyVNA5F5Sk7RI+rCecKraoYDeUEFbjWWYtU2FkEXsELEKj0emX5reWkR+wja3QokFcRZ25+Zd2dRC0K8W5QcY2UokLzKncBMCTC5q70H616S3r/9qW67Si1njsJ7RzP0NlZQUNQ/VCvwr4LCr9w+AD9i1SZtXxuux77tWEWSJvBzUc82dDMUv/floJuF7HTulSxxQoRm+fbzpXj9mgaJNiUHXru6ZRTCRVRUSXpcAco94bVoy/jnjrTe3jgAIZK5w14zA8yLw1Jxof31DlbcWORxgF+6fnY2nKPRN2oiQ50+jm1AuGDZX59/wMiu1QlkjOBHtikHp+u+7mp3SkkM04DvuQ/tWODQQnOOtrA0EB3i5H1zeTSnUcmbJufUljWWOvF1QYII08MccqwfG1KWbpobvdu+cV2iVhkq/lNCEL3Ai101CnmSCnMz+9oK/XxYOrx2TnaD9ootOKgnk7XWxF19GZecQx6O2hHTouxvB/0KcRPGWmMWl0H88f3T/Obql8bG8=" + +notifications: + email: + on_success: never diff -Nru cargo-0.25.0/vendor/quick-error-1.2.1/bulk.yaml cargo-0.26.0/vendor/quick-error-1.2.1/bulk.yaml --- cargo-0.25.0/vendor/quick-error-1.2.1/bulk.yaml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quick-error-1.2.1/bulk.yaml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,8 @@ +minimum-bulk: v0.4.5 + +versions: + +- file: Cargo.toml + block-start: ^\[package\] + block-end: ^\[.*\] + regex: ^version\s*=\s*"(\S+)" diff -Nru cargo-0.25.0/vendor/quick-error-1.2.1/.cargo-checksum.json cargo-0.26.0/vendor/quick-error-1.2.1/.cargo-checksum.json --- cargo-0.25.0/vendor/quick-error-1.2.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quick-error-1.2.1/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"eda5fe9b71976e62bc81b781206aaa076401769b2143379d3eb2118388babac4"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/quick-error-1.2.1/Cargo.toml cargo-0.26.0/vendor/quick-error-1.2.1/Cargo.toml --- cargo-0.25.0/vendor/quick-error-1.2.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quick-error-1.2.1/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,23 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "quick-error" +version = "1.2.1" +authors = ["Paul Colomiets ", "Colin Kiegel "] +description = " A macro which makes error types pleasant to write.\n" +homepage = "http://github.com/tailhook/quick-error" +documentation = "http://docs.rs/quick-error" +keywords = ["macro", "error", "type", "enum"] +categories = ["rust-patterns"] +license = "MIT/Apache-2.0" +repository = "http://github.com/tailhook/quick-error" diff -Nru cargo-0.25.0/vendor/quick-error-1.2.1/examples/context.rs cargo-0.26.0/vendor/quick-error-1.2.1/examples/context.rs --- cargo-0.25.0/vendor/quick-error-1.2.1/examples/context.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quick-error-1.2.1/examples/context.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,48 @@ +#[macro_use(quick_error)] extern crate quick_error; + +use std::io::{self, stderr, Read, Write}; +use std::fs::File; +use std::env; +use std::num::ParseIntError; +use std::path::{Path, PathBuf}; + +use quick_error::ResultExt; + +quick_error! { + #[derive(Debug)] + pub enum Error { + NoFileName { + description("no file name specified") + } + Io(err: io::Error, path: PathBuf) { + display("could not read file {:?}: {}", path, err) + context(path: &'a Path, err: io::Error) + -> (err, path.to_path_buf()) + } + Parse(err: ParseIntError, path: PathBuf) { + display("could not parse file {:?}: {}", path, err) + context(path: &'a Path, err: ParseIntError) + -> (err, path.to_path_buf()) + } + } +} + +fn parse_file() -> Result { + let fname = try!(env::args().skip(1).next().ok_or(Error::NoFileName)); + let fname = Path::new(&fname); + let mut file = try!(File::open(fname).context(fname)); + let mut buf = String::new(); + try!(file.read_to_string(&mut buf).context(fname)); + Ok(try!(buf.parse().context(fname))) +} + +fn main() { + match parse_file() { + Ok(val) => { + println!("Read: {}", val); + } + Err(e) => { + writeln!(&mut stderr(), "Error: {}", e).ok(); + } + } +} diff -Nru cargo-0.25.0/vendor/quick-error-1.2.1/LICENSE-APACHE cargo-0.26.0/vendor/quick-error-1.2.1/LICENSE-APACHE --- cargo-0.25.0/vendor/quick-error-1.2.1/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quick-error-1.2.1/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -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. + diff -Nru cargo-0.25.0/vendor/quick-error-1.2.1/LICENSE-MIT cargo-0.26.0/vendor/quick-error-1.2.1/LICENSE-MIT --- cargo-0.25.0/vendor/quick-error-1.2.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quick-error-1.2.1/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,19 @@ +Copyright (c) 2015 The quick-error 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. diff -Nru cargo-0.25.0/vendor/quick-error-1.2.1/README.rst cargo-0.26.0/vendor/quick-error-1.2.1/README.rst --- cargo-0.25.0/vendor/quick-error-1.2.1/README.rst 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quick-error-1.2.1/README.rst 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,69 @@ +=========== +Quick Error +=========== + +:Status: production-ready +:Documentation: http://tailhook.github.io/quick-error/ + +A macro which makes error types pleasant to write. + +Features: + +* Define enum type with arbitrary parameters +* Concise notation of ``Display`` and ``Error`` traits +* Full control of ``Display`` and ``Error`` trait implementation +* Any number of ``From`` traits +* Support for all enum-variants ``Unit``, ``Tuple`` and ``Struct`` + +Here is the comprehensive example: + +.. code-block:: rust + + quick_error! { + #[derive(Debug)] + pub enum IoWrapper { + Io(err: io::Error) { + from() + description("io error") + display("I/O error: {}", err) + cause(err) + } + Other(descr: &'static str) { + description(descr) + display("Error {}", descr) + } + IoAt { place: &'static str, err: io::Error } { + cause(err) + display(me) -> ("{} {}: {}", me.description(), place, err) + description("io error at") + from(s: String) -> { + place: "some string", + err: io::Error::new(io::ErrorKind::Other, s) + } + } + Discard { + from(&'static str) + } + } + } + +======= +License +======= + +Licensed under either of + + * Apache License, Version 2.0, (./LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) + * MIT license (./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. + diff -Nru cargo-0.25.0/vendor/quick-error-1.2.1/src/lib.rs cargo-0.26.0/vendor/quick-error-1.2.1/src/lib.rs --- cargo-0.25.0/vendor/quick-error-1.2.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quick-error-1.2.1/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1301 @@ +#![warn(missing_docs)] +//! A macro which makes errors easy to write +//! +//! Minimum type is like this: +//! +//! ```rust +//! #[macro_use] extern crate quick_error; +//! # fn main() {} +//! +//! quick_error! { +//! #[derive(Debug)] +//! pub enum SomeError { +//! Variant1 {} +//! } +//! } +//! ``` +//! Both ``pub`` and non-public types may be declared, and all meta attributes +//! (such as ``#[derive(Debug)]``) are forwarded as is. The `Debug` must be +//! implemented (but you may do that yourself if you like). The documentation +//! comments ``/// something`` (as well as other meta attrbiutes) on variants +//! are allowed. +//! +//! # Allowed Syntax +//! +//! You may add arbitrary parameters to any struct variant: +//! +//! ```rust +//! # #[macro_use] extern crate quick_error; +//! # fn main() {} +//! # +//! quick_error! { +//! #[derive(Debug)] +//! pub enum SomeError { +//! /// IO Error +//! Io(err: std::io::Error) {} +//! /// Utf8 Error +//! Utf8(err: std::str::Utf8Error) {} +//! } +//! } +//! ``` +//! +//! Note unlike in normal Enum declarations you declare names of fields (which +//! are omitted from type). How they can be used is outlined below. +//! +//! Now you might have noticed trailing braces `{}`. They are used to define +//! implementations. By default: +//! +//! * `Error::description()` returns variant name as static string +//! * `Error::cause()` returns None (even if type wraps some value) +//! * `Display` outputs `description()` +//! * No `From` implementations are defined +//! +//! To define description simply add `description(value)` inside braces: +//! +//! ```rust +//! # #[macro_use] extern crate quick_error; +//! # fn main() {} +//! # +//! quick_error! { +//! #[derive(Debug)] +//! pub enum SomeError { +//! Io(err: std::io::Error) { +//! description(err.description()) +//! } +//! Utf8(err: std::str::Utf8Error) { +//! description("utf8 error") +//! } +//! } +//! } +//! ``` +//! +//! Normal rules for borrowing apply. So most of the time description either +//! returns constant string or forwards description from enclosed type. +//! +//! To change `cause` method to return some error, add `cause(value)`, for +//! example: +//! +//! ```rust +//! # #[macro_use] extern crate quick_error; +//! # fn main() {} +//! # +//! quick_error! { +//! #[derive(Debug)] +//! pub enum SomeError { +//! Io(err: std::io::Error) { +//! cause(err) +//! description(err.description()) +//! } +//! Utf8(err: std::str::Utf8Error) { +//! description("utf8 error") +//! } +//! Other(err: Box) { +//! cause(&**err) +//! description(err.description()) +//! } +//! } +//! } +//! ``` +//! Note you don't need to wrap value in `Some`, its implicit. In case you want +//! `None` returned just omit the `cause`. You can't return `None` +//! conditionally. +//! +//! To change how each clause is `Display`ed add `display(pattern,..args)`, +//! for example: +//! +//! ```rust +//! # #[macro_use] extern crate quick_error; +//! # fn main() {} +//! # +//! quick_error! { +//! #[derive(Debug)] +//! pub enum SomeError { +//! Io(err: std::io::Error) { +//! display("I/O error: {}", err) +//! } +//! Utf8(err: std::str::Utf8Error) { +//! display("Utf8 error, valid up to {}", err.valid_up_to()) +//! } +//! } +//! } +//! ``` +//! +//! If you need a reference to the error when `Display`ing, you can instead use +//! `display(x) -> (pattern, ..args)`, where `x` sets the name of the reference. +//! +//! ```rust +//! # #[macro_use] extern crate quick_error; +//! # fn main() {} +//! # +//! use std::error::Error; // put methods like `description()` of this trait into scope +//! +//! quick_error! { +//! #[derive(Debug)] +//! pub enum SomeError { +//! Io(err: std::io::Error) { +//! display(x) -> ("{}: {}", x.description(), err) +//! } +//! Utf8(err: std::str::Utf8Error) { +//! display(self_) -> ("{}, valid up to {}", self_.description(), err.valid_up_to()) +//! } +//! } +//! } +//! ``` +//! +//! To convert to the type from any other, use one of the three forms of +//! `from` clause. +//! +//! For example, to convert simple wrapper use bare `from()`: +//! +//! ```rust +//! # #[macro_use] extern crate quick_error; +//! # fn main() {} +//! # +//! quick_error! { +//! #[derive(Debug)] +//! pub enum SomeError { +//! Io(err: std::io::Error) { +//! from() +//! } +//! } +//! } +//! ``` +//! +//! This implements ``From``. +//! +//! To convert to singleton enumeration type (discarding the value), use +//! the `from(type)` form: +//! +//! ```rust +//! # #[macro_use] extern crate quick_error; +//! # fn main() {} +//! # +//! quick_error! { +//! #[derive(Debug)] +//! pub enum SomeError { +//! FormatError { +//! from(std::fmt::Error) +//! } +//! } +//! } +//! ``` +//! +//! And the most powerful form is `from(var: type) -> (arguments...)`. It +//! might be used to convert to type with multiple arguments or for arbitrary +//! value conversions: +//! +//! ```rust +//! # #[macro_use] extern crate quick_error; +//! # fn main() {} +//! # +//! quick_error! { +//! #[derive(Debug)] +//! pub enum SomeError { +//! FailedOperation(s: &'static str, errno: i32) { +//! from(errno: i32) -> ("os error", errno) +//! from(e: std::io::Error) -> ("io error", e.raw_os_error().unwrap()) +//! } +//! /// Converts from both kinds of utf8 errors +//! Utf8(err: std::str::Utf8Error) { +//! from() +//! from(err: std::string::FromUtf8Error) -> (err.utf8_error()) +//! } +//! } +//! } +//! ``` +//! # Context +//! +//! Since quick-error 1.1 we also have a `context` declaration, which is +//! similar to (the longest form of) `from`, but allows adding some context to +//! the error. We need a longer example to demonstrate this: +//! +//! ```rust +//! # #[macro_use] extern crate quick_error; +//! # use std::io; +//! # use std::fs::File; +//! # use std::path::{Path, PathBuf}; +//! # +//! use quick_error::ResultExt; +//! +//! quick_error! { +//! #[derive(Debug)] +//! pub enum Error { +//! File(filename: PathBuf, err: io::Error) { +//! context(path: &'a Path, err: io::Error) +//! -> (path.to_path_buf(), err) +//! } +//! } +//! } +//! +//! fn openfile(path: &Path) -> Result<(), Error> { +//! try!(File::open(path).context(path)); +//! +//! // If we didn't have context, the line above would be written as; +//! // +//! // try!(File::open(path) +//! // .map_err(|err| Error::File(path.to_path_buf(), err))); +//! +//! Ok(()) +//! } +//! +//! # fn main() { +//! # openfile(Path::new("/etc/somefile")).ok(); +//! # } +//! ``` +//! +//! Each `context(a: A, b: B)` clause implements +//! `From> for Error`. Which means multiple `context` clauses +//! are a subject to the normal coherence rules. Unfortunately, we can't +//! provide full support of generics for the context, but you may either use a +//! lifetime `'a` for references or `AsRef` (the latter means `A: +//! AsRef`, and `Type` must be concrete). It's also occasionally useful +//! to use a tuple as a type of the first argument. +//! +//! You also need to `use quick_error::ResultExt` extension trait to get +//! working `.context()` method. +//! +//! More info on context in [this article](http://bit.ly/1PsuxDt). +//! +//! All forms of `from`, `display`, `description`, `cause`, and `context` +//! clauses can be combined and put in arbitrary order. Only `from` and +//! `context` can be used multiple times in single variant of enumeration. +//! Docstrings are also okay. Empty braces can be omitted as of quick_error +//! 0.1.3. +//! +//! # Private Enums +//! +//! Since quick-error 1.2.0 we have a way to make a private enum that is +//! wrapped by public structure: +//! +//! ```rust +//! #[macro_use] extern crate quick_error; +//! # fn main() {} +//! +//! quick_error! { +//! #[derive(Debug)] +//! pub enum PubError wraps ErrorEnum { +//! Variant1 {} +//! } +//! } +//! ``` +//! +//! This generates data structures like this +//! +//! ```rust +//! +//! pub struct PubError(ErrorEnum); +//! +//! enum ErrorEnum { +//! Variant1, +//! } +//! +//! ``` +//! +//! Which in turn allows you to export just `PubError` in your crate and keep +//! actual enumeration private to the crate. This is useful to keep backwards +//! compatibility for error types. Currently there is no shorcuts to define +//! error constructors for the inner type, but we consider adding some in +//! future versions. +//! +//! It's possible to declare internal enum as public too. +//! +//! + + +/// Main macro that does all the work +#[macro_export] +macro_rules! quick_error { + + ( $(#[$meta:meta])* + pub enum $name:ident { $($chunks:tt)* } + ) => { + quick_error!(SORT [pub enum $name $(#[$meta])* ] + items [] buf [] + queue [ $($chunks)* ]); + }; + ( $(#[$meta:meta])* + enum $name:ident { $($chunks:tt)* } + ) => { + quick_error!(SORT [enum $name $(#[$meta])* ] + items [] buf [] + queue [ $($chunks)* ]); + }; + + ( $(#[$meta:meta])* + pub enum $name:ident wraps $enum_name:ident { $($chunks:tt)* } + ) => { + quick_error!(WRAPPER $enum_name [ pub struct ] $name $(#[$meta])*); + quick_error!(SORT [enum $enum_name $(#[$meta])* ] + items [] buf [] + queue [ $($chunks)* ]); + }; + + ( $(#[$meta:meta])* + pub enum $name:ident wraps pub $enum_name:ident { $($chunks:tt)* } + ) => { + quick_error!(WRAPPER $enum_name [ pub struct ] $name $(#[$meta])*); + quick_error!(SORT [pub enum $enum_name $(#[$meta])* ] + items [] buf [] + queue [ $($chunks)* ]); + }; + ( $(#[$meta:meta])* + enum $name:ident wraps $enum_name:ident { $($chunks:tt)* } + ) => { + quick_error!(WRAPPER $enum_name [ struct ] $name $(#[$meta])*); + quick_error!(SORT [enum $enum_name $(#[$meta])* ] + items [] buf [] + queue [ $($chunks)* ]); + }; + + ( $(#[$meta:meta])* + enum $name:ident wraps pub $enum_name:ident { $($chunks:tt)* } + ) => { + quick_error!(WRAPPER $enum_name [ struct ] $name $(#[$meta])*); + quick_error!(SORT [pub enum $enum_name $(#[$meta])* ] + items [] buf [] + queue [ $($chunks)* ]); + }; + + + ( + WRAPPER $internal:ident [ $($strdef:tt)* ] $strname:ident + $(#[$meta:meta])* + ) => { + $(#[$meta])* + $($strdef)* $strname ( $internal ); + + impl ::std::fmt::Display for $strname { + fn fmt(&self, f: &mut ::std::fmt::Formatter) + -> ::std::fmt::Result + { + ::std::fmt::Display::fmt(&self.0, f) + } + } + + impl From<$internal> for $strname { + fn from(err: $internal) -> Self { + $strname(err) + } + } + + impl ::std::error::Error for $strname { + fn description(&self) -> &str { + self.0.description() + } + fn cause(&self) -> Option<&::std::error::Error> { + self.0.cause() + } + } + }; + + // Queue is empty, can do the work + (SORT [enum $name:ident $( #[$meta:meta] )*] + items [$($( #[$imeta:meta] )* + => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] + {$( $ifuncs:tt )*} )* ] + buf [ ] + queue [ ] + ) => { + quick_error!(ENUM_DEFINITION [enum $name $( #[$meta] )*] + body [] + queue [$($( #[$imeta] )* + => $iitem: $imode [$( $ivar: $ityp ),*] )*] + ); + quick_error!(IMPLEMENTATIONS $name {$( + $iitem: $imode [$(#[$imeta])*] [$( $ivar: $ityp ),*] {$( $ifuncs )*} + )*}); + $( + quick_error!(ERROR_CHECK $imode $($ifuncs)*); + )* + }; + (SORT [pub enum $name:ident $( #[$meta:meta] )*] + items [$($( #[$imeta:meta] )* + => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] + {$( $ifuncs:tt )*} )* ] + buf [ ] + queue [ ] + ) => { + quick_error!(ENUM_DEFINITION [pub enum $name $( #[$meta] )*] + body [] + queue [$($( #[$imeta] )* + => $iitem: $imode [$( $ivar: $ityp ),*] )*] + ); + quick_error!(IMPLEMENTATIONS $name {$( + $iitem: $imode [$(#[$imeta])*] [$( $ivar: $ityp ),*] {$( $ifuncs )*} + )*}); + $( + quick_error!(ERROR_CHECK $imode $($ifuncs)*); + )* + }; + // Add meta to buffer + (SORT [$( $def:tt )*] + items [$($( #[$imeta:meta] )* + => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] + {$( $ifuncs:tt )*} )* ] + buf [$( #[$bmeta:meta] )*] + queue [ #[$qmeta:meta] $( $tail:tt )*] + ) => { + quick_error!(SORT [$( $def )*] + items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )*] + buf [$( #[$bmeta] )* #[$qmeta] ] + queue [$( $tail )*]); + }; + // Add ident to buffer + (SORT [$( $def:tt )*] + items [$($( #[$imeta:meta] )* + => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] + {$( $ifuncs:tt )*} )* ] + buf [$( #[$bmeta:meta] )*] + queue [ $qitem:ident $( $tail:tt )*] + ) => { + quick_error!(SORT [$( $def )*] + items [$( $(#[$imeta])* + => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )*] + buf [$(#[$bmeta])* => $qitem : UNIT [ ] ] + queue [$( $tail )*]); + }; + // Flush buffer on meta after ident + (SORT [$( $def:tt )*] + items [$($( #[$imeta:meta] )* + => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] + {$( $ifuncs:tt )*} )* ] + buf [$( #[$bmeta:meta] )* + => $bitem:ident: $bmode:tt [$( $bvar:ident: $btyp:ty ),*] ] + queue [ #[$qmeta:meta] $( $tail:tt )*] + ) => { + quick_error!(SORT [$( $def )*] + enum [$( $(#[$emeta])* => $eitem $(( $($etyp),* ))* )* + $(#[$bmeta])* => $bitem: $bmode $(( $($btyp),* ))*] + items [$($( #[$imeta:meta] )* + => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )* + $bitem: $bmode [$( $bvar:$btyp ),*] {} ] + buf [ #[$qmeta] ] + queue [$( $tail )*]); + }; + // Add tuple enum-variant + (SORT [$( $def:tt )*] + items [$($( #[$imeta:meta] )* + => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] + {$( $ifuncs:tt )*} )* ] + buf [$( #[$bmeta:meta] )* => $bitem:ident: UNIT [ ] ] + queue [($( $qvar:ident: $qtyp:ty ),+) $( $tail:tt )*] + ) => { + quick_error!(SORT [$( $def )*] + items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )*] + buf [$( #[$bmeta] )* => $bitem: TUPLE [$( $qvar:$qtyp ),*] ] + queue [$( $tail )*] + ); + }; + // Add struct enum-variant - e.g. { descr: &'static str } + (SORT [$( $def:tt )*] + items [$($( #[$imeta:meta] )* + => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] + {$( $ifuncs:tt )*} )* ] + buf [$( #[$bmeta:meta] )* => $bitem:ident: UNIT [ ] ] + queue [{ $( $qvar:ident: $qtyp:ty ),+} $( $tail:tt )*] + ) => { + quick_error!(SORT [$( $def )*] + items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )*] + buf [$( #[$bmeta] )* => $bitem: STRUCT [$( $qvar:$qtyp ),*] ] + queue [$( $tail )*]); + }; + // Add struct enum-variant, with excess comma - e.g. { descr: &'static str, } + (SORT [$( $def:tt )*] + items [$($( #[$imeta:meta] )* + => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] + {$( $ifuncs:tt )*} )* ] + buf [$( #[$bmeta:meta] )* => $bitem:ident: UNIT [ ] ] + queue [{$( $qvar:ident: $qtyp:ty ),+ ,} $( $tail:tt )*] + ) => { + quick_error!(SORT [$( $def )*] + items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )*] + buf [$( #[$bmeta] )* => $bitem: STRUCT [$( $qvar:$qtyp ),*] ] + queue [$( $tail )*]); + }; + // Add braces and flush always on braces + (SORT [$( $def:tt )*] + items [$($( #[$imeta:meta] )* + => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] + {$( $ifuncs:tt )*} )* ] + buf [$( #[$bmeta:meta] )* + => $bitem:ident: $bmode:tt [$( $bvar:ident: $btyp:ty ),*] ] + queue [ {$( $qfuncs:tt )*} $( $tail:tt )*] + ) => { + quick_error!(SORT [$( $def )*] + items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )* + $(#[$bmeta])* => $bitem: $bmode [$( $bvar:$btyp ),*] {$( $qfuncs )*} ] + buf [ ] + queue [$( $tail )*]); + }; + // Flush buffer on double ident + (SORT [$( $def:tt )*] + items [$($( #[$imeta:meta] )* + => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] + {$( $ifuncs:tt )*} )* ] + buf [$( #[$bmeta:meta] )* + => $bitem:ident: $bmode:tt [$( $bvar:ident: $btyp:ty ),*] ] + queue [ $qitem:ident $( $tail:tt )*] + ) => { + quick_error!(SORT [$( $def )*] + items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )* + $(#[$bmeta])* => $bitem: $bmode [$( $bvar:$btyp ),*] {} ] + buf [ => $qitem : UNIT [ ] ] + queue [$( $tail )*]); + }; + // Flush buffer on end + (SORT [$( $def:tt )*] + items [$($( #[$imeta:meta] )* + => $iitem:ident: $imode:tt [$( $ivar:ident: $ityp:ty ),*] + {$( $ifuncs:tt )*} )* ] + buf [$( #[$bmeta:meta] )* + => $bitem:ident: $bmode:tt [$( $bvar:ident: $btyp:ty ),*] ] + queue [ ] + ) => { + quick_error!(SORT [$( $def )*] + items [$( $(#[$imeta])* => $iitem: $imode [$( $ivar:$ityp ),*] {$( $ifuncs )*} )* + $(#[$bmeta])* => $bitem: $bmode [$( $bvar:$btyp ),*] {} ] + buf [ ] + queue [ ]); + }; + // Public enum (Queue Empty) + (ENUM_DEFINITION [pub enum $name:ident $( #[$meta:meta] )*] + body [$($( #[$imeta:meta] )* + => $iitem:ident ($(($( $ttyp:ty ),+))*) {$({$( $svar:ident: $styp:ty ),*})*} )* ] + queue [ ] + ) => { + #[allow(unknown_lints)] // no unused_doc_comments in older rust + #[allow(unused_doc_comment)] + $(#[$meta])* + pub enum $name { + $( + $(#[$imeta])* + $iitem $(($( $ttyp ),*))* $({$( $svar: $styp ),*})*, + )* + } + }; + // Private enum (Queue Empty) + (ENUM_DEFINITION [enum $name:ident $( #[$meta:meta] )*] + body [$($( #[$imeta:meta] )* + => $iitem:ident ($(($( $ttyp:ty ),+))*) {$({$( $svar:ident: $styp:ty ),*})*} )* ] + queue [ ] + ) => { + #[allow(unknown_lints)] // no unused_doc_comments in older rust + #[allow(unused_doc_comment)] + $(#[$meta])* + enum $name { + $( + $(#[$imeta])* + $iitem $(($( $ttyp ),*))* $({$( $svar: $styp ),*})*, + )* + } + }; + // Unit variant + (ENUM_DEFINITION [$( $def:tt )*] + body [$($( #[$imeta:meta] )* + => $iitem:ident ($(($( $ttyp:ty ),+))*) {$({$( $svar:ident: $styp:ty ),*})*} )* ] + queue [$( #[$qmeta:meta] )* + => $qitem:ident: UNIT [ ] $( $queue:tt )*] + ) => { + quick_error!(ENUM_DEFINITION [ $($def)* ] + body [$($( #[$imeta] )* => $iitem ($(($( $ttyp ),+))*) {$({$( $svar: $styp ),*})*} )* + $( #[$qmeta] )* => $qitem () {} ] + queue [ $($queue)* ] + ); + }; + // Tuple variant + (ENUM_DEFINITION [$( $def:tt )*] + body [$($( #[$imeta:meta] )* + => $iitem:ident ($(($( $ttyp:ty ),+))*) {$({$( $svar:ident: $styp:ty ),*})*} )* ] + queue [$( #[$qmeta:meta] )* + => $qitem:ident: TUPLE [$( $qvar:ident: $qtyp:ty ),+] $( $queue:tt )*] + ) => { + quick_error!(ENUM_DEFINITION [ $($def)* ] + body [$($( #[$imeta] )* => $iitem ($(($( $ttyp ),+))*) {$({$( $svar: $styp ),*})*} )* + $( #[$qmeta] )* => $qitem (($( $qtyp ),*)) {} ] + queue [ $($queue)* ] + ); + }; + // Struct variant + (ENUM_DEFINITION [$( $def:tt )*] + body [$($( #[$imeta:meta] )* + => $iitem:ident ($(($( $ttyp:ty ),+))*) {$({$( $svar:ident: $styp:ty ),*})*} )* ] + queue [$( #[$qmeta:meta] )* + => $qitem:ident: STRUCT [$( $qvar:ident: $qtyp:ty ),*] $( $queue:tt )*] + ) => { + quick_error!(ENUM_DEFINITION [ $($def)* ] + body [$($( #[$imeta] )* => $iitem ($(($( $ttyp ),+))*) {$({$( $svar: $styp ),*})*} )* + $( #[$qmeta] )* => $qitem () {{$( $qvar: $qtyp ),*}} ] + queue [ $($queue)* ] + ); + }; + (IMPLEMENTATIONS + $name:ident {$( + $item:ident: $imode:tt [$(#[$imeta:meta])*] [$( $var:ident: $typ:ty ),*] {$( $funcs:tt )*} + )*} + ) => { + #[allow(unused)] + #[allow(unknown_lints)] // no unused_doc_comments in older rust + #[allow(unused_doc_comment)] + impl ::std::fmt::Display for $name { + fn fmt(&self, fmt: &mut ::std::fmt::Formatter) + -> ::std::fmt::Result + { + match *self { + $( + $(#[$imeta])* + quick_error!(ITEM_PATTERN + $name $item: $imode [$( ref $var ),*] + ) => { + let display_fn = quick_error!(FIND_DISPLAY_IMPL + $name $item: $imode + {$( $funcs )*}); + + display_fn(self, fmt) + } + )* + } + } + } + #[allow(unused)] + #[allow(unknown_lints)] // no unused_doc_comments in older rust + #[allow(unused_doc_comment)] + impl ::std::error::Error for $name { + fn description(&self) -> &str { + match *self { + $( + $(#[$imeta])* + quick_error!(ITEM_PATTERN + $name $item: $imode [$( ref $var ),*] + ) => { + quick_error!(FIND_DESCRIPTION_IMPL + $item: $imode self fmt [$( $var ),*] + {$( $funcs )*}) + } + )* + } + } + fn cause(&self) -> Option<&::std::error::Error> { + match *self { + $( + $(#[$imeta])* + quick_error!(ITEM_PATTERN + $name $item: $imode [$( ref $var ),*] + ) => { + quick_error!(FIND_CAUSE_IMPL + $item: $imode [$( $var ),*] + {$( $funcs )*}) + } + )* + } + } + } + $( + quick_error!(FIND_FROM_IMPL + $name $item: $imode [$( $var:$typ ),*] + {$( $funcs )*}); + )* + $( + quick_error!(FIND_CONTEXT_IMPL + $name $item: $imode [$( $var:$typ ),*] + {$( $funcs )*}); + )* + }; + (FIND_DISPLAY_IMPL $name:ident $item:ident: $imode:tt + { display($self_:tt) -> ($( $exprs:tt )*) $( $tail:tt )*} + ) => { + |quick_error!(IDENT $self_): &$name, f: &mut ::std::fmt::Formatter| { write!(f, $( $exprs )*) } + }; + (FIND_DISPLAY_IMPL $name:ident $item:ident: $imode:tt + { display($pattern:expr) $( $tail:tt )*} + ) => { + |_, f: &mut ::std::fmt::Formatter| { write!(f, $pattern) } + }; + (FIND_DISPLAY_IMPL $name:ident $item:ident: $imode:tt + { display($pattern:expr, $( $exprs:tt )*) $( $tail:tt )*} + ) => { + |_, f: &mut ::std::fmt::Formatter| { write!(f, $pattern, $( $exprs )*) } + }; + (FIND_DISPLAY_IMPL $name:ident $item:ident: $imode:tt + { $t:tt $( $tail:tt )*} + ) => { + quick_error!(FIND_DISPLAY_IMPL + $name $item: $imode + {$( $tail )*}) + }; + (FIND_DISPLAY_IMPL $name:ident $item:ident: $imode:tt + { } + ) => { + |self_: &$name, f: &mut ::std::fmt::Formatter| { + write!(f, "{}", ::std::error::Error::description(self_)) + } + }; + (FIND_DESCRIPTION_IMPL $item:ident: $imode:tt $me:ident $fmt:ident + [$( $var:ident ),*] + { description($expr:expr) $( $tail:tt )*} + ) => { + $expr + }; + (FIND_DESCRIPTION_IMPL $item:ident: $imode:tt $me:ident $fmt:ident + [$( $var:ident ),*] + { $t:tt $( $tail:tt )*} + ) => { + quick_error!(FIND_DESCRIPTION_IMPL + $item: $imode $me $fmt [$( $var ),*] + {$( $tail )*}) + }; + (FIND_DESCRIPTION_IMPL $item:ident: $imode:tt $me:ident $fmt:ident + [$( $var:ident ),*] + { } + ) => { + stringify!($item) + }; + (FIND_CAUSE_IMPL $item:ident: $imode:tt + [$( $var:ident ),*] + { cause($expr:expr) $( $tail:tt )*} + ) => { + Some($expr) + }; + (FIND_CAUSE_IMPL $item:ident: $imode:tt + [$( $var:ident ),*] + { $t:tt $( $tail:tt )*} + ) => { + quick_error!(FIND_CAUSE_IMPL + $item: $imode [$( $var ),*] + { $($tail)* }) + }; + (FIND_CAUSE_IMPL $item:ident: $imode:tt + [$( $var:ident ),*] + { } + ) => { + None + }; + // ----------------------------- FROM IMPL -------------------------- + (FIND_FROM_IMPL $name:ident $item:ident: $imode:tt + [$( $var:ident: $typ:ty ),*] + { from() $( $tail:tt )*} + ) => { + $( + impl From<$typ> for $name { + fn from($var: $typ) -> $name { + $name::$item($var) + } + } + )* + quick_error!(FIND_FROM_IMPL + $name $item: $imode [$( $var:$typ ),*] + {$( $tail )*}); + }; + (FIND_FROM_IMPL $name:ident $item:ident: UNIT + [ ] + { from($ftyp:ty) $( $tail:tt )*} + ) => { + impl From<$ftyp> for $name { + fn from(_discarded_error: $ftyp) -> $name { + $name::$item + } + } + quick_error!(FIND_FROM_IMPL + $name $item: UNIT [ ] + {$( $tail )*}); + }; + (FIND_FROM_IMPL $name:ident $item:ident: TUPLE + [$( $var:ident: $typ:ty ),*] + { from($fvar:ident: $ftyp:ty) -> ($( $texpr:expr ),*) $( $tail:tt )*} + ) => { + impl From<$ftyp> for $name { + fn from($fvar: $ftyp) -> $name { + $name::$item($( $texpr ),*) + } + } + quick_error!(FIND_FROM_IMPL + $name $item: TUPLE [$( $var:$typ ),*] + { $($tail)* }); + }; + (FIND_FROM_IMPL $name:ident $item:ident: STRUCT + [$( $var:ident: $typ:ty ),*] + { from($fvar:ident: $ftyp:ty) -> {$( $tvar:ident: $texpr:expr ),*} $( $tail:tt )*} + ) => { + impl From<$ftyp> for $name { + fn from($fvar: $ftyp) -> $name { + $name::$item { + $( $tvar: $texpr ),* + } + } + } + quick_error!(FIND_FROM_IMPL + $name $item: STRUCT [$( $var:$typ ),*] + { $($tail)* }); + }; + (FIND_FROM_IMPL $name:ident $item:ident: $imode:tt + [$( $var:ident: $typ:ty ),*] + { $t:tt $( $tail:tt )*} + ) => { + quick_error!(FIND_FROM_IMPL + $name $item: $imode [$( $var:$typ ),*] + {$( $tail )*} + ); + }; + (FIND_FROM_IMPL $name:ident $item:ident: $imode:tt + [$( $var:ident: $typ:ty ),*] + { } + ) => { + }; + // ----------------------------- CONTEXT IMPL -------------------------- + (FIND_CONTEXT_IMPL $name:ident $item:ident: TUPLE + [$( $var:ident: $typ:ty ),*] + { context($cvar:ident: AsRef<$ctyp:ty>, $fvar:ident: $ftyp:ty) + -> ($( $texpr:expr ),*) $( $tail:tt )* } + ) => { + impl> From<$crate::Context> for $name { + fn from( + $crate::Context($cvar, $fvar): $crate::Context) + -> $name + { + $name::$item($( $texpr ),*) + } + } + quick_error!(FIND_CONTEXT_IMPL + $name $item: TUPLE [$( $var:$typ ),*] + { $($tail)* }); + }; + (FIND_CONTEXT_IMPL $name:ident $item:ident: TUPLE + [$( $var:ident: $typ:ty ),*] + { context($cvar:ident: $ctyp:ty, $fvar:ident: $ftyp:ty) + -> ($( $texpr:expr ),*) $( $tail:tt )* } + ) => { + impl<'a> From<$crate::Context<$ctyp, $ftyp>> for $name { + fn from( + $crate::Context($cvar, $fvar): $crate::Context<$ctyp, $ftyp>) + -> $name + { + $name::$item($( $texpr ),*) + } + } + quick_error!(FIND_CONTEXT_IMPL + $name $item: TUPLE [$( $var:$typ ),*] + { $($tail)* }); + }; + (FIND_CONTEXT_IMPL $name:ident $item:ident: STRUCT + [$( $var:ident: $typ:ty ),*] + { context($cvar:ident: AsRef<$ctyp:ty>, $fvar:ident: $ftyp:ty) + -> {$( $tvar:ident: $texpr:expr ),*} $( $tail:tt )* } + ) => { + impl> From<$crate::Context> for $name { + fn from( + $crate::Context($cvar, $fvar): $crate::Context<$ctyp, $ftyp>) + -> $name + { + $name::$item { + $( $tvar: $texpr ),* + } + } + } + quick_error!(FIND_CONTEXT_IMPL + $name $item: STRUCT [$( $var:$typ ),*] + { $($tail)* }); + }; + (FIND_CONTEXT_IMPL $name:ident $item:ident: STRUCT + [$( $var:ident: $typ:ty ),*] + { context($cvar:ident: $ctyp:ty, $fvar:ident: $ftyp:ty) + -> {$( $tvar:ident: $texpr:expr ),*} $( $tail:tt )* } + ) => { + impl<'a> From<$crate::Context<$ctyp, $ftyp>> for $name { + fn from( + $crate::Context($cvar, $fvar): $crate::Context<$ctyp, $ftyp>) + -> $name + { + $name::$item { + $( $tvar: $texpr ),* + } + } + } + quick_error!(FIND_CONTEXT_IMPL + $name $item: STRUCT [$( $var:$typ ),*] + { $($tail)* }); + }; + (FIND_CONTEXT_IMPL $name:ident $item:ident: $imode:tt + [$( $var:ident: $typ:ty ),*] + { $t:tt $( $tail:tt )*} + ) => { + quick_error!(FIND_CONTEXT_IMPL + $name $item: $imode [$( $var:$typ ),*] + {$( $tail )*} + ); + }; + (FIND_CONTEXT_IMPL $name:ident $item:ident: $imode:tt + [$( $var:ident: $typ:ty ),*] + { } + ) => { + }; + // ----------------------------- ITEM IMPL -------------------------- + (ITEM_BODY $(#[$imeta:meta])* $item:ident: UNIT + ) => { }; + (ITEM_BODY $(#[$imeta:meta])* $item:ident: TUPLE + [$( $typ:ty ),*] + ) => { + ($( $typ ),*) + }; + (ITEM_BODY $(#[$imeta:meta])* $item:ident: STRUCT + [$( $var:ident: $typ:ty ),*] + ) => { + {$( $var:$typ ),*} + }; + (ITEM_PATTERN $name:ident $item:ident: UNIT [] + ) => { + $name::$item + }; + (ITEM_PATTERN $name:ident $item:ident: TUPLE + [$( ref $var:ident ),*] + ) => { + $name::$item ($( ref $var ),*) + }; + (ITEM_PATTERN $name:ident $item:ident: STRUCT + [$( ref $var:ident ),*] + ) => { + $name::$item {$( ref $var ),*} + }; + // This one should match all allowed sequences in "funcs" but not match + // anything else. + // This is to contrast FIND_* clauses which just find stuff they need and + // skip everything else completely + (ERROR_CHECK $imode:tt display($self_:tt) -> ($( $exprs:tt )*) $( $tail:tt )*) + => { quick_error!(ERROR_CHECK $imode $($tail)*); }; + (ERROR_CHECK $imode:tt display($pattern: expr) $( $tail:tt )*) + => { quick_error!(ERROR_CHECK $imode $($tail)*); }; + (ERROR_CHECK $imode:tt display($pattern: expr, $( $exprs:tt )*) $( $tail:tt )*) + => { quick_error!(ERROR_CHECK $imode $($tail)*); }; + (ERROR_CHECK $imode:tt description($expr:expr) $( $tail:tt )*) + => { quick_error!(ERROR_CHECK $imode $($tail)*); }; + (ERROR_CHECK $imode:tt cause($expr:expr) $($tail:tt)*) + => { quick_error!(ERROR_CHECK $imode $($tail)*); }; + (ERROR_CHECK $imode:tt from() $($tail:tt)*) + => { quick_error!(ERROR_CHECK $imode $($tail)*); }; + (ERROR_CHECK $imode:tt from($ftyp:ty) $($tail:tt)*) + => { quick_error!(ERROR_CHECK $imode $($tail)*); }; + (ERROR_CHECK TUPLE from($fvar:ident: $ftyp:ty) -> ($( $e:expr ),*) $( $tail:tt )*) + => { quick_error!(ERROR_CHECK TUPLE $($tail)*); }; + (ERROR_CHECK STRUCT from($fvar:ident: $ftyp:ty) -> {$( $v:ident: $e:expr ),*} $( $tail:tt )*) + => { quick_error!(ERROR_CHECK STRUCT $($tail)*); }; + + (ERROR_CHECK TUPLE context($cvar:ident: $ctyp:ty, $fvar:ident: $ftyp:ty) + -> ($( $e:expr ),*) $( $tail:tt )*) + => { quick_error!(ERROR_CHECK TUPLE $($tail)*); }; + (ERROR_CHECK STRUCT context($cvar:ident: $ctyp:ty, $fvar:ident: $ftyp:ty) + -> {$( $v:ident: $e:expr ),*} $( $tail:tt )*) + => { quick_error!(ERROR_CHECK STRUCT $($tail)*); }; + + (ERROR_CHECK $imode:tt ) => {}; + // Utility functions + (IDENT $ident:ident) => { $ident } +} + + +/// Generic context type +/// +/// Used mostly as a transport for `ResultExt::context` method +#[derive(Debug)] +pub struct Context(pub X, pub E); + +/// Result extension trait adding a `context` method +pub trait ResultExt { + /// The method is use to add context information to current operation + /// + /// The context data is then used in error constructor to store additional + /// information within error. For example, you may add a filename as a + /// context for file operation. See crate documentation for the actual + /// example. + fn context(self, x: X) -> Result>; +} + +impl ResultExt for Result { + fn context(self, x: X) -> Result> { + self.map_err(|e| Context(x, e)) + } +} + + + +#[cfg(test)] +mod test { + use std::num::{ParseFloatError, ParseIntError}; + use std::str::Utf8Error; + use std::string::FromUtf8Error; + use std::error::Error; + use std::path::{Path, PathBuf}; + + use super::ResultExt; + + quick_error! { + #[derive(Debug)] + pub enum Bare { + One + Two + } + } + + #[test] + fn bare_item_direct() { + assert_eq!(format!("{}", Bare::One), "One".to_string()); + assert_eq!(format!("{:?}", Bare::One), "One".to_string()); + assert_eq!(Bare::One.description(), "One".to_string()); + assert!(Bare::One.cause().is_none()); + } + #[test] + fn bare_item_trait() { + let err: &Error = &Bare::Two; + assert_eq!(format!("{}", err), "Two".to_string()); + assert_eq!(format!("{:?}", err), "Two".to_string()); + assert_eq!(err.description(), "Two".to_string()); + assert!(err.cause().is_none()); + } + + quick_error! { + #[derive(Debug)] + pub enum Wrapper wraps Wrapped { + One + Two(s: String) { + display("two: {}", s) + from() + } + } + } + + #[test] + fn wrapper() { + assert_eq!(format!("{}", Wrapper::from(Wrapped::One)), + "One".to_string()); + assert_eq!(format!("{}", + Wrapper::from(Wrapped::from(String::from("hello")))), + "two: hello".to_string()); + assert_eq!(format!("{:?}", Wrapper::from(Wrapped::One)), + "Wrapper(One)".to_string()); + assert_eq!(Wrapper::from(Wrapped::One).description(), + "One".to_string()); + } + + quick_error! { + #[derive(Debug, PartialEq)] + pub enum TupleWrapper { + /// ParseFloat Error + ParseFloatError(err: ParseFloatError) { + from() + description(err.description()) + display("parse float error: {err}", err=err) + cause(err) + } + Other(descr: &'static str) { + description(descr) + display("Error: {}", descr) + } + /// FromUtf8 Error + FromUtf8Error(err: Utf8Error, source: Vec) { + cause(err) + display(me) -> ("{desc} at index {pos}: {err}", desc=me.description(), pos=err.valid_up_to(), err=err) + description("utf8 error") + from(err: FromUtf8Error) -> (err.utf8_error().clone(), err.into_bytes()) + } + Discard { + from(&'static str) + } + Singleton { + display("Just a string") + } + } + } + + #[test] + fn tuple_wrapper_err() { + let cause = "one and a half times pi".parse::().unwrap_err(); + let err = TupleWrapper::ParseFloatError(cause.clone()); + assert_eq!(format!("{}", err), format!("parse float error: {}", cause)); + assert_eq!(format!("{:?}", err), format!("ParseFloatError({:?})", cause)); + assert_eq!(err.description(), cause.description()); + assert_eq!(format!("{:?}", err.cause().unwrap()), format!("{:?}", cause)); + } + + #[test] + fn tuple_wrapper_trait_str() { + let desc = "hello"; + let err: &Error = &TupleWrapper::Other(desc); + assert_eq!(format!("{}", err), format!("Error: {}", desc)); + assert_eq!(format!("{:?}", err), format!("Other({:?})", desc)); + assert_eq!(err.description(), desc); + assert!(err.cause().is_none()); + } + + #[test] + fn tuple_wrapper_trait_two_fields() { + let invalid_utf8: Vec = vec![0, 159, 146, 150]; + let cause = String::from_utf8(invalid_utf8.clone()).unwrap_err().utf8_error(); + let err: &Error = &TupleWrapper::FromUtf8Error(cause.clone(), invalid_utf8.clone()); + assert_eq!(format!("{}", err), format!("{desc} at index {pos}: {cause}", desc=err.description(), pos=cause.valid_up_to(), cause=cause)); + assert_eq!(format!("{:?}", err), format!("FromUtf8Error({:?}, {:?})", cause, invalid_utf8)); + assert_eq!(err.description(), "utf8 error"); + assert_eq!(format!("{:?}", err.cause().unwrap()), format!("{:?}", cause)); + } + + #[test] + fn tuple_wrapper_from() { + let cause = "one and a half times pi".parse::().unwrap_err(); + let err = TupleWrapper::ParseFloatError(cause.clone()); + let err_from: TupleWrapper = From::from(cause); + assert_eq!(err_from, err); + } + + #[test] + fn tuple_wrapper_custom_from() { + let invalid_utf8: Vec = vec![0, 159, 146, 150]; + let cause = String::from_utf8(invalid_utf8.clone()).unwrap_err(); + let err = TupleWrapper::FromUtf8Error(cause.utf8_error().clone(), invalid_utf8); + let err_from: TupleWrapper = From::from(cause); + assert_eq!(err_from, err); + } + + #[test] + fn tuple_wrapper_discard() { + let err: TupleWrapper = From::from("hello"); + assert_eq!(format!("{}", err), format!("Discard")); + assert_eq!(format!("{:?}", err), format!("Discard")); + assert_eq!(err.description(), "Discard"); + assert!(err.cause().is_none()); + } + + #[test] + fn tuple_wrapper_singleton() { + let err: TupleWrapper = TupleWrapper::Singleton; + assert_eq!(format!("{}", err), format!("Just a string")); + assert_eq!(format!("{:?}", err), format!("Singleton")); + assert_eq!(err.description(), "Singleton"); + assert!(err.cause().is_none()); + } + + quick_error! { + #[derive(Debug, PartialEq)] + pub enum StructWrapper { + // Utf8 Error + Utf8Error{ err: Utf8Error, hint: Option<&'static str> } { + cause(err) + display(me) -> ("{desc} at index {pos}: {err}", desc=me.description(), pos=err.valid_up_to(), err=err) + description("utf8 error") + from(err: Utf8Error) -> { err: err, hint: None } + } + // Utf8 Error + ExcessComma { descr: &'static str, } { + description(descr) + display("Error: {}", descr) + } + } + } + + #[test] + fn struct_wrapper_err() { + let invalid_utf8: Vec = vec![0, 159, 146, 150]; + let cause = String::from_utf8(invalid_utf8.clone()).unwrap_err().utf8_error(); + let err: &Error = &StructWrapper::Utf8Error{ err: cause.clone(), hint: Some("nonsense") }; + assert_eq!(format!("{}", err), format!("{desc} at index {pos}: {cause}", desc=err.description(), pos=cause.valid_up_to(), cause=cause)); + assert_eq!(format!("{:?}", err), format!("Utf8Error {{ err: {:?}, hint: {:?} }}", cause, Some("nonsense"))); + assert_eq!(err.description(), "utf8 error"); + assert_eq!(format!("{:?}", err.cause().unwrap()), format!("{:?}", cause)); + } + + #[test] + fn struct_wrapper_struct_from() { + let invalid_utf8: Vec = vec![0, 159, 146, 150]; + let cause = String::from_utf8(invalid_utf8.clone()).unwrap_err().utf8_error(); + let err = StructWrapper::Utf8Error{ err: cause.clone(), hint: None }; + let err_from: StructWrapper = From::from(cause); + assert_eq!(err_from, err); + } + + #[test] + fn struct_wrapper_excess_comma() { + let descr = "hello"; + let err = StructWrapper::ExcessComma { descr: descr }; + assert_eq!(format!("{}", err), format!("Error: {}", descr)); + assert_eq!(format!("{:?}", err), format!("ExcessComma {{ descr: {:?} }}", descr)); + assert_eq!(err.description(), descr); + assert!(err.cause().is_none()); + } + + quick_error! { + #[derive(Debug)] + pub enum ContextErr { + Float(src: String, err: ParseFloatError) { + context(s: &'a str, e: ParseFloatError) -> (s.to_string(), e) + display("Float error {:?}: {}", src, err) + } + Int { src: String, err: ParseIntError } { + context(s: &'a str, e: ParseIntError) + -> {src: s.to_string(), err: e} + display("Int error {:?}: {}", src, err) + } + Utf8(path: PathBuf, err: Utf8Error) { + context(p: AsRef, e: Utf8Error) + -> (p.as_ref().to_path_buf(), e) + display("Path error at {:?}: {}", path, err) + } + Utf8Str(s: String, err: ::std::io::Error) { + context(s: AsRef, e: ::std::io::Error) + -> (s.as_ref().to_string(), e) + display("Str error {:?}: {}", s, err) + } + } + } + + #[test] + fn parse_float_error() { + fn parse_float(s: &str) -> Result { + Ok(try!(s.parse().context(s))) + } + assert_eq!(format!("{}", parse_float("12ab").unwrap_err()), + r#"Float error "12ab": invalid float literal"#); + } + + #[test] + fn parse_int_error() { + fn parse_int(s: &str) -> Result { + Ok(try!(s.parse().context(s))) + } + assert_eq!(format!("{}", parse_int("12.5").unwrap_err()), + r#"Int error "12.5": invalid digit found in string"#); + } + + #[test] + fn debug_context() { + fn parse_int(s: &str) -> i32 { + s.parse().context(s).unwrap() + } + assert_eq!(parse_int("12"), 12); + assert_eq!(format!("{:?}", "x".parse::().context("x")), + r#"Err(Context("x", ParseIntError { kind: InvalidDigit }))"#); + } + + #[test] + fn path_context() { + fn parse_utf>(s: &[u8], p: P) + -> Result<(), ContextErr> + { + try!(::std::str::from_utf8(s).context(p)); + Ok(()) + } + let etext = parse_utf(b"a\x80\x80", "/etc").unwrap_err().to_string(); + assert!(etext.starts_with( + "Path error at \"/etc\": invalid utf-8")); + let etext = parse_utf(b"\x80\x80", PathBuf::from("/tmp")).unwrap_err() + .to_string(); + assert!(etext.starts_with( + "Path error at \"/tmp\": invalid utf-8")); + } + + #[test] + fn conditional_compilation() { + quick_error! { + #[allow(dead_code)] + #[derive(Debug)] + pub enum Test { + #[cfg(feature = "foo")] + Variant + } + } + } +} diff -Nru cargo-0.25.0/vendor/quick-error-1.2.1/.travis.yml cargo-0.26.0/vendor/quick-error-1.2.1/.travis.yml --- cargo-0.25.0/vendor/quick-error-1.2.1/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quick-error-1.2.1/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,34 @@ +sudo: false +dist: trusty +language: rust + +cache: +- cargo + +before_cache: +- rm -r $TRAVIS_BUILD_DIR/target/debug + +jobs: + include: + - os: linux + rust: stable + - os: linux + rust: beta + - os: linux + rust: nightly + + # deploy + - stage: publish + os: linux + rust: stable + env: + # CARGO_TOKEN + - secure: "tYrt4NUyp3jgpIO6k5zqBoSDO7e6j79IS0jRgAgeoAxfM6V36kU+xLM266mXeiXhYK/p4MjtjAnF7VmQwQklnkOXibTNnwRMkJLodl9WGTK9UxLrGEC7ZUS6QywvhOQEu2ZbAsYESw5+o3vLHZouxm1JfSSSoG/IfqiEIAvqlCmP2gync1nZ+gWSjPuEkUDAIlkCKc6yUvFA+qexuCnITTyKOjdBrnBIX9yZ5tPPZa/RAd/GqQwTf3oXhqZraxP6MwxFFjDNQz4dt+64Ew9odtXjgf0StoqOzb5FzWalbQN/hfvfRfAEs7C1Y6s3N+xMLPCmKTML0AmmGLj52KzVtf5TbxAonC/i8oRb+Yv6l+TloZEJnfn1VTozVQFt2FBabPeKN0NA3Rn3V1YF50sf9RzLD9R8Oksk1C3SuKIRWuUK6r98HXMT4Hu7SAk1T88O9btiiehspUfOhvaoRxeTuXsxoezTwKoKh2T/m989z6w+hPDS1LedULxQQjztxBp7EAVUGnBNxSNFX3SUuReFDY3AVFdPOLomi9XEAKv4i3yDmQJFZ7J9XQXITnWgtKdpfqFW7HlhyPlpLLRxWxfCrK7bP5LmHzWss7fR5zDd5FXUbHLre15DXXLbdPp8FTFEWoDV0p/EIIqUIUamlI1Ny1zQCD0PxhXLUuD+I+WzKpg=" + install: true + script: true + + deploy: + - provider: script + script: 'cargo publish --verbose --token=$CARGO_TOKEN' + on: + tags: true diff -Nru cargo-0.25.0/vendor/quick-error-1.2.1/vagga.yaml cargo-0.26.0/vendor/quick-error-1.2.1/vagga.yaml --- cargo-0.25.0/vendor/quick-error-1.2.1/vagga.yaml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quick-error-1.2.1/vagga.yaml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,36 @@ +commands: + + cargo: !Command + description: Run any cargo command + container: ubuntu + run: [cargo] + + test: !Command + description: Run unit tests + container: ubuntu + run: [cargo, test] + + _bulk: !Command + description: Run `bulk` command (for version bookkeeping) + container: ubuntu + run: [bulk] + +containers: + + ubuntu: + setup: + - !Ubuntu xenial + - !Install [ca-certificates, build-essential, vim] + + - !TarInstall + url: "https://static.rust-lang.org/dist/rust-1.16.0-x86_64-unknown-linux-gnu.tar.gz" + script: "./install.sh --prefix=/usr \ + --components=rustc,rust-std-x86_64-unknown-linux-gnu,cargo" + - &bulk !Tar + url: "https://github.com/tailhook/bulk/releases/download/v0.4.9/bulk-v0.4.9.tar.gz" + sha256: 23471a9986274bb4b7098c03e2eb7e1204171869b72c45385fcee1c64db2d111 + path: / + + environ: + HOME: /work/target + USER: pc diff -Nru cargo-0.25.0/vendor/quote-0.5.1/.cargo-checksum.json cargo-0.26.0/vendor/quote-0.5.1/.cargo-checksum.json --- cargo-0.25.0/vendor/quote-0.5.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quote-0.5.1/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"7b0ff51282f28dc1b53fd154298feaa2e77c5ea0dba68e1fd8b03b72fbe13d2a"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/quote-0.5.1/Cargo.toml cargo-0.26.0/vendor/quote-0.5.1/Cargo.toml --- cargo-0.25.0/vendor/quote-0.5.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quote-0.5.1/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,30 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "quote" +version = "0.5.1" +authors = ["David Tolnay "] +include = ["Cargo.toml", "src/**/*.rs", "tests/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] +description = "Quasi-quoting macro quote!(...)" +documentation = "https://docs.rs/quote/" +readme = "README.md" +keywords = ["syn"] +license = "MIT/Apache-2.0" +repository = "https://github.com/dtolnay/quote" +[dependencies.proc-macro2] +version = "0.3" +default-features = false + +[features] +default = ["proc-macro"] +proc-macro = ["proc-macro2/proc-macro"] diff -Nru cargo-0.25.0/vendor/quote-0.5.1/LICENSE-APACHE cargo-0.26.0/vendor/quote-0.5.1/LICENSE-APACHE --- cargo-0.25.0/vendor/quote-0.5.1/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quote-0.5.1/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/quote-0.5.1/LICENSE-MIT cargo-0.26.0/vendor/quote-0.5.1/LICENSE-MIT --- cargo-0.25.0/vendor/quote-0.5.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quote-0.5.1/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2016 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/quote-0.5.1/README.md cargo-0.26.0/vendor/quote-0.5.1/README.md --- cargo-0.25.0/vendor/quote-0.5.1/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quote-0.5.1/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,135 @@ +Rust Quasi-Quoting +================== + +[![Build Status](https://api.travis-ci.org/dtolnay/quote.svg?branch=master)](https://travis-ci.org/dtolnay/quote) +[![Latest Version](https://img.shields.io/crates/v/quote.svg)](https://crates.io/crates/quote) +[![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/quote/) + +This crate provides the [`quote!`] macro for turning Rust syntax tree data +structures into tokens of source code. + +[`quote!`]: https://docs.rs/quote/0.5/quote/macro.quote.html + +Procedural macros in Rust receive a stream of tokens as input, execute arbitrary +Rust code to determine how to manipulate those tokens, and produce a stream of +tokens to hand back to the compiler to compile into the caller's crate. +Quasi-quoting is a solution to one piece of that -- producing tokens to return +to the compiler. + +The idea of quasi-quoting is that we write *code* that we treat as *data*. +Within the `quote!` macro, we can write what looks like code to our text editor +or IDE. We get all the benefits of the editor's brace matching, syntax +highlighting, indentation, and maybe autocompletion. But rather than compiling +that as code into the current crate, we can treat it as data, pass it around, +mutate it, and eventually hand it back to the compiler as tokens to compile into +the macro caller's crate. + +This crate is motivated by the procedural macro use case, but is a +general-purpose Rust quasi-quoting library and is not specific to procedural +macros. + +*Version requirement: Quote supports any compiler version back to Rust's very +first support for procedural macros in Rust 1.15.0.* + +```toml +[dependencies] +quote = "0.5" +``` + +```rust +#[macro_use] +extern crate quote; +``` + +## Syntax + +The quote crate provides a [`quote!`] macro within which you can write Rust code +that gets packaged into a [`quote::Tokens`] and can be treated as data. You +should think of `Tokens` as representing a fragment of Rust source code. Call +`to_string()` on a `Tokens` to get back the fragment of source code as a string, +or call `into()` to stream them as a `TokenStream` back to the compiler in a +procedural macro. + +[`quote::Tokens`]: https://docs.rs/quote/0.5/quote/struct.Tokens.html + +Within the `quote!` macro, interpolation is done with `#var`. Any type +implementing the [`quote::ToTokens`] trait can be interpolated. This includes +most Rust primitive types as well as most of the syntax tree types from [`syn`]. + +[`quote::ToTokens`]: https://docs.rs/quote/0.5/quote/trait.ToTokens.html +[`syn`]: https://github.com/dtolnay/syn + +```rust +let tokens = quote! { + struct SerializeWith #generics #where_clause { + value: &'a #field_ty, + phantom: ::std::marker::PhantomData<#item_ty>, + } + + impl #generics serde::Serialize for SerializeWith #generics #where_clause { + fn serialize(&self, s: &mut S) -> Result<(), S::Error> + where S: serde::Serializer + { + #path(self.value, s) + } + } + + SerializeWith { + value: #value, + phantom: ::std::marker::PhantomData::<#item_ty>, + } +}; +``` + +## Repetition + +Repetition is done using `#(...)*` or `#(...),*` similar to `macro_rules!`. This +iterates through the elements of any variable interpolated within the repetition +and inserts a copy of the repetition body for each one. The variables in an +interpolation may be anything that implements `IntoIterator`, including `Vec` or +a pre-existing iterator. + +- `#(#var)*` — no separators +- `#(#var),*` — the character before the asterisk is used as a separator +- `#( struct #var; )*` — the repetition can contain other things +- `#( #k => println!("{}", #v), )*` — even multiple interpolations + +Note that there is a difference between `#(#var ,)*` and `#(#var),*`—the latter +does not produce a trailing comma. This matches the behavior of delimiters in +`macro_rules!`. + +## Hygiene + +Any interpolated tokens preserve the `Span` information provided by their +`ToTokens` implementation. Tokens that originate within a `quote!` invocation +are spanned with [`Span::def_site()`]. + +[`Span::def_site()`]: https://docs.rs/proc-macro2/0.2/proc_macro2/struct.Span.html#method.def_site + +A different span can be provided explicitly through the [`quote_spanned!`] +macro. + +[`quote_spanned!`]: https://docs.rs/quote/0.5/quote/macro.quote_spanned.html + +### Recursion limit + +The `quote!` macro relies on deep recursion so some large invocations may fail +with "recursion limit reached" when you compile. If it fails, bump up the +recursion limit by adding `#![recursion_limit = "128"]` to your crate. An even +higher limit may be necessary for especially large invocations. You don't need +this unless the compiler tells you that you need it. + +## 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 this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/quote-0.5.1/src/lib.rs cargo-0.26.0/vendor/quote-0.5.1/src/lib.rs --- cargo-0.25.0/vendor/quote-0.5.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quote-0.5.1/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,511 @@ +//! This crate provides the [`quote!`] macro for turning Rust syntax tree data +//! structures into tokens of source code. +//! +//! [`quote!`]: macro.quote.html +//! +//! Procedural macros in Rust receive a stream of tokens as input, execute +//! arbitrary Rust code to determine how to manipulate those tokens, and produce +//! a stream of tokens to hand back to the compiler to compile into the caller's +//! crate. Quasi-quoting is a solution to one piece of that -- producing tokens +//! to return to the compiler. +//! +//! The idea of quasi-quoting is that we write *code* that we treat as *data*. +//! Within the `quote!` macro, we can write what looks like code to our text +//! editor or IDE. We get all the benefits of the editor's brace matching, +//! syntax highlighting, indentation, and maybe autocompletion. But rather than +//! compiling that as code into the current crate, we can treat it as data, pass +//! it around, mutate it, and eventually hand it back to the compiler as tokens +//! to compile into the macro caller's crate. +//! +//! This crate is motivated by the procedural macro use case, but is a +//! general-purpose Rust quasi-quoting library and is not specific to procedural +//! macros. +//! +//! *Version requirement: Quote supports any compiler version back to Rust's +//! very first support for procedural macros in Rust 1.15.0.* +//! +//! ```toml +//! [dependencies] +//! quote = "0.5" +//! ``` +//! +//! ``` +//! #[macro_use] +//! extern crate quote; +//! # +//! # fn main() {} +//! ``` +//! +//! # Example +//! +//! The following quasi-quoted block of code is something you might find in [a] +//! procedural macro having to do with data structure serialization. The `#var` +//! syntax performs interpolation of runtime variables into the quoted tokens. +//! Check out the documentation of the [`quote!`] macro for more detail about +//! the syntax. See also the [`quote_spanned!`] macro which is important for +//! implementing hygienic procedural macros. +//! +//! [a]: https://serde.rs/ +//! [`quote_spanned!`]: macro.quote_spanned.html +//! +//! ``` +//! # #[macro_use] +//! # extern crate quote; +//! # +//! # fn main() { +//! # let generics = ""; +//! # let where_clause = ""; +//! # let field_ty = ""; +//! # let item_ty = ""; +//! # let path = ""; +//! # let value = ""; +//! # +//! let tokens = quote! { +//! struct SerializeWith #generics #where_clause { +//! value: &'a #field_ty, +//! phantom: ::std::marker::PhantomData<#item_ty>, +//! } +//! +//! impl #generics serde::Serialize for SerializeWith #generics #where_clause { +//! fn serialize(&self, s: &mut S) -> Result<(), S::Error> +//! where S: serde::Serializer +//! { +//! #path(self.value, s) +//! } +//! } +//! +//! SerializeWith { +//! value: #value, +//! phantom: ::std::marker::PhantomData::<#item_ty>, +//! } +//! }; +//! # +//! # } +//! ``` +//! +//! ## Recursion limit +//! +//! The `quote!` macro relies on deep recursion so some large invocations may +//! fail with "recursion limit reached" when you compile. If it fails, bump up +//! the recursion limit by adding `#![recursion_limit = "128"]` to your crate. +//! An even higher limit may be necessary for especially large invocations. + +// Quote types in rustdoc of other crates get linked to here. +#![doc(html_root_url = "https://docs.rs/quote/0.5.1")] + +#[cfg(feature = "proc-macro")] +extern crate proc_macro; +extern crate proc_macro2; + +mod tokens; +pub use tokens::Tokens; + +mod to_tokens; +pub use to_tokens::ToTokens; + +// Not public API. +#[doc(hidden)] +pub mod __rt { + // Not public API. + pub use proc_macro2::*; + + // Not public API. + pub fn parse(tokens: &mut ::Tokens, span: Span, s: &str) { + let s: TokenStream = s.parse().expect("invalid token stream"); + tokens.append_all(s.into_iter().map(|mut t| { + t.set_span(span); + t + })); + } +} + +/// The whole point. +/// +/// Performs variable interpolation against the input and produces it as +/// [`Tokens`]. For returning tokens to the compiler in a procedural macro, use +/// `into()` to build a `TokenStream`. +/// +/// [`Tokens`]: struct.Tokens.html +/// +/// # Interpolation +/// +/// Variable interpolation is done with `#var` (similar to `$var` in +/// `macro_rules!` macros). This grabs the `var` variable that is currently in +/// scope and inserts it in that location in the output tokens. The variable +/// must implement the [`ToTokens`] trait. +/// +/// [`ToTokens`]: trait.ToTokens.html +/// +/// Repetition is done using `#(...)*` or `#(...),*` again similar to +/// `macro_rules!`. This iterates through the elements of any variable +/// interpolated within the repetition and inserts a copy of the repetition body +/// for each one. The variables in an interpolation may be anything that +/// implements `IntoIterator`, including `Vec` or a pre-existing iterator. +/// +/// - `#(#var)*` — no separators +/// - `#(#var),*` — the character before the asterisk is used as a separator +/// - `#( struct #var; )*` — the repetition can contain other tokens +/// - `#( #k => println!("{}", #v), )*` — even multiple interpolations +/// +/// # Hygiene +/// +/// Any interpolated tokens preserve the `Span` information provided by their +/// `ToTokens` implementation. Tokens that originate within the `quote!` +/// invocation are spanned with [`Span::call_site()`]. +/// +/// [`Span::call_site()`]: https://docs.rs/proc-macro2/0.2/proc_macro2/struct.Span.html#method.call_site +/// +/// A different span can be provided through the [`quote_spanned!`] macro. +/// +/// [`quote_spanned!`]: macro.quote_spanned.html +/// +/// # Example +/// +/// ``` +/// # #[cfg(feature = "proc-macro")] +/// extern crate proc_macro; +/// # #[cfg(not(feature = "proc-macro"))] +/// # extern crate proc_macro2 as proc_macro; +/// +/// #[macro_use] +/// extern crate quote; +/// +/// use proc_macro::TokenStream; +/// +/// # const IGNORE_TOKENS: &'static str = stringify! { +/// #[proc_macro_derive(HeapSize)] +/// # }; +/// pub fn derive_heap_size(input: TokenStream) -> TokenStream { +/// // Parse the input and figure out what implementation to generate... +/// # const IGNORE_TOKENS: &'static str = stringify! { +/// let name = /* ... */; +/// let expr = /* ... */; +/// # }; +/// # +/// # let name = 0; +/// # let expr = 0; +/// +/// let expanded = quote! { +/// // The generated impl. +/// impl ::heapsize::HeapSize for #name { +/// fn heap_size_of_children(&self) -> usize { +/// #expr +/// } +/// } +/// }; +/// +/// // Hand the output tokens back to the compiler. +/// expanded.into() +/// } +/// # +/// # fn main() {} +/// ``` +#[macro_export] +macro_rules! quote { + ($($tt:tt)*) => (quote_spanned!($crate::__rt::Span::call_site()=> $($tt)*)); +} + +/// Same as `quote!`, but applies a given span to all tokens originating within +/// the macro invocation. +/// +/// # Syntax +/// +/// A span expression of type [`Span`], followed by `=>`, followed by the tokens +/// to quote. The span expression should be brief -- use a variable for anything +/// more than a few characters. There should be no space before the `=>` token. +/// +/// [`Span`]: https://docs.rs/proc-macro2/0.2/proc_macro2/struct.Span.html +/// +/// ``` +/// # #[macro_use] +/// # extern crate quote; +/// # extern crate proc_macro2; +/// # +/// # use proc_macro2::Span; +/// # +/// # fn main() { +/// # const IGNORE_TOKENS: &'static str = stringify! { +/// let span = /* ... */; +/// # }; +/// # let span = Span::call_site(); +/// # let init = 0; +/// +/// // On one line, use parentheses. +/// let tokens = quote_spanned!(span=> Box::into_raw(Box::new(#init))); +/// +/// // On multiple lines, place the span at the top and use braces. +/// let tokens = quote_spanned! {span=> +/// Box::into_raw(Box::new(#init)) +/// }; +/// # } +/// ``` +/// +/// The lack of space before the `=>` should look jarring to Rust programmers +/// and this is intentional. The formatting is designed to be visibly +/// off-balance and draw the eye a particular way, due to the span expression +/// being evaluated in the context of the procedural macro and the remaining +/// tokens being evaluated in the generated code. +/// +/// # Hygiene +/// +/// Any interpolated tokens preserve the `Span` information provided by their +/// `ToTokens` implementation. Tokens that originate within the `quote_spanned!` +/// invocation are spanned with the given span argument. +/// +/// # Example +/// +/// The following procedural macro code uses `quote_spanned!` to assert that a +/// particular Rust type implements the [`Sync`] trait so that references can be +/// safely shared between threads. +/// +/// [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html +/// +/// ``` +/// # #[macro_use] +/// # extern crate quote; +/// # extern crate proc_macro2; +/// # +/// # use quote::{Tokens, ToTokens}; +/// # use proc_macro2::Span; +/// # +/// # struct Type; +/// # +/// # impl Type { +/// # fn span(&self) -> Span { +/// # Span::call_site() +/// # } +/// # } +/// # +/// # impl ToTokens for Type { +/// # fn to_tokens(&self, _tokens: &mut Tokens) {} +/// # } +/// # +/// # fn main() { +/// # let ty = Type; +/// # let call_site = Span::call_site(); +/// # +/// let ty_span = ty.span(); +/// let assert_sync = quote_spanned! {ty_span=> +/// struct _AssertSync where #ty: Sync; +/// }; +/// # } +/// ``` +/// +/// If the assertion fails, the user will see an error like the following. The +/// input span of their type is hightlighted in the error. +/// +/// ```text +/// error[E0277]: the trait bound `*const (): std::marker::Sync` is not satisfied +/// --> src/main.rs:10:21 +/// | +/// 10 | static ref PTR: *const () = &(); +/// | ^^^^^^^^^ `*const ()` cannot be shared between threads safely +/// ``` +/// +/// In this example it is important for the where-clause to be spanned with the +/// line/column information of the user's input type so that error messages are +/// placed appropriately by the compiler. But it is also incredibly important +/// that `Sync` resolves at the macro definition site and not the macro call +/// site. If we resolve `Sync` at the same span that the user's type is going to +/// be resolved, then they could bypass our check by defining their own trait +/// named `Sync` that is implemented for their type. +#[macro_export] +macro_rules! quote_spanned { + ($span:expr=> $($tt:tt)*) => { + { + let mut _s = $crate::Tokens::new(); + let _span = $span; + quote_each_token!(_s _span $($tt)*); + _s + } + }; +} + +// Extract the names of all #metavariables and pass them to the $finish macro. +// +// in: pounded_var_names!(then () a #b c #( #d )* #e) +// out: then!(() b d e) +#[macro_export] +#[doc(hidden)] +macro_rules! pounded_var_names { + ($finish:ident ($($found:ident)*) # ( $($inner:tt)* ) $($rest:tt)*) => { + pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*) + }; + + ($finish:ident ($($found:ident)*) # [ $($inner:tt)* ] $($rest:tt)*) => { + pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*) + }; + + ($finish:ident ($($found:ident)*) # { $($inner:tt)* } $($rest:tt)*) => { + pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*) + }; + + ($finish:ident ($($found:ident)*) # $first:ident $($rest:tt)*) => { + pounded_var_names!($finish ($($found)* $first) $($rest)*) + }; + + ($finish:ident ($($found:ident)*) ( $($inner:tt)* ) $($rest:tt)*) => { + pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*) + }; + + ($finish:ident ($($found:ident)*) [ $($inner:tt)* ] $($rest:tt)*) => { + pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*) + }; + + ($finish:ident ($($found:ident)*) { $($inner:tt)* } $($rest:tt)*) => { + pounded_var_names!($finish ($($found)*) $($inner)* $($rest)*) + }; + + ($finish:ident ($($found:ident)*) $ignore:tt $($rest:tt)*) => { + pounded_var_names!($finish ($($found)*) $($rest)*) + }; + + ($finish:ident ($($found:ident)*)) => { + $finish!(() $($found)*) + }; +} + +// in: nested_tuples_pat!(() a b c d e) +// out: ((((a b) c) d) e) +// +// in: nested_tuples_pat!(() a) +// out: a +#[macro_export] +#[doc(hidden)] +macro_rules! nested_tuples_pat { + (()) => { + &() + }; + + (() $first:ident $($rest:ident)*) => { + nested_tuples_pat!(($first) $($rest)*) + }; + + (($pat:pat) $first:ident $($rest:ident)*) => { + nested_tuples_pat!((($pat, $first)) $($rest)*) + }; + + (($done:pat)) => { + $done + }; +} + +// in: multi_zip_expr!(() a b c d e) +// out: a.into_iter().zip(b).zip(c).zip(d).zip(e) +// +// in: multi_zip_iter!(() a) +// out: a +#[macro_export] +#[doc(hidden)] +macro_rules! multi_zip_expr { + (()) => { + &[] + }; + + (() $single:ident) => { + $single + }; + + (() $first:ident $($rest:ident)*) => { + multi_zip_expr!(($first.into_iter()) $($rest)*) + }; + + (($zips:expr) $first:ident $($rest:ident)*) => { + multi_zip_expr!(($zips.zip($first)) $($rest)*) + }; + + (($done:expr)) => { + $done + }; +} + +#[macro_export] +#[doc(hidden)] +macro_rules! quote_each_token { + ($tokens:ident $span:ident) => {}; + + ($tokens:ident $span:ident # ! $($rest:tt)*) => { + quote_each_token!($tokens $span #); + quote_each_token!($tokens $span !); + quote_each_token!($tokens $span $($rest)*); + }; + + ($tokens:ident $span:ident # ( $($inner:tt)* ) * $($rest:tt)*) => { + for pounded_var_names!(nested_tuples_pat () $($inner)*) + in pounded_var_names!(multi_zip_expr () $($inner)*) { + quote_each_token!($tokens $span $($inner)*); + } + quote_each_token!($tokens $span $($rest)*); + }; + + ($tokens:ident $span:ident # ( $($inner:tt)* ) $sep:tt * $($rest:tt)*) => { + for (_i, pounded_var_names!(nested_tuples_pat () $($inner)*)) + in pounded_var_names!(multi_zip_expr () $($inner)*).into_iter().enumerate() { + if _i > 0 { + quote_each_token!($tokens $span $sep); + } + quote_each_token!($tokens $span $($inner)*); + } + quote_each_token!($tokens $span $($rest)*); + }; + + ($tokens:ident $span:ident # [ $($inner:tt)* ] $($rest:tt)*) => { + quote_each_token!($tokens $span #); + $tokens.append({ + let mut g = $crate::__rt::Group::new( + $crate::__rt::Delimiter::Bracket, + quote_spanned!($span=> $($inner)*).into(), + ); + g.set_span($span); + g + }); + quote_each_token!($tokens $span $($rest)*); + }; + + ($tokens:ident $span:ident # $first:ident $($rest:tt)*) => { + $crate::ToTokens::to_tokens(&$first, &mut $tokens); + quote_each_token!($tokens $span $($rest)*); + }; + + ($tokens:ident $span:ident ( $($first:tt)* ) $($rest:tt)*) => { + $tokens.append({ + let mut g = $crate::__rt::Group::new( + $crate::__rt::Delimiter::Parenthesis, + quote_spanned!($span=> $($first)*).into(), + ); + g.set_span($span); + g + }); + quote_each_token!($tokens $span $($rest)*); + }; + + ($tokens:ident $span:ident [ $($first:tt)* ] $($rest:tt)*) => { + $tokens.append({ + let mut g = $crate::__rt::Group::new( + $crate::__rt::Delimiter::Bracket, + quote_spanned!($span=> $($first)*).into(), + ); + g.set_span($span); + g + }); + quote_each_token!($tokens $span $($rest)*); + }; + + ($tokens:ident $span:ident { $($first:tt)* } $($rest:tt)*) => { + $tokens.append({ + let mut g = $crate::__rt::Group::new( + $crate::__rt::Delimiter::Brace, + quote_spanned!($span=> $($first)*).into(), + ); + g.set_span($span); + g + }); + quote_each_token!($tokens $span $($rest)*); + }; + + ($tokens:ident $span:ident $first:tt $($rest:tt)*) => { + // TODO: this seems slow... special case some `:tt` arguments? + $crate::__rt::parse(&mut $tokens, $span, stringify!($first)); + quote_each_token!($tokens $span $($rest)*); + }; +} diff -Nru cargo-0.25.0/vendor/quote-0.5.1/src/tokens.rs cargo-0.26.0/vendor/quote-0.5.1/src/tokens.rs --- cargo-0.25.0/vendor/quote-0.5.1/src/tokens.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quote-0.5.1/src/tokens.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,266 @@ +use super::ToTokens; +use std::fmt::{self, Debug, Display}; +use std::hash::{Hash, Hasher}; + +#[cfg(feature = "proc-macro")] +use proc_macro; +use proc_macro2::{TokenStream, TokenTree}; + +/// Tokens produced by a [`quote!`] invocation. +/// +/// [`quote!`]: macro.quote.html +#[derive(Clone, Default)] +pub struct Tokens { + tts: Vec, +} + +impl Tokens { + /// Empty tokens. + pub fn new() -> Self { + Tokens { tts: Vec::new() } + } + + /// For use by `ToTokens` implementations. + /// + /// Appends the token specified to this list of tokens. + pub fn append(&mut self, token: U) + where + U: Into, + { + self.tts.push(token.into()); + } + + /// For use by `ToTokens` implementations. + /// + /// ``` + /// # #[macro_use] extern crate quote; + /// # use quote::{Tokens, ToTokens}; + /// # fn main() { + /// struct X; + /// + /// impl ToTokens for X { + /// fn to_tokens(&self, tokens: &mut Tokens) { + /// tokens.append_all(&[true, false]); + /// } + /// } + /// + /// let tokens = quote!(#X); + /// assert_eq!(tokens.to_string(), "true false"); + /// # } + /// ``` + pub fn append_all(&mut self, iter: I) + where + T: ToTokens, + I: IntoIterator, + { + for token in iter { + token.to_tokens(self); + } + } + + /// For use by `ToTokens` implementations. + /// + /// Appends all of the items in the iterator `I`, separated by the tokens + /// `U`. + pub fn append_separated(&mut self, iter: I, op: U) + where + T: ToTokens, + I: IntoIterator, + U: ToTokens, + { + for (i, token) in iter.into_iter().enumerate() { + if i > 0 { + op.to_tokens(self); + } + token.to_tokens(self); + } + } + + /// For use by `ToTokens` implementations. + /// + /// Appends all tokens in the iterator `I`, appending `U` after each + /// element, including after the last element of the iterator. + pub fn append_terminated(&mut self, iter: I, term: U) + where + T: ToTokens, + I: IntoIterator, + U: ToTokens, + { + for token in iter { + token.to_tokens(self); + term.to_tokens(self); + } + } +} + +impl ToTokens for Tokens { + fn to_tokens(&self, dst: &mut Tokens) { + dst.tts.extend(self.tts.iter().cloned()); + } + + fn into_tokens(self) -> Tokens { + self + } +} + +impl From for TokenStream { + fn from(tokens: Tokens) -> TokenStream { + tokens.tts.into_iter().collect() + } +} + +#[cfg(feature = "proc-macro")] +impl From for proc_macro::TokenStream { + fn from(tokens: Tokens) -> proc_macro::TokenStream { + TokenStream::from(tokens).into() + } +} + +/// Allows a `Tokens` to be passed to `Tokens::append_all`. +impl IntoIterator for Tokens { + type Item = TokenTree; + type IntoIter = private::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + private::into_iter(self.tts.into_iter()) + } +} + +mod private { + use proc_macro2::TokenTree; + use std::vec; + + pub struct IntoIter(vec::IntoIter); + + pub fn into_iter(tts: vec::IntoIter) -> IntoIter { + IntoIter(tts) + } + + impl Iterator for IntoIter { + type Item = TokenTree; + + fn next(&mut self) -> Option { + self.0.next() + } + } +} + +impl Display for Tokens { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&TokenStream::from(self.clone()), formatter) + } +} + +impl Debug for Tokens { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + struct DebugAsDisplay<'a, T: 'a>(&'a T); + + impl<'a, T> Debug for DebugAsDisplay<'a, T> + where + T: Display, + { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(self.0, formatter) + } + } + + formatter + .debug_tuple("Tokens") + .field(&DebugAsDisplay(self)) + .finish() + } +} + +fn tt_eq(a: &TokenTree, b: &TokenTree) -> bool { + use proc_macro2::{Delimiter, Spacing}; + + match (a, b) { + (&TokenTree::Group(ref s1), &TokenTree::Group(ref s2)) => { + match (s1.delimiter(), s2.delimiter()) { + (Delimiter::Parenthesis, Delimiter::Parenthesis) + | (Delimiter::Brace, Delimiter::Brace) + | (Delimiter::Bracket, Delimiter::Bracket) + | (Delimiter::None, Delimiter::None) => {} + _ => return false, + } + + let s1 = s1.stream().clone().into_iter(); + let mut s2 = s2.stream().clone().into_iter(); + + for item1 in s1 { + let item2 = match s2.next() { + Some(item) => item, + None => return false, + }; + if !tt_eq(&item1, &item2) { + return false; + } + } + s2.next().is_none() + } + (&TokenTree::Op(ref o1), &TokenTree::Op(ref o2)) => { + o1.op() == o2.op() && match (o1.spacing(), o2.spacing()) { + (Spacing::Alone, Spacing::Alone) | (Spacing::Joint, Spacing::Joint) => true, + _ => false, + } + } + (&TokenTree::Literal(ref l1), &TokenTree::Literal(ref l2)) => { + l1.to_string() == l2.to_string() + } + (&TokenTree::Term(ref s1), &TokenTree::Term(ref s2)) => s1.as_str() == s2.as_str(), + _ => false, + } +} + +impl PartialEq for Tokens { + fn eq(&self, other: &Self) -> bool { + if self.tts.len() != other.tts.len() { + return false; + } + + self.tts + .iter() + .zip(other.tts.iter()) + .all(|(a, b)| tt_eq(a, b)) + } +} + +fn tt_hash(tt: &TokenTree, h: &mut H) { + use proc_macro2::{Delimiter, Spacing}; + + match *tt { + TokenTree::Group(ref g) => { + 0u8.hash(h); + match g.delimiter() { + Delimiter::Parenthesis => 0u8.hash(h), + Delimiter::Brace => 1u8.hash(h), + Delimiter::Bracket => 2u8.hash(h), + Delimiter::None => 3u8.hash(h), + } + + for item in g.stream().clone() { + tt_hash(&item, h); + } + 0xffu8.hash(h); // terminator w/ a variant we don't normally hash + } + TokenTree::Op(ref t) => { + 1u8.hash(h); + t.op().hash(h); + match t.spacing() { + Spacing::Alone => 0u8.hash(h), + Spacing::Joint => 1u8.hash(h), + } + } + TokenTree::Literal(ref lit) => (2u8, lit.to_string()).hash(h), + TokenTree::Term(ref word) => (3u8, word.as_str()).hash(h), + } +} + +impl<'a> Hash for Tokens { + fn hash(&self, h: &mut H) { + self.tts.len().hash(h); + for tt in &self.tts { + tt_hash(&tt, h); + } + } +} diff -Nru cargo-0.25.0/vendor/quote-0.5.1/src/to_tokens.rs cargo-0.26.0/vendor/quote-0.5.1/src/to_tokens.rs --- cargo-0.25.0/vendor/quote-0.5.1/src/to_tokens.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quote-0.5.1/src/to_tokens.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,167 @@ +use super::Tokens; + +use std::borrow::Cow; + +use proc_macro2::{Literal, Span, Term, TokenStream, TokenTree}; + +/// Types that can be interpolated inside a [`quote!`] invocation. +/// +/// [`quote!`]: macro.quote.html +pub trait ToTokens { + /// Write `self` to the given `Tokens`. + /// + /// Example implementation for a struct representing Rust paths like + /// `std::cmp::PartialEq`: + /// + /// ``` + /// extern crate quote; + /// use quote::{Tokens, ToTokens}; + /// + /// extern crate proc_macro2; + /// use proc_macro2::{TokenTree, Spacing, Span, Op}; + /// + /// pub struct Path { + /// pub global: bool, + /// pub segments: Vec, + /// } + /// + /// impl ToTokens for Path { + /// fn to_tokens(&self, tokens: &mut Tokens) { + /// for (i, segment) in self.segments.iter().enumerate() { + /// if i > 0 || self.global { + /// // Double colon `::` + /// tokens.append(Op::new(':', Spacing::Joint)); + /// tokens.append(Op::new(':', Spacing::Alone)); + /// } + /// segment.to_tokens(tokens); + /// } + /// } + /// } + /// # + /// # pub struct PathSegment; + /// # + /// # impl ToTokens for PathSegment { + /// # fn to_tokens(&self, tokens: &mut Tokens) { + /// # unimplemented!() + /// # } + /// # } + /// # + /// # fn main() {} + /// ``` + fn to_tokens(&self, tokens: &mut Tokens); + + /// Convert `self` directly into a `Tokens` object. + /// + /// This method is implicitly implemented using `to_tokens`, and acts as a + /// convenience method for consumers of the `ToTokens` trait. + fn into_tokens(self) -> Tokens + where + Self: Sized, + { + let mut tokens = Tokens::new(); + self.to_tokens(&mut tokens); + tokens + } +} + +impl<'a, T: ?Sized + ToTokens> ToTokens for &'a T { + fn to_tokens(&self, tokens: &mut Tokens) { + (**self).to_tokens(tokens); + } +} + +impl<'a, T: ?Sized + ToOwned + ToTokens> ToTokens for Cow<'a, T> { + fn to_tokens(&self, tokens: &mut Tokens) { + (**self).to_tokens(tokens); + } +} + +impl ToTokens for Box { + fn to_tokens(&self, tokens: &mut Tokens) { + (**self).to_tokens(tokens); + } +} + +impl ToTokens for Option { + fn to_tokens(&self, tokens: &mut Tokens) { + if let Some(ref t) = *self { + t.to_tokens(tokens); + } + } +} + +impl ToTokens for str { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append(Literal::string(self)); + } +} + +impl ToTokens for String { + fn to_tokens(&self, tokens: &mut Tokens) { + self.as_str().to_tokens(tokens); + } +} + +macro_rules! primitive { + ($($t:ident => $name:ident)*) => ($( + impl ToTokens for $t { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append(Literal::$name(*self)); + } + } + )*) +} + +primitive! { + i8 => i8_suffixed + i16 => i16_suffixed + i32 => i32_suffixed + i64 => i64_suffixed + isize => isize_suffixed + + u8 => u8_suffixed + u16 => u16_suffixed + u32 => u32_suffixed + u64 => u64_suffixed + usize => usize_suffixed + + f32 => f32_suffixed + f64 => f64_suffixed +} + +impl ToTokens for char { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append(Literal::character(*self)); + } +} + +impl ToTokens for bool { + fn to_tokens(&self, tokens: &mut Tokens) { + let word = if *self { "true" } else { "false" }; + tokens.append(Term::new(word, Span::call_site())); + } +} + +impl ToTokens for Term { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append(self.clone()); + } +} + +impl ToTokens for Literal { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append(self.clone()); + } +} + +impl ToTokens for TokenTree { + fn to_tokens(&self, dst: &mut Tokens) { + dst.append(self.clone()); + } +} + +impl ToTokens for TokenStream { + fn to_tokens(&self, dst: &mut Tokens) { + dst.append_all(self.clone().into_iter()); + } +} diff -Nru cargo-0.25.0/vendor/quote-0.5.1/tests/test.rs cargo-0.26.0/vendor/quote-0.5.1/tests/test.rs --- cargo-0.25.0/vendor/quote-0.5.1/tests/test.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/quote-0.5.1/tests/test.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,289 @@ +#![cfg_attr(feature = "cargo-clippy", allow(blacklisted_name))] + +use std::borrow::Cow; + +extern crate proc_macro2; +#[macro_use] +extern crate quote; + +use proc_macro2::{Span, Term}; + +struct X; + +impl quote::ToTokens for X { + fn to_tokens(&self, tokens: &mut quote::Tokens) { + tokens.append(Term::new("X", Span::call_site())); + } +} + +#[test] +fn test_quote_impl() { + let tokens = quote! { + impl<'a, T: ToTokens> ToTokens for &'a T { + fn to_tokens(&self, tokens: &mut Tokens) { + (**self).to_tokens(tokens) + } + } + }; + + let expected = concat!( + "impl < 'a , T : ToTokens > ToTokens for & 'a T { ", + "fn to_tokens ( & self , tokens : & mut Tokens ) { ", + "( * * self ) . to_tokens ( tokens ) ", + "} ", + "}" + ); + + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_substitution() { + let x = X; + let tokens = quote!(#x <#x> (#x) [#x] {#x}); + + let expected = "X < X > ( X ) [ X ] { X }"; + + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_iter() { + let primes = &[X, X, X, X]; + + assert_eq!("X X X X", quote!(#(#primes)*).to_string()); + + assert_eq!("X , X , X , X ,", quote!(#(#primes,)*).to_string()); + + assert_eq!("X , X , X , X", quote!(#(#primes),*).to_string()); +} + +#[test] +fn test_advanced() { + let generics = quote!( <'a, T> ); + + let where_clause = quote!( where T: Serialize ); + + let field_ty = quote!(String); + + let item_ty = quote!(Cow<'a, str>); + + let path = quote!(SomeTrait::serialize_with); + + let value = quote!(self.x); + + let tokens = quote! { + struct SerializeWith #generics #where_clause { + value: &'a #field_ty, + phantom: ::std::marker::PhantomData<#item_ty>, + } + + impl #generics ::serde::Serialize for SerializeWith #generics #where_clause { + fn serialize(&self, s: &mut S) -> Result<(), S::Error> + where S: ::serde::Serializer + { + #path(self.value, s) + } + } + + SerializeWith { + value: #value, + phantom: ::std::marker::PhantomData::<#item_ty>, + } + }; + + let expected = concat!( + "struct SerializeWith < 'a , T > where T : Serialize { ", + "value : & 'a String , ", + "phantom : :: std :: marker :: PhantomData < Cow < 'a , str > > , ", + "} ", + "impl < 'a , T > :: serde :: Serialize for SerializeWith < 'a , T > where T : Serialize { ", + "fn serialize < S > ( & self , s : & mut S ) -> Result < ( ) , S :: Error > ", + "where S : :: serde :: Serializer ", + "{ ", + "SomeTrait :: serialize_with ( self . value , s ) ", + "} ", + "} ", + "SerializeWith { ", + "value : self . x , ", + "phantom : :: std :: marker :: PhantomData :: < Cow < 'a , str > > , ", + "}" + ); + + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_integer() { + let ii8 = -1i8; + let ii16 = -1i16; + let ii32 = -1i32; + let ii64 = -1i64; + let iisize = -1isize; + let uu8 = 1u8; + let uu16 = 1u16; + let uu32 = 1u32; + let uu64 = 1u64; + let uusize = 1usize; + + let tokens = quote! { + #ii8 #ii16 #ii32 #ii64 #iisize + #uu8 #uu16 #uu32 #uu64 #uusize + }; + let expected = "-1i8 -1i16 -1i32 -1i64 -1isize 1u8 1u16 1u32 1u64 1usize"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_floating() { + let e32 = 2.345f32; + + let e64 = 2.345f64; + + let tokens = quote! { + #e32 + #e64 + }; + let expected = concat!("2.345f32 2.345f64"); + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_char() { + let zero = '\0'; + let pound = '#'; + let quote = '"'; + let apost = '\''; + let newline = '\n'; + let heart = '\u{2764}'; + + let tokens = quote! { + #zero #pound #quote #apost #newline #heart + }; + let expected = "'\\u{0}' '#' '\\\"' '\\'' '\\n' '\\u{2764}'"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_str() { + let s = "\0 a 'b \" c"; + let tokens = quote!(#s); + let expected = "\"\\u{0} a \\'b \\\" c\""; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_string() { + let s = "\0 a 'b \" c".to_string(); + let tokens = quote!(#s); + let expected = "\"\\u{0} a \\'b \\\" c\""; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_ident() { + let foo = Term::new("Foo", Span::call_site()); + let bar = Term::new(&format!("Bar{}", 7), Span::call_site()); + let tokens = quote!(struct #foo; enum #bar {}); + let expected = "struct Foo ; enum Bar7 { }"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_duplicate() { + let ch = 'x'; + + let tokens = quote!(#ch #ch); + + let expected = "'x' 'x'"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_fancy_repetition() { + let foo = vec!["a", "b"]; + let bar = vec![true, false]; + + let tokens = quote! { + #(#foo: #bar),* + }; + + let expected = r#""a" : true , "b" : false"#; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_nested_fancy_repetition() { + let nested = vec![vec!['a', 'b', 'c'], vec!['x', 'y', 'z']]; + + let tokens = quote! { + #( + #(#nested)* + ),* + }; + + let expected = "'a' 'b' 'c' , 'x' 'y' 'z'"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_empty_repetition() { + let tokens = quote!(#(a b)* #(c d),*); + assert_eq!("", tokens.to_string()); +} + +#[test] +fn test_variable_name_conflict() { + // The implementation of `#(...),*` uses the variable `_i` but it should be + // fine, if a little confusing when debugging. + let _i = vec!['a', 'b']; + let tokens = quote! { #(#_i),* }; + let expected = "'a' , 'b'"; + assert_eq!(expected, tokens.to_string()); +} + +#[test] +fn test_empty_quote() { + let tokens = quote!(); + assert_eq!("", tokens.to_string()); +} + +#[test] +fn test_box_str() { + let b = "str".to_owned().into_boxed_str(); + let tokens = quote! { #b }; + assert_eq!("\"str\"", tokens.to_string()); +} + +#[test] +fn test_cow() { + let owned: Cow = Cow::Owned(Term::new("owned", Span::call_site())); + + let ident = Term::new("borrowed", Span::call_site()); + let borrowed = Cow::Borrowed(&ident); + + let tokens = quote! { #owned #borrowed }; + assert_eq!("owned borrowed", tokens.to_string()); +} + +#[test] +fn test_closure() { + fn field_i(i: usize) -> Term { + Term::new(&format!("__field{}", i), Span::call_site()) + } + + let fields = (0usize..3) + .map(field_i as fn(_) -> _) + .map(|var| quote! { #var }); + + let tokens = quote! { #(#fields)* }; + assert_eq!("__field0 __field1 __field2", tokens.to_string()); +} + +#[test] +fn test_append_tokens() { + let mut a = quote!(a); + let b = quote!(b); + a.append_all(b); + assert_eq!("a b", a.to_string()); +} diff -Nru cargo-0.25.0/vendor/rand-0.3.22/appveyor.yml cargo-0.26.0/vendor/rand-0.3.22/appveyor.yml --- cargo-0.25.0/vendor/rand-0.3.22/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rand-0.3.22/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,37 +0,0 @@ -environment: - - # At the time this was added AppVeyor was having troubles with checking - # revocation of SSL certificates of sites like static.rust-lang.org and what - # we think is crates.io. The libcurl HTTP client by default checks for - # revocation on Windows and according to a mailing list [1] this can be - # disabled. - # - # The `CARGO_HTTP_CHECK_REVOKE` env var here tells cargo to disable SSL - # revocation checking on Windows in libcurl. Note, though, that rustup, which - # we're using to download Rust here, also uses libcurl as the default backend. - # Unlike Cargo, however, rustup doesn't have a mechanism to disable revocation - # checking. To get rustup working we set `RUSTUP_USE_HYPER` which forces it to - # use the Hyper instead of libcurl backend. Both Hyper and libcurl use - # schannel on Windows but it appears that Hyper configures it slightly - # differently such that revocation checking isn't turned on by default. - # - # [1]: https://curl.haxx.se/mail/lib-2016-03/0202.html - RUSTUP_USE_HYPER: 1 - CARGO_HTTP_CHECK_REVOKE: false - - matrix: - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc -install: - - appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe - - rustup-init.exe -y --default-host %TARGET% --default-toolchain nightly - - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test - - cargo test --features nightly - - cargo test --manifest-path rand-derive/Cargo.toml diff -Nru cargo-0.25.0/vendor/rand-0.3.22/.cargo-checksum.json cargo-0.26.0/vendor/rand-0.3.22/.cargo-checksum.json --- cargo-0.25.0/vendor/rand-0.3.22/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rand-0.3.22/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"15a732abf9d20f0ad8eeb6f909bf6868722d9a06e1e50802b6a70351f40b4eb1"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/rand-0.3.22/Cargo.toml cargo-0.26.0/vendor/rand-0.3.22/Cargo.toml --- cargo-0.25.0/vendor/rand-0.3.22/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rand-0.3.22/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "rand" -version = "0.3.22" -authors = ["The Rust Project Developers"] -description = "Random number generators and other randomness functionality.\n" -homepage = "https://github.com/rust-lang-nursery/rand" -documentation = "https://docs.rs/rand" -readme = "README.md" -keywords = ["random", "rng"] -categories = ["algorithms"] -license = "MIT/Apache-2.0" -repository = "https://github.com/rust-lang-nursery/rand" - -[lib] -doctest = false -[dependencies.libc] -version = "0.2" - -[dependencies.rand] -version = "0.4" - -[features] -i128_support = [] -nightly = ["i128_support"] -[target."cfg(target_os = \"fuchsia\")".dependencies.fuchsia-zircon] -version = "0.3.2" diff -Nru cargo-0.25.0/vendor/rand-0.3.22/LICENSE-APACHE cargo-0.26.0/vendor/rand-0.3.22/LICENSE-APACHE --- cargo-0.25.0/vendor/rand-0.3.22/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rand-0.3.22/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/rand-0.3.22/LICENSE-MIT cargo-0.26.0/vendor/rand-0.3.22/LICENSE-MIT --- cargo-0.25.0/vendor/rand-0.3.22/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rand-0.3.22/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/rand-0.3.22/README.md cargo-0.26.0/vendor/rand-0.3.22/README.md --- cargo-0.25.0/vendor/rand-0.3.22/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rand-0.3.22/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,92 +0,0 @@ -rand -==== - -A Rust library for random number generators and other randomness functionality. - -[![Build Status](https://travis-ci.org/rust-lang-nursery/rand.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/rand) -[![Build status](https://ci.appveyor.com/api/projects/status/rm5c9o33k3jhchbw?svg=true)](https://ci.appveyor.com/project/alexcrichton/rand) - -[Documentation](https://docs.rs/rand) - -## Compatibility upgrade - -Version 0.3 has been replaced by a compatibility wrapper around `rand` 0.4. It -is recommended to update to 0.4. - -## Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -rand = "0.4" -``` - -and this to your crate root: - -```rust -extern crate rand; -``` - -## Examples - -There is built-in support for a random number generator (RNG) associated with each thread stored in thread-local storage. This RNG can be accessed via thread_rng, or used implicitly via random. This RNG is normally randomly seeded from an operating-system source of randomness, e.g. /dev/urandom on Unix systems, and will automatically reseed itself from this source after generating 32 KiB of random data. - -```rust -let tuple = rand::random::<(f64, char)>(); -println!("{:?}", tuple) -``` - -```rust -use rand::Rng; - -let mut rng = rand::thread_rng(); -if rng.gen() { // random bool - println!("i32: {}, u32: {}", rng.gen::(), rng.gen::()) -} -``` - -It is also possible to use other RNG types, which have a similar interface. The following uses the "ChaCha" algorithm instead of the default. - -```rust -use rand::{Rng, ChaChaRng}; - -let mut rng = rand::ChaChaRng::new_unseeded(); -println!("i32: {}, u32: {}", rng.gen::(), rng.gen::()) -``` - -# `derive(Rand)` - -You can derive the `Rand` trait for your custom type via the `#[derive(Rand)]` -directive. To use this first add this to your Cargo.toml: - -```toml -rand = "0.4" -rand_derive = "0.3" -``` - -Next in your crate: - -```rust -extern crate rand; -#[macro_use] -extern crate rand_derive; - -#[derive(Rand, Debug)] -struct MyStruct { - a: i32, - b: u32, -} - -fn main() { - println!("{:?}", rand::random::()); -} -``` - - -# License - -`rand` is primarily distributed under the terms of both the MIT -license and the Apache License (Version 2.0). - -See LICENSE-APACHE, and LICENSE-MIT for details. diff -Nru cargo-0.25.0/vendor/rand-0.3.22/src/distributions/mod.rs cargo-0.26.0/vendor/rand-0.3.22/src/distributions/mod.rs --- cargo-0.25.0/vendor/rand-0.3.22/src/distributions/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rand-0.3.22/src/distributions/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,159 +0,0 @@ -// Copyright 2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Sampling from random distributions. -//! -//! This is a generalization of `Rand` to allow parameters to control the -//! exact properties of the generated values, e.g. the mean and standard -//! deviation of a normal distribution. The `Sample` trait is the most -//! general, and allows for generating values that change some state -//! internally. The `IndependentSample` trait is for generating values -//! that do not need to record state. - -pub use rand4::distributions::Range; -pub use rand4::distributions::{Gamma, ChiSquared, FisherF, StudentT}; -pub use rand4::distributions::{Normal, LogNormal}; -pub use rand4::distributions::Exp; - -pub use rand4::distributions::{range, gamma, normal, exponential}; - -pub use rand4::distributions::{Sample, IndependentSample, RandSample}; -pub use rand4::distributions::{Weighted, WeightedChoice}; - -#[cfg(test)] -mod tests { - - use {Rng, Rand}; - use super::{RandSample, WeightedChoice, Weighted, Sample, IndependentSample}; - - #[derive(PartialEq, Debug)] - struct ConstRand(usize); - impl Rand for ConstRand { - fn rand(_: &mut R) -> ConstRand { - ConstRand(0) - } - } - - // 0, 1, 2, 3, ... - struct CountingRng { i: u32 } - impl Rng for CountingRng { - fn next_u32(&mut self) -> u32 { - self.i += 1; - self.i - 1 - } - fn next_u64(&mut self) -> u64 { - self.next_u32() as u64 - } - } - - #[test] - fn test_rand_sample() { - let mut rand_sample = RandSample::::new(); - - assert_eq!(rand_sample.sample(&mut ::test::rng()), ConstRand(0)); - assert_eq!(rand_sample.ind_sample(&mut ::test::rng()), ConstRand(0)); - } - #[test] - fn test_weighted_choice() { - // this makes assumptions about the internal implementation of - // WeightedChoice, specifically: it doesn't reorder the items, - // it doesn't do weird things to the RNG (so 0 maps to 0, 1 to - // 1, internally; modulo a modulo operation). - - macro_rules! t { - ($items:expr, $expected:expr) => {{ - let mut items = $items; - let wc = WeightedChoice::new(&mut items); - let expected = $expected; - - let mut rng = CountingRng { i: 0 }; - - for &val in expected.iter() { - assert_eq!(wc.ind_sample(&mut rng), val) - } - }} - } - - t!(vec!(Weighted { weight: 1, item: 10}), [10]); - - // skip some - t!(vec!(Weighted { weight: 0, item: 20}, - Weighted { weight: 2, item: 21}, - Weighted { weight: 0, item: 22}, - Weighted { weight: 1, item: 23}), - [21,21, 23]); - - // different weights - t!(vec!(Weighted { weight: 4, item: 30}, - Weighted { weight: 3, item: 31}), - [30,30,30,30, 31,31,31]); - - // check that we're binary searching - // correctly with some vectors of odd - // length. - t!(vec!(Weighted { weight: 1, item: 40}, - Weighted { weight: 1, item: 41}, - Weighted { weight: 1, item: 42}, - Weighted { weight: 1, item: 43}, - Weighted { weight: 1, item: 44}), - [40, 41, 42, 43, 44]); - t!(vec!(Weighted { weight: 1, item: 50}, - Weighted { weight: 1, item: 51}, - Weighted { weight: 1, item: 52}, - Weighted { weight: 1, item: 53}, - Weighted { weight: 1, item: 54}, - Weighted { weight: 1, item: 55}, - Weighted { weight: 1, item: 56}), - [50, 51, 52, 53, 54, 55, 56]); - } - - #[test] - fn test_weighted_clone_initialization() { - let initial : Weighted = Weighted {weight: 1, item: 1}; - let clone = initial.clone(); - assert_eq!(initial.weight, clone.weight); - assert_eq!(initial.item, clone.item); - } - - #[test] #[should_panic] - fn test_weighted_clone_change_weight() { - let initial : Weighted = Weighted {weight: 1, item: 1}; - let mut clone = initial.clone(); - clone.weight = 5; - assert_eq!(initial.weight, clone.weight); - } - - #[test] #[should_panic] - fn test_weighted_clone_change_item() { - let initial : Weighted = Weighted {weight: 1, item: 1}; - let mut clone = initial.clone(); - clone.item = 5; - assert_eq!(initial.item, clone.item); - - } - - #[test] #[should_panic] - fn test_weighted_choice_no_items() { - WeightedChoice::::new(&mut []); - } - #[test] #[should_panic] - fn test_weighted_choice_zero_weight() { - WeightedChoice::new(&mut [Weighted { weight: 0, item: 0}, - Weighted { weight: 0, item: 1}]); - } - #[test] #[should_panic] - fn test_weighted_choice_weight_overflows() { - let x = ::std::u32::MAX / 2; // x + x + 2 is the overflow - WeightedChoice::new(&mut [Weighted { weight: x, item: 0 }, - Weighted { weight: 1, item: 1 }, - Weighted { weight: x, item: 2 }, - Weighted { weight: 1, item: 3 }]); - } -} diff -Nru cargo-0.25.0/vendor/rand-0.3.22/src/lib.rs cargo-0.26.0/vendor/rand-0.3.22/src/lib.rs --- cargo-0.25.0/vendor/rand-0.3.22/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rand-0.3.22/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,297 +0,0 @@ -// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Utilities for random number generation -//! -//! This release is a compatibility wrapper around `rand` version 0.4. Please -//! upgrade. - -#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", - html_favicon_url = "https://www.rust-lang.org/favicon.ico", - html_root_url = "https://docs.rs/rand/0.3")] - -#![deny(missing_debug_implementations)] - -#![cfg_attr(feature = "i128_support", feature(i128_type))] - -extern crate rand as rand4; - -pub use rand4::OsRng; - -pub use rand4::{IsaacRng, Isaac64Rng}; -pub use rand4::ChaChaRng; - -pub mod distributions; -pub use rand4::{isaac, chacha, reseeding, os, read}; -mod rand_impls; - -pub use rand4::Rng; -pub use rand4::Rand; -pub use rand4::SeedableRng; - -pub use rand4::{Generator, AsciiGenerator}; -pub use rand4::XorShiftRng; -pub use rand4::{Open01, Closed01}; -pub use rand4::StdRng; -pub use rand4::{weak_rng, ThreadRng, thread_rng, random}; - -#[allow(deprecated)] -pub use rand4::sample; - -#[allow(deprecated)] -#[cfg(test)] -mod test { - use super::{Rng, thread_rng, random, SeedableRng, StdRng, sample, - weak_rng}; - use std::iter::repeat; - - pub struct MyRng { inner: R } - - impl Rng for MyRng { - fn next_u32(&mut self) -> u32 { - fn next(t: &mut T) -> u32 { - t.next_u32() - } - next(&mut self.inner) - } - } - - pub fn rng() -> MyRng<::ThreadRng> { - MyRng { inner: ::thread_rng() } - } - - struct ConstRng { i: u64 } - impl Rng for ConstRng { - fn next_u32(&mut self) -> u32 { self.i as u32 } - fn next_u64(&mut self) -> u64 { self.i } - - // no fill_bytes on purpose - } - - pub fn iter_eq(i: I, j: J) -> bool - where I: IntoIterator, - J: IntoIterator, - I::Item: Eq - { - // make sure the iterators have equal length - let mut i = i.into_iter(); - let mut j = j.into_iter(); - loop { - match (i.next(), j.next()) { - (Some(ref ei), Some(ref ej)) if ei == ej => { } - (None, None) => return true, - _ => return false, - } - } - } - - #[test] - fn test_fill_bytes_default() { - let mut r = ConstRng { i: 0x11_22_33_44_55_66_77_88 }; - - // check every remainder mod 8, both in small and big vectors. - let lengths = [0, 1, 2, 3, 4, 5, 6, 7, - 80, 81, 82, 83, 84, 85, 86, 87]; - for &n in lengths.iter() { - let mut v = repeat(0u8).take(n).collect::>(); - r.fill_bytes(&mut v); - - // use this to get nicer error messages. - for (i, &byte) in v.iter().enumerate() { - if byte == 0 { - panic!("byte {} of {} is zero", i, n) - } - } - } - } - - #[test] - fn test_gen_range() { - let mut r = thread_rng(); - for _ in 0..1000 { - let a = r.gen_range(-3, 42); - assert!(a >= -3 && a < 42); - assert_eq!(r.gen_range(0, 1), 0); - assert_eq!(r.gen_range(-12, -11), -12); - } - - for _ in 0..1000 { - let a = r.gen_range(10, 42); - assert!(a >= 10 && a < 42); - assert_eq!(r.gen_range(0, 1), 0); - assert_eq!(r.gen_range(3_000_000, 3_000_001), 3_000_000); - } - - } - - #[test] - #[should_panic] - fn test_gen_range_panic_int() { - let mut r = thread_rng(); - r.gen_range(5, -2); - } - - #[test] - #[should_panic] - fn test_gen_range_panic_usize() { - let mut r = thread_rng(); - r.gen_range(5, 2); - } - - #[test] - fn test_gen_weighted_bool() { - let mut r = thread_rng(); - assert_eq!(r.gen_weighted_bool(0), true); - assert_eq!(r.gen_weighted_bool(1), true); - } - - #[test] - fn test_gen_ascii_str() { - let mut r = thread_rng(); - assert_eq!(r.gen_ascii_chars().take(0).count(), 0); - assert_eq!(r.gen_ascii_chars().take(10).count(), 10); - assert_eq!(r.gen_ascii_chars().take(16).count(), 16); - } - - #[test] - fn test_gen_vec() { - let mut r = thread_rng(); - assert_eq!(r.gen_iter::().take(0).count(), 0); - assert_eq!(r.gen_iter::().take(10).count(), 10); - assert_eq!(r.gen_iter::().take(16).count(), 16); - } - - #[test] - fn test_choose() { - let mut r = thread_rng(); - assert_eq!(r.choose(&[1, 1, 1]).map(|&x|x), Some(1)); - - let v: &[isize] = &[]; - assert_eq!(r.choose(v), None); - } - - #[test] - fn test_shuffle() { - let mut r = thread_rng(); - let empty: &mut [isize] = &mut []; - r.shuffle(empty); - let mut one = [1]; - r.shuffle(&mut one); - let b: &[_] = &[1]; - assert_eq!(one, b); - - let mut two = [1, 2]; - r.shuffle(&mut two); - assert!(two == [1, 2] || two == [2, 1]); - - let mut x = [1, 1, 1]; - r.shuffle(&mut x); - let b: &[_] = &[1, 1, 1]; - assert_eq!(x, b); - } - - #[test] - fn test_thread_rng() { - let mut r = thread_rng(); - r.gen::(); - let mut v = [1, 1, 1]; - r.shuffle(&mut v); - let b: &[_] = &[1, 1, 1]; - assert_eq!(v, b); - assert_eq!(r.gen_range(0, 1), 0); - } - - #[test] - fn test_rng_trait_object() { - let mut rng = thread_rng(); - { - let mut r = &mut rng as &mut Rng; - r.next_u32(); - (&mut r).gen::(); - let mut v = [1, 1, 1]; - (&mut r).shuffle(&mut v); - let b: &[_] = &[1, 1, 1]; - assert_eq!(v, b); - assert_eq!((&mut r).gen_range(0, 1), 0); - } - { - let mut r = Box::new(rng) as Box; - r.next_u32(); - r.gen::(); - let mut v = [1, 1, 1]; - r.shuffle(&mut v); - let b: &[_] = &[1, 1, 1]; - assert_eq!(v, b); - assert_eq!(r.gen_range(0, 1), 0); - } - } - - #[test] - fn test_random() { - // not sure how to test this aside from just getting some values - let _n : usize = random(); - let _f : f32 = random(); - let _o : Option> = random(); - let _many : ((), - (usize, - isize, - Option<(u32, (bool,))>), - (u8, i8, u16, i16, u32, i32, u64, i64), - (f32, (f64, (f64,)))) = random(); - } - - #[test] - fn test_sample() { - let min_val = 1; - let max_val = 100; - - let mut r = thread_rng(); - let vals = (min_val..max_val).collect::>(); - let small_sample = sample(&mut r, vals.iter(), 5); - let large_sample = sample(&mut r, vals.iter(), vals.len() + 5); - - assert_eq!(small_sample.len(), 5); - assert_eq!(large_sample.len(), vals.len()); - - assert!(small_sample.iter().all(|e| { - **e >= min_val && **e <= max_val - })); - } - - #[test] - fn test_std_rng_seeded() { - let s = thread_rng().gen_iter::().take(256).collect::>(); - let mut ra: StdRng = SeedableRng::from_seed(&s[..]); - let mut rb: StdRng = SeedableRng::from_seed(&s[..]); - assert!(iter_eq(ra.gen_ascii_chars().take(100), - rb.gen_ascii_chars().take(100))); - } - - #[test] - fn test_std_rng_reseed() { - let s = thread_rng().gen_iter::().take(256).collect::>(); - let mut r: StdRng = SeedableRng::from_seed(&s[..]); - let string1 = r.gen_ascii_chars().take(100).collect::(); - - r.reseed(&s); - - let string2 = r.gen_ascii_chars().take(100).collect::(); - assert_eq!(string1, string2); - } - - #[test] - fn test_weak_rng() { - let s = weak_rng().gen_iter::().take(256).collect::>(); - let mut ra: StdRng = SeedableRng::from_seed(&s[..]); - let mut rb: StdRng = SeedableRng::from_seed(&s[..]); - assert!(iter_eq(ra.gen_ascii_chars().take(100), - rb.gen_ascii_chars().take(100))); - } -} diff -Nru cargo-0.25.0/vendor/rand-0.3.22/src/rand_impls.rs cargo-0.26.0/vendor/rand-0.3.22/src/rand_impls.rs --- cargo-0.25.0/vendor/rand-0.3.22/src/rand_impls.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rand-0.3.22/src/rand_impls.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The implementations of `Rand` for the built-in types. - -#[cfg(test)] -mod tests { - use {Rng, thread_rng, Open01, Closed01}; - - struct ConstantRng(u64); - impl Rng for ConstantRng { - fn next_u32(&mut self) -> u32 { - let ConstantRng(v) = *self; - v as u32 - } - fn next_u64(&mut self) -> u64 { - let ConstantRng(v) = *self; - v - } - } - - #[test] - fn floating_point_edge_cases() { - // the test for exact equality is correct here. - assert!(ConstantRng(0xffff_ffff).gen::() != 1.0); - assert!(ConstantRng(0xffff_ffff_ffff_ffff).gen::() != 1.0); - } - - #[test] - fn rand_open() { - // this is unlikely to catch an incorrect implementation that - // generates exactly 0 or 1, but it keeps it sane. - let mut rng = thread_rng(); - for _ in 0..1_000 { - // strict inequalities - let Open01(f) = rng.gen::>(); - assert!(0.0 < f && f < 1.0); - - let Open01(f) = rng.gen::>(); - assert!(0.0 < f && f < 1.0); - } - } - - #[test] - fn rand_closed() { - let mut rng = thread_rng(); - for _ in 0..1_000 { - // strict inequalities - let Closed01(f) = rng.gen::>(); - assert!(0.0 <= f && f <= 1.0); - - let Closed01(f) = rng.gen::>(); - assert!(0.0 <= f && f <= 1.0); - } - } -} diff -Nru cargo-0.25.0/vendor/rand-0.3.22/.travis.yml cargo-0.26.0/vendor/rand-0.3.22/.travis.yml --- cargo-0.25.0/vendor/rand-0.3.22/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rand-0.3.22/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -language: rust -sudo: false - -matrix: - include: - - rust: 1.15.0 - - rust: stable - - rust: stable - os: osx - - rust: beta - - rust: nightly - before_script: - - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH - script: - - cargo doc --no-deps --all-features - - cargo bench - - cargo test --features nightly - after_success: - - travis-cargo --only nightly doc-upload - -script: - - cargo test - - cargo test --manifest-path rand-derive/Cargo.toml - -env: - global: - secure: "BdDntVHSompN+Qxz5Rz45VI4ZqhD72r6aPl166FADlnkIwS6N6FLWdqs51O7G5CpoMXEDvyYrjmRMZe/GYLIG9cmqmn/wUrWPO+PauGiIuG/D2dmfuUNvSTRcIe7UQLXrfP3yyfZPgqsH6pSnNEVopquQKy3KjzqepgriOJtbyY=" - -notifications: - email: - on_success: never diff -Nru cargo-0.25.0/vendor/regex-0.2.10/appveyor.yml cargo-0.26.0/vendor/regex-0.2.10/appveyor.yml --- cargo-0.25.0/vendor/regex-0.2.10/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,19 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V +build: false +test_script: + - cargo test --verbose --jobs 4 +branches: + only: + - master + - auto diff -Nru cargo-0.25.0/vendor/regex-0.2.10/build.rs cargo-0.26.0/vendor/regex-0.2.10/build.rs --- cargo-0.25.0/vendor/regex-0.2.10/build.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/build.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,27 @@ +use std::env; +use std::ffi::OsString; +use std::process::Command; + +fn main() { + let rustc = env::var_os("RUSTC").unwrap_or(OsString::from("rustc")); + let output = Command::new(&rustc) + .arg("--version") + .output() + .unwrap() + .stdout; + let version = String::from_utf8(output).unwrap(); + + // If we're using nightly Rust, then we can enable vector optimizations. + // Note that these aren't actually activated unless the `nightly` feature + // is enabled. + // + // We also don't activate these if we've explicitly disabled auto + // optimizations. Disabling auto optimizations is intended for use in + // tests, so that we can reliably test fallback implementations. + if env::var_os("CARGO_CFG_REGEX_DISABLE_AUTO_OPTIMIZATIONS").is_none() { + if version.contains("nightly") { + println!("cargo:rustc-cfg=regex_runtime_teddy_ssse3"); + println!("cargo:rustc-cfg=regex_runtime_teddy_avx2"); + } + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/.cargo-checksum.json cargo-0.26.0/vendor/regex-0.2.10/.cargo-checksum.json --- cargo-0.25.0/vendor/regex-0.2.10/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"aec3f58d903a7d2a9dc2bf0e41a746f4530e0cab6b615494e058f67a3ef947fb"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/regex-0.2.10/Cargo.toml cargo-0.26.0/vendor/regex-0.2.10/Cargo.toml --- cargo-0.25.0/vendor/regex-0.2.10/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,100 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "regex" +version = "0.2.10" +authors = ["The Rust Project Developers"] +description = "An implementation of regular expressions for Rust. This implementation uses\nfinite automata and guarantees linear time matching on all inputs.\n" +homepage = "https://github.com/rust-lang/regex" +documentation = "https://docs.rs/regex" +readme = "README.md" +categories = ["text-processing"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-lang/regex" +[profile.test] +debug = true + +[profile.bench] +debug = true + +[profile.release] +debug = true + +[lib] +bench = false + +[[test]] +name = "default" +path = "tests/test_default.rs" + +[[test]] +name = "default-bytes" +path = "tests/test_default_bytes.rs" + +[[test]] +name = "nfa" +path = "tests/test_nfa.rs" + +[[test]] +name = "nfa-utf8bytes" +path = "tests/test_nfa_utf8bytes.rs" + +[[test]] +name = "nfa-bytes" +path = "tests/test_nfa_bytes.rs" + +[[test]] +name = "backtrack" +path = "tests/test_backtrack.rs" + +[[test]] +name = "backtrack-utf8bytes" +path = "tests/test_backtrack_utf8bytes.rs" + +[[test]] +name = "backtrack-bytes" +path = "tests/test_backtrack_bytes.rs" +[dependencies.aho-corasick] +version = "0.6.0" + +[dependencies.memchr] +version = "2.0.0" + +[dependencies.regex-syntax] +version = "0.5.1" + +[dependencies.thread_local] +version = "0.3.2" + +[dependencies.utf8-ranges] +version = "1.0.0" +[dev-dependencies.lazy_static] +version = "1" + +[dev-dependencies.quickcheck] +version = "0.6" +default-features = false + +[dev-dependencies.rand] +version = "0.4" + +[features] +default = [] +pattern = [] +simd-accel = [] +unstable = ["pattern"] +[badges.appveyor] +repository = "rust-lang-libs/regex" + +[badges.travis-ci] +repository = "rust-lang/regex" diff -Nru cargo-0.25.0/vendor/regex-0.2.10/CHANGELOG.md cargo-0.26.0/vendor/regex-0.2.10/CHANGELOG.md --- cargo-0.25.0/vendor/regex-0.2.10/CHANGELOG.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/CHANGELOG.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,403 @@ +0.2.9 (2018-03-12) +================== +This release introduces a new nightly only feature, `unstable`, which enables +SIMD optimizations for certain types of regexes. No additional compile time +options are necessary, and the regex crate will automatically choose the +best CPU features at run time. As a result, the `simd` (nightly only) crate +dependency has been dropped. + +New features: + +* [FEATURE #456](https://github.com/rust-lang/regex/pull/456): + The regex crate now includes AVX2 optimizations in addition to the extant + SSSE3 optimization. + +Bug gixes: + +* [BUG #455](https://github.com/rust-lang/regex/pull/455): + Fix a bug where `(?x)[ / - ]` failed to parse. + + +0.2.8 (2018-03-12) +================== +Bug gixes: + +* [BUG #454](https://github.com/rust-lang/regex/pull/454): + Fix a bug in the nest limit checker being too aggressive. + + +0.2.7 (2018-03-07) +================== +This release includes a ground-up rewrite of the regex-syntax crate, which has +been in development for over a year. + +New features: + +* Error messages for invalid regexes have been greatly improved. You get these + automatically; you don't need to do anything. In addition to better + formatting, error messages will now explicitly call out the use of look + around. When regex 1.0 is released, this will happen for backreferences as + well. +* Full support for intersection, difference and symmetric difference of + character classes. These can be used via the `&&`, `--` and `~~` binary + operators within classes. +* A Unicode Level 1 conformat implementation of `\p{..}` character classes. + Things like `\p{scx:Hira}`, `\p{age:3.2}` or `\p{Changes_When_Casefolded}` + now work. All property name and value aliases are supported, and properties + are selected via loose matching. e.g., `\p{Greek}` is the same as + `\p{G r E e K}`. +* A new `UNICODE.md` document has been added to this repository that + exhaustively documents support for UTS#18. +* Empty sub-expressions are now permitted in most places. That is, `()+` is + now a valid regex. +* Almost everything in regex-syntax now uses constant stack space, even when + performing anaylsis that requires structural induction. This reduces the risk + of a user provided regular expression causing a stack overflow. +* [FEATURE #174](https://github.com/rust-lang/regex/issues/174): + The `Ast` type in `regex-syntax` now contains span information. +* [FEATURE #424](https://github.com/rust-lang/regex/issues/424): + Support `\u`, `\u{...}`, `\U` and `\U{...}` syntax for specifying code points + in a regular expression. +* [FEATURE #449](https://github.com/rust-lang/regex/pull/449): + Add a `Replace::by_ref` adapter for use of a replacer without consuming it. + +Bug fixes: + +* [BUG #446](https://github.com/rust-lang/regex/issues/446): + We re-enable the Boyer-Moore literal matcher. + + +0.2.6 (2018-02-08) +================== +Bug fixes: + +* [BUG #446](https://github.com/rust-lang/regex/issues/446): + Fixes a bug in the new Boyer-Moore searcher that results in a match failure. + We fix this bug by temporarily disabling Boyer-Moore. + + +0.2.5 (2017-12-30) +================== +Bug fixes: + +* [BUG #437](https://github.com/rust-lang/regex/issues/437): + Fixes a bug in the new Boyer-Moore searcher that results in a panic. + + +0.2.4 (2017-12-30) +================== +New features: + +* [FEATURE #348](https://github.com/rust-lang/regex/pull/348): + Improve performance for capture searches on anchored regex. + (Contributed by @ethanpailes. Nice work!) +* [FEATURE #419](https://github.com/rust-lang/regex/pull/419): + Expand literal searching to include Tuned Boyer-Moore in some cases. + (Contributed by @ethanpailes. Nice work!) + +Bug fixes: + +* [BUG](https://github.com/rust-lang/regex/pull/436): + The regex compiler plugin has been removed. +* [BUG](https://github.com/rust-lang/regex/pull/436): + `simd` has been bumped to `0.2.1`, which fixes a Rust nightly build error. +* [BUG](https://github.com/rust-lang/regex/pull/436): + Bring the benchmark harness up to date. + + +0.2.3 (2017-11-30) +================== +New features: + +* [FEATURE #374](https://github.com/rust-lang/regex/pull/374): + Add `impl From for &str`. +* [FEATURE #380](https://github.com/rust-lang/regex/pull/380): + Derive `Clone` and `PartialEq` on `Error`. +* [FEATURE #400](https://github.com/rust-lang/regex/pull/400): + Update to Unicode 10. + +Bug fixes: + +* [BUG #375](https://github.com/rust-lang/regex/issues/375): + Fix a bug that prevented the bounded backtracker from terminating. +* [BUG #393](https://github.com/rust-lang/regex/issues/393), + [BUG #394](https://github.com/rust-lang/regex/issues/394): + Fix bug with `replace` methods for empty matches. + + +0.2.2 (2017-05-21) +================== +New features: + +* [FEATURE #341](https://github.com/rust-lang/regex/issues/341): + Support nested character classes and intersection operation. + For example, `[\p{Greek}&&\pL]` matches greek letters and + `[[0-9]&&[^4]]` matches every decimal digit except `4`. + (Much thanks to @robinst, who contributed this awesome feature.) + +Bug fixes: + +* [BUG #321](https://github.com/rust-lang/regex/issues/321): + Fix bug in literal extraction and UTF-8 decoding. +* [BUG #326](https://github.com/rust-lang/regex/issues/326): + Add documentation tip about the `(?x)` flag. +* [BUG #333](https://github.com/rust-lang/regex/issues/333): + Show additional replacement example using curly braces. +* [BUG #334](https://github.com/rust-lang/regex/issues/334): + Fix bug when resolving captures after a match. +* [BUG #338](https://github.com/rust-lang/regex/issues/338): + Add example that uses `Captures::get` to API documentation. +* [BUG #353](https://github.com/rust-lang/regex/issues/353): + Fix RegexSet bug that caused match failure in some cases. +* [BUG #354](https://github.com/rust-lang/regex/pull/354): + Fix panic in parser when `(?x)` is used. +* [BUG #358](https://github.com/rust-lang/regex/issues/358): + Fix literal optimization bug with RegexSet. +* [BUG #359](https://github.com/rust-lang/regex/issues/359): + Fix example code in README. +* [BUG #365](https://github.com/rust-lang/regex/pull/365): + Fix bug in `rure_captures_len` in the C binding. +* [BUG #367](https://github.com/rust-lang/regex/issues/367): + Fix byte class bug that caused a panic. + + +0.2.1 +===== +One major bug with `replace_all` has been fixed along with a couple of other +touchups. + +* [BUG #312](https://github.com/rust-lang/regex/issues/312): + Fix documentation for `NoExpand` to reference correct lifetime parameter. +* [BUG #314](https://github.com/rust-lang/regex/issues/314): + Fix a bug with `replace_all` when replacing a match with the empty string. +* [BUG #316](https://github.com/rust-lang/regex/issues/316): + Note a missing breaking change from the `0.2.0` CHANGELOG entry. + (`RegexBuilder::compile` was renamed to `RegexBuilder::build`.) +* [BUG #324](https://github.com/rust-lang/regex/issues/324): + Compiling `regex` should only require one version of `memchr` crate. + + +0.2.0 +===== +This is a new major release of the regex crate, and is an implementation of the +[regex 1.0 RFC](https://github.com/rust-lang/rfcs/blob/master/text/1620-regex-1.0.md). +We are releasing a `0.2` first, and if there are no major problems, we will +release a `1.0` shortly. For `0.2`, the minimum *supported* Rust version is +1.12. + +There are a number of **breaking changes** in `0.2`. They are split into two +types. The first type correspond to breaking changes in regular expression +syntax. The second type correspond to breaking changes in the API. + +Breaking changes for regex syntax: + +* POSIX character classes now require double bracketing. Previously, the regex + `[:upper:]` would parse as the `upper` POSIX character class. Now it parses + as the character class containing the characters `:upper:`. The fix to this + change is to use `[[:upper:]]` instead. Note that variants like + `[[:upper:][:blank:]]` continue to work. +* The character `[` must always be escaped inside a character class. +* The characters `&`, `-` and `~` must be escaped if any one of them are + repeated consecutively. For example, `[&]`, `[\&]`, `[\&\&]`, `[&-&]` are all + equivalent while `[&&]` is illegal. (The motivation for this and the prior + change is to provide a backwards compatible path for adding character class + set notation.) +* A `bytes::Regex` now has Unicode mode enabled by default (like the main + `Regex` type). This means regexes compiled with `bytes::Regex::new` that + don't have the Unicode flag set should add `(?-u)` to recover the original + behavior. + +Breaking changes for the regex API: + +* `find` and `find_iter` now **return `Match` values instead of + `(usize, usize)`.** `Match` values have `start` and `end` methods, which + return the match offsets. `Match` values also have an `as_str` method, + which returns the text of the match itself. +* The `Captures` type now only provides a single iterator over all capturing + matches, which should replace uses of `iter` and `iter_pos`. Uses of + `iter_named` should use the `capture_names` method on `Regex`. +* The `at` method on the `Captures` type has been renamed to `get`, and it + now returns a `Match`. Similarly, the `name` method on `Captures` now returns + a `Match`. +* The `replace` methods now return `Cow` values. The `Cow::Borrowed` variant + is returned when no replacements are made. +* The `Replacer` trait has been completely overhauled. This should only + impact clients that implement this trait explicitly. Standard uses of + the `replace` methods should continue to work unchanged. If you implement + the `Replacer` trait, please consult the new documentation. +* The `quote` free function has been renamed to `escape`. +* The `Regex::with_size_limit` method has been removed. It is replaced by + `RegexBuilder::size_limit`. +* The `RegexBuilder` type has switched from owned `self` method receivers to + `&mut self` method receivers. Most uses will continue to work unchanged, but + some code may require naming an intermediate variable to hold the builder. +* The `compile` method on `RegexBuilder` has been renamed to `build`. +* The free `is_match` function has been removed. It is replaced by compiling + a `Regex` and calling its `is_match` method. +* The `PartialEq` and `Eq` impls on `Regex` have been dropped. If you relied + on these impls, the fix is to define a wrapper type around `Regex`, impl + `Deref` on it and provide the necessary impls. +* The `is_empty` method on `Captures` has been removed. This always returns + `false`, so its use is superfluous. +* The `Syntax` variant of the `Error` type now contains a string instead of + a `regex_syntax::Error`. If you were examining syntax errors more closely, + you'll need to explicitly use the `regex_syntax` crate to re-parse the regex. +* The `InvalidSet` variant of the `Error` type has been removed since it is + no longer used. +* Most of the iterator types have been renamed to match conventions. If you + were using these iterator types explicitly, please consult the documentation + for its new name. For example, `RegexSplits` has been renamed to `Split`. + +A number of bugs have been fixed: + +* [BUG #151](https://github.com/rust-lang/regex/issues/151): + The `Replacer` trait has been changed to permit the caller to control + allocation. +* [BUG #165](https://github.com/rust-lang/regex/issues/165): + Remove the free `is_match` function. +* [BUG #166](https://github.com/rust-lang/regex/issues/166): + Expose more knobs (available in `0.1`) and remove `with_size_limit`. +* [BUG #168](https://github.com/rust-lang/regex/issues/168): + Iterators produced by `Captures` now have the correct lifetime parameters. +* [BUG #175](https://github.com/rust-lang/regex/issues/175): + Fix a corner case in the parsing of POSIX character classes. +* [BUG #178](https://github.com/rust-lang/regex/issues/178): + Drop the `PartialEq` and `Eq` impls on `Regex`. +* [BUG #179](https://github.com/rust-lang/regex/issues/179): + Remove `is_empty` from `Captures` since it always returns false. +* [BUG #276](https://github.com/rust-lang/regex/issues/276): + Position of named capture can now be retrieved from a `Captures`. +* [BUG #296](https://github.com/rust-lang/regex/issues/296): + Remove winapi/kernel32-sys dependency on UNIX. +* [BUG #307](https://github.com/rust-lang/regex/issues/307): + Fix error on emscripten. + + +0.1.80 +====== +* [PR #292](https://github.com/rust-lang/regex/pull/292): + Fixes bug #291, which was introduced by PR #290. + +0.1.79 +====== +* Require regex-syntax 0.3.8. + +0.1.78 +====== +* [PR #290](https://github.com/rust-lang/regex/pull/290): + Fixes bug #289, which caused some regexes with a certain combination + of literals to match incorrectly. + +0.1.77 +====== +* [PR #281](https://github.com/rust-lang/regex/pull/281): + Fixes bug #280 by disabling all literal optimizations when a pattern + is partially anchored. + +0.1.76 +====== +* Tweak criteria for using the Teddy literal matcher. + +0.1.75 +====== +* [PR #275](https://github.com/rust-lang/regex/pull/275): + Improves match verification performance in the Teddy SIMD searcher. +* [PR #278](https://github.com/rust-lang/regex/pull/278): + Replaces slow substring loop in the Teddy SIMD searcher with Aho-Corasick. +* Implemented DoubleEndedIterator on regex set match iterators. + +0.1.74 +====== +* Release regex-syntax 0.3.5 with a minor bug fix. +* Fix bug #272. +* Fix bug #277. +* [PR #270](https://github.com/rust-lang/regex/pull/270): + Fixes bugs #264, #268 and an unreported where the DFA cache size could be + drastically under estimated in some cases (leading to high unexpected memory + usage). + +0.1.73 +====== +* Release `regex-syntax 0.3.4`. +* Bump `regex-syntax` dependency version for `regex` to `0.3.4`. + +0.1.72 +====== +* [PR #262](https://github.com/rust-lang/regex/pull/262): + Fixes a number of small bugs caught by fuzz testing (AFL). + +0.1.71 +====== +* [PR #236](https://github.com/rust-lang/regex/pull/236): + Fix a bug in how suffix literals were extracted, which could lead + to invalid match behavior in some cases. + +0.1.70 +====== +* [PR #231](https://github.com/rust-lang/regex/pull/231): + Add SIMD accelerated multiple pattern search. +* [PR #228](https://github.com/rust-lang/regex/pull/228): + Reintroduce the reverse suffix literal optimization. +* [PR #226](https://github.com/rust-lang/regex/pull/226): + Implements NFA state compression in the lazy DFA. +* [PR #223](https://github.com/rust-lang/regex/pull/223): + A fully anchored RegexSet can now short-circuit. + +0.1.69 +====== +* [PR #216](https://github.com/rust-lang/regex/pull/216): + Tweak the threshold for running backtracking. +* [PR #217](https://github.com/rust-lang/regex/pull/217): + Add upper limit (from the DFA) to capture search (for the NFA). +* [PR #218](https://github.com/rust-lang/regex/pull/218): + Add rure, a C API. + +0.1.68 +====== +* [PR #210](https://github.com/rust-lang/regex/pull/210): + Fixed a performance bug in `bytes::Regex::replace` where `extend` was used + instead of `extend_from_slice`. +* [PR #211](https://github.com/rust-lang/regex/pull/211): + Fixed a bug in the handling of word boundaries in the DFA. +* [PR #213](https://github.com/rust-lang/pull/213): + Added RE2 and Tcl to the benchmark harness. Also added a CLI utility from + running regexes using any of the following regex engines: PCRE1, PCRE2, + Oniguruma, RE2, Tcl and of course Rust's own regexes. + +0.1.67 +====== +* [PR #201](https://github.com/rust-lang/regex/pull/201): + Fix undefined behavior in the `regex!` compiler plugin macro. +* [PR #205](https://github.com/rust-lang/regex/pull/205): + More improvements to DFA performance. Competitive with RE2. See PR for + benchmarks. +* [PR #209](https://github.com/rust-lang/regex/pull/209): + Release 0.1.66 was semver incompatible since it required a newer version + of Rust than previous releases. This PR fixes that. (And `0.1.66` was + yanked.) + +0.1.66 +====== +* Speculative support for Unicode word boundaries was added to the DFA. This + should remove the last common case that disqualified use of the DFA. +* An optimization that scanned for suffix literals and then matched the regular + expression in reverse was removed because it had worst case quadratic time + complexity. It was replaced with a more limited optimization where, given any + regex of the form `re$`, it will be matched in reverse from the end of the + haystack. +* [PR #202](https://github.com/rust-lang/regex/pull/202): + The inner loop of the DFA was heavily optimized to improve cache locality + and reduce the overall number of instructions run on each iteration. This + represents the first use of `unsafe` in `regex` (to elide bounds checks). +* [PR #200](https://github.com/rust-lang/regex/pull/200): + Use of the `mempool` crate (which used thread local storage) was replaced + with a faster version of a similar API in @Amanieu's `thread_local` crate. + It should reduce contention when using a regex from multiple threads + simultaneously. +* PCRE2 JIT benchmarks were added. A benchmark comparison can be found + [here](https://gist.github.com/anonymous/14683c01993e91689f7206a18675901b). + (Includes a comparison with PCRE1's JIT and Oniguruma.) +* A bug where word boundaries weren't being matched correctly in the DFA was + fixed. This only affected use of `bytes::Regex`. +* [#160](https://github.com/rust-lang/regex/issues/160): + `Captures` now has a `Debug` impl. diff -Nru cargo-0.25.0/vendor/regex-0.2.10/ci/after_success.sh cargo-0.26.0/vendor/regex-0.2.10/ci/after_success.sh --- cargo-0.25.0/vendor/regex-0.2.10/ci/after_success.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/ci/after_success.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +#!/bin/bash + +# This runs only when a commit is pushed to master. It is responsible for +# updating docs and computing coverage statistics. + +set -e + +if [ "$TRAVIS_RUST_VERSION" != "nightly" ] || [ "$TRAVIS_PULL_REQUEST" != "false" ] || [ "$TRAVIS_BRANCH" != "master" ]; then + exit 0 +fi + +env + +# Install kcov. +tmp=$(mktemp -d) +pushd "$tmp" +wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz +tar zxf master.tar.gz +mkdir kcov-master/build +cd kcov-master/build +cmake .. +make +make install DESTDIR="$tmp" +popd +PATH="$tmp/usr/local/bin:$PATH" ./ci/run-kcov --coveralls-id $TRAVIS_JOB_ID diff -Nru cargo-0.25.0/vendor/regex-0.2.10/ci/run-kcov cargo-0.26.0/vendor/regex-0.2.10/ci/run-kcov --- cargo-0.25.0/vendor/regex-0.2.10/ci/run-kcov 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/ci/run-kcov 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,44 @@ +#!/bin/bash + +set -e + +tests=( + default + default_bytes + backtrack + backtrack_utf8bytes + backtrack_bytes + nfa + nfa_utf8bytes + nfa_bytes + regex +) +tmpdir=$(mktemp -d) +coveralls_id= + +while true; do + case "$1" in + --coveralls-id) + coveralls_id="$2" + shift 2 + ;; + *) + break + ;; + esac +done + +cargo test --no-run --verbose --jobs 4 --features unstable +for t in ${tests[@]}; do + kcov \ + --verify \ + --include-pattern '/regex/src/' \ + "$tmpdir/$t" \ + $(find ./target/debug -executable -wholename "./target/debug/$t-*" | head -n1) +done + +if [ -n "$coveralls_id" ]; then + kcov --verify --coveralls-id=$coveralls_id --merge target/cov "$tmpdir"/* +else + kcov --verify --merge target/cov "$tmpdir"/* +fi diff -Nru cargo-0.25.0/vendor/regex-0.2.10/ci/run-shootout-test cargo-0.26.0/vendor/regex-0.2.10/ci/run-shootout-test --- cargo-0.25.0/vendor/regex-0.2.10/ci/run-shootout-test 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/ci/run-shootout-test 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,18 @@ +#!/bin/bash + +set -e + +cargo build --example shootout-regex-dna +diff \ + ./examples/regexdna-output.txt \ + <(./target/debug/examples/shootout-regex-dna < ./examples/regexdna-input.txt) + +cargo build --example shootout-regex-dna-single +diff \ + ./examples/regexdna-output.txt \ + <(./target/debug/examples/shootout-regex-dna-single < ./examples/regexdna-input.txt) + +cargo build --example shootout-regex-dna-cheat +diff \ + ./examples/regexdna-output.txt \ + <(./target/debug/examples/shootout-regex-dna-cheat < ./examples/regexdna-input.txt) diff -Nru cargo-0.25.0/vendor/regex-0.2.10/ci/script.sh cargo-0.26.0/vendor/regex-0.2.10/ci/script.sh --- cargo-0.25.0/vendor/regex-0.2.10/ci/script.sh 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/ci/script.sh 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,46 @@ +#!/bin/sh + +# This is the main CI script for testing the regex crate and its sub-crates. + +set -ex + +# Builds the regex crate and runs tests. +cargo build --verbose +cargo doc --verbose + +# If we're testing on an older version of Rust, then only check that we +# can build the crate. This is because the dev dependencies might be updated +# more frequently, and therefore might require a newer version of Rust. +# +# This isn't ideal. It's a compromise. +if [ "$TRAVIS_RUST_VERSION" = "1.12.0" ]; then + exit +fi + +# Run tests. If we have nightly, then enable our nightly features. +if [ "$TRAVIS_RUST_VERSION" = "nightly" ]; then + cargo test --verbose --features unstable +else + cargo test --verbose +fi + +# Run a test that confirms the shootout benchmarks are correct. +ci/run-shootout-test + +# Run tests on regex-syntax crate. +cargo test --verbose --manifest-path regex-syntax/Cargo.toml +cargo doc --verbose --manifest-path regex-syntax/Cargo.toml + +# Run tests on regex-capi crate. +cargo build --verbose --manifest-path regex-capi/Cargo.toml +(cd regex-capi/ctest && ./compile && LD_LIBRARY_PATH=../../target/debug ./test) +(cd regex-capi/examples && ./compile && LD_LIBRARY_PATH=../../target/debug ./iter) + +# Make sure benchmarks compile. Don't run them though because they take a +# very long time. Also, check that we can build the regex-debug tool. +if [ "$TRAVIS_RUST_VERSION" = "nightly" ]; then + cargo build --verbose --manifest-path regex-debug/Cargo.toml + for x in rust rust-bytes pcre1 onig; do + (cd bench && ./run $x --no-run --verbose) + done +fi diff -Nru cargo-0.25.0/vendor/regex-0.2.10/examples/regexdna-input.txt cargo-0.26.0/vendor/regex-0.2.10/examples/regexdna-input.txt --- cargo-0.25.0/vendor/regex-0.2.10/examples/regexdna-input.txt 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/examples/regexdna-input.txt 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1671 @@ +>ONE Homo sapiens alu +GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGA +TCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACT +AAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAG +GCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCG +CCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGT +GGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCA +GGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAA +TTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAG +AATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCA +GCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGT +AATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACC +AGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTG +GTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACC +CGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAG +AGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTT +TGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACA +TGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCT +GTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGG +TTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGT +CTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGG +CGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCG +TCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTA +CTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCG +AGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCG +GGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACC +TGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAA +TACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGA +GGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACT +GCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTC +ACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGT +TCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGC +CGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCG +CTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTG +GGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCC +CAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCT +GGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGC +GCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGA +GGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGA +GACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGA +GGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTG +AAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAAT +CCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCA +GTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAA +AAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGC +GGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCT +ACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGG +GAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATC +GCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGC +GGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGG +TCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAA +AAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAG +GAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACT +CCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCC +TGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAG +ACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGC +GTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGA +ACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGA +CAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCA +CTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCA +ACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCG +CCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGG +AGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTC +CGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCG +AGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACC +CCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAG +CTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAG +CCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGG +CCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATC +ACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAA +AAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGC +TGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCC +ACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGG +CTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGG +AGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATT +AGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAA +TCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGC +CTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAA +TCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAG +CCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGT +GGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCG +GGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAG +CGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTG +GGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATG +GTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGT +AATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTT +GCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCT +CAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCG +GGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTC +TCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACT +CGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAG +ATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGG +CGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTG +AGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATA +CAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGG +CAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGC +ACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCAC +GCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTC +GAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCG +GGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCT +TGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGG +CGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCA +GCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGG +CCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGC +GCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGG +CGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGA +CTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGG +CCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAA +ACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCC +CAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGT +GAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAA +AGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGG +ATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTAC +TAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGA +GGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGC +GCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGG +TGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTC +AGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAA +ATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGA +GAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC +AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTG +TAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGAC +CAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGT +GGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAAC +CCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACA +GAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACT +TTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAAC +ATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCC +TGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAG +GTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCG +TCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAG +GCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCC +GTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCT +ACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCC +GAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCC +GGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCAC +CTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAA +ATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTG +AGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCAC +TGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCT +CACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAG +TTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAG +CCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATC +GCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCT +GGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATC +CCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCC +TGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGG +CGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG +AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCG +AGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGG +AGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGT +GAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAA +TCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGC +AGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCA +AAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGG +CGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTC +TACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCG +GGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGAT +CGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCG +CGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAG +GTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACA +AAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCA +GGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCAC +TCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGC +CTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGA +GACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGG +CGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTG +AACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCG +ACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGC +ACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCC +AACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGC +GCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCG +GAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACT +CCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCC +GAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAAC +CCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA +GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGA +GCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAG +GCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGAT +CACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTA +AAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGG +CTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGC +CACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTG +GCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAG +GAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAAT +TAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGA +ATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAG +CCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTA +ATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCA +GCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGG +TGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCC +GGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGA +GCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTT +GGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACAT +GGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTG +TAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGT +TGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTC +TCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGC +GGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGT +CTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTAC +TCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGA +GATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGG +GCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCT +GAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT +ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAG +GCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTG +CACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCA +CGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTT +CGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCC +GGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGC +TTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGG +GCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCC +AGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTG +GCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCG +CGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAG +GCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAG +ACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAG +GCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGA +AACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATC +CCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAG +TGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAA +AAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCG +GATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTA +CTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGG +AGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCG +CGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCG +GTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGT +CAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAA +AATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGG +AGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTC +CAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCT +GTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA +CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCG +TGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAA +CCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGAC +AGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCAC +TTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAA +CATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGC +CTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGA +GGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCC +GTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGA +GGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCC +CGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGC +TACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGC +CGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGC +CGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCA +CCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAA +AATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCT +GAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCA +CTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGC +TCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGA +GTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTA +GCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAAT +CGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCC +TGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAAT +CCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGC +CTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTG +GCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGG +GAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGC +GAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG +GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGG +TGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTA +ATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTG +CAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTC +AAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGG +GCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCT +CTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTC +GGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGA +TCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGC +GCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGA +GGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATAC +AAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGC +AGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCA +CTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACG +CCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCG +AGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGG +GCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTT +GAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGC +GACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAG +CACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGC +CAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCG +CGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGC +GGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGAC +TCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGC +CGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAA +CCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCC +AGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTG +AGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA +GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGA +TCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACT +AAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAG +GCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCG +CCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGT +GGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCA +GGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAA +TTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAG +AATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCA +GCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGT +AATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACC +AGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTG +GTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACC +CGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAG +AGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTT +TGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACA +TGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCT +GTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGG +TTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGT +CTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGG +CGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCG +TCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTA +CTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCG +AGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCG +GGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACC +TGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAA +TACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGA +GGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACT +GCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTC +ACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGT +TCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGC +CGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCG +CTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTG +GGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCC +CAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCT +GGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGC +GCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGA +GGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGA +GACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGA +GGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTG +AAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAAT +CCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCA +GTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAA +AAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGC +GGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCT +ACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGG +GAGGCTGAGGCAGGAGAATC +>TWO IUB ambiguity codes +cttBtatcatatgctaKggNcataaaSatgtaaaDcDRtBggDtctttataattcBgtcg +tactDtDagcctatttSVHtHttKtgtHMaSattgWaHKHttttagacatWatgtRgaaa +NtactMcSMtYtcMgRtacttctWBacgaaatatagScDtttgaagacacatagtVgYgt +cattHWtMMWcStgttaggKtSgaYaaccWStcgBttgcgaMttBYatcWtgacaYcaga +gtaBDtRacttttcWatMttDBcatWtatcttactaBgaYtcttgttttttttYaaScYa +HgtgttNtSatcMtcVaaaStccRcctDaataataStcYtRDSaMtDttgttSagtRRca +tttHatSttMtWgtcgtatSSagactYaaattcaMtWatttaSgYttaRgKaRtccactt +tattRggaMcDaWaWagttttgacatgttctacaaaRaatataataaMttcgDacgaSSt +acaStYRctVaNMtMgtaggcKatcttttattaaaaagVWaHKYagtttttatttaacct +tacgtVtcVaattVMBcttaMtttaStgacttagattWWacVtgWYagWVRctDattBYt +gtttaagaagattattgacVatMaacattVctgtBSgaVtgWWggaKHaatKWcBScSWa +accRVacacaaactaccScattRatatKVtactatatttHttaagtttSKtRtacaaagt +RDttcaaaaWgcacatWaDgtDKacgaacaattacaRNWaatHtttStgttattaaMtgt +tgDcgtMgcatBtgcttcgcgaDWgagctgcgaggggVtaaScNatttacttaatgacag +cccccacatYScaMgtaggtYaNgttctgaMaacNaMRaacaaacaKctacatagYWctg +ttWaaataaaataRattagHacacaagcgKatacBttRttaagtatttccgatctHSaat +actcNttMaagtattMtgRtgaMgcataatHcMtaBSaRattagttgatHtMttaaKagg +YtaaBataSaVatactWtataVWgKgttaaaacagtgcgRatatacatVtHRtVYataSa +KtWaStVcNKHKttactatccctcatgWHatWaRcttactaggatctataDtDHBttata +aaaHgtacVtagaYttYaKcctattcttcttaataNDaaggaaaDYgcggctaaWSctBa +aNtgctggMBaKctaMVKagBaactaWaDaMaccYVtNtaHtVWtKgRtcaaNtYaNacg +gtttNattgVtttctgtBaWgtaattcaagtcaVWtactNggattctttaYtaaagccgc +tcttagHVggaYtgtNcDaVagctctctKgacgtatagYcctRYHDtgBattDaaDgccK +tcHaaStttMcctagtattgcRgWBaVatHaaaataYtgtttagMDMRtaataaggatMt +ttctWgtNtgtgaaaaMaatatRtttMtDgHHtgtcattttcWattRSHcVagaagtacg +ggtaKVattKYagactNaatgtttgKMMgYNtcccgSKttctaStatatNVataYHgtNa +BKRgNacaactgatttcctttaNcgatttctctataScaHtataRagtcRVttacDSDtt +aRtSatacHgtSKacYagttMHtWataggatgactNtatSaNctataVtttRNKtgRacc +tttYtatgttactttttcctttaaacatacaHactMacacggtWataMtBVacRaSaatc +cgtaBVttccagccBcttaRKtgtgcctttttRtgtcagcRttKtaaacKtaaatctcac +aattgcaNtSBaaccgggttattaaBcKatDagttactcttcattVtttHaaggctKKga +tacatcBggScagtVcacattttgaHaDSgHatRMaHWggtatatRgccDttcgtatcga +aacaHtaagttaRatgaVacttagattVKtaaYttaaatcaNatccRttRRaMScNaaaD +gttVHWgtcHaaHgacVaWtgttScactaagSgttatcttagggDtaccagWattWtRtg +ttHWHacgattBtgVcaYatcggttgagKcWtKKcaVtgaYgWctgYggVctgtHgaNcV +taBtWaaYatcDRaaRtSctgaHaYRttagatMatgcatttNattaDttaattgttctaa +ccctcccctagaWBtttHtBccttagaVaatMcBHagaVcWcagBVttcBtaYMccagat +gaaaaHctctaacgttagNWRtcggattNatcRaNHttcagtKttttgWatWttcSaNgg +gaWtactKKMaacatKatacNattgctWtatctaVgagctatgtRaHtYcWcttagccaa +tYttWttaWSSttaHcaaaaagVacVgtaVaRMgattaVcDactttcHHggHRtgNcctt +tYatcatKgctcctctatVcaaaaKaaaagtatatctgMtWtaaaacaStttMtcgactt +taSatcgDataaactaaacaagtaaVctaggaSccaatMVtaaSKNVattttgHccatca +cBVctgcaVatVttRtactgtVcaattHgtaaattaaattttYtatattaaRSgYtgBag +aHSBDgtagcacRHtYcBgtcacttacactaYcgctWtattgSHtSatcataaatataHt +cgtYaaMNgBaatttaRgaMaatatttBtttaaaHHKaatctgatWatYaacttMctctt +ttVctagctDaaagtaVaKaKRtaacBgtatccaaccactHHaagaagaaggaNaaatBW +attccgStaMSaMatBttgcatgRSacgttVVtaaDMtcSgVatWcaSatcttttVatag +ttactttacgatcaccNtaDVgSRcgVcgtgaacgaNtaNatatagtHtMgtHcMtagaa +attBgtataRaaaacaYKgtRccYtatgaagtaataKgtaaMttgaaRVatgcagaKStc +tHNaaatctBBtcttaYaBWHgtVtgacagcaRcataWctcaBcYacYgatDgtDHccta +aagacYRcaggattHaYgtKtaatgcVcaataMYacccatatcacgWDBtgaatcBaata +cKcttRaRtgatgaBDacggtaattaaYtataStgVHDtDctgactcaaatKtacaatgc +gYatBtRaDatHaactgtttatatDttttaaaKVccYcaaccNcBcgHaaVcattHctcg +attaaatBtatgcaaaaatYMctSactHatacgaWacattacMBgHttcgaatVaaaaca +BatatVtctgaaaaWtctRacgBMaatSgRgtgtcgactatcRtattaScctaStagKga +DcWgtYtDDWKRgRtHatRtggtcgaHgggcgtattaMgtcagccaBggWVcWctVaaat +tcgNaatcKWagcNaHtgaaaSaaagctcYctttRVtaaaatNtataaccKtaRgtttaM +tgtKaBtRtNaggaSattHatatWactcagtgtactaKctatttgRYYatKatgtccgtR +tttttatttaatatVgKtttgtatgtNtataRatWYNgtRtHggtaaKaYtKSDcatcKg +taaYatcSRctaVtSMWtVtRWHatttagataDtVggacagVcgKWagBgatBtaaagNc +aRtagcataBggactaacacRctKgttaatcctHgDgttKHHagttgttaatgHBtatHc +DaagtVaBaRccctVgtgDtacRHSctaagagcggWYaBtSaKtHBtaaactYacgNKBa +VYgtaacttagtVttcttaatgtBtatMtMtttaattaatBWccatRtttcatagVgMMt +agctStKctaMactacDNYgKYHgaWcgaHgagattacVgtttgtRaSttaWaVgataat +gtgtYtaStattattMtNgWtgttKaccaatagNYttattcgtatHcWtctaaaNVYKKt +tWtggcDtcgaagtNcagatacgcattaagaccWctgcagcttggNSgaNcHggatgtVt +catNtRaaBNcHVagagaaBtaaSggDaatWaatRccaVgggStctDaacataKttKatt +tggacYtattcSatcttagcaatgaVBMcttDattctYaaRgatgcattttNgVHtKcYR +aatRKctgtaaacRatVSagctgtWacBtKVatctgttttKcgtctaaDcaagtatcSat +aWVgcKKataWaYttcccSaatgaaaacccWgcRctWatNcWtBRttYaattataaNgac +acaatagtttVNtataNaYtaatRaVWKtBatKagtaatataDaNaaaaataMtaagaaS +tccBcaatNgaataWtHaNactgtcDtRcYaaVaaaaaDgtttRatctatgHtgttKtga +aNSgatactttcgagWaaatctKaaDaRttgtggKKagcDgataaattgSaacWaVtaNM +acKtcaDaaatttctRaaVcagNacaScRBatatctRatcctaNatWgRtcDcSaWSgtt +RtKaRtMtKaatgttBHcYaaBtgatSgaSWaScMgatNtctcctatttctYtatMatMt +RRtSaattaMtagaaaaStcgVgRttSVaScagtgDtttatcatcatacRcatatDctta +tcatVRtttataaHtattcYtcaaaatactttgVctagtaaYttagatagtSYacKaaac +gaaKtaaatagataatSatatgaaatSgKtaatVtttatcctgKHaatHattagaaccgt +YaaHactRcggSBNgtgctaaBagBttgtRttaaattYtVRaaaattgtaatVatttctc +ttcatgBcVgtgKgaHaaatattYatagWacNctgaaMcgaattStagWaSgtaaKagtt +ttaagaDgatKcctgtaHtcatggKttVDatcaaggtYcgccagNgtgcVttttagagat +gctaccacggggtNttttaSHaNtatNcctcatSaaVgtactgBHtagcaYggYVKNgta +KBcRttgaWatgaatVtagtcgattYgatgtaatttacDacSctgctaaaStttaWMagD +aaatcaVYctccgggcgaVtaaWtStaKMgDtttcaaMtVgBaatccagNaaatcYRMBg +gttWtaaScKttMWtYataRaDBMaDataatHBcacDaaKDactaMgagttDattaHatH +taYatDtattDcRNStgaatattSDttggtattaaNSYacttcDMgYgBatWtaMagact +VWttctttgYMaYaacRgHWaattgRtaagcattctMKVStatactacHVtatgatcBtV +NataaBttYtSttacKgggWgYDtgaVtYgatDaacattYgatggtRDaVDttNactaSa +MtgNttaacaaSaBStcDctaccacagacgcaHatMataWKYtaYattMcaMtgSttDag +cHacgatcaHttYaKHggagttccgatYcaatgatRaVRcaagatcagtatggScctata +ttaNtagcgacgtgKaaWaactSgagtMYtcttccaKtStaacggMtaagNttattatcg +tctaRcactctctDtaacWYtgaYaSaagaWtNtatttRacatgNaatgttattgWDDcN +aHcctgaaHacSgaataaRaataMHttatMtgaSDSKatatHHaNtacagtccaYatWtc +actaactatKDacSaStcggataHgYatagKtaatKagStaNgtatactatggRHacttg +tattatgtDVagDVaRctacMYattDgtttYgtctatggtKaRSttRccRtaaccttaga +gRatagSaaMaacgcaNtatgaaatcaRaagataatagatactcHaaYKBctccaagaRa +BaStNagataggcgaatgaMtagaatgtcaKttaaatgtaWcaBttaatRcggtgNcaca +aKtttScRtWtgcatagtttWYaagBttDKgcctttatMggNttattBtctagVtacata +aaYttacacaaRttcYtWttgHcaYYtaMgBaBatctNgcDtNttacgacDcgataaSat +YaSttWtcctatKaatgcagHaVaacgctgcatDtgttaSataaaaYSNttatagtaNYt +aDaaaNtggggacttaBggcHgcgtNtaaMcctggtVtaKcgNacNtatVaSWctWtgaW +cggNaBagctctgaYataMgaagatBSttctatacttgtgtKtaattttRagtDtacata +tatatgatNHVgBMtKtaKaNttDHaagatactHaccHtcatttaaagttVaMcNgHata +tKtaNtgYMccttatcaaNagctggacStttcNtggcaVtattactHaSttatgNMVatt +MMDtMactattattgWMSgtHBttStStgatatRaDaagattttctatMtaaaaaggtac +taaVttaSacNaatactgMttgacHaHRttgMacaaaatagttaatatWKRgacDgaRta +tatttattatcYttaWtgtBRtWatgHaaattHataagtVaDtWaVaWtgStcgtMSgaS +RgMKtaaataVacataatgtaSaatttagtcgaaHtaKaatgcacatcggRaggSKctDc +agtcSttcccStYtccRtctctYtcaaKcgagtaMttttcRaYDttgttatctaatcata +NctctgctatcaMatactataggDaHaaSttMtaDtcNatataattctMcStaaBYtaNa +gatgtaatHagagSttgWHVcttatKaYgDctcttggtgttMcRaVgSgggtagacaata +aDtaattSaDaNaHaBctattgNtaccaaRgaVtKNtaaYggHtaKKgHcatctWtctDt +ttctttggSDtNtaStagttataaacaattgcaBaBWggHgcaaaBtYgctaatgaaatW +cDcttHtcMtWWattBHatcatcaaatctKMagtDNatttWaBtHaaaNgMttaaStagt +tctctaatDtcRVaYttgttMtRtgtcaSaaYVgSWDRtaatagctcagDgcWWaaaBaa +RaBctgVgggNgDWStNaNBKcBctaaKtttDcttBaaggBttgaccatgaaaNgttttt +tttatctatgttataccaaDRaaSagtaVtDtcaWatBtacattaWacttaSgtattggD +gKaaatScaattacgWcagKHaaccaYcRcaRttaDttRtttHgaHVggcttBaRgtccc +tDatKaVtKtcRgYtaKttacgtatBtStaagcaattaagaRgBagSaattccSWYttta +ttVaataNctgHgttaaNBgcVYgtRtcccagWNaaaacaDNaBcaaaaRVtcWMgBagM +tttattacgDacttBtactatcattggaaatVccggttRttcatagttVYcatYaSHaHc +ttaaagcNWaHataaaRWtctVtRYtagHtaaaYMataHYtNBctNtKaatattStgaMc +BtRgctaKtgcScSttDgYatcVtggaaKtaagatWccHccgKYctaNNctacaWctttt +gcRtgtVcgaKttcMRHgctaHtVaataaDtatgKDcttatBtDttggNtacttttMtga +acRattaaNagaactcaaaBBVtcDtcgaStaDctgaaaSgttMaDtcgttcaccaaaag +gWtcKcgSMtcDtatgtttStaaBtatagDcatYatWtaaaBacaKgcaDatgRggaaYc +taRtccagattDaWtttggacBaVcHtHtaacDacYgtaatataMagaatgHMatcttat +acgtatttttatattacHactgttataMgStYaattYaccaattgagtcaaattaYtgta +tcatgMcaDcgggtcttDtKgcatgWRtataatatRacacNRBttcHtBgcRttgtgcgt +catacMtttBctatctBaatcattMttMYgattaaVYatgDaatVagtattDacaacDMa +tcMtHcccataagatgBggaccattVWtRtSacatgctcaaggggYtttDtaaNgNtaaB +atggaatgtctRtaBgBtcNYatatNRtagaacMgagSaSDDSaDcctRagtVWSHtVSR +ggaacaBVaccgtttaStagaacaMtactccagtttVctaaRaaHttNcttagcaattta +ttaatRtaaaatctaacDaBttggSagagctacHtaaRWgattcaaBtctRtSHaNtgta +cattVcaHaNaagtataccacaWtaRtaaVKgMYaWgttaKggKMtKcgWatcaDatYtK +SttgtacgaccNctSaattcDcatcttcaaaDKttacHtggttHggRRaRcaWacaMtBW +VHSHgaaMcKattgtaRWttScNattBBatYtaNRgcggaagacHSaattRtttcYgacc +BRccMacccKgatgaacttcgDgHcaaaaaRtatatDtatYVtttttHgSHaSaatagct +NYtaHYaVYttattNtttgaaaYtaKttWtctaNtgagaaaNctNDctaaHgttagDcRt +tatagccBaacgcaRBtRctRtggtaMYYttWtgataatcgaataattattataVaaaaa +ttacNRVYcaaMacNatRttcKatMctgaagactaattataaYgcKcaSYaatMNctcaa +cgtgatttttBacNtgatDccaattattKWWcattttatatatgatBcDtaaaagttgaa +VtaHtaHHtBtataRBgtgDtaataMttRtDgDcttattNtggtctatctaaBcatctaR +atgNacWtaatgaagtcMNaacNgHttatactaWgcNtaStaRgttaaHacccgaYStac +aaaatWggaYaWgaattattcMaactcBKaaaRVNcaNRDcYcgaBctKaacaaaaaSgc +tccYBBHYaVagaatagaaaacagYtctVccaMtcgtttVatcaatttDRtgWctagtac +RttMctgtDctttcKtWttttataaatgVttgBKtgtKWDaWagMtaaagaaattDVtag +gttacatcatttatgtcgMHaVcttaBtVRtcgtaYgBRHatttHgaBcKaYWaatcNSc +tagtaaaaatttacaatcactSWacgtaatgKttWattagttttNaggtctcaagtcact +attcttctaagKggaataMgtttcataagataaaaatagattatDgcBVHWgaBKttDgc +atRHaagcaYcRaattattatgtMatatattgHDtcaDtcaaaHctStattaatHaccga +cNattgatatattttgtgtDtRatagSacaMtcRtcattcccgacacSattgttKaWatt +NHcaacttccgtttSRtgtctgDcgctcaaMagVtBctBMcMcWtgtaacgactctcttR +ggRKSttgYtYatDccagttDgaKccacgVatWcataVaaagaataMgtgataaKYaaat +cHDaacgataYctRtcYatcgcaMgtNttaBttttgatttaRtStgcaacaaaataccVg +aaDgtVgDcStctatatttattaaaaRKDatagaaagaKaaYYcaYSgKStctccSttac +agtcNactttDVttagaaagMHttRaNcSaRaMgBttattggtttaRMggatggcKDgWR +tNaataataWKKacttcKWaaagNaBttaBatMHtccattaacttccccYtcBcYRtaga +ttaagctaaYBDttaNtgaaaccHcaRMtKtaaHMcNBttaNaNcVcgVttWNtDaBatg +ataaVtcWKcttRggWatcattgaRagHgaattNtatttctctattaattaatgaDaaMa +tacgttgggcHaYVaaNaDDttHtcaaHtcVVDgBVagcMacgtgttaaBRNtatRtcag +taagaggtttaagacaVaaggttaWatctccgtVtaDtcDatttccVatgtacNtttccg +tHttatKgScBatgtVgHtYcWagcaKtaMYaaHgtaattaSaHcgcagtWNaatNccNN +YcacgVaagaRacttctcattcccRtgtgtaattagcSttaaStWaMtctNNcSMacatt +ataaactaDgtatWgtagtttaagaaaattgtagtNagtcaataaatttgatMMYactaa +tatcggBWDtVcYttcDHtVttatacYaRgaMaacaStaatcRttttVtagaDtcacWat +ttWtgaaaagaaagNRacDtttStVatBaDNtaactatatcBSMcccaSttccggaMatg +attaaWatKMaBaBatttgataNctgttKtVaagtcagScgaaaDggaWgtgttttKtWt +atttHaatgtagttcactaaKMagttSYBtKtaYgaactcagagRtatagtVtatcaaaW +YagcgNtaDagtacNSaaYDgatBgtcgataacYDtaaactacagWDcYKaagtttatta +gcatcgagttKcatDaattgattatDtcagRtWSKtcgNtMaaaaacaMttKcaWcaaSV +MaaaccagMVtaMaDtMaHaBgaacataBBVtaatVYaNSWcSgNtDNaaKacacBttta +tKtgtttcaaHaMctcagtaacgtcgYtactDcgcctaNgagagcYgatattttaaattt +ccattttacatttDaaRctattttWctttacgtDatYtttcagacgcaaVttagtaaKaa +aRtgVtccataBggacttatttgtttaWNtgttVWtaWNVDaattgtatttBaagcBtaa +BttaaVatcHcaVgacattccNggtcgacKttaaaRtagRtctWagaYggtgMtataatM +tgaaRttattttgWcttNtDRRgMDKacagaaaaggaaaRStcccagtYccVattaNaaK +StNWtgacaVtagaagcttSaaDtcacaacgDYacWDYtgtttKatcVtgcMaDaSKStV +cgtagaaWaKaagtttcHaHgMgMtctataagBtKaaaKKcactggagRRttaagaBaaN +atVVcgRcKSttDaactagtSttSattgttgaaRYatggttVttaataaHttccaagDtg +atNWtaagHtgcYtaactRgcaatgMgtgtRaatRaNaacHKtagactactggaatttcg +ccataacgMctRgatgttaccctaHgtgWaYcactcacYaattcttaBtgacttaaacct +gYgaWatgBttcttVttcgttWttMcNYgtaaaatctYgMgaaattacNgaHgaacDVVM +tttggtHtctaaRgtacagacgHtVtaBMNBgattagcttaRcttacaHcRctgttcaaD +BggttKaacatgKtttYataVaNattccgMcgcgtagtRaVVaattaKaatggttRgaMc +agtatcWBttNtHagctaatctagaaNaaacaYBctatcgcVctBtgcaaagDgttVtga +HtactSNYtaaNccatgtgDacgaVtDcgKaRtacDcttgctaagggcagMDagggtBWR +tttSgccttttttaacgtcHctaVtVDtagatcaNMaVtcVacatHctDWNaataRgcgt +aVHaggtaaaaSgtttMtattDgBtctgatSgtRagagYtctSaKWaataMgattRKtaa +catttYcgtaacacattRWtBtcggtaaatMtaaacBatttctKagtcDtttgcBtKYYB +aKttctVttgttaDtgattttcttccacttgSaaacggaaaNDaattcYNNaWcgaaYat +tttMgcBtcatRtgtaaagatgaWtgaccaYBHgaatagataVVtHtttVgYBtMctaMt +cctgaDcYttgtccaaaRNtacagcMctKaaaggatttacatgtttaaWSaYaKttBtag +DacactagctMtttNaKtctttcNcSattNacttggaacaatDagtattRtgSHaataat +gccVgacccgatactatccctgtRctttgagaSgatcatatcgDcagWaaHSgctYYWta +tHttggttctttatVattatcgactaagtgtagcatVgtgHMtttgtttcgttaKattcM +atttgtttWcaaStNatgtHcaaaDtaagBaKBtRgaBgDtSagtatMtaacYaatYtVc +KatgtgcaacVaaaatactKcRgtaYtgtNgBBNcKtcttaccttKgaRaYcaNKtactt +tgagSBtgtRagaNgcaaaNcacagtVtttHWatgttaNatBgtttaatNgVtctgaata +tcaRtattcttttttttRaaKcRStctcggDgKagattaMaaaKtcaHacttaataataK +taRgDtKVBttttcgtKaggHHcatgttagHggttNctcgtatKKagVagRaaaggaaBt +NatttVKcRttaHctaHtcaaatgtaggHccaBataNaNaggttgcWaatctgatYcaaa +HaatWtaVgaaBttagtaagaKKtaaaKtRHatMaDBtBctagcatWtatttgWttVaaa +ScMNattRactttgtYtttaaaagtaagtMtaMaSttMBtatgaBtttaKtgaatgagYg +tNNacMtcNRacMMHcttWtgtRtctttaacaacattattcYaMagBaacYttMatcttK +cRMtgMNccattaRttNatHaHNaSaaHMacacaVaatacaKaSttHatattMtVatWga +ttttttaYctttKttHgScWaacgHtttcaVaaMgaacagNatcgttaacaaaaagtaca +HBNaattgttKtcttVttaaBtctgctacgBgcWtttcaggacacatMgacatcccagcg +gMgaVKaBattgacttaatgacacacaaaaaatRKaaBctacgtRaDcgtagcVBaacDS +BHaaaaSacatatacagacRNatcttNaaVtaaaataHattagtaaaaSWccgtatWatg +gDttaactattgcccatcttHaSgYataBttBaactattBtcHtgatcaataSttaBtat +KSHYttWggtcYtttBttaataccRgVatStaHaKagaatNtagRMNgtcttYaaSaact +cagDSgagaaYtMttDtMRVgWKWtgMaKtKaDttttgactatacataatcNtatNaHat +tVagacgYgatatatttttgtStWaaatctWaMgagaRttRatacgStgattcttaagaD +taWccaaatRcagcagaaNKagtaaDggcgccBtYtagSBMtactaaataMataBSacRM +gDgattMMgtcHtcaYDtRaDaacggttDaggcMtttatgttaNctaattaVacgaaMMt +aatDccSgtattgaRtWWaccaccgagtactMcgVNgctDctaMScatagcgtcaactat +acRacgHRttgctatttaatgaattataYKttgtaagWgtYttgcHgMtaMattWaWVta +RgcttgYgttBHtYataSccStBtgtagMgtDtggcVaaSBaatagDttgBgtctttctc +attttaNagtHKtaMWcYactVcgcgtatMVtttRacVagDaatcttgctBBcRDgcaac +KttgatSKtYtagBMagaRtcgBattHcBWcaactgatttaatttWDccatttatcgagS +KaWttataHactaHMttaatHtggaHtHagaatgtKtaaRactgtttMatacgatcaagD +gatKaDctataMggtHDtggHacctttRtatcttYattttgacttgaaSaataaatYcgB +aaaaccgNatVBttMacHaKaataagtatKgtcaagactcttaHttcggaattgttDtct +aaccHttttWaaatgaaatataaaWattccYDtKtaaaacggtgaggWVtctattagtga +ctattaagtMgtttaagcatttgSgaaatatccHaaggMaaaattttcWtatKctagDtY +tMcctagagHcactttactatacaaacattaacttaHatcVMYattYgVgtMttaaRtga +aataaDatcaHgtHHatKcDYaatcttMtNcgatYatgSaMaNtcttKcWataScKggta +tcttacgcttWaaagNatgMgHtctttNtaacVtgttcMaaRatccggggactcMtttaY +MtcWRgNctgNccKatcttgYDcMgattNYaRagatHaaHgKctcataRDttacatBatc +cattgDWttatttaWgtcggagaaaaatacaatacSNtgggtttccttacSMaagBatta +caMaNcactMttatgaRBacYcYtcaaaWtagctSaacttWgDMHgaggatgBVgcHaDt +ggaactttggtcNatNgtaKaBcccaNtaagttBaacagtatacDYttcctNgWgcgSMc +acatStctHatgRcNcgtacacaatRttMggaNKKggataaaSaYcMVcMgtaMaHtgat +tYMatYcggtcttcctHtcDccgtgRatcattgcgccgatatMaaYaataaYSggatagc +gcBtNtaaaScaKgttBgagVagttaKagagtatVaactaSacWactSaKatWccaKaaa +atBKgaaKtDMattttgtaaatcRctMatcaaMagMttDgVatggMaaWgttcgaWatga +aatttgRtYtattaWHKcRgctacatKttctaccaaHttRatctaYattaaWatVNccat +NgagtcKttKataStRaatatattcctRWatDctVagttYDgSBaatYgttttgtVaatt +taatagcagMatRaacttBctattgtMagagattaaactaMatVtHtaaatctRgaaaaa +aaatttWacaacaYccYDSaattMatgaccKtaBKWBattgtcaagcHKaagttMMtaat +ttcKcMagNaaKagattggMagaggtaatttYacatcWaaDgatMgKHacMacgcVaaca +DtaDatatYggttBcgtatgWgaSatttgtagaHYRVacaRtctHaaRtatgaactaata +tctSSBgggaaHMWtcaagatKgagtDaSatagttgattVRatNtctMtcSaagaSHaat +aNataataRaaRgattctttaataaagWaRHcYgcatgtWRcttgaaggaMcaataBRaa +ccagStaaacNtttcaatataYtaatatgHaDgcStcWttaacctaRgtYaRtataKtgM +ttttatgactaaaatttacYatcccRWtttHRtattaaatgtttatatttgttYaatMca +RcSVaaDatcgtaYMcatgtagacatgaaattgRtcaaYaaYtRBatKacttataccaNa +aattVaBtctggacaagKaaYaaatatWtMtatcYaaVNtcgHaactBaagKcHgtctac +aatWtaDtSgtaHcataHtactgataNctRgttMtDcDttatHtcgtacatcccaggStt +aBgtcacacWtccNMcNatMVaVgtccDYStatMaccDatggYaRKaaagataRatttHK +tSaaatDgataaacttaHgttgVBtcttVttHgDacgaKatgtatatNYataactctSat +atatattgcHRRYttStggaactHgttttYtttaWtatMcttttctatctDtagVHYgMR +BgtHttcctaatYRttKtaagatggaVRataKDctaMtKBNtMtHNtWtttYcVtattMc +gRaacMcctNSctcatttaaagDcaHtYccSgatgcaatYaaaaDcttcgtaWtaattct +cgttttScttggtaatctttYgtctaactKataHacctMctcttacHtKataacacagcN +RatgKatttttSaaatRYcgDttaMRcgaaattactMtgcgtaagcgttatBtttttaat +taagtNacatHgttcRgacKcBBtVgatKttcgaBaatactDRgtRtgaNacWtcacYtt +aaKcgttctHaKttaNaMgWgWaggtctRgaKgWttSttBtDcNtgtttacaaatYcDRt +gVtgcctattcNtctaaaDMNttttNtggctgagaVctDaacVtWccaagtaacacaNct +gaScattccDHcVBatcgatgtMtaatBgHaatDctMYgagaatgYWKcctaatNaStHa +aaKccgHgcgtYaaYtattgtStgtgcaaRtattaKatattagaWVtcaMtBagttatta +gNaWHcVgcaattttDcMtgtaRHVYtHtctgtaaaaHVtMKacatcgNaatttMatatg +ttgttactagWYtaRacgataKagYNKcattataNaRtgaacKaYgcaaYYacaNccHat +MatDcNgtHttRaWttagaaDcaaaaaatagggtKDtStaDaRtaVtHWKNtgtattVct +SVgRgataDaRaWataBgaagaaKtaataaYgDcaStaNgtaDaaggtattHaRaWMYaY +aWtggttHYgagVtgtgcttttcaaDKcagVcgttagacNaaWtagtaataDttctggtt +VcatcataaagtgKaaaNaMtaBBaattaatWaattgctHaVKaSgDaaVKaHtatatat +HatcatSBagNgHtatcHYMHgttDgtaHtBttWatcgtttaRaattgStKgSKNWKatc +agDtctcagatttctRtYtBatBgHHtKaWtgYBgacVVWaKtacKcDttKMaKaVcggt +gttataagaataaHaatattagtataatMHgttYgaRttagtaRtcaaVatacggtcMcg +agtaaRttacWgactKRYataaaagSattYaWgagatYagKagatgSaagKgttaatMgg +tataatgttWYttatgagaaacctNVataatHcccKtDctcctaatactggctHggaSag +gRtKHaWaattcgSatMatttagaggcYtctaMcgctcataSatatgRagacNaaDagga +VBagaYttKtacNaKgtSYtagttggaWcatcWttaatctatgaVtcgtgtMtatcaYcg +tRccaaYgDctgcMgtgtWgacWtgataacacgcgctBtgttaKtYDtatDcatcagKaV +MctaatcttgVcaaRgcRMtDcgattaHttcaNatgaatMtactacVgtRgatggaWttt +actaaKatgagSaaKggtaNtactVaYtaaKRagaacccacaMtaaMtKtatBcttgtaa +WBtMctaataaVcDaaYtcRHBtcgttNtaaHatttBNgRStVDattBatVtaagttaYa +tVattaagaBcacggtSgtVtatttaRattgatgtaHDKgcaatattKtggcctatgaWD +KRYcggattgRctatNgatacaatMNttctgtcRBYRaaaHctNYattcHtaWcaattct +BtMKtVgYataatMgYtcagcttMDataVtggRtKtgaatgccNcRttcaMtRgattaac +attRcagcctHtWMtgtDRagaKaBtgDttYaaaaKatKgatctVaaYaacWcgcatagB +VtaNtRtYRaggBaaBtgKgttacataagagcatgtRattccacttaccatRaaatgWgD +aMHaYVgVtaSctatcgKaatatattaDgacccYagtgtaYNaaatKcagtBRgagtcca +tgKgaaaccBgaagBtgSttWtacgatWHaYatcgatttRaaNRgcaNaKVacaNtDgat +tgHVaatcDaagcgtatgcNttaDataatcSataaKcaataaHWataBtttatBtcaKtK +tatagttaDgSaYctacaRatNtaWctSaatatttYaKaKtaccWtatcRagacttaYtt +VcKgSDcgagaagatccHtaattctSttatggtKYgtMaHagVaBRatttctgtRgtcta +tgggtaHKgtHacHtSYacgtacacHatacKaaBaVaccaDtatcSaataaHaagagaat +ScagactataaRttagcaaVcaHataKgDacatWccccaagcaBgagWatctaYttgaaa +tctVNcYtttWagHcgcgcDcVaaatgttKcHtNtcaatagtgtNRaactttttcaatgg +WgBcgDtgVgtttctacMtaaataaaRggaaacWaHttaRtNtgctaaRRtVBctYtVta +tDcattDtgaccYatagatYRKatNYKttNgcctagtaWtgaactaMVaacctgaStttc +tgaKVtaaVaRKDttVtVctaDNtataaaDtccccaagtWtcgatcactDgYaBcatcct +MtVtacDaaBtYtMaKNatNtcaNacgDatYcatcgcaRatWBgaacWttKttagYtaat +tcggttgSWttttDWctttacYtatatWtcatDtMgtBttgRtVDggttaacYtacgtac +atgaattgaaWcttMStaDgtatattgaDtcRBcattSgaaVBRgagccaaKtttcDgcg +aSMtatgWattaKttWtgDBMaggBBttBaatWttRtgcNtHcgttttHtKtcWtagHSt +aacagttgatatBtaWSaWggtaataaMttaKacDaatactcBttcaatatHttcBaaSa +aatYggtaRtatNtHcaatcaHtagVtgtattataNggaMtcttHtNagctaaaggtaga +YctMattNaMVNtcKtactBKcaHHcBttaSagaKacataYgctaKaYgttYcgacWVtt +WtSagcaacatcccHaccKtcttaacgaKttcacKtNtacHtatatRtaaatacactaBt +ttgaHaRttggttWtatYagcatYDatcggagagcWBataagRtacctataRKgtBgatg +aDatataSttagBaHtaatNtaDWcWtgtaattacagKttcNtMagtattaNgtctcgtc +ctcttBaHaKcKccgtRcaaYagSattaagtKataDatatatagtcDtaacaWHcaKttD +gaaRcgtgYttgtcatatNtatttttatggccHtgDtYHtWgttatYaacaattcaWtat +NgctcaaaSttRgctaatcaaatNatcgtttaBtNNVtgttataagcaaagattBacgtD +atttNatttaaaDcBgtaSKgacgtagataatttcHMVNttgttBtDtgtaWKaaRMcKM +tHtaVtagataWctccNNaSWtVaHatctcMgggDgtNHtDaDttatatVWttgttattt +aacctttcacaaggaSaDcggttttttatatVtctgVtaacaStDVaKactaMtttaSNa +gtgaaattaNacttSKctattcctctaSagKcaVttaagNaVcttaVaaRNaHaaHttat +gtHttgtgatMccaggtaDcgaccgtWgtWMtttaHcRtattgScctatttKtaaccaag +tYagaHgtWcHaatgccKNRtttagtMYSgaDatctgtgaWDtccMNcgHgcaaacNDaa +aRaStDWtcaaaaHKtaNBctagBtgtattaactaattttVctagaatggcWSatMaccc +ttHttaSgSgtgMRcatRVKtatctgaaaccDNatYgaaVHNgatMgHRtacttaaaRta +tStRtDtatDttYatattHggaBcttHgcgattgaKcKtttcRataMtcgaVttWacatN +catacctRataDDatVaWNcggttgaHtgtMacVtttaBHtgagVttMaataattatgtt +cttagtttgtgcDtSatttgBtcaacHattaaBagVWcgcaSYttMgcttacYKtVtatc +aYaKctgBatgcgggcYcaaaaacgNtctagKBtattatctttKtaVttatagtaYtRag +NtaYataaVtgaatatcHgcaaRataHtacacatgtaNtgtcgYatWMatttgaactacR +ctaWtWtatacaatctBatatgYtaagtatgtgtatSttactVatcttYtaBcKgRaSgg +RaaaaatgcagtaaaWgtaRgcgataatcBaataccgtatttttccatcNHtatWYgatH +SaaaDHttgctgtccHtggggcctaataatttttctatattYWtcattBtgBRcVttaVM +RSgctaatMagtYtttaaaaatBRtcBttcaaVtaacagctccSaaSttKNtHtKYcagc +agaaaccccRtttttaaDcDtaStatccaagcgctHtatcttaDRYgatDHtWcaaaBcW +gKWHttHataagHacgMNKttMKHccaYcatMVaacgttaKgYcaVaaBtacgcaacttt +MctaaHaatgtBatgagaSatgtatgSRgHgWaVWgataaatatttccKagVgataattW +aHNcYggaaatgctHtKtaDtctaaagtMaatVDVactWtSaaWaaMtaHtaSKtcBRaN +cttStggtBttacNagcatagRgtKtgcgaacaacBcgKaatgataagatgaaaattgta +ctgcgggtccHHWHaaNacaBttNKtKtcaaBatatgctaHNgtKcDWgtttatNgVDHg +accaacWctKaaggHttgaRgYaatHcaBacaatgagcaaattactgtaVaaYaDtagat +tgagNKggtggtgKtWKaatacagDRtatRaMRtgattDggtcaaYRtatttNtagaDtc +acaaSDctDtataatcgtactaHttatacaatYaacaaHttHatHtgcgatRRttNgcat +SVtacWWgaaggagtatVMaVaaattScDDKNcaYBYaDatHgtctatBagcaacaagaa +tgagaaRcataaKNaRtBDatcaaacgcattttttaaBtcSgtacaRggatgtMNaattg +gatatWtgagtattaaaVctgcaYMtatgatttttYgaHtgtcttaagWBttHttgtctt +attDtcgtatWtataataSgctaHagcDVcNtaatcaagtaBDaWaDgtttagYctaNcc +DtaKtaHcttaataacccaRKtacaVaatNgcWRaMgaattatgaBaaagattVYaHMDc +aDHtcRcgYtcttaaaWaaaVKgatacRtttRRKYgaatacaWVacVcRtatMacaBtac +tggMataaattttHggNagSctacHgtBagcgtcgtgattNtttgatSaaggMttctttc +ttNtYNagBtaaacaaatttMgaccttacataattgYtcgacBtVMctgStgMDtagtaR +ctHtatgttcatatVRNWataDKatWcgaaaaagttaaaagcacgHNacgtaatctttMR +tgacttttDacctataaacgaaatatgattagaactccSYtaBctttaataacWgaaaYa +tagatgWttcatKtNgatttttcaagHtaYgaaRaDaagtaggagcttatVtagtctttc +attaaaatcgKtattaRttacagVaDatgcatVgattgggtctttHVtagKaaRBtaHta +aggccccaaaaKatggtttaMWgtBtaaacttcactttKHtcgatctccctaYaBacMgt +cttBaBaNgcgaaacaatctagtHccHtKttcRtRVttccVctttcatacYagMVtMcag +aMaaacaataBctgYtaatRaaagattaaccatVRatHtaRagcgcaBcgDttStttttc +VtttaDtKgcaaWaaaaatSccMcVatgtKgtaKgcgatatgtagtSaaaDttatacaaa +catYaRRcVRHctKtcgacKttaaVctaDaatgttMggRcWaacttttHaDaKaDaBctg +taggcgtttaHBccatccattcNHtDaYtaataMttacggctNVaacDattgatatttta +cVttSaattacaaRtataNDgacVtgaacataVRttttaDtcaaacataYDBtttaatBa +DtttYDaDaMccMttNBttatatgagaaMgaNtattHccNataattcaHagtgaaggDga +tgtatatatgYatgaStcataaBStWacgtcccataRMaaDattggttaaattcMKtctM +acaBSactcggaatDDgatDgcWctaacaccgggaVcacWKVacggtaNatatacctMta +tgatagtgcaKagggVaDtgtaacttggagtcKatatcgMcttRaMagcattaBRaStct +YSggaHYtacaactMBaagDcaBDRaaacMYacaHaattagcattaaaHgcgctaaggSc +cKtgaaKtNaBtatDDcKBSaVtgatVYaagVtctSgMctacgttaacWaaattctSgtD +actaaStaaattgcagBBRVctaatatacctNttMcRggctttMttagacRaHcaBaacV +KgaataHttttMgYgattcYaNRgttMgcVaaacaVVcDHaatttgKtMYgtatBtVVct +WgVtatHtacaaHttcacgatagcagtaaNattBatatatttcVgaDagcggttMaagtc +ScHagaaatgcYNggcgtttttMtStggtRatctacttaaatVVtBacttHNttttaRca +aatcacagHgagagtMgatcSWaNRacagDtatactaaDKaSRtgattctccatSaaRtt +aaYctacacNtaRtaactggatgaccYtacactttaattaattgattYgttcagDtNKtt +agDttaaaaaaaBtttaaNaYWKMBaaaacVcBMtatWtgBatatgaacVtattMtYatM +NYDKNcKgDttDaVtaaaatgggatttctgtaaatWtctcWgtVVagtcgRgacttcccc +taDcacagcRcagagtgtWSatgtacatgttaaSttgtaaHcgatgggMagtgaacttat +RtttaVcaccaWaMgtactaatSSaHtcMgaaYtatcgaaggYgggcgtgaNDtgttMNg +aNDMtaattcgVttttaacatgVatgtWVMatatcaKgaaattcaBcctccWcttgaaWH +tWgHtcgNWgaRgctcBgSgaattgcaaHtgattgtgNagtDttHHgBttaaWcaaWagc +aSaHHtaaaVctRaaMagtaDaatHtDMtcVaWMtagSagcttHSattaacaaagtRacM +tRtctgttagcMtcaBatVKtKtKacgagaSNatSactgtatatcBctgagVtYactgta +aattaaaggcYgDHgtaacatSRDatMMccHatKgttaacgactKtgKagtcttcaaHRV +tccttKgtSataatttacaactggatDNgaacttcaRtVaagDcaWatcBctctHYatHa +DaaatttagYatSatccaWtttagaaatVaacBatHcatcgtacaatatcgcNYRcaata +YaRaYtgattVttgaatgaVaactcRcaNStgtgtattMtgaggtNttBaDRcgaaaagc +tNgBcWaWgtSaDcVtgVaatMKBtttcgtttctaaHctaaagYactgMtatBDtcStga +ccgtSDattYaataHctgggaYYttcggttaWaatctggtRagWMaDagtaacBccacta +cgHWMKaatgatWatcctgHcaBaSctVtcMtgtDttacctaVgatYcWaDRaaaaRtag +atcgaMagtggaRaWctctgMgcWttaagKBRtaaDaaWtctgtaagYMttactaHtaat +cttcataacggcacBtSgcgttNHtgtHccatgttttaaagtatcgaKtMttVcataYBB +aKtaMVaVgtattNDSataHcagtWMtaggtaSaaKgttgBtVtttgttatcatKcgHac +acRtctHatNVagSBgatgHtgaRaSgttRcctaacaaattDNttgacctaaYtBgaaaa +tagttattactcttttgatgtNNtVtgtatMgtcttRttcatttgatgacacttcHSaaa +ccaWWDtWagtaRDDVNacVaRatgttBccttaatHtgtaaacStcVNtcacaSRttcYa +gacagaMMttttgMcNttBcgWBtactgVtaRttctccaaYHBtaaagaBattaYacgat +ttacatctgtaaMKaRYtttttactaaVatWgctBtttDVttctggcDaHaggDaagtcg +aWcaagtagtWttHtgKtVataStccaMcWcaagataagatcactctHatgtcYgaKcat +cagatactaagNSStHcctRRNtattgtccttagttagMVgtatagactaactctVcaat +MctgtttgtgttgccttatWgtaBVtttctggMcaaKgDWtcgtaaYStgSactatttHg +atctgKagtagBtVacRaagRtMctatgggcaaaKaaaatacttcHctaRtgtDcttDat +taggaaatttcYHaRaaBttaatggcacKtgctHVcaDcaaaVDaaaVcgMttgtNagcg +taDWgtcgttaatDgKgagcSatatcSHtagtagttggtgtHaWtaHKtatagctgtVga +ttaBVaatgaataagtaatVatSttaHctttKtttgtagttaccttaatcgtagtcctgB +cgactatttVcMacHaaaggaatgDatggKtaHtgStatattaaSagctWcctccRtata +BaDYcgttgcNaagaggatRaaaYtaWgNtSMcaatttactaacatttaaWttHtatBat +tgtcgacaatNgattgcNgtMaaaKaBDattHacttggtRtttaYaacgVactBtaBaKt +gBttatgVttgtVttcaatcWcNctDBaaBgaDHacBttattNtgtDtatttVSaaacag +gatgcRatSgtaSaNtgBatagttcHBgcBBaaattaHgtDattatDaKaatBaaYaaMa +ataaataKtttYtagtBgMatNcatgtttgaNagtgttgtgKaNaSagtttgaSMaYBca +aaacDStagttVacaaaaactaaWttBaagtctgtgcgtMgtaattctcctacctcaNtt +taaccaaaaVtBcacataacaccccBcWMtatVtggaatgaWtcaaWaaaaaaaaWtDta +atatRcctDWtcctaccMtVVatKttaWaaKaaatataaagScHBagaggBaSMtaWaVt +atattactSaaaKNaactatNatccttgaYctattcaaaVgatttYHcRagattttaSat +aggttattcVtaaagaKgtattattKtRttNcggcRgtgtgtWYtaacHgKatKgatYta +cYagDtWcHBDctctgRaYKaYagcactKcacSaRtBttttBHKcMtNtcBatttatttt +tgSatVgaaagaWtcDtagDatatgMacaacRgatatatgtttgtKtNRaatatNatgYc +aHtgHataacKtgagtagtaacYttaNccaaatHcacaacaVDtagtaYtccagcattNt +acKtBtactaaagaBatVtKaaHBctgStgtBgtatgaSNtgDataaccctgtagcaBgt +gatcttaDataStgaMaccaSBBgWagtacKcgattgaDgNNaaaacacagtSatBacKD +gcgtataBKcatacactaSaatYtYcDaactHttcatRtttaatcaattataRtttgtaa +gMcgNttcatcBtYBagtNWNMtSHcattcRctttttRWgaKacKttgggagBcgttcgc +MaWHtaatactgtctctatttataVgtttaBScttttaBMaNaatMacactYtBMggtHa +cMagtaRtctgcatttaHtcaaaatttgagKtgNtactBacaHtcgtatttctMaSRagc +agttaatgtNtaaattgagagWcKtaNttagVtacgatttgaatttcgRtgtWcVatcgt +taaDVctgtttBWgaccagaaagtcSgtVtatagaBccttttcctaaattgHtatcggRa +ttttcaaggcYSKaagWaWtRactaaaacccBatMtttBaatYtaagaactSttcgaaSc +aatagtattgaccaagtgttttctaacatgtttNVaatcaaagagaaaNattaaRtttta +VaaaccgcaggNMtatattVctcaagaggaacgBgtttaacaagttcKcYaatatactaa +ccBaaaSggttcNtattctagttRtBacgScVctcaatttaatYtaaaaaaatgSaatga +tagaMBRatgRcMcgttgaWHtcaVYgaatYtaatctttYttatRaWtctgBtDcgatNa +tcKaBaDgatgtaNatWKctccgatattaacattNaaacDatgBgttctgtDtaaaMggt +gaBaSHataacgccSctaBtttaRBtcNHcDatcDcctagagtcRtaBgWttDRVHagat +tYatgtatcWtaHtttYcattWtaaagtctNgtStggRNcgcggagSSaaagaaaatYcH +DtcgctttaatgYcKBVSgtattRaYBaDaaatBgtatgaHtaaRaRgcaSWNtagatHa +acttNctBtcaccatctMcatattccaSatttgcgaDagDgtatYtaaaVDtaagtttWV +aagtagYatRttaagDcNgacKBcScagHtattatcDaDactaaaaaYgHttBcgaDttg +gataaaKSRcBMaBcgaBSttcWtgNBatRaccgattcatttataacggHVtaattcaca +agagVttaaRaatVVRKcgWtVgacctgDgYaaHaWtctttcacMagggatVgactagMa +aataKaaNWagKatagNaaWtaaaatttgaattttatttgctaaVgaHatBatcaaBWcB +gttcMatcgBaaNgttcgSNaggSaRtttgHtRtattaNttcDcatSaVttttcgaaaaa +ttgHatctaRaggSaNatMDaaatDcacgattttagaHgHaWtYgattaatHNSttatMS +gggNtcKtYatRggtttgtMWVtttaYtagcagBagHaYagttatatggtBacYcattaR +SataBatMtttaaatctHcaaaSaaaagttNSaaWcWRccRtKaagtBWtcaaattSttM +tattggaaaccttaacgttBtWatttatatWcDaatagattcctScacctaagggRaaYt +aNaatgVtBcttaaBaacaMVaaattatStYgRcctgtactatcMcVKatttcgSgatRH +MaaaHtagtaaHtVgcaaataatatcgKKtgccaatBNgaaWcVttgagttaKatagttc +aggKDatDtattgaKaVcaKtaataDataataHSaHcattagttaatRVYcNaHtaRcaa +ggtNHcgtcaaccaBaaagYtHWaaaRcKgaYaaDttgcWYtataRgaatatgtYtgcKt +aNttWacatYHctRaDtYtattcBttttatcSataYaYgttWaRagcacHMgtttHtYtt +YaatcggtatStttcgtRSattaaDaKMaatatactaNBaWgctacacYtgaYVgtgHta +aaRaaRgHtagtWattataaaSDaaWtgMattatcgaaaagtaYRSaWtSgNtBgagcRY +aMDtactaacttaWgtatctagacaagNtattHggataatYttYatcataDcgHgttBtt +ctttVttgccgaaWtaaaacgKgtatctaaaaaNtccDtaDatBMaMggaatNKtatBaa +atVtccRaHtaSacataHattgtttKVYattcataVaattWtcgtgMttcttKtgtctaa +cVtatctatatBRataactcgKatStatattcatHHRttKtccaacgtgggtgRgtgaMt +attattggctatcgtgacMtRcBDtcttgtactaatRHttttaagatcgVMDStattatY +BtttDttgtBtNttgRcMtYtgBacHaWaBaatDKctaagtgaaactaatgRaaKgatcc +aagNaaaatattaggWNtaagtatacttttKcgtcggSYtcttgRctataYcttatataa +agtatattaatttataVaacacaDHatctatttttKYVatHRactttaBHccaWagtact +BtcacgaVgcgttRtttttttSVgtSagtBaaattctgaHgactcttgMcattttagVta +agaattHctHtcaDaaNtaacRggWatagttcgtSttgaDatcNgNagctagDgatcNtt +KgttgtaDtctttRaaYStRatDtgMggactSttaDtagSaVtBDttgtDgccatcacaM +attaaaMtNacaVcgSWcVaaDatcaHaatgaattaMtatccVtctBtaattgtWattat +BRcWcaatgNNtactWYtDaKttaaatcactcagtRaaRgatggtKgcgccaaHgaggat +StattYcaNMtcaBttacttatgagDaNtaMgaaWtgtttcttctaHtMNgttatctaWW +atMtBtaaatagDVatgtBYtatcggcttaagacMRtaHScgatatYgRDtcattatSDa +HggaaataNgaWSRRaaaBaatagBattaDctttgHWNttacaataaaaaaatacggttt +gHgVtaHtWMttNtBtctagtMcgKMgHgYtataHaNagWtcaacYattaataYRgtaWK +gaBctataaccgatttaHaNBRaRaMtccggtNgacMtctcatttgcaattcWgMactta +caaDaaNtactWatVtttagccttMaatcagVaagtctVaaDaBtattaattaYtNaYtg +gattaKtaKctYaMtattYgatattataatKtVgDcttatatNBtcgttgtStttttMag +aggttaHYSttcKgtcKtDNtataagttataagSgttatDtRttattgttttSNggRtca +aKMNatgaatattgtBWtaMacctgggYgaSgaagYataagattacgagaatBtggtRcV +HtgYggaDgaYaKagWagctatagacgaaHgtWaNgacttHRatVaWacKYtgRVNgVcS +gRWctacatcKSactctgWYtBggtataagcttNRttVtgRcaWaaatDMatYattaact +ttcgaagRatSctgccttgcRKaccHtttSNVagtagHagBagttagaccaRtataBcca +taatSHatRtcHagacBWatagcaMtacaRtgtgaaBatctKRtScttccaNaatcNgta +atatWtcaMgactctBtWtaaNactHaaaaRctcgcatggctMcaaNtcagaaaaacaca +gtggggWttRttagtaagaVctVMtcgaatcttcMaaaHcaHBttcgattatgtcaDagc +YRtBtYcgacMgtDcagcgaNgttaataatagcagKYYtcgtaBtYctMaRtaRtDagaa +aacacatgYaBttgattattcgaaNttBctSataaMataWRgaHtttccgtDgaYtatgg +tDgHKgMtatttVtMtVagttaRatMattRagataaccctKctMtSttgaHagtcStcta +tttccSagatgttccacgaggYNttHRacgattcDatatDcataaaatBBttatcgaHtN +HaaatatDNaggctgaNcaaggagttBttMgRagVatBcRtaWgatgBtSgaKtcgHttt +gaatcaaDaHttcSBgHcagtVaaSttDcagccgttNBtgttHagYtattctttRWaaVt +SttcatatKaaRaaaNacaVtVctMtSDtDtRHRcgtaatgctcttaaatSacacaatcg +HattcaWcttaaaatHaaatcNctWttaNMcMtaKctVtcctaagYgatgatcYaaaRac +tctaRDaYagtaacgtDgaggaaatctcaaacatcaScttcKttNtaccatNtaNataca +tttHaaDHgcaDatMWaaBttcRggctMaagctVYcacgatcaDttatYtaatcKatWat +caatVYtNagatttgattgaYttttYgacttVtcKaRagaaaHVgDtaMatKYagagttN +atWttaccNtYtcDWgSatgaRgtMatgKtcgacaagWtacttaagtcgKtgatccttNc +ttatagMatHVggtagcgHctatagccctYttggtaattKNaacgaaYatatVctaataM +aaaYtgVtcKaYtaataacagaatHcacVagatYWHttagaaSMaatWtYtgtaaagNaa +acaVgaWtcacNWgataNttcaSagctMDaRttgNactaccgataMaaatgtttattDtc +aagacgctDHYYatggttcaagccNctccttcMctttagacBtaaWtaWVHggaaaaNat +ttaDtDtgctaaHHtMtatNtMtagtcatttgcaaaRatacagRHtatDNtgtDgaatVg +tVNtcaaatYBMaaaagcaKgtgatgatMgWWMaHttttMgMagatDtataaattaacca +actMtacataaattgRataatacgBtKtaataattRgtatDagDtcRDacctatRcagag +cSHatNtcaScNtttggacNtaaggaccgtgKNttgttNcttgaaRgYgRtNtcagttBc +ttttcHtKtgcttYaaNgYagtaaatgaatggWaMattBHtatctatSgtcYtgcHtaat +tHgaaMtHcagaaSatggtatgccaHBtYtcNattWtgtNgctttaggtttgtWatNtgH +tgcDttactttttttgcNtactKtWRaVcttcatagtgSNKaNccgaataaBttataata +YtSagctttaaatSttggctaaKSaatRccgWHgagDttaaatcatgagMtcgagtVtaD +ggaBtatttgDacataaacgtagYRagBWtgDStKDgatgaagttcattatttaKWcata +aatWRgatataRgttRacaaNKttNtKagaaYaStaactScattattaacgatttaaatg +DtaattagatHgaYataaactatggggatVHtgccgtNgatNYcaStRtagaccacWcaM +tatRagHgVactYtWHtcttcatgatWgagaKggagtatgaWtDtVtNaNtcgYYgtaaa +ctttaDtBactagtaDctatagtaatatttatatataacgHaaaRagKattSagttYtSt +>THREE Homo sapiens frequency +agagagacgatgaaaattaatcgtcaatacgctggcgaacactgagggggacccaatgct +cttctcggtctaaaaaggaatgtgtcagaaattggtcagttcaaaagtagaccggatctt +tgcggagaacaattcacggaacgtagcgttgggaaatatcctttctaccacacatcggat +tttcgccctctcccattatttattgtgttctcacatagaattattgtttagacatccctc +gttgtatggagagttgcccgagcgtaaaggcataatccatataccgccgggtgagtgacc +tgaaattgtttttagttgggatttcgctatggattagcttacacgaagagattctaatgg +tactataggataattataatgctgcgtggcgcagtacaccgttacaaacgtcgttcgcat +atgtggctaacacggtgaaaatacctacatcgtatttgcaatttcggtcgtttcatagag +cgcattgaattactcaaaaattatatatgttgattatttgattagactgcgtggaaagaa +ggggtactcaagccatttgtaaaagctgcatctcgcttaagtttgagagcttacattagt +ctatttcagtcttctaggaaatgtctgtgtgagtggttgtcgtccataggtcactggcat +atgcgattcatgacatgctaaactaagaaagtagattactattaccggcatgcctaatgc +gattgcactgctatgaaggtgcggacgtcgcgcccatgtagccctgataataccaatact +tacatttggtcagcaattctgacattatacctagcacccataaatttactcagacttgag +gacaggctcttggagtcgatcttctgtttgtatgcatgtgatcatatagatgaataagcg +atgcgactagttagggcatagtatagatctgtgtatacagttcagctgaacgtccgcgag +tggaagtacagctgagatctatcctaaaatgcaaccatatcgttcacacatgatatgaac +ccagggggaaacattgagttcagttaaattggcagcgaatcccccaagaagaaggcggag +tgacgttgaacgggcttatggtttttcagtacttcctccgtataagttgagcgaaatgta +aacagaataatcgttgtgttaacaacattaaaatcgcggaatatgatgagaatacacagt +gtgagcatttcacttgtaaaatatctttggtagaacttactttgctttaaatatgttaaa +ccgatctaataatctacaaaacggtagattttgcctagcacattgcgtccttctctattc +agatagaggcaatactcagaaggttttatccaaagcactgtgttgactaacctaagtttt +agtctaataatcatgattgattataggtgccgtggactacatgactcgtccacaaataat +acttagcagatcagcaattggccaagcacccgacttttatttaatggttgtgcaatagtc +cagattcgtattcgggactctttcaaataatagtttcctggcatctaagtaagaaaagct +cataaggaagcgatattatgacacgctcttccgccgctgttttgaaacttgagtattgct +cgtccgaaattgagggtcacttcaaaatttactgagaagacgaagatcgactaaagttaa +aatgctagtccacagttggtcaagttgaattcatccacgagttatatagctattttaatt +tatagtcgagtgtacaaaaaacatccacaataagatttatcttagaataacaacccccgt +atcatcgaaatcctccgttatggcctgactcctcgagcttatagcatttgtgctggcgct +cttgccaggaacttgctcgcgaggtggtgacgagtgagatgatcagtttcattatgatga +tacgattttatcgcgactagttaatcatcatagcaagtaaaatttgaattatgtcattat +catgctccattaacaggttatttaattgatactgacgaaattttttcacaatgggttttc +tagaatttaatatcagtaattgaagccttcataggggtcctactagtatcctacacgacg +caggtccgcagtatcctggagggacgtgttactgattaaaagggtcaaaggaatgaaggc +tcacaatgttacctgcttcaccatagtgagccgatgagttttacattagtactaaatccc +aaatcatactttacgatgaggcttgctagcgctaaagagaatacatacaccaccacatag +aattgttagcgatgatatcaaatagactcctggaagtgtcagggggaaactgttcaatat +ttcgtccacaggactgaccaggcatggaaaagactgacgttggaaactataccatctcac +gcccgacgcttcactaattgatgatccaaaaaatatagcccggattcctgattagcaaag +ggttcacagagaaagatattatcgacgtatatcccaaaaaacagacgtaatgtgcatctt +cgaatcgggatgaatacttgtatcataaaaatgtgacctctagtatacaggttaatgtta +gtgatacacaatactcgtgggccatgggttctcaaataaaatgtaatattgcgtcgatca +ctcacccacgtatttggtctaattatgttttatttagtgacaatccaatagataaccggt +cctattaagggctatatttttagcgaccacgcgtttaaacaaaggattgtatgtagatgg +taccagtttaattgccagtgggcaatcctaagcaaaatgagattctatcctaaagtttgg +gcttgatataagatttcggatgtatgggttttataatcgttggagagctcaatcatgagc +taatacatggatttcgctacctcaccgagagaccttgcatgaagaattctaaccaaaagt +ttaataggccggattggattgagttaattaagaccttgttcagtcatagtaaaaaccctt +aaattttaccgattgacaaagtgagcagtcgcaataccctatgcgaaacgcctcgatagt +gactaggtatacaaggtttttgagttcctttgaaatagttaactaatttaaaattaatta +acgacatggaaatcacagaacctaatgctttgtaggagttatttatgctgtttactgcct +ctacaaccctaataaagcagtcctaagaatgaaacgcatcttttagttcagaaagtggta +tccagggtggtcaatttaataaattcaacatcgggtctcaggatattcggtcatataatt +tattaagggctcttcgagtcttactctgagtgaaattggaaacagtcatccttttcgttg +tgaggcatcttacaccgctatcgatatacaatgcattccaccgcggtgtcccgtacacaa +ggaaacttgttaccttggggatataagaaaactcacacgtctcattattaaactgagtac +aatttttgcacgagaaagtaatgcaatacaatatgatgaaagccagctaatgaaaaggga +tggaacgcacctcggatctgttgcactggattaaaatccgattatttttaaaaatattca +gtgctagagcatatcaggtctacttttttatctggtatgtaaagcccacggagcgatagt +gagatccttacgactcaacgaaaagttataacataactcccgttagccaaagcccaatcc +cgattactgccctaccctaacgtctgccatctaaatatcgaacttgttatgatcaatgtg +actacctcccaccctttccccttcatttgttccactggggataagctagcgttttcagaa +tcaatgcaataagaatagccaattgtctcacttcatcagagctcttggcaattccaggcg +ctacgtggttctggaatatattcatttttcaaatagtaatacgtttagtgttgctattgt +ctacacgtttggatattacgttatgtgagcggacatcaatagttgtctaactctttagta +agccagagatagcactcttagcgaatggataccatcttccataagtttagttaatagtcc +gaaacaactgcttcgagcatatttgaacctccttgtaggcaaatagcctcttcaaagcaa +tcttactaatagatagagtttgttttaagggactactagaaatgggacaatcttaatagt +atgacctaaactgacatttaaagatatatccaggtggcaagcataaagatcattgcgcca +cctccaccgtgggattacttatcagtcgatatcctatatgctaagtttgcgacggcagaa +tacaaactaagctgagttgatgctaaccttacctatgataccccattggaccggttaaca +gccctacttattccaaataaaagaacttttatgctgtagaagctattatagtgatgcctg +gtaacttcagtatattaaaatgacacacatacgccatatagagctcctggaactttgaat +aatgagcgaacttcgaagttgaagagcaagaaaccatatgtcacggttgcctaaagcccg +gtaaccagacatgtgctatcattgatcattatcgaggttttcataaccttgacccattat +cggctgtgcgcggacaagtacttaaatcactagtttcttcacctgcttatcggtaagaaa +taaggttggcaaagaatcgcataagacggacgtagagccgcagcgttgtgcgagtccagg +tgcatgcgcagcaataggattttaaattttgttccatttttaatttagccgtaaggatgt +ccgtaaatgattgaaaattggattcaatctttgggcctatgctactggaacctgatcgac +aaaatttcaaacatacgttaactccgaaagaccgtatttttgcggctagaatagtcagtc +gcttggagccatataccttaccacttaaacgacgtgctcctgtagttgaaatataaacag +aacacaaagactaccgatcatatcaactgaagatctttgtaactttgaggcgaagcaccc +tcttcgagacaactaagagtaaagtaccgggcgccgcaaggagtcgattgggaccctaaa +tcttgacgaattgctaagaggctcagagctaccactgtaatttctctagagcccataata +aatgaacgatacatccgtaggtagcacctaagggattataatggaagccaaatgcagtta +ataatattatatactggcgtacacgattcgacggatctctcacatagtgattcacgaccc +ccccctttgattgacacagcgtcagcattttgcaagaacgatcttctgcatagggtgcgc +caccgtaaggatgacgtcgaagctacaactgggtataatttaccatgcttccctgatgct +gagtgcaatacactaagaatgagtttttaccccatatcaccagtatttgttctgttattg +cgaagaaatggctatgctgagttggcgactaaagtcacccatcctttttattaggtaacc +ccctcccttaaactaactgatttgctggagctgccctgcatacatatactttatcattta +tggacgtccgtgacgcttattatccaccatagtcgatatgctacacggattcattaatgg +atcgtaggagtttaagttatatttactaagatcggtctcggctactatcccgccttaccc +ggcgctatttacggccatttttaatatattgacggtaattattcctatggtttcgaccgc +acgtccttggacaagaaagaatggcaaaaaaaatgtaaaagaaaaaaaatattgagtccc +taccatcatataaaaaatatgtgatgagtaacttgacgaaatgttagtggttattaaaga +ctatctattacaccttttgttttctgtcgtagtatattaaagtctagaagccttacagga +aaatcagggttatacagccgatactccgcagcatgaatcatcgaggaggtgtcctaccat +cgcgccttgtaatcttgtctgtgtatactgtatttagaccttttatacaaagtaaatatc +tcggctttatgtgattgggaggggcctactcaaacatgatgacttgacctaataatcact +gtgcgggcgtcttatgactagctattccttgaaatccaccaccaaatggttaatatgtaa +aaactttgacgatgaaacaaggtgaatgtgtagttactttgtgtaattagctgcgtcgag +cattgcttgtaaaaccgtcaatcgcacacgttacttccataaaatttctacgaatacacc +cttcttaaaaaaaacgtaggaattcacgagtttaacaaacgataactgtataaagtggaa +gtccgaagaaagcagatgcccgaactactcgaagatgtttcgttttcttaaccatagggg +cttcttaatggcccactacgcacattttgttcaagcccgagagggacatccccattacgg +gagtattactaaaactgttccgtaatacgttcagcaagggatgaaaaaggccactgctca +agttattgacgtgggagtattacatcggaagcctgaatcccacactatgatggtctgtac +aggcctagggactgcgtctagacggtattaccggcttctaatcatacgatcgtgagtctt +aacgggaagtaaggctcacacctaccccaaaccatttatctatgtaagtataaaattgtg +cgtaagtgttcaaagtggacaataaagacgtggcaaaaacccccgcacataagccgcttt +agatttcacaaataccaatgcggttaaaaacatccttgagtcgtacatacaccatactcg +cgttaaacggatataacagaagataataaatccggatgtggagtcggtgtaactatagaa +agccaagtgaaataatgcttaccagtcatttagctatacggctttcatttcatgtcaaga +gggtggagtttgacctgtacagttgatatatcaccgatacttagaactcacctaaagcta +aaattgctcgcagcgtgtaatccgcatattacaaacaatagatgggattcattatacata +agacacgatgatctgctttttcaggttgcgagatgttgcctatcgtcaatcgagtcctgc +cttacaccacttaaacaaaagtattgacagggaacctattttcgaggtattatatagtcc +agcttgaatatcaatttgacagttaacctagtgaaaatcagtaagaggaaatacgccaca +ttctccagtgaaattctacgggttatcgtctagtccaactatcaattataactcacgaga +tataagtaaattctcgtacttggcctgatttttattatactttggatccttagtaaacag +gaagggagaaaccttcaacgaaaaacactggattttgttttactctcaaagctcttatat +gacggaaataccctgtcaagtcttaactttattactagactaatgaaatgggcttggggt +ggccagaatcatagtacaatttagcggatacactattcggactttcctatcggctgtctg +gttggataagtatggggactaataggctagacatacctatacttaaactatacaggcgtc +atctatctctgcaactttggagttccctgatgttctcccgccctttgggttcacatcttc +tataccgacacccctaataacgattagtttgtgggttagagtaaattaatacggttaata +ttaatgtatcgttgaaaagctggtgtcgccaataaggtaaccggctaggcagagtatatg +tcacgaagtataactaccctaatgataagctgtaggaataaaattaatgctgtctctaag +cgaagagatatttccgactctgttttaatgacgaatctcattacttctgacttgcaaatg +ttcaatatggcacggtttcacggcacctttgtgacgcatataatgaacttagaagattat +aacgacggaactttatatgataatccgttacgattaaagaatctgttaaatatcataatg +gcattcagttctagaccgtgcatcatggtaaacttactttctctgcatggcgacatacat +ttcgctattcaaattcgcgtgtggttacacccactcgcacctttggaatattaagagaag +atgatcagaaaatccattcgctcaatttttctgacgtacgtctaatttatcctaggagac +aaatcgttttatgtctctcacatttttgaagaaaggttcgagagacaatactcaggtcct +gaactgctagaagatactcggtggagcgtggcaacaatgaaaaactcgtgacataaatga +atgatacttttccaagttcagttaagtgaatatgtttaacatacccggcttttcgatctt +aagctgacgctggacgtgcgagtaatgtcagtctcttacatacactagtgactccaagtt +tcgtcaaaaacgccccctcccttctcgagcccactcacgctatgtattgacgcgaacttg +ttcgggatcagacttttcaggagttcggtcgcgtgtccctatgtgctaatatataagtta +gatcgcattagatgctaatctgaatacttatagacgaccttcaacgagaacgggtaccac +cttgaggctagagttaggtgtgaaacgacaggtagggacatataaaatttgagtgcggct +ttagttaagggtttaattacctactcaaacatcacgctcgcgcccttcgtacgtaatcga +ccatctagaggctaaggggactgtactaggtagtgattaatgatatcctagacgcacgtg +ccttagatcttcagactctgatggtccgcgatcaccgtaattgtagtcctccaactcgat +cactttgttggcgtcaaagaaattacgatatctaaatacttataatacaataaccaagga +tgagaatgactcatcgcgttggagttatattgcttgaagttctatggaatgaaagcacgt +tatctgccgtcccaatatctccagtgagctaattcattggacggtccactttgatcaatc +cccgaggagatgttcggacactttagtctgtaacacttagcgttgagaccacgaacaatt +gattactcagtcttgaaggtgttttccaaagttcattttaaataagactacgataggcct +ttcctattgatataaactacccggctctgttgttcgtgtgagtcgtacttctctgtgttt +ttctgattatagcaagattcgattcttagtgtaaacagcgatttttatttgacccgtcaa +tgagaagcgcataggatctaagcaaaattatcaagttgtgccacaaggtaagatctttcc +agttattgcaggtaggatgtatcccacgttgatagtatgaggtctgacgtcaactgtcta +ggagagttgaccgcgtgcgggtacaccggatttgcatcgatgttgagaacgcagaactcc +cactgtcgtggcggcgttcctgatatttagcaagaggcgttgataaagccctcatcatct +agatctcgacctcatctgccctcttgctccatcattttctacacagactactttcctatc +tacgttagtataattgctttctatcttagtatcatttagagcttctccgtcaacaggttc +gtgctattaaagttagtacgaaagggacaacttgtagcaacgcatttaatcggttttcga +ctacttcgcacaaaatcagataaagaagtttgtcattctattagacattgaattgcgcaa +ttgacttgtaccacttatgatcgaacactgaatcaagactgtgattaactaaaatagaca +agccactatatcaactaataaaaacgcccctggtggtcgaacatagttgactacaggata +attaattggactggagccattacattctctacaatcgtatcacttcccaagtagacaact +ttgaccttgtagtttcatgtacaaaaaaatgctttcgcaggagcacattggtagttcaat +agtttcatgggaacctcttgagccgtcttctgtgggtgtgttcggatagtaggtactgat +aaagtcgtgtcgctttcgatgagagggaattcaccggaaaacaccttggttaacaggata +gtctatgtaaacttcgagacatgtttaagagttaccagcttaatccacggtgctctacta +gtatcatcagctgtcttgcctcgcctagaaatatgcattctatcgttatcctatcaacgg +ttgccgtactgagcagccttattgtggaagagtaatatataaatgtagtcttgtctttac +gaagcagacgtaagtaataatgacttggaataccaaaactaaacatagtggattatcata +ctcaagaactctccagataaataacagtttttacgatacgtcaccaatgagcttaaagat +taggatcctcaaaactgatacaaacgctaattcatttgttattggatccagtatcagtta +aactgaatggagtgaagattgtagaatgttgttctggcctcgcatggggtctaggtgata +tacaatttctcatacttacacggtagtggaaatctgattctagcttcgtagctgactata +ctcaaggaaccactgctcaaggtaggagactagttccgaccctacagtcaaagtggccga +agcttaaactatagactagttgttaaatgctgatttcaagatatcatctatatacagttt +ggacaattatgtgtgcgaaactaaaattcatgctattcagatggatttcacttatgcctt +agaaacagatattgcccgagctcaatcaacagttttagccggaaacaatcgaagcatagg +gacaatgtatcttttcctaaattgccatgtgcagatttctgagtgtcacgaagcgcataa +tagaatcttgtgttgcctcaactcgttgaaaagtttaaaacaatcgcagcagtctttttg +gggtctactgtgtgtttgcaaaataactgaaagaaacgcttgaacaactctgaagtagct +cgagtactcattaaagtgtaacacattagtgaatatcggccaatgaaccaaacgcttccc +ggtacgctatctctctcatcgggaggcgatgtgcaggttatctacgaaagcatcccttta +cgttgagagtgtcgatgcatgaacctcattgtaacaatagcccagcaaattctcatacgt +gcctcagggtccgggcgtactcctccatggaagggcgcgcatctagtgttataccaactc +gctttttaactactatgctgtagttctacaggcatagtggccagtattttctaacttctc +tggatagatgctctcactcctcatccatcacggcttcagtttacgtcttacttgcttgtt +cagcaacggatggaggcattaagtatcttcactgttccctaaaattgctgttcaatatca +aagtaaggacgatacagggaaagctcaagcacactcattgaatactgccccagttgcaac +ctcacttaatctgacaaaaataatgactactctaagtgttgcggaagcagtctcttccac +gagcttgtctgtatcacttcgtataggcatgtaactcgatagacacgaacaccgagtgag +aaactatattcttgcttccgtgtgtgtgacaccaggtaattgatgcggatataagctgga +gatcactcacgcccacacaaggcgctgctacctctttattccaatgtgtaagaatttgct +aacttcatttctagaccgcagctttgcggtcataatttcacggtacggacccttgggtta +gagacttgataacacacttcgcagtttccaccgcgcacatgttttagtggcttctaacat +agaatttttgttgtgacataaagagtgcgtgggagacttgcccgaccgttaagccataat +caattgaaagccccgtgagtcacatctaattggttgtactgcgcatttagctatccttta +gctgactcgaagagattcgattcctaatataggttaattagatggctgccgcgcgaagta +aaacgtgaaaaacgtagtgcgcagatctgcataactcgcgcttaattacttatgagtagt +tccaagttcgctacgttatgagagagattggaattaagcaaatatgttttatggtgattt +tgggatgagaaggactgctaagtacggctactaaacaaatttctaaaaccgccatctacc +ttatcttggagacatttaagttgtatatgtcactagtctagcttttgtctgtgggacgcg +ttctcggaatgagggaaatgcaagagccgattcatcaaatgcttatctaagaaagtagtg +gactattacaccaagcacgaatgccagggaactgctttcttgctcaggacctcgcgacaa +ggtaccccgcataagtcctagaattacatttggtcagcaatgctgacatttgaccgtgaa +aacataattttaatcagaaggcagctcacccgcttgctctagatcttatctttgtatgaa +tgtcagaatttactgcaatatccgttccgaatagtgagggcttagtatagttctctgtat +acaggtcacatcaaactccccctgtcctagtacagctctgagctttaattaattgcatac +atttccttcaatcatcagatgaaaacaccgcgaatcatgctcttctcgtatagggcaaga +gaagcaacaaacaactagcccgactcacgttcatccgccgtatccttgttcagttcttac +tccgtattaggtcagcgaaatctaatcagaataatcggtcgcgtatcaaaattaaaatcc +cgcttgaggttgacaattaaaacgctgagcagttatcggctattagatagtggggtgaaa +gtaattggctggaattatgttaaaacgtgatattaagctaaaatacgctacttgttgccg +acctaattcagtcattcgatattcagttagagccaagaataacaagcttgtataaattga +acggggtgcactaaacgatgtgttactctaatattcagcttggagtatacctgaaggcga +attcatgtatcggccaataataagacgttgaagatcacaatttggactagcaaaagaagg +tgatttatgcgtggggattgagtccactgtacgagtacggtctctggaaaattataggtt +cagggaatataaggaagtaaagataattaccaagagatttttggtatcgctatgacccag +aggtgttctaacgtctgttttgatccgcagaatttctgcctcaatgcatatttgacggac +ttgaactagagcctctaaagttaaatggcgacgcaactgttcctaaacttcaattattac +tactctttttttcctagggtattgtagaggccagtggacaaaataaatcaaatttaagat +gtttcggacattaacatcccccgtagcatagaaatcatcagttatccaatctctcatcga +gcttttacaatttctgctggcgctatggacagcatatgccgcgagacctccgcaagactc +acttgatcactgtaagtatcttcattagaggttagagcctatagttaagctgctgaccta +gtaaaattggtattttctaattttattgctcaagttaaaggttagtgaagggataatgac +gttatttttgaacaatgggttgtattcaattttatatcacgaatggaacccttcattccc +ggcataatactagacgacacgaacaagctccgatctatcagccaggcacgtgttaaggtt +taattccggcaaaccaatgaagcatcaaaaggtgacctgatgcaacttagggtcacgatg +agtttttcaggactacttattacctattaataagttaacatgagccttcataccccgtaa +gacaatacatactccaccaattagaattctgagccatcttatctttttgtatcatcgaag +ggtatggccgaataggttaattagttactcctaacgtctctacaggcatgcatttgacgc +accttcgaaaatagtcaatctctcgccacacgcgtctagtatgcagcatcaaaaatatag +tccacggtttccggattaccaaacgcggcaaagagaaacattgtatcgacggagataact +taatacagaaggaaggggcatcttcgaatacggatgaataattctatctgtttattctga +catcttgttttcaggttaatcttacgcattcaaatgacgcctgccccatgcgtgcgcaat +tattttctaatattgacgagagcaatctcactccttttgggtctatttatgttttattga +ggcacaagcctatacagaacaggtactattaaggccgtgagtgtgagactcaaaccgtgg +aaacaaaggatgggttgttcttggtacaagttttagtgcatgtgggcaatccttaccaaa +atcagatgctatccttaactttgggctgcatttaagatggcggttggaggcctgtgagaa +tcctgcgtgtcatctttaatgaccgaattcatccatgtagattcagatcacacactcatt +ccttgatgttgtctaaacaaaagttgttgtggacgcattggagggagttaagtaacaact +tgggatcgcatacttataaaaattatatgttaaactttcacaaacgctgaagtccaaagt +aactagcccaaacgcctcgagagtcactaggtattaatggtgtttgagttcctgtgaaat +agtgttcgaaggtaaaatttatgtaccaaatcgaaagaacacttaataaggcttgcttgc +acggaggtatgatgtttactgactctacaaccctaattttccagtacgtacattcattcc +aataggttagttctcaaagtgctatacaggctcctcaattgatgatatgcttcagccgct +ctatggatattagctcattttatttaggaagcccgcttagaggcttactatgagggaaat +gccaaaatgtcatacttttcggtgtgtcccatatgacaccgctttacatagaatttgaat +taaaacgcgctctcccgttcactaccatacttggtaccgtgcgcatattacatatagata +taggatcattttttaaagctgtactaggtttgatcgacaatcttatgctatactatatga +tgtaaccctcataatcaataccgatcgtacgatcctagcataggtggcaagcgattttat +gccgattattgtgttaaatagtctgtgagtgtgattatcagggctacgttggtagagggg +ttgtatagacctcgcacacattgtgacatacttaacaatatacgaaaactgatataataa +atccccttacccaaacaccaatcccgttgaatcaactaccataacgtctcccatataaat +tgcctacttgtttgcataaatctgaatacataacaccattgcaccttcttgtgttccaat +cccgttaagattgccttgtcagatgatatgcaagaacaatagcatttgctagcaattatt +aacagctcttcgaattgcctccacataacgcgggagggtatattttaatttggcaaatac +taagtactgttggcgtcatatgctattaacggttggatattaagttatgtcagccgtaag +caagagtgggcgaaatattttgttacccagtgagagcactcttagagtttggatacaata +ggccatatgttgacttaagaggacgtaactacgccgtacaccattgttcaaccgacttct +tggcaaatagaatcgtattagcaatcttaagaatagagacacgttcgtgttagggtatac +tacaaatccgaaaatcttaagaggatcacctaaactgaaatttatacatatttcaacgtg +gatagatttaacataattcagccacctccaacctgggagtaattttcagtagatttacta +gatgattagtggcccaacgcacttgactatataagatctggggatcctaacctgacctat +gagacaaaattggaaacgttaacagcccttatgtgtacaaagaaaagtaagttgttgctg +ttcaacagatgatagtcatgacgcgtaacttcactatagtaaattgaaacaaatacgcaa +tttagacagaatggtacggtcatgaatgacagtaattcgaagtgctagaccaacttaaaa +taggtaaacgtgcccgaaaccccccttaacagaaagctgctatcatggtgcagtatcgac +gtgttcagaaacttgtaacttttgagcaggtccgagcacatggaagtatatcacgtgttt +ctgaaccggcttatccctaagatatatccgtcgcaaactttcgatttagtcccacgtaga +gcccaagcgttgtgcgactccacgtgcatgcccagaaatacgagtttaaatttggttaca +tggttaattttgaccgaagcatcgcactttatgattgataattggattcaatatgtcgcc +ctatgcgaatgcaacatgatccacaatttggctataagacgtttaatccgtatcacactt +tgtttgcggctagtatagtaacgcccgtgcaccaagagtcagtaacaattataagtactc +cgcaggtacttcaaatataaaaactaatcaaacacgacccatatgatcatctgaagatat +ttggaactttctcgacaaccaccctcgtactcaatacttacactaatcgacaggcacacg +caacgtgtacagtcgcaccatattgagtcaagatttgcttagtggcgatgagcgtacacg +cttatttctctagtcacaattagttatctacgagacatcacgagggagcaaataagcgat +gttatggctacacataggcacgtatgaatatgatataagccagttaaacagtcgaaccat +cgagcaaattctcatgcaccaacccacacgttgaggcacaaagagtaagctgtttgaatg +taacttcttctgctgagcgggccccaacgtaaggatcaactagaagagaaaactcggtat +tagtttaaatgcgtcacggagcatgagtgcatttcactaagaatgtctgtgtaaccaata +taacatctatttgttatctgattgcctacttatggctttgcggtcgtggcgactaatgtc +tccaatccttttgaggtcggtaccaactccctttaaattacgctgtgcaggctcatgcac +tgcatacatatacggtagcaggtagggacctcacgcacccttattataatcaatagtagt +tatcagtcaacgaggcaggaatgctgaggtcgaggtgttggtatattttctatgtgccgt +ctaggcgactatcacgcattaccaggcgagatttaagccaattttgaatatagtcaacgt +aatttttactatgggttccaccgaaacgccttgcacaactaagaatcccataaaatatcg +atatcaaataaaagattgtgtcaataccttcatatatattttttcggttgactaacgtga +actaaggttaggggttttgtatgtctatataggaaacagtttcttttctgtcctacttta +gtaaagtcttcaagccttactccaaaatcacggtgattaagccgttactcagcagcatga +ttctgcctgctcgggtcctaaaatccagccttgtaagagtcgctgtgtattagctaggga +gacctttgttaaaaaggatatatcgcggcgggatgtgagtgcgtggcgcatactcaatct +tcagctcgtgtcattataatatctctcccccacgcttttcactagatatgccgtgtaagc +aaacaccttatgcttaatttcgaaaatattggtacttgaaaaaagctgtaggggtactta +atgtctggtaggagatcaggagagaattgagtgtaaaaccgtaaagccctcacctgactt +catgtaaatggcttagaagactccatgatttaataaatactacgaaggaaagactggatc +taaagataactctagtaaggccaactcccttcaatgctgttgccagttataatccaagag +ctgtccttttctgaaccatagcggcttctgaagcgaactagaagcaaagttggttctagc +cagacagccacataccctgtacgggtgtattactaaaactggtccggtattagttcacca +agggaggaattaggcaaaggatctaggtatgcaagtcggagtattacatccctaccctga +atccatcaataggttcctctgtactggccttcgcaatgagtattcaaggttgtacagccg +tataataataagatagtgactatgaacgggaagtaacccgctcaccttccccaaaacatt +gttatatctaagtattaaagtctgccgtagtgttaatactcgaaaataaacaactggcaa +attacaccgcacttaagccgcttttgatttatatttttccaatgcgcttttaaaaataat +tcagtcctacatactaattaagacccttaaacggagatatcacaagttaagttttaacca +tctcgactaggtggaactatagatacccaactcaatttatcattacctgtaatgttccta +gaaggattgcatttcatgtcaagacggtggagtttcacagcgaaacttcagtgtgaacag +attctgagaaatcacctaaacctattagtcagagcacccggttagaaccagttgtcaaaa +aatagagcggttgcatgagacagaagtaacgatgagatccgttgtaacgttgagacatct +ggcctatcgtcaatacagtcctcccttaaaaatatttttaaatactaggcaaacccaaca +taggttagtcctatgtgatacgccacatggtatatcattttgtaacgttacctagggata +atcaggaagtggaattacgcaaaagtagacagtgaaatgcttagggttatagtctagtcc +aaagataaaggataaagcacgtcagagaactatattagccgaatgggaatcattgttagg +agactgtggatcatgtctaaaaagcaacgcagaaacagtcatcgaaaaaatctcgttttt +gtttgaatctaaaagagctttgatgaccgatagtacctgtatactagttactgtattacg +tgtctaatgatttcggattggggtccccagaatcagacgtcattgtagacgattcaagtt +taccaatttaatttcccagctctccttggagaactatcgccaataattgcagtcactttc +cttttctgaaacgataaagccgtcagagttctctgcaacgttggacttacctgaggttct +aacccactttcggttctaatagtagttaacgacacaacgaataacctttactgtggggct +ttcacgatattttttcgcttattattaatggttacgtcataagctggtgtccaaattaag +gttaccggcttcgcagagtagttgtatccaagtataacttccctaatcataagatcgagg +tagaaaattaatgctgtctctaaccgaacagatatgtcccactatgtggtatggacgttg +ctaattacttctgaagggaaattggtcattatggatacgtgtctaccatcaggtcggacg +cagatatggttctgtcttcagttgatccaccgttctttataggataataactgacgatta +aagattatggtaaatagattaagccaattctcttcttgtcagtgaagcatccttaactga +cttgctctgcagcccctcatacatttagctattcaaagtaccggctcgtttcaaactctc +ccacctttggaagaggttgtcaacttgataagtatatcatttacagcattttttcggacg +tacctctaatgtttcattgcagaaaattagttttttctatcgcacattttgcaagtaacg +ttagagacacaattatctgcgaatgaactgctagatctgacgaccgggagcctcgcaaat +atcaaaaaagactgacatatatcaaggagtcgttgacaagtgctggtaagtcaattggtt +tatctgtcccggcgtttcgatcttaagctgaccatgcacggcagagtaatgtcactctcg +ttcttacaagtctgtctccaagggtcggcaaaaaagacccctccattctcgagcccactc +acgatatgtagggacgacaacttgtgcggcttatgaattgtctggactgcgggcgagggt +ccatatctccgaagttagaagggacatacctttagatgataagatcaattcttattgacg +aaattcatccacaacggggaacaacttcaccctagacttacgtctgaaaagacacctagc +gtcttataaaaggtcagtgccccgtttcgtaaggctggaattacctacgcaaacttaaac +ctcgcgcccttccttacgtatcgacaagatagaggctatcgcgaatgtactacggaggca +tgaatcatatactagaaccaagtgcctgtgatattaacaagatgatccgacgcgagcacc +gtaattctaggcataaaactccagcaatttgggggccgaaaacaaatgacgttagctaat +taattatatgacatgatcaaaggaggtcaatcacgcatcgagttcgacgtatattcattg +aacttcgtgcgtttgaaagaaacttttatgaaggcaaaattgatcctgtctcctatttca +tgcgtacctcctagttgataattccccgagcagtggttaggacacttttgtcggtatcaa +gttccggtctcaaaacgtaaaattctgtaatctgtatggatggtctgtgaattagttaat +ttttatgaagtcgtcgagacgcagttcctattgatttattctaaacggagatgtgcttcg +tgggactcggaagtagatctgtgtttatgattattgctactttagatgctgactgttaac +tccgtgttgtttttcaaccgtatatcacaaccgaattggatagaacctatagtttcaagt +tctgccacaaggtatcatatttacagttagtgctggttgcttctttcaaacgtggtgagt +ttgtgctatcacgtcaacggtagagctcagtggaccgagtgcgcgttcaaccctgttcca +gagagggtgtgatagcacatataccacgctcgtcgaggcgttcatgatagtttgcaagag +ccggtgttaaacacatattattattgttatccaactaatcggacctatgcataaagcatt +gtctaaacagaataattgcctatatacggtagttttagtgatttatatcttagtatcagt +tagagcttcgaactcttcaggttcctcatatttaacgttcttcgaaagcgaaaacttcta +caaacgaatgtaagcggttttccaagtagtacctataaatcacagaaagatctgtctcag +tatagttgaaatggtattcagctagtgacgtgtaccaattatcatagttcactcaagcaa +gacgctcattaacgaatatagacaagacactatatcatataataaaaaagaacatggtgc +tcgaacatagttgaattcaccatattgaaggggaatgctgacatgtaattcgctactaga +cgatcaattccctacttgtcaaagttgaactggtacgttcttggaattaaatatgattgc +gctggaccaaattgcgacttcttgagtttcagggcaaacgattgagccggaggatgtccg +tctcttacctttcttgcttatgataaacgacggtccctgtacatcactgggaattctcag +caaaaataattgggtaaatcgagactcgatgtattcggccacaaaggtgttagacgttaa +agattattcaacggggcgataataggatcataaccggtatgcaagcgcattgaaagagcc +atgagatccttatccgataaacgctgcacggtatgtgcagccttattgtcgatcacgaat +ttataaatgtagtctgggctgtaagttgaagacctaagttataatgaagtgcaataccaa +atcgattcatagtggattatcagactcaagatatctcctgataaattacagttgttaaga +tacggataaaatgagatttaagattagcagcctctaatctgtttcaatcccgttggaatg +tggtatgcgatcaaggttaagttaaaatcaagcctgtcttcagtcttgattcttgttctg +ccatcgcatgcggtctacgtgagttaatatgtagcttacgttctagcttgtgctaatctg +agtatagattcgtagaggaatattatcaagcttccacgcctcaacgtacgtgtattggtc +acacaagacactaaaagtggaagtagcgtaaactatagtctagttgttaaatgctcagtt +cttgttatattcgatatactcttggctaatttatgtctgagtatataaaattaatgatat +taacttgcatttcacggatcccttagaaaaagattttgaccgagcgcattataaacggtt +acaccgaatcaatagaagcatacccaatagctttctttgaatttattgcctgcgcaactt +ggctgactctctagatccgaataattctatatggtcgtgacgaaactagttcattactgt +ttaaaatgccaacatgtcttttgggccgataatggctctttgcaaaattactcaatgata +cgattgatcaaagcggtagttgctagtggtagcatgtaagtctatcaaatgtctgattat +ccgaaaatcttccaaaagagtccacgtaccatatctatctcatagcgacgcgaggggaac +cttatctaactatcattccatttaccgggtgactctcgatgcaggatccgattgggataa +attgcccagaaatggctcattcctgactaagggtaaggccgttctcagcaagggaacccc +gcgaatctaggcttataccatctagattgttaactacttgcctgtagttctacagccata +ctggacagttgtttctaaatgatcgggattcatgctagcactcctctgaatgcaccgcgt +aagtttaactattacgtccgtgggcagataaggatggaggctgtatgtatcttaactgtt +acctaatatggctggtaattatcaaagtaaggaccttaatgccatagcgctagcaatcgc +tttgtatactgaccatgtgccaacctctcttaatctgtaaaatataatgtcttagctaac +tgtggacgatcatgtctctgcctagagcttcgctgtatcaattcctatagccagcgtact +agtgacacaacaacaccgtgtgagaaaagatattagtccttacgtctgtctctctacagc +ttattgatgaggattgaacatggacatatagctccccctcaaaagcagatgctacctctt +tattccattctcgaacatttgccgaacttaatttcgacaaacctgaggtcacgtcttaat +ttatcggtaacgtcacgtccctttgagactggataaatatattaccaggggccaacgagc +aattgttggaggcgcttctataatacaaggtgtcttgtcaaagaaagacggcgtgcgtct +cgtgcaactcacttaaccaatattaatgtgaaacccccctctctcacatcttatgcggtg +tactgccctggtacatttcctgtacaggactccaacagtgtagattcctaagatagctgt +tggagttgcctcacgccagatcgaaaaactgaataaactagtgagctgagctgcagaaat +accgcttaattacttatgactagttcaaagggacctacgtgatgtcagacattgcaagga +agaaattaggtttgtgcgtcattttggctggactagcactccttacttcccctactattc +aaatgtcgtaaacagcatgagacaggatcgtgctgacatttaaggtctattgggaacgag +gctacctttggtcgcgcgctcgcgttctccgaatgaccgaaatgcatgagcacagtatgc +aattgcttatagatctaaggtctggtcgttgaaaccaagcacgtaggcctgggaaatcag +ttcttcctcagcaactacacaaaagcgtccaagcattagtacttgtagtaaatgtccgaa +cctatgcgctcatttgaaagtcaaaaaatatttttaagcagtaggcacctaacccgattc +ctctacttagtagctttctttgattctcagaattgactgcaatatcactgcacaattctg +tgccattactagacttctctgtattaacgtctcatcttactaacactcgcctaggacaca +tctgagagtgaagtatttcaatacatttactgaaatcttcagttctaaaatccccgaata +aggctcttatcggtttggccaacacaagaaaaaaacttcttgcaccactcaccttcatac +gcaggagcctggggaacttagtaataactatttcggcagacaaagcttataacaagttgc +cggcgcgtataatatttaaaagaccccttgagctgctcaattaaaacgctcacctggtat +aggctattagatagtgccgtcttagtaaggggcgggaattatcggataaactgatatttt +gataaaataaccgacttgttcacgacataagtcactaaggagattttatctttctccaaa +gtatatcttccttggataatttcaaagcgctgcaatttaagttctgttactagtttatgc +tgctgggaggtgaccggaaggcgtagtaatctagaggcaaattataagaagttcatcata +tcattttcgactacaaaaacaaggtgttgtatgccggcgcattgtgtaaactggacgagt +accctagatggaaaattatacgttaagccaagatttcgatgtaatgataattacctacac +atttttgctatccataggaacaagagctgttctataggctcgtggcatacgaacatttgc +tgccgctatgaatattggaagctcttcaactacagactctattcttaattgccgtcgaaa +atgggccgaatcggctattattaatactcggtttttccgaggggattgttgtcgacagtc +gtaattattattaatattgatgttggtgaggtcatttaaatacaaccttgcagacaatga +ataagggatccaatctctcatactccttttacaattgctcatgcccctatgcaaacctta +tgccgccacacctccgcaactctctcttctgaactgtaagtagcttcattactggtttga +gactatactgaagctgatgacattctaaaatggctattttcgaatgtgattcataatgtt +tatcgtttgggatggcagaatcacgttatttttgatatagcccgggtattctattgtata +gaacgtatgctacaagtcattccccgaagaagactagaagtaaacaacatgcgaccatcg +ttaagccacgcaaggctgtagctttatttcccgataacctatcttccataaatagcggac +agcaggatactgacgctcaacatcagtggttatggtctaatttttaacttttaataaggt +aacttcagcaggcatacacagtaactctttaatttataatcaaattagaagtctgacact +tcttatatttttctatcatccaacgcgatcgcccattagcttattgtgttactaataacg +tatctaaaccaatccttttcaagctactgcctatattgtcaatatatacaaacaacagga +tagtaggctgcttaaaaaatattgtcaaccgtgtacgctttacaatacccggaaatcaca +aactttgtagacaacgagtgaaatttatacactacgaagggccagcgtacaagacccatg +aattaggcgatatgtttattctgacatattggtttatccttaatctgtcgctgtaaaatg +aagccgcccccatccctgcgaattttttttcgaagattcacgactgaaatataaatacgt +ttggctatatttatgttggagggaggcaatagcctttactgttaaccgaagatttagcca +gtgagtgtgacactaaaacactggaataaatgcaggcgttcttctgggtaaaaggtttag +tcaatctcgcctataagttcatatagctctggatataattatctggcccatgcatttatc +atggcgcttggtgccctgtgtgaagccggcctctcatattgaaggtccgaagtattccat +gtacattaagatcactctctcattcatgcatcttggcttaacaaatctggttgtccaagc +tttccaggcacgtatggtacaaattcggatcgaatacttataaaaatgatatgttaaact +gtctaaaacgctcatctacaaagtaaagtgcactaaccaatagagtctcaagaccgtgta +atgctggtgcactgaatgtgtaatacggttagaagggattagttatgttacaaatccatt +gaaaacttaagaagcattgcgtgctcggagggtgcatcttttatcaagagactaacatta +ttttcaacgacgtacatgctttacaatagggtacttatcaaacgccgagaaacgcgccta +tagtgatgttatgattatgacccgatatccattggaccgaattttatgtaggttcccagc +gtactcgcgtaatatctcggtattgccataatgtaatacttgtcggtctctcccagatga +aaaagcgttacagagtatttcaatgaaaaacagcgcgcaacgtcaatacctttaggggta +acggccgctgatttcatatagatatacgataagttggtatagctctactaggtggcatcc +acaatcgttgcatttactatagctggttacaatcataatctataccgttccttacatact +accatagcgggatagcgtttttttgccgttgattgggtttaagaggatgtcagtctcatt +atatccgattcggtgggagagccgttgttttcaaatcgcacactttgtgacataatgtac +aagataacaaaactgatataagatataaactgtcaatatcaccttgacacttgaatcaaa +gtaaattaactcgcaaatataatttgactaattgggtgcagatttctcaattaataaaaa +aatggcaccggatgggcttacaagccccttatcattcacttgtatcatgatttccaagaa +caatagaatttgctagcaagtatgaacagagattcgaattgcatccacagtacgccggag +cgtttattttaatgtggatatgacgatgtactgttggcggcatttgctagtaaccggtcc +ttatttacgtagcgcacacgtaagcatgtctgggagaaatatggtggtacaatctcagag +aaagattacagtttggtttaaataggacttatcgggtcggaagtggaacttaataagcag +tacacaattgggcaacagacgtcttgcctattacaataggattacaatgcgttagatttc +agacacgttcgtgtttggctattcgtcaattccctaaatagttagacgatcaactattat +caaagtgattctttgttcatcctccattcatgtaacagatggcacactacgcataacgcc +gaggaattttaacgagatttaagagagcagttcgggcacaacccacttgactttataaca +gctcggcagcataaacggtaatatgtgacaaatttccaaacgttataagaacgtatgtgt +acttagaaaactaagtggttcatgttcaacagatgtgacgcagcaagcctaacttatcta +ttggttttgctataaaagaacaaagttacacagaatcctaagggcttgtttcacacttat +gcctagtgcttcaccatcttaaaatagcgaaaccggcacgaatcaaaccttaaaacaatg +cgcagatattggtgatggtgactccgggtatgataatggtaactgttgaccagcgcccac +ctcatcgaagtatagaaagtggttaggataaggatgagaccgaacttatttccggccata +actttagattttctacctagtacacaacatcagggcggacacgaaaccgccatcacatca +tataccaggtttaatttgcttaatgggggaagtgtcaacgaaccttcgaactttagcagg +catatggccattatatatggccccagagcagaatgctacagcagacaaaatttggattta +tgtagtttaatacctatcaaacttggtgtgaccatacttgtctaacgacagtgcacaaag +tgtaagttacaattattactactcagcagcttctgcaatgataaaatcttatcatacacg +tcacatatgataatatctacttagggggaacgggctccacaacctacatagtactcaata +cttacactattcgacaggcacaccaaacctgtacagtcccaaaagattgagtcaactttg +cagtactgcagatcacagtaatagcttagttagcgagtcaaaattagttttctacgagac +tgcacgaccgtgcaaatttccgatgtgttggctacaaatagcaacgtatgaatttgtttg +aagccacgtaaactgtacaaccttagagataagtctcaggctactaaaaacacgttgtgg +cactaacaggatcatggttgattcttacttattcggctgaccggcccaataagtaacctt +caactagaacagaataatcgggagtagtttaattcagtcaaggtgcaggtctcattgtaa +ctaacaagctctgtgtaaccaagttaaaatcgttttcttagcggattccctacttatgga +tttgagctcgtccacaatattcgatacaagaagtttgtggtccgtaacaacgaaatttta +attacgctgtgcagcctcatccaaggaattaatagaaggttgatggtaggctccgaacgc +tccatgattataatcaagtggactgtgcagtaaacgaggaaggtatcctgacgtcgtggt +gttcgtttttgttatttgtgccctatacgagtagataaaccatgaacagcacagtgtgaa +cccatggttgattttaggctaccttatttttaatttccgttacacagaaacgaattccac +aactaacatgccattaatttttcgatatcttataaaagatggtcgaaattcattcattta +ttttttttcggttctcgaaagtcaactaagctgtcgcgttttgtttctctttagaggtaa +aagtggctttgatctcctacgtttggatactagtcaaccattactccatttgatccgtga +gtatcacctgtctaacatccagcattatgactcctcggcgaagaaaagacacacttctta +gagtcgatgtgtattagctagggacacagttgtttaatacgatagtgagcccagggaggg +cagtgcgtcccccagtagatttattcagctagtgtaagtataagatatctcacccacgag +gttcaagtgatatgcagtcttagaataatacttatcctgaatttcgatattatgggtact +tcaataatccgctagcgctactttatgtctcgttggacagcaggacacatggcagtctta +aacactaaagacatcacctgaatgaatgtaatgggattacaagaatcaatgaggtattat +atacgacgtaggaaactctggatatatacagtaatctagttacgccatcgcacttcattc +ctctggaaacttagaagacatcagctgtacgtggaggaaccagacccccgtatgtagcca +aatagaaccaaagttgcttatacaaacacacccaatgacaatggaccgctggagttcgta +aactcggaacgtagtactgcacaaacccagcatttagcaataggagctacgtatgcaact +cccacgtggtaataccttcaagctatcaatatataggtgcctagctaatcgcattcgcaa +gcagtattcaagcttgtaaaccagtataataattacagaggctctatgaaacccaacttt +ccagctaaaagtcccaattaaatggttatttcgtacttttaaagtcgcccgttctgttat +tacgcgaattgattctactccaaaattaaacacaaattatcaaccgtttcatttatattt +gtcaatgcagctgtttaaaataaggctctactaaattataattaagacacttattaccag +atttctctagttaagtttgaaccagctcgactaccgcgaaagatacattcccttctctat +ttttcagttcatctatgggtcagagaagcattgaatttattctattcaccctcgtcgttc +acagcgaatcgtcagtgtgatcagtgtatgagaaatatcctaaaccgtttagtcagacca +cacgcttagaacaagtggtctaaaaagactgccctggaaggagtaagaagtatacagctg +atccggtgtatccttcagtcatctgccctatactaattacacgacgcaaggaaaaatagg +tttattttctaggcaaacccttcataggtgactccgatgtgttacgaatcatgcttgaga +atgtgctatcgttaccgacggataataacgatctccaatgaaccaaatgtagaatgtcta +ttgattacccttttactattcgacttagagataggagatagaacctcagtgtactttttt +agccgaatgggaatctttgggaggtgaatggccataaggtcgtaaatccaaccctcttaa +agtcttccatattatatcgttgttcgtggaatcgataacagatttgttgacccatagtaa +atgtatactagtttatgttgtaagtgtagattgttttccgattgccgtccaaactttatg +tcgtaattgtagaccagtaaagttgaccaaggtaagtgcccagcgatcctgcgagatcga +tcgccaatttttccagtcactgtaagtgtaggtttagataaagccgtatgagttatatca +taagggcctcggaaagcagcttcgaaccaaagttcccttataatagtagtttaactataa +aagtatatactggtctgtcgccctttcacgatttgttttaccggtttatgaagcgttacg +tcattagagcggctccaatttaaggttaacggcttccatgtgtagttgtatacaaggata +acttaaagtatctgttcagcgagctagttaagttatcctcgatagaacacaactcagagg +tcccaagatcgggtttgcaacttgctaatttattctcaaggcaaattgggaattatcgat +acctgtataccataaggtcgctcgatgtgatgcttatgtcttctggtgatcctaccttag +ttagtgctgattaacggaacattaatgtttatcgttttgagatttagccaattctctgat +tctaactcaagatgccttatctgacgtgctatgcagcccctaagtattttacattgtaat +aggacacgctcctttaaaactcgccaaaaggtcgttgtggttctctactggttaactata +taatttacagctttgttgagctagttcctctttggtttaagtcctcaatattagttggtt +cgagcgataagttggctagttaccttagtcactatattagatccgaatgttatgcttcat +ctgaagaccgccaccctccaaaatttcttttaagactcacttattgcaaggtgtaggtga +attcggctcgtttctcaagtggtgtatctgtacacgagtttccatattttcatcaacagc +caccgcacacttatgtcactctaggtattaaaagtcgctctacaaggggacgcaattaag +aaacagacatgctagtcaaaaataaacatagcgaggcaccactaattcggccgcttatca +atgggatgctctgcgcgagacgcgccagagctcagtagttagttcggacatacatttact +tcagatgatcaattagttttctacaaatgcttactctaccccgaaaaaagtcaccagact +cttacgtctctttagtatccttccgtcttatataaggtcagtcccccgtttcggtaccct +ggaatttactaagaataatgaaacagcccccaaggacgtacgtttacaaatgatagacca +gatcgcctagcttattccgacgcatgttgcatagaattgaaccaacggaatgtgagagta +actagatgagccgaccacagcacccgtttgcgtcgcagaatacgcctgatagttcggcca +cgaaatcatatgtcctttgagtattaagtatttgtaatgatcaatcgagctcaagcaagc +ttacacttcctcggatattcagggaacttagtgcctttgaaagatacgttgatcaacgaa +aaattgataatggctcatatggaatgcctacctcatagtgctgaattaacacagcactgc +ggacctaacttttcgaggtttcaagttcacgtctcaaaacctaataggctggaatatgta +gggatcctcggtgaatttgtgattgggtttgttgtagtactgaccaagtgaatattcttt +ttttctaaaagcagatctgctgccgggcactacgaaggagatctctgtgtatcattattg +cttcttgacatgatgactcttaaatcactgtgggtgtgcaaaacgatagcacaacccaat +tcgatagtacatattgttgatacttcgcactaaaccgttcatatttaaaggttgtgctcc +ttccttcgttaaatactggtgacttggtcctatctactattagctagacctctggggaac +cacgcccccgtaaaacctgtgcaagagagggggtcatacatcttagacatcgcgcctcca +ccagggaagcattgggtgattgaccaggtgtgtaacaaatatgattattcttatactaat +attagcaaagatgcataatgatttgtattaaatgtataattgaattgataagggtctttt +agtcagtgatagagtagtataaggtagacattagaactcttaaccggacgcagatttttc +ggtcttagtaagccaattagtcgacaaaacaaggtaagagcggttactagtagtacctat +aatgcactgaatcttcggtcgaagtatagttctaatgctatgcagattgtgacggcgaca +aatgttcagacttatatcatgaaacaagctcttgtaagtattgacaaatgaaaagattga +atatttttaaatacaaaatgcgcctacttattaggggaattaaccagattgaaggccaat +cctcacatgtaatgagataatagacgataaatgaaattcttgtaatagttgaactgctac +gtgatgggtattatatatgattgagatcctccaattgccgacgtcttgtcttgatgccca +aaagattgtcaacgaggagctccctcgcgtacctgtcgtccgtatcataaacgacgcgac +atgtacagcactccgaagtataagcaataataatgcgggtaatccagactagatcttttc +ggactcaatgcggtttcacggtaaacatgattaataccggagagtagtcgagcttatcag +cgatgcaagcgaattcattgtgccaggagatacgttgcagataaaaccggcaacgtatgt +caacaagttttggcgatctcgttgtttgtattcgacgaggcgcgggaacttcaagaacta +tcgtatattcaagtccattaccttttagtttcagactggtggagctgactaaagttatat +catcattttgtacactggtttagttaacgataatttcagatttaacatgaccagacgata +atcgctgtatatccagttggaatgtggtttgccagaaaggttaacttataatcaagcctc +tcttcagtcttgattcgtcgtatcccatccattgcgctatacctcagtgtatttggagct +gtagttataccgtgtgctaagatcagtagacatgacgagagcaatattatctaccttaca +agcatcaacggacgtctagtcggaacaaaagactctaaaactcgaacttcaggttaatat +actatagttctgtattcagcagttattcttatattcgatattatcttgcctattggatgt +ctgactttagtatattaatcatagtatctgccatgtaaaggtgccagtactaaatctgtt +tcacagtgcgaattataaacggttacaaccattaaagacaacaagaccctatagctttat +ttgaattttgtcaatgcgcaacttggagctcgcgatacatcccaattagtctatagggtc +gggacgattctacggcatttctggttataatgacaacatggattgtggcccgagaatcgc +tctttcattaattaagcaatcattacagtcttataagcgctacttccgagtggtagcagg +taactcgatataaggtcgcatgagccgaatagcttaaaaaacaggccaccgaacattgat +agagaataccgaccacagcgcaacctttgattactttcattaaattgtacggctcactcg +acatcaagcttaagattgcgataatgtgaactcaaatggatcagtactgaagaaccgtaa +cccacttcgcagaaagcgtacccagagaagatacgctgttacaatatacagggtgaaatt +attgcctgttcttcgtaaccatttcgccaaacttggttagaaatgatagccattcatgat +agaaataagctgaatgataccagtatctttaactatgtagtcagggggaagataacgatg +gtccatgtatgtttctgatatgtgacagtattggccgcgtaatttgctaacgaagctact +taatgcctttgagcttcatatagatttctttaatcaaaatcggcaaaaagatagtatgag +ctataatatatgctagtagagaactctggaccatcatctatatgaatactgattcgagcg +tgcaattactttagcctgcgtactactgactctacaaaacactctgagataagtttgtag +tcagtaagtcgctctctataaaccttttggatgaccattgtacagccacttatagatccc +aataaatagcacaggagacagagtttttcaatgctcgatcatttgccgatagtattttcg +tctaacctcagggcacctattatttgatacctaacctaacggccctttcacaatggagaa +atatatgacatcgggacaaacacaaatggtgggtggccaggagatatgacatggtggcgt +ctctaagaaacacggactccctctaggcaaactcacgtaaccaattttaatgtcaaacaa +aacgctcgaaaagattttgccgtgtaatgacctggtacattgactggtcaggaatacatc +actgtagttgccgtagtgtcctgttggtgttccatcaagacacatcgtataacgcaattt +acgacggacatcagatcaagttatacagattatttaagtatcacgtgtgcattgggacat +aagggatctcacacatgccttggaacatttttgctttgtgccgctttttcgctgcactac +caatccttacttaccagtatattcaaaggtcgttaacagaatgagaaaggttagggctct +aagttatcgtcgattgggatagacgagacatttgcgagcgccctccacggatacgaatct +cccatatcaatgtgaactggatgctatgcagtttagttcttacgtctcctagtggtaaaa +atcaaagtagcactcgcatagcagttattcagaacctaatacacaaaaccgtcaaacatt +ttctaattctaggtatgggccgatcataggagctaaggtgaaactcataaatgttttgtt +agatctagcatcctaaaaagatgcatatactgagtagctggcgtgcattctctcaattgt +atcctttttaactgaactagtcggtcccatttcgtgactgagatctattaaccgataaga +ttaataacactcgcattcgtatcagctcagagtgaagtttttcaataatttgactgatat +attaacttctaaaataaccctttaagcctcggatccgtttcccaatcacatcaaaaattc +ttattccaactatctacggattaacaacgtgcatggggatcgtagtaagaacttgttccg +atcactttgagtatatcaagttgacggcccggttattattgaatagaaacattcacctgc +taaattaaataccgcacatcggatacccgatttcagagggccgtcttactaagggcaggc +tttgttcggtttaactgagatgttcattattttacagtatgcttcaactaatatgtaacg +aaggacagtggatctgtctccatagtagatcttcagtcgtgaatttcataccgctcctat +ttaagttcgcgttcgagttgttgatcatggcacgtgaaagcaacccctagtattctagac +gaaaattttttctagttcatctgataatttgccaattcaaaaacaaccgctggtttcccg +gcgcattctctaaaatggaagtcgaacctagagccattatttgtcggtaacccatgagtt +ccttcttttcagaagttaatacactgtggtcctatacagaggaaaaacagcggttatata +cgatcgtggcataacaacattggatcaagatagcaatttggctacctattctaattctca +ctagattcggtattccactacaatatcggcagattaggattggatgaataatcggtgttt +aagtccggttgcgtctccaatctcctaatttttattaatattgatcttggtgacctattg +taaataaaaacttcaagactttgaataacggtgaaaagatagaagactcatttgaaaatg +gatcatccacagatccaaacattagcaagacactaatccccaactagctattctgatcgc +gatcgtgctgcagtactcctgtcacaatagtctgttcatgatctaattctttttgggctt +tgttcgatggtgattcagaatctttatccggtcgcttccctgtagctactttgtggggat +attgcccggggattatagggttgagatcgtttcctaaaagtatttaaaccaagtagactt +caactaaactacatcagaacatcgtgaagacaccatacgcggtacctttatttaccgata +acatttcttcaagaaataccggtaagcagcataatgaccctaaacagctcggggtatcgt +cgtagttttaaattttatttaggttactgctcaaggaataaaaactaactatttaattta +taataatattacaaggctcacactgattagatttgtctataagacttcgcgatcccccat +taccggattgtcttaagaataaactagataaaccatgcattttctagataaggcctttag +tctaattagatacaaaaaacacgatagttgcatccttaatttattgtgtcaaacctggaa +ccttttaattacccgcaaatcactttatgtcgagactacctctgaaatttattatctacc +taccgcatgaggacttgaaccatcttgtaggagttatgtttattagctaagattcgttta +tcctgtagcggtccatgtatattcaacaagcaaaaagcactcagaattgtttttagttga +gtcaagactgatatataaataagtttccctagttttttcgtggtgggacgatattgaatt +gaatcttaaccgaagagtttcccactctgtcgcacaataatacacgccaatatttccagc +cctgcttatgccttaatcggttactcaatctcccattgaagttcattttgatctgcatag +aagtttcgggcccagccttttttctgccaccttcctccaagctctgtagacgcactctaa +gattgatgctcacatgtattaattctacattaacataaatatataagtcatgcatcttcg +agtaaaatatctggttctccaacatgtcctggcacgtatcgttataatgcccatacatgt +agtattaaaatgattgggttaactggatattaagatcatcgaaattgtaaagtcaaatta +acaatactgtctcaagaccgtgtattcctcgtgctcggaagggctattacgcttacttcc +gttttggtatcttaatatgactttcaaaaattaagttgcagtgagtcctacctgcgtgca +tcggttagcaagagtataaaagttgtttaaacgaactacttgctttacaataccggtcgt +atatatcgccgtgaatccagaagattgtcttctttggattatcaaccgagatcctgtgga +ccgatgttttgggaccttcacagaggactccaggtagagctcgcttttgcattaatctaa +gaattgtacctctctaaaagatctaaaacagtgaatgtgtatttcatggaaaaacacaga +gaaacgtaaattactttaggccgaaaggcacatgagttattatacatatacgagatggtg +gtatacatcgaattcggggcatacactatagttgcattgtatttagctgctttaaataat +atgatattaccttccttacataagacattaccggcataccctggttttcaacttgtgggg +ctttttgacgatcgcactctcatttgatccgagtagggcggtgacccctgcttttcaaat +acaaaaatttcgctatgaaggtaatagattacttttcgctgttatgatagaaacggtaaa +tttaaaattgaaacttctagaaaagtaaagtaacgagaaatgattttgtgaataatgcgg +tcatgattgcgcaagtaagaaaaaaaggcaaaaggatgcgcggaatagaaacttatcagt +cacgggtatcttgatttcattcttcttgtcaattgccgacataggatgaaatcagattcc +aatgcaatacacagtaacccccacccttgattgtaatgtcgatttgaagttgtacgcgtc +gacgaagtggatagtatacgggccttttgtacggtgcgatcaactatgaatctcggcgag +ttagatggtcgtacaatctcacacatagaggtcacttgcctgtaatgacgaattttcggc +taggtactcgaactttattagaagtaaaaatgtgggcaaaagaaggattccattttacaa +gacgattacaatgagttacatgtctctcaacgtagtctttccctagtagtctttgaacta +tttaggtactccagaaaattttagcaaagggtttctgtgtgaatccgccattcatgttta +tgatggaacaataagaataacgccctcgtatgttatcgacagtgaagtcagcagttcggc +caaaaacatattcaatttagtacagatccccagaagttaagctaagtgctctaaaatggc +ctaaacggttatcaaagtaggtctaattactatactaacgggtgcatcgtaataactgct +gtcgatgcaacactatatgatagtgtcgttttgctatatatgtacaatgtgacaaagaag +ccttagcgattcttgcaaacttaggacttcggattctcaatcttaaatgtccgaaaacgc +aaagattcaaaaatttaatctatgagcagatatgcctgatggtgactacgcgtatgttaa +ggctaaatgttgacaaccgcacacataatcgaactattgatagtcgggagcataaccagg +tgaacgtactttgttcacgacatttattgacatgttctaaatacgtctcaaaatcacggc +gcactagaaaacgcaatcaaatcattgtcctggtttaagggccgtaatgccggtagtgtc +aaacttcatgagaactttagctggcttttggccagtatttagggaccaagagcactagcc +ttaagctgaatattttgccatttatctactgttataactttaaaacttggtggcaccaga +cttgtcgatacacacgcatcaatctgtaacgtaaaaggtttactaagaacaagcgtagga +attgagtttatattatatttaaactaaaagatgatattagcttctgagggcgatagggct +ccaaatcataaagaggaatatattattacacgattagaaacccacaacatacctcgaatc +gcccaaaagtttgacgaaacttggcagtactccacatctcagtaatacagttgggagagt +ctcaaatgttgttttattactcaatgaaccaccctcataatttcactgctgttccattaa +atttgcaaacgatcatttgctttgaagaaacgtaaaatcgacaaaattacagataagtag +atgcataataaaaaaaactgctcgctataacacgatcatcgtgcattcttacttaggagc +atcacccgcacaataacgtaccttaaactacaacactattagaccgagtactgtaattca +cgaaagctcaagctcgcattgtaaagaacttgctctctcgtaaaatgtgataatagtttg +cggagaggattcaattattttccattgcacctactccactagattcgataaaagaaggtg +gtcctcccttaaaaagaaatgttaagtaacatcggaaccataagcaaagcatgtaagtga +accgtcatccttccctaagaaacataaaggtttttaataatgtcgactgtgaactataac +tgcatcctttcctgacctactccggttccttgttgttatttctgaacgagaccagtagat +aaacaatgtaaaccacagtgggtaccaatggtgcatgtgacgctaccgttgttttaagtg +cccgtacaaacataagaagtcataatcttacttgaaattaattttgccttttattttttt +tcaggctcgaaattaatgatttgttttttttgaccttctagttacgctaatatgcggtcg +cctgtggtttctattgagtcctataacgggatgggatctaatacgtttggttactagtaa +acaaggtataaatttgataccggagtatcaactgtataacatcaagctttatgactcata +cgcgaagtaatgacacaaggctttcaggagatcgcgagtacagagccactaaggggtgta +ttacgatagtgacaccaccgagcgcactcactccccaagtagatttatgatcctacgcta +agtattagatatataaccaaagaggttctagtcagtgcaactcttagaataataattagc +cggttttgcctttttaggcctaatgcaatattcagctagcccttatgtatctcgcgttcc +acagcaccactcatggcacgcgtttaaactaatcaaatataatctatgaatgttatgcca +gtacttgaataaatcaggttttttataagtccttgcatactctcgttatatactgttaga +gtcttaccccatagaaattctttcatctgcaaacttagaagaattctcagctacggggag +cataaagtccccaggatgttgacaaatacaacaaatgtggcttatacaaacactccatat +gaaaatcgaaccctcgtggtagttttagccgaaccttgtacggataaatccctccatttt +ccaatagcagatacctatcctactacctcgtggtattaaattaaagcttgaaatatagag +ctgcatagcttatccaattcccaagcacgagtctaccgtcgtaaccacgatttgatttac +agacgctagagcaaacccatctttaaacatataagtaaaaattaaagggtgagtgcgtac +gtgtttactagcaacttcgcttattaagacaattgtttataagccataattaaaaacata +tgttcaacaggttcattgatatttgtaattgcacaggtttttaataaggatctacgtaag +tataatgaacaaactttttaccagagttatattctgtactttgaaaatgctcctctaccg +ccttagagactttcaattagattttttgcagttaatctatgcgtaagtgaaccatgcaag +ggatgcgattcaaccgcctcgtgctaaccctatcgtctgtctcataactgtaggtctaat +ataattttcagttttcgaacacataaccctttgaaaatctgctatttaatgtctcacctg +catgcactatcttctatactgctcagaacggctatacgtcactatgctccaagtgacgat +ttaaacgaagcaaggaataataggtttattttagtgcaaaacaattaagtgcggactacg +tgctctttacaataagccttgtgattgggctataggttaagtcccatattaacgatctcc +aatgtacaaaatcgacaatcgctttgcattacccggttactagtcgaattacagatagct +gttagatactcactctaattttggacaacaatcccaatcttggggtcgtctatcgcctga +agctcgtaaatccttccatcttaaacgattacatattatagacttgttcggggtagagat +atcacagttgtgcaaacattgtaaatcgatactagtttatgttggtagtctagttgcttt +taccattccccgaaaaacttgatctactatttcgacaacagtaaacttgaactaggtaag +tgaaaacagagaatgcctcatagtgccactatttgtccactatatgtaagtgtagcttta +cataatccactatgactgagatcattacggcctaggaaagcagcgtagaaaaaaagggcc +cggatattacgactgtaactataaaactagttactggtagcgcgccatgtatagatttgt +tttaccggttgtggttgcgttaacgaatttcagccgcgaaaattgatccgttaaccagtc +catctcgacttctataaaacgataaagtaaagttgatgttcagcctccttcttatggttg +catcgagagtacactactcagtgggaaatagatcggggttcctacttcagattgtattat +ctaggcaattgccgattgtgccatacctggataaaataagctacctacatgtgatgctta +tctattatcgtcatactaccttagggtgtcctgttgaacgctacattaatctttagccgt +ttgagatgttccaatggataggagtctaacgcatgatgaagtttaggaaggcagagcatc +ccactaagtatgtgacagtgtatttcgaaacgagacgttataaatagaaaaaaggtcctt +ctggttctattctgctgaactattgaatggaaagattggttgacctacgtactatttgct +tgaagtcatcaatttgacggggtgagagacatatggtgcatactttacggactctatatt +ttagatcagaagcttagcagtcttctctacaccccctcacgacataattgcttttaagaa +tctatgtttgattcctctacgggaattcggatccgttcgcatgtgcggtttatctaaacc +aggggacatatgttcagctaaagcatacgaacactttgctaactagacgtatgtatagta +gctataaatcccgacgatatttacaaaaagaaatgagactcaaatatatacatagcgacc +ctacacttattcgcaccctgatctaggcgatcctagcacccacacccgaaagtgagcact +agtgtcttccgtattaaatttactgcagttgagattttagttgtctactaaggattactc +taacccgtaataaggatcaagactcggtactagctttactatcattccctatgtgttttc +ctaactcacaagggtacgtaccagcctatgtaattacaataatgataaagacacaaagga +agtaactttacaaatgagtctccagttacactagcttagtccctcccatcttgctttgaa +gtctaaatacgcaatctctgaggatatacagcagaagaacactcataacgttggagtcca +agaattagactcatagggcccccaacatttaatatgtactgtgagtttgaaggtgttcta +ttgttaattcctgctcttgatacatgacacgtactccgtgtttaaggcttcggactgact +ttctttcataagttgagcaacgaaaatttcagaatcgataagttggattcactaactaat +acggctgattgaaaactccactccggacctatatggtcgacctttatacgtaaccgatat +aaaacttataggctggtatatcgagccttcctagcgcaatttcggatggggtttcttcta +ctactcaacaacggaatagtctttgtttagtaaaccagagctcaggacgcccaatacgta +ggagagcgctgtggagcatgtgtcattatggactggagcactcttaaatcactctgcgtg +tgctaaacgatagatcataacatgtcctgagtaaattttcttgatacgtcgcaatatacc +gttattagttaaacgttctcatccgtcatgcgtgaaatacggctgtcgtgctcagatata +ctattagcgactcatctcgcctaacacgcacacgtataaactcggaatgactgccgctct +tacatattagaaatacagactacaccacggaagcattgggtcattctcaaccgctgtata +aaagatgattagtcttataataagattaccaaagaggcagaatcatgggtagtaaatcta +ttattcaagtgattaccgtcgtgtaggcagggagtgaggacgagatggtactcaggacaa +atattaaccggacgaagtggtttacgtcgtactttcactattagtagtaaatacaaggta +acaccggggaatagtactaaatataatgatatctatcttcgggagaacgagtcgtctatt +gctttgaacattctcaaggcgtaaaatgtgctgacttatagcatgatacaaccgattgtt +acttttgtctattcaaaagattgaatagttttttatacaaaagccgcatacttatgacgg +ctagtatacagtttcatcccctagcatcaatgctatggacagtattgaacttataggaaa +ttcttctaatagggcaaatccgtcgtgatgcctattttttttcagtcacatcctcaaatg +gcactagtattgtcgggatcccattaacaggctcaaccacgagctcacgcgaggacatgt +agtccgtatctttaacgaagcgacagcgacagaactcccatggataaccaattataaggc +ccgtaatcctctagacatcgtttaccaataaatccgctttctccgtaatcatgttgaata +ccccagagtagtccagatgataaccgatgaaacacaagtctttctcaatgcacttacggt +gaacttattaccgccaacgtagctcatcaaggttgcgacatctagttgtgtgtttgcgac +gagcccagcgaacttcatcaactttcgtatattcaacgccttgtaattttactttaagac +gcctggtgatgtagattcttagataatcagtttgttatcggctgtactttaccataattt +cacaggtttcaggtcaagaagattatagctgtatatacagttccatgctcggtgcacaga +aacgtgatcggataataatcaatcgcttatgtcgtctttaggcgtatccaatacatgccc +cgataccgcagtgtatttcgacatgtaggtataccgtcgcatttgagctcgagtcaggac +gtcagctagattagattccttaatagaatataccgacctctagtccgaactaaactatag +ataacgccaacttcaggttaattgtctagtcgtctgtttgcagatgggattcttagatga +gtgagtatcggccatattggttcgagcactttagtttttgatgcataggatatgcaatgt +atagctgaaagtactttatctgtttcaaactcacattgattaaaccggtaaacctttaaa +gactacaagaaaatattcagtgagggcaattttgtcaatcacaatcttccagctagagat +acttcacaatttgtcttgaggctacgcaacattagacggattttcgcgttttattgaaat +aatcgaggggcccaagagtatccatagttcattttgtaagatttctttacaggcttatta +cagcttcttcagactcctacatgcttacgagttatatgctagcatgtgaacaatagatta +atatacaggaaaacgtacattgagagagatgaccctacacagcgcaaccgttgagtactt +tcattaaagggtaacgctctcgagacagcatccttaagatggccttattgtcaaatcatt +tgcagaagtacgcaagatccctaaccaacgtagaagaatccctacaaacacatgagacgc +ggtgaaaatagacagggtgttagtattcaatcttcggagtatcaatttcgccaatcttgg +tgagaaagcataccctttcttcagagaaagaagatcaatcataacactatctttaacgag +gtacgcacgcgcatcattacctgcctccatggatctttaggatagcggaaagtattggca +gcgtattgtgatttcgttcctactttatcaatttcacattcatatacatgtcttttatca +aaatcgccaataagataggatgagctatattagatgctagtagagttcgcgccaacatca +tcgataggaatactcaggacagcgtgataggacttttcaatccctaatactctctataat +tataactctctcttaagtttggaggcagtaacgcgctctatataatcagtttgctgcacc +attcttcagcctctgatacatacaaataaattccacagcagtaagagggtttaattgaga +catcttgggaacttaggattttactctaacatcaccgaaacgattattggataccgtacc +taaacgaactttctcaaggcagtaatataggacatccgcaataacacaaatgctgcctcc +ccaggagttatgtcttcctggaggctatatcttacacccactcactataggcaaactaaa +gtttaaatgttgattgtctaaaaaaaagatagataagagttggccggcgtagcacatgcg +aaagtgaatcgtaagctataattctctggacttgaagttctgtcctgttcctctgcaaga +aacaaacttcctttaaagctatttacgacgcacatctcagcaagttataaacatgttgga +agtttctagtcggaattcccaaagaacggatctatctaatgcattcctacatttttcctg +tctgccgatggtgccatcctattcaaagaatttcttaaaagtagattaaatgggactttt +aacaatgagtaaccttacgcctctaagggttcctcgagtgccatacaccagtcaggtccg +agccacatacacggagaacattctaacatagcattctcaactcgatcatttgcaggttac +ttctttcctatcctagtgctaaaaatcatacttgcaatcccatagcacggattaagaacc +taagaaacaattcagtaaaacatgttcgaattcttggtatgggaacatcattgcagctat +ggtctaacgcattaatgtttgggtacatcttccatcatataaacaggaagagtctgacga +cagggagtgcttgcgatcatgtctatcattgtgaaatcaaattgtagctcacatgtcgtc +tatgagagcgtgtatccgataagatttagaaaaatagaagtcgtataagatctcactgaa +cttttgaatgaatgtgaagcatatatgatctgctttaataaaactttatccataggatac +gtttccaaatcaattcaataattattagtcaaaatagataaggatgaacaacctgaaggc +cgatcggacgtagaaagtggtcccatcactttgagttgatattgttgaaccacacgttat +tatggttttcaaacagtctcaggatattgtatatacagataatccgataccagttgtctg +acgcccctcttacgtaccccaccctttgtgacgtttaaagcagttgttcagtattttaaa +ctaggcggcaactaatttggaaagaagcacagtggatatgtctaaattcttgttattcag +gcctgaatttaatacaccgcatagttaacttcgcggtagagttgttcatcatgcctcctc +taagctaccacttctatgatacaccaatagttgttctacggaatctgataattggccaag +tcataaacttccgctgcgttcaacccccttgctcgaatatccaactcgaaaagacagcct +tttggtgtccggaacaaatcagttacttcttttctgatgttaattctctgtggtcagata +cagaccaaaaactccgcggatttaccatcctccaagaacaaatttgcatcaacatagcat +tttggctacatattctaagtctcaatagtttaggttttcaactacattatcccaacatta +ggattggaggaataatagctgggtaagtccccttgcgtctacaatcgactattttttatg +aatatgcttctgccgcacctatggttattaaaaaagtcatgactttgaagaaccctgaaa +agatagatgaatcaggtgtaatggcagcagccaaagagcatataattagcaacactctaa +gaacattatagatatgatgatagcgatcgtcatgatgttatccggtcacaatagtagctt +catcagctaattcgttttgccagtggtgacttgcgctggaagaatcgttatacggtccct +tccctcttgatacggtgggggcttattcaaccgcgtggattgggttgtcatacttgcatt +aaacgatgtaaaccatctagtagtcaactatactaaatcacaaaatagtgatcaatacat +acccgcttcatggttttaaccatttaattgattaaagatattccgctaagaaccattatc +tacctaaactgatcgccgtatcctagtagtttgaaatttgatgtaccgtaatgatcaacg +aagtaaaacgttatattgtatgtagaataataggtcttggagctaaatgatgtgattggt +agtgaagacttacccttacaactttaccggtttctcggaagaatatactagagaatcaat +gcatgggctacataagcactttagtctaatgagataaaaaatacacgagtcttccatcat +gaattttttgtcgaaaaactcgaacctggtaatttaaaccatatatctttatgtcgtcaa +taactctcatatgttttatataacttcccaatcacgacttgtaactgcttgttcgactga +gctgtttgagctatgaggccgggatccggttgagctacatctatttgctacaagaaaaat +gaaagcacatttgttgggagttctggctacactcatagagaaataagtggcccgagtggg +tgcggcctgcctccatattcaagtgtatcttaaaccaagtggttccaacgctcgcgctaa +agaattaaagcctttatttcctccacggagtagcccgtaatccggttcgaaagagaccat +tgaagttaattttcatatccagtgaagtttaggcacaagcatgtgttctgccacatgcct +caaagcgctcttcaaccaagatatgattcatcctaacttcgatgaatgcgtctgtaacat +aaatatagaaggaatgattcggcgagttaattttcgccttctccaacatggcatccctac +gttcgttataaggaccatacatgtaggttttaaaggtttgcggttaatcgatatttacat +catagaaattctatagtcaaatttacaagactctagatactcactcgttgcagccggcta +ggaagcgctttgtaccttacttcccttttcgttgcgtaatatgaatttcatatagtaagt +tcaaggcactcatacctccgtgaagagggtagatagactattaaagttgtttaatagtac +gtattgatggaaatgacccgtaggagatttaccactcaatccacaagattcgctgctgtg +cattatcaaaacagtgcatgtcgaaacatgggttgggtccttcaaacacgaatccaggta +gagatacctttgcaattttt diff -Nru cargo-0.25.0/vendor/regex-0.2.10/examples/regexdna-output.txt cargo-0.26.0/vendor/regex-0.2.10/examples/regexdna-output.txt --- cargo-0.25.0/vendor/regex-0.2.10/examples/regexdna-output.txt 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/examples/regexdna-output.txt 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,13 @@ +agggtaaa|tttaccct 0 +[cgt]gggtaaa|tttaccc[acg] 3 +a[act]ggtaaa|tttacc[agt]t 9 +ag[act]gtaaa|tttac[agt]ct 8 +agg[act]taaa|ttta[agt]cct 10 +aggg[acg]aaa|ttt[cgt]ccct 3 +agggt[cgt]aa|tt[acg]accct 4 +agggta[cgt]a|t[acg]taccct 3 +agggtaa[cgt]|[acg]ttaccct 5 + +101745 +100000 +133640 diff -Nru cargo-0.25.0/vendor/regex-0.2.10/examples/shootout-regex-dna-bytes.rs cargo-0.26.0/vendor/regex-0.2.10/examples/shootout-regex-dna-bytes.rs --- cargo-0.25.0/vendor/regex-0.2.10/examples/shootout-regex-dna-bytes.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/examples/shootout-regex-dna-bytes.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,66 @@ +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ +// +// contributed by the Rust Project Developers +// contributed by TeXitoi +// contributed by BurntSushi + +extern crate regex; + +use std::io::{self, Read}; +use std::sync::Arc; +use std::thread; + +macro_rules! regex { ($re:expr) => { ::regex::bytes::Regex::new($re).unwrap() } } + +fn main() { + let mut seq = Vec::with_capacity(51 * (1 << 20)); + io::stdin().read_to_end(&mut seq).unwrap(); + let ilen = seq.len(); + + seq = regex!(">[^\n]*\n|\n").replace_all(&seq, &b""[..]).into_owned(); + let clen = seq.len(); + let seq_arc = Arc::new(seq.clone()); + + let variants = vec![ + regex!("agggtaaa|tttaccct"), + regex!("[cgt]gggtaaa|tttaccc[acg]"), + regex!("a[act]ggtaaa|tttacc[agt]t"), + regex!("ag[act]gtaaa|tttac[agt]ct"), + regex!("agg[act]taaa|ttta[agt]cct"), + regex!("aggg[acg]aaa|ttt[cgt]ccct"), + regex!("agggt[cgt]aa|tt[acg]accct"), + regex!("agggta[cgt]a|t[acg]taccct"), + regex!("agggtaa[cgt]|[acg]ttaccct"), + ]; + let mut counts = vec![]; + for variant in variants { + let seq = seq_arc.clone(); + let restr = variant.to_string(); + let future = thread::spawn(move || variant.find_iter(&seq).count()); + counts.push((restr, future)); + } + + let substs = vec![ + (regex!("B"), &b"(c|g|t)"[..]), + (regex!("D"), &b"(a|g|t)"[..]), + (regex!("H"), &b"(a|c|t)"[..]), + (regex!("K"), &b"(g|t)"[..]), + (regex!("M"), &b"(a|c)"[..]), + (regex!("N"), &b"(a|c|g|t)"[..]), + (regex!("R"), &b"(a|g)"[..]), + (regex!("S"), &b"(c|g)"[..]), + (regex!("V"), &b"(a|c|g)"[..]), + (regex!("W"), &b"(a|t)"[..]), + (regex!("Y"), &b"(c|t)"[..]), + ]; + let mut seq = seq; + for (re, replacement) in substs { + seq = re.replace_all(&seq, replacement).into_owned(); + } + + for (variant, count) in counts { + println!("{} {}", variant, count.join().unwrap()); + } + println!("\n{}\n{}\n{}", ilen, clen, seq.len()); +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/examples/shootout-regex-dna-cheat.rs cargo-0.26.0/vendor/regex-0.2.10/examples/shootout-regex-dna-cheat.rs --- cargo-0.25.0/vendor/regex-0.2.10/examples/shootout-regex-dna-cheat.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/examples/shootout-regex-dna-cheat.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,88 @@ +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ +// +// contributed by the Rust Project Developers +// contributed by TeXitoi +// contributed by BurntSushi + +// This technically solves the problem posed in the `regex-dna` benchmark, but +// it cheats by combining all of the replacements into a single regex and +// replacing them with a single linear scan. i.e., it re-implements +// `replace_all`. As a result, this is around 25% faster. ---AG + +extern crate regex; + +use std::io::{self, Read}; +use std::sync::Arc; +use std::thread; + +macro_rules! regex { ($re:expr) => { ::regex::Regex::new($re).unwrap() } } + +fn main() { + let mut seq = String::with_capacity(50 * (1 << 20)); + io::stdin().read_to_string(&mut seq).unwrap(); + let ilen = seq.len(); + + seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); + let clen = seq.len(); + let seq_arc = Arc::new(seq.clone()); + + let variants = vec![ + regex!("agggtaaa|tttaccct"), + regex!("[cgt]gggtaaa|tttaccc[acg]"), + regex!("a[act]ggtaaa|tttacc[agt]t"), + regex!("ag[act]gtaaa|tttac[agt]ct"), + regex!("agg[act]taaa|ttta[agt]cct"), + regex!("aggg[acg]aaa|ttt[cgt]ccct"), + regex!("agggt[cgt]aa|tt[acg]accct"), + regex!("agggta[cgt]a|t[acg]taccct"), + regex!("agggtaa[cgt]|[acg]ttaccct"), + ]; + let mut counts = vec![]; + for variant in variants { + let seq = seq_arc.clone(); + let restr = variant.to_string(); + let future = thread::spawn(move || variant.find_iter(&seq).count()); + counts.push((restr, future)); + } + + let substs = vec![ + (b'B', "(c|g|t)"), + (b'D', "(a|g|t)"), + (b'H', "(a|c|t)"), + (b'K', "(g|t)"), + (b'M', "(a|c)"), + (b'N', "(a|c|g|t)"), + (b'R', "(a|g)"), + (b'S', "(c|g)"), + (b'V', "(a|c|g)"), + (b'W', "(a|t)"), + (b'Y', "(c|t)"), + ]; // combined into one regex in `replace_all` + let seq = replace_all(&seq, substs); + + for (variant, count) in counts { + println!("{} {}", variant, count.join().unwrap()); + } + println!("\n{}\n{}\n{}", ilen, clen, seq.len()); +} + +fn replace_all(text: &str, substs: Vec<(u8, &str)>) -> String { + let mut replacements = vec![""; 256]; + let mut alternates = vec![]; + for (re, replacement) in substs { + replacements[re as usize] = replacement; + alternates.push((re as char).to_string()); + } + + let re = regex!(&alternates.join("|")); + let mut new = String::with_capacity(text.len()); + let mut last_match = 0; + for m in re.find_iter(text) { + new.push_str(&text[last_match..m.start()]); + new.push_str(replacements[text.as_bytes()[m.start()] as usize]); + last_match = m.end(); + } + new.push_str(&text[last_match..]); + new +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/examples/shootout-regex-dna-replace.rs cargo-0.26.0/vendor/regex-0.2.10/examples/shootout-regex-dna-replace.rs --- cargo-0.25.0/vendor/regex-0.2.10/examples/shootout-regex-dna-replace.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/examples/shootout-regex-dna-replace.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,19 @@ +extern crate regex; + +use std::io::{self, Read}; + +macro_rules! regex { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re).build().unwrap().into_regex() + }} +} + +fn main() { + let mut seq = String::with_capacity(50 * (1 << 20)); + io::stdin().read_to_string(&mut seq).unwrap(); + let ilen = seq.len(); + + seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); + println!("original: {}, replaced: {}", ilen, seq.len()); +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/examples/shootout-regex-dna.rs cargo-0.26.0/vendor/regex-0.2.10/examples/shootout-regex-dna.rs --- cargo-0.25.0/vendor/regex-0.2.10/examples/shootout-regex-dna.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/examples/shootout-regex-dna.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,66 @@ +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ +// +// contributed by the Rust Project Developers +// contributed by TeXitoi +// contributed by BurntSushi + +extern crate regex; + +use std::io::{self, Read}; +use std::sync::Arc; +use std::thread; + +macro_rules! regex { ($re:expr) => { ::regex::Regex::new($re).unwrap() } } + +fn main() { + let mut seq = String::with_capacity(51 * (1 << 20)); + io::stdin().read_to_string(&mut seq).unwrap(); + let ilen = seq.len(); + + seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); + let clen = seq.len(); + let seq_arc = Arc::new(seq.clone()); + + let variants = vec![ + regex!("agggtaaa|tttaccct"), + regex!("[cgt]gggtaaa|tttaccc[acg]"), + regex!("a[act]ggtaaa|tttacc[agt]t"), + regex!("ag[act]gtaaa|tttac[agt]ct"), + regex!("agg[act]taaa|ttta[agt]cct"), + regex!("aggg[acg]aaa|ttt[cgt]ccct"), + regex!("agggt[cgt]aa|tt[acg]accct"), + regex!("agggta[cgt]a|t[acg]taccct"), + regex!("agggtaa[cgt]|[acg]ttaccct"), + ]; + let mut counts = vec![]; + for variant in variants { + let seq = seq_arc.clone(); + let restr = variant.to_string(); + let future = thread::spawn(move || variant.find_iter(&seq).count()); + counts.push((restr, future)); + } + + let substs = vec![ + (regex!("B"), "(c|g|t)"), + (regex!("D"), "(a|g|t)"), + (regex!("H"), "(a|c|t)"), + (regex!("K"), "(g|t)"), + (regex!("M"), "(a|c)"), + (regex!("N"), "(a|c|g|t)"), + (regex!("R"), "(a|g)"), + (regex!("S"), "(c|g)"), + (regex!("V"), "(a|c|g)"), + (regex!("W"), "(a|t)"), + (regex!("Y"), "(c|t)"), + ]; + let mut seq = seq; + for (re, replacement) in substs { + seq = re.replace_all(&seq, replacement).into_owned(); + } + + for (variant, count) in counts { + println!("{} {}", variant, count.join().unwrap()); + } + println!("\n{}\n{}\n{}", ilen, clen, seq.len()); +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/examples/shootout-regex-dna-single-cheat.rs cargo-0.26.0/vendor/regex-0.2.10/examples/shootout-regex-dna-single-cheat.rs --- cargo-0.25.0/vendor/regex-0.2.10/examples/shootout-regex-dna-single-cheat.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/examples/shootout-regex-dna-single-cheat.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,73 @@ +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ +// +// contributed by the Rust Project Developers +// contributed by TeXitoi +// contributed by BurntSushi + +extern crate regex; + +use std::io::{self, Read}; + +macro_rules! regex { ($re:expr) => { ::regex::Regex::new($re).unwrap() } } + +fn main() { + let mut seq = String::with_capacity(50 * (1 << 20)); + io::stdin().read_to_string(&mut seq).unwrap(); + let ilen = seq.len(); + + seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); + let clen = seq.len(); + + let variants = vec![ + regex!("agggtaaa|tttaccct"), + regex!("[cgt]gggtaaa|tttaccc[acg]"), + regex!("a[act]ggtaaa|tttacc[agt]t"), + regex!("ag[act]gtaaa|tttac[agt]ct"), + regex!("agg[act]taaa|ttta[agt]cct"), + regex!("aggg[acg]aaa|ttt[cgt]ccct"), + regex!("agggt[cgt]aa|tt[acg]accct"), + regex!("agggta[cgt]a|t[acg]taccct"), + regex!("agggtaa[cgt]|[acg]ttaccct"), + ]; + for re in variants { + println!("{} {}", re.to_string(), re.find_iter(&seq).count()); + } + + let substs = vec![ + (b'B', "(c|g|t)"), + (b'D', "(a|g|t)"), + (b'H', "(a|c|t)"), + (b'K', "(g|t)"), + (b'M', "(a|c)"), + (b'N', "(a|c|g|t)"), + (b'R', "(a|g)"), + (b'S', "(c|g)"), + (b'V', "(a|c|g)"), + (b'W', "(a|t)"), + (b'Y', "(c|t)"), + ]; // combined into one regex in `replace_all` + let seq = replace_all(&seq, substs); + + println!("\n{}\n{}\n{}", ilen, clen, seq.len()); +} + +fn replace_all(text: &str, substs: Vec<(u8, &str)>) -> String { + let mut replacements = vec![""; 256]; + let mut alternates = vec![]; + for (re, replacement) in substs { + replacements[re as usize] = replacement; + alternates.push((re as char).to_string()); + } + + let re = regex!(&alternates.join("|")); + let mut new = String::with_capacity(text.len()); + let mut last_match = 0; + for m in re.find_iter(text) { + new.push_str(&text[last_match..m.start()]); + new.push_str(replacements[text.as_bytes()[m.start()] as usize]); + last_match = m.end(); + } + new.push_str(&text[last_match..]); + new +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/examples/shootout-regex-dna-single.rs cargo-0.26.0/vendor/regex-0.2.10/examples/shootout-regex-dna-single.rs --- cargo-0.25.0/vendor/regex-0.2.10/examples/shootout-regex-dna-single.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/examples/shootout-regex-dna-single.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,55 @@ +// The Computer Language Benchmarks Game +// http://benchmarksgame.alioth.debian.org/ +// +// contributed by the Rust Project Developers +// contributed by TeXitoi +// contributed by BurntSushi + +extern crate regex; + +use std::io::{self, Read}; + +macro_rules! regex { ($re:expr) => { ::regex::Regex::new($re).unwrap() } } + +fn main() { + let mut seq = String::with_capacity(50 * (1 << 20)); + io::stdin().read_to_string(&mut seq).unwrap(); + let ilen = seq.len(); + + seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); + let clen = seq.len(); + + let variants = vec![ + regex!("agggtaaa|tttaccct"), + regex!("[cgt]gggtaaa|tttaccc[acg]"), + regex!("a[act]ggtaaa|tttacc[agt]t"), + regex!("ag[act]gtaaa|tttac[agt]ct"), + regex!("agg[act]taaa|ttta[agt]cct"), + regex!("aggg[acg]aaa|ttt[cgt]ccct"), + regex!("agggt[cgt]aa|tt[acg]accct"), + regex!("agggta[cgt]a|t[acg]taccct"), + regex!("agggtaa[cgt]|[acg]ttaccct"), + ]; + for re in variants { + println!("{} {}", re.to_string(), re.find_iter(&seq).count()); + } + + let substs = vec![ + (regex!("B"), "(c|g|t)"), + (regex!("D"), "(a|g|t)"), + (regex!("H"), "(a|c|t)"), + (regex!("K"), "(g|t)"), + (regex!("M"), "(a|c)"), + (regex!("N"), "(a|c|g|t)"), + (regex!("R"), "(a|g)"), + (regex!("S"), "(c|g)"), + (regex!("V"), "(a|c|g)"), + (regex!("W"), "(a|t)"), + (regex!("Y"), "(c|t)"), + ]; + let mut seq = seq; + for (re, replacement) in substs { + seq = re.replace_all(&seq, replacement).into_owned(); + } + println!("\n{}\n{}\n{}", ilen, clen, seq.len()); +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/HACKING.md cargo-0.26.0/vendor/regex-0.2.10/HACKING.md --- cargo-0.25.0/vendor/regex-0.2.10/HACKING.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/HACKING.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,330 @@ +Your friendly guide to hacking and navigating the regex library. + +This guide assumes familiarity with Rust and Cargo, and at least a perusal of +the user facing documentation for this crate. + +If you're looking for background on the implementation in this library, then +you can do no better than Russ Cox's article series on implementing regular +expressions using finite automata: https://swtch.com/~rsc/regexp/ + + +## Architecture overview + +As you probably already know, this library executes regular expressions using +finite automata. In particular, a design goal is to make searching linear +with respect to both the regular expression and the text being searched. +Meeting that design goal on its own is not so hard and can be done with an +implementation of the Pike VM (similar to Thompson's construction, but supports +capturing groups), as described in: https://swtch.com/~rsc/regexp/regexp2.html +--- This library contains such an implementation in src/pikevm.rs. + +Making it fast is harder. One of the key problems with the Pike VM is that it +can be in more than one state at any point in time, and must shuffle capture +positions between them. The Pike VM also spends a lot of time following the +same epsilon transitions over and over again. We can employ one trick to +speed up the Pike VM: extract one or more literal prefixes from the regular +expression and execute specialized code to quickly find matches of those +prefixes in the search text. The Pike VM can then be avoided for most the +search, and instead only executed when a prefix is found. The code to find +prefixes is in the regex-syntax crate (in this repository). The code to search +for literals is in src/literals.rs. When more than one literal prefix is found, +we fall back to an Aho-Corasick DFA using the aho-corasick crate. For one +literal, we use a variant of the Boyer-Moore algorithm. Both Aho-Corasick and +Boyer-Moore use `memchr` when appropriate. The Boyer-Moore variant in this +library also uses elementary frequency analysis to choose the right byte to run +`memchr` with. + +Of course, detecting prefix literals can only take us so far. Not all regular +expressions have literal prefixes. To remedy this, we try another approach +to executing the Pike VM: backtracking, whose implementation can be found in +src/backtrack.rs. One reason why backtracking can be faster is that it avoids +excessive shuffling of capture groups. Of course, backtracking is susceptible +to exponential runtimes, so we keep track of every state we've visited to make +sure we never visit it again. This guarantees linear time execution, but we +pay for it with the memory required to track visited states. Because of the +memory requirement, we only use this engine on small search strings *and* small +regular expressions. + +Lastly, the real workhorse of this library is the "lazy" DFA in src/dfa.rs. +It is distinct from the Pike VM in that the DFA is explicitly represented in +memory and is only ever in one state at a time. It is said to be "lazy" because +the DFA is computed as text is searched, where each byte in the search text +results in at most one new DFA state. It is made fast by caching states. DFAs +are susceptible to exponential state blow up (where the worst case is computing +a new state for every input byte, regardless of what's in the state cache). To +avoid using a lot of memory, the lazy DFA uses a bounded cache. Once the cache +is full, it is wiped and state computation starts over again. If the cache is +wiped too frequently, then the DFA gives up and searching falls back to one of +the aforementioned algorithms. + +All of the above matching engines expose precisely the same matching semantics. +This is indeed tested. (See the section below about testing.) + +The following sub-sections describe the rest of the library and how each of the +matching engines are actually used. + +### Parsing + +Regular expressions are parsed using the regex-syntax crate, which is +maintained in this repository. The regex-syntax crate defines an abstract +syntax and provides very detailed error messages when a parse error is +encountered. Parsing is done in a separate crate so that others may benefit +from its existence, and because it is relatively divorced from the rest of the +regex library. + +The regex-syntax crate also provides sophisticated support for extracting +prefix and suffix literals from regular expressions. + +### Compilation + +The compiler is in src/compile.rs. The input to the compiler is some abstract +syntax for a regular expression and the output is a sequence of opcodes that +matching engines use to execute a search. (One can think of matching engines as +mini virtual machines.) The sequence of opcodes is a particular encoding of a +non-deterministic finite automaton. In particular, the opcodes explicitly rely +on epsilon transitions. + +Consider a simple regular expression like `a|b`. Its compiled form looks like +this: + + 000 Save(0) + 001 Split(2, 3) + 002 'a' (goto: 4) + 003 'b' + 004 Save(1) + 005 Match + +The first column is the instruction pointer and the second column is the +instruction. Save instructions indicate that the current position in the input +should be stored in a captured location. Split instructions represent a binary +branch in the program (i.e., epsilon transitions). The instructions `'a'` and +`'b'` indicate that the literal bytes `'a'` or `'b'` should match. + +In older versions of this library, the compilation looked like this: + + 000 Save(0) + 001 Split(2, 3) + 002 'a' + 003 Jump(5) + 004 'b' + 005 Save(1) + 006 Match + +In particular, empty instructions that merely served to move execution from one +point in the program to another were removed. Instead, every instruction has a +`goto` pointer embedded into it. This resulted in a small performance boost for +the Pike VM, because it was one fewer epsilon transition that it had to follow. + +There exist more instructions and they are defined and documented in +src/prog.rs. + +Compilation has several knobs and a few unfortunately complicated invariants. +Namely, the output of compilation can be one of two types of programs: a +program that executes on Unicode scalar values or a program that executes +on raw bytes. In the former case, the matching engine is responsible for +performing UTF-8 decoding and executing instructions using Unicode codepoints. +In the latter case, the program handles UTF-8 decoding implicitly, so that the +matching engine can execute on raw bytes. All matching engines can execute +either Unicode or byte based programs except for the lazy DFA, which requires +byte based programs. In general, both representations were kept because (1) the +lazy DFA requires byte based programs so that states can be encoded in a memory +efficient manner and (2) the Pike VM benefits greatly from inlining Unicode +character classes into fewer instructions as it results in fewer epsilon +transitions. + +N.B. UTF-8 decoding is built into the compiled program by making use of the +utf8-ranges crate. The compiler in this library factors out common suffixes to +reduce the size of huge character classes (e.g., `\pL`). + +A regrettable consequence of this split in instruction sets is we generally +need to compile two programs; one for NFA execution and one for the lazy DFA. + +In fact, it is worse than that: the lazy DFA is not capable of finding the +starting location of a match in a single scan, and must instead execute a +backwards search after finding the end location. To execute a backwards search, +we must have compiled the regular expression *in reverse*. + +This means that every compilation of a regular expression generally results in +three distinct programs. It would be possible to lazily compile the Unicode +program, since it is never needed if (1) the regular expression uses no word +boundary assertions and (2) the caller never asks for sub-capture locations. + +### Execution + +At the time of writing, there are four matching engines in this library: + +1. The Pike VM (supports captures). +2. Bounded backtracking (supports captures). +3. Literal substring or multi-substring search. +4. Lazy DFA (no support for Unicode word boundary assertions). + +Only the first two matching engines are capable of executing every regular +expression program. They also happen to be the slowest, which means we need +some logic that (1) knows various facts about the regular expression and (2) +knows what the caller wants. Using this information, we can determine which +engine (or engines) to use. + +The logic for choosing which engine to execute is in src/exec.rs and is +documented on the Exec type. Exec values contain regular expression Programs +(defined in src/prog.rs), which contain all the necessary tidbits for actually +executing a regular expression on search text. + +For the most part, the execution logic is straight-forward and follows the +limitations of each engine described above pretty faithfully. The hairiest +part of src/exec.rs by far is the execution of the lazy DFA, since it requires +a forwards and backwards search, and then falls back to either the Pike VM or +backtracking if the caller requested capture locations. + +The Exec type also contains mutable scratch space for each type of matching +engine. This scratch space is used during search (for example, for the lazy +DFA, it contains compiled states that are reused on subsequent searches). + +### Programs + +A regular expression program is essentially a sequence of opcodes produced by +the compiler plus various facts about the regular expression (such as whether +it is anchored, its capture names, etc.). + +### The regex! macro + +The `regex!` macro no longer exists. It was developed in a bygone era as a +compiler plugin during the infancy of the regex crate. Back then, then only +matching engine in the crate was the Pike VM. The `regex!` macro was, itself, +also a Pike VM. The only advantages it offered over the dynamic Pike VM that +was built at runtime were the following: + + 1. Syntax checking was done at compile time. Your Rust program wouldn't + compile if your regex didn't compile. + 2. Reduction of overhead that was proportional to the size of the regex. + For the most part, this overhead consisted of heap allocation, which + was nearly eliminated in the compiler plugin. + +The main takeaway here is that the compiler plugin was a marginally faster +version of a slow regex engine. As the regex crate evolved, it grew other regex +engines (DFA, bounded backtracker) and sophisticated literal optimizations. +The regex macro didn't keep pace, and it therefore became (dramatically) slower +than the dynamic engines. The only reason left to use it was for the compile +time guarantee that your regex is correct. Fortunately, Clippy (the Rust lint +tool) has a lint that checks your regular expression validity, which mostly +replaces that use case. + +Additionally, the regex compiler plugin stopped receiving maintenance. Nobody +complained. At that point, it seemed prudent to just remove it. + +Will a compiler plugin be brought back? The future is murky, but there is +definitely an opportunity there to build something that is faster than the +dynamic engines in some cases. But it will be challenging! As of now, there +are no plans to work on this. + + +## Testing + +A key aspect of any mature regex library is its test suite. A subset of the +tests in this library come from Glenn Fowler's AT&T test suite (its online +presence seems gone at the time of writing). The source of the test suite is +located in src/testdata. The scripts/regex-match-tests.py takes the test suite +in src/testdata and generates tests/matches.rs. + +There are also many other manually crafted tests and regression tests in +tests/tests.rs. Some of these tests were taken from RE2. + +The biggest source of complexity in the tests is related to answering this +question: how can we reuse the tests to check all of our matching engines? One +approach would have been to encode every test into some kind of format (like +the AT&T test suite) and code generate tests for each matching engine. The +approach we use in this library is to create a Cargo.toml entry point for each +matching engine we want to test. The entry points are: + +* `tests/test_default.rs` - tests `Regex::new` +* `tests/test_default_bytes.rs` - tests `bytes::Regex::new` +* `tests/test_nfa.rs` - tests `Regex::new`, forced to use the NFA + algorithm on every regex. +* `tests/test_nfa_bytes.rs` - tests `Regex::new`, forced to use the NFA + algorithm on every regex and use *arbitrary* byte based programs. +* `tests/test_nfa_utf8bytes.rs` - tests `Regex::new`, forced to use the NFA + algorithm on every regex and use *UTF-8* byte based programs. +* `tests/test_backtrack.rs` - tests `Regex::new`, forced to use + backtracking on every regex. +* `tests/test_backtrack_bytes.rs` - tests `Regex::new`, forced to use + backtracking on every regex and use *arbitrary* byte based programs. +* `tests/test_backtrack_utf8bytes.rs` - tests `Regex::new`, forced to use + backtracking on every regex and use *UTF-8* byte based programs. + +The lazy DFA and pure literal engines are absent from this list because +they cannot be used on every regular expression. Instead, we rely on +`tests/test_dynamic.rs` to test the lazy DFA and literal engines when possible. + +Since the tests are repeated several times, and because `cargo test` runs all +entry points, it can take a while to compile everything. To reduce compile +times slightly, try using `cargo test --test default`, which will only use the +`tests/test_default.rs` entry point. + + +## Benchmarking + +The benchmarking in this crate is made up of many micro-benchmarks. Currently, +there are two primary sets of benchmarks: the benchmarks that were adopted +at this library's inception (in `bench/src/misc.rs`) and a newer set of +benchmarks meant to test various optimizations. Specifically, the latter set +contain some analysis and are in `bench/src/sherlock.rs`. Also, the latter +set are all executed on the same lengthy input whereas the former benchmarks +are executed on strings of varying length. + +There is also a smattering of benchmarks for parsing and compilation. + +Benchmarks are in a separate crate so that its dependencies can be managed +separately from the main regex crate. + +Benchmarking follows a similarly wonky setup as tests. There are multiple entry +points: + +* `bench_rust.rs` - benchmarks `Regex::new` +* `bench_rust_bytes.rs` benchmarks `bytes::Regex::new` +* `bench_pcre.rs` - benchmarks PCRE +* `bench_onig.rs` - benchmarks Oniguruma + +The PCRE and Oniguruma benchmarks exist as a comparison point to a mature +regular expression library. In general, this regex library compares favorably +(there are even a few benchmarks that PCRE simply runs too slowly on or +outright can't execute at all). I would love to add other regular expression +library benchmarks (especially RE2). + +If you're hacking on one of the matching engines and just want to see +benchmarks, then all you need to run is: + + $ ./bench/run rust + +If you want to compare your results with older benchmarks, then try: + + $ ./bench/run rust | tee old + $ ... make it faster + $ ./bench/run rust | tee new + $ cargo benchcmp old new --improvements + +The `cargo-benchcmp` utility is available here: +https://github.com/BurntSushi/cargo-benchcmp + +The `./bench/run` utility can run benchmarks for PCRE and Oniguruma too. See +`./bench/bench --help`. + +## Dev Docs + +When digging your teeth into the codebase for the first time, the +crate documentation can be a great resource. By default `rustdoc` +will strip out all documentation of private crate members in an +effort to help consumers of the crate focus on the *interface* +without having to concern themselves with the *implementation*. +Normally this is a great thing, but if you want to start hacking +on regex internals it is not what you want. Many of the private members +of this crate are well documented with rustdoc style comments, and +it would be a shame to miss out on the opportunity that presents. +You can generate the private docs with: + +``` +$ rustdoc --crate-name docs src/lib.rs -o target/doc -L target/debug/deps --no-defaults --passes collapse-docs --passes unindent-comments +``` + +Then just point your browser at `target/doc/regex/index.html`. + +See https://github.com/rust-lang/rust/issues/15347 for more info +about generating developer docs for internal use. diff -Nru cargo-0.25.0/vendor/regex-0.2.10/LICENSE-APACHE cargo-0.26.0/vendor/regex-0.2.10/LICENSE-APACHE --- cargo-0.25.0/vendor/regex-0.2.10/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/regex-0.2.10/LICENSE-MIT cargo-0.26.0/vendor/regex-0.2.10/LICENSE-MIT --- cargo-0.25.0/vendor/regex-0.2.10/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/regex-0.2.10/PERFORMANCE.md cargo-0.26.0/vendor/regex-0.2.10/PERFORMANCE.md --- cargo-0.25.0/vendor/regex-0.2.10/PERFORMANCE.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/PERFORMANCE.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,279 @@ +Your friendly guide to understanding the performance characteristics of this +crate. + +This guide assumes some familiarity with the public API of this crate, which +can be found here: https://docs.rs/regex + +## Theory vs. Practice + +One of the design goals of this crate is to provide worst case linear time +behavior with respect to the text searched using finite state automata. This +means that, *in theory*, the performance of this crate is much better than most +regex implementations, which typically use backtracking which has worst case +exponential time. + +For example, try opening a Python interpreter and typing this: + + >>> import re + >>> re.search('(a*)*c', 'a' * 30).span() + +I'll wait. + +At some point, you'll figure out that it won't terminate any time soon. ^C it. + +The promise of this crate is that *this pathological behavior can't happen*. + +With that said, just because we have protected ourselves against worst case +exponential behavior doesn't mean we are immune from large constant factors +or places where the current regex engine isn't quite optimal. This guide will +detail those cases and provide guidance on how to avoid them, among other +bits of general advice. + +## Thou Shalt Not Compile Regular Expressions In A Loop + +**Advice**: Use `lazy_static` to amortize the cost of `Regex` compilation. + +Don't do it unless you really don't mind paying for it. Compiling a regular +expression in this crate is quite expensive. It is conceivable that it may get +faster some day, but I wouldn't hold out hope for, say, an order of magnitude +improvement. In particular, compilation can take any where from a few dozen +microseconds to a few dozen milliseconds. Yes, milliseconds. Unicode character +classes, in particular, have the largest impact on compilation performance. At +the time of writing, for example, `\pL{100}` takes around 44ms to compile. This +is because `\pL` corresponds to every letter in Unicode and compilation must +turn it into a proper automaton that decodes a subset of UTF-8 which +corresponds to those letters. Compilation also spends some cycles shrinking the +size of the automaton. + +This means that in order to realize efficient regex matching, one must +*amortize the cost of compilation*. Trivially, if a call to `is_match` is +inside a loop, then make sure your call to `Regex::new` is *outside* that loop. + +In many programming languages, regular expressions can be conveniently defined +and compiled in a global scope, and code can reach out and use them as if +they were global static variables. In Rust, there is really no concept of +life-before-main, and therefore, one cannot utter this: + + static MY_REGEX: Regex = Regex::new("...").unwrap(); + +Unfortunately, this would seem to imply that one must pass `Regex` objects +around to everywhere they are used, which can be especially painful depending +on how your program is structured. Thankfully, the +[`lazy_static`](https://crates.io/crates/lazy_static) +crate provides an answer that works well: + + #[macro_use] extern crate lazy_static; + extern crate regex; + + use regex::Regex; + + fn some_helper_function(text: &str) -> bool { + lazy_static! { + static ref MY_REGEX: Regex = Regex::new("...").unwrap(); + } + MY_REGEX.is_match(text) + } + +In other words, the `lazy_static!` macro enables us to define a `Regex` *as if* +it were a global static value. What is actually happening under the covers is +that the code inside the macro (i.e., `Regex::new(...)`) is run on *first use* +of `MY_REGEX` via a `Deref` impl. The implementation is admittedly magical, but +it's self contained and everything works exactly as you expect. In particular, +`MY_REGEX` can be used from multiple threads without wrapping it in an `Arc` or +a `Mutex`. On that note... + +## Using a regex from multiple threads + +**Advice**: The performance impact from using a `Regex` from multiple threads +is likely negligible. If necessary, clone the `Regex` so that each thread gets +its own copy. Cloning a regex does not incur any additional memory overhead +than what would be used by using a `Regex` from multiple threads +simultaneously. *Its only cost is ergonomics.* + +It is supported and encouraged to define your regexes using `lazy_static!` as +if they were global static values, and then use them to search text from +multiple threads simultaneously. + +One might imagine that this is possible because a `Regex` represents a +*compiled* program, so that any allocation or mutation is already done, and is +therefore read-only. Unfortunately, this is not true. Each type of search +strategy in this crate requires some kind of mutable scratch space to use +*during search*. For example, when executing a DFA, its states are computed +lazily and reused on subsequent searches. Those states go into that mutable +scratch space. + +The mutable scratch space is an implementation detail, and in general, its +mutation should not be observable from users of this crate. Therefore, it uses +interior mutability. This implies that `Regex` can either only be used from one +thread, or it must do some sort of synchronization. Either choice is +reasonable, but this crate chooses the latter, in particular because it is +ergonomic and makes use with `lazy_static!` straight forward. + +Synchronization implies *some* amount of overhead. When a `Regex` is used from +a single thread, this overhead is negligible. When a `Regex` is used from +multiple threads simultaneously, it is possible for the overhead of +synchronization from contention to impact performance. The specific cases where +contention may happen is if you are calling any of these methods repeatedly +from multiple threads simultaneously: + +* shortest_match +* is_match +* find +* captures + +In particular, every invocation of one of these methods must synchronize with +other threads to retrieve its mutable scratch space before searching can start. +If, however, you are using one of these methods: + +* find_iter +* captures_iter + +Then you may not suffer from contention since the cost of synchronization is +amortized on *construction of the iterator*. That is, the mutable scratch space +is obtained when the iterator is created and retained throughout its lifetime. + +## Only ask for what you need + +**Advice**: Prefer in this order: `is_match`, `find`, `captures`. + +There are three primary search methods on a `Regex`: + +* is_match +* find +* captures + +In general, these are ordered from fastest to slowest. + +`is_match` is fastest because it doesn't actually need to find the start or the +end of the leftmost-first match. It can quit immediately after it knows there +is a match. For example, given the regex `a+` and the haystack, `aaaaa`, the +search will quit after examing the first byte. + +In constrast, `find` must return both the start and end location of the +leftmost-first match. It can use the DFA matcher for this, but must run it +forwards once to find the end of the match *and then run it backwards* to find +the start of the match. The two scans and the cost of finding the real end of +the leftmost-first match make this more expensive than `is_match`. + +`captures` is the most expensive of them all because it must do what `find` +does, and then run either the bounded backtracker or the Pike VM to fill in the +capture group locations. Both of these are simulations of an NFA, which must +spend a lot of time shuffling states around. The DFA limits the performance hit +somewhat by restricting the amount of text that must be searched via an NFA +simulation. + +One other method not mentioned is `shortest_match`. This method has precisely +the same performance characteristics as `is_match`, except it will return the +end location of when it discovered a match. For example, given the regex `a+` +and the haystack `aaaaa`, `shortest_match` may return `1` as opposed to `5`, +the latter of which being the correct end location of the leftmost-first match. + +## Literals in your regex may make it faster + +**Advice**: Literals can reduce the work that the regex engine needs to do. Use +them if you can, especially as prefixes. + +In particular, if your regex starts with a prefix literal, the prefix is +quickly searched before entering the (much slower) regex engine. For example, +given the regex `foo\w+`, the literal `foo` will be searched for using +Boyer-Moore. If there's no match, then no regex engine is ever used. Only when +there's a match is the regex engine invoked at the location of the match, which +effectively permits the regex engine to skip large portions of a haystack. +If a regex is comprised entirely of literals (possibly more than one), then +it's possible that the regex engine can be avoided entirely even when there's a +match. + +When one literal is found, Boyer-Moore is used. When multiple literals are +found, then an optimized version of Aho-Corasick is used. + +This optimization is in particular extended quite a bit in this crate. Here are +a few examples of regexes that get literal prefixes detected: + +* `(foo|bar)` detects `foo` and `bar` +* `(a|b)c` detects `ac` and `bc` +* `[ab]foo[yz]` detects `afooy`, `afooz`, `bfooy` and `bfooz` +* `a?b` detects `a` and `b` +* `a*b` detects `a` and `b` +* `(ab){3,6}` detects `ababab` + +Literals in anchored regexes can also be used for detecting non-matches very +quickly. For example, `^foo\w+` and `\w+foo$` may be able to detect a non-match +just by examing the first (or last) three bytes of the haystack. + +## Unicode word boundaries may prevent the DFA from being used + +**Advice**: In most cases, `\b` should work well. If not, use `(?-u:\b)` +instead of `\b` if you care about consistent performance more than correctness. + +It's a sad state of the current implementation. At the moment, the DFA will try +to interpret Unicode word boundaries as if they were ASCII word boundaries. +If the DFA comes across any non-ASCII byte, it will quit and fall back to an +alternative matching engine that can handle Unicode word boundaries correctly. +The alternate matching engine is generally quite a bit slower (perhaps by an +order of magnitude). If necessary, this can be ameliorated in two ways. + +The first way is to add some number of literal prefixes to your regular +expression. Even though the DFA may not be used, specialized routines will +still kick in to find prefix literals quickly, which limits how much work the +NFA simulation will need to do. + +The second way is to give up on Unicode and use an ASCII word boundary instead. +One can use an ASCII word boundary by disabling Unicode support. That is, +instead of using `\b`, use `(?-u:\b)`. Namely, given the regex `\b.+\b`, it +can be transformed into a regex that uses the DFA with `(?-u:\b).+(?-u:\b)`. It +is important to limit the scope of disabling the `u` flag, since it might lead +to a syntax error if the regex could match arbitrary bytes. For example, if one +wrote `(?-u)\b.+\b`, then a syntax error would be returned because `.` matches +any *byte* when the Unicode flag is disabled. + +The second way isn't appreciably different than just using a Unicode word +boundary in the first place, since the DFA will speculatively interpret it as +an ASCII word boundary anyway. The key difference is that if an ASCII word +boundary is used explicitly, then the DFA won't quit in the presence of +non-ASCII UTF-8 bytes. This results in giving up correctness in exchange for +more consistent performance. + +N.B. When using `bytes::Regex`, Unicode support is disabled by default, so one +can simply write `\b` to get an ASCII word boundary. + +## Excessive counting can lead to exponential state blow up in the DFA + +**Advice**: Don't write regexes that cause DFA state blow up if you care about +match performance. + +Wait, didn't I say that this crate guards against exponential worst cases? +Well, it turns out that the process of converting an NFA to a DFA can lead to +an exponential blow up in the number of states. This crate specifically guards +against exponential blow up by doing two things: + +1. The DFA is computed lazily. That is, a state in the DFA only exists in + memory if it is visited. In particular, the lazy DFA guarantees that *at + most* one state is created for every byte of input. This, on its own, + guarantees linear time complexity. +2. Of course, creating a new state for *every* byte of input means that search + will go incredibly slow because of very large constant factors. On top of + that, creating a state for every byte in a large haystack could result in + exorbitant memory usage. To ameliorate this, the DFA bounds the number of + states it can store. Once it reaches its limit, it flushes its cache. This + prevents reuse of states that it already computed. If the cache is flushed + too frequently, then the DFA will give up and execution will fall back to + one of the NFA simulations. + +In effect, this crate will detect exponential state blow up and fall back to +a search routine with fixed memory requirements. This does, however, mean that +searching will be much slower than one might expect. Regexes that rely on +counting in particular are strong aggravators of this behavior. For example, +matching `[01]*1[01]{20}$` against a random sequence of `0`s and `1`s. + +In the future, it may be possible to increase the bound that the DFA uses, +which would allow the caller to choose how much memory they're willing to +spend. + +## Resist the temptation to "optimize" regexes + +**Advice**: This ain't a backtracking engine. + +An entire book was written on how to optimize Perl-style regular expressions. +Most of those techniques are not applicable for this library. For example, +there is no problem with using non-greedy matching or having lots of +alternations in your regex. diff -Nru cargo-0.25.0/vendor/regex-0.2.10/README.md cargo-0.26.0/vendor/regex-0.2.10/README.md --- cargo-0.25.0/vendor/regex-0.2.10/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,222 @@ +regex +===== +A Rust library for parsing, compiling, and executing regular expressions. Its +syntax is similar to Perl-style regular expressions, but lacks a few features +like look around and backreferences. In exchange, all searches execute in +linear time with respect to the size of the regular expression and search text. +Much of the syntax and implementation is inspired +by [RE2](https://github.com/google/re2). + +[![Build Status](https://travis-ci.org/rust-lang/regex.svg?branch=master)](https://travis-ci.org/rust-lang/regex) +[![Build status](https://ci.appveyor.com/api/projects/status/github/rust-lang/regex?svg=true)](https://ci.appveyor.com/project/rust-lang-libs/regex) +[![Coverage Status](https://coveralls.io/repos/github/rust-lang/regex/badge.svg?branch=master)](https://coveralls.io/github/rust-lang/regex?branch=master) +[![](http://meritbadge.herokuapp.com/regex)](https://crates.io/crates/regex) + +### Documentation + +[Module documentation with examples](https://docs.rs/regex). +The module documentation also includes a comprehensive description of the +syntax supported. + +Documentation with examples for the various matching functions and iterators +can be found on the +[`Regex` type](https://docs.rs/regex/*/regex/struct.Regex.html). + +### Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +regex = "0.2" +``` + +and this to your crate root: + +```rust +extern crate regex; +``` + +Here's a simple example that matches a date in YYYY-MM-DD format and prints the +year, month and day: + +```rust +extern crate regex; + +use regex::Regex; + +fn main() { + let re = Regex::new(r"(?x) +(?P\d{4}) # the year +- +(?P\d{2}) # the month +- +(?P\d{2}) # the day +").unwrap(); + let caps = re.captures("2010-03-14").unwrap(); + + assert_eq!("2010", &caps["year"]); + assert_eq!("03", &caps["month"]); + assert_eq!("14", &caps["day"]); +} +``` + +If you have lots of dates in text that you'd like to iterate over, then it's +easy to adapt the above example with an iterator: + +```rust +extern crate regex; + +use regex::Regex; + +const TO_SEARCH: &'static str = " +On 2010-03-14, foo happened. On 2014-10-14, bar happened. +"; + +fn main() { + let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap(); + + for caps in re.captures_iter(TO_SEARCH) { + // Note that all of the unwraps are actually OK for this regex + // because the only way for the regex to match is if all of the + // capture groups match. This is not true in general though! + println!("year: {}, month: {}, day: {}", + caps.get(1).unwrap().as_str(), + caps.get(2).unwrap().as_str(), + caps.get(3).unwrap().as_str()); + } +} +``` + +This example outputs: + +``` +year: 2010, month: 03, day: 14 +year: 2014, month: 10, day: 14 +``` + +### Usage: Avoid compiling the same regex in a loop + +It is an anti-pattern to compile the same regular expression in a loop since +compilation is typically expensive. (It takes anywhere from a few microseconds +to a few **milliseconds** depending on the size of the regex.) Not only is +compilation itself expensive, but this also prevents optimizations that reuse +allocations internally to the matching engines. + +In Rust, it can sometimes be a pain to pass regular expressions around if +they're used from inside a helper function. Instead, we recommend using the +[`lazy_static`](https://crates.io/crates/lazy_static) crate to ensure that +regular expressions are compiled exactly once. + +For example: + +```rust +#[macro_use] extern crate lazy_static; +extern crate regex; + +use regex::Regex; + +fn some_helper_function(text: &str) -> bool { + lazy_static! { + static ref RE: Regex = Regex::new("...").unwrap(); + } + RE.is_match(text) +} +``` + +Specifically, in this example, the regex will be compiled when it is used for +the first time. On subsequent uses, it will reuse the previous compilation. + +### Usage: match regular expressions on `&[u8]` + +The main API of this crate (`regex::Regex`) requires the caller to pass a +`&str` for searching. In Rust, an `&str` is required to be valid UTF-8, which +means the main API can't be used for searching arbitrary bytes. + +To match on arbitrary bytes, use the `regex::bytes::Regex` API. The API +is identical to the main API, except that it takes an `&[u8]` to search +on instead of an `&str`. By default, `.` will match any *byte* using +`regex::bytes::Regex`, while `.` will match any *UTF-8 encoded Unicode scalar +value* using the main API. + +This example shows how to find all null-terminated strings in a slice of bytes: + +```rust +use regex::bytes::Regex; + +let re = Regex::new(r"(?P[^\x00]+)\x00").unwrap(); +let text = b"foo\x00bar\x00baz\x00"; + +// Extract all of the strings without the null terminator from each match. +// The unwrap is OK here since a match requires the `cstr` capture to match. +let cstrs: Vec<&[u8]> = + re.captures_iter(text) + .map(|c| c.name("cstr").unwrap().as_bytes()) + .collect(); +assert_eq!(vec![&b"foo"[..], &b"bar"[..], &b"baz"[..]], cstrs); +``` + +Notice here that the `[^\x00]+` will match any *byte* except for `NUL`. When +using the main API, `[^\x00]+` would instead match any valid UTF-8 sequence +except for `NUL`. + +### Usage: match multiple regular expressions simultaneously + +This demonstrates how to use a `RegexSet` to match multiple (possibly +overlapping) regular expressions in a single scan of the search text: + +```rust +use regex::RegexSet; + +let set = RegexSet::new(&[ + r"\w+", + r"\d+", + r"\pL+", + r"foo", + r"bar", + r"barfoo", + r"foobar", +]).unwrap(); + +// Iterate over and collect all of the matches. +let matches: Vec<_> = set.matches("foobar").into_iter().collect(); +assert_eq!(matches, vec![0, 2, 3, 4, 6]); + +// You can also test whether a particular regex matched: +let matches = set.matches("foobar"); +assert!(!matches.matched(5)); +assert!(matches.matched(6)); +``` + +### Usage: enable SIMD optimizations + +This crate provides an `unstable` feature that can only be enabled on nightly +Rust. When this feature is enabled, the regex crate will use SIMD optimizations +if your CPU supports them. No additional compile time flags are required; the +regex crate will detect your CPU support at runtime. + +When `std::arch` becomes stable, then these optimizations will be enabled +automatically. + + +### Usage: a regular expression parser + +This repository contains a crate that provides a well tested regular expression +parser, abstract syntax and a high-level intermediate representation for +convenient analysis. It provides no facilities for compilation or execution. +This may be useful if you're implementing your own regex engine or otherwise +need to do analysis on the syntax of a regular expression. It is otherwise not +recommended for general use. + +[Documentation `regex-syntax`.](https://docs.rs/regex-syntax) + +# License + +This project is 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. diff -Nru cargo-0.25.0/vendor/regex-0.2.10/scripts/frequencies.py cargo-0.26.0/vendor/regex-0.2.10/scripts/frequencies.py --- cargo-0.25.0/vendor/regex-0.2.10/scripts/frequencies.py 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/scripts/frequencies.py 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,82 @@ +#!/usr/bin/env python + +# This does simple normalized frequency analysis on UTF-8 encoded text. The +# result of the analysis is translated to a ranked list, where every byte is +# assigned a rank. This list is written to src/freqs.rs. +# +# Currently, the frequencies are generated from the following corpuses: +# +# * The CIA world fact book +# * The source code of rustc +# * Septuaginta + +from __future__ import absolute_import, division, print_function + +import argparse +from collections import Counter +import sys + +preamble = '''// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// NOTE: The following code was generated by "scripts/frequencies.py", do not +// edit directly +''' + + +def eprint(*args, **kwargs): + kwargs['file'] = sys.stderr + print(*args, **kwargs) + + +def main(): + p = argparse.ArgumentParser() + p.add_argument('corpus', metavar='FILE', nargs='+') + args = p.parse_args() + + # Get frequency counts of each byte. + freqs = Counter() + for i in range(0, 256): + freqs[i] = 0 + + eprint('reading entire corpus into memory') + corpus = [] + for fpath in args.corpus: + corpus.append(open(fpath, 'rb').read()) + + eprint('computing byte frequencies') + for c in corpus: + for byte in c: + freqs[byte] += 1.0 / float(len(c)) + + eprint('writing Rust code') + # Get the rank of each byte. A lower rank => lower relative frequency. + rank = [0] * 256 + for i, (byte, _) in enumerate(freqs.most_common()): + # print(byte) + rank[byte] = 255 - i + + # Forcefully set the highest rank possible for bytes that start multi-byte + # UTF-8 sequences. The idea here is that a continuation byte will be more + # discerning in a homogenous haystack. + for byte in range(0xC0, 0xFF + 1): + rank[byte] = 255 + + # Now write Rust. + olines = ['pub const BYTE_FREQUENCIES: [u8; 256] = ['] + for byte in range(256): + olines.append(' %3d, // %r' % (rank[byte], chr(byte))) + olines.append('];') + + print(preamble) + print('\n'.join(olines)) + +if __name__ == '__main__': + main() diff -Nru cargo-0.25.0/vendor/regex-0.2.10/scripts/regex-match-tests.py cargo-0.26.0/vendor/regex-0.2.10/scripts/regex-match-tests.py --- cargo-0.25.0/vendor/regex-0.2.10/scripts/regex-match-tests.py 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/scripts/regex-match-tests.py 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,107 @@ +#!/usr/bin/env python2 + +# Copyright 2014 The Rust Project Developers. See the COPYRIGHT +# file at the top-level directory of this distribution and at +# http://rust-lang.org/COPYRIGHT. +# +# Licensed under the Apache License, Version 2.0 or the MIT license +# , at your +# option. This file may not be copied, modified, or distributed +# except according to those terms. + +from __future__ import absolute_import, division, print_function +import argparse +import datetime +import os.path as path + + +def print_tests(tests): + print('\n'.join([test_tostr(t) for t in tests])) + + +def read_tests(f): + basename, _ = path.splitext(path.basename(f)) + tests = [] + for lineno, line in enumerate(open(f), 1): + fields = filter(None, map(str.strip, line.split('\t'))) + if not (4 <= len(fields) <= 5) \ + or 'E' not in fields[0] or fields[0][0] == '#': + continue + + opts, pat, text, sgroups = fields[0:4] + groups = [] # groups as integer ranges + if sgroups == 'NOMATCH': + groups = [None] + elif ',' in sgroups: + noparen = map(lambda s: s.strip('()'), sgroups.split(')(')) + for g in noparen: + s, e = map(str.strip, g.split(',')) + if s == '?' and e == '?': + groups.append(None) + else: + groups.append((int(s), int(e))) + else: + # This skips tests that should result in an error. + # There aren't many, so I think we can just capture those + # manually. Possibly fix this in future. + continue + + if pat == 'SAME': + pat = tests[-1][1] + if '$' in opts: + pat = pat.decode('string_escape') + text = text.decode('string_escape') + if 'i' in opts: + pat = '(?i)%s' % pat + + name = '%s_%d' % (basename, lineno) + tests.append((name, pat, text, groups)) + return tests + + +def test_tostr(t): + lineno, pat, text, groups = t + options = map(group_tostr, groups) + return 'mat!(match_%s, r"%s", r"%s", %s);' \ + % (lineno, pat, '' if text == "NULL" else text, ', '.join(options)) + + +def group_tostr(g): + if g is None: + return 'None' + else: + return 'Some((%d, %d))' % (g[0], g[1]) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description='Generate match tests from an AT&T POSIX test file.') + aa = parser.add_argument + aa('files', nargs='+', + help='A list of dat AT&T POSIX test files. See src/testdata') + args = parser.parse_args() + + tests = [] + for f in args.files: + tests += read_tests(f) + + tpl = '''// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// DO NOT EDIT. Automatically generated by 'scripts/regex-match-tests.py' +// on {date}. +''' + print(tpl.format(date=str(datetime.datetime.now()))) + + for f in args.files: + print('// Tests from %s' % path.basename(f)) + print_tests(read_tests(f)) + print('') diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/backtrack.rs cargo-0.26.0/vendor/regex-0.2.10/src/backtrack.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/backtrack.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/backtrack.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,302 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// This is the backtracking matching engine. It has the same exact capability +// as the full NFA simulation, except it is artificially restricted to small +// regexes on small inputs because of its memory requirements. +// +// In particular, this is a *bounded* backtracking engine. It retains worst +// case linear time by keeping track of the states that it has visited (using a +// bitmap). Namely, once a state is visited, it is never visited again. Since a +// state is keyed by `(instruction index, input index)`, we have that its time +// complexity is `O(mn)` (i.e., linear in the size of the search text). +// +// The backtracking engine can beat out the NFA simulation on small +// regexes/inputs because it doesn't have to keep track of multiple copies of +// the capture groups. In benchmarks, the backtracking engine is roughly twice +// as fast as the full NFA simulation. Note though that its performance doesn't +// scale, even if you're willing to live with the memory requirements. Namely, +// the bitset has to be zeroed on each execution, which becomes quite expensive +// on large bitsets. + +use exec::ProgramCache; +use input::{Input, InputAt}; +use prog::{Program, InstPtr}; +use re_trait::Slot; + +type Bits = u32; + +const BIT_SIZE: usize = 32; +const MAX_SIZE_BYTES: usize = 256 * (1 << 10); // 256 KB + +/// Returns true iff the given regex and input should be executed by this +/// engine with reasonable memory usage. +pub fn should_exec(num_insts: usize, text_len: usize) -> bool { + // Total memory usage in bytes is determined by: + // + // ((len(insts) * (len(input) + 1) + bits - 1) / bits) * (size_of(u32)) + // + // The actual limit picked is pretty much a heuristic. + // See: https://github.com/rust-lang/regex/issues/215 + let size = ((num_insts * (text_len + 1) + BIT_SIZE - 1) / BIT_SIZE) * 4; + size <= MAX_SIZE_BYTES +} + +/// A backtracking matching engine. +#[derive(Debug)] +pub struct Bounded<'a, 'm, 'r, 's, I> { + prog: &'r Program, + input: I, + matches: &'m mut [bool], + slots: &'s mut [Slot], + m: &'a mut Cache, +} + +/// Shared cached state between multiple invocations of a backtracking engine +/// in the same thread. +#[derive(Clone, Debug)] +pub struct Cache { + jobs: Vec, + visited: Vec, +} + +impl Cache { + /// Create new empty cache for the backtracking engine. + pub fn new(_prog: &Program) -> Self { + Cache { jobs: vec![], visited: vec![] } + } +} + +/// A job is an explicit unit of stack space in the backtracking engine. +/// +/// The "normal" representation is a single state transition, which corresponds +/// to an NFA state and a character in the input. However, the backtracking +/// engine must keep track of old capture group values. We use the explicit +/// stack to do it. +#[derive(Clone, Copy, Debug)] +enum Job { + Inst { ip: InstPtr, at: InputAt }, + SaveRestore { slot: usize, old_pos: Option }, +} + +impl<'a, 'm, 'r, 's, I: Input> Bounded<'a, 'm, 'r, 's, I> { + /// Execute the backtracking matching engine. + /// + /// If there's a match, `exec` returns `true` and populates the given + /// captures accordingly. + pub fn exec( + prog: &'r Program, + cache: &ProgramCache, + matches: &'m mut [bool], + slots: &'s mut [Slot], + input: I, + start: usize, + ) -> bool { + let mut cache = cache.borrow_mut(); + let cache = &mut cache.backtrack; + let start = input.at(start); + let mut b = Bounded { + prog: prog, + input: input, + matches: matches, + slots: slots, + m: cache, + }; + b.exec_(start) + } + + /// Clears the cache such that the backtracking engine can be executed + /// on some input of fixed length. + fn clear(&mut self) { + // Reset the job memory so that we start fresh. + self.m.jobs.clear(); + + // Now we need to clear the bit state set. + // We do this by figuring out how much space we need to keep track + // of the states we've visited. + // Then we reset all existing allocated space to 0. + // Finally, we request more space if we need it. + // + // This is all a little circuitous, but doing this unsafely + // doesn't seem to have a measurable impact on performance. + // (Probably because backtracking is limited to such small + // inputs/regexes in the first place.) + let visited_len = + (self.prog.len() * (self.input.len() + 1) + BIT_SIZE - 1) + / + BIT_SIZE; + self.m.visited.truncate(visited_len); + for v in &mut self.m.visited { + *v = 0; + } + if visited_len > self.m.visited.len() { + let len = self.m.visited.len(); + self.m.visited.reserve_exact(visited_len - len); + for _ in 0..(visited_len - len) { + self.m.visited.push(0); + } + } + } + + /// Start backtracking at the given position in the input, but also look + /// for literal prefixes. + fn exec_(&mut self, mut at: InputAt) -> bool { + self.clear(); + // If this is an anchored regex at the beginning of the input, then + // we're either already done or we only need to try backtracking once. + if self.prog.is_anchored_start { + return if !at.is_start() { + false + } else { + self.backtrack(at) + }; + } + let mut matched = false; + loop { + if !self.prog.prefixes.is_empty() { + at = match self.input.prefix_at(&self.prog.prefixes, at) { + None => break, + Some(at) => at, + }; + } + matched = self.backtrack(at) || matched; + if matched && self.prog.matches.len() == 1 { + return true; + } + if at.is_end() { + break; + } + at = self.input.at(at.next_pos()); + } + matched + } + + /// The main backtracking loop starting at the given input position. + fn backtrack(&mut self, start: InputAt) -> bool { + // N.B. We use an explicit stack to avoid recursion. + // To avoid excessive pushing and popping, most transitions are handled + // in the `step` helper function, which only pushes to the stack when + // there's a capture or a branch. + let mut matched = false; + self.m.jobs.push(Job::Inst { ip: 0, at: start }); + while let Some(job) = self.m.jobs.pop() { + match job { + Job::Inst { ip, at } => { + if self.step(ip, at) { + // Only quit if we're matching one regex. + // If we're matching a regex set, then mush on and + // try to find other matches (if we want them). + if self.prog.matches.len() == 1 { + return true; + } + matched = true; + } + } + Job::SaveRestore { slot, old_pos } => { + if slot < self.slots.len() { + self.slots[slot] = old_pos; + } + } + } + } + matched + } + + fn step(&mut self, mut ip: InstPtr, mut at: InputAt) -> bool { + use prog::Inst::*; + loop { + // This loop is an optimization to avoid constantly pushing/popping + // from the stack. Namely, if we're pushing a job only to run it + // next, avoid the push and just mutate `ip` (and possibly `at`) + // in place. + if self.has_visited(ip, at) { + return false; + } + match self.prog[ip] { + Match(slot) => { + if slot < self.matches.len() { + self.matches[slot] = true; + } + return true; + } + Save(ref inst) => { + if let Some(&old_pos) = self.slots.get(inst.slot) { + // If this path doesn't work out, then we save the old + // capture index (if one exists) in an alternate + // job. If the next path fails, then the alternate + // job is popped and the old capture index is restored. + self.m.jobs.push(Job::SaveRestore { + slot: inst.slot, + old_pos: old_pos, + }); + self.slots[inst.slot] = Some(at.pos()); + } + ip = inst.goto; + } + Split(ref inst) => { + self.m.jobs.push(Job::Inst { ip: inst.goto2, at: at }); + ip = inst.goto1; + } + EmptyLook(ref inst) => { + if self.input.is_empty_match(at, inst) { + ip = inst.goto; + } else { + return false; + } + } + Char(ref inst) => { + if inst.c == at.char() { + ip = inst.goto; + at = self.input.at(at.next_pos()); + } else { + return false; + } + } + Ranges(ref inst) => { + if inst.matches(at.char()) { + ip = inst.goto; + at = self.input.at(at.next_pos()); + } else { + return false; + } + } + Bytes(ref inst) => { + if let Some(b) = at.byte() { + if inst.matches(b) { + ip = inst.goto; + at = self.input.at(at.next_pos()); + continue; + } + } + return false; + } + } + } + } + + fn has_visited(&mut self, ip: InstPtr, at: InputAt) -> bool { + let k = ip * (self.input.len() + 1) + at.pos(); + let k1 = k / BIT_SIZE; + let k2 = usize_to_u32(1 << (k & (BIT_SIZE - 1))); + if self.m.visited[k1] & k2 == 0 { + self.m.visited[k1] |= k2; + false + } else { + true + } + } +} + +fn usize_to_u32(n: usize) -> u32 { + if (n as u64) > (::std::u32::MAX as u64) { + panic!("BUG: {} is too big to fit into u32", n) + } + n as u32 +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/compile.rs cargo-0.26.0/vendor/regex-0.2.10/src/compile.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/compile.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/compile.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1151 @@ +// Copyright 2014-2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::collections::HashMap; +use std::iter; +use std::result; +use std::sync::Arc; + +use syntax::is_word_byte; +use syntax::hir::{self, Hir}; +use utf8_ranges::{Utf8Range, Utf8Sequence, Utf8Sequences}; + +use prog::{ + Program, Inst, InstPtr, EmptyLook, + InstSave, InstSplit, InstEmptyLook, InstChar, InstRanges, InstBytes, +}; + +use Error; + +type Result = result::Result; + +#[derive(Debug)] +struct Patch { + hole: Hole, + entry: InstPtr, +} + +/// A compiler translates a regular expression AST to a sequence of +/// instructions. The sequence of instructions represents an NFA. +pub struct Compiler { + insts: Vec, + compiled: Program, + capture_name_idx: HashMap, + num_exprs: usize, + size_limit: usize, + suffix_cache: SuffixCache, + utf8_seqs: Option, + byte_classes: ByteClassSet, +} + +impl Compiler { + /// Create a new regular expression compiler. + /// + /// Various options can be set before calling `compile` on an expression. + pub fn new() -> Self { + Compiler { + insts: vec![], + compiled: Program::new(), + capture_name_idx: HashMap::new(), + num_exprs: 0, + size_limit: 10 * (1 << 20), + suffix_cache: SuffixCache::new(1000), + utf8_seqs: Some(Utf8Sequences::new('\x00', '\x00')), + byte_classes: ByteClassSet::new(), + } + } + + /// The size of the resulting program is limited by size_limit. If + /// the program approximately exceeds the given size (in bytes), then + /// compilation will stop and return an error. + pub fn size_limit(mut self, size_limit: usize) -> Self { + self.size_limit = size_limit; + self + } + + /// If bytes is true, then the program is compiled as a byte based + /// automaton, which incorporates UTF-8 decoding into the machine. If it's + /// false, then the automaton is Unicode scalar value based, e.g., an + /// engine utilizing such an automaton is resposible for UTF-8 decoding. + /// + /// The specific invariant is that when returning a byte based machine, + /// the neither the `Char` nor `Ranges` instructions are produced. + /// Conversely, when producing a Unicode scalar value machine, the `Bytes` + /// instruction is never produced. + /// + /// Note that `dfa(true)` implies `bytes(true)`. + pub fn bytes(mut self, yes: bool) -> Self { + self.compiled.is_bytes = yes; + self + } + + /// When disabled, the program compiled may match arbitrary bytes. + /// + /// When enabled (the default), all compiled programs exclusively match + /// valid UTF-8 bytes. + pub fn only_utf8(mut self, yes: bool) -> Self { + self.compiled.only_utf8 = yes; + self + } + + /// When set, the machine returned is suitable for use in the DFA matching + /// engine. + /// + /// In particular, this ensures that if the regex is not anchored in the + /// beginning, then a preceding `.*?` is included in the program. (The NFA + /// based engines handle the preceding `.*?` explicitly, which is difficult + /// or impossible in the DFA engine.) + pub fn dfa(mut self, yes: bool) -> Self { + self.compiled.is_dfa = yes; + self + } + + /// When set, the machine returned is suitable for matching text in + /// reverse. In particular, all concatenations are flipped. + pub fn reverse(mut self, yes: bool) -> Self { + self.compiled.is_reverse = yes; + self + } + + /// Compile a regular expression given its AST. + /// + /// The compiler is guaranteed to succeed unless the program exceeds the + /// specified size limit. If the size limit is exceeded, then compilation + /// stops and returns an error. + pub fn compile( + mut self, + exprs: &[Hir], + ) -> result::Result { + debug_assert!(exprs.len() >= 1); + self.num_exprs = exprs.len(); + if exprs.len() == 1 { + self.compile_one(&exprs[0]) + } else { + self.compile_many(exprs) + } + } + + fn compile_one(mut self, expr: &Hir) -> result::Result { + // If we're compiling a forward DFA and we aren't anchored, then + // add a `.*?` before the first capture group. + // Other matching engines handle this by baking the logic into the + // matching engine itself. + let mut dotstar_patch = Patch { hole: Hole::None, entry: 0 }; + self.compiled.is_anchored_start = expr.is_anchored_start(); + self.compiled.is_anchored_end = expr.is_anchored_end(); + if self.compiled.needs_dotstar() { + dotstar_patch = try!(self.c_dotstar()); + self.compiled.start = dotstar_patch.entry; + } + self.compiled.captures = vec![None]; + let patch = try!(self.c_capture(0, expr)); + if self.compiled.needs_dotstar() { + self.fill(dotstar_patch.hole, patch.entry); + } else { + self.compiled.start = patch.entry; + } + self.fill_to_next(patch.hole); + self.compiled.matches = vec![self.insts.len()]; + self.push_compiled(Inst::Match(0)); + self.compile_finish() + } + + fn compile_many( + mut self, + exprs: &[Hir], + ) -> result::Result { + debug_assert!(exprs.len() > 1); + + self.compiled.is_anchored_start = + exprs.iter().all(|e| e.is_anchored_start()); + self.compiled.is_anchored_end = + exprs.iter().all(|e| e.is_anchored_end()); + let mut dotstar_patch = Patch { hole: Hole::None, entry: 0 }; + if self.compiled.needs_dotstar() { + dotstar_patch = try!(self.c_dotstar()); + self.compiled.start = dotstar_patch.entry; + } else { + self.compiled.start = 0; // first instruction is always split + } + self.fill_to_next(dotstar_patch.hole); + + let mut prev_hole = Hole::None; + for (i, expr) in exprs[0..exprs.len() - 1].iter().enumerate() { + self.fill_to_next(prev_hole); + let split = self.push_split_hole(); + let Patch { hole, entry } = try!(self.c_capture(0, expr)); + self.fill_to_next(hole); + self.compiled.matches.push(self.insts.len()); + self.push_compiled(Inst::Match(i)); + prev_hole = self.fill_split(split, Some(entry), None); + } + let i = exprs.len() - 1; + let Patch { hole, entry } = try!(self.c_capture(0, &exprs[i])); + self.fill(prev_hole, entry); + self.fill_to_next(hole); + self.compiled.matches.push(self.insts.len()); + self.push_compiled(Inst::Match(i)); + self.compile_finish() + } + + fn compile_finish(mut self) -> result::Result { + self.compiled.insts = + self.insts.into_iter().map(|inst| inst.unwrap()).collect(); + self.compiled.byte_classes = self.byte_classes.byte_classes(); + self.compiled.capture_name_idx = Arc::new(self.capture_name_idx); + Ok(self.compiled) + } + + /// Compile expr into self.insts, returning a patch on success, + /// or an error if we run out of memory. + /// + /// All of the c_* methods of the compiler share the contract outlined + /// here. + /// + /// The main thing that a c_* method does is mutate `self.insts` + /// to add a list of mostly compiled instructions required to execute + /// the given expression. `self.insts` contains MaybeInsts rather than + /// Insts because there is some backpatching required. + /// + /// The `Patch` value returned by each c_* method provides metadata + /// about the compiled instructions emitted to `self.insts`. The + /// `entry` member of the patch refers to the first instruction + /// (the entry point), while the `hole` member contains zero or + /// more offsets to partial instructions that need to be backpatched. + /// The c_* routine can't know where its list of instructions are going to + /// jump to after execution, so it is up to the caller to patch + /// these jumps to point to the right place. So compiling some + /// expression, e, we would end up with a situation that looked like: + /// + /// ```text + /// self.insts = [ ..., i1, i2, ..., iexit1, ..., iexitn, ...] + /// ^ ^ ^ + /// | \ / + /// entry \ / + /// hole + /// ``` + /// + /// To compile two expressions, e1 and e2, concatinated together we + /// would do: + /// + /// ```ignore + /// let patch1 = self.c(e1); + /// let patch2 = self.c(e2); + /// ``` + /// + /// while leaves us with a situation that looks like + /// + /// ```text + /// self.insts = [ ..., i1, ..., iexit1, ..., i2, ..., iexit2 ] + /// ^ ^ ^ ^ + /// | | | | + /// entry1 hole1 entry2 hole2 + /// ``` + /// + /// Then to merge the two patches together into one we would backpatch + /// hole1 with entry2 and return a new patch that enters at entry1 + /// and has hole2 for a hole. In fact, if you look at the c_concat + /// method you will see that it does exactly this, though it handles + /// a list of expressions rather than just the two that we use for + /// an example. + fn c(&mut self, expr: &Hir) -> Result { + use prog; + use syntax::hir::HirKind::*; + + try!(self.check_size()); + match *expr.kind() { + Empty => Ok(Patch { hole: Hole::None, entry: self.insts.len() }), + Literal(hir::Literal::Unicode(c)) => { + self.c_literal(&[c]) + } + Literal(hir::Literal::Byte(b)) => { + assert!(self.compiled.uses_bytes()); + self.c_bytes(&[b]) + } + Class(hir::Class::Unicode(ref cls)) => { + self.c_class(cls.ranges()) + } + Class(hir::Class::Bytes(ref cls)) => { + if self.compiled.uses_bytes() { + self.c_class_bytes(cls.ranges()) + } else { + assert!(cls.is_all_ascii()); + let mut char_ranges = vec![]; + for r in cls.iter() { + let (s, e) = (r.start() as char, r.end() as char); + char_ranges.push(hir::ClassUnicodeRange::new(s, e)); + } + self.c_class(&char_ranges) + } + } + Anchor(hir::Anchor::StartLine) if self.compiled.is_reverse => { + self.byte_classes.set_range(b'\n', b'\n'); + self.c_empty_look(prog::EmptyLook::EndLine) + } + Anchor(hir::Anchor::StartLine) => { + self.byte_classes.set_range(b'\n', b'\n'); + self.c_empty_look(prog::EmptyLook::StartLine) + } + Anchor(hir::Anchor::EndLine) if self.compiled.is_reverse => { + self.byte_classes.set_range(b'\n', b'\n'); + self.c_empty_look(prog::EmptyLook::StartLine) + } + Anchor(hir::Anchor::EndLine) => { + self.byte_classes.set_range(b'\n', b'\n'); + self.c_empty_look(prog::EmptyLook::EndLine) + } + Anchor(hir::Anchor::StartText) if self.compiled.is_reverse => { + self.c_empty_look(prog::EmptyLook::EndText) + } + Anchor(hir::Anchor::StartText) => { + self.c_empty_look(prog::EmptyLook::StartText) + } + Anchor(hir::Anchor::EndText) if self.compiled.is_reverse => { + self.c_empty_look(prog::EmptyLook::StartText) + } + Anchor(hir::Anchor::EndText) => { + self.c_empty_look(prog::EmptyLook::EndText) + } + WordBoundary(hir::WordBoundary::Unicode) => { + self.compiled.has_unicode_word_boundary = true; + self.byte_classes.set_word_boundary(); + self.c_empty_look(prog::EmptyLook::WordBoundary) + } + WordBoundary(hir::WordBoundary::UnicodeNegate) => { + self.compiled.has_unicode_word_boundary = true; + self.byte_classes.set_word_boundary(); + self.c_empty_look(prog::EmptyLook::NotWordBoundary) + } + WordBoundary(hir::WordBoundary::Ascii) => { + self.byte_classes.set_word_boundary(); + self.c_empty_look(prog::EmptyLook::WordBoundaryAscii) + } + WordBoundary(hir::WordBoundary::AsciiNegate) => { + self.byte_classes.set_word_boundary(); + self.c_empty_look(prog::EmptyLook::NotWordBoundaryAscii) + } + Group(ref g) => { + match g.kind { + hir::GroupKind::NonCapturing => self.c(&g.hir), + hir::GroupKind::CaptureIndex(index) => { + if index as usize >= self.compiled.captures.len() { + self.compiled.captures.push(None); + } + self.c_capture(2 * index as usize, &g.hir) + } + hir::GroupKind::CaptureName { index, ref name } => { + if index as usize >= self.compiled.captures.len() { + let n = name.to_string(); + self.compiled.captures.push(Some(n.clone())); + self.capture_name_idx.insert(n, index as usize); + } + self.c_capture(2 * index as usize, &g.hir) + } + } + } + Concat(ref es) => { + if self.compiled.is_reverse { + self.c_concat(es.iter().rev()) + } else { + self.c_concat(es) + } + } + Alternation(ref es) => self.c_alternate(&**es), + Repetition(ref rep) => self.c_repeat(rep), + } + } + + fn c_capture(&mut self, first_slot: usize, expr: &Hir) -> Result { + if self.num_exprs > 1 || self.compiled.is_dfa { + // Don't ever compile Save instructions for regex sets because + // they are never used. They are also never used in DFA programs + // because DFAs can't handle captures. + self.c(expr) + } else { + let entry = self.insts.len(); + let hole = self.push_hole(InstHole::Save { slot: first_slot }); + let patch = try!(self.c(expr)); + self.fill(hole, patch.entry); + self.fill_to_next(patch.hole); + let hole = self.push_hole(InstHole::Save { slot: first_slot + 1 }); + Ok(Patch { hole: hole, entry: entry }) + } + } + + fn c_dotstar(&mut self) -> Result { + Ok(if !self.compiled.only_utf8() { + try!(self.c(&Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::ZeroOrMore, + greedy: false, + hir: Box::new(Hir::any(true)), + }))) + } else { + try!(self.c(&Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::ZeroOrMore, + greedy: false, + hir: Box::new(Hir::any(false)), + }))) + }) + } + + fn c_literal(&mut self, chars: &[char]) -> Result { + debug_assert!(!chars.is_empty()); + let mut chars: Box> = + if self.compiled.is_reverse { + Box::new(chars.iter().rev()) + } else { + Box::new(chars.iter()) + }; + let first = *chars.next().expect("non-empty literal"); + let Patch { mut hole, entry } = try!(self.c_char(first)); + for &c in chars { + let p = try!(self.c_char(c)); + self.fill(hole, p.entry); + hole = p.hole; + } + Ok(Patch { hole: hole, entry: entry }) + } + + fn c_char(&mut self, c: char) -> Result { + self.c_class(&[hir::ClassUnicodeRange::new(c, c)]) + } + + fn c_class(&mut self, ranges: &[hir::ClassUnicodeRange]) -> Result { + assert!(!ranges.is_empty()); + if self.compiled.uses_bytes() { + CompileClass { + c: self, + ranges: ranges, + }.compile() + } else { + let ranges: Vec<(char, char)> = + ranges.iter().map(|r| (r.start(), r.end())).collect(); + let hole = if ranges.len() == 1 && ranges[0].0 == ranges[0].1 { + self.push_hole(InstHole::Char { c: ranges[0].0 }) + } else { + self.push_hole(InstHole::Ranges { ranges: ranges }) + }; + Ok(Patch { hole: hole, entry: self.insts.len() - 1 }) + } + } + + fn c_bytes(&mut self, bytes: &[u8]) -> Result { + debug_assert!(!bytes.is_empty()); + let mut bytes: Box> = + if self.compiled.is_reverse { + Box::new(bytes.iter().rev()) + } else { + Box::new(bytes.iter()) + }; + let first = *bytes.next().expect("non-empty literal"); + let Patch { mut hole, entry } = try!(self.c_byte(first)); + for &b in bytes { + let p = try!(self.c_byte(b)); + self.fill(hole, p.entry); + hole = p.hole; + } + Ok(Patch { hole: hole, entry: entry }) + } + + fn c_byte(&mut self, b: u8) -> Result { + self.c_class_bytes(&[hir::ClassBytesRange::new(b, b)]) + } + + fn c_class_bytes(&mut self, ranges: &[hir::ClassBytesRange]) -> Result { + debug_assert!(!ranges.is_empty()); + + let first_split_entry = self.insts.len(); + let mut holes = vec![]; + let mut prev_hole = Hole::None; + for r in &ranges[0..ranges.len() - 1] { + self.fill_to_next(prev_hole); + let split = self.push_split_hole(); + let next = self.insts.len(); + self.byte_classes.set_range(r.start(), r.end()); + holes.push(self.push_hole(InstHole::Bytes { + start: r.start(), end: r.end(), + })); + prev_hole = self.fill_split(split, Some(next), None); + } + let next = self.insts.len(); + let r = &ranges[ranges.len() - 1]; + self.byte_classes.set_range(r.start(), r.end()); + holes.push(self.push_hole(InstHole::Bytes { + start: r.start(), end: r.end(), + })); + self.fill(prev_hole, next); + Ok(Patch { hole: Hole::Many(holes), entry: first_split_entry }) + } + + fn c_empty_look(&mut self, look: EmptyLook) -> Result { + let hole = self.push_hole(InstHole::EmptyLook { look: look }); + Ok(Patch { hole: hole, entry: self.insts.len() - 1 }) + } + + fn c_concat<'a, I>(&mut self, exprs: I) -> Result + where I: IntoIterator { + let mut exprs = exprs.into_iter(); + let first = match exprs.next() { + Some(expr) => expr, + None => { + return Ok(Patch { hole: Hole::None, entry: self.insts.len() }) + } + }; + let Patch { mut hole, entry } = try!(self.c(first)); + for e in exprs { + let p = try!(self.c(e)); + self.fill(hole, p.entry); + hole = p.hole; + } + Ok(Patch { hole: hole, entry: entry }) + } + + fn c_alternate(&mut self, exprs: &[Hir]) -> Result { + debug_assert!( + exprs.len() >= 2, "alternates must have at least 2 exprs"); + + // Initial entry point is always the first split. + let first_split_entry = self.insts.len(); + + // Save up all of the holes from each alternate. They will all get + // patched to point to the same location. + let mut holes = vec![]; + + let mut prev_hole = Hole::None; + for e in &exprs[0..exprs.len() - 1] { + self.fill_to_next(prev_hole); + let split = self.push_split_hole(); + let prev_entry = self.insts.len(); + let Patch { hole, entry } = try!(self.c(e)); + if prev_entry == self.insts.len() { + // TODO(burntsushi): It is kind of silly that we don't support + // empty-subexpressions in alternates, but it is supremely + // awkward to support them in the existing compiler + // infrastructure. This entire compiler needs to be thrown out + // anyway, so don't feel too bad. + return Err(Error::Syntax( + "alternations cannot currently contain \ + empty sub-expressions".to_string())); + } + holes.push(hole); + prev_hole = self.fill_split(split, Some(entry), None); + } + let prev_entry = self.insts.len(); + let Patch { hole, entry } = try!(self.c(&exprs[exprs.len() - 1])); + if prev_entry == self.insts.len() { + // TODO(burntsushi): See TODO above. + return Err(Error::Syntax( + "alternations cannot currently contain \ + empty sub-expressions".to_string())); + } + holes.push(hole); + self.fill(prev_hole, entry); + Ok(Patch { hole: Hole::Many(holes), entry: first_split_entry }) + } + + fn c_repeat(&mut self, rep: &hir::Repetition) -> Result { + use syntax::hir::RepetitionKind::*; + match rep.kind { + ZeroOrOne => self.c_repeat_zero_or_one(&rep.hir, rep.greedy), + ZeroOrMore => self.c_repeat_zero_or_more(&rep.hir, rep.greedy), + OneOrMore => self.c_repeat_one_or_more(&rep.hir, rep.greedy), + Range(hir::RepetitionRange::Exactly(min_max)) => { + self.c_repeat_range(&rep.hir, rep.greedy, min_max, min_max) + } + Range(hir::RepetitionRange::AtLeast(min)) => { + self.c_repeat_range_min_or_more(&rep.hir, rep.greedy, min) + } + Range(hir::RepetitionRange::Bounded(min, max)) => { + self.c_repeat_range(&rep.hir, rep.greedy, min, max) + } + } + } + + fn c_repeat_zero_or_one(&mut self, expr: &Hir, greedy: bool) -> Result { + let split_entry = self.insts.len(); + let split = self.push_split_hole(); + let Patch { hole: hole_rep, entry: entry_rep } = try!(self.c(expr)); + + let split_hole = if greedy { + self.fill_split(split, Some(entry_rep), None) + } else { + self.fill_split(split, None, Some(entry_rep)) + }; + let holes = vec![hole_rep, split_hole]; + Ok(Patch { hole: Hole::Many(holes), entry: split_entry }) + } + + fn c_repeat_zero_or_more(&mut self, expr: &Hir, greedy: bool) -> Result { + let split_entry = self.insts.len(); + let split = self.push_split_hole(); + let Patch { hole: hole_rep, entry: entry_rep } = try!(self.c(expr)); + + self.fill(hole_rep, split_entry); + let split_hole = if greedy { + self.fill_split(split, Some(entry_rep), None) + } else { + self.fill_split(split, None, Some(entry_rep)) + }; + Ok(Patch { hole: split_hole, entry: split_entry }) + } + + fn c_repeat_one_or_more(&mut self, expr: &Hir, greedy: bool) -> Result { + let Patch { hole: hole_rep, entry: entry_rep } = try!(self.c(expr)); + self.fill_to_next(hole_rep); + let split = self.push_split_hole(); + + let split_hole = if greedy { + self.fill_split(split, Some(entry_rep), None) + } else { + self.fill_split(split, None, Some(entry_rep)) + }; + Ok(Patch { hole: split_hole, entry: entry_rep }) + } + + fn c_repeat_range_min_or_more( + &mut self, + expr: &Hir, + greedy: bool, + min: u32, + ) -> Result { + let min = u32_to_usize(min); + let patch_concat = try!(self.c_concat(iter::repeat(expr).take(min))); + let patch_rep = try!(self.c_repeat_zero_or_more(expr, greedy)); + self.fill(patch_concat.hole, patch_rep.entry); + Ok(Patch { hole: patch_rep.hole, entry: patch_concat.entry }) + } + + fn c_repeat_range( + &mut self, + expr: &Hir, + greedy: bool, + min: u32, + max: u32, + ) -> Result { + let (min, max) = (u32_to_usize(min), u32_to_usize(max)); + let patch_concat = try!(self.c_concat(iter::repeat(expr).take(min))); + let initial_entry = patch_concat.entry; + if min == max { + return Ok(patch_concat); + } + // It is much simpler to compile, e.g., `a{2,5}` as: + // + // aaa?a?a? + // + // But you end up with a sequence of instructions like this: + // + // 0: 'a' + // 1: 'a', + // 2: split(3, 4) + // 3: 'a' + // 4: split(5, 6) + // 5: 'a' + // 6: split(7, 8) + // 7: 'a' + // 8: MATCH + // + // This is *incredibly* inefficient because the splits end + // up forming a chain, which has to be resolved everything a + // transition is followed. + let mut holes = vec![]; + let mut prev_hole = patch_concat.hole; + for _ in min..max { + self.fill_to_next(prev_hole); + let split = self.push_split_hole(); + let Patch { hole, entry } = try!(self.c(expr)); + prev_hole = hole; + if greedy { + holes.push(self.fill_split(split, Some(entry), None)); + } else { + holes.push(self.fill_split(split, None, Some(entry))); + } + } + holes.push(prev_hole); + Ok(Patch { hole: Hole::Many(holes), entry: initial_entry }) + } + + fn fill(&mut self, hole: Hole, goto: InstPtr) { + match hole { + Hole::None => {} + Hole::One(pc) => { + self.insts[pc].fill(goto); + } + Hole::Many(holes) => { + for hole in holes { + self.fill(hole, goto); + } + } + } + } + + fn fill_to_next(&mut self, hole: Hole) { + let next = self.insts.len(); + self.fill(hole, next); + } + + fn fill_split( + &mut self, + hole: Hole, + goto1: Option, + goto2: Option, + ) -> Hole { + match hole { + Hole::None => Hole::None, + Hole::One(pc) => { + match (goto1, goto2) { + (Some(goto1), Some(goto2)) => { + self.insts[pc].fill_split(goto1, goto2); + Hole::None + } + (Some(goto1), None) => { + self.insts[pc].half_fill_split_goto1(goto1); + Hole::One(pc) + } + (None, Some(goto2)) => { + self.insts[pc].half_fill_split_goto2(goto2); + Hole::One(pc) + } + (None, None) => unreachable!("at least one of the split \ + holes must be filled"), + } + } + Hole::Many(holes) => { + let mut new_holes = vec![]; + for hole in holes { + new_holes.push(self.fill_split(hole, goto1, goto2)); + } + if new_holes.is_empty() { + Hole::None + } else if new_holes.len() == 1 { + new_holes.pop().unwrap() + } else { + Hole::Many(new_holes) + } + } + } + } + + fn push_compiled(&mut self, inst: Inst) { + self.insts.push(MaybeInst::Compiled(inst)); + } + + fn push_hole(&mut self, inst: InstHole) -> Hole { + let hole = self.insts.len(); + self.insts.push(MaybeInst::Uncompiled(inst)); + Hole::One(hole) + } + + fn push_split_hole(&mut self) -> Hole { + let hole = self.insts.len(); + self.insts.push(MaybeInst::Split); + Hole::One(hole) + } + + fn check_size(&self) -> result::Result<(), Error> { + use std::mem::size_of; + + if self.insts.len() * size_of::() > self.size_limit { + Err(Error::CompiledTooBig(self.size_limit)) + } else { + Ok(()) + } + } +} + +#[derive(Debug)] +enum Hole { + None, + One(InstPtr), + Many(Vec), +} + +#[derive(Clone, Debug)] +enum MaybeInst { + Compiled(Inst), + Uncompiled(InstHole), + Split, + Split1(InstPtr), + Split2(InstPtr), +} + +impl MaybeInst { + fn fill(&mut self, goto: InstPtr) { + let filled = match *self { + MaybeInst::Uncompiled(ref inst) => inst.fill(goto), + MaybeInst::Split1(goto1) => { + Inst::Split(InstSplit { goto1: goto1, goto2: goto }) + } + MaybeInst::Split2(goto2) => { + Inst::Split(InstSplit { goto1: goto, goto2: goto2 }) + } + _ => unreachable!("not all instructions were compiled! \ + found uncompiled instruction: {:?}", self), + }; + *self = MaybeInst::Compiled(filled); + } + + fn fill_split(&mut self, goto1: InstPtr, goto2: InstPtr) { + let filled = match *self { + MaybeInst::Split => { + Inst::Split(InstSplit { goto1: goto1, goto2: goto2 }) + } + _ => unreachable!("must be called on Split instruction, \ + instead it was called on: {:?}", self), + }; + *self = MaybeInst::Compiled(filled); + } + + fn half_fill_split_goto1(&mut self, goto1: InstPtr) { + let half_filled = match *self { + MaybeInst::Split => goto1, + _ => unreachable!("must be called on Split instruction, \ + instead it was called on: {:?}", self), + }; + *self = MaybeInst::Split1(half_filled); + } + + fn half_fill_split_goto2(&mut self, goto2: InstPtr) { + let half_filled = match *self { + MaybeInst::Split => goto2, + _ => unreachable!("must be called on Split instruction, \ + instead it was called on: {:?}", self), + }; + *self = MaybeInst::Split2(half_filled); + } + + fn unwrap(self) -> Inst { + match self { + MaybeInst::Compiled(inst) => inst, + _ => unreachable!("must be called on a compiled instruction, \ + instead it was called on: {:?}", self), + } + } +} + +#[derive(Clone, Debug)] +enum InstHole { + Save { slot: usize }, + EmptyLook { look: EmptyLook }, + Char { c: char }, + Ranges { ranges: Vec<(char, char)> }, + Bytes { start: u8, end: u8 }, +} + +impl InstHole { + fn fill(&self, goto: InstPtr) -> Inst { + match *self { + InstHole::Save { slot } => Inst::Save(InstSave { + goto: goto, + slot: slot, + }), + InstHole::EmptyLook { look } => Inst::EmptyLook(InstEmptyLook { + goto: goto, + look: look, + }), + InstHole::Char { c } => Inst::Char(InstChar { + goto: goto, + c: c, + }), + InstHole::Ranges { ref ranges } => Inst::Ranges(InstRanges { + goto: goto, + ranges: ranges.clone(), + }), + InstHole::Bytes { start, end } => Inst::Bytes(InstBytes { + goto: goto, + start: start, + end: end, + }), + } + } +} + +struct CompileClass<'a, 'b> { + c: &'a mut Compiler, + ranges: &'b [hir::ClassUnicodeRange], +} + +impl<'a, 'b> CompileClass<'a, 'b> { + fn compile(mut self) -> Result { + let mut holes = vec![]; + let mut initial_entry = None; + let mut last_split = Hole::None; + let mut utf8_seqs = self.c.utf8_seqs.take().unwrap(); + self.c.suffix_cache.clear(); + + for (i, range) in self.ranges.iter().enumerate() { + let is_last_range = i + 1 == self.ranges.len(); + utf8_seqs.reset(range.start(), range.end()); + let mut it = (&mut utf8_seqs).peekable(); + loop { + let utf8_seq = match it.next() { + None => break, + Some(utf8_seq) => utf8_seq, + }; + if is_last_range && it.peek().is_none() { + let Patch { hole, entry } = try!(self.c_utf8_seq(&utf8_seq)); + holes.push(hole); + self.c.fill(last_split, entry); + last_split = Hole::None; + if initial_entry.is_none() { + initial_entry = Some(entry); + } + } else { + if initial_entry.is_none() { + initial_entry = Some(self.c.insts.len()); + } + self.c.fill_to_next(last_split); + last_split = self.c.push_split_hole(); + let Patch { hole, entry } = try!(self.c_utf8_seq(&utf8_seq)); + holes.push(hole); + last_split = self.c.fill_split(last_split, Some(entry), None); + } + } + } + self.c.utf8_seqs = Some(utf8_seqs); + Ok(Patch { + hole: Hole::Many(holes), + entry: initial_entry.unwrap(), + }) + } + + fn c_utf8_seq(&mut self, seq: &Utf8Sequence) -> Result { + if self.c.compiled.is_reverse { + self.c_utf8_seq_(seq) + } else { + self.c_utf8_seq_(seq.into_iter().rev()) + } + } + + fn c_utf8_seq_<'r, I>(&mut self, seq: I) -> Result + where I: IntoIterator { + // The initial instruction for each UTF-8 sequence should be the same. + let mut from_inst = ::std::usize::MAX; + let mut last_hole = Hole::None; + for byte_range in seq { + let key = SuffixCacheKey { + from_inst: from_inst, + start: byte_range.start, + end: byte_range.end, + }; + { + let pc = self.c.insts.len(); + if let Some(cached_pc) = self.c.suffix_cache.get(key, pc) { + from_inst = cached_pc; + continue; + } + } + self.c.byte_classes.set_range(byte_range.start, byte_range.end); + if from_inst == ::std::usize::MAX { + last_hole = self.c.push_hole(InstHole::Bytes { + start: byte_range.start, + end: byte_range.end, + }); + } else { + self.c.push_compiled(Inst::Bytes(InstBytes { + goto: from_inst, + start: byte_range.start, + end: byte_range.end, + })); + } + from_inst = self.c.insts.len().checked_sub(1).unwrap(); + debug_assert!(from_inst < ::std::usize::MAX); + } + debug_assert!(from_inst < ::std::usize::MAX); + Ok(Patch { hole: last_hole, entry: from_inst }) + } +} + +/// `SuffixCache` is a simple bounded hash map for caching suffix entries in +/// UTF-8 automata. For example, consider the Unicode range \u{0}-\u{FFFF}. +/// The set of byte ranges looks like this: +/// +/// [0-7F] +/// [C2-DF][80-BF] +/// [E0][A0-BF][80-BF] +/// [E1-EC][80-BF][80-BF] +/// [ED][80-9F][80-BF] +/// [EE-EF][80-BF][80-BF] +/// +/// Each line above translates to one alternate in the compiled regex program. +/// However, all but one of the alternates end in the same suffix, which is +/// a waste of an instruction. The suffix cache facilitates reusing them across +/// alternates. +/// +/// Note that a HashMap could be trivially used for this, but we don't need its +/// overhead. Some small bounded space (LRU style) is more than enough. +struct SuffixCache { + table: Vec, + // Every time the cache is cleared, we increment the version number instead + // of actually zeroing memory. Since we store a copy of the current version + // in every element, all we need to do is make sure to invalidate any stale + // entries upon access. This saves quite a bit of time! + version: usize, +} + +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] +struct SuffixCacheEntry { + key: SuffixCacheKey, + pc: InstPtr, + version: usize, +} + +#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] +struct SuffixCacheKey { + from_inst: InstPtr, + start: u8, + end: u8, +} + +impl SuffixCache { + fn new(size: usize) -> Self { + SuffixCache { + table: vec![SuffixCacheEntry::default(); size], + version: 0, + } + } + + fn get(&mut self, key: SuffixCacheKey, pc: InstPtr) -> Option { + let h = self.hash(&key); + let e = self.table[h]; + if e.key == key && e.version == self.version { + Some(e.pc) + } else { + self.table[h] = SuffixCacheEntry { + key: key, + pc: pc, + version: self.version, + }; + None + } + } + + fn clear(&mut self) { + self.version += 1; + } + + fn hash(&self, suffix: &SuffixCacheKey) -> usize { + // Basic FNV-1a hash as described: + // https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function + const FNV_PRIME: u64 = 1099511628211; + let mut h = 14695981039346656037; + h = (h ^ (suffix.from_inst as u64)).wrapping_mul(FNV_PRIME); + h = (h ^ (suffix.start as u64)).wrapping_mul(FNV_PRIME); + h = (h ^ (suffix.end as u64)).wrapping_mul(FNV_PRIME); + (h as usize) % self.table.len() + } +} + +struct ByteClassSet([bool; 256]); + +impl ByteClassSet { + fn new() -> Self { + ByteClassSet([false; 256]) + } + + fn set_range(&mut self, start: u8, end: u8) { + debug_assert!(start <= end); + if start > 0 { + self.0[start as usize - 1] = true; + } + self.0[end as usize] = true; + } + + fn set_word_boundary(&mut self) { + // We need to mark all ranges of bytes whose pairs result in + // evaluating \b differently. + let iswb = is_word_byte; + let mut b1: u16 = 0; + let mut b2: u16; + while b1 <= 255 { + b2 = b1 + 1; + while b2 <= 255 && iswb(b1 as u8) == iswb(b2 as u8) { + b2 += 1; + } + self.set_range(b1 as u8, (b2 - 1) as u8); + b1 = b2; + } + } + + fn byte_classes(&self) -> Vec { + // N.B. If you're debugging the DFA, it's useful to simply return + // `(0..256).collect()`, which effectively removes the byte classes + // and makes the transitions easier to read. + // (0usize..256).map(|x| x as u8).collect() + let mut byte_classes = vec![0; 256]; + let mut class = 0u8; + let mut i = 0; + loop { + byte_classes[i] = class as u8; + if i >= 255 { + break; + } + if self.0[i] { + class = class.checked_add(1).unwrap(); + } + i += 1; + } + byte_classes + } +} + +fn u32_to_usize(n: u32) -> usize { + // In case usize is less than 32 bits, we need to guard against overflow. + // On most platforms this compiles to nothing. + // TODO Use `std::convert::TryFrom` once it's stable. + if (n as u64) > (::std::usize::MAX as u64) { + panic!("BUG: {} is too big to be pointer sized", n) + } + n as usize +} + +#[cfg(test)] +mod tests { + use super::ByteClassSet; + + #[test] + fn byte_classes() { + let mut set = ByteClassSet::new(); + set.set_range(b'a', b'z'); + let classes = set.byte_classes(); + assert_eq!(classes[0], 0); + assert_eq!(classes[1], 0); + assert_eq!(classes[2], 0); + assert_eq!(classes[b'a' as usize - 1], 0); + assert_eq!(classes[b'a' as usize], 1); + assert_eq!(classes[b'm' as usize], 1); + assert_eq!(classes[b'z' as usize], 1); + assert_eq!(classes[b'z' as usize + 1], 2); + assert_eq!(classes[254], 2); + assert_eq!(classes[255], 2); + + let mut set = ByteClassSet::new(); + set.set_range(0, 2); + set.set_range(4, 6); + let classes = set.byte_classes(); + assert_eq!(classes[0], 0); + assert_eq!(classes[1], 0); + assert_eq!(classes[2], 0); + assert_eq!(classes[3], 1); + assert_eq!(classes[4], 2); + assert_eq!(classes[5], 2); + assert_eq!(classes[6], 2); + assert_eq!(classes[7], 3); + assert_eq!(classes[255], 3); + } + + #[test] + fn full_byte_classes() { + let mut set = ByteClassSet::new(); + for i in 0..256u16 { + set.set_range(i as u8, i as u8); + } + assert_eq!(set.byte_classes().len(), 256); + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/dfa.rs cargo-0.26.0/vendor/regex-0.2.10/src/dfa.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/dfa.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/dfa.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1894 @@ +// Copyright 2014-2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +The DFA matching engine. + +A DFA provides faster matching because the engine is in exactly one state at +any point in time. In the NFA, there may be multiple active states, and +considerable CPU cycles are spent shuffling them around. In finite automata +speak, the DFA follows epsilon transitions in the regex far less than the NFA. + +A DFA is a classic trade off between time and space. The NFA is slower, but +its memory requirements are typically small and predictable. The DFA is faster, +but given the right regex and the right input, the number of states in the +DFA can grow exponentially. To mitigate this space problem, we do two things: + +1. We implement an *online* DFA. That is, the DFA is constructed from the NFA + during a search. When a new state is computed, it is stored in a cache so + that it may be reused. An important consequence of this implementation + is that states that are never reached for a particular input are never + computed. (This is impossible in an "offline" DFA which needs to compute + all possible states up front.) +2. If the cache gets too big, we wipe it and continue matching. + +In pathological cases, a new state can be created for every byte of input. +(e.g., The regex `(a|b)*a(a|b){20}` on a long sequence of a's and b's.) +In this case, performance regresses to slightly slower than the full NFA +simulation, in large part because the cache becomes useless. If the cache +is wiped too frequently, the DFA quits and control falls back to one of the +NFA simulations. + +Because of the "lazy" nature of this DFA, the inner matching loop is +considerably more complex than one might expect out of a DFA. A number of +tricks are employed to make it fast. Tread carefully. + +N.B. While this implementation is heavily commented, Russ Cox's series of +articles on regexes is strongly recommended: https://swtch.com/~rsc/regexp/ +(As is the DFA implementation in RE2, which heavily influenced this +implementation.) +*/ + +use std::collections::HashMap; +use std::fmt; +use std::iter::repeat; +use std::mem; + +use exec::ProgramCache; +use prog::{Inst, Program}; +use sparse::SparseSet; + +/// Return true if and only if the given program can be executed by a DFA. +/// +/// Generally, a DFA is always possible. A pathological case where it is not +/// possible is if the number of NFA states exceeds `u32::MAX`, in which case, +/// this function will return false. +/// +/// This function will also return false if the given program has any Unicode +/// instructions (Char or Ranges) since the DFA operates on bytes only. +pub fn can_exec(insts: &Program) -> bool { + use prog::Inst::*; + // If for some reason we manage to allocate a regex program with more + // than i32::MAX instructions, then we can't execute the DFA because we + // use 32 bit instruction pointer deltas for memory savings. + // If i32::MAX is the largest positive delta, + // then -i32::MAX == i32::MIN + 1 is the largest negative delta, + // and we are OK to use 32 bits. + if insts.dfa_size_limit == 0 || insts.len() > ::std::i32::MAX as usize { + return false; + } + for inst in insts { + match *inst { + Char(_) | Ranges(_) => return false, + EmptyLook(_) | Match(_) | Save(_) | Split(_) | Bytes(_) => {} + } + } + true +} + +/// A reusable cache of DFA states. +/// +/// This cache is reused between multiple invocations of the same regex +/// program. (It is not shared simultaneously between threads. If there is +/// contention, then new caches are created.) +#[derive(Clone, Debug)] +pub struct Cache { + /// Group persistent DFA related cache state together. The sparse sets + /// listed below are used as scratch space while computing uncached states. + inner: CacheInner, + /// qcur and qnext are ordered sets with constant time + /// addition/membership/clearing-whole-set and linear time iteration. They + /// are used to manage the sets of NFA states in DFA states when computing + /// cached DFA states. In particular, the order of the NFA states matters + /// for leftmost-first style matching. Namely, when computing a cached + /// state, the set of NFA states stops growing as soon as the first Match + /// instruction is observed. + qcur: SparseSet, + qnext: SparseSet, +} + +/// `CacheInner` is logically just a part of Cache, but groups together fields +/// that aren't passed as function parameters throughout search. (This split +/// is mostly an artifact of the borrow checker. It is happily paid.) +#[derive(Clone, Debug)] +struct CacheInner { + /// A cache of pre-compiled DFA states, keyed by the set of NFA states + /// and the set of empty-width flags set at the byte in the input when the + /// state was observed. + /// + /// A StatePtr is effectively a `*State`, but to avoid various inconvenient + /// things, we just pass indexes around manually. The performance impact of + /// this is probably an instruction or two in the inner loop. However, on + /// 64 bit, each StatePtr is half the size of a *State. + compiled: HashMap, + /// The transition table. + /// + /// The transition table is laid out in row-major order, where states are + /// rows and the transitions for each state are columns. At a high level, + /// given state `s` and byte `b`, the next state can be found at index + /// `s * 256 + b`. + /// + /// This is, of course, a lie. A StatePtr is actually a pointer to the + /// *start* of a row in this table. When indexing in the DFA's inner loop, + /// this removes the need to multiply the StatePtr by the stride. Yes, it + /// matters. This reduces the number of states we can store, but: the + /// stride is rarely 256 since we define transitions in terms of + /// *equivalence classes* of bytes. Each class corresponds to a set of + /// bytes that never discriminate a distinct path through the DFA from each + /// other. + trans: Transitions, + /// Our set of states. Note that `StatePtr / num_byte_classes` indexes + /// this Vec rather than just a `StatePtr`. + states: Vec, + /// A set of cached start states, which are limited to the number of + /// permutations of flags set just before the initial byte of input. (The + /// index into this vec is a `EmptyFlags`.) + /// + /// N.B. A start state can be "dead" (i.e., no possible match), so we + /// represent it with a StatePtr. + start_states: Vec, + /// Stack scratch space used to follow epsilon transitions in the NFA. + /// (This permits us to avoid recursion.) + /// + /// The maximum stack size is the number of NFA states. + stack: Vec, + /// The total number of times this cache has been flushed by the DFA + /// because of space constraints. + flush_count: u64, + /// The total heap size of the DFA's cache. We use this to determine when + /// we should flush the cache. + size: usize, +} + +/// The transition table. +/// +/// It is laid out in row-major order, with states as rows and byte class +/// transitions as columns. +/// +/// The transition table is responsible for producing valid `StatePtrs`. A +/// `StatePtr` points to the start of a particular row in this table. When +/// indexing to find the next state this allows us to avoid a multiplication +/// when computing an index into the table. +#[derive(Clone)] +struct Transitions { + /// The table. + table: Vec, + /// The stride. + num_byte_classes: usize, +} + +/// Fsm encapsulates the actual execution of the DFA. +#[derive(Debug)] +pub struct Fsm<'a> { + /// prog contains the NFA instruction opcodes. DFA execution uses either + /// the `dfa` instructions or the `dfa_reverse` instructions from + /// `exec::ExecReadOnly`. (It never uses `ExecReadOnly.nfa`, which may have + /// Unicode opcodes that cannot be executed by the DFA.) + prog: &'a Program, + /// The start state. We record it here because the pointer may change + /// when the cache is wiped. + start: StatePtr, + /// The current position in the input. + at: usize, + /// Should we quit after seeing the first match? e.g., When the caller + /// uses `is_match` or `shortest_match`. + quit_after_match: bool, + /// The last state that matched. + /// + /// When no match has occurred, this is set to STATE_UNKNOWN. + /// + /// This is only useful when matching regex sets. The last match state + /// is useful because it contains all of the match instructions seen, + /// thereby allowing us to enumerate which regexes in the set matched. + last_match_si: StatePtr, + /// The input position of the last cache flush. We use this to determine + /// if we're thrashing in the cache too often. If so, the DFA quits so + /// that we can fall back to the NFA algorithm. + last_cache_flush: usize, + /// All cached DFA information that is persisted between searches. + cache: &'a mut CacheInner, +} + +/// The result of running the DFA. +/// +/// Generally, the result is either a match or not a match, but sometimes the +/// DFA runs too slowly because the cache size is too small. In that case, it +/// gives up with the intent of falling back to the NFA algorithm. +/// +/// The DFA can also give up if it runs out of room to create new states, or if +/// it sees non-ASCII bytes in the presence of a Unicode word boundary. +#[derive(Clone, Debug)] +pub enum Result { + Match(T), + NoMatch(usize), + Quit, +} + +impl Result { + /// Returns true if this result corresponds to a match. + pub fn is_match(&self) -> bool { + match *self { + Result::Match(_) => true, + Result::NoMatch(_) | Result::Quit => false, + } + } + + /// Maps the given function onto T and returns the result. + /// + /// If this isn't a match, then this is a no-op. + pub fn map U>(self, mut f: F) -> Result { + match self { + Result::Match(t) => Result::Match(f(t)), + Result::NoMatch(x) => Result::NoMatch(x), + Result::Quit => Result::Quit, + } + } + + /// Sets the non-match position. + /// + /// If this isn't a non-match, then this is a no-op. + fn set_non_match(self, at: usize) -> Result { + match self { + Result::NoMatch(_) => Result::NoMatch(at), + r => r, + } + } +} + +/// `State` is a DFA state. It contains an ordered set of NFA states (not +/// necessarily complete) and a smattering of flags. +/// +/// The flags are packed into the first byte of data. +/// +/// States don't carry their transitions. Instead, transitions are stored in +/// a single row-major table. +/// +/// Delta encoding is used to store the instruction pointers. +/// The first instruction pointer is stored directly starting +/// at data[1], and each following pointer is stored as an offset +/// to the previous one. If a delta is in the range -127..127, +/// it is packed into a single byte; Otherwise the byte 128 (-128 as an i8) +/// is coded as a flag, followed by 4 bytes encoding the delta. +#[derive(Clone, Eq, Hash, PartialEq)] +struct State{ + data: Box<[u8]>, +} + +/// `InstPtr` is a 32 bit pointer into a sequence of opcodes (i.e., it indexes +/// an NFA state). +/// +/// Throughout this library, this is usually set to `usize`, but we force a +/// `u32` here for the DFA to save on space. +type InstPtr = u32; + +/// Adds ip to data using delta encoding with respect to prev. +/// +/// After completion, `data` will contain `ip` and `prev` will be set to `ip`. +fn push_inst_ptr(data: &mut Vec, prev: &mut InstPtr, ip: InstPtr) { + let delta = (ip as i32) - (*prev as i32); + write_vari32(data, delta); + *prev = ip; +} + +struct InstPtrs<'a> { + base: usize, + data: &'a [u8], +} + +impl <'a>Iterator for InstPtrs<'a> { + type Item = usize; + + fn next(&mut self) -> Option { + if self.data.is_empty() { + return None; + } + let (delta, nread) = read_vari32(self.data); + let base = self.base as i32 + delta; + debug_assert!(base >= 0); + debug_assert!(nread > 0); + self.data = &self.data[nread..]; + self.base = base as usize; + Some(self.base) + } +} + +impl State { + fn flags(&self) -> StateFlags { + StateFlags(self.data[0]) + } + + fn inst_ptrs(&self) -> InstPtrs { + InstPtrs { + base: 0, + data: &self.data[1..], + } + } +} + +/// `StatePtr` is a 32 bit pointer to the start of a row in the transition +/// table. +/// +/// It has many special values. There are two types of special values: +/// sentinels and flags. +/// +/// Sentinels corresponds to special states that carry some kind of +/// significance. There are three such states: unknown, dead and quit states. +/// +/// Unknown states are states that haven't been computed yet. They indicate +/// that a transition should be filled in that points to either an existing +/// cached state or a new state altogether. In general, an unknown state means +/// "follow the NFA's epsilon transitions." +/// +/// Dead states are states that can never lead to a match, no matter what +/// subsequent input is observed. This means that the DFA should quit +/// immediately and return the longest match it has found thus far. +/// +/// Quit states are states that imply the DFA is not capable of matching the +/// regex correctly. Currently, this is only used when a Unicode word boundary +/// exists in the regex *and* a non-ASCII byte is observed. +/// +/// The other type of state pointer is a state pointer with special flag bits. +/// There are two flags: a start flag and a match flag. The lower bits of both +/// kinds always contain a "valid" `StatePtr` (indicated by the `STATE_MAX` +/// mask). +/// +/// The start flag means that the state is a start state, and therefore may be +/// subject to special prefix scanning optimizations. +/// +/// The match flag means that the state is a match state, and therefore the +/// current position in the input (while searching) should be recorded. +/// +/// The above exists mostly in the service of making the inner loop fast. +/// In particular, the inner *inner* loop looks something like this: +/// +/// ```ignore +/// while state <= STATE_MAX and i < len(text): +/// state = state.next[i] +/// ``` +/// +/// This is nice because it lets us execute a lazy DFA as if it were an +/// entirely offline DFA (i.e., with very few instructions). The loop will +/// quit only when we need to examine a case that needs special attention. +type StatePtr = u32; + +/// An unknown state means that the state has not been computed yet, and that +/// the only way to progress is to compute it. +const STATE_UNKNOWN: StatePtr = 1<<31; + +/// A dead state means that the state has been computed and it is known that +/// once it is entered, no future match can ever occur. +const STATE_DEAD: StatePtr = STATE_UNKNOWN + 1; + +/// A quit state means that the DFA came across some input that it doesn't +/// know how to process correctly. The DFA should quit and another matching +/// engine should be run in its place. +const STATE_QUIT: StatePtr = STATE_DEAD + 1; + +/// A start state is a state that the DFA can start in. +/// +/// Note that start states have their lower bits set to a state pointer. +const STATE_START: StatePtr = 1<<30; + +/// A match state means that the regex has successfully matched. +/// +/// Note that match states have their lower bits set to a state pointer. +const STATE_MATCH: StatePtr = 1<<29; + +/// The maximum state pointer. This is useful to mask out the "valid" state +/// pointer from a state with the "start" or "match" bits set. +/// +/// It doesn't make sense to use this with unknown, dead or quit state +/// pointers, since those pointers are sentinels and never have their lower +/// bits set to anything meaningful. +const STATE_MAX: StatePtr = STATE_MATCH - 1; + +/// Byte is a u8 in spirit, but a u16 in practice so that we can represent the +/// special EOF sentinel value. +#[derive(Copy, Clone, Debug)] +struct Byte(u16); + +/// A set of flags for zero-width assertions. +#[derive(Clone, Copy, Eq, Debug, Default, Hash, PartialEq)] +struct EmptyFlags { + start: bool, + end: bool, + start_line: bool, + end_line: bool, + word_boundary: bool, + not_word_boundary: bool, +} + +/// A set of flags describing various configurations of a DFA state. This is +/// represented by a `u8` so that it is compact. +#[derive(Clone, Copy, Eq, Default, Hash, PartialEq)] +struct StateFlags(u8); + +impl Cache { + /// Create new empty cache for the DFA engine. + pub fn new(prog: &Program) -> Self { + // We add 1 to account for the special EOF byte. + let num_byte_classes = (prog.byte_classes[255] as usize + 1) + 1; + let starts = vec![STATE_UNKNOWN; 256]; + let mut cache = Cache { + inner: CacheInner { + compiled: HashMap::new(), + trans: Transitions::new(num_byte_classes), + states: vec![], + start_states: starts, + stack: vec![], + flush_count: 0, + size: 0, + }, + qcur: SparseSet::new(prog.insts.len()), + qnext: SparseSet::new(prog.insts.len()), + }; + cache.inner.reset_size(); + cache + } +} + +impl CacheInner { + /// Resets the cache size to account for fixed costs, such as the program + /// and stack sizes. + fn reset_size(&mut self) { + self.size = + (self.start_states.len() * mem::size_of::()) + + (self.stack.len() * mem::size_of::()); + } +} + +impl<'a> Fsm<'a> { + #[inline(always)] // reduces constant overhead + pub fn forward( + prog: &'a Program, + cache: &ProgramCache, + quit_after_match: bool, + text: &[u8], + at: usize, + ) -> Result { + let mut cache = cache.borrow_mut(); + let cache = &mut cache.dfa; + let mut dfa = Fsm { + prog: prog, + start: 0, // filled in below + at: at, + quit_after_match: quit_after_match, + last_match_si: STATE_UNKNOWN, + last_cache_flush: at, + cache: &mut cache.inner, + }; + let (empty_flags, state_flags) = dfa.start_flags(text, at); + dfa.start = match dfa.start_state( + &mut cache.qcur, + empty_flags, + state_flags, + ) { + None => return Result::Quit, + Some(STATE_DEAD) => return Result::NoMatch(at), + Some(si) => si, + }; + debug_assert!(dfa.start != STATE_UNKNOWN); + dfa.exec_at(&mut cache.qcur, &mut cache.qnext, text) + } + + #[inline(always)] // reduces constant overhead + pub fn reverse( + prog: &'a Program, + cache: &ProgramCache, + quit_after_match: bool, + text: &[u8], + at: usize, + ) -> Result { + let mut cache = cache.borrow_mut(); + let cache = &mut cache.dfa_reverse; + let mut dfa = Fsm { + prog: prog, + start: 0, // filled in below + at: at, + quit_after_match: quit_after_match, + last_match_si: STATE_UNKNOWN, + last_cache_flush: at, + cache: &mut cache.inner, + }; + let (empty_flags, state_flags) = dfa.start_flags_reverse(text, at); + dfa.start = match dfa.start_state( + &mut cache.qcur, + empty_flags, + state_flags, + ) { + None => return Result::Quit, + Some(STATE_DEAD) => return Result::NoMatch(at), + Some(si) => si, + }; + debug_assert!(dfa.start != STATE_UNKNOWN); + dfa.exec_at_reverse(&mut cache.qcur, &mut cache.qnext, text) + } + + #[inline(always)] // reduces constant overhead + pub fn forward_many( + prog: &'a Program, + cache: &ProgramCache, + matches: &mut [bool], + text: &[u8], + at: usize, + ) -> Result { + debug_assert!(matches.len() == prog.matches.len()); + let mut cache = cache.borrow_mut(); + let cache = &mut cache.dfa; + let mut dfa = Fsm { + prog: prog, + start: 0, // filled in below + at: at, + quit_after_match: false, + last_match_si: STATE_UNKNOWN, + last_cache_flush: at, + cache: &mut cache.inner, + }; + let (empty_flags, state_flags) = dfa.start_flags(text, at); + dfa.start = match dfa.start_state( + &mut cache.qcur, + empty_flags, + state_flags, + ) { + None => return Result::Quit, + Some(STATE_DEAD) => return Result::NoMatch(at), + Some(si) => si, + }; + debug_assert!(dfa.start != STATE_UNKNOWN); + let result = dfa.exec_at(&mut cache.qcur, &mut cache.qnext, text); + if result.is_match() { + if matches.len() == 1 { + matches[0] = true; + } else { + debug_assert!(dfa.last_match_si != STATE_UNKNOWN); + debug_assert!(dfa.last_match_si != STATE_DEAD); + for ip in dfa.state(dfa.last_match_si).inst_ptrs() { + if let Inst::Match(slot) = dfa.prog[ip] { + matches[slot] = true; + } + } + } + } + result + } + + /// Executes the DFA on a forward NFA. + /// + /// {qcur,qnext} are scratch ordered sets which may be non-empty. + #[inline(always)] // reduces constant overhead + fn exec_at( + &mut self, + qcur: &mut SparseSet, + qnext: &mut SparseSet, + text: &[u8], + ) -> Result { + // For the most part, the DFA is basically: + // + // last_match = null + // while current_byte != EOF: + // si = current_state.next[current_byte] + // if si is match + // last_match = si + // return last_match + // + // However, we need to deal with a few things: + // + // 1. This is an *online* DFA, so the current state's next list + // may not point to anywhere yet, so we must go out and compute + // them. (They are then cached into the current state's next list + // to avoid re-computation.) + // 2. If we come across a state that is known to be dead (i.e., never + // leads to a match), then we can quit early. + // 3. If the caller just wants to know if a match occurs, then we + // can quit as soon as we know we have a match. (Full leftmost + // first semantics require continuing on.) + // 4. If we're in the start state, then we can use a pre-computed set + // of prefix literals to skip quickly along the input. + // 5. After the input is exhausted, we run the DFA on one symbol + // that stands for EOF. This is useful for handling empty width + // assertions. + // 6. We can't actually do state.next[byte]. Instead, we have to do + // state.next[byte_classes[byte]], which permits us to keep the + // 'next' list very small. + // + // Since there's a bunch of extra stuff we need to consider, we do some + // pretty hairy tricks to get the inner loop to run as fast as + // possible. + debug_assert!(!self.prog.is_reverse); + + // The last match is the currently known ending match position. It is + // reported as an index to the most recent byte that resulted in a + // transition to a match state and is always stored in capture slot `1` + // when searching forwards. Its maximum value is `text.len()`. + let mut result = Result::NoMatch(self.at); + let (mut prev_si, mut next_si) = (self.start, self.start); + let mut at = self.at; + while at < text.len() { + // This is the real inner loop. We take advantage of special bits + // set in the state pointer to determine whether a state is in the + // "common" case or not. Specifically, the common case is a + // non-match non-start non-dead state that has already been + // computed. So long as we remain in the common case, this inner + // loop will chew through the input. + // + // We also unroll the loop 4 times to amortize the cost of checking + // whether we've consumed the entire input. We are also careful + // to make sure that `prev_si` always represents the previous state + // and `next_si` always represents the next state after the loop + // exits, even if it isn't always true inside the loop. + while next_si <= STATE_MAX && at < text.len() { + // Argument for safety is in the definition of next_si. + prev_si = unsafe { self.next_si(next_si, text, at) }; + at += 1; + if prev_si > STATE_MAX || at + 2 >= text.len() { + mem::swap(&mut prev_si, &mut next_si); + break; + } + next_si = unsafe { self.next_si(prev_si, text, at) }; + at += 1; + if next_si > STATE_MAX { + break; + } + prev_si = unsafe { self.next_si(next_si, text, at) }; + at += 1; + if prev_si > STATE_MAX { + mem::swap(&mut prev_si, &mut next_si); + break; + } + next_si = unsafe { self.next_si(prev_si, text, at) }; + at += 1; + } + if next_si & STATE_MATCH > 0 { + // A match state is outside of the common case because it needs + // special case analysis. In particular, we need to record the + // last position as having matched and possibly quit the DFA if + // we don't need to keep matching. + next_si &= !STATE_MATCH; + result = Result::Match(at - 1); + if self.quit_after_match { + return result; + } + self.last_match_si = next_si; + prev_si = next_si; + + // This permits short-circuiting when matching a regex set. + // In particular, if this DFA state contains only match states, + // then it's impossible to extend the set of matches since + // match states are final. Therefore, we can quit. + if self.prog.matches.len() > 1 { + let state = self.state(next_si); + let just_matches = state.inst_ptrs() + .all(|ip| self.prog[ip].is_match()); + if just_matches { + return result; + } + } + + // Another inner loop! If the DFA stays in this particular + // match state, then we can rip through all of the input + // very quickly, and only recording the match location once + // we've left this particular state. + let cur = at; + while (next_si & !STATE_MATCH) == prev_si + && at + 2 < text.len() { + // Argument for safety is in the definition of next_si. + next_si = unsafe { + self.next_si(next_si & !STATE_MATCH, text, at) + }; + at += 1; + } + if at > cur { + result = Result::Match(at - 2); + } + } else if next_si & STATE_START > 0 { + // A start state isn't in the common case because we may + // what to do quick prefix scanning. If the program doesn't + // have a detected prefix, then start states are actually + // considered common and this case is never reached. + debug_assert!(self.has_prefix()); + next_si &= !STATE_START; + prev_si = next_si; + at = match self.prefix_at(text, at) { + None => return Result::NoMatch(text.len()), + Some(i) => i, + }; + } else if next_si >= STATE_UNKNOWN { + if next_si == STATE_QUIT { + return Result::Quit; + } + // Finally, this corresponds to the case where the transition + // entered a state that can never lead to a match or a state + // that hasn't been computed yet. The latter being the "slow" + // path. + let byte = Byte::byte(text[at - 1]); + // We no longer care about the special bits in the state + // pointer. + prev_si &= STATE_MAX; + // Record where we are. This is used to track progress for + // determining whether we should quit if we've flushed the + // cache too much. + self.at = at; + next_si = match self.next_state(qcur, qnext, prev_si, byte) { + None => return Result::Quit, + Some(STATE_DEAD) => return result.set_non_match(at), + Some(si) => si, + }; + debug_assert!(next_si != STATE_UNKNOWN); + if next_si & STATE_MATCH > 0 { + next_si &= !STATE_MATCH; + result = Result::Match(at - 1); + if self.quit_after_match { + return result; + } + self.last_match_si = next_si; + } + prev_si = next_si; + } else { + prev_si = next_si; + } + } + + // Run the DFA once more on the special EOF senitnel value. + // We don't care about the special bits in the state pointer any more, + // so get rid of them. + prev_si &= STATE_MAX; + prev_si = match self.next_state(qcur, qnext, prev_si, Byte::eof()) { + None => return Result::Quit, + Some(STATE_DEAD) => return result.set_non_match(text.len()), + Some(si) => si & !STATE_START, + }; + debug_assert!(prev_si != STATE_UNKNOWN); + if prev_si & STATE_MATCH > 0 { + prev_si &= !STATE_MATCH; + self.last_match_si = prev_si; + result = Result::Match(text.len()); + } + result + } + + /// Executes the DFA on a reverse NFA. + #[inline(always)] // reduces constant overhead + fn exec_at_reverse( + &mut self, + qcur: &mut SparseSet, + qnext: &mut SparseSet, + text: &[u8], + ) -> Result { + // The comments in `exec_at` above mostly apply here too. The main + // difference is that we move backwards over the input and we look for + // the longest possible match instead of the leftmost-first match. + // + // N.B. The code duplication here is regrettable. Efforts to improve + // it without sacrificing performance are welcome. ---AG + debug_assert!(self.prog.is_reverse); + let mut result = Result::NoMatch(self.at); + let (mut prev_si, mut next_si) = (self.start, self.start); + let mut at = self.at; + while at > 0 { + while next_si <= STATE_MAX && at > 0 { + // Argument for safety is in the definition of next_si. + at -= 1; + prev_si = unsafe { self.next_si(next_si, text, at) }; + if prev_si > STATE_MAX || at <= 4 { + mem::swap(&mut prev_si, &mut next_si); + break; + } + at -= 1; + next_si = unsafe { self.next_si(prev_si, text, at) }; + if next_si > STATE_MAX { + break; + } + at -= 1; + prev_si = unsafe { self.next_si(next_si, text, at) }; + if prev_si > STATE_MAX { + mem::swap(&mut prev_si, &mut next_si); + break; + } + at -= 1; + next_si = unsafe { self.next_si(prev_si, text, at) }; + } + if next_si & STATE_MATCH > 0 { + next_si &= !STATE_MATCH; + result = Result::Match(at + 1); + if self.quit_after_match { + return result + } + self.last_match_si = next_si; + prev_si = next_si; + let cur = at; + while (next_si & !STATE_MATCH) == prev_si && at >= 2 { + // Argument for safety is in the definition of next_si. + at -= 1; + next_si = unsafe { + self.next_si(next_si & !STATE_MATCH, text, at) + }; + } + if at < cur { + result = Result::Match(at + 2); + } + } else if next_si >= STATE_UNKNOWN { + if next_si == STATE_QUIT { + return Result::Quit; + } + let byte = Byte::byte(text[at]); + prev_si &= STATE_MAX; + self.at = at; + next_si = match self.next_state(qcur, qnext, prev_si, byte) { + None => return Result::Quit, + Some(STATE_DEAD) => return result.set_non_match(at), + Some(si) => si, + }; + debug_assert!(next_si != STATE_UNKNOWN); + if next_si & STATE_MATCH > 0 { + next_si &= !STATE_MATCH; + result = Result::Match(at + 1); + if self.quit_after_match { + return result; + } + self.last_match_si = next_si; + } + prev_si = next_si; + } else { + prev_si = next_si; + } + } + + // Run the DFA once more on the special EOF senitnel value. + prev_si = match self.next_state(qcur, qnext, prev_si, Byte::eof()) { + None => return Result::Quit, + Some(STATE_DEAD) => return result.set_non_match(0), + Some(si) => si, + }; + debug_assert!(prev_si != STATE_UNKNOWN); + if prev_si & STATE_MATCH > 0 { + prev_si &= !STATE_MATCH; + self.last_match_si = prev_si; + result = Result::Match(0); + } + result + } + + /// next_si transitions to the next state, where the transition input + /// corresponds to text[i]. + /// + /// This elides bounds checks, and is therefore unsafe. + #[inline(always)] + unsafe fn next_si(&self, si: StatePtr, text: &[u8], i: usize) -> StatePtr { + // What is the argument for safety here? + // We have three unchecked accesses that could possibly violate safety: + // + // 1. The given byte of input (`text[i]`). + // 2. The class of the byte of input (`classes[text[i]]`). + // 3. The transition for the class (`trans[si + cls]`). + // + // (1) is only safe when calling next_si is guarded by + // `i < text.len()`. + // + // (2) is the easiest case to guarantee since `text[i]` is always a + // `u8` and `self.prog.byte_classes` always has length `u8::MAX`. + // (See `ByteClassSet.byte_classes` in `compile.rs`.) + // + // (3) is only safe if (1)+(2) are safe. Namely, the transitions + // of every state are defined to have length equal to the number of + // byte classes in the program. Therefore, a valid class leads to a + // valid transition. (All possible transitions are valid lookups, even + // if it points to a state that hasn't been computed yet.) (3) also + // relies on `si` being correct, but StatePtrs should only ever be + // retrieved from the transition table, which ensures they are correct. + debug_assert!(i < text.len()); + let b = *text.get_unchecked(i); + debug_assert!((b as usize) < self.prog.byte_classes.len()); + let cls = *self.prog.byte_classes.get_unchecked(b as usize); + self.cache.trans.next_unchecked(si, cls as usize) + } + + /// Computes the next state given the current state and the current input + /// byte (which may be EOF). + /// + /// If STATE_DEAD is returned, then there is no valid state transition. + /// This implies that no permutation of future input can lead to a match + /// state. + /// + /// STATE_UNKNOWN can never be returned. + fn exec_byte( + &mut self, + qcur: &mut SparseSet, + qnext: &mut SparseSet, + mut si: StatePtr, + b: Byte, + ) -> Option { + use prog::Inst::*; + + // Initialize a queue with the current DFA state's NFA states. + qcur.clear(); + for ip in self.state(si).inst_ptrs() { + qcur.insert(ip); + } + + // Before inspecting the current byte, we may need to also inspect + // whether the position immediately preceding the current byte + // satisfies the empty assertions found in the current state. + // + // We only need to do this step if there are any empty assertions in + // the current state. + let is_word_last = self.state(si).flags().is_word(); + let is_word = b.is_ascii_word(); + if self.state(si).flags().has_empty() { + // Compute the flags immediately preceding the current byte. + // This means we only care about the "end" or "end line" flags. + // (The "start" flags are computed immediately proceding the + // current byte and is handled below.) + let mut flags = EmptyFlags::default(); + if b.is_eof() { + flags.end = true; + flags.end_line = true; + } else if b.as_byte().map_or(false, |b| b == b'\n') { + flags.end_line = true; + } + if is_word_last == is_word { + flags.not_word_boundary = true; + } else { + flags.word_boundary = true; + } + // Now follow epsilon transitions from every NFA state, but make + // sure we only follow transitions that satisfy our flags. + qnext.clear(); + for &ip in &*qcur { + self.follow_epsilons(usize_to_u32(ip), qnext, flags); + } + mem::swap(qcur, qnext); + } + + // Now we set flags for immediately after the current byte. Since start + // states are processed separately, and are the only states that can + // have the StartText flag set, we therefore only need to worry about + // the StartLine flag here. + // + // We do also keep track of whether this DFA state contains a NFA state + // that is a matching state. This is precisely how we delay the DFA + // matching by one byte in order to process the special EOF sentinel + // byte. Namely, if this DFA state containing a matching NFA state, + // then it is the *next* DFA state that is marked as a match. + let mut empty_flags = EmptyFlags::default(); + let mut state_flags = StateFlags::default(); + empty_flags.start_line = b.as_byte().map_or(false, |b| b == b'\n'); + if b.is_ascii_word() { + state_flags.set_word(); + } + // Now follow all epsilon transitions again, but only after consuming + // the current byte. + qnext.clear(); + for &ip in &*qcur { + match self.prog[ip as usize] { + // These states never happen in a byte-based program. + Char(_) | Ranges(_) => unreachable!(), + // These states are handled when following epsilon transitions. + Save(_) | Split(_) | EmptyLook(_) => {} + Match(_) => { + state_flags.set_match(); + if !self.continue_past_first_match() { + break; + } else if self.prog.matches.len() > 1 + && !qnext.contains(ip as usize) { + // If we are continuing on to find other matches, + // then keep a record of the match states we've seen. + qnext.insert(ip); + } + } + Bytes(ref inst) => { + if b.as_byte().map_or(false, |b| inst.matches(b)) { + self.follow_epsilons( + inst.goto as InstPtr, qnext, empty_flags); + } + } + } + } + + let cache = + if b.is_eof() && self.prog.matches.len() > 1 { + // If we're processing the last byte of the input and we're + // matching a regex set, then make the next state contain the + // previous states transitions. We do this so that the main + // matching loop can extract all of the match instructions. + mem::swap(qcur, qnext); + // And don't cache this state because it's totally bunk. + false + } else { + true + }; + + // We've now built up the set of NFA states that ought to comprise the + // next DFA state, so try to find it in the cache, and if it doesn't + // exist, cache it. + // + // N.B. We pass `&mut si` here because the cache may clear itself if + // it has gotten too full. When that happens, the location of the + // current state may change. + let mut next = match self.cached_state( + qnext, + state_flags, + Some(&mut si), + ) { + None => return None, + Some(next) => next, + }; + if (self.start & !STATE_START) == next { + // Start states can never be match states since all matches are + // delayed by one byte. + debug_assert!(!self.state(next).flags().is_match()); + next = self.start_ptr(next); + } + if next <= STATE_MAX && self.state(next).flags().is_match() { + next |= STATE_MATCH; + } + debug_assert!(next != STATE_UNKNOWN); + // And now store our state in the current state's next list. + if cache { + let cls = self.byte_class(b); + self.cache.trans.set_next(si, cls, next); + } + Some(next) + } + + /// Follows the epsilon transitions starting at (and including) `ip`. The + /// resulting states are inserted into the ordered set `q`. + /// + /// Conditional epsilon transitions (i.e., empty width assertions) are only + /// followed if they are satisfied by the given flags, which should + /// represent the flags set at the current location in the input. + /// + /// If the current location corresponds to the empty string, then only the + /// end line and/or end text flags may be set. If the current location + /// corresponds to a real byte in the input, then only the start line + /// and/or start text flags may be set. + /// + /// As an exception to the above, when finding the initial state, any of + /// the above flags may be set: + /// + /// If matching starts at the beginning of the input, then start text and + /// start line should be set. If the input is empty, then end text and end + /// line should also be set. + /// + /// If matching starts after the beginning of the input, then only start + /// line should be set if the preceding byte is `\n`. End line should never + /// be set in this case. (Even if the proceding byte is a `\n`, it will + /// be handled in a subsequent DFA state.) + fn follow_epsilons( + &mut self, + ip: InstPtr, + q: &mut SparseSet, + flags: EmptyFlags, + ) { + use prog::Inst::*; + use prog::EmptyLook::*; + + // We need to traverse the NFA to follow epsilon transitions, so avoid + // recursion with an explicit stack. + self.cache.stack.push(ip); + while let Some(mut ip) = self.cache.stack.pop() { + // Try to munch through as many states as possible without + // pushes/pops to the stack. + loop { + // Don't visit states we've already added. + if q.contains(ip as usize) { + break; + } + q.insert(ip as usize); + match self.prog[ip as usize] { + Char(_) | Ranges(_) => unreachable!(), + Match(_) | Bytes(_) => { + break; + } + EmptyLook(ref inst) => { + // Only follow empty assertion states if our flags + // satisfy the assertion. + match inst.look { + StartLine if flags.start_line => { + ip = inst.goto as InstPtr; + } + EndLine if flags.end_line => { + ip = inst.goto as InstPtr; + } + StartText if flags.start => { + ip = inst.goto as InstPtr; + } + EndText if flags.end => { + ip = inst.goto as InstPtr; + } + WordBoundaryAscii if flags.word_boundary => { + ip = inst.goto as InstPtr; + } + NotWordBoundaryAscii if flags.not_word_boundary => { + ip = inst.goto as InstPtr; + } + WordBoundary if flags.word_boundary => { + ip = inst.goto as InstPtr; + } + NotWordBoundary if flags.not_word_boundary => { + ip = inst.goto as InstPtr; + } + StartLine | EndLine | StartText | EndText + | WordBoundaryAscii | NotWordBoundaryAscii + | WordBoundary | NotWordBoundary => { + break; + } + } + } + Save(ref inst) => { + ip = inst.goto as InstPtr; + } + Split(ref inst) => { + self.cache.stack.push(inst.goto2 as InstPtr); + ip = inst.goto1 as InstPtr; + } + } + } + } + } + + /// Find a previously computed state matching the given set of instructions + /// and is_match bool. + /// + /// The given set of instructions should represent a single state in the + /// NFA along with all states reachable without consuming any input. + /// + /// The is_match bool should be true if and only if the preceding DFA state + /// contains an NFA matching state. The cached state produced here will + /// then signify a match. (This enables us to delay a match by one byte, + /// in order to account for the EOF sentinel byte.) + /// + /// If the cache is full, then it is wiped before caching a new state. + /// + /// The current state should be specified if it exists, since it will need + /// to be preserved if the cache clears itself. (Start states are + /// always saved, so they should not be passed here.) It takes a mutable + /// pointer to the index because if the cache is cleared, the state's + /// location may change. + fn cached_state( + &mut self, + q: &SparseSet, + mut state_flags: StateFlags, + current_state: Option<&mut StatePtr>, + ) -> Option { + // If we couldn't come up with a non-empty key to represent this state, + // then it is dead and can never lead to a match. + // + // Note that inst_flags represent the set of empty width assertions + // in q. We use this as an optimization in exec_byte to determine when + // we should follow epsilon transitions at the empty string preceding + // the current byte. + let key = match self.cached_state_key(q, &mut state_flags) { + None => return Some(STATE_DEAD), + Some(v) => v, + }; + // In the cache? Cool. Done. + if let Some(&si) = self.cache.compiled.get(&key) { + return Some(si); + } + // If the cache has gotten too big, wipe it. + if self.approximate_size() > self.prog.dfa_size_limit + && !self.clear_cache_and_save(current_state) + { + // Ooops. DFA is giving up. + return None; + } + // Allocate room for our state and add it. + self.add_state(key) + } + + /// Produces a key suitable for describing a state in the DFA cache. + /// + /// The key invariant here is that equivalent keys are produced for any two + /// sets of ordered NFA states (and toggling of whether the previous NFA + /// states contain a match state) that do not discriminate a match for any + /// input. + /// + /// Specifically, q should be an ordered set of NFA states and is_match + /// should be true if and only if the previous NFA states contained a match + /// state. + fn cached_state_key( + &mut self, + q: &SparseSet, + state_flags: &mut StateFlags, + ) -> Option { + use prog::Inst::*; + + // We need to build up enough information to recognize pre-built states + // in the DFA. Generally speaking, this includes every instruction + // except for those which are purely epsilon transitions, e.g., the + // Save and Split instructions. + // + // Empty width assertions are also epsilon transitions, but since they + // are conditional, we need to make them part of a state's key in the + // cache. + + // Reserve 1 byte for flags. + let mut insts = vec![0]; + let mut prev = 0; + for &ip in q { + let ip = usize_to_u32(ip); + match self.prog[ip as usize] { + Char(_) | Ranges(_) => unreachable!(), + Save(_) | Split(_) => {} + Bytes(_) => push_inst_ptr(&mut insts, &mut prev, ip), + EmptyLook(_) => { + state_flags.set_empty(); + push_inst_ptr(&mut insts, &mut prev, ip) + } + Match(_) => { + push_inst_ptr(&mut insts, &mut prev, ip); + if !self.continue_past_first_match() { + break; + } + } + } + } + // If we couldn't transition to any other instructions and we didn't + // see a match when expanding NFA states previously, then this is a + // dead state and no amount of additional input can transition out + // of this state. + if insts.len() == 1 && !state_flags.is_match() { + None + } else { + let StateFlags(f) = *state_flags; + insts[0] = f; + Some(State { data: insts.into_boxed_slice() }) + } + } + + /// Clears the cache, but saves and restores current_state if it is not + /// none. + /// + /// The current state must be provided here in case its location in the + /// cache changes. + /// + /// This returns false if the cache is not cleared and the DFA should + /// give up. + fn clear_cache_and_save( + &mut self, + current_state: Option<&mut StatePtr>, + ) -> bool { + if self.cache.states.is_empty() { + // Nothing to clear... + return true; + } + match current_state { + None => self.clear_cache(), + Some(si) => { + let cur = self.state(*si).clone(); + if !self.clear_cache() { + return false; + } + // The unwrap is OK because we just cleared the cache and + // therefore know that the next state pointer won't exceed + // STATE_MAX. + *si = self.restore_state(cur).unwrap(); + true + } + } + } + + /// Wipes the state cache, but saves and restores the current start state. + /// + /// This returns false if the cache is not cleared and the DFA should + /// give up. + fn clear_cache(&mut self) -> bool { + // Bail out of the DFA if we're moving too "slowly." + // A heuristic from RE2: assume the DFA is too slow if it is processing + // 10 or fewer bytes per state. + // Additionally, we permit the cache to be flushed a few times before + // caling it quits. + let nstates = self.cache.states.len(); + if self.cache.flush_count >= 3 + && self.at >= self.last_cache_flush + && (self.at - self.last_cache_flush) <= 10 * nstates { + return false; + } + // Update statistics tracking cache flushes. + self.last_cache_flush = self.at; + self.cache.flush_count += 1; + + // OK, actually flush the cache. + let start = self.state(self.start & !STATE_START).clone(); + let last_match = if self.last_match_si <= STATE_MAX { + Some(self.state(self.last_match_si).clone()) + } else { + None + }; + self.cache.reset_size(); + self.cache.trans.clear(); + self.cache.states.clear(); + self.cache.compiled.clear(); + for s in &mut self.cache.start_states { + *s = STATE_UNKNOWN; + } + // The unwraps are OK because we just cleared the cache and therefore + // know that the next state pointer won't exceed STATE_MAX. + let start_ptr = self.restore_state(start).unwrap(); + self.start = self.start_ptr(start_ptr); + if let Some(last_match) = last_match { + self.last_match_si = self.restore_state(last_match).unwrap(); + } + true + } + + /// Restores the given state back into the cache, and returns a pointer + /// to it. + fn restore_state(&mut self, state: State) -> Option { + // If we've already stored this state, just return a pointer to it. + // None will be the wiser. + if let Some(&si) = self.cache.compiled.get(&state) { + return Some(si); + } + self.add_state(state) + } + + /// Returns the next state given the current state si and current byte + /// b. {qcur,qnext} are used as scratch space for storing ordered NFA + /// states. + /// + /// This tries to fetch the next state from the cache, but if that fails, + /// it computes the next state, caches it and returns a pointer to it. + /// + /// The pointer can be to a real state, or it can be STATE_DEAD. + /// STATE_UNKNOWN cannot be returned. + /// + /// None is returned if a new state could not be allocated (i.e., the DFA + /// ran out of space and thinks it's running too slowly). + fn next_state( + &mut self, + qcur: &mut SparseSet, + qnext: &mut SparseSet, + si: StatePtr, + b: Byte, + ) -> Option { + if si == STATE_DEAD { + return Some(STATE_DEAD); + } + match self.cache.trans.next(si, self.byte_class(b)) { + STATE_UNKNOWN => self.exec_byte(qcur, qnext, si, b), + STATE_QUIT => None, + STATE_DEAD => Some(STATE_DEAD), + nsi => Some(nsi), + } + } + + /// Computes and returns the start state, where searching begins at + /// position `at` in `text`. If the state has already been computed, + /// then it is pulled from the cache. If the state hasn't been cached, + /// then it is computed, cached and a pointer to it is returned. + /// + /// This may return STATE_DEAD but never STATE_UNKNOWN. + #[inline(always)] // reduces constant overhead + fn start_state( + &mut self, + q: &mut SparseSet, + empty_flags: EmptyFlags, + state_flags: StateFlags, + ) -> Option { + // Compute an index into our cache of start states based on the set + // of empty/state flags set at the current position in the input. We + // don't use every flag since not all flags matter. For example, since + // matches are delayed by one byte, start states can never be match + // states. + let flagi = { + (((empty_flags.start as u8) << 0) | + ((empty_flags.end as u8) << 1) | + ((empty_flags.start_line as u8) << 2) | + ((empty_flags.end_line as u8) << 3) | + ((empty_flags.word_boundary as u8) << 4) | + ((empty_flags.not_word_boundary as u8) << 5) | + ((state_flags.is_word() as u8) << 6)) + as usize + }; + match self.cache.start_states[flagi] { + STATE_UNKNOWN => {} + STATE_DEAD => return Some(STATE_DEAD), + si => return Some(si), + } + q.clear(); + let start = usize_to_u32(self.prog.start); + self.follow_epsilons(start, q, empty_flags); + // Start states can never be match states because we delay every match + // by one byte. Given an empty string and an empty match, the match + // won't actually occur until the DFA processes the special EOF + // sentinel byte. + let sp = match self.cached_state(q, state_flags, None) { + None => return None, + Some(sp) => self.start_ptr(sp), + }; + self.cache.start_states[flagi] = sp; + Some(sp) + } + + /// Computes the set of starting flags for the given position in text. + /// + /// This should only be used when executing the DFA forwards over the + /// input. + fn start_flags(&self, text: &[u8], at: usize) -> (EmptyFlags, StateFlags) { + let mut empty_flags = EmptyFlags::default(); + let mut state_flags = StateFlags::default(); + empty_flags.start = at == 0; + empty_flags.end = text.is_empty(); + empty_flags.start_line = at == 0 || text[at - 1] == b'\n'; + empty_flags.end_line = text.is_empty(); + + let is_word_last = at > 0 && Byte::byte(text[at - 1]).is_ascii_word(); + let is_word = at < text.len() && Byte::byte(text[at]).is_ascii_word(); + if is_word_last { + state_flags.set_word(); + } + if is_word == is_word_last { + empty_flags.not_word_boundary = true; + } else { + empty_flags.word_boundary = true; + } + (empty_flags, state_flags) + } + + /// Computes the set of starting flags for the given position in text. + /// + /// This should only be used when executing the DFA in reverse over the + /// input. + fn start_flags_reverse( + &self, + text: &[u8], + at: usize, + ) -> (EmptyFlags, StateFlags) { + let mut empty_flags = EmptyFlags::default(); + let mut state_flags = StateFlags::default(); + empty_flags.start = at == text.len(); + empty_flags.end = text.is_empty(); + empty_flags.start_line = at == text.len() || text[at] == b'\n'; + empty_flags.end_line = text.is_empty(); + + let is_word_last = + at < text.len() && Byte::byte(text[at]).is_ascii_word(); + let is_word = at > 0 && Byte::byte(text[at - 1]).is_ascii_word(); + if is_word_last { + state_flags.set_word(); + } + if is_word == is_word_last { + empty_flags.not_word_boundary = true; + } else { + empty_flags.word_boundary = true; + } + (empty_flags, state_flags) + } + + /// Returns a reference to a State given a pointer to it. + fn state(&self, si: StatePtr) -> &State { + &self.cache.states[si as usize / self.num_byte_classes()] + } + + /// Adds the given state to the DFA. + /// + /// This allocates room for transitions out of this state in + /// self.cache.trans. The transitions can be set with the returned + /// StatePtr. + /// + /// If None is returned, then the state limit was reached and the DFA + /// should quit. + fn add_state(&mut self, state: State) -> Option { + // This will fail if the next state pointer exceeds STATE_PTR. In + // practice, the cache limit will prevent us from ever getting here, + // but maybe callers will set the cache size to something ridiculous... + let si = match self.cache.trans.add() { + None => return None, + Some(si) => si, + }; + // If the program has a Unicode word boundary, then set any transitions + // for non-ASCII bytes to STATE_QUIT. If the DFA stumbles over such a + // transition, then it will quit and an alternative matching engine + // will take over. + if self.prog.has_unicode_word_boundary { + for b in 128..256 { + let cls = self.byte_class(Byte::byte(b as u8)); + self.cache.trans.set_next(si, cls, STATE_QUIT); + } + } + // Finally, put our actual state on to our heap of states and index it + // so we can find it later. + self.cache.size += + self.cache.trans.state_heap_size() + + (2 * state.data.len()) + + (2 * mem::size_of::()) + + mem::size_of::(); + self.cache.states.push(state.clone()); + self.cache.compiled.insert(state, si); + // Transition table and set of states and map should all be in sync. + debug_assert!(self.cache.states.len() + == self.cache.trans.num_states()); + debug_assert!(self.cache.states.len() + == self.cache.compiled.len()); + Some(si) + } + + /// Quickly finds the next occurrence of any literal prefixes in the regex. + /// If there are no literal prefixes, then the current position is + /// returned. If there are literal prefixes and one could not be found, + /// then None is returned. + /// + /// This should only be called when the DFA is in a start state. + fn prefix_at(&self, text: &[u8], at: usize) -> Option { + self.prog.prefixes.find(&text[at..]).map(|(s, _)| at + s) + } + + /// Returns the number of byte classes required to discriminate transitions + /// in each state. + /// + /// invariant: num_byte_classes() == len(State.next) + fn num_byte_classes(&self) -> usize { + // We add 1 to account for the special EOF byte. + (self.prog.byte_classes[255] as usize + 1) + 1 + } + + /// Given an input byte or the special EOF sentinel, return its + /// corresponding byte class. + #[inline(always)] + fn byte_class(&self, b: Byte) -> usize { + match b.as_byte() { + None => self.num_byte_classes() - 1, + Some(b) => self.u8_class(b), + } + } + + /// Like byte_class, but explicitly for u8s. + #[inline(always)] + fn u8_class(&self, b: u8) -> usize { + self.prog.byte_classes[b as usize] as usize + } + + /// Returns true if the DFA should continue searching past the first match. + /// + /// Leftmost first semantics in the DFA are preserved by not following NFA + /// transitions after the first match is seen. + /// + /// On occasion, we want to avoid leftmost first semantics to find either + /// the longest match (for reverse search) or all possible matches (for + /// regex sets). + fn continue_past_first_match(&self) -> bool { + self.prog.is_reverse || self.prog.matches.len() > 1 + } + + /// Returns true if there is a prefix we can quickly search for. + fn has_prefix(&self) -> bool { + !self.prog.is_reverse + && !self.prog.prefixes.is_empty() + && !self.prog.is_anchored_start + } + + /// Sets the STATE_START bit in the given state pointer if and only if + /// we have a prefix to scan for. + /// + /// If there's no prefix, then it's a waste to treat the start state + /// specially. + fn start_ptr(&self, si: StatePtr) -> StatePtr { + if self.has_prefix() { + si | STATE_START + } else { + si + } + } + + /// Approximate size returns the approximate heap space currently used by + /// the DFA. It is used to determine whether the DFA's state cache needs to + /// be wiped. Namely, it is possible that for certain regexes on certain + /// inputs, a new state could be created for every byte of input. (This is + /// bad for memory use, so we bound it with a cache.) + fn approximate_size(&self) -> usize { + self.cache.size + self.prog.approximate_size() + } +} + +impl Transitions { + /// Create a new transition table. + /// + /// The number of byte classes corresponds to the stride. Every state will + /// have `num_byte_classes` slots for transitions. + fn new(num_byte_classes: usize) -> Transitions { + Transitions { + table: vec![], + num_byte_classes: num_byte_classes, + } + } + + /// Returns the total number of states currently in this table. + fn num_states(&self) -> usize { + self.table.len() / self.num_byte_classes + } + + /// Allocates room for one additional state and returns a pointer to it. + /// + /// If there's no more room, None is returned. + fn add(&mut self) -> Option { + let si = self.table.len(); + if si > STATE_MAX as usize { + return None; + } + self.table.extend(repeat(STATE_UNKNOWN).take(self.num_byte_classes)); + Some(usize_to_u32(si)) + } + + /// Clears the table of all states. + fn clear(&mut self) { + self.table.clear(); + } + + /// Sets the transition from (si, cls) to next. + fn set_next(&mut self, si: StatePtr, cls: usize, next: StatePtr) { + self.table[si as usize + cls] = next; + } + + /// Returns the transition corresponding to (si, cls). + fn next(&self, si: StatePtr, cls: usize) -> StatePtr { + self.table[si as usize + cls] + } + + /// The heap size, in bytes, of a single state in the transition table. + fn state_heap_size(&self) -> usize { + self.num_byte_classes * mem::size_of::() + } + + /// Like `next`, but uses unchecked access and is therefore unsafe. + unsafe fn next_unchecked(&self, si: StatePtr, cls: usize) -> StatePtr { + debug_assert!((si as usize) < self.table.len()); + debug_assert!(cls < self.num_byte_classes); + *self.table.get_unchecked(si as usize + cls) + } +} + +impl StateFlags { + fn is_match(&self) -> bool { + self.0 & 0b0000000_1 > 0 + } + + fn set_match(&mut self) { + self.0 |= 0b0000000_1; + } + + fn is_word(&self) -> bool { + self.0 & 0b000000_1_0 > 0 + } + + fn set_word(&mut self) { + self.0 |= 0b000000_1_0; + } + + fn has_empty(&self) -> bool { + self.0 & 0b00000_1_00 > 0 + } + + fn set_empty(&mut self) { + self.0 |= 0b00000_1_00; + } +} + +impl Byte { + fn byte(b: u8) -> Self { Byte(b as u16) } + fn eof() -> Self { Byte(256) } + fn is_eof(&self) -> bool { self.0 == 256 } + + fn is_ascii_word(&self) -> bool { + let b = match self.as_byte() { + None => return false, + Some(b) => b, + }; + match b { + b'A'...b'Z' | b'a'...b'z' | b'0'...b'9' | b'_' => true, + _ => false, + } + } + + fn as_byte(&self) -> Option { + if self.is_eof() { + None + } else { + Some(self.0 as u8) + } + } +} + +impl fmt::Debug for State { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let ips: Vec = self.inst_ptrs().collect(); + f.debug_struct("State") + .field("flags", &self.flags()) + .field("insts", &ips) + .finish() + } +} + +impl fmt::Debug for Transitions { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut fmtd = f.debug_map(); + for si in 0..self.num_states() { + let s = si * self.num_byte_classes; + let e = s + self.num_byte_classes; + fmtd.entry(&si.to_string(), &TransitionsRow(&self.table[s..e])); + } + fmtd.finish() + } +} + +struct TransitionsRow<'a>(&'a [StatePtr]); + +impl<'a> fmt::Debug for TransitionsRow<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut fmtd = f.debug_map(); + for (b, si) in self.0.iter().enumerate() { + match *si { + STATE_UNKNOWN => {} + STATE_DEAD => { + fmtd.entry(&vb(b as usize), &"DEAD"); + } + si => { + fmtd.entry(&vb(b as usize), &si.to_string()); + } + } + } + fmtd.finish() + } +} + +impl fmt::Debug for StateFlags { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("StateFlags") + .field("is_match", &self.is_match()) + .field("is_word", &self.is_word()) + .field("has_empty", &self.has_empty()) + .finish() + } +} + +/// Helper function for formatting a byte as a nice-to-read escaped string. +fn vb(b: usize) -> String { + use std::ascii::escape_default; + + if b > ::std::u8::MAX as usize { + "EOF".to_owned() + } else { + let escaped = escape_default(b as u8).collect::>(); + String::from_utf8_lossy(&escaped).into_owned() + } +} + +fn usize_to_u32(n: usize) -> u32 { + if (n as u64) > (::std::u32::MAX as u64) { + panic!("BUG: {} is too big to fit into u32", n) + } + n as u32 +} + +#[allow(dead_code)] // useful for debugging +fn show_state_ptr(si: StatePtr) -> String { + let mut s = format!("{:?}", si & STATE_MAX); + if si == STATE_UNKNOWN { + s = format!("{} (unknown)", s); + } + if si == STATE_DEAD { + s = format!("{} (dead)", s); + } + if si == STATE_QUIT { + s = format!("{} (quit)", s); + } + if si & STATE_START > 0 { + s = format!("{} (start)", s); + } + if si & STATE_MATCH > 0 { + s = format!("{} (match)", s); + } + s +} + +/// https://developers.google.com/protocol-buffers/docs/encoding#varints +fn write_vari32(data: &mut Vec, n: i32) { + let mut un = (n as u32) << 1; + if n < 0 { + un = !un; + } + write_varu32(data, un) +} + +/// https://developers.google.com/protocol-buffers/docs/encoding#varints +fn read_vari32(data: &[u8]) -> (i32, usize) { + let (un, i) = read_varu32(data); + let mut n = (un >> 1) as i32; + if un & 1 != 0 { + n = !n; + } + (n, i) +} + +/// https://developers.google.com/protocol-buffers/docs/encoding#varints +fn write_varu32(data: &mut Vec, mut n: u32) { + while n >= 0b1000_0000 { + data.push((n as u8) | 0b1000_0000); + n >>= 7; + } + data.push(n as u8); +} + +/// https://developers.google.com/protocol-buffers/docs/encoding#varints +fn read_varu32(data: &[u8]) -> (u32, usize) { + let mut n: u32 = 0; + let mut shift: u32 = 0; + for (i, &b) in data.iter().enumerate() { + if b < 0b1000_0000 { + return (n | ((b as u32) << shift), i + 1); + } + n |= ((b as u32) & 0b0111_1111) << shift; + shift += 7; + } + (0, 0) +} + +#[cfg(test)] +mod tests { + extern crate rand; + + use quickcheck::{QuickCheck, StdGen, quickcheck}; + use super::{ + StateFlags, State, push_inst_ptr, + write_varu32, read_varu32, write_vari32, read_vari32, + }; + + #[test] + fn prop_state_encode_decode() { + fn p(ips: Vec, flags: u8) -> bool { + let mut data = vec![flags]; + let mut prev = 0; + for &ip in ips.iter() { + push_inst_ptr(&mut data, &mut prev, ip); + } + let state = State { data: data.into_boxed_slice() }; + + let expected: Vec = + ips.into_iter().map(|ip| ip as usize).collect(); + let got: Vec = state.inst_ptrs().collect(); + expected == got && state.flags() == StateFlags(flags) + } + QuickCheck::new() + .gen(StdGen::new(self::rand::thread_rng(), 10_000)) + .quickcheck(p as fn(Vec, u8) -> bool); + } + + #[test] + fn prop_read_write_u32() { + fn p(n: u32) -> bool { + let mut buf = vec![]; + write_varu32(&mut buf, n); + let (got, nread) = read_varu32(&buf); + nread == buf.len() && got == n + } + quickcheck(p as fn(u32) -> bool); + } + + #[test] + fn prop_read_write_i32() { + fn p(n: i32) -> bool { + let mut buf = vec![]; + write_vari32(&mut buf, n); + let (got, nread) = read_vari32(&buf); + nread == buf.len() && got == n + } + quickcheck(p as fn(i32) -> bool); + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/error.rs cargo-0.26.0/vendor/regex-0.2.10/src/error.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/error.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/error.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,92 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::fmt; +use std::iter::repeat; + +use syntax; + +/// An error that occurred during parsing or compiling a regular expression. +#[derive(Clone, PartialEq)] +pub enum Error { + /// A syntax error. + Syntax(String), + /// The compiled program exceeded the set size limit. + /// The argument is the size limit imposed. + CompiledTooBig(usize), + /// Hints that destructuring should not be exhaustive. + /// + /// This enum may grow additional variants, so this makes sure clients + /// don't count on exhaustive matching. (Otherwise, adding a new variant + /// could break existing code.) + #[doc(hidden)] + __Nonexhaustive, +} + +impl ::std::error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::Syntax(ref err) => err, + Error::CompiledTooBig(_) => "compiled program too big", + Error::__Nonexhaustive => unreachable!(), + } + } + + fn cause(&self) -> Option<&::std::error::Error> { + None + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::Syntax(ref err) => err.fmt(f), + Error::CompiledTooBig(limit) => { + write!(f, "Compiled regex exceeds size limit of {} bytes.", + limit) + } + Error::__Nonexhaustive => unreachable!(), + } + } +} + +// We implement our own Debug implementation so that we show nicer syntax +// errors when people use `Regex::new(...).unwrap()`. It's a little weird, +// but the `Syntax` variant is already storing a `String` anyway, so we might +// as well format it nicely. +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::Syntax(ref err) => { + let hr: String = repeat('~').take(79).collect(); + try!(writeln!(f, "Syntax(")); + try!(writeln!(f, "{}", hr)); + try!(writeln!(f, "{}", err)); + try!(writeln!(f, "{}", hr)); + try!(write!(f, ")")); + Ok(()) + } + Error::CompiledTooBig(limit) => { + f.debug_tuple("CompiledTooBig") + .field(&limit) + .finish() + } + Error::__Nonexhaustive => { + f.debug_tuple("__Nonexhaustive").finish() + } + } + } +} + +impl From for Error { + fn from(err: syntax::Error) -> Error { + Error::Syntax(err.to_string()) + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/exec.rs cargo-0.26.0/vendor/regex-0.2.10/src/exec.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/exec.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/exec.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1288 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::cmp; +use std::sync::Arc; + +use thread_local::CachedThreadLocal; +use syntax::ParserBuilder; +use syntax::hir::Hir; +use syntax::hir::literal::Literals; + +use backtrack; +use compile::Compiler; +use dfa; +use error::Error; +use input::{ByteInput, CharInput}; +use literal::LiteralSearcher; +use pikevm; +use prog::Program; +use re_builder::RegexOptions; +use re_bytes; +use re_set; +use re_trait::{RegularExpression, Slot, Locations, as_slots}; +use re_unicode; +use utf8::next_utf8; + +/// `Exec` manages the execution of a regular expression. +/// +/// In particular, this manages the various compiled forms of a single regular +/// expression and the choice of which matching engine to use to execute a +/// regular expression. +pub struct Exec { + /// All read only state. + ro: Arc, + /// Caches for the various matching engines. + cache: CachedThreadLocal, +} + +/// `ExecNoSync` is like `Exec`, except it embeds a reference to a cache. This +/// means it is no longer Sync, but we can now avoid the overhead of +/// synchronization to fetch the cache. +#[derive(Debug)] +pub struct ExecNoSync<'c> { + /// All read only state. + ro: &'c Arc, + /// Caches for the various matching engines. + cache: &'c ProgramCache, +} + +/// `ExecNoSyncStr` is like `ExecNoSync`, but matches on &str instead of &[u8]. +pub struct ExecNoSyncStr<'c>(ExecNoSync<'c>); + +/// `ExecReadOnly` comprises all read only state for a regex. Namely, all such +/// state is determined at compile time and never changes during search. +#[derive(Debug)] +struct ExecReadOnly { + /// The original regular expressions given by the caller to compile. + res: Vec, + /// A compiled program that is used in the NFA simulation and backtracking. + /// It can be byte-based or Unicode codepoint based. + /// + /// N.B. It is not possibly to make this byte-based from the public API. + /// It is only used for testing byte based programs in the NFA simulations. + nfa: Program, + /// A compiled byte based program for DFA execution. This is only used + /// if a DFA can be executed. (Currently, only word boundary assertions are + /// not supported.) Note that this program contains an embedded `.*?` + /// preceding the first capture group, unless the regex is anchored at the + /// beginning. + dfa: Program, + /// The same as above, except the program is reversed (and there is no + /// preceding `.*?`). This is used by the DFA to find the starting location + /// of matches. + dfa_reverse: Program, + /// A set of suffix literals extracted from the regex. + /// + /// Prefix literals are stored on the `Program`, since they are used inside + /// the matching engines. + suffixes: LiteralSearcher, + /// match_type encodes as much upfront knowledge about how we're going to + /// execute a search as possible. + match_type: MatchType, +} + +/// Facilitates the construction of an executor by exposing various knobs +/// to control how a regex is executed and what kinds of resources it's +/// permitted to use. +pub struct ExecBuilder { + options: RegexOptions, + match_type: Option, + bytes: bool, + only_utf8: bool, +} + +/// Parsed represents a set of parsed regular expressions and their detected +/// literals. +struct Parsed { + exprs: Vec, + prefixes: Literals, + suffixes: Literals, + bytes: bool, +} + +impl ExecBuilder { + /// Create a regex execution builder. + /// + /// This uses default settings for everything except the regex itself, + /// which must be provided. Further knobs can be set by calling methods, + /// and then finally, `build` to actually create the executor. + pub fn new(re: &str) -> Self { + Self::new_many(&[re]) + } + + /// Like new, but compiles the union of the given regular expressions. + /// + /// Note that when compiling 2 or more regular expressions, capture groups + /// are completely unsupported. (This means both `find` and `captures` + /// wont work.) + pub fn new_many(res: I) -> Self + where S: AsRef, I: IntoIterator { + let mut opts = RegexOptions::default(); + opts.pats = res.into_iter().map(|s| s.as_ref().to_owned()).collect(); + Self::new_options(opts) + } + + /// Create a regex execution builder. + pub fn new_options(opts: RegexOptions) -> Self { + ExecBuilder { + options: opts, + match_type: None, + bytes: false, + only_utf8: true, + } + } + + /// Set the matching engine to be automatically determined. + /// + /// This is the default state and will apply whatever optimizations are + /// possible, such as running a DFA. + /// + /// This overrides whatever was previously set via the `nfa` or + /// `bounded_backtracking` methods. + pub fn automatic(mut self) -> Self { + self.match_type = None; + self + } + + /// Sets the matching engine to use the NFA algorithm no matter what + /// optimizations are possible. + /// + /// This overrides whatever was previously set via the `automatic` or + /// `bounded_backtracking` methods. + pub fn nfa(mut self) -> Self { + self.match_type = Some(MatchType::Nfa(MatchNfaType::PikeVM)); + self + } + + /// Sets the matching engine to use a bounded backtracking engine no + /// matter what optimizations are possible. + /// + /// One must use this with care, since the bounded backtracking engine + /// uses memory proportion to `len(regex) * len(text)`. + /// + /// This overrides whatever was previously set via the `automatic` or + /// `nfa` methods. + pub fn bounded_backtracking(mut self) -> Self { + self.match_type = Some(MatchType::Nfa(MatchNfaType::Backtrack)); + self + } + + /// Compiles byte based programs for use with the NFA matching engines. + /// + /// By default, the NFA engines match on Unicode scalar values. They can + /// be made to use byte based programs instead. In general, the byte based + /// programs are slower because of a less efficient encoding of character + /// classes. + /// + /// Note that this does not impact DFA matching engines, which always + /// execute on bytes. + pub fn bytes(mut self, yes: bool) -> Self { + self.bytes = yes; + self + } + + /// When disabled, the program compiled may match arbitrary bytes. + /// + /// When enabled (the default), all compiled programs exclusively match + /// valid UTF-8 bytes. + pub fn only_utf8(mut self, yes: bool) -> Self { + self.only_utf8 = yes; + self + } + + /// Set the Unicode flag. + pub fn unicode(mut self, yes: bool) -> Self { + self.options.unicode = yes; + self + } + + /// Parse the current set of patterns into their AST and extract literals. + fn parse(&self) -> Result { + let mut exprs = Vec::with_capacity(self.options.pats.len()); + let mut prefixes = Some(Literals::empty()); + let mut suffixes = Some(Literals::empty()); + let mut bytes = false; + let is_set = self.options.pats.len() > 1; + // If we're compiling a regex set and that set has any anchored + // expressions, then disable all literal optimizations. + for pat in &self.options.pats { + let mut parser = + ParserBuilder::new() + // TODO(burntsushi): Disable octal in regex 1.0. Nobody + // uses it, and we'll get better error messages when + // someone tries to use a backreference. Provide a new + // opt-in toggle for it though. + .octal(true) + .case_insensitive(self.options.case_insensitive) + .multi_line(self.options.multi_line) + .dot_matches_new_line(self.options.dot_matches_new_line) + .swap_greed(self.options.swap_greed) + .ignore_whitespace(self.options.ignore_whitespace) + .unicode(self.options.unicode) + .allow_invalid_utf8(!self.only_utf8) + .nest_limit(self.options.nest_limit) + .build(); + let expr = try!(parser.parse(pat)); + bytes = bytes || !expr.is_always_utf8(); + + if !expr.is_anchored_start() && expr.is_any_anchored_start() { + // Partial anchors unfortunately make it hard to use prefixes, + // so disable them. + prefixes = None; + } else if is_set && expr.is_anchored_start() { + // Regex sets with anchors do not go well with literal + // optimizations. + prefixes = None; + } + prefixes = prefixes.and_then(|mut prefixes| { + if !prefixes.union_prefixes(&expr) { + None + } else { + Some(prefixes) + } + }); + + if !expr.is_anchored_end() && expr.is_any_anchored_end() { + // Partial anchors unfortunately make it hard to use suffixes, + // so disable them. + suffixes = None; + } else if is_set && expr.is_anchored_end() { + // Regex sets with anchors do not go well with literal + // optimizations. + suffixes = None; + } + suffixes = suffixes.and_then(|mut suffixes| { + if !suffixes.union_suffixes(&expr) { + None + } else { + Some(suffixes) + } + }); + exprs.push(expr); + } + Ok(Parsed { + exprs: exprs, + prefixes: prefixes.unwrap_or_else(Literals::empty), + suffixes: suffixes.unwrap_or_else(Literals::empty), + bytes: bytes, + }) + } + + /// Build an executor that can run a regular expression. + pub fn build(self) -> Result { + // Special case when we have no patterns to compile. + // This can happen when compiling a regex set. + if self.options.pats.is_empty() { + let ro = Arc::new(ExecReadOnly { + res: vec![], + nfa: Program::new(), + dfa: Program::new(), + dfa_reverse: Program::new(), + suffixes: LiteralSearcher::empty(), + match_type: MatchType::Nothing, + }); + return Ok(Exec { ro: ro, cache: CachedThreadLocal::new() }); + } + let parsed = try!(self.parse()); + let mut nfa = try!( + Compiler::new() + .size_limit(self.options.size_limit) + .bytes(self.bytes || parsed.bytes) + .only_utf8(self.only_utf8) + .compile(&parsed.exprs)); + let mut dfa = try!( + Compiler::new() + .size_limit(self.options.size_limit) + .dfa(true) + .only_utf8(self.only_utf8) + .compile(&parsed.exprs)); + let mut dfa_reverse = try!( + Compiler::new() + .size_limit(self.options.size_limit) + .dfa(true) + .only_utf8(self.only_utf8) + .reverse(true) + .compile(&parsed.exprs)); + + let prefixes = parsed.prefixes.unambiguous_prefixes(); + let suffixes = parsed.suffixes.unambiguous_suffixes(); + nfa.prefixes = LiteralSearcher::prefixes(prefixes); + dfa.prefixes = nfa.prefixes.clone(); + dfa.dfa_size_limit = self.options.dfa_size_limit; + dfa_reverse.dfa_size_limit = self.options.dfa_size_limit; + + let mut ro = ExecReadOnly { + res: self.options.pats, + nfa: nfa, + dfa: dfa, + dfa_reverse: dfa_reverse, + suffixes: LiteralSearcher::suffixes(suffixes), + match_type: MatchType::Nothing, + }; + ro.match_type = ro.choose_match_type(self.match_type); + + let ro = Arc::new(ro); + Ok(Exec { ro: ro, cache: CachedThreadLocal::new() }) + } +} + +impl<'c> RegularExpression for ExecNoSyncStr<'c> { + type Text = str; + + fn slots_len(&self) -> usize { self.0.slots_len() } + + fn next_after_empty(&self, text: &str, i: usize) -> usize { + next_utf8(text.as_bytes(), i) + } + + #[inline(always)] // reduces constant overhead + fn shortest_match_at(&self, text: &str, start: usize) -> Option { + self.0.shortest_match_at(text.as_bytes(), start) + } + + #[inline(always)] // reduces constant overhead + fn is_match_at(&self, text: &str, start: usize) -> bool { + self.0.is_match_at(text.as_bytes(), start) + } + + #[inline(always)] // reduces constant overhead + fn find_at(&self, text: &str, start: usize) -> Option<(usize, usize)> { + self.0.find_at(text.as_bytes(), start) + } + + #[inline(always)] // reduces constant overhead + fn read_captures_at( + &self, + locs: &mut Locations, + text: &str, + start: usize, + ) -> Option<(usize, usize)> { + self.0.read_captures_at(locs, text.as_bytes(), start) + } +} + +impl<'c> RegularExpression for ExecNoSync<'c> { + type Text = [u8]; + + /// Returns the number of capture slots in the regular expression. (There + /// are two slots for every capture group, corresponding to possibly empty + /// start and end locations of the capture.) + fn slots_len(&self) -> usize { + self.ro.nfa.captures.len() * 2 + } + + fn next_after_empty(&self, _text: &[u8], i: usize) -> usize { + i + 1 + } + + /// Returns the end of a match location, possibly occurring before the + /// end location of the correct leftmost-first match. + #[inline(always)] // reduces constant overhead + fn shortest_match_at(&self, text: &[u8], start: usize) -> Option { + if !self.is_anchor_end_match(text) { + return None; + } + match self.ro.match_type { + MatchType::Literal(ty) => { + self.find_literals(ty, text, start).map(|(_, e)| e) + } + MatchType::Dfa | MatchType::DfaMany => { + match self.shortest_dfa(text, start) { + dfa::Result::Match(end) => Some(end), + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => self.shortest_nfa(text, start), + } + } + MatchType::DfaAnchoredReverse => { + match dfa::Fsm::reverse( + &self.ro.dfa_reverse, + self.cache, + true, + &text[start..], + text.len(), + ) { + dfa::Result::Match(_) => Some(text.len()), + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => self.shortest_nfa(text, start), + } + } + MatchType::DfaSuffix => { + match self.shortest_dfa_reverse_suffix(text, start) { + dfa::Result::Match(e) => Some(e), + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => self.shortest_nfa(text, start), + } + } + MatchType::Nfa(ty) => self.shortest_nfa_type(ty, text, start), + MatchType::Nothing => None, + } + } + + /// Returns true if and only if the regex matches text. + /// + /// For single regular expressions, this is equivalent to calling + /// shortest_match(...).is_some(). + #[inline(always)] // reduces constant overhead + fn is_match_at(&self, text: &[u8], start: usize) -> bool { + if !self.is_anchor_end_match(text) { + return false; + } + // We need to do this dance because shortest_match relies on the NFA + // filling in captures[1], but a RegexSet has no captures. In other + // words, a RegexSet can't (currently) use shortest_match. ---AG + match self.ro.match_type { + MatchType::Literal(ty) => { + self.find_literals(ty, text, start).is_some() + } + MatchType::Dfa | MatchType::DfaMany => { + match self.shortest_dfa(text, start) { + dfa::Result::Match(_) => true, + dfa::Result::NoMatch(_) => false, + dfa::Result::Quit => self.match_nfa(text, start), + } + } + MatchType::DfaAnchoredReverse => { + match dfa::Fsm::reverse( + &self.ro.dfa_reverse, + self.cache, + true, + &text[start..], + text.len(), + ) { + dfa::Result::Match(_) => true, + dfa::Result::NoMatch(_) => false, + dfa::Result::Quit => self.match_nfa(text, start), + } + } + MatchType::DfaSuffix => { + match self.shortest_dfa_reverse_suffix(text, start) { + dfa::Result::Match(_) => true, + dfa::Result::NoMatch(_) => false, + dfa::Result::Quit => self.match_nfa(text, start), + } + } + MatchType::Nfa(ty) => self.match_nfa_type(ty, text, start), + MatchType::Nothing => false, + } + } + + /// Finds the start and end location of the leftmost-first match, starting + /// at the given location. + #[inline(always)] // reduces constant overhead + fn find_at(&self, text: &[u8], start: usize) -> Option<(usize, usize)> { + if !self.is_anchor_end_match(text) { + return None; + } + match self.ro.match_type { + MatchType::Literal(ty) => { + self.find_literals(ty, text, start) + } + MatchType::Dfa => { + match self.find_dfa_forward(text, start) { + dfa::Result::Match((s, e)) => Some((s, e)), + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => { + self.find_nfa(MatchNfaType::Auto, text, start) + } + } + } + MatchType::DfaAnchoredReverse => { + match self.find_dfa_anchored_reverse(text, start) { + dfa::Result::Match((s, e)) => Some((s, e)), + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => { + self.find_nfa(MatchNfaType::Auto, text, start) + } + } + } + MatchType::DfaSuffix => { + match self.find_dfa_reverse_suffix(text, start) { + dfa::Result::Match((s, e)) => Some((s, e)), + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => { + self.find_nfa(MatchNfaType::Auto, text, start) + } + } + } + MatchType::Nfa(ty) => self.find_nfa(ty, text, start), + MatchType::Nothing => None, + MatchType::DfaMany => { + unreachable!("BUG: RegexSet cannot be used with find") + } + } + } + + /// Finds the start and end location of the leftmost-first match and also + /// fills in all matching capture groups. + /// + /// The number of capture slots given should be equal to the total number + /// of capture slots in the compiled program. + /// + /// Note that the first two slots always correspond to the start and end + /// locations of the overall match. + fn read_captures_at( + &self, + locs: &mut Locations, + text: &[u8], + start: usize, + ) -> Option<(usize, usize)> { + let slots = as_slots(locs); + for slot in slots.iter_mut() { + *slot = None; + } + // If the caller unnecessarily uses this, then we try to save them + // from themselves. + match slots.len() { + 0 => return self.find_at(text, start), + 2 => { + return self.find_at(text, start).map(|(s, e)| { + slots[0] = Some(s); + slots[1] = Some(e); + (s, e) + }); + } + _ => {} // fallthrough + } + if !self.is_anchor_end_match(text) { + return None; + } + match self.ro.match_type { + MatchType::Literal(ty) => { + self.find_literals(ty, text, start).and_then(|(s, e)| { + self.captures_nfa_with_match(slots, text, s, e) + }) + } + MatchType::Dfa => { + if self.ro.nfa.is_anchored_start { + self.captures_nfa(slots, text, start) + } else { + match self.find_dfa_forward(text, start) { + dfa::Result::Match((s, e)) => { + self.captures_nfa_with_match(slots, text, s, e) + } + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => self.captures_nfa(slots, text, start), + } + } + } + MatchType::DfaAnchoredReverse => { + match self.find_dfa_anchored_reverse(text, start) { + dfa::Result::Match((s, e)) => { + self.captures_nfa_with_match(slots, text, s, e) + } + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => self.captures_nfa(slots, text, start), + } + } + MatchType::DfaSuffix => { + match self.find_dfa_reverse_suffix(text, start) { + dfa::Result::Match((s, e)) => { + self.captures_nfa_with_match(slots, text, s, e) + } + dfa::Result::NoMatch(_) => None, + dfa::Result::Quit => self.captures_nfa(slots, text, start), + } + } + MatchType::Nfa(ty) => { + self.captures_nfa_type(ty, slots, text, start) + } + MatchType::Nothing => None, + MatchType::DfaMany => { + unreachable!("BUG: RegexSet cannot be used with captures") + } + } + } +} + +impl<'c> ExecNoSync<'c> { + /// Finds the leftmost-first match using only literal search. + #[inline(always)] // reduces constant overhead + fn find_literals( + &self, + ty: MatchLiteralType, + text: &[u8], + start: usize, + ) -> Option<(usize, usize)> { + use self::MatchLiteralType::*; + match ty { + Unanchored => { + let lits = &self.ro.nfa.prefixes; + lits.find(&text[start..]) + .map(|(s, e)| (start + s, start + e)) + } + AnchoredStart => { + let lits = &self.ro.nfa.prefixes; + lits.find_start(&text[start..]) + .map(|(s, e)| (start + s, start + e)) + } + AnchoredEnd => { + let lits = &self.ro.suffixes; + lits.find_end(&text[start..]) + .map(|(s, e)| (start + s, start + e)) + } + } + } + + /// Finds the leftmost-first match (start and end) using only the DFA. + /// + /// If the result returned indicates that the DFA quit, then another + /// matching engine should be used. + #[inline(always)] // reduces constant overhead + fn find_dfa_forward( + &self, + text: &[u8], + start: usize, + ) -> dfa::Result<(usize, usize)> { + use dfa::Result::*; + let end = match dfa::Fsm::forward( + &self.ro.dfa, + self.cache, + false, + text, + start, + ) { + NoMatch(i) => return NoMatch(i), + Quit => return Quit, + Match(end) if start == end => return Match((start, start)), + Match(end) => end, + }; + // Now run the DFA in reverse to find the start of the match. + match dfa::Fsm::reverse( + &self.ro.dfa_reverse, + self.cache, + false, + &text[start..], + end - start, + ) { + Match(s) => Match((start + s, end)), + NoMatch(i) => NoMatch(i), + Quit => Quit, + } + } + + /// Finds the leftmost-first match (start and end) using only the DFA, + /// but assumes the regex is anchored at the end and therefore starts at + /// the end of the regex and matches in reverse. + /// + /// If the result returned indicates that the DFA quit, then another + /// matching engine should be used. + #[inline(always)] // reduces constant overhead + fn find_dfa_anchored_reverse( + &self, + text: &[u8], + start: usize, + ) -> dfa::Result<(usize, usize)> { + use dfa::Result::*; + match dfa::Fsm::reverse( + &self.ro.dfa_reverse, + self.cache, + false, + &text[start..], + text.len() - start, + ) { + Match(s) => Match((start + s, text.len())), + NoMatch(i) => NoMatch(i), + Quit => Quit, + } + } + + /// Finds the end of the shortest match using only the DFA. + #[inline(always)] // reduces constant overhead + fn shortest_dfa(&self, text: &[u8], start: usize) -> dfa::Result { + dfa::Fsm::forward(&self.ro.dfa, self.cache, true, text, start) + } + + /// Finds the end of the shortest match using only the DFA by scanning for + /// suffix literals. + /// + #[inline(always)] // reduces constant overhead + fn shortest_dfa_reverse_suffix( + &self, + text: &[u8], + start: usize, + ) -> dfa::Result { + match self.exec_dfa_reverse_suffix(text, start) { + None => self.shortest_dfa(text, start), + Some(r) => r.map(|(_, end)| end), + } + } + + /// Finds the end of the shortest match using only the DFA by scanning for + /// suffix literals. It also reports the start of the match. + /// + /// Note that if None is returned, then the optimization gave up to avoid + /// worst case quadratic behavior. A forward scanning DFA should be tried + /// next. + /// + /// If a match is returned and the full leftmost-first match is desired, + /// then a forward scan starting from the beginning of the match must be + /// done. + /// + /// If the result returned indicates that the DFA quit, then another + /// matching engine should be used. + #[inline(always)] // reduces constant overhead + fn exec_dfa_reverse_suffix( + &self, + text: &[u8], + original_start: usize, + ) -> Option> { + use dfa::Result::*; + + let lcs = self.ro.suffixes.lcs(); + debug_assert!(lcs.len() >= 1); + let mut start = original_start; + let mut end = start; + while end <= text.len() { + start = end; + end += match lcs.find(&text[end..]) { + None => return Some(NoMatch(text.len())), + Some(start) => start + lcs.len(), + }; + match dfa::Fsm::reverse( + &self.ro.dfa_reverse, + self.cache, + false, + &text[start..end], + end - start, + ) { + Match(0) | NoMatch(0) => return None, + Match(s) => return Some(Match((s + start, end))), + NoMatch(_) => continue, + Quit => return Some(Quit), + }; + } + Some(NoMatch(text.len())) + } + + /// Finds the leftmost-first match (start and end) using only the DFA + /// by scanning for suffix literals. + /// + /// If the result returned indicates that the DFA quit, then another + /// matching engine should be used. + #[inline(always)] // reduces constant overhead + fn find_dfa_reverse_suffix( + &self, + text: &[u8], + start: usize, + ) -> dfa::Result<(usize, usize)> { + use dfa::Result::*; + + let match_start = match self.exec_dfa_reverse_suffix(text, start) { + None => return self.find_dfa_forward(text, start), + Some(Match((start, _))) => start, + Some(r) => return r, + }; + // At this point, we've found a match. The only way to quit now + // without a match is if the DFA gives up (seems unlikely). + // + // Now run the DFA forwards to find the proper end of the match. + // (The suffix literal match can only indicate the earliest + // possible end location, which may appear before the end of the + // leftmost-first match.) + match dfa::Fsm::forward( + &self.ro.dfa, + self.cache, + false, + text, + match_start, + ) { + NoMatch(_) => panic!("BUG: reverse match implies forward match"), + Quit => Quit, + Match(e) => Match((match_start, e)), + } + } + + /// Executes the NFA engine to return whether there is a match or not. + /// + /// Ideally, we could use shortest_nfa(...).is_some() and get the same + /// performance characteristics, but regex sets don't have captures, which + /// shortest_nfa depends on. + fn match_nfa( + &self, + text: &[u8], + start: usize, + ) -> bool { + self.match_nfa_type(MatchNfaType::Auto, text, start) + } + + /// Like match_nfa, but allows specification of the type of NFA engine. + fn match_nfa_type( + &self, + ty: MatchNfaType, + text: &[u8], + start: usize, + ) -> bool { + self.exec_nfa(ty, &mut [false], &mut [], true, text, start) + } + + /// Finds the shortest match using an NFA. + fn shortest_nfa(&self, text: &[u8], start: usize) -> Option { + self.shortest_nfa_type(MatchNfaType::Auto, text, start) + } + + /// Like shortest_nfa, but allows specification of the type of NFA engine. + fn shortest_nfa_type( + &self, + ty: MatchNfaType, + text: &[u8], + start: usize, + ) -> Option { + let mut slots = [None, None]; + if self.exec_nfa(ty, &mut [false], &mut slots, true, text, start) { + slots[1] + } else { + None + } + } + + /// Like find, but executes an NFA engine. + fn find_nfa( + &self, + ty: MatchNfaType, + text: &[u8], + start: usize, + ) -> Option<(usize, usize)> { + let mut slots = [None, None]; + if self.exec_nfa(ty, &mut [false], &mut slots, false, text, start) { + match (slots[0], slots[1]) { + (Some(s), Some(e)) => Some((s, e)), + _ => None, + } + } else { + None + } + } + + /// Like find_nfa, but fills in captures and restricts the search space + /// using previously found match information. + /// + /// `slots` should have length equal to `2 * nfa.captures.len()`. + fn captures_nfa_with_match( + &self, + slots: &mut [Slot], + text: &[u8], + match_start: usize, + match_end: usize, + ) -> Option<(usize, usize)> { + // We can't use match_end directly, because we may need to examine one + // "character" after the end of a match for lookahead operators. We + // need to move two characters beyond the end, since some look-around + // operations may falsely assume a premature end of text otherwise. + let e = cmp::min( + next_utf8(text, next_utf8(text, match_end)), text.len()); + self.captures_nfa(slots, &text[..e], match_start) + } + + /// Like find_nfa, but fills in captures. + /// + /// `slots` should have length equal to `2 * nfa.captures.len()`. + fn captures_nfa( + &self, + slots: &mut [Slot], + text: &[u8], + start: usize, + ) -> Option<(usize, usize)> { + self.captures_nfa_type(MatchNfaType::Auto, slots, text, start) + } + + /// Like captures_nfa, but allows specification of type of NFA engine. + fn captures_nfa_type( + &self, + ty: MatchNfaType, + slots: &mut [Slot], + text: &[u8], + start: usize, + ) -> Option<(usize, usize)> { + if self.exec_nfa(ty, &mut [false], slots, false, text, start) { + match (slots[0], slots[1]) { + (Some(s), Some(e)) => Some((s, e)), + _ => None, + } + } else { + None + } + } + + fn exec_nfa( + &self, + mut ty: MatchNfaType, + matches: &mut [bool], + slots: &mut [Slot], + quit_after_match: bool, + text: &[u8], + start: usize, + ) -> bool { + use self::MatchNfaType::*; + if let Auto = ty { + if backtrack::should_exec(self.ro.nfa.len(), text.len()) { + ty = Backtrack; + } else { + ty = PikeVM; + } + } + match ty { + Auto => unreachable!(), + Backtrack => self.exec_backtrack(matches, slots, text, start), + PikeVM => { + self.exec_pikevm( + matches, slots, quit_after_match, text, start) + } + } + } + + /// Always run the NFA algorithm. + fn exec_pikevm( + &self, + matches: &mut [bool], + slots: &mut [Slot], + quit_after_match: bool, + text: &[u8], + start: usize, + ) -> bool { + if self.ro.nfa.uses_bytes() { + pikevm::Fsm::exec( + &self.ro.nfa, + self.cache, + matches, + slots, + quit_after_match, + ByteInput::new(text, self.ro.nfa.only_utf8), + start) + } else { + pikevm::Fsm::exec( + &self.ro.nfa, + self.cache, + matches, + slots, + quit_after_match, + CharInput::new(text), + start) + } + } + + /// Always runs the NFA using bounded backtracking. + fn exec_backtrack( + &self, + matches: &mut [bool], + slots: &mut [Slot], + text: &[u8], + start: usize, + ) -> bool { + if self.ro.nfa.uses_bytes() { + backtrack::Bounded::exec( + &self.ro.nfa, + self.cache, + matches, + slots, + ByteInput::new(text, self.ro.nfa.only_utf8), + start) + } else { + backtrack::Bounded::exec( + &self.ro.nfa, + self.cache, + matches, + slots, + CharInput::new(text), + start) + } + } + + /// Finds which regular expressions match the given text. + /// + /// `matches` should have length equal to the number of regexes being + /// searched. + /// + /// This is only useful when one wants to know which regexes in a set + /// match some text. + pub fn many_matches_at( + &self, + matches: &mut [bool], + text: &[u8], + start: usize, + ) -> bool { + use self::MatchType::*; + if !self.is_anchor_end_match(text) { + return false; + } + match self.ro.match_type { + Literal(ty) => { + debug_assert_eq!(matches.len(), 1); + matches[0] = self.find_literals(ty, text, start).is_some(); + matches[0] + } + Dfa | DfaAnchoredReverse | DfaSuffix | DfaMany => { + match dfa::Fsm::forward_many( + &self.ro.dfa, + self.cache, + matches, + text, + start, + ) { + dfa::Result::Match(_) => true, + dfa::Result::NoMatch(_) => false, + dfa::Result::Quit => { + self.exec_nfa( + MatchNfaType::Auto, + matches, + &mut [], + false, + text, + start) + } + } + } + Nfa(ty) => self.exec_nfa(ty, matches, &mut [], false, text, start), + Nothing => false, + } + } + + #[inline(always)] // reduces constant overhead + fn is_anchor_end_match(&self, text: &[u8]) -> bool { + // Only do this check if the haystack is big (>1MB). + if text.len() > (1<<20) && self.ro.nfa.is_anchored_end { + let lcs = self.ro.suffixes.lcs(); + if lcs.len() >= 1 && !lcs.is_suffix(text) { + return false; + } + } + true + } + + pub fn capture_name_idx(&self) -> &Arc> { + &self.ro.nfa.capture_name_idx + } +} + +impl<'c> ExecNoSyncStr<'c> { + pub fn capture_name_idx(&self) -> &Arc> { + self.0.capture_name_idx() + } +} + +impl Exec { + /// Get a searcher that isn't Sync. + #[inline(always)] // reduces constant overhead + pub fn searcher(&self) -> ExecNoSync { + let create = || Box::new(RefCell::new(ProgramCacheInner::new(&self.ro))); + ExecNoSync { + ro: &self.ro, // a clone is too expensive here! (and not needed) + cache: self.cache.get_or(create), + } + } + + /// Get a searcher that isn't Sync and can match on &str. + #[inline(always)] // reduces constant overhead + pub fn searcher_str(&self) -> ExecNoSyncStr { + ExecNoSyncStr(self.searcher()) + } + + /// Build a Regex from this executor. + pub fn into_regex(self) -> re_unicode::Regex { + re_unicode::Regex::from(self) + } + + /// Build a RegexSet from this executor. + pub fn into_regex_set(self) -> re_set::unicode::RegexSet { + re_set::unicode::RegexSet::from(self) + } + + /// Build a Regex from this executor that can match arbitrary bytes. + pub fn into_byte_regex(self) -> re_bytes::Regex { + re_bytes::Regex::from(self) + } + + /// Build a RegexSet from this executor that can match arbitrary bytes. + pub fn into_byte_regex_set(self) -> re_set::bytes::RegexSet { + re_set::bytes::RegexSet::from(self) + } + + /// The original regular expressions given by the caller that were + /// compiled. + pub fn regex_strings(&self) -> &[String] { + &self.ro.res + } + + /// Return a slice of capture names. + /// + /// Any capture that isn't named is None. + pub fn capture_names(&self) -> &[Option] { + &self.ro.nfa.captures + } + + /// Return a reference to named groups mapping (from group name to + /// group position). + pub fn capture_name_idx(&self) -> &Arc> { + &self.ro.nfa.capture_name_idx + } +} + +impl Clone for Exec { + fn clone(&self) -> Exec { + Exec { + ro: self.ro.clone(), + cache: CachedThreadLocal::new(), + } + } +} + +impl ExecReadOnly { + fn choose_match_type(&self, hint: Option) -> MatchType { + use self::MatchType::*; + if let Some(Nfa(_)) = hint { + return hint.unwrap(); + } + // If the NFA is empty, then we'll never match anything. + if self.nfa.insts.is_empty() { + return Nothing; + } + // If our set of prefixes is complete, then we can use it to find + // a match in lieu of a regex engine. This doesn't quite work well in + // the presence of multiple regexes, so only do it when there's one. + // + // TODO(burntsushi): Also, don't try to match literals if the regex is + // partially anchored. We could technically do it, but we'd need to + // create two sets of literals: all of them and then the subset that + // aren't anchored. We would then only search for all of them when at + // the beginning of the input and use the subset in all other cases. + if self.res.len() == 1 { + if self.nfa.prefixes.complete() { + return if self.nfa.is_anchored_start { + Literal(MatchLiteralType::AnchoredStart) + } else { + Literal(MatchLiteralType::Unanchored) + }; + } + if self.suffixes.complete() { + return if self.nfa.is_anchored_end { + Literal(MatchLiteralType::AnchoredEnd) + } else { + // This case shouldn't happen. When the regex isn't + // anchored, then complete prefixes should imply complete + // suffixes. + Literal(MatchLiteralType::Unanchored) + }; + } + } + // If we can execute the DFA, then we totally should. + if dfa::can_exec(&self.dfa) { + // Regex sets require a slightly specialized path. + if self.res.len() >= 2 { + return DfaMany; + } + // If the regex is anchored at the end but not the start, then + // just match in reverse from the end of the haystack. + if !self.nfa.is_anchored_start && self.nfa.is_anchored_end { + return DfaAnchoredReverse; + } + // If there's a longish suffix literal, then it might be faster + // to look for that first. + if self.should_suffix_scan() { + return DfaSuffix; + } + // Fall back to your garden variety forward searching lazy DFA. + return Dfa; + } + // We're so totally hosed. + Nfa(MatchNfaType::Auto) + } + + /// Returns true if the program is amenable to suffix scanning. + /// + /// When this is true, as a heuristic, we assume it is OK to quickly scan + /// for suffix literals and then do a *reverse* DFA match from any matches + /// produced by the literal scan. (And then followed by a forward DFA + /// search, since the previously found suffix literal maybe not actually be + /// the end of a match.) + /// + /// This is a bit of a specialized optimization, but can result in pretty + /// big performance wins if 1) there are no prefix literals and 2) the + /// suffix literals are pretty rare in the text. (1) is obviously easy to + /// account for but (2) is harder. As a proxy, we assume that longer + /// strings are generally rarer, so we only enable this optimization when + /// we have a meaty suffix. + fn should_suffix_scan(&self) -> bool { + if self.suffixes.is_empty() { + return false; + } + let lcs_len = self.suffixes.lcs().char_len(); + lcs_len >= 3 && lcs_len > self.dfa.prefixes.lcp().char_len() + } +} + +#[derive(Clone, Copy, Debug)] +enum MatchType { + /// A single or multiple literal search. This is only used when the regex + /// can be decomposed into unambiguous literal search. + Literal(MatchLiteralType), + /// A normal DFA search. + Dfa, + /// A reverse DFA search starting from the end of a haystack. + DfaAnchoredReverse, + /// A reverse DFA search with suffix literal scanning. + DfaSuffix, + /// Use the DFA on two or more regular expressions. + DfaMany, + /// An NFA variant. + Nfa(MatchNfaType), + /// No match is ever possible, so don't ever try to search. + Nothing, +} + +#[derive(Clone, Copy, Debug)] +enum MatchLiteralType { + /// Match literals anywhere in text. + Unanchored, + /// Match literals only at the start of text. + AnchoredStart, + /// Match literals only at the end of text. + AnchoredEnd, +} + +#[derive(Clone, Copy, Debug)] +enum MatchNfaType { + /// Choose between Backtrack and PikeVM. + Auto, + /// NFA bounded backtracking. + /// + /// (This is only set by tests, since it never makes sense to always want + /// backtracking.) + Backtrack, + /// The Pike VM. + /// + /// (This is only set by tests, since it never makes sense to always want + /// the Pike VM.) + PikeVM, +} + +/// `ProgramCache` maintains reusable allocations for each matching engine +/// available to a particular program. +pub type ProgramCache = RefCell; + +#[derive(Clone, Debug)] +pub struct ProgramCacheInner { + pub pikevm: pikevm::Cache, + pub backtrack: backtrack::Cache, + pub dfa: dfa::Cache, + pub dfa_reverse: dfa::Cache, +} + +impl ProgramCacheInner { + fn new(ro: &ExecReadOnly) -> Self { + ProgramCacheInner { + pikevm: pikevm::Cache::new(&ro.nfa), + backtrack: backtrack::Cache::new(&ro.nfa), + dfa: dfa::Cache::new(&ro.dfa), + dfa_reverse: dfa::Cache::new(&ro.dfa_reverse), + } + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/expand.rs cargo-0.26.0/vendor/regex-0.2.10/src/expand.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/expand.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/expand.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,215 @@ +use std::str; + +use memchr::memchr; + +use re_bytes; +use re_unicode; + +pub fn expand_str( + caps: &re_unicode::Captures, + mut replacement: &str, + dst: &mut String, +) { + while !replacement.is_empty() { + match memchr(b'$', replacement.as_bytes()) { + None => break, + Some(i) => { + dst.push_str(&replacement[..i]); + replacement = &replacement[i..]; + } + } + if replacement.as_bytes().get(1).map_or(false, |&b| b == b'$') { + dst.push_str("$"); + replacement = &replacement[2..]; + continue; + } + debug_assert!(!replacement.is_empty()); + let cap_ref = match find_cap_ref(replacement) { + Some(cap_ref) => cap_ref, + None => { + dst.push_str("$"); + replacement = &replacement[1..]; + continue; + } + }; + replacement = &replacement[cap_ref.end..]; + match cap_ref.cap { + Ref::Number(i) => { + dst.push_str( + caps.get(i).map(|m| m.as_str()).unwrap_or("")); + } + Ref::Named(name) => { + dst.push_str( + caps.name(name).map(|m| m.as_str()).unwrap_or("")); + } + } + } + dst.push_str(replacement); +} + +pub fn expand_bytes( + caps: &re_bytes::Captures, + mut replacement: &[u8], + dst: &mut Vec, +) { + while !replacement.is_empty() { + match memchr(b'$', replacement) { + None => break, + Some(i) => { + dst.extend(&replacement[..i]); + replacement = &replacement[i..]; + } + } + if replacement.get(1).map_or(false, |&b| b == b'$') { + dst.push(b'$'); + replacement = &replacement[2..]; + continue; + } + debug_assert!(!replacement.is_empty()); + let cap_ref = match find_cap_ref(replacement) { + Some(cap_ref) => cap_ref, + None => { + dst.push(b'$'); + replacement = &replacement[1..]; + continue; + } + }; + replacement = &replacement[cap_ref.end..]; + match cap_ref.cap { + Ref::Number(i) => { + dst.extend( + caps.get(i).map(|m| m.as_bytes()).unwrap_or(b"")); + } + Ref::Named(name) => { + dst.extend( + caps.name(name).map(|m| m.as_bytes()).unwrap_or(b"")); + } + } + } + dst.extend(replacement); +} + +/// `CaptureRef` represents a reference to a capture group inside some text. +/// The reference is either a capture group name or a number. +/// +/// It is also tagged with the position in the text immediately proceding the +/// capture reference. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct CaptureRef<'a> { + cap: Ref<'a>, + end: usize, +} + +/// A reference to a capture group in some text. +/// +/// e.g., `$2`, `$foo`, `${foo}`. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Ref<'a> { + Named(&'a str), + Number(usize), +} + +impl<'a> From<&'a str> for Ref<'a> { + fn from(x: &'a str) -> Ref<'a> { + Ref::Named(x) + } +} + +impl From for Ref<'static> { + fn from(x: usize) -> Ref<'static> { + Ref::Number(x) + } +} + +/// Parses a possible reference to a capture group name in the given text, +/// starting at the beginning of `replacement`. +/// +/// If no such valid reference could be found, None is returned. +fn find_cap_ref>( + replacement: &T, +) -> Option { + let mut i = 0; + let rep: &[u8] = replacement.as_ref(); + if rep.len() <= 1 || rep[0] != b'$' { + return None; + } + let mut brace = false; + i += 1; + if rep[i] == b'{' { + brace = true; + i += 1; + } + let mut cap_end = i; + while rep.get(cap_end).map_or(false, is_valid_cap_letter) { + cap_end += 1; + } + if cap_end == i { + return None; + } + // We just verified that the range 0..cap_end is valid ASCII, so it must + // therefore be valid UTF-8. If we really cared, we could avoid this UTF-8 + // check with either unsafe or by parsing the number straight from &[u8]. + let cap = str::from_utf8(&rep[i..cap_end]) + .expect("valid UTF-8 capture name"); + if brace { + if !rep.get(cap_end).map_or(false, |&b| b == b'}') { + return None; + } + cap_end += 1; + } + Some(CaptureRef { + cap: match cap.parse::() { + Ok(i) => Ref::Number(i as usize), + Err(_) => Ref::Named(cap), + }, + end: cap_end, + }) +} + +/// Returns true if and only if the given byte is allowed in a capture name. +fn is_valid_cap_letter(b: &u8) -> bool { + match *b { + b'0' ... b'9' | b'a' ... b'z' | b'A' ... b'Z' | b'_' => true, + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::{CaptureRef, find_cap_ref}; + + macro_rules! find { + ($name:ident, $text:expr) => { + #[test] + fn $name() { + assert_eq!(None, find_cap_ref($text)); + } + }; + ($name:ident, $text:expr, $capref:expr) => { + #[test] + fn $name() { + assert_eq!(Some($capref), find_cap_ref($text)); + } + }; + } + + macro_rules! c { + ($name_or_number:expr, $pos:expr) => { + CaptureRef { cap: $name_or_number.into(), end: $pos } + }; + } + + find!(find_cap_ref1, "$foo", c!("foo", 4)); + find!(find_cap_ref2, "${foo}", c!("foo", 6)); + find!(find_cap_ref3, "$0", c!(0, 2)); + find!(find_cap_ref4, "$5", c!(5, 2)); + find!(find_cap_ref5, "$10", c!(10, 3)); + find!(find_cap_ref6, "$42a", c!("42a", 4)); + find!(find_cap_ref7, "${42}a", c!(42, 5)); + find!(find_cap_ref8, "${42"); + find!(find_cap_ref9, "${42 "); + find!(find_cap_ref10, " $0 "); + find!(find_cap_ref11, "$"); + find!(find_cap_ref12, " "); + find!(find_cap_ref13, ""); +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/freqs.rs cargo-0.26.0/vendor/regex-0.2.10/src/freqs.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/freqs.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/freqs.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,271 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// NOTE: The following code was generated by "scripts/frequencies.py", do not +// edit directly + +pub const BYTE_FREQUENCIES: [u8; 256] = [ + 55, // '\x00' + 52, // '\x01' + 51, // '\x02' + 50, // '\x03' + 49, // '\x04' + 48, // '\x05' + 47, // '\x06' + 46, // '\x07' + 45, // '\x08' + 103, // '\t' + 242, // '\n' + 66, // '\x0b' + 67, // '\x0c' + 229, // '\r' + 44, // '\x0e' + 43, // '\x0f' + 42, // '\x10' + 41, // '\x11' + 40, // '\x12' + 39, // '\x13' + 38, // '\x14' + 37, // '\x15' + 36, // '\x16' + 35, // '\x17' + 34, // '\x18' + 33, // '\x19' + 56, // '\x1a' + 32, // '\x1b' + 31, // '\x1c' + 30, // '\x1d' + 29, // '\x1e' + 28, // '\x1f' + 255, // ' ' + 148, // '!' + 164, // '"' + 149, // '#' + 136, // '$' + 160, // '%' + 155, // '&' + 173, // "'" + 221, // '(' + 222, // ')' + 134, // '*' + 122, // '+' + 232, // ',' + 202, // '-' + 215, // '.' + 224, // '/' + 208, // '0' + 220, // '1' + 204, // '2' + 187, // '3' + 183, // '4' + 179, // '5' + 177, // '6' + 168, // '7' + 178, // '8' + 200, // '9' + 226, // ':' + 195, // ';' + 154, // '<' + 184, // '=' + 174, // '>' + 126, // '?' + 120, // '@' + 191, // 'A' + 157, // 'B' + 194, // 'C' + 170, // 'D' + 189, // 'E' + 162, // 'F' + 161, // 'G' + 150, // 'H' + 193, // 'I' + 142, // 'J' + 137, // 'K' + 171, // 'L' + 176, // 'M' + 185, // 'N' + 167, // 'O' + 186, // 'P' + 112, // 'Q' + 175, // 'R' + 192, // 'S' + 188, // 'T' + 156, // 'U' + 140, // 'V' + 143, // 'W' + 123, // 'X' + 133, // 'Y' + 128, // 'Z' + 147, // '[' + 138, // '\\' + 146, // ']' + 114, // '^' + 223, // '_' + 151, // '`' + 249, // 'a' + 216, // 'b' + 238, // 'c' + 236, // 'd' + 253, // 'e' + 227, // 'f' + 218, // 'g' + 230, // 'h' + 247, // 'i' + 135, // 'j' + 180, // 'k' + 241, // 'l' + 233, // 'm' + 246, // 'n' + 244, // 'o' + 231, // 'p' + 139, // 'q' + 245, // 'r' + 243, // 's' + 251, // 't' + 235, // 'u' + 201, // 'v' + 196, // 'w' + 240, // 'x' + 214, // 'y' + 152, // 'z' + 182, // '{' + 205, // '|' + 181, // '}' + 127, // '~' + 27, // '\x7f' + 212, // '\x80' + 211, // '\x81' + 210, // '\x82' + 213, // '\x83' + 228, // '\x84' + 197, // '\x85' + 169, // '\x86' + 159, // '\x87' + 131, // '\x88' + 172, // '\x89' + 105, // '\x8a' + 80, // '\x8b' + 98, // '\x8c' + 96, // '\x8d' + 97, // '\x8e' + 81, // '\x8f' + 207, // '\x90' + 145, // '\x91' + 116, // '\x92' + 115, // '\x93' + 144, // '\x94' + 130, // '\x95' + 153, // '\x96' + 121, // '\x97' + 107, // '\x98' + 132, // '\x99' + 109, // '\x9a' + 110, // '\x9b' + 124, // '\x9c' + 111, // '\x9d' + 82, // '\x9e' + 108, // '\x9f' + 118, // '\xa0' + 141, // '¡' + 113, // '¢' + 129, // '£' + 119, // '¤' + 125, // '¥' + 165, // '¦' + 117, // '§' + 92, // '¨' + 106, // '©' + 83, // 'ª' + 72, // '«' + 99, // '¬' + 93, // '\xad' + 65, // '®' + 79, // '¯' + 166, // '°' + 237, // '±' + 163, // '²' + 199, // '³' + 190, // '´' + 225, // 'µ' + 209, // '¶' + 203, // '·' + 198, // '¸' + 217, // '¹' + 219, // 'º' + 206, // '»' + 234, // '¼' + 248, // '½' + 158, // '¾' + 239, // '¿' + 255, // 'À' + 255, // 'Á' + 255, // 'Â' + 255, // 'Ã' + 255, // 'Ä' + 255, // 'Å' + 255, // 'Æ' + 255, // 'Ç' + 255, // 'È' + 255, // 'É' + 255, // 'Ê' + 255, // 'Ë' + 255, // 'Ì' + 255, // 'Í' + 255, // 'Î' + 255, // 'Ï' + 255, // 'Ð' + 255, // 'Ñ' + 255, // 'Ò' + 255, // 'Ó' + 255, // 'Ô' + 255, // 'Õ' + 255, // 'Ö' + 255, // '×' + 255, // 'Ø' + 255, // 'Ù' + 255, // 'Ú' + 255, // 'Û' + 255, // 'Ü' + 255, // 'Ý' + 255, // 'Þ' + 255, // 'ß' + 255, // 'à' + 255, // 'á' + 255, // 'â' + 255, // 'ã' + 255, // 'ä' + 255, // 'å' + 255, // 'æ' + 255, // 'ç' + 255, // 'è' + 255, // 'é' + 255, // 'ê' + 255, // 'ë' + 255, // 'ì' + 255, // 'í' + 255, // 'î' + 255, // 'ï' + 255, // 'ð' + 255, // 'ñ' + 255, // 'ò' + 255, // 'ó' + 255, // 'ô' + 255, // 'õ' + 255, // 'ö' + 255, // '÷' + 255, // 'ø' + 255, // 'ù' + 255, // 'ú' + 255, // 'û' + 255, // 'ü' + 255, // 'ý' + 255, // 'þ' + 255, // 'ÿ' +]; diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/input.rs cargo-0.26.0/vendor/regex-0.2.10/src/input.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/input.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/input.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,420 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::char; +use std::cmp::Ordering; +use std::fmt; +use std::ops; +use std::u32; + +use syntax; + +use literal::LiteralSearcher; +use prog::InstEmptyLook; +use utf8::{decode_utf8, decode_last_utf8}; + +/// Represents a location in the input. +#[derive(Clone, Copy, Debug)] +pub struct InputAt { + pos: usize, + c: Char, + byte: Option, + len: usize, +} + +impl InputAt { + /// Returns true iff this position is at the beginning of the input. + pub fn is_start(&self) -> bool { + self.pos == 0 + } + + /// Returns true iff this position is past the end of the input. + pub fn is_end(&self) -> bool { + self.c.is_none() && self.byte.is_none() + } + + /// Returns the character at this position. + /// + /// If this position is just before or after the input, then an absent + /// character is returned. + pub fn char(&self) -> Char { + self.c + } + + /// Returns the byte at this position. + pub fn byte(&self) -> Option { + self.byte + } + + /// Returns the UTF-8 width of the character at this position. + pub fn len(&self) -> usize { + self.len + } + + /// Returns whether the UTF-8 width of the character at this position + /// is zero. + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Returns the byte offset of this position. + pub fn pos(&self) -> usize { + self.pos + } + + /// Returns the byte offset of the next position in the input. + pub fn next_pos(&self) -> usize { + self.pos + self.len + } +} + +/// An abstraction over input used in the matching engines. +pub trait Input { + /// Return an encoding of the position at byte offset `i`. + fn at(&self, i: usize) -> InputAt; + + /// Return the Unicode character occurring next to `at`. + /// + /// If no such character could be decoded, then `Char` is absent. + fn next_char(&self, at: InputAt) -> Char; + + /// Return the Unicode character occurring previous to `at`. + /// + /// If no such character could be decoded, then `Char` is absent. + fn previous_char(&self, at: InputAt) -> Char; + + /// Return true if the given empty width instruction matches at the + /// input position given. + fn is_empty_match(&self, at: InputAt, empty: &InstEmptyLook) -> bool; + + /// Scan the input for a matching prefix. + fn prefix_at( + &self, + prefixes: &LiteralSearcher, + at: InputAt, + ) -> Option; + + /// The number of bytes in the input. + fn len(&self) -> usize; + + /// Whether the input is empty. + fn is_empty(&self) -> bool { self.len() == 0 } + + /// Return the given input as a sequence of bytes. + fn as_bytes(&self) -> &[u8]; +} + +impl<'a, T: Input> Input for &'a T { + fn at(&self, i: usize) -> InputAt { (**self).at(i) } + + fn next_char(&self, at: InputAt) -> Char { (**self).next_char(at) } + + fn previous_char(&self, at: InputAt) -> Char { (**self).previous_char(at) } + + fn is_empty_match(&self, at: InputAt, empty: &InstEmptyLook) -> bool { + (**self).is_empty_match(at, empty) + } + + fn prefix_at( + &self, + prefixes: &LiteralSearcher, + at: InputAt, + ) -> Option { + (**self).prefix_at(prefixes, at) + } + + fn len(&self) -> usize { (**self).len() } + + fn as_bytes(&self) -> &[u8] { (**self).as_bytes() } +} + +/// An input reader over characters. +#[derive(Clone, Copy, Debug)] +pub struct CharInput<'t>(&'t [u8]); + +impl<'t> CharInput<'t> { + /// Return a new character input reader for the given string. + pub fn new(s: &'t [u8]) -> CharInput<'t> { + CharInput(s) + } +} + +impl<'t> ops::Deref for CharInput<'t> { + type Target = [u8]; + + fn deref(&self) -> &[u8] { + self.0 + } +} + +impl<'t> Input for CharInput<'t> { + fn at(&self, i: usize) -> InputAt { + let c = decode_utf8(&self[i..]).map(|(c, _)| c).into(); + InputAt { + pos: i, + c: c, + byte: None, + len: c.len_utf8(), + } + } + + fn next_char(&self, at: InputAt) -> Char { + at.char() + } + + fn previous_char(&self, at: InputAt) -> Char { + decode_last_utf8(&self[..at.pos()]).map(|(c, _)| c).into() + } + + fn is_empty_match(&self, at: InputAt, empty: &InstEmptyLook) -> bool { + use prog::EmptyLook::*; + match empty.look { + StartLine => { + let c = self.previous_char(at); + at.pos() == 0 || c == '\n' + } + EndLine => { + let c = self.next_char(at); + at.pos() == self.len() || c == '\n' + } + StartText => at.pos() == 0, + EndText => at.pos() == self.len(), + WordBoundary => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + c1.is_word_char() != c2.is_word_char() + } + NotWordBoundary => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + c1.is_word_char() == c2.is_word_char() + } + WordBoundaryAscii => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + c1.is_word_byte() != c2.is_word_byte() + } + NotWordBoundaryAscii => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + c1.is_word_byte() == c2.is_word_byte() + } + } + } + + fn prefix_at( + &self, + prefixes: &LiteralSearcher, + at: InputAt, + ) -> Option { + prefixes.find(&self[at.pos()..]).map(|(s, _)| self.at(at.pos() + s)) + } + + fn len(&self) -> usize { + self.0.len() + } + + fn as_bytes(&self) -> &[u8] { + self.0 + } +} + +/// An input reader over bytes. +#[derive(Clone, Copy, Debug)] +pub struct ByteInput<'t> { + text: &'t [u8], + only_utf8: bool, +} + +impl<'t> ByteInput<'t> { + /// Return a new byte-based input reader for the given string. + pub fn new(text: &'t [u8], only_utf8: bool) -> ByteInput<'t> { + ByteInput { + text: text, + only_utf8: only_utf8, + } + } +} + +impl<'t> ops::Deref for ByteInput<'t> { + type Target = [u8]; + + fn deref(&self) -> &[u8] { + self.text + } +} + +impl<'t> Input for ByteInput<'t> { + fn at(&self, i: usize) -> InputAt { + InputAt { + pos: i, + c: None.into(), + byte: self.get(i).cloned(), + len: 1, + } + } + + fn next_char(&self, at: InputAt) -> Char { + decode_utf8(&self[at.pos()..]).map(|(c, _)| c).into() + } + + fn previous_char(&self, at: InputAt) -> Char { + decode_last_utf8(&self[..at.pos()]).map(|(c, _)| c).into() + } + + fn is_empty_match(&self, at: InputAt, empty: &InstEmptyLook) -> bool { + use prog::EmptyLook::*; + match empty.look { + StartLine => { + let c = self.previous_char(at); + at.pos() == 0 || c == '\n' + } + EndLine => { + let c = self.next_char(at); + at.pos() == self.len() || c == '\n' + } + StartText => at.pos() == 0, + EndText => at.pos() == self.len(), + WordBoundary => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + c1.is_word_char() != c2.is_word_char() + } + NotWordBoundary => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + c1.is_word_char() == c2.is_word_char() + } + WordBoundaryAscii => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + if self.only_utf8 { + // If we must match UTF-8, then we can't match word + // boundaries at invalid UTF-8. + if c1.is_none() && !at.is_start() { + return false; + } + if c2.is_none() && !at.is_end() { + return false; + } + } + c1.is_word_byte() != c2.is_word_byte() + } + NotWordBoundaryAscii => { + let (c1, c2) = (self.previous_char(at), self.next_char(at)); + if self.only_utf8 { + // If we must match UTF-8, then we can't match word + // boundaries at invalid UTF-8. + if c1.is_none() && !at.is_start() { + return false; + } + if c2.is_none() && !at.is_end() { + return false; + } + } + c1.is_word_byte() == c2.is_word_byte() + } + } + } + + fn prefix_at( + &self, + prefixes: &LiteralSearcher, + at: InputAt, + ) -> Option { + prefixes.find(&self[at.pos()..]).map(|(s, _)| self.at(at.pos() + s)) + } + + fn len(&self) -> usize { + self.text.len() + } + + fn as_bytes(&self) -> &[u8] { + self.text + } +} + +/// An inline representation of `Option`. +/// +/// This eliminates the need to do case analysis on `Option` to determine +/// ordinality with other characters. +/// +/// (The `Option` is not related to encoding. Instead, it is used in the +/// matching engines to represent the beginning and ending boundaries of the +/// search text.) +#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] +pub struct Char(u32); + +impl fmt::Debug for Char { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match char::from_u32(self.0) { + None => write!(f, "Empty"), + Some(c) => write!(f, "{:?}", c), + } + } +} + +impl Char { + /// Returns true iff the character is absent. + #[inline] + pub fn is_none(self) -> bool { self.0 == u32::MAX } + + /// Returns the length of the character's UTF-8 encoding. + /// + /// If the character is absent, then `0` is returned. + #[inline] + pub fn len_utf8(self) -> usize { + char::from_u32(self.0).map_or(0, |c| c.len_utf8()) + } + + /// Returns true iff the character is a word character. + /// + /// If the character is absent, then false is returned. + pub fn is_word_char(self) -> bool { + char::from_u32(self.0).map_or(false, syntax::is_word_character) + } + + /// Returns true iff the byte is a word byte. + /// + /// If the byte is absent, then false is returned. + pub fn is_word_byte(self) -> bool { + match char::from_u32(self.0) { + Some(c) if c <= '\u{7F}' => syntax::is_word_byte(c as u8), + None | Some(_) => false, + } + } +} + +impl From for Char { + fn from(c: char) -> Char { Char(c as u32) } +} + +impl From> for Char { + fn from(c: Option) -> Char { + c.map_or(Char(u32::MAX), |c| c.into()) + } +} + +impl PartialEq for Char { + #[inline] + fn eq(&self, other: &char) -> bool { self.0 == *other as u32 } +} + +impl PartialEq for char { + #[inline] + fn eq(&self, other: &Char) -> bool { *self as u32 == other.0 } +} + +impl PartialOrd for Char { + #[inline] + fn partial_cmp(&self, other: &char) -> Option { + self.0.partial_cmp(&(*other as u32)) + } +} + +impl PartialOrd for char { + #[inline] + fn partial_cmp(&self, other: &Char) -> Option { + (*self as u32).partial_cmp(&other.0) + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/lib.rs cargo-0.26.0/vendor/regex-0.2.10/src/lib.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,675 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +This crate provides a library for parsing, compiling, and executing regular +expressions. Its syntax is similar to Perl-style regular expressions, but lacks +a few features like look around and backreferences. In exchange, all searches +execute in linear time with respect to the size of the regular expression and +search text. + +This crate's documentation provides some simple examples, describes +[Unicode support](#unicode) and exhaustively lists the +[supported syntax](#syntax). + +For more specific details on the API for regular expressions, please see the +documentation for the [`Regex`](struct.Regex.html) type. + +# Usage + +This crate is [on crates.io](https://crates.io/crates/regex) and can be +used by adding `regex` to your dependencies in your project's `Cargo.toml`. + +```toml +[dependencies] +regex = "0.2" +``` + +and this to your crate root: + +```rust +extern crate regex; +``` + +# Example: find a date + +General use of regular expressions in this package involves compiling an +expression and then using it to search, split or replace text. For example, +to confirm that some text resembles a date: + +```rust +use regex::Regex; +let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); +assert!(re.is_match("2014-01-01")); +``` + +Notice the use of the `^` and `$` anchors. In this crate, every expression +is executed with an implicit `.*?` at the beginning and end, which allows +it to match anywhere in the text. Anchors can be used to ensure that the +full text matches an expression. + +This example also demonstrates the utility of +[raw strings](https://doc.rust-lang.org/stable/reference/tokens.html#raw-string-literals) +in Rust, which +are just like regular strings except they are prefixed with an `r` and do +not process any escape sequences. For example, `"\\d"` is the same +expression as `r"\d"`. + +# Example: Avoid compiling the same regex in a loop + +It is an anti-pattern to compile the same regular expression in a loop +since compilation is typically expensive. (It takes anywhere from a few +microseconds to a few **milliseconds** depending on the size of the +regex.) Not only is compilation itself expensive, but this also prevents +optimizations that reuse allocations internally to the matching engines. + +In Rust, it can sometimes be a pain to pass regular expressions around if +they're used from inside a helper function. Instead, we recommend using the +[`lazy_static`](https://crates.io/crates/lazy_static) crate to ensure that +regular expressions are compiled exactly once. + +For example: + +```rust +#[macro_use] extern crate lazy_static; +extern crate regex; + +use regex::Regex; + +fn some_helper_function(text: &str) -> bool { + lazy_static! { + static ref RE: Regex = Regex::new("...").unwrap(); + } + RE.is_match(text) +} + +fn main() {} +``` + +Specifically, in this example, the regex will be compiled when it is used for +the first time. On subsequent uses, it will reuse the previous compilation. + +# Example: iterating over capture groups + +This crate provides convenient iterators for matching an expression +repeatedly against a search string to find successive non-overlapping +matches. For example, to find all dates in a string and be able to access +them by their component pieces: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap(); +let text = "2012-03-14, 2013-01-01 and 2014-07-05"; +for cap in re.captures_iter(text) { + println!("Month: {} Day: {} Year: {}", &cap[2], &cap[3], &cap[1]); +} +// Output: +// Month: 03 Day: 14 Year: 2012 +// Month: 01 Day: 01 Year: 2013 +// Month: 07 Day: 05 Year: 2014 +# } +``` + +Notice that the year is in the capture group indexed at `1`. This is +because the *entire match* is stored in the capture group at index `0`. + +# Example: replacement with named capture groups + +Building on the previous example, perhaps we'd like to rearrange the date +formats. This can be done with text replacement. But to make the code +clearer, we can *name* our capture groups and use those names as variables +in our replacement text: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"(?P\d{4})-(?P\d{2})-(?P\d{2})").unwrap(); +let before = "2012-03-14, 2013-01-01 and 2014-07-05"; +let after = re.replace_all(before, "$m/$d/$y"); +assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014"); +# } +``` + +The `replace` methods are actually polymorphic in the replacement, which +provides more flexibility than is seen here. (See the documentation for +`Regex::replace` for more details.) + +Note that if your regex gets complicated, you can use the `x` flag to +enable insigificant whitespace mode, which also lets you write comments: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"(?x) + (?P\d{4}) # the year + - + (?P\d{2}) # the month + - + (?P\d{2}) # the day +").unwrap(); +let before = "2012-03-14, 2013-01-01 and 2014-07-05"; +let after = re.replace_all(before, "$m/$d/$y"); +assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014"); +# } +``` + +If you wish to match against whitespace in this mode, you can still use `\s`, +`\n`, `\t`, etc. For escaping a single space character, you can use its hex +character code `\x20` or temporarily disable the `x` flag, e.g., `(?-x: )`. + +# Example: match multiple regular expressions simultaneously + +This demonstrates how to use a `RegexSet` to match multiple (possibly +overlapping) regular expressions in a single scan of the search text: + +```rust +use regex::RegexSet; + +let set = RegexSet::new(&[ + r"\w+", + r"\d+", + r"\pL+", + r"foo", + r"bar", + r"barfoo", + r"foobar", +]).unwrap(); + +// Iterate over and collect all of the matches. +let matches: Vec<_> = set.matches("foobar").into_iter().collect(); +assert_eq!(matches, vec![0, 2, 3, 4, 6]); + +// You can also test whether a particular regex matched: +let matches = set.matches("foobar"); +assert!(!matches.matched(5)); +assert!(matches.matched(6)); +``` + +# Pay for what you use + +With respect to searching text with a regular expression, there are three +questions that can be asked: + +1. Does the text match this expression? +2. If so, where does it match? +3. Where did the capturing groups match? + +Generally speaking, this crate could provide a function to answer only #3, +which would subsume #1 and #2 automatically. However, it can be significantly +more expensive to compute the location of capturing group matches, so it's best +not to do it if you don't need to. + +Therefore, only use what you need. For example, don't use `find` if you +only need to test if an expression matches a string. (Use `is_match` +instead.) + +# Unicode + +This implementation executes regular expressions **only** on valid UTF-8 +while exposing match locations as byte indices into the search string. + +Only simple case folding is supported. Namely, when matching +case-insensitively, the characters are first mapped using the "simple" case +folding rules defined by Unicode. + +Regular expressions themselves are **only** interpreted as a sequence of +Unicode scalar values. This means you can use Unicode characters directly +in your expression: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"(?i)Δ+").unwrap(); +let mat = re.find("ΔδΔ").unwrap(); +assert_eq!((mat.start(), mat.end()), (0, 6)); +# } +``` + +Most features of the regular expressions in this crate are Unicode aware. Here +are some examples: + +* `.` will match any valid UTF-8 encoded Unicode scalar value except for `\n`. + (To also match `\n`, enable the `s` flag, e.g., `(?s:.)`.) +* `\w`, `\d` and `\s` are Unicode aware. For example, `\s` will match all forms + of whitespace categorized by Unicode. +* `\b` matches a Unicode word boundary. +* Negated character classes like `[^a]` match all Unicode scalar values except + for `a`. +* `^` and `$` are **not** Unicode aware in multi-line mode. Namely, they only + recognize `\n` and not any of the other forms of line terminators defined + by Unicode. + +Unicode general categories, scripts, script extensions, ages and a smattering +of boolean properties are available as character classes. For example, you can +match a sequence of numerals, Greek or Cherokee letters: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"[\pN\p{Greek}\p{Cherokee}]+").unwrap(); +let mat = re.find("abcΔᎠβⅠᏴγδⅡxyz").unwrap(); +assert_eq!((mat.start(), mat.end()), (3, 23)); +# } +``` + +For a more detailed breakdown of Unicode support with respect to +[UTS#18](http://unicode.org/reports/tr18/), +please see the +[UNICODE](https://github.com/rust-lang/regex/blob/master/UNICODE.md) +document in the root of the regex repository. + +# Opt out of Unicode support + +The `bytes` sub-module provides a `Regex` type that can be used to match +on `&[u8]`. By default, text is interpreted as UTF-8 just like it is with +the main `Regex` type. However, this behavior can be disabled by turning +off the `u` flag, even if doing so could result in matching invalid UTF-8. +For example, when the `u` flag is disabled, `.` will match any byte instead +of any Unicode scalar value. + +Disabling the `u` flag is also possible with the standard `&str`-based `Regex` +type, but it is only allowed where the UTF-8 invariant is maintained. For +example, `(?-u:\w)` is an ASCII-only `\w` character class and is legal in an +`&str`-based `Regex`, but `(?-u:\xFF)` will attempt to match the raw byte +`\xFF`, which is invalid UTF-8 and therefore is illegal in `&str`-based +regexes. + +# Syntax + +The syntax supported in this crate is documented below. + +Note that the regular expression parser and abstract syntax are exposed in +a separate crate, [`regex-syntax`](../regex_syntax/index.html). + +## Matching one character + +
      +.             any character except new line (includes new line with s flag)
      +\d            digit (\p{Nd})
      +\D            not digit
      +\pN           One-letter name Unicode character class
      +\p{Greek}     Unicode character class (general category or script)
      +\PN           Negated one-letter name Unicode character class
      +\P{Greek}     negated Unicode character class (general category or script)
      +
      + +### Character classes + +
      +[xyz]         A character class matching either x, y or z (union).
      +[^xyz]        A character class matching any character except x, y and z.
      +[a-z]         A character class matching any character in range a-z.
      +[[:alpha:]]   ASCII character class ([A-Za-z])
      +[[:^alpha:]]  Negated ASCII character class ([^A-Za-z])
      +[x[^xyz]]     Nested/grouping character class (matching any character except y and z)
      +[a-y&&xyz]    Intersection (matching x or y)
      +[0-9&&[^4]]   Subtraction using intersection and negation (matching 0-9 except 4)
      +[0-9--4]      Direct subtraction (matching 0-9 except 4)
      +[a-g~~b-h]    Symmetric difference (matching `a` and `h` only)
      +[\[\]]        Escaping in character classes (matching [ or ])
      +
      + +Any named character class may appear inside a bracketed `[...]` character +class. For example, `[\p{Greek}[:digit:]]` matches any Greek or ASCII +digit. `[\p{Greek}&&\pL]` matches Greek letters. + +Precedence in character classes, from most binding to least: + +1. Ranges: `a-cd` == `[a-c]d` +2. Union: `ab&&bc` == `[ab]&&[bc]` +3. Intersection: `^a-z&&b` == `^[a-z&&b]` +4. Negation + +## Composites + +
      +xy    concatenation (x followed by y)
      +x|y   alternation (x or y, prefer x)
      +
      + +## Repetitions + +
      +x*        zero or more of x (greedy)
      +x+        one or more of x (greedy)
      +x?        zero or one of x (greedy)
      +x*?       zero or more of x (ungreedy/lazy)
      +x+?       one or more of x (ungreedy/lazy)
      +x??       zero or one of x (ungreedy/lazy)
      +x{n,m}    at least n x and at most m x (greedy)
      +x{n,}     at least n x (greedy)
      +x{n}      exactly n x
      +x{n,m}?   at least n x and at most m x (ungreedy/lazy)
      +x{n,}?    at least n x (ungreedy/lazy)
      +x{n}?     exactly n x
      +
      + +## Empty matches + +
      +^     the beginning of text (or start-of-line with multi-line mode)
      +$     the end of text (or end-of-line with multi-line mode)
      +\A    only the beginning of text (even with multi-line mode enabled)
      +\z    only the end of text (even with multi-line mode enabled)
      +\b    a Unicode word boundary (\w on one side and \W, \A, or \z on other)
      +\B    not a Unicode word boundary
      +
      + +## Grouping and flags + +
      +(exp)          numbered capture group (indexed by opening parenthesis)
      +(?P<name>exp)  named (also numbered) capture group (allowed chars: [_0-9a-zA-Z])
      +(?:exp)        non-capturing group
      +(?flags)       set flags within current group
      +(?flags:exp)   set flags for exp (non-capturing)
      +
      + +Flags are each a single character. For example, `(?x)` sets the flag `x` +and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at +the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets +the `x` flag and clears the `y` flag. + +All flags are by default disabled unless stated otherwise. They are: + +
      +i     case-insensitive: letters match both upper and lower case
      +m     multi-line mode: ^ and $ match begin/end of line
      +s     allow . to match \n
      +U     swap the meaning of x* and x*?
      +u     Unicode support (enabled by default)
      +x     ignore whitespace and allow line comments (starting with `#`)
      +
      + +Flags can be toggled within a pattern. Here's an example that matches +case-insensitively for the first part but case-sensitively for the second part: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"(?i)a+(?-i)b+").unwrap(); +let cap = re.captures("AaAaAbbBBBb").unwrap(); +assert_eq!(&cap[0], "AaAaAbb"); +# } +``` + +Notice that the `a+` matches either `a` or `A`, but the `b+` only matches +`b`. + +Multi-line mode means `^` and `$` no longer match just at the beginning/end of +the input, but at the beginning/end of lines: + +``` +# use regex::Regex; +let re = Regex::new(r"(?m)^line \d+").unwrap(); +let m = re.find("line one\nline 2\n").unwrap(); +assert_eq!(m.as_str(), "line 2"); +``` + +Note that `^` matches after new lines, even at the end of input: + +``` +# use regex::Regex; +let re = Regex::new(r"(?m)^").unwrap(); +let m = re.find_iter("test\n").last().unwrap(); +assert_eq!((m.start(), m.end()), (5, 5)); +``` + +Here is an example that uses an ASCII word boundary instead of a Unicode +word boundary: + +```rust +# extern crate regex; use regex::Regex; +# fn main() { +let re = Regex::new(r"(?-u:\b).+(?-u:\b)").unwrap(); +let cap = re.captures("$$abc$$").unwrap(); +assert_eq!(&cap[0], "abc"); +# } +``` + +## Escape sequences + +
      +\*          literal *, works for any punctuation character: \.+*?()|[]{}^$
      +\a          bell (\x07)
      +\f          form feed (\x0C)
      +\t          horizontal tab
      +\n          new line
      +\r          carriage return
      +\v          vertical tab (\x0B)
      +\123        octal character code (up to three digits)
      +\x7F        hex character code (exactly two digits)
      +\x{10FFFF}  any hex character code corresponding to a Unicode code point
      +\u007F      hex character code (exactly four digits)
      +\u{7F}      any hex character code corresponding to a Unicode code point
      +\U0000007F  hex character code (exactly eight digits)
      +\U{7F}      any hex character code corresponding to a Unicode code point
      +
      + +## Perl character classes (Unicode friendly) + +These classes are based on the definitions provided in +[UTS#18](http://www.unicode.org/reports/tr18/#Compatibility_Properties): + +
      +\d     digit (\p{Nd})
      +\D     not digit
      +\s     whitespace (\p{White_Space})
      +\S     not whitespace
      +\w     word character (\p{Alphabetic} + \p{M} + \d + \p{Pc} + \p{Join_Control})
      +\W     not word character
      +
      + +## ASCII character classes + +
      +[[:alnum:]]    alphanumeric ([0-9A-Za-z])
      +[[:alpha:]]    alphabetic ([A-Za-z])
      +[[:ascii:]]    ASCII ([\x00-\x7F])
      +[[:blank:]]    blank ([\t ])
      +[[:cntrl:]]    control ([\x00-\x1F\x7F])
      +[[:digit:]]    digits ([0-9])
      +[[:graph:]]    graphical ([!-~])
      +[[:lower:]]    lower case ([a-z])
      +[[:print:]]    printable ([ -~])
      +[[:punct:]]    punctuation ([!-/:-@\[-`{-~])
      +[[:space:]]    whitespace ([\t\n\v\f\r ])
      +[[:upper:]]    upper case ([A-Z])
      +[[:word:]]     word characters ([0-9A-Za-z_])
      +[[:xdigit:]]   hex digit ([0-9A-Fa-f])
      +
      + +# Untrusted input + +This crate can handle both untrusted regular expressions and untrusted +search text. + +Untrusted regular expressions are handled by capping the size of a compiled +regular expression. +(See [`RegexBuilder::size_limit`](struct.RegexBuilder.html#method.size_limit).) +Without this, it would be trivial for an attacker to exhaust your system's +memory with expressions like `a{100}{100}{100}`. + +Untrusted search text is allowed because the matching engine(s) in this +crate have time complexity `O(mn)` (with `m ~ regex` and `n ~ search +text`), which means there's no way to cause exponential blow-up like with +some other regular expression engines. (We pay for this by disallowing +features like arbitrary look-ahead and backreferences.) + +When a DFA is used, pathological cases with exponential state blow up are +avoided by constructing the DFA lazily or in an "online" manner. Therefore, +at most one new state can be created for each byte of input. This satisfies +our time complexity guarantees, but can lead to unbounded memory growth +proportional to the size of the input. As a stopgap, the DFA is only +allowed to store a fixed number of states. When the limit is reached, its +states are wiped and continues on, possibly duplicating previous work. If +the limit is reached too frequently, it gives up and hands control off to +another matching engine with fixed memory requirements. +(The DFA size limit can also be tweaked. See +[`RegexBuilder::dfa_size_limit`](struct.RegexBuilder.html#method.dfa_size_limit).) +*/ + +#![deny(missing_docs)] +#![cfg_attr(test, deny(warnings))] +#![cfg_attr(feature = "pattern", feature(pattern))] +#![cfg_attr( + feature = "unstable", + feature(cfg_target_feature, target_feature, stdsimd))] + +extern crate aho_corasick; +extern crate memchr; +extern crate thread_local; +#[cfg(test)] +#[macro_use] +extern crate quickcheck; +extern crate regex_syntax as syntax; +extern crate utf8_ranges; + +pub use error::Error; +pub use re_builder::unicode::*; +pub use re_builder::set_unicode::*; +pub use re_set::unicode::*; +pub use re_trait::Locations; +pub use re_unicode::{ + Regex, Match, Captures, + CaptureNames, Matches, CaptureMatches, SubCaptureMatches, + Replacer, ReplacerRef, NoExpand, Split, SplitN, + escape, +}; + +/** +Match regular expressions on arbitrary bytes. + +This module provides a nearly identical API to the one found in the +top-level of this crate. There are two important differences: + +1. Matching is done on `&[u8]` instead of `&str`. Additionally, `Vec` +is used where `String` would have been used. +2. Unicode support can be disabled even when disabling it would result in +matching invalid UTF-8 bytes. + +# Example: match null terminated string + +This shows how to find all null-terminated strings in a slice of bytes: + +```rust +# use regex::bytes::Regex; +let re = Regex::new(r"(?-u)(?P[^\x00]+)\x00").unwrap(); +let text = b"foo\x00bar\x00baz\x00"; + +// Extract all of the strings without the null terminator from each match. +// The unwrap is OK here since a match requires the `cstr` capture to match. +let cstrs: Vec<&[u8]> = + re.captures_iter(text) + .map(|c| c.name("cstr").unwrap().as_bytes()) + .collect(); +assert_eq!(vec![&b"foo"[..], &b"bar"[..], &b"baz"[..]], cstrs); +``` + +# Example: selectively enable Unicode support + +This shows how to match an arbitrary byte pattern followed by a UTF-8 encoded +string (e.g., to extract a title from a Matroska file): + +```rust +# use std::str; +# use regex::bytes::Regex; +let re = Regex::new( + r"(?-u)\x7b\xa9(?:[\x80-\xfe]|[\x40-\xff].)(?u:(.*))" +).unwrap(); +let text = b"\x12\xd0\x3b\x5f\x7b\xa9\x85\xe2\x98\x83\x80\x98\x54\x76\x68\x65"; +let caps = re.captures(text).unwrap(); + +// Notice that despite the `.*` at the end, it will only match valid UTF-8 +// because Unicode mode was enabled with the `u` flag. Without the `u` flag, +// the `.*` would match the rest of the bytes. +let mat = caps.get(1).unwrap(); +assert_eq!((7, 10), (mat.start(), mat.end())); + +// If there was a match, Unicode mode guarantees that `title` is valid UTF-8. +let title = str::from_utf8(&caps[1]).unwrap(); +assert_eq!("☃", title); +``` + +In general, if the Unicode flag is enabled in a capture group and that capture +is part of the overall match, then the capture is *guaranteed* to be valid +UTF-8. + +# Syntax + +The supported syntax is pretty much the same as the syntax for Unicode +regular expressions with a few changes that make sense for matching arbitrary +bytes: + +1. The `u` flag can be disabled even when disabling it might cause the regex to +match invalid UTF-8. When the `u` flag is disabled, the regex is said to be in +"ASCII compatible" mode. +2. In ASCII compatible mode, neither Unicode scalar values nor Unicode +character classes are allowed. +3. In ASCII compatible mode, Perl character classes (`\w`, `\d` and `\s`) +revert to their typical ASCII definition. `\w` maps to `[[:word:]]`, `\d` maps +to `[[:digit:]]` and `\s` maps to `[[:space:]]`. +4. In ASCII compatible mode, word boundaries use the ASCII compatible `\w` to +determine whether a byte is a word byte or not. +5. Hexadecimal notation can be used to specify arbitrary bytes instead of +Unicode codepoints. For example, in ASCII compatible mode, `\xFF` matches the +literal byte `\xFF`, while in Unicode mode, `\xFF` is a Unicode codepoint that +matches its UTF-8 encoding of `\xC3\xBF`. Similarly for octal notation. +6. `.` matches any *byte* except for `\n` instead of any Unicode scalar value. +When the `s` flag is enabled, `.` matches any byte. + +# Performance + +In general, one should expect performance on `&[u8]` to be roughly similar to +performance on `&str`. +*/ +pub mod bytes { + pub use re_builder::bytes::*; + pub use re_builder::set_bytes::*; + pub use re_bytes::*; + pub use re_set::bytes::*; + pub use re_trait::Locations; +} + +mod backtrack; +mod utf8; +mod compile; +mod dfa; +mod error; +mod exec; +mod expand; +mod freqs; +mod input; +mod literal; +#[cfg(feature = "pattern")] +mod pattern; +mod pikevm; +mod prog; +mod re_builder; +mod re_bytes; +mod re_set; +mod re_trait; +mod re_unicode; +mod sparse; +#[cfg(feature = "unstable")] +mod vector; + +/// The `internal` module exists to support suspicious activity, such as +/// testing different matching engines and supporting the `regex-debug` CLI +/// utility. +#[doc(hidden)] +pub mod internal { + pub use compile::Compiler; + pub use exec::{Exec, ExecBuilder}; + pub use input::{Char, Input, CharInput, InputAt}; + pub use literal::LiteralSearcher; + pub use prog::{Program, Inst, EmptyLook, InstRanges}; +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/literal/mod.rs cargo-0.26.0/vendor/regex-0.2.10/src/literal/mod.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/literal/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/literal/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1141 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cmp; +use std::mem; + +use aho_corasick::{Automaton, AcAutomaton, FullAcAutomaton}; +use memchr::{memchr, memchr2, memchr3}; +use syntax::hir::literal::{Literal, Literals}; + +use freqs::BYTE_FREQUENCIES; +use self::teddy_avx2::{Teddy as TeddyAVX2}; +use self::teddy_ssse3::{Teddy as TeddySSSE3}; + +mod teddy_avx2; +mod teddy_ssse3; + +/// A prefix extracted from a compiled regular expression. +/// +/// A regex prefix is a set of literal strings that *must* be matched at the +/// beginning of a regex in order for the entire regex to match. Similarly +/// for a regex suffix. +#[derive(Clone, Debug)] +pub struct LiteralSearcher { + complete: bool, + lcp: FreqyPacked, + lcs: FreqyPacked, + matcher: Matcher, +} + +#[derive(Clone, Debug)] +enum Matcher { + /// No literals. (Never advances through the input.) + Empty, + /// A set of four or more single byte literals. + Bytes(SingleByteSet), + /// A single substring, find using memchr and frequency analysis. + FreqyPacked(FreqyPacked), + /// A single substring, find using Boyer-Moore. + BoyerMoore(BoyerMooreSearch), + /// An Aho-Corasick automaton. + AC(FullAcAutomaton), + /// A simd accelerated multiple string matcher. Used only for a small + /// number of small literals. + TeddySSSE3(TeddySSSE3), + /// A simd accelerated multiple string matcher. Used only for a small + /// number of small literals. This uses 256-bit vectors. + TeddyAVX2(TeddyAVX2), +} + +impl LiteralSearcher { + /// Returns a matcher that never matches and never advances the input. + pub fn empty() -> Self { + Self::new(Literals::empty(), Matcher::Empty) + } + + /// Returns a matcher for literal prefixes from the given set. + pub fn prefixes(lits: Literals) -> Self { + let matcher = Matcher::prefixes(&lits); + Self::new(lits, matcher) + } + + /// Returns a matcher for literal suffixes from the given set. + pub fn suffixes(lits: Literals) -> Self { + let matcher = Matcher::suffixes(&lits); + Self::new(lits, matcher) + } + + fn new(lits: Literals, matcher: Matcher) -> Self { + let complete = lits.all_complete(); + LiteralSearcher { + complete: complete, + lcp: FreqyPacked::new(lits.longest_common_prefix().to_vec()), + lcs: FreqyPacked::new(lits.longest_common_suffix().to_vec()), + matcher: matcher, + } + } + + /// Returns true if all matches comprise the entire regular expression. + /// + /// This does not necessarily mean that a literal match implies a match + /// of the regular expression. For example, the regular expresison `^a` + /// is comprised of a single complete literal `a`, but the regular + /// expression demands that it only match at the beginning of a string. + pub fn complete(&self) -> bool { + self.complete && !self.is_empty() + } + + /// Find the position of a literal in `haystack` if it exists. + #[inline(always)] // reduces constant overhead + pub fn find(&self, haystack: &[u8]) -> Option<(usize, usize)> { + use self::Matcher::*; + match self.matcher { + Empty => Some((0, 0)), + Bytes(ref sset) => sset.find(haystack).map(|i| (i, i + 1)), + FreqyPacked(ref s) => s.find(haystack).map(|i| (i, i + s.len())), + BoyerMoore(ref s) => s.find(haystack).map(|i| (i, i + s.len())), + AC(ref aut) => aut.find(haystack).next().map(|m| (m.start, m.end)), + TeddySSSE3(ref t) => t.find(haystack).map(|m| (m.start, m.end)), + TeddyAVX2(ref t) => t.find(haystack).map(|m| (m.start, m.end)), + } + } + + /// Like find, except matches must start at index `0`. + pub fn find_start(&self, haystack: &[u8]) -> Option<(usize, usize)> { + for lit in self.iter() { + if lit.len() > haystack.len() { + continue; + } + if lit == &haystack[0..lit.len()] { + return Some((0, lit.len())); + } + } + None + } + + /// Like find, except matches must end at index `haystack.len()`. + pub fn find_end(&self, haystack: &[u8]) -> Option<(usize, usize)> { + for lit in self.iter() { + if lit.len() > haystack.len() { + continue; + } + if lit == &haystack[haystack.len() - lit.len()..] { + return Some((haystack.len() - lit.len(), haystack.len())); + } + } + None + } + + /// Returns an iterator over all literals to be matched. + pub fn iter(&self) -> LiteralIter { + match self.matcher { + Matcher::Empty => LiteralIter::Empty, + Matcher::Bytes(ref sset) => LiteralIter::Bytes(&sset.dense), + Matcher::FreqyPacked(ref s) => LiteralIter::Single(&s.pat), + Matcher::BoyerMoore(ref s) => LiteralIter::Single(&s.pattern), + Matcher::AC(ref ac) => LiteralIter::AC(ac.patterns()), + Matcher::TeddySSSE3(ref ted) => { + LiteralIter::TeddySSSE3(ted.patterns()) + } + Matcher::TeddyAVX2(ref ted) => { + LiteralIter::TeddyAVX2(ted.patterns()) + } + } + } + + /// Returns a matcher for the longest common prefix of this matcher. + pub fn lcp(&self) -> &FreqyPacked { + &self.lcp + } + + /// Returns a matcher for the longest common suffix of this matcher. + pub fn lcs(&self) -> &FreqyPacked { + &self.lcs + } + + /// Returns true iff this prefix is empty. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns the number of prefixes in this machine. + pub fn len(&self) -> usize { + use self::Matcher::*; + match self.matcher { + Empty => 0, + Bytes(ref sset) => sset.dense.len(), + FreqyPacked(_) => 1, + BoyerMoore(_) => 1, + AC(ref aut) => aut.len(), + TeddySSSE3(ref ted) => ted.len(), + TeddyAVX2(ref ted) => ted.len(), + } + } + + /// Return the approximate heap usage of literals in bytes. + pub fn approximate_size(&self) -> usize { + use self::Matcher::*; + match self.matcher { + Empty => 0, + Bytes(ref sset) => sset.approximate_size(), + FreqyPacked(ref single) => single.approximate_size(), + BoyerMoore(ref single) => single.approximate_size(), + AC(ref aut) => aut.heap_bytes(), + TeddySSSE3(ref ted) => ted.approximate_size(), + TeddyAVX2(ref ted) => ted.approximate_size(), + } + } +} + +impl Matcher { + fn prefixes(lits: &Literals) -> Self { + let sset = SingleByteSet::prefixes(lits); + Matcher::new(lits, sset) + } + + fn suffixes(lits: &Literals) -> Self { + let sset = SingleByteSet::suffixes(lits); + Matcher::new(lits, sset) + } + + fn new(lits: &Literals, sset: SingleByteSet) -> Self { + if lits.literals().is_empty() { + return Matcher::Empty; + } + if sset.dense.len() >= 26 { + // Avoid trying to match a large number of single bytes. + // This is *very* sensitive to a frequency analysis comparison + // between the bytes in sset and the composition of the haystack. + // No matter the size of sset, if its members all are rare in the + // haystack, then it'd be worth using it. How to tune this... IDK. + // ---AG + return Matcher::Empty; + } + if sset.complete { + return Matcher::Bytes(sset); + } + if lits.literals().len() == 1 { + let lit = lits.literals()[0].to_vec(); + if BoyerMooreSearch::should_use(lit.as_slice()) { + return Matcher::BoyerMoore(BoyerMooreSearch::new(lit)); + } else { + return Matcher::FreqyPacked(FreqyPacked::new(lit)); + } + } + let is_aho_corasick_fast = sset.dense.len() == 1 && sset.all_ascii; + if TeddyAVX2::available() && !is_aho_corasick_fast { + const MAX_TEDDY_LITERALS: usize = 32; + if lits.literals().len() <= MAX_TEDDY_LITERALS { + if let Some(ted) = TeddyAVX2::new(lits) { + return Matcher::TeddyAVX2(ted); + } + } + } + if TeddySSSE3::available() && !is_aho_corasick_fast { + // Only try Teddy if Aho-Corasick can't use memchr on an ASCII + // byte. Also, in its current form, Teddy doesn't scale well to + // lots of literals. + // + // We impose the ASCII restriction since an alternation of + // non-ASCII string literals in the same language is likely to all + // start with the same byte. Even worse, the corpus being searched + // probably has a similar composition, which ends up completely + // negating the benefit of memchr. + const MAX_TEDDY_LITERALS: usize = 32; + if lits.literals().len() <= MAX_TEDDY_LITERALS { + if let Some(ted) = TeddySSSE3::new(lits) { + return Matcher::TeddySSSE3(ted); + } + } + // Fallthrough to ol' reliable Aho-Corasick... + } + let pats = lits.literals().to_owned(); + Matcher::AC(AcAutomaton::new(pats).into_full()) + } +} + +pub enum LiteralIter<'a> { + Empty, + Bytes(&'a [u8]), + Single(&'a [u8]), + AC(&'a [Literal]), + TeddySSSE3(&'a [Vec]), + TeddyAVX2(&'a [Vec]), +} + +impl<'a> Iterator for LiteralIter<'a> { + type Item = &'a [u8]; + + fn next(&mut self) -> Option { + match *self { + LiteralIter::Empty => None, + LiteralIter::Bytes(ref mut many) => { + if many.is_empty() { + None + } else { + let next = &many[0..1]; + *many = &many[1..]; + Some(next) + } + } + LiteralIter::Single(ref mut one) => { + if one.is_empty() { + None + } else { + let next = &one[..]; + *one = &[]; + Some(next) + } + } + LiteralIter::AC(ref mut lits) => { + if lits.is_empty() { + None + } else { + let next = &lits[0]; + *lits = &lits[1..]; + Some(&**next) + } + } + LiteralIter::TeddySSSE3(ref mut lits) => { + if lits.is_empty() { + None + } else { + let next = &lits[0]; + *lits = &lits[1..]; + Some(&**next) + } + } + LiteralIter::TeddyAVX2(ref mut lits) => { + if lits.is_empty() { + None + } else { + let next = &lits[0]; + *lits = &lits[1..]; + Some(&**next) + } + } + } + } +} + +#[derive(Clone, Debug)] +struct SingleByteSet { + sparse: Vec, + dense: Vec, + complete: bool, + all_ascii: bool, +} + +impl SingleByteSet { + fn new() -> SingleByteSet { + SingleByteSet { + sparse: vec![false; 256], + dense: vec![], + complete: true, + all_ascii: true, + } + } + + fn prefixes(lits: &Literals) -> SingleByteSet { + let mut sset = SingleByteSet::new(); + for lit in lits.literals() { + sset.complete = sset.complete && lit.len() == 1; + if let Some(&b) = lit.get(0) { + if !sset.sparse[b as usize] { + if b > 0x7F { + sset.all_ascii = false; + } + sset.dense.push(b); + sset.sparse[b as usize] = true; + } + } + } + sset + } + + fn suffixes(lits: &Literals) -> SingleByteSet { + let mut sset = SingleByteSet::new(); + for lit in lits.literals() { + sset.complete = sset.complete && lit.len() == 1; + if let Some(&b) = lit.get(lit.len().checked_sub(1).unwrap()) { + if !sset.sparse[b as usize] { + if b > 0x7F { + sset.all_ascii = false; + } + sset.dense.push(b); + sset.sparse[b as usize] = true; + } + } + } + sset + } + + /// Faster find that special cases certain sizes to use memchr. + #[inline(always)] // reduces constant overhead + fn find(&self, text: &[u8]) -> Option { + match self.dense.len() { + 0 => None, + 1 => memchr(self.dense[0], text), + 2 => memchr2(self.dense[0], self.dense[1], text), + 3 => memchr3(self.dense[0], self.dense[1], self.dense[2], text), + _ => self._find(text), + } + } + + /// Generic find that works on any sized set. + fn _find(&self, haystack: &[u8]) -> Option { + for (i, &b) in haystack.iter().enumerate() { + if self.sparse[b as usize] { + return Some(i); + } + } + None + } + + fn approximate_size(&self) -> usize { + (self.dense.len() * mem::size_of::()) + + (self.sparse.len() * mem::size_of::()) + } +} + +/// Provides an implementation of fast subtring search using frequency +/// analysis. +/// +/// memchr is so fast that we do everything we can to keep the loop in memchr +/// for as long as possible. The easiest way to do this is to intelligently +/// pick the byte to send to memchr. The best byte is the byte that occurs +/// least frequently in the haystack. Since doing frequency analysis on the +/// haystack is far too expensive, we compute a set of fixed frequencies up +/// front and hard code them in src/freqs.rs. Frequency analysis is done via +/// scripts/frequencies.py. +#[derive(Clone, Debug)] +pub struct FreqyPacked { + /// The pattern. + pat: Vec, + /// The number of Unicode characters in the pattern. This is useful for + /// determining the effective length of a pattern when deciding which + /// optimizations to perform. A trailing incomplete UTF-8 sequence counts + /// as one character. + char_len: usize, + /// The rarest byte in the pattern, according to pre-computed frequency + /// analysis. + rare1: u8, + /// The offset of the rarest byte in `pat`. + rare1i: usize, + /// The second rarest byte in the pattern, according to pre-computed + /// frequency analysis. (This may be equivalent to the rarest byte.) + /// + /// The second rarest byte is used as a type of guard for quickly detecting + /// a mismatch after memchr locates an instance of the rarest byte. This + /// is a hedge against pathological cases where the pre-computed frequency + /// analysis may be off. (But of course, does not prevent *all* + /// pathological cases.) + rare2: u8, + /// The offset of the second rarest byte in `pat`. + rare2i: usize, +} + +impl FreqyPacked { + fn new(pat: Vec) -> FreqyPacked { + if pat.is_empty() { + return FreqyPacked::empty(); + } + + // Find the rarest two bytes. Try to make them distinct (but it's not + // required). + let mut rare1 = pat[0]; + let mut rare2 = pat[0]; + for b in pat[1..].iter().cloned() { + if freq_rank(b) < freq_rank(rare1) { + rare1 = b; + } + } + for &b in &pat { + if rare1 == rare2 { + rare2 = b + } else if b != rare1 && freq_rank(b) < freq_rank(rare2) { + rare2 = b; + } + } + + // And find the offsets of their last occurrences. + let rare1i = pat.iter().rposition(|&b| b == rare1).unwrap(); + let rare2i = pat.iter().rposition(|&b| b == rare2).unwrap(); + + let char_len = char_len_lossy(&pat); + FreqyPacked { + pat: pat, + char_len: char_len, + rare1: rare1, + rare1i: rare1i, + rare2: rare2, + rare2i: rare2i, + } + } + + fn empty() -> FreqyPacked { + FreqyPacked { + pat: vec![], + char_len: 0, + rare1: 0, + rare1i: 0, + rare2: 0, + rare2i: 0, + } + } + + #[inline(always)] // reduces constant overhead + pub fn find(&self, haystack: &[u8]) -> Option { + let pat = &*self.pat; + if haystack.len() < pat.len() || pat.is_empty() { + return None; + } + let mut i = self.rare1i; + while i < haystack.len() { + i += match memchr(self.rare1, &haystack[i..]) { + None => return None, + Some(i) => i, + }; + let start = i - self.rare1i; + let end = start + pat.len(); + if end > haystack.len() { + return None; + } + let aligned = &haystack[start..end]; + if aligned[self.rare2i] == self.rare2 && aligned == &*self.pat { + return Some(start); + } + i += 1; + } + None + } + + #[inline(always)] // reduces constant overhead + pub fn is_suffix(&self, text: &[u8]) -> bool { + if text.len() < self.len() { + return false; + } + text[text.len() - self.len()..] == *self.pat + } + + pub fn len(&self) -> usize { + self.pat.len() + } + + pub fn char_len(&self) -> usize { + self.char_len + } + + fn approximate_size(&self) -> usize { + self.pat.len() * mem::size_of::() + } +} + +fn char_len_lossy(bytes: &[u8]) -> usize { + String::from_utf8_lossy(bytes).chars().count() +} + +/// An implementation of Tuned Boyer-Moore as laid out by +/// Andrew Hume and Daniel Sunday in "Fast String Searching". +/// O(n) in the size of the input. +/// +/// Fast string searching algorithms come in many variations, +/// but they can generally be described in terms of three main +/// components. +/// +/// The skip loop is where the string searcher wants to spend +/// as much time as possible. Exactly which character in the +/// pattern the skip loop examines varies from algorithm to +/// algorithm, but in the simplest case this loop repeated +/// looks at the last character in the pattern and jumps +/// forward in the input if it is not in the pattern. +/// Robert Boyer and J Moore called this the "fast" loop in +/// their original paper. +/// +/// The match loop is responsible for actually examining the +/// whole potentially matching substring. In order to fail +/// faster, the match loop sometimes has a guard test attached. +/// The guard test uses frequency analysis of the different +/// characters in the pattern to choose the least frequency +/// occurring character and use it to find match failures +/// as quickly as possible. +/// +/// The shift rule governs how the algorithm will shuffle its +/// test window in the event of a failure during the match loop. +/// Certain shift rules allow the worst-case run time of the +/// algorithm to be shown to be O(n) in the size of the input +/// rather than O(nm) in the size of the input and the size +/// of the pattern (as naive Boyer-Moore is). +/// +/// "Fast String Searching", in addition to presenting a tuned +/// algorithm, provides a comprehensive taxonomy of the many +/// different flavors of string searchers. Under that taxonomy +/// TBM, the algorithm implemented here, uses an unrolled fast +/// skip loop with memchr fallback, a forward match loop with guard, +/// and the mini Sunday's delta shift rule. To unpack that you'll have to +/// read the paper. +#[derive(Clone, Debug)] +pub struct BoyerMooreSearch { + /// The pattern we are going to look for in the haystack. + pattern: Vec, + + /// The skip table for the skip loop. + /// + /// Maps the character at the end of the input + /// to a shift. + skip_table: Vec, + + /// The guard character (least frequently occurring char). + guard: u8, + /// The reverse-index of the guard character in the pattern. + guard_reverse_idx: usize, + + /// Daniel Sunday's mini generalized delta2 shift table. + /// + /// We use a skip loop, so we only have to provide a shift + /// for the skip char (last char). This is why it is a mini + /// shift rule. + md2_shift: usize, +} + +impl BoyerMooreSearch { + /// Create a new string searcher, performing whatever + /// compilation steps are required. + fn new(pattern: Vec) -> Self { + debug_assert!(pattern.len() > 0); + + let (g, gi) = Self::select_guard(pattern.as_slice()); + let skip_table = Self::compile_skip_table(pattern.as_slice()); + let md2_shift = Self::compile_md2_shift(pattern.as_slice()); + BoyerMooreSearch { + pattern: pattern, + skip_table: skip_table, + guard: g, + guard_reverse_idx: gi, + md2_shift: md2_shift, + } + } + + /// Find the pattern in `haystack`, returning the offset + /// of the start of the first occurrence of the pattern + /// in `haystack`. + #[inline] + fn find(&self, haystack: &[u8]) -> Option { + if haystack.len() < self.pattern.len() { + return None; + } + + let mut window_end = self.pattern.len() - 1; + + // Inspired by the grep source. It is a way + // to do correct loop unrolling without having to place + // a crashpad of terminating charicters at the end in + // the way described in the Fast String Searching paper. + const NUM_UNROLL: usize = 10; + // 1 for the initial position, and 1 for the md2 shift + let short_circut = (NUM_UNROLL + 2) * self.pattern.len(); + + if haystack.len() > short_circut { + // just 1 for the md2 shift + let backstop = haystack.len() - ((NUM_UNROLL + 1) * self.pattern.len()); + loop { + window_end = match self.skip_loop(haystack, window_end, backstop) { + Some(i) => i, + None => return None, + }; + if window_end >= backstop { + break; + } + + if self.check_match(haystack, window_end) { + return Some(window_end - (self.pattern.len() - 1)); + } else { + let skip = self.skip_table[haystack[window_end] as usize]; + window_end += + if skip == 0 { self.md2_shift } else { skip }; + continue; + } + } + } + + // now process the input after the backstop + while window_end < haystack.len() { + let mut skip = self.skip_table[haystack[window_end] as usize]; + if skip == 0 { + if self.check_match(haystack, window_end) { + return Some(window_end - (self.pattern.len() - 1)); + } else { + skip = self.md2_shift; + } + } + window_end += skip; + } + + None + } + + fn len(&self) -> usize { + return self.pattern.len() + } + + /// The key heuristic behind which the BoyerMooreSearch lives. + /// + /// See `rust-lang/regex/issues/408`. + /// + /// Tuned Boyer-Moore is actually pretty slow! It turns out a handrolled + /// platform-specific memchr routine with a bit of frequency + /// analysis sprinkled on top actually wins most of the time. + /// However, there are a few cases where Tuned Boyer-Moore still + /// wins. + /// + /// If the haystack is random, frequency analysis doesn't help us, + /// so Boyer-Moore will win for sufficiently large needles. + /// Unfortunately, there is no obvious way to determine this + /// ahead of time. + /// + /// If the pattern itself consists of very common characters, + /// frequency analysis won't get us anywhere. The most extreme + /// example of this is a pattern like `eeeeeeeeeeeeeeee`. Fortunately, + /// this case is wholly determined by the pattern, so we can actually + /// implement the heuristic. + /// + /// A third case is if the pattern is sufficiently long. The idea + /// here is that once the pattern gets long enough the Tuned + /// Boyer-Moore skip loop will start making strides long enough + /// to beat the asm deep magic that is memchr. + fn should_use(pattern: &[u8]) -> bool { + // The minimum pattern length required to use TBM. + const MIN_LEN: usize = 9; + // The minimum frequency rank (lower is rarer) that every byte in the + // pattern must have in order to use TBM. That is, if the pattern + // contains _any_ byte with a lower rank, then TBM won't be used. + const MIN_CUTOFF: usize = 150; + // The maximum frequency rank for any byte. + const MAX_CUTOFF: usize = 255; + // The scaling factor used to determine the actual cutoff frequency + // to use (keeping in mind that the minimum frequency rank is bounded + // by MIN_CUTOFF). This scaling factor is an attempt to make TBM more + // likely to be used as the pattern grows longer. That is, longer + // patterns permit somewhat less frequent bytes than shorter patterns, + // under the assumption that TBM gets better as the pattern gets + // longer. + const LEN_CUTOFF_PROPORTION: usize = 4; + + let scaled_rank = pattern.len().wrapping_mul(LEN_CUTOFF_PROPORTION); + let cutoff = cmp::max( + MIN_CUTOFF, + MAX_CUTOFF - cmp::min(MAX_CUTOFF, scaled_rank), + ); + // The pattern must be long enough to be worthwhile. e.g., memchr will + // be faster on `e` because it is short even though e is quite common. + pattern.len() > MIN_LEN + // all the bytes must be more common than the cutoff. + && pattern.iter().all(|c| freq_rank(*c) >= cutoff) + } + + /// Check to see if there is a match at the given position + #[inline] + fn check_match(&self, haystack: &[u8], window_end: usize) -> bool { + // guard test + if haystack[window_end - self.guard_reverse_idx] != self.guard { + return false; + } + + // match loop + let window_start = window_end - (self.pattern.len() - 1); + for i in 0..self.pattern.len() { + if self.pattern[i] != haystack[window_start + i] { + return false; + } + } + + true + } + + /// Skip forward according to the shift table. + /// + /// Returns the offset of the next occurrence + /// of the last char in the pattern, or the none + /// if it never reappears. If `skip_loop` hits the backstop + /// it will leave early. + #[inline] + fn skip_loop(&self, + haystack: &[u8], + mut window_end: usize, + backstop: usize, + ) -> Option { + use std::mem; + + let window_end_snapshot = window_end; + let skip_of = |we: usize| -> usize { + // Unsafe might make this faster, but the benchmarks + // were hard to interpret. + self.skip_table[haystack[we] as usize] + }; + + loop { + let mut skip = skip_of(window_end); window_end += skip; + skip = skip_of(window_end); window_end += skip; + if skip != 0 { + skip = skip_of(window_end); window_end += skip; + skip = skip_of(window_end); window_end += skip; + skip = skip_of(window_end); window_end += skip; + if skip != 0 { + skip = skip_of(window_end); window_end += skip; + skip = skip_of(window_end); window_end += skip; + skip = skip_of(window_end); window_end += skip; + if skip != 0 { + skip = skip_of(window_end); window_end += skip; + skip = skip_of(window_end); window_end += skip; + + // If ten iterations did not make at least 16 words + // worth of progress, we just fall back on memchr. + if window_end - window_end_snapshot > + 16 * mem::size_of::() { + + // Returning a window_end >= backstop will immediatly + // break us out of the inner loop in `find`. + if window_end >= backstop { + return Some(window_end); + } + + continue; // we made enough progress + } else { + // In case we are already there, and so that + // we will catch the guard char. + window_end = window_end + .checked_sub(1 + self.guard_reverse_idx) + .unwrap_or(0); + + match memchr(self.guard, &haystack[window_end..]) { + None => return None, + Some(g_idx) => { + return Some(window_end + g_idx + self.guard_reverse_idx); + } + } + } + } + } + } + + return Some(window_end); + } + } + + /// Compute the ufast skip table. + fn compile_skip_table(pattern: &[u8]) -> Vec { + let mut tab = vec![pattern.len(); 256]; + + // For every char in the pattern, we write a skip + // that will line us up with the rightmost occurrence. + // + // N.B. the sentinel (0) is written by the last + // loop iteration. + for (i, c) in pattern.iter().enumerate() { + tab[*c as usize] = (pattern.len() - 1) - i; + } + + tab + } + + /// Select the guard character based off of the precomputed + /// frequency table. + fn select_guard(pattern: &[u8]) -> (u8, usize) { + let mut rarest = pattern[0]; + let mut rarest_rev_idx = pattern.len() - 1; + for (i, c) in pattern.iter().enumerate() { + if freq_rank(*c) < freq_rank(rarest) { + rarest = *c; + rarest_rev_idx = (pattern.len() - 1) - i; + } + } + + (rarest, rarest_rev_idx) + } + + /// If there is another occurrence of the skip + /// char, shift to it, otherwise just shift to + /// the next window. + fn compile_md2_shift(pattern: &[u8]) -> usize { + let shiftc = *pattern.last().unwrap(); + + // For a pattern of length 1 we will never apply the + // shift rule, so we use a poison value on the principle + // that failing fast is a good thing. + if pattern.len() == 1 { + return 0xDEADBEAF; + } + + let mut i = pattern.len() - 2; + while i > 0 { + if pattern[i] == shiftc { + return (pattern.len() - 1) - i; + } + i -= 1; + } + + // The skip char never re-occurs in the pattern, so + // we can just shift the whole window length. + pattern.len() - 1 + } + + fn approximate_size(&self) -> usize { + (self.pattern.len() * mem::size_of::()) + + (256 * mem::size_of::()) // skip table + } +} + +fn freq_rank(b: u8) -> usize { + BYTE_FREQUENCIES[b as usize] as usize +} + +#[cfg(test)] +mod tests { + use super::{BoyerMooreSearch, FreqyPacked}; + + // + // Unit Tests + // + + // The "hello, world" of string searching + #[test] + fn bm_find_subs() { + let searcher = BoyerMooreSearch::new(Vec::from(&b"pattern"[..])); + let haystack = b"I keep seeing patterns in this text"; + assert_eq!(14, searcher.find(haystack).unwrap()); + } + + #[test] + fn bm_find_no_subs() { + let searcher = BoyerMooreSearch::new(Vec::from(&b"pattern"[..])); + let haystack = b"I keep seeing needles in this text"; + assert_eq!(None, searcher.find(haystack)); + } + + // + // Regression Tests + // + + #[test] + fn bm_skip_reset_bug() { + let haystack = vec![0, 0, 0, 0, 0, 1, 1, 0]; + let needle = vec![0, 1, 1, 0]; + + let searcher = BoyerMooreSearch::new(needle); + let offset = searcher.find(haystack.as_slice()).unwrap(); + assert_eq!(4, offset); + } + + #[test] + fn bm_backstop_underflow_bug() { + let haystack = vec![0, 0]; + let needle = vec![0, 0]; + + let searcher = BoyerMooreSearch::new(needle); + let offset = searcher.find(haystack.as_slice()).unwrap(); + assert_eq!(0, offset); + } + + #[test] + fn bm_naive_off_by_one_bug() { + let haystack = vec![91]; + let needle = vec![91]; + + let naive_offset = naive_find(&needle, &haystack).unwrap(); + assert_eq!(0, naive_offset); + } + + #[test] + fn bm_memchr_fallback_indexing_bug() { + let mut haystack = vec![ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let needle = vec![1, 1, 1, 1, 32, 32, 87]; + let needle_start = haystack.len(); + haystack.extend(needle.clone()); + + let searcher = BoyerMooreSearch::new(needle); + assert_eq!(needle_start, searcher.find(haystack.as_slice()).unwrap()); + } + + #[test] + fn bm_backstop_boundary() { + let haystack = b"\ +// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +e_data.clone_created(entity_id, entity_to_add.entity_id); +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +".to_vec(); + let needle = b"clone_created".to_vec(); + + let searcher = BoyerMooreSearch::new(needle); + let result = searcher.find(&haystack); + assert_eq!(Some(43), result); + } + + #[test] + fn bm_win_gnu_indexing_bug() { + let haystack_raw = vec![ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let needle = vec![1, 1, 1, 1, 1, 1, 1]; + let haystack = haystack_raw.as_slice(); + + BoyerMooreSearch::new(needle.clone()).find(haystack); + } + + // + // QuickCheck Properties + // + + use quickcheck::TestResult; + + fn naive_find(needle: &[u8], haystack: &[u8]) -> Option { + assert!(needle.len() <= haystack.len()); + + for i in 0..(haystack.len() - (needle.len() - 1)) { + if haystack[i] == needle[0] + && &haystack[i..(i+needle.len())] == needle { + return Some(i) + } + } + + None + } + + quickcheck! { + fn qc_bm_equals_nieve_find(pile1: Vec, pile2: Vec) -> TestResult { + if pile1.len() == 0 || pile2.len() == 0 { + return TestResult::discard(); + } + + let (needle, haystack) = if pile1.len() < pile2.len() { + (pile1, pile2.as_slice()) + } else { + (pile2, pile1.as_slice()) + }; + + let searcher = BoyerMooreSearch::new(needle.clone()); + TestResult::from_bool( + searcher.find(haystack) == naive_find(&needle, haystack)) + } + + fn qc_bm_equals_single(pile1: Vec, pile2: Vec) -> TestResult { + if pile1.len() == 0 || pile2.len() == 0 { + return TestResult::discard(); + } + + let (needle, haystack) = if pile1.len() < pile2.len() { + (pile1, pile2.as_slice()) + } else { + (pile2, pile1.as_slice()) + }; + + let bm_searcher = BoyerMooreSearch::new(needle.clone()); + let freqy_memchr = FreqyPacked::new(needle); + TestResult::from_bool( + bm_searcher.find(haystack) == freqy_memchr.find(haystack)) + } + + fn qc_bm_finds_trailing_needle( + haystack_pre: Vec, + needle: Vec + ) -> TestResult { + if needle.len() == 0 { + return TestResult::discard(); + } + + let mut haystack = haystack_pre.clone(); + let searcher = BoyerMooreSearch::new(needle.clone()); + + if haystack.len() >= needle.len() && + searcher.find(haystack.as_slice()).is_some() { + return TestResult::discard(); + } + + haystack.extend(needle.clone()); + + // What if the the tail of the haystack can start the + // needle? + let start = haystack_pre.len() + .checked_sub(needle.len()) + .unwrap_or(0); + for i in 0..(needle.len() - 1) { + if searcher.find(&haystack[(i + start)..]).is_some() { + return TestResult::discard(); + } + } + + TestResult::from_bool( + searcher.find(haystack.as_slice()) + .map(|x| x == haystack_pre.len()) + .unwrap_or(false)) + } + + // qc_equals_* is only testing the negative case as @burntsushi + // pointed out in https://github.com/rust-lang/regex/issues/446. + // This quickcheck prop represents an effort to force testing of + // the positive case. qc_bm_finds_first and qc_bm_finds_trailing_needle + // already check some of the positive cases, but they don't cover + // cases where the needle is in the middle of haystack. This prop + // fills that hole. + fn qc_bm_finds_subslice( + haystack: Vec, + needle_start: usize, + needle_length: usize + ) -> TestResult { + if haystack.len() == 0 { + return TestResult::discard(); + } + + let needle_start = needle_start % haystack.len(); + let needle_length = needle_length % (haystack.len() - needle_start); + + if needle_length == 0 { + return TestResult::discard(); + } + + let needle = &haystack[needle_start..(needle_start + needle_length)]; + + let bm_searcher = BoyerMooreSearch::new(needle.to_vec()); + + let start = naive_find(&needle, &haystack); + match start { + None => TestResult::from_bool(false), + Some(nf_start) => + TestResult::from_bool( + nf_start <= needle_start + && bm_searcher.find(&haystack) == start + ) + } + } + + fn qc_bm_finds_first(needle: Vec) -> TestResult { + if needle.len() == 0 { + return TestResult::discard(); + } + + let mut haystack = needle.clone(); + let searcher = BoyerMooreSearch::new(needle.clone()); + haystack.extend(needle); + + TestResult::from_bool( + searcher.find(haystack.as_slice()) + .map(|x| x == 0) + .unwrap_or(false)) + } + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/literal/teddy_avx2/fallback.rs cargo-0.26.0/vendor/regex-0.2.10/src/literal/teddy_avx2/fallback.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/literal/teddy_avx2/fallback.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/literal/teddy_avx2/fallback.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +use syntax::hir::literal::Literals; + +#[derive(Debug, Clone)] +pub struct Teddy(()); + +#[derive(Debug, Clone)] +pub struct Match { + pub pat: usize, + pub start: usize, + pub end: usize, +} + +impl Teddy { + pub fn available() -> bool { false } + pub fn new(_pats: &Literals) -> Option { None } + pub fn patterns(&self) -> &[Vec] { &[] } + pub fn len(&self) -> usize { 0 } + pub fn approximate_size(&self) -> usize { 0 } + pub fn find(&self, _haystack: &[u8]) -> Option { None } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/literal/teddy_avx2/imp.rs cargo-0.26.0/vendor/regex-0.2.10/src/literal/teddy_avx2/imp.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/literal/teddy_avx2/imp.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/literal/teddy_avx2/imp.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,467 @@ +/*! +This is the Teddy searcher, but ported to AVX2. + +See the module comments in the SSSE3 Teddy searcher for a more in depth +explanation of how this algorithm works. For the most part, this port is +basically the same as the SSSE3 version, but using 256-bit vectors instead of +128-bit vectors, which increases throughput. +*/ + +use std::cmp; + +use aho_corasick::{Automaton, AcAutomaton, FullAcAutomaton}; +use syntax::hir::literal::Literals; + +use vector::avx2::{AVX2VectorBuilder, u8x32}; + +/// Corresponds to the number of bytes read at a time in the haystack. +const BLOCK_SIZE: usize = 32; + +/// Match reports match information. +#[derive(Debug, Clone)] +pub struct Match { + /// The index of the pattern that matched. The index is in correspondence + /// with the order of the patterns given at construction. + pub pat: usize, + /// The start byte offset of the match. + pub start: usize, + /// The end byte offset of the match. This is always `start + pat.len()`. + pub end: usize, +} + +/// A SIMD accelerated multi substring searcher. +#[derive(Debug, Clone)] +pub struct Teddy { + /// A builder for AVX2 empowered vectors. + vb: AVX2VectorBuilder, + /// A list of substrings to match. + pats: Vec>, + /// An Aho-Corasick automaton of the patterns. We use this when we need to + /// search pieces smaller than the Teddy block size. + ac: FullAcAutomaton>, + /// A set of 8 buckets. Each bucket corresponds to a single member of a + /// bitset. A bucket contains zero or more substrings. This is useful + /// when the number of substrings exceeds 8, since our bitsets cannot have + /// more than 8 members. + buckets: Vec>, + /// Our set of masks. There's one mask for each byte in the fingerprint. + masks: Masks, +} + +impl Teddy { + /// Returns true if and only if Teddy is supported on this platform. + /// + /// If this returns `false`, then `Teddy::new(...)` is guaranteed to + /// return `None`. + pub fn available() -> bool { + AVX2VectorBuilder::new().is_some() + } + + /// Create a new `Teddy` multi substring matcher. + /// + /// If a `Teddy` matcher could not be created (e.g., `pats` is empty or has + /// an empty substring), then `None` is returned. + pub fn new(pats: &Literals) -> Option { + let vb = match AVX2VectorBuilder::new() { + None => return None, + Some(vb) => vb, + }; + if !Teddy::available() { + return None; + } + + let pats: Vec<_> = pats.literals().iter().map(|p|p.to_vec()).collect(); + let min_len = pats.iter().map(|p| p.len()).min().unwrap_or(0); + // Don't allow any empty patterns and require that we have at + // least one pattern. + if min_len < 1 { + return None; + } + // Pick the largest mask possible, but no larger than 3. + let nmasks = cmp::min(3, min_len); + let mut masks = Masks::new(vb, nmasks); + let mut buckets = vec![vec![]; 8]; + // Assign a substring to each bucket, and add the bucket's bitfield to + // the appropriate position in the mask. + for (pati, pat) in pats.iter().enumerate() { + let bucket = pati % 8; + buckets[bucket].push(pati); + masks.add(bucket as u8, pat); + } + Some(Teddy { + vb: vb, + pats: pats.to_vec(), + ac: AcAutomaton::new(pats.to_vec()).into_full(), + buckets: buckets, + masks: masks, + }) + } + + /// Returns all of the substrings matched by this `Teddy`. + pub fn patterns(&self) -> &[Vec] { + &self.pats + } + + /// Returns the number of substrings in this matcher. + pub fn len(&self) -> usize { + self.pats.len() + } + + /// Returns the approximate size on the heap used by this matcher. + pub fn approximate_size(&self) -> usize { + self.pats.iter().fold(0, |a, b| a + b.len()) + } + + /// Searches `haystack` for the substrings in this `Teddy`. If a match was + /// found, then it is returned. Otherwise, `None` is returned. + pub fn find(&self, haystack: &[u8]) -> Option { + // This is safe because the only way we can construct a Teddy type + // is if AVX2 is available. + unsafe { self.find_impl(haystack) } + } + + #[target_feature(enable = "avx2")] + unsafe fn find_impl(&self, haystack: &[u8]) -> Option { + // If our haystack is smaller than the block size, then fall back to + // a naive brute force search. + if haystack.is_empty() || haystack.len() < (BLOCK_SIZE + 2) { + return self.slow(haystack, 0); + } + match self.masks.len() { + 0 => None, + 1 => self.find1(haystack), + 2 => self.find2(haystack), + 3 => self.find3(haystack), + _ => unreachable!(), + } + } + + /// `find1` is used when there is only 1 mask. This is the easy case and is + /// pretty much as described in the module documentation. + #[inline(always)] + fn find1(&self, haystack: &[u8]) -> Option { + let mut pos = 0; + let zero = self.vb.u8x32_splat(0); + let len = haystack.len(); + debug_assert!(len >= BLOCK_SIZE); + while pos <= len - BLOCK_SIZE { + let h = unsafe { + // I tried and failed to eliminate bounds checks in safe code. + // This is safe because of our loop invariant: pos is always + // <= len-32. + let p = haystack.get_unchecked(pos..); + self.vb.u8x32_load_unchecked_unaligned(p) + }; + // N.B. `res0` is our `C` in the module documentation. + let res0 = self.masks.members1(h); + // Only do expensive verification if there are any non-zero bits. + let bitfield = res0.ne(zero).movemask(); + if bitfield != 0 { + if let Some(m) = self.verify(haystack, pos, res0, bitfield) { + return Some(m); + } + } + pos += BLOCK_SIZE; + } + self.slow(haystack, pos) + } + + /// `find2` is used when there are 2 masks, e.g., the fingerprint is 2 bytes + /// long. + #[inline(always)] + fn find2(&self, haystack: &[u8]) -> Option { + // This is an exotic way to right shift a SIMD vector across lanes. + // See below at use for more details. + let zero = self.vb.u8x32_splat(0); + let len = haystack.len(); + // The previous value of `C` (from the module documentation) for the + // *first* byte in the fingerprint. On subsequent iterations, we take + // the last bitset from the previous `C` and insert it into the first + // position of the current `C`, shifting all other bitsets to the right + // one lane. This causes `C` for the first byte to line up with `C` for + // the second byte, so that they can be `AND`'d together. + let mut prev0 = self.vb.u8x32_splat(0xFF); + let mut pos = 1; + debug_assert!(len >= BLOCK_SIZE); + while pos <= len - BLOCK_SIZE { + let h = unsafe { + // I tried and failed to eliminate bounds checks in safe code. + // This is safe because of our loop invariant: pos is always + // <= len-32. + let p = haystack.get_unchecked(pos..); + self.vb.u8x32_load_unchecked_unaligned(p) + }; + let (res0, res1) = self.masks.members2(h); + + // Do this: + // + // (prev0 << 15) | (res0 >> 1) + // + // This lets us line up our C values for each byte. + let res0prev0 = res0.alignr_15(prev0); + + // `AND`'s our `C` values together. + let res = res0prev0.and(res1); + prev0 = res0; + + let bitfield = res.ne(zero).movemask(); + if bitfield != 0 { + let pos = pos.checked_sub(1).unwrap(); + if let Some(m) = self.verify(haystack, pos, res, bitfield) { + return Some(m); + } + } + pos += BLOCK_SIZE; + } + // The windowing above doesn't check the last byte in the last + // window, so start the slow search at the last byte of the last + // window. + self.slow(haystack, pos.checked_sub(1).unwrap()) + } + + /// `find3` is used when there are 3 masks, e.g., the fingerprint is 3 bytes + /// long. + /// + /// N.B. This is a straight-forward extrapolation of `find2`. The only + /// difference is that we need to keep track of two previous values of `C`, + /// since we now need to align for three bytes. + #[inline(always)] + fn find3(&self, haystack: &[u8]) -> Option { + let zero = self.vb.u8x32_splat(0); + let len = haystack.len(); + let mut prev0 = self.vb.u8x32_splat(0xFF); + let mut prev1 = self.vb.u8x32_splat(0xFF); + let mut pos = 2; + + while pos <= len - BLOCK_SIZE { + let h = unsafe { + // I tried and failed to eliminate bounds checks in safe code. + // This is safe because of our loop invariant: pos is always + // <= len-32. + let p = haystack.get_unchecked(pos..); + self.vb.u8x32_load_unchecked_unaligned(p) + }; + let (res0, res1, res2) = self.masks.members3(h); + + let res0prev0 = res0.alignr_14(prev0); + let res1prev1 = res1.alignr_15(prev1); + let res = res0prev0.and(res1prev1).and(res2); + + prev0 = res0; + prev1 = res1; + + let bitfield = res.ne(zero).movemask(); + if bitfield != 0 { + let pos = pos.checked_sub(2).unwrap(); + if let Some(m) = self.verify(haystack, pos, res, bitfield) { + return Some(m); + } + } + pos += BLOCK_SIZE; + } + // The windowing above doesn't check the last two bytes in the last + // window, so start the slow search at the penultimate byte of the + // last window. + // self.slow(haystack, pos.saturating_sub(2)) + self.slow(haystack, pos.checked_sub(2).unwrap()) + } + + /// Runs the verification procedure on `res` (i.e., `C` from the module + /// documentation), where the haystack block starts at `pos` in + /// `haystack`. `bitfield` has ones in the bit positions that `res` has + /// non-zero bytes. + /// + /// If a match exists, it returns the first one. + #[inline(always)] + fn verify( + &self, + haystack: &[u8], + pos: usize, + res: u8x32, + mut bitfield: u32, + ) -> Option { + while bitfield != 0 { + // The next offset, relative to pos, where some fingerprint + // matched. + let byte_pos = bitfield.trailing_zeros() as usize; + bitfield &= !(1 << byte_pos); + + // Offset relative to the beginning of the haystack. + let start = pos + byte_pos; + + // The bitfield telling us which patterns had fingerprints that + // match at this starting position. + let mut patterns = res.extract(byte_pos); + while patterns != 0 { + let bucket = patterns.trailing_zeros() as usize; + patterns &= !(1 << bucket); + + // Actual substring search verification. + if let Some(m) = self.verify_bucket(haystack, bucket, start) { + return Some(m); + } + } + } + + None + } + + /// Verifies whether any substring in the given bucket matches in haystack + /// at the given starting position. + #[inline(always)] + fn verify_bucket( + &self, + haystack: &[u8], + bucket: usize, + start: usize, + ) -> Option { + // This cycles through the patterns in the bucket in the order that + // the patterns were given. Therefore, we guarantee leftmost-first + // semantics. + for &pati in &self.buckets[bucket] { + let pat = &*self.pats[pati]; + if start + pat.len() > haystack.len() { + continue; + } + if pat == &haystack[start..start + pat.len()] { + return Some(Match { + pat: pati, + start: start, + end: start + pat.len(), + }); + } + } + None + } + + /// Slow substring search through all patterns in this matcher. + /// + /// This is used when we don't have enough bytes in the haystack for our + /// block based approach. + #[inline(never)] + fn slow(&self, haystack: &[u8], pos: usize) -> Option { + self.ac.find(&haystack[pos..]).next().map(|m| { + Match { + pat: m.pati, + start: pos + m.start, + end: pos + m.end, + } + }) + } +} + +/// A list of masks. This has length equal to the length of the fingerprint. +/// The length of the fingerprint is always `min(3, len(smallest_substring))`. +#[derive(Debug, Clone)] +struct Masks { + vb: AVX2VectorBuilder, + masks: [Mask; 3], + size: usize, +} + +impl Masks { + /// Create a new set of masks of size `n`, where `n` corresponds to the + /// number of bytes in a fingerprint. + fn new(vb: AVX2VectorBuilder, n: usize) -> Masks { + Masks { + vb: vb, + masks: [Mask::new(vb), Mask::new(vb), Mask::new(vb)], + size: n, + } + } + + /// Returns the number of masks. + fn len(&self) -> usize { + self.size + } + + /// Adds the given pattern to the given bucket. The bucket should be a + /// power of `2 <= 2^7`. + fn add(&mut self, bucket: u8, pat: &[u8]) { + for i in 0..self.len() { + self.masks[i].add(bucket, pat[i]); + } + } + + /// Finds the fingerprints that are in the given haystack block. i.e., this + /// returns `C` as described in the module documentation. + /// + /// More specifically, `for i in 0..16` and `j in 0..8, C[i][j] == 1` if and + /// only if `haystack_block[i]` corresponds to a fingerprint that is part + /// of a pattern in bucket `j`. + #[inline(always)] + fn members1(&self, haystack_block: u8x32) -> u8x32 { + let masklo = self.vb.u8x32_splat(0xF); + let hlo = haystack_block.and(masklo); + let hhi = haystack_block.bit_shift_right_4().and(masklo); + + self.masks[0].lo.shuffle(hlo).and(self.masks[0].hi.shuffle(hhi)) + } + + /// Like members1, but computes C for the first and second bytes in the + /// fingerprint. + #[inline(always)] + fn members2(&self, haystack_block: u8x32) -> (u8x32, u8x32) { + let masklo = self.vb.u8x32_splat(0xF); + let hlo = haystack_block.and(masklo); + let hhi = haystack_block.bit_shift_right_4().and(masklo); + + let res0 = + self.masks[0].lo.shuffle(hlo).and(self.masks[0].hi.shuffle(hhi)); + let res1 = + self.masks[1].lo.shuffle(hlo).and(self.masks[1].hi.shuffle(hhi)); + (res0, res1) + } + + /// Like `members1`, but computes `C` for the first, second and third bytes + /// in the fingerprint. + #[inline(always)] + fn members3(&self, haystack_block: u8x32) -> (u8x32, u8x32, u8x32) { + let masklo = self.vb.u8x32_splat(0xF); + let hlo = haystack_block.and(masklo); + let hhi = haystack_block.bit_shift_right_4().and(masklo); + + let res0 = + self.masks[0].lo.shuffle(hlo).and(self.masks[0].hi.shuffle(hhi)); + let res1 = + self.masks[1].lo.shuffle(hlo).and(self.masks[1].hi.shuffle(hhi)); + let res2 = + self.masks[2].lo.shuffle(hlo).and(self.masks[2].hi.shuffle(hhi)); + (res0, res1, res2) + } +} + +/// A single mask. +#[derive(Debug, Clone, Copy)] +struct Mask { + /// Bitsets for the low nybbles in a fingerprint. + lo: u8x32, + /// Bitsets for the high nybbles in a fingerprint. + hi: u8x32, +} + +impl Mask { + /// Create a new mask with no members. + fn new(vb: AVX2VectorBuilder) -> Mask { + Mask { + lo: vb.u8x32_splat(0), + hi: vb.u8x32_splat(0), + } + } + + /// Adds the given byte to the given bucket. + fn add(&mut self, bucket: u8, byte: u8) { + // Split our byte into two nybbles, and add each nybble to our + // mask. + let byte_lo = (byte & 0xF) as usize; + let byte_hi = (byte >> 4) as usize; + + let lo = self.lo.extract(byte_lo) | ((1 << bucket) as u8); + self.lo.replace(byte_lo, lo); + self.lo.replace(byte_lo + 16, lo); + + let hi = self.hi.extract(byte_hi) | ((1 << bucket) as u8); + self.hi.replace(byte_hi, hi); + self.hi.replace(byte_hi + 16, hi); + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/literal/teddy_avx2/mod.rs cargo-0.26.0/vendor/regex-0.2.10/src/literal/teddy_avx2/mod.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/literal/teddy_avx2/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/literal/teddy_avx2/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,16 @@ +pub use self::imp::*; + +#[cfg(all( + feature = "unstable", + regex_runtime_teddy_avx2, + any(target_arch = "x86_64"), +))] +mod imp; + +#[cfg(not(all( + feature = "unstable", + regex_runtime_teddy_avx2, + any(target_arch = "x86_64"), +)))] +#[path = "fallback.rs"] +mod imp; diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/literal/teddy_ssse3/fallback.rs cargo-0.26.0/vendor/regex-0.2.10/src/literal/teddy_ssse3/fallback.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/literal/teddy_ssse3/fallback.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/literal/teddy_ssse3/fallback.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +use syntax::hir::literal::Literals; + +#[derive(Debug, Clone)] +pub struct Teddy(()); + +#[derive(Debug, Clone)] +pub struct Match { + pub pat: usize, + pub start: usize, + pub end: usize, +} + +impl Teddy { + pub fn available() -> bool { false } + pub fn new(_pats: &Literals) -> Option { None } + pub fn patterns(&self) -> &[Vec] { &[] } + pub fn len(&self) -> usize { 0 } + pub fn approximate_size(&self) -> usize { 0 } + pub fn find(&self, _haystack: &[u8]) -> Option { None } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/literal/teddy_ssse3/imp.rs cargo-0.26.0/vendor/regex-0.2.10/src/literal/teddy_ssse3/imp.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/literal/teddy_ssse3/imp.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/literal/teddy_ssse3/imp.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,775 @@ +/*! +Teddy is a simd accelerated multiple substring matching algorithm. The name +and the core ideas in the algorithm were learned from the [Hyperscan][1_u] +project. + + +Background +---------- + +The key idea of Teddy is to do *packed* substring matching. In the literature, +packed substring matching is the idea of examing multiple bytes in a haystack +at a time to detect matches. Implementations of, for example, memchr (which +detects matches of a single byte) have been doing this for years. Only +recently, with the introduction of various SIMD instructions, has this been +extended to substring matching. The PCMPESTRI instruction (and its relatives), +for example, implements substring matching in hardware. It is, however, limited +to substrings of length 16 bytes or fewer, but this restriction is fine in a +regex engine, since we rarely care about the performance difference between +searching for a 16 byte literal and a 16 + N literal; 16 is already long +enough. The key downside of the PCMPESTRI instruction, on current (2016) CPUs +at least, is its latency and throughput. As a result, it is often faster to do +substring search with a Boyer-Moore variant and a well placed memchr to quickly +skip through the haystack. + +There are fewer results from the literature on packed substring matching, +and even fewer for packed multiple substring matching. Ben-Kiki et al. [2] +describes use of PCMPESTRI for substring matching, but is mostly theoretical +and hand-waves performance. There is other theoretical work done by Bille [3] +as well. + +The rest of the work in the field, as far as I'm aware, is by Faro and Kulekci +and is generally focused on multiple pattern search. Their first paper [4a] +introduces the concept of a fingerprint, which is computed for every block of +N bytes in every pattern. The haystack is then scanned N bytes at a time and +a fingerprint is computed in the same way it was computed for blocks in the +patterns. If the fingerprint corresponds to one that was found in a pattern, +then a verification step follows to confirm that one of the substrings with the +corresponding fingerprint actually matches at the current location. Various +implementation tricks are employed to make sure the fingerprint lookup is fast; +typically by truncating the fingerprint. (This may, of course, provoke more +steps in the verification process, so a balance must be struck.) + +The main downside of [4a] is that the minimum substring length is 32 bytes, +presumably because of how the algorithm uses certain SIMD instructions. This +essentially makes it useless for general purpose regex matching, where a small +number of short patterns is far more likely. + +Faro and Kulekci published another paper [4b] that is conceptually very similar +to [4a]. The key difference is that it uses the CRC32 instruction (introduced +as part of SSE 4.2) to compute fingerprint values. This also enables the +algorithm to work effectively on substrings as short as 7 bytes with 4 byte +windows. 7 bytes is unfortunately still too long. The window could be +technically shrunk to 2 bytes, thereby reducing minimum length to 3, but the +small window size ends up negating most performance benefits—and it's likely +the common case in a general purpose regex engine. + +Faro and Kulekci also published [4c] that appears to be intended as a +replacement to using PCMPESTRI. In particular, it is specifically motivated by +the high throughput/latency time of PCMPESTRI and therefore chooses other SIMD +instructions that are faster. While this approach works for short substrings, +I personally couldn't see a way to generalize it to multiple substring search. + +Faro and Kulekci have another paper [4d] that I haven't been able to read +because it is behind a paywall. + + +Teddy +----- + +Finally, we get to Teddy. If the above literature review is complete, then it +appears that Teddy is a novel algorithm. More than that, in my experience, it +completely blows away the competition for short substrings, which is exactly +what we want in a general purpose regex engine. Again, the algorithm appears +to be developed by the authors of [Hyperscan][1_u]. Hyperscan was open sourced +late 2015, and no earlier history could be found. Therefore, tracking the exact +provenance of the algorithm with respect to the published literature seems +difficult. + +DISCLAIMER: My understanding of Teddy is limited to reading auto-generated C +code, its disassembly and observing its runtime behavior. + +At a high level, Teddy works somewhat similarly to the fingerprint algorithms +published by Faro and Kulekci, but Teddy does it in a way that scales a bit +better. Namely: + +1. Teddy's core algorithm scans the haystack in 16 byte chunks. 16 is + significant because it corresponds to the number of bytes in a SIMD vector. + If one used AVX2 instructions, then we could scan the haystack in 32 byte + chunks. Similarly, if one used AVX512 instructions, we could scan the + haystack in 64 byte chunks. Hyperscan implements SSE + AVX2, we only + implement SSE for the moment. +2. Bitwise operations are performed on each chunk to discover if any region of + it matches a set of precomputed fingerprints from the patterns. If there are + matches, then a verification step is performed. In this implementation, our + verification step is naive. This can be improved upon. + +The details to make this work are quite clever. First, we must choose how to +pick our fingerprints. In Hyperscan's implementation, I *believe* they use the +last N bytes of each substring, where N must be at least the minimum length of +any substring in the set being searched. In this implementation, we use the +first N bytes of each substring. (The tradeoffs between these choices aren't +yet clear to me.) We then must figure out how to quickly test whether an +occurrence of any fingerprint from the set of patterns appears in a 16 byte +block from the haystack. To keep things simple, let's assume N = 1 and examine +some examples to motivate the approach. Here are our patterns: + +```ignore +foo +bar +baz +``` + +The corresponding fingerprints, for N = 1, are `f`, `b` and `b`. Now let's set +our 16 byte block to: + +```ignore +bat cat foo bump +xxxxxxxxxxxxxxxx +``` + +To cut to the chase, Teddy works by using bitsets. In particular, Teddy creates +a mask that allows us to quickly compute membership of a fingerprint in a 16 +byte block that also tells which pattern the fingerprint corresponds to. In +this case, our fingerprint is a single byte, so an appropriate abstraction is +a map from a single byte to a list of patterns that contain that fingerprint: + +```ignore +f |--> foo +b |--> bar, baz +``` + +Now, all we need to do is figure out how to represent this map in vector space +and use normal SIMD operations to perform a lookup. The first simplification +we can make is to represent our patterns as bit fields occupying a single +byte. This is important, because a single SIMD vector can store 16 bytes. + +```ignore +f |--> 00000001 +b |--> 00000010, 00000100 +``` + +How do we perform lookup though? It turns out that SSSE3 introduced a very cool +instruction called PSHUFB. The instruction takes two SIMD vectors, `A` and `B`, +and returns a third vector `C`. All vectors are treated as 16 8-bit integers. +`C` is formed by `C[i] = A[B[i]]`. (This is a bit of a simplification, but true +for the purposes of this algorithm. For full details, see [Intel's Intrinsics +Guide][5_u].) This essentially lets us use the values in `B` to lookup values +in `A`. + +If we could somehow cause `B` to contain our 16 byte block from the haystack, +and if `A` could contain our bitmasks, then we'd end up with something like +this for `A`: + +```ignore + 0x00 0x01 ... 0x62 ... 0x66 ... 0xFF +A = 0 0 00000110 00000001 0 +``` + +And if `B` contains our window from our haystack, we could use shuffle to take +the values from `B` and use them to look up our bitsets in `A`. But of course, +we can't do this because `A` in the above example contains 256 bytes, which +is much larger than the size of a SIMD vector. + +Nybbles to the rescue! A nybble is 4 bits. Instead of one mask to hold all of +our bitsets, we can use two masks, where one mask corresponds to the lower four +bits of our fingerprint and the other mask corresponds to the upper four bits. +So our map now looks like: + +```ignore +'f' & 0xF = 0x6 |--> 00000001 +'f' >> 4 = 0x6 |--> 00000111 +'b' & 0xF = 0x2 |--> 00000110 +'b' >> 4 = 0x6 |--> 00000111 +``` + +Notice that the bitsets for each nybble correspond to the union of all +fingerprints that contain that nybble. For example, both `f` and `b` have the +same upper 4 bits but differ on the lower 4 bits. Putting this together, we +have `A0`, `A1` and `B`, where `A0` is our mask for the lower nybble, `A1` is +our mask for the upper nybble and `B` is our 16 byte block from the haystack: + +```ignore + 0x00 0x01 0x02 0x03 ... 0x06 ... 0xF +A0 = 0 0 00000110 0 00000001 0 +A1 = 0 0 0 0 00000111 0 +B = b a t _ t p +B = 0x62 0x61 0x74 0x20 0x74 0x70 +``` + +But of course, we can't use `B` with `PSHUFB` yet, since its values are 8 bits, +and we need indexes that are at most 4 bits (corresponding to one of 16 +values). We can apply the same transformation to split `B` into lower and upper +nybbles as we did `A`. As before, `B0` corresponds to the lower nybbles and +`B1` corresponds to the upper nybbles: + +```ignore + b a t _ c a t _ f o o _ b u m p +B0 = 0x2 0x1 0x4 0x0 0x3 0x1 0x4 0x0 0x6 0xF 0xF 0x0 0x2 0x5 0xD 0x0 +B1 = 0x6 0x6 0x7 0x2 0x6 0x6 0x7 0x2 0x6 0x6 0x6 0x2 0x6 0x7 0x6 0x7 +``` + +And now we have a nice correspondence. `B0` can index `A0` and `B1` can index +`A1`. Here's what we get when we apply `C0 = PSHUFB(A0, B0)`: + +```ignore + b a ... f o ... p + A0[0x2] A0[0x1] A0[0x6] A0[0xF] A0[0x0] +C0 = 00000110 0 00000001 0 0 +``` + +And `C1 = PSHUFB(A1, B1)`: + +```ignore + b a ... f o ... p + A1[0x6] A1[0x6] A1[0x6] A1[0x6] A1[0x7] +C1 = 00000111 00000111 00000111 00000111 0 +``` + +Notice how neither one of `C0` or `C1` is guaranteed to report fully correct +results all on its own. For example, `C1` claims that `b` is a fingerprint for +the pattern `foo` (since `A1[0x6] = 00000111`), and that `o` is a fingerprint +for all of our patterns. But if we combined `C0` and `C1` with an `AND` +operation: + +```ignore + b a ... f o ... p +C = 00000110 0 00000001 0 0 +``` + +Then we now have that `C[i]` contains a bitset corresponding to the matching +fingerprints in a haystack's 16 byte block, where `i` is the `ith` byte in that +block. + +Once we have that, we can look for the position of the least significant bit +in `C`. That position, modulo `8`, gives us the pattern that the fingerprint +matches. That position, integer divided by `8`, also gives us the byte offset +that the fingerprint occurs in inside the 16 byte haystack block. Using those +two pieces of information, we can run a verification procedure that tries +to match all substrings containing that fingerprint at that position in the +haystack. + + +Implementation notes +-------------------- + +The problem with the algorithm as described above is that it uses a single byte +for a fingerprint. This will work well if the fingerprints are rare in the +haystack (e.g., capital letters or special characters in normal English text), +but if the fingerprints are common, you'll wind up spending too much time in +the verification step, which effectively negate the performance benefits of +scanning 16 bytes at a time. Remember, the key to the performance of this +algorithm is to do as little work as possible per 16 bytes. + +This algorithm can be extrapolated in a relatively straight-forward way to use +larger fingerprints. That is, instead of a single byte prefix, we might use a +three byte prefix. The implementation below implements N = {1, 2, 3} and always +picks the largest N possible. The rationale is that the bigger the fingerprint, +the fewer verification steps we'll do. Of course, if N is too large, then we'll +end up doing too much on each step. + +The way to extend it is: + +1. Add a mask for each byte in the fingerprint. (Remember that each mask is + composed of two SIMD vectors.) This results in a value of `C` for each byte + in the fingerprint while searching. +2. When testing each 16 byte block, each value of `C` must be shifted so that + they are aligned. Once aligned, they should all be `AND`'d together. This + will give you only the bitsets corresponding to the full match of the + fingerprint. + +The implementation below is commented to fill in the nitty gritty details. + +References +---------- + +- **[1]** [Hyperscan on GitHub](https://github.com/01org/hyperscan), + [webpage](https://01.org/hyperscan) +- **[2a]** Ben-Kiki, O., Bille, P., Breslauer, D., Gasieniec, L., Grossi, R., + & Weimann, O. (2011). + _Optimal packed string matching_. + In LIPIcs-Leibniz International Proceedings in Informatics (Vol. 13). + Schloss Dagstuhl-Leibniz-Zentrum fuer Informatik. + DOI: 10.4230/LIPIcs.FSTTCS.2011.423. + [PDF](http://drops.dagstuhl.de/opus/volltexte/2011/3355/pdf/37.pdf). +- **[2b]** Ben-Kiki, O., Bille, P., Breslauer, D., Ga̧sieniec, L., Grossi, R., + & Weimann, O. (2014). + _Towards optimal packed string matching_. + Theoretical Computer Science, 525, 111-129. + DOI: 10.1016/j.tcs.2013.06.013. + [PDF](http://www.cs.haifa.ac.il/~oren/Publications/bpsm.pdf). +- **[3]** Bille, P. (2011). + _Fast searching in packed strings_. + Journal of Discrete Algorithms, 9(1), 49-56. + DOI: 10.1016/j.jda.2010.09.003. + [PDF](http://www.sciencedirect.com/science/article/pii/S1570866710000353). +- **[4a]** Faro, S., & Külekci, M. O. (2012, October). + _Fast multiple string matching using streaming SIMD extensions technology_. + In String Processing and Information Retrieval (pp. 217-228). + Springer Berlin Heidelberg. + DOI: 10.1007/978-3-642-34109-0_23. + [PDF](http://www.dmi.unict.it/~faro/papers/conference/faro32.pdf). +- **[4b]** Faro, S., & Külekci, M. O. (2013, September). + _Towards a Very Fast Multiple String Matching Algorithm for Short Patterns_. + In Stringology (pp. 78-91). + [PDF](http://www.dmi.unict.it/~faro/papers/conference/faro36.pdf). +- **[4c]** Faro, S., & Külekci, M. O. (2013, January). + _Fast packed string matching for short patterns_. + In Proceedings of the Meeting on Algorithm Engineering & Expermiments + (pp. 113-121). + Society for Industrial and Applied Mathematics. + [PDF](http://arxiv.org/pdf/1209.6449.pdf). +- **[4d]** Faro, S., & Külekci, M. O. (2014). + _Fast and flexible packed string matching_. + Journal of Discrete Algorithms, 28, 61-72. + DOI: 10.1016/j.jda.2014.07.003. + +[1_u]: https://github.com/01org/hyperscan +[5_u]: https://software.intel.com/sites/landingpage/IntrinsicsGuide +*/ + +use std::cmp; + +use aho_corasick::{Automaton, AcAutomaton, FullAcAutomaton}; +use syntax::hir::literal::Literals; + +use vector::ssse3::{SSSE3VectorBuilder, u8x16}; + +/// Corresponds to the number of bytes read at a time in the haystack. +const BLOCK_SIZE: usize = 16; + +/// Match reports match information. +#[derive(Debug, Clone)] +pub struct Match { + /// The index of the pattern that matched. The index is in correspondence + /// with the order of the patterns given at construction. + pub pat: usize, + /// The start byte offset of the match. + pub start: usize, + /// The end byte offset of the match. This is always `start + pat.len()`. + pub end: usize, +} + +/// A SIMD accelerated multi substring searcher. +#[derive(Debug, Clone)] +pub struct Teddy { + /// A builder for SSSE3 empowered vectors. + vb: SSSE3VectorBuilder, + /// A list of substrings to match. + pats: Vec>, + /// An Aho-Corasick automaton of the patterns. We use this when we need to + /// search pieces smaller than the Teddy block size. + ac: FullAcAutomaton>, + /// A set of 8 buckets. Each bucket corresponds to a single member of a + /// bitset. A bucket contains zero or more substrings. This is useful + /// when the number of substrings exceeds 8, since our bitsets cannot have + /// more than 8 members. + buckets: Vec>, + /// Our set of masks. There's one mask for each byte in the fingerprint. + masks: Masks, +} + +impl Teddy { + /// Returns true if and only if Teddy is supported on this platform. + /// + /// If this returns `false`, then `Teddy::new(...)` is guaranteed to + /// return `None`. + pub fn available() -> bool { + SSSE3VectorBuilder::new().is_some() + } + + /// Create a new `Teddy` multi substring matcher. + /// + /// If a `Teddy` matcher could not be created (e.g., `pats` is empty or has + /// an empty substring), then `None` is returned. + pub fn new(pats: &Literals) -> Option { + let vb = match SSSE3VectorBuilder::new() { + None => return None, + Some(vb) => vb, + }; + if !Teddy::available() { + return None; + } + + let pats: Vec<_> = pats.literals().iter().map(|p|p.to_vec()).collect(); + let min_len = pats.iter().map(|p| p.len()).min().unwrap_or(0); + // Don't allow any empty patterns and require that we have at + // least one pattern. + if min_len < 1 { + return None; + } + // Pick the largest mask possible, but no larger than 3. + let nmasks = cmp::min(3, min_len); + let mut masks = Masks::new(vb, nmasks); + let mut buckets = vec![vec![]; 8]; + // Assign a substring to each bucket, and add the bucket's bitfield to + // the appropriate position in the mask. + for (pati, pat) in pats.iter().enumerate() { + let bucket = pati % 8; + buckets[bucket].push(pati); + masks.add(bucket as u8, pat); + } + Some(Teddy { + vb: vb, + pats: pats.to_vec(), + ac: AcAutomaton::new(pats.to_vec()).into_full(), + buckets: buckets, + masks: masks, + }) + } + + /// Returns all of the substrings matched by this `Teddy`. + pub fn patterns(&self) -> &[Vec] { + &self.pats + } + + /// Returns the number of substrings in this matcher. + pub fn len(&self) -> usize { + self.pats.len() + } + + /// Returns the approximate size on the heap used by this matcher. + pub fn approximate_size(&self) -> usize { + self.pats.iter().fold(0, |a, b| a + b.len()) + } + + /// Searches `haystack` for the substrings in this `Teddy`. If a match was + /// found, then it is returned. Otherwise, `None` is returned. + pub fn find(&self, haystack: &[u8]) -> Option { + // This is safe because the only way we can construct a Teddy type + // is if SSSE3 is available. + unsafe { self.find_impl(haystack) } + } + + #[target_feature(enable = "ssse3")] + unsafe fn find_impl(&self, haystack: &[u8]) -> Option { + // If our haystack is smaller than the block size, then fall back to + // a naive brute force search. + if haystack.is_empty() || haystack.len() < (BLOCK_SIZE + 2) { + return self.slow(haystack, 0); + } + match self.masks.len() { + 0 => None, + 1 => self.find1(haystack), + 2 => self.find2(haystack), + 3 => self.find3(haystack), + _ => unreachable!(), + } + } + + /// `find1` is used when there is only 1 mask. This is the easy case and is + /// pretty much as described in the module documentation. + #[inline(always)] + fn find1(&self, haystack: &[u8]) -> Option { + let mut pos = 0; + let zero = self.vb.u8x16_splat(0); + let len = haystack.len(); + debug_assert!(len >= BLOCK_SIZE); + while pos <= len - BLOCK_SIZE { + let h = unsafe { + // I tried and failed to eliminate bounds checks in safe code. + // This is safe because of our loop invariant: pos is always + // <= len-16. + let p = haystack.get_unchecked(pos..); + self.vb.u8x16_load_unchecked_unaligned(p) + }; + // N.B. `res0` is our `C` in the module documentation. + let res0 = self.masks.members1(h); + // Only do expensive verification if there are any non-zero bits. + let bitfield = res0.ne(zero).movemask(); + if bitfield != 0 { + if let Some(m) = self.verify(haystack, pos, res0, bitfield) { + return Some(m); + } + } + pos += BLOCK_SIZE; + } + self.slow(haystack, pos) + } + + /// `find2` is used when there are 2 masks, e.g., the fingerprint is 2 bytes + /// long. + #[inline(always)] + fn find2(&self, haystack: &[u8]) -> Option { + // This is an exotic way to right shift a SIMD vector across lanes. + // See below at use for more details. + let zero = self.vb.u8x16_splat(0); + let len = haystack.len(); + // The previous value of `C` (from the module documentation) for the + // *first* byte in the fingerprint. On subsequent iterations, we take + // the last bitset from the previous `C` and insert it into the first + // position of the current `C`, shifting all other bitsets to the right + // one lane. This causes `C` for the first byte to line up with `C` for + // the second byte, so that they can be `AND`'d together. + let mut prev0 = self.vb.u8x16_splat(0xFF); + let mut pos = 1; + debug_assert!(len >= BLOCK_SIZE); + while pos <= len - BLOCK_SIZE { + let h = unsafe { + // I tried and failed to eliminate bounds checks in safe code. + // This is safe because of our loop invariant: pos is always + // <= len-16. + let p = haystack.get_unchecked(pos..); + self.vb.u8x16_load_unchecked_unaligned(p) + }; + let (res0, res1) = self.masks.members2(h); + + // Do this: + // + // (prev0 << 15) | (res0 >> 1) + // + // This lets us line up our C values for each byte. + let res0prev0 = res0.alignr_15(prev0); + + // `AND`'s our `C` values together. + let res = res0prev0.and(res1); + prev0 = res0; + + let bitfield = res.ne(zero).movemask(); + if bitfield != 0 { + let pos = pos.checked_sub(1).unwrap(); + if let Some(m) = self.verify(haystack, pos, res, bitfield) { + return Some(m); + } + } + pos += BLOCK_SIZE; + } + // The windowing above doesn't check the last byte in the last + // window, so start the slow search at the last byte of the last + // window. + self.slow(haystack, pos.checked_sub(1).unwrap()) + } + + /// `find3` is used when there are 3 masks, e.g., the fingerprint is 3 bytes + /// long. + /// + /// N.B. This is a straight-forward extrapolation of `find2`. The only + /// difference is that we need to keep track of two previous values of `C`, + /// since we now need to align for three bytes. + #[inline(always)] + fn find3(&self, haystack: &[u8]) -> Option { + let zero = self.vb.u8x16_splat(0); + let len = haystack.len(); + let mut prev0 = self.vb.u8x16_splat(0xFF); + let mut prev1 = self.vb.u8x16_splat(0xFF); + let mut pos = 2; + while pos <= len - BLOCK_SIZE { + let h = unsafe { + // I tried and failed to eliminate bounds checks in safe code. + // This is safe because of our loop invariant: pos is always + // <= len-16. + let p = haystack.get_unchecked(pos..); + self.vb.u8x16_load_unchecked_unaligned(p) + }; + let (res0, res1, res2) = self.masks.members3(h); + + let res0prev0 = res0.alignr_14(prev0); + let res1prev1 = res1.alignr_15(prev1); + let res = res0prev0.and(res1prev1).and(res2); + + prev0 = res0; + prev1 = res1; + + let bitfield = res.ne(zero).movemask(); + if bitfield != 0 { + let pos = pos.checked_sub(2).unwrap(); + if let Some(m) = self.verify(haystack, pos, res, bitfield) { + return Some(m); + } + } + pos += BLOCK_SIZE; + } + // The windowing above doesn't check the last two bytes in the last + // window, so start the slow search at the penultimate byte of the + // last window. + // self.slow(haystack, pos.saturating_sub(2)) + self.slow(haystack, pos.checked_sub(2).unwrap()) + } + + /// Runs the verification procedure on `res` (i.e., `C` from the module + /// documentation), where the haystack block starts at `pos` in + /// `haystack`. `bitfield` has ones in the bit positions that `res` has + /// non-zero bytes. + /// + /// If a match exists, it returns the first one. + #[inline(always)] + fn verify( + &self, + haystack: &[u8], + pos: usize, + res: u8x16, + mut bitfield: u32, + ) -> Option { + while bitfield != 0 { + // The next offset, relative to pos, where some fingerprint + // matched. + let byte_pos = bitfield.trailing_zeros() as usize; + bitfield &= !(1 << byte_pos); + + // Offset relative to the beginning of the haystack. + let start = pos + byte_pos; + + // The bitfield telling us which patterns had fingerprints that + // match at this starting position. + let mut patterns = res.extract(byte_pos); + while patterns != 0 { + let bucket = patterns.trailing_zeros() as usize; + patterns &= !(1 << bucket); + + // Actual substring search verification. + if let Some(m) = self.verify_bucket(haystack, bucket, start) { + return Some(m); + } + } + } + + None + } + + /// Verifies whether any substring in the given bucket matches in haystack + /// at the given starting position. + #[inline(always)] + fn verify_bucket( + &self, + haystack: &[u8], + bucket: usize, + start: usize, + ) -> Option { + // This cycles through the patterns in the bucket in the order that + // the patterns were given. Therefore, we guarantee leftmost-first + // semantics. + for &pati in &self.buckets[bucket] { + let pat = &*self.pats[pati]; + if start + pat.len() > haystack.len() { + continue; + } + if pat == &haystack[start..start + pat.len()] { + return Some(Match { + pat: pati, + start: start, + end: start + pat.len(), + }); + } + } + None + } + + /// Slow substring search through all patterns in this matcher. + /// + /// This is used when we don't have enough bytes in the haystack for our + /// block based approach. + #[inline(never)] + fn slow(&self, haystack: &[u8], pos: usize) -> Option { + self.ac.find(&haystack[pos..]).next().map(|m| { + Match { + pat: m.pati, + start: pos + m.start, + end: pos + m.end, + } + }) + } +} + +/// A list of masks. This has length equal to the length of the fingerprint. +/// The length of the fingerprint is always `min(3, len(smallest_substring))`. +#[derive(Debug, Clone)] +struct Masks { + vb: SSSE3VectorBuilder, + masks: [Mask; 3], + size: usize, +} + +impl Masks { + /// Create a new set of masks of size `n`, where `n` corresponds to the + /// number of bytes in a fingerprint. + fn new(vb: SSSE3VectorBuilder, n: usize) -> Masks { + Masks { + vb: vb, + masks: [Mask::new(vb), Mask::new(vb), Mask::new(vb)], + size: n, + } + } + + /// Returns the number of masks. + fn len(&self) -> usize { + self.size + } + + /// Adds the given pattern to the given bucket. The bucket should be a + /// power of `2 <= 2^7`. + fn add(&mut self, bucket: u8, pat: &[u8]) { + for i in 0..self.len() { + self.masks[i].add(bucket, pat[i]); + } + } + + /// Finds the fingerprints that are in the given haystack block. i.e., this + /// returns `C` as described in the module documentation. + /// + /// More specifically, `for i in 0..16` and `j in 0..8, C[i][j] == 1` if and + /// only if `haystack_block[i]` corresponds to a fingerprint that is part + /// of a pattern in bucket `j`. + #[inline(always)] + fn members1(&self, haystack_block: u8x16) -> u8x16 { + let masklo = self.vb.u8x16_splat(0xF); + let hlo = haystack_block.and(masklo); + let hhi = haystack_block.bit_shift_right_4().and(masklo); + + self.masks[0].lo.shuffle(hlo).and(self.masks[0].hi.shuffle(hhi)) + } + + /// Like members1, but computes C for the first and second bytes in the + /// fingerprint. + #[inline(always)] + fn members2(&self, haystack_block: u8x16) -> (u8x16, u8x16) { + let masklo = self.vb.u8x16_splat(0xF); + let hlo = haystack_block.and(masklo); + let hhi = haystack_block.bit_shift_right_4().and(masklo); + + let res0 = + self.masks[0].lo.shuffle(hlo).and(self.masks[0].hi.shuffle(hhi)); + let res1 = + self.masks[1].lo.shuffle(hlo).and(self.masks[1].hi.shuffle(hhi)); + (res0, res1) + } + + /// Like `members1`, but computes `C` for the first, second and third bytes + /// in the fingerprint. + #[inline(always)] + fn members3(&self, haystack_block: u8x16) -> (u8x16, u8x16, u8x16) { + let masklo = self.vb.u8x16_splat(0xF); + let hlo = haystack_block.and(masklo); + let hhi = haystack_block.bit_shift_right_4().and(masklo); + + let res0 = + self.masks[0].lo.shuffle(hlo).and(self.masks[0].hi.shuffle(hhi)); + let res1 = + self.masks[1].lo.shuffle(hlo).and(self.masks[1].hi.shuffle(hhi)); + let res2 = + self.masks[2].lo.shuffle(hlo).and(self.masks[2].hi.shuffle(hhi)); + (res0, res1, res2) + } +} + +/// A single mask. +#[derive(Debug, Clone, Copy)] +struct Mask { + /// Bitsets for the low nybbles in a fingerprint. + lo: u8x16, + /// Bitsets for the high nybbles in a fingerprint. + hi: u8x16, +} + +impl Mask { + /// Create a new mask with no members. + fn new(vb: SSSE3VectorBuilder) -> Mask { + Mask { + lo: vb.u8x16_splat(0), + hi: vb.u8x16_splat(0), + } + } + + /// Adds the given byte to the given bucket. + fn add(&mut self, bucket: u8, byte: u8) { + // Split our byte into two nybbles, and add each nybble to our + // mask. + let byte_lo = (byte & 0xF) as usize; + let byte_hi = (byte >> 4) as usize; + + let lo = self.lo.extract(byte_lo); + self.lo.replace(byte_lo, ((1 << bucket) as u8) | lo); + + let hi = self.hi.extract(byte_hi); + self.hi.replace(byte_hi, ((1 << bucket) as u8) | hi); + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/literal/teddy_ssse3/mod.rs cargo-0.26.0/vendor/regex-0.2.10/src/literal/teddy_ssse3/mod.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/literal/teddy_ssse3/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/literal/teddy_ssse3/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,16 @@ +pub use self::imp::*; + +#[cfg(all( + feature = "unstable", + regex_runtime_teddy_ssse3, + any(target_arch = "x86", target_arch = "x86_64"), +))] +mod imp; + +#[cfg(not(all( + feature = "unstable", + regex_runtime_teddy_ssse3, + any(target_arch = "x86", target_arch = "x86_64"), +)))] +#[path = "fallback.rs"] +mod imp; diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/pattern.rs cargo-0.26.0/vendor/regex-0.2.10/src/pattern.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/pattern.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/pattern.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,62 @@ +use std::str::pattern::{Pattern, Searcher, SearchStep}; + +use re_unicode::{Regex, Matches}; + +pub struct RegexSearcher<'r, 't> { + haystack: &'t str, + it: Matches<'r, 't>, + last_step_end: usize, + next_match: Option<(usize, usize)>, +} + +impl<'r, 't> Pattern<'t> for &'r Regex { + type Searcher = RegexSearcher<'r, 't>; + + fn into_searcher(self, haystack: &'t str) -> RegexSearcher<'r, 't> { + RegexSearcher { + haystack: haystack, + it: self.find_iter(haystack), + last_step_end: 0, + next_match: None, + } + } +} + +unsafe impl<'r, 't> Searcher<'t> for RegexSearcher<'r, 't> { + #[inline] + fn haystack(&self) -> &'t str { + self.haystack + } + + #[inline] + fn next(&mut self) -> SearchStep { + if let Some((s, e)) = self.next_match { + self.next_match = None; + self.last_step_end = e; + return SearchStep::Match(s, e); + } + match self.it.next() { + None => { + if self.last_step_end < self.haystack().len() { + let last = self.last_step_end; + self.last_step_end = self.haystack().len(); + SearchStep::Reject(last, self.haystack().len()) + } else { + SearchStep::Done + } + } + Some(m) => { + let (s, e) = (m.start(), m.end()); + if s == self.last_step_end { + self.last_step_end = e; + SearchStep::Match(s, e) + } else { + self.next_match = Some((s, e)); + let last = self.last_step_end; + self.last_step_end = s; + SearchStep::Reject(last, s) + } + } + } + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/pikevm.rs cargo-0.26.0/vendor/regex-0.2.10/src/pikevm.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/pikevm.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/pikevm.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,377 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// This module implements the Pike VM. That is, it guarantees linear time +// search of a regex on any text with memory use proportional to the size of +// the regex. +// +// It is equal in power to the backtracking engine in this crate, except the +// backtracking engine is typically faster on small regexes/texts at the +// expense of a bigger memory footprint. +// +// It can do more than the DFA can (specifically, record capture locations +// and execute Unicode word boundary assertions), but at a slower speed. +// Specifically, the Pike VM exectues a DFA implicitly by repeatedly expanding +// epsilon transitions. That is, the Pike VM engine can be in multiple states +// at once where as the DFA is only ever in one state at a time. +// +// Therefore, the Pike VM is generally treated as the fallback when the other +// matching engines either aren't feasible to run or are insufficient. + +use std::mem; + +use exec::ProgramCache; +use input::{Input, InputAt}; +use prog::{Program, InstPtr}; +use re_trait::Slot; +use sparse::SparseSet; + +/// An NFA simulation matching engine. +#[derive(Debug)] +pub struct Fsm<'r, I> { + /// The sequence of opcodes (among other things) that is actually executed. + /// + /// The program may be byte oriented or Unicode codepoint oriented. + prog: &'r Program, + /// An explicit stack used for following epsilon transitions. (This is + /// borrowed from the cache.) + stack: &'r mut Vec, + /// The input to search. + input: I, +} + +/// A cached allocation that can be reused on each execution. +#[derive(Clone, Debug)] +pub struct Cache { + /// A pair of ordered sets for tracking NFA states. + clist: Threads, + nlist: Threads, + /// An explicit stack used for following epsilon transitions. + stack: Vec, +} + +/// An ordered set of NFA states and their captures. +#[derive(Clone, Debug)] +struct Threads { + /// An ordered set of opcodes (each opcode is an NFA state). + set: SparseSet, + /// Captures for every NFA state. + /// + /// It is stored in row-major order, where the columns are the capture + /// slots and the rows are the states. + caps: Vec, + /// The number of capture slots stored per thread. (Every capture has + /// two slots.) + slots_per_thread: usize, +} + +/// A representation of an explicit stack frame when following epsilon +/// transitions. This is used to avoid recursion. +#[derive(Clone, Debug)] +enum FollowEpsilon { + /// Follow transitions at the given instruction pointer. + IP(InstPtr), + /// Restore the capture slot with the given position in the input. + Capture { slot: usize, pos: Slot }, +} + +impl Cache { + /// Create a new allocation used by the NFA machine to record execution + /// and captures. + pub fn new(_prog: &Program) -> Self { + Cache { + clist: Threads::new(), + nlist: Threads::new(), + stack: vec![], + } + } +} + +impl<'r, I: Input> Fsm<'r, I> { + /// Execute the NFA matching engine. + /// + /// If there's a match, `exec` returns `true` and populates the given + /// captures accordingly. + pub fn exec( + prog: &'r Program, + cache: &ProgramCache, + matches: &mut [bool], + slots: &mut [Slot], + quit_after_match: bool, + input: I, + start: usize, + ) -> bool { + let mut cache = cache.borrow_mut(); + let cache = &mut cache.pikevm; + cache.clist.resize(prog.len(), prog.captures.len()); + cache.nlist.resize(prog.len(), prog.captures.len()); + let at = input.at(start); + Fsm { + prog: prog, + stack: &mut cache.stack, + input: input, + }.exec_( + &mut cache.clist, + &mut cache.nlist, + matches, + slots, + quit_after_match, + at, + ) + } + + fn exec_( + &mut self, + mut clist: &mut Threads, + mut nlist: &mut Threads, + matches: &mut [bool], + slots: &mut [Slot], + quit_after_match: bool, + mut at: InputAt, + ) -> bool { + let mut matched = false; + let mut all_matched = false; + clist.set.clear(); + nlist.set.clear(); +'LOOP: loop { + if clist.set.is_empty() { + // Three ways to bail out when our current set of threads is + // empty. + // + // 1. We have a match---so we're done exploring any possible + // alternatives. Time to quit. (We can't do this if we're + // looking for matches for multiple regexes, unless we know + // they all matched.) + // + // 2. If the expression starts with a '^' we can terminate as + // soon as the last thread dies. + if (matched && matches.len() <= 1) + || all_matched + || (!at.is_start() && self.prog.is_anchored_start) { + break; + } + + // 3. If there's a literal prefix for the program, try to + // jump ahead quickly. If it can't be found, then we can + // bail out early. + if !self.prog.prefixes.is_empty() { + at = match self.input.prefix_at(&self.prog.prefixes, at) { + None => break, + Some(at) => at, + }; + } + } + + // This simulates a preceding '.*?' for every regex by adding + // a state starting at the current position in the input for the + // beginning of the program only if we don't already have a match. + if clist.set.is_empty() + || (!self.prog.is_anchored_start && !all_matched) { + self.add(&mut clist, slots, 0, at); + } + // The previous call to "add" actually inspects the position just + // before the current character. For stepping through the machine, + // we can to look at the current character, so we advance the + // input. + let at_next = self.input.at(at.next_pos()); + for i in 0..clist.set.len() { + let ip = clist.set[i]; + if self.step( + &mut nlist, + matches, + slots, + clist.caps(ip), + ip, + at, + at_next, + ) { + matched = true; + all_matched = all_matched || matches.iter().all(|&b| b); + if quit_after_match { + // If we only care if a match occurs (not its + // position), then we can quit right now. + break 'LOOP; + } + if self.prog.matches.len() == 1 { + // We don't need to check the rest of the threads + // in this set because we've matched something + // ("leftmost-first"). However, we still need to check + // threads in the next set to support things like + // greedy matching. + // + // This is only true on normal regexes. For regex sets, + // we need to mush on to observe other matches. + break; + } + } + } + if at.is_end() { + break; + } + at = at_next; + mem::swap(clist, nlist); + nlist.set.clear(); + } + matched + } + + /// Step through the input, one token (byte or codepoint) at a time. + /// + /// nlist is the set of states that will be processed on the next token + /// in the input. + /// + /// caps is the set of captures passed by the caller of the NFA. They are + /// written to only when a match state is visited. + /// + /// thread_caps is the set of captures set for the current NFA state, ip. + /// + /// at and at_next are the current and next positions in the input. at or + /// at_next may be EOF. + fn step( + &mut self, + nlist: &mut Threads, + matches: &mut [bool], + slots: &mut [Slot], + thread_caps: &mut [Option], + ip: usize, + at: InputAt, + at_next: InputAt, + ) -> bool { + use prog::Inst::*; + match self.prog[ip] { + Match(match_slot) => { + if match_slot < matches.len() { + matches[match_slot] = true; + } + for (slot, val) in slots.iter_mut().zip(thread_caps.iter()) { + *slot = *val; + } + true + } + Char(ref inst) => { + if inst.c == at.char() { + self.add(nlist, thread_caps, inst.goto, at_next); + } + false + } + Ranges(ref inst) => { + if inst.matches(at.char()) { + self.add(nlist, thread_caps, inst.goto, at_next); + } + false + } + Bytes(ref inst) => { + if let Some(b) = at.byte() { + if inst.matches(b) { + self.add(nlist, thread_caps, inst.goto, at_next); + } + } + false + } + EmptyLook(_) | Save(_) | Split(_) => false, + } + } + + /// Follows epsilon transitions and adds them for processing to nlist, + /// starting at and including ip. + fn add( + &mut self, + nlist: &mut Threads, + thread_caps: &mut [Option], + ip: usize, + at: InputAt, + ) { + self.stack.push(FollowEpsilon::IP(ip)); + while let Some(frame) = self.stack.pop() { + match frame { + FollowEpsilon::IP(ip) => { + self.add_step(nlist, thread_caps, ip, at); + } + FollowEpsilon::Capture { slot, pos } => { + thread_caps[slot] = pos; + } + } + } + } + + /// A helper function for add that avoids excessive pushing to the stack. + fn add_step( + &mut self, + nlist: &mut Threads, + thread_caps: &mut [Option], + mut ip: usize, + at: InputAt, + ) { + // Instead of pushing and popping to the stack, we mutate ip as we + // traverse the set of states. We only push to the stack when we + // absolutely need recursion (restoring captures or following a + // branch). + use prog::Inst::*; + loop { + // Don't visit states we've already added. + if nlist.set.contains(ip) { + return; + } + nlist.set.insert(ip); + match self.prog[ip] { + EmptyLook(ref inst) => { + if self.input.is_empty_match(at, inst) { + ip = inst.goto; + } + } + Save(ref inst) => { + if inst.slot < thread_caps.len() { + self.stack.push(FollowEpsilon::Capture { + slot: inst.slot, + pos: thread_caps[inst.slot], + }); + thread_caps[inst.slot] = Some(at.pos()); + } + ip = inst.goto; + } + Split(ref inst) => { + self.stack.push(FollowEpsilon::IP(inst.goto2)); + ip = inst.goto1; + } + Match(_) | Char(_) | Ranges(_) | Bytes(_) => { + let t = &mut nlist.caps(ip); + for (slot, val) in t.iter_mut().zip(thread_caps.iter()) { + *slot = *val; + } + return; + } + } + } + } +} + +impl Threads { + fn new() -> Self { + Threads { + set: SparseSet::new(0), + caps: vec![], + slots_per_thread: 0, + } + } + + fn resize(&mut self, num_insts: usize, ncaps: usize) { + if num_insts == self.set.capacity() { + return; + } + self.slots_per_thread = ncaps * 2; + self.set = SparseSet::new(num_insts); + self.caps = vec![None; self.slots_per_thread * num_insts]; + } + + fn caps(&mut self, pc: usize) -> &mut [Option] { + let i = pc * self.slots_per_thread; + &mut self.caps[i..i + self.slots_per_thread] + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/prog.rs cargo-0.26.0/vendor/regex-0.2.10/src/prog.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/prog.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/prog.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,425 @@ +use std::collections::HashMap; +use std::cmp::Ordering; +use std::fmt; +use std::ops::Deref; +use std::mem; +use std::slice; +use std::sync::Arc; + +use input::Char; +use literal::LiteralSearcher; + +/// `InstPtr` represents the index of an instruction in a regex program. +pub type InstPtr = usize; + +/// Program is a sequence of instructions and various facts about thos +/// instructions. +#[derive(Clone)] +pub struct Program { + /// A sequence of instructions that represents an NFA. + pub insts: Vec, + /// Pointers to each Match instruction in the sequence. + /// + /// This is always length 1 unless this program represents a regex set. + pub matches: Vec, + /// The ordered sequence of all capture groups extracted from the AST. + /// Unnamed groups are `None`. + pub captures: Vec>, + /// Pointers to all named capture groups into `captures`. + pub capture_name_idx: Arc>, + /// A pointer to the start instruction. This can vary depending on how + /// the program was compiled. For example, programs for use with the DFA + /// engine have a `.*?` inserted at the beginning of unanchored regular + /// expressions. The actual starting point of the program is after the + /// `.*?`. + pub start: InstPtr, + /// A set of equivalence classes for discriminating bytes in the compiled + /// program. + pub byte_classes: Vec, + /// When true, this program can only match valid UTF-8. + pub only_utf8: bool, + /// When true, this program uses byte range instructions instead of Unicode + /// range instructions. + pub is_bytes: bool, + /// When true, the program is compiled for DFA matching. For example, this + /// implies `is_bytes` and also inserts a preceding `.*?` for unanchored + /// regexes. + pub is_dfa: bool, + /// When true, the program matches text in reverse (for use only in the + /// DFA). + pub is_reverse: bool, + /// Whether the regex must match from the start of the input. + pub is_anchored_start: bool, + /// Whether the regex must match at the end of the input. + pub is_anchored_end: bool, + /// Whether this program contains a Unicode word boundary instruction. + pub has_unicode_word_boundary: bool, + /// A possibly empty machine for very quickly matching prefix literals. + pub prefixes: LiteralSearcher, + /// A limit on the size of the cache that the DFA is allowed to use while + /// matching. + /// + /// The cache limit specifies approximately how much space we're willing to + /// give to the state cache. Once the state cache exceeds the size, it is + /// wiped and all states must be re-computed. + /// + /// Note that this value does not impact correctness. It can be set to 0 + /// and the DFA will run just fine. (It will only ever store exactly one + /// state in the cache, and will likely run very slowly, but it will work.) + /// + /// Also note that this limit is *per thread of execution*. That is, + /// if the same regex is used to search text across multiple threads + /// simultaneously, then the DFA cache is not shared. Instead, copies are + /// made. + pub dfa_size_limit: usize, +} + +impl Program { + /// Creates an empty instruction sequence. Fields are given default + /// values. + pub fn new() -> Self { + Program { + insts: vec![], + matches: vec![], + captures: vec![], + capture_name_idx: Arc::new(HashMap::new()), + start: 0, + byte_classes: vec![0; 256], + only_utf8: true, + is_bytes: false, + is_dfa: false, + is_reverse: false, + is_anchored_start: false, + is_anchored_end: false, + has_unicode_word_boundary: false, + prefixes: LiteralSearcher::empty(), + dfa_size_limit: 2 * (1<<20), + } + } + + /// If pc is an index to a no-op instruction (like Save), then return the + /// next pc that is not a no-op instruction. + pub fn skip(&self, mut pc: usize) -> usize { + loop { + match self[pc] { + Inst::Save(ref i) => pc = i.goto, + _ => return pc, + } + } + } + + /// Return true if and only if an execution engine at instruction `pc` will + /// always lead to a match. + pub fn leads_to_match(&self, pc: usize) -> bool { + if self.matches.len() > 1 { + // If we have a regex set, then we have more than one ending + // state, so leading to one of those states is generally + // meaningless. + return false; + } + match self[self.skip(pc)] { + Inst::Match(_) => true, + _ => false, + } + } + + /// Returns true if the current configuration demands that an implicit + /// `.*?` be prepended to the instruction sequence. + pub fn needs_dotstar(&self) -> bool { + self.is_dfa && !self.is_reverse && !self.is_anchored_start + } + + /// Returns true if this program uses Byte instructions instead of + /// Char/Range instructions. + pub fn uses_bytes(&self) -> bool { + self.is_bytes || self.is_dfa + } + + /// Returns true if this program exclusively matches valid UTF-8 bytes. + /// + /// That is, if an invalid UTF-8 byte is seen, then no match is possible. + pub fn only_utf8(&self) -> bool { + self.only_utf8 + } + + /// Return the approximate heap usage of this instruction sequence in + /// bytes. + pub fn approximate_size(&self) -> usize { + // The only instruction that uses heap space is Ranges (for + // Unicode codepoint programs) to store non-overlapping codepoint + // ranges. To keep this operation constant time, we ignore them. + (self.len() * mem::size_of::()) + + (self.matches.len() * mem::size_of::()) + + (self.captures.len() * mem::size_of::>()) + + (self.capture_name_idx.len() * + (mem::size_of::() + mem::size_of::())) + + (self.byte_classes.len() * mem::size_of::()) + + self.prefixes.approximate_size() + } +} + +impl Deref for Program { + type Target = [Inst]; + + fn deref(&self) -> &Self::Target { + &*self.insts + } +} + +impl fmt::Debug for Program { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::Inst::*; + + fn with_goto(cur: usize, goto: usize, fmtd: String) -> String { + if goto == cur + 1 { + fmtd + } else { + format!("{} (goto: {})", fmtd, goto) + } + } + + fn visible_byte(b: u8) -> String { + use std::ascii::escape_default; + let escaped = escape_default(b).collect::>(); + String::from_utf8_lossy(&escaped).into_owned() + } + + for (pc, inst) in self.iter().enumerate() { + match *inst { + Match(slot) => { + try!(write!(f, "{:04} Match({:?})", pc, slot)) + } + Save(ref inst) => { + let s = format!("{:04} Save({})", pc, inst.slot); + try!(write!(f, "{}", with_goto(pc, inst.goto, s))); + } + Split(ref inst) => { + try!(write!(f, "{:04} Split({}, {})", + pc, inst.goto1, inst.goto2)); + } + EmptyLook(ref inst) => { + let s = format!("{:?}", inst.look); + try!(write!(f, "{:04} {}", + pc, with_goto(pc, inst.goto, s))); + } + Char(ref inst) => { + let s = format!("{:?}", inst.c); + try!(write!(f, "{:04} {}", + pc, with_goto(pc, inst.goto, s))); + } + Ranges(ref inst) => { + let ranges = inst.ranges + .iter() + .map(|r| format!("{:?}-{:?}", r.0, r.1)) + .collect::>() + .join(", "); + try!(write!(f, "{:04} {}", + pc, with_goto(pc, inst.goto, ranges))); + } + Bytes(ref inst) => { + let s = format!( + "Bytes({}, {})", + visible_byte(inst.start), + visible_byte(inst.end)); + try!(write!(f, "{:04} {}", + pc, with_goto(pc, inst.goto, s))); + } + } + if pc == self.start { + try!(write!(f, " (start)")); + } + try!(write!(f, "\n")); + } + Ok(()) + } +} + +impl<'a> IntoIterator for &'a Program { + type Item = &'a Inst; + type IntoIter = slice::Iter<'a, Inst>; + fn into_iter(self) -> Self::IntoIter { self.iter() } +} + +/// Inst is an instruction code in a Regex program. +/// +/// Regrettably, a regex program either contains Unicode codepoint +/// instructions (Char and Ranges) or it contains byte instructions (Bytes). +/// A regex program can never contain both. +/// +/// It would be worth investigating splitting this into two distinct types and +/// then figuring out how to make the matching engines polymorphic over those +/// types without sacrificing performance. +/// +/// Other than the benefit of moving invariants into the type system, another +/// benefit is the decreased size. If we remove the `Char` and `Ranges` +/// instructions from the `Inst` enum, then its size shrinks from 40 bytes to +/// 24 bytes. (This is because of the removal of a `Vec` in the `Ranges` +/// variant.) Given that byte based machines are typically much bigger than +/// their Unicode analogues (because they can decode UTF-8 directly), this ends +/// up being a pretty significant savings. +#[derive(Clone, Debug)] +pub enum Inst { + /// Match indicates that the program has reached a match state. + /// + /// The number in the match corresponds to the Nth logical regular + /// expression in this program. This index is always 0 for normal regex + /// programs. Values greater than 0 appear when compiling regex sets, and + /// each match instruction gets its own unique value. The value corresponds + /// to the Nth regex in the set. + Match(usize), + /// Save causes the program to save the current location of the input in + /// the slot indicated by InstSave. + Save(InstSave), + /// Split causes the program to diverge to one of two paths in the + /// program, preferring goto1 in InstSplit. + Split(InstSplit), + /// EmptyLook represents a zero-width assertion in a regex program. A + /// zero-width assertion does not consume any of the input text. + EmptyLook(InstEmptyLook), + /// Char requires the regex program to match the character in InstChar at + /// the current position in the input. + Char(InstChar), + /// Ranges requires the regex program to match the character at the current + /// position in the input with one of the ranges specified in InstRanges. + Ranges(InstRanges), + /// Bytes is like Ranges, except it expresses a single byte range. It is + /// used in conjunction with Split instructions to implement multi-byte + /// character classes. + Bytes(InstBytes), +} + +impl Inst { + /// Returns true if and only if this is a match instruction. + pub fn is_match(&self) -> bool { + match *self { + Inst::Match(_) => true, + _ => false, + } + } +} + +/// Representation of the Save instruction. +#[derive(Clone, Debug)] +pub struct InstSave { + /// The next location to execute in the program. + pub goto: InstPtr, + /// The capture slot (there are two slots for every capture in a regex, + /// including the zeroth capture for the entire match). + pub slot: usize, +} + +/// Representation of the Split instruction. +#[derive(Clone, Debug)] +pub struct InstSplit { + /// The first instruction to try. A match resulting from following goto1 + /// has precedence over a match resulting from following goto2. + pub goto1: InstPtr, + /// The second instruction to try. A match resulting from following goto1 + /// has precedence over a match resulting from following goto2. + pub goto2: InstPtr, +} + +/// Representation of the `EmptyLook` instruction. +#[derive(Clone, Debug)] +pub struct InstEmptyLook { + /// The next location to execute in the program if this instruction + /// succeeds. + pub goto: InstPtr, + /// The type of zero-width assertion to check. + pub look: EmptyLook, +} + +/// The set of zero-width match instructions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum EmptyLook { + /// Start of line or input. + StartLine, + /// End of line or input. + EndLine, + /// Start of input. + StartText, + /// End of input. + EndText, + /// Word character on one side and non-word character on other. + WordBoundary, + /// Word character on both sides or non-word character on both sides. + NotWordBoundary, + /// ASCII word boundary. + WordBoundaryAscii, + /// Not ASCII word boundary. + NotWordBoundaryAscii, +} + +/// Representation of the Char instruction. +#[derive(Clone, Debug)] +pub struct InstChar { + /// The next location to execute in the program if this instruction + /// succeeds. + pub goto: InstPtr, + /// The character to test. + pub c: char, +} + +/// Representation of the Ranges instruction. +#[derive(Clone, Debug)] +pub struct InstRanges { + /// The next location to execute in the program if this instruction + /// succeeds. + pub goto: InstPtr, + /// The set of Unicode scalar value ranges to test. + pub ranges: Vec<(char, char)>, +} + +impl InstRanges { + /// Tests whether the given input character matches this instruction. + pub fn matches(&self, c: Char) -> bool { + // This speeds up the `match_class_unicode` benchmark by checking + // some common cases quickly without binary search. e.g., Matching + // a Unicode class on predominantly ASCII text. + for r in self.ranges.iter().take(4) { + if c < r.0 { + return false; + } + if c <= r.1 { + return true; + } + } + self.ranges.binary_search_by(|r| { + if r.1 < c { + Ordering::Less + } else if r.0 > c { + Ordering::Greater + } else { + Ordering::Equal + } + }).is_ok() + } + + /// Return the number of distinct characters represented by all of the + /// ranges. + pub fn num_chars(&self) -> usize { + self.ranges.iter() + .map(|&(s, e)| 1 + (e as u32) - (s as u32)) + .fold(0, |acc, len| acc + len) + as usize + } +} + +/// Representation of the Bytes instruction. +#[derive(Clone, Debug)] +pub struct InstBytes { + /// The next location to execute in the program if this instruction + /// succeeds. + pub goto: InstPtr, + /// The start (inclusive) of this byte range. + pub start: u8, + /// The end (inclusive) of this byte range. + pub end: u8, +} + +impl InstBytes { + /// Returns true if and only if the given byte is in this range. + pub fn matches(&self, byte: u8) -> bool { + self.start <= byte && byte <= self.end + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/re_builder.rs cargo-0.26.0/vendor/regex-0.2.10/src/re_builder.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/re_builder.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/re_builder.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,346 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/// The set of user configurable options for compiling zero or more regexes. +#[derive(Clone, Debug)] +#[allow(missing_docs)] +pub struct RegexOptions { + pub pats: Vec, + pub size_limit: usize, + pub dfa_size_limit: usize, + pub nest_limit: u32, + pub case_insensitive: bool, + pub multi_line: bool, + pub dot_matches_new_line: bool, + pub swap_greed: bool, + pub ignore_whitespace: bool, + pub unicode: bool, +} + +impl Default for RegexOptions { + fn default() -> Self { + RegexOptions { + pats: vec![], + size_limit: 10 * (1<<20), + dfa_size_limit: 2 * (1<<20), + nest_limit: 250, + case_insensitive: false, + multi_line: false, + dot_matches_new_line: false, + swap_greed: false, + ignore_whitespace: false, + unicode: true, + } + } +} + +macro_rules! define_builder { + ($name:ident, $regex_mod:ident, $only_utf8:expr) => { + pub mod $name { + use error::Error; + use exec::ExecBuilder; + use super::RegexOptions; + + use $regex_mod::Regex; + +/// A configurable builder for a regular expression. +/// +/// A builder can be used to configure how the regex is built, for example, by +/// setting the default flags (which can be overridden in the expression +/// itself) or setting various limits. +pub struct RegexBuilder(RegexOptions); + +impl RegexBuilder { + /// Create a new regular expression builder with the given pattern. + /// + /// If the pattern is invalid, then an error will be returned when + /// `build` is called. + pub fn new(pattern: &str) -> RegexBuilder { + let mut builder = RegexBuilder(RegexOptions::default()); + builder.0.pats.push(pattern.to_owned()); + builder + } + + /// Consume the builder and compile the regular expression. + /// + /// Note that calling `as_str` on the resulting `Regex` will produce the + /// pattern given to `new` verbatim. Notably, it will not incorporate any + /// of the flags set on this builder. + pub fn build(&self) -> Result { + ExecBuilder::new_options(self.0.clone()) + .only_utf8($only_utf8) + .build() + .map(Regex::from) + } + + /// Set the value for the case insensitive (`i`) flag. + /// + /// When enabled, letters in the pattern will match both upper case and + /// lower case variants. + pub fn case_insensitive(&mut self, yes: bool) -> &mut RegexBuilder { + self.0.case_insensitive = yes; + self + } + + /// Set the value for the multi-line matching (`m`) flag. + /// + /// When enabled, `^` matches the beginning of lines and `$` matches the + /// end of lines. + /// + /// By default, they match beginning/end of the input. + pub fn multi_line(&mut self, yes: bool) -> &mut RegexBuilder { + self.0.multi_line = yes; + self + } + + /// Set the value for the any character (`s`) flag, where in `.` matches + /// anything when `s` is set and matches anything except for new line when + /// it is not set (the default). + /// + /// N.B. "matches anything" means "any byte" for `regex::bytes::Regex` + /// expressions and means "any Unicode scalar value" for `regex::Regex` + /// expressions. + pub fn dot_matches_new_line(&mut self, yes: bool) -> &mut RegexBuilder { + self.0.dot_matches_new_line = yes; + self + } + + /// Set the value for the greedy swap (`U`) flag. + /// + /// When enabled, a pattern like `a*` is lazy (tries to find shortest + /// match) and `a*?` is greedy (tries to find longest match). + /// + /// By default, `a*` is greedy and `a*?` is lazy. + pub fn swap_greed(&mut self, yes: bool) -> &mut RegexBuilder { + self.0.swap_greed = yes; + self + } + + /// Set the value for the ignore whitespace (`x`) flag. + /// + /// When enabled, whitespace such as new lines and spaces will be ignored + /// between expressions of the pattern, and `#` can be used to start a + /// comment until the next new line. + pub fn ignore_whitespace(&mut self, yes: bool) -> &mut RegexBuilder { + self.0.ignore_whitespace = yes; + self + } + + /// Set the value for the Unicode (`u`) flag. + /// + /// Enabled by default. When disabled, character classes such as `\w` only + /// match ASCII word characters instead of all Unicode word characters. + pub fn unicode(&mut self, yes: bool) -> &mut RegexBuilder { + self.0.unicode = yes; + self + } + + /// Set the approximate size limit of the compiled regular expression. + /// + /// This roughly corresponds to the number of bytes occupied by a single + /// compiled program. If the program exceeds this number, then a + /// compilation error is returned. + pub fn size_limit(&mut self, limit: usize) -> &mut RegexBuilder { + self.0.size_limit = limit; + self + } + + /// Set the approximate size of the cache used by the DFA. + /// + /// This roughly corresponds to the number of bytes that the DFA will + /// use while searching. + /// + /// Note that this is a *per thread* limit. There is no way to set a global + /// limit. In particular, if a regex is used from multiple threads + /// simultaneously, then each thread may use up to the number of bytes + /// specified here. + pub fn dfa_size_limit(&mut self, limit: usize) -> &mut RegexBuilder { + self.0.dfa_size_limit = limit; + self + } + + /// Set the nesting limit for this parser. + /// + /// The nesting limit controls how deep the abstract syntax tree is allowed + /// to be. If the AST exceeds the given limit (e.g., with too many nested + /// groups), then an error is returned by the parser. + /// + /// The purpose of this limit is to act as a heuristic to prevent stack + /// overflow for consumers that do structural induction on an `Ast` using + /// explicit recursion. While this crate never does this (instead using + /// constant stack space and moving the call stack to the heap), other + /// crates may. + /// + /// This limit is not checked until the entire Ast is parsed. Therefore, + /// if callers want to put a limit on the amount of heap space used, then + /// they should impose a limit on the length, in bytes, of the concrete + /// pattern string. In particular, this is viable since this parser + /// implementation will limit itself to heap space proportional to the + /// lenth of the pattern string. + /// + /// Note that a nest limit of `0` will return a nest limit error for most + /// patterns but not all. For example, a nest limit of `0` permits `a` but + /// not `ab`, since `ab` requires a concatenation, which results in a nest + /// depth of `1`. In general, a nest limit is not something that manifests + /// in an obvious way in the concrete syntax, therefore, it should not be + /// used in a granular way. + pub fn nest_limit(&mut self, limit: u32) -> &mut RegexBuilder { + self.0.nest_limit = limit; + self + } +} + } + } +} + +define_builder!(bytes, re_bytes, false); +define_builder!(unicode, re_unicode, true); + +macro_rules! define_set_builder { + ($name:ident, $regex_mod:ident, $only_utf8:expr) => { + pub mod $name { + use error::Error; + use exec::ExecBuilder; + use super::RegexOptions; + + use re_set::$regex_mod::RegexSet; + +/// A configurable builder for a set of regular expressions. +/// +/// A builder can be used to configure how the regexes are built, for example, +/// by setting the default flags (which can be overridden in the expression +/// itself) or setting various limits. +pub struct RegexSetBuilder(RegexOptions); + +impl RegexSetBuilder { + /// Create a new regular expression builder with the given pattern. + /// + /// If the pattern is invalid, then an error will be returned when + /// `build` is called. + pub fn new(patterns: I) -> RegexSetBuilder + where S: AsRef, I: IntoIterator { + let mut builder = RegexSetBuilder(RegexOptions::default()); + for pat in patterns { + builder.0.pats.push(pat.as_ref().to_owned()); + } + builder + } + + /// Consume the builder and compile the regular expressions into a set. + pub fn build(&self) -> Result { + ExecBuilder::new_options(self.0.clone()) + .only_utf8($only_utf8) + .build() + .map(RegexSet::from) + } + + /// Set the value for the case insensitive (`i`) flag. + pub fn case_insensitive(&mut self, yes: bool) -> &mut RegexSetBuilder { + self.0.case_insensitive = yes; + self + } + + /// Set the value for the multi-line matching (`m`) flag. + pub fn multi_line(&mut self, yes: bool) -> &mut RegexSetBuilder { + self.0.multi_line = yes; + self + } + + /// Set the value for the any character (`s`) flag, where in `.` matches + /// anything when `s` is set and matches anything except for new line when + /// it is not set (the default). + /// + /// N.B. "matches anything" means "any byte" for `regex::bytes::RegexSet` + /// expressions and means "any Unicode scalar value" for `regex::RegexSet` + /// expressions. + pub fn dot_matches_new_line(&mut self, yes: bool) -> &mut RegexSetBuilder { + self.0.dot_matches_new_line = yes; + self + } + + /// Set the value for the greedy swap (`U`) flag. + pub fn swap_greed(&mut self, yes: bool) -> &mut RegexSetBuilder { + self.0.swap_greed = yes; + self + } + + /// Set the value for the ignore whitespace (`x`) flag. + pub fn ignore_whitespace(&mut self, yes: bool) -> &mut RegexSetBuilder { + self.0.ignore_whitespace = yes; + self + } + + /// Set the value for the Unicode (`u`) flag. + pub fn unicode(&mut self, yes: bool) -> &mut RegexSetBuilder { + self.0.unicode = yes; + self + } + + /// Set the approximate size limit of the compiled regular expression. + /// + /// This roughly corresponds to the number of bytes occupied by a single + /// compiled program. If the program exceeds this number, then a + /// compilation error is returned. + pub fn size_limit(&mut self, limit: usize) -> &mut RegexSetBuilder { + self.0.size_limit = limit; + self + } + + /// Set the approximate size of the cache used by the DFA. + /// + /// This roughly corresponds to the number of bytes that the DFA will + /// use while searching. + /// + /// Note that this is a *per thread* limit. There is no way to set a global + /// limit. In particular, if a regex is used from multiple threads + /// simulanteously, then each thread may use up to the number of bytes + /// specified here. + pub fn dfa_size_limit(&mut self, limit: usize) -> &mut RegexSetBuilder { + self.0.dfa_size_limit = limit; + self + } + + /// Set the nesting limit for this parser. + /// + /// The nesting limit controls how deep the abstract syntax tree is allowed + /// to be. If the AST exceeds the given limit (e.g., with too many nested + /// groups), then an error is returned by the parser. + /// + /// The purpose of this limit is to act as a heuristic to prevent stack + /// overflow for consumers that do structural induction on an `Ast` using + /// explicit recursion. While this crate never does this (instead using + /// constant stack space and moving the call stack to the heap), other + /// crates may. + /// + /// This limit is not checked until the entire Ast is parsed. Therefore, + /// if callers want to put a limit on the amount of heap space used, then + /// they should impose a limit on the length, in bytes, of the concrete + /// pattern string. In particular, this is viable since this parser + /// implementation will limit itself to heap space proportional to the + /// lenth of the pattern string. + /// + /// Note that a nest limit of `0` will return a nest limit error for most + /// patterns but not all. For example, a nest limit of `0` permits `a` but + /// not `ab`, since `ab` requires a concatenation, which results in a nest + /// depth of `1`. In general, a nest limit is not something that manifests + /// in an obvious way in the concrete syntax, therefore, it should not be + /// used in a granular way. + pub fn nest_limit(&mut self, limit: u32) -> &mut RegexSetBuilder { + self.0.nest_limit = limit; + self + } + +} + } + } +} + +define_set_builder!(set_bytes, bytes, false); +define_set_builder!(set_unicode, unicode, true); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/re_bytes.rs cargo-0.26.0/vendor/regex-0.2.10/src/re_bytes.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/re_bytes.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/re_bytes.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1072 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::fmt; +use std::ops::Index; +use std::str::FromStr; +use std::sync::Arc; + +use memchr::memchr; + +use exec::{Exec, ExecNoSync}; +use expand::expand_bytes; +use error::Error; +use re_builder::bytes::RegexBuilder; +use re_trait::{self, RegularExpression, Locations, SubCapturesPosIter}; + +/// Match represents a single match of a regex in a haystack. +/// +/// The lifetime parameter `'t` refers to the lifetime of the matched text. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct Match<'t> { + text: &'t [u8], + start: usize, + end: usize, +} + +impl<'t> Match<'t> { + /// Returns the starting byte offset of the match in the haystack. + #[inline] + pub fn start(&self) -> usize { + self.start + } + + /// Returns the ending byte offset of the match in the haystack. + #[inline] + pub fn end(&self) -> usize { + self.end + } + + /// Returns the matched text. + #[inline] + pub fn as_bytes(&self) -> &'t [u8] { + &self.text[self.start..self.end] + } + + /// Creates a new match from the given haystack and byte offsets. + #[inline] + fn new(haystack: &'t [u8], start: usize, end: usize) -> Match<'t> { + Match { + text: haystack, + start: start, + end: end, + } + } +} + +/// A compiled regular expression for matching arbitrary bytes. +/// +/// It can be used to search, split or replace text. All searching is done with +/// an implicit `.*?` at the beginning and end of an expression. To force an +/// expression to match the whole string (or a prefix or a suffix), you must +/// use an anchor like `^` or `$` (or `\A` and `\z`). +/// +/// Like the `Regex` type in the parent module, matches with this regex return +/// byte offsets into the search text. **Unlike** the parent `Regex` type, +/// these byte offsets may not correspond to UTF-8 sequence boundaries since +/// the regexes in this module can match arbitrary bytes. +#[derive(Clone)] +pub struct Regex(Exec); + +impl fmt::Display for Regex { + /// Shows the original regular expression. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.as_str()) + } +} + +impl fmt::Debug for Regex { + /// Shows the original regular expression. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +/// A constructor for Regex from an Exec. +/// +/// This is hidden because Exec isn't actually part of the public API. +#[doc(hidden)] +impl From for Regex { + fn from(exec: Exec) -> Regex { + Regex(exec) + } +} + +impl FromStr for Regex { + type Err = Error; + + /// Attempts to parse a string into a regular expression + fn from_str(s: &str) -> Result { + Regex::new(s) + } +} + +/// Core regular expression methods. +impl Regex { + /// Compiles a regular expression. Once compiled, it can be used repeatedly + /// to search, split or replace text in a string. + /// + /// If an invalid expression is given, then an error is returned. + pub fn new(re: &str) -> Result { + RegexBuilder::new(re).build() + } + + /// Returns true if and only if the regex matches the string given. + /// + /// It is recommended to use this method if all you need to do is test + /// a match, since the underlying matching engine may be able to do less + /// work. + /// + /// # Example + /// + /// Test if some text contains at least one word with exactly 13 ASCII word + /// bytes: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let text = b"I categorically deny having triskaidekaphobia."; + /// assert!(Regex::new(r"\b\w{13}\b").unwrap().is_match(text)); + /// # } + /// ``` + pub fn is_match(&self, text: &[u8]) -> bool { + self.is_match_at(text, 0) + } + + /// Returns the start and end byte range of the leftmost-first match in + /// `text`. If no match exists, then `None` is returned. + /// + /// Note that this should only be used if you want to discover the position + /// of the match. Testing the existence of a match is faster if you use + /// `is_match`. + /// + /// # Example + /// + /// Find the start and end location of the first word with exactly 13 + /// ASCII word bytes: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let text = b"I categorically deny having triskaidekaphobia."; + /// let mat = Regex::new(r"\b\w{13}\b").unwrap().find(text).unwrap(); + /// assert_eq!((mat.start(), mat.end()), (2, 15)); + /// # } + /// ``` + pub fn find<'t>(&self, text: &'t [u8]) -> Option> { + self.find_at(text, 0) + } + + /// Returns an iterator for each successive non-overlapping match in + /// `text`, returning the start and end byte indices with respect to + /// `text`. + /// + /// # Example + /// + /// Find the start and end location of every word with exactly 13 ASCII + /// word bytes: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let text = b"Retroactively relinquishing remunerations is reprehensible."; + /// for mat in Regex::new(r"\b\w{13}\b").unwrap().find_iter(text) { + /// println!("{:?}", mat); + /// } + /// # } + /// ``` + pub fn find_iter<'r, 't>(&'r self, text: &'t [u8]) -> Matches<'r, 't> { + Matches(self.0.searcher().find_iter(text)) + } + + /// Returns the capture groups corresponding to the leftmost-first + /// match in `text`. Capture group `0` always corresponds to the entire + /// match. If no match is found, then `None` is returned. + /// + /// You should only use `captures` if you need access to the location of + /// capturing group matches. Otherwise, `find` is faster for discovering + /// the location of the overall match. + /// + /// # Examples + /// + /// Say you have some text with movie names and their release years, + /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text + /// looking like that, while also extracting the movie name and its release + /// year separately. + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"'([^']+)'\s+\((\d{4})\)").unwrap(); + /// let text = b"Not my favorite movie: 'Citizen Kane' (1941)."; + /// let caps = re.captures(text).unwrap(); + /// assert_eq!(&caps[1], &b"Citizen Kane"[..]); + /// assert_eq!(&caps[2], &b"1941"[..]); + /// assert_eq!(&caps[0], &b"'Citizen Kane' (1941)"[..]); + /// // You can also access the groups by index using the Index notation. + /// // Note that this will panic on an invalid index. + /// assert_eq!(&caps[1], b"Citizen Kane"); + /// assert_eq!(&caps[2], b"1941"); + /// assert_eq!(&caps[0], b"'Citizen Kane' (1941)"); + /// # } + /// ``` + /// + /// Note that the full match is at capture group `0`. Each subsequent + /// capture group is indexed by the order of its opening `(`. + /// + /// We can make this example a bit clearer by using *named* capture groups: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"'(?P[^']+)'\s+\((?P<year>\d{4})\)") + /// .unwrap(); + /// let text = b"Not my favorite movie: 'Citizen Kane' (1941)."; + /// let caps = re.captures(text).unwrap(); + /// assert_eq!(&caps["title"], &b"Citizen Kane"[..]); + /// assert_eq!(&caps["year"], &b"1941"[..]); + /// assert_eq!(&caps[0], &b"'Citizen Kane' (1941)"[..]); + /// // You can also access the groups by name using the Index notation. + /// // Note that this will panic on an invalid group name. + /// assert_eq!(&caps["title"], b"Citizen Kane"); + /// assert_eq!(&caps["year"], b"1941"); + /// assert_eq!(&caps[0], b"'Citizen Kane' (1941)"); + /// + /// # } + /// ``` + /// + /// Here we name the capture groups, which we can access with the `name` + /// method or the `Index` notation with a `&str`. Note that the named + /// capture groups are still accessible with `get` or the `Index` notation + /// with a `usize`. + /// + /// The `0`th capture group is always unnamed, so it must always be + /// accessed with `get(0)` or `[0]`. + pub fn captures<'t>(&self, text: &'t [u8]) -> Option<Captures<'t>> { + let mut locs = self.locations(); + self.read_captures_at(&mut locs, text, 0).map(|_| Captures { + text: text, + locs: locs, + named_groups: self.0.capture_name_idx().clone(), + }) + } + + /// Returns an iterator over all the non-overlapping capture groups matched + /// in `text`. This is operationally the same as `find_iter`, except it + /// yields information about capturing group matches. + /// + /// # Example + /// + /// We can use this to find all movie titles and their release years in + /// some text, where the movie is formatted like "'Title' (xxxx)": + /// + /// ```rust + /// # extern crate regex; use std::str; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)") + /// .unwrap(); + /// let text = b"'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931)."; + /// for caps in re.captures_iter(text) { + /// let title = str::from_utf8(&caps["title"]).unwrap(); + /// let year = str::from_utf8(&caps["year"]).unwrap(); + /// println!("Movie: {:?}, Released: {:?}", title, year); + /// } + /// // Output: + /// // Movie: Citizen Kane, Released: 1941 + /// // Movie: The Wizard of Oz, Released: 1939 + /// // Movie: M, Released: 1931 + /// # } + /// ``` + pub fn captures_iter<'r, 't>( + &'r self, + text: &'t [u8], + ) -> CaptureMatches<'r, 't> { + CaptureMatches(self.0.searcher().captures_iter(text)) + } + + /// Returns an iterator of substrings of `text` delimited by a match of the + /// regular expression. Namely, each element of the iterator corresponds to + /// text that *isn't* matched by the regular expression. + /// + /// This method will *not* copy the text given. + /// + /// # Example + /// + /// To split a string delimited by arbitrary amounts of spaces or tabs: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"[ \t]+").unwrap(); + /// let fields: Vec<&[u8]> = re.split(b"a b \t c\td e").collect(); + /// assert_eq!(fields, vec![ + /// &b"a"[..], &b"b"[..], &b"c"[..], &b"d"[..], &b"e"[..], + /// ]); + /// # } + /// ``` + pub fn split<'r, 't>(&'r self, text: &'t [u8]) -> Split<'r, 't> { + Split { + finder: self.find_iter(text), + last: 0, + } + } + + /// Returns an iterator of at most `limit` substrings of `text` delimited + /// by a match of the regular expression. (A `limit` of `0` will return no + /// substrings.) Namely, each element of the iterator corresponds to text + /// that *isn't* matched by the regular expression. The remainder of the + /// string that is not split will be the last element in the iterator. + /// + /// This method will *not* copy the text given. + /// + /// # Example + /// + /// Get the first two words in some text: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"\W+").unwrap(); + /// let fields: Vec<&[u8]> = re.splitn(b"Hey! How are you?", 3).collect(); + /// assert_eq!(fields, vec![&b"Hey"[..], &b"How"[..], &b"are you?"[..]]); + /// # } + /// ``` + pub fn splitn<'r, 't>( + &'r self, + text: &'t [u8], + limit: usize, + ) -> SplitN<'r, 't> { + SplitN { + splits: self.split(text), + n: limit, + } + } + + /// Replaces the leftmost-first match with the replacement provided. The + /// replacement can be a regular byte string (where `$N` and `$name` are + /// expanded to match capture groups) or a function that takes the matches' + /// `Captures` and returns the replaced byte string. + /// + /// If no match is found, then a copy of the byte string is returned + /// unchanged. + /// + /// # Replacement string syntax + /// + /// All instances of `$name` in the replacement text is replaced with the + /// corresponding capture group `name`. + /// + /// `name` may be an integer corresponding to the index of the + /// capture group (counted by order of opening parenthesis where `0` is the + /// entire match) or it can be a name (consisting of letters, digits or + /// underscores) corresponding to a named capture group. + /// + /// If `name` isn't a valid capture group (whether the name doesn't exist + /// or isn't a valid index), then it is replaced with the empty string. + /// + /// The longest possible name is used. e.g., `$1a` looks up the capture + /// group named `1a` and not the capture group at index `1`. To exert more + /// precise control over the name, use braces, e.g., `${1}a`. + /// + /// To write a literal `$` use `$$`. + /// + /// # Examples + /// + /// Note that this function is polymorphic with respect to the replacement. + /// In typical usage, this can just be a normal byte string: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new("[^01]+").unwrap(); + /// assert_eq!(re.replace(b"1078910", &b""[..]), &b"1010"[..]); + /// # } + /// ``` + /// + /// But anything satisfying the `Replacer` trait will work. For example, a + /// closure of type `|&Captures| -> Vec<u8>` provides direct access to the + /// captures corresponding to a match. This allows one to access capturing + /// group matches easily: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # use regex::bytes::Captures; fn main() { + /// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap(); + /// let result = re.replace(b"Springsteen, Bruce", |caps: &Captures| { + /// let mut replacement = caps[2].to_owned(); + /// replacement.push(b' '); + /// replacement.extend(&caps[1]); + /// replacement + /// }); + /// assert_eq!(result, &b"Bruce Springsteen"[..]); + /// # } + /// ``` + /// + /// But this is a bit cumbersome to use all the time. Instead, a simple + /// syntax is supported that expands `$name` into the corresponding capture + /// group. Here's the last example, but using this expansion technique + /// with named capture groups: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)").unwrap(); + /// let result = re.replace(b"Springsteen, Bruce", &b"$first $last"[..]); + /// assert_eq!(result, &b"Bruce Springsteen"[..]); + /// # } + /// ``` + /// + /// Note that using `$2` instead of `$first` or `$1` instead of `$last` + /// would produce the same result. To write a literal `$` use `$$`. + /// + /// Sometimes the replacement string requires use of curly braces to + /// delineate a capture group replacement and surrounding literal text. + /// For example, if we wanted to join two words together with an + /// underscore: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap(); + /// let result = re.replace(b"deep fried", &b"${first}_$second"[..]); + /// assert_eq!(result, &b"deep_fried"[..]); + /// # } + /// ``` + /// + /// Without the curly braces, the capture group name `first_` would be + /// used, and since it doesn't exist, it would be replaced with the empty + /// string. + /// + /// Finally, sometimes you just want to replace a literal string with no + /// regard for capturing group expansion. This can be done by wrapping a + /// byte string with `NoExpand`: + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// use regex::bytes::NoExpand; + /// + /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(\S+)").unwrap(); + /// let result = re.replace(b"Springsteen, Bruce", NoExpand(b"$2 $last")); + /// assert_eq!(result, &b"$2 $last"[..]); + /// # } + /// ``` + pub fn replace<'t, R: Replacer>( + &self, + text: &'t [u8], + rep: R, + ) -> Cow<'t, [u8]> { + self.replacen(text, 1, rep) + } + + /// Replaces all non-overlapping matches in `text` with the replacement + /// provided. This is the same as calling `replacen` with `limit` set to + /// `0`. + /// + /// See the documentation for `replace` for details on how to access + /// capturing group matches in the replacement text. + pub fn replace_all<'t, R: Replacer>( + &self, + text: &'t [u8], + rep: R, + ) -> Cow<'t, [u8]> { + self.replacen(text, 0, rep) + } + + /// Replaces at most `limit` non-overlapping matches in `text` with the + /// replacement provided. If `limit` is 0, then all non-overlapping matches + /// are replaced. + /// + /// See the documentation for `replace` for details on how to access + /// capturing group matches in the replacement text. + pub fn replacen<'t, R: Replacer>( + &self, + text: &'t [u8], + limit: usize, + mut rep: R, + ) -> Cow<'t, [u8]> { + if let Some(rep) = rep.no_expansion() { + let mut it = self.find_iter(text).enumerate().peekable(); + if it.peek().is_none() { + return Cow::Borrowed(text); + } + let mut new = Vec::with_capacity(text.len()); + let mut last_match = 0; + for (i, m) in it { + if limit > 0 && i >= limit { + break + } + new.extend_from_slice(&text[last_match..m.start()]); + new.extend_from_slice(&rep); + last_match = m.end(); + } + new.extend_from_slice(&text[last_match..]); + return Cow::Owned(new); + } + + // The slower path, which we use if the replacement needs access to + // capture groups. + let mut it = self.captures_iter(text).enumerate().peekable(); + if it.peek().is_none() { + return Cow::Borrowed(text); + } + let mut new = Vec::with_capacity(text.len()); + let mut last_match = 0; + for (i, cap) in it { + if limit > 0 && i >= limit { + break + } + // unwrap on 0 is OK because captures only reports matches + let m = cap.get(0).unwrap(); + new.extend_from_slice(&text[last_match..m.start()]); + rep.replace_append(&cap, &mut new); + last_match = m.end(); + } + new.extend_from_slice(&text[last_match..]); + Cow::Owned(new) + } +} + +/// Advanced or "lower level" search methods. +impl Regex { + /// Returns the end location of a match in the text given. + /// + /// This method may have the same performance characteristics as + /// `is_match`, except it provides an end location for a match. In + /// particular, the location returned *may be shorter* than the proper end + /// of the leftmost-first match. + /// + /// # Example + /// + /// Typically, `a+` would match the entire first sequence of `a` in some + /// text, but `shortest_match` can give up as soon as it sees the first + /// `a`. + /// + /// ```rust + /// # extern crate regex; use regex::bytes::Regex; + /// # fn main() { + /// let text = b"aaaaa"; + /// let pos = Regex::new(r"a+").unwrap().shortest_match(text); + /// assert_eq!(pos, Some(1)); + /// # } + /// ``` + pub fn shortest_match(&self, text: &[u8]) -> Option<usize> { + self.shortest_match_at(text, 0) + } + + /// Returns the same as shortest_match, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn shortest_match_at( + &self, + text: &[u8], + start: usize, + ) -> Option<usize> { + self.0.searcher().shortest_match_at(text, start) + } + + /// Returns the same as is_match, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn is_match_at(&self, text: &[u8], start: usize) -> bool { + self.shortest_match_at(text, start).is_some() + } + + /// Returns the same as find, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn find_at<'t>( + &self, + text: &'t [u8], + start: usize, + ) -> Option<Match<'t>> { + self.0.searcher().find_at(text, start) + .map(|(s, e)| Match::new(text, s, e)) + } + + /// Returns the same as captures, but starts the search at the given + /// offset and populates the capture locations given. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn read_captures_at<'t>( + &self, + locs: &mut Locations, + text: &'t [u8], + start: usize, + ) -> Option<Match<'t>> { + self.0.searcher().read_captures_at(locs, text, start) + .map(|(s, e)| Match::new(text, s, e)) + } +} + +/// Auxiliary methods. +impl Regex { + /// Returns the original string of this regex. + pub fn as_str(&self) -> &str { + &self.0.regex_strings()[0] + } + + /// Returns an iterator over the capture names. + pub fn capture_names(&self) -> CaptureNames { + CaptureNames(self.0.capture_names().iter()) + } + + /// Returns the number of captures. + pub fn captures_len(&self) -> usize { + self.0.capture_names().len() + } + + /// Returns an empty set of locations that can be reused in multiple calls + /// to `read_captures`. + #[doc(hidden)] + pub fn locations(&self) -> Locations { + self.0.searcher().locations() + } +} + +/// An iterator over all non-overlapping matches for a particular string. +/// +/// The iterator yields a tuple of integers corresponding to the start and end +/// of the match. The indices are byte offsets. The iterator stops when no more +/// matches can be found. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the matched byte string. +pub struct Matches<'r, 't>(re_trait::Matches<'t, ExecNoSync<'r>>); + +impl<'r, 't> Iterator for Matches<'r, 't> { + type Item = Match<'t>; + + fn next(&mut self) -> Option<Match<'t>> { + let text = self.0.text(); + self.0.next().map(|(s, e)| Match::new(text, s, e)) + } +} + +/// An iterator that yields all non-overlapping capture groups matching a +/// particular regular expression. +/// +/// The iterator stops when no more matches can be found. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the matched byte string. +pub struct CaptureMatches<'r, 't>(re_trait::CaptureMatches<'t, ExecNoSync<'r>>); + +impl<'r, 't> Iterator for CaptureMatches<'r, 't> { + type Item = Captures<'t>; + + fn next(&mut self) -> Option<Captures<'t>> { + self.0.next().map(|locs| Captures { + text: self.0.text(), + locs: locs, + named_groups: self.0.regex().capture_name_idx().clone(), + }) + } +} + +/// Yields all substrings delimited by a regular expression match. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the byte string being split. +pub struct Split<'r, 't> { + finder: Matches<'r, 't>, + last: usize, +} + +impl<'r, 't> Iterator for Split<'r, 't> { + type Item = &'t [u8]; + + fn next(&mut self) -> Option<&'t [u8]> { + let text = self.finder.0.text(); + match self.finder.next() { + None => { + if self.last >= text.len() { + None + } else { + let s = &text[self.last..]; + self.last = text.len(); + Some(s) + } + } + Some(m) => { + let matched = &text[self.last..m.start()]; + self.last = m.end(); + Some(matched) + } + } + } +} + +/// Yields at most `N` substrings delimited by a regular expression match. +/// +/// The last substring will be whatever remains after splitting. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the byte string being split. +pub struct SplitN<'r, 't> { + splits: Split<'r, 't>, + n: usize, +} + +impl<'r, 't> Iterator for SplitN<'r, 't> { + type Item = &'t [u8]; + + fn next(&mut self) -> Option<&'t [u8]> { + if self.n == 0 { + return None + } + self.n -= 1; + if self.n == 0 { + let text = self.splits.finder.0.text(); + Some(&text[self.splits.last..]) + } else { + self.splits.next() + } + } +} + +/// An iterator over the names of all possible captures. +/// +/// `None` indicates an unnamed capture; the first element (capture 0, the +/// whole matched region) is always unnamed. +/// +/// `'r` is the lifetime of the compiled regular expression. +pub struct CaptureNames<'r>(::std::slice::Iter<'r, Option<String>>); + +impl<'r> Iterator for CaptureNames<'r> { + type Item = Option<&'r str>; + + fn next(&mut self) -> Option<Option<&'r str>> { + self.0.next().as_ref() + .map(|slot| slot.as_ref().map(|name| name.as_ref())) + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.0.size_hint() + } +} + +/// Captures represents a group of captured byte strings for a single match. +/// +/// The 0th capture always corresponds to the entire match. Each subsequent +/// index corresponds to the next capture group in the regex. If a capture +/// group is named, then the matched byte string is *also* available via the +/// `name` method. (Note that the 0th capture is always unnamed and so must be +/// accessed with the `get` method.) +/// +/// Positions returned from a capture group are always byte indices. +/// +/// `'t` is the lifetime of the matched text. +pub struct Captures<'t> { + text: &'t [u8], + locs: Locations, + named_groups: Arc<HashMap<String, usize>>, +} + +impl<'t> Captures<'t> { + /// Returns the match associated with the capture group at index `i`. If + /// `i` does not correspond to a capture group, or if the capture group + /// did not participate in the match, then `None` is returned. + /// + /// # Examples + /// + /// Get the text of the match with a default of an empty string if this + /// group didn't participate in the match: + /// + /// ```rust + /// # use regex::bytes::Regex; + /// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap(); + /// let caps = re.captures(b"abc123").unwrap(); + /// + /// let text1 = caps.get(1).map_or(&b""[..], |m| m.as_bytes()); + /// let text2 = caps.get(2).map_or(&b""[..], |m| m.as_bytes()); + /// assert_eq!(text1, &b"123"[..]); + /// assert_eq!(text2, &b""[..]); + /// ``` + pub fn get(&self, i: usize) -> Option<Match<'t>> { + self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e)) + } + + /// Returns the match for the capture group named `name`. If `name` isn't a + /// valid capture group or didn't match anything, then `None` is returned. + pub fn name(&self, name: &str) -> Option<Match<'t>> { + self.named_groups.get(name).and_then(|&i| self.get(i)) + } + + /// An iterator that yields all capturing matches in the order in which + /// they appear in the regex. If a particular capture group didn't + /// participate in the match, then `None` is yielded for that capture. + /// + /// The first match always corresponds to the overall match of the regex. + pub fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 't> { + SubCaptureMatches { + caps: self, + it: self.locs.iter(), + } + } + + /// Expands all instances of `$name` in `replacement` to the corresponding + /// capture group `name`, and writes them to the `dst` buffer given. + /// + /// `name` may be an integer corresponding to the index of the + /// capture group (counted by order of opening parenthesis where `0` is the + /// entire match) or it can be a name (consisting of letters, digits or + /// underscores) corresponding to a named capture group. + /// + /// If `name` isn't a valid capture group (whether the name doesn't exist + /// or isn't a valid index), then it is replaced with the empty string. + /// + /// The longest possible name is used. e.g., `$1a` looks up the capture + /// group named `1a` and not the capture group at index `1`. To exert more + /// precise control over the name, use braces, e.g., `${1}a`. + /// + /// To write a literal `$` use `$$`. + pub fn expand(&self, replacement: &[u8], dst: &mut Vec<u8>) { + expand_bytes(self, replacement, dst) + } + + /// Returns the number of captured groups. + /// + /// This is always at least `1`, since every regex has at least one capture + /// group that corresponds to the full match. + #[inline] + pub fn len(&self) -> usize { + self.locs.len() + } +} + +impl<'t> fmt::Debug for Captures<'t> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_tuple("Captures").field(&CapturesDebug(self)).finish() + } +} + +struct CapturesDebug<'c, 't: 'c>(&'c Captures<'t>); + +impl<'c, 't> fmt::Debug for CapturesDebug<'c, 't> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fn escape_bytes(bytes: &[u8]) -> String { + let mut s = String::new(); + for &b in bytes { + s.push_str(&escape_byte(b)); + } + s + } + + fn escape_byte(byte: u8) -> String { + use std::ascii::escape_default; + + let escaped: Vec<u8> = escape_default(byte).collect(); + String::from_utf8_lossy(&escaped).into_owned() + } + + // We'd like to show something nice here, even if it means an + // allocation to build a reverse index. + let slot_to_name: HashMap<&usize, &String> = + self.0.named_groups.iter().map(|(a, b)| (b, a)).collect(); + let mut map = f.debug_map(); + for (slot, m) in self.0.locs.iter().enumerate() { + let m = m.map(|(s, e)| escape_bytes(&self.0.text[s..e])); + if let Some(name) = slot_to_name.get(&slot) { + map.entry(&name, &m); + } else { + map.entry(&slot, &m); + } + } + map.finish() + } +} + +/// Get a group by index. +/// +/// `'t` is the lifetime of the matched text. +/// +/// The text can't outlive the `Captures` object if this method is +/// used, because of how `Index` is defined (normally `a[i]` is part +/// of `a` and can't outlive it); to do that, use `get()` instead. +/// +/// # Panics +/// +/// If there is no group at the given index. +impl<'t> Index<usize> for Captures<'t> { + type Output = [u8]; + + fn index(&self, i: usize) -> &[u8] { + self.get(i).map(|m| m.as_bytes()) + .unwrap_or_else(|| panic!("no group at index '{}'", i)) + } +} + +/// Get a group by name. +/// +/// `'t` is the lifetime of the matched text and `'i` is the lifetime +/// of the group name (the index). +/// +/// The text can't outlive the `Captures` object if this method is +/// used, because of how `Index` is defined (normally `a[i]` is part +/// of `a` and can't outlive it); to do that, use `name` instead. +/// +/// # Panics +/// +/// If there is no group named by the given value. +impl<'t, 'i> Index<&'i str> for Captures<'t> { + type Output = [u8]; + + fn index<'a>(&'a self, name: &'i str) -> &'a [u8] { + self.name(name).map(|m| m.as_bytes()) + .unwrap_or_else(|| panic!("no group named '{}'", name)) + } +} + +/// An iterator that yields all capturing matches in the order in which they +/// appear in the regex. +/// +/// If a particular capture group didn't participate in the match, then `None` +/// is yielded for that capture. The first match always corresponds to the +/// overall match of the regex. +/// +/// The lifetime `'c` corresponds to the lifetime of the `Captures` value, and +/// the lifetime `'t` corresponds to the originally matched text. +pub struct SubCaptureMatches<'c, 't: 'c> { + caps: &'c Captures<'t>, + it: SubCapturesPosIter<'c>, +} + +impl<'c, 't> Iterator for SubCaptureMatches<'c, 't> { + type Item = Option<Match<'t>>; + + fn next(&mut self) -> Option<Option<Match<'t>>> { + self.it.next() + .map(|cap| cap.map(|(s, e)| Match::new(self.caps.text, s, e))) + } +} + +/// Replacer describes types that can be used to replace matches in a byte +/// string. +/// +/// In general, users of this crate shouldn't need to implement this trait, +/// since implementations are already provided for `&[u8]` and +/// `FnMut(&Captures) -> Vec<u8>`, which covers most use cases. +pub trait Replacer { + /// Appends text to `dst` to replace the current match. + /// + /// The current match is represented by `caps`, which is guaranteed to + /// have a match at capture group `0`. + /// + /// For example, a no-op replacement would be + /// `dst.extend(&caps[0])`. + fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>); + + /// Return a fixed unchanging replacement byte string. + /// + /// When doing replacements, if access to `Captures` is not needed (e.g., + /// the replacement byte string does not need `$` expansion), then it can + /// be beneficial to avoid finding sub-captures. + /// + /// In general, this is called once for every call to `replacen`. + fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> { + None + } + + /// Return a `Replacer` that borrows and wraps this `Replacer`. + /// + /// This is useful when you want to take a generic `Replacer` (which might + /// not be cloneable) and use it without consuming it, so it can be used + /// more than once. + /// + /// # Example + /// + /// ``` + /// use regex::bytes::{Regex, Replacer}; + /// + /// fn replace_all_twice<R: Replacer>( + /// re: Regex, + /// src: &[u8], + /// mut rep: R, + /// ) -> Vec<u8> { + /// let dst = re.replace_all(src, rep.by_ref()); + /// let dst = re.replace_all(&dst, rep.by_ref()); + /// dst.into_owned() + /// } + /// ``` + fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self> { + ReplacerRef(self) + } +} + +/// By-reference adaptor for a `Replacer` +/// +/// Returned by [`Replacer::by_ref`](trait.Replacer.html#method.by_ref). +#[derive(Debug)] +pub struct ReplacerRef<'a, R: ?Sized + 'a>(&'a mut R); + +impl<'a, R: Replacer + ?Sized + 'a> Replacer for ReplacerRef<'a, R> { + fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>) { + self.0.replace_append(caps, dst) + } + fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> { + self.0.no_expansion() + } +} + +impl<'a> Replacer for &'a [u8] { + fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>) { + caps.expand(*self, dst); + } + + fn no_expansion(&mut self) -> Option<Cow<[u8]>> { + match memchr(b'$', *self) { + Some(_) => None, + None => Some(Cow::Borrowed(*self)), + } + } +} + +impl<F> Replacer for F where F: FnMut(&Captures) -> Vec<u8> { + fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>) { + dst.extend_from_slice(&(*self)(caps)); + } +} + +/// `NoExpand` indicates literal byte string replacement. +/// +/// It can be used with `replace` and `replace_all` to do a literal byte string +/// replacement without expanding `$name` to their corresponding capture +/// groups. This can be both convenient (to avoid escaping `$`, for example) +/// and performant (since capture groups don't need to be found). +/// +/// `'t` is the lifetime of the literal text. +pub struct NoExpand<'t>(pub &'t [u8]); + +impl<'t> Replacer for NoExpand<'t> { + fn replace_append(&mut self, _: &Captures, dst: &mut Vec<u8>) { + dst.extend_from_slice(self.0); + } + + fn no_expansion(&mut self) -> Option<Cow<[u8]>> { + Some(Cow::Borrowed(self.0)) + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/re_set.rs cargo-0.26.0/vendor/regex-0.2.10/src/re_set.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/re_set.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/re_set.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,411 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +macro_rules! define_set { + ($name:ident, $builder_mod:ident, $text_ty:ty, $as_bytes:expr, + $(#[$doc_regexset_example:meta])* ) => { + pub mod $name { + use std::fmt; + use std::iter; + use std::slice; + use std::vec; + + use error::Error; + use exec::Exec; + use re_builder::$builder_mod::RegexSetBuilder; + use re_trait::RegularExpression; + +/// Match multiple (possibly overlapping) regular expressions in a single scan. +/// +/// A regex set corresponds to the union of two or more regular expressions. +/// That is, a regex set will match text where at least one of its +/// constituent regular expressions matches. A regex set as its formulated here +/// provides a touch more power: it will also report *which* regular +/// expressions in the set match. Indeed, this is the key difference between +/// regex sets and a single `Regex` with many alternates, since only one +/// alternate can match at a time. +/// +/// For example, consider regular expressions to match email addresses and +/// domains: `[a-z]+@[a-z]+\.(com|org|net)` and `[a-z]+\.(com|org|net)`. If a +/// regex set is constructed from those regexes, then searching the text +/// `foo@example.com` will report both regexes as matching. Of course, one +/// could accomplish this by compiling each regex on its own and doing two +/// searches over the text. The key advantage of using a regex set is that it +/// will report the matching regexes using a *single pass through the text*. +/// If one has hundreds or thousands of regexes to match repeatedly (like a URL +/// router for a complex web application or a user agent matcher), then a regex +/// set can realize huge performance gains. +/// +/// # Example +/// +/// This shows how the above two regexes (for matching email addresses and +/// domains) might work: +/// +$(#[$doc_regexset_example])* +/// +/// Note that it would be possible to adapt the above example to using `Regex` +/// with an expression like: +/// +/// ```ignore +/// (?P<email>[a-z]+@(?P<email_domain>[a-z]+[.](com|org|net)))|(?P<domain>[a-z]+[.](com|org|net)) +/// ``` +/// +/// After a match, one could then inspect the capture groups to figure out +/// which alternates matched. The problem is that it is hard to make this +/// approach scale when there are many regexes since the overlap between each +/// alternate isn't always obvious to reason about. +/// +/// # Limitations +/// +/// Regex sets are limited to answering the following two questions: +/// +/// 1. Does any regex in the set match? +/// 2. If so, which regexes in the set match? +/// +/// As with the main `Regex` type, it is cheaper to ask (1) instead of (2) +/// since the matching engines can stop after the first match is found. +/// +/// Other features like finding the location of successive matches or their +/// sub-captures aren't supported. If you need this functionality, the +/// recommended approach is to compile each regex in the set independently and +/// selectively match them based on which regexes in the set matched. +/// +/// # Performance +/// +/// A `RegexSet` has the same performance characteristics as `Regex`. Namely, +/// search takes `O(mn)` time, where `m` is proportional to the size of the +/// regex set and `n` is proportional to the length of the search text. +#[derive(Clone)] +pub struct RegexSet(Exec); + +impl RegexSet { + /// Create a new regex set with the given regular expressions. + /// + /// This takes an iterator of `S`, where `S` is something that can produce + /// a `&str`. If any of the strings in the iterator are not valid regular + /// expressions, then an error is returned. + /// + /// # Example + /// + /// Create a new regex set from an iterator of strings: + /// + /// ```rust + /// # use regex::RegexSet; + /// let set = RegexSet::new(&[r"\w+", r"\d+"]).unwrap(); + /// assert!(set.is_match("foo")); + /// ``` + pub fn new<I, S>(exprs: I) -> Result<RegexSet, Error> + where S: AsRef<str>, I: IntoIterator<Item=S> { + RegexSetBuilder::new(exprs).build() + } + + /// Returns true if and only if one of the regexes in this set matches + /// the text given. + /// + /// This method should be preferred if you only need to test whether any + /// of the regexes in the set should match, but don't care about *which* + /// regexes matched. This is because the underlying matching engine will + /// quit immediately after seeing the first match instead of continuing to + /// find all matches. + /// + /// Note that as with searches using `Regex`, the expression is unanchored + /// by default. That is, if the regex does not start with `^` or `\A`, or + /// end with `$` or `\z`, then it is permitted to match anywhere in the + /// text. + /// + /// # Example + /// + /// Tests whether a set matches some text: + /// + /// ```rust + /// # use regex::RegexSet; + /// let set = RegexSet::new(&[r"\w+", r"\d+"]).unwrap(); + /// assert!(set.is_match("foo")); + /// assert!(!set.is_match("☃")); + /// ``` + pub fn is_match(&self, text: $text_ty) -> bool { + self.is_match_at(text, 0) + } + + /// Returns the same as is_match, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn is_match_at(&self, text: $text_ty, start: usize) -> bool { + self.0.searcher().is_match_at($as_bytes(text), start) + } + + /// Returns the set of regular expressions that match in the given text. + /// + /// The set returned contains the index of each regular expression that + /// matches in the given text. The index is in correspondence with the + /// order of regular expressions given to `RegexSet`'s constructor. + /// + /// The set can also be used to iterate over the matched indices. + /// + /// Note that as with searches using `Regex`, the expression is unanchored + /// by default. That is, if the regex does not start with `^` or `\A`, or + /// end with `$` or `\z`, then it is permitted to match anywhere in the + /// text. + /// + /// # Example + /// + /// Tests which regular expressions match the given text: + /// + /// ```rust + /// # use regex::RegexSet; + /// let set = RegexSet::new(&[ + /// r"\w+", + /// r"\d+", + /// r"\pL+", + /// r"foo", + /// r"bar", + /// r"barfoo", + /// r"foobar", + /// ]).unwrap(); + /// let matches: Vec<_> = set.matches("foobar").into_iter().collect(); + /// assert_eq!(matches, vec![0, 2, 3, 4, 6]); + /// + /// // You can also test whether a particular regex matched: + /// let matches = set.matches("foobar"); + /// assert!(!matches.matched(5)); + /// assert!(matches.matched(6)); + /// ``` + pub fn matches(&self, text: $text_ty) -> SetMatches { + let mut matches = vec![false; self.0.regex_strings().len()]; + let any = self.read_matches_at(&mut matches, text, 0); + SetMatches { + matched_any: any, + matches: matches, + } + } + + /// Returns the same as matches, but starts the search at the given + /// offset and stores the matches into the slice given. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + /// + /// `matches` must have a length that is at least the number of regexes + /// in this set. + /// + /// This method returns true if and only if at least one member of + /// `matches` is true after executing the set against `text`. + #[doc(hidden)] + pub fn read_matches_at( + &self, + matches: &mut [bool], + text: $text_ty, + start: usize, + ) -> bool { + self.0.searcher().many_matches_at(matches, $as_bytes(text), start) + } + + /// Returns the total number of regular expressions in this set. + pub fn len(&self) -> usize { + self.0.regex_strings().len() + } +} + +/// A set of matches returned by a regex set. +#[derive(Clone, Debug)] +pub struct SetMatches { + matched_any: bool, + matches: Vec<bool>, +} + +impl SetMatches { + /// Whether this set contains any matches. + pub fn matched_any(&self) -> bool { + self.matched_any + } + + /// Whether the regex at the given index matched. + /// + /// The index for a regex is determined by its insertion order upon the + /// initial construction of a `RegexSet`, starting at `0`. + /// + /// # Panics + /// + /// If `regex_index` is greater than or equal to `self.len()`. + pub fn matched(&self, regex_index: usize) -> bool { + self.matches[regex_index] + } + + /// The total number of regexes in the set that created these matches. + pub fn len(&self) -> usize { + self.matches.len() + } + + /// Returns an iterator over indexes in the regex that matched. + pub fn iter(&self) -> SetMatchesIter { + SetMatchesIter((&*self.matches).into_iter().enumerate()) + } +} + +impl IntoIterator for SetMatches { + type IntoIter = SetMatchesIntoIter; + type Item = usize; + + fn into_iter(self) -> Self::IntoIter { + SetMatchesIntoIter(self.matches.into_iter().enumerate()) + } +} + +impl<'a> IntoIterator for &'a SetMatches { + type IntoIter = SetMatchesIter<'a>; + type Item = usize; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +/// An owned iterator over the set of matches from a regex set. +pub struct SetMatchesIntoIter(iter::Enumerate<vec::IntoIter<bool>>); + +impl Iterator for SetMatchesIntoIter { + type Item = usize; + + fn next(&mut self) -> Option<usize> { + loop { + match self.0.next() { + None => return None, + Some((_, false)) => {} + Some((i, true)) => return Some(i), + } + } + } +} + +impl DoubleEndedIterator for SetMatchesIntoIter { + fn next_back(&mut self) -> Option<usize> { + loop { + match self.0.next_back() { + None => return None, + Some((_, false)) => {} + Some((i, true)) => return Some(i), + } + } + } +} + +/// A borrowed iterator over the set of matches from a regex set. +/// +/// The lifetime `'a` refers to the lifetime of a `SetMatches` value. +#[derive(Clone)] +pub struct SetMatchesIter<'a>(iter::Enumerate<slice::Iter<'a, bool>>); + +impl<'a> Iterator for SetMatchesIter<'a> { + type Item = usize; + + fn next(&mut self) -> Option<usize> { + loop { + match self.0.next() { + None => return None, + Some((_, &false)) => {} + Some((i, &true)) => return Some(i), + } + } + } +} + +impl<'a> DoubleEndedIterator for SetMatchesIter<'a> { + fn next_back(&mut self) -> Option<usize> { + loop { + match self.0.next_back() { + None => return None, + Some((_, &false)) => {} + Some((i, &true)) => return Some(i), + } + } + } +} + +#[doc(hidden)] +impl From<Exec> for RegexSet { + fn from(exec: Exec) -> Self { + RegexSet(exec) + } +} + +impl fmt::Debug for RegexSet { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "RegexSet({:?})", self.0.regex_strings()) + } +} + +#[allow(dead_code)] fn as_bytes_str(text: &str) -> &[u8] { text.as_bytes() } +#[allow(dead_code)] fn as_bytes_bytes(text: &[u8]) -> &[u8] { text } + } + } +} + +define_set! { + unicode, + set_unicode, + &str, + as_bytes_str, +/// ```rust +/// # use regex::RegexSet; +/// let set = RegexSet::new(&[ +/// r"[a-z]+@[a-z]+\.(com|org|net)", +/// r"[a-z]+\.(com|org|net)", +/// ]).unwrap(); +/// +/// // Ask whether any regexes in the set match. +/// assert!(set.is_match("foo@example.com")); +/// +/// // Identify which regexes in the set match. +/// let matches: Vec<_> = set.matches("foo@example.com").into_iter().collect(); +/// assert_eq!(vec![0, 1], matches); +/// +/// // Try again, but with text that only matches one of the regexes. +/// let matches: Vec<_> = set.matches("example.com").into_iter().collect(); +/// assert_eq!(vec![1], matches); +/// +/// // Try again, but with text that doesn't match any regex in the set. +/// let matches: Vec<_> = set.matches("example").into_iter().collect(); +/// assert!(matches.is_empty()); +/// ``` +} + +define_set! { + bytes, + set_bytes, + &[u8], + as_bytes_bytes, +/// ```rust +/// # use regex::bytes::RegexSet; +/// let set = RegexSet::new(&[ +/// r"[a-z]+@[a-z]+\.(com|org|net)", +/// r"[a-z]+\.(com|org|net)", +/// ]).unwrap(); +/// +/// // Ask whether any regexes in the set match. +/// assert!(set.is_match(b"foo@example.com")); +/// +/// // Identify which regexes in the set match. +/// let matches: Vec<_> = set.matches(b"foo@example.com").into_iter().collect(); +/// assert_eq!(vec![0, 1], matches); +/// +/// // Try again, but with text that only matches one of the regexes. +/// let matches: Vec<_> = set.matches(b"example.com").into_iter().collect(); +/// assert_eq!(vec![1], matches); +/// +/// // Try again, but with text that doesn't match any regex in the set. +/// let matches: Vec<_> = set.matches(b"example").into_iter().collect(); +/// assert!(matches.is_empty()); +/// ``` +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/re_trait.rs cargo-0.26.0/vendor/regex-0.2.10/src/re_trait.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/re_trait.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/re_trait.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,268 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/// Slot is a single saved capture location. Note that there are two slots for +/// every capture in a regular expression (one slot each for the start and end +/// of the capture). +pub type Slot = Option<usize>; + +/// Locations represents the offsets of each capturing group in a regex for +/// a single match. +/// +/// Unlike `Captures`, a `Locations` value only stores offsets. +#[doc(hidden)] +pub struct Locations(Vec<Slot>); + +impl Locations { + /// Returns the start and end positions of the Nth capture group. Returns + /// `None` if `i` is not a valid capture group or if the capture group did + /// not match anything. The positions returned are *always* byte indices + /// with respect to the original string matched. + pub fn pos(&self, i: usize) -> Option<(usize, usize)> { + let (s, e) = (i * 2, i * 2 + 1); + match (self.0.get(s), self.0.get(e)) { + (Some(&Some(s)), Some(&Some(e))) => Some((s, e)), + _ => None, + } + } + + /// Creates an iterator of all the capture group positions in order of + /// appearance in the regular expression. Positions are byte indices + /// in terms of the original string matched. + pub fn iter(&self) -> SubCapturesPosIter { + SubCapturesPosIter { idx: 0, locs: self } + } + + /// Returns the total number of capturing groups. + /// + /// This is always at least `1` since every regex has at least `1` + /// capturing group that corresponds to the entire match. + pub fn len(&self) -> usize { + self.0.len() / 2 + } +} + +/// This is a hack to make Locations -> &mut [Slot] be available internally +/// without exposing it in the public API. +pub fn as_slots(locs: &mut Locations) -> &mut [Slot] { + &mut locs.0 +} + +/// An iterator over capture group positions for a particular match of a +/// regular expression. +/// +/// Positions are byte indices in terms of the original string matched. +/// +/// `'c` is the lifetime of the captures. +pub struct SubCapturesPosIter<'c> { + idx: usize, + locs: &'c Locations, +} + +impl<'c> Iterator for SubCapturesPosIter<'c> { + type Item = Option<(usize, usize)>; + + fn next(&mut self) -> Option<Option<(usize, usize)>> { + if self.idx >= self.locs.len() { + return None; + } + let x = match self.locs.pos(self.idx) { + None => Some(None), + Some((s, e)) => { + Some(Some((s, e))) + } + }; + self.idx += 1; + x + } +} + +/// `RegularExpression` describes types that can implement regex searching. +/// +/// This trait is my attempt at reducing code duplication and to standardize +/// the internal API. Specific duplication that is avoided are the `find` +/// and `capture` iterators, which are slightly tricky. +/// +/// It's not clear whether this trait is worth it, and it also isn't +/// clear whether it's useful as a public trait or not. Methods like +/// `next_after_empty` reak of bad design, but the rest of the methods seem +/// somewhat reasonable. One particular thing this trait would expose would be +/// the ability to start the search of a regex anywhere in a haystack, which +/// isn't possible in the current public API. +pub trait RegularExpression: Sized { + /// The type of the haystack. + type Text: ?Sized; + + /// The number of capture slots in the compiled regular expression. This is + /// always two times the number of capture groups (two slots per group). + fn slots_len(&self) -> usize; + + /// Allocates fresh space for all capturing groups in this regex. + fn locations(&self) -> Locations { + Locations(vec![None; self.slots_len()]) + } + + /// Returns the position of the next character after `i`. + /// + /// For example, a haystack with type `&[u8]` probably returns `i+1`, + /// whereas a haystack with type `&str` probably returns `i` plus the + /// length of the next UTF-8 sequence. + fn next_after_empty(&self, text: &Self::Text, i: usize) -> usize; + + /// Returns the location of the shortest match. + fn shortest_match_at( + &self, + text: &Self::Text, + start: usize, + ) -> Option<usize>; + + /// Returns whether the regex matches the text given. + fn is_match_at( + &self, + text: &Self::Text, + start: usize, + ) -> bool; + + /// Returns the leftmost-first match location if one exists. + fn find_at( + &self, + text: &Self::Text, + start: usize, + ) -> Option<(usize, usize)>; + + /// Returns the leftmost-first match location if one exists, and also + /// fills in any matching capture slot locations. + fn read_captures_at( + &self, + locs: &mut Locations, + text: &Self::Text, + start: usize, + ) -> Option<(usize, usize)>; + + /// Returns an iterator over all non-overlapping successive leftmost-first + /// matches. + fn find_iter ( + self, + text: &Self::Text, + ) -> Matches<Self> { + Matches { + re: self, + text: text, + last_end: 0, + last_match: None, + } + } + + /// Returns an iterator over all non-overlapping successive leftmost-first + /// matches with captures. + fn captures_iter( + self, + text: &Self::Text, + ) -> CaptureMatches<Self> { + CaptureMatches(self.find_iter(text)) + } +} + +/// An iterator over all non-overlapping successive leftmost-first matches. +pub struct Matches<'t, R> where R: RegularExpression, R::Text: 't { + re: R, + text: &'t R::Text, + last_end: usize, + last_match: Option<usize>, +} + +impl<'t, R> Matches<'t, R> where R: RegularExpression, R::Text: 't { + /// Return the text being searched. + pub fn text(&self) -> &'t R::Text { + self.text + } + + /// Return the underlying regex. + pub fn regex(&self) -> &R { + &self.re + } +} + +impl<'t, R> Iterator for Matches<'t, R> + where R: RegularExpression, R::Text: 't + AsRef<[u8]> { + type Item = (usize, usize); + + fn next(&mut self) -> Option<(usize, usize)> { + if self.last_end > self.text.as_ref().len() { + return None; + } + let (s, e) = match self.re.find_at(self.text, self.last_end) { + None => return None, + Some((s, e)) => (s, e), + }; + if s == e { + // This is an empty match. To ensure we make progress, start + // the next search at the smallest possible starting position + // of the next match following this one. + self.last_end = self.re.next_after_empty(self.text, e); + // Don't accept empty matches immediately following a match. + // Just move on to the next match. + if Some(e) == self.last_match { + return self.next(); + } + } else { + self.last_end = e; + } + self.last_match = Some(e); + Some((s, e)) + } +} + +/// An iterator over all non-overlapping successive leftmost-first matches with +/// captures. +pub struct CaptureMatches<'t, R>(Matches<'t, R>) + where R: RegularExpression, R::Text: 't; + +impl<'t, R> CaptureMatches<'t, R> where R: RegularExpression, R::Text: 't { + /// Return the text being searched. + pub fn text(&self) -> &'t R::Text { + self.0.text() + } + + /// Return the underlying regex. + pub fn regex(&self) -> &R { + self.0.regex() + } +} + +impl<'t, R> Iterator for CaptureMatches<'t, R> + where R: RegularExpression, R::Text: 't + AsRef<[u8]> { + type Item = Locations; + + fn next(&mut self) -> Option<Locations> { + if self.0.last_end > self.0.text.as_ref().len() { + return None + } + let mut locs = self.0.re.locations(); + let (s, e) = match self.0.re.read_captures_at( + &mut locs, + self.0.text, + self.0.last_end, + ) { + None => return None, + Some((s, e)) => (s, e), + }; + if s == e { + self.0.last_end = self.0.re.next_after_empty(self.0.text, e); + if Some(e) == self.0.last_match { + return self.next(); + } + } else { + self.0.last_end = e; + } + self.0.last_match = Some(e); + Some(locs) + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/re_unicode.rs cargo-0.26.0/vendor/regex-0.2.10/src/re_unicode.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/re_unicode.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/re_unicode.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1116 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::fmt; +use std::ops::Index; +use std::str::FromStr; +use std::sync::Arc; + +use memchr::memchr; +use syntax; + +use error::Error; +use exec::{Exec, ExecNoSyncStr}; +use expand::expand_str; +use re_builder::unicode::RegexBuilder; +use re_trait::{self, RegularExpression, Locations, SubCapturesPosIter}; + +/// Escapes all regular expression meta characters in `text`. +/// +/// The string returned may be safely used as a literal in a regular +/// expression. +pub fn escape(text: &str) -> String { + syntax::escape(text) +} + +/// Match represents a single match of a regex in a haystack. +/// +/// The lifetime parameter `'t` refers to the lifetime of the matched text. +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub struct Match<'t> { + text: &'t str, + start: usize, + end: usize, +} + +impl<'t> Match<'t> { + /// Returns the starting byte offset of the match in the haystack. + #[inline] + pub fn start(&self) -> usize { + self.start + } + + /// Returns the ending byte offset of the match in the haystack. + #[inline] + pub fn end(&self) -> usize { + self.end + } + + /// Returns the matched text. + #[inline] + pub fn as_str(&self) -> &'t str { + &self.text[self.start..self.end] + } + + /// Creates a new match from the given haystack and byte offsets. + #[inline] + fn new(haystack: &'t str, start: usize, end: usize) -> Match<'t> { + Match { + text: haystack, + start: start, + end: end, + } + } +} + +impl<'t> From<Match<'t>> for &'t str { + fn from(m: Match<'t>) -> &'t str { + m.as_str() + } +} + +/// A compiled regular expression for matching Unicode strings. +/// +/// It is represented as either a sequence of bytecode instructions (dynamic) +/// or as a specialized Rust function (native). It can be used to search, split +/// or replace text. All searching is done with an implicit `.*?` at the +/// beginning and end of an expression. To force an expression to match the +/// whole string (or a prefix or a suffix), you must use an anchor like `^` or +/// `$` (or `\A` and `\z`). +/// +/// While this crate will handle Unicode strings (whether in the regular +/// expression or in the search text), all positions returned are **byte +/// indices**. Every byte index is guaranteed to be at a Unicode code point +/// boundary. +/// +/// The lifetimes `'r` and `'t` in this crate correspond to the lifetime of a +/// compiled regular expression and text to search, respectively. +/// +/// The only methods that allocate new strings are the string replacement +/// methods. All other methods (searching and splitting) return borrowed +/// pointers into the string given. +/// +/// # Examples +/// +/// Find the location of a US phone number: +/// +/// ```rust +/// # use regex::Regex; +/// let re = Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}").unwrap(); +/// let mat = re.find("phone: 111-222-3333").unwrap(); +/// assert_eq!((mat.start(), mat.end()), (7, 19)); +/// ``` +/// +/// # Using the `std::str::pattern` methods with `Regex` +/// +/// > **Note**: This section requires that this crate is compiled with the +/// > `pattern` Cargo feature enabled, which **requires nightly Rust**. +/// +/// Since `Regex` implements `Pattern`, you can use regexes with methods +/// defined on `&str`. For example, `is_match`, `find`, `find_iter` +/// and `split` can be replaced with `str::contains`, `str::find`, +/// `str::match_indices` and `str::split`. +/// +/// Here are some examples: +/// +/// ```rust,ignore +/// # use regex::Regex; +/// let re = Regex::new(r"\d+").unwrap(); +/// let haystack = "a111b222c"; +/// +/// assert!(haystack.contains(&re)); +/// assert_eq!(haystack.find(&re), Some(1)); +/// assert_eq!(haystack.match_indices(&re).collect::<Vec<_>>(), +/// vec![(1, 4), (5, 8)]); +/// assert_eq!(haystack.split(&re).collect::<Vec<_>>(), vec!["a", "b", "c"]); +/// ``` +#[derive(Clone)] +pub struct Regex(Exec); + +impl fmt::Display for Regex { + /// Shows the original regular expression. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.as_str()) + } +} + +impl fmt::Debug for Regex { + /// Shows the original regular expression. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +#[doc(hidden)] +impl From<Exec> for Regex { + fn from(exec: Exec) -> Regex { + Regex(exec) + } +} + +impl FromStr for Regex { + type Err = Error; + + /// Attempts to parse a string into a regular expression + fn from_str(s: &str) -> Result<Regex, Error> { + Regex::new(s) + } +} + +/// Core regular expression methods. +impl Regex { + /// Compiles a regular expression. Once compiled, it can be used repeatedly + /// to search, split or replace text in a string. + /// + /// If an invalid expression is given, then an error is returned. + pub fn new(re: &str) -> Result<Regex, Error> { + RegexBuilder::new(re).build() + } + + /// Returns true if and only if the regex matches the string given. + /// + /// It is recommended to use this method if all you need to do is test + /// a match, since the underlying matching engine may be able to do less + /// work. + /// + /// # Example + /// + /// Test if some text contains at least one word with exactly 13 + /// Unicode word characters: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let text = "I categorically deny having triskaidekaphobia."; + /// assert!(Regex::new(r"\b\w{13}\b").unwrap().is_match(text)); + /// # } + /// ``` + pub fn is_match(&self, text: &str) -> bool { + self.is_match_at(text, 0) + } + + /// Returns the start and end byte range of the leftmost-first match in + /// `text`. If no match exists, then `None` is returned. + /// + /// Note that this should only be used if you want to discover the position + /// of the match. Testing the existence of a match is faster if you use + /// `is_match`. + /// + /// # Example + /// + /// Find the start and end location of the first word with exactly 13 + /// Unicode word characters: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let text = "I categorically deny having triskaidekaphobia."; + /// let mat = Regex::new(r"\b\w{13}\b").unwrap().find(text).unwrap(); + /// assert_eq!(mat.start(), 2); + /// assert_eq!(mat.end(), 15); + /// # } + /// ``` + pub fn find<'t>(&self, text: &'t str) -> Option<Match<'t>> { + self.find_at(text, 0) + } + + /// Returns an iterator for each successive non-overlapping match in + /// `text`, returning the start and end byte indices with respect to + /// `text`. + /// + /// # Example + /// + /// Find the start and end location of every word with exactly 13 Unicode + /// word characters: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let text = "Retroactively relinquishing remunerations is reprehensible."; + /// for mat in Regex::new(r"\b\w{13}\b").unwrap().find_iter(text) { + /// println!("{:?}", mat); + /// } + /// # } + /// ``` + pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> Matches<'r, 't> { + Matches(self.0.searcher_str().find_iter(text)) + } + + /// Returns the capture groups corresponding to the leftmost-first + /// match in `text`. Capture group `0` always corresponds to the entire + /// match. If no match is found, then `None` is returned. + /// + /// You should only use `captures` if you need access to the location of + /// capturing group matches. Otherwise, `find` is faster for discovering + /// the location of the overall match. + /// + /// # Examples + /// + /// Say you have some text with movie names and their release years, + /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text + /// looking like that, while also extracting the movie name and its release + /// year separately. + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"'([^']+)'\s+\((\d{4})\)").unwrap(); + /// let text = "Not my favorite movie: 'Citizen Kane' (1941)."; + /// let caps = re.captures(text).unwrap(); + /// assert_eq!(caps.get(1).unwrap().as_str(), "Citizen Kane"); + /// assert_eq!(caps.get(2).unwrap().as_str(), "1941"); + /// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)"); + /// // You can also access the groups by index using the Index notation. + /// // Note that this will panic on an invalid index. + /// assert_eq!(&caps[1], "Citizen Kane"); + /// assert_eq!(&caps[2], "1941"); + /// assert_eq!(&caps[0], "'Citizen Kane' (1941)"); + /// # } + /// ``` + /// + /// Note that the full match is at capture group `0`. Each subsequent + /// capture group is indexed by the order of its opening `(`. + /// + /// We can make this example a bit clearer by using *named* capture groups: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)") + /// .unwrap(); + /// let text = "Not my favorite movie: 'Citizen Kane' (1941)."; + /// let caps = re.captures(text).unwrap(); + /// assert_eq!(&caps["title"], "Citizen Kane"); + /// assert_eq!(&caps["year"], "1941"); + /// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)"); + /// // You can also access the groups by name using the Index notation. + /// // Note that this will panic on an invalid group name. + /// assert_eq!(&caps["title"], "Citizen Kane"); + /// assert_eq!(&caps["year"], "1941"); + /// assert_eq!(&caps[0], "'Citizen Kane' (1941)"); + /// + /// # } + /// ``` + /// + /// Here we name the capture groups, which we can access with the `name` + /// method or the `Index` notation with a `&str`. Note that the named + /// capture groups are still accessible with `get` or the `Index` notation + /// with a `usize`. + /// + /// The `0`th capture group is always unnamed, so it must always be + /// accessed with `get(0)` or `[0]`. + pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> { + let mut locs = self.locations(); + self.read_captures_at(&mut locs, text, 0).map(|_| Captures { + text: text, + locs: locs, + named_groups: self.0.capture_name_idx().clone(), + }) + } + + /// Returns an iterator over all the non-overlapping capture groups matched + /// in `text`. This is operationally the same as `find_iter`, except it + /// yields information about capturing group matches. + /// + /// # Example + /// + /// We can use this to find all movie titles and their release years in + /// some text, where the movie is formatted like "'Title' (xxxx)": + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)") + /// .unwrap(); + /// let text = "'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931)."; + /// for caps in re.captures_iter(text) { + /// println!("Movie: {:?}, Released: {:?}", + /// &caps["title"], &caps["year"]); + /// } + /// // Output: + /// // Movie: Citizen Kane, Released: 1941 + /// // Movie: The Wizard of Oz, Released: 1939 + /// // Movie: M, Released: 1931 + /// # } + /// ``` + pub fn captures_iter<'r, 't>( + &'r self, + text: &'t str, + ) -> CaptureMatches<'r, 't> { + CaptureMatches(self.0.searcher_str().captures_iter(text)) + } + + /// Returns an iterator of substrings of `text` delimited by a match of the + /// regular expression. Namely, each element of the iterator corresponds to + /// text that *isn't* matched by the regular expression. + /// + /// This method will *not* copy the text given. + /// + /// # Example + /// + /// To split a string delimited by arbitrary amounts of spaces or tabs: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"[ \t]+").unwrap(); + /// let fields: Vec<&str> = re.split("a b \t c\td e").collect(); + /// assert_eq!(fields, vec!["a", "b", "c", "d", "e"]); + /// # } + /// ``` + pub fn split<'r, 't>(&'r self, text: &'t str) -> Split<'r, 't> { + Split { + finder: self.find_iter(text), + last: 0, + } + } + + /// Returns an iterator of at most `limit` substrings of `text` delimited + /// by a match of the regular expression. (A `limit` of `0` will return no + /// substrings.) Namely, each element of the iterator corresponds to text + /// that *isn't* matched by the regular expression. The remainder of the + /// string that is not split will be the last element in the iterator. + /// + /// This method will *not* copy the text given. + /// + /// # Example + /// + /// Get the first two words in some text: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"\W+").unwrap(); + /// let fields: Vec<&str> = re.splitn("Hey! How are you?", 3).collect(); + /// assert_eq!(fields, vec!("Hey", "How", "are you?")); + /// # } + /// ``` + pub fn splitn<'r, 't>(&'r self, text: &'t str, limit: usize) + -> SplitN<'r, 't> { + SplitN { + splits: self.split(text), + n: limit, + } + } + + /// Replaces the leftmost-first match with the replacement provided. + /// The replacement can be a regular string (where `$N` and `$name` are + /// expanded to match capture groups) or a function that takes the matches' + /// `Captures` and returns the replaced string. + /// + /// If no match is found, then a copy of the string is returned unchanged. + /// + /// # Replacement string syntax + /// + /// All instances of `$name` in the replacement text is replaced with the + /// corresponding capture group `name`. + /// + /// `name` may be an integer corresponding to the index of the + /// capture group (counted by order of opening parenthesis where `0` is the + /// entire match) or it can be a name (consisting of letters, digits or + /// underscores) corresponding to a named capture group. + /// + /// If `name` isn't a valid capture group (whether the name doesn't exist + /// or isn't a valid index), then it is replaced with the empty string. + /// + /// The longest possible name is used. e.g., `$1a` looks up the capture + /// group named `1a` and not the capture group at index `1`. To exert more + /// precise control over the name, use braces, e.g., `${1}a`. + /// + /// To write a literal `$` use `$$`. + /// + /// # Examples + /// + /// Note that this function is polymorphic with respect to the replacement. + /// In typical usage, this can just be a normal string: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new("[^01]+").unwrap(); + /// assert_eq!(re.replace("1078910", ""), "1010"); + /// # } + /// ``` + /// + /// But anything satisfying the `Replacer` trait will work. For example, + /// a closure of type `|&Captures| -> String` provides direct access to the + /// captures corresponding to a match. This allows one to access + /// capturing group matches easily: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # use regex::Captures; fn main() { + /// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap(); + /// let result = re.replace("Springsteen, Bruce", |caps: &Captures| { + /// format!("{} {}", &caps[2], &caps[1]) + /// }); + /// assert_eq!(result, "Bruce Springsteen"); + /// # } + /// ``` + /// + /// But this is a bit cumbersome to use all the time. Instead, a simple + /// syntax is supported that expands `$name` into the corresponding capture + /// group. Here's the last example, but using this expansion technique + /// with named capture groups: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)").unwrap(); + /// let result = re.replace("Springsteen, Bruce", "$first $last"); + /// assert_eq!(result, "Bruce Springsteen"); + /// # } + /// ``` + /// + /// Note that using `$2` instead of `$first` or `$1` instead of `$last` + /// would produce the same result. To write a literal `$` use `$$`. + /// + /// Sometimes the replacement string requires use of curly braces to + /// delineate a capture group replacement and surrounding literal text. + /// For example, if we wanted to join two words together with an + /// underscore: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap(); + /// let result = re.replace("deep fried", "${first}_$second"); + /// assert_eq!(result, "deep_fried"); + /// # } + /// ``` + /// + /// Without the curly braces, the capture group name `first_` would be + /// used, and since it doesn't exist, it would be replaced with the empty + /// string. + /// + /// Finally, sometimes you just want to replace a literal string with no + /// regard for capturing group expansion. This can be done by wrapping a + /// byte string with `NoExpand`: + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// use regex::NoExpand; + /// + /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(\S+)").unwrap(); + /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last")); + /// assert_eq!(result, "$2 $last"); + /// # } + /// ``` + pub fn replace<'t, R: Replacer>( + &self, + text: &'t str, + rep: R, + ) -> Cow<'t, str> { + self.replacen(text, 1, rep) + } + + /// Replaces all non-overlapping matches in `text` with the replacement + /// provided. This is the same as calling `replacen` with `limit` set to + /// `0`. + /// + /// See the documentation for `replace` for details on how to access + /// capturing group matches in the replacement string. + pub fn replace_all<'t, R: Replacer>( + &self, + text: &'t str, + rep: R, + ) -> Cow<'t, str> { + self.replacen(text, 0, rep) + } + + /// Replaces at most `limit` non-overlapping matches in `text` with the + /// replacement provided. If `limit` is 0, then all non-overlapping matches + /// are replaced. + /// + /// See the documentation for `replace` for details on how to access + /// capturing group matches in the replacement string. + pub fn replacen<'t, R: Replacer>( + &self, + text: &'t str, + limit: usize, + mut rep: R, + ) -> Cow<'t, str> { + // If we know that the replacement doesn't have any capture expansions, + // then we can fast path. The fast path can make a tremendous + // difference: + // + // 1) We use `find_iter` instead of `captures_iter`. Not asking for + // captures generally makes the regex engines faster. + // 2) We don't need to look up all of the capture groups and do + // replacements inside the replacement string. We just push it + // at each match and be done with it. + if let Some(rep) = rep.no_expansion() { + let mut it = self.find_iter(text).enumerate().peekable(); + if it.peek().is_none() { + return Cow::Borrowed(text); + } + let mut new = String::with_capacity(text.len()); + let mut last_match = 0; + for (i, m) in it { + if limit > 0 && i >= limit { + break + } + new.push_str(&text[last_match..m.start()]); + new.push_str(&rep); + last_match = m.end(); + } + new.push_str(&text[last_match..]); + return Cow::Owned(new); + } + + // The slower path, which we use if the replacement needs access to + // capture groups. + let mut it = self.captures_iter(text).enumerate().peekable(); + if it.peek().is_none() { + return Cow::Borrowed(text); + } + let mut new = String::with_capacity(text.len()); + let mut last_match = 0; + for (i, cap) in it { + if limit > 0 && i >= limit { + break + } + // unwrap on 0 is OK because captures only reports matches + let m = cap.get(0).unwrap(); + new.push_str(&text[last_match..m.start()]); + rep.replace_append(&cap, &mut new); + last_match = m.end(); + } + new.push_str(&text[last_match..]); + Cow::Owned(new) + } +} + +/// Advanced or "lower level" search methods. +impl Regex { + /// Returns the end location of a match in the text given. + /// + /// This method may have the same performance characteristics as + /// `is_match`, except it provides an end location for a match. In + /// particular, the location returned *may be shorter* than the proper end + /// of the leftmost-first match. + /// + /// # Example + /// + /// Typically, `a+` would match the entire first sequence of `a` in some + /// text, but `shortest_match` can give up as soon as it sees the first + /// `a`. + /// + /// ```rust + /// # extern crate regex; use regex::Regex; + /// # fn main() { + /// let text = "aaaaa"; + /// let pos = Regex::new(r"a+").unwrap().shortest_match(text); + /// assert_eq!(pos, Some(1)); + /// # } + /// ``` + pub fn shortest_match(&self, text: &str) -> Option<usize> { + self.shortest_match_at(text, 0) + } + + /// Returns the same as shortest_match, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn shortest_match_at( + &self, + text: &str, + start: usize, + ) -> Option<usize> { + self.0.searcher_str().shortest_match_at(text, start) + } + + /// Returns the same as is_match, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn is_match_at(&self, text: &str, start: usize) -> bool { + self.shortest_match_at(text, start).is_some() + } + + /// Returns the same as find, but starts the search at the given + /// offset. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn find_at<'t>( + &self, + text: &'t str, + start: usize, + ) -> Option<Match<'t>> { + self.0.searcher_str().find_at(text, start).map(|(s, e)| { + Match::new(text, s, e) + }) + } + + /// Returns the same as captures, but starts the search at the given + /// offset and populates the capture locations given. + /// + /// The significance of the starting point is that it takes the surrounding + /// context into consideration. For example, the `\A` anchor can only + /// match when `start == 0`. + #[doc(hidden)] + pub fn read_captures_at<'t>( + &self, + locs: &mut Locations, + text: &'t str, + start: usize, + ) -> Option<Match<'t>> { + self.0 + .searcher_str() + .read_captures_at(locs, text, start) + .map(|(s, e)| Match::new(text, s, e)) + } +} + +/// Auxiliary methods. +impl Regex { + /// Returns the original string of this regex. + pub fn as_str(&self) -> &str { + &self.0.regex_strings()[0] + } + + /// Returns an iterator over the capture names. + pub fn capture_names(&self) -> CaptureNames { + CaptureNames(self.0.capture_names().iter()) + } + + /// Returns the number of captures. + pub fn captures_len(&self) -> usize { + self.0.capture_names().len() + } + + /// Returns an empty set of locations that can be reused in multiple calls + /// to `read_captures`. + #[doc(hidden)] + pub fn locations(&self) -> Locations { + self.0.searcher_str().locations() + } +} + +/// An iterator over the names of all possible captures. +/// +/// `None` indicates an unnamed capture; the first element (capture 0, the +/// whole matched region) is always unnamed. +/// +/// `'r` is the lifetime of the compiled regular expression. +pub struct CaptureNames<'r>(::std::slice::Iter<'r, Option<String>>); + +impl<'r> Iterator for CaptureNames<'r> { + type Item = Option<&'r str>; + + fn next(&mut self) -> Option<Option<&'r str>> { + self.0 + .next() + .as_ref() + .map(|slot| slot.as_ref().map(|name| name.as_ref())) + } + + fn size_hint(&self) -> (usize, Option<usize>) { + self.0.size_hint() + } +} + +/// Yields all substrings delimited by a regular expression match. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the string being split. +pub struct Split<'r, 't> { + finder: Matches<'r, 't>, + last: usize, +} + +impl<'r, 't> Iterator for Split<'r, 't> { + type Item = &'t str; + + fn next(&mut self) -> Option<&'t str> { + let text = self.finder.0.text(); + match self.finder.next() { + None => { + if self.last >= text.len() { + None + } else { + let s = &text[self.last..]; + self.last = text.len(); + Some(s) + } + } + Some(m) => { + let matched = &text[self.last..m.start()]; + self.last = m.end(); + Some(matched) + } + } + } +} + +/// Yields at most `N` substrings delimited by a regular expression match. +/// +/// The last substring will be whatever remains after splitting. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the string being split. +pub struct SplitN<'r, 't> { + splits: Split<'r, 't>, + n: usize, +} + +impl<'r, 't> Iterator for SplitN<'r, 't> { + type Item = &'t str; + + fn next(&mut self) -> Option<&'t str> { + if self.n == 0 { + return None + } + self.n -= 1; + if self.n == 0 { + let text = self.splits.finder.0.text(); + Some(&text[self.splits.last..]) + } else { + self.splits.next() + } + } +} + +/// Captures represents a group of captured strings for a single match. +/// +/// The 0th capture always corresponds to the entire match. Each subsequent +/// index corresponds to the next capture group in the regex. If a capture +/// group is named, then the matched string is *also* available via the `name` +/// method. (Note that the 0th capture is always unnamed and so must be +/// accessed with the `get` method.) +/// +/// Positions returned from a capture group are always byte indices. +/// +/// `'t` is the lifetime of the matched text. +pub struct Captures<'t> { + text: &'t str, + locs: Locations, + named_groups: Arc<HashMap<String, usize>>, +} + +impl<'t> Captures<'t> { + /// Returns the match associated with the capture group at index `i`. If + /// `i` does not correspond to a capture group, or if the capture group + /// did not participate in the match, then `None` is returned. + /// + /// # Examples + /// + /// Get the text of the match with a default of an empty string if this + /// group didn't participate in the match: + /// + /// ```rust + /// # use regex::Regex; + /// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap(); + /// let caps = re.captures("abc123").unwrap(); + /// + /// let text1 = caps.get(1).map_or("", |m| m.as_str()); + /// let text2 = caps.get(2).map_or("", |m| m.as_str()); + /// assert_eq!(text1, "123"); + /// assert_eq!(text2, ""); + /// ``` + pub fn get(&self, i: usize) -> Option<Match<'t>> { + self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e)) + } + + /// Returns the match for the capture group named `name`. If `name` isn't a + /// valid capture group or didn't match anything, then `None` is returned. + pub fn name(&self, name: &str) -> Option<Match<'t>> { + self.named_groups.get(name).and_then(|&i| self.get(i)) + } + + /// An iterator that yields all capturing matches in the order in which + /// they appear in the regex. If a particular capture group didn't + /// participate in the match, then `None` is yielded for that capture. + /// + /// The first match always corresponds to the overall match of the regex. + pub fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 't> { + SubCaptureMatches { + caps: self, + it: self.locs.iter(), + } + } + + /// Expands all instances of `$name` in `replacement` to the corresponding + /// capture group `name`, and writes them to the `dst` buffer given. + /// + /// `name` may be an integer corresponding to the index of the + /// capture group (counted by order of opening parenthesis where `0` is the + /// entire match) or it can be a name (consisting of letters, digits or + /// underscores) corresponding to a named capture group. + /// + /// If `name` isn't a valid capture group (whether the name doesn't exist + /// or isn't a valid index), then it is replaced with the empty string. + /// + /// The longest possible name is used. e.g., `$1a` looks up the capture + /// group named `1a` and not the capture group at index `1`. To exert more + /// precise control over the name, use braces, e.g., `${1}a`. + /// + /// To write a literal `$` use `$$`. + pub fn expand(&self, replacement: &str, dst: &mut String) { + expand_str(self, replacement, dst) + } + + /// Returns the number of captured groups. + /// + /// This is always at least `1`, since every regex has at least one capture + /// group that corresponds to the full match. + #[inline] + pub fn len(&self) -> usize { + self.locs.len() + } +} + +impl<'t> fmt::Debug for Captures<'t> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_tuple("Captures").field(&CapturesDebug(self)).finish() + } +} + +struct CapturesDebug<'c, 't: 'c>(&'c Captures<'t>); + +impl<'c, 't> fmt::Debug for CapturesDebug<'c, 't> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // We'd like to show something nice here, even if it means an + // allocation to build a reverse index. + let slot_to_name: HashMap<&usize, &String> = + self.0.named_groups.iter().map(|(a, b)| (b, a)).collect(); + let mut map = f.debug_map(); + for (slot, m) in self.0.locs.iter().enumerate() { + let m = m.map(|(s, e)| &self.0.text[s..e]); + if let Some(name) = slot_to_name.get(&slot) { + map.entry(&name, &m); + } else { + map.entry(&slot, &m); + } + } + map.finish() + } +} + +/// Get a group by index. +/// +/// `'t` is the lifetime of the matched text. +/// +/// The text can't outlive the `Captures` object if this method is +/// used, because of how `Index` is defined (normally `a[i]` is part +/// of `a` and can't outlive it); to do that, use `get()` instead. +/// +/// # Panics +/// +/// If there is no group at the given index. +impl<'t> Index<usize> for Captures<'t> { + type Output = str; + + fn index(&self, i: usize) -> &str { + self.get(i).map(|m| m.as_str()) + .unwrap_or_else(|| panic!("no group at index '{}'", i)) + } +} + +/// Get a group by name. +/// +/// `'t` is the lifetime of the matched text and `'i` is the lifetime +/// of the group name (the index). +/// +/// The text can't outlive the `Captures` object if this method is +/// used, because of how `Index` is defined (normally `a[i]` is part +/// of `a` and can't outlive it); to do that, use `name` instead. +/// +/// # Panics +/// +/// If there is no group named by the given value. +impl<'t, 'i> Index<&'i str> for Captures<'t> { + type Output = str; + + fn index<'a>(&'a self, name: &'i str) -> &'a str { + self.name(name).map(|m| m.as_str()) + .unwrap_or_else(|| panic!("no group named '{}'", name)) + } +} + +/// An iterator that yields all capturing matches in the order in which they +/// appear in the regex. +/// +/// If a particular capture group didn't participate in the match, then `None` +/// is yielded for that capture. The first match always corresponds to the +/// overall match of the regex. +/// +/// The lifetime `'c` corresponds to the lifetime of the `Captures` value, and +/// the lifetime `'t` corresponds to the originally matched text. +pub struct SubCaptureMatches<'c, 't: 'c> { + caps: &'c Captures<'t>, + it: SubCapturesPosIter<'c>, +} + +impl<'c, 't> Iterator for SubCaptureMatches<'c, 't> { + type Item = Option<Match<'t>>; + + fn next(&mut self) -> Option<Option<Match<'t>>> { + self.it.next() + .map(|cap| cap.map(|(s, e)| Match::new(self.caps.text, s, e))) + } +} + +/// An iterator that yields all non-overlapping capture groups matching a +/// particular regular expression. +/// +/// The iterator stops when no more matches can be found. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the matched string. +pub struct CaptureMatches<'r, 't>(re_trait::CaptureMatches<'t, ExecNoSyncStr<'r>>); + +impl<'r, 't> Iterator for CaptureMatches<'r, 't> { + type Item = Captures<'t>; + + fn next(&mut self) -> Option<Captures<'t>> { + self.0.next().map(|locs| Captures { + text: self.0.text(), + locs: locs, + named_groups: self.0.regex().capture_name_idx().clone(), + }) + } +} + +/// An iterator over all non-overlapping matches for a particular string. +/// +/// The iterator yields a `Match` value. The iterator stops when no more +/// matches can be found. +/// +/// `'r` is the lifetime of the compiled regular expression and `'t` is the +/// lifetime of the matched string. +pub struct Matches<'r, 't>(re_trait::Matches<'t, ExecNoSyncStr<'r>>); + +impl<'r, 't> Iterator for Matches<'r, 't> { + type Item = Match<'t>; + + fn next(&mut self) -> Option<Match<'t>> { + let text = self.0.text(); + self.0.next().map(|(s, e)| Match::new(text, s, e)) + } +} + +/// Replacer describes types that can be used to replace matches in a string. +/// +/// In general, users of this crate shouldn't need to implement this trait, +/// since implementations are already provided for `&str` and +/// `FnMut(&Captures) -> String`, which covers most use cases. +pub trait Replacer { + /// Appends text to `dst` to replace the current match. + /// + /// The current match is represented by `caps`, which is guaranteed to + /// have a match at capture group `0`. + /// + /// For example, a no-op replacement would be + /// `dst.extend(caps.get(0).unwrap().as_str())`. + fn replace_append(&mut self, caps: &Captures, dst: &mut String); + + /// Return a fixed unchanging replacement string. + /// + /// When doing replacements, if access to `Captures` is not needed (e.g., + /// the replacement byte string does not need `$` expansion), then it can + /// be beneficial to avoid finding sub-captures. + /// + /// In general, this is called once for every call to `replacen`. + fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, str>> { + None + } + + /// Return a `Replacer` that borrows and wraps this `Replacer`. + /// + /// This is useful when you want to take a generic `Replacer` (which might + /// not be cloneable) and use it without consuming it, so it can be used + /// more than once. + /// + /// # Example + /// + /// ``` + /// use regex::{Regex, Replacer}; + /// + /// fn replace_all_twice<R: Replacer>( + /// re: Regex, + /// src: &str, + /// mut rep: R, + /// ) -> String { + /// let dst = re.replace_all(src, rep.by_ref()); + /// let dst = re.replace_all(&dst, rep.by_ref()); + /// dst.into_owned() + /// } + /// ``` + fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self> { + ReplacerRef(self) + } +} + +/// By-reference adaptor for a `Replacer` +/// +/// Returned by [`Replacer::by_ref`](trait.Replacer.html#method.by_ref). +#[derive(Debug)] +pub struct ReplacerRef<'a, R: ?Sized + 'a>(&'a mut R); + +impl<'a, R: Replacer + ?Sized + 'a> Replacer for ReplacerRef<'a, R> { + fn replace_append(&mut self, caps: &Captures, dst: &mut String) { + self.0.replace_append(caps, dst) + } + fn no_expansion(&mut self) -> Option<Cow<str>> { + self.0.no_expansion() + } +} + +impl<'a> Replacer for &'a str { + fn replace_append(&mut self, caps: &Captures, dst: &mut String) { + caps.expand(*self, dst); + } + + fn no_expansion(&mut self) -> Option<Cow<str>> { + match memchr(b'$', self.as_bytes()) { + Some(_) => None, + None => Some(Cow::Borrowed(*self)), + } + } +} + +impl<F> Replacer for F where F: FnMut(&Captures) -> String { + fn replace_append(&mut self, caps: &Captures, dst: &mut String) { + dst.push_str(&(*self)(caps)); + } +} + +/// `NoExpand` indicates literal string replacement. +/// +/// It can be used with `replace` and `replace_all` to do a literal string +/// replacement without expanding `$name` to their corresponding capture +/// groups. This can be both convenient (to avoid escaping `$`, for example) +/// and performant (since capture groups don't need to be found). +/// +/// `'t` is the lifetime of the literal text. +pub struct NoExpand<'t>(pub &'t str); + +impl<'t> Replacer for NoExpand<'t> { + fn replace_append(&mut self, _: &Captures, dst: &mut String) { + dst.push_str(self.0); + } + + fn no_expansion(&mut self) -> Option<Cow<str>> { + Some(Cow::Borrowed(self.0)) + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/sparse.rs cargo-0.26.0/vendor/regex-0.2.10/src/sparse.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/sparse.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/sparse.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,78 @@ +use std::ops::Deref; +use std::slice; + +/// A sparse set used for representing ordered NFA states. +/// +/// This supports constant time addition and membership testing. Clearing an +/// entire set can also be done in constant time. Iteration yields elements +/// in the order in which they were inserted. +/// +/// The data structure is based on: http://research.swtch.com/sparse +/// Note though that we don't actually use unitialized memory. We generally +/// reuse allocations, so the initial allocation cost is bareable. However, +/// its other properties listed above are extremely useful. +#[derive(Clone, Debug)] +pub struct SparseSet { + /// Dense contains the instruction pointers in the order in which they + /// were inserted. Accessing elements >= self.size is illegal. + dense: Vec<usize>, + /// Sparse maps instruction pointers to their location in dense. + /// + /// An instruction pointer is in the set if and only if + /// sparse[ip] < size && ip == dense[sparse[ip]]. + sparse: Vec<usize>, + /// The number of elements in the set. + size: usize, +} + +impl SparseSet { + pub fn new(size: usize) -> SparseSet { + SparseSet { + dense: vec![0; size], + sparse: vec![0; size], + size: 0, + } + } + + pub fn len(&self) -> usize { + self.size + } + + pub fn is_empty(&self) -> bool { + self.size == 0 + } + + pub fn capacity(&self) -> usize { + self.dense.len() + } + + pub fn insert(&mut self, value: usize) { + let i = self.size; + self.dense[i] = value; + self.sparse[value] = i; + self.size += 1; + } + + pub fn contains(&self, value: usize) -> bool { + let i = self.sparse[value]; + i < self.size && self.dense[i] == value + } + + pub fn clear(&mut self) { + self.size = 0; + } +} + +impl Deref for SparseSet { + type Target = [usize]; + + fn deref(&self) -> &Self::Target { + &self.dense[0..self.size] + } +} + +impl<'a> IntoIterator for &'a SparseSet { + type Item = &'a usize; + type IntoIter = slice::Iter<'a, usize>; + fn into_iter(self) -> Self::IntoIter { self.iter() } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/testdata/basic.dat cargo-0.26.0/vendor/regex-0.2.10/src/testdata/basic.dat --- cargo-0.25.0/vendor/regex-0.2.10/src/testdata/basic.dat 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/testdata/basic.dat 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,221 @@ +NOTE all standard compliant implementations should pass these : 2002-05-31 + +BE abracadabra$ abracadabracadabra (7,18) +BE a...b abababbb (2,7) +BE XXXXXX ..XXXXXX (2,8) +E \) () (1,2) +BE a] a]a (0,2) +B } } (0,1) +E \} } (0,1) +BE \] ] (0,1) +B ] ] (0,1) +E ] ] (0,1) +B { { (0,1) +B } } (0,1) +BE ^a ax (0,1) +BE \^a a^a (1,3) +BE a\^ a^ (0,2) +BE a$ aa (1,2) +BE a\$ a$ (0,2) +BE ^$ NULL (0,0) +E $^ NULL (0,0) +E a($) aa (1,2)(2,2) +E a*(^a) aa (0,1)(0,1) +E (..)*(...)* a (0,0) +E (..)*(...)* abcd (0,4)(2,4) +E (ab|a)(bc|c) abc (0,3)(0,2)(2,3) +E (ab)c|abc abc (0,3)(0,2) +E a{0}b ab (1,2) +E (a*)(b?)(b+)b{3} aaabbbbbbb (0,10)(0,3)(3,4)(4,7) +E (a*)(b{0,1})(b{1,})b{3} aaabbbbbbb (0,10)(0,3)(3,4)(4,7) +E a{9876543210} NULL BADBR +E ((a|a)|a) a (0,1)(0,1)(0,1) +E (a*)(a|aa) aaaa (0,4)(0,3)(3,4) +E a*(a.|aa) aaaa (0,4)(2,4) +E a(b)|c(d)|a(e)f aef (0,3)(?,?)(?,?)(1,2) +E (a|b)?.* b (0,1)(0,1) +E (a|b)c|a(b|c) ac (0,2)(0,1) +E (a|b)c|a(b|c) ab (0,2)(?,?)(1,2) +E (a|b)*c|(a|ab)*c abc (0,3)(1,2) +E (a|b)*c|(a|ab)*c xc (1,2) +E (.a|.b).*|.*(.a|.b) xa (0,2)(0,2) +E a?(ab|ba)ab abab (0,4)(0,2) +E a?(ac{0}b|ba)ab abab (0,4)(0,2) +E ab|abab abbabab (0,2) +E aba|bab|bba baaabbbaba (5,8) +E aba|bab baaabbbaba (6,9) +E (aa|aaa)*|(a|aaaaa) aa (0,2)(0,2) +E (a.|.a.)*|(a|.a...) aa (0,2)(0,2) +E ab|a xabc (1,3) +E ab|a xxabc (2,4) +Ei (Ab|cD)* aBcD (0,4)(2,4) +BE [^-] --a (2,3) +BE [a-]* --a (0,3) +BE [a-m-]* --amoma-- (0,4) +E :::1:::0:|:::1:1:0: :::0:::1:::1:::0: (8,17) +E :::1:::0:|:::1:1:1: :::0:::1:::1:::0: (8,17) +{E [[:upper:]] A (0,1) [[<element>]] not supported +E [[:lower:]]+ `az{ (1,3) +E [[:upper:]]+ @AZ[ (1,3) +# No collation in Go +#BE [[-]] [[-]] (2,4) +#BE [[.NIL.]] NULL ECOLLATE +#BE [[=aleph=]] NULL ECOLLATE +} +BE$ \n \n (0,1) +BEn$ \n \n (0,1) +BE$ [^a] \n (0,1) +BE$ \na \na (0,2) +E (a)(b)(c) abc (0,3)(0,1)(1,2)(2,3) +BE xxx xxx (0,3) +E1 (^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$) feb 6, (0,6) +E1 (^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$) 2/7 (0,3) +E1 (^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$) feb 1,Feb 6 (5,11) +E3 ((((((((((((((((((((((((((((((x)))))))))))))))))))))))))))))) x (0,1)(0,1)(0,1) +E3 ((((((((((((((((((((((((((((((x))))))))))))))))))))))))))))))* xx (0,2)(1,2)(1,2) +E a?(ab|ba)* ababababababababababababababababababababababababababababababababababababababababa (0,81)(79,81) +E abaa|abbaa|abbbaa|abbbbaa ababbabbbabbbabbbbabbbbaa (18,25) +E abaa|abbaa|abbbaa|abbbbaa ababbabbbabbbabbbbabaa (18,22) +E aaac|aabc|abac|abbc|baac|babc|bbac|bbbc baaabbbabac (7,11) +BE$ .* \x01\x7f (0,2) +E aaaa|bbbb|cccc|ddddd|eeeeee|fffffff|gggg|hhhh|iiiii|jjjjj|kkkkk|llll XaaaXbbbXcccXdddXeeeXfffXgggXhhhXiiiXjjjXkkkXlllXcbaXaaaa (53,57) +L aaaa\nbbbb\ncccc\nddddd\neeeeee\nfffffff\ngggg\nhhhh\niiiii\njjjjj\nkkkkk\nllll XaaaXbbbXcccXdddXeeeXfffXgggXhhhXiiiXjjjXkkkXlllXcbaXaaaa NOMATCH +E a*a*a*a*a*b aaaaaaaaab (0,10) +BE ^ NULL (0,0) +BE $ NULL (0,0) +BE ^$ NULL (0,0) +BE ^a$ a (0,1) +BE abc abc (0,3) +BE abc xabcy (1,4) +BE abc ababc (2,5) +BE ab*c abc (0,3) +BE ab*bc abc (0,3) +BE ab*bc abbc (0,4) +BE ab*bc abbbbc (0,6) +E ab+bc abbc (0,4) +E ab+bc abbbbc (0,6) +E ab?bc abbc (0,4) +E ab?bc abc (0,3) +E ab?c abc (0,3) +BE ^abc$ abc (0,3) +BE ^abc abcc (0,3) +BE abc$ aabc (1,4) +BE ^ abc (0,0) +BE $ abc (3,3) +BE a.c abc (0,3) +BE a.c axc (0,3) +BE a.*c axyzc (0,5) +BE a[bc]d abd (0,3) +BE a[b-d]e ace (0,3) +BE a[b-d] aac (1,3) +BE a[-b] a- (0,2) +BE a[b-] a- (0,2) +BE a] a] (0,2) +BE a[]]b a]b (0,3) +BE a[^bc]d aed (0,3) +BE a[^-b]c adc (0,3) +BE a[^]b]c adc (0,3) +E ab|cd abc (0,2) +E ab|cd abcd (0,2) +E a\(b a(b (0,3) +E a\(*b ab (0,2) +E a\(*b a((b (0,4) +E ((a)) abc (0,1)(0,1)(0,1) +E (a)b(c) abc (0,3)(0,1)(2,3) +E a+b+c aabbabc (4,7) +E a* aaa (0,3) +#E (a*)* - (0,0)(0,0) +E (a*)* - (0,0)(?,?) RE2/Go +E (a*)+ - (0,0)(0,0) +#E (a*|b)* - (0,0)(0,0) +E (a*|b)* - (0,0)(?,?) RE2/Go +E (a+|b)* ab (0,2)(1,2) +E (a+|b)+ ab (0,2)(1,2) +E (a+|b)? ab (0,1)(0,1) +BE [^ab]* cde (0,3) +#E (^)* - (0,0)(0,0) +E (^)* - (0,0)(?,?) RE2/Go +BE a* NULL (0,0) +E ([abc])*d abbbcd (0,6)(4,5) +E ([abc])*bcd abcd (0,4)(0,1) +E a|b|c|d|e e (0,1) +E (a|b|c|d|e)f ef (0,2)(0,1) +#E ((a*|b))* - (0,0)(0,0)(0,0) +E ((a*|b))* - (0,0)(?,?)(?,?) RE2/Go +BE abcd*efg abcdefg (0,7) +BE ab* xabyabbbz (1,3) +BE ab* xayabbbz (1,2) +E (ab|cd)e abcde (2,5)(2,4) +BE [abhgefdc]ij hij (0,3) +E (a|b)c*d abcd (1,4)(1,2) +E (ab|ab*)bc abc (0,3)(0,1) +E a([bc]*)c* abc (0,3)(1,3) +E a([bc]*)(c*d) abcd (0,4)(1,3)(3,4) +E a([bc]+)(c*d) abcd (0,4)(1,3)(3,4) +E a([bc]*)(c+d) abcd (0,4)(1,2)(2,4) +E a[bcd]*dcdcde adcdcde (0,7) +E (ab|a)b*c abc (0,3)(0,2) +E ((a)(b)c)(d) abcd (0,4)(0,3)(0,1)(1,2)(3,4) +BE [A-Za-z_][A-Za-z0-9_]* alpha (0,5) +E ^a(bc+|b[eh])g|.h$ abh (1,3) +E (bc+d$|ef*g.|h?i(j|k)) effgz (0,5)(0,5) +E (bc+d$|ef*g.|h?i(j|k)) ij (0,2)(0,2)(1,2) +E (bc+d$|ef*g.|h?i(j|k)) reffgz (1,6)(1,6) +E (((((((((a))))))))) a (0,1)(0,1)(0,1)(0,1)(0,1)(0,1)(0,1)(0,1)(0,1)(0,1) +BE multiple words multiple words yeah (0,14) +E (.*)c(.*) abcde (0,5)(0,2)(3,5) +BE abcd abcd (0,4) +E a(bc)d abcd (0,4)(1,3) +E a[-]?c ac (0,3) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Qaddafi (0,15)(?,?)(10,12) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Mo'ammar Gadhafi (0,16)(?,?)(11,13) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Kaddafi (0,15)(?,?)(10,12) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Qadhafi (0,15)(?,?)(10,12) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Gadafi (0,14)(?,?)(10,11) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Mu'ammar Qadafi (0,15)(?,?)(11,12) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Moamar Gaddafi (0,14)(?,?)(9,11) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Mu'ammar Qadhdhafi (0,18)(?,?)(13,15) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Khaddafi (0,16)(?,?)(11,13) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Ghaddafy (0,16)(?,?)(11,13) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Ghadafi (0,15)(?,?)(11,12) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Ghaddafi (0,16)(?,?)(11,13) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muamar Kaddafi (0,14)(?,?)(9,11) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Quathafi (0,16)(?,?)(11,13) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Gheddafi (0,16)(?,?)(11,13) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Moammar Khadafy (0,15)(?,?)(11,12) +E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Moammar Qudhafi (0,15)(?,?)(10,12) +E a+(b|c)*d+ aabcdd (0,6)(3,4) +E ^.+$ vivi (0,4) +E ^(.+)$ vivi (0,4)(0,4) +E ^([^!.]+).att.com!(.+)$ gryphon.att.com!eby (0,19)(0,7)(16,19) +E ^([^!]+!)?([^!]+)$ bas (0,3)(?,?)(0,3) +E ^([^!]+!)?([^!]+)$ bar!bas (0,7)(0,4)(4,7) +E ^([^!]+!)?([^!]+)$ foo!bas (0,7)(0,4)(4,7) +E ^.+!([^!]+!)([^!]+)$ foo!bar!bas (0,11)(4,8)(8,11) +E ((foo)|(bar))!bas bar!bas (0,7)(0,3)(?,?)(0,3) +E ((foo)|(bar))!bas foo!bar!bas (4,11)(4,7)(?,?)(4,7) +E ((foo)|(bar))!bas foo!bas (0,7)(0,3)(0,3) +E ((foo)|bar)!bas bar!bas (0,7)(0,3) +E ((foo)|bar)!bas foo!bar!bas (4,11)(4,7) +E ((foo)|bar)!bas foo!bas (0,7)(0,3)(0,3) +E (foo|(bar))!bas bar!bas (0,7)(0,3)(0,3) +E (foo|(bar))!bas foo!bar!bas (4,11)(4,7)(4,7) +E (foo|(bar))!bas foo!bas (0,7)(0,3) +E (foo|bar)!bas bar!bas (0,7)(0,3) +E (foo|bar)!bas foo!bar!bas (4,11)(4,7) +E (foo|bar)!bas foo!bas (0,7)(0,3) +E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ foo!bar!bas (0,11)(0,11)(?,?)(?,?)(4,8)(8,11) +E ^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$ bas (0,3)(?,?)(0,3) +E ^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$ bar!bas (0,7)(0,4)(4,7) +E ^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$ foo!bar!bas (0,11)(?,?)(?,?)(4,8)(8,11) +E ^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$ foo!bas (0,7)(0,4)(4,7) +E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ bas (0,3)(0,3)(?,?)(0,3) +E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ bar!bas (0,7)(0,7)(0,4)(4,7) +E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ foo!bar!bas (0,11)(0,11)(?,?)(?,?)(4,8)(8,11) +E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ foo!bas (0,7)(0,7)(0,4)(4,7) +E .*(/XXX).* /XXX (0,4)(0,4) +E .*(\\XXX).* \XXX (0,4)(0,4) +E \\XXX \XXX (0,4) +E .*(/000).* /000 (0,4)(0,4) +E .*(\\000).* \000 (0,4)(0,4) +E \\000 \000 (0,4) diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/testdata/LICENSE cargo-0.26.0/vendor/regex-0.2.10/src/testdata/LICENSE --- cargo-0.25.0/vendor/regex-0.2.10/src/testdata/LICENSE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/testdata/LICENSE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,19 @@ +The following license covers testregex.c and all associated test data. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of THIS SOFTWARE FILE (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, and/or sell copies of the +Software, and to permit persons to whom the Software is furnished to do +so, subject to the following disclaimer: + +THIS SOFTWARE IS PROVIDED BY AT&T ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL AT&T BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/testdata/nullsubexpr.dat cargo-0.26.0/vendor/regex-0.2.10/src/testdata/nullsubexpr.dat --- cargo-0.25.0/vendor/regex-0.2.10/src/testdata/nullsubexpr.dat 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/testdata/nullsubexpr.dat 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,79 @@ +NOTE null subexpression matches : 2002-06-06 + +E (a*)* a (0,1)(0,1) +#E SAME x (0,0)(0,0) +E SAME x (0,0)(?,?) RE2/Go +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaax (0,6)(0,6) +E (a*)+ a (0,1)(0,1) +E SAME x (0,0)(0,0) +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaax (0,6)(0,6) +E (a+)* a (0,1)(0,1) +E SAME x (0,0) +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaax (0,6)(0,6) +E (a+)+ a (0,1)(0,1) +E SAME x NOMATCH +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaax (0,6)(0,6) + +E ([a]*)* a (0,1)(0,1) +#E SAME x (0,0)(0,0) +E SAME x (0,0)(?,?) RE2/Go +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaax (0,6)(0,6) +E ([a]*)+ a (0,1)(0,1) +E SAME x (0,0)(0,0) +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaax (0,6)(0,6) +E ([^b]*)* a (0,1)(0,1) +#E SAME b (0,0)(0,0) +E SAME b (0,0)(?,?) RE2/Go +E SAME aaaaaa (0,6)(0,6) +E SAME aaaaaab (0,6)(0,6) +E ([ab]*)* a (0,1)(0,1) +E SAME aaaaaa (0,6)(0,6) +E SAME ababab (0,6)(0,6) +E SAME bababa (0,6)(0,6) +E SAME b (0,1)(0,1) +E SAME bbbbbb (0,6)(0,6) +E SAME aaaabcde (0,5)(0,5) +E ([^a]*)* b (0,1)(0,1) +E SAME bbbbbb (0,6)(0,6) +#E SAME aaaaaa (0,0)(0,0) +E SAME aaaaaa (0,0)(?,?) RE2/Go +E ([^ab]*)* ccccxx (0,6)(0,6) +#E SAME ababab (0,0)(0,0) +E SAME ababab (0,0)(?,?) RE2/Go + +E ((z)+|a)* zabcde (0,2)(1,2) + +#{E a+? aaaaaa (0,1) no *? +? mimimal match ops +#E (a) aaa (0,1)(0,1) +#E (a*?) aaa (0,0)(0,0) +#E (a)*? aaa (0,0) +#E (a*?)*? aaa (0,0) +#} + +B \(a*\)*\(x\) x (0,1)(0,0)(0,1) +B \(a*\)*\(x\) ax (0,2)(0,1)(1,2) +B \(a*\)*\(x\) axa (0,2)(0,1)(1,2) +B \(a*\)*\(x\)\(\1\) x (0,1)(0,0)(0,1)(1,1) +B \(a*\)*\(x\)\(\1\) ax (0,2)(1,1)(1,2)(2,2) +B \(a*\)*\(x\)\(\1\) axa (0,3)(0,1)(1,2)(2,3) +B \(a*\)*\(x\)\(\1\)\(x\) axax (0,4)(0,1)(1,2)(2,3)(3,4) +B \(a*\)*\(x\)\(\1\)\(x\) axxa (0,3)(1,1)(1,2)(2,2)(2,3) + +#E (a*)*(x) x (0,1)(0,0)(0,1) +E (a*)*(x) x (0,1)(?,?)(0,1) RE2/Go +E (a*)*(x) ax (0,2)(0,1)(1,2) +E (a*)*(x) axa (0,2)(0,1)(1,2) + +E (a*)+(x) x (0,1)(0,0)(0,1) +E (a*)+(x) ax (0,2)(0,1)(1,2) +E (a*)+(x) axa (0,2)(0,1)(1,2) + +E (a*){2}(x) x (0,1)(0,0)(0,1) +E (a*){2}(x) ax (0,2)(1,1)(1,2) +E (a*){2}(x) axa (0,2)(1,1)(1,2) diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/testdata/README cargo-0.26.0/vendor/regex-0.2.10/src/testdata/README --- cargo-0.25.0/vendor/regex-0.2.10/src/testdata/README 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/testdata/README 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,17 @@ +Test data was taken from the Go distribution, which was in turn taken from the +testregex test suite: + + http://www2.research.att.com/~astopen/testregex/testregex.html + +The LICENSE in this directory corresponds to the LICENSE that the data was +released under. + +The tests themselves were modified for RE2/Go. A couple were modified further +by me (Andrew Gallant) (only in repetition.dat) so that RE2/Go would pass them. +(Yes, it seems like RE2/Go includes failing test cases.) This may or may not +have been a bad idea, but I think being consistent with an established Regex +library is worth something. + +Note that these files are read by 'scripts/regex-match-tests.py' and turned +into Rust tests found in 'regex_macros/tests/matches.rs'. + diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/testdata/repetition.dat cargo-0.26.0/vendor/regex-0.2.10/src/testdata/repetition.dat --- cargo-0.25.0/vendor/regex-0.2.10/src/testdata/repetition.dat 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/testdata/repetition.dat 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,163 @@ +NOTE implicit vs. explicit repetitions : 2009-02-02 + +# Glenn Fowler <gsf@research.att.com> +# conforming matches (column 4) must match one of the following BREs +# NOMATCH +# (0,.)\((\(.\),\(.\))(?,?)(\2,\3)\)* +# (0,.)\((\(.\),\(.\))(\2,\3)(?,?)\)* +# i.e., each 3-tuple has two identical elements and one (?,?) + +E ((..)|(.)) NULL NOMATCH +E ((..)|(.))((..)|(.)) NULL NOMATCH +E ((..)|(.))((..)|(.))((..)|(.)) NULL NOMATCH + +E ((..)|(.)){1} NULL NOMATCH +E ((..)|(.)){2} NULL NOMATCH +E ((..)|(.)){3} NULL NOMATCH + +E ((..)|(.))* NULL (0,0) + +E ((..)|(.)) a (0,1)(0,1)(?,?)(0,1) +E ((..)|(.))((..)|(.)) a NOMATCH +E ((..)|(.))((..)|(.))((..)|(.)) a NOMATCH + +E ((..)|(.)){1} a (0,1)(0,1)(?,?)(0,1) +E ((..)|(.)){2} a NOMATCH +E ((..)|(.)){3} a NOMATCH + +E ((..)|(.))* a (0,1)(0,1)(?,?)(0,1) + +E ((..)|(.)) aa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.))((..)|(.)) aa (0,2)(0,1)(?,?)(0,1)(1,2)(?,?)(1,2) +E ((..)|(.))((..)|(.))((..)|(.)) aa NOMATCH + +E ((..)|(.)){1} aa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.)){2} aa (0,2)(1,2)(?,?)(1,2) +E ((..)|(.)){3} aa NOMATCH + +E ((..)|(.))* aa (0,2)(0,2)(0,2)(?,?) + +E ((..)|(.)) aaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.))((..)|(.)) aaa (0,3)(0,2)(0,2)(?,?)(2,3)(?,?)(2,3) +E ((..)|(.))((..)|(.))((..)|(.)) aaa (0,3)(0,1)(?,?)(0,1)(1,2)(?,?)(1,2)(2,3)(?,?)(2,3) + +E ((..)|(.)){1} aaa (0,2)(0,2)(0,2)(?,?) +#E ((..)|(.)){2} aaa (0,3)(2,3)(?,?)(2,3) +E ((..)|(.)){2} aaa (0,3)(2,3)(0,2)(2,3) RE2/Go +E ((..)|(.)){3} aaa (0,3)(2,3)(?,?)(2,3) + +#E ((..)|(.))* aaa (0,3)(2,3)(?,?)(2,3) +E ((..)|(.))* aaa (0,3)(2,3)(0,2)(2,3) RE2/Go + +E ((..)|(.)) aaaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.))((..)|(.)) aaaa (0,4)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?) +E ((..)|(.))((..)|(.))((..)|(.)) aaaa (0,4)(0,2)(0,2)(?,?)(2,3)(?,?)(2,3)(3,4)(?,?)(3,4) + +E ((..)|(.)){1} aaaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.)){2} aaaa (0,4)(2,4)(2,4)(?,?) +#E ((..)|(.)){3} aaaa (0,4)(3,4)(?,?)(3,4) +E ((..)|(.)){3} aaaa (0,4)(3,4)(0,2)(3,4) RE2/Go + +E ((..)|(.))* aaaa (0,4)(2,4)(2,4)(?,?) + +E ((..)|(.)) aaaaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.))((..)|(.)) aaaaa (0,4)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?) +E ((..)|(.))((..)|(.))((..)|(.)) aaaaa (0,5)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?)(4,5)(?,?)(4,5) + +E ((..)|(.)){1} aaaaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.)){2} aaaaa (0,4)(2,4)(2,4)(?,?) +#E ((..)|(.)){3} aaaaa (0,5)(4,5)(?,?)(4,5) +E ((..)|(.)){3} aaaaa (0,5)(4,5)(2,4)(4,5) RE2/Go + +#E ((..)|(.))* aaaaa (0,5)(4,5)(?,?)(4,5) +E ((..)|(.))* aaaaa (0,5)(4,5)(2,4)(4,5) RE2/Go + +E ((..)|(.)) aaaaaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.))((..)|(.)) aaaaaa (0,4)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?) +E ((..)|(.))((..)|(.))((..)|(.)) aaaaaa (0,6)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?)(4,6)(4,6)(?,?) + +E ((..)|(.)){1} aaaaaa (0,2)(0,2)(0,2)(?,?) +E ((..)|(.)){2} aaaaaa (0,4)(2,4)(2,4)(?,?) +E ((..)|(.)){3} aaaaaa (0,6)(4,6)(4,6)(?,?) + +E ((..)|(.))* aaaaaa (0,6)(4,6)(4,6)(?,?) + +NOTE additional repetition tests graciously provided by Chris Kuklewicz www.haskell.org 2009-02-02 + +# These test a bug in OS X / FreeBSD / NetBSD, and libtree. +# Linux/GLIBC gets the {8,} and {8,8} wrong. + +:HA#100:E X(.?){0,}Y X1234567Y (0,9)(7,8) +:HA#101:E X(.?){1,}Y X1234567Y (0,9)(7,8) +:HA#102:E X(.?){2,}Y X1234567Y (0,9)(7,8) +:HA#103:E X(.?){3,}Y X1234567Y (0,9)(7,8) +:HA#104:E X(.?){4,}Y X1234567Y (0,9)(7,8) +:HA#105:E X(.?){5,}Y X1234567Y (0,9)(7,8) +:HA#106:E X(.?){6,}Y X1234567Y (0,9)(7,8) +:HA#107:E X(.?){7,}Y X1234567Y (0,9)(7,8) +:HA#108:E X(.?){8,}Y X1234567Y (0,9)(8,8) +#:HA#110:E X(.?){0,8}Y X1234567Y (0,9)(7,8) +:HA#110:E X(.?){0,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#111:E X(.?){1,8}Y X1234567Y (0,9)(7,8) +:HA#111:E X(.?){1,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#112:E X(.?){2,8}Y X1234567Y (0,9)(7,8) +:HA#112:E X(.?){2,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#113:E X(.?){3,8}Y X1234567Y (0,9)(7,8) +:HA#113:E X(.?){3,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#114:E X(.?){4,8}Y X1234567Y (0,9)(7,8) +:HA#114:E X(.?){4,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#115:E X(.?){5,8}Y X1234567Y (0,9)(7,8) +:HA#115:E X(.?){5,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#116:E X(.?){6,8}Y X1234567Y (0,9)(7,8) +:HA#116:E X(.?){6,8}Y X1234567Y (0,9)(8,8) RE2/Go +#:HA#117:E X(.?){7,8}Y X1234567Y (0,9)(7,8) +:HA#117:E X(.?){7,8}Y X1234567Y (0,9)(8,8) RE2/Go +:HA#118:E X(.?){8,8}Y X1234567Y (0,9)(8,8) + +# These test a fixed bug in my regex-tdfa that did not keep the expanded +# form properly grouped, so right association did the wrong thing with +# these ambiguous patterns (crafted just to test my code when I became +# suspicious of my implementation). The first subexpression should use +# "ab" then "a" then "bcd". + +# OS X / FreeBSD / NetBSD badly fail many of these, with impossible +# results like (0,6)(4,5)(6,6). + +:HA#260:E (a|ab|c|bcd){0,}(d*) ababcd (0,1)(0,1)(1,1) +:HA#261:E (a|ab|c|bcd){1,}(d*) ababcd (0,1)(0,1)(1,1) +:HA#262:E (a|ab|c|bcd){2,}(d*) ababcd (0,6)(3,6)(6,6) +:HA#263:E (a|ab|c|bcd){3,}(d*) ababcd (0,6)(3,6)(6,6) +:HA#264:E (a|ab|c|bcd){4,}(d*) ababcd NOMATCH +:HA#265:E (a|ab|c|bcd){0,10}(d*) ababcd (0,1)(0,1)(1,1) +:HA#266:E (a|ab|c|bcd){1,10}(d*) ababcd (0,1)(0,1)(1,1) +:HA#267:E (a|ab|c|bcd){2,10}(d*) ababcd (0,6)(3,6)(6,6) +:HA#268:E (a|ab|c|bcd){3,10}(d*) ababcd (0,6)(3,6)(6,6) +:HA#269:E (a|ab|c|bcd){4,10}(d*) ababcd NOMATCH +:HA#270:E (a|ab|c|bcd)*(d*) ababcd (0,1)(0,1)(1,1) +:HA#271:E (a|ab|c|bcd)+(d*) ababcd (0,1)(0,1)(1,1) + +# The above worked on Linux/GLIBC but the following often fail. +# They also trip up OS X / FreeBSD / NetBSD: + +#:HA#280:E (ab|a|c|bcd){0,}(d*) ababcd (0,6)(3,6)(6,6) +:HA#280:E (ab|a|c|bcd){0,}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#281:E (ab|a|c|bcd){1,}(d*) ababcd (0,6)(3,6)(6,6) +:HA#281:E (ab|a|c|bcd){1,}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#282:E (ab|a|c|bcd){2,}(d*) ababcd (0,6)(3,6)(6,6) +:HA#282:E (ab|a|c|bcd){2,}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#283:E (ab|a|c|bcd){3,}(d*) ababcd (0,6)(3,6)(6,6) +:HA#283:E (ab|a|c|bcd){3,}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +:HA#284:E (ab|a|c|bcd){4,}(d*) ababcd NOMATCH +#:HA#285:E (ab|a|c|bcd){0,10}(d*) ababcd (0,6)(3,6)(6,6) +:HA#285:E (ab|a|c|bcd){0,10}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#286:E (ab|a|c|bcd){1,10}(d*) ababcd (0,6)(3,6)(6,6) +:HA#286:E (ab|a|c|bcd){1,10}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#287:E (ab|a|c|bcd){2,10}(d*) ababcd (0,6)(3,6)(6,6) +:HA#287:E (ab|a|c|bcd){2,10}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#288:E (ab|a|c|bcd){3,10}(d*) ababcd (0,6)(3,6)(6,6) +:HA#288:E (ab|a|c|bcd){3,10}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +:HA#289:E (ab|a|c|bcd){4,10}(d*) ababcd NOMATCH +#:HA#290:E (ab|a|c|bcd)*(d*) ababcd (0,6)(3,6)(6,6) +:HA#290:E (ab|a|c|bcd)*(d*) ababcd (0,6)(4,5)(5,6) RE2/Go +#:HA#291:E (ab|a|c|bcd)+(d*) ababcd (0,6)(3,6)(6,6) +:HA#291:E (ab|a|c|bcd)+(d*) ababcd (0,6)(4,5)(5,6) RE2/Go diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/utf8.rs cargo-0.26.0/vendor/regex-0.2.10/src/utf8.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/utf8.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/utf8.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,290 @@ +/// A few elementary UTF-8 encoding and decoding functions used by the matching +/// engines. +/// +/// In an ideal world, the matching engines operate on `&str` and we can just +/// lean on the standard library for all our UTF-8 needs. However, to support +/// byte based regexes (that can match on arbitrary bytes which may contain +/// UTF-8), we need to be capable of searching and decoding UTF-8 on a `&[u8]`. +/// The standard library doesn't really recognize this use case, so we have +/// to build it out ourselves. +/// +/// Should this be factored out into a separate crate? It seems independently +/// useful. There are other crates that already exist (e.g., `utf-8`) that have +/// overlapping use cases. Not sure what to do. + +use std::char; + +const TAG_CONT: u8 = 0b1000_0000; +const TAG_TWO: u8 = 0b1100_0000; +const TAG_THREE: u8 = 0b1110_0000; +const TAG_FOUR: u8 = 0b1111_0000; + +/// Returns the smallest possible index of the next valid UTF-8 sequence +/// starting after `i`. +pub fn next_utf8(text: &[u8], i: usize) -> usize { + let b = match text.get(i) { + None => return i + 1, + Some(&b) => b, + }; + let inc = if b <= 0x7F { + 1 + } else if b <= 0b110_11111 { + 2 + } else if b <= 0b1110_1111 { + 3 + } else { + 4 + }; + i + inc +} + +/// Encode the given Unicode character to `dst` as a single UTF-8 sequence. +/// +/// If `dst` is not long enough, then `None` is returned. Otherwise, the number +/// of bytes written is returned. +#[allow(dead_code)] +#[inline] +pub fn encode_utf8(character: char, dst: &mut [u8]) -> Option<usize> { + let code = character as u32; + if code <= 0x7F && !dst.is_empty() { + dst[0] = code as u8; + Some(1) + } else if code <= 0x7FF && dst.len() >= 2 { + dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO; + dst[1] = (code & 0x3F) as u8 | TAG_CONT; + Some(2) + } else if code <= 0xFFFF && dst.len() >= 3 { + dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE; + dst[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + dst[2] = (code & 0x3F) as u8 | TAG_CONT; + Some(3) + } else if dst.len() >= 4 { + dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR; + dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; + dst[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + dst[3] = (code & 0x3F) as u8 | TAG_CONT; + Some(4) + } else { + None + } +} + +/// Decode a single UTF-8 sequence into a single Unicode codepoint from `src`. +/// +/// If no valid UTF-8 sequence could be found, then `None` is returned. +/// Otherwise, the decoded codepoint and the number of bytes read is returned. +/// The number of bytes read (for a valid UTF-8 sequence) is guaranteed to be +/// 1, 2, 3 or 4. +/// +/// Note that a UTF-8 sequence is invalid if it is incorrect UTF-8, encodes a +/// codepoint that is out of range (surrogate codepoints are out of range) or +/// is not the shortest possible UTF-8 sequence for that codepoint. +#[inline] +pub fn decode_utf8(src: &[u8]) -> Option<(char, usize)> { + let b0 = match src.get(0) { + None => return None, + Some(&b) if b <= 0x7F => return Some((b as char, 1)), + Some(&b) => b, + }; + match b0 { + 0b110_00000 ... 0b110_11111 => { + if src.len() < 2 { + return None; + } + let b1 = src[1]; + if 0b11_000000 & b1 != TAG_CONT { + return None; + } + let cp = ((b0 & !TAG_TWO) as u32) << 6 + | ((b1 & !TAG_CONT) as u32); + match cp { + 0x80 ... 0x7FF => char::from_u32(cp).map(|cp| (cp, 2)), + _ => None, + } + } + 0b1110_0000 ... 0b1110_1111 => { + if src.len() < 3 { + return None; + } + let (b1, b2) = (src[1], src[2]); + if 0b11_000000 & b1 != TAG_CONT { + return None; + } + if 0b11_000000 & b2 != TAG_CONT { + return None; + } + let cp = ((b0 & !TAG_THREE) as u32) << 12 + | ((b1 & !TAG_CONT) as u32) << 6 + | ((b2 & !TAG_CONT) as u32); + match cp { + // char::from_u32 will disallow surrogate codepoints. + 0x800 ... 0xFFFF => char::from_u32(cp).map(|cp| (cp, 3)), + _ => None, + } + } + 0b11110_000 ... 0b11110_111 => { + if src.len() < 4 { + return None; + } + let (b1, b2, b3) = (src[1], src[2], src[3]); + if 0b11_000000 & b1 != TAG_CONT { + return None; + } + if 0b11_000000 & b2 != TAG_CONT { + return None; + } + if 0b11_000000 & b3 != TAG_CONT { + return None; + } + let cp = ((b0 & !TAG_FOUR) as u32) << 18 + | ((b1 & !TAG_CONT) as u32) << 12 + | ((b2 & !TAG_CONT) as u32) << 6 + | ((b3 & !TAG_CONT) as u32); + match cp { + 0x10000 ... 0x10FFFF => char::from_u32(cp).map(|cp| (cp, 4)), + _ => None, + } + } + _ => None, + } +} + +/// Like `decode_utf8`, but decodes the last UTF-8 sequence in `src` instead +/// of the first. +pub fn decode_last_utf8(src: &[u8]) -> Option<(char, usize)> { + if src.is_empty() { + return None; + } + let mut start = src.len() - 1; + if src[start] <= 0x7F { + return Some((src[start] as char, 1)); + } + while start > src.len().saturating_sub(4) { + start -= 1; + if is_start_byte(src[start]) { + break; + } + } + match decode_utf8(&src[start..]) { + None => None, + Some((_, n)) if n < src.len() - start => None, + Some((cp, n)) => Some((cp, n)), + } +} + +fn is_start_byte(b: u8) -> bool { + b & 0b11_000000 != 0b1_0000000 +} + +#[cfg(test)] +mod tests { + use std::str; + + use quickcheck::quickcheck; + + use super::{ + TAG_CONT, TAG_TWO, TAG_THREE, TAG_FOUR, + decode_utf8, decode_last_utf8, encode_utf8, + }; + + #[test] + fn prop_roundtrip() { + fn p(given_cp: char) -> bool { + let mut tmp = [0; 4]; + let encoded_len = encode_utf8(given_cp, &mut tmp).unwrap(); + let (got_cp, got_len) = decode_utf8(&tmp[..encoded_len]).unwrap(); + encoded_len == got_len && given_cp == got_cp + } + quickcheck(p as fn(char) -> bool) + } + + #[test] + fn prop_roundtrip_last() { + fn p(given_cp: char) -> bool { + let mut tmp = [0; 4]; + let encoded_len = encode_utf8(given_cp, &mut tmp).unwrap(); + let (got_cp, got_len) = + decode_last_utf8(&tmp[..encoded_len]).unwrap(); + encoded_len == got_len && given_cp == got_cp + } + quickcheck(p as fn(char) -> bool) + } + + #[test] + fn prop_encode_matches_std() { + fn p(cp: char) -> bool { + let mut got = [0; 4]; + let n = encode_utf8(cp, &mut got).unwrap(); + let expected = cp.to_string(); + &got[..n] == expected.as_bytes() + } + quickcheck(p as fn(char) -> bool) + } + + #[test] + fn prop_decode_matches_std() { + fn p(given_cp: char) -> bool { + let mut tmp = [0; 4]; + let n = encode_utf8(given_cp, &mut tmp).unwrap(); + let (got_cp, _) = decode_utf8(&tmp[..n]).unwrap(); + let expected_cp = + str::from_utf8(&tmp[..n]).unwrap().chars().next().unwrap(); + got_cp == expected_cp + } + quickcheck(p as fn(char) -> bool) + } + + #[test] + fn prop_decode_last_matches_std() { + fn p(given_cp: char) -> bool { + let mut tmp = [0; 4]; + let n = encode_utf8(given_cp, &mut tmp).unwrap(); + let (got_cp, _) = decode_last_utf8(&tmp[..n]).unwrap(); + let expected_cp = + str::from_utf8(&tmp[..n]).unwrap() + .chars().rev().next().unwrap(); + got_cp == expected_cp + } + quickcheck(p as fn(char) -> bool) + } + + #[test] + fn reject_invalid() { + // Invalid start byte + assert_eq!(decode_utf8(&[0xFF]), None); + // Surrogate pair + assert_eq!(decode_utf8(&[0xED, 0xA0, 0x81]), None); + // Invalid continuation byte. + assert_eq!(decode_utf8(&[0xD4, 0xC2]), None); + // Bad lengths + assert_eq!(decode_utf8(&[0xC3]), None); // 2 bytes + assert_eq!(decode_utf8(&[0xEF, 0xBF]), None); // 3 bytes + assert_eq!(decode_utf8(&[0xF4, 0x8F, 0xBF]), None); // 4 bytes + // Not a minimal UTF-8 sequence + assert_eq!(decode_utf8(&[TAG_TWO, TAG_CONT | b'a']), None); + assert_eq!(decode_utf8(&[TAG_THREE, TAG_CONT, TAG_CONT | b'a']), None); + assert_eq!(decode_utf8(&[ + TAG_FOUR, TAG_CONT, TAG_CONT, TAG_CONT | b'a', + ]), None); + } + + #[test] + fn reject_invalid_last() { + // Invalid start byte + assert_eq!(decode_last_utf8(&[0xFF]), None); + // Surrogate pair + assert_eq!(decode_last_utf8(&[0xED, 0xA0, 0x81]), None); + // Bad lengths + assert_eq!(decode_last_utf8(&[0xC3]), None); // 2 bytes + assert_eq!(decode_last_utf8(&[0xEF, 0xBF]), None); // 3 bytes + assert_eq!(decode_last_utf8(&[0xF4, 0x8F, 0xBF]), None); // 4 bytes + // Not a minimal UTF-8 sequence + assert_eq!(decode_last_utf8(&[TAG_TWO, TAG_CONT | b'a']), None); + assert_eq!(decode_last_utf8(&[ + TAG_THREE, TAG_CONT, TAG_CONT | b'a', + ]), None); + assert_eq!(decode_last_utf8(&[ + TAG_FOUR, TAG_CONT, TAG_CONT, TAG_CONT | b'a', + ]), None); + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/vector/avx2.rs cargo-0.26.0/vendor/regex-0.2.10/src/vector/avx2.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/vector/avx2.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/vector/avx2.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,195 @@ +#![allow(dead_code)] + +use std::arch::x86_64::*; +use std::fmt; + +#[derive(Clone, Copy, Debug)] +pub struct AVX2VectorBuilder(()); + +impl AVX2VectorBuilder { + pub fn new() -> Option<AVX2VectorBuilder> { + if is_x86_feature_detected!("avx2") { + Some(AVX2VectorBuilder(())) + } else { + None + } + } + + /// Create a new u8x32 AVX2 vector where all of the bytes are set to + /// the given value. + #[inline] + pub fn u8x32_splat(self, n: u8) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { u8x32::splat(n) } + } + + /// Load 32 bytes from the given slice, with bounds checks. + #[inline] + pub fn u8x32_load_unaligned(self, slice: &[u8]) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { u8x32::load_unaligned(slice) } + } + + /// Load 32 bytes from the given slice, without bounds checks. + #[inline] + pub unsafe fn u8x32_load_unchecked_unaligned(self, slice: &[u8]) -> u8x32 { + // Safe because we know AVX2 is enabled, but still unsafe + // because we aren't doing bounds checks. + u8x32::load_unchecked_unaligned(slice) + } + + /// Load 32 bytes from the given slice, with bound and alignment checks. + #[inline] + pub fn u8x32_load(self, slice: &[u8]) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { u8x32::load(slice) } + } + + /// Load 32 bytes from the given slice, without bound or alignment checks. + #[inline] + pub unsafe fn u8x32_load_unchecked(self, slice: &[u8]) -> u8x32 { + // Safe because we know AVX2 is enabled, but still unsafe + // because we aren't doing bounds checks. + u8x32::load_unchecked(slice) + } +} + +// We define our union with a macro so that our code continues to compile on +// Rust 1.12. +macro_rules! defunion { + () => { + #[derive(Clone, Copy)] + #[allow(non_camel_case_types)] + pub union u8x32 { + vector: __m256i, + bytes: [u8; 32], + } + } +} + +defunion!(); + +impl u8x32 { + #[inline] + unsafe fn splat(n: u8) -> u8x32 { + u8x32 { vector: _mm256_set1_epi8(n as i8) } + } + + #[inline] + unsafe fn load_unaligned(slice: &[u8]) -> u8x32 { + assert!(slice.len() >= 32); + u8x32::load_unchecked_unaligned(slice) + } + + #[inline] + unsafe fn load_unchecked_unaligned(slice: &[u8]) -> u8x32 { + let p = slice.as_ptr() as *const u8 as *const __m256i; + u8x32 { vector: _mm256_loadu_si256(p) } + } + + #[inline] + unsafe fn load(slice: &[u8]) -> u8x32 { + assert!(slice.len() >= 32); + assert!(slice.as_ptr() as usize % 32 == 0); + u8x32::load_unchecked(slice) + } + + #[inline] + unsafe fn load_unchecked(slice: &[u8]) -> u8x32 { + let p = slice.as_ptr() as *const u8 as *const __m256i; + u8x32 { vector: _mm256_load_si256(p) } + } + + #[inline] + pub fn extract(self, i: usize) -> u8 { + // Safe because `bytes` is always accessible. + unsafe { self.bytes[i] } + } + + #[inline] + pub fn replace(&mut self, i: usize, byte: u8) { + // Safe because `bytes` is always accessible. + unsafe { self.bytes[i] = byte; } + } + + #[inline] + pub fn shuffle(self, indices: u8x32) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { + u8x32 { vector: _mm256_shuffle_epi8(self.vector, indices.vector) } + } + } + + #[inline] + pub fn ne(self, other: u8x32) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { + let boolv = _mm256_cmpeq_epi8(self.vector, other.vector); + let ones = _mm256_set1_epi8(0xFF as u8 as i8); + u8x32 { vector: _mm256_andnot_si256(boolv, ones) } + } + } + + #[inline] + pub fn and(self, other: u8x32) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { + u8x32 { vector: _mm256_and_si256(self.vector, other.vector) } + } + } + + #[inline] + pub fn movemask(self) -> u32 { + // Safe because we know AVX2 is enabled. + unsafe { + _mm256_movemask_epi8(self.vector) as u32 + } + } + + #[inline] + pub fn alignr_14(self, other: u8x32) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { + // Credit goes to jneem for figuring this out: + // https://github.com/jneem/teddy/blob/9ab5e899ad6ef6911aecd3cf1033f1abe6e1f66c/src/x86/teddy_simd.rs#L145-L184 + // + // TL;DR avx2's PALIGNR instruction is actually just two 128-bit + // PALIGNR instructions, which is not what we want, so we need to + // do some extra shuffling. + let v = _mm256_permute2x128_si256(other.vector, self.vector, 0x21); + let v = _mm256_alignr_epi8(self.vector, v, 14); + u8x32 { vector: v } + } + } + + #[inline] + pub fn alignr_15(self, other: u8x32) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { + // Credit goes to jneem for figuring this out: + // https://github.com/jneem/teddy/blob/9ab5e899ad6ef6911aecd3cf1033f1abe6e1f66c/src/x86/teddy_simd.rs#L145-L184 + // + // TL;DR avx2's PALIGNR instruction is actually just two 128-bit + // PALIGNR instructions, which is not what we want, so we need to + // do some extra shuffling. + let v = _mm256_permute2x128_si256(other.vector, self.vector, 0x21); + let v = _mm256_alignr_epi8(self.vector, v, 15); + u8x32 { vector: v } + } + } + + #[inline] + pub fn bit_shift_right_4(self) -> u8x32 { + // Safe because we know AVX2 is enabled. + unsafe { + u8x32 { vector: _mm256_srli_epi16(self.vector, 4) } + } + } +} + +impl fmt::Debug for u8x32 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Safe because `bytes` is always accessible. + unsafe { self.bytes.fmt(f) } + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/vector/mod.rs cargo-0.26.0/vendor/regex-0.2.10/src/vector/mod.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/vector/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/vector/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,4 @@ +#[cfg(target_arch = "x86_64")] +pub mod avx2; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +pub mod ssse3; diff -Nru cargo-0.25.0/vendor/regex-0.2.10/src/vector/ssse3.rs cargo-0.26.0/vendor/regex-0.2.10/src/vector/ssse3.rs --- cargo-0.25.0/vendor/regex-0.2.10/src/vector/ssse3.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/src/vector/ssse3.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,200 @@ +#![allow(dead_code)] + +use std::arch::x86_64::*; +use std::fmt; + +/// A builder for SSSE3 empowered vectors. +/// +/// This builder represents a receipt that the SSSE3 target feature is enabled +/// on the currently running CPU. Namely, the only way to get a value of this +/// type is if the SSSE3 feature is enabled. +/// +/// This type can then be used to build vector types that use SSSE3 features +/// safely. +#[derive(Clone, Copy, Debug)] +pub struct SSSE3VectorBuilder(()); + +impl SSSE3VectorBuilder { + /// Create a new SSSE3 vector builder. + /// + /// If the SSSE3 feature is not enabled for the current target, then + /// return `None`. + pub fn new() -> Option<SSSE3VectorBuilder> { + if is_x86_feature_detected!("ssse3") { + Some(SSSE3VectorBuilder(())) + } else { + None + } + } + + /// Create a new u8x16 SSSE3 vector where all of the bytes are set to + /// the given value. + #[inline] + pub fn u8x16_splat(self, n: u8) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { u8x16::splat(n) } + } + + /// Load 16 bytes from the given slice, with bounds checks. + #[inline] + pub fn u8x16_load_unaligned(self, slice: &[u8]) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { u8x16::load_unaligned(slice) } + } + + /// Load 16 bytes from the given slice, without bounds checks. + #[inline] + pub unsafe fn u8x16_load_unchecked_unaligned(self, slice: &[u8]) -> u8x16 { + // Safe because we know SSSE3 is enabled, but still unsafe + // because we aren't doing bounds checks. + u8x16::load_unchecked_unaligned(slice) + } + + /// Load 16 bytes from the given slice, with bound and alignment checks. + #[inline] + pub fn u8x16_load(self, slice: &[u8]) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { u8x16::load(slice) } + } + + /// Load 16 bytes from the given slice, without bound or alignment checks. + #[inline] + pub unsafe fn u8x16_load_unchecked(self, slice: &[u8]) -> u8x16 { + // Safe because we know SSSE3 is enabled, but still unsafe + // because we aren't doing bounds checks. + u8x16::load_unchecked(slice) + } +} + +// We define our union with a macro so that our code continues to compile on +// Rust 1.12. +macro_rules! defunion { + () => { + /// A u8x16 is a 128-bit vector with 16 single-byte lanes. + /// + /// It provides a safe API that uses only SSE2 or SSSE3 instructions. + /// The only way for callers to construct a value of this type is + /// through the SSSE3VectorBuilder type, and the only way to get a + /// SSSE3VectorBuilder is if the `ssse3` target feature is enabled. + /// + /// Note that generally speaking, all uses of this type should get + /// inlined, otherwise you probably have a performance bug. + #[derive(Clone, Copy)] + #[allow(non_camel_case_types)] + pub union u8x16 { + vector: __m128i, + bytes: [u8; 16], + } + } +} + +defunion!(); + +impl u8x16 { + #[inline] + unsafe fn splat(n: u8) -> u8x16 { + u8x16 { vector: _mm_set1_epi8(n as i8) } + } + + #[inline] + unsafe fn load_unaligned(slice: &[u8]) -> u8x16 { + assert!(slice.len() >= 16); + u8x16::load_unchecked(slice) + } + + #[inline] + unsafe fn load_unchecked_unaligned(slice: &[u8]) -> u8x16 { + let v = _mm_loadu_si128(slice.as_ptr() as *const u8 as *const __m128i); + u8x16 { vector: v } + } + + #[inline] + unsafe fn load(slice: &[u8]) -> u8x16 { + assert!(slice.len() >= 16); + assert!(slice.as_ptr() as usize % 16 == 0); + u8x16::load_unchecked(slice) + } + + #[inline] + unsafe fn load_unchecked(slice: &[u8]) -> u8x16 { + let v = _mm_load_si128(slice.as_ptr() as *const u8 as *const __m128i); + u8x16 { vector: v } + } + + #[inline] + pub fn extract(self, i: usize) -> u8 { + // Safe because `bytes` is always accessible. + unsafe { self.bytes[i] } + } + + #[inline] + pub fn replace(&mut self, i: usize, byte: u8) { + // Safe because `bytes` is always accessible. + unsafe { self.bytes[i] = byte; } + } + + #[inline] + pub fn shuffle(self, indices: u8x16) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { + u8x16 { vector: _mm_shuffle_epi8(self.vector, indices.vector) } + } + } + + #[inline] + pub fn ne(self, other: u8x16) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { + let boolv = _mm_cmpeq_epi8(self.vector, other.vector); + let ones = _mm_set1_epi8(0xFF as u8 as i8); + u8x16 { vector: _mm_andnot_si128(boolv, ones) } + } + } + + #[inline] + pub fn and(self, other: u8x16) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { + u8x16 { vector: _mm_and_si128(self.vector, other.vector) } + } + } + + #[inline] + pub fn movemask(self) -> u32 { + // Safe because we know SSSE3 is enabled. + unsafe { + _mm_movemask_epi8(self.vector) as u32 + } + } + + #[inline] + pub fn alignr_14(self, other: u8x16) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { + u8x16 { vector: _mm_alignr_epi8(self.vector, other.vector, 14) } + } + } + + #[inline] + pub fn alignr_15(self, other: u8x16) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { + u8x16 { vector: _mm_alignr_epi8(self.vector, other.vector, 15) } + } + } + + #[inline] + pub fn bit_shift_right_4(self) -> u8x16 { + // Safe because we know SSSE3 is enabled. + unsafe { + u8x16 { vector: _mm_srli_epi16(self.vector, 4) } + } + } +} + +impl fmt::Debug for u8x16 { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Safe because `bytes` is always accessible. + unsafe { self.bytes.fmt(f) } + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/api.rs cargo-0.26.0/vendor/regex-0.2.10/tests/api.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/api.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/api.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,182 @@ +#[test] +fn empty_regex_empty_match() { + let re = regex!(""); + assert_eq!(vec![(0, 0)], findall!(re, "")); +} + +#[test] +fn empty_regex_nonempty_match() { + let re = regex!(""); + assert_eq!(vec![(0, 0), (1, 1), (2, 2), (3, 3)], findall!(re, "abc")); +} + +#[test] +fn one_zero_length_match() { + let re = regex!(r"\d*"); + assert_eq!(vec![(0, 0), (1, 2), (3, 4)], findall!(re, "a1b2")); +} + +#[test] +fn many_zero_length_match() { + let re = regex!(r"\d*"); + assert_eq!(vec![(0, 0), (1, 2), (3, 3), (4, 4), (5, 6)], + findall!(re, "a1bbb2")); +} + +#[test] +fn many_sequential_zero_length_match() { + let re = regex!(r"\d?"); + assert_eq!(vec![(0, 0), (1, 2), (2, 3), (4, 5), (6, 6)], + findall!(re, "a12b3c")); +} + +#[test] +fn quoted_bracket_set() { + let re = regex!(r"([\x{5b}\x{5d}])"); + assert_eq!(vec![(0, 1), (1, 2)], findall!(re, "[]")); + let re = regex!(r"([\[\]])"); + assert_eq!(vec![(0, 1), (1, 2)], findall!(re, "[]")); +} + +#[test] +fn first_range_starts_with_left_bracket() { + let re = regex!(r"([\[-z])"); + assert_eq!(vec![(0, 1), (1, 2)], findall!(re, "[]")); +} + +#[test] +fn range_ends_with_escape() { + let re = regex!(r"([\[-\x{5d}])"); + assert_eq!(vec![(0, 1), (1, 2)], findall!(re, "[]")); +} + +#[test] +fn empty_match_find_iter() { + let re = regex!(r".*?"); + assert_eq!(vec![(0, 0), (1, 1), (2, 2), (3, 3)], findall!(re, "abc")); +} + +#[test] +fn empty_match_captures_iter() { + let re = regex!(r".*?"); + let ms: Vec<_> = re.captures_iter(text!("abc")) + .map(|c| c.get(0).unwrap()) + .map(|m| (m.start(), m.end())) + .collect(); + assert_eq!(ms, vec![(0, 0), (1, 1), (2, 2), (3, 3)]); +} + +#[test] +fn capture_names() { + let re = regex!(r"(.)(?P<a>.)"); + assert_eq!(3, re.captures_len()); + assert_eq!((3, Some(3)), re.capture_names().size_hint()); + assert_eq!(vec![None, None, Some("a")], + re.capture_names().collect::<Vec<_>>()); +} + +#[test] +fn regex_string() { + assert_eq!(r"[a-zA-Z0-9]+", regex!(r"[a-zA-Z0-9]+").as_str()); + assert_eq!(r"[a-zA-Z0-9]+", &format!("{}", regex!(r"[a-zA-Z0-9]+"))); + assert_eq!(r"[a-zA-Z0-9]+", &format!("{:?}", regex!(r"[a-zA-Z0-9]+"))); +} + +#[test] +fn capture_index() { + let re = regex!(r"^(?P<name>.+)$"); + let cap = re.captures(t!("abc")).unwrap(); + assert_eq!(&cap[0], t!("abc")); + assert_eq!(&cap[1], t!("abc")); + assert_eq!(&cap["name"], t!("abc")); +} + +#[test] +#[should_panic] +#[cfg_attr(all(target_env = "msvc", target_pointer_width = "32"), ignore)] +fn capture_index_panic_usize() { + let re = regex!(r"^(?P<name>.+)$"); + let cap = re.captures(t!("abc")).unwrap(); + let _ = cap[2]; +} + +#[test] +#[should_panic] +#[cfg_attr(all(target_env = "msvc", target_pointer_width = "32"), ignore)] +fn capture_index_panic_name() { + let re = regex!(r"^(?P<name>.+)$"); + let cap = re.captures(t!("abc")).unwrap(); + let _ = cap["bad name"]; +} + +#[test] +fn capture_index_lifetime() { + // This is a test of whether the types on `caps["..."]` are general + // enough. If not, this will fail to typecheck. + fn inner(s: &str) -> usize { + let re = regex!(r"(?P<number>\d+)"); + let caps = re.captures(t!(s)).unwrap(); + caps["number"].len() + } + assert_eq!(3, inner("123")); +} + +#[test] +fn capture_misc() { + let re = regex!(r"(.)(?P<a>a)?(.)(?P<b>.)"); + let cap = re.captures(t!("abc")).unwrap(); + + assert_eq!(5, cap.len()); + + assert_eq!((0, 3), { let m = cap.get(0).unwrap(); (m.start(), m.end()) }); + assert_eq!(None, cap.get(2)); + assert_eq!((2, 3), { let m = cap.get(4).unwrap(); (m.start(), m.end()) }); + + assert_eq!(t!("abc"), match_text!(cap.get(0).unwrap())); + assert_eq!(None, cap.get(2)); + assert_eq!(t!("c"), match_text!(cap.get(4).unwrap())); + + assert_eq!(None, cap.name("a")); + assert_eq!(t!("c"), match_text!(cap.name("b").unwrap())); +} + +#[test] +fn sub_capture_matches() { + let re = regex!(r"([a-z])(([a-z])|([0-9]))"); + let cap = re.captures(t!("a5")).unwrap(); + let subs: Vec<_> = cap.iter().collect(); + + assert_eq!(5, subs.len()); + assert!(subs[0].is_some()); + assert!(subs[1].is_some()); + assert!(subs[2].is_some()); + assert!(subs[3].is_none()); + assert!(subs[4].is_some()); + + assert_eq!(t!("a5"), match_text!(subs[0].unwrap())); + assert_eq!(t!("a"), match_text!(subs[1].unwrap())); + assert_eq!(t!("5"), match_text!(subs[2].unwrap())); + assert_eq!(t!("5"), match_text!(subs[4].unwrap())); +} + +expand!(expand1, r"(?P<foo>\w+)", "abc", "$foo", "abc"); +expand!(expand2, r"(?P<foo>\w+)", "abc", "$0", "abc"); +expand!(expand3, r"(?P<foo>\w+)", "abc", "$1", "abc"); +expand!(expand4, r"(?P<foo>\w+)", "abc", "$$1", "$1"); +expand!(expand5, r"(?P<foo>\w+)", "abc", "$$foo", "$foo"); +expand!(expand6, r"(?P<a>\w+)\s+(?P<b>\d+)", + "abc 123", "$b$a", "123abc"); +expand!(expand7, r"(?P<a>\w+)\s+(?P<b>\d+)", + "abc 123", "z$bz$az", "z"); +expand!(expand8, r"(?P<a>\w+)\s+(?P<b>\d+)", + "abc 123", ".$b.$a.", ".123.abc."); +expand!(expand9, r"(?P<a>\w+)\s+(?P<b>\d+)", + "abc 123", " $b $a ", " 123 abc "); +expand!(expand10, r"(?P<a>\w+)\s+(?P<b>\d+)", + "abc 123", "$bz$az", ""); + +split!(split1, r"\s+", "a b\nc\td\n\t e", + &[t!("a"), t!("b"), t!("c"), t!("d"), t!("e")]); +split!(split2, r"\b", "a b c", + &[t!(""), t!("a"), t!(" "), t!("b"), t!(" "), t!("c")]); +split!(split3, r"a$", "a", &[t!("")]); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/api_str.rs cargo-0.26.0/vendor/regex-0.2.10/tests/api_str.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/api_str.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/api_str.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,31 @@ +// These tests don't really make sense with the bytes API, so we only test them +// on the Unicode API. + +#[test] +fn empty_match_unicode_find_iter() { + // Tests that we still yield byte ranges at valid UTF-8 sequence boundaries + // even when we're susceptible to empty width matches. + let re = regex!(r".*?"); + assert_eq!(vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)], + findall!(re, "Ⅰ1Ⅱ2")); +} + +#[test] +fn empty_match_unicode_captures_iter() { + // Same as empty_match_unicode_find_iter, but tests capture iteration. + let re = regex!(r".*?"); + let ms: Vec<_> = re.captures_iter(text!("Ⅰ1Ⅱ2")) + .map(|c| c.get(0).unwrap()) + .map(|m| (m.start(), m.end())) + .collect(); + assert_eq!(vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)], ms); +} + +#[test] +fn match_as_str() { + let re = regex!(r"fo+"); + let caps = re.captures("barfoobar").unwrap(); + assert_eq!(caps.get(0).map(|m| m.as_str()), Some("foo")); + assert_eq!(caps.get(0).map(From::from), Some("foo")); + assert_eq!(caps.get(0).map(Into::into), Some("foo")); +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/bytes.rs cargo-0.26.0/vendor/regex-0.2.10/tests/bytes.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/bytes.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/bytes.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,62 @@ +// These are tests specifically crafted for regexes that can match arbitrary +// bytes. + +// A silly wrapper to make it possible to write and match raw bytes. +struct R<'a>(&'a [u8]); +impl<'a> R<'a> { fn as_bytes(&self) -> &'a [u8] { self.0 } } + +mat!(word_boundary, r"(?-u) \b", " δ", None); +mat!(word_boundary_unicode, r" \b", " δ", Some((0, 1))); +mat!(word_not_boundary, r"(?-u) \B", " δ", Some((0, 1))); +mat!(word_not_boundary_unicode, r" \B", " δ", None); + +mat!(perl_w_ascii, r"(?-u)\w+", "aδ", Some((0, 1))); +mat!(perl_w_unicode, r"\w+", "aδ", Some((0, 3))); +mat!(perl_d_ascii, r"(?-u)\d+", "1२३9", Some((0, 1))); +mat!(perl_d_unicode, r"\d+", "1२३9", Some((0, 8))); +mat!(perl_s_ascii, r"(?-u)\s+", " \u{1680}", Some((0, 1))); +mat!(perl_s_unicode, r"\s+", " \u{1680}", Some((0, 4))); + +// The first `(.+)` matches two Unicode codepoints, but can't match the 5th +// byte, which isn't valid UTF-8. The second (byte based) `(.+)` takes over and +// matches. +mat!(mixed1, r"(.+)(?-u)(.+)", R(b"\xCE\x93\xCE\x94\xFF"), + Some((0, 5)), Some((0, 4)), Some((4, 5))); + +mat!(case_ascii_one, r"(?i-u)a", "A", Some((0, 1))); +mat!(case_ascii_class, r"(?i-u)[a-z]+", "AaAaA", Some((0, 5))); +mat!(case_unicode, r"(?i)[a-z]+", "aA\u{212A}aA", Some((0, 7))); +mat!(case_not_unicode, r"(?i-u)[a-z]+", "aA\u{212A}aA", Some((0, 2))); + +mat!(negate_unicode, r"[^a]", "δ", Some((0, 2))); +mat!(negate_not_unicode, r"(?-u)[^a]", "δ", Some((0, 1))); + +// This doesn't match in a normal Unicode regex because the implicit preceding +// `.*?` is Unicode aware. +mat!(dotstar_prefix_not_unicode1, r"(?-u)a", R(b"\xFFa"), Some((1, 2))); +mat!(dotstar_prefix_not_unicode2, r"a", R(b"\xFFa"), Some((1, 2))); + +// Have fun with null bytes. +mat!(null_bytes, r"(?-u)(?P<cstr>[^\x00]+)\x00", + R(b"foo\x00"), Some((0, 4)), Some((0, 3))); + +// Test that lookahead operators work properly in the face of invalid UTF-8. +// See: https://github.com/rust-lang/regex/issues/277 +matiter!(invalidutf8_anchor1, + r"(?-u)\xcc?^", + R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), + (0, 0)); +matiter!(invalidutf8_anchor2, + r"(?-u)^\xf7|4\xff\d\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a##########[] d\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a##########\[] #####\x80\S7|$", + R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), + (22, 22)); +matiter!(invalidutf8_anchor3, + r"(?-u)^|ddp\xff\xffdddddlQd@\x80", + R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), + (0, 0)); + +// See https://github.com/rust-lang/regex/issues/303 +#[test] +fn negated_full_byte_range() { + assert!(::regex::bytes::Regex::new(r#"(?-u)[^\x00-\xff]"#).is_err()); +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/crazy.rs cargo-0.26.0/vendor/regex-0.2.10/tests/crazy.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/crazy.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/crazy.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,401 @@ +mat!(ascii_literal, r"a", "a", Some((0, 1))); + +// Some crazy expressions from regular-expressions.info. +mat!(match_ranges, + r"\b(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b", + "num: 255", Some((5, 8))); +mat!(match_ranges_not, + r"\b(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b", + "num: 256", None); +mat!(match_float1, r"[-+]?[0-9]*\.?[0-9]+", "0.1", Some((0, 3))); +mat!(match_float2, r"[-+]?[0-9]*\.?[0-9]+", "0.1.2", Some((0, 3))); +mat!(match_float3, r"[-+]?[0-9]*\.?[0-9]+", "a1.2", Some((1, 4))); +mat!(match_float4, r"^[-+]?[0-9]*\.?[0-9]+$", "1.a", None); +mat!(match_email, r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", + "mine is jam.slam@gmail.com ", Some((8, 26))); +mat!(match_email_not, r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", + "mine is jam.slam@gmail ", None); +mat!(match_email_big, r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", + "mine is jam.slam@gmail.com ", Some((8, 26))); +mat!(match_date1, + r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", + "1900-01-01", Some((0, 10))); +mat!(match_date2, + r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", + "1900-00-01", None); +mat!(match_date3, + r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", + "1900-13-01", None); + +// Do some crazy dancing with the start/end assertions. +matiter!(match_start_end_empty, r"^$", "", (0, 0)); +matiter!(match_start_end_empty_many_1, r"^$^$^$", "", (0, 0)); +matiter!(match_start_end_empty_many_2, r"^^^$$$", "", (0, 0)); +matiter!(match_start_end_empty_rev, r"$^", "", (0, 0)); +matiter!(match_start_end_empty_rep, r"(?:^$)*", "a\nb\nc", + (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); +matiter!(match_start_end_empty_rep_rev, r"(?:$^)*", "a\nb\nc", + (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); + +// Test negated character classes. +mat!(negclass_letters, r"[^ac]", "acx", Some((2, 3))); +mat!(negclass_letter_comma, r"[^a,]", "a,x", Some((2, 3))); +mat!(negclass_letter_space, r"[^a\s]", "a x", Some((2, 3))); +mat!(negclass_comma, r"[^,]", ",,x", Some((2, 3))); +mat!(negclass_space, r"[^\s]", " a", Some((1, 2))); +mat!(negclass_space_comma, r"[^,\s]", ", a", Some((2, 3))); +mat!(negclass_comma_space, r"[^\s,]", " ,a", Some((2, 3))); +mat!(negclass_ascii, r"[^[:alpha:]Z]", "A1", Some((1, 2))); + +// Test that repeated empty expressions don't loop forever. +mat!(lazy_many_many, r"((?:.*)*?)=", "a=b", Some((0, 2))); +mat!(lazy_many_optional, r"((?:.?)*?)=", "a=b", Some((0, 2))); +mat!(lazy_one_many_many, r"((?:.*)+?)=", "a=b", Some((0, 2))); +mat!(lazy_one_many_optional, r"((?:.?)+?)=", "a=b", Some((0, 2))); +mat!(lazy_range_min_many, r"((?:.*){1,}?)=", "a=b", Some((0, 2))); +mat!(lazy_range_many, r"((?:.*){1,2}?)=", "a=b", Some((0, 2))); +mat!(greedy_many_many, r"((?:.*)*)=", "a=b", Some((0, 2))); +mat!(greedy_many_optional, r"((?:.?)*)=", "a=b", Some((0, 2))); +mat!(greedy_one_many_many, r"((?:.*)+)=", "a=b", Some((0, 2))); +mat!(greedy_one_many_optional, r"((?:.?)+)=", "a=b", Some((0, 2))); +mat!(greedy_range_min_many, r"((?:.*){1,})=", "a=b", Some((0, 2))); +mat!(greedy_range_many, r"((?:.*){1,2})=", "a=b", Some((0, 2))); + +// Test that we handle various flavors of empty expressions. +matiter!(match_empty1, r"", "", (0, 0)); +matiter!(match_empty2, r"", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty3, r"()", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty4, r"()*", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty5, r"()+", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty6, r"()?", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty7, r"()()", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty8, r"()+|z", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty9, r"z|()+", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty10, r"()+|b", "abc", (0, 0), (1, 1), (2, 2), (3, 3)); +matiter!(match_empty11, r"b|()+", "abc", (0, 0), (1, 2), (3, 3)); + +// Test that the DFA can handle pathological cases. +// (This should result in the DFA's cache being flushed too frequently, which +// should cause it to quit and fall back to the NFA algorithm.) +#[test] +fn dfa_handles_pathological_case() { + fn ones_and_zeroes(count: usize) -> String { + use rand::{Rng, thread_rng}; + + let mut rng = thread_rng(); + let mut s = String::new(); + for _ in 0..count { + if rng.gen() { + s.push('1'); + } else { + s.push('0'); + } + } + s + } + + let re = regex!(r"[01]*1[01]{20}$"); + let text = { + let mut pieces = ones_and_zeroes(100_000); + pieces.push('1'); + pieces.push_str(&ones_and_zeroes(20)); + pieces + }; + assert!(re.is_match(text!(&*text))); +} + +#[test] +fn nest_limit_makes_it_parse() { + use regex::RegexBuilder; + + RegexBuilder::new( + r#" + 2(?: + [45]\d{3}| + 7(?: + 1[0-267]| + 2[0-289]| + 3[0-29]| + 4[01]| + 5[1-3]| + 6[013]| + 7[0178]| + 91 + )| + 8(?: + 0[125]| + [139][1-6]| + 2[0157-9]| + 41| + 6[1-35]| + 7[1-5]| + 8[1-8]| + 90 + )| + 9(?: + 0[0-2]| + 1[0-4]| + 2[568]| + 3[3-6]| + 5[5-7]| + 6[0167]| + 7[15]| + 8[0146-9] + ) + )\d{4}| + 3(?: + 12?[5-7]\d{2}| + 0(?: + 2(?: + [025-79]\d| + [348]\d{1,2} + )| + 3(?: + [2-4]\d| + [56]\d? + ) + )| + 2(?: + 1\d{2}| + 2(?: + [12]\d| + [35]\d{1,2}| + 4\d? + ) + )| + 3(?: + 1\d{2}| + 2(?: + [2356]\d| + 4\d{1,2} + ) + )| + 4(?: + 1\d{2}| + 2(?: + 2\d{1,2}| + [47]| + 5\d{2} + ) + )| + 5(?: + 1\d{2}| + 29 + )| + [67]1\d{2}| + 8(?: + 1\d{2}| + 2(?: + 2\d{2}| + 3| + 4\d + ) + ) + )\d{3}| + 4(?: + 0(?: + 2(?: + [09]\d| + 7 + )| + 33\d{2} + )| + 1\d{3}| + 2(?: + 1\d{2}| + 2(?: + [25]\d?| + [348]\d| + [67]\d{1,2} + ) + )| + 3(?: + 1\d{2}(?: + \d{2} + )?| + 2(?: + [045]\d| + [236-9]\d{1,2} + )| + 32\d{2} + )| + 4(?: + [18]\d{2}| + 2(?: + [2-46]\d{2}| + 3 + )| + 5[25]\d{2} + )| + 5(?: + 1\d{2}| + 2(?: + 3\d| + 5 + ) + )| + 6(?: + [18]\d{2}| + 2(?: + 3(?: + \d{2} + )?| + [46]\d{1,2}| + 5\d{2}| + 7\d + )| + 5(?: + 3\d?| + 4\d| + [57]\d{1,2}| + 6\d{2}| + 8 + ) + )| + 71\d{2}| + 8(?: + [18]\d{2}| + 23\d{2}| + 54\d{2} + )| + 9(?: + [18]\d{2}| + 2[2-5]\d{2}| + 53\d{1,2} + ) + )\d{3}| + 5(?: + 02[03489]\d{2}| + 1\d{2}| + 2(?: + 1\d{2}| + 2(?: + 2(?: + \d{2} + )?| + [457]\d{2} + ) + )| + 3(?: + 1\d{2}| + 2(?: + [37](?: + \d{2} + )?| + [569]\d{2} + ) + )| + 4(?: + 1\d{2}| + 2[46]\d{2} + )| + 5(?: + 1\d{2}| + 26\d{1,2} + )| + 6(?: + [18]\d{2}| + 2| + 53\d{2} + )| + 7(?: + 1| + 24 + )\d{2}| + 8(?: + 1| + 26 + )\d{2}| + 91\d{2} + )\d{3}| + 6(?: + 0(?: + 1\d{2}| + 2(?: + 3\d{2}| + 4\d{1,2} + ) + )| + 2(?: + 2[2-5]\d{2}| + 5(?: + [3-5]\d{2}| + 7 + )| + 8\d{2} + )| + 3(?: + 1| + 2[3478] + )\d{2}| + 4(?: + 1| + 2[34] + )\d{2}| + 5(?: + 1| + 2[47] + )\d{2}| + 6(?: + [18]\d{2}| + 6(?: + 2(?: + 2\d| + [34]\d{2} + )| + 5(?: + [24]\d{2}| + 3\d| + 5\d{1,2} + ) + ) + )| + 72[2-5]\d{2}| + 8(?: + 1\d{2}| + 2[2-5]\d{2} + )| + 9(?: + 1\d{2}| + 2[2-6]\d{2} + ) + )\d{3}| + 7(?: + (?: + 02| + [3-589]1| + 6[12]| + 72[24] + )\d{2}| + 21\d{3}| + 32 + )\d{3}| + 8(?: + (?: + 4[12]| + [5-7]2| + 1\d? + )| + (?: + 0| + 3[12]| + [5-7]1| + 217 + )\d + )\d{4}| + 9(?: + [35]1| + (?: + [024]2| + 81 + )\d| + (?: + 1| + [24]1 + )\d{2} + )\d{3} + "# + ) + .build() + .unwrap(); +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/flags.rs cargo-0.26.0/vendor/regex-0.2.10/tests/flags.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/flags.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/flags.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,11 @@ +mat!(match_flag_case, "(?i)abc", "ABC", Some((0, 3))); +mat!(match_flag_weird_case, "(?i)a(?-i)bc", "Abc", Some((0, 3))); +mat!(match_flag_weird_case_not, "(?i)a(?-i)bc", "ABC", None); +mat!(match_flag_case_dotnl, "(?is)a.", "A\n", Some((0, 2))); +mat!(match_flag_case_dotnl_toggle, "(?is)a.(?-is)a.", "A\nab", Some((0, 4))); +mat!(match_flag_case_dotnl_toggle_not, "(?is)a.(?-is)a.", "A\na\n", None); +mat!(match_flag_case_dotnl_toggle_ok, "(?is)a.(?-is:a.)?", "A\na\n", Some((0, 2))); +mat!(match_flag_multi, "(?m)(?:^\\d+$\n?)+", "123\n456\n789", Some((0, 11))); +mat!(match_flag_ungreedy, "(?U)a+", "aa", Some((0, 1))); +mat!(match_flag_ungreedy_greedy, "(?U)a+?", "aa", Some((0, 2))); +mat!(match_flag_ungreedy_noop, "(?U)(?-U)a+", "aa", Some((0, 2))); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/fowler.rs cargo-0.26.0/vendor/regex-0.2.10/tests/fowler.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/fowler.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/fowler.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,371 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// DO NOT EDIT. Automatically generated by 'scripts/regex-match-tests.py' +// on 2015-02-28 11:00:00.161706. + +// Tests from basic.dat +mat!(match_basic_3, r"abracadabra$", r"abracadabracadabra", Some((7, 18))); +mat!(match_basic_4, r"a...b", r"abababbb", Some((2, 7))); +mat!(match_basic_5, r"XXXXXX", r"..XXXXXX", Some((2, 8))); +mat!(match_basic_6, r"\)", r"()", Some((1, 2))); +mat!(match_basic_7, r"a]", r"a]a", Some((0, 2))); +mat!(match_basic_9, r"\}", r"}", Some((0, 1))); +mat!(match_basic_10, r"\]", r"]", Some((0, 1))); +mat!(match_basic_12, r"]", r"]", Some((0, 1))); +mat!(match_basic_15, r"^a", r"ax", Some((0, 1))); +mat!(match_basic_16, r"\^a", r"a^a", Some((1, 3))); +mat!(match_basic_17, r"a\^", r"a^", Some((0, 2))); +mat!(match_basic_18, r"a$", r"aa", Some((1, 2))); +mat!(match_basic_19, r"a\$", r"a$", Some((0, 2))); +mat!(match_basic_20, r"^$", r"", Some((0, 0))); +mat!(match_basic_21, r"$^", r"", Some((0, 0))); +mat!(match_basic_22, r"a($)", r"aa", Some((1, 2)), Some((2, 2))); +mat!(match_basic_23, r"a*(^a)", r"aa", Some((0, 1)), Some((0, 1))); +mat!(match_basic_24, r"(..)*(...)*", r"a", Some((0, 0))); +mat!(match_basic_25, r"(..)*(...)*", r"abcd", Some((0, 4)), Some((2, 4))); +mat!(match_basic_26, r"(ab|a)(bc|c)", r"abc", Some((0, 3)), Some((0, 2)), Some((2, 3))); +mat!(match_basic_27, r"(ab)c|abc", r"abc", Some((0, 3)), Some((0, 2))); +mat!(match_basic_28, r"a{0}b", r"ab", Some((1, 2))); +mat!(match_basic_29, r"(a*)(b?)(b+)b{3}", r"aaabbbbbbb", Some((0, 10)), Some((0, 3)), Some((3, 4)), Some((4, 7))); +mat!(match_basic_30, r"(a*)(b{0,1})(b{1,})b{3}", r"aaabbbbbbb", Some((0, 10)), Some((0, 3)), Some((3, 4)), Some((4, 7))); +mat!(match_basic_32, r"((a|a)|a)", r"a", Some((0, 1)), Some((0, 1)), Some((0, 1))); +mat!(match_basic_33, r"(a*)(a|aa)", r"aaaa", Some((0, 4)), Some((0, 3)), Some((3, 4))); +mat!(match_basic_34, r"a*(a.|aa)", r"aaaa", Some((0, 4)), Some((2, 4))); +mat!(match_basic_35, r"a(b)|c(d)|a(e)f", r"aef", Some((0, 3)), None, None, Some((1, 2))); +mat!(match_basic_36, r"(a|b)?.*", r"b", Some((0, 1)), Some((0, 1))); +mat!(match_basic_37, r"(a|b)c|a(b|c)", r"ac", Some((0, 2)), Some((0, 1))); +mat!(match_basic_38, r"(a|b)c|a(b|c)", r"ab", Some((0, 2)), None, Some((1, 2))); +mat!(match_basic_39, r"(a|b)*c|(a|ab)*c", r"abc", Some((0, 3)), Some((1, 2))); +mat!(match_basic_40, r"(a|b)*c|(a|ab)*c", r"xc", Some((1, 2))); +mat!(match_basic_41, r"(.a|.b).*|.*(.a|.b)", r"xa", Some((0, 2)), Some((0, 2))); +mat!(match_basic_42, r"a?(ab|ba)ab", r"abab", Some((0, 4)), Some((0, 2))); +mat!(match_basic_43, r"a?(ac{0}b|ba)ab", r"abab", Some((0, 4)), Some((0, 2))); +mat!(match_basic_44, r"ab|abab", r"abbabab", Some((0, 2))); +mat!(match_basic_45, r"aba|bab|bba", r"baaabbbaba", Some((5, 8))); +mat!(match_basic_46, r"aba|bab", r"baaabbbaba", Some((6, 9))); +mat!(match_basic_47, r"(aa|aaa)*|(a|aaaaa)", r"aa", Some((0, 2)), Some((0, 2))); +mat!(match_basic_48, r"(a.|.a.)*|(a|.a...)", r"aa", Some((0, 2)), Some((0, 2))); +mat!(match_basic_49, r"ab|a", r"xabc", Some((1, 3))); +mat!(match_basic_50, r"ab|a", r"xxabc", Some((2, 4))); +mat!(match_basic_51, r"(?i)(Ab|cD)*", r"aBcD", Some((0, 4)), Some((2, 4))); +mat!(match_basic_52, r"[^-]", r"--a", Some((2, 3))); +mat!(match_basic_53, r"[a-]*", r"--a", Some((0, 3))); +mat!(match_basic_54, r"[a-m-]*", r"--amoma--", Some((0, 4))); +mat!(match_basic_55, r":::1:::0:|:::1:1:0:", r":::0:::1:::1:::0:", Some((8, 17))); +mat!(match_basic_56, r":::1:::0:|:::1:1:1:", r":::0:::1:::1:::0:", Some((8, 17))); +mat!(match_basic_57, r"[[:upper:]]", r"A", Some((0, 1))); +mat!(match_basic_58, r"[[:lower:]]+", r"`az{", Some((1, 3))); +mat!(match_basic_59, r"[[:upper:]]+", r"@AZ[", Some((1, 3))); +mat!(match_basic_65, r" +", r" +", Some((0, 1))); +mat!(match_basic_66, r" +", r" +", Some((0, 1))); +mat!(match_basic_67, r"[^a]", r" +", Some((0, 1))); +mat!(match_basic_68, r" +a", r" +a", Some((0, 2))); +mat!(match_basic_69, r"(a)(b)(c)", r"abc", Some((0, 3)), Some((0, 1)), Some((1, 2)), Some((2, 3))); +mat!(match_basic_70, r"xxx", r"xxx", Some((0, 3))); +mat!(match_basic_71, r"(^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$)", r"feb 6,", Some((0, 6))); +mat!(match_basic_72, r"(^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$)", r"2/7", Some((0, 3))); +mat!(match_basic_73, r"(^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$)", r"feb 1,Feb 6", Some((5, 11))); +mat!(match_basic_74, r"((((((((((((((((((((((((((((((x))))))))))))))))))))))))))))))", r"x", Some((0, 1)), Some((0, 1)), Some((0, 1))); +mat!(match_basic_75, r"((((((((((((((((((((((((((((((x))))))))))))))))))))))))))))))*", r"xx", Some((0, 2)), Some((1, 2)), Some((1, 2))); +mat!(match_basic_76, r"a?(ab|ba)*", r"ababababababababababababababababababababababababababababababababababababababababa", Some((0, 81)), Some((79, 81))); +mat!(match_basic_77, r"abaa|abbaa|abbbaa|abbbbaa", r"ababbabbbabbbabbbbabbbbaa", Some((18, 25))); +mat!(match_basic_78, r"abaa|abbaa|abbbaa|abbbbaa", r"ababbabbbabbbabbbbabaa", Some((18, 22))); +mat!(match_basic_79, r"aaac|aabc|abac|abbc|baac|babc|bbac|bbbc", r"baaabbbabac", Some((7, 11))); +mat!(match_basic_80, r".*", r"", Some((0, 2))); +mat!(match_basic_81, r"aaaa|bbbb|cccc|ddddd|eeeeee|fffffff|gggg|hhhh|iiiii|jjjjj|kkkkk|llll", r"XaaaXbbbXcccXdddXeeeXfffXgggXhhhXiiiXjjjXkkkXlllXcbaXaaaa", Some((53, 57))); +mat!(match_basic_83, r"a*a*a*a*a*b", r"aaaaaaaaab", Some((0, 10))); +mat!(match_basic_84, r"^", r"", Some((0, 0))); +mat!(match_basic_85, r"$", r"", Some((0, 0))); +mat!(match_basic_86, r"^$", r"", Some((0, 0))); +mat!(match_basic_87, r"^a$", r"a", Some((0, 1))); +mat!(match_basic_88, r"abc", r"abc", Some((0, 3))); +mat!(match_basic_89, r"abc", r"xabcy", Some((1, 4))); +mat!(match_basic_90, r"abc", r"ababc", Some((2, 5))); +mat!(match_basic_91, r"ab*c", r"abc", Some((0, 3))); +mat!(match_basic_92, r"ab*bc", r"abc", Some((0, 3))); +mat!(match_basic_93, r"ab*bc", r"abbc", Some((0, 4))); +mat!(match_basic_94, r"ab*bc", r"abbbbc", Some((0, 6))); +mat!(match_basic_95, r"ab+bc", r"abbc", Some((0, 4))); +mat!(match_basic_96, r"ab+bc", r"abbbbc", Some((0, 6))); +mat!(match_basic_97, r"ab?bc", r"abbc", Some((0, 4))); +mat!(match_basic_98, r"ab?bc", r"abc", Some((0, 3))); +mat!(match_basic_99, r"ab?c", r"abc", Some((0, 3))); +mat!(match_basic_100, r"^abc$", r"abc", Some((0, 3))); +mat!(match_basic_101, r"^abc", r"abcc", Some((0, 3))); +mat!(match_basic_102, r"abc$", r"aabc", Some((1, 4))); +mat!(match_basic_103, r"^", r"abc", Some((0, 0))); +mat!(match_basic_104, r"$", r"abc", Some((3, 3))); +mat!(match_basic_105, r"a.c", r"abc", Some((0, 3))); +mat!(match_basic_106, r"a.c", r"axc", Some((0, 3))); +mat!(match_basic_107, r"a.*c", r"axyzc", Some((0, 5))); +mat!(match_basic_108, r"a[bc]d", r"abd", Some((0, 3))); +mat!(match_basic_109, r"a[b-d]e", r"ace", Some((0, 3))); +mat!(match_basic_110, r"a[b-d]", r"aac", Some((1, 3))); +mat!(match_basic_111, r"a[-b]", r"a-", Some((0, 2))); +mat!(match_basic_112, r"a[b-]", r"a-", Some((0, 2))); +mat!(match_basic_113, r"a]", r"a]", Some((0, 2))); +mat!(match_basic_114, r"a[]]b", r"a]b", Some((0, 3))); +mat!(match_basic_115, r"a[^bc]d", r"aed", Some((0, 3))); +mat!(match_basic_116, r"a[^-b]c", r"adc", Some((0, 3))); +mat!(match_basic_117, r"a[^]b]c", r"adc", Some((0, 3))); +mat!(match_basic_118, r"ab|cd", r"abc", Some((0, 2))); +mat!(match_basic_119, r"ab|cd", r"abcd", Some((0, 2))); +mat!(match_basic_120, r"a\(b", r"a(b", Some((0, 3))); +mat!(match_basic_121, r"a\(*b", r"ab", Some((0, 2))); +mat!(match_basic_122, r"a\(*b", r"a((b", Some((0, 4))); +mat!(match_basic_123, r"((a))", r"abc", Some((0, 1)), Some((0, 1)), Some((0, 1))); +mat!(match_basic_124, r"(a)b(c)", r"abc", Some((0, 3)), Some((0, 1)), Some((2, 3))); +mat!(match_basic_125, r"a+b+c", r"aabbabc", Some((4, 7))); +mat!(match_basic_126, r"a*", r"aaa", Some((0, 3))); +mat!(match_basic_128, r"(a*)*", r"-", Some((0, 0)), None); +mat!(match_basic_129, r"(a*)+", r"-", Some((0, 0)), Some((0, 0))); +mat!(match_basic_131, r"(a*|b)*", r"-", Some((0, 0)), None); +mat!(match_basic_132, r"(a+|b)*", r"ab", Some((0, 2)), Some((1, 2))); +mat!(match_basic_133, r"(a+|b)+", r"ab", Some((0, 2)), Some((1, 2))); +mat!(match_basic_134, r"(a+|b)?", r"ab", Some((0, 1)), Some((0, 1))); +mat!(match_basic_135, r"[^ab]*", r"cde", Some((0, 3))); +mat!(match_basic_137, r"(^)*", r"-", Some((0, 0)), None); +mat!(match_basic_138, r"a*", r"", Some((0, 0))); +mat!(match_basic_139, r"([abc])*d", r"abbbcd", Some((0, 6)), Some((4, 5))); +mat!(match_basic_140, r"([abc])*bcd", r"abcd", Some((0, 4)), Some((0, 1))); +mat!(match_basic_141, r"a|b|c|d|e", r"e", Some((0, 1))); +mat!(match_basic_142, r"(a|b|c|d|e)f", r"ef", Some((0, 2)), Some((0, 1))); +mat!(match_basic_144, r"((a*|b))*", r"-", Some((0, 0)), None, None); +mat!(match_basic_145, r"abcd*efg", r"abcdefg", Some((0, 7))); +mat!(match_basic_146, r"ab*", r"xabyabbbz", Some((1, 3))); +mat!(match_basic_147, r"ab*", r"xayabbbz", Some((1, 2))); +mat!(match_basic_148, r"(ab|cd)e", r"abcde", Some((2, 5)), Some((2, 4))); +mat!(match_basic_149, r"[abhgefdc]ij", r"hij", Some((0, 3))); +mat!(match_basic_150, r"(a|b)c*d", r"abcd", Some((1, 4)), Some((1, 2))); +mat!(match_basic_151, r"(ab|ab*)bc", r"abc", Some((0, 3)), Some((0, 1))); +mat!(match_basic_152, r"a([bc]*)c*", r"abc", Some((0, 3)), Some((1, 3))); +mat!(match_basic_153, r"a([bc]*)(c*d)", r"abcd", Some((0, 4)), Some((1, 3)), Some((3, 4))); +mat!(match_basic_154, r"a([bc]+)(c*d)", r"abcd", Some((0, 4)), Some((1, 3)), Some((3, 4))); +mat!(match_basic_155, r"a([bc]*)(c+d)", r"abcd", Some((0, 4)), Some((1, 2)), Some((2, 4))); +mat!(match_basic_156, r"a[bcd]*dcdcde", r"adcdcde", Some((0, 7))); +mat!(match_basic_157, r"(ab|a)b*c", r"abc", Some((0, 3)), Some((0, 2))); +mat!(match_basic_158, r"((a)(b)c)(d)", r"abcd", Some((0, 4)), Some((0, 3)), Some((0, 1)), Some((1, 2)), Some((3, 4))); +mat!(match_basic_159, r"[A-Za-z_][A-Za-z0-9_]*", r"alpha", Some((0, 5))); +mat!(match_basic_160, r"^a(bc+|b[eh])g|.h$", r"abh", Some((1, 3))); +mat!(match_basic_161, r"(bc+d$|ef*g.|h?i(j|k))", r"effgz", Some((0, 5)), Some((0, 5))); +mat!(match_basic_162, r"(bc+d$|ef*g.|h?i(j|k))", r"ij", Some((0, 2)), Some((0, 2)), Some((1, 2))); +mat!(match_basic_163, r"(bc+d$|ef*g.|h?i(j|k))", r"reffgz", Some((1, 6)), Some((1, 6))); +mat!(match_basic_164, r"(((((((((a)))))))))", r"a", Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1))); +mat!(match_basic_165, r"multiple words", r"multiple words yeah", Some((0, 14))); +mat!(match_basic_166, r"(.*)c(.*)", r"abcde", Some((0, 5)), Some((0, 2)), Some((3, 5))); +mat!(match_basic_167, r"abcd", r"abcd", Some((0, 4))); +mat!(match_basic_168, r"a(bc)d", r"abcd", Some((0, 4)), Some((1, 3))); +mat!(match_basic_169, r"a[-]?c", r"ac", Some((0, 3))); +mat!(match_basic_170, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Qaddafi", Some((0, 15)), None, Some((10, 12))); +mat!(match_basic_171, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Mo'ammar Gadhafi", Some((0, 16)), None, Some((11, 13))); +mat!(match_basic_172, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Kaddafi", Some((0, 15)), None, Some((10, 12))); +mat!(match_basic_173, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Qadhafi", Some((0, 15)), None, Some((10, 12))); +mat!(match_basic_174, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Gadafi", Some((0, 14)), None, Some((10, 11))); +mat!(match_basic_175, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Mu'ammar Qadafi", Some((0, 15)), None, Some((11, 12))); +mat!(match_basic_176, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Moamar Gaddafi", Some((0, 14)), None, Some((9, 11))); +mat!(match_basic_177, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Mu'ammar Qadhdhafi", Some((0, 18)), None, Some((13, 15))); +mat!(match_basic_178, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Khaddafi", Some((0, 16)), None, Some((11, 13))); +mat!(match_basic_179, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Ghaddafy", Some((0, 16)), None, Some((11, 13))); +mat!(match_basic_180, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Ghadafi", Some((0, 15)), None, Some((11, 12))); +mat!(match_basic_181, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Ghaddafi", Some((0, 16)), None, Some((11, 13))); +mat!(match_basic_182, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muamar Kaddafi", Some((0, 14)), None, Some((9, 11))); +mat!(match_basic_183, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Quathafi", Some((0, 16)), None, Some((11, 13))); +mat!(match_basic_184, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Gheddafi", Some((0, 16)), None, Some((11, 13))); +mat!(match_basic_185, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Moammar Khadafy", Some((0, 15)), None, Some((11, 12))); +mat!(match_basic_186, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Moammar Qudhafi", Some((0, 15)), None, Some((10, 12))); +mat!(match_basic_187, r"a+(b|c)*d+", r"aabcdd", Some((0, 6)), Some((3, 4))); +mat!(match_basic_188, r"^.+$", r"vivi", Some((0, 4))); +mat!(match_basic_189, r"^(.+)$", r"vivi", Some((0, 4)), Some((0, 4))); +mat!(match_basic_190, r"^([^!.]+).att.com!(.+)$", r"gryphon.att.com!eby", Some((0, 19)), Some((0, 7)), Some((16, 19))); +mat!(match_basic_191, r"^([^!]+!)?([^!]+)$", r"bas", Some((0, 3)), None, Some((0, 3))); +mat!(match_basic_192, r"^([^!]+!)?([^!]+)$", r"bar!bas", Some((0, 7)), Some((0, 4)), Some((4, 7))); +mat!(match_basic_193, r"^([^!]+!)?([^!]+)$", r"foo!bas", Some((0, 7)), Some((0, 4)), Some((4, 7))); +mat!(match_basic_194, r"^.+!([^!]+!)([^!]+)$", r"foo!bar!bas", Some((0, 11)), Some((4, 8)), Some((8, 11))); +mat!(match_basic_195, r"((foo)|(bar))!bas", r"bar!bas", Some((0, 7)), Some((0, 3)), None, Some((0, 3))); +mat!(match_basic_196, r"((foo)|(bar))!bas", r"foo!bar!bas", Some((4, 11)), Some((4, 7)), None, Some((4, 7))); +mat!(match_basic_197, r"((foo)|(bar))!bas", r"foo!bas", Some((0, 7)), Some((0, 3)), Some((0, 3))); +mat!(match_basic_198, r"((foo)|bar)!bas", r"bar!bas", Some((0, 7)), Some((0, 3))); +mat!(match_basic_199, r"((foo)|bar)!bas", r"foo!bar!bas", Some((4, 11)), Some((4, 7))); +mat!(match_basic_200, r"((foo)|bar)!bas", r"foo!bas", Some((0, 7)), Some((0, 3)), Some((0, 3))); +mat!(match_basic_201, r"(foo|(bar))!bas", r"bar!bas", Some((0, 7)), Some((0, 3)), Some((0, 3))); +mat!(match_basic_202, r"(foo|(bar))!bas", r"foo!bar!bas", Some((4, 11)), Some((4, 7)), Some((4, 7))); +mat!(match_basic_203, r"(foo|(bar))!bas", r"foo!bas", Some((0, 7)), Some((0, 3))); +mat!(match_basic_204, r"(foo|bar)!bas", r"bar!bas", Some((0, 7)), Some((0, 3))); +mat!(match_basic_205, r"(foo|bar)!bas", r"foo!bar!bas", Some((4, 11)), Some((4, 7))); +mat!(match_basic_206, r"(foo|bar)!bas", r"foo!bas", Some((0, 7)), Some((0, 3))); +mat!(match_basic_207, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"foo!bar!bas", Some((0, 11)), Some((0, 11)), None, None, Some((4, 8)), Some((8, 11))); +mat!(match_basic_208, r"^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$", r"bas", Some((0, 3)), None, Some((0, 3))); +mat!(match_basic_209, r"^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$", r"bar!bas", Some((0, 7)), Some((0, 4)), Some((4, 7))); +mat!(match_basic_210, r"^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$", r"foo!bar!bas", Some((0, 11)), None, None, Some((4, 8)), Some((8, 11))); +mat!(match_basic_211, r"^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$", r"foo!bas", Some((0, 7)), Some((0, 4)), Some((4, 7))); +mat!(match_basic_212, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"bas", Some((0, 3)), Some((0, 3)), None, Some((0, 3))); +mat!(match_basic_213, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"bar!bas", Some((0, 7)), Some((0, 7)), Some((0, 4)), Some((4, 7))); +mat!(match_basic_214, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"foo!bar!bas", Some((0, 11)), Some((0, 11)), None, None, Some((4, 8)), Some((8, 11))); +mat!(match_basic_215, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"foo!bas", Some((0, 7)), Some((0, 7)), Some((0, 4)), Some((4, 7))); +mat!(match_basic_216, r".*(/XXX).*", r"/XXX", Some((0, 4)), Some((0, 4))); +mat!(match_basic_217, r".*(\\XXX).*", r"\XXX", Some((0, 4)), Some((0, 4))); +mat!(match_basic_218, r"\\XXX", r"\XXX", Some((0, 4))); +mat!(match_basic_219, r".*(/000).*", r"/000", Some((0, 4)), Some((0, 4))); +mat!(match_basic_220, r".*(\\000).*", r"\000", Some((0, 4)), Some((0, 4))); +mat!(match_basic_221, r"\\000", r"\000", Some((0, 4))); + +// Tests from nullsubexpr.dat +mat!(match_nullsubexpr_3, r"(a*)*", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_5, r"(a*)*", r"x", Some((0, 0)), None); +mat!(match_nullsubexpr_6, r"(a*)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_7, r"(a*)*", r"aaaaaax", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_8, r"(a*)+", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_9, r"(a*)+", r"x", Some((0, 0)), Some((0, 0))); +mat!(match_nullsubexpr_10, r"(a*)+", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_11, r"(a*)+", r"aaaaaax", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_12, r"(a+)*", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_13, r"(a+)*", r"x", Some((0, 0))); +mat!(match_nullsubexpr_14, r"(a+)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_15, r"(a+)*", r"aaaaaax", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_16, r"(a+)+", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_17, r"(a+)+", r"x", None); +mat!(match_nullsubexpr_18, r"(a+)+", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_19, r"(a+)+", r"aaaaaax", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_21, r"([a]*)*", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_23, r"([a]*)*", r"x", Some((0, 0)), None); +mat!(match_nullsubexpr_24, r"([a]*)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_25, r"([a]*)*", r"aaaaaax", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_26, r"([a]*)+", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_27, r"([a]*)+", r"x", Some((0, 0)), Some((0, 0))); +mat!(match_nullsubexpr_28, r"([a]*)+", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_29, r"([a]*)+", r"aaaaaax", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_30, r"([^b]*)*", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_32, r"([^b]*)*", r"b", Some((0, 0)), None); +mat!(match_nullsubexpr_33, r"([^b]*)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_34, r"([^b]*)*", r"aaaaaab", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_35, r"([ab]*)*", r"a", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_36, r"([ab]*)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_37, r"([ab]*)*", r"ababab", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_38, r"([ab]*)*", r"bababa", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_39, r"([ab]*)*", r"b", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_40, r"([ab]*)*", r"bbbbbb", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_41, r"([ab]*)*", r"aaaabcde", Some((0, 5)), Some((0, 5))); +mat!(match_nullsubexpr_42, r"([^a]*)*", r"b", Some((0, 1)), Some((0, 1))); +mat!(match_nullsubexpr_43, r"([^a]*)*", r"bbbbbb", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_45, r"([^a]*)*", r"aaaaaa", Some((0, 0)), None); +mat!(match_nullsubexpr_46, r"([^ab]*)*", r"ccccxx", Some((0, 6)), Some((0, 6))); +mat!(match_nullsubexpr_48, r"([^ab]*)*", r"ababab", Some((0, 0)), None); +mat!(match_nullsubexpr_50, r"((z)+|a)*", r"zabcde", Some((0, 2)), Some((1, 2))); +mat!(match_nullsubexpr_69, r"(a*)*(x)", r"x", Some((0, 1)), None, Some((0, 1))); +mat!(match_nullsubexpr_70, r"(a*)*(x)", r"ax", Some((0, 2)), Some((0, 1)), Some((1, 2))); +mat!(match_nullsubexpr_71, r"(a*)*(x)", r"axa", Some((0, 2)), Some((0, 1)), Some((1, 2))); +mat!(match_nullsubexpr_73, r"(a*)+(x)", r"x", Some((0, 1)), Some((0, 0)), Some((0, 1))); +mat!(match_nullsubexpr_74, r"(a*)+(x)", r"ax", Some((0, 2)), Some((0, 1)), Some((1, 2))); +mat!(match_nullsubexpr_75, r"(a*)+(x)", r"axa", Some((0, 2)), Some((0, 1)), Some((1, 2))); +mat!(match_nullsubexpr_77, r"(a*){2}(x)", r"x", Some((0, 1)), Some((0, 0)), Some((0, 1))); +mat!(match_nullsubexpr_78, r"(a*){2}(x)", r"ax", Some((0, 2)), Some((1, 1)), Some((1, 2))); +mat!(match_nullsubexpr_79, r"(a*){2}(x)", r"axa", Some((0, 2)), Some((1, 1)), Some((1, 2))); + +// Tests from repetition.dat +mat!(match_repetition_10, r"((..)|(.))", r"", None); +mat!(match_repetition_11, r"((..)|(.))((..)|(.))", r"", None); +mat!(match_repetition_12, r"((..)|(.))((..)|(.))((..)|(.))", r"", None); +mat!(match_repetition_14, r"((..)|(.)){1}", r"", None); +mat!(match_repetition_15, r"((..)|(.)){2}", r"", None); +mat!(match_repetition_16, r"((..)|(.)){3}", r"", None); +mat!(match_repetition_18, r"((..)|(.))*", r"", Some((0, 0))); +mat!(match_repetition_20, r"((..)|(.))", r"a", Some((0, 1)), Some((0, 1)), None, Some((0, 1))); +mat!(match_repetition_21, r"((..)|(.))((..)|(.))", r"a", None); +mat!(match_repetition_22, r"((..)|(.))((..)|(.))((..)|(.))", r"a", None); +mat!(match_repetition_24, r"((..)|(.)){1}", r"a", Some((0, 1)), Some((0, 1)), None, Some((0, 1))); +mat!(match_repetition_25, r"((..)|(.)){2}", r"a", None); +mat!(match_repetition_26, r"((..)|(.)){3}", r"a", None); +mat!(match_repetition_28, r"((..)|(.))*", r"a", Some((0, 1)), Some((0, 1)), None, Some((0, 1))); +mat!(match_repetition_30, r"((..)|(.))", r"aa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_31, r"((..)|(.))((..)|(.))", r"aa", Some((0, 2)), Some((0, 1)), None, Some((0, 1)), Some((1, 2)), None, Some((1, 2))); +mat!(match_repetition_32, r"((..)|(.))((..)|(.))((..)|(.))", r"aa", None); +mat!(match_repetition_34, r"((..)|(.)){1}", r"aa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_35, r"((..)|(.)){2}", r"aa", Some((0, 2)), Some((1, 2)), None, Some((1, 2))); +mat!(match_repetition_36, r"((..)|(.)){3}", r"aa", None); +mat!(match_repetition_38, r"((..)|(.))*", r"aa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_40, r"((..)|(.))", r"aaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_41, r"((..)|(.))((..)|(.))", r"aaa", Some((0, 3)), Some((0, 2)), Some((0, 2)), None, Some((2, 3)), None, Some((2, 3))); +mat!(match_repetition_42, r"((..)|(.))((..)|(.))((..)|(.))", r"aaa", Some((0, 3)), Some((0, 1)), None, Some((0, 1)), Some((1, 2)), None, Some((1, 2)), Some((2, 3)), None, Some((2, 3))); +mat!(match_repetition_44, r"((..)|(.)){1}", r"aaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_46, r"((..)|(.)){2}", r"aaa", Some((0, 3)), Some((2, 3)), Some((0, 2)), Some((2, 3))); +mat!(match_repetition_47, r"((..)|(.)){3}", r"aaa", Some((0, 3)), Some((2, 3)), None, Some((2, 3))); +mat!(match_repetition_50, r"((..)|(.))*", r"aaa", Some((0, 3)), Some((2, 3)), Some((0, 2)), Some((2, 3))); +mat!(match_repetition_52, r"((..)|(.))", r"aaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_53, r"((..)|(.))((..)|(.))", r"aaaa", Some((0, 4)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_54, r"((..)|(.))((..)|(.))((..)|(.))", r"aaaa", Some((0, 4)), Some((0, 2)), Some((0, 2)), None, Some((2, 3)), None, Some((2, 3)), Some((3, 4)), None, Some((3, 4))); +mat!(match_repetition_56, r"((..)|(.)){1}", r"aaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_57, r"((..)|(.)){2}", r"aaaa", Some((0, 4)), Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_59, r"((..)|(.)){3}", r"aaaa", Some((0, 4)), Some((3, 4)), Some((0, 2)), Some((3, 4))); +mat!(match_repetition_61, r"((..)|(.))*", r"aaaa", Some((0, 4)), Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_63, r"((..)|(.))", r"aaaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_64, r"((..)|(.))((..)|(.))", r"aaaaa", Some((0, 4)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_65, r"((..)|(.))((..)|(.))((..)|(.))", r"aaaaa", Some((0, 5)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None, Some((4, 5)), None, Some((4, 5))); +mat!(match_repetition_67, r"((..)|(.)){1}", r"aaaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_68, r"((..)|(.)){2}", r"aaaaa", Some((0, 4)), Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_70, r"((..)|(.)){3}", r"aaaaa", Some((0, 5)), Some((4, 5)), Some((2, 4)), Some((4, 5))); +mat!(match_repetition_73, r"((..)|(.))*", r"aaaaa", Some((0, 5)), Some((4, 5)), Some((2, 4)), Some((4, 5))); +mat!(match_repetition_75, r"((..)|(.))", r"aaaaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_76, r"((..)|(.))((..)|(.))", r"aaaaaa", Some((0, 4)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_77, r"((..)|(.))((..)|(.))((..)|(.))", r"aaaaaa", Some((0, 6)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None, Some((4, 6)), Some((4, 6)), None); +mat!(match_repetition_79, r"((..)|(.)){1}", r"aaaaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); +mat!(match_repetition_80, r"((..)|(.)){2}", r"aaaaaa", Some((0, 4)), Some((2, 4)), Some((2, 4)), None); +mat!(match_repetition_81, r"((..)|(.)){3}", r"aaaaaa", Some((0, 6)), Some((4, 6)), Some((4, 6)), None); +mat!(match_repetition_83, r"((..)|(.))*", r"aaaaaa", Some((0, 6)), Some((4, 6)), Some((4, 6)), None); +mat!(match_repetition_90, r"X(.?){0,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_91, r"X(.?){1,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_92, r"X(.?){2,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_93, r"X(.?){3,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_94, r"X(.?){4,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_95, r"X(.?){5,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_96, r"X(.?){6,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_97, r"X(.?){7,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); +mat!(match_repetition_98, r"X(.?){8,}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_100, r"X(.?){0,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_102, r"X(.?){1,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_104, r"X(.?){2,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_106, r"X(.?){3,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_108, r"X(.?){4,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_110, r"X(.?){5,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_112, r"X(.?){6,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_114, r"X(.?){7,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_115, r"X(.?){8,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); +mat!(match_repetition_126, r"(a|ab|c|bcd){0,}(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); +mat!(match_repetition_127, r"(a|ab|c|bcd){1,}(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); +mat!(match_repetition_128, r"(a|ab|c|bcd){2,}(d*)", r"ababcd", Some((0, 6)), Some((3, 6)), Some((6, 6))); +mat!(match_repetition_129, r"(a|ab|c|bcd){3,}(d*)", r"ababcd", Some((0, 6)), Some((3, 6)), Some((6, 6))); +mat!(match_repetition_130, r"(a|ab|c|bcd){4,}(d*)", r"ababcd", None); +mat!(match_repetition_131, r"(a|ab|c|bcd){0,10}(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); +mat!(match_repetition_132, r"(a|ab|c|bcd){1,10}(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); +mat!(match_repetition_133, r"(a|ab|c|bcd){2,10}(d*)", r"ababcd", Some((0, 6)), Some((3, 6)), Some((6, 6))); +mat!(match_repetition_134, r"(a|ab|c|bcd){3,10}(d*)", r"ababcd", Some((0, 6)), Some((3, 6)), Some((6, 6))); +mat!(match_repetition_135, r"(a|ab|c|bcd){4,10}(d*)", r"ababcd", None); +mat!(match_repetition_136, r"(a|ab|c|bcd)*(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); +mat!(match_repetition_137, r"(a|ab|c|bcd)+(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); +mat!(match_repetition_143, r"(ab|a|c|bcd){0,}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_145, r"(ab|a|c|bcd){1,}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_147, r"(ab|a|c|bcd){2,}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_149, r"(ab|a|c|bcd){3,}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_150, r"(ab|a|c|bcd){4,}(d*)", r"ababcd", None); +mat!(match_repetition_152, r"(ab|a|c|bcd){0,10}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_154, r"(ab|a|c|bcd){1,10}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_156, r"(ab|a|c|bcd){2,10}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_158, r"(ab|a|c|bcd){3,10}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_159, r"(ab|a|c|bcd){4,10}(d*)", r"ababcd", None); +mat!(match_repetition_161, r"(ab|a|c|bcd)*(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); +mat!(match_repetition_163, r"(ab|a|c|bcd)+(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); + diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/macros_bytes.rs cargo-0.26.0/vendor/regex-0.2.10/tests/macros_bytes.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/macros_bytes.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/macros_bytes.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,38 @@ +// Macros for use in writing tests generic over &str/&[u8]. +macro_rules! text { ($text:expr) => { $text.as_bytes() } } +macro_rules! t { ($re:expr) => { text!($re) } } +macro_rules! match_text { ($text:expr) => { $text.as_bytes() } } + +macro_rules! bytes { ($text:expr) => { $text } } + +macro_rules! no_expand { + ($text:expr) => {{ + use regex::bytes::NoExpand; + NoExpand(text!($text)) + }} +} + +macro_rules! show { + ($text:expr) => {{ + use std::ascii::escape_default; + let mut s = vec![]; + for &b in bytes!($text) { + s.extend(escape_default(b)); + } + String::from_utf8(s).unwrap() + }} +} + +macro_rules! expand { + ($name:ident, $re:expr, $text:expr, $expand:expr, $expected:expr) => { + #[test] + fn $name() { + let re = regex!($re); + let cap = re.captures(t!($text)).unwrap(); + + let mut got = vec![]; + cap.expand(t!($expand), &mut got); + assert_eq!(show!(t!($expected)), show!(&*got)); + } + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/macros.rs cargo-0.26.0/vendor/regex-0.2.10/tests/macros.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/macros.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/macros.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,149 @@ +// Convenience macros. + +macro_rules! findall { + ($re:expr, $text:expr) => {{ + $re.find_iter(text!($text)) + .map(|m| (m.start(), m.end())).collect::<Vec<_>>() + }} +} + +// Macros for automatically producing tests. + +macro_rules! ismatch { + ($name:ident, $re:expr, $text:expr, $ismatch:expr) => { + #[test] + fn $name() { + let re = regex!($re); + assert_eq!($ismatch, re.is_match(text!($text))); + } + }; +} + +macro_rules! mat( + ($name:ident, $re:expr, $text:expr, $($loc:tt)+) => ( + #[test] + fn $name() { + let text = text!($text); + let expected: Vec<Option<_>> = vec![$($loc)+]; + let r = regex!($re); + let got: Vec<Option<_>> = match r.captures(text) { + Some(c) => { + assert!(r.is_match(text)); + assert!(r.shortest_match(text).is_some()); + r.capture_names() + .enumerate() + .map(|(i, _)| c.get(i).map(|m| (m.start(), m.end()))) + .collect() + } + None => vec![None], + }; + // The test set sometimes leave out capture groups, so truncate + // actual capture groups to match test set. + let mut sgot = &got[..]; + if sgot.len() > expected.len() { + sgot = &sgot[0..expected.len()] + } + if expected != sgot { + panic!("For RE '{}' against '{:?}', \ + expected '{:?}' but got '{:?}'", + $re, text, expected, sgot); + } + } + ); +); + +macro_rules! matiter( + ($name:ident, $re:expr, $text:expr) => ( + #[test] + fn $name() { + let text = text!($text); + let expected: Vec<(usize, usize)> = vec![]; + let r = regex!($re); + let got: Vec<_> = + r.find_iter(text).map(|m| (m.start(), m.end())).collect(); + if expected != got { + panic!("For RE '{}' against '{:?}', \ + expected '{:?}' but got '{:?}'", + $re, text, expected, got); + } + let captures_got: Vec<_> = + r.captures_iter(text) + .map(|c| c.get(0).unwrap()) + .map(|m| (m.start(), m.end())) + .collect(); + if captures_got != got { + panic!("For RE '{}' against '{:?}', \ + got '{:?}' using find_iter but got '{:?}' \ + using captures_iter", + $re, text, got, captures_got); + } + } + ); + ($name:ident, $re:expr, $text:expr, $($loc:tt)+) => ( + #[test] + fn $name() { + let text = text!($text); + let expected: Vec<_> = vec![$($loc)+]; + let r = regex!($re); + let got: Vec<_> = + r.find_iter(text).map(|m| (m.start(), m.end())).collect(); + if expected != got { + panic!("For RE '{}' against '{:?}', \ + expected '{:?}' but got '{:?}'", + $re, text, expected, got); + } + let captures_got: Vec<_> = + r.captures_iter(text) + .map(|c| c.get(0).unwrap()) + .map(|m| (m.start(), m.end())) + .collect(); + if captures_got != got { + panic!("For RE '{}' against '{:?}', \ + got '{:?}' using find_iter but got '{:?}' \ + using captures_iter", + $re, text, got, captures_got); + } + } + ); +); + +macro_rules! matset { + ($name:ident, $res:expr, $text:expr, $($match_index:expr),*) => { + #[test] + fn $name() { + let text = text!($text); + let set = regex_set!($res); + assert!(set.is_match(text)); + let expected = vec![$($match_index),*]; + let matches = set.matches(text); + assert!(matches.matched_any()); + let got: Vec<_> = matches.into_iter().collect(); + assert_eq!(expected, got); + } + } +} + +macro_rules! nomatset { + ($name:ident, $res:expr, $text:expr) => { + #[test] + fn $name() { + let text = text!($text); + let set = regex_set!($res); + assert!(!set.is_match(text)); + let matches = set.matches(text); + assert!(!matches.matched_any()); + assert_eq!(0, matches.into_iter().count()); + } + } +} + +macro_rules! split { + ($name:ident, $re:expr, $text:expr, $expected:expr) => { + #[test] + fn $name() { + let re = regex!($re); + let splitted: Vec<_> = re.split(t!($text)).collect(); + assert_eq!($expected, &*splitted); + } + } +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/macros_str.rs cargo-0.26.0/vendor/regex-0.2.10/tests/macros_str.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/macros_str.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/macros_str.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,35 @@ +// Macros for use in writing tests generic over &str/&[u8]. +macro_rules! text { ($text:expr) => { $text } } +macro_rules! t { ($text:expr) => { text!($text) } } +macro_rules! match_text { ($text:expr) => { $text.as_str() } } + +macro_rules! no_expand { + ($text:expr) => {{ + use regex::NoExpand; + NoExpand(text!($text)) + }} +} + +macro_rules! show { ($text:expr) => { $text } } + +// N.B. The expansion API for &str and &[u8] APIs differs slightly for now, +// but they should be unified in 1.0. Then we can move this macro back into +// tests/api.rs where it is used. ---AG +macro_rules! expand { + ($name:ident, $re:expr, $text:expr, $expand:expr, $expected:expr) => { + #[test] + fn $name() { + let re = regex!($re); + let cap = re.captures(t!($text)).unwrap(); + + let mut got = String::new(); + cap.expand(t!($expand), &mut got); + assert_eq!(show!(t!($expected)), show!(&*got)); + } + } +} + +#[cfg(feature = "pattern")] +macro_rules! searcher_expr { ($e:expr) => ($e) } +#[cfg(not(feature = "pattern"))] +macro_rules! searcher_expr { ($e:expr) => ({}) } diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/misc.rs cargo-0.26.0/vendor/regex-0.2.10/tests/misc.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/misc.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/misc.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,14 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +mat!(prefix_literal_match, r"^abc", r"abc", Some((0, 3))); +mat!(prefix_literal_nomatch, r"^abc", r"zabc", None); +mat!(one_literal_edge, r"abc", r"xxxxxab", None); +matiter!(terminates, r"a$", r"a", (0, 1)); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/multiline.rs cargo-0.26.0/vendor/regex-0.2.10/tests/multiline.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/multiline.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/multiline.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,49 @@ +matiter!(match_multi_1, r"(?m)^[a-z]+$", "abc\ndef\nxyz", + (0, 3), (4, 7), (8, 11)); +matiter!(match_multi_2, r"(?m)^$", "abc\ndef\nxyz"); +matiter!(match_multi_3, r"(?m)^", "abc\ndef\nxyz", + (0, 0), (4, 4), (8, 8)); +matiter!(match_multi_4, r"(?m)$", "abc\ndef\nxyz", + (3, 3), (7, 7), (11, 11)); +matiter!(match_multi_5, r"(?m)^[a-z]", "abc\ndef\nxyz", + (0, 1), (4, 5), (8, 9)); +matiter!(match_multi_6, r"(?m)[a-z]^", "abc\ndef\nxyz"); +matiter!(match_multi_7, r"(?m)[a-z]$", "abc\ndef\nxyz", + (2, 3), (6, 7), (10, 11)); +matiter!(match_multi_8, r"(?m)$[a-z]", "abc\ndef\nxyz"); +matiter!(match_multi_9, r"(?m)^$", "", (0, 0)); + +matiter!(match_multi_rep_1, r"(?m)(?:^$)*", "a\nb\nc", + (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); +matiter!(match_multi_rep_2, r"(?m)(?:^|a)+", "a\naaa\n", + (0, 0), (2, 2), (3, 5), (6, 6)); +matiter!(match_multi_rep_3, r"(?m)(?:^|a)*", "a\naaa\n", + (0, 1), (2, 5), (6, 6)); +matiter!(match_multi_rep_4, r"(?m)(?:^[a-z])+", "abc\ndef\nxyz", + (0, 1), (4, 5), (8, 9)); +matiter!(match_multi_rep_5, r"(?m)(?:^[a-z]{3}\n?)+", "abc\ndef\nxyz", + (0, 11)); +matiter!(match_multi_rep_6, r"(?m)(?:^[a-z]{3}\n?)*", "abc\ndef\nxyz", + (0, 11)); +matiter!(match_multi_rep_7, r"(?m)(?:\n?[a-z]{3}$)+", "abc\ndef\nxyz", + (0, 11)); +matiter!(match_multi_rep_8, r"(?m)(?:\n?[a-z]{3}$)*", "abc\ndef\nxyz", + (0, 11)); +matiter!(match_multi_rep_9, r"(?m)^*", "\naa\n", + (0, 0), (1, 1), (2, 2), (3, 3), (4, 4)); +matiter!(match_multi_rep_10, r"(?m)^+", "\naa\n", + (0, 0), (1, 1), (4, 4)); +matiter!(match_multi_rep_11, r"(?m)$*", "\naa\n", + (0, 0), (1, 1), (2, 2), (3, 3), (4, 4)); +matiter!(match_multi_rep_12, r"(?m)$+", "\naa\n", + (0, 0), (3, 3), (4, 4)); +matiter!(match_multi_rep_13, r"(?m)(?:$\n)+", "\n\naaa\n\n", + (0, 2), (5, 7)); +matiter!(match_multi_rep_14, r"(?m)(?:$\n)*", "\n\naaa\n\n", + (0, 2), (3, 3), (4, 4), (5, 7)); +matiter!(match_multi_rep_15, r"(?m)(?:$\n^)+", "\n\naaa\n\n", + (0, 2), (5, 7)); +matiter!(match_multi_rep_16, r"(?m)(?:^|$)+", "\n\naaa\n\n", + (0, 0), (1, 1), (2, 2), (5, 5), (6, 6), (7, 7)); +matiter!(match_multi_rep_17, r"(?m)(?:$\n)*", "\n\naaa\n\n", + (0, 2), (3, 3), (4, 4), (5, 7)); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/noparse.rs cargo-0.26.0/vendor/regex-0.2.10/tests/noparse.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/noparse.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/noparse.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,50 @@ +macro_rules! noparse( + ($name:ident, $re:expr) => ( + #[test] + fn $name() { + let re = $re; + match regex_new!(re) { + Err(_) => {}, + Ok(_) => panic!("Regex '{}' should cause a parse error.", re), + } + } + ); +); + +noparse!(fail_no_repeat_arg, "*"); +noparse!(fail_incomplete_escape, "\\"); +noparse!(fail_class_incomplete, "[A-"); +noparse!(fail_class_not_closed, "[A"); +noparse!(fail_class_no_begin, r"[\A]"); +noparse!(fail_class_no_end, r"[\z]"); +noparse!(fail_class_no_boundary, r"[\b]"); +noparse!(fail_open_paren, "("); +noparse!(fail_close_paren, ")"); +noparse!(fail_invalid_range, "[a-Z]"); +noparse!(fail_empty_capture_name, "(?P<>a)"); +noparse!(fail_bad_capture_name, "(?P<na-me>)"); +noparse!(fail_bad_flag, "(?a)a"); +noparse!(fail_too_big, "a{10000000}"); +noparse!(fail_counted_no_close, "a{1001"); +noparse!(fail_unfinished_cap, "(?"); +noparse!(fail_unfinished_escape, "\\"); +noparse!(fail_octal_digit, r"\8"); +noparse!(fail_hex_digit, r"\xG0"); +noparse!(fail_hex_short, r"\xF"); +noparse!(fail_hex_long_digits, r"\x{fffg}"); +noparse!(fail_flag_bad, "(?a)"); +noparse!(fail_flag_empty, "(?)"); +noparse!(fail_double_neg, "(?-i-i)"); +noparse!(fail_neg_empty, "(?i-)"); +noparse!(fail_dupe_named, "(?P<a>.)(?P<a>.)"); +noparse!(fail_range_end_no_class, "[a-[:lower:]]"); +noparse!(fail_range_end_no_begin, r"[a-\A]"); +noparse!(fail_range_end_no_end, r"[a-\z]"); +noparse!(fail_range_end_no_boundary, r"[a-\b]"); +noparse!(fail_empty_alt1, r"|z"); +noparse!(fail_empty_alt2, r"z|"); +noparse!(fail_empty_alt3, r"|"); +noparse!(fail_empty_alt4, r"||"); +noparse!(fail_empty_alt5, r"()|z"); +noparse!(fail_empty_alt6, r"z|()"); +noparse!(fail_empty_alt7, r"(|)"); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/regression.rs cargo-0.26.0/vendor/regex-0.2.10/tests/regression.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/regression.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/regression.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,99 @@ +// See: https://github.com/rust-lang/regex/issues/48 +#[test] +fn invalid_regexes_no_crash() { + assert!(regex_new!("(*)").is_err()); + assert!(regex_new!("(?:?)").is_err()); + assert!(regex_new!("(?)").is_err()); + assert!(regex_new!("*").is_err()); +} + +// See: https://github.com/rust-lang/regex/issues/98 +#[test] +fn regression_many_repeat_stack_overflow() { + let re = regex!("^.{1,2500}"); + assert_eq!(vec![(0, 1)], findall!(re, "a")); +} + +// See: https://github.com/rust-lang/regex/issues/75 +mat!(regression_unsorted_binary_search_1, r"(?i)[a_]+", "A_", Some((0, 2))); +mat!(regression_unsorted_binary_search_2, r"(?i)[A_]+", "a_", Some((0, 2))); + +// See: https://github.com/rust-lang/regex/issues/99 +mat!(regression_negated_char_class_1, r"(?i)[^x]", "x", None); +mat!(regression_negated_char_class_2, r"(?i)[^x]", "X", None); + +// See: https://github.com/rust-lang/regex/issues/101 +mat!(regression_ascii_word_underscore, r"[[:word:]]", "_", Some((0, 1))); + +// See: https://github.com/rust-lang/regex/issues/129 +#[test] +fn regression_captures_rep() { + let re = regex!(r"([a-f]){2}(?P<foo>[x-z])"); + let caps = re.captures(text!("abx")).unwrap(); + assert_eq!(match_text!(caps.name("foo").unwrap()), text!("x")); +} + +// See: https://github.com/rust-lang/regex/issues/153 +mat!(regression_alt_in_alt1, r"ab?|$", "az", Some((0, 1))); +mat!(regression_alt_in_alt2, r"^(.*?)(\n|\r\n?|$)", "ab\rcd", Some((0, 3))); + +// See: https://github.com/rust-lang/regex/issues/169 +mat!(regression_leftmost_first_prefix, r"z*azb", "azb", Some((0, 3))); + +// See: https://github.com/rust-lang/regex/issues/76 +mat!(uni_case_lower_nocase_flag, r"(?i)\p{Ll}+", "ΛΘΓΔα", Some((0, 10))); + +// See: https://github.com/rust-lang/regex/issues/191 +mat!(many_alternates, r"1|2|3|4|5|6|7|8|9|10|int", "int", Some((0, 3))); + +// burntsushi was bad and didn't create an issue for this bug. +mat!(anchored_prefix1, r"^a\S", "a ", None); +mat!(anchored_prefix2, r"^a\S", "foo boo a ", None); +mat!(anchored_prefix3, r"^-[a-z]", "r-f", None); + +// See: https://github.com/rust-lang/regex/issues/204 +split!(split_on_word_boundary, r"\b", r"Should this (work?)", + &[t!(""), t!("Should"), t!(" "), t!("this"), + t!(" ("), t!("work"), t!("?)")]); +matiter!(word_boundary_dfa, r"\b", "a b c", + (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); + +// See: https://github.com/rust-lang/regex/issues/268 +matiter!(partial_anchor, r"^a|b", "ba", (0, 1)); + +// See: https://github.com/rust-lang/regex/issues/264 +mat!(ascii_boundary_no_capture, r"(?-u)\B", "\u{28f3e}", Some((0, 0))); +mat!(ascii_boundary_capture, r"(?-u)(\B)", "\u{28f3e}", Some((0, 0))); + +// See: https://github.com/rust-lang/regex/issues/280 +ismatch!(partial_anchor_alternate_begin, r"^a|z", "yyyyya", false); +ismatch!(partial_anchor_alternate_end, r"a$|z", "ayyyyy", false); + +// See: https://github.com/rust-lang/regex/issues/289 +mat!(lits_unambiguous1, r"(ABC|CDA|BC)X", "CDAX", Some((0, 4))); + +// See: https://github.com/rust-lang/regex/issues/291 +mat!(lits_unambiguous2, r"((IMG|CAM|MG|MB2)_|(DSCN|CIMG))(?P<n>[0-9]+)$", + "CIMG2341", Some((0, 8)), Some((0, 4)), None, Some((0, 4)), Some((4, 8))); + +// See: https://github.com/rust-lang/regex/issues/271 +mat!(end_not_wb, r"$(?-u:\B)", "\u{5c124}\u{b576c}", Some((8, 8))); +mat!(endl_or_wb, r"(?m:$)|(?-u:\b)", "\u{6084e}", Some((4, 4))); +mat!(zero_or_end, r"(?i-u:\x00)|$", "\u{e682f}", Some((4, 4))); +mat!(y_or_endl, r"(?i-u:y)|(?m:$)", "\u{b4331}", Some((4, 4))); +mat!(wb_start_x, r"(?u:\b)^(?-u:X)", "X", Some((0, 1))); + +// See: https://github.com/rust-lang/regex/issues/321 +ismatch!(strange_anchor_non_complete_prefix, r"a^{2}", "", false); +ismatch!(strange_anchor_non_complete_suffix, r"${2}a", "", false); + +// See: https://github.com/rust-lang/regex/issues/334 +mat!(captures_after_dfa_premature_end, r"a(b*(X|$))?", "abcbX", + Some((0, 1)), None, None); + +// See: https://github.com/rust-lang/regex/issues/437 +ismatch!( + literal_panic, + r"typename type\-parameter\-\d+\-\d+::.+", + "test", + false); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/replace.rs cargo-0.26.0/vendor/regex-0.2.10/tests/replace.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/replace.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/replace.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,44 @@ +macro_rules! replace( + ($name:ident, $which:ident, $re:expr, + $search:expr, $replace:expr, $result:expr) => ( + #[test] + fn $name() { + let re = regex!($re); + assert_eq!(re.$which(text!($search), $replace), text!($result)); + } + ); +); + +replace!(first, replace, r"\d", "age: 26", t!("Z"), "age: Z6"); +replace!(plus, replace, r"\d+", "age: 26", t!("Z"), "age: Z"); +replace!(all, replace_all, r"\d", "age: 26", t!("Z"), "age: ZZ"); +replace!(groups, replace, r"(\S+)\s+(\S+)", "w1 w2", t!("$2 $1"), "w2 w1"); +replace!(double_dollar, replace, + r"(\S+)\s+(\S+)", "w1 w2", t!("$2 $$1"), "w2 $1"); +// replace!(adjacent_index, replace, + // r"([^aeiouy])ies$", "skies", t!("$1y"), "sky"); +replace!(named, replace_all, + r"(?P<first>\S+)\s+(?P<last>\S+)(?P<space>\s*)", + "w1 w2 w3 w4", t!("$last $first$space"), "w2 w1 w4 w3"); +replace!(trim, replace_all, "^[ \t]+|[ \t]+$", " \t trim me\t \t", + t!(""), "trim me"); +replace!(number_hypen, replace, r"(.)(.)", "ab", t!("$1-$2"), "a-b"); +// replace!(number_underscore, replace, r"(.)(.)", "ab", t!("$1_$2"), "a_b"); +replace!(simple_expand, replace_all, r"(\w) (\w)", "a b", t!("$2 $1"), "b a"); +replace!(literal_dollar1, replace_all, + r"(\w+) (\w+)", "a b", t!("$$1"), "$1"); +replace!(literal_dollar2, replace_all, + r"(\w+) (\w+)", "a b", t!("$2 $$c $1"), "b $c a"); +replace!(no_expand1, replace, + r"(\S+)\s+(\S+)", "w1 w2", no_expand!("$2 $1"), "$2 $1"); +replace!(no_expand2, replace, + r"(\S+)\s+(\S+)", "w1 w2", no_expand!("$$1"), "$$1"); + +// See https://github.com/rust-lang/regex/issues/314 +replace!(match_at_start_replace_with_empty, replace_all, r"foo", "foobar", t!(""), "bar"); + +// See https://github.com/rust-lang/regex/issues/393 +replace!(single_empty_match, replace, r"^", "bar", t!("foo"), "foobar"); + +// See https://github.com/rust-lang/regex/issues/399 +replace!(capture_longest_possible_name, replace_all, r"(.)", "b", t!("${1}a $1a"), "ba "); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/searcher.rs cargo-0.26.0/vendor/regex-0.2.10/tests/searcher.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/searcher.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/searcher.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,66 @@ +macro_rules! searcher { + ($name:ident, $re:expr, $haystack:expr) => ( + searcher!($name, $re, $haystack, vec vec![]); + ); + ($name:ident, $re:expr, $haystack:expr, $($steps:expr,)*) => ( + searcher!($name, $re, $haystack, vec vec![$($steps),*]); + ); + ($name:ident, $re:expr, $haystack:expr, $($steps:expr),*) => ( + searcher!($name, $re, $haystack, vec vec![$($steps),*]); + ); + ($name:ident, $re:expr, $haystack:expr, vec $expect_steps:expr) => ( + #[test] + #[allow(unused_imports)] + fn $name() { + searcher_expr! {{ + use std::str::pattern::{Pattern, Searcher}; + use std::str::pattern::SearchStep::{Match, Reject, Done}; + let re = regex!($re); + let mut se = re.into_searcher($haystack); + let mut got_steps = vec![]; + loop { + match se.next() { + Done => break, + step => { got_steps.push(step); } + } + } + assert_eq!(got_steps, $expect_steps); + }} + } + ); +} + +searcher!(searcher_empty_regex_empty_haystack, r"", "", Match(0, 0)); +searcher!(searcher_empty_regex, r"", "ab", + Match(0, 0), Reject(0, 1), Match(1, 1), Reject(1, 2), Match(2, 2)); +searcher!(searcher_empty_haystack, r"\d", ""); +searcher!(searcher_one_match, r"\d", "5", + Match(0, 1)); +searcher!(searcher_no_match, r"\d", "a", + Reject(0, 1)); +searcher!(searcher_two_adjacent_matches, r"\d", "56", + Match(0, 1), Match(1, 2)); +searcher!(searcher_two_non_adjacent_matches, r"\d", "5a6", + Match(0, 1), Reject(1, 2), Match(2, 3)); +searcher!(searcher_reject_first, r"\d", "a6", + Reject(0, 1), Match(1, 2)); +searcher!(searcher_one_zero_length_matches, r"\d*", "a1b2", + Match(0, 0), // ^ + Reject(0, 1), // a + Match(1, 2), // a1 + Reject(2, 3), // a1b + Match(3, 4), // a1b2 +); +searcher!(searcher_many_zero_length_matches, r"\d*", "a1bbb2", + Match(0, 0), // ^ + Reject(0, 1), // a + Match(1, 2), // a1 + Reject(2, 3), // a1b + Match(3, 3), // a1bb + Reject(3, 4), // a1bb + Match(4, 4), // a1bbb + Reject(4, 5), // a1bbb + Match(5, 6), // a1bbba +); +searcher!(searcher_unicode, r".+?", "Ⅰ1Ⅱ2", + Match(0, 3), Match(3, 4), Match(4, 7), Match(7, 8)); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/set.rs cargo-0.26.0/vendor/regex-0.2.10/tests/set.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/set.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/set.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,32 @@ +matset!(set1, &["a", "a"], "a", 0, 1); +matset!(set2, &["a", "a"], "ba", 0, 1); +matset!(set3, &["a", "b"], "a", 0); +matset!(set4, &["a", "b"], "b", 1); +matset!(set5, &["a|b", "b|a"], "b", 0, 1); +matset!(set6, &["foo", "oo"], "foo", 0, 1); +matset!(set7, &["^foo", "bar$"], "foo", 0); +matset!(set8, &["^foo", "bar$"], "foo bar", 0, 1); +matset!(set9, &["^foo", "bar$"], "bar", 1); +matset!(set10, &[r"[a-z]+$", "foo"], "01234 foo", 0, 1); +matset!(set11, &[r"[a-z]+$", "foo"], "foo 01234", 1); +matset!(set12, &[r".*?", "a"], "zzzzzza", 0, 1); +matset!(set13, &[r".*", "a"], "zzzzzza", 0, 1); +matset!(set14, &[r".*", "a"], "zzzzzz", 0); +matset!(set15, &[r"\ba\b"], "hello a bye", 0); +matset!(set16, &["a"], "a", 0); +matset!(set17, &[".*a"], "a", 0); +matset!(set18, &["a", "β"], "β", 1); + +nomatset!(nset1, &["a", "a"], "b"); +nomatset!(nset2, &["^foo", "bar$"], "bar foo"); +nomatset!(nset3, { let xs: &[&str] = &[]; xs }, "a"); +nomatset!(nset4, &[r"^rooted$", r"\.log$"], "notrooted"); + +// See: https://github.com/rust-lang/regex/issues/187 +#[test] +fn regression_subsequent_matches() { + let set = regex_set!(&["ab", "b"]); + let text = text!("ba"); + assert!(set.matches(text).matched(1)); + assert!(set.matches(text).matched(1)); +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/shortest_match.rs cargo-0.26.0/vendor/regex-0.2.10/tests/shortest_match.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/shortest_match.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/shortest_match.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,14 @@ +macro_rules! shortmat { + ($name:ident, $re:expr, $text:expr, $shortest_match:expr) => { + #[test] + fn $name() { + let text = text!($text); + let re = regex!($re); + assert_eq!($shortest_match, re.shortest_match(text)); + } + } +} + +shortmat!(t01, r"a+", r"aa", Some(1)); +// Test that the reverse suffix optimization gets it right. +shortmat!(t02, r".*(?:abcd)+", r"abcdabcd", Some(4)); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/suffix_reverse.rs cargo-0.26.0/vendor/regex-0.2.10/tests/suffix_reverse.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/suffix_reverse.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/suffix_reverse.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,16 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +mat!(t01, r".*abcd", r"abcd", Some((0, 4))); +mat!(t02, r".*(?:abcd)+", r"abcd", Some((0, 4))); +mat!(t03, r".*(?:abcd)+", r"abcdabcd", Some((0, 8))); +mat!(t04, r".*(?:abcd)+", r"abcdxabcd", Some((0, 9))); +mat!(t05, r".*x(?:abcd)+", r"abcdxabcd", Some((0, 9))); +mat!(t06, r"[^abcd]*x(?:abcd)+", r"abcdxabcd", Some((4, 9))); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/test_backtrack_bytes.rs cargo-0.26.0/vendor/regex-0.2.10/tests/test_backtrack_bytes.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/test_backtrack_bytes.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/test_backtrack_bytes.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,65 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re) + .bounded_backtracking() + .only_utf8(false) + .build() + .map(|e| e.into_byte_regex()) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new_many($re) + .bounded_backtracking() + .only_utf8(false) + .build() + .map(|e| e.into_byte_regex_set()) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_bytes.rs"); +include!("macros.rs"); + +mod api; +mod bytes; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod set; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_ascii; diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/test_backtrack.rs cargo-0.26.0/vendor/regex-0.2.10/tests/test_backtrack.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/test_backtrack.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/test_backtrack.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,64 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(feature = "pattern", feature(pattern))] + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re) + .bounded_backtracking().build().map(|e| e.into_regex()) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new_many($re) + .bounded_backtracking() + .build() + .map(|e| e.into_regex_set()) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_str.rs"); +include!("macros.rs"); + +mod api; +mod api_str; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod searcher; +mod set; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_unicode; diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/test_backtrack_utf8bytes.rs cargo-0.26.0/vendor/regex-0.2.10/tests/test_backtrack_utf8bytes.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/test_backtrack_utf8bytes.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/test_backtrack_utf8bytes.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,65 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(feature = "pattern", feature(pattern))] + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re) + .bounded_backtracking().bytes(true).build().map(|e| e.into_regex()) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new_many($re) + .bounded_backtracking() + .bytes(true) + .build() + .map(|e| e.into_regex_set()) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_str.rs"); +include!("macros.rs"); + +mod api; +mod api_str; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod searcher; +mod set; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_unicode; diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/test_default_bytes.rs cargo-0.26.0/vendor/regex-0.2.10/tests/test_default_bytes.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/test_default_bytes.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/test_default_bytes.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,73 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::bytes::Regex; + Regex::new($re) + }} +} + +macro_rules! regex_set_new { + ($res:expr) => {{ + use regex::bytes::RegexSet; + RegexSet::new($res) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_bytes.rs"); +include!("macros.rs"); + +// A silly wrapper to make it possible to write and match raw bytes. +struct R<'a>(&'a [u8]); +impl<'a> R<'a> { fn as_bytes(&self) -> &'a [u8] { self.0 } } + +// See: https://github.com/rust-lang/regex/issues/321 +// +// These tests are here because they do not have the same behavior in every +// regex engine. +mat!(invalid_utf8_nfa1, r".", R(b"\xD4\xC2\x65\x2B\x0E\xFE"), Some((2, 3))); +mat!(invalid_utf8_nfa2, r"${2}ä", R(b"\xD4\xC2\x65\x2B\x0E\xFE"), None); +mat!(invalid_utf8_nfa3, r".", R(b"\x0A\xDB\x82\x6E\x33\x01\xDD\x33\xCD"), + Some((1, 3))); +mat!(invalid_utf8_nfa4, r"${2}ä", R(b"\x0A\xDB\x82\x6E\x33\x01\xDD\x33\xCD"), + None); + +mod api; +mod bytes; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod set; +mod shortest_match; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_ascii; diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/test_default.rs cargo-0.26.0/vendor/regex-0.2.10/tests/test_default.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/test_default.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/test_default.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,77 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(feature = "pattern", feature(pattern))] + +extern crate rand; +extern crate regex; + +// Due to macro scoping rules, this definition only applies for the modules +// defined below. Effectively, it allows us to use the same tests for both +// native and dynamic regexes. +// +// This is also used to test the various matching engines. This one exercises +// the normal code path which automatically chooses the engine based on the +// regex and the input. Other dynamic tests explicitly set the engine to use. +macro_rules! regex_new { + ($re:expr) => {{ + use regex::Regex; + Regex::new($re) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::RegexSet; + RegexSet::new($re) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_str.rs"); +include!("macros.rs"); + +mod api; +mod api_str; +mod crazy; +mod flags; +mod fowler; +mod misc; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod searcher; +mod set; +mod shortest_match; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_unicode; + +#[test] +fn disallow_non_utf8() { + assert!(regex::Regex::new(r"(?-u)\xFF").is_err()); + assert!(regex::Regex::new(r"(?-u).").is_err()); + assert!(regex::Regex::new(r"(?-u)[\xFF]").is_err()); + assert!(regex::Regex::new(r"(?-u)☃").is_err()); +} diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/test_nfa_bytes.rs cargo-0.26.0/vendor/regex-0.2.10/tests/test_nfa_bytes.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/test_nfa_bytes.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/test_nfa_bytes.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,65 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re) + .nfa() + .only_utf8(false) + .build() + .map(|e| e.into_byte_regex()) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new_many($re) + .nfa() + .only_utf8(false) + .build() + .map(|e| e.into_byte_regex_set()) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_bytes.rs"); +include!("macros.rs"); + +mod api; +mod bytes; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod set; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_ascii; diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/test_nfa.rs cargo-0.26.0/vendor/regex-0.2.10/tests/test_nfa.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/test_nfa.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/test_nfa.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,60 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(feature = "pattern", feature(pattern))] + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re).nfa().build().map(|e| e.into_regex()) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new_many($re).nfa().build().map(|e| e.into_regex_set()) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_str.rs"); +include!("macros.rs"); + +mod api; +mod api_str; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod searcher; +mod set; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_unicode; diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/test_nfa_utf8bytes.rs cargo-0.26.0/vendor/regex-0.2.10/tests/test_nfa_utf8bytes.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/test_nfa_utf8bytes.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/test_nfa_utf8bytes.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,61 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![cfg_attr(feature = "pattern", feature(pattern))] + +extern crate rand; +extern crate regex; + +macro_rules! regex_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new($re).nfa().bytes(true).build().map(|e| e.into_regex()) + }} +} + +macro_rules! regex { + ($re:expr) => { + regex_new!($re).unwrap() + } +} + +macro_rules! regex_set_new { + ($re:expr) => {{ + use regex::internal::ExecBuilder; + ExecBuilder::new_many($re) + .nfa().bytes(true).build().map(|e| e.into_regex_set()) + }} +} + +macro_rules! regex_set { + ($res:expr) => { + regex_set_new!($res).unwrap() + } +} + +// Must come before other module definitions. +include!("macros_str.rs"); +include!("macros.rs"); + +mod api; +mod api_str; +mod crazy; +mod flags; +mod fowler; +mod multiline; +mod noparse; +mod regression; +mod replace; +mod searcher; +mod set; +mod suffix_reverse; +mod unicode; +mod word_boundary; +mod word_boundary_unicode; diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/unicode.rs cargo-0.26.0/vendor/regex-0.2.10/tests/unicode.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/unicode.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/unicode.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,110 @@ +mat!(uni_literal, r"☃", "☃", Some((0, 3))); +mat!(uni_literal_plus, r"☃+", "☃", Some((0, 3))); +mat!(uni_literal_casei_plus, r"(?i)☃+", "☃", Some((0, 3))); +mat!(uni_class_plus, r"[☃Ⅰ]+", "☃", Some((0, 3))); +mat!(uni_one, r"\pN", "Ⅰ", Some((0, 3))); +mat!(uni_mixed, r"\pN+", "Ⅰ1Ⅱ2", Some((0, 8))); +mat!(uni_not, r"\PN+", "abⅠ", Some((0, 2))); +mat!(uni_not_class, r"[\PN]+", "abⅠ", Some((0, 2))); +mat!(uni_not_class_neg, r"[^\PN]+", "abⅠ", Some((2, 5))); +mat!(uni_case, r"(?i)Δ", "δ", Some((0, 2))); +mat!(uni_case_upper, r"\p{Lu}+", "ΛΘΓΔα", Some((0, 8))); +mat!(uni_case_upper_nocase_flag, r"(?i)\p{Lu}+", "ΛΘΓΔα", Some((0, 10))); +mat!(uni_case_upper_nocase, r"\p{L}+", "ΛΘΓΔα", Some((0, 10))); +mat!(uni_case_lower, r"\p{Ll}+", "ΛΘΓΔα", Some((8, 10))); + +// Test the Unicode friendliness of Perl character classes. +mat!(uni_perl_w, r"\w+", "dδd", Some((0, 4))); +mat!(uni_perl_w_not, r"\w+", "⥡", None); +mat!(uni_perl_w_neg, r"\W+", "⥡", Some((0, 3))); +mat!(uni_perl_d, r"\d+", "1२३9", Some((0, 8))); +mat!(uni_perl_d_not, r"\d+", "Ⅱ", None); +mat!(uni_perl_d_neg, r"\D+", "Ⅱ", Some((0, 3))); +mat!(uni_perl_s, r"\s+", " ", Some((0, 3))); +mat!(uni_perl_s_not, r"\s+", "☃", None); +mat!(uni_perl_s_neg, r"\S+", "☃", Some((0, 3))); + +// And do the same for word boundaries. +mat!(uni_boundary_none, r"\d\b", "6δ", None); +mat!(uni_boundary_ogham, r"\d\b", "6 ", Some((0, 1))); +mat!(uni_not_boundary_none, r"\d\B", "6δ", Some((0, 1))); +mat!(uni_not_boundary_ogham, r"\d\B", "6 ", None); + +// Test general categories. +// +// We should test more, but there's a lot. Write a script to generate more of +// these tests. +mat!(uni_class_gencat_cased_letter, + r"\p{Cased_Letter}", "A", Some((0, 3))); +mat!(uni_class_gencat_close_punctuation, + r"\p{Close_Punctuation}", "❯", Some((0, 3))); +mat!(uni_class_gencat_connector_punctuation, + r"\p{Connector_Punctuation}", "⁀", Some((0, 3))); +mat!(uni_class_gencat_control, + r"\p{Control}", "\u{9f}", Some((0, 2))); +mat!(uni_class_gencat_currency_symbol, + r"\p{Currency_Symbol}", "£", Some((0, 3))); +mat!(uni_class_gencat_dash_punctuation, + r"\p{Dash_Punctuation}", "〰", Some((0, 3))); +mat!(uni_class_gencat_decimal_numer, + r"\p{Decimal_Number}", "𑓙", Some((0, 4))); +mat!(uni_class_gencat_enclosing_mark, + r"\p{Enclosing_Mark}", "\u{A672}", Some((0, 3))); +mat!(uni_class_gencat_final_punctuation, + r"\p{Final_Punctuation}", "⸡", Some((0, 3))); +mat!(uni_class_gencat_format, + r"\p{Format}", "\u{E007F}", Some((0, 4))); +mat!(uni_class_gencat_initial_punctuation, + r"\p{Initial_Punctuation}", "⸜", Some((0, 3))); +mat!(uni_class_gencat_letter, + r"\p{Letter}", "Έ", Some((0, 2))); +mat!(uni_class_gencat_letter_number, + r"\p{Letter_Number}", "ↂ", Some((0, 3))); +mat!(uni_class_gencat_line_separator, + r"\p{Line_Separator}", "\u{2028}", Some((0, 3))); +mat!(uni_class_gencat_lowercase_letter, + r"\p{Lowercase_Letter}", "ϛ", Some((0, 2))); +mat!(uni_class_gencat_mark, + r"\p{Mark}", "\u{E01EF}", Some((0, 4))); +mat!(uni_class_gencat_math, + r"\p{Math}", "⋿", Some((0, 3))); +mat!(uni_class_gencat_modifier_letter, + r"\p{Modifier_Letter}", "𖭃", Some((0, 4))); +mat!(uni_class_gencat_modifier_symbol, + r"\p{Modifier_Symbol}", "🏿", Some((0, 4))); +mat!(uni_class_gencat_nonspacing_mark, + r"\p{Nonspacing_Mark}", "\u{1E94A}", Some((0, 4))); +mat!(uni_class_gencat_number, + r"\p{Number}", "⓿", Some((0, 3))); +mat!(uni_class_gencat_open_punctuation, + r"\p{Open_Punctuation}", "⦅", Some((0, 3))); +mat!(uni_class_gencat_other, + r"\p{Other}", "\u{bc9}", Some((0, 3))); +mat!(uni_class_gencat_other_letter, + r"\p{Other_Letter}", "ꓷ", Some((0, 3))); +mat!(uni_class_gencat_other_number, + r"\p{Other_Number}", "㉏", Some((0, 3))); +mat!(uni_class_gencat_other_punctuation, + r"\p{Other_Punctuation}", "𞥞", Some((0, 4))); +mat!(uni_class_gencat_other_symbol, + r"\p{Other_Symbol}", "⅌", Some((0, 3))); +mat!(uni_class_gencat_paragraph_separator, + r"\p{Paragraph_Separator}", "\u{2029}", Some((0, 3))); +mat!(uni_class_gencat_private_use, + r"\p{Private_Use}", "\u{10FFFD}", Some((0, 4))); +mat!(uni_class_gencat_punctuation, + r"\p{Punctuation}", "𑁍", Some((0, 4))); +mat!(uni_class_gencat_separator, + r"\p{Separator}", "\u{3000}", Some((0, 3))); +mat!(uni_class_gencat_space_separator, + r"\p{Space_Separator}", "\u{205F}", Some((0, 3))); +mat!(uni_class_gencat_spacing_mark, + r"\p{Spacing_Mark}", "\u{16F7E}", Some((0, 4))); +mat!(uni_class_gencat_symbol, + r"\p{Symbol}", "⯈", Some((0, 3))); +mat!(uni_class_gencat_titlecase_letter, + r"\p{Titlecase_Letter}", "ῼ", Some((0, 3))); +mat!(uni_class_gencat_unassigned, + r"\p{Unassigned}", "\u{10FFFF}", Some((0, 4))); +mat!(uni_class_gencat_uppercase_letter, + r"\p{Uppercase_Letter}", "Ꝋ", Some((0, 3))); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/word_boundary_ascii.rs cargo-0.26.0/vendor/regex-0.2.10/tests/word_boundary_ascii.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/word_boundary_ascii.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/word_boundary_ascii.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,9 @@ +// ASCII word boundaries are completely oblivious to Unicode characters. +// For Unicode word boundaries, the tests are precisely inverted. +matiter!(ascii1, r"(?-u:\b)x(?-u:\b)", "áxβ", (2, 3)); +matiter!(ascii2, r"(?-u:\B)x(?-u:\B)", "áxβ"); +matiter!(ascii3, r"(?-u:\B)", "0\u{7EF5E}", (2, 2), (3, 3), (4, 4), (5, 5)); + +// We still get Unicode word boundaries by default in byte regexes. +matiter!(unicode1, r"\bx\b", "áxβ"); +matiter!(unicode2, r"\Bx\B", "áxβ", (2, 3)); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/word_boundary.rs cargo-0.26.0/vendor/regex-0.2.10/tests/word_boundary.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/word_boundary.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/word_boundary.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,89 @@ +// Many of these are cribbed from RE2's test suite. + +matiter!(wb1, r"\b", ""); +matiter!(wb2, r"\b", "a", (0, 0), (1, 1)); +matiter!(wb3, r"\b", "ab", (0, 0), (2, 2)); +matiter!(wb4, r"^\b", "ab", (0, 0)); +matiter!(wb5, r"\b$", "ab", (2, 2)); +matiter!(wb6, r"^\b$", "ab"); +matiter!(wb7, r"\bbar\b", "nobar bar foo bar", (6, 9), (14, 17)); +matiter!(wb8, r"a\b", "faoa x", (3, 4)); +matiter!(wb9, r"\bbar", "bar x", (0, 3)); +matiter!(wb10, r"\bbar", "foo\nbar x", (4, 7)); +matiter!(wb11, r"bar\b", "foobar", (3, 6)); +matiter!(wb12, r"bar\b", "foobar\nxxx", (3, 6)); +matiter!(wb13, r"(foo|bar|[A-Z])\b", "foo", (0, 3)); +matiter!(wb14, r"(foo|bar|[A-Z])\b", "foo\n", (0, 3)); +matiter!(wb15, r"\b(foo|bar|[A-Z])", "foo", (0, 3)); +matiter!(wb16, r"\b(foo|bar|[A-Z])\b", "X", (0, 1)); +matiter!(wb17, r"\b(foo|bar|[A-Z])\b", "XY"); +matiter!(wb18, r"\b(foo|bar|[A-Z])\b", "bar", (0, 3)); +matiter!(wb19, r"\b(foo|bar|[A-Z])\b", "foo", (0, 3)); +matiter!(wb20, r"\b(foo|bar|[A-Z])\b", "foo\n", (0, 3)); +matiter!(wb21, r"\b(foo|bar|[A-Z])\b", "ffoo bbar N x", (10, 11)); +matiter!(wb22, r"\b(fo|foo)\b", "fo", (0, 2)); +matiter!(wb23, r"\b(fo|foo)\b", "foo", (0, 3)); +matiter!(wb24, r"\b\b", ""); +matiter!(wb25, r"\b\b", "a", (0, 0), (1, 1)); +matiter!(wb26, r"\b$", ""); +matiter!(wb27, r"\b$", "x", (1, 1)); +matiter!(wb28, r"\b$", "y x", (3, 3)); +matiter!(wb29, r"\b.$", "x", (0, 1)); +matiter!(wb30, r"^\b(fo|foo)\b", "fo", (0, 2)); +matiter!(wb31, r"^\b(fo|foo)\b", "foo", (0, 3)); +matiter!(wb32, r"^\b$", ""); +matiter!(wb33, r"^\b$", "x"); +matiter!(wb34, r"^\b.$", "x", (0, 1)); +matiter!(wb35, r"^\b.\b$", "x", (0, 1)); +matiter!(wb36, r"^^^^^\b$$$$$", ""); +matiter!(wb37, r"^^^^^\b.$$$$$", "x", (0, 1)); +matiter!(wb38, r"^^^^^\b$$$$$", "x"); +matiter!(wb39, r"^^^^^\b\b\b.\b\b\b$$$$$", "x", (0, 1)); +matiter!(wb40, r"\b.+\b", "$$abc$$", (2, 5)); +matiter!(wb41, r"\b", "a b c", (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); + +matiter!(nb1, r"\Bfoo\B", "n foo xfoox that", (7, 10)); +matiter!(nb2, r"a\B", "faoa x", (1, 2)); +matiter!(nb3, r"\Bbar", "bar x"); +matiter!(nb4, r"\Bbar", "foo\nbar x"); +matiter!(nb5, r"bar\B", "foobar"); +matiter!(nb6, r"bar\B", "foobar\nxxx"); +matiter!(nb7, r"(foo|bar|[A-Z])\B", "foox", (0, 3)); +matiter!(nb8, r"(foo|bar|[A-Z])\B", "foo\n"); +matiter!(nb9, r"\B", "", (0, 0)); +matiter!(nb10, r"\B", "x"); +matiter!(nb11, r"\B(foo|bar|[A-Z])", "foo"); +matiter!(nb12, r"\B(foo|bar|[A-Z])\B", "xXy", (1, 2)); +matiter!(nb13, r"\B(foo|bar|[A-Z])\B", "XY"); +matiter!(nb14, r"\B(foo|bar|[A-Z])\B", "XYZ", (1, 2)); +matiter!(nb15, r"\B(foo|bar|[A-Z])\B", "abara", (1, 4)); +matiter!(nb16, r"\B(foo|bar|[A-Z])\B", "xfoo_", (1, 4)); +matiter!(nb17, r"\B(foo|bar|[A-Z])\B", "xfoo\n"); +matiter!(nb18, r"\B(foo|bar|[A-Z])\B", "foo bar vNX", (9, 10)); +matiter!(nb19, r"\B(fo|foo)\B", "xfoo", (1, 3)); +matiter!(nb20, r"\B(foo|fo)\B", "xfooo", (1, 4)); +matiter!(nb21, r"\B\B", "", (0, 0)); +matiter!(nb22, r"\B\B", "x"); +matiter!(nb23, r"\B$", "", (0, 0)); +matiter!(nb24, r"\B$", "x"); +matiter!(nb25, r"\B$", "y x"); +matiter!(nb26, r"\B.$", "x"); +matiter!(nb27, r"^\B(fo|foo)\B", "fo"); +matiter!(nb28, r"^\B(fo|foo)\B", "foo"); +matiter!(nb29, r"^\B", "", (0, 0)); +matiter!(nb30, r"^\B", "x"); +matiter!(nb31, r"^\B\B", "", (0, 0)); +matiter!(nb32, r"^\B\B", "x"); +matiter!(nb33, r"^\B$", "", (0, 0)); +matiter!(nb34, r"^\B$", "x"); +matiter!(nb35, r"^\B.$", "x"); +matiter!(nb36, r"^\B.\B$", "x"); +matiter!(nb37, r"^^^^^\B$$$$$", "", (0, 0)); +matiter!(nb38, r"^^^^^\B.$$$$$", "x"); +matiter!(nb39, r"^^^^^\B$$$$$", "x"); + +// These work for both Unicode and ASCII because all matches are reported as +// byte offsets, and « and » do not correspond to word boundaries at either +// the character or byte level. +matiter!(unicode1, r"\bx\b", "«x", (2, 3)); +matiter!(unicode2, r"\bx\b", "x»", (0, 1)); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/tests/word_boundary_unicode.rs cargo-0.26.0/vendor/regex-0.2.10/tests/word_boundary_unicode.rs --- cargo-0.25.0/vendor/regex-0.2.10/tests/word_boundary_unicode.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/tests/word_boundary_unicode.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,8 @@ +// Unicode word boundaries know about Unicode characters. +// For ASCII word boundaries, the tests are precisely inverted. +matiter!(unicode1, r"\bx\b", "áxβ"); +matiter!(unicode2, r"\Bx\B", "áxβ", (2, 3)); + +matiter!(ascii1, r"(?-u:\b)x(?-u:\b)", "áxβ", (2, 3)); +matiter!(ascii2, r"(?-u:\B)x(?-u:\B)", "áxβ"); +matiter!(ascii3, r"(?-u:\B)", "0\u{7EF5E}", (5, 5)); diff -Nru cargo-0.25.0/vendor/regex-0.2.10/.travis.yml cargo-0.26.0/vendor/regex-0.2.10/.travis.yml --- cargo-0.25.0/vendor/regex-0.2.10/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,29 @@ +dist: trusty +sudo: false +language: rust +rust: +- 1.12.0 +- stable +- beta +- nightly +script: ci/script.sh +addons: + apt: + packages: + - libcurl4-openssl-dev + - libelf-dev + - libdw-dev + - binutils-dev + - wget + - clang-3.6 + - cmake + - python + - python-virtualenv +after_success: ci/after_success.sh +notifications: + email: + on_success: never +branches: + only: + - master + - auto diff -Nru cargo-0.25.0/vendor/regex-0.2.10/UNICODE.md cargo-0.26.0/vendor/regex-0.2.10/UNICODE.md --- cargo-0.25.0/vendor/regex-0.2.10/UNICODE.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.10/UNICODE.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,250 @@ +# Unicode conformance + +This document describes the regex crate's conformance to Unicode's +[UTS#18](http://unicode.org/reports/tr18/) +report, which lays out 3 levels of support: Basic, Extended and Tailored. + +Full support for Level 1 ("Basic Unicode Support") is provided with two +exceptions: + +1. Line boundaries are not Unicode aware. Namely, only the `\n` + (`END OF LINE`) character is recognized as a line boundary. +2. The compatibility properties specified by + [RL1.2a](http://unicode.org/reports/tr18/#RL1.2a) + are ASCII-only definitions. + +Little to no support is provided for either Level 2 or Level 3. For the most +part, this is because the features are either complex/hard to implement, or at +the very least, very difficult to implement without sacrificing performance. +For example, tackling canonical equivalence such that matching worked as one +would expect regardless of normalization form would be a significant +undertaking. This is at least partially a result of the fact that this regex +engine is based on finite automata, which admits less flexibility normally +associated with backtracking implementations. + + +## RL1.1 Hex Notation + +[UTS#18 RL1.1](https://unicode.org/reports/tr18/#Hex_notation) + +Hex Notation refers to the ability to specify a Unicode code point in a regular +expression via its hexadecimal code point representation. This is useful in +environments that have poor Unicode font rendering or if you need to express a +code point that is not normally displayable. All forms of hexadecimal notation +are supported + + \x7F hex character code (exactly two digits) + \x{10FFFF} any hex character code corresponding to a Unicode code point + \u007F hex character code (exactly four digits) + \u{7F} any hex character code corresponding to a Unicode code point + \U0000007F hex character code (exactly eight digits) + \U{7F} any hex character code corresponding to a Unicode code point + +Briefly, the `\x{...}`, `\u{...}` and `\U{...}` are all exactly equivalent ways +of expressing hexadecimal code points. Any number of digits can be written +within the brackets. In contrast, `\xNN`, `\uNNNN`, `\UNNNNNNNN` are all +fixed-width variants of the same idea. + +Note that when Unicode mode is disabled, any non-ASCII Unicode codepoint is +banned. Additionally, the `\xNN` syntax represents arbitrary bytes when Unicode +mode is disabled. That is, the regex `\xFF` matches the Unicode codepoint +U+00FF (encoded as `\xC3\xBF` in UTF-8) while the regex `(?-u)\xFF` matches +the literal byte `\xFF`. + + +## RL1.2 Properties + +[UTS#18 RL1.2](https://unicode.org/reports/tr18/#Categories) + +Full support for Unicode property syntax is provided. Unicode properties +provide a convenient way to construct character classes of groups of code +points specified by Unicode. The regex crate does not provide exhaustive +support, but covers a useful subset. In particular: + +* [General categories](http://unicode.org/reports/tr18/#General_Category_Property) +* [Scripts and Script Extensions](http://unicode.org/reports/tr18/#Script_Property) +* [Age](http://unicode.org/reports/tr18/#Age) +* A smattering of boolean properties, including all of those specified by + [RL1.2](http://unicode.org/reports/tr18/#RL1.2) explicitly. + +In all cases, property name and value abbreviations are supported, and all +names/values are matched loosely without regard for case, whitespace or +underscores. Property name aliases can be found in Unicode's +[`PropertyAliases.txt`](http://www.unicode.org/Public/UCD/latest/ucd/PropertyAliases.txt) +file, while property value aliases can be found in Unicode's +[`PropertyValueAliases.txt`](http://www.unicode.org/Public/UCD/latest/ucd/PropertyValueAliases.txt) +file. + +The syntax supported is also consistent with the UTS#18 recommendation: + +* `\p{Greek}` selects the `Greek` script. Equivalent expressions follow: + `\p{sc:Greek}`, `\p{Script:Greek}`, `\p{Sc=Greek}`, `\p{script=Greek}`, + `\P{sc!=Greek}`. Similarly for `General_Category` (or `gc` for short) and + `Script_Extensions` (or `scx` for short). +* `\p{age:3.2}` selects all code points in Unicode 3.2. +* `\p{Alphabetic}` selects the "alphabetic" property and can be abbreviated + via `\p{alpha}` (for example). +* Single letter variants for properties with single letter abbreviations. + For example, `\p{Letter}` can be equivalently written as `\pL`. + +The following is a list of all properties supported by the regex crate (starred +properties correspond to properties required by RL1.2): + +* `General_Category` \* (including `Any`, `ASCII` and `Assigned`) +* `Script` \* +* `Script_Extensions` \* +* `Age` +* `ASCII_Hex_Digit` +* `Alphabetic` \* +* `Bidi_Control` +* `Case_Ignorable` +* `Cased` +* `Changes_When_Casefolded` +* `Changes_When_Casemapped` +* `Changes_When_Lowercased` +* `Changes_When_Titlecased` +* `Changes_When_Uppercased` +* `Dash` +* `Default_Ignorable_Code_Point` \* +* `Deprecated` +* `Diacritic` +* `Extender` +* `Grapheme_Base` +* `Grapheme_Extend` +* `Hex_Digit` +* `IDS_Binary_Operator` +* `IDS_Trinary_Operator` +* `ID_Continue` +* `ID_Start` +* `Join_Control` +* `Logical_Order_Exception` +* `Lowercase` \* +* `Math` +* `Noncharacter_Code_Point` \* +* `Pattern_Syntax` +* `Pattern_White_Space` +* `Prepended_Concatenation_Mark` +* `Quotation_Mark` +* `Radical` +* `Regional_Indicator` +* `Sentence_Terminal` +* `Soft_Dotted` +* `Terminal_Punctuation` +* `Unified_Ideograph` +* `Uppercase` \* +* `Variation_Selector` +* `White_Space` \* +* `XID_Continue` +* `XID_Start` + + +## RL1.2a Compatibility Properties + +[UTS#18 RL1.2a](http://unicode.org/reports/tr18/#RL1.2a) + +The regex crate only provides ASCII definitions of the +[compatibility properties documented in UTS#18 Annex C](http://unicode.org/reports/tr18/#Compatibility_Properties) +(sans the `\X` class, for matching grapheme clusters, which isn't provided +at all). This is because it seems to be consistent with most other regular +expression engines, and in particular, because these are often referred to as +"ASCII" or "POSIX" character classes. + +Note that the `\w`, `\s` and `\d` character classes **are** Unicode aware. +Their traditional ASCII definition can be used by disabling Unicode. That is, +`[[:word:]]` and `(?-u)\w` are equivalent. + + +## RL1.3 Subtraction and Intersection + +[UTS#18 RL1.3](http://unicode.org/reports/tr18/#Subtraction_and_Intersection) + +The regex crate provides full support for nested character classes, along with +union, intersection (`&&`), difference (`--`) and symmetric difference (`~~`) +operations on arbitrary character classes. + +For example, to match all non-ASCII letters, you could use either +`[\p{Letter}--\p{Ascii}]` (difference) or `[\p{Letter}&&[^\p{Ascii}]]` +(intersecting the negation). + + +## RL1.4 Simple Word Boundaries + +[UTS#18 RL1.4](http://unicode.org/reports/tr18/#Simple_Word_Boundaries) + +The regex crate provides basic Unicode aware word boundary assertions. A word +boundary assertion can be written as `\b`, or `\B` as its negation. A word +boundary negation corresponds to a zero-width match, where its adjacent +characters correspond to word and non-word, or non-word and word characters. + +Conformance in this case chooses to define word character in the same way that +the `\w` character class is defined: a code point that is a member of one of +the following classes: + +* `\p{Alphabetic}` +* `\p{Join_Control}` +* `\p{gc:Mark}` +* `\p{gc:Decimal_Number}` +* `\p{gc:Connector_Punctuation}` + +In particular, this differs slightly from the +[prescription given in RL1.4](http://unicode.org/reports/tr18/#Simple_Word_Boundaries) +but is permissible according to +[UTS#18 Annex C](http://unicode.org/reports/tr18/#Compatibility_Properties). +Namely, it is convenient and simpler to have `\w` and `\b` be in sync with +one another. + +Finally, Unicode word boundaries can be disabled, which will cause ASCII word +boundaries to be used instead. That is, `\b` is a Unicode word boundary while +`(?-u)\b` is an ASCII-only word boundary. This can occasionally be beneficial +if performance is important, since the implementation of Unicode word +boundaries is currently sub-optimal on non-ASCII text. + + +## RL1.5 Simple Loose Matches + +[UTS#18 RL1.5](http://unicode.org/reports/tr18/#Simple_Loose_Matches) + +The regex crate provides full support for case insensitive matching in +accordance with RL1.5. That is, it uses the "simple" case folding mapping. The +"simple" mapping was chosen because of a key convenient property: every +"simple" mapping is a mapping from exactly one code point to exactly one other +code point. This makes case insensitive matching of character classes, for +example, straight-forward to implement. + +When case insensitive mode is enabled (e.g., `(?i)[a]` is equivalent to `a|A`), +then all characters classes are case folded as well. + + +## RL1.6 Line Boundaries + +[UTS#18 RL1.6](http://unicode.org/reports/tr18/#Line_Boundaries) + +The regex crate only provides support for recognizing the `\n` (`END OF LINE`) +character as a line boundary. This choice was made mostly for implementation +convenience, and to avoid performance cliffs that Unicode word boundaries are +subject to. + +Ideally, it would be nice to at least support `\r\n` as a line boundary as +well, and in theory, this could be done efficiently. + + +## RL1.7 Code Points + +[UTS#18 RL1.7](http://unicode.org/reports/tr18/#Supplementary_Characters) + +The regex crate provides full support for Unicode code point matching. Namely, +the fundamental atom of any match is always a single code point. + +Given Rust's strong ties to UTF-8, the following guarantees are also provided: + +* All matches are reported on valid UTF-8 code unit boundaries. That is, any + match range returned by the public regex API is guaranteed to successfully + slice the string that was searched. +* By consequence of the above, it is impossible to match surrogode code points. + No support for UTF-16 is provided, so this is never necessary. + +Note that when Unicode mode is disabled, the fundamental atom of matching is +no longer a code point but a single byte. When Unicode mode is disabled, many +Unicode features are disabled as well. For example, `(?-u)\pL` is not a valid +regex but `\pL(?-u)\xFF` (matches any Unicode `Letter` followed by the literal +byte `\xFF`) is, for example. diff -Nru cargo-0.25.0/vendor/regex-0.2.6/appveyor.yml cargo-0.26.0/vendor/regex-0.2.6/appveyor.yml --- cargo-0.25.0/vendor/regex-0.2.6/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -environment: - matrix: - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc - - TARGET: i686-pc-windows-gnu -install: - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" - - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - - SET PATH=%PATH%;C:\MinGW\bin - - rustc -V - - cargo -V -build: false -test_script: - - cargo test --verbose --jobs 4 -branches: - only: - - master - - auto diff -Nru cargo-0.25.0/vendor/regex-0.2.6/.cargo-checksum.json cargo-0.26.0/vendor/regex-0.2.6/.cargo-checksum.json --- cargo-0.25.0/vendor/regex-0.2.6/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"5be5347bde0c48cfd8c3fdc0766cdfe9d8a755ef84d620d6794c778c91de8b2b"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/regex-0.2.6/Cargo.toml cargo-0.26.0/vendor/regex-0.2.6/Cargo.toml --- cargo-0.25.0/vendor/regex-0.2.6/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,102 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "regex" -version = "0.2.6" -authors = ["The Rust Project Developers"] -description = "An implementation of regular expressions for Rust. This implementation uses\nfinite automata and guarantees linear time matching on all inputs.\n" -homepage = "https://github.com/rust-lang/regex" -documentation = "https://docs.rs/regex" -readme = "README.md" -categories = ["text-processing"] -license = "MIT/Apache-2.0" -repository = "https://github.com/rust-lang/regex" -[profile.test] -debug = true - -[profile.bench] -debug = true - -[profile.release] -debug = true - -[lib] -bench = false - -[[test]] -name = "default" -path = "tests/test_default.rs" - -[[test]] -name = "default-bytes" -path = "tests/test_default_bytes.rs" - -[[test]] -name = "nfa" -path = "tests/test_nfa.rs" - -[[test]] -name = "nfa-utf8bytes" -path = "tests/test_nfa_utf8bytes.rs" - -[[test]] -name = "nfa-bytes" -path = "tests/test_nfa_bytes.rs" - -[[test]] -name = "backtrack" -path = "tests/test_backtrack.rs" - -[[test]] -name = "backtrack-utf8bytes" -path = "tests/test_backtrack_utf8bytes.rs" - -[[test]] -name = "backtrack-bytes" -path = "tests/test_backtrack_bytes.rs" -[dependencies.aho-corasick] -version = "0.6.0" - -[dependencies.memchr] -version = "2.0.0" - -[dependencies.regex-syntax] -version = "0.4.1" - -[dependencies.simd] -version = "0.2.1" -optional = true - -[dependencies.thread_local] -version = "0.3.2" - -[dependencies.utf8-ranges] -version = "1.0.0" -[dev-dependencies.lazy_static] -version = "1" - -[dev-dependencies.quickcheck] -version = "0.6" -default-features = false - -[dev-dependencies.rand] -version = "0.4" - -[features] -pattern = [] -simd-accel = ["simd"] -[badges.appveyor] -repository = "rust-lang-libs/regex" - -[badges.travis-ci] -repository = "rust-lang/regex" diff -Nru cargo-0.25.0/vendor/regex-0.2.6/CHANGELOG.md cargo-0.26.0/vendor/regex-0.2.6/CHANGELOG.md --- cargo-0.25.0/vendor/regex-0.2.6/CHANGELOG.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/CHANGELOG.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,334 +0,0 @@ -0.2.6 (2018-02-08) -================== -Bug fixes: - -* [BUG #446](https://github.com/rust-lang/regex/issues/446): - Fixes a bug in the new Boyer-Moore searcher that results in a match failure. - We fix this bug by temporarily disabling Boyer-Moore. - - -0.2.5 (2017-12-30) -================== -Bug fixes: - -* [BUG #437](https://github.com/rust-lang/regex/issues/437): - Fixes a bug in the new Boyer-Moore searcher that results in a panic. - - -0.2.4 (2017-12-30) -================== -New features: - -* [FEATURE #348](https://github.com/rust-lang/regex/pull/348): - Improve performance for capture searches on anchored regex. - (Contributed by @ethanpailes. Nice work!) -* [FEATURE #419](https://github.com/rust-lang/regex/pull/419): - Expand literal searching to include Tuned Boyer-Moore in some cases. - (Contributed by @ethanpailes. Nice work!) - -Bug fixes: - -* [BUG](https://github.com/rust-lang/regex/pull/436): - The regex compiler plugin has been removed. -* [BUG](https://github.com/rust-lang/regex/pull/436): - `simd` has been bumped to `0.2.1`, which fixes a Rust nightly build error. -* [BUG](https://github.com/rust-lang/regex/pull/436): - Bring the benchmark harness up to date. - - -0.2.3 (2017-11-30) -================== -New features: - -* [FEATURE #374](https://github.com/rust-lang/regex/pull/374): - Add `impl From<Match> for &str`. -* [FEATURE #380](https://github.com/rust-lang/regex/pull/380): - Derive `Clone` and `PartialEq` on `Error`. -* [FEATURE #400](https://github.com/rust-lang/regex/pull/400): - Update to Unicode 10. - -Bug fixes: - -* [BUG #375](https://github.com/rust-lang/regex/issues/375): - Fix a bug that prevented the bounded backtracker from terminating. -* [BUG #393](https://github.com/rust-lang/regex/issues/393), - [BUG #394](https://github.com/rust-lang/regex/issues/394): - Fix bug with `replace` methods for empty matches. - - -0.2.2 (2017-05-21) -================== -New features: - -* [FEATURE #341](https://github.com/rust-lang/regex/issues/341): - Support nested character classes and intersection operation. - For example, `[\p{Greek}&&\pL]` matches greek letters and - `[[0-9]&&[^4]]` matches every decimal digit except `4`. - (Much thanks to @robinst, who contributed this awesome feature.) - -Bug fixes: - -* [BUG #321](https://github.com/rust-lang/regex/issues/321): - Fix bug in literal extraction and UTF-8 decoding. -* [BUG #326](https://github.com/rust-lang/regex/issues/326): - Add documentation tip about the `(?x)` flag. -* [BUG #333](https://github.com/rust-lang/regex/issues/333): - Show additional replacement example using curly braces. -* [BUG #334](https://github.com/rust-lang/regex/issues/334): - Fix bug when resolving captures after a match. -* [BUG #338](https://github.com/rust-lang/regex/issues/338): - Add example that uses `Captures::get` to API documentation. -* [BUG #353](https://github.com/rust-lang/regex/issues/353): - Fix RegexSet bug that caused match failure in some cases. -* [BUG #354](https://github.com/rust-lang/regex/pull/354): - Fix panic in parser when `(?x)` is used. -* [BUG #358](https://github.com/rust-lang/regex/issues/358): - Fix literal optimization bug with RegexSet. -* [BUG #359](https://github.com/rust-lang/regex/issues/359): - Fix example code in README. -* [BUG #365](https://github.com/rust-lang/regex/pull/365): - Fix bug in `rure_captures_len` in the C binding. -* [BUG #367](https://github.com/rust-lang/regex/issues/367): - Fix byte class bug that caused a panic. - - -0.2.1 -===== -One major bug with `replace_all` has been fixed along with a couple of other -touchups. - -* [BUG #312](https://github.com/rust-lang/regex/issues/312): - Fix documentation for `NoExpand` to reference correct lifetime parameter. -* [BUG #314](https://github.com/rust-lang/regex/issues/314): - Fix a bug with `replace_all` when replacing a match with the empty string. -* [BUG #316](https://github.com/rust-lang/regex/issues/316): - Note a missing breaking change from the `0.2.0` CHANGELOG entry. - (`RegexBuilder::compile` was renamed to `RegexBuilder::build`.) -* [BUG #324](https://github.com/rust-lang/regex/issues/324): - Compiling `regex` should only require one version of `memchr` crate. - - -0.2.0 -===== -This is a new major release of the regex crate, and is an implementation of the -[regex 1.0 RFC](https://github.com/rust-lang/rfcs/blob/master/text/1620-regex-1.0.md). -We are releasing a `0.2` first, and if there are no major problems, we will -release a `1.0` shortly. For `0.2`, the minimum *supported* Rust version is -1.12. - -There are a number of **breaking changes** in `0.2`. They are split into two -types. The first type correspond to breaking changes in regular expression -syntax. The second type correspond to breaking changes in the API. - -Breaking changes for regex syntax: - -* POSIX character classes now require double bracketing. Previously, the regex - `[:upper:]` would parse as the `upper` POSIX character class. Now it parses - as the character class containing the characters `:upper:`. The fix to this - change is to use `[[:upper:]]` instead. Note that variants like - `[[:upper:][:blank:]]` continue to work. -* The character `[` must always be escaped inside a character class. -* The characters `&`, `-` and `~` must be escaped if any one of them are - repeated consecutively. For example, `[&]`, `[\&]`, `[\&\&]`, `[&-&]` are all - equivalent while `[&&]` is illegal. (The motivation for this and the prior - change is to provide a backwards compatible path for adding character class - set notation.) -* A `bytes::Regex` now has Unicode mode enabled by default (like the main - `Regex` type). This means regexes compiled with `bytes::Regex::new` that - don't have the Unicode flag set should add `(?-u)` to recover the original - behavior. - -Breaking changes for the regex API: - -* `find` and `find_iter` now **return `Match` values instead of - `(usize, usize)`.** `Match` values have `start` and `end` methods, which - return the match offsets. `Match` values also have an `as_str` method, - which returns the text of the match itself. -* The `Captures` type now only provides a single iterator over all capturing - matches, which should replace uses of `iter` and `iter_pos`. Uses of - `iter_named` should use the `capture_names` method on `Regex`. -* The `at` method on the `Captures` type has been renamed to `get`, and it - now returns a `Match`. Similarly, the `name` method on `Captures` now returns - a `Match`. -* The `replace` methods now return `Cow` values. The `Cow::Borrowed` variant - is returned when no replacements are made. -* The `Replacer` trait has been completely overhauled. This should only - impact clients that implement this trait explicitly. Standard uses of - the `replace` methods should continue to work unchanged. If you implement - the `Replacer` trait, please consult the new documentation. -* The `quote` free function has been renamed to `escape`. -* The `Regex::with_size_limit` method has been removed. It is replaced by - `RegexBuilder::size_limit`. -* The `RegexBuilder` type has switched from owned `self` method receivers to - `&mut self` method receivers. Most uses will continue to work unchanged, but - some code may require naming an intermediate variable to hold the builder. -* The `compile` method on `RegexBuilder` has been renamed to `build`. -* The free `is_match` function has been removed. It is replaced by compiling - a `Regex` and calling its `is_match` method. -* The `PartialEq` and `Eq` impls on `Regex` have been dropped. If you relied - on these impls, the fix is to define a wrapper type around `Regex`, impl - `Deref` on it and provide the necessary impls. -* The `is_empty` method on `Captures` has been removed. This always returns - `false`, so its use is superfluous. -* The `Syntax` variant of the `Error` type now contains a string instead of - a `regex_syntax::Error`. If you were examining syntax errors more closely, - you'll need to explicitly use the `regex_syntax` crate to re-parse the regex. -* The `InvalidSet` variant of the `Error` type has been removed since it is - no longer used. -* Most of the iterator types have been renamed to match conventions. If you - were using these iterator types explicitly, please consult the documentation - for its new name. For example, `RegexSplits` has been renamed to `Split`. - -A number of bugs have been fixed: - -* [BUG #151](https://github.com/rust-lang/regex/issues/151): - The `Replacer` trait has been changed to permit the caller to control - allocation. -* [BUG #165](https://github.com/rust-lang/regex/issues/165): - Remove the free `is_match` function. -* [BUG #166](https://github.com/rust-lang/regex/issues/166): - Expose more knobs (available in `0.1`) and remove `with_size_limit`. -* [BUG #168](https://github.com/rust-lang/regex/issues/168): - Iterators produced by `Captures` now have the correct lifetime parameters. -* [BUG #175](https://github.com/rust-lang/regex/issues/175): - Fix a corner case in the parsing of POSIX character classes. -* [BUG #178](https://github.com/rust-lang/regex/issues/178): - Drop the `PartialEq` and `Eq` impls on `Regex`. -* [BUG #179](https://github.com/rust-lang/regex/issues/179): - Remove `is_empty` from `Captures` since it always returns false. -* [BUG #276](https://github.com/rust-lang/regex/issues/276): - Position of named capture can now be retrieved from a `Captures`. -* [BUG #296](https://github.com/rust-lang/regex/issues/296): - Remove winapi/kernel32-sys dependency on UNIX. -* [BUG #307](https://github.com/rust-lang/regex/issues/307): - Fix error on emscripten. - - -0.1.80 -====== -* [PR #292](https://github.com/rust-lang/regex/pull/292): - Fixes bug #291, which was introduced by PR #290. - -0.1.79 -====== -* Require regex-syntax 0.3.8. - -0.1.78 -====== -* [PR #290](https://github.com/rust-lang/regex/pull/290): - Fixes bug #289, which caused some regexes with a certain combination - of literals to match incorrectly. - -0.1.77 -====== -* [PR #281](https://github.com/rust-lang/regex/pull/281): - Fixes bug #280 by disabling all literal optimizations when a pattern - is partially anchored. - -0.1.76 -====== -* Tweak criteria for using the Teddy literal matcher. - -0.1.75 -====== -* [PR #275](https://github.com/rust-lang/regex/pull/275): - Improves match verification performance in the Teddy SIMD searcher. -* [PR #278](https://github.com/rust-lang/regex/pull/278): - Replaces slow substring loop in the Teddy SIMD searcher with Aho-Corasick. -* Implemented DoubleEndedIterator on regex set match iterators. - -0.1.74 -====== -* Release regex-syntax 0.3.5 with a minor bug fix. -* Fix bug #272. -* Fix bug #277. -* [PR #270](https://github.com/rust-lang/regex/pull/270): - Fixes bugs #264, #268 and an unreported where the DFA cache size could be - drastically under estimated in some cases (leading to high unexpected memory - usage). - -0.1.73 -====== -* Release `regex-syntax 0.3.4`. -* Bump `regex-syntax` dependency version for `regex` to `0.3.4`. - -0.1.72 -====== -* [PR #262](https://github.com/rust-lang/regex/pull/262): - Fixes a number of small bugs caught by fuzz testing (AFL). - -0.1.71 -====== -* [PR #236](https://github.com/rust-lang/regex/pull/236): - Fix a bug in how suffix literals were extracted, which could lead - to invalid match behavior in some cases. - -0.1.70 -====== -* [PR #231](https://github.com/rust-lang/regex/pull/231): - Add SIMD accelerated multiple pattern search. -* [PR #228](https://github.com/rust-lang/regex/pull/228): - Reintroduce the reverse suffix literal optimization. -* [PR #226](https://github.com/rust-lang/regex/pull/226): - Implements NFA state compression in the lazy DFA. -* [PR #223](https://github.com/rust-lang/regex/pull/223): - A fully anchored RegexSet can now short-circuit. - -0.1.69 -====== -* [PR #216](https://github.com/rust-lang/regex/pull/216): - Tweak the threshold for running backtracking. -* [PR #217](https://github.com/rust-lang/regex/pull/217): - Add upper limit (from the DFA) to capture search (for the NFA). -* [PR #218](https://github.com/rust-lang/regex/pull/218): - Add rure, a C API. - -0.1.68 -====== -* [PR #210](https://github.com/rust-lang/regex/pull/210): - Fixed a performance bug in `bytes::Regex::replace` where `extend` was used - instead of `extend_from_slice`. -* [PR #211](https://github.com/rust-lang/regex/pull/211): - Fixed a bug in the handling of word boundaries in the DFA. -* [PR #213](https://github.com/rust-lang/pull/213): - Added RE2 and Tcl to the benchmark harness. Also added a CLI utility from - running regexes using any of the following regex engines: PCRE1, PCRE2, - Oniguruma, RE2, Tcl and of course Rust's own regexes. - -0.1.67 -====== -* [PR #201](https://github.com/rust-lang/regex/pull/201): - Fix undefined behavior in the `regex!` compiler plugin macro. -* [PR #205](https://github.com/rust-lang/regex/pull/205): - More improvements to DFA performance. Competitive with RE2. See PR for - benchmarks. -* [PR #209](https://github.com/rust-lang/regex/pull/209): - Release 0.1.66 was semver incompatible since it required a newer version - of Rust than previous releases. This PR fixes that. (And `0.1.66` was - yanked.) - -0.1.66 -====== -* Speculative support for Unicode word boundaries was added to the DFA. This - should remove the last common case that disqualified use of the DFA. -* An optimization that scanned for suffix literals and then matched the regular - expression in reverse was removed because it had worst case quadratic time - complexity. It was replaced with a more limited optimization where, given any - regex of the form `re$`, it will be matched in reverse from the end of the - haystack. -* [PR #202](https://github.com/rust-lang/regex/pull/202): - The inner loop of the DFA was heavily optimized to improve cache locality - and reduce the overall number of instructions run on each iteration. This - represents the first use of `unsafe` in `regex` (to elide bounds checks). -* [PR #200](https://github.com/rust-lang/regex/pull/200): - Use of the `mempool` crate (which used thread local storage) was replaced - with a faster version of a similar API in @Amanieu's `thread_local` crate. - It should reduce contention when using a regex from multiple threads - simultaneously. -* PCRE2 JIT benchmarks were added. A benchmark comparison can be found - [here](https://gist.github.com/anonymous/14683c01993e91689f7206a18675901b). - (Includes a comparison with PCRE1's JIT and Oniguruma.) -* A bug where word boundaries weren't being matched correctly in the DFA was - fixed. This only affected use of `bytes::Regex`. -* [#160](https://github.com/rust-lang/regex/issues/160): - `Captures` now has a `Debug` impl. diff -Nru cargo-0.25.0/vendor/regex-0.2.6/ci/after_success.sh cargo-0.26.0/vendor/regex-0.2.6/ci/after_success.sh --- cargo-0.25.0/vendor/regex-0.2.6/ci/after_success.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/ci/after_success.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,35 +0,0 @@ -#!/bin/bash - -# This runs only when a commit is pushed to master. It is responsible for -# updating docs and computing coverage statistics. - -set -e - -if [ "$TRAVIS_RUST_VERSION" != "nightly" ] || [ "$TRAVIS_PULL_REQUEST" != "false" ] || [ "$TRAVIS_BRANCH" != "master" ]; then - exit 0 -fi - -export RUSTFLAGS="-C target-feature=+ssse3" -env - -# Build and upload docs. -echo '<meta http-equiv=refresh content=0;url=regex/index.html>' > target/doc/index.html -ve=$(mktemp -d) -virtualenv "$ve" -"$ve"/bin/pip install --upgrade pip -"$ve"/bin/pip install ghp-import -"$ve"/bin/ghp-import -n target/doc -git push -qf https://${TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages - -# Install kcov. -tmp=$(mktemp -d) -pushd "$tmp" -wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz -tar zxf master.tar.gz -mkdir kcov-master/build -cd kcov-master/build -cmake .. -make -make install DESTDIR="$tmp" -popd -PATH="$tmp/usr/local/bin:$PATH" ./ci/run-kcov --coveralls-id $TRAVIS_JOB_ID diff -Nru cargo-0.25.0/vendor/regex-0.2.6/ci/run-kcov cargo-0.26.0/vendor/regex-0.2.6/ci/run-kcov --- cargo-0.25.0/vendor/regex-0.2.6/ci/run-kcov 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/ci/run-kcov 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -#!/bin/bash - -set -e - -tests=( - default - default_bytes - backtrack - backtrack_utf8bytes - backtrack_bytes - nfa - nfa_utf8bytes - nfa_bytes - regex -) -tmpdir=$(mktemp -d) -coveralls_id= - -while true; do - case "$1" in - --coveralls-id) - coveralls_id="$2" - shift 2 - ;; - *) - break - ;; - esac -done - -cargo test --no-run --verbose --jobs 4 -for t in ${tests[@]}; do - kcov \ - --verify \ - --include-pattern '/regex/src/' \ - "$tmpdir/$t" \ - $(find ./target/debug -executable -wholename "./target/debug/$t-*" | head -n1) -done - -if [ -n "$coveralls_id" ]; then - kcov --verify --coveralls-id=$coveralls_id --merge target/cov "$tmpdir"/* -else - kcov --verify --merge target/cov "$tmpdir"/* -fi diff -Nru cargo-0.25.0/vendor/regex-0.2.6/ci/run-shootout-test cargo-0.26.0/vendor/regex-0.2.6/ci/run-shootout-test --- cargo-0.25.0/vendor/regex-0.2.6/ci/run-shootout-test 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/ci/run-shootout-test 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -#!/bin/bash - -set -e - -cargo build --example shootout-regex-dna -diff \ - ./examples/regexdna-output.txt \ - <(./target/debug/examples/shootout-regex-dna < ./examples/regexdna-input.txt) - -cargo build --example shootout-regex-dna-single -diff \ - ./examples/regexdna-output.txt \ - <(./target/debug/examples/shootout-regex-dna-single < ./examples/regexdna-input.txt) - -cargo build --example shootout-regex-dna-cheat -diff \ - ./examples/regexdna-output.txt \ - <(./target/debug/examples/shootout-regex-dna-cheat < ./examples/regexdna-input.txt) diff -Nru cargo-0.25.0/vendor/regex-0.2.6/ci/script.sh cargo-0.26.0/vendor/regex-0.2.6/ci/script.sh --- cargo-0.25.0/vendor/regex-0.2.6/ci/script.sh 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/ci/script.sh 1970-01-01 00:00:00.000000000 +0000 @@ -1,52 +0,0 @@ -#!/bin/sh - -# This is the main CI script for testing the regex crate and its sub-crates. - -set -ex - -if [ "$TRAVIS_RUST_VERSION" = "nightly" ]; then - # We set this once so that all invocations share this setting. This should - # help with build times by avoiding excessive re-compiles. - export RUSTFLAGS="-C target-feature=+ssse3" -fi - -# Builds the regex crate and runs tests. -cargo build --verbose -cargo doc --verbose - -# If we're testing on an older version of Rust, then only check that we -# can build the crate. This is because the dev dependencies might be updated -# more frequently, and therefore might require a newer version of Rust. -# -# This isn't ideal. It's a compromise. -if [ "$TRAVIS_RUST_VERSION" = "1.12.0" ]; then - exit -fi - -# Run tests. If we have nightly, then enable our nightly features. -if [ "$TRAVIS_RUST_VERSION" = "nightly" ]; then - cargo test --verbose --features 'simd-accel pattern' -else - cargo test --verbose -fi - -# Run a test that confirms the shootout benchmarks are correct. -ci/run-shootout-test - -# Run tests on regex-syntax crate. -cargo test --verbose --manifest-path regex-syntax/Cargo.toml -cargo doc --verbose --manifest-path regex-syntax/Cargo.toml - -# Run tests on regex-capi crate. -cargo build --verbose --manifest-path regex-capi/Cargo.toml -(cd regex-capi/ctest && ./compile && LD_LIBRARY_PATH=../../target/debug ./test) -(cd regex-capi/examples && ./compile && LD_LIBRARY_PATH=../../target/debug ./iter) - -# Make sure benchmarks compile. Don't run them though because they take a -# very long time. Also, check that we can build the regex-debug tool. -if [ "$TRAVIS_RUST_VERSION" = "nightly" ]; then - cargo build --verbose --manifest-path regex-debug/Cargo.toml - for x in rust rust-bytes pcre1 onig; do - (cd bench && ./run $x --no-run --verbose) - done -fi diff -Nru cargo-0.25.0/vendor/regex-0.2.6/examples/regexdna-input.txt cargo-0.26.0/vendor/regex-0.2.6/examples/regexdna-input.txt --- cargo-0.25.0/vendor/regex-0.2.6/examples/regexdna-input.txt 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/examples/regexdna-input.txt 1970-01-01 00:00:00.000000000 +0000 @@ -1,1671 +0,0 @@ ->ONE Homo sapiens alu -GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGA -TCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACT -AAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAG -GCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCG -CCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGT -GGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCA -GGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAA -TTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAG -AATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCA -GCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGT -AATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACC -AGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTG -GTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACC -CGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAG -AGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTT -TGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACA -TGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCT -GTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGG -TTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGT -CTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGG -CGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCG -TCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTA -CTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCG -AGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCG -GGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACC -TGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAA -TACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGA -GGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACT -GCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTC -ACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGT -TCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGC -CGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCG -CTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTG -GGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCC -CAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCT -GGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGC -GCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGA -GGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGA -GACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGA -GGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTG -AAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAAT -CCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCA -GTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAA -AAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGC -GGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCT -ACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGG -GAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATC -GCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGC -GGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGG -TCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAA -AAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAG -GAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACT -CCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCC -TGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAG -ACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGC -GTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGA -ACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGA -CAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCA -CTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCA -ACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCG -CCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGG -AGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTC -CGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCG -AGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACC -CCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAG -CTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAG -CCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGG -CCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATC -ACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAA -AAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGC -TGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCC -ACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGG -CTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGG -AGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATT -AGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAA -TCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGC -CTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAA -TCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAG -CCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGT -GGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCG -GGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAG -CGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTG -GGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATG -GTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGT -AATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTT -GCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCT -CAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCG -GGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTC -TCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACT -CGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAG -ATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGG -CGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTG -AGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATA -CAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGG -CAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGC -ACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCAC -GCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTC -GAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCG -GGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCT -TGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGG -CGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCA -GCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGG -CCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGC -GCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGG -CGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGA -CTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGG -CCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAA -ACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCC -CAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGT -GAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAA -AGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGG -ATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTAC -TAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGA -GGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGC -GCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGG -TGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTC -AGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAA -ATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGA -GAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC -AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTG -TAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGAC -CAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGT -GGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAAC -CCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACA -GAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACT -TTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAAC -ATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCC -TGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAG -GTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCG -TCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAG -GCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCC -GTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCT -ACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCC -GAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCC -GGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCAC -CTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAA -ATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTG -AGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCAC -TGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCT -CACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAG -TTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAG -CCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATC -GCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCT -GGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATC -CCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCC -TGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGG -CGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG -AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCG -AGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGG -AGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGT -GAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAA -TCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGC -AGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCA -AAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGG -CGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTC -TACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCG -GGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGAT -CGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCG -CGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAG -GTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACA -AAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCA -GGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCAC -TCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGC -CTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGA -GACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGG -CGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTG -AACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCG -ACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGC -ACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCC -AACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGC -GCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCG -GAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACT -CCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCC -GAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAAC -CCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA -GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGA -GCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAG -GCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGAT -CACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTA -AAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGG -CTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGC -CACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTG -GCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAG -GAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAAT -TAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGA -ATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAG -CCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTA -ATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCA -GCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGG -TGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCC -GGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGA -GCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTT -GGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACAT -GGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTG -TAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGT -TGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTC -TCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGC -GGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGT -CTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTAC -TCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGA -GATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGG -GCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCT -GAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT -ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAG -GCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTG -CACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCA -CGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTT -CGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCC -GGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGC -TTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGG -GCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCC -AGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTG -GCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCG -CGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAG -GCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAG -ACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAG -GCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGA -AACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATC -CCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAG -TGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAA -AAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCG -GATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTA -CTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGG -AGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCG -CGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCG -GTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGT -CAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAA -AATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGG -AGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTC -CAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCT -GTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA -CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCG -TGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAA -CCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGAC -AGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCAC -TTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAA -CATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGC -CTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGA -GGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCC -GTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGA -GGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCC -CGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGC -TACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGC -CGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGC -CGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCA -CCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAA -AATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCT -GAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCA -CTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGC -TCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGA -GTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTA -GCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAAT -CGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCC -TGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAAT -CCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGC -CTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTG -GCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGG -GAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGC -GAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG -GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGG -TGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTA -ATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTG -CAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTC -AAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGG -GCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCT -CTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTC -GGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGA -TCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGC -GCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGA -GGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATAC -AAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGC -AGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCA -CTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACG -CCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCG -AGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGG -GCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTT -GAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGC -GACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAG -CACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGC -CAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCG -CGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGC -GGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGAC -TCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGC -CGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAA -CCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCC -AGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTG -AGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA -GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGA -TCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACT -AAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAG -GCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCG -CCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGT -GGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCA -GGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAA -TTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAG -AATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCA -GCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGT -AATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACC -AGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTG -GTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACC -CGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAG -AGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTT -TGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACA -TGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCT -GTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGG -TTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGT -CTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGG -CGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCG -TCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTA -CTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCG -AGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCG -GGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACC -TGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAA -TACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGA -GGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACT -GCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTC -ACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGT -TCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGC -CGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCG -CTTGAACCCGGGAGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTG -GGCGACAGAGCGAGACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCC -CAGCACTTTGGGAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCT -GGCCAACATGGTGAAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGC -GCGCGCCTGTAATCCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGA -GGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGA -GACTCCGTCTCAAAAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGA -GGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTG -AAACCCCGTCTCTACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAAT -CCCAGCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGGAGGCGGAGGTTGCA -GTGAGCCGAGATCGCGCCACTGCACTCCAGCCTGGGCGACAGAGCGAGACTCCGTCTCAA -AAAGGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGGGAGGCCGAGGCGGGC -GGATCACCTGAGGTCAGGAGTTCGAGACCAGCCTGGCCAACATGGTGAAACCCCGTCTCT -ACTAAAAATACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCAGCTACTCGG -GAGGCTGAGGCAGGAGAATC ->TWO IUB ambiguity codes -cttBtatcatatgctaKggNcataaaSatgtaaaDcDRtBggDtctttataattcBgtcg -tactDtDagcctatttSVHtHttKtgtHMaSattgWaHKHttttagacatWatgtRgaaa -NtactMcSMtYtcMgRtacttctWBacgaaatatagScDtttgaagacacatagtVgYgt -cattHWtMMWcStgttaggKtSgaYaaccWStcgBttgcgaMttBYatcWtgacaYcaga -gtaBDtRacttttcWatMttDBcatWtatcttactaBgaYtcttgttttttttYaaScYa -HgtgttNtSatcMtcVaaaStccRcctDaataataStcYtRDSaMtDttgttSagtRRca -tttHatSttMtWgtcgtatSSagactYaaattcaMtWatttaSgYttaRgKaRtccactt -tattRggaMcDaWaWagttttgacatgttctacaaaRaatataataaMttcgDacgaSSt -acaStYRctVaNMtMgtaggcKatcttttattaaaaagVWaHKYagtttttatttaacct -tacgtVtcVaattVMBcttaMtttaStgacttagattWWacVtgWYagWVRctDattBYt -gtttaagaagattattgacVatMaacattVctgtBSgaVtgWWggaKHaatKWcBScSWa -accRVacacaaactaccScattRatatKVtactatatttHttaagtttSKtRtacaaagt -RDttcaaaaWgcacatWaDgtDKacgaacaattacaRNWaatHtttStgttattaaMtgt -tgDcgtMgcatBtgcttcgcgaDWgagctgcgaggggVtaaScNatttacttaatgacag -cccccacatYScaMgtaggtYaNgttctgaMaacNaMRaacaaacaKctacatagYWctg -ttWaaataaaataRattagHacacaagcgKatacBttRttaagtatttccgatctHSaat -actcNttMaagtattMtgRtgaMgcataatHcMtaBSaRattagttgatHtMttaaKagg -YtaaBataSaVatactWtataVWgKgttaaaacagtgcgRatatacatVtHRtVYataSa -KtWaStVcNKHKttactatccctcatgWHatWaRcttactaggatctataDtDHBttata -aaaHgtacVtagaYttYaKcctattcttcttaataNDaaggaaaDYgcggctaaWSctBa -aNtgctggMBaKctaMVKagBaactaWaDaMaccYVtNtaHtVWtKgRtcaaNtYaNacg -gtttNattgVtttctgtBaWgtaattcaagtcaVWtactNggattctttaYtaaagccgc -tcttagHVggaYtgtNcDaVagctctctKgacgtatagYcctRYHDtgBattDaaDgccK -tcHaaStttMcctagtattgcRgWBaVatHaaaataYtgtttagMDMRtaataaggatMt -ttctWgtNtgtgaaaaMaatatRtttMtDgHHtgtcattttcWattRSHcVagaagtacg -ggtaKVattKYagactNaatgtttgKMMgYNtcccgSKttctaStatatNVataYHgtNa -BKRgNacaactgatttcctttaNcgatttctctataScaHtataRagtcRVttacDSDtt -aRtSatacHgtSKacYagttMHtWataggatgactNtatSaNctataVtttRNKtgRacc -tttYtatgttactttttcctttaaacatacaHactMacacggtWataMtBVacRaSaatc -cgtaBVttccagccBcttaRKtgtgcctttttRtgtcagcRttKtaaacKtaaatctcac -aattgcaNtSBaaccgggttattaaBcKatDagttactcttcattVtttHaaggctKKga -tacatcBggScagtVcacattttgaHaDSgHatRMaHWggtatatRgccDttcgtatcga -aacaHtaagttaRatgaVacttagattVKtaaYttaaatcaNatccRttRRaMScNaaaD -gttVHWgtcHaaHgacVaWtgttScactaagSgttatcttagggDtaccagWattWtRtg -ttHWHacgattBtgVcaYatcggttgagKcWtKKcaVtgaYgWctgYggVctgtHgaNcV -taBtWaaYatcDRaaRtSctgaHaYRttagatMatgcatttNattaDttaattgttctaa -ccctcccctagaWBtttHtBccttagaVaatMcBHagaVcWcagBVttcBtaYMccagat -gaaaaHctctaacgttagNWRtcggattNatcRaNHttcagtKttttgWatWttcSaNgg -gaWtactKKMaacatKatacNattgctWtatctaVgagctatgtRaHtYcWcttagccaa -tYttWttaWSSttaHcaaaaagVacVgtaVaRMgattaVcDactttcHHggHRtgNcctt -tYatcatKgctcctctatVcaaaaKaaaagtatatctgMtWtaaaacaStttMtcgactt -taSatcgDataaactaaacaagtaaVctaggaSccaatMVtaaSKNVattttgHccatca -cBVctgcaVatVttRtactgtVcaattHgtaaattaaattttYtatattaaRSgYtgBag -aHSBDgtagcacRHtYcBgtcacttacactaYcgctWtattgSHtSatcataaatataHt -cgtYaaMNgBaatttaRgaMaatatttBtttaaaHHKaatctgatWatYaacttMctctt -ttVctagctDaaagtaVaKaKRtaacBgtatccaaccactHHaagaagaaggaNaaatBW -attccgStaMSaMatBttgcatgRSacgttVVtaaDMtcSgVatWcaSatcttttVatag -ttactttacgatcaccNtaDVgSRcgVcgtgaacgaNtaNatatagtHtMgtHcMtagaa -attBgtataRaaaacaYKgtRccYtatgaagtaataKgtaaMttgaaRVatgcagaKStc -tHNaaatctBBtcttaYaBWHgtVtgacagcaRcataWctcaBcYacYgatDgtDHccta -aagacYRcaggattHaYgtKtaatgcVcaataMYacccatatcacgWDBtgaatcBaata -cKcttRaRtgatgaBDacggtaattaaYtataStgVHDtDctgactcaaatKtacaatgc -gYatBtRaDatHaactgtttatatDttttaaaKVccYcaaccNcBcgHaaVcattHctcg -attaaatBtatgcaaaaatYMctSactHatacgaWacattacMBgHttcgaatVaaaaca -BatatVtctgaaaaWtctRacgBMaatSgRgtgtcgactatcRtattaScctaStagKga -DcWgtYtDDWKRgRtHatRtggtcgaHgggcgtattaMgtcagccaBggWVcWctVaaat -tcgNaatcKWagcNaHtgaaaSaaagctcYctttRVtaaaatNtataaccKtaRgtttaM -tgtKaBtRtNaggaSattHatatWactcagtgtactaKctatttgRYYatKatgtccgtR -tttttatttaatatVgKtttgtatgtNtataRatWYNgtRtHggtaaKaYtKSDcatcKg -taaYatcSRctaVtSMWtVtRWHatttagataDtVggacagVcgKWagBgatBtaaagNc -aRtagcataBggactaacacRctKgttaatcctHgDgttKHHagttgttaatgHBtatHc -DaagtVaBaRccctVgtgDtacRHSctaagagcggWYaBtSaKtHBtaaactYacgNKBa -VYgtaacttagtVttcttaatgtBtatMtMtttaattaatBWccatRtttcatagVgMMt -agctStKctaMactacDNYgKYHgaWcgaHgagattacVgtttgtRaSttaWaVgataat -gtgtYtaStattattMtNgWtgttKaccaatagNYttattcgtatHcWtctaaaNVYKKt -tWtggcDtcgaagtNcagatacgcattaagaccWctgcagcttggNSgaNcHggatgtVt -catNtRaaBNcHVagagaaBtaaSggDaatWaatRccaVgggStctDaacataKttKatt -tggacYtattcSatcttagcaatgaVBMcttDattctYaaRgatgcattttNgVHtKcYR -aatRKctgtaaacRatVSagctgtWacBtKVatctgttttKcgtctaaDcaagtatcSat -aWVgcKKataWaYttcccSaatgaaaacccWgcRctWatNcWtBRttYaattataaNgac -acaatagtttVNtataNaYtaatRaVWKtBatKagtaatataDaNaaaaataMtaagaaS -tccBcaatNgaataWtHaNactgtcDtRcYaaVaaaaaDgtttRatctatgHtgttKtga -aNSgatactttcgagWaaatctKaaDaRttgtggKKagcDgataaattgSaacWaVtaNM -acKtcaDaaatttctRaaVcagNacaScRBatatctRatcctaNatWgRtcDcSaWSgtt -RtKaRtMtKaatgttBHcYaaBtgatSgaSWaScMgatNtctcctatttctYtatMatMt -RRtSaattaMtagaaaaStcgVgRttSVaScagtgDtttatcatcatacRcatatDctta -tcatVRtttataaHtattcYtcaaaatactttgVctagtaaYttagatagtSYacKaaac -gaaKtaaatagataatSatatgaaatSgKtaatVtttatcctgKHaatHattagaaccgt -YaaHactRcggSBNgtgctaaBagBttgtRttaaattYtVRaaaattgtaatVatttctc -ttcatgBcVgtgKgaHaaatattYatagWacNctgaaMcgaattStagWaSgtaaKagtt -ttaagaDgatKcctgtaHtcatggKttVDatcaaggtYcgccagNgtgcVttttagagat -gctaccacggggtNttttaSHaNtatNcctcatSaaVgtactgBHtagcaYggYVKNgta -KBcRttgaWatgaatVtagtcgattYgatgtaatttacDacSctgctaaaStttaWMagD -aaatcaVYctccgggcgaVtaaWtStaKMgDtttcaaMtVgBaatccagNaaatcYRMBg -gttWtaaScKttMWtYataRaDBMaDataatHBcacDaaKDactaMgagttDattaHatH -taYatDtattDcRNStgaatattSDttggtattaaNSYacttcDMgYgBatWtaMagact -VWttctttgYMaYaacRgHWaattgRtaagcattctMKVStatactacHVtatgatcBtV -NataaBttYtSttacKgggWgYDtgaVtYgatDaacattYgatggtRDaVDttNactaSa -MtgNttaacaaSaBStcDctaccacagacgcaHatMataWKYtaYattMcaMtgSttDag -cHacgatcaHttYaKHggagttccgatYcaatgatRaVRcaagatcagtatggScctata -ttaNtagcgacgtgKaaWaactSgagtMYtcttccaKtStaacggMtaagNttattatcg -tctaRcactctctDtaacWYtgaYaSaagaWtNtatttRacatgNaatgttattgWDDcN -aHcctgaaHacSgaataaRaataMHttatMtgaSDSKatatHHaNtacagtccaYatWtc -actaactatKDacSaStcggataHgYatagKtaatKagStaNgtatactatggRHacttg -tattatgtDVagDVaRctacMYattDgtttYgtctatggtKaRSttRccRtaaccttaga -gRatagSaaMaacgcaNtatgaaatcaRaagataatagatactcHaaYKBctccaagaRa -BaStNagataggcgaatgaMtagaatgtcaKttaaatgtaWcaBttaatRcggtgNcaca -aKtttScRtWtgcatagtttWYaagBttDKgcctttatMggNttattBtctagVtacata -aaYttacacaaRttcYtWttgHcaYYtaMgBaBatctNgcDtNttacgacDcgataaSat -YaSttWtcctatKaatgcagHaVaacgctgcatDtgttaSataaaaYSNttatagtaNYt -aDaaaNtggggacttaBggcHgcgtNtaaMcctggtVtaKcgNacNtatVaSWctWtgaW -cggNaBagctctgaYataMgaagatBSttctatacttgtgtKtaattttRagtDtacata -tatatgatNHVgBMtKtaKaNttDHaagatactHaccHtcatttaaagttVaMcNgHata -tKtaNtgYMccttatcaaNagctggacStttcNtggcaVtattactHaSttatgNMVatt -MMDtMactattattgWMSgtHBttStStgatatRaDaagattttctatMtaaaaaggtac -taaVttaSacNaatactgMttgacHaHRttgMacaaaatagttaatatWKRgacDgaRta -tatttattatcYttaWtgtBRtWatgHaaattHataagtVaDtWaVaWtgStcgtMSgaS -RgMKtaaataVacataatgtaSaatttagtcgaaHtaKaatgcacatcggRaggSKctDc -agtcSttcccStYtccRtctctYtcaaKcgagtaMttttcRaYDttgttatctaatcata -NctctgctatcaMatactataggDaHaaSttMtaDtcNatataattctMcStaaBYtaNa -gatgtaatHagagSttgWHVcttatKaYgDctcttggtgttMcRaVgSgggtagacaata -aDtaattSaDaNaHaBctattgNtaccaaRgaVtKNtaaYggHtaKKgHcatctWtctDt -ttctttggSDtNtaStagttataaacaattgcaBaBWggHgcaaaBtYgctaatgaaatW -cDcttHtcMtWWattBHatcatcaaatctKMagtDNatttWaBtHaaaNgMttaaStagt -tctctaatDtcRVaYttgttMtRtgtcaSaaYVgSWDRtaatagctcagDgcWWaaaBaa -RaBctgVgggNgDWStNaNBKcBctaaKtttDcttBaaggBttgaccatgaaaNgttttt -tttatctatgttataccaaDRaaSagtaVtDtcaWatBtacattaWacttaSgtattggD -gKaaatScaattacgWcagKHaaccaYcRcaRttaDttRtttHgaHVggcttBaRgtccc -tDatKaVtKtcRgYtaKttacgtatBtStaagcaattaagaRgBagSaattccSWYttta -ttVaataNctgHgttaaNBgcVYgtRtcccagWNaaaacaDNaBcaaaaRVtcWMgBagM -tttattacgDacttBtactatcattggaaatVccggttRttcatagttVYcatYaSHaHc -ttaaagcNWaHataaaRWtctVtRYtagHtaaaYMataHYtNBctNtKaatattStgaMc -BtRgctaKtgcScSttDgYatcVtggaaKtaagatWccHccgKYctaNNctacaWctttt -gcRtgtVcgaKttcMRHgctaHtVaataaDtatgKDcttatBtDttggNtacttttMtga -acRattaaNagaactcaaaBBVtcDtcgaStaDctgaaaSgttMaDtcgttcaccaaaag -gWtcKcgSMtcDtatgtttStaaBtatagDcatYatWtaaaBacaKgcaDatgRggaaYc -taRtccagattDaWtttggacBaVcHtHtaacDacYgtaatataMagaatgHMatcttat -acgtatttttatattacHactgttataMgStYaattYaccaattgagtcaaattaYtgta -tcatgMcaDcgggtcttDtKgcatgWRtataatatRacacNRBttcHtBgcRttgtgcgt -catacMtttBctatctBaatcattMttMYgattaaVYatgDaatVagtattDacaacDMa -tcMtHcccataagatgBggaccattVWtRtSacatgctcaaggggYtttDtaaNgNtaaB -atggaatgtctRtaBgBtcNYatatNRtagaacMgagSaSDDSaDcctRagtVWSHtVSR -ggaacaBVaccgtttaStagaacaMtactccagtttVctaaRaaHttNcttagcaattta -ttaatRtaaaatctaacDaBttggSagagctacHtaaRWgattcaaBtctRtSHaNtgta -cattVcaHaNaagtataccacaWtaRtaaVKgMYaWgttaKggKMtKcgWatcaDatYtK -SttgtacgaccNctSaattcDcatcttcaaaDKttacHtggttHggRRaRcaWacaMtBW -VHSHgaaMcKattgtaRWttScNattBBatYtaNRgcggaagacHSaattRtttcYgacc -BRccMacccKgatgaacttcgDgHcaaaaaRtatatDtatYVtttttHgSHaSaatagct -NYtaHYaVYttattNtttgaaaYtaKttWtctaNtgagaaaNctNDctaaHgttagDcRt -tatagccBaacgcaRBtRctRtggtaMYYttWtgataatcgaataattattataVaaaaa -ttacNRVYcaaMacNatRttcKatMctgaagactaattataaYgcKcaSYaatMNctcaa -cgtgatttttBacNtgatDccaattattKWWcattttatatatgatBcDtaaaagttgaa -VtaHtaHHtBtataRBgtgDtaataMttRtDgDcttattNtggtctatctaaBcatctaR -atgNacWtaatgaagtcMNaacNgHttatactaWgcNtaStaRgttaaHacccgaYStac -aaaatWggaYaWgaattattcMaactcBKaaaRVNcaNRDcYcgaBctKaacaaaaaSgc -tccYBBHYaVagaatagaaaacagYtctVccaMtcgtttVatcaatttDRtgWctagtac -RttMctgtDctttcKtWttttataaatgVttgBKtgtKWDaWagMtaaagaaattDVtag -gttacatcatttatgtcgMHaVcttaBtVRtcgtaYgBRHatttHgaBcKaYWaatcNSc -tagtaaaaatttacaatcactSWacgtaatgKttWattagttttNaggtctcaagtcact -attcttctaagKggaataMgtttcataagataaaaatagattatDgcBVHWgaBKttDgc -atRHaagcaYcRaattattatgtMatatattgHDtcaDtcaaaHctStattaatHaccga -cNattgatatattttgtgtDtRatagSacaMtcRtcattcccgacacSattgttKaWatt -NHcaacttccgtttSRtgtctgDcgctcaaMagVtBctBMcMcWtgtaacgactctcttR -ggRKSttgYtYatDccagttDgaKccacgVatWcataVaaagaataMgtgataaKYaaat -cHDaacgataYctRtcYatcgcaMgtNttaBttttgatttaRtStgcaacaaaataccVg -aaDgtVgDcStctatatttattaaaaRKDatagaaagaKaaYYcaYSgKStctccSttac -agtcNactttDVttagaaagMHttRaNcSaRaMgBttattggtttaRMggatggcKDgWR -tNaataataWKKacttcKWaaagNaBttaBatMHtccattaacttccccYtcBcYRtaga -ttaagctaaYBDttaNtgaaaccHcaRMtKtaaHMcNBttaNaNcVcgVttWNtDaBatg -ataaVtcWKcttRggWatcattgaRagHgaattNtatttctctattaattaatgaDaaMa -tacgttgggcHaYVaaNaDDttHtcaaHtcVVDgBVagcMacgtgttaaBRNtatRtcag -taagaggtttaagacaVaaggttaWatctccgtVtaDtcDatttccVatgtacNtttccg -tHttatKgScBatgtVgHtYcWagcaKtaMYaaHgtaattaSaHcgcagtWNaatNccNN -YcacgVaagaRacttctcattcccRtgtgtaattagcSttaaStWaMtctNNcSMacatt -ataaactaDgtatWgtagtttaagaaaattgtagtNagtcaataaatttgatMMYactaa -tatcggBWDtVcYttcDHtVttatacYaRgaMaacaStaatcRttttVtagaDtcacWat -ttWtgaaaagaaagNRacDtttStVatBaDNtaactatatcBSMcccaSttccggaMatg -attaaWatKMaBaBatttgataNctgttKtVaagtcagScgaaaDggaWgtgttttKtWt -atttHaatgtagttcactaaKMagttSYBtKtaYgaactcagagRtatagtVtatcaaaW -YagcgNtaDagtacNSaaYDgatBgtcgataacYDtaaactacagWDcYKaagtttatta -gcatcgagttKcatDaattgattatDtcagRtWSKtcgNtMaaaaacaMttKcaWcaaSV -MaaaccagMVtaMaDtMaHaBgaacataBBVtaatVYaNSWcSgNtDNaaKacacBttta -tKtgtttcaaHaMctcagtaacgtcgYtactDcgcctaNgagagcYgatattttaaattt -ccattttacatttDaaRctattttWctttacgtDatYtttcagacgcaaVttagtaaKaa -aRtgVtccataBggacttatttgtttaWNtgttVWtaWNVDaattgtatttBaagcBtaa -BttaaVatcHcaVgacattccNggtcgacKttaaaRtagRtctWagaYggtgMtataatM -tgaaRttattttgWcttNtDRRgMDKacagaaaaggaaaRStcccagtYccVattaNaaK -StNWtgacaVtagaagcttSaaDtcacaacgDYacWDYtgtttKatcVtgcMaDaSKStV -cgtagaaWaKaagtttcHaHgMgMtctataagBtKaaaKKcactggagRRttaagaBaaN -atVVcgRcKSttDaactagtSttSattgttgaaRYatggttVttaataaHttccaagDtg -atNWtaagHtgcYtaactRgcaatgMgtgtRaatRaNaacHKtagactactggaatttcg -ccataacgMctRgatgttaccctaHgtgWaYcactcacYaattcttaBtgacttaaacct -gYgaWatgBttcttVttcgttWttMcNYgtaaaatctYgMgaaattacNgaHgaacDVVM -tttggtHtctaaRgtacagacgHtVtaBMNBgattagcttaRcttacaHcRctgttcaaD -BggttKaacatgKtttYataVaNattccgMcgcgtagtRaVVaattaKaatggttRgaMc -agtatcWBttNtHagctaatctagaaNaaacaYBctatcgcVctBtgcaaagDgttVtga -HtactSNYtaaNccatgtgDacgaVtDcgKaRtacDcttgctaagggcagMDagggtBWR -tttSgccttttttaacgtcHctaVtVDtagatcaNMaVtcVacatHctDWNaataRgcgt -aVHaggtaaaaSgtttMtattDgBtctgatSgtRagagYtctSaKWaataMgattRKtaa -catttYcgtaacacattRWtBtcggtaaatMtaaacBatttctKagtcDtttgcBtKYYB -aKttctVttgttaDtgattttcttccacttgSaaacggaaaNDaattcYNNaWcgaaYat -tttMgcBtcatRtgtaaagatgaWtgaccaYBHgaatagataVVtHtttVgYBtMctaMt -cctgaDcYttgtccaaaRNtacagcMctKaaaggatttacatgtttaaWSaYaKttBtag -DacactagctMtttNaKtctttcNcSattNacttggaacaatDagtattRtgSHaataat -gccVgacccgatactatccctgtRctttgagaSgatcatatcgDcagWaaHSgctYYWta -tHttggttctttatVattatcgactaagtgtagcatVgtgHMtttgtttcgttaKattcM -atttgtttWcaaStNatgtHcaaaDtaagBaKBtRgaBgDtSagtatMtaacYaatYtVc -KatgtgcaacVaaaatactKcRgtaYtgtNgBBNcKtcttaccttKgaRaYcaNKtactt -tgagSBtgtRagaNgcaaaNcacagtVtttHWatgttaNatBgtttaatNgVtctgaata -tcaRtattcttttttttRaaKcRStctcggDgKagattaMaaaKtcaHacttaataataK -taRgDtKVBttttcgtKaggHHcatgttagHggttNctcgtatKKagVagRaaaggaaBt -NatttVKcRttaHctaHtcaaatgtaggHccaBataNaNaggttgcWaatctgatYcaaa -HaatWtaVgaaBttagtaagaKKtaaaKtRHatMaDBtBctagcatWtatttgWttVaaa -ScMNattRactttgtYtttaaaagtaagtMtaMaSttMBtatgaBtttaKtgaatgagYg -tNNacMtcNRacMMHcttWtgtRtctttaacaacattattcYaMagBaacYttMatcttK -cRMtgMNccattaRttNatHaHNaSaaHMacacaVaatacaKaSttHatattMtVatWga -ttttttaYctttKttHgScWaacgHtttcaVaaMgaacagNatcgttaacaaaaagtaca -HBNaattgttKtcttVttaaBtctgctacgBgcWtttcaggacacatMgacatcccagcg -gMgaVKaBattgacttaatgacacacaaaaaatRKaaBctacgtRaDcgtagcVBaacDS -BHaaaaSacatatacagacRNatcttNaaVtaaaataHattagtaaaaSWccgtatWatg -gDttaactattgcccatcttHaSgYataBttBaactattBtcHtgatcaataSttaBtat -KSHYttWggtcYtttBttaataccRgVatStaHaKagaatNtagRMNgtcttYaaSaact -cagDSgagaaYtMttDtMRVgWKWtgMaKtKaDttttgactatacataatcNtatNaHat -tVagacgYgatatatttttgtStWaaatctWaMgagaRttRatacgStgattcttaagaD -taWccaaatRcagcagaaNKagtaaDggcgccBtYtagSBMtactaaataMataBSacRM -gDgattMMgtcHtcaYDtRaDaacggttDaggcMtttatgttaNctaattaVacgaaMMt -aatDccSgtattgaRtWWaccaccgagtactMcgVNgctDctaMScatagcgtcaactat -acRacgHRttgctatttaatgaattataYKttgtaagWgtYttgcHgMtaMattWaWVta -RgcttgYgttBHtYataSccStBtgtagMgtDtggcVaaSBaatagDttgBgtctttctc -attttaNagtHKtaMWcYactVcgcgtatMVtttRacVagDaatcttgctBBcRDgcaac -KttgatSKtYtagBMagaRtcgBattHcBWcaactgatttaatttWDccatttatcgagS -KaWttataHactaHMttaatHtggaHtHagaatgtKtaaRactgtttMatacgatcaagD -gatKaDctataMggtHDtggHacctttRtatcttYattttgacttgaaSaataaatYcgB -aaaaccgNatVBttMacHaKaataagtatKgtcaagactcttaHttcggaattgttDtct -aaccHttttWaaatgaaatataaaWattccYDtKtaaaacggtgaggWVtctattagtga -ctattaagtMgtttaagcatttgSgaaatatccHaaggMaaaattttcWtatKctagDtY -tMcctagagHcactttactatacaaacattaacttaHatcVMYattYgVgtMttaaRtga -aataaDatcaHgtHHatKcDYaatcttMtNcgatYatgSaMaNtcttKcWataScKggta -tcttacgcttWaaagNatgMgHtctttNtaacVtgttcMaaRatccggggactcMtttaY -MtcWRgNctgNccKatcttgYDcMgattNYaRagatHaaHgKctcataRDttacatBatc -cattgDWttatttaWgtcggagaaaaatacaatacSNtgggtttccttacSMaagBatta -caMaNcactMttatgaRBacYcYtcaaaWtagctSaacttWgDMHgaggatgBVgcHaDt -ggaactttggtcNatNgtaKaBcccaNtaagttBaacagtatacDYttcctNgWgcgSMc -acatStctHatgRcNcgtacacaatRttMggaNKKggataaaSaYcMVcMgtaMaHtgat -tYMatYcggtcttcctHtcDccgtgRatcattgcgccgatatMaaYaataaYSggatagc -gcBtNtaaaScaKgttBgagVagttaKagagtatVaactaSacWactSaKatWccaKaaa -atBKgaaKtDMattttgtaaatcRctMatcaaMagMttDgVatggMaaWgttcgaWatga -aatttgRtYtattaWHKcRgctacatKttctaccaaHttRatctaYattaaWatVNccat -NgagtcKttKataStRaatatattcctRWatDctVagttYDgSBaatYgttttgtVaatt -taatagcagMatRaacttBctattgtMagagattaaactaMatVtHtaaatctRgaaaaa -aaatttWacaacaYccYDSaattMatgaccKtaBKWBattgtcaagcHKaagttMMtaat -ttcKcMagNaaKagattggMagaggtaatttYacatcWaaDgatMgKHacMacgcVaaca -DtaDatatYggttBcgtatgWgaSatttgtagaHYRVacaRtctHaaRtatgaactaata -tctSSBgggaaHMWtcaagatKgagtDaSatagttgattVRatNtctMtcSaagaSHaat -aNataataRaaRgattctttaataaagWaRHcYgcatgtWRcttgaaggaMcaataBRaa -ccagStaaacNtttcaatataYtaatatgHaDgcStcWttaacctaRgtYaRtataKtgM -ttttatgactaaaatttacYatcccRWtttHRtattaaatgtttatatttgttYaatMca -RcSVaaDatcgtaYMcatgtagacatgaaattgRtcaaYaaYtRBatKacttataccaNa -aattVaBtctggacaagKaaYaaatatWtMtatcYaaVNtcgHaactBaagKcHgtctac -aatWtaDtSgtaHcataHtactgataNctRgttMtDcDttatHtcgtacatcccaggStt -aBgtcacacWtccNMcNatMVaVgtccDYStatMaccDatggYaRKaaagataRatttHK -tSaaatDgataaacttaHgttgVBtcttVttHgDacgaKatgtatatNYataactctSat -atatattgcHRRYttStggaactHgttttYtttaWtatMcttttctatctDtagVHYgMR -BgtHttcctaatYRttKtaagatggaVRataKDctaMtKBNtMtHNtWtttYcVtattMc -gRaacMcctNSctcatttaaagDcaHtYccSgatgcaatYaaaaDcttcgtaWtaattct -cgttttScttggtaatctttYgtctaactKataHacctMctcttacHtKataacacagcN -RatgKatttttSaaatRYcgDttaMRcgaaattactMtgcgtaagcgttatBtttttaat -taagtNacatHgttcRgacKcBBtVgatKttcgaBaatactDRgtRtgaNacWtcacYtt -aaKcgttctHaKttaNaMgWgWaggtctRgaKgWttSttBtDcNtgtttacaaatYcDRt -gVtgcctattcNtctaaaDMNttttNtggctgagaVctDaacVtWccaagtaacacaNct -gaScattccDHcVBatcgatgtMtaatBgHaatDctMYgagaatgYWKcctaatNaStHa -aaKccgHgcgtYaaYtattgtStgtgcaaRtattaKatattagaWVtcaMtBagttatta -gNaWHcVgcaattttDcMtgtaRHVYtHtctgtaaaaHVtMKacatcgNaatttMatatg -ttgttactagWYtaRacgataKagYNKcattataNaRtgaacKaYgcaaYYacaNccHat -MatDcNgtHttRaWttagaaDcaaaaaatagggtKDtStaDaRtaVtHWKNtgtattVct -SVgRgataDaRaWataBgaagaaKtaataaYgDcaStaNgtaDaaggtattHaRaWMYaY -aWtggttHYgagVtgtgcttttcaaDKcagVcgttagacNaaWtagtaataDttctggtt -VcatcataaagtgKaaaNaMtaBBaattaatWaattgctHaVKaSgDaaVKaHtatatat -HatcatSBagNgHtatcHYMHgttDgtaHtBttWatcgtttaRaattgStKgSKNWKatc -agDtctcagatttctRtYtBatBgHHtKaWtgYBgacVVWaKtacKcDttKMaKaVcggt -gttataagaataaHaatattagtataatMHgttYgaRttagtaRtcaaVatacggtcMcg -agtaaRttacWgactKRYataaaagSattYaWgagatYagKagatgSaagKgttaatMgg -tataatgttWYttatgagaaacctNVataatHcccKtDctcctaatactggctHggaSag -gRtKHaWaattcgSatMatttagaggcYtctaMcgctcataSatatgRagacNaaDagga -VBagaYttKtacNaKgtSYtagttggaWcatcWttaatctatgaVtcgtgtMtatcaYcg -tRccaaYgDctgcMgtgtWgacWtgataacacgcgctBtgttaKtYDtatDcatcagKaV -MctaatcttgVcaaRgcRMtDcgattaHttcaNatgaatMtactacVgtRgatggaWttt -actaaKatgagSaaKggtaNtactVaYtaaKRagaacccacaMtaaMtKtatBcttgtaa -WBtMctaataaVcDaaYtcRHBtcgttNtaaHatttBNgRStVDattBatVtaagttaYa -tVattaagaBcacggtSgtVtatttaRattgatgtaHDKgcaatattKtggcctatgaWD -KRYcggattgRctatNgatacaatMNttctgtcRBYRaaaHctNYattcHtaWcaattct -BtMKtVgYataatMgYtcagcttMDataVtggRtKtgaatgccNcRttcaMtRgattaac -attRcagcctHtWMtgtDRagaKaBtgDttYaaaaKatKgatctVaaYaacWcgcatagB -VtaNtRtYRaggBaaBtgKgttacataagagcatgtRattccacttaccatRaaatgWgD -aMHaYVgVtaSctatcgKaatatattaDgacccYagtgtaYNaaatKcagtBRgagtcca -tgKgaaaccBgaagBtgSttWtacgatWHaYatcgatttRaaNRgcaNaKVacaNtDgat -tgHVaatcDaagcgtatgcNttaDataatcSataaKcaataaHWataBtttatBtcaKtK -tatagttaDgSaYctacaRatNtaWctSaatatttYaKaKtaccWtatcRagacttaYtt -VcKgSDcgagaagatccHtaattctSttatggtKYgtMaHagVaBRatttctgtRgtcta -tgggtaHKgtHacHtSYacgtacacHatacKaaBaVaccaDtatcSaataaHaagagaat -ScagactataaRttagcaaVcaHataKgDacatWccccaagcaBgagWatctaYttgaaa -tctVNcYtttWagHcgcgcDcVaaatgttKcHtNtcaatagtgtNRaactttttcaatgg -WgBcgDtgVgtttctacMtaaataaaRggaaacWaHttaRtNtgctaaRRtVBctYtVta -tDcattDtgaccYatagatYRKatNYKttNgcctagtaWtgaactaMVaacctgaStttc -tgaKVtaaVaRKDttVtVctaDNtataaaDtccccaagtWtcgatcactDgYaBcatcct -MtVtacDaaBtYtMaKNatNtcaNacgDatYcatcgcaRatWBgaacWttKttagYtaat -tcggttgSWttttDWctttacYtatatWtcatDtMgtBttgRtVDggttaacYtacgtac -atgaattgaaWcttMStaDgtatattgaDtcRBcattSgaaVBRgagccaaKtttcDgcg -aSMtatgWattaKttWtgDBMaggBBttBaatWttRtgcNtHcgttttHtKtcWtagHSt -aacagttgatatBtaWSaWggtaataaMttaKacDaatactcBttcaatatHttcBaaSa -aatYggtaRtatNtHcaatcaHtagVtgtattataNggaMtcttHtNagctaaaggtaga -YctMattNaMVNtcKtactBKcaHHcBttaSagaKacataYgctaKaYgttYcgacWVtt -WtSagcaacatcccHaccKtcttaacgaKttcacKtNtacHtatatRtaaatacactaBt -ttgaHaRttggttWtatYagcatYDatcggagagcWBataagRtacctataRKgtBgatg -aDatataSttagBaHtaatNtaDWcWtgtaattacagKttcNtMagtattaNgtctcgtc -ctcttBaHaKcKccgtRcaaYagSattaagtKataDatatatagtcDtaacaWHcaKttD -gaaRcgtgYttgtcatatNtatttttatggccHtgDtYHtWgttatYaacaattcaWtat -NgctcaaaSttRgctaatcaaatNatcgtttaBtNNVtgttataagcaaagattBacgtD -atttNatttaaaDcBgtaSKgacgtagataatttcHMVNttgttBtDtgtaWKaaRMcKM -tHtaVtagataWctccNNaSWtVaHatctcMgggDgtNHtDaDttatatVWttgttattt -aacctttcacaaggaSaDcggttttttatatVtctgVtaacaStDVaKactaMtttaSNa -gtgaaattaNacttSKctattcctctaSagKcaVttaagNaVcttaVaaRNaHaaHttat -gtHttgtgatMccaggtaDcgaccgtWgtWMtttaHcRtattgScctatttKtaaccaag -tYagaHgtWcHaatgccKNRtttagtMYSgaDatctgtgaWDtccMNcgHgcaaacNDaa -aRaStDWtcaaaaHKtaNBctagBtgtattaactaattttVctagaatggcWSatMaccc -ttHttaSgSgtgMRcatRVKtatctgaaaccDNatYgaaVHNgatMgHRtacttaaaRta -tStRtDtatDttYatattHggaBcttHgcgattgaKcKtttcRataMtcgaVttWacatN -catacctRataDDatVaWNcggttgaHtgtMacVtttaBHtgagVttMaataattatgtt -cttagtttgtgcDtSatttgBtcaacHattaaBagVWcgcaSYttMgcttacYKtVtatc -aYaKctgBatgcgggcYcaaaaacgNtctagKBtattatctttKtaVttatagtaYtRag -NtaYataaVtgaatatcHgcaaRataHtacacatgtaNtgtcgYatWMatttgaactacR -ctaWtWtatacaatctBatatgYtaagtatgtgtatSttactVatcttYtaBcKgRaSgg -RaaaaatgcagtaaaWgtaRgcgataatcBaataccgtatttttccatcNHtatWYgatH -SaaaDHttgctgtccHtggggcctaataatttttctatattYWtcattBtgBRcVttaVM -RSgctaatMagtYtttaaaaatBRtcBttcaaVtaacagctccSaaSttKNtHtKYcagc -agaaaccccRtttttaaDcDtaStatccaagcgctHtatcttaDRYgatDHtWcaaaBcW -gKWHttHataagHacgMNKttMKHccaYcatMVaacgttaKgYcaVaaBtacgcaacttt -MctaaHaatgtBatgagaSatgtatgSRgHgWaVWgataaatatttccKagVgataattW -aHNcYggaaatgctHtKtaDtctaaagtMaatVDVactWtSaaWaaMtaHtaSKtcBRaN -cttStggtBttacNagcatagRgtKtgcgaacaacBcgKaatgataagatgaaaattgta -ctgcgggtccHHWHaaNacaBttNKtKtcaaBatatgctaHNgtKcDWgtttatNgVDHg -accaacWctKaaggHttgaRgYaatHcaBacaatgagcaaattactgtaVaaYaDtagat -tgagNKggtggtgKtWKaatacagDRtatRaMRtgattDggtcaaYRtatttNtagaDtc -acaaSDctDtataatcgtactaHttatacaatYaacaaHttHatHtgcgatRRttNgcat -SVtacWWgaaggagtatVMaVaaattScDDKNcaYBYaDatHgtctatBagcaacaagaa -tgagaaRcataaKNaRtBDatcaaacgcattttttaaBtcSgtacaRggatgtMNaattg -gatatWtgagtattaaaVctgcaYMtatgatttttYgaHtgtcttaagWBttHttgtctt -attDtcgtatWtataataSgctaHagcDVcNtaatcaagtaBDaWaDgtttagYctaNcc -DtaKtaHcttaataacccaRKtacaVaatNgcWRaMgaattatgaBaaagattVYaHMDc -aDHtcRcgYtcttaaaWaaaVKgatacRtttRRKYgaatacaWVacVcRtatMacaBtac -tggMataaattttHggNagSctacHgtBagcgtcgtgattNtttgatSaaggMttctttc -ttNtYNagBtaaacaaatttMgaccttacataattgYtcgacBtVMctgStgMDtagtaR -ctHtatgttcatatVRNWataDKatWcgaaaaagttaaaagcacgHNacgtaatctttMR -tgacttttDacctataaacgaaatatgattagaactccSYtaBctttaataacWgaaaYa -tagatgWttcatKtNgatttttcaagHtaYgaaRaDaagtaggagcttatVtagtctttc -attaaaatcgKtattaRttacagVaDatgcatVgattgggtctttHVtagKaaRBtaHta -aggccccaaaaKatggtttaMWgtBtaaacttcactttKHtcgatctccctaYaBacMgt -cttBaBaNgcgaaacaatctagtHccHtKttcRtRVttccVctttcatacYagMVtMcag -aMaaacaataBctgYtaatRaaagattaaccatVRatHtaRagcgcaBcgDttStttttc -VtttaDtKgcaaWaaaaatSccMcVatgtKgtaKgcgatatgtagtSaaaDttatacaaa -catYaRRcVRHctKtcgacKttaaVctaDaatgttMggRcWaacttttHaDaKaDaBctg -taggcgtttaHBccatccattcNHtDaYtaataMttacggctNVaacDattgatatttta -cVttSaattacaaRtataNDgacVtgaacataVRttttaDtcaaacataYDBtttaatBa -DtttYDaDaMccMttNBttatatgagaaMgaNtattHccNataattcaHagtgaaggDga -tgtatatatgYatgaStcataaBStWacgtcccataRMaaDattggttaaattcMKtctM -acaBSactcggaatDDgatDgcWctaacaccgggaVcacWKVacggtaNatatacctMta -tgatagtgcaKagggVaDtgtaacttggagtcKatatcgMcttRaMagcattaBRaStct -YSggaHYtacaactMBaagDcaBDRaaacMYacaHaattagcattaaaHgcgctaaggSc -cKtgaaKtNaBtatDDcKBSaVtgatVYaagVtctSgMctacgttaacWaaattctSgtD -actaaStaaattgcagBBRVctaatatacctNttMcRggctttMttagacRaHcaBaacV -KgaataHttttMgYgattcYaNRgttMgcVaaacaVVcDHaatttgKtMYgtatBtVVct -WgVtatHtacaaHttcacgatagcagtaaNattBatatatttcVgaDagcggttMaagtc -ScHagaaatgcYNggcgtttttMtStggtRatctacttaaatVVtBacttHNttttaRca -aatcacagHgagagtMgatcSWaNRacagDtatactaaDKaSRtgattctccatSaaRtt -aaYctacacNtaRtaactggatgaccYtacactttaattaattgattYgttcagDtNKtt -agDttaaaaaaaBtttaaNaYWKMBaaaacVcBMtatWtgBatatgaacVtattMtYatM -NYDKNcKgDttDaVtaaaatgggatttctgtaaatWtctcWgtVVagtcgRgacttcccc -taDcacagcRcagagtgtWSatgtacatgttaaSttgtaaHcgatgggMagtgaacttat -RtttaVcaccaWaMgtactaatSSaHtcMgaaYtatcgaaggYgggcgtgaNDtgttMNg -aNDMtaattcgVttttaacatgVatgtWVMatatcaKgaaattcaBcctccWcttgaaWH -tWgHtcgNWgaRgctcBgSgaattgcaaHtgattgtgNagtDttHHgBttaaWcaaWagc -aSaHHtaaaVctRaaMagtaDaatHtDMtcVaWMtagSagcttHSattaacaaagtRacM -tRtctgttagcMtcaBatVKtKtKacgagaSNatSactgtatatcBctgagVtYactgta -aattaaaggcYgDHgtaacatSRDatMMccHatKgttaacgactKtgKagtcttcaaHRV -tccttKgtSataatttacaactggatDNgaacttcaRtVaagDcaWatcBctctHYatHa -DaaatttagYatSatccaWtttagaaatVaacBatHcatcgtacaatatcgcNYRcaata -YaRaYtgattVttgaatgaVaactcRcaNStgtgtattMtgaggtNttBaDRcgaaaagc -tNgBcWaWgtSaDcVtgVaatMKBtttcgtttctaaHctaaagYactgMtatBDtcStga -ccgtSDattYaataHctgggaYYttcggttaWaatctggtRagWMaDagtaacBccacta -cgHWMKaatgatWatcctgHcaBaSctVtcMtgtDttacctaVgatYcWaDRaaaaRtag -atcgaMagtggaRaWctctgMgcWttaagKBRtaaDaaWtctgtaagYMttactaHtaat -cttcataacggcacBtSgcgttNHtgtHccatgttttaaagtatcgaKtMttVcataYBB -aKtaMVaVgtattNDSataHcagtWMtaggtaSaaKgttgBtVtttgttatcatKcgHac -acRtctHatNVagSBgatgHtgaRaSgttRcctaacaaattDNttgacctaaYtBgaaaa -tagttattactcttttgatgtNNtVtgtatMgtcttRttcatttgatgacacttcHSaaa -ccaWWDtWagtaRDDVNacVaRatgttBccttaatHtgtaaacStcVNtcacaSRttcYa -gacagaMMttttgMcNttBcgWBtactgVtaRttctccaaYHBtaaagaBattaYacgat -ttacatctgtaaMKaRYtttttactaaVatWgctBtttDVttctggcDaHaggDaagtcg -aWcaagtagtWttHtgKtVataStccaMcWcaagataagatcactctHatgtcYgaKcat -cagatactaagNSStHcctRRNtattgtccttagttagMVgtatagactaactctVcaat -MctgtttgtgttgccttatWgtaBVtttctggMcaaKgDWtcgtaaYStgSactatttHg -atctgKagtagBtVacRaagRtMctatgggcaaaKaaaatacttcHctaRtgtDcttDat -taggaaatttcYHaRaaBttaatggcacKtgctHVcaDcaaaVDaaaVcgMttgtNagcg -taDWgtcgttaatDgKgagcSatatcSHtagtagttggtgtHaWtaHKtatagctgtVga -ttaBVaatgaataagtaatVatSttaHctttKtttgtagttaccttaatcgtagtcctgB -cgactatttVcMacHaaaggaatgDatggKtaHtgStatattaaSagctWcctccRtata -BaDYcgttgcNaagaggatRaaaYtaWgNtSMcaatttactaacatttaaWttHtatBat -tgtcgacaatNgattgcNgtMaaaKaBDattHacttggtRtttaYaacgVactBtaBaKt -gBttatgVttgtVttcaatcWcNctDBaaBgaDHacBttattNtgtDtatttVSaaacag -gatgcRatSgtaSaNtgBatagttcHBgcBBaaattaHgtDattatDaKaatBaaYaaMa -ataaataKtttYtagtBgMatNcatgtttgaNagtgttgtgKaNaSagtttgaSMaYBca -aaacDStagttVacaaaaactaaWttBaagtctgtgcgtMgtaattctcctacctcaNtt -taaccaaaaVtBcacataacaccccBcWMtatVtggaatgaWtcaaWaaaaaaaaWtDta -atatRcctDWtcctaccMtVVatKttaWaaKaaatataaagScHBagaggBaSMtaWaVt -atattactSaaaKNaactatNatccttgaYctattcaaaVgatttYHcRagattttaSat -aggttattcVtaaagaKgtattattKtRttNcggcRgtgtgtWYtaacHgKatKgatYta -cYagDtWcHBDctctgRaYKaYagcactKcacSaRtBttttBHKcMtNtcBatttatttt -tgSatVgaaagaWtcDtagDatatgMacaacRgatatatgtttgtKtNRaatatNatgYc -aHtgHataacKtgagtagtaacYttaNccaaatHcacaacaVDtagtaYtccagcattNt -acKtBtactaaagaBatVtKaaHBctgStgtBgtatgaSNtgDataaccctgtagcaBgt -gatcttaDataStgaMaccaSBBgWagtacKcgattgaDgNNaaaacacagtSatBacKD -gcgtataBKcatacactaSaatYtYcDaactHttcatRtttaatcaattataRtttgtaa -gMcgNttcatcBtYBagtNWNMtSHcattcRctttttRWgaKacKttgggagBcgttcgc -MaWHtaatactgtctctatttataVgtttaBScttttaBMaNaatMacactYtBMggtHa -cMagtaRtctgcatttaHtcaaaatttgagKtgNtactBacaHtcgtatttctMaSRagc -agttaatgtNtaaattgagagWcKtaNttagVtacgatttgaatttcgRtgtWcVatcgt -taaDVctgtttBWgaccagaaagtcSgtVtatagaBccttttcctaaattgHtatcggRa -ttttcaaggcYSKaagWaWtRactaaaacccBatMtttBaatYtaagaactSttcgaaSc -aatagtattgaccaagtgttttctaacatgtttNVaatcaaagagaaaNattaaRtttta -VaaaccgcaggNMtatattVctcaagaggaacgBgtttaacaagttcKcYaatatactaa -ccBaaaSggttcNtattctagttRtBacgScVctcaatttaatYtaaaaaaatgSaatga -tagaMBRatgRcMcgttgaWHtcaVYgaatYtaatctttYttatRaWtctgBtDcgatNa -tcKaBaDgatgtaNatWKctccgatattaacattNaaacDatgBgttctgtDtaaaMggt -gaBaSHataacgccSctaBtttaRBtcNHcDatcDcctagagtcRtaBgWttDRVHagat -tYatgtatcWtaHtttYcattWtaaagtctNgtStggRNcgcggagSSaaagaaaatYcH -DtcgctttaatgYcKBVSgtattRaYBaDaaatBgtatgaHtaaRaRgcaSWNtagatHa -acttNctBtcaccatctMcatattccaSatttgcgaDagDgtatYtaaaVDtaagtttWV -aagtagYatRttaagDcNgacKBcScagHtattatcDaDactaaaaaYgHttBcgaDttg -gataaaKSRcBMaBcgaBSttcWtgNBatRaccgattcatttataacggHVtaattcaca -agagVttaaRaatVVRKcgWtVgacctgDgYaaHaWtctttcacMagggatVgactagMa -aataKaaNWagKatagNaaWtaaaatttgaattttatttgctaaVgaHatBatcaaBWcB -gttcMatcgBaaNgttcgSNaggSaRtttgHtRtattaNttcDcatSaVttttcgaaaaa -ttgHatctaRaggSaNatMDaaatDcacgattttagaHgHaWtYgattaatHNSttatMS -gggNtcKtYatRggtttgtMWVtttaYtagcagBagHaYagttatatggtBacYcattaR -SataBatMtttaaatctHcaaaSaaaagttNSaaWcWRccRtKaagtBWtcaaattSttM -tattggaaaccttaacgttBtWatttatatWcDaatagattcctScacctaagggRaaYt -aNaatgVtBcttaaBaacaMVaaattatStYgRcctgtactatcMcVKatttcgSgatRH -MaaaHtagtaaHtVgcaaataatatcgKKtgccaatBNgaaWcVttgagttaKatagttc -aggKDatDtattgaKaVcaKtaataDataataHSaHcattagttaatRVYcNaHtaRcaa -ggtNHcgtcaaccaBaaagYtHWaaaRcKgaYaaDttgcWYtataRgaatatgtYtgcKt -aNttWacatYHctRaDtYtattcBttttatcSataYaYgttWaRagcacHMgtttHtYtt -YaatcggtatStttcgtRSattaaDaKMaatatactaNBaWgctacacYtgaYVgtgHta -aaRaaRgHtagtWattataaaSDaaWtgMattatcgaaaagtaYRSaWtSgNtBgagcRY -aMDtactaacttaWgtatctagacaagNtattHggataatYttYatcataDcgHgttBtt -ctttVttgccgaaWtaaaacgKgtatctaaaaaNtccDtaDatBMaMggaatNKtatBaa -atVtccRaHtaSacataHattgtttKVYattcataVaattWtcgtgMttcttKtgtctaa -cVtatctatatBRataactcgKatStatattcatHHRttKtccaacgtgggtgRgtgaMt -attattggctatcgtgacMtRcBDtcttgtactaatRHttttaagatcgVMDStattatY -BtttDttgtBtNttgRcMtYtgBacHaWaBaatDKctaagtgaaactaatgRaaKgatcc -aagNaaaatattaggWNtaagtatacttttKcgtcggSYtcttgRctataYcttatataa -agtatattaatttataVaacacaDHatctatttttKYVatHRactttaBHccaWagtact -BtcacgaVgcgttRtttttttSVgtSagtBaaattctgaHgactcttgMcattttagVta -agaattHctHtcaDaaNtaacRggWatagttcgtSttgaDatcNgNagctagDgatcNtt -KgttgtaDtctttRaaYStRatDtgMggactSttaDtagSaVtBDttgtDgccatcacaM -attaaaMtNacaVcgSWcVaaDatcaHaatgaattaMtatccVtctBtaattgtWattat -BRcWcaatgNNtactWYtDaKttaaatcactcagtRaaRgatggtKgcgccaaHgaggat -StattYcaNMtcaBttacttatgagDaNtaMgaaWtgtttcttctaHtMNgttatctaWW -atMtBtaaatagDVatgtBYtatcggcttaagacMRtaHScgatatYgRDtcattatSDa -HggaaataNgaWSRRaaaBaatagBattaDctttgHWNttacaataaaaaaatacggttt -gHgVtaHtWMttNtBtctagtMcgKMgHgYtataHaNagWtcaacYattaataYRgtaWK -gaBctataaccgatttaHaNBRaRaMtccggtNgacMtctcatttgcaattcWgMactta -caaDaaNtactWatVtttagccttMaatcagVaagtctVaaDaBtattaattaYtNaYtg -gattaKtaKctYaMtattYgatattataatKtVgDcttatatNBtcgttgtStttttMag -aggttaHYSttcKgtcKtDNtataagttataagSgttatDtRttattgttttSNggRtca -aKMNatgaatattgtBWtaMacctgggYgaSgaagYataagattacgagaatBtggtRcV -HtgYggaDgaYaKagWagctatagacgaaHgtWaNgacttHRatVaWacKYtgRVNgVcS -gRWctacatcKSactctgWYtBggtataagcttNRttVtgRcaWaaatDMatYattaact -ttcgaagRatSctgccttgcRKaccHtttSNVagtagHagBagttagaccaRtataBcca -taatSHatRtcHagacBWatagcaMtacaRtgtgaaBatctKRtScttccaNaatcNgta -atatWtcaMgactctBtWtaaNactHaaaaRctcgcatggctMcaaNtcagaaaaacaca -gtggggWttRttagtaagaVctVMtcgaatcttcMaaaHcaHBttcgattatgtcaDagc -YRtBtYcgacMgtDcagcgaNgttaataatagcagKYYtcgtaBtYctMaRtaRtDagaa -aacacatgYaBttgattattcgaaNttBctSataaMataWRgaHtttccgtDgaYtatgg -tDgHKgMtatttVtMtVagttaRatMattRagataaccctKctMtSttgaHagtcStcta -tttccSagatgttccacgaggYNttHRacgattcDatatDcataaaatBBttatcgaHtN -HaaatatDNaggctgaNcaaggagttBttMgRagVatBcRtaWgatgBtSgaKtcgHttt -gaatcaaDaHttcSBgHcagtVaaSttDcagccgttNBtgttHagYtattctttRWaaVt -SttcatatKaaRaaaNacaVtVctMtSDtDtRHRcgtaatgctcttaaatSacacaatcg -HattcaWcttaaaatHaaatcNctWttaNMcMtaKctVtcctaagYgatgatcYaaaRac -tctaRDaYagtaacgtDgaggaaatctcaaacatcaScttcKttNtaccatNtaNataca -tttHaaDHgcaDatMWaaBttcRggctMaagctVYcacgatcaDttatYtaatcKatWat -caatVYtNagatttgattgaYttttYgacttVtcKaRagaaaHVgDtaMatKYagagttN -atWttaccNtYtcDWgSatgaRgtMatgKtcgacaagWtacttaagtcgKtgatccttNc -ttatagMatHVggtagcgHctatagccctYttggtaattKNaacgaaYatatVctaataM -aaaYtgVtcKaYtaataacagaatHcacVagatYWHttagaaSMaatWtYtgtaaagNaa -acaVgaWtcacNWgataNttcaSagctMDaRttgNactaccgataMaaatgtttattDtc -aagacgctDHYYatggttcaagccNctccttcMctttagacBtaaWtaWVHggaaaaNat -ttaDtDtgctaaHHtMtatNtMtagtcatttgcaaaRatacagRHtatDNtgtDgaatVg -tVNtcaaatYBMaaaagcaKgtgatgatMgWWMaHttttMgMagatDtataaattaacca -actMtacataaattgRataatacgBtKtaataattRgtatDagDtcRDacctatRcagag -cSHatNtcaScNtttggacNtaaggaccgtgKNttgttNcttgaaRgYgRtNtcagttBc -ttttcHtKtgcttYaaNgYagtaaatgaatggWaMattBHtatctatSgtcYtgcHtaat -tHgaaMtHcagaaSatggtatgccaHBtYtcNattWtgtNgctttaggtttgtWatNtgH -tgcDttactttttttgcNtactKtWRaVcttcatagtgSNKaNccgaataaBttataata -YtSagctttaaatSttggctaaKSaatRccgWHgagDttaaatcatgagMtcgagtVtaD -ggaBtatttgDacataaacgtagYRagBWtgDStKDgatgaagttcattatttaKWcata -aatWRgatataRgttRacaaNKttNtKagaaYaStaactScattattaacgatttaaatg -DtaattagatHgaYataaactatggggatVHtgccgtNgatNYcaStRtagaccacWcaM -tatRagHgVactYtWHtcttcatgatWgagaKggagtatgaWtDtVtNaNtcgYYgtaaa -ctttaDtBactagtaDctatagtaatatttatatataacgHaaaRagKattSagttYtSt ->THREE Homo sapiens frequency -agagagacgatgaaaattaatcgtcaatacgctggcgaacactgagggggacccaatgct -cttctcggtctaaaaaggaatgtgtcagaaattggtcagttcaaaagtagaccggatctt -tgcggagaacaattcacggaacgtagcgttgggaaatatcctttctaccacacatcggat -tttcgccctctcccattatttattgtgttctcacatagaattattgtttagacatccctc -gttgtatggagagttgcccgagcgtaaaggcataatccatataccgccgggtgagtgacc -tgaaattgtttttagttgggatttcgctatggattagcttacacgaagagattctaatgg -tactataggataattataatgctgcgtggcgcagtacaccgttacaaacgtcgttcgcat -atgtggctaacacggtgaaaatacctacatcgtatttgcaatttcggtcgtttcatagag -cgcattgaattactcaaaaattatatatgttgattatttgattagactgcgtggaaagaa -ggggtactcaagccatttgtaaaagctgcatctcgcttaagtttgagagcttacattagt -ctatttcagtcttctaggaaatgtctgtgtgagtggttgtcgtccataggtcactggcat -atgcgattcatgacatgctaaactaagaaagtagattactattaccggcatgcctaatgc -gattgcactgctatgaaggtgcggacgtcgcgcccatgtagccctgataataccaatact -tacatttggtcagcaattctgacattatacctagcacccataaatttactcagacttgag -gacaggctcttggagtcgatcttctgtttgtatgcatgtgatcatatagatgaataagcg -atgcgactagttagggcatagtatagatctgtgtatacagttcagctgaacgtccgcgag -tggaagtacagctgagatctatcctaaaatgcaaccatatcgttcacacatgatatgaac -ccagggggaaacattgagttcagttaaattggcagcgaatcccccaagaagaaggcggag -tgacgttgaacgggcttatggtttttcagtacttcctccgtataagttgagcgaaatgta -aacagaataatcgttgtgttaacaacattaaaatcgcggaatatgatgagaatacacagt -gtgagcatttcacttgtaaaatatctttggtagaacttactttgctttaaatatgttaaa -ccgatctaataatctacaaaacggtagattttgcctagcacattgcgtccttctctattc -agatagaggcaatactcagaaggttttatccaaagcactgtgttgactaacctaagtttt -agtctaataatcatgattgattataggtgccgtggactacatgactcgtccacaaataat -acttagcagatcagcaattggccaagcacccgacttttatttaatggttgtgcaatagtc -cagattcgtattcgggactctttcaaataatagtttcctggcatctaagtaagaaaagct -cataaggaagcgatattatgacacgctcttccgccgctgttttgaaacttgagtattgct -cgtccgaaattgagggtcacttcaaaatttactgagaagacgaagatcgactaaagttaa -aatgctagtccacagttggtcaagttgaattcatccacgagttatatagctattttaatt -tatagtcgagtgtacaaaaaacatccacaataagatttatcttagaataacaacccccgt -atcatcgaaatcctccgttatggcctgactcctcgagcttatagcatttgtgctggcgct -cttgccaggaacttgctcgcgaggtggtgacgagtgagatgatcagtttcattatgatga -tacgattttatcgcgactagttaatcatcatagcaagtaaaatttgaattatgtcattat -catgctccattaacaggttatttaattgatactgacgaaattttttcacaatgggttttc -tagaatttaatatcagtaattgaagccttcataggggtcctactagtatcctacacgacg -caggtccgcagtatcctggagggacgtgttactgattaaaagggtcaaaggaatgaaggc -tcacaatgttacctgcttcaccatagtgagccgatgagttttacattagtactaaatccc -aaatcatactttacgatgaggcttgctagcgctaaagagaatacatacaccaccacatag -aattgttagcgatgatatcaaatagactcctggaagtgtcagggggaaactgttcaatat -ttcgtccacaggactgaccaggcatggaaaagactgacgttggaaactataccatctcac -gcccgacgcttcactaattgatgatccaaaaaatatagcccggattcctgattagcaaag -ggttcacagagaaagatattatcgacgtatatcccaaaaaacagacgtaatgtgcatctt -cgaatcgggatgaatacttgtatcataaaaatgtgacctctagtatacaggttaatgtta -gtgatacacaatactcgtgggccatgggttctcaaataaaatgtaatattgcgtcgatca -ctcacccacgtatttggtctaattatgttttatttagtgacaatccaatagataaccggt -cctattaagggctatatttttagcgaccacgcgtttaaacaaaggattgtatgtagatgg -taccagtttaattgccagtgggcaatcctaagcaaaatgagattctatcctaaagtttgg -gcttgatataagatttcggatgtatgggttttataatcgttggagagctcaatcatgagc -taatacatggatttcgctacctcaccgagagaccttgcatgaagaattctaaccaaaagt -ttaataggccggattggattgagttaattaagaccttgttcagtcatagtaaaaaccctt -aaattttaccgattgacaaagtgagcagtcgcaataccctatgcgaaacgcctcgatagt -gactaggtatacaaggtttttgagttcctttgaaatagttaactaatttaaaattaatta -acgacatggaaatcacagaacctaatgctttgtaggagttatttatgctgtttactgcct -ctacaaccctaataaagcagtcctaagaatgaaacgcatcttttagttcagaaagtggta -tccagggtggtcaatttaataaattcaacatcgggtctcaggatattcggtcatataatt -tattaagggctcttcgagtcttactctgagtgaaattggaaacagtcatccttttcgttg -tgaggcatcttacaccgctatcgatatacaatgcattccaccgcggtgtcccgtacacaa -ggaaacttgttaccttggggatataagaaaactcacacgtctcattattaaactgagtac -aatttttgcacgagaaagtaatgcaatacaatatgatgaaagccagctaatgaaaaggga -tggaacgcacctcggatctgttgcactggattaaaatccgattatttttaaaaatattca -gtgctagagcatatcaggtctacttttttatctggtatgtaaagcccacggagcgatagt -gagatccttacgactcaacgaaaagttataacataactcccgttagccaaagcccaatcc -cgattactgccctaccctaacgtctgccatctaaatatcgaacttgttatgatcaatgtg -actacctcccaccctttccccttcatttgttccactggggataagctagcgttttcagaa -tcaatgcaataagaatagccaattgtctcacttcatcagagctcttggcaattccaggcg -ctacgtggttctggaatatattcatttttcaaatagtaatacgtttagtgttgctattgt -ctacacgtttggatattacgttatgtgagcggacatcaatagttgtctaactctttagta -agccagagatagcactcttagcgaatggataccatcttccataagtttagttaatagtcc -gaaacaactgcttcgagcatatttgaacctccttgtaggcaaatagcctcttcaaagcaa -tcttactaatagatagagtttgttttaagggactactagaaatgggacaatcttaatagt -atgacctaaactgacatttaaagatatatccaggtggcaagcataaagatcattgcgcca -cctccaccgtgggattacttatcagtcgatatcctatatgctaagtttgcgacggcagaa -tacaaactaagctgagttgatgctaaccttacctatgataccccattggaccggttaaca -gccctacttattccaaataaaagaacttttatgctgtagaagctattatagtgatgcctg -gtaacttcagtatattaaaatgacacacatacgccatatagagctcctggaactttgaat -aatgagcgaacttcgaagttgaagagcaagaaaccatatgtcacggttgcctaaagcccg -gtaaccagacatgtgctatcattgatcattatcgaggttttcataaccttgacccattat -cggctgtgcgcggacaagtacttaaatcactagtttcttcacctgcttatcggtaagaaa -taaggttggcaaagaatcgcataagacggacgtagagccgcagcgttgtgcgagtccagg -tgcatgcgcagcaataggattttaaattttgttccatttttaatttagccgtaaggatgt -ccgtaaatgattgaaaattggattcaatctttgggcctatgctactggaacctgatcgac -aaaatttcaaacatacgttaactccgaaagaccgtatttttgcggctagaatagtcagtc -gcttggagccatataccttaccacttaaacgacgtgctcctgtagttgaaatataaacag -aacacaaagactaccgatcatatcaactgaagatctttgtaactttgaggcgaagcaccc -tcttcgagacaactaagagtaaagtaccgggcgccgcaaggagtcgattgggaccctaaa -tcttgacgaattgctaagaggctcagagctaccactgtaatttctctagagcccataata -aatgaacgatacatccgtaggtagcacctaagggattataatggaagccaaatgcagtta -ataatattatatactggcgtacacgattcgacggatctctcacatagtgattcacgaccc -ccccctttgattgacacagcgtcagcattttgcaagaacgatcttctgcatagggtgcgc -caccgtaaggatgacgtcgaagctacaactgggtataatttaccatgcttccctgatgct -gagtgcaatacactaagaatgagtttttaccccatatcaccagtatttgttctgttattg -cgaagaaatggctatgctgagttggcgactaaagtcacccatcctttttattaggtaacc -ccctcccttaaactaactgatttgctggagctgccctgcatacatatactttatcattta -tggacgtccgtgacgcttattatccaccatagtcgatatgctacacggattcattaatgg -atcgtaggagtttaagttatatttactaagatcggtctcggctactatcccgccttaccc -ggcgctatttacggccatttttaatatattgacggtaattattcctatggtttcgaccgc -acgtccttggacaagaaagaatggcaaaaaaaatgtaaaagaaaaaaaatattgagtccc -taccatcatataaaaaatatgtgatgagtaacttgacgaaatgttagtggttattaaaga -ctatctattacaccttttgttttctgtcgtagtatattaaagtctagaagccttacagga -aaatcagggttatacagccgatactccgcagcatgaatcatcgaggaggtgtcctaccat -cgcgccttgtaatcttgtctgtgtatactgtatttagaccttttatacaaagtaaatatc -tcggctttatgtgattgggaggggcctactcaaacatgatgacttgacctaataatcact -gtgcgggcgtcttatgactagctattccttgaaatccaccaccaaatggttaatatgtaa -aaactttgacgatgaaacaaggtgaatgtgtagttactttgtgtaattagctgcgtcgag -cattgcttgtaaaaccgtcaatcgcacacgttacttccataaaatttctacgaatacacc -cttcttaaaaaaaacgtaggaattcacgagtttaacaaacgataactgtataaagtggaa -gtccgaagaaagcagatgcccgaactactcgaagatgtttcgttttcttaaccatagggg -cttcttaatggcccactacgcacattttgttcaagcccgagagggacatccccattacgg -gagtattactaaaactgttccgtaatacgttcagcaagggatgaaaaaggccactgctca -agttattgacgtgggagtattacatcggaagcctgaatcccacactatgatggtctgtac -aggcctagggactgcgtctagacggtattaccggcttctaatcatacgatcgtgagtctt -aacgggaagtaaggctcacacctaccccaaaccatttatctatgtaagtataaaattgtg -cgtaagtgttcaaagtggacaataaagacgtggcaaaaacccccgcacataagccgcttt -agatttcacaaataccaatgcggttaaaaacatccttgagtcgtacatacaccatactcg -cgttaaacggatataacagaagataataaatccggatgtggagtcggtgtaactatagaa -agccaagtgaaataatgcttaccagtcatttagctatacggctttcatttcatgtcaaga -gggtggagtttgacctgtacagttgatatatcaccgatacttagaactcacctaaagcta -aaattgctcgcagcgtgtaatccgcatattacaaacaatagatgggattcattatacata -agacacgatgatctgctttttcaggttgcgagatgttgcctatcgtcaatcgagtcctgc -cttacaccacttaaacaaaagtattgacagggaacctattttcgaggtattatatagtcc -agcttgaatatcaatttgacagttaacctagtgaaaatcagtaagaggaaatacgccaca -ttctccagtgaaattctacgggttatcgtctagtccaactatcaattataactcacgaga -tataagtaaattctcgtacttggcctgatttttattatactttggatccttagtaaacag -gaagggagaaaccttcaacgaaaaacactggattttgttttactctcaaagctcttatat -gacggaaataccctgtcaagtcttaactttattactagactaatgaaatgggcttggggt -ggccagaatcatagtacaatttagcggatacactattcggactttcctatcggctgtctg -gttggataagtatggggactaataggctagacatacctatacttaaactatacaggcgtc -atctatctctgcaactttggagttccctgatgttctcccgccctttgggttcacatcttc -tataccgacacccctaataacgattagtttgtgggttagagtaaattaatacggttaata -ttaatgtatcgttgaaaagctggtgtcgccaataaggtaaccggctaggcagagtatatg -tcacgaagtataactaccctaatgataagctgtaggaataaaattaatgctgtctctaag -cgaagagatatttccgactctgttttaatgacgaatctcattacttctgacttgcaaatg -ttcaatatggcacggtttcacggcacctttgtgacgcatataatgaacttagaagattat -aacgacggaactttatatgataatccgttacgattaaagaatctgttaaatatcataatg -gcattcagttctagaccgtgcatcatggtaaacttactttctctgcatggcgacatacat -ttcgctattcaaattcgcgtgtggttacacccactcgcacctttggaatattaagagaag -atgatcagaaaatccattcgctcaatttttctgacgtacgtctaatttatcctaggagac -aaatcgttttatgtctctcacatttttgaagaaaggttcgagagacaatactcaggtcct -gaactgctagaagatactcggtggagcgtggcaacaatgaaaaactcgtgacataaatga -atgatacttttccaagttcagttaagtgaatatgtttaacatacccggcttttcgatctt -aagctgacgctggacgtgcgagtaatgtcagtctcttacatacactagtgactccaagtt -tcgtcaaaaacgccccctcccttctcgagcccactcacgctatgtattgacgcgaacttg -ttcgggatcagacttttcaggagttcggtcgcgtgtccctatgtgctaatatataagtta -gatcgcattagatgctaatctgaatacttatagacgaccttcaacgagaacgggtaccac -cttgaggctagagttaggtgtgaaacgacaggtagggacatataaaatttgagtgcggct -ttagttaagggtttaattacctactcaaacatcacgctcgcgcccttcgtacgtaatcga -ccatctagaggctaaggggactgtactaggtagtgattaatgatatcctagacgcacgtg -ccttagatcttcagactctgatggtccgcgatcaccgtaattgtagtcctccaactcgat -cactttgttggcgtcaaagaaattacgatatctaaatacttataatacaataaccaagga -tgagaatgactcatcgcgttggagttatattgcttgaagttctatggaatgaaagcacgt -tatctgccgtcccaatatctccagtgagctaattcattggacggtccactttgatcaatc -cccgaggagatgttcggacactttagtctgtaacacttagcgttgagaccacgaacaatt -gattactcagtcttgaaggtgttttccaaagttcattttaaataagactacgataggcct -ttcctattgatataaactacccggctctgttgttcgtgtgagtcgtacttctctgtgttt -ttctgattatagcaagattcgattcttagtgtaaacagcgatttttatttgacccgtcaa -tgagaagcgcataggatctaagcaaaattatcaagttgtgccacaaggtaagatctttcc -agttattgcaggtaggatgtatcccacgttgatagtatgaggtctgacgtcaactgtcta -ggagagttgaccgcgtgcgggtacaccggatttgcatcgatgttgagaacgcagaactcc -cactgtcgtggcggcgttcctgatatttagcaagaggcgttgataaagccctcatcatct -agatctcgacctcatctgccctcttgctccatcattttctacacagactactttcctatc -tacgttagtataattgctttctatcttagtatcatttagagcttctccgtcaacaggttc -gtgctattaaagttagtacgaaagggacaacttgtagcaacgcatttaatcggttttcga -ctacttcgcacaaaatcagataaagaagtttgtcattctattagacattgaattgcgcaa -ttgacttgtaccacttatgatcgaacactgaatcaagactgtgattaactaaaatagaca -agccactatatcaactaataaaaacgcccctggtggtcgaacatagttgactacaggata -attaattggactggagccattacattctctacaatcgtatcacttcccaagtagacaact -ttgaccttgtagtttcatgtacaaaaaaatgctttcgcaggagcacattggtagttcaat -agtttcatgggaacctcttgagccgtcttctgtgggtgtgttcggatagtaggtactgat -aaagtcgtgtcgctttcgatgagagggaattcaccggaaaacaccttggttaacaggata -gtctatgtaaacttcgagacatgtttaagagttaccagcttaatccacggtgctctacta -gtatcatcagctgtcttgcctcgcctagaaatatgcattctatcgttatcctatcaacgg -ttgccgtactgagcagccttattgtggaagagtaatatataaatgtagtcttgtctttac -gaagcagacgtaagtaataatgacttggaataccaaaactaaacatagtggattatcata -ctcaagaactctccagataaataacagtttttacgatacgtcaccaatgagcttaaagat -taggatcctcaaaactgatacaaacgctaattcatttgttattggatccagtatcagtta -aactgaatggagtgaagattgtagaatgttgttctggcctcgcatggggtctaggtgata -tacaatttctcatacttacacggtagtggaaatctgattctagcttcgtagctgactata -ctcaaggaaccactgctcaaggtaggagactagttccgaccctacagtcaaagtggccga -agcttaaactatagactagttgttaaatgctgatttcaagatatcatctatatacagttt -ggacaattatgtgtgcgaaactaaaattcatgctattcagatggatttcacttatgcctt -agaaacagatattgcccgagctcaatcaacagttttagccggaaacaatcgaagcatagg -gacaatgtatcttttcctaaattgccatgtgcagatttctgagtgtcacgaagcgcataa -tagaatcttgtgttgcctcaactcgttgaaaagtttaaaacaatcgcagcagtctttttg -gggtctactgtgtgtttgcaaaataactgaaagaaacgcttgaacaactctgaagtagct -cgagtactcattaaagtgtaacacattagtgaatatcggccaatgaaccaaacgcttccc -ggtacgctatctctctcatcgggaggcgatgtgcaggttatctacgaaagcatcccttta -cgttgagagtgtcgatgcatgaacctcattgtaacaatagcccagcaaattctcatacgt -gcctcagggtccgggcgtactcctccatggaagggcgcgcatctagtgttataccaactc -gctttttaactactatgctgtagttctacaggcatagtggccagtattttctaacttctc -tggatagatgctctcactcctcatccatcacggcttcagtttacgtcttacttgcttgtt -cagcaacggatggaggcattaagtatcttcactgttccctaaaattgctgttcaatatca -aagtaaggacgatacagggaaagctcaagcacactcattgaatactgccccagttgcaac -ctcacttaatctgacaaaaataatgactactctaagtgttgcggaagcagtctcttccac -gagcttgtctgtatcacttcgtataggcatgtaactcgatagacacgaacaccgagtgag -aaactatattcttgcttccgtgtgtgtgacaccaggtaattgatgcggatataagctgga -gatcactcacgcccacacaaggcgctgctacctctttattccaatgtgtaagaatttgct -aacttcatttctagaccgcagctttgcggtcataatttcacggtacggacccttgggtta -gagacttgataacacacttcgcagtttccaccgcgcacatgttttagtggcttctaacat -agaatttttgttgtgacataaagagtgcgtgggagacttgcccgaccgttaagccataat -caattgaaagccccgtgagtcacatctaattggttgtactgcgcatttagctatccttta -gctgactcgaagagattcgattcctaatataggttaattagatggctgccgcgcgaagta -aaacgtgaaaaacgtagtgcgcagatctgcataactcgcgcttaattacttatgagtagt -tccaagttcgctacgttatgagagagattggaattaagcaaatatgttttatggtgattt -tgggatgagaaggactgctaagtacggctactaaacaaatttctaaaaccgccatctacc -ttatcttggagacatttaagttgtatatgtcactagtctagcttttgtctgtgggacgcg -ttctcggaatgagggaaatgcaagagccgattcatcaaatgcttatctaagaaagtagtg -gactattacaccaagcacgaatgccagggaactgctttcttgctcaggacctcgcgacaa -ggtaccccgcataagtcctagaattacatttggtcagcaatgctgacatttgaccgtgaa -aacataattttaatcagaaggcagctcacccgcttgctctagatcttatctttgtatgaa -tgtcagaatttactgcaatatccgttccgaatagtgagggcttagtatagttctctgtat -acaggtcacatcaaactccccctgtcctagtacagctctgagctttaattaattgcatac -atttccttcaatcatcagatgaaaacaccgcgaatcatgctcttctcgtatagggcaaga -gaagcaacaaacaactagcccgactcacgttcatccgccgtatccttgttcagttcttac -tccgtattaggtcagcgaaatctaatcagaataatcggtcgcgtatcaaaattaaaatcc -cgcttgaggttgacaattaaaacgctgagcagttatcggctattagatagtggggtgaaa -gtaattggctggaattatgttaaaacgtgatattaagctaaaatacgctacttgttgccg -acctaattcagtcattcgatattcagttagagccaagaataacaagcttgtataaattga -acggggtgcactaaacgatgtgttactctaatattcagcttggagtatacctgaaggcga -attcatgtatcggccaataataagacgttgaagatcacaatttggactagcaaaagaagg -tgatttatgcgtggggattgagtccactgtacgagtacggtctctggaaaattataggtt -cagggaatataaggaagtaaagataattaccaagagatttttggtatcgctatgacccag -aggtgttctaacgtctgttttgatccgcagaatttctgcctcaatgcatatttgacggac -ttgaactagagcctctaaagttaaatggcgacgcaactgttcctaaacttcaattattac -tactctttttttcctagggtattgtagaggccagtggacaaaataaatcaaatttaagat -gtttcggacattaacatcccccgtagcatagaaatcatcagttatccaatctctcatcga -gcttttacaatttctgctggcgctatggacagcatatgccgcgagacctccgcaagactc -acttgatcactgtaagtatcttcattagaggttagagcctatagttaagctgctgaccta -gtaaaattggtattttctaattttattgctcaagttaaaggttagtgaagggataatgac -gttatttttgaacaatgggttgtattcaattttatatcacgaatggaacccttcattccc -ggcataatactagacgacacgaacaagctccgatctatcagccaggcacgtgttaaggtt -taattccggcaaaccaatgaagcatcaaaaggtgacctgatgcaacttagggtcacgatg -agtttttcaggactacttattacctattaataagttaacatgagccttcataccccgtaa -gacaatacatactccaccaattagaattctgagccatcttatctttttgtatcatcgaag -ggtatggccgaataggttaattagttactcctaacgtctctacaggcatgcatttgacgc -accttcgaaaatagtcaatctctcgccacacgcgtctagtatgcagcatcaaaaatatag -tccacggtttccggattaccaaacgcggcaaagagaaacattgtatcgacggagataact -taatacagaaggaaggggcatcttcgaatacggatgaataattctatctgtttattctga -catcttgttttcaggttaatcttacgcattcaaatgacgcctgccccatgcgtgcgcaat -tattttctaatattgacgagagcaatctcactccttttgggtctatttatgttttattga -ggcacaagcctatacagaacaggtactattaaggccgtgagtgtgagactcaaaccgtgg -aaacaaaggatgggttgttcttggtacaagttttagtgcatgtgggcaatccttaccaaa -atcagatgctatccttaactttgggctgcatttaagatggcggttggaggcctgtgagaa -tcctgcgtgtcatctttaatgaccgaattcatccatgtagattcagatcacacactcatt -ccttgatgttgtctaaacaaaagttgttgtggacgcattggagggagttaagtaacaact -tgggatcgcatacttataaaaattatatgttaaactttcacaaacgctgaagtccaaagt -aactagcccaaacgcctcgagagtcactaggtattaatggtgtttgagttcctgtgaaat -agtgttcgaaggtaaaatttatgtaccaaatcgaaagaacacttaataaggcttgcttgc -acggaggtatgatgtttactgactctacaaccctaattttccagtacgtacattcattcc -aataggttagttctcaaagtgctatacaggctcctcaattgatgatatgcttcagccgct -ctatggatattagctcattttatttaggaagcccgcttagaggcttactatgagggaaat -gccaaaatgtcatacttttcggtgtgtcccatatgacaccgctttacatagaatttgaat -taaaacgcgctctcccgttcactaccatacttggtaccgtgcgcatattacatatagata -taggatcattttttaaagctgtactaggtttgatcgacaatcttatgctatactatatga -tgtaaccctcataatcaataccgatcgtacgatcctagcataggtggcaagcgattttat -gccgattattgtgttaaatagtctgtgagtgtgattatcagggctacgttggtagagggg -ttgtatagacctcgcacacattgtgacatacttaacaatatacgaaaactgatataataa -atccccttacccaaacaccaatcccgttgaatcaactaccataacgtctcccatataaat -tgcctacttgtttgcataaatctgaatacataacaccattgcaccttcttgtgttccaat -cccgttaagattgccttgtcagatgatatgcaagaacaatagcatttgctagcaattatt -aacagctcttcgaattgcctccacataacgcgggagggtatattttaatttggcaaatac -taagtactgttggcgtcatatgctattaacggttggatattaagttatgtcagccgtaag -caagagtgggcgaaatattttgttacccagtgagagcactcttagagtttggatacaata -ggccatatgttgacttaagaggacgtaactacgccgtacaccattgttcaaccgacttct -tggcaaatagaatcgtattagcaatcttaagaatagagacacgttcgtgttagggtatac -tacaaatccgaaaatcttaagaggatcacctaaactgaaatttatacatatttcaacgtg -gatagatttaacataattcagccacctccaacctgggagtaattttcagtagatttacta -gatgattagtggcccaacgcacttgactatataagatctggggatcctaacctgacctat -gagacaaaattggaaacgttaacagcccttatgtgtacaaagaaaagtaagttgttgctg -ttcaacagatgatagtcatgacgcgtaacttcactatagtaaattgaaacaaatacgcaa -tttagacagaatggtacggtcatgaatgacagtaattcgaagtgctagaccaacttaaaa -taggtaaacgtgcccgaaaccccccttaacagaaagctgctatcatggtgcagtatcgac -gtgttcagaaacttgtaacttttgagcaggtccgagcacatggaagtatatcacgtgttt -ctgaaccggcttatccctaagatatatccgtcgcaaactttcgatttagtcccacgtaga -gcccaagcgttgtgcgactccacgtgcatgcccagaaatacgagtttaaatttggttaca -tggttaattttgaccgaagcatcgcactttatgattgataattggattcaatatgtcgcc -ctatgcgaatgcaacatgatccacaatttggctataagacgtttaatccgtatcacactt -tgtttgcggctagtatagtaacgcccgtgcaccaagagtcagtaacaattataagtactc -cgcaggtacttcaaatataaaaactaatcaaacacgacccatatgatcatctgaagatat -ttggaactttctcgacaaccaccctcgtactcaatacttacactaatcgacaggcacacg -caacgtgtacagtcgcaccatattgagtcaagatttgcttagtggcgatgagcgtacacg -cttatttctctagtcacaattagttatctacgagacatcacgagggagcaaataagcgat -gttatggctacacataggcacgtatgaatatgatataagccagttaaacagtcgaaccat -cgagcaaattctcatgcaccaacccacacgttgaggcacaaagagtaagctgtttgaatg -taacttcttctgctgagcgggccccaacgtaaggatcaactagaagagaaaactcggtat -tagtttaaatgcgtcacggagcatgagtgcatttcactaagaatgtctgtgtaaccaata -taacatctatttgttatctgattgcctacttatggctttgcggtcgtggcgactaatgtc -tccaatccttttgaggtcggtaccaactccctttaaattacgctgtgcaggctcatgcac -tgcatacatatacggtagcaggtagggacctcacgcacccttattataatcaatagtagt -tatcagtcaacgaggcaggaatgctgaggtcgaggtgttggtatattttctatgtgccgt -ctaggcgactatcacgcattaccaggcgagatttaagccaattttgaatatagtcaacgt -aatttttactatgggttccaccgaaacgccttgcacaactaagaatcccataaaatatcg -atatcaaataaaagattgtgtcaataccttcatatatattttttcggttgactaacgtga -actaaggttaggggttttgtatgtctatataggaaacagtttcttttctgtcctacttta -gtaaagtcttcaagccttactccaaaatcacggtgattaagccgttactcagcagcatga -ttctgcctgctcgggtcctaaaatccagccttgtaagagtcgctgtgtattagctaggga -gacctttgttaaaaaggatatatcgcggcgggatgtgagtgcgtggcgcatactcaatct -tcagctcgtgtcattataatatctctcccccacgcttttcactagatatgccgtgtaagc -aaacaccttatgcttaatttcgaaaatattggtacttgaaaaaagctgtaggggtactta -atgtctggtaggagatcaggagagaattgagtgtaaaaccgtaaagccctcacctgactt -catgtaaatggcttagaagactccatgatttaataaatactacgaaggaaagactggatc -taaagataactctagtaaggccaactcccttcaatgctgttgccagttataatccaagag -ctgtccttttctgaaccatagcggcttctgaagcgaactagaagcaaagttggttctagc -cagacagccacataccctgtacgggtgtattactaaaactggtccggtattagttcacca -agggaggaattaggcaaaggatctaggtatgcaagtcggagtattacatccctaccctga -atccatcaataggttcctctgtactggccttcgcaatgagtattcaaggttgtacagccg -tataataataagatagtgactatgaacgggaagtaacccgctcaccttccccaaaacatt -gttatatctaagtattaaagtctgccgtagtgttaatactcgaaaataaacaactggcaa -attacaccgcacttaagccgcttttgatttatatttttccaatgcgcttttaaaaataat -tcagtcctacatactaattaagacccttaaacggagatatcacaagttaagttttaacca -tctcgactaggtggaactatagatacccaactcaatttatcattacctgtaatgttccta -gaaggattgcatttcatgtcaagacggtggagtttcacagcgaaacttcagtgtgaacag -attctgagaaatcacctaaacctattagtcagagcacccggttagaaccagttgtcaaaa -aatagagcggttgcatgagacagaagtaacgatgagatccgttgtaacgttgagacatct -ggcctatcgtcaatacagtcctcccttaaaaatatttttaaatactaggcaaacccaaca -taggttagtcctatgtgatacgccacatggtatatcattttgtaacgttacctagggata -atcaggaagtggaattacgcaaaagtagacagtgaaatgcttagggttatagtctagtcc -aaagataaaggataaagcacgtcagagaactatattagccgaatgggaatcattgttagg -agactgtggatcatgtctaaaaagcaacgcagaaacagtcatcgaaaaaatctcgttttt -gtttgaatctaaaagagctttgatgaccgatagtacctgtatactagttactgtattacg -tgtctaatgatttcggattggggtccccagaatcagacgtcattgtagacgattcaagtt -taccaatttaatttcccagctctccttggagaactatcgccaataattgcagtcactttc -cttttctgaaacgataaagccgtcagagttctctgcaacgttggacttacctgaggttct -aacccactttcggttctaatagtagttaacgacacaacgaataacctttactgtggggct -ttcacgatattttttcgcttattattaatggttacgtcataagctggtgtccaaattaag -gttaccggcttcgcagagtagttgtatccaagtataacttccctaatcataagatcgagg -tagaaaattaatgctgtctctaaccgaacagatatgtcccactatgtggtatggacgttg -ctaattacttctgaagggaaattggtcattatggatacgtgtctaccatcaggtcggacg -cagatatggttctgtcttcagttgatccaccgttctttataggataataactgacgatta -aagattatggtaaatagattaagccaattctcttcttgtcagtgaagcatccttaactga -cttgctctgcagcccctcatacatttagctattcaaagtaccggctcgtttcaaactctc -ccacctttggaagaggttgtcaacttgataagtatatcatttacagcattttttcggacg -tacctctaatgtttcattgcagaaaattagttttttctatcgcacattttgcaagtaacg -ttagagacacaattatctgcgaatgaactgctagatctgacgaccgggagcctcgcaaat -atcaaaaaagactgacatatatcaaggagtcgttgacaagtgctggtaagtcaattggtt -tatctgtcccggcgtttcgatcttaagctgaccatgcacggcagagtaatgtcactctcg -ttcttacaagtctgtctccaagggtcggcaaaaaagacccctccattctcgagcccactc -acgatatgtagggacgacaacttgtgcggcttatgaattgtctggactgcgggcgagggt -ccatatctccgaagttagaagggacatacctttagatgataagatcaattcttattgacg -aaattcatccacaacggggaacaacttcaccctagacttacgtctgaaaagacacctagc -gtcttataaaaggtcagtgccccgtttcgtaaggctggaattacctacgcaaacttaaac -ctcgcgcccttccttacgtatcgacaagatagaggctatcgcgaatgtactacggaggca -tgaatcatatactagaaccaagtgcctgtgatattaacaagatgatccgacgcgagcacc -gtaattctaggcataaaactccagcaatttgggggccgaaaacaaatgacgttagctaat -taattatatgacatgatcaaaggaggtcaatcacgcatcgagttcgacgtatattcattg -aacttcgtgcgtttgaaagaaacttttatgaaggcaaaattgatcctgtctcctatttca -tgcgtacctcctagttgataattccccgagcagtggttaggacacttttgtcggtatcaa -gttccggtctcaaaacgtaaaattctgtaatctgtatggatggtctgtgaattagttaat -ttttatgaagtcgtcgagacgcagttcctattgatttattctaaacggagatgtgcttcg -tgggactcggaagtagatctgtgtttatgattattgctactttagatgctgactgttaac -tccgtgttgtttttcaaccgtatatcacaaccgaattggatagaacctatagtttcaagt -tctgccacaaggtatcatatttacagttagtgctggttgcttctttcaaacgtggtgagt -ttgtgctatcacgtcaacggtagagctcagtggaccgagtgcgcgttcaaccctgttcca -gagagggtgtgatagcacatataccacgctcgtcgaggcgttcatgatagtttgcaagag -ccggtgttaaacacatattattattgttatccaactaatcggacctatgcataaagcatt -gtctaaacagaataattgcctatatacggtagttttagtgatttatatcttagtatcagt -tagagcttcgaactcttcaggttcctcatatttaacgttcttcgaaagcgaaaacttcta -caaacgaatgtaagcggttttccaagtagtacctataaatcacagaaagatctgtctcag -tatagttgaaatggtattcagctagtgacgtgtaccaattatcatagttcactcaagcaa -gacgctcattaacgaatatagacaagacactatatcatataataaaaaagaacatggtgc -tcgaacatagttgaattcaccatattgaaggggaatgctgacatgtaattcgctactaga -cgatcaattccctacttgtcaaagttgaactggtacgttcttggaattaaatatgattgc -gctggaccaaattgcgacttcttgagtttcagggcaaacgattgagccggaggatgtccg -tctcttacctttcttgcttatgataaacgacggtccctgtacatcactgggaattctcag -caaaaataattgggtaaatcgagactcgatgtattcggccacaaaggtgttagacgttaa -agattattcaacggggcgataataggatcataaccggtatgcaagcgcattgaaagagcc -atgagatccttatccgataaacgctgcacggtatgtgcagccttattgtcgatcacgaat -ttataaatgtagtctgggctgtaagttgaagacctaagttataatgaagtgcaataccaa -atcgattcatagtggattatcagactcaagatatctcctgataaattacagttgttaaga -tacggataaaatgagatttaagattagcagcctctaatctgtttcaatcccgttggaatg -tggtatgcgatcaaggttaagttaaaatcaagcctgtcttcagtcttgattcttgttctg -ccatcgcatgcggtctacgtgagttaatatgtagcttacgttctagcttgtgctaatctg -agtatagattcgtagaggaatattatcaagcttccacgcctcaacgtacgtgtattggtc -acacaagacactaaaagtggaagtagcgtaaactatagtctagttgttaaatgctcagtt -cttgttatattcgatatactcttggctaatttatgtctgagtatataaaattaatgatat -taacttgcatttcacggatcccttagaaaaagattttgaccgagcgcattataaacggtt -acaccgaatcaatagaagcatacccaatagctttctttgaatttattgcctgcgcaactt -ggctgactctctagatccgaataattctatatggtcgtgacgaaactagttcattactgt -ttaaaatgccaacatgtcttttgggccgataatggctctttgcaaaattactcaatgata -cgattgatcaaagcggtagttgctagtggtagcatgtaagtctatcaaatgtctgattat -ccgaaaatcttccaaaagagtccacgtaccatatctatctcatagcgacgcgaggggaac -cttatctaactatcattccatttaccgggtgactctcgatgcaggatccgattgggataa -attgcccagaaatggctcattcctgactaagggtaaggccgttctcagcaagggaacccc -gcgaatctaggcttataccatctagattgttaactacttgcctgtagttctacagccata -ctggacagttgtttctaaatgatcgggattcatgctagcactcctctgaatgcaccgcgt -aagtttaactattacgtccgtgggcagataaggatggaggctgtatgtatcttaactgtt -acctaatatggctggtaattatcaaagtaaggaccttaatgccatagcgctagcaatcgc -tttgtatactgaccatgtgccaacctctcttaatctgtaaaatataatgtcttagctaac -tgtggacgatcatgtctctgcctagagcttcgctgtatcaattcctatagccagcgtact -agtgacacaacaacaccgtgtgagaaaagatattagtccttacgtctgtctctctacagc -ttattgatgaggattgaacatggacatatagctccccctcaaaagcagatgctacctctt -tattccattctcgaacatttgccgaacttaatttcgacaaacctgaggtcacgtcttaat -ttatcggtaacgtcacgtccctttgagactggataaatatattaccaggggccaacgagc -aattgttggaggcgcttctataatacaaggtgtcttgtcaaagaaagacggcgtgcgtct -cgtgcaactcacttaaccaatattaatgtgaaacccccctctctcacatcttatgcggtg -tactgccctggtacatttcctgtacaggactccaacagtgtagattcctaagatagctgt -tggagttgcctcacgccagatcgaaaaactgaataaactagtgagctgagctgcagaaat -accgcttaattacttatgactagttcaaagggacctacgtgatgtcagacattgcaagga -agaaattaggtttgtgcgtcattttggctggactagcactccttacttcccctactattc -aaatgtcgtaaacagcatgagacaggatcgtgctgacatttaaggtctattgggaacgag -gctacctttggtcgcgcgctcgcgttctccgaatgaccgaaatgcatgagcacagtatgc -aattgcttatagatctaaggtctggtcgttgaaaccaagcacgtaggcctgggaaatcag -ttcttcctcagcaactacacaaaagcgtccaagcattagtacttgtagtaaatgtccgaa -cctatgcgctcatttgaaagtcaaaaaatatttttaagcagtaggcacctaacccgattc -ctctacttagtagctttctttgattctcagaattgactgcaatatcactgcacaattctg -tgccattactagacttctctgtattaacgtctcatcttactaacactcgcctaggacaca -tctgagagtgaagtatttcaatacatttactgaaatcttcagttctaaaatccccgaata -aggctcttatcggtttggccaacacaagaaaaaaacttcttgcaccactcaccttcatac -gcaggagcctggggaacttagtaataactatttcggcagacaaagcttataacaagttgc -cggcgcgtataatatttaaaagaccccttgagctgctcaattaaaacgctcacctggtat -aggctattagatagtgccgtcttagtaaggggcgggaattatcggataaactgatatttt -gataaaataaccgacttgttcacgacataagtcactaaggagattttatctttctccaaa -gtatatcttccttggataatttcaaagcgctgcaatttaagttctgttactagtttatgc -tgctgggaggtgaccggaaggcgtagtaatctagaggcaaattataagaagttcatcata -tcattttcgactacaaaaacaaggtgttgtatgccggcgcattgtgtaaactggacgagt -accctagatggaaaattatacgttaagccaagatttcgatgtaatgataattacctacac -atttttgctatccataggaacaagagctgttctataggctcgtggcatacgaacatttgc -tgccgctatgaatattggaagctcttcaactacagactctattcttaattgccgtcgaaa -atgggccgaatcggctattattaatactcggtttttccgaggggattgttgtcgacagtc -gtaattattattaatattgatgttggtgaggtcatttaaatacaaccttgcagacaatga -ataagggatccaatctctcatactccttttacaattgctcatgcccctatgcaaacctta -tgccgccacacctccgcaactctctcttctgaactgtaagtagcttcattactggtttga -gactatactgaagctgatgacattctaaaatggctattttcgaatgtgattcataatgtt -tatcgtttgggatggcagaatcacgttatttttgatatagcccgggtattctattgtata -gaacgtatgctacaagtcattccccgaagaagactagaagtaaacaacatgcgaccatcg -ttaagccacgcaaggctgtagctttatttcccgataacctatcttccataaatagcggac -agcaggatactgacgctcaacatcagtggttatggtctaatttttaacttttaataaggt -aacttcagcaggcatacacagtaactctttaatttataatcaaattagaagtctgacact -tcttatatttttctatcatccaacgcgatcgcccattagcttattgtgttactaataacg -tatctaaaccaatccttttcaagctactgcctatattgtcaatatatacaaacaacagga -tagtaggctgcttaaaaaatattgtcaaccgtgtacgctttacaatacccggaaatcaca -aactttgtagacaacgagtgaaatttatacactacgaagggccagcgtacaagacccatg -aattaggcgatatgtttattctgacatattggtttatccttaatctgtcgctgtaaaatg -aagccgcccccatccctgcgaattttttttcgaagattcacgactgaaatataaatacgt -ttggctatatttatgttggagggaggcaatagcctttactgttaaccgaagatttagcca -gtgagtgtgacactaaaacactggaataaatgcaggcgttcttctgggtaaaaggtttag -tcaatctcgcctataagttcatatagctctggatataattatctggcccatgcatttatc -atggcgcttggtgccctgtgtgaagccggcctctcatattgaaggtccgaagtattccat -gtacattaagatcactctctcattcatgcatcttggcttaacaaatctggttgtccaagc -tttccaggcacgtatggtacaaattcggatcgaatacttataaaaatgatatgttaaact -gtctaaaacgctcatctacaaagtaaagtgcactaaccaatagagtctcaagaccgtgta -atgctggtgcactgaatgtgtaatacggttagaagggattagttatgttacaaatccatt -gaaaacttaagaagcattgcgtgctcggagggtgcatcttttatcaagagactaacatta -ttttcaacgacgtacatgctttacaatagggtacttatcaaacgccgagaaacgcgccta -tagtgatgttatgattatgacccgatatccattggaccgaattttatgtaggttcccagc -gtactcgcgtaatatctcggtattgccataatgtaatacttgtcggtctctcccagatga -aaaagcgttacagagtatttcaatgaaaaacagcgcgcaacgtcaatacctttaggggta -acggccgctgatttcatatagatatacgataagttggtatagctctactaggtggcatcc -acaatcgttgcatttactatagctggttacaatcataatctataccgttccttacatact -accatagcgggatagcgtttttttgccgttgattgggtttaagaggatgtcagtctcatt -atatccgattcggtgggagagccgttgttttcaaatcgcacactttgtgacataatgtac -aagataacaaaactgatataagatataaactgtcaatatcaccttgacacttgaatcaaa -gtaaattaactcgcaaatataatttgactaattgggtgcagatttctcaattaataaaaa -aatggcaccggatgggcttacaagccccttatcattcacttgtatcatgatttccaagaa -caatagaatttgctagcaagtatgaacagagattcgaattgcatccacagtacgccggag -cgtttattttaatgtggatatgacgatgtactgttggcggcatttgctagtaaccggtcc -ttatttacgtagcgcacacgtaagcatgtctgggagaaatatggtggtacaatctcagag -aaagattacagtttggtttaaataggacttatcgggtcggaagtggaacttaataagcag -tacacaattgggcaacagacgtcttgcctattacaataggattacaatgcgttagatttc -agacacgttcgtgtttggctattcgtcaattccctaaatagttagacgatcaactattat -caaagtgattctttgttcatcctccattcatgtaacagatggcacactacgcataacgcc -gaggaattttaacgagatttaagagagcagttcgggcacaacccacttgactttataaca -gctcggcagcataaacggtaatatgtgacaaatttccaaacgttataagaacgtatgtgt -acttagaaaactaagtggttcatgttcaacagatgtgacgcagcaagcctaacttatcta -ttggttttgctataaaagaacaaagttacacagaatcctaagggcttgtttcacacttat -gcctagtgcttcaccatcttaaaatagcgaaaccggcacgaatcaaaccttaaaacaatg -cgcagatattggtgatggtgactccgggtatgataatggtaactgttgaccagcgcccac -ctcatcgaagtatagaaagtggttaggataaggatgagaccgaacttatttccggccata -actttagattttctacctagtacacaacatcagggcggacacgaaaccgccatcacatca -tataccaggtttaatttgcttaatgggggaagtgtcaacgaaccttcgaactttagcagg -catatggccattatatatggccccagagcagaatgctacagcagacaaaatttggattta -tgtagtttaatacctatcaaacttggtgtgaccatacttgtctaacgacagtgcacaaag -tgtaagttacaattattactactcagcagcttctgcaatgataaaatcttatcatacacg -tcacatatgataatatctacttagggggaacgggctccacaacctacatagtactcaata -cttacactattcgacaggcacaccaaacctgtacagtcccaaaagattgagtcaactttg -cagtactgcagatcacagtaatagcttagttagcgagtcaaaattagttttctacgagac -tgcacgaccgtgcaaatttccgatgtgttggctacaaatagcaacgtatgaatttgtttg -aagccacgtaaactgtacaaccttagagataagtctcaggctactaaaaacacgttgtgg -cactaacaggatcatggttgattcttacttattcggctgaccggcccaataagtaacctt -caactagaacagaataatcgggagtagtttaattcagtcaaggtgcaggtctcattgtaa -ctaacaagctctgtgtaaccaagttaaaatcgttttcttagcggattccctacttatgga -tttgagctcgtccacaatattcgatacaagaagtttgtggtccgtaacaacgaaatttta -attacgctgtgcagcctcatccaaggaattaatagaaggttgatggtaggctccgaacgc -tccatgattataatcaagtggactgtgcagtaaacgaggaaggtatcctgacgtcgtggt -gttcgtttttgttatttgtgccctatacgagtagataaaccatgaacagcacagtgtgaa -cccatggttgattttaggctaccttatttttaatttccgttacacagaaacgaattccac -aactaacatgccattaatttttcgatatcttataaaagatggtcgaaattcattcattta -ttttttttcggttctcgaaagtcaactaagctgtcgcgttttgtttctctttagaggtaa -aagtggctttgatctcctacgtttggatactagtcaaccattactccatttgatccgtga -gtatcacctgtctaacatccagcattatgactcctcggcgaagaaaagacacacttctta -gagtcgatgtgtattagctagggacacagttgtttaatacgatagtgagcccagggaggg -cagtgcgtcccccagtagatttattcagctagtgtaagtataagatatctcacccacgag -gttcaagtgatatgcagtcttagaataatacttatcctgaatttcgatattatgggtact -tcaataatccgctagcgctactttatgtctcgttggacagcaggacacatggcagtctta -aacactaaagacatcacctgaatgaatgtaatgggattacaagaatcaatgaggtattat -atacgacgtaggaaactctggatatatacagtaatctagttacgccatcgcacttcattc -ctctggaaacttagaagacatcagctgtacgtggaggaaccagacccccgtatgtagcca -aatagaaccaaagttgcttatacaaacacacccaatgacaatggaccgctggagttcgta -aactcggaacgtagtactgcacaaacccagcatttagcaataggagctacgtatgcaact -cccacgtggtaataccttcaagctatcaatatataggtgcctagctaatcgcattcgcaa -gcagtattcaagcttgtaaaccagtataataattacagaggctctatgaaacccaacttt -ccagctaaaagtcccaattaaatggttatttcgtacttttaaagtcgcccgttctgttat -tacgcgaattgattctactccaaaattaaacacaaattatcaaccgtttcatttatattt -gtcaatgcagctgtttaaaataaggctctactaaattataattaagacacttattaccag -atttctctagttaagtttgaaccagctcgactaccgcgaaagatacattcccttctctat -ttttcagttcatctatgggtcagagaagcattgaatttattctattcaccctcgtcgttc -acagcgaatcgtcagtgtgatcagtgtatgagaaatatcctaaaccgtttagtcagacca -cacgcttagaacaagtggtctaaaaagactgccctggaaggagtaagaagtatacagctg -atccggtgtatccttcagtcatctgccctatactaattacacgacgcaaggaaaaatagg -tttattttctaggcaaacccttcataggtgactccgatgtgttacgaatcatgcttgaga -atgtgctatcgttaccgacggataataacgatctccaatgaaccaaatgtagaatgtcta -ttgattacccttttactattcgacttagagataggagatagaacctcagtgtactttttt -agccgaatgggaatctttgggaggtgaatggccataaggtcgtaaatccaaccctcttaa -agtcttccatattatatcgttgttcgtggaatcgataacagatttgttgacccatagtaa -atgtatactagtttatgttgtaagtgtagattgttttccgattgccgtccaaactttatg -tcgtaattgtagaccagtaaagttgaccaaggtaagtgcccagcgatcctgcgagatcga -tcgccaatttttccagtcactgtaagtgtaggtttagataaagccgtatgagttatatca -taagggcctcggaaagcagcttcgaaccaaagttcccttataatagtagtttaactataa -aagtatatactggtctgtcgccctttcacgatttgttttaccggtttatgaagcgttacg -tcattagagcggctccaatttaaggttaacggcttccatgtgtagttgtatacaaggata -acttaaagtatctgttcagcgagctagttaagttatcctcgatagaacacaactcagagg -tcccaagatcgggtttgcaacttgctaatttattctcaaggcaaattgggaattatcgat -acctgtataccataaggtcgctcgatgtgatgcttatgtcttctggtgatcctaccttag -ttagtgctgattaacggaacattaatgtttatcgttttgagatttagccaattctctgat -tctaactcaagatgccttatctgacgtgctatgcagcccctaagtattttacattgtaat -aggacacgctcctttaaaactcgccaaaaggtcgttgtggttctctactggttaactata -taatttacagctttgttgagctagttcctctttggtttaagtcctcaatattagttggtt -cgagcgataagttggctagttaccttagtcactatattagatccgaatgttatgcttcat -ctgaagaccgccaccctccaaaatttcttttaagactcacttattgcaaggtgtaggtga -attcggctcgtttctcaagtggtgtatctgtacacgagtttccatattttcatcaacagc -caccgcacacttatgtcactctaggtattaaaagtcgctctacaaggggacgcaattaag -aaacagacatgctagtcaaaaataaacatagcgaggcaccactaattcggccgcttatca -atgggatgctctgcgcgagacgcgccagagctcagtagttagttcggacatacatttact -tcagatgatcaattagttttctacaaatgcttactctaccccgaaaaaagtcaccagact -cttacgtctctttagtatccttccgtcttatataaggtcagtcccccgtttcggtaccct -ggaatttactaagaataatgaaacagcccccaaggacgtacgtttacaaatgatagacca -gatcgcctagcttattccgacgcatgttgcatagaattgaaccaacggaatgtgagagta -actagatgagccgaccacagcacccgtttgcgtcgcagaatacgcctgatagttcggcca -cgaaatcatatgtcctttgagtattaagtatttgtaatgatcaatcgagctcaagcaagc -ttacacttcctcggatattcagggaacttagtgcctttgaaagatacgttgatcaacgaa -aaattgataatggctcatatggaatgcctacctcatagtgctgaattaacacagcactgc -ggacctaacttttcgaggtttcaagttcacgtctcaaaacctaataggctggaatatgta -gggatcctcggtgaatttgtgattgggtttgttgtagtactgaccaagtgaatattcttt -ttttctaaaagcagatctgctgccgggcactacgaaggagatctctgtgtatcattattg -cttcttgacatgatgactcttaaatcactgtgggtgtgcaaaacgatagcacaacccaat -tcgatagtacatattgttgatacttcgcactaaaccgttcatatttaaaggttgtgctcc -ttccttcgttaaatactggtgacttggtcctatctactattagctagacctctggggaac -cacgcccccgtaaaacctgtgcaagagagggggtcatacatcttagacatcgcgcctcca -ccagggaagcattgggtgattgaccaggtgtgtaacaaatatgattattcttatactaat -attagcaaagatgcataatgatttgtattaaatgtataattgaattgataagggtctttt -agtcagtgatagagtagtataaggtagacattagaactcttaaccggacgcagatttttc -ggtcttagtaagccaattagtcgacaaaacaaggtaagagcggttactagtagtacctat -aatgcactgaatcttcggtcgaagtatagttctaatgctatgcagattgtgacggcgaca -aatgttcagacttatatcatgaaacaagctcttgtaagtattgacaaatgaaaagattga -atatttttaaatacaaaatgcgcctacttattaggggaattaaccagattgaaggccaat -cctcacatgtaatgagataatagacgataaatgaaattcttgtaatagttgaactgctac -gtgatgggtattatatatgattgagatcctccaattgccgacgtcttgtcttgatgccca -aaagattgtcaacgaggagctccctcgcgtacctgtcgtccgtatcataaacgacgcgac -atgtacagcactccgaagtataagcaataataatgcgggtaatccagactagatcttttc -ggactcaatgcggtttcacggtaaacatgattaataccggagagtagtcgagcttatcag -cgatgcaagcgaattcattgtgccaggagatacgttgcagataaaaccggcaacgtatgt -caacaagttttggcgatctcgttgtttgtattcgacgaggcgcgggaacttcaagaacta -tcgtatattcaagtccattaccttttagtttcagactggtggagctgactaaagttatat -catcattttgtacactggtttagttaacgataatttcagatttaacatgaccagacgata -atcgctgtatatccagttggaatgtggtttgccagaaaggttaacttataatcaagcctc -tcttcagtcttgattcgtcgtatcccatccattgcgctatacctcagtgtatttggagct -gtagttataccgtgtgctaagatcagtagacatgacgagagcaatattatctaccttaca -agcatcaacggacgtctagtcggaacaaaagactctaaaactcgaacttcaggttaatat -actatagttctgtattcagcagttattcttatattcgatattatcttgcctattggatgt -ctgactttagtatattaatcatagtatctgccatgtaaaggtgccagtactaaatctgtt -tcacagtgcgaattataaacggttacaaccattaaagacaacaagaccctatagctttat -ttgaattttgtcaatgcgcaacttggagctcgcgatacatcccaattagtctatagggtc -gggacgattctacggcatttctggttataatgacaacatggattgtggcccgagaatcgc -tctttcattaattaagcaatcattacagtcttataagcgctacttccgagtggtagcagg -taactcgatataaggtcgcatgagccgaatagcttaaaaaacaggccaccgaacattgat -agagaataccgaccacagcgcaacctttgattactttcattaaattgtacggctcactcg -acatcaagcttaagattgcgataatgtgaactcaaatggatcagtactgaagaaccgtaa -cccacttcgcagaaagcgtacccagagaagatacgctgttacaatatacagggtgaaatt -attgcctgttcttcgtaaccatttcgccaaacttggttagaaatgatagccattcatgat -agaaataagctgaatgataccagtatctttaactatgtagtcagggggaagataacgatg -gtccatgtatgtttctgatatgtgacagtattggccgcgtaatttgctaacgaagctact -taatgcctttgagcttcatatagatttctttaatcaaaatcggcaaaaagatagtatgag -ctataatatatgctagtagagaactctggaccatcatctatatgaatactgattcgagcg -tgcaattactttagcctgcgtactactgactctacaaaacactctgagataagtttgtag -tcagtaagtcgctctctataaaccttttggatgaccattgtacagccacttatagatccc -aataaatagcacaggagacagagtttttcaatgctcgatcatttgccgatagtattttcg -tctaacctcagggcacctattatttgatacctaacctaacggccctttcacaatggagaa -atatatgacatcgggacaaacacaaatggtgggtggccaggagatatgacatggtggcgt -ctctaagaaacacggactccctctaggcaaactcacgtaaccaattttaatgtcaaacaa -aacgctcgaaaagattttgccgtgtaatgacctggtacattgactggtcaggaatacatc -actgtagttgccgtagtgtcctgttggtgttccatcaagacacatcgtataacgcaattt -acgacggacatcagatcaagttatacagattatttaagtatcacgtgtgcattgggacat -aagggatctcacacatgccttggaacatttttgctttgtgccgctttttcgctgcactac -caatccttacttaccagtatattcaaaggtcgttaacagaatgagaaaggttagggctct -aagttatcgtcgattgggatagacgagacatttgcgagcgccctccacggatacgaatct -cccatatcaatgtgaactggatgctatgcagtttagttcttacgtctcctagtggtaaaa -atcaaagtagcactcgcatagcagttattcagaacctaatacacaaaaccgtcaaacatt -ttctaattctaggtatgggccgatcataggagctaaggtgaaactcataaatgttttgtt -agatctagcatcctaaaaagatgcatatactgagtagctggcgtgcattctctcaattgt -atcctttttaactgaactagtcggtcccatttcgtgactgagatctattaaccgataaga -ttaataacactcgcattcgtatcagctcagagtgaagtttttcaataatttgactgatat -attaacttctaaaataaccctttaagcctcggatccgtttcccaatcacatcaaaaattc -ttattccaactatctacggattaacaacgtgcatggggatcgtagtaagaacttgttccg -atcactttgagtatatcaagttgacggcccggttattattgaatagaaacattcacctgc -taaattaaataccgcacatcggatacccgatttcagagggccgtcttactaagggcaggc -tttgttcggtttaactgagatgttcattattttacagtatgcttcaactaatatgtaacg -aaggacagtggatctgtctccatagtagatcttcagtcgtgaatttcataccgctcctat -ttaagttcgcgttcgagttgttgatcatggcacgtgaaagcaacccctagtattctagac -gaaaattttttctagttcatctgataatttgccaattcaaaaacaaccgctggtttcccg -gcgcattctctaaaatggaagtcgaacctagagccattatttgtcggtaacccatgagtt -ccttcttttcagaagttaatacactgtggtcctatacagaggaaaaacagcggttatata -cgatcgtggcataacaacattggatcaagatagcaatttggctacctattctaattctca -ctagattcggtattccactacaatatcggcagattaggattggatgaataatcggtgttt -aagtccggttgcgtctccaatctcctaatttttattaatattgatcttggtgacctattg -taaataaaaacttcaagactttgaataacggtgaaaagatagaagactcatttgaaaatg -gatcatccacagatccaaacattagcaagacactaatccccaactagctattctgatcgc -gatcgtgctgcagtactcctgtcacaatagtctgttcatgatctaattctttttgggctt -tgttcgatggtgattcagaatctttatccggtcgcttccctgtagctactttgtggggat -attgcccggggattatagggttgagatcgtttcctaaaagtatttaaaccaagtagactt -caactaaactacatcagaacatcgtgaagacaccatacgcggtacctttatttaccgata -acatttcttcaagaaataccggtaagcagcataatgaccctaaacagctcggggtatcgt -cgtagttttaaattttatttaggttactgctcaaggaataaaaactaactatttaattta -taataatattacaaggctcacactgattagatttgtctataagacttcgcgatcccccat -taccggattgtcttaagaataaactagataaaccatgcattttctagataaggcctttag -tctaattagatacaaaaaacacgatagttgcatccttaatttattgtgtcaaacctggaa -ccttttaattacccgcaaatcactttatgtcgagactacctctgaaatttattatctacc -taccgcatgaggacttgaaccatcttgtaggagttatgtttattagctaagattcgttta -tcctgtagcggtccatgtatattcaacaagcaaaaagcactcagaattgtttttagttga -gtcaagactgatatataaataagtttccctagttttttcgtggtgggacgatattgaatt -gaatcttaaccgaagagtttcccactctgtcgcacaataatacacgccaatatttccagc -cctgcttatgccttaatcggttactcaatctcccattgaagttcattttgatctgcatag -aagtttcgggcccagccttttttctgccaccttcctccaagctctgtagacgcactctaa -gattgatgctcacatgtattaattctacattaacataaatatataagtcatgcatcttcg -agtaaaatatctggttctccaacatgtcctggcacgtatcgttataatgcccatacatgt -agtattaaaatgattgggttaactggatattaagatcatcgaaattgtaaagtcaaatta -acaatactgtctcaagaccgtgtattcctcgtgctcggaagggctattacgcttacttcc -gttttggtatcttaatatgactttcaaaaattaagttgcagtgagtcctacctgcgtgca -tcggttagcaagagtataaaagttgtttaaacgaactacttgctttacaataccggtcgt -atatatcgccgtgaatccagaagattgtcttctttggattatcaaccgagatcctgtgga -ccgatgttttgggaccttcacagaggactccaggtagagctcgcttttgcattaatctaa -gaattgtacctctctaaaagatctaaaacagtgaatgtgtatttcatggaaaaacacaga -gaaacgtaaattactttaggccgaaaggcacatgagttattatacatatacgagatggtg -gtatacatcgaattcggggcatacactatagttgcattgtatttagctgctttaaataat -atgatattaccttccttacataagacattaccggcataccctggttttcaacttgtgggg -ctttttgacgatcgcactctcatttgatccgagtagggcggtgacccctgcttttcaaat -acaaaaatttcgctatgaaggtaatagattacttttcgctgttatgatagaaacggtaaa -tttaaaattgaaacttctagaaaagtaaagtaacgagaaatgattttgtgaataatgcgg -tcatgattgcgcaagtaagaaaaaaaggcaaaaggatgcgcggaatagaaacttatcagt -cacgggtatcttgatttcattcttcttgtcaattgccgacataggatgaaatcagattcc -aatgcaatacacagtaacccccacccttgattgtaatgtcgatttgaagttgtacgcgtc -gacgaagtggatagtatacgggccttttgtacggtgcgatcaactatgaatctcggcgag -ttagatggtcgtacaatctcacacatagaggtcacttgcctgtaatgacgaattttcggc -taggtactcgaactttattagaagtaaaaatgtgggcaaaagaaggattccattttacaa -gacgattacaatgagttacatgtctctcaacgtagtctttccctagtagtctttgaacta -tttaggtactccagaaaattttagcaaagggtttctgtgtgaatccgccattcatgttta -tgatggaacaataagaataacgccctcgtatgttatcgacagtgaagtcagcagttcggc -caaaaacatattcaatttagtacagatccccagaagttaagctaagtgctctaaaatggc -ctaaacggttatcaaagtaggtctaattactatactaacgggtgcatcgtaataactgct -gtcgatgcaacactatatgatagtgtcgttttgctatatatgtacaatgtgacaaagaag -ccttagcgattcttgcaaacttaggacttcggattctcaatcttaaatgtccgaaaacgc -aaagattcaaaaatttaatctatgagcagatatgcctgatggtgactacgcgtatgttaa -ggctaaatgttgacaaccgcacacataatcgaactattgatagtcgggagcataaccagg -tgaacgtactttgttcacgacatttattgacatgttctaaatacgtctcaaaatcacggc -gcactagaaaacgcaatcaaatcattgtcctggtttaagggccgtaatgccggtagtgtc -aaacttcatgagaactttagctggcttttggccagtatttagggaccaagagcactagcc -ttaagctgaatattttgccatttatctactgttataactttaaaacttggtggcaccaga -cttgtcgatacacacgcatcaatctgtaacgtaaaaggtttactaagaacaagcgtagga -attgagtttatattatatttaaactaaaagatgatattagcttctgagggcgatagggct -ccaaatcataaagaggaatatattattacacgattagaaacccacaacatacctcgaatc -gcccaaaagtttgacgaaacttggcagtactccacatctcagtaatacagttgggagagt -ctcaaatgttgttttattactcaatgaaccaccctcataatttcactgctgttccattaa -atttgcaaacgatcatttgctttgaagaaacgtaaaatcgacaaaattacagataagtag -atgcataataaaaaaaactgctcgctataacacgatcatcgtgcattcttacttaggagc -atcacccgcacaataacgtaccttaaactacaacactattagaccgagtactgtaattca -cgaaagctcaagctcgcattgtaaagaacttgctctctcgtaaaatgtgataatagtttg -cggagaggattcaattattttccattgcacctactccactagattcgataaaagaaggtg -gtcctcccttaaaaagaaatgttaagtaacatcggaaccataagcaaagcatgtaagtga -accgtcatccttccctaagaaacataaaggtttttaataatgtcgactgtgaactataac -tgcatcctttcctgacctactccggttccttgttgttatttctgaacgagaccagtagat -aaacaatgtaaaccacagtgggtaccaatggtgcatgtgacgctaccgttgttttaagtg -cccgtacaaacataagaagtcataatcttacttgaaattaattttgccttttattttttt -tcaggctcgaaattaatgatttgttttttttgaccttctagttacgctaatatgcggtcg -cctgtggtttctattgagtcctataacgggatgggatctaatacgtttggttactagtaa -acaaggtataaatttgataccggagtatcaactgtataacatcaagctttatgactcata -cgcgaagtaatgacacaaggctttcaggagatcgcgagtacagagccactaaggggtgta -ttacgatagtgacaccaccgagcgcactcactccccaagtagatttatgatcctacgcta -agtattagatatataaccaaagaggttctagtcagtgcaactcttagaataataattagc -cggttttgcctttttaggcctaatgcaatattcagctagcccttatgtatctcgcgttcc -acagcaccactcatggcacgcgtttaaactaatcaaatataatctatgaatgttatgcca -gtacttgaataaatcaggttttttataagtccttgcatactctcgttatatactgttaga -gtcttaccccatagaaattctttcatctgcaaacttagaagaattctcagctacggggag -cataaagtccccaggatgttgacaaatacaacaaatgtggcttatacaaacactccatat -gaaaatcgaaccctcgtggtagttttagccgaaccttgtacggataaatccctccatttt -ccaatagcagatacctatcctactacctcgtggtattaaattaaagcttgaaatatagag -ctgcatagcttatccaattcccaagcacgagtctaccgtcgtaaccacgatttgatttac -agacgctagagcaaacccatctttaaacatataagtaaaaattaaagggtgagtgcgtac -gtgtttactagcaacttcgcttattaagacaattgtttataagccataattaaaaacata -tgttcaacaggttcattgatatttgtaattgcacaggtttttaataaggatctacgtaag -tataatgaacaaactttttaccagagttatattctgtactttgaaaatgctcctctaccg -ccttagagactttcaattagattttttgcagttaatctatgcgtaagtgaaccatgcaag -ggatgcgattcaaccgcctcgtgctaaccctatcgtctgtctcataactgtaggtctaat -ataattttcagttttcgaacacataaccctttgaaaatctgctatttaatgtctcacctg -catgcactatcttctatactgctcagaacggctatacgtcactatgctccaagtgacgat -ttaaacgaagcaaggaataataggtttattttagtgcaaaacaattaagtgcggactacg -tgctctttacaataagccttgtgattgggctataggttaagtcccatattaacgatctcc -aatgtacaaaatcgacaatcgctttgcattacccggttactagtcgaattacagatagct -gttagatactcactctaattttggacaacaatcccaatcttggggtcgtctatcgcctga -agctcgtaaatccttccatcttaaacgattacatattatagacttgttcggggtagagat -atcacagttgtgcaaacattgtaaatcgatactagtttatgttggtagtctagttgcttt -taccattccccgaaaaacttgatctactatttcgacaacagtaaacttgaactaggtaag -tgaaaacagagaatgcctcatagtgccactatttgtccactatatgtaagtgtagcttta -cataatccactatgactgagatcattacggcctaggaaagcagcgtagaaaaaaagggcc -cggatattacgactgtaactataaaactagttactggtagcgcgccatgtatagatttgt -tttaccggttgtggttgcgttaacgaatttcagccgcgaaaattgatccgttaaccagtc -catctcgacttctataaaacgataaagtaaagttgatgttcagcctccttcttatggttg -catcgagagtacactactcagtgggaaatagatcggggttcctacttcagattgtattat -ctaggcaattgccgattgtgccatacctggataaaataagctacctacatgtgatgctta -tctattatcgtcatactaccttagggtgtcctgttgaacgctacattaatctttagccgt -ttgagatgttccaatggataggagtctaacgcatgatgaagtttaggaaggcagagcatc -ccactaagtatgtgacagtgtatttcgaaacgagacgttataaatagaaaaaaggtcctt -ctggttctattctgctgaactattgaatggaaagattggttgacctacgtactatttgct -tgaagtcatcaatttgacggggtgagagacatatggtgcatactttacggactctatatt -ttagatcagaagcttagcagtcttctctacaccccctcacgacataattgcttttaagaa -tctatgtttgattcctctacgggaattcggatccgttcgcatgtgcggtttatctaaacc -aggggacatatgttcagctaaagcatacgaacactttgctaactagacgtatgtatagta -gctataaatcccgacgatatttacaaaaagaaatgagactcaaatatatacatagcgacc -ctacacttattcgcaccctgatctaggcgatcctagcacccacacccgaaagtgagcact -agtgtcttccgtattaaatttactgcagttgagattttagttgtctactaaggattactc -taacccgtaataaggatcaagactcggtactagctttactatcattccctatgtgttttc -ctaactcacaagggtacgtaccagcctatgtaattacaataatgataaagacacaaagga -agtaactttacaaatgagtctccagttacactagcttagtccctcccatcttgctttgaa -gtctaaatacgcaatctctgaggatatacagcagaagaacactcataacgttggagtcca -agaattagactcatagggcccccaacatttaatatgtactgtgagtttgaaggtgttcta -ttgttaattcctgctcttgatacatgacacgtactccgtgtttaaggcttcggactgact -ttctttcataagttgagcaacgaaaatttcagaatcgataagttggattcactaactaat -acggctgattgaaaactccactccggacctatatggtcgacctttatacgtaaccgatat -aaaacttataggctggtatatcgagccttcctagcgcaatttcggatggggtttcttcta -ctactcaacaacggaatagtctttgtttagtaaaccagagctcaggacgcccaatacgta -ggagagcgctgtggagcatgtgtcattatggactggagcactcttaaatcactctgcgtg -tgctaaacgatagatcataacatgtcctgagtaaattttcttgatacgtcgcaatatacc -gttattagttaaacgttctcatccgtcatgcgtgaaatacggctgtcgtgctcagatata -ctattagcgactcatctcgcctaacacgcacacgtataaactcggaatgactgccgctct -tacatattagaaatacagactacaccacggaagcattgggtcattctcaaccgctgtata -aaagatgattagtcttataataagattaccaaagaggcagaatcatgggtagtaaatcta -ttattcaagtgattaccgtcgtgtaggcagggagtgaggacgagatggtactcaggacaa -atattaaccggacgaagtggtttacgtcgtactttcactattagtagtaaatacaaggta -acaccggggaatagtactaaatataatgatatctatcttcgggagaacgagtcgtctatt -gctttgaacattctcaaggcgtaaaatgtgctgacttatagcatgatacaaccgattgtt -acttttgtctattcaaaagattgaatagttttttatacaaaagccgcatacttatgacgg -ctagtatacagtttcatcccctagcatcaatgctatggacagtattgaacttataggaaa -ttcttctaatagggcaaatccgtcgtgatgcctattttttttcagtcacatcctcaaatg -gcactagtattgtcgggatcccattaacaggctcaaccacgagctcacgcgaggacatgt -agtccgtatctttaacgaagcgacagcgacagaactcccatggataaccaattataaggc -ccgtaatcctctagacatcgtttaccaataaatccgctttctccgtaatcatgttgaata -ccccagagtagtccagatgataaccgatgaaacacaagtctttctcaatgcacttacggt -gaacttattaccgccaacgtagctcatcaaggttgcgacatctagttgtgtgtttgcgac -gagcccagcgaacttcatcaactttcgtatattcaacgccttgtaattttactttaagac -gcctggtgatgtagattcttagataatcagtttgttatcggctgtactttaccataattt -cacaggtttcaggtcaagaagattatagctgtatatacagttccatgctcggtgcacaga -aacgtgatcggataataatcaatcgcttatgtcgtctttaggcgtatccaatacatgccc -cgataccgcagtgtatttcgacatgtaggtataccgtcgcatttgagctcgagtcaggac -gtcagctagattagattccttaatagaatataccgacctctagtccgaactaaactatag -ataacgccaacttcaggttaattgtctagtcgtctgtttgcagatgggattcttagatga -gtgagtatcggccatattggttcgagcactttagtttttgatgcataggatatgcaatgt -atagctgaaagtactttatctgtttcaaactcacattgattaaaccggtaaacctttaaa -gactacaagaaaatattcagtgagggcaattttgtcaatcacaatcttccagctagagat -acttcacaatttgtcttgaggctacgcaacattagacggattttcgcgttttattgaaat -aatcgaggggcccaagagtatccatagttcattttgtaagatttctttacaggcttatta -cagcttcttcagactcctacatgcttacgagttatatgctagcatgtgaacaatagatta -atatacaggaaaacgtacattgagagagatgaccctacacagcgcaaccgttgagtactt -tcattaaagggtaacgctctcgagacagcatccttaagatggccttattgtcaaatcatt -tgcagaagtacgcaagatccctaaccaacgtagaagaatccctacaaacacatgagacgc -ggtgaaaatagacagggtgttagtattcaatcttcggagtatcaatttcgccaatcttgg -tgagaaagcataccctttcttcagagaaagaagatcaatcataacactatctttaacgag -gtacgcacgcgcatcattacctgcctccatggatctttaggatagcggaaagtattggca -gcgtattgtgatttcgttcctactttatcaatttcacattcatatacatgtcttttatca -aaatcgccaataagataggatgagctatattagatgctagtagagttcgcgccaacatca -tcgataggaatactcaggacagcgtgataggacttttcaatccctaatactctctataat -tataactctctcttaagtttggaggcagtaacgcgctctatataatcagtttgctgcacc -attcttcagcctctgatacatacaaataaattccacagcagtaagagggtttaattgaga -catcttgggaacttaggattttactctaacatcaccgaaacgattattggataccgtacc -taaacgaactttctcaaggcagtaatataggacatccgcaataacacaaatgctgcctcc -ccaggagttatgtcttcctggaggctatatcttacacccactcactataggcaaactaaa -gtttaaatgttgattgtctaaaaaaaagatagataagagttggccggcgtagcacatgcg -aaagtgaatcgtaagctataattctctggacttgaagttctgtcctgttcctctgcaaga -aacaaacttcctttaaagctatttacgacgcacatctcagcaagttataaacatgttgga -agtttctagtcggaattcccaaagaacggatctatctaatgcattcctacatttttcctg -tctgccgatggtgccatcctattcaaagaatttcttaaaagtagattaaatgggactttt -aacaatgagtaaccttacgcctctaagggttcctcgagtgccatacaccagtcaggtccg -agccacatacacggagaacattctaacatagcattctcaactcgatcatttgcaggttac -ttctttcctatcctagtgctaaaaatcatacttgcaatcccatagcacggattaagaacc -taagaaacaattcagtaaaacatgttcgaattcttggtatgggaacatcattgcagctat -ggtctaacgcattaatgtttgggtacatcttccatcatataaacaggaagagtctgacga -cagggagtgcttgcgatcatgtctatcattgtgaaatcaaattgtagctcacatgtcgtc -tatgagagcgtgtatccgataagatttagaaaaatagaagtcgtataagatctcactgaa -cttttgaatgaatgtgaagcatatatgatctgctttaataaaactttatccataggatac -gtttccaaatcaattcaataattattagtcaaaatagataaggatgaacaacctgaaggc -cgatcggacgtagaaagtggtcccatcactttgagttgatattgttgaaccacacgttat -tatggttttcaaacagtctcaggatattgtatatacagataatccgataccagttgtctg -acgcccctcttacgtaccccaccctttgtgacgtttaaagcagttgttcagtattttaaa -ctaggcggcaactaatttggaaagaagcacagtggatatgtctaaattcttgttattcag -gcctgaatttaatacaccgcatagttaacttcgcggtagagttgttcatcatgcctcctc -taagctaccacttctatgatacaccaatagttgttctacggaatctgataattggccaag -tcataaacttccgctgcgttcaacccccttgctcgaatatccaactcgaaaagacagcct -tttggtgtccggaacaaatcagttacttcttttctgatgttaattctctgtggtcagata -cagaccaaaaactccgcggatttaccatcctccaagaacaaatttgcatcaacatagcat -tttggctacatattctaagtctcaatagtttaggttttcaactacattatcccaacatta -ggattggaggaataatagctgggtaagtccccttgcgtctacaatcgactattttttatg -aatatgcttctgccgcacctatggttattaaaaaagtcatgactttgaagaaccctgaaa -agatagatgaatcaggtgtaatggcagcagccaaagagcatataattagcaacactctaa -gaacattatagatatgatgatagcgatcgtcatgatgttatccggtcacaatagtagctt -catcagctaattcgttttgccagtggtgacttgcgctggaagaatcgttatacggtccct -tccctcttgatacggtgggggcttattcaaccgcgtggattgggttgtcatacttgcatt -aaacgatgtaaaccatctagtagtcaactatactaaatcacaaaatagtgatcaatacat -acccgcttcatggttttaaccatttaattgattaaagatattccgctaagaaccattatc -tacctaaactgatcgccgtatcctagtagtttgaaatttgatgtaccgtaatgatcaacg -aagtaaaacgttatattgtatgtagaataataggtcttggagctaaatgatgtgattggt -agtgaagacttacccttacaactttaccggtttctcggaagaatatactagagaatcaat -gcatgggctacataagcactttagtctaatgagataaaaaatacacgagtcttccatcat -gaattttttgtcgaaaaactcgaacctggtaatttaaaccatatatctttatgtcgtcaa -taactctcatatgttttatataacttcccaatcacgacttgtaactgcttgttcgactga -gctgtttgagctatgaggccgggatccggttgagctacatctatttgctacaagaaaaat -gaaagcacatttgttgggagttctggctacactcatagagaaataagtggcccgagtggg -tgcggcctgcctccatattcaagtgtatcttaaaccaagtggttccaacgctcgcgctaa -agaattaaagcctttatttcctccacggagtagcccgtaatccggttcgaaagagaccat -tgaagttaattttcatatccagtgaagtttaggcacaagcatgtgttctgccacatgcct -caaagcgctcttcaaccaagatatgattcatcctaacttcgatgaatgcgtctgtaacat -aaatatagaaggaatgattcggcgagttaattttcgccttctccaacatggcatccctac -gttcgttataaggaccatacatgtaggttttaaaggtttgcggttaatcgatatttacat -catagaaattctatagtcaaatttacaagactctagatactcactcgttgcagccggcta -ggaagcgctttgtaccttacttcccttttcgttgcgtaatatgaatttcatatagtaagt -tcaaggcactcatacctccgtgaagagggtagatagactattaaagttgtttaatagtac -gtattgatggaaatgacccgtaggagatttaccactcaatccacaagattcgctgctgtg -cattatcaaaacagtgcatgtcgaaacatgggttgggtccttcaaacacgaatccaggta -gagatacctttgcaattttt diff -Nru cargo-0.25.0/vendor/regex-0.2.6/examples/regexdna-output.txt cargo-0.26.0/vendor/regex-0.2.6/examples/regexdna-output.txt --- cargo-0.25.0/vendor/regex-0.2.6/examples/regexdna-output.txt 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/examples/regexdna-output.txt 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -agggtaaa|tttaccct 0 -[cgt]gggtaaa|tttaccc[acg] 3 -a[act]ggtaaa|tttacc[agt]t 9 -ag[act]gtaaa|tttac[agt]ct 8 -agg[act]taaa|ttta[agt]cct 10 -aggg[acg]aaa|ttt[cgt]ccct 3 -agggt[cgt]aa|tt[acg]accct 4 -agggta[cgt]a|t[acg]taccct 3 -agggtaa[cgt]|[acg]ttaccct 5 - -101745 -100000 -133640 diff -Nru cargo-0.25.0/vendor/regex-0.2.6/examples/shootout-regex-dna-bytes.rs cargo-0.26.0/vendor/regex-0.2.6/examples/shootout-regex-dna-bytes.rs --- cargo-0.25.0/vendor/regex-0.2.6/examples/shootout-regex-dna-bytes.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/examples/shootout-regex-dna-bytes.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,66 +0,0 @@ -// The Computer Language Benchmarks Game -// http://benchmarksgame.alioth.debian.org/ -// -// contributed by the Rust Project Developers -// contributed by TeXitoi -// contributed by BurntSushi - -extern crate regex; - -use std::io::{self, Read}; -use std::sync::Arc; -use std::thread; - -macro_rules! regex { ($re:expr) => { ::regex::bytes::Regex::new($re).unwrap() } } - -fn main() { - let mut seq = Vec::with_capacity(51 * (1 << 20)); - io::stdin().read_to_end(&mut seq).unwrap(); - let ilen = seq.len(); - - seq = regex!(">[^\n]*\n|\n").replace_all(&seq, &b""[..]).into_owned(); - let clen = seq.len(); - let seq_arc = Arc::new(seq.clone()); - - let variants = vec![ - regex!("agggtaaa|tttaccct"), - regex!("[cgt]gggtaaa|tttaccc[acg]"), - regex!("a[act]ggtaaa|tttacc[agt]t"), - regex!("ag[act]gtaaa|tttac[agt]ct"), - regex!("agg[act]taaa|ttta[agt]cct"), - regex!("aggg[acg]aaa|ttt[cgt]ccct"), - regex!("agggt[cgt]aa|tt[acg]accct"), - regex!("agggta[cgt]a|t[acg]taccct"), - regex!("agggtaa[cgt]|[acg]ttaccct"), - ]; - let mut counts = vec![]; - for variant in variants { - let seq = seq_arc.clone(); - let restr = variant.to_string(); - let future = thread::spawn(move || variant.find_iter(&seq).count()); - counts.push((restr, future)); - } - - let substs = vec![ - (regex!("B"), &b"(c|g|t)"[..]), - (regex!("D"), &b"(a|g|t)"[..]), - (regex!("H"), &b"(a|c|t)"[..]), - (regex!("K"), &b"(g|t)"[..]), - (regex!("M"), &b"(a|c)"[..]), - (regex!("N"), &b"(a|c|g|t)"[..]), - (regex!("R"), &b"(a|g)"[..]), - (regex!("S"), &b"(c|g)"[..]), - (regex!("V"), &b"(a|c|g)"[..]), - (regex!("W"), &b"(a|t)"[..]), - (regex!("Y"), &b"(c|t)"[..]), - ]; - let mut seq = seq; - for (re, replacement) in substs { - seq = re.replace_all(&seq, replacement).into_owned(); - } - - for (variant, count) in counts { - println!("{} {}", variant, count.join().unwrap()); - } - println!("\n{}\n{}\n{}", ilen, clen, seq.len()); -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/examples/shootout-regex-dna-cheat.rs cargo-0.26.0/vendor/regex-0.2.6/examples/shootout-regex-dna-cheat.rs --- cargo-0.25.0/vendor/regex-0.2.6/examples/shootout-regex-dna-cheat.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/examples/shootout-regex-dna-cheat.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,88 +0,0 @@ -// The Computer Language Benchmarks Game -// http://benchmarksgame.alioth.debian.org/ -// -// contributed by the Rust Project Developers -// contributed by TeXitoi -// contributed by BurntSushi - -// This technically solves the problem posed in the `regex-dna` benchmark, but -// it cheats by combining all of the replacements into a single regex and -// replacing them with a single linear scan. i.e., it re-implements -// `replace_all`. As a result, this is around 25% faster. ---AG - -extern crate regex; - -use std::io::{self, Read}; -use std::sync::Arc; -use std::thread; - -macro_rules! regex { ($re:expr) => { ::regex::Regex::new($re).unwrap() } } - -fn main() { - let mut seq = String::with_capacity(50 * (1 << 20)); - io::stdin().read_to_string(&mut seq).unwrap(); - let ilen = seq.len(); - - seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); - let clen = seq.len(); - let seq_arc = Arc::new(seq.clone()); - - let variants = vec![ - regex!("agggtaaa|tttaccct"), - regex!("[cgt]gggtaaa|tttaccc[acg]"), - regex!("a[act]ggtaaa|tttacc[agt]t"), - regex!("ag[act]gtaaa|tttac[agt]ct"), - regex!("agg[act]taaa|ttta[agt]cct"), - regex!("aggg[acg]aaa|ttt[cgt]ccct"), - regex!("agggt[cgt]aa|tt[acg]accct"), - regex!("agggta[cgt]a|t[acg]taccct"), - regex!("agggtaa[cgt]|[acg]ttaccct"), - ]; - let mut counts = vec![]; - for variant in variants { - let seq = seq_arc.clone(); - let restr = variant.to_string(); - let future = thread::spawn(move || variant.find_iter(&seq).count()); - counts.push((restr, future)); - } - - let substs = vec![ - (b'B', "(c|g|t)"), - (b'D', "(a|g|t)"), - (b'H', "(a|c|t)"), - (b'K', "(g|t)"), - (b'M', "(a|c)"), - (b'N', "(a|c|g|t)"), - (b'R', "(a|g)"), - (b'S', "(c|g)"), - (b'V', "(a|c|g)"), - (b'W', "(a|t)"), - (b'Y', "(c|t)"), - ]; // combined into one regex in `replace_all` - let seq = replace_all(&seq, substs); - - for (variant, count) in counts { - println!("{} {}", variant, count.join().unwrap()); - } - println!("\n{}\n{}\n{}", ilen, clen, seq.len()); -} - -fn replace_all(text: &str, substs: Vec<(u8, &str)>) -> String { - let mut replacements = vec![""; 256]; - let mut alternates = vec![]; - for (re, replacement) in substs { - replacements[re as usize] = replacement; - alternates.push((re as char).to_string()); - } - - let re = regex!(&alternates.join("|")); - let mut new = String::with_capacity(text.len()); - let mut last_match = 0; - for m in re.find_iter(text) { - new.push_str(&text[last_match..m.start()]); - new.push_str(replacements[text.as_bytes()[m.start()] as usize]); - last_match = m.end(); - } - new.push_str(&text[last_match..]); - new -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/examples/shootout-regex-dna-replace.rs cargo-0.26.0/vendor/regex-0.2.6/examples/shootout-regex-dna-replace.rs --- cargo-0.25.0/vendor/regex-0.2.6/examples/shootout-regex-dna-replace.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/examples/shootout-regex-dna-replace.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -extern crate regex; - -use std::io::{self, Read}; - -macro_rules! regex { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new($re).build().unwrap().into_regex() - }} -} - -fn main() { - let mut seq = String::with_capacity(50 * (1 << 20)); - io::stdin().read_to_string(&mut seq).unwrap(); - let ilen = seq.len(); - - seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); - println!("original: {}, replaced: {}", ilen, seq.len()); -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/examples/shootout-regex-dna.rs cargo-0.26.0/vendor/regex-0.2.6/examples/shootout-regex-dna.rs --- cargo-0.25.0/vendor/regex-0.2.6/examples/shootout-regex-dna.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/examples/shootout-regex-dna.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,66 +0,0 @@ -// The Computer Language Benchmarks Game -// http://benchmarksgame.alioth.debian.org/ -// -// contributed by the Rust Project Developers -// contributed by TeXitoi -// contributed by BurntSushi - -extern crate regex; - -use std::io::{self, Read}; -use std::sync::Arc; -use std::thread; - -macro_rules! regex { ($re:expr) => { ::regex::Regex::new($re).unwrap() } } - -fn main() { - let mut seq = String::with_capacity(51 * (1 << 20)); - io::stdin().read_to_string(&mut seq).unwrap(); - let ilen = seq.len(); - - seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); - let clen = seq.len(); - let seq_arc = Arc::new(seq.clone()); - - let variants = vec![ - regex!("agggtaaa|tttaccct"), - regex!("[cgt]gggtaaa|tttaccc[acg]"), - regex!("a[act]ggtaaa|tttacc[agt]t"), - regex!("ag[act]gtaaa|tttac[agt]ct"), - regex!("agg[act]taaa|ttta[agt]cct"), - regex!("aggg[acg]aaa|ttt[cgt]ccct"), - regex!("agggt[cgt]aa|tt[acg]accct"), - regex!("agggta[cgt]a|t[acg]taccct"), - regex!("agggtaa[cgt]|[acg]ttaccct"), - ]; - let mut counts = vec![]; - for variant in variants { - let seq = seq_arc.clone(); - let restr = variant.to_string(); - let future = thread::spawn(move || variant.find_iter(&seq).count()); - counts.push((restr, future)); - } - - let substs = vec![ - (regex!("B"), "(c|g|t)"), - (regex!("D"), "(a|g|t)"), - (regex!("H"), "(a|c|t)"), - (regex!("K"), "(g|t)"), - (regex!("M"), "(a|c)"), - (regex!("N"), "(a|c|g|t)"), - (regex!("R"), "(a|g)"), - (regex!("S"), "(c|g)"), - (regex!("V"), "(a|c|g)"), - (regex!("W"), "(a|t)"), - (regex!("Y"), "(c|t)"), - ]; - let mut seq = seq; - for (re, replacement) in substs { - seq = re.replace_all(&seq, replacement).into_owned(); - } - - for (variant, count) in counts { - println!("{} {}", variant, count.join().unwrap()); - } - println!("\n{}\n{}\n{}", ilen, clen, seq.len()); -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/examples/shootout-regex-dna-single-cheat.rs cargo-0.26.0/vendor/regex-0.2.6/examples/shootout-regex-dna-single-cheat.rs --- cargo-0.25.0/vendor/regex-0.2.6/examples/shootout-regex-dna-single-cheat.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/examples/shootout-regex-dna-single-cheat.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -// The Computer Language Benchmarks Game -// http://benchmarksgame.alioth.debian.org/ -// -// contributed by the Rust Project Developers -// contributed by TeXitoi -// contributed by BurntSushi - -extern crate regex; - -use std::io::{self, Read}; - -macro_rules! regex { ($re:expr) => { ::regex::Regex::new($re).unwrap() } } - -fn main() { - let mut seq = String::with_capacity(50 * (1 << 20)); - io::stdin().read_to_string(&mut seq).unwrap(); - let ilen = seq.len(); - - seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); - let clen = seq.len(); - - let variants = vec![ - regex!("agggtaaa|tttaccct"), - regex!("[cgt]gggtaaa|tttaccc[acg]"), - regex!("a[act]ggtaaa|tttacc[agt]t"), - regex!("ag[act]gtaaa|tttac[agt]ct"), - regex!("agg[act]taaa|ttta[agt]cct"), - regex!("aggg[acg]aaa|ttt[cgt]ccct"), - regex!("agggt[cgt]aa|tt[acg]accct"), - regex!("agggta[cgt]a|t[acg]taccct"), - regex!("agggtaa[cgt]|[acg]ttaccct"), - ]; - for re in variants { - println!("{} {}", re.to_string(), re.find_iter(&seq).count()); - } - - let substs = vec![ - (b'B', "(c|g|t)"), - (b'D', "(a|g|t)"), - (b'H', "(a|c|t)"), - (b'K', "(g|t)"), - (b'M', "(a|c)"), - (b'N', "(a|c|g|t)"), - (b'R', "(a|g)"), - (b'S', "(c|g)"), - (b'V', "(a|c|g)"), - (b'W', "(a|t)"), - (b'Y', "(c|t)"), - ]; // combined into one regex in `replace_all` - let seq = replace_all(&seq, substs); - - println!("\n{}\n{}\n{}", ilen, clen, seq.len()); -} - -fn replace_all(text: &str, substs: Vec<(u8, &str)>) -> String { - let mut replacements = vec![""; 256]; - let mut alternates = vec![]; - for (re, replacement) in substs { - replacements[re as usize] = replacement; - alternates.push((re as char).to_string()); - } - - let re = regex!(&alternates.join("|")); - let mut new = String::with_capacity(text.len()); - let mut last_match = 0; - for m in re.find_iter(text) { - new.push_str(&text[last_match..m.start()]); - new.push_str(replacements[text.as_bytes()[m.start()] as usize]); - last_match = m.end(); - } - new.push_str(&text[last_match..]); - new -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/examples/shootout-regex-dna-single.rs cargo-0.26.0/vendor/regex-0.2.6/examples/shootout-regex-dna-single.rs --- cargo-0.25.0/vendor/regex-0.2.6/examples/shootout-regex-dna-single.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/examples/shootout-regex-dna-single.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ -// The Computer Language Benchmarks Game -// http://benchmarksgame.alioth.debian.org/ -// -// contributed by the Rust Project Developers -// contributed by TeXitoi -// contributed by BurntSushi - -extern crate regex; - -use std::io::{self, Read}; - -macro_rules! regex { ($re:expr) => { ::regex::Regex::new($re).unwrap() } } - -fn main() { - let mut seq = String::with_capacity(50 * (1 << 20)); - io::stdin().read_to_string(&mut seq).unwrap(); - let ilen = seq.len(); - - seq = regex!(">[^\n]*\n|\n").replace_all(&seq, "").into_owned(); - let clen = seq.len(); - - let variants = vec![ - regex!("agggtaaa|tttaccct"), - regex!("[cgt]gggtaaa|tttaccc[acg]"), - regex!("a[act]ggtaaa|tttacc[agt]t"), - regex!("ag[act]gtaaa|tttac[agt]ct"), - regex!("agg[act]taaa|ttta[agt]cct"), - regex!("aggg[acg]aaa|ttt[cgt]ccct"), - regex!("agggt[cgt]aa|tt[acg]accct"), - regex!("agggta[cgt]a|t[acg]taccct"), - regex!("agggtaa[cgt]|[acg]ttaccct"), - ]; - for re in variants { - println!("{} {}", re.to_string(), re.find_iter(&seq).count()); - } - - let substs = vec![ - (regex!("B"), "(c|g|t)"), - (regex!("D"), "(a|g|t)"), - (regex!("H"), "(a|c|t)"), - (regex!("K"), "(g|t)"), - (regex!("M"), "(a|c)"), - (regex!("N"), "(a|c|g|t)"), - (regex!("R"), "(a|g)"), - (regex!("S"), "(c|g)"), - (regex!("V"), "(a|c|g)"), - (regex!("W"), "(a|t)"), - (regex!("Y"), "(c|t)"), - ]; - let mut seq = seq; - for (re, replacement) in substs { - seq = re.replace_all(&seq, replacement).into_owned(); - } - println!("\n{}\n{}\n{}", ilen, clen, seq.len()); -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/HACKING.md cargo-0.26.0/vendor/regex-0.2.6/HACKING.md --- cargo-0.25.0/vendor/regex-0.2.6/HACKING.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/HACKING.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,330 +0,0 @@ -Your friendly guide to hacking and navigating the regex library. - -This guide assumes familiarity with Rust and Cargo, and at least a perusal of -the user facing documentation for this crate. - -If you're looking for background on the implementation in this library, then -you can do no better than Russ Cox's article series on implementing regular -expressions using finite automata: https://swtch.com/~rsc/regexp/ - - -## Architecture overview - -As you probably already know, this library executes regular expressions using -finite automata. In particular, a design goal is to make searching linear -with respect to both the regular expression and the text being searched. -Meeting that design goal on its own is not so hard and can be done with an -implementation of the Pike VM (similar to Thompson's construction, but supports -capturing groups), as described in: https://swtch.com/~rsc/regexp/regexp2.html ---- This library contains such an implementation in src/pikevm.rs. - -Making it fast is harder. One of the key problems with the Pike VM is that it -can be in more than one state at any point in time, and must shuffle capture -positions between them. The Pike VM also spends a lot of time following the -same epsilon transitions over and over again. We can employ one trick to -speed up the Pike VM: extract one or more literal prefixes from the regular -expression and execute specialized code to quickly find matches of those -prefixes in the search text. The Pike VM can then be avoided for most the -search, and instead only executed when a prefix is found. The code to find -prefixes is in the regex-syntax crate (in this repository). The code to search -for literals is in src/literals.rs. When more than one literal prefix is found, -we fall back to an Aho-Corasick DFA using the aho-corasick crate. For one -literal, we use a variant of the Boyer-Moore algorithm. Both Aho-Corasick and -Boyer-Moore use `memchr` when appropriate. The Boyer-Moore variant in this -library also uses elementary frequency analysis to choose the right byte to run -`memchr` with. - -Of course, detecting prefix literals can only take us so far. Not all regular -expressions have literal prefixes. To remedy this, we try another approach -to executing the Pike VM: backtracking, whose implementation can be found in -src/backtrack.rs. One reason why backtracking can be faster is that it avoids -excessive shuffling of capture groups. Of course, backtracking is susceptible -to exponential runtimes, so we keep track of every state we've visited to make -sure we never visit it again. This guarantees linear time execution, but we -pay for it with the memory required to track visited states. Because of the -memory requirement, we only use this engine on small search strings *and* small -regular expressions. - -Lastly, the real workhorse of this library is the "lazy" DFA in src/dfa.rs. -It is distinct from the Pike VM in that the DFA is explicitly represented in -memory and is only ever in one state at a time. It is said to be "lazy" because -the DFA is computed as text is searched, where each byte in the search text -results in at most one new DFA state. It is made fast by caching states. DFAs -are susceptible to exponential state blow up (where the worst case is computing -a new state for every input byte, regardless of what's in the state cache). To -avoid using a lot of memory, the lazy DFA uses a bounded cache. Once the cache -is full, it is wiped and state computation starts over again. If the cache is -wiped too frequently, then the DFA gives up and searching falls back to one of -the aforementioned algorithms. - -All of the above matching engines expose precisely the same matching semantics. -This is indeed tested. (See the section below about testing.) - -The following sub-sections describe the rest of the library and how each of the -matching engines are actually used. - -### Parsing - -Regular expressions are parsed using the regex-syntax crate, which is -maintained in this repository. The regex-syntax crate defines an abstract -syntax and provides very detailed error messages when a parse error is -encountered. Parsing is done in a separate crate so that others may benefit -from its existence, and because it is relatively divorced from the rest of the -regex library. - -The regex-syntax crate also provides sophisticated support for extracting -prefix and suffix literals from regular expressions. - -### Compilation - -The compiler is in src/compile.rs. The input to the compiler is some abstract -syntax for a regular expression and the output is a sequence of opcodes that -matching engines use to execute a search. (One can think of matching engines as -mini virtual machines.) The sequence of opcodes is a particular encoding of a -non-deterministic finite automaton. In particular, the opcodes explicitly rely -on epsilon transitions. - -Consider a simple regular expression like `a|b`. Its compiled form looks like -this: - - 000 Save(0) - 001 Split(2, 3) - 002 'a' (goto: 4) - 003 'b' - 004 Save(1) - 005 Match - -The first column is the instruction pointer and the second column is the -instruction. Save instructions indicate that the current position in the input -should be stored in a captured location. Split instructions represent a binary -branch in the program (i.e., epsilon transitions). The instructions `'a'` and -`'b'` indicate that the literal bytes `'a'` or `'b'` should match. - -In older versions of this library, the compilation looked like this: - - 000 Save(0) - 001 Split(2, 3) - 002 'a' - 003 Jump(5) - 004 'b' - 005 Save(1) - 006 Match - -In particular, empty instructions that merely served to move execution from one -point in the program to another were removed. Instead, every instruction has a -`goto` pointer embedded into it. This resulted in a small performance boost for -the Pike VM, because it was one fewer epsilon transition that it had to follow. - -There exist more instructions and they are defined and documented in -src/prog.rs. - -Compilation has several knobs and a few unfortunately complicated invariants. -Namely, the output of compilation can be one of two types of programs: a -program that executes on Unicode scalar values or a program that executes -on raw bytes. In the former case, the matching engine is responsible for -performing UTF-8 decoding and executing instructions using Unicode codepoints. -In the latter case, the program handles UTF-8 decoding implicitly, so that the -matching engine can execute on raw bytes. All matching engines can execute -either Unicode or byte based programs except for the lazy DFA, which requires -byte based programs. In general, both representations were kept because (1) the -lazy DFA requires byte based programs so that states can be encoded in a memory -efficient manner and (2) the Pike VM benefits greatly from inlining Unicode -character classes into fewer instructions as it results in fewer epsilon -transitions. - -N.B. UTF-8 decoding is built into the compiled program by making use of the -utf8-ranges crate. The compiler in this library factors out common suffixes to -reduce the size of huge character classes (e.g., `\pL`). - -A regrettable consequence of this split in instruction sets is we generally -need to compile two programs; one for NFA execution and one for the lazy DFA. - -In fact, it is worse than that: the lazy DFA is not capable of finding the -starting location of a match in a single scan, and must instead execute a -backwards search after finding the end location. To execute a backwards search, -we must have compiled the regular expression *in reverse*. - -This means that every compilation of a regular expression generally results in -three distinct programs. It would be possible to lazily compile the Unicode -program, since it is never needed if (1) the regular expression uses no word -boundary assertions and (2) the caller never asks for sub-capture locations. - -### Execution - -At the time of writing, there are four matching engines in this library: - -1. The Pike VM (supports captures). -2. Bounded backtracking (supports captures). -3. Literal substring or multi-substring search. -4. Lazy DFA (no support for Unicode word boundary assertions). - -Only the first two matching engines are capable of executing every regular -expression program. They also happen to be the slowest, which means we need -some logic that (1) knows various facts about the regular expression and (2) -knows what the caller wants. Using this information, we can determine which -engine (or engines) to use. - -The logic for choosing which engine to execute is in src/exec.rs and is -documented on the Exec type. Exec values contain regular expression Programs -(defined in src/prog.rs), which contain all the necessary tidbits for actually -executing a regular expression on search text. - -For the most part, the execution logic is straight-forward and follows the -limitations of each engine described above pretty faithfully. The hairiest -part of src/exec.rs by far is the execution of the lazy DFA, since it requires -a forwards and backwards search, and then falls back to either the Pike VM or -backtracking if the caller requested capture locations. - -The Exec type also contains mutable scratch space for each type of matching -engine. This scratch space is used during search (for example, for the lazy -DFA, it contains compiled states that are reused on subsequent searches). - -### Programs - -A regular expression program is essentially a sequence of opcodes produced by -the compiler plus various facts about the regular expression (such as whether -it is anchored, its capture names, etc.). - -### The regex! macro - -The `regex!` macro no longer exists. It was developed in a bygone era as a -compiler plugin during the infancy of the regex crate. Back then, then only -matching engine in the crate was the Pike VM. The `regex!` macro was, itself, -also a Pike VM. The only advantages it offered over the dynamic Pike VM that -was built at runtime were the following: - - 1. Syntax checking was done at compile time. Your Rust program wouldn't - compile if your regex didn't compile. - 2. Reduction of overhead that was proportional to the size of the regex. - For the most part, this overhead consisted of heap allocation, which - was nearly eliminated in the compiler plugin. - -The main takeaway here is that the compiler plugin was a marginally faster -version of a slow regex engine. As the regex crate evolved, it grew other regex -engines (DFA, bounded backtracker) and sophisticated literal optimizations. -The regex macro didn't keep pace, and it therefore became (dramatically) slower -than the dynamic engines. The only reason left to use it was for the compile -time guarantee that your regex is correct. Fortunately, Clippy (the Rust lint -tool) has a lint that checks your regular expression validity, which mostly -replaces that use case. - -Additionally, the regex compiler plugin stopped receiving maintenance. Nobody -complained. At that point, it seemed prudent to just remove it. - -Will a compiler plugin be brought back? The future is murky, but there is -definitely an opportunity there to build something that is faster than the -dynamic engines in some cases. But it will be challenging! As of now, there -are no plans to work on this. - - -## Testing - -A key aspect of any mature regex library is its test suite. A subset of the -tests in this library come from Glenn Fowler's AT&T test suite (its online -presence seems gone at the time of writing). The source of the test suite is -located in src/testdata. The scripts/regex-match-tests.py takes the test suite -in src/testdata and generates tests/matches.rs. - -There are also many other manually crafted tests and regression tests in -tests/tests.rs. Some of these tests were taken from RE2. - -The biggest source of complexity in the tests is related to answering this -question: how can we reuse the tests to check all of our matching engines? One -approach would have been to encode every test into some kind of format (like -the AT&T test suite) and code generate tests for each matching engine. The -approach we use in this library is to create a Cargo.toml entry point for each -matching engine we want to test. The entry points are: - -* `tests/test_default.rs` - tests `Regex::new` -* `tests/test_default_bytes.rs` - tests `bytes::Regex::new` -* `tests/test_nfa.rs` - tests `Regex::new`, forced to use the NFA - algorithm on every regex. -* `tests/test_nfa_bytes.rs` - tests `Regex::new`, forced to use the NFA - algorithm on every regex and use *arbitrary* byte based programs. -* `tests/test_nfa_utf8bytes.rs` - tests `Regex::new`, forced to use the NFA - algorithm on every regex and use *UTF-8* byte based programs. -* `tests/test_backtrack.rs` - tests `Regex::new`, forced to use - backtracking on every regex. -* `tests/test_backtrack_bytes.rs` - tests `Regex::new`, forced to use - backtracking on every regex and use *arbitrary* byte based programs. -* `tests/test_backtrack_utf8bytes.rs` - tests `Regex::new`, forced to use - backtracking on every regex and use *UTF-8* byte based programs. - -The lazy DFA and pure literal engines are absent from this list because -they cannot be used on every regular expression. Instead, we rely on -`tests/test_dynamic.rs` to test the lazy DFA and literal engines when possible. - -Since the tests are repeated several times, and because `cargo test` runs all -entry points, it can take a while to compile everything. To reduce compile -times slightly, try using `cargo test --test default`, which will only use the -`tests/test_default.rs` entry point. - - -## Benchmarking - -The benchmarking in this crate is made up of many micro-benchmarks. Currently, -there are two primary sets of benchmarks: the benchmarks that were adopted -at this library's inception (in `bench/src/misc.rs`) and a newer set of -benchmarks meant to test various optimizations. Specifically, the latter set -contain some analysis and are in `bench/src/sherlock.rs`. Also, the latter -set are all executed on the same lengthy input whereas the former benchmarks -are executed on strings of varying length. - -There is also a smattering of benchmarks for parsing and compilation. - -Benchmarks are in a separate crate so that its dependencies can be managed -separately from the main regex crate. - -Benchmarking follows a similarly wonky setup as tests. There are multiple entry -points: - -* `bench_rust.rs` - benchmarks `Regex::new` -* `bench_rust_bytes.rs` benchmarks `bytes::Regex::new` -* `bench_pcre.rs` - benchmarks PCRE -* `bench_onig.rs` - benchmarks Oniguruma - -The PCRE and Oniguruma benchmarks exist as a comparison point to a mature -regular expression library. In general, this regex library compares favorably -(there are even a few benchmarks that PCRE simply runs too slowly on or -outright can't execute at all). I would love to add other regular expression -library benchmarks (especially RE2). - -If you're hacking on one of the matching engines and just want to see -benchmarks, then all you need to run is: - - $ ./bench/run rust - -If you want to compare your results with older benchmarks, then try: - - $ ./bench/run rust | tee old - $ ... make it faster - $ ./bench/run rust | tee new - $ cargo benchcmp old new --improvements - -The `cargo-benchcmp` utility is available here: -https://github.com/BurntSushi/cargo-benchcmp - -The `./bench/run` utility can run benchmarks for PCRE and Oniguruma too. See -`./bench/bench --help`. - -## Dev Docs - -When digging your teeth into the codebase for the first time, the -crate documentation can be a great resource. By default `rustdoc` -will strip out all documentation of private crate members in an -effort to help consumers of the crate focus on the *interface* -without having to concern themselves with the *implementation*. -Normally this is a great thing, but if you want to start hacking -on regex internals it is not what you want. Many of the private members -of this crate are well documented with rustdoc style comments, and -it would be a shame to miss out on the opportunity that presents. -You can generate the private docs with: - -``` -$ rustdoc --crate-name docs src/lib.rs -o target/doc -L target/debug/deps --no-defaults --passes collapse-docs --passes unindent-comments -``` - -Then just point your browser at `target/doc/regex/index.html`. - -See https://github.com/rust-lang/rust/issues/15347 for more info -about generating developer docs for internal use. diff -Nru cargo-0.25.0/vendor/regex-0.2.6/LICENSE-APACHE cargo-0.26.0/vendor/regex-0.2.6/LICENSE-APACHE --- cargo-0.25.0/vendor/regex-0.2.6/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/regex-0.2.6/LICENSE-MIT cargo-0.26.0/vendor/regex-0.2.6/LICENSE-MIT --- cargo-0.25.0/vendor/regex-0.2.6/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/regex-0.2.6/PERFORMANCE.md cargo-0.26.0/vendor/regex-0.2.6/PERFORMANCE.md --- cargo-0.25.0/vendor/regex-0.2.6/PERFORMANCE.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/PERFORMANCE.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,279 +0,0 @@ -Your friendly guide to understanding the performance characteristics of this -crate. - -This guide assumes some familiarity with the public API of this crate, which -can be found here: https://docs.rs/regex - -## Theory vs. Practice - -One of the design goals of this crate is to provide worst case linear time -behavior with respect to the text searched using finite state automata. This -means that, *in theory*, the performance of this crate is much better than most -regex implementations, which typically use backtracking which has worst case -exponential time. - -For example, try opening a Python interpreter and typing this: - - >>> import re - >>> re.search('(a*)*c', 'a' * 30).span() - -I'll wait. - -At some point, you'll figure out that it won't terminate any time soon. ^C it. - -The promise of this crate is that *this pathological behavior can't happen*. - -With that said, just because we have protected ourselves against worst case -exponential behavior doesn't mean we are immune from large constant factors -or places where the current regex engine isn't quite optimal. This guide will -detail those cases and provide guidance on how to avoid them, among other -bits of general advice. - -## Thou Shalt Not Compile Regular Expressions In A Loop - -**Advice**: Use `lazy_static` to amortize the cost of `Regex` compilation. - -Don't do it unless you really don't mind paying for it. Compiling a regular -expression in this crate is quite expensive. It is conceivable that it may get -faster some day, but I wouldn't hold out hope for, say, an order of magnitude -improvement. In particular, compilation can take any where from a few dozen -microseconds to a few dozen milliseconds. Yes, milliseconds. Unicode character -classes, in particular, have the largest impact on compilation performance. At -the time of writing, for example, `\pL{100}` takes around 44ms to compile. This -is because `\pL` corresponds to every letter in Unicode and compilation must -turn it into a proper automaton that decodes a subset of UTF-8 which -corresponds to those letters. Compilation also spends some cycles shrinking the -size of the automaton. - -This means that in order to realize efficient regex matching, one must -*amortize the cost of compilation*. Trivially, if a call to `is_match` is -inside a loop, then make sure your call to `Regex::new` is *outside* that loop. - -In many programming languages, regular expressions can be conveniently defined -and compiled in a global scope, and code can reach out and use them as if -they were global static variables. In Rust, there is really no concept of -life-before-main, and therefore, one cannot utter this: - - static MY_REGEX: Regex = Regex::new("...").unwrap(); - -Unfortunately, this would seem to imply that one must pass `Regex` objects -around to everywhere they are used, which can be especially painful depending -on how your program is structured. Thankfully, the -[`lazy_static`](https://crates.io/crates/lazy_static) -crate provides an answer that works well: - - #[macro_use] extern crate lazy_static; - extern crate regex; - - use regex::Regex; - - fn some_helper_function(text: &str) -> bool { - lazy_static! { - static ref MY_REGEX: Regex = Regex::new("...").unwrap(); - } - MY_REGEX.is_match(text) - } - -In other words, the `lazy_static!` macro enables us to define a `Regex` *as if* -it were a global static value. What is actually happening under the covers is -that the code inside the macro (i.e., `Regex::new(...)`) is run on *first use* -of `MY_REGEX` via a `Deref` impl. The implementation is admittedly magical, but -it's self contained and everything works exactly as you expect. In particular, -`MY_REGEX` can be used from multiple threads without wrapping it in an `Arc` or -a `Mutex`. On that note... - -## Using a regex from multiple threads - -**Advice**: The performance impact from using a `Regex` from multiple threads -is likely negligible. If necessary, clone the `Regex` so that each thread gets -its own copy. Cloning a regex does not incur any additional memory overhead -than what would be used by using a `Regex` from multiple threads -simultaneously. *Its only cost is ergonomics.* - -It is supported and encouraged to define your regexes using `lazy_static!` as -if they were global static values, and then use them to search text from -multiple threads simultaneously. - -One might imagine that this is possible because a `Regex` represents a -*compiled* program, so that any allocation or mutation is already done, and is -therefore read-only. Unfortunately, this is not true. Each type of search -strategy in this crate requires some kind of mutable scratch space to use -*during search*. For example, when executing a DFA, its states are computed -lazily and reused on subsequent searches. Those states go into that mutable -scratch space. - -The mutable scratch space is an implementation detail, and in general, its -mutation should not be observable from users of this crate. Therefore, it uses -interior mutability. This implies that `Regex` can either only be used from one -thread, or it must do some sort of synchronization. Either choice is -reasonable, but this crate chooses the latter, in particular because it is -ergonomic and makes use with `lazy_static!` straight forward. - -Synchronization implies *some* amount of overhead. When a `Regex` is used from -a single thread, this overhead is negligible. When a `Regex` is used from -multiple threads simultaneously, it is possible for the overhead of -synchronization from contention to impact performance. The specific cases where -contention may happen is if you are calling any of these methods repeatedly -from multiple threads simultaneously: - -* shortest_match -* is_match -* find -* captures - -In particular, every invocation of one of these methods must synchronize with -other threads to retrieve its mutable scratch space before searching can start. -If, however, you are using one of these methods: - -* find_iter -* captures_iter - -Then you may not suffer from contention since the cost of synchronization is -amortized on *construction of the iterator*. That is, the mutable scratch space -is obtained when the iterator is created and retained throughout its lifetime. - -## Only ask for what you need - -**Advice**: Prefer in this order: `is_match`, `find`, `captures`. - -There are three primary search methods on a `Regex`: - -* is_match -* find -* captures - -In general, these are ordered from fastest to slowest. - -`is_match` is fastest because it doesn't actually need to find the start or the -end of the leftmost-first match. It can quit immediately after it knows there -is a match. For example, given the regex `a+` and the haystack, `aaaaa`, the -search will quit after examing the first byte. - -In constrast, `find` must return both the start and end location of the -leftmost-first match. It can use the DFA matcher for this, but must run it -forwards once to find the end of the match *and then run it backwards* to find -the start of the match. The two scans and the cost of finding the real end of -the leftmost-first match make this more expensive than `is_match`. - -`captures` is the most expensive of them all because it must do what `find` -does, and then run either the bounded backtracker or the Pike VM to fill in the -capture group locations. Both of these are simulations of an NFA, which must -spend a lot of time shuffling states around. The DFA limits the performance hit -somewhat by restricting the amount of text that must be searched via an NFA -simulation. - -One other method not mentioned is `shortest_match`. This method has precisely -the same performance characteristics as `is_match`, except it will return the -end location of when it discovered a match. For example, given the regex `a+` -and the haystack `aaaaa`, `shortest_match` may return `1` as opposed to `5`, -the latter of which being the correct end location of the leftmost-first match. - -## Literals in your regex may make it faster - -**Advice**: Literals can reduce the work that the regex engine needs to do. Use -them if you can, especially as prefixes. - -In particular, if your regex starts with a prefix literal, the prefix is -quickly searched before entering the (much slower) regex engine. For example, -given the regex `foo\w+`, the literal `foo` will be searched for using -Boyer-Moore. If there's no match, then no regex engine is ever used. Only when -there's a match is the regex engine invoked at the location of the match, which -effectively permits the regex engine to skip large portions of a haystack. -If a regex is comprised entirely of literals (possibly more than one), then -it's possible that the regex engine can be avoided entirely even when there's a -match. - -When one literal is found, Boyer-Moore is used. When multiple literals are -found, then an optimized version of Aho-Corasick is used. - -This optimization is in particular extended quite a bit in this crate. Here are -a few examples of regexes that get literal prefixes detected: - -* `(foo|bar)` detects `foo` and `bar` -* `(a|b)c` detects `ac` and `bc` -* `[ab]foo[yz]` detects `afooy`, `afooz`, `bfooy` and `bfooz` -* `a?b` detects `a` and `b` -* `a*b` detects `a` and `b` -* `(ab){3,6}` detects `ababab` - -Literals in anchored regexes can also be used for detecting non-matches very -quickly. For example, `^foo\w+` and `\w+foo$` may be able to detect a non-match -just by examing the first (or last) three bytes of the haystack. - -## Unicode word boundaries may prevent the DFA from being used - -**Advice**: In most cases, `\b` should work well. If not, use `(?-u:\b)` -instead of `\b` if you care about consistent performance more than correctness. - -It's a sad state of the current implementation. At the moment, the DFA will try -to interpret Unicode word boundaries as if they were ASCII word boundaries. -If the DFA comes across any non-ASCII byte, it will quit and fall back to an -alternative matching engine that can handle Unicode word boundaries correctly. -The alternate matching engine is generally quite a bit slower (perhaps by an -order of magnitude). If necessary, this can be ameliorated in two ways. - -The first way is to add some number of literal prefixes to your regular -expression. Even though the DFA may not be used, specialized routines will -still kick in to find prefix literals quickly, which limits how much work the -NFA simulation will need to do. - -The second way is to give up on Unicode and use an ASCII word boundary instead. -One can use an ASCII word boundary by disabling Unicode support. That is, -instead of using `\b`, use `(?-u:\b)`. Namely, given the regex `\b.+\b`, it -can be transformed into a regex that uses the DFA with `(?-u:\b).+(?-u:\b)`. It -is important to limit the scope of disabling the `u` flag, since it might lead -to a syntax error if the regex could match arbitrary bytes. For example, if one -wrote `(?-u)\b.+\b`, then a syntax error would be returned because `.` matches -any *byte* when the Unicode flag is disabled. - -The second way isn't appreciably different than just using a Unicode word -boundary in the first place, since the DFA will speculatively interpret it as -an ASCII word boundary anyway. The key difference is that if an ASCII word -boundary is used explicitly, then the DFA won't quit in the presence of -non-ASCII UTF-8 bytes. This results in giving up correctness in exchange for -more consistent performance. - -N.B. When using `bytes::Regex`, Unicode support is disabled by default, so one -can simply write `\b` to get an ASCII word boundary. - -## Excessive counting can lead to exponential state blow up in the DFA - -**Advice**: Don't write regexes that cause DFA state blow up if you care about -match performance. - -Wait, didn't I say that this crate guards against exponential worst cases? -Well, it turns out that the process of converting an NFA to a DFA can lead to -an exponential blow up in the number of states. This crate specifically guards -against exponential blow up by doing two things: - -1. The DFA is computed lazily. That is, a state in the DFA only exists in - memory if it is visited. In particular, the lazy DFA guarantees that *at - most* one state is created for every byte of input. This, on its own, - guarantees linear time complexity. -2. Of course, creating a new state for *every* byte of input means that search - will go incredibly slow because of very large constant factors. On top of - that, creating a state for every byte in a large haystack could result in - exorbitant memory usage. To ameliorate this, the DFA bounds the number of - states it can store. Once it reaches its limit, it flushes its cache. This - prevents reuse of states that it already computed. If the cache is flushed - too frequently, then the DFA will give up and execution will fall back to - one of the NFA simulations. - -In effect, this crate will detect exponential state blow up and fall back to -a search routine with fixed memory requirements. This does, however, mean that -searching will be much slower than one might expect. Regexes that rely on -counting in particular are strong aggravators of this behavior. For example, -matching `[01]*1[01]{20}$` against a random sequence of `0`s and `1`s. - -In the future, it may be possible to increase the bound that the DFA uses, -which would allow the caller to choose how much memory they're willing to -spend. - -## Resist the temptation to "optimize" regexes - -**Advice**: This ain't a backtracking engine. - -An entire book was written on how to optimize Perl-style regular expressions. -Most of those techniques are not applicable for this library. For example, -there is no problem with using non-greedy matching or having lots of -alternations in your regex. diff -Nru cargo-0.25.0/vendor/regex-0.2.6/README.md cargo-0.26.0/vendor/regex-0.2.6/README.md --- cargo-0.25.0/vendor/regex-0.2.6/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,211 +0,0 @@ -regex -===== -A Rust library for parsing, compiling, and executing regular expressions. Its -syntax is similar to Perl-style regular expressions, but lacks a few features -like look around and backreferences. In exchange, all searches execute in -linear time with respect to the size of the regular expression and search text. -Much of the syntax and implementation is inspired -by [RE2](https://github.com/google/re2). - -[![Build Status](https://travis-ci.org/rust-lang/regex.svg?branch=master)](https://travis-ci.org/rust-lang/regex) -[![Build status](https://ci.appveyor.com/api/projects/status/github/rust-lang/regex?svg=true)](https://ci.appveyor.com/project/rust-lang-libs/regex) -[![Coverage Status](https://coveralls.io/repos/github/rust-lang/regex/badge.svg?branch=master)](https://coveralls.io/github/rust-lang/regex?branch=master) -[![](http://meritbadge.herokuapp.com/regex)](https://crates.io/crates/regex) - -### Documentation - -[Module documentation with examples](https://docs.rs/regex). -The module documentation also include a comprehensive description of the syntax -supported. - -Documentation with examples for the various matching functions and iterators -can be found on the -[`Regex` type](https://docs.rs/regex/*/regex/struct.Regex.html). - -### Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -regex = "0.2" -``` - -and this to your crate root: - -```rust -extern crate regex; -``` - -Here's a simple example that matches a date in YYYY-MM-DD format and prints the -year, month and day: - -```rust -extern crate regex; - -use regex::Regex; - -fn main() { - let re = Regex::new(r"(?x) -(?P<year>\d{4}) # the year -- -(?P<month>\d{2}) # the month -- -(?P<day>\d{2}) # the day -").unwrap(); - let caps = re.captures("2010-03-14").unwrap(); - - assert_eq!("2010", &caps["year"]); - assert_eq!("03", &caps["month"]); - assert_eq!("14", &caps["day"]); -} -``` - -If you have lots of dates in text that you'd like to iterate over, then it's -easy to adapt the above example with an iterator: - -```rust -extern crate regex; - -use regex::Regex; - -const TO_SEARCH: &'static str = " -On 2010-03-14, foo happened. On 2014-10-14, bar happened. -"; - -fn main() { - let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap(); - - for caps in re.captures_iter(TO_SEARCH) { - // Note that all of the unwraps are actually OK for this regex - // because the only way for the regex to match is if all of the - // capture groups match. This is not true in general though! - println!("year: {}, month: {}, day: {}", - caps.get(1).unwrap().as_str(), - caps.get(2).unwrap().as_str(), - caps.get(3).unwrap().as_str()); - } -} -``` - -This example outputs: - -``` -year: 2010, month: 03, day: 14 -year: 2014, month: 10, day: 14 -``` - -### Usage: Avoid compiling the same regex in a loop - -It is an anti-pattern to compile the same regular expression in a loop since -compilation is typically expensive. (It takes anywhere from a few microseconds -to a few **milliseconds** depending on the size of the regex.) Not only is -compilation itself expensive, but this also prevents optimizations that reuse -allocations internally to the matching engines. - -In Rust, it can sometimes be a pain to pass regular expressions around if -they're used from inside a helper function. Instead, we recommend using the -[`lazy_static`](https://crates.io/crates/lazy_static) crate to ensure that -regular expressions are compiled exactly once. - -For example: - -```rust -#[macro_use] extern crate lazy_static; -extern crate regex; - -use regex::Regex; - -fn some_helper_function(text: &str) -> bool { - lazy_static! { - static ref RE: Regex = Regex::new("...").unwrap(); - } - RE.is_match(text) -} -``` - -Specifically, in this example, the regex will be compiled when it is used for -the first time. On subsequent uses, it will reuse the previous compilation. - -### Usage: match regular expressions on `&[u8]` - -The main API of this crate (`regex::Regex`) requires the caller to pass a -`&str` for searching. In Rust, an `&str` is required to be valid UTF-8, which -means the main API can't be used for searching arbitrary bytes. - -To match on arbitrary bytes, use the `regex::bytes::Regex` API. The API -is identical to the main API, except that it takes an `&[u8]` to search -on instead of an `&str`. By default, `.` will match any *byte* using -`regex::bytes::Regex`, while `.` will match any *UTF-8 encoded Unicode scalar -value* using the main API. - -This example shows how to find all null-terminated strings in a slice of bytes: - -```rust -use regex::bytes::Regex; - -let re = Regex::new(r"(?P<cstr>[^\x00]+)\x00").unwrap(); -let text = b"foo\x00bar\x00baz\x00"; - -// Extract all of the strings without the null terminator from each match. -// The unwrap is OK here since a match requires the `cstr` capture to match. -let cstrs: Vec<&[u8]> = - re.captures_iter(text) - .map(|c| c.name("cstr").unwrap().as_bytes()) - .collect(); -assert_eq!(vec![&b"foo"[..], &b"bar"[..], &b"baz"[..]], cstrs); -``` - -Notice here that the `[^\x00]+` will match any *byte* except for `NUL`. When -using the main API, `[^\x00]+` would instead match any valid UTF-8 sequence -except for `NUL`. - -### Usage: match multiple regular expressions simultaneously - -This demonstrates how to use a `RegexSet` to match multiple (possibly -overlapping) regular expressions in a single scan of the search text: - -```rust -use regex::RegexSet; - -let set = RegexSet::new(&[ - r"\w+", - r"\d+", - r"\pL+", - r"foo", - r"bar", - r"barfoo", - r"foobar", -]).unwrap(); - -// Iterate over and collect all of the matches. -let matches: Vec<_> = set.matches("foobar").into_iter().collect(); -assert_eq!(matches, vec![0, 2, 3, 4, 6]); - -// You can also test whether a particular regex matched: -let matches = set.matches("foobar"); -assert!(!matches.matched(5)); -assert!(matches.matched(6)); -``` - - -### Usage: a regular expression parser - -This repository contains a crate that provides a well tested regular expression -parser and abstract syntax. It provides no facilities for compilation or -execution. This may be useful if you're implementing your own regex engine or -otherwise need to do analysis on the syntax of a regular expression. It is -otherwise not recommended for general use. - -[Documentation for `regex-syntax` with examples](https://docs.rs/regex-syntax). - -# License - -This project is 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. diff -Nru cargo-0.25.0/vendor/regex-0.2.6/scripts/frequencies.py cargo-0.26.0/vendor/regex-0.2.6/scripts/frequencies.py --- cargo-0.25.0/vendor/regex-0.2.6/scripts/frequencies.py 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/scripts/frequencies.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,82 +0,0 @@ -#!/usr/bin/env python - -# This does simple normalized frequency analysis on UTF-8 encoded text. The -# result of the analysis is translated to a ranked list, where every byte is -# assigned a rank. This list is written to src/freqs.rs. -# -# Currently, the frequencies are generated from the following corpuses: -# -# * The CIA world fact book -# * The source code of rustc -# * Septuaginta - -from __future__ import absolute_import, division, print_function - -import argparse -from collections import Counter -import sys - -preamble = '''// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// NOTE: The following code was generated by "scripts/frequencies.py", do not -// edit directly -''' - - -def eprint(*args, **kwargs): - kwargs['file'] = sys.stderr - print(*args, **kwargs) - - -def main(): - p = argparse.ArgumentParser() - p.add_argument('corpus', metavar='FILE', nargs='+') - args = p.parse_args() - - # Get frequency counts of each byte. - freqs = Counter() - for i in range(0, 256): - freqs[i] = 0 - - eprint('reading entire corpus into memory') - corpus = [] - for fpath in args.corpus: - corpus.append(open(fpath, 'rb').read()) - - eprint('computing byte frequencies') - for c in corpus: - for byte in c: - freqs[byte] += 1.0 / float(len(c)) - - eprint('writing Rust code') - # Get the rank of each byte. A lower rank => lower relative frequency. - rank = [0] * 256 - for i, (byte, _) in enumerate(freqs.most_common()): - # print(byte) - rank[byte] = 255 - i - - # Forcefully set the highest rank possible for bytes that start multi-byte - # UTF-8 sequences. The idea here is that a continuation byte will be more - # discerning in a homogenous haystack. - for byte in range(0xC0, 0xFF + 1): - rank[byte] = 255 - - # Now write Rust. - olines = ['pub const BYTE_FREQUENCIES: [u8; 256] = ['] - for byte in range(256): - olines.append(' %3d, // %r' % (rank[byte], chr(byte))) - olines.append('];') - - print(preamble) - print('\n'.join(olines)) - -if __name__ == '__main__': - main() diff -Nru cargo-0.25.0/vendor/regex-0.2.6/scripts/regex-match-tests.py cargo-0.26.0/vendor/regex-0.2.6/scripts/regex-match-tests.py --- cargo-0.25.0/vendor/regex-0.2.6/scripts/regex-match-tests.py 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/scripts/regex-match-tests.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,107 +0,0 @@ -#!/usr/bin/env python2 - -# Copyright 2014 The Rust Project Developers. See the COPYRIGHT -# file at the top-level directory of this distribution and at -# http://rust-lang.org/COPYRIGHT. -# -# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -from __future__ import absolute_import, division, print_function -import argparse -import datetime -import os.path as path - - -def print_tests(tests): - print('\n'.join([test_tostr(t) for t in tests])) - - -def read_tests(f): - basename, _ = path.splitext(path.basename(f)) - tests = [] - for lineno, line in enumerate(open(f), 1): - fields = filter(None, map(str.strip, line.split('\t'))) - if not (4 <= len(fields) <= 5) \ - or 'E' not in fields[0] or fields[0][0] == '#': - continue - - opts, pat, text, sgroups = fields[0:4] - groups = [] # groups as integer ranges - if sgroups == 'NOMATCH': - groups = [None] - elif ',' in sgroups: - noparen = map(lambda s: s.strip('()'), sgroups.split(')(')) - for g in noparen: - s, e = map(str.strip, g.split(',')) - if s == '?' and e == '?': - groups.append(None) - else: - groups.append((int(s), int(e))) - else: - # This skips tests that should result in an error. - # There aren't many, so I think we can just capture those - # manually. Possibly fix this in future. - continue - - if pat == 'SAME': - pat = tests[-1][1] - if '$' in opts: - pat = pat.decode('string_escape') - text = text.decode('string_escape') - if 'i' in opts: - pat = '(?i)%s' % pat - - name = '%s_%d' % (basename, lineno) - tests.append((name, pat, text, groups)) - return tests - - -def test_tostr(t): - lineno, pat, text, groups = t - options = map(group_tostr, groups) - return 'mat!(match_%s, r"%s", r"%s", %s);' \ - % (lineno, pat, '' if text == "NULL" else text, ', '.join(options)) - - -def group_tostr(g): - if g is None: - return 'None' - else: - return 'Some((%d, %d))' % (g[0], g[1]) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description='Generate match tests from an AT&T POSIX test file.') - aa = parser.add_argument - aa('files', nargs='+', - help='A list of dat AT&T POSIX test files. See src/testdata') - args = parser.parse_args() - - tests = [] - for f in args.files: - tests += read_tests(f) - - tpl = '''// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// DO NOT EDIT. Automatically generated by 'scripts/regex-match-tests.py' -// on {date}. -''' - print(tpl.format(date=str(datetime.datetime.now()))) - - for f in args.files: - print('// Tests from %s' % path.basename(f)) - print_tests(read_tests(f)) - print('') diff -Nru cargo-0.25.0/vendor/regex-0.2.6/scripts/unicode.py cargo-0.26.0/vendor/regex-0.2.6/scripts/unicode.py --- cargo-0.25.0/vendor/regex-0.2.6/scripts/unicode.py 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/scripts/unicode.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,305 +0,0 @@ -#!/usr/bin/env python2 -# -# Copyright 2011-2013 The Rust Project Developers. See the COPYRIGHT -# file at the top-level directory of this distribution and at -# http://rust-lang.org/COPYRIGHT. -# -# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -# option. This file may not be copied, modified, or distributed -# except according to those terms. - -# This script uses the following Unicode tables: -# - DerivedCoreProperties.txt -# - EastAsianWidth.txt -# - PropList.txt -# - Scripts.txt -# - UnicodeData.txt -# -# Since this should not require frequent updates, we just store this -# out-of-line and check the unicode.rs file into git. - -from collections import defaultdict -import fileinput, re, os, sys - -preamble = '''// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// NOTE: The following code was generated by "scripts/unicode.py", do not edit -// directly - -#![allow(warnings)] -''' - -# Mapping taken from Table 12 from: -# http://www.unicode.org/reports/tr44/#General_Category_Values -expanded_categories = { - 'Lu': ['LC', 'L'], 'Ll': ['LC', 'L'], 'Lt': ['LC', 'L'], - 'Lm': ['L'], 'Lo': ['L'], - 'Mn': ['M'], 'Mc': ['M'], 'Me': ['M'], - 'Nd': ['N'], 'Nl': ['N'], 'No': ['No'], - 'Pc': ['P'], 'Pd': ['P'], 'Ps': ['P'], 'Pe': ['P'], - 'Pi': ['P'], 'Pf': ['P'], 'Po': ['P'], - 'Sm': ['S'], 'Sc': ['S'], 'Sk': ['S'], 'So': ['S'], - 'Zs': ['Z'], 'Zl': ['Z'], 'Zp': ['Z'], - 'Cc': ['C'], 'Cf': ['C'], 'Cs': ['C'], 'Co': ['C'], 'Cn': ['C'], -} - -def fetch(f): - if not os.path.exists(f): - os.system("curl -O http://www.unicode.org/Public/UNIDATA/%s" - % f) - - if not os.path.exists(f): - sys.stderr.write("cannot load %s" % f) - exit(1) - -def is_surrogate(n): - return 0xD800 <= n <= 0xDFFF - -def load_unicode_data(f): - fetch(f) - gencats = {} - - udict = {}; - range_start = -1; - for line in fileinput.input(f): - data = line.split(';'); - if len(data) != 15: - continue - cp = int(data[0], 16); - if is_surrogate(cp): - continue - if range_start >= 0: - for i in xrange(range_start, cp): - udict[i] = data; - range_start = -1; - if data[1].endswith(", First>"): - range_start = cp; - continue; - udict[cp] = data; - - for code in udict: - [code_org, name, gencat, combine, bidi, - decomp, deci, digit, num, mirror, - old, iso, upcase, lowcase, titlecase ] = udict[code]; - - # place letter in categories as appropriate - for cat in [gencat, "Assigned"] + expanded_categories.get(gencat, []): - if cat not in gencats: - gencats[cat] = [] - gencats[cat].append(code) - - # generate Not_Assigned from Assigned - gencats["Cn"] = gen_unassigned(gencats["Assigned"]) - # Assigned is not a real category - del(gencats["Assigned"]) - # Other contains Not_Assigned - gencats["C"].extend(gencats["Cn"]) - gencats = group_cats(gencats) - - return gencats - -def group_cats(cats): - cats_out = {} - for cat in cats: - cats_out[cat] = group_cat(cats[cat]) - return cats_out - -def group_cat(cat): - cat_out = [] - letters = sorted(set(cat)) - cur_start = letters.pop(0) - cur_end = cur_start - for letter in letters: - assert letter > cur_end, \ - "cur_end: %s, letter: %s" % (hex(cur_end), hex(letter)) - if letter == cur_end + 1: - cur_end = letter - else: - cat_out.append((cur_start, cur_end)) - cur_start = cur_end = letter - cat_out.append((cur_start, cur_end)) - return cat_out - -def ungroup_cat(cat): - cat_out = [] - for (lo, hi) in cat: - while lo <= hi: - cat_out.append(lo) - lo += 1 - return cat_out - -def gen_unassigned(assigned): - assigned = set(assigned) - return ([i for i in range(0, 0xd800) if i not in assigned] + - [i for i in range(0xe000, 0x110000) if i not in assigned]) - -def format_table_content(f, content, indent): - line = " "*indent - first = True - for chunk in content.split(","): - if len(line) + len(chunk) < 78: - if first: - line += chunk - else: - line += ", " + chunk - first = False - else: - f.write(line + ",\n") - line = " "*indent + chunk - f.write(line) - -def load_properties(f, interestingprops): - fetch(f) - props = {} - re1 = re.compile("^ *([0-9A-F]+) *; *(\w+)") - re2 = re.compile("^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+)") - - for line in fileinput.input(f): - prop = None - d_lo = 0 - d_hi = 0 - m = re1.match(line) - if m: - d_lo = m.group(1) - d_hi = m.group(1) - prop = m.group(2) - else: - m = re2.match(line) - if m: - d_lo = m.group(1) - d_hi = m.group(2) - prop = m.group(3) - else: - continue - if interestingprops and prop not in interestingprops: - continue - d_lo = int(d_lo, 16) - d_hi = int(d_hi, 16) - if prop not in props: - props[prop] = [] - props[prop].append((d_lo, d_hi)) - - # optimize props if possible - for prop in props: - props[prop] = group_cat(ungroup_cat(props[prop])) - - return props - -def load_case_folding(f): - fetch(f) - re1 = re.compile("^ *([0-9A-F]+) *; *[CS] *; *([0-9A-F]+) *;") - all_pairs = defaultdict(list) - for line in fileinput.input(f): - m = re1.match(line) - if m: - a = int(m.group(1), 16) - b = int(m.group(2), 16) - all_pairs[a].append(b) - all_pairs[b].append(a) - both = set() - for k, vs in all_pairs.iteritems(): - for v in vs: - both.add((k, v)) - for v2 in all_pairs[v]: - both.add((k, v2)) - c_plus_s_both = sorted((k1, k2) for k1, k2 in both if k1 != k2) - return {"C_plus_S_both": c_plus_s_both} - -def escape_char(c): - return "'\\u{%x}'" % c - -def emit_table(f, name, t_data, t_type = "&'static [(char, char)]", is_pub=True, - pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1]))): - pub_string = "" - if is_pub: - pub_string = "pub " - f.write(" %sconst %s: %s = &[\n" % (pub_string, name, t_type)) - data = "" - first = True - for dat in t_data: - if not first: - data += "," - first = False - data += pfun(dat) - format_table_content(f, data, 8) - f.write("\n ];\n\n") - -def emit_property_module(f, mod, tbl): - f.write("pub mod %s {\n" % mod) - keys = tbl.keys() - keys.sort() - for cat in keys: - emit_table(f, "%s_table" % cat, tbl[cat]) - f.write("}\n\n") - -def emit_regex_module(f, cats, w_data): - f.write("pub mod regex {\n") - regex_class = "&'static [(char, char)]" - class_table = "&'static [(&'static str, %s)]" % regex_class - - emit_table(f, "UNICODE_CLASSES", cats, class_table, - pfun=lambda x: "(\"%s\",super::%s::%s_table)" % (x[0], x[1], x[0])) - - f.write(" pub const PERLD: %s = super::general_category::Nd_table;\n\n" - % regex_class) - f.write(" pub const PERLS: %s = super::property::White_Space_table;\n\n" - % regex_class) - - emit_table(f, "PERLW", w_data, regex_class) - - f.write("}\n\n") - -if __name__ == "__main__": - r = "unicode.rs" - if os.path.exists(r): - os.remove(r) - with open(r, "w") as rf: - # write the file's preamble - rf.write(preamble) - - # download and parse all the data - fetch("ReadMe.txt") - with open("ReadMe.txt") as readme: - pattern = "for Version (\d+)\.(\d+)\.(\d+) of the Unicode" - unicode_version = re.search(pattern, readme.read()).groups() - gencats = load_unicode_data("UnicodeData.txt") - want_derived = ["XID_Start", "XID_Continue", "Alphabetic", "Lowercase", "Uppercase"] - other_derived = ["Default_Ignorable_Code_Point", "Grapheme_Extend"] - derived = load_properties("DerivedCoreProperties.txt", want_derived + other_derived) - scripts = load_properties("Scripts.txt", []) - props = load_properties("PropList.txt", - ["White_Space", "Join_Control", "Noncharacter_Code_Point"]) - case_folding = load_case_folding("CaseFolding.txt") - - # all of these categories will also be available as \p{} in libregex - allcats = [] - for (name, cat) in ("general_category", gencats), \ - ("derived_property", derived), \ - ("script", scripts), \ - ("property", props): - emit_property_module(rf, name, cat) - allcats.extend(map(lambda x: (x, name), cat)) - allcats.sort(key=lambda c: c[0]) - - # the \w regex corresponds to Alphabetic + Mark + Decimal_Number + - # Connector_Punctuation + Join-Control according to UTS#18 - # http://www.unicode.org/reports/tr18/#Compatibility_Properties - perl_words = [] - for cat in derived["Alphabetic"], gencats["M"], gencats["Nd"], \ - gencats["Pc"], props["Join_Control"]: - perl_words.extend(ungroup_cat(cat)) - perl_words = group_cat(perl_words) - - # emit lookup tables for \p{}, along with \d, \w, and \s for libregex - emit_regex_module(rf, allcats, perl_words) - emit_property_module(rf, "case_folding", case_folding) diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/backtrack.rs cargo-0.26.0/vendor/regex-0.2.6/src/backtrack.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/backtrack.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/backtrack.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,302 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// This is the backtracking matching engine. It has the same exact capability -// as the full NFA simulation, except it is artificially restricted to small -// regexes on small inputs because of its memory requirements. -// -// In particular, this is a *bounded* backtracking engine. It retains worst -// case linear time by keeping track of the states that it has visited (using a -// bitmap). Namely, once a state is visited, it is never visited again. Since a -// state is keyed by `(instruction index, input index)`, we have that its time -// complexity is `O(mn)` (i.e., linear in the size of the search text). -// -// The backtracking engine can beat out the NFA simulation on small -// regexes/inputs because it doesn't have to keep track of multiple copies of -// the capture groups. In benchmarks, the backtracking engine is roughly twice -// as fast as the full NFA simulation. Note though that its performance doesn't -// scale, even if you're willing to live with the memory requirements. Namely, -// the bitset has to be zeroed on each execution, which becomes quite expensive -// on large bitsets. - -use exec::ProgramCache; -use input::{Input, InputAt}; -use prog::{Program, InstPtr}; -use re_trait::Slot; - -type Bits = u32; - -const BIT_SIZE: usize = 32; -const MAX_SIZE_BYTES: usize = 256 * (1 << 10); // 256 KB - -/// Returns true iff the given regex and input should be executed by this -/// engine with reasonable memory usage. -pub fn should_exec(num_insts: usize, text_len: usize) -> bool { - // Total memory usage in bytes is determined by: - // - // ((len(insts) * (len(input) + 1) + bits - 1) / bits) * (size_of(u32)) - // - // The actual limit picked is pretty much a heuristic. - // See: https://github.com/rust-lang/regex/issues/215 - let size = ((num_insts * (text_len + 1) + BIT_SIZE - 1) / BIT_SIZE) * 4; - size <= MAX_SIZE_BYTES -} - -/// A backtracking matching engine. -#[derive(Debug)] -pub struct Bounded<'a, 'm, 'r, 's, I> { - prog: &'r Program, - input: I, - matches: &'m mut [bool], - slots: &'s mut [Slot], - m: &'a mut Cache, -} - -/// Shared cached state between multiple invocations of a backtracking engine -/// in the same thread. -#[derive(Clone, Debug)] -pub struct Cache { - jobs: Vec<Job>, - visited: Vec<Bits>, -} - -impl Cache { - /// Create new empty cache for the backtracking engine. - pub fn new(_prog: &Program) -> Self { - Cache { jobs: vec![], visited: vec![] } - } -} - -/// A job is an explicit unit of stack space in the backtracking engine. -/// -/// The "normal" representation is a single state transition, which corresponds -/// to an NFA state and a character in the input. However, the backtracking -/// engine must keep track of old capture group values. We use the explicit -/// stack to do it. -#[derive(Clone, Copy, Debug)] -enum Job { - Inst { ip: InstPtr, at: InputAt }, - SaveRestore { slot: usize, old_pos: Option<usize> }, -} - -impl<'a, 'm, 'r, 's, I: Input> Bounded<'a, 'm, 'r, 's, I> { - /// Execute the backtracking matching engine. - /// - /// If there's a match, `exec` returns `true` and populates the given - /// captures accordingly. - pub fn exec( - prog: &'r Program, - cache: &ProgramCache, - matches: &'m mut [bool], - slots: &'s mut [Slot], - input: I, - start: usize, - ) -> bool { - let mut cache = cache.borrow_mut(); - let cache = &mut cache.backtrack; - let start = input.at(start); - let mut b = Bounded { - prog: prog, - input: input, - matches: matches, - slots: slots, - m: cache, - }; - b.exec_(start) - } - - /// Clears the cache such that the backtracking engine can be executed - /// on some input of fixed length. - fn clear(&mut self) { - // Reset the job memory so that we start fresh. - self.m.jobs.clear(); - - // Now we need to clear the bit state set. - // We do this by figuring out how much space we need to keep track - // of the states we've visited. - // Then we reset all existing allocated space to 0. - // Finally, we request more space if we need it. - // - // This is all a little circuitous, but doing this unsafely - // doesn't seem to have a measurable impact on performance. - // (Probably because backtracking is limited to such small - // inputs/regexes in the first place.) - let visited_len = - (self.prog.len() * (self.input.len() + 1) + BIT_SIZE - 1) - / - BIT_SIZE; - self.m.visited.truncate(visited_len); - for v in &mut self.m.visited { - *v = 0; - } - if visited_len > self.m.visited.len() { - let len = self.m.visited.len(); - self.m.visited.reserve_exact(visited_len - len); - for _ in 0..(visited_len - len) { - self.m.visited.push(0); - } - } - } - - /// Start backtracking at the given position in the input, but also look - /// for literal prefixes. - fn exec_(&mut self, mut at: InputAt) -> bool { - self.clear(); - // If this is an anchored regex at the beginning of the input, then - // we're either already done or we only need to try backtracking once. - if self.prog.is_anchored_start { - return if !at.is_start() { - false - } else { - self.backtrack(at) - }; - } - let mut matched = false; - loop { - if !self.prog.prefixes.is_empty() { - at = match self.input.prefix_at(&self.prog.prefixes, at) { - None => break, - Some(at) => at, - }; - } - matched = self.backtrack(at) || matched; - if matched && self.prog.matches.len() == 1 { - return true; - } - if at.is_end() { - break; - } - at = self.input.at(at.next_pos()); - } - matched - } - - /// The main backtracking loop starting at the given input position. - fn backtrack(&mut self, start: InputAt) -> bool { - // N.B. We use an explicit stack to avoid recursion. - // To avoid excessive pushing and popping, most transitions are handled - // in the `step` helper function, which only pushes to the stack when - // there's a capture or a branch. - let mut matched = false; - self.m.jobs.push(Job::Inst { ip: 0, at: start }); - while let Some(job) = self.m.jobs.pop() { - match job { - Job::Inst { ip, at } => { - if self.step(ip, at) { - // Only quit if we're matching one regex. - // If we're matching a regex set, then mush on and - // try to find other matches (if we want them). - if self.prog.matches.len() == 1 { - return true; - } - matched = true; - } - } - Job::SaveRestore { slot, old_pos } => { - if slot < self.slots.len() { - self.slots[slot] = old_pos; - } - } - } - } - matched - } - - fn step(&mut self, mut ip: InstPtr, mut at: InputAt) -> bool { - use prog::Inst::*; - loop { - // This loop is an optimization to avoid constantly pushing/popping - // from the stack. Namely, if we're pushing a job only to run it - // next, avoid the push and just mutate `ip` (and possibly `at`) - // in place. - if self.has_visited(ip, at) { - return false; - } - match self.prog[ip] { - Match(slot) => { - if slot < self.matches.len() { - self.matches[slot] = true; - } - return true; - } - Save(ref inst) => { - if let Some(&old_pos) = self.slots.get(inst.slot) { - // If this path doesn't work out, then we save the old - // capture index (if one exists) in an alternate - // job. If the next path fails, then the alternate - // job is popped and the old capture index is restored. - self.m.jobs.push(Job::SaveRestore { - slot: inst.slot, - old_pos: old_pos, - }); - self.slots[inst.slot] = Some(at.pos()); - } - ip = inst.goto; - } - Split(ref inst) => { - self.m.jobs.push(Job::Inst { ip: inst.goto2, at: at }); - ip = inst.goto1; - } - EmptyLook(ref inst) => { - if self.input.is_empty_match(at, inst) { - ip = inst.goto; - } else { - return false; - } - } - Char(ref inst) => { - if inst.c == at.char() { - ip = inst.goto; - at = self.input.at(at.next_pos()); - } else { - return false; - } - } - Ranges(ref inst) => { - if inst.matches(at.char()) { - ip = inst.goto; - at = self.input.at(at.next_pos()); - } else { - return false; - } - } - Bytes(ref inst) => { - if let Some(b) = at.byte() { - if inst.matches(b) { - ip = inst.goto; - at = self.input.at(at.next_pos()); - continue; - } - } - return false; - } - } - } - } - - fn has_visited(&mut self, ip: InstPtr, at: InputAt) -> bool { - let k = ip * (self.input.len() + 1) + at.pos(); - let k1 = k / BIT_SIZE; - let k2 = usize_to_u32(1 << (k & (BIT_SIZE - 1))); - if self.m.visited[k1] & k2 == 0 { - self.m.visited[k1] |= k2; - false - } else { - true - } - } -} - -fn usize_to_u32(n: usize) -> u32 { - if (n as u64) > (::std::u32::MAX as u64) { - panic!("BUG: {} is too big to fit into u32", n) - } - n as u32 -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/compile.rs cargo-0.26.0/vendor/regex-0.2.6/src/compile.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/compile.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/compile.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1157 +0,0 @@ -// Copyright 2014-2016 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::collections::HashMap; -use std::iter; -use std::result; -use std::sync::Arc; - -use syntax::{ - Expr, Repeater, CharClass, ClassRange, ByteClass, ByteRange, - is_word_byte, -}; -use utf8_ranges::{Utf8Range, Utf8Sequence, Utf8Sequences}; - -use prog::{ - Program, Inst, InstPtr, EmptyLook, - InstSave, InstSplit, InstEmptyLook, InstChar, InstRanges, InstBytes, -}; - -use Error; - -type Result = result::Result<Patch, Error>; - -#[derive(Debug)] -struct Patch { - hole: Hole, - entry: InstPtr, -} - -/// A compiler translates a regular expression AST to a sequence of -/// instructions. The sequence of instructions represents an NFA. -pub struct Compiler { - insts: Vec<MaybeInst>, - compiled: Program, - capture_name_idx: HashMap<String, usize>, - num_exprs: usize, - size_limit: usize, - suffix_cache: SuffixCache, - utf8_seqs: Option<Utf8Sequences>, - byte_classes: ByteClassSet, -} - -impl Compiler { - /// Create a new regular expression compiler. - /// - /// Various options can be set before calling `compile` on an expression. - pub fn new() -> Self { - Compiler { - insts: vec![], - compiled: Program::new(), - capture_name_idx: HashMap::new(), - num_exprs: 0, - size_limit: 10 * (1 << 20), - suffix_cache: SuffixCache::new(1000), - utf8_seqs: Some(Utf8Sequences::new('\x00', '\x00')), - byte_classes: ByteClassSet::new(), - } - } - - /// The size of the resulting program is limited by size_limit. If - /// the program approximately exceeds the given size (in bytes), then - /// compilation will stop and return an error. - pub fn size_limit(mut self, size_limit: usize) -> Self { - self.size_limit = size_limit; - self - } - - /// If bytes is true, then the program is compiled as a byte based - /// automaton, which incorporates UTF-8 decoding into the machine. If it's - /// false, then the automaton is Unicode scalar value based, e.g., an - /// engine utilizing such an automaton is resposible for UTF-8 decoding. - /// - /// The specific invariant is that when returning a byte based machine, - /// the neither the `Char` nor `Ranges` instructions are produced. - /// Conversely, when producing a Unicode scalar value machine, the `Bytes` - /// instruction is never produced. - /// - /// Note that `dfa(true)` implies `bytes(true)`. - pub fn bytes(mut self, yes: bool) -> Self { - self.compiled.is_bytes = yes; - self - } - - /// When disabled, the program compiled may match arbitrary bytes. - /// - /// When enabled (the default), all compiled programs exclusively match - /// valid UTF-8 bytes. - pub fn only_utf8(mut self, yes: bool) -> Self { - self.compiled.only_utf8 = yes; - self - } - - /// When set, the machine returned is suitable for use in the DFA matching - /// engine. - /// - /// In particular, this ensures that if the regex is not anchored in the - /// beginning, then a preceding `.*?` is included in the program. (The NFA - /// based engines handle the preceding `.*?` explicitly, which is difficult - /// or impossible in the DFA engine.) - pub fn dfa(mut self, yes: bool) -> Self { - self.compiled.is_dfa = yes; - self - } - - /// When set, the machine returned is suitable for matching text in - /// reverse. In particular, all concatenations are flipped. - pub fn reverse(mut self, yes: bool) -> Self { - self.compiled.is_reverse = yes; - self - } - - /// Compile a regular expression given its AST. - /// - /// The compiler is guaranteed to succeed unless the program exceeds the - /// specified size limit. If the size limit is exceeded, then compilation - /// stops and returns an error. - pub fn compile( - mut self, - exprs: &[Expr], - ) -> result::Result<Program, Error> { - debug_assert!(exprs.len() >= 1); - self.num_exprs = exprs.len(); - if exprs.len() == 1 { - self.compile_one(&exprs[0]) - } else { - self.compile_many(exprs) - } - } - - fn compile_one(mut self, expr: &Expr) -> result::Result<Program, Error> { - // If we're compiling a forward DFA and we aren't anchored, then - // add a `.*?` before the first capture group. - // Other matching engines handle this by baking the logic into the - // matching engine itself. - let mut dotstar_patch = Patch { hole: Hole::None, entry: 0 }; - self.compiled.is_anchored_start = expr.is_anchored_start(); - self.compiled.is_anchored_end = expr.is_anchored_end(); - if self.compiled.needs_dotstar() { - dotstar_patch = try!(self.c_dotstar()); - self.compiled.start = dotstar_patch.entry; - } - self.compiled.captures = vec![None]; - let patch = try!(self.c_capture(0, expr)); - if self.compiled.needs_dotstar() { - self.fill(dotstar_patch.hole, patch.entry); - } else { - self.compiled.start = patch.entry; - } - self.fill_to_next(patch.hole); - self.compiled.matches = vec![self.insts.len()]; - self.push_compiled(Inst::Match(0)); - self.compile_finish() - } - - fn compile_many( - mut self, - exprs: &[Expr], - ) -> result::Result<Program, Error> { - debug_assert!(exprs.len() > 1); - - self.compiled.is_anchored_start = - exprs.iter().all(|e| e.is_anchored_start()); - self.compiled.is_anchored_end = - exprs.iter().all(|e| e.is_anchored_end()); - let mut dotstar_patch = Patch { hole: Hole::None, entry: 0 }; - if self.compiled.needs_dotstar() { - dotstar_patch = try!(self.c_dotstar()); - self.compiled.start = dotstar_patch.entry; - } else { - self.compiled.start = 0; // first instruction is always split - } - self.fill_to_next(dotstar_patch.hole); - - let mut prev_hole = Hole::None; - for (i, expr) in exprs[0..exprs.len() - 1].iter().enumerate() { - self.fill_to_next(prev_hole); - let split = self.push_split_hole(); - let Patch { hole, entry } = try!(self.c_capture(0, expr)); - self.fill_to_next(hole); - self.compiled.matches.push(self.insts.len()); - self.push_compiled(Inst::Match(i)); - prev_hole = self.fill_split(split, Some(entry), None); - } - let i = exprs.len() - 1; - let Patch { hole, entry } = try!(self.c_capture(0, &exprs[i])); - self.fill(prev_hole, entry); - self.fill_to_next(hole); - self.compiled.matches.push(self.insts.len()); - self.push_compiled(Inst::Match(i)); - self.compile_finish() - } - - fn compile_finish(mut self) -> result::Result<Program, Error> { - self.compiled.insts = - self.insts.into_iter().map(|inst| inst.unwrap()).collect(); - self.compiled.byte_classes = self.byte_classes.byte_classes(); - self.compiled.capture_name_idx = Arc::new(self.capture_name_idx); - Ok(self.compiled) - } - - /// Compile expr into self.insts, returning a patch on success, - /// or an error if we run out of memory. - /// - /// All of the c_* methods of the compiler share the contract outlined - /// here. - /// - /// The main thing that a c_* method does is mutate `self.insts` - /// to add a list of mostly compiled instructions required to execute - /// the given expression. `self.insts` contains MaybeInsts rather than - /// Insts because there is some backpatching required. - /// - /// The `Patch` value returned by each c_* method provides metadata - /// about the compiled instructions emitted to `self.insts`. The - /// `entry` member of the patch refers to the first instruction - /// (the entry point), while the `hole` member contains zero or - /// more offsets to partial instructions that need to be backpatched. - /// The c_* routine can't know where its list of instructions are going to - /// jump to after execution, so it is up to the caller to patch - /// these jumps to point to the right place. So compiling some - /// expression, e, we would end up with a situation that looked like: - /// - /// ```text - /// self.insts = [ ..., i1, i2, ..., iexit1, ..., iexitn, ...] - /// ^ ^ ^ - /// | \ / - /// entry \ / - /// hole - /// ``` - /// - /// To compile two expressions, e1 and e2, concatinated together we - /// would do: - /// - /// ```ignore - /// let patch1 = self.c(e1); - /// let patch2 = self.c(e2); - /// ``` - /// - /// while leaves us with a situation that looks like - /// - /// ```text - /// self.insts = [ ..., i1, ..., iexit1, ..., i2, ..., iexit2 ] - /// ^ ^ ^ ^ - /// | | | | - /// entry1 hole1 entry2 hole2 - /// ``` - /// - /// Then to merge the two patches together into one we would backpatch - /// hole1 with entry2 and return a new patch that enters at entry1 - /// and has hole2 for a hole. In fact, if you look at the c_concat - /// method you will see that it does exactly this, though it handles - /// a list of expressions rather than just the two that we use for - /// an example. - fn c(&mut self, expr: &Expr) -> Result { - use prog; - use syntax::Expr::*; - - try!(self.check_size()); - match *expr { - Empty => Ok(Patch { hole: Hole::None, entry: self.insts.len() }), - Literal { ref chars, casei } => self.c_literal(chars, casei), - LiteralBytes { ref bytes, casei } => self.c_bytes(bytes, casei), - AnyChar => self.c_class(&[ClassRange { - start: '\x00', - end: '\u{10ffff}', - }]), - AnyCharNoNL => { - self.c_class(&[ - ClassRange { start: '\x00', end: '\x09' }, - ClassRange { start: '\x0b', end: '\u{10ffff}' }, - ]) - } - AnyByte => { - self.c_class_bytes(&[ByteRange { start: 0, end: 0xFF }]) - } - AnyByteNoNL => { - self.c_class_bytes(&[ - ByteRange { start: 0, end: 0x9 }, - ByteRange { start: 0xB, end: 0xFF }, - ]) - } - Class(ref cls) => { - self.c_class(cls) - } - ClassBytes(ref cls) => { - self.c_class_bytes(cls) - } - StartLine if self.compiled.is_reverse => { - self.byte_classes.set_range(b'\n', b'\n'); - self.c_empty_look(prog::EmptyLook::EndLine) - } - StartLine => { - self.byte_classes.set_range(b'\n', b'\n'); - self.c_empty_look(prog::EmptyLook::StartLine) - } - EndLine if self.compiled.is_reverse => { - self.byte_classes.set_range(b'\n', b'\n'); - self.c_empty_look(prog::EmptyLook::StartLine) - } - EndLine => { - self.byte_classes.set_range(b'\n', b'\n'); - self.c_empty_look(prog::EmptyLook::EndLine) - } - StartText if self.compiled.is_reverse => { - self.c_empty_look(prog::EmptyLook::EndText) - } - StartText => { - self.c_empty_look(prog::EmptyLook::StartText) - } - EndText if self.compiled.is_reverse => { - self.c_empty_look(prog::EmptyLook::StartText) - } - EndText => { - self.c_empty_look(prog::EmptyLook::EndText) - } - WordBoundary => { - self.compiled.has_unicode_word_boundary = true; - self.byte_classes.set_word_boundary(); - self.c_empty_look(prog::EmptyLook::WordBoundary) - } - NotWordBoundary => { - self.compiled.has_unicode_word_boundary = true; - self.byte_classes.set_word_boundary(); - self.c_empty_look(prog::EmptyLook::NotWordBoundary) - } - WordBoundaryAscii => { - self.byte_classes.set_word_boundary(); - self.c_empty_look(prog::EmptyLook::WordBoundaryAscii) - } - NotWordBoundaryAscii => { - self.byte_classes.set_word_boundary(); - self.c_empty_look(prog::EmptyLook::NotWordBoundaryAscii) - } - Group { ref e, i: None, name: None } => self.c(e), - Group { ref e, i, ref name } => { - // it's impossible to have a named capture without an index - let i = i.expect("capture index"); - if i >= self.compiled.captures.len() { - self.compiled.captures.push(name.clone()); - if let Some(ref name) = *name { - self.capture_name_idx.insert(name.to_owned(), i); - } - } - self.c_capture(2 * i, e) - } - Concat(ref es) => { - if self.compiled.is_reverse { - self.c_concat(es.iter().rev()) - } else { - self.c_concat(es) - } - } - Alternate(ref es) => self.c_alternate(&**es), - Repeat { ref e, r, greedy } => self.c_repeat(e, r, greedy), - } - } - - fn c_capture(&mut self, first_slot: usize, expr: &Expr) -> Result { - if self.num_exprs > 1 || self.compiled.is_dfa { - // Don't ever compile Save instructions for regex sets because - // they are never used. They are also never used in DFA programs - // because DFAs can't handle captures. - self.c(expr) - } else { - let entry = self.insts.len(); - let hole = self.push_hole(InstHole::Save { slot: first_slot }); - let patch = try!(self.c(expr)); - self.fill(hole, patch.entry); - self.fill_to_next(patch.hole); - let hole = self.push_hole(InstHole::Save { slot: first_slot + 1 }); - Ok(Patch { hole: hole, entry: entry }) - } - } - - fn c_dotstar(&mut self) -> Result { - Ok(if !self.compiled.only_utf8() { - try!(self.c(&Expr::Repeat { - e: Box::new(Expr::AnyByte), - r: Repeater::ZeroOrMore, - greedy: false, - })) - } else { - try!(self.c(&Expr::Repeat { - e: Box::new(Expr::AnyChar), - r: Repeater::ZeroOrMore, - greedy: false, - })) - }) - } - - fn c_literal(&mut self, chars: &[char], casei: bool) -> Result { - debug_assert!(!chars.is_empty()); - let mut chars: Box<Iterator<Item=&char>> = - if self.compiled.is_reverse { - Box::new(chars.iter().rev()) - } else { - Box::new(chars.iter()) - }; - let first = *chars.next().expect("non-empty literal"); - let Patch { mut hole, entry } = try!(self.c_char(first, casei)); - for &c in chars { - let p = try!(self.c_char(c, casei)); - self.fill(hole, p.entry); - hole = p.hole; - } - Ok(Patch { hole: hole, entry: entry }) - } - - fn c_char(&mut self, c: char, casei: bool) -> Result { - if casei { - self.c_class(&CharClass::new(vec![ - ClassRange { start: c, end: c }, - ]).case_fold()) - } else { - self.c_class(&[ClassRange { start: c, end: c }]) - } - } - - fn c_class(&mut self, ranges: &[ClassRange]) -> Result { - assert!(!ranges.is_empty()); - if self.compiled.uses_bytes() { - CompileClass { - c: self, - ranges: ranges, - }.compile() - } else { - let ranges: Vec<(char, char)> = - ranges.iter().map(|r| (r.start, r.end)).collect(); - let hole = if ranges.len() == 1 && ranges[0].0 == ranges[0].1 { - self.push_hole(InstHole::Char { c: ranges[0].0 }) - } else { - self.push_hole(InstHole::Ranges { ranges: ranges }) - }; - Ok(Patch { hole: hole, entry: self.insts.len() - 1 }) - } - } - - fn c_bytes(&mut self, bytes: &[u8], casei: bool) -> Result { - debug_assert!(!bytes.is_empty()); - let mut bytes: Box<Iterator<Item=&u8>> = - if self.compiled.is_reverse { - Box::new(bytes.iter().rev()) - } else { - Box::new(bytes.iter()) - }; - let first = *bytes.next().expect("non-empty literal"); - let Patch { mut hole, entry } = try!(self.c_byte(first, casei)); - for &b in bytes { - let p = try!(self.c_byte(b, casei)); - self.fill(hole, p.entry); - hole = p.hole; - } - Ok(Patch { hole: hole, entry: entry }) - } - - fn c_byte(&mut self, b: u8, casei: bool) -> Result { - if casei { - self.c_class_bytes(&ByteClass::new(vec![ - ByteRange { start: b, end: b }, - ]).case_fold()) - } else { - self.c_class_bytes(&[ByteRange { start: b, end: b }]) - } - } - - fn c_class_bytes(&mut self, ranges: &[ByteRange]) -> Result { - debug_assert!(!ranges.is_empty()); - - let first_split_entry = self.insts.len(); - let mut holes = vec![]; - let mut prev_hole = Hole::None; - for r in &ranges[0..ranges.len() - 1] { - self.fill_to_next(prev_hole); - let split = self.push_split_hole(); - let next = self.insts.len(); - self.byte_classes.set_range(r.start, r.end); - holes.push(self.push_hole(InstHole::Bytes { - start: r.start, end: r.end, - })); - prev_hole = self.fill_split(split, Some(next), None); - } - let next = self.insts.len(); - let r = &ranges[ranges.len() - 1]; - self.byte_classes.set_range(r.start, r.end); - holes.push(self.push_hole(InstHole::Bytes { - start: r.start, end: r.end, - })); - self.fill(prev_hole, next); - Ok(Patch { hole: Hole::Many(holes), entry: first_split_entry }) - } - - fn c_empty_look(&mut self, look: EmptyLook) -> Result { - let hole = self.push_hole(InstHole::EmptyLook { look: look }); - Ok(Patch { hole: hole, entry: self.insts.len() - 1 }) - } - - fn c_concat<'a, I>(&mut self, exprs: I) -> Result - where I: IntoIterator<Item=&'a Expr> { - let mut exprs = exprs.into_iter(); - let first = match exprs.next() { - Some(expr) => expr, - None => { - return Ok(Patch { hole: Hole::None, entry: self.insts.len() }) - } - }; - let Patch { mut hole, entry } = try!(self.c(first)); - for e in exprs { - let p = try!(self.c(e)); - self.fill(hole, p.entry); - hole = p.hole; - } - Ok(Patch { hole: hole, entry: entry }) - } - - fn c_alternate(&mut self, exprs: &[Expr]) -> Result { - debug_assert!( - exprs.len() >= 2, "alternates must have at least 2 exprs"); - - // Initial entry point is always the first split. - let first_split_entry = self.insts.len(); - - // Save up all of the holes from each alternate. They will all get - // patched to point to the same location. - let mut holes = vec![]; - - let mut prev_hole = Hole::None; - for e in &exprs[0..exprs.len() - 1] { - self.fill_to_next(prev_hole); - let split = self.push_split_hole(); - let Patch { hole, entry } = try!(self.c(e)); - holes.push(hole); - prev_hole = self.fill_split(split, Some(entry), None); - } - let Patch { hole, entry } = try!(self.c(&exprs[exprs.len() - 1])); - holes.push(hole); - self.fill(prev_hole, entry); - Ok(Patch { hole: Hole::Many(holes), entry: first_split_entry }) - } - - fn c_repeat( - &mut self, - expr: &Expr, - kind: Repeater, - greedy: bool, - ) -> Result { - match kind { - Repeater::ZeroOrOne => self.c_repeat_zero_or_one(expr, greedy), - Repeater::ZeroOrMore => self.c_repeat_zero_or_more(expr, greedy), - Repeater::OneOrMore => self.c_repeat_one_or_more(expr, greedy), - Repeater::Range { min, max: None } => { - self.c_repeat_range_min_or_more(expr, greedy, min) - } - Repeater::Range { min, max: Some(max) } => { - self.c_repeat_range(expr, greedy, min, max) - } - } - } - - fn c_repeat_zero_or_one( - &mut self, - expr: &Expr, - greedy: bool, - ) -> Result { - let split_entry = self.insts.len(); - let split = self.push_split_hole(); - let Patch { hole: hole_rep, entry: entry_rep } = try!(self.c(expr)); - - let split_hole = if greedy { - self.fill_split(split, Some(entry_rep), None) - } else { - self.fill_split(split, None, Some(entry_rep)) - }; - let holes = vec![hole_rep, split_hole]; - Ok(Patch { hole: Hole::Many(holes), entry: split_entry }) - } - - fn c_repeat_zero_or_more( - &mut self, - expr: &Expr, - greedy: bool, - ) -> Result { - let split_entry = self.insts.len(); - let split = self.push_split_hole(); - let Patch { hole: hole_rep, entry: entry_rep } = try!(self.c(expr)); - - self.fill(hole_rep, split_entry); - let split_hole = if greedy { - self.fill_split(split, Some(entry_rep), None) - } else { - self.fill_split(split, None, Some(entry_rep)) - }; - Ok(Patch { hole: split_hole, entry: split_entry }) - } - - fn c_repeat_one_or_more( - &mut self, - expr: &Expr, - greedy: bool, - ) -> Result { - let Patch { hole: hole_rep, entry: entry_rep } = try!(self.c(expr)); - self.fill_to_next(hole_rep); - let split = self.push_split_hole(); - - let split_hole = if greedy { - self.fill_split(split, Some(entry_rep), None) - } else { - self.fill_split(split, None, Some(entry_rep)) - }; - Ok(Patch { hole: split_hole, entry: entry_rep }) - } - - fn c_repeat_range_min_or_more( - &mut self, - expr: &Expr, - greedy: bool, - min: u32, - ) -> Result { - let min = u32_to_usize(min); - let patch_concat = try!(self.c_concat(iter::repeat(expr).take(min))); - let patch_rep = try!(self.c_repeat_zero_or_more(expr, greedy)); - self.fill(patch_concat.hole, patch_rep.entry); - Ok(Patch { hole: patch_rep.hole, entry: patch_concat.entry }) - } - - fn c_repeat_range( - &mut self, - expr: &Expr, - greedy: bool, - min: u32, - max: u32, - ) -> Result { - let (min, max) = (u32_to_usize(min), u32_to_usize(max)); - let patch_concat = try!(self.c_concat(iter::repeat(expr).take(min))); - let initial_entry = patch_concat.entry; - if min == max { - return Ok(patch_concat); - } - // It is much simpler to compile, e.g., `a{2,5}` as: - // - // aaa?a?a? - // - // But you end up with a sequence of instructions like this: - // - // 0: 'a' - // 1: 'a', - // 2: split(3, 4) - // 3: 'a' - // 4: split(5, 6) - // 5: 'a' - // 6: split(7, 8) - // 7: 'a' - // 8: MATCH - // - // This is *incredibly* inefficient because the splits end - // up forming a chain, which has to be resolved everything a - // transition is followed. - let mut holes = vec![]; - let mut prev_hole = patch_concat.hole; - for _ in min..max { - self.fill_to_next(prev_hole); - let split = self.push_split_hole(); - let Patch { hole, entry } = try!(self.c(expr)); - prev_hole = hole; - if greedy { - holes.push(self.fill_split(split, Some(entry), None)); - } else { - holes.push(self.fill_split(split, None, Some(entry))); - } - } - holes.push(prev_hole); - Ok(Patch { hole: Hole::Many(holes), entry: initial_entry }) - } - - fn fill(&mut self, hole: Hole, goto: InstPtr) { - match hole { - Hole::None => {} - Hole::One(pc) => { - self.insts[pc].fill(goto); - } - Hole::Many(holes) => { - for hole in holes { - self.fill(hole, goto); - } - } - } - } - - fn fill_to_next(&mut self, hole: Hole) { - let next = self.insts.len(); - self.fill(hole, next); - } - - fn fill_split( - &mut self, - hole: Hole, - goto1: Option<InstPtr>, - goto2: Option<InstPtr>, - ) -> Hole { - match hole { - Hole::None => Hole::None, - Hole::One(pc) => { - match (goto1, goto2) { - (Some(goto1), Some(goto2)) => { - self.insts[pc].fill_split(goto1, goto2); - Hole::None - } - (Some(goto1), None) => { - self.insts[pc].half_fill_split_goto1(goto1); - Hole::One(pc) - } - (None, Some(goto2)) => { - self.insts[pc].half_fill_split_goto2(goto2); - Hole::One(pc) - } - (None, None) => unreachable!("at least one of the split \ - holes must be filled"), - } - } - Hole::Many(holes) => { - let mut new_holes = vec![]; - for hole in holes { - new_holes.push(self.fill_split(hole, goto1, goto2)); - } - if new_holes.is_empty() { - Hole::None - } else if new_holes.len() == 1 { - new_holes.pop().unwrap() - } else { - Hole::Many(new_holes) - } - } - } - } - - fn push_compiled(&mut self, inst: Inst) { - self.insts.push(MaybeInst::Compiled(inst)); - } - - fn push_hole(&mut self, inst: InstHole) -> Hole { - let hole = self.insts.len(); - self.insts.push(MaybeInst::Uncompiled(inst)); - Hole::One(hole) - } - - fn push_split_hole(&mut self) -> Hole { - let hole = self.insts.len(); - self.insts.push(MaybeInst::Split); - Hole::One(hole) - } - - fn check_size(&self) -> result::Result<(), Error> { - use std::mem::size_of; - - if self.insts.len() * size_of::<Inst>() > self.size_limit { - Err(Error::CompiledTooBig(self.size_limit)) - } else { - Ok(()) - } - } -} - -#[derive(Debug)] -enum Hole { - None, - One(InstPtr), - Many(Vec<Hole>), -} - -#[derive(Clone, Debug)] -enum MaybeInst { - Compiled(Inst), - Uncompiled(InstHole), - Split, - Split1(InstPtr), - Split2(InstPtr), -} - -impl MaybeInst { - fn fill(&mut self, goto: InstPtr) { - let filled = match *self { - MaybeInst::Uncompiled(ref inst) => inst.fill(goto), - MaybeInst::Split1(goto1) => { - Inst::Split(InstSplit { goto1: goto1, goto2: goto }) - } - MaybeInst::Split2(goto2) => { - Inst::Split(InstSplit { goto1: goto, goto2: goto2 }) - } - _ => unreachable!("not all instructions were compiled! \ - found uncompiled instruction: {:?}", self), - }; - *self = MaybeInst::Compiled(filled); - } - - fn fill_split(&mut self, goto1: InstPtr, goto2: InstPtr) { - let filled = match *self { - MaybeInst::Split => { - Inst::Split(InstSplit { goto1: goto1, goto2: goto2 }) - } - _ => unreachable!("must be called on Split instruction, \ - instead it was called on: {:?}", self), - }; - *self = MaybeInst::Compiled(filled); - } - - fn half_fill_split_goto1(&mut self, goto1: InstPtr) { - let half_filled = match *self { - MaybeInst::Split => goto1, - _ => unreachable!("must be called on Split instruction, \ - instead it was called on: {:?}", self), - }; - *self = MaybeInst::Split1(half_filled); - } - - fn half_fill_split_goto2(&mut self, goto2: InstPtr) { - let half_filled = match *self { - MaybeInst::Split => goto2, - _ => unreachable!("must be called on Split instruction, \ - instead it was called on: {:?}", self), - }; - *self = MaybeInst::Split2(half_filled); - } - - fn unwrap(self) -> Inst { - match self { - MaybeInst::Compiled(inst) => inst, - _ => unreachable!("must be called on a compiled instruction, \ - instead it was called on: {:?}", self), - } - } -} - -#[derive(Clone, Debug)] -enum InstHole { - Save { slot: usize }, - EmptyLook { look: EmptyLook }, - Char { c: char }, - Ranges { ranges: Vec<(char, char)> }, - Bytes { start: u8, end: u8 }, -} - -impl InstHole { - fn fill(&self, goto: InstPtr) -> Inst { - match *self { - InstHole::Save { slot } => Inst::Save(InstSave { - goto: goto, - slot: slot, - }), - InstHole::EmptyLook { look } => Inst::EmptyLook(InstEmptyLook { - goto: goto, - look: look, - }), - InstHole::Char { c } => Inst::Char(InstChar { - goto: goto, - c: c, - }), - InstHole::Ranges { ref ranges } => Inst::Ranges(InstRanges { - goto: goto, - ranges: ranges.clone(), - }), - InstHole::Bytes { start, end } => Inst::Bytes(InstBytes { - goto: goto, - start: start, - end: end, - }), - } - } -} - -struct CompileClass<'a, 'b> { - c: &'a mut Compiler, - ranges: &'b [ClassRange], -} - -impl<'a, 'b> CompileClass<'a, 'b> { - fn compile(mut self) -> Result { - let mut holes = vec![]; - let mut initial_entry = None; - let mut last_split = Hole::None; - let mut utf8_seqs = self.c.utf8_seqs.take().unwrap(); - self.c.suffix_cache.clear(); - - for (i, range) in self.ranges.iter().enumerate() { - let is_last_range = i + 1 == self.ranges.len(); - utf8_seqs.reset(range.start, range.end); - let mut it = (&mut utf8_seqs).peekable(); - loop { - let utf8_seq = match it.next() { - None => break, - Some(utf8_seq) => utf8_seq, - }; - if is_last_range && it.peek().is_none() { - let Patch { hole, entry } = try!(self.c_utf8_seq(&utf8_seq)); - holes.push(hole); - self.c.fill(last_split, entry); - last_split = Hole::None; - if initial_entry.is_none() { - initial_entry = Some(entry); - } - } else { - if initial_entry.is_none() { - initial_entry = Some(self.c.insts.len()); - } - self.c.fill_to_next(last_split); - last_split = self.c.push_split_hole(); - let Patch { hole, entry } = try!(self.c_utf8_seq(&utf8_seq)); - holes.push(hole); - last_split = self.c.fill_split(last_split, Some(entry), None); - } - } - } - self.c.utf8_seqs = Some(utf8_seqs); - Ok(Patch { - hole: Hole::Many(holes), - entry: initial_entry.unwrap(), - }) - } - - fn c_utf8_seq(&mut self, seq: &Utf8Sequence) -> Result { - if self.c.compiled.is_reverse { - self.c_utf8_seq_(seq) - } else { - self.c_utf8_seq_(seq.into_iter().rev()) - } - } - - fn c_utf8_seq_<'r, I>(&mut self, seq: I) -> Result - where I: IntoIterator<Item=&'r Utf8Range> { - // The initial instruction for each UTF-8 sequence should be the same. - let mut from_inst = ::std::usize::MAX; - let mut last_hole = Hole::None; - for byte_range in seq { - let key = SuffixCacheKey { - from_inst: from_inst, - start: byte_range.start, - end: byte_range.end, - }; - { - let pc = self.c.insts.len(); - if let Some(cached_pc) = self.c.suffix_cache.get(key, pc) { - from_inst = cached_pc; - continue; - } - } - self.c.byte_classes.set_range(byte_range.start, byte_range.end); - if from_inst == ::std::usize::MAX { - last_hole = self.c.push_hole(InstHole::Bytes { - start: byte_range.start, - end: byte_range.end, - }); - } else { - self.c.push_compiled(Inst::Bytes(InstBytes { - goto: from_inst, - start: byte_range.start, - end: byte_range.end, - })); - } - from_inst = self.c.insts.len().checked_sub(1).unwrap(); - debug_assert!(from_inst < ::std::usize::MAX); - } - debug_assert!(from_inst < ::std::usize::MAX); - Ok(Patch { hole: last_hole, entry: from_inst }) - } -} - -/// `SuffixCache` is a simple bounded hash map for caching suffix entries in -/// UTF-8 automata. For example, consider the Unicode range \u{0}-\u{FFFF}. -/// The set of byte ranges looks like this: -/// -/// [0-7F] -/// [C2-DF][80-BF] -/// [E0][A0-BF][80-BF] -/// [E1-EC][80-BF][80-BF] -/// [ED][80-9F][80-BF] -/// [EE-EF][80-BF][80-BF] -/// -/// Each line above translates to one alternate in the compiled regex program. -/// However, all but one of the alternates end in the same suffix, which is -/// a waste of an instruction. The suffix cache facilitates reusing them across -/// alternates. -/// -/// Note that a HashMap could be trivially used for this, but we don't need its -/// overhead. Some small bounded space (LRU style) is more than enough. -struct SuffixCache { - table: Vec<SuffixCacheEntry>, - // Every time the cache is cleared, we increment the version number instead - // of actually zeroing memory. Since we store a copy of the current version - // in every element, all we need to do is make sure to invalidate any stale - // entries upon access. This saves quite a bit of time! - version: usize, -} - -#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] -struct SuffixCacheEntry { - key: SuffixCacheKey, - pc: InstPtr, - version: usize, -} - -#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)] -struct SuffixCacheKey { - from_inst: InstPtr, - start: u8, - end: u8, -} - -impl SuffixCache { - fn new(size: usize) -> Self { - SuffixCache { - table: vec![SuffixCacheEntry::default(); size], - version: 0, - } - } - - fn get(&mut self, key: SuffixCacheKey, pc: InstPtr) -> Option<InstPtr> { - let h = self.hash(&key); - let e = self.table[h]; - if e.key == key && e.version == self.version { - Some(e.pc) - } else { - self.table[h] = SuffixCacheEntry { - key: key, - pc: pc, - version: self.version, - }; - None - } - } - - fn clear(&mut self) { - self.version += 1; - } - - fn hash(&self, suffix: &SuffixCacheKey) -> usize { - // Basic FNV-1a hash as described: - // https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function - const FNV_PRIME: u64 = 1099511628211; - let mut h = 14695981039346656037; - h = (h ^ (suffix.from_inst as u64)).wrapping_mul(FNV_PRIME); - h = (h ^ (suffix.start as u64)).wrapping_mul(FNV_PRIME); - h = (h ^ (suffix.end as u64)).wrapping_mul(FNV_PRIME); - (h as usize) % self.table.len() - } -} - -struct ByteClassSet([bool; 256]); - -impl ByteClassSet { - fn new() -> Self { - ByteClassSet([false; 256]) - } - - fn set_range(&mut self, start: u8, end: u8) { - debug_assert!(start <= end); - if start > 0 { - self.0[start as usize - 1] = true; - } - self.0[end as usize] = true; - } - - fn set_word_boundary(&mut self) { - // We need to mark all ranges of bytes whose pairs result in - // evaluating \b differently. - let iswb = is_word_byte; - let mut b1: u16 = 0; - let mut b2: u16; - while b1 <= 255 { - b2 = b1 + 1; - while b2 <= 255 && iswb(b1 as u8) == iswb(b2 as u8) { - b2 += 1; - } - self.set_range(b1 as u8, (b2 - 1) as u8); - b1 = b2; - } - } - - fn byte_classes(&self) -> Vec<u8> { - // N.B. If you're debugging the DFA, it's useful to simply return - // `(0..256).collect()`, which effectively removes the byte classes - // and makes the transitions easier to read. - // (0usize..256).map(|x| x as u8).collect() - let mut byte_classes = vec![0; 256]; - let mut class = 0u8; - let mut i = 0; - loop { - byte_classes[i] = class as u8; - if i >= 255 { - break; - } - if self.0[i] { - class = class.checked_add(1).unwrap(); - } - i += 1; - } - byte_classes - } -} - -fn u32_to_usize(n: u32) -> usize { - // In case usize is less than 32 bits, we need to guard against overflow. - // On most platforms this compiles to nothing. - // TODO Use `std::convert::TryFrom` once it's stable. - if (n as u64) > (::std::usize::MAX as u64) { - panic!("BUG: {} is too big to be pointer sized", n) - } - n as usize -} - -#[cfg(test)] -mod tests { - use super::ByteClassSet; - - #[test] - fn byte_classes() { - let mut set = ByteClassSet::new(); - set.set_range(b'a', b'z'); - let classes = set.byte_classes(); - assert_eq!(classes[0], 0); - assert_eq!(classes[1], 0); - assert_eq!(classes[2], 0); - assert_eq!(classes[b'a' as usize - 1], 0); - assert_eq!(classes[b'a' as usize], 1); - assert_eq!(classes[b'm' as usize], 1); - assert_eq!(classes[b'z' as usize], 1); - assert_eq!(classes[b'z' as usize + 1], 2); - assert_eq!(classes[254], 2); - assert_eq!(classes[255], 2); - - let mut set = ByteClassSet::new(); - set.set_range(0, 2); - set.set_range(4, 6); - let classes = set.byte_classes(); - assert_eq!(classes[0], 0); - assert_eq!(classes[1], 0); - assert_eq!(classes[2], 0); - assert_eq!(classes[3], 1); - assert_eq!(classes[4], 2); - assert_eq!(classes[5], 2); - assert_eq!(classes[6], 2); - assert_eq!(classes[7], 3); - assert_eq!(classes[255], 3); - } - - #[test] - fn full_byte_classes() { - let mut set = ByteClassSet::new(); - for i in 0..256u16 { - set.set_range(i as u8, i as u8); - } - assert_eq!(set.byte_classes().len(), 256); - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/dfa.rs cargo-0.26.0/vendor/regex-0.2.6/src/dfa.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/dfa.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/dfa.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1884 +0,0 @@ -// Copyright 2014-2016 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/*! -The DFA matching engine. - -A DFA provides faster matching because the engine is in exactly one state at -any point in time. In the NFA, there may be multiple active states, and -considerable CPU cycles are spent shuffling them around. In finite automata -speak, the DFA follows epsilon transitions in the regex far less than the NFA. - -A DFA is a classic trade off between time and space. The NFA is slower, but -its memory requirements are typically small and predictable. The DFA is faster, -but given the right regex and the right input, the number of states in the -DFA can grow exponentially. To mitigate this space problem, we do two things: - -1. We implement an *online* DFA. That is, the DFA is constructed from the NFA - during a search. When a new state is computed, it is stored in a cache so - that it may be reused. An important consequence of this implementation - is that states that are never reached for a particular input are never - computed. (This is impossible in an "offline" DFA which needs to compute - all possible states up front.) -2. If the cache gets too big, we wipe it and continue matching. - -In pathological cases, a new state can be created for every byte of input. -(e.g., The regex `(a|b)*a(a|b){20}` on a long sequence of a's and b's.) -In this case, performance regresses to slightly slower than the full NFA -simulation, in large part because the cache becomes useless. If the cache -is wiped too frequently, the DFA quits and control falls back to one of the -NFA simulations. - -Because of the "lazy" nature of this DFA, the inner matching loop is -considerably more complex than one might expect out of a DFA. A number of -tricks are employed to make it fast. Tread carefully. - -N.B. While this implementation is heavily commented, Russ Cox's series of -articles on regexes is strongly recommended: https://swtch.com/~rsc/regexp/ -(As is the DFA implementation in RE2, which heavily influenced this -implementation.) -*/ - -use std::collections::HashMap; -use std::fmt; -use std::iter::repeat; -use std::mem; - -use exec::ProgramCache; -use prog::{Inst, Program}; -use sparse::SparseSet; - -/// Return true if and only if the given program can be executed by a DFA. -/// -/// Generally, a DFA is always possible. A pathological case where it is not -/// possible is if the number of NFA states exceeds `u32::MAX`, in which case, -/// this function will return false. -/// -/// This function will also return false if the given program has any Unicode -/// instructions (Char or Ranges) since the DFA operates on bytes only. -pub fn can_exec(insts: &Program) -> bool { - use prog::Inst::*; - // If for some reason we manage to allocate a regex program with more - // than i32::MAX instructions, then we can't execute the DFA because we - // use 32 bit instruction pointer deltas for memory savings. - // If i32::MAX is the largest positive delta, - // then -i32::MAX == i32::MIN + 1 is the largest negative delta, - // and we are OK to use 32 bits. - if insts.len() > ::std::i32::MAX as usize { - return false; - } - for inst in insts { - match *inst { - Char(_) | Ranges(_) => return false, - EmptyLook(_) | Match(_) | Save(_) | Split(_) | Bytes(_) => {} - } - } - true -} - -/// A reusable cache of DFA states. -/// -/// This cache is reused between multiple invocations of the same regex -/// program. (It is not shared simultaneously between threads. If there is -/// contention, then new caches are created.) -#[derive(Clone, Debug)] -pub struct Cache { - /// Group persistent DFA related cache state together. The sparse sets - /// listed below are used as scratch space while computing uncached states. - inner: CacheInner, - /// qcur and qnext are ordered sets with constant time - /// addition/membership/clearing-whole-set and linear time iteration. They - /// are used to manage the sets of NFA states in DFA states when computing - /// cached DFA states. In particular, the order of the NFA states matters - /// for leftmost-first style matching. Namely, when computing a cached - /// state, the set of NFA states stops growing as soon as the first Match - /// instruction is observed. - qcur: SparseSet, - qnext: SparseSet, -} - -/// `CacheInner` is logically just a part of Cache, but groups together fields -/// that aren't passed as function parameters throughout search. (This split -/// is mostly an artifact of the borrow checker. It is happily paid.) -#[derive(Clone, Debug)] -struct CacheInner { - /// A cache of pre-compiled DFA states, keyed by the set of NFA states - /// and the set of empty-width flags set at the byte in the input when the - /// state was observed. - /// - /// A StatePtr is effectively a `*State`, but to avoid various inconvenient - /// things, we just pass indexes around manually. The performance impact of - /// this is probably an instruction or two in the inner loop. However, on - /// 64 bit, each StatePtr is half the size of a *State. - compiled: HashMap<State, StatePtr>, - /// The transition table. - /// - /// The transition table is laid out in row-major order, where states are - /// rows and the transitions for each state are columns. At a high level, - /// given state `s` and byte `b`, the next state can be found at index - /// `s * 256 + b`. - /// - /// This is, of course, a lie. A StatePtr is actually a pointer to the - /// *start* of a row in this table. When indexing in the DFA's inner loop, - /// this removes the need to multiply the StatePtr by the stride. Yes, it - /// matters. This reduces the number of states we can store, but: the - /// stride is rarely 256 since we define transitions in terms of - /// *equivalence classes* of bytes. Each class corresponds to a set of - /// bytes that never discriminate a distinct path through the DFA from each - /// other. - trans: Transitions, - /// Our set of states. Note that `StatePtr / num_byte_classes` indexes - /// this Vec rather than just a `StatePtr`. - states: Vec<State>, - /// A set of cached start states, which are limited to the number of - /// permutations of flags set just before the initial byte of input. (The - /// index into this vec is a `EmptyFlags`.) - /// - /// N.B. A start state can be "dead" (i.e., no possible match), so we - /// represent it with a StatePtr. - start_states: Vec<StatePtr>, - /// Stack scratch space used to follow epsilon transitions in the NFA. - /// (This permits us to avoid recursion.) - /// - /// The maximum stack size is the number of NFA states. - stack: Vec<InstPtr>, - /// The total number of times this cache has been flushed by the DFA - /// because of space constraints. - flush_count: u64, - /// The total heap size of the DFA's cache. We use this to determine when - /// we should flush the cache. - size: usize, -} - -/// The transition table. -/// -/// It is laid out in row-major order, with states as rows and byte class -/// transitions as columns. -/// -/// The transition table is responsible for producing valid `StatePtrs`. A -/// `StatePtr` points to the start of a particular row in this table. When -/// indexing to find the next state this allows us to avoid a multiplication -/// when computing an index into the table. -#[derive(Clone)] -struct Transitions { - /// The table. - table: Vec<StatePtr>, - /// The stride. - num_byte_classes: usize, -} - -/// Fsm encapsulates the actual execution of the DFA. -#[derive(Debug)] -pub struct Fsm<'a> { - /// prog contains the NFA instruction opcodes. DFA execution uses either - /// the `dfa` instructions or the `dfa_reverse` instructions from - /// `exec::ExecReadOnly`. (It never uses `ExecReadOnly.nfa`, which may have - /// Unicode opcodes that cannot be executed by the DFA.) - prog: &'a Program, - /// The start state. We record it here because the pointer may change - /// when the cache is wiped. - start: StatePtr, - /// The current position in the input. - at: usize, - /// Should we quit after seeing the first match? e.g., When the caller - /// uses `is_match` or `shortest_match`. - quit_after_match: bool, - /// The last state that matched. - /// - /// When no match has occurred, this is set to STATE_UNKNOWN. - /// - /// This is only useful when matching regex sets. The last match state - /// is useful because it contains all of the match instructions seen, - /// thereby allowing us to enumerate which regexes in the set matched. - last_match_si: StatePtr, - /// The input position of the last cache flush. We use this to determine - /// if we're thrashing in the cache too often. If so, the DFA quits so - /// that we can fall back to the NFA algorithm. - last_cache_flush: usize, - /// All cached DFA information that is persisted between searches. - cache: &'a mut CacheInner, -} - -/// The result of running the DFA. -/// -/// Generally, the result is either a match or not a match, but sometimes the -/// DFA runs too slowly because the cache size is too small. In that case, it -/// gives up with the intent of falling back to the NFA algorithm. -/// -/// The DFA can also give up if it runs out of room to create new states, or if -/// it sees non-ASCII bytes in the presence of a Unicode word boundary. -#[derive(Clone, Debug)] -pub enum Result<T> { - Match(T), - NoMatch(usize), - Quit, -} - -impl<T> Result<T> { - /// Returns true if this result corresponds to a match. - pub fn is_match(&self) -> bool { - match *self { - Result::Match(_) => true, - Result::NoMatch(_) | Result::Quit => false, - } - } - - /// Maps the given function onto T and returns the result. - /// - /// If this isn't a match, then this is a no-op. - pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> Result<U> { - match self { - Result::Match(t) => Result::Match(f(t)), - Result::NoMatch(x) => Result::NoMatch(x), - Result::Quit => Result::Quit, - } - } - - /// Sets the non-match position. - /// - /// If this isn't a non-match, then this is a no-op. - fn set_non_match(self, at: usize) -> Result<T> { - match self { - Result::NoMatch(_) => Result::NoMatch(at), - r => r, - } - } -} - -/// `State` is a DFA state. It contains an ordered set of NFA states (not -/// necessarily complete) and a smattering of flags. -/// -/// The flags are packed into the first byte of data. -/// -/// States don't carry their transitions. Instead, transitions are stored in -/// a single row-major table. -/// -/// Delta encoding is used to store the instruction pointers. -/// The first instruction pointer is stored directly starting -/// at data[1], and each following pointer is stored as an offset -/// to the previous one. If a delta is in the range -127..127, -/// it is packed into a single byte; Otherwise the byte 128 (-128 as an i8) -/// is coded as a flag, followed by 4 bytes encoding the delta. -#[derive(Clone, Eq, Hash, PartialEq)] -struct State{ - data: Box<[u8]>, -} - -/// `InstPtr` is a 32 bit pointer into a sequence of opcodes (i.e., it indexes -/// an NFA state). -/// -/// Throughout this library, this is usually set to `usize`, but we force a -/// `u32` here for the DFA to save on space. -type InstPtr = u32; - -/// Adds ip to data using delta encoding with respect to prev. -/// -/// After completion, `data` will contain `ip` and `prev` will be set to `ip`. -fn push_inst_ptr(data: &mut Vec<u8>, prev: &mut InstPtr, ip: InstPtr) { - let delta = (ip as i32) - (*prev as i32); - write_vari32(data, delta); - *prev = ip; -} - -struct InstPtrs<'a> { - base: usize, - data: &'a [u8], -} - -impl <'a>Iterator for InstPtrs<'a> { - type Item = usize; - - fn next(&mut self) -> Option<usize> { - if self.data.is_empty() { - return None; - } - let (delta, nread) = read_vari32(self.data); - let base = self.base as i32 + delta; - debug_assert!(base >= 0); - debug_assert!(nread > 0); - self.data = &self.data[nread..]; - self.base = base as usize; - Some(self.base) - } -} - -impl State { - fn flags(&self) -> StateFlags { - StateFlags(self.data[0]) - } - - fn inst_ptrs(&self) -> InstPtrs { - InstPtrs { - base: 0, - data: &self.data[1..], - } - } -} - -/// `StatePtr` is a 32 bit pointer to the start of a row in the transition -/// table. -/// -/// It has many special values. There are two types of special values: -/// sentinels and flags. -/// -/// Sentinels corresponds to special states that carry some kind of -/// significance. There are three such states: unknown, dead and quit states. -/// -/// Unknown states are states that haven't been computed yet. They indicate -/// that a transition should be filled in that points to either an existing -/// cached state or a new state altogether. In general, an unknown state means -/// "follow the NFA's epsilon transitions." -/// -/// Dead states are states that can never lead to a match, no matter what -/// subsequent input is observed. This means that the DFA should quit -/// immediately and return the longest match it has found thus far. -/// -/// Quit states are states that imply the DFA is not capable of matching the -/// regex correctly. Currently, this is only used when a Unicode word boundary -/// exists in the regex *and* a non-ASCII byte is observed. -/// -/// The other type of state pointer is a state pointer with special flag bits. -/// There are two flags: a start flag and a match flag. The lower bits of both -/// kinds always contain a "valid" `StatePtr` (indicated by the `STATE_MAX` -/// mask). -/// -/// The start flag means that the state is a start state, and therefore may be -/// subject to special prefix scanning optimizations. -/// -/// The match flag means that the state is a match state, and therefore the -/// current position in the input (while searching) should be recorded. -/// -/// The above exists mostly in the service of making the inner loop fast. -/// In particular, the inner *inner* loop looks something like this: -/// -/// ```ignore -/// while state <= STATE_MAX and i < len(text): -/// state = state.next[i] -/// ``` -/// -/// This is nice because it lets us execute a lazy DFA as if it were an -/// entirely offline DFA (i.e., with very few instructions). The loop will -/// quit only when we need to examine a case that needs special attention. -type StatePtr = u32; - -/// An unknown state means that the state has not been computed yet, and that -/// the only way to progress is to compute it. -const STATE_UNKNOWN: StatePtr = 1<<31; - -/// A dead state means that the state has been computed and it is known that -/// once it is entered, no future match can ever occur. -const STATE_DEAD: StatePtr = STATE_UNKNOWN + 1; - -/// A quit state means that the DFA came across some input that it doesn't -/// know how to process correctly. The DFA should quit and another matching -/// engine should be run in its place. -const STATE_QUIT: StatePtr = STATE_DEAD + 1; - -/// A start state is a state that the DFA can start in. -/// -/// Note that start states have their lower bits set to a state pointer. -const STATE_START: StatePtr = 1<<30; - -/// A match state means that the regex has successfully matched. -/// -/// Note that match states have their lower bits set to a state pointer. -const STATE_MATCH: StatePtr = 1<<29; - -/// The maximum state pointer. This is useful to mask out the "valid" state -/// pointer from a state with the "start" or "match" bits set. -/// -/// It doesn't make sense to use this with unknown, dead or quit state -/// pointers, since those pointers are sentinels and never have their lower -/// bits set to anything meaningful. -const STATE_MAX: StatePtr = STATE_MATCH - 1; - -/// Byte is a u8 in spirit, but a u16 in practice so that we can represent the -/// special EOF sentinel value. -#[derive(Copy, Clone, Debug)] -struct Byte(u16); - -/// A set of flags for zero-width assertions. -#[derive(Clone, Copy, Eq, Debug, Default, Hash, PartialEq)] -struct EmptyFlags { - start: bool, - end: bool, - start_line: bool, - end_line: bool, - word_boundary: bool, - not_word_boundary: bool, -} - -/// A set of flags describing various configurations of a DFA state. This is -/// represented by a `u8` so that it is compact. -#[derive(Clone, Copy, Eq, Default, Hash, PartialEq)] -struct StateFlags(u8); - -impl Cache { - /// Create new empty cache for the DFA engine. - pub fn new(prog: &Program) -> Self { - // We add 1 to account for the special EOF byte. - let num_byte_classes = (prog.byte_classes[255] as usize + 1) + 1; - let starts = vec![STATE_UNKNOWN; 256]; - let mut cache = Cache { - inner: CacheInner { - compiled: HashMap::new(), - trans: Transitions::new(num_byte_classes), - states: vec![], - start_states: starts, - stack: vec![], - flush_count: 0, - size: 0, - }, - qcur: SparseSet::new(prog.insts.len()), - qnext: SparseSet::new(prog.insts.len()), - }; - cache.inner.reset_size(); - cache - } -} - -impl CacheInner { - /// Resets the cache size to account for fixed costs, such as the program - /// and stack sizes. - fn reset_size(&mut self) { - self.size = - (self.start_states.len() * mem::size_of::<StatePtr>()) - + (self.stack.len() * mem::size_of::<InstPtr>()); - } -} - -impl<'a> Fsm<'a> { - #[inline(always)] // reduces constant overhead - pub fn forward( - prog: &'a Program, - cache: &ProgramCache, - quit_after_match: bool, - text: &[u8], - at: usize, - ) -> Result<usize> { - let mut cache = cache.borrow_mut(); - let cache = &mut cache.dfa; - let mut dfa = Fsm { - prog: prog, - start: 0, // filled in below - at: at, - quit_after_match: quit_after_match, - last_match_si: STATE_UNKNOWN, - last_cache_flush: at, - cache: &mut cache.inner, - }; - let (empty_flags, state_flags) = dfa.start_flags(text, at); - dfa.start = match dfa.start_state( - &mut cache.qcur, - empty_flags, - state_flags, - ) { - None => return Result::Quit, - Some(STATE_DEAD) => return Result::NoMatch(at), - Some(si) => si, - }; - debug_assert!(dfa.start != STATE_UNKNOWN); - dfa.exec_at(&mut cache.qcur, &mut cache.qnext, text) - } - - #[inline(always)] // reduces constant overhead - pub fn reverse( - prog: &'a Program, - cache: &ProgramCache, - quit_after_match: bool, - text: &[u8], - at: usize, - ) -> Result<usize> { - let mut cache = cache.borrow_mut(); - let cache = &mut cache.dfa_reverse; - let mut dfa = Fsm { - prog: prog, - start: 0, // filled in below - at: at, - quit_after_match: quit_after_match, - last_match_si: STATE_UNKNOWN, - last_cache_flush: at, - cache: &mut cache.inner, - }; - let (empty_flags, state_flags) = dfa.start_flags_reverse(text, at); - dfa.start = match dfa.start_state( - &mut cache.qcur, - empty_flags, - state_flags, - ) { - None => return Result::Quit, - Some(STATE_DEAD) => return Result::NoMatch(at), - Some(si) => si, - }; - debug_assert!(dfa.start != STATE_UNKNOWN); - dfa.exec_at_reverse(&mut cache.qcur, &mut cache.qnext, text) - } - - #[inline(always)] // reduces constant overhead - pub fn forward_many( - prog: &'a Program, - cache: &ProgramCache, - matches: &mut [bool], - text: &[u8], - at: usize, - ) -> Result<usize> { - debug_assert!(matches.len() == prog.matches.len()); - let mut cache = cache.borrow_mut(); - let cache = &mut cache.dfa; - let mut dfa = Fsm { - prog: prog, - start: 0, // filled in below - at: at, - quit_after_match: false, - last_match_si: STATE_UNKNOWN, - last_cache_flush: at, - cache: &mut cache.inner, - }; - let (empty_flags, state_flags) = dfa.start_flags(text, at); - dfa.start = match dfa.start_state( - &mut cache.qcur, - empty_flags, - state_flags, - ) { - None => return Result::Quit, - Some(STATE_DEAD) => return Result::NoMatch(at), - Some(si) => si, - }; - debug_assert!(dfa.start != STATE_UNKNOWN); - let result = dfa.exec_at(&mut cache.qcur, &mut cache.qnext, text); - if result.is_match() { - if matches.len() == 1 { - matches[0] = true; - } else { - debug_assert!(dfa.last_match_si != STATE_UNKNOWN); - debug_assert!(dfa.last_match_si != STATE_DEAD); - for ip in dfa.state(dfa.last_match_si).inst_ptrs() { - if let Inst::Match(slot) = dfa.prog[ip] { - matches[slot] = true; - } - } - } - } - result - } - - /// Executes the DFA on a forward NFA. - /// - /// {qcur,qnext} are scratch ordered sets which may be non-empty. - #[inline(always)] // reduces constant overhead - fn exec_at( - &mut self, - qcur: &mut SparseSet, - qnext: &mut SparseSet, - text: &[u8], - ) -> Result<usize> { - // For the most part, the DFA is basically: - // - // last_match = null - // while current_byte != EOF: - // si = current_state.next[current_byte] - // if si is match - // last_match = si - // return last_match - // - // However, we need to deal with a few things: - // - // 1. This is an *online* DFA, so the current state's next list - // may not point to anywhere yet, so we must go out and compute - // them. (They are then cached into the current state's next list - // to avoid re-computation.) - // 2. If we come across a state that is known to be dead (i.e., never - // leads to a match), then we can quit early. - // 3. If the caller just wants to know if a match occurs, then we - // can quit as soon as we know we have a match. (Full leftmost - // first semantics require continuing on.) - // 4. If we're in the start state, then we can use a pre-computed set - // of prefix literals to skip quickly along the input. - // 5. After the input is exhausted, we run the DFA on one symbol - // that stands for EOF. This is useful for handling empty width - // assertions. - // 6. We can't actually do state.next[byte]. Instead, we have to do - // state.next[byte_classes[byte]], which permits us to keep the - // 'next' list very small. - // - // Since there's a bunch of extra stuff we need to consider, we do some - // pretty hairy tricks to get the inner loop to run as fast as - // possible. - debug_assert!(!self.prog.is_reverse); - - // The last match is the currently known ending match position. It is - // reported as an index to the most recent byte that resulted in a - // transition to a match state and is always stored in capture slot `1` - // when searching forwards. Its maximum value is `text.len()`. - let mut result = Result::NoMatch(self.at); - let (mut prev_si, mut next_si) = (self.start, self.start); - let mut at = self.at; - while at < text.len() { - // This is the real inner loop. We take advantage of special bits - // set in the state pointer to determine whether a state is in the - // "common" case or not. Specifically, the common case is a - // non-match non-start non-dead state that has already been - // computed. So long as we remain in the common case, this inner - // loop will chew through the input. - // - // We also unroll the loop 4 times to amortize the cost of checking - // whether we've consumed the entire input. We are also careful - // to make sure that `prev_si` always represents the previous state - // and `next_si` always represents the next state after the loop - // exits, even if it isn't always true inside the loop. - while next_si <= STATE_MAX && at < text.len() { - // Argument for safety is in the definition of next_si. - prev_si = unsafe { self.next_si(next_si, text, at) }; - at += 1; - if prev_si > STATE_MAX || at + 2 >= text.len() { - mem::swap(&mut prev_si, &mut next_si); - break; - } - next_si = unsafe { self.next_si(prev_si, text, at) }; - at += 1; - if next_si > STATE_MAX { - break; - } - prev_si = unsafe { self.next_si(next_si, text, at) }; - at += 1; - if prev_si > STATE_MAX { - mem::swap(&mut prev_si, &mut next_si); - break; - } - next_si = unsafe { self.next_si(prev_si, text, at) }; - at += 1; - } - if next_si & STATE_MATCH > 0 { - // A match state is outside of the common case because it needs - // special case analysis. In particular, we need to record the - // last position as having matched and possibly quit the DFA if - // we don't need to keep matching. - next_si &= !STATE_MATCH; - result = Result::Match(at - 1); - if self.quit_after_match { - return result; - } - self.last_match_si = next_si; - prev_si = next_si; - - // This permits short-circuiting when matching a regex set. - // In particular, if this DFA state contains only match states, - // then it's impossible to extend the set of matches since - // match states are final. Therefore, we can quit. - if self.prog.matches.len() > 1 { - let state = self.state(next_si); - let just_matches = state.inst_ptrs() - .all(|ip| self.prog[ip].is_match()); - if just_matches { - return result; - } - } - - // Another inner loop! If the DFA stays in this particular - // match state, then we can rip through all of the input - // very quickly, and only recording the match location once - // we've left this particular state. - let cur = at; - while (next_si & !STATE_MATCH) == prev_si - && at + 2 < text.len() { - // Argument for safety is in the definition of next_si. - next_si = unsafe { - self.next_si(next_si & !STATE_MATCH, text, at) - }; - at += 1; - } - if at > cur { - result = Result::Match(at - 2); - } - } else if next_si & STATE_START > 0 { - // A start state isn't in the common case because we may - // what to do quick prefix scanning. If the program doesn't - // have a detected prefix, then start states are actually - // considered common and this case is never reached. - debug_assert!(self.has_prefix()); - next_si &= !STATE_START; - prev_si = next_si; - at = match self.prefix_at(text, at) { - None => return Result::NoMatch(text.len()), - Some(i) => i, - }; - } else if next_si >= STATE_UNKNOWN { - if next_si == STATE_QUIT { - return Result::Quit; - } - // Finally, this corresponds to the case where the transition - // entered a state that can never lead to a match or a state - // that hasn't been computed yet. The latter being the "slow" - // path. - let byte = Byte::byte(text[at - 1]); - // We no longer care about the special bits in the state - // pointer. - prev_si &= STATE_MAX; - // Record where we are. This is used to track progress for - // determining whether we should quit if we've flushed the - // cache too much. - self.at = at; - next_si = match self.next_state(qcur, qnext, prev_si, byte) { - None => return Result::Quit, - Some(STATE_DEAD) => return result.set_non_match(at), - Some(si) => si, - }; - debug_assert!(next_si != STATE_UNKNOWN); - if next_si & STATE_MATCH > 0 { - next_si &= !STATE_MATCH; - result = Result::Match(at - 1); - if self.quit_after_match { - return result; - } - self.last_match_si = next_si; - } - prev_si = next_si; - } else { - prev_si = next_si; - } - } - - // Run the DFA once more on the special EOF senitnel value. - // We don't care about the special bits in the state pointer any more, - // so get rid of them. - prev_si &= STATE_MAX; - prev_si = match self.next_state(qcur, qnext, prev_si, Byte::eof()) { - None => return Result::Quit, - Some(STATE_DEAD) => return result.set_non_match(text.len()), - Some(si) => si & !STATE_START, - }; - debug_assert!(prev_si != STATE_UNKNOWN); - if prev_si & STATE_MATCH > 0 { - prev_si &= !STATE_MATCH; - self.last_match_si = prev_si; - result = Result::Match(text.len()); - } - result - } - - /// Executes the DFA on a reverse NFA. - #[inline(always)] // reduces constant overhead - fn exec_at_reverse( - &mut self, - qcur: &mut SparseSet, - qnext: &mut SparseSet, - text: &[u8], - ) -> Result<usize> { - // The comments in `exec_at` above mostly apply here too. The main - // difference is that we move backwards over the input and we look for - // the longest possible match instead of the leftmost-first match. - // - // N.B. The code duplication here is regrettable. Efforts to improve - // it without sacrificing performance are welcome. ---AG - debug_assert!(self.prog.is_reverse); - let mut result = Result::NoMatch(self.at); - let (mut prev_si, mut next_si) = (self.start, self.start); - let mut at = self.at; - while at > 0 { - while next_si <= STATE_MAX && at > 0 { - // Argument for safety is in the definition of next_si. - at -= 1; - prev_si = unsafe { self.next_si(next_si, text, at) }; - if prev_si > STATE_MAX || at <= 4 { - mem::swap(&mut prev_si, &mut next_si); - break; - } - at -= 1; - next_si = unsafe { self.next_si(prev_si, text, at) }; - if next_si > STATE_MAX { - break; - } - at -= 1; - prev_si = unsafe { self.next_si(next_si, text, at) }; - if prev_si > STATE_MAX { - mem::swap(&mut prev_si, &mut next_si); - break; - } - at -= 1; - next_si = unsafe { self.next_si(prev_si, text, at) }; - } - if next_si & STATE_MATCH > 0 { - next_si &= !STATE_MATCH; - result = Result::Match(at + 1); - if self.quit_after_match { - return result - } - self.last_match_si = next_si; - prev_si = next_si; - let cur = at; - while (next_si & !STATE_MATCH) == prev_si && at >= 2 { - // Argument for safety is in the definition of next_si. - at -= 1; - next_si = unsafe { - self.next_si(next_si & !STATE_MATCH, text, at) - }; - } - if at < cur { - result = Result::Match(at + 2); - } - } else if next_si >= STATE_UNKNOWN { - if next_si == STATE_QUIT { - return Result::Quit; - } - let byte = Byte::byte(text[at]); - prev_si &= STATE_MAX; - self.at = at; - next_si = match self.next_state(qcur, qnext, prev_si, byte) { - None => return Result::Quit, - Some(STATE_DEAD) => return result.set_non_match(at), - Some(si) => si, - }; - debug_assert!(next_si != STATE_UNKNOWN); - if next_si & STATE_MATCH > 0 { - next_si &= !STATE_MATCH; - result = Result::Match(at + 1); - if self.quit_after_match { - return result; - } - self.last_match_si = next_si; - } - prev_si = next_si; - } else { - prev_si = next_si; - } - } - - // Run the DFA once more on the special EOF senitnel value. - prev_si = match self.next_state(qcur, qnext, prev_si, Byte::eof()) { - None => return Result::Quit, - Some(STATE_DEAD) => return result.set_non_match(0), - Some(si) => si, - }; - debug_assert!(prev_si != STATE_UNKNOWN); - if prev_si & STATE_MATCH > 0 { - prev_si &= !STATE_MATCH; - self.last_match_si = prev_si; - result = Result::Match(0); - } - result - } - - /// next_si transitions to the next state, where the transition input - /// corresponds to text[i]. - /// - /// This elides bounds checks, and is therefore unsafe. - #[inline(always)] - unsafe fn next_si(&self, si: StatePtr, text: &[u8], i: usize) -> StatePtr { - // What is the argument for safety here? - // We have three unchecked accesses that could possibly violate safety: - // - // 1. The given byte of input (`text[i]`). - // 2. The class of the byte of input (`classes[text[i]]`). - // 3. The transition for the class (`trans[si + cls]`). - // - // (1) is only safe when calling next_si is guarded by - // `i < text.len()`. - // - // (2) is the easiest case to guarantee since `text[i]` is always a - // `u8` and `self.prog.byte_classes` always has length `u8::MAX`. - // (See `ByteClassSet.byte_classes` in `compile.rs`.) - // - // (3) is only safe if (1)+(2) are safe. Namely, the transitions - // of every state are defined to have length equal to the number of - // byte classes in the program. Therefore, a valid class leads to a - // valid transition. (All possible transitions are valid lookups, even - // if it points to a state that hasn't been computed yet.) (3) also - // relies on `si` being correct, but StatePtrs should only ever be - // retrieved from the transition table, which ensures they are correct. - debug_assert!(i < text.len()); - let b = *text.get_unchecked(i); - debug_assert!((b as usize) < self.prog.byte_classes.len()); - let cls = *self.prog.byte_classes.get_unchecked(b as usize); - self.cache.trans.next_unchecked(si, cls as usize) - } - - /// Computes the next state given the current state and the current input - /// byte (which may be EOF). - /// - /// If STATE_DEAD is returned, then there is no valid state transition. - /// This implies that no permutation of future input can lead to a match - /// state. - /// - /// STATE_UNKNOWN can never be returned. - fn exec_byte( - &mut self, - qcur: &mut SparseSet, - qnext: &mut SparseSet, - mut si: StatePtr, - b: Byte, - ) -> Option<StatePtr> { - use prog::Inst::*; - - // Initialize a queue with the current DFA state's NFA states. - qcur.clear(); - for ip in self.state(si).inst_ptrs() { - qcur.insert(ip); - } - - // Before inspecting the current byte, we may need to also inspect - // whether the position immediately preceding the current byte - // satisfies the empty assertions found in the current state. - // - // We only need to do this step if there are any empty assertions in - // the current state. - let is_word_last = self.state(si).flags().is_word(); - let is_word = b.is_ascii_word(); - if self.state(si).flags().has_empty() { - // Compute the flags immediately preceding the current byte. - // This means we only care about the "end" or "end line" flags. - // (The "start" flags are computed immediately proceding the - // current byte and is handled below.) - let mut flags = EmptyFlags::default(); - if b.is_eof() { - flags.end = true; - flags.end_line = true; - } else if b.as_byte().map_or(false, |b| b == b'\n') { - flags.end_line = true; - } - if is_word_last == is_word { - flags.not_word_boundary = true; - } else { - flags.word_boundary = true; - } - // Now follow epsilon transitions from every NFA state, but make - // sure we only follow transitions that satisfy our flags. - qnext.clear(); - for &ip in &*qcur { - self.follow_epsilons(usize_to_u32(ip), qnext, flags); - } - mem::swap(qcur, qnext); - } - - // Now we set flags for immediately after the current byte. Since start - // states are processed separately, and are the only states that can - // have the StartText flag set, we therefore only need to worry about - // the StartLine flag here. - // - // We do also keep track of whether this DFA state contains a NFA state - // that is a matching state. This is precisely how we delay the DFA - // matching by one byte in order to process the special EOF sentinel - // byte. Namely, if this DFA state containing a matching NFA state, - // then it is the *next* DFA state that is marked as a match. - let mut empty_flags = EmptyFlags::default(); - let mut state_flags = StateFlags::default(); - empty_flags.start_line = b.as_byte().map_or(false, |b| b == b'\n'); - if b.is_ascii_word() { - state_flags.set_word(); - } - // Now follow all epsilon transitions again, but only after consuming - // the current byte. - qnext.clear(); - for &ip in &*qcur { - match self.prog[ip as usize] { - // These states never happen in a byte-based program. - Char(_) | Ranges(_) => unreachable!(), - // These states are handled when following epsilon transitions. - Save(_) | Split(_) | EmptyLook(_) => {} - Match(_) => { - state_flags.set_match(); - if !self.continue_past_first_match() { - break; - } else if self.prog.matches.len() > 1 - && !qnext.contains(ip as usize) { - // If we are continuing on to find other matches, - // then keep a record of the match states we've seen. - qnext.insert(ip); - } - } - Bytes(ref inst) => { - if b.as_byte().map_or(false, |b| inst.matches(b)) { - self.follow_epsilons( - inst.goto as InstPtr, qnext, empty_flags); - } - } - } - } - - let cache = - if b.is_eof() && self.prog.matches.len() > 1 { - // If we're processing the last byte of the input and we're - // matching a regex set, then make the next state contain the - // previous states transitions. We do this so that the main - // matching loop can extract all of the match instructions. - mem::swap(qcur, qnext); - // And don't cache this state because it's totally bunk. - false - } else { - true - }; - - // We've now built up the set of NFA states that ought to comprise the - // next DFA state, so try to find it in the cache, and if it doesn't - // exist, cache it. - // - // N.B. We pass `&mut si` here because the cache may clear itself if - // it has gotten too full. When that happens, the location of the - // current state may change. - let mut next = match self.cached_state( - qnext, - state_flags, - Some(&mut si), - ) { - None => return None, - Some(next) => next, - }; - if (self.start & !STATE_START) == next { - // Start states can never be match states since all matches are - // delayed by one byte. - debug_assert!(!self.state(next).flags().is_match()); - next = self.start_ptr(next); - } - if next <= STATE_MAX && self.state(next).flags().is_match() { - next |= STATE_MATCH; - } - debug_assert!(next != STATE_UNKNOWN); - // And now store our state in the current state's next list. - if cache { - let cls = self.byte_class(b); - self.cache.trans.set_next(si, cls, next); - } - Some(next) - } - - /// Follows the epsilon transitions starting at (and including) `ip`. The - /// resulting states are inserted into the ordered set `q`. - /// - /// Conditional epsilon transitions (i.e., empty width assertions) are only - /// followed if they are satisfied by the given flags, which should - /// represent the flags set at the current location in the input. - /// - /// If the current location corresponds to the empty string, then only the - /// end line and/or end text flags may be set. If the current location - /// corresponds to a real byte in the input, then only the start line - /// and/or start text flags may be set. - /// - /// As an exception to the above, when finding the initial state, any of - /// the above flags may be set: - /// - /// If matching starts at the beginning of the input, then start text and - /// start line should be set. If the input is empty, then end text and end - /// line should also be set. - /// - /// If matching starts after the beginning of the input, then only start - /// line should be set if the preceding byte is `\n`. End line should never - /// be set in this case. (Even if the proceding byte is a `\n`, it will - /// be handled in a subsequent DFA state.) - fn follow_epsilons( - &mut self, - ip: InstPtr, - q: &mut SparseSet, - flags: EmptyFlags, - ) { - use prog::Inst::*; - use prog::EmptyLook::*; - - // We need to traverse the NFA to follow epsilon transitions, so avoid - // recursion with an explicit stack. - self.cache.stack.push(ip); - while let Some(ip) = self.cache.stack.pop() { - // Don't visit states we've already added. - if q.contains(ip as usize) { - continue; - } - q.insert(ip as usize); - match self.prog[ip as usize] { - Char(_) | Ranges(_) => unreachable!(), - Match(_) | Bytes(_) => {} - EmptyLook(ref inst) => { - // Only follow empty assertion states if our flags satisfy - // the assertion. - match inst.look { - StartLine if flags.start_line => { - self.cache.stack.push(inst.goto as InstPtr); - } - EndLine if flags.end_line => { - self.cache.stack.push(inst.goto as InstPtr); - } - StartText if flags.start => { - self.cache.stack.push(inst.goto as InstPtr); - } - EndText if flags.end => { - self.cache.stack.push(inst.goto as InstPtr); - } - WordBoundaryAscii if flags.word_boundary => { - self.cache.stack.push(inst.goto as InstPtr); - } - NotWordBoundaryAscii if flags.not_word_boundary => { - self.cache.stack.push(inst.goto as InstPtr); - } - WordBoundary if flags.word_boundary => { - self.cache.stack.push(inst.goto as InstPtr); - } - NotWordBoundary if flags.not_word_boundary => { - self.cache.stack.push(inst.goto as InstPtr); - } - StartLine | EndLine | StartText | EndText - | WordBoundaryAscii | NotWordBoundaryAscii - | WordBoundary | NotWordBoundary => {} - } - } - Save(ref inst) => self.cache.stack.push(inst.goto as InstPtr), - Split(ref inst) => { - self.cache.stack.push(inst.goto2 as InstPtr); - self.cache.stack.push(inst.goto1 as InstPtr); - } - } - } - } - - /// Find a previously computed state matching the given set of instructions - /// and is_match bool. - /// - /// The given set of instructions should represent a single state in the - /// NFA along with all states reachable without consuming any input. - /// - /// The is_match bool should be true if and only if the preceding DFA state - /// contains an NFA matching state. The cached state produced here will - /// then signify a match. (This enables us to delay a match by one byte, - /// in order to account for the EOF sentinel byte.) - /// - /// If the cache is full, then it is wiped before caching a new state. - /// - /// The current state should be specified if it exists, since it will need - /// to be preserved if the cache clears itself. (Start states are - /// always saved, so they should not be passed here.) It takes a mutable - /// pointer to the index because if the cache is cleared, the state's - /// location may change. - fn cached_state( - &mut self, - q: &SparseSet, - mut state_flags: StateFlags, - current_state: Option<&mut StatePtr>, - ) -> Option<StatePtr> { - // If we couldn't come up with a non-empty key to represent this state, - // then it is dead and can never lead to a match. - // - // Note that inst_flags represent the set of empty width assertions - // in q. We use this as an optimization in exec_byte to determine when - // we should follow epsilon transitions at the empty string preceding - // the current byte. - let key = match self.cached_state_key(q, &mut state_flags) { - None => return Some(STATE_DEAD), - Some(v) => v, - }; - // In the cache? Cool. Done. - if let Some(&si) = self.cache.compiled.get(&key) { - return Some(si); - } - // If the cache has gotten too big, wipe it. - if self.approximate_size() > self.prog.dfa_size_limit - && !self.clear_cache_and_save(current_state) - { - // Ooops. DFA is giving up. - return None; - } - // Allocate room for our state and add it. - self.add_state(key) - } - - /// Produces a key suitable for describing a state in the DFA cache. - /// - /// The key invariant here is that equivalent keys are produced for any two - /// sets of ordered NFA states (and toggling of whether the previous NFA - /// states contain a match state) that do not discriminate a match for any - /// input. - /// - /// Specifically, q should be an ordered set of NFA states and is_match - /// should be true if and only if the previous NFA states contained a match - /// state. - fn cached_state_key( - &mut self, - q: &SparseSet, - state_flags: &mut StateFlags, - ) -> Option<State> { - use prog::Inst::*; - - // We need to build up enough information to recognize pre-built states - // in the DFA. Generally speaking, this includes every instruction - // except for those which are purely epsilon transitions, e.g., the - // Save and Split instructions. - // - // Empty width assertions are also epsilon transitions, but since they - // are conditional, we need to make them part of a state's key in the - // cache. - - // Reserve 1 byte for flags. - let mut insts = vec![0]; - let mut prev = 0; - for &ip in q { - let ip = usize_to_u32(ip); - match self.prog[ip as usize] { - Char(_) | Ranges(_) => unreachable!(), - Save(_) | Split(_) => {} - Bytes(_) => push_inst_ptr(&mut insts, &mut prev, ip), - EmptyLook(_) => { - state_flags.set_empty(); - push_inst_ptr(&mut insts, &mut prev, ip) - } - Match(_) => { - push_inst_ptr(&mut insts, &mut prev, ip); - if !self.continue_past_first_match() { - break; - } - } - } - } - // If we couldn't transition to any other instructions and we didn't - // see a match when expanding NFA states previously, then this is a - // dead state and no amount of additional input can transition out - // of this state. - if insts.len() == 1 && !state_flags.is_match() { - None - } else { - let StateFlags(f) = *state_flags; - insts[0] = f; - Some(State { data: insts.into_boxed_slice() }) - } - } - - /// Clears the cache, but saves and restores current_state if it is not - /// none. - /// - /// The current state must be provided here in case its location in the - /// cache changes. - /// - /// This returns false if the cache is not cleared and the DFA should - /// give up. - fn clear_cache_and_save( - &mut self, - current_state: Option<&mut StatePtr>, - ) -> bool { - if self.cache.states.is_empty() { - // Nothing to clear... - return true; - } - match current_state { - None => self.clear_cache(), - Some(si) => { - let cur = self.state(*si).clone(); - if !self.clear_cache() { - return false; - } - // The unwrap is OK because we just cleared the cache and - // therefore know that the next state pointer won't exceed - // STATE_MAX. - *si = self.restore_state(cur).unwrap(); - true - } - } - } - - /// Wipes the state cache, but saves and restores the current start state. - /// - /// This returns false if the cache is not cleared and the DFA should - /// give up. - fn clear_cache(&mut self) -> bool { - // Bail out of the DFA if we're moving too "slowly." - // A heuristic from RE2: assume the DFA is too slow if it is processing - // 10 or fewer bytes per state. - // Additionally, we permit the cache to be flushed a few times before - // caling it quits. - let nstates = self.cache.states.len(); - if self.cache.flush_count >= 3 - && self.at >= self.last_cache_flush - && (self.at - self.last_cache_flush) <= 10 * nstates { - return false; - } - // Update statistics tracking cache flushes. - self.last_cache_flush = self.at; - self.cache.flush_count += 1; - - // OK, actually flush the cache. - let start = self.state(self.start & !STATE_START).clone(); - let last_match = if self.last_match_si <= STATE_MAX { - Some(self.state(self.last_match_si).clone()) - } else { - None - }; - self.cache.reset_size(); - self.cache.trans.clear(); - self.cache.states.clear(); - self.cache.compiled.clear(); - for s in &mut self.cache.start_states { - *s = STATE_UNKNOWN; - } - // The unwraps are OK because we just cleared the cache and therefore - // know that the next state pointer won't exceed STATE_MAX. - let start_ptr = self.restore_state(start).unwrap(); - self.start = self.start_ptr(start_ptr); - if let Some(last_match) = last_match { - self.last_match_si = self.restore_state(last_match).unwrap(); - } - true - } - - /// Restores the given state back into the cache, and returns a pointer - /// to it. - fn restore_state(&mut self, state: State) -> Option<StatePtr> { - // If we've already stored this state, just return a pointer to it. - // None will be the wiser. - if let Some(&si) = self.cache.compiled.get(&state) { - return Some(si); - } - self.add_state(state) - } - - /// Returns the next state given the current state si and current byte - /// b. {qcur,qnext} are used as scratch space for storing ordered NFA - /// states. - /// - /// This tries to fetch the next state from the cache, but if that fails, - /// it computes the next state, caches it and returns a pointer to it. - /// - /// The pointer can be to a real state, or it can be STATE_DEAD. - /// STATE_UNKNOWN cannot be returned. - /// - /// None is returned if a new state could not be allocated (i.e., the DFA - /// ran out of space and thinks it's running too slowly). - fn next_state( - &mut self, - qcur: &mut SparseSet, - qnext: &mut SparseSet, - si: StatePtr, - b: Byte, - ) -> Option<StatePtr> { - if si == STATE_DEAD { - return Some(STATE_DEAD); - } - match self.cache.trans.next(si, self.byte_class(b)) { - STATE_UNKNOWN => self.exec_byte(qcur, qnext, si, b), - STATE_QUIT => None, - STATE_DEAD => Some(STATE_DEAD), - nsi => Some(nsi), - } - } - - /// Computes and returns the start state, where searching begins at - /// position `at` in `text`. If the state has already been computed, - /// then it is pulled from the cache. If the state hasn't been cached, - /// then it is computed, cached and a pointer to it is returned. - /// - /// This may return STATE_DEAD but never STATE_UNKNOWN. - #[inline(always)] // reduces constant overhead - fn start_state( - &mut self, - q: &mut SparseSet, - empty_flags: EmptyFlags, - state_flags: StateFlags, - ) -> Option<StatePtr> { - // Compute an index into our cache of start states based on the set - // of empty/state flags set at the current position in the input. We - // don't use every flag since not all flags matter. For example, since - // matches are delayed by one byte, start states can never be match - // states. - let flagi = { - (((empty_flags.start as u8) << 0) | - ((empty_flags.end as u8) << 1) | - ((empty_flags.start_line as u8) << 2) | - ((empty_flags.end_line as u8) << 3) | - ((empty_flags.word_boundary as u8) << 4) | - ((empty_flags.not_word_boundary as u8) << 5) | - ((state_flags.is_word() as u8) << 6)) - as usize - }; - match self.cache.start_states[flagi] { - STATE_UNKNOWN => {} - STATE_DEAD => return Some(STATE_DEAD), - si => return Some(si), - } - q.clear(); - let start = usize_to_u32(self.prog.start); - self.follow_epsilons(start, q, empty_flags); - // Start states can never be match states because we delay every match - // by one byte. Given an empty string and an empty match, the match - // won't actually occur until the DFA processes the special EOF - // sentinel byte. - let sp = match self.cached_state(q, state_flags, None) { - None => return None, - Some(sp) => self.start_ptr(sp), - }; - self.cache.start_states[flagi] = sp; - Some(sp) - } - - /// Computes the set of starting flags for the given position in text. - /// - /// This should only be used when executing the DFA forwards over the - /// input. - fn start_flags(&self, text: &[u8], at: usize) -> (EmptyFlags, StateFlags) { - let mut empty_flags = EmptyFlags::default(); - let mut state_flags = StateFlags::default(); - empty_flags.start = at == 0; - empty_flags.end = text.is_empty(); - empty_flags.start_line = at == 0 || text[at - 1] == b'\n'; - empty_flags.end_line = text.is_empty(); - - let is_word_last = at > 0 && Byte::byte(text[at - 1]).is_ascii_word(); - let is_word = at < text.len() && Byte::byte(text[at]).is_ascii_word(); - if is_word_last { - state_flags.set_word(); - } - if is_word == is_word_last { - empty_flags.not_word_boundary = true; - } else { - empty_flags.word_boundary = true; - } - (empty_flags, state_flags) - } - - /// Computes the set of starting flags for the given position in text. - /// - /// This should only be used when executing the DFA in reverse over the - /// input. - fn start_flags_reverse( - &self, - text: &[u8], - at: usize, - ) -> (EmptyFlags, StateFlags) { - let mut empty_flags = EmptyFlags::default(); - let mut state_flags = StateFlags::default(); - empty_flags.start = at == text.len(); - empty_flags.end = text.is_empty(); - empty_flags.start_line = at == text.len() || text[at] == b'\n'; - empty_flags.end_line = text.is_empty(); - - let is_word_last = - at < text.len() && Byte::byte(text[at]).is_ascii_word(); - let is_word = at > 0 && Byte::byte(text[at - 1]).is_ascii_word(); - if is_word_last { - state_flags.set_word(); - } - if is_word == is_word_last { - empty_flags.not_word_boundary = true; - } else { - empty_flags.word_boundary = true; - } - (empty_flags, state_flags) - } - - /// Returns a reference to a State given a pointer to it. - fn state(&self, si: StatePtr) -> &State { - &self.cache.states[si as usize / self.num_byte_classes()] - } - - /// Adds the given state to the DFA. - /// - /// This allocates room for transitions out of this state in - /// self.cache.trans. The transitions can be set with the returned - /// StatePtr. - /// - /// If None is returned, then the state limit was reached and the DFA - /// should quit. - fn add_state(&mut self, state: State) -> Option<StatePtr> { - // This will fail if the next state pointer exceeds STATE_PTR. In - // practice, the cache limit will prevent us from ever getting here, - // but maybe callers will set the cache size to something ridiculous... - let si = match self.cache.trans.add() { - None => return None, - Some(si) => si, - }; - // If the program has a Unicode word boundary, then set any transitions - // for non-ASCII bytes to STATE_QUIT. If the DFA stumbles over such a - // transition, then it will quit and an alternative matching engine - // will take over. - if self.prog.has_unicode_word_boundary { - for b in 128..256 { - let cls = self.byte_class(Byte::byte(b as u8)); - self.cache.trans.set_next(si, cls, STATE_QUIT); - } - } - // Finally, put our actual state on to our heap of states and index it - // so we can find it later. - self.cache.size += - self.cache.trans.state_heap_size() - + (2 * state.data.len()) - + (2 * mem::size_of::<State>()) - + mem::size_of::<StatePtr>(); - self.cache.states.push(state.clone()); - self.cache.compiled.insert(state, si); - // Transition table and set of states and map should all be in sync. - debug_assert!(self.cache.states.len() - == self.cache.trans.num_states()); - debug_assert!(self.cache.states.len() - == self.cache.compiled.len()); - Some(si) - } - - /// Quickly finds the next occurrence of any literal prefixes in the regex. - /// If there are no literal prefixes, then the current position is - /// returned. If there are literal prefixes and one could not be found, - /// then None is returned. - /// - /// This should only be called when the DFA is in a start state. - fn prefix_at(&self, text: &[u8], at: usize) -> Option<usize> { - self.prog.prefixes.find(&text[at..]).map(|(s, _)| at + s) - } - - /// Returns the number of byte classes required to discriminate transitions - /// in each state. - /// - /// invariant: num_byte_classes() == len(State.next) - fn num_byte_classes(&self) -> usize { - // We add 1 to account for the special EOF byte. - (self.prog.byte_classes[255] as usize + 1) + 1 - } - - /// Given an input byte or the special EOF sentinel, return its - /// corresponding byte class. - #[inline(always)] - fn byte_class(&self, b: Byte) -> usize { - match b.as_byte() { - None => self.num_byte_classes() - 1, - Some(b) => self.u8_class(b), - } - } - - /// Like byte_class, but explicitly for u8s. - #[inline(always)] - fn u8_class(&self, b: u8) -> usize { - self.prog.byte_classes[b as usize] as usize - } - - /// Returns true if the DFA should continue searching past the first match. - /// - /// Leftmost first semantics in the DFA are preserved by not following NFA - /// transitions after the first match is seen. - /// - /// On occasion, we want to avoid leftmost first semantics to find either - /// the longest match (for reverse search) or all possible matches (for - /// regex sets). - fn continue_past_first_match(&self) -> bool { - self.prog.is_reverse || self.prog.matches.len() > 1 - } - - /// Returns true if there is a prefix we can quickly search for. - fn has_prefix(&self) -> bool { - !self.prog.is_reverse - && !self.prog.prefixes.is_empty() - && !self.prog.is_anchored_start - } - - /// Sets the STATE_START bit in the given state pointer if and only if - /// we have a prefix to scan for. - /// - /// If there's no prefix, then it's a waste to treat the start state - /// specially. - fn start_ptr(&self, si: StatePtr) -> StatePtr { - if self.has_prefix() { - si | STATE_START - } else { - si - } - } - - /// Approximate size returns the approximate heap space currently used by - /// the DFA. It is used to determine whether the DFA's state cache needs to - /// be wiped. Namely, it is possible that for certain regexes on certain - /// inputs, a new state could be created for every byte of input. (This is - /// bad for memory use, so we bound it with a cache.) - fn approximate_size(&self) -> usize { - self.cache.size + self.prog.approximate_size() - } -} - -impl Transitions { - /// Create a new transition table. - /// - /// The number of byte classes corresponds to the stride. Every state will - /// have `num_byte_classes` slots for transitions. - fn new(num_byte_classes: usize) -> Transitions { - Transitions { - table: vec![], - num_byte_classes: num_byte_classes, - } - } - - /// Returns the total number of states currently in this table. - fn num_states(&self) -> usize { - self.table.len() / self.num_byte_classes - } - - /// Allocates room for one additional state and returns a pointer to it. - /// - /// If there's no more room, None is returned. - fn add(&mut self) -> Option<StatePtr> { - let si = self.table.len(); - if si > STATE_MAX as usize { - return None; - } - self.table.extend(repeat(STATE_UNKNOWN).take(self.num_byte_classes)); - Some(usize_to_u32(si)) - } - - /// Clears the table of all states. - fn clear(&mut self) { - self.table.clear(); - } - - /// Sets the transition from (si, cls) to next. - fn set_next(&mut self, si: StatePtr, cls: usize, next: StatePtr) { - self.table[si as usize + cls] = next; - } - - /// Returns the transition corresponding to (si, cls). - fn next(&self, si: StatePtr, cls: usize) -> StatePtr { - self.table[si as usize + cls] - } - - /// The heap size, in bytes, of a single state in the transition table. - fn state_heap_size(&self) -> usize { - self.num_byte_classes * mem::size_of::<StatePtr>() - } - - /// Like `next`, but uses unchecked access and is therefore unsafe. - unsafe fn next_unchecked(&self, si: StatePtr, cls: usize) -> StatePtr { - debug_assert!((si as usize) < self.table.len()); - debug_assert!(cls < self.num_byte_classes); - *self.table.get_unchecked(si as usize + cls) - } -} - -impl StateFlags { - fn is_match(&self) -> bool { - self.0 & 0b0000000_1 > 0 - } - - fn set_match(&mut self) { - self.0 |= 0b0000000_1; - } - - fn is_word(&self) -> bool { - self.0 & 0b000000_1_0 > 0 - } - - fn set_word(&mut self) { - self.0 |= 0b000000_1_0; - } - - fn has_empty(&self) -> bool { - self.0 & 0b00000_1_00 > 0 - } - - fn set_empty(&mut self) { - self.0 |= 0b00000_1_00; - } -} - -impl Byte { - fn byte(b: u8) -> Self { Byte(b as u16) } - fn eof() -> Self { Byte(256) } - fn is_eof(&self) -> bool { self.0 == 256 } - - fn is_ascii_word(&self) -> bool { - let b = match self.as_byte() { - None => return false, - Some(b) => b, - }; - match b { - b'A'...b'Z' | b'a'...b'z' | b'0'...b'9' | b'_' => true, - _ => false, - } - } - - fn as_byte(&self) -> Option<u8> { - if self.is_eof() { - None - } else { - Some(self.0 as u8) - } - } -} - -impl fmt::Debug for State { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let ips: Vec<usize> = self.inst_ptrs().collect(); - f.debug_struct("State") - .field("flags", &self.flags()) - .field("insts", &ips) - .finish() - } -} - -impl fmt::Debug for Transitions { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut fmtd = f.debug_map(); - for si in 0..self.num_states() { - let s = si * self.num_byte_classes; - let e = s + self.num_byte_classes; - fmtd.entry(&si.to_string(), &TransitionsRow(&self.table[s..e])); - } - fmtd.finish() - } -} - -struct TransitionsRow<'a>(&'a [StatePtr]); - -impl<'a> fmt::Debug for TransitionsRow<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut fmtd = f.debug_map(); - for (b, si) in self.0.iter().enumerate() { - match *si { - STATE_UNKNOWN => {} - STATE_DEAD => { - fmtd.entry(&vb(b as usize), &"DEAD"); - } - si => { - fmtd.entry(&vb(b as usize), &si.to_string()); - } - } - } - fmtd.finish() - } -} - -impl fmt::Debug for StateFlags { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("StateFlags") - .field("is_match", &self.is_match()) - .field("is_word", &self.is_word()) - .field("has_empty", &self.has_empty()) - .finish() - } -} - -/// Helper function for formatting a byte as a nice-to-read escaped string. -fn vb(b: usize) -> String { - use std::ascii::escape_default; - - if b > ::std::u8::MAX as usize { - "EOF".to_owned() - } else { - let escaped = escape_default(b as u8).collect::<Vec<u8>>(); - String::from_utf8_lossy(&escaped).into_owned() - } -} - -fn usize_to_u32(n: usize) -> u32 { - if (n as u64) > (::std::u32::MAX as u64) { - panic!("BUG: {} is too big to fit into u32", n) - } - n as u32 -} - -#[allow(dead_code)] // useful for debugging -fn show_state_ptr(si: StatePtr) -> String { - let mut s = format!("{:?}", si & STATE_MAX); - if si == STATE_UNKNOWN { - s = format!("{} (unknown)", s); - } - if si == STATE_DEAD { - s = format!("{} (dead)", s); - } - if si == STATE_QUIT { - s = format!("{} (quit)", s); - } - if si & STATE_START > 0 { - s = format!("{} (start)", s); - } - if si & STATE_MATCH > 0 { - s = format!("{} (match)", s); - } - s -} - -/// https://developers.google.com/protocol-buffers/docs/encoding#varints -fn write_vari32(data: &mut Vec<u8>, n: i32) { - let mut un = (n as u32) << 1; - if n < 0 { - un = !un; - } - write_varu32(data, un) -} - -/// https://developers.google.com/protocol-buffers/docs/encoding#varints -fn read_vari32(data: &[u8]) -> (i32, usize) { - let (un, i) = read_varu32(data); - let mut n = (un >> 1) as i32; - if un & 1 != 0 { - n = !n; - } - (n, i) -} - -/// https://developers.google.com/protocol-buffers/docs/encoding#varints -fn write_varu32(data: &mut Vec<u8>, mut n: u32) { - while n >= 0b1000_0000 { - data.push((n as u8) | 0b1000_0000); - n >>= 7; - } - data.push(n as u8); -} - -/// https://developers.google.com/protocol-buffers/docs/encoding#varints -fn read_varu32(data: &[u8]) -> (u32, usize) { - let mut n: u32 = 0; - let mut shift: u32 = 0; - for (i, &b) in data.iter().enumerate() { - if b < 0b1000_0000 { - return (n | ((b as u32) << shift), i + 1); - } - n |= ((b as u32) & 0b0111_1111) << shift; - shift += 7; - } - (0, 0) -} - -#[cfg(test)] -mod tests { - extern crate rand; - - use quickcheck::{QuickCheck, StdGen, quickcheck}; - use super::{ - StateFlags, State, push_inst_ptr, - write_varu32, read_varu32, write_vari32, read_vari32, - }; - - #[test] - fn prop_state_encode_decode() { - fn p(ips: Vec<u32>, flags: u8) -> bool { - let mut data = vec![flags]; - let mut prev = 0; - for &ip in ips.iter() { - push_inst_ptr(&mut data, &mut prev, ip); - } - let state = State { data: data.into_boxed_slice() }; - - let expected: Vec<usize> = - ips.into_iter().map(|ip| ip as usize).collect(); - let got: Vec<usize> = state.inst_ptrs().collect(); - expected == got && state.flags() == StateFlags(flags) - } - QuickCheck::new() - .gen(StdGen::new(self::rand::thread_rng(), 10_000)) - .quickcheck(p as fn(Vec<u32>, u8) -> bool); - } - - #[test] - fn prop_read_write_u32() { - fn p(n: u32) -> bool { - let mut buf = vec![]; - write_varu32(&mut buf, n); - let (got, nread) = read_varu32(&buf); - nread == buf.len() && got == n - } - quickcheck(p as fn(u32) -> bool); - } - - #[test] - fn prop_read_write_i32() { - fn p(n: i32) -> bool { - let mut buf = vec![]; - write_vari32(&mut buf, n); - let (got, nread) = read_vari32(&buf); - nread == buf.len() && got == n - } - quickcheck(p as fn(i32) -> bool); - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/error.rs cargo-0.26.0/vendor/regex-0.2.6/src/error.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/error.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/error.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,63 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::fmt; - -use syntax; - -/// An error that occurred during parsing or compiling a regular expression. -#[derive(Clone, Debug, PartialEq)] -pub enum Error { - /// A syntax error. - Syntax(String), - /// The compiled program exceeded the set size limit. - /// The argument is the size limit imposed. - CompiledTooBig(usize), - /// Hints that destructuring should not be exhaustive. - /// - /// This enum may grow additional variants, so this makes sure clients - /// don't count on exhaustive matching. (Otherwise, adding a new variant - /// could break existing code.) - #[doc(hidden)] - __Nonexhaustive, -} - -impl ::std::error::Error for Error { - fn description(&self) -> &str { - match *self { - Error::Syntax(ref err) => err, - Error::CompiledTooBig(_) => "compiled program too big", - Error::__Nonexhaustive => unreachable!(), - } - } - - fn cause(&self) -> Option<&::std::error::Error> { - None - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Error::Syntax(ref err) => err.fmt(f), - Error::CompiledTooBig(limit) => { - write!(f, "Compiled regex exceeds size limit of {} bytes.", - limit) - } - Error::__Nonexhaustive => unreachable!(), - } - } -} - -impl From<syntax::Error> for Error { - fn from(err: syntax::Error) -> Error { - Error::Syntax(err.to_string()) - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/exec.rs cargo-0.26.0/vendor/regex-0.2.6/src/exec.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/exec.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/exec.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1279 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::cell::RefCell; -use std::collections::HashMap; -use std::cmp; -use std::sync::Arc; - -use thread_local::CachedThreadLocal; -use syntax::{Expr, ExprBuilder, Literals}; - -use backtrack; -use compile::Compiler; -use dfa; -use error::Error; -use input::{ByteInput, CharInput}; -use literals::LiteralSearcher; -use pikevm; -use prog::Program; -use re_builder::RegexOptions; -use re_bytes; -use re_set; -use re_trait::{RegularExpression, Slot, Locations, as_slots}; -use re_unicode; -use utf8::next_utf8; - -/// `Exec` manages the execution of a regular expression. -/// -/// In particular, this manages the various compiled forms of a single regular -/// expression and the choice of which matching engine to use to execute a -/// regular expression. -pub struct Exec { - /// All read only state. - ro: Arc<ExecReadOnly>, - /// Caches for the various matching engines. - cache: CachedThreadLocal<ProgramCache>, -} - -/// `ExecNoSync` is like `Exec`, except it embeds a reference to a cache. This -/// means it is no longer Sync, but we can now avoid the overhead of -/// synchronization to fetch the cache. -#[derive(Debug)] -pub struct ExecNoSync<'c> { - /// All read only state. - ro: &'c Arc<ExecReadOnly>, - /// Caches for the various matching engines. - cache: &'c ProgramCache, -} - -/// `ExecNoSyncStr` is like `ExecNoSync`, but matches on &str instead of &[u8]. -pub struct ExecNoSyncStr<'c>(ExecNoSync<'c>); - -/// `ExecReadOnly` comprises all read only state for a regex. Namely, all such -/// state is determined at compile time and never changes during search. -#[derive(Debug)] -struct ExecReadOnly { - /// The original regular expressions given by the caller to compile. - res: Vec<String>, - /// A compiled program that is used in the NFA simulation and backtracking. - /// It can be byte-based or Unicode codepoint based. - /// - /// N.B. It is not possibly to make this byte-based from the public API. - /// It is only used for testing byte based programs in the NFA simulations. - nfa: Program, - /// A compiled byte based program for DFA execution. This is only used - /// if a DFA can be executed. (Currently, only word boundary assertions are - /// not supported.) Note that this program contains an embedded `.*?` - /// preceding the first capture group, unless the regex is anchored at the - /// beginning. - dfa: Program, - /// The same as above, except the program is reversed (and there is no - /// preceding `.*?`). This is used by the DFA to find the starting location - /// of matches. - dfa_reverse: Program, - /// A set of suffix literals extracted from the regex. - /// - /// Prefix literals are stored on the `Program`, since they are used inside - /// the matching engines. - suffixes: LiteralSearcher, - /// match_type encodes as much upfront knowledge about how we're going to - /// execute a search as possible. - match_type: MatchType, -} - -/// Facilitates the construction of an executor by exposing various knobs -/// to control how a regex is executed and what kinds of resources it's -/// permitted to use. -pub struct ExecBuilder { - options: RegexOptions, - match_type: Option<MatchType>, - bytes: bool, - only_utf8: bool, -} - -/// Parsed represents a set of parsed regular expressions and their detected -/// literals. -struct Parsed { - exprs: Vec<Expr>, - prefixes: Literals, - suffixes: Literals, - bytes: bool, -} - -impl ExecBuilder { - /// Create a regex execution builder. - /// - /// This uses default settings for everything except the regex itself, - /// which must be provided. Further knobs can be set by calling methods, - /// and then finally, `build` to actually create the executor. - pub fn new(re: &str) -> Self { - Self::new_many(&[re]) - } - - /// Like new, but compiles the union of the given regular expressions. - /// - /// Note that when compiling 2 or more regular expressions, capture groups - /// are completely unsupported. (This means both `find` and `captures` - /// wont work.) - pub fn new_many<I, S>(res: I) -> Self - where S: AsRef<str>, I: IntoIterator<Item=S> { - let mut opts = RegexOptions::default(); - opts.pats = res.into_iter().map(|s| s.as_ref().to_owned()).collect(); - Self::new_options(opts) - } - - /// Create a regex execution builder. - pub fn new_options(opts: RegexOptions) -> Self { - ExecBuilder { - options: opts, - match_type: None, - bytes: false, - only_utf8: true, - } - } - - /// Set the matching engine to be automatically determined. - /// - /// This is the default state and will apply whatever optimizations are - /// possible, such as running a DFA. - /// - /// This overrides whatever was previously set via the `nfa` or - /// `bounded_backtracking` methods. - pub fn automatic(mut self) -> Self { - self.match_type = None; - self - } - - /// Sets the matching engine to use the NFA algorithm no matter what - /// optimizations are possible. - /// - /// This overrides whatever was previously set via the `automatic` or - /// `bounded_backtracking` methods. - pub fn nfa(mut self) -> Self { - self.match_type = Some(MatchType::Nfa(MatchNfaType::PikeVM)); - self - } - - /// Sets the matching engine to use a bounded backtracking engine no - /// matter what optimizations are possible. - /// - /// One must use this with care, since the bounded backtracking engine - /// uses memory proportion to `len(regex) * len(text)`. - /// - /// This overrides whatever was previously set via the `automatic` or - /// `nfa` methods. - pub fn bounded_backtracking(mut self) -> Self { - self.match_type = Some(MatchType::Nfa(MatchNfaType::Backtrack)); - self - } - - /// Compiles byte based programs for use with the NFA matching engines. - /// - /// By default, the NFA engines match on Unicode scalar values. They can - /// be made to use byte based programs instead. In general, the byte based - /// programs are slower because of a less efficient encoding of character - /// classes. - /// - /// Note that this does not impact DFA matching engines, which always - /// execute on bytes. - pub fn bytes(mut self, yes: bool) -> Self { - self.bytes = yes; - self - } - - /// When disabled, the program compiled may match arbitrary bytes. - /// - /// When enabled (the default), all compiled programs exclusively match - /// valid UTF-8 bytes. - pub fn only_utf8(mut self, yes: bool) -> Self { - self.only_utf8 = yes; - self - } - - /// Set the Unicode flag. - pub fn unicode(mut self, yes: bool) -> Self { - self.options.unicode = yes; - self - } - - /// Parse the current set of patterns into their AST and extract literals. - fn parse(&self) -> Result<Parsed, Error> { - let mut exprs = Vec::with_capacity(self.options.pats.len()); - let mut prefixes = Some(Literals::empty()); - let mut suffixes = Some(Literals::empty()); - let mut bytes = false; - let is_set = self.options.pats.len() > 1; - // If we're compiling a regex set and that set has any anchored - // expressions, then disable all literal optimizations. - for pat in &self.options.pats { - let parser = - ExprBuilder::new() - .case_insensitive(self.options.case_insensitive) - .multi_line(self.options.multi_line) - .dot_matches_new_line(self.options.dot_matches_new_line) - .swap_greed(self.options.swap_greed) - .ignore_whitespace(self.options.ignore_whitespace) - .unicode(self.options.unicode) - .allow_bytes(!self.only_utf8); - let expr = try!(parser.parse(pat)); - bytes = bytes || expr.has_bytes(); - - if !expr.is_anchored_start() && expr.has_anchored_start() { - // Partial anchors unfortunately make it hard to use prefixes, - // so disable them. - prefixes = None; - } else if is_set && expr.is_anchored_start() { - // Regex sets with anchors do not go well with literal - // optimizations. - prefixes = None; - } - prefixes = prefixes.and_then(|mut prefixes| { - if !prefixes.union_prefixes(&expr) { - None - } else { - Some(prefixes) - } - }); - - if !expr.is_anchored_end() && expr.has_anchored_end() { - // Partial anchors unfortunately make it hard to use suffixes, - // so disable them. - suffixes = None; - } else if is_set && expr.is_anchored_end() { - // Regex sets with anchors do not go well with literal - // optimizations. - prefixes = None; - } - suffixes = suffixes.and_then(|mut suffixes| { - if !suffixes.union_suffixes(&expr) { - None - } else { - Some(suffixes) - } - }); - exprs.push(expr); - } - Ok(Parsed { - exprs: exprs, - prefixes: prefixes.unwrap_or_else(Literals::empty), - suffixes: suffixes.unwrap_or_else(Literals::empty), - bytes: bytes, - }) - } - - /// Build an executor that can run a regular expression. - pub fn build(self) -> Result<Exec, Error> { - // Special case when we have no patterns to compile. - // This can happen when compiling a regex set. - if self.options.pats.is_empty() { - let ro = Arc::new(ExecReadOnly { - res: vec![], - nfa: Program::new(), - dfa: Program::new(), - dfa_reverse: Program::new(), - suffixes: LiteralSearcher::empty(), - match_type: MatchType::Nothing, - }); - return Ok(Exec { ro: ro, cache: CachedThreadLocal::new() }); - } - let parsed = try!(self.parse()); - let mut nfa = try!( - Compiler::new() - .size_limit(self.options.size_limit) - .bytes(self.bytes || parsed.bytes) - .only_utf8(self.only_utf8) - .compile(&parsed.exprs)); - let mut dfa = try!( - Compiler::new() - .size_limit(self.options.size_limit) - .dfa(true) - .only_utf8(self.only_utf8) - .compile(&parsed.exprs)); - let mut dfa_reverse = try!( - Compiler::new() - .size_limit(self.options.size_limit) - .dfa(true) - .only_utf8(self.only_utf8) - .reverse(true) - .compile(&parsed.exprs)); - - let prefixes = parsed.prefixes.unambiguous_prefixes(); - let suffixes = parsed.suffixes.unambiguous_suffixes(); - nfa.prefixes = LiteralSearcher::prefixes(prefixes); - dfa.prefixes = nfa.prefixes.clone(); - dfa.dfa_size_limit = self.options.dfa_size_limit; - dfa_reverse.dfa_size_limit = self.options.dfa_size_limit; - - let mut ro = ExecReadOnly { - res: self.options.pats, - nfa: nfa, - dfa: dfa, - dfa_reverse: dfa_reverse, - suffixes: LiteralSearcher::suffixes(suffixes), - match_type: MatchType::Nothing, - }; - ro.match_type = ro.choose_match_type(self.match_type); - - let ro = Arc::new(ro); - Ok(Exec { ro: ro, cache: CachedThreadLocal::new() }) - } -} - -impl<'c> RegularExpression for ExecNoSyncStr<'c> { - type Text = str; - - fn slots_len(&self) -> usize { self.0.slots_len() } - - fn next_after_empty(&self, text: &str, i: usize) -> usize { - next_utf8(text.as_bytes(), i) - } - - #[inline(always)] // reduces constant overhead - fn shortest_match_at(&self, text: &str, start: usize) -> Option<usize> { - self.0.shortest_match_at(text.as_bytes(), start) - } - - #[inline(always)] // reduces constant overhead - fn is_match_at(&self, text: &str, start: usize) -> bool { - self.0.is_match_at(text.as_bytes(), start) - } - - #[inline(always)] // reduces constant overhead - fn find_at(&self, text: &str, start: usize) -> Option<(usize, usize)> { - self.0.find_at(text.as_bytes(), start) - } - - #[inline(always)] // reduces constant overhead - fn read_captures_at( - &self, - locs: &mut Locations, - text: &str, - start: usize, - ) -> Option<(usize, usize)> { - self.0.read_captures_at(locs, text.as_bytes(), start) - } -} - -impl<'c> RegularExpression for ExecNoSync<'c> { - type Text = [u8]; - - /// Returns the number of capture slots in the regular expression. (There - /// are two slots for every capture group, corresponding to possibly empty - /// start and end locations of the capture.) - fn slots_len(&self) -> usize { - self.ro.nfa.captures.len() * 2 - } - - fn next_after_empty(&self, _text: &[u8], i: usize) -> usize { - i + 1 - } - - /// Returns the end of a match location, possibly occurring before the - /// end location of the correct leftmost-first match. - #[inline(always)] // reduces constant overhead - fn shortest_match_at(&self, text: &[u8], start: usize) -> Option<usize> { - if !self.is_anchor_end_match(text) { - return None; - } - match self.ro.match_type { - MatchType::Literal(ty) => { - self.find_literals(ty, text, start).map(|(_, e)| e) - } - MatchType::Dfa | MatchType::DfaMany => { - match self.shortest_dfa(text, start) { - dfa::Result::Match(end) => Some(end), - dfa::Result::NoMatch(_) => None, - dfa::Result::Quit => self.shortest_nfa(text, start), - } - } - MatchType::DfaAnchoredReverse => { - match dfa::Fsm::reverse( - &self.ro.dfa_reverse, - self.cache, - true, - &text[start..], - text.len(), - ) { - dfa::Result::Match(_) => Some(text.len()), - dfa::Result::NoMatch(_) => None, - dfa::Result::Quit => self.shortest_nfa(text, start), - } - } - MatchType::DfaSuffix => { - match self.shortest_dfa_reverse_suffix(text, start) { - dfa::Result::Match(e) => Some(e), - dfa::Result::NoMatch(_) => None, - dfa::Result::Quit => self.shortest_nfa(text, start), - } - } - MatchType::Nfa(ty) => self.shortest_nfa_type(ty, text, start), - MatchType::Nothing => None, - } - } - - /// Returns true if and only if the regex matches text. - /// - /// For single regular expressions, this is equivalent to calling - /// shortest_match(...).is_some(). - #[inline(always)] // reduces constant overhead - fn is_match_at(&self, text: &[u8], start: usize) -> bool { - if !self.is_anchor_end_match(text) { - return false; - } - // We need to do this dance because shortest_match relies on the NFA - // filling in captures[1], but a RegexSet has no captures. In other - // words, a RegexSet can't (currently) use shortest_match. ---AG - match self.ro.match_type { - MatchType::Literal(ty) => { - self.find_literals(ty, text, start).is_some() - } - MatchType::Dfa | MatchType::DfaMany => { - match self.shortest_dfa(text, start) { - dfa::Result::Match(_) => true, - dfa::Result::NoMatch(_) => false, - dfa::Result::Quit => self.match_nfa(text, start), - } - } - MatchType::DfaAnchoredReverse => { - match dfa::Fsm::reverse( - &self.ro.dfa_reverse, - self.cache, - true, - &text[start..], - text.len(), - ) { - dfa::Result::Match(_) => true, - dfa::Result::NoMatch(_) => false, - dfa::Result::Quit => self.match_nfa(text, start), - } - } - MatchType::DfaSuffix => { - match self.shortest_dfa_reverse_suffix(text, start) { - dfa::Result::Match(_) => true, - dfa::Result::NoMatch(_) => false, - dfa::Result::Quit => self.match_nfa(text, start), - } - } - MatchType::Nfa(ty) => self.match_nfa_type(ty, text, start), - MatchType::Nothing => false, - } - } - - /// Finds the start and end location of the leftmost-first match, starting - /// at the given location. - #[inline(always)] // reduces constant overhead - fn find_at(&self, text: &[u8], start: usize) -> Option<(usize, usize)> { - if !self.is_anchor_end_match(text) { - return None; - } - match self.ro.match_type { - MatchType::Literal(ty) => { - self.find_literals(ty, text, start) - } - MatchType::Dfa => { - match self.find_dfa_forward(text, start) { - dfa::Result::Match((s, e)) => Some((s, e)), - dfa::Result::NoMatch(_) => None, - dfa::Result::Quit => { - self.find_nfa(MatchNfaType::Auto, text, start) - } - } - } - MatchType::DfaAnchoredReverse => { - match self.find_dfa_anchored_reverse(text, start) { - dfa::Result::Match((s, e)) => Some((s, e)), - dfa::Result::NoMatch(_) => None, - dfa::Result::Quit => { - self.find_nfa(MatchNfaType::Auto, text, start) - } - } - } - MatchType::DfaSuffix => { - match self.find_dfa_reverse_suffix(text, start) { - dfa::Result::Match((s, e)) => Some((s, e)), - dfa::Result::NoMatch(_) => None, - dfa::Result::Quit => { - self.find_nfa(MatchNfaType::Auto, text, start) - } - } - } - MatchType::Nfa(ty) => self.find_nfa(ty, text, start), - MatchType::Nothing => None, - MatchType::DfaMany => { - unreachable!("BUG: RegexSet cannot be used with find") - } - } - } - - /// Finds the start and end location of the leftmost-first match and also - /// fills in all matching capture groups. - /// - /// The number of capture slots given should be equal to the total number - /// of capture slots in the compiled program. - /// - /// Note that the first two slots always correspond to the start and end - /// locations of the overall match. - fn read_captures_at( - &self, - locs: &mut Locations, - text: &[u8], - start: usize, - ) -> Option<(usize, usize)> { - let slots = as_slots(locs); - for slot in slots.iter_mut() { - *slot = None; - } - // If the caller unnecessarily uses this, then we try to save them - // from themselves. - match slots.len() { - 0 => return self.find_at(text, start), - 2 => { - return self.find_at(text, start).map(|(s, e)| { - slots[0] = Some(s); - slots[1] = Some(e); - (s, e) - }); - } - _ => {} // fallthrough - } - if !self.is_anchor_end_match(text) { - return None; - } - match self.ro.match_type { - MatchType::Literal(ty) => { - self.find_literals(ty, text, start).and_then(|(s, e)| { - self.captures_nfa_with_match(slots, text, s, e) - }) - } - MatchType::Dfa => { - if self.ro.nfa.is_anchored_start { - self.captures_nfa(slots, text, start) - } else { - match self.find_dfa_forward(text, start) { - dfa::Result::Match((s, e)) => { - self.captures_nfa_with_match(slots, text, s, e) - } - dfa::Result::NoMatch(_) => None, - dfa::Result::Quit => self.captures_nfa(slots, text, start), - } - } - } - MatchType::DfaAnchoredReverse => { - match self.find_dfa_anchored_reverse(text, start) { - dfa::Result::Match((s, e)) => { - self.captures_nfa_with_match(slots, text, s, e) - } - dfa::Result::NoMatch(_) => None, - dfa::Result::Quit => self.captures_nfa(slots, text, start), - } - } - MatchType::DfaSuffix => { - match self.find_dfa_reverse_suffix(text, start) { - dfa::Result::Match((s, e)) => { - self.captures_nfa_with_match(slots, text, s, e) - } - dfa::Result::NoMatch(_) => None, - dfa::Result::Quit => self.captures_nfa(slots, text, start), - } - } - MatchType::Nfa(ty) => { - self.captures_nfa_type(ty, slots, text, start) - } - MatchType::Nothing => None, - MatchType::DfaMany => { - unreachable!("BUG: RegexSet cannot be used with captures") - } - } - } -} - -impl<'c> ExecNoSync<'c> { - /// Finds the leftmost-first match using only literal search. - #[inline(always)] // reduces constant overhead - fn find_literals( - &self, - ty: MatchLiteralType, - text: &[u8], - start: usize, - ) -> Option<(usize, usize)> { - use self::MatchLiteralType::*; - match ty { - Unanchored => { - let lits = &self.ro.nfa.prefixes; - lits.find(&text[start..]) - .map(|(s, e)| (start + s, start + e)) - } - AnchoredStart => { - let lits = &self.ro.nfa.prefixes; - lits.find_start(&text[start..]) - .map(|(s, e)| (start + s, start + e)) - } - AnchoredEnd => { - let lits = &self.ro.suffixes; - lits.find_end(&text[start..]) - .map(|(s, e)| (start + s, start + e)) - } - } - } - - /// Finds the leftmost-first match (start and end) using only the DFA. - /// - /// If the result returned indicates that the DFA quit, then another - /// matching engine should be used. - #[inline(always)] // reduces constant overhead - fn find_dfa_forward( - &self, - text: &[u8], - start: usize, - ) -> dfa::Result<(usize, usize)> { - use dfa::Result::*; - let end = match dfa::Fsm::forward( - &self.ro.dfa, - self.cache, - false, - text, - start, - ) { - NoMatch(i) => return NoMatch(i), - Quit => return Quit, - Match(end) if start == end => return Match((start, start)), - Match(end) => end, - }; - // Now run the DFA in reverse to find the start of the match. - match dfa::Fsm::reverse( - &self.ro.dfa_reverse, - self.cache, - false, - &text[start..], - end - start, - ) { - Match(s) => Match((start + s, end)), - NoMatch(i) => NoMatch(i), - Quit => Quit, - } - } - - /// Finds the leftmost-first match (start and end) using only the DFA, - /// but assumes the regex is anchored at the end and therefore starts at - /// the end of the regex and matches in reverse. - /// - /// If the result returned indicates that the DFA quit, then another - /// matching engine should be used. - #[inline(always)] // reduces constant overhead - fn find_dfa_anchored_reverse( - &self, - text: &[u8], - start: usize, - ) -> dfa::Result<(usize, usize)> { - use dfa::Result::*; - match dfa::Fsm::reverse( - &self.ro.dfa_reverse, - self.cache, - false, - &text[start..], - text.len() - start, - ) { - Match(s) => Match((start + s, text.len())), - NoMatch(i) => NoMatch(i), - Quit => Quit, - } - } - - /// Finds the end of the shortest match using only the DFA. - #[inline(always)] // reduces constant overhead - fn shortest_dfa(&self, text: &[u8], start: usize) -> dfa::Result<usize> { - dfa::Fsm::forward(&self.ro.dfa, self.cache, true, text, start) - } - - /// Finds the end of the shortest match using only the DFA by scanning for - /// suffix literals. - /// - #[inline(always)] // reduces constant overhead - fn shortest_dfa_reverse_suffix( - &self, - text: &[u8], - start: usize, - ) -> dfa::Result<usize> { - match self.exec_dfa_reverse_suffix(text, start) { - None => self.shortest_dfa(text, start), - Some(r) => r.map(|(_, end)| end), - } - } - - /// Finds the end of the shortest match using only the DFA by scanning for - /// suffix literals. It also reports the start of the match. - /// - /// Note that if None is returned, then the optimization gave up to avoid - /// worst case quadratic behavior. A forward scanning DFA should be tried - /// next. - /// - /// If a match is returned and the full leftmost-first match is desired, - /// then a forward scan starting from the beginning of the match must be - /// done. - /// - /// If the result returned indicates that the DFA quit, then another - /// matching engine should be used. - #[inline(always)] // reduces constant overhead - fn exec_dfa_reverse_suffix( - &self, - text: &[u8], - original_start: usize, - ) -> Option<dfa::Result<(usize, usize)>> { - use dfa::Result::*; - - let lcs = self.ro.suffixes.lcs(); - debug_assert!(lcs.len() >= 1); - let mut start = original_start; - let mut end = start; - while end <= text.len() { - start = end; - end += match lcs.find(&text[end..]) { - None => return Some(NoMatch(text.len())), - Some(start) => start + lcs.len(), - }; - match dfa::Fsm::reverse( - &self.ro.dfa_reverse, - self.cache, - false, - &text[start..end], - end - start, - ) { - Match(0) | NoMatch(0) => return None, - Match(s) => return Some(Match((s + start, end))), - NoMatch(_) => continue, - Quit => return Some(Quit), - }; - } - Some(NoMatch(text.len())) - } - - /// Finds the leftmost-first match (start and end) using only the DFA - /// by scanning for suffix literals. - /// - /// If the result returned indicates that the DFA quit, then another - /// matching engine should be used. - #[inline(always)] // reduces constant overhead - fn find_dfa_reverse_suffix( - &self, - text: &[u8], - start: usize, - ) -> dfa::Result<(usize, usize)> { - use dfa::Result::*; - - let match_start = match self.exec_dfa_reverse_suffix(text, start) { - None => return self.find_dfa_forward(text, start), - Some(Match((start, _))) => start, - Some(r) => return r, - }; - // At this point, we've found a match. The only way to quit now - // without a match is if the DFA gives up (seems unlikely). - // - // Now run the DFA forwards to find the proper end of the match. - // (The suffix literal match can only indicate the earliest - // possible end location, which may appear before the end of the - // leftmost-first match.) - match dfa::Fsm::forward( - &self.ro.dfa, - self.cache, - false, - text, - match_start, - ) { - NoMatch(_) => panic!("BUG: reverse match implies forward match"), - Quit => Quit, - Match(e) => Match((match_start, e)), - } - } - - /// Executes the NFA engine to return whether there is a match or not. - /// - /// Ideally, we could use shortest_nfa(...).is_some() and get the same - /// performance characteristics, but regex sets don't have captures, which - /// shortest_nfa depends on. - fn match_nfa( - &self, - text: &[u8], - start: usize, - ) -> bool { - self.match_nfa_type(MatchNfaType::Auto, text, start) - } - - /// Like match_nfa, but allows specification of the type of NFA engine. - fn match_nfa_type( - &self, - ty: MatchNfaType, - text: &[u8], - start: usize, - ) -> bool { - self.exec_nfa(ty, &mut [false], &mut [], true, text, start) - } - - /// Finds the shortest match using an NFA. - fn shortest_nfa(&self, text: &[u8], start: usize) -> Option<usize> { - self.shortest_nfa_type(MatchNfaType::Auto, text, start) - } - - /// Like shortest_nfa, but allows specification of the type of NFA engine. - fn shortest_nfa_type( - &self, - ty: MatchNfaType, - text: &[u8], - start: usize, - ) -> Option<usize> { - let mut slots = [None, None]; - if self.exec_nfa(ty, &mut [false], &mut slots, true, text, start) { - slots[1] - } else { - None - } - } - - /// Like find, but executes an NFA engine. - fn find_nfa( - &self, - ty: MatchNfaType, - text: &[u8], - start: usize, - ) -> Option<(usize, usize)> { - let mut slots = [None, None]; - if self.exec_nfa(ty, &mut [false], &mut slots, false, text, start) { - match (slots[0], slots[1]) { - (Some(s), Some(e)) => Some((s, e)), - _ => None, - } - } else { - None - } - } - - /// Like find_nfa, but fills in captures and restricts the search space - /// using previously found match information. - /// - /// `slots` should have length equal to `2 * nfa.captures.len()`. - fn captures_nfa_with_match( - &self, - slots: &mut [Slot], - text: &[u8], - match_start: usize, - match_end: usize, - ) -> Option<(usize, usize)> { - // We can't use match_end directly, because we may need to examine one - // "character" after the end of a match for lookahead operators. We - // need to move two characters beyond the end, since some look-around - // operations may falsely assume a premature end of text otherwise. - let e = cmp::min( - next_utf8(text, next_utf8(text, match_end)), text.len()); - self.captures_nfa(slots, &text[..e], match_start) - } - - /// Like find_nfa, but fills in captures. - /// - /// `slots` should have length equal to `2 * nfa.captures.len()`. - fn captures_nfa( - &self, - slots: &mut [Slot], - text: &[u8], - start: usize, - ) -> Option<(usize, usize)> { - self.captures_nfa_type(MatchNfaType::Auto, slots, text, start) - } - - /// Like captures_nfa, but allows specification of type of NFA engine. - fn captures_nfa_type( - &self, - ty: MatchNfaType, - slots: &mut [Slot], - text: &[u8], - start: usize, - ) -> Option<(usize, usize)> { - if self.exec_nfa(ty, &mut [false], slots, false, text, start) { - match (slots[0], slots[1]) { - (Some(s), Some(e)) => Some((s, e)), - _ => None, - } - } else { - None - } - } - - fn exec_nfa( - &self, - mut ty: MatchNfaType, - matches: &mut [bool], - slots: &mut [Slot], - quit_after_match: bool, - text: &[u8], - start: usize, - ) -> bool { - use self::MatchNfaType::*; - if let Auto = ty { - if backtrack::should_exec(self.ro.nfa.len(), text.len()) { - ty = Backtrack; - } else { - ty = PikeVM; - } - } - match ty { - Auto => unreachable!(), - Backtrack => self.exec_backtrack(matches, slots, text, start), - PikeVM => { - self.exec_pikevm( - matches, slots, quit_after_match, text, start) - } - } - } - - /// Always run the NFA algorithm. - fn exec_pikevm( - &self, - matches: &mut [bool], - slots: &mut [Slot], - quit_after_match: bool, - text: &[u8], - start: usize, - ) -> bool { - if self.ro.nfa.uses_bytes() { - pikevm::Fsm::exec( - &self.ro.nfa, - self.cache, - matches, - slots, - quit_after_match, - ByteInput::new(text, self.ro.nfa.only_utf8), - start) - } else { - pikevm::Fsm::exec( - &self.ro.nfa, - self.cache, - matches, - slots, - quit_after_match, - CharInput::new(text), - start) - } - } - - /// Always runs the NFA using bounded backtracking. - fn exec_backtrack( - &self, - matches: &mut [bool], - slots: &mut [Slot], - text: &[u8], - start: usize, - ) -> bool { - if self.ro.nfa.uses_bytes() { - backtrack::Bounded::exec( - &self.ro.nfa, - self.cache, - matches, - slots, - ByteInput::new(text, self.ro.nfa.only_utf8), - start) - } else { - backtrack::Bounded::exec( - &self.ro.nfa, - self.cache, - matches, - slots, - CharInput::new(text), - start) - } - } - - /// Finds which regular expressions match the given text. - /// - /// `matches` should have length equal to the number of regexes being - /// searched. - /// - /// This is only useful when one wants to know which regexes in a set - /// match some text. - pub fn many_matches_at( - &self, - matches: &mut [bool], - text: &[u8], - start: usize, - ) -> bool { - use self::MatchType::*; - if !self.is_anchor_end_match(text) { - return false; - } - match self.ro.match_type { - Literal(ty) => { - debug_assert_eq!(matches.len(), 1); - matches[0] = self.find_literals(ty, text, start).is_some(); - matches[0] - } - Dfa | DfaAnchoredReverse | DfaSuffix | DfaMany => { - match dfa::Fsm::forward_many( - &self.ro.dfa, - self.cache, - matches, - text, - start, - ) { - dfa::Result::Match(_) => true, - dfa::Result::NoMatch(_) => false, - dfa::Result::Quit => { - self.exec_nfa( - MatchNfaType::Auto, - matches, - &mut [], - false, - text, - start) - } - } - } - Nfa(ty) => self.exec_nfa(ty, matches, &mut [], false, text, start), - Nothing => false, - } - } - - #[inline(always)] // reduces constant overhead - fn is_anchor_end_match(&self, text: &[u8]) -> bool { - // Only do this check if the haystack is big (>1MB). - if text.len() > (1<<20) && self.ro.nfa.is_anchored_end { - let lcs = self.ro.suffixes.lcs(); - if lcs.len() >= 1 && !lcs.is_suffix(text) { - return false; - } - } - true - } - - pub fn capture_name_idx(&self) -> &Arc<HashMap<String, usize>> { - &self.ro.nfa.capture_name_idx - } -} - -impl<'c> ExecNoSyncStr<'c> { - pub fn capture_name_idx(&self) -> &Arc<HashMap<String, usize>> { - self.0.capture_name_idx() - } -} - -impl Exec { - /// Get a searcher that isn't Sync. - #[inline(always)] // reduces constant overhead - pub fn searcher(&self) -> ExecNoSync { - let create = || Box::new(RefCell::new(ProgramCacheInner::new(&self.ro))); - ExecNoSync { - ro: &self.ro, // a clone is too expensive here! (and not needed) - cache: self.cache.get_or(create), - } - } - - /// Get a searcher that isn't Sync and can match on &str. - #[inline(always)] // reduces constant overhead - pub fn searcher_str(&self) -> ExecNoSyncStr { - ExecNoSyncStr(self.searcher()) - } - - /// Build a Regex from this executor. - pub fn into_regex(self) -> re_unicode::Regex { - re_unicode::Regex::from(self) - } - - /// Build a RegexSet from this executor. - pub fn into_regex_set(self) -> re_set::unicode::RegexSet { - re_set::unicode::RegexSet::from(self) - } - - /// Build a Regex from this executor that can match arbitrary bytes. - pub fn into_byte_regex(self) -> re_bytes::Regex { - re_bytes::Regex::from(self) - } - - /// Build a RegexSet from this executor that can match arbitrary bytes. - pub fn into_byte_regex_set(self) -> re_set::bytes::RegexSet { - re_set::bytes::RegexSet::from(self) - } - - /// The original regular expressions given by the caller that were - /// compiled. - pub fn regex_strings(&self) -> &[String] { - &self.ro.res - } - - /// Return a slice of capture names. - /// - /// Any capture that isn't named is None. - pub fn capture_names(&self) -> &[Option<String>] { - &self.ro.nfa.captures - } - - /// Return a reference to named groups mapping (from group name to - /// group position). - pub fn capture_name_idx(&self) -> &Arc<HashMap<String, usize>> { - &self.ro.nfa.capture_name_idx - } -} - -impl Clone for Exec { - fn clone(&self) -> Exec { - Exec { - ro: self.ro.clone(), - cache: CachedThreadLocal::new(), - } - } -} - -impl ExecReadOnly { - fn choose_match_type(&self, hint: Option<MatchType>) -> MatchType { - use self::MatchType::*; - if let Some(Nfa(_)) = hint { - return hint.unwrap(); - } - // If the NFA is empty, then we'll never match anything. - if self.nfa.insts.is_empty() { - return Nothing; - } - // If our set of prefixes is complete, then we can use it to find - // a match in lieu of a regex engine. This doesn't quite work well in - // the presence of multiple regexes, so only do it when there's one. - // - // TODO(burntsushi): Also, don't try to match literals if the regex is - // partially anchored. We could technically do it, but we'd need to - // create two sets of literals: all of them and then the subset that - // aren't anchored. We would then only search for all of them when at - // the beginning of the input and use the subset in all other cases. - if self.res.len() == 1 { - if self.nfa.prefixes.complete() { - return if self.nfa.is_anchored_start { - Literal(MatchLiteralType::AnchoredStart) - } else { - Literal(MatchLiteralType::Unanchored) - }; - } - if self.suffixes.complete() { - return if self.nfa.is_anchored_end { - Literal(MatchLiteralType::AnchoredEnd) - } else { - // This case shouldn't happen. When the regex isn't - // anchored, then complete prefixes should imply complete - // suffixes. - Literal(MatchLiteralType::Unanchored) - }; - } - } - // If we can execute the DFA, then we totally should. - if dfa::can_exec(&self.dfa) { - // Regex sets require a slightly specialized path. - if self.res.len() >= 2 { - return DfaMany; - } - // If the regex is anchored at the end but not the start, then - // just match in reverse from the end of the haystack. - if !self.nfa.is_anchored_start && self.nfa.is_anchored_end { - return DfaAnchoredReverse; - } - // If there's a longish suffix literal, then it might be faster - // to look for that first. - if self.should_suffix_scan() { - return DfaSuffix; - } - // Fall back to your garden variety forward searching lazy DFA. - return Dfa; - } - // We're so totally hosed. - Nfa(MatchNfaType::Auto) - } - - /// Returns true if the program is amenable to suffix scanning. - /// - /// When this is true, as a heuristic, we assume it is OK to quickly scan - /// for suffix literals and then do a *reverse* DFA match from any matches - /// produced by the literal scan. (And then followed by a forward DFA - /// search, since the previously found suffix literal maybe not actually be - /// the end of a match.) - /// - /// This is a bit of a specialized optimization, but can result in pretty - /// big performance wins if 1) there are no prefix literals and 2) the - /// suffix literals are pretty rare in the text. (1) is obviously easy to - /// account for but (2) is harder. As a proxy, we assume that longer - /// strings are generally rarer, so we only enable this optimization when - /// we have a meaty suffix. - fn should_suffix_scan(&self) -> bool { - if self.suffixes.is_empty() { - return false; - } - let lcs_len = self.suffixes.lcs().char_len(); - lcs_len >= 3 && lcs_len > self.dfa.prefixes.lcp().char_len() - } -} - -#[derive(Clone, Copy, Debug)] -enum MatchType { - /// A single or multiple literal search. This is only used when the regex - /// can be decomposed into unambiguous literal search. - Literal(MatchLiteralType), - /// A normal DFA search. - Dfa, - /// A reverse DFA search starting from the end of a haystack. - DfaAnchoredReverse, - /// A reverse DFA search with suffix literal scanning. - DfaSuffix, - /// Use the DFA on two or more regular expressions. - DfaMany, - /// An NFA variant. - Nfa(MatchNfaType), - /// No match is ever possible, so don't ever try to search. - Nothing, -} - -#[derive(Clone, Copy, Debug)] -enum MatchLiteralType { - /// Match literals anywhere in text. - Unanchored, - /// Match literals only at the start of text. - AnchoredStart, - /// Match literals only at the end of text. - AnchoredEnd, -} - -#[derive(Clone, Copy, Debug)] -enum MatchNfaType { - /// Choose between Backtrack and PikeVM. - Auto, - /// NFA bounded backtracking. - /// - /// (This is only set by tests, since it never makes sense to always want - /// backtracking.) - Backtrack, - /// The Pike VM. - /// - /// (This is only set by tests, since it never makes sense to always want - /// the Pike VM.) - PikeVM, -} - -/// `ProgramCache` maintains reusable allocations for each matching engine -/// available to a particular program. -pub type ProgramCache = RefCell<ProgramCacheInner>; - -#[derive(Clone, Debug)] -pub struct ProgramCacheInner { - pub pikevm: pikevm::Cache, - pub backtrack: backtrack::Cache, - pub dfa: dfa::Cache, - pub dfa_reverse: dfa::Cache, -} - -impl ProgramCacheInner { - fn new(ro: &ExecReadOnly) -> Self { - ProgramCacheInner { - pikevm: pikevm::Cache::new(&ro.nfa), - backtrack: backtrack::Cache::new(&ro.nfa), - dfa: dfa::Cache::new(&ro.dfa), - dfa_reverse: dfa::Cache::new(&ro.dfa_reverse), - } - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/expand.rs cargo-0.26.0/vendor/regex-0.2.6/src/expand.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/expand.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/expand.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,215 +0,0 @@ -use std::str; - -use memchr::memchr; - -use re_bytes; -use re_unicode; - -pub fn expand_str( - caps: &re_unicode::Captures, - mut replacement: &str, - dst: &mut String, -) { - while !replacement.is_empty() { - match memchr(b'$', replacement.as_bytes()) { - None => break, - Some(i) => { - dst.push_str(&replacement[..i]); - replacement = &replacement[i..]; - } - } - if replacement.as_bytes().get(1).map_or(false, |&b| b == b'$') { - dst.push_str("$"); - replacement = &replacement[2..]; - continue; - } - debug_assert!(!replacement.is_empty()); - let cap_ref = match find_cap_ref(replacement) { - Some(cap_ref) => cap_ref, - None => { - dst.push_str("$"); - replacement = &replacement[1..]; - continue; - } - }; - replacement = &replacement[cap_ref.end..]; - match cap_ref.cap { - Ref::Number(i) => { - dst.push_str( - caps.get(i).map(|m| m.as_str()).unwrap_or("")); - } - Ref::Named(name) => { - dst.push_str( - caps.name(name).map(|m| m.as_str()).unwrap_or("")); - } - } - } - dst.push_str(replacement); -} - -pub fn expand_bytes( - caps: &re_bytes::Captures, - mut replacement: &[u8], - dst: &mut Vec<u8>, -) { - while !replacement.is_empty() { - match memchr(b'$', replacement) { - None => break, - Some(i) => { - dst.extend(&replacement[..i]); - replacement = &replacement[i..]; - } - } - if replacement.get(1).map_or(false, |&b| b == b'$') { - dst.push(b'$'); - replacement = &replacement[2..]; - continue; - } - debug_assert!(!replacement.is_empty()); - let cap_ref = match find_cap_ref(replacement) { - Some(cap_ref) => cap_ref, - None => { - dst.push(b'$'); - replacement = &replacement[1..]; - continue; - } - }; - replacement = &replacement[cap_ref.end..]; - match cap_ref.cap { - Ref::Number(i) => { - dst.extend( - caps.get(i).map(|m| m.as_bytes()).unwrap_or(b"")); - } - Ref::Named(name) => { - dst.extend( - caps.name(name).map(|m| m.as_bytes()).unwrap_or(b"")); - } - } - } - dst.extend(replacement); -} - -/// `CaptureRef` represents a reference to a capture group inside some text. -/// The reference is either a capture group name or a number. -/// -/// It is also tagged with the position in the text immediately proceding the -/// capture reference. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -struct CaptureRef<'a> { - cap: Ref<'a>, - end: usize, -} - -/// A reference to a capture group in some text. -/// -/// e.g., `$2`, `$foo`, `${foo}`. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -enum Ref<'a> { - Named(&'a str), - Number(usize), -} - -impl<'a> From<&'a str> for Ref<'a> { - fn from(x: &'a str) -> Ref<'a> { - Ref::Named(x) - } -} - -impl From<usize> for Ref<'static> { - fn from(x: usize) -> Ref<'static> { - Ref::Number(x) - } -} - -/// Parses a possible reference to a capture group name in the given text, -/// starting at the beginning of `replacement`. -/// -/// If no such valid reference could be found, None is returned. -fn find_cap_ref<T: ?Sized + AsRef<[u8]>>( - replacement: &T, -) -> Option<CaptureRef> { - let mut i = 0; - let rep: &[u8] = replacement.as_ref(); - if rep.len() <= 1 || rep[0] != b'$' { - return None; - } - let mut brace = false; - i += 1; - if rep[i] == b'{' { - brace = true; - i += 1; - } - let mut cap_end = i; - while rep.get(cap_end).map_or(false, is_valid_cap_letter) { - cap_end += 1; - } - if cap_end == i { - return None; - } - // We just verified that the range 0..cap_end is valid ASCII, so it must - // therefore be valid UTF-8. If we really cared, we could avoid this UTF-8 - // check with either unsafe or by parsing the number straight from &[u8]. - let cap = str::from_utf8(&rep[i..cap_end]) - .expect("valid UTF-8 capture name"); - if brace { - if !rep.get(cap_end).map_or(false, |&b| b == b'}') { - return None; - } - cap_end += 1; - } - Some(CaptureRef { - cap: match cap.parse::<u32>() { - Ok(i) => Ref::Number(i as usize), - Err(_) => Ref::Named(cap), - }, - end: cap_end, - }) -} - -/// Returns true if and only if the given byte is allowed in a capture name. -fn is_valid_cap_letter(b: &u8) -> bool { - match *b { - b'0' ... b'9' | b'a' ... b'z' | b'A' ... b'Z' | b'_' => true, - _ => false, - } -} - -#[cfg(test)] -mod tests { - use super::{CaptureRef, find_cap_ref}; - - macro_rules! find { - ($name:ident, $text:expr) => { - #[test] - fn $name() { - assert_eq!(None, find_cap_ref($text)); - } - }; - ($name:ident, $text:expr, $capref:expr) => { - #[test] - fn $name() { - assert_eq!(Some($capref), find_cap_ref($text)); - } - }; - } - - macro_rules! c { - ($name_or_number:expr, $pos:expr) => { - CaptureRef { cap: $name_or_number.into(), end: $pos } - }; - } - - find!(find_cap_ref1, "$foo", c!("foo", 4)); - find!(find_cap_ref2, "${foo}", c!("foo", 6)); - find!(find_cap_ref3, "$0", c!(0, 2)); - find!(find_cap_ref4, "$5", c!(5, 2)); - find!(find_cap_ref5, "$10", c!(10, 3)); - find!(find_cap_ref6, "$42a", c!("42a", 4)); - find!(find_cap_ref7, "${42}a", c!(42, 5)); - find!(find_cap_ref8, "${42"); - find!(find_cap_ref9, "${42 "); - find!(find_cap_ref10, " $0 "); - find!(find_cap_ref11, "$"); - find!(find_cap_ref12, " "); - find!(find_cap_ref13, ""); -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/freqs.rs cargo-0.26.0/vendor/regex-0.2.6/src/freqs.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/freqs.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/freqs.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,271 +0,0 @@ -// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// NOTE: The following code was generated by "scripts/frequencies.py", do not -// edit directly - -pub const BYTE_FREQUENCIES: [u8; 256] = [ - 55, // '\x00' - 52, // '\x01' - 51, // '\x02' - 50, // '\x03' - 49, // '\x04' - 48, // '\x05' - 47, // '\x06' - 46, // '\x07' - 45, // '\x08' - 103, // '\t' - 242, // '\n' - 66, // '\x0b' - 67, // '\x0c' - 229, // '\r' - 44, // '\x0e' - 43, // '\x0f' - 42, // '\x10' - 41, // '\x11' - 40, // '\x12' - 39, // '\x13' - 38, // '\x14' - 37, // '\x15' - 36, // '\x16' - 35, // '\x17' - 34, // '\x18' - 33, // '\x19' - 56, // '\x1a' - 32, // '\x1b' - 31, // '\x1c' - 30, // '\x1d' - 29, // '\x1e' - 28, // '\x1f' - 255, // ' ' - 148, // '!' - 164, // '"' - 149, // '#' - 136, // '$' - 160, // '%' - 155, // '&' - 173, // "'" - 221, // '(' - 222, // ')' - 134, // '*' - 122, // '+' - 232, // ',' - 202, // '-' - 215, // '.' - 224, // '/' - 208, // '0' - 220, // '1' - 204, // '2' - 187, // '3' - 183, // '4' - 179, // '5' - 177, // '6' - 168, // '7' - 178, // '8' - 200, // '9' - 226, // ':' - 195, // ';' - 154, // '<' - 184, // '=' - 174, // '>' - 126, // '?' - 120, // '@' - 191, // 'A' - 157, // 'B' - 194, // 'C' - 170, // 'D' - 189, // 'E' - 162, // 'F' - 161, // 'G' - 150, // 'H' - 193, // 'I' - 142, // 'J' - 137, // 'K' - 171, // 'L' - 176, // 'M' - 185, // 'N' - 167, // 'O' - 186, // 'P' - 112, // 'Q' - 175, // 'R' - 192, // 'S' - 188, // 'T' - 156, // 'U' - 140, // 'V' - 143, // 'W' - 123, // 'X' - 133, // 'Y' - 128, // 'Z' - 147, // '[' - 138, // '\\' - 146, // ']' - 114, // '^' - 223, // '_' - 151, // '`' - 249, // 'a' - 216, // 'b' - 238, // 'c' - 236, // 'd' - 253, // 'e' - 227, // 'f' - 218, // 'g' - 230, // 'h' - 247, // 'i' - 135, // 'j' - 180, // 'k' - 241, // 'l' - 233, // 'm' - 246, // 'n' - 244, // 'o' - 231, // 'p' - 139, // 'q' - 245, // 'r' - 243, // 's' - 251, // 't' - 235, // 'u' - 201, // 'v' - 196, // 'w' - 240, // 'x' - 214, // 'y' - 152, // 'z' - 182, // '{' - 205, // '|' - 181, // '}' - 127, // '~' - 27, // '\x7f' - 212, // '\x80' - 211, // '\x81' - 210, // '\x82' - 213, // '\x83' - 228, // '\x84' - 197, // '\x85' - 169, // '\x86' - 159, // '\x87' - 131, // '\x88' - 172, // '\x89' - 105, // '\x8a' - 80, // '\x8b' - 98, // '\x8c' - 96, // '\x8d' - 97, // '\x8e' - 81, // '\x8f' - 207, // '\x90' - 145, // '\x91' - 116, // '\x92' - 115, // '\x93' - 144, // '\x94' - 130, // '\x95' - 153, // '\x96' - 121, // '\x97' - 107, // '\x98' - 132, // '\x99' - 109, // '\x9a' - 110, // '\x9b' - 124, // '\x9c' - 111, // '\x9d' - 82, // '\x9e' - 108, // '\x9f' - 118, // '\xa0' - 141, // '¡' - 113, // '¢' - 129, // '£' - 119, // '¤' - 125, // '¥' - 165, // '¦' - 117, // '§' - 92, // '¨' - 106, // '©' - 83, // 'ª' - 72, // '«' - 99, // '¬' - 93, // '\xad' - 65, // '®' - 79, // '¯' - 166, // '°' - 237, // '±' - 163, // '²' - 199, // '³' - 190, // '´' - 225, // 'µ' - 209, // '¶' - 203, // '·' - 198, // '¸' - 217, // '¹' - 219, // 'º' - 206, // '»' - 234, // '¼' - 248, // '½' - 158, // '¾' - 239, // '¿' - 255, // 'À' - 255, // 'Á' - 255, // 'Â' - 255, // 'Ã' - 255, // 'Ä' - 255, // 'Å' - 255, // 'Æ' - 255, // 'Ç' - 255, // 'È' - 255, // 'É' - 255, // 'Ê' - 255, // 'Ë' - 255, // 'Ì' - 255, // 'Í' - 255, // 'Î' - 255, // 'Ï' - 255, // 'Ð' - 255, // 'Ñ' - 255, // 'Ò' - 255, // 'Ó' - 255, // 'Ô' - 255, // 'Õ' - 255, // 'Ö' - 255, // '×' - 255, // 'Ø' - 255, // 'Ù' - 255, // 'Ú' - 255, // 'Û' - 255, // 'Ü' - 255, // 'Ý' - 255, // 'Þ' - 255, // 'ß' - 255, // 'à' - 255, // 'á' - 255, // 'â' - 255, // 'ã' - 255, // 'ä' - 255, // 'å' - 255, // 'æ' - 255, // 'ç' - 255, // 'è' - 255, // 'é' - 255, // 'ê' - 255, // 'ë' - 255, // 'ì' - 255, // 'í' - 255, // 'î' - 255, // 'ï' - 255, // 'ð' - 255, // 'ñ' - 255, // 'ò' - 255, // 'ó' - 255, // 'ô' - 255, // 'õ' - 255, // 'ö' - 255, // '÷' - 255, // 'ø' - 255, // 'ù' - 255, // 'ú' - 255, // 'û' - 255, // 'ü' - 255, // 'ý' - 255, // 'þ' - 255, // 'ÿ' -]; diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/input.rs cargo-0.26.0/vendor/regex-0.2.6/src/input.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/input.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/input.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,420 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::char; -use std::cmp::Ordering; -use std::fmt; -use std::ops; -use std::u32; - -use syntax; - -use literals::LiteralSearcher; -use prog::InstEmptyLook; -use utf8::{decode_utf8, decode_last_utf8}; - -/// Represents a location in the input. -#[derive(Clone, Copy, Debug)] -pub struct InputAt { - pos: usize, - c: Char, - byte: Option<u8>, - len: usize, -} - -impl InputAt { - /// Returns true iff this position is at the beginning of the input. - pub fn is_start(&self) -> bool { - self.pos == 0 - } - - /// Returns true iff this position is past the end of the input. - pub fn is_end(&self) -> bool { - self.c.is_none() && self.byte.is_none() - } - - /// Returns the character at this position. - /// - /// If this position is just before or after the input, then an absent - /// character is returned. - pub fn char(&self) -> Char { - self.c - } - - /// Returns the byte at this position. - pub fn byte(&self) -> Option<u8> { - self.byte - } - - /// Returns the UTF-8 width of the character at this position. - pub fn len(&self) -> usize { - self.len - } - - /// Returns whether the UTF-8 width of the character at this position - /// is zero. - pub fn is_empty(&self) -> bool { - self.len == 0 - } - - /// Returns the byte offset of this position. - pub fn pos(&self) -> usize { - self.pos - } - - /// Returns the byte offset of the next position in the input. - pub fn next_pos(&self) -> usize { - self.pos + self.len - } -} - -/// An abstraction over input used in the matching engines. -pub trait Input { - /// Return an encoding of the position at byte offset `i`. - fn at(&self, i: usize) -> InputAt; - - /// Return the Unicode character occurring next to `at`. - /// - /// If no such character could be decoded, then `Char` is absent. - fn next_char(&self, at: InputAt) -> Char; - - /// Return the Unicode character occurring previous to `at`. - /// - /// If no such character could be decoded, then `Char` is absent. - fn previous_char(&self, at: InputAt) -> Char; - - /// Return true if the given empty width instruction matches at the - /// input position given. - fn is_empty_match(&self, at: InputAt, empty: &InstEmptyLook) -> bool; - - /// Scan the input for a matching prefix. - fn prefix_at( - &self, - prefixes: &LiteralSearcher, - at: InputAt, - ) -> Option<InputAt>; - - /// The number of bytes in the input. - fn len(&self) -> usize; - - /// Whether the input is empty. - fn is_empty(&self) -> bool { self.len() == 0 } - - /// Return the given input as a sequence of bytes. - fn as_bytes(&self) -> &[u8]; -} - -impl<'a, T: Input> Input for &'a T { - fn at(&self, i: usize) -> InputAt { (**self).at(i) } - - fn next_char(&self, at: InputAt) -> Char { (**self).next_char(at) } - - fn previous_char(&self, at: InputAt) -> Char { (**self).previous_char(at) } - - fn is_empty_match(&self, at: InputAt, empty: &InstEmptyLook) -> bool { - (**self).is_empty_match(at, empty) - } - - fn prefix_at( - &self, - prefixes: &LiteralSearcher, - at: InputAt, - ) -> Option<InputAt> { - (**self).prefix_at(prefixes, at) - } - - fn len(&self) -> usize { (**self).len() } - - fn as_bytes(&self) -> &[u8] { (**self).as_bytes() } -} - -/// An input reader over characters. -#[derive(Clone, Copy, Debug)] -pub struct CharInput<'t>(&'t [u8]); - -impl<'t> CharInput<'t> { - /// Return a new character input reader for the given string. - pub fn new(s: &'t [u8]) -> CharInput<'t> { - CharInput(s) - } -} - -impl<'t> ops::Deref for CharInput<'t> { - type Target = [u8]; - - fn deref(&self) -> &[u8] { - self.0 - } -} - -impl<'t> Input for CharInput<'t> { - fn at(&self, i: usize) -> InputAt { - let c = decode_utf8(&self[i..]).map(|(c, _)| c).into(); - InputAt { - pos: i, - c: c, - byte: None, - len: c.len_utf8(), - } - } - - fn next_char(&self, at: InputAt) -> Char { - at.char() - } - - fn previous_char(&self, at: InputAt) -> Char { - decode_last_utf8(&self[..at.pos()]).map(|(c, _)| c).into() - } - - fn is_empty_match(&self, at: InputAt, empty: &InstEmptyLook) -> bool { - use prog::EmptyLook::*; - match empty.look { - StartLine => { - let c = self.previous_char(at); - at.pos() == 0 || c == '\n' - } - EndLine => { - let c = self.next_char(at); - at.pos() == self.len() || c == '\n' - } - StartText => at.pos() == 0, - EndText => at.pos() == self.len(), - WordBoundary => { - let (c1, c2) = (self.previous_char(at), self.next_char(at)); - c1.is_word_char() != c2.is_word_char() - } - NotWordBoundary => { - let (c1, c2) = (self.previous_char(at), self.next_char(at)); - c1.is_word_char() == c2.is_word_char() - } - WordBoundaryAscii => { - let (c1, c2) = (self.previous_char(at), self.next_char(at)); - c1.is_word_byte() != c2.is_word_byte() - } - NotWordBoundaryAscii => { - let (c1, c2) = (self.previous_char(at), self.next_char(at)); - c1.is_word_byte() == c2.is_word_byte() - } - } - } - - fn prefix_at( - &self, - prefixes: &LiteralSearcher, - at: InputAt, - ) -> Option<InputAt> { - prefixes.find(&self[at.pos()..]).map(|(s, _)| self.at(at.pos() + s)) - } - - fn len(&self) -> usize { - self.0.len() - } - - fn as_bytes(&self) -> &[u8] { - self.0 - } -} - -/// An input reader over bytes. -#[derive(Clone, Copy, Debug)] -pub struct ByteInput<'t> { - text: &'t [u8], - only_utf8: bool, -} - -impl<'t> ByteInput<'t> { - /// Return a new byte-based input reader for the given string. - pub fn new(text: &'t [u8], only_utf8: bool) -> ByteInput<'t> { - ByteInput { - text: text, - only_utf8: only_utf8, - } - } -} - -impl<'t> ops::Deref for ByteInput<'t> { - type Target = [u8]; - - fn deref(&self) -> &[u8] { - self.text - } -} - -impl<'t> Input for ByteInput<'t> { - fn at(&self, i: usize) -> InputAt { - InputAt { - pos: i, - c: None.into(), - byte: self.get(i).cloned(), - len: 1, - } - } - - fn next_char(&self, at: InputAt) -> Char { - decode_utf8(&self[at.pos()..]).map(|(c, _)| c).into() - } - - fn previous_char(&self, at: InputAt) -> Char { - decode_last_utf8(&self[..at.pos()]).map(|(c, _)| c).into() - } - - fn is_empty_match(&self, at: InputAt, empty: &InstEmptyLook) -> bool { - use prog::EmptyLook::*; - match empty.look { - StartLine => { - let c = self.previous_char(at); - at.pos() == 0 || c == '\n' - } - EndLine => { - let c = self.next_char(at); - at.pos() == self.len() || c == '\n' - } - StartText => at.pos() == 0, - EndText => at.pos() == self.len(), - WordBoundary => { - let (c1, c2) = (self.previous_char(at), self.next_char(at)); - c1.is_word_char() != c2.is_word_char() - } - NotWordBoundary => { - let (c1, c2) = (self.previous_char(at), self.next_char(at)); - c1.is_word_char() == c2.is_word_char() - } - WordBoundaryAscii => { - let (c1, c2) = (self.previous_char(at), self.next_char(at)); - if self.only_utf8 { - // If we must match UTF-8, then we can't match word - // boundaries at invalid UTF-8. - if c1.is_none() && !at.is_start() { - return false; - } - if c2.is_none() && !at.is_end() { - return false; - } - } - c1.is_word_byte() != c2.is_word_byte() - } - NotWordBoundaryAscii => { - let (c1, c2) = (self.previous_char(at), self.next_char(at)); - if self.only_utf8 { - // If we must match UTF-8, then we can't match word - // boundaries at invalid UTF-8. - if c1.is_none() && !at.is_start() { - return false; - } - if c2.is_none() && !at.is_end() { - return false; - } - } - c1.is_word_byte() == c2.is_word_byte() - } - } - } - - fn prefix_at( - &self, - prefixes: &LiteralSearcher, - at: InputAt, - ) -> Option<InputAt> { - prefixes.find(&self[at.pos()..]).map(|(s, _)| self.at(at.pos() + s)) - } - - fn len(&self) -> usize { - self.text.len() - } - - fn as_bytes(&self) -> &[u8] { - self.text - } -} - -/// An inline representation of `Option<char>`. -/// -/// This eliminates the need to do case analysis on `Option<char>` to determine -/// ordinality with other characters. -/// -/// (The `Option<char>` is not related to encoding. Instead, it is used in the -/// matching engines to represent the beginning and ending boundaries of the -/// search text.) -#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] -pub struct Char(u32); - -impl fmt::Debug for Char { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match char::from_u32(self.0) { - None => write!(f, "Empty"), - Some(c) => write!(f, "{:?}", c), - } - } -} - -impl Char { - /// Returns true iff the character is absent. - #[inline] - pub fn is_none(self) -> bool { self.0 == u32::MAX } - - /// Returns the length of the character's UTF-8 encoding. - /// - /// If the character is absent, then `0` is returned. - #[inline] - pub fn len_utf8(self) -> usize { - char::from_u32(self.0).map_or(0, |c| c.len_utf8()) - } - - /// Returns true iff the character is a word character. - /// - /// If the character is absent, then false is returned. - pub fn is_word_char(self) -> bool { - char::from_u32(self.0).map_or(false, syntax::is_word_char) - } - - /// Returns true iff the byte is a word byte. - /// - /// If the byte is absent, then false is returned. - pub fn is_word_byte(self) -> bool { - match char::from_u32(self.0) { - Some(c) if c <= '\u{7F}' => syntax::is_word_byte(c as u8), - None | Some(_) => false, - } - } -} - -impl From<char> for Char { - fn from(c: char) -> Char { Char(c as u32) } -} - -impl From<Option<char>> for Char { - fn from(c: Option<char>) -> Char { - c.map_or(Char(u32::MAX), |c| c.into()) - } -} - -impl PartialEq<char> for Char { - #[inline] - fn eq(&self, other: &char) -> bool { self.0 == *other as u32 } -} - -impl PartialEq<Char> for char { - #[inline] - fn eq(&self, other: &Char) -> bool { *self as u32 == other.0 } -} - -impl PartialOrd<char> for Char { - #[inline] - fn partial_cmp(&self, other: &char) -> Option<Ordering> { - self.0.partial_cmp(&(*other as u32)) - } -} - -impl PartialOrd<Char> for char { - #[inline] - fn partial_cmp(&self, other: &Char) -> Option<Ordering> { - (*self as u32).partial_cmp(&other.0) - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/lib.rs cargo-0.26.0/vendor/regex-0.2.6/src/lib.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,664 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/*! -This crate provides a library for parsing, compiling, and executing regular -expressions. Its syntax is similar to Perl-style regular expressions, but lacks -a few features like look around and backreferences. In exchange, all searches -execute in linear time with respect to the size of the regular expression and -search text. - -This crate's documentation provides some simple examples, describes -[Unicode support](#unicode) and exhaustively lists the -[supported syntax](#syntax). - -For more specific details on the API for regular expressions, please see the -documentation for the [`Regex`](struct.Regex.html) type. - -# Usage - -This crate is [on crates.io](https://crates.io/crates/regex) and can be -used by adding `regex` to your dependencies in your project's `Cargo.toml`. - -```toml -[dependencies] -regex = "0.2" -``` - -and this to your crate root: - -```rust -extern crate regex; -``` - -# Example: find a date - -General use of regular expressions in this package involves compiling an -expression and then using it to search, split or replace text. For example, -to confirm that some text resembles a date: - -```rust -use regex::Regex; -let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); -assert!(re.is_match("2014-01-01")); -``` - -Notice the use of the `^` and `$` anchors. In this crate, every expression -is executed with an implicit `.*?` at the beginning and end, which allows -it to match anywhere in the text. Anchors can be used to ensure that the -full text matches an expression. - -This example also demonstrates the utility of -[raw strings](https://doc.rust-lang.org/stable/reference/tokens.html#raw-string-literals) -in Rust, which -are just like regular strings except they are prefixed with an `r` and do -not process any escape sequences. For example, `"\\d"` is the same -expression as `r"\d"`. - -# Example: Avoid compiling the same regex in a loop - -It is an anti-pattern to compile the same regular expression in a loop -since compilation is typically expensive. (It takes anywhere from a few -microseconds to a few **milliseconds** depending on the size of the -regex.) Not only is compilation itself expensive, but this also prevents -optimizations that reuse allocations internally to the matching engines. - -In Rust, it can sometimes be a pain to pass regular expressions around if -they're used from inside a helper function. Instead, we recommend using the -[`lazy_static`](https://crates.io/crates/lazy_static) crate to ensure that -regular expressions are compiled exactly once. - -For example: - -```rust -#[macro_use] extern crate lazy_static; -extern crate regex; - -use regex::Regex; - -fn some_helper_function(text: &str) -> bool { - lazy_static! { - static ref RE: Regex = Regex::new("...").unwrap(); - } - RE.is_match(text) -} - -fn main() {} -``` - -Specifically, in this example, the regex will be compiled when it is used for -the first time. On subsequent uses, it will reuse the previous compilation. - -# Example: iterating over capture groups - -This crate provides convenient iterators for matching an expression -repeatedly against a search string to find successive non-overlapping -matches. For example, to find all dates in a string and be able to access -them by their component pieces: - -```rust -# extern crate regex; use regex::Regex; -# fn main() { -let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap(); -let text = "2012-03-14, 2013-01-01 and 2014-07-05"; -for cap in re.captures_iter(text) { - println!("Month: {} Day: {} Year: {}", &cap[2], &cap[3], &cap[1]); -} -// Output: -// Month: 03 Day: 14 Year: 2012 -// Month: 01 Day: 01 Year: 2013 -// Month: 07 Day: 05 Year: 2014 -# } -``` - -Notice that the year is in the capture group indexed at `1`. This is -because the *entire match* is stored in the capture group at index `0`. - -# Example: replacement with named capture groups - -Building on the previous example, perhaps we'd like to rearrange the date -formats. This can be done with text replacement. But to make the code -clearer, we can *name* our capture groups and use those names as variables -in our replacement text: - -```rust -# extern crate regex; use regex::Regex; -# fn main() { -let re = Regex::new(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})").unwrap(); -let before = "2012-03-14, 2013-01-01 and 2014-07-05"; -let after = re.replace_all(before, "$m/$d/$y"); -assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014"); -# } -``` - -The `replace` methods are actually polymorphic in the replacement, which -provides more flexibility than is seen here. (See the documentation for -`Regex::replace` for more details.) - -Note that if your regex gets complicated, you can use the `x` flag to -enable insigificant whitespace mode, which also lets you write comments: - -```rust -# extern crate regex; use regex::Regex; -# fn main() { -let re = Regex::new(r"(?x) - (?P<y>\d{4}) # the year - - - (?P<m>\d{2}) # the month - - - (?P<d>\d{2}) # the day -").unwrap(); -let before = "2012-03-14, 2013-01-01 and 2014-07-05"; -let after = re.replace_all(before, "$m/$d/$y"); -assert_eq!(after, "03/14/2012, 01/01/2013 and 07/05/2014"); -# } -``` - -If you wish to match against whitespace in this mode, you can still use `\s`, -`\n`, `\t`, etc. For escaping a single space character, you can use its hex -character code `\x20` or temporarily disable the `x` flag, e.g., `(?-x: )`. - -# Example: match multiple regular expressions simultaneously - -This demonstrates how to use a `RegexSet` to match multiple (possibly -overlapping) regular expressions in a single scan of the search text: - -```rust -use regex::RegexSet; - -let set = RegexSet::new(&[ - r"\w+", - r"\d+", - r"\pL+", - r"foo", - r"bar", - r"barfoo", - r"foobar", -]).unwrap(); - -// Iterate over and collect all of the matches. -let matches: Vec<_> = set.matches("foobar").into_iter().collect(); -assert_eq!(matches, vec![0, 2, 3, 4, 6]); - -// You can also test whether a particular regex matched: -let matches = set.matches("foobar"); -assert!(!matches.matched(5)); -assert!(matches.matched(6)); -``` - -# Pay for what you use - -With respect to searching text with a regular expression, there are three -questions that can be asked: - -1. Does the text match this expression? -2. If so, where does it match? -3. Where did the capturing groups match? - -Generally speaking, this crate could provide a function to answer only #3, -which would subsume #1 and #2 automatically. However, it can be significantly -more expensive to compute the location of capturing group matches, so it's best -not to do it if you don't need to. - -Therefore, only use what you need. For example, don't use `find` if you -only need to test if an expression matches a string. (Use `is_match` -instead.) - -# Unicode - -This implementation executes regular expressions **only** on valid UTF-8 -while exposing match locations as byte indices into the search string. - -Only simple case folding is supported. Namely, when matching -case-insensitively, the characters are first mapped using the [simple case -folding](ftp://ftp.unicode.org/Public/UNIDATA/CaseFolding.txt) mapping -before matching. - -Regular expressions themselves are **only** interpreted as a sequence of -Unicode scalar values. This means you can use Unicode characters directly -in your expression: - -```rust -# extern crate regex; use regex::Regex; -# fn main() { -let re = Regex::new(r"(?i)Δ+").unwrap(); -let mat = re.find("ΔδΔ").unwrap(); -assert_eq!((mat.start(), mat.end()), (0, 6)); -# } -``` - -Most features of the regular expressions in this crate are Unicode aware. Here -are some examples: - -* `.` will match any valid UTF-8 encoded Unicode scalar value except for `\n`. - (To also match `\n`, enable the `s` flag, e.g., `(?s:.)`.) -* `\w`, `\d` and `\s` are Unicode aware. For example, `\s` will match all forms - of whitespace categorized by Unicode. -* `\b` matches a Unicode word boundary. -* Negated character classes like `[^a]` match all Unicode scalar values except - for `a`. -* `^` and `$` are **not** Unicode aware in multi-line mode. Namely, they only - recognize `\n` and not any of the other forms of line terminators defined - by Unicode. - -Finally, Unicode general categories and scripts are available as character -classes. For example, you can match a sequence of numerals, Greek or -Cherokee letters: - -```rust -# extern crate regex; use regex::Regex; -# fn main() { -let re = Regex::new(r"[\pN\p{Greek}\p{Cherokee}]+").unwrap(); -let mat = re.find("abcΔᎠβⅠᏴγδⅡxyz").unwrap(); -assert_eq!((mat.start(), mat.end()), (3, 23)); -# } -``` - -# Opt out of Unicode support - -The `bytes` sub-module provides a `Regex` type that can be used to match -on `&[u8]`. By default, text is interpreted as UTF-8 just like it is with -the main `Regex` type. However, this behavior can be disabled by turning -off the `u` flag, even if doing so could result in matching invalid UTF-8. -For example, when the `u` flag is disabled, `.` will match any byte instead -of any Unicode scalar value. - -Disabling the `u` flag is also possible with the standard `&str`-based `Regex` -type, but it is only allowed where the UTF-8 invariant is maintained. For -example, `(?-u:\w)` is an ASCII-only `\w` character class and is legal in an -`&str`-based `Regex`, but `(?-u:\xFF)` will attempt to match the raw byte -`\xFF`, which is invalid UTF-8 and therefore is illegal in `&str`-based -regexes. - -# Syntax - -The syntax supported in this crate is documented below. - -Note that the regular expression parser and abstract syntax are exposed in -a separate crate, [`regex-syntax`](../regex_syntax/index.html). - -## Matching one character - -<pre class="rust"> -. any character except new line (includes new line with s flag) -\d digit (\p{Nd}) -\D not digit -\pN One-letter name Unicode character class -\p{Greek} Unicode character class (general category or script) -\PN Negated one-letter name Unicode character class -\P{Greek} negated Unicode character class (general category or script) -</pre> - -### Character classes - -<pre class="rust"> -[xyz] A character class matching either x, y or z (union). -[^xyz] A character class matching any character except x, y and z. -[a-z] A character class matching any character in range a-z. -[[:alpha:]] ASCII character class ([A-Za-z]) -[[:^alpha:]] Negated ASCII character class ([^A-Za-z]) -[x[^xyz]] Nested/grouping character class (matching any character except y and z) -[a-y&&xyz] Intersection (matching x or y) -[0-9&&[^4]] Subtraction using intersection and negation (matching 0-9 except 4) -[\[\]] Escaping in character classes (matching [ or ]) -</pre> - -Any named character class may appear inside a bracketed `[...]` character -class. For example, `[\p{Greek}[:digit:]]` matches any Greek or ASCII -digit. `[\p{Greek}&&\pL]` matches Greek letters. - -Precedence in character classes, from most binding to least: - -1. Ranges: `a-cd` == `[a-c]d` -2. Union: `ab&&bc` == `[ab]&&[bc]` -3. Intersection: `^a-z&&b` == `^[a-z&&b]` -4. Negation - -## Composites - -<pre class="rust"> -xy concatenation (x followed by y) -x|y alternation (x or y, prefer x) -</pre> - -## Repetitions - -<pre class="rust"> -x* zero or more of x (greedy) -x+ one or more of x (greedy) -x? zero or one of x (greedy) -x*? zero or more of x (ungreedy/lazy) -x+? one or more of x (ungreedy/lazy) -x?? zero or one of x (ungreedy/lazy) -x{n,m} at least n x and at most m x (greedy) -x{n,} at least n x (greedy) -x{n} exactly n x -x{n,m}? at least n x and at most m x (ungreedy/lazy) -x{n,}? at least n x (ungreedy/lazy) -x{n}? exactly n x -</pre> - -## Empty matches - -<pre class="rust"> -^ the beginning of text (or start-of-line with multi-line mode) -$ the end of text (or end-of-line with multi-line mode) -\A only the beginning of text (even with multi-line mode enabled) -\z only the end of text (even with multi-line mode enabled) -\b a Unicode word boundary (\w on one side and \W, \A, or \z on other) -\B not a Unicode word boundary -</pre> - -## Grouping and flags - -<pre class="rust"> -(exp) numbered capture group (indexed by opening parenthesis) -(?P<name>exp) named (also numbered) capture group (allowed chars: [_0-9a-zA-Z]) -(?:exp) non-capturing group -(?flags) set flags within current group -(?flags:exp) set flags for exp (non-capturing) -</pre> - -Flags are each a single character. For example, `(?x)` sets the flag `x` -and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at -the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets -the `x` flag and clears the `y` flag. - -All flags are by default disabled unless stated otherwise. They are: - -<pre class="rust"> -i case-insensitive: letters match both upper and lower case -m multi-line mode: ^ and $ match begin/end of line -s allow . to match \n -U swap the meaning of x* and x*? -u Unicode support (enabled by default) -x ignore whitespace and allow line comments (starting with `#`) -</pre> - -Flags can be toggled within a pattern. Here's an example that matches -case-insensitively for the first part but case-sensitively for the second part: - -```rust -# extern crate regex; use regex::Regex; -# fn main() { -let re = Regex::new(r"(?i)a+(?-i)b+").unwrap(); -let cap = re.captures("AaAaAbbBBBb").unwrap(); -assert_eq!(&cap[0], "AaAaAbb"); -# } -``` - -Notice that the `a+` matches either `a` or `A`, but the `b+` only matches -`b`. - -Multi-line mode means `^` and `$` no longer match just at the beginning/end of -the input, but at the beginning/end of lines: - -``` -# use regex::Regex; -let re = Regex::new(r"(?m)^line \d+").unwrap(); -let m = re.find("line one\nline 2\n").unwrap(); -assert_eq!(m.as_str(), "line 2"); -``` - -Note that `^` matches after new lines, even at the end of input: - -``` -# use regex::Regex; -let re = Regex::new(r"(?m)^").unwrap(); -let m = re.find_iter("test\n").last().unwrap(); -assert_eq!((m.start(), m.end()), (5, 5)); -``` - -Here is an example that uses an ASCII word boundary instead of a Unicode -word boundary: - -```rust -# extern crate regex; use regex::Regex; -# fn main() { -let re = Regex::new(r"(?-u:\b).+(?-u:\b)").unwrap(); -let cap = re.captures("$$abc$$").unwrap(); -assert_eq!(&cap[0], "abc"); -# } -``` - -## Escape sequences - -<pre class="rust"> -\* literal *, works for any punctuation character: \.+*?()|[]{}^$ -\a bell (\x07) -\f form feed (\x0C) -\t horizontal tab -\n new line -\r carriage return -\v vertical tab (\x0B) -\123 octal character code (up to three digits) -\x7F hex character code (exactly two digits) -\x{10FFFF} any hex character code corresponding to a Unicode code point -</pre> - -## Perl character classes (Unicode friendly) - -These classes are based on the definitions provided in -[UTS#18](http://www.unicode.org/reports/tr18/#Compatibility_Properties): - -<pre class="rust"> -\d digit (\p{Nd}) -\D not digit -\s whitespace (\p{White_Space}) -\S not whitespace -\w word character (\p{Alphabetic} + \p{M} + \d + \p{Pc} + \p{Join_Control}) -\W not word character -</pre> - -## ASCII character classes - -<pre class="rust"> -[[:alnum:]] alphanumeric ([0-9A-Za-z]) -[[:alpha:]] alphabetic ([A-Za-z]) -[[:ascii:]] ASCII ([\x00-\x7F]) -[[:blank:]] blank ([\t ]) -[[:cntrl:]] control ([\x00-\x1F\x7F]) -[[:digit:]] digits ([0-9]) -[[:graph:]] graphical ([!-~]) -[[:lower:]] lower case ([a-z]) -[[:print:]] printable ([ -~]) -[[:punct:]] punctuation ([!-/:-@\[-`{-~]) -[[:space:]] whitespace ([\t\n\v\f\r ]) -[[:upper:]] upper case ([A-Z]) -[[:word:]] word characters ([0-9A-Za-z_]) -[[:xdigit:]] hex digit ([0-9A-Fa-f]) -</pre> - -# Untrusted input - -This crate can handle both untrusted regular expressions and untrusted -search text. - -Untrusted regular expressions are handled by capping the size of a compiled -regular expression. -(See [`RegexBuilder::size_limit`](struct.RegexBuilder.html#method.size_limit).) -Without this, it would be trivial for an attacker to exhaust your system's -memory with expressions like `a{100}{100}{100}`. - -Untrusted search text is allowed because the matching engine(s) in this -crate have time complexity `O(mn)` (with `m ~ regex` and `n ~ search -text`), which means there's no way to cause exponential blow-up like with -some other regular expression engines. (We pay for this by disallowing -features like arbitrary look-ahead and backreferences.) - -When a DFA is used, pathological cases with exponential state blow up are -avoided by constructing the DFA lazily or in an "online" manner. Therefore, -at most one new state can be created for each byte of input. This satisfies -our time complexity guarantees, but can lead to unbounded memory growth -proportional to the size of the input. As a stopgap, the DFA is only -allowed to store a fixed number of states. When the limit is reached, its -states are wiped and continues on, possibly duplicating previous work. If -the limit is reached too frequently, it gives up and hands control off to -another matching engine with fixed memory requirements. -(The DFA size limit can also be tweaked. See -[`RegexBuilder::dfa_size_limit`](struct.RegexBuilder.html#method.dfa_size_limit).) -*/ - -#![deny(missing_docs)] -#![cfg_attr(test, deny(warnings))] -#![cfg_attr(feature = "pattern", feature(pattern))] -#![cfg_attr(feature = "simd-accel", feature(cfg_target_feature))] - -extern crate aho_corasick; -extern crate memchr; -extern crate thread_local; -#[macro_use] #[cfg(test)] extern crate quickcheck; -extern crate regex_syntax as syntax; -#[cfg(feature = "simd-accel")] extern crate simd; -extern crate utf8_ranges; - -pub use error::Error; -pub use re_builder::unicode::*; -pub use re_builder::set_unicode::*; -pub use re_set::unicode::*; -pub use re_trait::Locations; -pub use re_unicode::{ - Regex, Match, Captures, - CaptureNames, Matches, CaptureMatches, SubCaptureMatches, - Replacer, NoExpand, Split, SplitN, - escape, -}; - -/** -Match regular expressions on arbitrary bytes. - -This module provides a nearly identical API to the one found in the -top-level of this crate. There are two important differences: - -1. Matching is done on `&[u8]` instead of `&str`. Additionally, `Vec<u8>` -is used where `String` would have been used. -2. Unicode support can be disabled even when disabling it would result in -matching invalid UTF-8 bytes. - -# Example: match null terminated string - -This shows how to find all null-terminated strings in a slice of bytes: - -```rust -# use regex::bytes::Regex; -let re = Regex::new(r"(?-u)(?P<cstr>[^\x00]+)\x00").unwrap(); -let text = b"foo\x00bar\x00baz\x00"; - -// Extract all of the strings without the null terminator from each match. -// The unwrap is OK here since a match requires the `cstr` capture to match. -let cstrs: Vec<&[u8]> = - re.captures_iter(text) - .map(|c| c.name("cstr").unwrap().as_bytes()) - .collect(); -assert_eq!(vec![&b"foo"[..], &b"bar"[..], &b"baz"[..]], cstrs); -``` - -# Example: selectively enable Unicode support - -This shows how to match an arbitrary byte pattern followed by a UTF-8 encoded -string (e.g., to extract a title from a Matroska file): - -```rust -# use std::str; -# use regex::bytes::Regex; -let re = Regex::new( - r"(?-u)\x7b\xa9(?:[\x80-\xfe]|[\x40-\xff].)(?u:(.*))" -).unwrap(); -let text = b"\x12\xd0\x3b\x5f\x7b\xa9\x85\xe2\x98\x83\x80\x98\x54\x76\x68\x65"; -let caps = re.captures(text).unwrap(); - -// Notice that despite the `.*` at the end, it will only match valid UTF-8 -// because Unicode mode was enabled with the `u` flag. Without the `u` flag, -// the `.*` would match the rest of the bytes. -let mat = caps.get(1).unwrap(); -assert_eq!((7, 10), (mat.start(), mat.end())); - -// If there was a match, Unicode mode guarantees that `title` is valid UTF-8. -let title = str::from_utf8(&caps[1]).unwrap(); -assert_eq!("☃", title); -``` - -In general, if the Unicode flag is enabled in a capture group and that capture -is part of the overall match, then the capture is *guaranteed* to be valid -UTF-8. - -# Syntax - -The supported syntax is pretty much the same as the syntax for Unicode -regular expressions with a few changes that make sense for matching arbitrary -bytes: - -1. The `u` flag can be disabled even when disabling it might cause the regex to -match invalid UTF-8. When the `u` flag is disabled, the regex is said to be in -"ASCII compatible" mode. -2. In ASCII compatible mode, neither Unicode scalar values nor Unicode -character classes are allowed. -3. In ASCII compatible mode, Perl character classes (`\w`, `\d` and `\s`) -revert to their typical ASCII definition. `\w` maps to `[[:word:]]`, `\d` maps -to `[[:digit:]]` and `\s` maps to `[[:space:]]`. -4. In ASCII compatible mode, word boundaries use the ASCII compatible `\w` to -determine whether a byte is a word byte or not. -5. Hexadecimal notation can be used to specify arbitrary bytes instead of -Unicode codepoints. For example, in ASCII compatible mode, `\xFF` matches the -literal byte `\xFF`, while in Unicode mode, `\xFF` is a Unicode codepoint that -matches its UTF-8 encoding of `\xC3\xBF`. Similarly for octal notation. -6. `.` matches any *byte* except for `\n` instead of any Unicode scalar value. -When the `s` flag is enabled, `.` matches any byte. - -# Performance - -In general, one should expect performance on `&[u8]` to be roughly similar to -performance on `&str`. -*/ -pub mod bytes { - pub use re_builder::bytes::*; - pub use re_builder::set_bytes::*; - pub use re_bytes::*; - pub use re_set::bytes::*; - pub use re_trait::Locations; -} - -mod backtrack; -mod utf8; -mod compile; -mod dfa; -mod error; -mod exec; -mod expand; -mod freqs; -mod input; -mod literals; -#[cfg(feature = "pattern")] -mod pattern; -mod pikevm; -mod prog; -mod re_builder; -mod re_bytes; -mod re_set; -mod re_trait; -mod re_unicode; -#[cfg(feature = "simd-accel")] -mod simd_accel; -#[cfg(not(feature = "simd-accel"))] -#[path = "simd_fallback/mod.rs"] -mod simd_accel; -mod sparse; - -/// The `internal` module exists to support suspicious activity, such as -/// testing different matching engines and supporting the `regex-debug` CLI -/// utility. -#[doc(hidden)] -pub mod internal { - pub use compile::Compiler; - pub use exec::{Exec, ExecBuilder}; - pub use input::{Char, Input, CharInput, InputAt}; - pub use literals::LiteralSearcher; - pub use prog::{Program, Inst, EmptyLook, InstRanges}; -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/literals.rs cargo-0.26.0/vendor/regex-0.2.6/src/literals.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/literals.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/literals.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1080 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::mem; - -use aho_corasick::{Automaton, AcAutomaton, FullAcAutomaton}; -use memchr::{memchr, memchr2, memchr3}; -use syntax; - -use freqs::BYTE_FREQUENCIES; - -use simd_accel::teddy128::{Teddy, is_teddy_128_available}; - -/// A prefix extracted from a compiled regular expression. -/// -/// A regex prefix is a set of literal strings that *must* be matched at the -/// beginning of a regex in order for the entire regex to match. Similarly -/// for a regex suffix. -#[derive(Clone, Debug)] -pub struct LiteralSearcher { - complete: bool, - lcp: FreqyPacked, - lcs: FreqyPacked, - matcher: Matcher, -} - -#[derive(Clone, Debug)] -enum Matcher { - /// No literals. (Never advances through the input.) - Empty, - /// A set of four or more single byte literals. - Bytes(SingleByteSet), - /// A single substring, find using memchr and frequency analysis. - FreqyPacked(FreqyPacked), - /// A single substring, find using Boyer-Moore. - BoyerMoore(BoyerMooreSearch), - /// An Aho-Corasick automaton. - AC(FullAcAutomaton<syntax::Lit>), - /// A simd accelerated multiple string matcher. Used only for a small - /// number of small literals. - Teddy128(Teddy), -} - -impl LiteralSearcher { - /// Returns a matcher that never matches and never advances the input. - pub fn empty() -> Self { - Self::new(syntax::Literals::empty(), Matcher::Empty) - } - - /// Returns a matcher for literal prefixes from the given set. - pub fn prefixes(lits: syntax::Literals) -> Self { - let matcher = Matcher::prefixes(&lits); - Self::new(lits, matcher) - } - - /// Returns a matcher for literal suffixes from the given set. - pub fn suffixes(lits: syntax::Literals) -> Self { - let matcher = Matcher::suffixes(&lits); - Self::new(lits, matcher) - } - - fn new(lits: syntax::Literals, matcher: Matcher) -> Self { - let complete = lits.all_complete(); - LiteralSearcher { - complete: complete, - lcp: FreqyPacked::new(lits.longest_common_prefix().to_vec()), - lcs: FreqyPacked::new(lits.longest_common_suffix().to_vec()), - matcher: matcher, - } - } - - /// Returns true if all matches comprise the entire regular expression. - /// - /// This does not necessarily mean that a literal match implies a match - /// of the regular expression. For example, the regular expresison `^a` - /// is comprised of a single complete literal `a`, but the regular - /// expression demands that it only match at the beginning of a string. - pub fn complete(&self) -> bool { - self.complete && !self.is_empty() - } - - /// Find the position of a literal in `haystack` if it exists. - #[inline(always)] // reduces constant overhead - pub fn find(&self, haystack: &[u8]) -> Option<(usize, usize)> { - use self::Matcher::*; - match self.matcher { - Empty => Some((0, 0)), - Bytes(ref sset) => sset.find(haystack).map(|i| (i, i + 1)), - FreqyPacked(ref s) => s.find(haystack).map(|i| (i, i + s.len())), - BoyerMoore(ref s) => s.find(haystack).map(|i| (i, i + s.len())), - AC(ref aut) => aut.find(haystack).next().map(|m| (m.start, m.end)), - Teddy128(ref ted) => ted.find(haystack).map(|m| (m.start, m.end)), - } - } - - /// Like find, except matches must start at index `0`. - pub fn find_start(&self, haystack: &[u8]) -> Option<(usize, usize)> { - for lit in self.iter() { - if lit.len() > haystack.len() { - continue; - } - if lit == &haystack[0..lit.len()] { - return Some((0, lit.len())); - } - } - None - } - - /// Like find, except matches must end at index `haystack.len()`. - pub fn find_end(&self, haystack: &[u8]) -> Option<(usize, usize)> { - for lit in self.iter() { - if lit.len() > haystack.len() { - continue; - } - if lit == &haystack[haystack.len() - lit.len()..] { - return Some((haystack.len() - lit.len(), haystack.len())); - } - } - None - } - - /// Returns an iterator over all literals to be matched. - pub fn iter(&self) -> LiteralIter { - match self.matcher { - Matcher::Empty => LiteralIter::Empty, - Matcher::Bytes(ref sset) => LiteralIter::Bytes(&sset.dense), - Matcher::FreqyPacked(ref s) => LiteralIter::Single(&s.pat), - Matcher::BoyerMoore(ref s) => LiteralIter::Single(&s.pattern), - Matcher::AC(ref ac) => LiteralIter::AC(ac.patterns()), - Matcher::Teddy128(ref ted) => { - LiteralIter::Teddy128(ted.patterns()) - } - } - } - - /// Returns a matcher for the longest common prefix of this matcher. - pub fn lcp(&self) -> &FreqyPacked { - &self.lcp - } - - /// Returns a matcher for the longest common suffix of this matcher. - pub fn lcs(&self) -> &FreqyPacked { - &self.lcs - } - - /// Returns true iff this prefix is empty. - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Returns the number of prefixes in this machine. - pub fn len(&self) -> usize { - use self::Matcher::*; - match self.matcher { - Empty => 0, - Bytes(ref sset) => sset.dense.len(), - FreqyPacked(_) => 1, - BoyerMoore(_) => 1, - AC(ref aut) => aut.len(), - Teddy128(ref ted) => ted.len(), - } - } - - /// Return the approximate heap usage of literals in bytes. - pub fn approximate_size(&self) -> usize { - use self::Matcher::*; - match self.matcher { - Empty => 0, - Bytes(ref sset) => sset.approximate_size(), - FreqyPacked(ref single) => single.approximate_size(), - BoyerMoore(ref single) => single.approximate_size(), - AC(ref aut) => aut.heap_bytes(), - Teddy128(ref ted) => ted.approximate_size(), - } - } -} - -impl Matcher { - fn prefixes(lits: &syntax::Literals) -> Self { - let sset = SingleByteSet::prefixes(lits); - Matcher::new(lits, sset) - } - - fn suffixes(lits: &syntax::Literals) -> Self { - let sset = SingleByteSet::suffixes(lits); - Matcher::new(lits, sset) - } - - fn new(lits: &syntax::Literals, sset: SingleByteSet) -> Self { - if lits.literals().is_empty() { - return Matcher::Empty; - } - if sset.dense.len() >= 26 { - // Avoid trying to match a large number of single bytes. - // This is *very* sensitive to a frequency analysis comparison - // between the bytes in sset and the composition of the haystack. - // No matter the size of sset, if its members all are rare in the - // haystack, then it'd be worth using it. How to tune this... IDK. - // ---AG - return Matcher::Empty; - } - if sset.complete { - return Matcher::Bytes(sset); - } - if lits.literals().len() == 1 { - let lit = lits.literals()[0].to_vec(); - if BoyerMooreSearch::should_use(lit.as_slice()) { - return Matcher::BoyerMoore(BoyerMooreSearch::new(lit)); - } else { - return Matcher::FreqyPacked(FreqyPacked::new(lit)); - } - } - let is_aho_corasick_fast = sset.dense.len() == 1 && sset.all_ascii; - if is_teddy_128_available() && !is_aho_corasick_fast { - // Only try Teddy if Aho-Corasick can't use memchr on an ASCII - // byte. Also, in its current form, Teddy doesn't scale well to - // lots of literals. - // - // We impose the ASCII restriction since an alternation of - // non-ASCII string literals in the same language is likely to all - // start with the same byte. Even worse, the corpus being searched - // probably has a similar composition, which ends up completely - // negating the benefit of memchr. - const MAX_TEDDY_LITERALS: usize = 32; - if lits.literals().len() <= MAX_TEDDY_LITERALS { - if let Some(ted) = Teddy::new(lits) { - return Matcher::Teddy128(ted); - } - } - // Fallthrough to ol' reliable Aho-Corasick... - } - let pats = lits.literals().to_owned(); - Matcher::AC(AcAutomaton::new(pats).into_full()) - } -} - -pub enum LiteralIter<'a> { - Empty, - Bytes(&'a [u8]), - Single(&'a [u8]), - AC(&'a [syntax::Lit]), - Teddy128(&'a [Vec<u8>]), -} - -impl<'a> Iterator for LiteralIter<'a> { - type Item = &'a [u8]; - - fn next(&mut self) -> Option<Self::Item> { - match *self { - LiteralIter::Empty => None, - LiteralIter::Bytes(ref mut many) => { - if many.is_empty() { - None - } else { - let next = &many[0..1]; - *many = &many[1..]; - Some(next) - } - } - LiteralIter::Single(ref mut one) => { - if one.is_empty() { - None - } else { - let next = &one[..]; - *one = &[]; - Some(next) - } - } - LiteralIter::AC(ref mut lits) => { - if lits.is_empty() { - None - } else { - let next = &lits[0]; - *lits = &lits[1..]; - Some(&**next) - } - } - LiteralIter::Teddy128(ref mut lits) => { - if lits.is_empty() { - None - } else { - let next = &lits[0]; - *lits = &lits[1..]; - Some(&**next) - } - } - } - } -} - -#[derive(Clone, Debug)] -struct SingleByteSet { - sparse: Vec<bool>, - dense: Vec<u8>, - complete: bool, - all_ascii: bool, -} - -impl SingleByteSet { - fn new() -> SingleByteSet { - SingleByteSet { - sparse: vec![false; 256], - dense: vec![], - complete: true, - all_ascii: true, - } - } - - fn prefixes(lits: &syntax::Literals) -> SingleByteSet { - let mut sset = SingleByteSet::new(); - for lit in lits.literals() { - sset.complete = sset.complete && lit.len() == 1; - if let Some(&b) = lit.get(0) { - if !sset.sparse[b as usize] { - if b > 0x7F { - sset.all_ascii = false; - } - sset.dense.push(b); - sset.sparse[b as usize] = true; - } - } - } - sset - } - - fn suffixes(lits: &syntax::Literals) -> SingleByteSet { - let mut sset = SingleByteSet::new(); - for lit in lits.literals() { - sset.complete = sset.complete && lit.len() == 1; - if let Some(&b) = lit.get(lit.len().checked_sub(1).unwrap()) { - if !sset.sparse[b as usize] { - if b > 0x7F { - sset.all_ascii = false; - } - sset.dense.push(b); - sset.sparse[b as usize] = true; - } - } - } - sset - } - - /// Faster find that special cases certain sizes to use memchr. - #[inline(always)] // reduces constant overhead - fn find(&self, text: &[u8]) -> Option<usize> { - match self.dense.len() { - 0 => None, - 1 => memchr(self.dense[0], text), - 2 => memchr2(self.dense[0], self.dense[1], text), - 3 => memchr3(self.dense[0], self.dense[1], self.dense[2], text), - _ => self._find(text), - } - } - - /// Generic find that works on any sized set. - fn _find(&self, haystack: &[u8]) -> Option<usize> { - for (i, &b) in haystack.iter().enumerate() { - if self.sparse[b as usize] { - return Some(i); - } - } - None - } - - fn approximate_size(&self) -> usize { - (self.dense.len() * mem::size_of::<u8>()) - + (self.sparse.len() * mem::size_of::<bool>()) - } -} - -/// Provides an implementation of fast subtring search using frequency -/// analysis. -/// -/// memchr is so fast that we do everything we can to keep the loop in memchr -/// for as long as possible. The easiest way to do this is to intelligently -/// pick the byte to send to memchr. The best byte is the byte that occurs -/// least frequently in the haystack. Since doing frequency analysis on the -/// haystack is far too expensive, we compute a set of fixed frequencies up -/// front and hard code them in src/freqs.rs. Frequency analysis is done via -/// scripts/frequencies.py. -#[derive(Clone, Debug)] -pub struct FreqyPacked { - /// The pattern. - pat: Vec<u8>, - /// The number of Unicode characters in the pattern. This is useful for - /// determining the effective length of a pattern when deciding which - /// optimizations to perform. A trailing incomplete UTF-8 sequence counts - /// as one character. - char_len: usize, - /// The rarest byte in the pattern, according to pre-computed frequency - /// analysis. - rare1: u8, - /// The offset of the rarest byte in `pat`. - rare1i: usize, - /// The second rarest byte in the pattern, according to pre-computed - /// frequency analysis. (This may be equivalent to the rarest byte.) - /// - /// The second rarest byte is used as a type of guard for quickly detecting - /// a mismatch after memchr locates an instance of the rarest byte. This - /// is a hedge against pathological cases where the pre-computed frequency - /// analysis may be off. (But of course, does not prevent *all* - /// pathological cases.) - rare2: u8, - /// The offset of the second rarest byte in `pat`. - rare2i: usize, -} - -impl FreqyPacked { - fn new(pat: Vec<u8>) -> FreqyPacked { - if pat.is_empty() { - return FreqyPacked::empty(); - } - - // Find the rarest two bytes. Try to make them distinct (but it's not - // required). - let mut rare1 = pat[0]; - let mut rare2 = pat[0]; - for b in pat[1..].iter().cloned() { - if freq_rank(b) < freq_rank(rare1) { - rare1 = b; - } - } - for &b in &pat { - if rare1 == rare2 { - rare2 = b - } else if b != rare1 && freq_rank(b) < freq_rank(rare2) { - rare2 = b; - } - } - - // And find the offsets of their last occurrences. - let rare1i = pat.iter().rposition(|&b| b == rare1).unwrap(); - let rare2i = pat.iter().rposition(|&b| b == rare2).unwrap(); - - let char_len = char_len_lossy(&pat); - FreqyPacked { - pat: pat, - char_len: char_len, - rare1: rare1, - rare1i: rare1i, - rare2: rare2, - rare2i: rare2i, - } - } - - fn empty() -> FreqyPacked { - FreqyPacked { - pat: vec![], - char_len: 0, - rare1: 0, - rare1i: 0, - rare2: 0, - rare2i: 0, - } - } - - #[inline(always)] // reduces constant overhead - pub fn find(&self, haystack: &[u8]) -> Option<usize> { - let pat = &*self.pat; - if haystack.len() < pat.len() || pat.is_empty() { - return None; - } - let mut i = self.rare1i; - while i < haystack.len() { - i += match memchr(self.rare1, &haystack[i..]) { - None => return None, - Some(i) => i, - }; - let start = i - self.rare1i; - let end = start + pat.len(); - if end > haystack.len() { - return None; - } - let aligned = &haystack[start..end]; - if aligned[self.rare2i] == self.rare2 && aligned == &*self.pat { - return Some(start); - } - i += 1; - } - None - } - - #[inline(always)] // reduces constant overhead - pub fn is_suffix(&self, text: &[u8]) -> bool { - if text.len() < self.len() { - return false; - } - text[text.len() - self.len()..] == *self.pat - } - - pub fn len(&self) -> usize { - self.pat.len() - } - - pub fn char_len(&self) -> usize { - self.char_len - } - - fn approximate_size(&self) -> usize { - self.pat.len() * mem::size_of::<u8>() - } -} - -fn char_len_lossy(bytes: &[u8]) -> usize { - String::from_utf8_lossy(bytes).chars().count() -} - -/// An implementation of Tuned Boyer-Moore as laid out by -/// Andrew Hume and Daniel Sunday in "Fast String Searching". -/// O(n) in the size of the input. -/// -/// Fast string searching algorithms come in many variations, -/// but they can generally be described in terms of three main -/// components. -/// -/// The skip loop is where the string searcher wants to spend -/// as much time as possible. Exactly which character in the -/// pattern the skip loop examines varies from algorithm to -/// algorithm, but in the simplest case this loop repeated -/// looks at the last character in the pattern and jumps -/// forward in the input if it is not in the pattern. -/// Robert Boyer and J Moore called this the "fast" loop in -/// their original paper. -/// -/// The match loop is responsible for actually examining the -/// whole potentially matching substring. In order to fail -/// faster, the match loop sometimes has a guard test attached. -/// The guard test uses frequency analysis of the different -/// characters in the pattern to choose the least frequency -/// occurring character and use it to find match failures -/// as quickly as possible. -/// -/// The shift rule governs how the algorithm will shuffle its -/// test window in the event of a failure during the match loop. -/// Certain shift rules allow the worst-case run time of the -/// algorithm to be shown to be O(n) in the size of the input -/// rather than O(nm) in the size of the input and the size -/// of the pattern (as naive Boyer-Moore is). -/// -/// "Fast String Searching", in addition to presenting a tuned -/// algorithm, provides a comprehensive taxonomy of the many -/// different flavors of string searchers. Under that taxonomy -/// TBM, the algorithm implemented here, uses an unrolled fast -/// skip loop with memchr fallback, a forward match loop with guard, -/// and the mini Sunday's delta shift rule. To unpack that you'll have to -/// read the paper. -#[derive(Clone, Debug)] -pub struct BoyerMooreSearch { - /// The pattern we are going to look for in the haystack. - pattern: Vec<u8>, - - /// The skip table for the skip loop. - /// - /// Maps the character at the end of the input - /// to a shift. - skip_table: Vec<usize>, - - /// The guard character (least frequently occurring char). - guard: u8, - /// The reverse-index of the guard character in the pattern. - guard_reverse_idx: usize, - - /// Daniel Sunday's mini generalized delta2 shift table. - /// - /// We use a skip loop, so we only have to provide a shift - /// for the skip char (last char). This is why it is a mini - /// shift rule. - md2_shift: usize, -} - -impl BoyerMooreSearch { - /// Create a new string searcher, performing whatever - /// compilation steps are required. - fn new(pattern: Vec<u8>) -> Self { - debug_assert!(pattern.len() > 0); - - let (g, gi) = Self::select_guard(pattern.as_slice()); - let skip_table = Self::compile_skip_table(pattern.as_slice()); - let md2_shift = Self::compile_md2_shift(pattern.as_slice()); - BoyerMooreSearch { - pattern: pattern, - skip_table: skip_table, - guard: g, - guard_reverse_idx: gi, - md2_shift: md2_shift, - } - } - - /// Find the pattern in `haystack`, returning the offset - /// of the start of the first occurrence of the pattern - /// in `haystack`. - #[inline] - fn find(&self, haystack: &[u8]) -> Option<usize> { - if haystack.len() < self.pattern.len() { - return None; - } - - let mut window_end = self.pattern.len() - 1; - - // Inspired by the grep source. It is a way - // to do correct loop unrolling without having to place - // a crashpad of terminating charicters at the end in - // the way described in the Fast String Searching paper. - const NUM_UNROLL: usize = 10; - // 1 for the initial position, and 1 for the md2 shift - let short_circut = (NUM_UNROLL + 2) * self.pattern.len(); - - if haystack.len() > short_circut { - // just 1 for the md2 shift - let backstop = haystack.len() - ((NUM_UNROLL + 1) * self.pattern.len()); - loop { - window_end = match self.skip_loop(haystack, window_end, backstop) { - Some(i) => i, - None => return None, - }; - if window_end >= backstop { - break; - } - - if self.check_match(haystack, window_end) { - return Some(window_end - (self.pattern.len() - 1)); - } else { - window_end += self.md2_shift; - continue; - } - } - } - - // now process the input after the backstop - while window_end < haystack.len() { - let mut skip = self.skip_table[haystack[window_end] as usize]; - if skip == 0 { - if self.check_match(haystack, window_end) { - return Some(window_end - (self.pattern.len() - 1)); - } else { - skip = self.md2_shift; - } - } - window_end += skip; - } - - None - } - - fn len(&self) -> usize { - return self.pattern.len() - } - - /// The key heuristic behind which the BoyerMooreSearch lives. - /// - /// See `rust-lang/regex/issues/408`. - /// - /// Tuned Boyer-Moore is actually pretty slow! It turns out a handrolled - /// platform-specific memchr routine with a bit of frequency - /// analysis sprinkled on top actually wins most of the time. - /// However, there are a few cases where Tuned Boyer-Moore still - /// wins. - /// - /// If the haystack is random, frequency analysis doesn't help us, - /// so Boyer-Moore will win for sufficiently large needles. - /// Unfortunately, there is no obvious way to determine this - /// ahead of time. - /// - /// If the pattern itself consists of very common characters, - /// frequency analysis won't get us anywhere. The most extreme - /// example of this is a pattern like `eeeeeeeeeeeeeeee`. Fortunately, - /// this case is wholly determined by the pattern, so we can actually - /// implement the heuristic. - /// - /// A third case is if the pattern is sufficiently long. The idea - /// here is that once the pattern gets long enough the Tuned - /// Boyer-Moore skip loop will start making strides long enough - /// to beat the asm deep magic that is memchr. Unfortunately, - /// I had trouble proving a useful turnover point. Hopefully, - /// we can find one in the future. - fn should_use(_pattern: &[u8]) -> bool { - // TBM is disabled until the bm_backstop_boundary unit test can pass - // and we're more confident that the implementation is correct. - // - // See: https://github.com/rust-lang/regex/issues/446 - false - /* - // The minimum pattern length required to use TBM. - const MIN_LEN: usize = 9; - // The minimum frequency rank (lower is rarer) that every byte in the - // pattern must have in order to use TBM. That is, if the pattern - // contains _any_ byte with a lower rank, then TBM won't be used. - const MIN_CUTOFF: usize = 150; - // The maximum frequency rank for any byte. - const MAX_CUTOFF: usize = 255; - // The scaling factor used to determine the actual cutoff frequency - // to use (keeping in mind that the minimum frequency rank is bounded - // by MIN_CUTOFF). This scaling factor is an attempt to make TBM more - // likely to be used as the pattern grows longer. That is, longer - // patterns permit somewhat less frequent bytes than shorter patterns, - // under the assumption that TBM gets better as the pattern gets - // longer. - const LEN_CUTOFF_PROPORTION: usize = 4; - - let scaled_rank = pattern.len().wrapping_mul(LEN_CUTOFF_PROPORTION); - let cutoff = cmp::max( - MIN_CUTOFF, - MAX_CUTOFF - cmp::min(MAX_CUTOFF, scaled_rank), - ); - // The pattern must be long enough to be worthwhile. e.g., memchr will - // be faster on `e` because it is short even though e is quite common. - pattern.len() > MIN_LEN - // all the bytes must be more common than the cutoff. - && pattern.iter().all(|c| freq_rank(*c) >= cutoff) - */ - } - - /// Check to see if there is a match at the given position - #[inline] - fn check_match(&self, haystack: &[u8], window_end: usize) -> bool { - // guard test - if haystack[window_end - self.guard_reverse_idx] != self.guard { - return false; - } - - // match loop - let window_start = window_end - (self.pattern.len() - 1); - for i in 0..self.pattern.len() { - if self.pattern[i] != haystack[window_start + i] { - return false; - } - } - - true - } - - /// Skip forward according to the shift table. - /// - /// Returns the offset of the next occurrence - /// of the last char in the pattern, or the none - /// if it never reappears. If `skip_loop` hits the backstop - /// it will leave early. - #[inline] - fn skip_loop(&self, - haystack: &[u8], - mut window_end: usize, - backstop: usize, - ) -> Option<usize> { - use std::mem; - - let window_end_snapshot = window_end; - let skip_of = |we: usize| -> usize { - // Unsafe might make this faster, but the benchmarks - // were hard to interpret. - self.skip_table[haystack[we] as usize] - }; - - loop { - let mut skip = skip_of(window_end); window_end += skip; - skip = skip_of(window_end); window_end += skip; - if skip != 0 { - skip = skip_of(window_end); window_end += skip; - skip = skip_of(window_end); window_end += skip; - skip = skip_of(window_end); window_end += skip; - if skip != 0 { - skip = skip_of(window_end); window_end += skip; - skip = skip_of(window_end); window_end += skip; - skip = skip_of(window_end); window_end += skip; - if skip != 0 { - skip = skip_of(window_end); window_end += skip; - skip = skip_of(window_end); window_end += skip; - - // If ten iterations did not make at least 16 words - // worth of progress, we just fall back on memchr. - if window_end - window_end_snapshot > - 16 * mem::size_of::<usize>() { - - // Returning a window_end >= backstop will immediatly - // break us out of the inner loop in `find`. - if window_end >= backstop { - return Some(window_end); - } - - continue; // we made enough progress - } else { - // In case we are already there, and so that - // we will catch the guard char. - window_end = window_end - .checked_sub(1 + self.guard_reverse_idx) - .unwrap_or(0); - - match memchr(self.guard, &haystack[window_end..]) { - None => return None, - Some(g_idx) => { - return Some(window_end + g_idx + self.guard_reverse_idx); - } - } - } - } - } - } - - return Some(window_end); - } - } - - /// Compute the ufast skip table. - fn compile_skip_table(pattern: &[u8]) -> Vec<usize> { - let mut tab = vec![pattern.len(); 256]; - - // For every char in the pattern, we write a skip - // that will line us up with the rightmost occurrence. - // - // N.B. the sentinel (0) is written by the last - // loop iteration. - for (i, c) in pattern.iter().enumerate() { - tab[*c as usize] = (pattern.len() - 1) - i; - } - - tab - } - - /// Select the guard character based off of the precomputed - /// frequency table. - fn select_guard(pattern: &[u8]) -> (u8, usize) { - let mut rarest = pattern[0]; - let mut rarest_rev_idx = pattern.len() - 1; - for (i, c) in pattern.iter().enumerate() { - if freq_rank(*c) < freq_rank(rarest) { - rarest = *c; - rarest_rev_idx = (pattern.len() - 1) - i; - } - } - - (rarest, rarest_rev_idx) - } - - /// If there is another occurrence of the skip - /// char, shift to it, otherwise just shift to - /// the next window. - fn compile_md2_shift(pattern: &[u8]) -> usize { - let shiftc = *pattern.last().unwrap(); - - // For a pattern of length 1 we will never apply the - // shift rule, so we use a poison value on the principle - // that failing fast is a good thing. - if pattern.len() == 1 { - return 0xDEADBEAF; - } - - let mut i = pattern.len() - 2; - while i > 0 { - if pattern[i] == shiftc { - return (pattern.len() - 1) - i; - } - i -= 1; - } - - // The skip char never re-occurs in the pattern, so - // we can just shift the whole window length. - pattern.len() - 1 - } - - fn approximate_size(&self) -> usize { - (self.pattern.len() * mem::size_of::<u8>()) - + (256 * mem::size_of::<usize>()) // skip table - } -} - -fn freq_rank(b: u8) -> usize { - BYTE_FREQUENCIES[b as usize] as usize -} - -#[cfg(test)] -mod tests { - use super::{BoyerMooreSearch, FreqyPacked}; - - // - // Unit Tests - // - - // The "hello, world" of string searching - #[test] - fn bm_find_subs() { - let searcher = BoyerMooreSearch::new(Vec::from(&b"pattern"[..])); - let haystack = b"I keep seeing patterns in this text"; - assert_eq!(14, searcher.find(haystack).unwrap()); - } - - #[test] - fn bm_find_no_subs() { - let searcher = BoyerMooreSearch::new(Vec::from(&b"pattern"[..])); - let haystack = b"I keep seeing needles in this text"; - assert_eq!(None, searcher.find(haystack)); - } - - // - // Regression Tests - // - - #[test] - fn bm_skip_reset_bug() { - let haystack = vec![0, 0, 0, 0, 0, 1, 1, 0]; - let needle = vec![0, 1, 1, 0]; - - let searcher = BoyerMooreSearch::new(needle); - let offset = searcher.find(haystack.as_slice()).unwrap(); - assert_eq!(4, offset); - } - - #[test] - fn bm_backstop_underflow_bug() { - let haystack = vec![0, 0]; - let needle = vec![0, 0]; - - let searcher = BoyerMooreSearch::new(needle); - let offset = searcher.find(haystack.as_slice()).unwrap(); - assert_eq!(0, offset); - } - - #[test] - fn bm_naive_off_by_one_bug() { - let haystack = vec![91]; - let needle = vec![91]; - - let naive_offset = naive_find(needle, haystack.as_slice()).unwrap(); - assert_eq!(0, naive_offset); - } - - #[test] - fn bm_memchr_fallback_indexing_bug() { - let mut haystack = vec![ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 87, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - let needle = vec![1, 1, 1, 1, 32, 32, 87]; - let needle_start = haystack.len(); - haystack.extend(needle.clone()); - - let searcher = BoyerMooreSearch::new(needle); - assert_eq!(needle_start, searcher.find(haystack.as_slice()).unwrap()); - } - - #[test] - #[should_panic] - fn bm_backstop_boundary() { - let haystack = b"\ -// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -e_data.clone_created(entity_id, entity_to_add.entity_id); -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -".to_vec(); - let needle = b"clone_created".to_vec(); - - let searcher = BoyerMooreSearch::new(needle); - let result = searcher.find(&haystack); - assert_eq!(Some(43), result); - } - - #[test] - fn bm_win_gnu_indexing_bug() { - let haystack_raw = vec![ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - let needle = vec![1, 1, 1, 1, 1, 1, 1]; - let haystack = haystack_raw.as_slice(); - - BoyerMooreSearch::new(needle.clone()).find(haystack); - } - - // - // QuickCheck Properties - // - - use quickcheck::TestResult; - - fn naive_find(needle: Vec<u8>, haystack: &[u8]) -> Option<usize> { - assert!(needle.len() <= haystack.len()); - - for i in 0..(haystack.len() - (needle.len() - 1)) { - if haystack[i] == needle[0] - && &haystack[i..(i+needle.len())] == needle.as_slice() { - return Some(i) - } - } - - None - } - - quickcheck! { - fn qc_bm_equals_nieve_find(pile1: Vec<u8>, pile2: Vec<u8>) -> TestResult { - if pile1.len() == 0 || pile2.len() == 0 { - return TestResult::discard(); - } - - let (needle, haystack) = if pile1.len() < pile2.len() { - (pile1, pile2.as_slice()) - } else { - (pile2, pile1.as_slice()) - }; - - let searcher = BoyerMooreSearch::new(needle.clone()); - TestResult::from_bool( - searcher.find(haystack) == naive_find(needle, haystack)) - } - - fn qc_bm_equals_single(pile1: Vec<u8>, pile2: Vec<u8>) -> TestResult { - if pile1.len() == 0 || pile2.len() == 0 { - return TestResult::discard(); - } - - let (needle, haystack) = if pile1.len() < pile2.len() { - (pile1, pile2.as_slice()) - } else { - (pile2, pile1.as_slice()) - }; - - let bm_searcher = BoyerMooreSearch::new(needle.clone()); - let freqy_memchr = FreqyPacked::new(needle); - TestResult::from_bool( - bm_searcher.find(haystack) == freqy_memchr.find(haystack)) - } - - fn qc_bm_finds_trailing_needle( - haystack_pre: Vec<u8>, - needle: Vec<u8> - ) -> TestResult { - if needle.len() == 0 { - return TestResult::discard(); - } - - let mut haystack = haystack_pre.clone(); - let searcher = BoyerMooreSearch::new(needle.clone()); - - if haystack.len() >= needle.len() && - searcher.find(haystack.as_slice()).is_some() { - return TestResult::discard(); - } - - haystack.extend(needle.clone()); - - // What if the the tail of the haystack can start the - // needle? - let start = haystack_pre.len() - .checked_sub(needle.len()) - .unwrap_or(0); - for i in 0..(needle.len() - 1) { - if searcher.find(&haystack[(i + start)..]).is_some() { - return TestResult::discard(); - } - } - - TestResult::from_bool( - searcher.find(haystack.as_slice()) - .map(|x| x == haystack_pre.len()) - .unwrap_or(false)) - } - - fn qc_bm_finds_first(needle: Vec<u8>) -> TestResult { - if needle.len() == 0 { - return TestResult::discard(); - } - - let mut haystack = needle.clone(); - let searcher = BoyerMooreSearch::new(needle.clone()); - haystack.extend(needle); - - TestResult::from_bool( - searcher.find(haystack.as_slice()) - .map(|x| x == 0) - .unwrap_or(false)) - } - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/pattern.rs cargo-0.26.0/vendor/regex-0.2.6/src/pattern.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/pattern.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/pattern.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -use std::str::pattern::{Pattern, Searcher, SearchStep}; - -use re_unicode::{Regex, Matches}; - -pub struct RegexSearcher<'r, 't> { - haystack: &'t str, - it: Matches<'r, 't>, - last_step_end: usize, - next_match: Option<(usize, usize)>, -} - -impl<'r, 't> Pattern<'t> for &'r Regex { - type Searcher = RegexSearcher<'r, 't>; - - fn into_searcher(self, haystack: &'t str) -> RegexSearcher<'r, 't> { - RegexSearcher { - haystack: haystack, - it: self.find_iter(haystack), - last_step_end: 0, - next_match: None, - } - } -} - -unsafe impl<'r, 't> Searcher<'t> for RegexSearcher<'r, 't> { - #[inline] - fn haystack(&self) -> &'t str { - self.haystack - } - - #[inline] - fn next(&mut self) -> SearchStep { - if let Some((s, e)) = self.next_match { - self.next_match = None; - self.last_step_end = e; - return SearchStep::Match(s, e); - } - match self.it.next() { - None => { - if self.last_step_end < self.haystack().len() { - let last = self.last_step_end; - self.last_step_end = self.haystack().len(); - SearchStep::Reject(last, self.haystack().len()) - } else { - SearchStep::Done - } - } - Some(m) => { - let (s, e) = (m.start(), m.end()); - if s == self.last_step_end { - self.last_step_end = e; - SearchStep::Match(s, e) - } else { - self.next_match = Some((s, e)); - let last = self.last_step_end; - self.last_step_end = s; - SearchStep::Reject(last, s) - } - } - } - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/pikevm.rs cargo-0.26.0/vendor/regex-0.2.6/src/pikevm.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/pikevm.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/pikevm.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,377 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// This module implements the Pike VM. That is, it guarantees linear time -// search of a regex on any text with memory use proportional to the size of -// the regex. -// -// It is equal in power to the backtracking engine in this crate, except the -// backtracking engine is typically faster on small regexes/texts at the -// expense of a bigger memory footprint. -// -// It can do more than the DFA can (specifically, record capture locations -// and execute Unicode word boundary assertions), but at a slower speed. -// Specifically, the Pike VM exectues a DFA implicitly by repeatedly expanding -// epsilon transitions. That is, the Pike VM engine can be in multiple states -// at once where as the DFA is only ever in one state at a time. -// -// Therefore, the Pike VM is generally treated as the fallback when the other -// matching engines either aren't feasible to run or are insufficient. - -use std::mem; - -use exec::ProgramCache; -use input::{Input, InputAt}; -use prog::{Program, InstPtr}; -use re_trait::Slot; -use sparse::SparseSet; - -/// An NFA simulation matching engine. -#[derive(Debug)] -pub struct Fsm<'r, I> { - /// The sequence of opcodes (among other things) that is actually executed. - /// - /// The program may be byte oriented or Unicode codepoint oriented. - prog: &'r Program, - /// An explicit stack used for following epsilon transitions. (This is - /// borrowed from the cache.) - stack: &'r mut Vec<FollowEpsilon>, - /// The input to search. - input: I, -} - -/// A cached allocation that can be reused on each execution. -#[derive(Clone, Debug)] -pub struct Cache { - /// A pair of ordered sets for tracking NFA states. - clist: Threads, - nlist: Threads, - /// An explicit stack used for following epsilon transitions. - stack: Vec<FollowEpsilon>, -} - -/// An ordered set of NFA states and their captures. -#[derive(Clone, Debug)] -struct Threads { - /// An ordered set of opcodes (each opcode is an NFA state). - set: SparseSet, - /// Captures for every NFA state. - /// - /// It is stored in row-major order, where the columns are the capture - /// slots and the rows are the states. - caps: Vec<Slot>, - /// The number of capture slots stored per thread. (Every capture has - /// two slots.) - slots_per_thread: usize, -} - -/// A representation of an explicit stack frame when following epsilon -/// transitions. This is used to avoid recursion. -#[derive(Clone, Debug)] -enum FollowEpsilon { - /// Follow transitions at the given instruction pointer. - IP(InstPtr), - /// Restore the capture slot with the given position in the input. - Capture { slot: usize, pos: Slot }, -} - -impl Cache { - /// Create a new allocation used by the NFA machine to record execution - /// and captures. - pub fn new(_prog: &Program) -> Self { - Cache { - clist: Threads::new(), - nlist: Threads::new(), - stack: vec![], - } - } -} - -impl<'r, I: Input> Fsm<'r, I> { - /// Execute the NFA matching engine. - /// - /// If there's a match, `exec` returns `true` and populates the given - /// captures accordingly. - pub fn exec( - prog: &'r Program, - cache: &ProgramCache, - matches: &mut [bool], - slots: &mut [Slot], - quit_after_match: bool, - input: I, - start: usize, - ) -> bool { - let mut cache = cache.borrow_mut(); - let cache = &mut cache.pikevm; - cache.clist.resize(prog.len(), prog.captures.len()); - cache.nlist.resize(prog.len(), prog.captures.len()); - let at = input.at(start); - Fsm { - prog: prog, - stack: &mut cache.stack, - input: input, - }.exec_( - &mut cache.clist, - &mut cache.nlist, - matches, - slots, - quit_after_match, - at, - ) - } - - fn exec_( - &mut self, - mut clist: &mut Threads, - mut nlist: &mut Threads, - matches: &mut [bool], - slots: &mut [Slot], - quit_after_match: bool, - mut at: InputAt, - ) -> bool { - let mut matched = false; - let mut all_matched = false; - clist.set.clear(); - nlist.set.clear(); -'LOOP: loop { - if clist.set.is_empty() { - // Three ways to bail out when our current set of threads is - // empty. - // - // 1. We have a match---so we're done exploring any possible - // alternatives. Time to quit. (We can't do this if we're - // looking for matches for multiple regexes, unless we know - // they all matched.) - // - // 2. If the expression starts with a '^' we can terminate as - // soon as the last thread dies. - if (matched && matches.len() <= 1) - || all_matched - || (!at.is_start() && self.prog.is_anchored_start) { - break; - } - - // 3. If there's a literal prefix for the program, try to - // jump ahead quickly. If it can't be found, then we can - // bail out early. - if !self.prog.prefixes.is_empty() { - at = match self.input.prefix_at(&self.prog.prefixes, at) { - None => break, - Some(at) => at, - }; - } - } - - // This simulates a preceding '.*?' for every regex by adding - // a state starting at the current position in the input for the - // beginning of the program only if we don't already have a match. - if clist.set.is_empty() - || (!self.prog.is_anchored_start && !all_matched) { - self.add(&mut clist, slots, 0, at); - } - // The previous call to "add" actually inspects the position just - // before the current character. For stepping through the machine, - // we can to look at the current character, so we advance the - // input. - let at_next = self.input.at(at.next_pos()); - for i in 0..clist.set.len() { - let ip = clist.set[i]; - if self.step( - &mut nlist, - matches, - slots, - clist.caps(ip), - ip, - at, - at_next, - ) { - matched = true; - all_matched = all_matched || matches.iter().all(|&b| b); - if quit_after_match { - // If we only care if a match occurs (not its - // position), then we can quit right now. - break 'LOOP; - } - if self.prog.matches.len() == 1 { - // We don't need to check the rest of the threads - // in this set because we've matched something - // ("leftmost-first"). However, we still need to check - // threads in the next set to support things like - // greedy matching. - // - // This is only true on normal regexes. For regex sets, - // we need to mush on to observe other matches. - break; - } - } - } - if at.is_end() { - break; - } - at = at_next; - mem::swap(clist, nlist); - nlist.set.clear(); - } - matched - } - - /// Step through the input, one token (byte or codepoint) at a time. - /// - /// nlist is the set of states that will be processed on the next token - /// in the input. - /// - /// caps is the set of captures passed by the caller of the NFA. They are - /// written to only when a match state is visited. - /// - /// thread_caps is the set of captures set for the current NFA state, ip. - /// - /// at and at_next are the current and next positions in the input. at or - /// at_next may be EOF. - fn step( - &mut self, - nlist: &mut Threads, - matches: &mut [bool], - slots: &mut [Slot], - thread_caps: &mut [Option<usize>], - ip: usize, - at: InputAt, - at_next: InputAt, - ) -> bool { - use prog::Inst::*; - match self.prog[ip] { - Match(match_slot) => { - if match_slot < matches.len() { - matches[match_slot] = true; - } - for (slot, val) in slots.iter_mut().zip(thread_caps.iter()) { - *slot = *val; - } - true - } - Char(ref inst) => { - if inst.c == at.char() { - self.add(nlist, thread_caps, inst.goto, at_next); - } - false - } - Ranges(ref inst) => { - if inst.matches(at.char()) { - self.add(nlist, thread_caps, inst.goto, at_next); - } - false - } - Bytes(ref inst) => { - if let Some(b) = at.byte() { - if inst.matches(b) { - self.add(nlist, thread_caps, inst.goto, at_next); - } - } - false - } - EmptyLook(_) | Save(_) | Split(_) => false, - } - } - - /// Follows epsilon transitions and adds them for processing to nlist, - /// starting at and including ip. - fn add( - &mut self, - nlist: &mut Threads, - thread_caps: &mut [Option<usize>], - ip: usize, - at: InputAt, - ) { - self.stack.push(FollowEpsilon::IP(ip)); - while let Some(frame) = self.stack.pop() { - match frame { - FollowEpsilon::IP(ip) => { - self.add_step(nlist, thread_caps, ip, at); - } - FollowEpsilon::Capture { slot, pos } => { - thread_caps[slot] = pos; - } - } - } - } - - /// A helper function for add that avoids excessive pushing to the stack. - fn add_step( - &mut self, - nlist: &mut Threads, - thread_caps: &mut [Option<usize>], - mut ip: usize, - at: InputAt, - ) { - // Instead of pushing and popping to the stack, we mutate ip as we - // traverse the set of states. We only push to the stack when we - // absolutely need recursion (restoring captures or following a - // branch). - use prog::Inst::*; - loop { - // Don't visit states we've already added. - if nlist.set.contains(ip) { - return; - } - nlist.set.insert(ip); - match self.prog[ip] { - EmptyLook(ref inst) => { - if self.input.is_empty_match(at, inst) { - ip = inst.goto; - } - } - Save(ref inst) => { - if inst.slot < thread_caps.len() { - self.stack.push(FollowEpsilon::Capture { - slot: inst.slot, - pos: thread_caps[inst.slot], - }); - thread_caps[inst.slot] = Some(at.pos()); - } - ip = inst.goto; - } - Split(ref inst) => { - self.stack.push(FollowEpsilon::IP(inst.goto2)); - ip = inst.goto1; - } - Match(_) | Char(_) | Ranges(_) | Bytes(_) => { - let t = &mut nlist.caps(ip); - for (slot, val) in t.iter_mut().zip(thread_caps.iter()) { - *slot = *val; - } - return; - } - } - } - } -} - -impl Threads { - fn new() -> Self { - Threads { - set: SparseSet::new(0), - caps: vec![], - slots_per_thread: 0, - } - } - - fn resize(&mut self, num_insts: usize, ncaps: usize) { - if num_insts == self.set.capacity() { - return; - } - self.slots_per_thread = ncaps * 2; - self.set = SparseSet::new(num_insts); - self.caps = vec![None; self.slots_per_thread * num_insts]; - } - - fn caps(&mut self, pc: usize) -> &mut [Option<usize>] { - let i = pc * self.slots_per_thread; - &mut self.caps[i..i + self.slots_per_thread] - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/prog.rs cargo-0.26.0/vendor/regex-0.2.6/src/prog.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/prog.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/prog.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,425 +0,0 @@ -use std::collections::HashMap; -use std::cmp::Ordering; -use std::fmt; -use std::ops::Deref; -use std::mem; -use std::slice; -use std::sync::Arc; - -use input::Char; -use literals::LiteralSearcher; - -/// `InstPtr` represents the index of an instruction in a regex program. -pub type InstPtr = usize; - -/// Program is a sequence of instructions and various facts about thos -/// instructions. -#[derive(Clone)] -pub struct Program { - /// A sequence of instructions that represents an NFA. - pub insts: Vec<Inst>, - /// Pointers to each Match instruction in the sequence. - /// - /// This is always length 1 unless this program represents a regex set. - pub matches: Vec<InstPtr>, - /// The ordered sequence of all capture groups extracted from the AST. - /// Unnamed groups are `None`. - pub captures: Vec<Option<String>>, - /// Pointers to all named capture groups into `captures`. - pub capture_name_idx: Arc<HashMap<String, usize>>, - /// A pointer to the start instruction. This can vary depending on how - /// the program was compiled. For example, programs for use with the DFA - /// engine have a `.*?` inserted at the beginning of unanchored regular - /// expressions. The actual starting point of the program is after the - /// `.*?`. - pub start: InstPtr, - /// A set of equivalence classes for discriminating bytes in the compiled - /// program. - pub byte_classes: Vec<u8>, - /// When true, this program can only match valid UTF-8. - pub only_utf8: bool, - /// When true, this program uses byte range instructions instead of Unicode - /// range instructions. - pub is_bytes: bool, - /// When true, the program is compiled for DFA matching. For example, this - /// implies `is_bytes` and also inserts a preceding `.*?` for unanchored - /// regexes. - pub is_dfa: bool, - /// When true, the program matches text in reverse (for use only in the - /// DFA). - pub is_reverse: bool, - /// Whether the regex must match from the start of the input. - pub is_anchored_start: bool, - /// Whether the regex must match at the end of the input. - pub is_anchored_end: bool, - /// Whether this program contains a Unicode word boundary instruction. - pub has_unicode_word_boundary: bool, - /// A possibly empty machine for very quickly matching prefix literals. - pub prefixes: LiteralSearcher, - /// A limit on the size of the cache that the DFA is allowed to use while - /// matching. - /// - /// The cache limit specifies approximately how much space we're willing to - /// give to the state cache. Once the state cache exceeds the size, it is - /// wiped and all states must be re-computed. - /// - /// Note that this value does not impact correctness. It can be set to 0 - /// and the DFA will run just fine. (It will only ever store exactly one - /// state in the cache, and will likely run very slowly, but it will work.) - /// - /// Also note that this limit is *per thread of execution*. That is, - /// if the same regex is used to search text across multiple threads - /// simultaneously, then the DFA cache is not shared. Instead, copies are - /// made. - pub dfa_size_limit: usize, -} - -impl Program { - /// Creates an empty instruction sequence. Fields are given default - /// values. - pub fn new() -> Self { - Program { - insts: vec![], - matches: vec![], - captures: vec![], - capture_name_idx: Arc::new(HashMap::new()), - start: 0, - byte_classes: vec![0; 256], - only_utf8: true, - is_bytes: false, - is_dfa: false, - is_reverse: false, - is_anchored_start: false, - is_anchored_end: false, - has_unicode_word_boundary: false, - prefixes: LiteralSearcher::empty(), - dfa_size_limit: 2 * (1<<20), - } - } - - /// If pc is an index to a no-op instruction (like Save), then return the - /// next pc that is not a no-op instruction. - pub fn skip(&self, mut pc: usize) -> usize { - loop { - match self[pc] { - Inst::Save(ref i) => pc = i.goto, - _ => return pc, - } - } - } - - /// Return true if and only if an execution engine at instruction `pc` will - /// always lead to a match. - pub fn leads_to_match(&self, pc: usize) -> bool { - if self.matches.len() > 1 { - // If we have a regex set, then we have more than one ending - // state, so leading to one of those states is generally - // meaningless. - return false; - } - match self[self.skip(pc)] { - Inst::Match(_) => true, - _ => false, - } - } - - /// Returns true if the current configuration demands that an implicit - /// `.*?` be prepended to the instruction sequence. - pub fn needs_dotstar(&self) -> bool { - self.is_dfa && !self.is_reverse && !self.is_anchored_start - } - - /// Returns true if this program uses Byte instructions instead of - /// Char/Range instructions. - pub fn uses_bytes(&self) -> bool { - self.is_bytes || self.is_dfa - } - - /// Returns true if this program exclusively matches valid UTF-8 bytes. - /// - /// That is, if an invalid UTF-8 byte is seen, then no match is possible. - pub fn only_utf8(&self) -> bool { - self.only_utf8 - } - - /// Return the approximate heap usage of this instruction sequence in - /// bytes. - pub fn approximate_size(&self) -> usize { - // The only instruction that uses heap space is Ranges (for - // Unicode codepoint programs) to store non-overlapping codepoint - // ranges. To keep this operation constant time, we ignore them. - (self.len() * mem::size_of::<Inst>()) - + (self.matches.len() * mem::size_of::<InstPtr>()) - + (self.captures.len() * mem::size_of::<Option<String>>()) - + (self.capture_name_idx.len() * - (mem::size_of::<String>() + mem::size_of::<usize>())) - + (self.byte_classes.len() * mem::size_of::<u8>()) - + self.prefixes.approximate_size() - } -} - -impl Deref for Program { - type Target = [Inst]; - - fn deref(&self) -> &Self::Target { - &*self.insts - } -} - -impl fmt::Debug for Program { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use self::Inst::*; - - fn with_goto(cur: usize, goto: usize, fmtd: String) -> String { - if goto == cur + 1 { - fmtd - } else { - format!("{} (goto: {})", fmtd, goto) - } - } - - fn visible_byte(b: u8) -> String { - use std::ascii::escape_default; - let escaped = escape_default(b).collect::<Vec<u8>>(); - String::from_utf8_lossy(&escaped).into_owned() - } - - for (pc, inst) in self.iter().enumerate() { - match *inst { - Match(slot) => { - try!(write!(f, "{:04} Match({:?})", pc, slot)) - } - Save(ref inst) => { - let s = format!("{:04} Save({})", pc, inst.slot); - try!(write!(f, "{}", with_goto(pc, inst.goto, s))); - } - Split(ref inst) => { - try!(write!(f, "{:04} Split({}, {})", - pc, inst.goto1, inst.goto2)); - } - EmptyLook(ref inst) => { - let s = format!("{:?}", inst.look); - try!(write!(f, "{:04} {}", - pc, with_goto(pc, inst.goto, s))); - } - Char(ref inst) => { - let s = format!("{:?}", inst.c); - try!(write!(f, "{:04} {}", - pc, with_goto(pc, inst.goto, s))); - } - Ranges(ref inst) => { - let ranges = inst.ranges - .iter() - .map(|r| format!("{:?}-{:?}", r.0, r.1)) - .collect::<Vec<String>>() - .join(", "); - try!(write!(f, "{:04} {}", - pc, with_goto(pc, inst.goto, ranges))); - } - Bytes(ref inst) => { - let s = format!( - "Bytes({}, {})", - visible_byte(inst.start), - visible_byte(inst.end)); - try!(write!(f, "{:04} {}", - pc, with_goto(pc, inst.goto, s))); - } - } - if pc == self.start { - try!(write!(f, " (start)")); - } - try!(write!(f, "\n")); - } - Ok(()) - } -} - -impl<'a> IntoIterator for &'a Program { - type Item = &'a Inst; - type IntoIter = slice::Iter<'a, Inst>; - fn into_iter(self) -> Self::IntoIter { self.iter() } -} - -/// Inst is an instruction code in a Regex program. -/// -/// Regrettably, a regex program either contains Unicode codepoint -/// instructions (Char and Ranges) or it contains byte instructions (Bytes). -/// A regex program can never contain both. -/// -/// It would be worth investigating splitting this into two distinct types and -/// then figuring out how to make the matching engines polymorphic over those -/// types without sacrificing performance. -/// -/// Other than the benefit of moving invariants into the type system, another -/// benefit is the decreased size. If we remove the `Char` and `Ranges` -/// instructions from the `Inst` enum, then its size shrinks from 40 bytes to -/// 24 bytes. (This is because of the removal of a `Vec` in the `Ranges` -/// variant.) Given that byte based machines are typically much bigger than -/// their Unicode analogues (because they can decode UTF-8 directly), this ends -/// up being a pretty significant savings. -#[derive(Clone, Debug)] -pub enum Inst { - /// Match indicates that the program has reached a match state. - /// - /// The number in the match corresponds to the Nth logical regular - /// expression in this program. This index is always 0 for normal regex - /// programs. Values greater than 0 appear when compiling regex sets, and - /// each match instruction gets its own unique value. The value corresponds - /// to the Nth regex in the set. - Match(usize), - /// Save causes the program to save the current location of the input in - /// the slot indicated by InstSave. - Save(InstSave), - /// Split causes the program to diverge to one of two paths in the - /// program, preferring goto1 in InstSplit. - Split(InstSplit), - /// EmptyLook represents a zero-width assertion in a regex program. A - /// zero-width assertion does not consume any of the input text. - EmptyLook(InstEmptyLook), - /// Char requires the regex program to match the character in InstChar at - /// the current position in the input. - Char(InstChar), - /// Ranges requires the regex program to match the character at the current - /// position in the input with one of the ranges specified in InstRanges. - Ranges(InstRanges), - /// Bytes is like Ranges, except it expresses a single byte range. It is - /// used in conjunction with Split instructions to implement multi-byte - /// character classes. - Bytes(InstBytes), -} - -impl Inst { - /// Returns true if and only if this is a match instruction. - pub fn is_match(&self) -> bool { - match *self { - Inst::Match(_) => true, - _ => false, - } - } -} - -/// Representation of the Save instruction. -#[derive(Clone, Debug)] -pub struct InstSave { - /// The next location to execute in the program. - pub goto: InstPtr, - /// The capture slot (there are two slots for every capture in a regex, - /// including the zeroth capture for the entire match). - pub slot: usize, -} - -/// Representation of the Split instruction. -#[derive(Clone, Debug)] -pub struct InstSplit { - /// The first instruction to try. A match resulting from following goto1 - /// has precedence over a match resulting from following goto2. - pub goto1: InstPtr, - /// The second instruction to try. A match resulting from following goto1 - /// has precedence over a match resulting from following goto2. - pub goto2: InstPtr, -} - -/// Representation of the `EmptyLook` instruction. -#[derive(Clone, Debug)] -pub struct InstEmptyLook { - /// The next location to execute in the program if this instruction - /// succeeds. - pub goto: InstPtr, - /// The type of zero-width assertion to check. - pub look: EmptyLook, -} - -/// The set of zero-width match instructions. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum EmptyLook { - /// Start of line or input. - StartLine, - /// End of line or input. - EndLine, - /// Start of input. - StartText, - /// End of input. - EndText, - /// Word character on one side and non-word character on other. - WordBoundary, - /// Word character on both sides or non-word character on both sides. - NotWordBoundary, - /// ASCII word boundary. - WordBoundaryAscii, - /// Not ASCII word boundary. - NotWordBoundaryAscii, -} - -/// Representation of the Char instruction. -#[derive(Clone, Debug)] -pub struct InstChar { - /// The next location to execute in the program if this instruction - /// succeeds. - pub goto: InstPtr, - /// The character to test. - pub c: char, -} - -/// Representation of the Ranges instruction. -#[derive(Clone, Debug)] -pub struct InstRanges { - /// The next location to execute in the program if this instruction - /// succeeds. - pub goto: InstPtr, - /// The set of Unicode scalar value ranges to test. - pub ranges: Vec<(char, char)>, -} - -impl InstRanges { - /// Tests whether the given input character matches this instruction. - pub fn matches(&self, c: Char) -> bool { - // This speeds up the `match_class_unicode` benchmark by checking - // some common cases quickly without binary search. e.g., Matching - // a Unicode class on predominantly ASCII text. - for r in self.ranges.iter().take(4) { - if c < r.0 { - return false; - } - if c <= r.1 { - return true; - } - } - self.ranges.binary_search_by(|r| { - if r.1 < c { - Ordering::Less - } else if r.0 > c { - Ordering::Greater - } else { - Ordering::Equal - } - }).is_ok() - } - - /// Return the number of distinct characters represented by all of the - /// ranges. - pub fn num_chars(&self) -> usize { - self.ranges.iter() - .map(|&(s, e)| 1 + (e as u32) - (s as u32)) - .fold(0, |acc, len| acc + len) - as usize - } -} - -/// Representation of the Bytes instruction. -#[derive(Clone, Debug)] -pub struct InstBytes { - /// The next location to execute in the program if this instruction - /// succeeds. - pub goto: InstPtr, - /// The start (inclusive) of this byte range. - pub start: u8, - /// The end (inclusive) of this byte range. - pub end: u8, -} - -impl InstBytes { - /// Returns true if and only if the given byte is in this range. - pub fn matches(&self, byte: u8) -> bool { - self.start <= byte && byte <= self.end - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/re_builder.rs cargo-0.26.0/vendor/regex-0.2.6/src/re_builder.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/re_builder.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/re_builder.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,283 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/// The set of user configurable options for compiling zero or more regexes. -#[derive(Clone, Debug)] -#[allow(missing_docs)] -pub struct RegexOptions { - pub pats: Vec<String>, - pub size_limit: usize, - pub dfa_size_limit: usize, - pub case_insensitive: bool, - pub multi_line: bool, - pub dot_matches_new_line: bool, - pub swap_greed: bool, - pub ignore_whitespace: bool, - pub unicode: bool, -} - -impl Default for RegexOptions { - fn default() -> Self { - RegexOptions { - pats: vec![], - size_limit: 10 * (1<<20), - dfa_size_limit: 2 * (1<<20), - case_insensitive: false, - multi_line: false, - dot_matches_new_line: false, - swap_greed: false, - ignore_whitespace: false, - unicode: true, - } - } -} - -macro_rules! define_builder { - ($name:ident, $regex_mod:ident, $only_utf8:expr) => { - pub mod $name { - use error::Error; - use exec::ExecBuilder; - use super::RegexOptions; - - use $regex_mod::Regex; - -/// A configurable builder for a regular expression. -/// -/// A builder can be used to configure how the regex is built, for example, by -/// setting the default flags (which can be overridden in the expression -/// itself) or setting various limits. -pub struct RegexBuilder(RegexOptions); - -impl RegexBuilder { - /// Create a new regular expression builder with the given pattern. - /// - /// If the pattern is invalid, then an error will be returned when - /// `build` is called. - pub fn new(pattern: &str) -> RegexBuilder { - let mut builder = RegexBuilder(RegexOptions::default()); - builder.0.pats.push(pattern.to_owned()); - builder - } - - /// Consume the builder and compile the regular expression. - /// - /// Note that calling `as_str` on the resulting `Regex` will produce the - /// pattern given to `new` verbatim. Notably, it will not incorporate any - /// of the flags set on this builder. - pub fn build(&self) -> Result<Regex, Error> { - ExecBuilder::new_options(self.0.clone()) - .only_utf8($only_utf8) - .build() - .map(Regex::from) - } - - /// Set the value for the case insensitive (`i`) flag. - /// - /// When enabled, letters in the pattern will match both upper case and - /// lower case variants. - pub fn case_insensitive(&mut self, yes: bool) -> &mut RegexBuilder { - self.0.case_insensitive = yes; - self - } - - /// Set the value for the multi-line matching (`m`) flag. - /// - /// When enabled, `^` matches the beginning of lines and `$` matches the - /// end of lines. - /// - /// By default, they match beginning/end of the input. - pub fn multi_line(&mut self, yes: bool) -> &mut RegexBuilder { - self.0.multi_line = yes; - self - } - - /// Set the value for the any character (`s`) flag, where in `.` matches - /// anything when `s` is set and matches anything except for new line when - /// it is not set (the default). - /// - /// N.B. "matches anything" means "any byte" for `regex::bytes::Regex` - /// expressions and means "any Unicode scalar value" for `regex::Regex` - /// expressions. - pub fn dot_matches_new_line(&mut self, yes: bool) -> &mut RegexBuilder { - self.0.dot_matches_new_line = yes; - self - } - - /// Set the value for the greedy swap (`U`) flag. - /// - /// When enabled, a pattern like `a*` is lazy (tries to find shortest - /// match) and `a*?` is greedy (tries to find longest match). - /// - /// By default, `a*` is greedy and `a*?` is lazy. - pub fn swap_greed(&mut self, yes: bool) -> &mut RegexBuilder { - self.0.swap_greed = yes; - self - } - - /// Set the value for the ignore whitespace (`x`) flag. - /// - /// When enabled, whitespace such as new lines and spaces will be ignored - /// between expressions of the pattern, and `#` can be used to start a - /// comment until the next new line. - pub fn ignore_whitespace(&mut self, yes: bool) -> &mut RegexBuilder { - self.0.ignore_whitespace = yes; - self - } - - /// Set the value for the Unicode (`u`) flag. - /// - /// Enabled by default. When disabled, character classes such as `\w` only - /// match ASCII word characters instead of all Unicode word characters. - pub fn unicode(&mut self, yes: bool) -> &mut RegexBuilder { - self.0.unicode = yes; - self - } - - /// Set the approximate size limit of the compiled regular expression. - /// - /// This roughly corresponds to the number of bytes occupied by a single - /// compiled program. If the program exceeds this number, then a - /// compilation error is returned. - pub fn size_limit(&mut self, limit: usize) -> &mut RegexBuilder { - self.0.size_limit = limit; - self - } - - /// Set the approximate size of the cache used by the DFA. - /// - /// This roughly corresponds to the number of bytes that the DFA will - /// use while searching. - /// - /// Note that this is a *per thread* limit. There is no way to set a global - /// limit. In particular, if a regex is used from multiple threads - /// simultaneously, then each thread may use up to the number of bytes - /// specified here. - pub fn dfa_size_limit(&mut self, limit: usize) -> &mut RegexBuilder { - self.0.dfa_size_limit = limit; - self - } -} - } - } -} - -define_builder!(bytes, re_bytes, false); -define_builder!(unicode, re_unicode, true); - -macro_rules! define_set_builder { - ($name:ident, $regex_mod:ident, $only_utf8:expr) => { - pub mod $name { - use error::Error; - use exec::ExecBuilder; - use super::RegexOptions; - - use re_set::$regex_mod::RegexSet; - -/// A configurable builder for a set of regular expressions. -/// -/// A builder can be used to configure how the regexes are built, for example, -/// by setting the default flags (which can be overridden in the expression -/// itself) or setting various limits. -pub struct RegexSetBuilder(RegexOptions); - -impl RegexSetBuilder { - /// Create a new regular expression builder with the given pattern. - /// - /// If the pattern is invalid, then an error will be returned when - /// `build` is called. - pub fn new<I, S>(patterns: I) -> RegexSetBuilder - where S: AsRef<str>, I: IntoIterator<Item=S> { - let mut builder = RegexSetBuilder(RegexOptions::default()); - for pat in patterns { - builder.0.pats.push(pat.as_ref().to_owned()); - } - builder - } - - /// Consume the builder and compile the regular expressions into a set. - pub fn build(&self) -> Result<RegexSet, Error> { - ExecBuilder::new_options(self.0.clone()) - .only_utf8($only_utf8) - .build() - .map(RegexSet::from) - } - - /// Set the value for the case insensitive (`i`) flag. - pub fn case_insensitive(&mut self, yes: bool) -> &mut RegexSetBuilder { - self.0.case_insensitive = yes; - self - } - - /// Set the value for the multi-line matching (`m`) flag. - pub fn multi_line(&mut self, yes: bool) -> &mut RegexSetBuilder { - self.0.multi_line = yes; - self - } - - /// Set the value for the any character (`s`) flag, where in `.` matches - /// anything when `s` is set and matches anything except for new line when - /// it is not set (the default). - /// - /// N.B. "matches anything" means "any byte" for `regex::bytes::RegexSet` - /// expressions and means "any Unicode scalar value" for `regex::RegexSet` - /// expressions. - pub fn dot_matches_new_line(&mut self, yes: bool) -> &mut RegexSetBuilder { - self.0.dot_matches_new_line = yes; - self - } - - /// Set the value for the greedy swap (`U`) flag. - pub fn swap_greed(&mut self, yes: bool) -> &mut RegexSetBuilder { - self.0.swap_greed = yes; - self - } - - /// Set the value for the ignore whitespace (`x`) flag. - pub fn ignore_whitespace(&mut self, yes: bool) -> &mut RegexSetBuilder { - self.0.ignore_whitespace = yes; - self - } - - /// Set the value for the Unicode (`u`) flag. - pub fn unicode(&mut self, yes: bool) -> &mut RegexSetBuilder { - self.0.unicode = yes; - self - } - - /// Set the approximate size limit of the compiled regular expression. - /// - /// This roughly corresponds to the number of bytes occupied by a single - /// compiled program. If the program exceeds this number, then a - /// compilation error is returned. - pub fn size_limit(&mut self, limit: usize) -> &mut RegexSetBuilder { - self.0.size_limit = limit; - self - } - - /// Set the approximate size of the cache used by the DFA. - /// - /// This roughly corresponds to the number of bytes that the DFA will - /// use while searching. - /// - /// Note that this is a *per thread* limit. There is no way to set a global - /// limit. In particular, if a regex is used from multiple threads - /// simulanteously, then each thread may use up to the number of bytes - /// specified here. - pub fn dfa_size_limit(&mut self, limit: usize) -> &mut RegexSetBuilder { - self.0.dfa_size_limit = limit; - self - } -} - } - } -} - -define_set_builder!(set_bytes, bytes, false); -define_set_builder!(set_unicode, unicode, true); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/re_bytes.rs cargo-0.26.0/vendor/regex-0.2.6/src/re_bytes.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/re_bytes.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/re_bytes.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1032 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::borrow::Cow; -use std::collections::HashMap; -use std::fmt; -use std::ops::Index; -use std::str::FromStr; -use std::sync::Arc; - -use memchr::memchr; - -use exec::{Exec, ExecNoSync}; -use expand::expand_bytes; -use error::Error; -use re_builder::bytes::RegexBuilder; -use re_trait::{self, RegularExpression, Locations, SubCapturesPosIter}; - -/// Match represents a single match of a regex in a haystack. -/// -/// The lifetime parameter `'t` refers to the lifetime of the matched text. -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub struct Match<'t> { - text: &'t [u8], - start: usize, - end: usize, -} - -impl<'t> Match<'t> { - /// Returns the starting byte offset of the match in the haystack. - #[inline] - pub fn start(&self) -> usize { - self.start - } - - /// Returns the ending byte offset of the match in the haystack. - #[inline] - pub fn end(&self) -> usize { - self.end - } - - /// Returns the matched text. - #[inline] - pub fn as_bytes(&self) -> &'t [u8] { - &self.text[self.start..self.end] - } - - /// Creates a new match from the given haystack and byte offsets. - #[inline] - fn new(haystack: &'t [u8], start: usize, end: usize) -> Match<'t> { - Match { - text: haystack, - start: start, - end: end, - } - } -} - -/// A compiled regular expression for matching arbitrary bytes. -/// -/// It can be used to search, split or replace text. All searching is done with -/// an implicit `.*?` at the beginning and end of an expression. To force an -/// expression to match the whole string (or a prefix or a suffix), you must -/// use an anchor like `^` or `$` (or `\A` and `\z`). -/// -/// Like the `Regex` type in the parent module, matches with this regex return -/// byte offsets into the search text. **Unlike** the parent `Regex` type, -/// these byte offsets may not correspond to UTF-8 sequence boundaries since -/// the regexes in this module can match arbitrary bytes. -#[derive(Clone)] -pub struct Regex(Exec); - -impl fmt::Display for Regex { - /// Shows the original regular expression. - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.as_str()) - } -} - -impl fmt::Debug for Regex { - /// Shows the original regular expression. - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(self, f) - } -} - -/// A constructor for Regex from an Exec. -/// -/// This is hidden because Exec isn't actually part of the public API. -#[doc(hidden)] -impl From<Exec> for Regex { - fn from(exec: Exec) -> Regex { - Regex(exec) - } -} - -impl FromStr for Regex { - type Err = Error; - - /// Attempts to parse a string into a regular expression - fn from_str(s: &str) -> Result<Regex, Error> { - Regex::new(s) - } -} - -/// Core regular expression methods. -impl Regex { - /// Compiles a regular expression. Once compiled, it can be used repeatedly - /// to search, split or replace text in a string. - /// - /// If an invalid expression is given, then an error is returned. - pub fn new(re: &str) -> Result<Regex, Error> { - RegexBuilder::new(re).build() - } - - /// Returns true if and only if the regex matches the string given. - /// - /// It is recommended to use this method if all you need to do is test - /// a match, since the underlying matching engine may be able to do less - /// work. - /// - /// # Example - /// - /// Test if some text contains at least one word with exactly 13 ASCII word - /// bytes: - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # fn main() { - /// let text = b"I categorically deny having triskaidekaphobia."; - /// assert!(Regex::new(r"\b\w{13}\b").unwrap().is_match(text)); - /// # } - /// ``` - pub fn is_match(&self, text: &[u8]) -> bool { - self.is_match_at(text, 0) - } - - /// Returns the start and end byte range of the leftmost-first match in - /// `text`. If no match exists, then `None` is returned. - /// - /// Note that this should only be used if you want to discover the position - /// of the match. Testing the existence of a match is faster if you use - /// `is_match`. - /// - /// # Example - /// - /// Find the start and end location of the first word with exactly 13 - /// ASCII word bytes: - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # fn main() { - /// let text = b"I categorically deny having triskaidekaphobia."; - /// let mat = Regex::new(r"\b\w{13}\b").unwrap().find(text).unwrap(); - /// assert_eq!((mat.start(), mat.end()), (2, 15)); - /// # } - /// ``` - pub fn find<'t>(&self, text: &'t [u8]) -> Option<Match<'t>> { - self.find_at(text, 0) - } - - /// Returns an iterator for each successive non-overlapping match in - /// `text`, returning the start and end byte indices with respect to - /// `text`. - /// - /// # Example - /// - /// Find the start and end location of every word with exactly 13 ASCII - /// word bytes: - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # fn main() { - /// let text = b"Retroactively relinquishing remunerations is reprehensible."; - /// for mat in Regex::new(r"\b\w{13}\b").unwrap().find_iter(text) { - /// println!("{:?}", mat); - /// } - /// # } - /// ``` - pub fn find_iter<'r, 't>(&'r self, text: &'t [u8]) -> Matches<'r, 't> { - Matches(self.0.searcher().find_iter(text)) - } - - /// Returns the capture groups corresponding to the leftmost-first - /// match in `text`. Capture group `0` always corresponds to the entire - /// match. If no match is found, then `None` is returned. - /// - /// You should only use `captures` if you need access to the location of - /// capturing group matches. Otherwise, `find` is faster for discovering - /// the location of the overall match. - /// - /// # Examples - /// - /// Say you have some text with movie names and their release years, - /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text - /// looking like that, while also extracting the movie name and its release - /// year separately. - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # fn main() { - /// let re = Regex::new(r"'([^']+)'\s+\((\d{4})\)").unwrap(); - /// let text = b"Not my favorite movie: 'Citizen Kane' (1941)."; - /// let caps = re.captures(text).unwrap(); - /// assert_eq!(&caps[1], &b"Citizen Kane"[..]); - /// assert_eq!(&caps[2], &b"1941"[..]); - /// assert_eq!(&caps[0], &b"'Citizen Kane' (1941)"[..]); - /// // You can also access the groups by index using the Index notation. - /// // Note that this will panic on an invalid index. - /// assert_eq!(&caps[1], b"Citizen Kane"); - /// assert_eq!(&caps[2], b"1941"); - /// assert_eq!(&caps[0], b"'Citizen Kane' (1941)"); - /// # } - /// ``` - /// - /// Note that the full match is at capture group `0`. Each subsequent - /// capture group is indexed by the order of its opening `(`. - /// - /// We can make this example a bit clearer by using *named* capture groups: - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # fn main() { - /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)") - /// .unwrap(); - /// let text = b"Not my favorite movie: 'Citizen Kane' (1941)."; - /// let caps = re.captures(text).unwrap(); - /// assert_eq!(&caps["title"], &b"Citizen Kane"[..]); - /// assert_eq!(&caps["year"], &b"1941"[..]); - /// assert_eq!(&caps[0], &b"'Citizen Kane' (1941)"[..]); - /// // You can also access the groups by name using the Index notation. - /// // Note that this will panic on an invalid group name. - /// assert_eq!(&caps["title"], b"Citizen Kane"); - /// assert_eq!(&caps["year"], b"1941"); - /// assert_eq!(&caps[0], b"'Citizen Kane' (1941)"); - /// - /// # } - /// ``` - /// - /// Here we name the capture groups, which we can access with the `name` - /// method or the `Index` notation with a `&str`. Note that the named - /// capture groups are still accessible with `get` or the `Index` notation - /// with a `usize`. - /// - /// The `0`th capture group is always unnamed, so it must always be - /// accessed with `get(0)` or `[0]`. - pub fn captures<'t>(&self, text: &'t [u8]) -> Option<Captures<'t>> { - let mut locs = self.locations(); - self.read_captures_at(&mut locs, text, 0).map(|_| Captures { - text: text, - locs: locs, - named_groups: self.0.capture_name_idx().clone(), - }) - } - - /// Returns an iterator over all the non-overlapping capture groups matched - /// in `text`. This is operationally the same as `find_iter`, except it - /// yields information about capturing group matches. - /// - /// # Example - /// - /// We can use this to find all movie titles and their release years in - /// some text, where the movie is formatted like "'Title' (xxxx)": - /// - /// ```rust - /// # extern crate regex; use std::str; use regex::bytes::Regex; - /// # fn main() { - /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)") - /// .unwrap(); - /// let text = b"'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931)."; - /// for caps in re.captures_iter(text) { - /// let title = str::from_utf8(&caps["title"]).unwrap(); - /// let year = str::from_utf8(&caps["year"]).unwrap(); - /// println!("Movie: {:?}, Released: {:?}", title, year); - /// } - /// // Output: - /// // Movie: Citizen Kane, Released: 1941 - /// // Movie: The Wizard of Oz, Released: 1939 - /// // Movie: M, Released: 1931 - /// # } - /// ``` - pub fn captures_iter<'r, 't>( - &'r self, - text: &'t [u8], - ) -> CaptureMatches<'r, 't> { - CaptureMatches(self.0.searcher().captures_iter(text)) - } - - /// Returns an iterator of substrings of `text` delimited by a match of the - /// regular expression. Namely, each element of the iterator corresponds to - /// text that *isn't* matched by the regular expression. - /// - /// This method will *not* copy the text given. - /// - /// # Example - /// - /// To split a string delimited by arbitrary amounts of spaces or tabs: - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # fn main() { - /// let re = Regex::new(r"[ \t]+").unwrap(); - /// let fields: Vec<&[u8]> = re.split(b"a b \t c\td e").collect(); - /// assert_eq!(fields, vec![ - /// &b"a"[..], &b"b"[..], &b"c"[..], &b"d"[..], &b"e"[..], - /// ]); - /// # } - /// ``` - pub fn split<'r, 't>(&'r self, text: &'t [u8]) -> Split<'r, 't> { - Split { - finder: self.find_iter(text), - last: 0, - } - } - - /// Returns an iterator of at most `limit` substrings of `text` delimited - /// by a match of the regular expression. (A `limit` of `0` will return no - /// substrings.) Namely, each element of the iterator corresponds to text - /// that *isn't* matched by the regular expression. The remainder of the - /// string that is not split will be the last element in the iterator. - /// - /// This method will *not* copy the text given. - /// - /// # Example - /// - /// Get the first two words in some text: - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # fn main() { - /// let re = Regex::new(r"\W+").unwrap(); - /// let fields: Vec<&[u8]> = re.splitn(b"Hey! How are you?", 3).collect(); - /// assert_eq!(fields, vec![&b"Hey"[..], &b"How"[..], &b"are you?"[..]]); - /// # } - /// ``` - pub fn splitn<'r, 't>( - &'r self, - text: &'t [u8], - limit: usize, - ) -> SplitN<'r, 't> { - SplitN { - splits: self.split(text), - n: limit, - } - } - - /// Replaces the leftmost-first match with the replacement provided. The - /// replacement can be a regular byte string (where `$N` and `$name` are - /// expanded to match capture groups) or a function that takes the matches' - /// `Captures` and returns the replaced byte string. - /// - /// If no match is found, then a copy of the byte string is returned - /// unchanged. - /// - /// # Replacement string syntax - /// - /// All instances of `$name` in the replacement text is replaced with the - /// corresponding capture group `name`. - /// - /// `name` may be an integer corresponding to the index of the - /// capture group (counted by order of opening parenthesis where `0` is the - /// entire match) or it can be a name (consisting of letters, digits or - /// underscores) corresponding to a named capture group. - /// - /// If `name` isn't a valid capture group (whether the name doesn't exist - /// or isn't a valid index), then it is replaced with the empty string. - /// - /// The longest possible name is used. e.g., `$1a` looks up the capture - /// group named `1a` and not the capture group at index `1`. To exert more - /// precise control over the name, use braces, e.g., `${1}a`. - /// - /// To write a literal `$` use `$$`. - /// - /// # Examples - /// - /// Note that this function is polymorphic with respect to the replacement. - /// In typical usage, this can just be a normal byte string: - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # fn main() { - /// let re = Regex::new("[^01]+").unwrap(); - /// assert_eq!(re.replace(b"1078910", &b""[..]), &b"1010"[..]); - /// # } - /// ``` - /// - /// But anything satisfying the `Replacer` trait will work. For example, a - /// closure of type `|&Captures| -> Vec<u8>` provides direct access to the - /// captures corresponding to a match. This allows one to access capturing - /// group matches easily: - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # use regex::bytes::Captures; fn main() { - /// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap(); - /// let result = re.replace(b"Springsteen, Bruce", |caps: &Captures| { - /// let mut replacement = caps[2].to_owned(); - /// replacement.push(b' '); - /// replacement.extend(&caps[1]); - /// replacement - /// }); - /// assert_eq!(result, &b"Bruce Springsteen"[..]); - /// # } - /// ``` - /// - /// But this is a bit cumbersome to use all the time. Instead, a simple - /// syntax is supported that expands `$name` into the corresponding capture - /// group. Here's the last example, but using this expansion technique - /// with named capture groups: - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # fn main() { - /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)").unwrap(); - /// let result = re.replace(b"Springsteen, Bruce", &b"$first $last"[..]); - /// assert_eq!(result, &b"Bruce Springsteen"[..]); - /// # } - /// ``` - /// - /// Note that using `$2` instead of `$first` or `$1` instead of `$last` - /// would produce the same result. To write a literal `$` use `$$`. - /// - /// Sometimes the replacement string requires use of curly braces to - /// delineate a capture group replacement and surrounding literal text. - /// For example, if we wanted to join two words together with an - /// underscore: - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # fn main() { - /// let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap(); - /// let result = re.replace(b"deep fried", &b"${first}_$second"[..]); - /// assert_eq!(result, &b"deep_fried"[..]); - /// # } - /// ``` - /// - /// Without the curly braces, the capture group name `first_` would be - /// used, and since it doesn't exist, it would be replaced with the empty - /// string. - /// - /// Finally, sometimes you just want to replace a literal string with no - /// regard for capturing group expansion. This can be done by wrapping a - /// byte string with `NoExpand`: - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # fn main() { - /// use regex::bytes::NoExpand; - /// - /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(\S+)").unwrap(); - /// let result = re.replace(b"Springsteen, Bruce", NoExpand(b"$2 $last")); - /// assert_eq!(result, &b"$2 $last"[..]); - /// # } - /// ``` - pub fn replace<'t, R: Replacer>( - &self, - text: &'t [u8], - rep: R, - ) -> Cow<'t, [u8]> { - self.replacen(text, 1, rep) - } - - /// Replaces all non-overlapping matches in `text` with the replacement - /// provided. This is the same as calling `replacen` with `limit` set to - /// `0`. - /// - /// See the documentation for `replace` for details on how to access - /// capturing group matches in the replacement text. - pub fn replace_all<'t, R: Replacer>( - &self, - text: &'t [u8], - rep: R, - ) -> Cow<'t, [u8]> { - self.replacen(text, 0, rep) - } - - /// Replaces at most `limit` non-overlapping matches in `text` with the - /// replacement provided. If `limit` is 0, then all non-overlapping matches - /// are replaced. - /// - /// See the documentation for `replace` for details on how to access - /// capturing group matches in the replacement text. - pub fn replacen<'t, R: Replacer>( - &self, - text: &'t [u8], - limit: usize, - mut rep: R, - ) -> Cow<'t, [u8]> { - if let Some(rep) = rep.no_expansion() { - let mut it = self.find_iter(text).enumerate().peekable(); - if it.peek().is_none() { - return Cow::Borrowed(text); - } - let mut new = Vec::with_capacity(text.len()); - let mut last_match = 0; - for (i, m) in it { - if limit > 0 && i >= limit { - break - } - new.extend_from_slice(&text[last_match..m.start()]); - new.extend_from_slice(&rep); - last_match = m.end(); - } - new.extend_from_slice(&text[last_match..]); - return Cow::Owned(new); - } - - // The slower path, which we use if the replacement needs access to - // capture groups. - let mut it = self.captures_iter(text).enumerate().peekable(); - if it.peek().is_none() { - return Cow::Borrowed(text); - } - let mut new = Vec::with_capacity(text.len()); - let mut last_match = 0; - for (i, cap) in it { - if limit > 0 && i >= limit { - break - } - // unwrap on 0 is OK because captures only reports matches - let m = cap.get(0).unwrap(); - new.extend_from_slice(&text[last_match..m.start()]); - rep.replace_append(&cap, &mut new); - last_match = m.end(); - } - new.extend_from_slice(&text[last_match..]); - Cow::Owned(new) - } -} - -/// Advanced or "lower level" search methods. -impl Regex { - /// Returns the end location of a match in the text given. - /// - /// This method may have the same performance characteristics as - /// `is_match`, except it provides an end location for a match. In - /// particular, the location returned *may be shorter* than the proper end - /// of the leftmost-first match. - /// - /// # Example - /// - /// Typically, `a+` would match the entire first sequence of `a` in some - /// text, but `shortest_match` can give up as soon as it sees the first - /// `a`. - /// - /// ```rust - /// # extern crate regex; use regex::bytes::Regex; - /// # fn main() { - /// let text = b"aaaaa"; - /// let pos = Regex::new(r"a+").unwrap().shortest_match(text); - /// assert_eq!(pos, Some(1)); - /// # } - /// ``` - pub fn shortest_match(&self, text: &[u8]) -> Option<usize> { - self.shortest_match_at(text, 0) - } - - /// Returns the same as shortest_match, but starts the search at the given - /// offset. - /// - /// The significance of the starting point is that it takes the surrounding - /// context into consideration. For example, the `\A` anchor can only - /// match when `start == 0`. - #[doc(hidden)] - pub fn shortest_match_at( - &self, - text: &[u8], - start: usize, - ) -> Option<usize> { - self.0.searcher().shortest_match_at(text, start) - } - - /// Returns the same as is_match, but starts the search at the given - /// offset. - /// - /// The significance of the starting point is that it takes the surrounding - /// context into consideration. For example, the `\A` anchor can only - /// match when `start == 0`. - #[doc(hidden)] - pub fn is_match_at(&self, text: &[u8], start: usize) -> bool { - self.shortest_match_at(text, start).is_some() - } - - /// Returns the same as find, but starts the search at the given - /// offset. - /// - /// The significance of the starting point is that it takes the surrounding - /// context into consideration. For example, the `\A` anchor can only - /// match when `start == 0`. - #[doc(hidden)] - pub fn find_at<'t>( - &self, - text: &'t [u8], - start: usize, - ) -> Option<Match<'t>> { - self.0.searcher().find_at(text, start) - .map(|(s, e)| Match::new(text, s, e)) - } - - /// Returns the same as captures, but starts the search at the given - /// offset and populates the capture locations given. - /// - /// The significance of the starting point is that it takes the surrounding - /// context into consideration. For example, the `\A` anchor can only - /// match when `start == 0`. - #[doc(hidden)] - pub fn read_captures_at<'t>( - &self, - locs: &mut Locations, - text: &'t [u8], - start: usize, - ) -> Option<Match<'t>> { - self.0.searcher().read_captures_at(locs, text, start) - .map(|(s, e)| Match::new(text, s, e)) - } -} - -/// Auxiliary methods. -impl Regex { - /// Returns the original string of this regex. - pub fn as_str(&self) -> &str { - &self.0.regex_strings()[0] - } - - /// Returns an iterator over the capture names. - pub fn capture_names(&self) -> CaptureNames { - CaptureNames(self.0.capture_names().iter()) - } - - /// Returns the number of captures. - pub fn captures_len(&self) -> usize { - self.0.capture_names().len() - } - - /// Returns an empty set of locations that can be reused in multiple calls - /// to `read_captures`. - #[doc(hidden)] - pub fn locations(&self) -> Locations { - self.0.searcher().locations() - } -} - -/// An iterator over all non-overlapping matches for a particular string. -/// -/// The iterator yields a tuple of integers corresponding to the start and end -/// of the match. The indices are byte offsets. The iterator stops when no more -/// matches can be found. -/// -/// `'r` is the lifetime of the compiled regular expression and `'t` is the -/// lifetime of the matched byte string. -pub struct Matches<'r, 't>(re_trait::Matches<'t, ExecNoSync<'r>>); - -impl<'r, 't> Iterator for Matches<'r, 't> { - type Item = Match<'t>; - - fn next(&mut self) -> Option<Match<'t>> { - let text = self.0.text(); - self.0.next().map(|(s, e)| Match::new(text, s, e)) - } -} - -/// An iterator that yields all non-overlapping capture groups matching a -/// particular regular expression. -/// -/// The iterator stops when no more matches can be found. -/// -/// `'r` is the lifetime of the compiled regular expression and `'t` is the -/// lifetime of the matched byte string. -pub struct CaptureMatches<'r, 't>(re_trait::CaptureMatches<'t, ExecNoSync<'r>>); - -impl<'r, 't> Iterator for CaptureMatches<'r, 't> { - type Item = Captures<'t>; - - fn next(&mut self) -> Option<Captures<'t>> { - self.0.next().map(|locs| Captures { - text: self.0.text(), - locs: locs, - named_groups: self.0.regex().capture_name_idx().clone(), - }) - } -} - -/// Yields all substrings delimited by a regular expression match. -/// -/// `'r` is the lifetime of the compiled regular expression and `'t` is the -/// lifetime of the byte string being split. -pub struct Split<'r, 't> { - finder: Matches<'r, 't>, - last: usize, -} - -impl<'r, 't> Iterator for Split<'r, 't> { - type Item = &'t [u8]; - - fn next(&mut self) -> Option<&'t [u8]> { - let text = self.finder.0.text(); - match self.finder.next() { - None => { - if self.last >= text.len() { - None - } else { - let s = &text[self.last..]; - self.last = text.len(); - Some(s) - } - } - Some(m) => { - let matched = &text[self.last..m.start()]; - self.last = m.end(); - Some(matched) - } - } - } -} - -/// Yields at most `N` substrings delimited by a regular expression match. -/// -/// The last substring will be whatever remains after splitting. -/// -/// `'r` is the lifetime of the compiled regular expression and `'t` is the -/// lifetime of the byte string being split. -pub struct SplitN<'r, 't> { - splits: Split<'r, 't>, - n: usize, -} - -impl<'r, 't> Iterator for SplitN<'r, 't> { - type Item = &'t [u8]; - - fn next(&mut self) -> Option<&'t [u8]> { - if self.n == 0 { - return None - } - self.n -= 1; - if self.n == 0 { - let text = self.splits.finder.0.text(); - Some(&text[self.splits.last..]) - } else { - self.splits.next() - } - } -} - -/// An iterator over the names of all possible captures. -/// -/// `None` indicates an unnamed capture; the first element (capture 0, the -/// whole matched region) is always unnamed. -/// -/// `'r` is the lifetime of the compiled regular expression. -pub struct CaptureNames<'r>(::std::slice::Iter<'r, Option<String>>); - -impl<'r> Iterator for CaptureNames<'r> { - type Item = Option<&'r str>; - - fn next(&mut self) -> Option<Option<&'r str>> { - self.0.next().as_ref() - .map(|slot| slot.as_ref().map(|name| name.as_ref())) - } - - fn size_hint(&self) -> (usize, Option<usize>) { - self.0.size_hint() - } -} - -/// Captures represents a group of captured byte strings for a single match. -/// -/// The 0th capture always corresponds to the entire match. Each subsequent -/// index corresponds to the next capture group in the regex. If a capture -/// group is named, then the matched byte string is *also* available via the -/// `name` method. (Note that the 0th capture is always unnamed and so must be -/// accessed with the `get` method.) -/// -/// Positions returned from a capture group are always byte indices. -/// -/// `'t` is the lifetime of the matched text. -pub struct Captures<'t> { - text: &'t [u8], - locs: Locations, - named_groups: Arc<HashMap<String, usize>>, -} - -impl<'t> Captures<'t> { - /// Returns the match associated with the capture group at index `i`. If - /// `i` does not correspond to a capture group, or if the capture group - /// did not participate in the match, then `None` is returned. - /// - /// # Examples - /// - /// Get the text of the match with a default of an empty string if this - /// group didn't participate in the match: - /// - /// ```rust - /// # use regex::bytes::Regex; - /// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap(); - /// let caps = re.captures(b"abc123").unwrap(); - /// - /// let text1 = caps.get(1).map_or(&b""[..], |m| m.as_bytes()); - /// let text2 = caps.get(2).map_or(&b""[..], |m| m.as_bytes()); - /// assert_eq!(text1, &b"123"[..]); - /// assert_eq!(text2, &b""[..]); - /// ``` - pub fn get(&self, i: usize) -> Option<Match<'t>> { - self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e)) - } - - /// Returns the match for the capture group named `name`. If `name` isn't a - /// valid capture group or didn't match anything, then `None` is returned. - pub fn name(&self, name: &str) -> Option<Match<'t>> { - self.named_groups.get(name).and_then(|&i| self.get(i)) - } - - /// An iterator that yields all capturing matches in the order in which - /// they appear in the regex. If a particular capture group didn't - /// participate in the match, then `None` is yielded for that capture. - /// - /// The first match always corresponds to the overall match of the regex. - pub fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 't> { - SubCaptureMatches { - caps: self, - it: self.locs.iter(), - } - } - - /// Expands all instances of `$name` in `replacement` to the corresponding - /// capture group `name`, and writes them to the `dst` buffer given. - /// - /// `name` may be an integer corresponding to the index of the - /// capture group (counted by order of opening parenthesis where `0` is the - /// entire match) or it can be a name (consisting of letters, digits or - /// underscores) corresponding to a named capture group. - /// - /// If `name` isn't a valid capture group (whether the name doesn't exist - /// or isn't a valid index), then it is replaced with the empty string. - /// - /// The longest possible name is used. e.g., `$1a` looks up the capture - /// group named `1a` and not the capture group at index `1`. To exert more - /// precise control over the name, use braces, e.g., `${1}a`. - /// - /// To write a literal `$` use `$$`. - pub fn expand(&self, replacement: &[u8], dst: &mut Vec<u8>) { - expand_bytes(self, replacement, dst) - } - - /// Returns the number of captured groups. - /// - /// This is always at least `1`, since every regex has at least one capture - /// group that corresponds to the full match. - #[inline] - pub fn len(&self) -> usize { - self.locs.len() - } -} - -impl<'t> fmt::Debug for Captures<'t> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_tuple("Captures").field(&CapturesDebug(self)).finish() - } -} - -struct CapturesDebug<'c, 't: 'c>(&'c Captures<'t>); - -impl<'c, 't> fmt::Debug for CapturesDebug<'c, 't> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fn escape_bytes(bytes: &[u8]) -> String { - let mut s = String::new(); - for &b in bytes { - s.push_str(&escape_byte(b)); - } - s - } - - fn escape_byte(byte: u8) -> String { - use std::ascii::escape_default; - - let escaped: Vec<u8> = escape_default(byte).collect(); - String::from_utf8_lossy(&escaped).into_owned() - } - - // We'd like to show something nice here, even if it means an - // allocation to build a reverse index. - let slot_to_name: HashMap<&usize, &String> = - self.0.named_groups.iter().map(|(a, b)| (b, a)).collect(); - let mut map = f.debug_map(); - for (slot, m) in self.0.locs.iter().enumerate() { - let m = m.map(|(s, e)| escape_bytes(&self.0.text[s..e])); - if let Some(name) = slot_to_name.get(&slot) { - map.entry(&name, &m); - } else { - map.entry(&slot, &m); - } - } - map.finish() - } -} - -/// Get a group by index. -/// -/// `'t` is the lifetime of the matched text. -/// -/// The text can't outlive the `Captures` object if this method is -/// used, because of how `Index` is defined (normally `a[i]` is part -/// of `a` and can't outlive it); to do that, use `get()` instead. -/// -/// # Panics -/// -/// If there is no group at the given index. -impl<'t> Index<usize> for Captures<'t> { - type Output = [u8]; - - fn index(&self, i: usize) -> &[u8] { - self.get(i).map(|m| m.as_bytes()) - .unwrap_or_else(|| panic!("no group at index '{}'", i)) - } -} - -/// Get a group by name. -/// -/// `'t` is the lifetime of the matched text and `'i` is the lifetime -/// of the group name (the index). -/// -/// The text can't outlive the `Captures` object if this method is -/// used, because of how `Index` is defined (normally `a[i]` is part -/// of `a` and can't outlive it); to do that, use `name` instead. -/// -/// # Panics -/// -/// If there is no group named by the given value. -impl<'t, 'i> Index<&'i str> for Captures<'t> { - type Output = [u8]; - - fn index<'a>(&'a self, name: &'i str) -> &'a [u8] { - self.name(name).map(|m| m.as_bytes()) - .unwrap_or_else(|| panic!("no group named '{}'", name)) - } -} - -/// An iterator that yields all capturing matches in the order in which they -/// appear in the regex. -/// -/// If a particular capture group didn't participate in the match, then `None` -/// is yielded for that capture. The first match always corresponds to the -/// overall match of the regex. -/// -/// The lifetime `'c` corresponds to the lifetime of the `Captures` value, and -/// the lifetime `'t` corresponds to the originally matched text. -pub struct SubCaptureMatches<'c, 't: 'c> { - caps: &'c Captures<'t>, - it: SubCapturesPosIter<'c>, -} - -impl<'c, 't> Iterator for SubCaptureMatches<'c, 't> { - type Item = Option<Match<'t>>; - - fn next(&mut self) -> Option<Option<Match<'t>>> { - self.it.next() - .map(|cap| cap.map(|(s, e)| Match::new(self.caps.text, s, e))) - } -} - -/// Replacer describes types that can be used to replace matches in a byte -/// string. -/// -/// In general, users of this crate shouldn't need to implement this trait, -/// since implementations are already provided for `&[u8]` and -/// `FnMut(&Captures) -> Vec<u8>`, which covers most use cases. -pub trait Replacer { - /// Appends text to `dst` to replace the current match. - /// - /// The current match is represented by `caps`, which is guaranteed to - /// have a match at capture group `0`. - /// - /// For example, a no-op replacement would be - /// `dst.extend(&caps[0])`. - fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>); - - /// Return a fixed unchanging replacement byte string. - /// - /// When doing replacements, if access to `Captures` is not needed (e.g., - /// the replacement byte string does not need `$` expansion), then it can - /// be beneficial to avoid finding sub-captures. - /// - /// In general, this is called once for every call to `replacen`. - fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, [u8]>> { - None - } -} - -impl<'a> Replacer for &'a [u8] { - fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>) { - caps.expand(*self, dst); - } - - fn no_expansion(&mut self) -> Option<Cow<[u8]>> { - match memchr(b'$', *self) { - Some(_) => None, - None => Some(Cow::Borrowed(*self)), - } - } -} - -impl<F> Replacer for F where F: FnMut(&Captures) -> Vec<u8> { - fn replace_append(&mut self, caps: &Captures, dst: &mut Vec<u8>) { - dst.extend_from_slice(&(*self)(caps)); - } -} - -/// `NoExpand` indicates literal byte string replacement. -/// -/// It can be used with `replace` and `replace_all` to do a literal byte string -/// replacement without expanding `$name` to their corresponding capture -/// groups. This can be both convenient (to avoid escaping `$`, for example) -/// and performant (since capture groups don't need to be found). -/// -/// `'t` is the lifetime of the literal text. -pub struct NoExpand<'t>(pub &'t [u8]); - -impl<'t> Replacer for NoExpand<'t> { - fn replace_append(&mut self, _: &Captures, dst: &mut Vec<u8>) { - dst.extend_from_slice(self.0); - } - - fn no_expansion(&mut self) -> Option<Cow<[u8]>> { - Some(Cow::Borrowed(self.0)) - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/re_set.rs cargo-0.26.0/vendor/regex-0.2.6/src/re_set.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/re_set.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/re_set.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,411 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -macro_rules! define_set { - ($name:ident, $builder_mod:ident, $text_ty:ty, $as_bytes:expr, - $(#[$doc_regexset_example:meta])* ) => { - pub mod $name { - use std::fmt; - use std::iter; - use std::slice; - use std::vec; - - use error::Error; - use exec::Exec; - use re_builder::$builder_mod::RegexSetBuilder; - use re_trait::RegularExpression; - -/// Match multiple (possibly overlapping) regular expressions in a single scan. -/// -/// A regex set corresponds to the union of two or more regular expressions. -/// That is, a regex set will match text where at least one of its -/// constituent regular expressions matches. A regex set as its formulated here -/// provides a touch more power: it will also report *which* regular -/// expressions in the set match. Indeed, this is the key difference between -/// regex sets and a single `Regex` with many alternates, since only one -/// alternate can match at a time. -/// -/// For example, consider regular expressions to match email addresses and -/// domains: `[a-z]+@[a-z]+\.(com|org|net)` and `[a-z]+\.(com|org|net)`. If a -/// regex set is constructed from those regexes, then searching the text -/// `foo@example.com` will report both regexes as matching. Of course, one -/// could accomplish this by compiling each regex on its own and doing two -/// searches over the text. The key advantage of using a regex set is that it -/// will report the matching regexes using a *single pass through the text*. -/// If one has hundreds or thousands of regexes to match repeatedly (like a URL -/// router for a complex web application or a user agent matcher), then a regex -/// set can realize huge performance gains. -/// -/// # Example -/// -/// This shows how the above two regexes (for matching email addresses and -/// domains) might work: -/// -$(#[$doc_regexset_example])* -/// -/// Note that it would be possible to adapt the above example to using `Regex` -/// with an expression like: -/// -/// ```ignore -/// (?P<email>[a-z]+@(?P<email_domain>[a-z]+[.](com|org|net)))|(?P<domain>[a-z]+[.](com|org|net)) -/// ``` -/// -/// After a match, one could then inspect the capture groups to figure out -/// which alternates matched. The problem is that it is hard to make this -/// approach scale when there are many regexes since the overlap between each -/// alternate isn't always obvious to reason about. -/// -/// # Limitations -/// -/// Regex sets are limited to answering the following two questions: -/// -/// 1. Does any regex in the set match? -/// 2. If so, which regexes in the set match? -/// -/// As with the main `Regex` type, it is cheaper to ask (1) instead of (2) -/// since the matching engines can stop after the first match is found. -/// -/// Other features like finding the location of successive matches or their -/// sub-captures aren't supported. If you need this functionality, the -/// recommended approach is to compile each regex in the set independently and -/// selectively match them based on which regexes in the set matched. -/// -/// # Performance -/// -/// A `RegexSet` has the same performance characteristics as `Regex`. Namely, -/// search takes `O(mn)` time, where `m` is proportional to the size of the -/// regex set and `n` is proportional to the length of the search text. -#[derive(Clone)] -pub struct RegexSet(Exec); - -impl RegexSet { - /// Create a new regex set with the given regular expressions. - /// - /// This takes an iterator of `S`, where `S` is something that can produce - /// a `&str`. If any of the strings in the iterator are not valid regular - /// expressions, then an error is returned. - /// - /// # Example - /// - /// Create a new regex set from an iterator of strings: - /// - /// ```rust - /// # use regex::RegexSet; - /// let set = RegexSet::new(&[r"\w+", r"\d+"]).unwrap(); - /// assert!(set.is_match("foo")); - /// ``` - pub fn new<I, S>(exprs: I) -> Result<RegexSet, Error> - where S: AsRef<str>, I: IntoIterator<Item=S> { - RegexSetBuilder::new(exprs).build() - } - - /// Returns true if and only if one of the regexes in this set matches - /// the text given. - /// - /// This method should be preferred if you only need to test whether any - /// of the regexes in the set should match, but don't care about *which* - /// regexes matched. This is because the underlying matching engine will - /// quit immediately after seeing the first match instead of continuing to - /// find all matches. - /// - /// Note that as with searches using `Regex`, the expression is unanchored - /// by default. That is, if the regex does not start with `^` or `\A`, or - /// end with `$` or `\z`, then it is permitted to match anywhere in the - /// text. - /// - /// # Example - /// - /// Tests whether a set matches some text: - /// - /// ```rust - /// # use regex::RegexSet; - /// let set = RegexSet::new(&[r"\w+", r"\d+"]).unwrap(); - /// assert!(set.is_match("foo")); - /// assert!(!set.is_match("☃")); - /// ``` - pub fn is_match(&self, text: $text_ty) -> bool { - self.is_match_at(text, 0) - } - - /// Returns the same as is_match, but starts the search at the given - /// offset. - /// - /// The significance of the starting point is that it takes the surrounding - /// context into consideration. For example, the `\A` anchor can only - /// match when `start == 0`. - #[doc(hidden)] - pub fn is_match_at(&self, text: $text_ty, start: usize) -> bool { - self.0.searcher().is_match_at($as_bytes(text), start) - } - - /// Returns the set of regular expressions that match in the given text. - /// - /// The set returned contains the index of each regular expression that - /// matches in the given text. The index is in correspondence with the - /// order of regular expressions given to `RegexSet`'s constructor. - /// - /// The set can also be used to iterate over the matched indices. - /// - /// Note that as with searches using `Regex`, the expression is unanchored - /// by default. That is, if the regex does not start with `^` or `\A`, or - /// end with `$` or `\z`, then it is permitted to match anywhere in the - /// text. - /// - /// # Example - /// - /// Tests which regular expressions match the given text: - /// - /// ```rust - /// # use regex::RegexSet; - /// let set = RegexSet::new(&[ - /// r"\w+", - /// r"\d+", - /// r"\pL+", - /// r"foo", - /// r"bar", - /// r"barfoo", - /// r"foobar", - /// ]).unwrap(); - /// let matches: Vec<_> = set.matches("foobar").into_iter().collect(); - /// assert_eq!(matches, vec![0, 2, 3, 4, 6]); - /// - /// // You can also test whether a particular regex matched: - /// let matches = set.matches("foobar"); - /// assert!(!matches.matched(5)); - /// assert!(matches.matched(6)); - /// ``` - pub fn matches(&self, text: $text_ty) -> SetMatches { - let mut matches = vec![false; self.0.regex_strings().len()]; - let any = self.read_matches_at(&mut matches, text, 0); - SetMatches { - matched_any: any, - matches: matches, - } - } - - /// Returns the same as matches, but starts the search at the given - /// offset and stores the matches into the slice given. - /// - /// The significance of the starting point is that it takes the surrounding - /// context into consideration. For example, the `\A` anchor can only - /// match when `start == 0`. - /// - /// `matches` must have a length that is at least the number of regexes - /// in this set. - /// - /// This method returns true if and only if at least one member of - /// `matches` is true after executing the set against `text`. - #[doc(hidden)] - pub fn read_matches_at( - &self, - matches: &mut [bool], - text: $text_ty, - start: usize, - ) -> bool { - self.0.searcher().many_matches_at(matches, $as_bytes(text), start) - } - - /// Returns the total number of regular expressions in this set. - pub fn len(&self) -> usize { - self.0.regex_strings().len() - } -} - -/// A set of matches returned by a regex set. -#[derive(Clone, Debug)] -pub struct SetMatches { - matched_any: bool, - matches: Vec<bool>, -} - -impl SetMatches { - /// Whether this set contains any matches. - pub fn matched_any(&self) -> bool { - self.matched_any - } - - /// Whether the regex at the given index matched. - /// - /// The index for a regex is determined by its insertion order upon the - /// initial construction of a `RegexSet`, starting at `0`. - /// - /// # Panics - /// - /// If `regex_index` is greater than or equal to `self.len()`. - pub fn matched(&self, regex_index: usize) -> bool { - self.matches[regex_index] - } - - /// The total number of regexes in the set that created these matches. - pub fn len(&self) -> usize { - self.matches.len() - } - - /// Returns an iterator over indexes in the regex that matched. - pub fn iter(&self) -> SetMatchesIter { - SetMatchesIter((&*self.matches).into_iter().enumerate()) - } -} - -impl IntoIterator for SetMatches { - type IntoIter = SetMatchesIntoIter; - type Item = usize; - - fn into_iter(self) -> Self::IntoIter { - SetMatchesIntoIter(self.matches.into_iter().enumerate()) - } -} - -impl<'a> IntoIterator for &'a SetMatches { - type IntoIter = SetMatchesIter<'a>; - type Item = usize; - - fn into_iter(self) -> Self::IntoIter { - self.iter() - } -} - -/// An owned iterator over the set of matches from a regex set. -pub struct SetMatchesIntoIter(iter::Enumerate<vec::IntoIter<bool>>); - -impl Iterator for SetMatchesIntoIter { - type Item = usize; - - fn next(&mut self) -> Option<usize> { - loop { - match self.0.next() { - None => return None, - Some((_, false)) => {} - Some((i, true)) => return Some(i), - } - } - } -} - -impl DoubleEndedIterator for SetMatchesIntoIter { - fn next_back(&mut self) -> Option<usize> { - loop { - match self.0.next_back() { - None => return None, - Some((_, false)) => {} - Some((i, true)) => return Some(i), - } - } - } -} - -/// A borrowed iterator over the set of matches from a regex set. -/// -/// The lifetime `'a` refers to the lifetime of a `SetMatches` value. -#[derive(Clone)] -pub struct SetMatchesIter<'a>(iter::Enumerate<slice::Iter<'a, bool>>); - -impl<'a> Iterator for SetMatchesIter<'a> { - type Item = usize; - - fn next(&mut self) -> Option<usize> { - loop { - match self.0.next() { - None => return None, - Some((_, &false)) => {} - Some((i, &true)) => return Some(i), - } - } - } -} - -impl<'a> DoubleEndedIterator for SetMatchesIter<'a> { - fn next_back(&mut self) -> Option<usize> { - loop { - match self.0.next_back() { - None => return None, - Some((_, &false)) => {} - Some((i, &true)) => return Some(i), - } - } - } -} - -#[doc(hidden)] -impl From<Exec> for RegexSet { - fn from(exec: Exec) -> Self { - RegexSet(exec) - } -} - -impl fmt::Debug for RegexSet { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "RegexSet({:?})", self.0.regex_strings()) - } -} - -#[allow(dead_code)] fn as_bytes_str(text: &str) -> &[u8] { text.as_bytes() } -#[allow(dead_code)] fn as_bytes_bytes(text: &[u8]) -> &[u8] { text } - } - } -} - -define_set! { - unicode, - set_unicode, - &str, - as_bytes_str, -/// ```rust -/// # use regex::RegexSet; -/// let set = RegexSet::new(&[ -/// r"[a-z]+@[a-z]+\.(com|org|net)", -/// r"[a-z]+\.(com|org|net)", -/// ]).unwrap(); -/// -/// // Ask whether any regexes in the set match. -/// assert!(set.is_match("foo@example.com")); -/// -/// // Identify which regexes in the set match. -/// let matches: Vec<_> = set.matches("foo@example.com").into_iter().collect(); -/// assert_eq!(vec![0, 1], matches); -/// -/// // Try again, but with text that only matches one of the regexes. -/// let matches: Vec<_> = set.matches("example.com").into_iter().collect(); -/// assert_eq!(vec![1], matches); -/// -/// // Try again, but with text that doesn't match any regex in the set. -/// let matches: Vec<_> = set.matches("example").into_iter().collect(); -/// assert!(matches.is_empty()); -/// ``` -} - -define_set! { - bytes, - set_bytes, - &[u8], - as_bytes_bytes, -/// ```rust -/// # use regex::bytes::RegexSet; -/// let set = RegexSet::new(&[ -/// r"[a-z]+@[a-z]+\.(com|org|net)", -/// r"[a-z]+\.(com|org|net)", -/// ]).unwrap(); -/// -/// // Ask whether any regexes in the set match. -/// assert!(set.is_match(b"foo@example.com")); -/// -/// // Identify which regexes in the set match. -/// let matches: Vec<_> = set.matches(b"foo@example.com").into_iter().collect(); -/// assert_eq!(vec![0, 1], matches); -/// -/// // Try again, but with text that only matches one of the regexes. -/// let matches: Vec<_> = set.matches(b"example.com").into_iter().collect(); -/// assert_eq!(vec![1], matches); -/// -/// // Try again, but with text that doesn't match any regex in the set. -/// let matches: Vec<_> = set.matches(b"example").into_iter().collect(); -/// assert!(matches.is_empty()); -/// ``` -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/re_trait.rs cargo-0.26.0/vendor/regex-0.2.6/src/re_trait.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/re_trait.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/re_trait.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,268 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/// Slot is a single saved capture location. Note that there are two slots for -/// every capture in a regular expression (one slot each for the start and end -/// of the capture). -pub type Slot = Option<usize>; - -/// Locations represents the offsets of each capturing group in a regex for -/// a single match. -/// -/// Unlike `Captures`, a `Locations` value only stores offsets. -#[doc(hidden)] -pub struct Locations(Vec<Slot>); - -impl Locations { - /// Returns the start and end positions of the Nth capture group. Returns - /// `None` if `i` is not a valid capture group or if the capture group did - /// not match anything. The positions returned are *always* byte indices - /// with respect to the original string matched. - pub fn pos(&self, i: usize) -> Option<(usize, usize)> { - let (s, e) = (i * 2, i * 2 + 1); - match (self.0.get(s), self.0.get(e)) { - (Some(&Some(s)), Some(&Some(e))) => Some((s, e)), - _ => None, - } - } - - /// Creates an iterator of all the capture group positions in order of - /// appearance in the regular expression. Positions are byte indices - /// in terms of the original string matched. - pub fn iter(&self) -> SubCapturesPosIter { - SubCapturesPosIter { idx: 0, locs: self } - } - - /// Returns the total number of capturing groups. - /// - /// This is always at least `1` since every regex has at least `1` - /// capturing group that corresponds to the entire match. - pub fn len(&self) -> usize { - self.0.len() / 2 - } -} - -/// This is a hack to make Locations -> &mut [Slot] be available internally -/// without exposing it in the public API. -pub fn as_slots(locs: &mut Locations) -> &mut [Slot] { - &mut locs.0 -} - -/// An iterator over capture group positions for a particular match of a -/// regular expression. -/// -/// Positions are byte indices in terms of the original string matched. -/// -/// `'c` is the lifetime of the captures. -pub struct SubCapturesPosIter<'c> { - idx: usize, - locs: &'c Locations, -} - -impl<'c> Iterator for SubCapturesPosIter<'c> { - type Item = Option<(usize, usize)>; - - fn next(&mut self) -> Option<Option<(usize, usize)>> { - if self.idx >= self.locs.len() { - return None; - } - let x = match self.locs.pos(self.idx) { - None => Some(None), - Some((s, e)) => { - Some(Some((s, e))) - } - }; - self.idx += 1; - x - } -} - -/// `RegularExpression` describes types that can implement regex searching. -/// -/// This trait is my attempt at reducing code duplication and to standardize -/// the internal API. Specific duplication that is avoided are the `find` -/// and `capture` iterators, which are slightly tricky. -/// -/// It's not clear whether this trait is worth it, and it also isn't -/// clear whether it's useful as a public trait or not. Methods like -/// `next_after_empty` reak of bad design, but the rest of the methods seem -/// somewhat reasonable. One particular thing this trait would expose would be -/// the ability to start the search of a regex anywhere in a haystack, which -/// isn't possible in the current public API. -pub trait RegularExpression: Sized { - /// The type of the haystack. - type Text: ?Sized; - - /// The number of capture slots in the compiled regular expression. This is - /// always two times the number of capture groups (two slots per group). - fn slots_len(&self) -> usize; - - /// Allocates fresh space for all capturing groups in this regex. - fn locations(&self) -> Locations { - Locations(vec![None; self.slots_len()]) - } - - /// Returns the position of the next character after `i`. - /// - /// For example, a haystack with type `&[u8]` probably returns `i+1`, - /// whereas a haystack with type `&str` probably returns `i` plus the - /// length of the next UTF-8 sequence. - fn next_after_empty(&self, text: &Self::Text, i: usize) -> usize; - - /// Returns the location of the shortest match. - fn shortest_match_at( - &self, - text: &Self::Text, - start: usize, - ) -> Option<usize>; - - /// Returns whether the regex matches the text given. - fn is_match_at( - &self, - text: &Self::Text, - start: usize, - ) -> bool; - - /// Returns the leftmost-first match location if one exists. - fn find_at( - &self, - text: &Self::Text, - start: usize, - ) -> Option<(usize, usize)>; - - /// Returns the leftmost-first match location if one exists, and also - /// fills in any matching capture slot locations. - fn read_captures_at( - &self, - locs: &mut Locations, - text: &Self::Text, - start: usize, - ) -> Option<(usize, usize)>; - - /// Returns an iterator over all non-overlapping successive leftmost-first - /// matches. - fn find_iter ( - self, - text: &Self::Text, - ) -> Matches<Self> { - Matches { - re: self, - text: text, - last_end: 0, - last_match: None, - } - } - - /// Returns an iterator over all non-overlapping successive leftmost-first - /// matches with captures. - fn captures_iter( - self, - text: &Self::Text, - ) -> CaptureMatches<Self> { - CaptureMatches(self.find_iter(text)) - } -} - -/// An iterator over all non-overlapping successive leftmost-first matches. -pub struct Matches<'t, R> where R: RegularExpression, R::Text: 't { - re: R, - text: &'t R::Text, - last_end: usize, - last_match: Option<usize>, -} - -impl<'t, R> Matches<'t, R> where R: RegularExpression, R::Text: 't { - /// Return the text being searched. - pub fn text(&self) -> &'t R::Text { - self.text - } - - /// Return the underlying regex. - pub fn regex(&self) -> &R { - &self.re - } -} - -impl<'t, R> Iterator for Matches<'t, R> - where R: RegularExpression, R::Text: 't + AsRef<[u8]> { - type Item = (usize, usize); - - fn next(&mut self) -> Option<(usize, usize)> { - if self.last_end > self.text.as_ref().len() { - return None; - } - let (s, e) = match self.re.find_at(self.text, self.last_end) { - None => return None, - Some((s, e)) => (s, e), - }; - if s == e { - // This is an empty match. To ensure we make progress, start - // the next search at the smallest possible starting position - // of the next match following this one. - self.last_end = self.re.next_after_empty(self.text, e); - // Don't accept empty matches immediately following a match. - // Just move on to the next match. - if Some(e) == self.last_match { - return self.next(); - } - } else { - self.last_end = e; - } - self.last_match = Some(e); - Some((s, e)) - } -} - -/// An iterator over all non-overlapping successive leftmost-first matches with -/// captures. -pub struct CaptureMatches<'t, R>(Matches<'t, R>) - where R: RegularExpression, R::Text: 't; - -impl<'t, R> CaptureMatches<'t, R> where R: RegularExpression, R::Text: 't { - /// Return the text being searched. - pub fn text(&self) -> &'t R::Text { - self.0.text() - } - - /// Return the underlying regex. - pub fn regex(&self) -> &R { - self.0.regex() - } -} - -impl<'t, R> Iterator for CaptureMatches<'t, R> - where R: RegularExpression, R::Text: 't + AsRef<[u8]> { - type Item = Locations; - - fn next(&mut self) -> Option<Locations> { - if self.0.last_end > self.0.text.as_ref().len() { - return None - } - let mut locs = self.0.re.locations(); - let (s, e) = match self.0.re.read_captures_at( - &mut locs, - self.0.text, - self.0.last_end, - ) { - None => return None, - Some((s, e)) => (s, e), - }; - if s == e { - self.0.last_end = self.0.re.next_after_empty(self.0.text, e); - if Some(e) == self.0.last_match { - return self.next(); - } - } else { - self.0.last_end = e; - } - self.0.last_match = Some(e); - Some(locs) - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/re_unicode.rs cargo-0.26.0/vendor/regex-0.2.6/src/re_unicode.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/re_unicode.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/re_unicode.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1076 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::borrow::Cow; -use std::collections::HashMap; -use std::fmt; -use std::ops::Index; -use std::str::FromStr; -use std::sync::Arc; - -use memchr::memchr; -use syntax; - -use error::Error; -use exec::{Exec, ExecNoSyncStr}; -use expand::expand_str; -use re_builder::unicode::RegexBuilder; -use re_trait::{self, RegularExpression, Locations, SubCapturesPosIter}; - -/// Escapes all regular expression meta characters in `text`. -/// -/// The string returned may be safely used as a literal in a regular -/// expression. -pub fn escape(text: &str) -> String { - syntax::escape(text) -} - -/// Match represents a single match of a regex in a haystack. -/// -/// The lifetime parameter `'t` refers to the lifetime of the matched text. -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub struct Match<'t> { - text: &'t str, - start: usize, - end: usize, -} - -impl<'t> Match<'t> { - /// Returns the starting byte offset of the match in the haystack. - #[inline] - pub fn start(&self) -> usize { - self.start - } - - /// Returns the ending byte offset of the match in the haystack. - #[inline] - pub fn end(&self) -> usize { - self.end - } - - /// Returns the matched text. - #[inline] - pub fn as_str(&self) -> &'t str { - &self.text[self.start..self.end] - } - - /// Creates a new match from the given haystack and byte offsets. - #[inline] - fn new(haystack: &'t str, start: usize, end: usize) -> Match<'t> { - Match { - text: haystack, - start: start, - end: end, - } - } -} - -impl<'t> From<Match<'t>> for &'t str { - fn from(m: Match<'t>) -> &'t str { - m.as_str() - } -} - -/// A compiled regular expression for matching Unicode strings. -/// -/// It is represented as either a sequence of bytecode instructions (dynamic) -/// or as a specialized Rust function (native). It can be used to search, split -/// or replace text. All searching is done with an implicit `.*?` at the -/// beginning and end of an expression. To force an expression to match the -/// whole string (or a prefix or a suffix), you must use an anchor like `^` or -/// `$` (or `\A` and `\z`). -/// -/// While this crate will handle Unicode strings (whether in the regular -/// expression or in the search text), all positions returned are **byte -/// indices**. Every byte index is guaranteed to be at a Unicode code point -/// boundary. -/// -/// The lifetimes `'r` and `'t` in this crate correspond to the lifetime of a -/// compiled regular expression and text to search, respectively. -/// -/// The only methods that allocate new strings are the string replacement -/// methods. All other methods (searching and splitting) return borrowed -/// pointers into the string given. -/// -/// # Examples -/// -/// Find the location of a US phone number: -/// -/// ```rust -/// # use regex::Regex; -/// let re = Regex::new("[0-9]{3}-[0-9]{3}-[0-9]{4}").unwrap(); -/// let mat = re.find("phone: 111-222-3333").unwrap(); -/// assert_eq!((mat.start(), mat.end()), (7, 19)); -/// ``` -/// -/// # Using the `std::str::pattern` methods with `Regex` -/// -/// > **Note**: This section requires that this crate is compiled with the -/// > `pattern` Cargo feature enabled, which **requires nightly Rust**. -/// -/// Since `Regex` implements `Pattern`, you can use regexes with methods -/// defined on `&str`. For example, `is_match`, `find`, `find_iter` -/// and `split` can be replaced with `str::contains`, `str::find`, -/// `str::match_indices` and `str::split`. -/// -/// Here are some examples: -/// -/// ```rust,ignore -/// # use regex::Regex; -/// let re = Regex::new(r"\d+").unwrap(); -/// let haystack = "a111b222c"; -/// -/// assert!(haystack.contains(&re)); -/// assert_eq!(haystack.find(&re), Some(1)); -/// assert_eq!(haystack.match_indices(&re).collect::<Vec<_>>(), -/// vec![(1, 4), (5, 8)]); -/// assert_eq!(haystack.split(&re).collect::<Vec<_>>(), vec!["a", "b", "c"]); -/// ``` -#[derive(Clone)] -pub struct Regex(Exec); - -impl fmt::Display for Regex { - /// Shows the original regular expression. - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.as_str()) - } -} - -impl fmt::Debug for Regex { - /// Shows the original regular expression. - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(self, f) - } -} - -#[doc(hidden)] -impl From<Exec> for Regex { - fn from(exec: Exec) -> Regex { - Regex(exec) - } -} - -impl FromStr for Regex { - type Err = Error; - - /// Attempts to parse a string into a regular expression - fn from_str(s: &str) -> Result<Regex, Error> { - Regex::new(s) - } -} - -/// Core regular expression methods. -impl Regex { - /// Compiles a regular expression. Once compiled, it can be used repeatedly - /// to search, split or replace text in a string. - /// - /// If an invalid expression is given, then an error is returned. - pub fn new(re: &str) -> Result<Regex, Error> { - RegexBuilder::new(re).build() - } - - /// Returns true if and only if the regex matches the string given. - /// - /// It is recommended to use this method if all you need to do is test - /// a match, since the underlying matching engine may be able to do less - /// work. - /// - /// # Example - /// - /// Test if some text contains at least one word with exactly 13 - /// Unicode word characters: - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// let text = "I categorically deny having triskaidekaphobia."; - /// assert!(Regex::new(r"\b\w{13}\b").unwrap().is_match(text)); - /// # } - /// ``` - pub fn is_match(&self, text: &str) -> bool { - self.is_match_at(text, 0) - } - - /// Returns the start and end byte range of the leftmost-first match in - /// `text`. If no match exists, then `None` is returned. - /// - /// Note that this should only be used if you want to discover the position - /// of the match. Testing the existence of a match is faster if you use - /// `is_match`. - /// - /// # Example - /// - /// Find the start and end location of the first word with exactly 13 - /// Unicode word characters: - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// let text = "I categorically deny having triskaidekaphobia."; - /// let mat = Regex::new(r"\b\w{13}\b").unwrap().find(text).unwrap(); - /// assert_eq!(mat.start(), 2); - /// assert_eq!(mat.end(), 15); - /// # } - /// ``` - pub fn find<'t>(&self, text: &'t str) -> Option<Match<'t>> { - self.find_at(text, 0) - } - - /// Returns an iterator for each successive non-overlapping match in - /// `text`, returning the start and end byte indices with respect to - /// `text`. - /// - /// # Example - /// - /// Find the start and end location of every word with exactly 13 Unicode - /// word characters: - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// let text = "Retroactively relinquishing remunerations is reprehensible."; - /// for mat in Regex::new(r"\b\w{13}\b").unwrap().find_iter(text) { - /// println!("{:?}", mat); - /// } - /// # } - /// ``` - pub fn find_iter<'r, 't>(&'r self, text: &'t str) -> Matches<'r, 't> { - Matches(self.0.searcher_str().find_iter(text)) - } - - /// Returns the capture groups corresponding to the leftmost-first - /// match in `text`. Capture group `0` always corresponds to the entire - /// match. If no match is found, then `None` is returned. - /// - /// You should only use `captures` if you need access to the location of - /// capturing group matches. Otherwise, `find` is faster for discovering - /// the location of the overall match. - /// - /// # Examples - /// - /// Say you have some text with movie names and their release years, - /// like "'Citizen Kane' (1941)". It'd be nice if we could search for text - /// looking like that, while also extracting the movie name and its release - /// year separately. - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// let re = Regex::new(r"'([^']+)'\s+\((\d{4})\)").unwrap(); - /// let text = "Not my favorite movie: 'Citizen Kane' (1941)."; - /// let caps = re.captures(text).unwrap(); - /// assert_eq!(caps.get(1).unwrap().as_str(), "Citizen Kane"); - /// assert_eq!(caps.get(2).unwrap().as_str(), "1941"); - /// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)"); - /// // You can also access the groups by index using the Index notation. - /// // Note that this will panic on an invalid index. - /// assert_eq!(&caps[1], "Citizen Kane"); - /// assert_eq!(&caps[2], "1941"); - /// assert_eq!(&caps[0], "'Citizen Kane' (1941)"); - /// # } - /// ``` - /// - /// Note that the full match is at capture group `0`. Each subsequent - /// capture group is indexed by the order of its opening `(`. - /// - /// We can make this example a bit clearer by using *named* capture groups: - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)") - /// .unwrap(); - /// let text = "Not my favorite movie: 'Citizen Kane' (1941)."; - /// let caps = re.captures(text).unwrap(); - /// assert_eq!(&caps["title"], "Citizen Kane"); - /// assert_eq!(&caps["year"], "1941"); - /// assert_eq!(caps.get(0).unwrap().as_str(), "'Citizen Kane' (1941)"); - /// // You can also access the groups by name using the Index notation. - /// // Note that this will panic on an invalid group name. - /// assert_eq!(&caps["title"], "Citizen Kane"); - /// assert_eq!(&caps["year"], "1941"); - /// assert_eq!(&caps[0], "'Citizen Kane' (1941)"); - /// - /// # } - /// ``` - /// - /// Here we name the capture groups, which we can access with the `name` - /// method or the `Index` notation with a `&str`. Note that the named - /// capture groups are still accessible with `get` or the `Index` notation - /// with a `usize`. - /// - /// The `0`th capture group is always unnamed, so it must always be - /// accessed with `get(0)` or `[0]`. - pub fn captures<'t>(&self, text: &'t str) -> Option<Captures<'t>> { - let mut locs = self.locations(); - self.read_captures_at(&mut locs, text, 0).map(|_| Captures { - text: text, - locs: locs, - named_groups: self.0.capture_name_idx().clone(), - }) - } - - /// Returns an iterator over all the non-overlapping capture groups matched - /// in `text`. This is operationally the same as `find_iter`, except it - /// yields information about capturing group matches. - /// - /// # Example - /// - /// We can use this to find all movie titles and their release years in - /// some text, where the movie is formatted like "'Title' (xxxx)": - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// let re = Regex::new(r"'(?P<title>[^']+)'\s+\((?P<year>\d{4})\)") - /// .unwrap(); - /// let text = "'Citizen Kane' (1941), 'The Wizard of Oz' (1939), 'M' (1931)."; - /// for caps in re.captures_iter(text) { - /// println!("Movie: {:?}, Released: {:?}", - /// &caps["title"], &caps["year"]); - /// } - /// // Output: - /// // Movie: Citizen Kane, Released: 1941 - /// // Movie: The Wizard of Oz, Released: 1939 - /// // Movie: M, Released: 1931 - /// # } - /// ``` - pub fn captures_iter<'r, 't>( - &'r self, - text: &'t str, - ) -> CaptureMatches<'r, 't> { - CaptureMatches(self.0.searcher_str().captures_iter(text)) - } - - /// Returns an iterator of substrings of `text` delimited by a match of the - /// regular expression. Namely, each element of the iterator corresponds to - /// text that *isn't* matched by the regular expression. - /// - /// This method will *not* copy the text given. - /// - /// # Example - /// - /// To split a string delimited by arbitrary amounts of spaces or tabs: - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// let re = Regex::new(r"[ \t]+").unwrap(); - /// let fields: Vec<&str> = re.split("a b \t c\td e").collect(); - /// assert_eq!(fields, vec!["a", "b", "c", "d", "e"]); - /// # } - /// ``` - pub fn split<'r, 't>(&'r self, text: &'t str) -> Split<'r, 't> { - Split { - finder: self.find_iter(text), - last: 0, - } - } - - /// Returns an iterator of at most `limit` substrings of `text` delimited - /// by a match of the regular expression. (A `limit` of `0` will return no - /// substrings.) Namely, each element of the iterator corresponds to text - /// that *isn't* matched by the regular expression. The remainder of the - /// string that is not split will be the last element in the iterator. - /// - /// This method will *not* copy the text given. - /// - /// # Example - /// - /// Get the first two words in some text: - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// let re = Regex::new(r"\W+").unwrap(); - /// let fields: Vec<&str> = re.splitn("Hey! How are you?", 3).collect(); - /// assert_eq!(fields, vec!("Hey", "How", "are you?")); - /// # } - /// ``` - pub fn splitn<'r, 't>(&'r self, text: &'t str, limit: usize) - -> SplitN<'r, 't> { - SplitN { - splits: self.split(text), - n: limit, - } - } - - /// Replaces the leftmost-first match with the replacement provided. - /// The replacement can be a regular string (where `$N` and `$name` are - /// expanded to match capture groups) or a function that takes the matches' - /// `Captures` and returns the replaced string. - /// - /// If no match is found, then a copy of the string is returned unchanged. - /// - /// # Replacement string syntax - /// - /// All instances of `$name` in the replacement text is replaced with the - /// corresponding capture group `name`. - /// - /// `name` may be an integer corresponding to the index of the - /// capture group (counted by order of opening parenthesis where `0` is the - /// entire match) or it can be a name (consisting of letters, digits or - /// underscores) corresponding to a named capture group. - /// - /// If `name` isn't a valid capture group (whether the name doesn't exist - /// or isn't a valid index), then it is replaced with the empty string. - /// - /// The longest possible name is used. e.g., `$1a` looks up the capture - /// group named `1a` and not the capture group at index `1`. To exert more - /// precise control over the name, use braces, e.g., `${1}a`. - /// - /// To write a literal `$` use `$$`. - /// - /// # Examples - /// - /// Note that this function is polymorphic with respect to the replacement. - /// In typical usage, this can just be a normal string: - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// let re = Regex::new("[^01]+").unwrap(); - /// assert_eq!(re.replace("1078910", ""), "1010"); - /// # } - /// ``` - /// - /// But anything satisfying the `Replacer` trait will work. For example, - /// a closure of type `|&Captures| -> String` provides direct access to the - /// captures corresponding to a match. This allows one to access - /// capturing group matches easily: - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # use regex::Captures; fn main() { - /// let re = Regex::new(r"([^,\s]+),\s+(\S+)").unwrap(); - /// let result = re.replace("Springsteen, Bruce", |caps: &Captures| { - /// format!("{} {}", &caps[2], &caps[1]) - /// }); - /// assert_eq!(result, "Bruce Springsteen"); - /// # } - /// ``` - /// - /// But this is a bit cumbersome to use all the time. Instead, a simple - /// syntax is supported that expands `$name` into the corresponding capture - /// group. Here's the last example, but using this expansion technique - /// with named capture groups: - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(?P<first>\S+)").unwrap(); - /// let result = re.replace("Springsteen, Bruce", "$first $last"); - /// assert_eq!(result, "Bruce Springsteen"); - /// # } - /// ``` - /// - /// Note that using `$2` instead of `$first` or `$1` instead of `$last` - /// would produce the same result. To write a literal `$` use `$$`. - /// - /// Sometimes the replacement string requires use of curly braces to - /// delineate a capture group replacement and surrounding literal text. - /// For example, if we wanted to join two words together with an - /// underscore: - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// let re = Regex::new(r"(?P<first>\w+)\s+(?P<second>\w+)").unwrap(); - /// let result = re.replace("deep fried", "${first}_$second"); - /// assert_eq!(result, "deep_fried"); - /// # } - /// ``` - /// - /// Without the curly braces, the capture group name `first_` would be - /// used, and since it doesn't exist, it would be replaced with the empty - /// string. - /// - /// Finally, sometimes you just want to replace a literal string with no - /// regard for capturing group expansion. This can be done by wrapping a - /// byte string with `NoExpand`: - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// use regex::NoExpand; - /// - /// let re = Regex::new(r"(?P<last>[^,\s]+),\s+(\S+)").unwrap(); - /// let result = re.replace("Springsteen, Bruce", NoExpand("$2 $last")); - /// assert_eq!(result, "$2 $last"); - /// # } - /// ``` - pub fn replace<'t, R: Replacer>( - &self, - text: &'t str, - rep: R, - ) -> Cow<'t, str> { - self.replacen(text, 1, rep) - } - - /// Replaces all non-overlapping matches in `text` with the replacement - /// provided. This is the same as calling `replacen` with `limit` set to - /// `0`. - /// - /// See the documentation for `replace` for details on how to access - /// capturing group matches in the replacement string. - pub fn replace_all<'t, R: Replacer>( - &self, - text: &'t str, - rep: R, - ) -> Cow<'t, str> { - self.replacen(text, 0, rep) - } - - /// Replaces at most `limit` non-overlapping matches in `text` with the - /// replacement provided. If `limit` is 0, then all non-overlapping matches - /// are replaced. - /// - /// See the documentation for `replace` for details on how to access - /// capturing group matches in the replacement string. - pub fn replacen<'t, R: Replacer>( - &self, - text: &'t str, - limit: usize, - mut rep: R, - ) -> Cow<'t, str> { - // If we know that the replacement doesn't have any capture expansions, - // then we can fast path. The fast path can make a tremendous - // difference: - // - // 1) We use `find_iter` instead of `captures_iter`. Not asking for - // captures generally makes the regex engines faster. - // 2) We don't need to look up all of the capture groups and do - // replacements inside the replacement string. We just push it - // at each match and be done with it. - if let Some(rep) = rep.no_expansion() { - let mut it = self.find_iter(text).enumerate().peekable(); - if it.peek().is_none() { - return Cow::Borrowed(text); - } - let mut new = String::with_capacity(text.len()); - let mut last_match = 0; - for (i, m) in it { - if limit > 0 && i >= limit { - break - } - new.push_str(&text[last_match..m.start()]); - new.push_str(&rep); - last_match = m.end(); - } - new.push_str(&text[last_match..]); - return Cow::Owned(new); - } - - // The slower path, which we use if the replacement needs access to - // capture groups. - let mut it = self.captures_iter(text).enumerate().peekable(); - if it.peek().is_none() { - return Cow::Borrowed(text); - } - let mut new = String::with_capacity(text.len()); - let mut last_match = 0; - for (i, cap) in it { - if limit > 0 && i >= limit { - break - } - // unwrap on 0 is OK because captures only reports matches - let m = cap.get(0).unwrap(); - new.push_str(&text[last_match..m.start()]); - rep.replace_append(&cap, &mut new); - last_match = m.end(); - } - new.push_str(&text[last_match..]); - Cow::Owned(new) - } -} - -/// Advanced or "lower level" search methods. -impl Regex { - /// Returns the end location of a match in the text given. - /// - /// This method may have the same performance characteristics as - /// `is_match`, except it provides an end location for a match. In - /// particular, the location returned *may be shorter* than the proper end - /// of the leftmost-first match. - /// - /// # Example - /// - /// Typically, `a+` would match the entire first sequence of `a` in some - /// text, but `shortest_match` can give up as soon as it sees the first - /// `a`. - /// - /// ```rust - /// # extern crate regex; use regex::Regex; - /// # fn main() { - /// let text = "aaaaa"; - /// let pos = Regex::new(r"a+").unwrap().shortest_match(text); - /// assert_eq!(pos, Some(1)); - /// # } - /// ``` - pub fn shortest_match(&self, text: &str) -> Option<usize> { - self.shortest_match_at(text, 0) - } - - /// Returns the same as shortest_match, but starts the search at the given - /// offset. - /// - /// The significance of the starting point is that it takes the surrounding - /// context into consideration. For example, the `\A` anchor can only - /// match when `start == 0`. - #[doc(hidden)] - pub fn shortest_match_at( - &self, - text: &str, - start: usize, - ) -> Option<usize> { - self.0.searcher_str().shortest_match_at(text, start) - } - - /// Returns the same as is_match, but starts the search at the given - /// offset. - /// - /// The significance of the starting point is that it takes the surrounding - /// context into consideration. For example, the `\A` anchor can only - /// match when `start == 0`. - #[doc(hidden)] - pub fn is_match_at(&self, text: &str, start: usize) -> bool { - self.shortest_match_at(text, start).is_some() - } - - /// Returns the same as find, but starts the search at the given - /// offset. - /// - /// The significance of the starting point is that it takes the surrounding - /// context into consideration. For example, the `\A` anchor can only - /// match when `start == 0`. - #[doc(hidden)] - pub fn find_at<'t>( - &self, - text: &'t str, - start: usize, - ) -> Option<Match<'t>> { - self.0.searcher_str().find_at(text, start).map(|(s, e)| { - Match::new(text, s, e) - }) - } - - /// Returns the same as captures, but starts the search at the given - /// offset and populates the capture locations given. - /// - /// The significance of the starting point is that it takes the surrounding - /// context into consideration. For example, the `\A` anchor can only - /// match when `start == 0`. - #[doc(hidden)] - pub fn read_captures_at<'t>( - &self, - locs: &mut Locations, - text: &'t str, - start: usize, - ) -> Option<Match<'t>> { - self.0 - .searcher_str() - .read_captures_at(locs, text, start) - .map(|(s, e)| Match::new(text, s, e)) - } -} - -/// Auxiliary methods. -impl Regex { - /// Returns the original string of this regex. - pub fn as_str(&self) -> &str { - &self.0.regex_strings()[0] - } - - /// Returns an iterator over the capture names. - pub fn capture_names(&self) -> CaptureNames { - CaptureNames(self.0.capture_names().iter()) - } - - /// Returns the number of captures. - pub fn captures_len(&self) -> usize { - self.0.capture_names().len() - } - - /// Returns an empty set of locations that can be reused in multiple calls - /// to `read_captures`. - #[doc(hidden)] - pub fn locations(&self) -> Locations { - self.0.searcher_str().locations() - } -} - -/// An iterator over the names of all possible captures. -/// -/// `None` indicates an unnamed capture; the first element (capture 0, the -/// whole matched region) is always unnamed. -/// -/// `'r` is the lifetime of the compiled regular expression. -pub struct CaptureNames<'r>(::std::slice::Iter<'r, Option<String>>); - -impl<'r> Iterator for CaptureNames<'r> { - type Item = Option<&'r str>; - - fn next(&mut self) -> Option<Option<&'r str>> { - self.0 - .next() - .as_ref() - .map(|slot| slot.as_ref().map(|name| name.as_ref())) - } - - fn size_hint(&self) -> (usize, Option<usize>) { - self.0.size_hint() - } -} - -/// Yields all substrings delimited by a regular expression match. -/// -/// `'r` is the lifetime of the compiled regular expression and `'t` is the -/// lifetime of the string being split. -pub struct Split<'r, 't> { - finder: Matches<'r, 't>, - last: usize, -} - -impl<'r, 't> Iterator for Split<'r, 't> { - type Item = &'t str; - - fn next(&mut self) -> Option<&'t str> { - let text = self.finder.0.text(); - match self.finder.next() { - None => { - if self.last >= text.len() { - None - } else { - let s = &text[self.last..]; - self.last = text.len(); - Some(s) - } - } - Some(m) => { - let matched = &text[self.last..m.start()]; - self.last = m.end(); - Some(matched) - } - } - } -} - -/// Yields at most `N` substrings delimited by a regular expression match. -/// -/// The last substring will be whatever remains after splitting. -/// -/// `'r` is the lifetime of the compiled regular expression and `'t` is the -/// lifetime of the string being split. -pub struct SplitN<'r, 't> { - splits: Split<'r, 't>, - n: usize, -} - -impl<'r, 't> Iterator for SplitN<'r, 't> { - type Item = &'t str; - - fn next(&mut self) -> Option<&'t str> { - if self.n == 0 { - return None - } - self.n -= 1; - if self.n == 0 { - let text = self.splits.finder.0.text(); - Some(&text[self.splits.last..]) - } else { - self.splits.next() - } - } -} - -/// Captures represents a group of captured strings for a single match. -/// -/// The 0th capture always corresponds to the entire match. Each subsequent -/// index corresponds to the next capture group in the regex. If a capture -/// group is named, then the matched string is *also* available via the `name` -/// method. (Note that the 0th capture is always unnamed and so must be -/// accessed with the `get` method.) -/// -/// Positions returned from a capture group are always byte indices. -/// -/// `'t` is the lifetime of the matched text. -pub struct Captures<'t> { - text: &'t str, - locs: Locations, - named_groups: Arc<HashMap<String, usize>>, -} - -impl<'t> Captures<'t> { - /// Returns the match associated with the capture group at index `i`. If - /// `i` does not correspond to a capture group, or if the capture group - /// did not participate in the match, then `None` is returned. - /// - /// # Examples - /// - /// Get the text of the match with a default of an empty string if this - /// group didn't participate in the match: - /// - /// ```rust - /// # use regex::Regex; - /// let re = Regex::new(r"[a-z]+(?:([0-9]+)|([A-Z]+))").unwrap(); - /// let caps = re.captures("abc123").unwrap(); - /// - /// let text1 = caps.get(1).map_or("", |m| m.as_str()); - /// let text2 = caps.get(2).map_or("", |m| m.as_str()); - /// assert_eq!(text1, "123"); - /// assert_eq!(text2, ""); - /// ``` - pub fn get(&self, i: usize) -> Option<Match<'t>> { - self.locs.pos(i).map(|(s, e)| Match::new(self.text, s, e)) - } - - /// Returns the match for the capture group named `name`. If `name` isn't a - /// valid capture group or didn't match anything, then `None` is returned. - pub fn name(&self, name: &str) -> Option<Match<'t>> { - self.named_groups.get(name).and_then(|&i| self.get(i)) - } - - /// An iterator that yields all capturing matches in the order in which - /// they appear in the regex. If a particular capture group didn't - /// participate in the match, then `None` is yielded for that capture. - /// - /// The first match always corresponds to the overall match of the regex. - pub fn iter<'c>(&'c self) -> SubCaptureMatches<'c, 't> { - SubCaptureMatches { - caps: self, - it: self.locs.iter(), - } - } - - /// Expands all instances of `$name` in `replacement` to the corresponding - /// capture group `name`, and writes them to the `dst` buffer given. - /// - /// `name` may be an integer corresponding to the index of the - /// capture group (counted by order of opening parenthesis where `0` is the - /// entire match) or it can be a name (consisting of letters, digits or - /// underscores) corresponding to a named capture group. - /// - /// If `name` isn't a valid capture group (whether the name doesn't exist - /// or isn't a valid index), then it is replaced with the empty string. - /// - /// The longest possible name is used. e.g., `$1a` looks up the capture - /// group named `1a` and not the capture group at index `1`. To exert more - /// precise control over the name, use braces, e.g., `${1}a`. - /// - /// To write a literal `$` use `$$`. - pub fn expand(&self, replacement: &str, dst: &mut String) { - expand_str(self, replacement, dst) - } - - /// Returns the number of captured groups. - /// - /// This is always at least `1`, since every regex has at least one capture - /// group that corresponds to the full match. - #[inline] - pub fn len(&self) -> usize { - self.locs.len() - } -} - -impl<'t> fmt::Debug for Captures<'t> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_tuple("Captures").field(&CapturesDebug(self)).finish() - } -} - -struct CapturesDebug<'c, 't: 'c>(&'c Captures<'t>); - -impl<'c, 't> fmt::Debug for CapturesDebug<'c, 't> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // We'd like to show something nice here, even if it means an - // allocation to build a reverse index. - let slot_to_name: HashMap<&usize, &String> = - self.0.named_groups.iter().map(|(a, b)| (b, a)).collect(); - let mut map = f.debug_map(); - for (slot, m) in self.0.locs.iter().enumerate() { - let m = m.map(|(s, e)| &self.0.text[s..e]); - if let Some(name) = slot_to_name.get(&slot) { - map.entry(&name, &m); - } else { - map.entry(&slot, &m); - } - } - map.finish() - } -} - -/// Get a group by index. -/// -/// `'t` is the lifetime of the matched text. -/// -/// The text can't outlive the `Captures` object if this method is -/// used, because of how `Index` is defined (normally `a[i]` is part -/// of `a` and can't outlive it); to do that, use `get()` instead. -/// -/// # Panics -/// -/// If there is no group at the given index. -impl<'t> Index<usize> for Captures<'t> { - type Output = str; - - fn index(&self, i: usize) -> &str { - self.get(i).map(|m| m.as_str()) - .unwrap_or_else(|| panic!("no group at index '{}'", i)) - } -} - -/// Get a group by name. -/// -/// `'t` is the lifetime of the matched text and `'i` is the lifetime -/// of the group name (the index). -/// -/// The text can't outlive the `Captures` object if this method is -/// used, because of how `Index` is defined (normally `a[i]` is part -/// of `a` and can't outlive it); to do that, use `name` instead. -/// -/// # Panics -/// -/// If there is no group named by the given value. -impl<'t, 'i> Index<&'i str> for Captures<'t> { - type Output = str; - - fn index<'a>(&'a self, name: &'i str) -> &'a str { - self.name(name).map(|m| m.as_str()) - .unwrap_or_else(|| panic!("no group named '{}'", name)) - } -} - -/// An iterator that yields all capturing matches in the order in which they -/// appear in the regex. -/// -/// If a particular capture group didn't participate in the match, then `None` -/// is yielded for that capture. The first match always corresponds to the -/// overall match of the regex. -/// -/// The lifetime `'c` corresponds to the lifetime of the `Captures` value, and -/// the lifetime `'t` corresponds to the originally matched text. -pub struct SubCaptureMatches<'c, 't: 'c> { - caps: &'c Captures<'t>, - it: SubCapturesPosIter<'c>, -} - -impl<'c, 't> Iterator for SubCaptureMatches<'c, 't> { - type Item = Option<Match<'t>>; - - fn next(&mut self) -> Option<Option<Match<'t>>> { - self.it.next() - .map(|cap| cap.map(|(s, e)| Match::new(self.caps.text, s, e))) - } -} - -/// An iterator that yields all non-overlapping capture groups matching a -/// particular regular expression. -/// -/// The iterator stops when no more matches can be found. -/// -/// `'r` is the lifetime of the compiled regular expression and `'t` is the -/// lifetime of the matched string. -pub struct CaptureMatches<'r, 't>(re_trait::CaptureMatches<'t, ExecNoSyncStr<'r>>); - -impl<'r, 't> Iterator for CaptureMatches<'r, 't> { - type Item = Captures<'t>; - - fn next(&mut self) -> Option<Captures<'t>> { - self.0.next().map(|locs| Captures { - text: self.0.text(), - locs: locs, - named_groups: self.0.regex().capture_name_idx().clone(), - }) - } -} - -/// An iterator over all non-overlapping matches for a particular string. -/// -/// The iterator yields a `Match` value. The iterator stops when no more -/// matches can be found. -/// -/// `'r` is the lifetime of the compiled regular expression and `'t` is the -/// lifetime of the matched string. -pub struct Matches<'r, 't>(re_trait::Matches<'t, ExecNoSyncStr<'r>>); - -impl<'r, 't> Iterator for Matches<'r, 't> { - type Item = Match<'t>; - - fn next(&mut self) -> Option<Match<'t>> { - let text = self.0.text(); - self.0.next().map(|(s, e)| Match::new(text, s, e)) - } -} - -/// Replacer describes types that can be used to replace matches in a string. -/// -/// In general, users of this crate shouldn't need to implement this trait, -/// since implementations are already provided for `&str` and -/// `FnMut(&Captures) -> String`, which covers most use cases. -pub trait Replacer { - /// Appends text to `dst` to replace the current match. - /// - /// The current match is represented by `caps`, which is guaranteed to - /// have a match at capture group `0`. - /// - /// For example, a no-op replacement would be - /// `dst.extend(caps.get(0).unwrap().as_str())`. - fn replace_append(&mut self, caps: &Captures, dst: &mut String); - - /// Return a fixed unchanging replacement string. - /// - /// When doing replacements, if access to `Captures` is not needed (e.g., - /// the replacement byte string does not need `$` expansion), then it can - /// be beneficial to avoid finding sub-captures. - /// - /// In general, this is called once for every call to `replacen`. - fn no_expansion<'r>(&'r mut self) -> Option<Cow<'r, str>> { - None - } -} - -impl<'a> Replacer for &'a str { - fn replace_append(&mut self, caps: &Captures, dst: &mut String) { - caps.expand(*self, dst); - } - - fn no_expansion(&mut self) -> Option<Cow<str>> { - match memchr(b'$', self.as_bytes()) { - Some(_) => None, - None => Some(Cow::Borrowed(*self)), - } - } -} - -impl<F> Replacer for F where F: FnMut(&Captures) -> String { - fn replace_append(&mut self, caps: &Captures, dst: &mut String) { - dst.push_str(&(*self)(caps)); - } -} - -/// `NoExpand` indicates literal string replacement. -/// -/// It can be used with `replace` and `replace_all` to do a literal string -/// replacement without expanding `$name` to their corresponding capture -/// groups. This can be both convenient (to avoid escaping `$`, for example) -/// and performant (since capture groups don't need to be found). -/// -/// `'t` is the lifetime of the literal text. -pub struct NoExpand<'t>(pub &'t str); - -impl<'t> Replacer for NoExpand<'t> { - fn replace_append(&mut self, _: &Captures, dst: &mut String) { - dst.push_str(self.0); - } - - fn no_expansion(&mut self) -> Option<Cow<str>> { - Some(Cow::Borrowed(self.0)) - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/simd_accel/mod.rs cargo-0.26.0/vendor/regex-0.2.6/src/simd_accel/mod.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/simd_accel/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/simd_accel/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -#[cfg(target_feature = "ssse3")] -pub mod teddy128; -#[cfg(not(target_feature = "ssse3"))] -#[path = "../simd_fallback/teddy128.rs"] -pub mod teddy128; diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/simd_accel/teddy128.rs cargo-0.26.0/vendor/regex-0.2.6/src/simd_accel/teddy128.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/simd_accel/teddy128.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/simd_accel/teddy128.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,794 +0,0 @@ -/*! -Teddy is a simd accelerated multiple substring matching algorithm. The name -and the core ideas in the algorithm were learned from the [Hyperscan][1_u] -project. - - -Background ----------- - -The key idea of Teddy is to do *packed* substring matching. In the literature, -packed substring matching is the idea of examing multiple bytes in a haystack -at a time to detect matches. Implementations of, for example, memchr (which -detects matches of a single byte) have been doing this for years. Only -recently, with the introduction of various SIMD instructions, has this been -extended to substring matching. The PCMPESTRI instruction (and its relatives), -for example, implements substring matching in hardware. It is, however, limited -to substrings of length 16 bytes or fewer, but this restriction is fine in a -regex engine, since we rarely care about the performance difference between -searching for a 16 byte literal and a 16 + N literal—16 is already long -enough. The key downside of the PCMPESTRI instruction, on current (2016) CPUs -at least, is its latency and throughput. As a result, it is often faster to do -substring search with a Boyer-Moore variant and a well placed memchr to quickly -skip through the haystack. - -There are fewer results from the literature on packed substring matching, -and even fewer for packed multiple substring matching. Ben-Kiki et al. [2] -describes use of PCMPESTRI for substring matching, but is mostly theoretical -and hand-waves performance. There is other theoretical work done by Bille [3] -as well. - -The rest of the work in the field, as far as I'm aware, is by Faro and Kulekci -and is generally focused on multiple pattern search. Their first paper [4a] -introduces the concept of a fingerprint, which is computed for every block of -N bytes in every pattern. The haystack is then scanned N bytes at a time and -a fingerprint is computed in the same way it was computed for blocks in the -patterns. If the fingerprint corresponds to one that was found in a pattern, -then a verification step follows to confirm that one of the substrings with the -corresponding fingerprint actually matches at the current location. Various -implementation tricks are employed to make sure the fingerprint lookup is fast; -typically by truncating the fingerprint. (This may, of course, provoke more -steps in the verification process, so a balance must be struck.) - -The main downside of [4a] is that the minimum substring length is 32 bytes, -presumably because of how the algorithm uses certain SIMD instructions. This -essentially makes it useless for general purpose regex matching, where a small -number of short patterns is far more likely. - -Faro and Kulekci published another paper [4b] that is conceptually very similar -to [4a]. The key difference is that it uses the CRC32 instruction (introduced -as part of SSE 4.2) to compute fingerprint values. This also enables the -algorithm to work effectively on substrings as short as 7 bytes with 4 byte -windows. 7 bytes is unfortunately still too long. The window could be -technically shrunk to 2 bytes, thereby reducing minimum length to 3, but the -small window size ends up negating most performance benefits—and it's likely -the common case in a general purpose regex engine. - -Faro and Kulekci also published [4c] that appears to be intended as a -replacement to using PCMPESTRI. In particular, it is specifically motivated by -the high throughput/latency time of PCMPESTRI and therefore chooses other SIMD -instructions that are faster. While this approach works for short substrings, -I personally couldn't see a way to generalize it to multiple substring search. - -Faro and Kulekci have another paper [4d] that I haven't been able to read -because it is behind a paywall. - - -Teddy ------ - -Finally, we get to Teddy. If the above literature review is complete, then it -appears that Teddy is a novel algorithm. More than that, in my experience, it -completely blows away the competition for short substrings, which is exactly -what we want in a general purpose regex engine. Again, the algorithm appears -to be developed by the authors of [Hyperscan][1_u]. Hyperscan was open sourced -late 2015, and no earlier history could be found. Therefore, tracking the exact -provenance of the algorithm with respect to the published literature seems -difficult. - -DISCLAIMER: My understanding of Teddy is limited to reading auto-generated C -code, its disassembly and observing its runtime behavior. - -At a high level, Teddy works somewhat similarly to the fingerprint algorithms -published by Faro and Kulekci, but Teddy does it in a way that scales a bit -better. Namely: - -1. Teddy's core algorithm scans the haystack in 16 byte chunks. 16 is - significant because it corresponds to the number of bytes in a SIMD vector. - If one used AVX2 instructions, then we could scan the haystack in 32 byte - chunks. Similarly, if one used AVX512 instructions, we could scan the - haystack in 64 byte chunks. Hyperscan implements SIMD + AVX2, we only - implement SIMD for the moment. (The author doesn't have a CPU with AVX2 - support... yet.) -2. Bitwise operations are performed on each chunk to discover if any region of - it matches a set of precomputed fingerprints from the patterns. If there are - matches, then a verification step is performed. In this implementation, our - verification step is naive. This can be improved upon. - -The details to make this work are quite clever. First, we must choose how to -pick our fingerprints. In Hyperscan's implementation, I *believe* they use the -last N bytes of each substring, where N must be at least the minimum length of -any substring in the set being searched. In this implementation, we use the -first N bytes of each substring. (The tradeoffs between these choices aren't -yet clear to me.) We then must figure out how to quickly test whether an -occurrence of any fingerprint from the set of patterns appears in a 16 byte -block from the haystack. To keep things simple, let's assume N = 1 and examine -some examples to motivate the approach. Here are our patterns: - -```ignore -foo -bar -baz -``` - -The corresponding fingerprints, for N = 1, are `f`, `b` and `b`. Now let's set -our 16 byte block to: - -```ignore -bat cat foo bump -xxxxxxxxxxxxxxxx -``` - -To cut to the chase, Teddy works by using bitsets. In particular, Teddy creates -a mask that allows us to quickly compute membership of a fingerprint in a 16 -byte block that also tells which pattern the fingerprint corresponds to. In -this case, our fingerprint is a single byte, so an appropriate abstraction is -a map from a single byte to a list of patterns that contain that fingerprint: - -```ignore -f |--> foo -b |--> bar, baz -``` - -Now, all we need to do is figure out how to represent this map in vector space -and use normal SIMD operations to perform a lookup. The first simplification -we can make is to represent our patterns as bit fields occupying a single -byte. This is important, because a single SIMD vector can store 16 bytes. - -```ignore -f |--> 00000001 -b |--> 00000010, 00000100 -``` - -How do we perform lookup though? It turns out that SSSE3 introduced a very cool -instruction called PSHUFB. The instruction takes two SIMD vectors, `A` and `B`, -and returns a third vector `C`. All vectors are treated as 16 8-bit integers. -`C` is formed by `C[i] = A[B[i]]`. (This is a bit of a simplification, but true -for the purposes of this algorithm. For full details, see [Intel's Intrinsics -Guide][5_u].) This essentially lets us use the values in `B` to lookup values in -`A`. - -If we could somehow cause `B` to contain our 16 byte block from the haystack, -and if `A` could contain our bitmasks, then we'd end up with something like -this for `A`: - -```ignore - 0x00 0x01 ... 0x62 ... 0x66 ... 0xFF -A = 0 0 00000110 00000001 0 -``` - -And if `B` contains our window from our haystack, we could use shuffle to take -the values from `B` and use them to look up our bitsets in `A`. But of course, -we can't do this because `A` in the above example contains 256 bytes, which -is much larger than the size of a SIMD vector. - -Nybbles to the rescue! A nybble is 4 bits. Instead of one mask to hold all of -our bitsets, we can use two masks, where one mask corresponds to the lower four -bits of our fingerprint and the other mask corresponds to the upper four bits. -So our map now looks like: - -```ignore -'f' & 0xF = 0x6 |--> 00000001 -'f' >> 4 = 0x6 |--> 00000111 -'b' & 0xF = 0x2 |--> 00000110 -'b' >> 4 = 0x6 |--> 00000111 -``` - -Notice that the bitsets for each nybble correspond to the union of all -fingerprints that contain that nibble. For example, both `f` and `b` have the -same upper 4 bits but differ on the lower 4 bits. Putting this together, we -have `A0`, `A1` and `B`, where `A0` is our mask for the lower nybble, `A1` is -our mask for the upper nybble and `B` is our 16 byte block from the haystack: - -```ignore - 0x00 0x01 0x02 0x03 ... 0x06 ... 0xF -A0 = 0 0 00000110 0 00000001 0 -A1 = 0 0 0 0 00000111 0 -B = b a t _ t p -B = 0x62 0x61 0x74 0x20 0x74 0x70 -``` - -But of course, we can't use `B` with `PSHUFB` yet, since its values are 8 bits, -and we need indexes that are at most 4 bits (corresponding to one of 16 -values). We can apply the same transformation to split `B` into lower and upper -nybbles as we did `A`. As before, `B0` corresponds to the lower nybbles and -`B1` corresponds to the upper nybbles: - -```ignore - b a t _ c a t _ f o o _ b u m p -B0 = 0x2 0x1 0x4 0x0 0x3 0x1 0x4 0x0 0x6 0xF 0xF 0x0 0x2 0x5 0xD 0x0 -B1 = 0x6 0x6 0x7 0x2 0x6 0x6 0x7 0x2 0x6 0x6 0x6 0x2 0x6 0x7 0x6 0x7 -``` - -And now we have a nice correspondence. `B0` can index `A0` and `B1` can index -`A1`. Here's what we get when we apply `C0 = PSHUFB(A0, B0)`: - -```ignore - b a ... f o ... p - A0[0x2] A0[0x1] A0[0x6] A0[0xF] A0[0x0] -C0 = 00000110 0 00000001 0 0 -``` - -And `C1 = PSHUFB(A1, B1)`: - -```ignore - b a ... f o ... p - A1[0x6] A1[0x6] A1[0x6] A1[0x6] A1[0x7] -C1 = 00000111 00000111 00000111 00000111 0 -``` - -Notice how neither one of `C0` or `C1` is guaranteed to report fully correct -results all on its own. For example, `C1` claims that `b` is a fingerprint for -the pattern `foo` (since `A1[0x6] = 00000111`), and that `o` is a fingerprint -for all of our patterns. But if we combined `C0` and `C1` with an `AND` -operation: - -``` - b a ... f o ... p -C = 00000110 0 00000001 0 0 -``` - -Then we now have that `C[i]` contains a bitset corresponding to the matching -fingerprints in a haystack's 16 byte block, where `i` is the `ith` byte in that -block. - -Once we have that, we can look for the position of the least significant bit -in `C`. That position, modulo `8`, gives us the pattern that the fingerprint -matches. That position, integer divided by `8`, also gives us the byte offset -that the fingerprint occurs in inside the 16 byte haystack block. Using those -two pieces of information, we can run a verification procedure that tries -to match all substrings containing that fingerprint at that position in the -haystack. - - -Implementation notes --------------------- - -The problem with the algorithm as described above is that it uses a single byte -for a fingerprint. This will work well if the fingerprints are rare in the -haystack (e.g., capital letters or special characters in normal English text), -but if the fingerprints are common, you'll wind up spending too much time in -the verification step, which effectively negate the performance benefits of -scanning 16 bytes at a time. Remember, the key to the performance of this -algorithm is to do as little work as possible per 16 bytes. - -This algorithm can be extrapolated in a relatively straight-forward way to use -larger fingerprints. That is, instead of a single byte prefix, we might use a -three byte prefix. The implementation below implements N = {1, 2, 3} and always -picks the largest N possible. The rationale is that the bigger the fingerprint, -the fewer verification steps we'll do. Of course, if N is too large, then we'll -end up doing too much on each step. - -The way to extend it is: - -1. Add a mask for each byte in the fingerprint. (Remember that each mask is - composed of two SIMD vectors.) This results in a value of `C` for each byte - in the fingerprint while searching. -2. When testing each 16 byte block, each value of `C` must be shifted so that - they are aligned. Once aligned, they should all be `AND`'d together. This - will give you only the bitsets corresponding to the full match of the - fingerprint. - -The implementation below is commented to fill in the nitty gritty details. - -References ----------- - -- **[1]** [Hyperscan on GitHub](https://github.com/01org/hyperscan), - [webpage](https://01.org/hyperscan) -- **[2a]** Ben-Kiki, O., Bille, P., Breslauer, D., Gasieniec, L., Grossi, R., - & Weimann, O. (2011). - _Optimal packed string matching_. - In LIPIcs-Leibniz International Proceedings in Informatics (Vol. 13). - Schloss Dagstuhl-Leibniz-Zentrum fuer Informatik. - DOI: 10.4230/LIPIcs.FSTTCS.2011.423. - [PDF](http://drops.dagstuhl.de/opus/volltexte/2011/3355/pdf/37.pdf). -- **[2b]** Ben-Kiki, O., Bille, P., Breslauer, D., Ga̧sieniec, L., Grossi, R., - & Weimann, O. (2014). - _Towards optimal packed string matching_. - Theoretical Computer Science, 525, 111-129. - DOI: 10.1016/j.tcs.2013.06.013. - [PDF](http://www.cs.haifa.ac.il/~oren/Publications/bpsm.pdf). -- **[3]** Bille, P. (2011). - _Fast searching in packed strings_. - Journal of Discrete Algorithms, 9(1), 49-56. - DOI: 10.1016/j.jda.2010.09.003. - [PDF](http://www.sciencedirect.com/science/article/pii/S1570866710000353). -- **[4a]** Faro, S., & Külekci, M. O. (2012, October). - _Fast multiple string matching using streaming SIMD extensions technology_. - In String Processing and Information Retrieval (pp. 217-228). - Springer Berlin Heidelberg. - DOI: 10.1007/978-3-642-34109-0_23. - [PDF](http://www.dmi.unict.it/~faro/papers/conference/faro32.pdf). -- **[4b]** Faro, S., & Külekci, M. O. (2013, September). - _Towards a Very Fast Multiple String Matching Algorithm for Short Patterns_. - In Stringology (pp. 78-91). - [PDF](http://www.dmi.unict.it/~faro/papers/conference/faro36.pdf). -- **[4c]** Faro, S., & Külekci, M. O. (2013, January). - _Fast packed string matching for short patterns_. - In Proceedings of the Meeting on Algorithm Engineering & Expermiments - (pp. 113-121). - Society for Industrial and Applied Mathematics. - [PDF](http://arxiv.org/pdf/1209.6449.pdf). -- **[4d]** Faro, S., & Külekci, M. O. (2014). - _Fast and flexible packed string matching_. - Journal of Discrete Algorithms, 28, 61-72. - DOI: 10.1016/j.jda.2014.07.003. - -[1_u]: https://github.com/01org/hyperscan -[5_u]: https://software.intel.com/sites/landingpage/IntrinsicsGuide -*/ - -// TODO: Extend this to use AVX2 instructions. -// TODO: Extend this to use AVX512 instructions. -// TODO: Make the inner loop do aligned loads. - -use std::cmp; -use std::ptr; - -use aho_corasick::{Automaton, AcAutomaton, FullAcAutomaton}; -use simd::u8x16; -use simd::x86::sse2::Sse2Bool8ix16; -use simd::x86::ssse3::Ssse3U8x16; - -use syntax; - -/// Corresponds to the number of bytes read at a time in the haystack. -const BLOCK_SIZE: usize = 16; - -pub fn is_teddy_128_available() -> bool { - true -} - -/// Match reports match information. -#[derive(Debug, Clone)] -pub struct Match { - /// The index of the pattern that matched. The index is in correspondence - /// with the order of the patterns given at construction. - pub pat: usize, - /// The start byte offset of the match. - pub start: usize, - /// The end byte offset of the match. This is always `start + pat.len()`. - pub end: usize, -} - -/// A SIMD accelerated multi substring searcher. -#[derive(Debug, Clone)] -pub struct Teddy { - /// A list of substrings to match. - pats: Vec<Vec<u8>>, - /// An Aho-Corasick automaton of the patterns. We use this when we need to - /// search pieces smaller than the Teddy block size. - ac: FullAcAutomaton<Vec<u8>>, - /// A set of 8 buckets. Each bucket corresponds to a single member of a - /// bitset. A bucket contains zero or more substrings. This is useful - /// when the number of substrings exceeds 8, since our bitsets cannot have - /// more than 8 members. - buckets: Vec<Vec<usize>>, - /// Our set of masks. There's one mask for each byte in the fingerprint. - masks: Masks, -} - -/// A list of masks. This has length equal to the length of the fingerprint. -/// The length of the fingerprint is always `min(3, len(smallest_substring))`. -#[derive(Debug, Clone)] -struct Masks(Vec<Mask>); - -/// A single mask. -#[derive(Debug, Clone, Copy)] -struct Mask { - /// Bitsets for the low nybbles in a fingerprint. - lo: u8x16, - /// Bitsets for the high nybbles in a fingerprint. - hi: u8x16, -} - -impl Teddy { - /// Create a new `Teddy` multi substring matcher. - /// - /// If a `Teddy` matcher could not be created (e.g., `pats` is empty or has - /// an empty substring), then `None` is returned. - pub fn new(pats: &syntax::Literals) -> Option<Teddy> { - let pats: Vec<_> = pats.literals().iter().map(|p|p.to_vec()).collect(); - let min_len = pats.iter().map(|p| p.len()).min().unwrap_or(0); - // Don't allow any empty patterns and require that we have at - // least one pattern. - if min_len < 1 { - return None; - } - // Pick the largest mask possible, but no larger than 3. - let nmasks = cmp::min(3, min_len); - let mut masks = Masks::new(nmasks); - let mut buckets = vec![vec![]; 8]; - // Assign a substring to each bucket, and add the bucket's bitfield to - // the appropriate position in the mask. - for (pati, pat) in pats.iter().enumerate() { - let bucket = pati % 8; - buckets[bucket].push(pati); - masks.add(bucket as u8, pat); - } - Some(Teddy { - pats: pats.to_vec(), - ac: AcAutomaton::new(pats.to_vec()).into_full(), - buckets: buckets, - masks: masks, - }) - } - - /// Returns all of the substrings matched by this `Teddy`. - pub fn patterns(&self) -> &[Vec<u8>] { - &self.pats - } - - /// Returns the number of substrings in this matcher. - pub fn len(&self) -> usize { - self.pats.len() - } - - /// Returns the approximate size on the heap used by this matcher. - pub fn approximate_size(&self) -> usize { - self.pats.iter().fold(0, |a, b| a + b.len()) - } - - /// Searches `haystack` for the substrings in this `Teddy`. If a match was - /// found, then it is returned. Otherwise, `None` is returned. - pub fn find(&self, haystack: &[u8]) -> Option<Match> { - // If our haystack is smaller than the block size, then fall back to - // a naive brute force search. - if haystack.is_empty() || haystack.len() < (BLOCK_SIZE + 2) { - return self.slow(haystack, 0); - } - match self.masks.len() { - 0 => None, - 1 => self.find1(haystack), - 2 => self.find2(haystack), - 3 => self.find3(haystack), - _ => unreachable!(), - } - } - - /// `find1` is used when there is only 1 mask. This is the easy case and is - /// pretty much as described in the module documentation. - #[inline(always)] - fn find1(&self, haystack: &[u8]) -> Option<Match> { - let mut pos = 0; - let zero = u8x16::splat(0); - let len = haystack.len(); - debug_assert!(len >= BLOCK_SIZE); - while pos <= len - BLOCK_SIZE { - let h = unsafe { u8x16::load_unchecked(haystack, pos) }; - // N.B. `res0` is our `C` in the module documentation. - let res0 = self.masks.members1(h); - // Only do expensive verification if there are any non-zero bits. - let bitfield = res0.ne(zero).move_mask(); - if bitfield != 0 { - if let Some(m) = self.verify(haystack, pos, res0, bitfield) { - return Some(m); - } - } - pos += BLOCK_SIZE; - } - self.slow(haystack, pos) - } - - /// `find2` is used when there are 2 masks, e.g., the fingerprint is 2 bytes - /// long. - #[inline(always)] - fn find2(&self, haystack: &[u8]) -> Option<Match> { - // This is an exotic way to right shift a SIMD vector across lanes. - // See below at use for more details. - let res0shuffle = u8x16::new( - 0, 0, 1, 2, - 3, 4, 5, 6, - 7, 8, 9, 10, - 11, 12, 13, 14, - ); - let zero = u8x16::splat(0); - let len = haystack.len(); - // The previous value of `C` (from the module documentation) for the - // *first* byte in the fingerprint. On subsequent iterations, we take - // the last bitset from the previous `C` and insert it into the first - // position of the current `C`, shifting all other bitsets to the right - // one lane. This causes `C` for the first byte to line up with `C` for - // the second byte, so that they can be `AND`'d together. - let mut prev0 = u8x16::splat(0xFF); - let mut pos = 1; - debug_assert!(len >= BLOCK_SIZE); - while pos <= len - BLOCK_SIZE { - let h = unsafe { u8x16::load_unchecked(haystack, pos) }; - let (res0, res1) = self.masks.members2(h); - - // The next three lines are essentially equivalent to - // - // ```rust,ignore - // (prev0 << 15) | (res0 >> 1) - // ``` - // - // ... if SIMD vectors could shift across lanes. There is the - // `PALIGNR` instruction, but apparently LLVM doesn't expose it as - // a proper intrinsic. Thankfully, it appears the following - // sequence does indeed compile down to a `PALIGNR`. - let prev0byte0 = prev0.extract(15); - let res0shiftr8 = res0.shuffle_bytes(res0shuffle); - let res0prev0 = res0shiftr8.replace(0, prev0byte0); - - // `AND`'s our `C` values together. - let res = res0prev0 & res1; - prev0 = res0; - - let bitfield = res.ne(zero).move_mask(); - if bitfield != 0 { - let pos = pos.checked_sub(1).unwrap(); - if let Some(m) = self.verify(haystack, pos, res, bitfield) { - return Some(m); - } - } - pos += BLOCK_SIZE; - } - // The windowing above doesn't check the last byte in the last - // window, so start the slow search at the last byte of the last - // window. - self.slow(haystack, pos.checked_sub(1).unwrap()) - } - - /// `find3` is used when there are 3 masks, e.g., the fingerprint is 3 bytes - /// long. - /// - /// N.B. This is a straight-forward extrapolation of `find2`. The only - /// difference is that we need to keep track of two previous values of `C`, - /// since we now need to align for three bytes. - #[inline(always)] - fn find3(&self, haystack: &[u8]) -> Option<Match> { - let zero = u8x16::splat(0); - let len = haystack.len(); - - let res0shuffle = u8x16::new( - 0, 0, 0, 1, - 2, 3, 4, 5, - 6, 7, 8, 9, - 10, 11, 12, 13, - ); - let res1shuffle = u8x16::new( - 0, 0, 1, 2, - 3, 4, 5, 6, - 7, 8, 9, 10, - 11, 12, 13, 14, - ); - let mut prev0 = u8x16::splat(0xFF); - let mut prev1 = u8x16::splat(0xFF); - let mut pos = 2; - while pos <= len - BLOCK_SIZE { - let h = unsafe { u8x16::load_unchecked(haystack, pos) }; - let (res0, res1, res2) = self.masks.members3(h); - - let prev0byte0 = prev0.extract(14); - let prev0byte1 = prev0.extract(15); - let res0shiftr16 = res0.shuffle_bytes(res0shuffle); - let res0prev0 = res0shiftr16.replace(0, prev0byte0) - .replace(1, prev0byte1); - - let prev1byte0 = prev1.extract(15); - let res1shiftr8 = res1.shuffle_bytes(res1shuffle); - let res1prev1 = res1shiftr8.replace(0, prev1byte0); - - let res = res0prev0 & res1prev1 & res2; - - prev0 = res0; - prev1 = res1; - - let bitfield = res.ne(zero).move_mask(); - if bitfield != 0 { - let pos = pos.checked_sub(2).unwrap(); - if let Some(m) = self.verify(haystack, pos, res, bitfield) { - return Some(m); - } - } - pos += BLOCK_SIZE; - } - // The windowing above doesn't check the last two bytes in the last - // window, so start the slow search at the penultimate byte of the - // last window. - // self.slow(haystack, pos.saturating_sub(2)) - self.slow(haystack, pos.checked_sub(2).unwrap()) - } - - /// Runs the verification procedure on `res` (i.e., `C` from the module - /// documentation), where the haystack block starts at `pos` in - /// `haystack`. `bitfield` has ones in the bit positions that `res` has - /// non-zero bytes. - /// - /// If a match exists, it returns the first one. - #[inline(always)] - fn verify( - &self, - haystack: &[u8], - pos: usize, - res: u8x16, - mut bitfield: u32, - ) -> Option<Match> { - while bitfield != 0 { - // The next offset, relative to pos, where some fingerprint - // matched. - let byte_pos = bitfield.trailing_zeros(); - bitfield &= !(1 << byte_pos); - - // Offset relative to the beginning of the haystack. - let start = pos + byte_pos as usize; - - // The bitfield telling us which patterns had fingerprints that - // match at this starting position. - let mut patterns = res.extract(byte_pos); - while patterns != 0 { - let bucket = patterns.trailing_zeros() as usize; - patterns &= !(1 << bucket); - - // Actual substring search verification. - if let Some(m) = self.verify_bucket(haystack, bucket, start) { - return Some(m); - } - } - } - - None - } - - /// Verifies whether any substring in the given bucket matches in haystack - /// at the given starting position. - #[inline(always)] - fn verify_bucket( - &self, - haystack: &[u8], - bucket: usize, - start: usize, - ) -> Option<Match> { - // This cycles through the patterns in the bucket in the order that - // the patterns were given. Therefore, we guarantee leftmost-first - // semantics. - for &pati in &self.buckets[bucket] { - let pat = &*self.pats[pati]; - if start + pat.len() > haystack.len() { - continue; - } - if pat == &haystack[start..start + pat.len()] { - return Some(Match { - pat: pati, - start: start, - end: start + pat.len(), - }); - } - } - None - } - - /// Slow substring search through all patterns in this matcher. - /// - /// This is used when we don't have enough bytes in the haystack for our - /// block based approach. - fn slow(&self, haystack: &[u8], pos: usize) -> Option<Match> { - self.ac.find(&haystack[pos..]).next().map(|m| { - Match { - pat: m.pati, - start: pos + m.start, - end: pos + m.end, - } - }) - } -} - -impl Masks { - /// Create a new set of masks of size `n`, where `n` corresponds to the - /// number of bytes in a fingerprint. - fn new(n: usize) -> Masks { - Masks(vec![Mask::new(); n]) - } - - /// Returns the number of masks. - fn len(&self) -> usize { - self.0.len() - } - - /// Adds the given pattern to the given bucket. The bucket should be a - /// power of `2 <= 2^7`. - fn add(&mut self, bucket: u8, pat: &[u8]) { - for (i, mask) in self.0.iter_mut().enumerate() { - mask.add(bucket, pat[i]); - } - } - - /// Finds the fingerprints that are in the given haystack block. i.e., this - /// returns `C` as described in the module documentation. - /// - /// More specifically, `for i in 0..16` and `j in 0..8, C[i][j] == 1` if and - /// only if `haystack_block[i]` corresponds to a fingerprint that is part - /// of a pattern in bucket `j`. - #[inline(always)] - fn members1(&self, haystack_block: u8x16) -> u8x16 { - let masklo = u8x16::splat(0xF); - let hlo = haystack_block & masklo; - let hhi = (haystack_block >> 4) & masklo; - - self.0[0].lo.shuffle_bytes(hlo) & self.0[0].hi.shuffle_bytes(hhi) - } - - /// Like members1, but computes C for the first and second bytes in the - /// fingerprint. - #[inline(always)] - fn members2(&self, haystack_block: u8x16) -> (u8x16, u8x16) { - let masklo = u8x16::splat(0xF); - let hlo = haystack_block & masklo; - let hhi = (haystack_block >> 4) & masklo; - - let res0 = self.0[0].lo.shuffle_bytes(hlo) - & self.0[0].hi.shuffle_bytes(hhi); - let res1 = self.0[1].lo.shuffle_bytes(hlo) - & self.0[1].hi.shuffle_bytes(hhi); - (res0, res1) - } - - /// Like `members1`, but computes `C` for the first, second and third bytes - /// in the fingerprint. - #[inline(always)] - fn members3(&self, haystack_block: u8x16) -> (u8x16, u8x16, u8x16) { - let masklo = u8x16::splat(0xF); - let hlo = haystack_block & masklo; - let hhi = (haystack_block >> 4) & masklo; - - let res0 = self.0[0].lo.shuffle_bytes(hlo) - & self.0[0].hi.shuffle_bytes(hhi); - let res1 = self.0[1].lo.shuffle_bytes(hlo) - & self.0[1].hi.shuffle_bytes(hhi); - let res2 = self.0[2].lo.shuffle_bytes(hlo) - & self.0[2].hi.shuffle_bytes(hhi); - (res0, res1, res2) - } -} - -impl Mask { - /// Create a new mask with no members. - fn new() -> Mask { - Mask { - lo: u8x16::splat(0), - hi: u8x16::splat(0), - } - } - - /// Adds the given byte to the given bucket. - fn add(&mut self, bucket: u8, byte: u8) { - // Split our byte into two nybbles, and add each nybble to our - // mask. - let byte_lo = (byte & 0xF) as u32; - let byte_hi = (byte >> 4) as u32; - - let lo = self.lo.extract(byte_lo); - self.lo = self.lo.replace(byte_lo, ((1 << bucket) as u8) | lo); - - let hi = self.hi.extract(byte_hi); - self.hi = self.hi.replace(byte_hi, ((1 << bucket) as u8) | hi); - } -} - -/// UnsafeLoad permits loading data into a SIMD vector without bounds checks. -/// -/// Ideally, this would be part of the `simd` crate, or even better, we could -/// figure out how to do it without `unsafe` at all. -trait UnsafeLoad { - type Elem; - - /// load_unchecked creates a new SIMD vector from the elements in `slice` - /// starting at `offset`. `slice` must have at least the number of elements - /// required to fill a SIMD vector. - unsafe fn load_unchecked(slice: &[Self::Elem], offset: usize) -> Self; -} - -impl UnsafeLoad for u8x16 { - type Elem = u8; - - unsafe fn load_unchecked(slice: &[u8], offset: usize) -> u8x16 { - let mut x = u8x16::splat(0); - ptr::copy_nonoverlapping( - slice.get_unchecked(offset), - &mut x as *mut u8x16 as *mut u8, - 16); - x - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/simd_fallback/mod.rs cargo-0.26.0/vendor/regex-0.2.6/src/simd_fallback/mod.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/simd_fallback/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/simd_fallback/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -pub mod teddy128; diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/simd_fallback/teddy128.rs cargo-0.26.0/vendor/regex-0.2.6/src/simd_fallback/teddy128.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/simd_fallback/teddy128.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/simd_fallback/teddy128.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -use syntax; - -pub fn is_teddy_128_available() -> bool { - false -} - -#[derive(Debug, Clone)] -pub struct Teddy(()); - -#[derive(Debug, Clone)] -pub struct Match { - pub pat: usize, - pub start: usize, - pub end: usize, -} - -impl Teddy { - pub fn new(_pats: &syntax::Literals) -> Option<Teddy> { None } - pub fn patterns(&self) -> &[Vec<u8>] { &[] } - pub fn len(&self) -> usize { 0 } - pub fn approximate_size(&self) -> usize { 0 } - pub fn find(&self, _haystack: &[u8]) -> Option<Match> { None } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/sparse.rs cargo-0.26.0/vendor/regex-0.2.6/src/sparse.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/sparse.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/sparse.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -use std::ops::Deref; -use std::slice; - -/// A sparse set used for representing ordered NFA states. -/// -/// This supports constant time addition and membership testing. Clearing an -/// entire set can also be done in constant time. Iteration yields elements -/// in the order in which they were inserted. -/// -/// The data structure is based on: http://research.swtch.com/sparse -/// Note though that we don't actually use unitialized memory. We generally -/// reuse allocations, so the initial allocation cost is bareable. However, -/// its other properties listed above are extremely useful. -#[derive(Clone, Debug)] -pub struct SparseSet { - /// Dense contains the instruction pointers in the order in which they - /// were inserted. Accessing elements >= self.size is illegal. - dense: Vec<usize>, - /// Sparse maps instruction pointers to their location in dense. - /// - /// An instruction pointer is in the set if and only if - /// sparse[ip] < size && ip == dense[sparse[ip]]. - sparse: Vec<usize>, - /// The number of elements in the set. - size: usize, -} - -impl SparseSet { - pub fn new(size: usize) -> SparseSet { - SparseSet { - dense: vec![0; size], - sparse: vec![0; size], - size: 0, - } - } - - pub fn len(&self) -> usize { - self.size - } - - pub fn is_empty(&self) -> bool { - self.size == 0 - } - - pub fn capacity(&self) -> usize { - self.dense.len() - } - - pub fn insert(&mut self, value: usize) { - let i = self.size; - self.dense[i] = value; - self.sparse[value] = i; - self.size += 1; - } - - pub fn contains(&self, value: usize) -> bool { - let i = self.sparse[value]; - i < self.size && self.dense[i] == value - } - - pub fn clear(&mut self) { - self.size = 0; - } -} - -impl Deref for SparseSet { - type Target = [usize]; - - fn deref(&self) -> &Self::Target { - &self.dense[0..self.size] - } -} - -impl<'a> IntoIterator for &'a SparseSet { - type Item = &'a usize; - type IntoIter = slice::Iter<'a, usize>; - fn into_iter(self) -> Self::IntoIter { self.iter() } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/testdata/basic.dat cargo-0.26.0/vendor/regex-0.2.6/src/testdata/basic.dat --- cargo-0.25.0/vendor/regex-0.2.6/src/testdata/basic.dat 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/testdata/basic.dat 1970-01-01 00:00:00.000000000 +0000 @@ -1,221 +0,0 @@ -NOTE all standard compliant implementations should pass these : 2002-05-31 - -BE abracadabra$ abracadabracadabra (7,18) -BE a...b abababbb (2,7) -BE XXXXXX ..XXXXXX (2,8) -E \) () (1,2) -BE a] a]a (0,2) -B } } (0,1) -E \} } (0,1) -BE \] ] (0,1) -B ] ] (0,1) -E ] ] (0,1) -B { { (0,1) -B } } (0,1) -BE ^a ax (0,1) -BE \^a a^a (1,3) -BE a\^ a^ (0,2) -BE a$ aa (1,2) -BE a\$ a$ (0,2) -BE ^$ NULL (0,0) -E $^ NULL (0,0) -E a($) aa (1,2)(2,2) -E a*(^a) aa (0,1)(0,1) -E (..)*(...)* a (0,0) -E (..)*(...)* abcd (0,4)(2,4) -E (ab|a)(bc|c) abc (0,3)(0,2)(2,3) -E (ab)c|abc abc (0,3)(0,2) -E a{0}b ab (1,2) -E (a*)(b?)(b+)b{3} aaabbbbbbb (0,10)(0,3)(3,4)(4,7) -E (a*)(b{0,1})(b{1,})b{3} aaabbbbbbb (0,10)(0,3)(3,4)(4,7) -E a{9876543210} NULL BADBR -E ((a|a)|a) a (0,1)(0,1)(0,1) -E (a*)(a|aa) aaaa (0,4)(0,3)(3,4) -E a*(a.|aa) aaaa (0,4)(2,4) -E a(b)|c(d)|a(e)f aef (0,3)(?,?)(?,?)(1,2) -E (a|b)?.* b (0,1)(0,1) -E (a|b)c|a(b|c) ac (0,2)(0,1) -E (a|b)c|a(b|c) ab (0,2)(?,?)(1,2) -E (a|b)*c|(a|ab)*c abc (0,3)(1,2) -E (a|b)*c|(a|ab)*c xc (1,2) -E (.a|.b).*|.*(.a|.b) xa (0,2)(0,2) -E a?(ab|ba)ab abab (0,4)(0,2) -E a?(ac{0}b|ba)ab abab (0,4)(0,2) -E ab|abab abbabab (0,2) -E aba|bab|bba baaabbbaba (5,8) -E aba|bab baaabbbaba (6,9) -E (aa|aaa)*|(a|aaaaa) aa (0,2)(0,2) -E (a.|.a.)*|(a|.a...) aa (0,2)(0,2) -E ab|a xabc (1,3) -E ab|a xxabc (2,4) -Ei (Ab|cD)* aBcD (0,4)(2,4) -BE [^-] --a (2,3) -BE [a-]* --a (0,3) -BE [a-m-]* --amoma-- (0,4) -E :::1:::0:|:::1:1:0: :::0:::1:::1:::0: (8,17) -E :::1:::0:|:::1:1:1: :::0:::1:::1:::0: (8,17) -{E [[:upper:]] A (0,1) [[<element>]] not supported -E [[:lower:]]+ `az{ (1,3) -E [[:upper:]]+ @AZ[ (1,3) -# No collation in Go -#BE [[-]] [[-]] (2,4) -#BE [[.NIL.]] NULL ECOLLATE -#BE [[=aleph=]] NULL ECOLLATE -} -BE$ \n \n (0,1) -BEn$ \n \n (0,1) -BE$ [^a] \n (0,1) -BE$ \na \na (0,2) -E (a)(b)(c) abc (0,3)(0,1)(1,2)(2,3) -BE xxx xxx (0,3) -E1 (^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$) feb 6, (0,6) -E1 (^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$) 2/7 (0,3) -E1 (^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$) feb 1,Feb 6 (5,11) -E3 ((((((((((((((((((((((((((((((x)))))))))))))))))))))))))))))) x (0,1)(0,1)(0,1) -E3 ((((((((((((((((((((((((((((((x))))))))))))))))))))))))))))))* xx (0,2)(1,2)(1,2) -E a?(ab|ba)* ababababababababababababababababababababababababababababababababababababababababa (0,81)(79,81) -E abaa|abbaa|abbbaa|abbbbaa ababbabbbabbbabbbbabbbbaa (18,25) -E abaa|abbaa|abbbaa|abbbbaa ababbabbbabbbabbbbabaa (18,22) -E aaac|aabc|abac|abbc|baac|babc|bbac|bbbc baaabbbabac (7,11) -BE$ .* \x01\x7f (0,2) -E aaaa|bbbb|cccc|ddddd|eeeeee|fffffff|gggg|hhhh|iiiii|jjjjj|kkkkk|llll XaaaXbbbXcccXdddXeeeXfffXgggXhhhXiiiXjjjXkkkXlllXcbaXaaaa (53,57) -L aaaa\nbbbb\ncccc\nddddd\neeeeee\nfffffff\ngggg\nhhhh\niiiii\njjjjj\nkkkkk\nllll XaaaXbbbXcccXdddXeeeXfffXgggXhhhXiiiXjjjXkkkXlllXcbaXaaaa NOMATCH -E a*a*a*a*a*b aaaaaaaaab (0,10) -BE ^ NULL (0,0) -BE $ NULL (0,0) -BE ^$ NULL (0,0) -BE ^a$ a (0,1) -BE abc abc (0,3) -BE abc xabcy (1,4) -BE abc ababc (2,5) -BE ab*c abc (0,3) -BE ab*bc abc (0,3) -BE ab*bc abbc (0,4) -BE ab*bc abbbbc (0,6) -E ab+bc abbc (0,4) -E ab+bc abbbbc (0,6) -E ab?bc abbc (0,4) -E ab?bc abc (0,3) -E ab?c abc (0,3) -BE ^abc$ abc (0,3) -BE ^abc abcc (0,3) -BE abc$ aabc (1,4) -BE ^ abc (0,0) -BE $ abc (3,3) -BE a.c abc (0,3) -BE a.c axc (0,3) -BE a.*c axyzc (0,5) -BE a[bc]d abd (0,3) -BE a[b-d]e ace (0,3) -BE a[b-d] aac (1,3) -BE a[-b] a- (0,2) -BE a[b-] a- (0,2) -BE a] a] (0,2) -BE a[]]b a]b (0,3) -BE a[^bc]d aed (0,3) -BE a[^-b]c adc (0,3) -BE a[^]b]c adc (0,3) -E ab|cd abc (0,2) -E ab|cd abcd (0,2) -E a\(b a(b (0,3) -E a\(*b ab (0,2) -E a\(*b a((b (0,4) -E ((a)) abc (0,1)(0,1)(0,1) -E (a)b(c) abc (0,3)(0,1)(2,3) -E a+b+c aabbabc (4,7) -E a* aaa (0,3) -#E (a*)* - (0,0)(0,0) -E (a*)* - (0,0)(?,?) RE2/Go -E (a*)+ - (0,0)(0,0) -#E (a*|b)* - (0,0)(0,0) -E (a*|b)* - (0,0)(?,?) RE2/Go -E (a+|b)* ab (0,2)(1,2) -E (a+|b)+ ab (0,2)(1,2) -E (a+|b)? ab (0,1)(0,1) -BE [^ab]* cde (0,3) -#E (^)* - (0,0)(0,0) -E (^)* - (0,0)(?,?) RE2/Go -BE a* NULL (0,0) -E ([abc])*d abbbcd (0,6)(4,5) -E ([abc])*bcd abcd (0,4)(0,1) -E a|b|c|d|e e (0,1) -E (a|b|c|d|e)f ef (0,2)(0,1) -#E ((a*|b))* - (0,0)(0,0)(0,0) -E ((a*|b))* - (0,0)(?,?)(?,?) RE2/Go -BE abcd*efg abcdefg (0,7) -BE ab* xabyabbbz (1,3) -BE ab* xayabbbz (1,2) -E (ab|cd)e abcde (2,5)(2,4) -BE [abhgefdc]ij hij (0,3) -E (a|b)c*d abcd (1,4)(1,2) -E (ab|ab*)bc abc (0,3)(0,1) -E a([bc]*)c* abc (0,3)(1,3) -E a([bc]*)(c*d) abcd (0,4)(1,3)(3,4) -E a([bc]+)(c*d) abcd (0,4)(1,3)(3,4) -E a([bc]*)(c+d) abcd (0,4)(1,2)(2,4) -E a[bcd]*dcdcde adcdcde (0,7) -E (ab|a)b*c abc (0,3)(0,2) -E ((a)(b)c)(d) abcd (0,4)(0,3)(0,1)(1,2)(3,4) -BE [A-Za-z_][A-Za-z0-9_]* alpha (0,5) -E ^a(bc+|b[eh])g|.h$ abh (1,3) -E (bc+d$|ef*g.|h?i(j|k)) effgz (0,5)(0,5) -E (bc+d$|ef*g.|h?i(j|k)) ij (0,2)(0,2)(1,2) -E (bc+d$|ef*g.|h?i(j|k)) reffgz (1,6)(1,6) -E (((((((((a))))))))) a (0,1)(0,1)(0,1)(0,1)(0,1)(0,1)(0,1)(0,1)(0,1)(0,1) -BE multiple words multiple words yeah (0,14) -E (.*)c(.*) abcde (0,5)(0,2)(3,5) -BE abcd abcd (0,4) -E a(bc)d abcd (0,4)(1,3) -E a[-]?c ac (0,3) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Qaddafi (0,15)(?,?)(10,12) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Mo'ammar Gadhafi (0,16)(?,?)(11,13) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Kaddafi (0,15)(?,?)(10,12) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Qadhafi (0,15)(?,?)(10,12) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Gadafi (0,14)(?,?)(10,11) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Mu'ammar Qadafi (0,15)(?,?)(11,12) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Moamar Gaddafi (0,14)(?,?)(9,11) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Mu'ammar Qadhdhafi (0,18)(?,?)(13,15) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Khaddafi (0,16)(?,?)(11,13) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Ghaddafy (0,16)(?,?)(11,13) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Ghadafi (0,15)(?,?)(11,12) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Ghaddafi (0,16)(?,?)(11,13) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muamar Kaddafi (0,14)(?,?)(9,11) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Quathafi (0,16)(?,?)(11,13) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Muammar Gheddafi (0,16)(?,?)(11,13) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Moammar Khadafy (0,15)(?,?)(11,12) -E M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy] Moammar Qudhafi (0,15)(?,?)(10,12) -E a+(b|c)*d+ aabcdd (0,6)(3,4) -E ^.+$ vivi (0,4) -E ^(.+)$ vivi (0,4)(0,4) -E ^([^!.]+).att.com!(.+)$ gryphon.att.com!eby (0,19)(0,7)(16,19) -E ^([^!]+!)?([^!]+)$ bas (0,3)(?,?)(0,3) -E ^([^!]+!)?([^!]+)$ bar!bas (0,7)(0,4)(4,7) -E ^([^!]+!)?([^!]+)$ foo!bas (0,7)(0,4)(4,7) -E ^.+!([^!]+!)([^!]+)$ foo!bar!bas (0,11)(4,8)(8,11) -E ((foo)|(bar))!bas bar!bas (0,7)(0,3)(?,?)(0,3) -E ((foo)|(bar))!bas foo!bar!bas (4,11)(4,7)(?,?)(4,7) -E ((foo)|(bar))!bas foo!bas (0,7)(0,3)(0,3) -E ((foo)|bar)!bas bar!bas (0,7)(0,3) -E ((foo)|bar)!bas foo!bar!bas (4,11)(4,7) -E ((foo)|bar)!bas foo!bas (0,7)(0,3)(0,3) -E (foo|(bar))!bas bar!bas (0,7)(0,3)(0,3) -E (foo|(bar))!bas foo!bar!bas (4,11)(4,7)(4,7) -E (foo|(bar))!bas foo!bas (0,7)(0,3) -E (foo|bar)!bas bar!bas (0,7)(0,3) -E (foo|bar)!bas foo!bar!bas (4,11)(4,7) -E (foo|bar)!bas foo!bas (0,7)(0,3) -E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ foo!bar!bas (0,11)(0,11)(?,?)(?,?)(4,8)(8,11) -E ^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$ bas (0,3)(?,?)(0,3) -E ^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$ bar!bas (0,7)(0,4)(4,7) -E ^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$ foo!bar!bas (0,11)(?,?)(?,?)(4,8)(8,11) -E ^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$ foo!bas (0,7)(0,4)(4,7) -E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ bas (0,3)(0,3)(?,?)(0,3) -E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ bar!bas (0,7)(0,7)(0,4)(4,7) -E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ foo!bar!bas (0,11)(0,11)(?,?)(?,?)(4,8)(8,11) -E ^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$ foo!bas (0,7)(0,7)(0,4)(4,7) -E .*(/XXX).* /XXX (0,4)(0,4) -E .*(\\XXX).* \XXX (0,4)(0,4) -E \\XXX \XXX (0,4) -E .*(/000).* /000 (0,4)(0,4) -E .*(\\000).* \000 (0,4)(0,4) -E \\000 \000 (0,4) diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/testdata/LICENSE cargo-0.26.0/vendor/regex-0.2.6/src/testdata/LICENSE --- cargo-0.25.0/vendor/regex-0.2.6/src/testdata/LICENSE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/testdata/LICENSE 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -The following license covers testregex.c and all associated test data. - -Permission is hereby granted, free of charge, to any person obtaining a -copy of THIS SOFTWARE FILE (the "Software"), to deal in the Software -without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, and/or sell copies of the -Software, and to permit persons to whom the Software is furnished to do -so, subject to the following disclaimer: - -THIS SOFTWARE IS PROVIDED BY AT&T ``AS IS'' AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -IN NO EVENT SHALL AT&T BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/testdata/nullsubexpr.dat cargo-0.26.0/vendor/regex-0.2.6/src/testdata/nullsubexpr.dat --- cargo-0.25.0/vendor/regex-0.2.6/src/testdata/nullsubexpr.dat 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/testdata/nullsubexpr.dat 1970-01-01 00:00:00.000000000 +0000 @@ -1,79 +0,0 @@ -NOTE null subexpression matches : 2002-06-06 - -E (a*)* a (0,1)(0,1) -#E SAME x (0,0)(0,0) -E SAME x (0,0)(?,?) RE2/Go -E SAME aaaaaa (0,6)(0,6) -E SAME aaaaaax (0,6)(0,6) -E (a*)+ a (0,1)(0,1) -E SAME x (0,0)(0,0) -E SAME aaaaaa (0,6)(0,6) -E SAME aaaaaax (0,6)(0,6) -E (a+)* a (0,1)(0,1) -E SAME x (0,0) -E SAME aaaaaa (0,6)(0,6) -E SAME aaaaaax (0,6)(0,6) -E (a+)+ a (0,1)(0,1) -E SAME x NOMATCH -E SAME aaaaaa (0,6)(0,6) -E SAME aaaaaax (0,6)(0,6) - -E ([a]*)* a (0,1)(0,1) -#E SAME x (0,0)(0,0) -E SAME x (0,0)(?,?) RE2/Go -E SAME aaaaaa (0,6)(0,6) -E SAME aaaaaax (0,6)(0,6) -E ([a]*)+ a (0,1)(0,1) -E SAME x (0,0)(0,0) -E SAME aaaaaa (0,6)(0,6) -E SAME aaaaaax (0,6)(0,6) -E ([^b]*)* a (0,1)(0,1) -#E SAME b (0,0)(0,0) -E SAME b (0,0)(?,?) RE2/Go -E SAME aaaaaa (0,6)(0,6) -E SAME aaaaaab (0,6)(0,6) -E ([ab]*)* a (0,1)(0,1) -E SAME aaaaaa (0,6)(0,6) -E SAME ababab (0,6)(0,6) -E SAME bababa (0,6)(0,6) -E SAME b (0,1)(0,1) -E SAME bbbbbb (0,6)(0,6) -E SAME aaaabcde (0,5)(0,5) -E ([^a]*)* b (0,1)(0,1) -E SAME bbbbbb (0,6)(0,6) -#E SAME aaaaaa (0,0)(0,0) -E SAME aaaaaa (0,0)(?,?) RE2/Go -E ([^ab]*)* ccccxx (0,6)(0,6) -#E SAME ababab (0,0)(0,0) -E SAME ababab (0,0)(?,?) RE2/Go - -E ((z)+|a)* zabcde (0,2)(1,2) - -#{E a+? aaaaaa (0,1) no *? +? mimimal match ops -#E (a) aaa (0,1)(0,1) -#E (a*?) aaa (0,0)(0,0) -#E (a)*? aaa (0,0) -#E (a*?)*? aaa (0,0) -#} - -B \(a*\)*\(x\) x (0,1)(0,0)(0,1) -B \(a*\)*\(x\) ax (0,2)(0,1)(1,2) -B \(a*\)*\(x\) axa (0,2)(0,1)(1,2) -B \(a*\)*\(x\)\(\1\) x (0,1)(0,0)(0,1)(1,1) -B \(a*\)*\(x\)\(\1\) ax (0,2)(1,1)(1,2)(2,2) -B \(a*\)*\(x\)\(\1\) axa (0,3)(0,1)(1,2)(2,3) -B \(a*\)*\(x\)\(\1\)\(x\) axax (0,4)(0,1)(1,2)(2,3)(3,4) -B \(a*\)*\(x\)\(\1\)\(x\) axxa (0,3)(1,1)(1,2)(2,2)(2,3) - -#E (a*)*(x) x (0,1)(0,0)(0,1) -E (a*)*(x) x (0,1)(?,?)(0,1) RE2/Go -E (a*)*(x) ax (0,2)(0,1)(1,2) -E (a*)*(x) axa (0,2)(0,1)(1,2) - -E (a*)+(x) x (0,1)(0,0)(0,1) -E (a*)+(x) ax (0,2)(0,1)(1,2) -E (a*)+(x) axa (0,2)(0,1)(1,2) - -E (a*){2}(x) x (0,1)(0,0)(0,1) -E (a*){2}(x) ax (0,2)(1,1)(1,2) -E (a*){2}(x) axa (0,2)(1,1)(1,2) diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/testdata/README cargo-0.26.0/vendor/regex-0.2.6/src/testdata/README --- cargo-0.25.0/vendor/regex-0.2.6/src/testdata/README 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/testdata/README 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -Test data was taken from the Go distribution, which was in turn taken from the -testregex test suite: - - http://www2.research.att.com/~astopen/testregex/testregex.html - -The LICENSE in this directory corresponds to the LICENSE that the data was -released under. - -The tests themselves were modified for RE2/Go. A couple were modified further -by me (Andrew Gallant) (only in repetition.dat) so that RE2/Go would pass them. -(Yes, it seems like RE2/Go includes failing test cases.) This may or may not -have been a bad idea, but I think being consistent with an established Regex -library is worth something. - -Note that these files are read by 'scripts/regex-match-tests.py' and turned -into Rust tests found in 'regex_macros/tests/matches.rs'. - diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/testdata/repetition.dat cargo-0.26.0/vendor/regex-0.2.6/src/testdata/repetition.dat --- cargo-0.25.0/vendor/regex-0.2.6/src/testdata/repetition.dat 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/testdata/repetition.dat 1970-01-01 00:00:00.000000000 +0000 @@ -1,163 +0,0 @@ -NOTE implicit vs. explicit repetitions : 2009-02-02 - -# Glenn Fowler <gsf@research.att.com> -# conforming matches (column 4) must match one of the following BREs -# NOMATCH -# (0,.)\((\(.\),\(.\))(?,?)(\2,\3)\)* -# (0,.)\((\(.\),\(.\))(\2,\3)(?,?)\)* -# i.e., each 3-tuple has two identical elements and one (?,?) - -E ((..)|(.)) NULL NOMATCH -E ((..)|(.))((..)|(.)) NULL NOMATCH -E ((..)|(.))((..)|(.))((..)|(.)) NULL NOMATCH - -E ((..)|(.)){1} NULL NOMATCH -E ((..)|(.)){2} NULL NOMATCH -E ((..)|(.)){3} NULL NOMATCH - -E ((..)|(.))* NULL (0,0) - -E ((..)|(.)) a (0,1)(0,1)(?,?)(0,1) -E ((..)|(.))((..)|(.)) a NOMATCH -E ((..)|(.))((..)|(.))((..)|(.)) a NOMATCH - -E ((..)|(.)){1} a (0,1)(0,1)(?,?)(0,1) -E ((..)|(.)){2} a NOMATCH -E ((..)|(.)){3} a NOMATCH - -E ((..)|(.))* a (0,1)(0,1)(?,?)(0,1) - -E ((..)|(.)) aa (0,2)(0,2)(0,2)(?,?) -E ((..)|(.))((..)|(.)) aa (0,2)(0,1)(?,?)(0,1)(1,2)(?,?)(1,2) -E ((..)|(.))((..)|(.))((..)|(.)) aa NOMATCH - -E ((..)|(.)){1} aa (0,2)(0,2)(0,2)(?,?) -E ((..)|(.)){2} aa (0,2)(1,2)(?,?)(1,2) -E ((..)|(.)){3} aa NOMATCH - -E ((..)|(.))* aa (0,2)(0,2)(0,2)(?,?) - -E ((..)|(.)) aaa (0,2)(0,2)(0,2)(?,?) -E ((..)|(.))((..)|(.)) aaa (0,3)(0,2)(0,2)(?,?)(2,3)(?,?)(2,3) -E ((..)|(.))((..)|(.))((..)|(.)) aaa (0,3)(0,1)(?,?)(0,1)(1,2)(?,?)(1,2)(2,3)(?,?)(2,3) - -E ((..)|(.)){1} aaa (0,2)(0,2)(0,2)(?,?) -#E ((..)|(.)){2} aaa (0,3)(2,3)(?,?)(2,3) -E ((..)|(.)){2} aaa (0,3)(2,3)(0,2)(2,3) RE2/Go -E ((..)|(.)){3} aaa (0,3)(2,3)(?,?)(2,3) - -#E ((..)|(.))* aaa (0,3)(2,3)(?,?)(2,3) -E ((..)|(.))* aaa (0,3)(2,3)(0,2)(2,3) RE2/Go - -E ((..)|(.)) aaaa (0,2)(0,2)(0,2)(?,?) -E ((..)|(.))((..)|(.)) aaaa (0,4)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?) -E ((..)|(.))((..)|(.))((..)|(.)) aaaa (0,4)(0,2)(0,2)(?,?)(2,3)(?,?)(2,3)(3,4)(?,?)(3,4) - -E ((..)|(.)){1} aaaa (0,2)(0,2)(0,2)(?,?) -E ((..)|(.)){2} aaaa (0,4)(2,4)(2,4)(?,?) -#E ((..)|(.)){3} aaaa (0,4)(3,4)(?,?)(3,4) -E ((..)|(.)){3} aaaa (0,4)(3,4)(0,2)(3,4) RE2/Go - -E ((..)|(.))* aaaa (0,4)(2,4)(2,4)(?,?) - -E ((..)|(.)) aaaaa (0,2)(0,2)(0,2)(?,?) -E ((..)|(.))((..)|(.)) aaaaa (0,4)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?) -E ((..)|(.))((..)|(.))((..)|(.)) aaaaa (0,5)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?)(4,5)(?,?)(4,5) - -E ((..)|(.)){1} aaaaa (0,2)(0,2)(0,2)(?,?) -E ((..)|(.)){2} aaaaa (0,4)(2,4)(2,4)(?,?) -#E ((..)|(.)){3} aaaaa (0,5)(4,5)(?,?)(4,5) -E ((..)|(.)){3} aaaaa (0,5)(4,5)(2,4)(4,5) RE2/Go - -#E ((..)|(.))* aaaaa (0,5)(4,5)(?,?)(4,5) -E ((..)|(.))* aaaaa (0,5)(4,5)(2,4)(4,5) RE2/Go - -E ((..)|(.)) aaaaaa (0,2)(0,2)(0,2)(?,?) -E ((..)|(.))((..)|(.)) aaaaaa (0,4)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?) -E ((..)|(.))((..)|(.))((..)|(.)) aaaaaa (0,6)(0,2)(0,2)(?,?)(2,4)(2,4)(?,?)(4,6)(4,6)(?,?) - -E ((..)|(.)){1} aaaaaa (0,2)(0,2)(0,2)(?,?) -E ((..)|(.)){2} aaaaaa (0,4)(2,4)(2,4)(?,?) -E ((..)|(.)){3} aaaaaa (0,6)(4,6)(4,6)(?,?) - -E ((..)|(.))* aaaaaa (0,6)(4,6)(4,6)(?,?) - -NOTE additional repetition tests graciously provided by Chris Kuklewicz www.haskell.org 2009-02-02 - -# These test a bug in OS X / FreeBSD / NetBSD, and libtree. -# Linux/GLIBC gets the {8,} and {8,8} wrong. - -:HA#100:E X(.?){0,}Y X1234567Y (0,9)(7,8) -:HA#101:E X(.?){1,}Y X1234567Y (0,9)(7,8) -:HA#102:E X(.?){2,}Y X1234567Y (0,9)(7,8) -:HA#103:E X(.?){3,}Y X1234567Y (0,9)(7,8) -:HA#104:E X(.?){4,}Y X1234567Y (0,9)(7,8) -:HA#105:E X(.?){5,}Y X1234567Y (0,9)(7,8) -:HA#106:E X(.?){6,}Y X1234567Y (0,9)(7,8) -:HA#107:E X(.?){7,}Y X1234567Y (0,9)(7,8) -:HA#108:E X(.?){8,}Y X1234567Y (0,9)(8,8) -#:HA#110:E X(.?){0,8}Y X1234567Y (0,9)(7,8) -:HA#110:E X(.?){0,8}Y X1234567Y (0,9)(8,8) RE2/Go -#:HA#111:E X(.?){1,8}Y X1234567Y (0,9)(7,8) -:HA#111:E X(.?){1,8}Y X1234567Y (0,9)(8,8) RE2/Go -#:HA#112:E X(.?){2,8}Y X1234567Y (0,9)(7,8) -:HA#112:E X(.?){2,8}Y X1234567Y (0,9)(8,8) RE2/Go -#:HA#113:E X(.?){3,8}Y X1234567Y (0,9)(7,8) -:HA#113:E X(.?){3,8}Y X1234567Y (0,9)(8,8) RE2/Go -#:HA#114:E X(.?){4,8}Y X1234567Y (0,9)(7,8) -:HA#114:E X(.?){4,8}Y X1234567Y (0,9)(8,8) RE2/Go -#:HA#115:E X(.?){5,8}Y X1234567Y (0,9)(7,8) -:HA#115:E X(.?){5,8}Y X1234567Y (0,9)(8,8) RE2/Go -#:HA#116:E X(.?){6,8}Y X1234567Y (0,9)(7,8) -:HA#116:E X(.?){6,8}Y X1234567Y (0,9)(8,8) RE2/Go -#:HA#117:E X(.?){7,8}Y X1234567Y (0,9)(7,8) -:HA#117:E X(.?){7,8}Y X1234567Y (0,9)(8,8) RE2/Go -:HA#118:E X(.?){8,8}Y X1234567Y (0,9)(8,8) - -# These test a fixed bug in my regex-tdfa that did not keep the expanded -# form properly grouped, so right association did the wrong thing with -# these ambiguous patterns (crafted just to test my code when I became -# suspicious of my implementation). The first subexpression should use -# "ab" then "a" then "bcd". - -# OS X / FreeBSD / NetBSD badly fail many of these, with impossible -# results like (0,6)(4,5)(6,6). - -:HA#260:E (a|ab|c|bcd){0,}(d*) ababcd (0,1)(0,1)(1,1) -:HA#261:E (a|ab|c|bcd){1,}(d*) ababcd (0,1)(0,1)(1,1) -:HA#262:E (a|ab|c|bcd){2,}(d*) ababcd (0,6)(3,6)(6,6) -:HA#263:E (a|ab|c|bcd){3,}(d*) ababcd (0,6)(3,6)(6,6) -:HA#264:E (a|ab|c|bcd){4,}(d*) ababcd NOMATCH -:HA#265:E (a|ab|c|bcd){0,10}(d*) ababcd (0,1)(0,1)(1,1) -:HA#266:E (a|ab|c|bcd){1,10}(d*) ababcd (0,1)(0,1)(1,1) -:HA#267:E (a|ab|c|bcd){2,10}(d*) ababcd (0,6)(3,6)(6,6) -:HA#268:E (a|ab|c|bcd){3,10}(d*) ababcd (0,6)(3,6)(6,6) -:HA#269:E (a|ab|c|bcd){4,10}(d*) ababcd NOMATCH -:HA#270:E (a|ab|c|bcd)*(d*) ababcd (0,1)(0,1)(1,1) -:HA#271:E (a|ab|c|bcd)+(d*) ababcd (0,1)(0,1)(1,1) - -# The above worked on Linux/GLIBC but the following often fail. -# They also trip up OS X / FreeBSD / NetBSD: - -#:HA#280:E (ab|a|c|bcd){0,}(d*) ababcd (0,6)(3,6)(6,6) -:HA#280:E (ab|a|c|bcd){0,}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go -#:HA#281:E (ab|a|c|bcd){1,}(d*) ababcd (0,6)(3,6)(6,6) -:HA#281:E (ab|a|c|bcd){1,}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go -#:HA#282:E (ab|a|c|bcd){2,}(d*) ababcd (0,6)(3,6)(6,6) -:HA#282:E (ab|a|c|bcd){2,}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go -#:HA#283:E (ab|a|c|bcd){3,}(d*) ababcd (0,6)(3,6)(6,6) -:HA#283:E (ab|a|c|bcd){3,}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go -:HA#284:E (ab|a|c|bcd){4,}(d*) ababcd NOMATCH -#:HA#285:E (ab|a|c|bcd){0,10}(d*) ababcd (0,6)(3,6)(6,6) -:HA#285:E (ab|a|c|bcd){0,10}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go -#:HA#286:E (ab|a|c|bcd){1,10}(d*) ababcd (0,6)(3,6)(6,6) -:HA#286:E (ab|a|c|bcd){1,10}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go -#:HA#287:E (ab|a|c|bcd){2,10}(d*) ababcd (0,6)(3,6)(6,6) -:HA#287:E (ab|a|c|bcd){2,10}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go -#:HA#288:E (ab|a|c|bcd){3,10}(d*) ababcd (0,6)(3,6)(6,6) -:HA#288:E (ab|a|c|bcd){3,10}(d*) ababcd (0,6)(4,5)(5,6) RE2/Go -:HA#289:E (ab|a|c|bcd){4,10}(d*) ababcd NOMATCH -#:HA#290:E (ab|a|c|bcd)*(d*) ababcd (0,6)(3,6)(6,6) -:HA#290:E (ab|a|c|bcd)*(d*) ababcd (0,6)(4,5)(5,6) RE2/Go -#:HA#291:E (ab|a|c|bcd)+(d*) ababcd (0,6)(3,6)(6,6) -:HA#291:E (ab|a|c|bcd)+(d*) ababcd (0,6)(4,5)(5,6) RE2/Go diff -Nru cargo-0.25.0/vendor/regex-0.2.6/src/utf8.rs cargo-0.26.0/vendor/regex-0.2.6/src/utf8.rs --- cargo-0.25.0/vendor/regex-0.2.6/src/utf8.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/src/utf8.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,290 +0,0 @@ -/// A few elementary UTF-8 encoding and decoding functions used by the matching -/// engines. -/// -/// In an ideal world, the matching engines operate on `&str` and we can just -/// lean on the standard library for all our UTF-8 needs. However, to support -/// byte based regexes (that can match on arbitrary bytes which may contain -/// UTF-8), we need to be capable of searching and decoding UTF-8 on a `&[u8]`. -/// The standard library doesn't really recognize this use case, so we have -/// to build it out ourselves. -/// -/// Should this be factored out into a separate crate? It seems independently -/// useful. There are other crates that already exist (e.g., `utf-8`) that have -/// overlapping use cases. Not sure what to do. - -use std::char; - -const TAG_CONT: u8 = 0b1000_0000; -const TAG_TWO: u8 = 0b1100_0000; -const TAG_THREE: u8 = 0b1110_0000; -const TAG_FOUR: u8 = 0b1111_0000; - -/// Returns the smallest possible index of the next valid UTF-8 sequence -/// starting after `i`. -pub fn next_utf8(text: &[u8], i: usize) -> usize { - let b = match text.get(i) { - None => return i + 1, - Some(&b) => b, - }; - let inc = if b <= 0x7F { - 1 - } else if b <= 0b110_11111 { - 2 - } else if b <= 0b1110_1111 { - 3 - } else { - 4 - }; - i + inc -} - -/// Encode the given Unicode character to `dst` as a single UTF-8 sequence. -/// -/// If `dst` is not long enough, then `None` is returned. Otherwise, the number -/// of bytes written is returned. -#[allow(dead_code)] -#[inline] -pub fn encode_utf8(character: char, dst: &mut [u8]) -> Option<usize> { - let code = character as u32; - if code <= 0x7F && !dst.is_empty() { - dst[0] = code as u8; - Some(1) - } else if code <= 0x7FF && dst.len() >= 2 { - dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO; - dst[1] = (code & 0x3F) as u8 | TAG_CONT; - Some(2) - } else if code <= 0xFFFF && dst.len() >= 3 { - dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE; - dst[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT; - dst[2] = (code & 0x3F) as u8 | TAG_CONT; - Some(3) - } else if dst.len() >= 4 { - dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR; - dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; - dst[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; - dst[3] = (code & 0x3F) as u8 | TAG_CONT; - Some(4) - } else { - None - } -} - -/// Decode a single UTF-8 sequence into a single Unicode codepoint from `src`. -/// -/// If no valid UTF-8 sequence could be found, then `None` is returned. -/// Otherwise, the decoded codepoint and the number of bytes read is returned. -/// The number of bytes read (for a valid UTF-8 sequence) is guaranteed to be -/// 1, 2, 3 or 4. -/// -/// Note that a UTF-8 sequence is invalid if it is incorrect UTF-8, encodes a -/// codepoint that is out of range (surrogate codepoints are out of range) or -/// is not the shortest possible UTF-8 sequence for that codepoint. -#[inline] -pub fn decode_utf8(src: &[u8]) -> Option<(char, usize)> { - let b0 = match src.get(0) { - None => return None, - Some(&b) if b <= 0x7F => return Some((b as char, 1)), - Some(&b) => b, - }; - match b0 { - 0b110_00000 ... 0b110_11111 => { - if src.len() < 2 { - return None; - } - let b1 = src[1]; - if 0b11_000000 & b1 != TAG_CONT { - return None; - } - let cp = ((b0 & !TAG_TWO) as u32) << 6 - | ((b1 & !TAG_CONT) as u32); - match cp { - 0x80 ... 0x7FF => char::from_u32(cp).map(|cp| (cp, 2)), - _ => None, - } - } - 0b1110_0000 ... 0b1110_1111 => { - if src.len() < 3 { - return None; - } - let (b1, b2) = (src[1], src[2]); - if 0b11_000000 & b1 != TAG_CONT { - return None; - } - if 0b11_000000 & b2 != TAG_CONT { - return None; - } - let cp = ((b0 & !TAG_THREE) as u32) << 12 - | ((b1 & !TAG_CONT) as u32) << 6 - | ((b2 & !TAG_CONT) as u32); - match cp { - // char::from_u32 will disallow surrogate codepoints. - 0x800 ... 0xFFFF => char::from_u32(cp).map(|cp| (cp, 3)), - _ => None, - } - } - 0b11110_000 ... 0b11110_111 => { - if src.len() < 4 { - return None; - } - let (b1, b2, b3) = (src[1], src[2], src[3]); - if 0b11_000000 & b1 != TAG_CONT { - return None; - } - if 0b11_000000 & b2 != TAG_CONT { - return None; - } - if 0b11_000000 & b3 != TAG_CONT { - return None; - } - let cp = ((b0 & !TAG_FOUR) as u32) << 18 - | ((b1 & !TAG_CONT) as u32) << 12 - | ((b2 & !TAG_CONT) as u32) << 6 - | ((b3 & !TAG_CONT) as u32); - match cp { - 0x10000 ... 0x10FFFF => char::from_u32(cp).map(|cp| (cp, 4)), - _ => None, - } - } - _ => None, - } -} - -/// Like `decode_utf8`, but decodes the last UTF-8 sequence in `src` instead -/// of the first. -pub fn decode_last_utf8(src: &[u8]) -> Option<(char, usize)> { - if src.is_empty() { - return None; - } - let mut start = src.len() - 1; - if src[start] <= 0x7F { - return Some((src[start] as char, 1)); - } - while start > src.len().saturating_sub(4) { - start -= 1; - if is_start_byte(src[start]) { - break; - } - } - match decode_utf8(&src[start..]) { - None => None, - Some((_, n)) if n < src.len() - start => None, - Some((cp, n)) => Some((cp, n)), - } -} - -fn is_start_byte(b: u8) -> bool { - b & 0b11_000000 != 0b1_0000000 -} - -#[cfg(test)] -mod tests { - use std::str; - - use quickcheck::quickcheck; - - use super::{ - TAG_CONT, TAG_TWO, TAG_THREE, TAG_FOUR, - decode_utf8, decode_last_utf8, encode_utf8, - }; - - #[test] - fn prop_roundtrip() { - fn p(given_cp: char) -> bool { - let mut tmp = [0; 4]; - let encoded_len = encode_utf8(given_cp, &mut tmp).unwrap(); - let (got_cp, got_len) = decode_utf8(&tmp[..encoded_len]).unwrap(); - encoded_len == got_len && given_cp == got_cp - } - quickcheck(p as fn(char) -> bool) - } - - #[test] - fn prop_roundtrip_last() { - fn p(given_cp: char) -> bool { - let mut tmp = [0; 4]; - let encoded_len = encode_utf8(given_cp, &mut tmp).unwrap(); - let (got_cp, got_len) = - decode_last_utf8(&tmp[..encoded_len]).unwrap(); - encoded_len == got_len && given_cp == got_cp - } - quickcheck(p as fn(char) -> bool) - } - - #[test] - fn prop_encode_matches_std() { - fn p(cp: char) -> bool { - let mut got = [0; 4]; - let n = encode_utf8(cp, &mut got).unwrap(); - let expected = cp.to_string(); - &got[..n] == expected.as_bytes() - } - quickcheck(p as fn(char) -> bool) - } - - #[test] - fn prop_decode_matches_std() { - fn p(given_cp: char) -> bool { - let mut tmp = [0; 4]; - let n = encode_utf8(given_cp, &mut tmp).unwrap(); - let (got_cp, _) = decode_utf8(&tmp[..n]).unwrap(); - let expected_cp = - str::from_utf8(&tmp[..n]).unwrap().chars().next().unwrap(); - got_cp == expected_cp - } - quickcheck(p as fn(char) -> bool) - } - - #[test] - fn prop_decode_last_matches_std() { - fn p(given_cp: char) -> bool { - let mut tmp = [0; 4]; - let n = encode_utf8(given_cp, &mut tmp).unwrap(); - let (got_cp, _) = decode_last_utf8(&tmp[..n]).unwrap(); - let expected_cp = - str::from_utf8(&tmp[..n]).unwrap() - .chars().rev().next().unwrap(); - got_cp == expected_cp - } - quickcheck(p as fn(char) -> bool) - } - - #[test] - fn reject_invalid() { - // Invalid start byte - assert_eq!(decode_utf8(&[0xFF]), None); - // Surrogate pair - assert_eq!(decode_utf8(&[0xED, 0xA0, 0x81]), None); - // Invalid continuation byte. - assert_eq!(decode_utf8(&[0xD4, 0xC2]), None); - // Bad lengths - assert_eq!(decode_utf8(&[0xC3]), None); // 2 bytes - assert_eq!(decode_utf8(&[0xEF, 0xBF]), None); // 3 bytes - assert_eq!(decode_utf8(&[0xF4, 0x8F, 0xBF]), None); // 4 bytes - // Not a minimal UTF-8 sequence - assert_eq!(decode_utf8(&[TAG_TWO, TAG_CONT | b'a']), None); - assert_eq!(decode_utf8(&[TAG_THREE, TAG_CONT, TAG_CONT | b'a']), None); - assert_eq!(decode_utf8(&[ - TAG_FOUR, TAG_CONT, TAG_CONT, TAG_CONT | b'a', - ]), None); - } - - #[test] - fn reject_invalid_last() { - // Invalid start byte - assert_eq!(decode_last_utf8(&[0xFF]), None); - // Surrogate pair - assert_eq!(decode_last_utf8(&[0xED, 0xA0, 0x81]), None); - // Bad lengths - assert_eq!(decode_last_utf8(&[0xC3]), None); // 2 bytes - assert_eq!(decode_last_utf8(&[0xEF, 0xBF]), None); // 3 bytes - assert_eq!(decode_last_utf8(&[0xF4, 0x8F, 0xBF]), None); // 4 bytes - // Not a minimal UTF-8 sequence - assert_eq!(decode_last_utf8(&[TAG_TWO, TAG_CONT | b'a']), None); - assert_eq!(decode_last_utf8(&[ - TAG_THREE, TAG_CONT, TAG_CONT | b'a', - ]), None); - assert_eq!(decode_last_utf8(&[ - TAG_FOUR, TAG_CONT, TAG_CONT, TAG_CONT | b'a', - ]), None); - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/api.rs cargo-0.26.0/vendor/regex-0.2.6/tests/api.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/api.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/api.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,182 +0,0 @@ -#[test] -fn empty_regex_empty_match() { - let re = regex!(""); - assert_eq!(vec![(0, 0)], findall!(re, "")); -} - -#[test] -fn empty_regex_nonempty_match() { - let re = regex!(""); - assert_eq!(vec![(0, 0), (1, 1), (2, 2), (3, 3)], findall!(re, "abc")); -} - -#[test] -fn one_zero_length_match() { - let re = regex!(r"\d*"); - assert_eq!(vec![(0, 0), (1, 2), (3, 4)], findall!(re, "a1b2")); -} - -#[test] -fn many_zero_length_match() { - let re = regex!(r"\d*"); - assert_eq!(vec![(0, 0), (1, 2), (3, 3), (4, 4), (5, 6)], - findall!(re, "a1bbb2")); -} - -#[test] -fn many_sequential_zero_length_match() { - let re = regex!(r"\d?"); - assert_eq!(vec![(0, 0), (1, 2), (2, 3), (4, 5), (6, 6)], - findall!(re, "a12b3c")); -} - -#[test] -fn quoted_bracket_set() { - let re = regex!(r"([\x{5b}\x{5d}])"); - assert_eq!(vec![(0, 1), (1, 2)], findall!(re, "[]")); - let re = regex!(r"([\[\]])"); - assert_eq!(vec![(0, 1), (1, 2)], findall!(re, "[]")); -} - -#[test] -fn first_range_starts_with_left_bracket() { - let re = regex!(r"([\[-z])"); - assert_eq!(vec![(0, 1), (1, 2)], findall!(re, "[]")); -} - -#[test] -fn range_ends_with_escape() { - let re = regex!(r"([\[-\x{5d}])"); - assert_eq!(vec![(0, 1), (1, 2)], findall!(re, "[]")); -} - -#[test] -fn empty_match_find_iter() { - let re = regex!(r".*?"); - assert_eq!(vec![(0, 0), (1, 1), (2, 2), (3, 3)], findall!(re, "abc")); -} - -#[test] -fn empty_match_captures_iter() { - let re = regex!(r".*?"); - let ms: Vec<_> = re.captures_iter(text!("abc")) - .map(|c| c.get(0).unwrap()) - .map(|m| (m.start(), m.end())) - .collect(); - assert_eq!(ms, vec![(0, 0), (1, 1), (2, 2), (3, 3)]); -} - -#[test] -fn capture_names() { - let re = regex!(r"(.)(?P<a>.)"); - assert_eq!(3, re.captures_len()); - assert_eq!((3, Some(3)), re.capture_names().size_hint()); - assert_eq!(vec![None, None, Some("a")], - re.capture_names().collect::<Vec<_>>()); -} - -#[test] -fn regex_string() { - assert_eq!(r"[a-zA-Z0-9]+", regex!(r"[a-zA-Z0-9]+").as_str()); - assert_eq!(r"[a-zA-Z0-9]+", &format!("{}", regex!(r"[a-zA-Z0-9]+"))); - assert_eq!(r"[a-zA-Z0-9]+", &format!("{:?}", regex!(r"[a-zA-Z0-9]+"))); -} - -#[test] -fn capture_index() { - let re = regex!(r"^(?P<name>.+)$"); - let cap = re.captures(t!("abc")).unwrap(); - assert_eq!(&cap[0], t!("abc")); - assert_eq!(&cap[1], t!("abc")); - assert_eq!(&cap["name"], t!("abc")); -} - -#[test] -#[should_panic] -#[cfg_attr(all(target_env = "msvc", target_pointer_width = "32"), ignore)] -fn capture_index_panic_usize() { - let re = regex!(r"^(?P<name>.+)$"); - let cap = re.captures(t!("abc")).unwrap(); - let _ = cap[2]; -} - -#[test] -#[should_panic] -#[cfg_attr(all(target_env = "msvc", target_pointer_width = "32"), ignore)] -fn capture_index_panic_name() { - let re = regex!(r"^(?P<name>.+)$"); - let cap = re.captures(t!("abc")).unwrap(); - let _ = cap["bad name"]; -} - -#[test] -fn capture_index_lifetime() { - // This is a test of whether the types on `caps["..."]` are general - // enough. If not, this will fail to typecheck. - fn inner(s: &str) -> usize { - let re = regex!(r"(?P<number>\d+)"); - let caps = re.captures(t!(s)).unwrap(); - caps["number"].len() - } - assert_eq!(3, inner("123")); -} - -#[test] -fn capture_misc() { - let re = regex!(r"(.)(?P<a>a)?(.)(?P<b>.)"); - let cap = re.captures(t!("abc")).unwrap(); - - assert_eq!(5, cap.len()); - - assert_eq!((0, 3), { let m = cap.get(0).unwrap(); (m.start(), m.end()) }); - assert_eq!(None, cap.get(2)); - assert_eq!((2, 3), { let m = cap.get(4).unwrap(); (m.start(), m.end()) }); - - assert_eq!(t!("abc"), match_text!(cap.get(0).unwrap())); - assert_eq!(None, cap.get(2)); - assert_eq!(t!("c"), match_text!(cap.get(4).unwrap())); - - assert_eq!(None, cap.name("a")); - assert_eq!(t!("c"), match_text!(cap.name("b").unwrap())); -} - -#[test] -fn sub_capture_matches() { - let re = regex!(r"([a-z])(([a-z])|([0-9]))"); - let cap = re.captures(t!("a5")).unwrap(); - let subs: Vec<_> = cap.iter().collect(); - - assert_eq!(5, subs.len()); - assert!(subs[0].is_some()); - assert!(subs[1].is_some()); - assert!(subs[2].is_some()); - assert!(subs[3].is_none()); - assert!(subs[4].is_some()); - - assert_eq!(t!("a5"), match_text!(subs[0].unwrap())); - assert_eq!(t!("a"), match_text!(subs[1].unwrap())); - assert_eq!(t!("5"), match_text!(subs[2].unwrap())); - assert_eq!(t!("5"), match_text!(subs[4].unwrap())); -} - -expand!(expand1, r"(?P<foo>\w+)", "abc", "$foo", "abc"); -expand!(expand2, r"(?P<foo>\w+)", "abc", "$0", "abc"); -expand!(expand3, r"(?P<foo>\w+)", "abc", "$1", "abc"); -expand!(expand4, r"(?P<foo>\w+)", "abc", "$$1", "$1"); -expand!(expand5, r"(?P<foo>\w+)", "abc", "$$foo", "$foo"); -expand!(expand6, r"(?P<a>\w+)\s+(?P<b>\d+)", - "abc 123", "$b$a", "123abc"); -expand!(expand7, r"(?P<a>\w+)\s+(?P<b>\d+)", - "abc 123", "z$bz$az", "z"); -expand!(expand8, r"(?P<a>\w+)\s+(?P<b>\d+)", - "abc 123", ".$b.$a.", ".123.abc."); -expand!(expand9, r"(?P<a>\w+)\s+(?P<b>\d+)", - "abc 123", " $b $a ", " 123 abc "); -expand!(expand10, r"(?P<a>\w+)\s+(?P<b>\d+)", - "abc 123", "$bz$az", ""); - -split!(split1, r"\s+", "a b\nc\td\n\t e", - &[t!("a"), t!("b"), t!("c"), t!("d"), t!("e")]); -split!(split2, r"\b", "a b c", - &[t!(""), t!("a"), t!(" "), t!("b"), t!(" "), t!("c")]); -split!(split3, r"a$", "a", &[t!("")]); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/api_str.rs cargo-0.26.0/vendor/regex-0.2.6/tests/api_str.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/api_str.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/api_str.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -// These tests don't really make sense with the bytes API, so we only test them -// on the Unicode API. - -#[test] -fn empty_match_unicode_find_iter() { - // Tests that we still yield byte ranges at valid UTF-8 sequence boundaries - // even when we're susceptible to empty width matches. - let re = regex!(r".*?"); - assert_eq!(vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)], - findall!(re, "Ⅰ1Ⅱ2")); -} - -#[test] -fn empty_match_unicode_captures_iter() { - // Same as empty_match_unicode_find_iter, but tests capture iteration. - let re = regex!(r".*?"); - let ms: Vec<_> = re.captures_iter(text!("Ⅰ1Ⅱ2")) - .map(|c| c.get(0).unwrap()) - .map(|m| (m.start(), m.end())) - .collect(); - assert_eq!(vec![(0, 0), (3, 3), (4, 4), (7, 7), (8, 8)], ms); -} - -#[test] -fn match_as_str() { - let re = regex!(r"fo+"); - let caps = re.captures("barfoobar").unwrap(); - assert_eq!(caps.get(0).map(|m| m.as_str()), Some("foo")); - assert_eq!(caps.get(0).map(From::from), Some("foo")); - assert_eq!(caps.get(0).map(Into::into), Some("foo")); -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/bytes.rs cargo-0.26.0/vendor/regex-0.2.6/tests/bytes.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/bytes.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/bytes.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,62 +0,0 @@ -// These are tests specifically crafted for regexes that can match arbitrary -// bytes. - -// A silly wrapper to make it possible to write and match raw bytes. -struct R<'a>(&'a [u8]); -impl<'a> R<'a> { fn as_bytes(&self) -> &'a [u8] { self.0 } } - -mat!(word_boundary, r"(?-u) \b", " δ", None); -mat!(word_boundary_unicode, r" \b", " δ", Some((0, 1))); -mat!(word_not_boundary, r"(?-u) \B", " δ", Some((0, 1))); -mat!(word_not_boundary_unicode, r" \B", " δ", None); - -mat!(perl_w_ascii, r"(?-u)\w+", "aδ", Some((0, 1))); -mat!(perl_w_unicode, r"\w+", "aδ", Some((0, 3))); -mat!(perl_d_ascii, r"(?-u)\d+", "1२३9", Some((0, 1))); -mat!(perl_d_unicode, r"\d+", "1२३9", Some((0, 8))); -mat!(perl_s_ascii, r"(?-u)\s+", " \u{1680}", Some((0, 1))); -mat!(perl_s_unicode, r"\s+", " \u{1680}", Some((0, 4))); - -// The first `(.+)` matches two Unicode codepoints, but can't match the 5th -// byte, which isn't valid UTF-8. The second (byte based) `(.+)` takes over and -// matches. -mat!(mixed1, r"(.+)(?-u)(.+)", R(b"\xCE\x93\xCE\x94\xFF"), - Some((0, 5)), Some((0, 4)), Some((4, 5))); - -mat!(case_ascii_one, r"(?i-u)a", "A", Some((0, 1))); -mat!(case_ascii_class, r"(?i-u)[a-z]+", "AaAaA", Some((0, 5))); -mat!(case_unicode, r"(?i)[a-z]+", "aA\u{212A}aA", Some((0, 7))); -mat!(case_not_unicode, r"(?i-u)[a-z]+", "aA\u{212A}aA", Some((0, 2))); - -mat!(negate_unicode, r"[^a]", "δ", Some((0, 2))); -mat!(negate_not_unicode, r"(?-u)[^a]", "δ", Some((0, 1))); - -// This doesn't match in a normal Unicode regex because the implicit preceding -// `.*?` is Unicode aware. -mat!(dotstar_prefix_not_unicode1, r"(?-u)a", R(b"\xFFa"), Some((1, 2))); -mat!(dotstar_prefix_not_unicode2, r"a", R(b"\xFFa"), Some((1, 2))); - -// Have fun with null bytes. -mat!(null_bytes, r"(?-u)(?P<cstr>[^\x00]+)\x00", - R(b"foo\x00"), Some((0, 4)), Some((0, 3))); - -// Test that lookahead operators work properly in the face of invalid UTF-8. -// See: https://github.com/rust-lang/regex/issues/277 -matiter!(invalidutf8_anchor1, - r"(?-u)\xcc?^", - R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), - (0, 0)); -matiter!(invalidutf8_anchor2, - r"(?-u)^\xf7|4\xff\d\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a##########[] d\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a\x8a##########\[] #####\x80\S7|$", - R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), - (22, 22)); -matiter!(invalidutf8_anchor3, - r"(?-u)^|ddp\xff\xffdddddlQd@\x80", - R(b"\x8d#;\x1a\xa4s3\x05foobarX\\\x0f0t\xe4\x9b\xa4"), - (0, 0)); - -// See https://github.com/rust-lang/regex/issues/303 -#[test] -fn negated_full_byte_range() { - assert!(::regex::bytes::Regex::new(r#"(?-u)[^\x00-\xff]"#).is_err()); -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/crazy.rs cargo-0.26.0/vendor/regex-0.2.6/tests/crazy.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/crazy.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/crazy.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,92 +0,0 @@ -mat!(ascii_literal, r"a", "a", Some((0, 1))); - -// Some crazy expressions from regular-expressions.info. -mat!(match_ranges, - r"\b(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b", - "num: 255", Some((5, 8))); -mat!(match_ranges_not, - r"\b(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b", - "num: 256", None); -mat!(match_float1, r"[-+]?[0-9]*\.?[0-9]+", "0.1", Some((0, 3))); -mat!(match_float2, r"[-+]?[0-9]*\.?[0-9]+", "0.1.2", Some((0, 3))); -mat!(match_float3, r"[-+]?[0-9]*\.?[0-9]+", "a1.2", Some((1, 4))); -mat!(match_float4, r"^[-+]?[0-9]*\.?[0-9]+$", "1.a", None); -mat!(match_email, r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", - "mine is jam.slam@gmail.com ", Some((8, 26))); -mat!(match_email_not, r"(?i)\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b", - "mine is jam.slam@gmail ", None); -mat!(match_email_big, r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", - "mine is jam.slam@gmail.com ", Some((8, 26))); -mat!(match_date1, - r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", - "1900-01-01", Some((0, 10))); -mat!(match_date2, - r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", - "1900-00-01", None); -mat!(match_date3, - r"^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$", - "1900-13-01", None); - -// Do some crazy dancing with the start/end assertions. -matiter!(match_start_end_empty, r"^$", "", (0, 0)); -matiter!(match_start_end_empty_many_1, r"^$^$^$", "", (0, 0)); -matiter!(match_start_end_empty_many_2, r"^^^$$$", "", (0, 0)); -matiter!(match_start_end_empty_rev, r"$^", "", (0, 0)); -matiter!(match_start_end_empty_rep, r"(?:^$)*", "a\nb\nc", - (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); -matiter!(match_start_end_empty_rep_rev, r"(?:$^)*", "a\nb\nc", - (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); - -// Test negated character classes. -mat!(negclass_letters, r"[^ac]", "acx", Some((2, 3))); -mat!(negclass_letter_comma, r"[^a,]", "a,x", Some((2, 3))); -mat!(negclass_letter_space, r"[^a\s]", "a x", Some((2, 3))); -mat!(negclass_comma, r"[^,]", ",,x", Some((2, 3))); -mat!(negclass_space, r"[^\s]", " a", Some((1, 2))); -mat!(negclass_space_comma, r"[^,\s]", ", a", Some((2, 3))); -mat!(negclass_comma_space, r"[^\s,]", " ,a", Some((2, 3))); -mat!(negclass_ascii, r"[^[:alpha:]Z]", "A1", Some((1, 2))); - -// Test that repeated empty expressions don't loop forever. -mat!(lazy_many_many, r"((?:.*)*?)=", "a=b", Some((0, 2))); -mat!(lazy_many_optional, r"((?:.?)*?)=", "a=b", Some((0, 2))); -mat!(lazy_one_many_many, r"((?:.*)+?)=", "a=b", Some((0, 2))); -mat!(lazy_one_many_optional, r"((?:.?)+?)=", "a=b", Some((0, 2))); -mat!(lazy_range_min_many, r"((?:.*){1,}?)=", "a=b", Some((0, 2))); -mat!(lazy_range_many, r"((?:.*){1,2}?)=", "a=b", Some((0, 2))); -mat!(greedy_many_many, r"((?:.*)*)=", "a=b", Some((0, 2))); -mat!(greedy_many_optional, r"((?:.?)*)=", "a=b", Some((0, 2))); -mat!(greedy_one_many_many, r"((?:.*)+)=", "a=b", Some((0, 2))); -mat!(greedy_one_many_optional, r"((?:.?)+)=", "a=b", Some((0, 2))); -mat!(greedy_range_min_many, r"((?:.*){1,})=", "a=b", Some((0, 2))); -mat!(greedy_range_many, r"((?:.*){1,2})=", "a=b", Some((0, 2))); - -// Test that the DFA can handle pathological cases. -// (This should result in the DFA's cache being flushed too frequently, which -// should cause it to quit and fall back to the NFA algorithm.) -#[test] -fn dfa_handles_pathological_case() { - fn ones_and_zeroes(count: usize) -> String { - use rand::{Rng, thread_rng}; - - let mut rng = thread_rng(); - let mut s = String::new(); - for _ in 0..count { - if rng.gen() { - s.push('1'); - } else { - s.push('0'); - } - } - s - } - - let re = regex!(r"[01]*1[01]{20}$"); - let text = { - let mut pieces = ones_and_zeroes(100_000); - pieces.push('1'); - pieces.push_str(&ones_and_zeroes(20)); - pieces - }; - assert!(re.is_match(text!(&*text))); -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/flags.rs cargo-0.26.0/vendor/regex-0.2.6/tests/flags.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/flags.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/flags.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -mat!(match_flag_case, "(?i)abc", "ABC", Some((0, 3))); -mat!(match_flag_weird_case, "(?i)a(?-i)bc", "Abc", Some((0, 3))); -mat!(match_flag_weird_case_not, "(?i)a(?-i)bc", "ABC", None); -mat!(match_flag_case_dotnl, "(?is)a.", "A\n", Some((0, 2))); -mat!(match_flag_case_dotnl_toggle, "(?is)a.(?-is)a.", "A\nab", Some((0, 4))); -mat!(match_flag_case_dotnl_toggle_not, "(?is)a.(?-is)a.", "A\na\n", None); -mat!(match_flag_case_dotnl_toggle_ok, "(?is)a.(?-is:a.)?", "A\na\n", Some((0, 2))); -mat!(match_flag_multi, "(?m)(?:^\\d+$\n?)+", "123\n456\n789", Some((0, 11))); -mat!(match_flag_ungreedy, "(?U)a+", "aa", Some((0, 1))); -mat!(match_flag_ungreedy_greedy, "(?U)a+?", "aa", Some((0, 2))); -mat!(match_flag_ungreedy_noop, "(?U)(?-U)a+", "aa", Some((0, 2))); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/fowler.rs cargo-0.26.0/vendor/regex-0.2.6/tests/fowler.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/fowler.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/fowler.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,371 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// DO NOT EDIT. Automatically generated by 'scripts/regex-match-tests.py' -// on 2015-02-28 11:00:00.161706. - -// Tests from basic.dat -mat!(match_basic_3, r"abracadabra$", r"abracadabracadabra", Some((7, 18))); -mat!(match_basic_4, r"a...b", r"abababbb", Some((2, 7))); -mat!(match_basic_5, r"XXXXXX", r"..XXXXXX", Some((2, 8))); -mat!(match_basic_6, r"\)", r"()", Some((1, 2))); -mat!(match_basic_7, r"a]", r"a]a", Some((0, 2))); -mat!(match_basic_9, r"\}", r"}", Some((0, 1))); -mat!(match_basic_10, r"\]", r"]", Some((0, 1))); -mat!(match_basic_12, r"]", r"]", Some((0, 1))); -mat!(match_basic_15, r"^a", r"ax", Some((0, 1))); -mat!(match_basic_16, r"\^a", r"a^a", Some((1, 3))); -mat!(match_basic_17, r"a\^", r"a^", Some((0, 2))); -mat!(match_basic_18, r"a$", r"aa", Some((1, 2))); -mat!(match_basic_19, r"a\$", r"a$", Some((0, 2))); -mat!(match_basic_20, r"^$", r"", Some((0, 0))); -mat!(match_basic_21, r"$^", r"", Some((0, 0))); -mat!(match_basic_22, r"a($)", r"aa", Some((1, 2)), Some((2, 2))); -mat!(match_basic_23, r"a*(^a)", r"aa", Some((0, 1)), Some((0, 1))); -mat!(match_basic_24, r"(..)*(...)*", r"a", Some((0, 0))); -mat!(match_basic_25, r"(..)*(...)*", r"abcd", Some((0, 4)), Some((2, 4))); -mat!(match_basic_26, r"(ab|a)(bc|c)", r"abc", Some((0, 3)), Some((0, 2)), Some((2, 3))); -mat!(match_basic_27, r"(ab)c|abc", r"abc", Some((0, 3)), Some((0, 2))); -mat!(match_basic_28, r"a{0}b", r"ab", Some((1, 2))); -mat!(match_basic_29, r"(a*)(b?)(b+)b{3}", r"aaabbbbbbb", Some((0, 10)), Some((0, 3)), Some((3, 4)), Some((4, 7))); -mat!(match_basic_30, r"(a*)(b{0,1})(b{1,})b{3}", r"aaabbbbbbb", Some((0, 10)), Some((0, 3)), Some((3, 4)), Some((4, 7))); -mat!(match_basic_32, r"((a|a)|a)", r"a", Some((0, 1)), Some((0, 1)), Some((0, 1))); -mat!(match_basic_33, r"(a*)(a|aa)", r"aaaa", Some((0, 4)), Some((0, 3)), Some((3, 4))); -mat!(match_basic_34, r"a*(a.|aa)", r"aaaa", Some((0, 4)), Some((2, 4))); -mat!(match_basic_35, r"a(b)|c(d)|a(e)f", r"aef", Some((0, 3)), None, None, Some((1, 2))); -mat!(match_basic_36, r"(a|b)?.*", r"b", Some((0, 1)), Some((0, 1))); -mat!(match_basic_37, r"(a|b)c|a(b|c)", r"ac", Some((0, 2)), Some((0, 1))); -mat!(match_basic_38, r"(a|b)c|a(b|c)", r"ab", Some((0, 2)), None, Some((1, 2))); -mat!(match_basic_39, r"(a|b)*c|(a|ab)*c", r"abc", Some((0, 3)), Some((1, 2))); -mat!(match_basic_40, r"(a|b)*c|(a|ab)*c", r"xc", Some((1, 2))); -mat!(match_basic_41, r"(.a|.b).*|.*(.a|.b)", r"xa", Some((0, 2)), Some((0, 2))); -mat!(match_basic_42, r"a?(ab|ba)ab", r"abab", Some((0, 4)), Some((0, 2))); -mat!(match_basic_43, r"a?(ac{0}b|ba)ab", r"abab", Some((0, 4)), Some((0, 2))); -mat!(match_basic_44, r"ab|abab", r"abbabab", Some((0, 2))); -mat!(match_basic_45, r"aba|bab|bba", r"baaabbbaba", Some((5, 8))); -mat!(match_basic_46, r"aba|bab", r"baaabbbaba", Some((6, 9))); -mat!(match_basic_47, r"(aa|aaa)*|(a|aaaaa)", r"aa", Some((0, 2)), Some((0, 2))); -mat!(match_basic_48, r"(a.|.a.)*|(a|.a...)", r"aa", Some((0, 2)), Some((0, 2))); -mat!(match_basic_49, r"ab|a", r"xabc", Some((1, 3))); -mat!(match_basic_50, r"ab|a", r"xxabc", Some((2, 4))); -mat!(match_basic_51, r"(?i)(Ab|cD)*", r"aBcD", Some((0, 4)), Some((2, 4))); -mat!(match_basic_52, r"[^-]", r"--a", Some((2, 3))); -mat!(match_basic_53, r"[a-]*", r"--a", Some((0, 3))); -mat!(match_basic_54, r"[a-m-]*", r"--amoma--", Some((0, 4))); -mat!(match_basic_55, r":::1:::0:|:::1:1:0:", r":::0:::1:::1:::0:", Some((8, 17))); -mat!(match_basic_56, r":::1:::0:|:::1:1:1:", r":::0:::1:::1:::0:", Some((8, 17))); -mat!(match_basic_57, r"[[:upper:]]", r"A", Some((0, 1))); -mat!(match_basic_58, r"[[:lower:]]+", r"`az{", Some((1, 3))); -mat!(match_basic_59, r"[[:upper:]]+", r"@AZ[", Some((1, 3))); -mat!(match_basic_65, r" -", r" -", Some((0, 1))); -mat!(match_basic_66, r" -", r" -", Some((0, 1))); -mat!(match_basic_67, r"[^a]", r" -", Some((0, 1))); -mat!(match_basic_68, r" -a", r" -a", Some((0, 2))); -mat!(match_basic_69, r"(a)(b)(c)", r"abc", Some((0, 3)), Some((0, 1)), Some((1, 2)), Some((2, 3))); -mat!(match_basic_70, r"xxx", r"xxx", Some((0, 3))); -mat!(match_basic_71, r"(^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$)", r"feb 6,", Some((0, 6))); -mat!(match_basic_72, r"(^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$)", r"2/7", Some((0, 3))); -mat!(match_basic_73, r"(^|[ (,;])((([Ff]eb[^ ]* *|0*2/|\* */?)0*[6-7]))([^0-9]|$)", r"feb 1,Feb 6", Some((5, 11))); -mat!(match_basic_74, r"((((((((((((((((((((((((((((((x))))))))))))))))))))))))))))))", r"x", Some((0, 1)), Some((0, 1)), Some((0, 1))); -mat!(match_basic_75, r"((((((((((((((((((((((((((((((x))))))))))))))))))))))))))))))*", r"xx", Some((0, 2)), Some((1, 2)), Some((1, 2))); -mat!(match_basic_76, r"a?(ab|ba)*", r"ababababababababababababababababababababababababababababababababababababababababa", Some((0, 81)), Some((79, 81))); -mat!(match_basic_77, r"abaa|abbaa|abbbaa|abbbbaa", r"ababbabbbabbbabbbbabbbbaa", Some((18, 25))); -mat!(match_basic_78, r"abaa|abbaa|abbbaa|abbbbaa", r"ababbabbbabbbabbbbabaa", Some((18, 22))); -mat!(match_basic_79, r"aaac|aabc|abac|abbc|baac|babc|bbac|bbbc", r"baaabbbabac", Some((7, 11))); -mat!(match_basic_80, r".*", r"", Some((0, 2))); -mat!(match_basic_81, r"aaaa|bbbb|cccc|ddddd|eeeeee|fffffff|gggg|hhhh|iiiii|jjjjj|kkkkk|llll", r"XaaaXbbbXcccXdddXeeeXfffXgggXhhhXiiiXjjjXkkkXlllXcbaXaaaa", Some((53, 57))); -mat!(match_basic_83, r"a*a*a*a*a*b", r"aaaaaaaaab", Some((0, 10))); -mat!(match_basic_84, r"^", r"", Some((0, 0))); -mat!(match_basic_85, r"$", r"", Some((0, 0))); -mat!(match_basic_86, r"^$", r"", Some((0, 0))); -mat!(match_basic_87, r"^a$", r"a", Some((0, 1))); -mat!(match_basic_88, r"abc", r"abc", Some((0, 3))); -mat!(match_basic_89, r"abc", r"xabcy", Some((1, 4))); -mat!(match_basic_90, r"abc", r"ababc", Some((2, 5))); -mat!(match_basic_91, r"ab*c", r"abc", Some((0, 3))); -mat!(match_basic_92, r"ab*bc", r"abc", Some((0, 3))); -mat!(match_basic_93, r"ab*bc", r"abbc", Some((0, 4))); -mat!(match_basic_94, r"ab*bc", r"abbbbc", Some((0, 6))); -mat!(match_basic_95, r"ab+bc", r"abbc", Some((0, 4))); -mat!(match_basic_96, r"ab+bc", r"abbbbc", Some((0, 6))); -mat!(match_basic_97, r"ab?bc", r"abbc", Some((0, 4))); -mat!(match_basic_98, r"ab?bc", r"abc", Some((0, 3))); -mat!(match_basic_99, r"ab?c", r"abc", Some((0, 3))); -mat!(match_basic_100, r"^abc$", r"abc", Some((0, 3))); -mat!(match_basic_101, r"^abc", r"abcc", Some((0, 3))); -mat!(match_basic_102, r"abc$", r"aabc", Some((1, 4))); -mat!(match_basic_103, r"^", r"abc", Some((0, 0))); -mat!(match_basic_104, r"$", r"abc", Some((3, 3))); -mat!(match_basic_105, r"a.c", r"abc", Some((0, 3))); -mat!(match_basic_106, r"a.c", r"axc", Some((0, 3))); -mat!(match_basic_107, r"a.*c", r"axyzc", Some((0, 5))); -mat!(match_basic_108, r"a[bc]d", r"abd", Some((0, 3))); -mat!(match_basic_109, r"a[b-d]e", r"ace", Some((0, 3))); -mat!(match_basic_110, r"a[b-d]", r"aac", Some((1, 3))); -mat!(match_basic_111, r"a[-b]", r"a-", Some((0, 2))); -mat!(match_basic_112, r"a[b-]", r"a-", Some((0, 2))); -mat!(match_basic_113, r"a]", r"a]", Some((0, 2))); -mat!(match_basic_114, r"a[]]b", r"a]b", Some((0, 3))); -mat!(match_basic_115, r"a[^bc]d", r"aed", Some((0, 3))); -mat!(match_basic_116, r"a[^-b]c", r"adc", Some((0, 3))); -mat!(match_basic_117, r"a[^]b]c", r"adc", Some((0, 3))); -mat!(match_basic_118, r"ab|cd", r"abc", Some((0, 2))); -mat!(match_basic_119, r"ab|cd", r"abcd", Some((0, 2))); -mat!(match_basic_120, r"a\(b", r"a(b", Some((0, 3))); -mat!(match_basic_121, r"a\(*b", r"ab", Some((0, 2))); -mat!(match_basic_122, r"a\(*b", r"a((b", Some((0, 4))); -mat!(match_basic_123, r"((a))", r"abc", Some((0, 1)), Some((0, 1)), Some((0, 1))); -mat!(match_basic_124, r"(a)b(c)", r"abc", Some((0, 3)), Some((0, 1)), Some((2, 3))); -mat!(match_basic_125, r"a+b+c", r"aabbabc", Some((4, 7))); -mat!(match_basic_126, r"a*", r"aaa", Some((0, 3))); -mat!(match_basic_128, r"(a*)*", r"-", Some((0, 0)), None); -mat!(match_basic_129, r"(a*)+", r"-", Some((0, 0)), Some((0, 0))); -mat!(match_basic_131, r"(a*|b)*", r"-", Some((0, 0)), None); -mat!(match_basic_132, r"(a+|b)*", r"ab", Some((0, 2)), Some((1, 2))); -mat!(match_basic_133, r"(a+|b)+", r"ab", Some((0, 2)), Some((1, 2))); -mat!(match_basic_134, r"(a+|b)?", r"ab", Some((0, 1)), Some((0, 1))); -mat!(match_basic_135, r"[^ab]*", r"cde", Some((0, 3))); -mat!(match_basic_137, r"(^)*", r"-", Some((0, 0)), None); -mat!(match_basic_138, r"a*", r"", Some((0, 0))); -mat!(match_basic_139, r"([abc])*d", r"abbbcd", Some((0, 6)), Some((4, 5))); -mat!(match_basic_140, r"([abc])*bcd", r"abcd", Some((0, 4)), Some((0, 1))); -mat!(match_basic_141, r"a|b|c|d|e", r"e", Some((0, 1))); -mat!(match_basic_142, r"(a|b|c|d|e)f", r"ef", Some((0, 2)), Some((0, 1))); -mat!(match_basic_144, r"((a*|b))*", r"-", Some((0, 0)), None, None); -mat!(match_basic_145, r"abcd*efg", r"abcdefg", Some((0, 7))); -mat!(match_basic_146, r"ab*", r"xabyabbbz", Some((1, 3))); -mat!(match_basic_147, r"ab*", r"xayabbbz", Some((1, 2))); -mat!(match_basic_148, r"(ab|cd)e", r"abcde", Some((2, 5)), Some((2, 4))); -mat!(match_basic_149, r"[abhgefdc]ij", r"hij", Some((0, 3))); -mat!(match_basic_150, r"(a|b)c*d", r"abcd", Some((1, 4)), Some((1, 2))); -mat!(match_basic_151, r"(ab|ab*)bc", r"abc", Some((0, 3)), Some((0, 1))); -mat!(match_basic_152, r"a([bc]*)c*", r"abc", Some((0, 3)), Some((1, 3))); -mat!(match_basic_153, r"a([bc]*)(c*d)", r"abcd", Some((0, 4)), Some((1, 3)), Some((3, 4))); -mat!(match_basic_154, r"a([bc]+)(c*d)", r"abcd", Some((0, 4)), Some((1, 3)), Some((3, 4))); -mat!(match_basic_155, r"a([bc]*)(c+d)", r"abcd", Some((0, 4)), Some((1, 2)), Some((2, 4))); -mat!(match_basic_156, r"a[bcd]*dcdcde", r"adcdcde", Some((0, 7))); -mat!(match_basic_157, r"(ab|a)b*c", r"abc", Some((0, 3)), Some((0, 2))); -mat!(match_basic_158, r"((a)(b)c)(d)", r"abcd", Some((0, 4)), Some((0, 3)), Some((0, 1)), Some((1, 2)), Some((3, 4))); -mat!(match_basic_159, r"[A-Za-z_][A-Za-z0-9_]*", r"alpha", Some((0, 5))); -mat!(match_basic_160, r"^a(bc+|b[eh])g|.h$", r"abh", Some((1, 3))); -mat!(match_basic_161, r"(bc+d$|ef*g.|h?i(j|k))", r"effgz", Some((0, 5)), Some((0, 5))); -mat!(match_basic_162, r"(bc+d$|ef*g.|h?i(j|k))", r"ij", Some((0, 2)), Some((0, 2)), Some((1, 2))); -mat!(match_basic_163, r"(bc+d$|ef*g.|h?i(j|k))", r"reffgz", Some((1, 6)), Some((1, 6))); -mat!(match_basic_164, r"(((((((((a)))))))))", r"a", Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 1))); -mat!(match_basic_165, r"multiple words", r"multiple words yeah", Some((0, 14))); -mat!(match_basic_166, r"(.*)c(.*)", r"abcde", Some((0, 5)), Some((0, 2)), Some((3, 5))); -mat!(match_basic_167, r"abcd", r"abcd", Some((0, 4))); -mat!(match_basic_168, r"a(bc)d", r"abcd", Some((0, 4)), Some((1, 3))); -mat!(match_basic_169, r"a[-]?c", r"ac", Some((0, 3))); -mat!(match_basic_170, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Qaddafi", Some((0, 15)), None, Some((10, 12))); -mat!(match_basic_171, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Mo'ammar Gadhafi", Some((0, 16)), None, Some((11, 13))); -mat!(match_basic_172, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Kaddafi", Some((0, 15)), None, Some((10, 12))); -mat!(match_basic_173, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Qadhafi", Some((0, 15)), None, Some((10, 12))); -mat!(match_basic_174, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Gadafi", Some((0, 14)), None, Some((10, 11))); -mat!(match_basic_175, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Mu'ammar Qadafi", Some((0, 15)), None, Some((11, 12))); -mat!(match_basic_176, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Moamar Gaddafi", Some((0, 14)), None, Some((9, 11))); -mat!(match_basic_177, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Mu'ammar Qadhdhafi", Some((0, 18)), None, Some((13, 15))); -mat!(match_basic_178, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Khaddafi", Some((0, 16)), None, Some((11, 13))); -mat!(match_basic_179, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Ghaddafy", Some((0, 16)), None, Some((11, 13))); -mat!(match_basic_180, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Ghadafi", Some((0, 15)), None, Some((11, 12))); -mat!(match_basic_181, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Ghaddafi", Some((0, 16)), None, Some((11, 13))); -mat!(match_basic_182, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muamar Kaddafi", Some((0, 14)), None, Some((9, 11))); -mat!(match_basic_183, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Quathafi", Some((0, 16)), None, Some((11, 13))); -mat!(match_basic_184, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Muammar Gheddafi", Some((0, 16)), None, Some((11, 13))); -mat!(match_basic_185, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Moammar Khadafy", Some((0, 15)), None, Some((11, 12))); -mat!(match_basic_186, r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", r"Moammar Qudhafi", Some((0, 15)), None, Some((10, 12))); -mat!(match_basic_187, r"a+(b|c)*d+", r"aabcdd", Some((0, 6)), Some((3, 4))); -mat!(match_basic_188, r"^.+$", r"vivi", Some((0, 4))); -mat!(match_basic_189, r"^(.+)$", r"vivi", Some((0, 4)), Some((0, 4))); -mat!(match_basic_190, r"^([^!.]+).att.com!(.+)$", r"gryphon.att.com!eby", Some((0, 19)), Some((0, 7)), Some((16, 19))); -mat!(match_basic_191, r"^([^!]+!)?([^!]+)$", r"bas", Some((0, 3)), None, Some((0, 3))); -mat!(match_basic_192, r"^([^!]+!)?([^!]+)$", r"bar!bas", Some((0, 7)), Some((0, 4)), Some((4, 7))); -mat!(match_basic_193, r"^([^!]+!)?([^!]+)$", r"foo!bas", Some((0, 7)), Some((0, 4)), Some((4, 7))); -mat!(match_basic_194, r"^.+!([^!]+!)([^!]+)$", r"foo!bar!bas", Some((0, 11)), Some((4, 8)), Some((8, 11))); -mat!(match_basic_195, r"((foo)|(bar))!bas", r"bar!bas", Some((0, 7)), Some((0, 3)), None, Some((0, 3))); -mat!(match_basic_196, r"((foo)|(bar))!bas", r"foo!bar!bas", Some((4, 11)), Some((4, 7)), None, Some((4, 7))); -mat!(match_basic_197, r"((foo)|(bar))!bas", r"foo!bas", Some((0, 7)), Some((0, 3)), Some((0, 3))); -mat!(match_basic_198, r"((foo)|bar)!bas", r"bar!bas", Some((0, 7)), Some((0, 3))); -mat!(match_basic_199, r"((foo)|bar)!bas", r"foo!bar!bas", Some((4, 11)), Some((4, 7))); -mat!(match_basic_200, r"((foo)|bar)!bas", r"foo!bas", Some((0, 7)), Some((0, 3)), Some((0, 3))); -mat!(match_basic_201, r"(foo|(bar))!bas", r"bar!bas", Some((0, 7)), Some((0, 3)), Some((0, 3))); -mat!(match_basic_202, r"(foo|(bar))!bas", r"foo!bar!bas", Some((4, 11)), Some((4, 7)), Some((4, 7))); -mat!(match_basic_203, r"(foo|(bar))!bas", r"foo!bas", Some((0, 7)), Some((0, 3))); -mat!(match_basic_204, r"(foo|bar)!bas", r"bar!bas", Some((0, 7)), Some((0, 3))); -mat!(match_basic_205, r"(foo|bar)!bas", r"foo!bar!bas", Some((4, 11)), Some((4, 7))); -mat!(match_basic_206, r"(foo|bar)!bas", r"foo!bas", Some((0, 7)), Some((0, 3))); -mat!(match_basic_207, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"foo!bar!bas", Some((0, 11)), Some((0, 11)), None, None, Some((4, 8)), Some((8, 11))); -mat!(match_basic_208, r"^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$", r"bas", Some((0, 3)), None, Some((0, 3))); -mat!(match_basic_209, r"^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$", r"bar!bas", Some((0, 7)), Some((0, 4)), Some((4, 7))); -mat!(match_basic_210, r"^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$", r"foo!bar!bas", Some((0, 11)), None, None, Some((4, 8)), Some((8, 11))); -mat!(match_basic_211, r"^([^!]+!)?([^!]+)$|^.+!([^!]+!)([^!]+)$", r"foo!bas", Some((0, 7)), Some((0, 4)), Some((4, 7))); -mat!(match_basic_212, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"bas", Some((0, 3)), Some((0, 3)), None, Some((0, 3))); -mat!(match_basic_213, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"bar!bas", Some((0, 7)), Some((0, 7)), Some((0, 4)), Some((4, 7))); -mat!(match_basic_214, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"foo!bar!bas", Some((0, 11)), Some((0, 11)), None, None, Some((4, 8)), Some((8, 11))); -mat!(match_basic_215, r"^(([^!]+!)?([^!]+)|.+!([^!]+!)([^!]+))$", r"foo!bas", Some((0, 7)), Some((0, 7)), Some((0, 4)), Some((4, 7))); -mat!(match_basic_216, r".*(/XXX).*", r"/XXX", Some((0, 4)), Some((0, 4))); -mat!(match_basic_217, r".*(\\XXX).*", r"\XXX", Some((0, 4)), Some((0, 4))); -mat!(match_basic_218, r"\\XXX", r"\XXX", Some((0, 4))); -mat!(match_basic_219, r".*(/000).*", r"/000", Some((0, 4)), Some((0, 4))); -mat!(match_basic_220, r".*(\\000).*", r"\000", Some((0, 4)), Some((0, 4))); -mat!(match_basic_221, r"\\000", r"\000", Some((0, 4))); - -// Tests from nullsubexpr.dat -mat!(match_nullsubexpr_3, r"(a*)*", r"a", Some((0, 1)), Some((0, 1))); -mat!(match_nullsubexpr_5, r"(a*)*", r"x", Some((0, 0)), None); -mat!(match_nullsubexpr_6, r"(a*)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_7, r"(a*)*", r"aaaaaax", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_8, r"(a*)+", r"a", Some((0, 1)), Some((0, 1))); -mat!(match_nullsubexpr_9, r"(a*)+", r"x", Some((0, 0)), Some((0, 0))); -mat!(match_nullsubexpr_10, r"(a*)+", r"aaaaaa", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_11, r"(a*)+", r"aaaaaax", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_12, r"(a+)*", r"a", Some((0, 1)), Some((0, 1))); -mat!(match_nullsubexpr_13, r"(a+)*", r"x", Some((0, 0))); -mat!(match_nullsubexpr_14, r"(a+)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_15, r"(a+)*", r"aaaaaax", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_16, r"(a+)+", r"a", Some((0, 1)), Some((0, 1))); -mat!(match_nullsubexpr_17, r"(a+)+", r"x", None); -mat!(match_nullsubexpr_18, r"(a+)+", r"aaaaaa", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_19, r"(a+)+", r"aaaaaax", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_21, r"([a]*)*", r"a", Some((0, 1)), Some((0, 1))); -mat!(match_nullsubexpr_23, r"([a]*)*", r"x", Some((0, 0)), None); -mat!(match_nullsubexpr_24, r"([a]*)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_25, r"([a]*)*", r"aaaaaax", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_26, r"([a]*)+", r"a", Some((0, 1)), Some((0, 1))); -mat!(match_nullsubexpr_27, r"([a]*)+", r"x", Some((0, 0)), Some((0, 0))); -mat!(match_nullsubexpr_28, r"([a]*)+", r"aaaaaa", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_29, r"([a]*)+", r"aaaaaax", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_30, r"([^b]*)*", r"a", Some((0, 1)), Some((0, 1))); -mat!(match_nullsubexpr_32, r"([^b]*)*", r"b", Some((0, 0)), None); -mat!(match_nullsubexpr_33, r"([^b]*)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_34, r"([^b]*)*", r"aaaaaab", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_35, r"([ab]*)*", r"a", Some((0, 1)), Some((0, 1))); -mat!(match_nullsubexpr_36, r"([ab]*)*", r"aaaaaa", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_37, r"([ab]*)*", r"ababab", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_38, r"([ab]*)*", r"bababa", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_39, r"([ab]*)*", r"b", Some((0, 1)), Some((0, 1))); -mat!(match_nullsubexpr_40, r"([ab]*)*", r"bbbbbb", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_41, r"([ab]*)*", r"aaaabcde", Some((0, 5)), Some((0, 5))); -mat!(match_nullsubexpr_42, r"([^a]*)*", r"b", Some((0, 1)), Some((0, 1))); -mat!(match_nullsubexpr_43, r"([^a]*)*", r"bbbbbb", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_45, r"([^a]*)*", r"aaaaaa", Some((0, 0)), None); -mat!(match_nullsubexpr_46, r"([^ab]*)*", r"ccccxx", Some((0, 6)), Some((0, 6))); -mat!(match_nullsubexpr_48, r"([^ab]*)*", r"ababab", Some((0, 0)), None); -mat!(match_nullsubexpr_50, r"((z)+|a)*", r"zabcde", Some((0, 2)), Some((1, 2))); -mat!(match_nullsubexpr_69, r"(a*)*(x)", r"x", Some((0, 1)), None, Some((0, 1))); -mat!(match_nullsubexpr_70, r"(a*)*(x)", r"ax", Some((0, 2)), Some((0, 1)), Some((1, 2))); -mat!(match_nullsubexpr_71, r"(a*)*(x)", r"axa", Some((0, 2)), Some((0, 1)), Some((1, 2))); -mat!(match_nullsubexpr_73, r"(a*)+(x)", r"x", Some((0, 1)), Some((0, 0)), Some((0, 1))); -mat!(match_nullsubexpr_74, r"(a*)+(x)", r"ax", Some((0, 2)), Some((0, 1)), Some((1, 2))); -mat!(match_nullsubexpr_75, r"(a*)+(x)", r"axa", Some((0, 2)), Some((0, 1)), Some((1, 2))); -mat!(match_nullsubexpr_77, r"(a*){2}(x)", r"x", Some((0, 1)), Some((0, 0)), Some((0, 1))); -mat!(match_nullsubexpr_78, r"(a*){2}(x)", r"ax", Some((0, 2)), Some((1, 1)), Some((1, 2))); -mat!(match_nullsubexpr_79, r"(a*){2}(x)", r"axa", Some((0, 2)), Some((1, 1)), Some((1, 2))); - -// Tests from repetition.dat -mat!(match_repetition_10, r"((..)|(.))", r"", None); -mat!(match_repetition_11, r"((..)|(.))((..)|(.))", r"", None); -mat!(match_repetition_12, r"((..)|(.))((..)|(.))((..)|(.))", r"", None); -mat!(match_repetition_14, r"((..)|(.)){1}", r"", None); -mat!(match_repetition_15, r"((..)|(.)){2}", r"", None); -mat!(match_repetition_16, r"((..)|(.)){3}", r"", None); -mat!(match_repetition_18, r"((..)|(.))*", r"", Some((0, 0))); -mat!(match_repetition_20, r"((..)|(.))", r"a", Some((0, 1)), Some((0, 1)), None, Some((0, 1))); -mat!(match_repetition_21, r"((..)|(.))((..)|(.))", r"a", None); -mat!(match_repetition_22, r"((..)|(.))((..)|(.))((..)|(.))", r"a", None); -mat!(match_repetition_24, r"((..)|(.)){1}", r"a", Some((0, 1)), Some((0, 1)), None, Some((0, 1))); -mat!(match_repetition_25, r"((..)|(.)){2}", r"a", None); -mat!(match_repetition_26, r"((..)|(.)){3}", r"a", None); -mat!(match_repetition_28, r"((..)|(.))*", r"a", Some((0, 1)), Some((0, 1)), None, Some((0, 1))); -mat!(match_repetition_30, r"((..)|(.))", r"aa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); -mat!(match_repetition_31, r"((..)|(.))((..)|(.))", r"aa", Some((0, 2)), Some((0, 1)), None, Some((0, 1)), Some((1, 2)), None, Some((1, 2))); -mat!(match_repetition_32, r"((..)|(.))((..)|(.))((..)|(.))", r"aa", None); -mat!(match_repetition_34, r"((..)|(.)){1}", r"aa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); -mat!(match_repetition_35, r"((..)|(.)){2}", r"aa", Some((0, 2)), Some((1, 2)), None, Some((1, 2))); -mat!(match_repetition_36, r"((..)|(.)){3}", r"aa", None); -mat!(match_repetition_38, r"((..)|(.))*", r"aa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); -mat!(match_repetition_40, r"((..)|(.))", r"aaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); -mat!(match_repetition_41, r"((..)|(.))((..)|(.))", r"aaa", Some((0, 3)), Some((0, 2)), Some((0, 2)), None, Some((2, 3)), None, Some((2, 3))); -mat!(match_repetition_42, r"((..)|(.))((..)|(.))((..)|(.))", r"aaa", Some((0, 3)), Some((0, 1)), None, Some((0, 1)), Some((1, 2)), None, Some((1, 2)), Some((2, 3)), None, Some((2, 3))); -mat!(match_repetition_44, r"((..)|(.)){1}", r"aaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); -mat!(match_repetition_46, r"((..)|(.)){2}", r"aaa", Some((0, 3)), Some((2, 3)), Some((0, 2)), Some((2, 3))); -mat!(match_repetition_47, r"((..)|(.)){3}", r"aaa", Some((0, 3)), Some((2, 3)), None, Some((2, 3))); -mat!(match_repetition_50, r"((..)|(.))*", r"aaa", Some((0, 3)), Some((2, 3)), Some((0, 2)), Some((2, 3))); -mat!(match_repetition_52, r"((..)|(.))", r"aaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); -mat!(match_repetition_53, r"((..)|(.))((..)|(.))", r"aaaa", Some((0, 4)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None); -mat!(match_repetition_54, r"((..)|(.))((..)|(.))((..)|(.))", r"aaaa", Some((0, 4)), Some((0, 2)), Some((0, 2)), None, Some((2, 3)), None, Some((2, 3)), Some((3, 4)), None, Some((3, 4))); -mat!(match_repetition_56, r"((..)|(.)){1}", r"aaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); -mat!(match_repetition_57, r"((..)|(.)){2}", r"aaaa", Some((0, 4)), Some((2, 4)), Some((2, 4)), None); -mat!(match_repetition_59, r"((..)|(.)){3}", r"aaaa", Some((0, 4)), Some((3, 4)), Some((0, 2)), Some((3, 4))); -mat!(match_repetition_61, r"((..)|(.))*", r"aaaa", Some((0, 4)), Some((2, 4)), Some((2, 4)), None); -mat!(match_repetition_63, r"((..)|(.))", r"aaaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); -mat!(match_repetition_64, r"((..)|(.))((..)|(.))", r"aaaaa", Some((0, 4)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None); -mat!(match_repetition_65, r"((..)|(.))((..)|(.))((..)|(.))", r"aaaaa", Some((0, 5)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None, Some((4, 5)), None, Some((4, 5))); -mat!(match_repetition_67, r"((..)|(.)){1}", r"aaaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); -mat!(match_repetition_68, r"((..)|(.)){2}", r"aaaaa", Some((0, 4)), Some((2, 4)), Some((2, 4)), None); -mat!(match_repetition_70, r"((..)|(.)){3}", r"aaaaa", Some((0, 5)), Some((4, 5)), Some((2, 4)), Some((4, 5))); -mat!(match_repetition_73, r"((..)|(.))*", r"aaaaa", Some((0, 5)), Some((4, 5)), Some((2, 4)), Some((4, 5))); -mat!(match_repetition_75, r"((..)|(.))", r"aaaaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); -mat!(match_repetition_76, r"((..)|(.))((..)|(.))", r"aaaaaa", Some((0, 4)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None); -mat!(match_repetition_77, r"((..)|(.))((..)|(.))((..)|(.))", r"aaaaaa", Some((0, 6)), Some((0, 2)), Some((0, 2)), None, Some((2, 4)), Some((2, 4)), None, Some((4, 6)), Some((4, 6)), None); -mat!(match_repetition_79, r"((..)|(.)){1}", r"aaaaaa", Some((0, 2)), Some((0, 2)), Some((0, 2)), None); -mat!(match_repetition_80, r"((..)|(.)){2}", r"aaaaaa", Some((0, 4)), Some((2, 4)), Some((2, 4)), None); -mat!(match_repetition_81, r"((..)|(.)){3}", r"aaaaaa", Some((0, 6)), Some((4, 6)), Some((4, 6)), None); -mat!(match_repetition_83, r"((..)|(.))*", r"aaaaaa", Some((0, 6)), Some((4, 6)), Some((4, 6)), None); -mat!(match_repetition_90, r"X(.?){0,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); -mat!(match_repetition_91, r"X(.?){1,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); -mat!(match_repetition_92, r"X(.?){2,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); -mat!(match_repetition_93, r"X(.?){3,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); -mat!(match_repetition_94, r"X(.?){4,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); -mat!(match_repetition_95, r"X(.?){5,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); -mat!(match_repetition_96, r"X(.?){6,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); -mat!(match_repetition_97, r"X(.?){7,}Y", r"X1234567Y", Some((0, 9)), Some((7, 8))); -mat!(match_repetition_98, r"X(.?){8,}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); -mat!(match_repetition_100, r"X(.?){0,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); -mat!(match_repetition_102, r"X(.?){1,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); -mat!(match_repetition_104, r"X(.?){2,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); -mat!(match_repetition_106, r"X(.?){3,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); -mat!(match_repetition_108, r"X(.?){4,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); -mat!(match_repetition_110, r"X(.?){5,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); -mat!(match_repetition_112, r"X(.?){6,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); -mat!(match_repetition_114, r"X(.?){7,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); -mat!(match_repetition_115, r"X(.?){8,8}Y", r"X1234567Y", Some((0, 9)), Some((8, 8))); -mat!(match_repetition_126, r"(a|ab|c|bcd){0,}(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); -mat!(match_repetition_127, r"(a|ab|c|bcd){1,}(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); -mat!(match_repetition_128, r"(a|ab|c|bcd){2,}(d*)", r"ababcd", Some((0, 6)), Some((3, 6)), Some((6, 6))); -mat!(match_repetition_129, r"(a|ab|c|bcd){3,}(d*)", r"ababcd", Some((0, 6)), Some((3, 6)), Some((6, 6))); -mat!(match_repetition_130, r"(a|ab|c|bcd){4,}(d*)", r"ababcd", None); -mat!(match_repetition_131, r"(a|ab|c|bcd){0,10}(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); -mat!(match_repetition_132, r"(a|ab|c|bcd){1,10}(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); -mat!(match_repetition_133, r"(a|ab|c|bcd){2,10}(d*)", r"ababcd", Some((0, 6)), Some((3, 6)), Some((6, 6))); -mat!(match_repetition_134, r"(a|ab|c|bcd){3,10}(d*)", r"ababcd", Some((0, 6)), Some((3, 6)), Some((6, 6))); -mat!(match_repetition_135, r"(a|ab|c|bcd){4,10}(d*)", r"ababcd", None); -mat!(match_repetition_136, r"(a|ab|c|bcd)*(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); -mat!(match_repetition_137, r"(a|ab|c|bcd)+(d*)", r"ababcd", Some((0, 1)), Some((0, 1)), Some((1, 1))); -mat!(match_repetition_143, r"(ab|a|c|bcd){0,}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); -mat!(match_repetition_145, r"(ab|a|c|bcd){1,}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); -mat!(match_repetition_147, r"(ab|a|c|bcd){2,}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); -mat!(match_repetition_149, r"(ab|a|c|bcd){3,}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); -mat!(match_repetition_150, r"(ab|a|c|bcd){4,}(d*)", r"ababcd", None); -mat!(match_repetition_152, r"(ab|a|c|bcd){0,10}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); -mat!(match_repetition_154, r"(ab|a|c|bcd){1,10}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); -mat!(match_repetition_156, r"(ab|a|c|bcd){2,10}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); -mat!(match_repetition_158, r"(ab|a|c|bcd){3,10}(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); -mat!(match_repetition_159, r"(ab|a|c|bcd){4,10}(d*)", r"ababcd", None); -mat!(match_repetition_161, r"(ab|a|c|bcd)*(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); -mat!(match_repetition_163, r"(ab|a|c|bcd)+(d*)", r"ababcd", Some((0, 6)), Some((4, 5)), Some((5, 6))); - diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/macros_bytes.rs cargo-0.26.0/vendor/regex-0.2.6/tests/macros_bytes.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/macros_bytes.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/macros_bytes.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -// Macros for use in writing tests generic over &str/&[u8]. -macro_rules! text { ($text:expr) => { $text.as_bytes() } } -macro_rules! t { ($re:expr) => { text!($re) } } -macro_rules! match_text { ($text:expr) => { $text.as_bytes() } } - -macro_rules! bytes { ($text:expr) => { $text } } - -macro_rules! no_expand { - ($text:expr) => {{ - use regex::bytes::NoExpand; - NoExpand(text!($text)) - }} -} - -macro_rules! show { - ($text:expr) => {{ - use std::ascii::escape_default; - let mut s = vec![]; - for &b in bytes!($text) { - s.extend(escape_default(b)); - } - String::from_utf8(s).unwrap() - }} -} - -macro_rules! expand { - ($name:ident, $re:expr, $text:expr, $expand:expr, $expected:expr) => { - #[test] - fn $name() { - let re = regex!($re); - let cap = re.captures(t!($text)).unwrap(); - - let mut got = vec![]; - cap.expand(t!($expand), &mut got); - assert_eq!(show!(t!($expected)), show!(&*got)); - } - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/macros.rs cargo-0.26.0/vendor/regex-0.2.6/tests/macros.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/macros.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/macros.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,149 +0,0 @@ -// Convenience macros. - -macro_rules! findall { - ($re:expr, $text:expr) => {{ - $re.find_iter(text!($text)) - .map(|m| (m.start(), m.end())).collect::<Vec<_>>() - }} -} - -// Macros for automatically producing tests. - -macro_rules! ismatch { - ($name:ident, $re:expr, $text:expr, $ismatch:expr) => { - #[test] - fn $name() { - let re = regex!($re); - assert_eq!($ismatch, re.is_match(text!($text))); - } - }; -} - -macro_rules! mat( - ($name:ident, $re:expr, $text:expr, $($loc:tt)+) => ( - #[test] - fn $name() { - let text = text!($text); - let expected: Vec<Option<_>> = vec![$($loc)+]; - let r = regex!($re); - let got: Vec<Option<_>> = match r.captures(text) { - Some(c) => { - assert!(r.is_match(text)); - assert!(r.shortest_match(text).is_some()); - r.capture_names() - .enumerate() - .map(|(i, _)| c.get(i).map(|m| (m.start(), m.end()))) - .collect() - } - None => vec![None], - }; - // The test set sometimes leave out capture groups, so truncate - // actual capture groups to match test set. - let mut sgot = &got[..]; - if sgot.len() > expected.len() { - sgot = &sgot[0..expected.len()] - } - if expected != sgot { - panic!("For RE '{}' against '{:?}', \ - expected '{:?}' but got '{:?}'", - $re, text, expected, sgot); - } - } - ); -); - -macro_rules! matiter( - ($name:ident, $re:expr, $text:expr) => ( - #[test] - fn $name() { - let text = text!($text); - let expected: Vec<(usize, usize)> = vec![]; - let r = regex!($re); - let got: Vec<_> = - r.find_iter(text).map(|m| (m.start(), m.end())).collect(); - if expected != got { - panic!("For RE '{}' against '{:?}', \ - expected '{:?}' but got '{:?}'", - $re, text, expected, got); - } - let captures_got: Vec<_> = - r.captures_iter(text) - .map(|c| c.get(0).unwrap()) - .map(|m| (m.start(), m.end())) - .collect(); - if captures_got != got { - panic!("For RE '{}' against '{:?}', \ - got '{:?}' using find_iter but got '{:?}' \ - using captures_iter", - $re, text, got, captures_got); - } - } - ); - ($name:ident, $re:expr, $text:expr, $($loc:tt)+) => ( - #[test] - fn $name() { - let text = text!($text); - let expected: Vec<_> = vec![$($loc)+]; - let r = regex!($re); - let got: Vec<_> = - r.find_iter(text).map(|m| (m.start(), m.end())).collect(); - if expected != got { - panic!("For RE '{}' against '{:?}', \ - expected '{:?}' but got '{:?}'", - $re, text, expected, got); - } - let captures_got: Vec<_> = - r.captures_iter(text) - .map(|c| c.get(0).unwrap()) - .map(|m| (m.start(), m.end())) - .collect(); - if captures_got != got { - panic!("For RE '{}' against '{:?}', \ - got '{:?}' using find_iter but got '{:?}' \ - using captures_iter", - $re, text, got, captures_got); - } - } - ); -); - -macro_rules! matset { - ($name:ident, $res:expr, $text:expr, $($match_index:expr),*) => { - #[test] - fn $name() { - let text = text!($text); - let set = regex_set!($res); - assert!(set.is_match(text)); - let expected = vec![$($match_index),*]; - let matches = set.matches(text); - assert!(matches.matched_any()); - let got: Vec<_> = matches.into_iter().collect(); - assert_eq!(expected, got); - } - } -} - -macro_rules! nomatset { - ($name:ident, $res:expr, $text:expr) => { - #[test] - fn $name() { - let text = text!($text); - let set = regex_set!($res); - assert!(!set.is_match(text)); - let matches = set.matches(text); - assert!(!matches.matched_any()); - assert_eq!(0, matches.into_iter().count()); - } - } -} - -macro_rules! split { - ($name:ident, $re:expr, $text:expr, $expected:expr) => { - #[test] - fn $name() { - let re = regex!($re); - let splitted: Vec<_> = re.split(t!($text)).collect(); - assert_eq!($expected, &*splitted); - } - } -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/macros_str.rs cargo-0.26.0/vendor/regex-0.2.6/tests/macros_str.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/macros_str.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/macros_str.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,35 +0,0 @@ -// Macros for use in writing tests generic over &str/&[u8]. -macro_rules! text { ($text:expr) => { $text } } -macro_rules! t { ($text:expr) => { text!($text) } } -macro_rules! match_text { ($text:expr) => { $text.as_str() } } - -macro_rules! no_expand { - ($text:expr) => {{ - use regex::NoExpand; - NoExpand(text!($text)) - }} -} - -macro_rules! show { ($text:expr) => { $text } } - -// N.B. The expansion API for &str and &[u8] APIs differs slightly for now, -// but they should be unified in 1.0. Then we can move this macro back into -// tests/api.rs where it is used. ---AG -macro_rules! expand { - ($name:ident, $re:expr, $text:expr, $expand:expr, $expected:expr) => { - #[test] - fn $name() { - let re = regex!($re); - let cap = re.captures(t!($text)).unwrap(); - - let mut got = String::new(); - cap.expand(t!($expand), &mut got); - assert_eq!(show!(t!($expected)), show!(&*got)); - } - } -} - -#[cfg(feature = "pattern")] -macro_rules! searcher_expr { ($e:expr) => ($e) } -#[cfg(not(feature = "pattern"))] -macro_rules! searcher_expr { ($e:expr) => ({}) } diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/misc.rs cargo-0.26.0/vendor/regex-0.2.6/tests/misc.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/misc.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/misc.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -mat!(prefix_literal_match, r"^abc", r"abc", Some((0, 3))); -mat!(prefix_literal_nomatch, r"^abc", r"zabc", None); -mat!(one_literal_edge, r"abc", r"xxxxxab", None); -matiter!(terminates, r"a$", r"a", (0, 1)); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/multiline.rs cargo-0.26.0/vendor/regex-0.2.6/tests/multiline.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/multiline.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/multiline.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -matiter!(match_multi_1, r"(?m)^[a-z]+$", "abc\ndef\nxyz", - (0, 3), (4, 7), (8, 11)); -matiter!(match_multi_2, r"(?m)^$", "abc\ndef\nxyz"); -matiter!(match_multi_3, r"(?m)^", "abc\ndef\nxyz", - (0, 0), (4, 4), (8, 8)); -matiter!(match_multi_4, r"(?m)$", "abc\ndef\nxyz", - (3, 3), (7, 7), (11, 11)); -matiter!(match_multi_5, r"(?m)^[a-z]", "abc\ndef\nxyz", - (0, 1), (4, 5), (8, 9)); -matiter!(match_multi_6, r"(?m)[a-z]^", "abc\ndef\nxyz"); -matiter!(match_multi_7, r"(?m)[a-z]$", "abc\ndef\nxyz", - (2, 3), (6, 7), (10, 11)); -matiter!(match_multi_8, r"(?m)$[a-z]", "abc\ndef\nxyz"); -matiter!(match_multi_9, r"(?m)^$", "", (0, 0)); - -matiter!(match_multi_rep_1, r"(?m)(?:^$)*", "a\nb\nc", - (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); -matiter!(match_multi_rep_2, r"(?m)(?:^|a)+", "a\naaa\n", - (0, 0), (2, 2), (3, 5), (6, 6)); -matiter!(match_multi_rep_3, r"(?m)(?:^|a)*", "a\naaa\n", - (0, 1), (2, 5), (6, 6)); -matiter!(match_multi_rep_4, r"(?m)(?:^[a-z])+", "abc\ndef\nxyz", - (0, 1), (4, 5), (8, 9)); -matiter!(match_multi_rep_5, r"(?m)(?:^[a-z]{3}\n?)+", "abc\ndef\nxyz", - (0, 11)); -matiter!(match_multi_rep_6, r"(?m)(?:^[a-z]{3}\n?)*", "abc\ndef\nxyz", - (0, 11)); -matiter!(match_multi_rep_7, r"(?m)(?:\n?[a-z]{3}$)+", "abc\ndef\nxyz", - (0, 11)); -matiter!(match_multi_rep_8, r"(?m)(?:\n?[a-z]{3}$)*", "abc\ndef\nxyz", - (0, 11)); -matiter!(match_multi_rep_9, r"(?m)^*", "\naa\n", - (0, 0), (1, 1), (2, 2), (3, 3), (4, 4)); -matiter!(match_multi_rep_10, r"(?m)^+", "\naa\n", - (0, 0), (1, 1), (4, 4)); -matiter!(match_multi_rep_11, r"(?m)$*", "\naa\n", - (0, 0), (1, 1), (2, 2), (3, 3), (4, 4)); -matiter!(match_multi_rep_12, r"(?m)$+", "\naa\n", - (0, 0), (3, 3), (4, 4)); -matiter!(match_multi_rep_13, r"(?m)(?:$\n)+", "\n\naaa\n\n", - (0, 2), (5, 7)); -matiter!(match_multi_rep_14, r"(?m)(?:$\n)*", "\n\naaa\n\n", - (0, 2), (3, 3), (4, 4), (5, 7)); -matiter!(match_multi_rep_15, r"(?m)(?:$\n^)+", "\n\naaa\n\n", - (0, 2), (5, 7)); -matiter!(match_multi_rep_16, r"(?m)(?:^|$)+", "\n\naaa\n\n", - (0, 0), (1, 1), (2, 2), (5, 5), (6, 6), (7, 7)); -matiter!(match_multi_rep_17, r"(?m)(?:$\n)*", "\n\naaa\n\n", - (0, 2), (3, 3), (4, 4), (5, 7)); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/noparse.rs cargo-0.26.0/vendor/regex-0.2.6/tests/noparse.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/noparse.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/noparse.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,48 +0,0 @@ -macro_rules! noparse( - ($name:ident, $re:expr) => ( - #[test] - fn $name() { - let re = $re; - match regex_new!(re) { - Err(_) => {}, - Ok(_) => panic!("Regex '{}' should cause a parse error.", re), - } - } - ); -); - -noparse!(fail_double_repeat, "a**"); -noparse!(fail_no_repeat_arg, "*"); -noparse!(fail_incomplete_escape, "\\"); -noparse!(fail_class_incomplete, "[A-"); -noparse!(fail_class_not_closed, "[A"); -noparse!(fail_class_no_begin, r"[\A]"); -noparse!(fail_class_no_end, r"[\z]"); -noparse!(fail_class_no_boundary, r"[\b]"); -noparse!(fail_open_paren, "("); -noparse!(fail_close_paren, ")"); -noparse!(fail_invalid_range, "[a-Z]"); -noparse!(fail_empty_capture_name, "(?P<>a)"); -noparse!(fail_empty_capture_exp, "(?P<name>)"); -noparse!(fail_bad_capture_name, "(?P<na-me>)"); -noparse!(fail_bad_flag, "(?a)a"); -noparse!(fail_empty_alt_before, "|a"); -noparse!(fail_empty_alt_after, "a|"); -noparse!(fail_too_big, "a{10000000}"); -noparse!(fail_counted_no_close, "a{1001"); -noparse!(fail_unfinished_cap, "(?"); -noparse!(fail_unfinished_escape, "\\"); -noparse!(fail_octal_digit, r"\8"); -noparse!(fail_hex_digit, r"\xG0"); -noparse!(fail_hex_short, r"\xF"); -noparse!(fail_hex_long_digits, r"\x{fffg}"); -noparse!(fail_flag_bad, "(?a)"); -noparse!(fail_flag_empty, "(?)"); -noparse!(fail_double_neg, "(?-i-i)"); -noparse!(fail_neg_empty, "(?i-)"); -noparse!(fail_empty_group, "()"); -noparse!(fail_dupe_named, "(?P<a>.)(?P<a>.)"); -noparse!(fail_range_end_no_class, "[a-[:lower:]]"); -noparse!(fail_range_end_no_begin, r"[a-\A]"); -noparse!(fail_range_end_no_end, r"[a-\z]"); -noparse!(fail_range_end_no_boundary, r"[a-\b]"); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/plugin.rs cargo-0.26.0/vendor/regex-0.2.6/tests/plugin.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/plugin.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/plugin.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use regex::Regex; -static RE: Regex = regex!(r"\d+"); - -#[test] -fn splitn() { - let text = "cauchy123plato456tyler789binx"; - let subs: Vec<&str> = RE.splitn(text, 2).collect(); - assert_eq!(subs, vec!("cauchy", "plato456tyler789binx")); -} - -#[test] -fn split() { - let text = "cauchy123plato456tyler789binx"; - let subs: Vec<&str> = RE.split(text).collect(); - assert_eq!(subs, vec!("cauchy", "plato", "tyler", "binx")); -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/regression.rs cargo-0.26.0/vendor/regex-0.2.6/tests/regression.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/regression.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/regression.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,99 +0,0 @@ -// See: https://github.com/rust-lang/regex/issues/48 -#[test] -fn invalid_regexes_no_crash() { - assert!(regex_new!("(*)").is_err()); - assert!(regex_new!("(?:?)").is_err()); - assert!(regex_new!("(?)").is_err()); - assert!(regex_new!("*").is_err()); -} - -// See: https://github.com/rust-lang/regex/issues/98 -#[test] -fn regression_many_repeat_stack_overflow() { - let re = regex!("^.{1,2500}"); - assert_eq!(vec![(0, 1)], findall!(re, "a")); -} - -// See: https://github.com/rust-lang/regex/issues/75 -mat!(regression_unsorted_binary_search_1, r"(?i)[a_]+", "A_", Some((0, 2))); -mat!(regression_unsorted_binary_search_2, r"(?i)[A_]+", "a_", Some((0, 2))); - -// See: https://github.com/rust-lang/regex/issues/99 -mat!(regression_negated_char_class_1, r"(?i)[^x]", "x", None); -mat!(regression_negated_char_class_2, r"(?i)[^x]", "X", None); - -// See: https://github.com/rust-lang/regex/issues/101 -mat!(regression_ascii_word_underscore, r"[[:word:]]", "_", Some((0, 1))); - -// See: https://github.com/rust-lang/regex/issues/129 -#[test] -fn regression_captures_rep() { - let re = regex!(r"([a-f]){2}(?P<foo>[x-z])"); - let caps = re.captures(text!("abx")).unwrap(); - assert_eq!(match_text!(caps.name("foo").unwrap()), text!("x")); -} - -// See: https://github.com/rust-lang/regex/issues/153 -mat!(regression_alt_in_alt1, r"ab?|$", "az", Some((0, 1))); -mat!(regression_alt_in_alt2, r"^(.*?)(\n|\r\n?|$)", "ab\rcd", Some((0, 3))); - -// See: https://github.com/rust-lang/regex/issues/169 -mat!(regression_leftmost_first_prefix, r"z*azb", "azb", Some((0, 3))); - -// See: https://github.com/rust-lang/regex/issues/76 -mat!(uni_case_lower_nocase_flag, r"(?i)\p{Ll}+", "ΛΘΓΔα", Some((0, 10))); - -// See: https://github.com/rust-lang/regex/issues/191 -mat!(many_alternates, r"1|2|3|4|5|6|7|8|9|10|int", "int", Some((0, 3))); - -// burntsushi was bad and didn't create an issue for this bug. -mat!(anchored_prefix1, r"^a\S", "a ", None); -mat!(anchored_prefix2, r"^a\S", "foo boo a ", None); -mat!(anchored_prefix3, r"^-[a-z]", "r-f", None); - -// See: https://github.com/rust-lang/regex/issues/204 -split!(split_on_word_boundary, r"\b", r"Should this (work?)", - &[t!(""), t!("Should"), t!(" "), t!("this"), - t!(" ("), t!("work"), t!("?)")]); -matiter!(word_boundary_dfa, r"\b", "a b c", - (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); - -// See: https://github.com/rust-lang/regex/issues/268 -matiter!(partial_anchor, r"^a|b", "ba", (0, 1)); - -// See: https://github.com/rust-lang/regex/issues/264 -mat!(ascii_boundary_no_capture, r"(?-u)\B", "\u{28f3e}", Some((0, 0))); -mat!(ascii_boundary_capture, r"(?-u)(\B)", "\u{28f3e}", Some((0, 0))); - -// See: https://github.com/rust-lang/regex/issues/280 -ismatch!(partial_anchor_alternate_begin, r"^a|z", "yyyyya", false); -ismatch!(partial_anchor_alternate_end, r"a$|z", "ayyyyy", false); - -// See: https://github.com/rust-lang/regex/issues/289 -mat!(lits_unambiguous1, r"(ABC|CDA|BC)X", "CDAX", Some((0, 4))); - -// See: https://github.com/rust-lang/regex/issues/291 -mat!(lits_unambiguous2, r"((IMG|CAM|MG|MB2)_|(DSCN|CIMG))(?P<n>[0-9]+)$", - "CIMG2341", Some((0, 8)), Some((0, 4)), None, Some((0, 4)), Some((4, 8))); - -// See: https://github.com/rust-lang/regex/issues/271 -mat!(end_not_wb, r"$(?-u:\B)", "\u{5c124}\u{b576c}", Some((8, 8))); -mat!(endl_or_wb, r"(?m:$)|(?-u:\b)", "\u{6084e}", Some((4, 4))); -mat!(zero_or_end, r"(?i-u:\x00)|$", "\u{e682f}", Some((4, 4))); -mat!(y_or_endl, r"(?i-u:y)|(?m:$)", "\u{b4331}", Some((4, 4))); -mat!(wb_start_x, r"(?u:\b)^(?-u:X)", "X", Some((0, 1))); - -// See: https://github.com/rust-lang/regex/issues/321 -ismatch!(strange_anchor_non_complete_prefix, r"a^{2}", "", false); -ismatch!(strange_anchor_non_complete_suffix, r"${2}a", "", false); - -// See: https://github.com/rust-lang/regex/issues/334 -mat!(captures_after_dfa_premature_end, r"a(b*(X|$))?", "abcbX", - Some((0, 1)), None, None); - -// See: https://github.com/rust-lang/regex/issues/437 -ismatch!( - literal_panic, - r"typename type\-parameter\-\d+\-\d+::.+", - "test", - false); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/replace.rs cargo-0.26.0/vendor/regex-0.2.6/tests/replace.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/replace.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/replace.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -macro_rules! replace( - ($name:ident, $which:ident, $re:expr, - $search:expr, $replace:expr, $result:expr) => ( - #[test] - fn $name() { - let re = regex!($re); - assert_eq!(re.$which(text!($search), $replace), text!($result)); - } - ); -); - -replace!(first, replace, r"\d", "age: 26", t!("Z"), "age: Z6"); -replace!(plus, replace, r"\d+", "age: 26", t!("Z"), "age: Z"); -replace!(all, replace_all, r"\d", "age: 26", t!("Z"), "age: ZZ"); -replace!(groups, replace, r"(\S+)\s+(\S+)", "w1 w2", t!("$2 $1"), "w2 w1"); -replace!(double_dollar, replace, - r"(\S+)\s+(\S+)", "w1 w2", t!("$2 $$1"), "w2 $1"); -// replace!(adjacent_index, replace, - // r"([^aeiouy])ies$", "skies", t!("$1y"), "sky"); -replace!(named, replace_all, - r"(?P<first>\S+)\s+(?P<last>\S+)(?P<space>\s*)", - "w1 w2 w3 w4", t!("$last $first$space"), "w2 w1 w4 w3"); -replace!(trim, replace_all, "^[ \t]+|[ \t]+$", " \t trim me\t \t", - t!(""), "trim me"); -replace!(number_hypen, replace, r"(.)(.)", "ab", t!("$1-$2"), "a-b"); -// replace!(number_underscore, replace, r"(.)(.)", "ab", t!("$1_$2"), "a_b"); -replace!(simple_expand, replace_all, r"(\w) (\w)", "a b", t!("$2 $1"), "b a"); -replace!(literal_dollar1, replace_all, - r"(\w+) (\w+)", "a b", t!("$$1"), "$1"); -replace!(literal_dollar2, replace_all, - r"(\w+) (\w+)", "a b", t!("$2 $$c $1"), "b $c a"); -replace!(no_expand1, replace, - r"(\S+)\s+(\S+)", "w1 w2", no_expand!("$2 $1"), "$2 $1"); -replace!(no_expand2, replace, - r"(\S+)\s+(\S+)", "w1 w2", no_expand!("$$1"), "$$1"); - -// See https://github.com/rust-lang/regex/issues/314 -replace!(match_at_start_replace_with_empty, replace_all, r"foo", "foobar", t!(""), "bar"); - -// See https://github.com/rust-lang/regex/issues/393 -replace!(single_empty_match, replace, r"^", "bar", t!("foo"), "foobar"); - -// See https://github.com/rust-lang/regex/issues/399 -replace!(capture_longest_possible_name, replace_all, r"(.)", "b", t!("${1}a $1a"), "ba "); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/searcher.rs cargo-0.26.0/vendor/regex-0.2.6/tests/searcher.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/searcher.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/searcher.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,66 +0,0 @@ -macro_rules! searcher { - ($name:ident, $re:expr, $haystack:expr) => ( - searcher!($name, $re, $haystack, vec vec![]); - ); - ($name:ident, $re:expr, $haystack:expr, $($steps:expr,)*) => ( - searcher!($name, $re, $haystack, vec vec![$($steps),*]); - ); - ($name:ident, $re:expr, $haystack:expr, $($steps:expr),*) => ( - searcher!($name, $re, $haystack, vec vec![$($steps),*]); - ); - ($name:ident, $re:expr, $haystack:expr, vec $expect_steps:expr) => ( - #[test] - #[allow(unused_imports)] - fn $name() { - searcher_expr! {{ - use std::str::pattern::{Pattern, Searcher}; - use std::str::pattern::SearchStep::{Match, Reject, Done}; - let re = regex!($re); - let mut se = re.into_searcher($haystack); - let mut got_steps = vec![]; - loop { - match se.next() { - Done => break, - step => { got_steps.push(step); } - } - } - assert_eq!(got_steps, $expect_steps); - }} - } - ); -} - -searcher!(searcher_empty_regex_empty_haystack, r"", "", Match(0, 0)); -searcher!(searcher_empty_regex, r"", "ab", - Match(0, 0), Reject(0, 1), Match(1, 1), Reject(1, 2), Match(2, 2)); -searcher!(searcher_empty_haystack, r"\d", ""); -searcher!(searcher_one_match, r"\d", "5", - Match(0, 1)); -searcher!(searcher_no_match, r"\d", "a", - Reject(0, 1)); -searcher!(searcher_two_adjacent_matches, r"\d", "56", - Match(0, 1), Match(1, 2)); -searcher!(searcher_two_non_adjacent_matches, r"\d", "5a6", - Match(0, 1), Reject(1, 2), Match(2, 3)); -searcher!(searcher_reject_first, r"\d", "a6", - Reject(0, 1), Match(1, 2)); -searcher!(searcher_one_zero_length_matches, r"\d*", "a1b2", - Match(0, 0), // ^ - Reject(0, 1), // a - Match(1, 2), // a1 - Reject(2, 3), // a1b - Match(3, 4), // a1b2 -); -searcher!(searcher_many_zero_length_matches, r"\d*", "a1bbb2", - Match(0, 0), // ^ - Reject(0, 1), // a - Match(1, 2), // a1 - Reject(2, 3), // a1b - Match(3, 3), // a1bb - Reject(3, 4), // a1bb - Match(4, 4), // a1bbb - Reject(4, 5), // a1bbb - Match(5, 6), // a1bbba -); -searcher!(searcher_unicode, r".+?", "Ⅰ1Ⅱ2", - Match(0, 3), Match(3, 4), Match(4, 7), Match(7, 8)); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/set.rs cargo-0.26.0/vendor/regex-0.2.6/tests/set.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/set.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/set.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -matset!(set1, &["a", "a"], "a", 0, 1); -matset!(set2, &["a", "a"], "ba", 0, 1); -matset!(set3, &["a", "b"], "a", 0); -matset!(set4, &["a", "b"], "b", 1); -matset!(set5, &["a|b", "b|a"], "b", 0, 1); -matset!(set6, &["foo", "oo"], "foo", 0, 1); -matset!(set7, &["^foo", "bar$"], "foo", 0); -matset!(set8, &["^foo", "bar$"], "foo bar", 0, 1); -matset!(set9, &["^foo", "bar$"], "bar", 1); -matset!(set10, &[r"[a-z]+$", "foo"], "01234 foo", 0, 1); -matset!(set11, &[r"[a-z]+$", "foo"], "foo 01234", 1); -matset!(set12, &[r".*?", "a"], "zzzzzza", 0, 1); -matset!(set13, &[r".*", "a"], "zzzzzza", 0, 1); -matset!(set14, &[r".*", "a"], "zzzzzz", 0); -matset!(set15, &[r"\ba\b"], "hello a bye", 0); -matset!(set16, &["a"], "a", 0); -matset!(set17, &[".*a"], "a", 0); -matset!(set18, &["a", "β"], "β", 1); - -nomatset!(nset1, &["a", "a"], "b"); -nomatset!(nset2, &["^foo", "bar$"], "bar foo"); -nomatset!(nset3, { let xs: &[&str] = &[]; xs }, "a"); -nomatset!(nset4, &[r"^rooted$", r"\.log$"], "notrooted"); - -// See: https://github.com/rust-lang/regex/issues/187 -#[test] -fn regression_subsequent_matches() { - let set = regex_set!(&["ab", "b"]); - let text = text!("ba"); - assert!(set.matches(text).matched(1)); - assert!(set.matches(text).matched(1)); -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/shortest_match.rs cargo-0.26.0/vendor/regex-0.2.6/tests/shortest_match.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/shortest_match.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/shortest_match.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -macro_rules! shortmat { - ($name:ident, $re:expr, $text:expr, $shortest_match:expr) => { - #[test] - fn $name() { - let text = text!($text); - let re = regex!($re); - assert_eq!($shortest_match, re.shortest_match(text)); - } - } -} - -shortmat!(t01, r"a+", r"aa", Some(1)); -// Test that the reverse suffix optimization gets it right. -shortmat!(t02, r".*(?:abcd)+", r"abcdabcd", Some(4)); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/suffix_reverse.rs cargo-0.26.0/vendor/regex-0.2.6/tests/suffix_reverse.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/suffix_reverse.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/suffix_reverse.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -mat!(t01, r".*abcd", r"abcd", Some((0, 4))); -mat!(t02, r".*(?:abcd)+", r"abcd", Some((0, 4))); -mat!(t03, r".*(?:abcd)+", r"abcdabcd", Some((0, 8))); -mat!(t04, r".*(?:abcd)+", r"abcdxabcd", Some((0, 9))); -mat!(t05, r".*x(?:abcd)+", r"abcdxabcd", Some((0, 9))); -mat!(t06, r"[^abcd]*x(?:abcd)+", r"abcdxabcd", Some((4, 9))); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/test_backtrack_bytes.rs cargo-0.26.0/vendor/regex-0.2.6/tests/test_backtrack_bytes.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/test_backtrack_bytes.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/test_backtrack_bytes.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,65 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -extern crate rand; -extern crate regex; - -macro_rules! regex_new { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new($re) - .bounded_backtracking() - .only_utf8(false) - .build() - .map(|e| e.into_byte_regex()) - }} -} - -macro_rules! regex { - ($re:expr) => { - regex_new!($re).unwrap() - } -} - -macro_rules! regex_set_new { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new_many($re) - .bounded_backtracking() - .only_utf8(false) - .build() - .map(|e| e.into_byte_regex_set()) - }} -} - -macro_rules! regex_set { - ($res:expr) => { - regex_set_new!($res).unwrap() - } -} - -// Must come before other module definitions. -include!("macros_bytes.rs"); -include!("macros.rs"); - -mod api; -mod bytes; -mod crazy; -mod flags; -mod fowler; -mod multiline; -mod noparse; -mod regression; -mod replace; -mod set; -mod suffix_reverse; -mod unicode; -mod word_boundary; -mod word_boundary_ascii; diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/test_backtrack.rs cargo-0.26.0/vendor/regex-0.2.6/tests/test_backtrack.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/test_backtrack.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/test_backtrack.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,64 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![cfg_attr(feature = "pattern", feature(pattern))] - -extern crate rand; -extern crate regex; - -macro_rules! regex_new { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new($re) - .bounded_backtracking().build().map(|e| e.into_regex()) - }} -} - -macro_rules! regex { - ($re:expr) => { - regex_new!($re).unwrap() - } -} - -macro_rules! regex_set_new { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new_many($re) - .bounded_backtracking() - .build() - .map(|e| e.into_regex_set()) - }} -} - -macro_rules! regex_set { - ($res:expr) => { - regex_set_new!($res).unwrap() - } -} - -// Must come before other module definitions. -include!("macros_str.rs"); -include!("macros.rs"); - -mod api; -mod api_str; -mod crazy; -mod flags; -mod fowler; -mod multiline; -mod noparse; -mod regression; -mod replace; -mod searcher; -mod set; -mod suffix_reverse; -mod unicode; -mod word_boundary; -mod word_boundary_unicode; diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/test_backtrack_utf8bytes.rs cargo-0.26.0/vendor/regex-0.2.6/tests/test_backtrack_utf8bytes.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/test_backtrack_utf8bytes.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/test_backtrack_utf8bytes.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,65 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![cfg_attr(feature = "pattern", feature(pattern))] - -extern crate rand; -extern crate regex; - -macro_rules! regex_new { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new($re) - .bounded_backtracking().bytes(true).build().map(|e| e.into_regex()) - }} -} - -macro_rules! regex { - ($re:expr) => { - regex_new!($re).unwrap() - } -} - -macro_rules! regex_set_new { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new_many($re) - .bounded_backtracking() - .bytes(true) - .build() - .map(|e| e.into_regex_set()) - }} -} - -macro_rules! regex_set { - ($res:expr) => { - regex_set_new!($res).unwrap() - } -} - -// Must come before other module definitions. -include!("macros_str.rs"); -include!("macros.rs"); - -mod api; -mod api_str; -mod crazy; -mod flags; -mod fowler; -mod multiline; -mod noparse; -mod regression; -mod replace; -mod searcher; -mod set; -mod suffix_reverse; -mod unicode; -mod word_boundary; -mod word_boundary_unicode; diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/test_default_bytes.rs cargo-0.26.0/vendor/regex-0.2.6/tests/test_default_bytes.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/test_default_bytes.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/test_default_bytes.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,73 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -extern crate rand; -extern crate regex; - -macro_rules! regex_new { - ($re:expr) => {{ - use regex::bytes::Regex; - Regex::new($re) - }} -} - -macro_rules! regex_set_new { - ($res:expr) => {{ - use regex::bytes::RegexSet; - RegexSet::new($res) - }} -} - -macro_rules! regex { - ($re:expr) => { - regex_new!($re).unwrap() - } -} - -macro_rules! regex_set { - ($res:expr) => { - regex_set_new!($res).unwrap() - } -} - -// Must come before other module definitions. -include!("macros_bytes.rs"); -include!("macros.rs"); - -// A silly wrapper to make it possible to write and match raw bytes. -struct R<'a>(&'a [u8]); -impl<'a> R<'a> { fn as_bytes(&self) -> &'a [u8] { self.0 } } - -// See: https://github.com/rust-lang/regex/issues/321 -// -// These tests are here because they do not have the same behavior in every -// regex engine. -mat!(invalid_utf8_nfa1, r".", R(b"\xD4\xC2\x65\x2B\x0E\xFE"), Some((2, 3))); -mat!(invalid_utf8_nfa2, r"${2}ä", R(b"\xD4\xC2\x65\x2B\x0E\xFE"), None); -mat!(invalid_utf8_nfa3, r".", R(b"\x0A\xDB\x82\x6E\x33\x01\xDD\x33\xCD"), - Some((1, 3))); -mat!(invalid_utf8_nfa4, r"${2}ä", R(b"\x0A\xDB\x82\x6E\x33\x01\xDD\x33\xCD"), - None); - -mod api; -mod bytes; -mod crazy; -mod flags; -mod fowler; -mod multiline; -mod noparse; -mod regression; -mod replace; -mod set; -mod shortest_match; -mod suffix_reverse; -mod unicode; -mod word_boundary; -mod word_boundary_ascii; diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/test_default.rs cargo-0.26.0/vendor/regex-0.2.6/tests/test_default.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/test_default.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/test_default.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,77 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![cfg_attr(feature = "pattern", feature(pattern))] - -extern crate rand; -extern crate regex; - -// Due to macro scoping rules, this definition only applies for the modules -// defined below. Effectively, it allows us to use the same tests for both -// native and dynamic regexes. -// -// This is also used to test the various matching engines. This one exercises -// the normal code path which automatically chooses the engine based on the -// regex and the input. Other dynamic tests explicitly set the engine to use. -macro_rules! regex_new { - ($re:expr) => {{ - use regex::Regex; - Regex::new($re) - }} -} - -macro_rules! regex { - ($re:expr) => { - regex_new!($re).unwrap() - } -} - -macro_rules! regex_set_new { - ($re:expr) => {{ - use regex::RegexSet; - RegexSet::new($re) - }} -} - -macro_rules! regex_set { - ($res:expr) => { - regex_set_new!($res).unwrap() - } -} - -// Must come before other module definitions. -include!("macros_str.rs"); -include!("macros.rs"); - -mod api; -mod api_str; -mod crazy; -mod flags; -mod fowler; -mod misc; -mod multiline; -mod noparse; -mod regression; -mod replace; -mod searcher; -mod set; -mod shortest_match; -mod suffix_reverse; -mod unicode; -mod word_boundary; -mod word_boundary_unicode; - -#[test] -fn disallow_non_utf8() { - assert!(regex::Regex::new(r"(?-u)\xFF").is_err()); - assert!(regex::Regex::new(r"(?-u).").is_err()); - assert!(regex::Regex::new(r"(?-u)[\xFF]").is_err()); - assert!(regex::Regex::new(r"(?-u)☃").is_err()); -} diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/test_nfa_bytes.rs cargo-0.26.0/vendor/regex-0.2.6/tests/test_nfa_bytes.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/test_nfa_bytes.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/test_nfa_bytes.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,65 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -extern crate rand; -extern crate regex; - -macro_rules! regex_new { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new($re) - .nfa() - .only_utf8(false) - .build() - .map(|e| e.into_byte_regex()) - }} -} - -macro_rules! regex { - ($re:expr) => { - regex_new!($re).unwrap() - } -} - -macro_rules! regex_set_new { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new_many($re) - .nfa() - .only_utf8(false) - .build() - .map(|e| e.into_byte_regex_set()) - }} -} - -macro_rules! regex_set { - ($res:expr) => { - regex_set_new!($res).unwrap() - } -} - -// Must come before other module definitions. -include!("macros_bytes.rs"); -include!("macros.rs"); - -mod api; -mod bytes; -mod crazy; -mod flags; -mod fowler; -mod multiline; -mod noparse; -mod regression; -mod replace; -mod set; -mod suffix_reverse; -mod unicode; -mod word_boundary; -mod word_boundary_ascii; diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/test_nfa.rs cargo-0.26.0/vendor/regex-0.2.6/tests/test_nfa.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/test_nfa.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/test_nfa.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![cfg_attr(feature = "pattern", feature(pattern))] - -extern crate rand; -extern crate regex; - -macro_rules! regex_new { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new($re).nfa().build().map(|e| e.into_regex()) - }} -} - -macro_rules! regex { - ($re:expr) => { - regex_new!($re).unwrap() - } -} - -macro_rules! regex_set_new { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new_many($re).nfa().build().map(|e| e.into_regex_set()) - }} -} - -macro_rules! regex_set { - ($res:expr) => { - regex_set_new!($res).unwrap() - } -} - -// Must come before other module definitions. -include!("macros_str.rs"); -include!("macros.rs"); - -mod api; -mod api_str; -mod crazy; -mod flags; -mod fowler; -mod multiline; -mod noparse; -mod regression; -mod replace; -mod searcher; -mod set; -mod suffix_reverse; -mod unicode; -mod word_boundary; -mod word_boundary_unicode; diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/test_nfa_utf8bytes.rs cargo-0.26.0/vendor/regex-0.2.6/tests/test_nfa_utf8bytes.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/test_nfa_utf8bytes.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/test_nfa_utf8bytes.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,61 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![cfg_attr(feature = "pattern", feature(pattern))] - -extern crate rand; -extern crate regex; - -macro_rules! regex_new { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new($re).nfa().bytes(true).build().map(|e| e.into_regex()) - }} -} - -macro_rules! regex { - ($re:expr) => { - regex_new!($re).unwrap() - } -} - -macro_rules! regex_set_new { - ($re:expr) => {{ - use regex::internal::ExecBuilder; - ExecBuilder::new_many($re) - .nfa().bytes(true).build().map(|e| e.into_regex_set()) - }} -} - -macro_rules! regex_set { - ($res:expr) => { - regex_set_new!($res).unwrap() - } -} - -// Must come before other module definitions. -include!("macros_str.rs"); -include!("macros.rs"); - -mod api; -mod api_str; -mod crazy; -mod flags; -mod fowler; -mod multiline; -mod noparse; -mod regression; -mod replace; -mod searcher; -mod set; -mod suffix_reverse; -mod unicode; -mod word_boundary; -mod word_boundary_unicode; diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/unicode.rs cargo-0.26.0/vendor/regex-0.2.6/tests/unicode.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/unicode.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/unicode.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -mat!(uni_literal, r"☃", "☃", Some((0, 3))); -mat!(uni_literal_plus, r"☃+", "☃", Some((0, 3))); -mat!(uni_literal_casei_plus, r"(?i)☃+", "☃", Some((0, 3))); -mat!(uni_class_plus, r"[☃Ⅰ]+", "☃", Some((0, 3))); -mat!(uni_one, r"\pN", "Ⅰ", Some((0, 3))); -mat!(uni_mixed, r"\pN+", "Ⅰ1Ⅱ2", Some((0, 8))); -mat!(uni_not, r"\PN+", "abⅠ", Some((0, 2))); -mat!(uni_not_class, r"[\PN]+", "abⅠ", Some((0, 2))); -mat!(uni_not_class_neg, r"[^\PN]+", "abⅠ", Some((2, 5))); -mat!(uni_case, r"(?i)Δ", "δ", Some((0, 2))); -mat!(uni_case_upper, r"\p{Lu}+", "ΛΘΓΔα", Some((0, 8))); -mat!(uni_case_upper_nocase_flag, r"(?i)\p{Lu}+", "ΛΘΓΔα", Some((0, 10))); -mat!(uni_case_upper_nocase, r"\p{L}+", "ΛΘΓΔα", Some((0, 10))); -mat!(uni_case_lower, r"\p{Ll}+", "ΛΘΓΔα", Some((8, 10))); - -// Test the Unicode friendliness of Perl character classes. -mat!(uni_perl_w, r"\w+", "dδd", Some((0, 4))); -mat!(uni_perl_w_not, r"\w+", "⥡", None); -mat!(uni_perl_w_neg, r"\W+", "⥡", Some((0, 3))); -mat!(uni_perl_d, r"\d+", "1२३9", Some((0, 8))); -mat!(uni_perl_d_not, r"\d+", "Ⅱ", None); -mat!(uni_perl_d_neg, r"\D+", "Ⅱ", Some((0, 3))); -mat!(uni_perl_s, r"\s+", " ", Some((0, 3))); -mat!(uni_perl_s_not, r"\s+", "☃", None); -mat!(uni_perl_s_neg, r"\S+", "☃", Some((0, 3))); - -// And do the same for word boundaries. -mat!(uni_boundary_none, r"\d\b", "6δ", None); -mat!(uni_boundary_ogham, r"\d\b", "6 ", Some((0, 1))); -mat!(uni_not_boundary_none, r"\d\B", "6δ", Some((0, 1))); -mat!(uni_not_boundary_ogham, r"\d\B", "6 ", None); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/word_boundary_ascii.rs cargo-0.26.0/vendor/regex-0.2.6/tests/word_boundary_ascii.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/word_boundary_ascii.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/word_boundary_ascii.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ -// ASCII word boundaries are completely oblivious to Unicode characters. -// For Unicode word boundaries, the tests are precisely inverted. -matiter!(ascii1, r"(?-u:\b)x(?-u:\b)", "áxβ", (2, 3)); -matiter!(ascii2, r"(?-u:\B)x(?-u:\B)", "áxβ"); -matiter!(ascii3, r"(?-u:\B)", "0\u{7EF5E}", (2, 2), (3, 3), (4, 4), (5, 5)); - -// We still get Unicode word boundaries by default in byte regexes. -matiter!(unicode1, r"\bx\b", "áxβ"); -matiter!(unicode2, r"\Bx\B", "áxβ", (2, 3)); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/word_boundary.rs cargo-0.26.0/vendor/regex-0.2.6/tests/word_boundary.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/word_boundary.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/word_boundary.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,89 +0,0 @@ -// Many of these are cribbed from RE2's test suite. - -matiter!(wb1, r"\b", ""); -matiter!(wb2, r"\b", "a", (0, 0), (1, 1)); -matiter!(wb3, r"\b", "ab", (0, 0), (2, 2)); -matiter!(wb4, r"^\b", "ab", (0, 0)); -matiter!(wb5, r"\b$", "ab", (2, 2)); -matiter!(wb6, r"^\b$", "ab"); -matiter!(wb7, r"\bbar\b", "nobar bar foo bar", (6, 9), (14, 17)); -matiter!(wb8, r"a\b", "faoa x", (3, 4)); -matiter!(wb9, r"\bbar", "bar x", (0, 3)); -matiter!(wb10, r"\bbar", "foo\nbar x", (4, 7)); -matiter!(wb11, r"bar\b", "foobar", (3, 6)); -matiter!(wb12, r"bar\b", "foobar\nxxx", (3, 6)); -matiter!(wb13, r"(foo|bar|[A-Z])\b", "foo", (0, 3)); -matiter!(wb14, r"(foo|bar|[A-Z])\b", "foo\n", (0, 3)); -matiter!(wb15, r"\b(foo|bar|[A-Z])", "foo", (0, 3)); -matiter!(wb16, r"\b(foo|bar|[A-Z])\b", "X", (0, 1)); -matiter!(wb17, r"\b(foo|bar|[A-Z])\b", "XY"); -matiter!(wb18, r"\b(foo|bar|[A-Z])\b", "bar", (0, 3)); -matiter!(wb19, r"\b(foo|bar|[A-Z])\b", "foo", (0, 3)); -matiter!(wb20, r"\b(foo|bar|[A-Z])\b", "foo\n", (0, 3)); -matiter!(wb21, r"\b(foo|bar|[A-Z])\b", "ffoo bbar N x", (10, 11)); -matiter!(wb22, r"\b(fo|foo)\b", "fo", (0, 2)); -matiter!(wb23, r"\b(fo|foo)\b", "foo", (0, 3)); -matiter!(wb24, r"\b\b", ""); -matiter!(wb25, r"\b\b", "a", (0, 0), (1, 1)); -matiter!(wb26, r"\b$", ""); -matiter!(wb27, r"\b$", "x", (1, 1)); -matiter!(wb28, r"\b$", "y x", (3, 3)); -matiter!(wb29, r"\b.$", "x", (0, 1)); -matiter!(wb30, r"^\b(fo|foo)\b", "fo", (0, 2)); -matiter!(wb31, r"^\b(fo|foo)\b", "foo", (0, 3)); -matiter!(wb32, r"^\b$", ""); -matiter!(wb33, r"^\b$", "x"); -matiter!(wb34, r"^\b.$", "x", (0, 1)); -matiter!(wb35, r"^\b.\b$", "x", (0, 1)); -matiter!(wb36, r"^^^^^\b$$$$$", ""); -matiter!(wb37, r"^^^^^\b.$$$$$", "x", (0, 1)); -matiter!(wb38, r"^^^^^\b$$$$$", "x"); -matiter!(wb39, r"^^^^^\b\b\b.\b\b\b$$$$$", "x", (0, 1)); -matiter!(wb40, r"\b.+\b", "$$abc$$", (2, 5)); -matiter!(wb41, r"\b", "a b c", (0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)); - -matiter!(nb1, r"\Bfoo\B", "n foo xfoox that", (7, 10)); -matiter!(nb2, r"a\B", "faoa x", (1, 2)); -matiter!(nb3, r"\Bbar", "bar x"); -matiter!(nb4, r"\Bbar", "foo\nbar x"); -matiter!(nb5, r"bar\B", "foobar"); -matiter!(nb6, r"bar\B", "foobar\nxxx"); -matiter!(nb7, r"(foo|bar|[A-Z])\B", "foox", (0, 3)); -matiter!(nb8, r"(foo|bar|[A-Z])\B", "foo\n"); -matiter!(nb9, r"\B", "", (0, 0)); -matiter!(nb10, r"\B", "x"); -matiter!(nb11, r"\B(foo|bar|[A-Z])", "foo"); -matiter!(nb12, r"\B(foo|bar|[A-Z])\B", "xXy", (1, 2)); -matiter!(nb13, r"\B(foo|bar|[A-Z])\B", "XY"); -matiter!(nb14, r"\B(foo|bar|[A-Z])\B", "XYZ", (1, 2)); -matiter!(nb15, r"\B(foo|bar|[A-Z])\B", "abara", (1, 4)); -matiter!(nb16, r"\B(foo|bar|[A-Z])\B", "xfoo_", (1, 4)); -matiter!(nb17, r"\B(foo|bar|[A-Z])\B", "xfoo\n"); -matiter!(nb18, r"\B(foo|bar|[A-Z])\B", "foo bar vNX", (9, 10)); -matiter!(nb19, r"\B(fo|foo)\B", "xfoo", (1, 3)); -matiter!(nb20, r"\B(foo|fo)\B", "xfooo", (1, 4)); -matiter!(nb21, r"\B\B", "", (0, 0)); -matiter!(nb22, r"\B\B", "x"); -matiter!(nb23, r"\B$", "", (0, 0)); -matiter!(nb24, r"\B$", "x"); -matiter!(nb25, r"\B$", "y x"); -matiter!(nb26, r"\B.$", "x"); -matiter!(nb27, r"^\B(fo|foo)\B", "fo"); -matiter!(nb28, r"^\B(fo|foo)\B", "foo"); -matiter!(nb29, r"^\B", "", (0, 0)); -matiter!(nb30, r"^\B", "x"); -matiter!(nb31, r"^\B\B", "", (0, 0)); -matiter!(nb32, r"^\B\B", "x"); -matiter!(nb33, r"^\B$", "", (0, 0)); -matiter!(nb34, r"^\B$", "x"); -matiter!(nb35, r"^\B.$", "x"); -matiter!(nb36, r"^\B.\B$", "x"); -matiter!(nb37, r"^^^^^\B$$$$$", "", (0, 0)); -matiter!(nb38, r"^^^^^\B.$$$$$", "x"); -matiter!(nb39, r"^^^^^\B$$$$$", "x"); - -// These work for both Unicode and ASCII because all matches are reported as -// byte offsets, and « and » do not correspond to word boundaries at either -// the character or byte level. -matiter!(unicode1, r"\bx\b", "«x", (2, 3)); -matiter!(unicode2, r"\bx\b", "x»", (0, 1)); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/tests/word_boundary_unicode.rs cargo-0.26.0/vendor/regex-0.2.6/tests/word_boundary_unicode.rs --- cargo-0.25.0/vendor/regex-0.2.6/tests/word_boundary_unicode.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/tests/word_boundary_unicode.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -// Unicode word boundaries know about Unicode characters. -// For ASCII word boundaries, the tests are precisely inverted. -matiter!(unicode1, r"\bx\b", "áxβ"); -matiter!(unicode2, r"\Bx\B", "áxβ", (2, 3)); - -matiter!(ascii1, r"(?-u:\b)x(?-u:\b)", "áxβ", (2, 3)); -matiter!(ascii2, r"(?-u:\B)x(?-u:\B)", "áxβ"); -matiter!(ascii3, r"(?-u:\B)", "0\u{7EF5E}", (5, 5)); diff -Nru cargo-0.25.0/vendor/regex-0.2.6/.travis.yml cargo-0.26.0/vendor/regex-0.2.6/.travis.yml --- cargo-0.25.0/vendor/regex-0.2.6/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-0.2.6/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,32 +0,0 @@ -dist: trusty -sudo: false -language: rust -rust: - - 1.12.0 - - stable - - beta - - nightly -script: ci/script.sh -addons: - apt: - packages: - - libcurl4-openssl-dev - - libelf-dev - - libdw-dev - - binutils-dev - - wget - - clang-3.6 - - cmake - - python - - python-virtualenv -after_success: ci/after_success.sh -env: - global: - secure: "GdGE0kFYiJGccVZligur7JlWRCy49eH6uWPl71mrnaaW8jLHmkva0jVb0LB9e5ol3YMaMCgrwM2pcj3Uk2C08YcGIoEKOLlDVho351KaD6XfclZ29CQTAPMz4Xut2IcB4YeuZlDrOnM26guTIOtn2NAjeQgOhpM/ErzVBgkB+wQ=" -notifications: - email: - on_success: never -branches: - only: - - master - - auto diff -Nru cargo-0.25.0/vendor/regex-syntax-0.4.2/.cargo-checksum.json cargo-0.26.0/vendor/regex-syntax-0.4.2/.cargo-checksum.json --- cargo-0.25.0/vendor/regex-syntax-0.4.2/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.4.2/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"8e931c58b93d86f080c734bfd2bce7dd0079ae2331235818133c8be7f422e20e"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/regex-syntax-0.4.2/Cargo.toml cargo-0.26.0/vendor/regex-syntax-0.4.2/Cargo.toml --- cargo-0.25.0/vendor/regex-syntax-0.4.2/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.4.2/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "regex-syntax" -version = "0.4.2" -authors = ["The Rust Project Developers"] -description = "A regular expression parser." -homepage = "https://github.com/rust-lang/regex" -documentation = "https://docs.rs/regex-syntax" -license = "MIT/Apache-2.0" -repository = "https://github.com/rust-lang/regex" -[dev-dependencies.quickcheck] -version = "0.6" -default-features = false - -[dev-dependencies.rand] -version = "0.4" diff -Nru cargo-0.25.0/vendor/regex-syntax-0.4.2/src/lib.rs cargo-0.26.0/vendor/regex-syntax-0.4.2/src/lib.rs --- cargo-0.25.0/vendor/regex-syntax-0.4.2/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.4.2/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2223 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/*! -This crate provides a regular expression parser and an abstract syntax for -regular expressions. The abstract syntax is defined by the `Expr` type. The -concrete syntax is enumerated in the -[`regex`](../regex/index.html#syntax) -crate documentation. - -Note that since this crate is first and foremost an implementation detail for -the `regex` crate, it may experience more frequent breaking changes. It is -exposed as a separate crate so that others may use it to do analysis on regular -expressions or even build their own matching engine. - -# Example: parsing an expression - -Parsing a regular expression can be done with the `Expr::parse` function. - -```rust -use regex_syntax::Expr; - -assert_eq!(Expr::parse(r"ab|yz").unwrap(), Expr::Alternate(vec![ - Expr::Literal { chars: vec!['a', 'b'], casei: false }, - Expr::Literal { chars: vec!['y', 'z'], casei: false }, -])); -``` - -# Example: inspecting an error - -The parser in this crate provides very detailed error values. For example, -if an invalid character class range is given: - -```rust -use regex_syntax::{Expr, ErrorKind}; - -let err = Expr::parse(r"[z-a]").unwrap_err(); -assert_eq!(err.position(), 4); -assert_eq!(err.kind(), &ErrorKind::InvalidClassRange { - start: 'z', - end: 'a', -}); -``` - -Or unbalanced parentheses: - -```rust -use regex_syntax::{Expr, ErrorKind}; - -let err = Expr::parse(r"ab(cd").unwrap_err(); -assert_eq!(err.position(), 2); -assert_eq!(err.kind(), &ErrorKind::UnclosedParen); -``` -*/ - -#![deny(missing_docs)] -#![cfg_attr(test, deny(warnings))] - -#[cfg(test)] extern crate quickcheck; -#[cfg(test)] extern crate rand; - -mod literals; -mod parser; -mod unicode; - -use std::ascii; -use std::char; -use std::cmp::{Ordering, max, min}; -use std::fmt; -use std::iter::IntoIterator; -use std::ops::Deref; -use std::result; -use std::slice; -use std::u8; -use std::vec; - -use unicode::case_folding; - -use self::Expr::*; -use self::Repeater::*; - -use parser::{Flags, Parser}; - -pub use literals::{Literals, Lit}; - -/// A regular expression abstract syntax tree. -/// -/// An `Expr` represents the abstract syntax of a regular expression. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Expr { - /// An empty regex (which never matches any text). - Empty, - /// A sequence of one or more literal characters to be matched. - Literal { - /// The characters. - chars: Vec<char>, - /// Whether to match case insensitively. - casei: bool, - }, - /// A sequence of one or more literal bytes to be matched. - LiteralBytes { - /// The bytes. - bytes: Vec<u8>, - /// Whether to match case insensitively. - /// - /// The interpretation of "case insensitive" in this context is - /// ambiguous since `bytes` can be arbitrary. However, a good heuristic - /// is to assume that the bytes are ASCII-compatible and do simple - /// ASCII case folding. - casei: bool, - }, - /// Match any character. - AnyChar, - /// Match any character, excluding new line (`0xA`). - AnyCharNoNL, - /// Match any byte. - AnyByte, - /// Match any byte, excluding new line (`0xA`). - AnyByteNoNL, - /// A character class. - Class(CharClass), - /// A character class with byte ranges only. - ClassBytes(ByteClass), - /// Match the start of a line or beginning of input. - StartLine, - /// Match the end of a line or end of input. - EndLine, - /// Match the beginning of input. - StartText, - /// Match the end of input. - EndText, - /// Match a word boundary (word character on one side and a non-word - /// character on the other). - WordBoundary, - /// Match a position that is not a word boundary (word or non-word - /// characters on both sides). - NotWordBoundary, - /// Match an ASCII word boundary. - WordBoundaryAscii, - /// Match a position that is not an ASCII word boundary. - NotWordBoundaryAscii, - /// A group, possibly non-capturing. - Group { - /// The expression inside the group. - e: Box<Expr>, - /// The capture index (starting at `1`) only for capturing groups. - i: Option<usize>, - /// The capture name, only for capturing named groups. - name: Option<String>, - }, - /// A repeat operator (`?`, `*`, `+` or `{m,n}`). - Repeat { - /// The expression to be repeated. Limited to literals, `.`, classes - /// or grouped expressions. - e: Box<Expr>, - /// The type of repeat operator used. - r: Repeater, - /// Whether the repeat is greedy (match the most) or not (match the - /// least). - greedy: bool, - }, - /// A concatenation of expressions. Must be matched one after the other. - /// - /// N.B. A concat expression can only appear at the top-level or - /// immediately inside a group expression. - Concat(Vec<Expr>), - /// An alternation of expressions. Only one must match. - /// - /// N.B. An alternate expression can only appear at the top-level or - /// immediately inside a group expression. - Alternate(Vec<Expr>), -} - -type CaptureIndex = Option<usize>; - -type CaptureName = Option<String>; - -/// The type of a repeat operator expression. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Repeater { - /// Match zero or one (`?`). - ZeroOrOne, - /// Match zero or more (`*`). - ZeroOrMore, - /// Match one or more (`+`). - OneOrMore, - /// Match for at least `min` and at most `max` (`{m,n}`). - /// - /// When `max` is `None`, there is no upper bound on the number of matches. - Range { - /// Lower bound on the number of matches. - min: u32, - /// Optional upper bound on the number of matches. - max: Option<u32>, - }, -} - -impl Repeater { - /// Returns true if and only if this repetition can match the empty string. - fn matches_empty(&self) -> bool { - use self::Repeater::*; - match *self { - ZeroOrOne => true, - ZeroOrMore => true, - OneOrMore => false, - Range { min, .. } => min == 0, - } - } -} - -/// A character class. -/// -/// A character class has a canonical format that the parser guarantees. Its -/// canonical format is defined by the following invariants: -/// -/// 1. Given any Unicode scalar value, it is matched by *at most* one character -/// range in a canonical character class. -/// 2. Every adjacent character range is separated by at least one Unicode -/// scalar value. -/// 3. Given any pair of character ranges `r1` and `r2`, if -/// `r1.end < r2.start`, then `r1` comes before `r2` in a canonical -/// character class. -/// -/// In sum, any `CharClass` produced by this crate's parser is a sorted -/// sequence of non-overlapping ranges. This makes it possible to test whether -/// a character is matched by a class with a binary search. -/// -/// If the case insensitive flag was set when parsing a character class, then -/// simple case folding is done automatically. For example, `(?i)[a-c]` is -/// automatically translated to `[a-cA-C]`. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct CharClass { - ranges: Vec<ClassRange>, -} - -/// A single inclusive range in a character class. -/// -/// Since range boundaries are defined by Unicode scalar values, the boundaries -/// can never be in the open interval `(0xD7FF, 0xE000)`. However, a range may -/// *cover* codepoints that are not scalar values. -/// -/// Note that this has a few convenient impls on `PartialEq` and `PartialOrd` -/// for testing whether a character is contained inside a given range. -#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord)] -pub struct ClassRange { - /// The start character of the range. - /// - /// This must be less than or equal to `end`. - pub start: char, - - /// The end character of the range. - /// - /// This must be greater than or equal to `start`. - pub end: char, -} - -/// A byte class for byte ranges only. -/// -/// A byte class has a canonical format that the parser guarantees. Its -/// canonical format is defined by the following invariants: -/// -/// 1. Given any byte, it is matched by *at most* one byte range in a canonical -/// character class. -/// 2. Every adjacent byte range is separated by at least one byte. -/// 3. Given any pair of byte ranges `r1` and `r2`, if -/// `r1.end < r2.start`, then `r1` comes before `r2` in a canonical -/// character class. -/// -/// In sum, any `ByteClass` produced by this crate's parser is a sorted -/// sequence of non-overlapping ranges. This makes it possible to test whether -/// a byte is matched by a class with a binary search. -/// -/// If the case insensitive flag was set when parsing a character class, -/// then simple ASCII-only case folding is done automatically. For example, -/// `(?i)[a-c]` is automatically translated to `[a-cA-C]`. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ByteClass { - ranges: Vec<ByteRange>, -} - -/// A single inclusive range in a byte class. -/// -/// Note that this has a few convenient impls on `PartialEq` and `PartialOrd` -/// for testing whether a byte is contained inside a given range. -#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord)] -pub struct ByteRange { - /// The start byte of the range. - /// - /// This must be less than or equal to `end`. - pub start: u8, - - /// The end byte of the range. - /// - /// This must be greater than or equal to `end`. - pub end: u8, -} - -/// A builder for configuring regular expression parsing. -/// -/// This allows setting the default values of flags and other options, such -/// as the maximum nesting depth. -#[derive(Clone, Debug)] -pub struct ExprBuilder { - flags: Flags, - nest_limit: usize, -} - -impl ExprBuilder { - /// Create a new builder for configuring expression parsing. - /// - /// Note that all flags are disabled by default. - pub fn new() -> ExprBuilder { - ExprBuilder { - flags: Flags::default(), - nest_limit: 200, - } - } - - /// Set the default value for the case insensitive (`i`) flag. - pub fn case_insensitive(mut self, yes: bool) -> ExprBuilder { - self.flags.casei = yes; - self - } - - /// Set the default value for the multi-line matching (`m`) flag. - pub fn multi_line(mut self, yes: bool) -> ExprBuilder { - self.flags.multi = yes; - self - } - - /// Set the default value for the any character (`s`) flag. - pub fn dot_matches_new_line(mut self, yes: bool) -> ExprBuilder { - self.flags.dotnl = yes; - self - } - - /// Set the default value for the greedy swap (`U`) flag. - pub fn swap_greed(mut self, yes: bool) -> ExprBuilder { - self.flags.swap_greed = yes; - self - } - - /// Set the default value for the ignore whitespace (`x`) flag. - pub fn ignore_whitespace(mut self, yes: bool) -> ExprBuilder { - self.flags.ignore_space = yes; - self - } - - /// Set the default value for the Unicode (`u`) flag. - /// - /// If `yes` is false, then `allow_bytes` is set to true. - pub fn unicode(mut self, yes: bool) -> ExprBuilder { - self.flags.unicode = yes; - if !yes { - self.allow_bytes(true) - } else { - self - } - } - - /// Whether the parser allows matching arbitrary bytes or not. - /// - /// When the `u` flag is disabled (either with this builder or in the - /// expression itself), the parser switches to interpreting the expression - /// as matching arbitrary bytes instead of Unicode codepoints. For example, - /// the expression `(?u:\xFF)` matches the *codepoint* `\xFF`, which - /// corresponds to the UTF-8 byte sequence `\xCE\xBF`. Conversely, - /// `(?-u:\xFF)` matches the *byte* `\xFF`, which is not valid UTF-8. - /// - /// When `allow_bytes` is disabled (the default), an expression like - /// `(?-u:\xFF)` will cause the parser to return an error, since it would - /// otherwise match invalid UTF-8. When enabled, it will be allowed. - pub fn allow_bytes(mut self, yes: bool) -> ExprBuilder { - self.flags.allow_bytes = yes; - self - } - - /// Set the nesting limit for regular expression parsing. - /// - /// Regular expressions that nest more than this limit will result in a - /// `StackExhausted` error. - pub fn nest_limit(mut self, limit: usize) -> ExprBuilder { - self.nest_limit = limit; - self - } - - /// Parse a string as a regular expression using the current configuraiton. - pub fn parse(self, s: &str) -> Result<Expr> { - Parser::parse(s, self.flags).and_then(|e| e.simplify(self.nest_limit)) - } -} - -impl Expr { - /// Parses a string in a regular expression syntax tree. - /// - /// This is a convenience method for parsing an expression using the - /// default configuration. To tweak parsing options (such as which flags - /// are enabled by default), use the `ExprBuilder` type. - pub fn parse(s: &str) -> Result<Expr> { - ExprBuilder::new().parse(s) - } - - /// Returns true iff the expression can be repeated by a quantifier. - fn can_repeat(&self) -> bool { - match *self { - Literal{..} | LiteralBytes{..} - | AnyChar | AnyCharNoNL | AnyByte | AnyByteNoNL - | Class(_) | ClassBytes(_) - | StartLine | EndLine | StartText | EndText - | WordBoundary | NotWordBoundary - | WordBoundaryAscii | NotWordBoundaryAscii - | Group{..} - => true, - _ => false, - } - } - - fn simplify(self, nest_limit: usize) -> Result<Expr> { - fn combine_literals(es: &mut Vec<Expr>, e: Expr) { - match (es.pop(), e) { - (None, e) => es.push(e), - (Some(Literal { chars: mut chars1, casei: casei1 }), - Literal { chars: chars2, casei: casei2 }) => { - if casei1 == casei2 { - chars1.extend(chars2); - es.push(Literal { chars: chars1, casei: casei1 }); - } else { - es.push(Literal { chars: chars1, casei: casei1 }); - es.push(Literal { chars: chars2, casei: casei2 }); - } - } - (Some(LiteralBytes { bytes: mut bytes1, casei: casei1 }), - LiteralBytes { bytes: bytes2, casei: casei2 }) => { - if casei1 == casei2 { - bytes1.extend(bytes2); - es.push(LiteralBytes { bytes: bytes1, casei: casei1 }); - } else { - es.push(LiteralBytes { bytes: bytes1, casei: casei1 }); - es.push(LiteralBytes { bytes: bytes2, casei: casei2 }); - } - } - (Some(e1), e2) => { - es.push(e1); - es.push(e2); - } - } - } - fn simp(expr: Expr, recurse: usize, limit: usize) -> Result<Expr> { - if recurse > limit { - return Err(Error { - pos: 0, - surround: "".to_owned(), - kind: ErrorKind::StackExhausted, - }); - } - let simplify = |e| simp(e, recurse + 1, limit); - Ok(match expr { - Repeat { e, r, greedy } => Repeat { - e: Box::new(try!(simplify(*e))), - r: r, - greedy: greedy, - }, - Group { e, i, name } => { - let e = try!(simplify(*e)); - if i.is_none() && name.is_none() && e.can_repeat() { - e - } else { - Group { e: Box::new(e), i: i, name: name } - } - } - Concat(es) => { - let mut new_es = Vec::with_capacity(es.len()); - for e in es { - combine_literals(&mut new_es, try!(simplify(e))); - } - if new_es.len() == 1 { - new_es.pop().unwrap() - } else { - Concat(new_es) - } - } - Alternate(es) => { - let mut new_es = Vec::with_capacity(es.len()); - for e in es { - new_es.push(try!(simplify(e))); - } - Alternate(new_es) - } - e => e, - }) - } - simp(self, 0, nest_limit) - } - - /// Returns a set of literal prefixes extracted from this expression. - pub fn prefixes(&self) -> Literals { - let mut lits = Literals::empty(); - lits.union_prefixes(self); - lits - } - - /// Returns a set of literal suffixes extracted from this expression. - pub fn suffixes(&self) -> Literals { - let mut lits = Literals::empty(); - lits.union_suffixes(self); - lits - } - - /// Returns true if and only if the expression is required to match from - /// the beginning of text. - pub fn is_anchored_start(&self) -> bool { - match *self { - Repeat { ref e, r, .. } => { - !r.matches_empty() && e.is_anchored_start() - } - Group { ref e, .. } => e.is_anchored_start(), - Concat(ref es) => es[0].is_anchored_start(), - Alternate(ref es) => es.iter().all(|e| e.is_anchored_start()), - StartText => true, - _ => false, - } - } - - /// Returns true if and only if the expression has at least one matchable - /// sub-expression that must match the beginning of text. - pub fn has_anchored_start(&self) -> bool { - match *self { - Repeat { ref e, r, .. } => { - !r.matches_empty() && e.has_anchored_start() - } - Group { ref e, .. } => e.has_anchored_start(), - Concat(ref es) => es[0].has_anchored_start(), - Alternate(ref es) => es.iter().any(|e| e.has_anchored_start()), - StartText => true, - _ => false, - } - } - - /// Returns true if and only if the expression is required to match at the - /// end of the text. - pub fn is_anchored_end(&self) -> bool { - match *self { - Repeat { ref e, r, .. } => { - !r.matches_empty() && e.is_anchored_end() - } - Group { ref e, .. } => e.is_anchored_end(), - Concat(ref es) => es[es.len() - 1].is_anchored_end(), - Alternate(ref es) => es.iter().all(|e| e.is_anchored_end()), - EndText => true, - _ => false, - } - } - - /// Returns true if and only if the expression has at least one matchable - /// sub-expression that must match the beginning of text. - pub fn has_anchored_end(&self) -> bool { - match *self { - Repeat { ref e, r, .. } => { - !r.matches_empty() && e.has_anchored_end() - } - Group { ref e, .. } => e.has_anchored_end(), - Concat(ref es) => es[es.len() - 1].has_anchored_end(), - Alternate(ref es) => es.iter().any(|e| e.has_anchored_end()), - EndText => true, - _ => false, - } - } - - /// Returns true if and only if the expression contains sub-expressions - /// that can match arbitrary bytes. - pub fn has_bytes(&self) -> bool { - match *self { - Repeat { ref e, .. } => e.has_bytes(), - Group { ref e, .. } => e.has_bytes(), - Concat(ref es) => es.iter().any(|e| e.has_bytes()), - Alternate(ref es) => es.iter().any(|e| e.has_bytes()), - LiteralBytes{..} => true, - AnyByte | AnyByteNoNL => true, - ClassBytes(_) => true, - WordBoundaryAscii | NotWordBoundaryAscii => true, - _ => false, - } - } -} - -impl Deref for CharClass { - type Target = Vec<ClassRange>; - fn deref(&self) -> &Vec<ClassRange> { &self.ranges } -} - -impl IntoIterator for CharClass { - type Item = ClassRange; - type IntoIter = vec::IntoIter<ClassRange>; - fn into_iter(self) -> vec::IntoIter<ClassRange> { self.ranges.into_iter() } -} - -impl<'a> IntoIterator for &'a CharClass { - type Item = &'a ClassRange; - type IntoIter = slice::Iter<'a, ClassRange>; - fn into_iter(self) -> slice::Iter<'a, ClassRange> { self.iter() } -} - -impl CharClass { - /// Create a new class from an existing set of ranges. - pub fn new(ranges: Vec<ClassRange>) -> CharClass { - CharClass { ranges: ranges } - } - - /// Create an empty class. - fn empty() -> CharClass { - CharClass::new(Vec::new()) - } - - /// Returns true if `c` is matched by this character class. - pub fn matches(&self, c: char) -> bool { - self.binary_search_by(|range| c.partial_cmp(range).unwrap()).is_ok() - } - - /// Removes the given character from the class if it exists. - /// - /// Note that this takes `O(n)` time in the number of ranges. - pub fn remove(&mut self, c: char) { - let mut i = match self.binary_search_by(|r| c.partial_cmp(r).unwrap()) { - Ok(i) => i, - Err(_) => return, - }; - let mut r = self.ranges.remove(i); - if r.start == c { - r.start = inc_char(c); - if r.start > r.end || c == char::MAX { - return; - } - self.ranges.insert(i, r); - } else if r.end == c { - r.end = dec_char(c); - if r.end < r.start || c == '\x00' { - return; - } - self.ranges.insert(0, r); - } else { - let (mut r1, mut r2) = (r.clone(), r.clone()); - r1.end = dec_char(c); - if r1.start <= r1.end { - self.ranges.insert(i, r1); - i += 1; - } - r2.start = inc_char(c); - if r2.start <= r2.end { - self.ranges.insert(i, r2); - } - } - } - - /// Create a new empty class from this one. - fn to_empty(&self) -> CharClass { - CharClass { ranges: Vec::with_capacity(self.len()) } - } - - /// Create a byte class from this character class. - /// - /// Codepoints above 0xFF are removed. - fn to_byte_class(self) -> ByteClass { - ByteClass::new( - self.ranges.into_iter() - .filter_map(|r| r.to_byte_range()) - .collect()).canonicalize() - } - - /// Merge two classes and canonicalize them. - #[cfg(test)] - fn merge(mut self, other: CharClass) -> CharClass { - self.ranges.extend(other); - self.canonicalize() - } - - /// Canonicalize any sequence of ranges. - /// - /// This is responsible for enforcing the canonical format invariants - /// as described on the docs for the `CharClass` type. - fn canonicalize(mut self) -> CharClass { - // TODO: Save some cycles here by checking if already canonicalized. - self.ranges.sort(); - let mut ordered = self.to_empty(); // TODO: Do this in place? - for candidate in self { - // If the candidate overlaps with an existing range, then it must - // be the most recent range added because we process the candidates - // in order. - if let Some(or) = ordered.ranges.last_mut() { - if or.overlapping(candidate) { - *or = or.merge(candidate); - continue; - } - } - ordered.ranges.push(candidate); - } - ordered - } - - /// Calculate the intersection of two canonical character classes. - /// - /// The returned intersection is canonical. - fn intersection(&self, other: &CharClass) -> CharClass { - if self.ranges.is_empty() || other.ranges.is_empty() { - return CharClass::empty(); - } - - let mut intersection = CharClass::empty(); - - let mut iter_a = self.ranges.iter(); - let mut iter_b = other.ranges.iter(); - let mut a = iter_a.next().unwrap(); - let mut b = iter_b.next().unwrap(); - loop { - if let Some(i) = a.intersection(&b) { - intersection.ranges.push(i); - } - - // If the range with the smaller end didn't match this time, - // it won't ever match, so move on to the next one. - let (iter, item) = if a.end < b.end { - (&mut iter_a, &mut a) - } else { - (&mut iter_b, &mut b) - }; - match iter.next() { - Some(v) => *item = v, - None => break, // no more ranges to check, done - } - } - - intersection.canonicalize() - } - - /// Negates the character class. - /// - /// For all `c` where `c` is a Unicode scalar value, `c` matches `self` - /// if and only if `c` does not match `self.negate()`. - pub fn negate(mut self) -> CharClass { - fn range(s: char, e: char) -> ClassRange { ClassRange::new(s, e) } - - if self.is_empty() { - // Inverting an empty range yields all of Unicode. - return CharClass { - ranges: vec![ClassRange { start: '\x00', end: '\u{10ffff}' }], - }; - } - self = self.canonicalize(); - let mut inv = self.to_empty(); - if self[0].start > '\x00' { - inv.ranges.push(range('\x00', dec_char(self[0].start))); - } - for win in self.windows(2) { - inv.ranges.push(range(inc_char(win[0].end), - dec_char(win[1].start))); - } - if self[self.len() - 1].end < char::MAX { - inv.ranges.push(range(inc_char(self[self.len() - 1].end), - char::MAX)); - } - inv - } - - /// Apply case folding to this character class. - /// - /// N.B. Applying case folding to a negated character class probably - /// won't produce the expected result. e.g., `(?i)[^x]` really should - /// match any character sans `x` and `X`, but if `[^x]` is negated - /// before being case folded, you'll end up matching any character. - pub fn case_fold(self) -> CharClass { - let mut folded = self.to_empty(); - for r in self { - // Applying case folding to a range is expensive because *every* - // character needs to be examined. Thus, we avoid that drudgery - // if no character in the current range is in our case folding - // table. - if r.needs_case_folding() { - folded.ranges.extend(r.case_fold()); - } - folded.ranges.push(r); - } - folded.canonicalize() - } - - /// Returns the number of characters that match this class. - fn num_chars(&self) -> usize { - self.ranges.iter() - .map(|&r| 1 + (r.end as u32) - (r.start as u32)) - .fold(0, |acc, len| acc + len) - as usize - } -} - -impl ClassRange { - /// Create a new class range. - /// - /// If `end < start`, then the two values are swapped so that - /// the invariant `start <= end` is preserved. - fn new(start: char, end: char) -> ClassRange { - if start <= end { - ClassRange { start: start, end: end } - } else { - ClassRange { start: end, end: start } - } - } - - /// Translate this to a byte class. - /// - /// If the start codepoint exceeds 0xFF, then this returns `None`. - /// - /// If the end codepoint exceeds 0xFF, then it is set to 0xFF. - fn to_byte_range(self) -> Option<ByteRange> { - if self.start > '\u{FF}' { - None - } else { - let s = self.start as u8; - let e = min('\u{FF}', self.end) as u8; - Some(ByteRange::new(s, e)) - } - } - - /// Create a range of one character. - fn one(c: char) -> ClassRange { - ClassRange { start: c, end: c } - } - - /// Returns true if and only if the two ranges are overlapping. Note that - /// since ranges are inclusive, `a-c` and `d-f` are overlapping! - fn overlapping(self, other: ClassRange) -> bool { - max(self.start, other.start) <= inc_char(min(self.end, other.end)) - } - - /// Returns the intersection of the two ranges if they have common - /// characters, `None` otherwise. - fn intersection(&self, other: &ClassRange) -> Option<ClassRange> { - let start = max(self.start, other.start); - let end = min(self.end, other.end); - if start <= end { - Some(ClassRange::new(start, end)) - } else { - None - } - } - - /// Creates a new range representing the union of `self` and `other. - fn merge(self, other: ClassRange) -> ClassRange { - ClassRange { - start: min(self.start, other.start), - end: max(self.end, other.end), - } - } - - /// Returns true if and only if this range contains a character that is - /// in the case folding table. - fn needs_case_folding(self) -> bool { - case_folding::C_plus_S_both_table - .binary_search_by(|&(c, _)| self.partial_cmp(&c).unwrap()).is_ok() - } - - /// Apply case folding to this range. - /// - /// Since case folding might add characters such that the range is no - /// longer contiguous, this returns multiple class ranges. They are in - /// canonical order. - fn case_fold(self) -> Vec<ClassRange> { - let table = &case_folding::C_plus_S_both_table; - let (s, e) = (self.start as u32, self.end as u32 + 1); - let mut start = self.start; - let mut end = start; - let mut next_case_fold = '\x00'; - let mut ranges = Vec::with_capacity(10); - for mut c in (s..e).filter_map(char::from_u32) { - if c >= next_case_fold { - c = match simple_case_fold_both_result(c) { - Ok(i) => { - for &(c1, c2) in &table[i..] { - if c1 != c { - break; - } - if c2 != inc_char(end) { - ranges.push(ClassRange::new(start, end)); - start = c2; - } - end = c2; - } - continue; - } - Err(i) => { - if i < table.len() { - next_case_fold = table[i].0; - } else { - next_case_fold = '\u{10FFFF}'; - } - c - } - }; - } - // The fast path. We know this character doesn't have an entry - // in the case folding table. - if c != inc_char(end) { - ranges.push(ClassRange::new(start, end)); - start = c; - } - end = c; - } - ranges.push(ClassRange::new(start, end)); - ranges - } -} - -impl PartialEq<char> for ClassRange { - #[inline] - fn eq(&self, other: &char) -> bool { - self.start <= *other && *other <= self.end - } -} - -impl PartialEq<ClassRange> for char { - #[inline] - fn eq(&self, other: &ClassRange) -> bool { - other.eq(self) - } -} - -impl PartialOrd<char> for ClassRange { - #[inline] - fn partial_cmp(&self, other: &char) -> Option<Ordering> { - Some(if self == other { - Ordering::Equal - } else if *other > self.end { - Ordering::Greater - } else { - Ordering::Less - }) - } -} - -impl PartialOrd<ClassRange> for char { - #[inline] - fn partial_cmp(&self, other: &ClassRange) -> Option<Ordering> { - other.partial_cmp(self).map(|o| o.reverse()) - } -} - -impl ByteClass { - /// Create a new class from an existing set of ranges. - pub fn new(ranges: Vec<ByteRange>) -> ByteClass { - ByteClass { ranges: ranges } - } - - /// Returns true if `b` is matched by this byte class. - pub fn matches(&self, b: u8) -> bool { - self.binary_search_by(|range| b.partial_cmp(range).unwrap()).is_ok() - } - - /// Removes the given byte from the class if it exists. - /// - /// Note that this takes `O(n)` time in the number of ranges. - pub fn remove(&mut self, b: u8) { - let mut i = match self.binary_search_by(|r| b.partial_cmp(r).unwrap()) { - Ok(i) => i, - Err(_) => return, - }; - let mut r = self.ranges.remove(i); - if r.start == b { - r.start = b.saturating_add(1); - if r.start > r.end || b == u8::MAX { - return; - } - self.ranges.insert(i, r); - } else if r.end == b { - r.end = b.saturating_sub(1); - if r.end < r.start || b == b'\x00' { - return; - } - self.ranges.insert(0, r); - } else { - let (mut r1, mut r2) = (r.clone(), r.clone()); - r1.end = b.saturating_sub(1); - if r1.start <= r1.end { - self.ranges.insert(i, r1); - i += 1; - } - r2.start = b.saturating_add(1); - if r2.start <= r2.end { - self.ranges.insert(i, r2); - } - } - } - - /// Create a new empty class from this one. - fn to_empty(&self) -> ByteClass { - ByteClass { ranges: Vec::with_capacity(self.len()) } - } - - /// Canonicalze any sequence of ranges. - /// - /// This is responsible for enforcing the canonical format invariants - /// as described on the docs for the `ByteClass` type. - fn canonicalize(mut self) -> ByteClass { - // TODO: Save some cycles here by checking if already canonicalized. - self.ranges.sort(); - let mut ordered = self.to_empty(); // TODO: Do this in place? - for candidate in self { - // If the candidate overlaps with an existing range, then it must - // be the most recent range added because we process the candidates - // in order. - if let Some(or) = ordered.ranges.last_mut() { - if or.overlapping(candidate) { - *or = or.merge(candidate); - continue; - } - } - ordered.ranges.push(candidate); - } - ordered - } - - /// Negates the byte class. - /// - /// For all `b` where `b` is a byte, `b` matches `self` if and only if `b` - /// does not match `self.negate()`. - pub fn negate(mut self) -> ByteClass { - fn range(s: u8, e: u8) -> ByteRange { ByteRange::new(s, e) } - - if self.is_empty() { - // Inverting an empty range yields all bytes. - return ByteClass { - ranges: vec![ByteRange { start: b'\x00', end: b'\xff' }], - }; - } - self = self.canonicalize(); - let mut inv = self.to_empty(); - if self[0].start > b'\x00' { - inv.ranges.push(range(b'\x00', self[0].start.saturating_sub(1))); - } - for win in self.windows(2) { - inv.ranges.push(range(win[0].end.saturating_add(1), - win[1].start.saturating_sub(1))); - } - if self[self.len() - 1].end < u8::MAX { - inv.ranges.push(range(self[self.len() - 1].end.saturating_add(1), - u8::MAX)); - } - inv - } - - /// Apply case folding to this byte class. - /// - /// This assumes that the bytes in the ranges are ASCII compatible. - /// - /// N.B. Applying case folding to a negated character class probably - /// won't produce the expected result. e.g., `(?i)[^x]` really should - /// match any character sans `x` and `X`, but if `[^x]` is negated - /// before being case folded, you'll end up matching any character. - pub fn case_fold(self) -> ByteClass { - let mut folded = self.to_empty(); - for r in self { - folded.ranges.extend(r.case_fold()); - } - folded.canonicalize() - } - - /// Returns the number of bytes that match this class. - fn num_bytes(&self) -> usize { - self.ranges.iter() - .map(|&r| 1 + (r.end as u32) - (r.start as u32)) - .fold(0, |acc, len| acc + len) - as usize - } -} - -impl ByteRange { - /// Create a new class range. - /// - /// If `end < start`, then the two values are swapped so that - /// the invariant `start <= end` is preserved. - fn new(start: u8, end: u8) -> ByteRange { - if start <= end { - ByteRange { start: start, end: end } - } else { - ByteRange { start: end, end: start } - } - } - - /// Returns true if and only if the two ranges are overlapping. Note that - /// since ranges are inclusive, `a-c` and `d-f` are overlapping! - fn overlapping(self, other: ByteRange) -> bool { - max(self.start, other.start) - <= min(self.end, other.end).saturating_add(1) - } - - /// Returns true if and only if the intersection of self and other is non - /// empty. - fn is_intersect_empty(self, other: ByteRange) -> bool { - max(self.start, other.start) > min(self.end, other.end) - } - - /// Creates a new range representing the union of `self` and `other. - fn merge(self, other: ByteRange) -> ByteRange { - ByteRange { - start: min(self.start, other.start), - end: max(self.end, other.end), - } - } - - /// Apply case folding to this range. - /// - /// Since case folding might add bytes such that the range is no - /// longer contiguous, this returns multiple byte ranges. - /// - /// This assumes that the bytes in this range are ASCII compatible. - fn case_fold(self) -> Vec<ByteRange> { - // So much easier than Unicode case folding! - let mut ranges = vec![self]; - if !ByteRange::new(b'a', b'z').is_intersect_empty(self) { - let lower = max(self.start, b'a'); - let upper = min(self.end, b'z'); - ranges.push(ByteRange::new(lower - 32, upper - 32)); - } - if !ByteRange::new(b'A', b'Z').is_intersect_empty(self) { - let lower = max(self.start, b'A'); - let upper = min(self.end, b'Z'); - ranges.push(ByteRange::new(lower + 32, upper + 32)); - } - ranges - } -} - -impl Deref for ByteClass { - type Target = Vec<ByteRange>; - fn deref(&self) -> &Vec<ByteRange> { &self.ranges } -} - -impl IntoIterator for ByteClass { - type Item = ByteRange; - type IntoIter = vec::IntoIter<ByteRange>; - fn into_iter(self) -> vec::IntoIter<ByteRange> { self.ranges.into_iter() } -} - -impl<'a> IntoIterator for &'a ByteClass { - type Item = &'a ByteRange; - type IntoIter = slice::Iter<'a, ByteRange>; - fn into_iter(self) -> slice::Iter<'a, ByteRange> { self.iter() } -} - -impl PartialEq<u8> for ByteRange { - #[inline] - fn eq(&self, other: &u8) -> bool { - self.start <= *other && *other <= self.end - } -} - -impl PartialEq<ByteRange> for u8 { - #[inline] - fn eq(&self, other: &ByteRange) -> bool { - other.eq(self) - } -} - -impl PartialOrd<u8> for ByteRange { - #[inline] - fn partial_cmp(&self, other: &u8) -> Option<Ordering> { - Some(if self == other { - Ordering::Equal - } else if *other > self.end { - Ordering::Greater - } else { - Ordering::Less - }) - } -} - -impl PartialOrd<ByteRange> for u8 { - #[inline] - fn partial_cmp(&self, other: &ByteRange) -> Option<Ordering> { - other.partial_cmp(self).map(|o| o.reverse()) - } -} - -/// This implementation of `Display` will write a regular expression from the -/// syntax tree. It does not write the original string parsed. -impl fmt::Display for Expr { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Empty => write!(f, ""), - Literal { ref chars, casei } => { - if casei { - try!(write!(f, "(?iu:")); - } else { - try!(write!(f, "(?u:")); - } - for &c in chars { - try!(write!(f, "{}", quote_char(c))); - } - try!(write!(f, ")")); - Ok(()) - } - LiteralBytes { ref bytes, casei } => { - if casei { - try!(write!(f, "(?i-u:")); - } else { - try!(write!(f, "(?-u:")); - } - for &b in bytes { - try!(write!(f, "{}", quote_byte(b))); - } - try!(write!(f, ")")); - Ok(()) - } - AnyChar => write!(f, "(?su:.)"), - AnyCharNoNL => write!(f, "(?u:.)"), - AnyByte => write!(f, "(?s-u:.)"), - AnyByteNoNL => write!(f, "(?-u:.)"), - Class(ref cls) => write!(f, "{}", cls), - ClassBytes(ref cls) => write!(f, "{}", cls), - StartLine => write!(f, "(?m:^)"), - EndLine => write!(f, "(?m:$)"), - StartText => write!(f, r"^"), - EndText => write!(f, r"$"), - WordBoundary => write!(f, r"(?u:\b)"), - NotWordBoundary => write!(f, r"(?u:\B)"), - WordBoundaryAscii => write!(f, r"(?-u:\b)"), - NotWordBoundaryAscii => write!(f, r"(?-u:\B)"), - Group { ref e, i: None, name: None } => write!(f, "(?:{})", e), - Group { ref e, name: None, .. } => write!(f, "({})", e), - Group { ref e, name: Some(ref n), .. } => { - write!(f, "(?P<{}>{})", n, e) - } - Repeat { ref e, r, greedy } => { - match &**e { - &Literal { ref chars, .. } if chars.len() > 1 => { - try!(write!(f, "(?:{}){}", e, r)) - } - _ => try!(write!(f, "{}{}", e, r)), - } - if !greedy { try!(write!(f, "?")); } - Ok(()) - } - Concat(ref es) => { - for e in es { - try!(write!(f, "{}", e)); - } - Ok(()) - } - Alternate(ref es) => { - for (i, e) in es.iter().enumerate() { - if i > 0 { try!(write!(f, "|")); } - try!(write!(f, "{}", e)); - } - Ok(()) - } - } - } -} - -impl fmt::Display for Repeater { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - ZeroOrOne => write!(f, "?"), - ZeroOrMore => write!(f, "*"), - OneOrMore => write!(f, "+"), - Range { min: s, max: None } => write!(f, "{{{},}}", s), - Range { min: s, max: Some(e) } if s == e => write!(f, "{{{}}}", s), - Range { min: s, max: Some(e) } => write!(f, "{{{}, {}}}", s, e), - } - } -} - -impl fmt::Display for CharClass { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "(?u:[")); - for range in self.iter() { - if range.start == '-' || range.end == '-' { - try!(write!(f, "-")); - break; - } - } - for range in self.iter() { - let mut range = *range; - if range.start == '-' { - range.start = ((range.start as u8) + 1) as char; - } - if range.end == '-' { - range.end = ((range.end as u8) - 1) as char; - } - if range.start > range.end { - continue; - } - try!(write!(f, "{}", range)); - } - try!(write!(f, "])")); - Ok(()) - } -} - -impl fmt::Display for ClassRange { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}-{}", quote_char(self.start), quote_char(self.end)) - } -} - -impl fmt::Display for ByteClass { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "(?-u:[")); - for range in self.iter() { - if range.start == b'-' || range.end == b'-' { - try!(write!(f, "-")); - break; - } - } - for range in self.iter() { - let mut range = *range; - if range.start == b'-' { - range.start += 1; - } - if range.end == b'-' { - range.start -= 1; - } - if range.start > range.end { - continue; - } - try!(write!(f, "{}", range)); - } - try!(write!(f, "])")); - Ok(()) - } -} - -impl fmt::Display for ByteRange { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}-{}", quote_byte(self.start), quote_byte(self.end)) - } -} - -/// An alias for computations that can return a `Error`. -pub type Result<T> = ::std::result::Result<T, Error>; - -/// A parse error. -/// -/// This includes details about the specific type of error and a rough -/// approximation of where it occurred. -#[derive(Clone, Debug, PartialEq)] -pub struct Error { - pos: usize, - surround: String, - kind: ErrorKind, -} - -/// The specific type of parse error that can occur. -#[derive(Clone, Debug, PartialEq)] -pub enum ErrorKind { - /// A negation symbol is used twice in flag settings. - /// e.g., `(?-i-s)`. - DoubleFlagNegation, - /// The same capture name was used more than once. - /// e.g., `(?P<a>.)(?P<a>.)`. - DuplicateCaptureName(String), - /// An alternate is empty. e.g., `(|a)`. - EmptyAlternate, - /// A capture group name is empty. e.g., `(?P<>a)`. - EmptyCaptureName, - /// A negation symbol was not proceded by any flags. e.g., `(?i-)`. - EmptyFlagNegation, - /// A group is empty. e.g., `()`. - EmptyGroup, - /// An invalid number was used in a counted repetition. e.g., `a{b}`. - InvalidBase10(String), - /// An invalid hexadecimal number was used in an escape sequence. - /// e.g., `\xAG`. - InvalidBase16(String), - /// An invalid capture name was used. e.g., `(?P<0a>b)`. - InvalidCaptureName(String), - /// An invalid class range was givien. Specifically, when the start of the - /// range is greater than the end. e.g., `[z-a]`. - InvalidClassRange { - /// The first character specified in the range. - start: char, - /// The second character specified in the range. - end: char, - }, - /// An escape sequence was used in a character class where it is not - /// allowed. e.g., `[a-\pN]` or `[\A]`. - InvalidClassEscape(Expr), - /// An invalid counted repetition min/max was given. e.g., `a{2,1}`. - InvalidRepeatRange { - /// The first number specified in the repetition. - min: u32, - /// The second number specified in the repetition. - max: u32, - }, - /// An invalid Unicode scalar value was used in a long hexadecimal - /// sequence. e.g., `\x{D800}`. - InvalidScalarValue(u32), - /// An empty counted repetition operator. e.g., `a{}`. - MissingBase10, - /// A repetition operator was not applied to an expression. e.g., `*`. - RepeaterExpectsExpr, - /// A repetition operator was applied to an expression that cannot be - /// repeated. e.g., `a+*` or `a|*`. - RepeaterUnexpectedExpr(Expr), - /// A capture group name that is never closed. e.g., `(?P<a`. - UnclosedCaptureName(String), - /// An unclosed hexadecimal literal. e.g., `\x{a`. - UnclosedHex, - /// An unclosed parenthesis. e.g., `(a`. - UnclosedParen, - /// An unclosed counted repetition operator. e.g., `a{2`. - UnclosedRepeat, - /// An unclosed named Unicode class. e.g., `\p{Yi`. - UnclosedUnicodeName, - /// Saw end of regex before class was closed. e.g., `[a`. - UnexpectedClassEof, - /// Saw end of regex before escape sequence was closed. e.g., `\`. - UnexpectedEscapeEof, - /// Saw end of regex before flags were closed. e.g., `(?i`. - UnexpectedFlagEof, - /// Saw end of regex before two hexadecimal digits were seen. e.g., `\xA`. - UnexpectedTwoDigitHexEof, - /// Unopened parenthesis. e.g., `)`. - UnopenedParen, - /// Unrecognized escape sequence. e.g., `\q`. - UnrecognizedEscape(char), - /// Unrecognized flag. e.g., `(?a)`. - UnrecognizedFlag(char), - /// Unrecognized named Unicode class. e.g., `\p{Foo}`. - UnrecognizedUnicodeClass(String), - /// Indicates that the regex uses too much nesting. - /// - /// (N.B. This error exists because traversing the Expr is recursive and - /// an explicit heap allocated stack is not (yet?) used. Regardless, some - /// sort of limit must be applied to avoid unbounded memory growth. - StackExhausted, - /// A disallowed flag was found (e.g., `u`). - FlagNotAllowed(char), - /// A Unicode class was used when the Unicode (`u`) flag was disabled. - UnicodeNotAllowed, - /// InvalidUtf8 indicates that the expression may match non-UTF-8 bytes. - /// This never returned if the parser is permitted to allow expressions - /// that match arbitrary bytes. - InvalidUtf8, - /// A character class was constructed such that it is empty. - /// e.g., `[^\d\D]`. - EmptyClass, - /// Indicates that unsupported notation was used in a character class. - /// - /// The char in this error corresponds to the illegal character. - /// - /// The intent of this error is to carve a path to support set notation - /// as described in UTS#18 RL1.3. We do this by rejecting regexes that - /// would use the notation. - /// - /// The work around for end users is to escape the character included in - /// this error message. - UnsupportedClassChar(char), - /// Hints that destructuring should not be exhaustive. - /// - /// This enum may grow additional variants, so this makes sure clients - /// don't count on exhaustive matching. (Otherwise, adding a new variant - /// could break existing code.) - #[doc(hidden)] - __Nonexhaustive, -} - -impl Error { - /// Returns an approximate *character* offset at which the error occurred. - /// - /// The character offset may be equal to the number of characters in the - /// string, in which case it should be interpreted as pointing to the end - /// of the regex. - pub fn position(&self) -> usize { - self.pos - } - - /// Returns the type of the regex parse error. - pub fn kind(&self) -> &ErrorKind { - &self.kind - } -} - -impl ErrorKind { - fn description(&self) -> &str { - use ErrorKind::*; - match *self { - DoubleFlagNegation => "double flag negation", - DuplicateCaptureName(_) => "duplicate capture name", - EmptyAlternate => "empty alternate", - EmptyCaptureName => "empty capture name", - EmptyFlagNegation => "flag negation without any flags", - EmptyGroup => "empty group (e.g., '()')", - InvalidBase10(_) => "invalid base 10 number", - InvalidBase16(_) => "invalid base 16 number", - InvalidCaptureName(_) => "invalid capture name", - InvalidClassRange{..} => "invalid character class range", - InvalidClassEscape(_) => "invalid escape sequence in class", - InvalidRepeatRange{..} => "invalid counted repetition range", - InvalidScalarValue(_) => "invalid Unicode scalar value", - MissingBase10 => "missing count in repetition operator", - RepeaterExpectsExpr => "repetition operator missing expression", - RepeaterUnexpectedExpr(_) => "expression cannot be repeated", - UnclosedCaptureName(_) => "unclosed capture group name", - UnclosedHex => "unclosed hexadecimal literal", - UnclosedParen => "unclosed parenthesis", - UnclosedRepeat => "unclosed counted repetition operator", - UnclosedUnicodeName => "unclosed Unicode class literal", - UnexpectedClassEof => "unexpected EOF in character class", - UnexpectedEscapeEof => "unexpected EOF in escape sequence", - UnexpectedFlagEof => "unexpected EOF in flags", - UnexpectedTwoDigitHexEof => "unexpected EOF in hex literal", - UnopenedParen => "unopened parenthesis", - UnrecognizedEscape(_) => "unrecognized escape sequence", - UnrecognizedFlag(_) => "unrecognized flag", - UnrecognizedUnicodeClass(_) => "unrecognized Unicode class name", - StackExhausted => "stack exhausted, too much nesting", - FlagNotAllowed(_) => "flag not allowed", - UnicodeNotAllowed => "Unicode features not allowed", - InvalidUtf8 => "matching arbitrary bytes is not allowed", - EmptyClass => "empty character class", - UnsupportedClassChar(_) => "unsupported class notation", - __Nonexhaustive => unreachable!(), - } - } -} - -impl ::std::error::Error for Error { - fn description(&self) -> &str { - self.kind.description() - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if let ErrorKind::StackExhausted = self.kind { - write!(f, "Error parsing regex: {}", self.kind) - } else { - write!( - f, "Error parsing regex near '{}' at character offset {}: {}", - self.surround, self.pos, self.kind) - } - } -} - -impl fmt::Display for ErrorKind { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use ErrorKind::*; - match *self { - DoubleFlagNegation => - write!(f, "Only one negation symbol is allowed in flags."), - DuplicateCaptureName(ref s) => - write!(f, "Capture name '{}' is used more than once.", s), - EmptyAlternate => - write!(f, "Alternations cannot be empty."), - EmptyCaptureName => - write!(f, "Capture names cannot be empty."), - EmptyFlagNegation => - write!(f, "Flag negation requires setting at least one flag."), - EmptyGroup => - write!(f, "Empty regex groups (e.g., '()') are not allowed."), - InvalidBase10(ref s) => - write!(f, "Not a valid base 10 number: '{}'", s), - InvalidBase16(ref s) => - write!(f, "Not a valid base 16 number: '{}'", s), - InvalidCaptureName(ref s) => - write!(f, "Invalid capture name: '{}'. Capture names must \ - consist of [_a-zA-Z0-9] and are not allowed to \ - start with with a number.", s), - InvalidClassRange { start, end } => - write!(f, "Invalid character class range '{}-{}'. \ - Character class ranges must start with the smaller \ - character, but {} > {}", start, end, start, end), - InvalidClassEscape(_) => - write!(f, "Invalid escape sequence in character class."), - InvalidRepeatRange { min, max } => - write!(f, "Invalid counted repetition range: {{{}, {}}}. \ - Counted repetition ranges must start with the \ - minimum, but {} > {}", min, max, min, max), - InvalidScalarValue(c) => - write!(f, "Number does not correspond to a Unicode scalar \ - value: '{}'.", c), - MissingBase10 => - write!(f, "Missing maximum in counted repetition operator."), - RepeaterExpectsExpr => - write!(f, "Missing expression for repetition operator."), - RepeaterUnexpectedExpr(_) => - write!(f, "Invalid application of repetition operator."), - UnclosedCaptureName(ref s) => - write!(f, "Capture name group for '{}' is not closed. \ - (Missing a '>'.)", s), - UnclosedHex => - write!(f, "Unclosed hexadecimal literal (missing a '}}')."), - UnclosedParen => - write!(f, "Unclosed parenthesis."), - UnclosedRepeat => - write!(f, "Unclosed counted repetition (missing a '}}')."), - UnclosedUnicodeName => - write!(f, "Unclosed Unicode literal (missing a '}}')."), - UnexpectedClassEof => - write!(f, "Character class was not closed before the end of \ - the regex (missing a ']')."), - UnexpectedEscapeEof => - write!(f, "Started an escape sequence that didn't finish \ - before the end of the regex."), - UnexpectedFlagEof => - write!(f, "Inline flag settings was not closed before the end \ - of the regex (missing a ')' or ':')."), - UnexpectedTwoDigitHexEof => - write!(f, "Unexpected end of two digit hexadecimal literal."), - UnopenedParen => - write!(f, "Unopened parenthesis."), - UnrecognizedEscape(c) => - write!(f, "Unrecognized escape sequence: '\\{}'.", c), - UnrecognizedFlag(c) => - write!(f, "Unrecognized flag: '{}'. \ - (Allowed flags: i, m, s, U, u, x.)", c), - UnrecognizedUnicodeClass(ref s) => - write!(f, "Unrecognized Unicode class name: '{}'.", s), - StackExhausted => - write!(f, "Exhausted space required to parse regex with too \ - much nesting."), - FlagNotAllowed(flag) => - write!(f, "Use of the flag '{}' is not allowed.", flag), - UnicodeNotAllowed => - write!(f, "Unicode features are not allowed when the Unicode \ - (u) flag is not set."), - InvalidUtf8 => - write!(f, "Matching arbitrary bytes is not allowed."), - EmptyClass => - write!(f, "Empty character classes are not allowed."), - UnsupportedClassChar(c) => - write!(f, "Use of unescaped '{}' in character class is \ - not allowed.", c), - __Nonexhaustive => unreachable!(), - } - } -} - -/// The result of binary search on the simple case folding table. -/// -/// Note that this binary search is done on the "both" table, such that -/// the index returned corresponds to the *first* location of `c1` in the -/// table. The table can then be scanned linearly starting from the position -/// returned to find other case mappings for `c1`. -fn simple_case_fold_both_result(c1: char) -> result::Result<usize, usize> { - let table = &case_folding::C_plus_S_both_table; - let i = binary_search(table, |&(c2, _)| c1 <= c2); - if i >= table.len() || table[i].0 != c1 { - Err(i) - } else { - Ok(i) - } -} - -/// Binary search to find first element such that `pred(T) == true`. -/// -/// Assumes that if `pred(xs[i]) == true` then `pred(xs[i+1]) == true`. -/// -/// If all elements yield `pred(T) == false`, then `xs.len()` is returned. -fn binary_search<T, F>(xs: &[T], mut pred: F) -> usize - where F: FnMut(&T) -> bool { - let (mut left, mut right) = (0, xs.len()); - while left < right { - let mid = (left + right) / 2; - if pred(&xs[mid]) { - right = mid; - } else { - left = mid + 1; - } - } - left -} - -/// Escapes all regular expression meta characters in `text`. -/// -/// The string returned may be safely used as a literal in a regular -/// expression. -pub fn escape(text: &str) -> String { - let mut quoted = String::with_capacity(text.len()); - for c in text.chars() { - if parser::is_punct(c) { - quoted.push('\\'); - } - quoted.push(c); - } - quoted -} - -fn quote_char(c: char) -> String { - let mut s = String::new(); - if parser::is_punct(c) { - s.push('\\'); - } - s.push(c); - s -} - -fn quote_byte(b: u8) -> String { - if parser::is_punct(b as char) || b == b'\'' || b == b'"' { - quote_char(b as char) - } else { - let escaped: Vec<u8> = ascii::escape_default(b).collect(); - String::from_utf8(escaped).unwrap() - } -} - -fn inc_char(c: char) -> char { - match c { - char::MAX => char::MAX, - '\u{D7FF}' => '\u{E000}', - c => char::from_u32(c as u32 + 1).unwrap(), - } -} - -fn dec_char(c: char) -> char { - match c { - '\x00' => '\x00', - '\u{E000}' => '\u{D7FF}', - c => char::from_u32(c as u32 - 1).unwrap(), - } -} - -/// Returns true if and only if `c` is a word character. -#[doc(hidden)] -pub fn is_word_char(c: char) -> bool { - match c { - '_' | '0' ... '9' | 'a' ... 'z' | 'A' ... 'Z' => true, - _ => ::unicode::regex::PERLW.binary_search_by(|&(start, end)| { - if c >= start && c <= end { - Ordering::Equal - } else if start > c { - Ordering::Greater - } else { - Ordering::Less - } - }).is_ok(), - } -} - -/// Returns true if and only if `c` is an ASCII word byte. -#[doc(hidden)] -pub fn is_word_byte(b: u8) -> bool { - match b { - b'_' | b'0' ... b'9' | b'a' ... b'z' | b'A' ... b'Z' => true, - _ => false, - } -} - -#[cfg(test)] -mod properties; - -#[cfg(test)] -mod tests { - use {CharClass, ClassRange, ByteClass, ByteRange, Expr}; - - fn class(ranges: &[(char, char)]) -> CharClass { - let ranges = ranges.iter().cloned() - .map(|(c1, c2)| ClassRange::new(c1, c2)).collect(); - CharClass::new(ranges) - } - - fn bclass(ranges: &[(u8, u8)]) -> ByteClass { - let ranges = ranges.iter().cloned() - .map(|(c1, c2)| ByteRange::new(c1, c2)).collect(); - ByteClass::new(ranges) - } - - fn e(re: &str) -> Expr { Expr::parse(re).unwrap() } - - #[test] - fn stack_exhaustion() { - use std::iter::repeat; - - let open: String = repeat('(').take(200).collect(); - let close: String = repeat(')').take(200).collect(); - assert!(Expr::parse(&format!("{}a{}", open, close)).is_ok()); - - let open: String = repeat('(').take(200 + 1).collect(); - let close: String = repeat(')').take(200 + 1).collect(); - assert!(Expr::parse(&format!("{}a{}", open, close)).is_err()); - } - - #[test] - fn anchored_start() { - assert!(e("^a").is_anchored_start()); - assert!(e("(^a)").is_anchored_start()); - assert!(e("^a|^b").is_anchored_start()); - assert!(e("(^a)|(^b)").is_anchored_start()); - assert!(e("(^(a|b))").is_anchored_start()); - - assert!(!e("^a|b").is_anchored_start()); - assert!(!e("a|^b").is_anchored_start()); - } - - #[test] - fn anchored_end() { - assert!(e("a$").is_anchored_end()); - assert!(e("(a$)").is_anchored_end()); - assert!(e("a$|b$").is_anchored_end()); - assert!(e("(a$)|(b$)").is_anchored_end()); - assert!(e("((a|b)$)").is_anchored_end()); - - assert!(!e("a$|b").is_anchored_end()); - assert!(!e("a|b$").is_anchored_end()); - } - - #[test] - fn class_canon_no_change() { - let cls = class(&[('a', 'c'), ('x', 'z')]); - assert_eq!(cls.clone().canonicalize(), cls); - } - - #[test] - fn class_canon_unordered() { - let cls = class(&[('x', 'z'), ('a', 'c')]); - assert_eq!(cls.canonicalize(), class(&[ - ('a', 'c'), ('x', 'z'), - ])); - } - - #[test] - fn class_canon_overlap() { - let cls = class(&[('x', 'z'), ('w', 'y')]); - assert_eq!(cls.canonicalize(), class(&[ - ('w', 'z'), - ])); - } - - #[test] - fn class_canon_overlap_many() { - let cls = class(&[ - ('c', 'f'), ('a', 'g'), ('d', 'j'), ('a', 'c'), - ('m', 'p'), ('l', 's'), - ]); - assert_eq!(cls.clone().canonicalize(), class(&[ - ('a', 'j'), ('l', 's'), - ])); - } - - #[test] - fn class_canon_overlap_boundary() { - let cls = class(&[('x', 'z'), ('u', 'w')]); - assert_eq!(cls.canonicalize(), class(&[ - ('u', 'z'), - ])); - } - - #[test] - fn class_canon_extreme_edge_case() { - let cls = class(&[('\x00', '\u{10FFFF}'), ('\x00', '\u{10FFFF}')]); - assert_eq!(cls.canonicalize(), class(&[ - ('\x00', '\u{10FFFF}'), - ])); - } - - #[test] - fn class_canon_singles() { - let cls = class(&[('a', 'a'), ('b', 'b')]); - assert_eq!(cls.canonicalize(), class(&[('a', 'b')])); - } - - #[test] - fn class_negate_single() { - let cls = class(&[('a', 'a')]); - assert_eq!(cls.negate(), class(&[ - ('\x00', '\x60'), ('\x62', '\u{10FFFF}'), - ])); - } - - #[test] - fn class_negate_singles() { - let cls = class(&[('a', 'a'), ('b', 'b')]); - assert_eq!(cls.negate(), class(&[ - ('\x00', '\x60'), ('\x63', '\u{10FFFF}'), - ])); - } - - #[test] - fn class_negate_multiples() { - let cls = class(&[('a', 'c'), ('x', 'z')]); - assert_eq!(cls.negate(), class(&[ - ('\x00', '\x60'), ('\x64', '\x77'), ('\x7b', '\u{10FFFF}'), - ])); - } - - #[test] - fn class_negate_min_scalar() { - let cls = class(&[('\x00', 'a')]); - assert_eq!(cls.negate(), class(&[ - ('\x62', '\u{10FFFF}'), - ])); - } - - #[test] - fn class_negate_max_scalar() { - let cls = class(&[('a', '\u{10FFFF}')]); - assert_eq!(cls.negate(), class(&[ - ('\x00', '\x60'), - ])); - } - - #[test] - fn class_negate_everything() { - let cls = class(&[('\x00', '\u{10FFFF}')]); - assert_eq!(cls.negate(), class(&[])); - } - - #[test] - fn class_negate_everything_sans_one() { - let cls = class(&[ - ('\x00', '\u{10FFFD}'), ('\u{10FFFF}', '\u{10FFFF}') - ]); - assert_eq!(cls.negate(), class(&[ - ('\u{10FFFE}', '\u{10FFFE}'), - ])); - } - - #[test] - fn class_negate_surrogates_min() { - let cls = class(&[('\x00', '\u{D7FF}')]); - assert_eq!(cls.negate(), class(&[ - ('\u{E000}', '\u{10FFFF}'), - ])); - } - - #[test] - fn class_negate_surrogates_min_edge() { - let cls = class(&[('\x00', '\u{D7FE}')]); - assert_eq!(cls.negate(), class(&[ - ('\u{D7FF}', '\u{10FFFF}'), - ])); - } - - #[test] - fn class_negate_surrogates_max() { - let cls = class(&[('\u{E000}', '\u{10FFFF}')]); - assert_eq!(cls.negate(), class(&[ - ('\x00', '\u{D7FF}'), - ])); - } - - #[test] - fn class_negate_surrogates_max_edge() { - let cls = class(&[('\u{E001}', '\u{10FFFF}')]); - assert_eq!(cls.negate(), class(&[ - ('\x00', '\u{E000}'), - ])); - } - - #[test] - fn class_intersection_empty() { - let cls1 = class(&[]); - let cls2 = class(&[('a', 'a')]); - assert_intersection(cls1, cls2, class(&[])); - } - - #[test] - fn class_intersection_single_equal() { - let cls1 = class(&[('a', 'a')]); - let cls2 = class(&[('a', 'a')]); - assert_intersection(cls1, cls2, class(&[('a', 'a')])); - } - - #[test] - fn class_intersection_single_unequal() { - let cls1 = class(&[('a', 'a')]); - let cls2 = class(&[('b', 'b')]); - assert_intersection(cls1, cls2, class(&[])); - } - - #[test] - fn class_intersection_single_in_other() { - let cls1 = class(&[('a', 'a')]); - let cls2 = class(&[('a', 'c')]); - assert_intersection(cls1, cls2, class(&[('a', 'a')])); - } - - #[test] - fn class_intersection_range_in_other() { - let cls1 = class(&[('a', 'b')]); - let cls2 = class(&[('a', 'c')]); - assert_intersection(cls1, cls2, class(&[('a', 'b')])); - } - - #[test] - fn class_intersection_range_intersection() { - let cls1 = class(&[('a', 'b')]); - let cls2 = class(&[('b', 'c')]); - assert_intersection(cls1, cls2, class(&[('b', 'b')])); - } - - #[test] - fn class_intersection_only_adjacent() { - let cls1 = class(&[('a', 'b')]); - let cls2 = class(&[('c', 'd')]); - assert_intersection(cls1, cls2, class(&[])); - } - - #[test] - fn class_intersection_range_subset() { - let cls1 = class(&[('b', 'c')]); - let cls2 = class(&[('a', 'd')]); - assert_intersection(cls1, cls2, class(&[('b', 'c')])); - } - - #[test] - fn class_intersection_many_ranges_in_one_big() { - let cls1 = class(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); - let cls2 = class(&[('a', 'h')]); - assert_intersection(cls1, cls2, class(&[ - ('a', 'b'), ('d', 'e'), ('g', 'h') - ])); - } - - #[test] - fn class_intersection_many_ranges_same() { - let cls1 = class(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); - let cls2 = class(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); - assert_intersection(cls1, cls2, class(&[ - ('a', 'b'), ('d', 'e'), ('g', 'h') - ])); - } - - #[test] - fn class_intersection_multiple_non_intersecting() { - let cls1 = class(&[('a', 'b'), ('g', 'h')]); - let cls2 = class(&[('d', 'e'), ('k', 'l')]); - assert_intersection(cls1, cls2, class(&[])); - } - - #[test] - fn class_intersection_non_intersecting_then_intersecting() { - let cls1 = class(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); - let cls2 = class(&[('h', 'h')]); - assert_intersection(cls1, cls2, class(&[('h', 'h')])); - } - - #[test] - fn class_intersection_adjacent_alternating() { - let cls1 = class(&[('a', 'b'), ('e', 'f'), ('i', 'j')]); - let cls2 = class(&[('c', 'd'), ('g', 'h'), ('k', 'l')]); - assert_intersection(cls1, cls2, class(&[])); - } - - #[test] - fn class_intersection_overlapping_alternating() { - let cls1 = class(&[('a', 'b'), ('c', 'd'), ('e', 'f')]); - let cls2 = class(&[('b', 'c'), ('d', 'e'), ('f', 'g')]); - assert_intersection(cls1, cls2, class(&[('b', 'f')])); - } - - #[test] - fn class_canon_overlap_many_case_fold() { - let cls = class(&[ - ('C', 'F'), ('A', 'G'), ('D', 'J'), ('A', 'C'), - ('M', 'P'), ('L', 'S'), ('c', 'f'), - ]); - assert_eq!(cls.case_fold(), class(&[ - ('A', 'J'), ('L', 'S'), - ('a', 'j'), ('l', 's'), - ('\u{17F}', '\u{17F}'), - ])); - - let cls = bclass(&[ - (b'C', b'F'), (b'A', b'G'), (b'D', b'J'), (b'A', b'C'), - (b'M', b'P'), (b'L', b'S'), (b'c', b'f'), - ]); - assert_eq!(cls.case_fold(), bclass(&[ - (b'A', b'J'), (b'L', b'S'), - (b'a', b'j'), (b'l', b's'), - ])); - } - - #[test] - fn class_fold_az() { - let cls = class(&[('A', 'Z')]); - assert_eq!(cls.case_fold(), class(&[ - ('A', 'Z'), ('a', 'z'), - ('\u{17F}', '\u{17F}'), - ('\u{212A}', '\u{212A}'), - ])); - let cls = class(&[('a', 'z')]); - assert_eq!(cls.case_fold(), class(&[ - ('A', 'Z'), ('a', 'z'), - ('\u{17F}', '\u{17F}'), - ('\u{212A}', '\u{212A}'), - ])); - - let cls = bclass(&[(b'A', b'Z')]); - assert_eq!(cls.case_fold(), bclass(&[ - (b'A', b'Z'), (b'a', b'z'), - ])); - let cls = bclass(&[(b'a', b'z')]); - assert_eq!(cls.case_fold(), bclass(&[ - (b'A', b'Z'), (b'a', b'z'), - ])); - } - - #[test] - fn class_fold_a_underscore() { - let cls = class(&[('A', 'A'), ('_', '_')]); - assert_eq!(cls.clone().canonicalize(), class(&[ - ('A', 'A'), ('_', '_'), - ])); - assert_eq!(cls.case_fold(), class(&[ - ('A', 'A'), ('_', '_'), ('a', 'a'), - ])); - - let cls = bclass(&[(b'A', b'A'), (b'_', b'_')]); - assert_eq!(cls.clone().canonicalize(), bclass(&[ - (b'A', b'A'), (b'_', b'_'), - ])); - assert_eq!(cls.case_fold(), bclass(&[ - (b'A', b'A'), (b'_', b'_'), (b'a', b'a'), - ])); - } - - #[test] - fn class_fold_a_equals() { - let cls = class(&[('A', 'A'), ('=', '=')]); - assert_eq!(cls.clone().canonicalize(), class(&[ - ('=', '='), ('A', 'A'), - ])); - assert_eq!(cls.case_fold(), class(&[ - ('=', '='), ('A', 'A'), ('a', 'a'), - ])); - - let cls = bclass(&[(b'A', b'A'), (b'=', b'=')]); - assert_eq!(cls.clone().canonicalize(), bclass(&[ - (b'=', b'='), (b'A', b'A'), - ])); - assert_eq!(cls.case_fold(), bclass(&[ - (b'=', b'='), (b'A', b'A'), (b'a', b'a'), - ])); - } - - #[test] - fn class_fold_no_folding_needed() { - let cls = class(&[('\x00', '\x10')]); - assert_eq!(cls.case_fold(), class(&[ - ('\x00', '\x10'), - ])); - - let cls = bclass(&[(b'\x00', b'\x10')]); - assert_eq!(cls.case_fold(), bclass(&[ - (b'\x00', b'\x10'), - ])); - } - - #[test] - fn class_fold_negated() { - let cls = class(&[('x', 'x')]); - assert_eq!(cls.clone().case_fold(), class(&[ - ('X', 'X'), ('x', 'x'), - ])); - assert_eq!(cls.case_fold().negate(), class(&[ - ('\x00', 'W'), ('Y', 'w'), ('y', '\u{10FFFF}'), - ])); - - let cls = bclass(&[(b'x', b'x')]); - assert_eq!(cls.clone().case_fold(), bclass(&[ - (b'X', b'X'), (b'x', b'x'), - ])); - assert_eq!(cls.case_fold().negate(), bclass(&[ - (b'\x00', b'W'), (b'Y', b'w'), (b'y', b'\xff'), - ])); - } - - #[test] - fn class_fold_single_to_multiple() { - let cls = class(&[('k', 'k')]); - assert_eq!(cls.case_fold(), class(&[ - ('K', 'K'), ('k', 'k'), ('\u{212A}', '\u{212A}'), - ])); - - let cls = bclass(&[(b'k', b'k')]); - assert_eq!(cls.case_fold(), bclass(&[ - (b'K', b'K'), (b'k', b'k'), - ])); - } - - #[test] - fn class_fold_at() { - let cls = class(&[('@', '@')]); - assert_eq!(cls.clone().canonicalize(), class(&[('@', '@')])); - assert_eq!(cls.case_fold(), class(&[('@', '@')])); - - let cls = bclass(&[(b'@', b'@')]); - assert_eq!(cls.clone().canonicalize(), bclass(&[(b'@', b'@')])); - assert_eq!(cls.case_fold(), bclass(&[(b'@', b'@')])); - } - - #[test] - fn is_word_char() { - use super::is_word_char; - assert!(is_word_char('a'), "ASCII"); - assert!(is_word_char('à'), "Latin-1"); - assert!(is_word_char('\u{11011}'), "Brahmi (Unicode 6.0)"); - assert!(is_word_char('\u{11611}'), "Modi (Unicode 7.0)"); - assert!(is_word_char('\u{11711}'), "Ahom (Unicode 8.0)"); - assert!(is_word_char('\u{17828}'), "Tangut (Unicode 9.0)"); - assert!(is_word_char('\u{1B1B1}'), "Nushu (Unicode 10.0)"); - } - - #[test] - fn roundtrip_class_hypen() { - let expr = e("[-./]"); - assert_eq!("(?u:[-\\.-/])", expr.to_string()); - - let expr = e("(?-u)[-./]"); - assert_eq!("(?-u:[-\\.-/])", expr.to_string()); - } - - fn assert_intersection(cls1: CharClass, cls2: CharClass, expected: CharClass) { - // intersection operation should be commutative - assert_eq!(cls1.intersection(&cls2), expected); - assert_eq!(cls2.intersection(&cls1), expected); - } -} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.4.2/src/literals.rs cargo-0.26.0/vendor/regex-syntax-0.4.2/src/literals.rs --- cargo-0.25.0/vendor/regex-syntax-0.4.2/src/literals.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.4.2/src/literals.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1504 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::cmp; -use std::fmt; -use std::iter; -use std::mem; -use std::ops; - -use {Expr, CharClass, ClassRange, ByteClass, ByteRange, Repeater}; - -/// A set of literal byte strings extracted from a regular expression. -/// -/// Every member of the set is a `Lit`, which is represented by a `Vec<u8>`. -/// (Notably, it may contain invalid UTF-8.) Every member is said to be either -/// *complete* or *cut*. A complete literal means that it extends until the -/// beginning (or end) of the regular expression. In some circumstances, this -/// can be used to indicate a match in the regular expression. -/// -/// Note that a key aspect of literal extraction is knowing when to stop. It is -/// not feasible to blindly extract all literals from a regular expression, -/// even if there are finitely many. For example, the regular expression -/// `[0-9]{10}` has `10^10` distinct literals. For this reason, literal -/// extraction is bounded to some low number by default using heuristics, but -/// the limits can be tweaked. -#[derive(Clone, Eq, PartialEq)] -pub struct Literals { - lits: Vec<Lit>, - limit_size: usize, - limit_class: usize, -} - -/// A single member of a set of literals extracted from a regular expression. -/// -/// This type has `Deref` and `DerefMut` impls to `Vec<u8>` so that all slice -/// and `Vec` operations are available. -#[derive(Clone, Eq, Ord)] -pub struct Lit { - v: Vec<u8>, - cut: bool, -} - -impl Literals { - /// Returns a new empty set of literals using default limits. - pub fn empty() -> Literals { - Literals { - lits: vec![], - limit_size: 250, - limit_class: 10, - } - } - - /// Get the approximate size limit (in bytes) of this set. - pub fn limit_size(&self) -> usize { - self.limit_size - } - - /// Set the approximate size limit (in bytes) of this set. - /// - /// If extracting a literal would put the set over this limit, then - /// extraction stops. - /// - /// The new limits will only apply to additions to this set. Existing - /// members remain unchanged, even if the set exceeds the new limit. - pub fn set_limit_size(&mut self, size: usize) -> &mut Literals { - self.limit_size = size; - self - } - - /// Get the character class size limit for this set. - pub fn limit_class(&self) -> usize { - self.limit_class - } - - /// Limits the size of character(or byte) classes considered. - /// - /// A value of `0` prevents all character classes from being considered. - /// - /// This limit also applies to case insensitive literals, since each - /// character in the case insensitive literal is converted to a class, and - /// then case folded. - /// - /// The new limits will only apply to additions to this set. Existing - /// members remain unchanged, even if the set exceeds the new limit. - pub fn set_limit_class(&mut self, size: usize) -> &mut Literals { - self.limit_class = size; - self - } - - /// Returns the set of literals as a slice. Its order is unspecified. - pub fn literals(&self) -> &[Lit] { - &self.lits - } - - /// Returns the length of the smallest literal. - /// - /// Returns None is there are no literals in the set. - pub fn min_len(&self) -> Option<usize> { - let mut min = None; - for lit in &self.lits { - match min { - None => min = Some(lit.len()), - Some(m) if lit.len() < m => min = Some(lit.len()), - _ => {} - } - } - min - } - - /// Returns true if all members in this set are complete. - pub fn all_complete(&self) -> bool { - !self.lits.is_empty() && self.lits.iter().all(|l| !l.is_cut()) - } - - /// Returns true if any member in this set is complete. - pub fn any_complete(&self) -> bool { - self.lits.iter().any(|lit| !lit.is_cut()) - } - - /// Returns true if this set contains an empty literal. - pub fn contains_empty(&self) -> bool { - self.lits.iter().any(|lit| lit.is_empty()) - } - - /// Returns true if this set is empty or if all of its members is empty. - pub fn is_empty(&self) -> bool { - self.lits.is_empty() || self.lits.iter().all(|lit| lit.is_empty()) - } - - /// Returns a new empty set of literals using this set's limits. - pub fn to_empty(&self) -> Literals { - let mut lits = Literals::empty(); - lits.set_limit_size(self.limit_size) - .set_limit_class(self.limit_class); - lits - } - - /// Returns the longest common prefix of all members in this set. - pub fn longest_common_prefix(&self) -> &[u8] { - if self.is_empty() { - return &[]; - } - let lit0 = &*self.lits[0]; - let mut len = lit0.len(); - for lit in &self.lits[1..] { - len = cmp::min( - len, - lit.iter() - .zip(lit0) - .take_while(|&(a, b)| a == b) - .count()); - } - &self.lits[0][..len] - } - - /// Returns the longest common suffix of all members in this set. - pub fn longest_common_suffix(&self) -> &[u8] { - if self.is_empty() { - return &[]; - } - let lit0 = &*self.lits[0]; - let mut len = lit0.len(); - for lit in &self.lits[1..] { - len = cmp::min( - len, - lit.iter() - .rev() - .zip(lit0.iter().rev()) - .take_while(|&(a, b)| a == b) - .count()); - } - &self.lits[0][self.lits[0].len() - len..] - } - - /// Returns a new set of literals with the given number of bytes trimmed - /// from the suffix of each literal. - /// - /// If any literal would be cut out completely by trimming, then None is - /// returned. - /// - /// Any duplicates that are created as a result of this transformation are - /// removed. - pub fn trim_suffix(&self, num_bytes: usize) -> Option<Literals> { - if self.min_len().map(|len| len <= num_bytes).unwrap_or(true) { - return None; - } - let mut new = self.to_empty(); - for mut lit in self.lits.iter().cloned() { - let new_len = lit.len() - num_bytes; - lit.truncate(new_len); - lit.cut(); - new.lits.push(lit); - } - new.lits.sort(); - new.lits.dedup(); - Some(new) - } - - /// Returns a new set of prefixes of this set of literals that are - /// guaranteed to be unambiguous. - /// - /// Any substring match with a member of the set is returned is guaranteed - /// to never overlap with a substring match of another member of the set - /// at the same starting position. - /// - /// Given any two members of the returned set, neither is a substring of - /// the other. - pub fn unambiguous_prefixes(&self) -> Literals { - if self.lits.is_empty() { - return self.to_empty(); - } - let mut old: Vec<Lit> = self.lits.iter().cloned().collect(); - let mut new = self.to_empty(); - 'OUTER: - while let Some(mut candidate) = old.pop() { - if candidate.is_empty() { - continue; - } - if new.lits.is_empty() { - new.lits.push(candidate); - continue; - } - for lit2 in &mut new.lits { - if lit2.is_empty() { - continue; - } - if &candidate == lit2 { - // If the literal is already in the set, then we can - // just drop it. But make sure that cut literals are - // infectious! - candidate.cut = candidate.cut || lit2.cut; - lit2.cut = candidate.cut; - continue 'OUTER; - } - if candidate.len() < lit2.len() { - if let Some(i) = position(&candidate, &lit2) { - candidate.cut(); - let mut lit3 = lit2.clone(); - lit3.truncate(i); - lit3.cut(); - old.push(lit3); - lit2.clear(); - } - } else { - if let Some(i) = position(&lit2, &candidate) { - lit2.cut(); - let mut new_candidate = candidate.clone(); - new_candidate.truncate(i); - new_candidate.cut(); - old.push(new_candidate); - candidate.clear(); - } - } - // Oops, the candidate is already represented in the set. - if candidate.is_empty() { - continue 'OUTER; - } - } - new.lits.push(candidate); - } - new.lits.retain(|lit| !lit.is_empty()); - new.lits.sort(); - new.lits.dedup(); - new - } - - /// Returns a new set of suffixes of this set of literals that are - /// guaranteed to be unambiguous. - /// - /// Any substring match with a member of the set is returned is guaranteed - /// to never overlap with a substring match of another member of the set - /// at the same ending position. - /// - /// Given any two members of the returned set, neither is a substring of - /// the other. - pub fn unambiguous_suffixes(&self) -> Literals { - // This is a touch wasteful... - let mut lits = self.clone(); - lits.reverse(); - let mut unamb = lits.unambiguous_prefixes(); - unamb.reverse(); - unamb - } - - /// Unions the prefixes from the given expression to this set. - /// - /// If prefixes could not be added (for example, this set would exceed its - /// size limits or the set of prefixes from `expr` includes the empty - /// string), then false is returned. - /// - /// Note that prefix literals extracted from `expr` are said to be complete - /// if and only if the literal extends from the beginning of `expr` to the - /// end of `expr`. - pub fn union_prefixes(&mut self, expr: &Expr) -> bool { - let mut lits = self.to_empty(); - prefixes(expr, &mut lits); - !lits.is_empty() && !lits.contains_empty() && self.union(lits) - } - - /// Unions the suffixes from the given expression to this set. - /// - /// If suffixes could not be added (for example, this set would exceed its - /// size limits or the set of suffixes from `expr` includes the empty - /// string), then false is returned. - /// - /// Note that prefix literals extracted from `expr` are said to be complete - /// if and only if the literal extends from the end of `expr` to the - /// beginning of `expr`. - pub fn union_suffixes(&mut self, expr: &Expr) -> bool { - let mut lits = self.to_empty(); - suffixes(expr, &mut lits); - lits.reverse(); - !lits.is_empty() && !lits.contains_empty() && self.union(lits) - } - - /// Unions this set with another set. - /// - /// If the union would cause the set to exceed its limits, then the union - /// is skipped and it returns false. Otherwise, if the union succeeds, it - /// returns true. - pub fn union(&mut self, lits: Literals) -> bool { - if self.num_bytes() + lits.num_bytes() > self.limit_size { - return false; - } - if lits.is_empty() { - self.lits.push(Lit::empty()); - } else { - self.lits.extend(lits.lits); - } - true - } - - /// Extends this set with another set. - /// - /// The set of literals is extended via a cross product. - /// - /// If a cross product would cause this set to exceed its limits, then the - /// cross product is skipped and it returns false. Otherwise, if the cross - /// product succeeds, it returns true. - pub fn cross_product(&mut self, lits: &Literals) -> bool { - if lits.is_empty() { - return true; - } - // Check that we make sure we stay in our limits. - let mut size_after; - if self.is_empty() || !self.any_complete() { - size_after = self.num_bytes(); - for lits_lit in lits.literals() { - size_after += lits_lit.len(); - } - } else { - size_after = self.lits.iter().fold(0, |accum, lit| { - accum + if lit.is_cut() { lit.len() } else { 0 } - }); - for lits_lit in lits.literals() { - for self_lit in self.literals() { - if !self_lit.is_cut() { - size_after += self_lit.len() + lits_lit.len(); - } - } - } - } - if size_after > self.limit_size { - return false; - } - - let mut base = self.remove_complete(); - if base.is_empty() { - base = vec![Lit::empty()]; - } - for lits_lit in lits.literals() { - for mut self_lit in base.clone() { - self_lit.extend(&**lits_lit); - self_lit.cut = lits_lit.cut; - self.lits.push(self_lit); - } - } - true - } - - /// Extends each literal in this set with the bytes given. - /// - /// If the set is empty, then the given literal is added to the set. - /// - /// If adding any number of bytes to all members of this set causes a limit - /// to be exceeded, then no bytes are added and false is returned. If a - /// prefix of `bytes` can be fit into this set, then it is used and all - /// resulting literals are cut. - pub fn cross_add(&mut self, bytes: &[u8]) -> bool { - // N.B. This could be implemented by simply calling cross_product with - // a literal set containing just `bytes`, but we can be smarter about - // taking shorter prefixes of `bytes` if they'll fit. - if bytes.is_empty() { - return true; - } - if self.lits.is_empty() { - let i = cmp::min(self.limit_size, bytes.len()); - self.lits.push(Lit::new(bytes[..i].to_owned())); - self.lits[0].cut = i < bytes.len(); - return !self.lits[0].is_cut(); - } - let size = self.num_bytes(); - if size + self.lits.len() >= self.limit_size { - return false; - } - let mut i = 1; - while size + (i * self.lits.len()) <= self.limit_size - && i < bytes.len() { - i += 1; - } - for lit in &mut self.lits { - if !lit.is_cut() { - lit.extend(&bytes[..i]); - if i < bytes.len() { - lit.cut(); - } - } - } - true - } - - /// Adds the given literal to this set. - /// - /// Returns false if adding this literal would cause the class to be too - /// big. - pub fn add(&mut self, lit: Lit) -> bool { - if self.num_bytes() + lit.len() > self.limit_size { - return false; - } - self.lits.push(lit); - true - } - - /// Extends each literal in this set with the character class given. - /// - /// Returns false if the character class was too big to add. - pub fn add_char_class(&mut self, cls: &CharClass) -> bool { - self._add_char_class(cls, false) - } - - /// Extends each literal in this set with the character class given, - /// writing the bytes of each character in reverse. - /// - /// Returns false if the character class was too big to add. - fn add_char_class_reverse(&mut self, cls: &CharClass) -> bool { - self._add_char_class(cls, true) - } - - fn _add_char_class(&mut self, cls: &CharClass, reverse: bool) -> bool { - use std::char; - - if self.class_exceeds_limits(cls.num_chars()) { - return false; - } - let mut base = self.remove_complete(); - if base.is_empty() { - base = vec![Lit::empty()]; - } - for r in cls { - let (s, e) = (r.start as u32, r.end as u32 + 1); - for c in (s..e).filter_map(char::from_u32) { - for mut lit in base.clone() { - let mut bytes = c.to_string().into_bytes(); - if reverse { - bytes.reverse(); - } - lit.extend(&bytes); - self.lits.push(lit); - } - } - } - true - } - - /// Extends each literal in this set with the byte class given. - /// - /// Returns false if the byte class was too big to add. - pub fn add_byte_class(&mut self, cls: &ByteClass) -> bool { - if self.class_exceeds_limits(cls.num_bytes()) { - return false; - } - let mut base = self.remove_complete(); - if base.is_empty() { - base = vec![Lit::empty()]; - } - for r in cls { - let (s, e) = (r.start as u32, r.end as u32 + 1); - for b in (s..e).map(|b| b as u8) { - for mut lit in base.clone() { - lit.push(b); - self.lits.push(lit); - } - } - } - true - } - - /// Cuts every member of this set. When a member is cut, it can never - /// be extended. - pub fn cut(&mut self) { - for lit in &mut self.lits { - lit.cut(); - } - } - - /// Reverses all members in place. - pub fn reverse(&mut self) { - for lit in &mut self.lits { - lit.reverse(); - } - } - - /// Clears this set of all members. - pub fn clear(&mut self) { - self.lits.clear(); - } - - /// Pops all complete literals out of this set. - fn remove_complete(&mut self) -> Vec<Lit> { - let mut base = vec![]; - for lit in mem::replace(&mut self.lits, vec![]) { - if lit.is_cut() { - self.lits.push(lit); - } else { - base.push(lit); - } - } - base - } - - /// Returns the total number of bytes in this set. - fn num_bytes(&self) -> usize { - self.lits.iter().fold(0, |accum, lit| accum + lit.len()) - } - - /// Returns true if a character class with the given size would cause this - /// set to exceed its limits. - /// - /// The size given should correspond to the number of items in the class. - fn class_exceeds_limits(&self, size: usize) -> bool { - if size > self.limit_class { - return true; - } - // This is an approximation since codepoints in a char class can encode - // to 1-4 bytes. - let new_byte_count = - if self.lits.is_empty() { - size - } else { - self.lits - .iter() - .fold(0, |accum, lit| { - accum + if lit.is_cut() { - // If the literal is cut, then we'll never add - // anything to it, so don't count it. - 0 - } else { - (lit.len() + 1) * size - } - }) - }; - new_byte_count > self.limit_size - } -} - -fn prefixes(expr: &Expr, lits: &mut Literals) { - use Expr::*; - match *expr { - Literal { ref chars, casei: false } => { - let s: String = chars.iter().cloned().collect(); - lits.cross_add(s.as_bytes()); - } - Literal { ref chars, casei: true } => { - for &c in chars { - let cls = CharClass::new(vec![ - ClassRange { start: c, end: c }, - ]).case_fold(); - if !lits.add_char_class(&cls) { - lits.cut(); - return; - } - } - } - LiteralBytes { ref bytes, casei: false } => { - lits.cross_add(bytes); - } - LiteralBytes { ref bytes, casei: true } => { - for &b in bytes { - let cls = ByteClass::new(vec![ - ByteRange { start: b, end: b }, - ]).case_fold(); - if !lits.add_byte_class(&cls) { - lits.cut(); - return; - } - } - } - Class(ref cls) => { - if !lits.add_char_class(cls) { - lits.cut(); - } - } - ClassBytes(ref cls) => { - if !lits.add_byte_class(cls) { - lits.cut(); - } - } - Group { ref e, .. } => { - prefixes(&**e, lits); - } - Repeat { ref e, r: Repeater::ZeroOrOne, .. } => { - repeat_zero_or_one_literals(&**e, lits, prefixes); - } - Repeat { ref e, r: Repeater::ZeroOrMore, .. } => { - repeat_zero_or_more_literals(&**e, lits, prefixes); - } - Repeat { ref e, r: Repeater::OneOrMore, .. } => { - repeat_one_or_more_literals(&**e, lits, prefixes); - } - Repeat { ref e, r: Repeater::Range { min, max }, greedy } => { - repeat_range_literals(&**e, min, max, greedy, lits, prefixes); - } - Concat(ref es) if es.is_empty() => {} - Concat(ref es) if es.len() == 1 => prefixes(&es[0], lits), - Concat(ref es) => { - for e in es { - if let StartText = *e { - if !lits.is_empty() { - lits.cut(); - break; - } - lits.add(Lit::empty()); - continue; - } - let mut lits2 = lits.to_empty(); - prefixes(e, &mut lits2); - if !lits.cross_product(&lits2) || !lits2.any_complete() { - // If this expression couldn't yield any literal that - // could be extended, then we need to quit. Since we're - // short-circuiting, we also need to freeze every member. - lits.cut(); - break; - } - } - } - Alternate(ref es) => { - alternate_literals(es, lits, prefixes); - } - _ => lits.cut(), - } -} - -fn suffixes(expr: &Expr, lits: &mut Literals) { - use Expr::*; - match *expr { - Literal { ref chars, casei: false } => { - let s: String = chars.iter().cloned().collect(); - let mut bytes = s.into_bytes(); - bytes.reverse(); - lits.cross_add(&bytes); - } - Literal { ref chars, casei: true } => { - for &c in chars.iter().rev() { - let cls = CharClass::new(vec![ - ClassRange { start: c, end: c }, - ]).case_fold(); - if !lits.add_char_class_reverse(&cls) { - lits.cut(); - return; - } - } - } - LiteralBytes { ref bytes, casei: false } => { - let b: Vec<u8> = bytes.iter().rev().cloned().collect(); - lits.cross_add(&b); - } - LiteralBytes { ref bytes, casei: true } => { - for &b in bytes.iter().rev() { - let cls = ByteClass::new(vec![ - ByteRange { start: b, end: b }, - ]).case_fold(); - if !lits.add_byte_class(&cls) { - lits.cut(); - return; - } - } - } - Class(ref cls) => { - if !lits.add_char_class_reverse(cls) { - lits.cut(); - } - } - ClassBytes(ref cls) => { - if !lits.add_byte_class(cls) { - lits.cut(); - } - } - Group { ref e, .. } => { - suffixes(&**e, lits); - } - Repeat { ref e, r: Repeater::ZeroOrOne, .. } => { - repeat_zero_or_one_literals(&**e, lits, suffixes); - } - Repeat { ref e, r: Repeater::ZeroOrMore, .. } => { - repeat_zero_or_more_literals(&**e, lits, suffixes); - } - Repeat { ref e, r: Repeater::OneOrMore, .. } => { - repeat_one_or_more_literals(&**e, lits, suffixes); - } - Repeat { ref e, r: Repeater::Range { min, max }, greedy } => { - repeat_range_literals(&**e, min, max, greedy, lits, suffixes); - } - Concat(ref es) if es.is_empty() => {} - Concat(ref es) if es.len() == 1 => suffixes(&es[0], lits), - Concat(ref es) => { - for e in es.iter().rev() { - if let EndText = *e { - if !lits.is_empty() { - lits.cut(); - break; - } - lits.add(Lit::empty()); - continue; - } - let mut lits2 = lits.to_empty(); - suffixes(e, &mut lits2); - if !lits.cross_product(&lits2) || !lits2.any_complete() { - // If this expression couldn't yield any literal that - // could be extended, then we need to quit. Since we're - // short-circuiting, we also need to freeze every member. - lits.cut(); - break; - } - } - } - Alternate(ref es) => { - alternate_literals(es, lits, suffixes); - } - _ => lits.cut(), - } -} - -fn repeat_zero_or_one_literals<F: FnMut(&Expr, &mut Literals)>( - e: &Expr, - lits: &mut Literals, - mut f: F, -) { - let (mut lits2, mut lits3) = (lits.clone(), lits.to_empty()); - lits3.set_limit_size(lits.limit_size() / 2); - f(e, &mut lits3); - - if lits3.is_empty() || !lits2.cross_product(&lits3) { - lits.cut(); - return; - } - lits2.add(Lit::empty()); - if !lits.union(lits2) { - lits.cut(); - } -} - -fn repeat_zero_or_more_literals<F: FnMut(&Expr, &mut Literals)>( - e: &Expr, - lits: &mut Literals, - mut f: F, -) { - let (mut lits2, mut lits3) = (lits.clone(), lits.to_empty()); - lits3.set_limit_size(lits.limit_size() / 2); - f(e, &mut lits3); - - if lits3.is_empty() || !lits2.cross_product(&lits3) { - lits.cut(); - return; - } - lits2.cut(); - lits2.add(Lit::empty()); - if !lits.union(lits2) { - lits.cut(); - } -} - -fn repeat_one_or_more_literals<F: FnMut(&Expr, &mut Literals)>( - e: &Expr, - lits: &mut Literals, - mut f: F, -) { - f(e, lits); - lits.cut(); -} - -fn repeat_range_literals<F: FnMut(&Expr, &mut Literals)>( - e: &Expr, - min: u32, - max: Option<u32>, - greedy: bool, - lits: &mut Literals, - mut f: F, -) { - use Expr::*; - - if min == 0 { - // This is a bit conservative. If `max` is set, then we could - // treat this as a finite set of alternations. For now, we - // just treat it as `e*`. - f(&Repeat { - e: Box::new(e.clone()), - r: Repeater::ZeroOrMore, - greedy: greedy, - }, lits); - } else { - if min > 0 { - let n = cmp::min(lits.limit_size, min as usize); - let es = iter::repeat(e.clone()).take(n).collect(); - f(&Concat(es), lits); - if n < min as usize || lits.contains_empty() { - lits.cut(); - } - } - if max.map_or(true, |max| min < max) { - lits.cut(); - } - } -} - -fn alternate_literals<F: FnMut(&Expr, &mut Literals)>( - es: &[Expr], - lits: &mut Literals, - mut f: F, -) { - let mut lits2 = lits.to_empty(); - for e in es { - let mut lits3 = lits.to_empty(); - lits3.set_limit_size(lits.limit_size() / 5); - f(e, &mut lits3); - if lits3.is_empty() || !lits2.union(lits3) { - // If we couldn't find suffixes for *any* of the - // alternates, then the entire alternation has to be thrown - // away and any existing members must be frozen. Similarly, - // if the union couldn't complete, stop and freeze. - lits.cut(); - return; - } - } - if !lits.cross_product(&lits2) { - lits.cut(); - } -} - -impl fmt::Debug for Literals { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("Literals") - .field("lits", &self.lits) - .field("limit_size", &self.limit_size) - .field("limit_class", &self.limit_class) - .finish() - } -} - -impl Lit { - /// Returns a new complete literal with the bytes given. - pub fn new(bytes: Vec<u8>) -> Lit { - Lit { v: bytes, cut: false } - } - - /// Returns a new complete empty literal. - pub fn empty() -> Lit { - Lit { v: vec![], cut: false } - } - - /// Returns true if this literal was "cut." - pub fn is_cut(&self) -> bool { - self.cut - } - - /// Cuts this literal. - pub fn cut(&mut self) { - self.cut = true; - } -} - -impl PartialEq for Lit { - fn eq(&self, other: &Lit) -> bool { - self.v == other.v - } -} - -impl PartialOrd for Lit { - fn partial_cmp(&self, other: &Lit) -> Option<cmp::Ordering> { - self.v.partial_cmp(&other.v) - } -} - -impl fmt::Debug for Lit { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if self.is_cut() { - write!(f, "Cut({})", escape_unicode(&self.v)) - } else { - write!(f, "Complete({})", escape_unicode(&self.v)) - } - } -} - -impl AsRef<[u8]> for Lit { - fn as_ref(&self) -> &[u8] { &self.v } -} - -impl ops::Deref for Lit { - type Target = Vec<u8>; - fn deref(&self) -> &Vec<u8> { &self.v } -} - -impl ops::DerefMut for Lit { - fn deref_mut(&mut self) -> &mut Vec<u8> { &mut self.v } -} - -fn position(needle: &[u8], mut haystack: &[u8]) -> Option<usize> { - let mut i = 0; - while haystack.len() >= needle.len() { - if needle == &haystack[..needle.len()] { - return Some(i); - } - i += 1; - haystack = &haystack[1..]; - } - None -} - -fn escape_unicode(bytes: &[u8]) -> String { - let show = match ::std::str::from_utf8(bytes) { - Ok(v) => v.to_string(), - Err(_) => escape_bytes(bytes), - }; - let mut space_escaped = String::new(); - for c in show.chars() { - if c.is_whitespace() { - let escaped = if c as u32 <= 0x7F { - escape_byte(c as u8) - } else { - if c as u32 <= 0xFFFF { - format!(r"\u{{{:04x}}}", c as u32) - } else { - format!(r"\U{{{:08x}}}", c as u32) - } - }; - space_escaped.push_str(&escaped); - } else { - space_escaped.push(c); - } - } - space_escaped -} - -fn escape_bytes(bytes: &[u8]) -> String { - let mut s = String::new(); - for &b in bytes { - s.push_str(&escape_byte(b)); - } - s -} - -fn escape_byte(byte: u8) -> String { - use std::ascii::escape_default; - - let escaped: Vec<u8> = escape_default(byte).collect(); - String::from_utf8_lossy(&escaped).into_owned() -} - -#[cfg(test)] -mod tests { - use std::fmt; - - use {Expr, ExprBuilder}; - use super::{Literals, Lit, escape_bytes}; - - // To make test failures easier to read. - #[derive(Debug, Eq, PartialEq)] - struct Bytes(Vec<ULit>); - #[derive(Debug, Eq, PartialEq)] - struct Unicode(Vec<ULit>); - - fn escape_lits(blits: &[Lit]) -> Vec<ULit> { - let mut ulits = vec![]; - for blit in blits { - ulits.push(ULit { v: escape_bytes(&blit), cut: blit.is_cut() }); - } - ulits - } - - fn create_lits<I: IntoIterator<Item=Lit>>(it: I) -> Literals { - Literals { - lits: it.into_iter().collect(), - limit_size: 0, - limit_class: 0, - } - } - - // Needs to be pub for 1.3? - #[derive(Clone, Eq, PartialEq)] - pub struct ULit { - v: String, - cut: bool, - } - - impl ULit { - fn is_cut(&self) -> bool { self.cut } - } - - impl fmt::Debug for ULit { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if self.is_cut() { - write!(f, "Cut({})", self.v) - } else { - write!(f, "Complete({})", self.v) - } - } - } - - impl PartialEq<Lit> for ULit { - fn eq(&self, other: &Lit) -> bool { - self.v.as_bytes() == &*other.v && self.is_cut() == other.is_cut() - } - } - - impl PartialEq<ULit> for Lit { - fn eq(&self, other: &ULit) -> bool { - &*self.v == other.v.as_bytes() && self.is_cut() == other.is_cut() - } - } - - #[allow(non_snake_case)] - fn C(s: &'static str) -> ULit { ULit { v: s.to_owned(), cut: true } } - #[allow(non_snake_case)] - fn M(s: &'static str) -> ULit { ULit { v: s.to_owned(), cut: false } } - - fn prefixes(lits: &mut Literals, expr: &Expr) { - lits.union_prefixes(expr); - } - - fn suffixes(lits: &mut Literals, expr: &Expr) { - lits.union_suffixes(expr); - } - - macro_rules! assert_lit_eq { - ($which:ident, $got_lits:expr, $($expected_lit:expr),*) => {{ - let expected: Vec<ULit> = vec![$($expected_lit),*]; - let lits = $got_lits; - assert_eq!( - $which(expected.clone()), - $which(escape_lits(lits.literals()))); - assert_eq!( - !expected.is_empty() && expected.iter().all(|l| !l.is_cut()), - lits.all_complete()); - assert_eq!( - expected.iter().any(|l| !l.is_cut()), - lits.any_complete()); - }}; - } - - macro_rules! test_lit { - ($name:ident, $which:ident, $re:expr) => { - test_lit!($name, $which, $re,); - }; - ($name:ident, $which:ident, $re:expr, $($lit:expr),*) => { - #[test] - fn $name() { - let expr = Expr::parse($re).unwrap(); - let lits = expr.$which(); - assert_lit_eq!(Unicode, lits, $($lit),*); - - let expr = ExprBuilder::new().allow_bytes(true).unicode(false) - .parse($re).unwrap(); - let lits = expr.$which(); - assert_lit_eq!(Bytes, lits, $($lit),*); - } - }; - } - - // ************************************************************************ - // Tests for prefix literal extraction. - // ************************************************************************ - - // Elementary tests. - test_lit!(pfx_one_lit1, prefixes, "a", M("a")); - test_lit!(pfx_one_lit2, prefixes, "abc", M("abc")); - test_lit!(pfx_one_lit3, prefixes, "(?u)☃", M("\\xe2\\x98\\x83")); - test_lit!(pfx_one_lit4, prefixes, "(?ui)☃", M("\\xe2\\x98\\x83")); - test_lit!(pfx_class1, prefixes, "[1-4]", - M("1"), M("2"), M("3"), M("4")); - test_lit!(pfx_class2, prefixes, "(?u)[☃Ⅰ]", - M("\\xe2\\x85\\xa0"), M("\\xe2\\x98\\x83")); - test_lit!(pfx_class3, prefixes, "(?ui)[☃Ⅰ]", - M("\\xe2\\x85\\xa0"), M("\\xe2\\x85\\xb0"), - M("\\xe2\\x98\\x83")); - test_lit!(pfx_one_lit_casei1, prefixes, "(?i)a", - M("A"), M("a")); - test_lit!(pfx_one_lit_casei2, prefixes, "(?i)abc", - M("ABC"), M("aBC"), M("AbC"), M("abC"), - M("ABc"), M("aBc"), M("Abc"), M("abc")); - test_lit!(pfx_group1, prefixes, "(a)", M("a")); - test_lit!(pfx_rep_zero_or_one1, prefixes, "a?"); - test_lit!(pfx_rep_zero_or_one2, prefixes, "(?:abc)?"); - test_lit!(pfx_rep_zero_or_more1, prefixes, "a*"); - test_lit!(pfx_rep_zero_or_more2, prefixes, "(?:abc)*"); - test_lit!(pfx_rep_one_or_more1, prefixes, "a+", C("a")); - test_lit!(pfx_rep_one_or_more2, prefixes, "(?:abc)+", C("abc")); - test_lit!(pfx_rep_nested_one_or_more, prefixes, "(?:a+)+", C("a")); - test_lit!(pfx_rep_range1, prefixes, "a{0}"); - test_lit!(pfx_rep_range2, prefixes, "a{0,}"); - test_lit!(pfx_rep_range3, prefixes, "a{0,1}"); - test_lit!(pfx_rep_range4, prefixes, "a{1}", M("a")); - test_lit!(pfx_rep_range5, prefixes, "a{2}", M("aa")); - test_lit!(pfx_rep_range6, prefixes, "a{1,2}", C("a")); - test_lit!(pfx_rep_range7, prefixes, "a{2,3}", C("aa")); - - // Test regexes with concatenations. - test_lit!(pfx_cat1, prefixes, "(?:a)(?:b)", M("ab")); - test_lit!(pfx_cat2, prefixes, "[ab]z", M("az"), M("bz")); - test_lit!(pfx_cat3, prefixes, "(?i)[ab]z", - M("AZ"), M("BZ"), M("aZ"), M("bZ"), - M("Az"), M("Bz"), M("az"), M("bz")); - test_lit!(pfx_cat4, prefixes, "[ab][yz]", - M("ay"), M("by"), M("az"), M("bz")); - test_lit!(pfx_cat5, prefixes, "a*b", C("a"), M("b")); - test_lit!(pfx_cat6, prefixes, "a*b*c", C("a"), C("b"), M("c")); - test_lit!(pfx_cat7, prefixes, "a*b*c+", C("a"), C("b"), C("c")); - test_lit!(pfx_cat8, prefixes, "a*b+c", C("a"), C("b")); - test_lit!(pfx_cat9, prefixes, "a*b+c*", C("a"), C("b")); - test_lit!(pfx_cat10, prefixes, "ab*", C("ab"), M("a")); - test_lit!(pfx_cat11, prefixes, "ab*c", C("ab"), M("ac")); - test_lit!(pfx_cat12, prefixes, "ab+", C("ab")); - test_lit!(pfx_cat13, prefixes, "ab+c", C("ab")); - test_lit!(pfx_cat14, prefixes, "a^", C("a")); - test_lit!(pfx_cat15, prefixes, "$a"); - test_lit!(pfx_cat16, prefixes, r"ab*c", C("ab"), M("ac")); - test_lit!(pfx_cat17, prefixes, r"ab+c", C("ab")); - test_lit!(pfx_cat18, prefixes, r"z*azb", C("z"), M("azb")); - test_lit!(pfx_cat19, prefixes, "a.z", C("a")); - - // Test regexes with alternations. - test_lit!(pfx_alt1, prefixes, "a|b", M("a"), M("b")); - test_lit!(pfx_alt2, prefixes, "[1-3]|b", M("1"), M("2"), M("3"), M("b")); - test_lit!(pfx_alt3, prefixes, "y(?:a|b)z", M("yaz"), M("ybz")); - test_lit!(pfx_alt4, prefixes, "a|b*"); - test_lit!(pfx_alt5, prefixes, "a|b+", M("a"), C("b")); - test_lit!(pfx_alt6, prefixes, "a|(?:b|c*)"); - test_lit!(pfx_alt7, prefixes, "(a|b)*c|(a|ab)*c", - C("a"), C("b"), M("c"), C("a"), C("ab"), M("c")); - test_lit!(pfx_alt8, prefixes, "a*b|c", C("a"), M("b"), M("c")); - - // Test regexes with empty assertions. - test_lit!(pfx_empty1, prefixes, "^a", M("a")); - test_lit!(pfx_empty2, prefixes, "a${2}", C("a")); - test_lit!(pfx_empty3, prefixes, "^abc", M("abc")); - test_lit!(pfx_empty4, prefixes, "(?:^abc)|(?:^z)", M("abc"), M("z")); - - // Make sure some curious regexes have no prefixes. - test_lit!(pfx_nothing1, prefixes, "."); - test_lit!(pfx_nothing2, prefixes, "(?s)."); - test_lit!(pfx_nothing3, prefixes, "^"); - test_lit!(pfx_nothing4, prefixes, "$"); - test_lit!(pfx_nothing6, prefixes, "(?m)$"); - test_lit!(pfx_nothing7, prefixes, r"\b"); - test_lit!(pfx_nothing8, prefixes, r"\B"); - - // Test a few regexes that defeat any prefix literal detection. - test_lit!(pfx_defeated1, prefixes, ".a"); - test_lit!(pfx_defeated2, prefixes, "(?s).a"); - test_lit!(pfx_defeated3, prefixes, "a*b*c*"); - test_lit!(pfx_defeated4, prefixes, "a|."); - test_lit!(pfx_defeated5, prefixes, ".|a"); - test_lit!(pfx_defeated6, prefixes, "a|^"); - test_lit!(pfx_defeated7, prefixes, ".(?:a(?:b)(?:c))"); - test_lit!(pfx_defeated8, prefixes, "$a"); - test_lit!(pfx_defeated9, prefixes, "(?m)$a"); - test_lit!(pfx_defeated10, prefixes, r"\ba"); - test_lit!(pfx_defeated11, prefixes, r"\Ba"); - test_lit!(pfx_defeated12, prefixes, "^*a"); - test_lit!(pfx_defeated13, prefixes, "^+a"); - - test_lit!( - pfx_crazy1, - prefixes, - r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", - C("Mo\\'am"), C("Mu\\'am"), C("Moam"), C("Muam")); - - // ************************************************************************ - // Tests for quiting prefix literal search. - // ************************************************************************ - - macro_rules! test_exhausted { - ($name:ident, $which:ident, $re:expr) => { - test_exhausted!($name, $which, $re,); - }; - ($name:ident, $which:ident, $re:expr, $($lit:expr),*) => { - #[test] - fn $name() { - let expr = Expr::parse($re).unwrap(); - let mut lits = Literals::empty(); - lits.set_limit_size(20).set_limit_class(10); - $which(&mut lits, &expr); - assert_lit_eq!(Unicode, lits, $($lit),*); - - let expr = ExprBuilder::new().allow_bytes(true).unicode(false) - .parse($re).unwrap(); - let mut lits = Literals::empty(); - lits.set_limit_size(20).set_limit_class(10); - $which(&mut lits, &expr); - assert_lit_eq!(Bytes, lits, $($lit),*); - } - }; - } - - // These test use a much lower limit than the default so that we can - // write test cases of reasonable size. - test_exhausted!(pfx_exhausted1, prefixes, "[a-z]"); - test_exhausted!(pfx_exhausted2, prefixes, "[a-z]*A"); - test_exhausted!(pfx_exhausted3, prefixes, "A[a-z]Z", C("A")); - test_exhausted!(pfx_exhausted4, prefixes, "(?i)foobar", - C("FO"), C("fO"), C("Fo"), C("fo")); - test_exhausted!(pfx_exhausted5, prefixes, "(?:ab){100}", - C("abababababababababab")); - test_exhausted!(pfx_exhausted6, prefixes, "(?:(?:ab){100})*cd", - C("ababababab"), M("cd")); - test_exhausted!(pfx_exhausted7, prefixes, "z(?:(?:ab){100})*cd", - C("zababababab"), M("zcd")); - test_exhausted!(pfx_exhausted8, prefixes, "aaaaaaaaaaaaaaaaaaaaz", - C("aaaaaaaaaaaaaaaaaaaa")); - - // ************************************************************************ - // Tests for suffix literal extraction. - // ************************************************************************ - - // Elementary tests. - test_lit!(sfx_one_lit1, suffixes, "a", M("a")); - test_lit!(sfx_one_lit2, suffixes, "abc", M("abc")); - test_lit!(sfx_one_lit3, suffixes, "(?u)☃", M("\\xe2\\x98\\x83")); - test_lit!(sfx_one_lit4, suffixes, "(?ui)☃", M("\\xe2\\x98\\x83")); - test_lit!(sfx_class1, suffixes, "[1-4]", - M("1"), M("2"), M("3"), M("4")); - test_lit!(sfx_class2, suffixes, "(?u)[☃Ⅰ]", - M("\\xe2\\x85\\xa0"), M("\\xe2\\x98\\x83")); - test_lit!(sfx_class3, suffixes, "(?ui)[☃Ⅰ]", - M("\\xe2\\x85\\xa0"), M("\\xe2\\x85\\xb0"), - M("\\xe2\\x98\\x83")); - test_lit!(sfx_one_lit_casei1, suffixes, "(?i)a", - M("A"), M("a")); - test_lit!(sfx_one_lit_casei2, suffixes, "(?i)abc", - M("ABC"), M("ABc"), M("AbC"), M("Abc"), - M("aBC"), M("aBc"), M("abC"), M("abc")); - test_lit!(sfx_group1, suffixes, "(a)", M("a")); - test_lit!(sfx_rep_zero_or_one1, suffixes, "a?"); - test_lit!(sfx_rep_zero_or_one2, suffixes, "(?:abc)?"); - test_lit!(sfx_rep_zero_or_more1, suffixes, "a*"); - test_lit!(sfx_rep_zero_or_more2, suffixes, "(?:abc)*"); - test_lit!(sfx_rep_one_or_more1, suffixes, "a+", C("a")); - test_lit!(sfx_rep_one_or_more2, suffixes, "(?:abc)+", C("abc")); - test_lit!(sfx_rep_nested_one_or_more, suffixes, "(?:a+)+", C("a")); - test_lit!(sfx_rep_range1, suffixes, "a{0}"); - test_lit!(sfx_rep_range2, suffixes, "a{0,}"); - test_lit!(sfx_rep_range3, suffixes, "a{0,1}"); - test_lit!(sfx_rep_range4, suffixes, "a{1}", M("a")); - test_lit!(sfx_rep_range5, suffixes, "a{2}", M("aa")); - test_lit!(sfx_rep_range6, suffixes, "a{1,2}", C("a")); - test_lit!(sfx_rep_range7, suffixes, "a{2,3}", C("aa")); - - // Test regexes with concatenations. - test_lit!(sfx_cat1, suffixes, "(?:a)(?:b)", M("ab")); - test_lit!(sfx_cat2, suffixes, "[ab]z", M("az"), M("bz")); - test_lit!(sfx_cat3, suffixes, "(?i)[ab]z", - M("AZ"), M("Az"), M("BZ"), M("Bz"), - M("aZ"), M("az"), M("bZ"), M("bz")); - test_lit!(sfx_cat4, suffixes, "[ab][yz]", - M("ay"), M("az"), M("by"), M("bz")); - test_lit!(sfx_cat5, suffixes, "a*b", C("ab"), M("b")); - test_lit!(sfx_cat6, suffixes, "a*b*c", C("bc"), C("ac"), M("c")); - test_lit!(sfx_cat7, suffixes, "a*b*c+", C("c")); - test_lit!(sfx_cat8, suffixes, "a*b+c", C("bc")); - test_lit!(sfx_cat9, suffixes, "a*b+c*", C("c"), C("b")); - test_lit!(sfx_cat10, suffixes, "ab*", C("b"), M("a")); - test_lit!(sfx_cat11, suffixes, "ab*c", C("bc"), M("ac")); - test_lit!(sfx_cat12, suffixes, "ab+", C("b")); - test_lit!(sfx_cat13, suffixes, "ab+c", C("bc")); - test_lit!(sfx_cat14, suffixes, "a^"); - test_lit!(sfx_cat15, suffixes, "$a", C("a")); - test_lit!(sfx_cat16, suffixes, r"ab*c", C("bc"), M("ac")); - test_lit!(sfx_cat17, suffixes, r"ab+c", C("bc")); - test_lit!(sfx_cat18, suffixes, r"z*azb", C("zazb"), M("azb")); - test_lit!(sfx_cat19, suffixes, "a.z", C("z")); - - // Test regexes with alternations. - test_lit!(sfx_alt1, suffixes, "a|b", M("a"), M("b")); - test_lit!(sfx_alt2, suffixes, "[1-3]|b", M("1"), M("2"), M("3"), M("b")); - test_lit!(sfx_alt3, suffixes, "y(?:a|b)z", M("yaz"), M("ybz")); - test_lit!(sfx_alt4, suffixes, "a|b*"); - test_lit!(sfx_alt5, suffixes, "a|b+", M("a"), C("b")); - test_lit!(sfx_alt6, suffixes, "a|(?:b|c*)"); - test_lit!(sfx_alt7, suffixes, "(a|b)*c|(a|ab)*c", - C("ac"), C("bc"), M("c"), C("ac"), C("abc"), M("c")); - test_lit!(sfx_alt8, suffixes, "a*b|c", C("ab"), M("b"), M("c")); - - // Test regexes with empty assertions. - test_lit!(sfx_empty1, suffixes, "a$", M("a")); - test_lit!(sfx_empty2, suffixes, "${2}a", C("a")); - - // Make sure some curious regexes have no suffixes. - test_lit!(sfx_nothing1, suffixes, "."); - test_lit!(sfx_nothing2, suffixes, "(?s)."); - test_lit!(sfx_nothing3, suffixes, "^"); - test_lit!(sfx_nothing4, suffixes, "$"); - test_lit!(sfx_nothing6, suffixes, "(?m)$"); - test_lit!(sfx_nothing7, suffixes, r"\b"); - test_lit!(sfx_nothing8, suffixes, r"\B"); - - // Test a few regexes that defeat any suffix literal detection. - test_lit!(sfx_defeated1, suffixes, "a."); - test_lit!(sfx_defeated2, suffixes, "(?s)a."); - test_lit!(sfx_defeated3, suffixes, "a*b*c*"); - test_lit!(sfx_defeated4, suffixes, "a|."); - test_lit!(sfx_defeated5, suffixes, ".|a"); - test_lit!(sfx_defeated6, suffixes, "a|^"); - test_lit!(sfx_defeated7, suffixes, "(?:a(?:b)(?:c))."); - test_lit!(sfx_defeated8, suffixes, "a^"); - test_lit!(sfx_defeated9, suffixes, "(?m)a$"); - test_lit!(sfx_defeated10, suffixes, r"a\b"); - test_lit!(sfx_defeated11, suffixes, r"a\B"); - test_lit!(sfx_defeated12, suffixes, "a^*"); - test_lit!(sfx_defeated13, suffixes, "a^+"); - - // These test use a much lower limit than the default so that we can - // write test cases of reasonable size. - test_exhausted!(sfx_exhausted1, suffixes, "[a-z]"); - test_exhausted!(sfx_exhausted2, suffixes, "A[a-z]*"); - test_exhausted!(sfx_exhausted3, suffixes, "A[a-z]Z", C("Z")); - test_exhausted!(sfx_exhausted4, suffixes, "(?i)foobar", - C("AR"), C("Ar"), C("aR"), C("ar")); - test_exhausted!(sfx_exhausted5, suffixes, "(?:ab){100}", - C("abababababababababab")); - test_exhausted!(sfx_exhausted6, suffixes, "cd(?:(?:ab){100})*", - C("ababababab"), M("cd")); - test_exhausted!(sfx_exhausted7, suffixes, "cd(?:(?:ab){100})*z", - C("abababababz"), M("cdz")); - test_exhausted!(sfx_exhausted8, suffixes, "zaaaaaaaaaaaaaaaaaaaa", - C("aaaaaaaaaaaaaaaaaaaa")); - - // ************************************************************************ - // Tests for generating unambiguous literal sets. - // ************************************************************************ - - macro_rules! test_unamb { - ($name:ident, $given:expr, $expected:expr) => { - #[test] - fn $name() { - let given: Vec<Lit> = - $given - .into_iter() - .map(|ul| { - let cut = ul.is_cut(); - Lit { v: ul.v.into_bytes(), cut: cut } - }) - .collect(); - let lits = create_lits(given); - let got = lits.unambiguous_prefixes(); - assert_eq!($expected, escape_lits(got.literals())); - } - }; - } - - test_unamb!(unambiguous1, vec![M("z"), M("azb")], vec![C("a"), C("z")]); - test_unamb!(unambiguous2, - vec![M("zaaaaaa"), M("aa")], vec![C("aa"), C("z")]); - test_unamb!(unambiguous3, - vec![M("Sherlock"), M("Watson")], - vec![M("Sherlock"), M("Watson")]); - test_unamb!(unambiguous4, vec![M("abc"), M("bc")], vec![C("a"), C("bc")]); - test_unamb!(unambiguous5, vec![M("bc"), M("abc")], vec![C("a"), C("bc")]); - test_unamb!(unambiguous6, vec![M("a"), M("aa")], vec![C("a")]); - test_unamb!(unambiguous7, vec![M("aa"), M("a")], vec![C("a")]); - test_unamb!(unambiguous8, vec![M("ab"), M("a")], vec![C("a")]); - test_unamb!(unambiguous9, - vec![M("ac"), M("bc"), M("c"), M("ac"), M("abc"), M("c")], - vec![C("a"), C("b"), C("c")]); - test_unamb!(unambiguous10, - vec![M("Mo'"), M("Mu'"), M("Mo"), M("Mu")], - vec![C("Mo"), C("Mu")]); - test_unamb!(unambiguous11, - vec![M("zazb"), M("azb")], vec![C("a"), C("z")]); - test_unamb!(unambiguous12, vec![M("foo"), C("foo")], vec![C("foo")]); - test_unamb!(unambiguous13, - vec![M("ABCX"), M("CDAX"), M("BCX")], - vec![C("A"), C("BCX"), C("CD")]); - test_unamb!(unambiguous14, - vec![M("IMGX"), M("MVIX"), M("MGX"), M("DSX")], - vec![M("DSX"), C("I"), C("MGX"), C("MV")]); - test_unamb!(unambiguous15, - vec![M("IMG_"), M("MG_"), M("CIMG")], - vec![C("C"), C("I"), C("MG_")]); - - - // ************************************************************************ - // Tests for suffix trimming. - // ************************************************************************ - macro_rules! test_trim { - ($name:ident, $trim:expr, $given:expr, $expected:expr) => { - #[test] - fn $name() { - let given: Vec<Lit> = - $given - .into_iter() - .map(|ul| { - let cut = ul.is_cut(); - Lit { v: ul.v.into_bytes(), cut: cut } - }) - .collect(); - let lits = create_lits(given); - let got = lits.trim_suffix($trim).unwrap(); - assert_eq!($expected, escape_lits(got.literals())); - } - } - } - - test_trim!(trim1, 1, vec![M("ab"), M("yz")], vec![C("a"), C("y")]); - test_trim!(trim2, 1, vec![M("abc"), M("abd")], vec![C("ab")]); - test_trim!(trim3, 2, vec![M("abc"), M("abd")], vec![C("a")]); - test_trim!(trim4, 2, vec![M("abc"), M("ghij")], vec![C("a"), C("gh")]); - - // ************************************************************************ - // Tests for longest common prefix. - // ************************************************************************ - - macro_rules! test_lcp { - ($name:ident, $given:expr, $expected:expr) => { - #[test] - fn $name() { - let given: Vec<Lit> = - $given - .into_iter() - .map(|s: &str| Lit { - v: s.to_owned().into_bytes(), - cut: false, - }) - .collect(); - let lits = create_lits(given); - let got = lits.longest_common_prefix(); - assert_eq!($expected, escape_bytes(got)); - } - }; - } - - test_lcp!(lcp1, vec!["a"], "a"); - test_lcp!(lcp2, vec![], ""); - test_lcp!(lcp3, vec!["a", "b"], ""); - test_lcp!(lcp4, vec!["ab", "ab"], "ab"); - test_lcp!(lcp5, vec!["ab", "a"], "a"); - test_lcp!(lcp6, vec!["a", "ab"], "a"); - test_lcp!(lcp7, vec!["ab", "b"], ""); - test_lcp!(lcp8, vec!["b", "ab"], ""); - test_lcp!(lcp9, vec!["foobar", "foobaz"], "fooba"); - test_lcp!(lcp10, vec!["foobar", "foobaz", "a"], ""); - test_lcp!(lcp11, vec!["a", "foobar", "foobaz"], ""); - test_lcp!(lcp12, vec!["foo", "flub", "flab", "floo"], "f"); - - // ************************************************************************ - // Tests for longest common suffix. - // ************************************************************************ - - macro_rules! test_lcs { - ($name:ident, $given:expr, $expected:expr) => { - #[test] - fn $name() { - let given: Vec<Lit> = - $given - .into_iter() - .map(|s: &str| Lit { - v: s.to_owned().into_bytes(), - cut: false, - }) - .collect(); - let lits = create_lits(given); - let got = lits.longest_common_suffix(); - assert_eq!($expected, escape_bytes(got)); - } - }; - } - - test_lcs!(lcs1, vec!["a"], "a"); - test_lcs!(lcs2, vec![], ""); - test_lcs!(lcs3, vec!["a", "b"], ""); - test_lcs!(lcs4, vec!["ab", "ab"], "ab"); - test_lcs!(lcs5, vec!["ab", "a"], ""); - test_lcs!(lcs6, vec!["a", "ab"], ""); - test_lcs!(lcs7, vec!["ab", "b"], "b"); - test_lcs!(lcs8, vec!["b", "ab"], "b"); - test_lcs!(lcs9, vec!["barfoo", "bazfoo"], "foo"); - test_lcs!(lcs10, vec!["barfoo", "bazfoo", "a"], ""); - test_lcs!(lcs11, vec!["a", "barfoo", "bazfoo"], ""); - test_lcs!(lcs12, vec!["flub", "bub", "boob", "dub"], "b"); -} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.4.2/src/parser.rs cargo-0.26.0/vendor/regex-syntax-0.4.2/src/parser.rs --- cargo-0.25.0/vendor/regex-syntax-0.4.2/src/parser.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.4.2/src/parser.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,3311 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::cmp::{max, min}; -use std::u8; - -use unicode::regex::UNICODE_CLASSES; - -use { - Expr, Repeater, CharClass, ClassRange, - CaptureIndex, CaptureName, - Error, ErrorKind, Result, -}; - -/// Parser state. -/// -/// Keeps the entire input in memory and maintains a cursor (char offset). -/// -/// It also keeps an expression stack, which is responsible for managing -/// grouped expressions and flag state. -#[derive(Debug)] -pub struct Parser { - chars: Vec<char>, - chari: usize, - stack: Vec<Build>, - caps: usize, - names: Vec<String>, // to check for duplicates - flags: Flags, -} - -/// Flag state used in the parser. -#[derive(Clone, Copy, Debug)] -pub struct Flags { - /// i - pub casei: bool, - /// m - pub multi: bool, - /// s - pub dotnl: bool, - /// U - pub swap_greed: bool, - /// x - pub ignore_space: bool, - /// u - pub unicode: bool, - /// Not actually a flag, but when disabled, every regex that may not match - /// UTF-8 exclusively will cause the parser to return an error. - pub allow_bytes: bool, -} - -impl Default for Flags { - fn default() -> Self { - Flags { - casei: false, - multi: false, - dotnl: false, - swap_greed: false, - ignore_space: false, - unicode: true, - allow_bytes: false, - } - } -} - -/// An ephemeral type for representing the expression stack. -/// -/// Everything on the stack is either a regular expression or a marker -/// indicating the opening of a group (possibly non-capturing). The opening -/// of a group copies the current flag state, which is reset on the parser -/// state once the group closes. -#[derive(Debug)] -enum Build { - Expr(Expr), - LeftParen { - i: CaptureIndex, - name: CaptureName, - chari: usize, - old_flags: Flags, - }, -} - -/// A type for representing the elements of a bracket stack used for parsing -/// character classes. -/// -/// This is for parsing nested character classes without recursion. -#[derive(Debug)] -enum Bracket { - /// The opening of a character class (possibly negated) - LeftBracket { - negated: bool, - }, - /// A set of characters within a character class, e.g., `a-z` - Set(CharClass), - /// An intersection operator (`&&`) - Intersection, -} - -// Primary expression parsing routines. -impl Parser { - pub fn parse(s: &str, flags: Flags) -> Result<Expr> { - Parser { - chars: s.chars().collect(), - chari: 0, - stack: vec![], - caps: 0, - names: vec![], - flags: flags, - }.parse_expr() - } - - // Top-level expression parser. - // - // Starts at the beginning of the input and consumes until either the end - // of input or an error. - fn parse_expr(mut self) -> Result<Expr> { - loop { - self.ignore_space(); - if self.eof() { - break; - } - let build_expr = match self.cur() { - '\\' => try!(self.parse_escape()), - '|' => { let e = try!(self.alternate()); self.bump(); e } - '?' => try!(self.parse_simple_repeat(Repeater::ZeroOrOne)), - '*' => try!(self.parse_simple_repeat(Repeater::ZeroOrMore)), - '+' => try!(self.parse_simple_repeat(Repeater::OneOrMore)), - '{' => try!(self.parse_counted_repeat()), - '[' => try!(self.parse_class()), - '^' => { - if self.flags.multi { - self.parse_one(Expr::StartLine) - } else { - self.parse_one(Expr::StartText) - } - } - '$' => { - if self.flags.multi { - self.parse_one(Expr::EndLine) - } else { - self.parse_one(Expr::EndText) - } - } - '.' => { - if self.flags.dotnl { - if self.flags.unicode { - self.parse_one(Expr::AnyChar) - } else { - if !self.flags.allow_bytes { - return Err(self.err(ErrorKind::InvalidUtf8)); - } - self.parse_one(Expr::AnyByte) - } - } else { - if self.flags.unicode { - self.parse_one(Expr::AnyCharNoNL) - } else { - if !self.flags.allow_bytes { - return Err(self.err(ErrorKind::InvalidUtf8)); - } - self.parse_one(Expr::AnyByteNoNL) - } - } - } - '(' => try!(self.parse_group()), - ')' => { - let (old_flags, e) = try!(self.close_paren()); - self.bump(); - self.flags = old_flags; - e - } - _ => { - let c = self.bump(); - try!(self.lit(c)) - } - }; - if !build_expr.is_empty() { - self.stack.push(build_expr); - } - } - self.finish_concat() - } - - // Parses an escape sequence, e.g., \Ax - // - // Start: `\` - // End: `x` - fn parse_escape(&mut self) -> Result<Build> { - self.bump(); - if self.eof() { - return Err(self.err(ErrorKind::UnexpectedEscapeEof)); - } - let c = self.cur(); - if is_punct(c) || (self.flags.ignore_space && c.is_whitespace()) { - let c = self.bump(); - return Ok(try!(self.lit(c))); - } - match c { - 'a' => { self.bump(); Ok(try!(self.lit('\x07'))) } - 'f' => { self.bump(); Ok(try!(self.lit('\x0C'))) } - 't' => { self.bump(); Ok(try!(self.lit('\t'))) } - 'n' => { self.bump(); Ok(try!(self.lit('\n'))) } - 'r' => { self.bump(); Ok(try!(self.lit('\r'))) } - 'v' => { self.bump(); Ok(try!(self.lit('\x0B'))) } - 'A' => { self.bump(); Ok(Build::Expr(Expr::StartText)) } - 'z' => { self.bump(); Ok(Build::Expr(Expr::EndText)) } - 'b' => { - self.bump(); - Ok(Build::Expr(if self.flags.unicode { - Expr::WordBoundary - } else { - Expr::WordBoundaryAscii - })) - } - 'B' => { - self.bump(); - Ok(Build::Expr(if self.flags.unicode { - Expr::NotWordBoundary - } else { - Expr::NotWordBoundaryAscii - })) - } - '0'|'1'|'2'|'3'|'4'|'5'|'6'|'7' => self.parse_octal(), - 'x' => { self.bump(); self.parse_hex() } - 'p'|'P' => { - self.bump(); - self.parse_unicode_class(c == 'P') - .map(|cls| Build::Expr(Expr::Class(cls))) - } - 'd'|'s'|'w'|'D'|'S'|'W' => { - self.bump(); - Ok(Build::Expr(Expr::Class(self.parse_perl_class(c)))) - } - c => Err(self.err(ErrorKind::UnrecognizedEscape(c))), - } - } - - // Parses a group, e.g., `(abc)`. - // - // Start: `(` - // End: `a` - // - // A more interesting example, `(?P<foo>abc)`. - // - // Start: `(` - // End: `a` - fn parse_group(&mut self) -> Result<Build> { - let chari = self.chari; - let mut name: CaptureName = None; - self.bump(); - self.ignore_space(); - if self.bump_if("?P<") { - let n = try!(self.parse_group_name()); - if self.names.iter().any(|n2| n2 == &n) { - return Err(self.err(ErrorKind::DuplicateCaptureName(n))); - } - self.names.push(n.clone()); - name = Some(n); - } else if self.bump_if("?") { - // This can never be capturing. It's either setting flags for - // the current group, or it's opening a non-capturing group or - // it's opening a group with a specific set of flags (which is - // also non-capturing). - // Anything else is an error. - return self.parse_group_flags(chari); - } - self.caps = checkadd(self.caps, 1); - Ok(Build::LeftParen { - i: Some(self.caps), - name: name, - chari: chari, - old_flags: self.flags, // no flags changed if we're here - }) - } - - // Parses flags (inline or grouped), e.g., `(?s-i:abc)`. - // - // Start: `s` - // End: `a` - // - // Another example, `(?s-i)a`. - // - // Start: `s` - // End: `a` - fn parse_group_flags(&mut self, opening_chari: usize) -> Result<Build> { - let old_flags = self.flags; - let mut sign = true; - let mut saw_flag = false; - loop { - if self.eof() { - // e.g., (?i - return Err(self.err(ErrorKind::UnexpectedFlagEof)); - } - match self.cur() { - 'i' => { self.flags.casei = sign; saw_flag = true } - 'm' => { self.flags.multi = sign; saw_flag = true } - 's' => { self.flags.dotnl = sign; saw_flag = true } - 'U' => { self.flags.swap_greed = sign; saw_flag = true } - 'x' => { self.flags.ignore_space = sign; saw_flag = true } - 'u' => { self.flags.unicode = sign; saw_flag = true } - '-' => { - if !sign { - // e.g., (?-i-s) - return Err(self.err(ErrorKind::DoubleFlagNegation)); - } - sign = false; - saw_flag = false; - } - ')' => { - if !saw_flag { - // e.g., (?) - return Err(self.err(ErrorKind::EmptyFlagNegation)); - } - // At this point, we're just changing the flags inside - // the current group, which means the old flags have - // been saved elsewhere. Our modifications in place are - // okey dokey! - // - // This particular flag expression only has a stateful - // impact on a regex's AST, so nothing gets explicitly - // added. - self.bump(); - return Ok(Build::Expr(Expr::Empty)); - } - ':' => { - if !sign && !saw_flag { - // e.g., (?i-:a) - // Note that if there's no negation, it's OK not - // to see flag, because you end up with a regular - // non-capturing group: `(?:a)`. - return Err(self.err(ErrorKind::EmptyFlagNegation)); - } - self.bump(); - return Ok(Build::LeftParen { - i: None, - name: None, - chari: opening_chari, - old_flags: old_flags, - }); - } - // e.g., (?z:a) - c => return Err(self.err(ErrorKind::UnrecognizedFlag(c))), - } - self.bump(); - } - } - - // Parses a group name, e.g., `foo` in `(?P<foo>abc)`. - // - // Start: `f` - // End: `a` - fn parse_group_name(&mut self) -> Result<String> { - let mut name = String::new(); - while !self.eof() && !self.peek_is('>') { - name.push(self.bump()); - } - if self.eof() { - // e.g., (?P<a - return Err(self.err(ErrorKind::UnclosedCaptureName(name))); - } - let all_valid = name.chars().all(is_valid_capture_char); - match name.chars().next() { - // e.g., (?P<>a) - None => Err(self.err(ErrorKind::EmptyCaptureName)), - Some(c) if (c >= '0' && c <= '9') || !all_valid => { - // e.g., (?P<a#>x) - // e.g., (?P<1a>x) - Err(self.err(ErrorKind::InvalidCaptureName(name))) - } - _ => { - self.bump(); // for `>` - Ok(name) - } - } - } - - // Parses a counted repeition operator, e.g., `a{2,4}?z`. - // - // Start: `{` - // End: `z` - fn parse_counted_repeat(&mut self) -> Result<Build> { - let e = try!(self.pop(ErrorKind::RepeaterExpectsExpr)); // e.g., ({5} - if !e.can_repeat() { - // e.g., a*{5} - return Err(self.err(ErrorKind::RepeaterUnexpectedExpr(e))); - } - self.bump(); - self.ignore_space(); - let min = try!(self.parse_decimal()); - let mut max_opt = Some(min); - self.ignore_space(); - if self.bump_if(',') { - self.ignore_space(); - if self.peek_is('}') { - max_opt = None; - } else { - let max = try!(self.parse_decimal()); - if min > max { - // e.g., a{2,1} - return Err(self.err(ErrorKind::InvalidRepeatRange { - min: min, - max: max, - })); - } - max_opt = Some(max); - } - } - self.ignore_space(); - if !self.bump_if('}') { - Err(self.err(ErrorKind::UnclosedRepeat)) - } else { - Ok(Build::Expr(Expr::Repeat { - e: Box::new(e), - r: Repeater::Range { min: min, max: max_opt }, - greedy: !self.bump_if('?') ^ self.flags.swap_greed, - })) - } - } - - // Parses a simple repetition operator, e.g., `a+?z`. - // - // Start: `+` - // End: `z` - // - // N.B. "simple" in this context means "not min/max repetition", - // e.g., `a{1,2}`. - fn parse_simple_repeat(&mut self, rep: Repeater) -> Result<Build> { - let e = try!(self.pop(ErrorKind::RepeaterExpectsExpr)); // e.g., (* - if !e.can_repeat() { - // e.g., a** - return Err(self.err(ErrorKind::RepeaterUnexpectedExpr(e))); - } - self.bump(); - Ok(Build::Expr(Expr::Repeat { - e: Box::new(e), - r: rep, - greedy: !self.bump_if('?') ^ self.flags.swap_greed, - })) - } - - // Parses a decimal number until the given character, e.g., `a{123,456}`. - // - // Start: `1` - // End: `,` (where `until == ','`) - fn parse_decimal(&mut self) -> Result<u32> { - match self.bump_get(|c| is_ascii_word(c) || c.is_whitespace()) { - // e.g., a{} - None => Err(self.err(ErrorKind::MissingBase10)), - Some(n) => { - // e.g., a{xyz - // e.g., a{9999999999} - let n = n.trim(); - u32::from_str_radix(n, 10) - .map_err(|_| self.err(ErrorKind::InvalidBase10(n.into()))) - } - } - } - - // Parses an octal number, up to 3 digits, e.g., `a\123b` - // - // Start: `1` - // End: `b` - fn parse_octal(&mut self) -> Result<Build> { - use std::char; - let mut i = 0; // counter for limiting octal to 3 digits. - let n = self.bump_get(|c| { i += 1; i <= 3 && c >= '0' && c <= '7' }) - .expect("octal string"); // guaranteed at least 1 digit - // I think both of the following unwraps are impossible to fail. - // We limit it to a three digit octal number, which maxes out at - // `0777` or `511` in decimal. Since all digits are in `0...7`, we'll - // always have a valid `u32` number. Moreover, since all numbers in - // the range `0...511` are valid Unicode scalar values, it will always - // be a valid `char`. - // - // Hence, we `unwrap` with reckless abandon. - let n = u32::from_str_radix(&n, 8).ok().expect("valid octal number"); - if !self.flags.unicode { - return Ok(try!(self.u32_to_one_byte(n))); - } - let c = char::from_u32(n).expect("Unicode scalar value"); - Ok(try!(self.lit(c))) - } - - // Parses a hex number, e.g., `a\x5ab`. - // - // Start: `5` - // End: `b` - // - // And also, `a\x{2603}b`. - // - // Start: `{` - // End: `b` - fn parse_hex(&mut self) -> Result<Build> { - self.ignore_space(); - if self.bump_if('{') { - self.parse_hex_many_digits() - } else { - self.parse_hex_two_digits() - } - } - - // Parses a many-digit hex number, e.g., `a\x{2603}b`. - // - // Start: `2` - // End: `b` - fn parse_hex_many_digits(&mut self) -> Result<Build> { - use std::char; - - self.ignore_space(); - let s = self.bump_get(is_ascii_word).unwrap_or("".into()); - let n = try!(u32::from_str_radix(&s, 16) - .map_err(|_| self.err(ErrorKind::InvalidBase16(s)))); - self.ignore_space(); - if !self.bump_if('}') { - // e.g., a\x{d - return Err(self.err(ErrorKind::UnclosedHex)); - } - if !self.flags.unicode { - return Ok(try!(self.u32_to_one_byte(n))); - } - let c = try!(char::from_u32(n) - .ok_or(self.err(ErrorKind::InvalidScalarValue(n)))); - Ok(try!(self.lit(c))) - } - - // Parses a two-digit hex number, e.g., `a\x5ab`. - // - // Start: `5` - // End: `b` - fn parse_hex_two_digits(&mut self) -> Result<Build> { - use std::char; - - let mut i = 0; - let s = self.bump_get(|_| { i += 1; i <= 2 }).unwrap_or("".into()); - if s.len() < 2 { - // e.g., a\x - // e.g., a\xf - return Err(self.err(ErrorKind::UnexpectedTwoDigitHexEof)); - } - let n = try!(u32::from_str_radix(&s, 16) - .map_err(|_| self.err(ErrorKind::InvalidBase16(s)))); - if !self.flags.unicode { - return Ok(try!(self.u32_to_one_byte(n))); - } - let c = char::from_u32(n).expect("Unicode scalar value"); - Ok(try!(self.lit(c))) - } - - // Parses a character class, e.g., `[^a-zA-Z0-9]+`. - // - // If the Unicode flag is enabled, the class is returned as a `CharClass`, - // otherwise it is converted to a `ByteClass`. - // - // Start: `[` - // End: `+` - fn parse_class(&mut self) -> Result<Build> { - let class = try!(self.parse_class_as_chars()); - Ok(Build::Expr(if self.flags.unicode { - Expr::Class(class) - } else { - let byte_class = class.to_byte_class(); - - // If `class` was only non-empty due to multibyte characters, the - // corresponding byte class will now be empty. - // - // See https://github.com/rust-lang/regex/issues/303 - if byte_class.is_empty() { - // e.g., (?-u)[^\x00-\xFF] - return Err(self.err(ErrorKind::EmptyClass)); - } - - Expr::ClassBytes(byte_class) - })) - } - - // Parses a character class as a `CharClass`, e.g., `[^a-zA-Z0-9]+`. - // - // Start: `[` - // End: `+` - fn parse_class_as_chars(&mut self) -> Result<CharClass> { - let mut bracket_stack = vec![]; - bracket_stack.extend(self.parse_open_bracket()); - loop { - self.ignore_space(); - if self.eof() { - // e.g., [a - return Err(self.err(ErrorKind::UnexpectedClassEof)); - } - match self.cur() { - '[' => { - if let Some(class) = self.maybe_parse_ascii() { - // e.g. `[:alnum:]` - bracket_stack.push(Bracket::Set(class)); - } else { - // nested set, e.g. `[c-d]` in `[a-b[c-d]]` - bracket_stack.extend(self.parse_open_bracket()); - } - } - ']' => { - self.bump(); - let class = try!(self.close_bracket(&mut bracket_stack)); - if bracket_stack.is_empty() { - // That was the outermost class, so stop now - return Ok(class); - } - bracket_stack.push(Bracket::Set(class)); - } - '\\' => { - let class = try!(self.parse_class_escape()); - bracket_stack.push(Bracket::Set(class)); - } - '&' if self.peek_is("&&") => { - self.bump(); - self.bump(); - bracket_stack.push(Bracket::Intersection); - } - start => { - if !self.flags.unicode { - let _ = try!(self.codepoint_to_one_byte(start)); - } - self.bump(); - match start { - '~'|'-' => { - // Only report an error if we see ~~ or --. - if self.peek_is(start) { - return Err(self.err( - ErrorKind::UnsupportedClassChar(start))); - } - } - _ => {} - } - let class = try!(self.parse_class_range(start)); - bracket_stack.push(Bracket::Set(class)); - } - } - } - } - - // Parses the start of a character class or a nested character class. - // That includes negation using `^` and unescaped `-` and `]` allowed at - // the start of the class. - // - // e.g., `[^a]` or `[-a]` or `[]a]` - // - // Start: `[` - // End: `a` - fn parse_open_bracket(&mut self) -> Vec<Bracket> { - self.bump(); - self.ignore_space(); - let negated = self.bump_if('^'); - self.ignore_space(); - - let mut class = CharClass::empty(); - while self.bump_if('-') { - class.ranges.push(ClassRange::one('-')); - self.ignore_space(); - } - if class.is_empty() { - if self.bump_if(']') { - class.ranges.push(ClassRange::one(']')); - self.ignore_space(); - } - } - - let bracket = Bracket::LeftBracket { negated: negated }; - if class.is_empty() { - vec![bracket] - } else { - vec![bracket, Bracket::Set(class)] - } - } - - // Parses an escape in a character class. - // - // This is a helper for `parse_class`. Instead of returning an `Ok` value, - // it either mutates the char class or returns an error. - // - // e.g., `\wx` - // - // Start: `\` - // End: `x` - fn parse_class_escape(&mut self) -> Result<CharClass> { - match try!(self.parse_escape()) { - Build::Expr(Expr::Class(class)) => { - Ok(class) - } - Build::Expr(Expr::ClassBytes(class2)) => { - let mut class = CharClass::empty(); - for byte_range in class2 { - let s = byte_range.start as char; - let e = byte_range.end as char; - class.ranges.push(ClassRange::new(s, e)); - } - Ok(class) - } - Build::Expr(Expr::Literal { chars, .. }) => { - self.parse_class_range(chars[0]) - } - Build::Expr(Expr::LiteralBytes { bytes, .. }) => { - let start = bytes[0] as char; - self.parse_class_range(start) - } - Build::Expr(e) => { - let err = ErrorKind::InvalidClassEscape(e); - Err(self.err(err)) - } - // Because `parse_escape` can never return `LeftParen`. - _ => unreachable!(), - } - } - - // Parses a single range in a character class. - // - // e.g., `[a-z]` - // - // Start: `-` (with start == `a`) - // End: `]` - fn parse_class_range(&mut self, start: char) -> Result<CharClass> { - self.ignore_space(); - if !self.bump_if('-') { - // Not a range, so just return a singleton range. - return Ok(CharClass::new(vec![ClassRange::one(start)])); - } - self.ignore_space(); - if self.eof() { - // e.g., [a- - return Err(self.err(ErrorKind::UnexpectedClassEof)); - } - if self.peek_is(']') { - // This is the end of the class, so we permit use of `-` as a - // regular char (just like we do in the beginning). - return Ok(CharClass::new(vec![ClassRange::one(start), ClassRange::one('-')])); - } - - // We have a real range. Just need to check to parse literal and - // make sure it's a valid range. - let end = match self.cur() { - '\\' => match try!(self.parse_escape()) { - Build::Expr(Expr::Literal { chars, .. }) => { - chars[0] - } - Build::Expr(Expr::LiteralBytes { bytes, .. }) => { - bytes[0] as char - } - Build::Expr(e) => { - return Err(self.err(ErrorKind::InvalidClassEscape(e))); - } - // Because `parse_escape` can never return `LeftParen`. - _ => unreachable!(), - }, - c => { - self.bump(); - if c == '-' { - return Err(self.err(ErrorKind::UnsupportedClassChar('-'))); - } - if !self.flags.unicode { - let _ = try!(self.codepoint_to_one_byte(c)); - } - c - } - }; - if end < start { - // e.g., [z-a] - return Err(self.err(ErrorKind::InvalidClassRange { - start: start, - end: end, - })); - } - Ok(CharClass::new(vec![ClassRange::new(start, end)])) - } - - // Parses an ASCII class, e.g., `[:alnum:]+`. - // - // Start: `[` - // End: `+` - // - // Also supports negation, e.g., `[:^alnum:]`. - // - // This parsing routine is distinct from the others in that it doesn't - // actually report any errors. Namely, if it fails, then the parser should - // fall back to parsing a regular class. - // - // This method will only make progress in the parser if it succeeds. - // Otherwise, the input remains where it started. - fn maybe_parse_ascii(&mut self) -> Option<CharClass> { - fn parse(p: &mut Parser) -> Option<CharClass> { - p.bump(); // the `[` - if !p.bump_if(':') { return None; } - let negate = p.bump_if('^'); - let name = match p.bump_get(|c| c != ':') { - None => return None, - Some(name) => name, - }; - if !p.bump_if(":]") { return None; } - ascii_class(&name).map(|cls| p.class_transform(negate, cls)) - } - let start = self.chari; - match parse(self) { - None => { self.chari = start; None } - result => result, - } - } - - // Parses a Uncode class name, e.g., `a\pLb`. - // - // Start: `L` - // End: `b` - // - // And also, `a\p{Greek}b`. - // - // Start: `{` - // End: `b` - // - // `negate` is true when the class name is used with `\P`. - fn parse_unicode_class(&mut self, neg: bool) -> Result<CharClass> { - self.ignore_space(); - let name = - if self.bump_if('{') { - self.ignore_space(); - let n = self.bump_get(is_ascii_word).unwrap_or("".into()); - self.ignore_space(); - if n.is_empty() || !self.bump_if('}') { - // e.g., \p{Greek - return Err(self.err(ErrorKind::UnclosedUnicodeName)); - } - n - } else { - if self.eof() { - // e.g., \p - return Err(self.err(ErrorKind::UnexpectedEscapeEof)); - } - self.bump().to_string() - }; - match unicode_class(&name) { - None => Err(self.err(ErrorKind::UnrecognizedUnicodeClass(name))), - Some(cls) => { - if self.flags.unicode { - Ok(self.class_transform(neg, cls)) - } else { - Err(self.err(ErrorKind::UnicodeNotAllowed)) - } - } - } - } - - // Parses a perl character class with Unicode support. - // - // `name` must be one of d, s, w, D, S, W. If not, this function panics. - // - // No parser state is changed. - fn parse_perl_class(&mut self, name: char) -> CharClass { - use unicode::regex::{PERLD, PERLS, PERLW}; - let (cls, negate) = match (self.flags.unicode, name) { - (true, 'd') => (raw_class_to_expr(PERLD), false), - (true, 'D') => (raw_class_to_expr(PERLD), true), - (true, 's') => (raw_class_to_expr(PERLS), false), - (true, 'S') => (raw_class_to_expr(PERLS), true), - (true, 'w') => (raw_class_to_expr(PERLW), false), - (true, 'W') => (raw_class_to_expr(PERLW), true), - (false, 'd') => (ascii_class("digit").unwrap(), false), - (false, 'D') => (ascii_class("digit").unwrap(), true), - (false, 's') => (ascii_class("space").unwrap(), false), - (false, 'S') => (ascii_class("space").unwrap(), true), - (false, 'w') => (ascii_class("word").unwrap(), false), - (false, 'W') => (ascii_class("word").unwrap(), true), - _ => unreachable!(), - }; - self.class_transform(negate, cls) - } - - // Always bump to the next input and return the given expression as a - // `Build`. - // - // This is mostly for convenience when the surrounding context implies - // that the next character corresponds to the given expression. - fn parse_one(&mut self, e: Expr) -> Build { - self.bump(); - Build::Expr(e) - } -} - -// Auxiliary helper methods. -impl Parser { - fn chars(&self) -> Chars { - Chars::new(&self.chars[self.chari..]) - } - - fn ignore_space(&mut self) { - if !self.flags.ignore_space { - return; - } - while !self.eof() { - match self.cur() { - '#' => { - self.bump(); - while !self.eof() { - match self.bump() { - '\n' => break, - _ => continue, - } - } - }, - c => if !c.is_whitespace() { - return; - } else { - self.bump(); - } - } - } - } - - fn bump(&mut self) -> char { - let c = self.cur(); - self.chari = checkadd(self.chari, self.chars().next_count()); - c - } - - fn cur(&self) -> char { self.chars().next().unwrap() } - - fn eof(&self) -> bool { self.chars().next().is_none() } - - fn bump_get<B: Bumpable>(&mut self, s: B) -> Option<String> { - let n = s.match_end(self); - if n == 0 { - None - } else { - let end = checkadd(self.chari, n); - let s = self.chars[self.chari..end] - .iter().cloned().collect::<String>(); - self.chari = end; - Some(s) - } - } - - fn bump_if<B: Bumpable>(&mut self, s: B) -> bool { - let n = s.match_end(self); - if n == 0 { - false - } else { - self.chari = checkadd(self.chari, n); - true - } - } - - fn peek_is<B: Bumpable>(&self, s: B) -> bool { - s.match_end(self) > 0 - } - - fn err(&self, kind: ErrorKind) -> Error { - self.errat(self.chari, kind) - } - - fn errat(&self, pos: usize, kind: ErrorKind) -> Error { - Error { pos: pos, surround: self.windowat(pos), kind: kind } - } - - fn windowat(&self, pos: usize) -> String { - let s = max(5, pos) - 5; - let e = min(self.chars.len(), checkadd(pos, 5)); - self.chars[s..e].iter().cloned().collect() - } - - fn pop(&mut self, expected: ErrorKind) -> Result<Expr> { - match self.stack.pop() { - None | Some(Build::LeftParen{..}) => Err(self.err(expected)), - Some(Build::Expr(e)) => Ok(e), - } - } - - // If the current context calls for case insensitivity, then apply - // case folding. Similarly, if `negate` is `true`, then negate the - // class. (Negation always proceeds case folding.) - fn class_transform(&self, negate: bool, mut cls: CharClass) -> CharClass { - if self.flags.casei { - cls = cls.case_fold(); - } - if negate { - cls = cls.negate(); - } - cls - } - - // Translates a Unicode codepoint into a single UTF-8 byte, and returns an - // error if it's not possible. - // - // This will panic if self.flags.unicode == true. - fn codepoint_to_one_byte(&self, c: char) -> Result<u8> { - assert!(!self.flags.unicode); - let bytes = c.to_string().as_bytes().to_owned(); - if bytes.len() > 1 { - return Err(self.err(ErrorKind::UnicodeNotAllowed)); - } - Ok(bytes[0]) - } - - // Creates a new byte literal from a single byte. - // - // If the given number can't fit into a single byte, then it is assumed - // to be a Unicode codepoint and an error is returned. - // - // This should only be called when the bytes flag is enabled. - fn u32_to_one_byte(&self, b: u32) -> Result<Build> { - assert!(!self.flags.unicode); - if b > u8::MAX as u32 { - Err(self.err(ErrorKind::UnicodeNotAllowed)) - } else if !self.flags.allow_bytes && b > 0x7F { - Err(self.err(ErrorKind::InvalidUtf8)) - } else { - Ok(Build::Expr(Expr::LiteralBytes { - bytes: vec![b as u8], - casei: self.flags.casei, - })) - } - } - - // Creates a new literal expr from a Unicode codepoint. - // - // Creates a byte literal if the `bytes` flag is set. - fn lit(&self, c: char) -> Result<Build> { - Ok(Build::Expr(if self.flags.unicode { - Expr::Literal { - chars: vec![c], - casei: self.flags.casei, - } - } else { - Expr::LiteralBytes { - bytes: vec![try!(self.codepoint_to_one_byte(c))], - casei: self.flags.casei, - } - })) - } -} - -struct Chars<'a> { - chars: &'a [char], - cur: usize, -} - -impl<'a> Iterator for Chars<'a> { - type Item = char; - fn next(&mut self) -> Option<char> { - let x = self.c(); - self.advance(); - return x; - } -} - -impl<'a> Chars<'a> { - fn new(chars: &[char]) -> Chars { - Chars { - chars: chars, - cur: 0, - } - } - - fn c(&self) -> Option<char> { - self.chars.get(self.cur).map(|&c| c) - } - - fn advance(&mut self) { - self.cur = checkadd(self.cur, 1); - } - - fn next_count(&mut self) -> usize { - self.next(); - self.cur - } -} - -// Auxiliary methods for manipulating the expression stack. -impl Parser { - // Called whenever an alternate (`|`) is found. - // - // This pops the expression stack until: - // - // 1. The stack is empty. Pushes an alternation with one arm. - // 2. An opening parenthesis is found. Leave the parenthesis - // on the stack and push an alternation with one arm. - // 3. An alternate (`|`) is found. Pop the existing alternation, - // add an arm and push the modified alternation. - // - // Each "arm" in the above corresponds to the concatenation of all - // popped expressions. - // - // In the first two cases, the stack is left in an invalid state - // because an alternation with one arm is not allowed. This - // particular state will be detected by `finish_concat` and an - // error will be reported. - // - // In none of the cases is an empty arm allowed. If an empty arm - // is found, an error is reported. - fn alternate(&mut self) -> Result<Build> { - let mut concat = vec![]; - let alts = |es| Ok(Build::Expr(Expr::Alternate(es))); - loop { - match self.stack.pop() { - None => { - if concat.is_empty() { - // e.g., |a - return Err(self.err(ErrorKind::EmptyAlternate)); - } - return alts(vec![rev_concat(concat)]); - } - Some(e @ Build::LeftParen{..}) => { - if concat.is_empty() { - // e.g., (|a) - return Err(self.err(ErrorKind::EmptyAlternate)); - } - self.stack.push(e); - return alts(vec![rev_concat(concat)]); - } - Some(Build::Expr(Expr::Alternate(mut es))) => { - if concat.is_empty() { - // e.g., a|| - return Err(self.err(ErrorKind::EmptyAlternate)); - } - es.push(rev_concat(concat)); - return alts(es); - } - Some(Build::Expr(e)) => { concat.push(e); } - } - } - } - - // Called whenever a closing parenthesis (`)`) is found. - // - // This pops the expression stack until: - // - // 1. The stack is empty. An error is reported because this - // indicates an unopened parenthesis. - // 2. An opening parenthesis is found. Pop the opening parenthesis - // and push a `Group` expression. - // 3. An alternate (`|`) is found. Pop the existing alternation - // and an arm to it in place. Pop one more item from the stack. - // If the stack was empty, then report an unopened parenthesis - // error, otherwise assume it is an opening parenthesis and - // push a `Group` expression with the popped alternation. - // (We can assume this is an opening parenthesis because an - // alternation either corresponds to the entire Regex or it - // corresponds to an entire group. This is guaranteed by the - // `alternate` method.) - // - // Each "arm" in the above corresponds to the concatenation of all - // popped expressions. - // - // Empty arms nor empty groups are allowed. - fn close_paren(&mut self) -> Result<(Flags, Build)> { - let mut concat = vec![]; - loop { - match self.stack.pop() { - // e.g., ) - None => return Err(self.err(ErrorKind::UnopenedParen)), - Some(Build::LeftParen { i, name, old_flags, .. }) => { - if concat.is_empty() { - // e.g., () - return Err(self.err(ErrorKind::EmptyGroup)); - } - return Ok((old_flags, Build::Expr(Expr::Group { - e: Box::new(rev_concat(concat)), - i: i, - name: name, - }))); - } - Some(Build::Expr(Expr::Alternate(mut es))) => { - if concat.is_empty() { - // e.g., (a|) - return Err(self.err(ErrorKind::EmptyAlternate)); - } - es.push(rev_concat(concat)); - match self.stack.pop() { - // e.g., a|b) - None => return Err(self.err(ErrorKind::UnopenedParen)), - Some(Build::Expr(_)) => unreachable!(), - Some(Build::LeftParen { i, name, old_flags, .. }) => { - return Ok((old_flags, Build::Expr(Expr::Group { - e: Box::new(Expr::Alternate(es)), - i: i, - name: name, - }))); - } - } - } - Some(Build::Expr(e)) => { concat.push(e); } - } - } - } - - // Called only when the parser reaches the end of input. - // - // This pops the expression stack until: - // - // 1. The stack is empty. Return concatenation of popped - // expressions. This concatenation may be empty! - // 2. An alternation is found. Pop the alternation and push - // a new arm. Return the alternation as the entire Regex. - // After this, the stack must be empty, or else there is - // an unclosed paren. - // - // If an opening parenthesis is popped, then an error is - // returned since it indicates an unclosed parenthesis. - fn finish_concat(&mut self) -> Result<Expr> { - let mut concat = vec![]; - loop { - match self.stack.pop() { - None => { return Ok(rev_concat(concat)); } - Some(Build::LeftParen{ chari, ..}) => { - // e.g., a(b - return Err(self.errat(chari, ErrorKind::UnclosedParen)); - } - Some(Build::Expr(Expr::Alternate(mut es))) => { - if concat.is_empty() { - // e.g., a| - return Err(self.err(ErrorKind::EmptyAlternate)); - } - es.push(rev_concat(concat)); - // Make sure there are no opening parens remaining. - match self.stack.pop() { - None => return Ok(Expr::Alternate(es)), - Some(Build::LeftParen{ chari, ..}) => { - // e.g., (a|b - return Err(self.errat( - chari, ErrorKind::UnclosedParen)); - } - e => unreachable!("{:?}", e), - } - } - Some(Build::Expr(e)) => { concat.push(e); } - } - } - } -} - -// Methods for working with the bracket stack used for character class parsing. -impl Parser { - - // After parsing a closing bracket `]`, process elements of the bracket - // stack until finding the corresponding opening bracket `[`, and return - // the combined character class. E.g. with `[^b-f&&ab-c]`: - // - // 1. Adjacent sets are merged into a single union: `ab-c` -> `a-c` - // 2. Unions separated by `&&` are intersected: `b-f` and `a-c` -> `b-c` - // 3. Negation is applied if necessary: `b-c` -> negation of `b-c` - fn close_bracket(&self, stack: &mut Vec<Bracket>) -> Result<CharClass> { - let mut union = CharClass::empty(); - let mut intersect = vec![]; - loop { - match stack.pop() { - Some(Bracket::Set(class)) => { - union.ranges.extend(class); - } - Some(Bracket::Intersection) => { - let class = self.class_union_transform(union); - intersect.push(class); - union = CharClass::empty(); - } - Some(Bracket::LeftBracket { negated }) => { - let mut class = self.class_union_transform(union); - for c in intersect { - class = class.intersection(&c); - } - // negate after combining all sets (`^` has lower precedence than `&&`) - if negated { - class = class.negate(); - } - if class.is_empty() { - // e.g., [^\d\D] - return Err(self.err(ErrorKind::EmptyClass)); - } - return Ok(class); - } - // The first element on the stack is a `LeftBracket` - None => unreachable!() - } - } - } - - // Apply case folding if requested on the union character class, and - // return a canonicalized class. - fn class_union_transform(&self, class: CharClass) -> CharClass { - if self.flags.casei { - // Case folding canonicalizes too - class.case_fold() - } else { - class.canonicalize() - } - } -} - -impl Build { - fn is_empty(&self) -> bool { - match *self { - Build::Expr(Expr::Empty) => true, - _ => false, - } - } -} - -// Make it ergonomic to conditionally bump the parser. -// i.e., `bump_if('a')` or `bump_if("abc")`. -trait Bumpable { - fn match_end(self, p: &Parser) -> usize; -} - -impl Bumpable for char { - fn match_end(self, p: &Parser) -> usize { - let mut chars = p.chars(); - if chars.next().map(|c| c == self).unwrap_or(false) { - chars.cur - } else { - 0 - } - } -} - -impl<'a> Bumpable for &'a str { - fn match_end(self, p: &Parser) -> usize { - let mut search = self.chars(); - let mut rest = p.chars(); - let mut count = 0; - loop { - match (rest.next(), search.next()) { - (Some(c1), Some(c2)) if c1 == c2 => count = rest.cur, - (_, None) => return count, - _ => return 0, - } - } - } -} - -impl<F: FnMut(char) -> bool> Bumpable for F { - fn match_end(mut self, p: &Parser) -> usize { - let mut chars = p.chars(); - let mut count = 0; - while let Some(c) = chars.next() { - if !self(c) { - break - } - count = chars.cur; - } - count - } -} - -// Turn a sequence of expressions into a concatenation. -// This only uses `Concat` if there are 2 or more expressions. -fn rev_concat(mut exprs: Vec<Expr>) -> Expr { - if exprs.len() == 0 { - Expr::Empty - } else if exprs.len() == 1 { - exprs.pop().unwrap() - } else { - exprs.reverse(); - Expr::Concat(exprs) - } -} - -// Returns true if and only if the given character is allowed in a capture -// name. Note that the first char of a capture name must not be numeric. -fn is_valid_capture_char(c: char) -> bool { - c == '_' || (c >= '0' && c <= '9') - || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') -} - -fn is_ascii_word(c: char) -> bool { - match c { - 'a' ... 'z' | 'A' ... 'Z' | '_' | '0' ... '9' => true, - _ => false, - } -} - -/// Returns true if the give character has significance in a regex. -pub fn is_punct(c: char) -> bool { - match c { - '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '|' | - '[' | ']' | '{' | '}' | '^' | '$' | '#' | '&' | '-' | '~' => true, - _ => false, - } -} - -fn checkadd(x: usize, y: usize) -> usize { - x.checked_add(y).expect("regex length overflow") -} - -fn unicode_class(name: &str) -> Option<CharClass> { - UNICODE_CLASSES.binary_search_by(|&(s, _)| s.cmp(name)).ok().map(|i| { - raw_class_to_expr(UNICODE_CLASSES[i].1) - }) -} - -fn ascii_class(name: &str) -> Option<CharClass> { - ASCII_CLASSES.binary_search_by(|&(s, _)| s.cmp(name)).ok().map(|i| { - raw_class_to_expr(ASCII_CLASSES[i].1) - }) -} - -fn raw_class_to_expr(raw: &[(char, char)]) -> CharClass { - let range = |&(s, e)| ClassRange { start: s, end: e }; - CharClass::new(raw.iter().map(range).collect()) -} - -type Class = &'static [(char, char)]; -type NamedClasses = &'static [(&'static str, Class)]; - -const ASCII_CLASSES: NamedClasses = &[ - // Classes must be in alphabetical order so that bsearch works. - // [:alnum:] alphanumeric (== [0-9A-Za-z]) - // [:alpha:] alphabetic (== [A-Za-z]) - // [:ascii:] ASCII (== [\x00-\x7F]) - // [:blank:] blank (== [\t ]) - // [:cntrl:] control (== [\x00-\x1F\x7F]) - // [:digit:] digits (== [0-9]) - // [:graph:] graphical (== [!-~]) - // [:lower:] lower case (== [a-z]) - // [:print:] printable (== [ -~] == [ [:graph:]]) - // [:punct:] punctuation (== [!-/:-@[-`{-~]) - // [:space:] whitespace (== [\t\n\v\f\r ]) - // [:upper:] upper case (== [A-Z]) - // [:word:] word characters (== [0-9A-Za-z_]) - // [:xdigit:] hex digit (== [0-9A-Fa-f]) - // Taken from: http://golang.org/pkg/regex/syntax/ - ("alnum", &ALNUM), - ("alpha", &ALPHA), - ("ascii", &ASCII), - ("blank", &BLANK), - ("cntrl", &CNTRL), - ("digit", &DIGIT), - ("graph", &GRAPH), - ("lower", &LOWER), - ("print", &PRINT), - ("punct", &PUNCT), - ("space", &SPACE), - ("upper", &UPPER), - ("word", &WORD), - ("xdigit", &XDIGIT), -]; - -const ALNUM: Class = &[('0', '9'), ('A', 'Z'), ('a', 'z')]; -const ALPHA: Class = &[('A', 'Z'), ('a', 'z')]; -const ASCII: Class = &[('\x00', '\x7F')]; -const BLANK: Class = &[(' ', ' '), ('\t', '\t')]; -const CNTRL: Class = &[('\x00', '\x1F'), ('\x7F', '\x7F')]; -const DIGIT: Class = &[('0', '9')]; -const GRAPH: Class = &[('!', '~')]; -const LOWER: Class = &[('a', 'z')]; -const PRINT: Class = &[(' ', '~')]; -const PUNCT: Class = &[('!', '/'), (':', '@'), ('[', '`'), ('{', '~')]; -const SPACE: Class = &[('\t', '\t'), ('\n', '\n'), ('\x0B', '\x0B'), - ('\x0C', '\x0C'), ('\r', '\r'), (' ', ' ')]; -const UPPER: Class = &[('A', 'Z')]; -const WORD: Class = &[('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z')]; -const XDIGIT: Class = &[('0', '9'), ('A', 'F'), ('a', 'f')]; - -#[cfg(test)] -mod tests { - use { - CharClass, ClassRange, ByteClass, ByteRange, - Expr, Repeater, - ErrorKind, - }; - use unicode::regex::{PERLD, PERLS, PERLW}; - use super::{LOWER, UPPER, WORD, Flags, Parser, ascii_class}; - - static YI: &'static [(char, char)] = &[ - ('\u{a000}', '\u{a48c}'), ('\u{a490}', '\u{a4c6}'), - ]; - - fn p(s: &str) -> Expr { Parser::parse(s, Flags::default()).unwrap() } - fn pf(s: &str, flags: Flags) -> Expr { Parser::parse(s, flags).unwrap() } - fn lit(c: char) -> Expr { Expr::Literal { chars: vec![c], casei: false } } - fn liti(c: char) -> Expr { Expr::Literal { chars: vec![c], casei: true } } - fn b<T>(v: T) -> Box<T> { Box::new(v) } - fn c(es: &[Expr]) -> Expr { Expr::Concat(es.to_vec()) } - - fn pb(s: &str) -> Expr { - let flags = Flags { allow_bytes: true, .. Flags::default() }; - Parser::parse(s, flags).unwrap() - } - - fn blit(b: u8) -> Expr { - Expr::LiteralBytes { - bytes: vec![b], - casei: false, - } - } - - fn bliti(b: u8) -> Expr { - Expr::LiteralBytes { - bytes: vec![b], - casei: true, - } - } - - fn class(ranges: &[(char, char)]) -> CharClass { - let ranges = ranges.iter().cloned() - .map(|(c1, c2)| ClassRange::new(c1, c2)).collect(); - CharClass::new(ranges) - } - - fn classes(classes: &[&[(char, char)]]) -> CharClass { - let mut cls = CharClass::empty(); - for &ranges in classes { - cls.ranges.extend(class(ranges)); - } - cls.canonicalize() - } - - fn bclass(ranges: &[(u8, u8)]) -> ByteClass { - let ranges = ranges.iter().cloned() - .map(|(c1, c2)| ByteRange::new(c1, c2)).collect(); - ByteClass::new(ranges) - } - - fn asciid() -> CharClass { - ascii_class("digit").unwrap() - } - - fn asciis() -> CharClass { - ascii_class("space").unwrap() - } - - fn asciiw() -> CharClass { - ascii_class("word").unwrap() - } - - fn asciid_bytes() -> ByteClass { - asciid().to_byte_class() - } - - fn asciis_bytes() -> ByteClass { - asciis().to_byte_class() - } - - fn asciiw_bytes() -> ByteClass { - asciiw().to_byte_class() - } - - #[test] - fn empty() { - assert_eq!(p(""), Expr::Empty); - } - - #[test] - fn literal() { - assert_eq!(p("a"), lit('a')); - assert_eq!(pb("(?-u)a"), blit(b'a')); - } - - #[test] - fn literal_string() { - assert_eq!(p("ab"), Expr::Concat(vec![lit('a'), lit('b')])); - assert_eq!(pb("(?-u)ab"), Expr::Concat(vec![blit(b'a'), blit(b'b')])); - } - - #[test] - fn start_literal() { - assert_eq!(p("^a"), Expr::Concat(vec![ - Expr::StartText, - Expr::Literal { chars: vec!['a'], casei: false }, - ])); - } - - #[test] - fn repeat_zero_or_one_greedy() { - assert_eq!(p("a?"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::ZeroOrOne, - greedy: true, - }); - } - - #[test] - fn repeat_zero_or_one_greedy_concat() { - assert_eq!(p("ab?"), Expr::Concat(vec![ - lit('a'), - Expr::Repeat { - e: b(lit('b')), - r: Repeater::ZeroOrOne, - greedy: true, - }, - ])); - } - - #[test] - fn repeat_zero_or_one_nongreedy() { - assert_eq!(p("a??"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::ZeroOrOne, - greedy: false, - }); - } - - #[test] - fn repeat_one_or_more_greedy() { - assert_eq!(p("a+"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::OneOrMore, - greedy: true, - }); - } - - #[test] - fn repeat_one_or_more_nongreedy() { - assert_eq!(p("a+?"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::OneOrMore, - greedy: false, - }); - } - - #[test] - fn repeat_zero_or_more_greedy() { - assert_eq!(p("a*"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::ZeroOrMore, - greedy: true, - }); - } - - #[test] - fn repeat_zero_or_more_nongreedy() { - assert_eq!(p("a*?"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::ZeroOrMore, - greedy: false, - }); - } - - #[test] - fn repeat_counted_exact() { - assert_eq!(p("a{5}"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::Range { min: 5, max: Some(5) }, - greedy: true, - }); - } - - #[test] - fn repeat_counted_min() { - assert_eq!(p("a{5,}"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::Range { min: 5, max: None }, - greedy: true, - }); - } - - #[test] - fn repeat_counted_min_max() { - assert_eq!(p("a{5,10}"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::Range { min: 5, max: Some(10) }, - greedy: true, - }); - } - - #[test] - fn repeat_counted_exact_nongreedy() { - assert_eq!(p("a{5}?"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::Range { min: 5, max: Some(5) }, - greedy: false, - }); - } - - #[test] - fn repeat_counted_min_nongreedy() { - assert_eq!(p("a{5,}?"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::Range { min: 5, max: None }, - greedy: false, - }); - } - - #[test] - fn repeat_counted_min_max_nongreedy() { - assert_eq!(p("a{5,10}?"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::Range { min: 5, max: Some(10) }, - greedy: false, - }); - } - - #[test] - fn repeat_counted_whitespace() { - assert_eq!(p("a{ 5 }"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::Range { min: 5, max: Some(5) }, - greedy: true, - }); - assert_eq!(p("a{ 5 , 10 }"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::Range { min: 5, max: Some(10) }, - greedy: true, - }); - } - - #[test] - fn group_literal() { - assert_eq!(p("(a)"), Expr::Group { - e: b(lit('a')), - i: Some(1), - name: None, - }); - } - - #[test] - fn group_literal_concat() { - assert_eq!(p("(ab)"), Expr::Group { - e: b(c(&[lit('a'), lit('b')])), - i: Some(1), - name: None, - }); - } - - #[test] - fn alt_two() { - assert_eq!(p("a|b"), Expr::Alternate(vec![lit('a'), lit('b')])); - } - - #[test] - fn alt_many() { - assert_eq!(p("a|b|c"), Expr::Alternate(vec![ - lit('a'), lit('b'), lit('c'), - ])); - } - - #[test] - fn alt_many_concat() { - assert_eq!(p("ab|bc|cd"), Expr::Alternate(vec![ - c(&[lit('a'), lit('b')]), - c(&[lit('b'), lit('c')]), - c(&[lit('c'), lit('d')]), - ])); - } - - #[test] - fn alt_group_two() { - assert_eq!(p("(a|b)"), Expr::Group { - e: b(Expr::Alternate(vec![lit('a'), lit('b')])), - i: Some(1), - name: None, - }); - } - - #[test] - fn alt_group_many() { - assert_eq!(p("(a|b|c)"), Expr::Group { - e: b(Expr::Alternate(vec![lit('a'), lit('b'), lit('c')])), - i: Some(1), - name: None, - }); - } - - #[test] - fn alt_group_many_concat() { - assert_eq!(p("(ab|bc|cd)"), Expr::Group { - e: b(Expr::Alternate(vec![ - c(&[lit('a'), lit('b')]), - c(&[lit('b'), lit('c')]), - c(&[lit('c'), lit('d')]), - ])), - i: Some(1), - name: None, - }); - } - - #[test] - fn alt_group_nested() { - assert_eq!(p("(ab|(bc|(cd)))"), Expr::Group { - e: b(Expr::Alternate(vec![ - c(&[lit('a'), lit('b')]), - Expr::Group { - e: b(Expr::Alternate(vec![ - c(&[lit('b'), lit('c')]), - Expr::Group { - e: b(c(&[lit('c'), lit('d')])), - i: Some(3), - name: None, - } - ])), - i: Some(2), - name: None, - }, - ])), - i: Some(1), - name: None, - }); - } - - #[test] - fn group_name() { - assert_eq!(p("(?P<foo>a)"), Expr::Group { - e: b(lit('a')), - i: Some(1), - name: Some("foo".into()), - }); - } - - #[test] - fn group_no_capture() { - assert_eq!(p("(?:a)"), Expr::Group { - e: b(lit('a')), - i: None, - name: None, - }); - } - - #[test] - fn group_flags() { - assert_eq!(p("(?i:a)"), Expr::Group { - e: b(liti('a')), - i: None, - name: None, - }); - assert_eq!(pb("(?i-u:a)"), Expr::Group { - e: b(bliti(b'a')), - i: None, - name: None, - }); - } - - #[test] - fn group_flags_returned() { - assert_eq!(p("(?i:a)a"), c(&[ - Expr::Group { - e: b(liti('a')), - i: None, - name: None, - }, - lit('a'), - ])); - assert_eq!(pb("(?i-u:a)a"), c(&[ - Expr::Group { - e: b(bliti(b'a')), - i: None, - name: None, - }, - lit('a'), - ])); - } - - #[test] - fn group_flags_retained() { - assert_eq!(p("(?i)(?-i:a)a"), c(&[ - Expr::Group { - e: b(lit('a')), - i: None, - name: None, - }, - liti('a'), - ])); - assert_eq!(pb("(?i-u)(?u-i:a)a"), c(&[ - Expr::Group { - e: b(lit('a')), - i: None, - name: None, - }, - bliti(b'a'), - ])); - } - - #[test] - fn flags_inline() { - assert_eq!(p("(?i)a"), liti('a')); - } - - #[test] - fn flags_inline_multiple() { - assert_eq!(p("(?is)a."), c(&[liti('a'), Expr::AnyChar])); - } - - #[test] - fn flags_inline_multiline() { - assert_eq!(p("(?m)^(?-m)$"), c(&[Expr::StartLine, Expr::EndText])); - } - - #[test] - fn flags_inline_swap_greed() { - assert_eq!(p("(?U)a*a*?(?i-U)a*a*?"), c(&[ - Expr::Repeat { - e: b(lit('a')), - r: Repeater::ZeroOrMore, - greedy: false, - }, - Expr::Repeat { - e: b(lit('a')), - r: Repeater::ZeroOrMore, - greedy: true, - }, - Expr::Repeat { - e: b(liti('a')), - r: Repeater::ZeroOrMore, - greedy: true, - }, - Expr::Repeat { - e: b(liti('a')), - r: Repeater::ZeroOrMore, - greedy: false, - }, - ])); - } - - #[test] - fn flags_inline_multiple_negate_one() { - assert_eq!(p("(?is)a.(?i-s)a."), c(&[ - liti('a'), Expr::AnyChar, liti('a'), Expr::AnyCharNoNL, - ])); - } - - #[test] - fn any_byte() { - assert_eq!( - pb("(?-u).(?u)."), c(&[Expr::AnyByteNoNL, Expr::AnyCharNoNL])); - assert_eq!( - pb("(?s)(?-u).(?u)."), c(&[Expr::AnyByte, Expr::AnyChar])); - } - - #[test] - fn flags_inline_negate() { - assert_eq!(p("(?i)a(?-i)a"), c(&[liti('a'), lit('a')])); - } - - #[test] - fn flags_group_inline() { - assert_eq!(p("(a(?i)a)a"), c(&[ - Expr::Group { - e: b(c(&[lit('a'), liti('a')])), - i: Some(1), - name: None, - }, - lit('a'), - ])); - } - - #[test] - fn flags_group_inline_retain() { - assert_eq!(p("(?i)((?-i)a)a"), c(&[ - Expr::Group { - e: b(lit('a')), - i: Some(1), - name: None, - }, - liti('a'), - ])); - } - - #[test] - fn flags_default_casei() { - let flags = Flags { casei: true, .. Flags::default() }; - assert_eq!(pf("a", flags), liti('a')); - } - - #[test] - fn flags_default_multi() { - let flags = Flags { multi: true, .. Flags::default() }; - assert_eq!(pf("^", flags), Expr::StartLine); - } - - #[test] - fn flags_default_dotnl() { - let flags = Flags { dotnl: true, .. Flags::default() }; - assert_eq!(pf(".", flags), Expr::AnyChar); - } - - #[test] - fn flags_default_swap_greed() { - let flags = Flags { swap_greed: true, .. Flags::default() }; - assert_eq!(pf("a+", flags), Expr::Repeat { - e: b(lit('a')), - r: Repeater::OneOrMore, - greedy: false, - }); - } - - #[test] - fn flags_default_ignore_space() { - let flags = Flags { ignore_space: true, .. Flags::default() }; - assert_eq!(pf(" a ", flags), lit('a')); - } - - #[test] - fn escape_simple() { - assert_eq!(p(r"\a\f\t\n\r\v"), c(&[ - lit('\x07'), lit('\x0C'), lit('\t'), - lit('\n'), lit('\r'), lit('\x0B'), - ])); - } - - #[test] - fn escape_boundaries() { - assert_eq!(p(r"\A\z\b\B"), c(&[ - Expr::StartText, Expr::EndText, - Expr::WordBoundary, Expr::NotWordBoundary, - ])); - assert_eq!(pb(r"(?-u)\b\B"), c(&[ - Expr::WordBoundaryAscii, Expr::NotWordBoundaryAscii, - ])); - } - - #[test] - fn escape_punctuation() { - assert_eq!(p(r"\\\.\+\*\?\(\)\|\[\]\{\}\^\$\#"), c(&[ - lit('\\'), lit('.'), lit('+'), lit('*'), lit('?'), - lit('('), lit(')'), lit('|'), lit('['), lit(']'), - lit('{'), lit('}'), lit('^'), lit('$'), lit('#'), - ])); - } - - #[test] - fn escape_octal() { - assert_eq!(p(r"\123"), lit('S')); - assert_eq!(p(r"\1234"), c(&[lit('S'), lit('4')])); - - assert_eq!(pb(r"(?-u)\377"), blit(0xFF)); - } - - #[test] - fn escape_hex2() { - assert_eq!(p(r"\x53"), lit('S')); - assert_eq!(p(r"\x534"), c(&[lit('S'), lit('4')])); - - assert_eq!(pb(r"(?-u)\xff"), blit(0xFF)); - assert_eq!(pb(r"(?-u)\x00"), blit(0x0)); - assert_eq!(pb(r"(?-u)[\x00]"), - Expr::ClassBytes(bclass(&[(b'\x00', b'\x00')]))); - assert_eq!(pb(r"(?-u)[^\x00]"), - Expr::ClassBytes(bclass(&[(b'\x01', b'\xFF')]))); - } - - #[test] - fn escape_hex() { - assert_eq!(p(r"\x{53}"), lit('S')); - assert_eq!(p(r"\x{53}4"), c(&[lit('S'), lit('4')])); - assert_eq!(p(r"\x{2603}"), lit('\u{2603}')); - - assert_eq!(pb(r"(?-u)\x{00FF}"), blit(0xFF)); - } - - #[test] - fn escape_unicode_name() { - assert_eq!(p(r"\p{Yi}"), Expr::Class(class(YI))); - } - - #[test] - fn escape_unicode_letter() { - assert_eq!(p(r"\pZ"), Expr::Class(class(&[ - ('\u{20}', '\u{20}'), ('\u{a0}', '\u{a0}'), - ('\u{1680}', '\u{1680}'), ('\u{2000}', '\u{200a}'), - ('\u{2028}', '\u{2029}'), ('\u{202f}', '\u{202f}'), - ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}'), - ]))); - } - - #[test] - fn escape_unicode_name_case_fold() { - assert_eq!(p(r"(?i)\p{Yi}"), Expr::Class(class(YI).case_fold())); - } - - #[test] - fn escape_unicode_letter_case_fold() { - assert_eq!(p(r"(?i)\pZ"), Expr::Class(class(&[ - ('\u{20}', '\u{20}'), ('\u{a0}', '\u{a0}'), - ('\u{1680}', '\u{1680}'), ('\u{2000}', '\u{200a}'), - ('\u{2028}', '\u{2029}'), ('\u{202f}', '\u{202f}'), - ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}'), - ]).case_fold())); - } - - #[test] - fn escape_unicode_name_negate() { - assert_eq!(p(r"\P{Yi}"), Expr::Class(class(YI).negate())); - } - - #[test] - fn escape_unicode_letter_negate() { - assert_eq!(p(r"\PZ"), Expr::Class(class(&[ - ('\u{20}', '\u{20}'), ('\u{a0}', '\u{a0}'), - ('\u{1680}', '\u{1680}'), ('\u{2000}', '\u{200a}'), - ('\u{2028}', '\u{2029}'), ('\u{202f}', '\u{202f}'), - ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}'), - ]).negate())); - } - - #[test] - fn escape_unicode_name_negate_case_fold() { - assert_eq!(p(r"(?i)\P{Yi}"), - Expr::Class(class(YI).negate().case_fold())); - } - - #[test] - fn escape_unicode_letter_negate_case_fold() { - assert_eq!(p(r"(?i)\PZ"), Expr::Class(class(&[ - ('\u{20}', '\u{20}'), ('\u{a0}', '\u{a0}'), - ('\u{1680}', '\u{1680}'), ('\u{2000}', '\u{200a}'), - ('\u{2028}', '\u{2029}'), ('\u{202f}', '\u{202f}'), - ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}'), - ]).negate().case_fold())); - } - - #[test] - fn escape_perl_d() { - assert_eq!(p(r"\d"), Expr::Class(class(PERLD))); - assert_eq!(pb(r"(?-u)\d"), Expr::Class(asciid())); - } - - #[test] - fn escape_perl_s() { - assert_eq!(p(r"\s"), Expr::Class(class(PERLS))); - assert_eq!(pb(r"(?-u)\s"), Expr::Class(asciis())); - } - - #[test] - fn escape_perl_w() { - assert_eq!(p(r"\w"), Expr::Class(class(PERLW))); - assert_eq!(pb(r"(?-u)\w"), Expr::Class(asciiw())); - } - - #[test] - fn escape_perl_d_negate() { - assert_eq!(p(r"\D"), Expr::Class(class(PERLD).negate())); - assert_eq!(pb(r"(?-u)\D"), Expr::Class(asciid().negate())); - } - - #[test] - fn escape_perl_s_negate() { - assert_eq!(p(r"\S"), Expr::Class(class(PERLS).negate())); - assert_eq!(pb(r"(?-u)\S"), Expr::Class(asciis().negate())); - } - - #[test] - fn escape_perl_w_negate() { - assert_eq!(p(r"\W"), Expr::Class(class(PERLW).negate())); - assert_eq!(pb(r"(?-u)\W"), Expr::Class(asciiw().negate())); - } - - #[test] - fn escape_perl_d_case_fold() { - assert_eq!(p(r"(?i)\d"), Expr::Class(class(PERLD).case_fold())); - assert_eq!(pb(r"(?i-u)\d"), Expr::Class(asciid().case_fold())); - } - - #[test] - fn escape_perl_s_case_fold() { - assert_eq!(p(r"(?i)\s"), Expr::Class(class(PERLS).case_fold())); - assert_eq!(pb(r"(?i-u)\s"), Expr::Class(asciis().case_fold())); - } - - #[test] - fn escape_perl_w_case_fold() { - assert_eq!(p(r"(?i)\w"), Expr::Class(class(PERLW).case_fold())); - assert_eq!(pb(r"(?i-u)\w"), Expr::Class(asciiw().case_fold())); - } - - #[test] - fn escape_perl_d_case_fold_negate() { - assert_eq!(p(r"(?i)\D"), - Expr::Class(class(PERLD).case_fold().negate())); - let bytes = asciid().case_fold().negate(); - assert_eq!(pb(r"(?i-u)\D"), Expr::Class(bytes)); - } - - #[test] - fn escape_perl_s_case_fold_negate() { - assert_eq!(p(r"(?i)\S"), - Expr::Class(class(PERLS).case_fold().negate())); - let bytes = asciis().case_fold().negate(); - assert_eq!(pb(r"(?i-u)\S"), Expr::Class(bytes)); - } - - #[test] - fn escape_perl_w_case_fold_negate() { - assert_eq!(p(r"(?i)\W"), - Expr::Class(class(PERLW).case_fold().negate())); - let bytes = asciiw().case_fold().negate(); - assert_eq!(pb(r"(?i-u)\W"), Expr::Class(bytes)); - } - - #[test] - fn class_singleton() { - assert_eq!(p(r"[a]"), Expr::Class(class(&[('a', 'a')]))); - assert_eq!(p(r"[\x00]"), Expr::Class(class(&[('\x00', '\x00')]))); - assert_eq!(p(r"[\n]"), Expr::Class(class(&[('\n', '\n')]))); - assert_eq!(p("[\n]"), Expr::Class(class(&[('\n', '\n')]))); - - assert_eq!(pb(r"(?-u)[a]"), Expr::ClassBytes(bclass(&[(b'a', b'a')]))); - assert_eq!(pb(r"(?-u)[\x00]"), Expr::ClassBytes(bclass(&[(0, 0)]))); - assert_eq!(pb(r"(?-u)[\xFF]"), - Expr::ClassBytes(bclass(&[(0xFF, 0xFF)]))); - assert_eq!(pb("(?-u)[\n]"), - Expr::ClassBytes(bclass(&[(b'\n', b'\n')]))); - assert_eq!(pb(r"(?-u)[\n]"), - Expr::ClassBytes(bclass(&[(b'\n', b'\n')]))); - } - - #[test] - fn class_singleton_negate() { - assert_eq!(p(r"[^a]"), Expr::Class(class(&[ - ('\x00', '\x60'), ('\x62', '\u{10FFFF}'), - ]))); - assert_eq!(p(r"[^\x00]"), Expr::Class(class(&[ - ('\x01', '\u{10FFFF}'), - ]))); - assert_eq!(p(r"[^\n]"), Expr::Class(class(&[ - ('\x00', '\x09'), ('\x0b', '\u{10FFFF}'), - ]))); - assert_eq!(p("[^\n]"), Expr::Class(class(&[ - ('\x00', '\x09'), ('\x0b', '\u{10FFFF}'), - ]))); - - assert_eq!(pb(r"(?-u)[^a]"), Expr::ClassBytes(bclass(&[ - (0x00, 0x60), (0x62, 0xFF), - ]))); - assert_eq!(pb(r"(?-u)[^\x00]"), Expr::ClassBytes(bclass(&[ - (0x01, 0xFF), - ]))); - assert_eq!(pb(r"(?-u)[^\n]"), Expr::ClassBytes(bclass(&[ - (0x00, 0x09), (0x0B, 0xFF), - ]))); - assert_eq!(pb("(?-u)[^\n]"), Expr::ClassBytes(bclass(&[ - (0x00, 0x09), (0x0B, 0xFF), - ]))); - } - - #[test] - fn class_singleton_class() { - assert_eq!(p(r"[\d]"), Expr::Class(class(PERLD))); - assert_eq!(p(r"[\p{Yi}]"), Expr::Class(class(YI))); - - let bytes = class(PERLD).to_byte_class(); - assert_eq!(pb(r"(?-u)[\d]"), Expr::ClassBytes(bytes)); - } - - #[test] - fn class_singleton_class_negate() { - assert_eq!(p(r"[^\d]"), Expr::Class(class(PERLD).negate())); - assert_eq!(p(r"[^\w]"), Expr::Class(class(PERLW).negate())); - assert_eq!(p(r"[^\s]"), Expr::Class(class(PERLS).negate())); - - let bytes = asciid_bytes().negate(); - assert_eq!(pb(r"(?-u)[^\d]"), Expr::ClassBytes(bytes)); - let bytes = asciiw_bytes().negate(); - assert_eq!(pb(r"(?-u)[^\w]"), Expr::ClassBytes(bytes)); - let bytes = asciis_bytes().negate(); - assert_eq!(pb(r"(?-u)[^\s]"), Expr::ClassBytes(bytes)); - } - - #[test] - fn class_singleton_class_negate_negate() { - assert_eq!(p(r"[^\D]"), Expr::Class(class(PERLD))); - assert_eq!(p(r"[^\W]"), Expr::Class(class(PERLW))); - assert_eq!(p(r"[^\S]"), Expr::Class(class(PERLS))); - - assert_eq!(pb(r"(?-u)[^\D]"), Expr::ClassBytes(asciid_bytes())); - assert_eq!(pb(r"(?-u)[^\W]"), Expr::ClassBytes(asciiw_bytes())); - assert_eq!(pb(r"(?-u)[^\S]"), Expr::ClassBytes(asciis_bytes())); - } - - #[test] - fn class_singleton_class_casei() { - assert_eq!(p(r"(?i)[\d]"), Expr::Class(class(PERLD).case_fold())); - assert_eq!(p(r"(?i)[\p{Yi}]"), Expr::Class(class(YI).case_fold())); - - assert_eq!(pb(r"(?i-u)[\d]"), - Expr::ClassBytes(asciid_bytes().case_fold())); - } - - #[test] - fn class_singleton_class_negate_casei() { - assert_eq!(p(r"(?i)[^\d]"), - Expr::Class(class(PERLD).case_fold().negate())); - assert_eq!(p(r"(?i)[^\w]"), - Expr::Class(class(PERLW).case_fold().negate())); - assert_eq!(p(r"(?i)[^\s]"), - Expr::Class(class(PERLS).case_fold().negate())); - - let bytes = asciid_bytes().case_fold().negate(); - assert_eq!(pb(r"(?i-u)[^\d]"), Expr::ClassBytes(bytes)); - let bytes = asciiw_bytes().case_fold().negate(); - assert_eq!(pb(r"(?i-u)[^\w]"), Expr::ClassBytes(bytes)); - let bytes = asciis_bytes().case_fold().negate(); - assert_eq!(pb(r"(?i-u)[^\s]"), Expr::ClassBytes(bytes)); - } - - #[test] - fn class_singleton_class_negate_negate_casei() { - assert_eq!(p(r"(?i)[^\D]"), Expr::Class(class(PERLD).case_fold())); - assert_eq!(p(r"(?i)[^\W]"), Expr::Class(class(PERLW).case_fold())); - assert_eq!(p(r"(?i)[^\S]"), Expr::Class(class(PERLS).case_fold())); - - assert_eq!(pb(r"(?i-u)[^\D]"), - Expr::ClassBytes(asciid_bytes().case_fold())); - assert_eq!(pb(r"(?i-u)[^\W]"), - Expr::ClassBytes(asciiw_bytes().case_fold())); - assert_eq!(pb(r"(?i-u)[^\S]"), - Expr::ClassBytes(asciis_bytes().case_fold())); - } - - #[test] - fn class_multiple_class() { - assert_eq!(p(r"[\d\p{Yi}]"), Expr::Class(classes(&[ - PERLD, YI, - ]))); - } - - #[test] - fn class_multiple_class_negate() { - assert_eq!(p(r"[^\d\p{Yi}]"), Expr::Class(classes(&[ - PERLD, YI, - ]).negate())); - } - - #[test] - fn class_multiple_class_negate_negate() { - let nperlw = class(PERLW).negate(); - let nyi = class(YI).negate(); - let cls = CharClass::empty().merge(nperlw).merge(nyi); - assert_eq!(p(r"[^\W\P{Yi}]"), Expr::Class(cls.negate())); - } - - #[test] - fn class_multiple_class_casei() { - assert_eq!(p(r"(?i)[\d\p{Yi}]"), Expr::Class(classes(&[ - PERLD, YI, - ]).case_fold())); - } - - #[test] - fn class_multiple_class_negate_casei() { - assert_eq!(p(r"(?i)[^\d\p{Yi}]"), Expr::Class(classes(&[ - PERLD, YI, - ]).case_fold().negate())); - } - - #[test] - fn class_multiple_class_negate_negate_casei() { - let nperlw = class(PERLW).negate(); - let nyi = class(YI).negate(); - let class = CharClass::empty().merge(nperlw).merge(nyi); - assert_eq!(p(r"(?i)[^\W\P{Yi}]"), - Expr::Class(class.case_fold().negate())); - } - - #[test] - fn class_class_hypen() { - assert_eq!(p(r"[\p{Yi}-]"), Expr::Class(classes(&[ - &[('-', '-')], YI, - ]))); - assert_eq!(p(r"[\p{Yi}-a]"), Expr::Class(classes(&[ - &[('-', '-')], &[('a', 'a')], YI, - ]))); - } - - #[test] - fn class_brackets() { - assert_eq!(p(r"[]]"), Expr::Class(class(&[(']', ']')]))); - assert_eq!(p(r"[]\[]"), Expr::Class(class(&[('[', '['), (']', ']')]))); - assert_eq!(p(r"[\[]]"), Expr::Concat(vec![ - Expr::Class(class(&[('[', '[')])), - lit(']'), - ])); - } - - #[test] - fn class_brackets_hypen() { - assert_eq!(p("[]-]"), Expr::Class(class(&[('-', '-'), (']', ']')]))); - assert_eq!(p("[-]]"), Expr::Concat(vec![ - Expr::Class(class(&[('-', '-')])), - lit(']'), - ])); - } - - #[test] - fn class_nested_class_union() { - assert_eq!(p(r"[c[a-b]]"), Expr::Class(class(&[('a', 'c')]))); - assert_eq!(p(r"[[a-b]]"), Expr::Class(class(&[('a', 'b')]))); - assert_eq!(p(r"[[c][a-b]]"), Expr::Class(class(&[('a', 'c')]))); - - assert_eq!(pb(r"(?-u)[c[a-b]]"), - Expr::ClassBytes(bclass(&[(b'a', b'c')]))); - assert_eq!(pb(r"(?-u)[[a-b]]"), - Expr::ClassBytes(bclass(&[(b'a', b'b')]))); - assert_eq!(pb(r"(?-u)[[c][a-b]]"), - Expr::ClassBytes(bclass(&[(b'a', b'c')]))); - } - - #[test] - fn class_nested_class_union_casei() { - assert_eq!(p(r"(?i)[c[a-b]]"), - Expr::Class(class(&[('a', 'c')]).case_fold())); - assert_eq!(p(r"(?i)[[a-b]]"), - Expr::Class(class(&[('a', 'b')]).case_fold())); - assert_eq!(p(r"(?i)[[c][a-b]]"), - Expr::Class(class(&[('a', 'c')]).case_fold())); - - assert_eq!(pb(r"(?i-u)[[\d]]"), - Expr::ClassBytes(asciid_bytes().case_fold())); - } - - #[test] - fn class_nested_class_negate() { - assert_eq!(p(r"[^[\d]]"), Expr::Class(class(PERLD).negate())); - assert_eq!(p(r"[[^\d]]"), Expr::Class(class(PERLD).negate())); - assert_eq!(p(r"[^[^\d]]"), Expr::Class(class(PERLD))); - assert_eq!(p(r"[^[\w]]"), Expr::Class(class(PERLW).negate())); - assert_eq!(p(r"[[^\w]]"), Expr::Class(class(PERLW).negate())); - assert_eq!(p(r"[^[^\w]]"), Expr::Class(class(PERLW))); - assert_eq!(p(r"[a-b[^c]]"), - Expr::Class(class(&[('\u{0}', 'b'), ('d', '\u{10FFFF}')]))); - - assert_eq!(pb(r"(?-u)[^[\d]]"), - Expr::ClassBytes(asciid_bytes().negate())); - assert_eq!(pb(r"(?-u)[[^\d]]"), - Expr::ClassBytes(asciid_bytes().negate())); - assert_eq!(pb(r"(?-u)[^[^\d]]"), - Expr::ClassBytes(asciid_bytes())); - assert_eq!(pb(r"(?-u)[^[\w]]"), - Expr::ClassBytes(asciiw_bytes().negate())); - assert_eq!(pb(r"(?-u)[[^\w]]"), - Expr::ClassBytes(asciiw_bytes().negate())); - assert_eq!(pb(r"(?-u)[^[^\w]]"), - Expr::ClassBytes(asciiw_bytes())); - assert_eq!(pb(r"(?-u)[a-b[^c]]"), - Expr::ClassBytes(bclass(&[(b'\x00', b'b'), (b'd', b'\xFF')]))) - } - - #[test] - fn class_nested_class_negate_casei() { - assert_eq!(p(r"(?i)[^[\d]]"), - Expr::Class(class(PERLD).case_fold().negate())); - assert_eq!(p(r"(?i)[[^\d]]"), - Expr::Class(class(PERLD).case_fold().negate())); - assert_eq!(p(r"(?i)[^[^\d]]"), - Expr::Class(class(PERLD).case_fold())); - assert_eq!(p(r"(?i)[^[\w]]"), - Expr::Class(class(PERLW).case_fold().negate())); - assert_eq!(p(r"(?i)[[^\w]]"), - Expr::Class(class(PERLW).case_fold().negate())); - assert_eq!(p(r"(?i)[^[^\w]]"), - Expr::Class(class(PERLW).case_fold())); - let mut cls = CharClass::empty().negate(); - cls.remove('c'); - cls.remove('C'); - assert_eq!(p(r"(?i)[a-b[^c]]"), Expr::Class(cls)); - - assert_eq!(pb(r"(?i-u)[^[\d]]"), - Expr::ClassBytes(asciid_bytes().case_fold().negate())); - assert_eq!(pb(r"(?i-u)[[^\d]]"), - Expr::ClassBytes(asciid_bytes().case_fold().negate())); - assert_eq!(pb(r"(?i-u)[^[^\d]]"), - Expr::ClassBytes(asciid_bytes().case_fold())); - assert_eq!(pb(r"(?i-u)[^[\w]]"), - Expr::ClassBytes(asciiw_bytes().case_fold().negate())); - assert_eq!(pb(r"(?i-u)[[^\w]]"), - Expr::ClassBytes(asciiw_bytes().case_fold().negate())); - assert_eq!(pb(r"(?i-u)[^[^\w]]"), - Expr::ClassBytes(asciiw_bytes().case_fold())); - let mut bytes = ByteClass::new(vec![]).negate(); - bytes.remove(b'c'); - bytes.remove(b'C'); - assert_eq!(pb(r"(?i-u)[a-b[^c]]"), Expr::ClassBytes(bytes)); - } - - #[test] - fn class_nested_class_brackets_hyphen() { - // This is confusing, but `]` is allowed if first character within a class - // It parses as a nested class with the `]` and `-` characters - assert_eq!(p(r"[[]-]]"), Expr::Class(class(&[('-', '-'), (']', ']')]))); - assert_eq!(p(r"[[\[]]"), Expr::Class(class(&[('[', '[')]))); - assert_eq!(p(r"[[\]]]"), Expr::Class(class(&[(']', ']')]))); - } - - #[test] - fn class_nested_class_deep_nesting() { - // Makes sure that implementation can handle deep nesting. - // With recursive parsing, this regex would blow the stack size. - use std::iter::repeat; - let nesting = 10_000; - let open: String = repeat("[").take(nesting).collect(); - let close: String = repeat("]").take(nesting).collect(); - let s = format!("{}a{}", open, close); - assert_eq!(p(&s), Expr::Class(class(&[('a', 'a')]))); - } - - #[test] - fn class_intersection_ranges() { - assert_eq!(p(r"[abc&&b-c]"), Expr::Class(class(&[('b', 'c')]))); - assert_eq!(p(r"[abc&&[b-c]]"), Expr::Class(class(&[('b', 'c')]))); - assert_eq!(p(r"[[abc]&&[b-c]]"), Expr::Class(class(&[('b', 'c')]))); - assert_eq!(p(r"[a-z&&b-y&&c-x]"), Expr::Class(class(&[('c', 'x')]))); - assert_eq!(p(r"[c-da-b&&a-d]"), Expr::Class(class(&[('a', 'd')]))); - assert_eq!(p(r"[a-d&&c-da-b]"), Expr::Class(class(&[('a', 'd')]))); - - assert_eq!(pb(r"(?-u)[abc&&b-c]"), - Expr::ClassBytes(bclass(&[(b'b', b'c')]))); - assert_eq!(pb(r"(?-u)[abc&&[b-c]]"), - Expr::ClassBytes(bclass(&[(b'b', b'c')]))); - assert_eq!(pb(r"(?-u)[[abc]&&[b-c]]"), - Expr::ClassBytes(bclass(&[(b'b', b'c')]))); - assert_eq!(pb(r"(?-u)[a-z&&b-y&&c-x]"), - Expr::ClassBytes(bclass(&[(b'c', b'x')]))); - assert_eq!(pb(r"(?-u)[c-da-b&&a-d]"), - Expr::ClassBytes(bclass(&[(b'a', b'd')]))); - } - - #[test] - fn class_intersection_ranges_casei() { - assert_eq!(p(r"(?i)[abc&&b-c]"), - Expr::Class(class(&[('b', 'c')]).case_fold())); - assert_eq!(p(r"(?i)[abc&&[b-c]]"), - Expr::Class(class(&[('b', 'c')]).case_fold())); - assert_eq!(p(r"(?i)[[abc]&&[b-c]]"), - Expr::Class(class(&[('b', 'c')]).case_fold())); - assert_eq!(p(r"(?i)[a-z&&b-y&&c-x]"), - Expr::Class(class(&[('c', 'x')]).case_fold())); - assert_eq!(p(r"(?i)[c-da-b&&a-d]"), - Expr::Class(class(&[('a', 'd')]).case_fold())); - - assert_eq!(pb(r"(?i-u)[abc&&b-c]"), - Expr::ClassBytes(bclass(&[(b'b', b'c')]).case_fold())); - assert_eq!(pb(r"(?i-u)[abc&&[b-c]]"), - Expr::ClassBytes(bclass(&[(b'b', b'c')]).case_fold())); - assert_eq!(pb(r"(?i-u)[[abc]&&[b-c]]"), - Expr::ClassBytes(bclass(&[(b'b', b'c')]).case_fold())); - assert_eq!(pb(r"(?i-u)[a-z&&b-y&&c-x]"), - Expr::ClassBytes(bclass(&[(b'c', b'x')]).case_fold())); - assert_eq!(pb(r"(?i-u)[c-da-b&&a-d]"), - Expr::ClassBytes(bclass(&[(b'a', b'd')]).case_fold())); - } - - #[test] - fn class_intersection_classes() { - assert_eq!(p(r"[\w&&\d]"), Expr::Class(class(PERLD))); - assert_eq!(p(r"[\w&&[[:ascii:]]]"), Expr::Class(asciiw())); - assert_eq!(p(r"[\x00-\xFF&&\pZ]"), - Expr::Class(class(&[('\u{20}', '\u{20}'), ('\u{a0}', '\u{a0}')]))); - - assert_eq!(pb(r"(?-u)[\w&&\d]"), Expr::ClassBytes(asciid_bytes())); - assert_eq!(pb(r"(?-u)[\w&&[[:ascii:]]]"), Expr::ClassBytes(asciiw_bytes())); - } - - #[test] - fn class_intersection_classes_casei() { - assert_eq!(p(r"(?i)[\w&&\d]"), Expr::Class(class(PERLD).case_fold())); - assert_eq!(p(r"(?i)[\w&&[[:ascii:]]]"), Expr::Class(asciiw().case_fold())); - assert_eq!(p(r"(?i)[\x00-\xFF&&\pZ]"), - Expr::Class(class(&[('\u{20}', '\u{20}'), ('\u{a0}', '\u{a0}')]))); - - assert_eq!(pb(r"(?i-u)[\w&&\d]"), Expr::ClassBytes(asciid_bytes().case_fold())); - assert_eq!(pb(r"(?i-u)[\w&&[[:ascii:]]]"), Expr::ClassBytes(asciiw_bytes().case_fold())); - } - - #[test] - fn class_intersection_negate() { - assert_eq!(p(r"[^\w&&\d]"), Expr::Class(class(PERLD).negate())); - assert_eq!(p(r"[^[\w&&\d]]"), Expr::Class(class(PERLD).negate())); - assert_eq!(p(r"[^[^\w&&\d]]"), Expr::Class(class(PERLD))); - assert_eq!(p(r"[\w&&[^\d]]"), - Expr::Class(class(PERLW).intersection(&class(PERLD).negate()))); - assert_eq!(p(r"[[^\w]&&[^\d]]"), - Expr::Class(class(PERLW).negate())); - - assert_eq!(pb(r"(?-u)[^\w&&\d]"), - Expr::ClassBytes(asciid_bytes().negate())); - assert_eq!(pb(r"(?-u)[^[\w&&\d]]"), - Expr::ClassBytes(asciid_bytes().negate())); - assert_eq!(pb(r"(?-u)[^[^\w&&\d]]"), - Expr::ClassBytes(asciid_bytes())); - assert_eq!(pb(r"(?-u)[\w&&[^\d]]"), - Expr::ClassBytes(asciiw().intersection(&asciid().negate()).to_byte_class())); - assert_eq!(pb(r"(?-u)[[^\w]&&[^\d]]"), - Expr::ClassBytes(asciiw_bytes().negate())); - } - - #[test] - fn class_intersection_negate_casei() { - assert_eq!(p(r"(?i)[^\w&&a-z]"), - Expr::Class(class(&[('a', 'z')]).case_fold().negate())); - assert_eq!(p(r"(?i)[^[\w&&a-z]]"), - Expr::Class(class(&[('a', 'z')]).case_fold().negate())); - assert_eq!(p(r"(?i)[^[^\w&&a-z]]"), - Expr::Class(class(&[('a', 'z')]).case_fold())); - assert_eq!(p(r"(?i)[\w&&[^a-z]]"), - Expr::Class( - class(PERLW).intersection(&class(&[('a', 'z')]) - .case_fold().negate()))); - assert_eq!(p(r"(?i)[[^\w]&&[^a-z]]"), - Expr::Class(class(PERLW).negate())); - - assert_eq!(pb(r"(?i-u)[^\w&&a-z]"), - Expr::ClassBytes(bclass(&[(b'a', b'z')]).case_fold().negate())); - assert_eq!(pb(r"(?i-u)[^[\w&&a-z]]"), - Expr::ClassBytes(bclass(&[(b'a', b'z')]).case_fold().negate())); - assert_eq!(pb(r"(?i-u)[^[^\w&&a-z]]"), - Expr::ClassBytes(bclass(&[(b'a', b'z')]).case_fold())); - assert_eq!(pb(r"(?i-u)[\w&&[^a-z]]"), - Expr::ClassBytes(bclass(&[(b'0', b'9'), (b'_', b'_')]))); - assert_eq!(pb(r"(?i-u)[[^\w]&&[^a-z]]"), - Expr::ClassBytes(asciiw_bytes().negate())); - } - - #[test] - fn class_intersection_caret() { - // In `[a^]`, `^` does not need to be escaped, so it makes sense that - // `^` is also allowed to be unescaped after `&&`. - assert_eq!(p(r"[\^&&^]"), Expr::Class(class(&[('^', '^')]))); - } - - #[test] - fn class_intersection_brackets_hyphen() { - // `]` needs to be escaped after `&&` because it is not at the start of the class. - assert_eq!(p(r"[]&&\]]"), Expr::Class(class(&[(']', ']')]))); - - assert_eq!(p(r"[-&&-]"), Expr::Class(class(&[('-', '-')]))); - } - - #[test] - fn class_intersection_ampersand() { - // Unescaped `&` after `&&` - assert_eq!(p(r"[\&&&&]"), Expr::Class(class(&[('&', '&')]))); - assert_eq!(p(r"[\&&&\&]"), Expr::Class(class(&[('&', '&')]))); - } - - #[test] - fn class_intersection_precedence() { - assert_eq!(p(r"[a-w&&[^c-g]z]"), Expr::Class(class(&[('a', 'b'), ('h', 'w')]))); - } - - #[test] - fn class_special_escaped_set_chars() { - // These tests ensure that some special characters require escaping - // for use in character classes. The intention is to use these - // characters to implement sets as described in UTS#18 RL1.3. Once - // that's done, these tests should be removed and replaced with others. - assert_eq!(p(r"[\[]"), Expr::Class(class(&[('[', '[')]))); - assert_eq!(p(r"[&]"), Expr::Class(class(&[('&', '&')]))); - assert_eq!(p(r"[\&]"), Expr::Class(class(&[('&', '&')]))); - assert_eq!(p(r"[\&\&]"), Expr::Class(class(&[('&', '&')]))); - assert_eq!(p(r"[\x00-&]"), Expr::Class(class(&[('\u{0}', '&')]))); - assert_eq!(p(r"[&-\xFF]"), Expr::Class(class(&[('&', '\u{FF}')]))); - - assert_eq!(p(r"[~]"), Expr::Class(class(&[('~', '~')]))); - assert_eq!(p(r"[\~]"), Expr::Class(class(&[('~', '~')]))); - assert_eq!(p(r"[\~\~]"), Expr::Class(class(&[('~', '~')]))); - assert_eq!(p(r"[\x00-~]"), Expr::Class(class(&[('\u{0}', '~')]))); - assert_eq!(p(r"[~-\xFF]"), Expr::Class(class(&[('~', '\u{FF}')]))); - - assert_eq!(p(r"[+-\-]"), Expr::Class(class(&[('+', '-')]))); - assert_eq!(p(r"[a-a\--\xFF]"), Expr::Class(class(&[ - ('-', '\u{FF}'), - ]))); - } - - #[test] - fn class_overlapping() { - assert_eq!(p("[a-fd-h]"), Expr::Class(class(&[('a', 'h')]))); - assert_eq!(p("[a-fg-m]"), Expr::Class(class(&[('a', 'm')]))); - - assert_eq!(pb("(?-u)[a-fd-h]"), - Expr::ClassBytes(bclass(&[(b'a', b'h')]))); - assert_eq!(pb("(?-u)[a-fg-m]"), - Expr::ClassBytes(bclass(&[(b'a', b'm')]))); - } - - #[test] - fn ascii_classes() { - assert_eq!(p("[:blank:]"), Expr::Class(class(&[ - (':', ':'), ('a', 'b'), ('k', 'l'), ('n', 'n'), - ]))); - assert_eq!(p("[[:upper:]]"), Expr::Class(class(UPPER))); - - assert_eq!(pb("(?-u)[[:upper:]]"), - Expr::ClassBytes(class(UPPER).to_byte_class())); - } - - #[test] - fn ascii_classes_not() { - assert_eq!(p("[:abc:]"), - Expr::Class(class(&[(':', ':'), ('a', 'c')]))); - assert_eq!(pb("(?-u)[:abc:]"), - Expr::ClassBytes(bclass(&[(b':', b':'), (b'a', b'c')]))); - } - - #[test] - fn ascii_classes_multiple() { - assert_eq!(p("[[:lower:][:upper:]]"), - Expr::Class(classes(&[UPPER, LOWER]))); - - assert_eq!(pb("(?-u)[[:lower:][:upper:]]"), - Expr::ClassBytes(classes(&[UPPER, LOWER]).to_byte_class())); - } - - #[test] - fn ascii_classes_negate() { - assert_eq!(p("[[:^upper:]]"), Expr::Class(class(UPPER).negate())); - assert_eq!(p("[^[:^upper:]]"), Expr::Class(class(UPPER))); - - assert_eq!(pb("(?-u)[[:^upper:]]"), - Expr::ClassBytes(class(UPPER).to_byte_class().negate())); - assert_eq!(pb("(?-u)[^[:^upper:]]"), - Expr::ClassBytes(class(UPPER).to_byte_class())); - } - - #[test] - fn ascii_classes_negate_multiple() { - let (nlower, nword) = (class(LOWER).negate(), class(WORD).negate()); - let cls = CharClass::empty().merge(nlower).merge(nword); - assert_eq!(p("[[:^lower:][:^word:]]"), Expr::Class(cls.clone())); - assert_eq!(p("[^[:^lower:][:^word:]]"), Expr::Class(cls.negate())); - } - - #[test] - fn ascii_classes_case_fold() { - assert_eq!(p("(?i)[[:upper:]]"), - Expr::Class(class(UPPER).case_fold())); - - assert_eq!(pb("(?i-u)[[:upper:]]"), - Expr::ClassBytes(class(UPPER).to_byte_class().case_fold())); - } - - #[test] - fn ascii_classes_negate_case_fold() { - assert_eq!(p("(?i)[[:^upper:]]"), - Expr::Class(class(UPPER).case_fold().negate())); - assert_eq!(p("(?i)[^[:^upper:]]"), - Expr::Class(class(UPPER).case_fold())); - - assert_eq!(pb("(?i-u)[[:^upper:]]"), - Expr::ClassBytes( - class(UPPER).to_byte_class().case_fold().negate())); - assert_eq!(pb("(?i-u)[^[:^upper:]]"), - Expr::ClassBytes(class(UPPER).to_byte_class().case_fold())); - } - - #[test] - fn single_class_negate_case_fold() { - assert_eq!(p("(?i)[^x]"), - Expr::Class(class(&[('x', 'x')]).case_fold().negate())); - - assert_eq!(pb("(?i-u)[^x]"), - Expr::ClassBytes( - class(&[('x', 'x')]) - .to_byte_class().case_fold().negate())); - } - - #[test] - fn ignore_space_empty() { - assert_eq!(p("(?x) "), Expr::Empty); - } - - #[test] - fn ignore_space_literal() { - assert_eq!(p("(?x) a b c"), Expr::Concat(vec![ - lit('a'), lit('b'), lit('c'), - ])); - } - - #[test] - fn ignore_space_literal_off() { - assert_eq!(p("(?x) a b c(?-x) a"), Expr::Concat(vec![ - lit('a'), lit('b'), lit('c'), lit(' '), lit('a'), - ])); - } - - #[test] - fn ignore_space_class() { - assert_eq!(p("(?x)[a - - z -]"), Expr::Class(class(&[('a', 'z')]))); - assert_eq!(p("(?x)[ ^ a - - z -]"), Expr::Class(class(&[('a', 'z')]).negate())); - } - - #[test] - fn ignore_space_escape_octal() { - assert_eq!(p(r"(?x)\12 3"), Expr::Concat(vec![ - lit('\n'), - lit('3'), - ])); - } - - #[test] - fn ignore_space_escape_hex() { - assert_eq!(p(r"(?x)\x { 53 }"), lit('S')); - assert_eq!(p(r"(?x)\x # comment -{ # comment - 53 # comment -} # comment"), lit('S')); - } - - #[test] - fn ignore_space_escape_hex2() { - assert_eq!(p(r"(?x)\x 53"), lit('S')); - assert_eq!(p(r"(?x)\x # comment - 53 # comment"), lit('S')); - } - - #[test] - fn ignore_space_escape_unicode_name() { - assert_eq!(p(r"(?x)\p # comment -{ # comment - Yi # comment -} # comment"), Expr::Class(class(YI))); - } - - #[test] - fn ignore_space_repeat_counted() { - assert_eq!(p("(?x)a # comment -{ # comment - 5 # comment - , # comment - 10 # comment -}"), Expr::Repeat { - e: b(lit('a')), - r: Repeater::Range { min: 5, max: Some(10) }, - greedy: true, - }); - } - - #[test] - fn ignore_space_comments() { - assert_eq!(p(r"(?x)(?P<foo> - a # comment 1 -)(?P<bar> - z # comment 2 -)"), Expr::Concat(vec![ - Expr::Group { - e: Box::new(lit('a')), - i: Some(1), - name: Some("foo".into()), - }, - Expr::Group { - e: Box::new(lit('z')), - i: Some(2), - name: Some("bar".into()), - }, - ])); - } - - #[test] - fn ignore_space_comments_re_enable() { - assert_eq!(p(r"(?x)a # hi -(?-x:#) # sweet"), Expr::Concat(vec![ - lit('a'), - Expr::Group { - e: Box::new(lit('#')), - i: None, - name: None, - }, - ])); - } - - #[test] - fn ignore_space_escape_punctuation() { - assert_eq!(p(r"(?x)\\\.\+\*\?\(\)\|\[\]\{\}\^\$\#"), c(&[ - lit('\\'), lit('.'), lit('+'), lit('*'), lit('?'), - lit('('), lit(')'), lit('|'), lit('['), lit(']'), - lit('{'), lit('}'), lit('^'), lit('$'), lit('#'), - ])); - } - - #[test] - fn ignore_space_escape_hash() { - assert_eq!(p(r"(?x)a\# # hi there"), Expr::Concat(vec![ - lit('a'), - lit('#'), - ])); - } - - #[test] - fn ignore_space_escape_space() { - assert_eq!(p(r"(?x)a\ # hi there"), Expr::Concat(vec![ - lit('a'), - lit(' '), - ])); - } - - // Test every single possible error case. - - macro_rules! test_err { - ($re:expr, $pos:expr, $kind:expr) => { - test_err!($re, $pos, $kind, Flags::default()); - }; - ($re:expr, $pos:expr, $kind:expr, $flags:expr) => {{ - let err = Parser::parse($re, $flags).unwrap_err(); - assert_eq!($pos, err.pos); - assert_eq!($kind, err.kind); - assert!($re.contains(&err.surround)); - }} - } - - #[test] - fn invalid_utf8_not_allowed() { - // let flags = Flags { unicode: false, .. Flags::default() }; - test_err!(r"(?-u)\xFF", 9, ErrorKind::InvalidUtf8); - test_err!(r"(?-u).", 5, ErrorKind::InvalidUtf8); - test_err!(r"(?-u)(?s).", 9, ErrorKind::InvalidUtf8); - test_err!(r"(?-u)[\x00-\x80]", 15, ErrorKind::InvalidUtf8); - test_err!(r"(?-u)\222", 9, ErrorKind::InvalidUtf8); - test_err!(r"(?-u)\x{0080}", 13, ErrorKind::InvalidUtf8); - } - - #[test] - fn unicode_char_not_allowed() { - let flags = Flags { allow_bytes: true, .. Flags::default() }; - test_err!("☃(?-u:☃)", 7, ErrorKind::UnicodeNotAllowed, flags); - } - - #[test] - fn unicode_class_not_allowed() { - let flags = Flags { allow_bytes: true, .. Flags::default() }; - test_err!(r"☃(?-u:\pL)", 9, ErrorKind::UnicodeNotAllowed, flags); - } - - #[test] - fn unicode_class_literal_not_allowed() { - let flags = Flags { allow_bytes: true, .. Flags::default() }; - test_err!(r"(?-u)[☃]", 6, ErrorKind::UnicodeNotAllowed, flags); - test_err!(r"(?-u)[☃-☃]", 6, ErrorKind::UnicodeNotAllowed, flags); - } - - #[test] - fn unicode_hex_not_allowed() { - let flags = Flags { allow_bytes: true, .. Flags::default() }; - test_err!(r"(?-u)\x{FFFF}", 13, ErrorKind::UnicodeNotAllowed, flags); - test_err!(r"(?-u)\x{100}", 12, ErrorKind::UnicodeNotAllowed, flags); - } - - #[test] - fn unicode_octal_not_allowed() { - let flags = Flags { allow_bytes: true, .. Flags::default() }; - test_err!(r"(?-u)\400", 9, ErrorKind::UnicodeNotAllowed, flags); - } - - #[test] - fn error_repeat_no_expr_simple() { - test_err!("(*", 1, ErrorKind::RepeaterExpectsExpr); - } - - #[test] - fn error_repeat_no_expr_counted() { - test_err!("({5}", 1, ErrorKind::RepeaterExpectsExpr); - } - - #[test] - fn error_repeat_beginning_counted() { - test_err!("{5}", 0, ErrorKind::RepeaterExpectsExpr); - } - - #[test] - fn error_repeat_illegal_exprs_simple() { - test_err!("a**", 2, ErrorKind::RepeaterUnexpectedExpr(Expr::Repeat { - e: b(lit('a')), - r: Repeater::ZeroOrMore, - greedy: true, - })); - test_err!("a|*", 2, - ErrorKind::RepeaterUnexpectedExpr(Expr::Alternate(vec![lit('a')])) - ); - } - - #[test] - fn error_repeat_illegal_exprs_counted() { - test_err!("a*{5}", 2, ErrorKind::RepeaterUnexpectedExpr(Expr::Repeat { - e: b(lit('a')), - r: Repeater::ZeroOrMore, - greedy: true, - })); - test_err!("a|{5}", 2, - ErrorKind::RepeaterUnexpectedExpr(Expr::Alternate(vec![lit('a')])) - ); - } - - #[test] - fn error_repeat_empty_number() { - test_err!("a{}", 2, ErrorKind::MissingBase10); - } - - #[test] - fn error_repeat_eof() { - test_err!("a{5", 3, ErrorKind::UnclosedRepeat); - } - - #[test] - fn error_repeat_empty_number_eof() { - test_err!("a{xyz", 5, ErrorKind::InvalidBase10("xyz".into())); - test_err!("a{12,xyz", 8, ErrorKind::InvalidBase10("xyz".into())); - } - - #[test] - fn error_repeat_invalid_number() { - test_err!("a{9999999999}", 12, - ErrorKind::InvalidBase10("9999999999".into())); - test_err!("a{1,9999999999}", 14, - ErrorKind::InvalidBase10("9999999999".into())); - } - - #[test] - fn error_repeat_invalid_number_extra() { - test_err!("a{12x}", 5, ErrorKind::InvalidBase10("12x".into())); - test_err!("a{1,12x}", 7, ErrorKind::InvalidBase10("12x".into())); - } - - #[test] - fn error_repeat_invalid_range() { - test_err!("a{2,1}", 5, - ErrorKind::InvalidRepeatRange { min: 2, max: 1 }); - } - - #[test] - fn error_alternate_empty() { - test_err!("|a", 0, ErrorKind::EmptyAlternate); - } - - #[test] - fn error_alternate_empty_with_group() { - test_err!("(|a)", 1, ErrorKind::EmptyAlternate); - } - - #[test] - fn error_alternate_empty_with_alternate() { - test_err!("a||", 2, ErrorKind::EmptyAlternate); - } - - #[test] - fn error_close_paren_unopened_empty() { - test_err!(")", 0, ErrorKind::UnopenedParen); - } - - #[test] - fn error_close_paren_unopened() { - test_err!("ab)", 2, ErrorKind::UnopenedParen); - } - - #[test] - fn error_close_paren_unopened_with_alt() { - test_err!("a|b)", 3, ErrorKind::UnopenedParen); - } - - #[test] - fn error_close_paren_unclosed_with_alt() { - test_err!("(a|b", 0, ErrorKind::UnclosedParen); - } - - #[test] - fn error_close_paren_empty_alt() { - test_err!("(a|)", 3, ErrorKind::EmptyAlternate); - } - - #[test] - fn error_close_paren_empty_group() { - test_err!("()", 1, ErrorKind::EmptyGroup); - } - - #[test] - fn error_close_paren_empty_group_with_name() { - test_err!("(?P<foo>)", 8, ErrorKind::EmptyGroup); - } - - #[test] - fn error_finish_concat_unclosed() { - test_err!("ab(xy", 2, ErrorKind::UnclosedParen); - } - - #[test] - fn error_finish_concat_empty_alt() { - test_err!("a|", 2, ErrorKind::EmptyAlternate); - } - - #[test] - fn error_group_name_invalid() { - test_err!("(?P<a#>x)", 6, ErrorKind::InvalidCaptureName("a#".into())); - } - - #[test] - fn error_group_name_invalid_leading() { - test_err!("(?P<1a>a)", 6, ErrorKind::InvalidCaptureName("1a".into())); - } - - #[test] - fn error_group_name_unexpected_eof() { - test_err!("(?P<a", 5, ErrorKind::UnclosedCaptureName("a".into())); - } - - #[test] - fn error_group_name_empty() { - test_err!("(?P<>a)", 4, ErrorKind::EmptyCaptureName); - } - - #[test] - fn error_group_opts_unrecognized_flag() { - test_err!("(?z:a)", 2, ErrorKind::UnrecognizedFlag('z')); - } - - #[test] - fn error_group_opts_unexpected_eof() { - test_err!("(?i", 3, ErrorKind::UnexpectedFlagEof); - } - - #[test] - fn error_group_opts_double_negation() { - test_err!("(?-i-s:a)", 4, ErrorKind::DoubleFlagNegation); - } - - #[test] - fn error_group_opts_empty_negation() { - test_err!("(?i-:a)", 4, ErrorKind::EmptyFlagNegation); - } - - #[test] - fn error_group_opts_empty() { - test_err!("(?)", 2, ErrorKind::EmptyFlagNegation); - } - - #[test] - fn error_escape_unexpected_eof() { - test_err!(r"\", 1, ErrorKind::UnexpectedEscapeEof); - } - - #[test] - fn error_escape_unrecognized() { - test_err!(r"\m", 1, ErrorKind::UnrecognizedEscape('m')); - } - - #[test] - fn error_escape_hex2_eof0() { - test_err!(r"\x", 2, ErrorKind::UnexpectedTwoDigitHexEof); - } - - #[test] - fn error_escape_hex2_eof1() { - test_err!(r"\xA", 3, ErrorKind::UnexpectedTwoDigitHexEof); - } - - #[test] - fn error_escape_hex2_invalid() { - test_err!(r"\xAG", 4, ErrorKind::InvalidBase16("AG".into())); - } - - #[test] - fn error_escape_hex_eof0() { - test_err!(r"\x{", 3, ErrorKind::InvalidBase16("".into())); - } - - #[test] - fn error_escape_hex_eof1() { - test_err!(r"\x{A", 4, ErrorKind::UnclosedHex); - } - - #[test] - fn error_escape_hex_invalid() { - test_err!(r"\x{AG}", 5, ErrorKind::InvalidBase16("AG".into())); - } - - #[test] - fn error_escape_hex_invalid_scalar_value_surrogate() { - test_err!(r"\x{D800}", 8, ErrorKind::InvalidScalarValue(0xD800)); - } - - #[test] - fn error_escape_hex_invalid_scalar_value_high() { - test_err!(r"\x{110000}", 10, ErrorKind::InvalidScalarValue(0x110000)); - } - - #[test] - fn error_escape_hex_invalid_u32() { - test_err!(r"\x{9999999999}", 13, - ErrorKind::InvalidBase16("9999999999".into())); - } - - #[test] - fn error_unicode_unclosed() { - test_err!(r"\p{", 3, ErrorKind::UnclosedUnicodeName); - test_err!(r"\p{Greek", 8, ErrorKind::UnclosedUnicodeName); - } - - #[test] - fn error_unicode_no_letter() { - test_err!(r"\p", 2, ErrorKind::UnexpectedEscapeEof); - } - - #[test] - fn error_unicode_unknown_letter() { - test_err!(r"\pA", 3, ErrorKind::UnrecognizedUnicodeClass("A".into())); - } - - #[test] - fn error_unicode_unknown_name() { - test_err!(r"\p{Yii}", 7, - ErrorKind::UnrecognizedUnicodeClass("Yii".into())); - } - - #[test] - fn error_class_eof_empty() { - test_err!("[", 1, ErrorKind::UnexpectedClassEof); - test_err!("[^", 2, ErrorKind::UnexpectedClassEof); - } - - #[test] - fn error_class_eof_non_empty() { - test_err!("[a", 2, ErrorKind::UnexpectedClassEof); - test_err!("[^a", 3, ErrorKind::UnexpectedClassEof); - } - - #[test] - fn error_class_eof_range() { - test_err!("[a-", 3, ErrorKind::UnexpectedClassEof); - test_err!("[^a-", 4, ErrorKind::UnexpectedClassEof); - test_err!("[---", 4, ErrorKind::UnexpectedClassEof); - } - - #[test] - fn error_class_invalid_escape() { - test_err!(r"[\pA]", 4, - ErrorKind::UnrecognizedUnicodeClass("A".into())); - } - - #[test] - fn error_class_valid_escape_not_allowed() { - test_err!(r"[\A]", 3, ErrorKind::InvalidClassEscape(Expr::StartText)); - } - - #[test] - fn error_class_range_valid_escape_not_allowed() { - test_err!(r"[a-\d]", 5, - ErrorKind::InvalidClassEscape(Expr::Class(class(PERLD)))); - test_err!(r"[a-\A]", 5, - ErrorKind::InvalidClassEscape(Expr::StartText)); - test_err!(r"[\A-a]", 3, - ErrorKind::InvalidClassEscape(Expr::StartText)); - } - - #[test] - fn error_class_invalid_range() { - test_err!("[z-a]", 4, ErrorKind::InvalidClassRange { - start: 'z', - end: 'a', - }); - } - - #[test] - fn error_class_empty_range() { - test_err!("[]", 2, ErrorKind::UnexpectedClassEof); - test_err!("[^]", 3, ErrorKind::UnexpectedClassEof); - test_err!(r"[^\d\D]", 7, ErrorKind::EmptyClass); - - let flags = Flags { allow_bytes: true, .. Flags::default() }; - test_err!(r"(?-u)[^\x00-\xFF]", 17, ErrorKind::EmptyClass, flags); - } - - #[test] - fn error_class_unsupported_char() { - // These tests ensure that some unescaped special characters are - // rejected in character classes. The intention is to use these - // characters to implement sets as described in UTS#18 RL1.3. Once - // that's done, these tests should be removed and replaced with others. - test_err!("[~~]", 2, ErrorKind::UnsupportedClassChar('~')); - test_err!("[+--]", 4, ErrorKind::UnsupportedClassChar('-')); - test_err!(r"[a-a--\xFF]", 5, ErrorKind::UnsupportedClassChar('-')); - test_err!(r"[a&&~~]", 5, ErrorKind::UnsupportedClassChar('~')); - test_err!(r"[a&&--]", 5, ErrorKind::UnsupportedClassChar('-')); - } - - #[test] - fn error_class_nested_class() { - test_err!(r"[[]]", 4, ErrorKind::UnexpectedClassEof); - test_err!(r"[[][]]", 6, ErrorKind::UnexpectedClassEof); - test_err!(r"[[^\d\D]]", 8, ErrorKind::EmptyClass); - test_err!(r"[[]", 3, ErrorKind::UnexpectedClassEof); - test_err!(r"[[^]", 4, ErrorKind::UnexpectedClassEof); - } - - #[test] - fn error_class_intersection() { - test_err!(r"[&&]", 4, ErrorKind::EmptyClass); - test_err!(r"[a&&]", 5, ErrorKind::EmptyClass); - test_err!(r"[&&&&]", 6, ErrorKind::EmptyClass); - // `]` after `&&` is not the same as in (`[]]`), because it's also not - // allowed unescaped in `[a]]`. - test_err!(r"[]&&]]", 5, ErrorKind::EmptyClass); - - let flags = Flags { allow_bytes: true, .. Flags::default() }; - test_err!(r"(?-u)[a&&\pZ]", 12, ErrorKind::UnicodeNotAllowed, flags); - } - - #[test] - fn error_duplicate_capture_name() { - test_err!("(?P<a>.)(?P<a>.)", 14, - ErrorKind::DuplicateCaptureName("a".into())); - } - - #[test] - fn error_ignore_space_escape_hex() { - test_err!(r"(?x)\x{ 5 3 }", 10, ErrorKind::UnclosedHex); - } - - #[test] - fn error_ignore_space_escape_hex2() { - test_err!(r"(?x)\x 5 3", 9, ErrorKind::InvalidBase16("5 ".into())); - } - - #[test] - fn error_ignore_space_escape_unicode_name() { - test_err!(r"(?x)\p{Y i}", 9, ErrorKind::UnclosedUnicodeName); - } -} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.4.2/src/properties.rs cargo-0.26.0/vendor/regex-syntax-0.4.2/src/properties.rs --- cargo-0.25.0/vendor/regex-syntax-0.4.2/src/properties.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.4.2/src/properties.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,482 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use quickcheck::{Arbitrary, Gen, Testable, QuickCheck, StdGen}; - -use { - Expr, ExprBuilder, - CharClass, ClassRange, ByteClass, ByteRange, Repeater, dec_char, -}; - -fn qc<T: Testable>(t: T) { - QuickCheck::new() - .tests(10_000) - .max_tests(20_000) - .quickcheck(t); -} - -fn class(ranges: &[(char, char)]) -> CharClass { - let ranges = ranges.iter().cloned() - .map(|(c1, c2)| ClassRange::new(c1, c2)).collect(); - CharClass::new(ranges) -} - -// Test invariants for canonicalizing character classes. - -#[test] -fn negate() { - fn prop(ranges: Vec<(char, char)>) -> bool { - let expected = class(&ranges).canonicalize(); - let got = class(&ranges).negate().negate(); - expected == got - } - qc(prop as fn(Vec<(char, char)>) -> bool); -} - -#[test] -fn classes_are_sorted_and_nonoverlapping() { - fn prop(ranges: Vec<(char, char)>) -> bool { - class(&ranges) - .canonicalize() - .windows(2) - .all(|w| w[0].end < dec_char(w[1].start)) - } - qc(prop as fn(Vec<(char, char)>) -> bool); -} - -#[test] -fn valid_class_ranges() { - fn prop(ranges: Vec<(char, char)>) -> bool { - class(&ranges).canonicalize().into_iter().all(|r| r.start <= r.end) - } - qc(prop as fn(Vec<(char, char)>) -> bool); -} - -#[test] -fn intersection() { - fn prop(ranges1: Vec<(char, char)>, ranges2: Vec<(char, char)>) -> bool { - let class1 = class(&ranges1).canonicalize(); - let class2 = class(&ranges2).canonicalize(); - - let mut expected = CharClass::empty(); - // This is inefficient but correct. - for range1 in &class1 { - for range2 in &class2 { - if let Some(intersection) = range1.intersection(range2) { - expected.ranges.push(intersection); - } - } - } - expected = expected.canonicalize(); - - let got = class1.intersection(&class2); - expected == got - } - qc(prop as fn(Vec<(char, char)>, Vec<(char, char)>) -> bool); -} - -/// A wrapper type for generating "regex-like" Unicode strings. -/// -/// In particular, this type's `Arbitrary` impl specifically biases toward -/// special regex characters to make test cases more interesting. -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -struct RegexLikeString(String); - -impl Arbitrary for RegexLikeString { - fn arbitrary<G: Gen>(g: &mut G) -> RegexLikeString { - const SPECIAL: &'static [char] = &[ - '\\', '.', '+', '*', '?', '(', ')', '|', '[', ']', '{', '}', - '^', '$', - ]; - // Generating random Unicode strings results in mostly uninteresting - // regexes. Namely, they'll mostly just be literals. - // To make properties using regex strings more interesting, we bias - // toward selecting characters of significance to a regex. - let size = { let s = g.size(); g.gen_range(0, s) }; - RegexLikeString((0..size).map(|_| { - if g.gen_weighted_bool(3) { - *g.choose(SPECIAL).unwrap() - } else { - g.gen() - } - }).collect()) - } - - fn shrink(&self) -> Box<Iterator<Item=RegexLikeString>> { - // The regular `String` shrinker is good enough. - Box::new(self.0.shrink().map(RegexLikeString)) - } -} - -/// A special type for generating small non-zero sized ASCII strings. -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] -struct SmallAscii(String); - -impl Arbitrary for SmallAscii { - fn arbitrary<G: Gen>(g: &mut G) -> SmallAscii { - use std::char::from_u32; - let size = g.gen_range(1, 5); - SmallAscii((0..size) - .map(|_| from_u32(g.gen_range(97, 123)).unwrap()) - .collect()) - } - - fn shrink(&self) -> Box<Iterator<Item=SmallAscii>> { - Box::new(self.0.shrink().map(SmallAscii)) - } -} - -#[test] -fn parser_never_panics() { - fn prop(s: RegexLikeString) -> bool { - let _ = Expr::parse(&s.0); true - } - qc(prop as fn(RegexLikeString) -> bool); -} - -// Testing entire expressions. -// -// We only have one test at the moment, but the machinery could be useful -// for other things. -// -// In particular, Russ Cox writes about testing regexes by comparing the -// strings they match with other regex implementations. A fuzzer/shrinker -// (which is what's implemented below) would be a great way to drive that -// process. ---AG - -impl Arbitrary for Expr { - fn arbitrary<G: Gen>(g: &mut G) -> Expr { - let e = fix_capture_indices(gen_expr(g, 0, ExprType::Anything)); - e.simplify(200).unwrap() - } - - fn shrink(&self) -> Box<Iterator<Item=Expr>> { - use Expr::*; - - let nada = || Box::new(None.into_iter()); - let es: Box<Iterator<Item=Expr>> = match *self { - Empty | AnyChar | AnyCharNoNL | AnyByte | AnyByteNoNL - | StartLine | EndLine | StartText | EndText - | WordBoundary | NotWordBoundary - | WordBoundaryAscii | NotWordBoundaryAscii => nada(), - Literal { ref chars, .. } if chars.len() == 1 => nada(), - Literal { ref chars, casei } => { - Box::new((chars.clone(), casei) - .shrink() - .filter(|&(ref chars, _)| chars.len() > 0) - .map(|(chars, casei)| { - Literal { chars: chars, casei: casei } - })) - } - LiteralBytes { ref bytes, .. } if bytes.len() == 1 => nada(), - LiteralBytes { ref bytes, casei } => { - Box::new((bytes.clone(), casei) - .shrink() - .filter(|&(ref bytes, _)| bytes.len() > 0) - .map(|(bytes, casei)| { - LiteralBytes { bytes: bytes, casei: casei } - })) - } - Class(ref cls) => Box::new(cls.shrink().map(Class)), - ClassBytes(ref cls) => Box::new(cls.shrink().map(ClassBytes)), - Group { ref e, ref i, ref name } => { - let (i, name) = (i.clone(), name.clone()); - Box::new((*e.clone()).shrink() - .chain((*e.clone()).shrink() - .map(move |e| Group { - e: Box::new(e), - i: i.clone(), - name: name.clone(), - }))) - } - Repeat { ref e, ref r, greedy } => { - Box::new((*e.clone(), r.clone()) - .shrink() - .filter(|&(ref e, _)| e.can_repeat()) - .map(move |(e, r)| Repeat { - e: Box::new(e), - r: r, - greedy: greedy, - })) - } - // Concat(ref es) if es.len() <= 2 => nada(), - Concat(ref es) => { - Box::new(es.clone() - .shrink() - .filter(|es| es.len() > 0) - .map(|mut es| if es.len() == 1 { - es.pop().unwrap() - } else { - Concat(es) - })) - } - // Alternate(ref es) if es.len() <= 2 => nada(), - Alternate(ref es) => { - Box::new(es.clone() - .shrink() - .filter(|es| es.len() > 0) - .map(|mut es| if es.len() == 1 { - es.pop().unwrap() - } else { - Alternate(es) - })) - } - }; - Box::new(es.map(|e| fix_capture_indices(e).simplify(200).unwrap())) - } -} - -enum ExprType { - NoSequences, // disallow concat/alternate - Anything, -} - -fn gen_expr<G: Gen>(g: &mut G, depth: u32, ty: ExprType) -> Expr { - use Expr::*; - let ub = match (depth as usize >= g.size(), ty) { - (true, _) => 16, - (false, ExprType::NoSequences) => 18, - (false, ExprType::Anything) => 20, - }; - match g.gen_range(1, ub) { - 0 => Empty, - 1 => Literal { - chars: SmallAscii::arbitrary(g).0.chars().collect(), - casei: g.gen(), - }, - 2 => LiteralBytes { - bytes: SmallAscii::arbitrary(g).0.as_bytes().to_owned(), - casei: g.gen(), - }, - 3 => AnyChar, - 4 => AnyCharNoNL, - 5 => AnyByte, - 6 => AnyByteNoNL, - 7 => Class(CharClass::arbitrary(g)), - 8 => StartLine, - 9 => EndLine, - 10 => StartText, - 11 => EndText, - 12 => WordBoundary, - 13 => NotWordBoundary, - 14 => WordBoundaryAscii, - 15 => NotWordBoundaryAscii, - 16 => gen_group_expr(g, depth + 1), - 17 => Repeat { - e: Box::new(gen_repeatable_expr(g, depth + 1)), - r: Repeater::arbitrary(g), - greedy: bool::arbitrary(g), - }, - 18 => { - let size = { let s = g.size(); g.gen_range(2, s) }; - Concat((0..size) - .map(|_| { - gen_expr(g, depth + 1, ExprType::NoSequences) - }) - .collect()) - } - 19 => { - let size = { let s = g.size(); g.gen_range(2, s) }; - Alternate((0..size) - .map(|_| { - gen_expr(g, depth + 1, ExprType::NoSequences) - }) - .collect()) - } - _ => unreachable!() - } -} - -fn gen_repeatable_expr<G: Gen>(g: &mut G, depth: u32) -> Expr { - use Expr::*; - match g.gen_range(1, 10) { - 0 => Empty, - 1 => Literal { - chars: vec![Arbitrary::arbitrary(g)], - casei: g.gen(), - }, - 2 => LiteralBytes { - bytes: vec![Arbitrary::arbitrary(g)], - casei: g.gen(), - }, - 3 => AnyChar, - 4 => AnyCharNoNL, - 5 => AnyByte, - 6 => AnyByteNoNL, - 7 => Class(CharClass::arbitrary(g)), - 8 => ClassBytes(ByteClass::arbitrary(g)), - 9 => gen_group_expr(g, depth + 1), - _ => unreachable!(), - } -} - -fn gen_group_expr<G: Gen>(g: &mut G, depth: u32) -> Expr { - let (i, name) = if g.gen() { - (None, None) - } else { - (Some(0), if g.gen() { - Some(SmallAscii::arbitrary(g).0) - } else { - None - }) - }; - Expr::Group { - e: Box::new(gen_expr(g, depth + 1, ExprType::Anything)), - i: i, - name: name, - } -} - -fn fix_capture_indices(e: Expr) -> Expr { - fn bx(e: Expr) -> Box<Expr> { Box::new(e) } - fn fix(e: Expr, capi: &mut usize, names: &mut Vec<String>) -> Expr { - use Expr::*; - match e { - Group { e, i: Some(_), mut name } => { - *capi += 1; - let i = *capi; - let mut dupe_name = false; - if let Some(ref n1) = name { - if names.iter().any(|n2| n1 == n2) { - dupe_name = true; - } else { - names.push(n1.clone()); - } - } - if dupe_name { name = None; } - Group { e: bx(fix(*e, capi, names)), i: Some(i), name: name } - } - Group { e, i, name } => { - Group { e: bx(fix(*e, capi, names)), i: i, name: name } - } - Repeat { e, r, greedy } => { - Repeat { e: bx(fix(*e, capi, names)), r: r, greedy: greedy } - } - Concat(es) => - Concat(es.into_iter().map(|e| fix(e, capi, names)).collect()), - Alternate(es) => - Alternate(es.into_iter().map(|e| fix(e, capi, names)).collect()), - e => e, - } - } - fix(e, &mut 0, &mut vec![]) -} - -impl Arbitrary for Repeater { - fn arbitrary<G: Gen>(g: &mut G) -> Repeater { - use Repeater::*; - match g.gen_range(0, 4) { - 0 => ZeroOrOne, - 1 => ZeroOrMore, - 2 => OneOrMore, - 3 => { - use std::cmp::{max, min}; - let n1 = Arbitrary::arbitrary(g); - let n2 = Arbitrary::arbitrary(g); - Range { - min: min(n1, n2), - max: if g.gen() { None } else { Some(max(n1, n2)) }, - } - }, - _ => unreachable!(), - } - } - - fn shrink(&self) -> Box<Iterator<Item=Repeater>> { - use Repeater::*; - match *self { - ZeroOrOne | ZeroOrMore | OneOrMore => Box::new(None.into_iter()), - Range { min, max } => { - Box::new((min, max) - .shrink() - .map(|(min, max)| Range { min: min, max: max })) - } - } - } -} - -impl Arbitrary for CharClass { - fn arbitrary<G: Gen>(g: &mut G) -> CharClass { - let mut ranges: Vec<ClassRange> = Arbitrary::arbitrary(g); - if ranges.is_empty() { - ranges.push(Arbitrary::arbitrary(g)); - } - let cls = CharClass { ranges: ranges }.canonicalize(); - if g.gen() { cls.case_fold() } else { cls } - } - - fn shrink(&self) -> Box<Iterator<Item=CharClass>> { - Box::new(self.ranges.clone() - .shrink() - .filter(|ranges| ranges.len() > 0) - .map(|ranges| CharClass { ranges: ranges }.canonicalize())) - } -} - -impl Arbitrary for ClassRange { - fn arbitrary<G: Gen>(g: &mut G) -> ClassRange { - use std::char::from_u32; - ClassRange::new( - from_u32(g.gen_range(97, 123)).unwrap(), - from_u32(g.gen_range(97, 123)).unwrap(), - ) - } - - fn shrink(&self) -> Box<Iterator<Item=ClassRange>> { - Box::new((self.start, self.end) - .shrink().map(|(s, e)| ClassRange::new(s, e))) - } -} - -impl Arbitrary for ByteClass { - fn arbitrary<G: Gen>(g: &mut G) -> ByteClass { - let mut ranges: Vec<ByteRange> = Arbitrary::arbitrary(g); - if ranges.is_empty() { - ranges.push(Arbitrary::arbitrary(g)); - } - let cls = ByteClass { ranges: ranges }.canonicalize(); - if g.gen() { cls.case_fold() } else { cls } - } - - fn shrink(&self) -> Box<Iterator<Item=ByteClass>> { - Box::new(self.ranges.clone() - .shrink() - .filter(|ranges| ranges.len() > 0) - .map(|ranges| ByteClass { ranges: ranges }.canonicalize())) - } -} - -impl Arbitrary for ByteRange { - fn arbitrary<G: Gen>(g: &mut G) -> ByteRange { - ByteRange::new(g.gen_range(97, 123), g.gen_range(97, 123)) - } - - fn shrink(&self) -> Box<Iterator<Item=ByteRange>> { - Box::new((self.start, self.end) - .shrink().map(|(s, e)| ByteRange::new(s, e))) - } -} - -#[test] -fn display_regex_roundtrips() { - // Given an AST, if we print it as a regex and then re-parse it, do we - // get back the same AST? - // A lot of this relies crucially on regex simplification. So this is - // testing `Expr::simplify` as much as it is testing the `Display` impl. - fn prop(e: Expr) -> bool { - let parser = ExprBuilder::new().allow_bytes(true); - e == parser.parse(&e.to_string()).unwrap() - } - QuickCheck::new() - .tests(10_000) - .max_tests(20_000) - .gen(StdGen::new(::rand::thread_rng(), 50)) - .quickcheck(prop as fn(Expr) -> bool); -} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.4.2/src/unicode.rs cargo-0.26.0/vendor/regex-syntax-0.4.2/src/unicode.rs --- cargo-0.25.0/vendor/regex-syntax-0.4.2/src/unicode.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.4.2/src/unicode.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,6018 +0,0 @@ -// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// NOTE: The following code was generated by "scripts/unicode.py", do not edit -// directly - -#![allow(warnings)] -pub mod general_category { - pub const C_table: &'static [(char, char)] = &[ - ('\u{0}', '\u{1f}'), ('\u{7f}', '\u{9f}'), ('\u{ad}', '\u{ad}'), - ('\u{378}', '\u{379}'), ('\u{380}', '\u{383}'), ('\u{38b}', '\u{38b}'), - ('\u{38d}', '\u{38d}'), ('\u{3a2}', '\u{3a2}'), ('\u{530}', '\u{530}'), - ('\u{557}', '\u{558}'), ('\u{560}', '\u{560}'), ('\u{588}', '\u{588}'), - ('\u{58b}', '\u{58c}'), ('\u{590}', '\u{590}'), ('\u{5c8}', '\u{5cf}'), - ('\u{5eb}', '\u{5ef}'), ('\u{5f5}', '\u{605}'), ('\u{61c}', '\u{61d}'), - ('\u{6dd}', '\u{6dd}'), ('\u{70e}', '\u{70f}'), ('\u{74b}', '\u{74c}'), - ('\u{7b2}', '\u{7bf}'), ('\u{7fb}', '\u{7ff}'), ('\u{82e}', '\u{82f}'), - ('\u{83f}', '\u{83f}'), ('\u{85c}', '\u{85d}'), ('\u{85f}', '\u{85f}'), - ('\u{86b}', '\u{89f}'), ('\u{8b5}', '\u{8b5}'), ('\u{8be}', '\u{8d3}'), - ('\u{8e2}', '\u{8e2}'), ('\u{984}', '\u{984}'), ('\u{98d}', '\u{98e}'), - ('\u{991}', '\u{992}'), ('\u{9a9}', '\u{9a9}'), ('\u{9b1}', '\u{9b1}'), - ('\u{9b3}', '\u{9b5}'), ('\u{9ba}', '\u{9bb}'), ('\u{9c5}', '\u{9c6}'), - ('\u{9c9}', '\u{9ca}'), ('\u{9cf}', '\u{9d6}'), ('\u{9d8}', '\u{9db}'), - ('\u{9de}', '\u{9de}'), ('\u{9e4}', '\u{9e5}'), ('\u{9fe}', '\u{a00}'), - ('\u{a04}', '\u{a04}'), ('\u{a0b}', '\u{a0e}'), ('\u{a11}', '\u{a12}'), - ('\u{a29}', '\u{a29}'), ('\u{a31}', '\u{a31}'), ('\u{a34}', '\u{a34}'), - ('\u{a37}', '\u{a37}'), ('\u{a3a}', '\u{a3b}'), ('\u{a3d}', '\u{a3d}'), - ('\u{a43}', '\u{a46}'), ('\u{a49}', '\u{a4a}'), ('\u{a4e}', '\u{a50}'), - ('\u{a52}', '\u{a58}'), ('\u{a5d}', '\u{a5d}'), ('\u{a5f}', '\u{a65}'), - ('\u{a76}', '\u{a80}'), ('\u{a84}', '\u{a84}'), ('\u{a8e}', '\u{a8e}'), - ('\u{a92}', '\u{a92}'), ('\u{aa9}', '\u{aa9}'), ('\u{ab1}', '\u{ab1}'), - ('\u{ab4}', '\u{ab4}'), ('\u{aba}', '\u{abb}'), ('\u{ac6}', '\u{ac6}'), - ('\u{aca}', '\u{aca}'), ('\u{ace}', '\u{acf}'), ('\u{ad1}', '\u{adf}'), - ('\u{ae4}', '\u{ae5}'), ('\u{af2}', '\u{af8}'), ('\u{b00}', '\u{b00}'), - ('\u{b04}', '\u{b04}'), ('\u{b0d}', '\u{b0e}'), ('\u{b11}', '\u{b12}'), - ('\u{b29}', '\u{b29}'), ('\u{b31}', '\u{b31}'), ('\u{b34}', '\u{b34}'), - ('\u{b3a}', '\u{b3b}'), ('\u{b45}', '\u{b46}'), ('\u{b49}', '\u{b4a}'), - ('\u{b4e}', '\u{b55}'), ('\u{b58}', '\u{b5b}'), ('\u{b5e}', '\u{b5e}'), - ('\u{b64}', '\u{b65}'), ('\u{b78}', '\u{b81}'), ('\u{b84}', '\u{b84}'), - ('\u{b8b}', '\u{b8d}'), ('\u{b91}', '\u{b91}'), ('\u{b96}', '\u{b98}'), - ('\u{b9b}', '\u{b9b}'), ('\u{b9d}', '\u{b9d}'), ('\u{ba0}', '\u{ba2}'), - ('\u{ba5}', '\u{ba7}'), ('\u{bab}', '\u{bad}'), ('\u{bba}', '\u{bbd}'), - ('\u{bc3}', '\u{bc5}'), ('\u{bc9}', '\u{bc9}'), ('\u{bce}', '\u{bcf}'), - ('\u{bd1}', '\u{bd6}'), ('\u{bd8}', '\u{be5}'), ('\u{bfb}', '\u{bff}'), - ('\u{c04}', '\u{c04}'), ('\u{c0d}', '\u{c0d}'), ('\u{c11}', '\u{c11}'), - ('\u{c29}', '\u{c29}'), ('\u{c3a}', '\u{c3c}'), ('\u{c45}', '\u{c45}'), - ('\u{c49}', '\u{c49}'), ('\u{c4e}', '\u{c54}'), ('\u{c57}', '\u{c57}'), - ('\u{c5b}', '\u{c5f}'), ('\u{c64}', '\u{c65}'), ('\u{c70}', '\u{c77}'), - ('\u{c84}', '\u{c84}'), ('\u{c8d}', '\u{c8d}'), ('\u{c91}', '\u{c91}'), - ('\u{ca9}', '\u{ca9}'), ('\u{cb4}', '\u{cb4}'), ('\u{cba}', '\u{cbb}'), - ('\u{cc5}', '\u{cc5}'), ('\u{cc9}', '\u{cc9}'), ('\u{cce}', '\u{cd4}'), - ('\u{cd7}', '\u{cdd}'), ('\u{cdf}', '\u{cdf}'), ('\u{ce4}', '\u{ce5}'), - ('\u{cf0}', '\u{cf0}'), ('\u{cf3}', '\u{cff}'), ('\u{d04}', '\u{d04}'), - ('\u{d0d}', '\u{d0d}'), ('\u{d11}', '\u{d11}'), ('\u{d45}', '\u{d45}'), - ('\u{d49}', '\u{d49}'), ('\u{d50}', '\u{d53}'), ('\u{d64}', '\u{d65}'), - ('\u{d80}', '\u{d81}'), ('\u{d84}', '\u{d84}'), ('\u{d97}', '\u{d99}'), - ('\u{db2}', '\u{db2}'), ('\u{dbc}', '\u{dbc}'), ('\u{dbe}', '\u{dbf}'), - ('\u{dc7}', '\u{dc9}'), ('\u{dcb}', '\u{dce}'), ('\u{dd5}', '\u{dd5}'), - ('\u{dd7}', '\u{dd7}'), ('\u{de0}', '\u{de5}'), ('\u{df0}', '\u{df1}'), - ('\u{df5}', '\u{e00}'), ('\u{e3b}', '\u{e3e}'), ('\u{e5c}', '\u{e80}'), - ('\u{e83}', '\u{e83}'), ('\u{e85}', '\u{e86}'), ('\u{e89}', '\u{e89}'), - ('\u{e8b}', '\u{e8c}'), ('\u{e8e}', '\u{e93}'), ('\u{e98}', '\u{e98}'), - ('\u{ea0}', '\u{ea0}'), ('\u{ea4}', '\u{ea4}'), ('\u{ea6}', '\u{ea6}'), - ('\u{ea8}', '\u{ea9}'), ('\u{eac}', '\u{eac}'), ('\u{eba}', '\u{eba}'), - ('\u{ebe}', '\u{ebf}'), ('\u{ec5}', '\u{ec5}'), ('\u{ec7}', '\u{ec7}'), - ('\u{ece}', '\u{ecf}'), ('\u{eda}', '\u{edb}'), ('\u{ee0}', '\u{eff}'), - ('\u{f48}', '\u{f48}'), ('\u{f6d}', '\u{f70}'), ('\u{f98}', '\u{f98}'), - ('\u{fbd}', '\u{fbd}'), ('\u{fcd}', '\u{fcd}'), ('\u{fdb}', '\u{fff}'), - ('\u{10c6}', '\u{10c6}'), ('\u{10c8}', '\u{10cc}'), ('\u{10ce}', - '\u{10cf}'), ('\u{1249}', '\u{1249}'), ('\u{124e}', '\u{124f}'), - ('\u{1257}', '\u{1257}'), ('\u{1259}', '\u{1259}'), ('\u{125e}', - '\u{125f}'), ('\u{1289}', '\u{1289}'), ('\u{128e}', '\u{128f}'), - ('\u{12b1}', '\u{12b1}'), ('\u{12b6}', '\u{12b7}'), ('\u{12bf}', - '\u{12bf}'), ('\u{12c1}', '\u{12c1}'), ('\u{12c6}', '\u{12c7}'), - ('\u{12d7}', '\u{12d7}'), ('\u{1311}', '\u{1311}'), ('\u{1316}', - '\u{1317}'), ('\u{135b}', '\u{135c}'), ('\u{137d}', '\u{137f}'), - ('\u{139a}', '\u{139f}'), ('\u{13f6}', '\u{13f7}'), ('\u{13fe}', - '\u{13ff}'), ('\u{169d}', '\u{169f}'), ('\u{16f9}', '\u{16ff}'), - ('\u{170d}', '\u{170d}'), ('\u{1715}', '\u{171f}'), ('\u{1737}', - '\u{173f}'), ('\u{1754}', '\u{175f}'), ('\u{176d}', '\u{176d}'), - ('\u{1771}', '\u{1771}'), ('\u{1774}', '\u{177f}'), ('\u{17de}', - '\u{17df}'), ('\u{17ea}', '\u{17ef}'), ('\u{17fa}', '\u{17ff}'), - ('\u{180e}', '\u{180f}'), ('\u{181a}', '\u{181f}'), ('\u{1878}', - '\u{187f}'), ('\u{18ab}', '\u{18af}'), ('\u{18f6}', '\u{18ff}'), - ('\u{191f}', '\u{191f}'), ('\u{192c}', '\u{192f}'), ('\u{193c}', - '\u{193f}'), ('\u{1941}', '\u{1943}'), ('\u{196e}', '\u{196f}'), - ('\u{1975}', '\u{197f}'), ('\u{19ac}', '\u{19af}'), ('\u{19ca}', - '\u{19cf}'), ('\u{19db}', '\u{19dd}'), ('\u{1a1c}', '\u{1a1d}'), - ('\u{1a5f}', '\u{1a5f}'), ('\u{1a7d}', '\u{1a7e}'), ('\u{1a8a}', - '\u{1a8f}'), ('\u{1a9a}', '\u{1a9f}'), ('\u{1aae}', '\u{1aaf}'), - ('\u{1abf}', '\u{1aff}'), ('\u{1b4c}', '\u{1b4f}'), ('\u{1b7d}', - '\u{1b7f}'), ('\u{1bf4}', '\u{1bfb}'), ('\u{1c38}', '\u{1c3a}'), - ('\u{1c4a}', '\u{1c4c}'), ('\u{1c89}', '\u{1cbf}'), ('\u{1cc8}', - '\u{1ccf}'), ('\u{1cfa}', '\u{1cff}'), ('\u{1dfa}', '\u{1dfa}'), - ('\u{1f16}', '\u{1f17}'), ('\u{1f1e}', '\u{1f1f}'), ('\u{1f46}', - '\u{1f47}'), ('\u{1f4e}', '\u{1f4f}'), ('\u{1f58}', '\u{1f58}'), - ('\u{1f5a}', '\u{1f5a}'), ('\u{1f5c}', '\u{1f5c}'), ('\u{1f5e}', - '\u{1f5e}'), ('\u{1f7e}', '\u{1f7f}'), ('\u{1fb5}', '\u{1fb5}'), - ('\u{1fc5}', '\u{1fc5}'), ('\u{1fd4}', '\u{1fd5}'), ('\u{1fdc}', - '\u{1fdc}'), ('\u{1ff0}', '\u{1ff1}'), ('\u{1ff5}', '\u{1ff5}'), - ('\u{1fff}', '\u{1fff}'), ('\u{200b}', '\u{200f}'), ('\u{202a}', - '\u{202e}'), ('\u{2060}', '\u{206f}'), ('\u{2072}', '\u{2073}'), - ('\u{208f}', '\u{208f}'), ('\u{209d}', '\u{209f}'), ('\u{20c0}', - '\u{20cf}'), ('\u{20f1}', '\u{20ff}'), ('\u{218c}', '\u{218f}'), - ('\u{2427}', '\u{243f}'), ('\u{244b}', '\u{245f}'), ('\u{2b74}', - '\u{2b75}'), ('\u{2b96}', '\u{2b97}'), ('\u{2bba}', '\u{2bbc}'), - ('\u{2bc9}', '\u{2bc9}'), ('\u{2bd3}', '\u{2beb}'), ('\u{2bf0}', - '\u{2bff}'), ('\u{2c2f}', '\u{2c2f}'), ('\u{2c5f}', '\u{2c5f}'), - ('\u{2cf4}', '\u{2cf8}'), ('\u{2d26}', '\u{2d26}'), ('\u{2d28}', - '\u{2d2c}'), ('\u{2d2e}', '\u{2d2f}'), ('\u{2d68}', '\u{2d6e}'), - ('\u{2d71}', '\u{2d7e}'), ('\u{2d97}', '\u{2d9f}'), ('\u{2da7}', - '\u{2da7}'), ('\u{2daf}', '\u{2daf}'), ('\u{2db7}', '\u{2db7}'), - ('\u{2dbf}', '\u{2dbf}'), ('\u{2dc7}', '\u{2dc7}'), ('\u{2dcf}', - '\u{2dcf}'), ('\u{2dd7}', '\u{2dd7}'), ('\u{2ddf}', '\u{2ddf}'), - ('\u{2e4a}', '\u{2e7f}'), ('\u{2e9a}', '\u{2e9a}'), ('\u{2ef4}', - '\u{2eff}'), ('\u{2fd6}', '\u{2fef}'), ('\u{2ffc}', '\u{2fff}'), - ('\u{3040}', '\u{3040}'), ('\u{3097}', '\u{3098}'), ('\u{3100}', - '\u{3104}'), ('\u{312f}', '\u{3130}'), ('\u{318f}', '\u{318f}'), - ('\u{31bb}', '\u{31bf}'), ('\u{31e4}', '\u{31ef}'), ('\u{321f}', - '\u{321f}'), ('\u{32ff}', '\u{32ff}'), ('\u{4db6}', '\u{4dbf}'), - ('\u{9feb}', '\u{9fff}'), ('\u{a48d}', '\u{a48f}'), ('\u{a4c7}', - '\u{a4cf}'), ('\u{a62c}', '\u{a63f}'), ('\u{a6f8}', '\u{a6ff}'), - ('\u{a7af}', '\u{a7af}'), ('\u{a7b8}', '\u{a7f6}'), ('\u{a82c}', - '\u{a82f}'), ('\u{a83a}', '\u{a83f}'), ('\u{a878}', '\u{a87f}'), - ('\u{a8c6}', '\u{a8cd}'), ('\u{a8da}', '\u{a8df}'), ('\u{a8fe}', - '\u{a8ff}'), ('\u{a954}', '\u{a95e}'), ('\u{a97d}', '\u{a97f}'), - ('\u{a9ce}', '\u{a9ce}'), ('\u{a9da}', '\u{a9dd}'), ('\u{a9ff}', - '\u{a9ff}'), ('\u{aa37}', '\u{aa3f}'), ('\u{aa4e}', '\u{aa4f}'), - ('\u{aa5a}', '\u{aa5b}'), ('\u{aac3}', '\u{aada}'), ('\u{aaf7}', - '\u{ab00}'), ('\u{ab07}', '\u{ab08}'), ('\u{ab0f}', '\u{ab10}'), - ('\u{ab17}', '\u{ab1f}'), ('\u{ab27}', '\u{ab27}'), ('\u{ab2f}', - '\u{ab2f}'), ('\u{ab66}', '\u{ab6f}'), ('\u{abee}', '\u{abef}'), - ('\u{abfa}', '\u{abff}'), ('\u{d7a4}', '\u{d7af}'), ('\u{d7c7}', - '\u{d7ca}'), ('\u{d7fc}', '\u{d7ff}'), ('\u{e000}', '\u{f8ff}'), - ('\u{fa6e}', '\u{fa6f}'), ('\u{fada}', '\u{faff}'), ('\u{fb07}', - '\u{fb12}'), ('\u{fb18}', '\u{fb1c}'), ('\u{fb37}', '\u{fb37}'), - ('\u{fb3d}', '\u{fb3d}'), ('\u{fb3f}', '\u{fb3f}'), ('\u{fb42}', - '\u{fb42}'), ('\u{fb45}', '\u{fb45}'), ('\u{fbc2}', '\u{fbd2}'), - ('\u{fd40}', '\u{fd4f}'), ('\u{fd90}', '\u{fd91}'), ('\u{fdc8}', - '\u{fdef}'), ('\u{fdfe}', '\u{fdff}'), ('\u{fe1a}', '\u{fe1f}'), - ('\u{fe53}', '\u{fe53}'), ('\u{fe67}', '\u{fe67}'), ('\u{fe6c}', - '\u{fe6f}'), ('\u{fe75}', '\u{fe75}'), ('\u{fefd}', '\u{ff00}'), - ('\u{ffbf}', '\u{ffc1}'), ('\u{ffc8}', '\u{ffc9}'), ('\u{ffd0}', - '\u{ffd1}'), ('\u{ffd8}', '\u{ffd9}'), ('\u{ffdd}', '\u{ffdf}'), - ('\u{ffe7}', '\u{ffe7}'), ('\u{ffef}', '\u{fffb}'), ('\u{fffe}', - '\u{ffff}'), ('\u{1000c}', '\u{1000c}'), ('\u{10027}', '\u{10027}'), - ('\u{1003b}', '\u{1003b}'), ('\u{1003e}', '\u{1003e}'), ('\u{1004e}', - '\u{1004f}'), ('\u{1005e}', '\u{1007f}'), ('\u{100fb}', '\u{100ff}'), - ('\u{10103}', '\u{10106}'), ('\u{10134}', '\u{10136}'), ('\u{1018f}', - '\u{1018f}'), ('\u{1019c}', '\u{1019f}'), ('\u{101a1}', '\u{101cf}'), - ('\u{101fe}', '\u{1027f}'), ('\u{1029d}', '\u{1029f}'), ('\u{102d1}', - '\u{102df}'), ('\u{102fc}', '\u{102ff}'), ('\u{10324}', '\u{1032c}'), - ('\u{1034b}', '\u{1034f}'), ('\u{1037b}', '\u{1037f}'), ('\u{1039e}', - '\u{1039e}'), ('\u{103c4}', '\u{103c7}'), ('\u{103d6}', '\u{103ff}'), - ('\u{1049e}', '\u{1049f}'), ('\u{104aa}', '\u{104af}'), ('\u{104d4}', - '\u{104d7}'), ('\u{104fc}', '\u{104ff}'), ('\u{10528}', '\u{1052f}'), - ('\u{10564}', '\u{1056e}'), ('\u{10570}', '\u{105ff}'), ('\u{10737}', - '\u{1073f}'), ('\u{10756}', '\u{1075f}'), ('\u{10768}', '\u{107ff}'), - ('\u{10806}', '\u{10807}'), ('\u{10809}', '\u{10809}'), ('\u{10836}', - '\u{10836}'), ('\u{10839}', '\u{1083b}'), ('\u{1083d}', '\u{1083e}'), - ('\u{10856}', '\u{10856}'), ('\u{1089f}', '\u{108a6}'), ('\u{108b0}', - '\u{108df}'), ('\u{108f3}', '\u{108f3}'), ('\u{108f6}', '\u{108fa}'), - ('\u{1091c}', '\u{1091e}'), ('\u{1093a}', '\u{1093e}'), ('\u{10940}', - '\u{1097f}'), ('\u{109b8}', '\u{109bb}'), ('\u{109d0}', '\u{109d1}'), - ('\u{10a04}', '\u{10a04}'), ('\u{10a07}', '\u{10a0b}'), ('\u{10a14}', - '\u{10a14}'), ('\u{10a18}', '\u{10a18}'), ('\u{10a34}', '\u{10a37}'), - ('\u{10a3b}', '\u{10a3e}'), ('\u{10a48}', '\u{10a4f}'), ('\u{10a59}', - '\u{10a5f}'), ('\u{10aa0}', '\u{10abf}'), ('\u{10ae7}', '\u{10aea}'), - ('\u{10af7}', '\u{10aff}'), ('\u{10b36}', '\u{10b38}'), ('\u{10b56}', - '\u{10b57}'), ('\u{10b73}', '\u{10b77}'), ('\u{10b92}', '\u{10b98}'), - ('\u{10b9d}', '\u{10ba8}'), ('\u{10bb0}', '\u{10bff}'), ('\u{10c49}', - '\u{10c7f}'), ('\u{10cb3}', '\u{10cbf}'), ('\u{10cf3}', '\u{10cf9}'), - ('\u{10d00}', '\u{10e5f}'), ('\u{10e7f}', '\u{10fff}'), ('\u{1104e}', - '\u{11051}'), ('\u{11070}', '\u{1107e}'), ('\u{110bd}', '\u{110bd}'), - ('\u{110c2}', '\u{110cf}'), ('\u{110e9}', '\u{110ef}'), ('\u{110fa}', - '\u{110ff}'), ('\u{11135}', '\u{11135}'), ('\u{11144}', '\u{1114f}'), - ('\u{11177}', '\u{1117f}'), ('\u{111ce}', '\u{111cf}'), ('\u{111e0}', - '\u{111e0}'), ('\u{111f5}', '\u{111ff}'), ('\u{11212}', '\u{11212}'), - ('\u{1123f}', '\u{1127f}'), ('\u{11287}', '\u{11287}'), ('\u{11289}', - '\u{11289}'), ('\u{1128e}', '\u{1128e}'), ('\u{1129e}', '\u{1129e}'), - ('\u{112aa}', '\u{112af}'), ('\u{112eb}', '\u{112ef}'), ('\u{112fa}', - '\u{112ff}'), ('\u{11304}', '\u{11304}'), ('\u{1130d}', '\u{1130e}'), - ('\u{11311}', '\u{11312}'), ('\u{11329}', '\u{11329}'), ('\u{11331}', - '\u{11331}'), ('\u{11334}', '\u{11334}'), ('\u{1133a}', '\u{1133b}'), - ('\u{11345}', '\u{11346}'), ('\u{11349}', '\u{1134a}'), ('\u{1134e}', - '\u{1134f}'), ('\u{11351}', '\u{11356}'), ('\u{11358}', '\u{1135c}'), - ('\u{11364}', '\u{11365}'), ('\u{1136d}', '\u{1136f}'), ('\u{11375}', - '\u{113ff}'), ('\u{1145a}', '\u{1145a}'), ('\u{1145c}', '\u{1145c}'), - ('\u{1145e}', '\u{1147f}'), ('\u{114c8}', '\u{114cf}'), ('\u{114da}', - '\u{1157f}'), ('\u{115b6}', '\u{115b7}'), ('\u{115de}', '\u{115ff}'), - ('\u{11645}', '\u{1164f}'), ('\u{1165a}', '\u{1165f}'), ('\u{1166d}', - '\u{1167f}'), ('\u{116b8}', '\u{116bf}'), ('\u{116ca}', '\u{116ff}'), - ('\u{1171a}', '\u{1171c}'), ('\u{1172c}', '\u{1172f}'), ('\u{11740}', - '\u{1189f}'), ('\u{118f3}', '\u{118fe}'), ('\u{11900}', '\u{119ff}'), - ('\u{11a48}', '\u{11a4f}'), ('\u{11a84}', '\u{11a85}'), ('\u{11a9d}', - '\u{11a9d}'), ('\u{11aa3}', '\u{11abf}'), ('\u{11af9}', '\u{11bff}'), - ('\u{11c09}', '\u{11c09}'), ('\u{11c37}', '\u{11c37}'), ('\u{11c46}', - '\u{11c4f}'), ('\u{11c6d}', '\u{11c6f}'), ('\u{11c90}', '\u{11c91}'), - ('\u{11ca8}', '\u{11ca8}'), ('\u{11cb7}', '\u{11cff}'), ('\u{11d07}', - '\u{11d07}'), ('\u{11d0a}', '\u{11d0a}'), ('\u{11d37}', '\u{11d39}'), - ('\u{11d3b}', '\u{11d3b}'), ('\u{11d3e}', '\u{11d3e}'), ('\u{11d48}', - '\u{11d4f}'), ('\u{11d5a}', '\u{11fff}'), ('\u{1239a}', '\u{123ff}'), - ('\u{1246f}', '\u{1246f}'), ('\u{12475}', '\u{1247f}'), ('\u{12544}', - '\u{12fff}'), ('\u{1342f}', '\u{143ff}'), ('\u{14647}', '\u{167ff}'), - ('\u{16a39}', '\u{16a3f}'), ('\u{16a5f}', '\u{16a5f}'), ('\u{16a6a}', - '\u{16a6d}'), ('\u{16a70}', '\u{16acf}'), ('\u{16aee}', '\u{16aef}'), - ('\u{16af6}', '\u{16aff}'), ('\u{16b46}', '\u{16b4f}'), ('\u{16b5a}', - '\u{16b5a}'), ('\u{16b62}', '\u{16b62}'), ('\u{16b78}', '\u{16b7c}'), - ('\u{16b90}', '\u{16eff}'), ('\u{16f45}', '\u{16f4f}'), ('\u{16f7f}', - '\u{16f8e}'), ('\u{16fa0}', '\u{16fdf}'), ('\u{16fe2}', '\u{16fff}'), - ('\u{187ed}', '\u{187ff}'), ('\u{18af3}', '\u{1afff}'), ('\u{1b11f}', - '\u{1b16f}'), ('\u{1b2fc}', '\u{1bbff}'), ('\u{1bc6b}', '\u{1bc6f}'), - ('\u{1bc7d}', '\u{1bc7f}'), ('\u{1bc89}', '\u{1bc8f}'), ('\u{1bc9a}', - '\u{1bc9b}'), ('\u{1bca0}', '\u{1cfff}'), ('\u{1d0f6}', '\u{1d0ff}'), - ('\u{1d127}', '\u{1d128}'), ('\u{1d173}', '\u{1d17a}'), ('\u{1d1e9}', - '\u{1d1ff}'), ('\u{1d246}', '\u{1d2ff}'), ('\u{1d357}', '\u{1d35f}'), - ('\u{1d372}', '\u{1d3ff}'), ('\u{1d455}', '\u{1d455}'), ('\u{1d49d}', - '\u{1d49d}'), ('\u{1d4a0}', '\u{1d4a1}'), ('\u{1d4a3}', '\u{1d4a4}'), - ('\u{1d4a7}', '\u{1d4a8}'), ('\u{1d4ad}', '\u{1d4ad}'), ('\u{1d4ba}', - '\u{1d4ba}'), ('\u{1d4bc}', '\u{1d4bc}'), ('\u{1d4c4}', '\u{1d4c4}'), - ('\u{1d506}', '\u{1d506}'), ('\u{1d50b}', '\u{1d50c}'), ('\u{1d515}', - '\u{1d515}'), ('\u{1d51d}', '\u{1d51d}'), ('\u{1d53a}', '\u{1d53a}'), - ('\u{1d53f}', '\u{1d53f}'), ('\u{1d545}', '\u{1d545}'), ('\u{1d547}', - '\u{1d549}'), ('\u{1d551}', '\u{1d551}'), ('\u{1d6a6}', '\u{1d6a7}'), - ('\u{1d7cc}', '\u{1d7cd}'), ('\u{1da8c}', '\u{1da9a}'), ('\u{1daa0}', - '\u{1daa0}'), ('\u{1dab0}', '\u{1dfff}'), ('\u{1e007}', '\u{1e007}'), - ('\u{1e019}', '\u{1e01a}'), ('\u{1e022}', '\u{1e022}'), ('\u{1e025}', - '\u{1e025}'), ('\u{1e02b}', '\u{1e7ff}'), ('\u{1e8c5}', '\u{1e8c6}'), - ('\u{1e8d7}', '\u{1e8ff}'), ('\u{1e94b}', '\u{1e94f}'), ('\u{1e95a}', - '\u{1e95d}'), ('\u{1e960}', '\u{1edff}'), ('\u{1ee04}', '\u{1ee04}'), - ('\u{1ee20}', '\u{1ee20}'), ('\u{1ee23}', '\u{1ee23}'), ('\u{1ee25}', - '\u{1ee26}'), ('\u{1ee28}', '\u{1ee28}'), ('\u{1ee33}', '\u{1ee33}'), - ('\u{1ee38}', '\u{1ee38}'), ('\u{1ee3a}', '\u{1ee3a}'), ('\u{1ee3c}', - '\u{1ee41}'), ('\u{1ee43}', '\u{1ee46}'), ('\u{1ee48}', '\u{1ee48}'), - ('\u{1ee4a}', '\u{1ee4a}'), ('\u{1ee4c}', '\u{1ee4c}'), ('\u{1ee50}', - '\u{1ee50}'), ('\u{1ee53}', '\u{1ee53}'), ('\u{1ee55}', '\u{1ee56}'), - ('\u{1ee58}', '\u{1ee58}'), ('\u{1ee5a}', '\u{1ee5a}'), ('\u{1ee5c}', - '\u{1ee5c}'), ('\u{1ee5e}', '\u{1ee5e}'), ('\u{1ee60}', '\u{1ee60}'), - ('\u{1ee63}', '\u{1ee63}'), ('\u{1ee65}', '\u{1ee66}'), ('\u{1ee6b}', - '\u{1ee6b}'), ('\u{1ee73}', '\u{1ee73}'), ('\u{1ee78}', '\u{1ee78}'), - ('\u{1ee7d}', '\u{1ee7d}'), ('\u{1ee7f}', '\u{1ee7f}'), ('\u{1ee8a}', - '\u{1ee8a}'), ('\u{1ee9c}', '\u{1eea0}'), ('\u{1eea4}', '\u{1eea4}'), - ('\u{1eeaa}', '\u{1eeaa}'), ('\u{1eebc}', '\u{1eeef}'), ('\u{1eef2}', - '\u{1efff}'), ('\u{1f02c}', '\u{1f02f}'), ('\u{1f094}', '\u{1f09f}'), - ('\u{1f0af}', '\u{1f0b0}'), ('\u{1f0c0}', '\u{1f0c0}'), ('\u{1f0d0}', - '\u{1f0d0}'), ('\u{1f0f6}', '\u{1f0ff}'), ('\u{1f10d}', '\u{1f10f}'), - ('\u{1f12f}', '\u{1f12f}'), ('\u{1f16c}', '\u{1f16f}'), ('\u{1f1ad}', - '\u{1f1e5}'), ('\u{1f203}', '\u{1f20f}'), ('\u{1f23c}', '\u{1f23f}'), - ('\u{1f249}', '\u{1f24f}'), ('\u{1f252}', '\u{1f25f}'), ('\u{1f266}', - '\u{1f2ff}'), ('\u{1f6d5}', '\u{1f6df}'), ('\u{1f6ed}', '\u{1f6ef}'), - ('\u{1f6f9}', '\u{1f6ff}'), ('\u{1f774}', '\u{1f77f}'), ('\u{1f7d5}', - '\u{1f7ff}'), ('\u{1f80c}', '\u{1f80f}'), ('\u{1f848}', '\u{1f84f}'), - ('\u{1f85a}', '\u{1f85f}'), ('\u{1f888}', '\u{1f88f}'), ('\u{1f8ae}', - '\u{1f8ff}'), ('\u{1f90c}', '\u{1f90f}'), ('\u{1f93f}', '\u{1f93f}'), - ('\u{1f94d}', '\u{1f94f}'), ('\u{1f96c}', '\u{1f97f}'), ('\u{1f998}', - '\u{1f9bf}'), ('\u{1f9c1}', '\u{1f9cf}'), ('\u{1f9e7}', '\u{1ffff}'), - ('\u{2a6d7}', '\u{2a6ff}'), ('\u{2b735}', '\u{2b73f}'), ('\u{2b81e}', - '\u{2b81f}'), ('\u{2cea2}', '\u{2ceaf}'), ('\u{2ebe1}', '\u{2f7ff}'), - ('\u{2fa1e}', '\u{e00ff}'), ('\u{e01f0}', '\u{10ffff}') - ]; - - pub const Cc_table: &'static [(char, char)] = &[ - ('\u{0}', '\u{1f}'), ('\u{7f}', '\u{9f}') - ]; - - pub const Cf_table: &'static [(char, char)] = &[ - ('\u{ad}', '\u{ad}'), ('\u{600}', '\u{605}'), ('\u{61c}', '\u{61c}'), - ('\u{6dd}', '\u{6dd}'), ('\u{70f}', '\u{70f}'), ('\u{8e2}', '\u{8e2}'), - ('\u{180e}', '\u{180e}'), ('\u{200b}', '\u{200f}'), ('\u{202a}', - '\u{202e}'), ('\u{2060}', '\u{2064}'), ('\u{2066}', '\u{206f}'), - ('\u{feff}', '\u{feff}'), ('\u{fff9}', '\u{fffb}'), ('\u{110bd}', - '\u{110bd}'), ('\u{1bca0}', '\u{1bca3}'), ('\u{1d173}', '\u{1d17a}'), - ('\u{e0001}', '\u{e0001}'), ('\u{e0020}', '\u{e007f}') - ]; - - pub const Cn_table: &'static [(char, char)] = &[ - ('\u{378}', '\u{379}'), ('\u{380}', '\u{383}'), ('\u{38b}', '\u{38b}'), - ('\u{38d}', '\u{38d}'), ('\u{3a2}', '\u{3a2}'), ('\u{530}', '\u{530}'), - ('\u{557}', '\u{558}'), ('\u{560}', '\u{560}'), ('\u{588}', '\u{588}'), - ('\u{58b}', '\u{58c}'), ('\u{590}', '\u{590}'), ('\u{5c8}', '\u{5cf}'), - ('\u{5eb}', '\u{5ef}'), ('\u{5f5}', '\u{5ff}'), ('\u{61d}', '\u{61d}'), - ('\u{70e}', '\u{70e}'), ('\u{74b}', '\u{74c}'), ('\u{7b2}', '\u{7bf}'), - ('\u{7fb}', '\u{7ff}'), ('\u{82e}', '\u{82f}'), ('\u{83f}', '\u{83f}'), - ('\u{85c}', '\u{85d}'), ('\u{85f}', '\u{85f}'), ('\u{86b}', '\u{89f}'), - ('\u{8b5}', '\u{8b5}'), ('\u{8be}', '\u{8d3}'), ('\u{984}', '\u{984}'), - ('\u{98d}', '\u{98e}'), ('\u{991}', '\u{992}'), ('\u{9a9}', '\u{9a9}'), - ('\u{9b1}', '\u{9b1}'), ('\u{9b3}', '\u{9b5}'), ('\u{9ba}', '\u{9bb}'), - ('\u{9c5}', '\u{9c6}'), ('\u{9c9}', '\u{9ca}'), ('\u{9cf}', '\u{9d6}'), - ('\u{9d8}', '\u{9db}'), ('\u{9de}', '\u{9de}'), ('\u{9e4}', '\u{9e5}'), - ('\u{9fe}', '\u{a00}'), ('\u{a04}', '\u{a04}'), ('\u{a0b}', '\u{a0e}'), - ('\u{a11}', '\u{a12}'), ('\u{a29}', '\u{a29}'), ('\u{a31}', '\u{a31}'), - ('\u{a34}', '\u{a34}'), ('\u{a37}', '\u{a37}'), ('\u{a3a}', '\u{a3b}'), - ('\u{a3d}', '\u{a3d}'), ('\u{a43}', '\u{a46}'), ('\u{a49}', '\u{a4a}'), - ('\u{a4e}', '\u{a50}'), ('\u{a52}', '\u{a58}'), ('\u{a5d}', '\u{a5d}'), - ('\u{a5f}', '\u{a65}'), ('\u{a76}', '\u{a80}'), ('\u{a84}', '\u{a84}'), - ('\u{a8e}', '\u{a8e}'), ('\u{a92}', '\u{a92}'), ('\u{aa9}', '\u{aa9}'), - ('\u{ab1}', '\u{ab1}'), ('\u{ab4}', '\u{ab4}'), ('\u{aba}', '\u{abb}'), - ('\u{ac6}', '\u{ac6}'), ('\u{aca}', '\u{aca}'), ('\u{ace}', '\u{acf}'), - ('\u{ad1}', '\u{adf}'), ('\u{ae4}', '\u{ae5}'), ('\u{af2}', '\u{af8}'), - ('\u{b00}', '\u{b00}'), ('\u{b04}', '\u{b04}'), ('\u{b0d}', '\u{b0e}'), - ('\u{b11}', '\u{b12}'), ('\u{b29}', '\u{b29}'), ('\u{b31}', '\u{b31}'), - ('\u{b34}', '\u{b34}'), ('\u{b3a}', '\u{b3b}'), ('\u{b45}', '\u{b46}'), - ('\u{b49}', '\u{b4a}'), ('\u{b4e}', '\u{b55}'), ('\u{b58}', '\u{b5b}'), - ('\u{b5e}', '\u{b5e}'), ('\u{b64}', '\u{b65}'), ('\u{b78}', '\u{b81}'), - ('\u{b84}', '\u{b84}'), ('\u{b8b}', '\u{b8d}'), ('\u{b91}', '\u{b91}'), - ('\u{b96}', '\u{b98}'), ('\u{b9b}', '\u{b9b}'), ('\u{b9d}', '\u{b9d}'), - ('\u{ba0}', '\u{ba2}'), ('\u{ba5}', '\u{ba7}'), ('\u{bab}', '\u{bad}'), - ('\u{bba}', '\u{bbd}'), ('\u{bc3}', '\u{bc5}'), ('\u{bc9}', '\u{bc9}'), - ('\u{bce}', '\u{bcf}'), ('\u{bd1}', '\u{bd6}'), ('\u{bd8}', '\u{be5}'), - ('\u{bfb}', '\u{bff}'), ('\u{c04}', '\u{c04}'), ('\u{c0d}', '\u{c0d}'), - ('\u{c11}', '\u{c11}'), ('\u{c29}', '\u{c29}'), ('\u{c3a}', '\u{c3c}'), - ('\u{c45}', '\u{c45}'), ('\u{c49}', '\u{c49}'), ('\u{c4e}', '\u{c54}'), - ('\u{c57}', '\u{c57}'), ('\u{c5b}', '\u{c5f}'), ('\u{c64}', '\u{c65}'), - ('\u{c70}', '\u{c77}'), ('\u{c84}', '\u{c84}'), ('\u{c8d}', '\u{c8d}'), - ('\u{c91}', '\u{c91}'), ('\u{ca9}', '\u{ca9}'), ('\u{cb4}', '\u{cb4}'), - ('\u{cba}', '\u{cbb}'), ('\u{cc5}', '\u{cc5}'), ('\u{cc9}', '\u{cc9}'), - ('\u{cce}', '\u{cd4}'), ('\u{cd7}', '\u{cdd}'), ('\u{cdf}', '\u{cdf}'), - ('\u{ce4}', '\u{ce5}'), ('\u{cf0}', '\u{cf0}'), ('\u{cf3}', '\u{cff}'), - ('\u{d04}', '\u{d04}'), ('\u{d0d}', '\u{d0d}'), ('\u{d11}', '\u{d11}'), - ('\u{d45}', '\u{d45}'), ('\u{d49}', '\u{d49}'), ('\u{d50}', '\u{d53}'), - ('\u{d64}', '\u{d65}'), ('\u{d80}', '\u{d81}'), ('\u{d84}', '\u{d84}'), - ('\u{d97}', '\u{d99}'), ('\u{db2}', '\u{db2}'), ('\u{dbc}', '\u{dbc}'), - ('\u{dbe}', '\u{dbf}'), ('\u{dc7}', '\u{dc9}'), ('\u{dcb}', '\u{dce}'), - ('\u{dd5}', '\u{dd5}'), ('\u{dd7}', '\u{dd7}'), ('\u{de0}', '\u{de5}'), - ('\u{df0}', '\u{df1}'), ('\u{df5}', '\u{e00}'), ('\u{e3b}', '\u{e3e}'), - ('\u{e5c}', '\u{e80}'), ('\u{e83}', '\u{e83}'), ('\u{e85}', '\u{e86}'), - ('\u{e89}', '\u{e89}'), ('\u{e8b}', '\u{e8c}'), ('\u{e8e}', '\u{e93}'), - ('\u{e98}', '\u{e98}'), ('\u{ea0}', '\u{ea0}'), ('\u{ea4}', '\u{ea4}'), - ('\u{ea6}', '\u{ea6}'), ('\u{ea8}', '\u{ea9}'), ('\u{eac}', '\u{eac}'), - ('\u{eba}', '\u{eba}'), ('\u{ebe}', '\u{ebf}'), ('\u{ec5}', '\u{ec5}'), - ('\u{ec7}', '\u{ec7}'), ('\u{ece}', '\u{ecf}'), ('\u{eda}', '\u{edb}'), - ('\u{ee0}', '\u{eff}'), ('\u{f48}', '\u{f48}'), ('\u{f6d}', '\u{f70}'), - ('\u{f98}', '\u{f98}'), ('\u{fbd}', '\u{fbd}'), ('\u{fcd}', '\u{fcd}'), - ('\u{fdb}', '\u{fff}'), ('\u{10c6}', '\u{10c6}'), ('\u{10c8}', - '\u{10cc}'), ('\u{10ce}', '\u{10cf}'), ('\u{1249}', '\u{1249}'), - ('\u{124e}', '\u{124f}'), ('\u{1257}', '\u{1257}'), ('\u{1259}', - '\u{1259}'), ('\u{125e}', '\u{125f}'), ('\u{1289}', '\u{1289}'), - ('\u{128e}', '\u{128f}'), ('\u{12b1}', '\u{12b1}'), ('\u{12b6}', - '\u{12b7}'), ('\u{12bf}', '\u{12bf}'), ('\u{12c1}', '\u{12c1}'), - ('\u{12c6}', '\u{12c7}'), ('\u{12d7}', '\u{12d7}'), ('\u{1311}', - '\u{1311}'), ('\u{1316}', '\u{1317}'), ('\u{135b}', '\u{135c}'), - ('\u{137d}', '\u{137f}'), ('\u{139a}', '\u{139f}'), ('\u{13f6}', - '\u{13f7}'), ('\u{13fe}', '\u{13ff}'), ('\u{169d}', '\u{169f}'), - ('\u{16f9}', '\u{16ff}'), ('\u{170d}', '\u{170d}'), ('\u{1715}', - '\u{171f}'), ('\u{1737}', '\u{173f}'), ('\u{1754}', '\u{175f}'), - ('\u{176d}', '\u{176d}'), ('\u{1771}', '\u{1771}'), ('\u{1774}', - '\u{177f}'), ('\u{17de}', '\u{17df}'), ('\u{17ea}', '\u{17ef}'), - ('\u{17fa}', '\u{17ff}'), ('\u{180f}', '\u{180f}'), ('\u{181a}', - '\u{181f}'), ('\u{1878}', '\u{187f}'), ('\u{18ab}', '\u{18af}'), - ('\u{18f6}', '\u{18ff}'), ('\u{191f}', '\u{191f}'), ('\u{192c}', - '\u{192f}'), ('\u{193c}', '\u{193f}'), ('\u{1941}', '\u{1943}'), - ('\u{196e}', '\u{196f}'), ('\u{1975}', '\u{197f}'), ('\u{19ac}', - '\u{19af}'), ('\u{19ca}', '\u{19cf}'), ('\u{19db}', '\u{19dd}'), - ('\u{1a1c}', '\u{1a1d}'), ('\u{1a5f}', '\u{1a5f}'), ('\u{1a7d}', - '\u{1a7e}'), ('\u{1a8a}', '\u{1a8f}'), ('\u{1a9a}', '\u{1a9f}'), - ('\u{1aae}', '\u{1aaf}'), ('\u{1abf}', '\u{1aff}'), ('\u{1b4c}', - '\u{1b4f}'), ('\u{1b7d}', '\u{1b7f}'), ('\u{1bf4}', '\u{1bfb}'), - ('\u{1c38}', '\u{1c3a}'), ('\u{1c4a}', '\u{1c4c}'), ('\u{1c89}', - '\u{1cbf}'), ('\u{1cc8}', '\u{1ccf}'), ('\u{1cfa}', '\u{1cff}'), - ('\u{1dfa}', '\u{1dfa}'), ('\u{1f16}', '\u{1f17}'), ('\u{1f1e}', - '\u{1f1f}'), ('\u{1f46}', '\u{1f47}'), ('\u{1f4e}', '\u{1f4f}'), - ('\u{1f58}', '\u{1f58}'), ('\u{1f5a}', '\u{1f5a}'), ('\u{1f5c}', - '\u{1f5c}'), ('\u{1f5e}', '\u{1f5e}'), ('\u{1f7e}', '\u{1f7f}'), - ('\u{1fb5}', '\u{1fb5}'), ('\u{1fc5}', '\u{1fc5}'), ('\u{1fd4}', - '\u{1fd5}'), ('\u{1fdc}', '\u{1fdc}'), ('\u{1ff0}', '\u{1ff1}'), - ('\u{1ff5}', '\u{1ff5}'), ('\u{1fff}', '\u{1fff}'), ('\u{2065}', - '\u{2065}'), ('\u{2072}', '\u{2073}'), ('\u{208f}', '\u{208f}'), - ('\u{209d}', '\u{209f}'), ('\u{20c0}', '\u{20cf}'), ('\u{20f1}', - '\u{20ff}'), ('\u{218c}', '\u{218f}'), ('\u{2427}', '\u{243f}'), - ('\u{244b}', '\u{245f}'), ('\u{2b74}', '\u{2b75}'), ('\u{2b96}', - '\u{2b97}'), ('\u{2bba}', '\u{2bbc}'), ('\u{2bc9}', '\u{2bc9}'), - ('\u{2bd3}', '\u{2beb}'), ('\u{2bf0}', '\u{2bff}'), ('\u{2c2f}', - '\u{2c2f}'), ('\u{2c5f}', '\u{2c5f}'), ('\u{2cf4}', '\u{2cf8}'), - ('\u{2d26}', '\u{2d26}'), ('\u{2d28}', '\u{2d2c}'), ('\u{2d2e}', - '\u{2d2f}'), ('\u{2d68}', '\u{2d6e}'), ('\u{2d71}', '\u{2d7e}'), - ('\u{2d97}', '\u{2d9f}'), ('\u{2da7}', '\u{2da7}'), ('\u{2daf}', - '\u{2daf}'), ('\u{2db7}', '\u{2db7}'), ('\u{2dbf}', '\u{2dbf}'), - ('\u{2dc7}', '\u{2dc7}'), ('\u{2dcf}', '\u{2dcf}'), ('\u{2dd7}', - '\u{2dd7}'), ('\u{2ddf}', '\u{2ddf}'), ('\u{2e4a}', '\u{2e7f}'), - ('\u{2e9a}', '\u{2e9a}'), ('\u{2ef4}', '\u{2eff}'), ('\u{2fd6}', - '\u{2fef}'), ('\u{2ffc}', '\u{2fff}'), ('\u{3040}', '\u{3040}'), - ('\u{3097}', '\u{3098}'), ('\u{3100}', '\u{3104}'), ('\u{312f}', - '\u{3130}'), ('\u{318f}', '\u{318f}'), ('\u{31bb}', '\u{31bf}'), - ('\u{31e4}', '\u{31ef}'), ('\u{321f}', '\u{321f}'), ('\u{32ff}', - '\u{32ff}'), ('\u{4db6}', '\u{4dbf}'), ('\u{9feb}', '\u{9fff}'), - ('\u{a48d}', '\u{a48f}'), ('\u{a4c7}', '\u{a4cf}'), ('\u{a62c}', - '\u{a63f}'), ('\u{a6f8}', '\u{a6ff}'), ('\u{a7af}', '\u{a7af}'), - ('\u{a7b8}', '\u{a7f6}'), ('\u{a82c}', '\u{a82f}'), ('\u{a83a}', - '\u{a83f}'), ('\u{a878}', '\u{a87f}'), ('\u{a8c6}', '\u{a8cd}'), - ('\u{a8da}', '\u{a8df}'), ('\u{a8fe}', '\u{a8ff}'), ('\u{a954}', - '\u{a95e}'), ('\u{a97d}', '\u{a97f}'), ('\u{a9ce}', '\u{a9ce}'), - ('\u{a9da}', '\u{a9dd}'), ('\u{a9ff}', '\u{a9ff}'), ('\u{aa37}', - '\u{aa3f}'), ('\u{aa4e}', '\u{aa4f}'), ('\u{aa5a}', '\u{aa5b}'), - ('\u{aac3}', '\u{aada}'), ('\u{aaf7}', '\u{ab00}'), ('\u{ab07}', - '\u{ab08}'), ('\u{ab0f}', '\u{ab10}'), ('\u{ab17}', '\u{ab1f}'), - ('\u{ab27}', '\u{ab27}'), ('\u{ab2f}', '\u{ab2f}'), ('\u{ab66}', - '\u{ab6f}'), ('\u{abee}', '\u{abef}'), ('\u{abfa}', '\u{abff}'), - ('\u{d7a4}', '\u{d7af}'), ('\u{d7c7}', '\u{d7ca}'), ('\u{d7fc}', - '\u{d7ff}'), ('\u{fa6e}', '\u{fa6f}'), ('\u{fada}', '\u{faff}'), - ('\u{fb07}', '\u{fb12}'), ('\u{fb18}', '\u{fb1c}'), ('\u{fb37}', - '\u{fb37}'), ('\u{fb3d}', '\u{fb3d}'), ('\u{fb3f}', '\u{fb3f}'), - ('\u{fb42}', '\u{fb42}'), ('\u{fb45}', '\u{fb45}'), ('\u{fbc2}', - '\u{fbd2}'), ('\u{fd40}', '\u{fd4f}'), ('\u{fd90}', '\u{fd91}'), - ('\u{fdc8}', '\u{fdef}'), ('\u{fdfe}', '\u{fdff}'), ('\u{fe1a}', - '\u{fe1f}'), ('\u{fe53}', '\u{fe53}'), ('\u{fe67}', '\u{fe67}'), - ('\u{fe6c}', '\u{fe6f}'), ('\u{fe75}', '\u{fe75}'), ('\u{fefd}', - '\u{fefe}'), ('\u{ff00}', '\u{ff00}'), ('\u{ffbf}', '\u{ffc1}'), - ('\u{ffc8}', '\u{ffc9}'), ('\u{ffd0}', '\u{ffd1}'), ('\u{ffd8}', - '\u{ffd9}'), ('\u{ffdd}', '\u{ffdf}'), ('\u{ffe7}', '\u{ffe7}'), - ('\u{ffef}', '\u{fff8}'), ('\u{fffe}', '\u{ffff}'), ('\u{1000c}', - '\u{1000c}'), ('\u{10027}', '\u{10027}'), ('\u{1003b}', '\u{1003b}'), - ('\u{1003e}', '\u{1003e}'), ('\u{1004e}', '\u{1004f}'), ('\u{1005e}', - '\u{1007f}'), ('\u{100fb}', '\u{100ff}'), ('\u{10103}', '\u{10106}'), - ('\u{10134}', '\u{10136}'), ('\u{1018f}', '\u{1018f}'), ('\u{1019c}', - '\u{1019f}'), ('\u{101a1}', '\u{101cf}'), ('\u{101fe}', '\u{1027f}'), - ('\u{1029d}', '\u{1029f}'), ('\u{102d1}', '\u{102df}'), ('\u{102fc}', - '\u{102ff}'), ('\u{10324}', '\u{1032c}'), ('\u{1034b}', '\u{1034f}'), - ('\u{1037b}', '\u{1037f}'), ('\u{1039e}', '\u{1039e}'), ('\u{103c4}', - '\u{103c7}'), ('\u{103d6}', '\u{103ff}'), ('\u{1049e}', '\u{1049f}'), - ('\u{104aa}', '\u{104af}'), ('\u{104d4}', '\u{104d7}'), ('\u{104fc}', - '\u{104ff}'), ('\u{10528}', '\u{1052f}'), ('\u{10564}', '\u{1056e}'), - ('\u{10570}', '\u{105ff}'), ('\u{10737}', '\u{1073f}'), ('\u{10756}', - '\u{1075f}'), ('\u{10768}', '\u{107ff}'), ('\u{10806}', '\u{10807}'), - ('\u{10809}', '\u{10809}'), ('\u{10836}', '\u{10836}'), ('\u{10839}', - '\u{1083b}'), ('\u{1083d}', '\u{1083e}'), ('\u{10856}', '\u{10856}'), - ('\u{1089f}', '\u{108a6}'), ('\u{108b0}', '\u{108df}'), ('\u{108f3}', - '\u{108f3}'), ('\u{108f6}', '\u{108fa}'), ('\u{1091c}', '\u{1091e}'), - ('\u{1093a}', '\u{1093e}'), ('\u{10940}', '\u{1097f}'), ('\u{109b8}', - '\u{109bb}'), ('\u{109d0}', '\u{109d1}'), ('\u{10a04}', '\u{10a04}'), - ('\u{10a07}', '\u{10a0b}'), ('\u{10a14}', '\u{10a14}'), ('\u{10a18}', - '\u{10a18}'), ('\u{10a34}', '\u{10a37}'), ('\u{10a3b}', '\u{10a3e}'), - ('\u{10a48}', '\u{10a4f}'), ('\u{10a59}', '\u{10a5f}'), ('\u{10aa0}', - '\u{10abf}'), ('\u{10ae7}', '\u{10aea}'), ('\u{10af7}', '\u{10aff}'), - ('\u{10b36}', '\u{10b38}'), ('\u{10b56}', '\u{10b57}'), ('\u{10b73}', - '\u{10b77}'), ('\u{10b92}', '\u{10b98}'), ('\u{10b9d}', '\u{10ba8}'), - ('\u{10bb0}', '\u{10bff}'), ('\u{10c49}', '\u{10c7f}'), ('\u{10cb3}', - '\u{10cbf}'), ('\u{10cf3}', '\u{10cf9}'), ('\u{10d00}', '\u{10e5f}'), - ('\u{10e7f}', '\u{10fff}'), ('\u{1104e}', '\u{11051}'), ('\u{11070}', - '\u{1107e}'), ('\u{110c2}', '\u{110cf}'), ('\u{110e9}', '\u{110ef}'), - ('\u{110fa}', '\u{110ff}'), ('\u{11135}', '\u{11135}'), ('\u{11144}', - '\u{1114f}'), ('\u{11177}', '\u{1117f}'), ('\u{111ce}', '\u{111cf}'), - ('\u{111e0}', '\u{111e0}'), ('\u{111f5}', '\u{111ff}'), ('\u{11212}', - '\u{11212}'), ('\u{1123f}', '\u{1127f}'), ('\u{11287}', '\u{11287}'), - ('\u{11289}', '\u{11289}'), ('\u{1128e}', '\u{1128e}'), ('\u{1129e}', - '\u{1129e}'), ('\u{112aa}', '\u{112af}'), ('\u{112eb}', '\u{112ef}'), - ('\u{112fa}', '\u{112ff}'), ('\u{11304}', '\u{11304}'), ('\u{1130d}', - '\u{1130e}'), ('\u{11311}', '\u{11312}'), ('\u{11329}', '\u{11329}'), - ('\u{11331}', '\u{11331}'), ('\u{11334}', '\u{11334}'), ('\u{1133a}', - '\u{1133b}'), ('\u{11345}', '\u{11346}'), ('\u{11349}', '\u{1134a}'), - ('\u{1134e}', '\u{1134f}'), ('\u{11351}', '\u{11356}'), ('\u{11358}', - '\u{1135c}'), ('\u{11364}', '\u{11365}'), ('\u{1136d}', '\u{1136f}'), - ('\u{11375}', '\u{113ff}'), ('\u{1145a}', '\u{1145a}'), ('\u{1145c}', - '\u{1145c}'), ('\u{1145e}', '\u{1147f}'), ('\u{114c8}', '\u{114cf}'), - ('\u{114da}', '\u{1157f}'), ('\u{115b6}', '\u{115b7}'), ('\u{115de}', - '\u{115ff}'), ('\u{11645}', '\u{1164f}'), ('\u{1165a}', '\u{1165f}'), - ('\u{1166d}', '\u{1167f}'), ('\u{116b8}', '\u{116bf}'), ('\u{116ca}', - '\u{116ff}'), ('\u{1171a}', '\u{1171c}'), ('\u{1172c}', '\u{1172f}'), - ('\u{11740}', '\u{1189f}'), ('\u{118f3}', '\u{118fe}'), ('\u{11900}', - '\u{119ff}'), ('\u{11a48}', '\u{11a4f}'), ('\u{11a84}', '\u{11a85}'), - ('\u{11a9d}', '\u{11a9d}'), ('\u{11aa3}', '\u{11abf}'), ('\u{11af9}', - '\u{11bff}'), ('\u{11c09}', '\u{11c09}'), ('\u{11c37}', '\u{11c37}'), - ('\u{11c46}', '\u{11c4f}'), ('\u{11c6d}', '\u{11c6f}'), ('\u{11c90}', - '\u{11c91}'), ('\u{11ca8}', '\u{11ca8}'), ('\u{11cb7}', '\u{11cff}'), - ('\u{11d07}', '\u{11d07}'), ('\u{11d0a}', '\u{11d0a}'), ('\u{11d37}', - '\u{11d39}'), ('\u{11d3b}', '\u{11d3b}'), ('\u{11d3e}', '\u{11d3e}'), - ('\u{11d48}', '\u{11d4f}'), ('\u{11d5a}', '\u{11fff}'), ('\u{1239a}', - '\u{123ff}'), ('\u{1246f}', '\u{1246f}'), ('\u{12475}', '\u{1247f}'), - ('\u{12544}', '\u{12fff}'), ('\u{1342f}', '\u{143ff}'), ('\u{14647}', - '\u{167ff}'), ('\u{16a39}', '\u{16a3f}'), ('\u{16a5f}', '\u{16a5f}'), - ('\u{16a6a}', '\u{16a6d}'), ('\u{16a70}', '\u{16acf}'), ('\u{16aee}', - '\u{16aef}'), ('\u{16af6}', '\u{16aff}'), ('\u{16b46}', '\u{16b4f}'), - ('\u{16b5a}', '\u{16b5a}'), ('\u{16b62}', '\u{16b62}'), ('\u{16b78}', - '\u{16b7c}'), ('\u{16b90}', '\u{16eff}'), ('\u{16f45}', '\u{16f4f}'), - ('\u{16f7f}', '\u{16f8e}'), ('\u{16fa0}', '\u{16fdf}'), ('\u{16fe2}', - '\u{16fff}'), ('\u{187ed}', '\u{187ff}'), ('\u{18af3}', '\u{1afff}'), - ('\u{1b11f}', '\u{1b16f}'), ('\u{1b2fc}', '\u{1bbff}'), ('\u{1bc6b}', - '\u{1bc6f}'), ('\u{1bc7d}', '\u{1bc7f}'), ('\u{1bc89}', '\u{1bc8f}'), - ('\u{1bc9a}', '\u{1bc9b}'), ('\u{1bca4}', '\u{1cfff}'), ('\u{1d0f6}', - '\u{1d0ff}'), ('\u{1d127}', '\u{1d128}'), ('\u{1d1e9}', '\u{1d1ff}'), - ('\u{1d246}', '\u{1d2ff}'), ('\u{1d357}', '\u{1d35f}'), ('\u{1d372}', - '\u{1d3ff}'), ('\u{1d455}', '\u{1d455}'), ('\u{1d49d}', '\u{1d49d}'), - ('\u{1d4a0}', '\u{1d4a1}'), ('\u{1d4a3}', '\u{1d4a4}'), ('\u{1d4a7}', - '\u{1d4a8}'), ('\u{1d4ad}', '\u{1d4ad}'), ('\u{1d4ba}', '\u{1d4ba}'), - ('\u{1d4bc}', '\u{1d4bc}'), ('\u{1d4c4}', '\u{1d4c4}'), ('\u{1d506}', - '\u{1d506}'), ('\u{1d50b}', '\u{1d50c}'), ('\u{1d515}', '\u{1d515}'), - ('\u{1d51d}', '\u{1d51d}'), ('\u{1d53a}', '\u{1d53a}'), ('\u{1d53f}', - '\u{1d53f}'), ('\u{1d545}', '\u{1d545}'), ('\u{1d547}', '\u{1d549}'), - ('\u{1d551}', '\u{1d551}'), ('\u{1d6a6}', '\u{1d6a7}'), ('\u{1d7cc}', - '\u{1d7cd}'), ('\u{1da8c}', '\u{1da9a}'), ('\u{1daa0}', '\u{1daa0}'), - ('\u{1dab0}', '\u{1dfff}'), ('\u{1e007}', '\u{1e007}'), ('\u{1e019}', - '\u{1e01a}'), ('\u{1e022}', '\u{1e022}'), ('\u{1e025}', '\u{1e025}'), - ('\u{1e02b}', '\u{1e7ff}'), ('\u{1e8c5}', '\u{1e8c6}'), ('\u{1e8d7}', - '\u{1e8ff}'), ('\u{1e94b}', '\u{1e94f}'), ('\u{1e95a}', '\u{1e95d}'), - ('\u{1e960}', '\u{1edff}'), ('\u{1ee04}', '\u{1ee04}'), ('\u{1ee20}', - '\u{1ee20}'), ('\u{1ee23}', '\u{1ee23}'), ('\u{1ee25}', '\u{1ee26}'), - ('\u{1ee28}', '\u{1ee28}'), ('\u{1ee33}', '\u{1ee33}'), ('\u{1ee38}', - '\u{1ee38}'), ('\u{1ee3a}', '\u{1ee3a}'), ('\u{1ee3c}', '\u{1ee41}'), - ('\u{1ee43}', '\u{1ee46}'), ('\u{1ee48}', '\u{1ee48}'), ('\u{1ee4a}', - '\u{1ee4a}'), ('\u{1ee4c}', '\u{1ee4c}'), ('\u{1ee50}', '\u{1ee50}'), - ('\u{1ee53}', '\u{1ee53}'), ('\u{1ee55}', '\u{1ee56}'), ('\u{1ee58}', - '\u{1ee58}'), ('\u{1ee5a}', '\u{1ee5a}'), ('\u{1ee5c}', '\u{1ee5c}'), - ('\u{1ee5e}', '\u{1ee5e}'), ('\u{1ee60}', '\u{1ee60}'), ('\u{1ee63}', - '\u{1ee63}'), ('\u{1ee65}', '\u{1ee66}'), ('\u{1ee6b}', '\u{1ee6b}'), - ('\u{1ee73}', '\u{1ee73}'), ('\u{1ee78}', '\u{1ee78}'), ('\u{1ee7d}', - '\u{1ee7d}'), ('\u{1ee7f}', '\u{1ee7f}'), ('\u{1ee8a}', '\u{1ee8a}'), - ('\u{1ee9c}', '\u{1eea0}'), ('\u{1eea4}', '\u{1eea4}'), ('\u{1eeaa}', - '\u{1eeaa}'), ('\u{1eebc}', '\u{1eeef}'), ('\u{1eef2}', '\u{1efff}'), - ('\u{1f02c}', '\u{1f02f}'), ('\u{1f094}', '\u{1f09f}'), ('\u{1f0af}', - '\u{1f0b0}'), ('\u{1f0c0}', '\u{1f0c0}'), ('\u{1f0d0}', '\u{1f0d0}'), - ('\u{1f0f6}', '\u{1f0ff}'), ('\u{1f10d}', '\u{1f10f}'), ('\u{1f12f}', - '\u{1f12f}'), ('\u{1f16c}', '\u{1f16f}'), ('\u{1f1ad}', '\u{1f1e5}'), - ('\u{1f203}', '\u{1f20f}'), ('\u{1f23c}', '\u{1f23f}'), ('\u{1f249}', - '\u{1f24f}'), ('\u{1f252}', '\u{1f25f}'), ('\u{1f266}', '\u{1f2ff}'), - ('\u{1f6d5}', '\u{1f6df}'), ('\u{1f6ed}', '\u{1f6ef}'), ('\u{1f6f9}', - '\u{1f6ff}'), ('\u{1f774}', '\u{1f77f}'), ('\u{1f7d5}', '\u{1f7ff}'), - ('\u{1f80c}', '\u{1f80f}'), ('\u{1f848}', '\u{1f84f}'), ('\u{1f85a}', - '\u{1f85f}'), ('\u{1f888}', '\u{1f88f}'), ('\u{1f8ae}', '\u{1f8ff}'), - ('\u{1f90c}', '\u{1f90f}'), ('\u{1f93f}', '\u{1f93f}'), ('\u{1f94d}', - '\u{1f94f}'), ('\u{1f96c}', '\u{1f97f}'), ('\u{1f998}', '\u{1f9bf}'), - ('\u{1f9c1}', '\u{1f9cf}'), ('\u{1f9e7}', '\u{1ffff}'), ('\u{2a6d7}', - '\u{2a6ff}'), ('\u{2b735}', '\u{2b73f}'), ('\u{2b81e}', '\u{2b81f}'), - ('\u{2cea2}', '\u{2ceaf}'), ('\u{2ebe1}', '\u{2f7ff}'), ('\u{2fa1e}', - '\u{e0000}'), ('\u{e0002}', '\u{e001f}'), ('\u{e0080}', '\u{e00ff}'), - ('\u{e01f0}', '\u{effff}'), ('\u{ffffe}', '\u{fffff}'), ('\u{10fffe}', - '\u{10ffff}') - ]; - - pub const Co_table: &'static [(char, char)] = &[ - ('\u{e000}', '\u{f8ff}'), ('\u{f0000}', '\u{ffffd}'), ('\u{100000}', - '\u{10fffd}') - ]; - - pub const L_table: &'static [(char, char)] = &[ - ('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), - ('\u{b5}', '\u{b5}'), ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), - ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{2c1}'), ('\u{2c6}', '\u{2d1}'), - ('\u{2e0}', '\u{2e4}'), ('\u{2ec}', '\u{2ec}'), ('\u{2ee}', '\u{2ee}'), - ('\u{370}', '\u{374}'), ('\u{376}', '\u{377}'), ('\u{37a}', '\u{37d}'), - ('\u{37f}', '\u{37f}'), ('\u{386}', '\u{386}'), ('\u{388}', '\u{38a}'), - ('\u{38c}', '\u{38c}'), ('\u{38e}', '\u{3a1}'), ('\u{3a3}', '\u{3f5}'), - ('\u{3f7}', '\u{481}'), ('\u{48a}', '\u{52f}'), ('\u{531}', '\u{556}'), - ('\u{559}', '\u{559}'), ('\u{561}', '\u{587}'), ('\u{5d0}', '\u{5ea}'), - ('\u{5f0}', '\u{5f2}'), ('\u{620}', '\u{64a}'), ('\u{66e}', '\u{66f}'), - ('\u{671}', '\u{6d3}'), ('\u{6d5}', '\u{6d5}'), ('\u{6e5}', '\u{6e6}'), - ('\u{6ee}', '\u{6ef}'), ('\u{6fa}', '\u{6fc}'), ('\u{6ff}', '\u{6ff}'), - ('\u{710}', '\u{710}'), ('\u{712}', '\u{72f}'), ('\u{74d}', '\u{7a5}'), - ('\u{7b1}', '\u{7b1}'), ('\u{7ca}', '\u{7ea}'), ('\u{7f4}', '\u{7f5}'), - ('\u{7fa}', '\u{7fa}'), ('\u{800}', '\u{815}'), ('\u{81a}', '\u{81a}'), - ('\u{824}', '\u{824}'), ('\u{828}', '\u{828}'), ('\u{840}', '\u{858}'), - ('\u{860}', '\u{86a}'), ('\u{8a0}', '\u{8b4}'), ('\u{8b6}', '\u{8bd}'), - ('\u{904}', '\u{939}'), ('\u{93d}', '\u{93d}'), ('\u{950}', '\u{950}'), - ('\u{958}', '\u{961}'), ('\u{971}', '\u{980}'), ('\u{985}', '\u{98c}'), - ('\u{98f}', '\u{990}'), ('\u{993}', '\u{9a8}'), ('\u{9aa}', '\u{9b0}'), - ('\u{9b2}', '\u{9b2}'), ('\u{9b6}', '\u{9b9}'), ('\u{9bd}', '\u{9bd}'), - ('\u{9ce}', '\u{9ce}'), ('\u{9dc}', '\u{9dd}'), ('\u{9df}', '\u{9e1}'), - ('\u{9f0}', '\u{9f1}'), ('\u{9fc}', '\u{9fc}'), ('\u{a05}', '\u{a0a}'), - ('\u{a0f}', '\u{a10}'), ('\u{a13}', '\u{a28}'), ('\u{a2a}', '\u{a30}'), - ('\u{a32}', '\u{a33}'), ('\u{a35}', '\u{a36}'), ('\u{a38}', '\u{a39}'), - ('\u{a59}', '\u{a5c}'), ('\u{a5e}', '\u{a5e}'), ('\u{a72}', '\u{a74}'), - ('\u{a85}', '\u{a8d}'), ('\u{a8f}', '\u{a91}'), ('\u{a93}', '\u{aa8}'), - ('\u{aaa}', '\u{ab0}'), ('\u{ab2}', '\u{ab3}'), ('\u{ab5}', '\u{ab9}'), - ('\u{abd}', '\u{abd}'), ('\u{ad0}', '\u{ad0}'), ('\u{ae0}', '\u{ae1}'), - ('\u{af9}', '\u{af9}'), ('\u{b05}', '\u{b0c}'), ('\u{b0f}', '\u{b10}'), - ('\u{b13}', '\u{b28}'), ('\u{b2a}', '\u{b30}'), ('\u{b32}', '\u{b33}'), - ('\u{b35}', '\u{b39}'), ('\u{b3d}', '\u{b3d}'), ('\u{b5c}', '\u{b5d}'), - ('\u{b5f}', '\u{b61}'), ('\u{b71}', '\u{b71}'), ('\u{b83}', '\u{b83}'), - ('\u{b85}', '\u{b8a}'), ('\u{b8e}', '\u{b90}'), ('\u{b92}', '\u{b95}'), - ('\u{b99}', '\u{b9a}'), ('\u{b9c}', '\u{b9c}'), ('\u{b9e}', '\u{b9f}'), - ('\u{ba3}', '\u{ba4}'), ('\u{ba8}', '\u{baa}'), ('\u{bae}', '\u{bb9}'), - ('\u{bd0}', '\u{bd0}'), ('\u{c05}', '\u{c0c}'), ('\u{c0e}', '\u{c10}'), - ('\u{c12}', '\u{c28}'), ('\u{c2a}', '\u{c39}'), ('\u{c3d}', '\u{c3d}'), - ('\u{c58}', '\u{c5a}'), ('\u{c60}', '\u{c61}'), ('\u{c80}', '\u{c80}'), - ('\u{c85}', '\u{c8c}'), ('\u{c8e}', '\u{c90}'), ('\u{c92}', '\u{ca8}'), - ('\u{caa}', '\u{cb3}'), ('\u{cb5}', '\u{cb9}'), ('\u{cbd}', '\u{cbd}'), - ('\u{cde}', '\u{cde}'), ('\u{ce0}', '\u{ce1}'), ('\u{cf1}', '\u{cf2}'), - ('\u{d05}', '\u{d0c}'), ('\u{d0e}', '\u{d10}'), ('\u{d12}', '\u{d3a}'), - ('\u{d3d}', '\u{d3d}'), ('\u{d4e}', '\u{d4e}'), ('\u{d54}', '\u{d56}'), - ('\u{d5f}', '\u{d61}'), ('\u{d7a}', '\u{d7f}'), ('\u{d85}', '\u{d96}'), - ('\u{d9a}', '\u{db1}'), ('\u{db3}', '\u{dbb}'), ('\u{dbd}', '\u{dbd}'), - ('\u{dc0}', '\u{dc6}'), ('\u{e01}', '\u{e30}'), ('\u{e32}', '\u{e33}'), - ('\u{e40}', '\u{e46}'), ('\u{e81}', '\u{e82}'), ('\u{e84}', '\u{e84}'), - ('\u{e87}', '\u{e88}'), ('\u{e8a}', '\u{e8a}'), ('\u{e8d}', '\u{e8d}'), - ('\u{e94}', '\u{e97}'), ('\u{e99}', '\u{e9f}'), ('\u{ea1}', '\u{ea3}'), - ('\u{ea5}', '\u{ea5}'), ('\u{ea7}', '\u{ea7}'), ('\u{eaa}', '\u{eab}'), - ('\u{ead}', '\u{eb0}'), ('\u{eb2}', '\u{eb3}'), ('\u{ebd}', '\u{ebd}'), - ('\u{ec0}', '\u{ec4}'), ('\u{ec6}', '\u{ec6}'), ('\u{edc}', '\u{edf}'), - ('\u{f00}', '\u{f00}'), ('\u{f40}', '\u{f47}'), ('\u{f49}', '\u{f6c}'), - ('\u{f88}', '\u{f8c}'), ('\u{1000}', '\u{102a}'), ('\u{103f}', - '\u{103f}'), ('\u{1050}', '\u{1055}'), ('\u{105a}', '\u{105d}'), - ('\u{1061}', '\u{1061}'), ('\u{1065}', '\u{1066}'), ('\u{106e}', - '\u{1070}'), ('\u{1075}', '\u{1081}'), ('\u{108e}', '\u{108e}'), - ('\u{10a0}', '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), ('\u{10cd}', - '\u{10cd}'), ('\u{10d0}', '\u{10fa}'), ('\u{10fc}', '\u{1248}'), - ('\u{124a}', '\u{124d}'), ('\u{1250}', '\u{1256}'), ('\u{1258}', - '\u{1258}'), ('\u{125a}', '\u{125d}'), ('\u{1260}', '\u{1288}'), - ('\u{128a}', '\u{128d}'), ('\u{1290}', '\u{12b0}'), ('\u{12b2}', - '\u{12b5}'), ('\u{12b8}', '\u{12be}'), ('\u{12c0}', '\u{12c0}'), - ('\u{12c2}', '\u{12c5}'), ('\u{12c8}', '\u{12d6}'), ('\u{12d8}', - '\u{1310}'), ('\u{1312}', '\u{1315}'), ('\u{1318}', '\u{135a}'), - ('\u{1380}', '\u{138f}'), ('\u{13a0}', '\u{13f5}'), ('\u{13f8}', - '\u{13fd}'), ('\u{1401}', '\u{166c}'), ('\u{166f}', '\u{167f}'), - ('\u{1681}', '\u{169a}'), ('\u{16a0}', '\u{16ea}'), ('\u{16f1}', - '\u{16f8}'), ('\u{1700}', '\u{170c}'), ('\u{170e}', '\u{1711}'), - ('\u{1720}', '\u{1731}'), ('\u{1740}', '\u{1751}'), ('\u{1760}', - '\u{176c}'), ('\u{176e}', '\u{1770}'), ('\u{1780}', '\u{17b3}'), - ('\u{17d7}', '\u{17d7}'), ('\u{17dc}', '\u{17dc}'), ('\u{1820}', - '\u{1877}'), ('\u{1880}', '\u{1884}'), ('\u{1887}', '\u{18a8}'), - ('\u{18aa}', '\u{18aa}'), ('\u{18b0}', '\u{18f5}'), ('\u{1900}', - '\u{191e}'), ('\u{1950}', '\u{196d}'), ('\u{1970}', '\u{1974}'), - ('\u{1980}', '\u{19ab}'), ('\u{19b0}', '\u{19c9}'), ('\u{1a00}', - '\u{1a16}'), ('\u{1a20}', '\u{1a54}'), ('\u{1aa7}', '\u{1aa7}'), - ('\u{1b05}', '\u{1b33}'), ('\u{1b45}', '\u{1b4b}'), ('\u{1b83}', - '\u{1ba0}'), ('\u{1bae}', '\u{1baf}'), ('\u{1bba}', '\u{1be5}'), - ('\u{1c00}', '\u{1c23}'), ('\u{1c4d}', '\u{1c4f}'), ('\u{1c5a}', - '\u{1c7d}'), ('\u{1c80}', '\u{1c88}'), ('\u{1ce9}', '\u{1cec}'), - ('\u{1cee}', '\u{1cf1}'), ('\u{1cf5}', '\u{1cf6}'), ('\u{1d00}', - '\u{1dbf}'), ('\u{1e00}', '\u{1f15}'), ('\u{1f18}', '\u{1f1d}'), - ('\u{1f20}', '\u{1f45}'), ('\u{1f48}', '\u{1f4d}'), ('\u{1f50}', - '\u{1f57}'), ('\u{1f59}', '\u{1f59}'), ('\u{1f5b}', '\u{1f5b}'), - ('\u{1f5d}', '\u{1f5d}'), ('\u{1f5f}', '\u{1f7d}'), ('\u{1f80}', - '\u{1fb4}'), ('\u{1fb6}', '\u{1fbc}'), ('\u{1fbe}', '\u{1fbe}'), - ('\u{1fc2}', '\u{1fc4}'), ('\u{1fc6}', '\u{1fcc}'), ('\u{1fd0}', - '\u{1fd3}'), ('\u{1fd6}', '\u{1fdb}'), ('\u{1fe0}', '\u{1fec}'), - ('\u{1ff2}', '\u{1ff4}'), ('\u{1ff6}', '\u{1ffc}'), ('\u{2071}', - '\u{2071}'), ('\u{207f}', '\u{207f}'), ('\u{2090}', '\u{209c}'), - ('\u{2102}', '\u{2102}'), ('\u{2107}', '\u{2107}'), ('\u{210a}', - '\u{2113}'), ('\u{2115}', '\u{2115}'), ('\u{2119}', '\u{211d}'), - ('\u{2124}', '\u{2124}'), ('\u{2126}', '\u{2126}'), ('\u{2128}', - '\u{2128}'), ('\u{212a}', '\u{212d}'), ('\u{212f}', '\u{2139}'), - ('\u{213c}', '\u{213f}'), ('\u{2145}', '\u{2149}'), ('\u{214e}', - '\u{214e}'), ('\u{2183}', '\u{2184}'), ('\u{2c00}', '\u{2c2e}'), - ('\u{2c30}', '\u{2c5e}'), ('\u{2c60}', '\u{2ce4}'), ('\u{2ceb}', - '\u{2cee}'), ('\u{2cf2}', '\u{2cf3}'), ('\u{2d00}', '\u{2d25}'), - ('\u{2d27}', '\u{2d27}'), ('\u{2d2d}', '\u{2d2d}'), ('\u{2d30}', - '\u{2d67}'), ('\u{2d6f}', '\u{2d6f}'), ('\u{2d80}', '\u{2d96}'), - ('\u{2da0}', '\u{2da6}'), ('\u{2da8}', '\u{2dae}'), ('\u{2db0}', - '\u{2db6}'), ('\u{2db8}', '\u{2dbe}'), ('\u{2dc0}', '\u{2dc6}'), - ('\u{2dc8}', '\u{2dce}'), ('\u{2dd0}', '\u{2dd6}'), ('\u{2dd8}', - '\u{2dde}'), ('\u{2e2f}', '\u{2e2f}'), ('\u{3005}', '\u{3006}'), - ('\u{3031}', '\u{3035}'), ('\u{303b}', '\u{303c}'), ('\u{3041}', - '\u{3096}'), ('\u{309d}', '\u{309f}'), ('\u{30a1}', '\u{30fa}'), - ('\u{30fc}', '\u{30ff}'), ('\u{3105}', '\u{312e}'), ('\u{3131}', - '\u{318e}'), ('\u{31a0}', '\u{31ba}'), ('\u{31f0}', '\u{31ff}'), - ('\u{3400}', '\u{4db5}'), ('\u{4e00}', '\u{9fea}'), ('\u{a000}', - '\u{a48c}'), ('\u{a4d0}', '\u{a4fd}'), ('\u{a500}', '\u{a60c}'), - ('\u{a610}', '\u{a61f}'), ('\u{a62a}', '\u{a62b}'), ('\u{a640}', - '\u{a66e}'), ('\u{a67f}', '\u{a69d}'), ('\u{a6a0}', '\u{a6e5}'), - ('\u{a717}', '\u{a71f}'), ('\u{a722}', '\u{a788}'), ('\u{a78b}', - '\u{a7ae}'), ('\u{a7b0}', '\u{a7b7}'), ('\u{a7f7}', '\u{a801}'), - ('\u{a803}', '\u{a805}'), ('\u{a807}', '\u{a80a}'), ('\u{a80c}', - '\u{a822}'), ('\u{a840}', '\u{a873}'), ('\u{a882}', '\u{a8b3}'), - ('\u{a8f2}', '\u{a8f7}'), ('\u{a8fb}', '\u{a8fb}'), ('\u{a8fd}', - '\u{a8fd}'), ('\u{a90a}', '\u{a925}'), ('\u{a930}', '\u{a946}'), - ('\u{a960}', '\u{a97c}'), ('\u{a984}', '\u{a9b2}'), ('\u{a9cf}', - '\u{a9cf}'), ('\u{a9e0}', '\u{a9e4}'), ('\u{a9e6}', '\u{a9ef}'), - ('\u{a9fa}', '\u{a9fe}'), ('\u{aa00}', '\u{aa28}'), ('\u{aa40}', - '\u{aa42}'), ('\u{aa44}', '\u{aa4b}'), ('\u{aa60}', '\u{aa76}'), - ('\u{aa7a}', '\u{aa7a}'), ('\u{aa7e}', '\u{aaaf}'), ('\u{aab1}', - '\u{aab1}'), ('\u{aab5}', '\u{aab6}'), ('\u{aab9}', '\u{aabd}'), - ('\u{aac0}', '\u{aac0}'), ('\u{aac2}', '\u{aac2}'), ('\u{aadb}', - '\u{aadd}'), ('\u{aae0}', '\u{aaea}'), ('\u{aaf2}', '\u{aaf4}'), - ('\u{ab01}', '\u{ab06}'), ('\u{ab09}', '\u{ab0e}'), ('\u{ab11}', - '\u{ab16}'), ('\u{ab20}', '\u{ab26}'), ('\u{ab28}', '\u{ab2e}'), - ('\u{ab30}', '\u{ab5a}'), ('\u{ab5c}', '\u{ab65}'), ('\u{ab70}', - '\u{abe2}'), ('\u{ac00}', '\u{d7a3}'), ('\u{d7b0}', '\u{d7c6}'), - ('\u{d7cb}', '\u{d7fb}'), ('\u{f900}', '\u{fa6d}'), ('\u{fa70}', - '\u{fad9}'), ('\u{fb00}', '\u{fb06}'), ('\u{fb13}', '\u{fb17}'), - ('\u{fb1d}', '\u{fb1d}'), ('\u{fb1f}', '\u{fb28}'), ('\u{fb2a}', - '\u{fb36}'), ('\u{fb38}', '\u{fb3c}'), ('\u{fb3e}', '\u{fb3e}'), - ('\u{fb40}', '\u{fb41}'), ('\u{fb43}', '\u{fb44}'), ('\u{fb46}', - '\u{fbb1}'), ('\u{fbd3}', '\u{fd3d}'), ('\u{fd50}', '\u{fd8f}'), - ('\u{fd92}', '\u{fdc7}'), ('\u{fdf0}', '\u{fdfb}'), ('\u{fe70}', - '\u{fe74}'), ('\u{fe76}', '\u{fefc}'), ('\u{ff21}', '\u{ff3a}'), - ('\u{ff41}', '\u{ff5a}'), ('\u{ff66}', '\u{ffbe}'), ('\u{ffc2}', - '\u{ffc7}'), ('\u{ffca}', '\u{ffcf}'), ('\u{ffd2}', '\u{ffd7}'), - ('\u{ffda}', '\u{ffdc}'), ('\u{10000}', '\u{1000b}'), ('\u{1000d}', - '\u{10026}'), ('\u{10028}', '\u{1003a}'), ('\u{1003c}', '\u{1003d}'), - ('\u{1003f}', '\u{1004d}'), ('\u{10050}', '\u{1005d}'), ('\u{10080}', - '\u{100fa}'), ('\u{10280}', '\u{1029c}'), ('\u{102a0}', '\u{102d0}'), - ('\u{10300}', '\u{1031f}'), ('\u{1032d}', '\u{10340}'), ('\u{10342}', - '\u{10349}'), ('\u{10350}', '\u{10375}'), ('\u{10380}', '\u{1039d}'), - ('\u{103a0}', '\u{103c3}'), ('\u{103c8}', '\u{103cf}'), ('\u{10400}', - '\u{1049d}'), ('\u{104b0}', '\u{104d3}'), ('\u{104d8}', '\u{104fb}'), - ('\u{10500}', '\u{10527}'), ('\u{10530}', '\u{10563}'), ('\u{10600}', - '\u{10736}'), ('\u{10740}', '\u{10755}'), ('\u{10760}', '\u{10767}'), - ('\u{10800}', '\u{10805}'), ('\u{10808}', '\u{10808}'), ('\u{1080a}', - '\u{10835}'), ('\u{10837}', '\u{10838}'), ('\u{1083c}', '\u{1083c}'), - ('\u{1083f}', '\u{10855}'), ('\u{10860}', '\u{10876}'), ('\u{10880}', - '\u{1089e}'), ('\u{108e0}', '\u{108f2}'), ('\u{108f4}', '\u{108f5}'), - ('\u{10900}', '\u{10915}'), ('\u{10920}', '\u{10939}'), ('\u{10980}', - '\u{109b7}'), ('\u{109be}', '\u{109bf}'), ('\u{10a00}', '\u{10a00}'), - ('\u{10a10}', '\u{10a13}'), ('\u{10a15}', '\u{10a17}'), ('\u{10a19}', - '\u{10a33}'), ('\u{10a60}', '\u{10a7c}'), ('\u{10a80}', '\u{10a9c}'), - ('\u{10ac0}', '\u{10ac7}'), ('\u{10ac9}', '\u{10ae4}'), ('\u{10b00}', - '\u{10b35}'), ('\u{10b40}', '\u{10b55}'), ('\u{10b60}', '\u{10b72}'), - ('\u{10b80}', '\u{10b91}'), ('\u{10c00}', '\u{10c48}'), ('\u{10c80}', - '\u{10cb2}'), ('\u{10cc0}', '\u{10cf2}'), ('\u{11003}', '\u{11037}'), - ('\u{11083}', '\u{110af}'), ('\u{110d0}', '\u{110e8}'), ('\u{11103}', - '\u{11126}'), ('\u{11150}', '\u{11172}'), ('\u{11176}', '\u{11176}'), - ('\u{11183}', '\u{111b2}'), ('\u{111c1}', '\u{111c4}'), ('\u{111da}', - '\u{111da}'), ('\u{111dc}', '\u{111dc}'), ('\u{11200}', '\u{11211}'), - ('\u{11213}', '\u{1122b}'), ('\u{11280}', '\u{11286}'), ('\u{11288}', - '\u{11288}'), ('\u{1128a}', '\u{1128d}'), ('\u{1128f}', '\u{1129d}'), - ('\u{1129f}', '\u{112a8}'), ('\u{112b0}', '\u{112de}'), ('\u{11305}', - '\u{1130c}'), ('\u{1130f}', '\u{11310}'), ('\u{11313}', '\u{11328}'), - ('\u{1132a}', '\u{11330}'), ('\u{11332}', '\u{11333}'), ('\u{11335}', - '\u{11339}'), ('\u{1133d}', '\u{1133d}'), ('\u{11350}', '\u{11350}'), - ('\u{1135d}', '\u{11361}'), ('\u{11400}', '\u{11434}'), ('\u{11447}', - '\u{1144a}'), ('\u{11480}', '\u{114af}'), ('\u{114c4}', '\u{114c5}'), - ('\u{114c7}', '\u{114c7}'), ('\u{11580}', '\u{115ae}'), ('\u{115d8}', - '\u{115db}'), ('\u{11600}', '\u{1162f}'), ('\u{11644}', '\u{11644}'), - ('\u{11680}', '\u{116aa}'), ('\u{11700}', '\u{11719}'), ('\u{118a0}', - '\u{118df}'), ('\u{118ff}', '\u{118ff}'), ('\u{11a00}', '\u{11a00}'), - ('\u{11a0b}', '\u{11a32}'), ('\u{11a3a}', '\u{11a3a}'), ('\u{11a50}', - '\u{11a50}'), ('\u{11a5c}', '\u{11a83}'), ('\u{11a86}', '\u{11a89}'), - ('\u{11ac0}', '\u{11af8}'), ('\u{11c00}', '\u{11c08}'), ('\u{11c0a}', - '\u{11c2e}'), ('\u{11c40}', '\u{11c40}'), ('\u{11c72}', '\u{11c8f}'), - ('\u{11d00}', '\u{11d06}'), ('\u{11d08}', '\u{11d09}'), ('\u{11d0b}', - '\u{11d30}'), ('\u{11d46}', '\u{11d46}'), ('\u{12000}', '\u{12399}'), - ('\u{12480}', '\u{12543}'), ('\u{13000}', '\u{1342e}'), ('\u{14400}', - '\u{14646}'), ('\u{16800}', '\u{16a38}'), ('\u{16a40}', '\u{16a5e}'), - ('\u{16ad0}', '\u{16aed}'), ('\u{16b00}', '\u{16b2f}'), ('\u{16b40}', - '\u{16b43}'), ('\u{16b63}', '\u{16b77}'), ('\u{16b7d}', '\u{16b8f}'), - ('\u{16f00}', '\u{16f44}'), ('\u{16f50}', '\u{16f50}'), ('\u{16f93}', - '\u{16f9f}'), ('\u{16fe0}', '\u{16fe1}'), ('\u{17000}', '\u{187ec}'), - ('\u{18800}', '\u{18af2}'), ('\u{1b000}', '\u{1b11e}'), ('\u{1b170}', - '\u{1b2fb}'), ('\u{1bc00}', '\u{1bc6a}'), ('\u{1bc70}', '\u{1bc7c}'), - ('\u{1bc80}', '\u{1bc88}'), ('\u{1bc90}', '\u{1bc99}'), ('\u{1d400}', - '\u{1d454}'), ('\u{1d456}', '\u{1d49c}'), ('\u{1d49e}', '\u{1d49f}'), - ('\u{1d4a2}', '\u{1d4a2}'), ('\u{1d4a5}', '\u{1d4a6}'), ('\u{1d4a9}', - '\u{1d4ac}'), ('\u{1d4ae}', '\u{1d4b9}'), ('\u{1d4bb}', '\u{1d4bb}'), - ('\u{1d4bd}', '\u{1d4c3}'), ('\u{1d4c5}', '\u{1d505}'), ('\u{1d507}', - '\u{1d50a}'), ('\u{1d50d}', '\u{1d514}'), ('\u{1d516}', '\u{1d51c}'), - ('\u{1d51e}', '\u{1d539}'), ('\u{1d53b}', '\u{1d53e}'), ('\u{1d540}', - '\u{1d544}'), ('\u{1d546}', '\u{1d546}'), ('\u{1d54a}', '\u{1d550}'), - ('\u{1d552}', '\u{1d6a5}'), ('\u{1d6a8}', '\u{1d6c0}'), ('\u{1d6c2}', - '\u{1d6da}'), ('\u{1d6dc}', '\u{1d6fa}'), ('\u{1d6fc}', '\u{1d714}'), - ('\u{1d716}', '\u{1d734}'), ('\u{1d736}', '\u{1d74e}'), ('\u{1d750}', - '\u{1d76e}'), ('\u{1d770}', '\u{1d788}'), ('\u{1d78a}', '\u{1d7a8}'), - ('\u{1d7aa}', '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7cb}'), ('\u{1e800}', - '\u{1e8c4}'), ('\u{1e900}', '\u{1e943}'), ('\u{1ee00}', '\u{1ee03}'), - ('\u{1ee05}', '\u{1ee1f}'), ('\u{1ee21}', '\u{1ee22}'), ('\u{1ee24}', - '\u{1ee24}'), ('\u{1ee27}', '\u{1ee27}'), ('\u{1ee29}', '\u{1ee32}'), - ('\u{1ee34}', '\u{1ee37}'), ('\u{1ee39}', '\u{1ee39}'), ('\u{1ee3b}', - '\u{1ee3b}'), ('\u{1ee42}', '\u{1ee42}'), ('\u{1ee47}', '\u{1ee47}'), - ('\u{1ee49}', '\u{1ee49}'), ('\u{1ee4b}', '\u{1ee4b}'), ('\u{1ee4d}', - '\u{1ee4f}'), ('\u{1ee51}', '\u{1ee52}'), ('\u{1ee54}', '\u{1ee54}'), - ('\u{1ee57}', '\u{1ee57}'), ('\u{1ee59}', '\u{1ee59}'), ('\u{1ee5b}', - '\u{1ee5b}'), ('\u{1ee5d}', '\u{1ee5d}'), ('\u{1ee5f}', '\u{1ee5f}'), - ('\u{1ee61}', '\u{1ee62}'), ('\u{1ee64}', '\u{1ee64}'), ('\u{1ee67}', - '\u{1ee6a}'), ('\u{1ee6c}', '\u{1ee72}'), ('\u{1ee74}', '\u{1ee77}'), - ('\u{1ee79}', '\u{1ee7c}'), ('\u{1ee7e}', '\u{1ee7e}'), ('\u{1ee80}', - '\u{1ee89}'), ('\u{1ee8b}', '\u{1ee9b}'), ('\u{1eea1}', '\u{1eea3}'), - ('\u{1eea5}', '\u{1eea9}'), ('\u{1eeab}', '\u{1eebb}'), ('\u{20000}', - '\u{2a6d6}'), ('\u{2a700}', '\u{2b734}'), ('\u{2b740}', '\u{2b81d}'), - ('\u{2b820}', '\u{2cea1}'), ('\u{2ceb0}', '\u{2ebe0}'), ('\u{2f800}', - '\u{2fa1d}') - ]; - - pub const LC_table: &'static [(char, char)] = &[ - ('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{b5}', '\u{b5}'), - ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{1ba}'), - ('\u{1bc}', '\u{1bf}'), ('\u{1c4}', '\u{293}'), ('\u{295}', '\u{2af}'), - ('\u{370}', '\u{373}'), ('\u{376}', '\u{377}'), ('\u{37b}', '\u{37d}'), - ('\u{37f}', '\u{37f}'), ('\u{386}', '\u{386}'), ('\u{388}', '\u{38a}'), - ('\u{38c}', '\u{38c}'), ('\u{38e}', '\u{3a1}'), ('\u{3a3}', '\u{3f5}'), - ('\u{3f7}', '\u{481}'), ('\u{48a}', '\u{52f}'), ('\u{531}', '\u{556}'), - ('\u{561}', '\u{587}'), ('\u{10a0}', '\u{10c5}'), ('\u{10c7}', - '\u{10c7}'), ('\u{10cd}', '\u{10cd}'), ('\u{13a0}', '\u{13f5}'), - ('\u{13f8}', '\u{13fd}'), ('\u{1c80}', '\u{1c88}'), ('\u{1d00}', - '\u{1d2b}'), ('\u{1d6b}', '\u{1d77}'), ('\u{1d79}', '\u{1d9a}'), - ('\u{1e00}', '\u{1f15}'), ('\u{1f18}', '\u{1f1d}'), ('\u{1f20}', - '\u{1f45}'), ('\u{1f48}', '\u{1f4d}'), ('\u{1f50}', '\u{1f57}'), - ('\u{1f59}', '\u{1f59}'), ('\u{1f5b}', '\u{1f5b}'), ('\u{1f5d}', - '\u{1f5d}'), ('\u{1f5f}', '\u{1f7d}'), ('\u{1f80}', '\u{1fb4}'), - ('\u{1fb6}', '\u{1fbc}'), ('\u{1fbe}', '\u{1fbe}'), ('\u{1fc2}', - '\u{1fc4}'), ('\u{1fc6}', '\u{1fcc}'), ('\u{1fd0}', '\u{1fd3}'), - ('\u{1fd6}', '\u{1fdb}'), ('\u{1fe0}', '\u{1fec}'), ('\u{1ff2}', - '\u{1ff4}'), ('\u{1ff6}', '\u{1ffc}'), ('\u{2102}', '\u{2102}'), - ('\u{2107}', '\u{2107}'), ('\u{210a}', '\u{2113}'), ('\u{2115}', - '\u{2115}'), ('\u{2119}', '\u{211d}'), ('\u{2124}', '\u{2124}'), - ('\u{2126}', '\u{2126}'), ('\u{2128}', '\u{2128}'), ('\u{212a}', - '\u{212d}'), ('\u{212f}', '\u{2134}'), ('\u{2139}', '\u{2139}'), - ('\u{213c}', '\u{213f}'), ('\u{2145}', '\u{2149}'), ('\u{214e}', - '\u{214e}'), ('\u{2183}', '\u{2184}'), ('\u{2c00}', '\u{2c2e}'), - ('\u{2c30}', '\u{2c5e}'), ('\u{2c60}', '\u{2c7b}'), ('\u{2c7e}', - '\u{2ce4}'), ('\u{2ceb}', '\u{2cee}'), ('\u{2cf2}', '\u{2cf3}'), - ('\u{2d00}', '\u{2d25}'), ('\u{2d27}', '\u{2d27}'), ('\u{2d2d}', - '\u{2d2d}'), ('\u{a640}', '\u{a66d}'), ('\u{a680}', '\u{a69b}'), - ('\u{a722}', '\u{a76f}'), ('\u{a771}', '\u{a787}'), ('\u{a78b}', - '\u{a78e}'), ('\u{a790}', '\u{a7ae}'), ('\u{a7b0}', '\u{a7b7}'), - ('\u{a7fa}', '\u{a7fa}'), ('\u{ab30}', '\u{ab5a}'), ('\u{ab60}', - '\u{ab65}'), ('\u{ab70}', '\u{abbf}'), ('\u{fb00}', '\u{fb06}'), - ('\u{fb13}', '\u{fb17}'), ('\u{ff21}', '\u{ff3a}'), ('\u{ff41}', - '\u{ff5a}'), ('\u{10400}', '\u{1044f}'), ('\u{104b0}', '\u{104d3}'), - ('\u{104d8}', '\u{104fb}'), ('\u{10c80}', '\u{10cb2}'), ('\u{10cc0}', - '\u{10cf2}'), ('\u{118a0}', '\u{118df}'), ('\u{1d400}', '\u{1d454}'), - ('\u{1d456}', '\u{1d49c}'), ('\u{1d49e}', '\u{1d49f}'), ('\u{1d4a2}', - '\u{1d4a2}'), ('\u{1d4a5}', '\u{1d4a6}'), ('\u{1d4a9}', '\u{1d4ac}'), - ('\u{1d4ae}', '\u{1d4b9}'), ('\u{1d4bb}', '\u{1d4bb}'), ('\u{1d4bd}', - '\u{1d4c3}'), ('\u{1d4c5}', '\u{1d505}'), ('\u{1d507}', '\u{1d50a}'), - ('\u{1d50d}', '\u{1d514}'), ('\u{1d516}', '\u{1d51c}'), ('\u{1d51e}', - '\u{1d539}'), ('\u{1d53b}', '\u{1d53e}'), ('\u{1d540}', '\u{1d544}'), - ('\u{1d546}', '\u{1d546}'), ('\u{1d54a}', '\u{1d550}'), ('\u{1d552}', - '\u{1d6a5}'), ('\u{1d6a8}', '\u{1d6c0}'), ('\u{1d6c2}', '\u{1d6da}'), - ('\u{1d6dc}', '\u{1d6fa}'), ('\u{1d6fc}', '\u{1d714}'), ('\u{1d716}', - '\u{1d734}'), ('\u{1d736}', '\u{1d74e}'), ('\u{1d750}', '\u{1d76e}'), - ('\u{1d770}', '\u{1d788}'), ('\u{1d78a}', '\u{1d7a8}'), ('\u{1d7aa}', - '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7cb}'), ('\u{1e900}', '\u{1e943}') - ]; - - pub const Ll_table: &'static [(char, char)] = &[ - ('\u{61}', '\u{7a}'), ('\u{b5}', '\u{b5}'), ('\u{df}', '\u{f6}'), - ('\u{f8}', '\u{ff}'), ('\u{101}', '\u{101}'), ('\u{103}', '\u{103}'), - ('\u{105}', '\u{105}'), ('\u{107}', '\u{107}'), ('\u{109}', '\u{109}'), - ('\u{10b}', '\u{10b}'), ('\u{10d}', '\u{10d}'), ('\u{10f}', '\u{10f}'), - ('\u{111}', '\u{111}'), ('\u{113}', '\u{113}'), ('\u{115}', '\u{115}'), - ('\u{117}', '\u{117}'), ('\u{119}', '\u{119}'), ('\u{11b}', '\u{11b}'), - ('\u{11d}', '\u{11d}'), ('\u{11f}', '\u{11f}'), ('\u{121}', '\u{121}'), - ('\u{123}', '\u{123}'), ('\u{125}', '\u{125}'), ('\u{127}', '\u{127}'), - ('\u{129}', '\u{129}'), ('\u{12b}', '\u{12b}'), ('\u{12d}', '\u{12d}'), - ('\u{12f}', '\u{12f}'), ('\u{131}', '\u{131}'), ('\u{133}', '\u{133}'), - ('\u{135}', '\u{135}'), ('\u{137}', '\u{138}'), ('\u{13a}', '\u{13a}'), - ('\u{13c}', '\u{13c}'), ('\u{13e}', '\u{13e}'), ('\u{140}', '\u{140}'), - ('\u{142}', '\u{142}'), ('\u{144}', '\u{144}'), ('\u{146}', '\u{146}'), - ('\u{148}', '\u{149}'), ('\u{14b}', '\u{14b}'), ('\u{14d}', '\u{14d}'), - ('\u{14f}', '\u{14f}'), ('\u{151}', '\u{151}'), ('\u{153}', '\u{153}'), - ('\u{155}', '\u{155}'), ('\u{157}', '\u{157}'), ('\u{159}', '\u{159}'), - ('\u{15b}', '\u{15b}'), ('\u{15d}', '\u{15d}'), ('\u{15f}', '\u{15f}'), - ('\u{161}', '\u{161}'), ('\u{163}', '\u{163}'), ('\u{165}', '\u{165}'), - ('\u{167}', '\u{167}'), ('\u{169}', '\u{169}'), ('\u{16b}', '\u{16b}'), - ('\u{16d}', '\u{16d}'), ('\u{16f}', '\u{16f}'), ('\u{171}', '\u{171}'), - ('\u{173}', '\u{173}'), ('\u{175}', '\u{175}'), ('\u{177}', '\u{177}'), - ('\u{17a}', '\u{17a}'), ('\u{17c}', '\u{17c}'), ('\u{17e}', '\u{180}'), - ('\u{183}', '\u{183}'), ('\u{185}', '\u{185}'), ('\u{188}', '\u{188}'), - ('\u{18c}', '\u{18d}'), ('\u{192}', '\u{192}'), ('\u{195}', '\u{195}'), - ('\u{199}', '\u{19b}'), ('\u{19e}', '\u{19e}'), ('\u{1a1}', '\u{1a1}'), - ('\u{1a3}', '\u{1a3}'), ('\u{1a5}', '\u{1a5}'), ('\u{1a8}', '\u{1a8}'), - ('\u{1aa}', '\u{1ab}'), ('\u{1ad}', '\u{1ad}'), ('\u{1b0}', '\u{1b0}'), - ('\u{1b4}', '\u{1b4}'), ('\u{1b6}', '\u{1b6}'), ('\u{1b9}', '\u{1ba}'), - ('\u{1bd}', '\u{1bf}'), ('\u{1c6}', '\u{1c6}'), ('\u{1c9}', '\u{1c9}'), - ('\u{1cc}', '\u{1cc}'), ('\u{1ce}', '\u{1ce}'), ('\u{1d0}', '\u{1d0}'), - ('\u{1d2}', '\u{1d2}'), ('\u{1d4}', '\u{1d4}'), ('\u{1d6}', '\u{1d6}'), - ('\u{1d8}', '\u{1d8}'), ('\u{1da}', '\u{1da}'), ('\u{1dc}', '\u{1dd}'), - ('\u{1df}', '\u{1df}'), ('\u{1e1}', '\u{1e1}'), ('\u{1e3}', '\u{1e3}'), - ('\u{1e5}', '\u{1e5}'), ('\u{1e7}', '\u{1e7}'), ('\u{1e9}', '\u{1e9}'), - ('\u{1eb}', '\u{1eb}'), ('\u{1ed}', '\u{1ed}'), ('\u{1ef}', '\u{1f0}'), - ('\u{1f3}', '\u{1f3}'), ('\u{1f5}', '\u{1f5}'), ('\u{1f9}', '\u{1f9}'), - ('\u{1fb}', '\u{1fb}'), ('\u{1fd}', '\u{1fd}'), ('\u{1ff}', '\u{1ff}'), - ('\u{201}', '\u{201}'), ('\u{203}', '\u{203}'), ('\u{205}', '\u{205}'), - ('\u{207}', '\u{207}'), ('\u{209}', '\u{209}'), ('\u{20b}', '\u{20b}'), - ('\u{20d}', '\u{20d}'), ('\u{20f}', '\u{20f}'), ('\u{211}', '\u{211}'), - ('\u{213}', '\u{213}'), ('\u{215}', '\u{215}'), ('\u{217}', '\u{217}'), - ('\u{219}', '\u{219}'), ('\u{21b}', '\u{21b}'), ('\u{21d}', '\u{21d}'), - ('\u{21f}', '\u{21f}'), ('\u{221}', '\u{221}'), ('\u{223}', '\u{223}'), - ('\u{225}', '\u{225}'), ('\u{227}', '\u{227}'), ('\u{229}', '\u{229}'), - ('\u{22b}', '\u{22b}'), ('\u{22d}', '\u{22d}'), ('\u{22f}', '\u{22f}'), - ('\u{231}', '\u{231}'), ('\u{233}', '\u{239}'), ('\u{23c}', '\u{23c}'), - ('\u{23f}', '\u{240}'), ('\u{242}', '\u{242}'), ('\u{247}', '\u{247}'), - ('\u{249}', '\u{249}'), ('\u{24b}', '\u{24b}'), ('\u{24d}', '\u{24d}'), - ('\u{24f}', '\u{293}'), ('\u{295}', '\u{2af}'), ('\u{371}', '\u{371}'), - ('\u{373}', '\u{373}'), ('\u{377}', '\u{377}'), ('\u{37b}', '\u{37d}'), - ('\u{390}', '\u{390}'), ('\u{3ac}', '\u{3ce}'), ('\u{3d0}', '\u{3d1}'), - ('\u{3d5}', '\u{3d7}'), ('\u{3d9}', '\u{3d9}'), ('\u{3db}', '\u{3db}'), - ('\u{3dd}', '\u{3dd}'), ('\u{3df}', '\u{3df}'), ('\u{3e1}', '\u{3e1}'), - ('\u{3e3}', '\u{3e3}'), ('\u{3e5}', '\u{3e5}'), ('\u{3e7}', '\u{3e7}'), - ('\u{3e9}', '\u{3e9}'), ('\u{3eb}', '\u{3eb}'), ('\u{3ed}', '\u{3ed}'), - ('\u{3ef}', '\u{3f3}'), ('\u{3f5}', '\u{3f5}'), ('\u{3f8}', '\u{3f8}'), - ('\u{3fb}', '\u{3fc}'), ('\u{430}', '\u{45f}'), ('\u{461}', '\u{461}'), - ('\u{463}', '\u{463}'), ('\u{465}', '\u{465}'), ('\u{467}', '\u{467}'), - ('\u{469}', '\u{469}'), ('\u{46b}', '\u{46b}'), ('\u{46d}', '\u{46d}'), - ('\u{46f}', '\u{46f}'), ('\u{471}', '\u{471}'), ('\u{473}', '\u{473}'), - ('\u{475}', '\u{475}'), ('\u{477}', '\u{477}'), ('\u{479}', '\u{479}'), - ('\u{47b}', '\u{47b}'), ('\u{47d}', '\u{47d}'), ('\u{47f}', '\u{47f}'), - ('\u{481}', '\u{481}'), ('\u{48b}', '\u{48b}'), ('\u{48d}', '\u{48d}'), - ('\u{48f}', '\u{48f}'), ('\u{491}', '\u{491}'), ('\u{493}', '\u{493}'), - ('\u{495}', '\u{495}'), ('\u{497}', '\u{497}'), ('\u{499}', '\u{499}'), - ('\u{49b}', '\u{49b}'), ('\u{49d}', '\u{49d}'), ('\u{49f}', '\u{49f}'), - ('\u{4a1}', '\u{4a1}'), ('\u{4a3}', '\u{4a3}'), ('\u{4a5}', '\u{4a5}'), - ('\u{4a7}', '\u{4a7}'), ('\u{4a9}', '\u{4a9}'), ('\u{4ab}', '\u{4ab}'), - ('\u{4ad}', '\u{4ad}'), ('\u{4af}', '\u{4af}'), ('\u{4b1}', '\u{4b1}'), - ('\u{4b3}', '\u{4b3}'), ('\u{4b5}', '\u{4b5}'), ('\u{4b7}', '\u{4b7}'), - ('\u{4b9}', '\u{4b9}'), ('\u{4bb}', '\u{4bb}'), ('\u{4bd}', '\u{4bd}'), - ('\u{4bf}', '\u{4bf}'), ('\u{4c2}', '\u{4c2}'), ('\u{4c4}', '\u{4c4}'), - ('\u{4c6}', '\u{4c6}'), ('\u{4c8}', '\u{4c8}'), ('\u{4ca}', '\u{4ca}'), - ('\u{4cc}', '\u{4cc}'), ('\u{4ce}', '\u{4cf}'), ('\u{4d1}', '\u{4d1}'), - ('\u{4d3}', '\u{4d3}'), ('\u{4d5}', '\u{4d5}'), ('\u{4d7}', '\u{4d7}'), - ('\u{4d9}', '\u{4d9}'), ('\u{4db}', '\u{4db}'), ('\u{4dd}', '\u{4dd}'), - ('\u{4df}', '\u{4df}'), ('\u{4e1}', '\u{4e1}'), ('\u{4e3}', '\u{4e3}'), - ('\u{4e5}', '\u{4e5}'), ('\u{4e7}', '\u{4e7}'), ('\u{4e9}', '\u{4e9}'), - ('\u{4eb}', '\u{4eb}'), ('\u{4ed}', '\u{4ed}'), ('\u{4ef}', '\u{4ef}'), - ('\u{4f1}', '\u{4f1}'), ('\u{4f3}', '\u{4f3}'), ('\u{4f5}', '\u{4f5}'), - ('\u{4f7}', '\u{4f7}'), ('\u{4f9}', '\u{4f9}'), ('\u{4fb}', '\u{4fb}'), - ('\u{4fd}', '\u{4fd}'), ('\u{4ff}', '\u{4ff}'), ('\u{501}', '\u{501}'), - ('\u{503}', '\u{503}'), ('\u{505}', '\u{505}'), ('\u{507}', '\u{507}'), - ('\u{509}', '\u{509}'), ('\u{50b}', '\u{50b}'), ('\u{50d}', '\u{50d}'), - ('\u{50f}', '\u{50f}'), ('\u{511}', '\u{511}'), ('\u{513}', '\u{513}'), - ('\u{515}', '\u{515}'), ('\u{517}', '\u{517}'), ('\u{519}', '\u{519}'), - ('\u{51b}', '\u{51b}'), ('\u{51d}', '\u{51d}'), ('\u{51f}', '\u{51f}'), - ('\u{521}', '\u{521}'), ('\u{523}', '\u{523}'), ('\u{525}', '\u{525}'), - ('\u{527}', '\u{527}'), ('\u{529}', '\u{529}'), ('\u{52b}', '\u{52b}'), - ('\u{52d}', '\u{52d}'), ('\u{52f}', '\u{52f}'), ('\u{561}', '\u{587}'), - ('\u{13f8}', '\u{13fd}'), ('\u{1c80}', '\u{1c88}'), ('\u{1d00}', - '\u{1d2b}'), ('\u{1d6b}', '\u{1d77}'), ('\u{1d79}', '\u{1d9a}'), - ('\u{1e01}', '\u{1e01}'), ('\u{1e03}', '\u{1e03}'), ('\u{1e05}', - '\u{1e05}'), ('\u{1e07}', '\u{1e07}'), ('\u{1e09}', '\u{1e09}'), - ('\u{1e0b}', '\u{1e0b}'), ('\u{1e0d}', '\u{1e0d}'), ('\u{1e0f}', - '\u{1e0f}'), ('\u{1e11}', '\u{1e11}'), ('\u{1e13}', '\u{1e13}'), - ('\u{1e15}', '\u{1e15}'), ('\u{1e17}', '\u{1e17}'), ('\u{1e19}', - '\u{1e19}'), ('\u{1e1b}', '\u{1e1b}'), ('\u{1e1d}', '\u{1e1d}'), - ('\u{1e1f}', '\u{1e1f}'), ('\u{1e21}', '\u{1e21}'), ('\u{1e23}', - '\u{1e23}'), ('\u{1e25}', '\u{1e25}'), ('\u{1e27}', '\u{1e27}'), - ('\u{1e29}', '\u{1e29}'), ('\u{1e2b}', '\u{1e2b}'), ('\u{1e2d}', - '\u{1e2d}'), ('\u{1e2f}', '\u{1e2f}'), ('\u{1e31}', '\u{1e31}'), - ('\u{1e33}', '\u{1e33}'), ('\u{1e35}', '\u{1e35}'), ('\u{1e37}', - '\u{1e37}'), ('\u{1e39}', '\u{1e39}'), ('\u{1e3b}', '\u{1e3b}'), - ('\u{1e3d}', '\u{1e3d}'), ('\u{1e3f}', '\u{1e3f}'), ('\u{1e41}', - '\u{1e41}'), ('\u{1e43}', '\u{1e43}'), ('\u{1e45}', '\u{1e45}'), - ('\u{1e47}', '\u{1e47}'), ('\u{1e49}', '\u{1e49}'), ('\u{1e4b}', - '\u{1e4b}'), ('\u{1e4d}', '\u{1e4d}'), ('\u{1e4f}', '\u{1e4f}'), - ('\u{1e51}', '\u{1e51}'), ('\u{1e53}', '\u{1e53}'), ('\u{1e55}', - '\u{1e55}'), ('\u{1e57}', '\u{1e57}'), ('\u{1e59}', '\u{1e59}'), - ('\u{1e5b}', '\u{1e5b}'), ('\u{1e5d}', '\u{1e5d}'), ('\u{1e5f}', - '\u{1e5f}'), ('\u{1e61}', '\u{1e61}'), ('\u{1e63}', '\u{1e63}'), - ('\u{1e65}', '\u{1e65}'), ('\u{1e67}', '\u{1e67}'), ('\u{1e69}', - '\u{1e69}'), ('\u{1e6b}', '\u{1e6b}'), ('\u{1e6d}', '\u{1e6d}'), - ('\u{1e6f}', '\u{1e6f}'), ('\u{1e71}', '\u{1e71}'), ('\u{1e73}', - '\u{1e73}'), ('\u{1e75}', '\u{1e75}'), ('\u{1e77}', '\u{1e77}'), - ('\u{1e79}', '\u{1e79}'), ('\u{1e7b}', '\u{1e7b}'), ('\u{1e7d}', - '\u{1e7d}'), ('\u{1e7f}', '\u{1e7f}'), ('\u{1e81}', '\u{1e81}'), - ('\u{1e83}', '\u{1e83}'), ('\u{1e85}', '\u{1e85}'), ('\u{1e87}', - '\u{1e87}'), ('\u{1e89}', '\u{1e89}'), ('\u{1e8b}', '\u{1e8b}'), - ('\u{1e8d}', '\u{1e8d}'), ('\u{1e8f}', '\u{1e8f}'), ('\u{1e91}', - '\u{1e91}'), ('\u{1e93}', '\u{1e93}'), ('\u{1e95}', '\u{1e9d}'), - ('\u{1e9f}', '\u{1e9f}'), ('\u{1ea1}', '\u{1ea1}'), ('\u{1ea3}', - '\u{1ea3}'), ('\u{1ea5}', '\u{1ea5}'), ('\u{1ea7}', '\u{1ea7}'), - ('\u{1ea9}', '\u{1ea9}'), ('\u{1eab}', '\u{1eab}'), ('\u{1ead}', - '\u{1ead}'), ('\u{1eaf}', '\u{1eaf}'), ('\u{1eb1}', '\u{1eb1}'), - ('\u{1eb3}', '\u{1eb3}'), ('\u{1eb5}', '\u{1eb5}'), ('\u{1eb7}', - '\u{1eb7}'), ('\u{1eb9}', '\u{1eb9}'), ('\u{1ebb}', '\u{1ebb}'), - ('\u{1ebd}', '\u{1ebd}'), ('\u{1ebf}', '\u{1ebf}'), ('\u{1ec1}', - '\u{1ec1}'), ('\u{1ec3}', '\u{1ec3}'), ('\u{1ec5}', '\u{1ec5}'), - ('\u{1ec7}', '\u{1ec7}'), ('\u{1ec9}', '\u{1ec9}'), ('\u{1ecb}', - '\u{1ecb}'), ('\u{1ecd}', '\u{1ecd}'), ('\u{1ecf}', '\u{1ecf}'), - ('\u{1ed1}', '\u{1ed1}'), ('\u{1ed3}', '\u{1ed3}'), ('\u{1ed5}', - '\u{1ed5}'), ('\u{1ed7}', '\u{1ed7}'), ('\u{1ed9}', '\u{1ed9}'), - ('\u{1edb}', '\u{1edb}'), ('\u{1edd}', '\u{1edd}'), ('\u{1edf}', - '\u{1edf}'), ('\u{1ee1}', '\u{1ee1}'), ('\u{1ee3}', '\u{1ee3}'), - ('\u{1ee5}', '\u{1ee5}'), ('\u{1ee7}', '\u{1ee7}'), ('\u{1ee9}', - '\u{1ee9}'), ('\u{1eeb}', '\u{1eeb}'), ('\u{1eed}', '\u{1eed}'), - ('\u{1eef}', '\u{1eef}'), ('\u{1ef1}', '\u{1ef1}'), ('\u{1ef3}', - '\u{1ef3}'), ('\u{1ef5}', '\u{1ef5}'), ('\u{1ef7}', '\u{1ef7}'), - ('\u{1ef9}', '\u{1ef9}'), ('\u{1efb}', '\u{1efb}'), ('\u{1efd}', - '\u{1efd}'), ('\u{1eff}', '\u{1f07}'), ('\u{1f10}', '\u{1f15}'), - ('\u{1f20}', '\u{1f27}'), ('\u{1f30}', '\u{1f37}'), ('\u{1f40}', - '\u{1f45}'), ('\u{1f50}', '\u{1f57}'), ('\u{1f60}', '\u{1f67}'), - ('\u{1f70}', '\u{1f7d}'), ('\u{1f80}', '\u{1f87}'), ('\u{1f90}', - '\u{1f97}'), ('\u{1fa0}', '\u{1fa7}'), ('\u{1fb0}', '\u{1fb4}'), - ('\u{1fb6}', '\u{1fb7}'), ('\u{1fbe}', '\u{1fbe}'), ('\u{1fc2}', - '\u{1fc4}'), ('\u{1fc6}', '\u{1fc7}'), ('\u{1fd0}', '\u{1fd3}'), - ('\u{1fd6}', '\u{1fd7}'), ('\u{1fe0}', '\u{1fe7}'), ('\u{1ff2}', - '\u{1ff4}'), ('\u{1ff6}', '\u{1ff7}'), ('\u{210a}', '\u{210a}'), - ('\u{210e}', '\u{210f}'), ('\u{2113}', '\u{2113}'), ('\u{212f}', - '\u{212f}'), ('\u{2134}', '\u{2134}'), ('\u{2139}', '\u{2139}'), - ('\u{213c}', '\u{213d}'), ('\u{2146}', '\u{2149}'), ('\u{214e}', - '\u{214e}'), ('\u{2184}', '\u{2184}'), ('\u{2c30}', '\u{2c5e}'), - ('\u{2c61}', '\u{2c61}'), ('\u{2c65}', '\u{2c66}'), ('\u{2c68}', - '\u{2c68}'), ('\u{2c6a}', '\u{2c6a}'), ('\u{2c6c}', '\u{2c6c}'), - ('\u{2c71}', '\u{2c71}'), ('\u{2c73}', '\u{2c74}'), ('\u{2c76}', - '\u{2c7b}'), ('\u{2c81}', '\u{2c81}'), ('\u{2c83}', '\u{2c83}'), - ('\u{2c85}', '\u{2c85}'), ('\u{2c87}', '\u{2c87}'), ('\u{2c89}', - '\u{2c89}'), ('\u{2c8b}', '\u{2c8b}'), ('\u{2c8d}', '\u{2c8d}'), - ('\u{2c8f}', '\u{2c8f}'), ('\u{2c91}', '\u{2c91}'), ('\u{2c93}', - '\u{2c93}'), ('\u{2c95}', '\u{2c95}'), ('\u{2c97}', '\u{2c97}'), - ('\u{2c99}', '\u{2c99}'), ('\u{2c9b}', '\u{2c9b}'), ('\u{2c9d}', - '\u{2c9d}'), ('\u{2c9f}', '\u{2c9f}'), ('\u{2ca1}', '\u{2ca1}'), - ('\u{2ca3}', '\u{2ca3}'), ('\u{2ca5}', '\u{2ca5}'), ('\u{2ca7}', - '\u{2ca7}'), ('\u{2ca9}', '\u{2ca9}'), ('\u{2cab}', '\u{2cab}'), - ('\u{2cad}', '\u{2cad}'), ('\u{2caf}', '\u{2caf}'), ('\u{2cb1}', - '\u{2cb1}'), ('\u{2cb3}', '\u{2cb3}'), ('\u{2cb5}', '\u{2cb5}'), - ('\u{2cb7}', '\u{2cb7}'), ('\u{2cb9}', '\u{2cb9}'), ('\u{2cbb}', - '\u{2cbb}'), ('\u{2cbd}', '\u{2cbd}'), ('\u{2cbf}', '\u{2cbf}'), - ('\u{2cc1}', '\u{2cc1}'), ('\u{2cc3}', '\u{2cc3}'), ('\u{2cc5}', - '\u{2cc5}'), ('\u{2cc7}', '\u{2cc7}'), ('\u{2cc9}', '\u{2cc9}'), - ('\u{2ccb}', '\u{2ccb}'), ('\u{2ccd}', '\u{2ccd}'), ('\u{2ccf}', - '\u{2ccf}'), ('\u{2cd1}', '\u{2cd1}'), ('\u{2cd3}', '\u{2cd3}'), - ('\u{2cd5}', '\u{2cd5}'), ('\u{2cd7}', '\u{2cd7}'), ('\u{2cd9}', - '\u{2cd9}'), ('\u{2cdb}', '\u{2cdb}'), ('\u{2cdd}', '\u{2cdd}'), - ('\u{2cdf}', '\u{2cdf}'), ('\u{2ce1}', '\u{2ce1}'), ('\u{2ce3}', - '\u{2ce4}'), ('\u{2cec}', '\u{2cec}'), ('\u{2cee}', '\u{2cee}'), - ('\u{2cf3}', '\u{2cf3}'), ('\u{2d00}', '\u{2d25}'), ('\u{2d27}', - '\u{2d27}'), ('\u{2d2d}', '\u{2d2d}'), ('\u{a641}', '\u{a641}'), - ('\u{a643}', '\u{a643}'), ('\u{a645}', '\u{a645}'), ('\u{a647}', - '\u{a647}'), ('\u{a649}', '\u{a649}'), ('\u{a64b}', '\u{a64b}'), - ('\u{a64d}', '\u{a64d}'), ('\u{a64f}', '\u{a64f}'), ('\u{a651}', - '\u{a651}'), ('\u{a653}', '\u{a653}'), ('\u{a655}', '\u{a655}'), - ('\u{a657}', '\u{a657}'), ('\u{a659}', '\u{a659}'), ('\u{a65b}', - '\u{a65b}'), ('\u{a65d}', '\u{a65d}'), ('\u{a65f}', '\u{a65f}'), - ('\u{a661}', '\u{a661}'), ('\u{a663}', '\u{a663}'), ('\u{a665}', - '\u{a665}'), ('\u{a667}', '\u{a667}'), ('\u{a669}', '\u{a669}'), - ('\u{a66b}', '\u{a66b}'), ('\u{a66d}', '\u{a66d}'), ('\u{a681}', - '\u{a681}'), ('\u{a683}', '\u{a683}'), ('\u{a685}', '\u{a685}'), - ('\u{a687}', '\u{a687}'), ('\u{a689}', '\u{a689}'), ('\u{a68b}', - '\u{a68b}'), ('\u{a68d}', '\u{a68d}'), ('\u{a68f}', '\u{a68f}'), - ('\u{a691}', '\u{a691}'), ('\u{a693}', '\u{a693}'), ('\u{a695}', - '\u{a695}'), ('\u{a697}', '\u{a697}'), ('\u{a699}', '\u{a699}'), - ('\u{a69b}', '\u{a69b}'), ('\u{a723}', '\u{a723}'), ('\u{a725}', - '\u{a725}'), ('\u{a727}', '\u{a727}'), ('\u{a729}', '\u{a729}'), - ('\u{a72b}', '\u{a72b}'), ('\u{a72d}', '\u{a72d}'), ('\u{a72f}', - '\u{a731}'), ('\u{a733}', '\u{a733}'), ('\u{a735}', '\u{a735}'), - ('\u{a737}', '\u{a737}'), ('\u{a739}', '\u{a739}'), ('\u{a73b}', - '\u{a73b}'), ('\u{a73d}', '\u{a73d}'), ('\u{a73f}', '\u{a73f}'), - ('\u{a741}', '\u{a741}'), ('\u{a743}', '\u{a743}'), ('\u{a745}', - '\u{a745}'), ('\u{a747}', '\u{a747}'), ('\u{a749}', '\u{a749}'), - ('\u{a74b}', '\u{a74b}'), ('\u{a74d}', '\u{a74d}'), ('\u{a74f}', - '\u{a74f}'), ('\u{a751}', '\u{a751}'), ('\u{a753}', '\u{a753}'), - ('\u{a755}', '\u{a755}'), ('\u{a757}', '\u{a757}'), ('\u{a759}', - '\u{a759}'), ('\u{a75b}', '\u{a75b}'), ('\u{a75d}', '\u{a75d}'), - ('\u{a75f}', '\u{a75f}'), ('\u{a761}', '\u{a761}'), ('\u{a763}', - '\u{a763}'), ('\u{a765}', '\u{a765}'), ('\u{a767}', '\u{a767}'), - ('\u{a769}', '\u{a769}'), ('\u{a76b}', '\u{a76b}'), ('\u{a76d}', - '\u{a76d}'), ('\u{a76f}', '\u{a76f}'), ('\u{a771}', '\u{a778}'), - ('\u{a77a}', '\u{a77a}'), ('\u{a77c}', '\u{a77c}'), ('\u{a77f}', - '\u{a77f}'), ('\u{a781}', '\u{a781}'), ('\u{a783}', '\u{a783}'), - ('\u{a785}', '\u{a785}'), ('\u{a787}', '\u{a787}'), ('\u{a78c}', - '\u{a78c}'), ('\u{a78e}', '\u{a78e}'), ('\u{a791}', '\u{a791}'), - ('\u{a793}', '\u{a795}'), ('\u{a797}', '\u{a797}'), ('\u{a799}', - '\u{a799}'), ('\u{a79b}', '\u{a79b}'), ('\u{a79d}', '\u{a79d}'), - ('\u{a79f}', '\u{a79f}'), ('\u{a7a1}', '\u{a7a1}'), ('\u{a7a3}', - '\u{a7a3}'), ('\u{a7a5}', '\u{a7a5}'), ('\u{a7a7}', '\u{a7a7}'), - ('\u{a7a9}', '\u{a7a9}'), ('\u{a7b5}', '\u{a7b5}'), ('\u{a7b7}', - '\u{a7b7}'), ('\u{a7fa}', '\u{a7fa}'), ('\u{ab30}', '\u{ab5a}'), - ('\u{ab60}', '\u{ab65}'), ('\u{ab70}', '\u{abbf}'), ('\u{fb00}', - '\u{fb06}'), ('\u{fb13}', '\u{fb17}'), ('\u{ff41}', '\u{ff5a}'), - ('\u{10428}', '\u{1044f}'), ('\u{104d8}', '\u{104fb}'), ('\u{10cc0}', - '\u{10cf2}'), ('\u{118c0}', '\u{118df}'), ('\u{1d41a}', '\u{1d433}'), - ('\u{1d44e}', '\u{1d454}'), ('\u{1d456}', '\u{1d467}'), ('\u{1d482}', - '\u{1d49b}'), ('\u{1d4b6}', '\u{1d4b9}'), ('\u{1d4bb}', '\u{1d4bb}'), - ('\u{1d4bd}', '\u{1d4c3}'), ('\u{1d4c5}', '\u{1d4cf}'), ('\u{1d4ea}', - '\u{1d503}'), ('\u{1d51e}', '\u{1d537}'), ('\u{1d552}', '\u{1d56b}'), - ('\u{1d586}', '\u{1d59f}'), ('\u{1d5ba}', '\u{1d5d3}'), ('\u{1d5ee}', - '\u{1d607}'), ('\u{1d622}', '\u{1d63b}'), ('\u{1d656}', '\u{1d66f}'), - ('\u{1d68a}', '\u{1d6a5}'), ('\u{1d6c2}', '\u{1d6da}'), ('\u{1d6dc}', - '\u{1d6e1}'), ('\u{1d6fc}', '\u{1d714}'), ('\u{1d716}', '\u{1d71b}'), - ('\u{1d736}', '\u{1d74e}'), ('\u{1d750}', '\u{1d755}'), ('\u{1d770}', - '\u{1d788}'), ('\u{1d78a}', '\u{1d78f}'), ('\u{1d7aa}', '\u{1d7c2}'), - ('\u{1d7c4}', '\u{1d7c9}'), ('\u{1d7cb}', '\u{1d7cb}'), ('\u{1e922}', - '\u{1e943}') - ]; - - pub const Lm_table: &'static [(char, char)] = &[ - ('\u{2b0}', '\u{2c1}'), ('\u{2c6}', '\u{2d1}'), ('\u{2e0}', '\u{2e4}'), - ('\u{2ec}', '\u{2ec}'), ('\u{2ee}', '\u{2ee}'), ('\u{374}', '\u{374}'), - ('\u{37a}', '\u{37a}'), ('\u{559}', '\u{559}'), ('\u{640}', '\u{640}'), - ('\u{6e5}', '\u{6e6}'), ('\u{7f4}', '\u{7f5}'), ('\u{7fa}', '\u{7fa}'), - ('\u{81a}', '\u{81a}'), ('\u{824}', '\u{824}'), ('\u{828}', '\u{828}'), - ('\u{971}', '\u{971}'), ('\u{e46}', '\u{e46}'), ('\u{ec6}', '\u{ec6}'), - ('\u{10fc}', '\u{10fc}'), ('\u{17d7}', '\u{17d7}'), ('\u{1843}', - '\u{1843}'), ('\u{1aa7}', '\u{1aa7}'), ('\u{1c78}', '\u{1c7d}'), - ('\u{1d2c}', '\u{1d6a}'), ('\u{1d78}', '\u{1d78}'), ('\u{1d9b}', - '\u{1dbf}'), ('\u{2071}', '\u{2071}'), ('\u{207f}', '\u{207f}'), - ('\u{2090}', '\u{209c}'), ('\u{2c7c}', '\u{2c7d}'), ('\u{2d6f}', - '\u{2d6f}'), ('\u{2e2f}', '\u{2e2f}'), ('\u{3005}', '\u{3005}'), - ('\u{3031}', '\u{3035}'), ('\u{303b}', '\u{303b}'), ('\u{309d}', - '\u{309e}'), ('\u{30fc}', '\u{30fe}'), ('\u{a015}', '\u{a015}'), - ('\u{a4f8}', '\u{a4fd}'), ('\u{a60c}', '\u{a60c}'), ('\u{a67f}', - '\u{a67f}'), ('\u{a69c}', '\u{a69d}'), ('\u{a717}', '\u{a71f}'), - ('\u{a770}', '\u{a770}'), ('\u{a788}', '\u{a788}'), ('\u{a7f8}', - '\u{a7f9}'), ('\u{a9cf}', '\u{a9cf}'), ('\u{a9e6}', '\u{a9e6}'), - ('\u{aa70}', '\u{aa70}'), ('\u{aadd}', '\u{aadd}'), ('\u{aaf3}', - '\u{aaf4}'), ('\u{ab5c}', '\u{ab5f}'), ('\u{ff70}', '\u{ff70}'), - ('\u{ff9e}', '\u{ff9f}'), ('\u{16b40}', '\u{16b43}'), ('\u{16f93}', - '\u{16f9f}'), ('\u{16fe0}', '\u{16fe1}') - ]; - - pub const Lo_table: &'static [(char, char)] = &[ - ('\u{aa}', '\u{aa}'), ('\u{ba}', '\u{ba}'), ('\u{1bb}', '\u{1bb}'), - ('\u{1c0}', '\u{1c3}'), ('\u{294}', '\u{294}'), ('\u{5d0}', '\u{5ea}'), - ('\u{5f0}', '\u{5f2}'), ('\u{620}', '\u{63f}'), ('\u{641}', '\u{64a}'), - ('\u{66e}', '\u{66f}'), ('\u{671}', '\u{6d3}'), ('\u{6d5}', '\u{6d5}'), - ('\u{6ee}', '\u{6ef}'), ('\u{6fa}', '\u{6fc}'), ('\u{6ff}', '\u{6ff}'), - ('\u{710}', '\u{710}'), ('\u{712}', '\u{72f}'), ('\u{74d}', '\u{7a5}'), - ('\u{7b1}', '\u{7b1}'), ('\u{7ca}', '\u{7ea}'), ('\u{800}', '\u{815}'), - ('\u{840}', '\u{858}'), ('\u{860}', '\u{86a}'), ('\u{8a0}', '\u{8b4}'), - ('\u{8b6}', '\u{8bd}'), ('\u{904}', '\u{939}'), ('\u{93d}', '\u{93d}'), - ('\u{950}', '\u{950}'), ('\u{958}', '\u{961}'), ('\u{972}', '\u{980}'), - ('\u{985}', '\u{98c}'), ('\u{98f}', '\u{990}'), ('\u{993}', '\u{9a8}'), - ('\u{9aa}', '\u{9b0}'), ('\u{9b2}', '\u{9b2}'), ('\u{9b6}', '\u{9b9}'), - ('\u{9bd}', '\u{9bd}'), ('\u{9ce}', '\u{9ce}'), ('\u{9dc}', '\u{9dd}'), - ('\u{9df}', '\u{9e1}'), ('\u{9f0}', '\u{9f1}'), ('\u{9fc}', '\u{9fc}'), - ('\u{a05}', '\u{a0a}'), ('\u{a0f}', '\u{a10}'), ('\u{a13}', '\u{a28}'), - ('\u{a2a}', '\u{a30}'), ('\u{a32}', '\u{a33}'), ('\u{a35}', '\u{a36}'), - ('\u{a38}', '\u{a39}'), ('\u{a59}', '\u{a5c}'), ('\u{a5e}', '\u{a5e}'), - ('\u{a72}', '\u{a74}'), ('\u{a85}', '\u{a8d}'), ('\u{a8f}', '\u{a91}'), - ('\u{a93}', '\u{aa8}'), ('\u{aaa}', '\u{ab0}'), ('\u{ab2}', '\u{ab3}'), - ('\u{ab5}', '\u{ab9}'), ('\u{abd}', '\u{abd}'), ('\u{ad0}', '\u{ad0}'), - ('\u{ae0}', '\u{ae1}'), ('\u{af9}', '\u{af9}'), ('\u{b05}', '\u{b0c}'), - ('\u{b0f}', '\u{b10}'), ('\u{b13}', '\u{b28}'), ('\u{b2a}', '\u{b30}'), - ('\u{b32}', '\u{b33}'), ('\u{b35}', '\u{b39}'), ('\u{b3d}', '\u{b3d}'), - ('\u{b5c}', '\u{b5d}'), ('\u{b5f}', '\u{b61}'), ('\u{b71}', '\u{b71}'), - ('\u{b83}', '\u{b83}'), ('\u{b85}', '\u{b8a}'), ('\u{b8e}', '\u{b90}'), - ('\u{b92}', '\u{b95}'), ('\u{b99}', '\u{b9a}'), ('\u{b9c}', '\u{b9c}'), - ('\u{b9e}', '\u{b9f}'), ('\u{ba3}', '\u{ba4}'), ('\u{ba8}', '\u{baa}'), - ('\u{bae}', '\u{bb9}'), ('\u{bd0}', '\u{bd0}'), ('\u{c05}', '\u{c0c}'), - ('\u{c0e}', '\u{c10}'), ('\u{c12}', '\u{c28}'), ('\u{c2a}', '\u{c39}'), - ('\u{c3d}', '\u{c3d}'), ('\u{c58}', '\u{c5a}'), ('\u{c60}', '\u{c61}'), - ('\u{c80}', '\u{c80}'), ('\u{c85}', '\u{c8c}'), ('\u{c8e}', '\u{c90}'), - ('\u{c92}', '\u{ca8}'), ('\u{caa}', '\u{cb3}'), ('\u{cb5}', '\u{cb9}'), - ('\u{cbd}', '\u{cbd}'), ('\u{cde}', '\u{cde}'), ('\u{ce0}', '\u{ce1}'), - ('\u{cf1}', '\u{cf2}'), ('\u{d05}', '\u{d0c}'), ('\u{d0e}', '\u{d10}'), - ('\u{d12}', '\u{d3a}'), ('\u{d3d}', '\u{d3d}'), ('\u{d4e}', '\u{d4e}'), - ('\u{d54}', '\u{d56}'), ('\u{d5f}', '\u{d61}'), ('\u{d7a}', '\u{d7f}'), - ('\u{d85}', '\u{d96}'), ('\u{d9a}', '\u{db1}'), ('\u{db3}', '\u{dbb}'), - ('\u{dbd}', '\u{dbd}'), ('\u{dc0}', '\u{dc6}'), ('\u{e01}', '\u{e30}'), - ('\u{e32}', '\u{e33}'), ('\u{e40}', '\u{e45}'), ('\u{e81}', '\u{e82}'), - ('\u{e84}', '\u{e84}'), ('\u{e87}', '\u{e88}'), ('\u{e8a}', '\u{e8a}'), - ('\u{e8d}', '\u{e8d}'), ('\u{e94}', '\u{e97}'), ('\u{e99}', '\u{e9f}'), - ('\u{ea1}', '\u{ea3}'), ('\u{ea5}', '\u{ea5}'), ('\u{ea7}', '\u{ea7}'), - ('\u{eaa}', '\u{eab}'), ('\u{ead}', '\u{eb0}'), ('\u{eb2}', '\u{eb3}'), - ('\u{ebd}', '\u{ebd}'), ('\u{ec0}', '\u{ec4}'), ('\u{edc}', '\u{edf}'), - ('\u{f00}', '\u{f00}'), ('\u{f40}', '\u{f47}'), ('\u{f49}', '\u{f6c}'), - ('\u{f88}', '\u{f8c}'), ('\u{1000}', '\u{102a}'), ('\u{103f}', - '\u{103f}'), ('\u{1050}', '\u{1055}'), ('\u{105a}', '\u{105d}'), - ('\u{1061}', '\u{1061}'), ('\u{1065}', '\u{1066}'), ('\u{106e}', - '\u{1070}'), ('\u{1075}', '\u{1081}'), ('\u{108e}', '\u{108e}'), - ('\u{10d0}', '\u{10fa}'), ('\u{10fd}', '\u{1248}'), ('\u{124a}', - '\u{124d}'), ('\u{1250}', '\u{1256}'), ('\u{1258}', '\u{1258}'), - ('\u{125a}', '\u{125d}'), ('\u{1260}', '\u{1288}'), ('\u{128a}', - '\u{128d}'), ('\u{1290}', '\u{12b0}'), ('\u{12b2}', '\u{12b5}'), - ('\u{12b8}', '\u{12be}'), ('\u{12c0}', '\u{12c0}'), ('\u{12c2}', - '\u{12c5}'), ('\u{12c8}', '\u{12d6}'), ('\u{12d8}', '\u{1310}'), - ('\u{1312}', '\u{1315}'), ('\u{1318}', '\u{135a}'), ('\u{1380}', - '\u{138f}'), ('\u{1401}', '\u{166c}'), ('\u{166f}', '\u{167f}'), - ('\u{1681}', '\u{169a}'), ('\u{16a0}', '\u{16ea}'), ('\u{16f1}', - '\u{16f8}'), ('\u{1700}', '\u{170c}'), ('\u{170e}', '\u{1711}'), - ('\u{1720}', '\u{1731}'), ('\u{1740}', '\u{1751}'), ('\u{1760}', - '\u{176c}'), ('\u{176e}', '\u{1770}'), ('\u{1780}', '\u{17b3}'), - ('\u{17dc}', '\u{17dc}'), ('\u{1820}', '\u{1842}'), ('\u{1844}', - '\u{1877}'), ('\u{1880}', '\u{1884}'), ('\u{1887}', '\u{18a8}'), - ('\u{18aa}', '\u{18aa}'), ('\u{18b0}', '\u{18f5}'), ('\u{1900}', - '\u{191e}'), ('\u{1950}', '\u{196d}'), ('\u{1970}', '\u{1974}'), - ('\u{1980}', '\u{19ab}'), ('\u{19b0}', '\u{19c9}'), ('\u{1a00}', - '\u{1a16}'), ('\u{1a20}', '\u{1a54}'), ('\u{1b05}', '\u{1b33}'), - ('\u{1b45}', '\u{1b4b}'), ('\u{1b83}', '\u{1ba0}'), ('\u{1bae}', - '\u{1baf}'), ('\u{1bba}', '\u{1be5}'), ('\u{1c00}', '\u{1c23}'), - ('\u{1c4d}', '\u{1c4f}'), ('\u{1c5a}', '\u{1c77}'), ('\u{1ce9}', - '\u{1cec}'), ('\u{1cee}', '\u{1cf1}'), ('\u{1cf5}', '\u{1cf6}'), - ('\u{2135}', '\u{2138}'), ('\u{2d30}', '\u{2d67}'), ('\u{2d80}', - '\u{2d96}'), ('\u{2da0}', '\u{2da6}'), ('\u{2da8}', '\u{2dae}'), - ('\u{2db0}', '\u{2db6}'), ('\u{2db8}', '\u{2dbe}'), ('\u{2dc0}', - '\u{2dc6}'), ('\u{2dc8}', '\u{2dce}'), ('\u{2dd0}', '\u{2dd6}'), - ('\u{2dd8}', '\u{2dde}'), ('\u{3006}', '\u{3006}'), ('\u{303c}', - '\u{303c}'), ('\u{3041}', '\u{3096}'), ('\u{309f}', '\u{309f}'), - ('\u{30a1}', '\u{30fa}'), ('\u{30ff}', '\u{30ff}'), ('\u{3105}', - '\u{312e}'), ('\u{3131}', '\u{318e}'), ('\u{31a0}', '\u{31ba}'), - ('\u{31f0}', '\u{31ff}'), ('\u{3400}', '\u{4db5}'), ('\u{4e00}', - '\u{9fea}'), ('\u{a000}', '\u{a014}'), ('\u{a016}', '\u{a48c}'), - ('\u{a4d0}', '\u{a4f7}'), ('\u{a500}', '\u{a60b}'), ('\u{a610}', - '\u{a61f}'), ('\u{a62a}', '\u{a62b}'), ('\u{a66e}', '\u{a66e}'), - ('\u{a6a0}', '\u{a6e5}'), ('\u{a78f}', '\u{a78f}'), ('\u{a7f7}', - '\u{a7f7}'), ('\u{a7fb}', '\u{a801}'), ('\u{a803}', '\u{a805}'), - ('\u{a807}', '\u{a80a}'), ('\u{a80c}', '\u{a822}'), ('\u{a840}', - '\u{a873}'), ('\u{a882}', '\u{a8b3}'), ('\u{a8f2}', '\u{a8f7}'), - ('\u{a8fb}', '\u{a8fb}'), ('\u{a8fd}', '\u{a8fd}'), ('\u{a90a}', - '\u{a925}'), ('\u{a930}', '\u{a946}'), ('\u{a960}', '\u{a97c}'), - ('\u{a984}', '\u{a9b2}'), ('\u{a9e0}', '\u{a9e4}'), ('\u{a9e7}', - '\u{a9ef}'), ('\u{a9fa}', '\u{a9fe}'), ('\u{aa00}', '\u{aa28}'), - ('\u{aa40}', '\u{aa42}'), ('\u{aa44}', '\u{aa4b}'), ('\u{aa60}', - '\u{aa6f}'), ('\u{aa71}', '\u{aa76}'), ('\u{aa7a}', '\u{aa7a}'), - ('\u{aa7e}', '\u{aaaf}'), ('\u{aab1}', '\u{aab1}'), ('\u{aab5}', - '\u{aab6}'), ('\u{aab9}', '\u{aabd}'), ('\u{aac0}', '\u{aac0}'), - ('\u{aac2}', '\u{aac2}'), ('\u{aadb}', '\u{aadc}'), ('\u{aae0}', - '\u{aaea}'), ('\u{aaf2}', '\u{aaf2}'), ('\u{ab01}', '\u{ab06}'), - ('\u{ab09}', '\u{ab0e}'), ('\u{ab11}', '\u{ab16}'), ('\u{ab20}', - '\u{ab26}'), ('\u{ab28}', '\u{ab2e}'), ('\u{abc0}', '\u{abe2}'), - ('\u{ac00}', '\u{d7a3}'), ('\u{d7b0}', '\u{d7c6}'), ('\u{d7cb}', - '\u{d7fb}'), ('\u{f900}', '\u{fa6d}'), ('\u{fa70}', '\u{fad9}'), - ('\u{fb1d}', '\u{fb1d}'), ('\u{fb1f}', '\u{fb28}'), ('\u{fb2a}', - '\u{fb36}'), ('\u{fb38}', '\u{fb3c}'), ('\u{fb3e}', '\u{fb3e}'), - ('\u{fb40}', '\u{fb41}'), ('\u{fb43}', '\u{fb44}'), ('\u{fb46}', - '\u{fbb1}'), ('\u{fbd3}', '\u{fd3d}'), ('\u{fd50}', '\u{fd8f}'), - ('\u{fd92}', '\u{fdc7}'), ('\u{fdf0}', '\u{fdfb}'), ('\u{fe70}', - '\u{fe74}'), ('\u{fe76}', '\u{fefc}'), ('\u{ff66}', '\u{ff6f}'), - ('\u{ff71}', '\u{ff9d}'), ('\u{ffa0}', '\u{ffbe}'), ('\u{ffc2}', - '\u{ffc7}'), ('\u{ffca}', '\u{ffcf}'), ('\u{ffd2}', '\u{ffd7}'), - ('\u{ffda}', '\u{ffdc}'), ('\u{10000}', '\u{1000b}'), ('\u{1000d}', - '\u{10026}'), ('\u{10028}', '\u{1003a}'), ('\u{1003c}', '\u{1003d}'), - ('\u{1003f}', '\u{1004d}'), ('\u{10050}', '\u{1005d}'), ('\u{10080}', - '\u{100fa}'), ('\u{10280}', '\u{1029c}'), ('\u{102a0}', '\u{102d0}'), - ('\u{10300}', '\u{1031f}'), ('\u{1032d}', '\u{10340}'), ('\u{10342}', - '\u{10349}'), ('\u{10350}', '\u{10375}'), ('\u{10380}', '\u{1039d}'), - ('\u{103a0}', '\u{103c3}'), ('\u{103c8}', '\u{103cf}'), ('\u{10450}', - '\u{1049d}'), ('\u{10500}', '\u{10527}'), ('\u{10530}', '\u{10563}'), - ('\u{10600}', '\u{10736}'), ('\u{10740}', '\u{10755}'), ('\u{10760}', - '\u{10767}'), ('\u{10800}', '\u{10805}'), ('\u{10808}', '\u{10808}'), - ('\u{1080a}', '\u{10835}'), ('\u{10837}', '\u{10838}'), ('\u{1083c}', - '\u{1083c}'), ('\u{1083f}', '\u{10855}'), ('\u{10860}', '\u{10876}'), - ('\u{10880}', '\u{1089e}'), ('\u{108e0}', '\u{108f2}'), ('\u{108f4}', - '\u{108f5}'), ('\u{10900}', '\u{10915}'), ('\u{10920}', '\u{10939}'), - ('\u{10980}', '\u{109b7}'), ('\u{109be}', '\u{109bf}'), ('\u{10a00}', - '\u{10a00}'), ('\u{10a10}', '\u{10a13}'), ('\u{10a15}', '\u{10a17}'), - ('\u{10a19}', '\u{10a33}'), ('\u{10a60}', '\u{10a7c}'), ('\u{10a80}', - '\u{10a9c}'), ('\u{10ac0}', '\u{10ac7}'), ('\u{10ac9}', '\u{10ae4}'), - ('\u{10b00}', '\u{10b35}'), ('\u{10b40}', '\u{10b55}'), ('\u{10b60}', - '\u{10b72}'), ('\u{10b80}', '\u{10b91}'), ('\u{10c00}', '\u{10c48}'), - ('\u{11003}', '\u{11037}'), ('\u{11083}', '\u{110af}'), ('\u{110d0}', - '\u{110e8}'), ('\u{11103}', '\u{11126}'), ('\u{11150}', '\u{11172}'), - ('\u{11176}', '\u{11176}'), ('\u{11183}', '\u{111b2}'), ('\u{111c1}', - '\u{111c4}'), ('\u{111da}', '\u{111da}'), ('\u{111dc}', '\u{111dc}'), - ('\u{11200}', '\u{11211}'), ('\u{11213}', '\u{1122b}'), ('\u{11280}', - '\u{11286}'), ('\u{11288}', '\u{11288}'), ('\u{1128a}', '\u{1128d}'), - ('\u{1128f}', '\u{1129d}'), ('\u{1129f}', '\u{112a8}'), ('\u{112b0}', - '\u{112de}'), ('\u{11305}', '\u{1130c}'), ('\u{1130f}', '\u{11310}'), - ('\u{11313}', '\u{11328}'), ('\u{1132a}', '\u{11330}'), ('\u{11332}', - '\u{11333}'), ('\u{11335}', '\u{11339}'), ('\u{1133d}', '\u{1133d}'), - ('\u{11350}', '\u{11350}'), ('\u{1135d}', '\u{11361}'), ('\u{11400}', - '\u{11434}'), ('\u{11447}', '\u{1144a}'), ('\u{11480}', '\u{114af}'), - ('\u{114c4}', '\u{114c5}'), ('\u{114c7}', '\u{114c7}'), ('\u{11580}', - '\u{115ae}'), ('\u{115d8}', '\u{115db}'), ('\u{11600}', '\u{1162f}'), - ('\u{11644}', '\u{11644}'), ('\u{11680}', '\u{116aa}'), ('\u{11700}', - '\u{11719}'), ('\u{118ff}', '\u{118ff}'), ('\u{11a00}', '\u{11a00}'), - ('\u{11a0b}', '\u{11a32}'), ('\u{11a3a}', '\u{11a3a}'), ('\u{11a50}', - '\u{11a50}'), ('\u{11a5c}', '\u{11a83}'), ('\u{11a86}', '\u{11a89}'), - ('\u{11ac0}', '\u{11af8}'), ('\u{11c00}', '\u{11c08}'), ('\u{11c0a}', - '\u{11c2e}'), ('\u{11c40}', '\u{11c40}'), ('\u{11c72}', '\u{11c8f}'), - ('\u{11d00}', '\u{11d06}'), ('\u{11d08}', '\u{11d09}'), ('\u{11d0b}', - '\u{11d30}'), ('\u{11d46}', '\u{11d46}'), ('\u{12000}', '\u{12399}'), - ('\u{12480}', '\u{12543}'), ('\u{13000}', '\u{1342e}'), ('\u{14400}', - '\u{14646}'), ('\u{16800}', '\u{16a38}'), ('\u{16a40}', '\u{16a5e}'), - ('\u{16ad0}', '\u{16aed}'), ('\u{16b00}', '\u{16b2f}'), ('\u{16b63}', - '\u{16b77}'), ('\u{16b7d}', '\u{16b8f}'), ('\u{16f00}', '\u{16f44}'), - ('\u{16f50}', '\u{16f50}'), ('\u{17000}', '\u{187ec}'), ('\u{18800}', - '\u{18af2}'), ('\u{1b000}', '\u{1b11e}'), ('\u{1b170}', '\u{1b2fb}'), - ('\u{1bc00}', '\u{1bc6a}'), ('\u{1bc70}', '\u{1bc7c}'), ('\u{1bc80}', - '\u{1bc88}'), ('\u{1bc90}', '\u{1bc99}'), ('\u{1e800}', '\u{1e8c4}'), - ('\u{1ee00}', '\u{1ee03}'), ('\u{1ee05}', '\u{1ee1f}'), ('\u{1ee21}', - '\u{1ee22}'), ('\u{1ee24}', '\u{1ee24}'), ('\u{1ee27}', '\u{1ee27}'), - ('\u{1ee29}', '\u{1ee32}'), ('\u{1ee34}', '\u{1ee37}'), ('\u{1ee39}', - '\u{1ee39}'), ('\u{1ee3b}', '\u{1ee3b}'), ('\u{1ee42}', '\u{1ee42}'), - ('\u{1ee47}', '\u{1ee47}'), ('\u{1ee49}', '\u{1ee49}'), ('\u{1ee4b}', - '\u{1ee4b}'), ('\u{1ee4d}', '\u{1ee4f}'), ('\u{1ee51}', '\u{1ee52}'), - ('\u{1ee54}', '\u{1ee54}'), ('\u{1ee57}', '\u{1ee57}'), ('\u{1ee59}', - '\u{1ee59}'), ('\u{1ee5b}', '\u{1ee5b}'), ('\u{1ee5d}', '\u{1ee5d}'), - ('\u{1ee5f}', '\u{1ee5f}'), ('\u{1ee61}', '\u{1ee62}'), ('\u{1ee64}', - '\u{1ee64}'), ('\u{1ee67}', '\u{1ee6a}'), ('\u{1ee6c}', '\u{1ee72}'), - ('\u{1ee74}', '\u{1ee77}'), ('\u{1ee79}', '\u{1ee7c}'), ('\u{1ee7e}', - '\u{1ee7e}'), ('\u{1ee80}', '\u{1ee89}'), ('\u{1ee8b}', '\u{1ee9b}'), - ('\u{1eea1}', '\u{1eea3}'), ('\u{1eea5}', '\u{1eea9}'), ('\u{1eeab}', - '\u{1eebb}'), ('\u{20000}', '\u{2a6d6}'), ('\u{2a700}', '\u{2b734}'), - ('\u{2b740}', '\u{2b81d}'), ('\u{2b820}', '\u{2cea1}'), ('\u{2ceb0}', - '\u{2ebe0}'), ('\u{2f800}', '\u{2fa1d}') - ]; - - pub const Lt_table: &'static [(char, char)] = &[ - ('\u{1c5}', '\u{1c5}'), ('\u{1c8}', '\u{1c8}'), ('\u{1cb}', '\u{1cb}'), - ('\u{1f2}', '\u{1f2}'), ('\u{1f88}', '\u{1f8f}'), ('\u{1f98}', - '\u{1f9f}'), ('\u{1fa8}', '\u{1faf}'), ('\u{1fbc}', '\u{1fbc}'), - ('\u{1fcc}', '\u{1fcc}'), ('\u{1ffc}', '\u{1ffc}') - ]; - - pub const Lu_table: &'static [(char, char)] = &[ - ('\u{41}', '\u{5a}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{de}'), - ('\u{100}', '\u{100}'), ('\u{102}', '\u{102}'), ('\u{104}', '\u{104}'), - ('\u{106}', '\u{106}'), ('\u{108}', '\u{108}'), ('\u{10a}', '\u{10a}'), - ('\u{10c}', '\u{10c}'), ('\u{10e}', '\u{10e}'), ('\u{110}', '\u{110}'), - ('\u{112}', '\u{112}'), ('\u{114}', '\u{114}'), ('\u{116}', '\u{116}'), - ('\u{118}', '\u{118}'), ('\u{11a}', '\u{11a}'), ('\u{11c}', '\u{11c}'), - ('\u{11e}', '\u{11e}'), ('\u{120}', '\u{120}'), ('\u{122}', '\u{122}'), - ('\u{124}', '\u{124}'), ('\u{126}', '\u{126}'), ('\u{128}', '\u{128}'), - ('\u{12a}', '\u{12a}'), ('\u{12c}', '\u{12c}'), ('\u{12e}', '\u{12e}'), - ('\u{130}', '\u{130}'), ('\u{132}', '\u{132}'), ('\u{134}', '\u{134}'), - ('\u{136}', '\u{136}'), ('\u{139}', '\u{139}'), ('\u{13b}', '\u{13b}'), - ('\u{13d}', '\u{13d}'), ('\u{13f}', '\u{13f}'), ('\u{141}', '\u{141}'), - ('\u{143}', '\u{143}'), ('\u{145}', '\u{145}'), ('\u{147}', '\u{147}'), - ('\u{14a}', '\u{14a}'), ('\u{14c}', '\u{14c}'), ('\u{14e}', '\u{14e}'), - ('\u{150}', '\u{150}'), ('\u{152}', '\u{152}'), ('\u{154}', '\u{154}'), - ('\u{156}', '\u{156}'), ('\u{158}', '\u{158}'), ('\u{15a}', '\u{15a}'), - ('\u{15c}', '\u{15c}'), ('\u{15e}', '\u{15e}'), ('\u{160}', '\u{160}'), - ('\u{162}', '\u{162}'), ('\u{164}', '\u{164}'), ('\u{166}', '\u{166}'), - ('\u{168}', '\u{168}'), ('\u{16a}', '\u{16a}'), ('\u{16c}', '\u{16c}'), - ('\u{16e}', '\u{16e}'), ('\u{170}', '\u{170}'), ('\u{172}', '\u{172}'), - ('\u{174}', '\u{174}'), ('\u{176}', '\u{176}'), ('\u{178}', '\u{179}'), - ('\u{17b}', '\u{17b}'), ('\u{17d}', '\u{17d}'), ('\u{181}', '\u{182}'), - ('\u{184}', '\u{184}'), ('\u{186}', '\u{187}'), ('\u{189}', '\u{18b}'), - ('\u{18e}', '\u{191}'), ('\u{193}', '\u{194}'), ('\u{196}', '\u{198}'), - ('\u{19c}', '\u{19d}'), ('\u{19f}', '\u{1a0}'), ('\u{1a2}', '\u{1a2}'), - ('\u{1a4}', '\u{1a4}'), ('\u{1a6}', '\u{1a7}'), ('\u{1a9}', '\u{1a9}'), - ('\u{1ac}', '\u{1ac}'), ('\u{1ae}', '\u{1af}'), ('\u{1b1}', '\u{1b3}'), - ('\u{1b5}', '\u{1b5}'), ('\u{1b7}', '\u{1b8}'), ('\u{1bc}', '\u{1bc}'), - ('\u{1c4}', '\u{1c4}'), ('\u{1c7}', '\u{1c7}'), ('\u{1ca}', '\u{1ca}'), - ('\u{1cd}', '\u{1cd}'), ('\u{1cf}', '\u{1cf}'), ('\u{1d1}', '\u{1d1}'), - ('\u{1d3}', '\u{1d3}'), ('\u{1d5}', '\u{1d5}'), ('\u{1d7}', '\u{1d7}'), - ('\u{1d9}', '\u{1d9}'), ('\u{1db}', '\u{1db}'), ('\u{1de}', '\u{1de}'), - ('\u{1e0}', '\u{1e0}'), ('\u{1e2}', '\u{1e2}'), ('\u{1e4}', '\u{1e4}'), - ('\u{1e6}', '\u{1e6}'), ('\u{1e8}', '\u{1e8}'), ('\u{1ea}', '\u{1ea}'), - ('\u{1ec}', '\u{1ec}'), ('\u{1ee}', '\u{1ee}'), ('\u{1f1}', '\u{1f1}'), - ('\u{1f4}', '\u{1f4}'), ('\u{1f6}', '\u{1f8}'), ('\u{1fa}', '\u{1fa}'), - ('\u{1fc}', '\u{1fc}'), ('\u{1fe}', '\u{1fe}'), ('\u{200}', '\u{200}'), - ('\u{202}', '\u{202}'), ('\u{204}', '\u{204}'), ('\u{206}', '\u{206}'), - ('\u{208}', '\u{208}'), ('\u{20a}', '\u{20a}'), ('\u{20c}', '\u{20c}'), - ('\u{20e}', '\u{20e}'), ('\u{210}', '\u{210}'), ('\u{212}', '\u{212}'), - ('\u{214}', '\u{214}'), ('\u{216}', '\u{216}'), ('\u{218}', '\u{218}'), - ('\u{21a}', '\u{21a}'), ('\u{21c}', '\u{21c}'), ('\u{21e}', '\u{21e}'), - ('\u{220}', '\u{220}'), ('\u{222}', '\u{222}'), ('\u{224}', '\u{224}'), - ('\u{226}', '\u{226}'), ('\u{228}', '\u{228}'), ('\u{22a}', '\u{22a}'), - ('\u{22c}', '\u{22c}'), ('\u{22e}', '\u{22e}'), ('\u{230}', '\u{230}'), - ('\u{232}', '\u{232}'), ('\u{23a}', '\u{23b}'), ('\u{23d}', '\u{23e}'), - ('\u{241}', '\u{241}'), ('\u{243}', '\u{246}'), ('\u{248}', '\u{248}'), - ('\u{24a}', '\u{24a}'), ('\u{24c}', '\u{24c}'), ('\u{24e}', '\u{24e}'), - ('\u{370}', '\u{370}'), ('\u{372}', '\u{372}'), ('\u{376}', '\u{376}'), - ('\u{37f}', '\u{37f}'), ('\u{386}', '\u{386}'), ('\u{388}', '\u{38a}'), - ('\u{38c}', '\u{38c}'), ('\u{38e}', '\u{38f}'), ('\u{391}', '\u{3a1}'), - ('\u{3a3}', '\u{3ab}'), ('\u{3cf}', '\u{3cf}'), ('\u{3d2}', '\u{3d4}'), - ('\u{3d8}', '\u{3d8}'), ('\u{3da}', '\u{3da}'), ('\u{3dc}', '\u{3dc}'), - ('\u{3de}', '\u{3de}'), ('\u{3e0}', '\u{3e0}'), ('\u{3e2}', '\u{3e2}'), - ('\u{3e4}', '\u{3e4}'), ('\u{3e6}', '\u{3e6}'), ('\u{3e8}', '\u{3e8}'), - ('\u{3ea}', '\u{3ea}'), ('\u{3ec}', '\u{3ec}'), ('\u{3ee}', '\u{3ee}'), - ('\u{3f4}', '\u{3f4}'), ('\u{3f7}', '\u{3f7}'), ('\u{3f9}', '\u{3fa}'), - ('\u{3fd}', '\u{42f}'), ('\u{460}', '\u{460}'), ('\u{462}', '\u{462}'), - ('\u{464}', '\u{464}'), ('\u{466}', '\u{466}'), ('\u{468}', '\u{468}'), - ('\u{46a}', '\u{46a}'), ('\u{46c}', '\u{46c}'), ('\u{46e}', '\u{46e}'), - ('\u{470}', '\u{470}'), ('\u{472}', '\u{472}'), ('\u{474}', '\u{474}'), - ('\u{476}', '\u{476}'), ('\u{478}', '\u{478}'), ('\u{47a}', '\u{47a}'), - ('\u{47c}', '\u{47c}'), ('\u{47e}', '\u{47e}'), ('\u{480}', '\u{480}'), - ('\u{48a}', '\u{48a}'), ('\u{48c}', '\u{48c}'), ('\u{48e}', '\u{48e}'), - ('\u{490}', '\u{490}'), ('\u{492}', '\u{492}'), ('\u{494}', '\u{494}'), - ('\u{496}', '\u{496}'), ('\u{498}', '\u{498}'), ('\u{49a}', '\u{49a}'), - ('\u{49c}', '\u{49c}'), ('\u{49e}', '\u{49e}'), ('\u{4a0}', '\u{4a0}'), - ('\u{4a2}', '\u{4a2}'), ('\u{4a4}', '\u{4a4}'), ('\u{4a6}', '\u{4a6}'), - ('\u{4a8}', '\u{4a8}'), ('\u{4aa}', '\u{4aa}'), ('\u{4ac}', '\u{4ac}'), - ('\u{4ae}', '\u{4ae}'), ('\u{4b0}', '\u{4b0}'), ('\u{4b2}', '\u{4b2}'), - ('\u{4b4}', '\u{4b4}'), ('\u{4b6}', '\u{4b6}'), ('\u{4b8}', '\u{4b8}'), - ('\u{4ba}', '\u{4ba}'), ('\u{4bc}', '\u{4bc}'), ('\u{4be}', '\u{4be}'), - ('\u{4c0}', '\u{4c1}'), ('\u{4c3}', '\u{4c3}'), ('\u{4c5}', '\u{4c5}'), - ('\u{4c7}', '\u{4c7}'), ('\u{4c9}', '\u{4c9}'), ('\u{4cb}', '\u{4cb}'), - ('\u{4cd}', '\u{4cd}'), ('\u{4d0}', '\u{4d0}'), ('\u{4d2}', '\u{4d2}'), - ('\u{4d4}', '\u{4d4}'), ('\u{4d6}', '\u{4d6}'), ('\u{4d8}', '\u{4d8}'), - ('\u{4da}', '\u{4da}'), ('\u{4dc}', '\u{4dc}'), ('\u{4de}', '\u{4de}'), - ('\u{4e0}', '\u{4e0}'), ('\u{4e2}', '\u{4e2}'), ('\u{4e4}', '\u{4e4}'), - ('\u{4e6}', '\u{4e6}'), ('\u{4e8}', '\u{4e8}'), ('\u{4ea}', '\u{4ea}'), - ('\u{4ec}', '\u{4ec}'), ('\u{4ee}', '\u{4ee}'), ('\u{4f0}', '\u{4f0}'), - ('\u{4f2}', '\u{4f2}'), ('\u{4f4}', '\u{4f4}'), ('\u{4f6}', '\u{4f6}'), - ('\u{4f8}', '\u{4f8}'), ('\u{4fa}', '\u{4fa}'), ('\u{4fc}', '\u{4fc}'), - ('\u{4fe}', '\u{4fe}'), ('\u{500}', '\u{500}'), ('\u{502}', '\u{502}'), - ('\u{504}', '\u{504}'), ('\u{506}', '\u{506}'), ('\u{508}', '\u{508}'), - ('\u{50a}', '\u{50a}'), ('\u{50c}', '\u{50c}'), ('\u{50e}', '\u{50e}'), - ('\u{510}', '\u{510}'), ('\u{512}', '\u{512}'), ('\u{514}', '\u{514}'), - ('\u{516}', '\u{516}'), ('\u{518}', '\u{518}'), ('\u{51a}', '\u{51a}'), - ('\u{51c}', '\u{51c}'), ('\u{51e}', '\u{51e}'), ('\u{520}', '\u{520}'), - ('\u{522}', '\u{522}'), ('\u{524}', '\u{524}'), ('\u{526}', '\u{526}'), - ('\u{528}', '\u{528}'), ('\u{52a}', '\u{52a}'), ('\u{52c}', '\u{52c}'), - ('\u{52e}', '\u{52e}'), ('\u{531}', '\u{556}'), ('\u{10a0}', - '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), ('\u{10cd}', '\u{10cd}'), - ('\u{13a0}', '\u{13f5}'), ('\u{1e00}', '\u{1e00}'), ('\u{1e02}', - '\u{1e02}'), ('\u{1e04}', '\u{1e04}'), ('\u{1e06}', '\u{1e06}'), - ('\u{1e08}', '\u{1e08}'), ('\u{1e0a}', '\u{1e0a}'), ('\u{1e0c}', - '\u{1e0c}'), ('\u{1e0e}', '\u{1e0e}'), ('\u{1e10}', '\u{1e10}'), - ('\u{1e12}', '\u{1e12}'), ('\u{1e14}', '\u{1e14}'), ('\u{1e16}', - '\u{1e16}'), ('\u{1e18}', '\u{1e18}'), ('\u{1e1a}', '\u{1e1a}'), - ('\u{1e1c}', '\u{1e1c}'), ('\u{1e1e}', '\u{1e1e}'), ('\u{1e20}', - '\u{1e20}'), ('\u{1e22}', '\u{1e22}'), ('\u{1e24}', '\u{1e24}'), - ('\u{1e26}', '\u{1e26}'), ('\u{1e28}', '\u{1e28}'), ('\u{1e2a}', - '\u{1e2a}'), ('\u{1e2c}', '\u{1e2c}'), ('\u{1e2e}', '\u{1e2e}'), - ('\u{1e30}', '\u{1e30}'), ('\u{1e32}', '\u{1e32}'), ('\u{1e34}', - '\u{1e34}'), ('\u{1e36}', '\u{1e36}'), ('\u{1e38}', '\u{1e38}'), - ('\u{1e3a}', '\u{1e3a}'), ('\u{1e3c}', '\u{1e3c}'), ('\u{1e3e}', - '\u{1e3e}'), ('\u{1e40}', '\u{1e40}'), ('\u{1e42}', '\u{1e42}'), - ('\u{1e44}', '\u{1e44}'), ('\u{1e46}', '\u{1e46}'), ('\u{1e48}', - '\u{1e48}'), ('\u{1e4a}', '\u{1e4a}'), ('\u{1e4c}', '\u{1e4c}'), - ('\u{1e4e}', '\u{1e4e}'), ('\u{1e50}', '\u{1e50}'), ('\u{1e52}', - '\u{1e52}'), ('\u{1e54}', '\u{1e54}'), ('\u{1e56}', '\u{1e56}'), - ('\u{1e58}', '\u{1e58}'), ('\u{1e5a}', '\u{1e5a}'), ('\u{1e5c}', - '\u{1e5c}'), ('\u{1e5e}', '\u{1e5e}'), ('\u{1e60}', '\u{1e60}'), - ('\u{1e62}', '\u{1e62}'), ('\u{1e64}', '\u{1e64}'), ('\u{1e66}', - '\u{1e66}'), ('\u{1e68}', '\u{1e68}'), ('\u{1e6a}', '\u{1e6a}'), - ('\u{1e6c}', '\u{1e6c}'), ('\u{1e6e}', '\u{1e6e}'), ('\u{1e70}', - '\u{1e70}'), ('\u{1e72}', '\u{1e72}'), ('\u{1e74}', '\u{1e74}'), - ('\u{1e76}', '\u{1e76}'), ('\u{1e78}', '\u{1e78}'), ('\u{1e7a}', - '\u{1e7a}'), ('\u{1e7c}', '\u{1e7c}'), ('\u{1e7e}', '\u{1e7e}'), - ('\u{1e80}', '\u{1e80}'), ('\u{1e82}', '\u{1e82}'), ('\u{1e84}', - '\u{1e84}'), ('\u{1e86}', '\u{1e86}'), ('\u{1e88}', '\u{1e88}'), - ('\u{1e8a}', '\u{1e8a}'), ('\u{1e8c}', '\u{1e8c}'), ('\u{1e8e}', - '\u{1e8e}'), ('\u{1e90}', '\u{1e90}'), ('\u{1e92}', '\u{1e92}'), - ('\u{1e94}', '\u{1e94}'), ('\u{1e9e}', '\u{1e9e}'), ('\u{1ea0}', - '\u{1ea0}'), ('\u{1ea2}', '\u{1ea2}'), ('\u{1ea4}', '\u{1ea4}'), - ('\u{1ea6}', '\u{1ea6}'), ('\u{1ea8}', '\u{1ea8}'), ('\u{1eaa}', - '\u{1eaa}'), ('\u{1eac}', '\u{1eac}'), ('\u{1eae}', '\u{1eae}'), - ('\u{1eb0}', '\u{1eb0}'), ('\u{1eb2}', '\u{1eb2}'), ('\u{1eb4}', - '\u{1eb4}'), ('\u{1eb6}', '\u{1eb6}'), ('\u{1eb8}', '\u{1eb8}'), - ('\u{1eba}', '\u{1eba}'), ('\u{1ebc}', '\u{1ebc}'), ('\u{1ebe}', - '\u{1ebe}'), ('\u{1ec0}', '\u{1ec0}'), ('\u{1ec2}', '\u{1ec2}'), - ('\u{1ec4}', '\u{1ec4}'), ('\u{1ec6}', '\u{1ec6}'), ('\u{1ec8}', - '\u{1ec8}'), ('\u{1eca}', '\u{1eca}'), ('\u{1ecc}', '\u{1ecc}'), - ('\u{1ece}', '\u{1ece}'), ('\u{1ed0}', '\u{1ed0}'), ('\u{1ed2}', - '\u{1ed2}'), ('\u{1ed4}', '\u{1ed4}'), ('\u{1ed6}', '\u{1ed6}'), - ('\u{1ed8}', '\u{1ed8}'), ('\u{1eda}', '\u{1eda}'), ('\u{1edc}', - '\u{1edc}'), ('\u{1ede}', '\u{1ede}'), ('\u{1ee0}', '\u{1ee0}'), - ('\u{1ee2}', '\u{1ee2}'), ('\u{1ee4}', '\u{1ee4}'), ('\u{1ee6}', - '\u{1ee6}'), ('\u{1ee8}', '\u{1ee8}'), ('\u{1eea}', '\u{1eea}'), - ('\u{1eec}', '\u{1eec}'), ('\u{1eee}', '\u{1eee}'), ('\u{1ef0}', - '\u{1ef0}'), ('\u{1ef2}', '\u{1ef2}'), ('\u{1ef4}', '\u{1ef4}'), - ('\u{1ef6}', '\u{1ef6}'), ('\u{1ef8}', '\u{1ef8}'), ('\u{1efa}', - '\u{1efa}'), ('\u{1efc}', '\u{1efc}'), ('\u{1efe}', '\u{1efe}'), - ('\u{1f08}', '\u{1f0f}'), ('\u{1f18}', '\u{1f1d}'), ('\u{1f28}', - '\u{1f2f}'), ('\u{1f38}', '\u{1f3f}'), ('\u{1f48}', '\u{1f4d}'), - ('\u{1f59}', '\u{1f59}'), ('\u{1f5b}', '\u{1f5b}'), ('\u{1f5d}', - '\u{1f5d}'), ('\u{1f5f}', '\u{1f5f}'), ('\u{1f68}', '\u{1f6f}'), - ('\u{1fb8}', '\u{1fbb}'), ('\u{1fc8}', '\u{1fcb}'), ('\u{1fd8}', - '\u{1fdb}'), ('\u{1fe8}', '\u{1fec}'), ('\u{1ff8}', '\u{1ffb}'), - ('\u{2102}', '\u{2102}'), ('\u{2107}', '\u{2107}'), ('\u{210b}', - '\u{210d}'), ('\u{2110}', '\u{2112}'), ('\u{2115}', '\u{2115}'), - ('\u{2119}', '\u{211d}'), ('\u{2124}', '\u{2124}'), ('\u{2126}', - '\u{2126}'), ('\u{2128}', '\u{2128}'), ('\u{212a}', '\u{212d}'), - ('\u{2130}', '\u{2133}'), ('\u{213e}', '\u{213f}'), ('\u{2145}', - '\u{2145}'), ('\u{2183}', '\u{2183}'), ('\u{2c00}', '\u{2c2e}'), - ('\u{2c60}', '\u{2c60}'), ('\u{2c62}', '\u{2c64}'), ('\u{2c67}', - '\u{2c67}'), ('\u{2c69}', '\u{2c69}'), ('\u{2c6b}', '\u{2c6b}'), - ('\u{2c6d}', '\u{2c70}'), ('\u{2c72}', '\u{2c72}'), ('\u{2c75}', - '\u{2c75}'), ('\u{2c7e}', '\u{2c80}'), ('\u{2c82}', '\u{2c82}'), - ('\u{2c84}', '\u{2c84}'), ('\u{2c86}', '\u{2c86}'), ('\u{2c88}', - '\u{2c88}'), ('\u{2c8a}', '\u{2c8a}'), ('\u{2c8c}', '\u{2c8c}'), - ('\u{2c8e}', '\u{2c8e}'), ('\u{2c90}', '\u{2c90}'), ('\u{2c92}', - '\u{2c92}'), ('\u{2c94}', '\u{2c94}'), ('\u{2c96}', '\u{2c96}'), - ('\u{2c98}', '\u{2c98}'), ('\u{2c9a}', '\u{2c9a}'), ('\u{2c9c}', - '\u{2c9c}'), ('\u{2c9e}', '\u{2c9e}'), ('\u{2ca0}', '\u{2ca0}'), - ('\u{2ca2}', '\u{2ca2}'), ('\u{2ca4}', '\u{2ca4}'), ('\u{2ca6}', - '\u{2ca6}'), ('\u{2ca8}', '\u{2ca8}'), ('\u{2caa}', '\u{2caa}'), - ('\u{2cac}', '\u{2cac}'), ('\u{2cae}', '\u{2cae}'), ('\u{2cb0}', - '\u{2cb0}'), ('\u{2cb2}', '\u{2cb2}'), ('\u{2cb4}', '\u{2cb4}'), - ('\u{2cb6}', '\u{2cb6}'), ('\u{2cb8}', '\u{2cb8}'), ('\u{2cba}', - '\u{2cba}'), ('\u{2cbc}', '\u{2cbc}'), ('\u{2cbe}', '\u{2cbe}'), - ('\u{2cc0}', '\u{2cc0}'), ('\u{2cc2}', '\u{2cc2}'), ('\u{2cc4}', - '\u{2cc4}'), ('\u{2cc6}', '\u{2cc6}'), ('\u{2cc8}', '\u{2cc8}'), - ('\u{2cca}', '\u{2cca}'), ('\u{2ccc}', '\u{2ccc}'), ('\u{2cce}', - '\u{2cce}'), ('\u{2cd0}', '\u{2cd0}'), ('\u{2cd2}', '\u{2cd2}'), - ('\u{2cd4}', '\u{2cd4}'), ('\u{2cd6}', '\u{2cd6}'), ('\u{2cd8}', - '\u{2cd8}'), ('\u{2cda}', '\u{2cda}'), ('\u{2cdc}', '\u{2cdc}'), - ('\u{2cde}', '\u{2cde}'), ('\u{2ce0}', '\u{2ce0}'), ('\u{2ce2}', - '\u{2ce2}'), ('\u{2ceb}', '\u{2ceb}'), ('\u{2ced}', '\u{2ced}'), - ('\u{2cf2}', '\u{2cf2}'), ('\u{a640}', '\u{a640}'), ('\u{a642}', - '\u{a642}'), ('\u{a644}', '\u{a644}'), ('\u{a646}', '\u{a646}'), - ('\u{a648}', '\u{a648}'), ('\u{a64a}', '\u{a64a}'), ('\u{a64c}', - '\u{a64c}'), ('\u{a64e}', '\u{a64e}'), ('\u{a650}', '\u{a650}'), - ('\u{a652}', '\u{a652}'), ('\u{a654}', '\u{a654}'), ('\u{a656}', - '\u{a656}'), ('\u{a658}', '\u{a658}'), ('\u{a65a}', '\u{a65a}'), - ('\u{a65c}', '\u{a65c}'), ('\u{a65e}', '\u{a65e}'), ('\u{a660}', - '\u{a660}'), ('\u{a662}', '\u{a662}'), ('\u{a664}', '\u{a664}'), - ('\u{a666}', '\u{a666}'), ('\u{a668}', '\u{a668}'), ('\u{a66a}', - '\u{a66a}'), ('\u{a66c}', '\u{a66c}'), ('\u{a680}', '\u{a680}'), - ('\u{a682}', '\u{a682}'), ('\u{a684}', '\u{a684}'), ('\u{a686}', - '\u{a686}'), ('\u{a688}', '\u{a688}'), ('\u{a68a}', '\u{a68a}'), - ('\u{a68c}', '\u{a68c}'), ('\u{a68e}', '\u{a68e}'), ('\u{a690}', - '\u{a690}'), ('\u{a692}', '\u{a692}'), ('\u{a694}', '\u{a694}'), - ('\u{a696}', '\u{a696}'), ('\u{a698}', '\u{a698}'), ('\u{a69a}', - '\u{a69a}'), ('\u{a722}', '\u{a722}'), ('\u{a724}', '\u{a724}'), - ('\u{a726}', '\u{a726}'), ('\u{a728}', '\u{a728}'), ('\u{a72a}', - '\u{a72a}'), ('\u{a72c}', '\u{a72c}'), ('\u{a72e}', '\u{a72e}'), - ('\u{a732}', '\u{a732}'), ('\u{a734}', '\u{a734}'), ('\u{a736}', - '\u{a736}'), ('\u{a738}', '\u{a738}'), ('\u{a73a}', '\u{a73a}'), - ('\u{a73c}', '\u{a73c}'), ('\u{a73e}', '\u{a73e}'), ('\u{a740}', - '\u{a740}'), ('\u{a742}', '\u{a742}'), ('\u{a744}', '\u{a744}'), - ('\u{a746}', '\u{a746}'), ('\u{a748}', '\u{a748}'), ('\u{a74a}', - '\u{a74a}'), ('\u{a74c}', '\u{a74c}'), ('\u{a74e}', '\u{a74e}'), - ('\u{a750}', '\u{a750}'), ('\u{a752}', '\u{a752}'), ('\u{a754}', - '\u{a754}'), ('\u{a756}', '\u{a756}'), ('\u{a758}', '\u{a758}'), - ('\u{a75a}', '\u{a75a}'), ('\u{a75c}', '\u{a75c}'), ('\u{a75e}', - '\u{a75e}'), ('\u{a760}', '\u{a760}'), ('\u{a762}', '\u{a762}'), - ('\u{a764}', '\u{a764}'), ('\u{a766}', '\u{a766}'), ('\u{a768}', - '\u{a768}'), ('\u{a76a}', '\u{a76a}'), ('\u{a76c}', '\u{a76c}'), - ('\u{a76e}', '\u{a76e}'), ('\u{a779}', '\u{a779}'), ('\u{a77b}', - '\u{a77b}'), ('\u{a77d}', '\u{a77e}'), ('\u{a780}', '\u{a780}'), - ('\u{a782}', '\u{a782}'), ('\u{a784}', '\u{a784}'), ('\u{a786}', - '\u{a786}'), ('\u{a78b}', '\u{a78b}'), ('\u{a78d}', '\u{a78d}'), - ('\u{a790}', '\u{a790}'), ('\u{a792}', '\u{a792}'), ('\u{a796}', - '\u{a796}'), ('\u{a798}', '\u{a798}'), ('\u{a79a}', '\u{a79a}'), - ('\u{a79c}', '\u{a79c}'), ('\u{a79e}', '\u{a79e}'), ('\u{a7a0}', - '\u{a7a0}'), ('\u{a7a2}', '\u{a7a2}'), ('\u{a7a4}', '\u{a7a4}'), - ('\u{a7a6}', '\u{a7a6}'), ('\u{a7a8}', '\u{a7a8}'), ('\u{a7aa}', - '\u{a7ae}'), ('\u{a7b0}', '\u{a7b4}'), ('\u{a7b6}', '\u{a7b6}'), - ('\u{ff21}', '\u{ff3a}'), ('\u{10400}', '\u{10427}'), ('\u{104b0}', - '\u{104d3}'), ('\u{10c80}', '\u{10cb2}'), ('\u{118a0}', '\u{118bf}'), - ('\u{1d400}', '\u{1d419}'), ('\u{1d434}', '\u{1d44d}'), ('\u{1d468}', - '\u{1d481}'), ('\u{1d49c}', '\u{1d49c}'), ('\u{1d49e}', '\u{1d49f}'), - ('\u{1d4a2}', '\u{1d4a2}'), ('\u{1d4a5}', '\u{1d4a6}'), ('\u{1d4a9}', - '\u{1d4ac}'), ('\u{1d4ae}', '\u{1d4b5}'), ('\u{1d4d0}', '\u{1d4e9}'), - ('\u{1d504}', '\u{1d505}'), ('\u{1d507}', '\u{1d50a}'), ('\u{1d50d}', - '\u{1d514}'), ('\u{1d516}', '\u{1d51c}'), ('\u{1d538}', '\u{1d539}'), - ('\u{1d53b}', '\u{1d53e}'), ('\u{1d540}', '\u{1d544}'), ('\u{1d546}', - '\u{1d546}'), ('\u{1d54a}', '\u{1d550}'), ('\u{1d56c}', '\u{1d585}'), - ('\u{1d5a0}', '\u{1d5b9}'), ('\u{1d5d4}', '\u{1d5ed}'), ('\u{1d608}', - '\u{1d621}'), ('\u{1d63c}', '\u{1d655}'), ('\u{1d670}', '\u{1d689}'), - ('\u{1d6a8}', '\u{1d6c0}'), ('\u{1d6e2}', '\u{1d6fa}'), ('\u{1d71c}', - '\u{1d734}'), ('\u{1d756}', '\u{1d76e}'), ('\u{1d790}', '\u{1d7a8}'), - ('\u{1d7ca}', '\u{1d7ca}'), ('\u{1e900}', '\u{1e921}') - ]; - - pub const M_table: &'static [(char, char)] = &[ - ('\u{300}', '\u{36f}'), ('\u{483}', '\u{489}'), ('\u{591}', '\u{5bd}'), - ('\u{5bf}', '\u{5bf}'), ('\u{5c1}', '\u{5c2}'), ('\u{5c4}', '\u{5c5}'), - ('\u{5c7}', '\u{5c7}'), ('\u{610}', '\u{61a}'), ('\u{64b}', '\u{65f}'), - ('\u{670}', '\u{670}'), ('\u{6d6}', '\u{6dc}'), ('\u{6df}', '\u{6e4}'), - ('\u{6e7}', '\u{6e8}'), ('\u{6ea}', '\u{6ed}'), ('\u{711}', '\u{711}'), - ('\u{730}', '\u{74a}'), ('\u{7a6}', '\u{7b0}'), ('\u{7eb}', '\u{7f3}'), - ('\u{816}', '\u{819}'), ('\u{81b}', '\u{823}'), ('\u{825}', '\u{827}'), - ('\u{829}', '\u{82d}'), ('\u{859}', '\u{85b}'), ('\u{8d4}', '\u{8e1}'), - ('\u{8e3}', '\u{903}'), ('\u{93a}', '\u{93c}'), ('\u{93e}', '\u{94f}'), - ('\u{951}', '\u{957}'), ('\u{962}', '\u{963}'), ('\u{981}', '\u{983}'), - ('\u{9bc}', '\u{9bc}'), ('\u{9be}', '\u{9c4}'), ('\u{9c7}', '\u{9c8}'), - ('\u{9cb}', '\u{9cd}'), ('\u{9d7}', '\u{9d7}'), ('\u{9e2}', '\u{9e3}'), - ('\u{a01}', '\u{a03}'), ('\u{a3c}', '\u{a3c}'), ('\u{a3e}', '\u{a42}'), - ('\u{a47}', '\u{a48}'), ('\u{a4b}', '\u{a4d}'), ('\u{a51}', '\u{a51}'), - ('\u{a70}', '\u{a71}'), ('\u{a75}', '\u{a75}'), ('\u{a81}', '\u{a83}'), - ('\u{abc}', '\u{abc}'), ('\u{abe}', '\u{ac5}'), ('\u{ac7}', '\u{ac9}'), - ('\u{acb}', '\u{acd}'), ('\u{ae2}', '\u{ae3}'), ('\u{afa}', '\u{aff}'), - ('\u{b01}', '\u{b03}'), ('\u{b3c}', '\u{b3c}'), ('\u{b3e}', '\u{b44}'), - ('\u{b47}', '\u{b48}'), ('\u{b4b}', '\u{b4d}'), ('\u{b56}', '\u{b57}'), - ('\u{b62}', '\u{b63}'), ('\u{b82}', '\u{b82}'), ('\u{bbe}', '\u{bc2}'), - ('\u{bc6}', '\u{bc8}'), ('\u{bca}', '\u{bcd}'), ('\u{bd7}', '\u{bd7}'), - ('\u{c00}', '\u{c03}'), ('\u{c3e}', '\u{c44}'), ('\u{c46}', '\u{c48}'), - ('\u{c4a}', '\u{c4d}'), ('\u{c55}', '\u{c56}'), ('\u{c62}', '\u{c63}'), - ('\u{c81}', '\u{c83}'), ('\u{cbc}', '\u{cbc}'), ('\u{cbe}', '\u{cc4}'), - ('\u{cc6}', '\u{cc8}'), ('\u{cca}', '\u{ccd}'), ('\u{cd5}', '\u{cd6}'), - ('\u{ce2}', '\u{ce3}'), ('\u{d00}', '\u{d03}'), ('\u{d3b}', '\u{d3c}'), - ('\u{d3e}', '\u{d44}'), ('\u{d46}', '\u{d48}'), ('\u{d4a}', '\u{d4d}'), - ('\u{d57}', '\u{d57}'), ('\u{d62}', '\u{d63}'), ('\u{d82}', '\u{d83}'), - ('\u{dca}', '\u{dca}'), ('\u{dcf}', '\u{dd4}'), ('\u{dd6}', '\u{dd6}'), - ('\u{dd8}', '\u{ddf}'), ('\u{df2}', '\u{df3}'), ('\u{e31}', '\u{e31}'), - ('\u{e34}', '\u{e3a}'), ('\u{e47}', '\u{e4e}'), ('\u{eb1}', '\u{eb1}'), - ('\u{eb4}', '\u{eb9}'), ('\u{ebb}', '\u{ebc}'), ('\u{ec8}', '\u{ecd}'), - ('\u{f18}', '\u{f19}'), ('\u{f35}', '\u{f35}'), ('\u{f37}', '\u{f37}'), - ('\u{f39}', '\u{f39}'), ('\u{f3e}', '\u{f3f}'), ('\u{f71}', '\u{f84}'), - ('\u{f86}', '\u{f87}'), ('\u{f8d}', '\u{f97}'), ('\u{f99}', '\u{fbc}'), - ('\u{fc6}', '\u{fc6}'), ('\u{102b}', '\u{103e}'), ('\u{1056}', - '\u{1059}'), ('\u{105e}', '\u{1060}'), ('\u{1062}', '\u{1064}'), - ('\u{1067}', '\u{106d}'), ('\u{1071}', '\u{1074}'), ('\u{1082}', - '\u{108d}'), ('\u{108f}', '\u{108f}'), ('\u{109a}', '\u{109d}'), - ('\u{135d}', '\u{135f}'), ('\u{1712}', '\u{1714}'), ('\u{1732}', - '\u{1734}'), ('\u{1752}', '\u{1753}'), ('\u{1772}', '\u{1773}'), - ('\u{17b4}', '\u{17d3}'), ('\u{17dd}', '\u{17dd}'), ('\u{180b}', - '\u{180d}'), ('\u{1885}', '\u{1886}'), ('\u{18a9}', '\u{18a9}'), - ('\u{1920}', '\u{192b}'), ('\u{1930}', '\u{193b}'), ('\u{1a17}', - '\u{1a1b}'), ('\u{1a55}', '\u{1a5e}'), ('\u{1a60}', '\u{1a7c}'), - ('\u{1a7f}', '\u{1a7f}'), ('\u{1ab0}', '\u{1abe}'), ('\u{1b00}', - '\u{1b04}'), ('\u{1b34}', '\u{1b44}'), ('\u{1b6b}', '\u{1b73}'), - ('\u{1b80}', '\u{1b82}'), ('\u{1ba1}', '\u{1bad}'), ('\u{1be6}', - '\u{1bf3}'), ('\u{1c24}', '\u{1c37}'), ('\u{1cd0}', '\u{1cd2}'), - ('\u{1cd4}', '\u{1ce8}'), ('\u{1ced}', '\u{1ced}'), ('\u{1cf2}', - '\u{1cf4}'), ('\u{1cf7}', '\u{1cf9}'), ('\u{1dc0}', '\u{1df9}'), - ('\u{1dfb}', '\u{1dff}'), ('\u{20d0}', '\u{20f0}'), ('\u{2cef}', - '\u{2cf1}'), ('\u{2d7f}', '\u{2d7f}'), ('\u{2de0}', '\u{2dff}'), - ('\u{302a}', '\u{302f}'), ('\u{3099}', '\u{309a}'), ('\u{a66f}', - '\u{a672}'), ('\u{a674}', '\u{a67d}'), ('\u{a69e}', '\u{a69f}'), - ('\u{a6f0}', '\u{a6f1}'), ('\u{a802}', '\u{a802}'), ('\u{a806}', - '\u{a806}'), ('\u{a80b}', '\u{a80b}'), ('\u{a823}', '\u{a827}'), - ('\u{a880}', '\u{a881}'), ('\u{a8b4}', '\u{a8c5}'), ('\u{a8e0}', - '\u{a8f1}'), ('\u{a926}', '\u{a92d}'), ('\u{a947}', '\u{a953}'), - ('\u{a980}', '\u{a983}'), ('\u{a9b3}', '\u{a9c0}'), ('\u{a9e5}', - '\u{a9e5}'), ('\u{aa29}', '\u{aa36}'), ('\u{aa43}', '\u{aa43}'), - ('\u{aa4c}', '\u{aa4d}'), ('\u{aa7b}', '\u{aa7d}'), ('\u{aab0}', - '\u{aab0}'), ('\u{aab2}', '\u{aab4}'), ('\u{aab7}', '\u{aab8}'), - ('\u{aabe}', '\u{aabf}'), ('\u{aac1}', '\u{aac1}'), ('\u{aaeb}', - '\u{aaef}'), ('\u{aaf5}', '\u{aaf6}'), ('\u{abe3}', '\u{abea}'), - ('\u{abec}', '\u{abed}'), ('\u{fb1e}', '\u{fb1e}'), ('\u{fe00}', - '\u{fe0f}'), ('\u{fe20}', '\u{fe2f}'), ('\u{101fd}', '\u{101fd}'), - ('\u{102e0}', '\u{102e0}'), ('\u{10376}', '\u{1037a}'), ('\u{10a01}', - '\u{10a03}'), ('\u{10a05}', '\u{10a06}'), ('\u{10a0c}', '\u{10a0f}'), - ('\u{10a38}', '\u{10a3a}'), ('\u{10a3f}', '\u{10a3f}'), ('\u{10ae5}', - '\u{10ae6}'), ('\u{11000}', '\u{11002}'), ('\u{11038}', '\u{11046}'), - ('\u{1107f}', '\u{11082}'), ('\u{110b0}', '\u{110ba}'), ('\u{11100}', - '\u{11102}'), ('\u{11127}', '\u{11134}'), ('\u{11173}', '\u{11173}'), - ('\u{11180}', '\u{11182}'), ('\u{111b3}', '\u{111c0}'), ('\u{111ca}', - '\u{111cc}'), ('\u{1122c}', '\u{11237}'), ('\u{1123e}', '\u{1123e}'), - ('\u{112df}', '\u{112ea}'), ('\u{11300}', '\u{11303}'), ('\u{1133c}', - '\u{1133c}'), ('\u{1133e}', '\u{11344}'), ('\u{11347}', '\u{11348}'), - ('\u{1134b}', '\u{1134d}'), ('\u{11357}', '\u{11357}'), ('\u{11362}', - '\u{11363}'), ('\u{11366}', '\u{1136c}'), ('\u{11370}', '\u{11374}'), - ('\u{11435}', '\u{11446}'), ('\u{114b0}', '\u{114c3}'), ('\u{115af}', - '\u{115b5}'), ('\u{115b8}', '\u{115c0}'), ('\u{115dc}', '\u{115dd}'), - ('\u{11630}', '\u{11640}'), ('\u{116ab}', '\u{116b7}'), ('\u{1171d}', - '\u{1172b}'), ('\u{11a01}', '\u{11a0a}'), ('\u{11a33}', '\u{11a39}'), - ('\u{11a3b}', '\u{11a3e}'), ('\u{11a47}', '\u{11a47}'), ('\u{11a51}', - '\u{11a5b}'), ('\u{11a8a}', '\u{11a99}'), ('\u{11c2f}', '\u{11c36}'), - ('\u{11c38}', '\u{11c3f}'), ('\u{11c92}', '\u{11ca7}'), ('\u{11ca9}', - '\u{11cb6}'), ('\u{11d31}', '\u{11d36}'), ('\u{11d3a}', '\u{11d3a}'), - ('\u{11d3c}', '\u{11d3d}'), ('\u{11d3f}', '\u{11d45}'), ('\u{11d47}', - '\u{11d47}'), ('\u{16af0}', '\u{16af4}'), ('\u{16b30}', '\u{16b36}'), - ('\u{16f51}', '\u{16f7e}'), ('\u{16f8f}', '\u{16f92}'), ('\u{1bc9d}', - '\u{1bc9e}'), ('\u{1d165}', '\u{1d169}'), ('\u{1d16d}', '\u{1d172}'), - ('\u{1d17b}', '\u{1d182}'), ('\u{1d185}', '\u{1d18b}'), ('\u{1d1aa}', - '\u{1d1ad}'), ('\u{1d242}', '\u{1d244}'), ('\u{1da00}', '\u{1da36}'), - ('\u{1da3b}', '\u{1da6c}'), ('\u{1da75}', '\u{1da75}'), ('\u{1da84}', - '\u{1da84}'), ('\u{1da9b}', '\u{1da9f}'), ('\u{1daa1}', '\u{1daaf}'), - ('\u{1e000}', '\u{1e006}'), ('\u{1e008}', '\u{1e018}'), ('\u{1e01b}', - '\u{1e021}'), ('\u{1e023}', '\u{1e024}'), ('\u{1e026}', '\u{1e02a}'), - ('\u{1e8d0}', '\u{1e8d6}'), ('\u{1e944}', '\u{1e94a}'), ('\u{e0100}', - '\u{e01ef}') - ]; - - pub const Mc_table: &'static [(char, char)] = &[ - ('\u{903}', '\u{903}'), ('\u{93b}', '\u{93b}'), ('\u{93e}', '\u{940}'), - ('\u{949}', '\u{94c}'), ('\u{94e}', '\u{94f}'), ('\u{982}', '\u{983}'), - ('\u{9be}', '\u{9c0}'), ('\u{9c7}', '\u{9c8}'), ('\u{9cb}', '\u{9cc}'), - ('\u{9d7}', '\u{9d7}'), ('\u{a03}', '\u{a03}'), ('\u{a3e}', '\u{a40}'), - ('\u{a83}', '\u{a83}'), ('\u{abe}', '\u{ac0}'), ('\u{ac9}', '\u{ac9}'), - ('\u{acb}', '\u{acc}'), ('\u{b02}', '\u{b03}'), ('\u{b3e}', '\u{b3e}'), - ('\u{b40}', '\u{b40}'), ('\u{b47}', '\u{b48}'), ('\u{b4b}', '\u{b4c}'), - ('\u{b57}', '\u{b57}'), ('\u{bbe}', '\u{bbf}'), ('\u{bc1}', '\u{bc2}'), - ('\u{bc6}', '\u{bc8}'), ('\u{bca}', '\u{bcc}'), ('\u{bd7}', '\u{bd7}'), - ('\u{c01}', '\u{c03}'), ('\u{c41}', '\u{c44}'), ('\u{c82}', '\u{c83}'), - ('\u{cbe}', '\u{cbe}'), ('\u{cc0}', '\u{cc4}'), ('\u{cc7}', '\u{cc8}'), - ('\u{cca}', '\u{ccb}'), ('\u{cd5}', '\u{cd6}'), ('\u{d02}', '\u{d03}'), - ('\u{d3e}', '\u{d40}'), ('\u{d46}', '\u{d48}'), ('\u{d4a}', '\u{d4c}'), - ('\u{d57}', '\u{d57}'), ('\u{d82}', '\u{d83}'), ('\u{dcf}', '\u{dd1}'), - ('\u{dd8}', '\u{ddf}'), ('\u{df2}', '\u{df3}'), ('\u{f3e}', '\u{f3f}'), - ('\u{f7f}', '\u{f7f}'), ('\u{102b}', '\u{102c}'), ('\u{1031}', - '\u{1031}'), ('\u{1038}', '\u{1038}'), ('\u{103b}', '\u{103c}'), - ('\u{1056}', '\u{1057}'), ('\u{1062}', '\u{1064}'), ('\u{1067}', - '\u{106d}'), ('\u{1083}', '\u{1084}'), ('\u{1087}', '\u{108c}'), - ('\u{108f}', '\u{108f}'), ('\u{109a}', '\u{109c}'), ('\u{17b6}', - '\u{17b6}'), ('\u{17be}', '\u{17c5}'), ('\u{17c7}', '\u{17c8}'), - ('\u{1923}', '\u{1926}'), ('\u{1929}', '\u{192b}'), ('\u{1930}', - '\u{1931}'), ('\u{1933}', '\u{1938}'), ('\u{1a19}', '\u{1a1a}'), - ('\u{1a55}', '\u{1a55}'), ('\u{1a57}', '\u{1a57}'), ('\u{1a61}', - '\u{1a61}'), ('\u{1a63}', '\u{1a64}'), ('\u{1a6d}', '\u{1a72}'), - ('\u{1b04}', '\u{1b04}'), ('\u{1b35}', '\u{1b35}'), ('\u{1b3b}', - '\u{1b3b}'), ('\u{1b3d}', '\u{1b41}'), ('\u{1b43}', '\u{1b44}'), - ('\u{1b82}', '\u{1b82}'), ('\u{1ba1}', '\u{1ba1}'), ('\u{1ba6}', - '\u{1ba7}'), ('\u{1baa}', '\u{1baa}'), ('\u{1be7}', '\u{1be7}'), - ('\u{1bea}', '\u{1bec}'), ('\u{1bee}', '\u{1bee}'), ('\u{1bf2}', - '\u{1bf3}'), ('\u{1c24}', '\u{1c2b}'), ('\u{1c34}', '\u{1c35}'), - ('\u{1ce1}', '\u{1ce1}'), ('\u{1cf2}', '\u{1cf3}'), ('\u{1cf7}', - '\u{1cf7}'), ('\u{302e}', '\u{302f}'), ('\u{a823}', '\u{a824}'), - ('\u{a827}', '\u{a827}'), ('\u{a880}', '\u{a881}'), ('\u{a8b4}', - '\u{a8c3}'), ('\u{a952}', '\u{a953}'), ('\u{a983}', '\u{a983}'), - ('\u{a9b4}', '\u{a9b5}'), ('\u{a9ba}', '\u{a9bb}'), ('\u{a9bd}', - '\u{a9c0}'), ('\u{aa2f}', '\u{aa30}'), ('\u{aa33}', '\u{aa34}'), - ('\u{aa4d}', '\u{aa4d}'), ('\u{aa7b}', '\u{aa7b}'), ('\u{aa7d}', - '\u{aa7d}'), ('\u{aaeb}', '\u{aaeb}'), ('\u{aaee}', '\u{aaef}'), - ('\u{aaf5}', '\u{aaf5}'), ('\u{abe3}', '\u{abe4}'), ('\u{abe6}', - '\u{abe7}'), ('\u{abe9}', '\u{abea}'), ('\u{abec}', '\u{abec}'), - ('\u{11000}', '\u{11000}'), ('\u{11002}', '\u{11002}'), ('\u{11082}', - '\u{11082}'), ('\u{110b0}', '\u{110b2}'), ('\u{110b7}', '\u{110b8}'), - ('\u{1112c}', '\u{1112c}'), ('\u{11182}', '\u{11182}'), ('\u{111b3}', - '\u{111b5}'), ('\u{111bf}', '\u{111c0}'), ('\u{1122c}', '\u{1122e}'), - ('\u{11232}', '\u{11233}'), ('\u{11235}', '\u{11235}'), ('\u{112e0}', - '\u{112e2}'), ('\u{11302}', '\u{11303}'), ('\u{1133e}', '\u{1133f}'), - ('\u{11341}', '\u{11344}'), ('\u{11347}', '\u{11348}'), ('\u{1134b}', - '\u{1134d}'), ('\u{11357}', '\u{11357}'), ('\u{11362}', '\u{11363}'), - ('\u{11435}', '\u{11437}'), ('\u{11440}', '\u{11441}'), ('\u{11445}', - '\u{11445}'), ('\u{114b0}', '\u{114b2}'), ('\u{114b9}', '\u{114b9}'), - ('\u{114bb}', '\u{114be}'), ('\u{114c1}', '\u{114c1}'), ('\u{115af}', - '\u{115b1}'), ('\u{115b8}', '\u{115bb}'), ('\u{115be}', '\u{115be}'), - ('\u{11630}', '\u{11632}'), ('\u{1163b}', '\u{1163c}'), ('\u{1163e}', - '\u{1163e}'), ('\u{116ac}', '\u{116ac}'), ('\u{116ae}', '\u{116af}'), - ('\u{116b6}', '\u{116b6}'), ('\u{11720}', '\u{11721}'), ('\u{11726}', - '\u{11726}'), ('\u{11a07}', '\u{11a08}'), ('\u{11a39}', '\u{11a39}'), - ('\u{11a57}', '\u{11a58}'), ('\u{11a97}', '\u{11a97}'), ('\u{11c2f}', - '\u{11c2f}'), ('\u{11c3e}', '\u{11c3e}'), ('\u{11ca9}', '\u{11ca9}'), - ('\u{11cb1}', '\u{11cb1}'), ('\u{11cb4}', '\u{11cb4}'), ('\u{16f51}', - '\u{16f7e}'), ('\u{1d165}', '\u{1d166}'), ('\u{1d16d}', '\u{1d172}') - ]; - - pub const Me_table: &'static [(char, char)] = &[ - ('\u{488}', '\u{489}'), ('\u{1abe}', '\u{1abe}'), ('\u{20dd}', - '\u{20e0}'), ('\u{20e2}', '\u{20e4}'), ('\u{a670}', '\u{a672}') - ]; - - pub const Mn_table: &'static [(char, char)] = &[ - ('\u{300}', '\u{36f}'), ('\u{483}', '\u{487}'), ('\u{591}', '\u{5bd}'), - ('\u{5bf}', '\u{5bf}'), ('\u{5c1}', '\u{5c2}'), ('\u{5c4}', '\u{5c5}'), - ('\u{5c7}', '\u{5c7}'), ('\u{610}', '\u{61a}'), ('\u{64b}', '\u{65f}'), - ('\u{670}', '\u{670}'), ('\u{6d6}', '\u{6dc}'), ('\u{6df}', '\u{6e4}'), - ('\u{6e7}', '\u{6e8}'), ('\u{6ea}', '\u{6ed}'), ('\u{711}', '\u{711}'), - ('\u{730}', '\u{74a}'), ('\u{7a6}', '\u{7b0}'), ('\u{7eb}', '\u{7f3}'), - ('\u{816}', '\u{819}'), ('\u{81b}', '\u{823}'), ('\u{825}', '\u{827}'), - ('\u{829}', '\u{82d}'), ('\u{859}', '\u{85b}'), ('\u{8d4}', '\u{8e1}'), - ('\u{8e3}', '\u{902}'), ('\u{93a}', '\u{93a}'), ('\u{93c}', '\u{93c}'), - ('\u{941}', '\u{948}'), ('\u{94d}', '\u{94d}'), ('\u{951}', '\u{957}'), - ('\u{962}', '\u{963}'), ('\u{981}', '\u{981}'), ('\u{9bc}', '\u{9bc}'), - ('\u{9c1}', '\u{9c4}'), ('\u{9cd}', '\u{9cd}'), ('\u{9e2}', '\u{9e3}'), - ('\u{a01}', '\u{a02}'), ('\u{a3c}', '\u{a3c}'), ('\u{a41}', '\u{a42}'), - ('\u{a47}', '\u{a48}'), ('\u{a4b}', '\u{a4d}'), ('\u{a51}', '\u{a51}'), - ('\u{a70}', '\u{a71}'), ('\u{a75}', '\u{a75}'), ('\u{a81}', '\u{a82}'), - ('\u{abc}', '\u{abc}'), ('\u{ac1}', '\u{ac5}'), ('\u{ac7}', '\u{ac8}'), - ('\u{acd}', '\u{acd}'), ('\u{ae2}', '\u{ae3}'), ('\u{afa}', '\u{aff}'), - ('\u{b01}', '\u{b01}'), ('\u{b3c}', '\u{b3c}'), ('\u{b3f}', '\u{b3f}'), - ('\u{b41}', '\u{b44}'), ('\u{b4d}', '\u{b4d}'), ('\u{b56}', '\u{b56}'), - ('\u{b62}', '\u{b63}'), ('\u{b82}', '\u{b82}'), ('\u{bc0}', '\u{bc0}'), - ('\u{bcd}', '\u{bcd}'), ('\u{c00}', '\u{c00}'), ('\u{c3e}', '\u{c40}'), - ('\u{c46}', '\u{c48}'), ('\u{c4a}', '\u{c4d}'), ('\u{c55}', '\u{c56}'), - ('\u{c62}', '\u{c63}'), ('\u{c81}', '\u{c81}'), ('\u{cbc}', '\u{cbc}'), - ('\u{cbf}', '\u{cbf}'), ('\u{cc6}', '\u{cc6}'), ('\u{ccc}', '\u{ccd}'), - ('\u{ce2}', '\u{ce3}'), ('\u{d00}', '\u{d01}'), ('\u{d3b}', '\u{d3c}'), - ('\u{d41}', '\u{d44}'), ('\u{d4d}', '\u{d4d}'), ('\u{d62}', '\u{d63}'), - ('\u{dca}', '\u{dca}'), ('\u{dd2}', '\u{dd4}'), ('\u{dd6}', '\u{dd6}'), - ('\u{e31}', '\u{e31}'), ('\u{e34}', '\u{e3a}'), ('\u{e47}', '\u{e4e}'), - ('\u{eb1}', '\u{eb1}'), ('\u{eb4}', '\u{eb9}'), ('\u{ebb}', '\u{ebc}'), - ('\u{ec8}', '\u{ecd}'), ('\u{f18}', '\u{f19}'), ('\u{f35}', '\u{f35}'), - ('\u{f37}', '\u{f37}'), ('\u{f39}', '\u{f39}'), ('\u{f71}', '\u{f7e}'), - ('\u{f80}', '\u{f84}'), ('\u{f86}', '\u{f87}'), ('\u{f8d}', '\u{f97}'), - ('\u{f99}', '\u{fbc}'), ('\u{fc6}', '\u{fc6}'), ('\u{102d}', - '\u{1030}'), ('\u{1032}', '\u{1037}'), ('\u{1039}', '\u{103a}'), - ('\u{103d}', '\u{103e}'), ('\u{1058}', '\u{1059}'), ('\u{105e}', - '\u{1060}'), ('\u{1071}', '\u{1074}'), ('\u{1082}', '\u{1082}'), - ('\u{1085}', '\u{1086}'), ('\u{108d}', '\u{108d}'), ('\u{109d}', - '\u{109d}'), ('\u{135d}', '\u{135f}'), ('\u{1712}', '\u{1714}'), - ('\u{1732}', '\u{1734}'), ('\u{1752}', '\u{1753}'), ('\u{1772}', - '\u{1773}'), ('\u{17b4}', '\u{17b5}'), ('\u{17b7}', '\u{17bd}'), - ('\u{17c6}', '\u{17c6}'), ('\u{17c9}', '\u{17d3}'), ('\u{17dd}', - '\u{17dd}'), ('\u{180b}', '\u{180d}'), ('\u{1885}', '\u{1886}'), - ('\u{18a9}', '\u{18a9}'), ('\u{1920}', '\u{1922}'), ('\u{1927}', - '\u{1928}'), ('\u{1932}', '\u{1932}'), ('\u{1939}', '\u{193b}'), - ('\u{1a17}', '\u{1a18}'), ('\u{1a1b}', '\u{1a1b}'), ('\u{1a56}', - '\u{1a56}'), ('\u{1a58}', '\u{1a5e}'), ('\u{1a60}', '\u{1a60}'), - ('\u{1a62}', '\u{1a62}'), ('\u{1a65}', '\u{1a6c}'), ('\u{1a73}', - '\u{1a7c}'), ('\u{1a7f}', '\u{1a7f}'), ('\u{1ab0}', '\u{1abd}'), - ('\u{1b00}', '\u{1b03}'), ('\u{1b34}', '\u{1b34}'), ('\u{1b36}', - '\u{1b3a}'), ('\u{1b3c}', '\u{1b3c}'), ('\u{1b42}', '\u{1b42}'), - ('\u{1b6b}', '\u{1b73}'), ('\u{1b80}', '\u{1b81}'), ('\u{1ba2}', - '\u{1ba5}'), ('\u{1ba8}', '\u{1ba9}'), ('\u{1bab}', '\u{1bad}'), - ('\u{1be6}', '\u{1be6}'), ('\u{1be8}', '\u{1be9}'), ('\u{1bed}', - '\u{1bed}'), ('\u{1bef}', '\u{1bf1}'), ('\u{1c2c}', '\u{1c33}'), - ('\u{1c36}', '\u{1c37}'), ('\u{1cd0}', '\u{1cd2}'), ('\u{1cd4}', - '\u{1ce0}'), ('\u{1ce2}', '\u{1ce8}'), ('\u{1ced}', '\u{1ced}'), - ('\u{1cf4}', '\u{1cf4}'), ('\u{1cf8}', '\u{1cf9}'), ('\u{1dc0}', - '\u{1df9}'), ('\u{1dfb}', '\u{1dff}'), ('\u{20d0}', '\u{20dc}'), - ('\u{20e1}', '\u{20e1}'), ('\u{20e5}', '\u{20f0}'), ('\u{2cef}', - '\u{2cf1}'), ('\u{2d7f}', '\u{2d7f}'), ('\u{2de0}', '\u{2dff}'), - ('\u{302a}', '\u{302d}'), ('\u{3099}', '\u{309a}'), ('\u{a66f}', - '\u{a66f}'), ('\u{a674}', '\u{a67d}'), ('\u{a69e}', '\u{a69f}'), - ('\u{a6f0}', '\u{a6f1}'), ('\u{a802}', '\u{a802}'), ('\u{a806}', - '\u{a806}'), ('\u{a80b}', '\u{a80b}'), ('\u{a825}', '\u{a826}'), - ('\u{a8c4}', '\u{a8c5}'), ('\u{a8e0}', '\u{a8f1}'), ('\u{a926}', - '\u{a92d}'), ('\u{a947}', '\u{a951}'), ('\u{a980}', '\u{a982}'), - ('\u{a9b3}', '\u{a9b3}'), ('\u{a9b6}', '\u{a9b9}'), ('\u{a9bc}', - '\u{a9bc}'), ('\u{a9e5}', '\u{a9e5}'), ('\u{aa29}', '\u{aa2e}'), - ('\u{aa31}', '\u{aa32}'), ('\u{aa35}', '\u{aa36}'), ('\u{aa43}', - '\u{aa43}'), ('\u{aa4c}', '\u{aa4c}'), ('\u{aa7c}', '\u{aa7c}'), - ('\u{aab0}', '\u{aab0}'), ('\u{aab2}', '\u{aab4}'), ('\u{aab7}', - '\u{aab8}'), ('\u{aabe}', '\u{aabf}'), ('\u{aac1}', '\u{aac1}'), - ('\u{aaec}', '\u{aaed}'), ('\u{aaf6}', '\u{aaf6}'), ('\u{abe5}', - '\u{abe5}'), ('\u{abe8}', '\u{abe8}'), ('\u{abed}', '\u{abed}'), - ('\u{fb1e}', '\u{fb1e}'), ('\u{fe00}', '\u{fe0f}'), ('\u{fe20}', - '\u{fe2f}'), ('\u{101fd}', '\u{101fd}'), ('\u{102e0}', '\u{102e0}'), - ('\u{10376}', '\u{1037a}'), ('\u{10a01}', '\u{10a03}'), ('\u{10a05}', - '\u{10a06}'), ('\u{10a0c}', '\u{10a0f}'), ('\u{10a38}', '\u{10a3a}'), - ('\u{10a3f}', '\u{10a3f}'), ('\u{10ae5}', '\u{10ae6}'), ('\u{11001}', - '\u{11001}'), ('\u{11038}', '\u{11046}'), ('\u{1107f}', '\u{11081}'), - ('\u{110b3}', '\u{110b6}'), ('\u{110b9}', '\u{110ba}'), ('\u{11100}', - '\u{11102}'), ('\u{11127}', '\u{1112b}'), ('\u{1112d}', '\u{11134}'), - ('\u{11173}', '\u{11173}'), ('\u{11180}', '\u{11181}'), ('\u{111b6}', - '\u{111be}'), ('\u{111ca}', '\u{111cc}'), ('\u{1122f}', '\u{11231}'), - ('\u{11234}', '\u{11234}'), ('\u{11236}', '\u{11237}'), ('\u{1123e}', - '\u{1123e}'), ('\u{112df}', '\u{112df}'), ('\u{112e3}', '\u{112ea}'), - ('\u{11300}', '\u{11301}'), ('\u{1133c}', '\u{1133c}'), ('\u{11340}', - '\u{11340}'), ('\u{11366}', '\u{1136c}'), ('\u{11370}', '\u{11374}'), - ('\u{11438}', '\u{1143f}'), ('\u{11442}', '\u{11444}'), ('\u{11446}', - '\u{11446}'), ('\u{114b3}', '\u{114b8}'), ('\u{114ba}', '\u{114ba}'), - ('\u{114bf}', '\u{114c0}'), ('\u{114c2}', '\u{114c3}'), ('\u{115b2}', - '\u{115b5}'), ('\u{115bc}', '\u{115bd}'), ('\u{115bf}', '\u{115c0}'), - ('\u{115dc}', '\u{115dd}'), ('\u{11633}', '\u{1163a}'), ('\u{1163d}', - '\u{1163d}'), ('\u{1163f}', '\u{11640}'), ('\u{116ab}', '\u{116ab}'), - ('\u{116ad}', '\u{116ad}'), ('\u{116b0}', '\u{116b5}'), ('\u{116b7}', - '\u{116b7}'), ('\u{1171d}', '\u{1171f}'), ('\u{11722}', '\u{11725}'), - ('\u{11727}', '\u{1172b}'), ('\u{11a01}', '\u{11a06}'), ('\u{11a09}', - '\u{11a0a}'), ('\u{11a33}', '\u{11a38}'), ('\u{11a3b}', '\u{11a3e}'), - ('\u{11a47}', '\u{11a47}'), ('\u{11a51}', '\u{11a56}'), ('\u{11a59}', - '\u{11a5b}'), ('\u{11a8a}', '\u{11a96}'), ('\u{11a98}', '\u{11a99}'), - ('\u{11c30}', '\u{11c36}'), ('\u{11c38}', '\u{11c3d}'), ('\u{11c3f}', - '\u{11c3f}'), ('\u{11c92}', '\u{11ca7}'), ('\u{11caa}', '\u{11cb0}'), - ('\u{11cb2}', '\u{11cb3}'), ('\u{11cb5}', '\u{11cb6}'), ('\u{11d31}', - '\u{11d36}'), ('\u{11d3a}', '\u{11d3a}'), ('\u{11d3c}', '\u{11d3d}'), - ('\u{11d3f}', '\u{11d45}'), ('\u{11d47}', '\u{11d47}'), ('\u{16af0}', - '\u{16af4}'), ('\u{16b30}', '\u{16b36}'), ('\u{16f8f}', '\u{16f92}'), - ('\u{1bc9d}', '\u{1bc9e}'), ('\u{1d167}', '\u{1d169}'), ('\u{1d17b}', - '\u{1d182}'), ('\u{1d185}', '\u{1d18b}'), ('\u{1d1aa}', '\u{1d1ad}'), - ('\u{1d242}', '\u{1d244}'), ('\u{1da00}', '\u{1da36}'), ('\u{1da3b}', - '\u{1da6c}'), ('\u{1da75}', '\u{1da75}'), ('\u{1da84}', '\u{1da84}'), - ('\u{1da9b}', '\u{1da9f}'), ('\u{1daa1}', '\u{1daaf}'), ('\u{1e000}', - '\u{1e006}'), ('\u{1e008}', '\u{1e018}'), ('\u{1e01b}', '\u{1e021}'), - ('\u{1e023}', '\u{1e024}'), ('\u{1e026}', '\u{1e02a}'), ('\u{1e8d0}', - '\u{1e8d6}'), ('\u{1e944}', '\u{1e94a}'), ('\u{e0100}', '\u{e01ef}') - ]; - - pub const N_table: &'static [(char, char)] = &[ - ('\u{30}', '\u{39}'), ('\u{660}', '\u{669}'), ('\u{6f0}', '\u{6f9}'), - ('\u{7c0}', '\u{7c9}'), ('\u{966}', '\u{96f}'), ('\u{9e6}', '\u{9ef}'), - ('\u{a66}', '\u{a6f}'), ('\u{ae6}', '\u{aef}'), ('\u{b66}', '\u{b6f}'), - ('\u{be6}', '\u{bef}'), ('\u{c66}', '\u{c6f}'), ('\u{ce6}', '\u{cef}'), - ('\u{d66}', '\u{d6f}'), ('\u{de6}', '\u{def}'), ('\u{e50}', '\u{e59}'), - ('\u{ed0}', '\u{ed9}'), ('\u{f20}', '\u{f29}'), ('\u{1040}', - '\u{1049}'), ('\u{1090}', '\u{1099}'), ('\u{16ee}', '\u{16f0}'), - ('\u{17e0}', '\u{17e9}'), ('\u{1810}', '\u{1819}'), ('\u{1946}', - '\u{194f}'), ('\u{19d0}', '\u{19d9}'), ('\u{1a80}', '\u{1a89}'), - ('\u{1a90}', '\u{1a99}'), ('\u{1b50}', '\u{1b59}'), ('\u{1bb0}', - '\u{1bb9}'), ('\u{1c40}', '\u{1c49}'), ('\u{1c50}', '\u{1c59}'), - ('\u{2160}', '\u{2182}'), ('\u{2185}', '\u{2188}'), ('\u{3007}', - '\u{3007}'), ('\u{3021}', '\u{3029}'), ('\u{3038}', '\u{303a}'), - ('\u{a620}', '\u{a629}'), ('\u{a6e6}', '\u{a6ef}'), ('\u{a8d0}', - '\u{a8d9}'), ('\u{a900}', '\u{a909}'), ('\u{a9d0}', '\u{a9d9}'), - ('\u{a9f0}', '\u{a9f9}'), ('\u{aa50}', '\u{aa59}'), ('\u{abf0}', - '\u{abf9}'), ('\u{ff10}', '\u{ff19}'), ('\u{10140}', '\u{10174}'), - ('\u{10341}', '\u{10341}'), ('\u{1034a}', '\u{1034a}'), ('\u{103d1}', - '\u{103d5}'), ('\u{104a0}', '\u{104a9}'), ('\u{11066}', '\u{1106f}'), - ('\u{110f0}', '\u{110f9}'), ('\u{11136}', '\u{1113f}'), ('\u{111d0}', - '\u{111d9}'), ('\u{112f0}', '\u{112f9}'), ('\u{11450}', '\u{11459}'), - ('\u{114d0}', '\u{114d9}'), ('\u{11650}', '\u{11659}'), ('\u{116c0}', - '\u{116c9}'), ('\u{11730}', '\u{11739}'), ('\u{118e0}', '\u{118e9}'), - ('\u{11c50}', '\u{11c59}'), ('\u{11d50}', '\u{11d59}'), ('\u{12400}', - '\u{1246e}'), ('\u{16a60}', '\u{16a69}'), ('\u{16b50}', '\u{16b59}'), - ('\u{1d7ce}', '\u{1d7ff}'), ('\u{1e950}', '\u{1e959}') - ]; - - pub const Nd_table: &'static [(char, char)] = &[ - ('\u{30}', '\u{39}'), ('\u{660}', '\u{669}'), ('\u{6f0}', '\u{6f9}'), - ('\u{7c0}', '\u{7c9}'), ('\u{966}', '\u{96f}'), ('\u{9e6}', '\u{9ef}'), - ('\u{a66}', '\u{a6f}'), ('\u{ae6}', '\u{aef}'), ('\u{b66}', '\u{b6f}'), - ('\u{be6}', '\u{bef}'), ('\u{c66}', '\u{c6f}'), ('\u{ce6}', '\u{cef}'), - ('\u{d66}', '\u{d6f}'), ('\u{de6}', '\u{def}'), ('\u{e50}', '\u{e59}'), - ('\u{ed0}', '\u{ed9}'), ('\u{f20}', '\u{f29}'), ('\u{1040}', - '\u{1049}'), ('\u{1090}', '\u{1099}'), ('\u{17e0}', '\u{17e9}'), - ('\u{1810}', '\u{1819}'), ('\u{1946}', '\u{194f}'), ('\u{19d0}', - '\u{19d9}'), ('\u{1a80}', '\u{1a89}'), ('\u{1a90}', '\u{1a99}'), - ('\u{1b50}', '\u{1b59}'), ('\u{1bb0}', '\u{1bb9}'), ('\u{1c40}', - '\u{1c49}'), ('\u{1c50}', '\u{1c59}'), ('\u{a620}', '\u{a629}'), - ('\u{a8d0}', '\u{a8d9}'), ('\u{a900}', '\u{a909}'), ('\u{a9d0}', - '\u{a9d9}'), ('\u{a9f0}', '\u{a9f9}'), ('\u{aa50}', '\u{aa59}'), - ('\u{abf0}', '\u{abf9}'), ('\u{ff10}', '\u{ff19}'), ('\u{104a0}', - '\u{104a9}'), ('\u{11066}', '\u{1106f}'), ('\u{110f0}', '\u{110f9}'), - ('\u{11136}', '\u{1113f}'), ('\u{111d0}', '\u{111d9}'), ('\u{112f0}', - '\u{112f9}'), ('\u{11450}', '\u{11459}'), ('\u{114d0}', '\u{114d9}'), - ('\u{11650}', '\u{11659}'), ('\u{116c0}', '\u{116c9}'), ('\u{11730}', - '\u{11739}'), ('\u{118e0}', '\u{118e9}'), ('\u{11c50}', '\u{11c59}'), - ('\u{11d50}', '\u{11d59}'), ('\u{16a60}', '\u{16a69}'), ('\u{16b50}', - '\u{16b59}'), ('\u{1d7ce}', '\u{1d7ff}'), ('\u{1e950}', '\u{1e959}') - ]; - - pub const Nl_table: &'static [(char, char)] = &[ - ('\u{16ee}', '\u{16f0}'), ('\u{2160}', '\u{2182}'), ('\u{2185}', - '\u{2188}'), ('\u{3007}', '\u{3007}'), ('\u{3021}', '\u{3029}'), - ('\u{3038}', '\u{303a}'), ('\u{a6e6}', '\u{a6ef}'), ('\u{10140}', - '\u{10174}'), ('\u{10341}', '\u{10341}'), ('\u{1034a}', '\u{1034a}'), - ('\u{103d1}', '\u{103d5}'), ('\u{12400}', '\u{1246e}') - ]; - - pub const No_table: &'static [(char, char)] = &[ - ('\u{b2}', '\u{b3}'), ('\u{b9}', '\u{b9}'), ('\u{bc}', '\u{be}'), - ('\u{9f4}', '\u{9f9}'), ('\u{b72}', '\u{b77}'), ('\u{bf0}', '\u{bf2}'), - ('\u{c78}', '\u{c7e}'), ('\u{d58}', '\u{d5e}'), ('\u{d70}', '\u{d78}'), - ('\u{f2a}', '\u{f33}'), ('\u{1369}', '\u{137c}'), ('\u{17f0}', - '\u{17f9}'), ('\u{19da}', '\u{19da}'), ('\u{2070}', '\u{2070}'), - ('\u{2074}', '\u{2079}'), ('\u{2080}', '\u{2089}'), ('\u{2150}', - '\u{215f}'), ('\u{2189}', '\u{2189}'), ('\u{2460}', '\u{249b}'), - ('\u{24ea}', '\u{24ff}'), ('\u{2776}', '\u{2793}'), ('\u{2cfd}', - '\u{2cfd}'), ('\u{3192}', '\u{3195}'), ('\u{3220}', '\u{3229}'), - ('\u{3248}', '\u{324f}'), ('\u{3251}', '\u{325f}'), ('\u{3280}', - '\u{3289}'), ('\u{32b1}', '\u{32bf}'), ('\u{a830}', '\u{a835}'), - ('\u{10107}', '\u{10133}'), ('\u{10175}', '\u{10178}'), ('\u{1018a}', - '\u{1018b}'), ('\u{102e1}', '\u{102fb}'), ('\u{10320}', '\u{10323}'), - ('\u{10858}', '\u{1085f}'), ('\u{10879}', '\u{1087f}'), ('\u{108a7}', - '\u{108af}'), ('\u{108fb}', '\u{108ff}'), ('\u{10916}', '\u{1091b}'), - ('\u{109bc}', '\u{109bd}'), ('\u{109c0}', '\u{109cf}'), ('\u{109d2}', - '\u{109ff}'), ('\u{10a40}', '\u{10a47}'), ('\u{10a7d}', '\u{10a7e}'), - ('\u{10a9d}', '\u{10a9f}'), ('\u{10aeb}', '\u{10aef}'), ('\u{10b58}', - '\u{10b5f}'), ('\u{10b78}', '\u{10b7f}'), ('\u{10ba9}', '\u{10baf}'), - ('\u{10cfa}', '\u{10cff}'), ('\u{10e60}', '\u{10e7e}'), ('\u{11052}', - '\u{11065}'), ('\u{111e1}', '\u{111f4}'), ('\u{1173a}', '\u{1173b}'), - ('\u{118ea}', '\u{118f2}'), ('\u{11c5a}', '\u{11c6c}'), ('\u{16b5b}', - '\u{16b61}'), ('\u{1d360}', '\u{1d371}'), ('\u{1e8c7}', '\u{1e8cf}'), - ('\u{1f100}', '\u{1f10c}') - ]; - - pub const P_table: &'static [(char, char)] = &[ - ('\u{21}', '\u{23}'), ('\u{25}', '\u{2a}'), ('\u{2c}', '\u{2f}'), - ('\u{3a}', '\u{3b}'), ('\u{3f}', '\u{40}'), ('\u{5b}', '\u{5d}'), - ('\u{5f}', '\u{5f}'), ('\u{7b}', '\u{7b}'), ('\u{7d}', '\u{7d}'), - ('\u{a1}', '\u{a1}'), ('\u{a7}', '\u{a7}'), ('\u{ab}', '\u{ab}'), - ('\u{b6}', '\u{b7}'), ('\u{bb}', '\u{bb}'), ('\u{bf}', '\u{bf}'), - ('\u{37e}', '\u{37e}'), ('\u{387}', '\u{387}'), ('\u{55a}', '\u{55f}'), - ('\u{589}', '\u{58a}'), ('\u{5be}', '\u{5be}'), ('\u{5c0}', '\u{5c0}'), - ('\u{5c3}', '\u{5c3}'), ('\u{5c6}', '\u{5c6}'), ('\u{5f3}', '\u{5f4}'), - ('\u{609}', '\u{60a}'), ('\u{60c}', '\u{60d}'), ('\u{61b}', '\u{61b}'), - ('\u{61e}', '\u{61f}'), ('\u{66a}', '\u{66d}'), ('\u{6d4}', '\u{6d4}'), - ('\u{700}', '\u{70d}'), ('\u{7f7}', '\u{7f9}'), ('\u{830}', '\u{83e}'), - ('\u{85e}', '\u{85e}'), ('\u{964}', '\u{965}'), ('\u{970}', '\u{970}'), - ('\u{9fd}', '\u{9fd}'), ('\u{af0}', '\u{af0}'), ('\u{df4}', '\u{df4}'), - ('\u{e4f}', '\u{e4f}'), ('\u{e5a}', '\u{e5b}'), ('\u{f04}', '\u{f12}'), - ('\u{f14}', '\u{f14}'), ('\u{f3a}', '\u{f3d}'), ('\u{f85}', '\u{f85}'), - ('\u{fd0}', '\u{fd4}'), ('\u{fd9}', '\u{fda}'), ('\u{104a}', - '\u{104f}'), ('\u{10fb}', '\u{10fb}'), ('\u{1360}', '\u{1368}'), - ('\u{1400}', '\u{1400}'), ('\u{166d}', '\u{166e}'), ('\u{169b}', - '\u{169c}'), ('\u{16eb}', '\u{16ed}'), ('\u{1735}', '\u{1736}'), - ('\u{17d4}', '\u{17d6}'), ('\u{17d8}', '\u{17da}'), ('\u{1800}', - '\u{180a}'), ('\u{1944}', '\u{1945}'), ('\u{1a1e}', '\u{1a1f}'), - ('\u{1aa0}', '\u{1aa6}'), ('\u{1aa8}', '\u{1aad}'), ('\u{1b5a}', - '\u{1b60}'), ('\u{1bfc}', '\u{1bff}'), ('\u{1c3b}', '\u{1c3f}'), - ('\u{1c7e}', '\u{1c7f}'), ('\u{1cc0}', '\u{1cc7}'), ('\u{1cd3}', - '\u{1cd3}'), ('\u{2010}', '\u{2027}'), ('\u{2030}', '\u{2043}'), - ('\u{2045}', '\u{2051}'), ('\u{2053}', '\u{205e}'), ('\u{207d}', - '\u{207e}'), ('\u{208d}', '\u{208e}'), ('\u{2308}', '\u{230b}'), - ('\u{2329}', '\u{232a}'), ('\u{2768}', '\u{2775}'), ('\u{27c5}', - '\u{27c6}'), ('\u{27e6}', '\u{27ef}'), ('\u{2983}', '\u{2998}'), - ('\u{29d8}', '\u{29db}'), ('\u{29fc}', '\u{29fd}'), ('\u{2cf9}', - '\u{2cfc}'), ('\u{2cfe}', '\u{2cff}'), ('\u{2d70}', '\u{2d70}'), - ('\u{2e00}', '\u{2e2e}'), ('\u{2e30}', '\u{2e49}'), ('\u{3001}', - '\u{3003}'), ('\u{3008}', '\u{3011}'), ('\u{3014}', '\u{301f}'), - ('\u{3030}', '\u{3030}'), ('\u{303d}', '\u{303d}'), ('\u{30a0}', - '\u{30a0}'), ('\u{30fb}', '\u{30fb}'), ('\u{a4fe}', '\u{a4ff}'), - ('\u{a60d}', '\u{a60f}'), ('\u{a673}', '\u{a673}'), ('\u{a67e}', - '\u{a67e}'), ('\u{a6f2}', '\u{a6f7}'), ('\u{a874}', '\u{a877}'), - ('\u{a8ce}', '\u{a8cf}'), ('\u{a8f8}', '\u{a8fa}'), ('\u{a8fc}', - '\u{a8fc}'), ('\u{a92e}', '\u{a92f}'), ('\u{a95f}', '\u{a95f}'), - ('\u{a9c1}', '\u{a9cd}'), ('\u{a9de}', '\u{a9df}'), ('\u{aa5c}', - '\u{aa5f}'), ('\u{aade}', '\u{aadf}'), ('\u{aaf0}', '\u{aaf1}'), - ('\u{abeb}', '\u{abeb}'), ('\u{fd3e}', '\u{fd3f}'), ('\u{fe10}', - '\u{fe19}'), ('\u{fe30}', '\u{fe52}'), ('\u{fe54}', '\u{fe61}'), - ('\u{fe63}', '\u{fe63}'), ('\u{fe68}', '\u{fe68}'), ('\u{fe6a}', - '\u{fe6b}'), ('\u{ff01}', '\u{ff03}'), ('\u{ff05}', '\u{ff0a}'), - ('\u{ff0c}', '\u{ff0f}'), ('\u{ff1a}', '\u{ff1b}'), ('\u{ff1f}', - '\u{ff20}'), ('\u{ff3b}', '\u{ff3d}'), ('\u{ff3f}', '\u{ff3f}'), - ('\u{ff5b}', '\u{ff5b}'), ('\u{ff5d}', '\u{ff5d}'), ('\u{ff5f}', - '\u{ff65}'), ('\u{10100}', '\u{10102}'), ('\u{1039f}', '\u{1039f}'), - ('\u{103d0}', '\u{103d0}'), ('\u{1056f}', '\u{1056f}'), ('\u{10857}', - '\u{10857}'), ('\u{1091f}', '\u{1091f}'), ('\u{1093f}', '\u{1093f}'), - ('\u{10a50}', '\u{10a58}'), ('\u{10a7f}', '\u{10a7f}'), ('\u{10af0}', - '\u{10af6}'), ('\u{10b39}', '\u{10b3f}'), ('\u{10b99}', '\u{10b9c}'), - ('\u{11047}', '\u{1104d}'), ('\u{110bb}', '\u{110bc}'), ('\u{110be}', - '\u{110c1}'), ('\u{11140}', '\u{11143}'), ('\u{11174}', '\u{11175}'), - ('\u{111c5}', '\u{111c9}'), ('\u{111cd}', '\u{111cd}'), ('\u{111db}', - '\u{111db}'), ('\u{111dd}', '\u{111df}'), ('\u{11238}', '\u{1123d}'), - ('\u{112a9}', '\u{112a9}'), ('\u{1144b}', '\u{1144f}'), ('\u{1145b}', - '\u{1145b}'), ('\u{1145d}', '\u{1145d}'), ('\u{114c6}', '\u{114c6}'), - ('\u{115c1}', '\u{115d7}'), ('\u{11641}', '\u{11643}'), ('\u{11660}', - '\u{1166c}'), ('\u{1173c}', '\u{1173e}'), ('\u{11a3f}', '\u{11a46}'), - ('\u{11a9a}', '\u{11a9c}'), ('\u{11a9e}', '\u{11aa2}'), ('\u{11c41}', - '\u{11c45}'), ('\u{11c70}', '\u{11c71}'), ('\u{12470}', '\u{12474}'), - ('\u{16a6e}', '\u{16a6f}'), ('\u{16af5}', '\u{16af5}'), ('\u{16b37}', - '\u{16b3b}'), ('\u{16b44}', '\u{16b44}'), ('\u{1bc9f}', '\u{1bc9f}'), - ('\u{1da87}', '\u{1da8b}'), ('\u{1e95e}', '\u{1e95f}') - ]; - - pub const Pc_table: &'static [(char, char)] = &[ - ('\u{5f}', '\u{5f}'), ('\u{203f}', '\u{2040}'), ('\u{2054}', - '\u{2054}'), ('\u{fe33}', '\u{fe34}'), ('\u{fe4d}', '\u{fe4f}'), - ('\u{ff3f}', '\u{ff3f}') - ]; - - pub const Pd_table: &'static [(char, char)] = &[ - ('\u{2d}', '\u{2d}'), ('\u{58a}', '\u{58a}'), ('\u{5be}', '\u{5be}'), - ('\u{1400}', '\u{1400}'), ('\u{1806}', '\u{1806}'), ('\u{2010}', - '\u{2015}'), ('\u{2e17}', '\u{2e17}'), ('\u{2e1a}', '\u{2e1a}'), - ('\u{2e3a}', '\u{2e3b}'), ('\u{2e40}', '\u{2e40}'), ('\u{301c}', - '\u{301c}'), ('\u{3030}', '\u{3030}'), ('\u{30a0}', '\u{30a0}'), - ('\u{fe31}', '\u{fe32}'), ('\u{fe58}', '\u{fe58}'), ('\u{fe63}', - '\u{fe63}'), ('\u{ff0d}', '\u{ff0d}') - ]; - - pub const Pe_table: &'static [(char, char)] = &[ - ('\u{29}', '\u{29}'), ('\u{5d}', '\u{5d}'), ('\u{7d}', '\u{7d}'), - ('\u{f3b}', '\u{f3b}'), ('\u{f3d}', '\u{f3d}'), ('\u{169c}', - '\u{169c}'), ('\u{2046}', '\u{2046}'), ('\u{207e}', '\u{207e}'), - ('\u{208e}', '\u{208e}'), ('\u{2309}', '\u{2309}'), ('\u{230b}', - '\u{230b}'), ('\u{232a}', '\u{232a}'), ('\u{2769}', '\u{2769}'), - ('\u{276b}', '\u{276b}'), ('\u{276d}', '\u{276d}'), ('\u{276f}', - '\u{276f}'), ('\u{2771}', '\u{2771}'), ('\u{2773}', '\u{2773}'), - ('\u{2775}', '\u{2775}'), ('\u{27c6}', '\u{27c6}'), ('\u{27e7}', - '\u{27e7}'), ('\u{27e9}', '\u{27e9}'), ('\u{27eb}', '\u{27eb}'), - ('\u{27ed}', '\u{27ed}'), ('\u{27ef}', '\u{27ef}'), ('\u{2984}', - '\u{2984}'), ('\u{2986}', '\u{2986}'), ('\u{2988}', '\u{2988}'), - ('\u{298a}', '\u{298a}'), ('\u{298c}', '\u{298c}'), ('\u{298e}', - '\u{298e}'), ('\u{2990}', '\u{2990}'), ('\u{2992}', '\u{2992}'), - ('\u{2994}', '\u{2994}'), ('\u{2996}', '\u{2996}'), ('\u{2998}', - '\u{2998}'), ('\u{29d9}', '\u{29d9}'), ('\u{29db}', '\u{29db}'), - ('\u{29fd}', '\u{29fd}'), ('\u{2e23}', '\u{2e23}'), ('\u{2e25}', - '\u{2e25}'), ('\u{2e27}', '\u{2e27}'), ('\u{2e29}', '\u{2e29}'), - ('\u{3009}', '\u{3009}'), ('\u{300b}', '\u{300b}'), ('\u{300d}', - '\u{300d}'), ('\u{300f}', '\u{300f}'), ('\u{3011}', '\u{3011}'), - ('\u{3015}', '\u{3015}'), ('\u{3017}', '\u{3017}'), ('\u{3019}', - '\u{3019}'), ('\u{301b}', '\u{301b}'), ('\u{301e}', '\u{301f}'), - ('\u{fd3e}', '\u{fd3e}'), ('\u{fe18}', '\u{fe18}'), ('\u{fe36}', - '\u{fe36}'), ('\u{fe38}', '\u{fe38}'), ('\u{fe3a}', '\u{fe3a}'), - ('\u{fe3c}', '\u{fe3c}'), ('\u{fe3e}', '\u{fe3e}'), ('\u{fe40}', - '\u{fe40}'), ('\u{fe42}', '\u{fe42}'), ('\u{fe44}', '\u{fe44}'), - ('\u{fe48}', '\u{fe48}'), ('\u{fe5a}', '\u{fe5a}'), ('\u{fe5c}', - '\u{fe5c}'), ('\u{fe5e}', '\u{fe5e}'), ('\u{ff09}', '\u{ff09}'), - ('\u{ff3d}', '\u{ff3d}'), ('\u{ff5d}', '\u{ff5d}'), ('\u{ff60}', - '\u{ff60}'), ('\u{ff63}', '\u{ff63}') - ]; - - pub const Pf_table: &'static [(char, char)] = &[ - ('\u{bb}', '\u{bb}'), ('\u{2019}', '\u{2019}'), ('\u{201d}', - '\u{201d}'), ('\u{203a}', '\u{203a}'), ('\u{2e03}', '\u{2e03}'), - ('\u{2e05}', '\u{2e05}'), ('\u{2e0a}', '\u{2e0a}'), ('\u{2e0d}', - '\u{2e0d}'), ('\u{2e1d}', '\u{2e1d}'), ('\u{2e21}', '\u{2e21}') - ]; - - pub const Pi_table: &'static [(char, char)] = &[ - ('\u{ab}', '\u{ab}'), ('\u{2018}', '\u{2018}'), ('\u{201b}', - '\u{201c}'), ('\u{201f}', '\u{201f}'), ('\u{2039}', '\u{2039}'), - ('\u{2e02}', '\u{2e02}'), ('\u{2e04}', '\u{2e04}'), ('\u{2e09}', - '\u{2e09}'), ('\u{2e0c}', '\u{2e0c}'), ('\u{2e1c}', '\u{2e1c}'), - ('\u{2e20}', '\u{2e20}') - ]; - - pub const Po_table: &'static [(char, char)] = &[ - ('\u{21}', '\u{23}'), ('\u{25}', '\u{27}'), ('\u{2a}', '\u{2a}'), - ('\u{2c}', '\u{2c}'), ('\u{2e}', '\u{2f}'), ('\u{3a}', '\u{3b}'), - ('\u{3f}', '\u{40}'), ('\u{5c}', '\u{5c}'), ('\u{a1}', '\u{a1}'), - ('\u{a7}', '\u{a7}'), ('\u{b6}', '\u{b7}'), ('\u{bf}', '\u{bf}'), - ('\u{37e}', '\u{37e}'), ('\u{387}', '\u{387}'), ('\u{55a}', '\u{55f}'), - ('\u{589}', '\u{589}'), ('\u{5c0}', '\u{5c0}'), ('\u{5c3}', '\u{5c3}'), - ('\u{5c6}', '\u{5c6}'), ('\u{5f3}', '\u{5f4}'), ('\u{609}', '\u{60a}'), - ('\u{60c}', '\u{60d}'), ('\u{61b}', '\u{61b}'), ('\u{61e}', '\u{61f}'), - ('\u{66a}', '\u{66d}'), ('\u{6d4}', '\u{6d4}'), ('\u{700}', '\u{70d}'), - ('\u{7f7}', '\u{7f9}'), ('\u{830}', '\u{83e}'), ('\u{85e}', '\u{85e}'), - ('\u{964}', '\u{965}'), ('\u{970}', '\u{970}'), ('\u{9fd}', '\u{9fd}'), - ('\u{af0}', '\u{af0}'), ('\u{df4}', '\u{df4}'), ('\u{e4f}', '\u{e4f}'), - ('\u{e5a}', '\u{e5b}'), ('\u{f04}', '\u{f12}'), ('\u{f14}', '\u{f14}'), - ('\u{f85}', '\u{f85}'), ('\u{fd0}', '\u{fd4}'), ('\u{fd9}', '\u{fda}'), - ('\u{104a}', '\u{104f}'), ('\u{10fb}', '\u{10fb}'), ('\u{1360}', - '\u{1368}'), ('\u{166d}', '\u{166e}'), ('\u{16eb}', '\u{16ed}'), - ('\u{1735}', '\u{1736}'), ('\u{17d4}', '\u{17d6}'), ('\u{17d8}', - '\u{17da}'), ('\u{1800}', '\u{1805}'), ('\u{1807}', '\u{180a}'), - ('\u{1944}', '\u{1945}'), ('\u{1a1e}', '\u{1a1f}'), ('\u{1aa0}', - '\u{1aa6}'), ('\u{1aa8}', '\u{1aad}'), ('\u{1b5a}', '\u{1b60}'), - ('\u{1bfc}', '\u{1bff}'), ('\u{1c3b}', '\u{1c3f}'), ('\u{1c7e}', - '\u{1c7f}'), ('\u{1cc0}', '\u{1cc7}'), ('\u{1cd3}', '\u{1cd3}'), - ('\u{2016}', '\u{2017}'), ('\u{2020}', '\u{2027}'), ('\u{2030}', - '\u{2038}'), ('\u{203b}', '\u{203e}'), ('\u{2041}', '\u{2043}'), - ('\u{2047}', '\u{2051}'), ('\u{2053}', '\u{2053}'), ('\u{2055}', - '\u{205e}'), ('\u{2cf9}', '\u{2cfc}'), ('\u{2cfe}', '\u{2cff}'), - ('\u{2d70}', '\u{2d70}'), ('\u{2e00}', '\u{2e01}'), ('\u{2e06}', - '\u{2e08}'), ('\u{2e0b}', '\u{2e0b}'), ('\u{2e0e}', '\u{2e16}'), - ('\u{2e18}', '\u{2e19}'), ('\u{2e1b}', '\u{2e1b}'), ('\u{2e1e}', - '\u{2e1f}'), ('\u{2e2a}', '\u{2e2e}'), ('\u{2e30}', '\u{2e39}'), - ('\u{2e3c}', '\u{2e3f}'), ('\u{2e41}', '\u{2e41}'), ('\u{2e43}', - '\u{2e49}'), ('\u{3001}', '\u{3003}'), ('\u{303d}', '\u{303d}'), - ('\u{30fb}', '\u{30fb}'), ('\u{a4fe}', '\u{a4ff}'), ('\u{a60d}', - '\u{a60f}'), ('\u{a673}', '\u{a673}'), ('\u{a67e}', '\u{a67e}'), - ('\u{a6f2}', '\u{a6f7}'), ('\u{a874}', '\u{a877}'), ('\u{a8ce}', - '\u{a8cf}'), ('\u{a8f8}', '\u{a8fa}'), ('\u{a8fc}', '\u{a8fc}'), - ('\u{a92e}', '\u{a92f}'), ('\u{a95f}', '\u{a95f}'), ('\u{a9c1}', - '\u{a9cd}'), ('\u{a9de}', '\u{a9df}'), ('\u{aa5c}', '\u{aa5f}'), - ('\u{aade}', '\u{aadf}'), ('\u{aaf0}', '\u{aaf1}'), ('\u{abeb}', - '\u{abeb}'), ('\u{fe10}', '\u{fe16}'), ('\u{fe19}', '\u{fe19}'), - ('\u{fe30}', '\u{fe30}'), ('\u{fe45}', '\u{fe46}'), ('\u{fe49}', - '\u{fe4c}'), ('\u{fe50}', '\u{fe52}'), ('\u{fe54}', '\u{fe57}'), - ('\u{fe5f}', '\u{fe61}'), ('\u{fe68}', '\u{fe68}'), ('\u{fe6a}', - '\u{fe6b}'), ('\u{ff01}', '\u{ff03}'), ('\u{ff05}', '\u{ff07}'), - ('\u{ff0a}', '\u{ff0a}'), ('\u{ff0c}', '\u{ff0c}'), ('\u{ff0e}', - '\u{ff0f}'), ('\u{ff1a}', '\u{ff1b}'), ('\u{ff1f}', '\u{ff20}'), - ('\u{ff3c}', '\u{ff3c}'), ('\u{ff61}', '\u{ff61}'), ('\u{ff64}', - '\u{ff65}'), ('\u{10100}', '\u{10102}'), ('\u{1039f}', '\u{1039f}'), - ('\u{103d0}', '\u{103d0}'), ('\u{1056f}', '\u{1056f}'), ('\u{10857}', - '\u{10857}'), ('\u{1091f}', '\u{1091f}'), ('\u{1093f}', '\u{1093f}'), - ('\u{10a50}', '\u{10a58}'), ('\u{10a7f}', '\u{10a7f}'), ('\u{10af0}', - '\u{10af6}'), ('\u{10b39}', '\u{10b3f}'), ('\u{10b99}', '\u{10b9c}'), - ('\u{11047}', '\u{1104d}'), ('\u{110bb}', '\u{110bc}'), ('\u{110be}', - '\u{110c1}'), ('\u{11140}', '\u{11143}'), ('\u{11174}', '\u{11175}'), - ('\u{111c5}', '\u{111c9}'), ('\u{111cd}', '\u{111cd}'), ('\u{111db}', - '\u{111db}'), ('\u{111dd}', '\u{111df}'), ('\u{11238}', '\u{1123d}'), - ('\u{112a9}', '\u{112a9}'), ('\u{1144b}', '\u{1144f}'), ('\u{1145b}', - '\u{1145b}'), ('\u{1145d}', '\u{1145d}'), ('\u{114c6}', '\u{114c6}'), - ('\u{115c1}', '\u{115d7}'), ('\u{11641}', '\u{11643}'), ('\u{11660}', - '\u{1166c}'), ('\u{1173c}', '\u{1173e}'), ('\u{11a3f}', '\u{11a46}'), - ('\u{11a9a}', '\u{11a9c}'), ('\u{11a9e}', '\u{11aa2}'), ('\u{11c41}', - '\u{11c45}'), ('\u{11c70}', '\u{11c71}'), ('\u{12470}', '\u{12474}'), - ('\u{16a6e}', '\u{16a6f}'), ('\u{16af5}', '\u{16af5}'), ('\u{16b37}', - '\u{16b3b}'), ('\u{16b44}', '\u{16b44}'), ('\u{1bc9f}', '\u{1bc9f}'), - ('\u{1da87}', '\u{1da8b}'), ('\u{1e95e}', '\u{1e95f}') - ]; - - pub const Ps_table: &'static [(char, char)] = &[ - ('\u{28}', '\u{28}'), ('\u{5b}', '\u{5b}'), ('\u{7b}', '\u{7b}'), - ('\u{f3a}', '\u{f3a}'), ('\u{f3c}', '\u{f3c}'), ('\u{169b}', - '\u{169b}'), ('\u{201a}', '\u{201a}'), ('\u{201e}', '\u{201e}'), - ('\u{2045}', '\u{2045}'), ('\u{207d}', '\u{207d}'), ('\u{208d}', - '\u{208d}'), ('\u{2308}', '\u{2308}'), ('\u{230a}', '\u{230a}'), - ('\u{2329}', '\u{2329}'), ('\u{2768}', '\u{2768}'), ('\u{276a}', - '\u{276a}'), ('\u{276c}', '\u{276c}'), ('\u{276e}', '\u{276e}'), - ('\u{2770}', '\u{2770}'), ('\u{2772}', '\u{2772}'), ('\u{2774}', - '\u{2774}'), ('\u{27c5}', '\u{27c5}'), ('\u{27e6}', '\u{27e6}'), - ('\u{27e8}', '\u{27e8}'), ('\u{27ea}', '\u{27ea}'), ('\u{27ec}', - '\u{27ec}'), ('\u{27ee}', '\u{27ee}'), ('\u{2983}', '\u{2983}'), - ('\u{2985}', '\u{2985}'), ('\u{2987}', '\u{2987}'), ('\u{2989}', - '\u{2989}'), ('\u{298b}', '\u{298b}'), ('\u{298d}', '\u{298d}'), - ('\u{298f}', '\u{298f}'), ('\u{2991}', '\u{2991}'), ('\u{2993}', - '\u{2993}'), ('\u{2995}', '\u{2995}'), ('\u{2997}', '\u{2997}'), - ('\u{29d8}', '\u{29d8}'), ('\u{29da}', '\u{29da}'), ('\u{29fc}', - '\u{29fc}'), ('\u{2e22}', '\u{2e22}'), ('\u{2e24}', '\u{2e24}'), - ('\u{2e26}', '\u{2e26}'), ('\u{2e28}', '\u{2e28}'), ('\u{2e42}', - '\u{2e42}'), ('\u{3008}', '\u{3008}'), ('\u{300a}', '\u{300a}'), - ('\u{300c}', '\u{300c}'), ('\u{300e}', '\u{300e}'), ('\u{3010}', - '\u{3010}'), ('\u{3014}', '\u{3014}'), ('\u{3016}', '\u{3016}'), - ('\u{3018}', '\u{3018}'), ('\u{301a}', '\u{301a}'), ('\u{301d}', - '\u{301d}'), ('\u{fd3f}', '\u{fd3f}'), ('\u{fe17}', '\u{fe17}'), - ('\u{fe35}', '\u{fe35}'), ('\u{fe37}', '\u{fe37}'), ('\u{fe39}', - '\u{fe39}'), ('\u{fe3b}', '\u{fe3b}'), ('\u{fe3d}', '\u{fe3d}'), - ('\u{fe3f}', '\u{fe3f}'), ('\u{fe41}', '\u{fe41}'), ('\u{fe43}', - '\u{fe43}'), ('\u{fe47}', '\u{fe47}'), ('\u{fe59}', '\u{fe59}'), - ('\u{fe5b}', '\u{fe5b}'), ('\u{fe5d}', '\u{fe5d}'), ('\u{ff08}', - '\u{ff08}'), ('\u{ff3b}', '\u{ff3b}'), ('\u{ff5b}', '\u{ff5b}'), - ('\u{ff5f}', '\u{ff5f}'), ('\u{ff62}', '\u{ff62}') - ]; - - pub const S_table: &'static [(char, char)] = &[ - ('\u{24}', '\u{24}'), ('\u{2b}', '\u{2b}'), ('\u{3c}', '\u{3e}'), - ('\u{5e}', '\u{5e}'), ('\u{60}', '\u{60}'), ('\u{7c}', '\u{7c}'), - ('\u{7e}', '\u{7e}'), ('\u{a2}', '\u{a6}'), ('\u{a8}', '\u{a9}'), - ('\u{ac}', '\u{ac}'), ('\u{ae}', '\u{b1}'), ('\u{b4}', '\u{b4}'), - ('\u{b8}', '\u{b8}'), ('\u{d7}', '\u{d7}'), ('\u{f7}', '\u{f7}'), - ('\u{2c2}', '\u{2c5}'), ('\u{2d2}', '\u{2df}'), ('\u{2e5}', '\u{2eb}'), - ('\u{2ed}', '\u{2ed}'), ('\u{2ef}', '\u{2ff}'), ('\u{375}', '\u{375}'), - ('\u{384}', '\u{385}'), ('\u{3f6}', '\u{3f6}'), ('\u{482}', '\u{482}'), - ('\u{58d}', '\u{58f}'), ('\u{606}', '\u{608}'), ('\u{60b}', '\u{60b}'), - ('\u{60e}', '\u{60f}'), ('\u{6de}', '\u{6de}'), ('\u{6e9}', '\u{6e9}'), - ('\u{6fd}', '\u{6fe}'), ('\u{7f6}', '\u{7f6}'), ('\u{9f2}', '\u{9f3}'), - ('\u{9fa}', '\u{9fb}'), ('\u{af1}', '\u{af1}'), ('\u{b70}', '\u{b70}'), - ('\u{bf3}', '\u{bfa}'), ('\u{c7f}', '\u{c7f}'), ('\u{d4f}', '\u{d4f}'), - ('\u{d79}', '\u{d79}'), ('\u{e3f}', '\u{e3f}'), ('\u{f01}', '\u{f03}'), - ('\u{f13}', '\u{f13}'), ('\u{f15}', '\u{f17}'), ('\u{f1a}', '\u{f1f}'), - ('\u{f34}', '\u{f34}'), ('\u{f36}', '\u{f36}'), ('\u{f38}', '\u{f38}'), - ('\u{fbe}', '\u{fc5}'), ('\u{fc7}', '\u{fcc}'), ('\u{fce}', '\u{fcf}'), - ('\u{fd5}', '\u{fd8}'), ('\u{109e}', '\u{109f}'), ('\u{1390}', - '\u{1399}'), ('\u{17db}', '\u{17db}'), ('\u{1940}', '\u{1940}'), - ('\u{19de}', '\u{19ff}'), ('\u{1b61}', '\u{1b6a}'), ('\u{1b74}', - '\u{1b7c}'), ('\u{1fbd}', '\u{1fbd}'), ('\u{1fbf}', '\u{1fc1}'), - ('\u{1fcd}', '\u{1fcf}'), ('\u{1fdd}', '\u{1fdf}'), ('\u{1fed}', - '\u{1fef}'), ('\u{1ffd}', '\u{1ffe}'), ('\u{2044}', '\u{2044}'), - ('\u{2052}', '\u{2052}'), ('\u{207a}', '\u{207c}'), ('\u{208a}', - '\u{208c}'), ('\u{20a0}', '\u{20bf}'), ('\u{2100}', '\u{2101}'), - ('\u{2103}', '\u{2106}'), ('\u{2108}', '\u{2109}'), ('\u{2114}', - '\u{2114}'), ('\u{2116}', '\u{2118}'), ('\u{211e}', '\u{2123}'), - ('\u{2125}', '\u{2125}'), ('\u{2127}', '\u{2127}'), ('\u{2129}', - '\u{2129}'), ('\u{212e}', '\u{212e}'), ('\u{213a}', '\u{213b}'), - ('\u{2140}', '\u{2144}'), ('\u{214a}', '\u{214d}'), ('\u{214f}', - '\u{214f}'), ('\u{218a}', '\u{218b}'), ('\u{2190}', '\u{2307}'), - ('\u{230c}', '\u{2328}'), ('\u{232b}', '\u{2426}'), ('\u{2440}', - '\u{244a}'), ('\u{249c}', '\u{24e9}'), ('\u{2500}', '\u{2767}'), - ('\u{2794}', '\u{27c4}'), ('\u{27c7}', '\u{27e5}'), ('\u{27f0}', - '\u{2982}'), ('\u{2999}', '\u{29d7}'), ('\u{29dc}', '\u{29fb}'), - ('\u{29fe}', '\u{2b73}'), ('\u{2b76}', '\u{2b95}'), ('\u{2b98}', - '\u{2bb9}'), ('\u{2bbd}', '\u{2bc8}'), ('\u{2bca}', '\u{2bd2}'), - ('\u{2bec}', '\u{2bef}'), ('\u{2ce5}', '\u{2cea}'), ('\u{2e80}', - '\u{2e99}'), ('\u{2e9b}', '\u{2ef3}'), ('\u{2f00}', '\u{2fd5}'), - ('\u{2ff0}', '\u{2ffb}'), ('\u{3004}', '\u{3004}'), ('\u{3012}', - '\u{3013}'), ('\u{3020}', '\u{3020}'), ('\u{3036}', '\u{3037}'), - ('\u{303e}', '\u{303f}'), ('\u{309b}', '\u{309c}'), ('\u{3190}', - '\u{3191}'), ('\u{3196}', '\u{319f}'), ('\u{31c0}', '\u{31e3}'), - ('\u{3200}', '\u{321e}'), ('\u{322a}', '\u{3247}'), ('\u{3250}', - '\u{3250}'), ('\u{3260}', '\u{327f}'), ('\u{328a}', '\u{32b0}'), - ('\u{32c0}', '\u{32fe}'), ('\u{3300}', '\u{33ff}'), ('\u{4dc0}', - '\u{4dff}'), ('\u{a490}', '\u{a4c6}'), ('\u{a700}', '\u{a716}'), - ('\u{a720}', '\u{a721}'), ('\u{a789}', '\u{a78a}'), ('\u{a828}', - '\u{a82b}'), ('\u{a836}', '\u{a839}'), ('\u{aa77}', '\u{aa79}'), - ('\u{ab5b}', '\u{ab5b}'), ('\u{fb29}', '\u{fb29}'), ('\u{fbb2}', - '\u{fbc1}'), ('\u{fdfc}', '\u{fdfd}'), ('\u{fe62}', '\u{fe62}'), - ('\u{fe64}', '\u{fe66}'), ('\u{fe69}', '\u{fe69}'), ('\u{ff04}', - '\u{ff04}'), ('\u{ff0b}', '\u{ff0b}'), ('\u{ff1c}', '\u{ff1e}'), - ('\u{ff3e}', '\u{ff3e}'), ('\u{ff40}', '\u{ff40}'), ('\u{ff5c}', - '\u{ff5c}'), ('\u{ff5e}', '\u{ff5e}'), ('\u{ffe0}', '\u{ffe6}'), - ('\u{ffe8}', '\u{ffee}'), ('\u{fffc}', '\u{fffd}'), ('\u{10137}', - '\u{1013f}'), ('\u{10179}', '\u{10189}'), ('\u{1018c}', '\u{1018e}'), - ('\u{10190}', '\u{1019b}'), ('\u{101a0}', '\u{101a0}'), ('\u{101d0}', - '\u{101fc}'), ('\u{10877}', '\u{10878}'), ('\u{10ac8}', '\u{10ac8}'), - ('\u{1173f}', '\u{1173f}'), ('\u{16b3c}', '\u{16b3f}'), ('\u{16b45}', - '\u{16b45}'), ('\u{1bc9c}', '\u{1bc9c}'), ('\u{1d000}', '\u{1d0f5}'), - ('\u{1d100}', '\u{1d126}'), ('\u{1d129}', '\u{1d164}'), ('\u{1d16a}', - '\u{1d16c}'), ('\u{1d183}', '\u{1d184}'), ('\u{1d18c}', '\u{1d1a9}'), - ('\u{1d1ae}', '\u{1d1e8}'), ('\u{1d200}', '\u{1d241}'), ('\u{1d245}', - '\u{1d245}'), ('\u{1d300}', '\u{1d356}'), ('\u{1d6c1}', '\u{1d6c1}'), - ('\u{1d6db}', '\u{1d6db}'), ('\u{1d6fb}', '\u{1d6fb}'), ('\u{1d715}', - '\u{1d715}'), ('\u{1d735}', '\u{1d735}'), ('\u{1d74f}', '\u{1d74f}'), - ('\u{1d76f}', '\u{1d76f}'), ('\u{1d789}', '\u{1d789}'), ('\u{1d7a9}', - '\u{1d7a9}'), ('\u{1d7c3}', '\u{1d7c3}'), ('\u{1d800}', '\u{1d9ff}'), - ('\u{1da37}', '\u{1da3a}'), ('\u{1da6d}', '\u{1da74}'), ('\u{1da76}', - '\u{1da83}'), ('\u{1da85}', '\u{1da86}'), ('\u{1eef0}', '\u{1eef1}'), - ('\u{1f000}', '\u{1f02b}'), ('\u{1f030}', '\u{1f093}'), ('\u{1f0a0}', - '\u{1f0ae}'), ('\u{1f0b1}', '\u{1f0bf}'), ('\u{1f0c1}', '\u{1f0cf}'), - ('\u{1f0d1}', '\u{1f0f5}'), ('\u{1f110}', '\u{1f12e}'), ('\u{1f130}', - '\u{1f16b}'), ('\u{1f170}', '\u{1f1ac}'), ('\u{1f1e6}', '\u{1f202}'), - ('\u{1f210}', '\u{1f23b}'), ('\u{1f240}', '\u{1f248}'), ('\u{1f250}', - '\u{1f251}'), ('\u{1f260}', '\u{1f265}'), ('\u{1f300}', '\u{1f6d4}'), - ('\u{1f6e0}', '\u{1f6ec}'), ('\u{1f6f0}', '\u{1f6f8}'), ('\u{1f700}', - '\u{1f773}'), ('\u{1f780}', '\u{1f7d4}'), ('\u{1f800}', '\u{1f80b}'), - ('\u{1f810}', '\u{1f847}'), ('\u{1f850}', '\u{1f859}'), ('\u{1f860}', - '\u{1f887}'), ('\u{1f890}', '\u{1f8ad}'), ('\u{1f900}', '\u{1f90b}'), - ('\u{1f910}', '\u{1f93e}'), ('\u{1f940}', '\u{1f94c}'), ('\u{1f950}', - '\u{1f96b}'), ('\u{1f980}', '\u{1f997}'), ('\u{1f9c0}', '\u{1f9c0}'), - ('\u{1f9d0}', '\u{1f9e6}') - ]; - - pub const Sc_table: &'static [(char, char)] = &[ - ('\u{24}', '\u{24}'), ('\u{a2}', '\u{a5}'), ('\u{58f}', '\u{58f}'), - ('\u{60b}', '\u{60b}'), ('\u{9f2}', '\u{9f3}'), ('\u{9fb}', '\u{9fb}'), - ('\u{af1}', '\u{af1}'), ('\u{bf9}', '\u{bf9}'), ('\u{e3f}', '\u{e3f}'), - ('\u{17db}', '\u{17db}'), ('\u{20a0}', '\u{20bf}'), ('\u{a838}', - '\u{a838}'), ('\u{fdfc}', '\u{fdfc}'), ('\u{fe69}', '\u{fe69}'), - ('\u{ff04}', '\u{ff04}'), ('\u{ffe0}', '\u{ffe1}'), ('\u{ffe5}', - '\u{ffe6}') - ]; - - pub const Sk_table: &'static [(char, char)] = &[ - ('\u{5e}', '\u{5e}'), ('\u{60}', '\u{60}'), ('\u{a8}', '\u{a8}'), - ('\u{af}', '\u{af}'), ('\u{b4}', '\u{b4}'), ('\u{b8}', '\u{b8}'), - ('\u{2c2}', '\u{2c5}'), ('\u{2d2}', '\u{2df}'), ('\u{2e5}', '\u{2eb}'), - ('\u{2ed}', '\u{2ed}'), ('\u{2ef}', '\u{2ff}'), ('\u{375}', '\u{375}'), - ('\u{384}', '\u{385}'), ('\u{1fbd}', '\u{1fbd}'), ('\u{1fbf}', - '\u{1fc1}'), ('\u{1fcd}', '\u{1fcf}'), ('\u{1fdd}', '\u{1fdf}'), - ('\u{1fed}', '\u{1fef}'), ('\u{1ffd}', '\u{1ffe}'), ('\u{309b}', - '\u{309c}'), ('\u{a700}', '\u{a716}'), ('\u{a720}', '\u{a721}'), - ('\u{a789}', '\u{a78a}'), ('\u{ab5b}', '\u{ab5b}'), ('\u{fbb2}', - '\u{fbc1}'), ('\u{ff3e}', '\u{ff3e}'), ('\u{ff40}', '\u{ff40}'), - ('\u{ffe3}', '\u{ffe3}'), ('\u{1f3fb}', '\u{1f3ff}') - ]; - - pub const Sm_table: &'static [(char, char)] = &[ - ('\u{2b}', '\u{2b}'), ('\u{3c}', '\u{3e}'), ('\u{7c}', '\u{7c}'), - ('\u{7e}', '\u{7e}'), ('\u{ac}', '\u{ac}'), ('\u{b1}', '\u{b1}'), - ('\u{d7}', '\u{d7}'), ('\u{f7}', '\u{f7}'), ('\u{3f6}', '\u{3f6}'), - ('\u{606}', '\u{608}'), ('\u{2044}', '\u{2044}'), ('\u{2052}', - '\u{2052}'), ('\u{207a}', '\u{207c}'), ('\u{208a}', '\u{208c}'), - ('\u{2118}', '\u{2118}'), ('\u{2140}', '\u{2144}'), ('\u{214b}', - '\u{214b}'), ('\u{2190}', '\u{2194}'), ('\u{219a}', '\u{219b}'), - ('\u{21a0}', '\u{21a0}'), ('\u{21a3}', '\u{21a3}'), ('\u{21a6}', - '\u{21a6}'), ('\u{21ae}', '\u{21ae}'), ('\u{21ce}', '\u{21cf}'), - ('\u{21d2}', '\u{21d2}'), ('\u{21d4}', '\u{21d4}'), ('\u{21f4}', - '\u{22ff}'), ('\u{2320}', '\u{2321}'), ('\u{237c}', '\u{237c}'), - ('\u{239b}', '\u{23b3}'), ('\u{23dc}', '\u{23e1}'), ('\u{25b7}', - '\u{25b7}'), ('\u{25c1}', '\u{25c1}'), ('\u{25f8}', '\u{25ff}'), - ('\u{266f}', '\u{266f}'), ('\u{27c0}', '\u{27c4}'), ('\u{27c7}', - '\u{27e5}'), ('\u{27f0}', '\u{27ff}'), ('\u{2900}', '\u{2982}'), - ('\u{2999}', '\u{29d7}'), ('\u{29dc}', '\u{29fb}'), ('\u{29fe}', - '\u{2aff}'), ('\u{2b30}', '\u{2b44}'), ('\u{2b47}', '\u{2b4c}'), - ('\u{fb29}', '\u{fb29}'), ('\u{fe62}', '\u{fe62}'), ('\u{fe64}', - '\u{fe66}'), ('\u{ff0b}', '\u{ff0b}'), ('\u{ff1c}', '\u{ff1e}'), - ('\u{ff5c}', '\u{ff5c}'), ('\u{ff5e}', '\u{ff5e}'), ('\u{ffe2}', - '\u{ffe2}'), ('\u{ffe9}', '\u{ffec}'), ('\u{1d6c1}', '\u{1d6c1}'), - ('\u{1d6db}', '\u{1d6db}'), ('\u{1d6fb}', '\u{1d6fb}'), ('\u{1d715}', - '\u{1d715}'), ('\u{1d735}', '\u{1d735}'), ('\u{1d74f}', '\u{1d74f}'), - ('\u{1d76f}', '\u{1d76f}'), ('\u{1d789}', '\u{1d789}'), ('\u{1d7a9}', - '\u{1d7a9}'), ('\u{1d7c3}', '\u{1d7c3}'), ('\u{1eef0}', '\u{1eef1}') - ]; - - pub const So_table: &'static [(char, char)] = &[ - ('\u{a6}', '\u{a6}'), ('\u{a9}', '\u{a9}'), ('\u{ae}', '\u{ae}'), - ('\u{b0}', '\u{b0}'), ('\u{482}', '\u{482}'), ('\u{58d}', '\u{58e}'), - ('\u{60e}', '\u{60f}'), ('\u{6de}', '\u{6de}'), ('\u{6e9}', '\u{6e9}'), - ('\u{6fd}', '\u{6fe}'), ('\u{7f6}', '\u{7f6}'), ('\u{9fa}', '\u{9fa}'), - ('\u{b70}', '\u{b70}'), ('\u{bf3}', '\u{bf8}'), ('\u{bfa}', '\u{bfa}'), - ('\u{c7f}', '\u{c7f}'), ('\u{d4f}', '\u{d4f}'), ('\u{d79}', '\u{d79}'), - ('\u{f01}', '\u{f03}'), ('\u{f13}', '\u{f13}'), ('\u{f15}', '\u{f17}'), - ('\u{f1a}', '\u{f1f}'), ('\u{f34}', '\u{f34}'), ('\u{f36}', '\u{f36}'), - ('\u{f38}', '\u{f38}'), ('\u{fbe}', '\u{fc5}'), ('\u{fc7}', '\u{fcc}'), - ('\u{fce}', '\u{fcf}'), ('\u{fd5}', '\u{fd8}'), ('\u{109e}', - '\u{109f}'), ('\u{1390}', '\u{1399}'), ('\u{1940}', '\u{1940}'), - ('\u{19de}', '\u{19ff}'), ('\u{1b61}', '\u{1b6a}'), ('\u{1b74}', - '\u{1b7c}'), ('\u{2100}', '\u{2101}'), ('\u{2103}', '\u{2106}'), - ('\u{2108}', '\u{2109}'), ('\u{2114}', '\u{2114}'), ('\u{2116}', - '\u{2117}'), ('\u{211e}', '\u{2123}'), ('\u{2125}', '\u{2125}'), - ('\u{2127}', '\u{2127}'), ('\u{2129}', '\u{2129}'), ('\u{212e}', - '\u{212e}'), ('\u{213a}', '\u{213b}'), ('\u{214a}', '\u{214a}'), - ('\u{214c}', '\u{214d}'), ('\u{214f}', '\u{214f}'), ('\u{218a}', - '\u{218b}'), ('\u{2195}', '\u{2199}'), ('\u{219c}', '\u{219f}'), - ('\u{21a1}', '\u{21a2}'), ('\u{21a4}', '\u{21a5}'), ('\u{21a7}', - '\u{21ad}'), ('\u{21af}', '\u{21cd}'), ('\u{21d0}', '\u{21d1}'), - ('\u{21d3}', '\u{21d3}'), ('\u{21d5}', '\u{21f3}'), ('\u{2300}', - '\u{2307}'), ('\u{230c}', '\u{231f}'), ('\u{2322}', '\u{2328}'), - ('\u{232b}', '\u{237b}'), ('\u{237d}', '\u{239a}'), ('\u{23b4}', - '\u{23db}'), ('\u{23e2}', '\u{2426}'), ('\u{2440}', '\u{244a}'), - ('\u{249c}', '\u{24e9}'), ('\u{2500}', '\u{25b6}'), ('\u{25b8}', - '\u{25c0}'), ('\u{25c2}', '\u{25f7}'), ('\u{2600}', '\u{266e}'), - ('\u{2670}', '\u{2767}'), ('\u{2794}', '\u{27bf}'), ('\u{2800}', - '\u{28ff}'), ('\u{2b00}', '\u{2b2f}'), ('\u{2b45}', '\u{2b46}'), - ('\u{2b4d}', '\u{2b73}'), ('\u{2b76}', '\u{2b95}'), ('\u{2b98}', - '\u{2bb9}'), ('\u{2bbd}', '\u{2bc8}'), ('\u{2bca}', '\u{2bd2}'), - ('\u{2bec}', '\u{2bef}'), ('\u{2ce5}', '\u{2cea}'), ('\u{2e80}', - '\u{2e99}'), ('\u{2e9b}', '\u{2ef3}'), ('\u{2f00}', '\u{2fd5}'), - ('\u{2ff0}', '\u{2ffb}'), ('\u{3004}', '\u{3004}'), ('\u{3012}', - '\u{3013}'), ('\u{3020}', '\u{3020}'), ('\u{3036}', '\u{3037}'), - ('\u{303e}', '\u{303f}'), ('\u{3190}', '\u{3191}'), ('\u{3196}', - '\u{319f}'), ('\u{31c0}', '\u{31e3}'), ('\u{3200}', '\u{321e}'), - ('\u{322a}', '\u{3247}'), ('\u{3250}', '\u{3250}'), ('\u{3260}', - '\u{327f}'), ('\u{328a}', '\u{32b0}'), ('\u{32c0}', '\u{32fe}'), - ('\u{3300}', '\u{33ff}'), ('\u{4dc0}', '\u{4dff}'), ('\u{a490}', - '\u{a4c6}'), ('\u{a828}', '\u{a82b}'), ('\u{a836}', '\u{a837}'), - ('\u{a839}', '\u{a839}'), ('\u{aa77}', '\u{aa79}'), ('\u{fdfd}', - '\u{fdfd}'), ('\u{ffe4}', '\u{ffe4}'), ('\u{ffe8}', '\u{ffe8}'), - ('\u{ffed}', '\u{ffee}'), ('\u{fffc}', '\u{fffd}'), ('\u{10137}', - '\u{1013f}'), ('\u{10179}', '\u{10189}'), ('\u{1018c}', '\u{1018e}'), - ('\u{10190}', '\u{1019b}'), ('\u{101a0}', '\u{101a0}'), ('\u{101d0}', - '\u{101fc}'), ('\u{10877}', '\u{10878}'), ('\u{10ac8}', '\u{10ac8}'), - ('\u{1173f}', '\u{1173f}'), ('\u{16b3c}', '\u{16b3f}'), ('\u{16b45}', - '\u{16b45}'), ('\u{1bc9c}', '\u{1bc9c}'), ('\u{1d000}', '\u{1d0f5}'), - ('\u{1d100}', '\u{1d126}'), ('\u{1d129}', '\u{1d164}'), ('\u{1d16a}', - '\u{1d16c}'), ('\u{1d183}', '\u{1d184}'), ('\u{1d18c}', '\u{1d1a9}'), - ('\u{1d1ae}', '\u{1d1e8}'), ('\u{1d200}', '\u{1d241}'), ('\u{1d245}', - '\u{1d245}'), ('\u{1d300}', '\u{1d356}'), ('\u{1d800}', '\u{1d9ff}'), - ('\u{1da37}', '\u{1da3a}'), ('\u{1da6d}', '\u{1da74}'), ('\u{1da76}', - '\u{1da83}'), ('\u{1da85}', '\u{1da86}'), ('\u{1f000}', '\u{1f02b}'), - ('\u{1f030}', '\u{1f093}'), ('\u{1f0a0}', '\u{1f0ae}'), ('\u{1f0b1}', - '\u{1f0bf}'), ('\u{1f0c1}', '\u{1f0cf}'), ('\u{1f0d1}', '\u{1f0f5}'), - ('\u{1f110}', '\u{1f12e}'), ('\u{1f130}', '\u{1f16b}'), ('\u{1f170}', - '\u{1f1ac}'), ('\u{1f1e6}', '\u{1f202}'), ('\u{1f210}', '\u{1f23b}'), - ('\u{1f240}', '\u{1f248}'), ('\u{1f250}', '\u{1f251}'), ('\u{1f260}', - '\u{1f265}'), ('\u{1f300}', '\u{1f3fa}'), ('\u{1f400}', '\u{1f6d4}'), - ('\u{1f6e0}', '\u{1f6ec}'), ('\u{1f6f0}', '\u{1f6f8}'), ('\u{1f700}', - '\u{1f773}'), ('\u{1f780}', '\u{1f7d4}'), ('\u{1f800}', '\u{1f80b}'), - ('\u{1f810}', '\u{1f847}'), ('\u{1f850}', '\u{1f859}'), ('\u{1f860}', - '\u{1f887}'), ('\u{1f890}', '\u{1f8ad}'), ('\u{1f900}', '\u{1f90b}'), - ('\u{1f910}', '\u{1f93e}'), ('\u{1f940}', '\u{1f94c}'), ('\u{1f950}', - '\u{1f96b}'), ('\u{1f980}', '\u{1f997}'), ('\u{1f9c0}', '\u{1f9c0}'), - ('\u{1f9d0}', '\u{1f9e6}') - ]; - - pub const Z_table: &'static [(char, char)] = &[ - ('\u{20}', '\u{20}'), ('\u{a0}', '\u{a0}'), ('\u{1680}', '\u{1680}'), - ('\u{2000}', '\u{200a}'), ('\u{2028}', '\u{2029}'), ('\u{202f}', - '\u{202f}'), ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}') - ]; - - pub const Zl_table: &'static [(char, char)] = &[ - ('\u{2028}', '\u{2028}') - ]; - - pub const Zp_table: &'static [(char, char)] = &[ - ('\u{2029}', '\u{2029}') - ]; - - pub const Zs_table: &'static [(char, char)] = &[ - ('\u{20}', '\u{20}'), ('\u{a0}', '\u{a0}'), ('\u{1680}', '\u{1680}'), - ('\u{2000}', '\u{200a}'), ('\u{202f}', '\u{202f}'), ('\u{205f}', - '\u{205f}'), ('\u{3000}', '\u{3000}') - ]; - -} - -pub mod derived_property { - pub const Alphabetic_table: &'static [(char, char)] = &[ - ('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), - ('\u{b5}', '\u{b5}'), ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), - ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{2c1}'), ('\u{2c6}', '\u{2d1}'), - ('\u{2e0}', '\u{2e4}'), ('\u{2ec}', '\u{2ec}'), ('\u{2ee}', '\u{2ee}'), - ('\u{345}', '\u{345}'), ('\u{370}', '\u{374}'), ('\u{376}', '\u{377}'), - ('\u{37a}', '\u{37d}'), ('\u{37f}', '\u{37f}'), ('\u{386}', '\u{386}'), - ('\u{388}', '\u{38a}'), ('\u{38c}', '\u{38c}'), ('\u{38e}', '\u{3a1}'), - ('\u{3a3}', '\u{3f5}'), ('\u{3f7}', '\u{481}'), ('\u{48a}', '\u{52f}'), - ('\u{531}', '\u{556}'), ('\u{559}', '\u{559}'), ('\u{561}', '\u{587}'), - ('\u{5b0}', '\u{5bd}'), ('\u{5bf}', '\u{5bf}'), ('\u{5c1}', '\u{5c2}'), - ('\u{5c4}', '\u{5c5}'), ('\u{5c7}', '\u{5c7}'), ('\u{5d0}', '\u{5ea}'), - ('\u{5f0}', '\u{5f2}'), ('\u{610}', '\u{61a}'), ('\u{620}', '\u{657}'), - ('\u{659}', '\u{65f}'), ('\u{66e}', '\u{6d3}'), ('\u{6d5}', '\u{6dc}'), - ('\u{6e1}', '\u{6e8}'), ('\u{6ed}', '\u{6ef}'), ('\u{6fa}', '\u{6fc}'), - ('\u{6ff}', '\u{6ff}'), ('\u{710}', '\u{73f}'), ('\u{74d}', '\u{7b1}'), - ('\u{7ca}', '\u{7ea}'), ('\u{7f4}', '\u{7f5}'), ('\u{7fa}', '\u{7fa}'), - ('\u{800}', '\u{817}'), ('\u{81a}', '\u{82c}'), ('\u{840}', '\u{858}'), - ('\u{860}', '\u{86a}'), ('\u{8a0}', '\u{8b4}'), ('\u{8b6}', '\u{8bd}'), - ('\u{8d4}', '\u{8df}'), ('\u{8e3}', '\u{8e9}'), ('\u{8f0}', '\u{93b}'), - ('\u{93d}', '\u{94c}'), ('\u{94e}', '\u{950}'), ('\u{955}', '\u{963}'), - ('\u{971}', '\u{983}'), ('\u{985}', '\u{98c}'), ('\u{98f}', '\u{990}'), - ('\u{993}', '\u{9a8}'), ('\u{9aa}', '\u{9b0}'), ('\u{9b2}', '\u{9b2}'), - ('\u{9b6}', '\u{9b9}'), ('\u{9bd}', '\u{9c4}'), ('\u{9c7}', '\u{9c8}'), - ('\u{9cb}', '\u{9cc}'), ('\u{9ce}', '\u{9ce}'), ('\u{9d7}', '\u{9d7}'), - ('\u{9dc}', '\u{9dd}'), ('\u{9df}', '\u{9e3}'), ('\u{9f0}', '\u{9f1}'), - ('\u{9fc}', '\u{9fc}'), ('\u{a01}', '\u{a03}'), ('\u{a05}', '\u{a0a}'), - ('\u{a0f}', '\u{a10}'), ('\u{a13}', '\u{a28}'), ('\u{a2a}', '\u{a30}'), - ('\u{a32}', '\u{a33}'), ('\u{a35}', '\u{a36}'), ('\u{a38}', '\u{a39}'), - ('\u{a3e}', '\u{a42}'), ('\u{a47}', '\u{a48}'), ('\u{a4b}', '\u{a4c}'), - ('\u{a51}', '\u{a51}'), ('\u{a59}', '\u{a5c}'), ('\u{a5e}', '\u{a5e}'), - ('\u{a70}', '\u{a75}'), ('\u{a81}', '\u{a83}'), ('\u{a85}', '\u{a8d}'), - ('\u{a8f}', '\u{a91}'), ('\u{a93}', '\u{aa8}'), ('\u{aaa}', '\u{ab0}'), - ('\u{ab2}', '\u{ab3}'), ('\u{ab5}', '\u{ab9}'), ('\u{abd}', '\u{ac5}'), - ('\u{ac7}', '\u{ac9}'), ('\u{acb}', '\u{acc}'), ('\u{ad0}', '\u{ad0}'), - ('\u{ae0}', '\u{ae3}'), ('\u{af9}', '\u{afc}'), ('\u{b01}', '\u{b03}'), - ('\u{b05}', '\u{b0c}'), ('\u{b0f}', '\u{b10}'), ('\u{b13}', '\u{b28}'), - ('\u{b2a}', '\u{b30}'), ('\u{b32}', '\u{b33}'), ('\u{b35}', '\u{b39}'), - ('\u{b3d}', '\u{b44}'), ('\u{b47}', '\u{b48}'), ('\u{b4b}', '\u{b4c}'), - ('\u{b56}', '\u{b57}'), ('\u{b5c}', '\u{b5d}'), ('\u{b5f}', '\u{b63}'), - ('\u{b71}', '\u{b71}'), ('\u{b82}', '\u{b83}'), ('\u{b85}', '\u{b8a}'), - ('\u{b8e}', '\u{b90}'), ('\u{b92}', '\u{b95}'), ('\u{b99}', '\u{b9a}'), - ('\u{b9c}', '\u{b9c}'), ('\u{b9e}', '\u{b9f}'), ('\u{ba3}', '\u{ba4}'), - ('\u{ba8}', '\u{baa}'), ('\u{bae}', '\u{bb9}'), ('\u{bbe}', '\u{bc2}'), - ('\u{bc6}', '\u{bc8}'), ('\u{bca}', '\u{bcc}'), ('\u{bd0}', '\u{bd0}'), - ('\u{bd7}', '\u{bd7}'), ('\u{c00}', '\u{c03}'), ('\u{c05}', '\u{c0c}'), - ('\u{c0e}', '\u{c10}'), ('\u{c12}', '\u{c28}'), ('\u{c2a}', '\u{c39}'), - ('\u{c3d}', '\u{c44}'), ('\u{c46}', '\u{c48}'), ('\u{c4a}', '\u{c4c}'), - ('\u{c55}', '\u{c56}'), ('\u{c58}', '\u{c5a}'), ('\u{c60}', '\u{c63}'), - ('\u{c80}', '\u{c83}'), ('\u{c85}', '\u{c8c}'), ('\u{c8e}', '\u{c90}'), - ('\u{c92}', '\u{ca8}'), ('\u{caa}', '\u{cb3}'), ('\u{cb5}', '\u{cb9}'), - ('\u{cbd}', '\u{cc4}'), ('\u{cc6}', '\u{cc8}'), ('\u{cca}', '\u{ccc}'), - ('\u{cd5}', '\u{cd6}'), ('\u{cde}', '\u{cde}'), ('\u{ce0}', '\u{ce3}'), - ('\u{cf1}', '\u{cf2}'), ('\u{d00}', '\u{d03}'), ('\u{d05}', '\u{d0c}'), - ('\u{d0e}', '\u{d10}'), ('\u{d12}', '\u{d3a}'), ('\u{d3d}', '\u{d44}'), - ('\u{d46}', '\u{d48}'), ('\u{d4a}', '\u{d4c}'), ('\u{d4e}', '\u{d4e}'), - ('\u{d54}', '\u{d57}'), ('\u{d5f}', '\u{d63}'), ('\u{d7a}', '\u{d7f}'), - ('\u{d82}', '\u{d83}'), ('\u{d85}', '\u{d96}'), ('\u{d9a}', '\u{db1}'), - ('\u{db3}', '\u{dbb}'), ('\u{dbd}', '\u{dbd}'), ('\u{dc0}', '\u{dc6}'), - ('\u{dcf}', '\u{dd4}'), ('\u{dd6}', '\u{dd6}'), ('\u{dd8}', '\u{ddf}'), - ('\u{df2}', '\u{df3}'), ('\u{e01}', '\u{e3a}'), ('\u{e40}', '\u{e46}'), - ('\u{e4d}', '\u{e4d}'), ('\u{e81}', '\u{e82}'), ('\u{e84}', '\u{e84}'), - ('\u{e87}', '\u{e88}'), ('\u{e8a}', '\u{e8a}'), ('\u{e8d}', '\u{e8d}'), - ('\u{e94}', '\u{e97}'), ('\u{e99}', '\u{e9f}'), ('\u{ea1}', '\u{ea3}'), - ('\u{ea5}', '\u{ea5}'), ('\u{ea7}', '\u{ea7}'), ('\u{eaa}', '\u{eab}'), - ('\u{ead}', '\u{eb9}'), ('\u{ebb}', '\u{ebd}'), ('\u{ec0}', '\u{ec4}'), - ('\u{ec6}', '\u{ec6}'), ('\u{ecd}', '\u{ecd}'), ('\u{edc}', '\u{edf}'), - ('\u{f00}', '\u{f00}'), ('\u{f40}', '\u{f47}'), ('\u{f49}', '\u{f6c}'), - ('\u{f71}', '\u{f81}'), ('\u{f88}', '\u{f97}'), ('\u{f99}', '\u{fbc}'), - ('\u{1000}', '\u{1036}'), ('\u{1038}', '\u{1038}'), ('\u{103b}', - '\u{103f}'), ('\u{1050}', '\u{1062}'), ('\u{1065}', '\u{1068}'), - ('\u{106e}', '\u{1086}'), ('\u{108e}', '\u{108e}'), ('\u{109c}', - '\u{109d}'), ('\u{10a0}', '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), - ('\u{10cd}', '\u{10cd}'), ('\u{10d0}', '\u{10fa}'), ('\u{10fc}', - '\u{1248}'), ('\u{124a}', '\u{124d}'), ('\u{1250}', '\u{1256}'), - ('\u{1258}', '\u{1258}'), ('\u{125a}', '\u{125d}'), ('\u{1260}', - '\u{1288}'), ('\u{128a}', '\u{128d}'), ('\u{1290}', '\u{12b0}'), - ('\u{12b2}', '\u{12b5}'), ('\u{12b8}', '\u{12be}'), ('\u{12c0}', - '\u{12c0}'), ('\u{12c2}', '\u{12c5}'), ('\u{12c8}', '\u{12d6}'), - ('\u{12d8}', '\u{1310}'), ('\u{1312}', '\u{1315}'), ('\u{1318}', - '\u{135a}'), ('\u{135f}', '\u{135f}'), ('\u{1380}', '\u{138f}'), - ('\u{13a0}', '\u{13f5}'), ('\u{13f8}', '\u{13fd}'), ('\u{1401}', - '\u{166c}'), ('\u{166f}', '\u{167f}'), ('\u{1681}', '\u{169a}'), - ('\u{16a0}', '\u{16ea}'), ('\u{16ee}', '\u{16f8}'), ('\u{1700}', - '\u{170c}'), ('\u{170e}', '\u{1713}'), ('\u{1720}', '\u{1733}'), - ('\u{1740}', '\u{1753}'), ('\u{1760}', '\u{176c}'), ('\u{176e}', - '\u{1770}'), ('\u{1772}', '\u{1773}'), ('\u{1780}', '\u{17b3}'), - ('\u{17b6}', '\u{17c8}'), ('\u{17d7}', '\u{17d7}'), ('\u{17dc}', - '\u{17dc}'), ('\u{1820}', '\u{1877}'), ('\u{1880}', '\u{18aa}'), - ('\u{18b0}', '\u{18f5}'), ('\u{1900}', '\u{191e}'), ('\u{1920}', - '\u{192b}'), ('\u{1930}', '\u{1938}'), ('\u{1950}', '\u{196d}'), - ('\u{1970}', '\u{1974}'), ('\u{1980}', '\u{19ab}'), ('\u{19b0}', - '\u{19c9}'), ('\u{1a00}', '\u{1a1b}'), ('\u{1a20}', '\u{1a5e}'), - ('\u{1a61}', '\u{1a74}'), ('\u{1aa7}', '\u{1aa7}'), ('\u{1b00}', - '\u{1b33}'), ('\u{1b35}', '\u{1b43}'), ('\u{1b45}', '\u{1b4b}'), - ('\u{1b80}', '\u{1ba9}'), ('\u{1bac}', '\u{1baf}'), ('\u{1bba}', - '\u{1be5}'), ('\u{1be7}', '\u{1bf1}'), ('\u{1c00}', '\u{1c35}'), - ('\u{1c4d}', '\u{1c4f}'), ('\u{1c5a}', '\u{1c7d}'), ('\u{1c80}', - '\u{1c88}'), ('\u{1ce9}', '\u{1cec}'), ('\u{1cee}', '\u{1cf3}'), - ('\u{1cf5}', '\u{1cf6}'), ('\u{1d00}', '\u{1dbf}'), ('\u{1de7}', - '\u{1df4}'), ('\u{1e00}', '\u{1f15}'), ('\u{1f18}', '\u{1f1d}'), - ('\u{1f20}', '\u{1f45}'), ('\u{1f48}', '\u{1f4d}'), ('\u{1f50}', - '\u{1f57}'), ('\u{1f59}', '\u{1f59}'), ('\u{1f5b}', '\u{1f5b}'), - ('\u{1f5d}', '\u{1f5d}'), ('\u{1f5f}', '\u{1f7d}'), ('\u{1f80}', - '\u{1fb4}'), ('\u{1fb6}', '\u{1fbc}'), ('\u{1fbe}', '\u{1fbe}'), - ('\u{1fc2}', '\u{1fc4}'), ('\u{1fc6}', '\u{1fcc}'), ('\u{1fd0}', - '\u{1fd3}'), ('\u{1fd6}', '\u{1fdb}'), ('\u{1fe0}', '\u{1fec}'), - ('\u{1ff2}', '\u{1ff4}'), ('\u{1ff6}', '\u{1ffc}'), ('\u{2071}', - '\u{2071}'), ('\u{207f}', '\u{207f}'), ('\u{2090}', '\u{209c}'), - ('\u{2102}', '\u{2102}'), ('\u{2107}', '\u{2107}'), ('\u{210a}', - '\u{2113}'), ('\u{2115}', '\u{2115}'), ('\u{2119}', '\u{211d}'), - ('\u{2124}', '\u{2124}'), ('\u{2126}', '\u{2126}'), ('\u{2128}', - '\u{2128}'), ('\u{212a}', '\u{212d}'), ('\u{212f}', '\u{2139}'), - ('\u{213c}', '\u{213f}'), ('\u{2145}', '\u{2149}'), ('\u{214e}', - '\u{214e}'), ('\u{2160}', '\u{2188}'), ('\u{24b6}', '\u{24e9}'), - ('\u{2c00}', '\u{2c2e}'), ('\u{2c30}', '\u{2c5e}'), ('\u{2c60}', - '\u{2ce4}'), ('\u{2ceb}', '\u{2cee}'), ('\u{2cf2}', '\u{2cf3}'), - ('\u{2d00}', '\u{2d25}'), ('\u{2d27}', '\u{2d27}'), ('\u{2d2d}', - '\u{2d2d}'), ('\u{2d30}', '\u{2d67}'), ('\u{2d6f}', '\u{2d6f}'), - ('\u{2d80}', '\u{2d96}'), ('\u{2da0}', '\u{2da6}'), ('\u{2da8}', - '\u{2dae}'), ('\u{2db0}', '\u{2db6}'), ('\u{2db8}', '\u{2dbe}'), - ('\u{2dc0}', '\u{2dc6}'), ('\u{2dc8}', '\u{2dce}'), ('\u{2dd0}', - '\u{2dd6}'), ('\u{2dd8}', '\u{2dde}'), ('\u{2de0}', '\u{2dff}'), - ('\u{2e2f}', '\u{2e2f}'), ('\u{3005}', '\u{3007}'), ('\u{3021}', - '\u{3029}'), ('\u{3031}', '\u{3035}'), ('\u{3038}', '\u{303c}'), - ('\u{3041}', '\u{3096}'), ('\u{309d}', '\u{309f}'), ('\u{30a1}', - '\u{30fa}'), ('\u{30fc}', '\u{30ff}'), ('\u{3105}', '\u{312e}'), - ('\u{3131}', '\u{318e}'), ('\u{31a0}', '\u{31ba}'), ('\u{31f0}', - '\u{31ff}'), ('\u{3400}', '\u{4db5}'), ('\u{4e00}', '\u{9fea}'), - ('\u{a000}', '\u{a48c}'), ('\u{a4d0}', '\u{a4fd}'), ('\u{a500}', - '\u{a60c}'), ('\u{a610}', '\u{a61f}'), ('\u{a62a}', '\u{a62b}'), - ('\u{a640}', '\u{a66e}'), ('\u{a674}', '\u{a67b}'), ('\u{a67f}', - '\u{a6ef}'), ('\u{a717}', '\u{a71f}'), ('\u{a722}', '\u{a788}'), - ('\u{a78b}', '\u{a7ae}'), ('\u{a7b0}', '\u{a7b7}'), ('\u{a7f7}', - '\u{a801}'), ('\u{a803}', '\u{a805}'), ('\u{a807}', '\u{a80a}'), - ('\u{a80c}', '\u{a827}'), ('\u{a840}', '\u{a873}'), ('\u{a880}', - '\u{a8c3}'), ('\u{a8c5}', '\u{a8c5}'), ('\u{a8f2}', '\u{a8f7}'), - ('\u{a8fb}', '\u{a8fb}'), ('\u{a8fd}', '\u{a8fd}'), ('\u{a90a}', - '\u{a92a}'), ('\u{a930}', '\u{a952}'), ('\u{a960}', '\u{a97c}'), - ('\u{a980}', '\u{a9b2}'), ('\u{a9b4}', '\u{a9bf}'), ('\u{a9cf}', - '\u{a9cf}'), ('\u{a9e0}', '\u{a9e4}'), ('\u{a9e6}', '\u{a9ef}'), - ('\u{a9fa}', '\u{a9fe}'), ('\u{aa00}', '\u{aa36}'), ('\u{aa40}', - '\u{aa4d}'), ('\u{aa60}', '\u{aa76}'), ('\u{aa7a}', '\u{aa7a}'), - ('\u{aa7e}', '\u{aabe}'), ('\u{aac0}', '\u{aac0}'), ('\u{aac2}', - '\u{aac2}'), ('\u{aadb}', '\u{aadd}'), ('\u{aae0}', '\u{aaef}'), - ('\u{aaf2}', '\u{aaf5}'), ('\u{ab01}', '\u{ab06}'), ('\u{ab09}', - '\u{ab0e}'), ('\u{ab11}', '\u{ab16}'), ('\u{ab20}', '\u{ab26}'), - ('\u{ab28}', '\u{ab2e}'), ('\u{ab30}', '\u{ab5a}'), ('\u{ab5c}', - '\u{ab65}'), ('\u{ab70}', '\u{abea}'), ('\u{ac00}', '\u{d7a3}'), - ('\u{d7b0}', '\u{d7c6}'), ('\u{d7cb}', '\u{d7fb}'), ('\u{f900}', - '\u{fa6d}'), ('\u{fa70}', '\u{fad9}'), ('\u{fb00}', '\u{fb06}'), - ('\u{fb13}', '\u{fb17}'), ('\u{fb1d}', '\u{fb28}'), ('\u{fb2a}', - '\u{fb36}'), ('\u{fb38}', '\u{fb3c}'), ('\u{fb3e}', '\u{fb3e}'), - ('\u{fb40}', '\u{fb41}'), ('\u{fb43}', '\u{fb44}'), ('\u{fb46}', - '\u{fbb1}'), ('\u{fbd3}', '\u{fd3d}'), ('\u{fd50}', '\u{fd8f}'), - ('\u{fd92}', '\u{fdc7}'), ('\u{fdf0}', '\u{fdfb}'), ('\u{fe70}', - '\u{fe74}'), ('\u{fe76}', '\u{fefc}'), ('\u{ff21}', '\u{ff3a}'), - ('\u{ff41}', '\u{ff5a}'), ('\u{ff66}', '\u{ffbe}'), ('\u{ffc2}', - '\u{ffc7}'), ('\u{ffca}', '\u{ffcf}'), ('\u{ffd2}', '\u{ffd7}'), - ('\u{ffda}', '\u{ffdc}'), ('\u{10000}', '\u{1000b}'), ('\u{1000d}', - '\u{10026}'), ('\u{10028}', '\u{1003a}'), ('\u{1003c}', '\u{1003d}'), - ('\u{1003f}', '\u{1004d}'), ('\u{10050}', '\u{1005d}'), ('\u{10080}', - '\u{100fa}'), ('\u{10140}', '\u{10174}'), ('\u{10280}', '\u{1029c}'), - ('\u{102a0}', '\u{102d0}'), ('\u{10300}', '\u{1031f}'), ('\u{1032d}', - '\u{1034a}'), ('\u{10350}', '\u{1037a}'), ('\u{10380}', '\u{1039d}'), - ('\u{103a0}', '\u{103c3}'), ('\u{103c8}', '\u{103cf}'), ('\u{103d1}', - '\u{103d5}'), ('\u{10400}', '\u{1049d}'), ('\u{104b0}', '\u{104d3}'), - ('\u{104d8}', '\u{104fb}'), ('\u{10500}', '\u{10527}'), ('\u{10530}', - '\u{10563}'), ('\u{10600}', '\u{10736}'), ('\u{10740}', '\u{10755}'), - ('\u{10760}', '\u{10767}'), ('\u{10800}', '\u{10805}'), ('\u{10808}', - '\u{10808}'), ('\u{1080a}', '\u{10835}'), ('\u{10837}', '\u{10838}'), - ('\u{1083c}', '\u{1083c}'), ('\u{1083f}', '\u{10855}'), ('\u{10860}', - '\u{10876}'), ('\u{10880}', '\u{1089e}'), ('\u{108e0}', '\u{108f2}'), - ('\u{108f4}', '\u{108f5}'), ('\u{10900}', '\u{10915}'), ('\u{10920}', - '\u{10939}'), ('\u{10980}', '\u{109b7}'), ('\u{109be}', '\u{109bf}'), - ('\u{10a00}', '\u{10a03}'), ('\u{10a05}', '\u{10a06}'), ('\u{10a0c}', - '\u{10a13}'), ('\u{10a15}', '\u{10a17}'), ('\u{10a19}', '\u{10a33}'), - ('\u{10a60}', '\u{10a7c}'), ('\u{10a80}', '\u{10a9c}'), ('\u{10ac0}', - '\u{10ac7}'), ('\u{10ac9}', '\u{10ae4}'), ('\u{10b00}', '\u{10b35}'), - ('\u{10b40}', '\u{10b55}'), ('\u{10b60}', '\u{10b72}'), ('\u{10b80}', - '\u{10b91}'), ('\u{10c00}', '\u{10c48}'), ('\u{10c80}', '\u{10cb2}'), - ('\u{10cc0}', '\u{10cf2}'), ('\u{11000}', '\u{11045}'), ('\u{11082}', - '\u{110b8}'), ('\u{110d0}', '\u{110e8}'), ('\u{11100}', '\u{11132}'), - ('\u{11150}', '\u{11172}'), ('\u{11176}', '\u{11176}'), ('\u{11180}', - '\u{111bf}'), ('\u{111c1}', '\u{111c4}'), ('\u{111da}', '\u{111da}'), - ('\u{111dc}', '\u{111dc}'), ('\u{11200}', '\u{11211}'), ('\u{11213}', - '\u{11234}'), ('\u{11237}', '\u{11237}'), ('\u{1123e}', '\u{1123e}'), - ('\u{11280}', '\u{11286}'), ('\u{11288}', '\u{11288}'), ('\u{1128a}', - '\u{1128d}'), ('\u{1128f}', '\u{1129d}'), ('\u{1129f}', '\u{112a8}'), - ('\u{112b0}', '\u{112e8}'), ('\u{11300}', '\u{11303}'), ('\u{11305}', - '\u{1130c}'), ('\u{1130f}', '\u{11310}'), ('\u{11313}', '\u{11328}'), - ('\u{1132a}', '\u{11330}'), ('\u{11332}', '\u{11333}'), ('\u{11335}', - '\u{11339}'), ('\u{1133d}', '\u{11344}'), ('\u{11347}', '\u{11348}'), - ('\u{1134b}', '\u{1134c}'), ('\u{11350}', '\u{11350}'), ('\u{11357}', - '\u{11357}'), ('\u{1135d}', '\u{11363}'), ('\u{11400}', '\u{11441}'), - ('\u{11443}', '\u{11445}'), ('\u{11447}', '\u{1144a}'), ('\u{11480}', - '\u{114c1}'), ('\u{114c4}', '\u{114c5}'), ('\u{114c7}', '\u{114c7}'), - ('\u{11580}', '\u{115b5}'), ('\u{115b8}', '\u{115be}'), ('\u{115d8}', - '\u{115dd}'), ('\u{11600}', '\u{1163e}'), ('\u{11640}', '\u{11640}'), - ('\u{11644}', '\u{11644}'), ('\u{11680}', '\u{116b5}'), ('\u{11700}', - '\u{11719}'), ('\u{1171d}', '\u{1172a}'), ('\u{118a0}', '\u{118df}'), - ('\u{118ff}', '\u{118ff}'), ('\u{11a00}', '\u{11a32}'), ('\u{11a35}', - '\u{11a3e}'), ('\u{11a50}', '\u{11a83}'), ('\u{11a86}', '\u{11a97}'), - ('\u{11ac0}', '\u{11af8}'), ('\u{11c00}', '\u{11c08}'), ('\u{11c0a}', - '\u{11c36}'), ('\u{11c38}', '\u{11c3e}'), ('\u{11c40}', '\u{11c40}'), - ('\u{11c72}', '\u{11c8f}'), ('\u{11c92}', '\u{11ca7}'), ('\u{11ca9}', - '\u{11cb6}'), ('\u{11d00}', '\u{11d06}'), ('\u{11d08}', '\u{11d09}'), - ('\u{11d0b}', '\u{11d36}'), ('\u{11d3a}', '\u{11d3a}'), ('\u{11d3c}', - '\u{11d3d}'), ('\u{11d3f}', '\u{11d41}'), ('\u{11d43}', '\u{11d43}'), - ('\u{11d46}', '\u{11d47}'), ('\u{12000}', '\u{12399}'), ('\u{12400}', - '\u{1246e}'), ('\u{12480}', '\u{12543}'), ('\u{13000}', '\u{1342e}'), - ('\u{14400}', '\u{14646}'), ('\u{16800}', '\u{16a38}'), ('\u{16a40}', - '\u{16a5e}'), ('\u{16ad0}', '\u{16aed}'), ('\u{16b00}', '\u{16b36}'), - ('\u{16b40}', '\u{16b43}'), ('\u{16b63}', '\u{16b77}'), ('\u{16b7d}', - '\u{16b8f}'), ('\u{16f00}', '\u{16f44}'), ('\u{16f50}', '\u{16f7e}'), - ('\u{16f93}', '\u{16f9f}'), ('\u{16fe0}', '\u{16fe1}'), ('\u{17000}', - '\u{187ec}'), ('\u{18800}', '\u{18af2}'), ('\u{1b000}', '\u{1b11e}'), - ('\u{1b170}', '\u{1b2fb}'), ('\u{1bc00}', '\u{1bc6a}'), ('\u{1bc70}', - '\u{1bc7c}'), ('\u{1bc80}', '\u{1bc88}'), ('\u{1bc90}', '\u{1bc99}'), - ('\u{1bc9e}', '\u{1bc9e}'), ('\u{1d400}', '\u{1d454}'), ('\u{1d456}', - '\u{1d49c}'), ('\u{1d49e}', '\u{1d49f}'), ('\u{1d4a2}', '\u{1d4a2}'), - ('\u{1d4a5}', '\u{1d4a6}'), ('\u{1d4a9}', '\u{1d4ac}'), ('\u{1d4ae}', - '\u{1d4b9}'), ('\u{1d4bb}', '\u{1d4bb}'), ('\u{1d4bd}', '\u{1d4c3}'), - ('\u{1d4c5}', '\u{1d505}'), ('\u{1d507}', '\u{1d50a}'), ('\u{1d50d}', - '\u{1d514}'), ('\u{1d516}', '\u{1d51c}'), ('\u{1d51e}', '\u{1d539}'), - ('\u{1d53b}', '\u{1d53e}'), ('\u{1d540}', '\u{1d544}'), ('\u{1d546}', - '\u{1d546}'), ('\u{1d54a}', '\u{1d550}'), ('\u{1d552}', '\u{1d6a5}'), - ('\u{1d6a8}', '\u{1d6c0}'), ('\u{1d6c2}', '\u{1d6da}'), ('\u{1d6dc}', - '\u{1d6fa}'), ('\u{1d6fc}', '\u{1d714}'), ('\u{1d716}', '\u{1d734}'), - ('\u{1d736}', '\u{1d74e}'), ('\u{1d750}', '\u{1d76e}'), ('\u{1d770}', - '\u{1d788}'), ('\u{1d78a}', '\u{1d7a8}'), ('\u{1d7aa}', '\u{1d7c2}'), - ('\u{1d7c4}', '\u{1d7cb}'), ('\u{1e000}', '\u{1e006}'), ('\u{1e008}', - '\u{1e018}'), ('\u{1e01b}', '\u{1e021}'), ('\u{1e023}', '\u{1e024}'), - ('\u{1e026}', '\u{1e02a}'), ('\u{1e800}', '\u{1e8c4}'), ('\u{1e900}', - '\u{1e943}'), ('\u{1e947}', '\u{1e947}'), ('\u{1ee00}', '\u{1ee03}'), - ('\u{1ee05}', '\u{1ee1f}'), ('\u{1ee21}', '\u{1ee22}'), ('\u{1ee24}', - '\u{1ee24}'), ('\u{1ee27}', '\u{1ee27}'), ('\u{1ee29}', '\u{1ee32}'), - ('\u{1ee34}', '\u{1ee37}'), ('\u{1ee39}', '\u{1ee39}'), ('\u{1ee3b}', - '\u{1ee3b}'), ('\u{1ee42}', '\u{1ee42}'), ('\u{1ee47}', '\u{1ee47}'), - ('\u{1ee49}', '\u{1ee49}'), ('\u{1ee4b}', '\u{1ee4b}'), ('\u{1ee4d}', - '\u{1ee4f}'), ('\u{1ee51}', '\u{1ee52}'), ('\u{1ee54}', '\u{1ee54}'), - ('\u{1ee57}', '\u{1ee57}'), ('\u{1ee59}', '\u{1ee59}'), ('\u{1ee5b}', - '\u{1ee5b}'), ('\u{1ee5d}', '\u{1ee5d}'), ('\u{1ee5f}', '\u{1ee5f}'), - ('\u{1ee61}', '\u{1ee62}'), ('\u{1ee64}', '\u{1ee64}'), ('\u{1ee67}', - '\u{1ee6a}'), ('\u{1ee6c}', '\u{1ee72}'), ('\u{1ee74}', '\u{1ee77}'), - ('\u{1ee79}', '\u{1ee7c}'), ('\u{1ee7e}', '\u{1ee7e}'), ('\u{1ee80}', - '\u{1ee89}'), ('\u{1ee8b}', '\u{1ee9b}'), ('\u{1eea1}', '\u{1eea3}'), - ('\u{1eea5}', '\u{1eea9}'), ('\u{1eeab}', '\u{1eebb}'), ('\u{1f130}', - '\u{1f149}'), ('\u{1f150}', '\u{1f169}'), ('\u{1f170}', '\u{1f189}'), - ('\u{20000}', '\u{2a6d6}'), ('\u{2a700}', '\u{2b734}'), ('\u{2b740}', - '\u{2b81d}'), ('\u{2b820}', '\u{2cea1}'), ('\u{2ceb0}', '\u{2ebe0}'), - ('\u{2f800}', '\u{2fa1d}') - ]; - - pub const Default_Ignorable_Code_Point_table: &'static [(char, char)] = &[ - ('\u{ad}', '\u{ad}'), ('\u{34f}', '\u{34f}'), ('\u{61c}', '\u{61c}'), - ('\u{115f}', '\u{1160}'), ('\u{17b4}', '\u{17b5}'), ('\u{180b}', - '\u{180e}'), ('\u{200b}', '\u{200f}'), ('\u{202a}', '\u{202e}'), - ('\u{2060}', '\u{206f}'), ('\u{3164}', '\u{3164}'), ('\u{fe00}', - '\u{fe0f}'), ('\u{feff}', '\u{feff}'), ('\u{ffa0}', '\u{ffa0}'), - ('\u{fff0}', '\u{fff8}'), ('\u{1bca0}', '\u{1bca3}'), ('\u{1d173}', - '\u{1d17a}'), ('\u{e0000}', '\u{e0fff}') - ]; - - pub const Grapheme_Extend_table: &'static [(char, char)] = &[ - ('\u{300}', '\u{36f}'), ('\u{483}', '\u{489}'), ('\u{591}', '\u{5bd}'), - ('\u{5bf}', '\u{5bf}'), ('\u{5c1}', '\u{5c2}'), ('\u{5c4}', '\u{5c5}'), - ('\u{5c7}', '\u{5c7}'), ('\u{610}', '\u{61a}'), ('\u{64b}', '\u{65f}'), - ('\u{670}', '\u{670}'), ('\u{6d6}', '\u{6dc}'), ('\u{6df}', '\u{6e4}'), - ('\u{6e7}', '\u{6e8}'), ('\u{6ea}', '\u{6ed}'), ('\u{711}', '\u{711}'), - ('\u{730}', '\u{74a}'), ('\u{7a6}', '\u{7b0}'), ('\u{7eb}', '\u{7f3}'), - ('\u{816}', '\u{819}'), ('\u{81b}', '\u{823}'), ('\u{825}', '\u{827}'), - ('\u{829}', '\u{82d}'), ('\u{859}', '\u{85b}'), ('\u{8d4}', '\u{8e1}'), - ('\u{8e3}', '\u{902}'), ('\u{93a}', '\u{93a}'), ('\u{93c}', '\u{93c}'), - ('\u{941}', '\u{948}'), ('\u{94d}', '\u{94d}'), ('\u{951}', '\u{957}'), - ('\u{962}', '\u{963}'), ('\u{981}', '\u{981}'), ('\u{9bc}', '\u{9bc}'), - ('\u{9be}', '\u{9be}'), ('\u{9c1}', '\u{9c4}'), ('\u{9cd}', '\u{9cd}'), - ('\u{9d7}', '\u{9d7}'), ('\u{9e2}', '\u{9e3}'), ('\u{a01}', '\u{a02}'), - ('\u{a3c}', '\u{a3c}'), ('\u{a41}', '\u{a42}'), ('\u{a47}', '\u{a48}'), - ('\u{a4b}', '\u{a4d}'), ('\u{a51}', '\u{a51}'), ('\u{a70}', '\u{a71}'), - ('\u{a75}', '\u{a75}'), ('\u{a81}', '\u{a82}'), ('\u{abc}', '\u{abc}'), - ('\u{ac1}', '\u{ac5}'), ('\u{ac7}', '\u{ac8}'), ('\u{acd}', '\u{acd}'), - ('\u{ae2}', '\u{ae3}'), ('\u{afa}', '\u{aff}'), ('\u{b01}', '\u{b01}'), - ('\u{b3c}', '\u{b3c}'), ('\u{b3e}', '\u{b3f}'), ('\u{b41}', '\u{b44}'), - ('\u{b4d}', '\u{b4d}'), ('\u{b56}', '\u{b57}'), ('\u{b62}', '\u{b63}'), - ('\u{b82}', '\u{b82}'), ('\u{bbe}', '\u{bbe}'), ('\u{bc0}', '\u{bc0}'), - ('\u{bcd}', '\u{bcd}'), ('\u{bd7}', '\u{bd7}'), ('\u{c00}', '\u{c00}'), - ('\u{c3e}', '\u{c40}'), ('\u{c46}', '\u{c48}'), ('\u{c4a}', '\u{c4d}'), - ('\u{c55}', '\u{c56}'), ('\u{c62}', '\u{c63}'), ('\u{c81}', '\u{c81}'), - ('\u{cbc}', '\u{cbc}'), ('\u{cbf}', '\u{cbf}'), ('\u{cc2}', '\u{cc2}'), - ('\u{cc6}', '\u{cc6}'), ('\u{ccc}', '\u{ccd}'), ('\u{cd5}', '\u{cd6}'), - ('\u{ce2}', '\u{ce3}'), ('\u{d00}', '\u{d01}'), ('\u{d3b}', '\u{d3c}'), - ('\u{d3e}', '\u{d3e}'), ('\u{d41}', '\u{d44}'), ('\u{d4d}', '\u{d4d}'), - ('\u{d57}', '\u{d57}'), ('\u{d62}', '\u{d63}'), ('\u{dca}', '\u{dca}'), - ('\u{dcf}', '\u{dcf}'), ('\u{dd2}', '\u{dd4}'), ('\u{dd6}', '\u{dd6}'), - ('\u{ddf}', '\u{ddf}'), ('\u{e31}', '\u{e31}'), ('\u{e34}', '\u{e3a}'), - ('\u{e47}', '\u{e4e}'), ('\u{eb1}', '\u{eb1}'), ('\u{eb4}', '\u{eb9}'), - ('\u{ebb}', '\u{ebc}'), ('\u{ec8}', '\u{ecd}'), ('\u{f18}', '\u{f19}'), - ('\u{f35}', '\u{f35}'), ('\u{f37}', '\u{f37}'), ('\u{f39}', '\u{f39}'), - ('\u{f71}', '\u{f7e}'), ('\u{f80}', '\u{f84}'), ('\u{f86}', '\u{f87}'), - ('\u{f8d}', '\u{f97}'), ('\u{f99}', '\u{fbc}'), ('\u{fc6}', '\u{fc6}'), - ('\u{102d}', '\u{1030}'), ('\u{1032}', '\u{1037}'), ('\u{1039}', - '\u{103a}'), ('\u{103d}', '\u{103e}'), ('\u{1058}', '\u{1059}'), - ('\u{105e}', '\u{1060}'), ('\u{1071}', '\u{1074}'), ('\u{1082}', - '\u{1082}'), ('\u{1085}', '\u{1086}'), ('\u{108d}', '\u{108d}'), - ('\u{109d}', '\u{109d}'), ('\u{135d}', '\u{135f}'), ('\u{1712}', - '\u{1714}'), ('\u{1732}', '\u{1734}'), ('\u{1752}', '\u{1753}'), - ('\u{1772}', '\u{1773}'), ('\u{17b4}', '\u{17b5}'), ('\u{17b7}', - '\u{17bd}'), ('\u{17c6}', '\u{17c6}'), ('\u{17c9}', '\u{17d3}'), - ('\u{17dd}', '\u{17dd}'), ('\u{180b}', '\u{180d}'), ('\u{1885}', - '\u{1886}'), ('\u{18a9}', '\u{18a9}'), ('\u{1920}', '\u{1922}'), - ('\u{1927}', '\u{1928}'), ('\u{1932}', '\u{1932}'), ('\u{1939}', - '\u{193b}'), ('\u{1a17}', '\u{1a18}'), ('\u{1a1b}', '\u{1a1b}'), - ('\u{1a56}', '\u{1a56}'), ('\u{1a58}', '\u{1a5e}'), ('\u{1a60}', - '\u{1a60}'), ('\u{1a62}', '\u{1a62}'), ('\u{1a65}', '\u{1a6c}'), - ('\u{1a73}', '\u{1a7c}'), ('\u{1a7f}', '\u{1a7f}'), ('\u{1ab0}', - '\u{1abe}'), ('\u{1b00}', '\u{1b03}'), ('\u{1b34}', '\u{1b34}'), - ('\u{1b36}', '\u{1b3a}'), ('\u{1b3c}', '\u{1b3c}'), ('\u{1b42}', - '\u{1b42}'), ('\u{1b6b}', '\u{1b73}'), ('\u{1b80}', '\u{1b81}'), - ('\u{1ba2}', '\u{1ba5}'), ('\u{1ba8}', '\u{1ba9}'), ('\u{1bab}', - '\u{1bad}'), ('\u{1be6}', '\u{1be6}'), ('\u{1be8}', '\u{1be9}'), - ('\u{1bed}', '\u{1bed}'), ('\u{1bef}', '\u{1bf1}'), ('\u{1c2c}', - '\u{1c33}'), ('\u{1c36}', '\u{1c37}'), ('\u{1cd0}', '\u{1cd2}'), - ('\u{1cd4}', '\u{1ce0}'), ('\u{1ce2}', '\u{1ce8}'), ('\u{1ced}', - '\u{1ced}'), ('\u{1cf4}', '\u{1cf4}'), ('\u{1cf8}', '\u{1cf9}'), - ('\u{1dc0}', '\u{1df9}'), ('\u{1dfb}', '\u{1dff}'), ('\u{200c}', - '\u{200c}'), ('\u{20d0}', '\u{20f0}'), ('\u{2cef}', '\u{2cf1}'), - ('\u{2d7f}', '\u{2d7f}'), ('\u{2de0}', '\u{2dff}'), ('\u{302a}', - '\u{302f}'), ('\u{3099}', '\u{309a}'), ('\u{a66f}', '\u{a672}'), - ('\u{a674}', '\u{a67d}'), ('\u{a69e}', '\u{a69f}'), ('\u{a6f0}', - '\u{a6f1}'), ('\u{a802}', '\u{a802}'), ('\u{a806}', '\u{a806}'), - ('\u{a80b}', '\u{a80b}'), ('\u{a825}', '\u{a826}'), ('\u{a8c4}', - '\u{a8c5}'), ('\u{a8e0}', '\u{a8f1}'), ('\u{a926}', '\u{a92d}'), - ('\u{a947}', '\u{a951}'), ('\u{a980}', '\u{a982}'), ('\u{a9b3}', - '\u{a9b3}'), ('\u{a9b6}', '\u{a9b9}'), ('\u{a9bc}', '\u{a9bc}'), - ('\u{a9e5}', '\u{a9e5}'), ('\u{aa29}', '\u{aa2e}'), ('\u{aa31}', - '\u{aa32}'), ('\u{aa35}', '\u{aa36}'), ('\u{aa43}', '\u{aa43}'), - ('\u{aa4c}', '\u{aa4c}'), ('\u{aa7c}', '\u{aa7c}'), ('\u{aab0}', - '\u{aab0}'), ('\u{aab2}', '\u{aab4}'), ('\u{aab7}', '\u{aab8}'), - ('\u{aabe}', '\u{aabf}'), ('\u{aac1}', '\u{aac1}'), ('\u{aaec}', - '\u{aaed}'), ('\u{aaf6}', '\u{aaf6}'), ('\u{abe5}', '\u{abe5}'), - ('\u{abe8}', '\u{abe8}'), ('\u{abed}', '\u{abed}'), ('\u{fb1e}', - '\u{fb1e}'), ('\u{fe00}', '\u{fe0f}'), ('\u{fe20}', '\u{fe2f}'), - ('\u{ff9e}', '\u{ff9f}'), ('\u{101fd}', '\u{101fd}'), ('\u{102e0}', - '\u{102e0}'), ('\u{10376}', '\u{1037a}'), ('\u{10a01}', '\u{10a03}'), - ('\u{10a05}', '\u{10a06}'), ('\u{10a0c}', '\u{10a0f}'), ('\u{10a38}', - '\u{10a3a}'), ('\u{10a3f}', '\u{10a3f}'), ('\u{10ae5}', '\u{10ae6}'), - ('\u{11001}', '\u{11001}'), ('\u{11038}', '\u{11046}'), ('\u{1107f}', - '\u{11081}'), ('\u{110b3}', '\u{110b6}'), ('\u{110b9}', '\u{110ba}'), - ('\u{11100}', '\u{11102}'), ('\u{11127}', '\u{1112b}'), ('\u{1112d}', - '\u{11134}'), ('\u{11173}', '\u{11173}'), ('\u{11180}', '\u{11181}'), - ('\u{111b6}', '\u{111be}'), ('\u{111ca}', '\u{111cc}'), ('\u{1122f}', - '\u{11231}'), ('\u{11234}', '\u{11234}'), ('\u{11236}', '\u{11237}'), - ('\u{1123e}', '\u{1123e}'), ('\u{112df}', '\u{112df}'), ('\u{112e3}', - '\u{112ea}'), ('\u{11300}', '\u{11301}'), ('\u{1133c}', '\u{1133c}'), - ('\u{1133e}', '\u{1133e}'), ('\u{11340}', '\u{11340}'), ('\u{11357}', - '\u{11357}'), ('\u{11366}', '\u{1136c}'), ('\u{11370}', '\u{11374}'), - ('\u{11438}', '\u{1143f}'), ('\u{11442}', '\u{11444}'), ('\u{11446}', - '\u{11446}'), ('\u{114b0}', '\u{114b0}'), ('\u{114b3}', '\u{114b8}'), - ('\u{114ba}', '\u{114ba}'), ('\u{114bd}', '\u{114bd}'), ('\u{114bf}', - '\u{114c0}'), ('\u{114c2}', '\u{114c3}'), ('\u{115af}', '\u{115af}'), - ('\u{115b2}', '\u{115b5}'), ('\u{115bc}', '\u{115bd}'), ('\u{115bf}', - '\u{115c0}'), ('\u{115dc}', '\u{115dd}'), ('\u{11633}', '\u{1163a}'), - ('\u{1163d}', '\u{1163d}'), ('\u{1163f}', '\u{11640}'), ('\u{116ab}', - '\u{116ab}'), ('\u{116ad}', '\u{116ad}'), ('\u{116b0}', '\u{116b5}'), - ('\u{116b7}', '\u{116b7}'), ('\u{1171d}', '\u{1171f}'), ('\u{11722}', - '\u{11725}'), ('\u{11727}', '\u{1172b}'), ('\u{11a01}', '\u{11a06}'), - ('\u{11a09}', '\u{11a0a}'), ('\u{11a33}', '\u{11a38}'), ('\u{11a3b}', - '\u{11a3e}'), ('\u{11a47}', '\u{11a47}'), ('\u{11a51}', '\u{11a56}'), - ('\u{11a59}', '\u{11a5b}'), ('\u{11a8a}', '\u{11a96}'), ('\u{11a98}', - '\u{11a99}'), ('\u{11c30}', '\u{11c36}'), ('\u{11c38}', '\u{11c3d}'), - ('\u{11c3f}', '\u{11c3f}'), ('\u{11c92}', '\u{11ca7}'), ('\u{11caa}', - '\u{11cb0}'), ('\u{11cb2}', '\u{11cb3}'), ('\u{11cb5}', '\u{11cb6}'), - ('\u{11d31}', '\u{11d36}'), ('\u{11d3a}', '\u{11d3a}'), ('\u{11d3c}', - '\u{11d3d}'), ('\u{11d3f}', '\u{11d45}'), ('\u{11d47}', '\u{11d47}'), - ('\u{16af0}', '\u{16af4}'), ('\u{16b30}', '\u{16b36}'), ('\u{16f8f}', - '\u{16f92}'), ('\u{1bc9d}', '\u{1bc9e}'), ('\u{1d165}', '\u{1d165}'), - ('\u{1d167}', '\u{1d169}'), ('\u{1d16e}', '\u{1d172}'), ('\u{1d17b}', - '\u{1d182}'), ('\u{1d185}', '\u{1d18b}'), ('\u{1d1aa}', '\u{1d1ad}'), - ('\u{1d242}', '\u{1d244}'), ('\u{1da00}', '\u{1da36}'), ('\u{1da3b}', - '\u{1da6c}'), ('\u{1da75}', '\u{1da75}'), ('\u{1da84}', '\u{1da84}'), - ('\u{1da9b}', '\u{1da9f}'), ('\u{1daa1}', '\u{1daaf}'), ('\u{1e000}', - '\u{1e006}'), ('\u{1e008}', '\u{1e018}'), ('\u{1e01b}', '\u{1e021}'), - ('\u{1e023}', '\u{1e024}'), ('\u{1e026}', '\u{1e02a}'), ('\u{1e8d0}', - '\u{1e8d6}'), ('\u{1e944}', '\u{1e94a}'), ('\u{e0020}', '\u{e007f}'), - ('\u{e0100}', '\u{e01ef}') - ]; - - pub const Lowercase_table: &'static [(char, char)] = &[ - ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), - ('\u{ba}', '\u{ba}'), ('\u{df}', '\u{f6}'), ('\u{f8}', '\u{ff}'), - ('\u{101}', '\u{101}'), ('\u{103}', '\u{103}'), ('\u{105}', '\u{105}'), - ('\u{107}', '\u{107}'), ('\u{109}', '\u{109}'), ('\u{10b}', '\u{10b}'), - ('\u{10d}', '\u{10d}'), ('\u{10f}', '\u{10f}'), ('\u{111}', '\u{111}'), - ('\u{113}', '\u{113}'), ('\u{115}', '\u{115}'), ('\u{117}', '\u{117}'), - ('\u{119}', '\u{119}'), ('\u{11b}', '\u{11b}'), ('\u{11d}', '\u{11d}'), - ('\u{11f}', '\u{11f}'), ('\u{121}', '\u{121}'), ('\u{123}', '\u{123}'), - ('\u{125}', '\u{125}'), ('\u{127}', '\u{127}'), ('\u{129}', '\u{129}'), - ('\u{12b}', '\u{12b}'), ('\u{12d}', '\u{12d}'), ('\u{12f}', '\u{12f}'), - ('\u{131}', '\u{131}'), ('\u{133}', '\u{133}'), ('\u{135}', '\u{135}'), - ('\u{137}', '\u{138}'), ('\u{13a}', '\u{13a}'), ('\u{13c}', '\u{13c}'), - ('\u{13e}', '\u{13e}'), ('\u{140}', '\u{140}'), ('\u{142}', '\u{142}'), - ('\u{144}', '\u{144}'), ('\u{146}', '\u{146}'), ('\u{148}', '\u{149}'), - ('\u{14b}', '\u{14b}'), ('\u{14d}', '\u{14d}'), ('\u{14f}', '\u{14f}'), - ('\u{151}', '\u{151}'), ('\u{153}', '\u{153}'), ('\u{155}', '\u{155}'), - ('\u{157}', '\u{157}'), ('\u{159}', '\u{159}'), ('\u{15b}', '\u{15b}'), - ('\u{15d}', '\u{15d}'), ('\u{15f}', '\u{15f}'), ('\u{161}', '\u{161}'), - ('\u{163}', '\u{163}'), ('\u{165}', '\u{165}'), ('\u{167}', '\u{167}'), - ('\u{169}', '\u{169}'), ('\u{16b}', '\u{16b}'), ('\u{16d}', '\u{16d}'), - ('\u{16f}', '\u{16f}'), ('\u{171}', '\u{171}'), ('\u{173}', '\u{173}'), - ('\u{175}', '\u{175}'), ('\u{177}', '\u{177}'), ('\u{17a}', '\u{17a}'), - ('\u{17c}', '\u{17c}'), ('\u{17e}', '\u{180}'), ('\u{183}', '\u{183}'), - ('\u{185}', '\u{185}'), ('\u{188}', '\u{188}'), ('\u{18c}', '\u{18d}'), - ('\u{192}', '\u{192}'), ('\u{195}', '\u{195}'), ('\u{199}', '\u{19b}'), - ('\u{19e}', '\u{19e}'), ('\u{1a1}', '\u{1a1}'), ('\u{1a3}', '\u{1a3}'), - ('\u{1a5}', '\u{1a5}'), ('\u{1a8}', '\u{1a8}'), ('\u{1aa}', '\u{1ab}'), - ('\u{1ad}', '\u{1ad}'), ('\u{1b0}', '\u{1b0}'), ('\u{1b4}', '\u{1b4}'), - ('\u{1b6}', '\u{1b6}'), ('\u{1b9}', '\u{1ba}'), ('\u{1bd}', '\u{1bf}'), - ('\u{1c6}', '\u{1c6}'), ('\u{1c9}', '\u{1c9}'), ('\u{1cc}', '\u{1cc}'), - ('\u{1ce}', '\u{1ce}'), ('\u{1d0}', '\u{1d0}'), ('\u{1d2}', '\u{1d2}'), - ('\u{1d4}', '\u{1d4}'), ('\u{1d6}', '\u{1d6}'), ('\u{1d8}', '\u{1d8}'), - ('\u{1da}', '\u{1da}'), ('\u{1dc}', '\u{1dd}'), ('\u{1df}', '\u{1df}'), - ('\u{1e1}', '\u{1e1}'), ('\u{1e3}', '\u{1e3}'), ('\u{1e5}', '\u{1e5}'), - ('\u{1e7}', '\u{1e7}'), ('\u{1e9}', '\u{1e9}'), ('\u{1eb}', '\u{1eb}'), - ('\u{1ed}', '\u{1ed}'), ('\u{1ef}', '\u{1f0}'), ('\u{1f3}', '\u{1f3}'), - ('\u{1f5}', '\u{1f5}'), ('\u{1f9}', '\u{1f9}'), ('\u{1fb}', '\u{1fb}'), - ('\u{1fd}', '\u{1fd}'), ('\u{1ff}', '\u{1ff}'), ('\u{201}', '\u{201}'), - ('\u{203}', '\u{203}'), ('\u{205}', '\u{205}'), ('\u{207}', '\u{207}'), - ('\u{209}', '\u{209}'), ('\u{20b}', '\u{20b}'), ('\u{20d}', '\u{20d}'), - ('\u{20f}', '\u{20f}'), ('\u{211}', '\u{211}'), ('\u{213}', '\u{213}'), - ('\u{215}', '\u{215}'), ('\u{217}', '\u{217}'), ('\u{219}', '\u{219}'), - ('\u{21b}', '\u{21b}'), ('\u{21d}', '\u{21d}'), ('\u{21f}', '\u{21f}'), - ('\u{221}', '\u{221}'), ('\u{223}', '\u{223}'), ('\u{225}', '\u{225}'), - ('\u{227}', '\u{227}'), ('\u{229}', '\u{229}'), ('\u{22b}', '\u{22b}'), - ('\u{22d}', '\u{22d}'), ('\u{22f}', '\u{22f}'), ('\u{231}', '\u{231}'), - ('\u{233}', '\u{239}'), ('\u{23c}', '\u{23c}'), ('\u{23f}', '\u{240}'), - ('\u{242}', '\u{242}'), ('\u{247}', '\u{247}'), ('\u{249}', '\u{249}'), - ('\u{24b}', '\u{24b}'), ('\u{24d}', '\u{24d}'), ('\u{24f}', '\u{293}'), - ('\u{295}', '\u{2b8}'), ('\u{2c0}', '\u{2c1}'), ('\u{2e0}', '\u{2e4}'), - ('\u{345}', '\u{345}'), ('\u{371}', '\u{371}'), ('\u{373}', '\u{373}'), - ('\u{377}', '\u{377}'), ('\u{37a}', '\u{37d}'), ('\u{390}', '\u{390}'), - ('\u{3ac}', '\u{3ce}'), ('\u{3d0}', '\u{3d1}'), ('\u{3d5}', '\u{3d7}'), - ('\u{3d9}', '\u{3d9}'), ('\u{3db}', '\u{3db}'), ('\u{3dd}', '\u{3dd}'), - ('\u{3df}', '\u{3df}'), ('\u{3e1}', '\u{3e1}'), ('\u{3e3}', '\u{3e3}'), - ('\u{3e5}', '\u{3e5}'), ('\u{3e7}', '\u{3e7}'), ('\u{3e9}', '\u{3e9}'), - ('\u{3eb}', '\u{3eb}'), ('\u{3ed}', '\u{3ed}'), ('\u{3ef}', '\u{3f3}'), - ('\u{3f5}', '\u{3f5}'), ('\u{3f8}', '\u{3f8}'), ('\u{3fb}', '\u{3fc}'), - ('\u{430}', '\u{45f}'), ('\u{461}', '\u{461}'), ('\u{463}', '\u{463}'), - ('\u{465}', '\u{465}'), ('\u{467}', '\u{467}'), ('\u{469}', '\u{469}'), - ('\u{46b}', '\u{46b}'), ('\u{46d}', '\u{46d}'), ('\u{46f}', '\u{46f}'), - ('\u{471}', '\u{471}'), ('\u{473}', '\u{473}'), ('\u{475}', '\u{475}'), - ('\u{477}', '\u{477}'), ('\u{479}', '\u{479}'), ('\u{47b}', '\u{47b}'), - ('\u{47d}', '\u{47d}'), ('\u{47f}', '\u{47f}'), ('\u{481}', '\u{481}'), - ('\u{48b}', '\u{48b}'), ('\u{48d}', '\u{48d}'), ('\u{48f}', '\u{48f}'), - ('\u{491}', '\u{491}'), ('\u{493}', '\u{493}'), ('\u{495}', '\u{495}'), - ('\u{497}', '\u{497}'), ('\u{499}', '\u{499}'), ('\u{49b}', '\u{49b}'), - ('\u{49d}', '\u{49d}'), ('\u{49f}', '\u{49f}'), ('\u{4a1}', '\u{4a1}'), - ('\u{4a3}', '\u{4a3}'), ('\u{4a5}', '\u{4a5}'), ('\u{4a7}', '\u{4a7}'), - ('\u{4a9}', '\u{4a9}'), ('\u{4ab}', '\u{4ab}'), ('\u{4ad}', '\u{4ad}'), - ('\u{4af}', '\u{4af}'), ('\u{4b1}', '\u{4b1}'), ('\u{4b3}', '\u{4b3}'), - ('\u{4b5}', '\u{4b5}'), ('\u{4b7}', '\u{4b7}'), ('\u{4b9}', '\u{4b9}'), - ('\u{4bb}', '\u{4bb}'), ('\u{4bd}', '\u{4bd}'), ('\u{4bf}', '\u{4bf}'), - ('\u{4c2}', '\u{4c2}'), ('\u{4c4}', '\u{4c4}'), ('\u{4c6}', '\u{4c6}'), - ('\u{4c8}', '\u{4c8}'), ('\u{4ca}', '\u{4ca}'), ('\u{4cc}', '\u{4cc}'), - ('\u{4ce}', '\u{4cf}'), ('\u{4d1}', '\u{4d1}'), ('\u{4d3}', '\u{4d3}'), - ('\u{4d5}', '\u{4d5}'), ('\u{4d7}', '\u{4d7}'), ('\u{4d9}', '\u{4d9}'), - ('\u{4db}', '\u{4db}'), ('\u{4dd}', '\u{4dd}'), ('\u{4df}', '\u{4df}'), - ('\u{4e1}', '\u{4e1}'), ('\u{4e3}', '\u{4e3}'), ('\u{4e5}', '\u{4e5}'), - ('\u{4e7}', '\u{4e7}'), ('\u{4e9}', '\u{4e9}'), ('\u{4eb}', '\u{4eb}'), - ('\u{4ed}', '\u{4ed}'), ('\u{4ef}', '\u{4ef}'), ('\u{4f1}', '\u{4f1}'), - ('\u{4f3}', '\u{4f3}'), ('\u{4f5}', '\u{4f5}'), ('\u{4f7}', '\u{4f7}'), - ('\u{4f9}', '\u{4f9}'), ('\u{4fb}', '\u{4fb}'), ('\u{4fd}', '\u{4fd}'), - ('\u{4ff}', '\u{4ff}'), ('\u{501}', '\u{501}'), ('\u{503}', '\u{503}'), - ('\u{505}', '\u{505}'), ('\u{507}', '\u{507}'), ('\u{509}', '\u{509}'), - ('\u{50b}', '\u{50b}'), ('\u{50d}', '\u{50d}'), ('\u{50f}', '\u{50f}'), - ('\u{511}', '\u{511}'), ('\u{513}', '\u{513}'), ('\u{515}', '\u{515}'), - ('\u{517}', '\u{517}'), ('\u{519}', '\u{519}'), ('\u{51b}', '\u{51b}'), - ('\u{51d}', '\u{51d}'), ('\u{51f}', '\u{51f}'), ('\u{521}', '\u{521}'), - ('\u{523}', '\u{523}'), ('\u{525}', '\u{525}'), ('\u{527}', '\u{527}'), - ('\u{529}', '\u{529}'), ('\u{52b}', '\u{52b}'), ('\u{52d}', '\u{52d}'), - ('\u{52f}', '\u{52f}'), ('\u{561}', '\u{587}'), ('\u{13f8}', - '\u{13fd}'), ('\u{1c80}', '\u{1c88}'), ('\u{1d00}', '\u{1dbf}'), - ('\u{1e01}', '\u{1e01}'), ('\u{1e03}', '\u{1e03}'), ('\u{1e05}', - '\u{1e05}'), ('\u{1e07}', '\u{1e07}'), ('\u{1e09}', '\u{1e09}'), - ('\u{1e0b}', '\u{1e0b}'), ('\u{1e0d}', '\u{1e0d}'), ('\u{1e0f}', - '\u{1e0f}'), ('\u{1e11}', '\u{1e11}'), ('\u{1e13}', '\u{1e13}'), - ('\u{1e15}', '\u{1e15}'), ('\u{1e17}', '\u{1e17}'), ('\u{1e19}', - '\u{1e19}'), ('\u{1e1b}', '\u{1e1b}'), ('\u{1e1d}', '\u{1e1d}'), - ('\u{1e1f}', '\u{1e1f}'), ('\u{1e21}', '\u{1e21}'), ('\u{1e23}', - '\u{1e23}'), ('\u{1e25}', '\u{1e25}'), ('\u{1e27}', '\u{1e27}'), - ('\u{1e29}', '\u{1e29}'), ('\u{1e2b}', '\u{1e2b}'), ('\u{1e2d}', - '\u{1e2d}'), ('\u{1e2f}', '\u{1e2f}'), ('\u{1e31}', '\u{1e31}'), - ('\u{1e33}', '\u{1e33}'), ('\u{1e35}', '\u{1e35}'), ('\u{1e37}', - '\u{1e37}'), ('\u{1e39}', '\u{1e39}'), ('\u{1e3b}', '\u{1e3b}'), - ('\u{1e3d}', '\u{1e3d}'), ('\u{1e3f}', '\u{1e3f}'), ('\u{1e41}', - '\u{1e41}'), ('\u{1e43}', '\u{1e43}'), ('\u{1e45}', '\u{1e45}'), - ('\u{1e47}', '\u{1e47}'), ('\u{1e49}', '\u{1e49}'), ('\u{1e4b}', - '\u{1e4b}'), ('\u{1e4d}', '\u{1e4d}'), ('\u{1e4f}', '\u{1e4f}'), - ('\u{1e51}', '\u{1e51}'), ('\u{1e53}', '\u{1e53}'), ('\u{1e55}', - '\u{1e55}'), ('\u{1e57}', '\u{1e57}'), ('\u{1e59}', '\u{1e59}'), - ('\u{1e5b}', '\u{1e5b}'), ('\u{1e5d}', '\u{1e5d}'), ('\u{1e5f}', - '\u{1e5f}'), ('\u{1e61}', '\u{1e61}'), ('\u{1e63}', '\u{1e63}'), - ('\u{1e65}', '\u{1e65}'), ('\u{1e67}', '\u{1e67}'), ('\u{1e69}', - '\u{1e69}'), ('\u{1e6b}', '\u{1e6b}'), ('\u{1e6d}', '\u{1e6d}'), - ('\u{1e6f}', '\u{1e6f}'), ('\u{1e71}', '\u{1e71}'), ('\u{1e73}', - '\u{1e73}'), ('\u{1e75}', '\u{1e75}'), ('\u{1e77}', '\u{1e77}'), - ('\u{1e79}', '\u{1e79}'), ('\u{1e7b}', '\u{1e7b}'), ('\u{1e7d}', - '\u{1e7d}'), ('\u{1e7f}', '\u{1e7f}'), ('\u{1e81}', '\u{1e81}'), - ('\u{1e83}', '\u{1e83}'), ('\u{1e85}', '\u{1e85}'), ('\u{1e87}', - '\u{1e87}'), ('\u{1e89}', '\u{1e89}'), ('\u{1e8b}', '\u{1e8b}'), - ('\u{1e8d}', '\u{1e8d}'), ('\u{1e8f}', '\u{1e8f}'), ('\u{1e91}', - '\u{1e91}'), ('\u{1e93}', '\u{1e93}'), ('\u{1e95}', '\u{1e9d}'), - ('\u{1e9f}', '\u{1e9f}'), ('\u{1ea1}', '\u{1ea1}'), ('\u{1ea3}', - '\u{1ea3}'), ('\u{1ea5}', '\u{1ea5}'), ('\u{1ea7}', '\u{1ea7}'), - ('\u{1ea9}', '\u{1ea9}'), ('\u{1eab}', '\u{1eab}'), ('\u{1ead}', - '\u{1ead}'), ('\u{1eaf}', '\u{1eaf}'), ('\u{1eb1}', '\u{1eb1}'), - ('\u{1eb3}', '\u{1eb3}'), ('\u{1eb5}', '\u{1eb5}'), ('\u{1eb7}', - '\u{1eb7}'), ('\u{1eb9}', '\u{1eb9}'), ('\u{1ebb}', '\u{1ebb}'), - ('\u{1ebd}', '\u{1ebd}'), ('\u{1ebf}', '\u{1ebf}'), ('\u{1ec1}', - '\u{1ec1}'), ('\u{1ec3}', '\u{1ec3}'), ('\u{1ec5}', '\u{1ec5}'), - ('\u{1ec7}', '\u{1ec7}'), ('\u{1ec9}', '\u{1ec9}'), ('\u{1ecb}', - '\u{1ecb}'), ('\u{1ecd}', '\u{1ecd}'), ('\u{1ecf}', '\u{1ecf}'), - ('\u{1ed1}', '\u{1ed1}'), ('\u{1ed3}', '\u{1ed3}'), ('\u{1ed5}', - '\u{1ed5}'), ('\u{1ed7}', '\u{1ed7}'), ('\u{1ed9}', '\u{1ed9}'), - ('\u{1edb}', '\u{1edb}'), ('\u{1edd}', '\u{1edd}'), ('\u{1edf}', - '\u{1edf}'), ('\u{1ee1}', '\u{1ee1}'), ('\u{1ee3}', '\u{1ee3}'), - ('\u{1ee5}', '\u{1ee5}'), ('\u{1ee7}', '\u{1ee7}'), ('\u{1ee9}', - '\u{1ee9}'), ('\u{1eeb}', '\u{1eeb}'), ('\u{1eed}', '\u{1eed}'), - ('\u{1eef}', '\u{1eef}'), ('\u{1ef1}', '\u{1ef1}'), ('\u{1ef3}', - '\u{1ef3}'), ('\u{1ef5}', '\u{1ef5}'), ('\u{1ef7}', '\u{1ef7}'), - ('\u{1ef9}', '\u{1ef9}'), ('\u{1efb}', '\u{1efb}'), ('\u{1efd}', - '\u{1efd}'), ('\u{1eff}', '\u{1f07}'), ('\u{1f10}', '\u{1f15}'), - ('\u{1f20}', '\u{1f27}'), ('\u{1f30}', '\u{1f37}'), ('\u{1f40}', - '\u{1f45}'), ('\u{1f50}', '\u{1f57}'), ('\u{1f60}', '\u{1f67}'), - ('\u{1f70}', '\u{1f7d}'), ('\u{1f80}', '\u{1f87}'), ('\u{1f90}', - '\u{1f97}'), ('\u{1fa0}', '\u{1fa7}'), ('\u{1fb0}', '\u{1fb4}'), - ('\u{1fb6}', '\u{1fb7}'), ('\u{1fbe}', '\u{1fbe}'), ('\u{1fc2}', - '\u{1fc4}'), ('\u{1fc6}', '\u{1fc7}'), ('\u{1fd0}', '\u{1fd3}'), - ('\u{1fd6}', '\u{1fd7}'), ('\u{1fe0}', '\u{1fe7}'), ('\u{1ff2}', - '\u{1ff4}'), ('\u{1ff6}', '\u{1ff7}'), ('\u{2071}', '\u{2071}'), - ('\u{207f}', '\u{207f}'), ('\u{2090}', '\u{209c}'), ('\u{210a}', - '\u{210a}'), ('\u{210e}', '\u{210f}'), ('\u{2113}', '\u{2113}'), - ('\u{212f}', '\u{212f}'), ('\u{2134}', '\u{2134}'), ('\u{2139}', - '\u{2139}'), ('\u{213c}', '\u{213d}'), ('\u{2146}', '\u{2149}'), - ('\u{214e}', '\u{214e}'), ('\u{2170}', '\u{217f}'), ('\u{2184}', - '\u{2184}'), ('\u{24d0}', '\u{24e9}'), ('\u{2c30}', '\u{2c5e}'), - ('\u{2c61}', '\u{2c61}'), ('\u{2c65}', '\u{2c66}'), ('\u{2c68}', - '\u{2c68}'), ('\u{2c6a}', '\u{2c6a}'), ('\u{2c6c}', '\u{2c6c}'), - ('\u{2c71}', '\u{2c71}'), ('\u{2c73}', '\u{2c74}'), ('\u{2c76}', - '\u{2c7d}'), ('\u{2c81}', '\u{2c81}'), ('\u{2c83}', '\u{2c83}'), - ('\u{2c85}', '\u{2c85}'), ('\u{2c87}', '\u{2c87}'), ('\u{2c89}', - '\u{2c89}'), ('\u{2c8b}', '\u{2c8b}'), ('\u{2c8d}', '\u{2c8d}'), - ('\u{2c8f}', '\u{2c8f}'), ('\u{2c91}', '\u{2c91}'), ('\u{2c93}', - '\u{2c93}'), ('\u{2c95}', '\u{2c95}'), ('\u{2c97}', '\u{2c97}'), - ('\u{2c99}', '\u{2c99}'), ('\u{2c9b}', '\u{2c9b}'), ('\u{2c9d}', - '\u{2c9d}'), ('\u{2c9f}', '\u{2c9f}'), ('\u{2ca1}', '\u{2ca1}'), - ('\u{2ca3}', '\u{2ca3}'), ('\u{2ca5}', '\u{2ca5}'), ('\u{2ca7}', - '\u{2ca7}'), ('\u{2ca9}', '\u{2ca9}'), ('\u{2cab}', '\u{2cab}'), - ('\u{2cad}', '\u{2cad}'), ('\u{2caf}', '\u{2caf}'), ('\u{2cb1}', - '\u{2cb1}'), ('\u{2cb3}', '\u{2cb3}'), ('\u{2cb5}', '\u{2cb5}'), - ('\u{2cb7}', '\u{2cb7}'), ('\u{2cb9}', '\u{2cb9}'), ('\u{2cbb}', - '\u{2cbb}'), ('\u{2cbd}', '\u{2cbd}'), ('\u{2cbf}', '\u{2cbf}'), - ('\u{2cc1}', '\u{2cc1}'), ('\u{2cc3}', '\u{2cc3}'), ('\u{2cc5}', - '\u{2cc5}'), ('\u{2cc7}', '\u{2cc7}'), ('\u{2cc9}', '\u{2cc9}'), - ('\u{2ccb}', '\u{2ccb}'), ('\u{2ccd}', '\u{2ccd}'), ('\u{2ccf}', - '\u{2ccf}'), ('\u{2cd1}', '\u{2cd1}'), ('\u{2cd3}', '\u{2cd3}'), - ('\u{2cd5}', '\u{2cd5}'), ('\u{2cd7}', '\u{2cd7}'), ('\u{2cd9}', - '\u{2cd9}'), ('\u{2cdb}', '\u{2cdb}'), ('\u{2cdd}', '\u{2cdd}'), - ('\u{2cdf}', '\u{2cdf}'), ('\u{2ce1}', '\u{2ce1}'), ('\u{2ce3}', - '\u{2ce4}'), ('\u{2cec}', '\u{2cec}'), ('\u{2cee}', '\u{2cee}'), - ('\u{2cf3}', '\u{2cf3}'), ('\u{2d00}', '\u{2d25}'), ('\u{2d27}', - '\u{2d27}'), ('\u{2d2d}', '\u{2d2d}'), ('\u{a641}', '\u{a641}'), - ('\u{a643}', '\u{a643}'), ('\u{a645}', '\u{a645}'), ('\u{a647}', - '\u{a647}'), ('\u{a649}', '\u{a649}'), ('\u{a64b}', '\u{a64b}'), - ('\u{a64d}', '\u{a64d}'), ('\u{a64f}', '\u{a64f}'), ('\u{a651}', - '\u{a651}'), ('\u{a653}', '\u{a653}'), ('\u{a655}', '\u{a655}'), - ('\u{a657}', '\u{a657}'), ('\u{a659}', '\u{a659}'), ('\u{a65b}', - '\u{a65b}'), ('\u{a65d}', '\u{a65d}'), ('\u{a65f}', '\u{a65f}'), - ('\u{a661}', '\u{a661}'), ('\u{a663}', '\u{a663}'), ('\u{a665}', - '\u{a665}'), ('\u{a667}', '\u{a667}'), ('\u{a669}', '\u{a669}'), - ('\u{a66b}', '\u{a66b}'), ('\u{a66d}', '\u{a66d}'), ('\u{a681}', - '\u{a681}'), ('\u{a683}', '\u{a683}'), ('\u{a685}', '\u{a685}'), - ('\u{a687}', '\u{a687}'), ('\u{a689}', '\u{a689}'), ('\u{a68b}', - '\u{a68b}'), ('\u{a68d}', '\u{a68d}'), ('\u{a68f}', '\u{a68f}'), - ('\u{a691}', '\u{a691}'), ('\u{a693}', '\u{a693}'), ('\u{a695}', - '\u{a695}'), ('\u{a697}', '\u{a697}'), ('\u{a699}', '\u{a699}'), - ('\u{a69b}', '\u{a69d}'), ('\u{a723}', '\u{a723}'), ('\u{a725}', - '\u{a725}'), ('\u{a727}', '\u{a727}'), ('\u{a729}', '\u{a729}'), - ('\u{a72b}', '\u{a72b}'), ('\u{a72d}', '\u{a72d}'), ('\u{a72f}', - '\u{a731}'), ('\u{a733}', '\u{a733}'), ('\u{a735}', '\u{a735}'), - ('\u{a737}', '\u{a737}'), ('\u{a739}', '\u{a739}'), ('\u{a73b}', - '\u{a73b}'), ('\u{a73d}', '\u{a73d}'), ('\u{a73f}', '\u{a73f}'), - ('\u{a741}', '\u{a741}'), ('\u{a743}', '\u{a743}'), ('\u{a745}', - '\u{a745}'), ('\u{a747}', '\u{a747}'), ('\u{a749}', '\u{a749}'), - ('\u{a74b}', '\u{a74b}'), ('\u{a74d}', '\u{a74d}'), ('\u{a74f}', - '\u{a74f}'), ('\u{a751}', '\u{a751}'), ('\u{a753}', '\u{a753}'), - ('\u{a755}', '\u{a755}'), ('\u{a757}', '\u{a757}'), ('\u{a759}', - '\u{a759}'), ('\u{a75b}', '\u{a75b}'), ('\u{a75d}', '\u{a75d}'), - ('\u{a75f}', '\u{a75f}'), ('\u{a761}', '\u{a761}'), ('\u{a763}', - '\u{a763}'), ('\u{a765}', '\u{a765}'), ('\u{a767}', '\u{a767}'), - ('\u{a769}', '\u{a769}'), ('\u{a76b}', '\u{a76b}'), ('\u{a76d}', - '\u{a76d}'), ('\u{a76f}', '\u{a778}'), ('\u{a77a}', '\u{a77a}'), - ('\u{a77c}', '\u{a77c}'), ('\u{a77f}', '\u{a77f}'), ('\u{a781}', - '\u{a781}'), ('\u{a783}', '\u{a783}'), ('\u{a785}', '\u{a785}'), - ('\u{a787}', '\u{a787}'), ('\u{a78c}', '\u{a78c}'), ('\u{a78e}', - '\u{a78e}'), ('\u{a791}', '\u{a791}'), ('\u{a793}', '\u{a795}'), - ('\u{a797}', '\u{a797}'), ('\u{a799}', '\u{a799}'), ('\u{a79b}', - '\u{a79b}'), ('\u{a79d}', '\u{a79d}'), ('\u{a79f}', '\u{a79f}'), - ('\u{a7a1}', '\u{a7a1}'), ('\u{a7a3}', '\u{a7a3}'), ('\u{a7a5}', - '\u{a7a5}'), ('\u{a7a7}', '\u{a7a7}'), ('\u{a7a9}', '\u{a7a9}'), - ('\u{a7b5}', '\u{a7b5}'), ('\u{a7b7}', '\u{a7b7}'), ('\u{a7f8}', - '\u{a7fa}'), ('\u{ab30}', '\u{ab5a}'), ('\u{ab5c}', '\u{ab65}'), - ('\u{ab70}', '\u{abbf}'), ('\u{fb00}', '\u{fb06}'), ('\u{fb13}', - '\u{fb17}'), ('\u{ff41}', '\u{ff5a}'), ('\u{10428}', '\u{1044f}'), - ('\u{104d8}', '\u{104fb}'), ('\u{10cc0}', '\u{10cf2}'), ('\u{118c0}', - '\u{118df}'), ('\u{1d41a}', '\u{1d433}'), ('\u{1d44e}', '\u{1d454}'), - ('\u{1d456}', '\u{1d467}'), ('\u{1d482}', '\u{1d49b}'), ('\u{1d4b6}', - '\u{1d4b9}'), ('\u{1d4bb}', '\u{1d4bb}'), ('\u{1d4bd}', '\u{1d4c3}'), - ('\u{1d4c5}', '\u{1d4cf}'), ('\u{1d4ea}', '\u{1d503}'), ('\u{1d51e}', - '\u{1d537}'), ('\u{1d552}', '\u{1d56b}'), ('\u{1d586}', '\u{1d59f}'), - ('\u{1d5ba}', '\u{1d5d3}'), ('\u{1d5ee}', '\u{1d607}'), ('\u{1d622}', - '\u{1d63b}'), ('\u{1d656}', '\u{1d66f}'), ('\u{1d68a}', '\u{1d6a5}'), - ('\u{1d6c2}', '\u{1d6da}'), ('\u{1d6dc}', '\u{1d6e1}'), ('\u{1d6fc}', - '\u{1d714}'), ('\u{1d716}', '\u{1d71b}'), ('\u{1d736}', '\u{1d74e}'), - ('\u{1d750}', '\u{1d755}'), ('\u{1d770}', '\u{1d788}'), ('\u{1d78a}', - '\u{1d78f}'), ('\u{1d7aa}', '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7c9}'), - ('\u{1d7cb}', '\u{1d7cb}'), ('\u{1e922}', '\u{1e943}') - ]; - - pub const Uppercase_table: &'static [(char, char)] = &[ - ('\u{41}', '\u{5a}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{de}'), - ('\u{100}', '\u{100}'), ('\u{102}', '\u{102}'), ('\u{104}', '\u{104}'), - ('\u{106}', '\u{106}'), ('\u{108}', '\u{108}'), ('\u{10a}', '\u{10a}'), - ('\u{10c}', '\u{10c}'), ('\u{10e}', '\u{10e}'), ('\u{110}', '\u{110}'), - ('\u{112}', '\u{112}'), ('\u{114}', '\u{114}'), ('\u{116}', '\u{116}'), - ('\u{118}', '\u{118}'), ('\u{11a}', '\u{11a}'), ('\u{11c}', '\u{11c}'), - ('\u{11e}', '\u{11e}'), ('\u{120}', '\u{120}'), ('\u{122}', '\u{122}'), - ('\u{124}', '\u{124}'), ('\u{126}', '\u{126}'), ('\u{128}', '\u{128}'), - ('\u{12a}', '\u{12a}'), ('\u{12c}', '\u{12c}'), ('\u{12e}', '\u{12e}'), - ('\u{130}', '\u{130}'), ('\u{132}', '\u{132}'), ('\u{134}', '\u{134}'), - ('\u{136}', '\u{136}'), ('\u{139}', '\u{139}'), ('\u{13b}', '\u{13b}'), - ('\u{13d}', '\u{13d}'), ('\u{13f}', '\u{13f}'), ('\u{141}', '\u{141}'), - ('\u{143}', '\u{143}'), ('\u{145}', '\u{145}'), ('\u{147}', '\u{147}'), - ('\u{14a}', '\u{14a}'), ('\u{14c}', '\u{14c}'), ('\u{14e}', '\u{14e}'), - ('\u{150}', '\u{150}'), ('\u{152}', '\u{152}'), ('\u{154}', '\u{154}'), - ('\u{156}', '\u{156}'), ('\u{158}', '\u{158}'), ('\u{15a}', '\u{15a}'), - ('\u{15c}', '\u{15c}'), ('\u{15e}', '\u{15e}'), ('\u{160}', '\u{160}'), - ('\u{162}', '\u{162}'), ('\u{164}', '\u{164}'), ('\u{166}', '\u{166}'), - ('\u{168}', '\u{168}'), ('\u{16a}', '\u{16a}'), ('\u{16c}', '\u{16c}'), - ('\u{16e}', '\u{16e}'), ('\u{170}', '\u{170}'), ('\u{172}', '\u{172}'), - ('\u{174}', '\u{174}'), ('\u{176}', '\u{176}'), ('\u{178}', '\u{179}'), - ('\u{17b}', '\u{17b}'), ('\u{17d}', '\u{17d}'), ('\u{181}', '\u{182}'), - ('\u{184}', '\u{184}'), ('\u{186}', '\u{187}'), ('\u{189}', '\u{18b}'), - ('\u{18e}', '\u{191}'), ('\u{193}', '\u{194}'), ('\u{196}', '\u{198}'), - ('\u{19c}', '\u{19d}'), ('\u{19f}', '\u{1a0}'), ('\u{1a2}', '\u{1a2}'), - ('\u{1a4}', '\u{1a4}'), ('\u{1a6}', '\u{1a7}'), ('\u{1a9}', '\u{1a9}'), - ('\u{1ac}', '\u{1ac}'), ('\u{1ae}', '\u{1af}'), ('\u{1b1}', '\u{1b3}'), - ('\u{1b5}', '\u{1b5}'), ('\u{1b7}', '\u{1b8}'), ('\u{1bc}', '\u{1bc}'), - ('\u{1c4}', '\u{1c4}'), ('\u{1c7}', '\u{1c7}'), ('\u{1ca}', '\u{1ca}'), - ('\u{1cd}', '\u{1cd}'), ('\u{1cf}', '\u{1cf}'), ('\u{1d1}', '\u{1d1}'), - ('\u{1d3}', '\u{1d3}'), ('\u{1d5}', '\u{1d5}'), ('\u{1d7}', '\u{1d7}'), - ('\u{1d9}', '\u{1d9}'), ('\u{1db}', '\u{1db}'), ('\u{1de}', '\u{1de}'), - ('\u{1e0}', '\u{1e0}'), ('\u{1e2}', '\u{1e2}'), ('\u{1e4}', '\u{1e4}'), - ('\u{1e6}', '\u{1e6}'), ('\u{1e8}', '\u{1e8}'), ('\u{1ea}', '\u{1ea}'), - ('\u{1ec}', '\u{1ec}'), ('\u{1ee}', '\u{1ee}'), ('\u{1f1}', '\u{1f1}'), - ('\u{1f4}', '\u{1f4}'), ('\u{1f6}', '\u{1f8}'), ('\u{1fa}', '\u{1fa}'), - ('\u{1fc}', '\u{1fc}'), ('\u{1fe}', '\u{1fe}'), ('\u{200}', '\u{200}'), - ('\u{202}', '\u{202}'), ('\u{204}', '\u{204}'), ('\u{206}', '\u{206}'), - ('\u{208}', '\u{208}'), ('\u{20a}', '\u{20a}'), ('\u{20c}', '\u{20c}'), - ('\u{20e}', '\u{20e}'), ('\u{210}', '\u{210}'), ('\u{212}', '\u{212}'), - ('\u{214}', '\u{214}'), ('\u{216}', '\u{216}'), ('\u{218}', '\u{218}'), - ('\u{21a}', '\u{21a}'), ('\u{21c}', '\u{21c}'), ('\u{21e}', '\u{21e}'), - ('\u{220}', '\u{220}'), ('\u{222}', '\u{222}'), ('\u{224}', '\u{224}'), - ('\u{226}', '\u{226}'), ('\u{228}', '\u{228}'), ('\u{22a}', '\u{22a}'), - ('\u{22c}', '\u{22c}'), ('\u{22e}', '\u{22e}'), ('\u{230}', '\u{230}'), - ('\u{232}', '\u{232}'), ('\u{23a}', '\u{23b}'), ('\u{23d}', '\u{23e}'), - ('\u{241}', '\u{241}'), ('\u{243}', '\u{246}'), ('\u{248}', '\u{248}'), - ('\u{24a}', '\u{24a}'), ('\u{24c}', '\u{24c}'), ('\u{24e}', '\u{24e}'), - ('\u{370}', '\u{370}'), ('\u{372}', '\u{372}'), ('\u{376}', '\u{376}'), - ('\u{37f}', '\u{37f}'), ('\u{386}', '\u{386}'), ('\u{388}', '\u{38a}'), - ('\u{38c}', '\u{38c}'), ('\u{38e}', '\u{38f}'), ('\u{391}', '\u{3a1}'), - ('\u{3a3}', '\u{3ab}'), ('\u{3cf}', '\u{3cf}'), ('\u{3d2}', '\u{3d4}'), - ('\u{3d8}', '\u{3d8}'), ('\u{3da}', '\u{3da}'), ('\u{3dc}', '\u{3dc}'), - ('\u{3de}', '\u{3de}'), ('\u{3e0}', '\u{3e0}'), ('\u{3e2}', '\u{3e2}'), - ('\u{3e4}', '\u{3e4}'), ('\u{3e6}', '\u{3e6}'), ('\u{3e8}', '\u{3e8}'), - ('\u{3ea}', '\u{3ea}'), ('\u{3ec}', '\u{3ec}'), ('\u{3ee}', '\u{3ee}'), - ('\u{3f4}', '\u{3f4}'), ('\u{3f7}', '\u{3f7}'), ('\u{3f9}', '\u{3fa}'), - ('\u{3fd}', '\u{42f}'), ('\u{460}', '\u{460}'), ('\u{462}', '\u{462}'), - ('\u{464}', '\u{464}'), ('\u{466}', '\u{466}'), ('\u{468}', '\u{468}'), - ('\u{46a}', '\u{46a}'), ('\u{46c}', '\u{46c}'), ('\u{46e}', '\u{46e}'), - ('\u{470}', '\u{470}'), ('\u{472}', '\u{472}'), ('\u{474}', '\u{474}'), - ('\u{476}', '\u{476}'), ('\u{478}', '\u{478}'), ('\u{47a}', '\u{47a}'), - ('\u{47c}', '\u{47c}'), ('\u{47e}', '\u{47e}'), ('\u{480}', '\u{480}'), - ('\u{48a}', '\u{48a}'), ('\u{48c}', '\u{48c}'), ('\u{48e}', '\u{48e}'), - ('\u{490}', '\u{490}'), ('\u{492}', '\u{492}'), ('\u{494}', '\u{494}'), - ('\u{496}', '\u{496}'), ('\u{498}', '\u{498}'), ('\u{49a}', '\u{49a}'), - ('\u{49c}', '\u{49c}'), ('\u{49e}', '\u{49e}'), ('\u{4a0}', '\u{4a0}'), - ('\u{4a2}', '\u{4a2}'), ('\u{4a4}', '\u{4a4}'), ('\u{4a6}', '\u{4a6}'), - ('\u{4a8}', '\u{4a8}'), ('\u{4aa}', '\u{4aa}'), ('\u{4ac}', '\u{4ac}'), - ('\u{4ae}', '\u{4ae}'), ('\u{4b0}', '\u{4b0}'), ('\u{4b2}', '\u{4b2}'), - ('\u{4b4}', '\u{4b4}'), ('\u{4b6}', '\u{4b6}'), ('\u{4b8}', '\u{4b8}'), - ('\u{4ba}', '\u{4ba}'), ('\u{4bc}', '\u{4bc}'), ('\u{4be}', '\u{4be}'), - ('\u{4c0}', '\u{4c1}'), ('\u{4c3}', '\u{4c3}'), ('\u{4c5}', '\u{4c5}'), - ('\u{4c7}', '\u{4c7}'), ('\u{4c9}', '\u{4c9}'), ('\u{4cb}', '\u{4cb}'), - ('\u{4cd}', '\u{4cd}'), ('\u{4d0}', '\u{4d0}'), ('\u{4d2}', '\u{4d2}'), - ('\u{4d4}', '\u{4d4}'), ('\u{4d6}', '\u{4d6}'), ('\u{4d8}', '\u{4d8}'), - ('\u{4da}', '\u{4da}'), ('\u{4dc}', '\u{4dc}'), ('\u{4de}', '\u{4de}'), - ('\u{4e0}', '\u{4e0}'), ('\u{4e2}', '\u{4e2}'), ('\u{4e4}', '\u{4e4}'), - ('\u{4e6}', '\u{4e6}'), ('\u{4e8}', '\u{4e8}'), ('\u{4ea}', '\u{4ea}'), - ('\u{4ec}', '\u{4ec}'), ('\u{4ee}', '\u{4ee}'), ('\u{4f0}', '\u{4f0}'), - ('\u{4f2}', '\u{4f2}'), ('\u{4f4}', '\u{4f4}'), ('\u{4f6}', '\u{4f6}'), - ('\u{4f8}', '\u{4f8}'), ('\u{4fa}', '\u{4fa}'), ('\u{4fc}', '\u{4fc}'), - ('\u{4fe}', '\u{4fe}'), ('\u{500}', '\u{500}'), ('\u{502}', '\u{502}'), - ('\u{504}', '\u{504}'), ('\u{506}', '\u{506}'), ('\u{508}', '\u{508}'), - ('\u{50a}', '\u{50a}'), ('\u{50c}', '\u{50c}'), ('\u{50e}', '\u{50e}'), - ('\u{510}', '\u{510}'), ('\u{512}', '\u{512}'), ('\u{514}', '\u{514}'), - ('\u{516}', '\u{516}'), ('\u{518}', '\u{518}'), ('\u{51a}', '\u{51a}'), - ('\u{51c}', '\u{51c}'), ('\u{51e}', '\u{51e}'), ('\u{520}', '\u{520}'), - ('\u{522}', '\u{522}'), ('\u{524}', '\u{524}'), ('\u{526}', '\u{526}'), - ('\u{528}', '\u{528}'), ('\u{52a}', '\u{52a}'), ('\u{52c}', '\u{52c}'), - ('\u{52e}', '\u{52e}'), ('\u{531}', '\u{556}'), ('\u{10a0}', - '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), ('\u{10cd}', '\u{10cd}'), - ('\u{13a0}', '\u{13f5}'), ('\u{1e00}', '\u{1e00}'), ('\u{1e02}', - '\u{1e02}'), ('\u{1e04}', '\u{1e04}'), ('\u{1e06}', '\u{1e06}'), - ('\u{1e08}', '\u{1e08}'), ('\u{1e0a}', '\u{1e0a}'), ('\u{1e0c}', - '\u{1e0c}'), ('\u{1e0e}', '\u{1e0e}'), ('\u{1e10}', '\u{1e10}'), - ('\u{1e12}', '\u{1e12}'), ('\u{1e14}', '\u{1e14}'), ('\u{1e16}', - '\u{1e16}'), ('\u{1e18}', '\u{1e18}'), ('\u{1e1a}', '\u{1e1a}'), - ('\u{1e1c}', '\u{1e1c}'), ('\u{1e1e}', '\u{1e1e}'), ('\u{1e20}', - '\u{1e20}'), ('\u{1e22}', '\u{1e22}'), ('\u{1e24}', '\u{1e24}'), - ('\u{1e26}', '\u{1e26}'), ('\u{1e28}', '\u{1e28}'), ('\u{1e2a}', - '\u{1e2a}'), ('\u{1e2c}', '\u{1e2c}'), ('\u{1e2e}', '\u{1e2e}'), - ('\u{1e30}', '\u{1e30}'), ('\u{1e32}', '\u{1e32}'), ('\u{1e34}', - '\u{1e34}'), ('\u{1e36}', '\u{1e36}'), ('\u{1e38}', '\u{1e38}'), - ('\u{1e3a}', '\u{1e3a}'), ('\u{1e3c}', '\u{1e3c}'), ('\u{1e3e}', - '\u{1e3e}'), ('\u{1e40}', '\u{1e40}'), ('\u{1e42}', '\u{1e42}'), - ('\u{1e44}', '\u{1e44}'), ('\u{1e46}', '\u{1e46}'), ('\u{1e48}', - '\u{1e48}'), ('\u{1e4a}', '\u{1e4a}'), ('\u{1e4c}', '\u{1e4c}'), - ('\u{1e4e}', '\u{1e4e}'), ('\u{1e50}', '\u{1e50}'), ('\u{1e52}', - '\u{1e52}'), ('\u{1e54}', '\u{1e54}'), ('\u{1e56}', '\u{1e56}'), - ('\u{1e58}', '\u{1e58}'), ('\u{1e5a}', '\u{1e5a}'), ('\u{1e5c}', - '\u{1e5c}'), ('\u{1e5e}', '\u{1e5e}'), ('\u{1e60}', '\u{1e60}'), - ('\u{1e62}', '\u{1e62}'), ('\u{1e64}', '\u{1e64}'), ('\u{1e66}', - '\u{1e66}'), ('\u{1e68}', '\u{1e68}'), ('\u{1e6a}', '\u{1e6a}'), - ('\u{1e6c}', '\u{1e6c}'), ('\u{1e6e}', '\u{1e6e}'), ('\u{1e70}', - '\u{1e70}'), ('\u{1e72}', '\u{1e72}'), ('\u{1e74}', '\u{1e74}'), - ('\u{1e76}', '\u{1e76}'), ('\u{1e78}', '\u{1e78}'), ('\u{1e7a}', - '\u{1e7a}'), ('\u{1e7c}', '\u{1e7c}'), ('\u{1e7e}', '\u{1e7e}'), - ('\u{1e80}', '\u{1e80}'), ('\u{1e82}', '\u{1e82}'), ('\u{1e84}', - '\u{1e84}'), ('\u{1e86}', '\u{1e86}'), ('\u{1e88}', '\u{1e88}'), - ('\u{1e8a}', '\u{1e8a}'), ('\u{1e8c}', '\u{1e8c}'), ('\u{1e8e}', - '\u{1e8e}'), ('\u{1e90}', '\u{1e90}'), ('\u{1e92}', '\u{1e92}'), - ('\u{1e94}', '\u{1e94}'), ('\u{1e9e}', '\u{1e9e}'), ('\u{1ea0}', - '\u{1ea0}'), ('\u{1ea2}', '\u{1ea2}'), ('\u{1ea4}', '\u{1ea4}'), - ('\u{1ea6}', '\u{1ea6}'), ('\u{1ea8}', '\u{1ea8}'), ('\u{1eaa}', - '\u{1eaa}'), ('\u{1eac}', '\u{1eac}'), ('\u{1eae}', '\u{1eae}'), - ('\u{1eb0}', '\u{1eb0}'), ('\u{1eb2}', '\u{1eb2}'), ('\u{1eb4}', - '\u{1eb4}'), ('\u{1eb6}', '\u{1eb6}'), ('\u{1eb8}', '\u{1eb8}'), - ('\u{1eba}', '\u{1eba}'), ('\u{1ebc}', '\u{1ebc}'), ('\u{1ebe}', - '\u{1ebe}'), ('\u{1ec0}', '\u{1ec0}'), ('\u{1ec2}', '\u{1ec2}'), - ('\u{1ec4}', '\u{1ec4}'), ('\u{1ec6}', '\u{1ec6}'), ('\u{1ec8}', - '\u{1ec8}'), ('\u{1eca}', '\u{1eca}'), ('\u{1ecc}', '\u{1ecc}'), - ('\u{1ece}', '\u{1ece}'), ('\u{1ed0}', '\u{1ed0}'), ('\u{1ed2}', - '\u{1ed2}'), ('\u{1ed4}', '\u{1ed4}'), ('\u{1ed6}', '\u{1ed6}'), - ('\u{1ed8}', '\u{1ed8}'), ('\u{1eda}', '\u{1eda}'), ('\u{1edc}', - '\u{1edc}'), ('\u{1ede}', '\u{1ede}'), ('\u{1ee0}', '\u{1ee0}'), - ('\u{1ee2}', '\u{1ee2}'), ('\u{1ee4}', '\u{1ee4}'), ('\u{1ee6}', - '\u{1ee6}'), ('\u{1ee8}', '\u{1ee8}'), ('\u{1eea}', '\u{1eea}'), - ('\u{1eec}', '\u{1eec}'), ('\u{1eee}', '\u{1eee}'), ('\u{1ef0}', - '\u{1ef0}'), ('\u{1ef2}', '\u{1ef2}'), ('\u{1ef4}', '\u{1ef4}'), - ('\u{1ef6}', '\u{1ef6}'), ('\u{1ef8}', '\u{1ef8}'), ('\u{1efa}', - '\u{1efa}'), ('\u{1efc}', '\u{1efc}'), ('\u{1efe}', '\u{1efe}'), - ('\u{1f08}', '\u{1f0f}'), ('\u{1f18}', '\u{1f1d}'), ('\u{1f28}', - '\u{1f2f}'), ('\u{1f38}', '\u{1f3f}'), ('\u{1f48}', '\u{1f4d}'), - ('\u{1f59}', '\u{1f59}'), ('\u{1f5b}', '\u{1f5b}'), ('\u{1f5d}', - '\u{1f5d}'), ('\u{1f5f}', '\u{1f5f}'), ('\u{1f68}', '\u{1f6f}'), - ('\u{1fb8}', '\u{1fbb}'), ('\u{1fc8}', '\u{1fcb}'), ('\u{1fd8}', - '\u{1fdb}'), ('\u{1fe8}', '\u{1fec}'), ('\u{1ff8}', '\u{1ffb}'), - ('\u{2102}', '\u{2102}'), ('\u{2107}', '\u{2107}'), ('\u{210b}', - '\u{210d}'), ('\u{2110}', '\u{2112}'), ('\u{2115}', '\u{2115}'), - ('\u{2119}', '\u{211d}'), ('\u{2124}', '\u{2124}'), ('\u{2126}', - '\u{2126}'), ('\u{2128}', '\u{2128}'), ('\u{212a}', '\u{212d}'), - ('\u{2130}', '\u{2133}'), ('\u{213e}', '\u{213f}'), ('\u{2145}', - '\u{2145}'), ('\u{2160}', '\u{216f}'), ('\u{2183}', '\u{2183}'), - ('\u{24b6}', '\u{24cf}'), ('\u{2c00}', '\u{2c2e}'), ('\u{2c60}', - '\u{2c60}'), ('\u{2c62}', '\u{2c64}'), ('\u{2c67}', '\u{2c67}'), - ('\u{2c69}', '\u{2c69}'), ('\u{2c6b}', '\u{2c6b}'), ('\u{2c6d}', - '\u{2c70}'), ('\u{2c72}', '\u{2c72}'), ('\u{2c75}', '\u{2c75}'), - ('\u{2c7e}', '\u{2c80}'), ('\u{2c82}', '\u{2c82}'), ('\u{2c84}', - '\u{2c84}'), ('\u{2c86}', '\u{2c86}'), ('\u{2c88}', '\u{2c88}'), - ('\u{2c8a}', '\u{2c8a}'), ('\u{2c8c}', '\u{2c8c}'), ('\u{2c8e}', - '\u{2c8e}'), ('\u{2c90}', '\u{2c90}'), ('\u{2c92}', '\u{2c92}'), - ('\u{2c94}', '\u{2c94}'), ('\u{2c96}', '\u{2c96}'), ('\u{2c98}', - '\u{2c98}'), ('\u{2c9a}', '\u{2c9a}'), ('\u{2c9c}', '\u{2c9c}'), - ('\u{2c9e}', '\u{2c9e}'), ('\u{2ca0}', '\u{2ca0}'), ('\u{2ca2}', - '\u{2ca2}'), ('\u{2ca4}', '\u{2ca4}'), ('\u{2ca6}', '\u{2ca6}'), - ('\u{2ca8}', '\u{2ca8}'), ('\u{2caa}', '\u{2caa}'), ('\u{2cac}', - '\u{2cac}'), ('\u{2cae}', '\u{2cae}'), ('\u{2cb0}', '\u{2cb0}'), - ('\u{2cb2}', '\u{2cb2}'), ('\u{2cb4}', '\u{2cb4}'), ('\u{2cb6}', - '\u{2cb6}'), ('\u{2cb8}', '\u{2cb8}'), ('\u{2cba}', '\u{2cba}'), - ('\u{2cbc}', '\u{2cbc}'), ('\u{2cbe}', '\u{2cbe}'), ('\u{2cc0}', - '\u{2cc0}'), ('\u{2cc2}', '\u{2cc2}'), ('\u{2cc4}', '\u{2cc4}'), - ('\u{2cc6}', '\u{2cc6}'), ('\u{2cc8}', '\u{2cc8}'), ('\u{2cca}', - '\u{2cca}'), ('\u{2ccc}', '\u{2ccc}'), ('\u{2cce}', '\u{2cce}'), - ('\u{2cd0}', '\u{2cd0}'), ('\u{2cd2}', '\u{2cd2}'), ('\u{2cd4}', - '\u{2cd4}'), ('\u{2cd6}', '\u{2cd6}'), ('\u{2cd8}', '\u{2cd8}'), - ('\u{2cda}', '\u{2cda}'), ('\u{2cdc}', '\u{2cdc}'), ('\u{2cde}', - '\u{2cde}'), ('\u{2ce0}', '\u{2ce0}'), ('\u{2ce2}', '\u{2ce2}'), - ('\u{2ceb}', '\u{2ceb}'), ('\u{2ced}', '\u{2ced}'), ('\u{2cf2}', - '\u{2cf2}'), ('\u{a640}', '\u{a640}'), ('\u{a642}', '\u{a642}'), - ('\u{a644}', '\u{a644}'), ('\u{a646}', '\u{a646}'), ('\u{a648}', - '\u{a648}'), ('\u{a64a}', '\u{a64a}'), ('\u{a64c}', '\u{a64c}'), - ('\u{a64e}', '\u{a64e}'), ('\u{a650}', '\u{a650}'), ('\u{a652}', - '\u{a652}'), ('\u{a654}', '\u{a654}'), ('\u{a656}', '\u{a656}'), - ('\u{a658}', '\u{a658}'), ('\u{a65a}', '\u{a65a}'), ('\u{a65c}', - '\u{a65c}'), ('\u{a65e}', '\u{a65e}'), ('\u{a660}', '\u{a660}'), - ('\u{a662}', '\u{a662}'), ('\u{a664}', '\u{a664}'), ('\u{a666}', - '\u{a666}'), ('\u{a668}', '\u{a668}'), ('\u{a66a}', '\u{a66a}'), - ('\u{a66c}', '\u{a66c}'), ('\u{a680}', '\u{a680}'), ('\u{a682}', - '\u{a682}'), ('\u{a684}', '\u{a684}'), ('\u{a686}', '\u{a686}'), - ('\u{a688}', '\u{a688}'), ('\u{a68a}', '\u{a68a}'), ('\u{a68c}', - '\u{a68c}'), ('\u{a68e}', '\u{a68e}'), ('\u{a690}', '\u{a690}'), - ('\u{a692}', '\u{a692}'), ('\u{a694}', '\u{a694}'), ('\u{a696}', - '\u{a696}'), ('\u{a698}', '\u{a698}'), ('\u{a69a}', '\u{a69a}'), - ('\u{a722}', '\u{a722}'), ('\u{a724}', '\u{a724}'), ('\u{a726}', - '\u{a726}'), ('\u{a728}', '\u{a728}'), ('\u{a72a}', '\u{a72a}'), - ('\u{a72c}', '\u{a72c}'), ('\u{a72e}', '\u{a72e}'), ('\u{a732}', - '\u{a732}'), ('\u{a734}', '\u{a734}'), ('\u{a736}', '\u{a736}'), - ('\u{a738}', '\u{a738}'), ('\u{a73a}', '\u{a73a}'), ('\u{a73c}', - '\u{a73c}'), ('\u{a73e}', '\u{a73e}'), ('\u{a740}', '\u{a740}'), - ('\u{a742}', '\u{a742}'), ('\u{a744}', '\u{a744}'), ('\u{a746}', - '\u{a746}'), ('\u{a748}', '\u{a748}'), ('\u{a74a}', '\u{a74a}'), - ('\u{a74c}', '\u{a74c}'), ('\u{a74e}', '\u{a74e}'), ('\u{a750}', - '\u{a750}'), ('\u{a752}', '\u{a752}'), ('\u{a754}', '\u{a754}'), - ('\u{a756}', '\u{a756}'), ('\u{a758}', '\u{a758}'), ('\u{a75a}', - '\u{a75a}'), ('\u{a75c}', '\u{a75c}'), ('\u{a75e}', '\u{a75e}'), - ('\u{a760}', '\u{a760}'), ('\u{a762}', '\u{a762}'), ('\u{a764}', - '\u{a764}'), ('\u{a766}', '\u{a766}'), ('\u{a768}', '\u{a768}'), - ('\u{a76a}', '\u{a76a}'), ('\u{a76c}', '\u{a76c}'), ('\u{a76e}', - '\u{a76e}'), ('\u{a779}', '\u{a779}'), ('\u{a77b}', '\u{a77b}'), - ('\u{a77d}', '\u{a77e}'), ('\u{a780}', '\u{a780}'), ('\u{a782}', - '\u{a782}'), ('\u{a784}', '\u{a784}'), ('\u{a786}', '\u{a786}'), - ('\u{a78b}', '\u{a78b}'), ('\u{a78d}', '\u{a78d}'), ('\u{a790}', - '\u{a790}'), ('\u{a792}', '\u{a792}'), ('\u{a796}', '\u{a796}'), - ('\u{a798}', '\u{a798}'), ('\u{a79a}', '\u{a79a}'), ('\u{a79c}', - '\u{a79c}'), ('\u{a79e}', '\u{a79e}'), ('\u{a7a0}', '\u{a7a0}'), - ('\u{a7a2}', '\u{a7a2}'), ('\u{a7a4}', '\u{a7a4}'), ('\u{a7a6}', - '\u{a7a6}'), ('\u{a7a8}', '\u{a7a8}'), ('\u{a7aa}', '\u{a7ae}'), - ('\u{a7b0}', '\u{a7b4}'), ('\u{a7b6}', '\u{a7b6}'), ('\u{ff21}', - '\u{ff3a}'), ('\u{10400}', '\u{10427}'), ('\u{104b0}', '\u{104d3}'), - ('\u{10c80}', '\u{10cb2}'), ('\u{118a0}', '\u{118bf}'), ('\u{1d400}', - '\u{1d419}'), ('\u{1d434}', '\u{1d44d}'), ('\u{1d468}', '\u{1d481}'), - ('\u{1d49c}', '\u{1d49c}'), ('\u{1d49e}', '\u{1d49f}'), ('\u{1d4a2}', - '\u{1d4a2}'), ('\u{1d4a5}', '\u{1d4a6}'), ('\u{1d4a9}', '\u{1d4ac}'), - ('\u{1d4ae}', '\u{1d4b5}'), ('\u{1d4d0}', '\u{1d4e9}'), ('\u{1d504}', - '\u{1d505}'), ('\u{1d507}', '\u{1d50a}'), ('\u{1d50d}', '\u{1d514}'), - ('\u{1d516}', '\u{1d51c}'), ('\u{1d538}', '\u{1d539}'), ('\u{1d53b}', - '\u{1d53e}'), ('\u{1d540}', '\u{1d544}'), ('\u{1d546}', '\u{1d546}'), - ('\u{1d54a}', '\u{1d550}'), ('\u{1d56c}', '\u{1d585}'), ('\u{1d5a0}', - '\u{1d5b9}'), ('\u{1d5d4}', '\u{1d5ed}'), ('\u{1d608}', '\u{1d621}'), - ('\u{1d63c}', '\u{1d655}'), ('\u{1d670}', '\u{1d689}'), ('\u{1d6a8}', - '\u{1d6c0}'), ('\u{1d6e2}', '\u{1d6fa}'), ('\u{1d71c}', '\u{1d734}'), - ('\u{1d756}', '\u{1d76e}'), ('\u{1d790}', '\u{1d7a8}'), ('\u{1d7ca}', - '\u{1d7ca}'), ('\u{1e900}', '\u{1e921}'), ('\u{1f130}', '\u{1f149}'), - ('\u{1f150}', '\u{1f169}'), ('\u{1f170}', '\u{1f189}') - ]; - - pub const XID_Continue_table: &'static [(char, char)] = &[ - ('\u{30}', '\u{39}'), ('\u{41}', '\u{5a}'), ('\u{5f}', '\u{5f}'), - ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), - ('\u{b7}', '\u{b7}'), ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), - ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{2c1}'), ('\u{2c6}', '\u{2d1}'), - ('\u{2e0}', '\u{2e4}'), ('\u{2ec}', '\u{2ec}'), ('\u{2ee}', '\u{2ee}'), - ('\u{300}', '\u{374}'), ('\u{376}', '\u{377}'), ('\u{37b}', '\u{37d}'), - ('\u{37f}', '\u{37f}'), ('\u{386}', '\u{38a}'), ('\u{38c}', '\u{38c}'), - ('\u{38e}', '\u{3a1}'), ('\u{3a3}', '\u{3f5}'), ('\u{3f7}', '\u{481}'), - ('\u{483}', '\u{487}'), ('\u{48a}', '\u{52f}'), ('\u{531}', '\u{556}'), - ('\u{559}', '\u{559}'), ('\u{561}', '\u{587}'), ('\u{591}', '\u{5bd}'), - ('\u{5bf}', '\u{5bf}'), ('\u{5c1}', '\u{5c2}'), ('\u{5c4}', '\u{5c5}'), - ('\u{5c7}', '\u{5c7}'), ('\u{5d0}', '\u{5ea}'), ('\u{5f0}', '\u{5f2}'), - ('\u{610}', '\u{61a}'), ('\u{620}', '\u{669}'), ('\u{66e}', '\u{6d3}'), - ('\u{6d5}', '\u{6dc}'), ('\u{6df}', '\u{6e8}'), ('\u{6ea}', '\u{6fc}'), - ('\u{6ff}', '\u{6ff}'), ('\u{710}', '\u{74a}'), ('\u{74d}', '\u{7b1}'), - ('\u{7c0}', '\u{7f5}'), ('\u{7fa}', '\u{7fa}'), ('\u{800}', '\u{82d}'), - ('\u{840}', '\u{85b}'), ('\u{860}', '\u{86a}'), ('\u{8a0}', '\u{8b4}'), - ('\u{8b6}', '\u{8bd}'), ('\u{8d4}', '\u{8e1}'), ('\u{8e3}', '\u{963}'), - ('\u{966}', '\u{96f}'), ('\u{971}', '\u{983}'), ('\u{985}', '\u{98c}'), - ('\u{98f}', '\u{990}'), ('\u{993}', '\u{9a8}'), ('\u{9aa}', '\u{9b0}'), - ('\u{9b2}', '\u{9b2}'), ('\u{9b6}', '\u{9b9}'), ('\u{9bc}', '\u{9c4}'), - ('\u{9c7}', '\u{9c8}'), ('\u{9cb}', '\u{9ce}'), ('\u{9d7}', '\u{9d7}'), - ('\u{9dc}', '\u{9dd}'), ('\u{9df}', '\u{9e3}'), ('\u{9e6}', '\u{9f1}'), - ('\u{9fc}', '\u{9fc}'), ('\u{a01}', '\u{a03}'), ('\u{a05}', '\u{a0a}'), - ('\u{a0f}', '\u{a10}'), ('\u{a13}', '\u{a28}'), ('\u{a2a}', '\u{a30}'), - ('\u{a32}', '\u{a33}'), ('\u{a35}', '\u{a36}'), ('\u{a38}', '\u{a39}'), - ('\u{a3c}', '\u{a3c}'), ('\u{a3e}', '\u{a42}'), ('\u{a47}', '\u{a48}'), - ('\u{a4b}', '\u{a4d}'), ('\u{a51}', '\u{a51}'), ('\u{a59}', '\u{a5c}'), - ('\u{a5e}', '\u{a5e}'), ('\u{a66}', '\u{a75}'), ('\u{a81}', '\u{a83}'), - ('\u{a85}', '\u{a8d}'), ('\u{a8f}', '\u{a91}'), ('\u{a93}', '\u{aa8}'), - ('\u{aaa}', '\u{ab0}'), ('\u{ab2}', '\u{ab3}'), ('\u{ab5}', '\u{ab9}'), - ('\u{abc}', '\u{ac5}'), ('\u{ac7}', '\u{ac9}'), ('\u{acb}', '\u{acd}'), - ('\u{ad0}', '\u{ad0}'), ('\u{ae0}', '\u{ae3}'), ('\u{ae6}', '\u{aef}'), - ('\u{af9}', '\u{aff}'), ('\u{b01}', '\u{b03}'), ('\u{b05}', '\u{b0c}'), - ('\u{b0f}', '\u{b10}'), ('\u{b13}', '\u{b28}'), ('\u{b2a}', '\u{b30}'), - ('\u{b32}', '\u{b33}'), ('\u{b35}', '\u{b39}'), ('\u{b3c}', '\u{b44}'), - ('\u{b47}', '\u{b48}'), ('\u{b4b}', '\u{b4d}'), ('\u{b56}', '\u{b57}'), - ('\u{b5c}', '\u{b5d}'), ('\u{b5f}', '\u{b63}'), ('\u{b66}', '\u{b6f}'), - ('\u{b71}', '\u{b71}'), ('\u{b82}', '\u{b83}'), ('\u{b85}', '\u{b8a}'), - ('\u{b8e}', '\u{b90}'), ('\u{b92}', '\u{b95}'), ('\u{b99}', '\u{b9a}'), - ('\u{b9c}', '\u{b9c}'), ('\u{b9e}', '\u{b9f}'), ('\u{ba3}', '\u{ba4}'), - ('\u{ba8}', '\u{baa}'), ('\u{bae}', '\u{bb9}'), ('\u{bbe}', '\u{bc2}'), - ('\u{bc6}', '\u{bc8}'), ('\u{bca}', '\u{bcd}'), ('\u{bd0}', '\u{bd0}'), - ('\u{bd7}', '\u{bd7}'), ('\u{be6}', '\u{bef}'), ('\u{c00}', '\u{c03}'), - ('\u{c05}', '\u{c0c}'), ('\u{c0e}', '\u{c10}'), ('\u{c12}', '\u{c28}'), - ('\u{c2a}', '\u{c39}'), ('\u{c3d}', '\u{c44}'), ('\u{c46}', '\u{c48}'), - ('\u{c4a}', '\u{c4d}'), ('\u{c55}', '\u{c56}'), ('\u{c58}', '\u{c5a}'), - ('\u{c60}', '\u{c63}'), ('\u{c66}', '\u{c6f}'), ('\u{c80}', '\u{c83}'), - ('\u{c85}', '\u{c8c}'), ('\u{c8e}', '\u{c90}'), ('\u{c92}', '\u{ca8}'), - ('\u{caa}', '\u{cb3}'), ('\u{cb5}', '\u{cb9}'), ('\u{cbc}', '\u{cc4}'), - ('\u{cc6}', '\u{cc8}'), ('\u{cca}', '\u{ccd}'), ('\u{cd5}', '\u{cd6}'), - ('\u{cde}', '\u{cde}'), ('\u{ce0}', '\u{ce3}'), ('\u{ce6}', '\u{cef}'), - ('\u{cf1}', '\u{cf2}'), ('\u{d00}', '\u{d03}'), ('\u{d05}', '\u{d0c}'), - ('\u{d0e}', '\u{d10}'), ('\u{d12}', '\u{d44}'), ('\u{d46}', '\u{d48}'), - ('\u{d4a}', '\u{d4e}'), ('\u{d54}', '\u{d57}'), ('\u{d5f}', '\u{d63}'), - ('\u{d66}', '\u{d6f}'), ('\u{d7a}', '\u{d7f}'), ('\u{d82}', '\u{d83}'), - ('\u{d85}', '\u{d96}'), ('\u{d9a}', '\u{db1}'), ('\u{db3}', '\u{dbb}'), - ('\u{dbd}', '\u{dbd}'), ('\u{dc0}', '\u{dc6}'), ('\u{dca}', '\u{dca}'), - ('\u{dcf}', '\u{dd4}'), ('\u{dd6}', '\u{dd6}'), ('\u{dd8}', '\u{ddf}'), - ('\u{de6}', '\u{def}'), ('\u{df2}', '\u{df3}'), ('\u{e01}', '\u{e3a}'), - ('\u{e40}', '\u{e4e}'), ('\u{e50}', '\u{e59}'), ('\u{e81}', '\u{e82}'), - ('\u{e84}', '\u{e84}'), ('\u{e87}', '\u{e88}'), ('\u{e8a}', '\u{e8a}'), - ('\u{e8d}', '\u{e8d}'), ('\u{e94}', '\u{e97}'), ('\u{e99}', '\u{e9f}'), - ('\u{ea1}', '\u{ea3}'), ('\u{ea5}', '\u{ea5}'), ('\u{ea7}', '\u{ea7}'), - ('\u{eaa}', '\u{eab}'), ('\u{ead}', '\u{eb9}'), ('\u{ebb}', '\u{ebd}'), - ('\u{ec0}', '\u{ec4}'), ('\u{ec6}', '\u{ec6}'), ('\u{ec8}', '\u{ecd}'), - ('\u{ed0}', '\u{ed9}'), ('\u{edc}', '\u{edf}'), ('\u{f00}', '\u{f00}'), - ('\u{f18}', '\u{f19}'), ('\u{f20}', '\u{f29}'), ('\u{f35}', '\u{f35}'), - ('\u{f37}', '\u{f37}'), ('\u{f39}', '\u{f39}'), ('\u{f3e}', '\u{f47}'), - ('\u{f49}', '\u{f6c}'), ('\u{f71}', '\u{f84}'), ('\u{f86}', '\u{f97}'), - ('\u{f99}', '\u{fbc}'), ('\u{fc6}', '\u{fc6}'), ('\u{1000}', - '\u{1049}'), ('\u{1050}', '\u{109d}'), ('\u{10a0}', '\u{10c5}'), - ('\u{10c7}', '\u{10c7}'), ('\u{10cd}', '\u{10cd}'), ('\u{10d0}', - '\u{10fa}'), ('\u{10fc}', '\u{1248}'), ('\u{124a}', '\u{124d}'), - ('\u{1250}', '\u{1256}'), ('\u{1258}', '\u{1258}'), ('\u{125a}', - '\u{125d}'), ('\u{1260}', '\u{1288}'), ('\u{128a}', '\u{128d}'), - ('\u{1290}', '\u{12b0}'), ('\u{12b2}', '\u{12b5}'), ('\u{12b8}', - '\u{12be}'), ('\u{12c0}', '\u{12c0}'), ('\u{12c2}', '\u{12c5}'), - ('\u{12c8}', '\u{12d6}'), ('\u{12d8}', '\u{1310}'), ('\u{1312}', - '\u{1315}'), ('\u{1318}', '\u{135a}'), ('\u{135d}', '\u{135f}'), - ('\u{1369}', '\u{1371}'), ('\u{1380}', '\u{138f}'), ('\u{13a0}', - '\u{13f5}'), ('\u{13f8}', '\u{13fd}'), ('\u{1401}', '\u{166c}'), - ('\u{166f}', '\u{167f}'), ('\u{1681}', '\u{169a}'), ('\u{16a0}', - '\u{16ea}'), ('\u{16ee}', '\u{16f8}'), ('\u{1700}', '\u{170c}'), - ('\u{170e}', '\u{1714}'), ('\u{1720}', '\u{1734}'), ('\u{1740}', - '\u{1753}'), ('\u{1760}', '\u{176c}'), ('\u{176e}', '\u{1770}'), - ('\u{1772}', '\u{1773}'), ('\u{1780}', '\u{17d3}'), ('\u{17d7}', - '\u{17d7}'), ('\u{17dc}', '\u{17dd}'), ('\u{17e0}', '\u{17e9}'), - ('\u{180b}', '\u{180d}'), ('\u{1810}', '\u{1819}'), ('\u{1820}', - '\u{1877}'), ('\u{1880}', '\u{18aa}'), ('\u{18b0}', '\u{18f5}'), - ('\u{1900}', '\u{191e}'), ('\u{1920}', '\u{192b}'), ('\u{1930}', - '\u{193b}'), ('\u{1946}', '\u{196d}'), ('\u{1970}', '\u{1974}'), - ('\u{1980}', '\u{19ab}'), ('\u{19b0}', '\u{19c9}'), ('\u{19d0}', - '\u{19da}'), ('\u{1a00}', '\u{1a1b}'), ('\u{1a20}', '\u{1a5e}'), - ('\u{1a60}', '\u{1a7c}'), ('\u{1a7f}', '\u{1a89}'), ('\u{1a90}', - '\u{1a99}'), ('\u{1aa7}', '\u{1aa7}'), ('\u{1ab0}', '\u{1abd}'), - ('\u{1b00}', '\u{1b4b}'), ('\u{1b50}', '\u{1b59}'), ('\u{1b6b}', - '\u{1b73}'), ('\u{1b80}', '\u{1bf3}'), ('\u{1c00}', '\u{1c37}'), - ('\u{1c40}', '\u{1c49}'), ('\u{1c4d}', '\u{1c7d}'), ('\u{1c80}', - '\u{1c88}'), ('\u{1cd0}', '\u{1cd2}'), ('\u{1cd4}', '\u{1cf9}'), - ('\u{1d00}', '\u{1df9}'), ('\u{1dfb}', '\u{1f15}'), ('\u{1f18}', - '\u{1f1d}'), ('\u{1f20}', '\u{1f45}'), ('\u{1f48}', '\u{1f4d}'), - ('\u{1f50}', '\u{1f57}'), ('\u{1f59}', '\u{1f59}'), ('\u{1f5b}', - '\u{1f5b}'), ('\u{1f5d}', '\u{1f5d}'), ('\u{1f5f}', '\u{1f7d}'), - ('\u{1f80}', '\u{1fb4}'), ('\u{1fb6}', '\u{1fbc}'), ('\u{1fbe}', - '\u{1fbe}'), ('\u{1fc2}', '\u{1fc4}'), ('\u{1fc6}', '\u{1fcc}'), - ('\u{1fd0}', '\u{1fd3}'), ('\u{1fd6}', '\u{1fdb}'), ('\u{1fe0}', - '\u{1fec}'), ('\u{1ff2}', '\u{1ff4}'), ('\u{1ff6}', '\u{1ffc}'), - ('\u{203f}', '\u{2040}'), ('\u{2054}', '\u{2054}'), ('\u{2071}', - '\u{2071}'), ('\u{207f}', '\u{207f}'), ('\u{2090}', '\u{209c}'), - ('\u{20d0}', '\u{20dc}'), ('\u{20e1}', '\u{20e1}'), ('\u{20e5}', - '\u{20f0}'), ('\u{2102}', '\u{2102}'), ('\u{2107}', '\u{2107}'), - ('\u{210a}', '\u{2113}'), ('\u{2115}', '\u{2115}'), ('\u{2118}', - '\u{211d}'), ('\u{2124}', '\u{2124}'), ('\u{2126}', '\u{2126}'), - ('\u{2128}', '\u{2128}'), ('\u{212a}', '\u{2139}'), ('\u{213c}', - '\u{213f}'), ('\u{2145}', '\u{2149}'), ('\u{214e}', '\u{214e}'), - ('\u{2160}', '\u{2188}'), ('\u{2c00}', '\u{2c2e}'), ('\u{2c30}', - '\u{2c5e}'), ('\u{2c60}', '\u{2ce4}'), ('\u{2ceb}', '\u{2cf3}'), - ('\u{2d00}', '\u{2d25}'), ('\u{2d27}', '\u{2d27}'), ('\u{2d2d}', - '\u{2d2d}'), ('\u{2d30}', '\u{2d67}'), ('\u{2d6f}', '\u{2d6f}'), - ('\u{2d7f}', '\u{2d96}'), ('\u{2da0}', '\u{2da6}'), ('\u{2da8}', - '\u{2dae}'), ('\u{2db0}', '\u{2db6}'), ('\u{2db8}', '\u{2dbe}'), - ('\u{2dc0}', '\u{2dc6}'), ('\u{2dc8}', '\u{2dce}'), ('\u{2dd0}', - '\u{2dd6}'), ('\u{2dd8}', '\u{2dde}'), ('\u{2de0}', '\u{2dff}'), - ('\u{3005}', '\u{3007}'), ('\u{3021}', '\u{302f}'), ('\u{3031}', - '\u{3035}'), ('\u{3038}', '\u{303c}'), ('\u{3041}', '\u{3096}'), - ('\u{3099}', '\u{309a}'), ('\u{309d}', '\u{309f}'), ('\u{30a1}', - '\u{30fa}'), ('\u{30fc}', '\u{30ff}'), ('\u{3105}', '\u{312e}'), - ('\u{3131}', '\u{318e}'), ('\u{31a0}', '\u{31ba}'), ('\u{31f0}', - '\u{31ff}'), ('\u{3400}', '\u{4db5}'), ('\u{4e00}', '\u{9fea}'), - ('\u{a000}', '\u{a48c}'), ('\u{a4d0}', '\u{a4fd}'), ('\u{a500}', - '\u{a60c}'), ('\u{a610}', '\u{a62b}'), ('\u{a640}', '\u{a66f}'), - ('\u{a674}', '\u{a67d}'), ('\u{a67f}', '\u{a6f1}'), ('\u{a717}', - '\u{a71f}'), ('\u{a722}', '\u{a788}'), ('\u{a78b}', '\u{a7ae}'), - ('\u{a7b0}', '\u{a7b7}'), ('\u{a7f7}', '\u{a827}'), ('\u{a840}', - '\u{a873}'), ('\u{a880}', '\u{a8c5}'), ('\u{a8d0}', '\u{a8d9}'), - ('\u{a8e0}', '\u{a8f7}'), ('\u{a8fb}', '\u{a8fb}'), ('\u{a8fd}', - '\u{a8fd}'), ('\u{a900}', '\u{a92d}'), ('\u{a930}', '\u{a953}'), - ('\u{a960}', '\u{a97c}'), ('\u{a980}', '\u{a9c0}'), ('\u{a9cf}', - '\u{a9d9}'), ('\u{a9e0}', '\u{a9fe}'), ('\u{aa00}', '\u{aa36}'), - ('\u{aa40}', '\u{aa4d}'), ('\u{aa50}', '\u{aa59}'), ('\u{aa60}', - '\u{aa76}'), ('\u{aa7a}', '\u{aac2}'), ('\u{aadb}', '\u{aadd}'), - ('\u{aae0}', '\u{aaef}'), ('\u{aaf2}', '\u{aaf6}'), ('\u{ab01}', - '\u{ab06}'), ('\u{ab09}', '\u{ab0e}'), ('\u{ab11}', '\u{ab16}'), - ('\u{ab20}', '\u{ab26}'), ('\u{ab28}', '\u{ab2e}'), ('\u{ab30}', - '\u{ab5a}'), ('\u{ab5c}', '\u{ab65}'), ('\u{ab70}', '\u{abea}'), - ('\u{abec}', '\u{abed}'), ('\u{abf0}', '\u{abf9}'), ('\u{ac00}', - '\u{d7a3}'), ('\u{d7b0}', '\u{d7c6}'), ('\u{d7cb}', '\u{d7fb}'), - ('\u{f900}', '\u{fa6d}'), ('\u{fa70}', '\u{fad9}'), ('\u{fb00}', - '\u{fb06}'), ('\u{fb13}', '\u{fb17}'), ('\u{fb1d}', '\u{fb28}'), - ('\u{fb2a}', '\u{fb36}'), ('\u{fb38}', '\u{fb3c}'), ('\u{fb3e}', - '\u{fb3e}'), ('\u{fb40}', '\u{fb41}'), ('\u{fb43}', '\u{fb44}'), - ('\u{fb46}', '\u{fbb1}'), ('\u{fbd3}', '\u{fc5d}'), ('\u{fc64}', - '\u{fd3d}'), ('\u{fd50}', '\u{fd8f}'), ('\u{fd92}', '\u{fdc7}'), - ('\u{fdf0}', '\u{fdf9}'), ('\u{fe00}', '\u{fe0f}'), ('\u{fe20}', - '\u{fe2f}'), ('\u{fe33}', '\u{fe34}'), ('\u{fe4d}', '\u{fe4f}'), - ('\u{fe71}', '\u{fe71}'), ('\u{fe73}', '\u{fe73}'), ('\u{fe77}', - '\u{fe77}'), ('\u{fe79}', '\u{fe79}'), ('\u{fe7b}', '\u{fe7b}'), - ('\u{fe7d}', '\u{fe7d}'), ('\u{fe7f}', '\u{fefc}'), ('\u{ff10}', - '\u{ff19}'), ('\u{ff21}', '\u{ff3a}'), ('\u{ff3f}', '\u{ff3f}'), - ('\u{ff41}', '\u{ff5a}'), ('\u{ff66}', '\u{ffbe}'), ('\u{ffc2}', - '\u{ffc7}'), ('\u{ffca}', '\u{ffcf}'), ('\u{ffd2}', '\u{ffd7}'), - ('\u{ffda}', '\u{ffdc}'), ('\u{10000}', '\u{1000b}'), ('\u{1000d}', - '\u{10026}'), ('\u{10028}', '\u{1003a}'), ('\u{1003c}', '\u{1003d}'), - ('\u{1003f}', '\u{1004d}'), ('\u{10050}', '\u{1005d}'), ('\u{10080}', - '\u{100fa}'), ('\u{10140}', '\u{10174}'), ('\u{101fd}', '\u{101fd}'), - ('\u{10280}', '\u{1029c}'), ('\u{102a0}', '\u{102d0}'), ('\u{102e0}', - '\u{102e0}'), ('\u{10300}', '\u{1031f}'), ('\u{1032d}', '\u{1034a}'), - ('\u{10350}', '\u{1037a}'), ('\u{10380}', '\u{1039d}'), ('\u{103a0}', - '\u{103c3}'), ('\u{103c8}', '\u{103cf}'), ('\u{103d1}', '\u{103d5}'), - ('\u{10400}', '\u{1049d}'), ('\u{104a0}', '\u{104a9}'), ('\u{104b0}', - '\u{104d3}'), ('\u{104d8}', '\u{104fb}'), ('\u{10500}', '\u{10527}'), - ('\u{10530}', '\u{10563}'), ('\u{10600}', '\u{10736}'), ('\u{10740}', - '\u{10755}'), ('\u{10760}', '\u{10767}'), ('\u{10800}', '\u{10805}'), - ('\u{10808}', '\u{10808}'), ('\u{1080a}', '\u{10835}'), ('\u{10837}', - '\u{10838}'), ('\u{1083c}', '\u{1083c}'), ('\u{1083f}', '\u{10855}'), - ('\u{10860}', '\u{10876}'), ('\u{10880}', '\u{1089e}'), ('\u{108e0}', - '\u{108f2}'), ('\u{108f4}', '\u{108f5}'), ('\u{10900}', '\u{10915}'), - ('\u{10920}', '\u{10939}'), ('\u{10980}', '\u{109b7}'), ('\u{109be}', - '\u{109bf}'), ('\u{10a00}', '\u{10a03}'), ('\u{10a05}', '\u{10a06}'), - ('\u{10a0c}', '\u{10a13}'), ('\u{10a15}', '\u{10a17}'), ('\u{10a19}', - '\u{10a33}'), ('\u{10a38}', '\u{10a3a}'), ('\u{10a3f}', '\u{10a3f}'), - ('\u{10a60}', '\u{10a7c}'), ('\u{10a80}', '\u{10a9c}'), ('\u{10ac0}', - '\u{10ac7}'), ('\u{10ac9}', '\u{10ae6}'), ('\u{10b00}', '\u{10b35}'), - ('\u{10b40}', '\u{10b55}'), ('\u{10b60}', '\u{10b72}'), ('\u{10b80}', - '\u{10b91}'), ('\u{10c00}', '\u{10c48}'), ('\u{10c80}', '\u{10cb2}'), - ('\u{10cc0}', '\u{10cf2}'), ('\u{11000}', '\u{11046}'), ('\u{11066}', - '\u{1106f}'), ('\u{1107f}', '\u{110ba}'), ('\u{110d0}', '\u{110e8}'), - ('\u{110f0}', '\u{110f9}'), ('\u{11100}', '\u{11134}'), ('\u{11136}', - '\u{1113f}'), ('\u{11150}', '\u{11173}'), ('\u{11176}', '\u{11176}'), - ('\u{11180}', '\u{111c4}'), ('\u{111ca}', '\u{111cc}'), ('\u{111d0}', - '\u{111da}'), ('\u{111dc}', '\u{111dc}'), ('\u{11200}', '\u{11211}'), - ('\u{11213}', '\u{11237}'), ('\u{1123e}', '\u{1123e}'), ('\u{11280}', - '\u{11286}'), ('\u{11288}', '\u{11288}'), ('\u{1128a}', '\u{1128d}'), - ('\u{1128f}', '\u{1129d}'), ('\u{1129f}', '\u{112a8}'), ('\u{112b0}', - '\u{112ea}'), ('\u{112f0}', '\u{112f9}'), ('\u{11300}', '\u{11303}'), - ('\u{11305}', '\u{1130c}'), ('\u{1130f}', '\u{11310}'), ('\u{11313}', - '\u{11328}'), ('\u{1132a}', '\u{11330}'), ('\u{11332}', '\u{11333}'), - ('\u{11335}', '\u{11339}'), ('\u{1133c}', '\u{11344}'), ('\u{11347}', - '\u{11348}'), ('\u{1134b}', '\u{1134d}'), ('\u{11350}', '\u{11350}'), - ('\u{11357}', '\u{11357}'), ('\u{1135d}', '\u{11363}'), ('\u{11366}', - '\u{1136c}'), ('\u{11370}', '\u{11374}'), ('\u{11400}', '\u{1144a}'), - ('\u{11450}', '\u{11459}'), ('\u{11480}', '\u{114c5}'), ('\u{114c7}', - '\u{114c7}'), ('\u{114d0}', '\u{114d9}'), ('\u{11580}', '\u{115b5}'), - ('\u{115b8}', '\u{115c0}'), ('\u{115d8}', '\u{115dd}'), ('\u{11600}', - '\u{11640}'), ('\u{11644}', '\u{11644}'), ('\u{11650}', '\u{11659}'), - ('\u{11680}', '\u{116b7}'), ('\u{116c0}', '\u{116c9}'), ('\u{11700}', - '\u{11719}'), ('\u{1171d}', '\u{1172b}'), ('\u{11730}', '\u{11739}'), - ('\u{118a0}', '\u{118e9}'), ('\u{118ff}', '\u{118ff}'), ('\u{11a00}', - '\u{11a3e}'), ('\u{11a47}', '\u{11a47}'), ('\u{11a50}', '\u{11a83}'), - ('\u{11a86}', '\u{11a99}'), ('\u{11ac0}', '\u{11af8}'), ('\u{11c00}', - '\u{11c08}'), ('\u{11c0a}', '\u{11c36}'), ('\u{11c38}', '\u{11c40}'), - ('\u{11c50}', '\u{11c59}'), ('\u{11c72}', '\u{11c8f}'), ('\u{11c92}', - '\u{11ca7}'), ('\u{11ca9}', '\u{11cb6}'), ('\u{11d00}', '\u{11d06}'), - ('\u{11d08}', '\u{11d09}'), ('\u{11d0b}', '\u{11d36}'), ('\u{11d3a}', - '\u{11d3a}'), ('\u{11d3c}', '\u{11d3d}'), ('\u{11d3f}', '\u{11d47}'), - ('\u{11d50}', '\u{11d59}'), ('\u{12000}', '\u{12399}'), ('\u{12400}', - '\u{1246e}'), ('\u{12480}', '\u{12543}'), ('\u{13000}', '\u{1342e}'), - ('\u{14400}', '\u{14646}'), ('\u{16800}', '\u{16a38}'), ('\u{16a40}', - '\u{16a5e}'), ('\u{16a60}', '\u{16a69}'), ('\u{16ad0}', '\u{16aed}'), - ('\u{16af0}', '\u{16af4}'), ('\u{16b00}', '\u{16b36}'), ('\u{16b40}', - '\u{16b43}'), ('\u{16b50}', '\u{16b59}'), ('\u{16b63}', '\u{16b77}'), - ('\u{16b7d}', '\u{16b8f}'), ('\u{16f00}', '\u{16f44}'), ('\u{16f50}', - '\u{16f7e}'), ('\u{16f8f}', '\u{16f9f}'), ('\u{16fe0}', '\u{16fe1}'), - ('\u{17000}', '\u{187ec}'), ('\u{18800}', '\u{18af2}'), ('\u{1b000}', - '\u{1b11e}'), ('\u{1b170}', '\u{1b2fb}'), ('\u{1bc00}', '\u{1bc6a}'), - ('\u{1bc70}', '\u{1bc7c}'), ('\u{1bc80}', '\u{1bc88}'), ('\u{1bc90}', - '\u{1bc99}'), ('\u{1bc9d}', '\u{1bc9e}'), ('\u{1d165}', '\u{1d169}'), - ('\u{1d16d}', '\u{1d172}'), ('\u{1d17b}', '\u{1d182}'), ('\u{1d185}', - '\u{1d18b}'), ('\u{1d1aa}', '\u{1d1ad}'), ('\u{1d242}', '\u{1d244}'), - ('\u{1d400}', '\u{1d454}'), ('\u{1d456}', '\u{1d49c}'), ('\u{1d49e}', - '\u{1d49f}'), ('\u{1d4a2}', '\u{1d4a2}'), ('\u{1d4a5}', '\u{1d4a6}'), - ('\u{1d4a9}', '\u{1d4ac}'), ('\u{1d4ae}', '\u{1d4b9}'), ('\u{1d4bb}', - '\u{1d4bb}'), ('\u{1d4bd}', '\u{1d4c3}'), ('\u{1d4c5}', '\u{1d505}'), - ('\u{1d507}', '\u{1d50a}'), ('\u{1d50d}', '\u{1d514}'), ('\u{1d516}', - '\u{1d51c}'), ('\u{1d51e}', '\u{1d539}'), ('\u{1d53b}', '\u{1d53e}'), - ('\u{1d540}', '\u{1d544}'), ('\u{1d546}', '\u{1d546}'), ('\u{1d54a}', - '\u{1d550}'), ('\u{1d552}', '\u{1d6a5}'), ('\u{1d6a8}', '\u{1d6c0}'), - ('\u{1d6c2}', '\u{1d6da}'), ('\u{1d6dc}', '\u{1d6fa}'), ('\u{1d6fc}', - '\u{1d714}'), ('\u{1d716}', '\u{1d734}'), ('\u{1d736}', '\u{1d74e}'), - ('\u{1d750}', '\u{1d76e}'), ('\u{1d770}', '\u{1d788}'), ('\u{1d78a}', - '\u{1d7a8}'), ('\u{1d7aa}', '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7cb}'), - ('\u{1d7ce}', '\u{1d7ff}'), ('\u{1da00}', '\u{1da36}'), ('\u{1da3b}', - '\u{1da6c}'), ('\u{1da75}', '\u{1da75}'), ('\u{1da84}', '\u{1da84}'), - ('\u{1da9b}', '\u{1da9f}'), ('\u{1daa1}', '\u{1daaf}'), ('\u{1e000}', - '\u{1e006}'), ('\u{1e008}', '\u{1e018}'), ('\u{1e01b}', '\u{1e021}'), - ('\u{1e023}', '\u{1e024}'), ('\u{1e026}', '\u{1e02a}'), ('\u{1e800}', - '\u{1e8c4}'), ('\u{1e8d0}', '\u{1e8d6}'), ('\u{1e900}', '\u{1e94a}'), - ('\u{1e950}', '\u{1e959}'), ('\u{1ee00}', '\u{1ee03}'), ('\u{1ee05}', - '\u{1ee1f}'), ('\u{1ee21}', '\u{1ee22}'), ('\u{1ee24}', '\u{1ee24}'), - ('\u{1ee27}', '\u{1ee27}'), ('\u{1ee29}', '\u{1ee32}'), ('\u{1ee34}', - '\u{1ee37}'), ('\u{1ee39}', '\u{1ee39}'), ('\u{1ee3b}', '\u{1ee3b}'), - ('\u{1ee42}', '\u{1ee42}'), ('\u{1ee47}', '\u{1ee47}'), ('\u{1ee49}', - '\u{1ee49}'), ('\u{1ee4b}', '\u{1ee4b}'), ('\u{1ee4d}', '\u{1ee4f}'), - ('\u{1ee51}', '\u{1ee52}'), ('\u{1ee54}', '\u{1ee54}'), ('\u{1ee57}', - '\u{1ee57}'), ('\u{1ee59}', '\u{1ee59}'), ('\u{1ee5b}', '\u{1ee5b}'), - ('\u{1ee5d}', '\u{1ee5d}'), ('\u{1ee5f}', '\u{1ee5f}'), ('\u{1ee61}', - '\u{1ee62}'), ('\u{1ee64}', '\u{1ee64}'), ('\u{1ee67}', '\u{1ee6a}'), - ('\u{1ee6c}', '\u{1ee72}'), ('\u{1ee74}', '\u{1ee77}'), ('\u{1ee79}', - '\u{1ee7c}'), ('\u{1ee7e}', '\u{1ee7e}'), ('\u{1ee80}', '\u{1ee89}'), - ('\u{1ee8b}', '\u{1ee9b}'), ('\u{1eea1}', '\u{1eea3}'), ('\u{1eea5}', - '\u{1eea9}'), ('\u{1eeab}', '\u{1eebb}'), ('\u{20000}', '\u{2a6d6}'), - ('\u{2a700}', '\u{2b734}'), ('\u{2b740}', '\u{2b81d}'), ('\u{2b820}', - '\u{2cea1}'), ('\u{2ceb0}', '\u{2ebe0}'), ('\u{2f800}', '\u{2fa1d}'), - ('\u{e0100}', '\u{e01ef}') - ]; - - pub const XID_Start_table: &'static [(char, char)] = &[ - ('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), - ('\u{b5}', '\u{b5}'), ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), - ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{2c1}'), ('\u{2c6}', '\u{2d1}'), - ('\u{2e0}', '\u{2e4}'), ('\u{2ec}', '\u{2ec}'), ('\u{2ee}', '\u{2ee}'), - ('\u{370}', '\u{374}'), ('\u{376}', '\u{377}'), ('\u{37b}', '\u{37d}'), - ('\u{37f}', '\u{37f}'), ('\u{386}', '\u{386}'), ('\u{388}', '\u{38a}'), - ('\u{38c}', '\u{38c}'), ('\u{38e}', '\u{3a1}'), ('\u{3a3}', '\u{3f5}'), - ('\u{3f7}', '\u{481}'), ('\u{48a}', '\u{52f}'), ('\u{531}', '\u{556}'), - ('\u{559}', '\u{559}'), ('\u{561}', '\u{587}'), ('\u{5d0}', '\u{5ea}'), - ('\u{5f0}', '\u{5f2}'), ('\u{620}', '\u{64a}'), ('\u{66e}', '\u{66f}'), - ('\u{671}', '\u{6d3}'), ('\u{6d5}', '\u{6d5}'), ('\u{6e5}', '\u{6e6}'), - ('\u{6ee}', '\u{6ef}'), ('\u{6fa}', '\u{6fc}'), ('\u{6ff}', '\u{6ff}'), - ('\u{710}', '\u{710}'), ('\u{712}', '\u{72f}'), ('\u{74d}', '\u{7a5}'), - ('\u{7b1}', '\u{7b1}'), ('\u{7ca}', '\u{7ea}'), ('\u{7f4}', '\u{7f5}'), - ('\u{7fa}', '\u{7fa}'), ('\u{800}', '\u{815}'), ('\u{81a}', '\u{81a}'), - ('\u{824}', '\u{824}'), ('\u{828}', '\u{828}'), ('\u{840}', '\u{858}'), - ('\u{860}', '\u{86a}'), ('\u{8a0}', '\u{8b4}'), ('\u{8b6}', '\u{8bd}'), - ('\u{904}', '\u{939}'), ('\u{93d}', '\u{93d}'), ('\u{950}', '\u{950}'), - ('\u{958}', '\u{961}'), ('\u{971}', '\u{980}'), ('\u{985}', '\u{98c}'), - ('\u{98f}', '\u{990}'), ('\u{993}', '\u{9a8}'), ('\u{9aa}', '\u{9b0}'), - ('\u{9b2}', '\u{9b2}'), ('\u{9b6}', '\u{9b9}'), ('\u{9bd}', '\u{9bd}'), - ('\u{9ce}', '\u{9ce}'), ('\u{9dc}', '\u{9dd}'), ('\u{9df}', '\u{9e1}'), - ('\u{9f0}', '\u{9f1}'), ('\u{9fc}', '\u{9fc}'), ('\u{a05}', '\u{a0a}'), - ('\u{a0f}', '\u{a10}'), ('\u{a13}', '\u{a28}'), ('\u{a2a}', '\u{a30}'), - ('\u{a32}', '\u{a33}'), ('\u{a35}', '\u{a36}'), ('\u{a38}', '\u{a39}'), - ('\u{a59}', '\u{a5c}'), ('\u{a5e}', '\u{a5e}'), ('\u{a72}', '\u{a74}'), - ('\u{a85}', '\u{a8d}'), ('\u{a8f}', '\u{a91}'), ('\u{a93}', '\u{aa8}'), - ('\u{aaa}', '\u{ab0}'), ('\u{ab2}', '\u{ab3}'), ('\u{ab5}', '\u{ab9}'), - ('\u{abd}', '\u{abd}'), ('\u{ad0}', '\u{ad0}'), ('\u{ae0}', '\u{ae1}'), - ('\u{af9}', '\u{af9}'), ('\u{b05}', '\u{b0c}'), ('\u{b0f}', '\u{b10}'), - ('\u{b13}', '\u{b28}'), ('\u{b2a}', '\u{b30}'), ('\u{b32}', '\u{b33}'), - ('\u{b35}', '\u{b39}'), ('\u{b3d}', '\u{b3d}'), ('\u{b5c}', '\u{b5d}'), - ('\u{b5f}', '\u{b61}'), ('\u{b71}', '\u{b71}'), ('\u{b83}', '\u{b83}'), - ('\u{b85}', '\u{b8a}'), ('\u{b8e}', '\u{b90}'), ('\u{b92}', '\u{b95}'), - ('\u{b99}', '\u{b9a}'), ('\u{b9c}', '\u{b9c}'), ('\u{b9e}', '\u{b9f}'), - ('\u{ba3}', '\u{ba4}'), ('\u{ba8}', '\u{baa}'), ('\u{bae}', '\u{bb9}'), - ('\u{bd0}', '\u{bd0}'), ('\u{c05}', '\u{c0c}'), ('\u{c0e}', '\u{c10}'), - ('\u{c12}', '\u{c28}'), ('\u{c2a}', '\u{c39}'), ('\u{c3d}', '\u{c3d}'), - ('\u{c58}', '\u{c5a}'), ('\u{c60}', '\u{c61}'), ('\u{c80}', '\u{c80}'), - ('\u{c85}', '\u{c8c}'), ('\u{c8e}', '\u{c90}'), ('\u{c92}', '\u{ca8}'), - ('\u{caa}', '\u{cb3}'), ('\u{cb5}', '\u{cb9}'), ('\u{cbd}', '\u{cbd}'), - ('\u{cde}', '\u{cde}'), ('\u{ce0}', '\u{ce1}'), ('\u{cf1}', '\u{cf2}'), - ('\u{d05}', '\u{d0c}'), ('\u{d0e}', '\u{d10}'), ('\u{d12}', '\u{d3a}'), - ('\u{d3d}', '\u{d3d}'), ('\u{d4e}', '\u{d4e}'), ('\u{d54}', '\u{d56}'), - ('\u{d5f}', '\u{d61}'), ('\u{d7a}', '\u{d7f}'), ('\u{d85}', '\u{d96}'), - ('\u{d9a}', '\u{db1}'), ('\u{db3}', '\u{dbb}'), ('\u{dbd}', '\u{dbd}'), - ('\u{dc0}', '\u{dc6}'), ('\u{e01}', '\u{e30}'), ('\u{e32}', '\u{e32}'), - ('\u{e40}', '\u{e46}'), ('\u{e81}', '\u{e82}'), ('\u{e84}', '\u{e84}'), - ('\u{e87}', '\u{e88}'), ('\u{e8a}', '\u{e8a}'), ('\u{e8d}', '\u{e8d}'), - ('\u{e94}', '\u{e97}'), ('\u{e99}', '\u{e9f}'), ('\u{ea1}', '\u{ea3}'), - ('\u{ea5}', '\u{ea5}'), ('\u{ea7}', '\u{ea7}'), ('\u{eaa}', '\u{eab}'), - ('\u{ead}', '\u{eb0}'), ('\u{eb2}', '\u{eb2}'), ('\u{ebd}', '\u{ebd}'), - ('\u{ec0}', '\u{ec4}'), ('\u{ec6}', '\u{ec6}'), ('\u{edc}', '\u{edf}'), - ('\u{f00}', '\u{f00}'), ('\u{f40}', '\u{f47}'), ('\u{f49}', '\u{f6c}'), - ('\u{f88}', '\u{f8c}'), ('\u{1000}', '\u{102a}'), ('\u{103f}', - '\u{103f}'), ('\u{1050}', '\u{1055}'), ('\u{105a}', '\u{105d}'), - ('\u{1061}', '\u{1061}'), ('\u{1065}', '\u{1066}'), ('\u{106e}', - '\u{1070}'), ('\u{1075}', '\u{1081}'), ('\u{108e}', '\u{108e}'), - ('\u{10a0}', '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), ('\u{10cd}', - '\u{10cd}'), ('\u{10d0}', '\u{10fa}'), ('\u{10fc}', '\u{1248}'), - ('\u{124a}', '\u{124d}'), ('\u{1250}', '\u{1256}'), ('\u{1258}', - '\u{1258}'), ('\u{125a}', '\u{125d}'), ('\u{1260}', '\u{1288}'), - ('\u{128a}', '\u{128d}'), ('\u{1290}', '\u{12b0}'), ('\u{12b2}', - '\u{12b5}'), ('\u{12b8}', '\u{12be}'), ('\u{12c0}', '\u{12c0}'), - ('\u{12c2}', '\u{12c5}'), ('\u{12c8}', '\u{12d6}'), ('\u{12d8}', - '\u{1310}'), ('\u{1312}', '\u{1315}'), ('\u{1318}', '\u{135a}'), - ('\u{1380}', '\u{138f}'), ('\u{13a0}', '\u{13f5}'), ('\u{13f8}', - '\u{13fd}'), ('\u{1401}', '\u{166c}'), ('\u{166f}', '\u{167f}'), - ('\u{1681}', '\u{169a}'), ('\u{16a0}', '\u{16ea}'), ('\u{16ee}', - '\u{16f8}'), ('\u{1700}', '\u{170c}'), ('\u{170e}', '\u{1711}'), - ('\u{1720}', '\u{1731}'), ('\u{1740}', '\u{1751}'), ('\u{1760}', - '\u{176c}'), ('\u{176e}', '\u{1770}'), ('\u{1780}', '\u{17b3}'), - ('\u{17d7}', '\u{17d7}'), ('\u{17dc}', '\u{17dc}'), ('\u{1820}', - '\u{1877}'), ('\u{1880}', '\u{18a8}'), ('\u{18aa}', '\u{18aa}'), - ('\u{18b0}', '\u{18f5}'), ('\u{1900}', '\u{191e}'), ('\u{1950}', - '\u{196d}'), ('\u{1970}', '\u{1974}'), ('\u{1980}', '\u{19ab}'), - ('\u{19b0}', '\u{19c9}'), ('\u{1a00}', '\u{1a16}'), ('\u{1a20}', - '\u{1a54}'), ('\u{1aa7}', '\u{1aa7}'), ('\u{1b05}', '\u{1b33}'), - ('\u{1b45}', '\u{1b4b}'), ('\u{1b83}', '\u{1ba0}'), ('\u{1bae}', - '\u{1baf}'), ('\u{1bba}', '\u{1be5}'), ('\u{1c00}', '\u{1c23}'), - ('\u{1c4d}', '\u{1c4f}'), ('\u{1c5a}', '\u{1c7d}'), ('\u{1c80}', - '\u{1c88}'), ('\u{1ce9}', '\u{1cec}'), ('\u{1cee}', '\u{1cf1}'), - ('\u{1cf5}', '\u{1cf6}'), ('\u{1d00}', '\u{1dbf}'), ('\u{1e00}', - '\u{1f15}'), ('\u{1f18}', '\u{1f1d}'), ('\u{1f20}', '\u{1f45}'), - ('\u{1f48}', '\u{1f4d}'), ('\u{1f50}', '\u{1f57}'), ('\u{1f59}', - '\u{1f59}'), ('\u{1f5b}', '\u{1f5b}'), ('\u{1f5d}', '\u{1f5d}'), - ('\u{1f5f}', '\u{1f7d}'), ('\u{1f80}', '\u{1fb4}'), ('\u{1fb6}', - '\u{1fbc}'), ('\u{1fbe}', '\u{1fbe}'), ('\u{1fc2}', '\u{1fc4}'), - ('\u{1fc6}', '\u{1fcc}'), ('\u{1fd0}', '\u{1fd3}'), ('\u{1fd6}', - '\u{1fdb}'), ('\u{1fe0}', '\u{1fec}'), ('\u{1ff2}', '\u{1ff4}'), - ('\u{1ff6}', '\u{1ffc}'), ('\u{2071}', '\u{2071}'), ('\u{207f}', - '\u{207f}'), ('\u{2090}', '\u{209c}'), ('\u{2102}', '\u{2102}'), - ('\u{2107}', '\u{2107}'), ('\u{210a}', '\u{2113}'), ('\u{2115}', - '\u{2115}'), ('\u{2118}', '\u{211d}'), ('\u{2124}', '\u{2124}'), - ('\u{2126}', '\u{2126}'), ('\u{2128}', '\u{2128}'), ('\u{212a}', - '\u{2139}'), ('\u{213c}', '\u{213f}'), ('\u{2145}', '\u{2149}'), - ('\u{214e}', '\u{214e}'), ('\u{2160}', '\u{2188}'), ('\u{2c00}', - '\u{2c2e}'), ('\u{2c30}', '\u{2c5e}'), ('\u{2c60}', '\u{2ce4}'), - ('\u{2ceb}', '\u{2cee}'), ('\u{2cf2}', '\u{2cf3}'), ('\u{2d00}', - '\u{2d25}'), ('\u{2d27}', '\u{2d27}'), ('\u{2d2d}', '\u{2d2d}'), - ('\u{2d30}', '\u{2d67}'), ('\u{2d6f}', '\u{2d6f}'), ('\u{2d80}', - '\u{2d96}'), ('\u{2da0}', '\u{2da6}'), ('\u{2da8}', '\u{2dae}'), - ('\u{2db0}', '\u{2db6}'), ('\u{2db8}', '\u{2dbe}'), ('\u{2dc0}', - '\u{2dc6}'), ('\u{2dc8}', '\u{2dce}'), ('\u{2dd0}', '\u{2dd6}'), - ('\u{2dd8}', '\u{2dde}'), ('\u{3005}', '\u{3007}'), ('\u{3021}', - '\u{3029}'), ('\u{3031}', '\u{3035}'), ('\u{3038}', '\u{303c}'), - ('\u{3041}', '\u{3096}'), ('\u{309d}', '\u{309f}'), ('\u{30a1}', - '\u{30fa}'), ('\u{30fc}', '\u{30ff}'), ('\u{3105}', '\u{312e}'), - ('\u{3131}', '\u{318e}'), ('\u{31a0}', '\u{31ba}'), ('\u{31f0}', - '\u{31ff}'), ('\u{3400}', '\u{4db5}'), ('\u{4e00}', '\u{9fea}'), - ('\u{a000}', '\u{a48c}'), ('\u{a4d0}', '\u{a4fd}'), ('\u{a500}', - '\u{a60c}'), ('\u{a610}', '\u{a61f}'), ('\u{a62a}', '\u{a62b}'), - ('\u{a640}', '\u{a66e}'), ('\u{a67f}', '\u{a69d}'), ('\u{a6a0}', - '\u{a6ef}'), ('\u{a717}', '\u{a71f}'), ('\u{a722}', '\u{a788}'), - ('\u{a78b}', '\u{a7ae}'), ('\u{a7b0}', '\u{a7b7}'), ('\u{a7f7}', - '\u{a801}'), ('\u{a803}', '\u{a805}'), ('\u{a807}', '\u{a80a}'), - ('\u{a80c}', '\u{a822}'), ('\u{a840}', '\u{a873}'), ('\u{a882}', - '\u{a8b3}'), ('\u{a8f2}', '\u{a8f7}'), ('\u{a8fb}', '\u{a8fb}'), - ('\u{a8fd}', '\u{a8fd}'), ('\u{a90a}', '\u{a925}'), ('\u{a930}', - '\u{a946}'), ('\u{a960}', '\u{a97c}'), ('\u{a984}', '\u{a9b2}'), - ('\u{a9cf}', '\u{a9cf}'), ('\u{a9e0}', '\u{a9e4}'), ('\u{a9e6}', - '\u{a9ef}'), ('\u{a9fa}', '\u{a9fe}'), ('\u{aa00}', '\u{aa28}'), - ('\u{aa40}', '\u{aa42}'), ('\u{aa44}', '\u{aa4b}'), ('\u{aa60}', - '\u{aa76}'), ('\u{aa7a}', '\u{aa7a}'), ('\u{aa7e}', '\u{aaaf}'), - ('\u{aab1}', '\u{aab1}'), ('\u{aab5}', '\u{aab6}'), ('\u{aab9}', - '\u{aabd}'), ('\u{aac0}', '\u{aac0}'), ('\u{aac2}', '\u{aac2}'), - ('\u{aadb}', '\u{aadd}'), ('\u{aae0}', '\u{aaea}'), ('\u{aaf2}', - '\u{aaf4}'), ('\u{ab01}', '\u{ab06}'), ('\u{ab09}', '\u{ab0e}'), - ('\u{ab11}', '\u{ab16}'), ('\u{ab20}', '\u{ab26}'), ('\u{ab28}', - '\u{ab2e}'), ('\u{ab30}', '\u{ab5a}'), ('\u{ab5c}', '\u{ab65}'), - ('\u{ab70}', '\u{abe2}'), ('\u{ac00}', '\u{d7a3}'), ('\u{d7b0}', - '\u{d7c6}'), ('\u{d7cb}', '\u{d7fb}'), ('\u{f900}', '\u{fa6d}'), - ('\u{fa70}', '\u{fad9}'), ('\u{fb00}', '\u{fb06}'), ('\u{fb13}', - '\u{fb17}'), ('\u{fb1d}', '\u{fb1d}'), ('\u{fb1f}', '\u{fb28}'), - ('\u{fb2a}', '\u{fb36}'), ('\u{fb38}', '\u{fb3c}'), ('\u{fb3e}', - '\u{fb3e}'), ('\u{fb40}', '\u{fb41}'), ('\u{fb43}', '\u{fb44}'), - ('\u{fb46}', '\u{fbb1}'), ('\u{fbd3}', '\u{fc5d}'), ('\u{fc64}', - '\u{fd3d}'), ('\u{fd50}', '\u{fd8f}'), ('\u{fd92}', '\u{fdc7}'), - ('\u{fdf0}', '\u{fdf9}'), ('\u{fe71}', '\u{fe71}'), ('\u{fe73}', - '\u{fe73}'), ('\u{fe77}', '\u{fe77}'), ('\u{fe79}', '\u{fe79}'), - ('\u{fe7b}', '\u{fe7b}'), ('\u{fe7d}', '\u{fe7d}'), ('\u{fe7f}', - '\u{fefc}'), ('\u{ff21}', '\u{ff3a}'), ('\u{ff41}', '\u{ff5a}'), - ('\u{ff66}', '\u{ff9d}'), ('\u{ffa0}', '\u{ffbe}'), ('\u{ffc2}', - '\u{ffc7}'), ('\u{ffca}', '\u{ffcf}'), ('\u{ffd2}', '\u{ffd7}'), - ('\u{ffda}', '\u{ffdc}'), ('\u{10000}', '\u{1000b}'), ('\u{1000d}', - '\u{10026}'), ('\u{10028}', '\u{1003a}'), ('\u{1003c}', '\u{1003d}'), - ('\u{1003f}', '\u{1004d}'), ('\u{10050}', '\u{1005d}'), ('\u{10080}', - '\u{100fa}'), ('\u{10140}', '\u{10174}'), ('\u{10280}', '\u{1029c}'), - ('\u{102a0}', '\u{102d0}'), ('\u{10300}', '\u{1031f}'), ('\u{1032d}', - '\u{1034a}'), ('\u{10350}', '\u{10375}'), ('\u{10380}', '\u{1039d}'), - ('\u{103a0}', '\u{103c3}'), ('\u{103c8}', '\u{103cf}'), ('\u{103d1}', - '\u{103d5}'), ('\u{10400}', '\u{1049d}'), ('\u{104b0}', '\u{104d3}'), - ('\u{104d8}', '\u{104fb}'), ('\u{10500}', '\u{10527}'), ('\u{10530}', - '\u{10563}'), ('\u{10600}', '\u{10736}'), ('\u{10740}', '\u{10755}'), - ('\u{10760}', '\u{10767}'), ('\u{10800}', '\u{10805}'), ('\u{10808}', - '\u{10808}'), ('\u{1080a}', '\u{10835}'), ('\u{10837}', '\u{10838}'), - ('\u{1083c}', '\u{1083c}'), ('\u{1083f}', '\u{10855}'), ('\u{10860}', - '\u{10876}'), ('\u{10880}', '\u{1089e}'), ('\u{108e0}', '\u{108f2}'), - ('\u{108f4}', '\u{108f5}'), ('\u{10900}', '\u{10915}'), ('\u{10920}', - '\u{10939}'), ('\u{10980}', '\u{109b7}'), ('\u{109be}', '\u{109bf}'), - ('\u{10a00}', '\u{10a00}'), ('\u{10a10}', '\u{10a13}'), ('\u{10a15}', - '\u{10a17}'), ('\u{10a19}', '\u{10a33}'), ('\u{10a60}', '\u{10a7c}'), - ('\u{10a80}', '\u{10a9c}'), ('\u{10ac0}', '\u{10ac7}'), ('\u{10ac9}', - '\u{10ae4}'), ('\u{10b00}', '\u{10b35}'), ('\u{10b40}', '\u{10b55}'), - ('\u{10b60}', '\u{10b72}'), ('\u{10b80}', '\u{10b91}'), ('\u{10c00}', - '\u{10c48}'), ('\u{10c80}', '\u{10cb2}'), ('\u{10cc0}', '\u{10cf2}'), - ('\u{11003}', '\u{11037}'), ('\u{11083}', '\u{110af}'), ('\u{110d0}', - '\u{110e8}'), ('\u{11103}', '\u{11126}'), ('\u{11150}', '\u{11172}'), - ('\u{11176}', '\u{11176}'), ('\u{11183}', '\u{111b2}'), ('\u{111c1}', - '\u{111c4}'), ('\u{111da}', '\u{111da}'), ('\u{111dc}', '\u{111dc}'), - ('\u{11200}', '\u{11211}'), ('\u{11213}', '\u{1122b}'), ('\u{11280}', - '\u{11286}'), ('\u{11288}', '\u{11288}'), ('\u{1128a}', '\u{1128d}'), - ('\u{1128f}', '\u{1129d}'), ('\u{1129f}', '\u{112a8}'), ('\u{112b0}', - '\u{112de}'), ('\u{11305}', '\u{1130c}'), ('\u{1130f}', '\u{11310}'), - ('\u{11313}', '\u{11328}'), ('\u{1132a}', '\u{11330}'), ('\u{11332}', - '\u{11333}'), ('\u{11335}', '\u{11339}'), ('\u{1133d}', '\u{1133d}'), - ('\u{11350}', '\u{11350}'), ('\u{1135d}', '\u{11361}'), ('\u{11400}', - '\u{11434}'), ('\u{11447}', '\u{1144a}'), ('\u{11480}', '\u{114af}'), - ('\u{114c4}', '\u{114c5}'), ('\u{114c7}', '\u{114c7}'), ('\u{11580}', - '\u{115ae}'), ('\u{115d8}', '\u{115db}'), ('\u{11600}', '\u{1162f}'), - ('\u{11644}', '\u{11644}'), ('\u{11680}', '\u{116aa}'), ('\u{11700}', - '\u{11719}'), ('\u{118a0}', '\u{118df}'), ('\u{118ff}', '\u{118ff}'), - ('\u{11a00}', '\u{11a00}'), ('\u{11a0b}', '\u{11a32}'), ('\u{11a3a}', - '\u{11a3a}'), ('\u{11a50}', '\u{11a50}'), ('\u{11a5c}', '\u{11a83}'), - ('\u{11a86}', '\u{11a89}'), ('\u{11ac0}', '\u{11af8}'), ('\u{11c00}', - '\u{11c08}'), ('\u{11c0a}', '\u{11c2e}'), ('\u{11c40}', '\u{11c40}'), - ('\u{11c72}', '\u{11c8f}'), ('\u{11d00}', '\u{11d06}'), ('\u{11d08}', - '\u{11d09}'), ('\u{11d0b}', '\u{11d30}'), ('\u{11d46}', '\u{11d46}'), - ('\u{12000}', '\u{12399}'), ('\u{12400}', '\u{1246e}'), ('\u{12480}', - '\u{12543}'), ('\u{13000}', '\u{1342e}'), ('\u{14400}', '\u{14646}'), - ('\u{16800}', '\u{16a38}'), ('\u{16a40}', '\u{16a5e}'), ('\u{16ad0}', - '\u{16aed}'), ('\u{16b00}', '\u{16b2f}'), ('\u{16b40}', '\u{16b43}'), - ('\u{16b63}', '\u{16b77}'), ('\u{16b7d}', '\u{16b8f}'), ('\u{16f00}', - '\u{16f44}'), ('\u{16f50}', '\u{16f50}'), ('\u{16f93}', '\u{16f9f}'), - ('\u{16fe0}', '\u{16fe1}'), ('\u{17000}', '\u{187ec}'), ('\u{18800}', - '\u{18af2}'), ('\u{1b000}', '\u{1b11e}'), ('\u{1b170}', '\u{1b2fb}'), - ('\u{1bc00}', '\u{1bc6a}'), ('\u{1bc70}', '\u{1bc7c}'), ('\u{1bc80}', - '\u{1bc88}'), ('\u{1bc90}', '\u{1bc99}'), ('\u{1d400}', '\u{1d454}'), - ('\u{1d456}', '\u{1d49c}'), ('\u{1d49e}', '\u{1d49f}'), ('\u{1d4a2}', - '\u{1d4a2}'), ('\u{1d4a5}', '\u{1d4a6}'), ('\u{1d4a9}', '\u{1d4ac}'), - ('\u{1d4ae}', '\u{1d4b9}'), ('\u{1d4bb}', '\u{1d4bb}'), ('\u{1d4bd}', - '\u{1d4c3}'), ('\u{1d4c5}', '\u{1d505}'), ('\u{1d507}', '\u{1d50a}'), - ('\u{1d50d}', '\u{1d514}'), ('\u{1d516}', '\u{1d51c}'), ('\u{1d51e}', - '\u{1d539}'), ('\u{1d53b}', '\u{1d53e}'), ('\u{1d540}', '\u{1d544}'), - ('\u{1d546}', '\u{1d546}'), ('\u{1d54a}', '\u{1d550}'), ('\u{1d552}', - '\u{1d6a5}'), ('\u{1d6a8}', '\u{1d6c0}'), ('\u{1d6c2}', '\u{1d6da}'), - ('\u{1d6dc}', '\u{1d6fa}'), ('\u{1d6fc}', '\u{1d714}'), ('\u{1d716}', - '\u{1d734}'), ('\u{1d736}', '\u{1d74e}'), ('\u{1d750}', '\u{1d76e}'), - ('\u{1d770}', '\u{1d788}'), ('\u{1d78a}', '\u{1d7a8}'), ('\u{1d7aa}', - '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7cb}'), ('\u{1e800}', '\u{1e8c4}'), - ('\u{1e900}', '\u{1e943}'), ('\u{1ee00}', '\u{1ee03}'), ('\u{1ee05}', - '\u{1ee1f}'), ('\u{1ee21}', '\u{1ee22}'), ('\u{1ee24}', '\u{1ee24}'), - ('\u{1ee27}', '\u{1ee27}'), ('\u{1ee29}', '\u{1ee32}'), ('\u{1ee34}', - '\u{1ee37}'), ('\u{1ee39}', '\u{1ee39}'), ('\u{1ee3b}', '\u{1ee3b}'), - ('\u{1ee42}', '\u{1ee42}'), ('\u{1ee47}', '\u{1ee47}'), ('\u{1ee49}', - '\u{1ee49}'), ('\u{1ee4b}', '\u{1ee4b}'), ('\u{1ee4d}', '\u{1ee4f}'), - ('\u{1ee51}', '\u{1ee52}'), ('\u{1ee54}', '\u{1ee54}'), ('\u{1ee57}', - '\u{1ee57}'), ('\u{1ee59}', '\u{1ee59}'), ('\u{1ee5b}', '\u{1ee5b}'), - ('\u{1ee5d}', '\u{1ee5d}'), ('\u{1ee5f}', '\u{1ee5f}'), ('\u{1ee61}', - '\u{1ee62}'), ('\u{1ee64}', '\u{1ee64}'), ('\u{1ee67}', '\u{1ee6a}'), - ('\u{1ee6c}', '\u{1ee72}'), ('\u{1ee74}', '\u{1ee77}'), ('\u{1ee79}', - '\u{1ee7c}'), ('\u{1ee7e}', '\u{1ee7e}'), ('\u{1ee80}', '\u{1ee89}'), - ('\u{1ee8b}', '\u{1ee9b}'), ('\u{1eea1}', '\u{1eea3}'), ('\u{1eea5}', - '\u{1eea9}'), ('\u{1eeab}', '\u{1eebb}'), ('\u{20000}', '\u{2a6d6}'), - ('\u{2a700}', '\u{2b734}'), ('\u{2b740}', '\u{2b81d}'), ('\u{2b820}', - '\u{2cea1}'), ('\u{2ceb0}', '\u{2ebe0}'), ('\u{2f800}', '\u{2fa1d}') - ]; - -} - -pub mod script { - pub const Adlam_table: &'static [(char, char)] = &[ - ('\u{1e900}', '\u{1e94a}'), ('\u{1e950}', '\u{1e959}'), ('\u{1e95e}', - '\u{1e95f}') - ]; - - pub const Ahom_table: &'static [(char, char)] = &[ - ('\u{11700}', '\u{11719}'), ('\u{1171d}', '\u{1172b}'), ('\u{11730}', - '\u{1173f}') - ]; - - pub const Anatolian_Hieroglyphs_table: &'static [(char, char)] = &[ - ('\u{14400}', '\u{14646}') - ]; - - pub const Arabic_table: &'static [(char, char)] = &[ - ('\u{600}', '\u{604}'), ('\u{606}', '\u{60b}'), ('\u{60d}', '\u{61a}'), - ('\u{61c}', '\u{61c}'), ('\u{61e}', '\u{61e}'), ('\u{620}', '\u{63f}'), - ('\u{641}', '\u{64a}'), ('\u{656}', '\u{66f}'), ('\u{671}', '\u{6dc}'), - ('\u{6de}', '\u{6ff}'), ('\u{750}', '\u{77f}'), ('\u{8a0}', '\u{8b4}'), - ('\u{8b6}', '\u{8bd}'), ('\u{8d4}', '\u{8e1}'), ('\u{8e3}', '\u{8ff}'), - ('\u{fb50}', '\u{fbc1}'), ('\u{fbd3}', '\u{fd3d}'), ('\u{fd50}', - '\u{fd8f}'), ('\u{fd92}', '\u{fdc7}'), ('\u{fdf0}', '\u{fdfd}'), - ('\u{fe70}', '\u{fe74}'), ('\u{fe76}', '\u{fefc}'), ('\u{10e60}', - '\u{10e7e}'), ('\u{1ee00}', '\u{1ee03}'), ('\u{1ee05}', '\u{1ee1f}'), - ('\u{1ee21}', '\u{1ee22}'), ('\u{1ee24}', '\u{1ee24}'), ('\u{1ee27}', - '\u{1ee27}'), ('\u{1ee29}', '\u{1ee32}'), ('\u{1ee34}', '\u{1ee37}'), - ('\u{1ee39}', '\u{1ee39}'), ('\u{1ee3b}', '\u{1ee3b}'), ('\u{1ee42}', - '\u{1ee42}'), ('\u{1ee47}', '\u{1ee47}'), ('\u{1ee49}', '\u{1ee49}'), - ('\u{1ee4b}', '\u{1ee4b}'), ('\u{1ee4d}', '\u{1ee4f}'), ('\u{1ee51}', - '\u{1ee52}'), ('\u{1ee54}', '\u{1ee54}'), ('\u{1ee57}', '\u{1ee57}'), - ('\u{1ee59}', '\u{1ee59}'), ('\u{1ee5b}', '\u{1ee5b}'), ('\u{1ee5d}', - '\u{1ee5d}'), ('\u{1ee5f}', '\u{1ee5f}'), ('\u{1ee61}', '\u{1ee62}'), - ('\u{1ee64}', '\u{1ee64}'), ('\u{1ee67}', '\u{1ee6a}'), ('\u{1ee6c}', - '\u{1ee72}'), ('\u{1ee74}', '\u{1ee77}'), ('\u{1ee79}', '\u{1ee7c}'), - ('\u{1ee7e}', '\u{1ee7e}'), ('\u{1ee80}', '\u{1ee89}'), ('\u{1ee8b}', - '\u{1ee9b}'), ('\u{1eea1}', '\u{1eea3}'), ('\u{1eea5}', '\u{1eea9}'), - ('\u{1eeab}', '\u{1eebb}'), ('\u{1eef0}', '\u{1eef1}') - ]; - - pub const Armenian_table: &'static [(char, char)] = &[ - ('\u{531}', '\u{556}'), ('\u{559}', '\u{55f}'), ('\u{561}', '\u{587}'), - ('\u{58a}', '\u{58a}'), ('\u{58d}', '\u{58f}'), ('\u{fb13}', - '\u{fb17}') - ]; - - pub const Avestan_table: &'static [(char, char)] = &[ - ('\u{10b00}', '\u{10b35}'), ('\u{10b39}', '\u{10b3f}') - ]; - - pub const Balinese_table: &'static [(char, char)] = &[ - ('\u{1b00}', '\u{1b4b}'), ('\u{1b50}', '\u{1b7c}') - ]; - - pub const Bamum_table: &'static [(char, char)] = &[ - ('\u{a6a0}', '\u{a6f7}'), ('\u{16800}', '\u{16a38}') - ]; - - pub const Bassa_Vah_table: &'static [(char, char)] = &[ - ('\u{16ad0}', '\u{16aed}'), ('\u{16af0}', '\u{16af5}') - ]; - - pub const Batak_table: &'static [(char, char)] = &[ - ('\u{1bc0}', '\u{1bf3}'), ('\u{1bfc}', '\u{1bff}') - ]; - - pub const Bengali_table: &'static [(char, char)] = &[ - ('\u{980}', '\u{983}'), ('\u{985}', '\u{98c}'), ('\u{98f}', '\u{990}'), - ('\u{993}', '\u{9a8}'), ('\u{9aa}', '\u{9b0}'), ('\u{9b2}', '\u{9b2}'), - ('\u{9b6}', '\u{9b9}'), ('\u{9bc}', '\u{9c4}'), ('\u{9c7}', '\u{9c8}'), - ('\u{9cb}', '\u{9ce}'), ('\u{9d7}', '\u{9d7}'), ('\u{9dc}', '\u{9dd}'), - ('\u{9df}', '\u{9e3}'), ('\u{9e6}', '\u{9fd}') - ]; - - pub const Bhaiksuki_table: &'static [(char, char)] = &[ - ('\u{11c00}', '\u{11c08}'), ('\u{11c0a}', '\u{11c36}'), ('\u{11c38}', - '\u{11c45}'), ('\u{11c50}', '\u{11c6c}') - ]; - - pub const Bopomofo_table: &'static [(char, char)] = &[ - ('\u{2ea}', '\u{2eb}'), ('\u{3105}', '\u{312e}'), ('\u{31a0}', - '\u{31ba}') - ]; - - pub const Brahmi_table: &'static [(char, char)] = &[ - ('\u{11000}', '\u{1104d}'), ('\u{11052}', '\u{1106f}'), ('\u{1107f}', - '\u{1107f}') - ]; - - pub const Braille_table: &'static [(char, char)] = &[ - ('\u{2800}', '\u{28ff}') - ]; - - pub const Buginese_table: &'static [(char, char)] = &[ - ('\u{1a00}', '\u{1a1b}'), ('\u{1a1e}', '\u{1a1f}') - ]; - - pub const Buhid_table: &'static [(char, char)] = &[ - ('\u{1740}', '\u{1753}') - ]; - - pub const Canadian_Aboriginal_table: &'static [(char, char)] = &[ - ('\u{1400}', '\u{167f}'), ('\u{18b0}', '\u{18f5}') - ]; - - pub const Carian_table: &'static [(char, char)] = &[ - ('\u{102a0}', '\u{102d0}') - ]; - - pub const Caucasian_Albanian_table: &'static [(char, char)] = &[ - ('\u{10530}', '\u{10563}'), ('\u{1056f}', '\u{1056f}') - ]; - - pub const Chakma_table: &'static [(char, char)] = &[ - ('\u{11100}', '\u{11134}'), ('\u{11136}', '\u{11143}') - ]; - - pub const Cham_table: &'static [(char, char)] = &[ - ('\u{aa00}', '\u{aa36}'), ('\u{aa40}', '\u{aa4d}'), ('\u{aa50}', - '\u{aa59}'), ('\u{aa5c}', '\u{aa5f}') - ]; - - pub const Cherokee_table: &'static [(char, char)] = &[ - ('\u{13a0}', '\u{13f5}'), ('\u{13f8}', '\u{13fd}'), ('\u{ab70}', - '\u{abbf}') - ]; - - pub const Common_table: &'static [(char, char)] = &[ - ('\u{0}', '\u{40}'), ('\u{5b}', '\u{60}'), ('\u{7b}', '\u{a9}'), - ('\u{ab}', '\u{b9}'), ('\u{bb}', '\u{bf}'), ('\u{d7}', '\u{d7}'), - ('\u{f7}', '\u{f7}'), ('\u{2b9}', '\u{2df}'), ('\u{2e5}', '\u{2e9}'), - ('\u{2ec}', '\u{2ff}'), ('\u{374}', '\u{374}'), ('\u{37e}', '\u{37e}'), - ('\u{385}', '\u{385}'), ('\u{387}', '\u{387}'), ('\u{589}', '\u{589}'), - ('\u{605}', '\u{605}'), ('\u{60c}', '\u{60c}'), ('\u{61b}', '\u{61b}'), - ('\u{61f}', '\u{61f}'), ('\u{640}', '\u{640}'), ('\u{6dd}', '\u{6dd}'), - ('\u{8e2}', '\u{8e2}'), ('\u{964}', '\u{965}'), ('\u{e3f}', '\u{e3f}'), - ('\u{fd5}', '\u{fd8}'), ('\u{10fb}', '\u{10fb}'), ('\u{16eb}', - '\u{16ed}'), ('\u{1735}', '\u{1736}'), ('\u{1802}', '\u{1803}'), - ('\u{1805}', '\u{1805}'), ('\u{1cd3}', '\u{1cd3}'), ('\u{1ce1}', - '\u{1ce1}'), ('\u{1ce9}', '\u{1cec}'), ('\u{1cee}', '\u{1cf3}'), - ('\u{1cf5}', '\u{1cf7}'), ('\u{2000}', '\u{200b}'), ('\u{200e}', - '\u{2064}'), ('\u{2066}', '\u{2070}'), ('\u{2074}', '\u{207e}'), - ('\u{2080}', '\u{208e}'), ('\u{20a0}', '\u{20bf}'), ('\u{2100}', - '\u{2125}'), ('\u{2127}', '\u{2129}'), ('\u{212c}', '\u{2131}'), - ('\u{2133}', '\u{214d}'), ('\u{214f}', '\u{215f}'), ('\u{2189}', - '\u{218b}'), ('\u{2190}', '\u{2426}'), ('\u{2440}', '\u{244a}'), - ('\u{2460}', '\u{27ff}'), ('\u{2900}', '\u{2b73}'), ('\u{2b76}', - '\u{2b95}'), ('\u{2b98}', '\u{2bb9}'), ('\u{2bbd}', '\u{2bc8}'), - ('\u{2bca}', '\u{2bd2}'), ('\u{2bec}', '\u{2bef}'), ('\u{2e00}', - '\u{2e49}'), ('\u{2ff0}', '\u{2ffb}'), ('\u{3000}', '\u{3004}'), - ('\u{3006}', '\u{3006}'), ('\u{3008}', '\u{3020}'), ('\u{3030}', - '\u{3037}'), ('\u{303c}', '\u{303f}'), ('\u{309b}', '\u{309c}'), - ('\u{30a0}', '\u{30a0}'), ('\u{30fb}', '\u{30fc}'), ('\u{3190}', - '\u{319f}'), ('\u{31c0}', '\u{31e3}'), ('\u{3220}', '\u{325f}'), - ('\u{327f}', '\u{32cf}'), ('\u{3358}', '\u{33ff}'), ('\u{4dc0}', - '\u{4dff}'), ('\u{a700}', '\u{a721}'), ('\u{a788}', '\u{a78a}'), - ('\u{a830}', '\u{a839}'), ('\u{a92e}', '\u{a92e}'), ('\u{a9cf}', - '\u{a9cf}'), ('\u{ab5b}', '\u{ab5b}'), ('\u{fd3e}', '\u{fd3f}'), - ('\u{fe10}', '\u{fe19}'), ('\u{fe30}', '\u{fe52}'), ('\u{fe54}', - '\u{fe66}'), ('\u{fe68}', '\u{fe6b}'), ('\u{feff}', '\u{feff}'), - ('\u{ff01}', '\u{ff20}'), ('\u{ff3b}', '\u{ff40}'), ('\u{ff5b}', - '\u{ff65}'), ('\u{ff70}', '\u{ff70}'), ('\u{ff9e}', '\u{ff9f}'), - ('\u{ffe0}', '\u{ffe6}'), ('\u{ffe8}', '\u{ffee}'), ('\u{fff9}', - '\u{fffd}'), ('\u{10100}', '\u{10102}'), ('\u{10107}', '\u{10133}'), - ('\u{10137}', '\u{1013f}'), ('\u{10190}', '\u{1019b}'), ('\u{101d0}', - '\u{101fc}'), ('\u{102e1}', '\u{102fb}'), ('\u{1bca0}', '\u{1bca3}'), - ('\u{1d000}', '\u{1d0f5}'), ('\u{1d100}', '\u{1d126}'), ('\u{1d129}', - '\u{1d166}'), ('\u{1d16a}', '\u{1d17a}'), ('\u{1d183}', '\u{1d184}'), - ('\u{1d18c}', '\u{1d1a9}'), ('\u{1d1ae}', '\u{1d1e8}'), ('\u{1d300}', - '\u{1d356}'), ('\u{1d360}', '\u{1d371}'), ('\u{1d400}', '\u{1d454}'), - ('\u{1d456}', '\u{1d49c}'), ('\u{1d49e}', '\u{1d49f}'), ('\u{1d4a2}', - '\u{1d4a2}'), ('\u{1d4a5}', '\u{1d4a6}'), ('\u{1d4a9}', '\u{1d4ac}'), - ('\u{1d4ae}', '\u{1d4b9}'), ('\u{1d4bb}', '\u{1d4bb}'), ('\u{1d4bd}', - '\u{1d4c3}'), ('\u{1d4c5}', '\u{1d505}'), ('\u{1d507}', '\u{1d50a}'), - ('\u{1d50d}', '\u{1d514}'), ('\u{1d516}', '\u{1d51c}'), ('\u{1d51e}', - '\u{1d539}'), ('\u{1d53b}', '\u{1d53e}'), ('\u{1d540}', '\u{1d544}'), - ('\u{1d546}', '\u{1d546}'), ('\u{1d54a}', '\u{1d550}'), ('\u{1d552}', - '\u{1d6a5}'), ('\u{1d6a8}', '\u{1d7cb}'), ('\u{1d7ce}', '\u{1d7ff}'), - ('\u{1f000}', '\u{1f02b}'), ('\u{1f030}', '\u{1f093}'), ('\u{1f0a0}', - '\u{1f0ae}'), ('\u{1f0b1}', '\u{1f0bf}'), ('\u{1f0c1}', '\u{1f0cf}'), - ('\u{1f0d1}', '\u{1f0f5}'), ('\u{1f100}', '\u{1f10c}'), ('\u{1f110}', - '\u{1f12e}'), ('\u{1f130}', '\u{1f16b}'), ('\u{1f170}', '\u{1f1ac}'), - ('\u{1f1e6}', '\u{1f1ff}'), ('\u{1f201}', '\u{1f202}'), ('\u{1f210}', - '\u{1f23b}'), ('\u{1f240}', '\u{1f248}'), ('\u{1f250}', '\u{1f251}'), - ('\u{1f260}', '\u{1f265}'), ('\u{1f300}', '\u{1f6d4}'), ('\u{1f6e0}', - '\u{1f6ec}'), ('\u{1f6f0}', '\u{1f6f8}'), ('\u{1f700}', '\u{1f773}'), - ('\u{1f780}', '\u{1f7d4}'), ('\u{1f800}', '\u{1f80b}'), ('\u{1f810}', - '\u{1f847}'), ('\u{1f850}', '\u{1f859}'), ('\u{1f860}', '\u{1f887}'), - ('\u{1f890}', '\u{1f8ad}'), ('\u{1f900}', '\u{1f90b}'), ('\u{1f910}', - '\u{1f93e}'), ('\u{1f940}', '\u{1f94c}'), ('\u{1f950}', '\u{1f96b}'), - ('\u{1f980}', '\u{1f997}'), ('\u{1f9c0}', '\u{1f9c0}'), ('\u{1f9d0}', - '\u{1f9e6}'), ('\u{e0001}', '\u{e0001}'), ('\u{e0020}', '\u{e007f}') - ]; - - pub const Coptic_table: &'static [(char, char)] = &[ - ('\u{3e2}', '\u{3ef}'), ('\u{2c80}', '\u{2cf3}'), ('\u{2cf9}', - '\u{2cff}') - ]; - - pub const Cuneiform_table: &'static [(char, char)] = &[ - ('\u{12000}', '\u{12399}'), ('\u{12400}', '\u{1246e}'), ('\u{12470}', - '\u{12474}'), ('\u{12480}', '\u{12543}') - ]; - - pub const Cypriot_table: &'static [(char, char)] = &[ - ('\u{10800}', '\u{10805}'), ('\u{10808}', '\u{10808}'), ('\u{1080a}', - '\u{10835}'), ('\u{10837}', '\u{10838}'), ('\u{1083c}', '\u{1083c}'), - ('\u{1083f}', '\u{1083f}') - ]; - - pub const Cyrillic_table: &'static [(char, char)] = &[ - ('\u{400}', '\u{484}'), ('\u{487}', '\u{52f}'), ('\u{1c80}', - '\u{1c88}'), ('\u{1d2b}', '\u{1d2b}'), ('\u{1d78}', '\u{1d78}'), - ('\u{2de0}', '\u{2dff}'), ('\u{a640}', '\u{a69f}'), ('\u{fe2e}', - '\u{fe2f}') - ]; - - pub const Deseret_table: &'static [(char, char)] = &[ - ('\u{10400}', '\u{1044f}') - ]; - - pub const Devanagari_table: &'static [(char, char)] = &[ - ('\u{900}', '\u{950}'), ('\u{953}', '\u{963}'), ('\u{966}', '\u{97f}'), - ('\u{a8e0}', '\u{a8fd}') - ]; - - pub const Duployan_table: &'static [(char, char)] = &[ - ('\u{1bc00}', '\u{1bc6a}'), ('\u{1bc70}', '\u{1bc7c}'), ('\u{1bc80}', - '\u{1bc88}'), ('\u{1bc90}', '\u{1bc99}'), ('\u{1bc9c}', '\u{1bc9f}') - ]; - - pub const Egyptian_Hieroglyphs_table: &'static [(char, char)] = &[ - ('\u{13000}', '\u{1342e}') - ]; - - pub const Elbasan_table: &'static [(char, char)] = &[ - ('\u{10500}', '\u{10527}') - ]; - - pub const Ethiopic_table: &'static [(char, char)] = &[ - ('\u{1200}', '\u{1248}'), ('\u{124a}', '\u{124d}'), ('\u{1250}', - '\u{1256}'), ('\u{1258}', '\u{1258}'), ('\u{125a}', '\u{125d}'), - ('\u{1260}', '\u{1288}'), ('\u{128a}', '\u{128d}'), ('\u{1290}', - '\u{12b0}'), ('\u{12b2}', '\u{12b5}'), ('\u{12b8}', '\u{12be}'), - ('\u{12c0}', '\u{12c0}'), ('\u{12c2}', '\u{12c5}'), ('\u{12c8}', - '\u{12d6}'), ('\u{12d8}', '\u{1310}'), ('\u{1312}', '\u{1315}'), - ('\u{1318}', '\u{135a}'), ('\u{135d}', '\u{137c}'), ('\u{1380}', - '\u{1399}'), ('\u{2d80}', '\u{2d96}'), ('\u{2da0}', '\u{2da6}'), - ('\u{2da8}', '\u{2dae}'), ('\u{2db0}', '\u{2db6}'), ('\u{2db8}', - '\u{2dbe}'), ('\u{2dc0}', '\u{2dc6}'), ('\u{2dc8}', '\u{2dce}'), - ('\u{2dd0}', '\u{2dd6}'), ('\u{2dd8}', '\u{2dde}'), ('\u{ab01}', - '\u{ab06}'), ('\u{ab09}', '\u{ab0e}'), ('\u{ab11}', '\u{ab16}'), - ('\u{ab20}', '\u{ab26}'), ('\u{ab28}', '\u{ab2e}') - ]; - - pub const Georgian_table: &'static [(char, char)] = &[ - ('\u{10a0}', '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), ('\u{10cd}', - '\u{10cd}'), ('\u{10d0}', '\u{10fa}'), ('\u{10fc}', '\u{10ff}'), - ('\u{2d00}', '\u{2d25}'), ('\u{2d27}', '\u{2d27}'), ('\u{2d2d}', - '\u{2d2d}') - ]; - - pub const Glagolitic_table: &'static [(char, char)] = &[ - ('\u{2c00}', '\u{2c2e}'), ('\u{2c30}', '\u{2c5e}'), ('\u{1e000}', - '\u{1e006}'), ('\u{1e008}', '\u{1e018}'), ('\u{1e01b}', '\u{1e021}'), - ('\u{1e023}', '\u{1e024}'), ('\u{1e026}', '\u{1e02a}') - ]; - - pub const Gothic_table: &'static [(char, char)] = &[ - ('\u{10330}', '\u{1034a}') - ]; - - pub const Grantha_table: &'static [(char, char)] = &[ - ('\u{11300}', '\u{11303}'), ('\u{11305}', '\u{1130c}'), ('\u{1130f}', - '\u{11310}'), ('\u{11313}', '\u{11328}'), ('\u{1132a}', '\u{11330}'), - ('\u{11332}', '\u{11333}'), ('\u{11335}', '\u{11339}'), ('\u{1133c}', - '\u{11344}'), ('\u{11347}', '\u{11348}'), ('\u{1134b}', '\u{1134d}'), - ('\u{11350}', '\u{11350}'), ('\u{11357}', '\u{11357}'), ('\u{1135d}', - '\u{11363}'), ('\u{11366}', '\u{1136c}'), ('\u{11370}', '\u{11374}') - ]; - - pub const Greek_table: &'static [(char, char)] = &[ - ('\u{370}', '\u{373}'), ('\u{375}', '\u{377}'), ('\u{37a}', '\u{37d}'), - ('\u{37f}', '\u{37f}'), ('\u{384}', '\u{384}'), ('\u{386}', '\u{386}'), - ('\u{388}', '\u{38a}'), ('\u{38c}', '\u{38c}'), ('\u{38e}', '\u{3a1}'), - ('\u{3a3}', '\u{3e1}'), ('\u{3f0}', '\u{3ff}'), ('\u{1d26}', - '\u{1d2a}'), ('\u{1d5d}', '\u{1d61}'), ('\u{1d66}', '\u{1d6a}'), - ('\u{1dbf}', '\u{1dbf}'), ('\u{1f00}', '\u{1f15}'), ('\u{1f18}', - '\u{1f1d}'), ('\u{1f20}', '\u{1f45}'), ('\u{1f48}', '\u{1f4d}'), - ('\u{1f50}', '\u{1f57}'), ('\u{1f59}', '\u{1f59}'), ('\u{1f5b}', - '\u{1f5b}'), ('\u{1f5d}', '\u{1f5d}'), ('\u{1f5f}', '\u{1f7d}'), - ('\u{1f80}', '\u{1fb4}'), ('\u{1fb6}', '\u{1fc4}'), ('\u{1fc6}', - '\u{1fd3}'), ('\u{1fd6}', '\u{1fdb}'), ('\u{1fdd}', '\u{1fef}'), - ('\u{1ff2}', '\u{1ff4}'), ('\u{1ff6}', '\u{1ffe}'), ('\u{2126}', - '\u{2126}'), ('\u{ab65}', '\u{ab65}'), ('\u{10140}', '\u{1018e}'), - ('\u{101a0}', '\u{101a0}'), ('\u{1d200}', '\u{1d245}') - ]; - - pub const Gujarati_table: &'static [(char, char)] = &[ - ('\u{a81}', '\u{a83}'), ('\u{a85}', '\u{a8d}'), ('\u{a8f}', '\u{a91}'), - ('\u{a93}', '\u{aa8}'), ('\u{aaa}', '\u{ab0}'), ('\u{ab2}', '\u{ab3}'), - ('\u{ab5}', '\u{ab9}'), ('\u{abc}', '\u{ac5}'), ('\u{ac7}', '\u{ac9}'), - ('\u{acb}', '\u{acd}'), ('\u{ad0}', '\u{ad0}'), ('\u{ae0}', '\u{ae3}'), - ('\u{ae6}', '\u{af1}'), ('\u{af9}', '\u{aff}') - ]; - - pub const Gurmukhi_table: &'static [(char, char)] = &[ - ('\u{a01}', '\u{a03}'), ('\u{a05}', '\u{a0a}'), ('\u{a0f}', '\u{a10}'), - ('\u{a13}', '\u{a28}'), ('\u{a2a}', '\u{a30}'), ('\u{a32}', '\u{a33}'), - ('\u{a35}', '\u{a36}'), ('\u{a38}', '\u{a39}'), ('\u{a3c}', '\u{a3c}'), - ('\u{a3e}', '\u{a42}'), ('\u{a47}', '\u{a48}'), ('\u{a4b}', '\u{a4d}'), - ('\u{a51}', '\u{a51}'), ('\u{a59}', '\u{a5c}'), ('\u{a5e}', '\u{a5e}'), - ('\u{a66}', '\u{a75}') - ]; - - pub const Han_table: &'static [(char, char)] = &[ - ('\u{2e80}', '\u{2e99}'), ('\u{2e9b}', '\u{2ef3}'), ('\u{2f00}', - '\u{2fd5}'), ('\u{3005}', '\u{3005}'), ('\u{3007}', '\u{3007}'), - ('\u{3021}', '\u{3029}'), ('\u{3038}', '\u{303b}'), ('\u{3400}', - '\u{4db5}'), ('\u{4e00}', '\u{9fea}'), ('\u{f900}', '\u{fa6d}'), - ('\u{fa70}', '\u{fad9}'), ('\u{20000}', '\u{2a6d6}'), ('\u{2a700}', - '\u{2b734}'), ('\u{2b740}', '\u{2b81d}'), ('\u{2b820}', '\u{2cea1}'), - ('\u{2ceb0}', '\u{2ebe0}'), ('\u{2f800}', '\u{2fa1d}') - ]; - - pub const Hangul_table: &'static [(char, char)] = &[ - ('\u{1100}', '\u{11ff}'), ('\u{302e}', '\u{302f}'), ('\u{3131}', - '\u{318e}'), ('\u{3200}', '\u{321e}'), ('\u{3260}', '\u{327e}'), - ('\u{a960}', '\u{a97c}'), ('\u{ac00}', '\u{d7a3}'), ('\u{d7b0}', - '\u{d7c6}'), ('\u{d7cb}', '\u{d7fb}'), ('\u{ffa0}', '\u{ffbe}'), - ('\u{ffc2}', '\u{ffc7}'), ('\u{ffca}', '\u{ffcf}'), ('\u{ffd2}', - '\u{ffd7}'), ('\u{ffda}', '\u{ffdc}') - ]; - - pub const Hanunoo_table: &'static [(char, char)] = &[ - ('\u{1720}', '\u{1734}') - ]; - - pub const Hatran_table: &'static [(char, char)] = &[ - ('\u{108e0}', '\u{108f2}'), ('\u{108f4}', '\u{108f5}'), ('\u{108fb}', - '\u{108ff}') - ]; - - pub const Hebrew_table: &'static [(char, char)] = &[ - ('\u{591}', '\u{5c7}'), ('\u{5d0}', '\u{5ea}'), ('\u{5f0}', '\u{5f4}'), - ('\u{fb1d}', '\u{fb36}'), ('\u{fb38}', '\u{fb3c}'), ('\u{fb3e}', - '\u{fb3e}'), ('\u{fb40}', '\u{fb41}'), ('\u{fb43}', '\u{fb44}'), - ('\u{fb46}', '\u{fb4f}') - ]; - - pub const Hiragana_table: &'static [(char, char)] = &[ - ('\u{3041}', '\u{3096}'), ('\u{309d}', '\u{309f}'), ('\u{1b001}', - '\u{1b11e}'), ('\u{1f200}', '\u{1f200}') - ]; - - pub const Imperial_Aramaic_table: &'static [(char, char)] = &[ - ('\u{10840}', '\u{10855}'), ('\u{10857}', '\u{1085f}') - ]; - - pub const Inherited_table: &'static [(char, char)] = &[ - ('\u{300}', '\u{36f}'), ('\u{485}', '\u{486}'), ('\u{64b}', '\u{655}'), - ('\u{670}', '\u{670}'), ('\u{951}', '\u{952}'), ('\u{1ab0}', - '\u{1abe}'), ('\u{1cd0}', '\u{1cd2}'), ('\u{1cd4}', '\u{1ce0}'), - ('\u{1ce2}', '\u{1ce8}'), ('\u{1ced}', '\u{1ced}'), ('\u{1cf4}', - '\u{1cf4}'), ('\u{1cf8}', '\u{1cf9}'), ('\u{1dc0}', '\u{1df9}'), - ('\u{1dfb}', '\u{1dff}'), ('\u{200c}', '\u{200d}'), ('\u{20d0}', - '\u{20f0}'), ('\u{302a}', '\u{302d}'), ('\u{3099}', '\u{309a}'), - ('\u{fe00}', '\u{fe0f}'), ('\u{fe20}', '\u{fe2d}'), ('\u{101fd}', - '\u{101fd}'), ('\u{102e0}', '\u{102e0}'), ('\u{1d167}', '\u{1d169}'), - ('\u{1d17b}', '\u{1d182}'), ('\u{1d185}', '\u{1d18b}'), ('\u{1d1aa}', - '\u{1d1ad}'), ('\u{e0100}', '\u{e01ef}') - ]; - - pub const Inscriptional_Pahlavi_table: &'static [(char, char)] = &[ - ('\u{10b60}', '\u{10b72}'), ('\u{10b78}', '\u{10b7f}') - ]; - - pub const Inscriptional_Parthian_table: &'static [(char, char)] = &[ - ('\u{10b40}', '\u{10b55}'), ('\u{10b58}', '\u{10b5f}') - ]; - - pub const Javanese_table: &'static [(char, char)] = &[ - ('\u{a980}', '\u{a9cd}'), ('\u{a9d0}', '\u{a9d9}'), ('\u{a9de}', - '\u{a9df}') - ]; - - pub const Kaithi_table: &'static [(char, char)] = &[ - ('\u{11080}', '\u{110c1}') - ]; - - pub const Kannada_table: &'static [(char, char)] = &[ - ('\u{c80}', '\u{c83}'), ('\u{c85}', '\u{c8c}'), ('\u{c8e}', '\u{c90}'), - ('\u{c92}', '\u{ca8}'), ('\u{caa}', '\u{cb3}'), ('\u{cb5}', '\u{cb9}'), - ('\u{cbc}', '\u{cc4}'), ('\u{cc6}', '\u{cc8}'), ('\u{cca}', '\u{ccd}'), - ('\u{cd5}', '\u{cd6}'), ('\u{cde}', '\u{cde}'), ('\u{ce0}', '\u{ce3}'), - ('\u{ce6}', '\u{cef}'), ('\u{cf1}', '\u{cf2}') - ]; - - pub const Katakana_table: &'static [(char, char)] = &[ - ('\u{30a1}', '\u{30fa}'), ('\u{30fd}', '\u{30ff}'), ('\u{31f0}', - '\u{31ff}'), ('\u{32d0}', '\u{32fe}'), ('\u{3300}', '\u{3357}'), - ('\u{ff66}', '\u{ff6f}'), ('\u{ff71}', '\u{ff9d}'), ('\u{1b000}', - '\u{1b000}') - ]; - - pub const Kayah_Li_table: &'static [(char, char)] = &[ - ('\u{a900}', '\u{a92d}'), ('\u{a92f}', '\u{a92f}') - ]; - - pub const Kharoshthi_table: &'static [(char, char)] = &[ - ('\u{10a00}', '\u{10a03}'), ('\u{10a05}', '\u{10a06}'), ('\u{10a0c}', - '\u{10a13}'), ('\u{10a15}', '\u{10a17}'), ('\u{10a19}', '\u{10a33}'), - ('\u{10a38}', '\u{10a3a}'), ('\u{10a3f}', '\u{10a47}'), ('\u{10a50}', - '\u{10a58}') - ]; - - pub const Khmer_table: &'static [(char, char)] = &[ - ('\u{1780}', '\u{17dd}'), ('\u{17e0}', '\u{17e9}'), ('\u{17f0}', - '\u{17f9}'), ('\u{19e0}', '\u{19ff}') - ]; - - pub const Khojki_table: &'static [(char, char)] = &[ - ('\u{11200}', '\u{11211}'), ('\u{11213}', '\u{1123e}') - ]; - - pub const Khudawadi_table: &'static [(char, char)] = &[ - ('\u{112b0}', '\u{112ea}'), ('\u{112f0}', '\u{112f9}') - ]; - - pub const Lao_table: &'static [(char, char)] = &[ - ('\u{e81}', '\u{e82}'), ('\u{e84}', '\u{e84}'), ('\u{e87}', '\u{e88}'), - ('\u{e8a}', '\u{e8a}'), ('\u{e8d}', '\u{e8d}'), ('\u{e94}', '\u{e97}'), - ('\u{e99}', '\u{e9f}'), ('\u{ea1}', '\u{ea3}'), ('\u{ea5}', '\u{ea5}'), - ('\u{ea7}', '\u{ea7}'), ('\u{eaa}', '\u{eab}'), ('\u{ead}', '\u{eb9}'), - ('\u{ebb}', '\u{ebd}'), ('\u{ec0}', '\u{ec4}'), ('\u{ec6}', '\u{ec6}'), - ('\u{ec8}', '\u{ecd}'), ('\u{ed0}', '\u{ed9}'), ('\u{edc}', '\u{edf}') - ]; - - pub const Latin_table: &'static [(char, char)] = &[ - ('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), - ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), - ('\u{f8}', '\u{2b8}'), ('\u{2e0}', '\u{2e4}'), ('\u{1d00}', '\u{1d25}'), - ('\u{1d2c}', '\u{1d5c}'), ('\u{1d62}', '\u{1d65}'), ('\u{1d6b}', - '\u{1d77}'), ('\u{1d79}', '\u{1dbe}'), ('\u{1e00}', '\u{1eff}'), - ('\u{2071}', '\u{2071}'), ('\u{207f}', '\u{207f}'), ('\u{2090}', - '\u{209c}'), ('\u{212a}', '\u{212b}'), ('\u{2132}', '\u{2132}'), - ('\u{214e}', '\u{214e}'), ('\u{2160}', '\u{2188}'), ('\u{2c60}', - '\u{2c7f}'), ('\u{a722}', '\u{a787}'), ('\u{a78b}', '\u{a7ae}'), - ('\u{a7b0}', '\u{a7b7}'), ('\u{a7f7}', '\u{a7ff}'), ('\u{ab30}', - '\u{ab5a}'), ('\u{ab5c}', '\u{ab64}'), ('\u{fb00}', '\u{fb06}'), - ('\u{ff21}', '\u{ff3a}'), ('\u{ff41}', '\u{ff5a}') - ]; - - pub const Lepcha_table: &'static [(char, char)] = &[ - ('\u{1c00}', '\u{1c37}'), ('\u{1c3b}', '\u{1c49}'), ('\u{1c4d}', - '\u{1c4f}') - ]; - - pub const Limbu_table: &'static [(char, char)] = &[ - ('\u{1900}', '\u{191e}'), ('\u{1920}', '\u{192b}'), ('\u{1930}', - '\u{193b}'), ('\u{1940}', '\u{1940}'), ('\u{1944}', '\u{194f}') - ]; - - pub const Linear_A_table: &'static [(char, char)] = &[ - ('\u{10600}', '\u{10736}'), ('\u{10740}', '\u{10755}'), ('\u{10760}', - '\u{10767}') - ]; - - pub const Linear_B_table: &'static [(char, char)] = &[ - ('\u{10000}', '\u{1000b}'), ('\u{1000d}', '\u{10026}'), ('\u{10028}', - '\u{1003a}'), ('\u{1003c}', '\u{1003d}'), ('\u{1003f}', '\u{1004d}'), - ('\u{10050}', '\u{1005d}'), ('\u{10080}', '\u{100fa}') - ]; - - pub const Lisu_table: &'static [(char, char)] = &[ - ('\u{a4d0}', '\u{a4ff}') - ]; - - pub const Lycian_table: &'static [(char, char)] = &[ - ('\u{10280}', '\u{1029c}') - ]; - - pub const Lydian_table: &'static [(char, char)] = &[ - ('\u{10920}', '\u{10939}'), ('\u{1093f}', '\u{1093f}') - ]; - - pub const Mahajani_table: &'static [(char, char)] = &[ - ('\u{11150}', '\u{11176}') - ]; - - pub const Malayalam_table: &'static [(char, char)] = &[ - ('\u{d00}', '\u{d03}'), ('\u{d05}', '\u{d0c}'), ('\u{d0e}', '\u{d10}'), - ('\u{d12}', '\u{d44}'), ('\u{d46}', '\u{d48}'), ('\u{d4a}', '\u{d4f}'), - ('\u{d54}', '\u{d63}'), ('\u{d66}', '\u{d7f}') - ]; - - pub const Mandaic_table: &'static [(char, char)] = &[ - ('\u{840}', '\u{85b}'), ('\u{85e}', '\u{85e}') - ]; - - pub const Manichaean_table: &'static [(char, char)] = &[ - ('\u{10ac0}', '\u{10ae6}'), ('\u{10aeb}', '\u{10af6}') - ]; - - pub const Marchen_table: &'static [(char, char)] = &[ - ('\u{11c70}', '\u{11c8f}'), ('\u{11c92}', '\u{11ca7}'), ('\u{11ca9}', - '\u{11cb6}') - ]; - - pub const Masaram_Gondi_table: &'static [(char, char)] = &[ - ('\u{11d00}', '\u{11d06}'), ('\u{11d08}', '\u{11d09}'), ('\u{11d0b}', - '\u{11d36}'), ('\u{11d3a}', '\u{11d3a}'), ('\u{11d3c}', '\u{11d3d}'), - ('\u{11d3f}', '\u{11d47}'), ('\u{11d50}', '\u{11d59}') - ]; - - pub const Meetei_Mayek_table: &'static [(char, char)] = &[ - ('\u{aae0}', '\u{aaf6}'), ('\u{abc0}', '\u{abed}'), ('\u{abf0}', - '\u{abf9}') - ]; - - pub const Mende_Kikakui_table: &'static [(char, char)] = &[ - ('\u{1e800}', '\u{1e8c4}'), ('\u{1e8c7}', '\u{1e8d6}') - ]; - - pub const Meroitic_Cursive_table: &'static [(char, char)] = &[ - ('\u{109a0}', '\u{109b7}'), ('\u{109bc}', '\u{109cf}'), ('\u{109d2}', - '\u{109ff}') - ]; - - pub const Meroitic_Hieroglyphs_table: &'static [(char, char)] = &[ - ('\u{10980}', '\u{1099f}') - ]; - - pub const Miao_table: &'static [(char, char)] = &[ - ('\u{16f00}', '\u{16f44}'), ('\u{16f50}', '\u{16f7e}'), ('\u{16f8f}', - '\u{16f9f}') - ]; - - pub const Modi_table: &'static [(char, char)] = &[ - ('\u{11600}', '\u{11644}'), ('\u{11650}', '\u{11659}') - ]; - - pub const Mongolian_table: &'static [(char, char)] = &[ - ('\u{1800}', '\u{1801}'), ('\u{1804}', '\u{1804}'), ('\u{1806}', - '\u{180e}'), ('\u{1810}', '\u{1819}'), ('\u{1820}', '\u{1877}'), - ('\u{1880}', '\u{18aa}'), ('\u{11660}', '\u{1166c}') - ]; - - pub const Mro_table: &'static [(char, char)] = &[ - ('\u{16a40}', '\u{16a5e}'), ('\u{16a60}', '\u{16a69}'), ('\u{16a6e}', - '\u{16a6f}') - ]; - - pub const Multani_table: &'static [(char, char)] = &[ - ('\u{11280}', '\u{11286}'), ('\u{11288}', '\u{11288}'), ('\u{1128a}', - '\u{1128d}'), ('\u{1128f}', '\u{1129d}'), ('\u{1129f}', '\u{112a9}') - ]; - - pub const Myanmar_table: &'static [(char, char)] = &[ - ('\u{1000}', '\u{109f}'), ('\u{a9e0}', '\u{a9fe}'), ('\u{aa60}', - '\u{aa7f}') - ]; - - pub const Nabataean_table: &'static [(char, char)] = &[ - ('\u{10880}', '\u{1089e}'), ('\u{108a7}', '\u{108af}') - ]; - - pub const New_Tai_Lue_table: &'static [(char, char)] = &[ - ('\u{1980}', '\u{19ab}'), ('\u{19b0}', '\u{19c9}'), ('\u{19d0}', - '\u{19da}'), ('\u{19de}', '\u{19df}') - ]; - - pub const Newa_table: &'static [(char, char)] = &[ - ('\u{11400}', '\u{11459}'), ('\u{1145b}', '\u{1145b}'), ('\u{1145d}', - '\u{1145d}') - ]; - - pub const Nko_table: &'static [(char, char)] = &[ - ('\u{7c0}', '\u{7fa}') - ]; - - pub const Nushu_table: &'static [(char, char)] = &[ - ('\u{16fe1}', '\u{16fe1}'), ('\u{1b170}', '\u{1b2fb}') - ]; - - pub const Ogham_table: &'static [(char, char)] = &[ - ('\u{1680}', '\u{169c}') - ]; - - pub const Ol_Chiki_table: &'static [(char, char)] = &[ - ('\u{1c50}', '\u{1c7f}') - ]; - - pub const Old_Hungarian_table: &'static [(char, char)] = &[ - ('\u{10c80}', '\u{10cb2}'), ('\u{10cc0}', '\u{10cf2}'), ('\u{10cfa}', - '\u{10cff}') - ]; - - pub const Old_Italic_table: &'static [(char, char)] = &[ - ('\u{10300}', '\u{10323}'), ('\u{1032d}', '\u{1032f}') - ]; - - pub const Old_North_Arabian_table: &'static [(char, char)] = &[ - ('\u{10a80}', '\u{10a9f}') - ]; - - pub const Old_Permic_table: &'static [(char, char)] = &[ - ('\u{10350}', '\u{1037a}') - ]; - - pub const Old_Persian_table: &'static [(char, char)] = &[ - ('\u{103a0}', '\u{103c3}'), ('\u{103c8}', '\u{103d5}') - ]; - - pub const Old_South_Arabian_table: &'static [(char, char)] = &[ - ('\u{10a60}', '\u{10a7f}') - ]; - - pub const Old_Turkic_table: &'static [(char, char)] = &[ - ('\u{10c00}', '\u{10c48}') - ]; - - pub const Oriya_table: &'static [(char, char)] = &[ - ('\u{b01}', '\u{b03}'), ('\u{b05}', '\u{b0c}'), ('\u{b0f}', '\u{b10}'), - ('\u{b13}', '\u{b28}'), ('\u{b2a}', '\u{b30}'), ('\u{b32}', '\u{b33}'), - ('\u{b35}', '\u{b39}'), ('\u{b3c}', '\u{b44}'), ('\u{b47}', '\u{b48}'), - ('\u{b4b}', '\u{b4d}'), ('\u{b56}', '\u{b57}'), ('\u{b5c}', '\u{b5d}'), - ('\u{b5f}', '\u{b63}'), ('\u{b66}', '\u{b77}') - ]; - - pub const Osage_table: &'static [(char, char)] = &[ - ('\u{104b0}', '\u{104d3}'), ('\u{104d8}', '\u{104fb}') - ]; - - pub const Osmanya_table: &'static [(char, char)] = &[ - ('\u{10480}', '\u{1049d}'), ('\u{104a0}', '\u{104a9}') - ]; - - pub const Pahawh_Hmong_table: &'static [(char, char)] = &[ - ('\u{16b00}', '\u{16b45}'), ('\u{16b50}', '\u{16b59}'), ('\u{16b5b}', - '\u{16b61}'), ('\u{16b63}', '\u{16b77}'), ('\u{16b7d}', '\u{16b8f}') - ]; - - pub const Palmyrene_table: &'static [(char, char)] = &[ - ('\u{10860}', '\u{1087f}') - ]; - - pub const Pau_Cin_Hau_table: &'static [(char, char)] = &[ - ('\u{11ac0}', '\u{11af8}') - ]; - - pub const Phags_Pa_table: &'static [(char, char)] = &[ - ('\u{a840}', '\u{a877}') - ]; - - pub const Phoenician_table: &'static [(char, char)] = &[ - ('\u{10900}', '\u{1091b}'), ('\u{1091f}', '\u{1091f}') - ]; - - pub const Psalter_Pahlavi_table: &'static [(char, char)] = &[ - ('\u{10b80}', '\u{10b91}'), ('\u{10b99}', '\u{10b9c}'), ('\u{10ba9}', - '\u{10baf}') - ]; - - pub const Rejang_table: &'static [(char, char)] = &[ - ('\u{a930}', '\u{a953}'), ('\u{a95f}', '\u{a95f}') - ]; - - pub const Runic_table: &'static [(char, char)] = &[ - ('\u{16a0}', '\u{16ea}'), ('\u{16ee}', '\u{16f8}') - ]; - - pub const Samaritan_table: &'static [(char, char)] = &[ - ('\u{800}', '\u{82d}'), ('\u{830}', '\u{83e}') - ]; - - pub const Saurashtra_table: &'static [(char, char)] = &[ - ('\u{a880}', '\u{a8c5}'), ('\u{a8ce}', '\u{a8d9}') - ]; - - pub const Sharada_table: &'static [(char, char)] = &[ - ('\u{11180}', '\u{111cd}'), ('\u{111d0}', '\u{111df}') - ]; - - pub const Shavian_table: &'static [(char, char)] = &[ - ('\u{10450}', '\u{1047f}') - ]; - - pub const Siddham_table: &'static [(char, char)] = &[ - ('\u{11580}', '\u{115b5}'), ('\u{115b8}', '\u{115dd}') - ]; - - pub const SignWriting_table: &'static [(char, char)] = &[ - ('\u{1d800}', '\u{1da8b}'), ('\u{1da9b}', '\u{1da9f}'), ('\u{1daa1}', - '\u{1daaf}') - ]; - - pub const Sinhala_table: &'static [(char, char)] = &[ - ('\u{d82}', '\u{d83}'), ('\u{d85}', '\u{d96}'), ('\u{d9a}', '\u{db1}'), - ('\u{db3}', '\u{dbb}'), ('\u{dbd}', '\u{dbd}'), ('\u{dc0}', '\u{dc6}'), - ('\u{dca}', '\u{dca}'), ('\u{dcf}', '\u{dd4}'), ('\u{dd6}', '\u{dd6}'), - ('\u{dd8}', '\u{ddf}'), ('\u{de6}', '\u{def}'), ('\u{df2}', '\u{df4}'), - ('\u{111e1}', '\u{111f4}') - ]; - - pub const Sora_Sompeng_table: &'static [(char, char)] = &[ - ('\u{110d0}', '\u{110e8}'), ('\u{110f0}', '\u{110f9}') - ]; - - pub const Soyombo_table: &'static [(char, char)] = &[ - ('\u{11a50}', '\u{11a83}'), ('\u{11a86}', '\u{11a9c}'), ('\u{11a9e}', - '\u{11aa2}') - ]; - - pub const Sundanese_table: &'static [(char, char)] = &[ - ('\u{1b80}', '\u{1bbf}'), ('\u{1cc0}', '\u{1cc7}') - ]; - - pub const Syloti_Nagri_table: &'static [(char, char)] = &[ - ('\u{a800}', '\u{a82b}') - ]; - - pub const Syriac_table: &'static [(char, char)] = &[ - ('\u{700}', '\u{70d}'), ('\u{70f}', '\u{74a}'), ('\u{74d}', '\u{74f}'), - ('\u{860}', '\u{86a}') - ]; - - pub const Tagalog_table: &'static [(char, char)] = &[ - ('\u{1700}', '\u{170c}'), ('\u{170e}', '\u{1714}') - ]; - - pub const Tagbanwa_table: &'static [(char, char)] = &[ - ('\u{1760}', '\u{176c}'), ('\u{176e}', '\u{1770}'), ('\u{1772}', - '\u{1773}') - ]; - - pub const Tai_Le_table: &'static [(char, char)] = &[ - ('\u{1950}', '\u{196d}'), ('\u{1970}', '\u{1974}') - ]; - - pub const Tai_Tham_table: &'static [(char, char)] = &[ - ('\u{1a20}', '\u{1a5e}'), ('\u{1a60}', '\u{1a7c}'), ('\u{1a7f}', - '\u{1a89}'), ('\u{1a90}', '\u{1a99}'), ('\u{1aa0}', '\u{1aad}') - ]; - - pub const Tai_Viet_table: &'static [(char, char)] = &[ - ('\u{aa80}', '\u{aac2}'), ('\u{aadb}', '\u{aadf}') - ]; - - pub const Takri_table: &'static [(char, char)] = &[ - ('\u{11680}', '\u{116b7}'), ('\u{116c0}', '\u{116c9}') - ]; - - pub const Tamil_table: &'static [(char, char)] = &[ - ('\u{b82}', '\u{b83}'), ('\u{b85}', '\u{b8a}'), ('\u{b8e}', '\u{b90}'), - ('\u{b92}', '\u{b95}'), ('\u{b99}', '\u{b9a}'), ('\u{b9c}', '\u{b9c}'), - ('\u{b9e}', '\u{b9f}'), ('\u{ba3}', '\u{ba4}'), ('\u{ba8}', '\u{baa}'), - ('\u{bae}', '\u{bb9}'), ('\u{bbe}', '\u{bc2}'), ('\u{bc6}', '\u{bc8}'), - ('\u{bca}', '\u{bcd}'), ('\u{bd0}', '\u{bd0}'), ('\u{bd7}', '\u{bd7}'), - ('\u{be6}', '\u{bfa}') - ]; - - pub const Tangut_table: &'static [(char, char)] = &[ - ('\u{16fe0}', '\u{16fe0}'), ('\u{17000}', '\u{187ec}'), ('\u{18800}', - '\u{18af2}') - ]; - - pub const Telugu_table: &'static [(char, char)] = &[ - ('\u{c00}', '\u{c03}'), ('\u{c05}', '\u{c0c}'), ('\u{c0e}', '\u{c10}'), - ('\u{c12}', '\u{c28}'), ('\u{c2a}', '\u{c39}'), ('\u{c3d}', '\u{c44}'), - ('\u{c46}', '\u{c48}'), ('\u{c4a}', '\u{c4d}'), ('\u{c55}', '\u{c56}'), - ('\u{c58}', '\u{c5a}'), ('\u{c60}', '\u{c63}'), ('\u{c66}', '\u{c6f}'), - ('\u{c78}', '\u{c7f}') - ]; - - pub const Thaana_table: &'static [(char, char)] = &[ - ('\u{780}', '\u{7b1}') - ]; - - pub const Thai_table: &'static [(char, char)] = &[ - ('\u{e01}', '\u{e3a}'), ('\u{e40}', '\u{e5b}') - ]; - - pub const Tibetan_table: &'static [(char, char)] = &[ - ('\u{f00}', '\u{f47}'), ('\u{f49}', '\u{f6c}'), ('\u{f71}', '\u{f97}'), - ('\u{f99}', '\u{fbc}'), ('\u{fbe}', '\u{fcc}'), ('\u{fce}', '\u{fd4}'), - ('\u{fd9}', '\u{fda}') - ]; - - pub const Tifinagh_table: &'static [(char, char)] = &[ - ('\u{2d30}', '\u{2d67}'), ('\u{2d6f}', '\u{2d70}'), ('\u{2d7f}', - '\u{2d7f}') - ]; - - pub const Tirhuta_table: &'static [(char, char)] = &[ - ('\u{11480}', '\u{114c7}'), ('\u{114d0}', '\u{114d9}') - ]; - - pub const Ugaritic_table: &'static [(char, char)] = &[ - ('\u{10380}', '\u{1039d}'), ('\u{1039f}', '\u{1039f}') - ]; - - pub const Vai_table: &'static [(char, char)] = &[ - ('\u{a500}', '\u{a62b}') - ]; - - pub const Warang_Citi_table: &'static [(char, char)] = &[ - ('\u{118a0}', '\u{118f2}'), ('\u{118ff}', '\u{118ff}') - ]; - - pub const Yi_table: &'static [(char, char)] = &[ - ('\u{a000}', '\u{a48c}'), ('\u{a490}', '\u{a4c6}') - ]; - - pub const Zanabazar_Square_table: &'static [(char, char)] = &[ - ('\u{11a00}', '\u{11a47}') - ]; - -} - -pub mod property { - pub const Join_Control_table: &'static [(char, char)] = &[ - ('\u{200c}', '\u{200d}') - ]; - - pub const Noncharacter_Code_Point_table: &'static [(char, char)] = &[ - ('\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}') - ]; - - pub const White_Space_table: &'static [(char, char)] = &[ - ('\u{9}', '\u{d}'), ('\u{20}', '\u{20}'), ('\u{85}', '\u{85}'), - ('\u{a0}', '\u{a0}'), ('\u{1680}', '\u{1680}'), ('\u{2000}', - '\u{200a}'), ('\u{2028}', '\u{2029}'), ('\u{202f}', '\u{202f}'), - ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}') - ]; - -} - -pub mod regex { - pub const UNICODE_CLASSES: &'static [(&'static str, &'static [(char, char)])] = &[ - ("Adlam", super::script::Adlam_table), ("Ahom", - super::script::Ahom_table), ("Alphabetic", - super::derived_property::Alphabetic_table), ("Anatolian_Hieroglyphs", - super::script::Anatolian_Hieroglyphs_table), ("Arabic", - super::script::Arabic_table), ("Armenian", - super::script::Armenian_table), ("Avestan", - super::script::Avestan_table), ("Balinese", - super::script::Balinese_table), ("Bamum", super::script::Bamum_table), - ("Bassa_Vah", super::script::Bassa_Vah_table), ("Batak", - super::script::Batak_table), ("Bengali", super::script::Bengali_table), - ("Bhaiksuki", super::script::Bhaiksuki_table), ("Bopomofo", - super::script::Bopomofo_table), ("Brahmi", super::script::Brahmi_table), - ("Braille", super::script::Braille_table), ("Buginese", - super::script::Buginese_table), ("Buhid", super::script::Buhid_table), - ("C", super::general_category::C_table), ("Canadian_Aboriginal", - super::script::Canadian_Aboriginal_table), ("Carian", - super::script::Carian_table), ("Caucasian_Albanian", - super::script::Caucasian_Albanian_table), ("Cc", - super::general_category::Cc_table), ("Cf", - super::general_category::Cf_table), ("Chakma", - super::script::Chakma_table), ("Cham", super::script::Cham_table), - ("Cherokee", super::script::Cherokee_table), ("Cn", - super::general_category::Cn_table), ("Co", - super::general_category::Co_table), ("Common", - super::script::Common_table), ("Coptic", super::script::Coptic_table), - ("Cuneiform", super::script::Cuneiform_table), ("Cypriot", - super::script::Cypriot_table), ("Cyrillic", - super::script::Cyrillic_table), ("Default_Ignorable_Code_Point", - super::derived_property::Default_Ignorable_Code_Point_table), - ("Deseret", super::script::Deseret_table), ("Devanagari", - super::script::Devanagari_table), ("Duployan", - super::script::Duployan_table), ("Egyptian_Hieroglyphs", - super::script::Egyptian_Hieroglyphs_table), ("Elbasan", - super::script::Elbasan_table), ("Ethiopic", - super::script::Ethiopic_table), ("Georgian", - super::script::Georgian_table), ("Glagolitic", - super::script::Glagolitic_table), ("Gothic", - super::script::Gothic_table), ("Grantha", super::script::Grantha_table), - ("Grapheme_Extend", super::derived_property::Grapheme_Extend_table), - ("Greek", super::script::Greek_table), ("Gujarati", - super::script::Gujarati_table), ("Gurmukhi", - super::script::Gurmukhi_table), ("Han", super::script::Han_table), - ("Hangul", super::script::Hangul_table), ("Hanunoo", - super::script::Hanunoo_table), ("Hatran", super::script::Hatran_table), - ("Hebrew", super::script::Hebrew_table), ("Hiragana", - super::script::Hiragana_table), ("Imperial_Aramaic", - super::script::Imperial_Aramaic_table), ("Inherited", - super::script::Inherited_table), ("Inscriptional_Pahlavi", - super::script::Inscriptional_Pahlavi_table), ("Inscriptional_Parthian", - super::script::Inscriptional_Parthian_table), ("Javanese", - super::script::Javanese_table), ("Join_Control", - super::property::Join_Control_table), ("Kaithi", - super::script::Kaithi_table), ("Kannada", super::script::Kannada_table), - ("Katakana", super::script::Katakana_table), ("Kayah_Li", - super::script::Kayah_Li_table), ("Kharoshthi", - super::script::Kharoshthi_table), ("Khmer", super::script::Khmer_table), - ("Khojki", super::script::Khojki_table), ("Khudawadi", - super::script::Khudawadi_table), ("L", - super::general_category::L_table), ("LC", - super::general_category::LC_table), ("Lao", super::script::Lao_table), - ("Latin", super::script::Latin_table), ("Lepcha", - super::script::Lepcha_table), ("Limbu", super::script::Limbu_table), - ("Linear_A", super::script::Linear_A_table), ("Linear_B", - super::script::Linear_B_table), ("Lisu", super::script::Lisu_table), - ("Ll", super::general_category::Ll_table), ("Lm", - super::general_category::Lm_table), ("Lo", - super::general_category::Lo_table), ("Lowercase", - super::derived_property::Lowercase_table), ("Lt", - super::general_category::Lt_table), ("Lu", - super::general_category::Lu_table), ("Lycian", - super::script::Lycian_table), ("Lydian", super::script::Lydian_table), - ("M", super::general_category::M_table), ("Mahajani", - super::script::Mahajani_table), ("Malayalam", - super::script::Malayalam_table), ("Mandaic", - super::script::Mandaic_table), ("Manichaean", - super::script::Manichaean_table), ("Marchen", - super::script::Marchen_table), ("Masaram_Gondi", - super::script::Masaram_Gondi_table), ("Mc", - super::general_category::Mc_table), ("Me", - super::general_category::Me_table), ("Meetei_Mayek", - super::script::Meetei_Mayek_table), ("Mende_Kikakui", - super::script::Mende_Kikakui_table), ("Meroitic_Cursive", - super::script::Meroitic_Cursive_table), ("Meroitic_Hieroglyphs", - super::script::Meroitic_Hieroglyphs_table), ("Miao", - super::script::Miao_table), ("Mn", super::general_category::Mn_table), - ("Modi", super::script::Modi_table), ("Mongolian", - super::script::Mongolian_table), ("Mro", super::script::Mro_table), - ("Multani", super::script::Multani_table), ("Myanmar", - super::script::Myanmar_table), ("N", super::general_category::N_table), - ("Nabataean", super::script::Nabataean_table), ("Nd", - super::general_category::Nd_table), ("New_Tai_Lue", - super::script::New_Tai_Lue_table), ("Newa", super::script::Newa_table), - ("Nko", super::script::Nko_table), ("Nl", - super::general_category::Nl_table), ("No", - super::general_category::No_table), ("Noncharacter_Code_Point", - super::property::Noncharacter_Code_Point_table), ("Nushu", - super::script::Nushu_table), ("Ogham", super::script::Ogham_table), - ("Ol_Chiki", super::script::Ol_Chiki_table), ("Old_Hungarian", - super::script::Old_Hungarian_table), ("Old_Italic", - super::script::Old_Italic_table), ("Old_North_Arabian", - super::script::Old_North_Arabian_table), ("Old_Permic", - super::script::Old_Permic_table), ("Old_Persian", - super::script::Old_Persian_table), ("Old_South_Arabian", - super::script::Old_South_Arabian_table), ("Old_Turkic", - super::script::Old_Turkic_table), ("Oriya", super::script::Oriya_table), - ("Osage", super::script::Osage_table), ("Osmanya", - super::script::Osmanya_table), ("P", super::general_category::P_table), - ("Pahawh_Hmong", super::script::Pahawh_Hmong_table), ("Palmyrene", - super::script::Palmyrene_table), ("Pau_Cin_Hau", - super::script::Pau_Cin_Hau_table), ("Pc", - super::general_category::Pc_table), ("Pd", - super::general_category::Pd_table), ("Pe", - super::general_category::Pe_table), ("Pf", - super::general_category::Pf_table), ("Phags_Pa", - super::script::Phags_Pa_table), ("Phoenician", - super::script::Phoenician_table), ("Pi", - super::general_category::Pi_table), ("Po", - super::general_category::Po_table), ("Ps", - super::general_category::Ps_table), ("Psalter_Pahlavi", - super::script::Psalter_Pahlavi_table), ("Rejang", - super::script::Rejang_table), ("Runic", super::script::Runic_table), - ("S", super::general_category::S_table), ("Samaritan", - super::script::Samaritan_table), ("Saurashtra", - super::script::Saurashtra_table), ("Sc", - super::general_category::Sc_table), ("Sharada", - super::script::Sharada_table), ("Shavian", - super::script::Shavian_table), ("Siddham", - super::script::Siddham_table), ("SignWriting", - super::script::SignWriting_table), ("Sinhala", - super::script::Sinhala_table), ("Sk", - super::general_category::Sk_table), ("Sm", - super::general_category::Sm_table), ("So", - super::general_category::So_table), ("Sora_Sompeng", - super::script::Sora_Sompeng_table), ("Soyombo", - super::script::Soyombo_table), ("Sundanese", - super::script::Sundanese_table), ("Syloti_Nagri", - super::script::Syloti_Nagri_table), ("Syriac", - super::script::Syriac_table), ("Tagalog", super::script::Tagalog_table), - ("Tagbanwa", super::script::Tagbanwa_table), ("Tai_Le", - super::script::Tai_Le_table), ("Tai_Tham", - super::script::Tai_Tham_table), ("Tai_Viet", - super::script::Tai_Viet_table), ("Takri", super::script::Takri_table), - ("Tamil", super::script::Tamil_table), ("Tangut", - super::script::Tangut_table), ("Telugu", super::script::Telugu_table), - ("Thaana", super::script::Thaana_table), ("Thai", - super::script::Thai_table), ("Tibetan", super::script::Tibetan_table), - ("Tifinagh", super::script::Tifinagh_table), ("Tirhuta", - super::script::Tirhuta_table), ("Ugaritic", - super::script::Ugaritic_table), ("Uppercase", - super::derived_property::Uppercase_table), ("Vai", - super::script::Vai_table), ("Warang_Citi", - super::script::Warang_Citi_table), ("White_Space", - super::property::White_Space_table), ("XID_Continue", - super::derived_property::XID_Continue_table), ("XID_Start", - super::derived_property::XID_Start_table), ("Yi", - super::script::Yi_table), ("Z", super::general_category::Z_table), - ("Zanabazar_Square", super::script::Zanabazar_Square_table), ("Zl", - super::general_category::Zl_table), ("Zp", - super::general_category::Zp_table), ("Zs", - super::general_category::Zs_table) - ]; - - pub const PERLD: &'static [(char, char)] = super::general_category::Nd_table; - - pub const PERLS: &'static [(char, char)] = super::property::White_Space_table; - - pub const PERLW: &'static [(char, char)] = &[ - ('\u{30}', '\u{39}'), ('\u{41}', '\u{5a}'), ('\u{5f}', '\u{5f}'), - ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), - ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), - ('\u{f8}', '\u{2c1}'), ('\u{2c6}', '\u{2d1}'), ('\u{2e0}', '\u{2e4}'), - ('\u{2ec}', '\u{2ec}'), ('\u{2ee}', '\u{2ee}'), ('\u{300}', '\u{374}'), - ('\u{376}', '\u{377}'), ('\u{37a}', '\u{37d}'), ('\u{37f}', '\u{37f}'), - ('\u{386}', '\u{386}'), ('\u{388}', '\u{38a}'), ('\u{38c}', '\u{38c}'), - ('\u{38e}', '\u{3a1}'), ('\u{3a3}', '\u{3f5}'), ('\u{3f7}', '\u{481}'), - ('\u{483}', '\u{52f}'), ('\u{531}', '\u{556}'), ('\u{559}', '\u{559}'), - ('\u{561}', '\u{587}'), ('\u{591}', '\u{5bd}'), ('\u{5bf}', '\u{5bf}'), - ('\u{5c1}', '\u{5c2}'), ('\u{5c4}', '\u{5c5}'), ('\u{5c7}', '\u{5c7}'), - ('\u{5d0}', '\u{5ea}'), ('\u{5f0}', '\u{5f2}'), ('\u{610}', '\u{61a}'), - ('\u{620}', '\u{669}'), ('\u{66e}', '\u{6d3}'), ('\u{6d5}', '\u{6dc}'), - ('\u{6df}', '\u{6e8}'), ('\u{6ea}', '\u{6fc}'), ('\u{6ff}', '\u{6ff}'), - ('\u{710}', '\u{74a}'), ('\u{74d}', '\u{7b1}'), ('\u{7c0}', '\u{7f5}'), - ('\u{7fa}', '\u{7fa}'), ('\u{800}', '\u{82d}'), ('\u{840}', '\u{85b}'), - ('\u{860}', '\u{86a}'), ('\u{8a0}', '\u{8b4}'), ('\u{8b6}', '\u{8bd}'), - ('\u{8d4}', '\u{8e1}'), ('\u{8e3}', '\u{963}'), ('\u{966}', '\u{96f}'), - ('\u{971}', '\u{983}'), ('\u{985}', '\u{98c}'), ('\u{98f}', '\u{990}'), - ('\u{993}', '\u{9a8}'), ('\u{9aa}', '\u{9b0}'), ('\u{9b2}', '\u{9b2}'), - ('\u{9b6}', '\u{9b9}'), ('\u{9bc}', '\u{9c4}'), ('\u{9c7}', '\u{9c8}'), - ('\u{9cb}', '\u{9ce}'), ('\u{9d7}', '\u{9d7}'), ('\u{9dc}', '\u{9dd}'), - ('\u{9df}', '\u{9e3}'), ('\u{9e6}', '\u{9f1}'), ('\u{9fc}', '\u{9fc}'), - ('\u{a01}', '\u{a03}'), ('\u{a05}', '\u{a0a}'), ('\u{a0f}', '\u{a10}'), - ('\u{a13}', '\u{a28}'), ('\u{a2a}', '\u{a30}'), ('\u{a32}', '\u{a33}'), - ('\u{a35}', '\u{a36}'), ('\u{a38}', '\u{a39}'), ('\u{a3c}', '\u{a3c}'), - ('\u{a3e}', '\u{a42}'), ('\u{a47}', '\u{a48}'), ('\u{a4b}', '\u{a4d}'), - ('\u{a51}', '\u{a51}'), ('\u{a59}', '\u{a5c}'), ('\u{a5e}', '\u{a5e}'), - ('\u{a66}', '\u{a75}'), ('\u{a81}', '\u{a83}'), ('\u{a85}', '\u{a8d}'), - ('\u{a8f}', '\u{a91}'), ('\u{a93}', '\u{aa8}'), ('\u{aaa}', '\u{ab0}'), - ('\u{ab2}', '\u{ab3}'), ('\u{ab5}', '\u{ab9}'), ('\u{abc}', '\u{ac5}'), - ('\u{ac7}', '\u{ac9}'), ('\u{acb}', '\u{acd}'), ('\u{ad0}', '\u{ad0}'), - ('\u{ae0}', '\u{ae3}'), ('\u{ae6}', '\u{aef}'), ('\u{af9}', '\u{aff}'), - ('\u{b01}', '\u{b03}'), ('\u{b05}', '\u{b0c}'), ('\u{b0f}', '\u{b10}'), - ('\u{b13}', '\u{b28}'), ('\u{b2a}', '\u{b30}'), ('\u{b32}', '\u{b33}'), - ('\u{b35}', '\u{b39}'), ('\u{b3c}', '\u{b44}'), ('\u{b47}', '\u{b48}'), - ('\u{b4b}', '\u{b4d}'), ('\u{b56}', '\u{b57}'), ('\u{b5c}', '\u{b5d}'), - ('\u{b5f}', '\u{b63}'), ('\u{b66}', '\u{b6f}'), ('\u{b71}', '\u{b71}'), - ('\u{b82}', '\u{b83}'), ('\u{b85}', '\u{b8a}'), ('\u{b8e}', '\u{b90}'), - ('\u{b92}', '\u{b95}'), ('\u{b99}', '\u{b9a}'), ('\u{b9c}', '\u{b9c}'), - ('\u{b9e}', '\u{b9f}'), ('\u{ba3}', '\u{ba4}'), ('\u{ba8}', '\u{baa}'), - ('\u{bae}', '\u{bb9}'), ('\u{bbe}', '\u{bc2}'), ('\u{bc6}', '\u{bc8}'), - ('\u{bca}', '\u{bcd}'), ('\u{bd0}', '\u{bd0}'), ('\u{bd7}', '\u{bd7}'), - ('\u{be6}', '\u{bef}'), ('\u{c00}', '\u{c03}'), ('\u{c05}', '\u{c0c}'), - ('\u{c0e}', '\u{c10}'), ('\u{c12}', '\u{c28}'), ('\u{c2a}', '\u{c39}'), - ('\u{c3d}', '\u{c44}'), ('\u{c46}', '\u{c48}'), ('\u{c4a}', '\u{c4d}'), - ('\u{c55}', '\u{c56}'), ('\u{c58}', '\u{c5a}'), ('\u{c60}', '\u{c63}'), - ('\u{c66}', '\u{c6f}'), ('\u{c80}', '\u{c83}'), ('\u{c85}', '\u{c8c}'), - ('\u{c8e}', '\u{c90}'), ('\u{c92}', '\u{ca8}'), ('\u{caa}', '\u{cb3}'), - ('\u{cb5}', '\u{cb9}'), ('\u{cbc}', '\u{cc4}'), ('\u{cc6}', '\u{cc8}'), - ('\u{cca}', '\u{ccd}'), ('\u{cd5}', '\u{cd6}'), ('\u{cde}', '\u{cde}'), - ('\u{ce0}', '\u{ce3}'), ('\u{ce6}', '\u{cef}'), ('\u{cf1}', '\u{cf2}'), - ('\u{d00}', '\u{d03}'), ('\u{d05}', '\u{d0c}'), ('\u{d0e}', '\u{d10}'), - ('\u{d12}', '\u{d44}'), ('\u{d46}', '\u{d48}'), ('\u{d4a}', '\u{d4e}'), - ('\u{d54}', '\u{d57}'), ('\u{d5f}', '\u{d63}'), ('\u{d66}', '\u{d6f}'), - ('\u{d7a}', '\u{d7f}'), ('\u{d82}', '\u{d83}'), ('\u{d85}', '\u{d96}'), - ('\u{d9a}', '\u{db1}'), ('\u{db3}', '\u{dbb}'), ('\u{dbd}', '\u{dbd}'), - ('\u{dc0}', '\u{dc6}'), ('\u{dca}', '\u{dca}'), ('\u{dcf}', '\u{dd4}'), - ('\u{dd6}', '\u{dd6}'), ('\u{dd8}', '\u{ddf}'), ('\u{de6}', '\u{def}'), - ('\u{df2}', '\u{df3}'), ('\u{e01}', '\u{e3a}'), ('\u{e40}', '\u{e4e}'), - ('\u{e50}', '\u{e59}'), ('\u{e81}', '\u{e82}'), ('\u{e84}', '\u{e84}'), - ('\u{e87}', '\u{e88}'), ('\u{e8a}', '\u{e8a}'), ('\u{e8d}', '\u{e8d}'), - ('\u{e94}', '\u{e97}'), ('\u{e99}', '\u{e9f}'), ('\u{ea1}', '\u{ea3}'), - ('\u{ea5}', '\u{ea5}'), ('\u{ea7}', '\u{ea7}'), ('\u{eaa}', '\u{eab}'), - ('\u{ead}', '\u{eb9}'), ('\u{ebb}', '\u{ebd}'), ('\u{ec0}', '\u{ec4}'), - ('\u{ec6}', '\u{ec6}'), ('\u{ec8}', '\u{ecd}'), ('\u{ed0}', '\u{ed9}'), - ('\u{edc}', '\u{edf}'), ('\u{f00}', '\u{f00}'), ('\u{f18}', '\u{f19}'), - ('\u{f20}', '\u{f29}'), ('\u{f35}', '\u{f35}'), ('\u{f37}', '\u{f37}'), - ('\u{f39}', '\u{f39}'), ('\u{f3e}', '\u{f47}'), ('\u{f49}', '\u{f6c}'), - ('\u{f71}', '\u{f84}'), ('\u{f86}', '\u{f97}'), ('\u{f99}', '\u{fbc}'), - ('\u{fc6}', '\u{fc6}'), ('\u{1000}', '\u{1049}'), ('\u{1050}', - '\u{109d}'), ('\u{10a0}', '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), - ('\u{10cd}', '\u{10cd}'), ('\u{10d0}', '\u{10fa}'), ('\u{10fc}', - '\u{1248}'), ('\u{124a}', '\u{124d}'), ('\u{1250}', '\u{1256}'), - ('\u{1258}', '\u{1258}'), ('\u{125a}', '\u{125d}'), ('\u{1260}', - '\u{1288}'), ('\u{128a}', '\u{128d}'), ('\u{1290}', '\u{12b0}'), - ('\u{12b2}', '\u{12b5}'), ('\u{12b8}', '\u{12be}'), ('\u{12c0}', - '\u{12c0}'), ('\u{12c2}', '\u{12c5}'), ('\u{12c8}', '\u{12d6}'), - ('\u{12d8}', '\u{1310}'), ('\u{1312}', '\u{1315}'), ('\u{1318}', - '\u{135a}'), ('\u{135d}', '\u{135f}'), ('\u{1380}', '\u{138f}'), - ('\u{13a0}', '\u{13f5}'), ('\u{13f8}', '\u{13fd}'), ('\u{1401}', - '\u{166c}'), ('\u{166f}', '\u{167f}'), ('\u{1681}', '\u{169a}'), - ('\u{16a0}', '\u{16ea}'), ('\u{16ee}', '\u{16f8}'), ('\u{1700}', - '\u{170c}'), ('\u{170e}', '\u{1714}'), ('\u{1720}', '\u{1734}'), - ('\u{1740}', '\u{1753}'), ('\u{1760}', '\u{176c}'), ('\u{176e}', - '\u{1770}'), ('\u{1772}', '\u{1773}'), ('\u{1780}', '\u{17d3}'), - ('\u{17d7}', '\u{17d7}'), ('\u{17dc}', '\u{17dd}'), ('\u{17e0}', - '\u{17e9}'), ('\u{180b}', '\u{180d}'), ('\u{1810}', '\u{1819}'), - ('\u{1820}', '\u{1877}'), ('\u{1880}', '\u{18aa}'), ('\u{18b0}', - '\u{18f5}'), ('\u{1900}', '\u{191e}'), ('\u{1920}', '\u{192b}'), - ('\u{1930}', '\u{193b}'), ('\u{1946}', '\u{196d}'), ('\u{1970}', - '\u{1974}'), ('\u{1980}', '\u{19ab}'), ('\u{19b0}', '\u{19c9}'), - ('\u{19d0}', '\u{19d9}'), ('\u{1a00}', '\u{1a1b}'), ('\u{1a20}', - '\u{1a5e}'), ('\u{1a60}', '\u{1a7c}'), ('\u{1a7f}', '\u{1a89}'), - ('\u{1a90}', '\u{1a99}'), ('\u{1aa7}', '\u{1aa7}'), ('\u{1ab0}', - '\u{1abe}'), ('\u{1b00}', '\u{1b4b}'), ('\u{1b50}', '\u{1b59}'), - ('\u{1b6b}', '\u{1b73}'), ('\u{1b80}', '\u{1bf3}'), ('\u{1c00}', - '\u{1c37}'), ('\u{1c40}', '\u{1c49}'), ('\u{1c4d}', '\u{1c7d}'), - ('\u{1c80}', '\u{1c88}'), ('\u{1cd0}', '\u{1cd2}'), ('\u{1cd4}', - '\u{1cf9}'), ('\u{1d00}', '\u{1df9}'), ('\u{1dfb}', '\u{1f15}'), - ('\u{1f18}', '\u{1f1d}'), ('\u{1f20}', '\u{1f45}'), ('\u{1f48}', - '\u{1f4d}'), ('\u{1f50}', '\u{1f57}'), ('\u{1f59}', '\u{1f59}'), - ('\u{1f5b}', '\u{1f5b}'), ('\u{1f5d}', '\u{1f5d}'), ('\u{1f5f}', - '\u{1f7d}'), ('\u{1f80}', '\u{1fb4}'), ('\u{1fb6}', '\u{1fbc}'), - ('\u{1fbe}', '\u{1fbe}'), ('\u{1fc2}', '\u{1fc4}'), ('\u{1fc6}', - '\u{1fcc}'), ('\u{1fd0}', '\u{1fd3}'), ('\u{1fd6}', '\u{1fdb}'), - ('\u{1fe0}', '\u{1fec}'), ('\u{1ff2}', '\u{1ff4}'), ('\u{1ff6}', - '\u{1ffc}'), ('\u{200c}', '\u{200d}'), ('\u{203f}', '\u{2040}'), - ('\u{2054}', '\u{2054}'), ('\u{2071}', '\u{2071}'), ('\u{207f}', - '\u{207f}'), ('\u{2090}', '\u{209c}'), ('\u{20d0}', '\u{20f0}'), - ('\u{2102}', '\u{2102}'), ('\u{2107}', '\u{2107}'), ('\u{210a}', - '\u{2113}'), ('\u{2115}', '\u{2115}'), ('\u{2119}', '\u{211d}'), - ('\u{2124}', '\u{2124}'), ('\u{2126}', '\u{2126}'), ('\u{2128}', - '\u{2128}'), ('\u{212a}', '\u{212d}'), ('\u{212f}', '\u{2139}'), - ('\u{213c}', '\u{213f}'), ('\u{2145}', '\u{2149}'), ('\u{214e}', - '\u{214e}'), ('\u{2160}', '\u{2188}'), ('\u{24b6}', '\u{24e9}'), - ('\u{2c00}', '\u{2c2e}'), ('\u{2c30}', '\u{2c5e}'), ('\u{2c60}', - '\u{2ce4}'), ('\u{2ceb}', '\u{2cf3}'), ('\u{2d00}', '\u{2d25}'), - ('\u{2d27}', '\u{2d27}'), ('\u{2d2d}', '\u{2d2d}'), ('\u{2d30}', - '\u{2d67}'), ('\u{2d6f}', '\u{2d6f}'), ('\u{2d7f}', '\u{2d96}'), - ('\u{2da0}', '\u{2da6}'), ('\u{2da8}', '\u{2dae}'), ('\u{2db0}', - '\u{2db6}'), ('\u{2db8}', '\u{2dbe}'), ('\u{2dc0}', '\u{2dc6}'), - ('\u{2dc8}', '\u{2dce}'), ('\u{2dd0}', '\u{2dd6}'), ('\u{2dd8}', - '\u{2dde}'), ('\u{2de0}', '\u{2dff}'), ('\u{2e2f}', '\u{2e2f}'), - ('\u{3005}', '\u{3007}'), ('\u{3021}', '\u{302f}'), ('\u{3031}', - '\u{3035}'), ('\u{3038}', '\u{303c}'), ('\u{3041}', '\u{3096}'), - ('\u{3099}', '\u{309a}'), ('\u{309d}', '\u{309f}'), ('\u{30a1}', - '\u{30fa}'), ('\u{30fc}', '\u{30ff}'), ('\u{3105}', '\u{312e}'), - ('\u{3131}', '\u{318e}'), ('\u{31a0}', '\u{31ba}'), ('\u{31f0}', - '\u{31ff}'), ('\u{3400}', '\u{4db5}'), ('\u{4e00}', '\u{9fea}'), - ('\u{a000}', '\u{a48c}'), ('\u{a4d0}', '\u{a4fd}'), ('\u{a500}', - '\u{a60c}'), ('\u{a610}', '\u{a62b}'), ('\u{a640}', '\u{a672}'), - ('\u{a674}', '\u{a67d}'), ('\u{a67f}', '\u{a6f1}'), ('\u{a717}', - '\u{a71f}'), ('\u{a722}', '\u{a788}'), ('\u{a78b}', '\u{a7ae}'), - ('\u{a7b0}', '\u{a7b7}'), ('\u{a7f7}', '\u{a827}'), ('\u{a840}', - '\u{a873}'), ('\u{a880}', '\u{a8c5}'), ('\u{a8d0}', '\u{a8d9}'), - ('\u{a8e0}', '\u{a8f7}'), ('\u{a8fb}', '\u{a8fb}'), ('\u{a8fd}', - '\u{a8fd}'), ('\u{a900}', '\u{a92d}'), ('\u{a930}', '\u{a953}'), - ('\u{a960}', '\u{a97c}'), ('\u{a980}', '\u{a9c0}'), ('\u{a9cf}', - '\u{a9d9}'), ('\u{a9e0}', '\u{a9fe}'), ('\u{aa00}', '\u{aa36}'), - ('\u{aa40}', '\u{aa4d}'), ('\u{aa50}', '\u{aa59}'), ('\u{aa60}', - '\u{aa76}'), ('\u{aa7a}', '\u{aac2}'), ('\u{aadb}', '\u{aadd}'), - ('\u{aae0}', '\u{aaef}'), ('\u{aaf2}', '\u{aaf6}'), ('\u{ab01}', - '\u{ab06}'), ('\u{ab09}', '\u{ab0e}'), ('\u{ab11}', '\u{ab16}'), - ('\u{ab20}', '\u{ab26}'), ('\u{ab28}', '\u{ab2e}'), ('\u{ab30}', - '\u{ab5a}'), ('\u{ab5c}', '\u{ab65}'), ('\u{ab70}', '\u{abea}'), - ('\u{abec}', '\u{abed}'), ('\u{abf0}', '\u{abf9}'), ('\u{ac00}', - '\u{d7a3}'), ('\u{d7b0}', '\u{d7c6}'), ('\u{d7cb}', '\u{d7fb}'), - ('\u{f900}', '\u{fa6d}'), ('\u{fa70}', '\u{fad9}'), ('\u{fb00}', - '\u{fb06}'), ('\u{fb13}', '\u{fb17}'), ('\u{fb1d}', '\u{fb28}'), - ('\u{fb2a}', '\u{fb36}'), ('\u{fb38}', '\u{fb3c}'), ('\u{fb3e}', - '\u{fb3e}'), ('\u{fb40}', '\u{fb41}'), ('\u{fb43}', '\u{fb44}'), - ('\u{fb46}', '\u{fbb1}'), ('\u{fbd3}', '\u{fd3d}'), ('\u{fd50}', - '\u{fd8f}'), ('\u{fd92}', '\u{fdc7}'), ('\u{fdf0}', '\u{fdfb}'), - ('\u{fe00}', '\u{fe0f}'), ('\u{fe20}', '\u{fe2f}'), ('\u{fe33}', - '\u{fe34}'), ('\u{fe4d}', '\u{fe4f}'), ('\u{fe70}', '\u{fe74}'), - ('\u{fe76}', '\u{fefc}'), ('\u{ff10}', '\u{ff19}'), ('\u{ff21}', - '\u{ff3a}'), ('\u{ff3f}', '\u{ff3f}'), ('\u{ff41}', '\u{ff5a}'), - ('\u{ff66}', '\u{ffbe}'), ('\u{ffc2}', '\u{ffc7}'), ('\u{ffca}', - '\u{ffcf}'), ('\u{ffd2}', '\u{ffd7}'), ('\u{ffda}', '\u{ffdc}'), - ('\u{10000}', '\u{1000b}'), ('\u{1000d}', '\u{10026}'), ('\u{10028}', - '\u{1003a}'), ('\u{1003c}', '\u{1003d}'), ('\u{1003f}', '\u{1004d}'), - ('\u{10050}', '\u{1005d}'), ('\u{10080}', '\u{100fa}'), ('\u{10140}', - '\u{10174}'), ('\u{101fd}', '\u{101fd}'), ('\u{10280}', '\u{1029c}'), - ('\u{102a0}', '\u{102d0}'), ('\u{102e0}', '\u{102e0}'), ('\u{10300}', - '\u{1031f}'), ('\u{1032d}', '\u{1034a}'), ('\u{10350}', '\u{1037a}'), - ('\u{10380}', '\u{1039d}'), ('\u{103a0}', '\u{103c3}'), ('\u{103c8}', - '\u{103cf}'), ('\u{103d1}', '\u{103d5}'), ('\u{10400}', '\u{1049d}'), - ('\u{104a0}', '\u{104a9}'), ('\u{104b0}', '\u{104d3}'), ('\u{104d8}', - '\u{104fb}'), ('\u{10500}', '\u{10527}'), ('\u{10530}', '\u{10563}'), - ('\u{10600}', '\u{10736}'), ('\u{10740}', '\u{10755}'), ('\u{10760}', - '\u{10767}'), ('\u{10800}', '\u{10805}'), ('\u{10808}', '\u{10808}'), - ('\u{1080a}', '\u{10835}'), ('\u{10837}', '\u{10838}'), ('\u{1083c}', - '\u{1083c}'), ('\u{1083f}', '\u{10855}'), ('\u{10860}', '\u{10876}'), - ('\u{10880}', '\u{1089e}'), ('\u{108e0}', '\u{108f2}'), ('\u{108f4}', - '\u{108f5}'), ('\u{10900}', '\u{10915}'), ('\u{10920}', '\u{10939}'), - ('\u{10980}', '\u{109b7}'), ('\u{109be}', '\u{109bf}'), ('\u{10a00}', - '\u{10a03}'), ('\u{10a05}', '\u{10a06}'), ('\u{10a0c}', '\u{10a13}'), - ('\u{10a15}', '\u{10a17}'), ('\u{10a19}', '\u{10a33}'), ('\u{10a38}', - '\u{10a3a}'), ('\u{10a3f}', '\u{10a3f}'), ('\u{10a60}', '\u{10a7c}'), - ('\u{10a80}', '\u{10a9c}'), ('\u{10ac0}', '\u{10ac7}'), ('\u{10ac9}', - '\u{10ae6}'), ('\u{10b00}', '\u{10b35}'), ('\u{10b40}', '\u{10b55}'), - ('\u{10b60}', '\u{10b72}'), ('\u{10b80}', '\u{10b91}'), ('\u{10c00}', - '\u{10c48}'), ('\u{10c80}', '\u{10cb2}'), ('\u{10cc0}', '\u{10cf2}'), - ('\u{11000}', '\u{11046}'), ('\u{11066}', '\u{1106f}'), ('\u{1107f}', - '\u{110ba}'), ('\u{110d0}', '\u{110e8}'), ('\u{110f0}', '\u{110f9}'), - ('\u{11100}', '\u{11134}'), ('\u{11136}', '\u{1113f}'), ('\u{11150}', - '\u{11173}'), ('\u{11176}', '\u{11176}'), ('\u{11180}', '\u{111c4}'), - ('\u{111ca}', '\u{111cc}'), ('\u{111d0}', '\u{111da}'), ('\u{111dc}', - '\u{111dc}'), ('\u{11200}', '\u{11211}'), ('\u{11213}', '\u{11237}'), - ('\u{1123e}', '\u{1123e}'), ('\u{11280}', '\u{11286}'), ('\u{11288}', - '\u{11288}'), ('\u{1128a}', '\u{1128d}'), ('\u{1128f}', '\u{1129d}'), - ('\u{1129f}', '\u{112a8}'), ('\u{112b0}', '\u{112ea}'), ('\u{112f0}', - '\u{112f9}'), ('\u{11300}', '\u{11303}'), ('\u{11305}', '\u{1130c}'), - ('\u{1130f}', '\u{11310}'), ('\u{11313}', '\u{11328}'), ('\u{1132a}', - '\u{11330}'), ('\u{11332}', '\u{11333}'), ('\u{11335}', '\u{11339}'), - ('\u{1133c}', '\u{11344}'), ('\u{11347}', '\u{11348}'), ('\u{1134b}', - '\u{1134d}'), ('\u{11350}', '\u{11350}'), ('\u{11357}', '\u{11357}'), - ('\u{1135d}', '\u{11363}'), ('\u{11366}', '\u{1136c}'), ('\u{11370}', - '\u{11374}'), ('\u{11400}', '\u{1144a}'), ('\u{11450}', '\u{11459}'), - ('\u{11480}', '\u{114c5}'), ('\u{114c7}', '\u{114c7}'), ('\u{114d0}', - '\u{114d9}'), ('\u{11580}', '\u{115b5}'), ('\u{115b8}', '\u{115c0}'), - ('\u{115d8}', '\u{115dd}'), ('\u{11600}', '\u{11640}'), ('\u{11644}', - '\u{11644}'), ('\u{11650}', '\u{11659}'), ('\u{11680}', '\u{116b7}'), - ('\u{116c0}', '\u{116c9}'), ('\u{11700}', '\u{11719}'), ('\u{1171d}', - '\u{1172b}'), ('\u{11730}', '\u{11739}'), ('\u{118a0}', '\u{118e9}'), - ('\u{118ff}', '\u{118ff}'), ('\u{11a00}', '\u{11a3e}'), ('\u{11a47}', - '\u{11a47}'), ('\u{11a50}', '\u{11a83}'), ('\u{11a86}', '\u{11a99}'), - ('\u{11ac0}', '\u{11af8}'), ('\u{11c00}', '\u{11c08}'), ('\u{11c0a}', - '\u{11c36}'), ('\u{11c38}', '\u{11c40}'), ('\u{11c50}', '\u{11c59}'), - ('\u{11c72}', '\u{11c8f}'), ('\u{11c92}', '\u{11ca7}'), ('\u{11ca9}', - '\u{11cb6}'), ('\u{11d00}', '\u{11d06}'), ('\u{11d08}', '\u{11d09}'), - ('\u{11d0b}', '\u{11d36}'), ('\u{11d3a}', '\u{11d3a}'), ('\u{11d3c}', - '\u{11d3d}'), ('\u{11d3f}', '\u{11d47}'), ('\u{11d50}', '\u{11d59}'), - ('\u{12000}', '\u{12399}'), ('\u{12400}', '\u{1246e}'), ('\u{12480}', - '\u{12543}'), ('\u{13000}', '\u{1342e}'), ('\u{14400}', '\u{14646}'), - ('\u{16800}', '\u{16a38}'), ('\u{16a40}', '\u{16a5e}'), ('\u{16a60}', - '\u{16a69}'), ('\u{16ad0}', '\u{16aed}'), ('\u{16af0}', '\u{16af4}'), - ('\u{16b00}', '\u{16b36}'), ('\u{16b40}', '\u{16b43}'), ('\u{16b50}', - '\u{16b59}'), ('\u{16b63}', '\u{16b77}'), ('\u{16b7d}', '\u{16b8f}'), - ('\u{16f00}', '\u{16f44}'), ('\u{16f50}', '\u{16f7e}'), ('\u{16f8f}', - '\u{16f9f}'), ('\u{16fe0}', '\u{16fe1}'), ('\u{17000}', '\u{187ec}'), - ('\u{18800}', '\u{18af2}'), ('\u{1b000}', '\u{1b11e}'), ('\u{1b170}', - '\u{1b2fb}'), ('\u{1bc00}', '\u{1bc6a}'), ('\u{1bc70}', '\u{1bc7c}'), - ('\u{1bc80}', '\u{1bc88}'), ('\u{1bc90}', '\u{1bc99}'), ('\u{1bc9d}', - '\u{1bc9e}'), ('\u{1d165}', '\u{1d169}'), ('\u{1d16d}', '\u{1d172}'), - ('\u{1d17b}', '\u{1d182}'), ('\u{1d185}', '\u{1d18b}'), ('\u{1d1aa}', - '\u{1d1ad}'), ('\u{1d242}', '\u{1d244}'), ('\u{1d400}', '\u{1d454}'), - ('\u{1d456}', '\u{1d49c}'), ('\u{1d49e}', '\u{1d49f}'), ('\u{1d4a2}', - '\u{1d4a2}'), ('\u{1d4a5}', '\u{1d4a6}'), ('\u{1d4a9}', '\u{1d4ac}'), - ('\u{1d4ae}', '\u{1d4b9}'), ('\u{1d4bb}', '\u{1d4bb}'), ('\u{1d4bd}', - '\u{1d4c3}'), ('\u{1d4c5}', '\u{1d505}'), ('\u{1d507}', '\u{1d50a}'), - ('\u{1d50d}', '\u{1d514}'), ('\u{1d516}', '\u{1d51c}'), ('\u{1d51e}', - '\u{1d539}'), ('\u{1d53b}', '\u{1d53e}'), ('\u{1d540}', '\u{1d544}'), - ('\u{1d546}', '\u{1d546}'), ('\u{1d54a}', '\u{1d550}'), ('\u{1d552}', - '\u{1d6a5}'), ('\u{1d6a8}', '\u{1d6c0}'), ('\u{1d6c2}', '\u{1d6da}'), - ('\u{1d6dc}', '\u{1d6fa}'), ('\u{1d6fc}', '\u{1d714}'), ('\u{1d716}', - '\u{1d734}'), ('\u{1d736}', '\u{1d74e}'), ('\u{1d750}', '\u{1d76e}'), - ('\u{1d770}', '\u{1d788}'), ('\u{1d78a}', '\u{1d7a8}'), ('\u{1d7aa}', - '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7cb}'), ('\u{1d7ce}', '\u{1d7ff}'), - ('\u{1da00}', '\u{1da36}'), ('\u{1da3b}', '\u{1da6c}'), ('\u{1da75}', - '\u{1da75}'), ('\u{1da84}', '\u{1da84}'), ('\u{1da9b}', '\u{1da9f}'), - ('\u{1daa1}', '\u{1daaf}'), ('\u{1e000}', '\u{1e006}'), ('\u{1e008}', - '\u{1e018}'), ('\u{1e01b}', '\u{1e021}'), ('\u{1e023}', '\u{1e024}'), - ('\u{1e026}', '\u{1e02a}'), ('\u{1e800}', '\u{1e8c4}'), ('\u{1e8d0}', - '\u{1e8d6}'), ('\u{1e900}', '\u{1e94a}'), ('\u{1e950}', '\u{1e959}'), - ('\u{1ee00}', '\u{1ee03}'), ('\u{1ee05}', '\u{1ee1f}'), ('\u{1ee21}', - '\u{1ee22}'), ('\u{1ee24}', '\u{1ee24}'), ('\u{1ee27}', '\u{1ee27}'), - ('\u{1ee29}', '\u{1ee32}'), ('\u{1ee34}', '\u{1ee37}'), ('\u{1ee39}', - '\u{1ee39}'), ('\u{1ee3b}', '\u{1ee3b}'), ('\u{1ee42}', '\u{1ee42}'), - ('\u{1ee47}', '\u{1ee47}'), ('\u{1ee49}', '\u{1ee49}'), ('\u{1ee4b}', - '\u{1ee4b}'), ('\u{1ee4d}', '\u{1ee4f}'), ('\u{1ee51}', '\u{1ee52}'), - ('\u{1ee54}', '\u{1ee54}'), ('\u{1ee57}', '\u{1ee57}'), ('\u{1ee59}', - '\u{1ee59}'), ('\u{1ee5b}', '\u{1ee5b}'), ('\u{1ee5d}', '\u{1ee5d}'), - ('\u{1ee5f}', '\u{1ee5f}'), ('\u{1ee61}', '\u{1ee62}'), ('\u{1ee64}', - '\u{1ee64}'), ('\u{1ee67}', '\u{1ee6a}'), ('\u{1ee6c}', '\u{1ee72}'), - ('\u{1ee74}', '\u{1ee77}'), ('\u{1ee79}', '\u{1ee7c}'), ('\u{1ee7e}', - '\u{1ee7e}'), ('\u{1ee80}', '\u{1ee89}'), ('\u{1ee8b}', '\u{1ee9b}'), - ('\u{1eea1}', '\u{1eea3}'), ('\u{1eea5}', '\u{1eea9}'), ('\u{1eeab}', - '\u{1eebb}'), ('\u{1f130}', '\u{1f149}'), ('\u{1f150}', '\u{1f169}'), - ('\u{1f170}', '\u{1f189}'), ('\u{20000}', '\u{2a6d6}'), ('\u{2a700}', - '\u{2b734}'), ('\u{2b740}', '\u{2b81d}'), ('\u{2b820}', '\u{2cea1}'), - ('\u{2ceb0}', '\u{2ebe0}'), ('\u{2f800}', '\u{2fa1d}'), ('\u{e0100}', - '\u{e01ef}') - ]; - -} - -pub mod case_folding { - pub const C_plus_S_both_table: &'static [(char, char)] = &[ - ('\u{41}', '\u{61}'), ('\u{42}', '\u{62}'), ('\u{43}', '\u{63}'), - ('\u{44}', '\u{64}'), ('\u{45}', '\u{65}'), ('\u{46}', '\u{66}'), - ('\u{47}', '\u{67}'), ('\u{48}', '\u{68}'), ('\u{49}', '\u{69}'), - ('\u{4a}', '\u{6a}'), ('\u{4b}', '\u{6b}'), ('\u{4b}', '\u{212a}'), - ('\u{4c}', '\u{6c}'), ('\u{4d}', '\u{6d}'), ('\u{4e}', '\u{6e}'), - ('\u{4f}', '\u{6f}'), ('\u{50}', '\u{70}'), ('\u{51}', '\u{71}'), - ('\u{52}', '\u{72}'), ('\u{53}', '\u{73}'), ('\u{53}', '\u{17f}'), - ('\u{54}', '\u{74}'), ('\u{55}', '\u{75}'), ('\u{56}', '\u{76}'), - ('\u{57}', '\u{77}'), ('\u{58}', '\u{78}'), ('\u{59}', '\u{79}'), - ('\u{5a}', '\u{7a}'), ('\u{61}', '\u{41}'), ('\u{62}', '\u{42}'), - ('\u{63}', '\u{43}'), ('\u{64}', '\u{44}'), ('\u{65}', '\u{45}'), - ('\u{66}', '\u{46}'), ('\u{67}', '\u{47}'), ('\u{68}', '\u{48}'), - ('\u{69}', '\u{49}'), ('\u{6a}', '\u{4a}'), ('\u{6b}', '\u{4b}'), - ('\u{6b}', '\u{212a}'), ('\u{6c}', '\u{4c}'), ('\u{6d}', '\u{4d}'), - ('\u{6e}', '\u{4e}'), ('\u{6f}', '\u{4f}'), ('\u{70}', '\u{50}'), - ('\u{71}', '\u{51}'), ('\u{72}', '\u{52}'), ('\u{73}', '\u{53}'), - ('\u{73}', '\u{17f}'), ('\u{74}', '\u{54}'), ('\u{75}', '\u{55}'), - ('\u{76}', '\u{56}'), ('\u{77}', '\u{57}'), ('\u{78}', '\u{58}'), - ('\u{79}', '\u{59}'), ('\u{7a}', '\u{5a}'), ('\u{b5}', '\u{39c}'), - ('\u{b5}', '\u{3bc}'), ('\u{c0}', '\u{e0}'), ('\u{c1}', '\u{e1}'), - ('\u{c2}', '\u{e2}'), ('\u{c3}', '\u{e3}'), ('\u{c4}', '\u{e4}'), - ('\u{c5}', '\u{e5}'), ('\u{c5}', '\u{212b}'), ('\u{c6}', '\u{e6}'), - ('\u{c7}', '\u{e7}'), ('\u{c8}', '\u{e8}'), ('\u{c9}', '\u{e9}'), - ('\u{ca}', '\u{ea}'), ('\u{cb}', '\u{eb}'), ('\u{cc}', '\u{ec}'), - ('\u{cd}', '\u{ed}'), ('\u{ce}', '\u{ee}'), ('\u{cf}', '\u{ef}'), - ('\u{d0}', '\u{f0}'), ('\u{d1}', '\u{f1}'), ('\u{d2}', '\u{f2}'), - ('\u{d3}', '\u{f3}'), ('\u{d4}', '\u{f4}'), ('\u{d5}', '\u{f5}'), - ('\u{d6}', '\u{f6}'), ('\u{d8}', '\u{f8}'), ('\u{d9}', '\u{f9}'), - ('\u{da}', '\u{fa}'), ('\u{db}', '\u{fb}'), ('\u{dc}', '\u{fc}'), - ('\u{dd}', '\u{fd}'), ('\u{de}', '\u{fe}'), ('\u{df}', '\u{1e9e}'), - ('\u{e0}', '\u{c0}'), ('\u{e1}', '\u{c1}'), ('\u{e2}', '\u{c2}'), - ('\u{e3}', '\u{c3}'), ('\u{e4}', '\u{c4}'), ('\u{e5}', '\u{c5}'), - ('\u{e5}', '\u{212b}'), ('\u{e6}', '\u{c6}'), ('\u{e7}', '\u{c7}'), - ('\u{e8}', '\u{c8}'), ('\u{e9}', '\u{c9}'), ('\u{ea}', '\u{ca}'), - ('\u{eb}', '\u{cb}'), ('\u{ec}', '\u{cc}'), ('\u{ed}', '\u{cd}'), - ('\u{ee}', '\u{ce}'), ('\u{ef}', '\u{cf}'), ('\u{f0}', '\u{d0}'), - ('\u{f1}', '\u{d1}'), ('\u{f2}', '\u{d2}'), ('\u{f3}', '\u{d3}'), - ('\u{f4}', '\u{d4}'), ('\u{f5}', '\u{d5}'), ('\u{f6}', '\u{d6}'), - ('\u{f8}', '\u{d8}'), ('\u{f9}', '\u{d9}'), ('\u{fa}', '\u{da}'), - ('\u{fb}', '\u{db}'), ('\u{fc}', '\u{dc}'), ('\u{fd}', '\u{dd}'), - ('\u{fe}', '\u{de}'), ('\u{ff}', '\u{178}'), ('\u{100}', '\u{101}'), - ('\u{101}', '\u{100}'), ('\u{102}', '\u{103}'), ('\u{103}', '\u{102}'), - ('\u{104}', '\u{105}'), ('\u{105}', '\u{104}'), ('\u{106}', '\u{107}'), - ('\u{107}', '\u{106}'), ('\u{108}', '\u{109}'), ('\u{109}', '\u{108}'), - ('\u{10a}', '\u{10b}'), ('\u{10b}', '\u{10a}'), ('\u{10c}', '\u{10d}'), - ('\u{10d}', '\u{10c}'), ('\u{10e}', '\u{10f}'), ('\u{10f}', '\u{10e}'), - ('\u{110}', '\u{111}'), ('\u{111}', '\u{110}'), ('\u{112}', '\u{113}'), - ('\u{113}', '\u{112}'), ('\u{114}', '\u{115}'), ('\u{115}', '\u{114}'), - ('\u{116}', '\u{117}'), ('\u{117}', '\u{116}'), ('\u{118}', '\u{119}'), - ('\u{119}', '\u{118}'), ('\u{11a}', '\u{11b}'), ('\u{11b}', '\u{11a}'), - ('\u{11c}', '\u{11d}'), ('\u{11d}', '\u{11c}'), ('\u{11e}', '\u{11f}'), - ('\u{11f}', '\u{11e}'), ('\u{120}', '\u{121}'), ('\u{121}', '\u{120}'), - ('\u{122}', '\u{123}'), ('\u{123}', '\u{122}'), ('\u{124}', '\u{125}'), - ('\u{125}', '\u{124}'), ('\u{126}', '\u{127}'), ('\u{127}', '\u{126}'), - ('\u{128}', '\u{129}'), ('\u{129}', '\u{128}'), ('\u{12a}', '\u{12b}'), - ('\u{12b}', '\u{12a}'), ('\u{12c}', '\u{12d}'), ('\u{12d}', '\u{12c}'), - ('\u{12e}', '\u{12f}'), ('\u{12f}', '\u{12e}'), ('\u{132}', '\u{133}'), - ('\u{133}', '\u{132}'), ('\u{134}', '\u{135}'), ('\u{135}', '\u{134}'), - ('\u{136}', '\u{137}'), ('\u{137}', '\u{136}'), ('\u{139}', '\u{13a}'), - ('\u{13a}', '\u{139}'), ('\u{13b}', '\u{13c}'), ('\u{13c}', '\u{13b}'), - ('\u{13d}', '\u{13e}'), ('\u{13e}', '\u{13d}'), ('\u{13f}', '\u{140}'), - ('\u{140}', '\u{13f}'), ('\u{141}', '\u{142}'), ('\u{142}', '\u{141}'), - ('\u{143}', '\u{144}'), ('\u{144}', '\u{143}'), ('\u{145}', '\u{146}'), - ('\u{146}', '\u{145}'), ('\u{147}', '\u{148}'), ('\u{148}', '\u{147}'), - ('\u{14a}', '\u{14b}'), ('\u{14b}', '\u{14a}'), ('\u{14c}', '\u{14d}'), - ('\u{14d}', '\u{14c}'), ('\u{14e}', '\u{14f}'), ('\u{14f}', '\u{14e}'), - ('\u{150}', '\u{151}'), ('\u{151}', '\u{150}'), ('\u{152}', '\u{153}'), - ('\u{153}', '\u{152}'), ('\u{154}', '\u{155}'), ('\u{155}', '\u{154}'), - ('\u{156}', '\u{157}'), ('\u{157}', '\u{156}'), ('\u{158}', '\u{159}'), - ('\u{159}', '\u{158}'), ('\u{15a}', '\u{15b}'), ('\u{15b}', '\u{15a}'), - ('\u{15c}', '\u{15d}'), ('\u{15d}', '\u{15c}'), ('\u{15e}', '\u{15f}'), - ('\u{15f}', '\u{15e}'), ('\u{160}', '\u{161}'), ('\u{161}', '\u{160}'), - ('\u{162}', '\u{163}'), ('\u{163}', '\u{162}'), ('\u{164}', '\u{165}'), - ('\u{165}', '\u{164}'), ('\u{166}', '\u{167}'), ('\u{167}', '\u{166}'), - ('\u{168}', '\u{169}'), ('\u{169}', '\u{168}'), ('\u{16a}', '\u{16b}'), - ('\u{16b}', '\u{16a}'), ('\u{16c}', '\u{16d}'), ('\u{16d}', '\u{16c}'), - ('\u{16e}', '\u{16f}'), ('\u{16f}', '\u{16e}'), ('\u{170}', '\u{171}'), - ('\u{171}', '\u{170}'), ('\u{172}', '\u{173}'), ('\u{173}', '\u{172}'), - ('\u{174}', '\u{175}'), ('\u{175}', '\u{174}'), ('\u{176}', '\u{177}'), - ('\u{177}', '\u{176}'), ('\u{178}', '\u{ff}'), ('\u{179}', '\u{17a}'), - ('\u{17a}', '\u{179}'), ('\u{17b}', '\u{17c}'), ('\u{17c}', '\u{17b}'), - ('\u{17d}', '\u{17e}'), ('\u{17e}', '\u{17d}'), ('\u{17f}', '\u{53}'), - ('\u{17f}', '\u{73}'), ('\u{180}', '\u{243}'), ('\u{181}', '\u{253}'), - ('\u{182}', '\u{183}'), ('\u{183}', '\u{182}'), ('\u{184}', '\u{185}'), - ('\u{185}', '\u{184}'), ('\u{186}', '\u{254}'), ('\u{187}', '\u{188}'), - ('\u{188}', '\u{187}'), ('\u{189}', '\u{256}'), ('\u{18a}', '\u{257}'), - ('\u{18b}', '\u{18c}'), ('\u{18c}', '\u{18b}'), ('\u{18e}', '\u{1dd}'), - ('\u{18f}', '\u{259}'), ('\u{190}', '\u{25b}'), ('\u{191}', '\u{192}'), - ('\u{192}', '\u{191}'), ('\u{193}', '\u{260}'), ('\u{194}', '\u{263}'), - ('\u{195}', '\u{1f6}'), ('\u{196}', '\u{269}'), ('\u{197}', '\u{268}'), - ('\u{198}', '\u{199}'), ('\u{199}', '\u{198}'), ('\u{19a}', '\u{23d}'), - ('\u{19c}', '\u{26f}'), ('\u{19d}', '\u{272}'), ('\u{19e}', '\u{220}'), - ('\u{19f}', '\u{275}'), ('\u{1a0}', '\u{1a1}'), ('\u{1a1}', '\u{1a0}'), - ('\u{1a2}', '\u{1a3}'), ('\u{1a3}', '\u{1a2}'), ('\u{1a4}', '\u{1a5}'), - ('\u{1a5}', '\u{1a4}'), ('\u{1a6}', '\u{280}'), ('\u{1a7}', '\u{1a8}'), - ('\u{1a8}', '\u{1a7}'), ('\u{1a9}', '\u{283}'), ('\u{1ac}', '\u{1ad}'), - ('\u{1ad}', '\u{1ac}'), ('\u{1ae}', '\u{288}'), ('\u{1af}', '\u{1b0}'), - ('\u{1b0}', '\u{1af}'), ('\u{1b1}', '\u{28a}'), ('\u{1b2}', '\u{28b}'), - ('\u{1b3}', '\u{1b4}'), ('\u{1b4}', '\u{1b3}'), ('\u{1b5}', '\u{1b6}'), - ('\u{1b6}', '\u{1b5}'), ('\u{1b7}', '\u{292}'), ('\u{1b8}', '\u{1b9}'), - ('\u{1b9}', '\u{1b8}'), ('\u{1bc}', '\u{1bd}'), ('\u{1bd}', '\u{1bc}'), - ('\u{1bf}', '\u{1f7}'), ('\u{1c4}', '\u{1c5}'), ('\u{1c4}', '\u{1c6}'), - ('\u{1c5}', '\u{1c4}'), ('\u{1c5}', '\u{1c6}'), ('\u{1c6}', '\u{1c4}'), - ('\u{1c6}', '\u{1c5}'), ('\u{1c7}', '\u{1c8}'), ('\u{1c7}', '\u{1c9}'), - ('\u{1c8}', '\u{1c7}'), ('\u{1c8}', '\u{1c9}'), ('\u{1c9}', '\u{1c7}'), - ('\u{1c9}', '\u{1c8}'), ('\u{1ca}', '\u{1cb}'), ('\u{1ca}', '\u{1cc}'), - ('\u{1cb}', '\u{1ca}'), ('\u{1cb}', '\u{1cc}'), ('\u{1cc}', '\u{1ca}'), - ('\u{1cc}', '\u{1cb}'), ('\u{1cd}', '\u{1ce}'), ('\u{1ce}', '\u{1cd}'), - ('\u{1cf}', '\u{1d0}'), ('\u{1d0}', '\u{1cf}'), ('\u{1d1}', '\u{1d2}'), - ('\u{1d2}', '\u{1d1}'), ('\u{1d3}', '\u{1d4}'), ('\u{1d4}', '\u{1d3}'), - ('\u{1d5}', '\u{1d6}'), ('\u{1d6}', '\u{1d5}'), ('\u{1d7}', '\u{1d8}'), - ('\u{1d8}', '\u{1d7}'), ('\u{1d9}', '\u{1da}'), ('\u{1da}', '\u{1d9}'), - ('\u{1db}', '\u{1dc}'), ('\u{1dc}', '\u{1db}'), ('\u{1dd}', '\u{18e}'), - ('\u{1de}', '\u{1df}'), ('\u{1df}', '\u{1de}'), ('\u{1e0}', '\u{1e1}'), - ('\u{1e1}', '\u{1e0}'), ('\u{1e2}', '\u{1e3}'), ('\u{1e3}', '\u{1e2}'), - ('\u{1e4}', '\u{1e5}'), ('\u{1e5}', '\u{1e4}'), ('\u{1e6}', '\u{1e7}'), - ('\u{1e7}', '\u{1e6}'), ('\u{1e8}', '\u{1e9}'), ('\u{1e9}', '\u{1e8}'), - ('\u{1ea}', '\u{1eb}'), ('\u{1eb}', '\u{1ea}'), ('\u{1ec}', '\u{1ed}'), - ('\u{1ed}', '\u{1ec}'), ('\u{1ee}', '\u{1ef}'), ('\u{1ef}', '\u{1ee}'), - ('\u{1f1}', '\u{1f2}'), ('\u{1f1}', '\u{1f3}'), ('\u{1f2}', '\u{1f1}'), - ('\u{1f2}', '\u{1f3}'), ('\u{1f3}', '\u{1f1}'), ('\u{1f3}', '\u{1f2}'), - ('\u{1f4}', '\u{1f5}'), ('\u{1f5}', '\u{1f4}'), ('\u{1f6}', '\u{195}'), - ('\u{1f7}', '\u{1bf}'), ('\u{1f8}', '\u{1f9}'), ('\u{1f9}', '\u{1f8}'), - ('\u{1fa}', '\u{1fb}'), ('\u{1fb}', '\u{1fa}'), ('\u{1fc}', '\u{1fd}'), - ('\u{1fd}', '\u{1fc}'), ('\u{1fe}', '\u{1ff}'), ('\u{1ff}', '\u{1fe}'), - ('\u{200}', '\u{201}'), ('\u{201}', '\u{200}'), ('\u{202}', '\u{203}'), - ('\u{203}', '\u{202}'), ('\u{204}', '\u{205}'), ('\u{205}', '\u{204}'), - ('\u{206}', '\u{207}'), ('\u{207}', '\u{206}'), ('\u{208}', '\u{209}'), - ('\u{209}', '\u{208}'), ('\u{20a}', '\u{20b}'), ('\u{20b}', '\u{20a}'), - ('\u{20c}', '\u{20d}'), ('\u{20d}', '\u{20c}'), ('\u{20e}', '\u{20f}'), - ('\u{20f}', '\u{20e}'), ('\u{210}', '\u{211}'), ('\u{211}', '\u{210}'), - ('\u{212}', '\u{213}'), ('\u{213}', '\u{212}'), ('\u{214}', '\u{215}'), - ('\u{215}', '\u{214}'), ('\u{216}', '\u{217}'), ('\u{217}', '\u{216}'), - ('\u{218}', '\u{219}'), ('\u{219}', '\u{218}'), ('\u{21a}', '\u{21b}'), - ('\u{21b}', '\u{21a}'), ('\u{21c}', '\u{21d}'), ('\u{21d}', '\u{21c}'), - ('\u{21e}', '\u{21f}'), ('\u{21f}', '\u{21e}'), ('\u{220}', '\u{19e}'), - ('\u{222}', '\u{223}'), ('\u{223}', '\u{222}'), ('\u{224}', '\u{225}'), - ('\u{225}', '\u{224}'), ('\u{226}', '\u{227}'), ('\u{227}', '\u{226}'), - ('\u{228}', '\u{229}'), ('\u{229}', '\u{228}'), ('\u{22a}', '\u{22b}'), - ('\u{22b}', '\u{22a}'), ('\u{22c}', '\u{22d}'), ('\u{22d}', '\u{22c}'), - ('\u{22e}', '\u{22f}'), ('\u{22f}', '\u{22e}'), ('\u{230}', '\u{231}'), - ('\u{231}', '\u{230}'), ('\u{232}', '\u{233}'), ('\u{233}', '\u{232}'), - ('\u{23a}', '\u{2c65}'), ('\u{23b}', '\u{23c}'), ('\u{23c}', '\u{23b}'), - ('\u{23d}', '\u{19a}'), ('\u{23e}', '\u{2c66}'), ('\u{23f}', - '\u{2c7e}'), ('\u{240}', '\u{2c7f}'), ('\u{241}', '\u{242}'), - ('\u{242}', '\u{241}'), ('\u{243}', '\u{180}'), ('\u{244}', '\u{289}'), - ('\u{245}', '\u{28c}'), ('\u{246}', '\u{247}'), ('\u{247}', '\u{246}'), - ('\u{248}', '\u{249}'), ('\u{249}', '\u{248}'), ('\u{24a}', '\u{24b}'), - ('\u{24b}', '\u{24a}'), ('\u{24c}', '\u{24d}'), ('\u{24d}', '\u{24c}'), - ('\u{24e}', '\u{24f}'), ('\u{24f}', '\u{24e}'), ('\u{250}', '\u{2c6f}'), - ('\u{251}', '\u{2c6d}'), ('\u{252}', '\u{2c70}'), ('\u{253}', - '\u{181}'), ('\u{254}', '\u{186}'), ('\u{256}', '\u{189}'), ('\u{257}', - '\u{18a}'), ('\u{259}', '\u{18f}'), ('\u{25b}', '\u{190}'), ('\u{25c}', - '\u{a7ab}'), ('\u{260}', '\u{193}'), ('\u{261}', '\u{a7ac}'), - ('\u{263}', '\u{194}'), ('\u{265}', '\u{a78d}'), ('\u{266}', - '\u{a7aa}'), ('\u{268}', '\u{197}'), ('\u{269}', '\u{196}'), ('\u{26a}', - '\u{a7ae}'), ('\u{26b}', '\u{2c62}'), ('\u{26c}', '\u{a7ad}'), - ('\u{26f}', '\u{19c}'), ('\u{271}', '\u{2c6e}'), ('\u{272}', '\u{19d}'), - ('\u{275}', '\u{19f}'), ('\u{27d}', '\u{2c64}'), ('\u{280}', '\u{1a6}'), - ('\u{283}', '\u{1a9}'), ('\u{287}', '\u{a7b1}'), ('\u{288}', '\u{1ae}'), - ('\u{289}', '\u{244}'), ('\u{28a}', '\u{1b1}'), ('\u{28b}', '\u{1b2}'), - ('\u{28c}', '\u{245}'), ('\u{292}', '\u{1b7}'), ('\u{29d}', '\u{a7b2}'), - ('\u{29e}', '\u{a7b0}'), ('\u{345}', '\u{399}'), ('\u{345}', '\u{3b9}'), - ('\u{345}', '\u{1fbe}'), ('\u{370}', '\u{371}'), ('\u{371}', '\u{370}'), - ('\u{372}', '\u{373}'), ('\u{373}', '\u{372}'), ('\u{376}', '\u{377}'), - ('\u{377}', '\u{376}'), ('\u{37b}', '\u{3fd}'), ('\u{37c}', '\u{3fe}'), - ('\u{37d}', '\u{3ff}'), ('\u{37f}', '\u{3f3}'), ('\u{386}', '\u{3ac}'), - ('\u{388}', '\u{3ad}'), ('\u{389}', '\u{3ae}'), ('\u{38a}', '\u{3af}'), - ('\u{38c}', '\u{3cc}'), ('\u{38e}', '\u{3cd}'), ('\u{38f}', '\u{3ce}'), - ('\u{391}', '\u{3b1}'), ('\u{392}', '\u{3b2}'), ('\u{392}', '\u{3d0}'), - ('\u{393}', '\u{3b3}'), ('\u{394}', '\u{3b4}'), ('\u{395}', '\u{3b5}'), - ('\u{395}', '\u{3f5}'), ('\u{396}', '\u{3b6}'), ('\u{397}', '\u{3b7}'), - ('\u{398}', '\u{3b8}'), ('\u{398}', '\u{3d1}'), ('\u{398}', '\u{3f4}'), - ('\u{399}', '\u{345}'), ('\u{399}', '\u{3b9}'), ('\u{399}', '\u{1fbe}'), - ('\u{39a}', '\u{3ba}'), ('\u{39a}', '\u{3f0}'), ('\u{39b}', '\u{3bb}'), - ('\u{39c}', '\u{b5}'), ('\u{39c}', '\u{3bc}'), ('\u{39d}', '\u{3bd}'), - ('\u{39e}', '\u{3be}'), ('\u{39f}', '\u{3bf}'), ('\u{3a0}', '\u{3c0}'), - ('\u{3a0}', '\u{3d6}'), ('\u{3a1}', '\u{3c1}'), ('\u{3a1}', '\u{3f1}'), - ('\u{3a3}', '\u{3c2}'), ('\u{3a3}', '\u{3c3}'), ('\u{3a4}', '\u{3c4}'), - ('\u{3a5}', '\u{3c5}'), ('\u{3a6}', '\u{3c6}'), ('\u{3a6}', '\u{3d5}'), - ('\u{3a7}', '\u{3c7}'), ('\u{3a8}', '\u{3c8}'), ('\u{3a9}', '\u{3c9}'), - ('\u{3a9}', '\u{2126}'), ('\u{3aa}', '\u{3ca}'), ('\u{3ab}', '\u{3cb}'), - ('\u{3ac}', '\u{386}'), ('\u{3ad}', '\u{388}'), ('\u{3ae}', '\u{389}'), - ('\u{3af}', '\u{38a}'), ('\u{3b1}', '\u{391}'), ('\u{3b2}', '\u{392}'), - ('\u{3b2}', '\u{3d0}'), ('\u{3b3}', '\u{393}'), ('\u{3b4}', '\u{394}'), - ('\u{3b5}', '\u{395}'), ('\u{3b5}', '\u{3f5}'), ('\u{3b6}', '\u{396}'), - ('\u{3b7}', '\u{397}'), ('\u{3b8}', '\u{398}'), ('\u{3b8}', '\u{3d1}'), - ('\u{3b8}', '\u{3f4}'), ('\u{3b9}', '\u{345}'), ('\u{3b9}', '\u{399}'), - ('\u{3b9}', '\u{1fbe}'), ('\u{3ba}', '\u{39a}'), ('\u{3ba}', '\u{3f0}'), - ('\u{3bb}', '\u{39b}'), ('\u{3bc}', '\u{b5}'), ('\u{3bc}', '\u{39c}'), - ('\u{3bd}', '\u{39d}'), ('\u{3be}', '\u{39e}'), ('\u{3bf}', '\u{39f}'), - ('\u{3c0}', '\u{3a0}'), ('\u{3c0}', '\u{3d6}'), ('\u{3c1}', '\u{3a1}'), - ('\u{3c1}', '\u{3f1}'), ('\u{3c2}', '\u{3a3}'), ('\u{3c2}', '\u{3c3}'), - ('\u{3c3}', '\u{3a3}'), ('\u{3c3}', '\u{3c2}'), ('\u{3c4}', '\u{3a4}'), - ('\u{3c5}', '\u{3a5}'), ('\u{3c6}', '\u{3a6}'), ('\u{3c6}', '\u{3d5}'), - ('\u{3c7}', '\u{3a7}'), ('\u{3c8}', '\u{3a8}'), ('\u{3c9}', '\u{3a9}'), - ('\u{3c9}', '\u{2126}'), ('\u{3ca}', '\u{3aa}'), ('\u{3cb}', '\u{3ab}'), - ('\u{3cc}', '\u{38c}'), ('\u{3cd}', '\u{38e}'), ('\u{3ce}', '\u{38f}'), - ('\u{3cf}', '\u{3d7}'), ('\u{3d0}', '\u{392}'), ('\u{3d0}', '\u{3b2}'), - ('\u{3d1}', '\u{398}'), ('\u{3d1}', '\u{3b8}'), ('\u{3d1}', '\u{3f4}'), - ('\u{3d5}', '\u{3a6}'), ('\u{3d5}', '\u{3c6}'), ('\u{3d6}', '\u{3a0}'), - ('\u{3d6}', '\u{3c0}'), ('\u{3d7}', '\u{3cf}'), ('\u{3d8}', '\u{3d9}'), - ('\u{3d9}', '\u{3d8}'), ('\u{3da}', '\u{3db}'), ('\u{3db}', '\u{3da}'), - ('\u{3dc}', '\u{3dd}'), ('\u{3dd}', '\u{3dc}'), ('\u{3de}', '\u{3df}'), - ('\u{3df}', '\u{3de}'), ('\u{3e0}', '\u{3e1}'), ('\u{3e1}', '\u{3e0}'), - ('\u{3e2}', '\u{3e3}'), ('\u{3e3}', '\u{3e2}'), ('\u{3e4}', '\u{3e5}'), - ('\u{3e5}', '\u{3e4}'), ('\u{3e6}', '\u{3e7}'), ('\u{3e7}', '\u{3e6}'), - ('\u{3e8}', '\u{3e9}'), ('\u{3e9}', '\u{3e8}'), ('\u{3ea}', '\u{3eb}'), - ('\u{3eb}', '\u{3ea}'), ('\u{3ec}', '\u{3ed}'), ('\u{3ed}', '\u{3ec}'), - ('\u{3ee}', '\u{3ef}'), ('\u{3ef}', '\u{3ee}'), ('\u{3f0}', '\u{39a}'), - ('\u{3f0}', '\u{3ba}'), ('\u{3f1}', '\u{3a1}'), ('\u{3f1}', '\u{3c1}'), - ('\u{3f2}', '\u{3f9}'), ('\u{3f3}', '\u{37f}'), ('\u{3f4}', '\u{398}'), - ('\u{3f4}', '\u{3b8}'), ('\u{3f4}', '\u{3d1}'), ('\u{3f5}', '\u{395}'), - ('\u{3f5}', '\u{3b5}'), ('\u{3f7}', '\u{3f8}'), ('\u{3f8}', '\u{3f7}'), - ('\u{3f9}', '\u{3f2}'), ('\u{3fa}', '\u{3fb}'), ('\u{3fb}', '\u{3fa}'), - ('\u{3fd}', '\u{37b}'), ('\u{3fe}', '\u{37c}'), ('\u{3ff}', '\u{37d}'), - ('\u{400}', '\u{450}'), ('\u{401}', '\u{451}'), ('\u{402}', '\u{452}'), - ('\u{403}', '\u{453}'), ('\u{404}', '\u{454}'), ('\u{405}', '\u{455}'), - ('\u{406}', '\u{456}'), ('\u{407}', '\u{457}'), ('\u{408}', '\u{458}'), - ('\u{409}', '\u{459}'), ('\u{40a}', '\u{45a}'), ('\u{40b}', '\u{45b}'), - ('\u{40c}', '\u{45c}'), ('\u{40d}', '\u{45d}'), ('\u{40e}', '\u{45e}'), - ('\u{40f}', '\u{45f}'), ('\u{410}', '\u{430}'), ('\u{411}', '\u{431}'), - ('\u{412}', '\u{432}'), ('\u{412}', '\u{1c80}'), ('\u{413}', '\u{433}'), - ('\u{414}', '\u{434}'), ('\u{414}', '\u{1c81}'), ('\u{415}', '\u{435}'), - ('\u{416}', '\u{436}'), ('\u{417}', '\u{437}'), ('\u{418}', '\u{438}'), - ('\u{419}', '\u{439}'), ('\u{41a}', '\u{43a}'), ('\u{41b}', '\u{43b}'), - ('\u{41c}', '\u{43c}'), ('\u{41d}', '\u{43d}'), ('\u{41e}', '\u{43e}'), - ('\u{41e}', '\u{1c82}'), ('\u{41f}', '\u{43f}'), ('\u{420}', '\u{440}'), - ('\u{421}', '\u{441}'), ('\u{421}', '\u{1c83}'), ('\u{422}', '\u{442}'), - ('\u{422}', '\u{1c84}'), ('\u{422}', '\u{1c85}'), ('\u{423}', - '\u{443}'), ('\u{424}', '\u{444}'), ('\u{425}', '\u{445}'), ('\u{426}', - '\u{446}'), ('\u{427}', '\u{447}'), ('\u{428}', '\u{448}'), ('\u{429}', - '\u{449}'), ('\u{42a}', '\u{44a}'), ('\u{42a}', '\u{1c86}'), ('\u{42b}', - '\u{44b}'), ('\u{42c}', '\u{44c}'), ('\u{42d}', '\u{44d}'), ('\u{42e}', - '\u{44e}'), ('\u{42f}', '\u{44f}'), ('\u{430}', '\u{410}'), ('\u{431}', - '\u{411}'), ('\u{432}', '\u{412}'), ('\u{432}', '\u{1c80}'), ('\u{433}', - '\u{413}'), ('\u{434}', '\u{414}'), ('\u{434}', '\u{1c81}'), ('\u{435}', - '\u{415}'), ('\u{436}', '\u{416}'), ('\u{437}', '\u{417}'), ('\u{438}', - '\u{418}'), ('\u{439}', '\u{419}'), ('\u{43a}', '\u{41a}'), ('\u{43b}', - '\u{41b}'), ('\u{43c}', '\u{41c}'), ('\u{43d}', '\u{41d}'), ('\u{43e}', - '\u{41e}'), ('\u{43e}', '\u{1c82}'), ('\u{43f}', '\u{41f}'), ('\u{440}', - '\u{420}'), ('\u{441}', '\u{421}'), ('\u{441}', '\u{1c83}'), ('\u{442}', - '\u{422}'), ('\u{442}', '\u{1c84}'), ('\u{442}', '\u{1c85}'), - ('\u{443}', '\u{423}'), ('\u{444}', '\u{424}'), ('\u{445}', '\u{425}'), - ('\u{446}', '\u{426}'), ('\u{447}', '\u{427}'), ('\u{448}', '\u{428}'), - ('\u{449}', '\u{429}'), ('\u{44a}', '\u{42a}'), ('\u{44a}', '\u{1c86}'), - ('\u{44b}', '\u{42b}'), ('\u{44c}', '\u{42c}'), ('\u{44d}', '\u{42d}'), - ('\u{44e}', '\u{42e}'), ('\u{44f}', '\u{42f}'), ('\u{450}', '\u{400}'), - ('\u{451}', '\u{401}'), ('\u{452}', '\u{402}'), ('\u{453}', '\u{403}'), - ('\u{454}', '\u{404}'), ('\u{455}', '\u{405}'), ('\u{456}', '\u{406}'), - ('\u{457}', '\u{407}'), ('\u{458}', '\u{408}'), ('\u{459}', '\u{409}'), - ('\u{45a}', '\u{40a}'), ('\u{45b}', '\u{40b}'), ('\u{45c}', '\u{40c}'), - ('\u{45d}', '\u{40d}'), ('\u{45e}', '\u{40e}'), ('\u{45f}', '\u{40f}'), - ('\u{460}', '\u{461}'), ('\u{461}', '\u{460}'), ('\u{462}', '\u{463}'), - ('\u{462}', '\u{1c87}'), ('\u{463}', '\u{462}'), ('\u{463}', - '\u{1c87}'), ('\u{464}', '\u{465}'), ('\u{465}', '\u{464}'), ('\u{466}', - '\u{467}'), ('\u{467}', '\u{466}'), ('\u{468}', '\u{469}'), ('\u{469}', - '\u{468}'), ('\u{46a}', '\u{46b}'), ('\u{46b}', '\u{46a}'), ('\u{46c}', - '\u{46d}'), ('\u{46d}', '\u{46c}'), ('\u{46e}', '\u{46f}'), ('\u{46f}', - '\u{46e}'), ('\u{470}', '\u{471}'), ('\u{471}', '\u{470}'), ('\u{472}', - '\u{473}'), ('\u{473}', '\u{472}'), ('\u{474}', '\u{475}'), ('\u{475}', - '\u{474}'), ('\u{476}', '\u{477}'), ('\u{477}', '\u{476}'), ('\u{478}', - '\u{479}'), ('\u{479}', '\u{478}'), ('\u{47a}', '\u{47b}'), ('\u{47b}', - '\u{47a}'), ('\u{47c}', '\u{47d}'), ('\u{47d}', '\u{47c}'), ('\u{47e}', - '\u{47f}'), ('\u{47f}', '\u{47e}'), ('\u{480}', '\u{481}'), ('\u{481}', - '\u{480}'), ('\u{48a}', '\u{48b}'), ('\u{48b}', '\u{48a}'), ('\u{48c}', - '\u{48d}'), ('\u{48d}', '\u{48c}'), ('\u{48e}', '\u{48f}'), ('\u{48f}', - '\u{48e}'), ('\u{490}', '\u{491}'), ('\u{491}', '\u{490}'), ('\u{492}', - '\u{493}'), ('\u{493}', '\u{492}'), ('\u{494}', '\u{495}'), ('\u{495}', - '\u{494}'), ('\u{496}', '\u{497}'), ('\u{497}', '\u{496}'), ('\u{498}', - '\u{499}'), ('\u{499}', '\u{498}'), ('\u{49a}', '\u{49b}'), ('\u{49b}', - '\u{49a}'), ('\u{49c}', '\u{49d}'), ('\u{49d}', '\u{49c}'), ('\u{49e}', - '\u{49f}'), ('\u{49f}', '\u{49e}'), ('\u{4a0}', '\u{4a1}'), ('\u{4a1}', - '\u{4a0}'), ('\u{4a2}', '\u{4a3}'), ('\u{4a3}', '\u{4a2}'), ('\u{4a4}', - '\u{4a5}'), ('\u{4a5}', '\u{4a4}'), ('\u{4a6}', '\u{4a7}'), ('\u{4a7}', - '\u{4a6}'), ('\u{4a8}', '\u{4a9}'), ('\u{4a9}', '\u{4a8}'), ('\u{4aa}', - '\u{4ab}'), ('\u{4ab}', '\u{4aa}'), ('\u{4ac}', '\u{4ad}'), ('\u{4ad}', - '\u{4ac}'), ('\u{4ae}', '\u{4af}'), ('\u{4af}', '\u{4ae}'), ('\u{4b0}', - '\u{4b1}'), ('\u{4b1}', '\u{4b0}'), ('\u{4b2}', '\u{4b3}'), ('\u{4b3}', - '\u{4b2}'), ('\u{4b4}', '\u{4b5}'), ('\u{4b5}', '\u{4b4}'), ('\u{4b6}', - '\u{4b7}'), ('\u{4b7}', '\u{4b6}'), ('\u{4b8}', '\u{4b9}'), ('\u{4b9}', - '\u{4b8}'), ('\u{4ba}', '\u{4bb}'), ('\u{4bb}', '\u{4ba}'), ('\u{4bc}', - '\u{4bd}'), ('\u{4bd}', '\u{4bc}'), ('\u{4be}', '\u{4bf}'), ('\u{4bf}', - '\u{4be}'), ('\u{4c0}', '\u{4cf}'), ('\u{4c1}', '\u{4c2}'), ('\u{4c2}', - '\u{4c1}'), ('\u{4c3}', '\u{4c4}'), ('\u{4c4}', '\u{4c3}'), ('\u{4c5}', - '\u{4c6}'), ('\u{4c6}', '\u{4c5}'), ('\u{4c7}', '\u{4c8}'), ('\u{4c8}', - '\u{4c7}'), ('\u{4c9}', '\u{4ca}'), ('\u{4ca}', '\u{4c9}'), ('\u{4cb}', - '\u{4cc}'), ('\u{4cc}', '\u{4cb}'), ('\u{4cd}', '\u{4ce}'), ('\u{4ce}', - '\u{4cd}'), ('\u{4cf}', '\u{4c0}'), ('\u{4d0}', '\u{4d1}'), ('\u{4d1}', - '\u{4d0}'), ('\u{4d2}', '\u{4d3}'), ('\u{4d3}', '\u{4d2}'), ('\u{4d4}', - '\u{4d5}'), ('\u{4d5}', '\u{4d4}'), ('\u{4d6}', '\u{4d7}'), ('\u{4d7}', - '\u{4d6}'), ('\u{4d8}', '\u{4d9}'), ('\u{4d9}', '\u{4d8}'), ('\u{4da}', - '\u{4db}'), ('\u{4db}', '\u{4da}'), ('\u{4dc}', '\u{4dd}'), ('\u{4dd}', - '\u{4dc}'), ('\u{4de}', '\u{4df}'), ('\u{4df}', '\u{4de}'), ('\u{4e0}', - '\u{4e1}'), ('\u{4e1}', '\u{4e0}'), ('\u{4e2}', '\u{4e3}'), ('\u{4e3}', - '\u{4e2}'), ('\u{4e4}', '\u{4e5}'), ('\u{4e5}', '\u{4e4}'), ('\u{4e6}', - '\u{4e7}'), ('\u{4e7}', '\u{4e6}'), ('\u{4e8}', '\u{4e9}'), ('\u{4e9}', - '\u{4e8}'), ('\u{4ea}', '\u{4eb}'), ('\u{4eb}', '\u{4ea}'), ('\u{4ec}', - '\u{4ed}'), ('\u{4ed}', '\u{4ec}'), ('\u{4ee}', '\u{4ef}'), ('\u{4ef}', - '\u{4ee}'), ('\u{4f0}', '\u{4f1}'), ('\u{4f1}', '\u{4f0}'), ('\u{4f2}', - '\u{4f3}'), ('\u{4f3}', '\u{4f2}'), ('\u{4f4}', '\u{4f5}'), ('\u{4f5}', - '\u{4f4}'), ('\u{4f6}', '\u{4f7}'), ('\u{4f7}', '\u{4f6}'), ('\u{4f8}', - '\u{4f9}'), ('\u{4f9}', '\u{4f8}'), ('\u{4fa}', '\u{4fb}'), ('\u{4fb}', - '\u{4fa}'), ('\u{4fc}', '\u{4fd}'), ('\u{4fd}', '\u{4fc}'), ('\u{4fe}', - '\u{4ff}'), ('\u{4ff}', '\u{4fe}'), ('\u{500}', '\u{501}'), ('\u{501}', - '\u{500}'), ('\u{502}', '\u{503}'), ('\u{503}', '\u{502}'), ('\u{504}', - '\u{505}'), ('\u{505}', '\u{504}'), ('\u{506}', '\u{507}'), ('\u{507}', - '\u{506}'), ('\u{508}', '\u{509}'), ('\u{509}', '\u{508}'), ('\u{50a}', - '\u{50b}'), ('\u{50b}', '\u{50a}'), ('\u{50c}', '\u{50d}'), ('\u{50d}', - '\u{50c}'), ('\u{50e}', '\u{50f}'), ('\u{50f}', '\u{50e}'), ('\u{510}', - '\u{511}'), ('\u{511}', '\u{510}'), ('\u{512}', '\u{513}'), ('\u{513}', - '\u{512}'), ('\u{514}', '\u{515}'), ('\u{515}', '\u{514}'), ('\u{516}', - '\u{517}'), ('\u{517}', '\u{516}'), ('\u{518}', '\u{519}'), ('\u{519}', - '\u{518}'), ('\u{51a}', '\u{51b}'), ('\u{51b}', '\u{51a}'), ('\u{51c}', - '\u{51d}'), ('\u{51d}', '\u{51c}'), ('\u{51e}', '\u{51f}'), ('\u{51f}', - '\u{51e}'), ('\u{520}', '\u{521}'), ('\u{521}', '\u{520}'), ('\u{522}', - '\u{523}'), ('\u{523}', '\u{522}'), ('\u{524}', '\u{525}'), ('\u{525}', - '\u{524}'), ('\u{526}', '\u{527}'), ('\u{527}', '\u{526}'), ('\u{528}', - '\u{529}'), ('\u{529}', '\u{528}'), ('\u{52a}', '\u{52b}'), ('\u{52b}', - '\u{52a}'), ('\u{52c}', '\u{52d}'), ('\u{52d}', '\u{52c}'), ('\u{52e}', - '\u{52f}'), ('\u{52f}', '\u{52e}'), ('\u{531}', '\u{561}'), ('\u{532}', - '\u{562}'), ('\u{533}', '\u{563}'), ('\u{534}', '\u{564}'), ('\u{535}', - '\u{565}'), ('\u{536}', '\u{566}'), ('\u{537}', '\u{567}'), ('\u{538}', - '\u{568}'), ('\u{539}', '\u{569}'), ('\u{53a}', '\u{56a}'), ('\u{53b}', - '\u{56b}'), ('\u{53c}', '\u{56c}'), ('\u{53d}', '\u{56d}'), ('\u{53e}', - '\u{56e}'), ('\u{53f}', '\u{56f}'), ('\u{540}', '\u{570}'), ('\u{541}', - '\u{571}'), ('\u{542}', '\u{572}'), ('\u{543}', '\u{573}'), ('\u{544}', - '\u{574}'), ('\u{545}', '\u{575}'), ('\u{546}', '\u{576}'), ('\u{547}', - '\u{577}'), ('\u{548}', '\u{578}'), ('\u{549}', '\u{579}'), ('\u{54a}', - '\u{57a}'), ('\u{54b}', '\u{57b}'), ('\u{54c}', '\u{57c}'), ('\u{54d}', - '\u{57d}'), ('\u{54e}', '\u{57e}'), ('\u{54f}', '\u{57f}'), ('\u{550}', - '\u{580}'), ('\u{551}', '\u{581}'), ('\u{552}', '\u{582}'), ('\u{553}', - '\u{583}'), ('\u{554}', '\u{584}'), ('\u{555}', '\u{585}'), ('\u{556}', - '\u{586}'), ('\u{561}', '\u{531}'), ('\u{562}', '\u{532}'), ('\u{563}', - '\u{533}'), ('\u{564}', '\u{534}'), ('\u{565}', '\u{535}'), ('\u{566}', - '\u{536}'), ('\u{567}', '\u{537}'), ('\u{568}', '\u{538}'), ('\u{569}', - '\u{539}'), ('\u{56a}', '\u{53a}'), ('\u{56b}', '\u{53b}'), ('\u{56c}', - '\u{53c}'), ('\u{56d}', '\u{53d}'), ('\u{56e}', '\u{53e}'), ('\u{56f}', - '\u{53f}'), ('\u{570}', '\u{540}'), ('\u{571}', '\u{541}'), ('\u{572}', - '\u{542}'), ('\u{573}', '\u{543}'), ('\u{574}', '\u{544}'), ('\u{575}', - '\u{545}'), ('\u{576}', '\u{546}'), ('\u{577}', '\u{547}'), ('\u{578}', - '\u{548}'), ('\u{579}', '\u{549}'), ('\u{57a}', '\u{54a}'), ('\u{57b}', - '\u{54b}'), ('\u{57c}', '\u{54c}'), ('\u{57d}', '\u{54d}'), ('\u{57e}', - '\u{54e}'), ('\u{57f}', '\u{54f}'), ('\u{580}', '\u{550}'), ('\u{581}', - '\u{551}'), ('\u{582}', '\u{552}'), ('\u{583}', '\u{553}'), ('\u{584}', - '\u{554}'), ('\u{585}', '\u{555}'), ('\u{586}', '\u{556}'), ('\u{10a0}', - '\u{2d00}'), ('\u{10a1}', '\u{2d01}'), ('\u{10a2}', '\u{2d02}'), - ('\u{10a3}', '\u{2d03}'), ('\u{10a4}', '\u{2d04}'), ('\u{10a5}', - '\u{2d05}'), ('\u{10a6}', '\u{2d06}'), ('\u{10a7}', '\u{2d07}'), - ('\u{10a8}', '\u{2d08}'), ('\u{10a9}', '\u{2d09}'), ('\u{10aa}', - '\u{2d0a}'), ('\u{10ab}', '\u{2d0b}'), ('\u{10ac}', '\u{2d0c}'), - ('\u{10ad}', '\u{2d0d}'), ('\u{10ae}', '\u{2d0e}'), ('\u{10af}', - '\u{2d0f}'), ('\u{10b0}', '\u{2d10}'), ('\u{10b1}', '\u{2d11}'), - ('\u{10b2}', '\u{2d12}'), ('\u{10b3}', '\u{2d13}'), ('\u{10b4}', - '\u{2d14}'), ('\u{10b5}', '\u{2d15}'), ('\u{10b6}', '\u{2d16}'), - ('\u{10b7}', '\u{2d17}'), ('\u{10b8}', '\u{2d18}'), ('\u{10b9}', - '\u{2d19}'), ('\u{10ba}', '\u{2d1a}'), ('\u{10bb}', '\u{2d1b}'), - ('\u{10bc}', '\u{2d1c}'), ('\u{10bd}', '\u{2d1d}'), ('\u{10be}', - '\u{2d1e}'), ('\u{10bf}', '\u{2d1f}'), ('\u{10c0}', '\u{2d20}'), - ('\u{10c1}', '\u{2d21}'), ('\u{10c2}', '\u{2d22}'), ('\u{10c3}', - '\u{2d23}'), ('\u{10c4}', '\u{2d24}'), ('\u{10c5}', '\u{2d25}'), - ('\u{10c7}', '\u{2d27}'), ('\u{10cd}', '\u{2d2d}'), ('\u{13a0}', - '\u{ab70}'), ('\u{13a1}', '\u{ab71}'), ('\u{13a2}', '\u{ab72}'), - ('\u{13a3}', '\u{ab73}'), ('\u{13a4}', '\u{ab74}'), ('\u{13a5}', - '\u{ab75}'), ('\u{13a6}', '\u{ab76}'), ('\u{13a7}', '\u{ab77}'), - ('\u{13a8}', '\u{ab78}'), ('\u{13a9}', '\u{ab79}'), ('\u{13aa}', - '\u{ab7a}'), ('\u{13ab}', '\u{ab7b}'), ('\u{13ac}', '\u{ab7c}'), - ('\u{13ad}', '\u{ab7d}'), ('\u{13ae}', '\u{ab7e}'), ('\u{13af}', - '\u{ab7f}'), ('\u{13b0}', '\u{ab80}'), ('\u{13b1}', '\u{ab81}'), - ('\u{13b2}', '\u{ab82}'), ('\u{13b3}', '\u{ab83}'), ('\u{13b4}', - '\u{ab84}'), ('\u{13b5}', '\u{ab85}'), ('\u{13b6}', '\u{ab86}'), - ('\u{13b7}', '\u{ab87}'), ('\u{13b8}', '\u{ab88}'), ('\u{13b9}', - '\u{ab89}'), ('\u{13ba}', '\u{ab8a}'), ('\u{13bb}', '\u{ab8b}'), - ('\u{13bc}', '\u{ab8c}'), ('\u{13bd}', '\u{ab8d}'), ('\u{13be}', - '\u{ab8e}'), ('\u{13bf}', '\u{ab8f}'), ('\u{13c0}', '\u{ab90}'), - ('\u{13c1}', '\u{ab91}'), ('\u{13c2}', '\u{ab92}'), ('\u{13c3}', - '\u{ab93}'), ('\u{13c4}', '\u{ab94}'), ('\u{13c5}', '\u{ab95}'), - ('\u{13c6}', '\u{ab96}'), ('\u{13c7}', '\u{ab97}'), ('\u{13c8}', - '\u{ab98}'), ('\u{13c9}', '\u{ab99}'), ('\u{13ca}', '\u{ab9a}'), - ('\u{13cb}', '\u{ab9b}'), ('\u{13cc}', '\u{ab9c}'), ('\u{13cd}', - '\u{ab9d}'), ('\u{13ce}', '\u{ab9e}'), ('\u{13cf}', '\u{ab9f}'), - ('\u{13d0}', '\u{aba0}'), ('\u{13d1}', '\u{aba1}'), ('\u{13d2}', - '\u{aba2}'), ('\u{13d3}', '\u{aba3}'), ('\u{13d4}', '\u{aba4}'), - ('\u{13d5}', '\u{aba5}'), ('\u{13d6}', '\u{aba6}'), ('\u{13d7}', - '\u{aba7}'), ('\u{13d8}', '\u{aba8}'), ('\u{13d9}', '\u{aba9}'), - ('\u{13da}', '\u{abaa}'), ('\u{13db}', '\u{abab}'), ('\u{13dc}', - '\u{abac}'), ('\u{13dd}', '\u{abad}'), ('\u{13de}', '\u{abae}'), - ('\u{13df}', '\u{abaf}'), ('\u{13e0}', '\u{abb0}'), ('\u{13e1}', - '\u{abb1}'), ('\u{13e2}', '\u{abb2}'), ('\u{13e3}', '\u{abb3}'), - ('\u{13e4}', '\u{abb4}'), ('\u{13e5}', '\u{abb5}'), ('\u{13e6}', - '\u{abb6}'), ('\u{13e7}', '\u{abb7}'), ('\u{13e8}', '\u{abb8}'), - ('\u{13e9}', '\u{abb9}'), ('\u{13ea}', '\u{abba}'), ('\u{13eb}', - '\u{abbb}'), ('\u{13ec}', '\u{abbc}'), ('\u{13ed}', '\u{abbd}'), - ('\u{13ee}', '\u{abbe}'), ('\u{13ef}', '\u{abbf}'), ('\u{13f0}', - '\u{13f8}'), ('\u{13f1}', '\u{13f9}'), ('\u{13f2}', '\u{13fa}'), - ('\u{13f3}', '\u{13fb}'), ('\u{13f4}', '\u{13fc}'), ('\u{13f5}', - '\u{13fd}'), ('\u{13f8}', '\u{13f0}'), ('\u{13f9}', '\u{13f1}'), - ('\u{13fa}', '\u{13f2}'), ('\u{13fb}', '\u{13f3}'), ('\u{13fc}', - '\u{13f4}'), ('\u{13fd}', '\u{13f5}'), ('\u{1c80}', '\u{412}'), - ('\u{1c80}', '\u{432}'), ('\u{1c81}', '\u{414}'), ('\u{1c81}', - '\u{434}'), ('\u{1c82}', '\u{41e}'), ('\u{1c82}', '\u{43e}'), - ('\u{1c83}', '\u{421}'), ('\u{1c83}', '\u{441}'), ('\u{1c84}', - '\u{422}'), ('\u{1c84}', '\u{442}'), ('\u{1c84}', '\u{1c85}'), - ('\u{1c85}', '\u{422}'), ('\u{1c85}', '\u{442}'), ('\u{1c85}', - '\u{1c84}'), ('\u{1c86}', '\u{42a}'), ('\u{1c86}', '\u{44a}'), - ('\u{1c87}', '\u{462}'), ('\u{1c87}', '\u{463}'), ('\u{1c88}', - '\u{a64a}'), ('\u{1c88}', '\u{a64b}'), ('\u{1d79}', '\u{a77d}'), - ('\u{1d7d}', '\u{2c63}'), ('\u{1e00}', '\u{1e01}'), ('\u{1e01}', - '\u{1e00}'), ('\u{1e02}', '\u{1e03}'), ('\u{1e03}', '\u{1e02}'), - ('\u{1e04}', '\u{1e05}'), ('\u{1e05}', '\u{1e04}'), ('\u{1e06}', - '\u{1e07}'), ('\u{1e07}', '\u{1e06}'), ('\u{1e08}', '\u{1e09}'), - ('\u{1e09}', '\u{1e08}'), ('\u{1e0a}', '\u{1e0b}'), ('\u{1e0b}', - '\u{1e0a}'), ('\u{1e0c}', '\u{1e0d}'), ('\u{1e0d}', '\u{1e0c}'), - ('\u{1e0e}', '\u{1e0f}'), ('\u{1e0f}', '\u{1e0e}'), ('\u{1e10}', - '\u{1e11}'), ('\u{1e11}', '\u{1e10}'), ('\u{1e12}', '\u{1e13}'), - ('\u{1e13}', '\u{1e12}'), ('\u{1e14}', '\u{1e15}'), ('\u{1e15}', - '\u{1e14}'), ('\u{1e16}', '\u{1e17}'), ('\u{1e17}', '\u{1e16}'), - ('\u{1e18}', '\u{1e19}'), ('\u{1e19}', '\u{1e18}'), ('\u{1e1a}', - '\u{1e1b}'), ('\u{1e1b}', '\u{1e1a}'), ('\u{1e1c}', '\u{1e1d}'), - ('\u{1e1d}', '\u{1e1c}'), ('\u{1e1e}', '\u{1e1f}'), ('\u{1e1f}', - '\u{1e1e}'), ('\u{1e20}', '\u{1e21}'), ('\u{1e21}', '\u{1e20}'), - ('\u{1e22}', '\u{1e23}'), ('\u{1e23}', '\u{1e22}'), ('\u{1e24}', - '\u{1e25}'), ('\u{1e25}', '\u{1e24}'), ('\u{1e26}', '\u{1e27}'), - ('\u{1e27}', '\u{1e26}'), ('\u{1e28}', '\u{1e29}'), ('\u{1e29}', - '\u{1e28}'), ('\u{1e2a}', '\u{1e2b}'), ('\u{1e2b}', '\u{1e2a}'), - ('\u{1e2c}', '\u{1e2d}'), ('\u{1e2d}', '\u{1e2c}'), ('\u{1e2e}', - '\u{1e2f}'), ('\u{1e2f}', '\u{1e2e}'), ('\u{1e30}', '\u{1e31}'), - ('\u{1e31}', '\u{1e30}'), ('\u{1e32}', '\u{1e33}'), ('\u{1e33}', - '\u{1e32}'), ('\u{1e34}', '\u{1e35}'), ('\u{1e35}', '\u{1e34}'), - ('\u{1e36}', '\u{1e37}'), ('\u{1e37}', '\u{1e36}'), ('\u{1e38}', - '\u{1e39}'), ('\u{1e39}', '\u{1e38}'), ('\u{1e3a}', '\u{1e3b}'), - ('\u{1e3b}', '\u{1e3a}'), ('\u{1e3c}', '\u{1e3d}'), ('\u{1e3d}', - '\u{1e3c}'), ('\u{1e3e}', '\u{1e3f}'), ('\u{1e3f}', '\u{1e3e}'), - ('\u{1e40}', '\u{1e41}'), ('\u{1e41}', '\u{1e40}'), ('\u{1e42}', - '\u{1e43}'), ('\u{1e43}', '\u{1e42}'), ('\u{1e44}', '\u{1e45}'), - ('\u{1e45}', '\u{1e44}'), ('\u{1e46}', '\u{1e47}'), ('\u{1e47}', - '\u{1e46}'), ('\u{1e48}', '\u{1e49}'), ('\u{1e49}', '\u{1e48}'), - ('\u{1e4a}', '\u{1e4b}'), ('\u{1e4b}', '\u{1e4a}'), ('\u{1e4c}', - '\u{1e4d}'), ('\u{1e4d}', '\u{1e4c}'), ('\u{1e4e}', '\u{1e4f}'), - ('\u{1e4f}', '\u{1e4e}'), ('\u{1e50}', '\u{1e51}'), ('\u{1e51}', - '\u{1e50}'), ('\u{1e52}', '\u{1e53}'), ('\u{1e53}', '\u{1e52}'), - ('\u{1e54}', '\u{1e55}'), ('\u{1e55}', '\u{1e54}'), ('\u{1e56}', - '\u{1e57}'), ('\u{1e57}', '\u{1e56}'), ('\u{1e58}', '\u{1e59}'), - ('\u{1e59}', '\u{1e58}'), ('\u{1e5a}', '\u{1e5b}'), ('\u{1e5b}', - '\u{1e5a}'), ('\u{1e5c}', '\u{1e5d}'), ('\u{1e5d}', '\u{1e5c}'), - ('\u{1e5e}', '\u{1e5f}'), ('\u{1e5f}', '\u{1e5e}'), ('\u{1e60}', - '\u{1e61}'), ('\u{1e60}', '\u{1e9b}'), ('\u{1e61}', '\u{1e60}'), - ('\u{1e61}', '\u{1e9b}'), ('\u{1e62}', '\u{1e63}'), ('\u{1e63}', - '\u{1e62}'), ('\u{1e64}', '\u{1e65}'), ('\u{1e65}', '\u{1e64}'), - ('\u{1e66}', '\u{1e67}'), ('\u{1e67}', '\u{1e66}'), ('\u{1e68}', - '\u{1e69}'), ('\u{1e69}', '\u{1e68}'), ('\u{1e6a}', '\u{1e6b}'), - ('\u{1e6b}', '\u{1e6a}'), ('\u{1e6c}', '\u{1e6d}'), ('\u{1e6d}', - '\u{1e6c}'), ('\u{1e6e}', '\u{1e6f}'), ('\u{1e6f}', '\u{1e6e}'), - ('\u{1e70}', '\u{1e71}'), ('\u{1e71}', '\u{1e70}'), ('\u{1e72}', - '\u{1e73}'), ('\u{1e73}', '\u{1e72}'), ('\u{1e74}', '\u{1e75}'), - ('\u{1e75}', '\u{1e74}'), ('\u{1e76}', '\u{1e77}'), ('\u{1e77}', - '\u{1e76}'), ('\u{1e78}', '\u{1e79}'), ('\u{1e79}', '\u{1e78}'), - ('\u{1e7a}', '\u{1e7b}'), ('\u{1e7b}', '\u{1e7a}'), ('\u{1e7c}', - '\u{1e7d}'), ('\u{1e7d}', '\u{1e7c}'), ('\u{1e7e}', '\u{1e7f}'), - ('\u{1e7f}', '\u{1e7e}'), ('\u{1e80}', '\u{1e81}'), ('\u{1e81}', - '\u{1e80}'), ('\u{1e82}', '\u{1e83}'), ('\u{1e83}', '\u{1e82}'), - ('\u{1e84}', '\u{1e85}'), ('\u{1e85}', '\u{1e84}'), ('\u{1e86}', - '\u{1e87}'), ('\u{1e87}', '\u{1e86}'), ('\u{1e88}', '\u{1e89}'), - ('\u{1e89}', '\u{1e88}'), ('\u{1e8a}', '\u{1e8b}'), ('\u{1e8b}', - '\u{1e8a}'), ('\u{1e8c}', '\u{1e8d}'), ('\u{1e8d}', '\u{1e8c}'), - ('\u{1e8e}', '\u{1e8f}'), ('\u{1e8f}', '\u{1e8e}'), ('\u{1e90}', - '\u{1e91}'), ('\u{1e91}', '\u{1e90}'), ('\u{1e92}', '\u{1e93}'), - ('\u{1e93}', '\u{1e92}'), ('\u{1e94}', '\u{1e95}'), ('\u{1e95}', - '\u{1e94}'), ('\u{1e9b}', '\u{1e60}'), ('\u{1e9b}', '\u{1e61}'), - ('\u{1e9e}', '\u{df}'), ('\u{1ea0}', '\u{1ea1}'), ('\u{1ea1}', - '\u{1ea0}'), ('\u{1ea2}', '\u{1ea3}'), ('\u{1ea3}', '\u{1ea2}'), - ('\u{1ea4}', '\u{1ea5}'), ('\u{1ea5}', '\u{1ea4}'), ('\u{1ea6}', - '\u{1ea7}'), ('\u{1ea7}', '\u{1ea6}'), ('\u{1ea8}', '\u{1ea9}'), - ('\u{1ea9}', '\u{1ea8}'), ('\u{1eaa}', '\u{1eab}'), ('\u{1eab}', - '\u{1eaa}'), ('\u{1eac}', '\u{1ead}'), ('\u{1ead}', '\u{1eac}'), - ('\u{1eae}', '\u{1eaf}'), ('\u{1eaf}', '\u{1eae}'), ('\u{1eb0}', - '\u{1eb1}'), ('\u{1eb1}', '\u{1eb0}'), ('\u{1eb2}', '\u{1eb3}'), - ('\u{1eb3}', '\u{1eb2}'), ('\u{1eb4}', '\u{1eb5}'), ('\u{1eb5}', - '\u{1eb4}'), ('\u{1eb6}', '\u{1eb7}'), ('\u{1eb7}', '\u{1eb6}'), - ('\u{1eb8}', '\u{1eb9}'), ('\u{1eb9}', '\u{1eb8}'), ('\u{1eba}', - '\u{1ebb}'), ('\u{1ebb}', '\u{1eba}'), ('\u{1ebc}', '\u{1ebd}'), - ('\u{1ebd}', '\u{1ebc}'), ('\u{1ebe}', '\u{1ebf}'), ('\u{1ebf}', - '\u{1ebe}'), ('\u{1ec0}', '\u{1ec1}'), ('\u{1ec1}', '\u{1ec0}'), - ('\u{1ec2}', '\u{1ec3}'), ('\u{1ec3}', '\u{1ec2}'), ('\u{1ec4}', - '\u{1ec5}'), ('\u{1ec5}', '\u{1ec4}'), ('\u{1ec6}', '\u{1ec7}'), - ('\u{1ec7}', '\u{1ec6}'), ('\u{1ec8}', '\u{1ec9}'), ('\u{1ec9}', - '\u{1ec8}'), ('\u{1eca}', '\u{1ecb}'), ('\u{1ecb}', '\u{1eca}'), - ('\u{1ecc}', '\u{1ecd}'), ('\u{1ecd}', '\u{1ecc}'), ('\u{1ece}', - '\u{1ecf}'), ('\u{1ecf}', '\u{1ece}'), ('\u{1ed0}', '\u{1ed1}'), - ('\u{1ed1}', '\u{1ed0}'), ('\u{1ed2}', '\u{1ed3}'), ('\u{1ed3}', - '\u{1ed2}'), ('\u{1ed4}', '\u{1ed5}'), ('\u{1ed5}', '\u{1ed4}'), - ('\u{1ed6}', '\u{1ed7}'), ('\u{1ed7}', '\u{1ed6}'), ('\u{1ed8}', - '\u{1ed9}'), ('\u{1ed9}', '\u{1ed8}'), ('\u{1eda}', '\u{1edb}'), - ('\u{1edb}', '\u{1eda}'), ('\u{1edc}', '\u{1edd}'), ('\u{1edd}', - '\u{1edc}'), ('\u{1ede}', '\u{1edf}'), ('\u{1edf}', '\u{1ede}'), - ('\u{1ee0}', '\u{1ee1}'), ('\u{1ee1}', '\u{1ee0}'), ('\u{1ee2}', - '\u{1ee3}'), ('\u{1ee3}', '\u{1ee2}'), ('\u{1ee4}', '\u{1ee5}'), - ('\u{1ee5}', '\u{1ee4}'), ('\u{1ee6}', '\u{1ee7}'), ('\u{1ee7}', - '\u{1ee6}'), ('\u{1ee8}', '\u{1ee9}'), ('\u{1ee9}', '\u{1ee8}'), - ('\u{1eea}', '\u{1eeb}'), ('\u{1eeb}', '\u{1eea}'), ('\u{1eec}', - '\u{1eed}'), ('\u{1eed}', '\u{1eec}'), ('\u{1eee}', '\u{1eef}'), - ('\u{1eef}', '\u{1eee}'), ('\u{1ef0}', '\u{1ef1}'), ('\u{1ef1}', - '\u{1ef0}'), ('\u{1ef2}', '\u{1ef3}'), ('\u{1ef3}', '\u{1ef2}'), - ('\u{1ef4}', '\u{1ef5}'), ('\u{1ef5}', '\u{1ef4}'), ('\u{1ef6}', - '\u{1ef7}'), ('\u{1ef7}', '\u{1ef6}'), ('\u{1ef8}', '\u{1ef9}'), - ('\u{1ef9}', '\u{1ef8}'), ('\u{1efa}', '\u{1efb}'), ('\u{1efb}', - '\u{1efa}'), ('\u{1efc}', '\u{1efd}'), ('\u{1efd}', '\u{1efc}'), - ('\u{1efe}', '\u{1eff}'), ('\u{1eff}', '\u{1efe}'), ('\u{1f00}', - '\u{1f08}'), ('\u{1f01}', '\u{1f09}'), ('\u{1f02}', '\u{1f0a}'), - ('\u{1f03}', '\u{1f0b}'), ('\u{1f04}', '\u{1f0c}'), ('\u{1f05}', - '\u{1f0d}'), ('\u{1f06}', '\u{1f0e}'), ('\u{1f07}', '\u{1f0f}'), - ('\u{1f08}', '\u{1f00}'), ('\u{1f09}', '\u{1f01}'), ('\u{1f0a}', - '\u{1f02}'), ('\u{1f0b}', '\u{1f03}'), ('\u{1f0c}', '\u{1f04}'), - ('\u{1f0d}', '\u{1f05}'), ('\u{1f0e}', '\u{1f06}'), ('\u{1f0f}', - '\u{1f07}'), ('\u{1f10}', '\u{1f18}'), ('\u{1f11}', '\u{1f19}'), - ('\u{1f12}', '\u{1f1a}'), ('\u{1f13}', '\u{1f1b}'), ('\u{1f14}', - '\u{1f1c}'), ('\u{1f15}', '\u{1f1d}'), ('\u{1f18}', '\u{1f10}'), - ('\u{1f19}', '\u{1f11}'), ('\u{1f1a}', '\u{1f12}'), ('\u{1f1b}', - '\u{1f13}'), ('\u{1f1c}', '\u{1f14}'), ('\u{1f1d}', '\u{1f15}'), - ('\u{1f20}', '\u{1f28}'), ('\u{1f21}', '\u{1f29}'), ('\u{1f22}', - '\u{1f2a}'), ('\u{1f23}', '\u{1f2b}'), ('\u{1f24}', '\u{1f2c}'), - ('\u{1f25}', '\u{1f2d}'), ('\u{1f26}', '\u{1f2e}'), ('\u{1f27}', - '\u{1f2f}'), ('\u{1f28}', '\u{1f20}'), ('\u{1f29}', '\u{1f21}'), - ('\u{1f2a}', '\u{1f22}'), ('\u{1f2b}', '\u{1f23}'), ('\u{1f2c}', - '\u{1f24}'), ('\u{1f2d}', '\u{1f25}'), ('\u{1f2e}', '\u{1f26}'), - ('\u{1f2f}', '\u{1f27}'), ('\u{1f30}', '\u{1f38}'), ('\u{1f31}', - '\u{1f39}'), ('\u{1f32}', '\u{1f3a}'), ('\u{1f33}', '\u{1f3b}'), - ('\u{1f34}', '\u{1f3c}'), ('\u{1f35}', '\u{1f3d}'), ('\u{1f36}', - '\u{1f3e}'), ('\u{1f37}', '\u{1f3f}'), ('\u{1f38}', '\u{1f30}'), - ('\u{1f39}', '\u{1f31}'), ('\u{1f3a}', '\u{1f32}'), ('\u{1f3b}', - '\u{1f33}'), ('\u{1f3c}', '\u{1f34}'), ('\u{1f3d}', '\u{1f35}'), - ('\u{1f3e}', '\u{1f36}'), ('\u{1f3f}', '\u{1f37}'), ('\u{1f40}', - '\u{1f48}'), ('\u{1f41}', '\u{1f49}'), ('\u{1f42}', '\u{1f4a}'), - ('\u{1f43}', '\u{1f4b}'), ('\u{1f44}', '\u{1f4c}'), ('\u{1f45}', - '\u{1f4d}'), ('\u{1f48}', '\u{1f40}'), ('\u{1f49}', '\u{1f41}'), - ('\u{1f4a}', '\u{1f42}'), ('\u{1f4b}', '\u{1f43}'), ('\u{1f4c}', - '\u{1f44}'), ('\u{1f4d}', '\u{1f45}'), ('\u{1f51}', '\u{1f59}'), - ('\u{1f53}', '\u{1f5b}'), ('\u{1f55}', '\u{1f5d}'), ('\u{1f57}', - '\u{1f5f}'), ('\u{1f59}', '\u{1f51}'), ('\u{1f5b}', '\u{1f53}'), - ('\u{1f5d}', '\u{1f55}'), ('\u{1f5f}', '\u{1f57}'), ('\u{1f60}', - '\u{1f68}'), ('\u{1f61}', '\u{1f69}'), ('\u{1f62}', '\u{1f6a}'), - ('\u{1f63}', '\u{1f6b}'), ('\u{1f64}', '\u{1f6c}'), ('\u{1f65}', - '\u{1f6d}'), ('\u{1f66}', '\u{1f6e}'), ('\u{1f67}', '\u{1f6f}'), - ('\u{1f68}', '\u{1f60}'), ('\u{1f69}', '\u{1f61}'), ('\u{1f6a}', - '\u{1f62}'), ('\u{1f6b}', '\u{1f63}'), ('\u{1f6c}', '\u{1f64}'), - ('\u{1f6d}', '\u{1f65}'), ('\u{1f6e}', '\u{1f66}'), ('\u{1f6f}', - '\u{1f67}'), ('\u{1f70}', '\u{1fba}'), ('\u{1f71}', '\u{1fbb}'), - ('\u{1f72}', '\u{1fc8}'), ('\u{1f73}', '\u{1fc9}'), ('\u{1f74}', - '\u{1fca}'), ('\u{1f75}', '\u{1fcb}'), ('\u{1f76}', '\u{1fda}'), - ('\u{1f77}', '\u{1fdb}'), ('\u{1f78}', '\u{1ff8}'), ('\u{1f79}', - '\u{1ff9}'), ('\u{1f7a}', '\u{1fea}'), ('\u{1f7b}', '\u{1feb}'), - ('\u{1f7c}', '\u{1ffa}'), ('\u{1f7d}', '\u{1ffb}'), ('\u{1f80}', - '\u{1f88}'), ('\u{1f81}', '\u{1f89}'), ('\u{1f82}', '\u{1f8a}'), - ('\u{1f83}', '\u{1f8b}'), ('\u{1f84}', '\u{1f8c}'), ('\u{1f85}', - '\u{1f8d}'), ('\u{1f86}', '\u{1f8e}'), ('\u{1f87}', '\u{1f8f}'), - ('\u{1f88}', '\u{1f80}'), ('\u{1f89}', '\u{1f81}'), ('\u{1f8a}', - '\u{1f82}'), ('\u{1f8b}', '\u{1f83}'), ('\u{1f8c}', '\u{1f84}'), - ('\u{1f8d}', '\u{1f85}'), ('\u{1f8e}', '\u{1f86}'), ('\u{1f8f}', - '\u{1f87}'), ('\u{1f90}', '\u{1f98}'), ('\u{1f91}', '\u{1f99}'), - ('\u{1f92}', '\u{1f9a}'), ('\u{1f93}', '\u{1f9b}'), ('\u{1f94}', - '\u{1f9c}'), ('\u{1f95}', '\u{1f9d}'), ('\u{1f96}', '\u{1f9e}'), - ('\u{1f97}', '\u{1f9f}'), ('\u{1f98}', '\u{1f90}'), ('\u{1f99}', - '\u{1f91}'), ('\u{1f9a}', '\u{1f92}'), ('\u{1f9b}', '\u{1f93}'), - ('\u{1f9c}', '\u{1f94}'), ('\u{1f9d}', '\u{1f95}'), ('\u{1f9e}', - '\u{1f96}'), ('\u{1f9f}', '\u{1f97}'), ('\u{1fa0}', '\u{1fa8}'), - ('\u{1fa1}', '\u{1fa9}'), ('\u{1fa2}', '\u{1faa}'), ('\u{1fa3}', - '\u{1fab}'), ('\u{1fa4}', '\u{1fac}'), ('\u{1fa5}', '\u{1fad}'), - ('\u{1fa6}', '\u{1fae}'), ('\u{1fa7}', '\u{1faf}'), ('\u{1fa8}', - '\u{1fa0}'), ('\u{1fa9}', '\u{1fa1}'), ('\u{1faa}', '\u{1fa2}'), - ('\u{1fab}', '\u{1fa3}'), ('\u{1fac}', '\u{1fa4}'), ('\u{1fad}', - '\u{1fa5}'), ('\u{1fae}', '\u{1fa6}'), ('\u{1faf}', '\u{1fa7}'), - ('\u{1fb0}', '\u{1fb8}'), ('\u{1fb1}', '\u{1fb9}'), ('\u{1fb3}', - '\u{1fbc}'), ('\u{1fb8}', '\u{1fb0}'), ('\u{1fb9}', '\u{1fb1}'), - ('\u{1fba}', '\u{1f70}'), ('\u{1fbb}', '\u{1f71}'), ('\u{1fbc}', - '\u{1fb3}'), ('\u{1fbe}', '\u{345}'), ('\u{1fbe}', '\u{399}'), - ('\u{1fbe}', '\u{3b9}'), ('\u{1fc3}', '\u{1fcc}'), ('\u{1fc8}', - '\u{1f72}'), ('\u{1fc9}', '\u{1f73}'), ('\u{1fca}', '\u{1f74}'), - ('\u{1fcb}', '\u{1f75}'), ('\u{1fcc}', '\u{1fc3}'), ('\u{1fd0}', - '\u{1fd8}'), ('\u{1fd1}', '\u{1fd9}'), ('\u{1fd8}', '\u{1fd0}'), - ('\u{1fd9}', '\u{1fd1}'), ('\u{1fda}', '\u{1f76}'), ('\u{1fdb}', - '\u{1f77}'), ('\u{1fe0}', '\u{1fe8}'), ('\u{1fe1}', '\u{1fe9}'), - ('\u{1fe5}', '\u{1fec}'), ('\u{1fe8}', '\u{1fe0}'), ('\u{1fe9}', - '\u{1fe1}'), ('\u{1fea}', '\u{1f7a}'), ('\u{1feb}', '\u{1f7b}'), - ('\u{1fec}', '\u{1fe5}'), ('\u{1ff3}', '\u{1ffc}'), ('\u{1ff8}', - '\u{1f78}'), ('\u{1ff9}', '\u{1f79}'), ('\u{1ffa}', '\u{1f7c}'), - ('\u{1ffb}', '\u{1f7d}'), ('\u{1ffc}', '\u{1ff3}'), ('\u{2126}', - '\u{3a9}'), ('\u{2126}', '\u{3c9}'), ('\u{212a}', '\u{4b}'), - ('\u{212a}', '\u{6b}'), ('\u{212b}', '\u{c5}'), ('\u{212b}', '\u{e5}'), - ('\u{2132}', '\u{214e}'), ('\u{214e}', '\u{2132}'), ('\u{2160}', - '\u{2170}'), ('\u{2161}', '\u{2171}'), ('\u{2162}', '\u{2172}'), - ('\u{2163}', '\u{2173}'), ('\u{2164}', '\u{2174}'), ('\u{2165}', - '\u{2175}'), ('\u{2166}', '\u{2176}'), ('\u{2167}', '\u{2177}'), - ('\u{2168}', '\u{2178}'), ('\u{2169}', '\u{2179}'), ('\u{216a}', - '\u{217a}'), ('\u{216b}', '\u{217b}'), ('\u{216c}', '\u{217c}'), - ('\u{216d}', '\u{217d}'), ('\u{216e}', '\u{217e}'), ('\u{216f}', - '\u{217f}'), ('\u{2170}', '\u{2160}'), ('\u{2171}', '\u{2161}'), - ('\u{2172}', '\u{2162}'), ('\u{2173}', '\u{2163}'), ('\u{2174}', - '\u{2164}'), ('\u{2175}', '\u{2165}'), ('\u{2176}', '\u{2166}'), - ('\u{2177}', '\u{2167}'), ('\u{2178}', '\u{2168}'), ('\u{2179}', - '\u{2169}'), ('\u{217a}', '\u{216a}'), ('\u{217b}', '\u{216b}'), - ('\u{217c}', '\u{216c}'), ('\u{217d}', '\u{216d}'), ('\u{217e}', - '\u{216e}'), ('\u{217f}', '\u{216f}'), ('\u{2183}', '\u{2184}'), - ('\u{2184}', '\u{2183}'), ('\u{24b6}', '\u{24d0}'), ('\u{24b7}', - '\u{24d1}'), ('\u{24b8}', '\u{24d2}'), ('\u{24b9}', '\u{24d3}'), - ('\u{24ba}', '\u{24d4}'), ('\u{24bb}', '\u{24d5}'), ('\u{24bc}', - '\u{24d6}'), ('\u{24bd}', '\u{24d7}'), ('\u{24be}', '\u{24d8}'), - ('\u{24bf}', '\u{24d9}'), ('\u{24c0}', '\u{24da}'), ('\u{24c1}', - '\u{24db}'), ('\u{24c2}', '\u{24dc}'), ('\u{24c3}', '\u{24dd}'), - ('\u{24c4}', '\u{24de}'), ('\u{24c5}', '\u{24df}'), ('\u{24c6}', - '\u{24e0}'), ('\u{24c7}', '\u{24e1}'), ('\u{24c8}', '\u{24e2}'), - ('\u{24c9}', '\u{24e3}'), ('\u{24ca}', '\u{24e4}'), ('\u{24cb}', - '\u{24e5}'), ('\u{24cc}', '\u{24e6}'), ('\u{24cd}', '\u{24e7}'), - ('\u{24ce}', '\u{24e8}'), ('\u{24cf}', '\u{24e9}'), ('\u{24d0}', - '\u{24b6}'), ('\u{24d1}', '\u{24b7}'), ('\u{24d2}', '\u{24b8}'), - ('\u{24d3}', '\u{24b9}'), ('\u{24d4}', '\u{24ba}'), ('\u{24d5}', - '\u{24bb}'), ('\u{24d6}', '\u{24bc}'), ('\u{24d7}', '\u{24bd}'), - ('\u{24d8}', '\u{24be}'), ('\u{24d9}', '\u{24bf}'), ('\u{24da}', - '\u{24c0}'), ('\u{24db}', '\u{24c1}'), ('\u{24dc}', '\u{24c2}'), - ('\u{24dd}', '\u{24c3}'), ('\u{24de}', '\u{24c4}'), ('\u{24df}', - '\u{24c5}'), ('\u{24e0}', '\u{24c6}'), ('\u{24e1}', '\u{24c7}'), - ('\u{24e2}', '\u{24c8}'), ('\u{24e3}', '\u{24c9}'), ('\u{24e4}', - '\u{24ca}'), ('\u{24e5}', '\u{24cb}'), ('\u{24e6}', '\u{24cc}'), - ('\u{24e7}', '\u{24cd}'), ('\u{24e8}', '\u{24ce}'), ('\u{24e9}', - '\u{24cf}'), ('\u{2c00}', '\u{2c30}'), ('\u{2c01}', '\u{2c31}'), - ('\u{2c02}', '\u{2c32}'), ('\u{2c03}', '\u{2c33}'), ('\u{2c04}', - '\u{2c34}'), ('\u{2c05}', '\u{2c35}'), ('\u{2c06}', '\u{2c36}'), - ('\u{2c07}', '\u{2c37}'), ('\u{2c08}', '\u{2c38}'), ('\u{2c09}', - '\u{2c39}'), ('\u{2c0a}', '\u{2c3a}'), ('\u{2c0b}', '\u{2c3b}'), - ('\u{2c0c}', '\u{2c3c}'), ('\u{2c0d}', '\u{2c3d}'), ('\u{2c0e}', - '\u{2c3e}'), ('\u{2c0f}', '\u{2c3f}'), ('\u{2c10}', '\u{2c40}'), - ('\u{2c11}', '\u{2c41}'), ('\u{2c12}', '\u{2c42}'), ('\u{2c13}', - '\u{2c43}'), ('\u{2c14}', '\u{2c44}'), ('\u{2c15}', '\u{2c45}'), - ('\u{2c16}', '\u{2c46}'), ('\u{2c17}', '\u{2c47}'), ('\u{2c18}', - '\u{2c48}'), ('\u{2c19}', '\u{2c49}'), ('\u{2c1a}', '\u{2c4a}'), - ('\u{2c1b}', '\u{2c4b}'), ('\u{2c1c}', '\u{2c4c}'), ('\u{2c1d}', - '\u{2c4d}'), ('\u{2c1e}', '\u{2c4e}'), ('\u{2c1f}', '\u{2c4f}'), - ('\u{2c20}', '\u{2c50}'), ('\u{2c21}', '\u{2c51}'), ('\u{2c22}', - '\u{2c52}'), ('\u{2c23}', '\u{2c53}'), ('\u{2c24}', '\u{2c54}'), - ('\u{2c25}', '\u{2c55}'), ('\u{2c26}', '\u{2c56}'), ('\u{2c27}', - '\u{2c57}'), ('\u{2c28}', '\u{2c58}'), ('\u{2c29}', '\u{2c59}'), - ('\u{2c2a}', '\u{2c5a}'), ('\u{2c2b}', '\u{2c5b}'), ('\u{2c2c}', - '\u{2c5c}'), ('\u{2c2d}', '\u{2c5d}'), ('\u{2c2e}', '\u{2c5e}'), - ('\u{2c30}', '\u{2c00}'), ('\u{2c31}', '\u{2c01}'), ('\u{2c32}', - '\u{2c02}'), ('\u{2c33}', '\u{2c03}'), ('\u{2c34}', '\u{2c04}'), - ('\u{2c35}', '\u{2c05}'), ('\u{2c36}', '\u{2c06}'), ('\u{2c37}', - '\u{2c07}'), ('\u{2c38}', '\u{2c08}'), ('\u{2c39}', '\u{2c09}'), - ('\u{2c3a}', '\u{2c0a}'), ('\u{2c3b}', '\u{2c0b}'), ('\u{2c3c}', - '\u{2c0c}'), ('\u{2c3d}', '\u{2c0d}'), ('\u{2c3e}', '\u{2c0e}'), - ('\u{2c3f}', '\u{2c0f}'), ('\u{2c40}', '\u{2c10}'), ('\u{2c41}', - '\u{2c11}'), ('\u{2c42}', '\u{2c12}'), ('\u{2c43}', '\u{2c13}'), - ('\u{2c44}', '\u{2c14}'), ('\u{2c45}', '\u{2c15}'), ('\u{2c46}', - '\u{2c16}'), ('\u{2c47}', '\u{2c17}'), ('\u{2c48}', '\u{2c18}'), - ('\u{2c49}', '\u{2c19}'), ('\u{2c4a}', '\u{2c1a}'), ('\u{2c4b}', - '\u{2c1b}'), ('\u{2c4c}', '\u{2c1c}'), ('\u{2c4d}', '\u{2c1d}'), - ('\u{2c4e}', '\u{2c1e}'), ('\u{2c4f}', '\u{2c1f}'), ('\u{2c50}', - '\u{2c20}'), ('\u{2c51}', '\u{2c21}'), ('\u{2c52}', '\u{2c22}'), - ('\u{2c53}', '\u{2c23}'), ('\u{2c54}', '\u{2c24}'), ('\u{2c55}', - '\u{2c25}'), ('\u{2c56}', '\u{2c26}'), ('\u{2c57}', '\u{2c27}'), - ('\u{2c58}', '\u{2c28}'), ('\u{2c59}', '\u{2c29}'), ('\u{2c5a}', - '\u{2c2a}'), ('\u{2c5b}', '\u{2c2b}'), ('\u{2c5c}', '\u{2c2c}'), - ('\u{2c5d}', '\u{2c2d}'), ('\u{2c5e}', '\u{2c2e}'), ('\u{2c60}', - '\u{2c61}'), ('\u{2c61}', '\u{2c60}'), ('\u{2c62}', '\u{26b}'), - ('\u{2c63}', '\u{1d7d}'), ('\u{2c64}', '\u{27d}'), ('\u{2c65}', - '\u{23a}'), ('\u{2c66}', '\u{23e}'), ('\u{2c67}', '\u{2c68}'), - ('\u{2c68}', '\u{2c67}'), ('\u{2c69}', '\u{2c6a}'), ('\u{2c6a}', - '\u{2c69}'), ('\u{2c6b}', '\u{2c6c}'), ('\u{2c6c}', '\u{2c6b}'), - ('\u{2c6d}', '\u{251}'), ('\u{2c6e}', '\u{271}'), ('\u{2c6f}', - '\u{250}'), ('\u{2c70}', '\u{252}'), ('\u{2c72}', '\u{2c73}'), - ('\u{2c73}', '\u{2c72}'), ('\u{2c75}', '\u{2c76}'), ('\u{2c76}', - '\u{2c75}'), ('\u{2c7e}', '\u{23f}'), ('\u{2c7f}', '\u{240}'), - ('\u{2c80}', '\u{2c81}'), ('\u{2c81}', '\u{2c80}'), ('\u{2c82}', - '\u{2c83}'), ('\u{2c83}', '\u{2c82}'), ('\u{2c84}', '\u{2c85}'), - ('\u{2c85}', '\u{2c84}'), ('\u{2c86}', '\u{2c87}'), ('\u{2c87}', - '\u{2c86}'), ('\u{2c88}', '\u{2c89}'), ('\u{2c89}', '\u{2c88}'), - ('\u{2c8a}', '\u{2c8b}'), ('\u{2c8b}', '\u{2c8a}'), ('\u{2c8c}', - '\u{2c8d}'), ('\u{2c8d}', '\u{2c8c}'), ('\u{2c8e}', '\u{2c8f}'), - ('\u{2c8f}', '\u{2c8e}'), ('\u{2c90}', '\u{2c91}'), ('\u{2c91}', - '\u{2c90}'), ('\u{2c92}', '\u{2c93}'), ('\u{2c93}', '\u{2c92}'), - ('\u{2c94}', '\u{2c95}'), ('\u{2c95}', '\u{2c94}'), ('\u{2c96}', - '\u{2c97}'), ('\u{2c97}', '\u{2c96}'), ('\u{2c98}', '\u{2c99}'), - ('\u{2c99}', '\u{2c98}'), ('\u{2c9a}', '\u{2c9b}'), ('\u{2c9b}', - '\u{2c9a}'), ('\u{2c9c}', '\u{2c9d}'), ('\u{2c9d}', '\u{2c9c}'), - ('\u{2c9e}', '\u{2c9f}'), ('\u{2c9f}', '\u{2c9e}'), ('\u{2ca0}', - '\u{2ca1}'), ('\u{2ca1}', '\u{2ca0}'), ('\u{2ca2}', '\u{2ca3}'), - ('\u{2ca3}', '\u{2ca2}'), ('\u{2ca4}', '\u{2ca5}'), ('\u{2ca5}', - '\u{2ca4}'), ('\u{2ca6}', '\u{2ca7}'), ('\u{2ca7}', '\u{2ca6}'), - ('\u{2ca8}', '\u{2ca9}'), ('\u{2ca9}', '\u{2ca8}'), ('\u{2caa}', - '\u{2cab}'), ('\u{2cab}', '\u{2caa}'), ('\u{2cac}', '\u{2cad}'), - ('\u{2cad}', '\u{2cac}'), ('\u{2cae}', '\u{2caf}'), ('\u{2caf}', - '\u{2cae}'), ('\u{2cb0}', '\u{2cb1}'), ('\u{2cb1}', '\u{2cb0}'), - ('\u{2cb2}', '\u{2cb3}'), ('\u{2cb3}', '\u{2cb2}'), ('\u{2cb4}', - '\u{2cb5}'), ('\u{2cb5}', '\u{2cb4}'), ('\u{2cb6}', '\u{2cb7}'), - ('\u{2cb7}', '\u{2cb6}'), ('\u{2cb8}', '\u{2cb9}'), ('\u{2cb9}', - '\u{2cb8}'), ('\u{2cba}', '\u{2cbb}'), ('\u{2cbb}', '\u{2cba}'), - ('\u{2cbc}', '\u{2cbd}'), ('\u{2cbd}', '\u{2cbc}'), ('\u{2cbe}', - '\u{2cbf}'), ('\u{2cbf}', '\u{2cbe}'), ('\u{2cc0}', '\u{2cc1}'), - ('\u{2cc1}', '\u{2cc0}'), ('\u{2cc2}', '\u{2cc3}'), ('\u{2cc3}', - '\u{2cc2}'), ('\u{2cc4}', '\u{2cc5}'), ('\u{2cc5}', '\u{2cc4}'), - ('\u{2cc6}', '\u{2cc7}'), ('\u{2cc7}', '\u{2cc6}'), ('\u{2cc8}', - '\u{2cc9}'), ('\u{2cc9}', '\u{2cc8}'), ('\u{2cca}', '\u{2ccb}'), - ('\u{2ccb}', '\u{2cca}'), ('\u{2ccc}', '\u{2ccd}'), ('\u{2ccd}', - '\u{2ccc}'), ('\u{2cce}', '\u{2ccf}'), ('\u{2ccf}', '\u{2cce}'), - ('\u{2cd0}', '\u{2cd1}'), ('\u{2cd1}', '\u{2cd0}'), ('\u{2cd2}', - '\u{2cd3}'), ('\u{2cd3}', '\u{2cd2}'), ('\u{2cd4}', '\u{2cd5}'), - ('\u{2cd5}', '\u{2cd4}'), ('\u{2cd6}', '\u{2cd7}'), ('\u{2cd7}', - '\u{2cd6}'), ('\u{2cd8}', '\u{2cd9}'), ('\u{2cd9}', '\u{2cd8}'), - ('\u{2cda}', '\u{2cdb}'), ('\u{2cdb}', '\u{2cda}'), ('\u{2cdc}', - '\u{2cdd}'), ('\u{2cdd}', '\u{2cdc}'), ('\u{2cde}', '\u{2cdf}'), - ('\u{2cdf}', '\u{2cde}'), ('\u{2ce0}', '\u{2ce1}'), ('\u{2ce1}', - '\u{2ce0}'), ('\u{2ce2}', '\u{2ce3}'), ('\u{2ce3}', '\u{2ce2}'), - ('\u{2ceb}', '\u{2cec}'), ('\u{2cec}', '\u{2ceb}'), ('\u{2ced}', - '\u{2cee}'), ('\u{2cee}', '\u{2ced}'), ('\u{2cf2}', '\u{2cf3}'), - ('\u{2cf3}', '\u{2cf2}'), ('\u{2d00}', '\u{10a0}'), ('\u{2d01}', - '\u{10a1}'), ('\u{2d02}', '\u{10a2}'), ('\u{2d03}', '\u{10a3}'), - ('\u{2d04}', '\u{10a4}'), ('\u{2d05}', '\u{10a5}'), ('\u{2d06}', - '\u{10a6}'), ('\u{2d07}', '\u{10a7}'), ('\u{2d08}', '\u{10a8}'), - ('\u{2d09}', '\u{10a9}'), ('\u{2d0a}', '\u{10aa}'), ('\u{2d0b}', - '\u{10ab}'), ('\u{2d0c}', '\u{10ac}'), ('\u{2d0d}', '\u{10ad}'), - ('\u{2d0e}', '\u{10ae}'), ('\u{2d0f}', '\u{10af}'), ('\u{2d10}', - '\u{10b0}'), ('\u{2d11}', '\u{10b1}'), ('\u{2d12}', '\u{10b2}'), - ('\u{2d13}', '\u{10b3}'), ('\u{2d14}', '\u{10b4}'), ('\u{2d15}', - '\u{10b5}'), ('\u{2d16}', '\u{10b6}'), ('\u{2d17}', '\u{10b7}'), - ('\u{2d18}', '\u{10b8}'), ('\u{2d19}', '\u{10b9}'), ('\u{2d1a}', - '\u{10ba}'), ('\u{2d1b}', '\u{10bb}'), ('\u{2d1c}', '\u{10bc}'), - ('\u{2d1d}', '\u{10bd}'), ('\u{2d1e}', '\u{10be}'), ('\u{2d1f}', - '\u{10bf}'), ('\u{2d20}', '\u{10c0}'), ('\u{2d21}', '\u{10c1}'), - ('\u{2d22}', '\u{10c2}'), ('\u{2d23}', '\u{10c3}'), ('\u{2d24}', - '\u{10c4}'), ('\u{2d25}', '\u{10c5}'), ('\u{2d27}', '\u{10c7}'), - ('\u{2d2d}', '\u{10cd}'), ('\u{a640}', '\u{a641}'), ('\u{a641}', - '\u{a640}'), ('\u{a642}', '\u{a643}'), ('\u{a643}', '\u{a642}'), - ('\u{a644}', '\u{a645}'), ('\u{a645}', '\u{a644}'), ('\u{a646}', - '\u{a647}'), ('\u{a647}', '\u{a646}'), ('\u{a648}', '\u{a649}'), - ('\u{a649}', '\u{a648}'), ('\u{a64a}', '\u{1c88}'), ('\u{a64a}', - '\u{a64b}'), ('\u{a64b}', '\u{1c88}'), ('\u{a64b}', '\u{a64a}'), - ('\u{a64c}', '\u{a64d}'), ('\u{a64d}', '\u{a64c}'), ('\u{a64e}', - '\u{a64f}'), ('\u{a64f}', '\u{a64e}'), ('\u{a650}', '\u{a651}'), - ('\u{a651}', '\u{a650}'), ('\u{a652}', '\u{a653}'), ('\u{a653}', - '\u{a652}'), ('\u{a654}', '\u{a655}'), ('\u{a655}', '\u{a654}'), - ('\u{a656}', '\u{a657}'), ('\u{a657}', '\u{a656}'), ('\u{a658}', - '\u{a659}'), ('\u{a659}', '\u{a658}'), ('\u{a65a}', '\u{a65b}'), - ('\u{a65b}', '\u{a65a}'), ('\u{a65c}', '\u{a65d}'), ('\u{a65d}', - '\u{a65c}'), ('\u{a65e}', '\u{a65f}'), ('\u{a65f}', '\u{a65e}'), - ('\u{a660}', '\u{a661}'), ('\u{a661}', '\u{a660}'), ('\u{a662}', - '\u{a663}'), ('\u{a663}', '\u{a662}'), ('\u{a664}', '\u{a665}'), - ('\u{a665}', '\u{a664}'), ('\u{a666}', '\u{a667}'), ('\u{a667}', - '\u{a666}'), ('\u{a668}', '\u{a669}'), ('\u{a669}', '\u{a668}'), - ('\u{a66a}', '\u{a66b}'), ('\u{a66b}', '\u{a66a}'), ('\u{a66c}', - '\u{a66d}'), ('\u{a66d}', '\u{a66c}'), ('\u{a680}', '\u{a681}'), - ('\u{a681}', '\u{a680}'), ('\u{a682}', '\u{a683}'), ('\u{a683}', - '\u{a682}'), ('\u{a684}', '\u{a685}'), ('\u{a685}', '\u{a684}'), - ('\u{a686}', '\u{a687}'), ('\u{a687}', '\u{a686}'), ('\u{a688}', - '\u{a689}'), ('\u{a689}', '\u{a688}'), ('\u{a68a}', '\u{a68b}'), - ('\u{a68b}', '\u{a68a}'), ('\u{a68c}', '\u{a68d}'), ('\u{a68d}', - '\u{a68c}'), ('\u{a68e}', '\u{a68f}'), ('\u{a68f}', '\u{a68e}'), - ('\u{a690}', '\u{a691}'), ('\u{a691}', '\u{a690}'), ('\u{a692}', - '\u{a693}'), ('\u{a693}', '\u{a692}'), ('\u{a694}', '\u{a695}'), - ('\u{a695}', '\u{a694}'), ('\u{a696}', '\u{a697}'), ('\u{a697}', - '\u{a696}'), ('\u{a698}', '\u{a699}'), ('\u{a699}', '\u{a698}'), - ('\u{a69a}', '\u{a69b}'), ('\u{a69b}', '\u{a69a}'), ('\u{a722}', - '\u{a723}'), ('\u{a723}', '\u{a722}'), ('\u{a724}', '\u{a725}'), - ('\u{a725}', '\u{a724}'), ('\u{a726}', '\u{a727}'), ('\u{a727}', - '\u{a726}'), ('\u{a728}', '\u{a729}'), ('\u{a729}', '\u{a728}'), - ('\u{a72a}', '\u{a72b}'), ('\u{a72b}', '\u{a72a}'), ('\u{a72c}', - '\u{a72d}'), ('\u{a72d}', '\u{a72c}'), ('\u{a72e}', '\u{a72f}'), - ('\u{a72f}', '\u{a72e}'), ('\u{a732}', '\u{a733}'), ('\u{a733}', - '\u{a732}'), ('\u{a734}', '\u{a735}'), ('\u{a735}', '\u{a734}'), - ('\u{a736}', '\u{a737}'), ('\u{a737}', '\u{a736}'), ('\u{a738}', - '\u{a739}'), ('\u{a739}', '\u{a738}'), ('\u{a73a}', '\u{a73b}'), - ('\u{a73b}', '\u{a73a}'), ('\u{a73c}', '\u{a73d}'), ('\u{a73d}', - '\u{a73c}'), ('\u{a73e}', '\u{a73f}'), ('\u{a73f}', '\u{a73e}'), - ('\u{a740}', '\u{a741}'), ('\u{a741}', '\u{a740}'), ('\u{a742}', - '\u{a743}'), ('\u{a743}', '\u{a742}'), ('\u{a744}', '\u{a745}'), - ('\u{a745}', '\u{a744}'), ('\u{a746}', '\u{a747}'), ('\u{a747}', - '\u{a746}'), ('\u{a748}', '\u{a749}'), ('\u{a749}', '\u{a748}'), - ('\u{a74a}', '\u{a74b}'), ('\u{a74b}', '\u{a74a}'), ('\u{a74c}', - '\u{a74d}'), ('\u{a74d}', '\u{a74c}'), ('\u{a74e}', '\u{a74f}'), - ('\u{a74f}', '\u{a74e}'), ('\u{a750}', '\u{a751}'), ('\u{a751}', - '\u{a750}'), ('\u{a752}', '\u{a753}'), ('\u{a753}', '\u{a752}'), - ('\u{a754}', '\u{a755}'), ('\u{a755}', '\u{a754}'), ('\u{a756}', - '\u{a757}'), ('\u{a757}', '\u{a756}'), ('\u{a758}', '\u{a759}'), - ('\u{a759}', '\u{a758}'), ('\u{a75a}', '\u{a75b}'), ('\u{a75b}', - '\u{a75a}'), ('\u{a75c}', '\u{a75d}'), ('\u{a75d}', '\u{a75c}'), - ('\u{a75e}', '\u{a75f}'), ('\u{a75f}', '\u{a75e}'), ('\u{a760}', - '\u{a761}'), ('\u{a761}', '\u{a760}'), ('\u{a762}', '\u{a763}'), - ('\u{a763}', '\u{a762}'), ('\u{a764}', '\u{a765}'), ('\u{a765}', - '\u{a764}'), ('\u{a766}', '\u{a767}'), ('\u{a767}', '\u{a766}'), - ('\u{a768}', '\u{a769}'), ('\u{a769}', '\u{a768}'), ('\u{a76a}', - '\u{a76b}'), ('\u{a76b}', '\u{a76a}'), ('\u{a76c}', '\u{a76d}'), - ('\u{a76d}', '\u{a76c}'), ('\u{a76e}', '\u{a76f}'), ('\u{a76f}', - '\u{a76e}'), ('\u{a779}', '\u{a77a}'), ('\u{a77a}', '\u{a779}'), - ('\u{a77b}', '\u{a77c}'), ('\u{a77c}', '\u{a77b}'), ('\u{a77d}', - '\u{1d79}'), ('\u{a77e}', '\u{a77f}'), ('\u{a77f}', '\u{a77e}'), - ('\u{a780}', '\u{a781}'), ('\u{a781}', '\u{a780}'), ('\u{a782}', - '\u{a783}'), ('\u{a783}', '\u{a782}'), ('\u{a784}', '\u{a785}'), - ('\u{a785}', '\u{a784}'), ('\u{a786}', '\u{a787}'), ('\u{a787}', - '\u{a786}'), ('\u{a78b}', '\u{a78c}'), ('\u{a78c}', '\u{a78b}'), - ('\u{a78d}', '\u{265}'), ('\u{a790}', '\u{a791}'), ('\u{a791}', - '\u{a790}'), ('\u{a792}', '\u{a793}'), ('\u{a793}', '\u{a792}'), - ('\u{a796}', '\u{a797}'), ('\u{a797}', '\u{a796}'), ('\u{a798}', - '\u{a799}'), ('\u{a799}', '\u{a798}'), ('\u{a79a}', '\u{a79b}'), - ('\u{a79b}', '\u{a79a}'), ('\u{a79c}', '\u{a79d}'), ('\u{a79d}', - '\u{a79c}'), ('\u{a79e}', '\u{a79f}'), ('\u{a79f}', '\u{a79e}'), - ('\u{a7a0}', '\u{a7a1}'), ('\u{a7a1}', '\u{a7a0}'), ('\u{a7a2}', - '\u{a7a3}'), ('\u{a7a3}', '\u{a7a2}'), ('\u{a7a4}', '\u{a7a5}'), - ('\u{a7a5}', '\u{a7a4}'), ('\u{a7a6}', '\u{a7a7}'), ('\u{a7a7}', - '\u{a7a6}'), ('\u{a7a8}', '\u{a7a9}'), ('\u{a7a9}', '\u{a7a8}'), - ('\u{a7aa}', '\u{266}'), ('\u{a7ab}', '\u{25c}'), ('\u{a7ac}', - '\u{261}'), ('\u{a7ad}', '\u{26c}'), ('\u{a7ae}', '\u{26a}'), - ('\u{a7b0}', '\u{29e}'), ('\u{a7b1}', '\u{287}'), ('\u{a7b2}', - '\u{29d}'), ('\u{a7b3}', '\u{ab53}'), ('\u{a7b4}', '\u{a7b5}'), - ('\u{a7b5}', '\u{a7b4}'), ('\u{a7b6}', '\u{a7b7}'), ('\u{a7b7}', - '\u{a7b6}'), ('\u{ab53}', '\u{a7b3}'), ('\u{ab70}', '\u{13a0}'), - ('\u{ab71}', '\u{13a1}'), ('\u{ab72}', '\u{13a2}'), ('\u{ab73}', - '\u{13a3}'), ('\u{ab74}', '\u{13a4}'), ('\u{ab75}', '\u{13a5}'), - ('\u{ab76}', '\u{13a6}'), ('\u{ab77}', '\u{13a7}'), ('\u{ab78}', - '\u{13a8}'), ('\u{ab79}', '\u{13a9}'), ('\u{ab7a}', '\u{13aa}'), - ('\u{ab7b}', '\u{13ab}'), ('\u{ab7c}', '\u{13ac}'), ('\u{ab7d}', - '\u{13ad}'), ('\u{ab7e}', '\u{13ae}'), ('\u{ab7f}', '\u{13af}'), - ('\u{ab80}', '\u{13b0}'), ('\u{ab81}', '\u{13b1}'), ('\u{ab82}', - '\u{13b2}'), ('\u{ab83}', '\u{13b3}'), ('\u{ab84}', '\u{13b4}'), - ('\u{ab85}', '\u{13b5}'), ('\u{ab86}', '\u{13b6}'), ('\u{ab87}', - '\u{13b7}'), ('\u{ab88}', '\u{13b8}'), ('\u{ab89}', '\u{13b9}'), - ('\u{ab8a}', '\u{13ba}'), ('\u{ab8b}', '\u{13bb}'), ('\u{ab8c}', - '\u{13bc}'), ('\u{ab8d}', '\u{13bd}'), ('\u{ab8e}', '\u{13be}'), - ('\u{ab8f}', '\u{13bf}'), ('\u{ab90}', '\u{13c0}'), ('\u{ab91}', - '\u{13c1}'), ('\u{ab92}', '\u{13c2}'), ('\u{ab93}', '\u{13c3}'), - ('\u{ab94}', '\u{13c4}'), ('\u{ab95}', '\u{13c5}'), ('\u{ab96}', - '\u{13c6}'), ('\u{ab97}', '\u{13c7}'), ('\u{ab98}', '\u{13c8}'), - ('\u{ab99}', '\u{13c9}'), ('\u{ab9a}', '\u{13ca}'), ('\u{ab9b}', - '\u{13cb}'), ('\u{ab9c}', '\u{13cc}'), ('\u{ab9d}', '\u{13cd}'), - ('\u{ab9e}', '\u{13ce}'), ('\u{ab9f}', '\u{13cf}'), ('\u{aba0}', - '\u{13d0}'), ('\u{aba1}', '\u{13d1}'), ('\u{aba2}', '\u{13d2}'), - ('\u{aba3}', '\u{13d3}'), ('\u{aba4}', '\u{13d4}'), ('\u{aba5}', - '\u{13d5}'), ('\u{aba6}', '\u{13d6}'), ('\u{aba7}', '\u{13d7}'), - ('\u{aba8}', '\u{13d8}'), ('\u{aba9}', '\u{13d9}'), ('\u{abaa}', - '\u{13da}'), ('\u{abab}', '\u{13db}'), ('\u{abac}', '\u{13dc}'), - ('\u{abad}', '\u{13dd}'), ('\u{abae}', '\u{13de}'), ('\u{abaf}', - '\u{13df}'), ('\u{abb0}', '\u{13e0}'), ('\u{abb1}', '\u{13e1}'), - ('\u{abb2}', '\u{13e2}'), ('\u{abb3}', '\u{13e3}'), ('\u{abb4}', - '\u{13e4}'), ('\u{abb5}', '\u{13e5}'), ('\u{abb6}', '\u{13e6}'), - ('\u{abb7}', '\u{13e7}'), ('\u{abb8}', '\u{13e8}'), ('\u{abb9}', - '\u{13e9}'), ('\u{abba}', '\u{13ea}'), ('\u{abbb}', '\u{13eb}'), - ('\u{abbc}', '\u{13ec}'), ('\u{abbd}', '\u{13ed}'), ('\u{abbe}', - '\u{13ee}'), ('\u{abbf}', '\u{13ef}'), ('\u{ff21}', '\u{ff41}'), - ('\u{ff22}', '\u{ff42}'), ('\u{ff23}', '\u{ff43}'), ('\u{ff24}', - '\u{ff44}'), ('\u{ff25}', '\u{ff45}'), ('\u{ff26}', '\u{ff46}'), - ('\u{ff27}', '\u{ff47}'), ('\u{ff28}', '\u{ff48}'), ('\u{ff29}', - '\u{ff49}'), ('\u{ff2a}', '\u{ff4a}'), ('\u{ff2b}', '\u{ff4b}'), - ('\u{ff2c}', '\u{ff4c}'), ('\u{ff2d}', '\u{ff4d}'), ('\u{ff2e}', - '\u{ff4e}'), ('\u{ff2f}', '\u{ff4f}'), ('\u{ff30}', '\u{ff50}'), - ('\u{ff31}', '\u{ff51}'), ('\u{ff32}', '\u{ff52}'), ('\u{ff33}', - '\u{ff53}'), ('\u{ff34}', '\u{ff54}'), ('\u{ff35}', '\u{ff55}'), - ('\u{ff36}', '\u{ff56}'), ('\u{ff37}', '\u{ff57}'), ('\u{ff38}', - '\u{ff58}'), ('\u{ff39}', '\u{ff59}'), ('\u{ff3a}', '\u{ff5a}'), - ('\u{ff41}', '\u{ff21}'), ('\u{ff42}', '\u{ff22}'), ('\u{ff43}', - '\u{ff23}'), ('\u{ff44}', '\u{ff24}'), ('\u{ff45}', '\u{ff25}'), - ('\u{ff46}', '\u{ff26}'), ('\u{ff47}', '\u{ff27}'), ('\u{ff48}', - '\u{ff28}'), ('\u{ff49}', '\u{ff29}'), ('\u{ff4a}', '\u{ff2a}'), - ('\u{ff4b}', '\u{ff2b}'), ('\u{ff4c}', '\u{ff2c}'), ('\u{ff4d}', - '\u{ff2d}'), ('\u{ff4e}', '\u{ff2e}'), ('\u{ff4f}', '\u{ff2f}'), - ('\u{ff50}', '\u{ff30}'), ('\u{ff51}', '\u{ff31}'), ('\u{ff52}', - '\u{ff32}'), ('\u{ff53}', '\u{ff33}'), ('\u{ff54}', '\u{ff34}'), - ('\u{ff55}', '\u{ff35}'), ('\u{ff56}', '\u{ff36}'), ('\u{ff57}', - '\u{ff37}'), ('\u{ff58}', '\u{ff38}'), ('\u{ff59}', '\u{ff39}'), - ('\u{ff5a}', '\u{ff3a}'), ('\u{10400}', '\u{10428}'), ('\u{10401}', - '\u{10429}'), ('\u{10402}', '\u{1042a}'), ('\u{10403}', '\u{1042b}'), - ('\u{10404}', '\u{1042c}'), ('\u{10405}', '\u{1042d}'), ('\u{10406}', - '\u{1042e}'), ('\u{10407}', '\u{1042f}'), ('\u{10408}', '\u{10430}'), - ('\u{10409}', '\u{10431}'), ('\u{1040a}', '\u{10432}'), ('\u{1040b}', - '\u{10433}'), ('\u{1040c}', '\u{10434}'), ('\u{1040d}', '\u{10435}'), - ('\u{1040e}', '\u{10436}'), ('\u{1040f}', '\u{10437}'), ('\u{10410}', - '\u{10438}'), ('\u{10411}', '\u{10439}'), ('\u{10412}', '\u{1043a}'), - ('\u{10413}', '\u{1043b}'), ('\u{10414}', '\u{1043c}'), ('\u{10415}', - '\u{1043d}'), ('\u{10416}', '\u{1043e}'), ('\u{10417}', '\u{1043f}'), - ('\u{10418}', '\u{10440}'), ('\u{10419}', '\u{10441}'), ('\u{1041a}', - '\u{10442}'), ('\u{1041b}', '\u{10443}'), ('\u{1041c}', '\u{10444}'), - ('\u{1041d}', '\u{10445}'), ('\u{1041e}', '\u{10446}'), ('\u{1041f}', - '\u{10447}'), ('\u{10420}', '\u{10448}'), ('\u{10421}', '\u{10449}'), - ('\u{10422}', '\u{1044a}'), ('\u{10423}', '\u{1044b}'), ('\u{10424}', - '\u{1044c}'), ('\u{10425}', '\u{1044d}'), ('\u{10426}', '\u{1044e}'), - ('\u{10427}', '\u{1044f}'), ('\u{10428}', '\u{10400}'), ('\u{10429}', - '\u{10401}'), ('\u{1042a}', '\u{10402}'), ('\u{1042b}', '\u{10403}'), - ('\u{1042c}', '\u{10404}'), ('\u{1042d}', '\u{10405}'), ('\u{1042e}', - '\u{10406}'), ('\u{1042f}', '\u{10407}'), ('\u{10430}', '\u{10408}'), - ('\u{10431}', '\u{10409}'), ('\u{10432}', '\u{1040a}'), ('\u{10433}', - '\u{1040b}'), ('\u{10434}', '\u{1040c}'), ('\u{10435}', '\u{1040d}'), - ('\u{10436}', '\u{1040e}'), ('\u{10437}', '\u{1040f}'), ('\u{10438}', - '\u{10410}'), ('\u{10439}', '\u{10411}'), ('\u{1043a}', '\u{10412}'), - ('\u{1043b}', '\u{10413}'), ('\u{1043c}', '\u{10414}'), ('\u{1043d}', - '\u{10415}'), ('\u{1043e}', '\u{10416}'), ('\u{1043f}', '\u{10417}'), - ('\u{10440}', '\u{10418}'), ('\u{10441}', '\u{10419}'), ('\u{10442}', - '\u{1041a}'), ('\u{10443}', '\u{1041b}'), ('\u{10444}', '\u{1041c}'), - ('\u{10445}', '\u{1041d}'), ('\u{10446}', '\u{1041e}'), ('\u{10447}', - '\u{1041f}'), ('\u{10448}', '\u{10420}'), ('\u{10449}', '\u{10421}'), - ('\u{1044a}', '\u{10422}'), ('\u{1044b}', '\u{10423}'), ('\u{1044c}', - '\u{10424}'), ('\u{1044d}', '\u{10425}'), ('\u{1044e}', '\u{10426}'), - ('\u{1044f}', '\u{10427}'), ('\u{104b0}', '\u{104d8}'), ('\u{104b1}', - '\u{104d9}'), ('\u{104b2}', '\u{104da}'), ('\u{104b3}', '\u{104db}'), - ('\u{104b4}', '\u{104dc}'), ('\u{104b5}', '\u{104dd}'), ('\u{104b6}', - '\u{104de}'), ('\u{104b7}', '\u{104df}'), ('\u{104b8}', '\u{104e0}'), - ('\u{104b9}', '\u{104e1}'), ('\u{104ba}', '\u{104e2}'), ('\u{104bb}', - '\u{104e3}'), ('\u{104bc}', '\u{104e4}'), ('\u{104bd}', '\u{104e5}'), - ('\u{104be}', '\u{104e6}'), ('\u{104bf}', '\u{104e7}'), ('\u{104c0}', - '\u{104e8}'), ('\u{104c1}', '\u{104e9}'), ('\u{104c2}', '\u{104ea}'), - ('\u{104c3}', '\u{104eb}'), ('\u{104c4}', '\u{104ec}'), ('\u{104c5}', - '\u{104ed}'), ('\u{104c6}', '\u{104ee}'), ('\u{104c7}', '\u{104ef}'), - ('\u{104c8}', '\u{104f0}'), ('\u{104c9}', '\u{104f1}'), ('\u{104ca}', - '\u{104f2}'), ('\u{104cb}', '\u{104f3}'), ('\u{104cc}', '\u{104f4}'), - ('\u{104cd}', '\u{104f5}'), ('\u{104ce}', '\u{104f6}'), ('\u{104cf}', - '\u{104f7}'), ('\u{104d0}', '\u{104f8}'), ('\u{104d1}', '\u{104f9}'), - ('\u{104d2}', '\u{104fa}'), ('\u{104d3}', '\u{104fb}'), ('\u{104d8}', - '\u{104b0}'), ('\u{104d9}', '\u{104b1}'), ('\u{104da}', '\u{104b2}'), - ('\u{104db}', '\u{104b3}'), ('\u{104dc}', '\u{104b4}'), ('\u{104dd}', - '\u{104b5}'), ('\u{104de}', '\u{104b6}'), ('\u{104df}', '\u{104b7}'), - ('\u{104e0}', '\u{104b8}'), ('\u{104e1}', '\u{104b9}'), ('\u{104e2}', - '\u{104ba}'), ('\u{104e3}', '\u{104bb}'), ('\u{104e4}', '\u{104bc}'), - ('\u{104e5}', '\u{104bd}'), ('\u{104e6}', '\u{104be}'), ('\u{104e7}', - '\u{104bf}'), ('\u{104e8}', '\u{104c0}'), ('\u{104e9}', '\u{104c1}'), - ('\u{104ea}', '\u{104c2}'), ('\u{104eb}', '\u{104c3}'), ('\u{104ec}', - '\u{104c4}'), ('\u{104ed}', '\u{104c5}'), ('\u{104ee}', '\u{104c6}'), - ('\u{104ef}', '\u{104c7}'), ('\u{104f0}', '\u{104c8}'), ('\u{104f1}', - '\u{104c9}'), ('\u{104f2}', '\u{104ca}'), ('\u{104f3}', '\u{104cb}'), - ('\u{104f4}', '\u{104cc}'), ('\u{104f5}', '\u{104cd}'), ('\u{104f6}', - '\u{104ce}'), ('\u{104f7}', '\u{104cf}'), ('\u{104f8}', '\u{104d0}'), - ('\u{104f9}', '\u{104d1}'), ('\u{104fa}', '\u{104d2}'), ('\u{104fb}', - '\u{104d3}'), ('\u{10c80}', '\u{10cc0}'), ('\u{10c81}', '\u{10cc1}'), - ('\u{10c82}', '\u{10cc2}'), ('\u{10c83}', '\u{10cc3}'), ('\u{10c84}', - '\u{10cc4}'), ('\u{10c85}', '\u{10cc5}'), ('\u{10c86}', '\u{10cc6}'), - ('\u{10c87}', '\u{10cc7}'), ('\u{10c88}', '\u{10cc8}'), ('\u{10c89}', - '\u{10cc9}'), ('\u{10c8a}', '\u{10cca}'), ('\u{10c8b}', '\u{10ccb}'), - ('\u{10c8c}', '\u{10ccc}'), ('\u{10c8d}', '\u{10ccd}'), ('\u{10c8e}', - '\u{10cce}'), ('\u{10c8f}', '\u{10ccf}'), ('\u{10c90}', '\u{10cd0}'), - ('\u{10c91}', '\u{10cd1}'), ('\u{10c92}', '\u{10cd2}'), ('\u{10c93}', - '\u{10cd3}'), ('\u{10c94}', '\u{10cd4}'), ('\u{10c95}', '\u{10cd5}'), - ('\u{10c96}', '\u{10cd6}'), ('\u{10c97}', '\u{10cd7}'), ('\u{10c98}', - '\u{10cd8}'), ('\u{10c99}', '\u{10cd9}'), ('\u{10c9a}', '\u{10cda}'), - ('\u{10c9b}', '\u{10cdb}'), ('\u{10c9c}', '\u{10cdc}'), ('\u{10c9d}', - '\u{10cdd}'), ('\u{10c9e}', '\u{10cde}'), ('\u{10c9f}', '\u{10cdf}'), - ('\u{10ca0}', '\u{10ce0}'), ('\u{10ca1}', '\u{10ce1}'), ('\u{10ca2}', - '\u{10ce2}'), ('\u{10ca3}', '\u{10ce3}'), ('\u{10ca4}', '\u{10ce4}'), - ('\u{10ca5}', '\u{10ce5}'), ('\u{10ca6}', '\u{10ce6}'), ('\u{10ca7}', - '\u{10ce7}'), ('\u{10ca8}', '\u{10ce8}'), ('\u{10ca9}', '\u{10ce9}'), - ('\u{10caa}', '\u{10cea}'), ('\u{10cab}', '\u{10ceb}'), ('\u{10cac}', - '\u{10cec}'), ('\u{10cad}', '\u{10ced}'), ('\u{10cae}', '\u{10cee}'), - ('\u{10caf}', '\u{10cef}'), ('\u{10cb0}', '\u{10cf0}'), ('\u{10cb1}', - '\u{10cf1}'), ('\u{10cb2}', '\u{10cf2}'), ('\u{10cc0}', '\u{10c80}'), - ('\u{10cc1}', '\u{10c81}'), ('\u{10cc2}', '\u{10c82}'), ('\u{10cc3}', - '\u{10c83}'), ('\u{10cc4}', '\u{10c84}'), ('\u{10cc5}', '\u{10c85}'), - ('\u{10cc6}', '\u{10c86}'), ('\u{10cc7}', '\u{10c87}'), ('\u{10cc8}', - '\u{10c88}'), ('\u{10cc9}', '\u{10c89}'), ('\u{10cca}', '\u{10c8a}'), - ('\u{10ccb}', '\u{10c8b}'), ('\u{10ccc}', '\u{10c8c}'), ('\u{10ccd}', - '\u{10c8d}'), ('\u{10cce}', '\u{10c8e}'), ('\u{10ccf}', '\u{10c8f}'), - ('\u{10cd0}', '\u{10c90}'), ('\u{10cd1}', '\u{10c91}'), ('\u{10cd2}', - '\u{10c92}'), ('\u{10cd3}', '\u{10c93}'), ('\u{10cd4}', '\u{10c94}'), - ('\u{10cd5}', '\u{10c95}'), ('\u{10cd6}', '\u{10c96}'), ('\u{10cd7}', - '\u{10c97}'), ('\u{10cd8}', '\u{10c98}'), ('\u{10cd9}', '\u{10c99}'), - ('\u{10cda}', '\u{10c9a}'), ('\u{10cdb}', '\u{10c9b}'), ('\u{10cdc}', - '\u{10c9c}'), ('\u{10cdd}', '\u{10c9d}'), ('\u{10cde}', '\u{10c9e}'), - ('\u{10cdf}', '\u{10c9f}'), ('\u{10ce0}', '\u{10ca0}'), ('\u{10ce1}', - '\u{10ca1}'), ('\u{10ce2}', '\u{10ca2}'), ('\u{10ce3}', '\u{10ca3}'), - ('\u{10ce4}', '\u{10ca4}'), ('\u{10ce5}', '\u{10ca5}'), ('\u{10ce6}', - '\u{10ca6}'), ('\u{10ce7}', '\u{10ca7}'), ('\u{10ce8}', '\u{10ca8}'), - ('\u{10ce9}', '\u{10ca9}'), ('\u{10cea}', '\u{10caa}'), ('\u{10ceb}', - '\u{10cab}'), ('\u{10cec}', '\u{10cac}'), ('\u{10ced}', '\u{10cad}'), - ('\u{10cee}', '\u{10cae}'), ('\u{10cef}', '\u{10caf}'), ('\u{10cf0}', - '\u{10cb0}'), ('\u{10cf1}', '\u{10cb1}'), ('\u{10cf2}', '\u{10cb2}'), - ('\u{118a0}', '\u{118c0}'), ('\u{118a1}', '\u{118c1}'), ('\u{118a2}', - '\u{118c2}'), ('\u{118a3}', '\u{118c3}'), ('\u{118a4}', '\u{118c4}'), - ('\u{118a5}', '\u{118c5}'), ('\u{118a6}', '\u{118c6}'), ('\u{118a7}', - '\u{118c7}'), ('\u{118a8}', '\u{118c8}'), ('\u{118a9}', '\u{118c9}'), - ('\u{118aa}', '\u{118ca}'), ('\u{118ab}', '\u{118cb}'), ('\u{118ac}', - '\u{118cc}'), ('\u{118ad}', '\u{118cd}'), ('\u{118ae}', '\u{118ce}'), - ('\u{118af}', '\u{118cf}'), ('\u{118b0}', '\u{118d0}'), ('\u{118b1}', - '\u{118d1}'), ('\u{118b2}', '\u{118d2}'), ('\u{118b3}', '\u{118d3}'), - ('\u{118b4}', '\u{118d4}'), ('\u{118b5}', '\u{118d5}'), ('\u{118b6}', - '\u{118d6}'), ('\u{118b7}', '\u{118d7}'), ('\u{118b8}', '\u{118d8}'), - ('\u{118b9}', '\u{118d9}'), ('\u{118ba}', '\u{118da}'), ('\u{118bb}', - '\u{118db}'), ('\u{118bc}', '\u{118dc}'), ('\u{118bd}', '\u{118dd}'), - ('\u{118be}', '\u{118de}'), ('\u{118bf}', '\u{118df}'), ('\u{118c0}', - '\u{118a0}'), ('\u{118c1}', '\u{118a1}'), ('\u{118c2}', '\u{118a2}'), - ('\u{118c3}', '\u{118a3}'), ('\u{118c4}', '\u{118a4}'), ('\u{118c5}', - '\u{118a5}'), ('\u{118c6}', '\u{118a6}'), ('\u{118c7}', '\u{118a7}'), - ('\u{118c8}', '\u{118a8}'), ('\u{118c9}', '\u{118a9}'), ('\u{118ca}', - '\u{118aa}'), ('\u{118cb}', '\u{118ab}'), ('\u{118cc}', '\u{118ac}'), - ('\u{118cd}', '\u{118ad}'), ('\u{118ce}', '\u{118ae}'), ('\u{118cf}', - '\u{118af}'), ('\u{118d0}', '\u{118b0}'), ('\u{118d1}', '\u{118b1}'), - ('\u{118d2}', '\u{118b2}'), ('\u{118d3}', '\u{118b3}'), ('\u{118d4}', - '\u{118b4}'), ('\u{118d5}', '\u{118b5}'), ('\u{118d6}', '\u{118b6}'), - ('\u{118d7}', '\u{118b7}'), ('\u{118d8}', '\u{118b8}'), ('\u{118d9}', - '\u{118b9}'), ('\u{118da}', '\u{118ba}'), ('\u{118db}', '\u{118bb}'), - ('\u{118dc}', '\u{118bc}'), ('\u{118dd}', '\u{118bd}'), ('\u{118de}', - '\u{118be}'), ('\u{118df}', '\u{118bf}'), ('\u{1e900}', '\u{1e922}'), - ('\u{1e901}', '\u{1e923}'), ('\u{1e902}', '\u{1e924}'), ('\u{1e903}', - '\u{1e925}'), ('\u{1e904}', '\u{1e926}'), ('\u{1e905}', '\u{1e927}'), - ('\u{1e906}', '\u{1e928}'), ('\u{1e907}', '\u{1e929}'), ('\u{1e908}', - '\u{1e92a}'), ('\u{1e909}', '\u{1e92b}'), ('\u{1e90a}', '\u{1e92c}'), - ('\u{1e90b}', '\u{1e92d}'), ('\u{1e90c}', '\u{1e92e}'), ('\u{1e90d}', - '\u{1e92f}'), ('\u{1e90e}', '\u{1e930}'), ('\u{1e90f}', '\u{1e931}'), - ('\u{1e910}', '\u{1e932}'), ('\u{1e911}', '\u{1e933}'), ('\u{1e912}', - '\u{1e934}'), ('\u{1e913}', '\u{1e935}'), ('\u{1e914}', '\u{1e936}'), - ('\u{1e915}', '\u{1e937}'), ('\u{1e916}', '\u{1e938}'), ('\u{1e917}', - '\u{1e939}'), ('\u{1e918}', '\u{1e93a}'), ('\u{1e919}', '\u{1e93b}'), - ('\u{1e91a}', '\u{1e93c}'), ('\u{1e91b}', '\u{1e93d}'), ('\u{1e91c}', - '\u{1e93e}'), ('\u{1e91d}', '\u{1e93f}'), ('\u{1e91e}', '\u{1e940}'), - ('\u{1e91f}', '\u{1e941}'), ('\u{1e920}', '\u{1e942}'), ('\u{1e921}', - '\u{1e943}'), ('\u{1e922}', '\u{1e900}'), ('\u{1e923}', '\u{1e901}'), - ('\u{1e924}', '\u{1e902}'), ('\u{1e925}', '\u{1e903}'), ('\u{1e926}', - '\u{1e904}'), ('\u{1e927}', '\u{1e905}'), ('\u{1e928}', '\u{1e906}'), - ('\u{1e929}', '\u{1e907}'), ('\u{1e92a}', '\u{1e908}'), ('\u{1e92b}', - '\u{1e909}'), ('\u{1e92c}', '\u{1e90a}'), ('\u{1e92d}', '\u{1e90b}'), - ('\u{1e92e}', '\u{1e90c}'), ('\u{1e92f}', '\u{1e90d}'), ('\u{1e930}', - '\u{1e90e}'), ('\u{1e931}', '\u{1e90f}'), ('\u{1e932}', '\u{1e910}'), - ('\u{1e933}', '\u{1e911}'), ('\u{1e934}', '\u{1e912}'), ('\u{1e935}', - '\u{1e913}'), ('\u{1e936}', '\u{1e914}'), ('\u{1e937}', '\u{1e915}'), - ('\u{1e938}', '\u{1e916}'), ('\u{1e939}', '\u{1e917}'), ('\u{1e93a}', - '\u{1e918}'), ('\u{1e93b}', '\u{1e919}'), ('\u{1e93c}', '\u{1e91a}'), - ('\u{1e93d}', '\u{1e91b}'), ('\u{1e93e}', '\u{1e91c}'), ('\u{1e93f}', - '\u{1e91d}'), ('\u{1e940}', '\u{1e91e}'), ('\u{1e941}', '\u{1e91f}'), - ('\u{1e942}', '\u{1e920}'), ('\u{1e943}', '\u{1e921}') - ]; - -} - diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/benches/bench.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/benches/bench.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/benches/bench.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/benches/bench.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,73 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(test)] + +extern crate regex_syntax; +extern crate test; + +use regex_syntax::Parser; +use test::Bencher; + +#[bench] +fn parse_simple1(b: &mut Bencher) { + b.iter(|| { + let re = r"^bc(d|e)*$"; + Parser::new().parse(re).unwrap() + }); +} + +#[bench] +fn parse_simple2(b: &mut Bencher) { + b.iter(|| { + let re = r"'[a-zA-Z_][a-zA-Z0-9_]*(')\b"; + Parser::new().parse(re).unwrap() + }); +} + +#[bench] +fn parse_small1(b: &mut Bencher) { + b.iter(|| { + let re = r"\p{L}|\p{N}|\s|.|\d"; + Parser::new().parse(re).unwrap() + }); +} + +#[bench] +fn parse_medium1(b: &mut Bencher) { + b.iter(|| { + let re = r"\pL\p{Greek}\p{Hiragana}\p{Alphabetic}\p{Hebrew}\p{Arabic}"; + Parser::new().parse(re).unwrap() + }); +} + +#[bench] +fn parse_medium2(b: &mut Bencher) { + b.iter(|| { + let re = r"\s\S\w\W\d\D"; + Parser::new().parse(re).unwrap() + }); +} + +#[bench] +fn parse_medium3(b: &mut Bencher) { + b.iter(|| { + let re = r"\p{age:3.2}\p{hira}\p{scx:hira}\p{alphabetic}\p{sc:Greek}\pL"; + Parser::new().parse(re).unwrap() + }); +} + +#[bench] +fn parse_huge(b: &mut Bencher) { + b.iter(|| { + let re = r"\p{L}{100}"; + Parser::new().parse(re).unwrap() + }); +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/.cargo-checksum.json cargo-0.26.0/vendor/regex-syntax-0.5.3/.cargo-checksum.json --- cargo-0.25.0/vendor/regex-syntax-0.5.3/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"b2550876c31dc914696a6c2e01cbce8afba79a93c8ae979d2fe051c0230b3756"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/Cargo.toml cargo-0.26.0/vendor/regex-syntax-0.5.3/Cargo.toml --- cargo-0.25.0/vendor/regex-syntax-0.5.3/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,23 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "regex-syntax" +version = "0.5.3" +authors = ["The Rust Project Developers"] +description = "A regular expression parser." +homepage = "https://github.com/rust-lang/regex" +documentation = "https://docs.rs/regex-syntax" +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-lang/regex" +[dependencies.ucd-util] +version = "0.1.0" diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/LICENSE-APACHE cargo-0.26.0/vendor/regex-syntax-0.5.3/LICENSE-APACHE --- cargo-0.25.0/vendor/regex-syntax-0.5.3/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/LICENSE-MIT cargo-0.26.0/vendor/regex-syntax-0.5.3/LICENSE-MIT --- cargo-0.25.0/vendor/regex-syntax-0.5.3/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/ast/mod.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/ast/mod.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/ast/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/ast/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1507 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +Defines an abstract syntax for regular expressions. +*/ + +use std::cmp::Ordering; +use std::error; +use std::fmt; + +pub use ast::visitor::{Visitor, visit}; + +pub mod parse; +pub mod print; +mod visitor; + +/// An error that occurred while parsing a regular expression into an abstract +/// syntax tree. +/// +/// Note that note all ASTs represents a valid regular expression. For example, +/// an AST is constructed without error for `\p{Quux}`, but `Quux` is not a +/// valid Unicode property name. That particular error is reported when +/// translating an AST to the high-level intermediate representation (`HIR`). +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Error { + /// The kind of error. + kind: ErrorKind, + /// The original pattern that the parser generated the error from. Every + /// span in an error is a valid range into this string. + pattern: String, + /// The span of this error. + span: Span, +} + +impl Error { + /// Return the type of this error. + pub fn kind(&self) -> &ErrorKind { + &self.kind + } + + /// The original pattern string in which this error occurred. + /// + /// Every span reported by this error is reported in terms of this string. + pub fn pattern(&self) -> &str { + &self.pattern + } + + /// Return the span at which this error occurred. + pub fn span(&self) -> &Span { + &self.span + } + + /// Return an auxiliary span. This span exists only for some errors that + /// benefit from being able to point to two locations in the original + /// regular expression. For example, "duplicate" errors will have the + /// main error position set to the duplicate occurrence while its + /// auxiliary span will be set to the initial occurrence. + pub fn auxiliary_span(&self) -> Option<&Span> { + use self::ErrorKind::*; + match self.kind { + FlagDuplicate { ref original } => Some(original), + FlagRepeatedNegation { ref original, .. } => Some(original), + GroupNameDuplicate { ref original, .. } => Some(original), + _ => None, + } + } +} + +/// The type of an error that occurred while building an AST. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ErrorKind { + /// The capturing group limit was exceeded. + /// + /// Note that this represents a limit on the total number of capturing + /// groups in a regex and not necessarily the number of nested capturing + /// groups. That is, the nest limit can be low and it is still possible for + /// this error to occur. + CaptureLimitExceeded, + /// An invalid escape sequence was found in a character class set. + ClassEscapeInvalid, + /// An invalid character class range was found. An invalid range is any + /// range where the start is greater than the end. + ClassRangeInvalid, + /// An opening `[` was found with no corresponding closing `]`. + ClassUnclosed, + /// An empty decimal number was given where one was expected. + DecimalEmpty, + /// An invalid decimal number was given where one was expected. + DecimalInvalid, + /// A bracketed hex literal was empty. + EscapeHexEmpty, + /// A bracketed hex literal did not correspond to a Unicode scalar value. + EscapeHexInvalid, + /// An invalid hexadecimal digit was found. + EscapeHexInvalidDigit, + /// EOF was found before an escape sequence was completed. + EscapeUnexpectedEof, + /// An unrecognized escape sequence. + EscapeUnrecognized, + /// A dangling negation was used when setting flags, e.g., `i-`. + FlagDanglingNegation, + /// A flag was used twice, e.g., `i-i`. + FlagDuplicate { + /// The position of the original flag. The error position + /// points to the duplicate flag. + original: Span, + }, + /// The negation operator was used twice, e.g., `-i-s`. + FlagRepeatedNegation { + /// The position of the original negation operator. The error position + /// points to the duplicate negation operator. + original: Span, + }, + /// Expected a flag but got EOF, e.g., `(?`. + FlagUnexpectedEof, + /// Unrecognized flag, e.g., `a`. + FlagUnrecognized, + /// A duplicate capture name was found. + GroupNameDuplicate { + /// The position of the initial occurrence of the capture name. The + /// error position itself points to the duplicate occurrence. + original: Span, + }, + /// A capture group name is empty, e.g., `(?P<>abc)`. + GroupNameEmpty, + /// An invalid character was seen for a capture group name. This includes + /// errors where the first character is a digit (even though subsequent + /// characters are allowed to be digits). + GroupNameInvalid, + /// A closing `>` could not be found for a capture group name. + GroupNameUnexpectedEof, + /// An unclosed group, e.g., `(ab`. + /// + /// The span of this error corresponds to the unclosed parenthesis. + GroupUnclosed, + /// An unopened group, e.g., `ab)`. + GroupUnopened, + /// The nest limit was exceeded. The limit stored here is the limit + /// configured in the parser. + NestLimitExceeded(u32), + /// The range provided in a counted repetition operator is invalid. The + /// range is invalid if the start is greater than the end. + RepetitionCountInvalid, + /// An opening `{` was found with no corresponding closing `}`. + RepetitionCountUnclosed, + /// A repetition operator was applied to a missing sub-expression. This + /// occurs, for example, in the regex consisting of just a `*`. It is, + /// however, possible to create a repetition operating on an empty + /// sub-expression. For example, `()*` is still considered valid. + RepetitionMissing, + /// When octal support is disabled, this error is produced when an octal + /// escape is used. The octal escape is assumed to be an invocation of + /// a backreference, which is the common case. + UnsupportedBackreference, + /// When syntax similar to PCRE's look-around is used, this error is + /// returned. Some example syntaxes that are rejected include, but are + /// not necessarily limited to, `(?=re)`, `(?!re)`, `(?<=re)` and + /// `(?<!re)`. Note that all of these syntaxes are otherwise invalid; this + /// error is used to improve the user experience. + UnsupportedLookAround, + /// Hints that destructuring should not be exhaustive. + /// + /// This enum may grow additional variants, so this makes sure clients + /// don't count on exhaustive matching. (Otherwise, adding a new variant + /// could break existing code.) + #[doc(hidden)] + __Nonexhaustive, +} + +impl error::Error for Error { + fn description(&self) -> &str { + use self::ErrorKind::*; + match self.kind { + CaptureLimitExceeded => "capture group limit exceeded", + ClassEscapeInvalid => "invalid escape sequence in character class", + ClassRangeInvalid => "invalid character class range", + ClassUnclosed => "unclosed character class", + DecimalEmpty => "empty decimal literal", + DecimalInvalid => "invalid decimal literal", + EscapeHexEmpty => "empty hexadecimal literal", + EscapeHexInvalid => "invalid hexadecimal literal", + EscapeHexInvalidDigit => "invalid hexadecimal digit", + EscapeUnexpectedEof => "unexpected eof (escape sequence)", + EscapeUnrecognized => "unrecognized escape sequence", + FlagDanglingNegation => "dangling flag negation operator", + FlagDuplicate{..} => "duplicate flag", + FlagRepeatedNegation{..} => "repeated negation", + FlagUnexpectedEof => "unexpected eof (flag)", + FlagUnrecognized => "unrecognized flag", + GroupNameDuplicate{..} => "duplicate capture group name", + GroupNameEmpty => "empty capture group name", + GroupNameInvalid => "invalid capture group name", + GroupNameUnexpectedEof => "unclosed capture group name", + GroupUnclosed => "unclosed group", + GroupUnopened => "unopened group", + NestLimitExceeded(_) => "nest limit exceeded", + RepetitionCountInvalid => "invalid repetition count range", + RepetitionCountUnclosed => "unclosed counted repetition", + RepetitionMissing => "repetition operator missing expression", + UnsupportedBackreference => "backreferences are not supported", + UnsupportedLookAround => "look-around is not supported", + _ => unreachable!(), + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ::error::Formatter::from(self).fmt(f) + } +} + +impl fmt::Display for ErrorKind { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::ErrorKind::*; + match *self { + CaptureLimitExceeded => { + write!(f, "exceeded the maximum number of \ + capturing groups ({})", ::std::u32::MAX) + } + ClassEscapeInvalid => { + write!(f, "invalid escape sequence found in character class") + } + ClassRangeInvalid => { + write!(f, "invalid character class range, \ + the start must be <= the end") + } + ClassUnclosed => { + write!(f, "unclosed character class") + } + DecimalEmpty => { + write!(f, "decimal literal empty") + } + DecimalInvalid => { + write!(f, "decimal literal invalid") + } + EscapeHexEmpty => { + write!(f, "hexadecimal literal empty") + } + EscapeHexInvalid => { + write!(f, "hexadecimal literal is not a Unicode scalar value") + } + EscapeHexInvalidDigit => { + write!(f, "invalid hexadecimal digit") + } + EscapeUnexpectedEof => { + write!(f, "incomplete escape sequence, \ + reached end of pattern prematurely") + } + EscapeUnrecognized => { + write!(f, "unrecognized escape sequence") + } + FlagDanglingNegation => { + write!(f, "dangling flag negation operator") + } + FlagDuplicate{..} => { + write!(f, "duplicate flag") + } + FlagRepeatedNegation{..} => { + write!(f, "flag negation operator repeated") + } + FlagUnexpectedEof => { + write!(f, "expected flag but got end of regex") + } + FlagUnrecognized => { + write!(f, "unrecognized flag") + } + GroupNameDuplicate{..} => { + write!(f, "duplicate capture group name") + } + GroupNameEmpty => { + write!(f, "empty capture group name") + } + GroupNameInvalid => { + write!(f, "invalid capture group character") + } + GroupNameUnexpectedEof => { + write!(f, "unclosed capture group name") + } + GroupUnclosed => { + write!(f, "unclosed group") + } + GroupUnopened => { + write!(f, "unopened group") + } + NestLimitExceeded(limit) => { + write!(f, "exceed the maximum number of \ + nested parentheses/brackets ({})", limit) + } + RepetitionCountInvalid => { + write!(f, "invalid repetition count range, \ + the start must be <= the end") + } + RepetitionCountUnclosed => { + write!(f, "unclosed counted repetition") + } + RepetitionMissing => { + write!(f, "repetition operator missing expression") + } + UnsupportedBackreference => { + write!(f, "backreferences are not supported") + } + UnsupportedLookAround => { + write!(f, "look-around, including look-ahead and look-behind, \ + is not supported") + } + _ => unreachable!(), + } + } +} + +/// Span represents the position information of a single AST item. +/// +/// All span positions are absolute byte offsets that can be used on the +/// original regular expression that was parsed. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct Span { + /// The start byte offset. + pub start: Position, + /// The end byte offset. + pub end: Position, +} + +impl fmt::Debug for Span { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Span({:?}, {:?})", self.start, self.end) + } +} + +impl Ord for Span { + fn cmp(&self, other: &Span) -> Ordering { + (&self.start, &self.end).cmp(&(&other.start, &other.end)) + } +} + +impl PartialOrd for Span { + fn partial_cmp(&self, other: &Span) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +/// A single position in a regular expression. +/// +/// A position encodes one half of a span, and include the byte offset, line +/// number and column number. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct Position { + /// The absolute offset of this position, starting at `0` from the + /// beginning of the regular expression pattern string. + pub offset: usize, + /// The line number, starting at `1`. + pub line: usize, + /// The approximate column number, starting at `1`. + pub column: usize, +} + +impl fmt::Debug for Position { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "Position(o: {:?}, l: {:?}, c: {:?})", + self.offset, self.line, self.column) + } +} + +impl Ord for Position { + fn cmp(&self, other: &Position) -> Ordering { + self.offset.cmp(&other.offset) + } +} + +impl PartialOrd for Position { + fn partial_cmp(&self, other: &Position) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl Span { + /// Create a new span with the given positions. + pub fn new(start: Position, end: Position) -> Span { + Span { start: start, end: end } + } + + /// Create a new span using the given position as the start and end. + pub fn splat(pos: Position) -> Span { + Span::new(pos, pos) + } + + /// Create a new span by replacing the starting the position with the one + /// given. + pub fn with_start(self, pos: Position) -> Span { + Span { start: pos, ..self } + } + + /// Create a new span by replacing the ending the position with the one + /// given. + pub fn with_end(self, pos: Position) -> Span { + Span { end: pos, ..self } + } + + /// Returns true if and only if this span occurs on a single line. + pub fn is_one_line(&self) -> bool { + self.start.line == self.end.line + } + + /// Returns true if and only if this span is empty. That is, it points to + /// a single position in the concrete syntax of a regular expression. + pub fn is_empty(&self) -> bool { + self.start.offset == self.end.offset + } +} + +impl Position { + /// Create a new position with the given information. + /// + /// `offset` is the absolute offset of the position, starting at `0` from + /// the beginning of the regular expression pattern string. + /// + /// `line` is the line number, starting at `1`. + /// + /// `column` is the approximate column number, starting at `1`. + pub fn new(offset: usize, line: usize, column: usize) -> Position { + Position { offset: offset, line: line, column: column } + } +} + +/// An abstract syntax tree for a singular expression along with comments +/// found. +/// +/// Comments are not stored in the tree itself to avoid complexity. Each +/// comment contains a span of precisely where it occurred in the original +/// regular expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct WithComments { + /// The actual ast. + pub ast: Ast, + /// All comments found in the original regular expression. + pub comments: Vec<Comment>, +} + +/// A comment from a regular expression with an associated span. +/// +/// A regular expression can only contain comments when the `x` flag is +/// enabled. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Comment { + /// The span of this comment, including the beginning `#` and ending `\n`. + pub span: Span, + /// The comment text, starting with the first character following the `#` + /// and ending with the last character preceding the `\n`. + pub comment: String, +} + +/// An abstract syntax tree for a single regular expression. +/// +/// An `Ast`'s `fmt::Display` implementation uses constant stack space and heap +/// space proportional to the size of the `Ast`. +/// +/// This type defines its own destructor that uses constant stack space and +/// heap space proportional to the size of the `Ast`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Ast { + /// An empty regex that matches everything. + Empty(Span), + /// A set of flags, e.g., `(?is)`. + Flags(SetFlags), + /// A single character literal, which includes escape sequences. + Literal(Literal), + /// The "any character" class. + Dot(Span), + /// A single zero-width assertion. + Assertion(Assertion), + /// A single character class. This includes all forms of character classes + /// except for `.`. e.g., `\d`, `\pN`, `[a-z]` and `[[:alpha:]]`. + Class(Class), + /// A repetition operator applied to an arbitrary regular expression. + Repetition(Repetition), + /// A grouped regular expression. + Group(Group), + /// An alternation of regular expressions. + Alternation(Alternation), + /// A concatenation of regular expressions. + Concat(Concat), +} + +impl Ast { + /// Return the span of this abstract syntax tree. + pub fn span(&self) -> &Span { + match *self { + Ast::Empty(ref span) => span, + Ast::Flags(ref x) => &x.span, + Ast::Literal(ref x) => &x.span, + Ast::Dot(ref span) => span, + Ast::Assertion(ref x) => &x.span, + Ast::Class(ref x) => x.span(), + Ast::Repetition(ref x) => &x.span, + Ast::Group(ref x) => &x.span, + Ast::Alternation(ref x) => &x.span, + Ast::Concat(ref x) => &x.span, + } + } + + /// Return true if and only if this Ast is empty. + pub fn is_empty(&self) -> bool { + match *self { + Ast::Empty(_) => true, + _ => false, + } + } + + /// Returns true if and only if this AST has any (including possibly empty) + /// subexpressions. + fn has_subexprs(&self) -> bool { + match *self { + Ast::Empty(_) + | Ast::Flags(_) + | Ast::Literal(_) + | Ast::Dot(_) + | Ast::Assertion(_) => false, + Ast::Class(_) + | Ast::Repetition(_) + | Ast::Group(_) + | Ast::Alternation(_) + | Ast::Concat(_) => true, + } + } +} + +/// Print a display representation of this Ast. +/// +/// This does not preserve any of the original whitespace formatting that may +/// have originally been present in the concrete syntax from which this Ast +/// was generated. +/// +/// This implementation uses constant stack space and heap space proportional +/// to the size of the `Ast`. +impl fmt::Display for Ast { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use ast::print::Printer; + Printer::new().print(self, f) + } +} + +/// An alternation of regular expressions. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Alternation { + /// The span of this alternation. + pub span: Span, + /// The alternate regular expressions. + pub asts: Vec<Ast>, +} + +impl Alternation { + /// Return this alternation as an AST. + /// + /// If this alternation contains zero ASTs, then Ast::Empty is + /// returned. If this alternation contains exactly 1 AST, then the + /// corresponding AST is returned. Otherwise, Ast::Alternation is returned. + pub fn into_ast(mut self) -> Ast { + match self.asts.len() { + 0 => Ast::Empty(self.span), + 1 => self.asts.pop().unwrap(), + _ => Ast::Alternation(self), + } + } +} + +/// A concatenation of regular expressions. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Concat { + /// The span of this concatenation. + pub span: Span, + /// The concatenation regular expressions. + pub asts: Vec<Ast>, +} + +impl Concat { + /// Return this concatenation as an AST. + /// + /// If this concatenation contains zero ASTs, then Ast::Empty is + /// returned. If this concatenation contains exactly 1 AST, then the + /// corresponding AST is returned. Otherwise, Ast::Concat is returned. + pub fn into_ast(mut self) -> Ast { + match self.asts.len() { + 0 => Ast::Empty(self.span), + 1 => self.asts.pop().unwrap(), + _ => Ast::Concat(self), + } + } +} + +/// A single literal expression. +/// +/// A literal corresponds to a single Unicode scalar value. Literals may be +/// represented in their literal form, e.g., `a` or in their escaped form, +/// e.g., `\x61`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Literal { + /// The span of this literal. + pub span: Span, + /// The kind of this literal. + pub kind: LiteralKind, + /// The Unicode scalar value corresponding to this literal. + pub c: char, +} + +impl Literal { + /// If this literal was written as a `\x` hex escape, then this returns + /// the corresponding byte value. Otherwise, this returns `None`. + pub fn byte(&self) -> Option<u8> { + let short_hex = LiteralKind::HexFixed(HexLiteralKind::X); + if self.c as u32 <= 255 && self.kind == short_hex { + Some(self.c as u8) + } else { + None + } + } +} + +/// The kind of a single literal expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum LiteralKind { + /// The literal is written verbatim, e.g., `a` or `☃`. + Verbatim, + /// The literal is written as an escape because it is punctuation, e.g., + /// `\*` or `\[`. + Punctuation, + /// The literal is written as an octal escape, e.g., `\141`. + Octal, + /// The literal is written as a hex code with a fixed number of digits + /// depending on the type of the escape, e.g., `\x61` or or `\u0061` or + /// `\U00000061`. + HexFixed(HexLiteralKind), + /// The literal is written as a hex code with a bracketed number of + /// digits. The only restriction is that the bracketed hex code must refer + /// to a valid Unicode scalar value. + HexBrace(HexLiteralKind), + /// The literal is written as a specially recognized escape, e.g., `\f` + /// or `\n`. + Special(SpecialLiteralKind), +} + +/// The type of a special literal. +/// +/// A special literal is a special escape sequence recognized by the regex +/// parser, e.g., `\f` or `\n`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum SpecialLiteralKind { + /// Bell, spelled `\a` (`\x07`). + Bell, + /// Form feed, spelled `\f` (`\x0C`). + FormFeed, + /// Tab, spelled `\t` (`\x09`). + Tab, + /// Line feed, spelled `\n` (`\x0A`). + LineFeed, + /// Carriage return, spelled `\r` (`\x0D`). + CarriageReturn, + /// Vertical tab, spelled `\v` (`\x0B`). + VerticalTab, + /// Space, spelled `\ ` (`\x20`). Note that this can only appear when + /// parsing in verbose mode. + Space, +} + +/// The type of a Unicode hex literal. +/// +/// Note that all variants behave the same when used with brackets. They only +/// differ when used without brackets in the number of hex digits that must +/// follow. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum HexLiteralKind { + /// A `\x` prefix. When used without brackets, this form is limited to + /// two digits. + X, + /// A `\u` prefix. When used without brackets, this form is limited to + /// four digits. + UnicodeShort, + /// A `\U` prefix. When used without brackets, this form is limited to + /// eight digits. + UnicodeLong, +} + +impl HexLiteralKind { + /// The number of digits that must be used with this literal form when + /// used without brackets. When used with brackets, there is no + /// restriction on the number of digits. + pub fn digits(&self) -> u32 { + match *self { + HexLiteralKind::X => 2, + HexLiteralKind::UnicodeShort => 4, + HexLiteralKind::UnicodeLong => 8, + } + } +} + +/// A single character class expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Class { + /// A Unicode character class, e.g., `\pL` or `\p{Greek}`. + Unicode(ClassUnicode), + /// A perl character class, e.g., `\d` or `\W`. + Perl(ClassPerl), + /// A bracketed character class set, which may contain zero or more + /// character ranges and/or zero or more nested classes. e.g., + /// `[a-zA-Z\pL]`. + Bracketed(ClassBracketed), +} + +impl Class { + /// Return the span of this character class. + pub fn span(&self) -> &Span { + match *self { + Class::Perl(ref x) => &x.span, + Class::Unicode(ref x) => &x.span, + Class::Bracketed(ref x) => &x.span, + } + } +} + +/// A Perl character class. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassPerl { + /// The span of this class. + pub span: Span, + /// The kind of Perl class. + pub kind: ClassPerlKind, + /// Whether the class is negated or not. e.g., `\d` is not negated but + /// `\D` is. + pub negated: bool, +} + +/// The available Perl character classes. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ClassPerlKind { + /// Decimal numbers. + Digit, + /// Whitespace. + Space, + /// Word characters. + Word, +} + +/// An ASCII character class. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassAscii { + /// The span of this class. + pub span: Span, + /// The kind of ASCII class. + pub kind: ClassAsciiKind, + /// Whether the class is negated or not. e.g., `[[:alpha:]]` is not negated + /// but `[[:^alpha:]]` is. + pub negated: bool, +} + +/// The available ASCII character classes. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ClassAsciiKind { + /// `[0-9A-Za-z]` + Alnum, + /// `[A-Za-z]` + Alpha, + /// `[\x00-\x7F]` + Ascii, + /// `[ \t]` + Blank, + /// `[\x00-\x1F\x7F]` + Cntrl, + /// `[0-9]` + Digit, + /// `[!-~]` + Graph, + /// `[a-z]` + Lower, + /// `[ -~]` + Print, + /// `[!-/:-@\[-`{-~]` + Punct, + /// `[\t\n\v\f\r ]` + Space, + /// `[A-Z]` + Upper, + /// `[0-9A-Za-z_]` + Word, + /// `[0-9A-Fa-f]` + Xdigit, +} + +impl ClassAsciiKind { + /// Return the corresponding ClassAsciiKind variant for the given name. + /// + /// The name given should correspond to the lowercase version of the + /// variant name. e.g., `cntrl` is the name for `ClassAsciiKind::Cntrl`. + /// + /// If no variant with the corresponding name exists, then `None` is + /// returned. + pub fn from_name(name: &str) -> Option<ClassAsciiKind> { + use self::ClassAsciiKind::*; + match name { + "alnum" => Some(Alnum), + "alpha" => Some(Alpha), + "ascii" => Some(Ascii), + "blank" => Some(Blank), + "cntrl" => Some(Cntrl), + "digit" => Some(Digit), + "graph" => Some(Graph), + "lower" => Some(Lower), + "print" => Some(Print), + "punct" => Some(Punct), + "space" => Some(Space), + "upper" => Some(Upper), + "word" => Some(Word), + "xdigit" => Some(Xdigit), + _ => None, + } + } +} + +/// A Unicode character class. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassUnicode { + /// The span of this class. + pub span: Span, + /// Whether this class is negated or not. + /// + /// Note: be careful when using this attribute. This specifically refers + /// to whether the class is written as `\p` or `\P`, where the latter + /// is `negated = true`. However, it also possible to write something like + /// `\P{scx!=Katakana}` which is actually equivalent to + /// `\p{scx=Katakana}` and is therefore not actually negated even though + /// `negated = true` here. To test whether this class is truly negated + /// or not, use the `is_negated` method. + pub negated: bool, + /// The kind of Unicode class. + pub kind: ClassUnicodeKind, +} + +impl ClassUnicode { + /// Returns true if this class has been negated. + /// + /// Note that this takes the Unicode op into account, if it's present. + /// e.g., `is_negated` for `\P{scx!=Katakana}` will return `false`. + pub fn is_negated(&self) -> bool { + match self.kind { + ClassUnicodeKind::NamedValue { + op: ClassUnicodeOpKind::NotEqual, .. + } => !self.negated, + _ => self.negated, + } + } +} + +/// The available forms of Unicode character classes. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ClassUnicodeKind { + /// A one letter abbreviated class, e.g., `\pN`. + OneLetter(char), + /// A binary property, general category or script. The string may be + /// empty. + Named(String), + /// A property name and an associated value. + NamedValue { + /// The type of Unicode op used to associate `name` with `value`. + op: ClassUnicodeOpKind, + /// The property name (which may be empty). + name: String, + /// The property value (which may be empty). + value: String, + }, +} + +/// The type of op used in a Unicode character class. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ClassUnicodeOpKind { + /// A property set to a specific value, e.g., `\p{scx=Katakana}`. + Equal, + /// A property set to a specific value using a colon, e.g., + /// `\p{scx:Katakana}`. + Colon, + /// A property that isn't a particular value, e.g., `\p{scx!=Katakana}`. + NotEqual, +} + +impl ClassUnicodeOpKind { + /// Whether the op is an equality op or not. + pub fn is_equal(&self) -> bool { + match *self { + ClassUnicodeOpKind::Equal|ClassUnicodeOpKind::Colon => true, + _ => false, + } + } +} + +/// A bracketed character class, e.g., `[a-z0-9]`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassBracketed { + /// The span of this class. + pub span: Span, + /// Whether this class is negated or not. e.g., `[a]` is not negated but + /// `[^a]` is. + pub negated: bool, + /// The type of this set. A set is either a normal union of things, e.g., + /// `[abc]` or a result of applying set operations, e.g., `[\pL--c]`. + pub kind: ClassSet, +} + +/// A character class set. +/// +/// This type corresponds to the internal structure of a bracketed character +/// class. That is, every bracketed character is one of two types: a union of +/// items (literals, ranges, other bracketed classes) or a tree of binary set +/// operations. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ClassSet { + /// An item, which can be a single literal, range, nested character class + /// or a union of items. + Item(ClassSetItem), + /// A single binary operation (i.e., &&, -- or ~~). + BinaryOp(ClassSetBinaryOp), +} + +impl ClassSet { + /// Build a set from a union. + pub fn union(ast: ClassSetUnion) -> ClassSet { + ClassSet::Item(ClassSetItem::Union(ast)) + } + + /// Return the span of this character class set. + pub fn span(&self) -> &Span { + match *self { + ClassSet::Item(ref x) => x.span(), + ClassSet::BinaryOp(ref x) => &x.span, + } + } + + /// Return true if and only if this class set is empty. + fn is_empty(&self) -> bool { + match *self { + ClassSet::Item(ClassSetItem::Empty(_)) => true, + _ => false, + } + } +} + +/// A single component of a character class set. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ClassSetItem { + /// An empty item. + /// + /// Note that a bracketed character class cannot contain a single empty + /// item. Empty items can appear when using one of the binary operators. + /// For example, `[&&]` is the intersection of two empty classes. + Empty(Span), + /// A single literal. + Literal(Literal), + /// A range between two literals. + Range(ClassSetRange), + /// An ASCII character class, e.g., `[:alnum:]` or `[:punct:]`. + Ascii(ClassAscii), + /// A Unicode character class, e.g., `\pL` or `\p{Greek}`. + Unicode(ClassUnicode), + /// A perl character class, e.g., `\d` or `\W`. + Perl(ClassPerl), + /// A bracketed character class set, which may contain zero or more + /// character ranges and/or zero or more nested classes. e.g., + /// `[a-zA-Z\pL]`. + Bracketed(Box<ClassBracketed>), + /// A union of items. + Union(ClassSetUnion), +} + +impl ClassSetItem { + /// Return the span of this character class set item. + pub fn span(&self) -> &Span { + match *self { + ClassSetItem::Empty(ref span) => span, + ClassSetItem::Literal(ref x) => &x.span, + ClassSetItem::Range(ref x) => &x.span, + ClassSetItem::Ascii(ref x) => &x.span, + ClassSetItem::Perl(ref x) => &x.span, + ClassSetItem::Unicode(ref x) => &x.span, + ClassSetItem::Bracketed(ref x) => &x.span, + ClassSetItem::Union(ref x) => &x.span, + } + } +} + +/// A single character class range in a set. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassSetRange { + /// The span of this range. + pub span: Span, + /// The start of this range. + pub start: Literal, + /// The end of this range. + pub end: Literal, +} + +impl ClassSetRange { + /// Returns true if and only if this character class range is valid. + /// + /// The only case where a range is invalid is if its start is greater than + /// its end. + pub fn is_valid(&self) -> bool { + self.start.c <= self.end.c + } +} + +/// A union of items inside a character class set. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassSetUnion { + /// The span of the items in this operation. e.g., the `a-z0-9` in + /// `[^a-z0-9]` + pub span: Span, + /// The sequence of items that make up this union. + pub items: Vec<ClassSetItem>, +} + +impl ClassSetUnion { + /// Push a new item in this union. + /// + /// The ending position of this union's span is updated to the ending + /// position of the span of the item given. If the union is empty, then + /// the starting position of this union is set to the starting position + /// of this item. + /// + /// In other words, if you only use this method to add items to a union + /// and you set the spans on each item correctly, then you should never + /// need to adjust the span of the union directly. + pub fn push(&mut self, item: ClassSetItem) { + if self.items.is_empty() { + self.span.start = item.span().start; + } + self.span.end = item.span().end; + self.items.push(item); + } + + /// Return this union as a character class set item. + /// + /// If this union contains zero items, then an empty union is + /// returned. If this concatenation contains exactly 1 item, then the + /// corresponding item is returned. Otherwise, ClassSetItem::Union is + /// returned. + pub fn into_item(mut self) -> ClassSetItem { + match self.items.len() { + 0 => ClassSetItem::Empty(self.span), + 1 => self.items.pop().unwrap(), + _ => ClassSetItem::Union(self), + } + } +} + +/// A Unicode character class set operation. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassSetBinaryOp { + /// The span of this operation. e.g., the `a-z--[h-p]` in `[a-z--h-p]`. + pub span: Span, + /// The type of this set operation. + pub kind: ClassSetBinaryOpKind, + /// The left hand side of the operation. + pub lhs: Box<ClassSet>, + /// The right hand side of the operation. + pub rhs: Box<ClassSet>, +} + +/// The type of a Unicode character class set operation. +/// +/// Note that this doesn't explicitly represent union since there is no +/// explicit union operator. Concatenation inside a character class corresponds +/// to the union operation. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ClassSetBinaryOpKind { + /// The intersection of two sets, e.g., `\pN&&[a-z]`. + Intersection, + /// The difference of two sets, e.g., `\pN--[0-9]`. + Difference, + /// The symmetric difference of two sets. The symmetric difference is the + /// set of elements belonging to one but not both sets. + /// e.g., `[\pL~~[:ascii:]]`. + SymmetricDifference, +} + +/// A single zero-width assertion. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Assertion { + /// The span of this assertion. + pub span: Span, + /// The assertion kind, e.g., `\b` or `^`. + pub kind: AssertionKind, +} + +/// An assertion kind. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum AssertionKind { + /// `^` + StartLine, + /// `$` + EndLine, + /// `\A` + StartText, + /// `\z` + EndText, + /// `\b` + WordBoundary, + /// `\B` + NotWordBoundary, +} + +/// A repetition operation applied to a regular expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Repetition { + /// The span of this operation. + pub span: Span, + /// The actual operation. + pub op: RepetitionOp, + /// Whether this operation was applied greedily or not. + pub greedy: bool, + /// The regular expression under repetition. + pub ast: Box<Ast>, +} + +/// The repetition operator itself. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct RepetitionOp { + /// The span of this operator. This includes things like `+`, `*?` and + /// `{m,n}`. + pub span: Span, + /// The type of operation. + pub kind: RepetitionKind, +} + +/// The kind of a repetition operator. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum RepetitionKind { + /// `?` + ZeroOrOne, + /// `*` + ZeroOrMore, + /// `+` + OneOrMore, + /// `{m,n}` + Range(RepetitionRange), +} + +/// A range repetition operator. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum RepetitionRange { + /// `{m}` + Exactly(u32), + /// `{m,}` + AtLeast(u32), + /// `{m,n}` + Bounded(u32, u32), +} + +impl RepetitionRange { + /// Returns true if and only if this repetition range is valid. + /// + /// The only case where a repetition range is invalid is if it is bounded + /// and its start is greater than its end. + pub fn is_valid(&self) -> bool { + match *self { + RepetitionRange::Bounded(s, e) if s > e => false, + _ => true, + } + } +} + +/// A grouped regular expression. +/// +/// This includes both capturing and non-capturing groups. This does **not** +/// include flag-only groups like `(?is)`, but does contain any group that +/// contains a sub-expression, e.g., `(a)`, `(?P<name>a)`, `(?:a)` and +/// `(?is:a)`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Group { + /// The span of this group. + pub span: Span, + /// The kind of this group. + pub kind: GroupKind, + /// The regular expression in this group. + pub ast: Box<Ast>, +} + +impl Group { + /// If this group is non-capturing, then this returns the (possibly empty) + /// set of flags. Otherwise, `None` is returned. + pub fn flags(&self) -> Option<&Flags> { + match self.kind { + GroupKind::NonCapturing(ref flags) => Some(flags), + _ => None, + } + } + + /// Returns true if and only if this group is capturing. + pub fn is_capturing(&self) -> bool { + match self.kind { + GroupKind::CaptureIndex(_) | GroupKind::CaptureName(_) => true, + GroupKind::NonCapturing(_) => false, + } + } + + /// Returns the capture index of this group, if this is a capturing group. + /// + /// This returns a capture index precisely when `is_capturing` is `true`. + pub fn capture_index(&self) -> Option<u32> { + match self.kind { + GroupKind::CaptureIndex(i) => Some(i), + GroupKind::CaptureName(ref x) => Some(x.index), + GroupKind::NonCapturing(_) => None, + } + } +} + +/// The kind of a group. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum GroupKind { + /// `(a)` + CaptureIndex(u32), + /// `(?P<name>a)` + CaptureName(CaptureName), + /// `(?:a)` and `(?i:a)` + NonCapturing(Flags), +} + +/// A capture name. +/// +/// This corresponds to the name itself between the angle brackets in, e.g., +/// `(?P<foo>expr)`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct CaptureName { + /// The span of this capture name. + pub span: Span, + /// The capture name. + pub name: String, + /// The capture index. + pub index: u32, +} + +/// A group of flags that is not applied to a particular regular expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct SetFlags { + /// The span of these flags, including the grouping parentheses. + pub span: Span, + /// The actual sequence of flags. + pub flags: Flags, +} + +/// A group of flags. +/// +/// This corresponds only to the sequence of flags themselves, e.g., `is-u`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Flags { + /// The span of this group of flags. + pub span: Span, + /// A sequence of flag items. Each item is either a flag or a negation + /// operator. + pub items: Vec<FlagsItem>, +} + +impl Flags { + /// Add the given item to this sequence of flags. + /// + /// If the item was added successfully, then `None` is returned. If the + /// given item is a duplicate, then `Some(i)` is returned, where + /// `items[i].kind == item.kind`. + pub fn add_item(&mut self, item: FlagsItem) -> Option<usize> { + for (i, x) in self.items.iter().enumerate() { + if x.kind == item.kind { + return Some(i); + } + } + self.items.push(item); + None + } + + /// Returns the state of the given flag in this set. + /// + /// If the given flag is in the set but is negated, then `Some(false)` is + /// returned. + /// + /// If the given flag is in the set and is not negated, then `Some(true)` + /// is returned. + /// + /// Otherwise, `None` is returned. + pub fn flag_state(&self, flag: Flag) -> Option<bool> { + let mut negated = false; + for x in &self.items { + match x.kind { + FlagsItemKind::Negation => { + negated = true; + } + FlagsItemKind::Flag(ref xflag) if xflag == &flag => { + return Some(!negated); + } + _ => {} + } + } + None + } +} + +/// A single item in a group of flags. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct FlagsItem { + /// The span of this item. + pub span: Span, + /// The kind of this item. + pub kind: FlagsItemKind, +} + +/// The kind of an item in a group of flags. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum FlagsItemKind { + /// A negation operator applied to all subsequent flags in the enclosing + /// group. + Negation, + /// A single flag in a group. + Flag(Flag), +} + +impl FlagsItemKind { + /// Returns true if and only if this item is a negation operator. + pub fn is_negation(&self) -> bool { + match *self { + FlagsItemKind::Negation => true, + _ => false, + } + } +} + +/// A single flag. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Flag { + /// `i` + CaseInsensitive, + /// `m` + MultiLine, + /// `s` + DotMatchesNewLine, + /// `U` + SwapGreed, + /// `u` + Unicode, + /// `x` + IgnoreWhitespace, +} + +/// A custom `Drop` impl is used for `Ast` such that it uses constant stack +/// space but heap space proportional to the depth of the `Ast`. +impl Drop for Ast { + fn drop(&mut self) { + use std::mem; + + match *self { + Ast::Empty(_) + | Ast::Flags(_) + | Ast::Literal(_) + | Ast::Dot(_) + | Ast::Assertion(_) + // Classes are recursive, so they get their own Drop impl. + | Ast::Class(_) => return, + Ast::Repetition(ref x) if !x.ast.has_subexprs() => return, + Ast::Group(ref x) if !x.ast.has_subexprs() => return, + Ast::Alternation(ref x) if x.asts.is_empty() => return, + Ast::Concat(ref x) if x.asts.is_empty() => return, + _ => {} + } + + let empty_span = || Span::splat(Position::new(0, 0, 0)); + let empty_ast = || Ast::Empty(empty_span()); + let mut stack = vec![mem::replace(self, empty_ast())]; + while let Some(mut ast) = stack.pop() { + match ast { + Ast::Empty(_) + | Ast::Flags(_) + | Ast::Literal(_) + | Ast::Dot(_) + | Ast::Assertion(_) + // Classes are recursive, so they get their own Drop impl. + | Ast::Class(_) => {} + Ast::Repetition(ref mut x) => { + stack.push(mem::replace(&mut x.ast, empty_ast())); + } + Ast::Group(ref mut x) => { + stack.push(mem::replace(&mut x.ast, empty_ast())); + } + Ast::Alternation(ref mut x) => { + stack.extend(x.asts.drain(..)); + } + Ast::Concat(ref mut x) => { + stack.extend(x.asts.drain(..)); + } + } + } + } +} + +/// A custom `Drop` impl is used for `ClassSet` such that it uses constant +/// stack space but heap space proportional to the depth of the `ClassSet`. +impl Drop for ClassSet { + fn drop(&mut self) { + use std::mem; + + match *self { + ClassSet::Item(ref item) => { + match *item { + ClassSetItem::Empty(_) + | ClassSetItem::Literal(_) + | ClassSetItem::Range(_) + | ClassSetItem::Ascii(_) + | ClassSetItem::Unicode(_) + | ClassSetItem::Perl(_) => return, + ClassSetItem::Bracketed(ref x) => { + if x.kind.is_empty() { + return; + } + } + ClassSetItem::Union(ref x) => { + if x.items.is_empty() { + return; + } + } + } + } + ClassSet::BinaryOp(ref op) => { + if op.lhs.is_empty() && op.rhs.is_empty() { + return; + } + } + } + + let empty_span = || Span::splat(Position::new(0, 0, 0)); + let empty_set = || ClassSet::Item(ClassSetItem::Empty(empty_span())); + let mut stack = vec![mem::replace(self, empty_set())]; + while let Some(mut set) = stack.pop() { + match set { + ClassSet::Item(ref mut item) => { + match *item { + ClassSetItem::Empty(_) + | ClassSetItem::Literal(_) + | ClassSetItem::Range(_) + | ClassSetItem::Ascii(_) + | ClassSetItem::Unicode(_) + | ClassSetItem::Perl(_) => {} + ClassSetItem::Bracketed(ref mut x) => { + stack.push(mem::replace(&mut x.kind, empty_set())); + } + ClassSetItem::Union(ref mut x) => { + stack.extend( + x.items.drain(..).map(ClassSet::Item)); + } + } + } + ClassSet::BinaryOp(ref mut op) => { + stack.push(mem::replace(&mut op.lhs, empty_set())); + stack.push(mem::replace(&mut op.rhs, empty_set())); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // We use a thread with an explicit stack size to test that our destructor + // for Ast can handle arbitrarily sized expressions in constant stack + // space. In case we run on a platform without threads (WASM?), we limit + // this test to Windows/Unix. + #[test] + #[cfg(any(unix, windows))] + fn no_stack_overflow_on_drop() { + use std::thread; + + let run = || { + let span = || Span::splat(Position::new(0, 0, 0)); + let mut ast = Ast::Empty(span()); + for i in 0..200 { + ast = Ast::Group(Group { + span: span(), + kind: GroupKind::CaptureIndex(i), + ast: Box::new(ast), + }); + } + assert!(!ast.is_empty()); + }; + + // We run our test on a thread with a small stack size so we can + // force the issue more easily. + thread::Builder::new() + .stack_size(1<<10) + .spawn(run) + .unwrap() + .join() + .unwrap(); + } +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/ast/parse.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/ast/parse.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/ast/parse.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/ast/parse.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,5352 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +This module provides a regular expression parser. +*/ + +use std::borrow::Borrow; +use std::cell::{Cell, RefCell}; +use std::mem; +use std::result; + +use ast::{self, Ast, Position, Span}; +use either::Either; + +use is_meta_character; + +type Result<T> = result::Result<T, ast::Error>; + +/// A primitive is an expression with no sub-expressions. This includes +/// literals, assertions and non-set character classes. This representation +/// is used as intermediate state in the parser. +/// +/// This does not include ASCII character classes, since they can only appear +/// within a set character class. +#[derive(Clone, Debug, Eq, PartialEq)] +enum Primitive { + Literal(ast::Literal), + Assertion(ast::Assertion), + Dot(Span), + Perl(ast::ClassPerl), + Unicode(ast::ClassUnicode), +} + +impl Primitive { + /// Return the span of this primitive. + fn span(&self) -> &Span { + match *self { + Primitive::Literal(ref x) => &x.span, + Primitive::Assertion(ref x) => &x.span, + Primitive::Dot(ref span) => span, + Primitive::Perl(ref x) => &x.span, + Primitive::Unicode(ref x) => &x.span, + } + } + + /// Convert this primitive into a proper AST. + fn into_ast(self) -> Ast { + match self { + Primitive::Literal(lit) => Ast::Literal(lit), + Primitive::Assertion(assert) => Ast::Assertion(assert), + Primitive::Dot(span) => Ast::Dot(span), + Primitive::Perl(cls) => Ast::Class(ast::Class::Perl(cls)), + Primitive::Unicode(cls) => Ast::Class(ast::Class::Unicode(cls)), + } + } + + /// Convert this primitive into an item in a character class. + /// + /// If this primitive is not a legal item (i.e., an assertion or a dot), + /// then return an error. + fn into_class_set_item<P: Borrow<Parser>>( + self, + p: &ParserI<P>, + ) -> Result<ast::ClassSetItem> { + use ast::ClassSetItem; + use self::Primitive::*; + + match self { + Literal(lit) => Ok(ClassSetItem::Literal(lit)), + Perl(cls) => Ok(ClassSetItem::Perl(cls)), + Unicode(cls) => Ok(ClassSetItem::Unicode(cls)), + x => Err(p.error(*x.span(), ast::ErrorKind::ClassEscapeInvalid)), + } + } + + /// Convert this primitive into a literal in a character class. In + /// particular, literals are the only valid items that can appear in + /// ranges. + /// + /// If this primitive is not a legal item (i.e., a class, assertion or a + /// dot), then return an error. + fn into_class_literal<P: Borrow<Parser>>( + self, + p: &ParserI<P>, + ) -> Result<ast::Literal> { + use self::Primitive::*; + + match self { + Literal(lit) => Ok(lit), + x => Err(p.error(*x.span(), ast::ErrorKind::ClassEscapeInvalid)), + } + } +} + +/// Returns true if the given character is a hexadecimal digit. +fn is_hex(c: char) -> bool { + ('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') +} + +/// Returns true if the given character is a valid in a capture group name. +/// +/// If `first` is true, then `c` is treated as the first character in the +/// group name (which is not allowed to be a digit). +fn is_capture_char(c: char, first: bool) -> bool { + c == '_' || (!first && c >= '0' && c <= '9') + || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') +} + +/// A builder for a regular expression parser. +/// +/// This builder permits modifying configuration options for the parser. +#[derive(Clone, Debug)] +pub struct ParserBuilder { + ignore_whitespace: bool, + nest_limit: u32, + octal: bool, +} + +impl Default for ParserBuilder { + fn default() -> ParserBuilder { + ParserBuilder::new() + } +} + +impl ParserBuilder { + /// Create a new parser builder with a default configuration. + pub fn new() -> ParserBuilder { + ParserBuilder { + ignore_whitespace: false, + nest_limit: 250, + octal: false, + } + } + + /// Build a parser from this configuration with the given pattern. + pub fn build(&self) -> Parser { + Parser { + pos: Cell::new(Position { offset: 0, line: 1, column: 1 }), + capture_index: Cell::new(0), + nest_limit: self.nest_limit, + octal: self.octal, + initial_ignore_whitespace: self.ignore_whitespace, + ignore_whitespace: Cell::new(self.ignore_whitespace), + comments: RefCell::new(vec![]), + stack_group: RefCell::new(vec![]), + stack_class: RefCell::new(vec![]), + capture_names: RefCell::new(vec![]), + scratch: RefCell::new(String::new()), + } + } + + /// Set the nesting limit for this parser. + /// + /// The nesting limit controls how deep the abstract syntax tree is allowed + /// to be. If the AST exceeds the given limit (e.g., with too many nested + /// groups), then an error is returned by the parser. + /// + /// The purpose of this limit is to act as a heuristic to prevent stack + /// overflow for consumers that do structural induction on an `Ast` using + /// explicit recursion. While this crate never does this (instead using + /// constant stack space and moving the call stack to the heap), other + /// crates may. + /// + /// This limit is not checked until the entire Ast is parsed. Therefore, + /// if callers want to put a limit on the amount of heap space used, then + /// they should impose a limit on the length, in bytes, of the concrete + /// pattern string. In particular, this is viable since this parser + /// implementation will limit itself to heap space proportional to the + /// lenth of the pattern string. + /// + /// Note that a nest limit of `0` will return a nest limit error for most + /// patterns but not all. For example, a nest limit of `0` permits `a` but + /// not `ab`, since `ab` requires a concatenation, which results in a nest + /// depth of `1`. In general, a nest limit is not something that manifests + /// in an obvious way in the concrete syntax, therefore, it should not be + /// used in a granular way. + pub fn nest_limit(&mut self, limit: u32) -> &mut ParserBuilder { + self.nest_limit = limit; + self + } + + /// Whether to support octal syntax or not. + /// + /// Octal syntax is a little-known way of uttering Unicode codepoints in + /// a regular expression. For example, `a`, `\x61`, `\u0061` and + /// `\141` are all equivalent regular expressions, where the last example + /// shows octal syntax. + /// + /// While supporting octal syntax isn't in and of itself a problem, it does + /// make good error messages harder. That is, in PCRE based regex engines, + /// syntax like `\0` invokes a backreference, which is explicitly + /// unsupported in Rust's regex engine. However, many users expect it to + /// be supported. Therefore, when octal support is disabled, the error + /// message will explicitly mention that backreferences aren't supported. + /// + /// Octal syntax is disabled by default. + pub fn octal(&mut self, yes: bool) -> &mut ParserBuilder { + self.octal = yes; + self + } + + /// Enable verbose mode in the regular expression. + /// + /// When enabled, verbose mode permits insigificant whitespace in many + /// places in the regular expression, as well as comments. Comments are + /// started using `#` and continue until the end of the line. + /// + /// By default, this is disabled. It may be selectively enabled in the + /// regular expression by using the `x` flag regardless of this setting. + pub fn ignore_whitespace(&mut self, yes: bool) -> &mut ParserBuilder { + self.ignore_whitespace = yes; + self + } +} + +/// A regular expression parser. +/// +/// This parses a string representation of a regular expression into an +/// abstract syntax tree. The size of the tree is proportional to the length +/// of the regular expression pattern. +/// +/// A `Parser` can be configured in more detail via a +/// [`ParserBuilder`](struct.ParserBuilder.html). +#[derive(Clone, Debug)] +pub struct Parser { + /// The current position of the parser. + pos: Cell<Position>, + /// The current capture index. + capture_index: Cell<u32>, + /// The maximum number of open parens/brackets allowed. If the parser + /// exceeds this number, then an error is returned. + nest_limit: u32, + /// Whether to support octal syntax or not. When `false`, the parser will + /// return an error helpfully pointing out that backreferences are not + /// supported. + octal: bool, + /// The initial setting for `ignore_whitespace` as provided by + /// Th`ParserBuilder`. is is used when reseting the parser's state. + initial_ignore_whitespace: bool, + /// Whether whitespace should be ignored. When enabled, comments are + /// also permitted. + ignore_whitespace: Cell<bool>, + /// A list of comments, in order of appearance. + comments: RefCell<Vec<ast::Comment>>, + /// A stack of grouped sub-expressions, including alternations. + stack_group: RefCell<Vec<GroupState>>, + /// A stack of nested character classes. This is only non-empty when + /// parsing a class. + stack_class: RefCell<Vec<ClassState>>, + /// A sorted sequence of capture names. This is used to detect duplicate + /// capture names and report an error if one is detected. + capture_names: RefCell<Vec<ast::CaptureName>>, + /// A scratch buffer used in various places. Mostly this is used to + /// accumulate relevant characters from parts of a pattern. + scratch: RefCell<String>, +} + +/// ParserI is the internal parser implementation. +/// +/// We use this separate type so that we can carry the provided pattern string +/// along with us. In particular, a `Parser` internal state is not tied to any +/// one pattern, but `ParserI` is. +/// +/// This type also lets us use `ParserI<&Parser>` in production code while +/// retaining the convenience of `ParserI<Parser>` for tests, which sometimes +/// work against the internal interface of the parser. +#[derive(Clone, Debug)] +struct ParserI<'s, P> { + /// The parser state/configuration. + parser: P, + /// The full regular expression provided by the user. + pattern: &'s str, +} + +/// GroupState represents a single stack frame while parsing nested groups +/// and alternations. Each frame records the state up to an opening parenthesis +/// or a alternating bracket `|`. +#[derive(Clone, Debug)] +enum GroupState { + /// This state is pushed whenever an opening group is found. + Group { + /// The concatenation immediately preceding the opening group. + concat: ast::Concat, + /// The group that has been opened. Its sub-AST is always empty. + group: ast::Group, + /// Whether this group has the `x` flag enabled or not. + ignore_whitespace: bool, + }, + /// This state is pushed whenever a new alternation branch is found. If + /// an alternation branch is found and this state is at the top of the + /// stack, then this state should be modified to include the new + /// alternation. + Alternation(ast::Alternation), +} + +/// ClassState represents a single stack frame while parsing character classes. +/// Each frame records the state up to an intersection, difference, symmetric +/// difference or nested class. +/// +/// Note that a parser's character class stack is only non-empty when parsing +/// a character class. In all other cases, it is empty. +#[derive(Clone, Debug)] +enum ClassState { + /// This state is pushed whenever an opening bracket is found. + Open { + /// The union of class items immediately preceding this class. + union: ast::ClassSetUnion, + /// The class that has been opened. Typically this just corresponds + /// to the `[`, but it can also include `[^` since `^` indicates + /// negation of the class. + set: ast::ClassBracketed, + }, + /// This state is pushed when a operator is seen. When popped, the stored + /// set becomes the left hand side of the operator. + Op { + /// The type of the operation, i.e., &&, -- or ~~. + kind: ast::ClassSetBinaryOpKind, + /// The left-hand side of the operator. + lhs: ast::ClassSet, + }, +} + +impl Parser { + /// Create a new parser with a default configuration. + /// + /// The parser can be run with either the `parse` or `parse_with_comments` + /// methods. The parse methods return an abstract syntax tree. + /// + /// To set configuration options on the parser, use + /// [`ParserBuilder`](struct.ParserBuilder.html). + pub fn new() -> Parser { + ParserBuilder::new().build() + } + + /// Parse the regular expression into an abstract syntax tree. + pub fn parse(&mut self, pattern: &str) -> Result<Ast> { + ParserI::new(self, pattern).parse() + } + + /// Parse the regular expression and return an abstract syntax tree with + /// all of the comments found in the pattern. + pub fn parse_with_comments( + &mut self, + pattern: &str, + ) -> Result<ast::WithComments> { + ParserI::new(self, pattern).parse_with_comments() + } + + /// Reset the internal state of a parser. + /// + /// This is called at the beginning of every parse. This prevents the + /// parser from running with inconsistent state (say, if a previous + /// invocation returned an error and the parser is reused). + fn reset(&self) { + // These settings should be in line with the construction + // in `ParserBuilder::build`. + self.pos.set(Position { offset: 0, line: 1, column: 1}); + self.ignore_whitespace.set(self.initial_ignore_whitespace); + self.comments.borrow_mut().clear(); + self.stack_group.borrow_mut().clear(); + self.stack_class.borrow_mut().clear(); + } +} + +impl<'s, P: Borrow<Parser>> ParserI<'s, P> { + /// Build an internal parser from a parser configuration and a pattern. + fn new(parser: P, pattern: &'s str) -> ParserI<'s, P> { + ParserI { parser: parser, pattern: pattern } + } + + /// Return a reference to the parser state. + fn parser(&self) -> &Parser { + self.parser.borrow() + } + + /// Return a reference to the pattern being parsed. + fn pattern(&self) -> &str { + self.pattern.borrow() + } + + /// Create a new error with the given span and error type. + fn error(&self, span: Span, kind: ast::ErrorKind) -> ast::Error { + ast::Error { + kind: kind, + pattern: self.pattern().to_string(), + span: span, + } + } + + /// Return the current offset of the parser. + /// + /// The offset starts at `0` from the beginning of the regular expression + /// pattern string. + fn offset(&self) -> usize { + self.parser().pos.get().offset + } + + /// Return the current line number of the parser. + /// + /// The line number starts at `1`. + fn line(&self) -> usize { + self.parser().pos.get().line + } + + /// Return the current column of the parser. + /// + /// The column number starts at `1` and is reset whenever a `\n` is seen. + fn column(&self) -> usize { + self.parser().pos.get().column + } + + /// Return the next capturing index. Each subsequent call increments the + /// internal index. + /// + /// The span given should correspond to the location of the opening + /// parenthesis. + /// + /// If the capture limit is exceeded, then an error is returned. + fn next_capture_index(&self, span: Span) -> Result<u32> { + let current = self.parser().capture_index.get(); + let i = try!(current.checked_add(1).ok_or_else(|| { + self.error(span, ast::ErrorKind::CaptureLimitExceeded) + })); + self.parser().capture_index.set(i); + Ok(i) + } + + /// Adds the given capture name to this parser. If this capture name has + /// already been used, then an error is returned. + fn add_capture_name(&self, cap: &ast::CaptureName) -> Result<()> { + let mut names = self.parser().capture_names.borrow_mut(); + match names.binary_search_by_key( + &cap.name.as_str(), + |c| c.name.as_str(), + ) { + Err(i) => { + names.insert(i, cap.clone()); + Ok(()) + } + Ok(i) => { + Err(self.error(cap.span, ast::ErrorKind::GroupNameDuplicate { + original: names[i].span, + })) + } + } + } + + /// Return whether the parser should ignore whitespace or not. + fn ignore_whitespace(&self) -> bool { + self.parser().ignore_whitespace.get() + } + + /// Return the character at the current position of the parser. + /// + /// This panics if the current position does not point to a valid char. + fn char(&self) -> char { + self.char_at(self.offset()) + } + + /// Return the character at the given position. + /// + /// This panics if the given position does not point to a valid char. + fn char_at(&self, i: usize) -> char { + self.pattern()[i..].chars().next() + .unwrap_or_else(|| { + panic!("expected char at offset {}", i) + }) + } + + /// Bump the parser to the next Unicode scalar value. + /// + /// If the end of the input has been reached, then `false` is returned. + fn bump(&self) -> bool { + if self.is_eof() { + return false; + } + let Position { mut offset, mut line, mut column } = self.pos(); + if self.char() == '\n' { + line = line.checked_add(1).unwrap(); + column = 1; + } else { + column = column.checked_add(1).unwrap(); + } + offset += self.char().len_utf8(); + self.parser().pos.set(Position { + offset: offset, + line: line, + column: column, + }); + self.pattern()[self.offset()..].chars().next().is_some() + } + + /// If the substring starting at the current position of the parser has + /// the given prefix, then bump the parser to the character immediately + /// following the prefix and return true. Otherwise, don't bump the parser + /// and return false. + fn bump_if(&self, prefix: &str) -> bool { + if self.pattern()[self.offset()..].starts_with(prefix) { + for _ in 0..prefix.chars().count() { + self.bump(); + } + true + } else { + false + } + } + + /// Returns true if and only if the parser is positioned at a look-around + /// prefix. The conditions under which this returns true must always + /// correspond to a regular expression that would otherwise be consider + /// invalid. + /// + /// This should only be called immediately after parsing the opening of + /// a group or a set of flags. + fn is_lookaround_prefix(&self) -> bool { + self.bump_if("?=") + || self.bump_if("?!") + || self.bump_if("?<=") + || self.bump_if("?<!") + } + + /// Bump the parser, and if the `x` flag is enabled, bump through any + /// subsequent spaces. Return true if and only if the parser is not at + /// EOF. + fn bump_and_bump_space(&self) -> bool { + if !self.bump() { + return false; + } + self.bump_space(); + !self.is_eof() + } + + /// If the `x` flag is enabled (i.e., whitespace insensitivity with + /// comments), then this will advance the parser through all whitespace + /// and comments to the next non-whitespace non-comment byte. + /// + /// If the `x` flag is disabled, then this is a no-op. + /// + /// This should be used selectively throughout the parser where + /// arbitrary whitespace is permitted when the `x` flag is enabled. For + /// example, `{ 5 , 6}` is equivalent to `{5,6}`. + fn bump_space(&self) { + if !self.ignore_whitespace() { + return; + } + while !self.is_eof() { + if self.char().is_whitespace() { + self.bump(); + } else if self.char() == '#' { + let start = self.pos(); + let mut comment_text = String::new(); + self.bump(); + while !self.is_eof() { + let c = self.char(); + self.bump(); + if c == '\n' { + break; + } + comment_text.push(c); + } + let comment = ast::Comment { + span: Span::new(start, self.pos()), + comment: comment_text, + }; + self.parser().comments.borrow_mut().push(comment); + } else { + break; + } + } + } + + /// Peek at the next character in the input without advancing the parser. + /// + /// If the input has been exhausted, then this returns `None`. + fn peek(&self) -> Option<char> { + if self.is_eof() { + return None; + } + self.pattern()[self.offset() + self.char().len_utf8()..].chars().next() + } + + /// Like peek, but will ignore spaces when the parser is in whitespace + /// insensitive mode. + fn peek_space(&self) -> Option<char> { + if !self.ignore_whitespace() { + return self.peek(); + } + if self.is_eof() { + return None; + } + let mut start = self.offset() + self.char().len_utf8(); + let mut in_comment = false; + for (i, c) in self.pattern()[start..].char_indices() { + if c.is_whitespace() { + continue; + } else if !in_comment && c == '#' { + in_comment = true; + } else if in_comment && c == '\n' { + in_comment = false; + } else { + start += i; + break; + } + } + self.pattern()[start..].chars().next() + } + + /// Returns true if the next call to `bump` would return false. + fn is_eof(&self) -> bool { + self.offset() == self.pattern().len() + } + + /// Return the current position of the parser, which includes the offset, + /// line and column. + fn pos(&self) -> Position { + self.parser().pos.get() + } + + /// Create a span at the current position of the parser. Both the start + /// and end of the span are set. + fn span(&self) -> Span { + Span::splat(self.pos()) + } + + /// Create a span that covers the current character. + fn span_char(&self) -> Span { + let mut next = Position { + offset: self.offset().checked_add(self.char().len_utf8()).unwrap(), + line: self.line(), + column: self.column().checked_add(1).unwrap(), + }; + if self.char() == '\n' { + next.line += 1; + next.column = 1; + } + Span::new(self.pos(), next) + } + + /// Parse and push a single alternation on to the parser's internal stack. + /// If the top of the stack already has an alternation, then add to that + /// instead of pushing a new one. + /// + /// The concatenation given corresponds to a single alternation branch. + /// The concatenation returned starts the next branch and is empty. + /// + /// This assumes the parser is currently positioned at `|` and will advance + /// the parser to the character following `|`. + fn push_alternate(&self, mut concat: ast::Concat) -> Result<ast::Concat> { + assert_eq!(self.char(), '|'); + concat.span.end = self.pos(); + self.push_or_add_alternation(concat); + self.bump(); + Ok(ast::Concat { + span: self.span(), + asts: vec![], + }) + } + + /// Pushes or adds the given branch of an alternation to the parser's + /// internal stack of state. + fn push_or_add_alternation(&self, concat: ast::Concat) { + use self::GroupState::*; + + let mut stack = self.parser().stack_group.borrow_mut(); + if let Some(&mut Alternation(ref mut alts)) = stack.last_mut() { + alts.asts.push(concat.into_ast()); + return; + } + stack.push(Alternation(ast::Alternation { + span: Span::new(concat.span.start, self.pos()), + asts: vec![concat.into_ast()], + })); + } + + /// Parse and push a group AST (and its parent concatenation) on to the + /// parser's internal stack. Return a fresh concatenation corresponding + /// to the group's sub-AST. + /// + /// If a set of flags was found (with no group), then the concatenation + /// is returned with that set of flags added. + /// + /// This assumes that the parser is currently positioned on the opening + /// parenthesis. It advances the parser to the character at the start + /// of the sub-expression (or adjoining expression). + /// + /// If there was a problem parsing the start of the group, then an error + /// is returned. + fn push_group(&self, mut concat: ast::Concat) -> Result<ast::Concat> { + assert_eq!(self.char(), '('); + match try!(self.parse_group()) { + Either::Left(set) => { + let ignore = set.flags.flag_state(ast::Flag::IgnoreWhitespace); + if let Some(v) = ignore { + self.parser().ignore_whitespace.set(v); + } + + concat.asts.push(Ast::Flags(set)); + Ok(concat) + } + Either::Right(group) => { + let old_ignore_whitespace = self.ignore_whitespace(); + let new_ignore_whitespace = group + .flags() + .and_then(|f| f.flag_state(ast::Flag::IgnoreWhitespace)) + .unwrap_or(old_ignore_whitespace); + self.parser().stack_group.borrow_mut().push(GroupState::Group { + concat: concat, + group: group, + ignore_whitespace: old_ignore_whitespace, + }); + self.parser().ignore_whitespace.set(new_ignore_whitespace); + Ok(ast::Concat { + span: self.span(), + asts: vec![], + }) + } + } + } + + /// Pop a group AST from the parser's internal stack and set the group's + /// AST to the given concatenation. Return the concatenation containing + /// the group. + /// + /// This assumes that the parser is currently positioned on the closing + /// parenthesis and advances the parser to the character following the `)`. + /// + /// If no such group could be popped, then an unopened group error is + /// returned. + fn pop_group(&self, mut group_concat: ast::Concat) -> Result<ast::Concat> { + use self::GroupState::*; + + assert_eq!(self.char(), ')'); + let mut stack = self.parser().stack_group.borrow_mut(); + let (mut prior_concat, mut group, ignore_whitespace, alt) = + match stack.pop() { + Some(Group { concat, group, ignore_whitespace }) => { + (concat, group, ignore_whitespace, None) + } + Some(Alternation(alt)) => { + match stack.pop() { + Some(Group { concat, group, ignore_whitespace }) => { + (concat, group, ignore_whitespace, Some(alt)) + } + None | Some(Alternation(_)) => { + return Err(self.error( + self.span_char(), + ast::ErrorKind::GroupUnopened, + )); + } + } + } + None => { + return Err(self.error( + self.span_char(), + ast::ErrorKind::GroupUnopened, + )); + } + }; + self.parser().ignore_whitespace.set(ignore_whitespace); + group_concat.span.end = self.pos(); + self.bump(); + group.span.end = self.pos(); + match alt { + Some(mut alt) => { + alt.span.end = group_concat.span.end; + alt.asts.push(group_concat.into_ast()); + group.ast = Box::new(alt.into_ast()); + } + None => { + group.ast = Box::new(group_concat.into_ast()); + } + } + prior_concat.asts.push(Ast::Group(group)); + Ok(prior_concat) + } + + /// Pop the last state from the parser's internal stack, if it exists, and + /// add the given concatenation to it. There either must be no state or a + /// single alternation item on the stack. Any other scenario produces an + /// error. + /// + /// This assumes that the parser has advanced to the end. + fn pop_group_end(&self, mut concat: ast::Concat) -> Result<Ast> { + concat.span.end = self.pos(); + let mut stack = self.parser().stack_group.borrow_mut(); + let ast = match stack.pop() { + None => Ok(concat.into_ast()), + Some(GroupState::Alternation(mut alt)) => { + alt.span.end = self.pos(); + alt.asts.push(concat.into_ast()); + Ok(Ast::Alternation(alt)) + } + Some(GroupState::Group { group, .. }) => { + return Err(self.error( + group.span, + ast::ErrorKind::GroupUnclosed, + )); + } + }; + // If we try to pop again, there should be nothing. + match stack.pop() { + None => ast, + Some(GroupState::Alternation(_)) => { + // This unreachable is unfortunate. This case can't happen + // because the only way we can be here is if there were two + // `GroupState::Alternation`s adjacent in the parser's stack, + // which we guarantee to never happen because we never push a + // `GroupState::Alternation` if one is already at the top of + // the stack. + unreachable!() + } + Some(GroupState::Group { group, .. }) => { + Err(self.error(group.span, ast::ErrorKind::GroupUnclosed)) + } + } + } + + /// Parse the opening of a character class and push the current class + /// parsing context onto the parser's stack. This assumes that the parser + /// is positioned at an opening `[`. The given union should correspond to + /// the union of set items built up before seeing the `[`. + /// + /// If there was a problem parsing the opening of the class, then an error + /// is returned. Otherwise, a new union of set items for the class is + /// returned (which may be populated with either a `]` or a `-`). + fn push_class_open( + &self, + parent_union: ast::ClassSetUnion, + ) -> Result<ast::ClassSetUnion> { + assert_eq!(self.char(), '['); + + let (nested_set, nested_union) = try!(self.parse_set_class_open()); + self.parser().stack_class.borrow_mut().push(ClassState::Open { + union: parent_union, + set: nested_set, + }); + Ok(nested_union) + } + + /// Parse the end of a character class set and pop the character class + /// parser stack. The union given corresponds to the last union built + /// before seeing the closing `]`. The union returned corresponds to the + /// parent character class set with the nested class added to it. + /// + /// This assumes that the parser is positioned at a `]` and will advance + /// the parser to the byte immediately following the `]`. + /// + /// If the stack is empty after popping, then this returns the final + /// "top-level" character class AST (where a "top-level" character class + /// is one that is not nested inside any other character class). + /// + /// If there is no corresponding opening bracket on the parser's stack, + /// then an error is returned. + fn pop_class( + &self, + nested_union: ast::ClassSetUnion, + ) -> Result<Either<ast::ClassSetUnion, ast::Class>> { + assert_eq!(self.char(), ']'); + + let item = ast::ClassSet::Item(nested_union.into_item()); + let prevset = self.pop_class_op(item); + let mut stack = self.parser().stack_class.borrow_mut(); + match stack.pop() { + None => { + // We can never observe an empty stack: + // + // 1) We are guaranteed to start with a non-empty stack since + // the character class parser is only initiated when it sees + // a `[`. + // 2) If we ever observe an empty stack while popping after + // seeing a `]`, then we signal the character class parser + // to terminate. + panic!("unexpected empty character class stack") + }, + Some(ClassState::Op { .. }) => { + // This panic is unfortunate, but this case is impossible + // since we already popped the Op state if one exists above. + // Namely, every push to the class parser stack is guarded by + // whether an existing Op is already on the top of the stack. + // If it is, the existing Op is modified. That is, the stack + // can never have consecutive Op states. + panic!("unexpected ClassState::Op") + } + Some(ClassState::Open { mut union, mut set }) => { + self.bump(); + set.span.end = self.pos(); + set.kind = prevset; + if stack.is_empty() { + Ok(Either::Right(ast::Class::Bracketed(set))) + } else { + union.push(ast::ClassSetItem::Bracketed(Box::new(set))); + Ok(Either::Left(union)) + } + } + } + } + + /// Return an "unclosed class" error whose span points to the most + /// recently opened class. + /// + /// This should only be called while parsing a character class. + fn unclosed_class_error(&self) -> ast::Error { + for state in self.parser().stack_class.borrow().iter().rev() { + match *state { + ClassState::Open { ref set, .. } => { + return self.error(set.span, ast::ErrorKind::ClassUnclosed); + } + _ => {} + } + } + // We are guaranteed to have a non-empty stack with at least + // one open bracket, so we should never get here. + panic!("no open character class found") + } + + /// Push the current set of class items on to the class parser's stack as + /// the left hand side of the given operator. + /// + /// A fresh set union is returned, which should be used to build the right + /// hand side of this operator. + fn push_class_op( + &self, + next_kind: ast::ClassSetBinaryOpKind, + next_union: ast::ClassSetUnion, + ) -> ast::ClassSetUnion { + + let item = ast::ClassSet::Item(next_union.into_item()); + let new_lhs = self.pop_class_op(item); + self.parser().stack_class.borrow_mut().push(ClassState::Op { + kind: next_kind, + lhs: new_lhs, + }); + ast::ClassSetUnion { span: self.span(), items: vec![] } + } + + /// Pop a character class set from the character class parser stack. If the + /// top of the stack is just an item (not an operation), then return the + /// given set unchanged. If the top of the stack is an operation, then the + /// given set will be used as the rhs of the operation on the top of the + /// stack. In that case, the binary operation is returned as a set. + fn pop_class_op(&self, rhs: ast::ClassSet) -> ast::ClassSet { + let mut stack = self.parser().stack_class.borrow_mut(); + let (kind, lhs) = match stack.pop() { + Some(ClassState::Op { kind, lhs }) => (kind, lhs), + Some(state @ ClassState::Open { .. }) => { + stack.push(state); + return rhs; + } + None => unreachable!(), + }; + let span = Span::new(lhs.span().start, rhs.span().end); + ast::ClassSet::BinaryOp(ast::ClassSetBinaryOp { + span: span, + kind: kind, + lhs: Box::new(lhs), + rhs: Box::new(rhs), + }) + } +} + +impl<'s, P: Borrow<Parser>> ParserI<'s, P> { + /// Parse the regular expression into an abstract syntax tree. + fn parse(&self) -> Result<Ast> { + self.parse_with_comments().map(|astc| astc.ast) + } + + /// Parse the regular expression and return an abstract syntax tree with + /// all of the comments found in the pattern. + fn parse_with_comments(&self) -> Result<ast::WithComments> { + assert_eq!(self.offset(), 0, "parser can only be used once"); + self.parser().reset(); + let mut concat = ast::Concat { + span: self.span(), + asts: vec![], + }; + loop { + self.bump_space(); + if self.is_eof() { + break; + } + match self.char() { + '(' => concat = try!(self.push_group(concat)), + ')' => concat = try!(self.pop_group(concat)), + '|' => concat = try!(self.push_alternate(concat)), + '[' => { + let class = try!(self.parse_set_class()); + concat.asts.push(Ast::Class(class)); + } + '?' => { + concat = try!(self.parse_uncounted_repetition( + concat, ast::RepetitionKind::ZeroOrOne)); + } + '*' => { + concat = try!(self.parse_uncounted_repetition( + concat, ast::RepetitionKind::ZeroOrMore)); + } + '+' => { + concat = try!(self.parse_uncounted_repetition( + concat, ast::RepetitionKind::OneOrMore)); + } + '{' => { + concat = try!(self.parse_counted_repetition(concat)); + } + _ => concat.asts.push(try!(self.parse_primitive()).into_ast()), + } + } + let ast = try!(self.pop_group_end(concat)); + try!(NestLimiter::new(self).check(&ast)); + Ok(ast::WithComments { + ast: ast, + comments: mem::replace( + &mut *self.parser().comments.borrow_mut(), + vec![], + ), + }) + } + + /// Parses an uncounted repetition operation. An uncounted repetition + /// operator includes ?, * and +, but does not include the {m,n} syntax. + /// The given `kind` should correspond to the operator observed by the + /// caller. + /// + /// This assumes that the paser is currently positioned at the repetition + /// operator and advances the parser to the first character after the + /// operator. (Note that the operator may include a single additional `?`, + /// which makes the operator ungreedy.) + /// + /// The caller should include the concatenation that is being built. The + /// concatenation returned includes the repetition operator applied to the + /// last expression in the given concatenation. + fn parse_uncounted_repetition( + &self, + mut concat: ast::Concat, + kind: ast::RepetitionKind, + ) -> Result<ast::Concat> { + assert!( + self.char() == '?' || self.char() == '*' || self.char() == '+'); + let op_start = self.pos(); + let ast = match concat.asts.pop() { + Some(ast) => ast, + None => return Err(self.error( + self.span(), + ast::ErrorKind::RepetitionMissing, + )), + }; + let mut greedy = true; + if self.bump() && self.char() == '?' { + greedy = false; + self.bump(); + } + concat.asts.push(Ast::Repetition(ast::Repetition { + span: ast.span().with_end(self.pos()), + op: ast::RepetitionOp { + span: Span::new(op_start, self.pos()), + kind: kind, + }, + greedy: greedy, + ast: Box::new(ast), + })); + Ok(concat) + } + + /// Parses a counted repetition operation. A counted repetition operator + /// corresponds to the {m,n} syntax, and does not include the ?, * or + + /// operators. + /// + /// This assumes that the paser is currently positioned at the opening `{` + /// and advances the parser to the first character after the operator. + /// (Note that the operator may include a single additional `?`, which + /// makes the operator ungreedy.) + /// + /// The caller should include the concatenation that is being built. The + /// concatenation returned includes the repetition operator applied to the + /// last expression in the given concatenation. + fn parse_counted_repetition( + &self, + mut concat: ast::Concat, + ) -> Result<ast::Concat> { + assert!(self.char() == '{'); + let start = self.pos(); + let ast = match concat.asts.pop() { + Some(ast) => ast, + None => return Err(self.error( + self.span(), + ast::ErrorKind::RepetitionMissing, + )), + }; + if !self.bump_and_bump_space() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::RepetitionCountUnclosed, + )); + } + let count_start = try!(self.parse_decimal()); + let mut range = ast::RepetitionRange::Exactly(count_start); + if self.is_eof() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::RepetitionCountUnclosed, + )); + } + if self.char() == ',' { + if !self.bump_and_bump_space() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::RepetitionCountUnclosed, + )); + } + if self.char() != '}' { + let count_end = try!(self.parse_decimal()); + range = ast::RepetitionRange::Bounded(count_start, count_end); + } else { + range = ast::RepetitionRange::AtLeast(count_start); + } + } + if self.is_eof() || self.char() != '}' { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::RepetitionCountUnclosed, + )); + } + + let mut greedy = true; + if self.bump_and_bump_space() && self.char() == '?' { + greedy = false; + self.bump(); + } + + let op_span = Span::new(start, self.pos()); + if !range.is_valid() { + return Err(self.error( + op_span, + ast::ErrorKind::RepetitionCountInvalid, + )); + } + concat.asts.push(Ast::Repetition(ast::Repetition { + span: ast.span().with_end(self.pos()), + op: ast::RepetitionOp { + span: op_span, + kind: ast::RepetitionKind::Range(range), + }, + greedy: greedy, + ast: Box::new(ast), + })); + Ok(concat) + } + + /// Parse a group (which contains a sub-expression) or a set of flags. + /// + /// If a group was found, then it is returned with an empty AST. If a set + /// of flags is found, then that set is returned. + /// + /// The parser should be positioned at the opening parenthesis. + /// + /// This advances the parser to the character before the start of the + /// sub-expression (in the case of a group) or to the closing parenthesis + /// immediately following the set of flags. + /// + /// # Errors + /// + /// If flags are given and incorrectly specified, then a corresponding + /// error is returned. + /// + /// If a capture name is given and it is incorrectly specified, then a + /// corresponding error is returned. + fn parse_group(&self) -> Result<Either<ast::SetFlags, ast::Group>> { + assert_eq!(self.char(), '('); + let open_span = self.span_char(); + self.bump(); + self.bump_space(); + if self.is_lookaround_prefix() { + return Err(self.error( + Span::new(open_span.start, self.span().end), + ast::ErrorKind::UnsupportedLookAround, + )); + } + let inner_span = self.span(); + if self.bump_if("?P<") { + let capture_index = try!(self.next_capture_index(open_span)); + let cap = try!(self.parse_capture_name(capture_index)); + Ok(Either::Right(ast::Group { + span: open_span, + kind: ast::GroupKind::CaptureName(cap), + ast: Box::new(Ast::Empty(self.span())), + })) + } else if self.bump_if("?") { + if self.is_eof() { + return Err(self.error( + open_span, + ast::ErrorKind::GroupUnclosed, + )); + } + let flags = try!(self.parse_flags()); + let char_end = self.char(); + self.bump(); + if char_end == ')' { + // We don't allow empty flags, e.g., `(?)`. We instead + // interpret it as a repetition operator missing its argument. + if flags.items.is_empty() { + return Err(self.error( + inner_span, + ast::ErrorKind::RepetitionMissing, + )); + } + Ok(Either::Left(ast::SetFlags { + span: Span { end: self.pos(), ..open_span }, + flags: flags, + })) + } else { + assert_eq!(char_end, ':'); + Ok(Either::Right(ast::Group { + span: open_span, + kind: ast::GroupKind::NonCapturing(flags), + ast: Box::new(Ast::Empty(self.span())), + })) + } + } else { + let capture_index = try!(self.next_capture_index(open_span)); + Ok(Either::Right(ast::Group { + span: open_span, + kind: ast::GroupKind::CaptureIndex(capture_index), + ast: Box::new(Ast::Empty(self.span())), + })) + } + } + + /// Parses a capture group name. Assumes that the parser is positioned at + /// the first character in the name following the opening `<` (and may + /// possibly be EOF). This advances the parser to the first character + /// following the closing `>`. + /// + /// The caller must provide the capture index of the group for this name. + fn parse_capture_name( + &self, + capture_index: u32, + ) -> Result<ast::CaptureName> { + if self.is_eof() { + return Err(self.error( + self.span(), + ast::ErrorKind::GroupNameUnexpectedEof, + )); + } + let start = self.pos(); + loop { + if self.char() == '>' { + break; + } + if !is_capture_char(self.char(), self.pos() == start) { + return Err(self.error( + self.span_char(), + ast::ErrorKind::GroupNameInvalid, + )); + } + if !self.bump() { + break; + } + } + let end = self.pos(); + if self.is_eof() { + return Err(self.error( + self.span(), + ast::ErrorKind::GroupNameUnexpectedEof, + )); + } + assert_eq!(self.char(), '>'); + self.bump(); + let name = &self.pattern()[start.offset..end.offset]; + if name.is_empty() { + return Err(self.error( + Span::new(start, start), + ast::ErrorKind::GroupNameEmpty, + )); + } + let capname = ast::CaptureName { + span: Span::new(start, end), + name: name.to_string(), + index: capture_index, + }; + try!(self.add_capture_name(&capname)); + Ok(capname) + } + + /// Parse a sequence of flags starting at the current character. + /// + /// This advances the parser to the character immediately following the + /// flags, which is guaranteed to be either `:` or `)`. + /// + /// # Errors + /// + /// If any flags are duplicated, then an error is returned. + /// + /// If the negation operator is used more than once, then an error is + /// returned. + /// + /// If no flags could be found or if the negation operation is not followed + /// by any flags, then an error is returned. + fn parse_flags(&self) -> Result<ast::Flags> { + let mut flags = ast::Flags { + span: self.span(), + items: vec![], + }; + let mut last_was_negation = None; + while self.char() != ':' && self.char() != ')' { + if self.char() == '-' { + last_was_negation = Some(self.span_char()); + let item = ast::FlagsItem { + span: self.span_char(), + kind: ast::FlagsItemKind::Negation, + }; + if let Some(i) = flags.add_item(item) { + return Err(self.error( + self.span_char(), + ast::ErrorKind::FlagRepeatedNegation { + original: flags.items[i].span, + }, + )); + } + } else { + last_was_negation = None; + let item = ast::FlagsItem { + span: self.span_char(), + kind: ast::FlagsItemKind::Flag(try!(self.parse_flag())), + }; + if let Some(i) = flags.add_item(item) { + return Err(self.error( + self.span_char(), + ast::ErrorKind::FlagDuplicate { + original: flags.items[i].span, + }, + )); + } + } + if !self.bump() { + return Err(self.error( + self.span(), + ast::ErrorKind::FlagUnexpectedEof, + )); + } + } + if let Some(span) = last_was_negation { + return Err(self.error(span, ast::ErrorKind::FlagDanglingNegation)); + } + flags.span.end = self.pos(); + Ok(flags) + } + + /// Parse the current character as a flag. Do not advance the parser. + /// + /// # Errors + /// + /// If the flag is not recognized, then an error is returned. + fn parse_flag(&self) -> Result<ast::Flag> { + match self.char() { + 'i' => Ok(ast::Flag::CaseInsensitive), + 'm' => Ok(ast::Flag::MultiLine), + 's' => Ok(ast::Flag::DotMatchesNewLine), + 'U' => Ok(ast::Flag::SwapGreed), + 'u' => Ok(ast::Flag::Unicode), + 'x' => Ok(ast::Flag::IgnoreWhitespace), + _ => Err(self.error( + self.span_char(), + ast::ErrorKind::FlagUnrecognized, + )), + } + } + + /// Parse a primitive AST. e.g., A literal, non-set character class or + /// assertion. + /// + /// This assumes that the parser expects a primitive at the current + /// location. i.e., All other non-primitive cases have been handled. + /// For example, if the parser's position is at `|`, then `|` will be + /// treated as a literal (e.g., inside a character class). + /// + /// This advances the parser to the first character immediately following + /// the primitive. + fn parse_primitive(&self) -> Result<Primitive> { + match self.char() { + '\\' => self.parse_escape(), + '.' => { + let ast = Primitive::Dot(self.span_char()); + self.bump(); + Ok(ast) + } + '^' => { + let ast = Primitive::Assertion(ast::Assertion { + span: self.span_char(), + kind: ast::AssertionKind::StartLine, + }); + self.bump(); + Ok(ast) + } + '$' => { + let ast = Primitive::Assertion(ast::Assertion { + span: self.span_char(), + kind: ast::AssertionKind::EndLine, + }); + self.bump(); + Ok(ast) + } + c => { + let ast = Primitive::Literal(ast::Literal { + span: self.span_char(), + kind: ast::LiteralKind::Verbatim, + c: c, + }); + self.bump(); + Ok(ast) + } + } + } + + /// Parse an escape sequence as a primitive AST. + /// + /// This assumes the parser is positioned at the start of the escape + /// sequence, i.e., `\`. It advances the parser to the first position + /// immediately following the escape sequence. + fn parse_escape(&self) -> Result<Primitive> { + assert_eq!(self.char(), '\\'); + let start = self.pos(); + if !self.bump() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::EscapeUnexpectedEof, + )); + } + let c = self.char(); + // Put some of the more complicated routines into helpers. + match c { + '0'...'7' => { + if !self.parser().octal { + return Err(self.error( + Span::new(start, self.span_char().end), + ast::ErrorKind::UnsupportedBackreference, + )); + } + let mut lit = self.parse_octal(); + lit.span.start = start; + return Ok(Primitive::Literal(lit)); + } + '8'...'9' if !self.parser().octal => { + return Err(self.error( + Span::new(start, self.span_char().end), + ast::ErrorKind::UnsupportedBackreference, + )); + } + 'x' | 'u' | 'U' => { + let mut lit = try!(self.parse_hex()); + lit.span.start = start; + return Ok(Primitive::Literal(lit)); + } + 'p' | 'P' => { + let mut cls = try!(self.parse_unicode_class()); + cls.span.start = start; + return Ok(Primitive::Unicode(cls)); + } + 'd' | 's' | 'w' | 'D' | 'S' | 'W' => { + let mut cls = self.parse_perl_class(); + cls.span.start = start; + return Ok(Primitive::Perl(cls)); + } + _ => {} + } + + // Handle all of the one letter sequences inline. + self.bump(); + let span = Span::new(start, self.pos()); + if is_meta_character(c) { + return Ok(Primitive::Literal(ast::Literal { + span: span, + kind: ast::LiteralKind::Punctuation, + c: c, + })); + } + let special = |kind, c| Ok(Primitive::Literal(ast::Literal { + span: span, + kind: ast::LiteralKind::Special(kind), + c: c, + })); + match c { + 'a' => special(ast::SpecialLiteralKind::Bell, '\x07'), + 'f' => special(ast::SpecialLiteralKind::FormFeed, '\x0C'), + 't' => special(ast::SpecialLiteralKind::Tab, '\t'), + 'n' => special(ast::SpecialLiteralKind::LineFeed, '\n'), + 'r' => special(ast::SpecialLiteralKind::CarriageReturn, '\r'), + 'v' => special(ast::SpecialLiteralKind::VerticalTab, '\x0B'), + ' ' if self.ignore_whitespace() => { + special(ast::SpecialLiteralKind::Space, ' ') + } + 'A' => Ok(Primitive::Assertion(ast::Assertion { + span: span, + kind: ast::AssertionKind::StartText, + })), + 'z' => Ok(Primitive::Assertion(ast::Assertion { + span: span, + kind: ast::AssertionKind::EndText, + })), + 'b' => Ok(Primitive::Assertion(ast::Assertion { + span: span, + kind: ast::AssertionKind::WordBoundary, + })), + 'B' => Ok(Primitive::Assertion(ast::Assertion { + span: span, + kind: ast::AssertionKind::NotWordBoundary, + })), + _ => Err(self.error(span, ast::ErrorKind::EscapeUnrecognized)), + } + } + + /// Parse an octal representation of a Unicode codepoint up to 3 digits + /// long. This expects the parser to be positioned at the first octal + /// digit and advances the parser to the first character immediately + /// following the octal number. This also assumes that parsing octal + /// escapes is enabled. + /// + /// Assuming the preconditions are met, this routine can never fail. + fn parse_octal(&self) -> ast::Literal { + use std::char; + use std::u32; + + assert!(self.parser().octal); + assert!('0' <= self.char() && self.char() <= '7'); + let start = self.pos(); + // Parse up to two more digits. + while + self.bump() && + '0' <= self.char() && self.char() <= '7' && + self.pos().offset - start.offset <= 2 + {} + let end = self.pos(); + let octal = &self.pattern()[start.offset..end.offset]; + // Parsing the octal should never fail since the above guarantees a + // valid number. + let codepoint = + u32::from_str_radix(octal, 8).expect("valid octal number"); + // The max value for 3 digit octal is 0777 = 511 and [0, 511] has no + // invalid Unicode scalar values. + let c = char::from_u32(codepoint).expect("Unicode scalar value"); + ast::Literal { + span: Span::new(start, end), + kind: ast::LiteralKind::Octal, + c: c, + } + } + + /// Parse a hex representation of a Unicode codepoint. This handles both + /// hex notations, i.e., `\xFF` and `\x{FFFF}`. This expects the parser to + /// be positioned at the `x`, `u` or `U` prefix. The parser is advanced to + /// the first character immediately following the hexadecimal literal. + fn parse_hex(&self) -> Result<ast::Literal> { + assert!(self.char() == 'x' + || self.char() == 'u' + || self.char() == 'U'); + + let hex_kind = match self.char() { + 'x' => ast::HexLiteralKind::X, + 'u' => ast::HexLiteralKind::UnicodeShort, + _ => ast::HexLiteralKind::UnicodeLong, + }; + if !self.bump_and_bump_space() { + return Err(self.error( + self.span(), + ast::ErrorKind::EscapeUnexpectedEof, + )); + } + if self.char() == '{' { + self.parse_hex_brace(hex_kind) + } else { + self.parse_hex_digits(hex_kind) + } + } + + /// Parse an N-digit hex representation of a Unicode codepoint. This + /// expects the parser to be positioned at the first digit and will advance + /// the parser to the first character immediately following the escape + /// sequence. + /// + /// The number of digits given must be 2 (for `\xNN`), 4 (for `\uNNNN`) + /// or 8 (for `\UNNNNNNNN`). + fn parse_hex_digits( + &self, + kind: ast::HexLiteralKind, + ) -> Result<ast::Literal> { + use std::char; + use std::u32; + + let mut scratch = self.parser().scratch.borrow_mut(); + scratch.clear(); + + let start = self.pos(); + for i in 0..kind.digits() { + if i > 0 && !self.bump_and_bump_space() { + return Err(self.error( + self.span(), + ast::ErrorKind::EscapeUnexpectedEof, + )); + } + if !is_hex(self.char()) { + return Err(self.error( + self.span_char(), + ast::ErrorKind::EscapeHexInvalidDigit, + )); + } + scratch.push(self.char()); + } + // The final bump just moves the parser past the literal, which may + // be EOF. + self.bump_and_bump_space(); + let end = self.pos(); + let hex = scratch.as_str(); + match u32::from_str_radix(hex, 16).ok().and_then(char::from_u32) { + None => Err(self.error( + Span::new(start, end), + ast::ErrorKind::EscapeHexInvalid, + )), + Some(c) => Ok(ast::Literal { + span: Span::new(start, end), + kind: ast::LiteralKind::HexFixed(kind), + c: c, + }), + } + } + + /// Parse a hex representation of any Unicode scalar value. This expects + /// the parser to be positioned at the opening brace `{` and will advance + /// the parser to the first character following the closing brace `}`. + fn parse_hex_brace( + &self, + kind: ast::HexLiteralKind, + ) -> Result<ast::Literal> { + use std::char; + use std::u32; + + let mut scratch = self.parser().scratch.borrow_mut(); + scratch.clear(); + + let brace_pos = self.pos(); + let start = self.span_char().end; + while self.bump_and_bump_space() && self.char() != '}' { + if !is_hex(self.char()) { + return Err(self.error( + self.span_char(), + ast::ErrorKind::EscapeHexInvalidDigit, + )); + } + scratch.push(self.char()); + } + if self.is_eof() { + return Err(self.error( + Span::new(brace_pos, self.pos()), + ast::ErrorKind::EscapeUnexpectedEof, + )); + } + let end = self.pos(); + let hex = scratch.as_str(); + assert_eq!(self.char(), '}'); + self.bump_and_bump_space(); + + if hex.is_empty() { + return Err(self.error( + Span::new(brace_pos, self.pos()), + ast::ErrorKind::EscapeHexEmpty, + )); + } + match u32::from_str_radix(hex, 16).ok().and_then(char::from_u32) { + None => Err(self.error( + Span::new(start, end), + ast::ErrorKind::EscapeHexInvalid, + )), + Some(c) => Ok(ast::Literal { + span: Span::new(start, self.pos()), + kind: ast::LiteralKind::HexBrace(kind), + c: c, + }), + } + } + + /// Parse a decimal number into a u32 while trimming leading and trailing + /// whitespace. + /// + /// This expects the parser to be positioned at the first position where + /// a decimal digit could occur. This will advance the parser to the byte + /// immediately following the last contiguous decimal digit. + /// + /// If no decimal digit could be found or if there was a problem parsing + /// the complete set of digits into a u32, then an error is returned. + fn parse_decimal(&self) -> Result<u32> { + let mut scratch = self.parser().scratch.borrow_mut(); + scratch.clear(); + + while !self.is_eof() && self.char().is_whitespace() { + self.bump(); + } + let start = self.pos(); + while !self.is_eof() && '0' <= self.char() && self.char() <= '9' { + scratch.push(self.char()); + self.bump_and_bump_space(); + } + let span = Span::new(start, self.pos()); + while !self.is_eof() && self.char().is_whitespace() { + self.bump_and_bump_space(); + } + let digits = scratch.as_str(); + if digits.is_empty() { + return Err(self.error(span, ast::ErrorKind::DecimalEmpty)); + } + match u32::from_str_radix(digits, 10).ok() { + Some(n) => Ok(n), + None => Err(self.error(span, ast::ErrorKind::DecimalInvalid)), + } + } + + /// Parse a standard character class consisting primarily of characters or + /// character ranges, but can also contain nested character classes of + /// any type (sans `.`). + /// + /// This assumes the parser is positioned at the opening `[`. If parsing + /// is successful, then the parser is advanced to the position immediately + /// following the closing `]`. + fn parse_set_class(&self) -> Result<ast::Class> { + assert_eq!(self.char(), '['); + + let mut union = ast::ClassSetUnion { + span: self.span(), + items: vec![], + }; + loop { + self.bump_space(); + if self.is_eof() { + return Err(self.unclosed_class_error()); + } + match self.char() { + '[' => { + // If we've already parsed the opening bracket, then + // attempt to treat this as the beginning of an ASCII + // class. If ASCII class parsing fails, then the parser + // backs up to `[`. + if !self.parser().stack_class.borrow().is_empty() { + if let Some(cls) = self.maybe_parse_ascii_class() { + union.push(ast::ClassSetItem::Ascii(cls)); + continue; + } + } + union = try!(self.push_class_open(union)); + } + ']' => { + match try!(self.pop_class(union)) { + Either::Left(nested_union) => { union = nested_union; } + Either::Right(class) => return Ok(class), + } + } + '&' if self.peek() == Some('&') => { + assert!(self.bump_if("&&")); + union = self.push_class_op( + ast::ClassSetBinaryOpKind::Intersection, union); + } + '-' if self.peek() == Some('-') => { + assert!(self.bump_if("--")); + union = self.push_class_op( + ast::ClassSetBinaryOpKind::Difference, union); + } + '~' if self.peek() == Some('~') => { + assert!(self.bump_if("~~")); + union = self.push_class_op( + ast::ClassSetBinaryOpKind::SymmetricDifference, union); + } + _ => { + union.push(try!(self.parse_set_class_range())); + } + } + } + } + + /// Parse a single primitive item in a character class set. The item to + /// be parsed can either be one of a simple literal character, a range + /// between two simple literal characters or a "primitive" character + /// class like \w or \p{Greek}. + /// + /// If an invalid escape is found, or if a character class is found where + /// a simple literal is expected (e.g., in a range), then an error is + /// returned. + fn parse_set_class_range(&self) -> Result<ast::ClassSetItem> { + let prim1 = try!(self.parse_set_class_item()); + self.bump_space(); + if self.is_eof() { + return Err(self.unclosed_class_error()); + } + // If the next char isn't a `-`, then we don't have a range. + // There are two exceptions. If the char after a `-` is a `]`, then + // `-` is interpreted as a literal `-`. Alternatively, if the char + // after a `-` is a `-`, then `--` corresponds to a "difference" + // operation. + if self.char() != '-' + || self.peek_space() == Some(']') + || self.peek_space() == Some('-') + { + return prim1.into_class_set_item(self); + } + // OK, now we're parsing a range, so bump past the `-` and parse the + // second half of the range. + if !self.bump_and_bump_space() { + return Err(self.unclosed_class_error()); + } + let prim2 = try!(self.parse_set_class_item()); + let range = ast::ClassSetRange { + span: Span::new(prim1.span().start, prim2.span().end), + start: try!(prim1.into_class_literal(self)), + end: try!(prim2.into_class_literal(self)), + }; + if !range.is_valid() { + return Err(self.error( + range.span, + ast::ErrorKind::ClassRangeInvalid, + )); + } + Ok(ast::ClassSetItem::Range(range)) + } + + /// Parse a single item in a character class as a primitive, where the + /// primitive either consists of a verbatim literal or a single escape + /// sequence. + /// + /// This assumes the parser is positioned at the beginning of a primitive, + /// and advances the parser to the first position after the primitive if + /// successful. + /// + /// Note that it is the caller's responsibility to report an error if an + /// illegal primitive was parsed. + fn parse_set_class_item(&self) -> Result<Primitive> { + if self.char() == '\\' { + self.parse_escape() + } else { + let x = Primitive::Literal(ast::Literal { + span: self.span_char(), + kind: ast::LiteralKind::Verbatim, + c: self.char(), + }); + self.bump(); + Ok(x) + } + } + + /// Parses the opening of a character class set. This includes the opening + /// bracket along with `^` if present to indicate negation. This also + /// starts parsing the opening set of unioned items if applicable, since + /// there are special rules applied to certain characters in the opening + /// of a character class. For example, `[^]]` is the class of all + /// characters not equal to `]`. (`]` would need to be escaped in any other + /// position.) Similarly for `-`. + /// + /// In all cases, the op inside the returned `ast::ClassBracketed` is an + /// empty union. This empty union should be replaced with the actual item + /// when it is popped from the parser's stack. + /// + /// This assumes the parser is positioned at the opening `[` and advances + /// the parser to the first non-special byte of the character class. + /// + /// An error is returned if EOF is found. + fn parse_set_class_open( + &self, + ) -> Result<(ast::ClassBracketed, ast::ClassSetUnion)> { + assert_eq!(self.char(), '['); + let start = self.pos(); + if !self.bump_and_bump_space() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::ClassUnclosed, + )); + } + + let negated = + if self.char() != '^' { + false + } else { + if !self.bump_and_bump_space() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::ClassUnclosed, + )); + } + true + }; + // Accept any number of `-` as literal `-`. + let mut union = ast::ClassSetUnion { + span: self.span(), + items: vec![], + }; + while self.char() == '-' { + union.push(ast::ClassSetItem::Literal(ast::Literal { + span: self.span_char(), + kind: ast::LiteralKind::Verbatim, + c: '-', + })); + if !self.bump_and_bump_space() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::ClassUnclosed, + )); + } + } + // If `]` is the *first* char in a set, then interpret it as a literal + // `]`. That is, an empty class is impossible to write. + if union.items.is_empty() && self.char() == ']' { + union.push(ast::ClassSetItem::Literal(ast::Literal { + span: self.span_char(), + kind: ast::LiteralKind::Verbatim, + c: ']', + })); + if !self.bump_and_bump_space() { + return Err(self.error( + Span::new(start, self.pos()), + ast::ErrorKind::ClassUnclosed, + )); + } + } + let set = ast::ClassBracketed { + span: Span::new(start, self.pos()), + negated: negated, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: Span::new(union.span.start, union.span.start), + items: vec![], + }), + }; + Ok((set, union)) + } + + /// Attempt to parse an ASCII character class, e.g., `[:alnum:]`. + /// + /// This assumes the parser is positioned at the opening `[`. + /// + /// If no valid ASCII character class could be found, then this does not + /// advance the parser and `None` is returned. Otherwise, the parser is + /// advanced to the first byte following the closing `]` and the + /// corresponding ASCII class is returned. + fn maybe_parse_ascii_class(&self) -> Option<ast::ClassAscii> { + // ASCII character classes are interesting from a parsing perspective + // because parsing cannot fail with any interesting error. For example, + // in order to use an ASCII character class, it must be enclosed in + // double brackets, e.g., `[[:alnum:]]`. Alternatively, you might think + // of it as "ASCII character characters have the syntax `[:NAME:]` + // which can only appear within character brackets." This means that + // things like `[[:lower:]A]` are legal constructs. + // + // However, if one types an incorrect ASCII character class, e.g., + // `[[:loower:]]`, then we treat that as a normal nested character + // class containing the characters `:elorw`. One might argue that we + // should return an error instead since the repeated colons give away + // the intent to write an ASCII class. But what if the user typed + // `[[:lower]]` instead? How can we tell that was intended to be an + // ASCII class and not just a normal nested class? + // + // Reasonable people can probably disagree over this, but for better + // or worse, we implement semantics that never fails at the expense + // of better failure modes. + assert_eq!(self.char(), '['); + // If parsing fails, then we back up the parser to this starting point. + let start = self.pos(); + let mut negated = false; + if !self.bump() || self.char() != ':' { + self.parser().pos.set(start); + return None; + } + if !self.bump() { + self.parser().pos.set(start); + return None; + } + if self.char() == '^' { + negated = true; + if !self.bump() { + self.parser().pos.set(start); + return None; + } + } + let name_start = self.offset(); + while self.char() != ':' && self.bump() {} + if self.is_eof() { + self.parser().pos.set(start); + return None; + } + let name = &self.pattern()[name_start..self.offset()]; + if !self.bump_if(":]") { + self.parser().pos.set(start); + return None; + } + let kind = match ast::ClassAsciiKind::from_name(name) { + Some(kind) => kind, + None => { + self.parser().pos.set(start); + return None; + } + }; + Some(ast::ClassAscii { + span: Span::new(start, self.pos()), + kind: kind, + negated: negated, + }) + } + + /// Parse a Unicode class in either the single character notation, `\pN` + /// or the multi-character bracketed notation, `\p{Greek}`. This assumes + /// the parser is positioned at the `p` (or `P` for negation) and will + /// advance the parser to the character immediately following the class. + /// + /// Note that this does not check whether the class name is valid or not. + fn parse_unicode_class(&self) -> Result<ast::ClassUnicode> { + assert!(self.char() == 'p' || self.char() == 'P'); + + let mut scratch = self.parser().scratch.borrow_mut(); + scratch.clear(); + + let negated = self.char() == 'P'; + if !self.bump_and_bump_space() { + return Err(self.error( + self.span(), + ast::ErrorKind::EscapeUnexpectedEof, + )); + } + let (start, kind) = + if self.char() == '{' { + let start = self.span_char().end; + while self.bump_and_bump_space() && self.char() != '}' { + scratch.push(self.char()); + } + if self.is_eof() { + return Err(self.error( + self.span(), + ast::ErrorKind::EscapeUnexpectedEof, + )); + } + assert_eq!(self.char(), '}'); + self.bump(); + + let name = scratch.as_str(); + if let Some(i) = name.find("!=") { + (start, ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::NotEqual, + name: name[..i].to_string(), + value: name[i+2..].to_string(), + }) + } else if let Some(i) = name.find(':') { + (start, ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::Colon, + name: name[..i].to_string(), + value: name[i+1..].to_string(), + }) + } else if let Some(i) = name.find('=') { + (start, ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::Equal, + name: name[..i].to_string(), + value: name[i+1..].to_string(), + }) + } else { + (start, ast::ClassUnicodeKind::Named(name.to_string())) + } + } else { + let start = self.pos(); + let c = self.char(); + self.bump_and_bump_space(); + let kind = ast::ClassUnicodeKind::OneLetter(c); + (start, kind) + }; + Ok(ast::ClassUnicode { + span: Span::new(start, self.pos()), + negated: negated, + kind: kind, + }) + } + + /// Parse a Perl character class, e.g., `\d` or `\W`. This assumes the + /// parser is currently at a valid character class name and will be + /// advanced to the character immediately following the class. + fn parse_perl_class(&self) -> ast::ClassPerl { + let c = self.char(); + let span = self.span_char(); + self.bump(); + let (negated, kind) = match c { + 'd' => (false, ast::ClassPerlKind::Digit), + 'D' => (true, ast::ClassPerlKind::Digit), + 's' => (false, ast::ClassPerlKind::Space), + 'S' => (true, ast::ClassPerlKind::Space), + 'w' => (false, ast::ClassPerlKind::Word), + 'W' => (true, ast::ClassPerlKind::Word), + c => panic!("expected valid Perl class but got '{}'", c), + }; + ast::ClassPerl { span: span, kind: kind, negated: negated } + } +} + +/// A type that traverses a fully parsed Ast and checks whether its depth +/// exceeds the specified nesting limit. If it does, then an error is returned. +#[derive(Debug)] +struct NestLimiter<'p, 's: 'p, P: 'p + 's> { + /// The parser that is checking the nest limit. + p: &'p ParserI<'s, P>, + /// The current depth while walking an Ast. + depth: u32, +} + +impl<'p, 's, P: Borrow<Parser>> NestLimiter<'p, 's, P> { + fn new(p: &'p ParserI<'s, P>) -> NestLimiter<'p, 's, P> { + NestLimiter { p: p, depth: 0 } + } + + fn check(self, ast: &Ast) -> Result<()> { + ast::visit(ast, self) + } + + fn increment_depth(&mut self, span: &Span) -> Result<()> { + let new = try!(self.depth.checked_add(1).ok_or_else(|| self.p.error( + span.clone(), + ast::ErrorKind::NestLimitExceeded(::std::u32::MAX), + ))); + let limit = self.p.parser().nest_limit; + if new > limit { + return Err(self.p.error( + span.clone(), + ast::ErrorKind::NestLimitExceeded(limit), + )); + } + self.depth = new; + Ok(()) + } + + fn decrement_depth(&mut self) { + // Assuming the correctness of the visitor, this should never drop + // below 0. + self.depth = self.depth.checked_sub(1).unwrap(); + } +} + +impl<'p, 's, P: Borrow<Parser>> ast::Visitor for NestLimiter<'p, 's, P> { + type Output = (); + type Err = ast::Error; + + fn finish(self) -> Result<()> { + Ok(()) + } + + fn visit_pre(&mut self, ast: &Ast) -> Result<()> { + let span = match *ast { + Ast::Empty(_) + | Ast::Flags(_) + | Ast::Literal(_) + | Ast::Dot(_) + | Ast::Assertion(_) + | Ast::Class(ast::Class::Unicode(_)) + | Ast::Class(ast::Class::Perl(_)) => { + // These are all base cases, so we don't increment depth. + return Ok(()); + } + Ast::Class(ast::Class::Bracketed(ref x)) => &x.span, + Ast::Repetition(ref x) => &x.span, + Ast::Group(ref x) => &x.span, + Ast::Alternation(ref x) => &x.span, + Ast::Concat(ref x) => &x.span, + }; + self.increment_depth(span) + } + + fn visit_post(&mut self, ast: &Ast) -> Result<()> { + match *ast { + Ast::Empty(_) + | Ast::Flags(_) + | Ast::Literal(_) + | Ast::Dot(_) + | Ast::Assertion(_) + | Ast::Class(ast::Class::Unicode(_)) + | Ast::Class(ast::Class::Perl(_)) => { + // These are all base cases, so we don't decrement depth. + Ok(()) + } + Ast::Class(ast::Class::Bracketed(_)) + | Ast::Repetition(_) + | Ast::Group(_) + | Ast::Alternation(_) + | Ast::Concat(_) => { + self.decrement_depth(); + Ok(()) + } + } + } + + fn visit_class_set_item_pre( + &mut self, + ast: &ast::ClassSetItem, + ) -> Result<()> { + let span = match *ast { + ast::ClassSetItem::Empty(_) + | ast::ClassSetItem::Literal(_) + | ast::ClassSetItem::Range(_) + | ast::ClassSetItem::Ascii(_) + | ast::ClassSetItem::Unicode(_) + | ast::ClassSetItem::Perl(_) => { + // These are all base cases, so we don't increment depth. + return Ok(()); + } + ast::ClassSetItem::Bracketed(ref x) => &x.span, + ast::ClassSetItem::Union(ref x) => &x.span, + }; + self.increment_depth(span) + } + + fn visit_class_set_item_post( + &mut self, + ast: &ast::ClassSetItem, + ) -> Result<()> { + match *ast { + ast::ClassSetItem::Empty(_) + | ast::ClassSetItem::Literal(_) + | ast::ClassSetItem::Range(_) + | ast::ClassSetItem::Ascii(_) + | ast::ClassSetItem::Unicode(_) + | ast::ClassSetItem::Perl(_) => { + // These are all base cases, so we don't decrement depth. + Ok(()) + } + ast::ClassSetItem::Bracketed(_) + | ast::ClassSetItem::Union(_) => { + self.decrement_depth(); + Ok(()) + } + } + } + + fn visit_class_set_binary_op_pre( + &mut self, + ast: &ast::ClassSetBinaryOp, + ) -> Result<()> { + self.increment_depth(&ast.span) + } + + fn visit_class_set_binary_op_post( + &mut self, + _ast: &ast::ClassSetBinaryOp, + ) -> Result<()> { + self.decrement_depth(); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use std::ops::Range; + + use ast::{self, Ast, Position, Span}; + use super::{Parser, ParserI, ParserBuilder, Primitive}; + + // Our own assert_eq, which has slightly better formatting (but honestly + // still kind of crappy). + macro_rules! assert_eq { + ($left:expr, $right:expr) => ({ + match (&$left, &$right) { + (left_val, right_val) => { + if !(*left_val == *right_val) { + panic!("assertion failed: `(left == right)`\n\n\ + left: `{:?}`\nright: `{:?}`\n\n", + left_val, right_val) + } + } + } + }); + } + + // We create these errors to compare with real ast::Errors in the tests. + // We define equality between TestError and ast::Error to disregard the + // pattern string in ast::Error, which is annoying to provide in tests. + #[derive(Clone, Debug)] + struct TestError { + span: Span, + kind: ast::ErrorKind, + } + + impl PartialEq<ast::Error> for TestError { + fn eq(&self, other: &ast::Error) -> bool { + self.span == other.span && self.kind == other.kind + } + } + + impl PartialEq<TestError> for ast::Error { + fn eq(&self, other: &TestError) -> bool { + self.span == other.span && self.kind == other.kind + } + } + + fn s(str: &str) -> String { + str.to_string() + } + + fn parser(pattern: &str) -> ParserI<Parser> { + ParserI::new(Parser::new(), pattern) + } + + fn parser_octal(pattern: &str) -> ParserI<Parser> { + let parser = ParserBuilder::new().octal(true).build(); + ParserI::new(parser, pattern) + } + + fn parser_nest_limit(pattern: &str, nest_limit: u32) -> ParserI<Parser> { + let p = ParserBuilder::new().nest_limit(nest_limit).build(); + ParserI::new(p, pattern) + } + + fn parser_ignore_whitespace(pattern: &str) -> ParserI<Parser> { + let p = ParserBuilder::new().ignore_whitespace(true).build(); + ParserI::new(p, pattern) + } + + /// Short alias for creating a new span. + fn nspan(start: Position, end: Position) -> Span { + Span::new(start, end) + } + + /// Short alias for creating a new position. + fn npos(offset: usize, line: usize, column: usize) -> Position { + Position::new(offset, line, column) + } + + /// Create a new span from the given offset range. This assumes a single + /// line and sets the columns based on the offsets. i.e., This only works + /// out of the box for ASCII, which is fine for most tests. + fn span(range: Range<usize>) -> Span { + let start = Position::new(range.start, 1, range.start + 1); + let end = Position::new(range.end, 1, range.end + 1); + Span::new(start, end) + } + + /// Create a new span for the corresponding byte range in the given string. + fn span_range(subject: &str, range: Range<usize>) -> Span { + let start = Position { + offset: range.start, + line: 1 + subject[..range.start].matches('\n').count(), + column: 1 + subject[..range.start] + .chars() + .rev() + .position(|c| c == '\n') + .unwrap_or(subject[..range.start].chars().count()), + }; + let end = Position { + offset: range.end, + line: 1 + subject[..range.end].matches('\n').count(), + column: 1 + subject[..range.end] + .chars() + .rev() + .position(|c| c == '\n') + .unwrap_or(subject[..range.end].chars().count()), + }; + Span::new(start, end) + } + + /// Create a verbatim literal starting at the given position. + fn lit(c: char, start: usize) -> Ast { + lit_with(c, span(start..start + c.len_utf8())) + } + + /// Create a punctuation literal starting at the given position. + fn punct_lit(c: char, span: Span) -> Ast { + Ast::Literal(ast::Literal { + span: span, + kind: ast::LiteralKind::Punctuation, + c: c, + }) + } + + /// Create a verbatim literal with the given span. + fn lit_with(c: char, span: Span) -> Ast { + Ast::Literal(ast::Literal { + span: span, + kind: ast::LiteralKind::Verbatim, + c: c, + }) + } + + /// Create a concatenation with the given range. + fn concat(range: Range<usize>, asts: Vec<Ast>) -> Ast { + concat_with(span(range), asts) + } + + /// Create a concatenation with the given span. + fn concat_with(span: Span, asts: Vec<Ast>) -> Ast { + Ast::Concat(ast::Concat { span: span, asts: asts }) + } + + /// Create an alternation with the given span. + fn alt(range: Range<usize>, asts: Vec<Ast>) -> Ast { + Ast::Alternation(ast::Alternation { span: span(range), asts: asts }) + } + + /// Create a capturing group with the given span. + fn group(range: Range<usize>, index: u32, ast: Ast) -> Ast { + Ast::Group(ast::Group { + span: span(range), + kind: ast::GroupKind::CaptureIndex(index), + ast: Box::new(ast), + }) + } + + /// Create an ast::SetFlags. + /// + /// The given pattern should be the full pattern string. The range given + /// should correspond to the byte offsets where the flag set occurs. + /// + /// If negated is true, then the set is interpreted as beginning with a + /// negation. + fn flag_set( + pat: &str, + range: Range<usize>, + flag: ast::Flag, + negated: bool, + ) -> Ast { + let mut items = vec![ + ast::FlagsItem { + span: span_range(pat, (range.end - 2)..(range.end - 1)), + kind: ast::FlagsItemKind::Flag(flag), + }, + ]; + if negated { + items.insert(0, ast::FlagsItem { + span: span_range(pat, (range.start + 2)..(range.end - 2)), + kind: ast::FlagsItemKind::Negation, + }); + } + Ast::Flags(ast::SetFlags { + span: span_range(pat, range.clone()), + flags: ast::Flags { + span: span_range(pat, (range.start + 2)..(range.end - 1)), + items: items, + }, + }) + } + + #[test] + fn parse_nest_limit() { + // A nest limit of 0 still allows some types of regexes. + assert_eq!( + parser_nest_limit("", 0).parse(), + Ok(Ast::Empty(span(0..0)))); + assert_eq!( + parser_nest_limit("a", 0).parse(), + Ok(lit('a', 0))); + + // Test repetition operations, which require one level of nesting. + assert_eq!( + parser_nest_limit("a+", 0).parse().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::NestLimitExceeded(0), + }); + assert_eq!( + parser_nest_limit("a+", 1).parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::OneOrMore, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser_nest_limit("(a)+", 1).parse().unwrap_err(), + TestError { + span: span(0..3), + kind: ast::ErrorKind::NestLimitExceeded(1), + }); + assert_eq!( + parser_nest_limit("a+*", 1).parse().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::NestLimitExceeded(1), + }); + assert_eq!( + parser_nest_limit("a+*", 2).parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..3), + op: ast::RepetitionOp { + span: span(2..3), + kind: ast::RepetitionKind::ZeroOrMore, + }, + greedy: true, + ast: Box::new(Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::OneOrMore, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + })), + }))); + + // Test concatenations. A concatenation requires one level of nesting. + assert_eq!( + parser_nest_limit("ab", 0).parse().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::NestLimitExceeded(0), + }); + assert_eq!( + parser_nest_limit("ab", 1).parse(), + Ok(concat(0..2, vec![lit('a', 0), lit('b', 1)]))); + assert_eq!( + parser_nest_limit("abc", 1).parse(), + Ok(concat(0..3, vec![lit('a', 0), lit('b', 1), lit('c', 2)]))); + + // Test alternations. An alternation requires one level of nesting. + assert_eq!( + parser_nest_limit("a|b", 0).parse().unwrap_err(), + TestError { + span: span(0..3), + kind: ast::ErrorKind::NestLimitExceeded(0), + }); + assert_eq!( + parser_nest_limit("a|b", 1).parse(), + Ok(alt(0..3, vec![lit('a', 0), lit('b', 2)]))); + assert_eq!( + parser_nest_limit("a|b|c", 1).parse(), + Ok(alt(0..5, vec![lit('a', 0), lit('b', 2), lit('c', 4)]))); + + // Test character classes. Classes form their own mini-recursive + // syntax! + assert_eq!( + parser_nest_limit("[a]", 0).parse().unwrap_err(), + TestError { + span: span(0..3), + kind: ast::ErrorKind::NestLimitExceeded(0), + }); + assert_eq!( + parser_nest_limit("[a]", 1).parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..3), + negated: false, + kind: ast::ClassSet::Item( + ast::ClassSetItem::Literal(ast::Literal { + span: span(1..2), + kind: ast::LiteralKind::Verbatim, + c: 'a', + }) + ), + })))); + assert_eq!( + parser_nest_limit("[ab]", 1).parse().unwrap_err(), + TestError { + span: span(1..3), + kind: ast::ErrorKind::NestLimitExceeded(1), + }); + assert_eq!( + parser_nest_limit("[ab[cd]]", 2).parse().unwrap_err(), + TestError { + span: span(3..7), + kind: ast::ErrorKind::NestLimitExceeded(2), + }); + assert_eq!( + parser_nest_limit("[ab[cd]]", 3).parse().unwrap_err(), + TestError { + span: span(4..6), + kind: ast::ErrorKind::NestLimitExceeded(3), + }); + assert_eq!( + parser_nest_limit("[a--b]", 1).parse().unwrap_err(), + TestError { + span: span(1..5), + kind: ast::ErrorKind::NestLimitExceeded(1), + }); + assert_eq!( + parser_nest_limit("[a--bc]", 2).parse().unwrap_err(), + TestError { + span: span(4..6), + kind: ast::ErrorKind::NestLimitExceeded(2), + }); + } + + #[test] + fn parse_comments() { + let pat = "(?x) +# This is comment 1. +foo # This is comment 2. + # This is comment 3. +bar +# This is comment 4."; + let astc = parser(pat).parse_with_comments().unwrap(); + assert_eq!( + astc.ast, + concat_with(span_range(pat, 0..pat.len()), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + lit_with('f', span_range(pat, 26..27)), + lit_with('o', span_range(pat, 27..28)), + lit_with('o', span_range(pat, 28..29)), + lit_with('b', span_range(pat, 74..75)), + lit_with('a', span_range(pat, 75..76)), + lit_with('r', span_range(pat, 76..77)), + ])); + assert_eq!(astc.comments, vec![ + ast::Comment { + span: span_range(pat, 5..26), + comment: s(" This is comment 1."), + }, + ast::Comment { + span: span_range(pat, 30..51), + comment: s(" This is comment 2."), + }, + ast::Comment { + span: span_range(pat, 53..74), + comment: s(" This is comment 3."), + }, + ast::Comment { + span: span_range(pat, 78..98), + comment: s(" This is comment 4."), + }, + ]); + } + + #[test] + fn parse_holistic() { + assert_eq!( + parser("]").parse(), + Ok(lit(']', 0))); + assert_eq!( + parser(r"\\\.\+\*\?\(\)\|\[\]\{\}\^\$\#\&\-\~").parse(), + Ok(concat(0..36, vec![ + punct_lit('\\', span(0..2)), + punct_lit('.', span(2..4)), + punct_lit('+', span(4..6)), + punct_lit('*', span(6..8)), + punct_lit('?', span(8..10)), + punct_lit('(', span(10..12)), + punct_lit(')', span(12..14)), + punct_lit('|', span(14..16)), + punct_lit('[', span(16..18)), + punct_lit(']', span(18..20)), + punct_lit('{', span(20..22)), + punct_lit('}', span(22..24)), + punct_lit('^', span(24..26)), + punct_lit('$', span(26..28)), + punct_lit('#', span(28..30)), + punct_lit('&', span(30..32)), + punct_lit('-', span(32..34)), + punct_lit('~', span(34..36)), + ]))); + } + + #[test] + fn parse_ignore_whitespace() { + // Test that basic whitespace insensitivity works. + let pat = "(?x)a b"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(nspan(npos(0, 1, 1), npos(7, 1, 8)), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + lit_with('a', nspan(npos(4, 1, 5), npos(5, 1, 6))), + lit_with('b', nspan(npos(6, 1, 7), npos(7, 1, 8))), + ]))); + + // Test that we can toggle whitespace insensitivity. + let pat = "(?x)a b(?-x)a b"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(nspan(npos(0, 1, 1), npos(15, 1, 16)), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + lit_with('a', nspan(npos(4, 1, 5), npos(5, 1, 6))), + lit_with('b', nspan(npos(6, 1, 7), npos(7, 1, 8))), + flag_set(pat, 7..12, ast::Flag::IgnoreWhitespace, true), + lit_with('a', nspan(npos(12, 1, 13), npos(13, 1, 14))), + lit_with(' ', nspan(npos(13, 1, 14), npos(14, 1, 15))), + lit_with('b', nspan(npos(14, 1, 15), npos(15, 1, 16))), + ]))); + + // Test that nesting whitespace insensitive flags works. + let pat = "a (?x:a )a "; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..11), vec![ + lit_with('a', span_range(pat, 0..1)), + lit_with(' ', span_range(pat, 1..2)), + Ast::Group(ast::Group { + span: span_range(pat, 2..9), + kind: ast::GroupKind::NonCapturing(ast::Flags { + span: span_range(pat, 4..5), + items: vec![ + ast::FlagsItem { + span: span_range(pat, 4..5), + kind: ast::FlagsItemKind::Flag( + ast::Flag::IgnoreWhitespace), + }, + ], + }), + ast: Box::new(lit_with('a', span_range(pat, 6..7))), + }), + lit_with('a', span_range(pat, 9..10)), + lit_with(' ', span_range(pat, 10..11)), + ]))); + + // Test that whitespace after an opening paren is insignificant. + let pat = "(?x)( ?P<foo> a )"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..pat.len()), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + Ast::Group(ast::Group { + span: span_range(pat, 4..pat.len()), + kind: ast::GroupKind::CaptureName(ast::CaptureName { + span: span_range(pat, 9..12), + name: s("foo"), + index: 1, + }), + ast: Box::new(lit_with('a', span_range(pat, 14..15))), + }), + ]))); + let pat = "(?x)( a )"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..pat.len()), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + Ast::Group(ast::Group { + span: span_range(pat, 4..pat.len()), + kind: ast::GroupKind::CaptureIndex(1), + ast: Box::new(lit_with('a', span_range(pat, 7..8))), + }), + ]))); + let pat = "(?x)( ?: a )"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..pat.len()), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + Ast::Group(ast::Group { + span: span_range(pat, 4..pat.len()), + kind: ast::GroupKind::NonCapturing(ast::Flags { + span: span_range(pat, 8..8), + items: vec![], + }), + ast: Box::new(lit_with('a', span_range(pat, 11..12))), + }), + ]))); + let pat = r"(?x)\x { 53 }"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..pat.len()), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + Ast::Literal(ast::Literal { + span: span(4..13), + kind: ast::LiteralKind::HexBrace(ast::HexLiteralKind::X), + c: 'S', + }), + ]))); + + // Test that whitespace after an escape is OK. + let pat = r"(?x)\ "; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..pat.len()), vec![ + flag_set(pat, 0..4, ast::Flag::IgnoreWhitespace, false), + Ast::Literal(ast::Literal { + span: span_range(pat, 4..6), + kind: ast::LiteralKind::Special( + ast::SpecialLiteralKind::Space), + c: ' ', + }), + ]))); + // ... but only when `x` mode is enabled. + let pat = r"\ "; + assert_eq!( + parser(pat).parse().unwrap_err(), + TestError { + span: span_range(pat, 0..2), + kind: ast::ErrorKind::EscapeUnrecognized, + }); + } + + #[test] + fn parse_newlines() { + let pat = ".\n."; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..3), vec![ + Ast::Dot(span_range(pat, 0..1)), + lit_with('\n', span_range(pat, 1..2)), + Ast::Dot(span_range(pat, 2..3)), + ]))); + + let pat = "foobar\nbaz\nquux\n"; + assert_eq!( + parser(pat).parse(), + Ok(concat_with(span_range(pat, 0..pat.len()), vec![ + lit_with('f', nspan(npos(0, 1, 1), npos(1, 1, 2))), + lit_with('o', nspan(npos(1, 1, 2), npos(2, 1, 3))), + lit_with('o', nspan(npos(2, 1, 3), npos(3, 1, 4))), + lit_with('b', nspan(npos(3, 1, 4), npos(4, 1, 5))), + lit_with('a', nspan(npos(4, 1, 5), npos(5, 1, 6))), + lit_with('r', nspan(npos(5, 1, 6), npos(6, 1, 7))), + lit_with('\n', nspan(npos(6, 1, 7), npos(7, 2, 1))), + lit_with('b', nspan(npos(7, 2, 1), npos(8, 2, 2))), + lit_with('a', nspan(npos(8, 2, 2), npos(9, 2, 3))), + lit_with('z', nspan(npos(9, 2, 3), npos(10, 2, 4))), + lit_with('\n', nspan(npos(10, 2, 4), npos(11, 3, 1))), + lit_with('q', nspan(npos(11, 3, 1), npos(12, 3, 2))), + lit_with('u', nspan(npos(12, 3, 2), npos(13, 3, 3))), + lit_with('u', nspan(npos(13, 3, 3), npos(14, 3, 4))), + lit_with('x', nspan(npos(14, 3, 4), npos(15, 3, 5))), + lit_with('\n', nspan(npos(15, 3, 5), npos(16, 4, 1))), + ]))); + } + + #[test] + fn parse_uncounted_repetition() { + assert_eq!( + parser(r"a*").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::ZeroOrMore, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a+").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::OneOrMore, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + + assert_eq!( + parser(r"a?").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a??").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..3), + op: ast::RepetitionOp { + span: span(1..3), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: false, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a?").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a?b").parse(), + Ok(concat(0..3, vec![ + Ast::Repetition(ast::Repetition { + span: span(0..2), + op: ast::RepetitionOp { + span: span(1..2), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }), + lit('b', 2), + ]))); + assert_eq!( + parser(r"a??b").parse(), + Ok(concat(0..4, vec![ + Ast::Repetition(ast::Repetition { + span: span(0..3), + op: ast::RepetitionOp { + span: span(1..3), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: false, + ast: Box::new(lit('a', 0)), + }), + lit('b', 3), + ]))); + assert_eq!( + parser(r"ab?").parse(), + Ok(concat(0..3, vec![ + lit('a', 0), + Ast::Repetition(ast::Repetition { + span: span(1..3), + op: ast::RepetitionOp { + span: span(2..3), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: true, + ast: Box::new(lit('b', 1)), + }), + ]))); + assert_eq!( + parser(r"(ab)?").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..5), + op: ast::RepetitionOp { + span: span(4..5), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: true, + ast: Box::new(group(0..4, 1, concat(1..3, vec![ + lit('a', 1), + lit('b', 2), + ]))), + }))); + assert_eq!( + parser(r"|a?").parse(), + Ok(alt(0..3, vec![ + Ast::Empty(span(0..0)), + Ast::Repetition(ast::Repetition { + span: span(1..3), + op: ast::RepetitionOp { + span: span(2..3), + kind: ast::RepetitionKind::ZeroOrOne, + }, + greedy: true, + ast: Box::new(lit('a', 1)), + }), + ]))); + + assert_eq!( + parser(r"*").parse().unwrap_err(), + TestError { + span: span(0..0), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"(*)").parse().unwrap_err(), + TestError { + span: span(1..1), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"(?:?)").parse().unwrap_err(), + TestError { + span: span(3..3), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"+").parse().unwrap_err(), + TestError { + span: span(0..0), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"?").parse().unwrap_err(), + TestError { + span: span(0..0), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"(?)").parse().unwrap_err(), + TestError { + span: span(1..1), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"|*").parse().unwrap_err(), + TestError { + span: span(1..1), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"|+").parse().unwrap_err(), + TestError { + span: span(1..1), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"|?").parse().unwrap_err(), + TestError { + span: span(1..1), + kind: ast::ErrorKind::RepetitionMissing, + }); + } + + #[test] + fn parse_counted_repetition() { + assert_eq!( + parser(r"a{5}").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..4), + op: ast::RepetitionOp { + span: span(1..4), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Exactly(5)), + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a{5,}").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..5), + op: ast::RepetitionOp { + span: span(1..5), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::AtLeast(5)), + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a{5,9}").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..6), + op: ast::RepetitionOp { + span: span(1..6), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Bounded(5, 9)), + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a{5}?").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..5), + op: ast::RepetitionOp { + span: span(1..5), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Exactly(5)), + }, + greedy: false, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"ab{5}").parse(), + Ok(concat(0..5, vec![ + lit('a', 0), + Ast::Repetition(ast::Repetition { + span: span(1..5), + op: ast::RepetitionOp { + span: span(2..5), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Exactly(5)), + }, + greedy: true, + ast: Box::new(lit('b', 1)), + }), + ]))); + assert_eq!( + parser(r"ab{5}c").parse(), + Ok(concat(0..6, vec![ + lit('a', 0), + Ast::Repetition(ast::Repetition { + span: span(1..5), + op: ast::RepetitionOp { + span: span(2..5), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Exactly(5)), + }, + greedy: true, + ast: Box::new(lit('b', 1)), + }), + lit('c', 5), + ]))); + + assert_eq!( + parser(r"a{ 5 }").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..6), + op: ast::RepetitionOp { + span: span(1..6), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Exactly(5)), + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser(r"a{ 5 , 9 }").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..10), + op: ast::RepetitionOp { + span: span(1..10), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Bounded(5, 9)), + }, + greedy: true, + ast: Box::new(lit('a', 0)), + }))); + assert_eq!( + parser_ignore_whitespace(r"a{5,9} ?").parse(), + Ok(Ast::Repetition(ast::Repetition { + span: span(0..8), + op: ast::RepetitionOp { + span: span(1..8), + kind: ast::RepetitionKind::Range( + ast::RepetitionRange::Bounded(5, 9)), + }, + greedy: false, + ast: Box::new(lit('a', 0)), + }))); + + assert_eq!( + parser(r"a{").parse().unwrap_err(), + TestError { + span: span(1..2), + kind: ast::ErrorKind::RepetitionCountUnclosed, + }); + assert_eq!( + parser(r"a{}").parse().unwrap_err(), + TestError { + span: span(2..2), + kind: ast::ErrorKind::DecimalEmpty, + }); + assert_eq!( + parser(r"a{a").parse().unwrap_err(), + TestError { + span: span(2..2), + kind: ast::ErrorKind::DecimalEmpty, + }); + assert_eq!( + parser(r"a{9999999999}").parse().unwrap_err(), + TestError { + span: span(2..12), + kind: ast::ErrorKind::DecimalInvalid, + }); + assert_eq!( + parser(r"a{9").parse().unwrap_err(), + TestError { + span: span(1..3), + kind: ast::ErrorKind::RepetitionCountUnclosed, + }); + assert_eq!( + parser(r"a{9,a").parse().unwrap_err(), + TestError { + span: span(4..4), + kind: ast::ErrorKind::DecimalEmpty, + }); + assert_eq!( + parser(r"a{9,9999999999}").parse().unwrap_err(), + TestError { + span: span(4..14), + kind: ast::ErrorKind::DecimalInvalid, + }); + assert_eq!( + parser(r"a{9,").parse().unwrap_err(), + TestError { + span: span(1..4), + kind: ast::ErrorKind::RepetitionCountUnclosed, + }); + assert_eq!( + parser(r"a{9,11").parse().unwrap_err(), + TestError { + span: span(1..6), + kind: ast::ErrorKind::RepetitionCountUnclosed, + }); + assert_eq!( + parser(r"a{2,1}").parse().unwrap_err(), + TestError { + span: span(1..6), + kind: ast::ErrorKind::RepetitionCountInvalid, + }); + assert_eq!( + parser(r"{5}").parse().unwrap_err(), + TestError { + span: span(0..0), + kind: ast::ErrorKind::RepetitionMissing, + }); + assert_eq!( + parser(r"|{5}").parse().unwrap_err(), + TestError { + span: span(1..1), + kind: ast::ErrorKind::RepetitionMissing, + }); + } + + #[test] + fn parse_alternate() { + assert_eq!( + parser(r"a|b").parse(), + Ok(Ast::Alternation(ast::Alternation { + span: span(0..3), + asts: vec![lit('a', 0), lit('b', 2)], + }))); + assert_eq!( + parser(r"(a|b)").parse(), + Ok(group(0..5, 1, Ast::Alternation(ast::Alternation { + span: span(1..4), + asts: vec![lit('a', 1), lit('b', 3)], + })))); + + assert_eq!( + parser(r"a|b|c").parse(), + Ok(Ast::Alternation(ast::Alternation { + span: span(0..5), + asts: vec![lit('a', 0), lit('b', 2), lit('c', 4)], + }))); + assert_eq!( + parser(r"ax|by|cz").parse(), + Ok(Ast::Alternation(ast::Alternation { + span: span(0..8), + asts: vec![ + concat(0..2, vec![lit('a', 0), lit('x', 1)]), + concat(3..5, vec![lit('b', 3), lit('y', 4)]), + concat(6..8, vec![lit('c', 6), lit('z', 7)]), + ], + }))); + assert_eq!( + parser(r"(ax|by|cz)").parse(), + Ok(group(0..10, 1, Ast::Alternation(ast::Alternation { + span: span(1..9), + asts: vec![ + concat(1..3, vec![lit('a', 1), lit('x', 2)]), + concat(4..6, vec![lit('b', 4), lit('y', 5)]), + concat(7..9, vec![lit('c', 7), lit('z', 8)]), + ], + })))); + assert_eq!( + parser(r"(ax|(by|(cz)))").parse(), + Ok(group(0..14, 1, alt(1..13, vec![ + concat(1..3, vec![lit('a', 1), lit('x', 2)]), + group(4..13, 2, alt(5..12, vec![ + concat(5..7, vec![lit('b', 5), lit('y', 6)]), + group(8..12, 3, concat(9..11, vec![ + lit('c', 9), + lit('z', 10), + ])), + ])), + ])))); + + assert_eq!( + parser(r"|").parse(), Ok(alt(0..1, vec![ + Ast::Empty(span(0..0)), Ast::Empty(span(1..1)), + ]))); + assert_eq!( + parser(r"||").parse(), Ok(alt(0..2, vec![ + Ast::Empty(span(0..0)), + Ast::Empty(span(1..1)), + Ast::Empty(span(2..2)), + ]))); + assert_eq!( + parser(r"a|").parse(), Ok(alt(0..2, vec![ + lit('a', 0), Ast::Empty(span(2..2)), + ]))); + assert_eq!( + parser(r"|a").parse(), Ok(alt(0..2, vec![ + Ast::Empty(span(0..0)), lit('a', 1), + ]))); + + assert_eq!( + parser(r"(|)").parse(), Ok(group(0..3, 1, alt(1..2, vec![ + Ast::Empty(span(1..1)), Ast::Empty(span(2..2)), + ])))); + assert_eq!( + parser(r"(a|)").parse(), Ok(group(0..4, 1, alt(1..3, vec![ + lit('a', 1), Ast::Empty(span(3..3)), + ])))); + assert_eq!( + parser(r"(|a)").parse(), Ok(group(0..4, 1, alt(1..3, vec![ + Ast::Empty(span(1..1)), lit('a', 2), + ])))); + + assert_eq!( + parser(r"a|b)").parse().unwrap_err(), + TestError { + span: span(3..4), + kind: ast::ErrorKind::GroupUnopened, + }); + assert_eq!( + parser(r"(a|b").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::GroupUnclosed, + }); + } + + #[test] + fn parse_unsupported_lookaround() { + assert_eq!( + parser(r"(?=a)").parse().unwrap_err(), + TestError { + span: span(0..3), + kind: ast::ErrorKind::UnsupportedLookAround, + }); + assert_eq!( + parser(r"(?!a)").parse().unwrap_err(), + TestError { + span: span(0..3), + kind: ast::ErrorKind::UnsupportedLookAround, + }); + assert_eq!( + parser(r"(?<=a)").parse().unwrap_err(), + TestError { + span: span(0..4), + kind: ast::ErrorKind::UnsupportedLookAround, + }); + assert_eq!( + parser(r"(?<!a)").parse().unwrap_err(), + TestError { + span: span(0..4), + kind: ast::ErrorKind::UnsupportedLookAround, + }); + } + + #[test] + fn parse_group() { + assert_eq!(parser("(?i)").parse(), Ok(Ast::Flags(ast::SetFlags { + span: span(0..4), + flags: ast::Flags { + span: span(2..3), + items: vec![ast::FlagsItem { + span: span(2..3), + kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive), + }], + }, + }))); + assert_eq!(parser("(?iU)").parse(), Ok(Ast::Flags(ast::SetFlags { + span: span(0..5), + flags: ast::Flags { + span: span(2..4), + items: vec![ + ast::FlagsItem { + span: span(2..3), + kind: ast::FlagsItemKind::Flag( + ast::Flag::CaseInsensitive), + }, + ast::FlagsItem { + span: span(3..4), + kind: ast::FlagsItemKind::Flag(ast::Flag::SwapGreed), + }, + ], + }, + }))); + assert_eq!(parser("(?i-U)").parse(), Ok(Ast::Flags(ast::SetFlags { + span: span(0..6), + flags: ast::Flags { + span: span(2..5), + items: vec![ + ast::FlagsItem { + span: span(2..3), + kind: ast::FlagsItemKind::Flag( + ast::Flag::CaseInsensitive), + }, + ast::FlagsItem { + span: span(3..4), + kind: ast::FlagsItemKind::Negation, + }, + ast::FlagsItem { + span: span(4..5), + kind: ast::FlagsItemKind::Flag(ast::Flag::SwapGreed), + }, + ], + }, + }))); + + assert_eq!(parser("()").parse(), Ok(Ast::Group(ast::Group { + span: span(0..2), + kind: ast::GroupKind::CaptureIndex(1), + ast: Box::new(Ast::Empty(span(1..1))), + }))); + assert_eq!(parser("(a)").parse(), Ok(Ast::Group(ast::Group { + span: span(0..3), + kind: ast::GroupKind::CaptureIndex(1), + ast: Box::new(lit('a', 1)), + }))); + assert_eq!(parser("(())").parse(), Ok(Ast::Group(ast::Group { + span: span(0..4), + kind: ast::GroupKind::CaptureIndex(1), + ast: Box::new(Ast::Group(ast::Group { + span: span(1..3), + kind: ast::GroupKind::CaptureIndex(2), + ast: Box::new(Ast::Empty(span(2..2))), + })), + }))); + + assert_eq!(parser("(?:a)").parse(), Ok(Ast::Group(ast::Group { + span: span(0..5), + kind: ast::GroupKind::NonCapturing(ast::Flags { + span: span(2..2), + items: vec![], + }), + ast: Box::new(lit('a', 3)), + }))); + + assert_eq!(parser("(?i:a)").parse(), Ok(Ast::Group(ast::Group { + span: span(0..6), + kind: ast::GroupKind::NonCapturing(ast::Flags { + span: span(2..3), + items: vec![ + ast::FlagsItem { + span: span(2..3), + kind: ast::FlagsItemKind::Flag( + ast::Flag::CaseInsensitive), + }, + ], + }), + ast: Box::new(lit('a', 4)), + }))); + assert_eq!(parser("(?i-U:a)").parse(), Ok(Ast::Group(ast::Group { + span: span(0..8), + kind: ast::GroupKind::NonCapturing(ast::Flags { + span: span(2..5), + items: vec![ + ast::FlagsItem { + span: span(2..3), + kind: ast::FlagsItemKind::Flag( + ast::Flag::CaseInsensitive), + }, + ast::FlagsItem { + span: span(3..4), + kind: ast::FlagsItemKind::Negation, + }, + ast::FlagsItem { + span: span(4..5), + kind: ast::FlagsItemKind::Flag(ast::Flag::SwapGreed), + }, + ], + }), + ast: Box::new(lit('a', 6)), + }))); + + assert_eq!( + parser("(").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::GroupUnclosed, + }); + assert_eq!( + parser("(?").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::GroupUnclosed, + }); + assert_eq!( + parser("(?P").parse().unwrap_err(), + TestError { + span: span(2..3), + kind: ast::ErrorKind::FlagUnrecognized, + }); + assert_eq!( + parser("(?P<").parse().unwrap_err(), + TestError { + span: span(4..4), + kind: ast::ErrorKind::GroupNameUnexpectedEof, + }); + assert_eq!( + parser("(a").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::GroupUnclosed, + }); + assert_eq!( + parser("(()").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::GroupUnclosed, + }); + assert_eq!( + parser(")").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::GroupUnopened, + }); + assert_eq!( + parser("a)").parse().unwrap_err(), + TestError { + span: span(1..2), + kind: ast::ErrorKind::GroupUnopened, + }); + } + + #[test] + fn parse_capture_name() { + assert_eq!(parser("(?P<a>z)").parse(), Ok(Ast::Group(ast::Group { + span: span(0..8), + kind: ast::GroupKind::CaptureName(ast::CaptureName { + span: span(4..5), + name: s("a"), + index: 1, + }), + ast: Box::new(lit('z', 6)), + }))); + assert_eq!(parser("(?P<abc>z)").parse(), Ok(Ast::Group(ast::Group { + span: span(0..10), + kind: ast::GroupKind::CaptureName(ast::CaptureName { + span: span(4..7), + name: s("abc"), + index: 1, + }), + ast: Box::new(lit('z', 8)), + }))); + + assert_eq!( + parser("(?P<").parse().unwrap_err(), + TestError { + span: span(4..4), + kind: ast::ErrorKind::GroupNameUnexpectedEof, + }); + assert_eq!( + parser("(?P<>z)").parse().unwrap_err(), + TestError { + span: span(4..4), + kind: ast::ErrorKind::GroupNameEmpty, + }); + assert_eq!( + parser("(?P<a").parse().unwrap_err(), + TestError { + span: span(5..5), + kind: ast::ErrorKind::GroupNameUnexpectedEof, + }); + assert_eq!( + parser("(?P<ab").parse().unwrap_err(), + TestError { + span: span(6..6), + kind: ast::ErrorKind::GroupNameUnexpectedEof, + }); + assert_eq!( + parser("(?P<0a").parse().unwrap_err(), + TestError { + span: span(4..5), + kind: ast::ErrorKind::GroupNameInvalid, + }); + assert_eq!( + parser("(?P<~").parse().unwrap_err(), + TestError { + span: span(4..5), + kind: ast::ErrorKind::GroupNameInvalid, + }); + assert_eq!( + parser("(?P<abc~").parse().unwrap_err(), + TestError { + span: span(7..8), + kind: ast::ErrorKind::GroupNameInvalid, + }); + assert_eq!( + parser("(?P<a>y)(?P<a>z)").parse().unwrap_err(), + TestError { + span: span(12..13), + kind: ast::ErrorKind::GroupNameDuplicate { + original: span(4..5), + }, + }); + } + + #[test] + fn parse_flags() { + assert_eq!(parser("i:").parse_flags(), Ok(ast::Flags { + span: span(0..1), + items: vec![ast::FlagsItem { + span: span(0..1), + kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive), + }], + })); + assert_eq!(parser("i)").parse_flags(), Ok(ast::Flags { + span: span(0..1), + items: vec![ast::FlagsItem { + span: span(0..1), + kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive), + }], + })); + + assert_eq!(parser("isU:").parse_flags(), Ok(ast::Flags { + span: span(0..3), + items: vec![ + ast::FlagsItem { + span: span(0..1), + kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive), + }, + ast::FlagsItem { + span: span(1..2), + kind: ast::FlagsItemKind::Flag( + ast::Flag::DotMatchesNewLine), + }, + ast::FlagsItem { + span: span(2..3), + kind: ast::FlagsItemKind::Flag(ast::Flag::SwapGreed), + }, + ], + })); + + assert_eq!(parser("-isU:").parse_flags(), Ok(ast::Flags { + span: span(0..4), + items: vec![ + ast::FlagsItem { + span: span(0..1), + kind: ast::FlagsItemKind::Negation, + }, + ast::FlagsItem { + span: span(1..2), + kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive), + }, + ast::FlagsItem { + span: span(2..3), + kind: ast::FlagsItemKind::Flag( + ast::Flag::DotMatchesNewLine), + }, + ast::FlagsItem { + span: span(3..4), + kind: ast::FlagsItemKind::Flag(ast::Flag::SwapGreed), + }, + ], + })); + assert_eq!(parser("i-sU:").parse_flags(), Ok(ast::Flags { + span: span(0..4), + items: vec![ + ast::FlagsItem { + span: span(0..1), + kind: ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive), + }, + ast::FlagsItem { + span: span(1..2), + kind: ast::FlagsItemKind::Negation, + }, + ast::FlagsItem { + span: span(2..3), + kind: ast::FlagsItemKind::Flag( + ast::Flag::DotMatchesNewLine), + }, + ast::FlagsItem { + span: span(3..4), + kind: ast::FlagsItemKind::Flag(ast::Flag::SwapGreed), + }, + ], + })); + + assert_eq!( + parser("isU").parse_flags().unwrap_err(), + TestError { + span: span(3..3), + kind: ast::ErrorKind::FlagUnexpectedEof, + }); + assert_eq!( + parser("isUa:").parse_flags().unwrap_err(), + TestError { + span: span(3..4), + kind: ast::ErrorKind::FlagUnrecognized, + }); + assert_eq!( + parser("isUi:").parse_flags().unwrap_err(), + TestError { + span: span(3..4), + kind: ast::ErrorKind::FlagDuplicate { + original: span(0..1), + }, + }); + assert_eq!( + parser("i-sU-i:").parse_flags().unwrap_err(), + TestError { + span: span(4..5), + kind: ast::ErrorKind::FlagRepeatedNegation { + original: span(1..2), + }, + }); + assert_eq!( + parser("-)").parse_flags().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::FlagDanglingNegation, + }); + assert_eq!( + parser("i-)").parse_flags().unwrap_err(), + TestError { + span: span(1..2), + kind: ast::ErrorKind::FlagDanglingNegation, + }); + assert_eq!( + parser("iU-)").parse_flags().unwrap_err(), + TestError { + span: span(2..3), + kind: ast::ErrorKind::FlagDanglingNegation, + }); + } + + #[test] + fn parse_flag() { + assert_eq!(parser("i").parse_flag(), Ok(ast::Flag::CaseInsensitive)); + assert_eq!(parser("m").parse_flag(), Ok(ast::Flag::MultiLine)); + assert_eq!(parser("s").parse_flag(), Ok(ast::Flag::DotMatchesNewLine)); + assert_eq!(parser("U").parse_flag(), Ok(ast::Flag::SwapGreed)); + assert_eq!(parser("u").parse_flag(), Ok(ast::Flag::Unicode)); + assert_eq!(parser("x").parse_flag(), Ok(ast::Flag::IgnoreWhitespace)); + + assert_eq!( + parser("a").parse_flag().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::FlagUnrecognized, + }); + assert_eq!( + parser("☃").parse_flag().unwrap_err(), + TestError { + span: span_range("☃", 0..3), + kind: ast::ErrorKind::FlagUnrecognized, + }); + } + + #[test] + fn parse_primitive_non_escape() { + assert_eq!( + parser(r".").parse_primitive(), + Ok(Primitive::Dot(span(0..1)))); + assert_eq!( + parser(r"^").parse_primitive(), + Ok(Primitive::Assertion(ast::Assertion { + span: span(0..1), + kind: ast::AssertionKind::StartLine, + }))); + assert_eq!( + parser(r"$").parse_primitive(), + Ok(Primitive::Assertion(ast::Assertion { + span: span(0..1), + kind: ast::AssertionKind::EndLine, + }))); + + assert_eq!( + parser(r"a").parse_primitive(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..1), + kind: ast::LiteralKind::Verbatim, + c: 'a', + }))); + assert_eq!( + parser(r"|").parse_primitive(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..1), + kind: ast::LiteralKind::Verbatim, + c: '|', + }))); + assert_eq!( + parser(r"☃").parse_primitive(), + Ok(Primitive::Literal(ast::Literal { + span: span_range("☃", 0..3), + kind: ast::LiteralKind::Verbatim, + c: '☃', + }))); + } + + #[test] + fn parse_escape() { + assert_eq!( + parser(r"\|").parse_primitive(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..2), + kind: ast::LiteralKind::Punctuation, + c: '|', + }))); + let specials = &[ + (r"\a", '\x07', ast::SpecialLiteralKind::Bell), + (r"\f", '\x0C', ast::SpecialLiteralKind::FormFeed), + (r"\t", '\t', ast::SpecialLiteralKind::Tab), + (r"\n", '\n', ast::SpecialLiteralKind::LineFeed), + (r"\r", '\r', ast::SpecialLiteralKind::CarriageReturn), + (r"\v", '\x0B', ast::SpecialLiteralKind::VerticalTab), + ]; + for &(pat, c, ref kind) in specials { + assert_eq!( + parser(pat).parse_primitive(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..2), + kind: ast::LiteralKind::Special(kind.clone()), + c: c, + }))); + } + assert_eq!( + parser(r"\A").parse_primitive(), + Ok(Primitive::Assertion(ast::Assertion { + span: span(0..2), + kind: ast::AssertionKind::StartText, + }))); + assert_eq!( + parser(r"\z").parse_primitive(), + Ok(Primitive::Assertion(ast::Assertion { + span: span(0..2), + kind: ast::AssertionKind::EndText, + }))); + assert_eq!( + parser(r"\b").parse_primitive(), + Ok(Primitive::Assertion(ast::Assertion { + span: span(0..2), + kind: ast::AssertionKind::WordBoundary, + }))); + assert_eq!( + parser(r"\B").parse_primitive(), + Ok(Primitive::Assertion(ast::Assertion { + span: span(0..2), + kind: ast::AssertionKind::NotWordBoundary, + }))); + + assert_eq!( + parser(r"\").parse_escape().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\y").parse_escape().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::EscapeUnrecognized, + }); + } + + #[test] + fn parse_unsupported_backreference() { + assert_eq!( + parser(r"\0").parse_escape().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::UnsupportedBackreference, + }); + assert_eq!( + parser(r"\9").parse_escape().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::UnsupportedBackreference, + }); + } + + #[test] + fn parse_octal() { + for i in 0..511 { + let pat = format!(r"\{:o}", i); + assert_eq!( + parser_octal(&pat).parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..pat.len()), + kind: ast::LiteralKind::Octal, + c: ::std::char::from_u32(i).unwrap(), + }))); + } + assert_eq!( + parser_octal(r"\778").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..3), + kind: ast::LiteralKind::Octal, + c: '?', + }))); + assert_eq!( + parser_octal(r"\7777").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..4), + kind: ast::LiteralKind::Octal, + c: '\u{01FF}', + }))); + assert_eq!( + parser_octal(r"\778").parse(), + Ok(Ast::Concat(ast::Concat { + span: span(0..4), + asts: vec![ + Ast::Literal(ast::Literal { + span: span(0..3), + kind: ast::LiteralKind::Octal, + c: '?', + }), + Ast::Literal(ast::Literal { + span: span(3..4), + kind: ast::LiteralKind::Verbatim, + c: '8', + }), + ], + }))); + assert_eq!( + parser_octal(r"\7777").parse(), + Ok(Ast::Concat(ast::Concat { + span: span(0..5), + asts: vec![ + Ast::Literal(ast::Literal { + span: span(0..4), + kind: ast::LiteralKind::Octal, + c: '\u{01FF}', + }), + Ast::Literal(ast::Literal { + span: span(4..5), + kind: ast::LiteralKind::Verbatim, + c: '7', + }), + ], + }))); + + assert_eq!( + parser_octal(r"\8").parse_escape().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::EscapeUnrecognized, + }); + } + + #[test] + fn parse_hex_two() { + for i in 0..256 { + let pat = format!(r"\x{:02x}", i); + assert_eq!( + parser(&pat).parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..pat.len()), + kind: ast::LiteralKind::HexFixed(ast::HexLiteralKind::X), + c: ::std::char::from_u32(i).unwrap(), + }))); + } + + assert_eq!( + parser(r"\xF").parse_escape().unwrap_err(), + TestError { + span: span(3..3), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\xG").parse_escape().unwrap_err(), + TestError { + span: span(2..3), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\xFG").parse_escape().unwrap_err(), + TestError { + span: span(3..4), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + } + + #[test] + fn parse_hex_four() { + for i in 0..65536 { + let c = match ::std::char::from_u32(i) { + None => continue, + Some(c) => c, + }; + let pat = format!(r"\u{:04x}", i); + assert_eq!( + parser(&pat).parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..pat.len()), + kind: ast::LiteralKind::HexFixed( + ast::HexLiteralKind::UnicodeShort), + c: c, + }))); + } + + assert_eq!( + parser(r"\uF").parse_escape().unwrap_err(), + TestError { + span: span(3..3), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\uG").parse_escape().unwrap_err(), + TestError { + span: span(2..3), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\uFG").parse_escape().unwrap_err(), + TestError { + span: span(3..4), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\uFFG").parse_escape().unwrap_err(), + TestError { + span: span(4..5), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\uFFFG").parse_escape().unwrap_err(), + TestError { + span: span(5..6), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\uD800").parse_escape().unwrap_err(), + TestError { + span: span(2..6), + kind: ast::ErrorKind::EscapeHexInvalid, + }); + } + + #[test] + fn parse_hex_eight() { + for i in 0..65536 { + let c = match ::std::char::from_u32(i) { + None => continue, + Some(c) => c, + }; + let pat = format!(r"\U{:08x}", i); + assert_eq!( + parser(&pat).parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..pat.len()), + kind: ast::LiteralKind::HexFixed( + ast::HexLiteralKind::UnicodeLong), + c: c, + }))); + } + + assert_eq!( + parser(r"\UF").parse_escape().unwrap_err(), + TestError { + span: span(3..3), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\UG").parse_escape().unwrap_err(), + TestError { + span: span(2..3), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFG").parse_escape().unwrap_err(), + TestError { + span: span(3..4), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFFG").parse_escape().unwrap_err(), + TestError { + span: span(4..5), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFFFG").parse_escape().unwrap_err(), + TestError { + span: span(5..6), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFFFFG").parse_escape().unwrap_err(), + TestError { + span: span(6..7), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFFFFFG").parse_escape().unwrap_err(), + TestError { + span: span(7..8), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFFFFFFG").parse_escape().unwrap_err(), + TestError { + span: span(8..9), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\UFFFFFFFG").parse_escape().unwrap_err(), + TestError { + span: span(9..10), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + } + + #[test] + fn parse_hex_brace() { + assert_eq!( + parser(r"\u{26c4}").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..8), + kind: ast::LiteralKind::HexBrace( + ast::HexLiteralKind::UnicodeShort), + c: '⛄', + }))); + assert_eq!( + parser(r"\U{26c4}").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..8), + kind: ast::LiteralKind::HexBrace( + ast::HexLiteralKind::UnicodeLong), + c: '⛄', + }))); + assert_eq!( + parser(r"\x{26c4}").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..8), + kind: ast::LiteralKind::HexBrace(ast::HexLiteralKind::X), + c: '⛄', + }))); + assert_eq!( + parser(r"\x{26C4}").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..8), + kind: ast::LiteralKind::HexBrace(ast::HexLiteralKind::X), + c: '⛄', + }))); + assert_eq!( + parser(r"\x{10fFfF}").parse_escape(), + Ok(Primitive::Literal(ast::Literal { + span: span(0..10), + kind: ast::LiteralKind::HexBrace(ast::HexLiteralKind::X), + c: '\u{10FFFF}', + }))); + + assert_eq!( + parser(r"\x").parse_escape().unwrap_err(), + TestError { + span: span(2..2), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\x{").parse_escape().unwrap_err(), + TestError { + span: span(2..3), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\x{FF").parse_escape().unwrap_err(), + TestError { + span: span(2..5), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\x{}").parse_escape().unwrap_err(), + TestError { + span: span(2..4), + kind: ast::ErrorKind::EscapeHexEmpty, + }); + assert_eq!( + parser(r"\x{FGF}").parse_escape().unwrap_err(), + TestError { + span: span(4..5), + kind: ast::ErrorKind::EscapeHexInvalidDigit, + }); + assert_eq!( + parser(r"\x{FFFFFF}").parse_escape().unwrap_err(), + TestError { + span: span(3..9), + kind: ast::ErrorKind::EscapeHexInvalid, + }); + assert_eq!( + parser(r"\x{D800}").parse_escape().unwrap_err(), + TestError { + span: span(3..7), + kind: ast::ErrorKind::EscapeHexInvalid, + }); + assert_eq!( + parser(r"\x{FFFFFFFFF}").parse_escape().unwrap_err(), + TestError { + span: span(3..12), + kind: ast::ErrorKind::EscapeHexInvalid, + }); + } + + #[test] + fn parse_decimal() { + assert_eq!(parser("123").parse_decimal(), Ok(123)); + assert_eq!(parser("0").parse_decimal(), Ok(0)); + assert_eq!(parser("01").parse_decimal(), Ok(1)); + + assert_eq!( + parser("-1").parse_decimal().unwrap_err(), + TestError { + span: span(0..0), + kind: ast::ErrorKind::DecimalEmpty, + }); + assert_eq!( + parser("").parse_decimal().unwrap_err(), + TestError { + span: span(0..0), + kind: ast::ErrorKind::DecimalEmpty, + }); + assert_eq!( + parser("9999999999").parse_decimal().unwrap_err(), + TestError { + span: span(0..10), + kind: ast::ErrorKind::DecimalInvalid, + }); + } + + #[test] + fn parse_set_class() { + fn union(span: Span, items: Vec<ast::ClassSetItem>) -> ast::ClassSet { + ast::ClassSet::union(ast::ClassSetUnion { + span: span, + items: items, + }) + } + + fn intersection( + span: Span, + lhs: ast::ClassSet, + rhs: ast::ClassSet, + ) -> ast::ClassSet { + ast::ClassSet::BinaryOp(ast::ClassSetBinaryOp { + span: span, + kind: ast::ClassSetBinaryOpKind::Intersection, + lhs: Box::new(lhs), + rhs: Box::new(rhs), + }) + } + + fn difference( + span: Span, + lhs: ast::ClassSet, + rhs: ast::ClassSet, + ) -> ast::ClassSet { + ast::ClassSet::BinaryOp(ast::ClassSetBinaryOp { + span: span, + kind: ast::ClassSetBinaryOpKind::Difference, + lhs: Box::new(lhs), + rhs: Box::new(rhs), + }) + } + + fn symdifference( + span: Span, + lhs: ast::ClassSet, + rhs: ast::ClassSet, + ) -> ast::ClassSet { + ast::ClassSet::BinaryOp(ast::ClassSetBinaryOp { + span: span, + kind: ast::ClassSetBinaryOpKind::SymmetricDifference, + lhs: Box::new(lhs), + rhs: Box::new(rhs), + }) + } + + fn itemset(item: ast::ClassSetItem) -> ast::ClassSet { + ast::ClassSet::Item(item) + } + + fn item_ascii(cls: ast::ClassAscii) -> ast::ClassSetItem { + ast::ClassSetItem::Ascii(cls) + } + + fn item_unicode(cls: ast::ClassUnicode) -> ast::ClassSetItem { + ast::ClassSetItem::Unicode(cls) + } + + fn item_perl(cls: ast::ClassPerl) -> ast::ClassSetItem { + ast::ClassSetItem::Perl(cls) + } + + fn item_bracket(cls: ast::ClassBracketed) -> ast::ClassSetItem { + ast::ClassSetItem::Bracketed(Box::new(cls)) + } + + fn lit(span: Span, c: char) -> ast::ClassSetItem { + ast::ClassSetItem::Literal(ast::Literal { + span: span, + kind: ast::LiteralKind::Verbatim, + c: c, + }) + } + + fn empty(span: Span) -> ast::ClassSetItem { + ast::ClassSetItem::Empty(span) + } + + fn range(span: Span, start: char, end: char) -> ast::ClassSetItem { + let pos1 = Position { + offset: span.start.offset + start.len_utf8(), + column: span.start.column + 1, + ..span.start + }; + let pos2 = Position { + offset: span.end.offset - end.len_utf8(), + column: span.end.column - 1, + ..span.end + }; + ast::ClassSetItem::Range(ast::ClassSetRange { + span: span, + start: ast::Literal { + span: Span { end: pos1, ..span }, + kind: ast::LiteralKind::Verbatim, + c: start, + }, + end: ast::Literal { + span: Span { start: pos2, ..span }, + kind: ast::LiteralKind::Verbatim, + c: end, + }, + }) + } + + fn alnum(span: Span, negated: bool) -> ast::ClassAscii { + ast::ClassAscii { + span: span, + kind: ast::ClassAsciiKind::Alnum, + negated: negated, + } + } + + fn lower(span: Span, negated: bool) -> ast::ClassAscii { + ast::ClassAscii { + span: span, + kind: ast::ClassAsciiKind::Lower, + negated: negated, + } + } + + assert_eq!( + parser("[[:alnum:]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..11), + negated: false, + kind: itemset(item_ascii(alnum(span(1..10), false))), + })))); + assert_eq!( + parser("[[[:alnum:]]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..13), + negated: false, + kind: itemset(item_bracket(ast::ClassBracketed { + span: span(1..12), + negated: false, + kind: itemset(item_ascii(alnum(span(2..11), false))), + })), + })))); + assert_eq!( + parser("[[:alnum:]&&[:lower:]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..22), + negated: false, + kind: intersection( + span(1..21), + itemset(item_ascii(alnum(span(1..10), false))), + itemset(item_ascii(lower(span(12..21), false))), + ), + })))); + assert_eq!( + parser("[[:alnum:]--[:lower:]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..22), + negated: false, + kind: difference( + span(1..21), + itemset(item_ascii(alnum(span(1..10), false))), + itemset(item_ascii(lower(span(12..21), false))), + ), + })))); + assert_eq!( + parser("[[:alnum:]~~[:lower:]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..22), + negated: false, + kind: symdifference( + span(1..21), + itemset(item_ascii(alnum(span(1..10), false))), + itemset(item_ascii(lower(span(12..21), false))), + ), + })))); + + assert_eq!( + parser("[a]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..3), + negated: false, + kind: itemset(lit(span(1..2), 'a')), + })))); + assert_eq!( + parser(r"[a\]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..5), + negated: false, + kind: union(span(1..4), vec![ + lit(span(1..2), 'a'), + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..4), + kind: ast::LiteralKind::Punctuation, + c: ']', + }), + ]), + })))); + assert_eq!( + parser(r"[a\-z]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..6), + negated: false, + kind: union(span(1..5), vec![ + lit(span(1..2), 'a'), + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..4), + kind: ast::LiteralKind::Punctuation, + c: '-', + }), + lit(span(4..5), 'z'), + ]), + })))); + assert_eq!( + parser("[ab]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: union(span(1..3), vec![ + lit(span(1..2), 'a'), + lit(span(2..3), 'b'), + ]), + })))); + assert_eq!( + parser("[a-]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: union(span(1..3), vec![ + lit(span(1..2), 'a'), + lit(span(2..3), '-'), + ]), + })))); + assert_eq!( + parser("[-a]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: union(span(1..3), vec![ + lit(span(1..2), '-'), + lit(span(2..3), 'a'), + ]), + })))); + assert_eq!( + parser(r"[\pL]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..5), + negated: false, + kind: itemset(item_unicode(ast::ClassUnicode { + span: span(1..4), + negated: false, + kind: ast::ClassUnicodeKind::OneLetter('L'), + })), + })))); + assert_eq!( + parser(r"[\w]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: itemset(item_perl(ast::ClassPerl { + span: span(1..3), + kind: ast::ClassPerlKind::Word, + negated: false, + })), + })))); + assert_eq!( + parser(r"[a\wz]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..6), + negated: false, + kind: union(span(1..5), vec![ + lit(span(1..2), 'a'), + item_perl(ast::ClassPerl { + span: span(2..4), + kind: ast::ClassPerlKind::Word, + negated: false, + }), + lit(span(4..5), 'z'), + ]), + })))); + + assert_eq!( + parser("[a-z]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..5), + negated: false, + kind: itemset(range(span(1..4), 'a', 'z')), + })))); + assert_eq!( + parser("[a-cx-z]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..8), + negated: false, + kind: union(span(1..7), vec![ + range(span(1..4), 'a', 'c'), + range(span(4..7), 'x', 'z'), + ]), + })))); + assert_eq!( + parser(r"[\w&&a-cx-z]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..12), + negated: false, + kind: intersection( + span(1..11), + itemset(item_perl(ast::ClassPerl { + span: span(1..3), + kind: ast::ClassPerlKind::Word, + negated: false, + })), + union(span(5..11), vec![ + range(span(5..8), 'a', 'c'), + range(span(8..11), 'x', 'z'), + ]), + ), + })))); + assert_eq!( + parser(r"[a-cx-z&&\w]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..12), + negated: false, + kind: intersection( + span(1..11), + union(span(1..7), vec![ + range(span(1..4), 'a', 'c'), + range(span(4..7), 'x', 'z'), + ]), + itemset(item_perl(ast::ClassPerl { + span: span(9..11), + kind: ast::ClassPerlKind::Word, + negated: false, + })), + ), + })))); + assert_eq!( + parser(r"[a--b--c]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..9), + negated: false, + kind: difference( + span(1..8), + difference( + span(1..5), + itemset(lit(span(1..2), 'a')), + itemset(lit(span(4..5), 'b')), + ), + itemset(lit(span(7..8), 'c')), + ), + })))); + assert_eq!( + parser(r"[a~~b~~c]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..9), + negated: false, + kind: symdifference( + span(1..8), + symdifference( + span(1..5), + itemset(lit(span(1..2), 'a')), + itemset(lit(span(4..5), 'b')), + ), + itemset(lit(span(7..8), 'c')), + ), + })))); + assert_eq!( + parser(r"[\^&&^]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..7), + negated: false, + kind: intersection( + span(1..6), + itemset(ast::ClassSetItem::Literal(ast::Literal { + span: span(1..3), + kind: ast::LiteralKind::Punctuation, + c: '^', + })), + itemset(lit(span(5..6), '^')), + ), + })))); + assert_eq!( + parser(r"[\&&&&]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..7), + negated: false, + kind: intersection( + span(1..6), + itemset(ast::ClassSetItem::Literal(ast::Literal { + span: span(1..3), + kind: ast::LiteralKind::Punctuation, + c: '&', + })), + itemset(lit(span(5..6), '&')), + ), + })))); + assert_eq!( + parser(r"[&&&&]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..6), + negated: false, + kind: intersection( + span(1..5), + intersection( + span(1..3), + itemset(empty(span(1..1))), + itemset(empty(span(3..3))), + ), + itemset(empty(span(5..5))), + ), + })))); + + let pat = "[☃-⛄]"; + assert_eq!( + parser(pat).parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span_range(pat, 0..9), + negated: false, + kind: itemset(ast::ClassSetItem::Range(ast::ClassSetRange { + span: span_range(pat, 1..8), + start: ast::Literal { + span: span_range(pat, 1..4), + kind: ast::LiteralKind::Verbatim, + c: '☃', + }, + end: ast::Literal { + span: span_range(pat, 5..8), + kind: ast::LiteralKind::Verbatim, + c: '⛄', + }, + })), + })))); + + assert_eq!( + parser(r"[]]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..3), + negated: false, + kind: itemset(lit(span(1..2), ']')), + })))); + assert_eq!( + parser(r"[]\[]").parse(), + Ok(Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..5), + negated: false, + kind: union(span(1..4), vec![ + lit(span(1..2), ']'), + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..4), + kind: ast::LiteralKind::Punctuation, + c: '[', + }), + ]), + })))); + assert_eq!( + parser(r"[\[]]").parse(), + Ok(concat(0..5, vec![ + Ast::Class(ast::Class::Bracketed(ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: itemset(ast::ClassSetItem::Literal(ast::Literal { + span: span(1..3), + kind: ast::LiteralKind::Punctuation, + c: '[', + })), + })), + Ast::Literal(ast::Literal { + span: span(4..5), + kind: ast::LiteralKind::Verbatim, + c: ']', + }), + ]))); + + assert_eq!( + parser("[").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[[").parse().unwrap_err(), + TestError { + span: span(1..2), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[[-]").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[[[:alnum:]").parse().unwrap_err(), + TestError { + span: span(1..2), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser(r"[\b]").parse().unwrap_err(), + TestError { + span: span(1..3), + kind: ast::ErrorKind::ClassEscapeInvalid, + }); + assert_eq!( + parser(r"[\w-a]").parse().unwrap_err(), + TestError { + span: span(1..3), + kind: ast::ErrorKind::ClassEscapeInvalid, + }); + assert_eq!( + parser(r"[a-\w]").parse().unwrap_err(), + TestError { + span: span(3..5), + kind: ast::ErrorKind::ClassEscapeInvalid, + }); + assert_eq!( + parser(r"[z-a]").parse().unwrap_err(), + TestError { + span: span(1..4), + kind: ast::ErrorKind::ClassRangeInvalid, + }); + + assert_eq!( + parser_ignore_whitespace("[a ").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser_ignore_whitespace("[a- ").parse().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::ClassUnclosed, + }); + } + + #[test] + fn parse_set_class_open() { + assert_eq!( + parser("[a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..1), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(1..1), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(1..1), + items: vec![], + }; + Ok((set, union)) + }); + assert_eq!( + parser_ignore_whitespace("[ a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(4..4), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(4..4), + items: vec![], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[^a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..2), + negated: true, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(2..2), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(2..2), + items: vec![], + }; + Ok((set, union)) + }); + assert_eq!( + parser_ignore_whitespace("[ ^ a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..4), + negated: true, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(4..4), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(4..4), + items: vec![], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[-a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..2), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(1..1), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(1..2), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(1..2), + kind: ast::LiteralKind::Verbatim, + c: '-', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser_ignore_whitespace("[ - a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(2..2), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(2..3), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..3), + kind: ast::LiteralKind::Verbatim, + c: '-', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[^-a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..3), + negated: true, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(2..2), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(2..3), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..3), + kind: ast::LiteralKind::Verbatim, + c: '-', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[--a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..3), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(1..1), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(1..3), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(1..2), + kind: ast::LiteralKind::Verbatim, + c: '-', + }), + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..3), + kind: ast::LiteralKind::Verbatim, + c: '-', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[]a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..2), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(1..1), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(1..2), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(1..2), + kind: ast::LiteralKind::Verbatim, + c: ']', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser_ignore_whitespace("[ ] a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..4), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(2..2), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(2..3), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..3), + kind: ast::LiteralKind::Verbatim, + c: ']', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[^]a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..3), + negated: true, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(2..2), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(2..3), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(2..3), + kind: ast::LiteralKind::Verbatim, + c: ']', + }), + ], + }; + Ok((set, union)) + }); + assert_eq!( + parser("[-]a]").parse_set_class_open(), { + let set = ast::ClassBracketed { + span: span(0..2), + negated: false, + kind: ast::ClassSet::union(ast::ClassSetUnion { + span: span(1..1), + items: vec![], + }), + }; + let union = ast::ClassSetUnion { + span: span(1..2), + items: vec![ + ast::ClassSetItem::Literal(ast::Literal { + span: span(1..2), + kind: ast::LiteralKind::Verbatim, + c: '-', + }), + ], + }; + Ok((set, union)) + }); + + assert_eq!( + parser("[").parse_set_class_open().unwrap_err(), + TestError { + span: span(0..1), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser_ignore_whitespace("[ ") + .parse_set_class_open() + .unwrap_err(), + TestError { + span: span(0..5), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[^").parse_set_class_open().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[]").parse_set_class_open().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[-").parse_set_class_open().unwrap_err(), + TestError { + span: span(0..2), + kind: ast::ErrorKind::ClassUnclosed, + }); + assert_eq!( + parser("[--").parse_set_class_open().unwrap_err(), + TestError { + span: span(0..3), + kind: ast::ErrorKind::ClassUnclosed, + }); + } + + #[test] + fn maybe_parse_ascii_class() { + assert_eq!( + parser(r"[:alnum:]").maybe_parse_ascii_class(), + Some(ast::ClassAscii { + span: span(0..9), + kind: ast::ClassAsciiKind::Alnum, + negated: false, + })); + assert_eq!( + parser(r"[:alnum:]A").maybe_parse_ascii_class(), + Some(ast::ClassAscii { + span: span(0..9), + kind: ast::ClassAsciiKind::Alnum, + negated: false, + })); + assert_eq!( + parser(r"[:^alnum:]").maybe_parse_ascii_class(), + Some(ast::ClassAscii { + span: span(0..10), + kind: ast::ClassAsciiKind::Alnum, + negated: true, + })); + + let p = parser(r"[:"); + assert_eq!(p.maybe_parse_ascii_class(), None); + assert_eq!(p.offset(), 0); + + let p = parser(r"[:^"); + assert_eq!(p.maybe_parse_ascii_class(), None); + assert_eq!(p.offset(), 0); + + let p = parser(r"[^:alnum:]"); + assert_eq!(p.maybe_parse_ascii_class(), None); + assert_eq!(p.offset(), 0); + + let p = parser(r"[:alnnum:]"); + assert_eq!(p.maybe_parse_ascii_class(), None); + assert_eq!(p.offset(), 0); + + let p = parser(r"[:alnum]"); + assert_eq!(p.maybe_parse_ascii_class(), None); + assert_eq!(p.offset(), 0); + + let p = parser(r"[:alnum:"); + assert_eq!(p.maybe_parse_ascii_class(), None); + assert_eq!(p.offset(), 0); + } + + #[test] + fn parse_unicode_class() { + assert_eq!( + parser(r"\pN").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..3), + negated: false, + kind: ast::ClassUnicodeKind::OneLetter('N'), + }))); + assert_eq!( + parser(r"\PN").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..3), + negated: true, + kind: ast::ClassUnicodeKind::OneLetter('N'), + }))); + assert_eq!( + parser(r"\p{N}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..5), + negated: false, + kind: ast::ClassUnicodeKind::Named(s("N")), + }))); + assert_eq!( + parser(r"\P{N}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..5), + negated: true, + kind: ast::ClassUnicodeKind::Named(s("N")), + }))); + assert_eq!( + parser(r"\p{Greek}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..9), + negated: false, + kind: ast::ClassUnicodeKind::Named(s("Greek")), + }))); + + assert_eq!( + parser(r"\p{scx:Katakana}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..16), + negated: false, + kind: ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::Colon, + name: s("scx"), + value: s("Katakana"), + }, + }))); + assert_eq!( + parser(r"\p{scx=Katakana}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..16), + negated: false, + kind: ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::Equal, + name: s("scx"), + value: s("Katakana"), + }, + }))); + assert_eq!( + parser(r"\p{scx!=Katakana}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..17), + negated: false, + kind: ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::NotEqual, + name: s("scx"), + value: s("Katakana"), + }, + }))); + + assert_eq!( + parser(r"\p{:}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..5), + negated: false, + kind: ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::Colon, + name: s(""), + value: s(""), + }, + }))); + assert_eq!( + parser(r"\p{=}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..5), + negated: false, + kind: ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::Equal, + name: s(""), + value: s(""), + }, + }))); + assert_eq!( + parser(r"\p{!=}").parse_escape(), + Ok(Primitive::Unicode(ast::ClassUnicode { + span: span(0..6), + negated: false, + kind: ast::ClassUnicodeKind::NamedValue { + op: ast::ClassUnicodeOpKind::NotEqual, + name: s(""), + value: s(""), + }, + }))); + + assert_eq!( + parser(r"\p").parse_escape().unwrap_err(), + TestError { + span: span(2..2), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\p{").parse_escape().unwrap_err(), + TestError { + span: span(3..3), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\p{N").parse_escape().unwrap_err(), + TestError { + span: span(4..4), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + assert_eq!( + parser(r"\p{Greek").parse_escape().unwrap_err(), + TestError { + span: span(8..8), + kind: ast::ErrorKind::EscapeUnexpectedEof, + }); + + assert_eq!( + parser(r"\pNz").parse(), + Ok(Ast::Concat(ast::Concat { + span: span(0..4), + asts: vec![ + Ast::Class(ast::Class::Unicode(ast::ClassUnicode { + span: span(0..3), + negated: false, + kind: ast::ClassUnicodeKind::OneLetter('N'), + })), + Ast::Literal(ast::Literal { + span: span(3..4), + kind: ast::LiteralKind::Verbatim, + c: 'z', + }), + ], + }))); + assert_eq!( + parser(r"\p{Greek}z").parse(), + Ok(Ast::Concat(ast::Concat { + span: span(0..10), + asts: vec![ + Ast::Class(ast::Class::Unicode(ast::ClassUnicode { + span: span(0..9), + negated: false, + kind: ast::ClassUnicodeKind::Named(s("Greek")), + })), + Ast::Literal(ast::Literal { + span: span(9..10), + kind: ast::LiteralKind::Verbatim, + c: 'z', + }), + ], + }))); + } + + #[test] + fn parse_perl_class() { + assert_eq!( + parser(r"\d").parse_escape(), + Ok(Primitive::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Digit, + negated: false, + }))); + assert_eq!( + parser(r"\D").parse_escape(), + Ok(Primitive::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Digit, + negated: true, + }))); + assert_eq!( + parser(r"\s").parse_escape(), + Ok(Primitive::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Space, + negated: false, + }))); + assert_eq!( + parser(r"\S").parse_escape(), + Ok(Primitive::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Space, + negated: true, + }))); + assert_eq!( + parser(r"\w").parse_escape(), + Ok(Primitive::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Word, + negated: false, + }))); + assert_eq!( + parser(r"\W").parse_escape(), + Ok(Primitive::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Word, + negated: true, + }))); + + assert_eq!( + parser(r"\d").parse(), + Ok(Ast::Class(ast::Class::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Digit, + negated: false, + })))); + assert_eq!( + parser(r"\dz").parse(), + Ok(Ast::Concat(ast::Concat { + span: span(0..3), + asts: vec![ + Ast::Class(ast::Class::Perl(ast::ClassPerl { + span: span(0..2), + kind: ast::ClassPerlKind::Digit, + negated: false, + })), + Ast::Literal(ast::Literal { + span: span(2..3), + kind: ast::LiteralKind::Verbatim, + c: 'z', + }), + ], + }))); + } + + // This tests a bug fix where the nest limit checker wasn't decrementing + // its depth during post-traversal, which causes long regexes to trip + // the default limit too aggressively. + #[test] + fn regression_454_nest_too_big() { + let pattern = r#" + 2(?: + [45]\d{3}| + 7(?: + 1[0-267]| + 2[0-289]| + 3[0-29]| + 4[01]| + 5[1-3]| + 6[013]| + 7[0178]| + 91 + )| + 8(?: + 0[125]| + [139][1-6]| + 2[0157-9]| + 41| + 6[1-35]| + 7[1-5]| + 8[1-8]| + 90 + )| + 9(?: + 0[0-2]| + 1[0-4]| + 2[568]| + 3[3-6]| + 5[5-7]| + 6[0167]| + 7[15]| + 8[0146-9] + ) + )\d{4} + "#; + assert!(parser_nest_limit(pattern, 50).parse().is_ok()); + } + + // This tests that we treat a trailing `-` in a character class as a + // literal `-` even when whitespace mode is enabled and there is whitespace + // after the trailing `-`. + #[test] + fn regression_455_trailing_dash_ignore_whitespace() { + assert!(parser("(?x)[ / - ]").parse().is_ok()); + assert!(parser("(?x)[ a - ]").parse().is_ok()); + assert!(parser("(?x)[ + a + - ] + ").parse().is_ok()); + assert!(parser("(?x)[ + a # wat + - ] + ").parse().is_ok()); + + assert!(parser("(?x)[ / -").parse().is_err()); + assert!(parser("(?x)[ / - ").parse().is_err()); + assert!(parser("(?x)[ + / - + ").parse().is_err()); + assert!(parser("(?x)[ + / - # wat + ").parse().is_err()); + } +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/ast/print.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/ast/print.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/ast/print.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/ast/print.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,586 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +This module provides a regular expression printer for `Ast`. +*/ + +use std::fmt; + +use ast::{self, Ast}; +use ast::visitor::{self, Visitor}; + +/// A builder for constructing a printer. +/// +/// Note that since a printer doesn't have any configuration knobs, this type +/// remains unexported. +#[derive(Clone, Debug)] +struct PrinterBuilder { + _priv: (), +} + +impl Default for PrinterBuilder { + fn default() -> PrinterBuilder { + PrinterBuilder::new() + } +} + +impl PrinterBuilder { + fn new() -> PrinterBuilder { + PrinterBuilder { + _priv: (), + } + } + + fn build(&self) -> Printer { + Printer { + _priv: (), + } + } +} + +/// A printer for a regular expression abstract syntax tree. +/// +/// A printer converts an abstract syntax tree (AST) to a regular expression +/// pattern string. This particular printer uses constant stack space and heap +/// space proportional to the size of the AST. +/// +/// This printer will not necessarily preserve the original formatting of the +/// regular expression pattern string. For example, all whitespace and comments +/// are ignored. +#[derive(Debug)] +pub struct Printer { + _priv: (), +} + +impl Printer { + /// Create a new printer. + pub fn new() -> Printer { + PrinterBuilder::new().build() + } + + /// Print the given `Ast` to the given writer. The writer must implement + /// `fmt::Write`. Typical implementations of `fmt::Write` that can be used + /// here are a `fmt::Formatter` (which is available in `fmt::Display` + /// implementations) or a `&mut String`. + pub fn print<W: fmt::Write>(&mut self, ast: &Ast, wtr: W) -> fmt::Result { + visitor::visit(ast, Writer { printer: self, wtr: wtr }) + } +} + +#[derive(Debug)] +struct Writer<'p, W> { + printer: &'p mut Printer, + wtr: W, +} + +impl<'p, W: fmt::Write> Visitor for Writer<'p, W> { + type Output = (); + type Err = fmt::Error; + + fn finish(self) -> fmt::Result { + Ok(()) + } + + fn visit_pre(&mut self, ast: &Ast) -> fmt::Result { + match *ast { + Ast::Group(ref x) => self.fmt_group_pre(x), + Ast::Class(ast::Class::Bracketed(ref x)) => { + self.fmt_class_bracketed_pre(x) + } + _ => Ok(()) + } + } + + fn visit_post(&mut self, ast: &Ast) -> fmt::Result { + use ast::Class; + + match *ast { + Ast::Empty(_) => Ok(()), + Ast::Flags(ref x) => self.fmt_set_flags(x), + Ast::Literal(ref x) => self.fmt_literal(x), + Ast::Dot(_) => self.wtr.write_str("."), + Ast::Assertion(ref x) => self.fmt_assertion(x), + Ast::Class(Class::Perl(ref x)) => self.fmt_class_perl(x), + Ast::Class(Class::Unicode(ref x)) => self.fmt_class_unicode(x), + Ast::Class(Class::Bracketed(ref x)) => { + self.fmt_class_bracketed_post(x) + } + Ast::Repetition(ref x) => self.fmt_repetition(x), + Ast::Group(ref x) => self.fmt_group_post(x), + Ast::Alternation(_) => Ok(()), + Ast::Concat(_) => Ok(()), + } + } + + fn visit_alternation_in(&mut self) -> fmt::Result { + self.wtr.write_str("|") + } + + fn visit_class_set_item_pre( + &mut self, + ast: &ast::ClassSetItem, + ) -> Result<(), Self::Err> { + match *ast { + ast::ClassSetItem::Bracketed(ref x) => { + self.fmt_class_bracketed_pre(x) + } + _ => Ok(()), + } + } + + fn visit_class_set_item_post( + &mut self, + ast: &ast::ClassSetItem, + ) -> Result<(), Self::Err> { + use ast::ClassSetItem::*; + + match *ast { + Empty(_) => Ok(()), + Literal(ref x) => self.fmt_literal(x), + Range(ref x) => { + try!(self.fmt_literal(&x.start)); + try!(self.wtr.write_str("-")); + try!(self.fmt_literal(&x.end)); + Ok(()) + } + Ascii(ref x) => self.fmt_class_ascii(x), + Unicode(ref x) => self.fmt_class_unicode(x), + Perl(ref x) => self.fmt_class_perl(x), + Bracketed(ref x) => self.fmt_class_bracketed_post(x), + Union(_) => Ok(()), + } + } + + fn visit_class_set_binary_op_in( + &mut self, + ast: &ast::ClassSetBinaryOp, + ) -> Result<(), Self::Err> { + self.fmt_class_set_binary_op_kind(&ast.kind) + } +} + +impl<'p, W: fmt::Write> Writer<'p, W> { + fn fmt_group_pre(&mut self, ast: &ast::Group) -> fmt::Result { + use ast::GroupKind::*; + match ast.kind { + CaptureIndex(_) => self.wtr.write_str("("), + CaptureName(ref x) => { + try!(self.wtr.write_str("(?P<")); + try!(self.wtr.write_str(&x.name)); + try!(self.wtr.write_str(">")); + Ok(()) + } + NonCapturing(ref flags) => { + try!(self.wtr.write_str("(?")); + try!(self.fmt_flags(flags)); + try!(self.wtr.write_str(":")); + Ok(()) + } + } + } + + fn fmt_group_post(&mut self, _ast: &ast::Group) -> fmt::Result { + self.wtr.write_str(")") + } + + fn fmt_repetition(&mut self, ast: &ast::Repetition) -> fmt::Result { + use ast::RepetitionKind::*; + match ast.op.kind { + ZeroOrOne if ast.greedy => self.wtr.write_str("?"), + ZeroOrOne => self.wtr.write_str("??"), + ZeroOrMore if ast.greedy => self.wtr.write_str("*"), + ZeroOrMore => self.wtr.write_str("*?"), + OneOrMore if ast.greedy => self.wtr.write_str("+"), + OneOrMore => self.wtr.write_str("+?"), + Range(ref x) => { + try!(self.fmt_repetition_range(x)); + if !ast.greedy { + try!(self.wtr.write_str("?")); + } + Ok(()) + } + } + } + + fn fmt_repetition_range( + &mut self, + ast: &ast::RepetitionRange, + ) -> fmt::Result { + use ast::RepetitionRange::*; + match *ast { + Exactly(x) => write!(self.wtr, "{{{}}}", x), + AtLeast(x) => write!(self.wtr, "{{{},}}", x), + Bounded(x, y) => write!(self.wtr, "{{{},{}}}", x, y), + } + } + + fn fmt_literal(&mut self, ast: &ast::Literal) -> fmt::Result { + use ast::LiteralKind::*; + + match ast.kind { + Verbatim => self.wtr.write_char(ast.c), + Punctuation => write!(self.wtr, r"\{}", ast.c), + Octal => write!(self.wtr, r"\{:o}", ast.c as u32), + HexFixed(ast::HexLiteralKind::X) => { + write!(self.wtr, r"\x{:02X}", ast.c as u32) + } + HexFixed(ast::HexLiteralKind::UnicodeShort) => { + write!(self.wtr, r"\u{:04X}", ast.c as u32) + } + HexFixed(ast::HexLiteralKind::UnicodeLong) => { + write!(self.wtr, r"\U{:08X}", ast.c as u32) + } + HexBrace(ast::HexLiteralKind::X) => { + write!(self.wtr, r"\x{{{:X}}}", ast.c as u32) + } + HexBrace(ast::HexLiteralKind::UnicodeShort) => { + write!(self.wtr, r"\u{{{:X}}}", ast.c as u32) + } + HexBrace(ast::HexLiteralKind::UnicodeLong) => { + write!(self.wtr, r"\U{{{:X}}}", ast.c as u32) + } + Special(ast::SpecialLiteralKind::Bell) => { + self.wtr.write_str(r"\a") + } + Special(ast::SpecialLiteralKind::FormFeed) => { + self.wtr.write_str(r"\f") + } + Special(ast::SpecialLiteralKind::Tab) => { + self.wtr.write_str(r"\t") + } + Special(ast::SpecialLiteralKind::LineFeed) => { + self.wtr.write_str(r"\n") + } + Special(ast::SpecialLiteralKind::CarriageReturn) => { + self.wtr.write_str(r"\r") + } + Special(ast::SpecialLiteralKind::VerticalTab) => { + self.wtr.write_str(r"\v") + } + Special(ast::SpecialLiteralKind::Space) => { + self.wtr.write_str(r"\ ") + } + } + } + + fn fmt_assertion(&mut self, ast: &ast::Assertion) -> fmt::Result { + use ast::AssertionKind::*; + match ast.kind { + StartLine => self.wtr.write_str("^"), + EndLine => self.wtr.write_str("$"), + StartText => self.wtr.write_str(r"\A"), + EndText => self.wtr.write_str(r"\z"), + WordBoundary => self.wtr.write_str(r"\b"), + NotWordBoundary => self.wtr.write_str(r"\B"), + } + } + + fn fmt_set_flags(&mut self, ast: &ast::SetFlags) -> fmt::Result { + try!(self.wtr.write_str("(?")); + try!(self.fmt_flags(&ast.flags)); + try!(self.wtr.write_str(")")); + Ok(()) + } + + fn fmt_flags(&mut self, ast: &ast::Flags) -> fmt::Result { + use ast::{Flag, FlagsItemKind}; + + for item in &ast.items { + try!(match item.kind { + FlagsItemKind::Negation => self.wtr.write_str("-"), + FlagsItemKind::Flag(ref flag) => { + match *flag { + Flag::CaseInsensitive => self.wtr.write_str("i"), + Flag::MultiLine => self.wtr.write_str("m"), + Flag::DotMatchesNewLine => self.wtr.write_str("s"), + Flag::SwapGreed => self.wtr.write_str("U"), + Flag::Unicode => self.wtr.write_str("u"), + Flag::IgnoreWhitespace => self.wtr.write_str("x"), + } + } + }); + } + Ok(()) + } + + fn fmt_class_bracketed_pre( + &mut self, + ast: &ast::ClassBracketed, + ) -> fmt::Result { + if ast.negated { + self.wtr.write_str("[^") + } else { + self.wtr.write_str("[") + } + } + + fn fmt_class_bracketed_post( + &mut self, + _ast: &ast::ClassBracketed, + ) -> fmt::Result { + self.wtr.write_str("]") + } + + fn fmt_class_set_binary_op_kind( + &mut self, + ast: &ast::ClassSetBinaryOpKind, + ) -> fmt::Result { + use ast::ClassSetBinaryOpKind::*; + match *ast { + Intersection => self.wtr.write_str("&&"), + Difference => self.wtr.write_str("--"), + SymmetricDifference => self.wtr.write_str("~~"), + } + } + + fn fmt_class_perl(&mut self, ast: &ast::ClassPerl) -> fmt::Result { + use ast::ClassPerlKind::*; + match ast.kind { + Digit if ast.negated => self.wtr.write_str(r"\D"), + Digit => self.wtr.write_str(r"\d"), + Space if ast.negated => self.wtr.write_str(r"\S"), + Space => self.wtr.write_str(r"\s"), + Word if ast.negated => self.wtr.write_str(r"\W"), + Word => self.wtr.write_str(r"\w"), + } + } + + fn fmt_class_ascii(&mut self, ast: &ast::ClassAscii) -> fmt::Result { + use ast::ClassAsciiKind::*; + match ast.kind { + Alnum if ast.negated => self.wtr.write_str("[:^alnum:]"), + Alnum => self.wtr.write_str("[:alnum:]"), + Alpha if ast.negated => self.wtr.write_str("[:^alpha:]"), + Alpha => self.wtr.write_str("[:alpha:]"), + Ascii if ast.negated => self.wtr.write_str("[:^ascii:]"), + Ascii => self.wtr.write_str("[:ascii:]"), + Blank if ast.negated => self.wtr.write_str("[:^blank:]"), + Blank => self.wtr.write_str("[:blank:]"), + Cntrl if ast.negated => self.wtr.write_str("[:^cntrl:]"), + Cntrl => self.wtr.write_str("[:cntrl:]"), + Digit if ast.negated => self.wtr.write_str("[:^digit:]"), + Digit => self.wtr.write_str("[:digit:]"), + Graph if ast.negated => self.wtr.write_str("[:^graph:]"), + Graph => self.wtr.write_str("[:graph:]"), + Lower if ast.negated => self.wtr.write_str("[:^lower:]"), + Lower => self.wtr.write_str("[:lower:]"), + Print if ast.negated => self.wtr.write_str("[:^print:]"), + Print => self.wtr.write_str("[:print:]"), + Punct if ast.negated => self.wtr.write_str("[:^punct:]"), + Punct => self.wtr.write_str("[:punct:]"), + Space if ast.negated => self.wtr.write_str("[:^space:]"), + Space => self.wtr.write_str("[:space:]"), + Upper if ast.negated => self.wtr.write_str("[:^upper:]"), + Upper => self.wtr.write_str("[:upper:]"), + Word if ast.negated => self.wtr.write_str("[:^word:]"), + Word => self.wtr.write_str("[:word:]"), + Xdigit if ast.negated => self.wtr.write_str("[:^xdigit:]"), + Xdigit => self.wtr.write_str("[:xdigit:]"), + } + } + + fn fmt_class_unicode(&mut self, ast: &ast::ClassUnicode) -> fmt::Result { + use ast::ClassUnicodeKind::*; + use ast::ClassUnicodeOpKind::*; + + if ast.negated { + try!(self.wtr.write_str(r"\P")); + } else { + try!(self.wtr.write_str(r"\p")); + } + match ast.kind { + OneLetter(c) => self.wtr.write_char(c), + Named(ref x) => write!(self.wtr, "{{{}}}", x), + NamedValue { op: Equal, ref name, ref value } => { + write!(self.wtr, "{{{}={}}}", name, value) + } + NamedValue { op: Colon, ref name, ref value } => { + write!(self.wtr, "{{{}:{}}}", name, value) + } + NamedValue { op: NotEqual, ref name, ref value } => { + write!(self.wtr, "{{{}!={}}}", name, value) + } + } + } +} + +#[cfg(test)] +mod tests { + use ast::parse::ParserBuilder; + use super::Printer; + + fn roundtrip(given: &str) { + roundtrip_with(|b| b, given); + } + + fn roundtrip_with<F>(mut f: F, given: &str) + where F: FnMut(&mut ParserBuilder) -> &mut ParserBuilder + { + let mut builder = ParserBuilder::new(); + f(&mut builder); + let ast = builder.build().parse(given).unwrap(); + + let mut printer = Printer::new(); + let mut dst = String::new(); + printer.print(&ast, &mut dst).unwrap(); + assert_eq!(given, dst); + } + + #[test] + fn print_literal() { + roundtrip("a"); + roundtrip(r"\["); + roundtrip_with(|b| b.octal(true), r"\141"); + roundtrip(r"\x61"); + roundtrip(r"\x7F"); + roundtrip(r"\u0061"); + roundtrip(r"\U00000061"); + roundtrip(r"\x{61}"); + roundtrip(r"\x{7F}"); + roundtrip(r"\u{61}"); + roundtrip(r"\U{61}"); + + roundtrip(r"\a"); + roundtrip(r"\f"); + roundtrip(r"\t"); + roundtrip(r"\n"); + roundtrip(r"\r"); + roundtrip(r"\v"); + roundtrip(r"(?x)\ "); + } + + #[test] + fn print_dot() { + roundtrip("."); + } + + #[test] + fn print_concat() { + roundtrip("ab"); + roundtrip("abcde"); + roundtrip("a(bcd)ef"); + } + + #[test] + fn print_alternation() { + roundtrip("a|b"); + roundtrip("a|b|c|d|e"); + roundtrip("|a|b|c|d|e"); + roundtrip("|a|b|c|d|e|"); + roundtrip("a(b|c|d)|e|f"); + } + + #[test] + fn print_assertion() { + roundtrip(r"^"); + roundtrip(r"$"); + roundtrip(r"\A"); + roundtrip(r"\z"); + roundtrip(r"\b"); + roundtrip(r"\B"); + } + + #[test] + fn print_repetition() { + roundtrip("a?"); + roundtrip("a??"); + roundtrip("a*"); + roundtrip("a*?"); + roundtrip("a+"); + roundtrip("a+?"); + roundtrip("a{5}"); + roundtrip("a{5}?"); + roundtrip("a{5,}"); + roundtrip("a{5,}?"); + roundtrip("a{5,10}"); + roundtrip("a{5,10}?"); + } + + #[test] + fn print_flags() { + roundtrip("(?i)"); + roundtrip("(?-i)"); + roundtrip("(?s-i)"); + roundtrip("(?-si)"); + roundtrip("(?siUmux)"); + } + + #[test] + fn print_group() { + roundtrip("(?i:a)"); + roundtrip("(?P<foo>a)"); + roundtrip("(a)"); + } + + #[test] + fn print_class() { + roundtrip(r"[abc]"); + roundtrip(r"[a-z]"); + roundtrip(r"[^a-z]"); + roundtrip(r"[a-z0-9]"); + roundtrip(r"[-a-z0-9]"); + roundtrip(r"[-a-z0-9]"); + roundtrip(r"[a-z0-9---]"); + roundtrip(r"[a-z&&m-n]"); + roundtrip(r"[[a-z&&m-n]]"); + roundtrip(r"[a-z--m-n]"); + roundtrip(r"[a-z~~m-n]"); + roundtrip(r"[a-z[0-9]]"); + roundtrip(r"[a-z[^0-9]]"); + + roundtrip(r"\d"); + roundtrip(r"\D"); + roundtrip(r"\s"); + roundtrip(r"\S"); + roundtrip(r"\w"); + roundtrip(r"\W"); + + roundtrip(r"[[:alnum:]]"); + roundtrip(r"[[:^alnum:]]"); + roundtrip(r"[[:alpha:]]"); + roundtrip(r"[[:^alpha:]]"); + roundtrip(r"[[:ascii:]]"); + roundtrip(r"[[:^ascii:]]"); + roundtrip(r"[[:blank:]]"); + roundtrip(r"[[:^blank:]]"); + roundtrip(r"[[:cntrl:]]"); + roundtrip(r"[[:^cntrl:]]"); + roundtrip(r"[[:digit:]]"); + roundtrip(r"[[:^digit:]]"); + roundtrip(r"[[:graph:]]"); + roundtrip(r"[[:^graph:]]"); + roundtrip(r"[[:lower:]]"); + roundtrip(r"[[:^lower:]]"); + roundtrip(r"[[:print:]]"); + roundtrip(r"[[:^print:]]"); + roundtrip(r"[[:punct:]]"); + roundtrip(r"[[:^punct:]]"); + roundtrip(r"[[:space:]]"); + roundtrip(r"[[:^space:]]"); + roundtrip(r"[[:upper:]]"); + roundtrip(r"[[:^upper:]]"); + roundtrip(r"[[:word:]]"); + roundtrip(r"[[:^word:]]"); + roundtrip(r"[[:xdigit:]]"); + roundtrip(r"[[:^xdigit:]]"); + + roundtrip(r"\pL"); + roundtrip(r"\PL"); + roundtrip(r"\p{L}"); + roundtrip(r"\P{L}"); + roundtrip(r"\p{X=Y}"); + roundtrip(r"\P{X=Y}"); + roundtrip(r"\p{X:Y}"); + roundtrip(r"\P{X:Y}"); + roundtrip(r"\p{X!=Y}"); + roundtrip(r"\P{X!=Y}"); + } +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/ast/visitor.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/ast/visitor.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/ast/visitor.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/ast/visitor.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,557 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::fmt; + +use ast::{self, Ast}; + +/// A trait for visiting an abstract syntax tree (AST) in depth first order. +/// +/// The principle aim of this trait is to enable callers to perform case +/// analysis on an abstract syntax tree without necessarily using recursion. +/// In particular, this permits callers to do case analysis with constant stack +/// usage, which can be important since the size of an abstract syntax tree +/// may be proportional to end user input. +/// +/// Typical usage of this trait involves providing an implementation and then +/// running it using the [`visit`](fn.visit.html) function. +/// +/// Note that the abstract syntax tree for a regular expression is quite +/// complex. Unless you specifically need it, you might be able to use the +/// much simpler +/// [high-level intermediate representation](../hir/struct.Hir.html) +/// and its +/// [corresponding `Visitor` trait](../hir/trait.Visitor.html) +/// instead. +pub trait Visitor { + /// The result of visiting an AST. + type Output; + /// An error that visiting an AST might return. + type Err; + + /// All implementors of `Visitor` must provide a `finish` method, which + /// yields the result of visiting the AST or an error. + fn finish(self) -> Result<Self::Output, Self::Err>; + + /// This method is called before beginning traversal of the AST. + fn start(&mut self) {} + + /// This method is called on an `Ast` before descending into child `Ast` + /// nodes. + fn visit_pre(&mut self, _ast: &Ast) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called on an `Ast` after descending all of its child + /// `Ast` nodes. + fn visit_post(&mut self, _ast: &Ast) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called between child nodes of an + /// [`Alternation`](struct.Alternation.html). + fn visit_alternation_in(&mut self) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called on every + /// [`ClassSetItem`](enum.ClassSetItem.html) + /// before descending into child nodes. + fn visit_class_set_item_pre( + &mut self, + _ast: &ast::ClassSetItem, + ) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called on every + /// [`ClassSetItem`](enum.ClassSetItem.html) + /// after descending into child nodes. + fn visit_class_set_item_post( + &mut self, + _ast: &ast::ClassSetItem, + ) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called on every + /// [`ClassSetBinaryOp`](struct.ClassSetBinaryOp.html) + /// before descending into child nodes. + fn visit_class_set_binary_op_pre( + &mut self, + _ast: &ast::ClassSetBinaryOp, + ) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called on every + /// [`ClassSetBinaryOp`](struct.ClassSetBinaryOp.html) + /// after descending into child nodes. + fn visit_class_set_binary_op_post( + &mut self, + _ast: &ast::ClassSetBinaryOp, + ) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called between the left hand and right hand child nodes + /// of a [`ClassSetBinaryOp`](struct.ClassSetBinaryOp.html). + fn visit_class_set_binary_op_in( + &mut self, + _ast: &ast::ClassSetBinaryOp, + ) -> Result<(), Self::Err> { + Ok(()) + } +} + +/// Executes an implementation of `Visitor` in constant stack space. +/// +/// This function will visit every node in the given `Ast` while calling the +/// appropriate methods provided by the +/// [`Visitor`](trait.Visitor.html) trait. +/// +/// The primary use case for this method is when one wants to perform case +/// analysis over an `Ast` without using a stack size proportional to the depth +/// of the `Ast`. Namely, this method will instead use constant stack size, but +/// will use heap space proportional to the size of the `Ast`. This may be +/// desirable in cases where the size of `Ast` is proportional to end user +/// input. +/// +/// If the visitor returns an error at any point, then visiting is stopped and +/// the error is returned. +pub fn visit<V: Visitor>(ast: &Ast, visitor: V) -> Result<V::Output, V::Err> { + HeapVisitor::new().visit(ast, visitor) +} + +/// HeapVisitor visits every item in an `Ast` recursively using constant stack +/// size and a heap size proportional to the size of the `Ast`. +struct HeapVisitor<'a> { + /// A stack of `Ast` nodes. This is roughly analogous to the call stack + /// used in a typical recursive visitor. + stack: Vec<(&'a Ast, Frame<'a>)>, + /// Similar to the `Ast` stack above, but is used only for character + /// classes. In particular, character classes embed their own mini + /// recursive syntax. + stack_class: Vec<(ClassInduct<'a>, ClassFrame<'a>)>, +} + +/// Represents a single stack frame while performing structural induction over +/// an `Ast`. +enum Frame<'a> { + /// A stack frame allocated just before descending into a repetition + /// operator's child node. + Repetition(&'a ast::Repetition), + /// A stack frame allocated just before descending into a group's child + /// node. + Group(&'a ast::Group), + /// The stack frame used while visiting every child node of a concatenation + /// of expressions. + Concat { + /// The child node we are currently visiting. + head: &'a Ast, + /// The remaining child nodes to visit (which may be empty). + tail: &'a [Ast], + }, + /// The stack frame used while visiting every child node of an alternation + /// of expressions. + Alternation { + /// The child node we are currently visiting. + head: &'a Ast, + /// The remaining child nodes to visit (which may be empty). + tail: &'a [Ast], + }, +} + +/// Represents a single stack frame while performing structural induction over +/// a character class. +enum ClassFrame<'a> { + /// The stack frame used while visiting every child node of a union of + /// character class items. + Union { + /// The child node we are currently visiting. + head: &'a ast::ClassSetItem, + /// The remaining child nodes to visit (which may be empty). + tail: &'a [ast::ClassSetItem], + }, + /// The stack frame used while a binary class operation. + Binary { + op: &'a ast::ClassSetBinaryOp, + }, + /// A stack frame allocated just before descending into a binary operator's + /// left hand child node. + BinaryLHS { + op: &'a ast::ClassSetBinaryOp, + lhs: &'a ast::ClassSet, + rhs: &'a ast::ClassSet, + }, + /// A stack frame allocated just before descending into a binary operator's + /// right hand child node. + BinaryRHS { + op: &'a ast::ClassSetBinaryOp, + rhs: &'a ast::ClassSet, + }, +} + +/// A representation of the inductive step when performing structural induction +/// over a character class. +/// +/// Note that there is no analogous explicit type for the inductive step for +/// `Ast` nodes because the inductive step is just an `Ast`. For character +/// classes, the inductive step can produce one of two possible child nodes: +/// an item or a binary operation. (An item cannot be a binary operation +/// because that would imply binary operations can be unioned in the concrete +/// syntax, which is not possible.) +enum ClassInduct<'a> { + Item(&'a ast::ClassSetItem), + BinaryOp(&'a ast::ClassSetBinaryOp), +} + +impl<'a> HeapVisitor<'a> { + fn new() -> HeapVisitor<'a> { + HeapVisitor { stack: vec![], stack_class: vec![] } + } + + fn visit<V: Visitor>( + &mut self, + mut ast: &'a Ast, + mut visitor: V, + ) -> Result<V::Output, V::Err> { + self.stack.clear(); + self.stack_class.clear(); + + visitor.start(); + loop { + try!(visitor.visit_pre(ast)); + if let Some(x) = try!(self.induct(ast, &mut visitor)) { + let child = x.child(); + self.stack.push((ast, x)); + ast = child; + continue; + } + // No induction means we have a base case, so we can post visit + // it now. + try!(visitor.visit_post(ast)); + + // At this point, we now try to pop our call stack until it is + // either empty or we hit another inductive case. + loop { + let (post_ast, frame) = match self.stack.pop() { + None => return visitor.finish(), + Some((post_ast, frame)) => (post_ast, frame), + }; + // If this is a concat/alternate, then we might have additional + // inductive steps to process. + if let Some(x) = self.pop(frame) { + if let Frame::Alternation {..} = x { + try!(visitor.visit_alternation_in()); + } + ast = x.child(); + self.stack.push((post_ast, x)); + break; + } + // Otherwise, we've finished visiting all the child nodes for + // this AST, so we can post visit it now. + try!(visitor.visit_post(post_ast)); + } + } + } + + /// Build a stack frame for the given AST if one is needed (which occurs if + /// and only if there are child nodes in the AST). Otherwise, return None. + /// + /// If this visits a class, then the underlying visitor implementation may + /// return an error which will be passed on here. + fn induct<V: Visitor>( + &mut self, + ast: &'a Ast, + visitor: &mut V, + ) -> Result<Option<Frame<'a>>, V::Err> { + Ok(match *ast { + Ast::Class(ast::Class::Bracketed(ref x)) => { + try!(self.visit_class(x, visitor)); + None + } + Ast::Repetition(ref x) => Some(Frame::Repetition(x)), + Ast::Group(ref x) => Some(Frame::Group(x)), + Ast::Concat(ref x) if x.asts.is_empty() => None, + Ast::Concat(ref x) => { + Some(Frame::Concat { + head: &x.asts[0], + tail: &x.asts[1..], + }) + } + Ast::Alternation(ref x) if x.asts.is_empty() => None, + Ast::Alternation(ref x) => { + Some(Frame::Alternation { + head: &x.asts[0], + tail: &x.asts[1..], + }) + } + _ => None, + }) + } + + /// Pops the given frame. If the frame has an additional inductive step, + /// then return it, otherwise return `None`. + fn pop(&self, induct: Frame<'a>) -> Option<Frame<'a>> { + match induct { + Frame::Repetition(_) => None, + Frame::Group(_) => None, + Frame::Concat { tail, .. } => { + if tail.is_empty() { + None + } else { + Some(Frame::Concat { + head: &tail[0], + tail: &tail[1..], + }) + } + } + Frame::Alternation { tail, .. } => { + if tail.is_empty() { + None + } else { + Some(Frame::Alternation { + head: &tail[0], + tail: &tail[1..], + }) + } + } + } + } + + fn visit_class<V: Visitor>( + &mut self, + ast: &'a ast::ClassBracketed, + visitor: &mut V, + ) -> Result<(), V::Err> { + let mut ast = ClassInduct::from_bracketed(ast); + loop { + try!(self.visit_class_pre(&ast, visitor)); + if let Some(x) = self.induct_class(&ast) { + let child = x.child(); + self.stack_class.push((ast, x)); + ast = child; + continue; + } + try!(self.visit_class_post(&ast, visitor)); + + // At this point, we now try to pop our call stack until it is + // either empty or we hit another inductive case. + loop { + let (post_ast, frame) = match self.stack_class.pop() { + None => return Ok(()), + Some((post_ast, frame)) => (post_ast, frame), + }; + // If this is a union or a binary op, then we might have + // additional inductive steps to process. + if let Some(x) = self.pop_class(frame) { + if let ClassFrame::BinaryRHS { ref op, .. } = x { + try!(visitor.visit_class_set_binary_op_in(op)); + } + ast = x.child(); + self.stack_class.push((post_ast, x)); + break; + } + // Otherwise, we've finished visiting all the child nodes for + // this class node, so we can post visit it now. + try!(self.visit_class_post(&post_ast, visitor)); + } + } + } + + /// Call the appropriate `Visitor` methods given an inductive step. + fn visit_class_pre<V: Visitor>( + &self, + ast: &ClassInduct<'a>, + visitor: &mut V, + ) -> Result<(), V::Err> { + match *ast { + ClassInduct::Item(item) => { + try!(visitor.visit_class_set_item_pre(item)); + } + ClassInduct::BinaryOp(op) => { + try!(visitor.visit_class_set_binary_op_pre(op)); + } + } + Ok(()) + } + + /// Call the appropriate `Visitor` methods given an inductive step. + fn visit_class_post<V: Visitor>( + &self, + ast: &ClassInduct<'a>, + visitor: &mut V, + ) -> Result<(), V::Err> { + match *ast { + ClassInduct::Item(item) => { + try!(visitor.visit_class_set_item_post(item)); + } + ClassInduct::BinaryOp(op) => { + try!(visitor.visit_class_set_binary_op_post(op)); + } + } + Ok(()) + } + + /// Build a stack frame for the given class node if one is needed (which + /// occurs if and only if there are child nodes). Otherwise, return None. + fn induct_class( + &self, + ast: &ClassInduct<'a>, + ) -> Option<ClassFrame<'a>> { + match *ast { + ClassInduct::Item(&ast::ClassSetItem::Bracketed(ref x)) => { + match x.kind { + ast::ClassSet::Item(ref item) => { + Some(ClassFrame::Union { + head: item, + tail: &[], + }) + } + ast::ClassSet::BinaryOp(ref op) => { + Some(ClassFrame::Binary { op: op }) + } + } + } + ClassInduct::Item(&ast::ClassSetItem::Union(ref x)) => { + if x.items.is_empty() { + None + } else { + Some(ClassFrame::Union { + head: &x.items[0], + tail: &x.items[1..], + }) + } + } + ClassInduct::BinaryOp(op) => { + Some(ClassFrame::BinaryLHS { + op: op, + lhs: &op.lhs, + rhs: &op.rhs, + }) + } + _ => None, + } + } + + /// Pops the given frame. If the frame has an additional inductive step, + /// then return it, otherwise return `None`. + fn pop_class(&self, induct: ClassFrame<'a>) -> Option<ClassFrame<'a>> { + match induct { + ClassFrame::Union { tail, .. } => { + if tail.is_empty() { + None + } else { + Some(ClassFrame::Union { + head: &tail[0], + tail: &tail[1..], + }) + } + } + ClassFrame::Binary {..} => None, + ClassFrame::BinaryLHS { op, rhs, .. } => { + Some(ClassFrame::BinaryRHS { + op: op, + rhs: rhs, + }) + } + ClassFrame::BinaryRHS {..} => None, + } + } +} + +impl<'a> Frame<'a> { + /// Perform the next inductive step on this frame and return the next + /// child AST node to visit. + fn child(&self) -> &'a Ast { + match *self { + Frame::Repetition(rep) => &rep.ast, + Frame::Group(group) => &group.ast, + Frame::Concat { head, .. } => head, + Frame::Alternation { head, .. } => head, + } + } +} + +impl<'a> ClassFrame<'a> { + /// Perform the next inductive step on this frame and return the next + /// child class node to visit. + fn child(&self) -> ClassInduct<'a> { + match *self { + ClassFrame::Union { head, .. } => ClassInduct::Item(head), + ClassFrame::Binary { op, .. } => ClassInduct::BinaryOp(op), + ClassFrame::BinaryLHS { ref lhs, .. } => { + ClassInduct::from_set(lhs) + } + ClassFrame::BinaryRHS { ref rhs, .. } => { + ClassInduct::from_set(rhs) + } + } + } +} + +impl<'a> ClassInduct<'a> { + fn from_bracketed(ast: &'a ast::ClassBracketed) -> ClassInduct<'a> { + ClassInduct::from_set(&ast.kind) + } + + fn from_set(ast: &'a ast::ClassSet) -> ClassInduct<'a> { + match *ast { + ast::ClassSet::Item(ref item) => ClassInduct::Item(item), + ast::ClassSet::BinaryOp(ref op) => ClassInduct::BinaryOp(op), + } + } +} + +impl<'a> fmt::Debug for ClassFrame<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let x = match *self { + ClassFrame::Union{..} => "Union", + ClassFrame::Binary{..} => "Binary", + ClassFrame::BinaryLHS{..} => "BinaryLHS", + ClassFrame::BinaryRHS{..} => "BinaryRHS", + }; + write!(f, "{}", x) + } +} + +impl<'a> fmt::Debug for ClassInduct<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let x = match *self { + ClassInduct::Item(it) => { + match *it { + ast::ClassSetItem::Empty(_) => "Item(Empty)", + ast::ClassSetItem::Literal(_) => "Item(Literal)", + ast::ClassSetItem::Range(_) => "Item(Range)", + ast::ClassSetItem::Ascii(_) => "Item(Ascii)", + ast::ClassSetItem::Perl(_) => "Item(Perl)", + ast::ClassSetItem::Unicode(_) => "Item(Unicode)", + ast::ClassSetItem::Bracketed(_) => "Item(Bracketed)", + ast::ClassSetItem::Union(_) => "Item(Union)", + } + } + ClassInduct::BinaryOp(it) => { + match it.kind { + ast::ClassSetBinaryOpKind::Intersection => { + "BinaryOp(Intersection)" + } + ast::ClassSetBinaryOpKind::Difference => { + "BinaryOp(Difference)" + } + ast::ClassSetBinaryOpKind::SymmetricDifference => { + "BinaryOp(SymmetricDifference)" + } + } + } + }; + write!(f, "{}", x) + } +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/either.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/either.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/either.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/either.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,8 @@ +/// A simple binary sum type. +/// +/// This is occasionally useful in an ad hoc fashion. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Either<Left, Right> { + Left(Left), + Right(Right), +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/error.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/error.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/error.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/error.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,278 @@ +use std::cmp; +use std::error; +use std::fmt; +use std::result; + +use ast; +use hir; + +/// A type alias for dealing with errors returned by this crate. +pub type Result<T> = result::Result<T, Error>; + +/// This error type encompasses any error that can be returned by this crate. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Error { + /// An error that occurred while translating concrete syntax into abstract + /// syntax (AST). + Parse(ast::Error), + /// An error that occurred while translating abstract syntax into a high + /// level intermediate representation (HIR). + Translate(hir::Error), + /// Hints that destructuring should not be exhaustive. + /// + /// This enum may grow additional variants, so this makes sure clients + /// don't count on exhaustive matching. (Otherwise, adding a new variant + /// could break existing code.) + #[doc(hidden)] + __Nonexhaustive, +} + +impl From<ast::Error> for Error { + fn from(err: ast::Error) -> Error { + Error::Parse(err) + } +} + +impl From<hir::Error> for Error { + fn from(err: hir::Error) -> Error { + Error::Translate(err) + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::Parse(ref x) => x.description(), + Error::Translate(ref x) => x.description(), + _ => unreachable!(), + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::Parse(ref x) => x.fmt(f), + Error::Translate(ref x) => x.fmt(f), + _ => unreachable!(), + } + } +} + +/// A helper type for formatting nice error messages. +/// +/// This type is responsible for reporting regex parse errors in a nice human +/// readable format. Most of its complexity is from interspersing notational +/// markers pointing out the position where an error occurred. +#[derive(Debug)] +pub struct Formatter<'e, E: 'e> { + /// The original regex pattern in which the error occurred. + pattern: &'e str, + /// The error kind. It must impl fmt::Display. + err: &'e E, + /// The primary span of the error. + span: &'e ast::Span, + /// An auxiliary and optional span, in case the error needs to point to + /// two locations (e.g., when reporting a duplicate capture group name). + aux_span: Option<&'e ast::Span>, +} + +impl<'e> From<&'e ast::Error> for Formatter<'e, ast::ErrorKind> { + fn from(err: &'e ast::Error) -> Self { + Formatter { + pattern: err.pattern(), + err: err.kind(), + span: err.span(), + aux_span: err.auxiliary_span(), + } + } +} + +impl<'e> From<&'e hir::Error> for Formatter<'e, hir::ErrorKind> { + fn from(err: &'e hir::Error) -> Self { + Formatter { + pattern: err.pattern(), + err: err.kind(), + span: err.span(), + aux_span: None, + } + } +} + +impl<'e, E: fmt::Display> fmt::Display for Formatter<'e, E> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let spans = Spans::from_formatter(self); + if self.pattern.contains('\n') { + let divider = repeat_char('~', 79); + + try!(writeln!(f, "regex parse error:")); + try!(writeln!(f, "{}", divider)); + let notated = spans.notate(); + try!(write!(f, "{}", notated)); + try!(writeln!(f, "{}", divider)); + // If we have error spans that cover multiple lines, then we just + // note the line numbers. + if !spans.multi_line.is_empty() { + let mut notes = vec![]; + for span in &spans.multi_line { + notes.push(format!( + "on line {} (column {}) through line {} (column {})", + span.start.line, span.start.column, + span.end.line, span.end.column - 1)); + } + try!(writeln!(f, "{}", notes.join("\n"))); + } + try!(write!(f, "error: {}", self.err)); + } else { + try!(writeln!(f, "regex parse error:")); + let notated = Spans::from_formatter(self).notate(); + try!(write!(f, "{}", notated)); + try!(write!(f, "error: {}", self.err)); + } + Ok(()) + } +} + +/// This type represents an arbitrary number of error spans in a way that makes +/// it convenient to notate the regex pattern. ("Notate" means "point out +/// exactly where the error occurred in the regex pattern.") +/// +/// Technically, we can only ever have two spans given our current error +/// structure. However, after toiling with a specific algorithm for handling +/// two spans, it became obvious that an algorithm to handle an arbitrary +/// number of spans was actually much simpler. +struct Spans<'p> { + /// The original regex pattern string. + pattern: &'p str, + /// The total width that should be used for line numbers. The width is + /// used for left padding the line numbers for alignment. + /// + /// A value of `0` means line numbers should not be displayed. That is, + /// the pattern is itself only one line. + line_number_width: usize, + /// All error spans that occur on a single line. This sequence always has + /// length equivalent to the number of lines in `pattern`, where the index + /// of the sequence represents a line number, starting at `0`. The spans + /// in each line are sorted in ascending order. + by_line: Vec<Vec<ast::Span>>, + /// All error spans that occur over one or more lines. That is, the start + /// and end position of the span have different line numbers. The spans are + /// sorted in ascending order. + multi_line: Vec<ast::Span>, +} + +impl<'p> Spans<'p> { + /// Build a sequence of spans from a formatter. + fn from_formatter<'e, E: fmt::Display>( + fmter: &'p Formatter<'e, E>, + ) -> Spans<'p> { + let line_count = fmter.pattern.lines().count(); + let line_number_width = + if line_count <= 1 { + 0 + } else { + line_count.to_string().len() + }; + let mut spans = Spans { + pattern: &fmter.pattern, + line_number_width: line_number_width, + by_line: vec![vec![]; line_count], + multi_line: vec![], + }; + spans.add(fmter.span.clone()); + if let Some(span) = fmter.aux_span { + spans.add(span.clone()); + } + spans + } + + /// Add the given span to this sequence, putting it in the right place. + fn add(&mut self, span: ast::Span) { + // This is grossly inefficient since we sort after each add, but right + // now, we only ever add two spans at most. + if span.is_one_line() { + let i = span.start.line - 1; // because lines are 1-indexed + self.by_line[i].push(span); + self.by_line[i].sort(); + } else { + self.multi_line.push(span); + self.multi_line.sort(); + } + } + + /// Notate the pattern string with carents (`^`) pointing at each span + /// location. This only applies to spans that occur within a single line. + fn notate(&self) -> String { + let mut notated = String::new(); + for (i, line) in self.pattern.lines().enumerate() { + if self.line_number_width > 0 { + notated.push_str(&self.left_pad_line_number(i + 1)); + notated.push_str(": "); + } else { + notated.push_str(" "); + } + notated.push_str(line); + notated.push('\n'); + if let Some(notes) = self.notate_line(i) { + notated.push_str(¬es); + notated.push('\n'); + } + } + notated + } + + /// Return notes for the line indexed at `i` (zero-based). If there are no + /// spans for the given line, then `None` is returned. Otherwise, an + /// appropriately space padded string with correctly positioned `^` is + /// returned, accounting for line numbers. + fn notate_line(&self, i: usize) -> Option<String> { + let spans = &self.by_line[i]; + if spans.is_empty() { + return None; + } + let mut notes = String::new(); + for _ in 0..self.line_number_padding() { + notes.push(' '); + } + let mut pos = 0; + for span in spans { + for _ in pos..(span.start.column - 1) { + notes.push(' '); + pos += 1; + } + let note_len = span.end.column.saturating_sub(span.start.column); + for _ in 0..cmp::max(1, note_len) { + notes.push('^'); + pos += 1; + } + } + Some(notes) + } + + /// Left pad the given line number with spaces such that it is aligned with + /// other line numbers. + fn left_pad_line_number(&self, n: usize) -> String { + let n = n.to_string(); + let pad = self.line_number_width.checked_sub(n.len()).unwrap(); + let mut result = repeat_char(' ', pad); + result.push_str(&n); + result + } + + /// Return the line number padding beginning at the start of each line of + /// the pattern. + /// + /// If the pattern is only one line, then this returns a fixed padding + /// for visual indentation. + fn line_number_padding(&self) -> usize { + if self.line_number_width == 0 { + 4 + } else { + 2 + self.line_number_width + } + } +} + +fn repeat_char(c: char, count: usize) -> String { + ::std::iter::repeat(c).take(count).collect() +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/hir/interval.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/hir/interval.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/hir/interval.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/hir/interval.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,490 @@ +use std::char; +use std::cmp; +use std::fmt::Debug; +use std::slice; +use std::u8; + +// This module contains an *internal* implementation of interval sets. +// +// The primary invariant that interval sets guards is canonical ordering. That +// is, every interval set contains an ordered sequence of intervals where +// no two intervals are overlapping or adjacent. While this invariant is +// ocassionally broken within the implementation, it should be impossible for +// callers to observe it. +// +// Since case folding (as implemented below) breaks that invariant, we roll +// that into this API even though it is a little out of place in an otherwise +// generic interval set. +// +// Some of the implementation complexity here is a result of me wanting to +// preserve the sequential representation without using additional memory. +// In many cases, we do use linear extra memory, but it is at most 2x and it +// is amortized. If we relaxed the memory requirements, this implementation +// could become much simpler. The extra memory is honestly probably OK, but +// character classes (especially of the Unicode variety) can become quite +// large, and it would be nice to keep regex compilation snappy even in debug +// builds. (In the past, I have been careless with this area of code and it has +// caused slow regex compilations in debug mode, so this isn't entirely +// unwarranted.) +// +// Tests on this are relegated to the public API of HIR in src/hir.rs. + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct IntervalSet<I> { + ranges: Vec<I>, +} + +impl<I: Interval> IntervalSet<I> { + /// Create a new set from a sequence of intervals. Each interval is + /// specified as a pair of bounds, where both bounds are inclusive. + /// + /// The given ranges do not need to be in any specific order, and ranges + /// may overlap. + pub fn new<T: IntoIterator<Item=I>>(intervals: T) -> IntervalSet<I> { + let mut set = IntervalSet { ranges: intervals.into_iter().collect() }; + set.canonicalize(); + set + } + + /// Add a new interval to this set. + pub fn push(&mut self, interval: I) { + // TODO: This could be faster. e.g., Push the interval such that + // it preserves canonicalization. + self.ranges.push(interval); + self.canonicalize(); + } + + /// Return an iterator over all intervals in this set. + /// + /// The iterator yields intervals in ascending order. + pub fn iter(&self) -> IntervalSetIter<I> { + IntervalSetIter(self.ranges.iter()) + } + + /// Return an immutable slice of intervals in this set. + /// + /// The sequence returned is in canonical ordering. + pub fn intervals(&self) -> &[I] { + &self.ranges + } + + /// Expand this interval set such that it contains all case folded + /// characters. For example, if this class consists of the range `a-z`, + /// then applying case folding will result in the class containing both the + /// ranges `a-z` and `A-Z`. + pub fn case_fold_simple(&mut self) { + let len = self.ranges.len(); + for i in 0..len { + let range = self.ranges[i]; + range.case_fold_simple(&mut self.ranges); + } + self.canonicalize(); + } + + /// Union this set with the given set, in place. + pub fn union(&mut self, other: &IntervalSet<I>) { + // This could almost certainly be done more efficiently. + self.ranges.extend(&other.ranges); + self.canonicalize(); + } + + /// Intersect this set with the given set, in place. + pub fn intersect(&mut self, other: &IntervalSet<I>) { + if self.ranges.is_empty() { + return; + } + if other.ranges.is_empty() { + self.ranges.clear(); + return; + } + + // There should be a way to do this in-place with constant memory, + // but I couldn't figure out a simple way to do it. So just append + // the intersection to the end of this range, and then drain it before + // we're done. + let drain_end = self.ranges.len(); + + let mut ita = (0..drain_end).into_iter(); + let mut itb = (0..other.ranges.len()).into_iter(); + let mut a = ita.next().unwrap(); + let mut b = itb.next().unwrap(); + loop { + if let Some(ab) = self.ranges[a].intersect(&other.ranges[b]) { + self.ranges.push(ab); + } + let (it, aorb) = + if self.ranges[a].upper() < other.ranges[b].upper() { + (&mut ita, &mut a) + } else { + (&mut itb, &mut b) + }; + match it.next() { + Some(v) => *aorb = v, + None => break, + } + } + self.ranges.drain(..drain_end); + } + + /// Subtract the given set from this set, in place. + pub fn difference(&mut self, other: &IntervalSet<I>) { + if self.ranges.is_empty() || other.ranges.is_empty() { + return; + } + + // This algorithm is (to me) surprisingly complex. A search of the + // interwebs indicate that this is a potentially interesting problem. + // Folks seem to suggest interval or segment trees, but I'd like to + // avoid the overhead (both runtime and conceptual) of that. + // + // The following is basically my Shitty First Draft. Therefore, in + // order to grok it, you probably need to read each line carefully. + // Simplifications are most welcome! + // + // Remember, we can assume the canonical format invariant here, which + // says that all ranges are sorted, not overlapping and not adjacent in + // each class. + let drain_end = self.ranges.len(); + let (mut a, mut b) = (0, 0); + 'LOOP: + while a < drain_end && b < other.ranges.len() { + // Basically, the easy cases are when neither range overlaps with + // each other. If the `b` range is less than our current `a` + // range, then we can skip it and move on. + if other.ranges[b].upper() < self.ranges[a].lower() { + b += 1; + continue; + } + // ... similarly for the `a` range. If it's less than the smallest + // `b` range, then we can add it as-is. + if self.ranges[a].upper() < other.ranges[b].lower() { + let range = self.ranges[a]; + self.ranges.push(range); + a += 1; + continue; + } + // Otherwise, we have overlapping ranges. + assert!(!self.ranges[a].is_intersection_empty(&other.ranges[b])); + + // This part is tricky and was non-obvious to me without looking + // at explicit examples (see the tests). The trickiness stems from + // two things: 1) subtracting a range from another range could + // yield two ranges and 2) after subtracting a range, it's possible + // that future ranges can have an impact. The loop below advances + // the `b` ranges until they can't possible impact the current + // range. + // + // For example, if our `a` range is `a-t` and our next three `b` + // ranges are `a-c`, `g-i`, `r-t` and `x-z`, then we need to apply + // subtraction three times before moving on to the next `a` range. + let mut range = self.ranges[a]; + while b < other.ranges.len() + && !range.is_intersection_empty(&other.ranges[b]) + { + let old_range = range; + range = match range.difference(&other.ranges[b]) { + (None, None) => { + // We lost the entire range, so move on to the next + // without adding this one. + a += 1; + continue 'LOOP; + } + (Some(range1), None) | (None, Some(range1)) => range1, + (Some(range1), Some(range2)) => { + self.ranges.push(range1); + range2 + } + }; + // It's possible that the `b` range has more to contribute + // here. In particular, if it is greater than the original + // range, then it might impact the next `a` range *and* it + // has impacted the current `a` range as much as possible, + // so we can quit. We don't bump `b` so that the next `a` + // range can apply it. + if other.ranges[b].upper() > old_range.upper() { + break; + } + // Otherwise, the next `b` range might apply to the current + // `a` range. + b += 1; + } + self.ranges.push(range); + a += 1; + } + while a < drain_end { + let range = self.ranges[a]; + self.ranges.push(range); + a += 1; + } + self.ranges.drain(..drain_end); + } + + /// Compute the symmetric difference of the two sets, in place. + /// + /// This computes the symmetric difference of two interval sets. This + /// removes all elements in this set that are also in the given set, + /// but also adds all elements from the given set that aren't in this + /// set. That is, the set will contain all elements in either set, + /// but will not contain any elements that are in both sets. + pub fn symmetric_difference(&mut self, other: &IntervalSet<I>) { + // TODO(burntsushi): Fix this so that it amortizes allocation. + let mut intersection = self.clone(); + intersection.intersect(other); + self.union(other); + self.difference(&intersection); + } + + /// Negate this interval set. + /// + /// For all `x` where `x` is any element, if `x` was in this set, then it + /// will not be in this set after negation. + pub fn negate(&mut self) { + if self.ranges.is_empty() { + let (min, max) = (I::Bound::min_value(), I::Bound::max_value()); + self.ranges.push(I::create(min, max)); + return; + } + + // There should be a way to do this in-place with constant memory, + // but I couldn't figure out a simple way to do it. So just append + // the negation to the end of this range, and then drain it before + // we're done. + let drain_end = self.ranges.len(); + + // We do checked arithmetic below because of the canonical ordering + // invariant. + if self.ranges[0].lower() > I::Bound::min_value() { + let upper = self.ranges[0].lower().decrement(); + self.ranges.push(I::create(I::Bound::min_value(), upper)); + } + for i in 1..drain_end { + let lower = self.ranges[i - 1].upper().increment(); + let upper = self.ranges[i].lower().decrement(); + self.ranges.push(I::create(lower, upper)); + } + if self.ranges[drain_end - 1].upper() < I::Bound::max_value() { + let lower = self.ranges[drain_end - 1].upper().increment(); + self.ranges.push(I::create(lower, I::Bound::max_value())); + } + self.ranges.drain(..drain_end); + } + + /// Converts this set into a canonical ordering. + fn canonicalize(&mut self) { + if self.is_canonical() { + return; + } + self.ranges.sort(); + assert!(!self.ranges.is_empty()); + + // Is there a way to do this in-place with constant memory? I couldn't + // figure out a way to do it. So just append the canonicalization to + // the end of this range, and then drain it before we're done. + let drain_end = self.ranges.len(); + for oldi in 0..drain_end { + // If we've added at least one new range, then check if we can + // merge this range in the previously added range. + if self.ranges.len() > drain_end { + let (last, rest) = self.ranges.split_last_mut().unwrap(); + if let Some(union) = last.union(&rest[oldi]) { + *last = union; + continue; + } + } + let range = self.ranges[oldi]; + self.ranges.push(range); + } + self.ranges.drain(..drain_end); + } + + /// Returns true if and only if this class is in a canonical ordering. + fn is_canonical(&self) -> bool { + for pair in self.ranges.windows(2) { + if pair[0] >= pair[1] { + return false; + } + if pair[0].is_contiguous(&pair[1]) { + return false; + } + } + true + } +} + +/// An iterator over intervals. +#[derive(Debug)] +pub struct IntervalSetIter<'a, I: 'a>(slice::Iter<'a, I>); + +impl<'a, I> Iterator for IntervalSetIter<'a, I> { + type Item = &'a I; + + fn next(&mut self) -> Option<&'a I> { + self.0.next() + } +} + +pub trait Interval: + Clone + Copy + Debug + Default + Eq + PartialEq + PartialOrd + Ord +{ + type Bound: Bound; + + fn lower(&self) -> Self::Bound; + fn upper(&self) -> Self::Bound; + fn set_lower(&mut self, bound: Self::Bound); + fn set_upper(&mut self, bound: Self::Bound); + fn case_fold_simple(&self, intervals: &mut Vec<Self>); + + /// Create a new interval. + fn create(lower: Self::Bound, upper: Self::Bound) -> Self { + let mut int = Self::default(); + if lower <= upper { + int.set_lower(lower); + int.set_upper(upper); + } else { + int.set_lower(upper); + int.set_upper(lower); + } + int + } + + /// Union the given overlapping range into this range. + /// + /// If the two ranges aren't contiguous, then this returns `None`. + fn union(&self, other: &Self) -> Option<Self> { + if !self.is_contiguous(other) { + return None; + } + let lower = cmp::min(self.lower(), other.lower()); + let upper = cmp::max(self.upper(), other.upper()); + Some(Self::create(lower, upper)) + } + + /// Intersect this range with the given range and return the result. + /// + /// If the intersection is empty, then this returns `None`. + fn intersect(&self, other: &Self) -> Option<Self> { + let lower = cmp::max(self.lower(), other.lower()); + let upper = cmp::min(self.upper(), other.upper()); + if lower <= upper { + Some(Self::create(lower, upper)) + } else { + None + } + } + + /// Subtract the given range from this range and return the resulting + /// ranges. + /// + /// If subtraction would result in an empty range, then no ranges are + /// returned. + fn difference(&self, other: &Self) -> (Option<Self>, Option<Self>) { + if self.is_subset(other) { + return (None, None); + } + if self.is_intersection_empty(other) { + return (Some(self.clone()), None); + } + let add_lower = other.lower() > self.lower(); + let add_upper = other.upper() < self.upper(); + // We know this because !self.is_subset(other) and the ranges have + // a non-empty intersection. + assert!(add_lower || add_upper); + let mut ret = (None, None); + if add_lower { + let upper = other.lower().decrement(); + ret.0 = Some(Self::create(self.lower(), upper)); + } + if add_upper { + let lower = other.upper().increment(); + let range = Self::create(lower, self.upper()); + if ret.0.is_none() { + ret.0 = Some(range); + } else { + ret.1 = Some(range); + } + } + ret + } + + /// Compute the symmetric difference the given range from this range. This + /// returns the union of the two ranges minus its intersection. + fn symmetric_difference( + &self, + other: &Self, + ) -> (Option<Self>, Option<Self>) { + let union = match self.union(other) { + None => return (Some(self.clone()), Some(other.clone())), + Some(union) => union, + }; + let intersection = match self.intersect(other) { + None => return (Some(self.clone()), Some(other.clone())), + Some(intersection) => intersection, + }; + union.difference(&intersection) + } + + /// Returns true if and only if the two ranges are contiguous. Two ranges + /// are contiguous if and only if the ranges are either overlapping or + /// adjacent. + fn is_contiguous(&self, other: &Self) -> bool { + let lower1 = self.lower().as_u32(); + let upper1 = self.upper().as_u32(); + let lower2 = other.lower().as_u32(); + let upper2 = other.upper().as_u32(); + cmp::max(lower1, lower2) <= cmp::min(upper1, upper2).saturating_add(1) + } + + /// Returns true if and only if the intersection of this range and the + /// other range is empty. + fn is_intersection_empty(&self, other: &Self) -> bool { + let (lower1, upper1) = (self.lower(), self.upper()); + let (lower2, upper2) = (other.lower(), other.upper()); + cmp::max(lower1, lower2) > cmp::min(upper1, upper2) + } + + /// Returns true if and only if this range is a subset of the other range. + fn is_subset(&self, other: &Self) -> bool { + let (lower1, upper1) = (self.lower(), self.upper()); + let (lower2, upper2) = (other.lower(), other.upper()); + (lower2 <= lower1 && lower1 <= upper2) + && (lower2 <= upper1 && upper1 <= upper2) + } +} + +pub trait Bound: Copy + Clone + Debug + Eq + PartialEq + PartialOrd + Ord { + fn min_value() -> Self; + fn max_value() -> Self; + fn as_u32(self) -> u32; + fn increment(self) -> Self; + fn decrement(self) -> Self; +} + +impl Bound for u8 { + fn min_value() -> Self { u8::MIN } + fn max_value() -> Self { u8::MAX } + fn as_u32(self) -> u32 { self as u32 } + fn increment(self) -> Self { self.checked_add(1).unwrap() } + fn decrement(self) -> Self { self.checked_sub(1).unwrap() } +} + +impl Bound for char { + fn min_value() -> Self { '\x00' } + fn max_value() -> Self { '\u{10FFFF}' } + fn as_u32(self) -> u32 { self as u32 } + + fn increment(self) -> Self { + match self { + '\u{D7FF}' => '\u{E000}', + c => char::from_u32((c as u32).checked_add(1).unwrap()).unwrap(), + } + } + + fn decrement(self) -> Self { + match self { + '\u{E000}' => '\u{D7FF}', + c => char::from_u32((c as u32).checked_sub(1).unwrap()).unwrap(), + } + } +} + +// Tests for interval sets are written in src/hir.rs against the public API. diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/hir/literal/mod.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/hir/literal/mod.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/hir/literal/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/hir/literal/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1553 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +Provides routines for extracting literal prefixes and suffixes from an `Hir`. +*/ + +use std::cmp; +use std::fmt; +use std::iter; +use std::mem; +use std::ops; + +use hir::{self, Hir, HirKind}; +use unicode; + +/// A set of literal byte strings extracted from a regular expression. +/// +/// Every member of the set is a `Literal`, which is represented by a +/// `Vec<u8>`. (Notably, it may contain invalid UTF-8.) Every member is +/// said to be either *complete* or *cut*. A complete literal means that +/// it extends until the beginning (or end) of the regular expression. In +/// some circumstances, this can be used to indicate a match in the regular +/// expression. +/// +/// A key aspect of literal extraction is knowing when to stop. It is not +/// feasible to blindly extract all literals from a regular expression, even if +/// there are finitely many. For example, the regular expression `[0-9]{10}` +/// has `10^10` distinct literals. For this reason, literal extraction is +/// bounded to some low number by default using heuristics, but the limits can +/// be tweaked. +/// +/// **WARNING**: Literal extraction uses stack space proportional to the size +/// of the `Hir` expression. At some point, this drawback will be eliminated. +/// To protect yourself, set a reasonable +/// [`nest_limit` on your `Parser`](../../struct.ParserBuilder.html#method.nest_limit). +/// This is done for you by default. +#[derive(Clone, Eq, PartialEq)] +pub struct Literals { + lits: Vec<Literal>, + limit_size: usize, + limit_class: usize, +} + +/// A single member of a set of literals extracted from a regular expression. +/// +/// This type has `Deref` and `DerefMut` impls to `Vec<u8>` so that all slice +/// and `Vec` operations are available. +#[derive(Clone, Eq, Ord)] +pub struct Literal { + v: Vec<u8>, + cut: bool, +} + +impl Literals { + /// Returns a new empty set of literals using default limits. + pub fn empty() -> Literals { + Literals { + lits: vec![], + limit_size: 250, + limit_class: 10, + } + } + + /// Returns a set of literal prefixes extracted from the given `Hir`. + pub fn prefixes(expr: &Hir) -> Literals { + let mut lits = Literals::empty(); + lits.union_prefixes(expr); + lits + } + + /// Returns a set of literal suffixes extracted from the given `Hir`. + pub fn suffixes(expr: &Hir) -> Literals { + let mut lits = Literals::empty(); + lits.union_suffixes(expr); + lits + } + + /// Get the approximate size limit (in bytes) of this set. + pub fn limit_size(&self) -> usize { + self.limit_size + } + + /// Set the approximate size limit (in bytes) of this set. + /// + /// If extracting a literal would put the set over this limit, then + /// extraction stops. + /// + /// The new limits will only apply to additions to this set. Existing + /// members remain unchanged, even if the set exceeds the new limit. + pub fn set_limit_size(&mut self, size: usize) -> &mut Literals { + self.limit_size = size; + self + } + + /// Get the character class size limit for this set. + pub fn limit_class(&self) -> usize { + self.limit_class + } + + /// Limits the size of character(or byte) classes considered. + /// + /// A value of `0` prevents all character classes from being considered. + /// + /// This limit also applies to case insensitive literals, since each + /// character in the case insensitive literal is converted to a class, and + /// then case folded. + /// + /// The new limits will only apply to additions to this set. Existing + /// members remain unchanged, even if the set exceeds the new limit. + pub fn set_limit_class(&mut self, size: usize) -> &mut Literals { + self.limit_class = size; + self + } + + /// Returns the set of literals as a slice. Its order is unspecified. + pub fn literals(&self) -> &[Literal] { + &self.lits + } + + /// Returns the length of the smallest literal. + /// + /// Returns None is there are no literals in the set. + pub fn min_len(&self) -> Option<usize> { + let mut min = None; + for lit in &self.lits { + match min { + None => min = Some(lit.len()), + Some(m) if lit.len() < m => min = Some(lit.len()), + _ => {} + } + } + min + } + + /// Returns true if all members in this set are complete. + pub fn all_complete(&self) -> bool { + !self.lits.is_empty() && self.lits.iter().all(|l| !l.is_cut()) + } + + /// Returns true if any member in this set is complete. + pub fn any_complete(&self) -> bool { + self.lits.iter().any(|lit| !lit.is_cut()) + } + + /// Returns true if this set contains an empty literal. + pub fn contains_empty(&self) -> bool { + self.lits.iter().any(|lit| lit.is_empty()) + } + + /// Returns true if this set is empty or if all of its members is empty. + pub fn is_empty(&self) -> bool { + self.lits.is_empty() || self.lits.iter().all(|lit| lit.is_empty()) + } + + /// Returns a new empty set of literals using this set's limits. + pub fn to_empty(&self) -> Literals { + let mut lits = Literals::empty(); + lits.set_limit_size(self.limit_size) + .set_limit_class(self.limit_class); + lits + } + + /// Returns the longest common prefix of all members in this set. + pub fn longest_common_prefix(&self) -> &[u8] { + if self.is_empty() { + return &[]; + } + let lit0 = &*self.lits[0]; + let mut len = lit0.len(); + for lit in &self.lits[1..] { + len = cmp::min( + len, + lit.iter() + .zip(lit0) + .take_while(|&(a, b)| a == b) + .count()); + } + &self.lits[0][..len] + } + + /// Returns the longest common suffix of all members in this set. + pub fn longest_common_suffix(&self) -> &[u8] { + if self.is_empty() { + return &[]; + } + let lit0 = &*self.lits[0]; + let mut len = lit0.len(); + for lit in &self.lits[1..] { + len = cmp::min( + len, + lit.iter() + .rev() + .zip(lit0.iter().rev()) + .take_while(|&(a, b)| a == b) + .count()); + } + &self.lits[0][self.lits[0].len() - len..] + } + + /// Returns a new set of literals with the given number of bytes trimmed + /// from the suffix of each literal. + /// + /// If any literal would be cut out completely by trimming, then None is + /// returned. + /// + /// Any duplicates that are created as a result of this transformation are + /// removed. + pub fn trim_suffix(&self, num_bytes: usize) -> Option<Literals> { + if self.min_len().map(|len| len <= num_bytes).unwrap_or(true) { + return None; + } + let mut new = self.to_empty(); + for mut lit in self.lits.iter().cloned() { + let new_len = lit.len() - num_bytes; + lit.truncate(new_len); + lit.cut(); + new.lits.push(lit); + } + new.lits.sort(); + new.lits.dedup(); + Some(new) + } + + /// Returns a new set of prefixes of this set of literals that are + /// guaranteed to be unambiguous. + /// + /// Any substring match with a member of the set is returned is guaranteed + /// to never overlap with a substring match of another member of the set + /// at the same starting position. + /// + /// Given any two members of the returned set, neither is a substring of + /// the other. + pub fn unambiguous_prefixes(&self) -> Literals { + if self.lits.is_empty() { + return self.to_empty(); + } + let mut old: Vec<Literal> = self.lits.iter().cloned().collect(); + let mut new = self.to_empty(); + 'OUTER: + while let Some(mut candidate) = old.pop() { + if candidate.is_empty() { + continue; + } + if new.lits.is_empty() { + new.lits.push(candidate); + continue; + } + for lit2 in &mut new.lits { + if lit2.is_empty() { + continue; + } + if &candidate == lit2 { + // If the literal is already in the set, then we can + // just drop it. But make sure that cut literals are + // infectious! + candidate.cut = candidate.cut || lit2.cut; + lit2.cut = candidate.cut; + continue 'OUTER; + } + if candidate.len() < lit2.len() { + if let Some(i) = position(&candidate, &lit2) { + candidate.cut(); + let mut lit3 = lit2.clone(); + lit3.truncate(i); + lit3.cut(); + old.push(lit3); + lit2.clear(); + } + } else { + if let Some(i) = position(&lit2, &candidate) { + lit2.cut(); + let mut new_candidate = candidate.clone(); + new_candidate.truncate(i); + new_candidate.cut(); + old.push(new_candidate); + candidate.clear(); + } + } + // Oops, the candidate is already represented in the set. + if candidate.is_empty() { + continue 'OUTER; + } + } + new.lits.push(candidate); + } + new.lits.retain(|lit| !lit.is_empty()); + new.lits.sort(); + new.lits.dedup(); + new + } + + /// Returns a new set of suffixes of this set of literals that are + /// guaranteed to be unambiguous. + /// + /// Any substring match with a member of the set is returned is guaranteed + /// to never overlap with a substring match of another member of the set + /// at the same ending position. + /// + /// Given any two members of the returned set, neither is a substring of + /// the other. + pub fn unambiguous_suffixes(&self) -> Literals { + // This is a touch wasteful... + let mut lits = self.clone(); + lits.reverse(); + let mut unamb = lits.unambiguous_prefixes(); + unamb.reverse(); + unamb + } + + /// Unions the prefixes from the given expression to this set. + /// + /// If prefixes could not be added (for example, this set would exceed its + /// size limits or the set of prefixes from `expr` includes the empty + /// string), then false is returned. + /// + /// Note that prefix literals extracted from `expr` are said to be complete + /// if and only if the literal extends from the beginning of `expr` to the + /// end of `expr`. + pub fn union_prefixes(&mut self, expr: &Hir) -> bool { + let mut lits = self.to_empty(); + prefixes(expr, &mut lits); + !lits.is_empty() && !lits.contains_empty() && self.union(lits) + } + + /// Unions the suffixes from the given expression to this set. + /// + /// If suffixes could not be added (for example, this set would exceed its + /// size limits or the set of suffixes from `expr` includes the empty + /// string), then false is returned. + /// + /// Note that prefix literals extracted from `expr` are said to be complete + /// if and only if the literal extends from the end of `expr` to the + /// beginning of `expr`. + pub fn union_suffixes(&mut self, expr: &Hir) -> bool { + let mut lits = self.to_empty(); + suffixes(expr, &mut lits); + lits.reverse(); + !lits.is_empty() && !lits.contains_empty() && self.union(lits) + } + + /// Unions this set with another set. + /// + /// If the union would cause the set to exceed its limits, then the union + /// is skipped and it returns false. Otherwise, if the union succeeds, it + /// returns true. + pub fn union(&mut self, lits: Literals) -> bool { + if self.num_bytes() + lits.num_bytes() > self.limit_size { + return false; + } + if lits.is_empty() { + self.lits.push(Literal::empty()); + } else { + self.lits.extend(lits.lits); + } + true + } + + /// Extends this set with another set. + /// + /// The set of literals is extended via a cross product. + /// + /// If a cross product would cause this set to exceed its limits, then the + /// cross product is skipped and it returns false. Otherwise, if the cross + /// product succeeds, it returns true. + pub fn cross_product(&mut self, lits: &Literals) -> bool { + if lits.is_empty() { + return true; + } + // Check that we make sure we stay in our limits. + let mut size_after; + if self.is_empty() || !self.any_complete() { + size_after = self.num_bytes(); + for lits_lit in lits.literals() { + size_after += lits_lit.len(); + } + } else { + size_after = self.lits.iter().fold(0, |accum, lit| { + accum + if lit.is_cut() { lit.len() } else { 0 } + }); + for lits_lit in lits.literals() { + for self_lit in self.literals() { + if !self_lit.is_cut() { + size_after += self_lit.len() + lits_lit.len(); + } + } + } + } + if size_after > self.limit_size { + return false; + } + + let mut base = self.remove_complete(); + if base.is_empty() { + base = vec![Literal::empty()]; + } + for lits_lit in lits.literals() { + for mut self_lit in base.clone() { + self_lit.extend(&**lits_lit); + self_lit.cut = lits_lit.cut; + self.lits.push(self_lit); + } + } + true + } + + /// Extends each literal in this set with the bytes given. + /// + /// If the set is empty, then the given literal is added to the set. + /// + /// If adding any number of bytes to all members of this set causes a limit + /// to be exceeded, then no bytes are added and false is returned. If a + /// prefix of `bytes` can be fit into this set, then it is used and all + /// resulting literals are cut. + pub fn cross_add(&mut self, bytes: &[u8]) -> bool { + // N.B. This could be implemented by simply calling cross_product with + // a literal set containing just `bytes`, but we can be smarter about + // taking shorter prefixes of `bytes` if they'll fit. + if bytes.is_empty() { + return true; + } + if self.lits.is_empty() { + let i = cmp::min(self.limit_size, bytes.len()); + self.lits.push(Literal::new(bytes[..i].to_owned())); + self.lits[0].cut = i < bytes.len(); + return !self.lits[0].is_cut(); + } + let size = self.num_bytes(); + if size + self.lits.len() >= self.limit_size { + return false; + } + let mut i = 1; + while size + (i * self.lits.len()) <= self.limit_size + && i < bytes.len() { + i += 1; + } + for lit in &mut self.lits { + if !lit.is_cut() { + lit.extend(&bytes[..i]); + if i < bytes.len() { + lit.cut(); + } + } + } + true + } + + /// Adds the given literal to this set. + /// + /// Returns false if adding this literal would cause the class to be too + /// big. + pub fn add(&mut self, lit: Literal) -> bool { + if self.num_bytes() + lit.len() > self.limit_size { + return false; + } + self.lits.push(lit); + true + } + + /// Extends each literal in this set with the character class given. + /// + /// Returns false if the character class was too big to add. + pub fn add_char_class(&mut self, cls: &hir::ClassUnicode) -> bool { + self._add_char_class(cls, false) + } + + /// Extends each literal in this set with the character class given, + /// writing the bytes of each character in reverse. + /// + /// Returns false if the character class was too big to add. + fn add_char_class_reverse(&mut self, cls: &hir::ClassUnicode) -> bool { + self._add_char_class(cls, true) + } + + fn _add_char_class( + &mut self, + cls: &hir::ClassUnicode, + reverse: bool, + ) -> bool { + use std::char; + + if self.class_exceeds_limits(cls_char_count(cls)) { + return false; + } + let mut base = self.remove_complete(); + if base.is_empty() { + base = vec![Literal::empty()]; + } + for r in cls.iter() { + let (s, e) = (r.start as u32, r.end as u32 + 1); + for c in (s..e).filter_map(char::from_u32) { + for mut lit in base.clone() { + let mut bytes = c.to_string().into_bytes(); + if reverse { + bytes.reverse(); + } + lit.extend(&bytes); + self.lits.push(lit); + } + } + } + true + } + + /// Extends each literal in this set with the byte class given. + /// + /// Returns false if the byte class was too big to add. + pub fn add_byte_class(&mut self, cls: &hir::ClassBytes) -> bool { + if self.class_exceeds_limits(cls_byte_count(cls)) { + return false; + } + let mut base = self.remove_complete(); + if base.is_empty() { + base = vec![Literal::empty()]; + } + for r in cls.iter() { + let (s, e) = (r.start as u32, r.end as u32 + 1); + for b in (s..e).map(|b| b as u8) { + for mut lit in base.clone() { + lit.push(b); + self.lits.push(lit); + } + } + } + true + } + + /// Cuts every member of this set. When a member is cut, it can never + /// be extended. + pub fn cut(&mut self) { + for lit in &mut self.lits { + lit.cut(); + } + } + + /// Reverses all members in place. + pub fn reverse(&mut self) { + for lit in &mut self.lits { + lit.reverse(); + } + } + + /// Clears this set of all members. + pub fn clear(&mut self) { + self.lits.clear(); + } + + /// Pops all complete literals out of this set. + fn remove_complete(&mut self) -> Vec<Literal> { + let mut base = vec![]; + for lit in mem::replace(&mut self.lits, vec![]) { + if lit.is_cut() { + self.lits.push(lit); + } else { + base.push(lit); + } + } + base + } + + /// Returns the total number of bytes in this set. + fn num_bytes(&self) -> usize { + self.lits.iter().fold(0, |accum, lit| accum + lit.len()) + } + + /// Returns true if a character class with the given size would cause this + /// set to exceed its limits. + /// + /// The size given should correspond to the number of items in the class. + fn class_exceeds_limits(&self, size: usize) -> bool { + if size > self.limit_class { + return true; + } + // This is an approximation since codepoints in a char class can encode + // to 1-4 bytes. + let new_byte_count = + if self.lits.is_empty() { + size + } else { + self.lits + .iter() + .fold(0, |accum, lit| { + accum + if lit.is_cut() { + // If the literal is cut, then we'll never add + // anything to it, so don't count it. + 0 + } else { + (lit.len() + 1) * size + } + }) + }; + new_byte_count > self.limit_size + } +} + +fn prefixes(expr: &Hir, lits: &mut Literals) { + match *expr.kind() { + HirKind::Literal(hir::Literal::Unicode(c)) => { + let mut buf = [0u8; 4]; + let i = unicode::encode_utf8(c, &mut buf).unwrap(); + lits.cross_add(&buf[..i]); + } + HirKind::Literal(hir::Literal::Byte(b)) => { + lits.cross_add(&[b]); + } + HirKind::Class(hir::Class::Unicode(ref cls)) => { + if !lits.add_char_class(cls) { + lits.cut(); + } + } + HirKind::Class(hir::Class::Bytes(ref cls)) => { + if !lits.add_byte_class(cls) { + lits.cut(); + } + } + HirKind::Group(hir::Group { ref hir, .. }) => { + prefixes(&**hir, lits); + } + HirKind::Repetition(ref x) => { + match x.kind { + hir::RepetitionKind::ZeroOrOne => { + repeat_zero_or_one_literals(&x.hir, lits, prefixes); + } + hir::RepetitionKind::ZeroOrMore => { + repeat_zero_or_more_literals(&x.hir, lits, prefixes); + } + hir::RepetitionKind::OneOrMore => { + repeat_one_or_more_literals(&x.hir, lits, prefixes); + } + hir::RepetitionKind::Range(ref rng) => { + let (min, max) = match *rng { + hir::RepetitionRange::Exactly(m) => { + (m, Some(m)) + } + hir::RepetitionRange::AtLeast(m) => { + (m, None) + } + hir::RepetitionRange::Bounded(m, n) => { + (m, Some(n)) + } + }; + repeat_range_literals( + &x.hir, min, max, x.greedy, lits, prefixes) + } + } + } + HirKind::Concat(ref es) if es.is_empty() => {} + HirKind::Concat(ref es) if es.len() == 1 => prefixes(&es[0], lits), + HirKind::Concat(ref es) => { + for e in es { + if let HirKind::Anchor(hir::Anchor::StartText) = *e.kind() { + if !lits.is_empty() { + lits.cut(); + break; + } + lits.add(Literal::empty()); + continue; + } + let mut lits2 = lits.to_empty(); + prefixes(e, &mut lits2); + if !lits.cross_product(&lits2) || !lits2.any_complete() { + // If this expression couldn't yield any literal that + // could be extended, then we need to quit. Since we're + // short-circuiting, we also need to freeze every member. + lits.cut(); + break; + } + } + } + HirKind::Alternation(ref es) => { + alternate_literals(es, lits, prefixes); + } + _ => lits.cut(), + } +} + +fn suffixes(expr: &Hir, lits: &mut Literals) { + match *expr.kind() { + HirKind::Literal(hir::Literal::Unicode(c)) => { + let mut buf = [0u8; 4]; + let i = unicode::encode_utf8(c, &mut buf).unwrap(); + let mut buf = &mut buf[..i]; + buf.reverse(); + lits.cross_add(buf); + } + HirKind::Literal(hir::Literal::Byte(b)) => { + lits.cross_add(&[b]); + } + HirKind::Class(hir::Class::Unicode(ref cls)) => { + if !lits.add_char_class_reverse(cls) { + lits.cut(); + } + } + HirKind::Class(hir::Class::Bytes(ref cls)) => { + if !lits.add_byte_class(cls) { + lits.cut(); + } + } + HirKind::Group(hir::Group { ref hir, .. }) => { + suffixes(&**hir, lits); + } + HirKind::Repetition(ref x) => { + match x.kind { + hir::RepetitionKind::ZeroOrOne => { + repeat_zero_or_one_literals(&x.hir, lits, suffixes); + } + hir::RepetitionKind::ZeroOrMore => { + repeat_zero_or_more_literals(&x.hir, lits, suffixes); + } + hir::RepetitionKind::OneOrMore => { + repeat_one_or_more_literals(&x.hir, lits, suffixes); + } + hir::RepetitionKind::Range(ref rng) => { + let (min, max) = match *rng { + hir::RepetitionRange::Exactly(m) => { + (m, Some(m)) + } + hir::RepetitionRange::AtLeast(m) => { + (m, None) + } + hir::RepetitionRange::Bounded(m, n) => { + (m, Some(n)) + } + }; + repeat_range_literals( + &x.hir, min, max, x.greedy, lits, suffixes) + } + } + } + HirKind::Concat(ref es) if es.is_empty() => {} + HirKind::Concat(ref es) if es.len() == 1 => suffixes(&es[0], lits), + HirKind::Concat(ref es) => { + for e in es.iter().rev() { + if let HirKind::Anchor(hir::Anchor::EndText) = *e.kind() { + if !lits.is_empty() { + lits.cut(); + break; + } + lits.add(Literal::empty()); + continue; + } + let mut lits2 = lits.to_empty(); + suffixes(e, &mut lits2); + if !lits.cross_product(&lits2) || !lits2.any_complete() { + // If this expression couldn't yield any literal that + // could be extended, then we need to quit. Since we're + // short-circuiting, we also need to freeze every member. + lits.cut(); + break; + } + } + } + HirKind::Alternation(ref es) => { + alternate_literals(es, lits, suffixes); + } + _ => lits.cut(), + } +} + +fn repeat_zero_or_one_literals<F: FnMut(&Hir, &mut Literals)>( + e: &Hir, + lits: &mut Literals, + mut f: F, +) { + let (mut lits2, mut lits3) = (lits.clone(), lits.to_empty()); + lits3.set_limit_size(lits.limit_size() / 2); + f(e, &mut lits3); + + if lits3.is_empty() || !lits2.cross_product(&lits3) { + lits.cut(); + return; + } + lits2.add(Literal::empty()); + if !lits.union(lits2) { + lits.cut(); + } +} + +fn repeat_zero_or_more_literals<F: FnMut(&Hir, &mut Literals)>( + e: &Hir, + lits: &mut Literals, + mut f: F, +) { + let (mut lits2, mut lits3) = (lits.clone(), lits.to_empty()); + lits3.set_limit_size(lits.limit_size() / 2); + f(e, &mut lits3); + + if lits3.is_empty() || !lits2.cross_product(&lits3) { + lits.cut(); + return; + } + lits2.cut(); + lits2.add(Literal::empty()); + if !lits.union(lits2) { + lits.cut(); + } +} + +fn repeat_one_or_more_literals<F: FnMut(&Hir, &mut Literals)>( + e: &Hir, + lits: &mut Literals, + mut f: F, +) { + f(e, lits); + lits.cut(); +} + +fn repeat_range_literals<F: FnMut(&Hir, &mut Literals)>( + e: &Hir, + min: u32, + max: Option<u32>, + greedy: bool, + lits: &mut Literals, + mut f: F, +) { + if min == 0 { + // This is a bit conservative. If `max` is set, then we could + // treat this as a finite set of alternations. For now, we + // just treat it as `e*`. + f(&Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::ZeroOrMore, + greedy: greedy, + hir: Box::new(e.clone()), + }), lits); + } else { + if min > 0 { + let n = cmp::min(lits.limit_size, min as usize); + let es = iter::repeat(e.clone()).take(n).collect(); + f(&Hir::concat(es), lits); + if n < min as usize || lits.contains_empty() { + lits.cut(); + } + } + if max.map_or(true, |max| min < max) { + lits.cut(); + } + } +} + +fn alternate_literals<F: FnMut(&Hir, &mut Literals)>( + es: &[Hir], + lits: &mut Literals, + mut f: F, +) { + let mut lits2 = lits.to_empty(); + for e in es { + let mut lits3 = lits.to_empty(); + lits3.set_limit_size(lits.limit_size() / 5); + f(e, &mut lits3); + if lits3.is_empty() || !lits2.union(lits3) { + // If we couldn't find suffixes for *any* of the + // alternates, then the entire alternation has to be thrown + // away and any existing members must be frozen. Similarly, + // if the union couldn't complete, stop and freeze. + lits.cut(); + return; + } + } + if !lits.cross_product(&lits2) { + lits.cut(); + } +} + +impl fmt::Debug for Literals { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("Literals") + .field("lits", &self.lits) + .field("limit_size", &self.limit_size) + .field("limit_class", &self.limit_class) + .finish() + } +} + +impl Literal { + /// Returns a new complete literal with the bytes given. + pub fn new(bytes: Vec<u8>) -> Literal { + Literal { v: bytes, cut: false } + } + + /// Returns a new complete empty literal. + pub fn empty() -> Literal { + Literal { v: vec![], cut: false } + } + + /// Returns true if this literal was "cut." + pub fn is_cut(&self) -> bool { + self.cut + } + + /// Cuts this literal. + pub fn cut(&mut self) { + self.cut = true; + } +} + +impl PartialEq for Literal { + fn eq(&self, other: &Literal) -> bool { + self.v == other.v + } +} + +impl PartialOrd for Literal { + fn partial_cmp(&self, other: &Literal) -> Option<cmp::Ordering> { + self.v.partial_cmp(&other.v) + } +} + +impl fmt::Debug for Literal { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if self.is_cut() { + write!(f, "Cut({})", escape_unicode(&self.v)) + } else { + write!(f, "Complete({})", escape_unicode(&self.v)) + } + } +} + +impl AsRef<[u8]> for Literal { + fn as_ref(&self) -> &[u8] { &self.v } +} + +impl ops::Deref for Literal { + type Target = Vec<u8>; + fn deref(&self) -> &Vec<u8> { &self.v } +} + +impl ops::DerefMut for Literal { + fn deref_mut(&mut self) -> &mut Vec<u8> { &mut self.v } +} + +fn position(needle: &[u8], mut haystack: &[u8]) -> Option<usize> { + let mut i = 0; + while haystack.len() >= needle.len() { + if needle == &haystack[..needle.len()] { + return Some(i); + } + i += 1; + haystack = &haystack[1..]; + } + None +} + +fn escape_unicode(bytes: &[u8]) -> String { + let show = match ::std::str::from_utf8(bytes) { + Ok(v) => v.to_string(), + Err(_) => escape_bytes(bytes), + }; + let mut space_escaped = String::new(); + for c in show.chars() { + if c.is_whitespace() { + let escaped = if c as u32 <= 0x7F { + escape_byte(c as u8) + } else { + if c as u32 <= 0xFFFF { + format!(r"\u{{{:04x}}}", c as u32) + } else { + format!(r"\U{{{:08x}}}", c as u32) + } + }; + space_escaped.push_str(&escaped); + } else { + space_escaped.push(c); + } + } + space_escaped +} + +fn escape_bytes(bytes: &[u8]) -> String { + let mut s = String::new(); + for &b in bytes { + s.push_str(&escape_byte(b)); + } + s +} + +fn escape_byte(byte: u8) -> String { + use std::ascii::escape_default; + + let escaped: Vec<u8> = escape_default(byte).collect(); + String::from_utf8_lossy(&escaped).into_owned() +} + +fn cls_char_count(cls: &hir::ClassUnicode) -> usize { + cls.iter() + .map(|&r| 1 + (r.end as u32) - (r.start as u32)) + .sum::<u32>() as usize +} + +fn cls_byte_count(cls: &hir::ClassBytes) -> usize { + cls.iter() + .map(|&r| 1 + (r.end as u32) - (r.start as u32)) + .sum::<u32>() as usize +} + +#[cfg(test)] +mod tests { + use std::fmt; + + use ParserBuilder; + use hir::Hir; + use super::{Literals, Literal, escape_bytes}; + + // To make test failures easier to read. + #[derive(Debug, Eq, PartialEq)] + struct Bytes(Vec<ULiteral>); + #[derive(Debug, Eq, PartialEq)] + struct Unicode(Vec<ULiteral>); + + fn escape_lits(blits: &[Literal]) -> Vec<ULiteral> { + let mut ulits = vec![]; + for blit in blits { + ulits.push(ULiteral { + v: escape_bytes(&blit), + cut: blit.is_cut(), + }); + } + ulits + } + + fn create_lits<I: IntoIterator<Item=Literal>>(it: I) -> Literals { + Literals { + lits: it.into_iter().collect(), + limit_size: 0, + limit_class: 0, + } + } + + // Needs to be pub for 1.3? + #[derive(Clone, Eq, PartialEq)] + pub struct ULiteral { + v: String, + cut: bool, + } + + impl ULiteral { + fn is_cut(&self) -> bool { self.cut } + } + + impl fmt::Debug for ULiteral { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if self.is_cut() { + write!(f, "Cut({})", self.v) + } else { + write!(f, "Complete({})", self.v) + } + } + } + + impl PartialEq<Literal> for ULiteral { + fn eq(&self, other: &Literal) -> bool { + self.v.as_bytes() == &*other.v && self.is_cut() == other.is_cut() + } + } + + impl PartialEq<ULiteral> for Literal { + fn eq(&self, other: &ULiteral) -> bool { + &*self.v == other.v.as_bytes() && self.is_cut() == other.is_cut() + } + } + + #[allow(non_snake_case)] + fn C(s: &'static str) -> ULiteral { + ULiteral { v: s.to_owned(), cut: true } + } + #[allow(non_snake_case)] + fn M(s: &'static str) -> ULiteral { + ULiteral { v: s.to_owned(), cut: false } + } + + fn prefixes(lits: &mut Literals, expr: &Hir) { + lits.union_prefixes(expr); + } + + fn suffixes(lits: &mut Literals, expr: &Hir) { + lits.union_suffixes(expr); + } + + macro_rules! assert_lit_eq { + ($which:ident, $got_lits:expr, $($expected_lit:expr),*) => {{ + let expected: Vec<ULiteral> = vec![$($expected_lit),*]; + let lits = $got_lits; + assert_eq!( + $which(expected.clone()), + $which(escape_lits(lits.literals()))); + assert_eq!( + !expected.is_empty() && expected.iter().all(|l| !l.is_cut()), + lits.all_complete()); + assert_eq!( + expected.iter().any(|l| !l.is_cut()), + lits.any_complete()); + }}; + } + + macro_rules! test_lit { + ($name:ident, $which:ident, $re:expr) => { + test_lit!($name, $which, $re,); + }; + ($name:ident, $which:ident, $re:expr, $($lit:expr),*) => { + #[test] + fn $name() { + let expr = ParserBuilder::new() + .build() + .parse($re) + .unwrap(); + let lits = Literals::$which(&expr); + assert_lit_eq!(Unicode, lits, $($lit),*); + + let expr = ParserBuilder::new() + .allow_invalid_utf8(true) + .unicode(false) + .build() + .parse($re) + .unwrap(); + let lits = Literals::$which(&expr); + assert_lit_eq!(Bytes, lits, $($lit),*); + } + }; + } + + // ************************************************************************ + // Tests for prefix literal extraction. + // ************************************************************************ + + // Elementary tests. + test_lit!(pfx_one_lit1, prefixes, "a", M("a")); + test_lit!(pfx_one_lit2, prefixes, "abc", M("abc")); + test_lit!(pfx_one_lit3, prefixes, "(?u)☃", M("\\xe2\\x98\\x83")); + test_lit!(pfx_one_lit4, prefixes, "(?ui)☃", M("\\xe2\\x98\\x83")); + test_lit!(pfx_class1, prefixes, "[1-4]", + M("1"), M("2"), M("3"), M("4")); + test_lit!(pfx_class2, prefixes, "(?u)[☃Ⅰ]", + M("\\xe2\\x85\\xa0"), M("\\xe2\\x98\\x83")); + test_lit!(pfx_class3, prefixes, "(?ui)[☃Ⅰ]", + M("\\xe2\\x85\\xa0"), M("\\xe2\\x85\\xb0"), + M("\\xe2\\x98\\x83")); + test_lit!(pfx_one_lit_casei1, prefixes, "(?i)a", + M("A"), M("a")); + test_lit!(pfx_one_lit_casei2, prefixes, "(?i)abc", + M("ABC"), M("aBC"), M("AbC"), M("abC"), + M("ABc"), M("aBc"), M("Abc"), M("abc")); + test_lit!(pfx_group1, prefixes, "(a)", M("a")); + test_lit!(pfx_rep_zero_or_one1, prefixes, "a?"); + test_lit!(pfx_rep_zero_or_one2, prefixes, "(?:abc)?"); + test_lit!(pfx_rep_zero_or_more1, prefixes, "a*"); + test_lit!(pfx_rep_zero_or_more2, prefixes, "(?:abc)*"); + test_lit!(pfx_rep_one_or_more1, prefixes, "a+", C("a")); + test_lit!(pfx_rep_one_or_more2, prefixes, "(?:abc)+", C("abc")); + test_lit!(pfx_rep_nested_one_or_more, prefixes, "(?:a+)+", C("a")); + test_lit!(pfx_rep_range1, prefixes, "a{0}"); + test_lit!(pfx_rep_range2, prefixes, "a{0,}"); + test_lit!(pfx_rep_range3, prefixes, "a{0,1}"); + test_lit!(pfx_rep_range4, prefixes, "a{1}", M("a")); + test_lit!(pfx_rep_range5, prefixes, "a{2}", M("aa")); + test_lit!(pfx_rep_range6, prefixes, "a{1,2}", C("a")); + test_lit!(pfx_rep_range7, prefixes, "a{2,3}", C("aa")); + + // Test regexes with concatenations. + test_lit!(pfx_cat1, prefixes, "(?:a)(?:b)", M("ab")); + test_lit!(pfx_cat2, prefixes, "[ab]z", M("az"), M("bz")); + test_lit!(pfx_cat3, prefixes, "(?i)[ab]z", + M("AZ"), M("BZ"), M("aZ"), M("bZ"), + M("Az"), M("Bz"), M("az"), M("bz")); + test_lit!(pfx_cat4, prefixes, "[ab][yz]", + M("ay"), M("by"), M("az"), M("bz")); + test_lit!(pfx_cat5, prefixes, "a*b", C("a"), M("b")); + test_lit!(pfx_cat6, prefixes, "a*b*c", C("a"), C("b"), M("c")); + test_lit!(pfx_cat7, prefixes, "a*b*c+", C("a"), C("b"), C("c")); + test_lit!(pfx_cat8, prefixes, "a*b+c", C("a"), C("b")); + test_lit!(pfx_cat9, prefixes, "a*b+c*", C("a"), C("b")); + test_lit!(pfx_cat10, prefixes, "ab*", C("ab"), M("a")); + test_lit!(pfx_cat11, prefixes, "ab*c", C("ab"), M("ac")); + test_lit!(pfx_cat12, prefixes, "ab+", C("ab")); + test_lit!(pfx_cat13, prefixes, "ab+c", C("ab")); + test_lit!(pfx_cat14, prefixes, "a^", C("a")); + test_lit!(pfx_cat15, prefixes, "$a"); + test_lit!(pfx_cat16, prefixes, r"ab*c", C("ab"), M("ac")); + test_lit!(pfx_cat17, prefixes, r"ab+c", C("ab")); + test_lit!(pfx_cat18, prefixes, r"z*azb", C("z"), M("azb")); + test_lit!(pfx_cat19, prefixes, "a.z", C("a")); + + // Test regexes with alternations. + test_lit!(pfx_alt1, prefixes, "a|b", M("a"), M("b")); + test_lit!(pfx_alt2, prefixes, "[1-3]|b", M("1"), M("2"), M("3"), M("b")); + test_lit!(pfx_alt3, prefixes, "y(?:a|b)z", M("yaz"), M("ybz")); + test_lit!(pfx_alt4, prefixes, "a|b*"); + test_lit!(pfx_alt5, prefixes, "a|b+", M("a"), C("b")); + test_lit!(pfx_alt6, prefixes, "a|(?:b|c*)"); + test_lit!(pfx_alt7, prefixes, "(a|b)*c|(a|ab)*c", + C("a"), C("b"), M("c"), C("a"), C("ab"), M("c")); + test_lit!(pfx_alt8, prefixes, "a*b|c", C("a"), M("b"), M("c")); + + // Test regexes with empty assertions. + test_lit!(pfx_empty1, prefixes, "^a", M("a")); + test_lit!(pfx_empty2, prefixes, "a${2}", C("a")); + test_lit!(pfx_empty3, prefixes, "^abc", M("abc")); + test_lit!(pfx_empty4, prefixes, "(?:^abc)|(?:^z)", M("abc"), M("z")); + + // Make sure some curious regexes have no prefixes. + test_lit!(pfx_nothing1, prefixes, "."); + test_lit!(pfx_nothing2, prefixes, "(?s)."); + test_lit!(pfx_nothing3, prefixes, "^"); + test_lit!(pfx_nothing4, prefixes, "$"); + test_lit!(pfx_nothing6, prefixes, "(?m)$"); + test_lit!(pfx_nothing7, prefixes, r"\b"); + test_lit!(pfx_nothing8, prefixes, r"\B"); + + // Test a few regexes that defeat any prefix literal detection. + test_lit!(pfx_defeated1, prefixes, ".a"); + test_lit!(pfx_defeated2, prefixes, "(?s).a"); + test_lit!(pfx_defeated3, prefixes, "a*b*c*"); + test_lit!(pfx_defeated4, prefixes, "a|."); + test_lit!(pfx_defeated5, prefixes, ".|a"); + test_lit!(pfx_defeated6, prefixes, "a|^"); + test_lit!(pfx_defeated7, prefixes, ".(?:a(?:b)(?:c))"); + test_lit!(pfx_defeated8, prefixes, "$a"); + test_lit!(pfx_defeated9, prefixes, "(?m)$a"); + test_lit!(pfx_defeated10, prefixes, r"\ba"); + test_lit!(pfx_defeated11, prefixes, r"\Ba"); + test_lit!(pfx_defeated12, prefixes, "^*a"); + test_lit!(pfx_defeated13, prefixes, "^+a"); + + test_lit!( + pfx_crazy1, + prefixes, + r"M[ou]'?am+[ae]r .*([AEae]l[- ])?[GKQ]h?[aeu]+([dtz][dhz]?)+af[iy]", + C("Mo\\'am"), C("Mu\\'am"), C("Moam"), C("Muam")); + + // ************************************************************************ + // Tests for quiting prefix literal search. + // ************************************************************************ + + macro_rules! test_exhausted { + ($name:ident, $which:ident, $re:expr) => { + test_exhausted!($name, $which, $re,); + }; + ($name:ident, $which:ident, $re:expr, $($lit:expr),*) => { + #[test] + fn $name() { + let expr = ParserBuilder::new() + .build() + .parse($re) + .unwrap(); + let mut lits = Literals::empty(); + lits.set_limit_size(20).set_limit_class(10); + $which(&mut lits, &expr); + assert_lit_eq!(Unicode, lits, $($lit),*); + + let expr = ParserBuilder::new() + .allow_invalid_utf8(true) + .unicode(false) + .build() + .parse($re) + .unwrap(); + let mut lits = Literals::empty(); + lits.set_limit_size(20).set_limit_class(10); + $which(&mut lits, &expr); + assert_lit_eq!(Bytes, lits, $($lit),*); + } + }; + } + + // These test use a much lower limit than the default so that we can + // write test cases of reasonable size. + test_exhausted!(pfx_exhausted1, prefixes, "[a-z]"); + test_exhausted!(pfx_exhausted2, prefixes, "[a-z]*A"); + test_exhausted!(pfx_exhausted3, prefixes, "A[a-z]Z", C("A")); + test_exhausted!(pfx_exhausted4, prefixes, "(?i)foobar", + C("FO"), C("fO"), C("Fo"), C("fo")); + test_exhausted!(pfx_exhausted5, prefixes, "(?:ab){100}", + C("abababababababababab")); + test_exhausted!(pfx_exhausted6, prefixes, "(?:(?:ab){100})*cd", + C("ababababab"), M("cd")); + test_exhausted!(pfx_exhausted7, prefixes, "z(?:(?:ab){100})*cd", + C("zababababab"), M("zcd")); + test_exhausted!(pfx_exhausted8, prefixes, "aaaaaaaaaaaaaaaaaaaaz", + C("aaaaaaaaaaaaaaaaaaaa")); + + // ************************************************************************ + // Tests for suffix literal extraction. + // ************************************************************************ + + // Elementary tests. + test_lit!(sfx_one_lit1, suffixes, "a", M("a")); + test_lit!(sfx_one_lit2, suffixes, "abc", M("abc")); + test_lit!(sfx_one_lit3, suffixes, "(?u)☃", M("\\xe2\\x98\\x83")); + test_lit!(sfx_one_lit4, suffixes, "(?ui)☃", M("\\xe2\\x98\\x83")); + test_lit!(sfx_class1, suffixes, "[1-4]", + M("1"), M("2"), M("3"), M("4")); + test_lit!(sfx_class2, suffixes, "(?u)[☃Ⅰ]", + M("\\xe2\\x85\\xa0"), M("\\xe2\\x98\\x83")); + test_lit!(sfx_class3, suffixes, "(?ui)[☃Ⅰ]", + M("\\xe2\\x85\\xa0"), M("\\xe2\\x85\\xb0"), + M("\\xe2\\x98\\x83")); + test_lit!(sfx_one_lit_casei1, suffixes, "(?i)a", + M("A"), M("a")); + test_lit!(sfx_one_lit_casei2, suffixes, "(?i)abc", + M("ABC"), M("ABc"), M("AbC"), M("Abc"), + M("aBC"), M("aBc"), M("abC"), M("abc")); + test_lit!(sfx_group1, suffixes, "(a)", M("a")); + test_lit!(sfx_rep_zero_or_one1, suffixes, "a?"); + test_lit!(sfx_rep_zero_or_one2, suffixes, "(?:abc)?"); + test_lit!(sfx_rep_zero_or_more1, suffixes, "a*"); + test_lit!(sfx_rep_zero_or_more2, suffixes, "(?:abc)*"); + test_lit!(sfx_rep_one_or_more1, suffixes, "a+", C("a")); + test_lit!(sfx_rep_one_or_more2, suffixes, "(?:abc)+", C("abc")); + test_lit!(sfx_rep_nested_one_or_more, suffixes, "(?:a+)+", C("a")); + test_lit!(sfx_rep_range1, suffixes, "a{0}"); + test_lit!(sfx_rep_range2, suffixes, "a{0,}"); + test_lit!(sfx_rep_range3, suffixes, "a{0,1}"); + test_lit!(sfx_rep_range4, suffixes, "a{1}", M("a")); + test_lit!(sfx_rep_range5, suffixes, "a{2}", M("aa")); + test_lit!(sfx_rep_range6, suffixes, "a{1,2}", C("a")); + test_lit!(sfx_rep_range7, suffixes, "a{2,3}", C("aa")); + + // Test regexes with concatenations. + test_lit!(sfx_cat1, suffixes, "(?:a)(?:b)", M("ab")); + test_lit!(sfx_cat2, suffixes, "[ab]z", M("az"), M("bz")); + test_lit!(sfx_cat3, suffixes, "(?i)[ab]z", + M("AZ"), M("Az"), M("BZ"), M("Bz"), + M("aZ"), M("az"), M("bZ"), M("bz")); + test_lit!(sfx_cat4, suffixes, "[ab][yz]", + M("ay"), M("az"), M("by"), M("bz")); + test_lit!(sfx_cat5, suffixes, "a*b", C("ab"), M("b")); + test_lit!(sfx_cat6, suffixes, "a*b*c", C("bc"), C("ac"), M("c")); + test_lit!(sfx_cat7, suffixes, "a*b*c+", C("c")); + test_lit!(sfx_cat8, suffixes, "a*b+c", C("bc")); + test_lit!(sfx_cat9, suffixes, "a*b+c*", C("c"), C("b")); + test_lit!(sfx_cat10, suffixes, "ab*", C("b"), M("a")); + test_lit!(sfx_cat11, suffixes, "ab*c", C("bc"), M("ac")); + test_lit!(sfx_cat12, suffixes, "ab+", C("b")); + test_lit!(sfx_cat13, suffixes, "ab+c", C("bc")); + test_lit!(sfx_cat14, suffixes, "a^"); + test_lit!(sfx_cat15, suffixes, "$a", C("a")); + test_lit!(sfx_cat16, suffixes, r"ab*c", C("bc"), M("ac")); + test_lit!(sfx_cat17, suffixes, r"ab+c", C("bc")); + test_lit!(sfx_cat18, suffixes, r"z*azb", C("zazb"), M("azb")); + test_lit!(sfx_cat19, suffixes, "a.z", C("z")); + + // Test regexes with alternations. + test_lit!(sfx_alt1, suffixes, "a|b", M("a"), M("b")); + test_lit!(sfx_alt2, suffixes, "[1-3]|b", M("1"), M("2"), M("3"), M("b")); + test_lit!(sfx_alt3, suffixes, "y(?:a|b)z", M("yaz"), M("ybz")); + test_lit!(sfx_alt4, suffixes, "a|b*"); + test_lit!(sfx_alt5, suffixes, "a|b+", M("a"), C("b")); + test_lit!(sfx_alt6, suffixes, "a|(?:b|c*)"); + test_lit!(sfx_alt7, suffixes, "(a|b)*c|(a|ab)*c", + C("ac"), C("bc"), M("c"), C("ac"), C("abc"), M("c")); + test_lit!(sfx_alt8, suffixes, "a*b|c", C("ab"), M("b"), M("c")); + + // Test regexes with empty assertions. + test_lit!(sfx_empty1, suffixes, "a$", M("a")); + test_lit!(sfx_empty2, suffixes, "${2}a", C("a")); + + // Make sure some curious regexes have no suffixes. + test_lit!(sfx_nothing1, suffixes, "."); + test_lit!(sfx_nothing2, suffixes, "(?s)."); + test_lit!(sfx_nothing3, suffixes, "^"); + test_lit!(sfx_nothing4, suffixes, "$"); + test_lit!(sfx_nothing6, suffixes, "(?m)$"); + test_lit!(sfx_nothing7, suffixes, r"\b"); + test_lit!(sfx_nothing8, suffixes, r"\B"); + + // Test a few regexes that defeat any suffix literal detection. + test_lit!(sfx_defeated1, suffixes, "a."); + test_lit!(sfx_defeated2, suffixes, "(?s)a."); + test_lit!(sfx_defeated3, suffixes, "a*b*c*"); + test_lit!(sfx_defeated4, suffixes, "a|."); + test_lit!(sfx_defeated5, suffixes, ".|a"); + test_lit!(sfx_defeated6, suffixes, "a|^"); + test_lit!(sfx_defeated7, suffixes, "(?:a(?:b)(?:c))."); + test_lit!(sfx_defeated8, suffixes, "a^"); + test_lit!(sfx_defeated9, suffixes, "(?m)a$"); + test_lit!(sfx_defeated10, suffixes, r"a\b"); + test_lit!(sfx_defeated11, suffixes, r"a\B"); + test_lit!(sfx_defeated12, suffixes, "a^*"); + test_lit!(sfx_defeated13, suffixes, "a^+"); + + // These test use a much lower limit than the default so that we can + // write test cases of reasonable size. + test_exhausted!(sfx_exhausted1, suffixes, "[a-z]"); + test_exhausted!(sfx_exhausted2, suffixes, "A[a-z]*"); + test_exhausted!(sfx_exhausted3, suffixes, "A[a-z]Z", C("Z")); + test_exhausted!(sfx_exhausted4, suffixes, "(?i)foobar", + C("AR"), C("Ar"), C("aR"), C("ar")); + test_exhausted!(sfx_exhausted5, suffixes, "(?:ab){100}", + C("abababababababababab")); + test_exhausted!(sfx_exhausted6, suffixes, "cd(?:(?:ab){100})*", + C("ababababab"), M("cd")); + test_exhausted!(sfx_exhausted7, suffixes, "cd(?:(?:ab){100})*z", + C("abababababz"), M("cdz")); + test_exhausted!(sfx_exhausted8, suffixes, "zaaaaaaaaaaaaaaaaaaaa", + C("aaaaaaaaaaaaaaaaaaaa")); + + // ************************************************************************ + // Tests for generating unambiguous literal sets. + // ************************************************************************ + + macro_rules! test_unamb { + ($name:ident, $given:expr, $expected:expr) => { + #[test] + fn $name() { + let given: Vec<Literal> = + $given + .into_iter() + .map(|ul| { + let cut = ul.is_cut(); + Literal { v: ul.v.into_bytes(), cut: cut } + }) + .collect(); + let lits = create_lits(given); + let got = lits.unambiguous_prefixes(); + assert_eq!($expected, escape_lits(got.literals())); + } + }; + } + + test_unamb!(unambiguous1, vec![M("z"), M("azb")], vec![C("a"), C("z")]); + test_unamb!(unambiguous2, + vec![M("zaaaaaa"), M("aa")], vec![C("aa"), C("z")]); + test_unamb!(unambiguous3, + vec![M("Sherlock"), M("Watson")], + vec![M("Sherlock"), M("Watson")]); + test_unamb!(unambiguous4, vec![M("abc"), M("bc")], vec![C("a"), C("bc")]); + test_unamb!(unambiguous5, vec![M("bc"), M("abc")], vec![C("a"), C("bc")]); + test_unamb!(unambiguous6, vec![M("a"), M("aa")], vec![C("a")]); + test_unamb!(unambiguous7, vec![M("aa"), M("a")], vec![C("a")]); + test_unamb!(unambiguous8, vec![M("ab"), M("a")], vec![C("a")]); + test_unamb!(unambiguous9, + vec![M("ac"), M("bc"), M("c"), M("ac"), M("abc"), M("c")], + vec![C("a"), C("b"), C("c")]); + test_unamb!(unambiguous10, + vec![M("Mo'"), M("Mu'"), M("Mo"), M("Mu")], + vec![C("Mo"), C("Mu")]); + test_unamb!(unambiguous11, + vec![M("zazb"), M("azb")], vec![C("a"), C("z")]); + test_unamb!(unambiguous12, vec![M("foo"), C("foo")], vec![C("foo")]); + test_unamb!(unambiguous13, + vec![M("ABCX"), M("CDAX"), M("BCX")], + vec![C("A"), C("BCX"), C("CD")]); + test_unamb!(unambiguous14, + vec![M("IMGX"), M("MVIX"), M("MGX"), M("DSX")], + vec![M("DSX"), C("I"), C("MGX"), C("MV")]); + test_unamb!(unambiguous15, + vec![M("IMG_"), M("MG_"), M("CIMG")], + vec![C("C"), C("I"), C("MG_")]); + + + // ************************************************************************ + // Tests for suffix trimming. + // ************************************************************************ + macro_rules! test_trim { + ($name:ident, $trim:expr, $given:expr, $expected:expr) => { + #[test] + fn $name() { + let given: Vec<Literal> = + $given + .into_iter() + .map(|ul| { + let cut = ul.is_cut(); + Literal { v: ul.v.into_bytes(), cut: cut } + }) + .collect(); + let lits = create_lits(given); + let got = lits.trim_suffix($trim).unwrap(); + assert_eq!($expected, escape_lits(got.literals())); + } + } + } + + test_trim!(trim1, 1, vec![M("ab"), M("yz")], vec![C("a"), C("y")]); + test_trim!(trim2, 1, vec![M("abc"), M("abd")], vec![C("ab")]); + test_trim!(trim3, 2, vec![M("abc"), M("abd")], vec![C("a")]); + test_trim!(trim4, 2, vec![M("abc"), M("ghij")], vec![C("a"), C("gh")]); + + // ************************************************************************ + // Tests for longest common prefix. + // ************************************************************************ + + macro_rules! test_lcp { + ($name:ident, $given:expr, $expected:expr) => { + #[test] + fn $name() { + let given: Vec<Literal> = + $given + .into_iter() + .map(|s: &str| Literal { + v: s.to_owned().into_bytes(), + cut: false, + }) + .collect(); + let lits = create_lits(given); + let got = lits.longest_common_prefix(); + assert_eq!($expected, escape_bytes(got)); + } + }; + } + + test_lcp!(lcp1, vec!["a"], "a"); + test_lcp!(lcp2, vec![], ""); + test_lcp!(lcp3, vec!["a", "b"], ""); + test_lcp!(lcp4, vec!["ab", "ab"], "ab"); + test_lcp!(lcp5, vec!["ab", "a"], "a"); + test_lcp!(lcp6, vec!["a", "ab"], "a"); + test_lcp!(lcp7, vec!["ab", "b"], ""); + test_lcp!(lcp8, vec!["b", "ab"], ""); + test_lcp!(lcp9, vec!["foobar", "foobaz"], "fooba"); + test_lcp!(lcp10, vec!["foobar", "foobaz", "a"], ""); + test_lcp!(lcp11, vec!["a", "foobar", "foobaz"], ""); + test_lcp!(lcp12, vec!["foo", "flub", "flab", "floo"], "f"); + + // ************************************************************************ + // Tests for longest common suffix. + // ************************************************************************ + + macro_rules! test_lcs { + ($name:ident, $given:expr, $expected:expr) => { + #[test] + fn $name() { + let given: Vec<Literal> = + $given + .into_iter() + .map(|s: &str| Literal { + v: s.to_owned().into_bytes(), + cut: false, + }) + .collect(); + let lits = create_lits(given); + let got = lits.longest_common_suffix(); + assert_eq!($expected, escape_bytes(got)); + } + }; + } + + test_lcs!(lcs1, vec!["a"], "a"); + test_lcs!(lcs2, vec![], ""); + test_lcs!(lcs3, vec!["a", "b"], ""); + test_lcs!(lcs4, vec!["ab", "ab"], "ab"); + test_lcs!(lcs5, vec!["ab", "a"], ""); + test_lcs!(lcs6, vec!["a", "ab"], ""); + test_lcs!(lcs7, vec!["ab", "b"], "b"); + test_lcs!(lcs8, vec!["b", "ab"], "b"); + test_lcs!(lcs9, vec!["barfoo", "bazfoo"], "foo"); + test_lcs!(lcs10, vec!["barfoo", "bazfoo", "a"], ""); + test_lcs!(lcs11, vec!["a", "barfoo", "bazfoo"], ""); + test_lcs!(lcs12, vec!["flub", "bub", "boob", "dub"], "b"); +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/hir/mod.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/hir/mod.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/hir/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/hir/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2055 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +Defines a high-level intermediate representation for regular expressions. +*/ +use std::char; +use std::cmp; +use std::error; +use std::fmt; +use std::u8; + +use ast::Span; +use hir::interval::{Interval, IntervalSet, IntervalSetIter}; +use unicode; + +pub use hir::visitor::{Visitor, visit}; + +mod interval; +pub mod literal; +pub mod print; +pub mod translate; +mod visitor; + +/// An error that can occur while translating an `Ast` to a `Hir`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Error { + /// The kind of error. + kind: ErrorKind, + /// The original pattern that the translator's Ast was parsed from. Every + /// span in an error is a valid range into this string. + pattern: String, + /// The span of this error, derived from the Ast given to the translator. + span: Span, +} + +impl Error { + /// Return the type of this error. + pub fn kind(&self) -> &ErrorKind { + &self.kind + } + + /// The original pattern string in which this error occurred. + /// + /// Every span reported by this error is reported in terms of this string. + pub fn pattern(&self) -> &str { + &self.pattern + } + + /// Return the span at which this error occurred. + pub fn span(&self) -> &Span { + &self.span + } +} + +/// The type of an error that occurred while building an `Hir`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ErrorKind { + /// This error occurs when a Unicode feature is used when Unicode + /// support is disabled. For example `(?-u:\pL)` would trigger this error. + UnicodeNotAllowed, + /// This error occurs when translating a pattern that could match a byte + /// sequence that isn't UTF-8 and `allow_invalid_utf8` was disabled. + InvalidUtf8, + /// This occurs when an unrecognized Unicode property name could not + /// be found. + UnicodePropertyNotFound, + /// This occurs when an unrecognized Unicode property value could not + /// be found. + UnicodePropertyValueNotFound, + /// This occurs when the translator attempts to construct a character class + /// that is empty. + /// + /// Note that this restriction in the translator may be removed in the + /// future. + EmptyClassNotAllowed, + /// Hints that destructuring should not be exhaustive. + /// + /// This enum may grow additional variants, so this makes sure clients + /// don't count on exhaustive matching. (Otherwise, adding a new variant + /// could break existing code.) + #[doc(hidden)] + __Nonexhaustive, +} + +impl ErrorKind { + fn description(&self) -> &str { + use self::ErrorKind::*; + match *self { + UnicodeNotAllowed => "Unicode not allowed here", + InvalidUtf8 => "pattern can match invalid UTF-8", + UnicodePropertyNotFound => "Unicode property not found", + UnicodePropertyValueNotFound => "Unicode property value not found", + EmptyClassNotAllowed => "empty character classes are not allowed", + _ => unreachable!(), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + self.kind.description() + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ::error::Formatter::from(self).fmt(f) + } +} + +impl fmt::Display for ErrorKind { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(self.description()) + } +} + +/// A high-level intermediate representation (HIR) for a regular expression. +/// +/// The HIR of a regular expression represents an intermediate step between its +/// abstract syntax (a structured description of the concrete syntax) and +/// compiled byte codes. The purpose of HIR is to make regular expressions +/// easier to analyze. In particular, the AST is much more complex than the +/// HIR. For example, while an AST supports arbitrarily nested character +/// classes, the HIR will flatten all nested classes into a single set. The HIR +/// will also "compile away" every flag present in the concrete syntax. For +/// example, users of HIR expressions never need to worry about case folding; +/// it is handled automatically by the translator (e.g., by translating `(?i)A` +/// to `[aA]`). +/// +/// If the HIR was produced by a translator that disallows invalid UTF-8, then +/// the HIR is guaranteed to match UTF-8 exclusively. +/// +/// This type defines its own destructor that uses constant stack space and +/// heap space proportional to the size of the HIR. +/// +/// The specific type of an HIR expression can be accessed via its `kind` +/// or `into_kind` methods. This extra level of indirection exists for two +/// reasons: +/// +/// 1. Construction of an HIR expression *must* use the constructor methods +/// on this `Hir` type instead of building the `HirKind` values directly. +/// This permits construction to enforce invariants like "concatenations +/// always consist of two or more sub-expressions." +/// 2. Every HIR expression contains attributes that are defined inductively, +/// and can be computed cheaply during the construction process. For +/// example, one such attribute is whether the expression must match at the +/// beginning of the text. +/// +/// Also, an `Hir`'s `fmt::Display` implementation prints an HIR as a regular +/// expression pattern string, and uses constant stack space and heap space +/// proportional to the size of the `Hir`. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Hir { + /// The underlying HIR kind. + kind: HirKind, + /// Analysis info about this HIR, computed during construction. + info: HirInfo, +} + +/// The kind of an arbitrary `Hir` expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum HirKind { + /// The empty regular expression, which matches everything, including the + /// empty string. + Empty, + /// A single literal character that matches exactly this character. + Literal(Literal), + /// A single character class that matches any of the characters in the + /// class. A class can either consist of Unicode scalar values as + /// characters, or it can use bytes. + Class(Class), + /// An anchor assertion. An anchor assertion match always has zero length. + Anchor(Anchor), + /// A word boundary assertion, which may or may not be Unicode aware. A + /// word boundary assertion match always has zero length. + WordBoundary(WordBoundary), + /// A repetition operation applied to a child expression. + Repetition(Repetition), + /// A possibly capturing group, which contains a child expression. + Group(Group), + /// A concatenation of expressions. A concatenation always has at least two + /// child expressions. + /// + /// A concatenation matches only if each of its child expression matches + /// one after the other. + Concat(Vec<Hir>), + /// An alternation of expressions. An alternation always has at least two + /// child expressions. + /// + /// An alternation matches only if at least one of its child expression + /// matches. If multiple expressions match, then the leftmost is preferred. + Alternation(Vec<Hir>), +} + +impl Hir { + /// Returns a reference to the underlying HIR kind. + pub fn kind(&self) -> &HirKind { + &self.kind + } + + /// Consumes ownership of this HIR expression and returns its underlying + /// `HirKind`. + pub fn into_kind(mut self) -> HirKind { + use std::mem; + mem::replace(&mut self.kind, HirKind::Empty) + } + + /// Returns an empty HIR expression. + /// + /// An empty HIR expression always matches, including the empty string. + pub fn empty() -> Hir { + let mut info = HirInfo::new(); + info.set_always_utf8(true); + info.set_all_assertions(true); + info.set_anchored_start(false); + info.set_anchored_end(false); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + info.set_match_empty(true); + Hir { + kind: HirKind::Empty, + info: info, + } + } + + /// Creates a literal HIR expression. + /// + /// If the given literal has a `Byte` variant with an ASCII byte, then this + /// method panics. This enforces the invariant that `Byte` variants are + /// only used to express matching of invalid UTF-8. + pub fn literal(lit: Literal) -> Hir { + if let Literal::Byte(b) = lit { + assert!(b > 0x7F); + } + + let mut info = HirInfo::new(); + info.set_always_utf8(lit.is_unicode()); + info.set_all_assertions(false); + info.set_anchored_start(false); + info.set_anchored_end(false); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + info.set_match_empty(false); + Hir { + kind: HirKind::Literal(lit), + info: info, + } + } + + /// Creates a class HIR expression. + pub fn class(class: Class) -> Hir { + let mut info = HirInfo::new(); + info.set_always_utf8(class.is_always_utf8()); + info.set_all_assertions(false); + info.set_anchored_start(false); + info.set_anchored_end(false); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + info.set_match_empty(false); + Hir { + kind: HirKind::Class(class), + info: info, + } + } + + /// Creates an anchor assertion HIR expression. + pub fn anchor(anchor: Anchor) -> Hir { + let mut info = HirInfo::new(); + info.set_always_utf8(true); + info.set_all_assertions(true); + info.set_anchored_start(false); + info.set_anchored_end(false); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + info.set_match_empty(true); + if let Anchor::StartText = anchor { + info.set_anchored_start(true); + info.set_any_anchored_start(true); + } + if let Anchor::EndText = anchor { + info.set_anchored_end(true); + info.set_any_anchored_end(true); + } + Hir { + kind: HirKind::Anchor(anchor), + info: info, + } + } + + /// Creates a word boundary assertion HIR expression. + pub fn word_boundary(word_boundary: WordBoundary) -> Hir { + let mut info = HirInfo::new(); + info.set_always_utf8(true); + info.set_all_assertions(true); + info.set_anchored_start(false); + info.set_anchored_end(false); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + // A negated word boundary matches the empty string, but a normal + // word boundary does not! + info.set_match_empty(word_boundary.is_negated()); + // Negated ASCII word boundaries can match invalid UTF-8. + if let WordBoundary::AsciiNegate = word_boundary { + info.set_always_utf8(false); + } + Hir { + kind: HirKind::WordBoundary(word_boundary), + info: info, + } + } + + /// Creates a repetition HIR expression. + pub fn repetition(rep: Repetition) -> Hir { + let mut info = HirInfo::new(); + info.set_always_utf8(rep.hir.is_always_utf8()); + info.set_all_assertions(rep.hir.is_all_assertions()); + // If this operator can match the empty string, then it can never + // be anchored. + info.set_anchored_start( + !rep.is_match_empty() && rep.hir.is_anchored_start() + ); + info.set_anchored_end( + !rep.is_match_empty() && rep.hir.is_anchored_end() + ); + info.set_any_anchored_start(rep.hir.is_any_anchored_start()); + info.set_any_anchored_end(rep.hir.is_any_anchored_end()); + info.set_match_empty(rep.is_match_empty() || rep.hir.is_match_empty()); + Hir { + kind: HirKind::Repetition(rep), + info: info, + } + } + + /// Creates a group HIR expression. + pub fn group(group: Group) -> Hir { + let mut info = HirInfo::new(); + info.set_always_utf8(group.hir.is_always_utf8()); + info.set_all_assertions(group.hir.is_all_assertions()); + info.set_anchored_start(group.hir.is_anchored_start()); + info.set_anchored_end(group.hir.is_anchored_end()); + info.set_any_anchored_start(group.hir.is_any_anchored_start()); + info.set_any_anchored_end(group.hir.is_any_anchored_end()); + info.set_match_empty(group.hir.is_match_empty()); + Hir { + kind: HirKind::Group(group), + info: info, + } + } + + /// Returns the concatenation of the given expressions. + /// + /// This flattens the concatenation as appropriate. + pub fn concat(mut exprs: Vec<Hir>) -> Hir { + match exprs.len() { + 0 => Hir::empty(), + 1 => exprs.pop().unwrap(), + _ => { + let mut info = HirInfo::new(); + info.set_always_utf8(true); + info.set_all_assertions(true); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + info.set_match_empty(true); + + // Some attributes require analyzing all sub-expressions. + for e in &exprs { + let x = info.is_always_utf8() && e.is_always_utf8(); + info.set_always_utf8(x); + + let x = info.is_all_assertions() && e.is_all_assertions(); + info.set_all_assertions(x); + + let x = + info.is_any_anchored_start() + || e.is_any_anchored_start(); + info.set_any_anchored_start(x); + + let x = + info.is_any_anchored_end() + || e.is_any_anchored_end(); + info.set_any_anchored_end(x); + + let x = info.is_match_empty() && e.is_match_empty(); + info.set_match_empty(x); + } + // Anchored attributes require something slightly more + // sophisticated. Normally, WLOG, to determine whether an + // expression is anchored to the start, we'd only need to check + // the first expression of a concatenation. However, + // expressions like `$\b^` are still anchored to the start, + // but the first expression in the concatenation *isn't* + // anchored to the start. So the "first" expression to look at + // is actually one that is either not an assertion or is + // specifically the StartText assertion. + info.set_anchored_start( + exprs.iter() + .take_while(|e| { + e.is_anchored_start() || e.is_all_assertions() + }) + .any(|e| { + e.is_anchored_start() + })); + // Similarly for the end anchor, but in reverse. + info.set_anchored_end( + exprs.iter() + .rev() + .take_while(|e| { + e.is_anchored_end() || e.is_all_assertions() + }) + .any(|e| { + e.is_anchored_end() + })); + Hir { + kind: HirKind::Concat(exprs), + info: info, + } + } + } + } + + /// Returns the alternation of the given expressions. + /// + /// This flattens the alternation as appropriate. + pub fn alternation(mut exprs: Vec<Hir>) -> Hir { + match exprs.len() { + 0 => Hir::empty(), + 1 => exprs.pop().unwrap(), + _ => { + let mut info = HirInfo::new(); + info.set_always_utf8(true); + info.set_all_assertions(true); + info.set_anchored_start(true); + info.set_anchored_end(true); + info.set_any_anchored_start(false); + info.set_any_anchored_end(false); + info.set_match_empty(false); + + // Some attributes require analyzing all sub-expressions. + for e in &exprs { + let x = info.is_always_utf8() && e.is_always_utf8(); + info.set_always_utf8(x); + + let x = info.is_all_assertions() && e.is_all_assertions(); + info.set_all_assertions(x); + + let x = info.is_anchored_start() && e.is_anchored_start(); + info.set_anchored_start(x); + + let x = info.is_anchored_end() && e.is_anchored_end(); + info.set_anchored_end(x); + + let x = + info.is_any_anchored_start() + || e.is_any_anchored_start(); + info.set_any_anchored_start(x); + + let x = + info.is_any_anchored_end() + || e.is_any_anchored_end(); + info.set_any_anchored_end(x); + + let x = info.is_match_empty() || e.is_match_empty(); + info.set_match_empty(x); + } + Hir { + kind: HirKind::Alternation(exprs), + info: info, + } + } + } + } + + /// Build an HIR expression for `.`. + /// + /// A `.` expression matches any character except for `\n`. To build an + /// expression that matches any character, including `\n`, use the `any` + /// method. + /// + /// If `bytes` is `true`, then this assumes characters are limited to a + /// single byte. + pub fn dot(bytes: bool) -> Hir { + if bytes { + let mut cls = ClassBytes::empty(); + cls.push(ClassBytesRange::new(b'\0', b'\x09')); + cls.push(ClassBytesRange::new(b'\x0B', b'\xFF')); + Hir::class(Class::Bytes(cls)) + } else { + let mut cls = ClassUnicode::empty(); + cls.push(ClassUnicodeRange::new('\0', '\x09')); + cls.push(ClassUnicodeRange::new('\x0B', '\u{10FFFF}')); + Hir::class(Class::Unicode(cls)) + } + } + + /// Build an HIR expression for `(?s).`. + /// + /// A `(?s).` expression matches any character, including `\n`. To build an + /// expression that matches any character except for `\n`, then use the + /// `dot` method. + /// + /// If `bytes` is `true`, then this assumes characters are limited to a + /// single byte. + pub fn any(bytes: bool) -> Hir { + if bytes { + let mut cls = ClassBytes::empty(); + cls.push(ClassBytesRange::new(b'\0', b'\xFF')); + Hir::class(Class::Bytes(cls)) + } else { + let mut cls = ClassUnicode::empty(); + cls.push(ClassUnicodeRange::new('\0', '\u{10FFFF}')); + Hir::class(Class::Unicode(cls)) + } + } + + /// Return true if and only if this HIR will always match valid UTF-8. + /// + /// When this returns false, then it is possible for this HIR expression + /// to match invalid UTF-8. + pub fn is_always_utf8(&self) -> bool { + self.info.is_always_utf8() + } + + /// Returns true if and only if this entire HIR expression is made up of + /// zero-width assertions. + /// + /// This includes expressions like `^$\b\A\z` and even `((\b)+())*^`, but + /// not `^a`. + pub fn is_all_assertions(&self) -> bool { + self.info.is_all_assertions() + } + + /// Return true if and only if this HIR is required to match from the + /// beginning of text. This includes expressions like `^foo`, `^(foo|bar)`, + /// `^foo|^bar` but not `^foo|bar`. + pub fn is_anchored_start(&self) -> bool { + self.info.is_anchored_start() + } + + /// Return true if and only if this HIR is required to match at the end + /// of text. This includes expressions like `foo$`, `(foo|bar)$`, + /// `foo$|bar$` but not `foo$|bar`. + pub fn is_anchored_end(&self) -> bool { + self.info.is_anchored_end() + } + + /// Return true if and only if this HIR contains any sub-expression that + /// is required to match at the beginning of text. Specifically, this + /// returns true if the `^` symbol (when multiline mode is disabled) or the + /// `\A` escape appear anywhere in the regex. + pub fn is_any_anchored_start(&self) -> bool { + self.info.is_any_anchored_start() + } + + /// Return true if and only if this HIR contains any sub-expression that is + /// required to match at the end of text. Specifically, this returns true + /// if the `$` symbol (when multiline mode is disabled) or the `\z` escape + /// appear anywhere in the regex. + pub fn is_any_anchored_end(&self) -> bool { + self.info.is_any_anchored_end() + } + + /// Return true if and only if the empty string is part of the language + /// matched by this regular expression. + /// + /// This includes `a*`, `a?b*`, `a{0}`, `()`, `()+`, `^$`, `a|b?`, `\B`, + /// but not `a`, `a+` or `\b`. + pub fn is_match_empty(&self) -> bool { + self.info.is_match_empty() + } +} + +impl HirKind { + /// Return true if and only if this HIR is the empty regular expression. + /// + /// Note that this is not defined inductively. That is, it only tests if + /// this kind is the `Empty` variant. To get the inductive definition, + /// use the `is_match_empty` method on [`Hir`](struct.Hir.html). + pub fn is_empty(&self) -> bool { + match *self { + HirKind::Empty => true, + _ => false, + } + } + + /// Returns true if and only if this kind has any (including possibly + /// empty) subexpressions. + pub fn has_subexprs(&self) -> bool { + match *self { + HirKind::Empty + | HirKind::Literal(_) + | HirKind::Class(_) + | HirKind::Anchor(_) + | HirKind::WordBoundary(_) => false, + HirKind::Group(_) + | HirKind::Repetition(_) + | HirKind::Concat(_) + | HirKind::Alternation(_) => true, + } + } +} + +/// Print a display representation of this Hir. +/// +/// The result of this is a valid regular expression pattern string. +/// +/// This implementation uses constant stack space and heap space proportional +/// to the size of the `Hir`. +impl fmt::Display for Hir { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use hir::print::Printer; + Printer::new().print(self, f) + } +} + +/// The high-level intermediate representation of a literal. +/// +/// A literal corresponds to a single character, where a character is either +/// defined by a Unicode scalar value or an arbitrary byte. Unicode characters +/// are preferred whenever possible. In particular, a `Byte` variant is only +/// ever produced when it could match invalid UTF-8. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Literal { + /// A single character represented by a Unicode scalar value. + Unicode(char), + /// A single character represented by an arbitrary byte. + Byte(u8), +} + +impl Literal { + /// Returns true if and only if this literal corresponds to a Unicode + /// scalar value. + pub fn is_unicode(&self) -> bool { + match *self { + Literal::Unicode(_) => true, + Literal::Byte(b) if b <= 0x7F => true, + Literal::Byte(_) => false, + } + } +} + +/// The high-level intermediate representation of a character class. +/// +/// A character class corresponds to a set of characters. A character is either +/// defined by a Unicode scalar value or a byte. Unicode characters are used +/// by default, while bytes are used when Unicode mode (via the `u` flag) is +/// disabled. +/// +/// A character class, regardless of its character type, is represented by a +/// sequence of non-overlapping non-adjacent ranges of characters. +/// +/// Note that unlike [`Literal`](enum.Literal.html), a `Bytes` variant may +/// be produced even when it exclusively matches valid UTF-8. This is because +/// a `Bytes` variant represents an intention by the author of the regular +/// expression to disable Unicode mode, which in turn impacts the semantics of +/// case insensitive matching. For example, `(?i)k` and `(?i-u)k` will not +/// match the same set of strings. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Class { + /// A set of characters represented by Unicode scalar values. + Unicode(ClassUnicode), + /// A set of characters represented by arbitrary bytes (one byte per + /// character). + Bytes(ClassBytes), +} + +impl Class { + /// Apply Unicode simple case folding to this character class, in place. + /// The character class will be expanded to include all simple case folded + /// character variants. + /// + /// If this is a byte oriented character class, then this will be limited + /// to the ASCII ranges `A-Z` and `a-z`. + pub fn case_fold_simple(&mut self) { + match *self { + Class::Unicode(ref mut x) => x.case_fold_simple(), + Class::Bytes(ref mut x) => x.case_fold_simple(), + } + } + + /// Negate this character class in place. + /// + /// After completion, this character class will contain precisely the + /// characters that weren't previously in the class. + pub fn negate(&mut self) { + match *self { + Class::Unicode(ref mut x) => x.negate(), + Class::Bytes(ref mut x) => x.negate(), + } + } + + /// Returns true if and only if this character class will only ever match + /// valid UTF-8. + /// + /// A character class can match invalid UTF-8 only when the following + /// conditions are met: + /// + /// 1. The translator was configured to permit generating an expression + /// that can match invalid UTF-8. (By default, this is disabled.) + /// 2. Unicode mode (via the `u` flag) was disabled either in the concrete + /// syntax or in the parser builder. By default, Unicode mode is + /// enabled. + pub fn is_always_utf8(&self) -> bool { + match *self { + Class::Unicode(_) => true, + Class::Bytes(ref x) => x.is_all_ascii(), + } + } +} + +/// A set of characters represented by Unicode scalar values. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassUnicode { + set: IntervalSet<ClassUnicodeRange>, +} + +impl ClassUnicode { + /// Create a new class from a sequence of ranges. + /// + /// The given ranges do not need to be in any specific order, and ranges + /// may overlap. + pub fn new<I>(ranges: I) -> ClassUnicode + where I: IntoIterator<Item=ClassUnicodeRange> + { + ClassUnicode { set: IntervalSet::new(ranges) } + } + + /// Create a new class with no ranges. + pub fn empty() -> ClassUnicode { + ClassUnicode::new(vec![]) + } + + /// Add a new range to this set. + pub fn push(&mut self, range: ClassUnicodeRange) { + self.set.push(range); + } + + /// Return an iterator over all ranges in this class. + /// + /// The iterator yields ranges in ascending order. + pub fn iter(&self) -> ClassUnicodeIter { + ClassUnicodeIter(self.set.iter()) + } + + /// Return the underlying ranges as a slice. + pub fn ranges(&self) -> &[ClassUnicodeRange] { + self.set.intervals() + } + + /// Expand this character class such that it contains all case folded + /// characters, according to Unicode's "simple" mapping. For example, if + /// this class consists of the range `a-z`, then applying case folding will + /// result in the class containing both the ranges `a-z` and `A-Z`. + pub fn case_fold_simple(&mut self) { + self.set.case_fold_simple(); + } + + /// Negate this character class. + /// + /// For all `c` where `c` is a Unicode scalar value, if `c` was in this + /// set, then it will not be in this set after negation. + pub fn negate(&mut self) { + self.set.negate(); + } + + /// Union this character class with the given character class, in place. + pub fn union(&mut self, other: &ClassUnicode) { + self.set.union(&other.set); + } + + /// Intersect this character class with the given character class, in + /// place. + pub fn intersect(&mut self, other: &ClassUnicode) { + self.set.intersect(&other.set); + } + + /// Subtract the given character class from this character class, in place. + pub fn difference(&mut self, other: &ClassUnicode) { + self.set.difference(&other.set); + } + + /// Compute the symmetric difference of the given character classes, in + /// place. + /// + /// This computes the symmetric difference of two character classes. This + /// removes all elements in this class that are also in the given class, + /// but all adds all elements from the given class that aren't in this + /// class. That is, the class will contain all elements in either class, + /// but will not contain any elements that are in both classes. + pub fn symmetric_difference(&mut self, other: &ClassUnicode) { + self.set.symmetric_difference(&other.set); + } +} + +/// An iterator over all ranges in a Unicode character class. +/// +/// The lifetime `'a` refers to the lifetime of the underlying class. +#[derive(Debug)] +pub struct ClassUnicodeIter<'a>(IntervalSetIter<'a, ClassUnicodeRange>); + +impl<'a> Iterator for ClassUnicodeIter<'a> { + type Item = &'a ClassUnicodeRange; + + fn next(&mut self) -> Option<&'a ClassUnicodeRange> { + self.0.next() + } +} + +/// A single range of characters represented by Unicode scalar values. +/// +/// The range is closed. That is, the start and end of the range are included +/// in the range. +#[derive(Clone, Copy, Default, Eq, PartialEq, PartialOrd, Ord)] +pub struct ClassUnicodeRange { + start: char, + end: char, +} + +impl fmt::Debug for ClassUnicodeRange { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let start = + if !self.start.is_whitespace() && !self.start.is_control() { + self.start.to_string() + } else { + format!("0x{:X}", self.start as u32) + }; + let end = + if !self.end.is_whitespace() && !self.end.is_control() { + self.end.to_string() + } else { + format!("0x{:X}", self.end as u32) + }; + f.debug_struct("ClassUnicodeRange") + .field("start", &start) + .field("end", &end) + .finish() + } +} + +impl Interval for ClassUnicodeRange { + type Bound = char; + + #[inline] fn lower(&self) -> char { self.start } + #[inline] fn upper(&self) -> char { self.end } + #[inline] fn set_lower(&mut self, bound: char) { self.start = bound; } + #[inline] fn set_upper(&mut self, bound: char) { self.end = bound; } + + /// Apply simple case folding to this Unicode scalar value range. + /// + /// Additional ranges are appended to the given vector. Canonical ordering + /// is *not* maintained in the given vector. + fn case_fold_simple(&self, ranges: &mut Vec<ClassUnicodeRange>) { + if !unicode::contains_simple_case_mapping(self.start, self.end) { + return; + } + let start = self.start as u32; + let end = (self.end as u32).saturating_add(1); + let mut next_simple_cp = None; + for cp in (start..end).filter_map(char::from_u32) { + if next_simple_cp.map_or(false, |next| cp < next) { + continue; + } + let it = match unicode::simple_fold(cp) { + Ok(it) => it, + Err(next) => { + next_simple_cp = next; + continue; + } + }; + for cp_folded in it { + ranges.push(ClassUnicodeRange::new(cp_folded, cp_folded)); + } + } + } +} + +impl ClassUnicodeRange { + /// Create a new Unicode scalar value range for a character class. + /// + /// The returned range is always in a canonical form. That is, the range + /// returned always satisfies the invariant that `start <= end`. + pub fn new(start: char, end: char) -> ClassUnicodeRange { + ClassUnicodeRange::create(start, end) + } + + /// Return the start of this range. + /// + /// The start of a range is always less than or equal to the end of the + /// range. + pub fn start(&self) -> char { + self.start + } + + /// Return the end of this range. + /// + /// The end of a range is always greater than or equal to the start of the + /// range. + pub fn end(&self) -> char { + self.end + } +} + +/// A set of characters represented by arbitrary bytes (where one byte +/// corresponds to one character). +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ClassBytes { + set: IntervalSet<ClassBytesRange>, +} + +impl ClassBytes { + /// Create a new class from a sequence of ranges. + /// + /// The given ranges do not need to be in any specific order, and ranges + /// may overlap. + pub fn new<I>(ranges: I) -> ClassBytes + where I: IntoIterator<Item=ClassBytesRange> + { + ClassBytes { set: IntervalSet::new(ranges) } + } + + /// Create a new class with no ranges. + pub fn empty() -> ClassBytes { + ClassBytes::new(vec![]) + } + + /// Add a new range to this set. + pub fn push(&mut self, range: ClassBytesRange) { + self.set.push(range); + } + + /// Return an iterator over all ranges in this class. + /// + /// The iterator yields ranges in ascending order. + pub fn iter(&self) -> ClassBytesIter { + ClassBytesIter(self.set.iter()) + } + + /// Return the underlying ranges as a slice. + pub fn ranges(&self) -> &[ClassBytesRange] { + self.set.intervals() + } + + /// Expand this character class such that it contains all case folded + /// characters. For example, if this class consists of the range `a-z`, + /// then applying case folding will result in the class containing both the + /// ranges `a-z` and `A-Z`. + /// + /// Note that this only applies ASCII case folding, which is limited to the + /// characters `a-z` and `A-Z`. + pub fn case_fold_simple(&mut self) { + self.set.case_fold_simple(); + } + + /// Negate this byte class. + /// + /// For all `b` where `b` is a any byte, if `b` was in this set, then it + /// will not be in this set after negation. + pub fn negate(&mut self) { + self.set.negate(); + } + + /// Union this byte class with the given byte class, in place. + pub fn union(&mut self, other: &ClassBytes) { + self.set.union(&other.set); + } + + /// Intersect this byte class with the given byte class, in place. + pub fn intersect(&mut self, other: &ClassBytes) { + self.set.intersect(&other.set); + } + + /// Subtract the given byte class from this byte class, in place. + pub fn difference(&mut self, other: &ClassBytes) { + self.set.difference(&other.set); + } + + /// Compute the symmetric difference of the given byte classes, in place. + /// + /// This computes the symmetric difference of two byte classes. This + /// removes all elements in this class that are also in the given class, + /// but all adds all elements from the given class that aren't in this + /// class. That is, the class will contain all elements in either class, + /// but will not contain any elements that are in both classes. + pub fn symmetric_difference(&mut self, other: &ClassBytes) { + self.set.symmetric_difference(&other.set); + } + + /// Returns true if and only if this character class will either match + /// nothing or only ASCII bytes. Stated differently, this returns false + /// if and only if this class contains a non-ASCII byte. + pub fn is_all_ascii(&self) -> bool { + self.set.intervals().last().map_or(true, |r| r.end <= 0x7F) + } +} + +/// An iterator over all ranges in a byte character class. +/// +/// The lifetime `'a` refers to the lifetime of the underlying class. +#[derive(Debug)] +pub struct ClassBytesIter<'a>(IntervalSetIter<'a, ClassBytesRange>); + +impl<'a> Iterator for ClassBytesIter<'a> { + type Item = &'a ClassBytesRange; + + fn next(&mut self) -> Option<&'a ClassBytesRange> { + self.0.next() + } +} + +/// A single range of characters represented by arbitrary bytes. +/// +/// The range is closed. That is, the start and end of the range are included +/// in the range. +#[derive(Clone, Copy, Default, Eq, PartialEq, PartialOrd, Ord)] +pub struct ClassBytesRange { + start: u8, + end: u8, +} + +impl Interval for ClassBytesRange { + type Bound = u8; + + #[inline] fn lower(&self) -> u8 { self.start } + #[inline] fn upper(&self) -> u8 { self.end } + #[inline] fn set_lower(&mut self, bound: u8) { self.start = bound; } + #[inline] fn set_upper(&mut self, bound: u8) { self.end = bound; } + + /// Apply simple case folding to this byte range. Only ASCII case mappings + /// (for a-z) are applied. + /// + /// Additional ranges are appended to the given vector. Canonical ordering + /// is *not* maintained in the given vector. + fn case_fold_simple(&self, ranges: &mut Vec<ClassBytesRange>) { + if !ClassBytesRange::new(b'a', b'z').is_intersection_empty(self) { + let lower = cmp::max(self.start, b'a'); + let upper = cmp::min(self.end, b'z'); + ranges.push(ClassBytesRange::new(lower - 32, upper - 32)); + } + if !ClassBytesRange::new(b'A', b'Z').is_intersection_empty(self) { + let lower = cmp::max(self.start, b'A'); + let upper = cmp::min(self.end, b'Z'); + ranges.push(ClassBytesRange::new(lower + 32, upper + 32)); + } + } +} + +impl ClassBytesRange { + /// Create a new byte range for a character class. + /// + /// The returned range is always in a canonical form. That is, the range + /// returned always satisfies the invariant that `start <= end`. + pub fn new(start: u8, end: u8) -> ClassBytesRange { + ClassBytesRange::create(start, end) + } + + /// Return the start of this range. + /// + /// The start of a range is always less than or equal to the end of the + /// range. + pub fn start(&self) -> u8 { + self.start + } + + /// Return the end of this range. + /// + /// The end of a range is always greater than or equal to the start of the + /// range. + pub fn end(&self) -> u8 { + self.end + } +} + +impl fmt::Debug for ClassBytesRange { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut debug = f.debug_struct("ClassBytesRange"); + if self.start <= 0x7F { + debug.field("start", &(self.start as char)); + } else { + debug.field("start", &self.start); + } + if self.end <= 0x7F { + debug.field("end", &(self.end as char)); + } else { + debug.field("end", &self.end); + } + debug.finish() + } +} + +/// The high-level intermediate representation for an anchor assertion. +/// +/// A matching anchor assertion is always zero-length. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Anchor { + /// Match the beginning of a line or the beginning of text. Specifically, + /// this matches at the starting position of the input, or at the position + /// immediately following a `\n` character. + StartLine, + /// Match the end of a line or the end of text. Specifically, + /// this matches at the end position of the input, or at the position + /// immediately preceding a `\n` character. + EndLine, + /// Match the beginning of text. Specifically, this matches at the starting + /// position of the input. + StartText, + /// Match the end of text. Specifically, this matches at the ending + /// position of the input. + EndText, +} + +/// The high-level intermediate representation for a word-boundary assertion. +/// +/// A matching word boundary assertion is always zero-length. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum WordBoundary { + /// Match a Unicode-aware word boundary. That is, this matches a position + /// where the left adjacent character and right adjacent character + /// correspond to a word and non-word or a non-word and word character. + Unicode, + /// Match a Unicode-aware negation of a word boundary. + UnicodeNegate, + /// Match an ASCII-only word boundary. That is, this matches a position + /// where the left adjacent character and right adjacent character + /// correspond to a word and non-word or a non-word and word character. + Ascii, + /// Match an ASCII-only negation of a word boundary. + AsciiNegate, +} + +impl WordBoundary { + /// Returns true if and only if this word boundary assertion is negated. + pub fn is_negated(&self) -> bool { + match *self { + WordBoundary::Unicode | WordBoundary::Ascii => false, + WordBoundary::UnicodeNegate | WordBoundary::AsciiNegate => true, + } + } +} + +/// The high-level intermediate representation for a group. +/// +/// This represents one of three possible group types: +/// +/// 1. A non-capturing group (e.g., `(?:expr)`). +/// 2. A capturing group (e.g., `(expr)`). +/// 3. A named capturing group (e.g., `(?P<name>expr)`). +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Group { + /// The kind of this group. If it is a capturing group, then the kind + /// contains the capture group index (and the name, if it is a named + /// group). + pub kind: GroupKind, + /// The expression inside the capturing group, which may be empty. + pub hir: Box<Hir>, +} + +/// The kind of group. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum GroupKind { + /// A normal unnamed capturing group. + /// + /// The value is the capture index of the group. + CaptureIndex(u32), + /// A named capturing group. + CaptureName { + /// The name of the group. + name: String, + /// The capture index of the group. + index: u32, + }, + /// A non-capturing group. + NonCapturing, +} + +/// The high-level intermediate representation of a repetition operator. +/// +/// A repetition operator permits the repetition of an arbitrary +/// sub-expression. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Repetition { + /// The kind of this repetition operator. + pub kind: RepetitionKind, + /// Whether this repetition operator is greedy or not. A greedy operator + /// will match as much as it can. A non-greedy operator will match as + /// little as it can. + /// + /// Typically, operators are greedy by default and are only non-greedy when + /// a `?` suffix is used, e.g., `(expr)*` is greedy while `(expr)*?` is + /// not. However, this can be inverted via the `U` "ungreedy" flag. + pub greedy: bool, + /// The expression being repeated. + pub hir: Box<Hir>, +} + +impl Repetition { + /// Returns true if and only if this repetition operator makes it possible + /// to match the empty string. + /// + /// Note that this is not defined inductively. For example, while `a*` + /// will report `true`, `()+` will not, even though `()` matches the empty + /// string and one or more occurrences of something that matches the empty + /// string will always match the empty string. In order to get the + /// inductive definition, see the corresponding method on + /// [`Hir`](struct.Hir.html). + pub fn is_match_empty(&self) -> bool { + match self.kind { + RepetitionKind::ZeroOrOne => true, + RepetitionKind::ZeroOrMore => true, + RepetitionKind::OneOrMore => false, + RepetitionKind::Range(RepetitionRange::Exactly(m)) => m == 0, + RepetitionKind::Range(RepetitionRange::AtLeast(m)) => m == 0, + RepetitionKind::Range(RepetitionRange::Bounded(m, _)) => m == 0, + } + } +} + +/// The kind of a repetition operator. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum RepetitionKind { + /// Matches a sub-expression zero or one times. + ZeroOrOne, + /// Matches a sub-expression zero or more times. + ZeroOrMore, + /// Matches a sub-expression one or more times. + OneOrMore, + /// Matches a sub-expression within a bounded range of times. + Range(RepetitionRange), +} + +/// The kind of a counted repetition operator. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum RepetitionRange { + /// Matches a sub-expression exactly this many times. + Exactly(u32), + /// Matches a sub-expression at least this many times. + AtLeast(u32), + /// Matches a sub-expression at least `m` times and at most `n` times. + Bounded(u32, u32), +} + +/// A custom `Drop` impl is used for `HirKind` such that it uses constant stack +/// space but heap space proportional to the depth of the total `Hir`. +impl Drop for Hir { + fn drop(&mut self) { + use std::mem; + + match *self.kind() { + HirKind::Empty + | HirKind::Literal(_) + | HirKind::Class(_) + | HirKind::Anchor(_) + | HirKind::WordBoundary(_) => return, + HirKind::Group(ref x) if !x.hir.kind.has_subexprs() => return, + HirKind::Repetition(ref x) if !x.hir.kind.has_subexprs() => return, + HirKind::Concat(ref x) if x.is_empty() => return, + HirKind::Alternation(ref x) if x.is_empty() => return, + _ => {} + } + + let mut stack = vec![mem::replace(self, Hir::empty())]; + while let Some(mut expr) = stack.pop() { + match expr.kind { + HirKind::Empty + | HirKind::Literal(_) + | HirKind::Class(_) + | HirKind::Anchor(_) + | HirKind::WordBoundary(_) => {} + HirKind::Group(ref mut x) => { + stack.push(mem::replace(&mut x.hir, Hir::empty())); + } + HirKind::Repetition(ref mut x) => { + stack.push(mem::replace(&mut x.hir, Hir::empty())); + } + HirKind::Concat(ref mut x) => { + stack.extend(x.drain(..)); + } + HirKind::Alternation(ref mut x) => { + stack.extend(x.drain(..)); + } + } + } + } +} + +/// A type that documents various attributes of an HIR expression. +/// +/// These attributes are typically defined inductively on the HIR. +#[derive(Clone, Debug, Eq, PartialEq)] +struct HirInfo { + /// Represent yes/no questions by a bitfield to conserve space, since + /// this is included in every HIR expression. + /// + /// If more attributes need to be added, it is OK to increase the size of + /// this as appropriate. + bools: u8, +} + +// A simple macro for defining bitfield accessors/mutators. +macro_rules! define_bool { + ($bit:expr, $is_fn_name:ident, $set_fn_name:ident) => { + fn $is_fn_name(&self) -> bool { + self.bools & (0b1 << $bit) > 0 + } + + fn $set_fn_name(&mut self, yes: bool) { + if yes { + self.bools |= 1 << $bit; + } else { + self.bools &= !(1 << $bit); + } + } + } +} + +impl HirInfo { + fn new() -> HirInfo { + HirInfo { + bools: 0, + } + } + + define_bool!(0, is_always_utf8, set_always_utf8); + define_bool!(1, is_all_assertions, set_all_assertions); + define_bool!(2, is_anchored_start, set_anchored_start); + define_bool!(3, is_anchored_end, set_anchored_end); + define_bool!(4, is_any_anchored_start, set_any_anchored_start); + define_bool!(5, is_any_anchored_end, set_any_anchored_end); + define_bool!(6, is_match_empty, set_match_empty); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn uclass(ranges: &[(char, char)]) -> ClassUnicode { + let ranges: Vec<ClassUnicodeRange> = ranges + .iter() + .map(|&(s, e)| ClassUnicodeRange::new(s, e)) + .collect(); + ClassUnicode::new(ranges) + } + + fn bclass(ranges: &[(u8, u8)]) -> ClassBytes { + let ranges: Vec<ClassBytesRange> = ranges + .iter() + .map(|&(s, e)| ClassBytesRange::new(s, e)) + .collect(); + ClassBytes::new(ranges) + } + + fn uranges(cls: &ClassUnicode) -> Vec<(char, char)> { + cls.iter().map(|x| (x.start(), x.end())).collect() + } + + fn ucasefold(cls: &ClassUnicode) -> ClassUnicode { + let mut cls_ = cls.clone(); + cls_.case_fold_simple(); + cls_ + } + + fn uunion(cls1: &ClassUnicode, cls2: &ClassUnicode) -> ClassUnicode { + let mut cls_ = cls1.clone(); + cls_.union(cls2); + cls_ + } + + fn uintersect(cls1: &ClassUnicode, cls2: &ClassUnicode) -> ClassUnicode { + let mut cls_ = cls1.clone(); + cls_.intersect(cls2); + cls_ + } + + fn udifference(cls1: &ClassUnicode, cls2: &ClassUnicode) -> ClassUnicode { + let mut cls_ = cls1.clone(); + cls_.difference(cls2); + cls_ + } + + fn usymdifference(cls1: &ClassUnicode, cls2: &ClassUnicode) -> ClassUnicode { + let mut cls_ = cls1.clone(); + cls_.symmetric_difference(cls2); + cls_ + } + + fn unegate(cls: &ClassUnicode) -> ClassUnicode { + let mut cls_ = cls.clone(); + cls_.negate(); + cls_ + } + + fn branges(cls: &ClassBytes) -> Vec<(u8, u8)> { + cls.iter().map(|x| (x.start(), x.end())).collect() + } + + fn bcasefold(cls: &ClassBytes) -> ClassBytes { + let mut cls_ = cls.clone(); + cls_.case_fold_simple(); + cls_ + } + + fn bunion(cls1: &ClassBytes, cls2: &ClassBytes) -> ClassBytes { + let mut cls_ = cls1.clone(); + cls_.union(cls2); + cls_ + } + + fn bintersect(cls1: &ClassBytes, cls2: &ClassBytes) -> ClassBytes { + let mut cls_ = cls1.clone(); + cls_.intersect(cls2); + cls_ + } + + fn bdifference(cls1: &ClassBytes, cls2: &ClassBytes) -> ClassBytes { + let mut cls_ = cls1.clone(); + cls_.difference(cls2); + cls_ + } + + fn bsymdifference(cls1: &ClassBytes, cls2: &ClassBytes) -> ClassBytes { + let mut cls_ = cls1.clone(); + cls_.symmetric_difference(cls2); + cls_ + } + + fn bnegate(cls: &ClassBytes) -> ClassBytes { + let mut cls_ = cls.clone(); + cls_.negate(); + cls_ + } + + #[test] + fn class_range_canonical_unicode() { + let range = ClassUnicodeRange::new('\u{00FF}', '\0'); + assert_eq!('\0', range.start()); + assert_eq!('\u{00FF}', range.end()); + } + + #[test] + fn class_range_canonical_bytes() { + let range = ClassBytesRange::new(b'\xFF', b'\0'); + assert_eq!(b'\0', range.start()); + assert_eq!(b'\xFF', range.end()); + } + + #[test] + fn class_canonicalize_unicode() { + let cls = uclass(&[('a', 'c'), ('x', 'z')]); + let expected = vec![('a', 'c'), ('x', 'z')]; + assert_eq!(expected, uranges(&cls)); + + let cls = uclass(&[('x', 'z'), ('a', 'c')]); + let expected = vec![('a', 'c'), ('x', 'z')]; + assert_eq!(expected, uranges(&cls)); + + let cls = uclass(&[('x', 'z'), ('w', 'y')]); + let expected = vec![('w', 'z')]; + assert_eq!(expected, uranges(&cls)); + + let cls = uclass(&[ + ('c', 'f'), ('a', 'g'), ('d', 'j'), ('a', 'c'), + ('m', 'p'), ('l', 's'), + ]); + let expected = vec![('a', 'j'), ('l', 's')]; + assert_eq!(expected, uranges(&cls)); + + let cls = uclass(&[('x', 'z'), ('u', 'w')]); + let expected = vec![('u', 'z')]; + assert_eq!(expected, uranges(&cls)); + + let cls = uclass(&[('\x00', '\u{10FFFF}'), ('\x00', '\u{10FFFF}')]); + let expected = vec![('\x00', '\u{10FFFF}')]; + assert_eq!(expected, uranges(&cls)); + + + let cls = uclass(&[('a', 'a'), ('b', 'b')]); + let expected = vec![('a', 'b')]; + assert_eq!(expected, uranges(&cls)); + } + + #[test] + fn class_canonicalize_bytes() { + let cls = bclass(&[(b'a', b'c'), (b'x', b'z')]); + let expected = vec![(b'a', b'c'), (b'x', b'z')]; + assert_eq!(expected, branges(&cls)); + + let cls = bclass(&[(b'x', b'z'), (b'a', b'c')]); + let expected = vec![(b'a', b'c'), (b'x', b'z')]; + assert_eq!(expected, branges(&cls)); + + let cls = bclass(&[(b'x', b'z'), (b'w', b'y')]); + let expected = vec![(b'w', b'z')]; + assert_eq!(expected, branges(&cls)); + + let cls = bclass(&[ + (b'c', b'f'), (b'a', b'g'), (b'd', b'j'), (b'a', b'c'), + (b'm', b'p'), (b'l', b's'), + ]); + let expected = vec![(b'a', b'j'), (b'l', b's')]; + assert_eq!(expected, branges(&cls)); + + let cls = bclass(&[(b'x', b'z'), (b'u', b'w')]); + let expected = vec![(b'u', b'z')]; + assert_eq!(expected, branges(&cls)); + + let cls = bclass(&[(b'\x00', b'\xFF'), (b'\x00', b'\xFF')]); + let expected = vec![(b'\x00', b'\xFF')]; + assert_eq!(expected, branges(&cls)); + + let cls = bclass(&[(b'a', b'a'), (b'b', b'b')]); + let expected = vec![(b'a', b'b')]; + assert_eq!(expected, branges(&cls)); + } + + #[test] + fn class_case_fold_unicode() { + let cls = uclass(&[ + ('C', 'F'), ('A', 'G'), ('D', 'J'), ('A', 'C'), + ('M', 'P'), ('L', 'S'), ('c', 'f'), + ]); + let expected = uclass(&[ + ('A', 'J'), ('L', 'S'), + ('a', 'j'), ('l', 's'), + ('\u{17F}', '\u{17F}'), + ]); + assert_eq!(expected, ucasefold(&cls)); + + let cls = uclass(&[('A', 'Z')]); + let expected = uclass(&[ + ('A', 'Z'), ('a', 'z'), + ('\u{17F}', '\u{17F}'), + ('\u{212A}', '\u{212A}'), + ]); + assert_eq!(expected, ucasefold(&cls)); + + let cls = uclass(&[('a', 'z')]); + let expected = uclass(&[ + ('A', 'Z'), ('a', 'z'), + ('\u{17F}', '\u{17F}'), + ('\u{212A}', '\u{212A}'), + ]); + assert_eq!(expected, ucasefold(&cls)); + + let cls = uclass(&[('A', 'A'), ('_', '_')]); + let expected = uclass(&[('A', 'A'), ('_', '_'), ('a', 'a')]); + assert_eq!(expected, ucasefold(&cls)); + + let cls = uclass(&[('A', 'A'), ('=', '=')]); + let expected = uclass(&[('=', '='), ('A', 'A'), ('a', 'a')]); + assert_eq!(expected, ucasefold(&cls)); + + let cls = uclass(&[('\x00', '\x10')]); + assert_eq!(cls, ucasefold(&cls)); + + let cls = uclass(&[('k', 'k')]); + let expected = uclass(&[ + ('K', 'K'), ('k', 'k'), ('\u{212A}', '\u{212A}'), + ]); + assert_eq!(expected, ucasefold(&cls)); + + let cls = uclass(&[('@', '@')]); + assert_eq!(cls, ucasefold(&cls)); + } + + #[test] + fn class_case_fold_bytes() { + let cls = bclass(&[ + (b'C', b'F'), (b'A', b'G'), (b'D', b'J'), (b'A', b'C'), + (b'M', b'P'), (b'L', b'S'), (b'c', b'f'), + ]); + let expected = bclass(&[ + (b'A', b'J'), (b'L', b'S'), + (b'a', b'j'), (b'l', b's'), + ]); + assert_eq!(expected, bcasefold(&cls)); + + let cls = bclass(&[(b'A', b'Z')]); + let expected = bclass(&[(b'A', b'Z'), (b'a', b'z')]); + assert_eq!(expected, bcasefold(&cls)); + + let cls = bclass(&[(b'a', b'z')]); + let expected = bclass(&[(b'A', b'Z'), (b'a', b'z')]); + assert_eq!(expected, bcasefold(&cls)); + + let cls = bclass(&[(b'A', b'A'), (b'_', b'_')]); + let expected = bclass(&[(b'A', b'A'), (b'_', b'_'), (b'a', b'a')]); + assert_eq!(expected, bcasefold(&cls)); + + let cls = bclass(&[(b'A', b'A'), (b'=', b'=')]); + let expected = bclass(&[(b'=', b'='), (b'A', b'A'), (b'a', b'a')]); + assert_eq!(expected, bcasefold(&cls)); + + let cls = bclass(&[(b'\x00', b'\x10')]); + assert_eq!(cls, bcasefold(&cls)); + + let cls = bclass(&[(b'k', b'k')]); + let expected = bclass(&[(b'K', b'K'), (b'k', b'k')]); + assert_eq!(expected, bcasefold(&cls)); + + let cls = bclass(&[(b'@', b'@')]); + assert_eq!(cls, bcasefold(&cls)); + } + + #[test] + fn class_negate_unicode() { + let cls = uclass(&[('a', 'a')]); + let expected = uclass(&[('\x00', '\x60'), ('\x62', '\u{10FFFF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('a', 'a'), ('b', 'b')]); + let expected = uclass(&[('\x00', '\x60'), ('\x63', '\u{10FFFF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('a', 'c'), ('x', 'z')]); + let expected = uclass(&[ + ('\x00', '\x60'), ('\x64', '\x77'), ('\x7B', '\u{10FFFF}'), + ]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('\x00', 'a')]); + let expected = uclass(&[('\x62', '\u{10FFFF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('a', '\u{10FFFF}')]); + let expected = uclass(&[('\x00', '\x60')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('\x00', '\u{10FFFF}')]); + let expected = uclass(&[]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[]); + let expected = uclass(&[('\x00', '\u{10FFFF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[ + ('\x00', '\u{10FFFD}'), ('\u{10FFFF}', '\u{10FFFF}'), + ]); + let expected = uclass(&[('\u{10FFFE}', '\u{10FFFE}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('\x00', '\u{D7FF}')]); + let expected = uclass(&[('\u{E000}', '\u{10FFFF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('\x00', '\u{D7FE}')]); + let expected = uclass(&[('\u{D7FF}', '\u{10FFFF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('\u{E000}', '\u{10FFFF}')]); + let expected = uclass(&[('\x00', '\u{D7FF}')]); + assert_eq!(expected, unegate(&cls)); + + let cls = uclass(&[('\u{E001}', '\u{10FFFF}')]); + let expected = uclass(&[('\x00', '\u{E000}')]); + assert_eq!(expected, unegate(&cls)); + } + + #[test] + fn class_negate_bytes() { + let cls = bclass(&[(b'a', b'a')]); + let expected = bclass(&[(b'\x00', b'\x60'), (b'\x62', b'\xFF')]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[(b'a', b'a'), (b'b', b'b')]); + let expected = bclass(&[(b'\x00', b'\x60'), (b'\x63', b'\xFF')]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[(b'a', b'c'), (b'x', b'z')]); + let expected = bclass(&[ + (b'\x00', b'\x60'), (b'\x64', b'\x77'), (b'\x7B', b'\xFF'), + ]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[(b'\x00', b'a')]); + let expected = bclass(&[(b'\x62', b'\xFF')]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[(b'a', b'\xFF')]); + let expected = bclass(&[(b'\x00', b'\x60')]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[(b'\x00', b'\xFF')]); + let expected = bclass(&[]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[]); + let expected = bclass(&[(b'\x00', b'\xFF')]); + assert_eq!(expected, bnegate(&cls)); + + let cls = bclass(&[(b'\x00', b'\xFD'), (b'\xFF', b'\xFF')]); + let expected = bclass(&[(b'\xFE', b'\xFE')]); + assert_eq!(expected, bnegate(&cls)); + } + + #[test] + fn class_union_unicode() { + let cls1 = uclass(&[('a', 'g'), ('m', 't'), ('A', 'C')]); + let cls2 = uclass(&[('a', 'z')]); + let expected = uclass(&[('a', 'z'), ('A', 'C')]); + assert_eq!(expected, uunion(&cls1, &cls2)); + } + + #[test] + fn class_union_bytes() { + let cls1 = bclass(&[(b'a', b'g'), (b'm', b't'), (b'A', b'C')]); + let cls2 = bclass(&[(b'a', b'z')]); + let expected = bclass(&[(b'a', b'z'), (b'A', b'C')]); + assert_eq!(expected, bunion(&cls1, &cls2)); + } + + #[test] + fn class_intersect_unicode() { + let cls1 = uclass(&[]); + let cls2 = uclass(&[('a', 'a')]); + let expected = uclass(&[]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'a')]); + let cls2 = uclass(&[('a', 'a')]); + let expected = uclass(&[('a', 'a')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'a')]); + let cls2 = uclass(&[('b', 'b')]); + let expected = uclass(&[]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'a')]); + let cls2 = uclass(&[('a', 'c')]); + let expected = uclass(&[('a', 'a')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b')]); + let cls2 = uclass(&[('a', 'c')]); + let expected = uclass(&[('a', 'b')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b')]); + let cls2 = uclass(&[('b', 'c')]); + let expected = uclass(&[('b', 'b')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b')]); + let cls2 = uclass(&[('c', 'd')]); + let expected = uclass(&[]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('b', 'c')]); + let cls2 = uclass(&[('a', 'd')]); + let expected = uclass(&[('b', 'c')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); + let cls2 = uclass(&[('a', 'h')]); + let expected = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); + let cls2 = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); + let expected = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b'), ('g', 'h')]); + let cls2 = uclass(&[('d', 'e'), ('k', 'l')]); + let expected = uclass(&[]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b'), ('d', 'e'), ('g', 'h')]); + let cls2 = uclass(&[('h', 'h')]); + let expected = uclass(&[('h', 'h')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b'), ('e', 'f'), ('i', 'j')]); + let cls2 = uclass(&[('c', 'd'), ('g', 'h'), ('k', 'l')]); + let expected = uclass(&[]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'b'), ('c', 'd'), ('e', 'f')]); + let cls2 = uclass(&[('b', 'c'), ('d', 'e'), ('f', 'g')]); + let expected = uclass(&[('b', 'f')]); + assert_eq!(expected, uintersect(&cls1, &cls2)); + } + + #[test] + fn class_intersect_bytes() { + let cls1 = bclass(&[]); + let cls2 = bclass(&[(b'a', b'a')]); + let expected = bclass(&[]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'a')]); + let cls2 = bclass(&[(b'a', b'a')]); + let expected = bclass(&[(b'a', b'a')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'a')]); + let cls2 = bclass(&[(b'b', b'b')]); + let expected = bclass(&[]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'a')]); + let cls2 = bclass(&[(b'a', b'c')]); + let expected = bclass(&[(b'a', b'a')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b')]); + let cls2 = bclass(&[(b'a', b'c')]); + let expected = bclass(&[(b'a', b'b')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b')]); + let cls2 = bclass(&[(b'b', b'c')]); + let expected = bclass(&[(b'b', b'b')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b')]); + let cls2 = bclass(&[(b'c', b'd')]); + let expected = bclass(&[]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'b', b'c')]); + let cls2 = bclass(&[(b'a', b'd')]); + let expected = bclass(&[(b'b', b'c')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]); + let cls2 = bclass(&[(b'a', b'h')]); + let expected = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]); + let cls2 = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]); + let expected = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b'), (b'g', b'h')]); + let cls2 = bclass(&[(b'd', b'e'), (b'k', b'l')]); + let expected = bclass(&[]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b'), (b'd', b'e'), (b'g', b'h')]); + let cls2 = bclass(&[(b'h', b'h')]); + let expected = bclass(&[(b'h', b'h')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b'), (b'e', b'f'), (b'i', b'j')]); + let cls2 = bclass(&[(b'c', b'd'), (b'g', b'h'), (b'k', b'l')]); + let expected = bclass(&[]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'b'), (b'c', b'd'), (b'e', b'f')]); + let cls2 = bclass(&[(b'b', b'c'), (b'd', b'e'), (b'f', b'g')]); + let expected = bclass(&[(b'b', b'f')]); + assert_eq!(expected, bintersect(&cls1, &cls2)); + } + + #[test] + fn class_difference_unicode() { + let cls1 = uclass(&[('a', 'a')]); + let cls2 = uclass(&[('a', 'a')]); + let expected = uclass(&[]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'a')]); + let cls2 = uclass(&[]); + let expected = uclass(&[('a', 'a')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[]); + let cls2 = uclass(&[('a', 'a')]); + let expected = uclass(&[]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'z')]); + let cls2 = uclass(&[('a', 'a')]); + let expected = uclass(&[('b', 'z')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'z')]); + let cls2 = uclass(&[('z', 'z')]); + let expected = uclass(&[('a', 'y')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'z')]); + let cls2 = uclass(&[('m', 'm')]); + let expected = uclass(&[('a', 'l'), ('n', 'z')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'c'), ('g', 'i'), ('r', 't')]); + let cls2 = uclass(&[('a', 'z')]); + let expected = uclass(&[]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'c'), ('g', 'i'), ('r', 't')]); + let cls2 = uclass(&[('d', 'v')]); + let expected = uclass(&[('a', 'c')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'c'), ('g', 'i'), ('r', 't')]); + let cls2 = uclass(&[('b', 'g'), ('s', 'u')]); + let expected = uclass(&[('a', 'a'), ('h', 'i'), ('r', 'r')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'c'), ('g', 'i'), ('r', 't')]); + let cls2 = uclass(&[('b', 'd'), ('e', 'g'), ('s', 'u')]); + let expected = uclass(&[('a', 'a'), ('h', 'i'), ('r', 'r')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('x', 'z')]); + let cls2 = uclass(&[('a', 'c'), ('e', 'g'), ('s', 'u')]); + let expected = uclass(&[('x', 'z')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + + let cls1 = uclass(&[('a', 'z')]); + let cls2 = uclass(&[('a', 'c'), ('e', 'g'), ('s', 'u')]); + let expected = uclass(&[('d', 'd'), ('h', 'r'), ('v', 'z')]); + assert_eq!(expected, udifference(&cls1, &cls2)); + } + + #[test] + fn class_difference_bytes() { + let cls1 = bclass(&[(b'a', b'a')]); + let cls2 = bclass(&[(b'a', b'a')]); + let expected = bclass(&[]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'a')]); + let cls2 = bclass(&[]); + let expected = bclass(&[(b'a', b'a')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[]); + let cls2 = bclass(&[(b'a', b'a')]); + let expected = bclass(&[]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'z')]); + let cls2 = bclass(&[(b'a', b'a')]); + let expected = bclass(&[(b'b', b'z')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'z')]); + let cls2 = bclass(&[(b'z', b'z')]); + let expected = bclass(&[(b'a', b'y')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'z')]); + let cls2 = bclass(&[(b'm', b'm')]); + let expected = bclass(&[(b'a', b'l'), (b'n', b'z')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'c'), (b'g', b'i'), (b'r', b't')]); + let cls2 = bclass(&[(b'a', b'z')]); + let expected = bclass(&[]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'c'), (b'g', b'i'), (b'r', b't')]); + let cls2 = bclass(&[(b'd', b'v')]); + let expected = bclass(&[(b'a', b'c')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'c'), (b'g', b'i'), (b'r', b't')]); + let cls2 = bclass(&[(b'b', b'g'), (b's', b'u')]); + let expected = bclass(&[(b'a', b'a'), (b'h', b'i'), (b'r', b'r')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'c'), (b'g', b'i'), (b'r', b't')]); + let cls2 = bclass(&[(b'b', b'd'), (b'e', b'g'), (b's', b'u')]); + let expected = bclass(&[(b'a', b'a'), (b'h', b'i'), (b'r', b'r')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'x', b'z')]); + let cls2 = bclass(&[(b'a', b'c'), (b'e', b'g'), (b's', b'u')]); + let expected = bclass(&[(b'x', b'z')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + + let cls1 = bclass(&[(b'a', b'z')]); + let cls2 = bclass(&[(b'a', b'c'), (b'e', b'g'), (b's', b'u')]); + let expected = bclass(&[(b'd', b'd'), (b'h', b'r'), (b'v', b'z')]); + assert_eq!(expected, bdifference(&cls1, &cls2)); + } + + #[test] + fn class_symmetric_difference_unicode() { + let cls1 = uclass(&[('a', 'm')]); + let cls2 = uclass(&[('g', 't')]); + let expected = uclass(&[('a', 'f'), ('n', 't')]); + assert_eq!(expected, usymdifference(&cls1, &cls2)); + } + + #[test] + fn class_symmetric_difference_bytes() { + let cls1 = bclass(&[(b'a', b'm')]); + let cls2 = bclass(&[(b'g', b't')]); + let expected = bclass(&[(b'a', b'f'), (b'n', b't')]); + assert_eq!(expected, bsymdifference(&cls1, &cls2)); + } + + #[test] + #[should_panic] + fn hir_byte_literal_non_ascii() { + Hir::literal(Literal::Byte(b'a')); + } + + // We use a thread with an explicit stack size to test that our destructor + // for Hir can handle arbitrarily sized expressions in constant stack + // space. In case we run on a platform without threads (WASM?), we limit + // this test to Windows/Unix. + #[test] + #[cfg(any(unix, windows))] + fn no_stack_overflow_on_drop() { + use std::thread; + + let run = || { + let mut expr = Hir::empty(); + for _ in 0..100 { + expr = Hir::group(Group { + kind: GroupKind::NonCapturing, + hir: Box::new(expr), + }); + expr = Hir::repetition(Repetition { + kind: RepetitionKind::ZeroOrOne, + greedy: true, + hir: Box::new(expr), + }); + + expr = Hir { + kind: HirKind::Concat(vec![expr]), + info: HirInfo::new(), + }; + expr = Hir { + kind: HirKind::Alternation(vec![expr]), + info: HirInfo::new(), + }; + } + assert!(!expr.kind.is_empty()); + }; + + // We run our test on a thread with a small stack size so we can + // force the issue more easily. + thread::Builder::new() + .stack_size(1<<10) + .spawn(run) + .unwrap() + .join() + .unwrap(); + } +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/hir/print.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/hir/print.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/hir/print.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/hir/print.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,359 @@ +/*! +This module provides a regular expression printer for `Hir`. +*/ + +use std::fmt; + +use hir::{self, Hir, HirKind}; +use hir::visitor::{self, Visitor}; +use is_meta_character; + +/// A builder for constructing a printer. +/// +/// Note that since a printer doesn't have any configuration knobs, this type +/// remains unexported. +#[derive(Clone, Debug)] +struct PrinterBuilder { + _priv: (), +} + +impl Default for PrinterBuilder { + fn default() -> PrinterBuilder { + PrinterBuilder::new() + } +} + +impl PrinterBuilder { + fn new() -> PrinterBuilder { + PrinterBuilder { + _priv: (), + } + } + + fn build(&self) -> Printer { + Printer { + _priv: (), + } + } +} + +/// A printer for a regular expression's high-level intermediate +/// representation. +/// +/// A printer converts a high-level intermediate representation (HIR) to a +/// regular expression pattern string. This particular printer uses constant +/// stack space and heap space proportional to the size of the HIR. +/// +/// Since this printer is only using the HIR, the pattern it prints will likely +/// not resemble the original pattern at all. For example, a pattern like +/// `\pL` will have its entire class written out. +/// +/// The purpose of this printer is to provide a means to mutate an HIR and then +/// build a regular expression from the result of that mutation. (A regex +/// library could provide a constructor from this HIR explicitly, but that +/// creates an unnecessary public coupling between the regex library and this +/// specific HIR representation.) +#[derive(Debug)] +pub struct Printer { + _priv: (), +} + +impl Printer { + /// Create a new printer. + pub fn new() -> Printer { + PrinterBuilder::new().build() + } + + /// Print the given `Ast` to the given writer. The writer must implement + /// `fmt::Write`. Typical implementations of `fmt::Write` that can be used + /// here are a `fmt::Formatter` (which is available in `fmt::Display` + /// implementations) or a `&mut String`. + pub fn print<W: fmt::Write>(&mut self, hir: &Hir, wtr: W) -> fmt::Result { + visitor::visit(hir, Writer { printer: self, wtr: wtr }) + } +} + +#[derive(Debug)] +struct Writer<'p, W> { + printer: &'p mut Printer, + wtr: W, +} + +impl<'p, W: fmt::Write> Visitor for Writer<'p, W> { + type Output = (); + type Err = fmt::Error; + + fn finish(self) -> fmt::Result { + Ok(()) + } + + fn visit_pre(&mut self, hir: &Hir) -> fmt::Result { + match *hir.kind() { + HirKind::Empty + | HirKind::Repetition(_) + | HirKind::Concat(_) + | HirKind::Alternation(_) => {} + HirKind::Literal(hir::Literal::Unicode(c)) => { + try!(self.write_literal_char(c)); + } + HirKind::Literal(hir::Literal::Byte(b)) => { + try!(self.write_literal_byte(b)); + } + HirKind::Class(hir::Class::Unicode(ref cls)) => { + try!(self.wtr.write_str("[")); + for range in cls.iter() { + if range.start() == range.end() { + try!(self.write_literal_char(range.start())); + } else { + try!(self.write_literal_char(range.start())); + try!(self.wtr.write_str("-")); + try!(self.write_literal_char(range.end())); + } + } + try!(self.wtr.write_str("]")); + } + HirKind::Class(hir::Class::Bytes(ref cls)) => { + try!(self.wtr.write_str("(?-u:[")); + for range in cls.iter() { + if range.start() == range.end() { + try!(self.write_literal_class_byte(range.start())); + } else { + try!(self.write_literal_class_byte(range.start())); + try!(self.wtr.write_str("-")); + try!(self.write_literal_class_byte(range.end())); + } + } + try!(self.wtr.write_str("])")); + } + HirKind::Anchor(hir::Anchor::StartLine) => { + try!(self.wtr.write_str("(?m:^)")); + } + HirKind::Anchor(hir::Anchor::EndLine) => { + try!(self.wtr.write_str("(?m:$)")); + } + HirKind::Anchor(hir::Anchor::StartText) => { + try!(self.wtr.write_str(r"\A")); + } + HirKind::Anchor(hir::Anchor::EndText) => { + try!(self.wtr.write_str(r"\z")); + } + HirKind::WordBoundary(hir::WordBoundary::Unicode) => { + try!(self.wtr.write_str(r"\b")); + } + HirKind::WordBoundary(hir::WordBoundary::UnicodeNegate) => { + try!(self.wtr.write_str(r"\B")); + } + HirKind::WordBoundary(hir::WordBoundary::Ascii) => { + try!(self.wtr.write_str(r"(?-u:\b)")); + } + HirKind::WordBoundary(hir::WordBoundary::AsciiNegate) => { + try!(self.wtr.write_str(r"(?-u:\B)")); + } + HirKind::Group(ref x) => { + match x.kind { + hir::GroupKind::CaptureIndex(_) => { + try!(self.wtr.write_str("(")); + } + hir::GroupKind::CaptureName { ref name, .. } => { + try!(write!(self.wtr, "(?P<{}>", name)); + } + hir::GroupKind::NonCapturing => { + try!(self.wtr.write_str("(?:")); + } + } + } + } + Ok(()) + } + + fn visit_post(&mut self, hir: &Hir) -> fmt::Result { + match *hir.kind() { + // Handled during visit_pre + HirKind::Empty + | HirKind::Literal(_) + | HirKind::Class(_) + | HirKind::Anchor(_) + | HirKind::WordBoundary(_) + | HirKind::Concat(_) + | HirKind::Alternation(_) => {} + HirKind::Repetition(ref x) => { + match x.kind { + hir::RepetitionKind::ZeroOrOne => { + try!(self.wtr.write_str("?")); + } + hir::RepetitionKind::ZeroOrMore => { + try!(self.wtr.write_str("*")); + } + hir::RepetitionKind::OneOrMore => { + try!(self.wtr.write_str("+")); + } + hir::RepetitionKind::Range(ref x) => { + match *x { + hir::RepetitionRange::Exactly(m) => { + try!(write!(self.wtr, "{{{}}}", m)); + } + hir::RepetitionRange::AtLeast(m) => { + try!(write!(self.wtr, "{{{},}}", m)); + } + hir::RepetitionRange::Bounded(m, n) => { + try!(write!(self.wtr, "{{{},{}}}", m, n)); + } + } + } + } + if !x.greedy { + try!(self.wtr.write_str("?")); + } + } + HirKind::Group(_) => { + try!(self.wtr.write_str(")")); + } + } + Ok(()) + } + + fn visit_alternation_in(&mut self) -> fmt::Result { + self.wtr.write_str("|") + } +} + +impl<'p, W: fmt::Write> Writer<'p, W> { + fn write_literal_char(&mut self, c: char) -> fmt::Result { + if is_meta_character(c) { + try!(self.wtr.write_str("\\")); + } + self.wtr.write_char(c) + } + + fn write_literal_byte(&mut self, b: u8) -> fmt::Result { + let c = b as char; + if c <= 0x7F as char && !c.is_control() && !c.is_whitespace() { + self.wtr.write_char(c) + } else { + write!(self.wtr, "(?-u:\\x{:02X})", b) + } + } + + fn write_literal_class_byte(&mut self, b: u8) -> fmt::Result { + let c = b as char; + if c <= 0x7F as char && !c.is_control() && !c.is_whitespace() { + self.wtr.write_char(c) + } else { + write!(self.wtr, "\\x{:02X}", b) + } + } +} + +#[cfg(test)] +mod tests { + use ParserBuilder; + use super::Printer; + + fn roundtrip(given: &str, expected: &str) { + roundtrip_with(|b| b, given, expected); + } + + fn roundtrip_bytes(given: &str, expected: &str) { + roundtrip_with(|b| b.allow_invalid_utf8(true), given, expected); + } + + fn roundtrip_with<F>(mut f: F, given: &str, expected: &str) + where F: FnMut(&mut ParserBuilder) -> &mut ParserBuilder + { + let mut builder = ParserBuilder::new(); + f(&mut builder); + let hir = builder.build().parse(given).unwrap(); + + let mut printer = Printer::new(); + let mut dst = String::new(); + printer.print(&hir, &mut dst).unwrap(); + assert_eq!(expected, dst); + } + + #[test] + fn print_literal() { + roundtrip("a", "a"); + roundtrip(r"\xff", "\u{FF}"); + roundtrip_bytes(r"\xff", "\u{FF}"); + roundtrip_bytes(r"(?-u)\xff", r"(?-u:\xFF)"); + roundtrip("☃", "☃"); + } + + #[test] + fn print_class() { + roundtrip(r"[a]", r"[a]"); + roundtrip(r"[a-z]", r"[a-z]"); + roundtrip(r"[a-z--b-c--x-y]", r"[ad-wz]"); + roundtrip(r"[^\x01-\u{10FFFF}]", "[\u{0}]"); + roundtrip(r"[-]", r"[\-]"); + roundtrip(r"[☃-⛄]", r"[☃-⛄]"); + + roundtrip(r"(?-u)[a]", r"(?-u:[a])"); + roundtrip(r"(?-u)[a-z]", r"(?-u:[a-z])"); + roundtrip_bytes(r"(?-u)[a-\xFF]", r"(?-u:[a-\xFF])"); + } + + #[test] + fn print_anchor() { + roundtrip(r"^", r"\A"); + roundtrip(r"$", r"\z"); + roundtrip(r"(?m)^", r"(?m:^)"); + roundtrip(r"(?m)$", r"(?m:$)"); + } + + #[test] + fn print_word_boundary() { + roundtrip(r"\b", r"\b"); + roundtrip(r"\B", r"\B"); + roundtrip(r"(?-u)\b", r"(?-u:\b)"); + roundtrip_bytes(r"(?-u)\B", r"(?-u:\B)"); + } + + #[test] + fn print_repetition() { + roundtrip("a?", "a?"); + roundtrip("a??", "a??"); + roundtrip("(?U)a?", "a??"); + + roundtrip("a*", "a*"); + roundtrip("a*?", "a*?"); + roundtrip("(?U)a*", "a*?"); + + roundtrip("a+", "a+"); + roundtrip("a+?", "a+?"); + roundtrip("(?U)a+", "a+?"); + + roundtrip("a{1}", "a{1}"); + roundtrip("a{1,}", "a{1,}"); + roundtrip("a{1,5}", "a{1,5}"); + roundtrip("a{1}?", "a{1}?"); + roundtrip("a{1,}?", "a{1,}?"); + roundtrip("a{1,5}?", "a{1,5}?"); + roundtrip("(?U)a{1}", "a{1}?"); + roundtrip("(?U)a{1,}", "a{1,}?"); + roundtrip("(?U)a{1,5}", "a{1,5}?"); + } + + #[test] + fn print_group() { + roundtrip("()", "()"); + roundtrip("(?P<foo>)", "(?P<foo>)"); + roundtrip("(?:)", "(?:)"); + + roundtrip("(a)", "(a)"); + roundtrip("(?P<foo>a)", "(?P<foo>a)"); + roundtrip("(?:a)", "(?:a)"); + + roundtrip("((((a))))", "((((a))))"); + } + + #[test] + fn print_alternation() { + roundtrip("|", "|"); + roundtrip("||", "||"); + + roundtrip("a|b", "a|b"); + roundtrip("a|b|c", "a|b|c"); + roundtrip("foo|bar|quux", "foo|bar|quux"); + } +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/hir/translate.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/hir/translate.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/hir/translate.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/hir/translate.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2529 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +Defines a translator that converts an `Ast` to an `Hir`. +*/ + +use std::cell::{Cell, RefCell}; +use std::result; + +use ast::{self, Ast, Span, Visitor}; +use hir::{self, Error, ErrorKind, Hir}; +use unicode::{self, ClassQuery}; + +type Result<T> = result::Result<T, Error>; + +/// A builder for constructing an AST->HIR translator. +#[derive(Clone, Debug)] +pub struct TranslatorBuilder { + allow_invalid_utf8: bool, + flags: Flags, +} + +impl Default for TranslatorBuilder { + fn default() -> TranslatorBuilder { + TranslatorBuilder::new() + } +} + +impl TranslatorBuilder { + /// Create a new translator builder with a default c onfiguration. + pub fn new() -> TranslatorBuilder { + TranslatorBuilder { + allow_invalid_utf8: false, + flags: Flags::default(), + } + } + + /// Build a translator using the current configuration. + pub fn build(&self) -> Translator { + Translator { + stack: RefCell::new(vec![]), + flags: Cell::new(self.flags), + allow_invalid_utf8: self.allow_invalid_utf8, + } + } + + /// When enabled, translation will permit the construction of a regular + /// expression that may match invalid UTF-8. + /// + /// When disabled (the default), the translator is guaranteed to produce + /// an expression that will only ever match valid UTF-8 (otherwise, the + /// translator will return an error). + /// + /// Note that currently, even when invalid UTF-8 is banned, the translator + /// will permit a negated ASCII word boundary (i.e., `(?-u:\B)`) even + /// though it can actually match at invalid UTF-8 boundaries. This bug + /// will be fixed on the next semver release. + pub fn allow_invalid_utf8( + &mut self, + yes: bool, + ) -> &mut TranslatorBuilder { + self.allow_invalid_utf8 = yes; + self + } + + /// Enable or disable the case insensitive flag (`i`) by default. + pub fn case_insensitive(&mut self, yes: bool) -> &mut TranslatorBuilder { + self.flags.case_insensitive = if yes { Some(true) } else { None }; + self + } + + /// Enable or disable the multi-line matching flag (`m`) by default. + pub fn multi_line(&mut self, yes: bool) -> &mut TranslatorBuilder { + self.flags.multi_line = if yes { Some(true) } else { None }; + self + } + + /// Enable or disable the "dot matches any character" flag (`s`) by + /// default. + pub fn dot_matches_new_line( + &mut self, + yes: bool, + ) -> &mut TranslatorBuilder { + self.flags.dot_matches_new_line = if yes { Some(true) } else { None }; + self + } + + /// Enable or disable the "swap greed" flag (`U`) by default. + pub fn swap_greed(&mut self, yes: bool) -> &mut TranslatorBuilder { + self.flags.swap_greed = if yes { Some(true) } else { None }; + self + } + + /// Enable or disable the Unicode flag (`u`) by default. + pub fn unicode(&mut self, yes: bool) -> &mut TranslatorBuilder { + self.flags.unicode = if yes { None } else { Some(false) }; + self + } +} + +/// A translator maps abstract syntax to a high level intermediate +/// representation. +/// +/// A translator may be benefit from reuse. That is, a translator can translate +/// many abstract syntax trees. +/// +/// A `Translator` can be configured in more detail via a +/// [`TranslatorBuilder`](struct.TranslatorBuilder.html). +#[derive(Clone, Debug)] +pub struct Translator { + /// Our call stack, but on the heap. + stack: RefCell<Vec<HirFrame>>, + /// The current flag settings. + flags: Cell<Flags>, + /// Whether we're allowed to produce HIR that can match arbitrary bytes. + allow_invalid_utf8: bool, +} + +impl Translator { + /// Create a new translator using the default configuration. + pub fn new() -> Translator { + TranslatorBuilder::new().build() + } + + /// Translate the given abstract syntax tree (AST) into a high level + /// intermediate representation (HIR). + /// + /// If there was a problem doing the translation, then an HIR-specific + /// error is returned. + /// + /// The original pattern string used to produce the `Ast` *must* also be + /// provided. The translator does not use the pattern string during any + /// correct translation, but is used for error reporting. + pub fn translate(&mut self, pattern: &str, ast: &Ast) -> Result<Hir> { + ast::visit(ast, TranslatorI::new(self, pattern)) + } +} + +/// An HirFrame is a single stack frame, represented explicitly, which is +/// created for each item in the Ast that we traverse. +/// +/// Note that technically, this type doesn't represent our entire stack +/// frame. In particular, the Ast visitor represents any state associated with +/// traversing the Ast itself. +#[derive(Clone, Debug)] +enum HirFrame { + /// An arbitrary HIR expression. These get pushed whenever we hit a base + /// case in the Ast. They get popped after an inductive (i.e., recursive) + /// step is complete. + Expr(Hir), + /// A Unicode character class. This frame is mutated as we descend into + /// the Ast of a character class (which is itself its own mini recursive + /// structure). + ClassUnicode(hir::ClassUnicode), + /// A byte-oriented character class. This frame is mutated as we descend + /// into the Ast of a character class (which is itself its own mini + /// recursive structure). + /// + /// Byte character classes are created when Unicode mode (`u`) is disabled. + /// If `allow_invalid_utf8` is disabled (the default), then a byte + /// character is only permitted to match ASCII text. + ClassBytes(hir::ClassBytes), + /// This is pushed on to the stack upon first seeing any kind of group, + /// indicated by parentheses (including non-capturing groups). It is popped + /// upon leaving a group. + Group { + /// The old active flags, if any, when this group was opened. + /// + /// If this group sets flags, then the new active flags are set to the + /// result of merging the old flags with the flags introduced by this + /// group. + /// + /// When this group is popped, the active flags should be restored to + /// the flags set here. + /// + /// The "active" flags correspond to whatever flags are set in the + /// Translator. + old_flags: Option<Flags>, + }, + /// This is pushed whenever a concatenation is observed. After visiting + /// every sub-expression in the concatenation, the translator's stack is + /// popped until it sees a Concat frame. + Concat, + /// This is pushed whenever an alternation is observed. After visiting + /// every sub-expression in the alternation, the translator's stack is + /// popped until it sees an Alternation frame. + Alternation, +} + +impl HirFrame { + /// Assert that the current stack frame is an Hir expression and return it. + fn unwrap_expr(self) -> Hir { + match self { + HirFrame::Expr(expr) => expr, + _ => panic!("tried to unwrap expr from HirFrame, got: {:?}", self) + } + } + + /// Assert that the current stack frame is a Unicode class expression and + /// return it. + fn unwrap_class_unicode(self) -> hir::ClassUnicode { + match self { + HirFrame::ClassUnicode(cls) => cls, + _ => panic!("tried to unwrap Unicode class \ + from HirFrame, got: {:?}", self) + } + } + + /// Assert that the current stack frame is a byte class expression and + /// return it. + fn unwrap_class_bytes(self) -> hir::ClassBytes { + match self { + HirFrame::ClassBytes(cls) => cls, + _ => panic!("tried to unwrap byte class \ + from HirFrame, got: {:?}", self) + } + } + + /// Assert that the current stack frame is a group indicator and return + /// its corresponding flags (the flags that were active at the time the + /// group was entered) if they exist. + fn unwrap_group(self) -> Option<Flags> { + match self { + HirFrame::Group { old_flags } => old_flags, + _ => panic!("tried to unwrap group from HirFrame, got: {:?}", self) + } + } +} + +impl<'t, 'p> Visitor for TranslatorI<'t, 'p> { + type Output = Hir; + type Err = Error; + + fn finish(self) -> Result<Hir> { + if self.trans().stack.borrow().is_empty() { + // This can happen if the Ast given consists of a single set of + // flags. e.g., `(?i)`. /shrug + return Ok(Hir::empty()); + } + // ... otherwise, we should have exactly one HIR on the stack. + assert_eq!(self.trans().stack.borrow().len(), 1); + Ok(self.pop().unwrap().unwrap_expr()) + } + + fn visit_pre(&mut self, ast: &Ast) -> Result<()> { + match *ast { + Ast::Class(ast::Class::Bracketed(_)) => { + if self.flags().unicode() { + let cls = hir::ClassUnicode::empty(); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let cls = hir::ClassBytes::empty(); + self.push(HirFrame::ClassBytes(cls)); + } + } + Ast::Group(ref x) => { + let old_flags = x.flags().map(|ast| self.set_flags(ast)); + self.push(HirFrame::Group { + old_flags: old_flags, + }); + } + Ast::Concat(ref x) if x.asts.is_empty() => {} + Ast::Concat(_) => { + self.push(HirFrame::Concat); + } + Ast::Alternation(ref x) if x.asts.is_empty() => {} + Ast::Alternation(_) => { + self.push(HirFrame::Alternation); + } + _ => {} + } + Ok(()) + } + + fn visit_post(&mut self, ast: &Ast) -> Result<()> { + match *ast { + Ast::Empty(_) => { + self.push(HirFrame::Expr(Hir::empty())); + } + Ast::Flags(ref x) => { + self.set_flags(&x.flags); + } + Ast::Literal(ref x) => { + self.push(HirFrame::Expr(try!(self.hir_literal(x)))); + } + Ast::Dot(span) => { + self.push(HirFrame::Expr(try!(self.hir_dot(span)))); + } + Ast::Assertion(ref x) => { + self.push(HirFrame::Expr(try!(self.hir_assertion(x)))); + } + Ast::Class(ast::Class::Perl(ref x)) => { + if self.flags().unicode() { + let cls = self.hir_perl_unicode_class(x); + let hcls = hir::Class::Unicode(cls); + self.push(HirFrame::Expr(Hir::class(hcls))); + } else { + let cls = self.hir_perl_byte_class(x); + let hcls = hir::Class::Bytes(cls); + self.push(HirFrame::Expr(Hir::class(hcls))); + } + } + Ast::Class(ast::Class::Unicode(ref x)) => { + let cls = hir::Class::Unicode(try!(self.hir_unicode_class(x))); + self.push(HirFrame::Expr(Hir::class(cls))); + } + Ast::Class(ast::Class::Bracketed(ref ast)) => { + if self.flags().unicode() { + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + self.unicode_fold_and_negate(ast.negated, &mut cls); + if cls.iter().next().is_none() { + return Err(self.error( + ast.span, ErrorKind::EmptyClassNotAllowed)); + } + let expr = Hir::class(hir::Class::Unicode(cls)); + self.push(HirFrame::Expr(expr)); + } else { + let mut cls = self.pop().unwrap().unwrap_class_bytes(); + try!(self.bytes_fold_and_negate( + &ast.span, ast.negated, &mut cls)); + if cls.iter().next().is_none() { + return Err(self.error( + ast.span, ErrorKind::EmptyClassNotAllowed)); + } + + let expr = Hir::class(hir::Class::Bytes(cls)); + self.push(HirFrame::Expr(expr)); + } + } + Ast::Repetition(ref x) => { + let expr = self.pop().unwrap().unwrap_expr(); + self.push(HirFrame::Expr(self.hir_repetition(x, expr))); + } + Ast::Group(ref x) => { + let expr = self.pop().unwrap().unwrap_expr(); + if let Some(flags) = self.pop().unwrap().unwrap_group() { + self.trans().flags.set(flags); + } + self.push(HirFrame::Expr(self.hir_group(x, expr))); + } + Ast::Concat(_) => { + let mut exprs = vec![]; + while let Some(HirFrame::Expr(expr)) = self.pop() { + exprs.push(expr); + } + exprs.reverse(); + self.push(HirFrame::Expr(Hir::concat(exprs))); + } + Ast::Alternation(_) => { + let mut exprs = vec![]; + while let Some(HirFrame::Expr(expr)) = self.pop() { + exprs.push(expr); + } + exprs.reverse(); + self.push(HirFrame::Expr(Hir::alternation(exprs))); + } + } + Ok(()) + } + + fn visit_class_set_item_pre( + &mut self, + ast: &ast::ClassSetItem, + ) -> Result<()> { + match *ast { + ast::ClassSetItem::Bracketed(_) => { + if self.flags().unicode() { + let cls = hir::ClassUnicode::empty(); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let cls = hir::ClassBytes::empty(); + self.push(HirFrame::ClassBytes(cls)); + } + } + // We needn't handle the Union case here since the visitor will + // do it for us. + _ => {} + } + Ok(()) + } + + fn visit_class_set_item_post( + &mut self, + ast: &ast::ClassSetItem, + ) -> Result<()> { + match *ast { + ast::ClassSetItem::Empty(_) => {} + ast::ClassSetItem::Literal(ref x) => { + if self.flags().unicode() { + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + cls.push(hir::ClassUnicodeRange::new(x.c, x.c)); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let mut cls = self.pop().unwrap().unwrap_class_bytes(); + let byte = try!(self.class_literal_byte(x)); + cls.push(hir::ClassBytesRange::new(byte, byte)); + self.push(HirFrame::ClassBytes(cls)); + } + } + ast::ClassSetItem::Range(ref x) => { + if self.flags().unicode() { + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + cls.push(hir::ClassUnicodeRange::new(x.start.c, x.end.c)); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let mut cls = self.pop().unwrap().unwrap_class_bytes(); + let start = try!(self.class_literal_byte(&x.start)); + let end = try!(self.class_literal_byte(&x.end)); + cls.push(hir::ClassBytesRange::new(start, end)); + self.push(HirFrame::ClassBytes(cls)); + } + } + ast::ClassSetItem::Ascii(ref x) => { + if self.flags().unicode() { + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + for &(s, e) in ascii_class(&x.kind) { + cls.push(hir::ClassUnicodeRange::new(s, e)); + } + self.unicode_fold_and_negate(x.negated, &mut cls); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let mut cls = self.pop().unwrap().unwrap_class_bytes(); + for &(s, e) in ascii_class(&x.kind) { + cls.push(hir::ClassBytesRange::new(s as u8, e as u8)); + } + try!(self.bytes_fold_and_negate( + &x.span, x.negated, &mut cls)); + self.push(HirFrame::ClassBytes(cls)); + } + } + ast::ClassSetItem::Unicode(ref x) => { + let xcls = try!(self.hir_unicode_class(x)); + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + cls.union(&xcls); + self.push(HirFrame::ClassUnicode(cls)); + } + ast::ClassSetItem::Perl(ref x) => { + if self.flags().unicode() { + let xcls = self.hir_perl_unicode_class(x); + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + cls.union(&xcls); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let xcls = self.hir_perl_byte_class(x); + let mut cls = self.pop().unwrap().unwrap_class_bytes(); + cls.union(&xcls); + self.push(HirFrame::ClassBytes(cls)); + } + } + ast::ClassSetItem::Bracketed(ref ast) => { + if self.flags().unicode() { + let mut cls1 = self.pop().unwrap().unwrap_class_unicode(); + self.unicode_fold_and_negate(ast.negated, &mut cls1); + + let mut cls2 = self.pop().unwrap().unwrap_class_unicode(); + cls2.union(&cls1); + self.push(HirFrame::ClassUnicode(cls2)); + } else { + let mut cls1 = self.pop().unwrap().unwrap_class_bytes(); + try!(self.bytes_fold_and_negate( + &ast.span, ast.negated, &mut cls1)); + + let mut cls2 = self.pop().unwrap().unwrap_class_bytes(); + cls2.union(&cls1); + self.push(HirFrame::ClassBytes(cls2)); + } + } + // This is handled automatically by the visitor. + ast::ClassSetItem::Union(_) => {} + } + Ok(()) + } + + fn visit_class_set_binary_op_pre( + &mut self, + _op: &ast::ClassSetBinaryOp, + ) -> Result<()> { + if self.flags().unicode() { + let cls = hir::ClassUnicode::empty(); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let cls = hir::ClassBytes::empty(); + self.push(HirFrame::ClassBytes(cls)); + } + Ok(()) + } + + fn visit_class_set_binary_op_in( + &mut self, + _op: &ast::ClassSetBinaryOp, + ) -> Result<()> { + if self.flags().unicode() { + let cls = hir::ClassUnicode::empty(); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let cls = hir::ClassBytes::empty(); + self.push(HirFrame::ClassBytes(cls)); + } + Ok(()) + } + + fn visit_class_set_binary_op_post( + &mut self, + op: &ast::ClassSetBinaryOp, + ) -> Result<()> { + use ast::ClassSetBinaryOpKind::*; + + if self.flags().unicode() { + let mut rhs = self.pop().unwrap().unwrap_class_unicode(); + let mut lhs = self.pop().unwrap().unwrap_class_unicode(); + let mut cls = self.pop().unwrap().unwrap_class_unicode(); + if self.flags().case_insensitive() { + rhs.case_fold_simple(); + lhs.case_fold_simple(); + } + match op.kind { + Intersection => lhs.intersect(&rhs), + Difference => lhs.difference(&rhs), + SymmetricDifference => lhs.symmetric_difference(&rhs), + } + cls.union(&lhs); + self.push(HirFrame::ClassUnicode(cls)); + } else { + let mut rhs = self.pop().unwrap().unwrap_class_bytes(); + let mut lhs = self.pop().unwrap().unwrap_class_bytes(); + let mut cls = self.pop().unwrap().unwrap_class_bytes(); + if self.flags().case_insensitive() { + rhs.case_fold_simple(); + lhs.case_fold_simple(); + } + match op.kind { + Intersection => lhs.intersect(&rhs), + Difference => lhs.difference(&rhs), + SymmetricDifference => lhs.symmetric_difference(&rhs), + } + cls.union(&lhs); + self.push(HirFrame::ClassBytes(cls)); + } + Ok(()) + } +} + +/// The internal implementation of a translator. +/// +/// This type is responsible for carrying around the original pattern string, +/// which is not tied to the internal state of a translator. +/// +/// A TranslatorI exists for the time it takes to translate a single Ast. +#[derive(Clone, Debug)] +struct TranslatorI<'t, 'p> { + trans: &'t Translator, + pattern: &'p str, +} + +impl<'t, 'p> TranslatorI<'t, 'p> { + /// Build a new internal translator. + fn new(trans: &'t Translator, pattern: &'p str) -> TranslatorI<'t, 'p> { + TranslatorI { trans: trans, pattern: pattern } + } + + /// Return a reference to the underlying translator. + fn trans(&self) -> &Translator { + &self.trans + } + + /// Push the given frame on to the call stack. + fn push(&self, frame: HirFrame) { + self.trans().stack.borrow_mut().push(frame); + } + + /// Pop the top of the call stack. If the call stack is empty, return None. + fn pop(&self) -> Option<HirFrame> { + self.trans().stack.borrow_mut().pop() + } + + /// Create a new error with the given span and error type. + fn error(&self, span: Span, kind: ErrorKind) -> Error { + Error { kind: kind, pattern: self.pattern.to_string(), span: span } + } + + /// Return a copy of the active flags. + fn flags(&self) -> Flags { + self.trans().flags.get() + } + + /// Set the flags of this translator from the flags set in the given AST. + /// Then, return the old flags. + fn set_flags(&self, ast_flags: &ast::Flags) -> Flags { + let old_flags = self.flags(); + let mut new_flags = Flags::from_ast(ast_flags); + new_flags.merge(&old_flags); + self.trans().flags.set(new_flags); + old_flags + } + + fn hir_literal(&self, lit: &ast::Literal) -> Result<Hir> { + let ch = match try!(self.literal_to_char(lit)) { + byte @ hir::Literal::Byte(_) => return Ok(Hir::literal(byte)), + hir::Literal::Unicode(ch) => ch, + }; + if self.flags().case_insensitive() { + self.hir_from_char_case_insensitive(lit.span, ch) + } else { + self.hir_from_char(lit.span, ch) + } + } + + /// Convert an Ast literal to its scalar representation. + /// + /// When Unicode mode is enabled, then this always succeeds and returns a + /// `char` (Unicode scalar value). + /// + /// When Unicode mode is disabled, then a raw byte is returned. If that + /// byte is not ASCII and invalid UTF-8 is not allowed, then this returns + /// an error. + fn literal_to_char(&self, lit: &ast::Literal) -> Result<hir::Literal> { + if self.flags().unicode() { + return Ok(hir::Literal::Unicode(lit.c)); + } + let byte = match lit.byte() { + None => return Ok(hir::Literal::Unicode(lit.c)), + Some(byte) => byte, + }; + if byte <= 0x7F { + return Ok(hir::Literal::Unicode(byte as char)); + } + if !self.trans().allow_invalid_utf8 { + return Err(self.error(lit.span, ErrorKind::InvalidUtf8)); + } + Ok(hir::Literal::Byte(byte)) + } + + fn hir_from_char(&self, span: Span, c: char) -> Result<Hir> { + if !self.flags().unicode() && c.len_utf8() > 1 { + return Err(self.error(span, ErrorKind::UnicodeNotAllowed)); + } + Ok(Hir::literal(hir::Literal::Unicode(c))) + } + + fn hir_from_char_case_insensitive( + &self, + span: Span, + c: char, + ) -> Result<Hir> { + // If case folding won't do anything, then don't bother trying. + if !unicode::contains_simple_case_mapping(c, c) { + return self.hir_from_char(span, c); + } + if self.flags().unicode() { + let mut cls = hir::ClassUnicode::new(vec![ + hir::ClassUnicodeRange::new(c, c), + ]); + cls.case_fold_simple(); + Ok(Hir::class(hir::Class::Unicode(cls))) + } else { + if c.len_utf8() > 1 { + return Err(self.error(span, ErrorKind::UnicodeNotAllowed)); + } + let mut cls = hir::ClassBytes::new(vec![ + hir::ClassBytesRange::new(c as u8, c as u8), + ]); + cls.case_fold_simple(); + Ok(Hir::class(hir::Class::Bytes(cls))) + } + } + + fn hir_dot(&self, span: Span) -> Result<Hir> { + let unicode = self.flags().unicode(); + if !unicode && !self.trans().allow_invalid_utf8 { + return Err(self.error(span, ErrorKind::InvalidUtf8)); + } + Ok(if self.flags().dot_matches_new_line() { + Hir::any(!unicode) + } else { + Hir::dot(!unicode) + }) + } + + fn hir_assertion(&self, asst: &ast::Assertion) -> Result<Hir> { + let unicode = self.flags().unicode(); + let multi_line = self.flags().multi_line(); + Ok(match asst.kind { + ast::AssertionKind::StartLine => { + Hir::anchor(if multi_line { + hir::Anchor::StartLine + } else { + hir::Anchor::StartText + }) + } + ast::AssertionKind::EndLine => { + Hir::anchor(if multi_line { + hir::Anchor::EndLine + } else { + hir::Anchor::EndText + }) + } + ast::AssertionKind::StartText => { + Hir::anchor(hir::Anchor::StartText) + } + ast::AssertionKind::EndText => { + Hir::anchor(hir::Anchor::EndText) + } + ast::AssertionKind::WordBoundary => { + Hir::word_boundary(if unicode { + hir::WordBoundary::Unicode + } else { + hir::WordBoundary::Ascii + }) + } + ast::AssertionKind::NotWordBoundary => { + Hir::word_boundary(if unicode { + hir::WordBoundary::UnicodeNegate + } else { + // It is possible for negated ASCII word boundaries to + // match at invalid UTF-8 boundaries, even when searching + // valid UTF-8. + // + // TODO(ag): Enable this error when regex goes to 1.0. + // Otherwise, it is too steep of a breaking change. + // if !self.trans().allow_invalid_utf8 { + // return Err(self.error( + // asst.span, ErrorKind::InvalidUtf8)); + // } + hir::WordBoundary::AsciiNegate + }) + } + }) + } + + fn hir_group(&self, group: &ast::Group, expr: Hir) -> Hir { + let kind = match group.kind { + ast::GroupKind::CaptureIndex(idx) => { + hir::GroupKind::CaptureIndex(idx) + } + ast::GroupKind::CaptureName(ref capname) => { + hir::GroupKind::CaptureName { + name: capname.name.clone(), + index: capname.index, + } + } + ast::GroupKind::NonCapturing(_) => hir::GroupKind::NonCapturing, + }; + Hir::group(hir::Group { + kind: kind, + hir: Box::new(expr), + }) + } + + fn hir_repetition(&self, rep: &ast::Repetition, expr: Hir) -> Hir { + let kind = match rep.op.kind { + ast::RepetitionKind::ZeroOrOne => hir::RepetitionKind::ZeroOrOne, + ast::RepetitionKind::ZeroOrMore => hir::RepetitionKind::ZeroOrMore, + ast::RepetitionKind::OneOrMore => hir::RepetitionKind::OneOrMore, + ast::RepetitionKind::Range(ast::RepetitionRange::Exactly(m)) => { + hir::RepetitionKind::Range(hir::RepetitionRange::Exactly(m)) + } + ast::RepetitionKind::Range(ast::RepetitionRange::AtLeast(m)) => { + hir::RepetitionKind::Range(hir::RepetitionRange::AtLeast(m)) + } + ast::RepetitionKind::Range(ast::RepetitionRange::Bounded(m,n)) => { + hir::RepetitionKind::Range(hir::RepetitionRange::Bounded(m, n)) + } + }; + let greedy = + if self.flags().swap_greed() { + !rep.greedy + } else { + rep.greedy + }; + Hir::repetition(hir::Repetition { + kind: kind, + greedy: greedy, + hir: Box::new(expr), + }) + } + + fn hir_unicode_class( + &self, + ast_class: &ast::ClassUnicode, + ) -> Result<hir::ClassUnicode> { + use ast::ClassUnicodeKind::*; + + if !self.flags().unicode() { + return Err(self.error( + ast_class.span, + ErrorKind::UnicodeNotAllowed, + )); + } + let query = match ast_class.kind { + OneLetter(name) => ClassQuery::OneLetter(name), + Named(ref name) => ClassQuery::Binary(name), + NamedValue { ref name, ref value, .. } => { + ClassQuery::ByValue { + property_name: name, + property_value: value, + } + } + }; + match unicode::class(query) { + Ok(mut class) => { + self.unicode_fold_and_negate(ast_class.negated, &mut class); + Ok(class) + } + Err(unicode::Error::PropertyNotFound) => { + Err(self.error( + ast_class.span, + ErrorKind::UnicodePropertyNotFound, + )) + } + Err(unicode::Error::PropertyValueNotFound) => { + Err(self.error( + ast_class.span, + ErrorKind::UnicodePropertyValueNotFound, + )) + } + } + } + + fn hir_perl_unicode_class( + &self, + ast_class: &ast::ClassPerl, + ) -> hir::ClassUnicode { + use ast::ClassPerlKind::*; + use unicode_tables::perl_word::PERL_WORD; + + assert!(self.flags().unicode()); + let mut class = match ast_class.kind { + Digit => { + let query = ClassQuery::Binary("Decimal_Number"); + unicode::class(query).unwrap() + } + Space => { + let query = ClassQuery::Binary("Whitespace"); + unicode::class(query).unwrap() + } + Word => unicode::hir_class(PERL_WORD), + }; + // We needn't apply case folding here because the Perl Unicode classes + // are already closed under Unicode simple case folding. + if ast_class.negated { + class.negate(); + } + class + } + + fn hir_perl_byte_class( + &self, + ast_class: &ast::ClassPerl, + ) -> hir::ClassBytes { + use ast::ClassPerlKind::*; + + assert!(!self.flags().unicode()); + let mut class = match ast_class.kind { + Digit => hir_ascii_class_bytes(&ast::ClassAsciiKind::Digit), + Space => hir_ascii_class_bytes(&ast::ClassAsciiKind::Space), + Word => hir_ascii_class_bytes(&ast::ClassAsciiKind::Word), + }; + // We needn't apply case folding here because the Perl ASCII classes + // are already closed (under ASCII case folding). + if ast_class.negated { + class.negate(); + } + class + } + + fn unicode_fold_and_negate( + &self, + negated: bool, + class: &mut hir::ClassUnicode, + ) { + // Note that we must apply case folding before negation! + // Consider `(?i)[^x]`. If we applied negation field, then + // the result would be the character class that matched any + // Unicode scalar value. + if self.flags().case_insensitive() { + class.case_fold_simple(); + } + if negated { + class.negate(); + } + } + + fn bytes_fold_and_negate( + &self, + span: &Span, + negated: bool, + class: &mut hir::ClassBytes, + ) -> Result<()> { + // Note that we must apply case folding before negation! + // Consider `(?i)[^x]`. If we applied negation field, then + // the result would be the character class that matched any + // Unicode scalar value. + if self.flags().case_insensitive() { + class.case_fold_simple(); + } + if negated { + class.negate(); + } + if !self.trans().allow_invalid_utf8 && !class.is_all_ascii() { + return Err(self.error(span.clone(), ErrorKind::InvalidUtf8)); + } + Ok(()) + } + + /// Return a scalar byte value suitable for use as a literal in a byte + /// character class. + fn class_literal_byte(&self, ast: &ast::Literal) -> Result<u8> { + match try!(self.literal_to_char(ast)) { + hir::Literal::Byte(byte) => Ok(byte), + hir::Literal::Unicode(ch) => { + if ch <= 0x7F as char { + Ok(ch as u8) + } else { + // We can't feasibly support Unicode in + // byte oriented classes. Byte classes don't + // do Unicode case folding. + Err(self.error(ast.span, ErrorKind::UnicodeNotAllowed)) + } + } + } + } +} + +/// A translator's representation of a regular expression's flags at any given +/// moment in time. +/// +/// Each flag can be in one of three states: absent, present but disabled or +/// present but enabled. +#[derive(Clone, Copy, Debug, Default)] +struct Flags { + case_insensitive: Option<bool>, + multi_line: Option<bool>, + dot_matches_new_line: Option<bool>, + swap_greed: Option<bool>, + unicode: Option<bool>, + // Note that `ignore_whitespace` is omitted here because it is handled + // entirely in the parser. +} + +impl Flags { + fn from_ast(ast: &ast::Flags) -> Flags { + let mut flags = Flags::default(); + let mut enable = true; + for item in &ast.items { + match item.kind { + ast::FlagsItemKind::Negation => { + enable = false; + } + ast::FlagsItemKind::Flag(ast::Flag::CaseInsensitive) => { + flags.case_insensitive = Some(enable); + } + ast::FlagsItemKind::Flag(ast::Flag::MultiLine) => { + flags.multi_line = Some(enable); + } + ast::FlagsItemKind::Flag(ast::Flag::DotMatchesNewLine) => { + flags.dot_matches_new_line = Some(enable); + } + ast::FlagsItemKind::Flag(ast::Flag::SwapGreed) => { + flags.swap_greed = Some(enable); + } + ast::FlagsItemKind::Flag(ast::Flag::Unicode) => { + flags.unicode = Some(enable); + } + ast::FlagsItemKind::Flag(ast::Flag::IgnoreWhitespace) => {} + } + } + flags + } + + fn merge(&mut self, previous: &Flags) { + if self.case_insensitive.is_none() { + self.case_insensitive = previous.case_insensitive; + } + if self.multi_line.is_none() { + self.multi_line = previous.multi_line; + } + if self.dot_matches_new_line.is_none() { + self.dot_matches_new_line = previous.dot_matches_new_line; + } + if self.swap_greed.is_none() { + self.swap_greed = previous.swap_greed; + } + if self.unicode.is_none() { + self.unicode = previous.unicode; + } + } + + fn case_insensitive(&self) -> bool { + self.case_insensitive.unwrap_or(false) + } + + fn multi_line(&self) -> bool { + self.multi_line.unwrap_or(false) + } + + fn dot_matches_new_line(&self) -> bool { + self.dot_matches_new_line.unwrap_or(false) + } + + fn swap_greed(&self) -> bool { + self.swap_greed.unwrap_or(false) + } + + fn unicode(&self) -> bool { + self.unicode.unwrap_or(true) + } +} + +fn hir_ascii_class_bytes(kind: &ast::ClassAsciiKind) -> hir::ClassBytes { + let ranges: Vec<_> = ascii_class(kind).iter().cloned().map(|(s, e)| { + hir::ClassBytesRange::new(s as u8, e as u8) + }).collect(); + hir::ClassBytes::new(ranges) +} + +fn ascii_class(kind: &ast::ClassAsciiKind) -> &'static [(char, char)] { + use ast::ClassAsciiKind::*; + + // TODO: Get rid of these consts, which appear necessary for older + // versions of Rust. + type T = &'static [(char, char)]; + match *kind { + Alnum => { + const X: T = &[('0', '9'), ('A', 'Z'), ('a', 'z')]; + X + } + Alpha => { + const X: T = &[('A', 'Z'), ('a', 'z')]; + X + } + Ascii => { + const X: T = &[('\x00', '\x7F')]; + X + } + Blank => { + const X: T = &[(' ', '\t')]; + X + } + Cntrl => { + const X: T = &[('\x00', '\x1F'), ('\x7F', '\x7F')]; + X + } + Digit => { + const X: T = &[('0', '9')]; + X + } + Graph => { + const X: T = &[('!', '~')]; + X + } + Lower => { + const X: T = &[('a', 'z')]; + X + } + Print => { + const X: T = &[(' ', '~')]; + X + } + Punct => { + const X: T = &[('!', '/'), (':', '@'), ('[', '`'), ('{', '~')]; + X + } + Space => { + const X: T = &[ + ('\t', '\t'), ('\n', '\n'), ('\x0B', '\x0B'), ('\x0C', '\x0C'), + ('\r', '\r'), (' ', ' '), + ]; + X + } + Upper => { + const X: T = &[('A', 'Z')]; + X + } + Word => { + const X: T = &[('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z')]; + X + } + Xdigit => { + const X: T = &[('0', '9'), ('A', 'F'), ('a', 'f')]; + X + } + } +} + +#[cfg(test)] +mod tests { + use ast::{self, Ast, Position, Span}; + use ast::parse::ParserBuilder; + use hir::{self, Hir, HirKind}; + use unicode::{self, ClassQuery}; + + use super::{TranslatorBuilder, ascii_class}; + + // We create these errors to compare with real hir::Errors in the tests. + // We define equality between TestError and hir::Error to disregard the + // pattern string in hir::Error, which is annoying to provide in tests. + #[derive(Clone, Debug)] + struct TestError { + span: Span, + kind: hir::ErrorKind, + } + + impl PartialEq<hir::Error> for TestError { + fn eq(&self, other: &hir::Error) -> bool { + self.span == other.span && self.kind == other.kind + } + } + + impl PartialEq<TestError> for hir::Error { + fn eq(&self, other: &TestError) -> bool { + self.span == other.span && self.kind == other.kind + } + } + + fn parse(pattern: &str) -> Ast { + ParserBuilder::new().octal(true).build().parse(pattern).unwrap() + } + + fn t(pattern: &str) -> Hir { + TranslatorBuilder::new() + .allow_invalid_utf8(false) + .build() + .translate(pattern, &parse(pattern)) + .unwrap() + } + + fn t_err(pattern: &str) -> hir::Error { + TranslatorBuilder::new() + .allow_invalid_utf8(false) + .build() + .translate(pattern, &parse(pattern)) + .unwrap_err() + } + + fn t_bytes(pattern: &str) -> Hir { + TranslatorBuilder::new() + .allow_invalid_utf8(true) + .build() + .translate(pattern, &parse(pattern)) + .unwrap() + } + + fn hir_lit(s: &str) -> Hir { + match s.len() { + 0 => Hir::empty(), + _ => { + let lits = s + .chars() + .map(hir::Literal::Unicode) + .map(Hir::literal) + .collect(); + Hir::concat(lits) + } + } + } + + fn hir_blit(s: &[u8]) -> Hir { + match s.len() { + 0 => Hir::empty(), + 1 => Hir::literal(hir::Literal::Byte(s[0])), + _ => { + let lits = s + .iter() + .cloned() + .map(hir::Literal::Byte) + .map(Hir::literal) + .collect(); + Hir::concat(lits) + } + } + } + + fn hir_group(i: u32, expr: Hir) -> Hir { + Hir::group(hir::Group { + kind: hir::GroupKind::CaptureIndex(i), + hir: Box::new(expr), + }) + } + + fn hir_group_name(i: u32, name: &str, expr: Hir) -> Hir { + Hir::group(hir::Group { + kind: hir::GroupKind::CaptureName { + name: name.to_string(), + index: i, + }, + hir: Box::new(expr), + }) + } + + fn hir_group_nocap(expr: Hir) -> Hir { + Hir::group(hir::Group { + kind: hir::GroupKind::NonCapturing, + hir: Box::new(expr), + }) + } + + fn hir_quest(greedy: bool, expr: Hir) -> Hir { + Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::ZeroOrOne, + greedy: greedy, + hir: Box::new(expr), + }) + } + + fn hir_star(greedy: bool, expr: Hir) -> Hir { + Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::ZeroOrMore, + greedy: greedy, + hir: Box::new(expr), + }) + } + + fn hir_plus(greedy: bool, expr: Hir) -> Hir { + Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::OneOrMore, + greedy: greedy, + hir: Box::new(expr), + }) + } + + fn hir_range(greedy: bool, range: hir::RepetitionRange, expr: Hir) -> Hir { + Hir::repetition(hir::Repetition { + kind: hir::RepetitionKind::Range(range), + greedy: greedy, + hir: Box::new(expr), + }) + } + + fn hir_alt(alts: Vec<Hir>) -> Hir { + Hir::alternation(alts) + } + + fn hir_cat(exprs: Vec<Hir>) -> Hir { + Hir::concat(exprs) + } + + fn hir_uclass_query(query: ClassQuery) -> Hir { + Hir::class(hir::Class::Unicode(unicode::class(query).unwrap())) + } + + fn hir_uclass_perl_word() -> Hir { + use unicode_tables::perl_word::PERL_WORD; + Hir::class(hir::Class::Unicode(unicode::hir_class(PERL_WORD))) + } + + fn hir_uclass(ranges: &[(char, char)]) -> Hir { + let ranges: Vec<hir::ClassUnicodeRange> = ranges + .iter() + .map(|&(s, e)| hir::ClassUnicodeRange::new(s, e)) + .collect(); + Hir::class(hir::Class::Unicode(hir::ClassUnicode::new(ranges))) + } + + fn hir_bclass(ranges: &[(u8, u8)]) -> Hir { + let ranges: Vec<hir::ClassBytesRange> = ranges + .iter() + .map(|&(s, e)| hir::ClassBytesRange::new(s, e)) + .collect(); + Hir::class(hir::Class::Bytes(hir::ClassBytes::new(ranges))) + } + + fn hir_bclass_from_char(ranges: &[(char, char)]) -> Hir { + let ranges: Vec<hir::ClassBytesRange> = ranges + .iter() + .map(|&(s, e)| { + assert!(s as u32 <= 0x7F); + assert!(e as u32 <= 0x7F); + hir::ClassBytesRange::new(s as u8, e as u8) + }) + .collect(); + Hir::class(hir::Class::Bytes(hir::ClassBytes::new(ranges))) + } + + fn hir_case_fold(expr: Hir) -> Hir { + match expr.into_kind() { + HirKind::Class(mut cls) => { + cls.case_fold_simple(); + Hir::class(cls) + } + _ => panic!("cannot case fold non-class Hir expr"), + } + } + + fn hir_negate(expr: Hir) -> Hir { + match expr.into_kind() { + HirKind::Class(mut cls) => { + cls.negate(); + Hir::class(cls) + } + _ => panic!("cannot negate non-class Hir expr"), + } + } + + fn hir_union(expr1: Hir, expr2: Hir) -> Hir { + use hir::Class::{Bytes, Unicode}; + + match (expr1.into_kind(), expr2.into_kind()) { + ( + HirKind::Class(Unicode(mut c1)), + HirKind::Class(Unicode(c2)), + ) => { + c1.union(&c2); + Hir::class(hir::Class::Unicode(c1)) + } + ( + HirKind::Class(Bytes(mut c1)), + HirKind::Class(Bytes(c2)), + ) => { + c1.union(&c2); + Hir::class(hir::Class::Bytes(c1)) + } + _ => panic!("cannot union non-class Hir exprs"), + } + } + + fn hir_difference(expr1: Hir, expr2: Hir) -> Hir { + use hir::Class::{Bytes, Unicode}; + + match (expr1.into_kind(), expr2.into_kind()) { + ( + HirKind::Class(Unicode(mut c1)), + HirKind::Class(Unicode(c2)), + ) => { + c1.difference(&c2); + Hir::class(hir::Class::Unicode(c1)) + } + ( + HirKind::Class(Bytes(mut c1)), + HirKind::Class(Bytes(c2)), + ) => { + c1.difference(&c2); + Hir::class(hir::Class::Bytes(c1)) + } + _ => panic!("cannot difference non-class Hir exprs"), + } + } + + fn hir_anchor(anchor: hir::Anchor) -> Hir { + Hir::anchor(anchor) + } + + fn hir_word(wb: hir::WordBoundary) -> Hir { + Hir::word_boundary(wb) + } + + #[test] + fn empty() { + assert_eq!(t(""), Hir::empty()); + assert_eq!(t("(?i)"), Hir::empty()); + assert_eq!(t("()"), hir_group(1, Hir::empty())); + assert_eq!(t("(?:)"), hir_group_nocap(Hir::empty())); + assert_eq!(t("(?P<wat>)"), hir_group_name(1, "wat", Hir::empty())); + assert_eq!(t("|"), hir_alt(vec![Hir::empty(), Hir::empty()])); + assert_eq!(t("()|()"), hir_alt(vec![ + hir_group(1, Hir::empty()), + hir_group(2, Hir::empty()), + ])); + assert_eq!(t("(|b)"), hir_group(1, hir_alt(vec![ + Hir::empty(), + hir_lit("b"), + ]))); + assert_eq!(t("(a|)"), hir_group(1, hir_alt(vec![ + hir_lit("a"), + Hir::empty(), + ]))); + assert_eq!(t("(a||c)"), hir_group(1, hir_alt(vec![ + hir_lit("a"), + Hir::empty(), + hir_lit("c"), + ]))); + assert_eq!(t("(||)"), hir_group(1, hir_alt(vec![ + Hir::empty(), + Hir::empty(), + Hir::empty(), + ]))); + } + + #[test] + fn literal() { + assert_eq!(t("a"), hir_lit("a")); + assert_eq!(t("(?-u)a"), hir_lit("a")); + assert_eq!(t("☃"), hir_lit("☃")); + assert_eq!(t("abcd"), hir_lit("abcd")); + + assert_eq!(t_bytes("(?-u)a"), hir_lit("a")); + assert_eq!(t_bytes("(?-u)\x61"), hir_lit("a")); + assert_eq!(t_bytes(r"(?-u)\x61"), hir_lit("a")); + assert_eq!(t_bytes(r"(?-u)\xFF"), hir_blit(b"\xFF")); + + assert_eq!(t_err("(?-u)☃"), TestError { + kind: hir::ErrorKind::UnicodeNotAllowed, + span: Span::new(Position::new(5, 1, 6), Position::new(8, 1, 7)), + }); + assert_eq!(t_err(r"(?-u)\xFF"), TestError { + kind: hir::ErrorKind::InvalidUtf8, + span: Span::new(Position::new(5, 1, 6), Position::new(9, 1, 10)), + }); + } + + #[test] + fn literal_case_insensitive() { + assert_eq!(t("(?i)a"), hir_uclass(&[ + ('A', 'A'), ('a', 'a'), + ])); + assert_eq!(t("(?i:a)"), hir_group_nocap(hir_uclass(&[ + ('A', 'A'), ('a', 'a')], + ))); + assert_eq!(t("a(?i)a(?-i)a"), hir_cat(vec![ + hir_lit("a"), + hir_uclass(&[('A', 'A'), ('a', 'a')]), + hir_lit("a"), + ])); + assert_eq!(t("(?i)ab@c"), hir_cat(vec![ + hir_uclass(&[('A', 'A'), ('a', 'a')]), + hir_uclass(&[('B', 'B'), ('b', 'b')]), + hir_lit("@"), + hir_uclass(&[('C', 'C'), ('c', 'c')]), + ])); + assert_eq!(t("(?i)β"), hir_uclass(&[ + ('Β', 'Β'), ('β', 'β'), ('ϐ', 'ϐ'), + ])); + + assert_eq!(t("(?i-u)a"), hir_bclass(&[ + (b'A', b'A'), (b'a', b'a'), + ])); + assert_eq!(t("(?-u)a(?i)a(?-i)a"), hir_cat(vec![ + hir_lit("a"), + hir_bclass(&[(b'A', b'A'), (b'a', b'a')]), + hir_lit("a"), + ])); + assert_eq!(t("(?i-u)ab@c"), hir_cat(vec![ + hir_bclass(&[(b'A', b'A'), (b'a', b'a')]), + hir_bclass(&[(b'B', b'B'), (b'b', b'b')]), + hir_lit("@"), + hir_bclass(&[(b'C', b'C'), (b'c', b'c')]), + ])); + + assert_eq!(t_bytes("(?i-u)a"), hir_bclass(&[ + (b'A', b'A'), (b'a', b'a'), + ])); + assert_eq!(t_bytes("(?i-u)\x61"), hir_bclass(&[ + (b'A', b'A'), (b'a', b'a'), + ])); + assert_eq!(t_bytes(r"(?i-u)\x61"), hir_bclass(&[ + (b'A', b'A'), (b'a', b'a'), + ])); + assert_eq!(t_bytes(r"(?i-u)\xFF"), hir_blit(b"\xFF")); + + assert_eq!(t_err("(?i-u)β"), TestError { + kind: hir::ErrorKind::UnicodeNotAllowed, + span: Span::new( + Position::new(6, 1, 7), + Position::new(8, 1, 8), + ), + }); + } + + #[test] + fn dot() { + assert_eq!(t("."), hir_uclass(&[ + ('\0', '\t'), + ('\x0B', '\u{10FFFF}'), + ])); + assert_eq!(t("(?s)."), hir_uclass(&[ + ('\0', '\u{10FFFF}'), + ])); + assert_eq!(t_bytes("(?-u)."), hir_bclass(&[ + (b'\0', b'\t'), + (b'\x0B', b'\xFF'), + ])); + assert_eq!(t_bytes("(?s-u)."), hir_bclass(&[ + (b'\0', b'\xFF'), + ])); + + // If invalid UTF-8 isn't allowed, then non-Unicode `.` isn't allowed. + assert_eq!(t_err("(?-u)."), TestError { + kind: hir::ErrorKind::InvalidUtf8, + span: Span::new(Position::new(5, 1, 6), Position::new(6, 1, 7)), + }); + assert_eq!(t_err("(?s-u)."), TestError { + kind: hir::ErrorKind::InvalidUtf8, + span: Span::new(Position::new(6, 1, 7), Position::new(7, 1, 8)), + }); + } + + #[test] + fn assertions() { + assert_eq!(t("^"), hir_anchor(hir::Anchor::StartText)); + assert_eq!(t("$"), hir_anchor(hir::Anchor::EndText)); + assert_eq!(t(r"\A"), hir_anchor(hir::Anchor::StartText)); + assert_eq!(t(r"\z"), hir_anchor(hir::Anchor::EndText)); + assert_eq!(t("(?m)^"), hir_anchor(hir::Anchor::StartLine)); + assert_eq!(t("(?m)$"), hir_anchor(hir::Anchor::EndLine)); + assert_eq!(t(r"(?m)\A"), hir_anchor(hir::Anchor::StartText)); + assert_eq!(t(r"(?m)\z"), hir_anchor(hir::Anchor::EndText)); + + assert_eq!(t(r"\b"), hir_word(hir::WordBoundary::Unicode)); + assert_eq!(t(r"\B"), hir_word(hir::WordBoundary::UnicodeNegate)); + assert_eq!(t(r"(?-u)\b"), hir_word(hir::WordBoundary::Ascii)); + assert_eq!( + t_bytes(r"(?-u)\B"), + hir_word(hir::WordBoundary::AsciiNegate)); + + // TODO(ag): Enable this tests when regex goes to 1.0. + // assert_eq!(t_err(r"(?-u)\B"), TestError { + // kind: hir::ErrorKind::InvalidUtf8, + // span: Span::new(Position::new(5, 1, 6), Position::new(7, 1, 8)), + // }); + } + + #[test] + fn group() { + assert_eq!(t("(a)"), hir_group(1, hir_lit("a"))); + assert_eq!(t("(a)(b)"), hir_cat(vec![ + hir_group(1, hir_lit("a")), + hir_group(2, hir_lit("b")), + ])); + assert_eq!(t("(a)|(b)"), hir_alt(vec![ + hir_group(1, hir_lit("a")), + hir_group(2, hir_lit("b")), + ])); + assert_eq!(t("(?P<foo>)"), hir_group_name(1, "foo", Hir::empty())); + assert_eq!(t("(?P<foo>a)"), hir_group_name(1, "foo", hir_lit("a"))); + assert_eq!(t("(?P<foo>a)(?P<bar>b)"), hir_cat(vec![ + hir_group_name(1, "foo", hir_lit("a")), + hir_group_name(2, "bar", hir_lit("b")), + ])); + assert_eq!(t("(?:)"), hir_group_nocap(Hir::empty())); + assert_eq!(t("(?:a)"), hir_group_nocap(hir_lit("a"))); + assert_eq!(t("(?:a)(b)"), hir_cat(vec![ + hir_group_nocap(hir_lit("a")), + hir_group(1, hir_lit("b")), + ])); + assert_eq!(t("(a)(?:b)(c)"), hir_cat(vec![ + hir_group(1, hir_lit("a")), + hir_group_nocap(hir_lit("b")), + hir_group(2, hir_lit("c")), + ])); + assert_eq!(t("(a)(?P<foo>b)(c)"), hir_cat(vec![ + hir_group(1, hir_lit("a")), + hir_group_name(2, "foo", hir_lit("b")), + hir_group(3, hir_lit("c")), + ])); + } + + #[test] + fn flags() { + assert_eq!(t("(?i:a)a"), hir_cat(vec![ + hir_group_nocap(hir_uclass(&[('A', 'A'), ('a', 'a')])), + hir_lit("a"), + ])); + assert_eq!(t("(?i-u:a)β"), hir_cat(vec![ + hir_group_nocap(hir_bclass(&[(b'A', b'A'), (b'a', b'a')])), + hir_lit("β"), + ])); + assert_eq!(t("(?i)(?-i:a)a"), hir_cat(vec![ + hir_group_nocap(hir_lit("a")), + hir_uclass(&[('A', 'A'), ('a', 'a')]), + ])); + assert_eq!(t("(?im)a^"), hir_cat(vec![ + hir_uclass(&[('A', 'A'), ('a', 'a')]), + hir_anchor(hir::Anchor::StartLine), + ])); + assert_eq!(t("(?im)a^(?i-m)a^"), hir_cat(vec![ + hir_uclass(&[('A', 'A'), ('a', 'a')]), + hir_anchor(hir::Anchor::StartLine), + hir_uclass(&[('A', 'A'), ('a', 'a')]), + hir_anchor(hir::Anchor::StartText), + ])); + assert_eq!(t("(?U)a*a*?(?-U)a*a*?"), hir_cat(vec![ + hir_star(false, hir_lit("a")), + hir_star(true, hir_lit("a")), + hir_star(true, hir_lit("a")), + hir_star(false, hir_lit("a")), + ])); + assert_eq!(t("(?:a(?i)a)a"), hir_cat(vec![ + hir_group_nocap(hir_cat(vec![ + hir_lit("a"), + hir_uclass(&[('A', 'A'), ('a', 'a')]), + ])), + hir_lit("a"), + ])); + assert_eq!(t("(?i)(?:a(?-i)a)a"), hir_cat(vec![ + hir_group_nocap(hir_cat(vec![ + hir_uclass(&[('A', 'A'), ('a', 'a')]), + hir_lit("a"), + ])), + hir_uclass(&[('A', 'A'), ('a', 'a')]), + ])); + } + + #[test] + fn escape() { + assert_eq!( + t(r"\\\.\+\*\?\(\)\|\[\]\{\}\^\$\#"), + hir_lit(r"\.+*?()|[]{}^$#"), + ); + } + + #[test] + fn repetition() { + assert_eq!(t("a?"), hir_quest(true, hir_lit("a"))); + assert_eq!(t("a*"), hir_star(true, hir_lit("a"))); + assert_eq!(t("a+"), hir_plus(true, hir_lit("a"))); + assert_eq!(t("a??"), hir_quest(false, hir_lit("a"))); + assert_eq!(t("a*?"), hir_star(false, hir_lit("a"))); + assert_eq!(t("a+?"), hir_plus(false, hir_lit("a"))); + + assert_eq!( + t("a{1}"), + hir_range( + true, + hir::RepetitionRange::Exactly(1), + hir_lit("a"), + )); + assert_eq!( + t("a{1,}"), + hir_range( + true, + hir::RepetitionRange::AtLeast(1), + hir_lit("a"), + )); + assert_eq!( + t("a{1,2}"), + hir_range( + true, + hir::RepetitionRange::Bounded(1, 2), + hir_lit("a"), + )); + assert_eq!( + t("a{1}?"), + hir_range( + false, + hir::RepetitionRange::Exactly(1), + hir_lit("a"), + )); + assert_eq!( + t("a{1,}?"), + hir_range( + false, + hir::RepetitionRange::AtLeast(1), + hir_lit("a"), + )); + assert_eq!( + t("a{1,2}?"), + hir_range( + false, + hir::RepetitionRange::Bounded(1, 2), + hir_lit("a"), + )); + + assert_eq!(t("ab?"), hir_cat(vec![ + hir_lit("a"), + hir_quest(true, hir_lit("b")), + ])); + assert_eq!(t("(ab)?"), hir_quest(true, hir_group(1, hir_cat(vec![ + hir_lit("a"), + hir_lit("b"), + ])))); + assert_eq!(t("a|b?"), hir_alt(vec![ + hir_lit("a"), + hir_quest(true, hir_lit("b")), + ])); + } + + #[test] + fn cat_alt() { + assert_eq!(t("(ab)"), hir_group(1, hir_cat(vec![ + hir_lit("a"), + hir_lit("b"), + ]))); + assert_eq!(t("a|b"), hir_alt(vec![ + hir_lit("a"), + hir_lit("b"), + ])); + assert_eq!(t("a|b|c"), hir_alt(vec![ + hir_lit("a"), + hir_lit("b"), + hir_lit("c"), + ])); + assert_eq!(t("ab|bc|cd"), hir_alt(vec![ + hir_lit("ab"), + hir_lit("bc"), + hir_lit("cd"), + ])); + assert_eq!(t("(a|b)"), hir_group(1, hir_alt(vec![ + hir_lit("a"), + hir_lit("b"), + ]))); + assert_eq!(t("(a|b|c)"), hir_group(1, hir_alt(vec![ + hir_lit("a"), + hir_lit("b"), + hir_lit("c"), + ]))); + assert_eq!(t("(ab|bc|cd)"), hir_group(1, hir_alt(vec![ + hir_lit("ab"), + hir_lit("bc"), + hir_lit("cd"), + ]))); + assert_eq!(t("(ab|(bc|(cd)))"), hir_group(1, hir_alt(vec![ + hir_lit("ab"), + hir_group(2, hir_alt(vec![ + hir_lit("bc"), + hir_group(3, hir_lit("cd")), + ])), + ]))); + } + + #[test] + fn class_ascii() { + assert_eq!( + t("[[:alnum:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Alnum))); + assert_eq!( + t("[[:alpha:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Alpha))); + assert_eq!( + t("[[:ascii:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Ascii))); + assert_eq!( + t("[[:blank:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Blank))); + assert_eq!( + t("[[:cntrl:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Cntrl))); + assert_eq!( + t("[[:digit:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Digit))); + assert_eq!( + t("[[:graph:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Graph))); + assert_eq!( + t("[[:lower:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Lower))); + assert_eq!( + t("[[:print:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Print))); + assert_eq!( + t("[[:punct:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Punct))); + assert_eq!( + t("[[:space:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Space))); + assert_eq!( + t("[[:upper:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Upper))); + assert_eq!( + t("[[:word:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Word))); + assert_eq!( + t("[[:xdigit:]]"), + hir_uclass(ascii_class(&ast::ClassAsciiKind::Xdigit))); + + assert_eq!( + t("[[:^lower:]]"), + hir_negate(hir_uclass(ascii_class(&ast::ClassAsciiKind::Lower)))); + assert_eq!( + t("(?i)[[:lower:]]"), + hir_uclass(&[ + ('A', 'Z'), ('a', 'z'), + ('\u{17F}', '\u{17F}'), + ('\u{212A}', '\u{212A}'), + ])); + + assert_eq!( + t("(?-u)[[:lower:]]"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Lower))); + assert_eq!( + t("(?i-u)[[:lower:]]"), + hir_case_fold(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Lower)))); + + assert_eq!(t_err("(?-u)[[:^lower:]]"), TestError { + kind: hir::ErrorKind::InvalidUtf8, + span: Span::new(Position::new(6, 1, 7), Position::new(16, 1, 17)), + }); + assert_eq!(t_err("(?i-u)[[:^lower:]]"), TestError { + kind: hir::ErrorKind::InvalidUtf8, + span: Span::new(Position::new(7, 1, 8), Position::new(17, 1, 18)), + }); + } + + #[test] + fn class_perl() { + // Unicode + assert_eq!( + t(r"\d"), + hir_uclass_query(ClassQuery::Binary("digit"))); + assert_eq!( + t(r"\s"), + hir_uclass_query(ClassQuery::Binary("space"))); + assert_eq!( + t(r"\w"), + hir_uclass_perl_word()); + assert_eq!( + t(r"(?i)\d"), + hir_uclass_query(ClassQuery::Binary("digit"))); + assert_eq!( + t(r"(?i)\s"), + hir_uclass_query(ClassQuery::Binary("space"))); + assert_eq!( + t(r"(?i)\w"), + hir_uclass_perl_word()); + + // Unicode, negated + assert_eq!( + t(r"\D"), + hir_negate(hir_uclass_query(ClassQuery::Binary("digit")))); + assert_eq!( + t(r"\S"), + hir_negate(hir_uclass_query(ClassQuery::Binary("space")))); + assert_eq!( + t(r"\W"), + hir_negate(hir_uclass_perl_word())); + assert_eq!( + t(r"(?i)\D"), + hir_negate(hir_uclass_query(ClassQuery::Binary("digit")))); + assert_eq!( + t(r"(?i)\S"), + hir_negate(hir_uclass_query(ClassQuery::Binary("space")))); + assert_eq!( + t(r"(?i)\W"), + hir_negate(hir_uclass_perl_word())); + + // ASCII only + assert_eq!( + t(r"(?-u)\d"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Digit))); + assert_eq!( + t(r"(?-u)\s"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Space))); + assert_eq!( + t(r"(?-u)\w"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Word))); + assert_eq!( + t(r"(?i-u)\d"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Digit))); + assert_eq!( + t(r"(?i-u)\s"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Space))); + assert_eq!( + t(r"(?i-u)\w"), + hir_bclass_from_char(ascii_class(&ast::ClassAsciiKind::Word))); + + // ASCII only, negated + assert_eq!( + t(r"(?-u)\D"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Digit)))); + assert_eq!( + t(r"(?-u)\S"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Space)))); + assert_eq!( + t(r"(?-u)\W"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Word)))); + assert_eq!( + t(r"(?i-u)\D"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Digit)))); + assert_eq!( + t(r"(?i-u)\S"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Space)))); + assert_eq!( + t(r"(?i-u)\W"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Word)))); + } + + #[test] + fn class_unicode() { + assert_eq!( + t(r"\pZ"), + hir_uclass_query(ClassQuery::Binary("Z"))); + assert_eq!( + t(r"\pz"), + hir_uclass_query(ClassQuery::Binary("Z"))); + assert_eq!( + t(r"\p{Separator}"), + hir_uclass_query(ClassQuery::Binary("Z"))); + assert_eq!( + t(r"\p{se PaRa ToR}"), + hir_uclass_query(ClassQuery::Binary("Z"))); + assert_eq!( + t(r"\p{gc:Separator}"), + hir_uclass_query(ClassQuery::Binary("Z"))); + assert_eq!( + t(r"\p{gc=Separator}"), + hir_uclass_query(ClassQuery::Binary("Z"))); + + assert_eq!( + t(r"\PZ"), + hir_negate(hir_uclass_query(ClassQuery::Binary("Z")))); + assert_eq!( + t(r"\P{separator}"), + hir_negate(hir_uclass_query(ClassQuery::Binary("Z")))); + assert_eq!( + t(r"\P{gc!=separator}"), + hir_negate(hir_uclass_query(ClassQuery::Binary("Z")))); + + assert_eq!( + t(r"\p{Greek}"), + hir_uclass_query(ClassQuery::Binary("Greek"))); + assert_eq!( + t(r"(?i)\p{Greek}"), + hir_case_fold(hir_uclass_query(ClassQuery::Binary("Greek")))); + assert_eq!( + t(r"(?i)\P{Greek}"), + hir_negate(hir_case_fold(hir_uclass_query( + ClassQuery::Binary("Greek"))))); + + assert_eq!( + t(r"\p{any}"), + hir_uclass_query(ClassQuery::Binary("Any"))); + assert_eq!( + t(r"\p{assigned}"), + hir_uclass_query(ClassQuery::Binary("Assigned"))); + assert_eq!( + t(r"\p{ascii}"), + hir_uclass_query(ClassQuery::Binary("ASCII"))); + assert_eq!( + t(r"\p{gc:any}"), + hir_uclass_query(ClassQuery::Binary("Any"))); + assert_eq!( + t(r"\p{gc:assigned}"), + hir_uclass_query(ClassQuery::Binary("Assigned"))); + assert_eq!( + t(r"\p{gc:ascii}"), + hir_uclass_query(ClassQuery::Binary("ASCII"))); + + assert_eq!(t_err(r"(?-u)\pZ"), TestError { + kind: hir::ErrorKind::UnicodeNotAllowed, + span: Span::new(Position::new(5, 1, 6), Position::new(8, 1, 9)), + }); + assert_eq!(t_err(r"(?-u)\p{Separator}"), TestError { + kind: hir::ErrorKind::UnicodeNotAllowed, + span: Span::new(Position::new(5, 1, 6), Position::new(18, 1, 19)), + }); + assert_eq!(t_err(r"\pE"), TestError { + kind: hir::ErrorKind::UnicodePropertyNotFound, + span: Span::new(Position::new(0, 1, 1), Position::new(3, 1, 4)), + }); + assert_eq!(t_err(r"\p{Foo}"), TestError { + kind: hir::ErrorKind::UnicodePropertyNotFound, + span: Span::new(Position::new(0, 1, 1), Position::new(7, 1, 8)), + }); + assert_eq!(t_err(r"\p{gc:Foo}"), TestError { + kind: hir::ErrorKind::UnicodePropertyValueNotFound, + span: Span::new(Position::new(0, 1, 1), Position::new(10, 1, 11)), + }); + assert_eq!(t_err(r"\p{sc:Foo}"), TestError { + kind: hir::ErrorKind::UnicodePropertyValueNotFound, + span: Span::new(Position::new(0, 1, 1), Position::new(10, 1, 11)), + }); + assert_eq!(t_err(r"\p{scx:Foo}"), TestError { + kind: hir::ErrorKind::UnicodePropertyValueNotFound, + span: Span::new(Position::new(0, 1, 1), Position::new(11, 1, 12)), + }); + assert_eq!(t_err(r"\p{age:Foo}"), TestError { + kind: hir::ErrorKind::UnicodePropertyValueNotFound, + span: Span::new(Position::new(0, 1, 1), Position::new(11, 1, 12)), + }); + } + + #[test] + fn class_bracketed() { + assert_eq!(t("[a]"), hir_uclass(&[('a', 'a')])); + assert_eq!(t("[^[a]]"), hir_negate(hir_uclass(&[('a', 'a')]))); + assert_eq!(t("[a-z]"), hir_uclass(&[('a', 'z')])); + assert_eq!(t("[a-fd-h]"), hir_uclass(&[('a', 'h')])); + assert_eq!(t("[a-fg-m]"), hir_uclass(&[('a', 'm')])); + assert_eq!(t(r"[\x00]"), hir_uclass(&[('\0', '\0')])); + assert_eq!(t(r"[\n]"), hir_uclass(&[('\n', '\n')])); + assert_eq!(t("[\n]"), hir_uclass(&[('\n', '\n')])); + assert_eq!( + t(r"[\d]"), + hir_uclass_query(ClassQuery::Binary("digit"))); + assert_eq!( + t(r"[\pZ]"), + hir_uclass_query(ClassQuery::Binary("separator"))); + assert_eq!( + t(r"[\p{separator}]"), + hir_uclass_query(ClassQuery::Binary("separator"))); + assert_eq!( + t(r"[^\D]"), + hir_uclass_query(ClassQuery::Binary("digit"))); + assert_eq!( + t(r"[^\PZ]"), + hir_uclass_query(ClassQuery::Binary("separator"))); + assert_eq!( + t(r"[^\P{separator}]"), + hir_uclass_query(ClassQuery::Binary("separator"))); + assert_eq!( + t(r"(?i)[^\D]"), + hir_uclass_query(ClassQuery::Binary("digit"))); + assert_eq!( + t(r"(?i)[^\P{greek}]"), + hir_case_fold(hir_uclass_query(ClassQuery::Binary("greek")))); + + assert_eq!(t("(?-u)[a]"), hir_bclass(&[(b'a', b'a')])); + assert_eq!(t(r"(?-u)[\x00]"), hir_bclass(&[(b'\0', b'\0')])); + assert_eq!(t_bytes(r"(?-u)[\xFF]"), hir_bclass(&[(b'\xFF', b'\xFF')])); + + assert_eq!(t("(?i)[a]"), hir_uclass(&[('A', 'A'), ('a', 'a')])); + assert_eq!(t("(?i)[k]"), hir_uclass(&[ + ('K', 'K'), ('k', 'k'), ('\u{212A}', '\u{212A}'), + ])); + assert_eq!(t("(?i)[β]"), hir_uclass(&[ + ('Β', 'Β'), ('β', 'β'), ('ϐ', 'ϐ'), + ])); + assert_eq!(t("(?i-u)[k]"), hir_bclass(&[ + (b'K', b'K'), (b'k', b'k'), + ])); + + assert_eq!(t("[^a]"), hir_negate(hir_uclass(&[('a', 'a')]))); + assert_eq!(t(r"[^\x00]"), hir_negate(hir_uclass(&[('\0', '\0')]))); + assert_eq!( + t_bytes("(?-u)[^a]"), + hir_negate(hir_bclass(&[(b'a', b'a')]))); + assert_eq!( + t(r"[^\d]"), + hir_negate(hir_uclass_query(ClassQuery::Binary("digit")))); + assert_eq!( + t(r"[^\pZ]"), + hir_negate(hir_uclass_query(ClassQuery::Binary("separator")))); + assert_eq!( + t(r"[^\p{separator}]"), + hir_negate(hir_uclass_query(ClassQuery::Binary("separator")))); + assert_eq!( + t(r"(?i)[^\p{greek}]"), + hir_negate(hir_case_fold(hir_uclass_query( + ClassQuery::Binary("greek"))))); + assert_eq!( + t(r"(?i)[\P{greek}]"), + hir_negate(hir_case_fold(hir_uclass_query( + ClassQuery::Binary("greek"))))); + + // Test some weird cases. + assert_eq!(t(r"[\[]"), hir_uclass(&[('[', '[')])); + + assert_eq!(t(r"[&]"), hir_uclass(&[('&', '&')])); + assert_eq!(t(r"[\&]"), hir_uclass(&[('&', '&')])); + assert_eq!(t(r"[\&\&]"), hir_uclass(&[('&', '&')])); + assert_eq!(t(r"[\x00-&]"), hir_uclass(&[('\0', '&')])); + assert_eq!(t(r"[&-\xFF]"), hir_uclass(&[('&', '\u{FF}')])); + + assert_eq!(t(r"[~]"), hir_uclass(&[('~', '~')])); + assert_eq!(t(r"[\~]"), hir_uclass(&[('~', '~')])); + assert_eq!(t(r"[\~\~]"), hir_uclass(&[('~', '~')])); + assert_eq!(t(r"[\x00-~]"), hir_uclass(&[('\0', '~')])); + assert_eq!(t(r"[~-\xFF]"), hir_uclass(&[('~', '\u{FF}')])); + + assert_eq!(t(r"[-]"), hir_uclass(&[('-', '-')])); + assert_eq!(t(r"[\-]"), hir_uclass(&[('-', '-')])); + assert_eq!(t(r"[\-\-]"), hir_uclass(&[('-', '-')])); + assert_eq!(t(r"[\x00-\-]"), hir_uclass(&[('\0', '-')])); + assert_eq!(t(r"[\--\xFF]"), hir_uclass(&[('-', '\u{FF}')])); + + assert_eq!(t_err("(?-u)[^a]"), TestError { + kind: hir::ErrorKind::InvalidUtf8, + span: Span::new(Position::new(5, 1, 6), Position::new(9, 1, 10)), + }); + assert_eq!(t_err(r"[^\s\S]"), TestError { + kind: hir::ErrorKind::EmptyClassNotAllowed, + span: Span::new(Position::new(0, 1, 1), Position::new(7, 1, 8)), + }); + assert_eq!(t_err(r"(?-u)[^\s\S]"), TestError { + kind: hir::ErrorKind::EmptyClassNotAllowed, + span: Span::new(Position::new(5, 1, 6), Position::new(12, 1, 13)), + }); + } + + #[test] + fn class_bracketed_union() { + assert_eq!( + t("[a-zA-Z]"), + hir_uclass(&[('A', 'Z'), ('a', 'z')])); + assert_eq!( + t(r"[a\pZb]"), + hir_union( + hir_uclass(&[('a', 'b')]), + hir_uclass_query(ClassQuery::Binary("separator")))); + assert_eq!( + t(r"[\pZ\p{Greek}]"), + hir_union( + hir_uclass_query(ClassQuery::Binary("greek")), + hir_uclass_query(ClassQuery::Binary("separator")))); + assert_eq!( + t(r"[\p{age:3.0}\pZ\p{Greek}]"), + hir_union( + hir_uclass_query(ClassQuery::ByValue { + property_name: "age", + property_value: "3.0", + }), + hir_union( + hir_uclass_query(ClassQuery::Binary("greek")), + hir_uclass_query(ClassQuery::Binary("separator"))))); + assert_eq!( + t(r"[[[\p{age:3.0}\pZ]\p{Greek}][\p{Cyrillic}]]"), + hir_union( + hir_uclass_query(ClassQuery::ByValue { + property_name: "age", + property_value: "3.0", + }), + hir_union( + hir_uclass_query(ClassQuery::Binary("cyrillic")), + hir_union( + hir_uclass_query(ClassQuery::Binary("greek")), + hir_uclass_query(ClassQuery::Binary("separator")))))); + + assert_eq!( + t(r"(?i)[\p{age:3.0}\pZ\p{Greek}]"), + hir_case_fold(hir_union( + hir_uclass_query(ClassQuery::ByValue { + property_name: "age", + property_value: "3.0", + }), + hir_union( + hir_uclass_query(ClassQuery::Binary("greek")), + hir_uclass_query(ClassQuery::Binary("separator")))))); + assert_eq!( + t(r"[^\p{age:3.0}\pZ\p{Greek}]"), + hir_negate(hir_union( + hir_uclass_query(ClassQuery::ByValue { + property_name: "age", + property_value: "3.0", + }), + hir_union( + hir_uclass_query(ClassQuery::Binary("greek")), + hir_uclass_query(ClassQuery::Binary("separator")))))); + assert_eq!( + t(r"(?i)[^\p{age:3.0}\pZ\p{Greek}]"), + hir_negate(hir_case_fold(hir_union( + hir_uclass_query(ClassQuery::ByValue { + property_name: "age", + property_value: "3.0", + }), + hir_union( + hir_uclass_query(ClassQuery::Binary("greek")), + hir_uclass_query(ClassQuery::Binary("separator"))))))); + } + + #[test] + fn class_bracketed_nested() { + assert_eq!( + t(r"[a[^c]]"), + hir_negate(hir_uclass(&[('c', 'c')]))); + assert_eq!( + t(r"[a-b[^c]]"), + hir_negate(hir_uclass(&[('c', 'c')]))); + assert_eq!( + t(r"[a-c[^c]]"), + hir_negate(hir_uclass(&[]))); + + assert_eq!( + t(r"[^a[^c]]"), + hir_uclass(&[('c', 'c')])); + assert_eq!( + t(r"[^a-b[^c]]"), + hir_uclass(&[('c', 'c')])); + + assert_eq!( + t(r"(?i)[a[^c]]"), + hir_negate(hir_case_fold(hir_uclass(&[('c', 'c')])))); + assert_eq!( + t(r"(?i)[a-b[^c]]"), + hir_negate(hir_case_fold(hir_uclass(&[('c', 'c')])))); + + assert_eq!( + t(r"(?i)[^a[^c]]"), + hir_uclass(&[('C', 'C'), ('c', 'c')])); + assert_eq!( + t(r"(?i)[^a-b[^c]]"), + hir_uclass(&[('C', 'C'), ('c', 'c')])); + + assert_eq!(t_err(r"[^a-c[^c]]"), TestError { + kind: hir::ErrorKind::EmptyClassNotAllowed, + span: Span::new(Position::new(0, 1, 1), Position::new(10, 1, 11)), + }); + assert_eq!(t_err(r"(?i)[^a-c[^c]]"), TestError { + kind: hir::ErrorKind::EmptyClassNotAllowed, + span: Span::new(Position::new(4, 1, 5), Position::new(14, 1, 15)), + }); + } + + #[test] + fn class_bracketed_intersect() { + assert_eq!(t("[abc&&b-c]"), hir_uclass(&[('b', 'c')])); + assert_eq!(t("[abc&&[b-c]]"), hir_uclass(&[('b', 'c')])); + assert_eq!(t("[[abc]&&[b-c]]"), hir_uclass(&[('b', 'c')])); + assert_eq!(t("[a-z&&b-y&&c-x]"), hir_uclass(&[('c', 'x')])); + assert_eq!(t("[c-da-b&&a-d]"), hir_uclass(&[('a', 'd')])); + assert_eq!(t("[a-d&&c-da-b]"), hir_uclass(&[('a', 'd')])); + assert_eq!(t(r"[a-z&&a-c]"), hir_uclass(&[('a', 'c')])); + assert_eq!(t(r"[[a-z&&a-c]]"), hir_uclass(&[('a', 'c')])); + assert_eq!(t(r"[^[a-z&&a-c]]"), hir_negate(hir_uclass(&[('a', 'c')]))); + + assert_eq!(t("(?-u)[abc&&b-c]"), hir_bclass(&[(b'b', b'c')])); + assert_eq!(t("(?-u)[abc&&[b-c]]"), hir_bclass(&[(b'b', b'c')])); + assert_eq!(t("(?-u)[[abc]&&[b-c]]"), hir_bclass(&[(b'b', b'c')])); + assert_eq!(t("(?-u)[a-z&&b-y&&c-x]"), hir_bclass(&[(b'c', b'x')])); + assert_eq!(t("(?-u)[c-da-b&&a-d]"), hir_bclass(&[(b'a', b'd')])); + assert_eq!(t("(?-u)[a-d&&c-da-b]"), hir_bclass(&[(b'a', b'd')])); + + assert_eq!( + t("(?i)[abc&&b-c]"), + hir_case_fold(hir_uclass(&[('b', 'c')]))); + assert_eq!( + t("(?i)[abc&&[b-c]]"), + hir_case_fold(hir_uclass(&[('b', 'c')]))); + assert_eq!( + t("(?i)[[abc]&&[b-c]]"), + hir_case_fold(hir_uclass(&[('b', 'c')]))); + assert_eq!( + t("(?i)[a-z&&b-y&&c-x]"), + hir_case_fold(hir_uclass(&[('c', 'x')]))); + assert_eq!( + t("(?i)[c-da-b&&a-d]"), + hir_case_fold(hir_uclass(&[('a', 'd')]))); + assert_eq!( + t("(?i)[a-d&&c-da-b]"), + hir_case_fold(hir_uclass(&[('a', 'd')]))); + + assert_eq!( + t("(?i-u)[abc&&b-c]"), + hir_case_fold(hir_bclass(&[(b'b', b'c')]))); + assert_eq!( + t("(?i-u)[abc&&[b-c]]"), + hir_case_fold(hir_bclass(&[(b'b', b'c')]))); + assert_eq!( + t("(?i-u)[[abc]&&[b-c]]"), + hir_case_fold(hir_bclass(&[(b'b', b'c')]))); + assert_eq!( + t("(?i-u)[a-z&&b-y&&c-x]"), + hir_case_fold(hir_bclass(&[(b'c', b'x')]))); + assert_eq!( + t("(?i-u)[c-da-b&&a-d]"), + hir_case_fold(hir_bclass(&[(b'a', b'd')]))); + assert_eq!( + t("(?i-u)[a-d&&c-da-b]"), + hir_case_fold(hir_bclass(&[(b'a', b'd')]))); + + // In `[a^]`, `^` does not need to be escaped, so it makes sense that + // `^` is also allowed to be unescaped after `&&`. + assert_eq!(t(r"[\^&&^]"), hir_uclass(&[('^', '^')])); + // `]` needs to be escaped after `&&` since it's not at start of class. + assert_eq!(t(r"[]&&\]]"), hir_uclass(&[(']', ']')])); + assert_eq!(t(r"[-&&-]"), hir_uclass(&[('-', '-')])); + assert_eq!(t(r"[\&&&&]"), hir_uclass(&[('&', '&')])); + assert_eq!(t(r"[\&&&\&]"), hir_uclass(&[('&', '&')])); + // Test precedence. + assert_eq!( + t(r"[a-w&&[^c-g]z]"), + hir_uclass(&[('a', 'b'), ('h', 'w')])); + } + + #[test] + fn class_bracketed_intersect_negate() { + assert_eq!( + t(r"[^\w&&\d]"), + hir_negate(hir_uclass_query(ClassQuery::Binary("digit")))); + assert_eq!( + t(r"[^[a-z&&a-c]]"), + hir_negate(hir_uclass(&[('a', 'c')]))); + assert_eq!( + t(r"[^[\w&&\d]]"), + hir_negate(hir_uclass_query(ClassQuery::Binary("digit")))); + assert_eq!( + t(r"[^[^\w&&\d]]"), + hir_uclass_query(ClassQuery::Binary("digit"))); + assert_eq!( + t(r"[[[^\w]&&[^\d]]]"), + hir_negate(hir_uclass_perl_word())); + + assert_eq!( + t_bytes(r"(?-u)[^\w&&\d]"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Digit)))); + assert_eq!( + t_bytes(r"(?-u)[^[a-z&&a-c]]"), + hir_negate(hir_bclass(&[(b'a', b'c')]))); + assert_eq!( + t_bytes(r"(?-u)[^[\w&&\d]]"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Digit)))); + assert_eq!( + t_bytes(r"(?-u)[^[^\w&&\d]]"), + hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Digit))); + assert_eq!( + t_bytes(r"(?-u)[[[^\w]&&[^\d]]]"), + hir_negate(hir_bclass_from_char(ascii_class( + &ast::ClassAsciiKind::Word)))); + } + + #[test] + fn class_bracketed_difference() { + assert_eq!( + t(r"[\pL--[:ascii:]]"), + hir_difference( + hir_uclass_query(ClassQuery::Binary("letter")), + hir_uclass(&[('\0', '\x7F')]))); + + assert_eq!( + t(r"(?-u)[[:alpha:]--[:lower:]]"), + hir_bclass(&[(b'A', b'Z')])); + } + + #[test] + fn class_bracketed_symmetric_difference() { + assert_eq!( + t(r"[\p{sc:Greek}~~\p{scx:Greek}]"), + hir_uclass(&[ + ('\u{0342}', '\u{0342}'), + ('\u{0345}', '\u{0345}'), + ('\u{1DC0}', '\u{1DC1}'), + ])); + assert_eq!( + t(r"[a-g~~c-j]"), + hir_uclass(&[('a', 'b'), ('h', 'j')])); + + assert_eq!( + t(r"(?-u)[a-g~~c-j]"), + hir_bclass(&[(b'a', b'b'), (b'h', b'j')])); + } + + #[test] + fn ignore_whitespace() { + assert_eq!(t(r"(?x)\12 3"), hir_lit("\n3")); + assert_eq!(t(r"(?x)\x { 53 }"), hir_lit("S")); + assert_eq!(t(r"(?x)\x # comment +{ # comment + 53 # comment +} #comment"), hir_lit("S")); + + assert_eq!(t(r"(?x)\x 53"), hir_lit("S")); + assert_eq!(t(r"(?x)\x # comment + 53 # comment"), hir_lit("S")); + assert_eq!(t(r"(?x)\x5 3"), hir_lit("S")); + + assert_eq!(t(r"(?x)\p # comment +{ # comment + Separator # comment +} # comment"), hir_uclass_query(ClassQuery::Binary("separator"))); + + assert_eq!(t(r"(?x)a # comment +{ # comment + 5 # comment + , # comment + 10 # comment +} # comment"), + hir_range( + true, hir::RepetitionRange::Bounded(5, 10), hir_lit("a"))); + + assert_eq!(t(r"(?x)a\ # hi there"), hir_lit("a ")); + } + + #[test] + fn analysis_is_always_utf8() { + // Positive examples. + assert!(t_bytes(r"a").is_always_utf8()); + assert!(t_bytes(r"ab").is_always_utf8()); + assert!(t_bytes(r"(?-u)a").is_always_utf8()); + assert!(t_bytes(r"(?-u)ab").is_always_utf8()); + assert!(t_bytes(r"\xFF").is_always_utf8()); + assert!(t_bytes(r"\xFF\xFF").is_always_utf8()); + assert!(t_bytes(r"[^a]").is_always_utf8()); + assert!(t_bytes(r"[^a][^a]").is_always_utf8()); + assert!(t_bytes(r"\b").is_always_utf8()); + assert!(t_bytes(r"\B").is_always_utf8()); + assert!(t_bytes(r"(?-u)\b").is_always_utf8()); + + // Negative examples. + assert!(!t_bytes(r"(?-u)\xFF").is_always_utf8()); + assert!(!t_bytes(r"(?-u)\xFF\xFF").is_always_utf8()); + assert!(!t_bytes(r"(?-u)[^a]").is_always_utf8()); + assert!(!t_bytes(r"(?-u)[^a][^a]").is_always_utf8()); + assert!(!t_bytes(r"(?-u)\B").is_always_utf8()); + } + + #[test] + fn analysis_is_all_assertions() { + // Positive examples. + assert!(t(r"\b").is_all_assertions()); + assert!(t(r"\B").is_all_assertions()); + assert!(t(r"^").is_all_assertions()); + assert!(t(r"$").is_all_assertions()); + assert!(t(r"\A").is_all_assertions()); + assert!(t(r"\z").is_all_assertions()); + assert!(t(r"$^\z\A\b\B").is_all_assertions()); + assert!(t(r"$|^|\z|\A|\b|\B").is_all_assertions()); + assert!(t(r"^$|$^").is_all_assertions()); + assert!(t(r"((\b)+())*^").is_all_assertions()); + + // Negative examples. + assert!(!t(r"^a").is_all_assertions()); + } + + #[test] + fn analysis_is_anchored() { + // Positive examples. + assert!(t(r"^").is_anchored_start()); + assert!(t(r"$").is_anchored_end()); + + assert!(t(r"^^").is_anchored_start()); + assert!(t(r"$$").is_anchored_end()); + + assert!(t(r"^$").is_anchored_start()); + assert!(t(r"^$").is_anchored_end()); + + assert!(t(r"^foo").is_anchored_start()); + assert!(t(r"foo$").is_anchored_end()); + + assert!(t(r"^foo|^bar").is_anchored_start()); + assert!(t(r"foo$|bar$").is_anchored_end()); + + assert!(t(r"^(foo|bar)").is_anchored_start()); + assert!(t(r"(foo|bar)$").is_anchored_end()); + + assert!(t(r"^+").is_anchored_start()); + assert!(t(r"$+").is_anchored_end()); + assert!(t(r"^++").is_anchored_start()); + assert!(t(r"$++").is_anchored_end()); + assert!(t(r"(^)+").is_anchored_start()); + assert!(t(r"($)+").is_anchored_end()); + + assert!(t(r"$^").is_anchored_start()); + assert!(t(r"$^").is_anchored_end()); + assert!(t(r"$^|^$").is_anchored_start()); + assert!(t(r"$^|^$").is_anchored_end()); + + assert!(t(r"\b^").is_anchored_start()); + assert!(t(r"$\b").is_anchored_end()); + assert!(t(r"^(?m:^)").is_anchored_start()); + assert!(t(r"(?m:$)$").is_anchored_end()); + assert!(t(r"(?m:^)^").is_anchored_start()); + assert!(t(r"$(?m:$)").is_anchored_end()); + + // Negative examples. + assert!(!t(r"(?m)^").is_anchored_start()); + assert!(!t(r"(?m)$").is_anchored_end()); + assert!(!t(r"(?m:^$)|$^").is_anchored_start()); + assert!(!t(r"(?m:^$)|$^").is_anchored_end()); + assert!(!t(r"$^|(?m:^$)").is_anchored_start()); + assert!(!t(r"$^|(?m:^$)").is_anchored_end()); + + assert!(!t(r"a^").is_anchored_start()); + assert!(!t(r"$a").is_anchored_start()); + + assert!(!t(r"a^").is_anchored_start()); + assert!(!t(r"$a").is_anchored_start()); + + assert!(!t(r"^foo|bar").is_anchored_start()); + assert!(!t(r"foo|bar$").is_anchored_end()); + + assert!(!t(r"^*").is_anchored_start()); + assert!(!t(r"$*").is_anchored_end()); + assert!(!t(r"^*+").is_anchored_start()); + assert!(!t(r"$*+").is_anchored_end()); + assert!(!t(r"^+*").is_anchored_start()); + assert!(!t(r"$+*").is_anchored_end()); + assert!(!t(r"(^)*").is_anchored_start()); + assert!(!t(r"($)*").is_anchored_end()); + } + + #[test] + fn analysis_is_any_anchored() { + // Positive examples. + assert!(t(r"^").is_any_anchored_start()); + assert!(t(r"$").is_any_anchored_end()); + assert!(t(r"\A").is_any_anchored_start()); + assert!(t(r"\z").is_any_anchored_end()); + + // Negative examples. + assert!(!t(r"(?m)^").is_any_anchored_start()); + assert!(!t(r"(?m)$").is_any_anchored_end()); + assert!(!t(r"$").is_any_anchored_start()); + assert!(!t(r"^").is_any_anchored_end()); + } + + #[test] + fn analysis_is_match_empty() { + // Positive examples. + assert!(t(r"").is_match_empty()); + assert!(t(r"()").is_match_empty()); + assert!(t(r"()*").is_match_empty()); + assert!(t(r"()+").is_match_empty()); + assert!(t(r"()?").is_match_empty()); + assert!(t(r"a*").is_match_empty()); + assert!(t(r"a?").is_match_empty()); + assert!(t(r"a{0}").is_match_empty()); + assert!(t(r"a{0,}").is_match_empty()); + assert!(t(r"a{0,1}").is_match_empty()); + assert!(t(r"a{0,10}").is_match_empty()); + assert!(t(r"\pL*").is_match_empty()); + assert!(t(r"a*|b").is_match_empty()); + assert!(t(r"b|a*").is_match_empty()); + assert!(t(r"a*a?(abcd)*").is_match_empty()); + assert!(t(r"^").is_match_empty()); + assert!(t(r"$").is_match_empty()); + assert!(t(r"(?m)^").is_match_empty()); + assert!(t(r"(?m)$").is_match_empty()); + assert!(t(r"\A").is_match_empty()); + assert!(t(r"\z").is_match_empty()); + assert!(t(r"\B").is_match_empty()); + assert!(t_bytes(r"(?-u)\B").is_match_empty()); + + // Negative examples. + assert!(!t(r"a+").is_match_empty()); + assert!(!t(r"a{1}").is_match_empty()); + assert!(!t(r"a{1,}").is_match_empty()); + assert!(!t(r"a{1,2}").is_match_empty()); + assert!(!t(r"a{1,10}").is_match_empty()); + assert!(!t(r"b|a").is_match_empty()); + assert!(!t(r"a*a+(abcd)*").is_match_empty()); + assert!(!t(r"\b").is_match_empty()); + assert!(!t(r"(?-u)\b").is_match_empty()); + } +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/hir/visitor.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/hir/visitor.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/hir/visitor.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/hir/visitor.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,222 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use hir::{self, Hir, HirKind}; + +/// A trait for visiting the high-level IR (HIR) in depth first order. +/// +/// The principle aim of this trait is to enable callers to perform case +/// analysis on a high-level intermediate representation of a regular +/// expression without necessarily using recursion. In particular, this permits +/// callers to do case analysis with constant stack usage, which can be +/// important since the size of an HIR may be proportional to end user input. +/// +/// Typical usage of this trait involves providing an implementation and then +/// running it using the [`visit`](fn.visit.html) function. +pub trait Visitor { + /// The result of visiting an HIR. + type Output; + /// An error that visiting an HIR might return. + type Err; + + /// All implementors of `Visitor` must provide a `finish` method, which + /// yields the result of visiting the HIR or an error. + fn finish(self) -> Result<Self::Output, Self::Err>; + + /// This method is called before beginning traversal of the HIR. + fn start(&mut self) {} + + /// This method is called on an `Hir` before descending into child `Hir` + /// nodes. + fn visit_pre(&mut self, _hir: &Hir) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called on an `Hir` after descending all of its child + /// `Hir` nodes. + fn visit_post(&mut self, _hir: &Hir) -> Result<(), Self::Err> { + Ok(()) + } + + /// This method is called between child nodes of an alternation. + fn visit_alternation_in(&mut self) -> Result<(), Self::Err> { + Ok(()) + } +} + +/// Executes an implementation of `Visitor` in constant stack space. +/// +/// This function will visit every node in the given `Hir` while calling +/// appropriate methods provided by the +/// [`Visitor`](trait.Visitor.html) trait. +/// +/// The primary use case for this method is when one wants to perform case +/// analysis over an `Hir` without using a stack size proportional to the depth +/// of the `Hir`. Namely, this method will instead use constant stack space, +/// but will use heap space proportional to the size of the `Hir`. This may be +/// desirable in cases where the size of `Hir` is proportional to end user +/// input. +/// +/// If the visitor returns an error at any point, then visiting is stopped and +/// the error is returned. +pub fn visit<V: Visitor>(hir: &Hir, visitor: V) -> Result<V::Output, V::Err> { + HeapVisitor::new().visit(hir, visitor) +} + +/// HeapVisitor visits every item in an `Hir` recursively using constant stack +/// size and a heap size proportional to the size of the `Hir`. +struct HeapVisitor<'a> { + /// A stack of `Hir` nodes. This is roughly analogous to the call stack + /// used in a typical recursive visitor. + stack: Vec<(&'a Hir, Frame<'a>)>, +} + +/// Represents a single stack frame while performing structural induction over +/// an `Hir`. +enum Frame<'a> { + /// A stack frame allocated just before descending into a repetition + /// operator's child node. + Repetition(&'a hir::Repetition), + /// A stack frame allocated just before descending into a group's child + /// node. + Group(&'a hir::Group), + /// The stack frame used while visiting every child node of a concatenation + /// of expressions. + Concat { + /// The child node we are currently visiting. + head: &'a Hir, + /// The remaining child nodes to visit (which may be empty). + tail: &'a [Hir], + }, + /// The stack frame used while visiting every child node of an alternation + /// of expressions. + Alternation { + /// The child node we are currently visiting. + head: &'a Hir, + /// The remaining child nodes to visit (which may be empty). + tail: &'a [Hir], + }, +} + +impl<'a> HeapVisitor<'a> { + fn new() -> HeapVisitor<'a> { + HeapVisitor { stack: vec![] } + } + + fn visit<V: Visitor>( + &mut self, + mut hir: &'a Hir, + mut visitor: V, + ) -> Result<V::Output, V::Err> { + self.stack.clear(); + + visitor.start(); + loop { + try!(visitor.visit_pre(hir)); + if let Some(x) = self.induct(hir) { + let child = x.child(); + self.stack.push((hir, x)); + hir = child; + continue; + } + // No induction means we have a base case, so we can post visit + // it now. + try!(visitor.visit_post(hir)); + + // At this point, we now try to pop our call stack until it is + // either empty or we hit another inductive case. + loop { + let (post_hir, frame) = match self.stack.pop() { + None => return visitor.finish(), + Some((post_hir, frame)) => (post_hir, frame), + }; + // If this is a concat/alternate, then we might have additional + // inductive steps to process. + if let Some(x) = self.pop(frame) { + if let Frame::Alternation {..} = x { + try!(visitor.visit_alternation_in()); + } + hir = x.child(); + self.stack.push((post_hir, x)); + break; + } + // Otherwise, we've finished visiting all the child nodes for + // this HIR, so we can post visit it now. + try!(visitor.visit_post(post_hir)); + } + } + } + + /// Build a stack frame for the given HIR if one is needed (which occurs if + /// and only if there are child nodes in the HIR). Otherwise, return None. + fn induct(&mut self, hir: &'a Hir) -> Option<Frame<'a>> { + match *hir.kind() { + HirKind::Repetition(ref x) => Some(Frame::Repetition(x)), + HirKind::Group(ref x) => Some(Frame::Group(x)), + HirKind::Concat(ref x) if x.is_empty() => None, + HirKind::Concat(ref x) => { + Some(Frame::Concat { + head: &x[0], + tail: &x[1..], + }) + } + HirKind::Alternation(ref x) if x.is_empty() => None, + HirKind::Alternation(ref x) => { + Some(Frame::Alternation { + head: &x[0], + tail: &x[1..], + }) + } + _ => None, + } + } + + /// Pops the given frame. If the frame has an additional inductive step, + /// then return it, otherwise return `None`. + fn pop(&self, induct: Frame<'a>) -> Option<Frame<'a>> { + match induct { + Frame::Repetition(_) => None, + Frame::Group(_) => None, + Frame::Concat { tail, .. } => { + if tail.is_empty() { + None + } else { + Some(Frame::Concat { + head: &tail[0], + tail: &tail[1..], + }) + } + } + Frame::Alternation { tail, .. } => { + if tail.is_empty() { + None + } else { + Some(Frame::Alternation { + head: &tail[0], + tail: &tail[1..], + }) + } + } + } + } +} + +impl<'a> Frame<'a> { + /// Perform the next inductive step on this frame and return the next + /// child HIR node to visit. + fn child(&self) -> &'a Hir { + match *self { + Frame::Repetition(rep) => &rep.hir, + Frame::Group(group) => &group.hir, + Frame::Concat { head, .. } => head, + Frame::Alternation { head, .. } => head, + } + } +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/lib.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/lib.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,222 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/*! +This crate provides a robust regular expression parser. + +This crate defines two primary types: + +* [`Ast`](ast/enum.Ast.html) is the abstract syntax of a regular expression. + An abstract syntax corresponds to a *structured representation* of the + concrete syntax of a regular expression, where the concrete syntax is the + pattern string itself (e.g., `foo(bar)+`). Given some abstract syntax, it + can be converted back to the original concrete syntax (modulo some details, + like whitespace). To a first approximation, the abstract syntax is complex + and difficult to analyze. +* [`Hir`](hir/struct.Hir.html) is the high-level intermediate representation + ("HIR" or "high-level IR" for short) of regular expression. It corresponds to + an intermediate state of a regular expression that sits between the abstract + syntax and the low level compiled opcodes that are eventually responsible for + executing a regular expression search. Given some high-level IR, it is not + possible to produce the original concrete syntax (although it is possible to + produce an equivalent conrete syntax, but it will likely scarcely resemble + the original pattern). To a first approximation, the high-level IR is simple + and easy to analyze. + +These two types come with conversion routines: + +* An [`ast::parse::Parser`](ast/parse/struct.Parser.html) converts concrete + syntax (a `&str`) to an [`Ast`](ast/enum.Ast.html). +* A [`hir::translate::Translator`](hir/translate/struct.Translator.html) + converts an [`Ast`](ast/enum.Ast.html) to a [`Hir`](hir/struct.Hir.html). + +As a convenience, the above two conversion routines are combined into one via +the top-level [`Parser`](struct.Parser.html) type. This `Parser` will first +convert your pattern to an `Ast` and then convert the `Ast` to an `Hir`. + + +# Example + +This example shows how to parse a pattern string into its HIR: + +``` +use regex_syntax::Parser; +use regex_syntax::hir::{self, Hir}; + +let hir = Parser::new().parse("a|b").unwrap(); +assert_eq!(hir, Hir::alternation(vec![ + Hir::literal(hir::Literal::Unicode('a')), + Hir::literal(hir::Literal::Unicode('b')), +])); +``` + + +# Concrete syntax supported + +The concrete syntax is documented as part of the public API of the +[`regex` crate](https://docs.rs/regex/%2A/regex/#syntax). + + +# Input safety + +A key feature of this library is that it is safe to use with end user facing +input. This plays a significant role in the internal implementation. In +particular: + +1. Parsers provide a `nest_limit` option that permits callers to control how + deeply nested a regular expression is allowed to be. This makes it possible + to do case analysis over an `Ast` or an `Hir` using recursion without + worrying about stack overflow. +2. Since relying on a particular stack size is brittle, this crate goes to + great lengths to ensure that all interactions with both the `Ast` and the + `Hir` do not use recursion. Namely, they use constant stack space and heap + space proportional to the size of the original pattern string (in bytes). + This includes the type's corresponding destructors. (One exception to this + is literal extraction, but this will eventually get fixed.) + + +# Error reporting + +The `Display` implementations on all `Error` types exposed in this library +provide nice human readable errors that are suitable for showing to end users +in a monospace font. + + +# Literal extraction + +This crate provides limited support for +[literal extraction from `Hir` values](hir/literal/struct.Literals.html). +Be warned that literal extraction currently uses recursion, and therefore, +stack size proportional to the size of the `Hir`. + +The purpose of literal extraction is to speed up searches. That is, if you +know a regular expression must match a prefix or suffix literal, then it is +often quicker to search for instances of that literal, and then confirm or deny +the match using the full regular expression engine. These optimizations are +done automatically in the `regex` crate. +*/ + +#![deny(missing_docs)] + +extern crate ucd_util; + +pub use error::{Error, Result}; +pub use parser::{Parser, ParserBuilder}; + +pub mod ast; +mod either; +mod error; +pub mod hir; +mod parser; +mod unicode; +mod unicode_tables; + +/// Escapes all regular expression meta characters in `text`. +/// +/// The string returned may be safely used as a literal in a regular +/// expression. +pub fn escape(text: &str) -> String { + let mut quoted = String::with_capacity(text.len()); + escape_into(text, &mut quoted); + quoted +} + +/// Escapes all meta characters in `text` and writes the result into `buf`. +/// +/// This will append escape characters into the given buffer. The characters +/// that are appended are safe to use as a literal in a regular expression. +pub fn escape_into(text: &str, buf: &mut String) { + for c in text.chars() { + if is_meta_character(c) { + buf.push('\\'); + } + buf.push(c); + } +} + +/// Returns true if the give character has significance in a regex. +/// +/// These are the only characters that are allowed to be escaped, with one +/// exception: an ASCII space character may be escaped when extended mode (with +/// the `x` flag) is enabld. In particular, `is_meta_character(' ')` returns +/// `false`. +/// +/// Note that the set of characters for which this function returns `true` or +/// `false` is fixed and won't change in a semver compatible release. +pub fn is_meta_character(c: char) -> bool { + match c { + '\\' | '.' | '+' | '*' | '?' | '(' | ')' | '|' | + '[' | ']' | '{' | '}' | '^' | '$' | '#' | '&' | '-' | '~' => true, + _ => false, + } +} + +/// Returns true if and only if the given character is a Unicode word +/// character. +/// +/// A Unicode word character is defined by +/// [UTS#18 Annex C](http://unicode.org/reports/tr18/#Compatibility_Properties). +/// In particular, a character +/// is considered a word character if it is in either of the `Alphabetic` or +/// `Join_Control` properties, or is in one of the `Decimal_Number`, `Mark` +/// or `Connector_Punctuation` general categories. +pub fn is_word_character(c: char) -> bool { + use std::cmp::Ordering; + use unicode_tables::perl_word::PERL_WORD; + + if c <= 0x7F as char && is_word_byte(c as u8) { + return true; + } + PERL_WORD + .binary_search_by(|&(start, end)| { + if start <= c && c <= end { + Ordering::Equal + } else if start > c { + Ordering::Greater + } else { + Ordering::Less + } + }).is_ok() +} + +/// Returns true if and only if the given character is an ASCII word character. +/// +/// An ASCII word character is defined by the following character class: +/// `[_0-9a-zA-Z]'. +pub fn is_word_byte(c: u8) -> bool { + match c { + b'_' | b'0' ... b'9' | b'a' ... b'z' | b'A' ... b'Z' => true, + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn escape_meta() { + assert_eq!( + escape(r"\.+*?()|[]{}^$#&-~"), + r"\\\.\+\*\?\(\)\|\[\]\{\}\^\$\#\&\-\~".to_string(), + ); + } + + #[test] + fn word() { + assert!(is_word_byte(b'a')); + assert!(!is_word_byte(b'-')); + + assert!(is_word_character('a')); + assert!(is_word_character('β')); + assert!(!is_word_character('-')); + assert!(!is_word_character('☃')); + } +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/parser.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/parser.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/parser.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/parser.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,206 @@ +use ast; +use hir; + +use Result; + +/// A builder for a regular expression parser. +/// +/// This builder permits modifying configuration options for the parser. +/// +/// This type combines the builder options for both the +/// [AST `ParserBuilder`](ast/parse/struct.ParserBuilder.html) +/// and the +/// [HIR `TranslatorBuilder`](hir/translate/struct.TranslatorBuilder.html). +#[derive(Clone, Debug, Default)] +pub struct ParserBuilder { + ast: ast::parse::ParserBuilder, + hir: hir::translate::TranslatorBuilder, +} + +impl ParserBuilder { + /// Create a new parser builder with a default configuration. + pub fn new() -> ParserBuilder { + ParserBuilder::default() + } + + /// Build a parser from this configuration with the given pattern. + pub fn build(&self) -> Parser { + Parser { + ast: self.ast.build(), + hir: self.hir.build(), + } + } + + /// Set the nesting limit for this parser. + /// + /// The nesting limit controls how deep the abstract syntax tree is allowed + /// to be. If the AST exceeds the given limit (e.g., with too many nested + /// groups), then an error is returned by the parser. + /// + /// The purpose of this limit is to act as a heuristic to prevent stack + /// overflow for consumers that do structural induction on an `Ast` using + /// explicit recursion. While this crate never does this (instead using + /// constant stack space and moving the call stack to the heap), other + /// crates may. + /// + /// This limit is not checked until the entire Ast is parsed. Therefore, + /// if callers want to put a limit on the amount of heap space used, then + /// they should impose a limit on the length, in bytes, of the concrete + /// pattern string. In particular, this is viable since this parser + /// implementation will limit itself to heap space proportional to the + /// lenth of the pattern string. + /// + /// Note that a nest limit of `0` will return a nest limit error for most + /// patterns but not all. For example, a nest limit of `0` permits `a` but + /// not `ab`, since `ab` requires a concatenation, which results in a nest + /// depth of `1`. In general, a nest limit is not something that manifests + /// in an obvious way in the concrete syntax, therefore, it should not be + /// used in a granular way. + pub fn nest_limit(&mut self, limit: u32) -> &mut ParserBuilder { + self.ast.nest_limit(limit); + self + } + + /// Whether to support octal syntax or not. + /// + /// Octal syntax is a little-known way of uttering Unicode codepoints in + /// a regular expression. For example, `a`, `\x61`, `\u0061` and + /// `\141` are all equivalent regular expressions, where the last example + /// shows octal syntax. + /// + /// While supporting octal syntax isn't in and of itself a problem, it does + /// make good error messages harder. That is, in PCRE based regex engines, + /// syntax like `\0` invokes a backreference, which is explicitly + /// unsupported in Rust's regex engine. However, many users expect it to + /// be supported. Therefore, when octal support is disabled, the error + /// message will explicitly mention that backreferences aren't supported. + /// + /// Octal syntax is disabled by default. + pub fn octal(&mut self, yes: bool) -> &mut ParserBuilder { + self.ast.octal(yes); + self + } + + /// When enabled, the parser will permit the construction of a regular + /// expression that may match invalid UTF-8. + /// + /// When disabled (the default), the parser is guaranteed to produce + /// an expression that will only ever match valid UTF-8 (otherwise, the + /// parser will return an error). + /// + /// Note that currently, even when invalid UTF-8 is banned, the parser + /// will permit a negated ASCII word boundary (i.e., `(?-u:\B)`) even + /// though it can actually match at invalid UTF-8 boundaries. This bug + /// will be fixed on the next semver release. + pub fn allow_invalid_utf8(&mut self, yes: bool) -> &mut ParserBuilder { + self.hir.allow_invalid_utf8(yes); + self + } + + /// Enable verbose mode in the regular expression. + /// + /// When enabled, verbose mode permits insigificant whitespace in many + /// places in the regular expression, as well as comments. Comments are + /// started using `#` and continue until the end of the line. + /// + /// By default, this is disabled. It may be selectively enabled in the + /// regular expression by using the `x` flag regardless of this setting. + pub fn ignore_whitespace(&mut self, yes: bool) -> &mut ParserBuilder { + self.ast.ignore_whitespace(yes); + self + } + + /// Enable or disable the case insensitive flag by default. + /// + /// By default this is disabled. It may alternatively be selectively + /// enabled in the regular expression itself via the `i` flag. + pub fn case_insensitive(&mut self, yes: bool) -> &mut ParserBuilder { + self.hir.case_insensitive(yes); + self + } + + /// Enable or disable the multi-line matching flag by default. + /// + /// By default this is disabled. It may alternatively be selectively + /// enabled in the regular expression itself via the `m` flag. + pub fn multi_line(&mut self, yes: bool) -> &mut ParserBuilder { + self.hir.multi_line(yes); + self + } + + /// Enable or disable the "dot matches any character" flag by default. + /// + /// By default this is disabled. It may alternatively be selectively + /// enabled in the regular expression itself via the `s` flag. + pub fn dot_matches_new_line( + &mut self, + yes: bool, + ) -> &mut ParserBuilder { + self.hir.dot_matches_new_line(yes); + self + } + + /// Enable or disable the "swap greed" flag by default. + /// + /// By default this is disabled. It may alternatively be selectively + /// enabled in the regular expression itself via the `U` flag. + pub fn swap_greed(&mut self, yes: bool) -> &mut ParserBuilder { + self.hir.swap_greed(yes); + self + } + + /// Enable or disable the Unicode flag (`u`) by default. + /// + /// By default this is **enabled**. It may alternatively be selectively + /// disabled in the regular expression itself via the `u` flag. + /// + /// Note that unless `allow_invalid_utf8` is enabled (it's disabled by + /// default), a regular expression will fail to parse if Unicode mode is + /// disabled and a sub-expression could possibly match invalid UTF-8. + pub fn unicode(&mut self, yes: bool) -> &mut ParserBuilder { + self.hir.unicode(yes); + self + } +} + +/// A convenience parser for regular expressions. +/// +/// This parser takes as input a regular expression pattern string (the +/// "concrete syntax") and returns a high-level intermediate representation +/// (the HIR) suitable for most types of analysis. In particular, this parser +/// hides the intermediate state of producing an AST (the "abstract syntax"). +/// The AST is itself far more complex than the HIR, so this parser serves as a +/// convenience for never having to deal with it at all. +/// +/// If callers have more fine grained use cases that need an AST, then please +/// see the [`ast::parse`](ast/parse/index.html) module. +/// +/// A `Parser` can be configured in more detail via a +/// [`ParserBuilder`](struct.ParserBuilder.html). +#[derive(Clone, Debug)] +pub struct Parser { + ast: ast::parse::Parser, + hir: hir::translate::Translator, +} + +impl Parser { + /// Create a new parser with a default configuration. + /// + /// The parser can be run with `parse` method. The parse method returns + /// a high level intermediate representation of the given regular + /// expression. + /// + /// To set configuration options on the parser, use + /// [`ParserBuilder`](struct.ParserBuilder.html). + pub fn new() -> Parser { + ParserBuilder::new().build() + } + + /// Parse the regular expression into a high level intermediate + /// representation. + pub fn parse(&mut self, pattern: &str) -> Result<hir::Hir> { + let ast = try!(self.ast.parse(pattern)); + let hir = try!(self.hir.translate(pattern, &ast)); + Ok(hir) + } +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,462 @@ +use std::cmp::Ordering; +use std::result; + +use ucd_util::{self, PropertyValues}; + +use hir; +use unicode_tables::age; +use unicode_tables::case_folding_simple::CASE_FOLDING_SIMPLE; +use unicode_tables::general_category; +use unicode_tables::property_bool; +use unicode_tables::property_names::PROPERTY_NAMES; +use unicode_tables::property_values::PROPERTY_VALUES; +use unicode_tables::script; +use unicode_tables::script_extension; + +type Result<T> = result::Result<T, Error>; + +/// An error that occurs when dealing with Unicode. +/// +/// We don't impl the Error trait here because these always get converted +/// into other public errors. (This error type isn't exported.) +#[derive(Debug)] +pub enum Error { + PropertyNotFound, + PropertyValueNotFound, +} + +/// Encode the given Unicode character to `dst` as a single UTF-8 sequence. +/// +/// If `dst` is not long enough, then `None` is returned. Otherwise, the number +/// of bytes written is returned. +pub fn encode_utf8(character: char, dst: &mut [u8]) -> Option<usize> { + // TODO: Remove this function once we move to at least Rust 1.15, which + // provides char::encode_utf8 for us. + const TAG_CONT: u8 = 0b1000_0000; + const TAG_TWO: u8 = 0b1100_0000; + const TAG_THREE: u8 = 0b1110_0000; + const TAG_FOUR: u8 = 0b1111_0000; + + let code = character as u32; + if code <= 0x7F && !dst.is_empty() { + dst[0] = code as u8; + Some(1) + } else if code <= 0x7FF && dst.len() >= 2 { + dst[0] = (code >> 6 & 0x1F) as u8 | TAG_TWO; + dst[1] = (code & 0x3F) as u8 | TAG_CONT; + Some(2) + } else if code <= 0xFFFF && dst.len() >= 3 { + dst[0] = (code >> 12 & 0x0F) as u8 | TAG_THREE; + dst[1] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + dst[2] = (code & 0x3F) as u8 | TAG_CONT; + Some(3) + } else if dst.len() >= 4 { + dst[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR; + dst[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; + dst[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + dst[3] = (code & 0x3F) as u8 | TAG_CONT; + Some(4) + } else { + None + } +} + +/// An iterator over a codepoint's simple case equivalence class. +#[derive(Debug)] +pub struct SimpleFoldIter(::std::slice::Iter<'static, char>); + +impl Iterator for SimpleFoldIter { + type Item = char; + + fn next(&mut self) -> Option<char> { + self.0.next().map(|c| *c) + } +} + +/// Return an iterator over the equivalence class of simple case mappings +/// for the given codepoint. The equivalence class does not include the +/// given codepoint. +/// +/// If the equivalence class is empty, then this returns the next scalar +/// value that has a non-empty equivalence class, if it exists. If no such +/// scalar value exists, then `None` is returned. The point of this behavior +/// is to permit callers to avoid calling `simple_fold` more than they need +/// to, since there is some cost to fetching the equivalence class. +pub fn simple_fold(c: char) -> result::Result<SimpleFoldIter, Option<char>> { + CASE_FOLDING_SIMPLE + .binary_search_by_key(&c, |&(c1, _)| c1) + .map(|i| SimpleFoldIter(CASE_FOLDING_SIMPLE[i].1.iter())) + .map_err(|i| { + if i >= CASE_FOLDING_SIMPLE.len() { + None + } else { + Some(CASE_FOLDING_SIMPLE[i].0) + } + }) +} + +/// Returns true if and only if the given (inclusive) range contains at least +/// one Unicode scalar value that has a non-empty non-trivial simple case +/// mapping. +/// +/// This function panics if `end < start`. +pub fn contains_simple_case_mapping(start: char, end: char) -> bool { + assert!(start <= end); + CASE_FOLDING_SIMPLE + .binary_search_by(|&(c, _)| { + if start <= c && c <= end { + Ordering::Equal + } else if c > end { + Ordering::Greater + } else { + Ordering::Less + } + }).is_ok() +} + +/// A query for finding a character class defined by Unicode. This supports +/// either use of a property name directly, or lookup by property value. The +/// former generally refers to Binary properties (see UTS#44, Table 8), but +/// as a special exception (see UTS#18, Section 1.2) both general categories +/// (an enumeration) and scripts (a catalog) are supported as if each of their +/// possible values were a binary property. +/// +/// In all circumstances, property names and values are normalized and +/// canonicalized. That is, `GC == gc == GeneralCategory == general_category`. +/// +/// The lifetime `'a` refers to the shorter of the lifetimes of property name +/// and property value. +#[derive(Debug)] +pub enum ClassQuery<'a> { + /// Return a class corresponding to a Unicode binary property, named by + /// a single letter. + OneLetter(char), + /// Return a class corresponding to a Unicode binary property. + /// + /// Note that, by special exception (see UTS#18, Section 1.2), both + /// general category values and script values are permitted here as if + /// they were a binary property. + Binary(&'a str), + /// Return a class corresponding to all codepoints whose property + /// (identified by `property_name`) corresponds to the given value + /// (identified by `property_value`). + ByValue { + /// A property name. + property_name: &'a str, + /// A property value. + property_value: &'a str, + }, +} + +impl<'a> ClassQuery<'a> { + fn canonicalize(&self) -> Result<CanonicalClassQuery> { + match *self { + ClassQuery::OneLetter(c) => self.canonical_binary(&c.to_string()), + ClassQuery::Binary(name) => self.canonical_binary(name), + ClassQuery::ByValue { property_name, property_value } => { + let property_name = normalize(property_name); + let property_value = normalize(property_value); + + let canon_name = match canonical_prop(&property_name) { + None => return Err(Error::PropertyNotFound), + Some(canon_name) => canon_name, + }; + Ok(match canon_name { + "General_Category" => { + let canon = match canonical_gencat(&property_value) { + None => return Err(Error::PropertyValueNotFound), + Some(canon) => canon, + }; + CanonicalClassQuery::GeneralCategory(canon) + } + "Script" => { + let canon = match canonical_script(&property_value) { + None => return Err(Error::PropertyValueNotFound), + Some(canon) => canon, + }; + CanonicalClassQuery::Script(canon) + } + _ => { + let vals = match property_values(canon_name) { + None => return Err(Error::PropertyValueNotFound), + Some(vals) => vals, + }; + let canon_val = match canonical_value( + vals, + &property_value, + ) { + None => return Err(Error::PropertyValueNotFound), + Some(canon_val) => canon_val, + }; + CanonicalClassQuery::ByValue { + property_name: canon_name, + property_value: canon_val, + } + } + }) + } + } + } + + fn canonical_binary(&self, name: &str) -> Result<CanonicalClassQuery> { + let norm = normalize(name); + + if let Some(canon) = canonical_prop(&norm) { + return Ok(CanonicalClassQuery::Binary(canon)); + } + if let Some(canon) = canonical_gencat(&norm) { + return Ok(CanonicalClassQuery::GeneralCategory(canon)); + } + if let Some(canon) = canonical_script(&norm) { + return Ok(CanonicalClassQuery::Script(canon)); + } + Err(Error::PropertyNotFound) + } +} + +/// Like ClassQuery, but its parameters have been canonicalized. This also +/// differentiates binary properties from flattened general categories and +/// scripts. +#[derive(Debug)] +enum CanonicalClassQuery { + /// The canonical binary property name. + Binary(&'static str), + /// The canonical general category name. + GeneralCategory(&'static str), + /// The canonical script name. + Script(&'static str), + /// An arbitrary association between property and value, both of which + /// have been canonicalized. + /// + /// Note that by construction, the property name of ByValue will never + /// be General_Category or Script. Those two cases are subsumed by the + /// eponymous variants. + ByValue { + /// The canonical property name. + property_name: &'static str, + /// The canonical property value. + property_value: &'static str, + }, +} + +/// Looks up a Unicode class given a query. If one doesn't exist, then +/// `None` is returned. +pub fn class<'a>(query: ClassQuery<'a>) -> Result<hir::ClassUnicode> { + use self::CanonicalClassQuery::*; + + match try!(query.canonicalize()) { + Binary(name) => { + property_set(property_bool::BY_NAME, name) + .map(hir_class) + .ok_or(Error::PropertyNotFound) + } + GeneralCategory("Any") => { + Ok(hir_class(&[('\0', '\u{10FFFF}')])) + } + GeneralCategory("Assigned") => { + let mut cls = + try!(property_set(general_category::BY_NAME, "Unassigned") + .map(hir_class) + .ok_or(Error::PropertyNotFound)); + cls.negate(); + Ok(cls) + } + GeneralCategory("ASCII") => { + Ok(hir_class(&[('\0', '\x7F')])) + } + GeneralCategory(name) => { + property_set(general_category::BY_NAME, name) + .map(hir_class) + .ok_or(Error::PropertyValueNotFound) + } + Script(name) => { + property_set(script::BY_NAME, name) + .map(hir_class) + .ok_or(Error::PropertyValueNotFound) + } + ByValue { property_name: "Age", property_value } => { + let mut class = hir::ClassUnicode::empty(); + for set in try!(ages(property_value)) { + class.union(&hir_class(set)); + } + Ok(class) + } + ByValue { property_name: "Script_Extensions", property_value } => { + property_set(script_extension::BY_NAME, property_value) + .map(hir_class) + .ok_or(Error::PropertyValueNotFound) + } + _ => { + // What else should we support? + Err(Error::PropertyNotFound) + } + } +} + +/// Build a Unicode HIR class from a sequence of Unicode scalar value ranges. +pub fn hir_class(ranges: &[(char, char)]) -> hir::ClassUnicode { + let hir_ranges: Vec<hir::ClassUnicodeRange> = ranges + .iter() + .map(|&(s, e)| hir::ClassUnicodeRange::new(s, e)) + .collect(); + hir::ClassUnicode::new(hir_ranges) +} + +fn canonical_prop(normalized_name: &str) -> Option<&'static str> { + ucd_util::canonical_property_name(PROPERTY_NAMES, normalized_name) +} + +fn canonical_gencat(normalized_value: &str) -> Option<&'static str> { + match normalized_value { + "any" => Some("Any"), + "assigned" => Some("Assigned"), + "ascii" => Some("ASCII"), + _ => { + let gencats = property_values("General_Category").unwrap(); + canonical_value(gencats, normalized_value) + } + } +} + +fn canonical_script(normalized_value: &str) -> Option<&'static str> { + let scripts = property_values("Script").unwrap(); + canonical_value(scripts, normalized_value) +} + +fn canonical_value( + vals: PropertyValues, + normalized_value: &str, +) -> Option<&'static str> { + ucd_util::canonical_property_value(vals, normalized_value) +} + +fn normalize(x: &str) -> String { + let mut x = x.to_string(); + ucd_util::symbolic_name_normalize(&mut x); + x +} + +fn property_values( + canonical_property_name: &'static str, +) -> Option<PropertyValues> +{ + ucd_util::property_values(PROPERTY_VALUES, canonical_property_name) +} + +fn property_set( + name_map: &'static [(&'static str, &'static [(char, char)])], + canonical: &'static str, +) -> Option<&'static [(char, char)]> { + name_map + .binary_search_by_key(&canonical, |x| x.0) + .ok() + .map(|i| name_map[i].1) +} + +/// An iterator over Unicode Age sets. Each item corresponds to a set of +/// codepoints that were added in a particular revision of Unicode. The +/// iterator yields items in chronological order. +#[derive(Debug)] +struct AgeIter { + ages: &'static [(&'static str, &'static [(char, char)])], +} + +fn ages(canonical_age: &str) -> Result<AgeIter> { + const AGES: &'static [(&'static str, &'static [(char, char)])] = &[ + ("V1_1", age::V1_1), + ("V2_0", age::V2_0), + ("V2_1", age::V2_1), + ("V3_0", age::V3_0), + ("V3_1", age::V3_1), + ("V3_2", age::V3_2), + ("V4_0", age::V4_0), + ("V4_1", age::V4_1), + ("V5_0", age::V5_0), + ("V5_1", age::V5_1), + ("V5_2", age::V5_2), + ("V6_0", age::V6_0), + ("V6_1", age::V6_1), + ("V6_2", age::V6_2), + ("V6_3", age::V6_3), + ("V7_0", age::V7_0), + ("V8_0", age::V8_0), + ("V9_0", age::V9_0), + ("V10_0", age::V10_0), + ]; + assert_eq!(AGES.len(), age::BY_NAME.len(), "ages are out of sync"); + + let pos = AGES.iter().position(|&(age, _)| canonical_age == age); + match pos { + None => Err(Error::PropertyValueNotFound), + Some(i) => Ok(AgeIter { ages: &AGES[..i+1] }), + } +} + +impl Iterator for AgeIter { + type Item = &'static [(char, char)]; + + fn next(&mut self) -> Option<&'static [(char, char)]> { + if self.ages.is_empty() { + None + } else { + let set = self.ages[0]; + self.ages = &self.ages[1..]; + Some(set.1) + } + } +} + +#[cfg(test)] +mod tests { + use super::{contains_simple_case_mapping, simple_fold}; + + #[test] + fn simple_fold_k() { + let xs: Vec<char> = simple_fold('k').unwrap().collect(); + assert_eq!(xs, vec!['K', 'K']); + + let xs: Vec<char> = simple_fold('K').unwrap().collect(); + assert_eq!(xs, vec!['k', 'K']); + + let xs: Vec<char> = simple_fold('K').unwrap().collect(); + assert_eq!(xs, vec!['K', 'k']); + } + + #[test] + fn simple_fold_a() { + let xs: Vec<char> = simple_fold('a').unwrap().collect(); + assert_eq!(xs, vec!['A']); + + let xs: Vec<char> = simple_fold('A').unwrap().collect(); + assert_eq!(xs, vec!['a']); + } + + #[test] + fn simple_fold_empty() { + assert_eq!(Some('A'), simple_fold('?').unwrap_err()); + assert_eq!(Some('A'), simple_fold('@').unwrap_err()); + assert_eq!(Some('a'), simple_fold('[').unwrap_err()); + assert_eq!(Some('Ⰰ'), simple_fold('☃').unwrap_err()); + } + + #[test] + fn simple_fold_max() { + assert_eq!(None, simple_fold('\u{10FFFE}').unwrap_err()); + assert_eq!(None, simple_fold('\u{10FFFF}').unwrap_err()); + } + + #[test] + fn range_contains() { + assert!(contains_simple_case_mapping('A', 'A')); + assert!(contains_simple_case_mapping('Z', 'Z')); + assert!(contains_simple_case_mapping('A', 'Z')); + assert!(contains_simple_case_mapping('@', 'A')); + assert!(contains_simple_case_mapping('Z', '[')); + assert!(contains_simple_case_mapping('☃', 'Ⰰ')); + + assert!(!contains_simple_case_mapping('[', '[')); + assert!(!contains_simple_case_mapping('[', '`')); + + assert!(!contains_simple_case_mapping('☃', '☃')); + } +} diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/age.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/age.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/age.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/age.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,424 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate age tmp/ucd-10.0.0/ --chars +// +// ucd-generate is available on crates.io. + +pub const BY_NAME: &'static [(&'static str, &'static [(char, char)])] = &[ + ("V10_0", V10_0), ("V1_1", V1_1), ("V2_0", V2_0), ("V2_1", V2_1), + ("V3_0", V3_0), ("V3_1", V3_1), ("V3_2", V3_2), ("V4_0", V4_0), + ("V4_1", V4_1), ("V5_0", V5_0), ("V5_1", V5_1), ("V5_2", V5_2), + ("V6_0", V6_0), ("V6_1", V6_1), ("V6_2", V6_2), ("V6_3", V6_3), + ("V7_0", V7_0), ("V8_0", V8_0), ("V9_0", V9_0), +]; + +pub const V10_0: &'static [(char, char)] = &[ + ('ࡠ', 'ࡪ'), ('ৼ', '৽'), ('ૺ', '૿'), ('ഀ', 'ഀ'), + ('഻', '഼'), ('᳷', '᳷'), ('᷶', '᷹'), ('₿', '₿'), + ('⏿', '⏿'), ('⯒', '⯒'), ('⹅', '⹉'), ('ㄮ', 'ㄮ'), + ('鿖', '鿪'), ('𐌭', '𐌯'), ('𑨀', '𑩇'), ('𑩐', '𑪃'), + ('𑪆', '𑪜'), ('𑪞', '𑪢'), ('𑴀', '𑴆'), ('𑴈', '𑴉'), + ('𑴋', '𑴶'), ('𑴺', '𑴺'), ('𑴼', '𑴽'), ('𑴿', '𑵇'), + ('𑵐', '𑵙'), ('𖿡', '𖿡'), ('𛀂', '𛄞'), ('𛅰', '𛋻'), + ('🉠', '🉥'), ('🛓', '🛔'), ('🛷', '🛸'), ('🤀', '🤋'), + ('🤟', '🤟'), ('🤨', '🤯'), ('🤱', '🤲'), ('🥌', '🥌'), + ('🥟', '🥫'), ('🦒', '🦗'), ('🧐', '🧦'), ('𬺰', '𮯠'), +]; + +pub const V1_1: &'static [(char, char)] = &[ + ('\u{0}', 'ǵ'), ('Ǻ', 'ȗ'), ('ɐ', 'ʨ'), ('ʰ', '˞'), ('ˠ', '˩'), + ('̀', 'ͅ'), ('͠', '͡'), ('ʹ', '͵'), ('ͺ', 'ͺ'), (';', ';'), + ('΄', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), ('Σ', 'ώ'), ('ϐ', 'ϖ'), + ('Ϛ', 'Ϛ'), ('Ϝ', 'Ϝ'), ('Ϟ', 'Ϟ'), ('Ϡ', 'Ϡ'), ('Ϣ', 'ϳ'), + ('Ё', 'Ќ'), ('Ў', 'я'), ('ё', 'ќ'), ('ў', '҆'), ('Ґ', 'ӄ'), + ('Ӈ', 'ӈ'), ('Ӌ', 'ӌ'), ('Ӑ', 'ӫ'), ('Ӯ', 'ӵ'), ('Ӹ', 'ӹ'), + ('Ա', 'Ֆ'), ('ՙ', '՟'), ('ա', 'և'), ('։', '։'), ('ְ', 'ֹ'), + ('ֻ', '׃'), ('א', 'ת'), ('װ', '״'), ('،', '،'), ('؛', '؛'), + ('؟', '؟'), ('ء', 'غ'), ('ـ', 'ْ'), ('٠', '٭'), ('ٰ', 'ڷ'), + ('ں', 'ھ'), ('ۀ', 'ێ'), ('ې', 'ۭ'), ('۰', '۹'), ('ँ', 'ः'), + ('अ', 'ह'), ('़', '्'), ('ॐ', '॔'), ('क़', '॰'), + ('ঁ', 'ঃ'), ('অ', 'ঌ'), ('এ', 'ঐ'), ('ও', 'ন'), + ('প', 'র'), ('ল', 'ল'), ('শ', 'হ'), ('়', '়'), + ('া', 'ৄ'), ('ে', 'ৈ'), ('ো', '্'), ('ৗ', 'ৗ'), + ('ড়', 'ঢ়'), ('য়', 'ৣ'), ('০', '৺'), ('ਂ', 'ਂ'), + ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), + ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('਼', '਼'), + ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', '੍'), ('ਖ਼', 'ੜ'), + ('ਫ਼', 'ਫ਼'), ('੦', 'ੴ'), ('ઁ', 'ઃ'), ('અ', 'ઋ'), + ('ઍ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), ('પ', 'ર'), + ('લ', 'ળ'), ('વ', 'હ'), ('઼', 'ૅ'), ('ે', 'ૉ'), + ('ો', '્'), ('ૐ', 'ૐ'), ('ૠ', 'ૠ'), ('૦', '૯'), + ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), ('ଏ', 'ଐ'), ('ଓ', 'ନ'), + ('ପ', 'ର'), ('ଲ', 'ଳ'), ('ଶ', 'ହ'), ('଼', 'ୃ'), + ('େ', 'ୈ'), ('ୋ', '୍'), ('ୖ', 'ୗ'), ('ଡ଼', 'ଢ଼'), + ('ୟ', 'ୡ'), ('୦', '୰'), ('ஂ', 'ஃ'), ('அ', 'ஊ'), + ('எ', 'ஐ'), ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), + ('ஞ', 'ட'), ('ண', 'த'), ('ந', 'ப'), ('ம', 'வ'), + ('ஷ', 'ஹ'), ('ா', 'ூ'), ('ெ', 'ை'), ('ொ', '்'), + ('ௗ', 'ௗ'), ('௧', '௲'), ('ఁ', 'ః'), ('అ', 'ఌ'), + ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'ళ'), ('వ', 'హ'), + ('ా', 'ౄ'), ('ె', 'ై'), ('ొ', '్'), ('ౕ', 'ౖ'), + ('ౠ', 'ౡ'), ('౦', '౯'), ('ಂ', 'ಃ'), ('ಅ', 'ಌ'), + ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), + ('ಾ', 'ೄ'), ('ೆ', 'ೈ'), ('ೊ', '್'), ('ೕ', 'ೖ'), + ('ೞ', 'ೞ'), ('ೠ', 'ೡ'), ('೦', '೯'), ('ം', 'ഃ'), + ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ന'), ('പ', 'ഹ'), + ('ാ', 'ൃ'), ('െ', 'ൈ'), ('ൊ', '്'), ('ൗ', 'ൗ'), + ('ൠ', 'ൡ'), ('൦', '൯'), ('ก', 'ฺ'), ('฿', '๛'), + ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), + ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), + ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), + ('ົ', 'ຽ'), ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('່', 'ໍ'), + ('໐', '໙'), ('ໜ', 'ໝ'), ('Ⴀ', 'Ⴥ'), ('ა', 'ჶ'), + ('჻', '჻'), ('ᄀ', 'ᅙ'), ('ᅟ', 'ᆢ'), ('ᆨ', 'ᇹ'), + ('Ḁ', 'ẚ'), ('Ạ', 'ỹ'), ('ἀ', 'ἕ'), ('Ἐ', 'Ἕ'), + ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), + ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), + ('ᾶ', 'ῄ'), ('ῆ', 'ΐ'), ('ῖ', 'Ί'), ('῝', '`'), + ('ῲ', 'ῴ'), ('ῶ', '῾'), ('\u{2000}', '\u{202e}'), ('‰', '⁆'), + ('\u{206a}', '⁰'), ('⁴', '₎'), ('₠', '₪'), ('⃐', '⃡'), + ('℀', 'ℸ'), ('⅓', 'ↂ'), ('←', '⇪'), ('∀', '⋱'), + ('⌀', '⌀'), ('⌂', '⍺'), ('␀', '␤'), ('⑀', '⑊'), + ('①', '⓪'), ('─', '▕'), ('■', '◯'), ('☀', '☓'), + ('☚', '♯'), ('✁', '✄'), ('✆', '✉'), ('✌', '✧'), + ('✩', '❋'), ('❍', '❍'), ('❏', '❒'), ('❖', '❖'), + ('❘', '❞'), ('❡', '❧'), ('❶', '➔'), ('➘', '➯'), + ('➱', '➾'), ('\u{3000}', '〷'), ('〿', '〿'), ('ぁ', 'ゔ'), + ('゙', 'ゞ'), ('ァ', 'ヾ'), ('ㄅ', 'ㄬ'), ('ㄱ', 'ㆎ'), + ('㆐', '㆟'), ('㈀', '㈜'), ('㈠', '㉃'), ('㉠', '㉻'), + ('㉿', '㊰'), ('㋀', '㋋'), ('㋐', '㋾'), ('㌀', '㍶'), + ('㍻', '㏝'), ('㏠', '㏾'), ('一', '龥'), ('\u{e000}', '鶴'), + ('ff', 'st'), ('ﬓ', 'ﬗ'), ('ﬞ', 'זּ'), ('טּ', 'לּ'), + ('מּ', 'מּ'), ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﮱ'), + ('ﯓ', '﴿'), ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷻ'), + ('︠', '︣'), ('︰', '﹄'), ('﹉', '﹒'), ('﹔', '﹦'), + ('﹨', '﹫'), ('ﹰ', 'ﹲ'), ('ﹴ', 'ﹴ'), ('ﹶ', 'ﻼ'), + ('\u{feff}', '\u{feff}'), ('!', '~'), ('。', 'ᄒ'), ('ᅡ', 'ᅦ'), + ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), ('¢', '₩'), + ('│', '○'), ('�', '\u{ffff}'), +]; + +pub const V2_0: &'static [(char, char)] = &[ + ('֑', '֡'), ('֣', '֯'), ('ׄ', 'ׄ'), ('ༀ', 'ཇ'), ('ཉ', 'ཀྵ'), + ('ཱ', 'ྋ'), ('ྐ', 'ྕ'), ('ྗ', 'ྗ'), ('ྙ', 'ྭ'), + ('ྱ', 'ྷ'), ('ྐྵ', 'ྐྵ'), ('ẛ', 'ẛ'), ('₫', '₫'), + ('가', '힣'), ('\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{10ffff}'), +]; + +pub const V2_1: &'static [(char, char)] = &[ + ('€', '€'), ('', ''), +]; + +pub const V3_0: &'static [(char, char)] = &[ + ('Ƕ', 'ǹ'), ('Ș', 'ȟ'), ('Ȣ', 'ȳ'), ('ʩ', 'ʭ'), ('˟', '˟'), + ('˪', 'ˮ'), ('͆', '͎'), ('͢', '͢'), ('ϗ', 'ϗ'), ('ϛ', 'ϛ'), + ('ϝ', 'ϝ'), ('ϟ', 'ϟ'), ('ϡ', 'ϡ'), ('Ѐ', 'Ѐ'), ('Ѝ', 'Ѝ'), + ('ѐ', 'ѐ'), ('ѝ', 'ѝ'), ('҈', '҉'), ('Ҍ', 'ҏ'), ('Ӭ', 'ӭ'), + ('֊', '֊'), ('ٓ', 'ٕ'), ('ڸ', 'ڹ'), ('ڿ', 'ڿ'), ('ۏ', 'ۏ'), + ('ۺ', '۾'), ('܀', '܍'), ('\u{70f}', 'ܬ'), ('ܰ', '݊'), ('ހ', 'ް'), + ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('්', '්'), ('ා', 'ු'), + ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('ෲ', '෴'), ('ཪ', 'ཪ'), + ('ྖ', 'ྖ'), ('ྮ', 'ྰ'), ('ྸ', 'ྸ'), ('ྺ', 'ྼ'), + ('྾', '࿌'), ('࿏', '࿏'), ('က', 'အ'), ('ဣ', 'ဧ'), + ('ဩ', 'ဪ'), ('ာ', 'ဲ'), ('ံ', '္'), ('၀', 'ၙ'), + ('ሀ', 'ሆ'), ('ለ', 'ቆ'), ('ቈ', 'ቈ'), ('ቊ', 'ቍ'), + ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), ('በ', 'ኆ'), + ('ኈ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኮ'), ('ኰ', 'ኰ'), + ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), + ('ወ', 'ዎ'), ('ዐ', 'ዖ'), ('ዘ', 'ዮ'), ('ደ', 'ጎ'), + ('ጐ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ጞ'), ('ጠ', 'ፆ'), + ('ፈ', 'ፚ'), ('፡', '፼'), ('Ꭰ', 'Ᏼ'), ('ᐁ', 'ᙶ'), + ('\u{1680}', '᚜'), ('ᚠ', 'ᛰ'), ('ក', 'ៜ'), ('០', '៩'), + ('᠀', '\u{180e}'), ('᠐', '᠙'), ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢩ'), + ('\u{202f}', '\u{202f}'), ('⁈', '⁍'), ('₭', '₯'), ('⃢', '⃣'), + ('ℹ', '℺'), ('Ↄ', 'Ↄ'), ('⇫', '⇳'), ('⌁', '⌁'), + ('⍻', '⍻'), ('⍽', '⎚'), ('␥', '␦'), ('◰', '◷'), + ('☙', '☙'), ('♰', '♱'), ('⠀', '⣿'), ('⺀', '⺙'), + ('⺛', '⻳'), ('⼀', '⿕'), ('⿰', '⿻'), ('〸', '〺'), + ('〾', '〾'), ('ㆠ', 'ㆷ'), ('㐀', '䶵'), ('ꀀ', 'ꒌ'), + ('꒐', '꒡'), ('꒤', '꒳'), ('꒵', '꓀'), ('꓂', '꓄'), + ('꓆', '꓆'), ('יִ', 'יִ'), ('\u{fff9}', '\u{fffb}'), +]; + +pub const V3_1: &'static [(char, char)] = &[ + ('ϴ', 'ϵ'), ('\u{fdd0}', '\u{fdef}'), ('𐌀', '𐌞'), ('𐌠', '𐌣'), + ('𐌰', '𐍊'), ('𐐀', '𐐥'), ('𐐨', '𐑍'), ('𝀀', '𝃵'), + ('𝄀', '𝄦'), ('𝄪', '𝇝'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), + ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), + ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓀'), ('𝓂', '𝓃'), + ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), + ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), + ('𝕊', '𝕐'), ('𝕒', '𝚣'), ('𝚨', '𝟉'), ('𝟎', '𝟿'), + ('𠀀', '𪛖'), ('丽', '𪘀'), ('\u{e0001}', '\u{e0001}'), + ('\u{e0020}', '\u{e007f}'), +]; + +pub const V3_2: &'static [(char, char)] = &[ + ('Ƞ', 'Ƞ'), ('͏', '͏'), ('ͣ', 'ͯ'), ('Ϙ', 'ϙ'), ('϶', '϶'), + ('Ҋ', 'ҋ'), ('Ӆ', 'ӆ'), ('Ӊ', 'ӊ'), ('Ӎ', 'ӎ'), ('Ԁ', 'ԏ'), + ('ٮ', 'ٯ'), ('ޱ', 'ޱ'), ('ჷ', 'ჸ'), ('ᜀ', 'ᜌ'), ('ᜎ', '᜔'), + ('ᜠ', '᜶'), ('ᝀ', 'ᝓ'), ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), + ('ᝲ', 'ᝳ'), ('⁇', '⁇'), ('⁎', '⁒'), ('⁗', '⁗'), + ('\u{205f}', '\u{2063}'), ('ⁱ', 'ⁱ'), ('₰', '₱'), ('⃤', '⃪'), + ('ℽ', '⅋'), ('⇴', '⇿'), ('⋲', '⋿'), ('⍼', '⍼'), + ('⎛', '⏎'), ('⓫', '⓾'), ('▖', '▟'), ('◸', '◿'), + ('☖', '☗'), ('♲', '♽'), ('⚀', '⚉'), ('❨', '❵'), + ('⟐', '⟫'), ('⟰', '⟿'), ('⤀', '⫿'), ('〻', '〽'), + ('ゕ', 'ゖ'), ('ゟ', '゠'), ('ヿ', 'ヿ'), ('ㇰ', 'ㇿ'), + ('㉑', '㉟'), ('㊱', '㊿'), ('꒢', '꒣'), ('꒴', '꒴'), + ('꓁', '꓁'), ('꓅', '꓅'), ('侮', '頻'), ('﷼', '﷼'), + ('︀', '️'), ('﹅', '﹆'), ('ﹳ', 'ﹳ'), ('⦅', '⦆'), +]; + +pub const V4_0: &'static [(char, char)] = &[ + ('ȡ', 'ȡ'), ('ȴ', 'ȶ'), ('ʮ', 'ʯ'), ('˯', '˿'), ('͐', '͗'), + ('͝', '͟'), ('Ϸ', 'ϻ'), ('\u{600}', '\u{603}'), ('؍', 'ؕ'), + ('ٖ', '٘'), ('ۮ', 'ۯ'), ('ۿ', 'ۿ'), ('ܭ', 'ܯ'), ('ݍ', 'ݏ'), + ('ऄ', 'ऄ'), ('ঽ', 'ঽ'), ('ਁ', 'ਁ'), ('ਃ', 'ਃ'), + ('ઌ', 'ઌ'), ('ૡ', 'ૣ'), ('૱', '૱'), ('ଵ', 'ଵ'), + ('ୱ', 'ୱ'), ('௳', '௺'), ('಼', 'ಽ'), ('៝', '៝'), + ('៰', '៹'), ('ᤀ', 'ᤜ'), ('ᤠ', 'ᤫ'), ('ᤰ', '᤻'), + ('᥀', '᥀'), ('᥄', 'ᥭ'), ('ᥰ', 'ᥴ'), ('᧠', '᧿'), + ('ᴀ', 'ᵫ'), ('⁓', '⁔'), ('℻', '℻'), ('⏏', '⏐'), + ('⓿', '⓿'), ('☔', '☕'), ('⚊', '⚑'), ('⚠', '⚡'), + ('⬀', '⬍'), ('㈝', '㈞'), ('㉐', '㉐'), ('㉼', '㉽'), + ('㋌', '㋏'), ('㍷', '㍺'), ('㏞', '㏟'), ('㏿', '㏿'), + ('䷀', '䷿'), ('﷽', '﷽'), ('﹇', '﹈'), ('𐀀', '𐀋'), + ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), ('𐀿', '𐁍'), + ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐄀', '𐄂'), ('𐄇', '𐄳'), + ('𐄷', '𐄿'), ('𐎀', '𐎝'), ('𐎟', '𐎟'), ('𐐦', '𐐧'), + ('𐑎', '𐒝'), ('𐒠', '𐒩'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), + ('𐠊', '𐠵'), ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐠿'), + ('𝌀', '𝍖'), ('𝓁', '𝓁'), ('󠄀', '󠇯'), +]; + +pub const V4_1: &'static [(char, char)] = &[ + ('ȷ', 'Ɂ'), ('͘', '͜'), ('ϼ', 'Ͽ'), ('Ӷ', 'ӷ'), ('֢', '֢'), + ('ׅ', 'ׇ'), ('؋', '؋'), ('؞', '؞'), ('ٙ', 'ٞ'), ('ݐ', 'ݭ'), + ('ॽ', 'ॽ'), ('ৎ', 'ৎ'), ('ஶ', 'ஶ'), ('௦', '௦'), + ('࿐', '࿑'), ('ჹ', 'ჺ'), ('ჼ', 'ჼ'), ('ሇ', 'ሇ'), + ('ቇ', 'ቇ'), ('ኇ', 'ኇ'), ('ኯ', 'ኯ'), ('ዏ', 'ዏ'), + ('ዯ', 'ዯ'), ('ጏ', 'ጏ'), ('ጟ', 'ጟ'), ('ፇ', 'ፇ'), + ('፟', '፠'), ('ᎀ', '᎙'), ('ᦀ', 'ᦩ'), ('ᦰ', 'ᧉ'), + ('᧐', '᧙'), ('᧞', '᧟'), ('ᨀ', 'ᨛ'), ('᨞', '᨟'), + ('ᵬ', '᷃'), ('⁕', '⁖'), ('⁘', '⁞'), ('ₐ', 'ₔ'), + ('₲', '₵'), ('⃫', '⃫'), ('ℼ', 'ℼ'), ('⅌', '⅌'), + ('⏑', '⏛'), ('☘', '☘'), ('♾', '♿'), ('⚒', '⚜'), + ('⚢', '⚱'), ('⟀', '⟆'), ('⬎', '⬓'), ('Ⰰ', 'Ⱞ'), + ('ⰰ', 'ⱞ'), ('Ⲁ', '⳪'), ('⳹', 'ⴥ'), ('ⴰ', 'ⵥ'), + ('ⵯ', 'ⵯ'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), ('ⶨ', 'ⶮ'), + ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), ('ⷈ', 'ⷎ'), + ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('⸀', '⸗'), ('⸜', '⸝'), + ('㇀', '㇏'), ('㉾', '㉾'), ('龦', '龻'), ('꜀', '꜖'), + ('ꠀ', '꠫'), ('並', '龎'), ('︐', '︙'), ('𐅀', '𐆊'), + ('𐎠', '𐏃'), ('𐏈', '𐏕'), ('𐨀', '𐨃'), ('𐨅', '𐨆'), + ('𐨌', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), ('𐨸', '𐨺'), + ('𐨿', '𐩇'), ('𐩐', '𐩘'), ('𝈀', '𝉅'), ('𝚤', '𝚥'), +]; + +pub const V5_0: &'static [(char, char)] = &[ + ('ɂ', 'ɏ'), ('ͻ', 'ͽ'), ('ӏ', 'ӏ'), ('Ӻ', 'ӿ'), ('Ԑ', 'ԓ'), + ('ֺ', 'ֺ'), ('߀', 'ߺ'), ('ॻ', 'ॼ'), ('ॾ', 'ॿ'), ('ೢ', 'ೣ'), + ('ೱ', 'ೲ'), ('ᬀ', 'ᭋ'), ('᭐', '᭼'), ('᷄', '᷊'), + ('᷾', '᷿'), ('⃬', '⃯'), ('⅍', 'ⅎ'), ('ↄ', 'ↄ'), + ('⏜', '⏧'), ('⚲', '⚲'), ('⟇', '⟊'), ('⬔', '⬚'), + ('⬠', '⬣'), ('Ⱡ', 'ⱬ'), ('ⱴ', 'ⱷ'), ('ꜗ', 'ꜚ'), + ('꜠', '꜡'), ('ꡀ', '꡷'), ('𐤀', '𐤙'), ('𐤟', '𐤟'), + ('𒀀', '𒍮'), ('𒐀', '𒑢'), ('𒑰', '𒑳'), ('𝍠', '𝍱'), + ('𝟊', '𝟋'), +]; + +pub const V5_1: &'static [(char, char)] = &[ + ('Ͱ', 'ͳ'), ('Ͷ', 'ͷ'), ('Ϗ', 'Ϗ'), ('҇', '҇'), ('Ԕ', 'ԣ'), + ('؆', '؊'), ('ؖ', 'ؚ'), ('ػ', 'ؿ'), ('ݮ', 'ݿ'), ('ॱ', 'ॲ'), + ('ੑ', 'ੑ'), ('ੵ', 'ੵ'), ('ୄ', 'ୄ'), ('ୢ', 'ୣ'), + ('ௐ', 'ௐ'), ('ఽ', 'ఽ'), ('ౘ', 'ౙ'), ('ౢ', 'ౣ'), + ('౸', '౿'), ('ഽ', 'ഽ'), ('ൄ', 'ൄ'), ('ൢ', 'ൣ'), + ('൰', '൵'), ('൹', 'ൿ'), ('ཫ', 'ཬ'), ('࿎', '࿎'), + ('࿒', '࿔'), ('ဢ', 'ဢ'), ('ဨ', 'ဨ'), ('ါ', 'ါ'), + ('ဳ', 'ဵ'), ('်', 'ဿ'), ('ၚ', '႙'), ('႞', '႟'), + ('ᢪ', 'ᢪ'), ('ᮀ', '᮪'), ('ᮮ', '᮹'), ('ᰀ', '᰷'), + ('᰻', '᱉'), ('ᱍ', '᱿'), ('᷋', 'ᷦ'), ('ẜ', 'ẟ'), + ('Ỻ', 'ỿ'), ('\u{2064}', '\u{2064}'), ('⃰', '⃰'), ('⅏', '⅏'), + ('ↅ', 'ↈ'), ('⚝', '⚝'), ('⚳', '⚼'), ('⛀', '⛃'), + ('⟌', '⟌'), ('⟬', '⟯'), ('⬛', '⬟'), ('⬤', '⭌'), + ('⭐', '⭔'), ('Ɑ', 'Ɐ'), ('ⱱ', 'ⱳ'), ('ⱸ', 'ⱽ'), + ('ⷠ', 'ⷿ'), ('⸘', '⸛'), ('⸞', '⸰'), ('ㄭ', 'ㄭ'), + ('㇐', '㇣'), ('龼', '鿃'), ('ꔀ', 'ꘫ'), ('Ꙁ', 'ꙟ'), + ('Ꙣ', '꙳'), ('꙼', 'ꚗ'), ('ꜛ', 'ꜟ'), ('Ꜣ', 'ꞌ'), + ('ꟻ', 'ꟿ'), ('ꢀ', '꣄'), ('꣎', '꣙'), ('꤀', '꥓'), + ('꥟', '꥟'), ('ꨀ', 'ꨶ'), ('ꩀ', 'ꩍ'), ('꩐', '꩙'), + ('꩜', '꩟'), ('︤', '︦'), ('𐆐', '𐆛'), ('𐇐', '𐇽'), + ('𐊀', '𐊜'), ('𐊠', '𐋐'), ('𐤠', '𐤹'), ('𐤿', '𐤿'), + ('𝄩', '𝄩'), ('🀀', '🀫'), ('🀰', '🂓'), +]; + +pub const V5_2: &'static [(char, char)] = &[ + ('Ԥ', 'ԥ'), ('ࠀ', '࠭'), ('࠰', '࠾'), ('ऀ', 'ऀ'), + ('ॎ', 'ॎ'), ('ॕ', 'ॕ'), ('ॹ', 'ॺ'), ('৻', '৻'), + ('࿕', '࿘'), ('ႚ', 'ႝ'), ('ᅚ', 'ᅞ'), ('ᆣ', 'ᆧ'), + ('ᇺ', 'ᇿ'), ('᐀', '᐀'), ('ᙷ', 'ᙿ'), ('ᢰ', 'ᣵ'), + ('ᦪ', 'ᦫ'), ('᧚', '᧚'), ('ᨠ', 'ᩞ'), ('᩠', '᩼'), + ('᩿', '᪉'), ('᪐', '᪙'), ('᪠', '᪭'), ('᳐', 'ᳲ'), + ('᷽', '᷽'), ('₶', '₸'), ('⅐', '⅒'), ('↉', '↉'), + ('⏨', '⏨'), ('⚞', '⚟'), ('⚽', '⚿'), ('⛄', '⛍'), + ('⛏', '⛡'), ('⛣', '⛣'), ('⛨', '⛿'), ('❗', '❗'), + ('⭕', '⭙'), ('Ɒ', 'Ɒ'), ('Ȿ', 'Ɀ'), ('Ⳬ', '⳱'), + ('⸱', '⸱'), ('㉄', '㉏'), ('鿄', '鿋'), ('ꓐ', '꓿'), + ('ꚠ', '꛷'), ('꠰', '꠹'), ('꣠', 'ꣻ'), ('ꥠ', 'ꥼ'), + ('ꦀ', '꧍'), ('ꧏ', '꧙'), ('꧞', '꧟'), ('ꩠ', 'ꩻ'), + ('ꪀ', 'ꫂ'), ('ꫛ', '꫟'), ('ꯀ', '꯭'), ('꯰', '꯹'), + ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('恵', '舘'), ('𐡀', '𐡕'), + ('𐡗', '𐡟'), ('𐤚', '𐤛'), ('𐩠', '𐩿'), ('𐬀', '𐬵'), + ('𐬹', '𐭕'), ('𐭘', '𐭲'), ('𐭸', '𐭿'), ('𐰀', '𐱈'), + ('𐹠', '𐹾'), ('𑂀', '𑃁'), ('𓀀', '𓐮'), ('🄀', '🄊'), + ('🄐', '🄮'), ('🄱', '🄱'), ('🄽', '🄽'), ('🄿', '🄿'), + ('🅂', '🅂'), ('🅆', '🅆'), ('🅊', '🅎'), ('🅗', '🅗'), + ('🅟', '🅟'), ('🅹', '🅹'), ('🅻', '🅼'), ('🅿', '🅿'), + ('🆊', '🆍'), ('🆐', '🆐'), ('🈀', '🈀'), ('🈐', '🈱'), + ('🉀', '🉈'), ('𪜀', '𫜴'), +]; + +pub const V6_0: &'static [(char, char)] = &[ + ('Ԧ', 'ԧ'), ('ؠ', 'ؠ'), ('ٟ', 'ٟ'), ('ࡀ', '࡛'), ('࡞', '࡞'), + ('ऺ', 'ऻ'), ('ॏ', 'ॏ'), ('ॖ', 'ॗ'), ('ॳ', 'ॷ'), + ('୲', '୷'), ('ഩ', 'ഩ'), ('ഺ', 'ഺ'), ('ൎ', 'ൎ'), + ('ྌ', 'ྏ'), ('࿙', '࿚'), ('፝', '፞'), ('ᯀ', '᯳'), + ('᯼', '᯿'), ('᷼', '᷼'), ('ₕ', 'ₜ'), ('₹', '₹'), + ('⏩', '⏳'), ('⛎', '⛎'), ('⛢', '⛢'), ('⛤', '⛧'), + ('✅', '✅'), ('✊', '✋'), ('✨', '✨'), ('❌', '❌'), + ('❎', '❎'), ('❓', '❕'), ('❟', '❠'), ('➕', '➗'), + ('➰', '➰'), ('➿', '➿'), ('⟎', '⟏'), ('⵰', '⵰'), + ('⵿', '⵿'), ('ㆸ', 'ㆺ'), ('Ꙡ', 'ꙡ'), ('Ɥ', 'ꞎ'), + ('Ꞑ', 'ꞑ'), ('Ꞡ', 'ꞩ'), ('ꟺ', 'ꟺ'), ('ꬁ', 'ꬆ'), + ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), + ('﮲', '﯁'), ('𑀀', '𑁍'), ('𑁒', '𑁯'), ('𖠀', '𖨸'), + ('𛀀', '𛀁'), ('🂠', '🂮'), ('🂱', '🂾'), ('🃁', '🃏'), + ('🃑', '🃟'), ('🄰', '🄰'), ('🄲', '🄼'), ('🄾', '🄾'), + ('🅀', '🅁'), ('🅃', '🅅'), ('🅇', '🅉'), ('🅏', '🅖'), + ('🅘', '🅞'), ('🅠', '🅩'), ('🅰', '🅸'), ('🅺', '🅺'), + ('🅽', '🅾'), ('🆀', '🆉'), ('🆎', '🆏'), ('🆑', '🆚'), + ('🇦', '🇿'), ('🈁', '🈂'), ('🈲', '🈺'), ('🉐', '🉑'), + ('🌀', '🌠'), ('🌰', '🌵'), ('🌷', '🍼'), ('🎀', '🎓'), + ('🎠', '🏄'), ('🏆', '🏊'), ('🏠', '🏰'), ('🐀', '🐾'), + ('👀', '👀'), ('👂', '📷'), ('📹', '📼'), ('🔀', '🔽'), + ('🕐', '🕧'), ('🗻', '🗿'), ('😁', '😐'), ('😒', '😔'), + ('😖', '😖'), ('😘', '😘'), ('😚', '😚'), ('😜', '😞'), + ('😠', '😥'), ('😨', '😫'), ('😭', '😭'), ('😰', '😳'), + ('😵', '🙀'), ('🙅', '🙏'), ('🚀', '🛅'), ('🜀', '🝳'), + ('𫝀', '𫠝'), +]; + +pub const V6_1: &'static [(char, char)] = &[ + ('֏', '֏'), ('\u{604}', '\u{604}'), ('ࢠ', 'ࢠ'), ('ࢢ', 'ࢬ'), + ('ࣤ', 'ࣾ'), ('૰', '૰'), ('ໞ', 'ໟ'), ('Ⴧ', 'Ⴧ'), + ('Ⴭ', 'Ⴭ'), ('ჽ', 'ჿ'), ('᮫', 'ᮭ'), ('ᮺ', 'ᮿ'), + ('᳀', '᳇'), ('ᳳ', 'ᳶ'), ('⟋', '⟋'), ('⟍', '⟍'), + ('Ⳳ', 'ⳳ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ⵦ', 'ⵧ'), + ('⸲', '⸻'), ('鿌', '鿌'), ('ꙴ', 'ꙻ'), ('ꚟ', 'ꚟ'), + ('Ꞓ', 'ꞓ'), ('Ɦ', 'Ɦ'), ('ꟸ', 'ꟹ'), ('ꫠ', '꫶'), + ('郞', '隷'), ('𐦀', '𐦷'), ('𐦾', '𐦿'), ('𑃐', '𑃨'), + ('𑃰', '𑃹'), ('𑄀', '𑄴'), ('𑄶', '𑅃'), ('𑆀', '𑇈'), + ('𑇐', '𑇙'), ('𑚀', '𑚷'), ('𑛀', '𑛉'), ('𖼀', '𖽄'), + ('𖽐', '𖽾'), ('𖾏', '𖾟'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), + ('𞸡', '𞸢'), ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), + ('𞸴', '𞸷'), ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), + ('𞹇', '𞹇'), ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), + ('𞹑', '𞹒'), ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), + ('𞹛', '𞹛'), ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), + ('𞹤', '𞹤'), ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), + ('𞹹', '𞹼'), ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), + ('𞺡', '𞺣'), ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𞻰', '𞻱'), + ('🅪', '🅫'), ('🕀', '🕃'), ('😀', '😀'), ('😑', '😑'), + ('😕', '😕'), ('😗', '😗'), ('😙', '😙'), ('😛', '😛'), + ('😟', '😟'), ('😦', '😧'), ('😬', '😬'), ('😮', '😯'), + ('😴', '😴'), +]; + +pub const V6_2: &'static [(char, char)] = &[ + ('₺', '₺'), +]; + +pub const V6_3: &'static [(char, char)] = &[ + ('\u{61c}', '\u{61c}'), ('\u{2066}', '\u{2069}'), +]; + +pub const V7_0: &'static [(char, char)] = &[ + ('Ϳ', 'Ϳ'), ('Ԩ', 'ԯ'), ('֍', '֎'), ('\u{605}', '\u{605}'), + ('ࢡ', 'ࢡ'), ('ࢭ', 'ࢲ'), ('ࣿ', 'ࣿ'), ('ॸ', 'ॸ'), + ('ঀ', 'ঀ'), ('ఀ', 'ఀ'), ('ఴ', 'ఴ'), ('ಁ', 'ಁ'), + ('ഁ', 'ഁ'), ('෦', '෯'), ('ᛱ', 'ᛸ'), ('ᤝ', 'ᤞ'), + ('᪰', '᪾'), ('᳸', '᳹'), ('ᷧ', '᷵'), ('₻', '₽'), + ('⏴', '⏺'), ('✀', '✀'), ('⭍', '⭏'), ('⭚', '⭳'), + ('⭶', '⮕'), ('⮘', '⮹'), ('⮽', '⯈'), ('⯊', '⯑'), + ('⸼', '⹂'), ('Ꚙ', 'ꚝ'), ('ꞔ', 'ꞟ'), ('Ɜ', 'Ɬ'), + ('Ʞ', 'Ʇ'), ('ꟷ', 'ꟷ'), ('ꧠ', 'ꧾ'), ('ꩼ', 'ꩿ'), + ('ꬰ', 'ꭟ'), ('ꭤ', 'ꭥ'), ('︧', '︭'), ('𐆋', '𐆌'), + ('𐆠', '𐆠'), ('𐋠', '𐋻'), ('𐌟', '𐌟'), ('𐍐', '𐍺'), + ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐕯', '𐕯'), ('𐘀', '𐜶'), + ('𐝀', '𐝕'), ('𐝠', '𐝧'), ('𐡠', '𐢞'), ('𐢧', '𐢯'), + ('𐪀', '𐪟'), ('𐫀', '𐫦'), ('𐫫', '𐫶'), ('𐮀', '𐮑'), + ('𐮙', '𐮜'), ('𐮩', '𐮯'), ('𑁿', '𑁿'), ('𑅐', '𑅶'), + ('𑇍', '𑇍'), ('𑇚', '𑇚'), ('𑇡', '𑇴'), ('𑈀', '𑈑'), + ('𑈓', '𑈽'), ('𑊰', '𑋪'), ('𑋰', '𑋹'), ('𑌁', '𑌃'), + ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), + ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌼', '𑍄'), ('𑍇', '𑍈'), + ('𑍋', '𑍍'), ('𑍗', '𑍗'), ('𑍝', '𑍣'), ('𑍦', '𑍬'), + ('𑍰', '𑍴'), ('𑒀', '𑓇'), ('𑓐', '𑓙'), ('𑖀', '𑖵'), + ('𑖸', '𑗉'), ('𑘀', '𑙄'), ('𑙐', '𑙙'), ('𑢠', '𑣲'), + ('𑣿', '𑣿'), ('𑫀', '𑫸'), ('𒍯', '𒎘'), ('𒑣', '𒑮'), + ('𒑴', '𒑴'), ('𖩀', '𖩞'), ('𖩠', '𖩩'), ('𖩮', '𖩯'), + ('𖫐', '𖫭'), ('𖫰', '𖫵'), ('𖬀', '𖭅'), ('𖭐', '𖭙'), + ('𖭛', '𖭡'), ('𖭣', '𖭷'), ('𖭽', '𖮏'), ('𛰀', '𛱪'), + ('𛱰', '𛱼'), ('𛲀', '𛲈'), ('𛲐', '𛲙'), ('𛲜', '\u{1bca3}'), + ('𞠀', '𞣄'), ('𞣇', '𞣖'), ('🂿', '🂿'), ('🃠', '🃵'), + ('🄋', '🄌'), ('🌡', '🌬'), ('🌶', '🌶'), ('🍽', '🍽'), + ('🎔', '🎟'), ('🏅', '🏅'), ('🏋', '🏎'), ('🏔', '🏟'), + ('🏱', '🏷'), ('🐿', '🐿'), ('👁', '👁'), ('📸', '📸'), + ('📽', '📾'), ('🔾', '🔿'), ('🕄', '🕊'), ('🕨', '🕹'), + ('🕻', '🖣'), ('🖥', '🗺'), ('🙁', '🙂'), ('🙐', '🙿'), + ('🛆', '🛏'), ('🛠', '🛬'), ('🛰', '🛳'), ('🞀', '🟔'), + ('🠀', '🠋'), ('🠐', '🡇'), ('🡐', '🡙'), ('🡠', '🢇'), + ('🢐', '🢭'), +]; + +pub const V8_0: &'static [(char, char)] = &[ + ('ࢳ', 'ࢴ'), ('ࣣ', 'ࣣ'), ('ૹ', 'ૹ'), ('ౚ', 'ౚ'), + ('ൟ', 'ൟ'), ('Ᏽ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('₾', '₾'), + ('↊', '↋'), ('⯬', '⯯'), ('鿍', '鿕'), ('ꚞ', 'ꚞ'), + ('ꞏ', 'ꞏ'), ('Ʝ', 'ꞷ'), ('꣼', 'ꣽ'), ('ꭠ', 'ꭣ'), + ('ꭰ', 'ꮿ'), ('︮', '︯'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), + ('𐣻', '𐣿'), ('𐦼', '𐦽'), ('𐧀', '𐧏'), ('𐧒', '𐧿'), + ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𐳺', '𐳿'), ('𑇉', '𑇌'), + ('𑇛', '𑇟'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), + ('𑊏', '𑊝'), ('𑊟', '𑊩'), ('𑌀', '𑌀'), ('𑍐', '𑍐'), + ('𑗊', '𑗝'), ('𑜀', '𑜙'), ('𑜝', '𑜫'), ('𑜰', '𑜿'), + ('𒎙', '𒎙'), ('𒒀', '𒕃'), ('𔐀', '𔙆'), ('𝇞', '𝇨'), + ('𝠀', '𝪋'), ('𝪛', '𝪟'), ('𝪡', '𝪯'), ('🌭', '🌯'), + ('🍾', '🍿'), ('🏏', '🏓'), ('🏸', '🏿'), ('📿', '📿'), + ('🕋', '🕏'), ('🙃', '🙄'), ('🛐', '🛐'), ('🤐', '🤘'), + ('🦀', '🦄'), ('🧀', '🧀'), ('𫠠', '𬺡'), +]; + +pub const V9_0: &'static [(char, char)] = &[ + ('ࢶ', 'ࢽ'), ('ࣔ', '\u{8e2}'), ('ಀ', 'ಀ'), ('൏', '൏'), + ('ൔ', 'ൖ'), ('൘', '൞'), ('൶', '൸'), ('ᲀ', 'ᲈ'), + ('᷻', '᷻'), ('⏻', '⏾'), ('⹃', '⹄'), ('Ɪ', 'Ɪ'), + ('ꣅ', 'ꣅ'), ('𐆍', '𐆎'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), + ('𑈾', '𑈾'), ('𑐀', '𑑙'), ('𑑛', '𑑛'), ('𑑝', '𑑝'), + ('𑙠', '𑙬'), ('𑰀', '𑰈'), ('𑰊', '𑰶'), ('𑰸', '𑱅'), + ('𑱐', '𑱬'), ('𑱰', '𑲏'), ('𑲒', '𑲧'), ('𑲩', '𑲶'), + ('𖿠', '𖿠'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𞀀', '𞀆'), + ('𞀈', '𞀘'), ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), + ('𞤀', '𞥊'), ('𞥐', '𞥙'), ('𞥞', '𞥟'), ('🆛', '🆬'), + ('🈻', '🈻'), ('🕺', '🕺'), ('🖤', '🖤'), ('🛑', '🛒'), + ('🛴', '🛶'), ('🤙', '🤞'), ('🤠', '🤧'), ('🤰', '🤰'), + ('🤳', '🤾'), ('🥀', '🥋'), ('🥐', '🥞'), ('🦅', '🦑'), +]; diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/case_folding_simple.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/case_folding_simple.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/case_folding_simple.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/case_folding_simple.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,662 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate case-folding-simple /home/andrew/tmp/ucd-10.0.0/ --chars --all-pairs +// +// ucd-generate is available on crates.io. + +pub const CASE_FOLDING_SIMPLE: &'static [(char, &'static [char])] = &[ + ('A', &['a']), ('B', &['b']), ('C', &['c']), ('D', &['d']), ('E', &['e']), + ('F', &['f']), ('G', &['g']), ('H', &['h']), ('I', &['i']), ('J', &['j']), + ('K', &['k', 'K', ]), ('L', &['l']), ('M', &['m']), ('N', &['n']), ('O', &[ + 'o']), ('P', &['p']), ('Q', &['q']), ('R', &['r']), ('S', &['s', 'ſ', ]), + ('T', &['t']), ('U', &['u']), ('V', &['v']), ('W', &['w']), ('X', &['x']), + ('Y', &['y']), ('Z', &['z']), ('a', &['A']), ('b', &['B']), ('c', &['C']), + ('d', &['D']), ('e', &['E']), ('f', &['F']), ('g', &['G']), ('h', &['H']), + ('i', &['I']), ('j', &['J']), ('k', &['K', 'K', ]), ('l', &['L']), ('m', &[ + 'M']), ('n', &['N']), ('o', &['O']), ('p', &['P']), ('q', &['Q']), ('r', &[ + 'R']), ('s', &['S', 'ſ', ]), ('t', &['T']), ('u', &['U']), ('v', &['V']), + ('w', &['W']), ('x', &['X']), ('y', &['Y']), ('z', &['Z']), ('µ', &['Μ', + 'μ', ]), ('À', &['à']), ('Á', &['á']), ('Â', &['â']), ('Ã', &['ã' + ]), ('Ä', &['ä']), ('Å', &['å', 'Å', ]), ('Æ', &['æ']), ('Ç', &['ç' + ]), ('È', &['è']), ('É', &['é']), ('Ê', &['ê']), ('Ë', &['ë']), + ('Ì', &['ì']), ('Í', &['í']), ('Î', &['î']), ('Ï', &['ï']), ('Ð', &[ + 'ð']), ('Ñ', &['ñ']), ('Ò', &['ò']), ('Ó', &['ó']), ('Ô', &['ô']), + ('Õ', &['õ']), ('Ö', &['ö']), ('Ø', &['ø']), ('Ù', &['ù']), ('Ú', &[ + 'ú']), ('Û', &['û']), ('Ü', &['ü']), ('Ý', &['ý']), ('Þ', &['þ']), + ('ß', &['ẞ']), ('à', &['À']), ('á', &['Á']), ('â', &['Â']), + ('ã', &['Ã']), ('ä', &['Ä']), ('å', &['Å', 'Å', ]), ('æ', &['Æ']), + ('ç', &['Ç']), ('è', &['È']), ('é', &['É']), ('ê', &['Ê']), ('ë', &[ + 'Ë']), ('ì', &['Ì']), ('í', &['Í']), ('î', &['Î']), ('ï', &['Ï']), + ('ð', &['Ð']), ('ñ', &['Ñ']), ('ò', &['Ò']), ('ó', &['Ó']), ('ô', &[ + 'Ô']), ('õ', &['Õ']), ('ö', &['Ö']), ('ø', &['Ø']), ('ù', &['Ù']), + ('ú', &['Ú']), ('û', &['Û']), ('ü', &['Ü']), ('ý', &['Ý']), ('þ', &[ + 'Þ']), ('ÿ', &['Ÿ']), ('Ā', &['ā']), ('ā', &['Ā']), ('Ă', &['ă']), + ('ă', &['Ă']), ('Ą', &['ą']), ('ą', &['Ą']), ('Ć', &['ć']), ('ć', &[ + 'Ć']), ('Ĉ', &['ĉ']), ('ĉ', &['Ĉ']), ('Ċ', &['ċ']), ('ċ', &['Ċ']), + ('Č', &['č']), ('č', &['Č']), ('Ď', &['ď']), ('ď', &['Ď']), ('Đ', &[ + 'đ']), ('đ', &['Đ']), ('Ē', &['ē']), ('ē', &['Ē']), ('Ĕ', &['ĕ']), + ('ĕ', &['Ĕ']), ('Ė', &['ė']), ('ė', &['Ė']), ('Ę', &['ę']), ('ę', &[ + 'Ę']), ('Ě', &['ě']), ('ě', &['Ě']), ('Ĝ', &['ĝ']), ('ĝ', &['Ĝ']), + ('Ğ', &['ğ']), ('ğ', &['Ğ']), ('Ġ', &['ġ']), ('ġ', &['Ġ']), ('Ģ', &[ + 'ģ']), ('ģ', &['Ģ']), ('Ĥ', &['ĥ']), ('ĥ', &['Ĥ']), ('Ħ', &['ħ']), + ('ħ', &['Ħ']), ('Ĩ', &['ĩ']), ('ĩ', &['Ĩ']), ('Ī', &['ī']), ('ī', &[ + 'Ī']), ('Ĭ', &['ĭ']), ('ĭ', &['Ĭ']), ('Į', &['į']), ('į', &['Į']), + ('IJ', &['ij']), ('ij', &['IJ']), ('Ĵ', &['ĵ']), ('ĵ', &['Ĵ']), ('Ķ', &[ + 'ķ']), ('ķ', &['Ķ']), ('Ĺ', &['ĺ']), ('ĺ', &['Ĺ']), ('Ļ', &['ļ']), + ('ļ', &['Ļ']), ('Ľ', &['ľ']), ('ľ', &['Ľ']), ('Ŀ', &['ŀ']), ('ŀ', &[ + 'Ŀ']), ('Ł', &['ł']), ('ł', &['Ł']), ('Ń', &['ń']), ('ń', &['Ń']), + ('Ņ', &['ņ']), ('ņ', &['Ņ']), ('Ň', &['ň']), ('ň', &['Ň']), ('Ŋ', &[ + 'ŋ']), ('ŋ', &['Ŋ']), ('Ō', &['ō']), ('ō', &['Ō']), ('Ŏ', &['ŏ']), + ('ŏ', &['Ŏ']), ('Ő', &['ő']), ('ő', &['Ő']), ('Œ', &['œ']), ('œ', &[ + 'Œ']), ('Ŕ', &['ŕ']), ('ŕ', &['Ŕ']), ('Ŗ', &['ŗ']), ('ŗ', &['Ŗ']), + ('Ř', &['ř']), ('ř', &['Ř']), ('Ś', &['ś']), ('ś', &['Ś']), ('Ŝ', &[ + 'ŝ']), ('ŝ', &['Ŝ']), ('Ş', &['ş']), ('ş', &['Ş']), ('Š', &['š']), + ('š', &['Š']), ('Ţ', &['ţ']), ('ţ', &['Ţ']), ('Ť', &['ť']), ('ť', &[ + 'Ť']), ('Ŧ', &['ŧ']), ('ŧ', &['Ŧ']), ('Ũ', &['ũ']), ('ũ', &['Ũ']), + ('Ū', &['ū']), ('ū', &['Ū']), ('Ŭ', &['ŭ']), ('ŭ', &['Ŭ']), ('Ů', &[ + 'ů']), ('ů', &['Ů']), ('Ű', &['ű']), ('ű', &['Ű']), ('Ų', &['ų']), + ('ų', &['Ų']), ('Ŵ', &['ŵ']), ('ŵ', &['Ŵ']), ('Ŷ', &['ŷ']), ('ŷ', &[ + 'Ŷ']), ('Ÿ', &['ÿ']), ('Ź', &['ź']), ('ź', &['Ź']), ('Ż', &['ż']), + ('ż', &['Ż']), ('Ž', &['ž']), ('ž', &['Ž']), ('ſ', &['S', 's', ]), + ('ƀ', &['Ƀ']), ('Ɓ', &['ɓ']), ('Ƃ', &['ƃ']), ('ƃ', &['Ƃ']), ('Ƅ', &[ + 'ƅ']), ('ƅ', &['Ƅ']), ('Ɔ', &['ɔ']), ('Ƈ', &['ƈ']), ('ƈ', &['Ƈ']), + ('Ɖ', &['ɖ']), ('Ɗ', &['ɗ']), ('Ƌ', &['ƌ']), ('ƌ', &['Ƌ']), ('Ǝ', &[ + 'ǝ']), ('Ə', &['ə']), ('Ɛ', &['ɛ']), ('Ƒ', &['ƒ']), ('ƒ', &['Ƒ']), + ('Ɠ', &['ɠ']), ('Ɣ', &['ɣ']), ('ƕ', &['Ƕ']), ('Ɩ', &['ɩ']), ('Ɨ', &[ + 'ɨ']), ('Ƙ', &['ƙ']), ('ƙ', &['Ƙ']), ('ƚ', &['Ƚ']), ('Ɯ', &['ɯ']), + ('Ɲ', &['ɲ']), ('ƞ', &['Ƞ']), ('Ɵ', &['ɵ']), ('Ơ', &['ơ']), ('ơ', &[ + 'Ơ']), ('Ƣ', &['ƣ']), ('ƣ', &['Ƣ']), ('Ƥ', &['ƥ']), ('ƥ', &['Ƥ']), + ('Ʀ', &['ʀ']), ('Ƨ', &['ƨ']), ('ƨ', &['Ƨ']), ('Ʃ', &['ʃ']), ('Ƭ', &[ + 'ƭ']), ('ƭ', &['Ƭ']), ('Ʈ', &['ʈ']), ('Ư', &['ư']), ('ư', &['Ư']), + ('Ʊ', &['ʊ']), ('Ʋ', &['ʋ']), ('Ƴ', &['ƴ']), ('ƴ', &['Ƴ']), ('Ƶ', &[ + 'ƶ']), ('ƶ', &['Ƶ']), ('Ʒ', &['ʒ']), ('Ƹ', &['ƹ']), ('ƹ', &['Ƹ']), + ('Ƽ', &['ƽ']), ('ƽ', &['Ƽ']), ('ƿ', &['Ƿ']), ('DŽ', &['Dž', 'dž', ]), + ('Dž', &['DŽ', 'dž', ]), ('dž', &['DŽ', 'Dž', ]), ('LJ', &['Lj', 'lj', ]), + ('Lj', &['LJ', 'lj', ]), ('lj', &['LJ', 'Lj', ]), ('NJ', &['Nj', 'nj', ]), + ('Nj', &['NJ', 'nj', ]), ('nj', &['NJ', 'Nj', ]), ('Ǎ', &['ǎ']), ('ǎ', &[ + 'Ǎ']), ('Ǐ', &['ǐ']), ('ǐ', &['Ǐ']), ('Ǒ', &['ǒ']), ('ǒ', &['Ǒ']), + ('Ǔ', &['ǔ']), ('ǔ', &['Ǔ']), ('Ǖ', &['ǖ']), ('ǖ', &['Ǖ']), ('Ǘ', &[ + 'ǘ']), ('ǘ', &['Ǘ']), ('Ǚ', &['ǚ']), ('ǚ', &['Ǚ']), ('Ǜ', &['ǜ']), + ('ǜ', &['Ǜ']), ('ǝ', &['Ǝ']), ('Ǟ', &['ǟ']), ('ǟ', &['Ǟ']), ('Ǡ', &[ + 'ǡ']), ('ǡ', &['Ǡ']), ('Ǣ', &['ǣ']), ('ǣ', &['Ǣ']), ('Ǥ', &['ǥ']), + ('ǥ', &['Ǥ']), ('Ǧ', &['ǧ']), ('ǧ', &['Ǧ']), ('Ǩ', &['ǩ']), ('ǩ', &[ + 'Ǩ']), ('Ǫ', &['ǫ']), ('ǫ', &['Ǫ']), ('Ǭ', &['ǭ']), ('ǭ', &['Ǭ']), + ('Ǯ', &['ǯ']), ('ǯ', &['Ǯ']), ('DZ', &['Dz', 'dz', ]), ('Dz', &['DZ', + 'dz', ]), ('dz', &['DZ', 'Dz', ]), ('Ǵ', &['ǵ']), ('ǵ', &['Ǵ']), + ('Ƕ', &['ƕ']), ('Ƿ', &['ƿ']), ('Ǹ', &['ǹ']), ('ǹ', &['Ǹ']), ('Ǻ', &[ + 'ǻ']), ('ǻ', &['Ǻ']), ('Ǽ', &['ǽ']), ('ǽ', &['Ǽ']), ('Ǿ', &['ǿ']), + ('ǿ', &['Ǿ']), ('Ȁ', &['ȁ']), ('ȁ', &['Ȁ']), ('Ȃ', &['ȃ']), ('ȃ', &[ + 'Ȃ']), ('Ȅ', &['ȅ']), ('ȅ', &['Ȅ']), ('Ȇ', &['ȇ']), ('ȇ', &['Ȇ']), + ('Ȉ', &['ȉ']), ('ȉ', &['Ȉ']), ('Ȋ', &['ȋ']), ('ȋ', &['Ȋ']), ('Ȍ', &[ + 'ȍ']), ('ȍ', &['Ȍ']), ('Ȏ', &['ȏ']), ('ȏ', &['Ȏ']), ('Ȑ', &['ȑ']), + ('ȑ', &['Ȑ']), ('Ȓ', &['ȓ']), ('ȓ', &['Ȓ']), ('Ȕ', &['ȕ']), ('ȕ', &[ + 'Ȕ']), ('Ȗ', &['ȗ']), ('ȗ', &['Ȗ']), ('Ș', &['ș']), ('ș', &['Ș']), + ('Ț', &['ț']), ('ț', &['Ț']), ('Ȝ', &['ȝ']), ('ȝ', &['Ȝ']), ('Ȟ', &[ + 'ȟ']), ('ȟ', &['Ȟ']), ('Ƞ', &['ƞ']), ('Ȣ', &['ȣ']), ('ȣ', &['Ȣ']), + ('Ȥ', &['ȥ']), ('ȥ', &['Ȥ']), ('Ȧ', &['ȧ']), ('ȧ', &['Ȧ']), ('Ȩ', &[ + 'ȩ']), ('ȩ', &['Ȩ']), ('Ȫ', &['ȫ']), ('ȫ', &['Ȫ']), ('Ȭ', &['ȭ']), + ('ȭ', &['Ȭ']), ('Ȯ', &['ȯ']), ('ȯ', &['Ȯ']), ('Ȱ', &['ȱ']), ('ȱ', &[ + 'Ȱ']), ('Ȳ', &['ȳ']), ('ȳ', &['Ȳ']), ('Ⱥ', &['ⱥ']), ('Ȼ', &['ȼ']), + ('ȼ', &['Ȼ']), ('Ƚ', &['ƚ']), ('Ⱦ', &['ⱦ']), ('ȿ', &['Ȿ']), + ('ɀ', &['Ɀ']), ('Ɂ', &['ɂ']), ('ɂ', &['Ɂ']), ('Ƀ', &['ƀ']), + ('Ʉ', &['ʉ']), ('Ʌ', &['ʌ']), ('Ɇ', &['ɇ']), ('ɇ', &['Ɇ']), ('Ɉ', &[ + 'ɉ']), ('ɉ', &['Ɉ']), ('Ɋ', &['ɋ']), ('ɋ', &['Ɋ']), ('Ɍ', &['ɍ']), + ('ɍ', &['Ɍ']), ('Ɏ', &['ɏ']), ('ɏ', &['Ɏ']), ('ɐ', &['Ɐ']), + ('ɑ', &['Ɑ']), ('ɒ', &['Ɒ']), ('ɓ', &['Ɓ']), ('ɔ', &['Ɔ']), + ('ɖ', &['Ɖ']), ('ɗ', &['Ɗ']), ('ə', &['Ə']), ('ɛ', &['Ɛ']), ('ɜ', &[ + 'Ɜ']), ('ɠ', &['Ɠ']), ('ɡ', &['Ɡ']), ('ɣ', &['Ɣ']), ('ɥ', &['Ɥ' + ]), ('ɦ', &['Ɦ']), ('ɨ', &['Ɨ']), ('ɩ', &['Ɩ']), ('ɪ', &['Ɪ']), + ('ɫ', &['Ɫ']), ('ɬ', &['Ɬ']), ('ɯ', &['Ɯ']), ('ɱ', &['Ɱ']), + ('ɲ', &['Ɲ']), ('ɵ', &['Ɵ']), ('ɽ', &['Ɽ']), ('ʀ', &['Ʀ']), + ('ʃ', &['Ʃ']), ('ʇ', &['Ʇ']), ('ʈ', &['Ʈ']), ('ʉ', &['Ʉ']), + ('ʊ', &['Ʊ']), ('ʋ', &['Ʋ']), ('ʌ', &['Ʌ']), ('ʒ', &['Ʒ']), ('ʝ', &[ + 'Ʝ']), ('ʞ', &['Ʞ']), ('ͅ', &['Ι', 'ι', 'ι', ]), ('Ͱ', &['ͱ']), + ('ͱ', &['Ͱ']), ('Ͳ', &['ͳ']), ('ͳ', &['Ͳ']), ('Ͷ', &['ͷ']), ('ͷ', &[ + 'Ͷ']), ('ͻ', &['Ͻ']), ('ͼ', &['Ͼ']), ('ͽ', &['Ͽ']), ('Ϳ', &['ϳ']), + ('Ά', &['ά']), ('Έ', &['έ']), ('Ή', &['ή']), ('Ί', &['ί']), ('Ό', &[ + 'ό']), ('Ύ', &['ύ']), ('Ώ', &['ώ']), ('Α', &['α']), ('Β', &['β', + 'ϐ', ]), ('Γ', &['γ']), ('Δ', &['δ']), ('Ε', &['ε', 'ϵ', ]), + ('Ζ', &['ζ']), ('Η', &['η']), ('Θ', &['θ', 'ϑ', 'ϴ', ]), ('Ι', &[ + 'ͅ', 'ι', 'ι', ]), ('Κ', &['κ', 'ϰ', ]), ('Λ', &['λ']), ('Μ', &[ + 'µ', 'μ', ]), ('Ν', &['ν']), ('Ξ', &['ξ']), ('Ο', &['ο']), ('Π', &[ + 'π', 'ϖ', ]), ('Ρ', &['ρ', 'ϱ', ]), ('Σ', &['ς', 'σ', ]), ('Τ', &[ + 'τ']), ('Υ', &['υ']), ('Φ', &['φ', 'ϕ', ]), ('Χ', &['χ']), ('Ψ', &[ + 'ψ']), ('Ω', &['ω', 'Ω', ]), ('Ϊ', &['ϊ']), ('Ϋ', &['ϋ']), ('ά', &[ + 'Ά']), ('έ', &['Έ']), ('ή', &['Ή']), ('ί', &['Ί']), ('α', &['Α']), + ('β', &['Β', 'ϐ', ]), ('γ', &['Γ']), ('δ', &['Δ']), ('ε', &['Ε', + 'ϵ', ]), ('ζ', &['Ζ']), ('η', &['Η']), ('θ', &['Θ', 'ϑ', 'ϴ', ]), + ('ι', &['ͅ', 'Ι', 'ι', ]), ('κ', &['Κ', 'ϰ', ]), ('λ', &['Λ']), + ('μ', &['µ', 'Μ', ]), ('ν', &['Ν']), ('ξ', &['Ξ']), ('ο', &['Ο']), + ('π', &['Π', 'ϖ', ]), ('ρ', &['Ρ', 'ϱ', ]), ('ς', &['Σ', 'σ', ]), + ('σ', &['Σ', 'ς', ]), ('τ', &['Τ']), ('υ', &['Υ']), ('φ', &['Φ', + 'ϕ', ]), ('χ', &['Χ']), ('ψ', &['Ψ']), ('ω', &['Ω', 'Ω', ]), + ('ϊ', &['Ϊ']), ('ϋ', &['Ϋ']), ('ό', &['Ό']), ('ύ', &['Ύ']), ('ώ', &[ + 'Ώ']), ('Ϗ', &['ϗ']), ('ϐ', &['Β', 'β', ]), ('ϑ', &['Θ', 'θ', 'ϴ', + ]), ('ϕ', &['Φ', 'φ', ]), ('ϖ', &['Π', 'π', ]), ('ϗ', &['Ϗ']), + ('Ϙ', &['ϙ']), ('ϙ', &['Ϙ']), ('Ϛ', &['ϛ']), ('ϛ', &['Ϛ']), ('Ϝ', &[ + 'ϝ']), ('ϝ', &['Ϝ']), ('Ϟ', &['ϟ']), ('ϟ', &['Ϟ']), ('Ϡ', &['ϡ']), + ('ϡ', &['Ϡ']), ('Ϣ', &['ϣ']), ('ϣ', &['Ϣ']), ('Ϥ', &['ϥ']), ('ϥ', &[ + 'Ϥ']), ('Ϧ', &['ϧ']), ('ϧ', &['Ϧ']), ('Ϩ', &['ϩ']), ('ϩ', &['Ϩ']), + ('Ϫ', &['ϫ']), ('ϫ', &['Ϫ']), ('Ϭ', &['ϭ']), ('ϭ', &['Ϭ']), ('Ϯ', &[ + 'ϯ']), ('ϯ', &['Ϯ']), ('ϰ', &['Κ', 'κ', ]), ('ϱ', &['Ρ', 'ρ', ]), + ('ϲ', &['Ϲ']), ('ϳ', &['Ϳ']), ('ϴ', &['Θ', 'θ', 'ϑ', ]), ('ϵ', &[ + 'Ε', 'ε', ]), ('Ϸ', &['ϸ']), ('ϸ', &['Ϸ']), ('Ϲ', &['ϲ']), ('Ϻ', &[ + 'ϻ']), ('ϻ', &['Ϻ']), ('Ͻ', &['ͻ']), ('Ͼ', &['ͼ']), ('Ͽ', &['ͽ']), + ('Ѐ', &['ѐ']), ('Ё', &['ё']), ('Ђ', &['ђ']), ('Ѓ', &['ѓ']), ('Є', &[ + 'є']), ('Ѕ', &['ѕ']), ('І', &['і']), ('Ї', &['ї']), ('Ј', &['ј']), + ('Љ', &['љ']), ('Њ', &['њ']), ('Ћ', &['ћ']), ('Ќ', &['ќ']), ('Ѝ', &[ + 'ѝ']), ('Ў', &['ў']), ('Џ', &['џ']), ('А', &['а']), ('Б', &['б']), + ('В', &['в', 'ᲀ', ]), ('Г', &['г']), ('Д', &['д', 'ᲁ', ]), + ('Е', &['е']), ('Ж', &['ж']), ('З', &['з']), ('И', &['и']), ('Й', &[ + 'й']), ('К', &['к']), ('Л', &['л']), ('М', &['м']), ('Н', &['н']), + ('О', &['о', 'ᲂ', ]), ('П', &['п']), ('Р', &['р']), ('С', &['с', + 'ᲃ', ]), ('Т', &['т', 'ᲄ', 'ᲅ', ]), ('У', &['у']), ('Ф', &['ф' + ]), ('Х', &['х']), ('Ц', &['ц']), ('Ч', &['ч']), ('Ш', &['ш']), + ('Щ', &['щ']), ('Ъ', &['ъ', 'ᲆ', ]), ('Ы', &['ы']), ('Ь', &['ь']), + ('Э', &['э']), ('Ю', &['ю']), ('Я', &['я']), ('а', &['А']), ('б', &[ + 'Б']), ('в', &['В', 'ᲀ', ]), ('г', &['Г']), ('д', &['Д', 'ᲁ', ]), + ('е', &['Е']), ('ж', &['Ж']), ('з', &['З']), ('и', &['И']), ('й', &[ + 'Й']), ('к', &['К']), ('л', &['Л']), ('м', &['М']), ('н', &['Н']), + ('о', &['О', 'ᲂ', ]), ('п', &['П']), ('р', &['Р']), ('с', &['С', + 'ᲃ', ]), ('т', &['Т', 'ᲄ', 'ᲅ', ]), ('у', &['У']), ('ф', &['Ф' + ]), ('х', &['Х']), ('ц', &['Ц']), ('ч', &['Ч']), ('ш', &['Ш']), + ('щ', &['Щ']), ('ъ', &['Ъ', 'ᲆ', ]), ('ы', &['Ы']), ('ь', &['Ь']), + ('э', &['Э']), ('ю', &['Ю']), ('я', &['Я']), ('ѐ', &['Ѐ']), ('ё', &[ + 'Ё']), ('ђ', &['Ђ']), ('ѓ', &['Ѓ']), ('є', &['Є']), ('ѕ', &['Ѕ']), + ('і', &['І']), ('ї', &['Ї']), ('ј', &['Ј']), ('љ', &['Љ']), ('њ', &[ + 'Њ']), ('ћ', &['Ћ']), ('ќ', &['Ќ']), ('ѝ', &['Ѝ']), ('ў', &['Ў']), + ('џ', &['Џ']), ('Ѡ', &['ѡ']), ('ѡ', &['Ѡ']), ('Ѣ', &['ѣ', 'ᲇ', ]), + ('ѣ', &['Ѣ', 'ᲇ', ]), ('Ѥ', &['ѥ']), ('ѥ', &['Ѥ']), ('Ѧ', &['ѧ']), + ('ѧ', &['Ѧ']), ('Ѩ', &['ѩ']), ('ѩ', &['Ѩ']), ('Ѫ', &['ѫ']), ('ѫ', &[ + 'Ѫ']), ('Ѭ', &['ѭ']), ('ѭ', &['Ѭ']), ('Ѯ', &['ѯ']), ('ѯ', &['Ѯ']), + ('Ѱ', &['ѱ']), ('ѱ', &['Ѱ']), ('Ѳ', &['ѳ']), ('ѳ', &['Ѳ']), ('Ѵ', &[ + 'ѵ']), ('ѵ', &['Ѵ']), ('Ѷ', &['ѷ']), ('ѷ', &['Ѷ']), ('Ѹ', &['ѹ']), + ('ѹ', &['Ѹ']), ('Ѻ', &['ѻ']), ('ѻ', &['Ѻ']), ('Ѽ', &['ѽ']), ('ѽ', &[ + 'Ѽ']), ('Ѿ', &['ѿ']), ('ѿ', &['Ѿ']), ('Ҁ', &['ҁ']), ('ҁ', &['Ҁ']), + ('Ҋ', &['ҋ']), ('ҋ', &['Ҋ']), ('Ҍ', &['ҍ']), ('ҍ', &['Ҍ']), ('Ҏ', &[ + 'ҏ']), ('ҏ', &['Ҏ']), ('Ґ', &['ґ']), ('ґ', &['Ґ']), ('Ғ', &['ғ']), + ('ғ', &['Ғ']), ('Ҕ', &['ҕ']), ('ҕ', &['Ҕ']), ('Җ', &['җ']), ('җ', &[ + 'Җ']), ('Ҙ', &['ҙ']), ('ҙ', &['Ҙ']), ('Қ', &['қ']), ('қ', &['Қ']), + ('Ҝ', &['ҝ']), ('ҝ', &['Ҝ']), ('Ҟ', &['ҟ']), ('ҟ', &['Ҟ']), ('Ҡ', &[ + 'ҡ']), ('ҡ', &['Ҡ']), ('Ң', &['ң']), ('ң', &['Ң']), ('Ҥ', &['ҥ']), + ('ҥ', &['Ҥ']), ('Ҧ', &['ҧ']), ('ҧ', &['Ҧ']), ('Ҩ', &['ҩ']), ('ҩ', &[ + 'Ҩ']), ('Ҫ', &['ҫ']), ('ҫ', &['Ҫ']), ('Ҭ', &['ҭ']), ('ҭ', &['Ҭ']), + ('Ү', &['ү']), ('ү', &['Ү']), ('Ұ', &['ұ']), ('ұ', &['Ұ']), ('Ҳ', &[ + 'ҳ']), ('ҳ', &['Ҳ']), ('Ҵ', &['ҵ']), ('ҵ', &['Ҵ']), ('Ҷ', &['ҷ']), + ('ҷ', &['Ҷ']), ('Ҹ', &['ҹ']), ('ҹ', &['Ҹ']), ('Һ', &['һ']), ('һ', &[ + 'Һ']), ('Ҽ', &['ҽ']), ('ҽ', &['Ҽ']), ('Ҿ', &['ҿ']), ('ҿ', &['Ҿ']), + ('Ӏ', &['ӏ']), ('Ӂ', &['ӂ']), ('ӂ', &['Ӂ']), ('Ӄ', &['ӄ']), ('ӄ', &[ + 'Ӄ']), ('Ӆ', &['ӆ']), ('ӆ', &['Ӆ']), ('Ӈ', &['ӈ']), ('ӈ', &['Ӈ']), + ('Ӊ', &['ӊ']), ('ӊ', &['Ӊ']), ('Ӌ', &['ӌ']), ('ӌ', &['Ӌ']), ('Ӎ', &[ + 'ӎ']), ('ӎ', &['Ӎ']), ('ӏ', &['Ӏ']), ('Ӑ', &['ӑ']), ('ӑ', &['Ӑ']), + ('Ӓ', &['ӓ']), ('ӓ', &['Ӓ']), ('Ӕ', &['ӕ']), ('ӕ', &['Ӕ']), ('Ӗ', &[ + 'ӗ']), ('ӗ', &['Ӗ']), ('Ә', &['ә']), ('ә', &['Ә']), ('Ӛ', &['ӛ']), + ('ӛ', &['Ӛ']), ('Ӝ', &['ӝ']), ('ӝ', &['Ӝ']), ('Ӟ', &['ӟ']), ('ӟ', &[ + 'Ӟ']), ('Ӡ', &['ӡ']), ('ӡ', &['Ӡ']), ('Ӣ', &['ӣ']), ('ӣ', &['Ӣ']), + ('Ӥ', &['ӥ']), ('ӥ', &['Ӥ']), ('Ӧ', &['ӧ']), ('ӧ', &['Ӧ']), ('Ө', &[ + 'ө']), ('ө', &['Ө']), ('Ӫ', &['ӫ']), ('ӫ', &['Ӫ']), ('Ӭ', &['ӭ']), + ('ӭ', &['Ӭ']), ('Ӯ', &['ӯ']), ('ӯ', &['Ӯ']), ('Ӱ', &['ӱ']), ('ӱ', &[ + 'Ӱ']), ('Ӳ', &['ӳ']), ('ӳ', &['Ӳ']), ('Ӵ', &['ӵ']), ('ӵ', &['Ӵ']), + ('Ӷ', &['ӷ']), ('ӷ', &['Ӷ']), ('Ӹ', &['ӹ']), ('ӹ', &['Ӹ']), ('Ӻ', &[ + 'ӻ']), ('ӻ', &['Ӻ']), ('Ӽ', &['ӽ']), ('ӽ', &['Ӽ']), ('Ӿ', &['ӿ']), + ('ӿ', &['Ӿ']), ('Ԁ', &['ԁ']), ('ԁ', &['Ԁ']), ('Ԃ', &['ԃ']), ('ԃ', &[ + 'Ԃ']), ('Ԅ', &['ԅ']), ('ԅ', &['Ԅ']), ('Ԇ', &['ԇ']), ('ԇ', &['Ԇ']), + ('Ԉ', &['ԉ']), ('ԉ', &['Ԉ']), ('Ԋ', &['ԋ']), ('ԋ', &['Ԋ']), ('Ԍ', &[ + 'ԍ']), ('ԍ', &['Ԍ']), ('Ԏ', &['ԏ']), ('ԏ', &['Ԏ']), ('Ԑ', &['ԑ']), + ('ԑ', &['Ԑ']), ('Ԓ', &['ԓ']), ('ԓ', &['Ԓ']), ('Ԕ', &['ԕ']), ('ԕ', &[ + 'Ԕ']), ('Ԗ', &['ԗ']), ('ԗ', &['Ԗ']), ('Ԙ', &['ԙ']), ('ԙ', &['Ԙ']), + ('Ԛ', &['ԛ']), ('ԛ', &['Ԛ']), ('Ԝ', &['ԝ']), ('ԝ', &['Ԝ']), ('Ԟ', &[ + 'ԟ']), ('ԟ', &['Ԟ']), ('Ԡ', &['ԡ']), ('ԡ', &['Ԡ']), ('Ԣ', &['ԣ']), + ('ԣ', &['Ԣ']), ('Ԥ', &['ԥ']), ('ԥ', &['Ԥ']), ('Ԧ', &['ԧ']), ('ԧ', &[ + 'Ԧ']), ('Ԩ', &['ԩ']), ('ԩ', &['Ԩ']), ('Ԫ', &['ԫ']), ('ԫ', &['Ԫ']), + ('Ԭ', &['ԭ']), ('ԭ', &['Ԭ']), ('Ԯ', &['ԯ']), ('ԯ', &['Ԯ']), ('Ա', &[ + 'ա']), ('Բ', &['բ']), ('Գ', &['գ']), ('Դ', &['դ']), ('Ե', &['ե']), + ('Զ', &['զ']), ('Է', &['է']), ('Ը', &['ը']), ('Թ', &['թ']), ('Ժ', &[ + 'ժ']), ('Ի', &['ի']), ('Լ', &['լ']), ('Խ', &['խ']), ('Ծ', &['ծ']), + ('Կ', &['կ']), ('Հ', &['հ']), ('Ձ', &['ձ']), ('Ղ', &['ղ']), ('Ճ', &[ + 'ճ']), ('Մ', &['մ']), ('Յ', &['յ']), ('Ն', &['ն']), ('Շ', &['շ']), + ('Ո', &['ո']), ('Չ', &['չ']), ('Պ', &['պ']), ('Ջ', &['ջ']), ('Ռ', &[ + 'ռ']), ('Ս', &['ս']), ('Վ', &['վ']), ('Տ', &['տ']), ('Ր', &['ր']), + ('Ց', &['ց']), ('Ւ', &['ւ']), ('Փ', &['փ']), ('Ք', &['ք']), ('Օ', &[ + 'օ']), ('Ֆ', &['ֆ']), ('ա', &['Ա']), ('բ', &['Բ']), ('գ', &['Գ']), + ('դ', &['Դ']), ('ե', &['Ե']), ('զ', &['Զ']), ('է', &['Է']), ('ը', &[ + 'Ը']), ('թ', &['Թ']), ('ժ', &['Ժ']), ('ի', &['Ի']), ('լ', &['Լ']), + ('խ', &['Խ']), ('ծ', &['Ծ']), ('կ', &['Կ']), ('հ', &['Հ']), ('ձ', &[ + 'Ձ']), ('ղ', &['Ղ']), ('ճ', &['Ճ']), ('մ', &['Մ']), ('յ', &['Յ']), + ('ն', &['Ն']), ('շ', &['Շ']), ('ո', &['Ո']), ('չ', &['Չ']), ('պ', &[ + 'Պ']), ('ջ', &['Ջ']), ('ռ', &['Ռ']), ('ս', &['Ս']), ('վ', &['Վ']), + ('տ', &['Տ']), ('ր', &['Ր']), ('ց', &['Ց']), ('ւ', &['Ւ']), ('փ', &[ + 'Փ']), ('ք', &['Ք']), ('օ', &['Օ']), ('ֆ', &['Ֆ']), ('Ⴀ', &['ⴀ' + ]), ('Ⴁ', &['ⴁ']), ('Ⴂ', &['ⴂ']), ('Ⴃ', &['ⴃ']), ('Ⴄ', &['ⴄ' + ]), ('Ⴅ', &['ⴅ']), ('Ⴆ', &['ⴆ']), ('Ⴇ', &['ⴇ']), ('Ⴈ', &['ⴈ' + ]), ('Ⴉ', &['ⴉ']), ('Ⴊ', &['ⴊ']), ('Ⴋ', &['ⴋ']), ('Ⴌ', &['ⴌ' + ]), ('Ⴍ', &['ⴍ']), ('Ⴎ', &['ⴎ']), ('Ⴏ', &['ⴏ']), ('Ⴐ', &['ⴐ' + ]), ('Ⴑ', &['ⴑ']), ('Ⴒ', &['ⴒ']), ('Ⴓ', &['ⴓ']), ('Ⴔ', &['ⴔ' + ]), ('Ⴕ', &['ⴕ']), ('Ⴖ', &['ⴖ']), ('Ⴗ', &['ⴗ']), ('Ⴘ', &['ⴘ' + ]), ('Ⴙ', &['ⴙ']), ('Ⴚ', &['ⴚ']), ('Ⴛ', &['ⴛ']), ('Ⴜ', &['ⴜ' + ]), ('Ⴝ', &['ⴝ']), ('Ⴞ', &['ⴞ']), ('Ⴟ', &['ⴟ']), ('Ⴠ', &['ⴠ' + ]), ('Ⴡ', &['ⴡ']), ('Ⴢ', &['ⴢ']), ('Ⴣ', &['ⴣ']), ('Ⴤ', &['ⴤ' + ]), ('Ⴥ', &['ⴥ']), ('Ⴧ', &['ⴧ']), ('Ⴭ', &['ⴭ']), ('Ꭰ', &['ꭰ' + ]), ('Ꭱ', &['ꭱ']), ('Ꭲ', &['ꭲ']), ('Ꭳ', &['ꭳ']), ('Ꭴ', &['ꭴ' + ]), ('Ꭵ', &['ꭵ']), ('Ꭶ', &['ꭶ']), ('Ꭷ', &['ꭷ']), ('Ꭸ', &['ꭸ' + ]), ('Ꭹ', &['ꭹ']), ('Ꭺ', &['ꭺ']), ('Ꭻ', &['ꭻ']), ('Ꭼ', &['ꭼ' + ]), ('Ꭽ', &['ꭽ']), ('Ꭾ', &['ꭾ']), ('Ꭿ', &['ꭿ']), ('Ꮀ', &['ꮀ' + ]), ('Ꮁ', &['ꮁ']), ('Ꮂ', &['ꮂ']), ('Ꮃ', &['ꮃ']), ('Ꮄ', &['ꮄ' + ]), ('Ꮅ', &['ꮅ']), ('Ꮆ', &['ꮆ']), ('Ꮇ', &['ꮇ']), ('Ꮈ', &['ꮈ' + ]), ('Ꮉ', &['ꮉ']), ('Ꮊ', &['ꮊ']), ('Ꮋ', &['ꮋ']), ('Ꮌ', &['ꮌ' + ]), ('Ꮍ', &['ꮍ']), ('Ꮎ', &['ꮎ']), ('Ꮏ', &['ꮏ']), ('Ꮐ', &['ꮐ' + ]), ('Ꮑ', &['ꮑ']), ('Ꮒ', &['ꮒ']), ('Ꮓ', &['ꮓ']), ('Ꮔ', &['ꮔ' + ]), ('Ꮕ', &['ꮕ']), ('Ꮖ', &['ꮖ']), ('Ꮗ', &['ꮗ']), ('Ꮘ', &['ꮘ' + ]), ('Ꮙ', &['ꮙ']), ('Ꮚ', &['ꮚ']), ('Ꮛ', &['ꮛ']), ('Ꮜ', &['ꮜ' + ]), ('Ꮝ', &['ꮝ']), ('Ꮞ', &['ꮞ']), ('Ꮟ', &['ꮟ']), ('Ꮠ', &['ꮠ' + ]), ('Ꮡ', &['ꮡ']), ('Ꮢ', &['ꮢ']), ('Ꮣ', &['ꮣ']), ('Ꮤ', &['ꮤ' + ]), ('Ꮥ', &['ꮥ']), ('Ꮦ', &['ꮦ']), ('Ꮧ', &['ꮧ']), ('Ꮨ', &['ꮨ' + ]), ('Ꮩ', &['ꮩ']), ('Ꮪ', &['ꮪ']), ('Ꮫ', &['ꮫ']), ('Ꮬ', &['ꮬ' + ]), ('Ꮭ', &['ꮭ']), ('Ꮮ', &['ꮮ']), ('Ꮯ', &['ꮯ']), ('Ꮰ', &['ꮰ' + ]), ('Ꮱ', &['ꮱ']), ('Ꮲ', &['ꮲ']), ('Ꮳ', &['ꮳ']), ('Ꮴ', &['ꮴ' + ]), ('Ꮵ', &['ꮵ']), ('Ꮶ', &['ꮶ']), ('Ꮷ', &['ꮷ']), ('Ꮸ', &['ꮸ' + ]), ('Ꮹ', &['ꮹ']), ('Ꮺ', &['ꮺ']), ('Ꮻ', &['ꮻ']), ('Ꮼ', &['ꮼ' + ]), ('Ꮽ', &['ꮽ']), ('Ꮾ', &['ꮾ']), ('Ꮿ', &['ꮿ']), ('Ᏸ', &['ᏸ' + ]), ('Ᏹ', &['ᏹ']), ('Ᏺ', &['ᏺ']), ('Ᏻ', &['ᏻ']), ('Ᏼ', &['ᏼ' + ]), ('Ᏽ', &['ᏽ']), ('ᏸ', &['Ᏸ']), ('ᏹ', &['Ᏹ']), ('ᏺ', &['Ᏺ' + ]), ('ᏻ', &['Ᏻ']), ('ᏼ', &['Ᏼ']), ('ᏽ', &['Ᏽ']), ('ᲀ', &['В', + 'в', ]), ('ᲁ', &['Д', 'д', ]), ('ᲂ', &['О', 'о', ]), ('ᲃ', &[ + 'С', 'с', ]), ('ᲄ', &['Т', 'т', 'ᲅ', ]), ('ᲅ', &['Т', 'т', + 'ᲄ', ]), ('ᲆ', &['Ъ', 'ъ', ]), ('ᲇ', &['Ѣ', 'ѣ', ]), ('ᲈ', &[ + 'Ꙋ', 'ꙋ', ]), ('ᵹ', &['Ᵹ']), ('ᵽ', &['Ᵽ']), ('Ḁ', &['ḁ']), + ('ḁ', &['Ḁ']), ('Ḃ', &['ḃ']), ('ḃ', &['Ḃ']), ('Ḅ', &['ḅ']), + ('ḅ', &['Ḅ']), ('Ḇ', &['ḇ']), ('ḇ', &['Ḇ']), ('Ḉ', &['ḉ']), + ('ḉ', &['Ḉ']), ('Ḋ', &['ḋ']), ('ḋ', &['Ḋ']), ('Ḍ', &['ḍ']), + ('ḍ', &['Ḍ']), ('Ḏ', &['ḏ']), ('ḏ', &['Ḏ']), ('Ḑ', &['ḑ']), + ('ḑ', &['Ḑ']), ('Ḓ', &['ḓ']), ('ḓ', &['Ḓ']), ('Ḕ', &['ḕ']), + ('ḕ', &['Ḕ']), ('Ḗ', &['ḗ']), ('ḗ', &['Ḗ']), ('Ḙ', &['ḙ']), + ('ḙ', &['Ḙ']), ('Ḛ', &['ḛ']), ('ḛ', &['Ḛ']), ('Ḝ', &['ḝ']), + ('ḝ', &['Ḝ']), ('Ḟ', &['ḟ']), ('ḟ', &['Ḟ']), ('Ḡ', &['ḡ']), + ('ḡ', &['Ḡ']), ('Ḣ', &['ḣ']), ('ḣ', &['Ḣ']), ('Ḥ', &['ḥ']), + ('ḥ', &['Ḥ']), ('Ḧ', &['ḧ']), ('ḧ', &['Ḧ']), ('Ḩ', &['ḩ']), + ('ḩ', &['Ḩ']), ('Ḫ', &['ḫ']), ('ḫ', &['Ḫ']), ('Ḭ', &['ḭ']), + ('ḭ', &['Ḭ']), ('Ḯ', &['ḯ']), ('ḯ', &['Ḯ']), ('Ḱ', &['ḱ']), + ('ḱ', &['Ḱ']), ('Ḳ', &['ḳ']), ('ḳ', &['Ḳ']), ('Ḵ', &['ḵ']), + ('ḵ', &['Ḵ']), ('Ḷ', &['ḷ']), ('ḷ', &['Ḷ']), ('Ḹ', &['ḹ']), + ('ḹ', &['Ḹ']), ('Ḻ', &['ḻ']), ('ḻ', &['Ḻ']), ('Ḽ', &['ḽ']), + ('ḽ', &['Ḽ']), ('Ḿ', &['ḿ']), ('ḿ', &['Ḿ']), ('Ṁ', &['ṁ']), + ('ṁ', &['Ṁ']), ('Ṃ', &['ṃ']), ('ṃ', &['Ṃ']), ('Ṅ', &['ṅ']), + ('ṅ', &['Ṅ']), ('Ṇ', &['ṇ']), ('ṇ', &['Ṇ']), ('Ṉ', &['ṉ']), + ('ṉ', &['Ṉ']), ('Ṋ', &['ṋ']), ('ṋ', &['Ṋ']), ('Ṍ', &['ṍ']), + ('ṍ', &['Ṍ']), ('Ṏ', &['ṏ']), ('ṏ', &['Ṏ']), ('Ṑ', &['ṑ']), + ('ṑ', &['Ṑ']), ('Ṓ', &['ṓ']), ('ṓ', &['Ṓ']), ('Ṕ', &['ṕ']), + ('ṕ', &['Ṕ']), ('Ṗ', &['ṗ']), ('ṗ', &['Ṗ']), ('Ṙ', &['ṙ']), + ('ṙ', &['Ṙ']), ('Ṛ', &['ṛ']), ('ṛ', &['Ṛ']), ('Ṝ', &['ṝ']), + ('ṝ', &['Ṝ']), ('Ṟ', &['ṟ']), ('ṟ', &['Ṟ']), ('Ṡ', &['ṡ', + 'ẛ', ]), ('ṡ', &['Ṡ', 'ẛ', ]), ('Ṣ', &['ṣ']), ('ṣ', &['Ṣ']), + ('Ṥ', &['ṥ']), ('ṥ', &['Ṥ']), ('Ṧ', &['ṧ']), ('ṧ', &['Ṧ']), + ('Ṩ', &['ṩ']), ('ṩ', &['Ṩ']), ('Ṫ', &['ṫ']), ('ṫ', &['Ṫ']), + ('Ṭ', &['ṭ']), ('ṭ', &['Ṭ']), ('Ṯ', &['ṯ']), ('ṯ', &['Ṯ']), + ('Ṱ', &['ṱ']), ('ṱ', &['Ṱ']), ('Ṳ', &['ṳ']), ('ṳ', &['Ṳ']), + ('Ṵ', &['ṵ']), ('ṵ', &['Ṵ']), ('Ṷ', &['ṷ']), ('ṷ', &['Ṷ']), + ('Ṹ', &['ṹ']), ('ṹ', &['Ṹ']), ('Ṻ', &['ṻ']), ('ṻ', &['Ṻ']), + ('Ṽ', &['ṽ']), ('ṽ', &['Ṽ']), ('Ṿ', &['ṿ']), ('ṿ', &['Ṿ']), + ('Ẁ', &['ẁ']), ('ẁ', &['Ẁ']), ('Ẃ', &['ẃ']), ('ẃ', &['Ẃ']), + ('Ẅ', &['ẅ']), ('ẅ', &['Ẅ']), ('Ẇ', &['ẇ']), ('ẇ', &['Ẇ']), + ('Ẉ', &['ẉ']), ('ẉ', &['Ẉ']), ('Ẋ', &['ẋ']), ('ẋ', &['Ẋ']), + ('Ẍ', &['ẍ']), ('ẍ', &['Ẍ']), ('Ẏ', &['ẏ']), ('ẏ', &['Ẏ']), + ('Ẑ', &['ẑ']), ('ẑ', &['Ẑ']), ('Ẓ', &['ẓ']), ('ẓ', &['Ẓ']), + ('Ẕ', &['ẕ']), ('ẕ', &['Ẕ']), ('ẛ', &['Ṡ', 'ṡ', ]), ('ẞ', &[ + 'ß']), ('Ạ', &['ạ']), ('ạ', &['Ạ']), ('Ả', &['ả']), ('ả', &[ + 'Ả']), ('Ấ', &['ấ']), ('ấ', &['Ấ']), ('Ầ', &['ầ']), ('ầ', &[ + 'Ầ']), ('Ẩ', &['ẩ']), ('ẩ', &['Ẩ']), ('Ẫ', &['ẫ']), ('ẫ', &[ + 'Ẫ']), ('Ậ', &['ậ']), ('ậ', &['Ậ']), ('Ắ', &['ắ']), ('ắ', &[ + 'Ắ']), ('Ằ', &['ằ']), ('ằ', &['Ằ']), ('Ẳ', &['ẳ']), ('ẳ', &[ + 'Ẳ']), ('Ẵ', &['ẵ']), ('ẵ', &['Ẵ']), ('Ặ', &['ặ']), ('ặ', &[ + 'Ặ']), ('Ẹ', &['ẹ']), ('ẹ', &['Ẹ']), ('Ẻ', &['ẻ']), ('ẻ', &[ + 'Ẻ']), ('Ẽ', &['ẽ']), ('ẽ', &['Ẽ']), ('Ế', &['ế']), ('ế', &[ + 'Ế']), ('Ề', &['ề']), ('ề', &['Ề']), ('Ể', &['ể']), ('ể', &[ + 'Ể']), ('Ễ', &['ễ']), ('ễ', &['Ễ']), ('Ệ', &['ệ']), ('ệ', &[ + 'Ệ']), ('Ỉ', &['ỉ']), ('ỉ', &['Ỉ']), ('Ị', &['ị']), ('ị', &[ + 'Ị']), ('Ọ', &['ọ']), ('ọ', &['Ọ']), ('Ỏ', &['ỏ']), ('ỏ', &[ + 'Ỏ']), ('Ố', &['ố']), ('ố', &['Ố']), ('Ồ', &['ồ']), ('ồ', &[ + 'Ồ']), ('Ổ', &['ổ']), ('ổ', &['Ổ']), ('Ỗ', &['ỗ']), ('ỗ', &[ + 'Ỗ']), ('Ộ', &['ộ']), ('ộ', &['Ộ']), ('Ớ', &['ớ']), ('ớ', &[ + 'Ớ']), ('Ờ', &['ờ']), ('ờ', &['Ờ']), ('Ở', &['ở']), ('ở', &[ + 'Ở']), ('Ỡ', &['ỡ']), ('ỡ', &['Ỡ']), ('Ợ', &['ợ']), ('ợ', &[ + 'Ợ']), ('Ụ', &['ụ']), ('ụ', &['Ụ']), ('Ủ', &['ủ']), ('ủ', &[ + 'Ủ']), ('Ứ', &['ứ']), ('ứ', &['Ứ']), ('Ừ', &['ừ']), ('ừ', &[ + 'Ừ']), ('Ử', &['ử']), ('ử', &['Ử']), ('Ữ', &['ữ']), ('ữ', &[ + 'Ữ']), ('Ự', &['ự']), ('ự', &['Ự']), ('Ỳ', &['ỳ']), ('ỳ', &[ + 'Ỳ']), ('Ỵ', &['ỵ']), ('ỵ', &['Ỵ']), ('Ỷ', &['ỷ']), ('ỷ', &[ + 'Ỷ']), ('Ỹ', &['ỹ']), ('ỹ', &['Ỹ']), ('Ỻ', &['ỻ']), ('ỻ', &[ + 'Ỻ']), ('Ỽ', &['ỽ']), ('ỽ', &['Ỽ']), ('Ỿ', &['ỿ']), ('ỿ', &[ + 'Ỿ']), ('ἀ', &['Ἀ']), ('ἁ', &['Ἁ']), ('ἂ', &['Ἂ']), ('ἃ', &[ + 'Ἃ']), ('ἄ', &['Ἄ']), ('ἅ', &['Ἅ']), ('ἆ', &['Ἆ']), ('ἇ', &[ + 'Ἇ']), ('Ἀ', &['ἀ']), ('Ἁ', &['ἁ']), ('Ἂ', &['ἂ']), ('Ἃ', &[ + 'ἃ']), ('Ἄ', &['ἄ']), ('Ἅ', &['ἅ']), ('Ἆ', &['ἆ']), ('Ἇ', &[ + 'ἇ']), ('ἐ', &['Ἐ']), ('ἑ', &['Ἑ']), ('ἒ', &['Ἒ']), ('ἓ', &[ + 'Ἓ']), ('ἔ', &['Ἔ']), ('ἕ', &['Ἕ']), ('Ἐ', &['ἐ']), ('Ἑ', &[ + 'ἑ']), ('Ἒ', &['ἒ']), ('Ἓ', &['ἓ']), ('Ἔ', &['ἔ']), ('Ἕ', &[ + 'ἕ']), ('ἠ', &['Ἠ']), ('ἡ', &['Ἡ']), ('ἢ', &['Ἢ']), ('ἣ', &[ + 'Ἣ']), ('ἤ', &['Ἤ']), ('ἥ', &['Ἥ']), ('ἦ', &['Ἦ']), ('ἧ', &[ + 'Ἧ']), ('Ἠ', &['ἠ']), ('Ἡ', &['ἡ']), ('Ἢ', &['ἢ']), ('Ἣ', &[ + 'ἣ']), ('Ἤ', &['ἤ']), ('Ἥ', &['ἥ']), ('Ἦ', &['ἦ']), ('Ἧ', &[ + 'ἧ']), ('ἰ', &['Ἰ']), ('ἱ', &['Ἱ']), ('ἲ', &['Ἲ']), ('ἳ', &[ + 'Ἳ']), ('ἴ', &['Ἴ']), ('ἵ', &['Ἵ']), ('ἶ', &['Ἶ']), ('ἷ', &[ + 'Ἷ']), ('Ἰ', &['ἰ']), ('Ἱ', &['ἱ']), ('Ἲ', &['ἲ']), ('Ἳ', &[ + 'ἳ']), ('Ἴ', &['ἴ']), ('Ἵ', &['ἵ']), ('Ἶ', &['ἶ']), ('Ἷ', &[ + 'ἷ']), ('ὀ', &['Ὀ']), ('ὁ', &['Ὁ']), ('ὂ', &['Ὂ']), ('ὃ', &[ + 'Ὃ']), ('ὄ', &['Ὄ']), ('ὅ', &['Ὅ']), ('Ὀ', &['ὀ']), ('Ὁ', &[ + 'ὁ']), ('Ὂ', &['ὂ']), ('Ὃ', &['ὃ']), ('Ὄ', &['ὄ']), ('Ὅ', &[ + 'ὅ']), ('ὑ', &['Ὑ']), ('ὓ', &['Ὓ']), ('ὕ', &['Ὕ']), ('ὗ', &[ + 'Ὗ']), ('Ὑ', &['ὑ']), ('Ὓ', &['ὓ']), ('Ὕ', &['ὕ']), ('Ὗ', &[ + 'ὗ']), ('ὠ', &['Ὠ']), ('ὡ', &['Ὡ']), ('ὢ', &['Ὢ']), ('ὣ', &[ + 'Ὣ']), ('ὤ', &['Ὤ']), ('ὥ', &['Ὥ']), ('ὦ', &['Ὦ']), ('ὧ', &[ + 'Ὧ']), ('Ὠ', &['ὠ']), ('Ὡ', &['ὡ']), ('Ὢ', &['ὢ']), ('Ὣ', &[ + 'ὣ']), ('Ὤ', &['ὤ']), ('Ὥ', &['ὥ']), ('Ὦ', &['ὦ']), ('Ὧ', &[ + 'ὧ']), ('ὰ', &['Ὰ']), ('ά', &['Ά']), ('ὲ', &['Ὲ']), ('έ', &[ + 'Έ']), ('ὴ', &['Ὴ']), ('ή', &['Ή']), ('ὶ', &['Ὶ']), ('ί', &[ + 'Ί']), ('ὸ', &['Ὸ']), ('ό', &['Ό']), ('ὺ', &['Ὺ']), ('ύ', &[ + 'Ύ']), ('ὼ', &['Ὼ']), ('ώ', &['Ώ']), ('ᾀ', &['ᾈ']), ('ᾁ', &[ + 'ᾉ']), ('ᾂ', &['ᾊ']), ('ᾃ', &['ᾋ']), ('ᾄ', &['ᾌ']), ('ᾅ', &[ + 'ᾍ']), ('ᾆ', &['ᾎ']), ('ᾇ', &['ᾏ']), ('ᾈ', &['ᾀ']), ('ᾉ', &[ + 'ᾁ']), ('ᾊ', &['ᾂ']), ('ᾋ', &['ᾃ']), ('ᾌ', &['ᾄ']), ('ᾍ', &[ + 'ᾅ']), ('ᾎ', &['ᾆ']), ('ᾏ', &['ᾇ']), ('ᾐ', &['ᾘ']), ('ᾑ', &[ + 'ᾙ']), ('ᾒ', &['ᾚ']), ('ᾓ', &['ᾛ']), ('ᾔ', &['ᾜ']), ('ᾕ', &[ + 'ᾝ']), ('ᾖ', &['ᾞ']), ('ᾗ', &['ᾟ']), ('ᾘ', &['ᾐ']), ('ᾙ', &[ + 'ᾑ']), ('ᾚ', &['ᾒ']), ('ᾛ', &['ᾓ']), ('ᾜ', &['ᾔ']), ('ᾝ', &[ + 'ᾕ']), ('ᾞ', &['ᾖ']), ('ᾟ', &['ᾗ']), ('ᾠ', &['ᾨ']), ('ᾡ', &[ + 'ᾩ']), ('ᾢ', &['ᾪ']), ('ᾣ', &['ᾫ']), ('ᾤ', &['ᾬ']), ('ᾥ', &[ + 'ᾭ']), ('ᾦ', &['ᾮ']), ('ᾧ', &['ᾯ']), ('ᾨ', &['ᾠ']), ('ᾩ', &[ + 'ᾡ']), ('ᾪ', &['ᾢ']), ('ᾫ', &['ᾣ']), ('ᾬ', &['ᾤ']), ('ᾭ', &[ + 'ᾥ']), ('ᾮ', &['ᾦ']), ('ᾯ', &['ᾧ']), ('ᾰ', &['Ᾰ']), ('ᾱ', &[ + 'Ᾱ']), ('ᾳ', &['ᾼ']), ('Ᾰ', &['ᾰ']), ('Ᾱ', &['ᾱ']), ('Ὰ', &[ + 'ὰ']), ('Ά', &['ά']), ('ᾼ', &['ᾳ']), ('ι', &['ͅ', 'Ι', 'ι', + ]), ('ῃ', &['ῌ']), ('Ὲ', &['ὲ']), ('Έ', &['έ']), ('Ὴ', &['ὴ' + ]), ('Ή', &['ή']), ('ῌ', &['ῃ']), ('ῐ', &['Ῐ']), ('ῑ', &['Ῑ' + ]), ('Ῐ', &['ῐ']), ('Ῑ', &['ῑ']), ('Ὶ', &['ὶ']), ('Ί', &['ί' + ]), ('ῠ', &['Ῠ']), ('ῡ', &['Ῡ']), ('ῥ', &['Ῥ']), ('Ῠ', &['ῠ' + ]), ('Ῡ', &['ῡ']), ('Ὺ', &['ὺ']), ('Ύ', &['ύ']), ('Ῥ', &['ῥ' + ]), ('ῳ', &['ῼ']), ('Ὸ', &['ὸ']), ('Ό', &['ό']), ('Ὼ', &['ὼ' + ]), ('Ώ', &['ώ']), ('ῼ', &['ῳ']), ('Ω', &['Ω', 'ω', ]), + ('K', &['K', 'k', ]), ('Å', &['Å', 'å', ]), ('Ⅎ', &['ⅎ']), + ('ⅎ', &['Ⅎ']), ('Ⅰ', &['ⅰ']), ('Ⅱ', &['ⅱ']), ('Ⅲ', &['ⅲ']), + ('Ⅳ', &['ⅳ']), ('Ⅴ', &['ⅴ']), ('Ⅵ', &['ⅵ']), ('Ⅶ', &['ⅶ']), + ('Ⅷ', &['ⅷ']), ('Ⅸ', &['ⅸ']), ('Ⅹ', &['ⅹ']), ('Ⅺ', &['ⅺ']), + ('Ⅻ', &['ⅻ']), ('Ⅼ', &['ⅼ']), ('Ⅽ', &['ⅽ']), ('Ⅾ', &['ⅾ']), + ('Ⅿ', &['ⅿ']), ('ⅰ', &['Ⅰ']), ('ⅱ', &['Ⅱ']), ('ⅲ', &['Ⅲ']), + ('ⅳ', &['Ⅳ']), ('ⅴ', &['Ⅴ']), ('ⅵ', &['Ⅵ']), ('ⅶ', &['Ⅶ']), + ('ⅷ', &['Ⅷ']), ('ⅸ', &['Ⅸ']), ('ⅹ', &['Ⅹ']), ('ⅺ', &['Ⅺ']), + ('ⅻ', &['Ⅻ']), ('ⅼ', &['Ⅼ']), ('ⅽ', &['Ⅽ']), ('ⅾ', &['Ⅾ']), + ('ⅿ', &['Ⅿ']), ('Ↄ', &['ↄ']), ('ↄ', &['Ↄ']), ('Ⓐ', &['ⓐ']), + ('Ⓑ', &['ⓑ']), ('Ⓒ', &['ⓒ']), ('Ⓓ', &['ⓓ']), ('Ⓔ', &['ⓔ']), + ('Ⓕ', &['ⓕ']), ('Ⓖ', &['ⓖ']), ('Ⓗ', &['ⓗ']), ('Ⓘ', &['ⓘ']), + ('Ⓙ', &['ⓙ']), ('Ⓚ', &['ⓚ']), ('Ⓛ', &['ⓛ']), ('Ⓜ', &['ⓜ']), + ('Ⓝ', &['ⓝ']), ('Ⓞ', &['ⓞ']), ('Ⓟ', &['ⓟ']), ('Ⓠ', &['ⓠ']), + ('Ⓡ', &['ⓡ']), ('Ⓢ', &['ⓢ']), ('Ⓣ', &['ⓣ']), ('Ⓤ', &['ⓤ']), + ('Ⓥ', &['ⓥ']), ('Ⓦ', &['ⓦ']), ('Ⓧ', &['ⓧ']), ('Ⓨ', &['ⓨ']), + ('Ⓩ', &['ⓩ']), ('ⓐ', &['Ⓐ']), ('ⓑ', &['Ⓑ']), ('ⓒ', &['Ⓒ']), + ('ⓓ', &['Ⓓ']), ('ⓔ', &['Ⓔ']), ('ⓕ', &['Ⓕ']), ('ⓖ', &['Ⓖ']), + ('ⓗ', &['Ⓗ']), ('ⓘ', &['Ⓘ']), ('ⓙ', &['Ⓙ']), ('ⓚ', &['Ⓚ']), + ('ⓛ', &['Ⓛ']), ('ⓜ', &['Ⓜ']), ('ⓝ', &['Ⓝ']), ('ⓞ', &['Ⓞ']), + ('ⓟ', &['Ⓟ']), ('ⓠ', &['Ⓠ']), ('ⓡ', &['Ⓡ']), ('ⓢ', &['Ⓢ']), + ('ⓣ', &['Ⓣ']), ('ⓤ', &['Ⓤ']), ('ⓥ', &['Ⓥ']), ('ⓦ', &['Ⓦ']), + ('ⓧ', &['Ⓧ']), ('ⓨ', &['Ⓨ']), ('ⓩ', &['Ⓩ']), ('Ⰰ', &['ⰰ']), + ('Ⰱ', &['ⰱ']), ('Ⰲ', &['ⰲ']), ('Ⰳ', &['ⰳ']), ('Ⰴ', &['ⰴ']), + ('Ⰵ', &['ⰵ']), ('Ⰶ', &['ⰶ']), ('Ⰷ', &['ⰷ']), ('Ⰸ', &['ⰸ']), + ('Ⰹ', &['ⰹ']), ('Ⰺ', &['ⰺ']), ('Ⰻ', &['ⰻ']), ('Ⰼ', &['ⰼ']), + ('Ⰽ', &['ⰽ']), ('Ⰾ', &['ⰾ']), ('Ⰿ', &['ⰿ']), ('Ⱀ', &['ⱀ']), + ('Ⱁ', &['ⱁ']), ('Ⱂ', &['ⱂ']), ('Ⱃ', &['ⱃ']), ('Ⱄ', &['ⱄ']), + ('Ⱅ', &['ⱅ']), ('Ⱆ', &['ⱆ']), ('Ⱇ', &['ⱇ']), ('Ⱈ', &['ⱈ']), + ('Ⱉ', &['ⱉ']), ('Ⱊ', &['ⱊ']), ('Ⱋ', &['ⱋ']), ('Ⱌ', &['ⱌ']), + ('Ⱍ', &['ⱍ']), ('Ⱎ', &['ⱎ']), ('Ⱏ', &['ⱏ']), ('Ⱐ', &['ⱐ']), + ('Ⱑ', &['ⱑ']), ('Ⱒ', &['ⱒ']), ('Ⱓ', &['ⱓ']), ('Ⱔ', &['ⱔ']), + ('Ⱕ', &['ⱕ']), ('Ⱖ', &['ⱖ']), ('Ⱗ', &['ⱗ']), ('Ⱘ', &['ⱘ']), + ('Ⱙ', &['ⱙ']), ('Ⱚ', &['ⱚ']), ('Ⱛ', &['ⱛ']), ('Ⱜ', &['ⱜ']), + ('Ⱝ', &['ⱝ']), ('Ⱞ', &['ⱞ']), ('ⰰ', &['Ⰰ']), ('ⰱ', &['Ⰱ']), + ('ⰲ', &['Ⰲ']), ('ⰳ', &['Ⰳ']), ('ⰴ', &['Ⰴ']), ('ⰵ', &['Ⰵ']), + ('ⰶ', &['Ⰶ']), ('ⰷ', &['Ⰷ']), ('ⰸ', &['Ⰸ']), ('ⰹ', &['Ⰹ']), + ('ⰺ', &['Ⰺ']), ('ⰻ', &['Ⰻ']), ('ⰼ', &['Ⰼ']), ('ⰽ', &['Ⰽ']), + ('ⰾ', &['Ⰾ']), ('ⰿ', &['Ⰿ']), ('ⱀ', &['Ⱀ']), ('ⱁ', &['Ⱁ']), + ('ⱂ', &['Ⱂ']), ('ⱃ', &['Ⱃ']), ('ⱄ', &['Ⱄ']), ('ⱅ', &['Ⱅ']), + ('ⱆ', &['Ⱆ']), ('ⱇ', &['Ⱇ']), ('ⱈ', &['Ⱈ']), ('ⱉ', &['Ⱉ']), + ('ⱊ', &['Ⱊ']), ('ⱋ', &['Ⱋ']), ('ⱌ', &['Ⱌ']), ('ⱍ', &['Ⱍ']), + ('ⱎ', &['Ⱎ']), ('ⱏ', &['Ⱏ']), ('ⱐ', &['Ⱐ']), ('ⱑ', &['Ⱑ']), + ('ⱒ', &['Ⱒ']), ('ⱓ', &['Ⱓ']), ('ⱔ', &['Ⱔ']), ('ⱕ', &['Ⱕ']), + ('ⱖ', &['Ⱖ']), ('ⱗ', &['Ⱗ']), ('ⱘ', &['Ⱘ']), ('ⱙ', &['Ⱙ']), + ('ⱚ', &['Ⱚ']), ('ⱛ', &['Ⱛ']), ('ⱜ', &['Ⱜ']), ('ⱝ', &['Ⱝ']), + ('ⱞ', &['Ⱞ']), ('Ⱡ', &['ⱡ']), ('ⱡ', &['Ⱡ']), ('Ɫ', &['ɫ']), + ('Ᵽ', &['ᵽ']), ('Ɽ', &['ɽ']), ('ⱥ', &['Ⱥ']), ('ⱦ', &['Ⱦ']), + ('Ⱨ', &['ⱨ']), ('ⱨ', &['Ⱨ']), ('Ⱪ', &['ⱪ']), ('ⱪ', &['Ⱪ']), + ('Ⱬ', &['ⱬ']), ('ⱬ', &['Ⱬ']), ('Ɑ', &['ɑ']), ('Ɱ', &['ɱ']), + ('Ɐ', &['ɐ']), ('Ɒ', &['ɒ']), ('Ⱳ', &['ⱳ']), ('ⱳ', &['Ⱳ']), + ('Ⱶ', &['ⱶ']), ('ⱶ', &['Ⱶ']), ('Ȿ', &['ȿ']), ('Ɀ', &['ɀ']), + ('Ⲁ', &['ⲁ']), ('ⲁ', &['Ⲁ']), ('Ⲃ', &['ⲃ']), ('ⲃ', &['Ⲃ']), + ('Ⲅ', &['ⲅ']), ('ⲅ', &['Ⲅ']), ('Ⲇ', &['ⲇ']), ('ⲇ', &['Ⲇ']), + ('Ⲉ', &['ⲉ']), ('ⲉ', &['Ⲉ']), ('Ⲋ', &['ⲋ']), ('ⲋ', &['Ⲋ']), + ('Ⲍ', &['ⲍ']), ('ⲍ', &['Ⲍ']), ('Ⲏ', &['ⲏ']), ('ⲏ', &['Ⲏ']), + ('Ⲑ', &['ⲑ']), ('ⲑ', &['Ⲑ']), ('Ⲓ', &['ⲓ']), ('ⲓ', &['Ⲓ']), + ('Ⲕ', &['ⲕ']), ('ⲕ', &['Ⲕ']), ('Ⲗ', &['ⲗ']), ('ⲗ', &['Ⲗ']), + ('Ⲙ', &['ⲙ']), ('ⲙ', &['Ⲙ']), ('Ⲛ', &['ⲛ']), ('ⲛ', &['Ⲛ']), + ('Ⲝ', &['ⲝ']), ('ⲝ', &['Ⲝ']), ('Ⲟ', &['ⲟ']), ('ⲟ', &['Ⲟ']), + ('Ⲡ', &['ⲡ']), ('ⲡ', &['Ⲡ']), ('Ⲣ', &['ⲣ']), ('ⲣ', &['Ⲣ']), + ('Ⲥ', &['ⲥ']), ('ⲥ', &['Ⲥ']), ('Ⲧ', &['ⲧ']), ('ⲧ', &['Ⲧ']), + ('Ⲩ', &['ⲩ']), ('ⲩ', &['Ⲩ']), ('Ⲫ', &['ⲫ']), ('ⲫ', &['Ⲫ']), + ('Ⲭ', &['ⲭ']), ('ⲭ', &['Ⲭ']), ('Ⲯ', &['ⲯ']), ('ⲯ', &['Ⲯ']), + ('Ⲱ', &['ⲱ']), ('ⲱ', &['Ⲱ']), ('Ⲳ', &['ⲳ']), ('ⲳ', &['Ⲳ']), + ('Ⲵ', &['ⲵ']), ('ⲵ', &['Ⲵ']), ('Ⲷ', &['ⲷ']), ('ⲷ', &['Ⲷ']), + ('Ⲹ', &['ⲹ']), ('ⲹ', &['Ⲹ']), ('Ⲻ', &['ⲻ']), ('ⲻ', &['Ⲻ']), + ('Ⲽ', &['ⲽ']), ('ⲽ', &['Ⲽ']), ('Ⲿ', &['ⲿ']), ('ⲿ', &['Ⲿ']), + ('Ⳁ', &['ⳁ']), ('ⳁ', &['Ⳁ']), ('Ⳃ', &['ⳃ']), ('ⳃ', &['Ⳃ']), + ('Ⳅ', &['ⳅ']), ('ⳅ', &['Ⳅ']), ('Ⳇ', &['ⳇ']), ('ⳇ', &['Ⳇ']), + ('Ⳉ', &['ⳉ']), ('ⳉ', &['Ⳉ']), ('Ⳋ', &['ⳋ']), ('ⳋ', &['Ⳋ']), + ('Ⳍ', &['ⳍ']), ('ⳍ', &['Ⳍ']), ('Ⳏ', &['ⳏ']), ('ⳏ', &['Ⳏ']), + ('Ⳑ', &['ⳑ']), ('ⳑ', &['Ⳑ']), ('Ⳓ', &['ⳓ']), ('ⳓ', &['Ⳓ']), + ('Ⳕ', &['ⳕ']), ('ⳕ', &['Ⳕ']), ('Ⳗ', &['ⳗ']), ('ⳗ', &['Ⳗ']), + ('Ⳙ', &['ⳙ']), ('ⳙ', &['Ⳙ']), ('Ⳛ', &['ⳛ']), ('ⳛ', &['Ⳛ']), + ('Ⳝ', &['ⳝ']), ('ⳝ', &['Ⳝ']), ('Ⳟ', &['ⳟ']), ('ⳟ', &['Ⳟ']), + ('Ⳡ', &['ⳡ']), ('ⳡ', &['Ⳡ']), ('Ⳣ', &['ⳣ']), ('ⳣ', &['Ⳣ']), + ('Ⳬ', &['ⳬ']), ('ⳬ', &['Ⳬ']), ('Ⳮ', &['ⳮ']), ('ⳮ', &['Ⳮ']), + ('Ⳳ', &['ⳳ']), ('ⳳ', &['Ⳳ']), ('ⴀ', &['Ⴀ']), ('ⴁ', &['Ⴁ']), + ('ⴂ', &['Ⴂ']), ('ⴃ', &['Ⴃ']), ('ⴄ', &['Ⴄ']), ('ⴅ', &['Ⴅ']), + ('ⴆ', &['Ⴆ']), ('ⴇ', &['Ⴇ']), ('ⴈ', &['Ⴈ']), ('ⴉ', &['Ⴉ']), + ('ⴊ', &['Ⴊ']), ('ⴋ', &['Ⴋ']), ('ⴌ', &['Ⴌ']), ('ⴍ', &['Ⴍ']), + ('ⴎ', &['Ⴎ']), ('ⴏ', &['Ⴏ']), ('ⴐ', &['Ⴐ']), ('ⴑ', &['Ⴑ']), + ('ⴒ', &['Ⴒ']), ('ⴓ', &['Ⴓ']), ('ⴔ', &['Ⴔ']), ('ⴕ', &['Ⴕ']), + ('ⴖ', &['Ⴖ']), ('ⴗ', &['Ⴗ']), ('ⴘ', &['Ⴘ']), ('ⴙ', &['Ⴙ']), + ('ⴚ', &['Ⴚ']), ('ⴛ', &['Ⴛ']), ('ⴜ', &['Ⴜ']), ('ⴝ', &['Ⴝ']), + ('ⴞ', &['Ⴞ']), ('ⴟ', &['Ⴟ']), ('ⴠ', &['Ⴠ']), ('ⴡ', &['Ⴡ']), + ('ⴢ', &['Ⴢ']), ('ⴣ', &['Ⴣ']), ('ⴤ', &['Ⴤ']), ('ⴥ', &['Ⴥ']), + ('ⴧ', &['Ⴧ']), ('ⴭ', &['Ⴭ']), ('Ꙁ', &['ꙁ']), ('ꙁ', &['Ꙁ']), + ('Ꙃ', &['ꙃ']), ('ꙃ', &['Ꙃ']), ('Ꙅ', &['ꙅ']), ('ꙅ', &['Ꙅ']), + ('Ꙇ', &['ꙇ']), ('ꙇ', &['Ꙇ']), ('Ꙉ', &['ꙉ']), ('ꙉ', &['Ꙉ']), + ('Ꙋ', &['ᲈ', 'ꙋ', ]), ('ꙋ', &['ᲈ', 'Ꙋ', ]), ('Ꙍ', &['ꙍ']), + ('ꙍ', &['Ꙍ']), ('Ꙏ', &['ꙏ']), ('ꙏ', &['Ꙏ']), ('Ꙑ', &['ꙑ']), + ('ꙑ', &['Ꙑ']), ('Ꙓ', &['ꙓ']), ('ꙓ', &['Ꙓ']), ('Ꙕ', &['ꙕ']), + ('ꙕ', &['Ꙕ']), ('Ꙗ', &['ꙗ']), ('ꙗ', &['Ꙗ']), ('Ꙙ', &['ꙙ']), + ('ꙙ', &['Ꙙ']), ('Ꙛ', &['ꙛ']), ('ꙛ', &['Ꙛ']), ('Ꙝ', &['ꙝ']), + ('ꙝ', &['Ꙝ']), ('Ꙟ', &['ꙟ']), ('ꙟ', &['Ꙟ']), ('Ꙡ', &['ꙡ']), + ('ꙡ', &['Ꙡ']), ('Ꙣ', &['ꙣ']), ('ꙣ', &['Ꙣ']), ('Ꙥ', &['ꙥ']), + ('ꙥ', &['Ꙥ']), ('Ꙧ', &['ꙧ']), ('ꙧ', &['Ꙧ']), ('Ꙩ', &['ꙩ']), + ('ꙩ', &['Ꙩ']), ('Ꙫ', &['ꙫ']), ('ꙫ', &['Ꙫ']), ('Ꙭ', &['ꙭ']), + ('ꙭ', &['Ꙭ']), ('Ꚁ', &['ꚁ']), ('ꚁ', &['Ꚁ']), ('Ꚃ', &['ꚃ']), + ('ꚃ', &['Ꚃ']), ('Ꚅ', &['ꚅ']), ('ꚅ', &['Ꚅ']), ('Ꚇ', &['ꚇ']), + ('ꚇ', &['Ꚇ']), ('Ꚉ', &['ꚉ']), ('ꚉ', &['Ꚉ']), ('Ꚋ', &['ꚋ']), + ('ꚋ', &['Ꚋ']), ('Ꚍ', &['ꚍ']), ('ꚍ', &['Ꚍ']), ('Ꚏ', &['ꚏ']), + ('ꚏ', &['Ꚏ']), ('Ꚑ', &['ꚑ']), ('ꚑ', &['Ꚑ']), ('Ꚓ', &['ꚓ']), + ('ꚓ', &['Ꚓ']), ('Ꚕ', &['ꚕ']), ('ꚕ', &['Ꚕ']), ('Ꚗ', &['ꚗ']), + ('ꚗ', &['Ꚗ']), ('Ꚙ', &['ꚙ']), ('ꚙ', &['Ꚙ']), ('Ꚛ', &['ꚛ']), + ('ꚛ', &['Ꚛ']), ('Ꜣ', &['ꜣ']), ('ꜣ', &['Ꜣ']), ('Ꜥ', &['ꜥ']), + ('ꜥ', &['Ꜥ']), ('Ꜧ', &['ꜧ']), ('ꜧ', &['Ꜧ']), ('Ꜩ', &['ꜩ']), + ('ꜩ', &['Ꜩ']), ('Ꜫ', &['ꜫ']), ('ꜫ', &['Ꜫ']), ('Ꜭ', &['ꜭ']), + ('ꜭ', &['Ꜭ']), ('Ꜯ', &['ꜯ']), ('ꜯ', &['Ꜯ']), ('Ꜳ', &['ꜳ']), + ('ꜳ', &['Ꜳ']), ('Ꜵ', &['ꜵ']), ('ꜵ', &['Ꜵ']), ('Ꜷ', &['ꜷ']), + ('ꜷ', &['Ꜷ']), ('Ꜹ', &['ꜹ']), ('ꜹ', &['Ꜹ']), ('Ꜻ', &['ꜻ']), + ('ꜻ', &['Ꜻ']), ('Ꜽ', &['ꜽ']), ('ꜽ', &['Ꜽ']), ('Ꜿ', &['ꜿ']), + ('ꜿ', &['Ꜿ']), ('Ꝁ', &['ꝁ']), ('ꝁ', &['Ꝁ']), ('Ꝃ', &['ꝃ']), + ('ꝃ', &['Ꝃ']), ('Ꝅ', &['ꝅ']), ('ꝅ', &['Ꝅ']), ('Ꝇ', &['ꝇ']), + ('ꝇ', &['Ꝇ']), ('Ꝉ', &['ꝉ']), ('ꝉ', &['Ꝉ']), ('Ꝋ', &['ꝋ']), + ('ꝋ', &['Ꝋ']), ('Ꝍ', &['ꝍ']), ('ꝍ', &['Ꝍ']), ('Ꝏ', &['ꝏ']), + ('ꝏ', &['Ꝏ']), ('Ꝑ', &['ꝑ']), ('ꝑ', &['Ꝑ']), ('Ꝓ', &['ꝓ']), + ('ꝓ', &['Ꝓ']), ('Ꝕ', &['ꝕ']), ('ꝕ', &['Ꝕ']), ('Ꝗ', &['ꝗ']), + ('ꝗ', &['Ꝗ']), ('Ꝙ', &['ꝙ']), ('ꝙ', &['Ꝙ']), ('Ꝛ', &['ꝛ']), + ('ꝛ', &['Ꝛ']), ('Ꝝ', &['ꝝ']), ('ꝝ', &['Ꝝ']), ('Ꝟ', &['ꝟ']), + ('ꝟ', &['Ꝟ']), ('Ꝡ', &['ꝡ']), ('ꝡ', &['Ꝡ']), ('Ꝣ', &['ꝣ']), + ('ꝣ', &['Ꝣ']), ('Ꝥ', &['ꝥ']), ('ꝥ', &['Ꝥ']), ('Ꝧ', &['ꝧ']), + ('ꝧ', &['Ꝧ']), ('Ꝩ', &['ꝩ']), ('ꝩ', &['Ꝩ']), ('Ꝫ', &['ꝫ']), + ('ꝫ', &['Ꝫ']), ('Ꝭ', &['ꝭ']), ('ꝭ', &['Ꝭ']), ('Ꝯ', &['ꝯ']), + ('ꝯ', &['Ꝯ']), ('Ꝺ', &['ꝺ']), ('ꝺ', &['Ꝺ']), ('Ꝼ', &['ꝼ']), + ('ꝼ', &['Ꝼ']), ('Ᵹ', &['ᵹ']), ('Ꝿ', &['ꝿ']), ('ꝿ', &['Ꝿ']), + ('Ꞁ', &['ꞁ']), ('ꞁ', &['Ꞁ']), ('Ꞃ', &['ꞃ']), ('ꞃ', &['Ꞃ']), + ('Ꞅ', &['ꞅ']), ('ꞅ', &['Ꞅ']), ('Ꞇ', &['ꞇ']), ('ꞇ', &['Ꞇ']), + ('Ꞌ', &['ꞌ']), ('ꞌ', &['Ꞌ']), ('Ɥ', &['ɥ']), ('Ꞑ', &['ꞑ']), + ('ꞑ', &['Ꞑ']), ('Ꞓ', &['ꞓ']), ('ꞓ', &['Ꞓ']), ('Ꞗ', &['ꞗ']), + ('ꞗ', &['Ꞗ']), ('Ꞙ', &['ꞙ']), ('ꞙ', &['Ꞙ']), ('Ꞛ', &['ꞛ']), + ('ꞛ', &['Ꞛ']), ('Ꞝ', &['ꞝ']), ('ꞝ', &['Ꞝ']), ('Ꞟ', &['ꞟ']), + ('ꞟ', &['Ꞟ']), ('Ꞡ', &['ꞡ']), ('ꞡ', &['Ꞡ']), ('Ꞣ', &['ꞣ']), + ('ꞣ', &['Ꞣ']), ('Ꞥ', &['ꞥ']), ('ꞥ', &['Ꞥ']), ('Ꞧ', &['ꞧ']), + ('ꞧ', &['Ꞧ']), ('Ꞩ', &['ꞩ']), ('ꞩ', &['Ꞩ']), ('Ɦ', &['ɦ']), + ('Ɜ', &['ɜ']), ('Ɡ', &['ɡ']), ('Ɬ', &['ɬ']), ('Ɪ', &['ɪ']), + ('Ʞ', &['ʞ']), ('Ʇ', &['ʇ']), ('Ʝ', &['ʝ']), ('Ꭓ', &['ꭓ']), + ('Ꞵ', &['ꞵ']), ('ꞵ', &['Ꞵ']), ('Ꞷ', &['ꞷ']), ('ꞷ', &['Ꞷ']), + ('ꭓ', &['Ꭓ']), ('ꭰ', &['Ꭰ']), ('ꭱ', &['Ꭱ']), ('ꭲ', &['Ꭲ']), + ('ꭳ', &['Ꭳ']), ('ꭴ', &['Ꭴ']), ('ꭵ', &['Ꭵ']), ('ꭶ', &['Ꭶ']), + ('ꭷ', &['Ꭷ']), ('ꭸ', &['Ꭸ']), ('ꭹ', &['Ꭹ']), ('ꭺ', &['Ꭺ']), + ('ꭻ', &['Ꭻ']), ('ꭼ', &['Ꭼ']), ('ꭽ', &['Ꭽ']), ('ꭾ', &['Ꭾ']), + ('ꭿ', &['Ꭿ']), ('ꮀ', &['Ꮀ']), ('ꮁ', &['Ꮁ']), ('ꮂ', &['Ꮂ']), + ('ꮃ', &['Ꮃ']), ('ꮄ', &['Ꮄ']), ('ꮅ', &['Ꮅ']), ('ꮆ', &['Ꮆ']), + ('ꮇ', &['Ꮇ']), ('ꮈ', &['Ꮈ']), ('ꮉ', &['Ꮉ']), ('ꮊ', &['Ꮊ']), + ('ꮋ', &['Ꮋ']), ('ꮌ', &['Ꮌ']), ('ꮍ', &['Ꮍ']), ('ꮎ', &['Ꮎ']), + ('ꮏ', &['Ꮏ']), ('ꮐ', &['Ꮐ']), ('ꮑ', &['Ꮑ']), ('ꮒ', &['Ꮒ']), + ('ꮓ', &['Ꮓ']), ('ꮔ', &['Ꮔ']), ('ꮕ', &['Ꮕ']), ('ꮖ', &['Ꮖ']), + ('ꮗ', &['Ꮗ']), ('ꮘ', &['Ꮘ']), ('ꮙ', &['Ꮙ']), ('ꮚ', &['Ꮚ']), + ('ꮛ', &['Ꮛ']), ('ꮜ', &['Ꮜ']), ('ꮝ', &['Ꮝ']), ('ꮞ', &['Ꮞ']), + ('ꮟ', &['Ꮟ']), ('ꮠ', &['Ꮠ']), ('ꮡ', &['Ꮡ']), ('ꮢ', &['Ꮢ']), + ('ꮣ', &['Ꮣ']), ('ꮤ', &['Ꮤ']), ('ꮥ', &['Ꮥ']), ('ꮦ', &['Ꮦ']), + ('ꮧ', &['Ꮧ']), ('ꮨ', &['Ꮨ']), ('ꮩ', &['Ꮩ']), ('ꮪ', &['Ꮪ']), + ('ꮫ', &['Ꮫ']), ('ꮬ', &['Ꮬ']), ('ꮭ', &['Ꮭ']), ('ꮮ', &['Ꮮ']), + ('ꮯ', &['Ꮯ']), ('ꮰ', &['Ꮰ']), ('ꮱ', &['Ꮱ']), ('ꮲ', &['Ꮲ']), + ('ꮳ', &['Ꮳ']), ('ꮴ', &['Ꮴ']), ('ꮵ', &['Ꮵ']), ('ꮶ', &['Ꮶ']), + ('ꮷ', &['Ꮷ']), ('ꮸ', &['Ꮸ']), ('ꮹ', &['Ꮹ']), ('ꮺ', &['Ꮺ']), + ('ꮻ', &['Ꮻ']), ('ꮼ', &['Ꮼ']), ('ꮽ', &['Ꮽ']), ('ꮾ', &['Ꮾ']), + ('ꮿ', &['Ꮿ']), ('A', &['a']), ('B', &['b']), ('C', &['c']), + ('D', &['d']), ('E', &['e']), ('F', &['f']), ('G', &['g']), + ('H', &['h']), ('I', &['i']), ('J', &['j']), ('K', &['k']), + ('L', &['l']), ('M', &['m']), ('N', &['n']), ('O', &['o']), + ('P', &['p']), ('Q', &['q']), ('R', &['r']), ('S', &['s']), + ('T', &['t']), ('U', &['u']), ('V', &['v']), ('W', &['w']), + ('X', &['x']), ('Y', &['y']), ('Z', &['z']), ('a', &['A']), + ('b', &['B']), ('c', &['C']), ('d', &['D']), ('e', &['E']), + ('f', &['F']), ('g', &['G']), ('h', &['H']), ('i', &['I']), + ('j', &['J']), ('k', &['K']), ('l', &['L']), ('m', &['M']), + ('n', &['N']), ('o', &['O']), ('p', &['P']), ('q', &['Q']), + ('r', &['R']), ('s', &['S']), ('t', &['T']), ('u', &['U']), + ('v', &['V']), ('w', &['W']), ('x', &['X']), ('y', &['Y']), + ('z', &['Z']), ('𐐀', &['𐐨']), ('𐐁', &['𐐩']), ('𐐂', &[ + '𐐪']), ('𐐃', &['𐐫']), ('𐐄', &['𐐬']), ('𐐅', &['𐐭']), + ('𐐆', &['𐐮']), ('𐐇', &['𐐯']), ('𐐈', &['𐐰']), ('𐐉', &[ + '𐐱']), ('𐐊', &['𐐲']), ('𐐋', &['𐐳']), ('𐐌', &['𐐴']), + ('𐐍', &['𐐵']), ('𐐎', &['𐐶']), ('𐐏', &['𐐷']), ('𐐐', &[ + '𐐸']), ('𐐑', &['𐐹']), ('𐐒', &['𐐺']), ('𐐓', &['𐐻']), + ('𐐔', &['𐐼']), ('𐐕', &['𐐽']), ('𐐖', &['𐐾']), ('𐐗', &[ + '𐐿']), ('𐐘', &['𐑀']), ('𐐙', &['𐑁']), ('𐐚', &['𐑂']), + ('𐐛', &['𐑃']), ('𐐜', &['𐑄']), ('𐐝', &['𐑅']), ('𐐞', &[ + '𐑆']), ('𐐟', &['𐑇']), ('𐐠', &['𐑈']), ('𐐡', &['𐑉']), + ('𐐢', &['𐑊']), ('𐐣', &['𐑋']), ('𐐤', &['𐑌']), ('𐐥', &[ + '𐑍']), ('𐐦', &['𐑎']), ('𐐧', &['𐑏']), ('𐐨', &['𐐀']), + ('𐐩', &['𐐁']), ('𐐪', &['𐐂']), ('𐐫', &['𐐃']), ('𐐬', &[ + '𐐄']), ('𐐭', &['𐐅']), ('𐐮', &['𐐆']), ('𐐯', &['𐐇']), + ('𐐰', &['𐐈']), ('𐐱', &['𐐉']), ('𐐲', &['𐐊']), ('𐐳', &[ + '𐐋']), ('𐐴', &['𐐌']), ('𐐵', &['𐐍']), ('𐐶', &['𐐎']), + ('𐐷', &['𐐏']), ('𐐸', &['𐐐']), ('𐐹', &['𐐑']), ('𐐺', &[ + '𐐒']), ('𐐻', &['𐐓']), ('𐐼', &['𐐔']), ('𐐽', &['𐐕']), + ('𐐾', &['𐐖']), ('𐐿', &['𐐗']), ('𐑀', &['𐐘']), ('𐑁', &[ + '𐐙']), ('𐑂', &['𐐚']), ('𐑃', &['𐐛']), ('𐑄', &['𐐜']), + ('𐑅', &['𐐝']), ('𐑆', &['𐐞']), ('𐑇', &['𐐟']), ('𐑈', &[ + '𐐠']), ('𐑉', &['𐐡']), ('𐑊', &['𐐢']), ('𐑋', &['𐐣']), + ('𐑌', &['𐐤']), ('𐑍', &['𐐥']), ('𐑎', &['𐐦']), ('𐑏', &[ + '𐐧']), ('𐒰', &['𐓘']), ('𐒱', &['𐓙']), ('𐒲', &['𐓚']), + ('𐒳', &['𐓛']), ('𐒴', &['𐓜']), ('𐒵', &['𐓝']), ('𐒶', &[ + '𐓞']), ('𐒷', &['𐓟']), ('𐒸', &['𐓠']), ('𐒹', &['𐓡']), + ('𐒺', &['𐓢']), ('𐒻', &['𐓣']), ('𐒼', &['𐓤']), ('𐒽', &[ + '𐓥']), ('𐒾', &['𐓦']), ('𐒿', &['𐓧']), ('𐓀', &['𐓨']), + ('𐓁', &['𐓩']), ('𐓂', &['𐓪']), ('𐓃', &['𐓫']), ('𐓄', &[ + '𐓬']), ('𐓅', &['𐓭']), ('𐓆', &['𐓮']), ('𐓇', &['𐓯']), + ('𐓈', &['𐓰']), ('𐓉', &['𐓱']), ('𐓊', &['𐓲']), ('𐓋', &[ + '𐓳']), ('𐓌', &['𐓴']), ('𐓍', &['𐓵']), ('𐓎', &['𐓶']), + ('𐓏', &['𐓷']), ('𐓐', &['𐓸']), ('𐓑', &['𐓹']), ('𐓒', &[ + '𐓺']), ('𐓓', &['𐓻']), ('𐓘', &['𐒰']), ('𐓙', &['𐒱']), + ('𐓚', &['𐒲']), ('𐓛', &['𐒳']), ('𐓜', &['𐒴']), ('𐓝', &[ + '𐒵']), ('𐓞', &['𐒶']), ('𐓟', &['𐒷']), ('𐓠', &['𐒸']), + ('𐓡', &['𐒹']), ('𐓢', &['𐒺']), ('𐓣', &['𐒻']), ('𐓤', &[ + '𐒼']), ('𐓥', &['𐒽']), ('𐓦', &['𐒾']), ('𐓧', &['𐒿']), + ('𐓨', &['𐓀']), ('𐓩', &['𐓁']), ('𐓪', &['𐓂']), ('𐓫', &[ + '𐓃']), ('𐓬', &['𐓄']), ('𐓭', &['𐓅']), ('𐓮', &['𐓆']), + ('𐓯', &['𐓇']), ('𐓰', &['𐓈']), ('𐓱', &['𐓉']), ('𐓲', &[ + '𐓊']), ('𐓳', &['𐓋']), ('𐓴', &['𐓌']), ('𐓵', &['𐓍']), + ('𐓶', &['𐓎']), ('𐓷', &['𐓏']), ('𐓸', &['𐓐']), ('𐓹', &[ + '𐓑']), ('𐓺', &['𐓒']), ('𐓻', &['𐓓']), ('𐲀', &['𐳀']), + ('𐲁', &['𐳁']), ('𐲂', &['𐳂']), ('𐲃', &['𐳃']), ('𐲄', &[ + '𐳄']), ('𐲅', &['𐳅']), ('𐲆', &['𐳆']), ('𐲇', &['𐳇']), + ('𐲈', &['𐳈']), ('𐲉', &['𐳉']), ('𐲊', &['𐳊']), ('𐲋', &[ + '𐳋']), ('𐲌', &['𐳌']), ('𐲍', &['𐳍']), ('𐲎', &['𐳎']), + ('𐲏', &['𐳏']), ('𐲐', &['𐳐']), ('𐲑', &['𐳑']), ('𐲒', &[ + '𐳒']), ('𐲓', &['𐳓']), ('𐲔', &['𐳔']), ('𐲕', &['𐳕']), + ('𐲖', &['𐳖']), ('𐲗', &['𐳗']), ('𐲘', &['𐳘']), ('𐲙', &[ + '𐳙']), ('𐲚', &['𐳚']), ('𐲛', &['𐳛']), ('𐲜', &['𐳜']), + ('𐲝', &['𐳝']), ('𐲞', &['𐳞']), ('𐲟', &['𐳟']), ('𐲠', &[ + '𐳠']), ('𐲡', &['𐳡']), ('𐲢', &['𐳢']), ('𐲣', &['𐳣']), + ('𐲤', &['𐳤']), ('𐲥', &['𐳥']), ('𐲦', &['𐳦']), ('𐲧', &[ + '𐳧']), ('𐲨', &['𐳨']), ('𐲩', &['𐳩']), ('𐲪', &['𐳪']), + ('𐲫', &['𐳫']), ('𐲬', &['𐳬']), ('𐲭', &['𐳭']), ('𐲮', &[ + '𐳮']), ('𐲯', &['𐳯']), ('𐲰', &['𐳰']), ('𐲱', &['𐳱']), + ('𐲲', &['𐳲']), ('𐳀', &['𐲀']), ('𐳁', &['𐲁']), ('𐳂', &[ + '𐲂']), ('𐳃', &['𐲃']), ('𐳄', &['𐲄']), ('𐳅', &['𐲅']), + ('𐳆', &['𐲆']), ('𐳇', &['𐲇']), ('𐳈', &['𐲈']), ('𐳉', &[ + '𐲉']), ('𐳊', &['𐲊']), ('𐳋', &['𐲋']), ('𐳌', &['𐲌']), + ('𐳍', &['𐲍']), ('𐳎', &['𐲎']), ('𐳏', &['𐲏']), ('𐳐', &[ + '𐲐']), ('𐳑', &['𐲑']), ('𐳒', &['𐲒']), ('𐳓', &['𐲓']), + ('𐳔', &['𐲔']), ('𐳕', &['𐲕']), ('𐳖', &['𐲖']), ('𐳗', &[ + '𐲗']), ('𐳘', &['𐲘']), ('𐳙', &['𐲙']), ('𐳚', &['𐲚']), + ('𐳛', &['𐲛']), ('𐳜', &['𐲜']), ('𐳝', &['𐲝']), ('𐳞', &[ + '𐲞']), ('𐳟', &['𐲟']), ('𐳠', &['𐲠']), ('𐳡', &['𐲡']), + ('𐳢', &['𐲢']), ('𐳣', &['𐲣']), ('𐳤', &['𐲤']), ('𐳥', &[ + '𐲥']), ('𐳦', &['𐲦']), ('𐳧', &['𐲧']), ('𐳨', &['𐲨']), + ('𐳩', &['𐲩']), ('𐳪', &['𐲪']), ('𐳫', &['𐲫']), ('𐳬', &[ + '𐲬']), ('𐳭', &['𐲭']), ('𐳮', &['𐲮']), ('𐳯', &['𐲯']), + ('𐳰', &['𐲰']), ('𐳱', &['𐲱']), ('𐳲', &['𐲲']), ('𑢠', &[ + '𑣀']), ('𑢡', &['𑣁']), ('𑢢', &['𑣂']), ('𑢣', &['𑣃']), + ('𑢤', &['𑣄']), ('𑢥', &['𑣅']), ('𑢦', &['𑣆']), ('𑢧', &[ + '𑣇']), ('𑢨', &['𑣈']), ('𑢩', &['𑣉']), ('𑢪', &['𑣊']), + ('𑢫', &['𑣋']), ('𑢬', &['𑣌']), ('𑢭', &['𑣍']), ('𑢮', &[ + '𑣎']), ('𑢯', &['𑣏']), ('𑢰', &['𑣐']), ('𑢱', &['𑣑']), + ('𑢲', &['𑣒']), ('𑢳', &['𑣓']), ('𑢴', &['𑣔']), ('𑢵', &[ + '𑣕']), ('𑢶', &['𑣖']), ('𑢷', &['𑣗']), ('𑢸', &['𑣘']), + ('𑢹', &['𑣙']), ('𑢺', &['𑣚']), ('𑢻', &['𑣛']), ('𑢼', &[ + '𑣜']), ('𑢽', &['𑣝']), ('𑢾', &['𑣞']), ('𑢿', &['𑣟']), + ('𑣀', &['𑢠']), ('𑣁', &['𑢡']), ('𑣂', &['𑢢']), ('𑣃', &[ + '𑢣']), ('𑣄', &['𑢤']), ('𑣅', &['𑢥']), ('𑣆', &['𑢦']), + ('𑣇', &['𑢧']), ('𑣈', &['𑢨']), ('𑣉', &['𑢩']), ('𑣊', &[ + '𑢪']), ('𑣋', &['𑢫']), ('𑣌', &['𑢬']), ('𑣍', &['𑢭']), + ('𑣎', &['𑢮']), ('𑣏', &['𑢯']), ('𑣐', &['𑢰']), ('𑣑', &[ + '𑢱']), ('𑣒', &['𑢲']), ('𑣓', &['𑢳']), ('𑣔', &['𑢴']), + ('𑣕', &['𑢵']), ('𑣖', &['𑢶']), ('𑣗', &['𑢷']), ('𑣘', &[ + '𑢸']), ('𑣙', &['𑢹']), ('𑣚', &['𑢺']), ('𑣛', &['𑢻']), + ('𑣜', &['𑢼']), ('𑣝', &['𑢽']), ('𑣞', &['𑢾']), ('𑣟', &[ + '𑢿']), ('𞤀', &['𞤢']), ('𞤁', &['𞤣']), ('𞤂', &['𞤤']), + ('𞤃', &['𞤥']), ('𞤄', &['𞤦']), ('𞤅', &['𞤧']), ('𞤆', &[ + '𞤨']), ('𞤇', &['𞤩']), ('𞤈', &['𞤪']), ('𞤉', &['𞤫']), + ('𞤊', &['𞤬']), ('𞤋', &['𞤭']), ('𞤌', &['𞤮']), ('𞤍', &[ + '𞤯']), ('𞤎', &['𞤰']), ('𞤏', &['𞤱']), ('𞤐', &['𞤲']), + ('𞤑', &['𞤳']), ('𞤒', &['𞤴']), ('𞤓', &['𞤵']), ('𞤔', &[ + '𞤶']), ('𞤕', &['𞤷']), ('𞤖', &['𞤸']), ('𞤗', &['𞤹']), + ('𞤘', &['𞤺']), ('𞤙', &['𞤻']), ('𞤚', &['𞤼']), ('𞤛', &[ + '𞤽']), ('𞤜', &['𞤾']), ('𞤝', &['𞤿']), ('𞤞', &['𞥀']), + ('𞤟', &['𞥁']), ('𞤠', &['𞥂']), ('𞤡', &['𞥃']), ('𞤢', &[ + '𞤀']), ('𞤣', &['𞤁']), ('𞤤', &['𞤂']), ('𞤥', &['𞤃']), + ('𞤦', &['𞤄']), ('𞤧', &['𞤅']), ('𞤨', &['𞤆']), ('𞤩', &[ + '𞤇']), ('𞤪', &['𞤈']), ('𞤫', &['𞤉']), ('𞤬', &['𞤊']), + ('𞤭', &['𞤋']), ('𞤮', &['𞤌']), ('𞤯', &['𞤍']), ('𞤰', &[ + '𞤎']), ('𞤱', &['𞤏']), ('𞤲', &['𞤐']), ('𞤳', &['𞤑']), + ('𞤴', &['𞤒']), ('𞤵', &['𞤓']), ('𞤶', &['𞤔']), ('𞤷', &[ + '𞤕']), ('𞤸', &['𞤖']), ('𞤹', &['𞤗']), ('𞤺', &['𞤘']), + ('𞤻', &['𞤙']), ('𞤼', &['𞤚']), ('𞤽', &['𞤛']), ('𞤾', &[ + '𞤜']), ('𞤿', &['𞤝']), ('𞥀', &['𞤞']), ('𞥁', &['𞤟']), + ('𞥂', &['𞤠']), ('𞥃', &['𞤡']), +]; diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/general_category.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/general_category.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/general_category.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/general_category.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1844 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate general-category tmp/ucd-10.0.0/ --chars --exclude surrogate +// +// ucd-generate is available on crates.io. + +pub const BY_NAME: &'static [(&'static str, &'static [(char, char)])] = &[ + ("Cased_Letter", CASED_LETTER), ("Close_Punctuation", CLOSE_PUNCTUATION), + ("Connector_Punctuation", CONNECTOR_PUNCTUATION), ("Control", CONTROL), + ("Currency_Symbol", CURRENCY_SYMBOL), + ("Dash_Punctuation", DASH_PUNCTUATION), ("Decimal_Number", DECIMAL_NUMBER), + ("Enclosing_Mark", ENCLOSING_MARK), + ("Final_Punctuation", FINAL_PUNCTUATION), ("Format", FORMAT), + ("Initial_Punctuation", INITIAL_PUNCTUATION), ("Letter", LETTER), + ("Letter_Number", LETTER_NUMBER), ("Line_Separator", LINE_SEPARATOR), + ("Lowercase_Letter", LOWERCASE_LETTER), ("Mark", MARK), + ("Math_Symbol", MATH_SYMBOL), ("Modifier_Letter", MODIFIER_LETTER), + ("Modifier_Symbol", MODIFIER_SYMBOL), ("Nonspacing_Mark", NONSPACING_MARK), + ("Number", NUMBER), ("Open_Punctuation", OPEN_PUNCTUATION), + ("Other", OTHER), ("Other_Letter", OTHER_LETTER), + ("Other_Number", OTHER_NUMBER), ("Other_Punctuation", OTHER_PUNCTUATION), + ("Other_Symbol", OTHER_SYMBOL), + ("Paragraph_Separator", PARAGRAPH_SEPARATOR), ("Private_Use", PRIVATE_USE), + ("Punctuation", PUNCTUATION), ("Separator", SEPARATOR), + ("Space_Separator", SPACE_SEPARATOR), ("Spacing_Mark", SPACING_MARK), + ("Symbol", SYMBOL), ("Titlecase_Letter", TITLECASE_LETTER), + ("Unassigned", UNASSIGNED), ("Uppercase_Letter", UPPERCASE_LETTER), +]; + +pub const CASED_LETTER: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('µ', 'µ'), ('À', 'Ö'), ('Ø', 'ö'), + ('ø', 'ƺ'), ('Ƽ', 'ƿ'), ('DŽ', 'ʓ'), ('ʕ', 'ʯ'), ('Ͱ', 'ͳ'), + ('Ͷ', 'ͷ'), ('ͻ', 'ͽ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), + ('Ό', 'Ό'), ('Ύ', 'Ρ'), ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('Ҋ', 'ԯ'), + ('Ա', 'Ֆ'), ('ա', 'և'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᴀ', 'ᴫ'), + ('ᵫ', 'ᵷ'), ('ᵹ', 'ᶚ'), ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), + ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), + ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), + ('ᾶ', 'ᾼ'), ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), + ('ῐ', 'ΐ'), ('ῖ', 'Ί'), ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), + ('ῶ', 'ῼ'), ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), + ('ℕ', 'ℕ'), ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), ('Ω', 'Ω'), + ('ℨ', 'ℨ'), ('K', 'ℭ'), ('ℯ', 'ℴ'), ('ℹ', 'ℹ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('Ↄ', 'ↄ'), + ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⱻ'), ('Ȿ', 'ⳤ'), + ('Ⳬ', 'ⳮ'), ('Ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), + ('ⴭ', 'ⴭ'), ('Ꙁ', 'ꙭ'), ('Ꚁ', 'ꚛ'), ('Ꜣ', 'ꝯ'), + ('ꝱ', 'ꞇ'), ('Ꞌ', 'ꞎ'), ('Ꞑ', 'Ɪ'), ('Ʞ', 'ꞷ'), + ('ꟺ', 'ꟺ'), ('ꬰ', 'ꭚ'), ('ꭠ', 'ꭥ'), ('ꭰ', 'ꮿ'), + ('ff', 'st'), ('ﬓ', 'ﬗ'), ('A', 'Z'), ('a', 'z'), + ('𐐀', '𐑏'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), ('𐲀', '𐲲'), + ('𐳀', '𐳲'), ('𑢠', '𑣟'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), + ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), + ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), + ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), + ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), + ('𝕒', '𝚥'), ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), + ('𝛼', '𝜔'), ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), + ('𝝰', '𝞈'), ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), + ('𞤀', '𞥃'), +]; + +pub const CLOSE_PUNCTUATION: &'static [(char, char)] = &[ + (')', ')'), (']', ']'), ('}', '}'), ('༻', '༻'), ('༽', '༽'), + ('᚜', '᚜'), ('⁆', '⁆'), ('⁾', '⁾'), ('₎', '₎'), + ('⌉', '⌉'), ('⌋', '⌋'), ('〉', '〉'), ('❩', '❩'), + ('❫', '❫'), ('❭', '❭'), ('❯', '❯'), ('❱', '❱'), + ('❳', '❳'), ('❵', '❵'), ('⟆', '⟆'), ('⟧', '⟧'), + ('⟩', '⟩'), ('⟫', '⟫'), ('⟭', '⟭'), ('⟯', '⟯'), + ('⦄', '⦄'), ('⦆', '⦆'), ('⦈', '⦈'), ('⦊', '⦊'), + ('⦌', '⦌'), ('⦎', '⦎'), ('⦐', '⦐'), ('⦒', '⦒'), + ('⦔', '⦔'), ('⦖', '⦖'), ('⦘', '⦘'), ('⧙', '⧙'), + ('⧛', '⧛'), ('⧽', '⧽'), ('⸣', '⸣'), ('⸥', '⸥'), + ('⸧', '⸧'), ('⸩', '⸩'), ('〉', '〉'), ('》', '》'), + ('」', '」'), ('』', '』'), ('】', '】'), ('〕', '〕'), + ('〗', '〗'), ('〙', '〙'), ('〛', '〛'), ('〞', '〟'), + ('﴾', '﴾'), ('︘', '︘'), ('︶', '︶'), ('︸', '︸'), + ('︺', '︺'), ('︼', '︼'), ('︾', '︾'), ('﹀', '﹀'), + ('﹂', '﹂'), ('﹄', '﹄'), ('﹈', '﹈'), ('﹚', '﹚'), + ('﹜', '﹜'), ('﹞', '﹞'), (')', ')'), (']', ']'), + ('}', '}'), ('⦆', '⦆'), ('」', '」'), +]; + +pub const CONNECTOR_PUNCTUATION: &'static [(char, char)] = &[ + ('_', '_'), ('‿', '⁀'), ('⁔', '⁔'), ('︳', '︴'), ('﹍', '﹏'), + ('_', '_'), +]; + +pub const CONTROL: &'static [(char, char)] = &[ + ('\u{0}', '\u{1f}'), ('\u{7f}', '\u{9f}'), +]; + +pub const CURRENCY_SYMBOL: &'static [(char, char)] = &[ + ('$', '$'), ('¢', '¥'), ('֏', '֏'), ('؋', '؋'), ('৲', '৳'), + ('৻', '৻'), ('૱', '૱'), ('௹', '௹'), ('฿', '฿'), + ('៛', '៛'), ('₠', '₿'), ('꠸', '꠸'), ('﷼', '﷼'), + ('﹩', '﹩'), ('$', '$'), ('¢', '£'), ('¥', '₩'), +]; + +pub const DASH_PUNCTUATION: &'static [(char, char)] = &[ + ('-', '-'), ('֊', '֊'), ('־', '־'), ('᐀', '᐀'), ('᠆', '᠆'), + ('‐', '―'), ('⸗', '⸗'), ('⸚', '⸚'), ('⸺', '⸻'), + ('⹀', '⹀'), ('〜', '〜'), ('〰', '〰'), ('゠', '゠'), + ('︱', '︲'), ('﹘', '﹘'), ('﹣', '﹣'), ('-', '-'), +]; + +pub const DECIMAL_NUMBER: &'static [(char, char)] = &[ + ('0', '9'), ('٠', '٩'), ('۰', '۹'), ('߀', '߉'), ('०', '९'), + ('০', '৯'), ('੦', '੯'), ('૦', '૯'), ('୦', '୯'), + ('௦', '௯'), ('౦', '౯'), ('೦', '೯'), ('൦', '൯'), + ('෦', '෯'), ('๐', '๙'), ('໐', '໙'), ('༠', '༩'), + ('၀', '၉'), ('႐', '႙'), ('០', '៩'), ('᠐', '᠙'), + ('᥆', '᥏'), ('᧐', '᧙'), ('᪀', '᪉'), ('᪐', '᪙'), + ('᭐', '᭙'), ('᮰', '᮹'), ('᱀', '᱉'), ('᱐', '᱙'), + ('꘠', '꘩'), ('꣐', '꣙'), ('꤀', '꤉'), ('꧐', '꧙'), + ('꧰', '꧹'), ('꩐', '꩙'), ('꯰', '꯹'), ('0', '9'), + ('𐒠', '𐒩'), ('𑁦', '𑁯'), ('𑃰', '𑃹'), ('𑄶', '𑄿'), + ('𑇐', '𑇙'), ('𑋰', '𑋹'), ('𑑐', '𑑙'), ('𑓐', '𑓙'), + ('𑙐', '𑙙'), ('𑛀', '𑛉'), ('𑜰', '𑜹'), ('𑣠', '𑣩'), + ('𑱐', '𑱙'), ('𑵐', '𑵙'), ('𖩠', '𖩩'), ('𖭐', '𖭙'), + ('𝟎', '𝟿'), ('𞥐', '𞥙'), +]; + +pub const ENCLOSING_MARK: &'static [(char, char)] = &[ + ('҈', '҉'), ('᪾', '᪾'), ('⃝', '⃠'), ('⃢', '⃤'), + ('꙰', '꙲'), +]; + +pub const FINAL_PUNCTUATION: &'static [(char, char)] = &[ + ('»', '»'), ('’', '’'), ('”', '”'), ('›', '›'), + ('⸃', '⸃'), ('⸅', '⸅'), ('⸊', '⸊'), ('⸍', '⸍'), + ('⸝', '⸝'), ('⸡', '⸡'), +]; + +pub const FORMAT: &'static [(char, char)] = &[ + ('\u{ad}', '\u{ad}'), ('\u{600}', '\u{605}'), ('\u{61c}', '\u{61c}'), + ('\u{6dd}', '\u{6dd}'), ('\u{70f}', '\u{70f}'), ('\u{8e2}', '\u{8e2}'), + ('\u{180e}', '\u{180e}'), ('\u{200b}', '\u{200f}'), + ('\u{202a}', '\u{202e}'), ('\u{2060}', '\u{2064}'), + ('\u{2066}', '\u{206f}'), ('\u{feff}', '\u{feff}'), + ('\u{fff9}', '\u{fffb}'), ('\u{110bd}', '\u{110bd}'), + ('\u{1bca0}', '\u{1bca3}'), ('\u{1d173}', '\u{1d17a}'), + ('\u{e0001}', '\u{e0001}'), ('\u{e0020}', '\u{e007f}'), +]; + +pub const INITIAL_PUNCTUATION: &'static [(char, char)] = &[ + ('«', '«'), ('‘', '‘'), ('‛', '“'), ('‟', '‟'), + ('‹', '‹'), ('⸂', '⸂'), ('⸄', '⸄'), ('⸉', '⸉'), + ('⸌', '⸌'), ('⸜', '⸜'), ('⸠', '⸠'), +]; + +pub const LETTER: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), ('º', 'º'), + ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), + ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('Ͱ', 'ʹ'), ('Ͷ', 'ͷ'), ('ͺ', 'ͽ'), + ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), + ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('Ҋ', 'ԯ'), ('Ա', 'Ֆ'), ('ՙ', 'ՙ'), + ('ա', 'և'), ('א', 'ת'), ('װ', 'ײ'), ('ؠ', 'ي'), ('ٮ', 'ٯ'), + ('ٱ', 'ۓ'), ('ە', 'ە'), ('ۥ', 'ۦ'), ('ۮ', 'ۯ'), ('ۺ', 'ۼ'), + ('ۿ', 'ۿ'), ('ܐ', 'ܐ'), ('ܒ', 'ܯ'), ('ݍ', 'ޥ'), ('ޱ', 'ޱ'), + ('ߊ', 'ߪ'), ('ߴ', 'ߵ'), ('ߺ', 'ߺ'), ('ࠀ', 'ࠕ'), ('ࠚ', 'ࠚ'), + ('ࠤ', 'ࠤ'), ('ࠨ', 'ࠨ'), ('ࡀ', 'ࡘ'), ('ࡠ', 'ࡪ'), + ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ऄ', 'ह'), ('ऽ', 'ऽ'), + ('ॐ', 'ॐ'), ('क़', 'ॡ'), ('ॱ', 'ঀ'), ('অ', 'ঌ'), + ('এ', 'ঐ'), ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), + ('শ', 'হ'), ('ঽ', 'ঽ'), ('ৎ', 'ৎ'), ('ড়', 'ঢ়'), + ('য়', 'ৡ'), ('ৰ', 'ৱ'), ('ৼ', 'ৼ'), ('ਅ', 'ਊ'), + ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), + ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), + ('ੲ', 'ੴ'), ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), + ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), ('ઽ', 'ઽ'), + ('ૐ', 'ૐ'), ('ૠ', 'ૡ'), ('ૹ', 'ૹ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('ଽ', 'ଽ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୡ'), + ('ୱ', 'ୱ'), ('ஃ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), + ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), + ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), ('ௐ', 'ௐ'), + ('అ', 'ఌ'), ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), + ('ఽ', 'ఽ'), ('ౘ', 'ౚ'), ('ౠ', 'ౡ'), ('ಀ', 'ಀ'), + ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), + ('ವ', 'ಹ'), ('ಽ', 'ಽ'), ('ೞ', 'ೞ'), ('ೠ', 'ೡ'), + ('ೱ', 'ೲ'), ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ഺ'), + ('ഽ', 'ഽ'), ('ൎ', 'ൎ'), ('ൔ', 'ൖ'), ('ൟ', 'ൡ'), + ('ൺ', 'ൿ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('ก', 'ะ'), ('า', 'ำ'), + ('เ', 'ๆ'), ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), + ('ຊ', 'ຊ'), ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), + ('ມ', 'ຣ'), ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), + ('ອ', 'ະ'), ('າ', 'ຳ'), ('ຽ', 'ຽ'), ('ເ', 'ໄ'), + ('ໆ', 'ໆ'), ('ໜ', 'ໟ'), ('ༀ', 'ༀ'), ('ཀ', 'ཇ'), + ('ཉ', 'ཬ'), ('ྈ', 'ྌ'), ('က', 'ဪ'), ('ဿ', 'ဿ'), + ('ၐ', 'ၕ'), ('ၚ', 'ၝ'), ('ၡ', 'ၡ'), ('ၥ', 'ၦ'), + ('ၮ', 'ၰ'), ('ၵ', 'ႁ'), ('ႎ', 'ႎ'), ('Ⴀ', 'Ⴥ'), + ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), ('ჼ', 'ቈ'), + ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), + ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), + ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), + ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('ᎀ', 'ᎏ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), ('ᙯ', 'ᙿ'), + ('ᚁ', 'ᚚ'), ('ᚠ', 'ᛪ'), ('ᛱ', 'ᛸ'), ('ᜀ', 'ᜌ'), + ('ᜎ', 'ᜑ'), ('ᜠ', 'ᜱ'), ('ᝀ', 'ᝑ'), ('ᝠ', 'ᝬ'), + ('ᝮ', 'ᝰ'), ('ក', 'ឳ'), ('ៗ', 'ៗ'), ('ៜ', 'ៜ'), + ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢄ'), ('ᢇ', 'ᢨ'), ('ᢪ', 'ᢪ'), + ('ᢰ', 'ᣵ'), ('ᤀ', 'ᤞ'), ('ᥐ', 'ᥭ'), ('ᥰ', 'ᥴ'), + ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), ('ᨀ', 'ᨖ'), ('ᨠ', 'ᩔ'), + ('ᪧ', 'ᪧ'), ('ᬅ', 'ᬳ'), ('ᭅ', 'ᭋ'), ('ᮃ', 'ᮠ'), + ('ᮮ', 'ᮯ'), ('ᮺ', 'ᯥ'), ('ᰀ', 'ᰣ'), ('ᱍ', 'ᱏ'), + ('ᱚ', 'ᱽ'), ('ᲀ', 'ᲈ'), ('ᳩ', 'ᳬ'), ('ᳮ', 'ᳱ'), + ('ᳵ', 'ᳶ'), ('ᴀ', 'ᶿ'), ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), + ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), + ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), + ('ᾶ', 'ᾼ'), ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), + ('ῐ', 'ΐ'), ('ῖ', 'Ί'), ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), + ('ῶ', 'ῼ'), ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), + ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), + ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), ('Ω', 'Ω'), ('ℨ', 'ℨ'), + ('K', 'ℭ'), ('ℯ', 'ℹ'), ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), + ('ⅎ', 'ⅎ'), ('Ↄ', 'ↄ'), ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), + ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳮ'), ('Ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), + ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ⴰ', 'ⵧ'), ('ⵯ', 'ⵯ'), + ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), + ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), + ('ⷘ', 'ⷞ'), ('ⸯ', 'ⸯ'), ('々', '〆'), ('〱', '〵'), + ('〻', '〼'), ('ぁ', 'ゖ'), ('ゝ', 'ゟ'), ('ァ', 'ヺ'), + ('ー', 'ヿ'), ('ㄅ', 'ㄮ'), ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), + ('ㇰ', 'ㇿ'), ('㐀', '䶵'), ('一', '鿪'), ('ꀀ', 'ꒌ'), + ('ꓐ', 'ꓽ'), ('ꔀ', 'ꘌ'), ('ꘐ', 'ꘟ'), ('ꘪ', 'ꘫ'), + ('Ꙁ', 'ꙮ'), ('ꙿ', 'ꚝ'), ('ꚠ', 'ꛥ'), ('ꜗ', 'ꜟ'), + ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), ('Ʞ', 'ꞷ'), ('ꟷ', 'ꠁ'), + ('ꠃ', 'ꠅ'), ('ꠇ', 'ꠊ'), ('ꠌ', 'ꠢ'), ('ꡀ', 'ꡳ'), + ('ꢂ', 'ꢳ'), ('ꣲ', 'ꣷ'), ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), + ('ꤊ', 'ꤥ'), ('ꤰ', 'ꥆ'), ('ꥠ', 'ꥼ'), ('ꦄ', 'ꦲ'), + ('ꧏ', 'ꧏ'), ('ꧠ', 'ꧤ'), ('ꧦ', 'ꧯ'), ('ꧺ', 'ꧾ'), + ('ꨀ', 'ꨨ'), ('ꩀ', 'ꩂ'), ('ꩄ', 'ꩋ'), ('ꩠ', 'ꩶ'), + ('ꩺ', 'ꩺ'), ('ꩾ', 'ꪯ'), ('ꪱ', 'ꪱ'), ('ꪵ', 'ꪶ'), + ('ꪹ', 'ꪽ'), ('ꫀ', 'ꫀ'), ('ꫂ', 'ꫂ'), ('ꫛ', 'ꫝ'), + ('ꫠ', 'ꫪ'), ('ꫲ', 'ꫴ'), ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), + ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), + ('ꭜ', 'ꭥ'), ('ꭰ', 'ꯢ'), ('가', '힣'), ('ힰ', 'ퟆ'), + ('ퟋ', 'ퟻ'), ('豈', '舘'), ('並', '龎'), ('ff', 'st'), + ('ﬓ', 'ﬗ'), ('יִ', 'יִ'), ('ײַ', 'ﬨ'), ('שׁ', 'זּ'), + ('טּ', 'לּ'), ('מּ', 'מּ'), ('נּ', 'סּ'), ('ףּ', 'פּ'), + ('צּ', 'ﮱ'), ('ﯓ', 'ﴽ'), ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), + ('ﷰ', 'ﷻ'), ('ﹰ', 'ﹴ'), ('ﹶ', 'ﻼ'), ('A', 'Z'), + ('a', 'z'), ('ヲ', 'ᄒ'), ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), + ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), ('𐀀', '𐀋'), ('𐀍', '𐀦'), + ('𐀨', '𐀺'), ('𐀼', '𐀽'), ('𐀿', '𐁍'), ('𐁐', '𐁝'), + ('𐂀', '𐃺'), ('𐊀', '𐊜'), ('𐊠', '𐋐'), ('𐌀', '𐌟'), + ('𐌭', '𐍀'), ('𐍂', '𐍉'), ('𐍐', '𐍵'), ('𐎀', '𐎝'), + ('𐎠', '𐏃'), ('𐏈', '𐏏'), ('𐐀', '𐒝'), ('𐒰', '𐓓'), + ('𐓘', '𐓻'), ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐘀', '𐜶'), + ('𐝀', '𐝕'), ('𐝠', '𐝧'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), + ('𐠊', '𐠵'), ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐡕'), + ('𐡠', '𐡶'), ('𐢀', '𐢞'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), + ('𐤀', '𐤕'), ('𐤠', '𐤹'), ('𐦀', '𐦷'), ('𐦾', '𐦿'), + ('𐨀', '𐨀'), ('𐨐', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), + ('𐩠', '𐩼'), ('𐪀', '𐪜'), ('𐫀', '𐫇'), ('𐫉', '𐫤'), + ('𐬀', '𐬵'), ('𐭀', '𐭕'), ('𐭠', '𐭲'), ('𐮀', '𐮑'), + ('𐰀', '𐱈'), ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𑀃', '𑀷'), + ('𑂃', '𑂯'), ('𑃐', '𑃨'), ('𑄃', '𑄦'), ('𑅐', '𑅲'), + ('𑅶', '𑅶'), ('𑆃', '𑆲'), ('𑇁', '𑇄'), ('𑇚', '𑇚'), + ('𑇜', '𑇜'), ('𑈀', '𑈑'), ('𑈓', '𑈫'), ('𑊀', '𑊆'), + ('𑊈', '𑊈'), ('𑊊', '𑊍'), ('𑊏', '𑊝'), ('𑊟', '𑊨'), + ('𑊰', '𑋞'), ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), + ('𑌪', '𑌰'), ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌽', '𑌽'), + ('𑍐', '𑍐'), ('𑍝', '𑍡'), ('𑐀', '𑐴'), ('𑑇', '𑑊'), + ('𑒀', '𑒯'), ('𑓄', '𑓅'), ('𑓇', '𑓇'), ('𑖀', '𑖮'), + ('𑗘', '𑗛'), ('𑘀', '𑘯'), ('𑙄', '𑙄'), ('𑚀', '𑚪'), + ('𑜀', '𑜙'), ('𑢠', '𑣟'), ('𑣿', '𑣿'), ('𑨀', '𑨀'), + ('𑨋', '𑨲'), ('𑨺', '𑨺'), ('𑩐', '𑩐'), ('𑩜', '𑪃'), + ('𑪆', '𑪉'), ('𑫀', '𑫸'), ('𑰀', '𑰈'), ('𑰊', '𑰮'), + ('𑱀', '𑱀'), ('𑱲', '𑲏'), ('𑴀', '𑴆'), ('𑴈', '𑴉'), + ('𑴋', '𑴰'), ('𑵆', '𑵆'), ('𒀀', '𒎙'), ('𒒀', '𒕃'), + ('𓀀', '𓐮'), ('𔐀', '𔙆'), ('𖠀', '𖨸'), ('𖩀', '𖩞'), + ('𖫐', '𖫭'), ('𖬀', '𖬯'), ('𖭀', '𖭃'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽐'), ('𖾓', '𖾟'), + ('𖿠', '𖿡'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𛀀', '𛄞'), + ('𛅰', '𛋻'), ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), + ('𛲐', '𛲙'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), + ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), + ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), + ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), + ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), + ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), ('𝛼', '𝜔'), + ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), ('𝝰', '𝞈'), + ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), ('𞠀', '𞣄'), + ('𞤀', '𞥃'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), + ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), + ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), + ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), + ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), + ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), + ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), + ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), + ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), + ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), ('丽', '𪘀'), +]; + +pub const LETTER_NUMBER: &'static [(char, char)] = &[ + ('ᛮ', 'ᛰ'), ('Ⅰ', 'ↂ'), ('ↅ', 'ↈ'), ('〇', '〇'), + ('〡', '〩'), ('〸', '〺'), ('ꛦ', 'ꛯ'), ('𐅀', '𐅴'), + ('𐍁', '𐍁'), ('𐍊', '𐍊'), ('𐏑', '𐏕'), ('𒐀', '𒑮'), +]; + +pub const LINE_SEPARATOR: &'static [(char, char)] = &[ + ('\u{2028}', '\u{2028}'), +]; + +pub const LOWERCASE_LETTER: &'static [(char, char)] = &[ + ('a', 'z'), ('µ', 'µ'), ('ß', 'ö'), ('ø', 'ÿ'), ('ā', 'ā'), + ('ă', 'ă'), ('ą', 'ą'), ('ć', 'ć'), ('ĉ', 'ĉ'), ('ċ', 'ċ'), + ('č', 'č'), ('ď', 'ď'), ('đ', 'đ'), ('ē', 'ē'), ('ĕ', 'ĕ'), + ('ė', 'ė'), ('ę', 'ę'), ('ě', 'ě'), ('ĝ', 'ĝ'), ('ğ', 'ğ'), + ('ġ', 'ġ'), ('ģ', 'ģ'), ('ĥ', 'ĥ'), ('ħ', 'ħ'), ('ĩ', 'ĩ'), + ('ī', 'ī'), ('ĭ', 'ĭ'), ('į', 'į'), ('ı', 'ı'), ('ij', 'ij'), + ('ĵ', 'ĵ'), ('ķ', 'ĸ'), ('ĺ', 'ĺ'), ('ļ', 'ļ'), ('ľ', 'ľ'), + ('ŀ', 'ŀ'), ('ł', 'ł'), ('ń', 'ń'), ('ņ', 'ņ'), ('ň', 'ʼn'), + ('ŋ', 'ŋ'), ('ō', 'ō'), ('ŏ', 'ŏ'), ('ő', 'ő'), ('œ', 'œ'), + ('ŕ', 'ŕ'), ('ŗ', 'ŗ'), ('ř', 'ř'), ('ś', 'ś'), ('ŝ', 'ŝ'), + ('ş', 'ş'), ('š', 'š'), ('ţ', 'ţ'), ('ť', 'ť'), ('ŧ', 'ŧ'), + ('ũ', 'ũ'), ('ū', 'ū'), ('ŭ', 'ŭ'), ('ů', 'ů'), ('ű', 'ű'), + ('ų', 'ų'), ('ŵ', 'ŵ'), ('ŷ', 'ŷ'), ('ź', 'ź'), ('ż', 'ż'), + ('ž', 'ƀ'), ('ƃ', 'ƃ'), ('ƅ', 'ƅ'), ('ƈ', 'ƈ'), ('ƌ', 'ƍ'), + ('ƒ', 'ƒ'), ('ƕ', 'ƕ'), ('ƙ', 'ƛ'), ('ƞ', 'ƞ'), ('ơ', 'ơ'), + ('ƣ', 'ƣ'), ('ƥ', 'ƥ'), ('ƨ', 'ƨ'), ('ƪ', 'ƫ'), ('ƭ', 'ƭ'), + ('ư', 'ư'), ('ƴ', 'ƴ'), ('ƶ', 'ƶ'), ('ƹ', 'ƺ'), ('ƽ', 'ƿ'), + ('dž', 'dž'), ('lj', 'lj'), ('nj', 'nj'), ('ǎ', 'ǎ'), ('ǐ', 'ǐ'), + ('ǒ', 'ǒ'), ('ǔ', 'ǔ'), ('ǖ', 'ǖ'), ('ǘ', 'ǘ'), ('ǚ', 'ǚ'), + ('ǜ', 'ǝ'), ('ǟ', 'ǟ'), ('ǡ', 'ǡ'), ('ǣ', 'ǣ'), ('ǥ', 'ǥ'), + ('ǧ', 'ǧ'), ('ǩ', 'ǩ'), ('ǫ', 'ǫ'), ('ǭ', 'ǭ'), ('ǯ', 'ǰ'), + ('dz', 'dz'), ('ǵ', 'ǵ'), ('ǹ', 'ǹ'), ('ǻ', 'ǻ'), ('ǽ', 'ǽ'), + ('ǿ', 'ǿ'), ('ȁ', 'ȁ'), ('ȃ', 'ȃ'), ('ȅ', 'ȅ'), ('ȇ', 'ȇ'), + ('ȉ', 'ȉ'), ('ȋ', 'ȋ'), ('ȍ', 'ȍ'), ('ȏ', 'ȏ'), ('ȑ', 'ȑ'), + ('ȓ', 'ȓ'), ('ȕ', 'ȕ'), ('ȗ', 'ȗ'), ('ș', 'ș'), ('ț', 'ț'), + ('ȝ', 'ȝ'), ('ȟ', 'ȟ'), ('ȡ', 'ȡ'), ('ȣ', 'ȣ'), ('ȥ', 'ȥ'), + ('ȧ', 'ȧ'), ('ȩ', 'ȩ'), ('ȫ', 'ȫ'), ('ȭ', 'ȭ'), ('ȯ', 'ȯ'), + ('ȱ', 'ȱ'), ('ȳ', 'ȹ'), ('ȼ', 'ȼ'), ('ȿ', 'ɀ'), ('ɂ', 'ɂ'), + ('ɇ', 'ɇ'), ('ɉ', 'ɉ'), ('ɋ', 'ɋ'), ('ɍ', 'ɍ'), ('ɏ', 'ʓ'), + ('ʕ', 'ʯ'), ('ͱ', 'ͱ'), ('ͳ', 'ͳ'), ('ͷ', 'ͷ'), ('ͻ', 'ͽ'), + ('ΐ', 'ΐ'), ('ά', 'ώ'), ('ϐ', 'ϑ'), ('ϕ', 'ϗ'), ('ϙ', 'ϙ'), + ('ϛ', 'ϛ'), ('ϝ', 'ϝ'), ('ϟ', 'ϟ'), ('ϡ', 'ϡ'), ('ϣ', 'ϣ'), + ('ϥ', 'ϥ'), ('ϧ', 'ϧ'), ('ϩ', 'ϩ'), ('ϫ', 'ϫ'), ('ϭ', 'ϭ'), + ('ϯ', 'ϳ'), ('ϵ', 'ϵ'), ('ϸ', 'ϸ'), ('ϻ', 'ϼ'), ('а', 'џ'), + ('ѡ', 'ѡ'), ('ѣ', 'ѣ'), ('ѥ', 'ѥ'), ('ѧ', 'ѧ'), ('ѩ', 'ѩ'), + ('ѫ', 'ѫ'), ('ѭ', 'ѭ'), ('ѯ', 'ѯ'), ('ѱ', 'ѱ'), ('ѳ', 'ѳ'), + ('ѵ', 'ѵ'), ('ѷ', 'ѷ'), ('ѹ', 'ѹ'), ('ѻ', 'ѻ'), ('ѽ', 'ѽ'), + ('ѿ', 'ѿ'), ('ҁ', 'ҁ'), ('ҋ', 'ҋ'), ('ҍ', 'ҍ'), ('ҏ', 'ҏ'), + ('ґ', 'ґ'), ('ғ', 'ғ'), ('ҕ', 'ҕ'), ('җ', 'җ'), ('ҙ', 'ҙ'), + ('қ', 'қ'), ('ҝ', 'ҝ'), ('ҟ', 'ҟ'), ('ҡ', 'ҡ'), ('ң', 'ң'), + ('ҥ', 'ҥ'), ('ҧ', 'ҧ'), ('ҩ', 'ҩ'), ('ҫ', 'ҫ'), ('ҭ', 'ҭ'), + ('ү', 'ү'), ('ұ', 'ұ'), ('ҳ', 'ҳ'), ('ҵ', 'ҵ'), ('ҷ', 'ҷ'), + ('ҹ', 'ҹ'), ('һ', 'һ'), ('ҽ', 'ҽ'), ('ҿ', 'ҿ'), ('ӂ', 'ӂ'), + ('ӄ', 'ӄ'), ('ӆ', 'ӆ'), ('ӈ', 'ӈ'), ('ӊ', 'ӊ'), ('ӌ', 'ӌ'), + ('ӎ', 'ӏ'), ('ӑ', 'ӑ'), ('ӓ', 'ӓ'), ('ӕ', 'ӕ'), ('ӗ', 'ӗ'), + ('ә', 'ә'), ('ӛ', 'ӛ'), ('ӝ', 'ӝ'), ('ӟ', 'ӟ'), ('ӡ', 'ӡ'), + ('ӣ', 'ӣ'), ('ӥ', 'ӥ'), ('ӧ', 'ӧ'), ('ө', 'ө'), ('ӫ', 'ӫ'), + ('ӭ', 'ӭ'), ('ӯ', 'ӯ'), ('ӱ', 'ӱ'), ('ӳ', 'ӳ'), ('ӵ', 'ӵ'), + ('ӷ', 'ӷ'), ('ӹ', 'ӹ'), ('ӻ', 'ӻ'), ('ӽ', 'ӽ'), ('ӿ', 'ӿ'), + ('ԁ', 'ԁ'), ('ԃ', 'ԃ'), ('ԅ', 'ԅ'), ('ԇ', 'ԇ'), ('ԉ', 'ԉ'), + ('ԋ', 'ԋ'), ('ԍ', 'ԍ'), ('ԏ', 'ԏ'), ('ԑ', 'ԑ'), ('ԓ', 'ԓ'), + ('ԕ', 'ԕ'), ('ԗ', 'ԗ'), ('ԙ', 'ԙ'), ('ԛ', 'ԛ'), ('ԝ', 'ԝ'), + ('ԟ', 'ԟ'), ('ԡ', 'ԡ'), ('ԣ', 'ԣ'), ('ԥ', 'ԥ'), ('ԧ', 'ԧ'), + ('ԩ', 'ԩ'), ('ԫ', 'ԫ'), ('ԭ', 'ԭ'), ('ԯ', 'ԯ'), ('ա', 'և'), + ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᴀ', 'ᴫ'), ('ᵫ', 'ᵷ'), + ('ᵹ', 'ᶚ'), ('ḁ', 'ḁ'), ('ḃ', 'ḃ'), ('ḅ', 'ḅ'), + ('ḇ', 'ḇ'), ('ḉ', 'ḉ'), ('ḋ', 'ḋ'), ('ḍ', 'ḍ'), + ('ḏ', 'ḏ'), ('ḑ', 'ḑ'), ('ḓ', 'ḓ'), ('ḕ', 'ḕ'), + ('ḗ', 'ḗ'), ('ḙ', 'ḙ'), ('ḛ', 'ḛ'), ('ḝ', 'ḝ'), + ('ḟ', 'ḟ'), ('ḡ', 'ḡ'), ('ḣ', 'ḣ'), ('ḥ', 'ḥ'), + ('ḧ', 'ḧ'), ('ḩ', 'ḩ'), ('ḫ', 'ḫ'), ('ḭ', 'ḭ'), + ('ḯ', 'ḯ'), ('ḱ', 'ḱ'), ('ḳ', 'ḳ'), ('ḵ', 'ḵ'), + ('ḷ', 'ḷ'), ('ḹ', 'ḹ'), ('ḻ', 'ḻ'), ('ḽ', 'ḽ'), + ('ḿ', 'ḿ'), ('ṁ', 'ṁ'), ('ṃ', 'ṃ'), ('ṅ', 'ṅ'), + ('ṇ', 'ṇ'), ('ṉ', 'ṉ'), ('ṋ', 'ṋ'), ('ṍ', 'ṍ'), + ('ṏ', 'ṏ'), ('ṑ', 'ṑ'), ('ṓ', 'ṓ'), ('ṕ', 'ṕ'), + ('ṗ', 'ṗ'), ('ṙ', 'ṙ'), ('ṛ', 'ṛ'), ('ṝ', 'ṝ'), + ('ṟ', 'ṟ'), ('ṡ', 'ṡ'), ('ṣ', 'ṣ'), ('ṥ', 'ṥ'), + ('ṧ', 'ṧ'), ('ṩ', 'ṩ'), ('ṫ', 'ṫ'), ('ṭ', 'ṭ'), + ('ṯ', 'ṯ'), ('ṱ', 'ṱ'), ('ṳ', 'ṳ'), ('ṵ', 'ṵ'), + ('ṷ', 'ṷ'), ('ṹ', 'ṹ'), ('ṻ', 'ṻ'), ('ṽ', 'ṽ'), + ('ṿ', 'ṿ'), ('ẁ', 'ẁ'), ('ẃ', 'ẃ'), ('ẅ', 'ẅ'), + ('ẇ', 'ẇ'), ('ẉ', 'ẉ'), ('ẋ', 'ẋ'), ('ẍ', 'ẍ'), + ('ẏ', 'ẏ'), ('ẑ', 'ẑ'), ('ẓ', 'ẓ'), ('ẕ', 'ẝ'), + ('ẟ', 'ẟ'), ('ạ', 'ạ'), ('ả', 'ả'), ('ấ', 'ấ'), + ('ầ', 'ầ'), ('ẩ', 'ẩ'), ('ẫ', 'ẫ'), ('ậ', 'ậ'), + ('ắ', 'ắ'), ('ằ', 'ằ'), ('ẳ', 'ẳ'), ('ẵ', 'ẵ'), + ('ặ', 'ặ'), ('ẹ', 'ẹ'), ('ẻ', 'ẻ'), ('ẽ', 'ẽ'), + ('ế', 'ế'), ('ề', 'ề'), ('ể', 'ể'), ('ễ', 'ễ'), + ('ệ', 'ệ'), ('ỉ', 'ỉ'), ('ị', 'ị'), ('ọ', 'ọ'), + ('ỏ', 'ỏ'), ('ố', 'ố'), ('ồ', 'ồ'), ('ổ', 'ổ'), + ('ỗ', 'ỗ'), ('ộ', 'ộ'), ('ớ', 'ớ'), ('ờ', 'ờ'), + ('ở', 'ở'), ('ỡ', 'ỡ'), ('ợ', 'ợ'), ('ụ', 'ụ'), + ('ủ', 'ủ'), ('ứ', 'ứ'), ('ừ', 'ừ'), ('ử', 'ử'), + ('ữ', 'ữ'), ('ự', 'ự'), ('ỳ', 'ỳ'), ('ỵ', 'ỵ'), + ('ỷ', 'ỷ'), ('ỹ', 'ỹ'), ('ỻ', 'ỻ'), ('ỽ', 'ỽ'), + ('ỿ', 'ἇ'), ('ἐ', 'ἕ'), ('ἠ', 'ἧ'), ('ἰ', 'ἷ'), + ('ὀ', 'ὅ'), ('ὐ', 'ὗ'), ('ὠ', 'ὧ'), ('ὰ', 'ώ'), + ('ᾀ', 'ᾇ'), ('ᾐ', 'ᾗ'), ('ᾠ', 'ᾧ'), ('ᾰ', 'ᾴ'), + ('ᾶ', 'ᾷ'), ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῇ'), + ('ῐ', 'ΐ'), ('ῖ', 'ῗ'), ('ῠ', 'ῧ'), ('ῲ', 'ῴ'), + ('ῶ', 'ῷ'), ('ℊ', 'ℊ'), ('ℎ', 'ℏ'), ('ℓ', 'ℓ'), + ('ℯ', 'ℯ'), ('ℴ', 'ℴ'), ('ℹ', 'ℹ'), ('ℼ', 'ℽ'), + ('ⅆ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('ↄ', 'ↄ'), ('ⰰ', 'ⱞ'), + ('ⱡ', 'ⱡ'), ('ⱥ', 'ⱦ'), ('ⱨ', 'ⱨ'), ('ⱪ', 'ⱪ'), + ('ⱬ', 'ⱬ'), ('ⱱ', 'ⱱ'), ('ⱳ', 'ⱴ'), ('ⱶ', 'ⱻ'), + ('ⲁ', 'ⲁ'), ('ⲃ', 'ⲃ'), ('ⲅ', 'ⲅ'), ('ⲇ', 'ⲇ'), + ('ⲉ', 'ⲉ'), ('ⲋ', 'ⲋ'), ('ⲍ', 'ⲍ'), ('ⲏ', 'ⲏ'), + ('ⲑ', 'ⲑ'), ('ⲓ', 'ⲓ'), ('ⲕ', 'ⲕ'), ('ⲗ', 'ⲗ'), + ('ⲙ', 'ⲙ'), ('ⲛ', 'ⲛ'), ('ⲝ', 'ⲝ'), ('ⲟ', 'ⲟ'), + ('ⲡ', 'ⲡ'), ('ⲣ', 'ⲣ'), ('ⲥ', 'ⲥ'), ('ⲧ', 'ⲧ'), + ('ⲩ', 'ⲩ'), ('ⲫ', 'ⲫ'), ('ⲭ', 'ⲭ'), ('ⲯ', 'ⲯ'), + ('ⲱ', 'ⲱ'), ('ⲳ', 'ⲳ'), ('ⲵ', 'ⲵ'), ('ⲷ', 'ⲷ'), + ('ⲹ', 'ⲹ'), ('ⲻ', 'ⲻ'), ('ⲽ', 'ⲽ'), ('ⲿ', 'ⲿ'), + ('ⳁ', 'ⳁ'), ('ⳃ', 'ⳃ'), ('ⳅ', 'ⳅ'), ('ⳇ', 'ⳇ'), + ('ⳉ', 'ⳉ'), ('ⳋ', 'ⳋ'), ('ⳍ', 'ⳍ'), ('ⳏ', 'ⳏ'), + ('ⳑ', 'ⳑ'), ('ⳓ', 'ⳓ'), ('ⳕ', 'ⳕ'), ('ⳗ', 'ⳗ'), + ('ⳙ', 'ⳙ'), ('ⳛ', 'ⳛ'), ('ⳝ', 'ⳝ'), ('ⳟ', 'ⳟ'), + ('ⳡ', 'ⳡ'), ('ⳣ', 'ⳤ'), ('ⳬ', 'ⳬ'), ('ⳮ', 'ⳮ'), + ('ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), + ('ꙁ', 'ꙁ'), ('ꙃ', 'ꙃ'), ('ꙅ', 'ꙅ'), ('ꙇ', 'ꙇ'), + ('ꙉ', 'ꙉ'), ('ꙋ', 'ꙋ'), ('ꙍ', 'ꙍ'), ('ꙏ', 'ꙏ'), + ('ꙑ', 'ꙑ'), ('ꙓ', 'ꙓ'), ('ꙕ', 'ꙕ'), ('ꙗ', 'ꙗ'), + ('ꙙ', 'ꙙ'), ('ꙛ', 'ꙛ'), ('ꙝ', 'ꙝ'), ('ꙟ', 'ꙟ'), + ('ꙡ', 'ꙡ'), ('ꙣ', 'ꙣ'), ('ꙥ', 'ꙥ'), ('ꙧ', 'ꙧ'), + ('ꙩ', 'ꙩ'), ('ꙫ', 'ꙫ'), ('ꙭ', 'ꙭ'), ('ꚁ', 'ꚁ'), + ('ꚃ', 'ꚃ'), ('ꚅ', 'ꚅ'), ('ꚇ', 'ꚇ'), ('ꚉ', 'ꚉ'), + ('ꚋ', 'ꚋ'), ('ꚍ', 'ꚍ'), ('ꚏ', 'ꚏ'), ('ꚑ', 'ꚑ'), + ('ꚓ', 'ꚓ'), ('ꚕ', 'ꚕ'), ('ꚗ', 'ꚗ'), ('ꚙ', 'ꚙ'), + ('ꚛ', 'ꚛ'), ('ꜣ', 'ꜣ'), ('ꜥ', 'ꜥ'), ('ꜧ', 'ꜧ'), + ('ꜩ', 'ꜩ'), ('ꜫ', 'ꜫ'), ('ꜭ', 'ꜭ'), ('ꜯ', 'ꜱ'), + ('ꜳ', 'ꜳ'), ('ꜵ', 'ꜵ'), ('ꜷ', 'ꜷ'), ('ꜹ', 'ꜹ'), + ('ꜻ', 'ꜻ'), ('ꜽ', 'ꜽ'), ('ꜿ', 'ꜿ'), ('ꝁ', 'ꝁ'), + ('ꝃ', 'ꝃ'), ('ꝅ', 'ꝅ'), ('ꝇ', 'ꝇ'), ('ꝉ', 'ꝉ'), + ('ꝋ', 'ꝋ'), ('ꝍ', 'ꝍ'), ('ꝏ', 'ꝏ'), ('ꝑ', 'ꝑ'), + ('ꝓ', 'ꝓ'), ('ꝕ', 'ꝕ'), ('ꝗ', 'ꝗ'), ('ꝙ', 'ꝙ'), + ('ꝛ', 'ꝛ'), ('ꝝ', 'ꝝ'), ('ꝟ', 'ꝟ'), ('ꝡ', 'ꝡ'), + ('ꝣ', 'ꝣ'), ('ꝥ', 'ꝥ'), ('ꝧ', 'ꝧ'), ('ꝩ', 'ꝩ'), + ('ꝫ', 'ꝫ'), ('ꝭ', 'ꝭ'), ('ꝯ', 'ꝯ'), ('ꝱ', 'ꝸ'), + ('ꝺ', 'ꝺ'), ('ꝼ', 'ꝼ'), ('ꝿ', 'ꝿ'), ('ꞁ', 'ꞁ'), + ('ꞃ', 'ꞃ'), ('ꞅ', 'ꞅ'), ('ꞇ', 'ꞇ'), ('ꞌ', 'ꞌ'), + ('ꞎ', 'ꞎ'), ('ꞑ', 'ꞑ'), ('ꞓ', 'ꞕ'), ('ꞗ', 'ꞗ'), + ('ꞙ', 'ꞙ'), ('ꞛ', 'ꞛ'), ('ꞝ', 'ꞝ'), ('ꞟ', 'ꞟ'), + ('ꞡ', 'ꞡ'), ('ꞣ', 'ꞣ'), ('ꞥ', 'ꞥ'), ('ꞧ', 'ꞧ'), + ('ꞩ', 'ꞩ'), ('ꞵ', 'ꞵ'), ('ꞷ', 'ꞷ'), ('ꟺ', 'ꟺ'), + ('ꬰ', 'ꭚ'), ('ꭠ', 'ꭥ'), ('ꭰ', 'ꮿ'), ('ff', 'st'), + ('ﬓ', 'ﬗ'), ('a', 'z'), ('𐐨', '𐑏'), ('𐓘', '𐓻'), + ('𐳀', '𐳲'), ('𑣀', '𑣟'), ('𝐚', '𝐳'), ('𝑎', '𝑔'), + ('𝑖', '𝑧'), ('𝒂', '𝒛'), ('𝒶', '𝒹'), ('𝒻', '𝒻'), + ('𝒽', '𝓃'), ('𝓅', '𝓏'), ('𝓪', '𝔃'), ('𝔞', '𝔷'), + ('𝕒', '𝕫'), ('𝖆', '𝖟'), ('𝖺', '𝗓'), ('𝗮', '𝘇'), + ('𝘢', '𝘻'), ('𝙖', '𝙯'), ('𝚊', '𝚥'), ('𝛂', '𝛚'), + ('𝛜', '𝛡'), ('𝛼', '𝜔'), ('𝜖', '𝜛'), ('𝜶', '𝝎'), + ('𝝐', '𝝕'), ('𝝰', '𝞈'), ('𝞊', '𝞏'), ('𝞪', '𝟂'), + ('𝟄', '𝟉'), ('𝟋', '𝟋'), ('𞤢', '𞥃'), +]; + +pub const MARK: &'static [(char, char)] = &[ + ('̀', 'ͯ'), ('҃', '҉'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), + ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('ؐ', 'ؚ'), ('ً', 'ٟ'), ('ٰ', 'ٰ'), + ('ۖ', 'ۜ'), ('۟', 'ۤ'), ('ۧ', 'ۨ'), ('۪', 'ۭ'), ('ܑ', 'ܑ'), + ('ܰ', '݊'), ('ަ', 'ް'), ('߫', '߳'), ('ࠖ', '࠙'), ('ࠛ', 'ࠣ'), + ('ࠥ', 'ࠧ'), ('ࠩ', '࠭'), ('࡙', '࡛'), ('ࣔ', '࣡'), + ('ࣣ', 'ः'), ('ऺ', '़'), ('ा', 'ॏ'), ('॑', 'ॗ'), + ('ॢ', 'ॣ'), ('ঁ', 'ঃ'), ('়', '়'), ('া', 'ৄ'), + ('ে', 'ৈ'), ('ো', '্'), ('ৗ', 'ৗ'), ('ৢ', 'ৣ'), + ('ਁ', 'ਃ'), ('਼', '਼'), ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), + ('ੋ', '੍'), ('ੑ', 'ੑ'), ('ੰ', 'ੱ'), ('ੵ', 'ੵ'), + ('ઁ', 'ઃ'), ('઼', '઼'), ('ા', 'ૅ'), ('ે', 'ૉ'), + ('ો', '્'), ('ૢ', 'ૣ'), ('ૺ', '૿'), ('ଁ', 'ଃ'), + ('଼', '଼'), ('ା', 'ୄ'), ('େ', 'ୈ'), ('ୋ', '୍'), + ('ୖ', 'ୗ'), ('ୢ', 'ୣ'), ('ஂ', 'ஂ'), ('ா', 'ூ'), + ('ெ', 'ை'), ('ொ', '்'), ('ௗ', 'ௗ'), ('ఀ', 'ః'), + ('ా', 'ౄ'), ('ె', 'ై'), ('ొ', '్'), ('ౕ', 'ౖ'), + ('ౢ', 'ౣ'), ('ಁ', 'ಃ'), ('಼', '಼'), ('ಾ', 'ೄ'), + ('ೆ', 'ೈ'), ('ೊ', '್'), ('ೕ', 'ೖ'), ('ೢ', 'ೣ'), + ('ഀ', 'ഃ'), ('഻', '഼'), ('ാ', 'ൄ'), ('െ', 'ൈ'), + ('ൊ', '്'), ('ൗ', 'ൗ'), ('ൢ', 'ൣ'), ('ං', 'ඃ'), + ('්', '්'), ('ා', 'ු'), ('ූ', 'ූ'), ('ෘ', 'ෟ'), + ('ෲ', 'ෳ'), ('ั', 'ั'), ('ิ', 'ฺ'), ('็', '๎'), + ('ັ', 'ັ'), ('ິ', 'ູ'), ('ົ', 'ຼ'), ('່', 'ໍ'), + ('༘', '༙'), ('༵', '༵'), ('༷', '༷'), ('༹', '༹'), + ('༾', '༿'), ('ཱ', '྄'), ('྆', '྇'), ('ྍ', 'ྗ'), + ('ྙ', 'ྼ'), ('࿆', '࿆'), ('ါ', 'ှ'), ('ၖ', 'ၙ'), + ('ၞ', 'ၠ'), ('ၢ', 'ၤ'), ('ၧ', 'ၭ'), ('ၱ', 'ၴ'), + ('ႂ', 'ႍ'), ('ႏ', 'ႏ'), ('ႚ', 'ႝ'), ('፝', '፟'), + ('ᜒ', '᜔'), ('ᜲ', '᜴'), ('ᝒ', 'ᝓ'), ('ᝲ', 'ᝳ'), + ('឴', '៓'), ('៝', '៝'), ('᠋', '᠍'), ('ᢅ', 'ᢆ'), + ('ᢩ', 'ᢩ'), ('ᤠ', 'ᤫ'), ('ᤰ', '᤻'), ('ᨗ', 'ᨛ'), + ('ᩕ', 'ᩞ'), ('᩠', '᩼'), ('᩿', '᩿'), ('᪰', '᪾'), + ('ᬀ', 'ᬄ'), ('᬴', '᭄'), ('᭫', '᭳'), ('ᮀ', 'ᮂ'), + ('ᮡ', 'ᮭ'), ('᯦', '᯳'), ('ᰤ', '᰷'), ('᳐', '᳒'), + ('᳔', '᳨'), ('᳭', '᳭'), ('ᳲ', '᳴'), ('᳷', '᳹'), + ('᷀', '᷹'), ('᷻', '᷿'), ('⃐', '⃰'), ('⳯', '⳱'), + ('⵿', '⵿'), ('ⷠ', 'ⷿ'), ('〪', '〯'), ('゙', '゚'), + ('꙯', '꙲'), ('ꙴ', '꙽'), ('ꚞ', 'ꚟ'), ('꛰', '꛱'), + ('ꠂ', 'ꠂ'), ('꠆', '꠆'), ('ꠋ', 'ꠋ'), ('ꠣ', 'ꠧ'), + ('ꢀ', 'ꢁ'), ('ꢴ', 'ꣅ'), ('꣠', '꣱'), ('ꤦ', '꤭'), + ('ꥇ', '꥓'), ('ꦀ', 'ꦃ'), ('꦳', '꧀'), ('ꧥ', 'ꧥ'), + ('ꨩ', 'ꨶ'), ('ꩃ', 'ꩃ'), ('ꩌ', 'ꩍ'), ('ꩻ', 'ꩽ'), + ('ꪰ', 'ꪰ'), ('ꪲ', 'ꪴ'), ('ꪷ', 'ꪸ'), ('ꪾ', '꪿'), + ('꫁', '꫁'), ('ꫫ', 'ꫯ'), ('ꫵ', '꫶'), ('ꯣ', 'ꯪ'), + ('꯬', '꯭'), ('ﬞ', 'ﬞ'), ('︀', '️'), ('︠', '︯'), + ('𐇽', '𐇽'), ('𐋠', '𐋠'), ('𐍶', '𐍺'), ('𐨁', '𐨃'), + ('𐨅', '𐨆'), ('𐨌', '𐨏'), ('𐨸', '𐨺'), ('𐨿', '𐨿'), + ('𐫥', '𐫦'), ('𑀀', '𑀂'), ('𑀸', '𑁆'), ('𑁿', '𑂂'), + ('𑂰', '𑂺'), ('𑄀', '𑄂'), ('𑄧', '𑄴'), ('𑅳', '𑅳'), + ('𑆀', '𑆂'), ('𑆳', '𑇀'), ('𑇊', '𑇌'), ('𑈬', '𑈷'), + ('𑈾', '𑈾'), ('𑋟', '𑋪'), ('𑌀', '𑌃'), ('𑌼', '𑌼'), + ('𑌾', '𑍄'), ('𑍇', '𑍈'), ('𑍋', '𑍍'), ('𑍗', '𑍗'), + ('𑍢', '𑍣'), ('𑍦', '𑍬'), ('𑍰', '𑍴'), ('𑐵', '𑑆'), + ('𑒰', '𑓃'), ('𑖯', '𑖵'), ('𑖸', '𑗀'), ('𑗜', '𑗝'), + ('𑘰', '𑙀'), ('𑚫', '𑚷'), ('𑜝', '𑜫'), ('𑨁', '𑨊'), + ('𑨳', '𑨹'), ('𑨻', '𑨾'), ('𑩇', '𑩇'), ('𑩑', '𑩛'), + ('𑪊', '𑪙'), ('𑰯', '𑰶'), ('𑰸', '𑰿'), ('𑲒', '𑲧'), + ('𑲩', '𑲶'), ('𑴱', '𑴶'), ('𑴺', '𑴺'), ('𑴼', '𑴽'), + ('𑴿', '𑵅'), ('𑵇', '𑵇'), ('𖫰', '𖫴'), ('𖬰', '𖬶'), + ('𖽑', '𖽾'), ('𖾏', '𖾒'), ('𛲝', '𛲞'), ('𝅥', '𝅩'), + ('𝅭', '𝅲'), ('𝅻', '𝆂'), ('𝆅', '𝆋'), ('𝆪', '𝆭'), + ('𝉂', '𝉄'), ('𝨀', '𝨶'), ('𝨻', '𝩬'), ('𝩵', '𝩵'), + ('𝪄', '𝪄'), ('𝪛', '𝪟'), ('𝪡', '𝪯'), ('𞀀', '𞀆'), + ('𞀈', '𞀘'), ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), + ('𞣐', '𞣖'), ('𞥄', '𞥊'), ('󠄀', '󠇯'), +]; + +pub const MATH_SYMBOL: &'static [(char, char)] = &[ + ('+', '+'), ('<', '>'), ('|', '|'), ('~', '~'), ('¬', '¬'), ('±', '±'), + ('×', '×'), ('÷', '÷'), ('϶', '϶'), ('؆', '؈'), ('⁄', '⁄'), + ('⁒', '⁒'), ('⁺', '⁼'), ('₊', '₌'), ('℘', '℘'), + ('⅀', '⅄'), ('⅋', '⅋'), ('←', '↔'), ('↚', '↛'), + ('↠', '↠'), ('↣', '↣'), ('↦', '↦'), ('↮', '↮'), + ('⇎', '⇏'), ('⇒', '⇒'), ('⇔', '⇔'), ('⇴', '⋿'), + ('⌠', '⌡'), ('⍼', '⍼'), ('⎛', '⎳'), ('⏜', '⏡'), + ('▷', '▷'), ('◁', '◁'), ('◸', '◿'), ('♯', '♯'), + ('⟀', '⟄'), ('⟇', '⟥'), ('⟰', '⟿'), ('⤀', '⦂'), + ('⦙', '⧗'), ('⧜', '⧻'), ('⧾', '⫿'), ('⬰', '⭄'), + ('⭇', '⭌'), ('﬩', '﬩'), ('﹢', '﹢'), ('﹤', '﹦'), + ('+', '+'), ('<', '>'), ('|', '|'), ('~', '~'), + ('¬', '¬'), ('←', '↓'), ('𝛁', '𝛁'), ('𝛛', '𝛛'), + ('𝛻', '𝛻'), ('𝜕', '𝜕'), ('𝜵', '𝜵'), ('𝝏', '𝝏'), + ('𝝯', '𝝯'), ('𝞉', '𝞉'), ('𝞩', '𝞩'), ('𝟃', '𝟃'), + ('𞻰', '𞻱'), +]; + +pub const MODIFIER_LETTER: &'static [(char, char)] = &[ + ('ʰ', 'ˁ'), ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), + ('ʹ', 'ʹ'), ('ͺ', 'ͺ'), ('ՙ', 'ՙ'), ('ـ', 'ـ'), ('ۥ', 'ۦ'), + ('ߴ', 'ߵ'), ('ߺ', 'ߺ'), ('ࠚ', 'ࠚ'), ('ࠤ', 'ࠤ'), ('ࠨ', 'ࠨ'), + ('ॱ', 'ॱ'), ('ๆ', 'ๆ'), ('ໆ', 'ໆ'), ('ჼ', 'ჼ'), + ('ៗ', 'ៗ'), ('ᡃ', 'ᡃ'), ('ᪧ', 'ᪧ'), ('ᱸ', 'ᱽ'), + ('ᴬ', 'ᵪ'), ('ᵸ', 'ᵸ'), ('ᶛ', 'ᶿ'), ('ⁱ', 'ⁱ'), + ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ⱼ', 'ⱽ'), ('ⵯ', 'ⵯ'), + ('ⸯ', 'ⸯ'), ('々', '々'), ('〱', '〵'), ('〻', '〻'), + ('ゝ', 'ゞ'), ('ー', 'ヾ'), ('ꀕ', 'ꀕ'), ('ꓸ', 'ꓽ'), + ('ꘌ', 'ꘌ'), ('ꙿ', 'ꙿ'), ('ꚜ', 'ꚝ'), ('ꜗ', 'ꜟ'), + ('ꝰ', 'ꝰ'), ('ꞈ', 'ꞈ'), ('ꟸ', 'ꟹ'), ('ꧏ', 'ꧏ'), + ('ꧦ', 'ꧦ'), ('ꩰ', 'ꩰ'), ('ꫝ', 'ꫝ'), ('ꫳ', 'ꫴ'), + ('ꭜ', 'ꭟ'), ('ー', 'ー'), ('゙', '゚'), ('𖭀', '𖭃'), + ('𖾓', '𖾟'), ('𖿠', '𖿡'), +]; + +pub const MODIFIER_SYMBOL: &'static [(char, char)] = &[ + ('^', '^'), ('`', '`'), ('¨', '¨'), ('¯', '¯'), ('´', '´'), + ('¸', '¸'), ('˂', '˅'), ('˒', '˟'), ('˥', '˫'), ('˭', '˭'), + ('˯', '˿'), ('͵', '͵'), ('΄', '΅'), ('᾽', '᾽'), ('᾿', '῁'), + ('῍', '῏'), ('῝', '῟'), ('῭', '`'), ('´', '῾'), + ('゛', '゜'), ('꜀', '꜖'), ('꜠', '꜡'), ('꞉', '꞊'), + ('꭛', '꭛'), ('﮲', '﯁'), ('^', '^'), ('`', '`'), + (' ̄', ' ̄'), ('🏻', '🏿'), +]; + +pub const NONSPACING_MARK: &'static [(char, char)] = &[ + ('̀', 'ͯ'), ('҃', '҇'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), + ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('ؐ', 'ؚ'), ('ً', 'ٟ'), ('ٰ', 'ٰ'), + ('ۖ', 'ۜ'), ('۟', 'ۤ'), ('ۧ', 'ۨ'), ('۪', 'ۭ'), ('ܑ', 'ܑ'), + ('ܰ', '݊'), ('ަ', 'ް'), ('߫', '߳'), ('ࠖ', '࠙'), ('ࠛ', 'ࠣ'), + ('ࠥ', 'ࠧ'), ('ࠩ', '࠭'), ('࡙', '࡛'), ('ࣔ', '࣡'), + ('ࣣ', 'ं'), ('ऺ', 'ऺ'), ('़', '़'), ('ु', 'ै'), + ('्', '्'), ('॑', 'ॗ'), ('ॢ', 'ॣ'), ('ঁ', 'ঁ'), + ('়', '়'), ('ু', 'ৄ'), ('্', '্'), ('ৢ', 'ৣ'), + ('ਁ', 'ਂ'), ('਼', '਼'), ('ੁ', 'ੂ'), ('ੇ', 'ੈ'), + ('ੋ', '੍'), ('ੑ', 'ੑ'), ('ੰ', 'ੱ'), ('ੵ', 'ੵ'), + ('ઁ', 'ં'), ('઼', '઼'), ('ુ', 'ૅ'), ('ે', 'ૈ'), + ('્', '્'), ('ૢ', 'ૣ'), ('ૺ', '૿'), ('ଁ', 'ଁ'), + ('଼', '଼'), ('ି', 'ି'), ('ୁ', 'ୄ'), ('୍', '୍'), + ('ୖ', 'ୖ'), ('ୢ', 'ୣ'), ('ஂ', 'ஂ'), ('ீ', 'ீ'), + ('்', '்'), ('ఀ', 'ఀ'), ('ా', 'ీ'), ('ె', 'ై'), + ('ొ', '్'), ('ౕ', 'ౖ'), ('ౢ', 'ౣ'), ('ಁ', 'ಁ'), + ('಼', '಼'), ('ಿ', 'ಿ'), ('ೆ', 'ೆ'), ('ೌ', '್'), + ('ೢ', 'ೣ'), ('ഀ', 'ഁ'), ('഻', '഼'), ('ു', 'ൄ'), + ('്', '്'), ('ൢ', 'ൣ'), ('්', '්'), ('ි', 'ු'), + ('ූ', 'ූ'), ('ั', 'ั'), ('ิ', 'ฺ'), ('็', '๎'), + ('ັ', 'ັ'), ('ິ', 'ູ'), ('ົ', 'ຼ'), ('່', 'ໍ'), + ('༘', '༙'), ('༵', '༵'), ('༷', '༷'), ('༹', '༹'), + ('ཱ', 'ཾ'), ('ྀ', '྄'), ('྆', '྇'), ('ྍ', 'ྗ'), + ('ྙ', 'ྼ'), ('࿆', '࿆'), ('ိ', 'ူ'), ('ဲ', '့'), + ('္', '်'), ('ွ', 'ှ'), ('ၘ', 'ၙ'), ('ၞ', 'ၠ'), + ('ၱ', 'ၴ'), ('ႂ', 'ႂ'), ('ႅ', 'ႆ'), ('ႍ', 'ႍ'), + ('ႝ', 'ႝ'), ('፝', '፟'), ('ᜒ', '᜔'), ('ᜲ', '᜴'), + ('ᝒ', 'ᝓ'), ('ᝲ', 'ᝳ'), ('឴', '឵'), ('ិ', 'ួ'), + ('ំ', 'ំ'), ('៉', '៓'), ('៝', '៝'), ('᠋', '᠍'), + ('ᢅ', 'ᢆ'), ('ᢩ', 'ᢩ'), ('ᤠ', 'ᤢ'), ('ᤧ', 'ᤨ'), + ('ᤲ', 'ᤲ'), ('᤹', '᤻'), ('ᨗ', 'ᨘ'), ('ᨛ', 'ᨛ'), + ('ᩖ', 'ᩖ'), ('ᩘ', 'ᩞ'), ('᩠', '᩠'), ('ᩢ', 'ᩢ'), + ('ᩥ', 'ᩬ'), ('ᩳ', '᩼'), ('᩿', '᩿'), ('᪰', '᪽'), + ('ᬀ', 'ᬃ'), ('᬴', '᬴'), ('ᬶ', 'ᬺ'), ('ᬼ', 'ᬼ'), + ('ᭂ', 'ᭂ'), ('᭫', '᭳'), ('ᮀ', 'ᮁ'), ('ᮢ', 'ᮥ'), + ('ᮨ', 'ᮩ'), ('᮫', 'ᮭ'), ('᯦', '᯦'), ('ᯨ', 'ᯩ'), + ('ᯭ', 'ᯭ'), ('ᯯ', 'ᯱ'), ('ᰬ', 'ᰳ'), ('ᰶ', '᰷'), + ('᳐', '᳒'), ('᳔', '᳠'), ('᳢', '᳨'), ('᳭', '᳭'), + ('᳴', '᳴'), ('᳸', '᳹'), ('᷀', '᷹'), ('᷻', '᷿'), + ('⃐', '⃜'), ('⃡', '⃡'), ('⃥', '⃰'), ('⳯', '⳱'), + ('⵿', '⵿'), ('ⷠ', 'ⷿ'), ('〪', '〭'), ('゙', '゚'), + ('꙯', '꙯'), ('ꙴ', '꙽'), ('ꚞ', 'ꚟ'), ('꛰', '꛱'), + ('ꠂ', 'ꠂ'), ('꠆', '꠆'), ('ꠋ', 'ꠋ'), ('ꠥ', 'ꠦ'), + ('꣄', 'ꣅ'), ('꣠', '꣱'), ('ꤦ', '꤭'), ('ꥇ', 'ꥑ'), + ('ꦀ', 'ꦂ'), ('꦳', '꦳'), ('ꦶ', 'ꦹ'), ('ꦼ', 'ꦼ'), + ('ꧥ', 'ꧥ'), ('ꨩ', 'ꨮ'), ('ꨱ', 'ꨲ'), ('ꨵ', 'ꨶ'), + ('ꩃ', 'ꩃ'), ('ꩌ', 'ꩌ'), ('ꩼ', 'ꩼ'), ('ꪰ', 'ꪰ'), + ('ꪲ', 'ꪴ'), ('ꪷ', 'ꪸ'), ('ꪾ', '꪿'), ('꫁', '꫁'), + ('ꫬ', 'ꫭ'), ('꫶', '꫶'), ('ꯥ', 'ꯥ'), ('ꯨ', 'ꯨ'), + ('꯭', '꯭'), ('ﬞ', 'ﬞ'), ('︀', '️'), ('︠', '︯'), + ('𐇽', '𐇽'), ('𐋠', '𐋠'), ('𐍶', '𐍺'), ('𐨁', '𐨃'), + ('𐨅', '𐨆'), ('𐨌', '𐨏'), ('𐨸', '𐨺'), ('𐨿', '𐨿'), + ('𐫥', '𐫦'), ('𑀁', '𑀁'), ('𑀸', '𑁆'), ('𑁿', '𑂁'), + ('𑂳', '𑂶'), ('𑂹', '𑂺'), ('𑄀', '𑄂'), ('𑄧', '𑄫'), + ('𑄭', '𑄴'), ('𑅳', '𑅳'), ('𑆀', '𑆁'), ('𑆶', '𑆾'), + ('𑇊', '𑇌'), ('𑈯', '𑈱'), ('𑈴', '𑈴'), ('𑈶', '𑈷'), + ('𑈾', '𑈾'), ('𑋟', '𑋟'), ('𑋣', '𑋪'), ('𑌀', '𑌁'), + ('𑌼', '𑌼'), ('𑍀', '𑍀'), ('𑍦', '𑍬'), ('𑍰', '𑍴'), + ('𑐸', '𑐿'), ('𑑂', '𑑄'), ('𑑆', '𑑆'), ('𑒳', '𑒸'), + ('𑒺', '𑒺'), ('𑒿', '𑓀'), ('𑓂', '𑓃'), ('𑖲', '𑖵'), + ('𑖼', '𑖽'), ('𑖿', '𑗀'), ('𑗜', '𑗝'), ('𑘳', '𑘺'), + ('𑘽', '𑘽'), ('𑘿', '𑙀'), ('𑚫', '𑚫'), ('𑚭', '𑚭'), + ('𑚰', '𑚵'), ('𑚷', '𑚷'), ('𑜝', '𑜟'), ('𑜢', '𑜥'), + ('𑜧', '𑜫'), ('𑨁', '𑨆'), ('𑨉', '𑨊'), ('𑨳', '𑨸'), + ('𑨻', '𑨾'), ('𑩇', '𑩇'), ('𑩑', '𑩖'), ('𑩙', '𑩛'), + ('𑪊', '𑪖'), ('𑪘', '𑪙'), ('𑰰', '𑰶'), ('𑰸', '𑰽'), + ('𑰿', '𑰿'), ('𑲒', '𑲧'), ('𑲪', '𑲰'), ('𑲲', '𑲳'), + ('𑲵', '𑲶'), ('𑴱', '𑴶'), ('𑴺', '𑴺'), ('𑴼', '𑴽'), + ('𑴿', '𑵅'), ('𑵇', '𑵇'), ('𖫰', '𖫴'), ('𖬰', '𖬶'), + ('𖾏', '𖾒'), ('𛲝', '𛲞'), ('𝅧', '𝅩'), ('𝅻', '𝆂'), + ('𝆅', '𝆋'), ('𝆪', '𝆭'), ('𝉂', '𝉄'), ('𝨀', '𝨶'), + ('𝨻', '𝩬'), ('𝩵', '𝩵'), ('𝪄', '𝪄'), ('𝪛', '𝪟'), + ('𝪡', '𝪯'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), ('𞀛', '𞀡'), + ('𞀣', '𞀤'), ('𞀦', '𞀪'), ('𞣐', '𞣖'), ('𞥄', '𞥊'), + ('󠄀', '󠇯'), +]; + +pub const NUMBER: &'static [(char, char)] = &[ + ('0', '9'), ('²', '³'), ('¹', '¹'), ('¼', '¾'), ('٠', '٩'), + ('۰', '۹'), ('߀', '߉'), ('०', '९'), ('০', '৯'), ('৴', '৹'), + ('੦', '੯'), ('૦', '૯'), ('୦', '୯'), ('୲', '୷'), + ('௦', '௲'), ('౦', '౯'), ('౸', '౾'), ('೦', '೯'), + ('൘', '൞'), ('൦', '൸'), ('෦', '෯'), ('๐', '๙'), + ('໐', '໙'), ('༠', '༳'), ('၀', '၉'), ('႐', '႙'), + ('፩', '፼'), ('ᛮ', 'ᛰ'), ('០', '៩'), ('៰', '៹'), + ('᠐', '᠙'), ('᥆', '᥏'), ('᧐', '᧚'), ('᪀', '᪉'), + ('᪐', '᪙'), ('᭐', '᭙'), ('᮰', '᮹'), ('᱀', '᱉'), + ('᱐', '᱙'), ('⁰', '⁰'), ('⁴', '⁹'), ('₀', '₉'), + ('⅐', 'ↂ'), ('ↅ', '↉'), ('①', '⒛'), ('⓪', '⓿'), + ('❶', '➓'), ('⳽', '⳽'), ('〇', '〇'), ('〡', '〩'), + ('〸', '〺'), ('㆒', '㆕'), ('㈠', '㈩'), ('㉈', '㉏'), + ('㉑', '㉟'), ('㊀', '㊉'), ('㊱', '㊿'), ('꘠', '꘩'), + ('ꛦ', 'ꛯ'), ('꠰', '꠵'), ('꣐', '꣙'), ('꤀', '꤉'), + ('꧐', '꧙'), ('꧰', '꧹'), ('꩐', '꩙'), ('꯰', '꯹'), + ('0', '9'), ('𐄇', '𐄳'), ('𐅀', '𐅸'), ('𐆊', '𐆋'), + ('𐋡', '𐋻'), ('𐌠', '𐌣'), ('𐍁', '𐍁'), ('𐍊', '𐍊'), + ('𐏑', '𐏕'), ('𐒠', '𐒩'), ('𐡘', '𐡟'), ('𐡹', '𐡿'), + ('𐢧', '𐢯'), ('𐣻', '𐣿'), ('𐤖', '𐤛'), ('𐦼', '𐦽'), + ('𐧀', '𐧏'), ('𐧒', '𐧿'), ('𐩀', '𐩇'), ('𐩽', '𐩾'), + ('𐪝', '𐪟'), ('𐫫', '𐫯'), ('𐭘', '𐭟'), ('𐭸', '𐭿'), + ('𐮩', '𐮯'), ('𐳺', '𐳿'), ('𐹠', '𐹾'), ('𑁒', '𑁯'), + ('𑃰', '𑃹'), ('𑄶', '𑄿'), ('𑇐', '𑇙'), ('𑇡', '𑇴'), + ('𑋰', '𑋹'), ('𑑐', '𑑙'), ('𑓐', '𑓙'), ('𑙐', '𑙙'), + ('𑛀', '𑛉'), ('𑜰', '𑜻'), ('𑣠', '𑣲'), ('𑱐', '𑱬'), + ('𑵐', '𑵙'), ('𒐀', '𒑮'), ('𖩠', '𖩩'), ('𖭐', '𖭙'), + ('𖭛', '𖭡'), ('𝍠', '𝍱'), ('𝟎', '𝟿'), ('𞣇', '𞣏'), + ('𞥐', '𞥙'), ('🄀', '🄌'), +]; + +pub const OPEN_PUNCTUATION: &'static [(char, char)] = &[ + ('(', '('), ('[', '['), ('{', '{'), ('༺', '༺'), ('༼', '༼'), + ('᚛', '᚛'), ('‚', '‚'), ('„', '„'), ('⁅', '⁅'), + ('⁽', '⁽'), ('₍', '₍'), ('⌈', '⌈'), ('⌊', '⌊'), + ('〈', '〈'), ('❨', '❨'), ('❪', '❪'), ('❬', '❬'), + ('❮', '❮'), ('❰', '❰'), ('❲', '❲'), ('❴', '❴'), + ('⟅', '⟅'), ('⟦', '⟦'), ('⟨', '⟨'), ('⟪', '⟪'), + ('⟬', '⟬'), ('⟮', '⟮'), ('⦃', '⦃'), ('⦅', '⦅'), + ('⦇', '⦇'), ('⦉', '⦉'), ('⦋', '⦋'), ('⦍', '⦍'), + ('⦏', '⦏'), ('⦑', '⦑'), ('⦓', '⦓'), ('⦕', '⦕'), + ('⦗', '⦗'), ('⧘', '⧘'), ('⧚', '⧚'), ('⧼', '⧼'), + ('⸢', '⸢'), ('⸤', '⸤'), ('⸦', '⸦'), ('⸨', '⸨'), + ('⹂', '⹂'), ('〈', '〈'), ('《', '《'), ('「', '「'), + ('『', '『'), ('【', '【'), ('〔', '〔'), ('〖', '〖'), + ('〘', '〘'), ('〚', '〚'), ('〝', '〝'), ('﴿', '﴿'), + ('︗', '︗'), ('︵', '︵'), ('︷', '︷'), ('︹', '︹'), + ('︻', '︻'), ('︽', '︽'), ('︿', '︿'), ('﹁', '﹁'), + ('﹃', '﹃'), ('﹇', '﹇'), ('﹙', '﹙'), ('﹛', '﹛'), + ('﹝', '﹝'), ('(', '('), ('[', '['), ('{', '{'), + ('⦅', '⦅'), ('「', '「'), +]; + +pub const OTHER: &'static [(char, char)] = &[ + ('\u{0}', '\u{1f}'), ('\u{7f}', '\u{9f}'), ('\u{ad}', '\u{ad}'), + ('\u{378}', '\u{379}'), ('\u{380}', '\u{383}'), ('\u{38b}', '\u{38b}'), + ('\u{38d}', '\u{38d}'), ('\u{3a2}', '\u{3a2}'), ('\u{530}', '\u{530}'), + ('\u{557}', '\u{558}'), ('\u{560}', '\u{560}'), ('\u{588}', '\u{588}'), + ('\u{58b}', '\u{58c}'), ('\u{590}', '\u{590}'), ('\u{5c8}', '\u{5cf}'), + ('\u{5eb}', '\u{5ef}'), ('\u{5f5}', '\u{605}'), ('\u{61c}', '\u{61d}'), + ('\u{6dd}', '\u{6dd}'), ('\u{70e}', '\u{70f}'), ('\u{74b}', '\u{74c}'), + ('\u{7b2}', '\u{7bf}'), ('\u{7fb}', '\u{7ff}'), ('\u{82e}', '\u{82f}'), + ('\u{83f}', '\u{83f}'), ('\u{85c}', '\u{85d}'), ('\u{85f}', '\u{85f}'), + ('\u{86b}', '\u{89f}'), ('\u{8b5}', '\u{8b5}'), ('\u{8be}', '\u{8d3}'), + ('\u{8e2}', '\u{8e2}'), ('\u{984}', '\u{984}'), ('\u{98d}', '\u{98e}'), + ('\u{991}', '\u{992}'), ('\u{9a9}', '\u{9a9}'), ('\u{9b1}', '\u{9b1}'), + ('\u{9b3}', '\u{9b5}'), ('\u{9ba}', '\u{9bb}'), ('\u{9c5}', '\u{9c6}'), + ('\u{9c9}', '\u{9ca}'), ('\u{9cf}', '\u{9d6}'), ('\u{9d8}', '\u{9db}'), + ('\u{9de}', '\u{9de}'), ('\u{9e4}', '\u{9e5}'), ('\u{9fe}', '\u{a00}'), + ('\u{a04}', '\u{a04}'), ('\u{a0b}', '\u{a0e}'), ('\u{a11}', '\u{a12}'), + ('\u{a29}', '\u{a29}'), ('\u{a31}', '\u{a31}'), ('\u{a34}', '\u{a34}'), + ('\u{a37}', '\u{a37}'), ('\u{a3a}', '\u{a3b}'), ('\u{a3d}', '\u{a3d}'), + ('\u{a43}', '\u{a46}'), ('\u{a49}', '\u{a4a}'), ('\u{a4e}', '\u{a50}'), + ('\u{a52}', '\u{a58}'), ('\u{a5d}', '\u{a5d}'), ('\u{a5f}', '\u{a65}'), + ('\u{a76}', '\u{a80}'), ('\u{a84}', '\u{a84}'), ('\u{a8e}', '\u{a8e}'), + ('\u{a92}', '\u{a92}'), ('\u{aa9}', '\u{aa9}'), ('\u{ab1}', '\u{ab1}'), + ('\u{ab4}', '\u{ab4}'), ('\u{aba}', '\u{abb}'), ('\u{ac6}', '\u{ac6}'), + ('\u{aca}', '\u{aca}'), ('\u{ace}', '\u{acf}'), ('\u{ad1}', '\u{adf}'), + ('\u{ae4}', '\u{ae5}'), ('\u{af2}', '\u{af8}'), ('\u{b00}', '\u{b00}'), + ('\u{b04}', '\u{b04}'), ('\u{b0d}', '\u{b0e}'), ('\u{b11}', '\u{b12}'), + ('\u{b29}', '\u{b29}'), ('\u{b31}', '\u{b31}'), ('\u{b34}', '\u{b34}'), + ('\u{b3a}', '\u{b3b}'), ('\u{b45}', '\u{b46}'), ('\u{b49}', '\u{b4a}'), + ('\u{b4e}', '\u{b55}'), ('\u{b58}', '\u{b5b}'), ('\u{b5e}', '\u{b5e}'), + ('\u{b64}', '\u{b65}'), ('\u{b78}', '\u{b81}'), ('\u{b84}', '\u{b84}'), + ('\u{b8b}', '\u{b8d}'), ('\u{b91}', '\u{b91}'), ('\u{b96}', '\u{b98}'), + ('\u{b9b}', '\u{b9b}'), ('\u{b9d}', '\u{b9d}'), ('\u{ba0}', '\u{ba2}'), + ('\u{ba5}', '\u{ba7}'), ('\u{bab}', '\u{bad}'), ('\u{bba}', '\u{bbd}'), + ('\u{bc3}', '\u{bc5}'), ('\u{bc9}', '\u{bc9}'), ('\u{bce}', '\u{bcf}'), + ('\u{bd1}', '\u{bd6}'), ('\u{bd8}', '\u{be5}'), ('\u{bfb}', '\u{bff}'), + ('\u{c04}', '\u{c04}'), ('\u{c0d}', '\u{c0d}'), ('\u{c11}', '\u{c11}'), + ('\u{c29}', '\u{c29}'), ('\u{c3a}', '\u{c3c}'), ('\u{c45}', '\u{c45}'), + ('\u{c49}', '\u{c49}'), ('\u{c4e}', '\u{c54}'), ('\u{c57}', '\u{c57}'), + ('\u{c5b}', '\u{c5f}'), ('\u{c64}', '\u{c65}'), ('\u{c70}', '\u{c77}'), + ('\u{c84}', '\u{c84}'), ('\u{c8d}', '\u{c8d}'), ('\u{c91}', '\u{c91}'), + ('\u{ca9}', '\u{ca9}'), ('\u{cb4}', '\u{cb4}'), ('\u{cba}', '\u{cbb}'), + ('\u{cc5}', '\u{cc5}'), ('\u{cc9}', '\u{cc9}'), ('\u{cce}', '\u{cd4}'), + ('\u{cd7}', '\u{cdd}'), ('\u{cdf}', '\u{cdf}'), ('\u{ce4}', '\u{ce5}'), + ('\u{cf0}', '\u{cf0}'), ('\u{cf3}', '\u{cff}'), ('\u{d04}', '\u{d04}'), + ('\u{d0d}', '\u{d0d}'), ('\u{d11}', '\u{d11}'), ('\u{d45}', '\u{d45}'), + ('\u{d49}', '\u{d49}'), ('\u{d50}', '\u{d53}'), ('\u{d64}', '\u{d65}'), + ('\u{d80}', '\u{d81}'), ('\u{d84}', '\u{d84}'), ('\u{d97}', '\u{d99}'), + ('\u{db2}', '\u{db2}'), ('\u{dbc}', '\u{dbc}'), ('\u{dbe}', '\u{dbf}'), + ('\u{dc7}', '\u{dc9}'), ('\u{dcb}', '\u{dce}'), ('\u{dd5}', '\u{dd5}'), + ('\u{dd7}', '\u{dd7}'), ('\u{de0}', '\u{de5}'), ('\u{df0}', '\u{df1}'), + ('\u{df5}', '\u{e00}'), ('\u{e3b}', '\u{e3e}'), ('\u{e5c}', '\u{e80}'), + ('\u{e83}', '\u{e83}'), ('\u{e85}', '\u{e86}'), ('\u{e89}', '\u{e89}'), + ('\u{e8b}', '\u{e8c}'), ('\u{e8e}', '\u{e93}'), ('\u{e98}', '\u{e98}'), + ('\u{ea0}', '\u{ea0}'), ('\u{ea4}', '\u{ea4}'), ('\u{ea6}', '\u{ea6}'), + ('\u{ea8}', '\u{ea9}'), ('\u{eac}', '\u{eac}'), ('\u{eba}', '\u{eba}'), + ('\u{ebe}', '\u{ebf}'), ('\u{ec5}', '\u{ec5}'), ('\u{ec7}', '\u{ec7}'), + ('\u{ece}', '\u{ecf}'), ('\u{eda}', '\u{edb}'), ('\u{ee0}', '\u{eff}'), + ('\u{f48}', '\u{f48}'), ('\u{f6d}', '\u{f70}'), ('\u{f98}', '\u{f98}'), + ('\u{fbd}', '\u{fbd}'), ('\u{fcd}', '\u{fcd}'), ('\u{fdb}', '\u{fff}'), + ('\u{10c6}', '\u{10c6}'), ('\u{10c8}', '\u{10cc}'), + ('\u{10ce}', '\u{10cf}'), ('\u{1249}', '\u{1249}'), + ('\u{124e}', '\u{124f}'), ('\u{1257}', '\u{1257}'), + ('\u{1259}', '\u{1259}'), ('\u{125e}', '\u{125f}'), + ('\u{1289}', '\u{1289}'), ('\u{128e}', '\u{128f}'), + ('\u{12b1}', '\u{12b1}'), ('\u{12b6}', '\u{12b7}'), + ('\u{12bf}', '\u{12bf}'), ('\u{12c1}', '\u{12c1}'), + ('\u{12c6}', '\u{12c7}'), ('\u{12d7}', '\u{12d7}'), + ('\u{1311}', '\u{1311}'), ('\u{1316}', '\u{1317}'), + ('\u{135b}', '\u{135c}'), ('\u{137d}', '\u{137f}'), + ('\u{139a}', '\u{139f}'), ('\u{13f6}', '\u{13f7}'), + ('\u{13fe}', '\u{13ff}'), ('\u{169d}', '\u{169f}'), + ('\u{16f9}', '\u{16ff}'), ('\u{170d}', '\u{170d}'), + ('\u{1715}', '\u{171f}'), ('\u{1737}', '\u{173f}'), + ('\u{1754}', '\u{175f}'), ('\u{176d}', '\u{176d}'), + ('\u{1771}', '\u{1771}'), ('\u{1774}', '\u{177f}'), + ('\u{17de}', '\u{17df}'), ('\u{17ea}', '\u{17ef}'), + ('\u{17fa}', '\u{17ff}'), ('\u{180e}', '\u{180f}'), + ('\u{181a}', '\u{181f}'), ('\u{1878}', '\u{187f}'), + ('\u{18ab}', '\u{18af}'), ('\u{18f6}', '\u{18ff}'), + ('\u{191f}', '\u{191f}'), ('\u{192c}', '\u{192f}'), + ('\u{193c}', '\u{193f}'), ('\u{1941}', '\u{1943}'), + ('\u{196e}', '\u{196f}'), ('\u{1975}', '\u{197f}'), + ('\u{19ac}', '\u{19af}'), ('\u{19ca}', '\u{19cf}'), + ('\u{19db}', '\u{19dd}'), ('\u{1a1c}', '\u{1a1d}'), + ('\u{1a5f}', '\u{1a5f}'), ('\u{1a7d}', '\u{1a7e}'), + ('\u{1a8a}', '\u{1a8f}'), ('\u{1a9a}', '\u{1a9f}'), + ('\u{1aae}', '\u{1aaf}'), ('\u{1abf}', '\u{1aff}'), + ('\u{1b4c}', '\u{1b4f}'), ('\u{1b7d}', '\u{1b7f}'), + ('\u{1bf4}', '\u{1bfb}'), ('\u{1c38}', '\u{1c3a}'), + ('\u{1c4a}', '\u{1c4c}'), ('\u{1c89}', '\u{1cbf}'), + ('\u{1cc8}', '\u{1ccf}'), ('\u{1cfa}', '\u{1cff}'), + ('\u{1dfa}', '\u{1dfa}'), ('\u{1f16}', '\u{1f17}'), + ('\u{1f1e}', '\u{1f1f}'), ('\u{1f46}', '\u{1f47}'), + ('\u{1f4e}', '\u{1f4f}'), ('\u{1f58}', '\u{1f58}'), + ('\u{1f5a}', '\u{1f5a}'), ('\u{1f5c}', '\u{1f5c}'), + ('\u{1f5e}', '\u{1f5e}'), ('\u{1f7e}', '\u{1f7f}'), + ('\u{1fb5}', '\u{1fb5}'), ('\u{1fc5}', '\u{1fc5}'), + ('\u{1fd4}', '\u{1fd5}'), ('\u{1fdc}', '\u{1fdc}'), + ('\u{1ff0}', '\u{1ff1}'), ('\u{1ff5}', '\u{1ff5}'), + ('\u{1fff}', '\u{1fff}'), ('\u{200b}', '\u{200f}'), + ('\u{202a}', '\u{202e}'), ('\u{2060}', '\u{206f}'), + ('\u{2072}', '\u{2073}'), ('\u{208f}', '\u{208f}'), + ('\u{209d}', '\u{209f}'), ('\u{20c0}', '\u{20cf}'), + ('\u{20f1}', '\u{20ff}'), ('\u{218c}', '\u{218f}'), + ('\u{2427}', '\u{243f}'), ('\u{244b}', '\u{245f}'), + ('\u{2b74}', '\u{2b75}'), ('\u{2b96}', '\u{2b97}'), + ('\u{2bba}', '\u{2bbc}'), ('\u{2bc9}', '\u{2bc9}'), + ('\u{2bd3}', '\u{2beb}'), ('\u{2bf0}', '\u{2bff}'), + ('\u{2c2f}', '\u{2c2f}'), ('\u{2c5f}', '\u{2c5f}'), + ('\u{2cf4}', '\u{2cf8}'), ('\u{2d26}', '\u{2d26}'), + ('\u{2d28}', '\u{2d2c}'), ('\u{2d2e}', '\u{2d2f}'), + ('\u{2d68}', '\u{2d6e}'), ('\u{2d71}', '\u{2d7e}'), + ('\u{2d97}', '\u{2d9f}'), ('\u{2da7}', '\u{2da7}'), + ('\u{2daf}', '\u{2daf}'), ('\u{2db7}', '\u{2db7}'), + ('\u{2dbf}', '\u{2dbf}'), ('\u{2dc7}', '\u{2dc7}'), + ('\u{2dcf}', '\u{2dcf}'), ('\u{2dd7}', '\u{2dd7}'), + ('\u{2ddf}', '\u{2ddf}'), ('\u{2e4a}', '\u{2e7f}'), + ('\u{2e9a}', '\u{2e9a}'), ('\u{2ef4}', '\u{2eff}'), + ('\u{2fd6}', '\u{2fef}'), ('\u{2ffc}', '\u{2fff}'), + ('\u{3040}', '\u{3040}'), ('\u{3097}', '\u{3098}'), + ('\u{3100}', '\u{3104}'), ('\u{312f}', '\u{3130}'), + ('\u{318f}', '\u{318f}'), ('\u{31bb}', '\u{31bf}'), + ('\u{31e4}', '\u{31ef}'), ('\u{321f}', '\u{321f}'), + ('\u{32ff}', '\u{32ff}'), ('\u{4db6}', '\u{4dbf}'), + ('\u{9feb}', '\u{9fff}'), ('\u{a48d}', '\u{a48f}'), + ('\u{a4c7}', '\u{a4cf}'), ('\u{a62c}', '\u{a63f}'), + ('\u{a6f8}', '\u{a6ff}'), ('\u{a7af}', '\u{a7af}'), + ('\u{a7b8}', '\u{a7f6}'), ('\u{a82c}', '\u{a82f}'), + ('\u{a83a}', '\u{a83f}'), ('\u{a878}', '\u{a87f}'), + ('\u{a8c6}', '\u{a8cd}'), ('\u{a8da}', '\u{a8df}'), + ('\u{a8fe}', '\u{a8ff}'), ('\u{a954}', '\u{a95e}'), + ('\u{a97d}', '\u{a97f}'), ('\u{a9ce}', '\u{a9ce}'), + ('\u{a9da}', '\u{a9dd}'), ('\u{a9ff}', '\u{a9ff}'), + ('\u{aa37}', '\u{aa3f}'), ('\u{aa4e}', '\u{aa4f}'), + ('\u{aa5a}', '\u{aa5b}'), ('\u{aac3}', '\u{aada}'), + ('\u{aaf7}', '\u{ab00}'), ('\u{ab07}', '\u{ab08}'), + ('\u{ab0f}', '\u{ab10}'), ('\u{ab17}', '\u{ab1f}'), + ('\u{ab27}', '\u{ab27}'), ('\u{ab2f}', '\u{ab2f}'), + ('\u{ab66}', '\u{ab6f}'), ('\u{abee}', '\u{abef}'), + ('\u{abfa}', '\u{abff}'), ('\u{d7a4}', '\u{d7af}'), + ('\u{d7c7}', '\u{d7ca}'), ('\u{d7fc}', '\u{f8ff}'), + ('\u{fa6e}', '\u{fa6f}'), ('\u{fada}', '\u{faff}'), + ('\u{fb07}', '\u{fb12}'), ('\u{fb18}', '\u{fb1c}'), + ('\u{fb37}', '\u{fb37}'), ('\u{fb3d}', '\u{fb3d}'), + ('\u{fb3f}', '\u{fb3f}'), ('\u{fb42}', '\u{fb42}'), + ('\u{fb45}', '\u{fb45}'), ('\u{fbc2}', '\u{fbd2}'), + ('\u{fd40}', '\u{fd4f}'), ('\u{fd90}', '\u{fd91}'), + ('\u{fdc8}', '\u{fdef}'), ('\u{fdfe}', '\u{fdff}'), + ('\u{fe1a}', '\u{fe1f}'), ('\u{fe53}', '\u{fe53}'), + ('\u{fe67}', '\u{fe67}'), ('\u{fe6c}', '\u{fe6f}'), + ('\u{fe75}', '\u{fe75}'), ('\u{fefd}', '\u{ff00}'), + ('\u{ffbf}', '\u{ffc1}'), ('\u{ffc8}', '\u{ffc9}'), + ('\u{ffd0}', '\u{ffd1}'), ('\u{ffd8}', '\u{ffd9}'), + ('\u{ffdd}', '\u{ffdf}'), ('\u{ffe7}', '\u{ffe7}'), + ('\u{ffef}', '\u{fffb}'), ('\u{fffe}', '\u{ffff}'), + ('\u{1000c}', '\u{1000c}'), ('\u{10027}', '\u{10027}'), + ('\u{1003b}', '\u{1003b}'), ('\u{1003e}', '\u{1003e}'), + ('\u{1004e}', '\u{1004f}'), ('\u{1005e}', '\u{1007f}'), + ('\u{100fb}', '\u{100ff}'), ('\u{10103}', '\u{10106}'), + ('\u{10134}', '\u{10136}'), ('\u{1018f}', '\u{1018f}'), + ('\u{1019c}', '\u{1019f}'), ('\u{101a1}', '\u{101cf}'), + ('\u{101fe}', '\u{1027f}'), ('\u{1029d}', '\u{1029f}'), + ('\u{102d1}', '\u{102df}'), ('\u{102fc}', '\u{102ff}'), + ('\u{10324}', '\u{1032c}'), ('\u{1034b}', '\u{1034f}'), + ('\u{1037b}', '\u{1037f}'), ('\u{1039e}', '\u{1039e}'), + ('\u{103c4}', '\u{103c7}'), ('\u{103d6}', '\u{103ff}'), + ('\u{1049e}', '\u{1049f}'), ('\u{104aa}', '\u{104af}'), + ('\u{104d4}', '\u{104d7}'), ('\u{104fc}', '\u{104ff}'), + ('\u{10528}', '\u{1052f}'), ('\u{10564}', '\u{1056e}'), + ('\u{10570}', '\u{105ff}'), ('\u{10737}', '\u{1073f}'), + ('\u{10756}', '\u{1075f}'), ('\u{10768}', '\u{107ff}'), + ('\u{10806}', '\u{10807}'), ('\u{10809}', '\u{10809}'), + ('\u{10836}', '\u{10836}'), ('\u{10839}', '\u{1083b}'), + ('\u{1083d}', '\u{1083e}'), ('\u{10856}', '\u{10856}'), + ('\u{1089f}', '\u{108a6}'), ('\u{108b0}', '\u{108df}'), + ('\u{108f3}', '\u{108f3}'), ('\u{108f6}', '\u{108fa}'), + ('\u{1091c}', '\u{1091e}'), ('\u{1093a}', '\u{1093e}'), + ('\u{10940}', '\u{1097f}'), ('\u{109b8}', '\u{109bb}'), + ('\u{109d0}', '\u{109d1}'), ('\u{10a04}', '\u{10a04}'), + ('\u{10a07}', '\u{10a0b}'), ('\u{10a14}', '\u{10a14}'), + ('\u{10a18}', '\u{10a18}'), ('\u{10a34}', '\u{10a37}'), + ('\u{10a3b}', '\u{10a3e}'), ('\u{10a48}', '\u{10a4f}'), + ('\u{10a59}', '\u{10a5f}'), ('\u{10aa0}', '\u{10abf}'), + ('\u{10ae7}', '\u{10aea}'), ('\u{10af7}', '\u{10aff}'), + ('\u{10b36}', '\u{10b38}'), ('\u{10b56}', '\u{10b57}'), + ('\u{10b73}', '\u{10b77}'), ('\u{10b92}', '\u{10b98}'), + ('\u{10b9d}', '\u{10ba8}'), ('\u{10bb0}', '\u{10bff}'), + ('\u{10c49}', '\u{10c7f}'), ('\u{10cb3}', '\u{10cbf}'), + ('\u{10cf3}', '\u{10cf9}'), ('\u{10d00}', '\u{10e5f}'), + ('\u{10e7f}', '\u{10fff}'), ('\u{1104e}', '\u{11051}'), + ('\u{11070}', '\u{1107e}'), ('\u{110bd}', '\u{110bd}'), + ('\u{110c2}', '\u{110cf}'), ('\u{110e9}', '\u{110ef}'), + ('\u{110fa}', '\u{110ff}'), ('\u{11135}', '\u{11135}'), + ('\u{11144}', '\u{1114f}'), ('\u{11177}', '\u{1117f}'), + ('\u{111ce}', '\u{111cf}'), ('\u{111e0}', '\u{111e0}'), + ('\u{111f5}', '\u{111ff}'), ('\u{11212}', '\u{11212}'), + ('\u{1123f}', '\u{1127f}'), ('\u{11287}', '\u{11287}'), + ('\u{11289}', '\u{11289}'), ('\u{1128e}', '\u{1128e}'), + ('\u{1129e}', '\u{1129e}'), ('\u{112aa}', '\u{112af}'), + ('\u{112eb}', '\u{112ef}'), ('\u{112fa}', '\u{112ff}'), + ('\u{11304}', '\u{11304}'), ('\u{1130d}', '\u{1130e}'), + ('\u{11311}', '\u{11312}'), ('\u{11329}', '\u{11329}'), + ('\u{11331}', '\u{11331}'), ('\u{11334}', '\u{11334}'), + ('\u{1133a}', '\u{1133b}'), ('\u{11345}', '\u{11346}'), + ('\u{11349}', '\u{1134a}'), ('\u{1134e}', '\u{1134f}'), + ('\u{11351}', '\u{11356}'), ('\u{11358}', '\u{1135c}'), + ('\u{11364}', '\u{11365}'), ('\u{1136d}', '\u{1136f}'), + ('\u{11375}', '\u{113ff}'), ('\u{1145a}', '\u{1145a}'), + ('\u{1145c}', '\u{1145c}'), ('\u{1145e}', '\u{1147f}'), + ('\u{114c8}', '\u{114cf}'), ('\u{114da}', '\u{1157f}'), + ('\u{115b6}', '\u{115b7}'), ('\u{115de}', '\u{115ff}'), + ('\u{11645}', '\u{1164f}'), ('\u{1165a}', '\u{1165f}'), + ('\u{1166d}', '\u{1167f}'), ('\u{116b8}', '\u{116bf}'), + ('\u{116ca}', '\u{116ff}'), ('\u{1171a}', '\u{1171c}'), + ('\u{1172c}', '\u{1172f}'), ('\u{11740}', '\u{1189f}'), + ('\u{118f3}', '\u{118fe}'), ('\u{11900}', '\u{119ff}'), + ('\u{11a48}', '\u{11a4f}'), ('\u{11a84}', '\u{11a85}'), + ('\u{11a9d}', '\u{11a9d}'), ('\u{11aa3}', '\u{11abf}'), + ('\u{11af9}', '\u{11bff}'), ('\u{11c09}', '\u{11c09}'), + ('\u{11c37}', '\u{11c37}'), ('\u{11c46}', '\u{11c4f}'), + ('\u{11c6d}', '\u{11c6f}'), ('\u{11c90}', '\u{11c91}'), + ('\u{11ca8}', '\u{11ca8}'), ('\u{11cb7}', '\u{11cff}'), + ('\u{11d07}', '\u{11d07}'), ('\u{11d0a}', '\u{11d0a}'), + ('\u{11d37}', '\u{11d39}'), ('\u{11d3b}', '\u{11d3b}'), + ('\u{11d3e}', '\u{11d3e}'), ('\u{11d48}', '\u{11d4f}'), + ('\u{11d5a}', '\u{11fff}'), ('\u{1239a}', '\u{123ff}'), + ('\u{1246f}', '\u{1246f}'), ('\u{12475}', '\u{1247f}'), + ('\u{12544}', '\u{12fff}'), ('\u{1342f}', '\u{143ff}'), + ('\u{14647}', '\u{167ff}'), ('\u{16a39}', '\u{16a3f}'), + ('\u{16a5f}', '\u{16a5f}'), ('\u{16a6a}', '\u{16a6d}'), + ('\u{16a70}', '\u{16acf}'), ('\u{16aee}', '\u{16aef}'), + ('\u{16af6}', '\u{16aff}'), ('\u{16b46}', '\u{16b4f}'), + ('\u{16b5a}', '\u{16b5a}'), ('\u{16b62}', '\u{16b62}'), + ('\u{16b78}', '\u{16b7c}'), ('\u{16b90}', '\u{16eff}'), + ('\u{16f45}', '\u{16f4f}'), ('\u{16f7f}', '\u{16f8e}'), + ('\u{16fa0}', '\u{16fdf}'), ('\u{16fe2}', '\u{16fff}'), + ('\u{187ed}', '\u{187ff}'), ('\u{18af3}', '\u{1afff}'), + ('\u{1b11f}', '\u{1b16f}'), ('\u{1b2fc}', '\u{1bbff}'), + ('\u{1bc6b}', '\u{1bc6f}'), ('\u{1bc7d}', '\u{1bc7f}'), + ('\u{1bc89}', '\u{1bc8f}'), ('\u{1bc9a}', '\u{1bc9b}'), + ('\u{1bca0}', '\u{1cfff}'), ('\u{1d0f6}', '\u{1d0ff}'), + ('\u{1d127}', '\u{1d128}'), ('\u{1d173}', '\u{1d17a}'), + ('\u{1d1e9}', '\u{1d1ff}'), ('\u{1d246}', '\u{1d2ff}'), + ('\u{1d357}', '\u{1d35f}'), ('\u{1d372}', '\u{1d3ff}'), + ('\u{1d455}', '\u{1d455}'), ('\u{1d49d}', '\u{1d49d}'), + ('\u{1d4a0}', '\u{1d4a1}'), ('\u{1d4a3}', '\u{1d4a4}'), + ('\u{1d4a7}', '\u{1d4a8}'), ('\u{1d4ad}', '\u{1d4ad}'), + ('\u{1d4ba}', '\u{1d4ba}'), ('\u{1d4bc}', '\u{1d4bc}'), + ('\u{1d4c4}', '\u{1d4c4}'), ('\u{1d506}', '\u{1d506}'), + ('\u{1d50b}', '\u{1d50c}'), ('\u{1d515}', '\u{1d515}'), + ('\u{1d51d}', '\u{1d51d}'), ('\u{1d53a}', '\u{1d53a}'), + ('\u{1d53f}', '\u{1d53f}'), ('\u{1d545}', '\u{1d545}'), + ('\u{1d547}', '\u{1d549}'), ('\u{1d551}', '\u{1d551}'), + ('\u{1d6a6}', '\u{1d6a7}'), ('\u{1d7cc}', '\u{1d7cd}'), + ('\u{1da8c}', '\u{1da9a}'), ('\u{1daa0}', '\u{1daa0}'), + ('\u{1dab0}', '\u{1dfff}'), ('\u{1e007}', '\u{1e007}'), + ('\u{1e019}', '\u{1e01a}'), ('\u{1e022}', '\u{1e022}'), + ('\u{1e025}', '\u{1e025}'), ('\u{1e02b}', '\u{1e7ff}'), + ('\u{1e8c5}', '\u{1e8c6}'), ('\u{1e8d7}', '\u{1e8ff}'), + ('\u{1e94b}', '\u{1e94f}'), ('\u{1e95a}', '\u{1e95d}'), + ('\u{1e960}', '\u{1edff}'), ('\u{1ee04}', '\u{1ee04}'), + ('\u{1ee20}', '\u{1ee20}'), ('\u{1ee23}', '\u{1ee23}'), + ('\u{1ee25}', '\u{1ee26}'), ('\u{1ee28}', '\u{1ee28}'), + ('\u{1ee33}', '\u{1ee33}'), ('\u{1ee38}', '\u{1ee38}'), + ('\u{1ee3a}', '\u{1ee3a}'), ('\u{1ee3c}', '\u{1ee41}'), + ('\u{1ee43}', '\u{1ee46}'), ('\u{1ee48}', '\u{1ee48}'), + ('\u{1ee4a}', '\u{1ee4a}'), ('\u{1ee4c}', '\u{1ee4c}'), + ('\u{1ee50}', '\u{1ee50}'), ('\u{1ee53}', '\u{1ee53}'), + ('\u{1ee55}', '\u{1ee56}'), ('\u{1ee58}', '\u{1ee58}'), + ('\u{1ee5a}', '\u{1ee5a}'), ('\u{1ee5c}', '\u{1ee5c}'), + ('\u{1ee5e}', '\u{1ee5e}'), ('\u{1ee60}', '\u{1ee60}'), + ('\u{1ee63}', '\u{1ee63}'), ('\u{1ee65}', '\u{1ee66}'), + ('\u{1ee6b}', '\u{1ee6b}'), ('\u{1ee73}', '\u{1ee73}'), + ('\u{1ee78}', '\u{1ee78}'), ('\u{1ee7d}', '\u{1ee7d}'), + ('\u{1ee7f}', '\u{1ee7f}'), ('\u{1ee8a}', '\u{1ee8a}'), + ('\u{1ee9c}', '\u{1eea0}'), ('\u{1eea4}', '\u{1eea4}'), + ('\u{1eeaa}', '\u{1eeaa}'), ('\u{1eebc}', '\u{1eeef}'), + ('\u{1eef2}', '\u{1efff}'), ('\u{1f02c}', '\u{1f02f}'), + ('\u{1f094}', '\u{1f09f}'), ('\u{1f0af}', '\u{1f0b0}'), + ('\u{1f0c0}', '\u{1f0c0}'), ('\u{1f0d0}', '\u{1f0d0}'), + ('\u{1f0f6}', '\u{1f0ff}'), ('\u{1f10d}', '\u{1f10f}'), + ('\u{1f12f}', '\u{1f12f}'), ('\u{1f16c}', '\u{1f16f}'), + ('\u{1f1ad}', '\u{1f1e5}'), ('\u{1f203}', '\u{1f20f}'), + ('\u{1f23c}', '\u{1f23f}'), ('\u{1f249}', '\u{1f24f}'), + ('\u{1f252}', '\u{1f25f}'), ('\u{1f266}', '\u{1f2ff}'), + ('\u{1f6d5}', '\u{1f6df}'), ('\u{1f6ed}', '\u{1f6ef}'), + ('\u{1f6f9}', '\u{1f6ff}'), ('\u{1f774}', '\u{1f77f}'), + ('\u{1f7d5}', '\u{1f7ff}'), ('\u{1f80c}', '\u{1f80f}'), + ('\u{1f848}', '\u{1f84f}'), ('\u{1f85a}', '\u{1f85f}'), + ('\u{1f888}', '\u{1f88f}'), ('\u{1f8ae}', '\u{1f8ff}'), + ('\u{1f90c}', '\u{1f90f}'), ('\u{1f93f}', '\u{1f93f}'), + ('\u{1f94d}', '\u{1f94f}'), ('\u{1f96c}', '\u{1f97f}'), + ('\u{1f998}', '\u{1f9bf}'), ('\u{1f9c1}', '\u{1f9cf}'), + ('\u{1f9e7}', '\u{1ffff}'), ('\u{2a6d7}', '\u{2a6ff}'), + ('\u{2b735}', '\u{2b73f}'), ('\u{2b81e}', '\u{2b81f}'), + ('\u{2cea2}', '\u{2ceaf}'), ('\u{2ebe1}', '\u{2f7ff}'), + ('\u{2fa1e}', '\u{e00ff}'), ('\u{e01f0}', '\u{10ffff}'), +]; + +pub const OTHER_LETTER: &'static [(char, char)] = &[ + ('ª', 'ª'), ('º', 'º'), ('ƻ', 'ƻ'), ('ǀ', 'ǃ'), ('ʔ', 'ʔ'), + ('א', 'ת'), ('װ', 'ײ'), ('ؠ', 'ؿ'), ('ف', 'ي'), ('ٮ', 'ٯ'), + ('ٱ', 'ۓ'), ('ە', 'ە'), ('ۮ', 'ۯ'), ('ۺ', 'ۼ'), ('ۿ', 'ۿ'), + ('ܐ', 'ܐ'), ('ܒ', 'ܯ'), ('ݍ', 'ޥ'), ('ޱ', 'ޱ'), ('ߊ', 'ߪ'), + ('ࠀ', 'ࠕ'), ('ࡀ', 'ࡘ'), ('ࡠ', 'ࡪ'), ('ࢠ', 'ࢴ'), + ('ࢶ', 'ࢽ'), ('ऄ', 'ह'), ('ऽ', 'ऽ'), ('ॐ', 'ॐ'), + ('क़', 'ॡ'), ('ॲ', 'ঀ'), ('অ', 'ঌ'), ('এ', 'ঐ'), + ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), ('শ', 'হ'), + ('ঽ', 'ঽ'), ('ৎ', 'ৎ'), ('ড়', 'ঢ়'), ('য়', 'ৡ'), + ('ৰ', 'ৱ'), ('ৼ', 'ৼ'), ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), + ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), + ('ਸ', 'ਹ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), ('ੲ', 'ੴ'), + ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), ('પ', 'ર'), + ('લ', 'ળ'), ('વ', 'હ'), ('ઽ', 'ઽ'), ('ૐ', 'ૐ'), + ('ૠ', 'ૡ'), ('ૹ', 'ૹ'), ('ଅ', 'ଌ'), ('ଏ', 'ଐ'), + ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), ('ଵ', 'ହ'), + ('ଽ', 'ଽ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୡ'), ('ୱ', 'ୱ'), + ('ஃ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), ('ஒ', 'க'), + ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), ('ண', 'த'), + ('ந', 'ப'), ('ம', 'ஹ'), ('ௐ', 'ௐ'), ('అ', 'ఌ'), + ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), ('ఽ', 'ఽ'), + ('ౘ', 'ౚ'), ('ౠ', 'ౡ'), ('ಀ', 'ಀ'), ('ಅ', 'ಌ'), + ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), + ('ಽ', 'ಽ'), ('ೞ', 'ೞ'), ('ೠ', 'ೡ'), ('ೱ', 'ೲ'), + ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ഺ'), ('ഽ', 'ഽ'), + ('ൎ', 'ൎ'), ('ൔ', 'ൖ'), ('ൟ', 'ൡ'), ('ൺ', 'ൿ'), + ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), ('ල', 'ල'), + ('ව', 'ෆ'), ('ก', 'ะ'), ('า', 'ำ'), ('เ', 'ๅ'), + ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), + ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), + ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ະ'), + ('າ', 'ຳ'), ('ຽ', 'ຽ'), ('ເ', 'ໄ'), ('ໜ', 'ໟ'), + ('ༀ', 'ༀ'), ('ཀ', 'ཇ'), ('ཉ', 'ཬ'), ('ྈ', 'ྌ'), + ('က', 'ဪ'), ('ဿ', 'ဿ'), ('ၐ', 'ၕ'), ('ၚ', 'ၝ'), + ('ၡ', 'ၡ'), ('ၥ', 'ၦ'), ('ၮ', 'ၰ'), ('ၵ', 'ႁ'), + ('ႎ', 'ႎ'), ('ა', 'ჺ'), ('ჽ', 'ቈ'), ('ቊ', 'ቍ'), + ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), ('በ', 'ኈ'), + ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), + ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), ('ዘ', 'ጐ'), + ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('ᎀ', 'ᎏ'), ('ᐁ', 'ᙬ'), + ('ᙯ', 'ᙿ'), ('ᚁ', 'ᚚ'), ('ᚠ', 'ᛪ'), ('ᛱ', 'ᛸ'), + ('ᜀ', 'ᜌ'), ('ᜎ', 'ᜑ'), ('ᜠ', 'ᜱ'), ('ᝀ', 'ᝑ'), + ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), ('ក', 'ឳ'), ('ៜ', 'ៜ'), + ('ᠠ', 'ᡂ'), ('ᡄ', 'ᡷ'), ('ᢀ', 'ᢄ'), ('ᢇ', 'ᢨ'), + ('ᢪ', 'ᢪ'), ('ᢰ', 'ᣵ'), ('ᤀ', 'ᤞ'), ('ᥐ', 'ᥭ'), + ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), ('ᨀ', 'ᨖ'), + ('ᨠ', 'ᩔ'), ('ᬅ', 'ᬳ'), ('ᭅ', 'ᭋ'), ('ᮃ', 'ᮠ'), + ('ᮮ', 'ᮯ'), ('ᮺ', 'ᯥ'), ('ᰀ', 'ᰣ'), ('ᱍ', 'ᱏ'), + ('ᱚ', 'ᱷ'), ('ᳩ', 'ᳬ'), ('ᳮ', 'ᳱ'), ('ᳵ', 'ᳶ'), + ('ℵ', 'ℸ'), ('ⴰ', 'ⵧ'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), + ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), + ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('〆', '〆'), + ('〼', '〼'), ('ぁ', 'ゖ'), ('ゟ', 'ゟ'), ('ァ', 'ヺ'), + ('ヿ', 'ヿ'), ('ㄅ', 'ㄮ'), ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), + ('ㇰ', 'ㇿ'), ('㐀', '䶵'), ('一', '鿪'), ('ꀀ', 'ꀔ'), + ('ꀖ', 'ꒌ'), ('ꓐ', 'ꓷ'), ('ꔀ', 'ꘋ'), ('ꘐ', 'ꘟ'), + ('ꘪ', 'ꘫ'), ('ꙮ', 'ꙮ'), ('ꚠ', 'ꛥ'), ('ꞏ', 'ꞏ'), + ('ꟷ', 'ꟷ'), ('ꟻ', 'ꠁ'), ('ꠃ', 'ꠅ'), ('ꠇ', 'ꠊ'), + ('ꠌ', 'ꠢ'), ('ꡀ', 'ꡳ'), ('ꢂ', 'ꢳ'), ('ꣲ', 'ꣷ'), + ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), ('ꤊ', 'ꤥ'), ('ꤰ', 'ꥆ'), + ('ꥠ', 'ꥼ'), ('ꦄ', 'ꦲ'), ('ꧠ', 'ꧤ'), ('ꧧ', 'ꧯ'), + ('ꧺ', 'ꧾ'), ('ꨀ', 'ꨨ'), ('ꩀ', 'ꩂ'), ('ꩄ', 'ꩋ'), + ('ꩠ', 'ꩯ'), ('ꩱ', 'ꩶ'), ('ꩺ', 'ꩺ'), ('ꩾ', 'ꪯ'), + ('ꪱ', 'ꪱ'), ('ꪵ', 'ꪶ'), ('ꪹ', 'ꪽ'), ('ꫀ', 'ꫀ'), + ('ꫂ', 'ꫂ'), ('ꫛ', 'ꫜ'), ('ꫠ', 'ꫪ'), ('ꫲ', 'ꫲ'), + ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), + ('ꬨ', 'ꬮ'), ('ꯀ', 'ꯢ'), ('가', '힣'), ('ힰ', 'ퟆ'), + ('ퟋ', 'ퟻ'), ('豈', '舘'), ('並', '龎'), ('יִ', 'יִ'), + ('ײַ', 'ﬨ'), ('שׁ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), + ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﮱ'), ('ﯓ', 'ﴽ'), + ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷻ'), ('ﹰ', 'ﹴ'), + ('ﹶ', 'ﻼ'), ('ヲ', 'ッ'), ('ア', 'ン'), ('ᅠ', 'ᄒ'), + ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), + ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), + ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐊀', '𐊜'), + ('𐊠', '𐋐'), ('𐌀', '𐌟'), ('𐌭', '𐍀'), ('𐍂', '𐍉'), + ('𐍐', '𐍵'), ('𐎀', '𐎝'), ('𐎠', '𐏃'), ('𐏈', '𐏏'), + ('𐑐', '𐒝'), ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐘀', '𐜶'), + ('𐝀', '𐝕'), ('𐝠', '𐝧'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), + ('𐠊', '𐠵'), ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐡕'), + ('𐡠', '𐡶'), ('𐢀', '𐢞'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), + ('𐤀', '𐤕'), ('𐤠', '𐤹'), ('𐦀', '𐦷'), ('𐦾', '𐦿'), + ('𐨀', '𐨀'), ('𐨐', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), + ('𐩠', '𐩼'), ('𐪀', '𐪜'), ('𐫀', '𐫇'), ('𐫉', '𐫤'), + ('𐬀', '𐬵'), ('𐭀', '𐭕'), ('𐭠', '𐭲'), ('𐮀', '𐮑'), + ('𐰀', '𐱈'), ('𑀃', '𑀷'), ('𑂃', '𑂯'), ('𑃐', '𑃨'), + ('𑄃', '𑄦'), ('𑅐', '𑅲'), ('𑅶', '𑅶'), ('𑆃', '𑆲'), + ('𑇁', '𑇄'), ('𑇚', '𑇚'), ('𑇜', '𑇜'), ('𑈀', '𑈑'), + ('𑈓', '𑈫'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), + ('𑊏', '𑊝'), ('𑊟', '𑊨'), ('𑊰', '𑋞'), ('𑌅', '𑌌'), + ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), ('𑌲', '𑌳'), + ('𑌵', '𑌹'), ('𑌽', '𑌽'), ('𑍐', '𑍐'), ('𑍝', '𑍡'), + ('𑐀', '𑐴'), ('𑑇', '𑑊'), ('𑒀', '𑒯'), ('𑓄', '𑓅'), + ('𑓇', '𑓇'), ('𑖀', '𑖮'), ('𑗘', '𑗛'), ('𑘀', '𑘯'), + ('𑙄', '𑙄'), ('𑚀', '𑚪'), ('𑜀', '𑜙'), ('𑣿', '𑣿'), + ('𑨀', '𑨀'), ('𑨋', '𑨲'), ('𑨺', '𑨺'), ('𑩐', '𑩐'), + ('𑩜', '𑪃'), ('𑪆', '𑪉'), ('𑫀', '𑫸'), ('𑰀', '𑰈'), + ('𑰊', '𑰮'), ('𑱀', '𑱀'), ('𑱲', '𑲏'), ('𑴀', '𑴆'), + ('𑴈', '𑴉'), ('𑴋', '𑴰'), ('𑵆', '𑵆'), ('𒀀', '𒎙'), + ('𒒀', '𒕃'), ('𓀀', '𓐮'), ('𔐀', '𔙆'), ('𖠀', '𖨸'), + ('𖩀', '𖩞'), ('𖫐', '𖫭'), ('𖬀', '𖬯'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽐'), ('𗀀', '𘟬'), + ('𘠀', '𘫲'), ('𛀀', '𛄞'), ('𛅰', '𛋻'), ('𛰀', '𛱪'), + ('𛱰', '𛱼'), ('𛲀', '𛲈'), ('𛲐', '𛲙'), ('𞠀', '𞣄'), + ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), + ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), + ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), + ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), + ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), + ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), + ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), + ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), + ('𞺫', '𞺻'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), ('𫝀', '𫠝'), + ('𫠠', '𬺡'), ('𬺰', '𮯠'), ('丽', '𪘀'), +]; + +pub const OTHER_NUMBER: &'static [(char, char)] = &[ + ('²', '³'), ('¹', '¹'), ('¼', '¾'), ('৴', '৹'), ('୲', '୷'), + ('௰', '௲'), ('౸', '౾'), ('൘', '൞'), ('൰', '൸'), + ('༪', '༳'), ('፩', '፼'), ('៰', '៹'), ('᧚', '᧚'), + ('⁰', '⁰'), ('⁴', '⁹'), ('₀', '₉'), ('⅐', '⅟'), + ('↉', '↉'), ('①', '⒛'), ('⓪', '⓿'), ('❶', '➓'), + ('⳽', '⳽'), ('㆒', '㆕'), ('㈠', '㈩'), ('㉈', '㉏'), + ('㉑', '㉟'), ('㊀', '㊉'), ('㊱', '㊿'), ('꠰', '꠵'), + ('𐄇', '𐄳'), ('𐅵', '𐅸'), ('𐆊', '𐆋'), ('𐋡', '𐋻'), + ('𐌠', '𐌣'), ('𐡘', '𐡟'), ('𐡹', '𐡿'), ('𐢧', '𐢯'), + ('𐣻', '𐣿'), ('𐤖', '𐤛'), ('𐦼', '𐦽'), ('𐧀', '𐧏'), + ('𐧒', '𐧿'), ('𐩀', '𐩇'), ('𐩽', '𐩾'), ('𐪝', '𐪟'), + ('𐫫', '𐫯'), ('𐭘', '𐭟'), ('𐭸', '𐭿'), ('𐮩', '𐮯'), + ('𐳺', '𐳿'), ('𐹠', '𐹾'), ('𑁒', '𑁥'), ('𑇡', '𑇴'), + ('𑜺', '𑜻'), ('𑣪', '𑣲'), ('𑱚', '𑱬'), ('𖭛', '𖭡'), + ('𝍠', '𝍱'), ('𞣇', '𞣏'), ('🄀', '🄌'), +]; + +pub const OTHER_PUNCTUATION: &'static [(char, char)] = &[ + ('!', '#'), ('%', '\''), ('*', '*'), (',', ','), ('.', '/'), (':', ';'), + ('?', '@'), ('\\', '\\'), ('¡', '¡'), ('§', '§'), ('¶', '·'), + ('¿', '¿'), (';', ';'), ('·', '·'), ('՚', '՟'), ('։', '։'), + ('׀', '׀'), ('׃', '׃'), ('׆', '׆'), ('׳', '״'), ('؉', '؊'), + ('،', '؍'), ('؛', '؛'), ('؞', '؟'), ('٪', '٭'), ('۔', '۔'), + ('܀', '܍'), ('߷', '߹'), ('࠰', '࠾'), ('࡞', '࡞'), ('।', '॥'), + ('॰', '॰'), ('৽', '৽'), ('૰', '૰'), ('෴', '෴'), + ('๏', '๏'), ('๚', '๛'), ('༄', '༒'), ('༔', '༔'), + ('྅', '྅'), ('࿐', '࿔'), ('࿙', '࿚'), ('၊', '၏'), + ('჻', '჻'), ('፠', '፨'), ('᙭', '᙮'), ('᛫', '᛭'), + ('᜵', '᜶'), ('។', '៖'), ('៘', '៚'), ('᠀', '᠅'), + ('᠇', '᠊'), ('᥄', '᥅'), ('᨞', '᨟'), ('᪠', '᪦'), + ('᪨', '᪭'), ('᭚', '᭠'), ('᯼', '᯿'), ('᰻', '᰿'), + ('᱾', '᱿'), ('᳀', '᳇'), ('᳓', '᳓'), ('‖', '‗'), + ('†', '‧'), ('‰', '‸'), ('※', '‾'), ('⁁', '⁃'), + ('⁇', '⁑'), ('⁓', '⁓'), ('⁕', '⁞'), ('⳹', '⳼'), + ('⳾', '⳿'), ('⵰', '⵰'), ('⸀', '⸁'), ('⸆', '⸈'), + ('⸋', '⸋'), ('⸎', '⸖'), ('⸘', '⸙'), ('⸛', '⸛'), + ('⸞', '⸟'), ('⸪', '⸮'), ('⸰', '⸹'), ('⸼', '⸿'), + ('⹁', '⹁'), ('⹃', '⹉'), ('、', '〃'), ('〽', '〽'), + ('・', '・'), ('꓾', '꓿'), ('꘍', '꘏'), ('꙳', '꙳'), + ('꙾', '꙾'), ('꛲', '꛷'), ('꡴', '꡷'), ('꣎', '꣏'), + ('꣸', '꣺'), ('꣼', '꣼'), ('꤮', '꤯'), ('꥟', '꥟'), + ('꧁', '꧍'), ('꧞', '꧟'), ('꩜', '꩟'), ('꫞', '꫟'), + ('꫰', '꫱'), ('꯫', '꯫'), ('︐', '︖'), ('︙', '︙'), + ('︰', '︰'), ('﹅', '﹆'), ('﹉', '﹌'), ('﹐', '﹒'), + ('﹔', '﹗'), ('﹟', '﹡'), ('﹨', '﹨'), ('﹪', '﹫'), + ('!', '#'), ('%', '''), ('*', '*'), (',', ','), + ('.', '/'), (':', ';'), ('?', '@'), ('\', '\'), + ('。', '。'), ('、', '・'), ('𐄀', '𐄂'), ('𐎟', '𐎟'), + ('𐏐', '𐏐'), ('𐕯', '𐕯'), ('𐡗', '𐡗'), ('𐤟', '𐤟'), + ('𐤿', '𐤿'), ('𐩐', '𐩘'), ('𐩿', '𐩿'), ('𐫰', '𐫶'), + ('𐬹', '𐬿'), ('𐮙', '𐮜'), ('𑁇', '𑁍'), ('𑂻', '𑂼'), + ('𑂾', '𑃁'), ('𑅀', '𑅃'), ('𑅴', '𑅵'), ('𑇅', '𑇉'), + ('𑇍', '𑇍'), ('𑇛', '𑇛'), ('𑇝', '𑇟'), ('𑈸', '𑈽'), + ('𑊩', '𑊩'), ('𑑋', '𑑏'), ('𑑛', '𑑛'), ('𑑝', '𑑝'), + ('𑓆', '𑓆'), ('𑗁', '𑗗'), ('𑙁', '𑙃'), ('𑙠', '𑙬'), + ('𑜼', '𑜾'), ('𑨿', '𑩆'), ('𑪚', '𑪜'), ('𑪞', '𑪢'), + ('𑱁', '𑱅'), ('𑱰', '𑱱'), ('𒑰', '𒑴'), ('𖩮', '𖩯'), + ('𖫵', '𖫵'), ('𖬷', '𖬻'), ('𖭄', '𖭄'), ('𛲟', '𛲟'), + ('𝪇', '𝪋'), ('𞥞', '𞥟'), +]; + +pub const OTHER_SYMBOL: &'static [(char, char)] = &[ + ('¦', '¦'), ('©', '©'), ('®', '®'), ('°', '°'), ('҂', '҂'), + ('֍', '֎'), ('؎', '؏'), ('۞', '۞'), ('۩', '۩'), ('۽', '۾'), + ('߶', '߶'), ('৺', '৺'), ('୰', '୰'), ('௳', '௸'), + ('௺', '௺'), ('౿', '౿'), ('൏', '൏'), ('൹', '൹'), + ('༁', '༃'), ('༓', '༓'), ('༕', '༗'), ('༚', '༟'), + ('༴', '༴'), ('༶', '༶'), ('༸', '༸'), ('྾', '࿅'), + ('࿇', '࿌'), ('࿎', '࿏'), ('࿕', '࿘'), ('႞', '႟'), + ('᎐', '᎙'), ('᥀', '᥀'), ('᧞', '᧿'), ('᭡', '᭪'), + ('᭴', '᭼'), ('℀', '℁'), ('℃', '℆'), ('℈', '℉'), + ('℔', '℔'), ('№', '℗'), ('℞', '℣'), ('℥', '℥'), + ('℧', '℧'), ('℩', '℩'), ('℮', '℮'), ('℺', '℻'), + ('⅊', '⅊'), ('⅌', '⅍'), ('⅏', '⅏'), ('↊', '↋'), + ('↕', '↙'), ('↜', '↟'), ('↡', '↢'), ('↤', '↥'), + ('↧', '↭'), ('↯', '⇍'), ('⇐', '⇑'), ('⇓', '⇓'), + ('⇕', '⇳'), ('⌀', '⌇'), ('⌌', '⌟'), ('⌢', '⌨'), + ('⌫', '⍻'), ('⍽', '⎚'), ('⎴', '⏛'), ('⏢', '␦'), + ('⑀', '⑊'), ('⒜', 'ⓩ'), ('─', '▶'), ('▸', '◀'), + ('◂', '◷'), ('☀', '♮'), ('♰', '❧'), ('➔', '➿'), + ('⠀', '⣿'), ('⬀', '⬯'), ('⭅', '⭆'), ('⭍', '⭳'), + ('⭶', '⮕'), ('⮘', '⮹'), ('⮽', '⯈'), ('⯊', '⯒'), + ('⯬', '⯯'), ('⳥', '⳪'), ('⺀', '⺙'), ('⺛', '⻳'), + ('⼀', '⿕'), ('⿰', '⿻'), ('〄', '〄'), ('〒', '〓'), + ('〠', '〠'), ('〶', '〷'), ('〾', '〿'), ('㆐', '㆑'), + ('㆖', '㆟'), ('㇀', '㇣'), ('㈀', '㈞'), ('㈪', '㉇'), + ('㉐', '㉐'), ('㉠', '㉿'), ('㊊', '㊰'), ('㋀', '㋾'), + ('㌀', '㏿'), ('䷀', '䷿'), ('꒐', '꓆'), ('꠨', '꠫'), + ('꠶', '꠷'), ('꠹', '꠹'), ('꩷', '꩹'), ('﷽', '﷽'), + ('¦', '¦'), ('│', '│'), ('■', '○'), ('', '�'), + ('𐄷', '𐄿'), ('𐅹', '𐆉'), ('𐆌', '𐆎'), ('𐆐', '𐆛'), + ('𐆠', '𐆠'), ('𐇐', '𐇼'), ('𐡷', '𐡸'), ('𐫈', '𐫈'), + ('𑜿', '𑜿'), ('𖬼', '𖬿'), ('𖭅', '𖭅'), ('𛲜', '𛲜'), + ('𝀀', '𝃵'), ('𝄀', '𝄦'), ('𝄩', '𝅘𝅥𝅲'), ('𝅪', '𝅬'), + ('𝆃', '𝆄'), ('𝆌', '𝆩'), ('𝆮', '𝇨'), ('𝈀', '𝉁'), + ('𝉅', '𝉅'), ('𝌀', '𝍖'), ('𝠀', '𝧿'), ('𝨷', '𝨺'), + ('𝩭', '𝩴'), ('𝩶', '𝪃'), ('𝪅', '𝪆'), ('🀀', '🀫'), + ('🀰', '🂓'), ('🂠', '🂮'), ('🂱', '🂿'), ('🃁', '🃏'), + ('🃑', '🃵'), ('🄐', '🄮'), ('🄰', '🅫'), ('🅰', '🆬'), + ('🇦', '🈂'), ('🈐', '🈻'), ('🉀', '🉈'), ('🉐', '🉑'), + ('🉠', '🉥'), ('🌀', '🏺'), ('🐀', '🛔'), ('🛠', '🛬'), + ('🛰', '🛸'), ('🜀', '🝳'), ('🞀', '🟔'), ('🠀', '🠋'), + ('🠐', '🡇'), ('🡐', '🡙'), ('🡠', '🢇'), ('🢐', '🢭'), + ('🤀', '🤋'), ('🤐', '🤾'), ('🥀', '🥌'), ('🥐', '🥫'), + ('🦀', '🦗'), ('🧀', '🧀'), ('🧐', '🧦'), +]; + +pub const PARAGRAPH_SEPARATOR: &'static [(char, char)] = &[ + ('\u{2029}', '\u{2029}'), +]; + +pub const PRIVATE_USE: &'static [(char, char)] = &[ + ('\u{e000}', '\u{f8ff}'), ('\u{f0000}', '\u{ffffd}'), + ('\u{100000}', '\u{10fffd}'), +]; + +pub const PUNCTUATION: &'static [(char, char)] = &[ + ('!', '#'), ('%', '*'), (',', '/'), (':', ';'), ('?', '@'), ('[', ']'), + ('_', '_'), ('{', '{'), ('}', '}'), ('¡', '¡'), ('§', '§'), + ('«', '«'), ('¶', '·'), ('»', '»'), ('¿', '¿'), (';', ';'), + ('·', '·'), ('՚', '՟'), ('։', '֊'), ('־', '־'), ('׀', '׀'), + ('׃', '׃'), ('׆', '׆'), ('׳', '״'), ('؉', '؊'), ('،', '؍'), + ('؛', '؛'), ('؞', '؟'), ('٪', '٭'), ('۔', '۔'), ('܀', '܍'), + ('߷', '߹'), ('࠰', '࠾'), ('࡞', '࡞'), ('।', '॥'), + ('॰', '॰'), ('৽', '৽'), ('૰', '૰'), ('෴', '෴'), + ('๏', '๏'), ('๚', '๛'), ('༄', '༒'), ('༔', '༔'), + ('༺', '༽'), ('྅', '྅'), ('࿐', '࿔'), ('࿙', '࿚'), + ('၊', '၏'), ('჻', '჻'), ('፠', '፨'), ('᐀', '᐀'), + ('᙭', '᙮'), ('᚛', '᚜'), ('᛫', '᛭'), ('᜵', '᜶'), + ('។', '៖'), ('៘', '៚'), ('᠀', '᠊'), ('᥄', '᥅'), + ('᨞', '᨟'), ('᪠', '᪦'), ('᪨', '᪭'), ('᭚', '᭠'), + ('᯼', '᯿'), ('᰻', '᰿'), ('᱾', '᱿'), ('᳀', '᳇'), + ('᳓', '᳓'), ('‐', '‧'), ('‰', '⁃'), ('⁅', '⁑'), + ('⁓', '⁞'), ('⁽', '⁾'), ('₍', '₎'), ('⌈', '⌋'), + ('〈', '〉'), ('❨', '❵'), ('⟅', '⟆'), ('⟦', '⟯'), + ('⦃', '⦘'), ('⧘', '⧛'), ('⧼', '⧽'), ('⳹', '⳼'), + ('⳾', '⳿'), ('⵰', '⵰'), ('⸀', '⸮'), ('⸰', '⹉'), + ('、', '〃'), ('〈', '】'), ('〔', '〟'), ('〰', '〰'), + ('〽', '〽'), ('゠', '゠'), ('・', '・'), ('꓾', '꓿'), + ('꘍', '꘏'), ('꙳', '꙳'), ('꙾', '꙾'), ('꛲', '꛷'), + ('꡴', '꡷'), ('꣎', '꣏'), ('꣸', '꣺'), ('꣼', '꣼'), + ('꤮', '꤯'), ('꥟', '꥟'), ('꧁', '꧍'), ('꧞', '꧟'), + ('꩜', '꩟'), ('꫞', '꫟'), ('꫰', '꫱'), ('꯫', '꯫'), + ('﴾', '﴿'), ('︐', '︙'), ('︰', '﹒'), ('﹔', '﹡'), + ('﹣', '﹣'), ('﹨', '﹨'), ('﹪', '﹫'), ('!', '#'), + ('%', '*'), (',', '/'), (':', ';'), ('?', '@'), + ('[', ']'), ('_', '_'), ('{', '{'), ('}', '}'), + ('⦅', '・'), ('𐄀', '𐄂'), ('𐎟', '𐎟'), ('𐏐', '𐏐'), + ('𐕯', '𐕯'), ('𐡗', '𐡗'), ('𐤟', '𐤟'), ('𐤿', '𐤿'), + ('𐩐', '𐩘'), ('𐩿', '𐩿'), ('𐫰', '𐫶'), ('𐬹', '𐬿'), + ('𐮙', '𐮜'), ('𑁇', '𑁍'), ('𑂻', '𑂼'), ('𑂾', '𑃁'), + ('𑅀', '𑅃'), ('𑅴', '𑅵'), ('𑇅', '𑇉'), ('𑇍', '𑇍'), + ('𑇛', '𑇛'), ('𑇝', '𑇟'), ('𑈸', '𑈽'), ('𑊩', '𑊩'), + ('𑑋', '𑑏'), ('𑑛', '𑑛'), ('𑑝', '𑑝'), ('𑓆', '𑓆'), + ('𑗁', '𑗗'), ('𑙁', '𑙃'), ('𑙠', '𑙬'), ('𑜼', '𑜾'), + ('𑨿', '𑩆'), ('𑪚', '𑪜'), ('𑪞', '𑪢'), ('𑱁', '𑱅'), + ('𑱰', '𑱱'), ('𒑰', '𒑴'), ('𖩮', '𖩯'), ('𖫵', '𖫵'), + ('𖬷', '𖬻'), ('𖭄', '𖭄'), ('𛲟', '𛲟'), ('𝪇', '𝪋'), + ('𞥞', '𞥟'), +]; + +pub const SEPARATOR: &'static [(char, char)] = &[ + (' ', ' '), ('\u{a0}', '\u{a0}'), ('\u{1680}', '\u{1680}'), + ('\u{2000}', '\u{200a}'), ('\u{2028}', '\u{2029}'), + ('\u{202f}', '\u{202f}'), ('\u{205f}', '\u{205f}'), + ('\u{3000}', '\u{3000}'), +]; + +pub const SPACE_SEPARATOR: &'static [(char, char)] = &[ + (' ', ' '), ('\u{a0}', '\u{a0}'), ('\u{1680}', '\u{1680}'), + ('\u{2000}', '\u{200a}'), ('\u{202f}', '\u{202f}'), + ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}'), +]; + +pub const SPACING_MARK: &'static [(char, char)] = &[ + ('ः', 'ः'), ('ऻ', 'ऻ'), ('ा', 'ी'), ('ॉ', 'ौ'), + ('ॎ', 'ॏ'), ('ং', 'ঃ'), ('া', 'ী'), ('ে', 'ৈ'), + ('ো', 'ৌ'), ('ৗ', 'ৗ'), ('ਃ', 'ਃ'), ('ਾ', 'ੀ'), + ('ઃ', 'ઃ'), ('ા', 'ી'), ('ૉ', 'ૉ'), ('ો', 'ૌ'), + ('ଂ', 'ଃ'), ('ା', 'ା'), ('ୀ', 'ୀ'), ('େ', 'ୈ'), + ('ୋ', 'ୌ'), ('ୗ', 'ୗ'), ('ா', 'ி'), ('ு', 'ூ'), + ('ெ', 'ை'), ('ொ', 'ௌ'), ('ௗ', 'ௗ'), ('ఁ', 'ః'), + ('ు', 'ౄ'), ('ಂ', 'ಃ'), ('ಾ', 'ಾ'), ('ೀ', 'ೄ'), + ('ೇ', 'ೈ'), ('ೊ', 'ೋ'), ('ೕ', 'ೖ'), ('ം', 'ഃ'), + ('ാ', 'ീ'), ('െ', 'ൈ'), ('ൊ', 'ൌ'), ('ൗ', 'ൗ'), + ('ං', 'ඃ'), ('ා', 'ෑ'), ('ෘ', 'ෟ'), ('ෲ', 'ෳ'), + ('༾', '༿'), ('ཿ', 'ཿ'), ('ါ', 'ာ'), ('ေ', 'ေ'), + ('း', 'း'), ('ျ', 'ြ'), ('ၖ', 'ၗ'), ('ၢ', 'ၤ'), + ('ၧ', 'ၭ'), ('ႃ', 'ႄ'), ('ႇ', 'ႌ'), ('ႏ', 'ႏ'), + ('ႚ', 'ႜ'), ('ា', 'ា'), ('ើ', 'ៅ'), ('ះ', 'ៈ'), + ('ᤣ', 'ᤦ'), ('ᤩ', 'ᤫ'), ('ᤰ', 'ᤱ'), ('ᤳ', 'ᤸ'), + ('ᨙ', 'ᨚ'), ('ᩕ', 'ᩕ'), ('ᩗ', 'ᩗ'), ('ᩡ', 'ᩡ'), + ('ᩣ', 'ᩤ'), ('ᩭ', 'ᩲ'), ('ᬄ', 'ᬄ'), ('ᬵ', 'ᬵ'), + ('ᬻ', 'ᬻ'), ('ᬽ', 'ᭁ'), ('ᭃ', '᭄'), ('ᮂ', 'ᮂ'), + ('ᮡ', 'ᮡ'), ('ᮦ', 'ᮧ'), ('᮪', '᮪'), ('ᯧ', 'ᯧ'), + ('ᯪ', 'ᯬ'), ('ᯮ', 'ᯮ'), ('᯲', '᯳'), ('ᰤ', 'ᰫ'), + ('ᰴ', 'ᰵ'), ('᳡', '᳡'), ('ᳲ', 'ᳳ'), ('᳷', '᳷'), + ('〮', '〯'), ('ꠣ', 'ꠤ'), ('ꠧ', 'ꠧ'), ('ꢀ', 'ꢁ'), + ('ꢴ', 'ꣃ'), ('ꥒ', '꥓'), ('ꦃ', 'ꦃ'), ('ꦴ', 'ꦵ'), + ('ꦺ', 'ꦻ'), ('ꦽ', '꧀'), ('ꨯ', 'ꨰ'), ('ꨳ', 'ꨴ'), + ('ꩍ', 'ꩍ'), ('ꩻ', 'ꩻ'), ('ꩽ', 'ꩽ'), ('ꫫ', 'ꫫ'), + ('ꫮ', 'ꫯ'), ('ꫵ', 'ꫵ'), ('ꯣ', 'ꯤ'), ('ꯦ', 'ꯧ'), + ('ꯩ', 'ꯪ'), ('꯬', '꯬'), ('𑀀', '𑀀'), ('𑀂', '𑀂'), + ('𑂂', '𑂂'), ('𑂰', '𑂲'), ('𑂷', '𑂸'), ('𑄬', '𑄬'), + ('𑆂', '𑆂'), ('𑆳', '𑆵'), ('𑆿', '𑇀'), ('𑈬', '𑈮'), + ('𑈲', '𑈳'), ('𑈵', '𑈵'), ('𑋠', '𑋢'), ('𑌂', '𑌃'), + ('𑌾', '𑌿'), ('𑍁', '𑍄'), ('𑍇', '𑍈'), ('𑍋', '𑍍'), + ('𑍗', '𑍗'), ('𑍢', '𑍣'), ('𑐵', '𑐷'), ('𑑀', '𑑁'), + ('𑑅', '𑑅'), ('𑒰', '𑒲'), ('𑒹', '𑒹'), ('𑒻', '𑒾'), + ('𑓁', '𑓁'), ('𑖯', '𑖱'), ('𑖸', '𑖻'), ('𑖾', '𑖾'), + ('𑘰', '𑘲'), ('𑘻', '𑘼'), ('𑘾', '𑘾'), ('𑚬', '𑚬'), + ('𑚮', '𑚯'), ('𑚶', '𑚶'), ('𑜠', '𑜡'), ('𑜦', '𑜦'), + ('𑨇', '𑨈'), ('𑨹', '𑨹'), ('𑩗', '𑩘'), ('𑪗', '𑪗'), + ('𑰯', '𑰯'), ('𑰾', '𑰾'), ('𑲩', '𑲩'), ('𑲱', '𑲱'), + ('𑲴', '𑲴'), ('𖽑', '𖽾'), ('𝅥', '𝅦'), ('𝅭', '𝅲'), +]; + +pub const SYMBOL: &'static [(char, char)] = &[ + ('$', '$'), ('+', '+'), ('<', '>'), ('^', '^'), ('`', '`'), ('|', '|'), + ('~', '~'), ('¢', '¦'), ('¨', '©'), ('¬', '¬'), ('®', '±'), + ('´', '´'), ('¸', '¸'), ('×', '×'), ('÷', '÷'), ('˂', '˅'), + ('˒', '˟'), ('˥', '˫'), ('˭', '˭'), ('˯', '˿'), ('͵', '͵'), + ('΄', '΅'), ('϶', '϶'), ('҂', '҂'), ('֍', '֏'), ('؆', '؈'), + ('؋', '؋'), ('؎', '؏'), ('۞', '۞'), ('۩', '۩'), ('۽', '۾'), + ('߶', '߶'), ('৲', '৳'), ('৺', '৻'), ('૱', '૱'), + ('୰', '୰'), ('௳', '௺'), ('౿', '౿'), ('൏', '൏'), + ('൹', '൹'), ('฿', '฿'), ('༁', '༃'), ('༓', '༓'), + ('༕', '༗'), ('༚', '༟'), ('༴', '༴'), ('༶', '༶'), + ('༸', '༸'), ('྾', '࿅'), ('࿇', '࿌'), ('࿎', '࿏'), + ('࿕', '࿘'), ('႞', '႟'), ('᎐', '᎙'), ('៛', '៛'), + ('᥀', '᥀'), ('᧞', '᧿'), ('᭡', '᭪'), ('᭴', '᭼'), + ('᾽', '᾽'), ('᾿', '῁'), ('῍', '῏'), ('῝', '῟'), + ('῭', '`'), ('´', '῾'), ('⁄', '⁄'), ('⁒', '⁒'), + ('⁺', '⁼'), ('₊', '₌'), ('₠', '₿'), ('℀', '℁'), + ('℃', '℆'), ('℈', '℉'), ('℔', '℔'), ('№', '℘'), + ('℞', '℣'), ('℥', '℥'), ('℧', '℧'), ('℩', '℩'), + ('℮', '℮'), ('℺', '℻'), ('⅀', '⅄'), ('⅊', '⅍'), + ('⅏', '⅏'), ('↊', '↋'), ('←', '⌇'), ('⌌', '⌨'), + ('⌫', '␦'), ('⑀', '⑊'), ('⒜', 'ⓩ'), ('─', '❧'), + ('➔', '⟄'), ('⟇', '⟥'), ('⟰', '⦂'), ('⦙', '⧗'), + ('⧜', '⧻'), ('⧾', '⭳'), ('⭶', '⮕'), ('⮘', '⮹'), + ('⮽', '⯈'), ('⯊', '⯒'), ('⯬', '⯯'), ('⳥', '⳪'), + ('⺀', '⺙'), ('⺛', '⻳'), ('⼀', '⿕'), ('⿰', '⿻'), + ('〄', '〄'), ('〒', '〓'), ('〠', '〠'), ('〶', '〷'), + ('〾', '〿'), ('゛', '゜'), ('㆐', '㆑'), ('㆖', '㆟'), + ('㇀', '㇣'), ('㈀', '㈞'), ('㈪', '㉇'), ('㉐', '㉐'), + ('㉠', '㉿'), ('㊊', '㊰'), ('㋀', '㋾'), ('㌀', '㏿'), + ('䷀', '䷿'), ('꒐', '꓆'), ('꜀', '꜖'), ('꜠', '꜡'), + ('꞉', '꞊'), ('꠨', '꠫'), ('꠶', '꠹'), ('꩷', '꩹'), + ('꭛', '꭛'), ('﬩', '﬩'), ('﮲', '﯁'), ('﷼', '﷽'), + ('﹢', '﹢'), ('﹤', '﹦'), ('﹩', '﹩'), ('$', '$'), + ('+', '+'), ('<', '>'), ('^', '^'), ('`', '`'), + ('|', '|'), ('~', '~'), ('¢', '₩'), ('│', '○'), + ('', '�'), ('𐄷', '𐄿'), ('𐅹', '𐆉'), ('𐆌', '𐆎'), + ('𐆐', '𐆛'), ('𐆠', '𐆠'), ('𐇐', '𐇼'), ('𐡷', '𐡸'), + ('𐫈', '𐫈'), ('𑜿', '𑜿'), ('𖬼', '𖬿'), ('𖭅', '𖭅'), + ('𛲜', '𛲜'), ('𝀀', '𝃵'), ('𝄀', '𝄦'), ('𝄩', '𝅘𝅥𝅲'), + ('𝅪', '𝅬'), ('𝆃', '𝆄'), ('𝆌', '𝆩'), ('𝆮', '𝇨'), + ('𝈀', '𝉁'), ('𝉅', '𝉅'), ('𝌀', '𝍖'), ('𝛁', '𝛁'), + ('𝛛', '𝛛'), ('𝛻', '𝛻'), ('𝜕', '𝜕'), ('𝜵', '𝜵'), + ('𝝏', '𝝏'), ('𝝯', '𝝯'), ('𝞉', '𝞉'), ('𝞩', '𝞩'), + ('𝟃', '𝟃'), ('𝠀', '𝧿'), ('𝨷', '𝨺'), ('𝩭', '𝩴'), + ('𝩶', '𝪃'), ('𝪅', '𝪆'), ('𞻰', '𞻱'), ('🀀', '🀫'), + ('🀰', '🂓'), ('🂠', '🂮'), ('🂱', '🂿'), ('🃁', '🃏'), + ('🃑', '🃵'), ('🄐', '🄮'), ('🄰', '🅫'), ('🅰', '🆬'), + ('🇦', '🈂'), ('🈐', '🈻'), ('🉀', '🉈'), ('🉐', '🉑'), + ('🉠', '🉥'), ('🌀', '🛔'), ('🛠', '🛬'), ('🛰', '🛸'), + ('🜀', '🝳'), ('🞀', '🟔'), ('🠀', '🠋'), ('🠐', '🡇'), + ('🡐', '🡙'), ('🡠', '🢇'), ('🢐', '🢭'), ('🤀', '🤋'), + ('🤐', '🤾'), ('🥀', '🥌'), ('🥐', '🥫'), ('🦀', '🦗'), + ('🧀', '🧀'), ('🧐', '🧦'), +]; + +pub const TITLECASE_LETTER: &'static [(char, char)] = &[ + ('Dž', 'Dž'), ('Lj', 'Lj'), ('Nj', 'Nj'), ('Dz', 'Dz'), ('ᾈ', 'ᾏ'), + ('ᾘ', 'ᾟ'), ('ᾨ', 'ᾯ'), ('ᾼ', 'ᾼ'), ('ῌ', 'ῌ'), + ('ῼ', 'ῼ'), +]; + +pub const UNASSIGNED: &'static [(char, char)] = &[ + ('\u{378}', '\u{379}'), ('\u{380}', '\u{383}'), ('\u{38b}', '\u{38b}'), + ('\u{38d}', '\u{38d}'), ('\u{3a2}', '\u{3a2}'), ('\u{530}', '\u{530}'), + ('\u{557}', '\u{558}'), ('\u{560}', '\u{560}'), ('\u{588}', '\u{588}'), + ('\u{58b}', '\u{58c}'), ('\u{590}', '\u{590}'), ('\u{5c8}', '\u{5cf}'), + ('\u{5eb}', '\u{5ef}'), ('\u{5f5}', '\u{5ff}'), ('\u{61d}', '\u{61d}'), + ('\u{70e}', '\u{70e}'), ('\u{74b}', '\u{74c}'), ('\u{7b2}', '\u{7bf}'), + ('\u{7fb}', '\u{7ff}'), ('\u{82e}', '\u{82f}'), ('\u{83f}', '\u{83f}'), + ('\u{85c}', '\u{85d}'), ('\u{85f}', '\u{85f}'), ('\u{86b}', '\u{89f}'), + ('\u{8b5}', '\u{8b5}'), ('\u{8be}', '\u{8d3}'), ('\u{984}', '\u{984}'), + ('\u{98d}', '\u{98e}'), ('\u{991}', '\u{992}'), ('\u{9a9}', '\u{9a9}'), + ('\u{9b1}', '\u{9b1}'), ('\u{9b3}', '\u{9b5}'), ('\u{9ba}', '\u{9bb}'), + ('\u{9c5}', '\u{9c6}'), ('\u{9c9}', '\u{9ca}'), ('\u{9cf}', '\u{9d6}'), + ('\u{9d8}', '\u{9db}'), ('\u{9de}', '\u{9de}'), ('\u{9e4}', '\u{9e5}'), + ('\u{9fe}', '\u{a00}'), ('\u{a04}', '\u{a04}'), ('\u{a0b}', '\u{a0e}'), + ('\u{a11}', '\u{a12}'), ('\u{a29}', '\u{a29}'), ('\u{a31}', '\u{a31}'), + ('\u{a34}', '\u{a34}'), ('\u{a37}', '\u{a37}'), ('\u{a3a}', '\u{a3b}'), + ('\u{a3d}', '\u{a3d}'), ('\u{a43}', '\u{a46}'), ('\u{a49}', '\u{a4a}'), + ('\u{a4e}', '\u{a50}'), ('\u{a52}', '\u{a58}'), ('\u{a5d}', '\u{a5d}'), + ('\u{a5f}', '\u{a65}'), ('\u{a76}', '\u{a80}'), ('\u{a84}', '\u{a84}'), + ('\u{a8e}', '\u{a8e}'), ('\u{a92}', '\u{a92}'), ('\u{aa9}', '\u{aa9}'), + ('\u{ab1}', '\u{ab1}'), ('\u{ab4}', '\u{ab4}'), ('\u{aba}', '\u{abb}'), + ('\u{ac6}', '\u{ac6}'), ('\u{aca}', '\u{aca}'), ('\u{ace}', '\u{acf}'), + ('\u{ad1}', '\u{adf}'), ('\u{ae4}', '\u{ae5}'), ('\u{af2}', '\u{af8}'), + ('\u{b00}', '\u{b00}'), ('\u{b04}', '\u{b04}'), ('\u{b0d}', '\u{b0e}'), + ('\u{b11}', '\u{b12}'), ('\u{b29}', '\u{b29}'), ('\u{b31}', '\u{b31}'), + ('\u{b34}', '\u{b34}'), ('\u{b3a}', '\u{b3b}'), ('\u{b45}', '\u{b46}'), + ('\u{b49}', '\u{b4a}'), ('\u{b4e}', '\u{b55}'), ('\u{b58}', '\u{b5b}'), + ('\u{b5e}', '\u{b5e}'), ('\u{b64}', '\u{b65}'), ('\u{b78}', '\u{b81}'), + ('\u{b84}', '\u{b84}'), ('\u{b8b}', '\u{b8d}'), ('\u{b91}', '\u{b91}'), + ('\u{b96}', '\u{b98}'), ('\u{b9b}', '\u{b9b}'), ('\u{b9d}', '\u{b9d}'), + ('\u{ba0}', '\u{ba2}'), ('\u{ba5}', '\u{ba7}'), ('\u{bab}', '\u{bad}'), + ('\u{bba}', '\u{bbd}'), ('\u{bc3}', '\u{bc5}'), ('\u{bc9}', '\u{bc9}'), + ('\u{bce}', '\u{bcf}'), ('\u{bd1}', '\u{bd6}'), ('\u{bd8}', '\u{be5}'), + ('\u{bfb}', '\u{bff}'), ('\u{c04}', '\u{c04}'), ('\u{c0d}', '\u{c0d}'), + ('\u{c11}', '\u{c11}'), ('\u{c29}', '\u{c29}'), ('\u{c3a}', '\u{c3c}'), + ('\u{c45}', '\u{c45}'), ('\u{c49}', '\u{c49}'), ('\u{c4e}', '\u{c54}'), + ('\u{c57}', '\u{c57}'), ('\u{c5b}', '\u{c5f}'), ('\u{c64}', '\u{c65}'), + ('\u{c70}', '\u{c77}'), ('\u{c84}', '\u{c84}'), ('\u{c8d}', '\u{c8d}'), + ('\u{c91}', '\u{c91}'), ('\u{ca9}', '\u{ca9}'), ('\u{cb4}', '\u{cb4}'), + ('\u{cba}', '\u{cbb}'), ('\u{cc5}', '\u{cc5}'), ('\u{cc9}', '\u{cc9}'), + ('\u{cce}', '\u{cd4}'), ('\u{cd7}', '\u{cdd}'), ('\u{cdf}', '\u{cdf}'), + ('\u{ce4}', '\u{ce5}'), ('\u{cf0}', '\u{cf0}'), ('\u{cf3}', '\u{cff}'), + ('\u{d04}', '\u{d04}'), ('\u{d0d}', '\u{d0d}'), ('\u{d11}', '\u{d11}'), + ('\u{d45}', '\u{d45}'), ('\u{d49}', '\u{d49}'), ('\u{d50}', '\u{d53}'), + ('\u{d64}', '\u{d65}'), ('\u{d80}', '\u{d81}'), ('\u{d84}', '\u{d84}'), + ('\u{d97}', '\u{d99}'), ('\u{db2}', '\u{db2}'), ('\u{dbc}', '\u{dbc}'), + ('\u{dbe}', '\u{dbf}'), ('\u{dc7}', '\u{dc9}'), ('\u{dcb}', '\u{dce}'), + ('\u{dd5}', '\u{dd5}'), ('\u{dd7}', '\u{dd7}'), ('\u{de0}', '\u{de5}'), + ('\u{df0}', '\u{df1}'), ('\u{df5}', '\u{e00}'), ('\u{e3b}', '\u{e3e}'), + ('\u{e5c}', '\u{e80}'), ('\u{e83}', '\u{e83}'), ('\u{e85}', '\u{e86}'), + ('\u{e89}', '\u{e89}'), ('\u{e8b}', '\u{e8c}'), ('\u{e8e}', '\u{e93}'), + ('\u{e98}', '\u{e98}'), ('\u{ea0}', '\u{ea0}'), ('\u{ea4}', '\u{ea4}'), + ('\u{ea6}', '\u{ea6}'), ('\u{ea8}', '\u{ea9}'), ('\u{eac}', '\u{eac}'), + ('\u{eba}', '\u{eba}'), ('\u{ebe}', '\u{ebf}'), ('\u{ec5}', '\u{ec5}'), + ('\u{ec7}', '\u{ec7}'), ('\u{ece}', '\u{ecf}'), ('\u{eda}', '\u{edb}'), + ('\u{ee0}', '\u{eff}'), ('\u{f48}', '\u{f48}'), ('\u{f6d}', '\u{f70}'), + ('\u{f98}', '\u{f98}'), ('\u{fbd}', '\u{fbd}'), ('\u{fcd}', '\u{fcd}'), + ('\u{fdb}', '\u{fff}'), ('\u{10c6}', '\u{10c6}'), ('\u{10c8}', '\u{10cc}'), + ('\u{10ce}', '\u{10cf}'), ('\u{1249}', '\u{1249}'), + ('\u{124e}', '\u{124f}'), ('\u{1257}', '\u{1257}'), + ('\u{1259}', '\u{1259}'), ('\u{125e}', '\u{125f}'), + ('\u{1289}', '\u{1289}'), ('\u{128e}', '\u{128f}'), + ('\u{12b1}', '\u{12b1}'), ('\u{12b6}', '\u{12b7}'), + ('\u{12bf}', '\u{12bf}'), ('\u{12c1}', '\u{12c1}'), + ('\u{12c6}', '\u{12c7}'), ('\u{12d7}', '\u{12d7}'), + ('\u{1311}', '\u{1311}'), ('\u{1316}', '\u{1317}'), + ('\u{135b}', '\u{135c}'), ('\u{137d}', '\u{137f}'), + ('\u{139a}', '\u{139f}'), ('\u{13f6}', '\u{13f7}'), + ('\u{13fe}', '\u{13ff}'), ('\u{169d}', '\u{169f}'), + ('\u{16f9}', '\u{16ff}'), ('\u{170d}', '\u{170d}'), + ('\u{1715}', '\u{171f}'), ('\u{1737}', '\u{173f}'), + ('\u{1754}', '\u{175f}'), ('\u{176d}', '\u{176d}'), + ('\u{1771}', '\u{1771}'), ('\u{1774}', '\u{177f}'), + ('\u{17de}', '\u{17df}'), ('\u{17ea}', '\u{17ef}'), + ('\u{17fa}', '\u{17ff}'), ('\u{180f}', '\u{180f}'), + ('\u{181a}', '\u{181f}'), ('\u{1878}', '\u{187f}'), + ('\u{18ab}', '\u{18af}'), ('\u{18f6}', '\u{18ff}'), + ('\u{191f}', '\u{191f}'), ('\u{192c}', '\u{192f}'), + ('\u{193c}', '\u{193f}'), ('\u{1941}', '\u{1943}'), + ('\u{196e}', '\u{196f}'), ('\u{1975}', '\u{197f}'), + ('\u{19ac}', '\u{19af}'), ('\u{19ca}', '\u{19cf}'), + ('\u{19db}', '\u{19dd}'), ('\u{1a1c}', '\u{1a1d}'), + ('\u{1a5f}', '\u{1a5f}'), ('\u{1a7d}', '\u{1a7e}'), + ('\u{1a8a}', '\u{1a8f}'), ('\u{1a9a}', '\u{1a9f}'), + ('\u{1aae}', '\u{1aaf}'), ('\u{1abf}', '\u{1aff}'), + ('\u{1b4c}', '\u{1b4f}'), ('\u{1b7d}', '\u{1b7f}'), + ('\u{1bf4}', '\u{1bfb}'), ('\u{1c38}', '\u{1c3a}'), + ('\u{1c4a}', '\u{1c4c}'), ('\u{1c89}', '\u{1cbf}'), + ('\u{1cc8}', '\u{1ccf}'), ('\u{1cfa}', '\u{1cff}'), + ('\u{1dfa}', '\u{1dfa}'), ('\u{1f16}', '\u{1f17}'), + ('\u{1f1e}', '\u{1f1f}'), ('\u{1f46}', '\u{1f47}'), + ('\u{1f4e}', '\u{1f4f}'), ('\u{1f58}', '\u{1f58}'), + ('\u{1f5a}', '\u{1f5a}'), ('\u{1f5c}', '\u{1f5c}'), + ('\u{1f5e}', '\u{1f5e}'), ('\u{1f7e}', '\u{1f7f}'), + ('\u{1fb5}', '\u{1fb5}'), ('\u{1fc5}', '\u{1fc5}'), + ('\u{1fd4}', '\u{1fd5}'), ('\u{1fdc}', '\u{1fdc}'), + ('\u{1ff0}', '\u{1ff1}'), ('\u{1ff5}', '\u{1ff5}'), + ('\u{1fff}', '\u{1fff}'), ('\u{2065}', '\u{2065}'), + ('\u{2072}', '\u{2073}'), ('\u{208f}', '\u{208f}'), + ('\u{209d}', '\u{209f}'), ('\u{20c0}', '\u{20cf}'), + ('\u{20f1}', '\u{20ff}'), ('\u{218c}', '\u{218f}'), + ('\u{2427}', '\u{243f}'), ('\u{244b}', '\u{245f}'), + ('\u{2b74}', '\u{2b75}'), ('\u{2b96}', '\u{2b97}'), + ('\u{2bba}', '\u{2bbc}'), ('\u{2bc9}', '\u{2bc9}'), + ('\u{2bd3}', '\u{2beb}'), ('\u{2bf0}', '\u{2bff}'), + ('\u{2c2f}', '\u{2c2f}'), ('\u{2c5f}', '\u{2c5f}'), + ('\u{2cf4}', '\u{2cf8}'), ('\u{2d26}', '\u{2d26}'), + ('\u{2d28}', '\u{2d2c}'), ('\u{2d2e}', '\u{2d2f}'), + ('\u{2d68}', '\u{2d6e}'), ('\u{2d71}', '\u{2d7e}'), + ('\u{2d97}', '\u{2d9f}'), ('\u{2da7}', '\u{2da7}'), + ('\u{2daf}', '\u{2daf}'), ('\u{2db7}', '\u{2db7}'), + ('\u{2dbf}', '\u{2dbf}'), ('\u{2dc7}', '\u{2dc7}'), + ('\u{2dcf}', '\u{2dcf}'), ('\u{2dd7}', '\u{2dd7}'), + ('\u{2ddf}', '\u{2ddf}'), ('\u{2e4a}', '\u{2e7f}'), + ('\u{2e9a}', '\u{2e9a}'), ('\u{2ef4}', '\u{2eff}'), + ('\u{2fd6}', '\u{2fef}'), ('\u{2ffc}', '\u{2fff}'), + ('\u{3040}', '\u{3040}'), ('\u{3097}', '\u{3098}'), + ('\u{3100}', '\u{3104}'), ('\u{312f}', '\u{3130}'), + ('\u{318f}', '\u{318f}'), ('\u{31bb}', '\u{31bf}'), + ('\u{31e4}', '\u{31ef}'), ('\u{321f}', '\u{321f}'), + ('\u{32ff}', '\u{32ff}'), ('\u{4db6}', '\u{4dbf}'), + ('\u{9feb}', '\u{9fff}'), ('\u{a48d}', '\u{a48f}'), + ('\u{a4c7}', '\u{a4cf}'), ('\u{a62c}', '\u{a63f}'), + ('\u{a6f8}', '\u{a6ff}'), ('\u{a7af}', '\u{a7af}'), + ('\u{a7b8}', '\u{a7f6}'), ('\u{a82c}', '\u{a82f}'), + ('\u{a83a}', '\u{a83f}'), ('\u{a878}', '\u{a87f}'), + ('\u{a8c6}', '\u{a8cd}'), ('\u{a8da}', '\u{a8df}'), + ('\u{a8fe}', '\u{a8ff}'), ('\u{a954}', '\u{a95e}'), + ('\u{a97d}', '\u{a97f}'), ('\u{a9ce}', '\u{a9ce}'), + ('\u{a9da}', '\u{a9dd}'), ('\u{a9ff}', '\u{a9ff}'), + ('\u{aa37}', '\u{aa3f}'), ('\u{aa4e}', '\u{aa4f}'), + ('\u{aa5a}', '\u{aa5b}'), ('\u{aac3}', '\u{aada}'), + ('\u{aaf7}', '\u{ab00}'), ('\u{ab07}', '\u{ab08}'), + ('\u{ab0f}', '\u{ab10}'), ('\u{ab17}', '\u{ab1f}'), + ('\u{ab27}', '\u{ab27}'), ('\u{ab2f}', '\u{ab2f}'), + ('\u{ab66}', '\u{ab6f}'), ('\u{abee}', '\u{abef}'), + ('\u{abfa}', '\u{abff}'), ('\u{d7a4}', '\u{d7af}'), + ('\u{d7c7}', '\u{d7ca}'), ('\u{d7fc}', '\u{d7ff}'), + ('\u{fa6e}', '\u{fa6f}'), ('\u{fada}', '\u{faff}'), + ('\u{fb07}', '\u{fb12}'), ('\u{fb18}', '\u{fb1c}'), + ('\u{fb37}', '\u{fb37}'), ('\u{fb3d}', '\u{fb3d}'), + ('\u{fb3f}', '\u{fb3f}'), ('\u{fb42}', '\u{fb42}'), + ('\u{fb45}', '\u{fb45}'), ('\u{fbc2}', '\u{fbd2}'), + ('\u{fd40}', '\u{fd4f}'), ('\u{fd90}', '\u{fd91}'), + ('\u{fdc8}', '\u{fdef}'), ('\u{fdfe}', '\u{fdff}'), + ('\u{fe1a}', '\u{fe1f}'), ('\u{fe53}', '\u{fe53}'), + ('\u{fe67}', '\u{fe67}'), ('\u{fe6c}', '\u{fe6f}'), + ('\u{fe75}', '\u{fe75}'), ('\u{fefd}', '\u{fefe}'), + ('\u{ff00}', '\u{ff00}'), ('\u{ffbf}', '\u{ffc1}'), + ('\u{ffc8}', '\u{ffc9}'), ('\u{ffd0}', '\u{ffd1}'), + ('\u{ffd8}', '\u{ffd9}'), ('\u{ffdd}', '\u{ffdf}'), + ('\u{ffe7}', '\u{ffe7}'), ('\u{ffef}', '\u{fff8}'), + ('\u{fffe}', '\u{ffff}'), ('\u{1000c}', '\u{1000c}'), + ('\u{10027}', '\u{10027}'), ('\u{1003b}', '\u{1003b}'), + ('\u{1003e}', '\u{1003e}'), ('\u{1004e}', '\u{1004f}'), + ('\u{1005e}', '\u{1007f}'), ('\u{100fb}', '\u{100ff}'), + ('\u{10103}', '\u{10106}'), ('\u{10134}', '\u{10136}'), + ('\u{1018f}', '\u{1018f}'), ('\u{1019c}', '\u{1019f}'), + ('\u{101a1}', '\u{101cf}'), ('\u{101fe}', '\u{1027f}'), + ('\u{1029d}', '\u{1029f}'), ('\u{102d1}', '\u{102df}'), + ('\u{102fc}', '\u{102ff}'), ('\u{10324}', '\u{1032c}'), + ('\u{1034b}', '\u{1034f}'), ('\u{1037b}', '\u{1037f}'), + ('\u{1039e}', '\u{1039e}'), ('\u{103c4}', '\u{103c7}'), + ('\u{103d6}', '\u{103ff}'), ('\u{1049e}', '\u{1049f}'), + ('\u{104aa}', '\u{104af}'), ('\u{104d4}', '\u{104d7}'), + ('\u{104fc}', '\u{104ff}'), ('\u{10528}', '\u{1052f}'), + ('\u{10564}', '\u{1056e}'), ('\u{10570}', '\u{105ff}'), + ('\u{10737}', '\u{1073f}'), ('\u{10756}', '\u{1075f}'), + ('\u{10768}', '\u{107ff}'), ('\u{10806}', '\u{10807}'), + ('\u{10809}', '\u{10809}'), ('\u{10836}', '\u{10836}'), + ('\u{10839}', '\u{1083b}'), ('\u{1083d}', '\u{1083e}'), + ('\u{10856}', '\u{10856}'), ('\u{1089f}', '\u{108a6}'), + ('\u{108b0}', '\u{108df}'), ('\u{108f3}', '\u{108f3}'), + ('\u{108f6}', '\u{108fa}'), ('\u{1091c}', '\u{1091e}'), + ('\u{1093a}', '\u{1093e}'), ('\u{10940}', '\u{1097f}'), + ('\u{109b8}', '\u{109bb}'), ('\u{109d0}', '\u{109d1}'), + ('\u{10a04}', '\u{10a04}'), ('\u{10a07}', '\u{10a0b}'), + ('\u{10a14}', '\u{10a14}'), ('\u{10a18}', '\u{10a18}'), + ('\u{10a34}', '\u{10a37}'), ('\u{10a3b}', '\u{10a3e}'), + ('\u{10a48}', '\u{10a4f}'), ('\u{10a59}', '\u{10a5f}'), + ('\u{10aa0}', '\u{10abf}'), ('\u{10ae7}', '\u{10aea}'), + ('\u{10af7}', '\u{10aff}'), ('\u{10b36}', '\u{10b38}'), + ('\u{10b56}', '\u{10b57}'), ('\u{10b73}', '\u{10b77}'), + ('\u{10b92}', '\u{10b98}'), ('\u{10b9d}', '\u{10ba8}'), + ('\u{10bb0}', '\u{10bff}'), ('\u{10c49}', '\u{10c7f}'), + ('\u{10cb3}', '\u{10cbf}'), ('\u{10cf3}', '\u{10cf9}'), + ('\u{10d00}', '\u{10e5f}'), ('\u{10e7f}', '\u{10fff}'), + ('\u{1104e}', '\u{11051}'), ('\u{11070}', '\u{1107e}'), + ('\u{110c2}', '\u{110cf}'), ('\u{110e9}', '\u{110ef}'), + ('\u{110fa}', '\u{110ff}'), ('\u{11135}', '\u{11135}'), + ('\u{11144}', '\u{1114f}'), ('\u{11177}', '\u{1117f}'), + ('\u{111ce}', '\u{111cf}'), ('\u{111e0}', '\u{111e0}'), + ('\u{111f5}', '\u{111ff}'), ('\u{11212}', '\u{11212}'), + ('\u{1123f}', '\u{1127f}'), ('\u{11287}', '\u{11287}'), + ('\u{11289}', '\u{11289}'), ('\u{1128e}', '\u{1128e}'), + ('\u{1129e}', '\u{1129e}'), ('\u{112aa}', '\u{112af}'), + ('\u{112eb}', '\u{112ef}'), ('\u{112fa}', '\u{112ff}'), + ('\u{11304}', '\u{11304}'), ('\u{1130d}', '\u{1130e}'), + ('\u{11311}', '\u{11312}'), ('\u{11329}', '\u{11329}'), + ('\u{11331}', '\u{11331}'), ('\u{11334}', '\u{11334}'), + ('\u{1133a}', '\u{1133b}'), ('\u{11345}', '\u{11346}'), + ('\u{11349}', '\u{1134a}'), ('\u{1134e}', '\u{1134f}'), + ('\u{11351}', '\u{11356}'), ('\u{11358}', '\u{1135c}'), + ('\u{11364}', '\u{11365}'), ('\u{1136d}', '\u{1136f}'), + ('\u{11375}', '\u{113ff}'), ('\u{1145a}', '\u{1145a}'), + ('\u{1145c}', '\u{1145c}'), ('\u{1145e}', '\u{1147f}'), + ('\u{114c8}', '\u{114cf}'), ('\u{114da}', '\u{1157f}'), + ('\u{115b6}', '\u{115b7}'), ('\u{115de}', '\u{115ff}'), + ('\u{11645}', '\u{1164f}'), ('\u{1165a}', '\u{1165f}'), + ('\u{1166d}', '\u{1167f}'), ('\u{116b8}', '\u{116bf}'), + ('\u{116ca}', '\u{116ff}'), ('\u{1171a}', '\u{1171c}'), + ('\u{1172c}', '\u{1172f}'), ('\u{11740}', '\u{1189f}'), + ('\u{118f3}', '\u{118fe}'), ('\u{11900}', '\u{119ff}'), + ('\u{11a48}', '\u{11a4f}'), ('\u{11a84}', '\u{11a85}'), + ('\u{11a9d}', '\u{11a9d}'), ('\u{11aa3}', '\u{11abf}'), + ('\u{11af9}', '\u{11bff}'), ('\u{11c09}', '\u{11c09}'), + ('\u{11c37}', '\u{11c37}'), ('\u{11c46}', '\u{11c4f}'), + ('\u{11c6d}', '\u{11c6f}'), ('\u{11c90}', '\u{11c91}'), + ('\u{11ca8}', '\u{11ca8}'), ('\u{11cb7}', '\u{11cff}'), + ('\u{11d07}', '\u{11d07}'), ('\u{11d0a}', '\u{11d0a}'), + ('\u{11d37}', '\u{11d39}'), ('\u{11d3b}', '\u{11d3b}'), + ('\u{11d3e}', '\u{11d3e}'), ('\u{11d48}', '\u{11d4f}'), + ('\u{11d5a}', '\u{11fff}'), ('\u{1239a}', '\u{123ff}'), + ('\u{1246f}', '\u{1246f}'), ('\u{12475}', '\u{1247f}'), + ('\u{12544}', '\u{12fff}'), ('\u{1342f}', '\u{143ff}'), + ('\u{14647}', '\u{167ff}'), ('\u{16a39}', '\u{16a3f}'), + ('\u{16a5f}', '\u{16a5f}'), ('\u{16a6a}', '\u{16a6d}'), + ('\u{16a70}', '\u{16acf}'), ('\u{16aee}', '\u{16aef}'), + ('\u{16af6}', '\u{16aff}'), ('\u{16b46}', '\u{16b4f}'), + ('\u{16b5a}', '\u{16b5a}'), ('\u{16b62}', '\u{16b62}'), + ('\u{16b78}', '\u{16b7c}'), ('\u{16b90}', '\u{16eff}'), + ('\u{16f45}', '\u{16f4f}'), ('\u{16f7f}', '\u{16f8e}'), + ('\u{16fa0}', '\u{16fdf}'), ('\u{16fe2}', '\u{16fff}'), + ('\u{187ed}', '\u{187ff}'), ('\u{18af3}', '\u{1afff}'), + ('\u{1b11f}', '\u{1b16f}'), ('\u{1b2fc}', '\u{1bbff}'), + ('\u{1bc6b}', '\u{1bc6f}'), ('\u{1bc7d}', '\u{1bc7f}'), + ('\u{1bc89}', '\u{1bc8f}'), ('\u{1bc9a}', '\u{1bc9b}'), + ('\u{1bca4}', '\u{1cfff}'), ('\u{1d0f6}', '\u{1d0ff}'), + ('\u{1d127}', '\u{1d128}'), ('\u{1d1e9}', '\u{1d1ff}'), + ('\u{1d246}', '\u{1d2ff}'), ('\u{1d357}', '\u{1d35f}'), + ('\u{1d372}', '\u{1d3ff}'), ('\u{1d455}', '\u{1d455}'), + ('\u{1d49d}', '\u{1d49d}'), ('\u{1d4a0}', '\u{1d4a1}'), + ('\u{1d4a3}', '\u{1d4a4}'), ('\u{1d4a7}', '\u{1d4a8}'), + ('\u{1d4ad}', '\u{1d4ad}'), ('\u{1d4ba}', '\u{1d4ba}'), + ('\u{1d4bc}', '\u{1d4bc}'), ('\u{1d4c4}', '\u{1d4c4}'), + ('\u{1d506}', '\u{1d506}'), ('\u{1d50b}', '\u{1d50c}'), + ('\u{1d515}', '\u{1d515}'), ('\u{1d51d}', '\u{1d51d}'), + ('\u{1d53a}', '\u{1d53a}'), ('\u{1d53f}', '\u{1d53f}'), + ('\u{1d545}', '\u{1d545}'), ('\u{1d547}', '\u{1d549}'), + ('\u{1d551}', '\u{1d551}'), ('\u{1d6a6}', '\u{1d6a7}'), + ('\u{1d7cc}', '\u{1d7cd}'), ('\u{1da8c}', '\u{1da9a}'), + ('\u{1daa0}', '\u{1daa0}'), ('\u{1dab0}', '\u{1dfff}'), + ('\u{1e007}', '\u{1e007}'), ('\u{1e019}', '\u{1e01a}'), + ('\u{1e022}', '\u{1e022}'), ('\u{1e025}', '\u{1e025}'), + ('\u{1e02b}', '\u{1e7ff}'), ('\u{1e8c5}', '\u{1e8c6}'), + ('\u{1e8d7}', '\u{1e8ff}'), ('\u{1e94b}', '\u{1e94f}'), + ('\u{1e95a}', '\u{1e95d}'), ('\u{1e960}', '\u{1edff}'), + ('\u{1ee04}', '\u{1ee04}'), ('\u{1ee20}', '\u{1ee20}'), + ('\u{1ee23}', '\u{1ee23}'), ('\u{1ee25}', '\u{1ee26}'), + ('\u{1ee28}', '\u{1ee28}'), ('\u{1ee33}', '\u{1ee33}'), + ('\u{1ee38}', '\u{1ee38}'), ('\u{1ee3a}', '\u{1ee3a}'), + ('\u{1ee3c}', '\u{1ee41}'), ('\u{1ee43}', '\u{1ee46}'), + ('\u{1ee48}', '\u{1ee48}'), ('\u{1ee4a}', '\u{1ee4a}'), + ('\u{1ee4c}', '\u{1ee4c}'), ('\u{1ee50}', '\u{1ee50}'), + ('\u{1ee53}', '\u{1ee53}'), ('\u{1ee55}', '\u{1ee56}'), + ('\u{1ee58}', '\u{1ee58}'), ('\u{1ee5a}', '\u{1ee5a}'), + ('\u{1ee5c}', '\u{1ee5c}'), ('\u{1ee5e}', '\u{1ee5e}'), + ('\u{1ee60}', '\u{1ee60}'), ('\u{1ee63}', '\u{1ee63}'), + ('\u{1ee65}', '\u{1ee66}'), ('\u{1ee6b}', '\u{1ee6b}'), + ('\u{1ee73}', '\u{1ee73}'), ('\u{1ee78}', '\u{1ee78}'), + ('\u{1ee7d}', '\u{1ee7d}'), ('\u{1ee7f}', '\u{1ee7f}'), + ('\u{1ee8a}', '\u{1ee8a}'), ('\u{1ee9c}', '\u{1eea0}'), + ('\u{1eea4}', '\u{1eea4}'), ('\u{1eeaa}', '\u{1eeaa}'), + ('\u{1eebc}', '\u{1eeef}'), ('\u{1eef2}', '\u{1efff}'), + ('\u{1f02c}', '\u{1f02f}'), ('\u{1f094}', '\u{1f09f}'), + ('\u{1f0af}', '\u{1f0b0}'), ('\u{1f0c0}', '\u{1f0c0}'), + ('\u{1f0d0}', '\u{1f0d0}'), ('\u{1f0f6}', '\u{1f0ff}'), + ('\u{1f10d}', '\u{1f10f}'), ('\u{1f12f}', '\u{1f12f}'), + ('\u{1f16c}', '\u{1f16f}'), ('\u{1f1ad}', '\u{1f1e5}'), + ('\u{1f203}', '\u{1f20f}'), ('\u{1f23c}', '\u{1f23f}'), + ('\u{1f249}', '\u{1f24f}'), ('\u{1f252}', '\u{1f25f}'), + ('\u{1f266}', '\u{1f2ff}'), ('\u{1f6d5}', '\u{1f6df}'), + ('\u{1f6ed}', '\u{1f6ef}'), ('\u{1f6f9}', '\u{1f6ff}'), + ('\u{1f774}', '\u{1f77f}'), ('\u{1f7d5}', '\u{1f7ff}'), + ('\u{1f80c}', '\u{1f80f}'), ('\u{1f848}', '\u{1f84f}'), + ('\u{1f85a}', '\u{1f85f}'), ('\u{1f888}', '\u{1f88f}'), + ('\u{1f8ae}', '\u{1f8ff}'), ('\u{1f90c}', '\u{1f90f}'), + ('\u{1f93f}', '\u{1f93f}'), ('\u{1f94d}', '\u{1f94f}'), + ('\u{1f96c}', '\u{1f97f}'), ('\u{1f998}', '\u{1f9bf}'), + ('\u{1f9c1}', '\u{1f9cf}'), ('\u{1f9e7}', '\u{1ffff}'), + ('\u{2a6d7}', '\u{2a6ff}'), ('\u{2b735}', '\u{2b73f}'), + ('\u{2b81e}', '\u{2b81f}'), ('\u{2cea2}', '\u{2ceaf}'), + ('\u{2ebe1}', '\u{2f7ff}'), ('\u{2fa1e}', '\u{e0000}'), + ('\u{e0002}', '\u{e001f}'), ('\u{e0080}', '\u{e00ff}'), + ('\u{e01f0}', '\u{effff}'), ('\u{ffffe}', '\u{fffff}'), + ('\u{10fffe}', '\u{10ffff}'), +]; + +pub const UPPERCASE_LETTER: &'static [(char, char)] = &[ + ('A', 'Z'), ('À', 'Ö'), ('Ø', 'Þ'), ('Ā', 'Ā'), ('Ă', 'Ă'), + ('Ą', 'Ą'), ('Ć', 'Ć'), ('Ĉ', 'Ĉ'), ('Ċ', 'Ċ'), ('Č', 'Č'), + ('Ď', 'Ď'), ('Đ', 'Đ'), ('Ē', 'Ē'), ('Ĕ', 'Ĕ'), ('Ė', 'Ė'), + ('Ę', 'Ę'), ('Ě', 'Ě'), ('Ĝ', 'Ĝ'), ('Ğ', 'Ğ'), ('Ġ', 'Ġ'), + ('Ģ', 'Ģ'), ('Ĥ', 'Ĥ'), ('Ħ', 'Ħ'), ('Ĩ', 'Ĩ'), ('Ī', 'Ī'), + ('Ĭ', 'Ĭ'), ('Į', 'Į'), ('İ', 'İ'), ('IJ', 'IJ'), ('Ĵ', 'Ĵ'), + ('Ķ', 'Ķ'), ('Ĺ', 'Ĺ'), ('Ļ', 'Ļ'), ('Ľ', 'Ľ'), ('Ŀ', 'Ŀ'), + ('Ł', 'Ł'), ('Ń', 'Ń'), ('Ņ', 'Ņ'), ('Ň', 'Ň'), ('Ŋ', 'Ŋ'), + ('Ō', 'Ō'), ('Ŏ', 'Ŏ'), ('Ő', 'Ő'), ('Œ', 'Œ'), ('Ŕ', 'Ŕ'), + ('Ŗ', 'Ŗ'), ('Ř', 'Ř'), ('Ś', 'Ś'), ('Ŝ', 'Ŝ'), ('Ş', 'Ş'), + ('Š', 'Š'), ('Ţ', 'Ţ'), ('Ť', 'Ť'), ('Ŧ', 'Ŧ'), ('Ũ', 'Ũ'), + ('Ū', 'Ū'), ('Ŭ', 'Ŭ'), ('Ů', 'Ů'), ('Ű', 'Ű'), ('Ų', 'Ų'), + ('Ŵ', 'Ŵ'), ('Ŷ', 'Ŷ'), ('Ÿ', 'Ź'), ('Ż', 'Ż'), ('Ž', 'Ž'), + ('Ɓ', 'Ƃ'), ('Ƅ', 'Ƅ'), ('Ɔ', 'Ƈ'), ('Ɖ', 'Ƌ'), ('Ǝ', 'Ƒ'), + ('Ɠ', 'Ɣ'), ('Ɩ', 'Ƙ'), ('Ɯ', 'Ɲ'), ('Ɵ', 'Ơ'), ('Ƣ', 'Ƣ'), + ('Ƥ', 'Ƥ'), ('Ʀ', 'Ƨ'), ('Ʃ', 'Ʃ'), ('Ƭ', 'Ƭ'), ('Ʈ', 'Ư'), + ('Ʊ', 'Ƴ'), ('Ƶ', 'Ƶ'), ('Ʒ', 'Ƹ'), ('Ƽ', 'Ƽ'), ('DŽ', 'DŽ'), + ('LJ', 'LJ'), ('NJ', 'NJ'), ('Ǎ', 'Ǎ'), ('Ǐ', 'Ǐ'), ('Ǒ', 'Ǒ'), + ('Ǔ', 'Ǔ'), ('Ǖ', 'Ǖ'), ('Ǘ', 'Ǘ'), ('Ǚ', 'Ǚ'), ('Ǜ', 'Ǜ'), + ('Ǟ', 'Ǟ'), ('Ǡ', 'Ǡ'), ('Ǣ', 'Ǣ'), ('Ǥ', 'Ǥ'), ('Ǧ', 'Ǧ'), + ('Ǩ', 'Ǩ'), ('Ǫ', 'Ǫ'), ('Ǭ', 'Ǭ'), ('Ǯ', 'Ǯ'), ('DZ', 'DZ'), + ('Ǵ', 'Ǵ'), ('Ƕ', 'Ǹ'), ('Ǻ', 'Ǻ'), ('Ǽ', 'Ǽ'), ('Ǿ', 'Ǿ'), + ('Ȁ', 'Ȁ'), ('Ȃ', 'Ȃ'), ('Ȅ', 'Ȅ'), ('Ȇ', 'Ȇ'), ('Ȉ', 'Ȉ'), + ('Ȋ', 'Ȋ'), ('Ȍ', 'Ȍ'), ('Ȏ', 'Ȏ'), ('Ȑ', 'Ȑ'), ('Ȓ', 'Ȓ'), + ('Ȕ', 'Ȕ'), ('Ȗ', 'Ȗ'), ('Ș', 'Ș'), ('Ț', 'Ț'), ('Ȝ', 'Ȝ'), + ('Ȟ', 'Ȟ'), ('Ƞ', 'Ƞ'), ('Ȣ', 'Ȣ'), ('Ȥ', 'Ȥ'), ('Ȧ', 'Ȧ'), + ('Ȩ', 'Ȩ'), ('Ȫ', 'Ȫ'), ('Ȭ', 'Ȭ'), ('Ȯ', 'Ȯ'), ('Ȱ', 'Ȱ'), + ('Ȳ', 'Ȳ'), ('Ⱥ', 'Ȼ'), ('Ƚ', 'Ⱦ'), ('Ɂ', 'Ɂ'), ('Ƀ', 'Ɇ'), + ('Ɉ', 'Ɉ'), ('Ɋ', 'Ɋ'), ('Ɍ', 'Ɍ'), ('Ɏ', 'Ɏ'), ('Ͱ', 'Ͱ'), + ('Ͳ', 'Ͳ'), ('Ͷ', 'Ͷ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), + ('Ό', 'Ό'), ('Ύ', 'Ώ'), ('Α', 'Ρ'), ('Σ', 'Ϋ'), ('Ϗ', 'Ϗ'), + ('ϒ', 'ϔ'), ('Ϙ', 'Ϙ'), ('Ϛ', 'Ϛ'), ('Ϝ', 'Ϝ'), ('Ϟ', 'Ϟ'), + ('Ϡ', 'Ϡ'), ('Ϣ', 'Ϣ'), ('Ϥ', 'Ϥ'), ('Ϧ', 'Ϧ'), ('Ϩ', 'Ϩ'), + ('Ϫ', 'Ϫ'), ('Ϭ', 'Ϭ'), ('Ϯ', 'Ϯ'), ('ϴ', 'ϴ'), ('Ϸ', 'Ϸ'), + ('Ϲ', 'Ϻ'), ('Ͻ', 'Я'), ('Ѡ', 'Ѡ'), ('Ѣ', 'Ѣ'), ('Ѥ', 'Ѥ'), + ('Ѧ', 'Ѧ'), ('Ѩ', 'Ѩ'), ('Ѫ', 'Ѫ'), ('Ѭ', 'Ѭ'), ('Ѯ', 'Ѯ'), + ('Ѱ', 'Ѱ'), ('Ѳ', 'Ѳ'), ('Ѵ', 'Ѵ'), ('Ѷ', 'Ѷ'), ('Ѹ', 'Ѹ'), + ('Ѻ', 'Ѻ'), ('Ѽ', 'Ѽ'), ('Ѿ', 'Ѿ'), ('Ҁ', 'Ҁ'), ('Ҋ', 'Ҋ'), + ('Ҍ', 'Ҍ'), ('Ҏ', 'Ҏ'), ('Ґ', 'Ґ'), ('Ғ', 'Ғ'), ('Ҕ', 'Ҕ'), + ('Җ', 'Җ'), ('Ҙ', 'Ҙ'), ('Қ', 'Қ'), ('Ҝ', 'Ҝ'), ('Ҟ', 'Ҟ'), + ('Ҡ', 'Ҡ'), ('Ң', 'Ң'), ('Ҥ', 'Ҥ'), ('Ҧ', 'Ҧ'), ('Ҩ', 'Ҩ'), + ('Ҫ', 'Ҫ'), ('Ҭ', 'Ҭ'), ('Ү', 'Ү'), ('Ұ', 'Ұ'), ('Ҳ', 'Ҳ'), + ('Ҵ', 'Ҵ'), ('Ҷ', 'Ҷ'), ('Ҹ', 'Ҹ'), ('Һ', 'Һ'), ('Ҽ', 'Ҽ'), + ('Ҿ', 'Ҿ'), ('Ӏ', 'Ӂ'), ('Ӄ', 'Ӄ'), ('Ӆ', 'Ӆ'), ('Ӈ', 'Ӈ'), + ('Ӊ', 'Ӊ'), ('Ӌ', 'Ӌ'), ('Ӎ', 'Ӎ'), ('Ӑ', 'Ӑ'), ('Ӓ', 'Ӓ'), + ('Ӕ', 'Ӕ'), ('Ӗ', 'Ӗ'), ('Ә', 'Ә'), ('Ӛ', 'Ӛ'), ('Ӝ', 'Ӝ'), + ('Ӟ', 'Ӟ'), ('Ӡ', 'Ӡ'), ('Ӣ', 'Ӣ'), ('Ӥ', 'Ӥ'), ('Ӧ', 'Ӧ'), + ('Ө', 'Ө'), ('Ӫ', 'Ӫ'), ('Ӭ', 'Ӭ'), ('Ӯ', 'Ӯ'), ('Ӱ', 'Ӱ'), + ('Ӳ', 'Ӳ'), ('Ӵ', 'Ӵ'), ('Ӷ', 'Ӷ'), ('Ӹ', 'Ӹ'), ('Ӻ', 'Ӻ'), + ('Ӽ', 'Ӽ'), ('Ӿ', 'Ӿ'), ('Ԁ', 'Ԁ'), ('Ԃ', 'Ԃ'), ('Ԅ', 'Ԅ'), + ('Ԇ', 'Ԇ'), ('Ԉ', 'Ԉ'), ('Ԋ', 'Ԋ'), ('Ԍ', 'Ԍ'), ('Ԏ', 'Ԏ'), + ('Ԑ', 'Ԑ'), ('Ԓ', 'Ԓ'), ('Ԕ', 'Ԕ'), ('Ԗ', 'Ԗ'), ('Ԙ', 'Ԙ'), + ('Ԛ', 'Ԛ'), ('Ԝ', 'Ԝ'), ('Ԟ', 'Ԟ'), ('Ԡ', 'Ԡ'), ('Ԣ', 'Ԣ'), + ('Ԥ', 'Ԥ'), ('Ԧ', 'Ԧ'), ('Ԩ', 'Ԩ'), ('Ԫ', 'Ԫ'), ('Ԭ', 'Ԭ'), + ('Ԯ', 'Ԯ'), ('Ա', 'Ֆ'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('Ꭰ', 'Ᏽ'), ('Ḁ', 'Ḁ'), ('Ḃ', 'Ḃ'), ('Ḅ', 'Ḅ'), + ('Ḇ', 'Ḇ'), ('Ḉ', 'Ḉ'), ('Ḋ', 'Ḋ'), ('Ḍ', 'Ḍ'), + ('Ḏ', 'Ḏ'), ('Ḑ', 'Ḑ'), ('Ḓ', 'Ḓ'), ('Ḕ', 'Ḕ'), + ('Ḗ', 'Ḗ'), ('Ḙ', 'Ḙ'), ('Ḛ', 'Ḛ'), ('Ḝ', 'Ḝ'), + ('Ḟ', 'Ḟ'), ('Ḡ', 'Ḡ'), ('Ḣ', 'Ḣ'), ('Ḥ', 'Ḥ'), + ('Ḧ', 'Ḧ'), ('Ḩ', 'Ḩ'), ('Ḫ', 'Ḫ'), ('Ḭ', 'Ḭ'), + ('Ḯ', 'Ḯ'), ('Ḱ', 'Ḱ'), ('Ḳ', 'Ḳ'), ('Ḵ', 'Ḵ'), + ('Ḷ', 'Ḷ'), ('Ḹ', 'Ḹ'), ('Ḻ', 'Ḻ'), ('Ḽ', 'Ḽ'), + ('Ḿ', 'Ḿ'), ('Ṁ', 'Ṁ'), ('Ṃ', 'Ṃ'), ('Ṅ', 'Ṅ'), + ('Ṇ', 'Ṇ'), ('Ṉ', 'Ṉ'), ('Ṋ', 'Ṋ'), ('Ṍ', 'Ṍ'), + ('Ṏ', 'Ṏ'), ('Ṑ', 'Ṑ'), ('Ṓ', 'Ṓ'), ('Ṕ', 'Ṕ'), + ('Ṗ', 'Ṗ'), ('Ṙ', 'Ṙ'), ('Ṛ', 'Ṛ'), ('Ṝ', 'Ṝ'), + ('Ṟ', 'Ṟ'), ('Ṡ', 'Ṡ'), ('Ṣ', 'Ṣ'), ('Ṥ', 'Ṥ'), + ('Ṧ', 'Ṧ'), ('Ṩ', 'Ṩ'), ('Ṫ', 'Ṫ'), ('Ṭ', 'Ṭ'), + ('Ṯ', 'Ṯ'), ('Ṱ', 'Ṱ'), ('Ṳ', 'Ṳ'), ('Ṵ', 'Ṵ'), + ('Ṷ', 'Ṷ'), ('Ṹ', 'Ṹ'), ('Ṻ', 'Ṻ'), ('Ṽ', 'Ṽ'), + ('Ṿ', 'Ṿ'), ('Ẁ', 'Ẁ'), ('Ẃ', 'Ẃ'), ('Ẅ', 'Ẅ'), + ('Ẇ', 'Ẇ'), ('Ẉ', 'Ẉ'), ('Ẋ', 'Ẋ'), ('Ẍ', 'Ẍ'), + ('Ẏ', 'Ẏ'), ('Ẑ', 'Ẑ'), ('Ẓ', 'Ẓ'), ('Ẕ', 'Ẕ'), + ('ẞ', 'ẞ'), ('Ạ', 'Ạ'), ('Ả', 'Ả'), ('Ấ', 'Ấ'), + ('Ầ', 'Ầ'), ('Ẩ', 'Ẩ'), ('Ẫ', 'Ẫ'), ('Ậ', 'Ậ'), + ('Ắ', 'Ắ'), ('Ằ', 'Ằ'), ('Ẳ', 'Ẳ'), ('Ẵ', 'Ẵ'), + ('Ặ', 'Ặ'), ('Ẹ', 'Ẹ'), ('Ẻ', 'Ẻ'), ('Ẽ', 'Ẽ'), + ('Ế', 'Ế'), ('Ề', 'Ề'), ('Ể', 'Ể'), ('Ễ', 'Ễ'), + ('Ệ', 'Ệ'), ('Ỉ', 'Ỉ'), ('Ị', 'Ị'), ('Ọ', 'Ọ'), + ('Ỏ', 'Ỏ'), ('Ố', 'Ố'), ('Ồ', 'Ồ'), ('Ổ', 'Ổ'), + ('Ỗ', 'Ỗ'), ('Ộ', 'Ộ'), ('Ớ', 'Ớ'), ('Ờ', 'Ờ'), + ('Ở', 'Ở'), ('Ỡ', 'Ỡ'), ('Ợ', 'Ợ'), ('Ụ', 'Ụ'), + ('Ủ', 'Ủ'), ('Ứ', 'Ứ'), ('Ừ', 'Ừ'), ('Ử', 'Ử'), + ('Ữ', 'Ữ'), ('Ự', 'Ự'), ('Ỳ', 'Ỳ'), ('Ỵ', 'Ỵ'), + ('Ỷ', 'Ỷ'), ('Ỹ', 'Ỹ'), ('Ỻ', 'Ỻ'), ('Ỽ', 'Ỽ'), + ('Ỿ', 'Ỿ'), ('Ἀ', 'Ἇ'), ('Ἐ', 'Ἕ'), ('Ἠ', 'Ἧ'), + ('Ἰ', 'Ἷ'), ('Ὀ', 'Ὅ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), + ('Ὕ', 'Ὕ'), ('Ὗ', 'Ὗ'), ('Ὠ', 'Ὧ'), ('Ᾰ', 'Ά'), + ('Ὲ', 'Ή'), ('Ῐ', 'Ί'), ('Ῠ', 'Ῥ'), ('Ὸ', 'Ώ'), + ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), ('ℋ', 'ℍ'), ('ℐ', 'ℒ'), + ('ℕ', 'ℕ'), ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), ('Ω', 'Ω'), + ('ℨ', 'ℨ'), ('K', 'ℭ'), ('ℰ', 'ℳ'), ('ℾ', 'ℿ'), + ('ⅅ', 'ⅅ'), ('Ↄ', 'Ↄ'), ('Ⰰ', 'Ⱞ'), ('Ⱡ', 'Ⱡ'), + ('Ɫ', 'Ɽ'), ('Ⱨ', 'Ⱨ'), ('Ⱪ', 'Ⱪ'), ('Ⱬ', 'Ⱬ'), + ('Ɑ', 'Ɒ'), ('Ⱳ', 'Ⱳ'), ('Ⱶ', 'Ⱶ'), ('Ȿ', 'Ⲁ'), + ('Ⲃ', 'Ⲃ'), ('Ⲅ', 'Ⲅ'), ('Ⲇ', 'Ⲇ'), ('Ⲉ', 'Ⲉ'), + ('Ⲋ', 'Ⲋ'), ('Ⲍ', 'Ⲍ'), ('Ⲏ', 'Ⲏ'), ('Ⲑ', 'Ⲑ'), + ('Ⲓ', 'Ⲓ'), ('Ⲕ', 'Ⲕ'), ('Ⲗ', 'Ⲗ'), ('Ⲙ', 'Ⲙ'), + ('Ⲛ', 'Ⲛ'), ('Ⲝ', 'Ⲝ'), ('Ⲟ', 'Ⲟ'), ('Ⲡ', 'Ⲡ'), + ('Ⲣ', 'Ⲣ'), ('Ⲥ', 'Ⲥ'), ('Ⲧ', 'Ⲧ'), ('Ⲩ', 'Ⲩ'), + ('Ⲫ', 'Ⲫ'), ('Ⲭ', 'Ⲭ'), ('Ⲯ', 'Ⲯ'), ('Ⲱ', 'Ⲱ'), + ('Ⲳ', 'Ⲳ'), ('Ⲵ', 'Ⲵ'), ('Ⲷ', 'Ⲷ'), ('Ⲹ', 'Ⲹ'), + ('Ⲻ', 'Ⲻ'), ('Ⲽ', 'Ⲽ'), ('Ⲿ', 'Ⲿ'), ('Ⳁ', 'Ⳁ'), + ('Ⳃ', 'Ⳃ'), ('Ⳅ', 'Ⳅ'), ('Ⳇ', 'Ⳇ'), ('Ⳉ', 'Ⳉ'), + ('Ⳋ', 'Ⳋ'), ('Ⳍ', 'Ⳍ'), ('Ⳏ', 'Ⳏ'), ('Ⳑ', 'Ⳑ'), + ('Ⳓ', 'Ⳓ'), ('Ⳕ', 'Ⳕ'), ('Ⳗ', 'Ⳗ'), ('Ⳙ', 'Ⳙ'), + ('Ⳛ', 'Ⳛ'), ('Ⳝ', 'Ⳝ'), ('Ⳟ', 'Ⳟ'), ('Ⳡ', 'Ⳡ'), + ('Ⳣ', 'Ⳣ'), ('Ⳬ', 'Ⳬ'), ('Ⳮ', 'Ⳮ'), ('Ⳳ', 'Ⳳ'), + ('Ꙁ', 'Ꙁ'), ('Ꙃ', 'Ꙃ'), ('Ꙅ', 'Ꙅ'), ('Ꙇ', 'Ꙇ'), + ('Ꙉ', 'Ꙉ'), ('Ꙋ', 'Ꙋ'), ('Ꙍ', 'Ꙍ'), ('Ꙏ', 'Ꙏ'), + ('Ꙑ', 'Ꙑ'), ('Ꙓ', 'Ꙓ'), ('Ꙕ', 'Ꙕ'), ('Ꙗ', 'Ꙗ'), + ('Ꙙ', 'Ꙙ'), ('Ꙛ', 'Ꙛ'), ('Ꙝ', 'Ꙝ'), ('Ꙟ', 'Ꙟ'), + ('Ꙡ', 'Ꙡ'), ('Ꙣ', 'Ꙣ'), ('Ꙥ', 'Ꙥ'), ('Ꙧ', 'Ꙧ'), + ('Ꙩ', 'Ꙩ'), ('Ꙫ', 'Ꙫ'), ('Ꙭ', 'Ꙭ'), ('Ꚁ', 'Ꚁ'), + ('Ꚃ', 'Ꚃ'), ('Ꚅ', 'Ꚅ'), ('Ꚇ', 'Ꚇ'), ('Ꚉ', 'Ꚉ'), + ('Ꚋ', 'Ꚋ'), ('Ꚍ', 'Ꚍ'), ('Ꚏ', 'Ꚏ'), ('Ꚑ', 'Ꚑ'), + ('Ꚓ', 'Ꚓ'), ('Ꚕ', 'Ꚕ'), ('Ꚗ', 'Ꚗ'), ('Ꚙ', 'Ꚙ'), + ('Ꚛ', 'Ꚛ'), ('Ꜣ', 'Ꜣ'), ('Ꜥ', 'Ꜥ'), ('Ꜧ', 'Ꜧ'), + ('Ꜩ', 'Ꜩ'), ('Ꜫ', 'Ꜫ'), ('Ꜭ', 'Ꜭ'), ('Ꜯ', 'Ꜯ'), + ('Ꜳ', 'Ꜳ'), ('Ꜵ', 'Ꜵ'), ('Ꜷ', 'Ꜷ'), ('Ꜹ', 'Ꜹ'), + ('Ꜻ', 'Ꜻ'), ('Ꜽ', 'Ꜽ'), ('Ꜿ', 'Ꜿ'), ('Ꝁ', 'Ꝁ'), + ('Ꝃ', 'Ꝃ'), ('Ꝅ', 'Ꝅ'), ('Ꝇ', 'Ꝇ'), ('Ꝉ', 'Ꝉ'), + ('Ꝋ', 'Ꝋ'), ('Ꝍ', 'Ꝍ'), ('Ꝏ', 'Ꝏ'), ('Ꝑ', 'Ꝑ'), + ('Ꝓ', 'Ꝓ'), ('Ꝕ', 'Ꝕ'), ('Ꝗ', 'Ꝗ'), ('Ꝙ', 'Ꝙ'), + ('Ꝛ', 'Ꝛ'), ('Ꝝ', 'Ꝝ'), ('Ꝟ', 'Ꝟ'), ('Ꝡ', 'Ꝡ'), + ('Ꝣ', 'Ꝣ'), ('Ꝥ', 'Ꝥ'), ('Ꝧ', 'Ꝧ'), ('Ꝩ', 'Ꝩ'), + ('Ꝫ', 'Ꝫ'), ('Ꝭ', 'Ꝭ'), ('Ꝯ', 'Ꝯ'), ('Ꝺ', 'Ꝺ'), + ('Ꝼ', 'Ꝼ'), ('Ᵹ', 'Ꝿ'), ('Ꞁ', 'Ꞁ'), ('Ꞃ', 'Ꞃ'), + ('Ꞅ', 'Ꞅ'), ('Ꞇ', 'Ꞇ'), ('Ꞌ', 'Ꞌ'), ('Ɥ', 'Ɥ'), + ('Ꞑ', 'Ꞑ'), ('Ꞓ', 'Ꞓ'), ('Ꞗ', 'Ꞗ'), ('Ꞙ', 'Ꞙ'), + ('Ꞛ', 'Ꞛ'), ('Ꞝ', 'Ꞝ'), ('Ꞟ', 'Ꞟ'), ('Ꞡ', 'Ꞡ'), + ('Ꞣ', 'Ꞣ'), ('Ꞥ', 'Ꞥ'), ('Ꞧ', 'Ꞧ'), ('Ꞩ', 'Ꞩ'), + ('Ɦ', 'Ɪ'), ('Ʞ', 'Ꞵ'), ('Ꞷ', 'Ꞷ'), ('A', 'Z'), + ('𐐀', '𐐧'), ('𐒰', '𐓓'), ('𐲀', '𐲲'), ('𑢠', '𑢿'), + ('𝐀', '𝐙'), ('𝐴', '𝑍'), ('𝑨', '𝒁'), ('𝒜', '𝒜'), + ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), + ('𝒮', '𝒵'), ('𝓐', '𝓩'), ('𝔄', '𝔅'), ('𝔇', '𝔊'), + ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔸', '𝔹'), ('𝔻', '𝔾'), + ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕬', '𝖅'), + ('𝖠', '𝖹'), ('𝗔', '𝗭'), ('𝘈', '𝘡'), ('𝘼', '𝙕'), + ('𝙰', '𝚉'), ('𝚨', '𝛀'), ('𝛢', '𝛺'), ('𝜜', '𝜴'), + ('𝝖', '𝝮'), ('𝞐', '𝞨'), ('𝟊', '𝟊'), ('𞤀', '𞤡'), +]; diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/mod.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/mod.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,9 @@ +pub mod age; +pub mod case_folding_simple; +pub mod general_category; +pub mod perl_word; +pub mod property_bool; +pub mod property_names; +pub mod property_values; +pub mod script_extension; +pub mod script; diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/perl_word.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/perl_word.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/perl_word.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/perl_word.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,179 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate perl-word /home/andrew/tmp/ucd-10.0.0/ --chars +// +// ucd-generate is available on crates.io. + +pub const PERL_WORD: &'static [(char, char)] = &[ + ('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), + ('º', 'º'), ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), ('ˆ', 'ˑ'), + ('ˠ', 'ˤ'), ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('̀', 'ʹ'), ('Ͷ', 'ͷ'), + ('ͺ', 'ͽ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), + ('Ύ', 'Ρ'), ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('҃', 'ԯ'), ('Ա', 'Ֆ'), + ('ՙ', 'ՙ'), ('ա', 'և'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), + ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('א', 'ת'), ('װ', 'ײ'), ('ؐ', 'ؚ'), + ('ؠ', '٩'), ('ٮ', 'ۓ'), ('ە', 'ۜ'), ('۟', 'ۨ'), ('۪', 'ۼ'), + ('ۿ', 'ۿ'), ('ܐ', '݊'), ('ݍ', 'ޱ'), ('߀', 'ߵ'), ('ߺ', 'ߺ'), + ('ࠀ', '࠭'), ('ࡀ', '࡛'), ('ࡠ', 'ࡪ'), ('ࢠ', 'ࢴ'), + ('ࢶ', 'ࢽ'), ('ࣔ', '࣡'), ('ࣣ', 'ॣ'), ('०', '९'), + ('ॱ', 'ঃ'), ('অ', 'ঌ'), ('এ', 'ঐ'), ('ও', 'ন'), + ('প', 'র'), ('ল', 'ল'), ('শ', 'হ'), ('়', 'ৄ'), + ('ে', 'ৈ'), ('ো', 'ৎ'), ('ৗ', 'ৗ'), ('ড়', 'ঢ়'), + ('য়', 'ৣ'), ('০', 'ৱ'), ('ৼ', 'ৼ'), ('ਁ', 'ਃ'), + ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), + ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('਼', '਼'), + ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', '੍'), ('ੑ', 'ੑ'), + ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), ('੦', 'ੵ'), ('ઁ', 'ઃ'), + ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), ('પ', 'ર'), + ('લ', 'ળ'), ('વ', 'હ'), ('઼', 'ૅ'), ('ે', 'ૉ'), + ('ો', '્'), ('ૐ', 'ૐ'), ('ૠ', 'ૣ'), ('૦', '૯'), + ('ૹ', '૿'), ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), ('ଏ', 'ଐ'), + ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), ('ଵ', 'ହ'), + ('଼', 'ୄ'), ('େ', 'ୈ'), ('ୋ', '୍'), ('ୖ', 'ୗ'), + ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୣ'), ('୦', '୯'), ('ୱ', 'ୱ'), + ('ஂ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), ('ஒ', 'க'), + ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), ('ண', 'த'), + ('ந', 'ப'), ('ம', 'ஹ'), ('ா', 'ூ'), ('ெ', 'ை'), + ('ொ', '்'), ('ௐ', 'ௐ'), ('ௗ', 'ௗ'), ('௦', '௯'), + ('ఀ', 'ః'), ('అ', 'ఌ'), ('ఎ', 'ఐ'), ('ఒ', 'న'), + ('ప', 'హ'), ('ఽ', 'ౄ'), ('ె', 'ై'), ('ొ', '్'), + ('ౕ', 'ౖ'), ('ౘ', 'ౚ'), ('ౠ', 'ౣ'), ('౦', '౯'), + ('ಀ', 'ಃ'), ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), ('ಒ', 'ನ'), + ('ಪ', 'ಳ'), ('ವ', 'ಹ'), ('಼', 'ೄ'), ('ೆ', 'ೈ'), + ('ೊ', '್'), ('ೕ', 'ೖ'), ('ೞ', 'ೞ'), ('ೠ', 'ೣ'), + ('೦', '೯'), ('ೱ', 'ೲ'), ('ഀ', 'ഃ'), ('അ', 'ഌ'), + ('എ', 'ഐ'), ('ഒ', 'ൄ'), ('െ', 'ൈ'), ('ൊ', 'ൎ'), + ('ൔ', 'ൗ'), ('ൟ', 'ൣ'), ('൦', '൯'), ('ൺ', 'ൿ'), + ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('්', '්'), ('ා', 'ු'), + ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('෦', '෯'), ('ෲ', 'ෳ'), + ('ก', 'ฺ'), ('เ', '๎'), ('๐', '๙'), ('ກ', 'ຂ'), + ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), ('ຍ', 'ຍ'), + ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), ('ລ', 'ລ'), + ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), ('ົ', 'ຽ'), + ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('່', 'ໍ'), ('໐', '໙'), + ('ໜ', 'ໟ'), ('ༀ', 'ༀ'), ('༘', '༙'), ('༠', '༩'), + ('༵', '༵'), ('༷', '༷'), ('༹', '༹'), ('༾', 'ཇ'), + ('ཉ', 'ཬ'), ('ཱ', '྄'), ('྆', 'ྗ'), ('ྙ', 'ྼ'), + ('࿆', '࿆'), ('က', '၉'), ('ၐ', 'ႝ'), ('Ⴀ', 'Ⴥ'), + ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), ('ჼ', 'ቈ'), + ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), + ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), + ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), + ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('፝', '፟'), + ('ᎀ', 'ᎏ'), ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), + ('ᙯ', 'ᙿ'), ('ᚁ', 'ᚚ'), ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), + ('ᜀ', 'ᜌ'), ('ᜎ', '᜔'), ('ᜠ', '᜴'), ('ᝀ', 'ᝓ'), + ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), ('ᝲ', 'ᝳ'), ('ក', '៓'), + ('ៗ', 'ៗ'), ('ៜ', '៝'), ('០', '៩'), ('᠋', '᠍'), + ('᠐', '᠙'), ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢪ'), ('ᢰ', 'ᣵ'), + ('ᤀ', 'ᤞ'), ('ᤠ', 'ᤫ'), ('ᤰ', '᤻'), ('᥆', 'ᥭ'), + ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), ('᧐', '᧙'), + ('ᨀ', 'ᨛ'), ('ᨠ', 'ᩞ'), ('᩠', '᩼'), ('᩿', '᪉'), + ('᪐', '᪙'), ('ᪧ', 'ᪧ'), ('᪰', '᪾'), ('ᬀ', 'ᭋ'), + ('᭐', '᭙'), ('᭫', '᭳'), ('ᮀ', '᯳'), ('ᰀ', '᰷'), + ('᱀', '᱉'), ('ᱍ', 'ᱽ'), ('ᲀ', 'ᲈ'), ('᳐', '᳒'), + ('᳔', '᳹'), ('ᴀ', '᷹'), ('᷻', 'ἕ'), ('Ἐ', 'Ἕ'), + ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), + ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), + ('ᾶ', 'ᾼ'), ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), + ('ῐ', 'ΐ'), ('ῖ', 'Ί'), ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), + ('ῶ', 'ῼ'), ('\u{200c}', '\u{200d}'), ('‿', '⁀'), ('⁔', '⁔'), + ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('⃐', '⃰'), + ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), + ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), ('Ω', 'Ω'), ('ℨ', 'ℨ'), + ('K', 'ℭ'), ('ℯ', 'ℹ'), ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), + ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), ('Ⓐ', 'ⓩ'), ('Ⰰ', 'Ⱞ'), + ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳳ'), ('ⴀ', 'ⴥ'), + ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ⴰ', 'ⵧ'), ('ⵯ', 'ⵯ'), + ('⵿', 'ⶖ'), ('ⶠ', 'ⶦ'), ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), + ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), + ('ⷘ', 'ⷞ'), ('ⷠ', 'ⷿ'), ('ⸯ', 'ⸯ'), ('々', '〇'), + ('〡', '〯'), ('〱', '〵'), ('〸', '〼'), ('ぁ', 'ゖ'), + ('゙', '゚'), ('ゝ', 'ゟ'), ('ァ', 'ヺ'), ('ー', 'ヿ'), + ('ㄅ', 'ㄮ'), ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), ('ㇰ', 'ㇿ'), + ('㐀', '䶵'), ('一', '鿪'), ('ꀀ', 'ꒌ'), ('ꓐ', 'ꓽ'), + ('ꔀ', 'ꘌ'), ('ꘐ', 'ꘫ'), ('Ꙁ', '꙲'), ('ꙴ', '꙽'), + ('ꙿ', '꛱'), ('ꜗ', 'ꜟ'), ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), + ('Ʞ', 'ꞷ'), ('ꟷ', 'ꠧ'), ('ꡀ', 'ꡳ'), ('ꢀ', 'ꣅ'), + ('꣐', '꣙'), ('꣠', 'ꣷ'), ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), + ('꤀', '꤭'), ('ꤰ', '꥓'), ('ꥠ', 'ꥼ'), ('ꦀ', '꧀'), + ('ꧏ', '꧙'), ('ꧠ', 'ꧾ'), ('ꨀ', 'ꨶ'), ('ꩀ', 'ꩍ'), + ('꩐', '꩙'), ('ꩠ', 'ꩶ'), ('ꩺ', 'ꫂ'), ('ꫛ', 'ꫝ'), + ('ꫠ', 'ꫯ'), ('ꫲ', '꫶'), ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), + ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), + ('ꭜ', 'ꭥ'), ('ꭰ', 'ꯪ'), ('꯬', '꯭'), ('꯰', '꯹'), + ('가', '힣'), ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('豈', '舘'), + ('並', '龎'), ('ff', 'st'), ('ﬓ', 'ﬗ'), ('יִ', 'ﬨ'), + ('שׁ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), ('נּ', 'סּ'), + ('ףּ', 'פּ'), ('צּ', 'ﮱ'), ('ﯓ', 'ﴽ'), ('ﵐ', 'ﶏ'), + ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷻ'), ('︀', '️'), ('︠', '︯'), + ('︳', '︴'), ('﹍', '﹏'), ('ﹰ', 'ﹴ'), ('ﹶ', 'ﻼ'), + ('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z'), + ('ヲ', 'ᄒ'), ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), + ('ᅳ', 'ᅵ'), ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), + ('𐀼', '𐀽'), ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), + ('𐅀', '𐅴'), ('𐇽', '𐇽'), ('𐊀', '𐊜'), ('𐊠', '𐋐'), + ('𐋠', '𐋠'), ('𐌀', '𐌟'), ('𐌭', '𐍊'), ('𐍐', '𐍺'), + ('𐎀', '𐎝'), ('𐎠', '𐏃'), ('𐏈', '𐏏'), ('𐏑', '𐏕'), + ('𐐀', '𐒝'), ('𐒠', '𐒩'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), + ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐘀', '𐜶'), ('𐝀', '𐝕'), + ('𐝠', '𐝧'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), ('𐠊', '𐠵'), + ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐡕'), ('𐡠', '𐡶'), + ('𐢀', '𐢞'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐤀', '𐤕'), + ('𐤠', '𐤹'), ('𐦀', '𐦷'), ('𐦾', '𐦿'), ('𐨀', '𐨃'), + ('𐨅', '𐨆'), ('𐨌', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), + ('𐨸', '𐨺'), ('𐨿', '𐨿'), ('𐩠', '𐩼'), ('𐪀', '𐪜'), + ('𐫀', '𐫇'), ('𐫉', '𐫦'), ('𐬀', '𐬵'), ('𐭀', '𐭕'), + ('𐭠', '𐭲'), ('𐮀', '𐮑'), ('𐰀', '𐱈'), ('𐲀', '𐲲'), + ('𐳀', '𐳲'), ('𑀀', '𑁆'), ('𑁦', '𑁯'), ('𑁿', '𑂺'), + ('𑃐', '𑃨'), ('𑃰', '𑃹'), ('𑄀', '𑄴'), ('𑄶', '𑄿'), + ('𑅐', '𑅳'), ('𑅶', '𑅶'), ('𑆀', '𑇄'), ('𑇊', '𑇌'), + ('𑇐', '𑇚'), ('𑇜', '𑇜'), ('𑈀', '𑈑'), ('𑈓', '𑈷'), + ('𑈾', '𑈾'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), + ('𑊏', '𑊝'), ('𑊟', '𑊨'), ('𑊰', '𑋪'), ('𑋰', '𑋹'), + ('𑌀', '𑌃'), ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), + ('𑌪', '𑌰'), ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌼', '𑍄'), + ('𑍇', '𑍈'), ('𑍋', '𑍍'), ('𑍐', '𑍐'), ('𑍗', '𑍗'), + ('𑍝', '𑍣'), ('𑍦', '𑍬'), ('𑍰', '𑍴'), ('𑐀', '𑑊'), + ('𑑐', '𑑙'), ('𑒀', '𑓅'), ('𑓇', '𑓇'), ('𑓐', '𑓙'), + ('𑖀', '𑖵'), ('𑖸', '𑗀'), ('𑗘', '𑗝'), ('𑘀', '𑙀'), + ('𑙄', '𑙄'), ('𑙐', '𑙙'), ('𑚀', '𑚷'), ('𑛀', '𑛉'), + ('𑜀', '𑜙'), ('𑜝', '𑜫'), ('𑜰', '𑜹'), ('𑢠', '𑣩'), + ('𑣿', '𑣿'), ('𑨀', '𑨾'), ('𑩇', '𑩇'), ('𑩐', '𑪃'), + ('𑪆', '𑪙'), ('𑫀', '𑫸'), ('𑰀', '𑰈'), ('𑰊', '𑰶'), + ('𑰸', '𑱀'), ('𑱐', '𑱙'), ('𑱲', '𑲏'), ('𑲒', '𑲧'), + ('𑲩', '𑲶'), ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴶'), + ('𑴺', '𑴺'), ('𑴼', '𑴽'), ('𑴿', '𑵇'), ('𑵐', '𑵙'), + ('𒀀', '𒎙'), ('𒐀', '𒑮'), ('𒒀', '𒕃'), ('𓀀', '𓐮'), + ('𔐀', '𔙆'), ('𖠀', '𖨸'), ('𖩀', '𖩞'), ('𖩠', '𖩩'), + ('𖫐', '𖫭'), ('𖫰', '𖫴'), ('𖬀', '𖬶'), ('𖭀', '𖭃'), + ('𖭐', '𖭙'), ('𖭣', '𖭷'), ('𖭽', '𖮏'), ('𖼀', '𖽄'), + ('𖽐', '𖽾'), ('𖾏', '𖾟'), ('𖿠', '𖿡'), ('𗀀', '𘟬'), + ('𘠀', '𘫲'), ('𛀀', '𛄞'), ('𛅰', '𛋻'), ('𛰀', '𛱪'), + ('𛱰', '𛱼'), ('𛲀', '𛲈'), ('𛲐', '𛲙'), ('𛲝', '𛲞'), + ('𝅥', '𝅩'), ('𝅭', '𝅲'), ('𝅻', '𝆂'), ('𝆅', '𝆋'), + ('𝆪', '𝆭'), ('𝉂', '𝉄'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), + ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), + ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), + ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), + ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), + ('𝕒', '𝚥'), ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), + ('𝛼', '𝜔'), ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), + ('𝝰', '𝞈'), ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), + ('𝟎', '𝟿'), ('𝨀', '𝨶'), ('𝨻', '𝩬'), ('𝩵', '𝩵'), + ('𝪄', '𝪄'), ('𝪛', '𝪟'), ('𝪡', '𝪯'), ('𞀀', '𞀆'), + ('𞀈', '𞀘'), ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), + ('𞠀', '𞣄'), ('𞣐', '𞣖'), ('𞤀', '𞥊'), ('𞥐', '𞥙'), + ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), + ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), + ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), + ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), + ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), + ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), + ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), + ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), + ('𞺫', '𞺻'), ('🄰', '🅉'), ('🅐', '🅩'), ('🅰', '🆉'), + ('𠀀', '𪛖'), ('𪜀', '𫜴'), ('𫝀', '𫠝'), ('𫠠', '𬺡'), + ('𬺰', '𮯠'), ('丽', '𪘀'), ('󠄀', '󠇯'), +]; diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/property_bool.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/property_bool.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/property_bool.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/property_bool.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2576 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate property-bool tmp/ucd-10.0.0/ --chars +// +// ucd-generate is available on crates.io. + +pub const BY_NAME: &'static [(&'static str, &'static [(char, char)])] = &[ + ("ASCII_Hex_Digit", ASCII_HEX_DIGIT), ("Alphabetic", ALPHABETIC), + ("Bidi_Control", BIDI_CONTROL), ("Case_Ignorable", CASE_IGNORABLE), + ("Cased", CASED), ("Changes_When_Casefolded", CHANGES_WHEN_CASEFOLDED), + ("Changes_When_Casemapped", CHANGES_WHEN_CASEMAPPED), + ("Changes_When_Lowercased", CHANGES_WHEN_LOWERCASED), + ("Changes_When_Titlecased", CHANGES_WHEN_TITLECASED), + ("Changes_When_Uppercased", CHANGES_WHEN_UPPERCASED), ("Dash", DASH), + ("Default_Ignorable_Code_Point", DEFAULT_IGNORABLE_CODE_POINT), + ("Deprecated", DEPRECATED), ("Diacritic", DIACRITIC), + ("Extender", EXTENDER), ("Grapheme_Base", GRAPHEME_BASE), + ("Grapheme_Extend", GRAPHEME_EXTEND), ("Grapheme_Link", GRAPHEME_LINK), + ("Hex_Digit", HEX_DIGIT), ("Hyphen", HYPHEN), + ("IDS_Binary_Operator", IDS_BINARY_OPERATOR), + ("IDS_Trinary_Operator", IDS_TRINARY_OPERATOR), + ("ID_Continue", ID_CONTINUE), ("ID_Start", ID_START), + ("Ideographic", IDEOGRAPHIC), ("Join_Control", JOIN_CONTROL), + ("Logical_Order_Exception", LOGICAL_ORDER_EXCEPTION), + ("Lowercase", LOWERCASE), ("Math", MATH), + ("Noncharacter_Code_Point", NONCHARACTER_CODE_POINT), + ("Other_Alphabetic", OTHER_ALPHABETIC), + ("Other_Default_Ignorable_Code_Point", OTHER_DEFAULT_IGNORABLE_CODE_POINT), + ("Other_Grapheme_Extend", OTHER_GRAPHEME_EXTEND), + ("Other_ID_Continue", OTHER_ID_CONTINUE), + ("Other_ID_Start", OTHER_ID_START), ("Other_Lowercase", OTHER_LOWERCASE), + ("Other_Math", OTHER_MATH), ("Other_Uppercase", OTHER_UPPERCASE), + ("Pattern_Syntax", PATTERN_SYNTAX), + ("Pattern_White_Space", PATTERN_WHITE_SPACE), + ("Prepended_Concatenation_Mark", PREPENDED_CONCATENATION_MARK), + ("Quotation_Mark", QUOTATION_MARK), ("Radical", RADICAL), + ("Regional_Indicator", REGIONAL_INDICATOR), + ("Sentence_Terminal", SENTENCE_TERMINAL), ("Soft_Dotted", SOFT_DOTTED), + ("Terminal_Punctuation", TERMINAL_PUNCTUATION), + ("Unified_Ideograph", UNIFIED_IDEOGRAPH), ("Uppercase", UPPERCASE), + ("Variation_Selector", VARIATION_SELECTOR), ("White_Space", WHITE_SPACE), + ("XID_Continue", XID_CONTINUE), ("XID_Start", XID_START), +]; + +pub const ASCII_HEX_DIGIT: &'static [(char, char)] = &[ + ('0', '9'), ('A', 'F'), ('a', 'f'), +]; + +pub const ALPHABETIC: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), ('º', 'º'), + ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), + ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('ͅ', 'ͅ'), ('Ͱ', 'ʹ'), ('Ͷ', 'ͷ'), + ('ͺ', 'ͽ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), + ('Ύ', 'Ρ'), ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('Ҋ', 'ԯ'), ('Ա', 'Ֆ'), + ('ՙ', 'ՙ'), ('ա', 'և'), ('ְ', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), + ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('א', 'ת'), ('װ', 'ײ'), ('ؐ', 'ؚ'), + ('ؠ', 'ٗ'), ('ٙ', 'ٟ'), ('ٮ', 'ۓ'), ('ە', 'ۜ'), ('ۡ', 'ۨ'), + ('ۭ', 'ۯ'), ('ۺ', 'ۼ'), ('ۿ', 'ۿ'), ('ܐ', 'ܿ'), ('ݍ', 'ޱ'), + ('ߊ', 'ߪ'), ('ߴ', 'ߵ'), ('ߺ', 'ߺ'), ('ࠀ', 'ࠗ'), ('ࠚ', 'ࠬ'), + ('ࡀ', 'ࡘ'), ('ࡠ', 'ࡪ'), ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), + ('ࣔ', 'ࣟ'), ('ࣣ', 'ࣩ'), ('ࣰ', 'ऻ'), ('ऽ', 'ौ'), + ('ॎ', 'ॐ'), ('ॕ', 'ॣ'), ('ॱ', 'ঃ'), ('অ', 'ঌ'), + ('এ', 'ঐ'), ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), + ('শ', 'হ'), ('ঽ', 'ৄ'), ('ে', 'ৈ'), ('ো', 'ৌ'), + ('ৎ', 'ৎ'), ('ৗ', 'ৗ'), ('ড়', 'ঢ়'), ('য়', 'ৣ'), + ('ৰ', 'ৱ'), ('ৼ', 'ৼ'), ('ਁ', 'ਃ'), ('ਅ', 'ਊ'), + ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), + ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), + ('ੋ', 'ੌ'), ('ੑ', 'ੑ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), + ('ੰ', 'ੵ'), ('ઁ', 'ઃ'), ('અ', 'ઍ'), ('એ', 'ઑ'), + ('ઓ', 'ન'), ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), + ('ઽ', 'ૅ'), ('ે', 'ૉ'), ('ો', 'ૌ'), ('ૐ', 'ૐ'), + ('ૠ', 'ૣ'), ('ૹ', 'ૼ'), ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('ଽ', 'ୄ'), ('େ', 'ୈ'), ('ୋ', 'ୌ'), + ('ୖ', 'ୗ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୣ'), ('ୱ', 'ୱ'), + ('ஂ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), ('ஒ', 'க'), + ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), ('ண', 'த'), + ('ந', 'ப'), ('ம', 'ஹ'), ('ா', 'ூ'), ('ெ', 'ை'), + ('ொ', 'ௌ'), ('ௐ', 'ௐ'), ('ௗ', 'ௗ'), ('ఀ', 'ః'), + ('అ', 'ఌ'), ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), + ('ఽ', 'ౄ'), ('ె', 'ై'), ('ొ', 'ౌ'), ('ౕ', 'ౖ'), + ('ౘ', 'ౚ'), ('ౠ', 'ౣ'), ('ಀ', 'ಃ'), ('ಅ', 'ಌ'), + ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), + ('ಽ', 'ೄ'), ('ೆ', 'ೈ'), ('ೊ', 'ೌ'), ('ೕ', 'ೖ'), + ('ೞ', 'ೞ'), ('ೠ', 'ೣ'), ('ೱ', 'ೲ'), ('ഀ', 'ഃ'), + ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ഺ'), ('ഽ', 'ൄ'), + ('െ', 'ൈ'), ('ൊ', 'ൌ'), ('ൎ', 'ൎ'), ('ൔ', 'ൗ'), + ('ൟ', 'ൣ'), ('ൺ', 'ൿ'), ('ං', 'ඃ'), ('අ', 'ඖ'), + ('ක', 'න'), ('ඳ', 'ර'), ('ල', 'ල'), ('ව', 'ෆ'), + ('ා', 'ු'), ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('ෲ', 'ෳ'), + ('ก', 'ฺ'), ('เ', 'ๆ'), ('ํ', 'ํ'), ('ກ', 'ຂ'), + ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), ('ຍ', 'ຍ'), + ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), ('ລ', 'ລ'), + ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), ('ົ', 'ຽ'), + ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('ໍ', 'ໍ'), ('ໜ', 'ໟ'), + ('ༀ', 'ༀ'), ('ཀ', 'ཇ'), ('ཉ', 'ཬ'), ('ཱ', 'ཱྀ'), + ('ྈ', 'ྗ'), ('ྙ', 'ྼ'), ('က', 'ံ'), ('း', 'း'), + ('ျ', 'ဿ'), ('ၐ', 'ၢ'), ('ၥ', 'ၨ'), ('ၮ', 'ႆ'), + ('ႎ', 'ႎ'), ('ႜ', 'ႝ'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), + ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), ('ჼ', 'ቈ'), ('ቊ', 'ቍ'), + ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), ('በ', 'ኈ'), + ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), + ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), ('ዘ', 'ጐ'), + ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('፟', '፟'), ('ᎀ', 'ᎏ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), ('ᙯ', 'ᙿ'), + ('ᚁ', 'ᚚ'), ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), ('ᜀ', 'ᜌ'), + ('ᜎ', 'ᜓ'), ('ᜠ', 'ᜳ'), ('ᝀ', 'ᝓ'), ('ᝠ', 'ᝬ'), + ('ᝮ', 'ᝰ'), ('ᝲ', 'ᝳ'), ('ក', 'ឳ'), ('ា', 'ៈ'), + ('ៗ', 'ៗ'), ('ៜ', 'ៜ'), ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢪ'), + ('ᢰ', 'ᣵ'), ('ᤀ', 'ᤞ'), ('ᤠ', 'ᤫ'), ('ᤰ', 'ᤸ'), + ('ᥐ', 'ᥭ'), ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), + ('ᨀ', 'ᨛ'), ('ᨠ', 'ᩞ'), ('ᩡ', 'ᩴ'), ('ᪧ', 'ᪧ'), + ('ᬀ', 'ᬳ'), ('ᬵ', 'ᭃ'), ('ᭅ', 'ᭋ'), ('ᮀ', 'ᮩ'), + ('ᮬ', 'ᮯ'), ('ᮺ', 'ᯥ'), ('ᯧ', 'ᯱ'), ('ᰀ', 'ᰵ'), + ('ᱍ', 'ᱏ'), ('ᱚ', 'ᱽ'), ('ᲀ', 'ᲈ'), ('ᳩ', 'ᳬ'), + ('ᳮ', 'ᳳ'), ('ᳵ', 'ᳶ'), ('ᴀ', 'ᶿ'), ('ᷧ', 'ᷴ'), + ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), + ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), + ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), ('ι', 'ι'), + ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), ('ῖ', 'Ί'), + ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), ('ⁱ', 'ⁱ'), + ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), + ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), + ('Ω', 'Ω'), ('ℨ', 'ℨ'), ('K', 'ℭ'), ('ℯ', 'ℹ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), + ('Ⓐ', 'ⓩ'), ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), + ('Ⳬ', 'ⳮ'), ('Ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), + ('ⴭ', 'ⴭ'), ('ⴰ', 'ⵧ'), ('ⵯ', 'ⵯ'), ('ⶀ', 'ⶖ'), + ('ⶠ', 'ⶦ'), ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), + ('ⷀ', 'ⷆ'), ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), + ('ⷠ', 'ⷿ'), ('ⸯ', 'ⸯ'), ('々', '〇'), ('〡', '〩'), + ('〱', '〵'), ('〸', '〼'), ('ぁ', 'ゖ'), ('ゝ', 'ゟ'), + ('ァ', 'ヺ'), ('ー', 'ヿ'), ('ㄅ', 'ㄮ'), ('ㄱ', 'ㆎ'), + ('ㆠ', 'ㆺ'), ('ㇰ', 'ㇿ'), ('㐀', '䶵'), ('一', '鿪'), + ('ꀀ', 'ꒌ'), ('ꓐ', 'ꓽ'), ('ꔀ', 'ꘌ'), ('ꘐ', 'ꘟ'), + ('ꘪ', 'ꘫ'), ('Ꙁ', 'ꙮ'), ('ꙴ', 'ꙻ'), ('ꙿ', 'ꛯ'), + ('ꜗ', 'ꜟ'), ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), ('Ʞ', 'ꞷ'), + ('ꟷ', 'ꠁ'), ('ꠃ', 'ꠅ'), ('ꠇ', 'ꠊ'), ('ꠌ', 'ꠧ'), + ('ꡀ', 'ꡳ'), ('ꢀ', 'ꣃ'), ('ꣅ', 'ꣅ'), ('ꣲ', 'ꣷ'), + ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), ('ꤊ', 'ꤪ'), ('ꤰ', 'ꥒ'), + ('ꥠ', 'ꥼ'), ('ꦀ', 'ꦲ'), ('ꦴ', 'ꦿ'), ('ꧏ', 'ꧏ'), + ('ꧠ', 'ꧤ'), ('ꧦ', 'ꧯ'), ('ꧺ', 'ꧾ'), ('ꨀ', 'ꨶ'), + ('ꩀ', 'ꩍ'), ('ꩠ', 'ꩶ'), ('ꩺ', 'ꩺ'), ('ꩾ', 'ꪾ'), + ('ꫀ', 'ꫀ'), ('ꫂ', 'ꫂ'), ('ꫛ', 'ꫝ'), ('ꫠ', 'ꫯ'), + ('ꫲ', 'ꫵ'), ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), + ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭥ'), + ('ꭰ', 'ꯪ'), ('가', '힣'), ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), + ('豈', '舘'), ('並', '龎'), ('ff', 'st'), ('ﬓ', 'ﬗ'), + ('יִ', 'ﬨ'), ('שׁ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), + ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﮱ'), ('ﯓ', 'ﴽ'), + ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷻ'), ('ﹰ', 'ﹴ'), + ('ﹶ', 'ﻼ'), ('A', 'Z'), ('a', 'z'), ('ヲ', 'ᄒ'), + ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), + ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), + ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐅀', '𐅴'), + ('𐊀', '𐊜'), ('𐊠', '𐋐'), ('𐌀', '𐌟'), ('𐌭', '𐍊'), + ('𐍐', '𐍺'), ('𐎀', '𐎝'), ('𐎠', '𐏃'), ('𐏈', '𐏏'), + ('𐏑', '𐏕'), ('𐐀', '𐒝'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), + ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐘀', '𐜶'), ('𐝀', '𐝕'), + ('𐝠', '𐝧'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), ('𐠊', '𐠵'), + ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐡕'), ('𐡠', '𐡶'), + ('𐢀', '𐢞'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐤀', '𐤕'), + ('𐤠', '𐤹'), ('𐦀', '𐦷'), ('𐦾', '𐦿'), ('𐨀', '𐨃'), + ('𐨅', '𐨆'), ('𐨌', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), + ('𐩠', '𐩼'), ('𐪀', '𐪜'), ('𐫀', '𐫇'), ('𐫉', '𐫤'), + ('𐬀', '𐬵'), ('𐭀', '𐭕'), ('𐭠', '𐭲'), ('𐮀', '𐮑'), + ('𐰀', '𐱈'), ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𑀀', '𑁅'), + ('𑂂', '𑂸'), ('𑃐', '𑃨'), ('𑄀', '𑄲'), ('𑅐', '𑅲'), + ('𑅶', '𑅶'), ('𑆀', '𑆿'), ('𑇁', '𑇄'), ('𑇚', '𑇚'), + ('𑇜', '𑇜'), ('𑈀', '𑈑'), ('𑈓', '𑈴'), ('𑈷', '𑈷'), + ('𑈾', '𑈾'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), + ('𑊏', '𑊝'), ('𑊟', '𑊨'), ('𑊰', '𑋨'), ('𑌀', '𑌃'), + ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), + ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌽', '𑍄'), ('𑍇', '𑍈'), + ('𑍋', '𑍌'), ('𑍐', '𑍐'), ('𑍗', '𑍗'), ('𑍝', '𑍣'), + ('𑐀', '𑑁'), ('𑑃', '𑑅'), ('𑑇', '𑑊'), ('𑒀', '𑓁'), + ('𑓄', '𑓅'), ('𑓇', '𑓇'), ('𑖀', '𑖵'), ('𑖸', '𑖾'), + ('𑗘', '𑗝'), ('𑘀', '𑘾'), ('𑙀', '𑙀'), ('𑙄', '𑙄'), + ('𑚀', '𑚵'), ('𑜀', '𑜙'), ('𑜝', '𑜪'), ('𑢠', '𑣟'), + ('𑣿', '𑣿'), ('𑨀', '𑨲'), ('𑨵', '𑨾'), ('𑩐', '𑪃'), + ('𑪆', '𑪗'), ('𑫀', '𑫸'), ('𑰀', '𑰈'), ('𑰊', '𑰶'), + ('𑰸', '𑰾'), ('𑱀', '𑱀'), ('𑱲', '𑲏'), ('𑲒', '𑲧'), + ('𑲩', '𑲶'), ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴶'), + ('𑴺', '𑴺'), ('𑴼', '𑴽'), ('𑴿', '𑵁'), ('𑵃', '𑵃'), + ('𑵆', '𑵇'), ('𒀀', '𒎙'), ('𒐀', '𒑮'), ('𒒀', '𒕃'), + ('𓀀', '𓐮'), ('𔐀', '𔙆'), ('𖠀', '𖨸'), ('𖩀', '𖩞'), + ('𖫐', '𖫭'), ('𖬀', '𖬶'), ('𖭀', '𖭃'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽾'), ('𖾓', '𖾟'), + ('𖿠', '𖿡'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𛀀', '𛄞'), + ('𛅰', '𛋻'), ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), + ('𛲐', '𛲙'), ('𛲞', '𛲞'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), + ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), + ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), + ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), + ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), + ('𝕒', '𝚥'), ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), + ('𝛼', '𝜔'), ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), + ('𝝰', '𝞈'), ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), + ('𞀀', '𞀆'), ('𞀈', '𞀘'), ('𞀛', '𞀡'), ('𞀣', '𞀤'), + ('𞀦', '𞀪'), ('𞠀', '𞣄'), ('𞤀', '𞥃'), ('𞥇', '𞥇'), + ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), + ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), + ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), + ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), + ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), + ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), + ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), + ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), + ('𞺫', '𞺻'), ('🄰', '🅉'), ('🅐', '🅩'), ('🅰', '🆉'), + ('𠀀', '𪛖'), ('𪜀', '𫜴'), ('𫝀', '𫠝'), ('𫠠', '𬺡'), + ('𬺰', '𮯠'), ('丽', '𪘀'), +]; + +pub const BIDI_CONTROL: &'static [(char, char)] = &[ + ('\u{61c}', '\u{61c}'), ('\u{200e}', '\u{200f}'), ('\u{202a}', '\u{202e}'), + ('\u{2066}', '\u{2069}'), +]; + +pub const CASE_IGNORABLE: &'static [(char, char)] = &[ + ('\'', '\''), ('.', '.'), (':', ':'), ('^', '^'), ('`', '`'), ('¨', '¨'), + ('\u{ad}', '\u{ad}'), ('¯', '¯'), ('´', '´'), ('·', '¸'), + ('ʰ', 'ͯ'), ('ʹ', '͵'), ('ͺ', 'ͺ'), ('΄', '΅'), ('·', '·'), + ('҃', '҉'), ('ՙ', 'ՙ'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), + ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('״', '״'), ('\u{600}', '\u{605}'), + ('ؐ', 'ؚ'), ('\u{61c}', '\u{61c}'), ('ـ', 'ـ'), ('ً', 'ٟ'), + ('ٰ', 'ٰ'), ('ۖ', '\u{6dd}'), ('۟', 'ۨ'), ('۪', 'ۭ'), + ('\u{70f}', '\u{70f}'), ('ܑ', 'ܑ'), ('ܰ', '݊'), ('ަ', 'ް'), + ('߫', 'ߵ'), ('ߺ', 'ߺ'), ('ࠖ', '࠭'), ('࡙', '࡛'), ('ࣔ', 'ं'), + ('ऺ', 'ऺ'), ('़', '़'), ('ु', 'ै'), ('्', '्'), + ('॑', 'ॗ'), ('ॢ', 'ॣ'), ('ॱ', 'ॱ'), ('ঁ', 'ঁ'), + ('়', '়'), ('ু', 'ৄ'), ('্', '্'), ('ৢ', 'ৣ'), + ('ਁ', 'ਂ'), ('਼', '਼'), ('ੁ', 'ੂ'), ('ੇ', 'ੈ'), + ('ੋ', '੍'), ('ੑ', 'ੑ'), ('ੰ', 'ੱ'), ('ੵ', 'ੵ'), + ('ઁ', 'ં'), ('઼', '઼'), ('ુ', 'ૅ'), ('ે', 'ૈ'), + ('્', '્'), ('ૢ', 'ૣ'), ('ૺ', '૿'), ('ଁ', 'ଁ'), + ('଼', '଼'), ('ି', 'ି'), ('ୁ', 'ୄ'), ('୍', '୍'), + ('ୖ', 'ୖ'), ('ୢ', 'ୣ'), ('ஂ', 'ஂ'), ('ீ', 'ீ'), + ('்', '்'), ('ఀ', 'ఀ'), ('ా', 'ీ'), ('ె', 'ై'), + ('ొ', '్'), ('ౕ', 'ౖ'), ('ౢ', 'ౣ'), ('ಁ', 'ಁ'), + ('಼', '಼'), ('ಿ', 'ಿ'), ('ೆ', 'ೆ'), ('ೌ', '್'), + ('ೢ', 'ೣ'), ('ഀ', 'ഁ'), ('഻', '഼'), ('ു', 'ൄ'), + ('്', '്'), ('ൢ', 'ൣ'), ('්', '්'), ('ි', 'ු'), + ('ූ', 'ූ'), ('ั', 'ั'), ('ิ', 'ฺ'), ('ๆ', '๎'), + ('ັ', 'ັ'), ('ິ', 'ູ'), ('ົ', 'ຼ'), ('ໆ', 'ໆ'), + ('່', 'ໍ'), ('༘', '༙'), ('༵', '༵'), ('༷', '༷'), + ('༹', '༹'), ('ཱ', 'ཾ'), ('ྀ', '྄'), ('྆', '྇'), + ('ྍ', 'ྗ'), ('ྙ', 'ྼ'), ('࿆', '࿆'), ('ိ', 'ူ'), + ('ဲ', '့'), ('္', '်'), ('ွ', 'ှ'), ('ၘ', 'ၙ'), + ('ၞ', 'ၠ'), ('ၱ', 'ၴ'), ('ႂ', 'ႂ'), ('ႅ', 'ႆ'), + ('ႍ', 'ႍ'), ('ႝ', 'ႝ'), ('ჼ', 'ჼ'), ('፝', '፟'), + ('ᜒ', '᜔'), ('ᜲ', '᜴'), ('ᝒ', 'ᝓ'), ('ᝲ', 'ᝳ'), + ('឴', '឵'), ('ិ', 'ួ'), ('ំ', 'ំ'), ('៉', '៓'), + ('ៗ', 'ៗ'), ('៝', '៝'), ('᠋', '\u{180e}'), ('ᡃ', 'ᡃ'), + ('ᢅ', 'ᢆ'), ('ᢩ', 'ᢩ'), ('ᤠ', 'ᤢ'), ('ᤧ', 'ᤨ'), + ('ᤲ', 'ᤲ'), ('᤹', '᤻'), ('ᨗ', 'ᨘ'), ('ᨛ', 'ᨛ'), + ('ᩖ', 'ᩖ'), ('ᩘ', 'ᩞ'), ('᩠', '᩠'), ('ᩢ', 'ᩢ'), + ('ᩥ', 'ᩬ'), ('ᩳ', '᩼'), ('᩿', '᩿'), ('ᪧ', 'ᪧ'), + ('᪰', '᪾'), ('ᬀ', 'ᬃ'), ('᬴', '᬴'), ('ᬶ', 'ᬺ'), + ('ᬼ', 'ᬼ'), ('ᭂ', 'ᭂ'), ('᭫', '᭳'), ('ᮀ', 'ᮁ'), + ('ᮢ', 'ᮥ'), ('ᮨ', 'ᮩ'), ('᮫', 'ᮭ'), ('᯦', '᯦'), + ('ᯨ', 'ᯩ'), ('ᯭ', 'ᯭ'), ('ᯯ', 'ᯱ'), ('ᰬ', 'ᰳ'), + ('ᰶ', '᰷'), ('ᱸ', 'ᱽ'), ('᳐', '᳒'), ('᳔', '᳠'), + ('᳢', '᳨'), ('᳭', '᳭'), ('᳴', '᳴'), ('᳸', '᳹'), + ('ᴬ', 'ᵪ'), ('ᵸ', 'ᵸ'), ('ᶛ', '᷹'), ('᷻', '᷿'), + ('᾽', '᾽'), ('᾿', '῁'), ('῍', '῏'), ('῝', '῟'), + ('῭', '`'), ('´', '῾'), ('\u{200b}', '\u{200f}'), ('‘', '’'), + ('․', '․'), ('‧', '‧'), ('\u{202a}', '\u{202e}'), + ('\u{2060}', '\u{2064}'), ('\u{2066}', '\u{206f}'), ('ⁱ', 'ⁱ'), + ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('⃐', '⃰'), ('ⱼ', 'ⱽ'), + ('⳯', '⳱'), ('ⵯ', 'ⵯ'), ('⵿', '⵿'), ('ⷠ', 'ⷿ'), + ('ⸯ', 'ⸯ'), ('々', '々'), ('〪', '〭'), ('〱', '〵'), + ('〻', '〻'), ('゙', 'ゞ'), ('ー', 'ヾ'), ('ꀕ', 'ꀕ'), + ('ꓸ', 'ꓽ'), ('ꘌ', 'ꘌ'), ('꙯', '꙲'), ('ꙴ', '꙽'), + ('ꙿ', 'ꙿ'), ('ꚜ', 'ꚟ'), ('꛰', '꛱'), ('꜀', '꜡'), + ('ꝰ', 'ꝰ'), ('ꞈ', '꞊'), ('ꟸ', 'ꟹ'), ('ꠂ', 'ꠂ'), + ('꠆', '꠆'), ('ꠋ', 'ꠋ'), ('ꠥ', 'ꠦ'), ('꣄', 'ꣅ'), + ('꣠', '꣱'), ('ꤦ', '꤭'), ('ꥇ', 'ꥑ'), ('ꦀ', 'ꦂ'), + ('꦳', '꦳'), ('ꦶ', 'ꦹ'), ('ꦼ', 'ꦼ'), ('ꧏ', 'ꧏ'), + ('ꧥ', 'ꧦ'), ('ꨩ', 'ꨮ'), ('ꨱ', 'ꨲ'), ('ꨵ', 'ꨶ'), + ('ꩃ', 'ꩃ'), ('ꩌ', 'ꩌ'), ('ꩰ', 'ꩰ'), ('ꩼ', 'ꩼ'), + ('ꪰ', 'ꪰ'), ('ꪲ', 'ꪴ'), ('ꪷ', 'ꪸ'), ('ꪾ', '꪿'), + ('꫁', '꫁'), ('ꫝ', 'ꫝ'), ('ꫬ', 'ꫭ'), ('ꫳ', 'ꫴ'), + ('꫶', '꫶'), ('꭛', 'ꭟ'), ('ꯥ', 'ꯥ'), ('ꯨ', 'ꯨ'), + ('꯭', '꯭'), ('ﬞ', 'ﬞ'), ('﮲', '﯁'), ('︀', '️'), + ('︓', '︓'), ('︠', '︯'), ('﹒', '﹒'), ('﹕', '﹕'), + ('\u{feff}', '\u{feff}'), (''', '''), ('.', '.'), (':', ':'), + ('^', '^'), ('`', '`'), ('ー', 'ー'), ('゙', '゚'), + (' ̄', ' ̄'), ('\u{fff9}', '\u{fffb}'), ('𐇽', '𐇽'), + ('𐋠', '𐋠'), ('𐍶', '𐍺'), ('𐨁', '𐨃'), ('𐨅', '𐨆'), + ('𐨌', '𐨏'), ('𐨸', '𐨺'), ('𐨿', '𐨿'), ('𐫥', '𐫦'), + ('𑀁', '𑀁'), ('𑀸', '𑁆'), ('𑁿', '𑂁'), ('𑂳', '𑂶'), + ('𑂹', '𑂺'), ('\u{110bd}', '\u{110bd}'), ('𑄀', '𑄂'), + ('𑄧', '𑄫'), ('𑄭', '𑄴'), ('𑅳', '𑅳'), ('𑆀', '𑆁'), + ('𑆶', '𑆾'), ('𑇊', '𑇌'), ('𑈯', '𑈱'), ('𑈴', '𑈴'), + ('𑈶', '𑈷'), ('𑈾', '𑈾'), ('𑋟', '𑋟'), ('𑋣', '𑋪'), + ('𑌀', '𑌁'), ('𑌼', '𑌼'), ('𑍀', '𑍀'), ('𑍦', '𑍬'), + ('𑍰', '𑍴'), ('𑐸', '𑐿'), ('𑑂', '𑑄'), ('𑑆', '𑑆'), + ('𑒳', '𑒸'), ('𑒺', '𑒺'), ('𑒿', '𑓀'), ('𑓂', '𑓃'), + ('𑖲', '𑖵'), ('𑖼', '𑖽'), ('𑖿', '𑗀'), ('𑗜', '𑗝'), + ('𑘳', '𑘺'), ('𑘽', '𑘽'), ('𑘿', '𑙀'), ('𑚫', '𑚫'), + ('𑚭', '𑚭'), ('𑚰', '𑚵'), ('𑚷', '𑚷'), ('𑜝', '𑜟'), + ('𑜢', '𑜥'), ('𑜧', '𑜫'), ('𑨁', '𑨆'), ('𑨉', '𑨊'), + ('𑨳', '𑨸'), ('𑨻', '𑨾'), ('𑩇', '𑩇'), ('𑩑', '𑩖'), + ('𑩙', '𑩛'), ('𑪊', '𑪖'), ('𑪘', '𑪙'), ('𑰰', '𑰶'), + ('𑰸', '𑰽'), ('𑰿', '𑰿'), ('𑲒', '𑲧'), ('𑲪', '𑲰'), + ('𑲲', '𑲳'), ('𑲵', '𑲶'), ('𑴱', '𑴶'), ('𑴺', '𑴺'), + ('𑴼', '𑴽'), ('𑴿', '𑵅'), ('𑵇', '𑵇'), ('𖫰', '𖫴'), + ('𖬰', '𖬶'), ('𖭀', '𖭃'), ('𖾏', '𖾟'), ('𖿠', '𖿡'), + ('𛲝', '𛲞'), ('\u{1bca0}', '\u{1bca3}'), ('𝅧', '𝅩'), + ('\u{1d173}', '𝆂'), ('𝆅', '𝆋'), ('𝆪', '𝆭'), ('𝉂', '𝉄'), + ('𝨀', '𝨶'), ('𝨻', '𝩬'), ('𝩵', '𝩵'), ('𝪄', '𝪄'), + ('𝪛', '𝪟'), ('𝪡', '𝪯'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), + ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), ('𞣐', '𞣖'), + ('𞥄', '𞥊'), ('🏻', '🏿'), ('\u{e0001}', '\u{e0001}'), + ('\u{e0020}', '\u{e007f}'), ('󠄀', '󠇯'), +]; + +pub const CASED: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), ('º', 'º'), + ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ƺ'), ('Ƽ', 'ƿ'), ('DŽ', 'ʓ'), + ('ʕ', 'ʸ'), ('ˀ', 'ˁ'), ('ˠ', 'ˤ'), ('ͅ', 'ͅ'), ('Ͱ', 'ͳ'), + ('Ͷ', 'ͷ'), ('ͺ', 'ͽ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), + ('Ό', 'Ό'), ('Ύ', 'Ρ'), ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('Ҋ', 'ԯ'), + ('Ա', 'Ֆ'), ('ա', 'և'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᴀ', 'ᶿ'), + ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), + ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), + ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), ('ι', 'ι'), + ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), ('ῖ', 'Ί'), + ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), ('ⁱ', 'ⁱ'), + ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), + ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), + ('Ω', 'Ω'), ('ℨ', 'ℨ'), ('K', 'ℭ'), ('ℯ', 'ℴ'), + ('ℹ', 'ℹ'), ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), + ('Ⅰ', 'ⅿ'), ('Ↄ', 'ↄ'), ('Ⓐ', 'ⓩ'), ('Ⰰ', 'Ⱞ'), + ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳮ'), ('Ⳳ', 'ⳳ'), + ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('Ꙁ', 'ꙭ'), + ('Ꚁ', 'ꚝ'), ('Ꜣ', 'ꞇ'), ('Ꞌ', 'ꞎ'), ('Ꞑ', 'Ɪ'), + ('Ʞ', 'ꞷ'), ('ꟸ', 'ꟺ'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭥ'), + ('ꭰ', 'ꮿ'), ('ff', 'st'), ('ﬓ', 'ﬗ'), ('A', 'Z'), + ('a', 'z'), ('𐐀', '𐑏'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), + ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𑢠', '𑣟'), ('𝐀', '𝑔'), + ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), + ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), + ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), + ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), + ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝛀'), ('𝛂', '𝛚'), + ('𝛜', '𝛺'), ('𝛼', '𝜔'), ('𝜖', '𝜴'), ('𝜶', '𝝎'), + ('𝝐', '𝝮'), ('𝝰', '𝞈'), ('𝞊', '𝞨'), ('𝞪', '𝟂'), + ('𝟄', '𝟋'), ('𞤀', '𞥃'), ('🄰', '🅉'), ('🅐', '🅩'), + ('🅰', '🆉'), +]; + +pub const CHANGES_WHEN_CASEFOLDED: &'static [(char, char)] = &[ + ('A', 'Z'), ('µ', 'µ'), ('À', 'Ö'), ('Ø', 'ß'), ('Ā', 'Ā'), + ('Ă', 'Ă'), ('Ą', 'Ą'), ('Ć', 'Ć'), ('Ĉ', 'Ĉ'), ('Ċ', 'Ċ'), + ('Č', 'Č'), ('Ď', 'Ď'), ('Đ', 'Đ'), ('Ē', 'Ē'), ('Ĕ', 'Ĕ'), + ('Ė', 'Ė'), ('Ę', 'Ę'), ('Ě', 'Ě'), ('Ĝ', 'Ĝ'), ('Ğ', 'Ğ'), + ('Ġ', 'Ġ'), ('Ģ', 'Ģ'), ('Ĥ', 'Ĥ'), ('Ħ', 'Ħ'), ('Ĩ', 'Ĩ'), + ('Ī', 'Ī'), ('Ĭ', 'Ĭ'), ('Į', 'Į'), ('İ', 'İ'), ('IJ', 'IJ'), + ('Ĵ', 'Ĵ'), ('Ķ', 'Ķ'), ('Ĺ', 'Ĺ'), ('Ļ', 'Ļ'), ('Ľ', 'Ľ'), + ('Ŀ', 'Ŀ'), ('Ł', 'Ł'), ('Ń', 'Ń'), ('Ņ', 'Ņ'), ('Ň', 'Ň'), + ('ʼn', 'Ŋ'), ('Ō', 'Ō'), ('Ŏ', 'Ŏ'), ('Ő', 'Ő'), ('Œ', 'Œ'), + ('Ŕ', 'Ŕ'), ('Ŗ', 'Ŗ'), ('Ř', 'Ř'), ('Ś', 'Ś'), ('Ŝ', 'Ŝ'), + ('Ş', 'Ş'), ('Š', 'Š'), ('Ţ', 'Ţ'), ('Ť', 'Ť'), ('Ŧ', 'Ŧ'), + ('Ũ', 'Ũ'), ('Ū', 'Ū'), ('Ŭ', 'Ŭ'), ('Ů', 'Ů'), ('Ű', 'Ű'), + ('Ų', 'Ų'), ('Ŵ', 'Ŵ'), ('Ŷ', 'Ŷ'), ('Ÿ', 'Ź'), ('Ż', 'Ż'), + ('Ž', 'Ž'), ('ſ', 'ſ'), ('Ɓ', 'Ƃ'), ('Ƅ', 'Ƅ'), ('Ɔ', 'Ƈ'), + ('Ɖ', 'Ƌ'), ('Ǝ', 'Ƒ'), ('Ɠ', 'Ɣ'), ('Ɩ', 'Ƙ'), ('Ɯ', 'Ɲ'), + ('Ɵ', 'Ơ'), ('Ƣ', 'Ƣ'), ('Ƥ', 'Ƥ'), ('Ʀ', 'Ƨ'), ('Ʃ', 'Ʃ'), + ('Ƭ', 'Ƭ'), ('Ʈ', 'Ư'), ('Ʊ', 'Ƴ'), ('Ƶ', 'Ƶ'), ('Ʒ', 'Ƹ'), + ('Ƽ', 'Ƽ'), ('DŽ', 'Dž'), ('LJ', 'Lj'), ('NJ', 'Nj'), ('Ǎ', 'Ǎ'), + ('Ǐ', 'Ǐ'), ('Ǒ', 'Ǒ'), ('Ǔ', 'Ǔ'), ('Ǖ', 'Ǖ'), ('Ǘ', 'Ǘ'), + ('Ǚ', 'Ǚ'), ('Ǜ', 'Ǜ'), ('Ǟ', 'Ǟ'), ('Ǡ', 'Ǡ'), ('Ǣ', 'Ǣ'), + ('Ǥ', 'Ǥ'), ('Ǧ', 'Ǧ'), ('Ǩ', 'Ǩ'), ('Ǫ', 'Ǫ'), ('Ǭ', 'Ǭ'), + ('Ǯ', 'Ǯ'), ('DZ', 'Dz'), ('Ǵ', 'Ǵ'), ('Ƕ', 'Ǹ'), ('Ǻ', 'Ǻ'), + ('Ǽ', 'Ǽ'), ('Ǿ', 'Ǿ'), ('Ȁ', 'Ȁ'), ('Ȃ', 'Ȃ'), ('Ȅ', 'Ȅ'), + ('Ȇ', 'Ȇ'), ('Ȉ', 'Ȉ'), ('Ȋ', 'Ȋ'), ('Ȍ', 'Ȍ'), ('Ȏ', 'Ȏ'), + ('Ȑ', 'Ȑ'), ('Ȓ', 'Ȓ'), ('Ȕ', 'Ȕ'), ('Ȗ', 'Ȗ'), ('Ș', 'Ș'), + ('Ț', 'Ț'), ('Ȝ', 'Ȝ'), ('Ȟ', 'Ȟ'), ('Ƞ', 'Ƞ'), ('Ȣ', 'Ȣ'), + ('Ȥ', 'Ȥ'), ('Ȧ', 'Ȧ'), ('Ȩ', 'Ȩ'), ('Ȫ', 'Ȫ'), ('Ȭ', 'Ȭ'), + ('Ȯ', 'Ȯ'), ('Ȱ', 'Ȱ'), ('Ȳ', 'Ȳ'), ('Ⱥ', 'Ȼ'), ('Ƚ', 'Ⱦ'), + ('Ɂ', 'Ɂ'), ('Ƀ', 'Ɇ'), ('Ɉ', 'Ɉ'), ('Ɋ', 'Ɋ'), ('Ɍ', 'Ɍ'), + ('Ɏ', 'Ɏ'), ('ͅ', 'ͅ'), ('Ͱ', 'Ͱ'), ('Ͳ', 'Ͳ'), ('Ͷ', 'Ͷ'), + ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ώ'), + ('Α', 'Ρ'), ('Σ', 'Ϋ'), ('ς', 'ς'), ('Ϗ', 'ϑ'), ('ϕ', 'ϖ'), + ('Ϙ', 'Ϙ'), ('Ϛ', 'Ϛ'), ('Ϝ', 'Ϝ'), ('Ϟ', 'Ϟ'), ('Ϡ', 'Ϡ'), + ('Ϣ', 'Ϣ'), ('Ϥ', 'Ϥ'), ('Ϧ', 'Ϧ'), ('Ϩ', 'Ϩ'), ('Ϫ', 'Ϫ'), + ('Ϭ', 'Ϭ'), ('Ϯ', 'Ϯ'), ('ϰ', 'ϱ'), ('ϴ', 'ϵ'), ('Ϸ', 'Ϸ'), + ('Ϲ', 'Ϻ'), ('Ͻ', 'Я'), ('Ѡ', 'Ѡ'), ('Ѣ', 'Ѣ'), ('Ѥ', 'Ѥ'), + ('Ѧ', 'Ѧ'), ('Ѩ', 'Ѩ'), ('Ѫ', 'Ѫ'), ('Ѭ', 'Ѭ'), ('Ѯ', 'Ѯ'), + ('Ѱ', 'Ѱ'), ('Ѳ', 'Ѳ'), ('Ѵ', 'Ѵ'), ('Ѷ', 'Ѷ'), ('Ѹ', 'Ѹ'), + ('Ѻ', 'Ѻ'), ('Ѽ', 'Ѽ'), ('Ѿ', 'Ѿ'), ('Ҁ', 'Ҁ'), ('Ҋ', 'Ҋ'), + ('Ҍ', 'Ҍ'), ('Ҏ', 'Ҏ'), ('Ґ', 'Ґ'), ('Ғ', 'Ғ'), ('Ҕ', 'Ҕ'), + ('Җ', 'Җ'), ('Ҙ', 'Ҙ'), ('Қ', 'Қ'), ('Ҝ', 'Ҝ'), ('Ҟ', 'Ҟ'), + ('Ҡ', 'Ҡ'), ('Ң', 'Ң'), ('Ҥ', 'Ҥ'), ('Ҧ', 'Ҧ'), ('Ҩ', 'Ҩ'), + ('Ҫ', 'Ҫ'), ('Ҭ', 'Ҭ'), ('Ү', 'Ү'), ('Ұ', 'Ұ'), ('Ҳ', 'Ҳ'), + ('Ҵ', 'Ҵ'), ('Ҷ', 'Ҷ'), ('Ҹ', 'Ҹ'), ('Һ', 'Һ'), ('Ҽ', 'Ҽ'), + ('Ҿ', 'Ҿ'), ('Ӏ', 'Ӂ'), ('Ӄ', 'Ӄ'), ('Ӆ', 'Ӆ'), ('Ӈ', 'Ӈ'), + ('Ӊ', 'Ӊ'), ('Ӌ', 'Ӌ'), ('Ӎ', 'Ӎ'), ('Ӑ', 'Ӑ'), ('Ӓ', 'Ӓ'), + ('Ӕ', 'Ӕ'), ('Ӗ', 'Ӗ'), ('Ә', 'Ә'), ('Ӛ', 'Ӛ'), ('Ӝ', 'Ӝ'), + ('Ӟ', 'Ӟ'), ('Ӡ', 'Ӡ'), ('Ӣ', 'Ӣ'), ('Ӥ', 'Ӥ'), ('Ӧ', 'Ӧ'), + ('Ө', 'Ө'), ('Ӫ', 'Ӫ'), ('Ӭ', 'Ӭ'), ('Ӯ', 'Ӯ'), ('Ӱ', 'Ӱ'), + ('Ӳ', 'Ӳ'), ('Ӵ', 'Ӵ'), ('Ӷ', 'Ӷ'), ('Ӹ', 'Ӹ'), ('Ӻ', 'Ӻ'), + ('Ӽ', 'Ӽ'), ('Ӿ', 'Ӿ'), ('Ԁ', 'Ԁ'), ('Ԃ', 'Ԃ'), ('Ԅ', 'Ԅ'), + ('Ԇ', 'Ԇ'), ('Ԉ', 'Ԉ'), ('Ԋ', 'Ԋ'), ('Ԍ', 'Ԍ'), ('Ԏ', 'Ԏ'), + ('Ԑ', 'Ԑ'), ('Ԓ', 'Ԓ'), ('Ԕ', 'Ԕ'), ('Ԗ', 'Ԗ'), ('Ԙ', 'Ԙ'), + ('Ԛ', 'Ԛ'), ('Ԝ', 'Ԝ'), ('Ԟ', 'Ԟ'), ('Ԡ', 'Ԡ'), ('Ԣ', 'Ԣ'), + ('Ԥ', 'Ԥ'), ('Ԧ', 'Ԧ'), ('Ԩ', 'Ԩ'), ('Ԫ', 'Ԫ'), ('Ԭ', 'Ԭ'), + ('Ԯ', 'Ԯ'), ('Ա', 'Ֆ'), ('և', 'և'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), + ('Ⴭ', 'Ⴭ'), ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('Ḁ', 'Ḁ'), + ('Ḃ', 'Ḃ'), ('Ḅ', 'Ḅ'), ('Ḇ', 'Ḇ'), ('Ḉ', 'Ḉ'), + ('Ḋ', 'Ḋ'), ('Ḍ', 'Ḍ'), ('Ḏ', 'Ḏ'), ('Ḑ', 'Ḑ'), + ('Ḓ', 'Ḓ'), ('Ḕ', 'Ḕ'), ('Ḗ', 'Ḗ'), ('Ḙ', 'Ḙ'), + ('Ḛ', 'Ḛ'), ('Ḝ', 'Ḝ'), ('Ḟ', 'Ḟ'), ('Ḡ', 'Ḡ'), + ('Ḣ', 'Ḣ'), ('Ḥ', 'Ḥ'), ('Ḧ', 'Ḧ'), ('Ḩ', 'Ḩ'), + ('Ḫ', 'Ḫ'), ('Ḭ', 'Ḭ'), ('Ḯ', 'Ḯ'), ('Ḱ', 'Ḱ'), + ('Ḳ', 'Ḳ'), ('Ḵ', 'Ḵ'), ('Ḷ', 'Ḷ'), ('Ḹ', 'Ḹ'), + ('Ḻ', 'Ḻ'), ('Ḽ', 'Ḽ'), ('Ḿ', 'Ḿ'), ('Ṁ', 'Ṁ'), + ('Ṃ', 'Ṃ'), ('Ṅ', 'Ṅ'), ('Ṇ', 'Ṇ'), ('Ṉ', 'Ṉ'), + ('Ṋ', 'Ṋ'), ('Ṍ', 'Ṍ'), ('Ṏ', 'Ṏ'), ('Ṑ', 'Ṑ'), + ('Ṓ', 'Ṓ'), ('Ṕ', 'Ṕ'), ('Ṗ', 'Ṗ'), ('Ṙ', 'Ṙ'), + ('Ṛ', 'Ṛ'), ('Ṝ', 'Ṝ'), ('Ṟ', 'Ṟ'), ('Ṡ', 'Ṡ'), + ('Ṣ', 'Ṣ'), ('Ṥ', 'Ṥ'), ('Ṧ', 'Ṧ'), ('Ṩ', 'Ṩ'), + ('Ṫ', 'Ṫ'), ('Ṭ', 'Ṭ'), ('Ṯ', 'Ṯ'), ('Ṱ', 'Ṱ'), + ('Ṳ', 'Ṳ'), ('Ṵ', 'Ṵ'), ('Ṷ', 'Ṷ'), ('Ṹ', 'Ṹ'), + ('Ṻ', 'Ṻ'), ('Ṽ', 'Ṽ'), ('Ṿ', 'Ṿ'), ('Ẁ', 'Ẁ'), + ('Ẃ', 'Ẃ'), ('Ẅ', 'Ẅ'), ('Ẇ', 'Ẇ'), ('Ẉ', 'Ẉ'), + ('Ẋ', 'Ẋ'), ('Ẍ', 'Ẍ'), ('Ẏ', 'Ẏ'), ('Ẑ', 'Ẑ'), + ('Ẓ', 'Ẓ'), ('Ẕ', 'Ẕ'), ('ẚ', 'ẛ'), ('ẞ', 'ẞ'), + ('Ạ', 'Ạ'), ('Ả', 'Ả'), ('Ấ', 'Ấ'), ('Ầ', 'Ầ'), + ('Ẩ', 'Ẩ'), ('Ẫ', 'Ẫ'), ('Ậ', 'Ậ'), ('Ắ', 'Ắ'), + ('Ằ', 'Ằ'), ('Ẳ', 'Ẳ'), ('Ẵ', 'Ẵ'), ('Ặ', 'Ặ'), + ('Ẹ', 'Ẹ'), ('Ẻ', 'Ẻ'), ('Ẽ', 'Ẽ'), ('Ế', 'Ế'), + ('Ề', 'Ề'), ('Ể', 'Ể'), ('Ễ', 'Ễ'), ('Ệ', 'Ệ'), + ('Ỉ', 'Ỉ'), ('Ị', 'Ị'), ('Ọ', 'Ọ'), ('Ỏ', 'Ỏ'), + ('Ố', 'Ố'), ('Ồ', 'Ồ'), ('Ổ', 'Ổ'), ('Ỗ', 'Ỗ'), + ('Ộ', 'Ộ'), ('Ớ', 'Ớ'), ('Ờ', 'Ờ'), ('Ở', 'Ở'), + ('Ỡ', 'Ỡ'), ('Ợ', 'Ợ'), ('Ụ', 'Ụ'), ('Ủ', 'Ủ'), + ('Ứ', 'Ứ'), ('Ừ', 'Ừ'), ('Ử', 'Ử'), ('Ữ', 'Ữ'), + ('Ự', 'Ự'), ('Ỳ', 'Ỳ'), ('Ỵ', 'Ỵ'), ('Ỷ', 'Ỷ'), + ('Ỹ', 'Ỹ'), ('Ỻ', 'Ỻ'), ('Ỽ', 'Ỽ'), ('Ỿ', 'Ỿ'), + ('Ἀ', 'Ἇ'), ('Ἐ', 'Ἕ'), ('Ἠ', 'Ἧ'), ('Ἰ', 'Ἷ'), + ('Ὀ', 'Ὅ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), + ('Ὗ', 'Ὗ'), ('Ὠ', 'Ὧ'), ('ᾀ', 'ᾯ'), ('ᾲ', 'ᾴ'), + ('ᾷ', 'ᾼ'), ('ῂ', 'ῄ'), ('ῇ', 'ῌ'), ('Ῐ', 'Ί'), + ('Ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῷ', 'ῼ'), ('Ω', 'Ω'), + ('K', 'Å'), ('Ⅎ', 'Ⅎ'), ('Ⅰ', 'Ⅿ'), ('Ↄ', 'Ↄ'), + ('Ⓐ', 'Ⓩ'), ('Ⰰ', 'Ⱞ'), ('Ⱡ', 'Ⱡ'), ('Ɫ', 'Ɽ'), + ('Ⱨ', 'Ⱨ'), ('Ⱪ', 'Ⱪ'), ('Ⱬ', 'Ⱬ'), ('Ɑ', 'Ɒ'), + ('Ⱳ', 'Ⱳ'), ('Ⱶ', 'Ⱶ'), ('Ȿ', 'Ⲁ'), ('Ⲃ', 'Ⲃ'), + ('Ⲅ', 'Ⲅ'), ('Ⲇ', 'Ⲇ'), ('Ⲉ', 'Ⲉ'), ('Ⲋ', 'Ⲋ'), + ('Ⲍ', 'Ⲍ'), ('Ⲏ', 'Ⲏ'), ('Ⲑ', 'Ⲑ'), ('Ⲓ', 'Ⲓ'), + ('Ⲕ', 'Ⲕ'), ('Ⲗ', 'Ⲗ'), ('Ⲙ', 'Ⲙ'), ('Ⲛ', 'Ⲛ'), + ('Ⲝ', 'Ⲝ'), ('Ⲟ', 'Ⲟ'), ('Ⲡ', 'Ⲡ'), ('Ⲣ', 'Ⲣ'), + ('Ⲥ', 'Ⲥ'), ('Ⲧ', 'Ⲧ'), ('Ⲩ', 'Ⲩ'), ('Ⲫ', 'Ⲫ'), + ('Ⲭ', 'Ⲭ'), ('Ⲯ', 'Ⲯ'), ('Ⲱ', 'Ⲱ'), ('Ⲳ', 'Ⲳ'), + ('Ⲵ', 'Ⲵ'), ('Ⲷ', 'Ⲷ'), ('Ⲹ', 'Ⲹ'), ('Ⲻ', 'Ⲻ'), + ('Ⲽ', 'Ⲽ'), ('Ⲿ', 'Ⲿ'), ('Ⳁ', 'Ⳁ'), ('Ⳃ', 'Ⳃ'), + ('Ⳅ', 'Ⳅ'), ('Ⳇ', 'Ⳇ'), ('Ⳉ', 'Ⳉ'), ('Ⳋ', 'Ⳋ'), + ('Ⳍ', 'Ⳍ'), ('Ⳏ', 'Ⳏ'), ('Ⳑ', 'Ⳑ'), ('Ⳓ', 'Ⳓ'), + ('Ⳕ', 'Ⳕ'), ('Ⳗ', 'Ⳗ'), ('Ⳙ', 'Ⳙ'), ('Ⳛ', 'Ⳛ'), + ('Ⳝ', 'Ⳝ'), ('Ⳟ', 'Ⳟ'), ('Ⳡ', 'Ⳡ'), ('Ⳣ', 'Ⳣ'), + ('Ⳬ', 'Ⳬ'), ('Ⳮ', 'Ⳮ'), ('Ⳳ', 'Ⳳ'), ('Ꙁ', 'Ꙁ'), + ('Ꙃ', 'Ꙃ'), ('Ꙅ', 'Ꙅ'), ('Ꙇ', 'Ꙇ'), ('Ꙉ', 'Ꙉ'), + ('Ꙋ', 'Ꙋ'), ('Ꙍ', 'Ꙍ'), ('Ꙏ', 'Ꙏ'), ('Ꙑ', 'Ꙑ'), + ('Ꙓ', 'Ꙓ'), ('Ꙕ', 'Ꙕ'), ('Ꙗ', 'Ꙗ'), ('Ꙙ', 'Ꙙ'), + ('Ꙛ', 'Ꙛ'), ('Ꙝ', 'Ꙝ'), ('Ꙟ', 'Ꙟ'), ('Ꙡ', 'Ꙡ'), + ('Ꙣ', 'Ꙣ'), ('Ꙥ', 'Ꙥ'), ('Ꙧ', 'Ꙧ'), ('Ꙩ', 'Ꙩ'), + ('Ꙫ', 'Ꙫ'), ('Ꙭ', 'Ꙭ'), ('Ꚁ', 'Ꚁ'), ('Ꚃ', 'Ꚃ'), + ('Ꚅ', 'Ꚅ'), ('Ꚇ', 'Ꚇ'), ('Ꚉ', 'Ꚉ'), ('Ꚋ', 'Ꚋ'), + ('Ꚍ', 'Ꚍ'), ('Ꚏ', 'Ꚏ'), ('Ꚑ', 'Ꚑ'), ('Ꚓ', 'Ꚓ'), + ('Ꚕ', 'Ꚕ'), ('Ꚗ', 'Ꚗ'), ('Ꚙ', 'Ꚙ'), ('Ꚛ', 'Ꚛ'), + ('Ꜣ', 'Ꜣ'), ('Ꜥ', 'Ꜥ'), ('Ꜧ', 'Ꜧ'), ('Ꜩ', 'Ꜩ'), + ('Ꜫ', 'Ꜫ'), ('Ꜭ', 'Ꜭ'), ('Ꜯ', 'Ꜯ'), ('Ꜳ', 'Ꜳ'), + ('Ꜵ', 'Ꜵ'), ('Ꜷ', 'Ꜷ'), ('Ꜹ', 'Ꜹ'), ('Ꜻ', 'Ꜻ'), + ('Ꜽ', 'Ꜽ'), ('Ꜿ', 'Ꜿ'), ('Ꝁ', 'Ꝁ'), ('Ꝃ', 'Ꝃ'), + ('Ꝅ', 'Ꝅ'), ('Ꝇ', 'Ꝇ'), ('Ꝉ', 'Ꝉ'), ('Ꝋ', 'Ꝋ'), + ('Ꝍ', 'Ꝍ'), ('Ꝏ', 'Ꝏ'), ('Ꝑ', 'Ꝑ'), ('Ꝓ', 'Ꝓ'), + ('Ꝕ', 'Ꝕ'), ('Ꝗ', 'Ꝗ'), ('Ꝙ', 'Ꝙ'), ('Ꝛ', 'Ꝛ'), + ('Ꝝ', 'Ꝝ'), ('Ꝟ', 'Ꝟ'), ('Ꝡ', 'Ꝡ'), ('Ꝣ', 'Ꝣ'), + ('Ꝥ', 'Ꝥ'), ('Ꝧ', 'Ꝧ'), ('Ꝩ', 'Ꝩ'), ('Ꝫ', 'Ꝫ'), + ('Ꝭ', 'Ꝭ'), ('Ꝯ', 'Ꝯ'), ('Ꝺ', 'Ꝺ'), ('Ꝼ', 'Ꝼ'), + ('Ᵹ', 'Ꝿ'), ('Ꞁ', 'Ꞁ'), ('Ꞃ', 'Ꞃ'), ('Ꞅ', 'Ꞅ'), + ('Ꞇ', 'Ꞇ'), ('Ꞌ', 'Ꞌ'), ('Ɥ', 'Ɥ'), ('Ꞑ', 'Ꞑ'), + ('Ꞓ', 'Ꞓ'), ('Ꞗ', 'Ꞗ'), ('Ꞙ', 'Ꞙ'), ('Ꞛ', 'Ꞛ'), + ('Ꞝ', 'Ꞝ'), ('Ꞟ', 'Ꞟ'), ('Ꞡ', 'Ꞡ'), ('Ꞣ', 'Ꞣ'), + ('Ꞥ', 'Ꞥ'), ('Ꞧ', 'Ꞧ'), ('Ꞩ', 'Ꞩ'), ('Ɦ', 'Ɪ'), + ('Ʞ', 'Ꞵ'), ('Ꞷ', 'Ꞷ'), ('ꭰ', 'ꮿ'), ('ff', 'st'), + ('ﬓ', 'ﬗ'), ('A', 'Z'), ('𐐀', '𐐧'), ('𐒰', '𐓓'), + ('𐲀', '𐲲'), ('𑢠', '𑢿'), ('𞤀', '𞤡'), +]; + +pub const CHANGES_WHEN_CASEMAPPED: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('µ', 'µ'), ('À', 'Ö'), ('Ø', 'ö'), + ('ø', 'ķ'), ('Ĺ', 'ƌ'), ('Ǝ', 'ƚ'), ('Ɯ', 'Ʃ'), ('Ƭ', 'ƹ'), + ('Ƽ', 'ƽ'), ('ƿ', 'ƿ'), ('DŽ', 'Ƞ'), ('Ȣ', 'ȳ'), ('Ⱥ', 'ɔ'), + ('ɖ', 'ɗ'), ('ə', 'ə'), ('ɛ', 'ɜ'), ('ɠ', 'ɡ'), ('ɣ', 'ɣ'), + ('ɥ', 'ɦ'), ('ɨ', 'ɬ'), ('ɯ', 'ɯ'), ('ɱ', 'ɲ'), ('ɵ', 'ɵ'), + ('ɽ', 'ɽ'), ('ʀ', 'ʀ'), ('ʃ', 'ʃ'), ('ʇ', 'ʌ'), ('ʒ', 'ʒ'), + ('ʝ', 'ʞ'), ('ͅ', 'ͅ'), ('Ͱ', 'ͳ'), ('Ͷ', 'ͷ'), ('ͻ', 'ͽ'), + ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), + ('Σ', 'ϑ'), ('ϕ', 'ϵ'), ('Ϸ', 'ϻ'), ('Ͻ', 'ҁ'), ('Ҋ', 'ԯ'), + ('Ա', 'Ֆ'), ('ա', 'և'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᵹ', 'ᵹ'), + ('ᵽ', 'ᵽ'), ('Ḁ', 'ẛ'), ('ẞ', 'ẞ'), ('Ạ', 'ἕ'), + ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), + ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), + ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), ('ι', 'ι'), ('ῂ', 'ῄ'), + ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), ('ῖ', 'Ί'), ('ῠ', 'Ῥ'), + ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), ('Ω', 'Ω'), ('K', 'Å'), + ('Ⅎ', 'Ⅎ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ⅿ'), ('Ↄ', 'ↄ'), + ('Ⓐ', 'ⓩ'), ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'Ɒ'), + ('Ⱳ', 'ⱳ'), ('Ⱶ', 'ⱶ'), ('Ȿ', 'ⳣ'), ('Ⳬ', 'ⳮ'), + ('Ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), + ('Ꙁ', 'ꙭ'), ('Ꚁ', 'ꚛ'), ('Ꜣ', 'ꜯ'), ('Ꜳ', 'ꝯ'), + ('Ꝺ', 'ꞇ'), ('Ꞌ', 'Ɥ'), ('Ꞑ', 'ꞓ'), ('Ꞗ', 'Ɪ'), + ('Ʞ', 'ꞷ'), ('ꭓ', 'ꭓ'), ('ꭰ', 'ꮿ'), ('ff', 'st'), + ('ﬓ', 'ﬗ'), ('A', 'Z'), ('a', 'z'), ('𐐀', '𐑏'), + ('𐒰', '𐓓'), ('𐓘', '𐓻'), ('𐲀', '𐲲'), ('𐳀', '𐳲'), + ('𑢠', '𑣟'), ('𞤀', '𞥃'), +]; + +pub const CHANGES_WHEN_LOWERCASED: &'static [(char, char)] = &[ + ('A', 'Z'), ('À', 'Ö'), ('Ø', 'Þ'), ('Ā', 'Ā'), ('Ă', 'Ă'), + ('Ą', 'Ą'), ('Ć', 'Ć'), ('Ĉ', 'Ĉ'), ('Ċ', 'Ċ'), ('Č', 'Č'), + ('Ď', 'Ď'), ('Đ', 'Đ'), ('Ē', 'Ē'), ('Ĕ', 'Ĕ'), ('Ė', 'Ė'), + ('Ę', 'Ę'), ('Ě', 'Ě'), ('Ĝ', 'Ĝ'), ('Ğ', 'Ğ'), ('Ġ', 'Ġ'), + ('Ģ', 'Ģ'), ('Ĥ', 'Ĥ'), ('Ħ', 'Ħ'), ('Ĩ', 'Ĩ'), ('Ī', 'Ī'), + ('Ĭ', 'Ĭ'), ('Į', 'Į'), ('İ', 'İ'), ('IJ', 'IJ'), ('Ĵ', 'Ĵ'), + ('Ķ', 'Ķ'), ('Ĺ', 'Ĺ'), ('Ļ', 'Ļ'), ('Ľ', 'Ľ'), ('Ŀ', 'Ŀ'), + ('Ł', 'Ł'), ('Ń', 'Ń'), ('Ņ', 'Ņ'), ('Ň', 'Ň'), ('Ŋ', 'Ŋ'), + ('Ō', 'Ō'), ('Ŏ', 'Ŏ'), ('Ő', 'Ő'), ('Œ', 'Œ'), ('Ŕ', 'Ŕ'), + ('Ŗ', 'Ŗ'), ('Ř', 'Ř'), ('Ś', 'Ś'), ('Ŝ', 'Ŝ'), ('Ş', 'Ş'), + ('Š', 'Š'), ('Ţ', 'Ţ'), ('Ť', 'Ť'), ('Ŧ', 'Ŧ'), ('Ũ', 'Ũ'), + ('Ū', 'Ū'), ('Ŭ', 'Ŭ'), ('Ů', 'Ů'), ('Ű', 'Ű'), ('Ų', 'Ų'), + ('Ŵ', 'Ŵ'), ('Ŷ', 'Ŷ'), ('Ÿ', 'Ź'), ('Ż', 'Ż'), ('Ž', 'Ž'), + ('Ɓ', 'Ƃ'), ('Ƅ', 'Ƅ'), ('Ɔ', 'Ƈ'), ('Ɖ', 'Ƌ'), ('Ǝ', 'Ƒ'), + ('Ɠ', 'Ɣ'), ('Ɩ', 'Ƙ'), ('Ɯ', 'Ɲ'), ('Ɵ', 'Ơ'), ('Ƣ', 'Ƣ'), + ('Ƥ', 'Ƥ'), ('Ʀ', 'Ƨ'), ('Ʃ', 'Ʃ'), ('Ƭ', 'Ƭ'), ('Ʈ', 'Ư'), + ('Ʊ', 'Ƴ'), ('Ƶ', 'Ƶ'), ('Ʒ', 'Ƹ'), ('Ƽ', 'Ƽ'), ('DŽ', 'Dž'), + ('LJ', 'Lj'), ('NJ', 'Nj'), ('Ǎ', 'Ǎ'), ('Ǐ', 'Ǐ'), ('Ǒ', 'Ǒ'), + ('Ǔ', 'Ǔ'), ('Ǖ', 'Ǖ'), ('Ǘ', 'Ǘ'), ('Ǚ', 'Ǚ'), ('Ǜ', 'Ǜ'), + ('Ǟ', 'Ǟ'), ('Ǡ', 'Ǡ'), ('Ǣ', 'Ǣ'), ('Ǥ', 'Ǥ'), ('Ǧ', 'Ǧ'), + ('Ǩ', 'Ǩ'), ('Ǫ', 'Ǫ'), ('Ǭ', 'Ǭ'), ('Ǯ', 'Ǯ'), ('DZ', 'Dz'), + ('Ǵ', 'Ǵ'), ('Ƕ', 'Ǹ'), ('Ǻ', 'Ǻ'), ('Ǽ', 'Ǽ'), ('Ǿ', 'Ǿ'), + ('Ȁ', 'Ȁ'), ('Ȃ', 'Ȃ'), ('Ȅ', 'Ȅ'), ('Ȇ', 'Ȇ'), ('Ȉ', 'Ȉ'), + ('Ȋ', 'Ȋ'), ('Ȍ', 'Ȍ'), ('Ȏ', 'Ȏ'), ('Ȑ', 'Ȑ'), ('Ȓ', 'Ȓ'), + ('Ȕ', 'Ȕ'), ('Ȗ', 'Ȗ'), ('Ș', 'Ș'), ('Ț', 'Ț'), ('Ȝ', 'Ȝ'), + ('Ȟ', 'Ȟ'), ('Ƞ', 'Ƞ'), ('Ȣ', 'Ȣ'), ('Ȥ', 'Ȥ'), ('Ȧ', 'Ȧ'), + ('Ȩ', 'Ȩ'), ('Ȫ', 'Ȫ'), ('Ȭ', 'Ȭ'), ('Ȯ', 'Ȯ'), ('Ȱ', 'Ȱ'), + ('Ȳ', 'Ȳ'), ('Ⱥ', 'Ȼ'), ('Ƚ', 'Ⱦ'), ('Ɂ', 'Ɂ'), ('Ƀ', 'Ɇ'), + ('Ɉ', 'Ɉ'), ('Ɋ', 'Ɋ'), ('Ɍ', 'Ɍ'), ('Ɏ', 'Ɏ'), ('Ͱ', 'Ͱ'), + ('Ͳ', 'Ͳ'), ('Ͷ', 'Ͷ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), + ('Ό', 'Ό'), ('Ύ', 'Ώ'), ('Α', 'Ρ'), ('Σ', 'Ϋ'), ('Ϗ', 'Ϗ'), + ('Ϙ', 'Ϙ'), ('Ϛ', 'Ϛ'), ('Ϝ', 'Ϝ'), ('Ϟ', 'Ϟ'), ('Ϡ', 'Ϡ'), + ('Ϣ', 'Ϣ'), ('Ϥ', 'Ϥ'), ('Ϧ', 'Ϧ'), ('Ϩ', 'Ϩ'), ('Ϫ', 'Ϫ'), + ('Ϭ', 'Ϭ'), ('Ϯ', 'Ϯ'), ('ϴ', 'ϴ'), ('Ϸ', 'Ϸ'), ('Ϲ', 'Ϻ'), + ('Ͻ', 'Я'), ('Ѡ', 'Ѡ'), ('Ѣ', 'Ѣ'), ('Ѥ', 'Ѥ'), ('Ѧ', 'Ѧ'), + ('Ѩ', 'Ѩ'), ('Ѫ', 'Ѫ'), ('Ѭ', 'Ѭ'), ('Ѯ', 'Ѯ'), ('Ѱ', 'Ѱ'), + ('Ѳ', 'Ѳ'), ('Ѵ', 'Ѵ'), ('Ѷ', 'Ѷ'), ('Ѹ', 'Ѹ'), ('Ѻ', 'Ѻ'), + ('Ѽ', 'Ѽ'), ('Ѿ', 'Ѿ'), ('Ҁ', 'Ҁ'), ('Ҋ', 'Ҋ'), ('Ҍ', 'Ҍ'), + ('Ҏ', 'Ҏ'), ('Ґ', 'Ґ'), ('Ғ', 'Ғ'), ('Ҕ', 'Ҕ'), ('Җ', 'Җ'), + ('Ҙ', 'Ҙ'), ('Қ', 'Қ'), ('Ҝ', 'Ҝ'), ('Ҟ', 'Ҟ'), ('Ҡ', 'Ҡ'), + ('Ң', 'Ң'), ('Ҥ', 'Ҥ'), ('Ҧ', 'Ҧ'), ('Ҩ', 'Ҩ'), ('Ҫ', 'Ҫ'), + ('Ҭ', 'Ҭ'), ('Ү', 'Ү'), ('Ұ', 'Ұ'), ('Ҳ', 'Ҳ'), ('Ҵ', 'Ҵ'), + ('Ҷ', 'Ҷ'), ('Ҹ', 'Ҹ'), ('Һ', 'Һ'), ('Ҽ', 'Ҽ'), ('Ҿ', 'Ҿ'), + ('Ӏ', 'Ӂ'), ('Ӄ', 'Ӄ'), ('Ӆ', 'Ӆ'), ('Ӈ', 'Ӈ'), ('Ӊ', 'Ӊ'), + ('Ӌ', 'Ӌ'), ('Ӎ', 'Ӎ'), ('Ӑ', 'Ӑ'), ('Ӓ', 'Ӓ'), ('Ӕ', 'Ӕ'), + ('Ӗ', 'Ӗ'), ('Ә', 'Ә'), ('Ӛ', 'Ӛ'), ('Ӝ', 'Ӝ'), ('Ӟ', 'Ӟ'), + ('Ӡ', 'Ӡ'), ('Ӣ', 'Ӣ'), ('Ӥ', 'Ӥ'), ('Ӧ', 'Ӧ'), ('Ө', 'Ө'), + ('Ӫ', 'Ӫ'), ('Ӭ', 'Ӭ'), ('Ӯ', 'Ӯ'), ('Ӱ', 'Ӱ'), ('Ӳ', 'Ӳ'), + ('Ӵ', 'Ӵ'), ('Ӷ', 'Ӷ'), ('Ӹ', 'Ӹ'), ('Ӻ', 'Ӻ'), ('Ӽ', 'Ӽ'), + ('Ӿ', 'Ӿ'), ('Ԁ', 'Ԁ'), ('Ԃ', 'Ԃ'), ('Ԅ', 'Ԅ'), ('Ԇ', 'Ԇ'), + ('Ԉ', 'Ԉ'), ('Ԋ', 'Ԋ'), ('Ԍ', 'Ԍ'), ('Ԏ', 'Ԏ'), ('Ԑ', 'Ԑ'), + ('Ԓ', 'Ԓ'), ('Ԕ', 'Ԕ'), ('Ԗ', 'Ԗ'), ('Ԙ', 'Ԙ'), ('Ԛ', 'Ԛ'), + ('Ԝ', 'Ԝ'), ('Ԟ', 'Ԟ'), ('Ԡ', 'Ԡ'), ('Ԣ', 'Ԣ'), ('Ԥ', 'Ԥ'), + ('Ԧ', 'Ԧ'), ('Ԩ', 'Ԩ'), ('Ԫ', 'Ԫ'), ('Ԭ', 'Ԭ'), ('Ԯ', 'Ԯ'), + ('Ա', 'Ֆ'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('Ꭰ', 'Ᏽ'), ('Ḁ', 'Ḁ'), ('Ḃ', 'Ḃ'), ('Ḅ', 'Ḅ'), + ('Ḇ', 'Ḇ'), ('Ḉ', 'Ḉ'), ('Ḋ', 'Ḋ'), ('Ḍ', 'Ḍ'), + ('Ḏ', 'Ḏ'), ('Ḑ', 'Ḑ'), ('Ḓ', 'Ḓ'), ('Ḕ', 'Ḕ'), + ('Ḗ', 'Ḗ'), ('Ḙ', 'Ḙ'), ('Ḛ', 'Ḛ'), ('Ḝ', 'Ḝ'), + ('Ḟ', 'Ḟ'), ('Ḡ', 'Ḡ'), ('Ḣ', 'Ḣ'), ('Ḥ', 'Ḥ'), + ('Ḧ', 'Ḧ'), ('Ḩ', 'Ḩ'), ('Ḫ', 'Ḫ'), ('Ḭ', 'Ḭ'), + ('Ḯ', 'Ḯ'), ('Ḱ', 'Ḱ'), ('Ḳ', 'Ḳ'), ('Ḵ', 'Ḵ'), + ('Ḷ', 'Ḷ'), ('Ḹ', 'Ḹ'), ('Ḻ', 'Ḻ'), ('Ḽ', 'Ḽ'), + ('Ḿ', 'Ḿ'), ('Ṁ', 'Ṁ'), ('Ṃ', 'Ṃ'), ('Ṅ', 'Ṅ'), + ('Ṇ', 'Ṇ'), ('Ṉ', 'Ṉ'), ('Ṋ', 'Ṋ'), ('Ṍ', 'Ṍ'), + ('Ṏ', 'Ṏ'), ('Ṑ', 'Ṑ'), ('Ṓ', 'Ṓ'), ('Ṕ', 'Ṕ'), + ('Ṗ', 'Ṗ'), ('Ṙ', 'Ṙ'), ('Ṛ', 'Ṛ'), ('Ṝ', 'Ṝ'), + ('Ṟ', 'Ṟ'), ('Ṡ', 'Ṡ'), ('Ṣ', 'Ṣ'), ('Ṥ', 'Ṥ'), + ('Ṧ', 'Ṧ'), ('Ṩ', 'Ṩ'), ('Ṫ', 'Ṫ'), ('Ṭ', 'Ṭ'), + ('Ṯ', 'Ṯ'), ('Ṱ', 'Ṱ'), ('Ṳ', 'Ṳ'), ('Ṵ', 'Ṵ'), + ('Ṷ', 'Ṷ'), ('Ṹ', 'Ṹ'), ('Ṻ', 'Ṻ'), ('Ṽ', 'Ṽ'), + ('Ṿ', 'Ṿ'), ('Ẁ', 'Ẁ'), ('Ẃ', 'Ẃ'), ('Ẅ', 'Ẅ'), + ('Ẇ', 'Ẇ'), ('Ẉ', 'Ẉ'), ('Ẋ', 'Ẋ'), ('Ẍ', 'Ẍ'), + ('Ẏ', 'Ẏ'), ('Ẑ', 'Ẑ'), ('Ẓ', 'Ẓ'), ('Ẕ', 'Ẕ'), + ('ẞ', 'ẞ'), ('Ạ', 'Ạ'), ('Ả', 'Ả'), ('Ấ', 'Ấ'), + ('Ầ', 'Ầ'), ('Ẩ', 'Ẩ'), ('Ẫ', 'Ẫ'), ('Ậ', 'Ậ'), + ('Ắ', 'Ắ'), ('Ằ', 'Ằ'), ('Ẳ', 'Ẳ'), ('Ẵ', 'Ẵ'), + ('Ặ', 'Ặ'), ('Ẹ', 'Ẹ'), ('Ẻ', 'Ẻ'), ('Ẽ', 'Ẽ'), + ('Ế', 'Ế'), ('Ề', 'Ề'), ('Ể', 'Ể'), ('Ễ', 'Ễ'), + ('Ệ', 'Ệ'), ('Ỉ', 'Ỉ'), ('Ị', 'Ị'), ('Ọ', 'Ọ'), + ('Ỏ', 'Ỏ'), ('Ố', 'Ố'), ('Ồ', 'Ồ'), ('Ổ', 'Ổ'), + ('Ỗ', 'Ỗ'), ('Ộ', 'Ộ'), ('Ớ', 'Ớ'), ('Ờ', 'Ờ'), + ('Ở', 'Ở'), ('Ỡ', 'Ỡ'), ('Ợ', 'Ợ'), ('Ụ', 'Ụ'), + ('Ủ', 'Ủ'), ('Ứ', 'Ứ'), ('Ừ', 'Ừ'), ('Ử', 'Ử'), + ('Ữ', 'Ữ'), ('Ự', 'Ự'), ('Ỳ', 'Ỳ'), ('Ỵ', 'Ỵ'), + ('Ỷ', 'Ỷ'), ('Ỹ', 'Ỹ'), ('Ỻ', 'Ỻ'), ('Ỽ', 'Ỽ'), + ('Ỿ', 'Ỿ'), ('Ἀ', 'Ἇ'), ('Ἐ', 'Ἕ'), ('Ἠ', 'Ἧ'), + ('Ἰ', 'Ἷ'), ('Ὀ', 'Ὅ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), + ('Ὕ', 'Ὕ'), ('Ὗ', 'Ὗ'), ('Ὠ', 'Ὧ'), ('ᾈ', 'ᾏ'), + ('ᾘ', 'ᾟ'), ('ᾨ', 'ᾯ'), ('Ᾰ', 'ᾼ'), ('Ὲ', 'ῌ'), + ('Ῐ', 'Ί'), ('Ῠ', 'Ῥ'), ('Ὸ', 'ῼ'), ('Ω', 'Ω'), + ('K', 'Å'), ('Ⅎ', 'Ⅎ'), ('Ⅰ', 'Ⅿ'), ('Ↄ', 'Ↄ'), + ('Ⓐ', 'Ⓩ'), ('Ⰰ', 'Ⱞ'), ('Ⱡ', 'Ⱡ'), ('Ɫ', 'Ɽ'), + ('Ⱨ', 'Ⱨ'), ('Ⱪ', 'Ⱪ'), ('Ⱬ', 'Ⱬ'), ('Ɑ', 'Ɒ'), + ('Ⱳ', 'Ⱳ'), ('Ⱶ', 'Ⱶ'), ('Ȿ', 'Ⲁ'), ('Ⲃ', 'Ⲃ'), + ('Ⲅ', 'Ⲅ'), ('Ⲇ', 'Ⲇ'), ('Ⲉ', 'Ⲉ'), ('Ⲋ', 'Ⲋ'), + ('Ⲍ', 'Ⲍ'), ('Ⲏ', 'Ⲏ'), ('Ⲑ', 'Ⲑ'), ('Ⲓ', 'Ⲓ'), + ('Ⲕ', 'Ⲕ'), ('Ⲗ', 'Ⲗ'), ('Ⲙ', 'Ⲙ'), ('Ⲛ', 'Ⲛ'), + ('Ⲝ', 'Ⲝ'), ('Ⲟ', 'Ⲟ'), ('Ⲡ', 'Ⲡ'), ('Ⲣ', 'Ⲣ'), + ('Ⲥ', 'Ⲥ'), ('Ⲧ', 'Ⲧ'), ('Ⲩ', 'Ⲩ'), ('Ⲫ', 'Ⲫ'), + ('Ⲭ', 'Ⲭ'), ('Ⲯ', 'Ⲯ'), ('Ⲱ', 'Ⲱ'), ('Ⲳ', 'Ⲳ'), + ('Ⲵ', 'Ⲵ'), ('Ⲷ', 'Ⲷ'), ('Ⲹ', 'Ⲹ'), ('Ⲻ', 'Ⲻ'), + ('Ⲽ', 'Ⲽ'), ('Ⲿ', 'Ⲿ'), ('Ⳁ', 'Ⳁ'), ('Ⳃ', 'Ⳃ'), + ('Ⳅ', 'Ⳅ'), ('Ⳇ', 'Ⳇ'), ('Ⳉ', 'Ⳉ'), ('Ⳋ', 'Ⳋ'), + ('Ⳍ', 'Ⳍ'), ('Ⳏ', 'Ⳏ'), ('Ⳑ', 'Ⳑ'), ('Ⳓ', 'Ⳓ'), + ('Ⳕ', 'Ⳕ'), ('Ⳗ', 'Ⳗ'), ('Ⳙ', 'Ⳙ'), ('Ⳛ', 'Ⳛ'), + ('Ⳝ', 'Ⳝ'), ('Ⳟ', 'Ⳟ'), ('Ⳡ', 'Ⳡ'), ('Ⳣ', 'Ⳣ'), + ('Ⳬ', 'Ⳬ'), ('Ⳮ', 'Ⳮ'), ('Ⳳ', 'Ⳳ'), ('Ꙁ', 'Ꙁ'), + ('Ꙃ', 'Ꙃ'), ('Ꙅ', 'Ꙅ'), ('Ꙇ', 'Ꙇ'), ('Ꙉ', 'Ꙉ'), + ('Ꙋ', 'Ꙋ'), ('Ꙍ', 'Ꙍ'), ('Ꙏ', 'Ꙏ'), ('Ꙑ', 'Ꙑ'), + ('Ꙓ', 'Ꙓ'), ('Ꙕ', 'Ꙕ'), ('Ꙗ', 'Ꙗ'), ('Ꙙ', 'Ꙙ'), + ('Ꙛ', 'Ꙛ'), ('Ꙝ', 'Ꙝ'), ('Ꙟ', 'Ꙟ'), ('Ꙡ', 'Ꙡ'), + ('Ꙣ', 'Ꙣ'), ('Ꙥ', 'Ꙥ'), ('Ꙧ', 'Ꙧ'), ('Ꙩ', 'Ꙩ'), + ('Ꙫ', 'Ꙫ'), ('Ꙭ', 'Ꙭ'), ('Ꚁ', 'Ꚁ'), ('Ꚃ', 'Ꚃ'), + ('Ꚅ', 'Ꚅ'), ('Ꚇ', 'Ꚇ'), ('Ꚉ', 'Ꚉ'), ('Ꚋ', 'Ꚋ'), + ('Ꚍ', 'Ꚍ'), ('Ꚏ', 'Ꚏ'), ('Ꚑ', 'Ꚑ'), ('Ꚓ', 'Ꚓ'), + ('Ꚕ', 'Ꚕ'), ('Ꚗ', 'Ꚗ'), ('Ꚙ', 'Ꚙ'), ('Ꚛ', 'Ꚛ'), + ('Ꜣ', 'Ꜣ'), ('Ꜥ', 'Ꜥ'), ('Ꜧ', 'Ꜧ'), ('Ꜩ', 'Ꜩ'), + ('Ꜫ', 'Ꜫ'), ('Ꜭ', 'Ꜭ'), ('Ꜯ', 'Ꜯ'), ('Ꜳ', 'Ꜳ'), + ('Ꜵ', 'Ꜵ'), ('Ꜷ', 'Ꜷ'), ('Ꜹ', 'Ꜹ'), ('Ꜻ', 'Ꜻ'), + ('Ꜽ', 'Ꜽ'), ('Ꜿ', 'Ꜿ'), ('Ꝁ', 'Ꝁ'), ('Ꝃ', 'Ꝃ'), + ('Ꝅ', 'Ꝅ'), ('Ꝇ', 'Ꝇ'), ('Ꝉ', 'Ꝉ'), ('Ꝋ', 'Ꝋ'), + ('Ꝍ', 'Ꝍ'), ('Ꝏ', 'Ꝏ'), ('Ꝑ', 'Ꝑ'), ('Ꝓ', 'Ꝓ'), + ('Ꝕ', 'Ꝕ'), ('Ꝗ', 'Ꝗ'), ('Ꝙ', 'Ꝙ'), ('Ꝛ', 'Ꝛ'), + ('Ꝝ', 'Ꝝ'), ('Ꝟ', 'Ꝟ'), ('Ꝡ', 'Ꝡ'), ('Ꝣ', 'Ꝣ'), + ('Ꝥ', 'Ꝥ'), ('Ꝧ', 'Ꝧ'), ('Ꝩ', 'Ꝩ'), ('Ꝫ', 'Ꝫ'), + ('Ꝭ', 'Ꝭ'), ('Ꝯ', 'Ꝯ'), ('Ꝺ', 'Ꝺ'), ('Ꝼ', 'Ꝼ'), + ('Ᵹ', 'Ꝿ'), ('Ꞁ', 'Ꞁ'), ('Ꞃ', 'Ꞃ'), ('Ꞅ', 'Ꞅ'), + ('Ꞇ', 'Ꞇ'), ('Ꞌ', 'Ꞌ'), ('Ɥ', 'Ɥ'), ('Ꞑ', 'Ꞑ'), + ('Ꞓ', 'Ꞓ'), ('Ꞗ', 'Ꞗ'), ('Ꞙ', 'Ꞙ'), ('Ꞛ', 'Ꞛ'), + ('Ꞝ', 'Ꞝ'), ('Ꞟ', 'Ꞟ'), ('Ꞡ', 'Ꞡ'), ('Ꞣ', 'Ꞣ'), + ('Ꞥ', 'Ꞥ'), ('Ꞧ', 'Ꞧ'), ('Ꞩ', 'Ꞩ'), ('Ɦ', 'Ɪ'), + ('Ʞ', 'Ꞵ'), ('Ꞷ', 'Ꞷ'), ('A', 'Z'), ('𐐀', '𐐧'), + ('𐒰', '𐓓'), ('𐲀', '𐲲'), ('𑢠', '𑢿'), ('𞤀', '𞤡'), +]; + +pub const CHANGES_WHEN_TITLECASED: &'static [(char, char)] = &[ + ('a', 'z'), ('µ', 'µ'), ('ß', 'ö'), ('ø', 'ÿ'), ('ā', 'ā'), + ('ă', 'ă'), ('ą', 'ą'), ('ć', 'ć'), ('ĉ', 'ĉ'), ('ċ', 'ċ'), + ('č', 'č'), ('ď', 'ď'), ('đ', 'đ'), ('ē', 'ē'), ('ĕ', 'ĕ'), + ('ė', 'ė'), ('ę', 'ę'), ('ě', 'ě'), ('ĝ', 'ĝ'), ('ğ', 'ğ'), + ('ġ', 'ġ'), ('ģ', 'ģ'), ('ĥ', 'ĥ'), ('ħ', 'ħ'), ('ĩ', 'ĩ'), + ('ī', 'ī'), ('ĭ', 'ĭ'), ('į', 'į'), ('ı', 'ı'), ('ij', 'ij'), + ('ĵ', 'ĵ'), ('ķ', 'ķ'), ('ĺ', 'ĺ'), ('ļ', 'ļ'), ('ľ', 'ľ'), + ('ŀ', 'ŀ'), ('ł', 'ł'), ('ń', 'ń'), ('ņ', 'ņ'), ('ň', 'ʼn'), + ('ŋ', 'ŋ'), ('ō', 'ō'), ('ŏ', 'ŏ'), ('ő', 'ő'), ('œ', 'œ'), + ('ŕ', 'ŕ'), ('ŗ', 'ŗ'), ('ř', 'ř'), ('ś', 'ś'), ('ŝ', 'ŝ'), + ('ş', 'ş'), ('š', 'š'), ('ţ', 'ţ'), ('ť', 'ť'), ('ŧ', 'ŧ'), + ('ũ', 'ũ'), ('ū', 'ū'), ('ŭ', 'ŭ'), ('ů', 'ů'), ('ű', 'ű'), + ('ų', 'ų'), ('ŵ', 'ŵ'), ('ŷ', 'ŷ'), ('ź', 'ź'), ('ż', 'ż'), + ('ž', 'ƀ'), ('ƃ', 'ƃ'), ('ƅ', 'ƅ'), ('ƈ', 'ƈ'), ('ƌ', 'ƌ'), + ('ƒ', 'ƒ'), ('ƕ', 'ƕ'), ('ƙ', 'ƚ'), ('ƞ', 'ƞ'), ('ơ', 'ơ'), + ('ƣ', 'ƣ'), ('ƥ', 'ƥ'), ('ƨ', 'ƨ'), ('ƭ', 'ƭ'), ('ư', 'ư'), + ('ƴ', 'ƴ'), ('ƶ', 'ƶ'), ('ƹ', 'ƹ'), ('ƽ', 'ƽ'), ('ƿ', 'ƿ'), + ('DŽ', 'DŽ'), ('dž', 'LJ'), ('lj', 'NJ'), ('nj', 'nj'), ('ǎ', 'ǎ'), + ('ǐ', 'ǐ'), ('ǒ', 'ǒ'), ('ǔ', 'ǔ'), ('ǖ', 'ǖ'), ('ǘ', 'ǘ'), + ('ǚ', 'ǚ'), ('ǜ', 'ǝ'), ('ǟ', 'ǟ'), ('ǡ', 'ǡ'), ('ǣ', 'ǣ'), + ('ǥ', 'ǥ'), ('ǧ', 'ǧ'), ('ǩ', 'ǩ'), ('ǫ', 'ǫ'), ('ǭ', 'ǭ'), + ('ǯ', 'DZ'), ('dz', 'dz'), ('ǵ', 'ǵ'), ('ǹ', 'ǹ'), ('ǻ', 'ǻ'), + ('ǽ', 'ǽ'), ('ǿ', 'ǿ'), ('ȁ', 'ȁ'), ('ȃ', 'ȃ'), ('ȅ', 'ȅ'), + ('ȇ', 'ȇ'), ('ȉ', 'ȉ'), ('ȋ', 'ȋ'), ('ȍ', 'ȍ'), ('ȏ', 'ȏ'), + ('ȑ', 'ȑ'), ('ȓ', 'ȓ'), ('ȕ', 'ȕ'), ('ȗ', 'ȗ'), ('ș', 'ș'), + ('ț', 'ț'), ('ȝ', 'ȝ'), ('ȟ', 'ȟ'), ('ȣ', 'ȣ'), ('ȥ', 'ȥ'), + ('ȧ', 'ȧ'), ('ȩ', 'ȩ'), ('ȫ', 'ȫ'), ('ȭ', 'ȭ'), ('ȯ', 'ȯ'), + ('ȱ', 'ȱ'), ('ȳ', 'ȳ'), ('ȼ', 'ȼ'), ('ȿ', 'ɀ'), ('ɂ', 'ɂ'), + ('ɇ', 'ɇ'), ('ɉ', 'ɉ'), ('ɋ', 'ɋ'), ('ɍ', 'ɍ'), ('ɏ', 'ɔ'), + ('ɖ', 'ɗ'), ('ə', 'ə'), ('ɛ', 'ɜ'), ('ɠ', 'ɡ'), ('ɣ', 'ɣ'), + ('ɥ', 'ɦ'), ('ɨ', 'ɬ'), ('ɯ', 'ɯ'), ('ɱ', 'ɲ'), ('ɵ', 'ɵ'), + ('ɽ', 'ɽ'), ('ʀ', 'ʀ'), ('ʃ', 'ʃ'), ('ʇ', 'ʌ'), ('ʒ', 'ʒ'), + ('ʝ', 'ʞ'), ('ͅ', 'ͅ'), ('ͱ', 'ͱ'), ('ͳ', 'ͳ'), ('ͷ', 'ͷ'), + ('ͻ', 'ͽ'), ('ΐ', 'ΐ'), ('ά', 'ώ'), ('ϐ', 'ϑ'), ('ϕ', 'ϗ'), + ('ϙ', 'ϙ'), ('ϛ', 'ϛ'), ('ϝ', 'ϝ'), ('ϟ', 'ϟ'), ('ϡ', 'ϡ'), + ('ϣ', 'ϣ'), ('ϥ', 'ϥ'), ('ϧ', 'ϧ'), ('ϩ', 'ϩ'), ('ϫ', 'ϫ'), + ('ϭ', 'ϭ'), ('ϯ', 'ϳ'), ('ϵ', 'ϵ'), ('ϸ', 'ϸ'), ('ϻ', 'ϻ'), + ('а', 'џ'), ('ѡ', 'ѡ'), ('ѣ', 'ѣ'), ('ѥ', 'ѥ'), ('ѧ', 'ѧ'), + ('ѩ', 'ѩ'), ('ѫ', 'ѫ'), ('ѭ', 'ѭ'), ('ѯ', 'ѯ'), ('ѱ', 'ѱ'), + ('ѳ', 'ѳ'), ('ѵ', 'ѵ'), ('ѷ', 'ѷ'), ('ѹ', 'ѹ'), ('ѻ', 'ѻ'), + ('ѽ', 'ѽ'), ('ѿ', 'ѿ'), ('ҁ', 'ҁ'), ('ҋ', 'ҋ'), ('ҍ', 'ҍ'), + ('ҏ', 'ҏ'), ('ґ', 'ґ'), ('ғ', 'ғ'), ('ҕ', 'ҕ'), ('җ', 'җ'), + ('ҙ', 'ҙ'), ('қ', 'қ'), ('ҝ', 'ҝ'), ('ҟ', 'ҟ'), ('ҡ', 'ҡ'), + ('ң', 'ң'), ('ҥ', 'ҥ'), ('ҧ', 'ҧ'), ('ҩ', 'ҩ'), ('ҫ', 'ҫ'), + ('ҭ', 'ҭ'), ('ү', 'ү'), ('ұ', 'ұ'), ('ҳ', 'ҳ'), ('ҵ', 'ҵ'), + ('ҷ', 'ҷ'), ('ҹ', 'ҹ'), ('һ', 'һ'), ('ҽ', 'ҽ'), ('ҿ', 'ҿ'), + ('ӂ', 'ӂ'), ('ӄ', 'ӄ'), ('ӆ', 'ӆ'), ('ӈ', 'ӈ'), ('ӊ', 'ӊ'), + ('ӌ', 'ӌ'), ('ӎ', 'ӏ'), ('ӑ', 'ӑ'), ('ӓ', 'ӓ'), ('ӕ', 'ӕ'), + ('ӗ', 'ӗ'), ('ә', 'ә'), ('ӛ', 'ӛ'), ('ӝ', 'ӝ'), ('ӟ', 'ӟ'), + ('ӡ', 'ӡ'), ('ӣ', 'ӣ'), ('ӥ', 'ӥ'), ('ӧ', 'ӧ'), ('ө', 'ө'), + ('ӫ', 'ӫ'), ('ӭ', 'ӭ'), ('ӯ', 'ӯ'), ('ӱ', 'ӱ'), ('ӳ', 'ӳ'), + ('ӵ', 'ӵ'), ('ӷ', 'ӷ'), ('ӹ', 'ӹ'), ('ӻ', 'ӻ'), ('ӽ', 'ӽ'), + ('ӿ', 'ӿ'), ('ԁ', 'ԁ'), ('ԃ', 'ԃ'), ('ԅ', 'ԅ'), ('ԇ', 'ԇ'), + ('ԉ', 'ԉ'), ('ԋ', 'ԋ'), ('ԍ', 'ԍ'), ('ԏ', 'ԏ'), ('ԑ', 'ԑ'), + ('ԓ', 'ԓ'), ('ԕ', 'ԕ'), ('ԗ', 'ԗ'), ('ԙ', 'ԙ'), ('ԛ', 'ԛ'), + ('ԝ', 'ԝ'), ('ԟ', 'ԟ'), ('ԡ', 'ԡ'), ('ԣ', 'ԣ'), ('ԥ', 'ԥ'), + ('ԧ', 'ԧ'), ('ԩ', 'ԩ'), ('ԫ', 'ԫ'), ('ԭ', 'ԭ'), ('ԯ', 'ԯ'), + ('ա', 'և'), ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᵹ', 'ᵹ'), + ('ᵽ', 'ᵽ'), ('ḁ', 'ḁ'), ('ḃ', 'ḃ'), ('ḅ', 'ḅ'), + ('ḇ', 'ḇ'), ('ḉ', 'ḉ'), ('ḋ', 'ḋ'), ('ḍ', 'ḍ'), + ('ḏ', 'ḏ'), ('ḑ', 'ḑ'), ('ḓ', 'ḓ'), ('ḕ', 'ḕ'), + ('ḗ', 'ḗ'), ('ḙ', 'ḙ'), ('ḛ', 'ḛ'), ('ḝ', 'ḝ'), + ('ḟ', 'ḟ'), ('ḡ', 'ḡ'), ('ḣ', 'ḣ'), ('ḥ', 'ḥ'), + ('ḧ', 'ḧ'), ('ḩ', 'ḩ'), ('ḫ', 'ḫ'), ('ḭ', 'ḭ'), + ('ḯ', 'ḯ'), ('ḱ', 'ḱ'), ('ḳ', 'ḳ'), ('ḵ', 'ḵ'), + ('ḷ', 'ḷ'), ('ḹ', 'ḹ'), ('ḻ', 'ḻ'), ('ḽ', 'ḽ'), + ('ḿ', 'ḿ'), ('ṁ', 'ṁ'), ('ṃ', 'ṃ'), ('ṅ', 'ṅ'), + ('ṇ', 'ṇ'), ('ṉ', 'ṉ'), ('ṋ', 'ṋ'), ('ṍ', 'ṍ'), + ('ṏ', 'ṏ'), ('ṑ', 'ṑ'), ('ṓ', 'ṓ'), ('ṕ', 'ṕ'), + ('ṗ', 'ṗ'), ('ṙ', 'ṙ'), ('ṛ', 'ṛ'), ('ṝ', 'ṝ'), + ('ṟ', 'ṟ'), ('ṡ', 'ṡ'), ('ṣ', 'ṣ'), ('ṥ', 'ṥ'), + ('ṧ', 'ṧ'), ('ṩ', 'ṩ'), ('ṫ', 'ṫ'), ('ṭ', 'ṭ'), + ('ṯ', 'ṯ'), ('ṱ', 'ṱ'), ('ṳ', 'ṳ'), ('ṵ', 'ṵ'), + ('ṷ', 'ṷ'), ('ṹ', 'ṹ'), ('ṻ', 'ṻ'), ('ṽ', 'ṽ'), + ('ṿ', 'ṿ'), ('ẁ', 'ẁ'), ('ẃ', 'ẃ'), ('ẅ', 'ẅ'), + ('ẇ', 'ẇ'), ('ẉ', 'ẉ'), ('ẋ', 'ẋ'), ('ẍ', 'ẍ'), + ('ẏ', 'ẏ'), ('ẑ', 'ẑ'), ('ẓ', 'ẓ'), ('ẕ', 'ẛ'), + ('ạ', 'ạ'), ('ả', 'ả'), ('ấ', 'ấ'), ('ầ', 'ầ'), + ('ẩ', 'ẩ'), ('ẫ', 'ẫ'), ('ậ', 'ậ'), ('ắ', 'ắ'), + ('ằ', 'ằ'), ('ẳ', 'ẳ'), ('ẵ', 'ẵ'), ('ặ', 'ặ'), + ('ẹ', 'ẹ'), ('ẻ', 'ẻ'), ('ẽ', 'ẽ'), ('ế', 'ế'), + ('ề', 'ề'), ('ể', 'ể'), ('ễ', 'ễ'), ('ệ', 'ệ'), + ('ỉ', 'ỉ'), ('ị', 'ị'), ('ọ', 'ọ'), ('ỏ', 'ỏ'), + ('ố', 'ố'), ('ồ', 'ồ'), ('ổ', 'ổ'), ('ỗ', 'ỗ'), + ('ộ', 'ộ'), ('ớ', 'ớ'), ('ờ', 'ờ'), ('ở', 'ở'), + ('ỡ', 'ỡ'), ('ợ', 'ợ'), ('ụ', 'ụ'), ('ủ', 'ủ'), + ('ứ', 'ứ'), ('ừ', 'ừ'), ('ử', 'ử'), ('ữ', 'ữ'), + ('ự', 'ự'), ('ỳ', 'ỳ'), ('ỵ', 'ỵ'), ('ỷ', 'ỷ'), + ('ỹ', 'ỹ'), ('ỻ', 'ỻ'), ('ỽ', 'ỽ'), ('ỿ', 'ἇ'), + ('ἐ', 'ἕ'), ('ἠ', 'ἧ'), ('ἰ', 'ἷ'), ('ὀ', 'ὅ'), + ('ὐ', 'ὗ'), ('ὠ', 'ὧ'), ('ὰ', 'ώ'), ('ᾀ', 'ᾇ'), + ('ᾐ', 'ᾗ'), ('ᾠ', 'ᾧ'), ('ᾰ', 'ᾴ'), ('ᾶ', 'ᾷ'), + ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῇ'), ('ῐ', 'ΐ'), + ('ῖ', 'ῗ'), ('ῠ', 'ῧ'), ('ῲ', 'ῴ'), ('ῶ', 'ῷ'), + ('ⅎ', 'ⅎ'), ('ⅰ', 'ⅿ'), ('ↄ', 'ↄ'), ('ⓐ', 'ⓩ'), + ('ⰰ', 'ⱞ'), ('ⱡ', 'ⱡ'), ('ⱥ', 'ⱦ'), ('ⱨ', 'ⱨ'), + ('ⱪ', 'ⱪ'), ('ⱬ', 'ⱬ'), ('ⱳ', 'ⱳ'), ('ⱶ', 'ⱶ'), + ('ⲁ', 'ⲁ'), ('ⲃ', 'ⲃ'), ('ⲅ', 'ⲅ'), ('ⲇ', 'ⲇ'), + ('ⲉ', 'ⲉ'), ('ⲋ', 'ⲋ'), ('ⲍ', 'ⲍ'), ('ⲏ', 'ⲏ'), + ('ⲑ', 'ⲑ'), ('ⲓ', 'ⲓ'), ('ⲕ', 'ⲕ'), ('ⲗ', 'ⲗ'), + ('ⲙ', 'ⲙ'), ('ⲛ', 'ⲛ'), ('ⲝ', 'ⲝ'), ('ⲟ', 'ⲟ'), + ('ⲡ', 'ⲡ'), ('ⲣ', 'ⲣ'), ('ⲥ', 'ⲥ'), ('ⲧ', 'ⲧ'), + ('ⲩ', 'ⲩ'), ('ⲫ', 'ⲫ'), ('ⲭ', 'ⲭ'), ('ⲯ', 'ⲯ'), + ('ⲱ', 'ⲱ'), ('ⲳ', 'ⲳ'), ('ⲵ', 'ⲵ'), ('ⲷ', 'ⲷ'), + ('ⲹ', 'ⲹ'), ('ⲻ', 'ⲻ'), ('ⲽ', 'ⲽ'), ('ⲿ', 'ⲿ'), + ('ⳁ', 'ⳁ'), ('ⳃ', 'ⳃ'), ('ⳅ', 'ⳅ'), ('ⳇ', 'ⳇ'), + ('ⳉ', 'ⳉ'), ('ⳋ', 'ⳋ'), ('ⳍ', 'ⳍ'), ('ⳏ', 'ⳏ'), + ('ⳑ', 'ⳑ'), ('ⳓ', 'ⳓ'), ('ⳕ', 'ⳕ'), ('ⳗ', 'ⳗ'), + ('ⳙ', 'ⳙ'), ('ⳛ', 'ⳛ'), ('ⳝ', 'ⳝ'), ('ⳟ', 'ⳟ'), + ('ⳡ', 'ⳡ'), ('ⳣ', 'ⳣ'), ('ⳬ', 'ⳬ'), ('ⳮ', 'ⳮ'), + ('ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), + ('ꙁ', 'ꙁ'), ('ꙃ', 'ꙃ'), ('ꙅ', 'ꙅ'), ('ꙇ', 'ꙇ'), + ('ꙉ', 'ꙉ'), ('ꙋ', 'ꙋ'), ('ꙍ', 'ꙍ'), ('ꙏ', 'ꙏ'), + ('ꙑ', 'ꙑ'), ('ꙓ', 'ꙓ'), ('ꙕ', 'ꙕ'), ('ꙗ', 'ꙗ'), + ('ꙙ', 'ꙙ'), ('ꙛ', 'ꙛ'), ('ꙝ', 'ꙝ'), ('ꙟ', 'ꙟ'), + ('ꙡ', 'ꙡ'), ('ꙣ', 'ꙣ'), ('ꙥ', 'ꙥ'), ('ꙧ', 'ꙧ'), + ('ꙩ', 'ꙩ'), ('ꙫ', 'ꙫ'), ('ꙭ', 'ꙭ'), ('ꚁ', 'ꚁ'), + ('ꚃ', 'ꚃ'), ('ꚅ', 'ꚅ'), ('ꚇ', 'ꚇ'), ('ꚉ', 'ꚉ'), + ('ꚋ', 'ꚋ'), ('ꚍ', 'ꚍ'), ('ꚏ', 'ꚏ'), ('ꚑ', 'ꚑ'), + ('ꚓ', 'ꚓ'), ('ꚕ', 'ꚕ'), ('ꚗ', 'ꚗ'), ('ꚙ', 'ꚙ'), + ('ꚛ', 'ꚛ'), ('ꜣ', 'ꜣ'), ('ꜥ', 'ꜥ'), ('ꜧ', 'ꜧ'), + ('ꜩ', 'ꜩ'), ('ꜫ', 'ꜫ'), ('ꜭ', 'ꜭ'), ('ꜯ', 'ꜯ'), + ('ꜳ', 'ꜳ'), ('ꜵ', 'ꜵ'), ('ꜷ', 'ꜷ'), ('ꜹ', 'ꜹ'), + ('ꜻ', 'ꜻ'), ('ꜽ', 'ꜽ'), ('ꜿ', 'ꜿ'), ('ꝁ', 'ꝁ'), + ('ꝃ', 'ꝃ'), ('ꝅ', 'ꝅ'), ('ꝇ', 'ꝇ'), ('ꝉ', 'ꝉ'), + ('ꝋ', 'ꝋ'), ('ꝍ', 'ꝍ'), ('ꝏ', 'ꝏ'), ('ꝑ', 'ꝑ'), + ('ꝓ', 'ꝓ'), ('ꝕ', 'ꝕ'), ('ꝗ', 'ꝗ'), ('ꝙ', 'ꝙ'), + ('ꝛ', 'ꝛ'), ('ꝝ', 'ꝝ'), ('ꝟ', 'ꝟ'), ('ꝡ', 'ꝡ'), + ('ꝣ', 'ꝣ'), ('ꝥ', 'ꝥ'), ('ꝧ', 'ꝧ'), ('ꝩ', 'ꝩ'), + ('ꝫ', 'ꝫ'), ('ꝭ', 'ꝭ'), ('ꝯ', 'ꝯ'), ('ꝺ', 'ꝺ'), + ('ꝼ', 'ꝼ'), ('ꝿ', 'ꝿ'), ('ꞁ', 'ꞁ'), ('ꞃ', 'ꞃ'), + ('ꞅ', 'ꞅ'), ('ꞇ', 'ꞇ'), ('ꞌ', 'ꞌ'), ('ꞑ', 'ꞑ'), + ('ꞓ', 'ꞓ'), ('ꞗ', 'ꞗ'), ('ꞙ', 'ꞙ'), ('ꞛ', 'ꞛ'), + ('ꞝ', 'ꞝ'), ('ꞟ', 'ꞟ'), ('ꞡ', 'ꞡ'), ('ꞣ', 'ꞣ'), + ('ꞥ', 'ꞥ'), ('ꞧ', 'ꞧ'), ('ꞩ', 'ꞩ'), ('ꞵ', 'ꞵ'), + ('ꞷ', 'ꞷ'), ('ꭓ', 'ꭓ'), ('ꭰ', 'ꮿ'), ('ff', 'st'), + ('ﬓ', 'ﬗ'), ('a', 'z'), ('𐐨', '𐑏'), ('𐓘', '𐓻'), + ('𐳀', '𐳲'), ('𑣀', '𑣟'), ('𞤢', '𞥃'), +]; + +pub const CHANGES_WHEN_UPPERCASED: &'static [(char, char)] = &[ + ('a', 'z'), ('µ', 'µ'), ('ß', 'ö'), ('ø', 'ÿ'), ('ā', 'ā'), + ('ă', 'ă'), ('ą', 'ą'), ('ć', 'ć'), ('ĉ', 'ĉ'), ('ċ', 'ċ'), + ('č', 'č'), ('ď', 'ď'), ('đ', 'đ'), ('ē', 'ē'), ('ĕ', 'ĕ'), + ('ė', 'ė'), ('ę', 'ę'), ('ě', 'ě'), ('ĝ', 'ĝ'), ('ğ', 'ğ'), + ('ġ', 'ġ'), ('ģ', 'ģ'), ('ĥ', 'ĥ'), ('ħ', 'ħ'), ('ĩ', 'ĩ'), + ('ī', 'ī'), ('ĭ', 'ĭ'), ('į', 'į'), ('ı', 'ı'), ('ij', 'ij'), + ('ĵ', 'ĵ'), ('ķ', 'ķ'), ('ĺ', 'ĺ'), ('ļ', 'ļ'), ('ľ', 'ľ'), + ('ŀ', 'ŀ'), ('ł', 'ł'), ('ń', 'ń'), ('ņ', 'ņ'), ('ň', 'ʼn'), + ('ŋ', 'ŋ'), ('ō', 'ō'), ('ŏ', 'ŏ'), ('ő', 'ő'), ('œ', 'œ'), + ('ŕ', 'ŕ'), ('ŗ', 'ŗ'), ('ř', 'ř'), ('ś', 'ś'), ('ŝ', 'ŝ'), + ('ş', 'ş'), ('š', 'š'), ('ţ', 'ţ'), ('ť', 'ť'), ('ŧ', 'ŧ'), + ('ũ', 'ũ'), ('ū', 'ū'), ('ŭ', 'ŭ'), ('ů', 'ů'), ('ű', 'ű'), + ('ų', 'ų'), ('ŵ', 'ŵ'), ('ŷ', 'ŷ'), ('ź', 'ź'), ('ż', 'ż'), + ('ž', 'ƀ'), ('ƃ', 'ƃ'), ('ƅ', 'ƅ'), ('ƈ', 'ƈ'), ('ƌ', 'ƌ'), + ('ƒ', 'ƒ'), ('ƕ', 'ƕ'), ('ƙ', 'ƚ'), ('ƞ', 'ƞ'), ('ơ', 'ơ'), + ('ƣ', 'ƣ'), ('ƥ', 'ƥ'), ('ƨ', 'ƨ'), ('ƭ', 'ƭ'), ('ư', 'ư'), + ('ƴ', 'ƴ'), ('ƶ', 'ƶ'), ('ƹ', 'ƹ'), ('ƽ', 'ƽ'), ('ƿ', 'ƿ'), + ('Dž', 'dž'), ('Lj', 'lj'), ('Nj', 'nj'), ('ǎ', 'ǎ'), ('ǐ', 'ǐ'), + ('ǒ', 'ǒ'), ('ǔ', 'ǔ'), ('ǖ', 'ǖ'), ('ǘ', 'ǘ'), ('ǚ', 'ǚ'), + ('ǜ', 'ǝ'), ('ǟ', 'ǟ'), ('ǡ', 'ǡ'), ('ǣ', 'ǣ'), ('ǥ', 'ǥ'), + ('ǧ', 'ǧ'), ('ǩ', 'ǩ'), ('ǫ', 'ǫ'), ('ǭ', 'ǭ'), ('ǯ', 'ǰ'), + ('Dz', 'dz'), ('ǵ', 'ǵ'), ('ǹ', 'ǹ'), ('ǻ', 'ǻ'), ('ǽ', 'ǽ'), + ('ǿ', 'ǿ'), ('ȁ', 'ȁ'), ('ȃ', 'ȃ'), ('ȅ', 'ȅ'), ('ȇ', 'ȇ'), + ('ȉ', 'ȉ'), ('ȋ', 'ȋ'), ('ȍ', 'ȍ'), ('ȏ', 'ȏ'), ('ȑ', 'ȑ'), + ('ȓ', 'ȓ'), ('ȕ', 'ȕ'), ('ȗ', 'ȗ'), ('ș', 'ș'), ('ț', 'ț'), + ('ȝ', 'ȝ'), ('ȟ', 'ȟ'), ('ȣ', 'ȣ'), ('ȥ', 'ȥ'), ('ȧ', 'ȧ'), + ('ȩ', 'ȩ'), ('ȫ', 'ȫ'), ('ȭ', 'ȭ'), ('ȯ', 'ȯ'), ('ȱ', 'ȱ'), + ('ȳ', 'ȳ'), ('ȼ', 'ȼ'), ('ȿ', 'ɀ'), ('ɂ', 'ɂ'), ('ɇ', 'ɇ'), + ('ɉ', 'ɉ'), ('ɋ', 'ɋ'), ('ɍ', 'ɍ'), ('ɏ', 'ɔ'), ('ɖ', 'ɗ'), + ('ə', 'ə'), ('ɛ', 'ɜ'), ('ɠ', 'ɡ'), ('ɣ', 'ɣ'), ('ɥ', 'ɦ'), + ('ɨ', 'ɬ'), ('ɯ', 'ɯ'), ('ɱ', 'ɲ'), ('ɵ', 'ɵ'), ('ɽ', 'ɽ'), + ('ʀ', 'ʀ'), ('ʃ', 'ʃ'), ('ʇ', 'ʌ'), ('ʒ', 'ʒ'), ('ʝ', 'ʞ'), + ('ͅ', 'ͅ'), ('ͱ', 'ͱ'), ('ͳ', 'ͳ'), ('ͷ', 'ͷ'), ('ͻ', 'ͽ'), + ('ΐ', 'ΐ'), ('ά', 'ώ'), ('ϐ', 'ϑ'), ('ϕ', 'ϗ'), ('ϙ', 'ϙ'), + ('ϛ', 'ϛ'), ('ϝ', 'ϝ'), ('ϟ', 'ϟ'), ('ϡ', 'ϡ'), ('ϣ', 'ϣ'), + ('ϥ', 'ϥ'), ('ϧ', 'ϧ'), ('ϩ', 'ϩ'), ('ϫ', 'ϫ'), ('ϭ', 'ϭ'), + ('ϯ', 'ϳ'), ('ϵ', 'ϵ'), ('ϸ', 'ϸ'), ('ϻ', 'ϻ'), ('а', 'џ'), + ('ѡ', 'ѡ'), ('ѣ', 'ѣ'), ('ѥ', 'ѥ'), ('ѧ', 'ѧ'), ('ѩ', 'ѩ'), + ('ѫ', 'ѫ'), ('ѭ', 'ѭ'), ('ѯ', 'ѯ'), ('ѱ', 'ѱ'), ('ѳ', 'ѳ'), + ('ѵ', 'ѵ'), ('ѷ', 'ѷ'), ('ѹ', 'ѹ'), ('ѻ', 'ѻ'), ('ѽ', 'ѽ'), + ('ѿ', 'ѿ'), ('ҁ', 'ҁ'), ('ҋ', 'ҋ'), ('ҍ', 'ҍ'), ('ҏ', 'ҏ'), + ('ґ', 'ґ'), ('ғ', 'ғ'), ('ҕ', 'ҕ'), ('җ', 'җ'), ('ҙ', 'ҙ'), + ('қ', 'қ'), ('ҝ', 'ҝ'), ('ҟ', 'ҟ'), ('ҡ', 'ҡ'), ('ң', 'ң'), + ('ҥ', 'ҥ'), ('ҧ', 'ҧ'), ('ҩ', 'ҩ'), ('ҫ', 'ҫ'), ('ҭ', 'ҭ'), + ('ү', 'ү'), ('ұ', 'ұ'), ('ҳ', 'ҳ'), ('ҵ', 'ҵ'), ('ҷ', 'ҷ'), + ('ҹ', 'ҹ'), ('һ', 'һ'), ('ҽ', 'ҽ'), ('ҿ', 'ҿ'), ('ӂ', 'ӂ'), + ('ӄ', 'ӄ'), ('ӆ', 'ӆ'), ('ӈ', 'ӈ'), ('ӊ', 'ӊ'), ('ӌ', 'ӌ'), + ('ӎ', 'ӏ'), ('ӑ', 'ӑ'), ('ӓ', 'ӓ'), ('ӕ', 'ӕ'), ('ӗ', 'ӗ'), + ('ә', 'ә'), ('ӛ', 'ӛ'), ('ӝ', 'ӝ'), ('ӟ', 'ӟ'), ('ӡ', 'ӡ'), + ('ӣ', 'ӣ'), ('ӥ', 'ӥ'), ('ӧ', 'ӧ'), ('ө', 'ө'), ('ӫ', 'ӫ'), + ('ӭ', 'ӭ'), ('ӯ', 'ӯ'), ('ӱ', 'ӱ'), ('ӳ', 'ӳ'), ('ӵ', 'ӵ'), + ('ӷ', 'ӷ'), ('ӹ', 'ӹ'), ('ӻ', 'ӻ'), ('ӽ', 'ӽ'), ('ӿ', 'ӿ'), + ('ԁ', 'ԁ'), ('ԃ', 'ԃ'), ('ԅ', 'ԅ'), ('ԇ', 'ԇ'), ('ԉ', 'ԉ'), + ('ԋ', 'ԋ'), ('ԍ', 'ԍ'), ('ԏ', 'ԏ'), ('ԑ', 'ԑ'), ('ԓ', 'ԓ'), + ('ԕ', 'ԕ'), ('ԗ', 'ԗ'), ('ԙ', 'ԙ'), ('ԛ', 'ԛ'), ('ԝ', 'ԝ'), + ('ԟ', 'ԟ'), ('ԡ', 'ԡ'), ('ԣ', 'ԣ'), ('ԥ', 'ԥ'), ('ԧ', 'ԧ'), + ('ԩ', 'ԩ'), ('ԫ', 'ԫ'), ('ԭ', 'ԭ'), ('ԯ', 'ԯ'), ('ա', 'և'), + ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᵹ', 'ᵹ'), ('ᵽ', 'ᵽ'), + ('ḁ', 'ḁ'), ('ḃ', 'ḃ'), ('ḅ', 'ḅ'), ('ḇ', 'ḇ'), + ('ḉ', 'ḉ'), ('ḋ', 'ḋ'), ('ḍ', 'ḍ'), ('ḏ', 'ḏ'), + ('ḑ', 'ḑ'), ('ḓ', 'ḓ'), ('ḕ', 'ḕ'), ('ḗ', 'ḗ'), + ('ḙ', 'ḙ'), ('ḛ', 'ḛ'), ('ḝ', 'ḝ'), ('ḟ', 'ḟ'), + ('ḡ', 'ḡ'), ('ḣ', 'ḣ'), ('ḥ', 'ḥ'), ('ḧ', 'ḧ'), + ('ḩ', 'ḩ'), ('ḫ', 'ḫ'), ('ḭ', 'ḭ'), ('ḯ', 'ḯ'), + ('ḱ', 'ḱ'), ('ḳ', 'ḳ'), ('ḵ', 'ḵ'), ('ḷ', 'ḷ'), + ('ḹ', 'ḹ'), ('ḻ', 'ḻ'), ('ḽ', 'ḽ'), ('ḿ', 'ḿ'), + ('ṁ', 'ṁ'), ('ṃ', 'ṃ'), ('ṅ', 'ṅ'), ('ṇ', 'ṇ'), + ('ṉ', 'ṉ'), ('ṋ', 'ṋ'), ('ṍ', 'ṍ'), ('ṏ', 'ṏ'), + ('ṑ', 'ṑ'), ('ṓ', 'ṓ'), ('ṕ', 'ṕ'), ('ṗ', 'ṗ'), + ('ṙ', 'ṙ'), ('ṛ', 'ṛ'), ('ṝ', 'ṝ'), ('ṟ', 'ṟ'), + ('ṡ', 'ṡ'), ('ṣ', 'ṣ'), ('ṥ', 'ṥ'), ('ṧ', 'ṧ'), + ('ṩ', 'ṩ'), ('ṫ', 'ṫ'), ('ṭ', 'ṭ'), ('ṯ', 'ṯ'), + ('ṱ', 'ṱ'), ('ṳ', 'ṳ'), ('ṵ', 'ṵ'), ('ṷ', 'ṷ'), + ('ṹ', 'ṹ'), ('ṻ', 'ṻ'), ('ṽ', 'ṽ'), ('ṿ', 'ṿ'), + ('ẁ', 'ẁ'), ('ẃ', 'ẃ'), ('ẅ', 'ẅ'), ('ẇ', 'ẇ'), + ('ẉ', 'ẉ'), ('ẋ', 'ẋ'), ('ẍ', 'ẍ'), ('ẏ', 'ẏ'), + ('ẑ', 'ẑ'), ('ẓ', 'ẓ'), ('ẕ', 'ẛ'), ('ạ', 'ạ'), + ('ả', 'ả'), ('ấ', 'ấ'), ('ầ', 'ầ'), ('ẩ', 'ẩ'), + ('ẫ', 'ẫ'), ('ậ', 'ậ'), ('ắ', 'ắ'), ('ằ', 'ằ'), + ('ẳ', 'ẳ'), ('ẵ', 'ẵ'), ('ặ', 'ặ'), ('ẹ', 'ẹ'), + ('ẻ', 'ẻ'), ('ẽ', 'ẽ'), ('ế', 'ế'), ('ề', 'ề'), + ('ể', 'ể'), ('ễ', 'ễ'), ('ệ', 'ệ'), ('ỉ', 'ỉ'), + ('ị', 'ị'), ('ọ', 'ọ'), ('ỏ', 'ỏ'), ('ố', 'ố'), + ('ồ', 'ồ'), ('ổ', 'ổ'), ('ỗ', 'ỗ'), ('ộ', 'ộ'), + ('ớ', 'ớ'), ('ờ', 'ờ'), ('ở', 'ở'), ('ỡ', 'ỡ'), + ('ợ', 'ợ'), ('ụ', 'ụ'), ('ủ', 'ủ'), ('ứ', 'ứ'), + ('ừ', 'ừ'), ('ử', 'ử'), ('ữ', 'ữ'), ('ự', 'ự'), + ('ỳ', 'ỳ'), ('ỵ', 'ỵ'), ('ỷ', 'ỷ'), ('ỹ', 'ỹ'), + ('ỻ', 'ỻ'), ('ỽ', 'ỽ'), ('ỿ', 'ἇ'), ('ἐ', 'ἕ'), + ('ἠ', 'ἧ'), ('ἰ', 'ἷ'), ('ὀ', 'ὅ'), ('ὐ', 'ὗ'), + ('ὠ', 'ὧ'), ('ὰ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾷ'), + ('ᾼ', 'ᾼ'), ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῇ'), + ('ῌ', 'ῌ'), ('ῐ', 'ΐ'), ('ῖ', 'ῗ'), ('ῠ', 'ῧ'), + ('ῲ', 'ῴ'), ('ῶ', 'ῷ'), ('ῼ', 'ῼ'), ('ⅎ', 'ⅎ'), + ('ⅰ', 'ⅿ'), ('ↄ', 'ↄ'), ('ⓐ', 'ⓩ'), ('ⰰ', 'ⱞ'), + ('ⱡ', 'ⱡ'), ('ⱥ', 'ⱦ'), ('ⱨ', 'ⱨ'), ('ⱪ', 'ⱪ'), + ('ⱬ', 'ⱬ'), ('ⱳ', 'ⱳ'), ('ⱶ', 'ⱶ'), ('ⲁ', 'ⲁ'), + ('ⲃ', 'ⲃ'), ('ⲅ', 'ⲅ'), ('ⲇ', 'ⲇ'), ('ⲉ', 'ⲉ'), + ('ⲋ', 'ⲋ'), ('ⲍ', 'ⲍ'), ('ⲏ', 'ⲏ'), ('ⲑ', 'ⲑ'), + ('ⲓ', 'ⲓ'), ('ⲕ', 'ⲕ'), ('ⲗ', 'ⲗ'), ('ⲙ', 'ⲙ'), + ('ⲛ', 'ⲛ'), ('ⲝ', 'ⲝ'), ('ⲟ', 'ⲟ'), ('ⲡ', 'ⲡ'), + ('ⲣ', 'ⲣ'), ('ⲥ', 'ⲥ'), ('ⲧ', 'ⲧ'), ('ⲩ', 'ⲩ'), + ('ⲫ', 'ⲫ'), ('ⲭ', 'ⲭ'), ('ⲯ', 'ⲯ'), ('ⲱ', 'ⲱ'), + ('ⲳ', 'ⲳ'), ('ⲵ', 'ⲵ'), ('ⲷ', 'ⲷ'), ('ⲹ', 'ⲹ'), + ('ⲻ', 'ⲻ'), ('ⲽ', 'ⲽ'), ('ⲿ', 'ⲿ'), ('ⳁ', 'ⳁ'), + ('ⳃ', 'ⳃ'), ('ⳅ', 'ⳅ'), ('ⳇ', 'ⳇ'), ('ⳉ', 'ⳉ'), + ('ⳋ', 'ⳋ'), ('ⳍ', 'ⳍ'), ('ⳏ', 'ⳏ'), ('ⳑ', 'ⳑ'), + ('ⳓ', 'ⳓ'), ('ⳕ', 'ⳕ'), ('ⳗ', 'ⳗ'), ('ⳙ', 'ⳙ'), + ('ⳛ', 'ⳛ'), ('ⳝ', 'ⳝ'), ('ⳟ', 'ⳟ'), ('ⳡ', 'ⳡ'), + ('ⳣ', 'ⳣ'), ('ⳬ', 'ⳬ'), ('ⳮ', 'ⳮ'), ('ⳳ', 'ⳳ'), + ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ꙁ', 'ꙁ'), + ('ꙃ', 'ꙃ'), ('ꙅ', 'ꙅ'), ('ꙇ', 'ꙇ'), ('ꙉ', 'ꙉ'), + ('ꙋ', 'ꙋ'), ('ꙍ', 'ꙍ'), ('ꙏ', 'ꙏ'), ('ꙑ', 'ꙑ'), + ('ꙓ', 'ꙓ'), ('ꙕ', 'ꙕ'), ('ꙗ', 'ꙗ'), ('ꙙ', 'ꙙ'), + ('ꙛ', 'ꙛ'), ('ꙝ', 'ꙝ'), ('ꙟ', 'ꙟ'), ('ꙡ', 'ꙡ'), + ('ꙣ', 'ꙣ'), ('ꙥ', 'ꙥ'), ('ꙧ', 'ꙧ'), ('ꙩ', 'ꙩ'), + ('ꙫ', 'ꙫ'), ('ꙭ', 'ꙭ'), ('ꚁ', 'ꚁ'), ('ꚃ', 'ꚃ'), + ('ꚅ', 'ꚅ'), ('ꚇ', 'ꚇ'), ('ꚉ', 'ꚉ'), ('ꚋ', 'ꚋ'), + ('ꚍ', 'ꚍ'), ('ꚏ', 'ꚏ'), ('ꚑ', 'ꚑ'), ('ꚓ', 'ꚓ'), + ('ꚕ', 'ꚕ'), ('ꚗ', 'ꚗ'), ('ꚙ', 'ꚙ'), ('ꚛ', 'ꚛ'), + ('ꜣ', 'ꜣ'), ('ꜥ', 'ꜥ'), ('ꜧ', 'ꜧ'), ('ꜩ', 'ꜩ'), + ('ꜫ', 'ꜫ'), ('ꜭ', 'ꜭ'), ('ꜯ', 'ꜯ'), ('ꜳ', 'ꜳ'), + ('ꜵ', 'ꜵ'), ('ꜷ', 'ꜷ'), ('ꜹ', 'ꜹ'), ('ꜻ', 'ꜻ'), + ('ꜽ', 'ꜽ'), ('ꜿ', 'ꜿ'), ('ꝁ', 'ꝁ'), ('ꝃ', 'ꝃ'), + ('ꝅ', 'ꝅ'), ('ꝇ', 'ꝇ'), ('ꝉ', 'ꝉ'), ('ꝋ', 'ꝋ'), + ('ꝍ', 'ꝍ'), ('ꝏ', 'ꝏ'), ('ꝑ', 'ꝑ'), ('ꝓ', 'ꝓ'), + ('ꝕ', 'ꝕ'), ('ꝗ', 'ꝗ'), ('ꝙ', 'ꝙ'), ('ꝛ', 'ꝛ'), + ('ꝝ', 'ꝝ'), ('ꝟ', 'ꝟ'), ('ꝡ', 'ꝡ'), ('ꝣ', 'ꝣ'), + ('ꝥ', 'ꝥ'), ('ꝧ', 'ꝧ'), ('ꝩ', 'ꝩ'), ('ꝫ', 'ꝫ'), + ('ꝭ', 'ꝭ'), ('ꝯ', 'ꝯ'), ('ꝺ', 'ꝺ'), ('ꝼ', 'ꝼ'), + ('ꝿ', 'ꝿ'), ('ꞁ', 'ꞁ'), ('ꞃ', 'ꞃ'), ('ꞅ', 'ꞅ'), + ('ꞇ', 'ꞇ'), ('ꞌ', 'ꞌ'), ('ꞑ', 'ꞑ'), ('ꞓ', 'ꞓ'), + ('ꞗ', 'ꞗ'), ('ꞙ', 'ꞙ'), ('ꞛ', 'ꞛ'), ('ꞝ', 'ꞝ'), + ('ꞟ', 'ꞟ'), ('ꞡ', 'ꞡ'), ('ꞣ', 'ꞣ'), ('ꞥ', 'ꞥ'), + ('ꞧ', 'ꞧ'), ('ꞩ', 'ꞩ'), ('ꞵ', 'ꞵ'), ('ꞷ', 'ꞷ'), + ('ꭓ', 'ꭓ'), ('ꭰ', 'ꮿ'), ('ff', 'st'), ('ﬓ', 'ﬗ'), + ('a', 'z'), ('𐐨', '𐑏'), ('𐓘', '𐓻'), ('𐳀', '𐳲'), + ('𑣀', '𑣟'), ('𞤢', '𞥃'), +]; + +pub const DASH: &'static [(char, char)] = &[ + ('-', '-'), ('֊', '֊'), ('־', '־'), ('᐀', '᐀'), ('᠆', '᠆'), + ('‐', '―'), ('⁓', '⁓'), ('⁻', '⁻'), ('₋', '₋'), + ('−', '−'), ('⸗', '⸗'), ('⸚', '⸚'), ('⸺', '⸻'), + ('⹀', '⹀'), ('〜', '〜'), ('〰', '〰'), ('゠', '゠'), + ('︱', '︲'), ('﹘', '﹘'), ('﹣', '﹣'), ('-', '-'), +]; + +pub const DEFAULT_IGNORABLE_CODE_POINT: &'static [(char, char)] = &[ + ('\u{ad}', '\u{ad}'), ('͏', '͏'), ('\u{61c}', '\u{61c}'), ('ᅟ', 'ᅠ'), + ('឴', '឵'), ('᠋', '\u{180e}'), ('\u{200b}', '\u{200f}'), + ('\u{202a}', '\u{202e}'), ('\u{2060}', '\u{206f}'), ('ㅤ', 'ㅤ'), + ('︀', '️'), ('\u{feff}', '\u{feff}'), ('ᅠ', 'ᅠ'), + ('\u{fff0}', '\u{fff8}'), ('\u{1bca0}', '\u{1bca3}'), + ('\u{1d173}', '\u{1d17a}'), ('\u{e0000}', '\u{e0fff}'), +]; + +pub const DEPRECATED: &'static [(char, char)] = &[ + ('ʼn', 'ʼn'), ('ٳ', 'ٳ'), ('ཷ', 'ཷ'), ('ཹ', 'ཹ'), ('ឣ', 'ឤ'), + ('\u{206a}', '\u{206f}'), ('〈', '〉'), ('\u{e0001}', '\u{e0001}'), +]; + +pub const DIACRITIC: &'static [(char, char)] = &[ + ('^', '^'), ('`', '`'), ('¨', '¨'), ('¯', '¯'), ('´', '´'), + ('·', '¸'), ('ʰ', '͎'), ('͐', '͗'), ('͝', '͢'), ('ʹ', '͵'), + ('ͺ', 'ͺ'), ('΄', '΅'), ('҃', '҇'), ('ՙ', 'ՙ'), ('֑', '֡'), + ('֣', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), ('ׄ', 'ׄ'), ('ً', 'ْ'), + ('ٗ', '٘'), ('۟', '۠'), ('ۥ', 'ۦ'), ('۪', '۬'), ('ܰ', '݊'), + ('ަ', 'ް'), ('߫', 'ߵ'), ('࠘', '࠙'), ('ࣣ', 'ࣾ'), ('़', '़'), + ('्', '्'), ('॑', '॔'), ('ॱ', 'ॱ'), ('়', '়'), + ('্', '্'), ('਼', '਼'), ('੍', '੍'), ('઼', '઼'), + ('્', '્'), ('૽', '૿'), ('଼', '଼'), ('୍', '୍'), + ('்', '்'), ('్', '్'), ('಼', '಼'), ('್', '್'), + ('഻', '഼'), ('്', '്'), ('්', '්'), ('็', '์'), + ('๎', '๎'), ('່', '໌'), ('༘', '༙'), ('༵', '༵'), + ('༷', '༷'), ('༹', '༹'), ('༾', '༿'), ('ྂ', '྄'), + ('྆', '྇'), ('࿆', '࿆'), ('့', '့'), ('္', '်'), + ('ႇ', 'ႍ'), ('ႏ', 'ႏ'), ('ႚ', 'ႛ'), ('៉', '៓'), + ('៝', '៝'), ('᤹', '᤻'), ('᩵', '᩼'), ('᩿', '᩿'), + ('᪰', '᪽'), ('᬴', '᬴'), ('᭄', '᭄'), ('᭫', '᭳'), + ('᮪', '᮫'), ('ᰶ', '᰷'), ('ᱸ', 'ᱽ'), ('᳐', '᳨'), + ('᳭', '᳭'), ('᳴', '᳴'), ('᳷', '᳹'), ('ᴬ', 'ᵪ'), + ('᷄', '᷏'), ('᷵', '᷹'), ('᷽', '᷿'), ('᾽', '᾽'), + ('᾿', '῁'), ('῍', '῏'), ('῝', '῟'), ('῭', '`'), + ('´', '῾'), ('⳯', '⳱'), ('ⸯ', 'ⸯ'), ('〪', '〯'), + ('゙', '゜'), ('ー', 'ー'), ('꙯', '꙯'), ('꙼', '꙽'), + ('ꙿ', 'ꙿ'), ('ꚜ', 'ꚝ'), ('꛰', '꛱'), ('ꜗ', '꜡'), + ('ꞈ', 'ꞈ'), ('ꟸ', 'ꟹ'), ('꣄', '꣄'), ('꣠', '꣱'), + ('꤫', '꤮'), ('꥓', '꥓'), ('꦳', '꦳'), ('꧀', '꧀'), + ('ꧥ', 'ꧥ'), ('ꩻ', 'ꩽ'), ('꪿', 'ꫂ'), ('꫶', '꫶'), + ('꭛', 'ꭟ'), ('꯬', '꯭'), ('ﬞ', 'ﬞ'), ('︠', '︯'), + ('^', '^'), ('`', '`'), ('ー', 'ー'), ('゙', '゚'), + (' ̄', ' ̄'), ('𐋠', '𐋠'), ('𐫥', '𐫦'), ('𑂹', '𑂺'), + ('𑄳', '𑄴'), ('𑅳', '𑅳'), ('𑇀', '𑇀'), ('𑇊', '𑇌'), + ('𑈵', '𑈶'), ('𑋩', '𑋪'), ('𑌼', '𑌼'), ('𑍍', '𑍍'), + ('𑍦', '𑍬'), ('𑍰', '𑍴'), ('𑑂', '𑑂'), ('𑑆', '𑑆'), + ('𑓂', '𑓃'), ('𑖿', '𑗀'), ('𑘿', '𑘿'), ('𑚶', '𑚷'), + ('𑜫', '𑜫'), ('𑨴', '𑨴'), ('𑩇', '𑩇'), ('𑪙', '𑪙'), + ('𑰿', '𑰿'), ('𑵂', '𑵂'), ('𑵄', '𑵅'), ('𖫰', '𖫴'), + ('𖾏', '𖾟'), ('𝅧', '𝅩'), ('𝅭', '𝅲'), ('𝅻', '𝆂'), + ('𝆅', '𝆋'), ('𝆪', '𝆭'), ('𞣐', '𞣖'), ('𞥄', '𞥆'), + ('𞥈', '𞥊'), +]; + +pub const EXTENDER: &'static [(char, char)] = &[ + ('·', '·'), ('ː', 'ˑ'), ('ـ', 'ـ'), ('ߺ', 'ߺ'), ('ๆ', 'ๆ'), + ('ໆ', 'ໆ'), ('᠊', '᠊'), ('ᡃ', 'ᡃ'), ('ᪧ', 'ᪧ'), + ('ᰶ', 'ᰶ'), ('ᱻ', 'ᱻ'), ('々', '々'), ('〱', '〵'), + ('ゝ', 'ゞ'), ('ー', 'ヾ'), ('ꀕ', 'ꀕ'), ('ꘌ', 'ꘌ'), + ('ꧏ', 'ꧏ'), ('ꧦ', 'ꧦ'), ('ꩰ', 'ꩰ'), ('ꫝ', 'ꫝ'), + ('ꫳ', 'ꫴ'), ('ー', 'ー'), ('𑍝', '𑍝'), ('𑗆', '𑗈'), + ('𑪘', '𑪘'), ('𖭂', '𖭃'), ('𖿠', '𖿡'), ('𞥄', '𞥆'), +]; + +pub const GRAPHEME_BASE: &'static [(char, char)] = &[ + (' ', '~'), ('\u{a0}', '¬'), ('®', '˿'), ('Ͱ', 'ͷ'), ('ͺ', 'Ϳ'), + ('΄', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), ('Σ', '҂'), ('Ҋ', 'ԯ'), + ('Ա', 'Ֆ'), ('ՙ', '՟'), ('ա', 'և'), ('։', '֊'), ('֍', '֏'), + ('־', '־'), ('׀', '׀'), ('׃', '׃'), ('׆', '׆'), ('א', 'ת'), + ('װ', '״'), ('؆', '؏'), ('؛', '؛'), ('؞', 'ي'), ('٠', 'ٯ'), + ('ٱ', 'ە'), ('۞', '۞'), ('ۥ', 'ۦ'), ('۩', '۩'), ('ۮ', '܍'), + ('ܐ', 'ܐ'), ('ܒ', 'ܯ'), ('ݍ', 'ޥ'), ('ޱ', 'ޱ'), ('߀', 'ߪ'), + ('ߴ', 'ߺ'), ('ࠀ', 'ࠕ'), ('ࠚ', 'ࠚ'), ('ࠤ', 'ࠤ'), + ('ࠨ', 'ࠨ'), ('࠰', '࠾'), ('ࡀ', 'ࡘ'), ('࡞', '࡞'), + ('ࡠ', 'ࡪ'), ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ः', 'ह'), + ('ऻ', 'ऻ'), ('ऽ', 'ी'), ('ॉ', 'ौ'), ('ॎ', 'ॐ'), + ('क़', 'ॡ'), ('।', 'ঀ'), ('ং', 'ঃ'), ('অ', 'ঌ'), + ('এ', 'ঐ'), ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), + ('শ', 'হ'), ('ঽ', 'ঽ'), ('ি', 'ী'), ('ে', 'ৈ'), + ('ো', 'ৌ'), ('ৎ', 'ৎ'), ('ড়', 'ঢ়'), ('য়', 'ৡ'), + ('০', '৽'), ('ਃ', 'ਃ'), ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), + ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), + ('ਸ', 'ਹ'), ('ਾ', 'ੀ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), + ('੦', '੯'), ('ੲ', 'ੴ'), ('ઃ', 'ઃ'), ('અ', 'ઍ'), + ('એ', 'ઑ'), ('ઓ', 'ન'), ('પ', 'ર'), ('લ', 'ળ'), + ('વ', 'હ'), ('ઽ', 'ી'), ('ૉ', 'ૉ'), ('ો', 'ૌ'), + ('ૐ', 'ૐ'), ('ૠ', 'ૡ'), ('૦', '૱'), ('ૹ', 'ૹ'), + ('ଂ', 'ଃ'), ('ଅ', 'ଌ'), ('ଏ', 'ଐ'), ('ଓ', 'ନ'), + ('ପ', 'ର'), ('ଲ', 'ଳ'), ('ଵ', 'ହ'), ('ଽ', 'ଽ'), + ('ୀ', 'ୀ'), ('େ', 'ୈ'), ('ୋ', 'ୌ'), ('ଡ଼', 'ଢ଼'), + ('ୟ', 'ୡ'), ('୦', '୷'), ('ஃ', 'ஃ'), ('அ', 'ஊ'), + ('எ', 'ஐ'), ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), + ('ஞ', 'ட'), ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), + ('ி', 'ி'), ('ு', 'ூ'), ('ெ', 'ை'), ('ொ', 'ௌ'), + ('ௐ', 'ௐ'), ('௦', '௺'), ('ఁ', 'ః'), ('అ', 'ఌ'), + ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), ('ఽ', 'ఽ'), + ('ు', 'ౄ'), ('ౘ', 'ౚ'), ('ౠ', 'ౡ'), ('౦', '౯'), + ('౸', 'ಀ'), ('ಂ', 'ಃ'), ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), + ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), ('ಽ', 'ಾ'), + ('ೀ', 'ು'), ('ೃ', 'ೄ'), ('ೇ', 'ೈ'), ('ೊ', 'ೋ'), + ('ೞ', 'ೞ'), ('ೠ', 'ೡ'), ('೦', '೯'), ('ೱ', 'ೲ'), + ('ം', 'ഃ'), ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ഺ'), + ('ഽ', 'ഽ'), ('ി', 'ീ'), ('െ', 'ൈ'), ('ൊ', 'ൌ'), + ('ൎ', '൏'), ('ൔ', 'ൖ'), ('൘', 'ൡ'), ('൦', 'ൿ'), + ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('ැ', 'ෑ'), ('ෘ', 'ෞ'), + ('෦', '෯'), ('ෲ', '෴'), ('ก', 'ะ'), ('า', 'ำ'), + ('฿', 'ๆ'), ('๏', '๛'), ('ກ', 'ຂ'), ('ຄ', 'ຄ'), + ('ງ', 'ຈ'), ('ຊ', 'ຊ'), ('ຍ', 'ຍ'), ('ດ', 'ທ'), + ('ນ', 'ຟ'), ('ມ', 'ຣ'), ('ລ', 'ລ'), ('ວ', 'ວ'), + ('ສ', 'ຫ'), ('ອ', 'ະ'), ('າ', 'ຳ'), ('ຽ', 'ຽ'), + ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('໐', '໙'), ('ໜ', 'ໟ'), + ('ༀ', '༗'), ('༚', '༴'), ('༶', '༶'), ('༸', '༸'), + ('༺', 'ཇ'), ('ཉ', 'ཬ'), ('ཿ', 'ཿ'), ('྅', '྅'), + ('ྈ', 'ྌ'), ('྾', '࿅'), ('࿇', '࿌'), ('࿎', '࿚'), + ('က', 'ာ'), ('ေ', 'ေ'), ('း', 'း'), ('ျ', 'ြ'), + ('ဿ', 'ၗ'), ('ၚ', 'ၝ'), ('ၡ', 'ၰ'), ('ၵ', 'ႁ'), + ('ႃ', 'ႄ'), ('ႇ', 'ႌ'), ('ႎ', 'ႜ'), ('႞', 'Ⴥ'), + ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ቈ'), ('ቊ', 'ቍ'), + ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), ('በ', 'ኈ'), + ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), + ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), ('ዘ', 'ጐ'), + ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('፠', '፼'), ('ᎀ', '᎙'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('᐀', '᚜'), ('ᚠ', 'ᛸ'), + ('ᜀ', 'ᜌ'), ('ᜎ', 'ᜑ'), ('ᜠ', 'ᜱ'), ('᜵', '᜶'), + ('ᝀ', 'ᝑ'), ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), ('ក', 'ឳ'), + ('ា', 'ា'), ('ើ', 'ៅ'), ('ះ', 'ៈ'), ('។', 'ៜ'), + ('០', '៩'), ('៰', '៹'), ('᠀', '᠊'), ('᠐', '᠙'), + ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢄ'), ('ᢇ', 'ᢨ'), ('ᢪ', 'ᢪ'), + ('ᢰ', 'ᣵ'), ('ᤀ', 'ᤞ'), ('ᤣ', 'ᤦ'), ('ᤩ', 'ᤫ'), + ('ᤰ', 'ᤱ'), ('ᤳ', 'ᤸ'), ('᥀', '᥀'), ('᥄', 'ᥭ'), + ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), ('᧐', '᧚'), + ('᧞', 'ᨖ'), ('ᨙ', 'ᨚ'), ('᨞', 'ᩕ'), ('ᩗ', 'ᩗ'), + ('ᩡ', 'ᩡ'), ('ᩣ', 'ᩤ'), ('ᩭ', 'ᩲ'), ('᪀', '᪉'), + ('᪐', '᪙'), ('᪠', '᪭'), ('ᬄ', 'ᬳ'), ('ᬵ', 'ᬵ'), + ('ᬻ', 'ᬻ'), ('ᬽ', 'ᭁ'), ('ᭃ', 'ᭋ'), ('᭐', '᭪'), + ('᭴', '᭼'), ('ᮂ', 'ᮡ'), ('ᮦ', 'ᮧ'), ('᮪', '᮪'), + ('ᮮ', 'ᯥ'), ('ᯧ', 'ᯧ'), ('ᯪ', 'ᯬ'), ('ᯮ', 'ᯮ'), + ('᯲', '᯳'), ('᯼', 'ᰫ'), ('ᰴ', 'ᰵ'), ('᰻', '᱉'), + ('ᱍ', 'ᲈ'), ('᳀', '᳇'), ('᳓', '᳓'), ('᳡', '᳡'), + ('ᳩ', 'ᳬ'), ('ᳮ', 'ᳳ'), ('ᳵ', '᳷'), ('ᴀ', 'ᶿ'), + ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), + ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), + ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ῄ'), ('ῆ', 'ΐ'), + ('ῖ', 'Ί'), ('῝', '`'), ('ῲ', 'ῴ'), ('ῶ', '῾'), + ('\u{2000}', '\u{200a}'), ('‐', '‧'), ('\u{202f}', '\u{205f}'), + ('⁰', 'ⁱ'), ('⁴', '₎'), ('ₐ', 'ₜ'), ('₠', '₿'), + ('℀', '↋'), ('←', '␦'), ('⑀', '⑊'), ('①', '⭳'), + ('⭶', '⮕'), ('⮘', '⮹'), ('⮽', '⯈'), ('⯊', '⯒'), + ('⯬', '⯯'), ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳮ'), + ('Ⳳ', 'ⳳ'), ('⳹', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), + ('ⴰ', 'ⵧ'), ('ⵯ', '⵰'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), + ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), + ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('⸀', '⹉'), + ('⺀', '⺙'), ('⺛', '⻳'), ('⼀', '⿕'), ('⿰', '⿻'), + ('\u{3000}', '〩'), ('〰', '〿'), ('ぁ', 'ゖ'), ('゛', 'ヿ'), + ('ㄅ', 'ㄮ'), ('ㄱ', 'ㆎ'), ('㆐', 'ㆺ'), ('㇀', '㇣'), + ('ㇰ', '㈞'), ('㈠', '㋾'), ('㌀', '䶵'), ('䷀', '鿪'), + ('ꀀ', 'ꒌ'), ('꒐', '꓆'), ('ꓐ', 'ꘫ'), ('Ꙁ', 'ꙮ'), + ('꙳', '꙳'), ('꙾', 'ꚝ'), ('ꚠ', 'ꛯ'), ('꛲', '꛷'), + ('꜀', 'Ɪ'), ('Ʞ', 'ꞷ'), ('ꟷ', 'ꠁ'), ('ꠃ', 'ꠅ'), + ('ꠇ', 'ꠊ'), ('ꠌ', 'ꠤ'), ('ꠧ', '꠫'), ('꠰', '꠹'), + ('ꡀ', '꡷'), ('ꢀ', 'ꣃ'), ('꣎', '꣙'), ('ꣲ', 'ꣽ'), + ('꤀', 'ꤥ'), ('꤮', 'ꥆ'), ('ꥒ', '꥓'), ('꥟', 'ꥼ'), + ('ꦃ', 'ꦲ'), ('ꦴ', 'ꦵ'), ('ꦺ', 'ꦻ'), ('ꦽ', '꧍'), + ('ꧏ', '꧙'), ('꧞', 'ꧤ'), ('ꧦ', 'ꧾ'), ('ꨀ', 'ꨨ'), + ('ꨯ', 'ꨰ'), ('ꨳ', 'ꨴ'), ('ꩀ', 'ꩂ'), ('ꩄ', 'ꩋ'), + ('ꩍ', 'ꩍ'), ('꩐', '꩙'), ('꩜', 'ꩻ'), ('ꩽ', 'ꪯ'), + ('ꪱ', 'ꪱ'), ('ꪵ', 'ꪶ'), ('ꪹ', 'ꪽ'), ('ꫀ', 'ꫀ'), + ('ꫂ', 'ꫂ'), ('ꫛ', 'ꫫ'), ('ꫮ', 'ꫵ'), ('ꬁ', 'ꬆ'), + ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), + ('ꬰ', 'ꭥ'), ('ꭰ', 'ꯤ'), ('ꯦ', 'ꯧ'), ('ꯩ', '꯬'), + ('꯰', '꯹'), ('가', '힣'), ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), + ('豈', '舘'), ('並', '龎'), ('ff', 'st'), ('ﬓ', 'ﬗ'), + ('יִ', 'יִ'), ('ײַ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), + ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', '﯁'), ('ﯓ', '﴿'), + ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', '﷽'), ('︐', '︙'), + ('︰', '﹒'), ('﹔', '﹦'), ('﹨', '﹫'), ('ﹰ', 'ﹴ'), + ('ﹶ', 'ﻼ'), ('!', 'ン'), ('ᅠ', 'ᄒ'), ('ᅡ', 'ᅦ'), + ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), ('¢', '₩'), + ('│', '○'), ('', '�'), ('𐀀', '𐀋'), ('𐀍', '𐀦'), + ('𐀨', '𐀺'), ('𐀼', '𐀽'), ('𐀿', '𐁍'), ('𐁐', '𐁝'), + ('𐂀', '𐃺'), ('𐄀', '𐄂'), ('𐄇', '𐄳'), ('𐄷', '𐆎'), + ('𐆐', '𐆛'), ('𐆠', '𐆠'), ('𐇐', '𐇼'), ('𐊀', '𐊜'), + ('𐊠', '𐋐'), ('𐋡', '𐋻'), ('𐌀', '𐌣'), ('𐌭', '𐍊'), + ('𐍐', '𐍵'), ('𐎀', '𐎝'), ('𐎟', '𐏃'), ('𐏈', '𐏕'), + ('𐐀', '𐒝'), ('𐒠', '𐒩'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), + ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐕯', '𐕯'), ('𐘀', '𐜶'), + ('𐝀', '𐝕'), ('𐝠', '𐝧'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), + ('𐠊', '𐠵'), ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐡕'), + ('𐡗', '𐢞'), ('𐢧', '𐢯'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), + ('𐣻', '𐤛'), ('𐤟', '𐤹'), ('𐤿', '𐤿'), ('𐦀', '𐦷'), + ('𐦼', '𐧏'), ('𐧒', '𐨀'), ('𐨐', '𐨓'), ('𐨕', '𐨗'), + ('𐨙', '𐨳'), ('𐩀', '𐩇'), ('𐩐', '𐩘'), ('𐩠', '𐪟'), + ('𐫀', '𐫤'), ('𐫫', '𐫶'), ('𐬀', '𐬵'), ('𐬹', '𐭕'), + ('𐭘', '𐭲'), ('𐭸', '𐮑'), ('𐮙', '𐮜'), ('𐮩', '𐮯'), + ('𐰀', '𐱈'), ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𐳺', '𐳿'), + ('𐹠', '𐹾'), ('𑀀', '𑀀'), ('𑀂', '𑀷'), ('𑁇', '𑁍'), + ('𑁒', '𑁯'), ('𑂂', '𑂲'), ('𑂷', '𑂸'), ('𑂻', '𑂼'), + ('𑂾', '𑃁'), ('𑃐', '𑃨'), ('𑃰', '𑃹'), ('𑄃', '𑄦'), + ('𑄬', '𑄬'), ('𑄶', '𑅃'), ('𑅐', '𑅲'), ('𑅴', '𑅶'), + ('𑆂', '𑆵'), ('𑆿', '𑇉'), ('𑇍', '𑇍'), ('𑇐', '𑇟'), + ('𑇡', '𑇴'), ('𑈀', '𑈑'), ('𑈓', '𑈮'), ('𑈲', '𑈳'), + ('𑈵', '𑈵'), ('𑈸', '𑈽'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), + ('𑊊', '𑊍'), ('𑊏', '𑊝'), ('𑊟', '𑊩'), ('𑊰', '𑋞'), + ('𑋠', '𑋢'), ('𑋰', '𑋹'), ('𑌂', '𑌃'), ('𑌅', '𑌌'), + ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), ('𑌲', '𑌳'), + ('𑌵', '𑌹'), ('𑌽', '𑌽'), ('𑌿', '𑌿'), ('𑍁', '𑍄'), + ('𑍇', '𑍈'), ('𑍋', '𑍍'), ('𑍐', '𑍐'), ('𑍝', '𑍣'), + ('𑐀', '𑐷'), ('𑑀', '𑑁'), ('𑑅', '𑑅'), ('𑑇', '𑑙'), + ('𑑛', '𑑛'), ('𑑝', '𑑝'), ('𑒀', '𑒯'), ('𑒱', '𑒲'), + ('𑒹', '𑒹'), ('𑒻', '𑒼'), ('𑒾', '𑒾'), ('𑓁', '𑓁'), + ('𑓄', '𑓇'), ('𑓐', '𑓙'), ('𑖀', '𑖮'), ('𑖰', '𑖱'), + ('𑖸', '𑖻'), ('𑖾', '𑖾'), ('𑗁', '𑗛'), ('𑘀', '𑘲'), + ('𑘻', '𑘼'), ('𑘾', '𑘾'), ('𑙁', '𑙄'), ('𑙐', '𑙙'), + ('𑙠', '𑙬'), ('𑚀', '𑚪'), ('𑚬', '𑚬'), ('𑚮', '𑚯'), + ('𑚶', '𑚶'), ('𑛀', '𑛉'), ('𑜀', '𑜙'), ('𑜠', '𑜡'), + ('𑜦', '𑜦'), ('𑜰', '𑜿'), ('𑢠', '𑣲'), ('𑣿', '𑣿'), + ('𑨀', '𑨀'), ('𑨇', '𑨈'), ('𑨋', '𑨲'), ('𑨹', '𑨺'), + ('𑨿', '𑩆'), ('𑩐', '𑩐'), ('𑩗', '𑩘'), ('𑩜', '𑪃'), + ('𑪆', '𑪉'), ('𑪗', '𑪗'), ('𑪚', '𑪜'), ('𑪞', '𑪢'), + ('𑫀', '𑫸'), ('𑰀', '𑰈'), ('𑰊', '𑰯'), ('𑰾', '𑰾'), + ('𑱀', '𑱅'), ('𑱐', '𑱬'), ('𑱰', '𑲏'), ('𑲩', '𑲩'), + ('𑲱', '𑲱'), ('𑲴', '𑲴'), ('𑴀', '𑴆'), ('𑴈', '𑴉'), + ('𑴋', '𑴰'), ('𑵆', '𑵆'), ('𑵐', '𑵙'), ('𒀀', '𒎙'), + ('𒐀', '𒑮'), ('𒑰', '𒑴'), ('𒒀', '𒕃'), ('𓀀', '𓐮'), + ('𔐀', '𔙆'), ('𖠀', '𖨸'), ('𖩀', '𖩞'), ('𖩠', '𖩩'), + ('𖩮', '𖩯'), ('𖫐', '𖫭'), ('𖫵', '𖫵'), ('𖬀', '𖬯'), + ('𖬷', '𖭅'), ('𖭐', '𖭙'), ('𖭛', '𖭡'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽾'), ('𖾓', '𖾟'), + ('𖿠', '𖿡'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𛀀', '𛄞'), + ('𛅰', '𛋻'), ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), + ('𛲐', '𛲙'), ('𛲜', '𛲜'), ('𛲟', '𛲟'), ('𝀀', '𝃵'), + ('𝄀', '𝄦'), ('𝄩', '𝅘𝅥𝅲'), ('𝅦', '𝅦'), ('𝅪', '𝅭'), + ('𝆃', '𝆄'), ('𝆌', '𝆩'), ('𝆮', '𝇨'), ('𝈀', '𝉁'), + ('𝉅', '𝉅'), ('𝌀', '𝍖'), ('𝍠', '𝍱'), ('𝐀', '𝑔'), + ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), + ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), + ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), + ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), + ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝟋'), ('𝟎', '𝧿'), + ('𝨷', '𝨺'), ('𝩭', '𝩴'), ('𝩶', '𝪃'), ('𝪅', '𝪋'), + ('𞠀', '𞣄'), ('𞣇', '𞣏'), ('𞤀', '𞥃'), ('𞥐', '𞥙'), + ('𞥞', '𞥟'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), + ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), + ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), + ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), + ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), + ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), + ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), + ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), + ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𞻰', '𞻱'), ('🀀', '🀫'), + ('🀰', '🂓'), ('🂠', '🂮'), ('🂱', '🂿'), ('🃁', '🃏'), + ('🃑', '🃵'), ('🄀', '🄌'), ('🄐', '🄮'), ('🄰', '🅫'), + ('🅰', '🆬'), ('🇦', '🈂'), ('🈐', '🈻'), ('🉀', '🉈'), + ('🉐', '🉑'), ('🉠', '🉥'), ('🌀', '🛔'), ('🛠', '🛬'), + ('🛰', '🛸'), ('🜀', '🝳'), ('🞀', '🟔'), ('🠀', '🠋'), + ('🠐', '🡇'), ('🡐', '🡙'), ('🡠', '🢇'), ('🢐', '🢭'), + ('🤀', '🤋'), ('🤐', '🤾'), ('🥀', '🥌'), ('🥐', '🥫'), + ('🦀', '🦗'), ('🧀', '🧀'), ('🧐', '🧦'), ('𠀀', '𪛖'), + ('𪜀', '𫜴'), ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), + ('丽', '𪘀'), +]; + +pub const GRAPHEME_EXTEND: &'static [(char, char)] = &[ + ('̀', 'ͯ'), ('҃', '҉'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), + ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('ؐ', 'ؚ'), ('ً', 'ٟ'), ('ٰ', 'ٰ'), + ('ۖ', 'ۜ'), ('۟', 'ۤ'), ('ۧ', 'ۨ'), ('۪', 'ۭ'), ('ܑ', 'ܑ'), + ('ܰ', '݊'), ('ަ', 'ް'), ('߫', '߳'), ('ࠖ', '࠙'), ('ࠛ', 'ࠣ'), + ('ࠥ', 'ࠧ'), ('ࠩ', '࠭'), ('࡙', '࡛'), ('ࣔ', '࣡'), + ('ࣣ', 'ं'), ('ऺ', 'ऺ'), ('़', '़'), ('ु', 'ै'), + ('्', '्'), ('॑', 'ॗ'), ('ॢ', 'ॣ'), ('ঁ', 'ঁ'), + ('়', '়'), ('া', 'া'), ('ু', 'ৄ'), ('্', '্'), + ('ৗ', 'ৗ'), ('ৢ', 'ৣ'), ('ਁ', 'ਂ'), ('਼', '਼'), + ('ੁ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', '੍'), ('ੑ', 'ੑ'), + ('ੰ', 'ੱ'), ('ੵ', 'ੵ'), ('ઁ', 'ં'), ('઼', '઼'), + ('ુ', 'ૅ'), ('ે', 'ૈ'), ('્', '્'), ('ૢ', 'ૣ'), + ('ૺ', '૿'), ('ଁ', 'ଁ'), ('଼', '଼'), ('ା', 'ି'), + ('ୁ', 'ୄ'), ('୍', '୍'), ('ୖ', 'ୗ'), ('ୢ', 'ୣ'), + ('ஂ', 'ஂ'), ('ா', 'ா'), ('ீ', 'ீ'), ('்', '்'), + ('ௗ', 'ௗ'), ('ఀ', 'ఀ'), ('ా', 'ీ'), ('ె', 'ై'), + ('ొ', '్'), ('ౕ', 'ౖ'), ('ౢ', 'ౣ'), ('ಁ', 'ಁ'), + ('಼', '಼'), ('ಿ', 'ಿ'), ('ೂ', 'ೂ'), ('ೆ', 'ೆ'), + ('ೌ', '್'), ('ೕ', 'ೖ'), ('ೢ', 'ೣ'), ('ഀ', 'ഁ'), + ('഻', '഼'), ('ാ', 'ാ'), ('ു', 'ൄ'), ('്', '്'), + ('ൗ', 'ൗ'), ('ൢ', 'ൣ'), ('්', '්'), ('ා', 'ා'), + ('ි', 'ු'), ('ූ', 'ූ'), ('ෟ', 'ෟ'), ('ั', 'ั'), + ('ิ', 'ฺ'), ('็', '๎'), ('ັ', 'ັ'), ('ິ', 'ູ'), + ('ົ', 'ຼ'), ('່', 'ໍ'), ('༘', '༙'), ('༵', '༵'), + ('༷', '༷'), ('༹', '༹'), ('ཱ', 'ཾ'), ('ྀ', '྄'), + ('྆', '྇'), ('ྍ', 'ྗ'), ('ྙ', 'ྼ'), ('࿆', '࿆'), + ('ိ', 'ူ'), ('ဲ', '့'), ('္', '်'), ('ွ', 'ှ'), + ('ၘ', 'ၙ'), ('ၞ', 'ၠ'), ('ၱ', 'ၴ'), ('ႂ', 'ႂ'), + ('ႅ', 'ႆ'), ('ႍ', 'ႍ'), ('ႝ', 'ႝ'), ('፝', '፟'), + ('ᜒ', '᜔'), ('ᜲ', '᜴'), ('ᝒ', 'ᝓ'), ('ᝲ', 'ᝳ'), + ('឴', '឵'), ('ិ', 'ួ'), ('ំ', 'ំ'), ('៉', '៓'), + ('៝', '៝'), ('᠋', '᠍'), ('ᢅ', 'ᢆ'), ('ᢩ', 'ᢩ'), + ('ᤠ', 'ᤢ'), ('ᤧ', 'ᤨ'), ('ᤲ', 'ᤲ'), ('᤹', '᤻'), + ('ᨗ', 'ᨘ'), ('ᨛ', 'ᨛ'), ('ᩖ', 'ᩖ'), ('ᩘ', 'ᩞ'), + ('᩠', '᩠'), ('ᩢ', 'ᩢ'), ('ᩥ', 'ᩬ'), ('ᩳ', '᩼'), + ('᩿', '᩿'), ('᪰', '᪾'), ('ᬀ', 'ᬃ'), ('᬴', '᬴'), + ('ᬶ', 'ᬺ'), ('ᬼ', 'ᬼ'), ('ᭂ', 'ᭂ'), ('᭫', '᭳'), + ('ᮀ', 'ᮁ'), ('ᮢ', 'ᮥ'), ('ᮨ', 'ᮩ'), ('᮫', 'ᮭ'), + ('᯦', '᯦'), ('ᯨ', 'ᯩ'), ('ᯭ', 'ᯭ'), ('ᯯ', 'ᯱ'), + ('ᰬ', 'ᰳ'), ('ᰶ', '᰷'), ('᳐', '᳒'), ('᳔', '᳠'), + ('᳢', '᳨'), ('᳭', '᳭'), ('᳴', '᳴'), ('᳸', '᳹'), + ('᷀', '᷹'), ('᷻', '᷿'), ('\u{200c}', '\u{200c}'), ('⃐', '⃰'), + ('⳯', '⳱'), ('⵿', '⵿'), ('ⷠ', 'ⷿ'), ('〪', '〯'), + ('゙', '゚'), ('꙯', '꙲'), ('ꙴ', '꙽'), ('ꚞ', 'ꚟ'), + ('꛰', '꛱'), ('ꠂ', 'ꠂ'), ('꠆', '꠆'), ('ꠋ', 'ꠋ'), + ('ꠥ', 'ꠦ'), ('꣄', 'ꣅ'), ('꣠', '꣱'), ('ꤦ', '꤭'), + ('ꥇ', 'ꥑ'), ('ꦀ', 'ꦂ'), ('꦳', '꦳'), ('ꦶ', 'ꦹ'), + ('ꦼ', 'ꦼ'), ('ꧥ', 'ꧥ'), ('ꨩ', 'ꨮ'), ('ꨱ', 'ꨲ'), + ('ꨵ', 'ꨶ'), ('ꩃ', 'ꩃ'), ('ꩌ', 'ꩌ'), ('ꩼ', 'ꩼ'), + ('ꪰ', 'ꪰ'), ('ꪲ', 'ꪴ'), ('ꪷ', 'ꪸ'), ('ꪾ', '꪿'), + ('꫁', '꫁'), ('ꫬ', 'ꫭ'), ('꫶', '꫶'), ('ꯥ', 'ꯥ'), + ('ꯨ', 'ꯨ'), ('꯭', '꯭'), ('ﬞ', 'ﬞ'), ('︀', '️'), + ('︠', '︯'), ('゙', '゚'), ('𐇽', '𐇽'), ('𐋠', '𐋠'), + ('𐍶', '𐍺'), ('𐨁', '𐨃'), ('𐨅', '𐨆'), ('𐨌', '𐨏'), + ('𐨸', '𐨺'), ('𐨿', '𐨿'), ('𐫥', '𐫦'), ('𑀁', '𑀁'), + ('𑀸', '𑁆'), ('𑁿', '𑂁'), ('𑂳', '𑂶'), ('𑂹', '𑂺'), + ('𑄀', '𑄂'), ('𑄧', '𑄫'), ('𑄭', '𑄴'), ('𑅳', '𑅳'), + ('𑆀', '𑆁'), ('𑆶', '𑆾'), ('𑇊', '𑇌'), ('𑈯', '𑈱'), + ('𑈴', '𑈴'), ('𑈶', '𑈷'), ('𑈾', '𑈾'), ('𑋟', '𑋟'), + ('𑋣', '𑋪'), ('𑌀', '𑌁'), ('𑌼', '𑌼'), ('𑌾', '𑌾'), + ('𑍀', '𑍀'), ('𑍗', '𑍗'), ('𑍦', '𑍬'), ('𑍰', '𑍴'), + ('𑐸', '𑐿'), ('𑑂', '𑑄'), ('𑑆', '𑑆'), ('𑒰', '𑒰'), + ('𑒳', '𑒸'), ('𑒺', '𑒺'), ('𑒽', '𑒽'), ('𑒿', '𑓀'), + ('𑓂', '𑓃'), ('𑖯', '𑖯'), ('𑖲', '𑖵'), ('𑖼', '𑖽'), + ('𑖿', '𑗀'), ('𑗜', '𑗝'), ('𑘳', '𑘺'), ('𑘽', '𑘽'), + ('𑘿', '𑙀'), ('𑚫', '𑚫'), ('𑚭', '𑚭'), ('𑚰', '𑚵'), + ('𑚷', '𑚷'), ('𑜝', '𑜟'), ('𑜢', '𑜥'), ('𑜧', '𑜫'), + ('𑨁', '𑨆'), ('𑨉', '𑨊'), ('𑨳', '𑨸'), ('𑨻', '𑨾'), + ('𑩇', '𑩇'), ('𑩑', '𑩖'), ('𑩙', '𑩛'), ('𑪊', '𑪖'), + ('𑪘', '𑪙'), ('𑰰', '𑰶'), ('𑰸', '𑰽'), ('𑰿', '𑰿'), + ('𑲒', '𑲧'), ('𑲪', '𑲰'), ('𑲲', '𑲳'), ('𑲵', '𑲶'), + ('𑴱', '𑴶'), ('𑴺', '𑴺'), ('𑴼', '𑴽'), ('𑴿', '𑵅'), + ('𑵇', '𑵇'), ('𖫰', '𖫴'), ('𖬰', '𖬶'), ('𖾏', '𖾒'), + ('𛲝', '𛲞'), ('𝅥', '𝅥'), ('𝅧', '𝅩'), ('𝅮', '𝅲'), + ('𝅻', '𝆂'), ('𝆅', '𝆋'), ('𝆪', '𝆭'), ('𝉂', '𝉄'), + ('𝨀', '𝨶'), ('𝨻', '𝩬'), ('𝩵', '𝩵'), ('𝪄', '𝪄'), + ('𝪛', '𝪟'), ('𝪡', '𝪯'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), + ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), ('𞣐', '𞣖'), + ('𞥄', '𞥊'), ('\u{e0020}', '\u{e007f}'), ('󠄀', '󠇯'), +]; + +pub const GRAPHEME_LINK: &'static [(char, char)] = &[ + ('्', '्'), ('্', '্'), ('੍', '੍'), ('્', '્'), + ('୍', '୍'), ('்', '்'), ('్', '్'), ('್', '್'), + ('഻', '഼'), ('്', '്'), ('්', '්'), ('ฺ', 'ฺ'), + ('྄', '྄'), ('္', '်'), ('᜔', '᜔'), ('᜴', '᜴'), + ('្', '្'), ('᩠', '᩠'), ('᭄', '᭄'), ('᮪', '᮫'), + ('᯲', '᯳'), ('⵿', '⵿'), ('꠆', '꠆'), ('꣄', '꣄'), + ('꥓', '꥓'), ('꧀', '꧀'), ('꫶', '꫶'), ('꯭', '꯭'), + ('𐨿', '𐨿'), ('𑁆', '𑁆'), ('𑁿', '𑁿'), ('𑂹', '𑂹'), + ('𑄳', '𑄴'), ('𑇀', '𑇀'), ('𑈵', '𑈵'), ('𑋪', '𑋪'), + ('𑍍', '𑍍'), ('𑑂', '𑑂'), ('𑓂', '𑓂'), ('𑖿', '𑖿'), + ('𑘿', '𑘿'), ('𑚶', '𑚶'), ('𑜫', '𑜫'), ('𑨴', '𑨴'), + ('𑩇', '𑩇'), ('𑪙', '𑪙'), ('𑰿', '𑰿'), ('𑵄', '𑵅'), +]; + +pub const HEX_DIGIT: &'static [(char, char)] = &[ + ('0', '9'), ('A', 'F'), ('a', 'f'), ('0', '9'), ('A', 'F'), + ('a', 'f'), +]; + +pub const HYPHEN: &'static [(char, char)] = &[ + ('-', '-'), ('\u{ad}', '\u{ad}'), ('֊', '֊'), ('᠆', '᠆'), + ('‐', '‑'), ('⸗', '⸗'), ('・', '・'), ('﹣', '﹣'), + ('-', '-'), ('・', '・'), +]; + +pub const IDS_BINARY_OPERATOR: &'static [(char, char)] = &[ + ('⿰', '⿱'), ('⿴', '⿻'), +]; + +pub const IDS_TRINARY_OPERATOR: &'static [(char, char)] = &[ + ('⿲', '⿳'), +]; + +pub const ID_CONTINUE: &'static [(char, char)] = &[ + ('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), + ('·', '·'), ('º', 'º'), ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), + ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('̀', 'ʹ'), + ('Ͷ', 'ͷ'), ('ͺ', 'ͽ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ί'), ('Ό', 'Ό'), + ('Ύ', 'Ρ'), ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('҃', '҇'), ('Ҋ', 'ԯ'), + ('Ա', 'Ֆ'), ('ՙ', 'ՙ'), ('ա', 'և'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), + ('ׁ', 'ׂ'), ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('א', 'ת'), ('װ', 'ײ'), + ('ؐ', 'ؚ'), ('ؠ', '٩'), ('ٮ', 'ۓ'), ('ە', 'ۜ'), ('۟', 'ۨ'), + ('۪', 'ۼ'), ('ۿ', 'ۿ'), ('ܐ', '݊'), ('ݍ', 'ޱ'), ('߀', 'ߵ'), + ('ߺ', 'ߺ'), ('ࠀ', '࠭'), ('ࡀ', '࡛'), ('ࡠ', 'ࡪ'), + ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ࣔ', '࣡'), ('ࣣ', 'ॣ'), + ('०', '९'), ('ॱ', 'ঃ'), ('অ', 'ঌ'), ('এ', 'ঐ'), + ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), ('শ', 'হ'), + ('়', 'ৄ'), ('ে', 'ৈ'), ('ো', 'ৎ'), ('ৗ', 'ৗ'), + ('ড়', 'ঢ়'), ('য়', 'ৣ'), ('০', 'ৱ'), ('ৼ', 'ৼ'), + ('ਁ', 'ਃ'), ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), + ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), + ('਼', '਼'), ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', '੍'), + ('ੑ', 'ੑ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), ('੦', 'ੵ'), + ('ઁ', 'ઃ'), ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), + ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), ('઼', 'ૅ'), + ('ે', 'ૉ'), ('ો', '્'), ('ૐ', 'ૐ'), ('ૠ', 'ૣ'), + ('૦', '૯'), ('ૹ', '૿'), ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('଼', 'ୄ'), ('େ', 'ୈ'), ('ୋ', '୍'), + ('ୖ', 'ୗ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୣ'), ('୦', '୯'), + ('ୱ', 'ୱ'), ('ஂ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), + ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), + ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), ('ா', 'ூ'), + ('ெ', 'ை'), ('ொ', '்'), ('ௐ', 'ௐ'), ('ௗ', 'ௗ'), + ('௦', '௯'), ('ఀ', 'ః'), ('అ', 'ఌ'), ('ఎ', 'ఐ'), + ('ఒ', 'న'), ('ప', 'హ'), ('ఽ', 'ౄ'), ('ె', 'ై'), + ('ొ', '్'), ('ౕ', 'ౖ'), ('ౘ', 'ౚ'), ('ౠ', 'ౣ'), + ('౦', '౯'), ('ಀ', 'ಃ'), ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), + ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), ('಼', 'ೄ'), + ('ೆ', 'ೈ'), ('ೊ', '್'), ('ೕ', 'ೖ'), ('ೞ', 'ೞ'), + ('ೠ', 'ೣ'), ('೦', '೯'), ('ೱ', 'ೲ'), ('ഀ', 'ഃ'), + ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ൄ'), ('െ', 'ൈ'), + ('ൊ', 'ൎ'), ('ൔ', 'ൗ'), ('ൟ', 'ൣ'), ('൦', '൯'), + ('ൺ', 'ൿ'), ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), + ('ඳ', 'ර'), ('ල', 'ල'), ('ව', 'ෆ'), ('්', '්'), + ('ා', 'ු'), ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('෦', '෯'), + ('ෲ', 'ෳ'), ('ก', 'ฺ'), ('เ', '๎'), ('๐', '๙'), + ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), + ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), + ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), + ('ົ', 'ຽ'), ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('່', 'ໍ'), + ('໐', '໙'), ('ໜ', 'ໟ'), ('ༀ', 'ༀ'), ('༘', '༙'), + ('༠', '༩'), ('༵', '༵'), ('༷', '༷'), ('༹', '༹'), + ('༾', 'ཇ'), ('ཉ', 'ཬ'), ('ཱ', '྄'), ('྆', 'ྗ'), + ('ྙ', 'ྼ'), ('࿆', '࿆'), ('က', '၉'), ('ၐ', 'ႝ'), + ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), + ('ჼ', 'ቈ'), ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), + ('ቚ', 'ቝ'), ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), + ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), + ('ወ', 'ዖ'), ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), + ('፝', '፟'), ('፩', '፱'), ('ᎀ', 'ᎏ'), ('Ꭰ', 'Ᏽ'), + ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), ('ᙯ', 'ᙿ'), ('ᚁ', 'ᚚ'), + ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), ('ᜀ', 'ᜌ'), ('ᜎ', '᜔'), + ('ᜠ', '᜴'), ('ᝀ', 'ᝓ'), ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), + ('ᝲ', 'ᝳ'), ('ក', '៓'), ('ៗ', 'ៗ'), ('ៜ', '៝'), + ('០', '៩'), ('᠋', '᠍'), ('᠐', '᠙'), ('ᠠ', 'ᡷ'), + ('ᢀ', 'ᢪ'), ('ᢰ', 'ᣵ'), ('ᤀ', 'ᤞ'), ('ᤠ', 'ᤫ'), + ('ᤰ', '᤻'), ('᥆', 'ᥭ'), ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), + ('ᦰ', 'ᧉ'), ('᧐', '᧚'), ('ᨀ', 'ᨛ'), ('ᨠ', 'ᩞ'), + ('᩠', '᩼'), ('᩿', '᪉'), ('᪐', '᪙'), ('ᪧ', 'ᪧ'), + ('᪰', '᪽'), ('ᬀ', 'ᭋ'), ('᭐', '᭙'), ('᭫', '᭳'), + ('ᮀ', '᯳'), ('ᰀ', '᰷'), ('᱀', '᱉'), ('ᱍ', 'ᱽ'), + ('ᲀ', 'ᲈ'), ('᳐', '᳒'), ('᳔', '᳹'), ('ᴀ', '᷹'), + ('᷻', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), + ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), + ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), ('ι', 'ι'), + ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), ('ῖ', 'Ί'), + ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), ('‿', '⁀'), + ('⁔', '⁔'), ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), + ('⃐', '⃜'), ('⃡', '⃡'), ('⃥', '⃰'), ('ℂ', 'ℂ'), + ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('℘', 'ℝ'), + ('ℤ', 'ℤ'), ('Ω', 'Ω'), ('ℨ', 'ℨ'), ('K', 'ℹ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), + ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳳ'), + ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ⴰ', 'ⵧ'), + ('ⵯ', 'ⵯ'), ('⵿', 'ⶖ'), ('ⶠ', 'ⶦ'), ('ⶨ', 'ⶮ'), + ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), ('ⷈ', 'ⷎ'), + ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('ⷠ', 'ⷿ'), ('々', '〇'), + ('〡', '〯'), ('〱', '〵'), ('〸', '〼'), ('ぁ', 'ゖ'), + ('゙', 'ゟ'), ('ァ', 'ヺ'), ('ー', 'ヿ'), ('ㄅ', 'ㄮ'), + ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), ('ㇰ', 'ㇿ'), ('㐀', '䶵'), + ('一', '鿪'), ('ꀀ', 'ꒌ'), ('ꓐ', 'ꓽ'), ('ꔀ', 'ꘌ'), + ('ꘐ', 'ꘫ'), ('Ꙁ', '꙯'), ('ꙴ', '꙽'), ('ꙿ', '꛱'), + ('ꜗ', 'ꜟ'), ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), ('Ʞ', 'ꞷ'), + ('ꟷ', 'ꠧ'), ('ꡀ', 'ꡳ'), ('ꢀ', 'ꣅ'), ('꣐', '꣙'), + ('꣠', 'ꣷ'), ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), ('꤀', '꤭'), + ('ꤰ', '꥓'), ('ꥠ', 'ꥼ'), ('ꦀ', '꧀'), ('ꧏ', '꧙'), + ('ꧠ', 'ꧾ'), ('ꨀ', 'ꨶ'), ('ꩀ', 'ꩍ'), ('꩐', '꩙'), + ('ꩠ', 'ꩶ'), ('ꩺ', 'ꫂ'), ('ꫛ', 'ꫝ'), ('ꫠ', 'ꫯ'), + ('ꫲ', '꫶'), ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), + ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭥ'), + ('ꭰ', 'ꯪ'), ('꯬', '꯭'), ('꯰', '꯹'), ('가', '힣'), + ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('豈', '舘'), ('並', '龎'), + ('ff', 'st'), ('ﬓ', 'ﬗ'), ('יִ', 'ﬨ'), ('שׁ', 'זּ'), + ('טּ', 'לּ'), ('מּ', 'מּ'), ('נּ', 'סּ'), ('ףּ', 'פּ'), + ('צּ', 'ﮱ'), ('ﯓ', 'ﴽ'), ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), + ('ﷰ', 'ﷻ'), ('︀', '️'), ('︠', '︯'), ('︳', '︴'), + ('﹍', '﹏'), ('ﹰ', 'ﹴ'), ('ﹶ', 'ﻼ'), ('0', '9'), + ('A', 'Z'), ('_', '_'), ('a', 'z'), ('ヲ', 'ᄒ'), + ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), + ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), + ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐅀', '𐅴'), + ('𐇽', '𐇽'), ('𐊀', '𐊜'), ('𐊠', '𐋐'), ('𐋠', '𐋠'), + ('𐌀', '𐌟'), ('𐌭', '𐍊'), ('𐍐', '𐍺'), ('𐎀', '𐎝'), + ('𐎠', '𐏃'), ('𐏈', '𐏏'), ('𐏑', '𐏕'), ('𐐀', '𐒝'), + ('𐒠', '𐒩'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), ('𐔀', '𐔧'), + ('𐔰', '𐕣'), ('𐘀', '𐜶'), ('𐝀', '𐝕'), ('𐝠', '𐝧'), + ('𐠀', '𐠅'), ('𐠈', '𐠈'), ('𐠊', '𐠵'), ('𐠷', '𐠸'), + ('𐠼', '𐠼'), ('𐠿', '𐡕'), ('𐡠', '𐡶'), ('𐢀', '𐢞'), + ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐤀', '𐤕'), ('𐤠', '𐤹'), + ('𐦀', '𐦷'), ('𐦾', '𐦿'), ('𐨀', '𐨃'), ('𐨅', '𐨆'), + ('𐨌', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), ('𐨸', '𐨺'), + ('𐨿', '𐨿'), ('𐩠', '𐩼'), ('𐪀', '𐪜'), ('𐫀', '𐫇'), + ('𐫉', '𐫦'), ('𐬀', '𐬵'), ('𐭀', '𐭕'), ('𐭠', '𐭲'), + ('𐮀', '𐮑'), ('𐰀', '𐱈'), ('𐲀', '𐲲'), ('𐳀', '𐳲'), + ('𑀀', '𑁆'), ('𑁦', '𑁯'), ('𑁿', '𑂺'), ('𑃐', '𑃨'), + ('𑃰', '𑃹'), ('𑄀', '𑄴'), ('𑄶', '𑄿'), ('𑅐', '𑅳'), + ('𑅶', '𑅶'), ('𑆀', '𑇄'), ('𑇊', '𑇌'), ('𑇐', '𑇚'), + ('𑇜', '𑇜'), ('𑈀', '𑈑'), ('𑈓', '𑈷'), ('𑈾', '𑈾'), + ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), ('𑊏', '𑊝'), + ('𑊟', '𑊨'), ('𑊰', '𑋪'), ('𑋰', '𑋹'), ('𑌀', '𑌃'), + ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), + ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌼', '𑍄'), ('𑍇', '𑍈'), + ('𑍋', '𑍍'), ('𑍐', '𑍐'), ('𑍗', '𑍗'), ('𑍝', '𑍣'), + ('𑍦', '𑍬'), ('𑍰', '𑍴'), ('𑐀', '𑑊'), ('𑑐', '𑑙'), + ('𑒀', '𑓅'), ('𑓇', '𑓇'), ('𑓐', '𑓙'), ('𑖀', '𑖵'), + ('𑖸', '𑗀'), ('𑗘', '𑗝'), ('𑘀', '𑙀'), ('𑙄', '𑙄'), + ('𑙐', '𑙙'), ('𑚀', '𑚷'), ('𑛀', '𑛉'), ('𑜀', '𑜙'), + ('𑜝', '𑜫'), ('𑜰', '𑜹'), ('𑢠', '𑣩'), ('𑣿', '𑣿'), + ('𑨀', '𑨾'), ('𑩇', '𑩇'), ('𑩐', '𑪃'), ('𑪆', '𑪙'), + ('𑫀', '𑫸'), ('𑰀', '𑰈'), ('𑰊', '𑰶'), ('𑰸', '𑱀'), + ('𑱐', '𑱙'), ('𑱲', '𑲏'), ('𑲒', '𑲧'), ('𑲩', '𑲶'), + ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴶'), ('𑴺', '𑴺'), + ('𑴼', '𑴽'), ('𑴿', '𑵇'), ('𑵐', '𑵙'), ('𒀀', '𒎙'), + ('𒐀', '𒑮'), ('𒒀', '𒕃'), ('𓀀', '𓐮'), ('𔐀', '𔙆'), + ('𖠀', '𖨸'), ('𖩀', '𖩞'), ('𖩠', '𖩩'), ('𖫐', '𖫭'), + ('𖫰', '𖫴'), ('𖬀', '𖬶'), ('𖭀', '𖭃'), ('𖭐', '𖭙'), + ('𖭣', '𖭷'), ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽾'), + ('𖾏', '𖾟'), ('𖿠', '𖿡'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), + ('𛀀', '𛄞'), ('𛅰', '𛋻'), ('𛰀', '𛱪'), ('𛱰', '𛱼'), + ('𛲀', '𛲈'), ('𛲐', '𛲙'), ('𛲝', '𛲞'), ('𝅥', '𝅩'), + ('𝅭', '𝅲'), ('𝅻', '𝆂'), ('𝆅', '𝆋'), ('𝆪', '𝆭'), + ('𝉂', '𝉄'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), + ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), + ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), + ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), + ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), + ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), ('𝛼', '𝜔'), + ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), ('𝝰', '𝞈'), + ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), ('𝟎', '𝟿'), + ('𝨀', '𝨶'), ('𝨻', '𝩬'), ('𝩵', '𝩵'), ('𝪄', '𝪄'), + ('𝪛', '𝪟'), ('𝪡', '𝪯'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), + ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), ('𞠀', '𞣄'), + ('𞣐', '𞣖'), ('𞤀', '𞥊'), ('𞥐', '𞥙'), ('𞸀', '𞸃'), + ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), ('𞸧', '𞸧'), + ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), ('𞸻', '𞸻'), + ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), ('𞹋', '𞹋'), + ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), ('𞹗', '𞹗'), + ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), ('𞹟', '𞹟'), + ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), ('𞹬', '𞹲'), + ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), ('𞺀', '𞺉'), + ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), ('𞺫', '𞺻'), + ('𠀀', '𪛖'), ('𪜀', '𫜴'), ('𫝀', '𫠝'), ('𫠠', '𬺡'), + ('𬺰', '𮯠'), ('丽', '𪘀'), ('󠄀', '󠇯'), +]; + +pub const ID_START: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), ('º', 'º'), + ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), + ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('Ͱ', 'ʹ'), ('Ͷ', 'ͷ'), ('ͺ', 'ͽ'), + ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), + ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('Ҋ', 'ԯ'), ('Ա', 'Ֆ'), ('ՙ', 'ՙ'), + ('ա', 'և'), ('א', 'ת'), ('װ', 'ײ'), ('ؠ', 'ي'), ('ٮ', 'ٯ'), + ('ٱ', 'ۓ'), ('ە', 'ە'), ('ۥ', 'ۦ'), ('ۮ', 'ۯ'), ('ۺ', 'ۼ'), + ('ۿ', 'ۿ'), ('ܐ', 'ܐ'), ('ܒ', 'ܯ'), ('ݍ', 'ޥ'), ('ޱ', 'ޱ'), + ('ߊ', 'ߪ'), ('ߴ', 'ߵ'), ('ߺ', 'ߺ'), ('ࠀ', 'ࠕ'), ('ࠚ', 'ࠚ'), + ('ࠤ', 'ࠤ'), ('ࠨ', 'ࠨ'), ('ࡀ', 'ࡘ'), ('ࡠ', 'ࡪ'), + ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ऄ', 'ह'), ('ऽ', 'ऽ'), + ('ॐ', 'ॐ'), ('क़', 'ॡ'), ('ॱ', 'ঀ'), ('অ', 'ঌ'), + ('এ', 'ঐ'), ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), + ('শ', 'হ'), ('ঽ', 'ঽ'), ('ৎ', 'ৎ'), ('ড়', 'ঢ়'), + ('য়', 'ৡ'), ('ৰ', 'ৱ'), ('ৼ', 'ৼ'), ('ਅ', 'ਊ'), + ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), + ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), + ('ੲ', 'ੴ'), ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), + ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), ('ઽ', 'ઽ'), + ('ૐ', 'ૐ'), ('ૠ', 'ૡ'), ('ૹ', 'ૹ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('ଽ', 'ଽ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୡ'), + ('ୱ', 'ୱ'), ('ஃ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), + ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), + ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), ('ௐ', 'ௐ'), + ('అ', 'ఌ'), ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), + ('ఽ', 'ఽ'), ('ౘ', 'ౚ'), ('ౠ', 'ౡ'), ('ಀ', 'ಀ'), + ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), + ('ವ', 'ಹ'), ('ಽ', 'ಽ'), ('ೞ', 'ೞ'), ('ೠ', 'ೡ'), + ('ೱ', 'ೲ'), ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ഺ'), + ('ഽ', 'ഽ'), ('ൎ', 'ൎ'), ('ൔ', 'ൖ'), ('ൟ', 'ൡ'), + ('ൺ', 'ൿ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('ก', 'ะ'), ('า', 'ำ'), + ('เ', 'ๆ'), ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), + ('ຊ', 'ຊ'), ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), + ('ມ', 'ຣ'), ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), + ('ອ', 'ະ'), ('າ', 'ຳ'), ('ຽ', 'ຽ'), ('ເ', 'ໄ'), + ('ໆ', 'ໆ'), ('ໜ', 'ໟ'), ('ༀ', 'ༀ'), ('ཀ', 'ཇ'), + ('ཉ', 'ཬ'), ('ྈ', 'ྌ'), ('က', 'ဪ'), ('ဿ', 'ဿ'), + ('ၐ', 'ၕ'), ('ၚ', 'ၝ'), ('ၡ', 'ၡ'), ('ၥ', 'ၦ'), + ('ၮ', 'ၰ'), ('ၵ', 'ႁ'), ('ႎ', 'ႎ'), ('Ⴀ', 'Ⴥ'), + ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), ('ჼ', 'ቈ'), + ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), + ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), + ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), + ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('ᎀ', 'ᎏ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), ('ᙯ', 'ᙿ'), + ('ᚁ', 'ᚚ'), ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), ('ᜀ', 'ᜌ'), + ('ᜎ', 'ᜑ'), ('ᜠ', 'ᜱ'), ('ᝀ', 'ᝑ'), ('ᝠ', 'ᝬ'), + ('ᝮ', 'ᝰ'), ('ក', 'ឳ'), ('ៗ', 'ៗ'), ('ៜ', 'ៜ'), + ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢨ'), ('ᢪ', 'ᢪ'), ('ᢰ', 'ᣵ'), + ('ᤀ', 'ᤞ'), ('ᥐ', 'ᥭ'), ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), + ('ᦰ', 'ᧉ'), ('ᨀ', 'ᨖ'), ('ᨠ', 'ᩔ'), ('ᪧ', 'ᪧ'), + ('ᬅ', 'ᬳ'), ('ᭅ', 'ᭋ'), ('ᮃ', 'ᮠ'), ('ᮮ', 'ᮯ'), + ('ᮺ', 'ᯥ'), ('ᰀ', 'ᰣ'), ('ᱍ', 'ᱏ'), ('ᱚ', 'ᱽ'), + ('ᲀ', 'ᲈ'), ('ᳩ', 'ᳬ'), ('ᳮ', 'ᳱ'), ('ᳵ', 'ᳶ'), + ('ᴀ', 'ᶿ'), ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), + ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), + ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), + ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), + ('ῖ', 'Ί'), ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), + ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ℂ', 'ℂ'), + ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('℘', 'ℝ'), + ('ℤ', 'ℤ'), ('Ω', 'Ω'), ('ℨ', 'ℨ'), ('K', 'ℹ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), + ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳮ'), + ('Ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), + ('ⴰ', 'ⵧ'), ('ⵯ', 'ⵯ'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), + ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), + ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('々', '〇'), + ('〡', '〩'), ('〱', '〵'), ('〸', '〼'), ('ぁ', 'ゖ'), + ('゛', 'ゟ'), ('ァ', 'ヺ'), ('ー', 'ヿ'), ('ㄅ', 'ㄮ'), + ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), ('ㇰ', 'ㇿ'), ('㐀', '䶵'), + ('一', '鿪'), ('ꀀ', 'ꒌ'), ('ꓐ', 'ꓽ'), ('ꔀ', 'ꘌ'), + ('ꘐ', 'ꘟ'), ('ꘪ', 'ꘫ'), ('Ꙁ', 'ꙮ'), ('ꙿ', 'ꚝ'), + ('ꚠ', 'ꛯ'), ('ꜗ', 'ꜟ'), ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), + ('Ʞ', 'ꞷ'), ('ꟷ', 'ꠁ'), ('ꠃ', 'ꠅ'), ('ꠇ', 'ꠊ'), + ('ꠌ', 'ꠢ'), ('ꡀ', 'ꡳ'), ('ꢂ', 'ꢳ'), ('ꣲ', 'ꣷ'), + ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), ('ꤊ', 'ꤥ'), ('ꤰ', 'ꥆ'), + ('ꥠ', 'ꥼ'), ('ꦄ', 'ꦲ'), ('ꧏ', 'ꧏ'), ('ꧠ', 'ꧤ'), + ('ꧦ', 'ꧯ'), ('ꧺ', 'ꧾ'), ('ꨀ', 'ꨨ'), ('ꩀ', 'ꩂ'), + ('ꩄ', 'ꩋ'), ('ꩠ', 'ꩶ'), ('ꩺ', 'ꩺ'), ('ꩾ', 'ꪯ'), + ('ꪱ', 'ꪱ'), ('ꪵ', 'ꪶ'), ('ꪹ', 'ꪽ'), ('ꫀ', 'ꫀ'), + ('ꫂ', 'ꫂ'), ('ꫛ', 'ꫝ'), ('ꫠ', 'ꫪ'), ('ꫲ', 'ꫴ'), + ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), + ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭥ'), ('ꭰ', 'ꯢ'), + ('가', '힣'), ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('豈', '舘'), + ('並', '龎'), ('ff', 'st'), ('ﬓ', 'ﬗ'), ('יִ', 'יִ'), + ('ײַ', 'ﬨ'), ('שׁ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), + ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﮱ'), ('ﯓ', 'ﴽ'), + ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷻ'), ('ﹰ', 'ﹴ'), + ('ﹶ', 'ﻼ'), ('A', 'Z'), ('a', 'z'), ('ヲ', 'ᄒ'), + ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), + ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), + ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐅀', '𐅴'), + ('𐊀', '𐊜'), ('𐊠', '𐋐'), ('𐌀', '𐌟'), ('𐌭', '𐍊'), + ('𐍐', '𐍵'), ('𐎀', '𐎝'), ('𐎠', '𐏃'), ('𐏈', '𐏏'), + ('𐏑', '𐏕'), ('𐐀', '𐒝'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), + ('𐔀', '𐔧'), ('𐔰', '𐕣'), ('𐘀', '𐜶'), ('𐝀', '𐝕'), + ('𐝠', '𐝧'), ('𐠀', '𐠅'), ('𐠈', '𐠈'), ('𐠊', '𐠵'), + ('𐠷', '𐠸'), ('𐠼', '𐠼'), ('𐠿', '𐡕'), ('𐡠', '𐡶'), + ('𐢀', '𐢞'), ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐤀', '𐤕'), + ('𐤠', '𐤹'), ('𐦀', '𐦷'), ('𐦾', '𐦿'), ('𐨀', '𐨀'), + ('𐨐', '𐨓'), ('𐨕', '𐨗'), ('𐨙', '𐨳'), ('𐩠', '𐩼'), + ('𐪀', '𐪜'), ('𐫀', '𐫇'), ('𐫉', '𐫤'), ('𐬀', '𐬵'), + ('𐭀', '𐭕'), ('𐭠', '𐭲'), ('𐮀', '𐮑'), ('𐰀', '𐱈'), + ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𑀃', '𑀷'), ('𑂃', '𑂯'), + ('𑃐', '𑃨'), ('𑄃', '𑄦'), ('𑅐', '𑅲'), ('𑅶', '𑅶'), + ('𑆃', '𑆲'), ('𑇁', '𑇄'), ('𑇚', '𑇚'), ('𑇜', '𑇜'), + ('𑈀', '𑈑'), ('𑈓', '𑈫'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), + ('𑊊', '𑊍'), ('𑊏', '𑊝'), ('𑊟', '𑊨'), ('𑊰', '𑋞'), + ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), + ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌽', '𑌽'), ('𑍐', '𑍐'), + ('𑍝', '𑍡'), ('𑐀', '𑐴'), ('𑑇', '𑑊'), ('𑒀', '𑒯'), + ('𑓄', '𑓅'), ('𑓇', '𑓇'), ('𑖀', '𑖮'), ('𑗘', '𑗛'), + ('𑘀', '𑘯'), ('𑙄', '𑙄'), ('𑚀', '𑚪'), ('𑜀', '𑜙'), + ('𑢠', '𑣟'), ('𑣿', '𑣿'), ('𑨀', '𑨀'), ('𑨋', '𑨲'), + ('𑨺', '𑨺'), ('𑩐', '𑩐'), ('𑩜', '𑪃'), ('𑪆', '𑪉'), + ('𑫀', '𑫸'), ('𑰀', '𑰈'), ('𑰊', '𑰮'), ('𑱀', '𑱀'), + ('𑱲', '𑲏'), ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴰'), + ('𑵆', '𑵆'), ('𒀀', '𒎙'), ('𒐀', '𒑮'), ('𒒀', '𒕃'), + ('𓀀', '𓐮'), ('𔐀', '𔙆'), ('𖠀', '𖨸'), ('𖩀', '𖩞'), + ('𖫐', '𖫭'), ('𖬀', '𖬯'), ('𖭀', '𖭃'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽐'), ('𖾓', '𖾟'), + ('𖿠', '𖿡'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𛀀', '𛄞'), + ('𛅰', '𛋻'), ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), + ('𛲐', '𛲙'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), + ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), + ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), + ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), + ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), + ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), ('𝛼', '𝜔'), + ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), ('𝝰', '𝞈'), + ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), ('𞠀', '𞣄'), + ('𞤀', '𞥃'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), + ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), + ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), + ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), + ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), + ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), + ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), + ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), + ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), + ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), ('丽', '𪘀'), +]; + +pub const IDEOGRAPHIC: &'static [(char, char)] = &[ + ('〆', '〇'), ('〡', '〩'), ('〸', '〺'), ('㐀', '䶵'), + ('一', '鿪'), ('豈', '舘'), ('並', '龎'), ('𗀀', '𘟬'), + ('𘠀', '𘫲'), ('𛅰', '𛋻'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), + ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), ('丽', '𪘀'), +]; + +pub const JOIN_CONTROL: &'static [(char, char)] = &[ + ('\u{200c}', '\u{200d}'), +]; + +pub const LOGICAL_ORDER_EXCEPTION: &'static [(char, char)] = &[ + ('เ', 'ไ'), ('ເ', 'ໄ'), ('ᦵ', 'ᦷ'), ('ᦺ', 'ᦺ'), + ('ꪵ', 'ꪶ'), ('ꪹ', 'ꪹ'), ('ꪻ', 'ꪼ'), +]; + +pub const LOWERCASE: &'static [(char, char)] = &[ + ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), ('º', 'º'), ('ß', 'ö'), + ('ø', 'ÿ'), ('ā', 'ā'), ('ă', 'ă'), ('ą', 'ą'), ('ć', 'ć'), + ('ĉ', 'ĉ'), ('ċ', 'ċ'), ('č', 'č'), ('ď', 'ď'), ('đ', 'đ'), + ('ē', 'ē'), ('ĕ', 'ĕ'), ('ė', 'ė'), ('ę', 'ę'), ('ě', 'ě'), + ('ĝ', 'ĝ'), ('ğ', 'ğ'), ('ġ', 'ġ'), ('ģ', 'ģ'), ('ĥ', 'ĥ'), + ('ħ', 'ħ'), ('ĩ', 'ĩ'), ('ī', 'ī'), ('ĭ', 'ĭ'), ('į', 'į'), + ('ı', 'ı'), ('ij', 'ij'), ('ĵ', 'ĵ'), ('ķ', 'ĸ'), ('ĺ', 'ĺ'), + ('ļ', 'ļ'), ('ľ', 'ľ'), ('ŀ', 'ŀ'), ('ł', 'ł'), ('ń', 'ń'), + ('ņ', 'ņ'), ('ň', 'ʼn'), ('ŋ', 'ŋ'), ('ō', 'ō'), ('ŏ', 'ŏ'), + ('ő', 'ő'), ('œ', 'œ'), ('ŕ', 'ŕ'), ('ŗ', 'ŗ'), ('ř', 'ř'), + ('ś', 'ś'), ('ŝ', 'ŝ'), ('ş', 'ş'), ('š', 'š'), ('ţ', 'ţ'), + ('ť', 'ť'), ('ŧ', 'ŧ'), ('ũ', 'ũ'), ('ū', 'ū'), ('ŭ', 'ŭ'), + ('ů', 'ů'), ('ű', 'ű'), ('ų', 'ų'), ('ŵ', 'ŵ'), ('ŷ', 'ŷ'), + ('ź', 'ź'), ('ż', 'ż'), ('ž', 'ƀ'), ('ƃ', 'ƃ'), ('ƅ', 'ƅ'), + ('ƈ', 'ƈ'), ('ƌ', 'ƍ'), ('ƒ', 'ƒ'), ('ƕ', 'ƕ'), ('ƙ', 'ƛ'), + ('ƞ', 'ƞ'), ('ơ', 'ơ'), ('ƣ', 'ƣ'), ('ƥ', 'ƥ'), ('ƨ', 'ƨ'), + ('ƪ', 'ƫ'), ('ƭ', 'ƭ'), ('ư', 'ư'), ('ƴ', 'ƴ'), ('ƶ', 'ƶ'), + ('ƹ', 'ƺ'), ('ƽ', 'ƿ'), ('dž', 'dž'), ('lj', 'lj'), ('nj', 'nj'), + ('ǎ', 'ǎ'), ('ǐ', 'ǐ'), ('ǒ', 'ǒ'), ('ǔ', 'ǔ'), ('ǖ', 'ǖ'), + ('ǘ', 'ǘ'), ('ǚ', 'ǚ'), ('ǜ', 'ǝ'), ('ǟ', 'ǟ'), ('ǡ', 'ǡ'), + ('ǣ', 'ǣ'), ('ǥ', 'ǥ'), ('ǧ', 'ǧ'), ('ǩ', 'ǩ'), ('ǫ', 'ǫ'), + ('ǭ', 'ǭ'), ('ǯ', 'ǰ'), ('dz', 'dz'), ('ǵ', 'ǵ'), ('ǹ', 'ǹ'), + ('ǻ', 'ǻ'), ('ǽ', 'ǽ'), ('ǿ', 'ǿ'), ('ȁ', 'ȁ'), ('ȃ', 'ȃ'), + ('ȅ', 'ȅ'), ('ȇ', 'ȇ'), ('ȉ', 'ȉ'), ('ȋ', 'ȋ'), ('ȍ', 'ȍ'), + ('ȏ', 'ȏ'), ('ȑ', 'ȑ'), ('ȓ', 'ȓ'), ('ȕ', 'ȕ'), ('ȗ', 'ȗ'), + ('ș', 'ș'), ('ț', 'ț'), ('ȝ', 'ȝ'), ('ȟ', 'ȟ'), ('ȡ', 'ȡ'), + ('ȣ', 'ȣ'), ('ȥ', 'ȥ'), ('ȧ', 'ȧ'), ('ȩ', 'ȩ'), ('ȫ', 'ȫ'), + ('ȭ', 'ȭ'), ('ȯ', 'ȯ'), ('ȱ', 'ȱ'), ('ȳ', 'ȹ'), ('ȼ', 'ȼ'), + ('ȿ', 'ɀ'), ('ɂ', 'ɂ'), ('ɇ', 'ɇ'), ('ɉ', 'ɉ'), ('ɋ', 'ɋ'), + ('ɍ', 'ɍ'), ('ɏ', 'ʓ'), ('ʕ', 'ʸ'), ('ˀ', 'ˁ'), ('ˠ', 'ˤ'), + ('ͅ', 'ͅ'), ('ͱ', 'ͱ'), ('ͳ', 'ͳ'), ('ͷ', 'ͷ'), ('ͺ', 'ͽ'), + ('ΐ', 'ΐ'), ('ά', 'ώ'), ('ϐ', 'ϑ'), ('ϕ', 'ϗ'), ('ϙ', 'ϙ'), + ('ϛ', 'ϛ'), ('ϝ', 'ϝ'), ('ϟ', 'ϟ'), ('ϡ', 'ϡ'), ('ϣ', 'ϣ'), + ('ϥ', 'ϥ'), ('ϧ', 'ϧ'), ('ϩ', 'ϩ'), ('ϫ', 'ϫ'), ('ϭ', 'ϭ'), + ('ϯ', 'ϳ'), ('ϵ', 'ϵ'), ('ϸ', 'ϸ'), ('ϻ', 'ϼ'), ('а', 'џ'), + ('ѡ', 'ѡ'), ('ѣ', 'ѣ'), ('ѥ', 'ѥ'), ('ѧ', 'ѧ'), ('ѩ', 'ѩ'), + ('ѫ', 'ѫ'), ('ѭ', 'ѭ'), ('ѯ', 'ѯ'), ('ѱ', 'ѱ'), ('ѳ', 'ѳ'), + ('ѵ', 'ѵ'), ('ѷ', 'ѷ'), ('ѹ', 'ѹ'), ('ѻ', 'ѻ'), ('ѽ', 'ѽ'), + ('ѿ', 'ѿ'), ('ҁ', 'ҁ'), ('ҋ', 'ҋ'), ('ҍ', 'ҍ'), ('ҏ', 'ҏ'), + ('ґ', 'ґ'), ('ғ', 'ғ'), ('ҕ', 'ҕ'), ('җ', 'җ'), ('ҙ', 'ҙ'), + ('қ', 'қ'), ('ҝ', 'ҝ'), ('ҟ', 'ҟ'), ('ҡ', 'ҡ'), ('ң', 'ң'), + ('ҥ', 'ҥ'), ('ҧ', 'ҧ'), ('ҩ', 'ҩ'), ('ҫ', 'ҫ'), ('ҭ', 'ҭ'), + ('ү', 'ү'), ('ұ', 'ұ'), ('ҳ', 'ҳ'), ('ҵ', 'ҵ'), ('ҷ', 'ҷ'), + ('ҹ', 'ҹ'), ('һ', 'һ'), ('ҽ', 'ҽ'), ('ҿ', 'ҿ'), ('ӂ', 'ӂ'), + ('ӄ', 'ӄ'), ('ӆ', 'ӆ'), ('ӈ', 'ӈ'), ('ӊ', 'ӊ'), ('ӌ', 'ӌ'), + ('ӎ', 'ӏ'), ('ӑ', 'ӑ'), ('ӓ', 'ӓ'), ('ӕ', 'ӕ'), ('ӗ', 'ӗ'), + ('ә', 'ә'), ('ӛ', 'ӛ'), ('ӝ', 'ӝ'), ('ӟ', 'ӟ'), ('ӡ', 'ӡ'), + ('ӣ', 'ӣ'), ('ӥ', 'ӥ'), ('ӧ', 'ӧ'), ('ө', 'ө'), ('ӫ', 'ӫ'), + ('ӭ', 'ӭ'), ('ӯ', 'ӯ'), ('ӱ', 'ӱ'), ('ӳ', 'ӳ'), ('ӵ', 'ӵ'), + ('ӷ', 'ӷ'), ('ӹ', 'ӹ'), ('ӻ', 'ӻ'), ('ӽ', 'ӽ'), ('ӿ', 'ӿ'), + ('ԁ', 'ԁ'), ('ԃ', 'ԃ'), ('ԅ', 'ԅ'), ('ԇ', 'ԇ'), ('ԉ', 'ԉ'), + ('ԋ', 'ԋ'), ('ԍ', 'ԍ'), ('ԏ', 'ԏ'), ('ԑ', 'ԑ'), ('ԓ', 'ԓ'), + ('ԕ', 'ԕ'), ('ԗ', 'ԗ'), ('ԙ', 'ԙ'), ('ԛ', 'ԛ'), ('ԝ', 'ԝ'), + ('ԟ', 'ԟ'), ('ԡ', 'ԡ'), ('ԣ', 'ԣ'), ('ԥ', 'ԥ'), ('ԧ', 'ԧ'), + ('ԩ', 'ԩ'), ('ԫ', 'ԫ'), ('ԭ', 'ԭ'), ('ԯ', 'ԯ'), ('ա', 'և'), + ('ᏸ', 'ᏽ'), ('ᲀ', 'ᲈ'), ('ᴀ', 'ᶿ'), ('ḁ', 'ḁ'), + ('ḃ', 'ḃ'), ('ḅ', 'ḅ'), ('ḇ', 'ḇ'), ('ḉ', 'ḉ'), + ('ḋ', 'ḋ'), ('ḍ', 'ḍ'), ('ḏ', 'ḏ'), ('ḑ', 'ḑ'), + ('ḓ', 'ḓ'), ('ḕ', 'ḕ'), ('ḗ', 'ḗ'), ('ḙ', 'ḙ'), + ('ḛ', 'ḛ'), ('ḝ', 'ḝ'), ('ḟ', 'ḟ'), ('ḡ', 'ḡ'), + ('ḣ', 'ḣ'), ('ḥ', 'ḥ'), ('ḧ', 'ḧ'), ('ḩ', 'ḩ'), + ('ḫ', 'ḫ'), ('ḭ', 'ḭ'), ('ḯ', 'ḯ'), ('ḱ', 'ḱ'), + ('ḳ', 'ḳ'), ('ḵ', 'ḵ'), ('ḷ', 'ḷ'), ('ḹ', 'ḹ'), + ('ḻ', 'ḻ'), ('ḽ', 'ḽ'), ('ḿ', 'ḿ'), ('ṁ', 'ṁ'), + ('ṃ', 'ṃ'), ('ṅ', 'ṅ'), ('ṇ', 'ṇ'), ('ṉ', 'ṉ'), + ('ṋ', 'ṋ'), ('ṍ', 'ṍ'), ('ṏ', 'ṏ'), ('ṑ', 'ṑ'), + ('ṓ', 'ṓ'), ('ṕ', 'ṕ'), ('ṗ', 'ṗ'), ('ṙ', 'ṙ'), + ('ṛ', 'ṛ'), ('ṝ', 'ṝ'), ('ṟ', 'ṟ'), ('ṡ', 'ṡ'), + ('ṣ', 'ṣ'), ('ṥ', 'ṥ'), ('ṧ', 'ṧ'), ('ṩ', 'ṩ'), + ('ṫ', 'ṫ'), ('ṭ', 'ṭ'), ('ṯ', 'ṯ'), ('ṱ', 'ṱ'), + ('ṳ', 'ṳ'), ('ṵ', 'ṵ'), ('ṷ', 'ṷ'), ('ṹ', 'ṹ'), + ('ṻ', 'ṻ'), ('ṽ', 'ṽ'), ('ṿ', 'ṿ'), ('ẁ', 'ẁ'), + ('ẃ', 'ẃ'), ('ẅ', 'ẅ'), ('ẇ', 'ẇ'), ('ẉ', 'ẉ'), + ('ẋ', 'ẋ'), ('ẍ', 'ẍ'), ('ẏ', 'ẏ'), ('ẑ', 'ẑ'), + ('ẓ', 'ẓ'), ('ẕ', 'ẝ'), ('ẟ', 'ẟ'), ('ạ', 'ạ'), + ('ả', 'ả'), ('ấ', 'ấ'), ('ầ', 'ầ'), ('ẩ', 'ẩ'), + ('ẫ', 'ẫ'), ('ậ', 'ậ'), ('ắ', 'ắ'), ('ằ', 'ằ'), + ('ẳ', 'ẳ'), ('ẵ', 'ẵ'), ('ặ', 'ặ'), ('ẹ', 'ẹ'), + ('ẻ', 'ẻ'), ('ẽ', 'ẽ'), ('ế', 'ế'), ('ề', 'ề'), + ('ể', 'ể'), ('ễ', 'ễ'), ('ệ', 'ệ'), ('ỉ', 'ỉ'), + ('ị', 'ị'), ('ọ', 'ọ'), ('ỏ', 'ỏ'), ('ố', 'ố'), + ('ồ', 'ồ'), ('ổ', 'ổ'), ('ỗ', 'ỗ'), ('ộ', 'ộ'), + ('ớ', 'ớ'), ('ờ', 'ờ'), ('ở', 'ở'), ('ỡ', 'ỡ'), + ('ợ', 'ợ'), ('ụ', 'ụ'), ('ủ', 'ủ'), ('ứ', 'ứ'), + ('ừ', 'ừ'), ('ử', 'ử'), ('ữ', 'ữ'), ('ự', 'ự'), + ('ỳ', 'ỳ'), ('ỵ', 'ỵ'), ('ỷ', 'ỷ'), ('ỹ', 'ỹ'), + ('ỻ', 'ỻ'), ('ỽ', 'ỽ'), ('ỿ', 'ἇ'), ('ἐ', 'ἕ'), + ('ἠ', 'ἧ'), ('ἰ', 'ἷ'), ('ὀ', 'ὅ'), ('ὐ', 'ὗ'), + ('ὠ', 'ὧ'), ('ὰ', 'ώ'), ('ᾀ', 'ᾇ'), ('ᾐ', 'ᾗ'), + ('ᾠ', 'ᾧ'), ('ᾰ', 'ᾴ'), ('ᾶ', 'ᾷ'), ('ι', 'ι'), + ('ῂ', 'ῄ'), ('ῆ', 'ῇ'), ('ῐ', 'ΐ'), ('ῖ', 'ῗ'), + ('ῠ', 'ῧ'), ('ῲ', 'ῴ'), ('ῶ', 'ῷ'), ('ⁱ', 'ⁱ'), + ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ℊ', 'ℊ'), ('ℎ', 'ℏ'), + ('ℓ', 'ℓ'), ('ℯ', 'ℯ'), ('ℴ', 'ℴ'), ('ℹ', 'ℹ'), + ('ℼ', 'ℽ'), ('ⅆ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('ⅰ', 'ⅿ'), + ('ↄ', 'ↄ'), ('ⓐ', 'ⓩ'), ('ⰰ', 'ⱞ'), ('ⱡ', 'ⱡ'), + ('ⱥ', 'ⱦ'), ('ⱨ', 'ⱨ'), ('ⱪ', 'ⱪ'), ('ⱬ', 'ⱬ'), + ('ⱱ', 'ⱱ'), ('ⱳ', 'ⱴ'), ('ⱶ', 'ⱽ'), ('ⲁ', 'ⲁ'), + ('ⲃ', 'ⲃ'), ('ⲅ', 'ⲅ'), ('ⲇ', 'ⲇ'), ('ⲉ', 'ⲉ'), + ('ⲋ', 'ⲋ'), ('ⲍ', 'ⲍ'), ('ⲏ', 'ⲏ'), ('ⲑ', 'ⲑ'), + ('ⲓ', 'ⲓ'), ('ⲕ', 'ⲕ'), ('ⲗ', 'ⲗ'), ('ⲙ', 'ⲙ'), + ('ⲛ', 'ⲛ'), ('ⲝ', 'ⲝ'), ('ⲟ', 'ⲟ'), ('ⲡ', 'ⲡ'), + ('ⲣ', 'ⲣ'), ('ⲥ', 'ⲥ'), ('ⲧ', 'ⲧ'), ('ⲩ', 'ⲩ'), + ('ⲫ', 'ⲫ'), ('ⲭ', 'ⲭ'), ('ⲯ', 'ⲯ'), ('ⲱ', 'ⲱ'), + ('ⲳ', 'ⲳ'), ('ⲵ', 'ⲵ'), ('ⲷ', 'ⲷ'), ('ⲹ', 'ⲹ'), + ('ⲻ', 'ⲻ'), ('ⲽ', 'ⲽ'), ('ⲿ', 'ⲿ'), ('ⳁ', 'ⳁ'), + ('ⳃ', 'ⳃ'), ('ⳅ', 'ⳅ'), ('ⳇ', 'ⳇ'), ('ⳉ', 'ⳉ'), + ('ⳋ', 'ⳋ'), ('ⳍ', 'ⳍ'), ('ⳏ', 'ⳏ'), ('ⳑ', 'ⳑ'), + ('ⳓ', 'ⳓ'), ('ⳕ', 'ⳕ'), ('ⳗ', 'ⳗ'), ('ⳙ', 'ⳙ'), + ('ⳛ', 'ⳛ'), ('ⳝ', 'ⳝ'), ('ⳟ', 'ⳟ'), ('ⳡ', 'ⳡ'), + ('ⳣ', 'ⳤ'), ('ⳬ', 'ⳬ'), ('ⳮ', 'ⳮ'), ('ⳳ', 'ⳳ'), + ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ꙁ', 'ꙁ'), + ('ꙃ', 'ꙃ'), ('ꙅ', 'ꙅ'), ('ꙇ', 'ꙇ'), ('ꙉ', 'ꙉ'), + ('ꙋ', 'ꙋ'), ('ꙍ', 'ꙍ'), ('ꙏ', 'ꙏ'), ('ꙑ', 'ꙑ'), + ('ꙓ', 'ꙓ'), ('ꙕ', 'ꙕ'), ('ꙗ', 'ꙗ'), ('ꙙ', 'ꙙ'), + ('ꙛ', 'ꙛ'), ('ꙝ', 'ꙝ'), ('ꙟ', 'ꙟ'), ('ꙡ', 'ꙡ'), + ('ꙣ', 'ꙣ'), ('ꙥ', 'ꙥ'), ('ꙧ', 'ꙧ'), ('ꙩ', 'ꙩ'), + ('ꙫ', 'ꙫ'), ('ꙭ', 'ꙭ'), ('ꚁ', 'ꚁ'), ('ꚃ', 'ꚃ'), + ('ꚅ', 'ꚅ'), ('ꚇ', 'ꚇ'), ('ꚉ', 'ꚉ'), ('ꚋ', 'ꚋ'), + ('ꚍ', 'ꚍ'), ('ꚏ', 'ꚏ'), ('ꚑ', 'ꚑ'), ('ꚓ', 'ꚓ'), + ('ꚕ', 'ꚕ'), ('ꚗ', 'ꚗ'), ('ꚙ', 'ꚙ'), ('ꚛ', 'ꚝ'), + ('ꜣ', 'ꜣ'), ('ꜥ', 'ꜥ'), ('ꜧ', 'ꜧ'), ('ꜩ', 'ꜩ'), + ('ꜫ', 'ꜫ'), ('ꜭ', 'ꜭ'), ('ꜯ', 'ꜱ'), ('ꜳ', 'ꜳ'), + ('ꜵ', 'ꜵ'), ('ꜷ', 'ꜷ'), ('ꜹ', 'ꜹ'), ('ꜻ', 'ꜻ'), + ('ꜽ', 'ꜽ'), ('ꜿ', 'ꜿ'), ('ꝁ', 'ꝁ'), ('ꝃ', 'ꝃ'), + ('ꝅ', 'ꝅ'), ('ꝇ', 'ꝇ'), ('ꝉ', 'ꝉ'), ('ꝋ', 'ꝋ'), + ('ꝍ', 'ꝍ'), ('ꝏ', 'ꝏ'), ('ꝑ', 'ꝑ'), ('ꝓ', 'ꝓ'), + ('ꝕ', 'ꝕ'), ('ꝗ', 'ꝗ'), ('ꝙ', 'ꝙ'), ('ꝛ', 'ꝛ'), + ('ꝝ', 'ꝝ'), ('ꝟ', 'ꝟ'), ('ꝡ', 'ꝡ'), ('ꝣ', 'ꝣ'), + ('ꝥ', 'ꝥ'), ('ꝧ', 'ꝧ'), ('ꝩ', 'ꝩ'), ('ꝫ', 'ꝫ'), + ('ꝭ', 'ꝭ'), ('ꝯ', 'ꝸ'), ('ꝺ', 'ꝺ'), ('ꝼ', 'ꝼ'), + ('ꝿ', 'ꝿ'), ('ꞁ', 'ꞁ'), ('ꞃ', 'ꞃ'), ('ꞅ', 'ꞅ'), + ('ꞇ', 'ꞇ'), ('ꞌ', 'ꞌ'), ('ꞎ', 'ꞎ'), ('ꞑ', 'ꞑ'), + ('ꞓ', 'ꞕ'), ('ꞗ', 'ꞗ'), ('ꞙ', 'ꞙ'), ('ꞛ', 'ꞛ'), + ('ꞝ', 'ꞝ'), ('ꞟ', 'ꞟ'), ('ꞡ', 'ꞡ'), ('ꞣ', 'ꞣ'), + ('ꞥ', 'ꞥ'), ('ꞧ', 'ꞧ'), ('ꞩ', 'ꞩ'), ('ꞵ', 'ꞵ'), + ('ꞷ', 'ꞷ'), ('ꟸ', 'ꟺ'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭥ'), + ('ꭰ', 'ꮿ'), ('ff', 'st'), ('ﬓ', 'ﬗ'), ('a', 'z'), + ('𐐨', '𐑏'), ('𐓘', '𐓻'), ('𐳀', '𐳲'), ('𑣀', '𑣟'), + ('𝐚', '𝐳'), ('𝑎', '𝑔'), ('𝑖', '𝑧'), ('𝒂', '𝒛'), + ('𝒶', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝓏'), + ('𝓪', '𝔃'), ('𝔞', '𝔷'), ('𝕒', '𝕫'), ('𝖆', '𝖟'), + ('𝖺', '𝗓'), ('𝗮', '𝘇'), ('𝘢', '𝘻'), ('𝙖', '𝙯'), + ('𝚊', '𝚥'), ('𝛂', '𝛚'), ('𝛜', '𝛡'), ('𝛼', '𝜔'), + ('𝜖', '𝜛'), ('𝜶', '𝝎'), ('𝝐', '𝝕'), ('𝝰', '𝞈'), + ('𝞊', '𝞏'), ('𝞪', '𝟂'), ('𝟄', '𝟉'), ('𝟋', '𝟋'), + ('𞤢', '𞥃'), +]; + +pub const MATH: &'static [(char, char)] = &[ + ('+', '+'), ('<', '>'), ('^', '^'), ('|', '|'), ('~', '~'), ('¬', '¬'), + ('±', '±'), ('×', '×'), ('÷', '÷'), ('ϐ', 'ϒ'), ('ϕ', 'ϕ'), + ('ϰ', 'ϱ'), ('ϴ', '϶'), ('؆', '؈'), ('‖', '‖'), ('′', '‴'), + ('⁀', '⁀'), ('⁄', '⁄'), ('⁒', '⁒'), ('\u{2061}', '\u{2064}'), + ('⁺', '⁾'), ('₊', '₎'), ('⃐', '⃜'), ('⃡', '⃡'), + ('⃥', '⃦'), ('⃫', '⃯'), ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), + ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('℘', 'ℝ'), ('ℤ', 'ℤ'), + ('ℨ', '℩'), ('ℬ', 'ℭ'), ('ℯ', 'ℱ'), ('ℳ', 'ℸ'), + ('ℼ', 'ⅉ'), ('⅋', '⅋'), ('←', '↧'), ('↩', '↮'), + ('↰', '↱'), ('↶', '↷'), ('↼', '⇛'), ('⇝', '⇝'), + ('⇤', '⇥'), ('⇴', '⋿'), ('⌈', '⌋'), ('⌠', '⌡'), + ('⍼', '⍼'), ('⎛', '⎵'), ('⎷', '⎷'), ('⏐', '⏐'), + ('⏜', '⏢'), ('■', '□'), ('▮', '▷'), ('▼', '◁'), + ('◆', '◇'), ('◊', '○'), ('●', '◓'), ('◢', '◢'), + ('◤', '◤'), ('◧', '◬'), ('◸', '◿'), ('★', '☆'), + ('♀', '♀'), ('♂', '♂'), ('♠', '♣'), ('♭', '♯'), + ('⟀', '⟿'), ('⤀', '⫿'), ('⬰', '⭄'), ('⭇', '⭌'), + ('﬩', '﬩'), ('﹡', '﹦'), ('﹨', '﹨'), ('+', '+'), + ('<', '>'), ('\', '\'), ('^', '^'), ('|', '|'), + ('~', '~'), ('¬', '¬'), ('←', '↓'), ('𝐀', '𝑔'), + ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), + ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), + ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), + ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), + ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝟋'), ('𝟎', '𝟿'), + ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), + ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), + ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), + ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), + ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), + ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), + ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), + ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), + ('𞺫', '𞺻'), ('𞻰', '𞻱'), +]; + +pub const NONCHARACTER_CODE_POINT: &'static [(char, char)] = &[ + ('\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}'), +]; + +pub const OTHER_ALPHABETIC: &'static [(char, char)] = &[ + ('ͅ', 'ͅ'), ('ְ', 'ֽ'), ('ֿ', 'ֿ'), ('ׁ', 'ׂ'), ('ׄ', 'ׅ'), + ('ׇ', 'ׇ'), ('ؐ', 'ؚ'), ('ً', 'ٗ'), ('ٙ', 'ٟ'), ('ٰ', 'ٰ'), + ('ۖ', 'ۜ'), ('ۡ', 'ۤ'), ('ۧ', 'ۨ'), ('ۭ', 'ۭ'), ('ܑ', 'ܑ'), + ('ܰ', 'ܿ'), ('ަ', 'ް'), ('ࠖ', 'ࠗ'), ('ࠛ', 'ࠣ'), ('ࠥ', 'ࠧ'), + ('ࠩ', 'ࠬ'), ('ࣔ', 'ࣟ'), ('ࣣ', 'ࣩ'), ('ࣰ', 'ः'), + ('ऺ', 'ऻ'), ('ा', 'ौ'), ('ॎ', 'ॏ'), ('ॕ', 'ॗ'), + ('ॢ', 'ॣ'), ('ঁ', 'ঃ'), ('া', 'ৄ'), ('ে', 'ৈ'), + ('ো', 'ৌ'), ('ৗ', 'ৗ'), ('ৢ', 'ৣ'), ('ਁ', 'ਃ'), + ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', 'ੌ'), ('ੑ', 'ੑ'), + ('ੰ', 'ੱ'), ('ੵ', 'ੵ'), ('ઁ', 'ઃ'), ('ા', 'ૅ'), + ('ે', 'ૉ'), ('ો', 'ૌ'), ('ૢ', 'ૣ'), ('ૺ', 'ૼ'), + ('ଁ', 'ଃ'), ('ା', 'ୄ'), ('େ', 'ୈ'), ('ୋ', 'ୌ'), + ('ୖ', 'ୗ'), ('ୢ', 'ୣ'), ('ஂ', 'ஂ'), ('ா', 'ூ'), + ('ெ', 'ை'), ('ொ', 'ௌ'), ('ௗ', 'ௗ'), ('ఀ', 'ః'), + ('ా', 'ౄ'), ('ె', 'ై'), ('ొ', 'ౌ'), ('ౕ', 'ౖ'), + ('ౢ', 'ౣ'), ('ಁ', 'ಃ'), ('ಾ', 'ೄ'), ('ೆ', 'ೈ'), + ('ೊ', 'ೌ'), ('ೕ', 'ೖ'), ('ೢ', 'ೣ'), ('ഀ', 'ഃ'), + ('ാ', 'ൄ'), ('െ', 'ൈ'), ('ൊ', 'ൌ'), ('ൗ', 'ൗ'), + ('ൢ', 'ൣ'), ('ං', 'ඃ'), ('ා', 'ු'), ('ූ', 'ූ'), + ('ෘ', 'ෟ'), ('ෲ', 'ෳ'), ('ั', 'ั'), ('ิ', 'ฺ'), + ('ํ', 'ํ'), ('ັ', 'ັ'), ('ິ', 'ູ'), ('ົ', 'ຼ'), + ('ໍ', 'ໍ'), ('ཱ', 'ཱྀ'), ('ྍ', 'ྗ'), ('ྙ', 'ྼ'), + ('ါ', 'ံ'), ('း', 'း'), ('ျ', 'ှ'), ('ၖ', 'ၙ'), + ('ၞ', 'ၠ'), ('ၢ', 'ၢ'), ('ၧ', 'ၨ'), ('ၱ', 'ၴ'), + ('ႂ', 'ႆ'), ('ႜ', 'ႝ'), ('፟', '፟'), ('ᜒ', 'ᜓ'), + ('ᜲ', 'ᜳ'), ('ᝒ', 'ᝓ'), ('ᝲ', 'ᝳ'), ('ា', 'ៈ'), + ('ᢅ', 'ᢆ'), ('ᢩ', 'ᢩ'), ('ᤠ', 'ᤫ'), ('ᤰ', 'ᤸ'), + ('ᨗ', 'ᨛ'), ('ᩕ', 'ᩞ'), ('ᩡ', 'ᩴ'), ('ᬀ', 'ᬄ'), + ('ᬵ', 'ᭃ'), ('ᮀ', 'ᮂ'), ('ᮡ', 'ᮩ'), ('ᮬ', 'ᮭ'), + ('ᯧ', 'ᯱ'), ('ᰤ', 'ᰵ'), ('ᳲ', 'ᳳ'), ('ᷧ', 'ᷴ'), + ('Ⓐ', 'ⓩ'), ('ⷠ', 'ⷿ'), ('ꙴ', 'ꙻ'), ('ꚞ', 'ꚟ'), + ('ꠣ', 'ꠧ'), ('ꢀ', 'ꢁ'), ('ꢴ', 'ꣃ'), ('ꣅ', 'ꣅ'), + ('ꤦ', 'ꤪ'), ('ꥇ', 'ꥒ'), ('ꦀ', 'ꦃ'), ('ꦴ', 'ꦿ'), + ('ꨩ', 'ꨶ'), ('ꩃ', 'ꩃ'), ('ꩌ', 'ꩍ'), ('ꪰ', 'ꪰ'), + ('ꪲ', 'ꪴ'), ('ꪷ', 'ꪸ'), ('ꪾ', 'ꪾ'), ('ꫫ', 'ꫯ'), + ('ꫵ', 'ꫵ'), ('ꯣ', 'ꯪ'), ('ﬞ', 'ﬞ'), ('𐍶', '𐍺'), + ('𐨁', '𐨃'), ('𐨅', '𐨆'), ('𐨌', '𐨏'), ('𑀀', '𑀂'), + ('𑀸', '𑁅'), ('𑂂', '𑂂'), ('𑂰', '𑂸'), ('𑄀', '𑄂'), + ('𑄧', '𑄲'), ('𑆀', '𑆂'), ('𑆳', '𑆿'), ('𑈬', '𑈴'), + ('𑈷', '𑈷'), ('𑈾', '𑈾'), ('𑋟', '𑋨'), ('𑌀', '𑌃'), + ('𑌾', '𑍄'), ('𑍇', '𑍈'), ('𑍋', '𑍌'), ('𑍗', '𑍗'), + ('𑍢', '𑍣'), ('𑐵', '𑑁'), ('𑑃', '𑑅'), ('𑒰', '𑓁'), + ('𑖯', '𑖵'), ('𑖸', '𑖾'), ('𑗜', '𑗝'), ('𑘰', '𑘾'), + ('𑙀', '𑙀'), ('𑚫', '𑚵'), ('𑜝', '𑜪'), ('𑨁', '𑨊'), + ('𑨵', '𑨹'), ('𑨻', '𑨾'), ('𑩑', '𑩛'), ('𑪊', '𑪗'), + ('𑰯', '𑰶'), ('𑰸', '𑰾'), ('𑲒', '𑲧'), ('𑲩', '𑲶'), + ('𑴱', '𑴶'), ('𑴺', '𑴺'), ('𑴼', '𑴽'), ('𑴿', '𑵁'), + ('𑵃', '𑵃'), ('𑵇', '𑵇'), ('𖬰', '𖬶'), ('𖽑', '𖽾'), + ('𛲞', '𛲞'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), ('𞀛', '𞀡'), + ('𞀣', '𞀤'), ('𞀦', '𞀪'), ('𞥇', '𞥇'), ('🄰', '🅉'), + ('🅐', '🅩'), ('🅰', '🆉'), +]; + +pub const OTHER_DEFAULT_IGNORABLE_CODE_POINT: &'static [(char, char)] = &[ + ('͏', '͏'), ('ᅟ', 'ᅠ'), ('឴', '឵'), ('\u{2065}', '\u{2065}'), + ('ㅤ', 'ㅤ'), ('ᅠ', 'ᅠ'), ('\u{fff0}', '\u{fff8}'), + ('\u{e0000}', '\u{e0000}'), ('\u{e0002}', '\u{e001f}'), + ('\u{e0080}', '\u{e00ff}'), ('\u{e01f0}', '\u{e0fff}'), +]; + +pub const OTHER_GRAPHEME_EXTEND: &'static [(char, char)] = &[ + ('া', 'া'), ('ৗ', 'ৗ'), ('ା', 'ା'), ('ୗ', 'ୗ'), + ('ா', 'ா'), ('ௗ', 'ௗ'), ('ೂ', 'ೂ'), ('ೕ', 'ೖ'), + ('ാ', 'ാ'), ('ൗ', 'ൗ'), ('ා', 'ා'), ('ෟ', 'ෟ'), + ('\u{200c}', '\u{200c}'), ('〮', '〯'), ('゙', '゚'), ('𑌾', '𑌾'), + ('𑍗', '𑍗'), ('𑒰', '𑒰'), ('𑒽', '𑒽'), ('𑖯', '𑖯'), + ('𝅥', '𝅥'), ('𝅮', '𝅲'), ('\u{e0020}', '\u{e007f}'), +]; + +pub const OTHER_ID_CONTINUE: &'static [(char, char)] = &[ + ('·', '·'), ('·', '·'), ('፩', '፱'), ('᧚', '᧚'), +]; + +pub const OTHER_ID_START: &'static [(char, char)] = &[ + ('ᢅ', 'ᢆ'), ('℘', '℘'), ('℮', '℮'), ('゛', '゜'), +]; + +pub const OTHER_LOWERCASE: &'static [(char, char)] = &[ + ('ª', 'ª'), ('º', 'º'), ('ʰ', 'ʸ'), ('ˀ', 'ˁ'), ('ˠ', 'ˤ'), + ('ͅ', 'ͅ'), ('ͺ', 'ͺ'), ('ᴬ', 'ᵪ'), ('ᵸ', 'ᵸ'), ('ᶛ', 'ᶿ'), + ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ⅰ', 'ⅿ'), + ('ⓐ', 'ⓩ'), ('ⱼ', 'ⱽ'), ('ꚜ', 'ꚝ'), ('ꝰ', 'ꝰ'), + ('ꟸ', 'ꟹ'), ('ꭜ', 'ꭟ'), +]; + +pub const OTHER_MATH: &'static [(char, char)] = &[ + ('^', '^'), ('ϐ', 'ϒ'), ('ϕ', 'ϕ'), ('ϰ', 'ϱ'), ('ϴ', 'ϵ'), + ('‖', '‖'), ('′', '‴'), ('⁀', '⁀'), ('\u{2061}', '\u{2064}'), + ('⁽', '⁾'), ('₍', '₎'), ('⃐', '⃜'), ('⃡', '⃡'), + ('⃥', '⃦'), ('⃫', '⃯'), ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), + ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), + ('ℨ', '℩'), ('ℬ', 'ℭ'), ('ℯ', 'ℱ'), ('ℳ', 'ℸ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('↕', '↙'), ('↜', '↟'), + ('↡', '↢'), ('↤', '↥'), ('↧', '↧'), ('↩', '↭'), + ('↰', '↱'), ('↶', '↷'), ('↼', '⇍'), ('⇐', '⇑'), + ('⇓', '⇓'), ('⇕', '⇛'), ('⇝', '⇝'), ('⇤', '⇥'), + ('⌈', '⌋'), ('⎴', '⎵'), ('⎷', '⎷'), ('⏐', '⏐'), + ('⏢', '⏢'), ('■', '□'), ('▮', '▶'), ('▼', '◀'), + ('◆', '◇'), ('◊', '○'), ('●', '◓'), ('◢', '◢'), + ('◤', '◤'), ('◧', '◬'), ('★', '☆'), ('♀', '♀'), + ('♂', '♂'), ('♠', '♣'), ('♭', '♮'), ('⟅', '⟆'), + ('⟦', '⟯'), ('⦃', '⦘'), ('⧘', '⧛'), ('⧼', '⧽'), + ('﹡', '﹡'), ('﹣', '﹣'), ('﹨', '﹨'), ('\', '\'), + ('^', '^'), ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), + ('𝒢', '𝒢'), ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), + ('𝒻', '𝒻'), ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), + ('𝔍', '𝔔'), ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), + ('𝕀', '𝕄'), ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), + ('𝚨', '𝛀'), ('𝛂', '𝛚'), ('𝛜', '𝛺'), ('𝛼', '𝜔'), + ('𝜖', '𝜴'), ('𝜶', '𝝎'), ('𝝐', '𝝮'), ('𝝰', '𝞈'), + ('𝞊', '𝞨'), ('𝞪', '𝟂'), ('𝟄', '𝟋'), ('𝟎', '𝟿'), + ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), + ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), + ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), + ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), + ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), + ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), + ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), + ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), + ('𞺫', '𞺻'), +]; + +pub const OTHER_UPPERCASE: &'static [(char, char)] = &[ + ('Ⅰ', 'Ⅿ'), ('Ⓐ', 'Ⓩ'), ('🄰', '🅉'), ('🅐', '🅩'), + ('🅰', '🆉'), +]; + +pub const PATTERN_SYNTAX: &'static [(char, char)] = &[ + ('!', '/'), (':', '@'), ('[', '^'), ('`', '`'), ('{', '~'), ('¡', '§'), + ('©', '©'), ('«', '¬'), ('®', '®'), ('°', '±'), ('¶', '¶'), + ('»', '»'), ('¿', '¿'), ('×', '×'), ('÷', '÷'), ('‐', '‧'), + ('‰', '‾'), ('⁁', '⁓'), ('⁕', '⁞'), ('←', '\u{245f}'), + ('─', '❵'), ('➔', '\u{2bff}'), ('⸀', '\u{2e7f}'), ('、', '〃'), + ('〈', '〠'), ('〰', '〰'), ('﴾', '﴿'), ('﹅', '﹆'), +]; + +pub const PATTERN_WHITE_SPACE: &'static [(char, char)] = &[ + ('\t', '\r'), (' ', ' '), ('\u{85}', '\u{85}'), ('\u{200e}', '\u{200f}'), + ('\u{2028}', '\u{2029}'), +]; + +pub const PREPENDED_CONCATENATION_MARK: &'static [(char, char)] = &[ + ('\u{600}', '\u{605}'), ('\u{6dd}', '\u{6dd}'), ('\u{70f}', '\u{70f}'), + ('\u{8e2}', '\u{8e2}'), ('\u{110bd}', '\u{110bd}'), +]; + +pub const QUOTATION_MARK: &'static [(char, char)] = &[ + ('\"', '\"'), ('\'', '\''), ('«', '«'), ('»', '»'), ('‘', '‟'), + ('‹', '›'), ('⹂', '⹂'), ('「', '』'), ('〝', '〟'), + ('﹁', '﹄'), ('"', '"'), (''', '''), ('「', '」'), +]; + +pub const RADICAL: &'static [(char, char)] = &[ + ('⺀', '⺙'), ('⺛', '⻳'), ('⼀', '⿕'), +]; + +pub const REGIONAL_INDICATOR: &'static [(char, char)] = &[ + ('🇦', '🇿'), +]; + +pub const SENTENCE_TERMINAL: &'static [(char, char)] = &[ + ('!', '!'), ('.', '.'), ('?', '?'), ('։', '։'), ('؟', '؟'), + ('۔', '۔'), ('܀', '܂'), ('߹', '߹'), ('।', '॥'), ('၊', '။'), + ('።', '።'), ('፧', '፨'), ('᙮', '᙮'), ('᜵', '᜶'), + ('᠃', '᠃'), ('᠉', '᠉'), ('᥄', '᥅'), ('᪨', '᪫'), + ('᭚', '᭛'), ('᭞', '᭟'), ('᰻', '᰼'), ('᱾', '᱿'), + ('‼', '‽'), ('⁇', '⁉'), ('⸮', '⸮'), ('⸼', '⸼'), + ('。', '。'), ('꓿', '꓿'), ('꘎', '꘏'), ('꛳', '꛳'), + ('꛷', '꛷'), ('꡶', '꡷'), ('꣎', '꣏'), ('꤯', '꤯'), + ('꧈', '꧉'), ('꩝', '꩟'), ('꫰', '꫱'), ('꯫', '꯫'), + ('﹒', '﹒'), ('﹖', '﹗'), ('!', '!'), ('.', '.'), + ('?', '?'), ('。', '。'), ('𐩖', '𐩗'), ('𑁇', '𑁈'), + ('𑂾', '𑃁'), ('𑅁', '𑅃'), ('𑇅', '𑇆'), ('𑇍', '𑇍'), + ('𑇞', '𑇟'), ('𑈸', '𑈹'), ('𑈻', '𑈼'), ('𑊩', '𑊩'), + ('𑑋', '𑑌'), ('𑗂', '𑗃'), ('𑗉', '𑗗'), ('𑙁', '𑙂'), + ('𑜼', '𑜾'), ('𑩂', '𑩃'), ('𑪛', '𑪜'), ('𑱁', '𑱂'), + ('𖩮', '𖩯'), ('𖫵', '𖫵'), ('𖬷', '𖬸'), ('𖭄', '𖭄'), + ('𛲟', '𛲟'), ('𝪈', '𝪈'), +]; + +pub const SOFT_DOTTED: &'static [(char, char)] = &[ + ('i', 'j'), ('į', 'į'), ('ɉ', 'ɉ'), ('ɨ', 'ɨ'), ('ʝ', 'ʝ'), + ('ʲ', 'ʲ'), ('ϳ', 'ϳ'), ('і', 'і'), ('ј', 'ј'), ('ᵢ', 'ᵢ'), + ('ᶖ', 'ᶖ'), ('ᶤ', 'ᶤ'), ('ᶨ', 'ᶨ'), ('ḭ', 'ḭ'), + ('ị', 'ị'), ('ⁱ', 'ⁱ'), ('ⅈ', 'ⅉ'), ('ⱼ', 'ⱼ'), + ('𝐢', '𝐣'), ('𝑖', '𝑗'), ('𝒊', '𝒋'), ('𝒾', '𝒿'), + ('𝓲', '𝓳'), ('𝔦', '𝔧'), ('𝕚', '𝕛'), ('𝖎', '𝖏'), + ('𝗂', '𝗃'), ('𝗶', '𝗷'), ('𝘪', '𝘫'), ('𝙞', '𝙟'), + ('𝚒', '𝚓'), +]; + +pub const TERMINAL_PUNCTUATION: &'static [(char, char)] = &[ + ('!', '!'), (',', ','), ('.', '.'), (':', ';'), ('?', '?'), (';', ';'), + ('·', '·'), ('։', '։'), ('׃', '׃'), ('،', '،'), ('؛', '؛'), + ('؟', '؟'), ('۔', '۔'), ('܀', '܊'), ('܌', '܌'), ('߸', '߹'), + ('࠰', '࠾'), ('࡞', '࡞'), ('।', '॥'), ('๚', '๛'), + ('༈', '༈'), ('།', '༒'), ('၊', '။'), ('፡', '፨'), + ('᙭', '᙮'), ('᛫', '᛭'), ('᜵', '᜶'), ('។', '៖'), + ('៚', '៚'), ('᠂', '᠅'), ('᠈', '᠉'), ('᥄', '᥅'), + ('᪨', '᪫'), ('᭚', '᭛'), ('᭝', '᭟'), ('᰻', '᰿'), + ('᱾', '᱿'), ('‼', '‽'), ('⁇', '⁉'), ('⸮', '⸮'), + ('⸼', '⸼'), ('⹁', '⹁'), ('、', '。'), ('꓾', '꓿'), + ('꘍', '꘏'), ('꛳', '꛷'), ('꡶', '꡷'), ('꣎', '꣏'), + ('꤯', '꤯'), ('꧇', '꧉'), ('꩝', '꩟'), ('꫟', '꫟'), + ('꫰', '꫱'), ('꯫', '꯫'), ('﹐', '﹒'), ('﹔', '﹗'), + ('!', '!'), (',', ','), ('.', '.'), (':', ';'), + ('?', '?'), ('。', '。'), ('、', '、'), ('𐎟', '𐎟'), + ('𐏐', '𐏐'), ('𐡗', '𐡗'), ('𐤟', '𐤟'), ('𐩖', '𐩗'), + ('𐫰', '𐫵'), ('𐬺', '𐬿'), ('𐮙', '𐮜'), ('𑁇', '𑁍'), + ('𑂾', '𑃁'), ('𑅁', '𑅃'), ('𑇅', '𑇆'), ('𑇍', '𑇍'), + ('𑇞', '𑇟'), ('𑈸', '𑈼'), ('𑊩', '𑊩'), ('𑑋', '𑑍'), + ('𑑛', '𑑛'), ('𑗂', '𑗅'), ('𑗉', '𑗗'), ('𑙁', '𑙂'), + ('𑜼', '𑜾'), ('𑩂', '𑩃'), ('𑪛', '𑪜'), ('𑪡', '𑪢'), + ('𑱁', '𑱃'), ('𑱱', '𑱱'), ('𒑰', '𒑴'), ('𖩮', '𖩯'), + ('𖫵', '𖫵'), ('𖬷', '𖬹'), ('𖭄', '𖭄'), ('𛲟', '𛲟'), + ('𝪇', '𝪊'), +]; + +pub const UNIFIED_IDEOGRAPH: &'static [(char, char)] = &[ + ('㐀', '䶵'), ('一', '鿪'), ('﨎', '﨏'), ('﨑', '﨑'), + ('﨓', '﨔'), ('﨟', '﨟'), ('﨡', '﨡'), ('﨣', '﨤'), + ('﨧', '﨩'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), ('𫝀', '𫠝'), + ('𫠠', '𬺡'), ('𬺰', '𮯠'), +]; + +pub const UPPERCASE: &'static [(char, char)] = &[ + ('A', 'Z'), ('À', 'Ö'), ('Ø', 'Þ'), ('Ā', 'Ā'), ('Ă', 'Ă'), + ('Ą', 'Ą'), ('Ć', 'Ć'), ('Ĉ', 'Ĉ'), ('Ċ', 'Ċ'), ('Č', 'Č'), + ('Ď', 'Ď'), ('Đ', 'Đ'), ('Ē', 'Ē'), ('Ĕ', 'Ĕ'), ('Ė', 'Ė'), + ('Ę', 'Ę'), ('Ě', 'Ě'), ('Ĝ', 'Ĝ'), ('Ğ', 'Ğ'), ('Ġ', 'Ġ'), + ('Ģ', 'Ģ'), ('Ĥ', 'Ĥ'), ('Ħ', 'Ħ'), ('Ĩ', 'Ĩ'), ('Ī', 'Ī'), + ('Ĭ', 'Ĭ'), ('Į', 'Į'), ('İ', 'İ'), ('IJ', 'IJ'), ('Ĵ', 'Ĵ'), + ('Ķ', 'Ķ'), ('Ĺ', 'Ĺ'), ('Ļ', 'Ļ'), ('Ľ', 'Ľ'), ('Ŀ', 'Ŀ'), + ('Ł', 'Ł'), ('Ń', 'Ń'), ('Ņ', 'Ņ'), ('Ň', 'Ň'), ('Ŋ', 'Ŋ'), + ('Ō', 'Ō'), ('Ŏ', 'Ŏ'), ('Ő', 'Ő'), ('Œ', 'Œ'), ('Ŕ', 'Ŕ'), + ('Ŗ', 'Ŗ'), ('Ř', 'Ř'), ('Ś', 'Ś'), ('Ŝ', 'Ŝ'), ('Ş', 'Ş'), + ('Š', 'Š'), ('Ţ', 'Ţ'), ('Ť', 'Ť'), ('Ŧ', 'Ŧ'), ('Ũ', 'Ũ'), + ('Ū', 'Ū'), ('Ŭ', 'Ŭ'), ('Ů', 'Ů'), ('Ű', 'Ű'), ('Ų', 'Ų'), + ('Ŵ', 'Ŵ'), ('Ŷ', 'Ŷ'), ('Ÿ', 'Ź'), ('Ż', 'Ż'), ('Ž', 'Ž'), + ('Ɓ', 'Ƃ'), ('Ƅ', 'Ƅ'), ('Ɔ', 'Ƈ'), ('Ɖ', 'Ƌ'), ('Ǝ', 'Ƒ'), + ('Ɠ', 'Ɣ'), ('Ɩ', 'Ƙ'), ('Ɯ', 'Ɲ'), ('Ɵ', 'Ơ'), ('Ƣ', 'Ƣ'), + ('Ƥ', 'Ƥ'), ('Ʀ', 'Ƨ'), ('Ʃ', 'Ʃ'), ('Ƭ', 'Ƭ'), ('Ʈ', 'Ư'), + ('Ʊ', 'Ƴ'), ('Ƶ', 'Ƶ'), ('Ʒ', 'Ƹ'), ('Ƽ', 'Ƽ'), ('DŽ', 'DŽ'), + ('LJ', 'LJ'), ('NJ', 'NJ'), ('Ǎ', 'Ǎ'), ('Ǐ', 'Ǐ'), ('Ǒ', 'Ǒ'), + ('Ǔ', 'Ǔ'), ('Ǖ', 'Ǖ'), ('Ǘ', 'Ǘ'), ('Ǚ', 'Ǚ'), ('Ǜ', 'Ǜ'), + ('Ǟ', 'Ǟ'), ('Ǡ', 'Ǡ'), ('Ǣ', 'Ǣ'), ('Ǥ', 'Ǥ'), ('Ǧ', 'Ǧ'), + ('Ǩ', 'Ǩ'), ('Ǫ', 'Ǫ'), ('Ǭ', 'Ǭ'), ('Ǯ', 'Ǯ'), ('DZ', 'DZ'), + ('Ǵ', 'Ǵ'), ('Ƕ', 'Ǹ'), ('Ǻ', 'Ǻ'), ('Ǽ', 'Ǽ'), ('Ǿ', 'Ǿ'), + ('Ȁ', 'Ȁ'), ('Ȃ', 'Ȃ'), ('Ȅ', 'Ȅ'), ('Ȇ', 'Ȇ'), ('Ȉ', 'Ȉ'), + ('Ȋ', 'Ȋ'), ('Ȍ', 'Ȍ'), ('Ȏ', 'Ȏ'), ('Ȑ', 'Ȑ'), ('Ȓ', 'Ȓ'), + ('Ȕ', 'Ȕ'), ('Ȗ', 'Ȗ'), ('Ș', 'Ș'), ('Ț', 'Ț'), ('Ȝ', 'Ȝ'), + ('Ȟ', 'Ȟ'), ('Ƞ', 'Ƞ'), ('Ȣ', 'Ȣ'), ('Ȥ', 'Ȥ'), ('Ȧ', 'Ȧ'), + ('Ȩ', 'Ȩ'), ('Ȫ', 'Ȫ'), ('Ȭ', 'Ȭ'), ('Ȯ', 'Ȯ'), ('Ȱ', 'Ȱ'), + ('Ȳ', 'Ȳ'), ('Ⱥ', 'Ȼ'), ('Ƚ', 'Ⱦ'), ('Ɂ', 'Ɂ'), ('Ƀ', 'Ɇ'), + ('Ɉ', 'Ɉ'), ('Ɋ', 'Ɋ'), ('Ɍ', 'Ɍ'), ('Ɏ', 'Ɏ'), ('Ͱ', 'Ͱ'), + ('Ͳ', 'Ͳ'), ('Ͷ', 'Ͷ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), + ('Ό', 'Ό'), ('Ύ', 'Ώ'), ('Α', 'Ρ'), ('Σ', 'Ϋ'), ('Ϗ', 'Ϗ'), + ('ϒ', 'ϔ'), ('Ϙ', 'Ϙ'), ('Ϛ', 'Ϛ'), ('Ϝ', 'Ϝ'), ('Ϟ', 'Ϟ'), + ('Ϡ', 'Ϡ'), ('Ϣ', 'Ϣ'), ('Ϥ', 'Ϥ'), ('Ϧ', 'Ϧ'), ('Ϩ', 'Ϩ'), + ('Ϫ', 'Ϫ'), ('Ϭ', 'Ϭ'), ('Ϯ', 'Ϯ'), ('ϴ', 'ϴ'), ('Ϸ', 'Ϸ'), + ('Ϲ', 'Ϻ'), ('Ͻ', 'Я'), ('Ѡ', 'Ѡ'), ('Ѣ', 'Ѣ'), ('Ѥ', 'Ѥ'), + ('Ѧ', 'Ѧ'), ('Ѩ', 'Ѩ'), ('Ѫ', 'Ѫ'), ('Ѭ', 'Ѭ'), ('Ѯ', 'Ѯ'), + ('Ѱ', 'Ѱ'), ('Ѳ', 'Ѳ'), ('Ѵ', 'Ѵ'), ('Ѷ', 'Ѷ'), ('Ѹ', 'Ѹ'), + ('Ѻ', 'Ѻ'), ('Ѽ', 'Ѽ'), ('Ѿ', 'Ѿ'), ('Ҁ', 'Ҁ'), ('Ҋ', 'Ҋ'), + ('Ҍ', 'Ҍ'), ('Ҏ', 'Ҏ'), ('Ґ', 'Ґ'), ('Ғ', 'Ғ'), ('Ҕ', 'Ҕ'), + ('Җ', 'Җ'), ('Ҙ', 'Ҙ'), ('Қ', 'Қ'), ('Ҝ', 'Ҝ'), ('Ҟ', 'Ҟ'), + ('Ҡ', 'Ҡ'), ('Ң', 'Ң'), ('Ҥ', 'Ҥ'), ('Ҧ', 'Ҧ'), ('Ҩ', 'Ҩ'), + ('Ҫ', 'Ҫ'), ('Ҭ', 'Ҭ'), ('Ү', 'Ү'), ('Ұ', 'Ұ'), ('Ҳ', 'Ҳ'), + ('Ҵ', 'Ҵ'), ('Ҷ', 'Ҷ'), ('Ҹ', 'Ҹ'), ('Һ', 'Һ'), ('Ҽ', 'Ҽ'), + ('Ҿ', 'Ҿ'), ('Ӏ', 'Ӂ'), ('Ӄ', 'Ӄ'), ('Ӆ', 'Ӆ'), ('Ӈ', 'Ӈ'), + ('Ӊ', 'Ӊ'), ('Ӌ', 'Ӌ'), ('Ӎ', 'Ӎ'), ('Ӑ', 'Ӑ'), ('Ӓ', 'Ӓ'), + ('Ӕ', 'Ӕ'), ('Ӗ', 'Ӗ'), ('Ә', 'Ә'), ('Ӛ', 'Ӛ'), ('Ӝ', 'Ӝ'), + ('Ӟ', 'Ӟ'), ('Ӡ', 'Ӡ'), ('Ӣ', 'Ӣ'), ('Ӥ', 'Ӥ'), ('Ӧ', 'Ӧ'), + ('Ө', 'Ө'), ('Ӫ', 'Ӫ'), ('Ӭ', 'Ӭ'), ('Ӯ', 'Ӯ'), ('Ӱ', 'Ӱ'), + ('Ӳ', 'Ӳ'), ('Ӵ', 'Ӵ'), ('Ӷ', 'Ӷ'), ('Ӹ', 'Ӹ'), ('Ӻ', 'Ӻ'), + ('Ӽ', 'Ӽ'), ('Ӿ', 'Ӿ'), ('Ԁ', 'Ԁ'), ('Ԃ', 'Ԃ'), ('Ԅ', 'Ԅ'), + ('Ԇ', 'Ԇ'), ('Ԉ', 'Ԉ'), ('Ԋ', 'Ԋ'), ('Ԍ', 'Ԍ'), ('Ԏ', 'Ԏ'), + ('Ԑ', 'Ԑ'), ('Ԓ', 'Ԓ'), ('Ԕ', 'Ԕ'), ('Ԗ', 'Ԗ'), ('Ԙ', 'Ԙ'), + ('Ԛ', 'Ԛ'), ('Ԝ', 'Ԝ'), ('Ԟ', 'Ԟ'), ('Ԡ', 'Ԡ'), ('Ԣ', 'Ԣ'), + ('Ԥ', 'Ԥ'), ('Ԧ', 'Ԧ'), ('Ԩ', 'Ԩ'), ('Ԫ', 'Ԫ'), ('Ԭ', 'Ԭ'), + ('Ԯ', 'Ԯ'), ('Ա', 'Ֆ'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('Ꭰ', 'Ᏽ'), ('Ḁ', 'Ḁ'), ('Ḃ', 'Ḃ'), ('Ḅ', 'Ḅ'), + ('Ḇ', 'Ḇ'), ('Ḉ', 'Ḉ'), ('Ḋ', 'Ḋ'), ('Ḍ', 'Ḍ'), + ('Ḏ', 'Ḏ'), ('Ḑ', 'Ḑ'), ('Ḓ', 'Ḓ'), ('Ḕ', 'Ḕ'), + ('Ḗ', 'Ḗ'), ('Ḙ', 'Ḙ'), ('Ḛ', 'Ḛ'), ('Ḝ', 'Ḝ'), + ('Ḟ', 'Ḟ'), ('Ḡ', 'Ḡ'), ('Ḣ', 'Ḣ'), ('Ḥ', 'Ḥ'), + ('Ḧ', 'Ḧ'), ('Ḩ', 'Ḩ'), ('Ḫ', 'Ḫ'), ('Ḭ', 'Ḭ'), + ('Ḯ', 'Ḯ'), ('Ḱ', 'Ḱ'), ('Ḳ', 'Ḳ'), ('Ḵ', 'Ḵ'), + ('Ḷ', 'Ḷ'), ('Ḹ', 'Ḹ'), ('Ḻ', 'Ḻ'), ('Ḽ', 'Ḽ'), + ('Ḿ', 'Ḿ'), ('Ṁ', 'Ṁ'), ('Ṃ', 'Ṃ'), ('Ṅ', 'Ṅ'), + ('Ṇ', 'Ṇ'), ('Ṉ', 'Ṉ'), ('Ṋ', 'Ṋ'), ('Ṍ', 'Ṍ'), + ('Ṏ', 'Ṏ'), ('Ṑ', 'Ṑ'), ('Ṓ', 'Ṓ'), ('Ṕ', 'Ṕ'), + ('Ṗ', 'Ṗ'), ('Ṙ', 'Ṙ'), ('Ṛ', 'Ṛ'), ('Ṝ', 'Ṝ'), + ('Ṟ', 'Ṟ'), ('Ṡ', 'Ṡ'), ('Ṣ', 'Ṣ'), ('Ṥ', 'Ṥ'), + ('Ṧ', 'Ṧ'), ('Ṩ', 'Ṩ'), ('Ṫ', 'Ṫ'), ('Ṭ', 'Ṭ'), + ('Ṯ', 'Ṯ'), ('Ṱ', 'Ṱ'), ('Ṳ', 'Ṳ'), ('Ṵ', 'Ṵ'), + ('Ṷ', 'Ṷ'), ('Ṹ', 'Ṹ'), ('Ṻ', 'Ṻ'), ('Ṽ', 'Ṽ'), + ('Ṿ', 'Ṿ'), ('Ẁ', 'Ẁ'), ('Ẃ', 'Ẃ'), ('Ẅ', 'Ẅ'), + ('Ẇ', 'Ẇ'), ('Ẉ', 'Ẉ'), ('Ẋ', 'Ẋ'), ('Ẍ', 'Ẍ'), + ('Ẏ', 'Ẏ'), ('Ẑ', 'Ẑ'), ('Ẓ', 'Ẓ'), ('Ẕ', 'Ẕ'), + ('ẞ', 'ẞ'), ('Ạ', 'Ạ'), ('Ả', 'Ả'), ('Ấ', 'Ấ'), + ('Ầ', 'Ầ'), ('Ẩ', 'Ẩ'), ('Ẫ', 'Ẫ'), ('Ậ', 'Ậ'), + ('Ắ', 'Ắ'), ('Ằ', 'Ằ'), ('Ẳ', 'Ẳ'), ('Ẵ', 'Ẵ'), + ('Ặ', 'Ặ'), ('Ẹ', 'Ẹ'), ('Ẻ', 'Ẻ'), ('Ẽ', 'Ẽ'), + ('Ế', 'Ế'), ('Ề', 'Ề'), ('Ể', 'Ể'), ('Ễ', 'Ễ'), + ('Ệ', 'Ệ'), ('Ỉ', 'Ỉ'), ('Ị', 'Ị'), ('Ọ', 'Ọ'), + ('Ỏ', 'Ỏ'), ('Ố', 'Ố'), ('Ồ', 'Ồ'), ('Ổ', 'Ổ'), + ('Ỗ', 'Ỗ'), ('Ộ', 'Ộ'), ('Ớ', 'Ớ'), ('Ờ', 'Ờ'), + ('Ở', 'Ở'), ('Ỡ', 'Ỡ'), ('Ợ', 'Ợ'), ('Ụ', 'Ụ'), + ('Ủ', 'Ủ'), ('Ứ', 'Ứ'), ('Ừ', 'Ừ'), ('Ử', 'Ử'), + ('Ữ', 'Ữ'), ('Ự', 'Ự'), ('Ỳ', 'Ỳ'), ('Ỵ', 'Ỵ'), + ('Ỷ', 'Ỷ'), ('Ỹ', 'Ỹ'), ('Ỻ', 'Ỻ'), ('Ỽ', 'Ỽ'), + ('Ỿ', 'Ỿ'), ('Ἀ', 'Ἇ'), ('Ἐ', 'Ἕ'), ('Ἠ', 'Ἧ'), + ('Ἰ', 'Ἷ'), ('Ὀ', 'Ὅ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), + ('Ὕ', 'Ὕ'), ('Ὗ', 'Ὗ'), ('Ὠ', 'Ὧ'), ('Ᾰ', 'Ά'), + ('Ὲ', 'Ή'), ('Ῐ', 'Ί'), ('Ῠ', 'Ῥ'), ('Ὸ', 'Ώ'), + ('ℂ', 'ℂ'), ('ℇ', 'ℇ'), ('ℋ', 'ℍ'), ('ℐ', 'ℒ'), + ('ℕ', 'ℕ'), ('ℙ', 'ℝ'), ('ℤ', 'ℤ'), ('Ω', 'Ω'), + ('ℨ', 'ℨ'), ('K', 'ℭ'), ('ℰ', 'ℳ'), ('ℾ', 'ℿ'), + ('ⅅ', 'ⅅ'), ('Ⅰ', 'Ⅿ'), ('Ↄ', 'Ↄ'), ('Ⓐ', 'Ⓩ'), + ('Ⰰ', 'Ⱞ'), ('Ⱡ', 'Ⱡ'), ('Ɫ', 'Ɽ'), ('Ⱨ', 'Ⱨ'), + ('Ⱪ', 'Ⱪ'), ('Ⱬ', 'Ⱬ'), ('Ɑ', 'Ɒ'), ('Ⱳ', 'Ⱳ'), + ('Ⱶ', 'Ⱶ'), ('Ȿ', 'Ⲁ'), ('Ⲃ', 'Ⲃ'), ('Ⲅ', 'Ⲅ'), + ('Ⲇ', 'Ⲇ'), ('Ⲉ', 'Ⲉ'), ('Ⲋ', 'Ⲋ'), ('Ⲍ', 'Ⲍ'), + ('Ⲏ', 'Ⲏ'), ('Ⲑ', 'Ⲑ'), ('Ⲓ', 'Ⲓ'), ('Ⲕ', 'Ⲕ'), + ('Ⲗ', 'Ⲗ'), ('Ⲙ', 'Ⲙ'), ('Ⲛ', 'Ⲛ'), ('Ⲝ', 'Ⲝ'), + ('Ⲟ', 'Ⲟ'), ('Ⲡ', 'Ⲡ'), ('Ⲣ', 'Ⲣ'), ('Ⲥ', 'Ⲥ'), + ('Ⲧ', 'Ⲧ'), ('Ⲩ', 'Ⲩ'), ('Ⲫ', 'Ⲫ'), ('Ⲭ', 'Ⲭ'), + ('Ⲯ', 'Ⲯ'), ('Ⲱ', 'Ⲱ'), ('Ⲳ', 'Ⲳ'), ('Ⲵ', 'Ⲵ'), + ('Ⲷ', 'Ⲷ'), ('Ⲹ', 'Ⲹ'), ('Ⲻ', 'Ⲻ'), ('Ⲽ', 'Ⲽ'), + ('Ⲿ', 'Ⲿ'), ('Ⳁ', 'Ⳁ'), ('Ⳃ', 'Ⳃ'), ('Ⳅ', 'Ⳅ'), + ('Ⳇ', 'Ⳇ'), ('Ⳉ', 'Ⳉ'), ('Ⳋ', 'Ⳋ'), ('Ⳍ', 'Ⳍ'), + ('Ⳏ', 'Ⳏ'), ('Ⳑ', 'Ⳑ'), ('Ⳓ', 'Ⳓ'), ('Ⳕ', 'Ⳕ'), + ('Ⳗ', 'Ⳗ'), ('Ⳙ', 'Ⳙ'), ('Ⳛ', 'Ⳛ'), ('Ⳝ', 'Ⳝ'), + ('Ⳟ', 'Ⳟ'), ('Ⳡ', 'Ⳡ'), ('Ⳣ', 'Ⳣ'), ('Ⳬ', 'Ⳬ'), + ('Ⳮ', 'Ⳮ'), ('Ⳳ', 'Ⳳ'), ('Ꙁ', 'Ꙁ'), ('Ꙃ', 'Ꙃ'), + ('Ꙅ', 'Ꙅ'), ('Ꙇ', 'Ꙇ'), ('Ꙉ', 'Ꙉ'), ('Ꙋ', 'Ꙋ'), + ('Ꙍ', 'Ꙍ'), ('Ꙏ', 'Ꙏ'), ('Ꙑ', 'Ꙑ'), ('Ꙓ', 'Ꙓ'), + ('Ꙕ', 'Ꙕ'), ('Ꙗ', 'Ꙗ'), ('Ꙙ', 'Ꙙ'), ('Ꙛ', 'Ꙛ'), + ('Ꙝ', 'Ꙝ'), ('Ꙟ', 'Ꙟ'), ('Ꙡ', 'Ꙡ'), ('Ꙣ', 'Ꙣ'), + ('Ꙥ', 'Ꙥ'), ('Ꙧ', 'Ꙧ'), ('Ꙩ', 'Ꙩ'), ('Ꙫ', 'Ꙫ'), + ('Ꙭ', 'Ꙭ'), ('Ꚁ', 'Ꚁ'), ('Ꚃ', 'Ꚃ'), ('Ꚅ', 'Ꚅ'), + ('Ꚇ', 'Ꚇ'), ('Ꚉ', 'Ꚉ'), ('Ꚋ', 'Ꚋ'), ('Ꚍ', 'Ꚍ'), + ('Ꚏ', 'Ꚏ'), ('Ꚑ', 'Ꚑ'), ('Ꚓ', 'Ꚓ'), ('Ꚕ', 'Ꚕ'), + ('Ꚗ', 'Ꚗ'), ('Ꚙ', 'Ꚙ'), ('Ꚛ', 'Ꚛ'), ('Ꜣ', 'Ꜣ'), + ('Ꜥ', 'Ꜥ'), ('Ꜧ', 'Ꜧ'), ('Ꜩ', 'Ꜩ'), ('Ꜫ', 'Ꜫ'), + ('Ꜭ', 'Ꜭ'), ('Ꜯ', 'Ꜯ'), ('Ꜳ', 'Ꜳ'), ('Ꜵ', 'Ꜵ'), + ('Ꜷ', 'Ꜷ'), ('Ꜹ', 'Ꜹ'), ('Ꜻ', 'Ꜻ'), ('Ꜽ', 'Ꜽ'), + ('Ꜿ', 'Ꜿ'), ('Ꝁ', 'Ꝁ'), ('Ꝃ', 'Ꝃ'), ('Ꝅ', 'Ꝅ'), + ('Ꝇ', 'Ꝇ'), ('Ꝉ', 'Ꝉ'), ('Ꝋ', 'Ꝋ'), ('Ꝍ', 'Ꝍ'), + ('Ꝏ', 'Ꝏ'), ('Ꝑ', 'Ꝑ'), ('Ꝓ', 'Ꝓ'), ('Ꝕ', 'Ꝕ'), + ('Ꝗ', 'Ꝗ'), ('Ꝙ', 'Ꝙ'), ('Ꝛ', 'Ꝛ'), ('Ꝝ', 'Ꝝ'), + ('Ꝟ', 'Ꝟ'), ('Ꝡ', 'Ꝡ'), ('Ꝣ', 'Ꝣ'), ('Ꝥ', 'Ꝥ'), + ('Ꝧ', 'Ꝧ'), ('Ꝩ', 'Ꝩ'), ('Ꝫ', 'Ꝫ'), ('Ꝭ', 'Ꝭ'), + ('Ꝯ', 'Ꝯ'), ('Ꝺ', 'Ꝺ'), ('Ꝼ', 'Ꝼ'), ('Ᵹ', 'Ꝿ'), + ('Ꞁ', 'Ꞁ'), ('Ꞃ', 'Ꞃ'), ('Ꞅ', 'Ꞅ'), ('Ꞇ', 'Ꞇ'), + ('Ꞌ', 'Ꞌ'), ('Ɥ', 'Ɥ'), ('Ꞑ', 'Ꞑ'), ('Ꞓ', 'Ꞓ'), + ('Ꞗ', 'Ꞗ'), ('Ꞙ', 'Ꞙ'), ('Ꞛ', 'Ꞛ'), ('Ꞝ', 'Ꞝ'), + ('Ꞟ', 'Ꞟ'), ('Ꞡ', 'Ꞡ'), ('Ꞣ', 'Ꞣ'), ('Ꞥ', 'Ꞥ'), + ('Ꞧ', 'Ꞧ'), ('Ꞩ', 'Ꞩ'), ('Ɦ', 'Ɪ'), ('Ʞ', 'Ꞵ'), + ('Ꞷ', 'Ꞷ'), ('A', 'Z'), ('𐐀', '𐐧'), ('𐒰', '𐓓'), + ('𐲀', '𐲲'), ('𑢠', '𑢿'), ('𝐀', '𝐙'), ('𝐴', '𝑍'), + ('𝑨', '𝒁'), ('𝒜', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), + ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒵'), ('𝓐', '𝓩'), + ('𝔄', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), + ('𝔸', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), + ('𝕊', '𝕐'), ('𝕬', '𝖅'), ('𝖠', '𝖹'), ('𝗔', '𝗭'), + ('𝘈', '𝘡'), ('𝘼', '𝙕'), ('𝙰', '𝚉'), ('𝚨', '𝛀'), + ('𝛢', '𝛺'), ('𝜜', '𝜴'), ('𝝖', '𝝮'), ('𝞐', '𝞨'), + ('𝟊', '𝟊'), ('𞤀', '𞤡'), ('🄰', '🅉'), ('🅐', '🅩'), + ('🅰', '🆉'), +]; + +pub const VARIATION_SELECTOR: &'static [(char, char)] = &[ + ('᠋', '᠍'), ('︀', '️'), ('󠄀', '󠇯'), +]; + +pub const WHITE_SPACE: &'static [(char, char)] = &[ + ('\t', '\r'), (' ', ' '), ('\u{85}', '\u{85}'), ('\u{a0}', '\u{a0}'), + ('\u{1680}', '\u{1680}'), ('\u{2000}', '\u{200a}'), + ('\u{2028}', '\u{2029}'), ('\u{202f}', '\u{202f}'), + ('\u{205f}', '\u{205f}'), ('\u{3000}', '\u{3000}'), +]; + +pub const XID_CONTINUE: &'static [(char, char)] = &[ + ('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), + ('·', '·'), ('º', 'º'), ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), + ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('̀', 'ʹ'), + ('Ͷ', 'ͷ'), ('ͻ', 'ͽ'), ('Ϳ', 'Ϳ'), ('Ά', 'Ί'), ('Ό', 'Ό'), + ('Ύ', 'Ρ'), ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('҃', '҇'), ('Ҋ', 'ԯ'), + ('Ա', 'Ֆ'), ('ՙ', 'ՙ'), ('ա', 'և'), ('֑', 'ֽ'), ('ֿ', 'ֿ'), + ('ׁ', 'ׂ'), ('ׄ', 'ׅ'), ('ׇ', 'ׇ'), ('א', 'ת'), ('װ', 'ײ'), + ('ؐ', 'ؚ'), ('ؠ', '٩'), ('ٮ', 'ۓ'), ('ە', 'ۜ'), ('۟', 'ۨ'), + ('۪', 'ۼ'), ('ۿ', 'ۿ'), ('ܐ', '݊'), ('ݍ', 'ޱ'), ('߀', 'ߵ'), + ('ߺ', 'ߺ'), ('ࠀ', '࠭'), ('ࡀ', '࡛'), ('ࡠ', 'ࡪ'), + ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ࣔ', '࣡'), ('ࣣ', 'ॣ'), + ('०', '९'), ('ॱ', 'ঃ'), ('অ', 'ঌ'), ('এ', 'ঐ'), + ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), ('শ', 'হ'), + ('়', 'ৄ'), ('ে', 'ৈ'), ('ো', 'ৎ'), ('ৗ', 'ৗ'), + ('ড়', 'ঢ়'), ('য়', 'ৣ'), ('০', 'ৱ'), ('ৼ', 'ৼ'), + ('ਁ', 'ਃ'), ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), + ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), + ('਼', '਼'), ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', '੍'), + ('ੑ', 'ੑ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), ('੦', 'ੵ'), + ('ઁ', 'ઃ'), ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), + ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), ('઼', 'ૅ'), + ('ે', 'ૉ'), ('ો', '્'), ('ૐ', 'ૐ'), ('ૠ', 'ૣ'), + ('૦', '૯'), ('ૹ', '૿'), ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('଼', 'ୄ'), ('େ', 'ୈ'), ('ୋ', '୍'), + ('ୖ', 'ୗ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୣ'), ('୦', '୯'), + ('ୱ', 'ୱ'), ('ஂ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), + ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), + ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), ('ா', 'ூ'), + ('ெ', 'ை'), ('ொ', '்'), ('ௐ', 'ௐ'), ('ௗ', 'ௗ'), + ('௦', '௯'), ('ఀ', 'ః'), ('అ', 'ఌ'), ('ఎ', 'ఐ'), + ('ఒ', 'న'), ('ప', 'హ'), ('ఽ', 'ౄ'), ('ె', 'ై'), + ('ొ', '్'), ('ౕ', 'ౖ'), ('ౘ', 'ౚ'), ('ౠ', 'ౣ'), + ('౦', '౯'), ('ಀ', 'ಃ'), ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), + ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), ('಼', 'ೄ'), + ('ೆ', 'ೈ'), ('ೊ', '್'), ('ೕ', 'ೖ'), ('ೞ', 'ೞ'), + ('ೠ', 'ೣ'), ('೦', '೯'), ('ೱ', 'ೲ'), ('ഀ', 'ഃ'), + ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ൄ'), ('െ', 'ൈ'), + ('ൊ', 'ൎ'), ('ൔ', 'ൗ'), ('ൟ', 'ൣ'), ('൦', '൯'), + ('ൺ', 'ൿ'), ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), + ('ඳ', 'ර'), ('ල', 'ල'), ('ව', 'ෆ'), ('්', '්'), + ('ා', 'ු'), ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('෦', '෯'), + ('ෲ', 'ෳ'), ('ก', 'ฺ'), ('เ', '๎'), ('๐', '๙'), + ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), + ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), + ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), + ('ົ', 'ຽ'), ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('່', 'ໍ'), + ('໐', '໙'), ('ໜ', 'ໟ'), ('ༀ', 'ༀ'), ('༘', '༙'), + ('༠', '༩'), ('༵', '༵'), ('༷', '༷'), ('༹', '༹'), + ('༾', 'ཇ'), ('ཉ', 'ཬ'), ('ཱ', '྄'), ('྆', 'ྗ'), + ('ྙ', 'ྼ'), ('࿆', '࿆'), ('က', '၉'), ('ၐ', 'ႝ'), + ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), + ('ჼ', 'ቈ'), ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), + ('ቚ', 'ቝ'), ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), + ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), + ('ወ', 'ዖ'), ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), + ('፝', '፟'), ('፩', '፱'), ('ᎀ', 'ᎏ'), ('Ꭰ', 'Ᏽ'), + ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), ('ᙯ', 'ᙿ'), ('ᚁ', 'ᚚ'), + ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), ('ᜀ', 'ᜌ'), ('ᜎ', '᜔'), + ('ᜠ', '᜴'), ('ᝀ', 'ᝓ'), ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), + ('ᝲ', 'ᝳ'), ('ក', '៓'), ('ៗ', 'ៗ'), ('ៜ', '៝'), + ('០', '៩'), ('᠋', '᠍'), ('᠐', '᠙'), ('ᠠ', 'ᡷ'), + ('ᢀ', 'ᢪ'), ('ᢰ', 'ᣵ'), ('ᤀ', 'ᤞ'), ('ᤠ', 'ᤫ'), + ('ᤰ', '᤻'), ('᥆', 'ᥭ'), ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), + ('ᦰ', 'ᧉ'), ('᧐', '᧚'), ('ᨀ', 'ᨛ'), ('ᨠ', 'ᩞ'), + ('᩠', '᩼'), ('᩿', '᪉'), ('᪐', '᪙'), ('ᪧ', 'ᪧ'), + ('᪰', '᪽'), ('ᬀ', 'ᭋ'), ('᭐', '᭙'), ('᭫', '᭳'), + ('ᮀ', '᯳'), ('ᰀ', '᰷'), ('᱀', '᱉'), ('ᱍ', 'ᱽ'), + ('ᲀ', 'ᲈ'), ('᳐', '᳒'), ('᳔', '᳹'), ('ᴀ', '᷹'), + ('᷻', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), + ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), + ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), ('ι', 'ι'), + ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), ('ῖ', 'Ί'), + ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), ('‿', '⁀'), + ('⁔', '⁔'), ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), + ('⃐', '⃜'), ('⃡', '⃡'), ('⃥', '⃰'), ('ℂ', 'ℂ'), + ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('℘', 'ℝ'), + ('ℤ', 'ℤ'), ('Ω', 'Ω'), ('ℨ', 'ℨ'), ('K', 'ℹ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), + ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳳ'), + ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), ('ⴰ', 'ⵧ'), + ('ⵯ', 'ⵯ'), ('⵿', 'ⶖ'), ('ⶠ', 'ⶦ'), ('ⶨ', 'ⶮ'), + ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), ('ⷈ', 'ⷎ'), + ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('ⷠ', 'ⷿ'), ('々', '〇'), + ('〡', '〯'), ('〱', '〵'), ('〸', '〼'), ('ぁ', 'ゖ'), + ('゙', '゚'), ('ゝ', 'ゟ'), ('ァ', 'ヺ'), ('ー', 'ヿ'), + ('ㄅ', 'ㄮ'), ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), ('ㇰ', 'ㇿ'), + ('㐀', '䶵'), ('一', '鿪'), ('ꀀ', 'ꒌ'), ('ꓐ', 'ꓽ'), + ('ꔀ', 'ꘌ'), ('ꘐ', 'ꘫ'), ('Ꙁ', '꙯'), ('ꙴ', '꙽'), + ('ꙿ', '꛱'), ('ꜗ', 'ꜟ'), ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), + ('Ʞ', 'ꞷ'), ('ꟷ', 'ꠧ'), ('ꡀ', 'ꡳ'), ('ꢀ', 'ꣅ'), + ('꣐', '꣙'), ('꣠', 'ꣷ'), ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), + ('꤀', '꤭'), ('ꤰ', '꥓'), ('ꥠ', 'ꥼ'), ('ꦀ', '꧀'), + ('ꧏ', '꧙'), ('ꧠ', 'ꧾ'), ('ꨀ', 'ꨶ'), ('ꩀ', 'ꩍ'), + ('꩐', '꩙'), ('ꩠ', 'ꩶ'), ('ꩺ', 'ꫂ'), ('ꫛ', 'ꫝ'), + ('ꫠ', 'ꫯ'), ('ꫲ', '꫶'), ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), + ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), + ('ꭜ', 'ꭥ'), ('ꭰ', 'ꯪ'), ('꯬', '꯭'), ('꯰', '꯹'), + ('가', '힣'), ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('豈', '舘'), + ('並', '龎'), ('ff', 'st'), ('ﬓ', 'ﬗ'), ('יִ', 'ﬨ'), + ('שׁ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), ('נּ', 'סּ'), + ('ףּ', 'פּ'), ('צּ', 'ﮱ'), ('ﯓ', 'ﱝ'), ('ﱤ', 'ﴽ'), + ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷹ'), ('︀', '️'), + ('︠', '︯'), ('︳', '︴'), ('﹍', '﹏'), ('ﹱ', 'ﹱ'), + ('ﹳ', 'ﹳ'), ('ﹷ', 'ﹷ'), ('ﹹ', 'ﹹ'), ('ﹻ', 'ﹻ'), + ('ﹽ', 'ﹽ'), ('ﹿ', 'ﻼ'), ('0', '9'), ('A', 'Z'), + ('_', '_'), ('a', 'z'), ('ヲ', 'ᄒ'), ('ᅡ', 'ᅦ'), + ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), ('𐀀', '𐀋'), + ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), ('𐀿', '𐁍'), + ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐅀', '𐅴'), ('𐇽', '𐇽'), + ('𐊀', '𐊜'), ('𐊠', '𐋐'), ('𐋠', '𐋠'), ('𐌀', '𐌟'), + ('𐌭', '𐍊'), ('𐍐', '𐍺'), ('𐎀', '𐎝'), ('𐎠', '𐏃'), + ('𐏈', '𐏏'), ('𐏑', '𐏕'), ('𐐀', '𐒝'), ('𐒠', '𐒩'), + ('𐒰', '𐓓'), ('𐓘', '𐓻'), ('𐔀', '𐔧'), ('𐔰', '𐕣'), + ('𐘀', '𐜶'), ('𐝀', '𐝕'), ('𐝠', '𐝧'), ('𐠀', '𐠅'), + ('𐠈', '𐠈'), ('𐠊', '𐠵'), ('𐠷', '𐠸'), ('𐠼', '𐠼'), + ('𐠿', '𐡕'), ('𐡠', '𐡶'), ('𐢀', '𐢞'), ('𐣠', '𐣲'), + ('𐣴', '𐣵'), ('𐤀', '𐤕'), ('𐤠', '𐤹'), ('𐦀', '𐦷'), + ('𐦾', '𐦿'), ('𐨀', '𐨃'), ('𐨅', '𐨆'), ('𐨌', '𐨓'), + ('𐨕', '𐨗'), ('𐨙', '𐨳'), ('𐨸', '𐨺'), ('𐨿', '𐨿'), + ('𐩠', '𐩼'), ('𐪀', '𐪜'), ('𐫀', '𐫇'), ('𐫉', '𐫦'), + ('𐬀', '𐬵'), ('𐭀', '𐭕'), ('𐭠', '𐭲'), ('𐮀', '𐮑'), + ('𐰀', '𐱈'), ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𑀀', '𑁆'), + ('𑁦', '𑁯'), ('𑁿', '𑂺'), ('𑃐', '𑃨'), ('𑃰', '𑃹'), + ('𑄀', '𑄴'), ('𑄶', '𑄿'), ('𑅐', '𑅳'), ('𑅶', '𑅶'), + ('𑆀', '𑇄'), ('𑇊', '𑇌'), ('𑇐', '𑇚'), ('𑇜', '𑇜'), + ('𑈀', '𑈑'), ('𑈓', '𑈷'), ('𑈾', '𑈾'), ('𑊀', '𑊆'), + ('𑊈', '𑊈'), ('𑊊', '𑊍'), ('𑊏', '𑊝'), ('𑊟', '𑊨'), + ('𑊰', '𑋪'), ('𑋰', '𑋹'), ('𑌀', '𑌃'), ('𑌅', '𑌌'), + ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), ('𑌲', '𑌳'), + ('𑌵', '𑌹'), ('𑌼', '𑍄'), ('𑍇', '𑍈'), ('𑍋', '𑍍'), + ('𑍐', '𑍐'), ('𑍗', '𑍗'), ('𑍝', '𑍣'), ('𑍦', '𑍬'), + ('𑍰', '𑍴'), ('𑐀', '𑑊'), ('𑑐', '𑑙'), ('𑒀', '𑓅'), + ('𑓇', '𑓇'), ('𑓐', '𑓙'), ('𑖀', '𑖵'), ('𑖸', '𑗀'), + ('𑗘', '𑗝'), ('𑘀', '𑙀'), ('𑙄', '𑙄'), ('𑙐', '𑙙'), + ('𑚀', '𑚷'), ('𑛀', '𑛉'), ('𑜀', '𑜙'), ('𑜝', '𑜫'), + ('𑜰', '𑜹'), ('𑢠', '𑣩'), ('𑣿', '𑣿'), ('𑨀', '𑨾'), + ('𑩇', '𑩇'), ('𑩐', '𑪃'), ('𑪆', '𑪙'), ('𑫀', '𑫸'), + ('𑰀', '𑰈'), ('𑰊', '𑰶'), ('𑰸', '𑱀'), ('𑱐', '𑱙'), + ('𑱲', '𑲏'), ('𑲒', '𑲧'), ('𑲩', '𑲶'), ('𑴀', '𑴆'), + ('𑴈', '𑴉'), ('𑴋', '𑴶'), ('𑴺', '𑴺'), ('𑴼', '𑴽'), + ('𑴿', '𑵇'), ('𑵐', '𑵙'), ('𒀀', '𒎙'), ('𒐀', '𒑮'), + ('𒒀', '𒕃'), ('𓀀', '𓐮'), ('𔐀', '𔙆'), ('𖠀', '𖨸'), + ('𖩀', '𖩞'), ('𖩠', '𖩩'), ('𖫐', '𖫭'), ('𖫰', '𖫴'), + ('𖬀', '𖬶'), ('𖭀', '𖭃'), ('𖭐', '𖭙'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), ('𖼀', '𖽄'), ('𖽐', '𖽾'), ('𖾏', '𖾟'), + ('𖿠', '𖿡'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𛀀', '𛄞'), + ('𛅰', '𛋻'), ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), + ('𛲐', '𛲙'), ('𛲝', '𛲞'), ('𝅥', '𝅩'), ('𝅭', '𝅲'), + ('𝅻', '𝆂'), ('𝆅', '𝆋'), ('𝆪', '𝆭'), ('𝉂', '𝉄'), + ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), + ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), + ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), + ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), + ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝛀'), + ('𝛂', '𝛚'), ('𝛜', '𝛺'), ('𝛼', '𝜔'), ('𝜖', '𝜴'), + ('𝜶', '𝝎'), ('𝝐', '𝝮'), ('𝝰', '𝞈'), ('𝞊', '𝞨'), + ('𝞪', '𝟂'), ('𝟄', '𝟋'), ('𝟎', '𝟿'), ('𝨀', '𝨶'), + ('𝨻', '𝩬'), ('𝩵', '𝩵'), ('𝪄', '𝪄'), ('𝪛', '𝪟'), + ('𝪡', '𝪯'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), ('𞀛', '𞀡'), + ('𞀣', '𞀤'), ('𞀦', '𞀪'), ('𞠀', '𞣄'), ('𞣐', '𞣖'), + ('𞤀', '𞥊'), ('𞥐', '𞥙'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), + ('𞸡', '𞸢'), ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), + ('𞸴', '𞸷'), ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), + ('𞹇', '𞹇'), ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), + ('𞹑', '𞹒'), ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), + ('𞹛', '𞹛'), ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), + ('𞹤', '𞹤'), ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), + ('𞹹', '𞹼'), ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), + ('𞺡', '𞺣'), ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𠀀', '𪛖'), + ('𪜀', '𫜴'), ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), + ('丽', '𪘀'), ('󠄀', '󠇯'), +]; + +pub const XID_START: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('µ', 'µ'), ('º', 'º'), + ('À', 'Ö'), ('Ø', 'ö'), ('ø', 'ˁ'), ('ˆ', 'ˑ'), ('ˠ', 'ˤ'), + ('ˬ', 'ˬ'), ('ˮ', 'ˮ'), ('Ͱ', 'ʹ'), ('Ͷ', 'ͷ'), ('ͻ', 'ͽ'), + ('Ϳ', 'Ϳ'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), + ('Σ', 'ϵ'), ('Ϸ', 'ҁ'), ('Ҋ', 'ԯ'), ('Ա', 'Ֆ'), ('ՙ', 'ՙ'), + ('ա', 'և'), ('א', 'ת'), ('װ', 'ײ'), ('ؠ', 'ي'), ('ٮ', 'ٯ'), + ('ٱ', 'ۓ'), ('ە', 'ە'), ('ۥ', 'ۦ'), ('ۮ', 'ۯ'), ('ۺ', 'ۼ'), + ('ۿ', 'ۿ'), ('ܐ', 'ܐ'), ('ܒ', 'ܯ'), ('ݍ', 'ޥ'), ('ޱ', 'ޱ'), + ('ߊ', 'ߪ'), ('ߴ', 'ߵ'), ('ߺ', 'ߺ'), ('ࠀ', 'ࠕ'), ('ࠚ', 'ࠚ'), + ('ࠤ', 'ࠤ'), ('ࠨ', 'ࠨ'), ('ࡀ', 'ࡘ'), ('ࡠ', 'ࡪ'), + ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ऄ', 'ह'), ('ऽ', 'ऽ'), + ('ॐ', 'ॐ'), ('क़', 'ॡ'), ('ॱ', 'ঀ'), ('অ', 'ঌ'), + ('এ', 'ঐ'), ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), + ('শ', 'হ'), ('ঽ', 'ঽ'), ('ৎ', 'ৎ'), ('ড়', 'ঢ়'), + ('য়', 'ৡ'), ('ৰ', 'ৱ'), ('ৼ', 'ৼ'), ('ਅ', 'ਊ'), + ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), + ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), + ('ੲ', 'ੴ'), ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), + ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), ('ઽ', 'ઽ'), + ('ૐ', 'ૐ'), ('ૠ', 'ૡ'), ('ૹ', 'ૹ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('ଽ', 'ଽ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୡ'), + ('ୱ', 'ୱ'), ('ஃ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), + ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), + ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), ('ௐ', 'ௐ'), + ('అ', 'ఌ'), ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), + ('ఽ', 'ఽ'), ('ౘ', 'ౚ'), ('ౠ', 'ౡ'), ('ಀ', 'ಀ'), + ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), + ('ವ', 'ಹ'), ('ಽ', 'ಽ'), ('ೞ', 'ೞ'), ('ೠ', 'ೡ'), + ('ೱ', 'ೲ'), ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ഺ'), + ('ഽ', 'ഽ'), ('ൎ', 'ൎ'), ('ൔ', 'ൖ'), ('ൟ', 'ൡ'), + ('ൺ', 'ൿ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('ก', 'ะ'), ('า', 'า'), + ('เ', 'ๆ'), ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), + ('ຊ', 'ຊ'), ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), + ('ມ', 'ຣ'), ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), + ('ອ', 'ະ'), ('າ', 'າ'), ('ຽ', 'ຽ'), ('ເ', 'ໄ'), + ('ໆ', 'ໆ'), ('ໜ', 'ໟ'), ('ༀ', 'ༀ'), ('ཀ', 'ཇ'), + ('ཉ', 'ཬ'), ('ྈ', 'ྌ'), ('က', 'ဪ'), ('ဿ', 'ဿ'), + ('ၐ', 'ၕ'), ('ၚ', 'ၝ'), ('ၡ', 'ၡ'), ('ၥ', 'ၦ'), + ('ၮ', 'ၰ'), ('ၵ', 'ႁ'), ('ႎ', 'ႎ'), ('Ⴀ', 'Ⴥ'), + ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), ('ჼ', 'ቈ'), + ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), ('ቚ', 'ቝ'), + ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), ('ኲ', 'ኵ'), + ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), ('ወ', 'ዖ'), + ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), ('ᎀ', 'ᎏ'), + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ᐁ', 'ᙬ'), ('ᙯ', 'ᙿ'), + ('ᚁ', 'ᚚ'), ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), ('ᜀ', 'ᜌ'), + ('ᜎ', 'ᜑ'), ('ᜠ', 'ᜱ'), ('ᝀ', 'ᝑ'), ('ᝠ', 'ᝬ'), + ('ᝮ', 'ᝰ'), ('ក', 'ឳ'), ('ៗ', 'ៗ'), ('ៜ', 'ៜ'), + ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢨ'), ('ᢪ', 'ᢪ'), ('ᢰ', 'ᣵ'), + ('ᤀ', 'ᤞ'), ('ᥐ', 'ᥭ'), ('ᥰ', 'ᥴ'), ('ᦀ', 'ᦫ'), + ('ᦰ', 'ᧉ'), ('ᨀ', 'ᨖ'), ('ᨠ', 'ᩔ'), ('ᪧ', 'ᪧ'), + ('ᬅ', 'ᬳ'), ('ᭅ', 'ᭋ'), ('ᮃ', 'ᮠ'), ('ᮮ', 'ᮯ'), + ('ᮺ', 'ᯥ'), ('ᰀ', 'ᰣ'), ('ᱍ', 'ᱏ'), ('ᱚ', 'ᱽ'), + ('ᲀ', 'ᲈ'), ('ᳩ', 'ᳬ'), ('ᳮ', 'ᳱ'), ('ᳵ', 'ᳶ'), + ('ᴀ', 'ᶿ'), ('Ḁ', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), + ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), + ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ᾼ'), + ('ι', 'ι'), ('ῂ', 'ῄ'), ('ῆ', 'ῌ'), ('ῐ', 'ΐ'), + ('ῖ', 'Ί'), ('ῠ', 'Ῥ'), ('ῲ', 'ῴ'), ('ῶ', 'ῼ'), + ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('ℂ', 'ℂ'), + ('ℇ', 'ℇ'), ('ℊ', 'ℓ'), ('ℕ', 'ℕ'), ('℘', 'ℝ'), + ('ℤ', 'ℤ'), ('Ω', 'Ω'), ('ℨ', 'ℨ'), ('K', 'ℹ'), + ('ℼ', 'ℿ'), ('ⅅ', 'ⅉ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), + ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('Ⱡ', 'ⳤ'), ('Ⳬ', 'ⳮ'), + ('Ⳳ', 'ⳳ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), + ('ⴰ', 'ⵧ'), ('ⵯ', 'ⵯ'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), + ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), + ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('々', '〇'), + ('〡', '〩'), ('〱', '〵'), ('〸', '〼'), ('ぁ', 'ゖ'), + ('ゝ', 'ゟ'), ('ァ', 'ヺ'), ('ー', 'ヿ'), ('ㄅ', 'ㄮ'), + ('ㄱ', 'ㆎ'), ('ㆠ', 'ㆺ'), ('ㇰ', 'ㇿ'), ('㐀', '䶵'), + ('一', '鿪'), ('ꀀ', 'ꒌ'), ('ꓐ', 'ꓽ'), ('ꔀ', 'ꘌ'), + ('ꘐ', 'ꘟ'), ('ꘪ', 'ꘫ'), ('Ꙁ', 'ꙮ'), ('ꙿ', 'ꚝ'), + ('ꚠ', 'ꛯ'), ('ꜗ', 'ꜟ'), ('Ꜣ', 'ꞈ'), ('Ꞌ', 'Ɪ'), + ('Ʞ', 'ꞷ'), ('ꟷ', 'ꠁ'), ('ꠃ', 'ꠅ'), ('ꠇ', 'ꠊ'), + ('ꠌ', 'ꠢ'), ('ꡀ', 'ꡳ'), ('ꢂ', 'ꢳ'), ('ꣲ', 'ꣷ'), + ('ꣻ', 'ꣻ'), ('ꣽ', 'ꣽ'), ('ꤊ', 'ꤥ'), ('ꤰ', 'ꥆ'), + ('ꥠ', 'ꥼ'), ('ꦄ', 'ꦲ'), ('ꧏ', 'ꧏ'), ('ꧠ', 'ꧤ'), + ('ꧦ', 'ꧯ'), ('ꧺ', 'ꧾ'), ('ꨀ', 'ꨨ'), ('ꩀ', 'ꩂ'), + ('ꩄ', 'ꩋ'), ('ꩠ', 'ꩶ'), ('ꩺ', 'ꩺ'), ('ꩾ', 'ꪯ'), + ('ꪱ', 'ꪱ'), ('ꪵ', 'ꪶ'), ('ꪹ', 'ꪽ'), ('ꫀ', 'ꫀ'), + ('ꫂ', 'ꫂ'), ('ꫛ', 'ꫝ'), ('ꫠ', 'ꫪ'), ('ꫲ', 'ꫴ'), + ('ꬁ', 'ꬆ'), ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), + ('ꬨ', 'ꬮ'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭥ'), ('ꭰ', 'ꯢ'), + ('가', '힣'), ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('豈', '舘'), + ('並', '龎'), ('ff', 'st'), ('ﬓ', 'ﬗ'), ('יִ', 'יִ'), + ('ײַ', 'ﬨ'), ('שׁ', 'זּ'), ('טּ', 'לּ'), ('מּ', 'מּ'), + ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﮱ'), ('ﯓ', 'ﱝ'), + ('ﱤ', 'ﴽ'), ('ﵐ', 'ﶏ'), ('ﶒ', 'ﷇ'), ('ﷰ', 'ﷹ'), + ('ﹱ', 'ﹱ'), ('ﹳ', 'ﹳ'), ('ﹷ', 'ﹷ'), ('ﹹ', 'ﹹ'), + ('ﹻ', 'ﹻ'), ('ﹽ', 'ﹽ'), ('ﹿ', 'ﻼ'), ('A', 'Z'), + ('a', 'z'), ('ヲ', 'ン'), ('ᅠ', 'ᄒ'), ('ᅡ', 'ᅦ'), + ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), ('𐀀', '𐀋'), + ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), ('𐀿', '𐁍'), + ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐅀', '𐅴'), ('𐊀', '𐊜'), + ('𐊠', '𐋐'), ('𐌀', '𐌟'), ('𐌭', '𐍊'), ('𐍐', '𐍵'), + ('𐎀', '𐎝'), ('𐎠', '𐏃'), ('𐏈', '𐏏'), ('𐏑', '𐏕'), + ('𐐀', '𐒝'), ('𐒰', '𐓓'), ('𐓘', '𐓻'), ('𐔀', '𐔧'), + ('𐔰', '𐕣'), ('𐘀', '𐜶'), ('𐝀', '𐝕'), ('𐝠', '𐝧'), + ('𐠀', '𐠅'), ('𐠈', '𐠈'), ('𐠊', '𐠵'), ('𐠷', '𐠸'), + ('𐠼', '𐠼'), ('𐠿', '𐡕'), ('𐡠', '𐡶'), ('𐢀', '𐢞'), + ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐤀', '𐤕'), ('𐤠', '𐤹'), + ('𐦀', '𐦷'), ('𐦾', '𐦿'), ('𐨀', '𐨀'), ('𐨐', '𐨓'), + ('𐨕', '𐨗'), ('𐨙', '𐨳'), ('𐩠', '𐩼'), ('𐪀', '𐪜'), + ('𐫀', '𐫇'), ('𐫉', '𐫤'), ('𐬀', '𐬵'), ('𐭀', '𐭕'), + ('𐭠', '𐭲'), ('𐮀', '𐮑'), ('𐰀', '𐱈'), ('𐲀', '𐲲'), + ('𐳀', '𐳲'), ('𑀃', '𑀷'), ('𑂃', '𑂯'), ('𑃐', '𑃨'), + ('𑄃', '𑄦'), ('𑅐', '𑅲'), ('𑅶', '𑅶'), ('𑆃', '𑆲'), + ('𑇁', '𑇄'), ('𑇚', '𑇚'), ('𑇜', '𑇜'), ('𑈀', '𑈑'), + ('𑈓', '𑈫'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), + ('𑊏', '𑊝'), ('𑊟', '𑊨'), ('𑊰', '𑋞'), ('𑌅', '𑌌'), + ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), ('𑌲', '𑌳'), + ('𑌵', '𑌹'), ('𑌽', '𑌽'), ('𑍐', '𑍐'), ('𑍝', '𑍡'), + ('𑐀', '𑐴'), ('𑑇', '𑑊'), ('𑒀', '𑒯'), ('𑓄', '𑓅'), + ('𑓇', '𑓇'), ('𑖀', '𑖮'), ('𑗘', '𑗛'), ('𑘀', '𑘯'), + ('𑙄', '𑙄'), ('𑚀', '𑚪'), ('𑜀', '𑜙'), ('𑢠', '𑣟'), + ('𑣿', '𑣿'), ('𑨀', '𑨀'), ('𑨋', '𑨲'), ('𑨺', '𑨺'), + ('𑩐', '𑩐'), ('𑩜', '𑪃'), ('𑪆', '𑪉'), ('𑫀', '𑫸'), + ('𑰀', '𑰈'), ('𑰊', '𑰮'), ('𑱀', '𑱀'), ('𑱲', '𑲏'), + ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴰'), ('𑵆', '𑵆'), + ('𒀀', '𒎙'), ('𒐀', '𒑮'), ('𒒀', '𒕃'), ('𓀀', '𓐮'), + ('𔐀', '𔙆'), ('𖠀', '𖨸'), ('𖩀', '𖩞'), ('𖫐', '𖫭'), + ('𖬀', '𖬯'), ('𖭀', '𖭃'), ('𖭣', '𖭷'), ('𖭽', '𖮏'), + ('𖼀', '𖽄'), ('𖽐', '𖽐'), ('𖾓', '𖾟'), ('𖿠', '𖿡'), + ('𗀀', '𘟬'), ('𘠀', '𘫲'), ('𛀀', '𛄞'), ('𛅰', '𛋻'), + ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), ('𛲐', '𛲙'), + ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), + ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), + ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), + ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), + ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝛀'), + ('𝛂', '𝛚'), ('𝛜', '𝛺'), ('𝛼', '𝜔'), ('𝜖', '𝜴'), + ('𝜶', '𝝎'), ('𝝐', '𝝮'), ('𝝰', '𝞈'), ('𝞊', '𝞨'), + ('𝞪', '𝟂'), ('𝟄', '𝟋'), ('𞠀', '𞣄'), ('𞤀', '𞥃'), + ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), ('𞸤', '𞸤'), + ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), ('𞸹', '𞸹'), + ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), ('𞹉', '𞹉'), + ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), ('𞹔', '𞹔'), + ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), ('𞹝', '𞹝'), + ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), ('𞹧', '𞹪'), + ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), ('𞹾', '𞹾'), + ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), ('𞺥', '𞺩'), + ('𞺫', '𞺻'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), ('𫝀', '𫠝'), + ('𫠠', '𬺡'), ('𬺰', '𮯠'), ('丽', '𪘀'), +]; diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/property_names.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/property_names.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/property_names.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/property_names.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,146 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate property-names tmp/ucd-10.0.0/ +// +// ucd-generate is available on crates.io. + +pub const PROPERTY_NAMES: &'static [(&'static str, &'static str)] = &[ + ("age", "Age"), ("ahex", "ASCII_Hex_Digit"), ("alpha", "Alphabetic"), + ("alphabetic", "Alphabetic"), ("asciihexdigit", "ASCII_Hex_Digit"), + ("bc", "Bidi_Class"), ("bidic", "Bidi_Control"), + ("bidiclass", "Bidi_Class"), ("bidicontrol", "Bidi_Control"), + ("bidim", "Bidi_Mirrored"), ("bidimirrored", "Bidi_Mirrored"), + ("bidimirroringglyph", "Bidi_Mirroring_Glyph"), + ("bidipairedbracket", "Bidi_Paired_Bracket"), + ("bidipairedbrackettype", "Bidi_Paired_Bracket_Type"), ("blk", "Block"), + ("block", "Block"), ("bmg", "Bidi_Mirroring_Glyph"), + ("bpb", "Bidi_Paired_Bracket"), ("bpt", "Bidi_Paired_Bracket_Type"), + ("c", "ISO_Comment"), + ("canonicalcombiningclass", "Canonical_Combining_Class"), + ("cased", "Cased"), ("casefolding", "Case_Folding"), + ("caseignorable", "Case_Ignorable"), ("ccc", "Canonical_Combining_Class"), + ("ce", "Composition_Exclusion"), ("cf", "Case_Folding"), + ("changeswhencasefolded", "Changes_When_Casefolded"), + ("changeswhencasemapped", "Changes_When_Casemapped"), + ("changeswhenlowercased", "Changes_When_Lowercased"), + ("changeswhennfkccasefolded", "Changes_When_NFKC_Casefolded"), + ("changeswhentitlecased", "Changes_When_Titlecased"), + ("changeswhenuppercased", "Changes_When_Uppercased"), + ("ci", "Case_Ignorable"), ("cjkaccountingnumeric", "kAccountingNumeric"), + ("cjkcompatibilityvariant", "kCompatibilityVariant"), + ("cjkiicore", "kIICore"), ("cjkirggsource", "kIRG_GSource"), + ("cjkirghsource", "kIRG_HSource"), ("cjkirgjsource", "kIRG_JSource"), + ("cjkirgkpsource", "kIRG_KPSource"), ("cjkirgksource", "kIRG_KSource"), + ("cjkirgmsource", "kIRG_MSource"), ("cjkirgtsource", "kIRG_TSource"), + ("cjkirgusource", "kIRG_USource"), ("cjkirgvsource", "kIRG_VSource"), + ("cjkothernumeric", "kOtherNumeric"), + ("cjkprimarynumeric", "kPrimaryNumeric"), ("cjkrsunicode", "kRSUnicode"), + ("compex", "Full_Composition_Exclusion"), + ("compositionexclusion", "Composition_Exclusion"), + ("cwcf", "Changes_When_Casefolded"), ("cwcm", "Changes_When_Casemapped"), + ("cwkcf", "Changes_When_NFKC_Casefolded"), + ("cwl", "Changes_When_Lowercased"), ("cwt", "Changes_When_Titlecased"), + ("cwu", "Changes_When_Uppercased"), ("dash", "Dash"), + ("decompositionmapping", "Decomposition_Mapping"), + ("decompositiontype", "Decomposition_Type"), + ("defaultignorablecodepoint", "Default_Ignorable_Code_Point"), + ("dep", "Deprecated"), ("deprecated", "Deprecated"), + ("di", "Default_Ignorable_Code_Point"), ("dia", "Diacritic"), + ("diacritic", "Diacritic"), ("dm", "Decomposition_Mapping"), + ("dt", "Decomposition_Type"), ("ea", "East_Asian_Width"), + ("eastasianwidth", "East_Asian_Width"), ("expandsonnfc", "Expands_On_NFC"), + ("expandsonnfd", "Expands_On_NFD"), ("expandsonnfkc", "Expands_On_NFKC"), + ("expandsonnfkd", "Expands_On_NFKD"), ("ext", "Extender"), + ("extender", "Extender"), ("fcnfkc", "FC_NFKC_Closure"), + ("fcnfkcclosure", "FC_NFKC_Closure"), + ("fullcompositionexclusion", "Full_Composition_Exclusion"), + ("gc", "General_Category"), ("gcb", "Grapheme_Cluster_Break"), + ("generalcategory", "General_Category"), ("graphemebase", "Grapheme_Base"), + ("graphemeclusterbreak", "Grapheme_Cluster_Break"), + ("graphemeextend", "Grapheme_Extend"), ("graphemelink", "Grapheme_Link"), + ("grbase", "Grapheme_Base"), ("grext", "Grapheme_Extend"), + ("grlink", "Grapheme_Link"), ("hangulsyllabletype", "Hangul_Syllable_Type"), + ("hex", "Hex_Digit"), ("hexdigit", "Hex_Digit"), + ("hst", "Hangul_Syllable_Type"), ("hyphen", "Hyphen"), + ("idc", "ID_Continue"), ("idcontinue", "ID_Continue"), + ("ideo", "Ideographic"), ("ideographic", "Ideographic"), + ("ids", "ID_Start"), ("idsb", "IDS_Binary_Operator"), + ("idsbinaryoperator", "IDS_Binary_Operator"), + ("idst", "IDS_Trinary_Operator"), ("idstart", "ID_Start"), + ("idstrinaryoperator", "IDS_Trinary_Operator"), + ("indicpositionalcategory", "Indic_Positional_Category"), + ("indicsyllabiccategory", "Indic_Syllabic_Category"), + ("inpc", "Indic_Positional_Category"), ("insc", "Indic_Syllabic_Category"), + ("jamoshortname", "Jamo_Short_Name"), ("jg", "Joining_Group"), + ("joinc", "Join_Control"), ("joincontrol", "Join_Control"), + ("joininggroup", "Joining_Group"), ("joiningtype", "Joining_Type"), + ("jsn", "Jamo_Short_Name"), ("jt", "Joining_Type"), + ("kaccountingnumeric", "kAccountingNumeric"), + ("kcompatibilityvariant", "kCompatibilityVariant"), ("kiicore", "kIICore"), + ("kirggsource", "kIRG_GSource"), ("kirghsource", "kIRG_HSource"), + ("kirgjsource", "kIRG_JSource"), ("kirgkpsource", "kIRG_KPSource"), + ("kirgksource", "kIRG_KSource"), ("kirgmsource", "kIRG_MSource"), + ("kirgtsource", "kIRG_TSource"), ("kirgusource", "kIRG_USource"), + ("kirgvsource", "kIRG_VSource"), ("kothernumeric", "kOtherNumeric"), + ("kprimarynumeric", "kPrimaryNumeric"), ("krsunicode", "kRSUnicode"), + ("lb", "Line_Break"), ("lc", "Lowercase_Mapping"), + ("linebreak", "Line_Break"), ("loe", "Logical_Order_Exception"), + ("logicalorderexception", "Logical_Order_Exception"), + ("lower", "Lowercase"), ("lowercase", "Lowercase"), + ("lowercasemapping", "Lowercase_Mapping"), ("math", "Math"), ("na", "Name"), + ("na1", "Unicode_1_Name"), ("name", "Name"), ("namealias", "Name_Alias"), + ("nchar", "Noncharacter_Code_Point"), ("nfcqc", "NFC_Quick_Check"), + ("nfcquickcheck", "NFC_Quick_Check"), ("nfdqc", "NFD_Quick_Check"), + ("nfdquickcheck", "NFD_Quick_Check"), ("nfkccasefold", "NFKC_Casefold"), + ("nfkccf", "NFKC_Casefold"), ("nfkcqc", "NFKC_Quick_Check"), + ("nfkcquickcheck", "NFKC_Quick_Check"), ("nfkdqc", "NFKD_Quick_Check"), + ("nfkdquickcheck", "NFKD_Quick_Check"), + ("noncharactercodepoint", "Noncharacter_Code_Point"), + ("nt", "Numeric_Type"), ("numerictype", "Numeric_Type"), + ("numericvalue", "Numeric_Value"), ("nv", "Numeric_Value"), + ("oalpha", "Other_Alphabetic"), ("ocomment", "ISO_Comment"), + ("odi", "Other_Default_Ignorable_Code_Point"), + ("ogrext", "Other_Grapheme_Extend"), ("oidc", "Other_ID_Continue"), + ("oids", "Other_ID_Start"), ("olower", "Other_Lowercase"), + ("omath", "Other_Math"), ("otheralphabetic", "Other_Alphabetic"), + ("otherdefaultignorablecodepoint", "Other_Default_Ignorable_Code_Point"), + ("othergraphemeextend", "Other_Grapheme_Extend"), + ("otheridcontinue", "Other_ID_Continue"), + ("otheridstart", "Other_ID_Start"), ("otherlowercase", "Other_Lowercase"), + ("othermath", "Other_Math"), ("otheruppercase", "Other_Uppercase"), + ("oupper", "Other_Uppercase"), ("patsyn", "Pattern_Syntax"), + ("patternsyntax", "Pattern_Syntax"), + ("patternwhitespace", "Pattern_White_Space"), + ("patws", "Pattern_White_Space"), ("pcm", "Prepended_Concatenation_Mark"), + ("prependedconcatenationmark", "Prepended_Concatenation_Mark"), + ("qmark", "Quotation_Mark"), ("quotationmark", "Quotation_Mark"), + ("radical", "Radical"), ("regionalindicator", "Regional_Indicator"), + ("ri", "Regional_Indicator"), ("sb", "Sentence_Break"), ("sc", "Script"), + ("scf", "Simple_Case_Folding"), ("script", "Script"), + ("scriptextensions", "Script_Extensions"), ("scx", "Script_Extensions"), + ("sd", "Soft_Dotted"), ("sentencebreak", "Sentence_Break"), + ("sentenceterminal", "Sentence_Terminal"), ("sfc", "Simple_Case_Folding"), + ("simplecasefolding", "Simple_Case_Folding"), + ("simplelowercasemapping", "Simple_Lowercase_Mapping"), + ("simpletitlecasemapping", "Simple_Titlecase_Mapping"), + ("simpleuppercasemapping", "Simple_Uppercase_Mapping"), + ("slc", "Simple_Lowercase_Mapping"), ("softdotted", "Soft_Dotted"), + ("space", "White_Space"), ("stc", "Simple_Titlecase_Mapping"), + ("sterm", "Sentence_Terminal"), ("suc", "Simple_Uppercase_Mapping"), + ("tc", "Titlecase_Mapping"), ("term", "Terminal_Punctuation"), + ("terminalpunctuation", "Terminal_Punctuation"), + ("titlecasemapping", "Titlecase_Mapping"), ("uc", "Uppercase_Mapping"), + ("uideo", "Unified_Ideograph"), ("unicode1name", "Unicode_1_Name"), + ("unicoderadicalstroke", "kRSUnicode"), + ("unifiedideograph", "Unified_Ideograph"), ("upper", "Uppercase"), + ("uppercase", "Uppercase"), ("uppercasemapping", "Uppercase_Mapping"), + ("urs", "kRSUnicode"), ("variationselector", "Variation_Selector"), + ("verticalorientation", "Vertical_Orientation"), + ("vo", "Vertical_Orientation"), ("vs", "Variation_Selector"), + ("wb", "Word_Break"), ("whitespace", "White_Space"), + ("wordbreak", "Word_Break"), ("wspace", "White_Space"), + ("xidc", "XID_Continue"), ("xidcontinue", "XID_Continue"), + ("xids", "XID_Start"), ("xidstart", "XID_Start"), + ("xonfc", "Expands_On_NFC"), ("xonfd", "Expands_On_NFD"), + ("xonfkc", "Expands_On_NFKC"), ("xonfkd", "Expands_On_NFKD"), +]; diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/property_values.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/property_values.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/property_values.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/property_values.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,277 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate property-values tmp/ucd-10.0.0 --include gc,script,scx,age +// +// ucd-generate is available on crates.io. + +pub const PROPERTY_VALUES: &'static [(&'static str, &'static [(&'static str, &'static str)])] = &[ + ("Age", &[("1.1", "V1_1"), ("10.0", "V10_0"), ("2.0", "V2_0"), + ("2.1", "V2_1"), ("3.0", "V3_0"), ("3.1", "V3_1"), ("3.2", "V3_2"), + ("4.0", "V4_0"), ("4.1", "V4_1"), ("5.0", "V5_0"), ("5.1", "V5_1"), + ("5.2", "V5_2"), ("6.0", "V6_0"), ("6.1", "V6_1"), ("6.2", "V6_2"), + ("6.3", "V6_3"), ("7.0", "V7_0"), ("8.0", "V8_0"), ("9.0", "V9_0"), + ("na", "Unassigned"), ("unassigned", "Unassigned"), ("v100", "V10_0"), + ("v11", "V1_1"), ("v20", "V2_0"), ("v21", "V2_1"), ("v30", "V3_0"), + ("v31", "V3_1"), ("v32", "V3_2"), ("v40", "V4_0"), ("v41", "V4_1"), + ("v50", "V5_0"), ("v51", "V5_1"), ("v52", "V5_2"), ("v60", "V6_0"), + ("v61", "V6_1"), ("v62", "V6_2"), ("v63", "V6_3"), ("v70", "V7_0"), + ("v80", "V8_0"), ("v90", "V9_0"), ]), + + ("General_Category", &[("c", "Other"), ("casedletter", "Cased_Letter"), + ("cc", "Control"), ("cf", "Format"), + ("closepunctuation", "Close_Punctuation"), ("cn", "Unassigned"), + ("cntrl", "Control"), ("co", "Private_Use"), ("combiningmark", "Mark"), + ("connectorpunctuation", "Connector_Punctuation"), ("control", "Control"), + ("cs", "Surrogate"), ("currencysymbol", "Currency_Symbol"), + ("dashpunctuation", "Dash_Punctuation"), + ("decimalnumber", "Decimal_Number"), ("digit", "Decimal_Number"), + ("enclosingmark", "Enclosing_Mark"), + ("finalpunctuation", "Final_Punctuation"), ("format", "Format"), + ("initialpunctuation", "Initial_Punctuation"), ("l", "Letter"), + ("lc", "Cased_Letter"), ("letter", "Letter"), + ("letternumber", "Letter_Number"), ("lineseparator", "Line_Separator"), + ("ll", "Lowercase_Letter"), ("lm", "Modifier_Letter"), + ("lo", "Other_Letter"), ("lowercaseletter", "Lowercase_Letter"), + ("lt", "Titlecase_Letter"), ("lu", "Uppercase_Letter"), ("m", "Mark"), + ("mark", "Mark"), ("mathsymbol", "Math_Symbol"), ("mc", "Spacing_Mark"), + ("me", "Enclosing_Mark"), ("mn", "Nonspacing_Mark"), + ("modifierletter", "Modifier_Letter"), + ("modifiersymbol", "Modifier_Symbol"), ("n", "Number"), + ("nd", "Decimal_Number"), ("nl", "Letter_Number"), ("no", "Other_Number"), + ("nonspacingmark", "Nonspacing_Mark"), ("number", "Number"), + ("openpunctuation", "Open_Punctuation"), ("other", "Other"), + ("otherletter", "Other_Letter"), ("othernumber", "Other_Number"), + ("otherpunctuation", "Other_Punctuation"), ("othersymbol", "Other_Symbol"), + ("p", "Punctuation"), ("paragraphseparator", "Paragraph_Separator"), + ("pc", "Connector_Punctuation"), ("pd", "Dash_Punctuation"), + ("pe", "Close_Punctuation"), ("pf", "Final_Punctuation"), + ("pi", "Initial_Punctuation"), ("po", "Other_Punctuation"), + ("privateuse", "Private_Use"), ("ps", "Open_Punctuation"), + ("punct", "Punctuation"), ("punctuation", "Punctuation"), ("s", "Symbol"), + ("sc", "Currency_Symbol"), ("separator", "Separator"), + ("sk", "Modifier_Symbol"), ("sm", "Math_Symbol"), ("so", "Other_Symbol"), + ("spaceseparator", "Space_Separator"), ("spacingmark", "Spacing_Mark"), + ("surrogate", "Surrogate"), ("symbol", "Symbol"), + ("titlecaseletter", "Titlecase_Letter"), ("unassigned", "Unassigned"), + ("uppercaseletter", "Uppercase_Letter"), ("z", "Separator"), + ("zl", "Line_Separator"), ("zp", "Paragraph_Separator"), + ("zs", "Space_Separator"), ]), + + ("Script", &[("adlam", "Adlam"), ("adlm", "Adlam"), + ("aghb", "Caucasian_Albanian"), ("ahom", "Ahom"), + ("anatolianhieroglyphs", "Anatolian_Hieroglyphs"), ("arab", "Arabic"), + ("arabic", "Arabic"), ("armenian", "Armenian"), + ("armi", "Imperial_Aramaic"), ("armn", "Armenian"), ("avestan", "Avestan"), + ("avst", "Avestan"), ("bali", "Balinese"), ("balinese", "Balinese"), + ("bamu", "Bamum"), ("bamum", "Bamum"), ("bass", "Bassa_Vah"), + ("bassavah", "Bassa_Vah"), ("batak", "Batak"), ("batk", "Batak"), + ("beng", "Bengali"), ("bengali", "Bengali"), ("bhaiksuki", "Bhaiksuki"), + ("bhks", "Bhaiksuki"), ("bopo", "Bopomofo"), ("bopomofo", "Bopomofo"), + ("brah", "Brahmi"), ("brahmi", "Brahmi"), ("brai", "Braille"), + ("braille", "Braille"), ("bugi", "Buginese"), ("buginese", "Buginese"), + ("buhd", "Buhid"), ("buhid", "Buhid"), ("cakm", "Chakma"), + ("canadianaboriginal", "Canadian_Aboriginal"), + ("cans", "Canadian_Aboriginal"), ("cari", "Carian"), ("carian", "Carian"), + ("caucasianalbanian", "Caucasian_Albanian"), ("chakma", "Chakma"), + ("cham", "Cham"), ("cher", "Cherokee"), ("cherokee", "Cherokee"), + ("common", "Common"), ("copt", "Coptic"), ("coptic", "Coptic"), + ("cprt", "Cypriot"), ("cuneiform", "Cuneiform"), ("cypriot", "Cypriot"), + ("cyrillic", "Cyrillic"), ("cyrl", "Cyrillic"), ("deseret", "Deseret"), + ("deva", "Devanagari"), ("devanagari", "Devanagari"), ("dsrt", "Deseret"), + ("dupl", "Duployan"), ("duployan", "Duployan"), + ("egyp", "Egyptian_Hieroglyphs"), + ("egyptianhieroglyphs", "Egyptian_Hieroglyphs"), ("elba", "Elbasan"), + ("elbasan", "Elbasan"), ("ethi", "Ethiopic"), ("ethiopic", "Ethiopic"), + ("geor", "Georgian"), ("georgian", "Georgian"), ("glag", "Glagolitic"), + ("glagolitic", "Glagolitic"), ("gonm", "Masaram_Gondi"), ("goth", "Gothic"), + ("gothic", "Gothic"), ("gran", "Grantha"), ("grantha", "Grantha"), + ("greek", "Greek"), ("grek", "Greek"), ("gujarati", "Gujarati"), + ("gujr", "Gujarati"), ("gurmukhi", "Gurmukhi"), ("guru", "Gurmukhi"), + ("han", "Han"), ("hang", "Hangul"), ("hangul", "Hangul"), ("hani", "Han"), + ("hano", "Hanunoo"), ("hanunoo", "Hanunoo"), ("hatr", "Hatran"), + ("hatran", "Hatran"), ("hebr", "Hebrew"), ("hebrew", "Hebrew"), + ("hira", "Hiragana"), ("hiragana", "Hiragana"), + ("hluw", "Anatolian_Hieroglyphs"), ("hmng", "Pahawh_Hmong"), + ("hrkt", "Katakana_Or_Hiragana"), ("hung", "Old_Hungarian"), + ("imperialaramaic", "Imperial_Aramaic"), ("inherited", "Inherited"), + ("inscriptionalpahlavi", "Inscriptional_Pahlavi"), + ("inscriptionalparthian", "Inscriptional_Parthian"), ("ital", "Old_Italic"), + ("java", "Javanese"), ("javanese", "Javanese"), ("kaithi", "Kaithi"), + ("kali", "Kayah_Li"), ("kana", "Katakana"), ("kannada", "Kannada"), + ("katakana", "Katakana"), ("katakanaorhiragana", "Katakana_Or_Hiragana"), + ("kayahli", "Kayah_Li"), ("khar", "Kharoshthi"), + ("kharoshthi", "Kharoshthi"), ("khmer", "Khmer"), ("khmr", "Khmer"), + ("khoj", "Khojki"), ("khojki", "Khojki"), ("khudawadi", "Khudawadi"), + ("knda", "Kannada"), ("kthi", "Kaithi"), ("lana", "Tai_Tham"), + ("lao", "Lao"), ("laoo", "Lao"), ("latin", "Latin"), ("latn", "Latin"), + ("lepc", "Lepcha"), ("lepcha", "Lepcha"), ("limb", "Limbu"), + ("limbu", "Limbu"), ("lina", "Linear_A"), ("linb", "Linear_B"), + ("lineara", "Linear_A"), ("linearb", "Linear_B"), ("lisu", "Lisu"), + ("lyci", "Lycian"), ("lycian", "Lycian"), ("lydi", "Lydian"), + ("lydian", "Lydian"), ("mahajani", "Mahajani"), ("mahj", "Mahajani"), + ("malayalam", "Malayalam"), ("mand", "Mandaic"), ("mandaic", "Mandaic"), + ("mani", "Manichaean"), ("manichaean", "Manichaean"), ("marc", "Marchen"), + ("marchen", "Marchen"), ("masaramgondi", "Masaram_Gondi"), + ("meeteimayek", "Meetei_Mayek"), ("mend", "Mende_Kikakui"), + ("mendekikakui", "Mende_Kikakui"), ("merc", "Meroitic_Cursive"), + ("mero", "Meroitic_Hieroglyphs"), ("meroiticcursive", "Meroitic_Cursive"), + ("meroitichieroglyphs", "Meroitic_Hieroglyphs"), ("miao", "Miao"), + ("mlym", "Malayalam"), ("modi", "Modi"), ("mong", "Mongolian"), + ("mongolian", "Mongolian"), ("mro", "Mro"), ("mroo", "Mro"), + ("mtei", "Meetei_Mayek"), ("mult", "Multani"), ("multani", "Multani"), + ("myanmar", "Myanmar"), ("mymr", "Myanmar"), ("nabataean", "Nabataean"), + ("narb", "Old_North_Arabian"), ("nbat", "Nabataean"), ("newa", "Newa"), + ("newtailue", "New_Tai_Lue"), ("nko", "Nko"), ("nkoo", "Nko"), + ("nshu", "Nushu"), ("nushu", "Nushu"), ("ogam", "Ogham"), + ("ogham", "Ogham"), ("olchiki", "Ol_Chiki"), ("olck", "Ol_Chiki"), + ("oldhungarian", "Old_Hungarian"), ("olditalic", "Old_Italic"), + ("oldnortharabian", "Old_North_Arabian"), ("oldpermic", "Old_Permic"), + ("oldpersian", "Old_Persian"), ("oldsoutharabian", "Old_South_Arabian"), + ("oldturkic", "Old_Turkic"), ("oriya", "Oriya"), ("orkh", "Old_Turkic"), + ("orya", "Oriya"), ("osage", "Osage"), ("osge", "Osage"), + ("osma", "Osmanya"), ("osmanya", "Osmanya"), + ("pahawhhmong", "Pahawh_Hmong"), ("palm", "Palmyrene"), + ("palmyrene", "Palmyrene"), ("pauc", "Pau_Cin_Hau"), + ("paucinhau", "Pau_Cin_Hau"), ("perm", "Old_Permic"), ("phag", "Phags_Pa"), + ("phagspa", "Phags_Pa"), ("phli", "Inscriptional_Pahlavi"), + ("phlp", "Psalter_Pahlavi"), ("phnx", "Phoenician"), + ("phoenician", "Phoenician"), ("plrd", "Miao"), + ("prti", "Inscriptional_Parthian"), ("psalterpahlavi", "Psalter_Pahlavi"), + ("qaac", "Coptic"), ("qaai", "Inherited"), ("rejang", "Rejang"), + ("rjng", "Rejang"), ("runic", "Runic"), ("runr", "Runic"), + ("samaritan", "Samaritan"), ("samr", "Samaritan"), + ("sarb", "Old_South_Arabian"), ("saur", "Saurashtra"), + ("saurashtra", "Saurashtra"), ("sgnw", "SignWriting"), + ("sharada", "Sharada"), ("shavian", "Shavian"), ("shaw", "Shavian"), + ("shrd", "Sharada"), ("sidd", "Siddham"), ("siddham", "Siddham"), + ("signwriting", "SignWriting"), ("sind", "Khudawadi"), ("sinh", "Sinhala"), + ("sinhala", "Sinhala"), ("sora", "Sora_Sompeng"), + ("sorasompeng", "Sora_Sompeng"), ("soyo", "Soyombo"), + ("soyombo", "Soyombo"), ("sund", "Sundanese"), ("sundanese", "Sundanese"), + ("sylo", "Syloti_Nagri"), ("sylotinagri", "Syloti_Nagri"), + ("syrc", "Syriac"), ("syriac", "Syriac"), ("tagalog", "Tagalog"), + ("tagb", "Tagbanwa"), ("tagbanwa", "Tagbanwa"), ("taile", "Tai_Le"), + ("taitham", "Tai_Tham"), ("taiviet", "Tai_Viet"), ("takr", "Takri"), + ("takri", "Takri"), ("tale", "Tai_Le"), ("talu", "New_Tai_Lue"), + ("tamil", "Tamil"), ("taml", "Tamil"), ("tang", "Tangut"), + ("tangut", "Tangut"), ("tavt", "Tai_Viet"), ("telu", "Telugu"), + ("telugu", "Telugu"), ("tfng", "Tifinagh"), ("tglg", "Tagalog"), + ("thaa", "Thaana"), ("thaana", "Thaana"), ("thai", "Thai"), + ("tibetan", "Tibetan"), ("tibt", "Tibetan"), ("tifinagh", "Tifinagh"), + ("tirh", "Tirhuta"), ("tirhuta", "Tirhuta"), ("ugar", "Ugaritic"), + ("ugaritic", "Ugaritic"), ("unknown", "Unknown"), ("vai", "Vai"), + ("vaii", "Vai"), ("wara", "Warang_Citi"), ("warangciti", "Warang_Citi"), + ("xpeo", "Old_Persian"), ("xsux", "Cuneiform"), ("yi", "Yi"), + ("yiii", "Yi"), ("zanabazarsquare", "Zanabazar_Square"), + ("zanb", "Zanabazar_Square"), ("zinh", "Inherited"), ("zyyy", "Common"), + ("zzzz", "Unknown"), ]), + + ("Script_Extensions", &[("adlam", "Adlam"), ("adlm", "Adlam"), + ("aghb", "Caucasian_Albanian"), ("ahom", "Ahom"), + ("anatolianhieroglyphs", "Anatolian_Hieroglyphs"), ("arab", "Arabic"), + ("arabic", "Arabic"), ("armenian", "Armenian"), + ("armi", "Imperial_Aramaic"), ("armn", "Armenian"), ("avestan", "Avestan"), + ("avst", "Avestan"), ("bali", "Balinese"), ("balinese", "Balinese"), + ("bamu", "Bamum"), ("bamum", "Bamum"), ("bass", "Bassa_Vah"), + ("bassavah", "Bassa_Vah"), ("batak", "Batak"), ("batk", "Batak"), + ("beng", "Bengali"), ("bengali", "Bengali"), ("bhaiksuki", "Bhaiksuki"), + ("bhks", "Bhaiksuki"), ("bopo", "Bopomofo"), ("bopomofo", "Bopomofo"), + ("brah", "Brahmi"), ("brahmi", "Brahmi"), ("brai", "Braille"), + ("braille", "Braille"), ("bugi", "Buginese"), ("buginese", "Buginese"), + ("buhd", "Buhid"), ("buhid", "Buhid"), ("cakm", "Chakma"), + ("canadianaboriginal", "Canadian_Aboriginal"), + ("cans", "Canadian_Aboriginal"), ("cari", "Carian"), ("carian", "Carian"), + ("caucasianalbanian", "Caucasian_Albanian"), ("chakma", "Chakma"), + ("cham", "Cham"), ("cher", "Cherokee"), ("cherokee", "Cherokee"), + ("common", "Common"), ("copt", "Coptic"), ("coptic", "Coptic"), + ("cprt", "Cypriot"), ("cuneiform", "Cuneiform"), ("cypriot", "Cypriot"), + ("cyrillic", "Cyrillic"), ("cyrl", "Cyrillic"), ("deseret", "Deseret"), + ("deva", "Devanagari"), ("devanagari", "Devanagari"), ("dsrt", "Deseret"), + ("dupl", "Duployan"), ("duployan", "Duployan"), + ("egyp", "Egyptian_Hieroglyphs"), + ("egyptianhieroglyphs", "Egyptian_Hieroglyphs"), ("elba", "Elbasan"), + ("elbasan", "Elbasan"), ("ethi", "Ethiopic"), ("ethiopic", "Ethiopic"), + ("geor", "Georgian"), ("georgian", "Georgian"), ("glag", "Glagolitic"), + ("glagolitic", "Glagolitic"), ("gonm", "Masaram_Gondi"), ("goth", "Gothic"), + ("gothic", "Gothic"), ("gran", "Grantha"), ("grantha", "Grantha"), + ("greek", "Greek"), ("grek", "Greek"), ("gujarati", "Gujarati"), + ("gujr", "Gujarati"), ("gurmukhi", "Gurmukhi"), ("guru", "Gurmukhi"), + ("han", "Han"), ("hang", "Hangul"), ("hangul", "Hangul"), ("hani", "Han"), + ("hano", "Hanunoo"), ("hanunoo", "Hanunoo"), ("hatr", "Hatran"), + ("hatran", "Hatran"), ("hebr", "Hebrew"), ("hebrew", "Hebrew"), + ("hira", "Hiragana"), ("hiragana", "Hiragana"), + ("hluw", "Anatolian_Hieroglyphs"), ("hmng", "Pahawh_Hmong"), + ("hrkt", "Katakana_Or_Hiragana"), ("hung", "Old_Hungarian"), + ("imperialaramaic", "Imperial_Aramaic"), ("inherited", "Inherited"), + ("inscriptionalpahlavi", "Inscriptional_Pahlavi"), + ("inscriptionalparthian", "Inscriptional_Parthian"), ("ital", "Old_Italic"), + ("java", "Javanese"), ("javanese", "Javanese"), ("kaithi", "Kaithi"), + ("kali", "Kayah_Li"), ("kana", "Katakana"), ("kannada", "Kannada"), + ("katakana", "Katakana"), ("katakanaorhiragana", "Katakana_Or_Hiragana"), + ("kayahli", "Kayah_Li"), ("khar", "Kharoshthi"), + ("kharoshthi", "Kharoshthi"), ("khmer", "Khmer"), ("khmr", "Khmer"), + ("khoj", "Khojki"), ("khojki", "Khojki"), ("khudawadi", "Khudawadi"), + ("knda", "Kannada"), ("kthi", "Kaithi"), ("lana", "Tai_Tham"), + ("lao", "Lao"), ("laoo", "Lao"), ("latin", "Latin"), ("latn", "Latin"), + ("lepc", "Lepcha"), ("lepcha", "Lepcha"), ("limb", "Limbu"), + ("limbu", "Limbu"), ("lina", "Linear_A"), ("linb", "Linear_B"), + ("lineara", "Linear_A"), ("linearb", "Linear_B"), ("lisu", "Lisu"), + ("lyci", "Lycian"), ("lycian", "Lycian"), ("lydi", "Lydian"), + ("lydian", "Lydian"), ("mahajani", "Mahajani"), ("mahj", "Mahajani"), + ("malayalam", "Malayalam"), ("mand", "Mandaic"), ("mandaic", "Mandaic"), + ("mani", "Manichaean"), ("manichaean", "Manichaean"), ("marc", "Marchen"), + ("marchen", "Marchen"), ("masaramgondi", "Masaram_Gondi"), + ("meeteimayek", "Meetei_Mayek"), ("mend", "Mende_Kikakui"), + ("mendekikakui", "Mende_Kikakui"), ("merc", "Meroitic_Cursive"), + ("mero", "Meroitic_Hieroglyphs"), ("meroiticcursive", "Meroitic_Cursive"), + ("meroitichieroglyphs", "Meroitic_Hieroglyphs"), ("miao", "Miao"), + ("mlym", "Malayalam"), ("modi", "Modi"), ("mong", "Mongolian"), + ("mongolian", "Mongolian"), ("mro", "Mro"), ("mroo", "Mro"), + ("mtei", "Meetei_Mayek"), ("mult", "Multani"), ("multani", "Multani"), + ("myanmar", "Myanmar"), ("mymr", "Myanmar"), ("nabataean", "Nabataean"), + ("narb", "Old_North_Arabian"), ("nbat", "Nabataean"), ("newa", "Newa"), + ("newtailue", "New_Tai_Lue"), ("nko", "Nko"), ("nkoo", "Nko"), + ("nshu", "Nushu"), ("nushu", "Nushu"), ("ogam", "Ogham"), + ("ogham", "Ogham"), ("olchiki", "Ol_Chiki"), ("olck", "Ol_Chiki"), + ("oldhungarian", "Old_Hungarian"), ("olditalic", "Old_Italic"), + ("oldnortharabian", "Old_North_Arabian"), ("oldpermic", "Old_Permic"), + ("oldpersian", "Old_Persian"), ("oldsoutharabian", "Old_South_Arabian"), + ("oldturkic", "Old_Turkic"), ("oriya", "Oriya"), ("orkh", "Old_Turkic"), + ("orya", "Oriya"), ("osage", "Osage"), ("osge", "Osage"), + ("osma", "Osmanya"), ("osmanya", "Osmanya"), + ("pahawhhmong", "Pahawh_Hmong"), ("palm", "Palmyrene"), + ("palmyrene", "Palmyrene"), ("pauc", "Pau_Cin_Hau"), + ("paucinhau", "Pau_Cin_Hau"), ("perm", "Old_Permic"), ("phag", "Phags_Pa"), + ("phagspa", "Phags_Pa"), ("phli", "Inscriptional_Pahlavi"), + ("phlp", "Psalter_Pahlavi"), ("phnx", "Phoenician"), + ("phoenician", "Phoenician"), ("plrd", "Miao"), + ("prti", "Inscriptional_Parthian"), ("psalterpahlavi", "Psalter_Pahlavi"), + ("qaac", "Coptic"), ("qaai", "Inherited"), ("rejang", "Rejang"), + ("rjng", "Rejang"), ("runic", "Runic"), ("runr", "Runic"), + ("samaritan", "Samaritan"), ("samr", "Samaritan"), + ("sarb", "Old_South_Arabian"), ("saur", "Saurashtra"), + ("saurashtra", "Saurashtra"), ("sgnw", "SignWriting"), + ("sharada", "Sharada"), ("shavian", "Shavian"), ("shaw", "Shavian"), + ("shrd", "Sharada"), ("sidd", "Siddham"), ("siddham", "Siddham"), + ("signwriting", "SignWriting"), ("sind", "Khudawadi"), ("sinh", "Sinhala"), + ("sinhala", "Sinhala"), ("sora", "Sora_Sompeng"), + ("sorasompeng", "Sora_Sompeng"), ("soyo", "Soyombo"), + ("soyombo", "Soyombo"), ("sund", "Sundanese"), ("sundanese", "Sundanese"), + ("sylo", "Syloti_Nagri"), ("sylotinagri", "Syloti_Nagri"), + ("syrc", "Syriac"), ("syriac", "Syriac"), ("tagalog", "Tagalog"), + ("tagb", "Tagbanwa"), ("tagbanwa", "Tagbanwa"), ("taile", "Tai_Le"), + ("taitham", "Tai_Tham"), ("taiviet", "Tai_Viet"), ("takr", "Takri"), + ("takri", "Takri"), ("tale", "Tai_Le"), ("talu", "New_Tai_Lue"), + ("tamil", "Tamil"), ("taml", "Tamil"), ("tang", "Tangut"), + ("tangut", "Tangut"), ("tavt", "Tai_Viet"), ("telu", "Telugu"), + ("telugu", "Telugu"), ("tfng", "Tifinagh"), ("tglg", "Tagalog"), + ("thaa", "Thaana"), ("thaana", "Thaana"), ("thai", "Thai"), + ("tibetan", "Tibetan"), ("tibt", "Tibetan"), ("tifinagh", "Tifinagh"), + ("tirh", "Tirhuta"), ("tirhuta", "Tirhuta"), ("ugar", "Ugaritic"), + ("ugaritic", "Ugaritic"), ("unknown", "Unknown"), ("vai", "Vai"), + ("vaii", "Vai"), ("wara", "Warang_Citi"), ("warangciti", "Warang_Citi"), + ("xpeo", "Old_Persian"), ("xsux", "Cuneiform"), ("yi", "Yi"), + ("yiii", "Yi"), ("zanabazarsquare", "Zanabazar_Square"), + ("zanb", "Zanabazar_Square"), ("zinh", "Inherited"), ("zyyy", "Common"), + ("zzzz", "Unknown"), ]), +]; diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/script_extension.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/script_extension.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/script_extension.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/script_extension.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,785 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate script-extension tmp/ucd-10.0.0/ --chars +// +// ucd-generate is available on crates.io. + +pub const BY_NAME: &'static [(&'static str, &'static [(char, char)])] = &[ + ("Adlam", ADLAM), ("Ahom", AHOM), + ("Anatolian_Hieroglyphs", ANATOLIAN_HIEROGLYPHS), ("Arabic", ARABIC), + ("Armenian", ARMENIAN), ("Avestan", AVESTAN), ("Balinese", BALINESE), + ("Bamum", BAMUM), ("Bassa_Vah", BASSA_VAH), ("Batak", BATAK), + ("Bengali", BENGALI), ("Bhaiksuki", BHAIKSUKI), ("Bopomofo", BOPOMOFO), + ("Brahmi", BRAHMI), ("Braille", BRAILLE), ("Buginese", BUGINESE), + ("Buhid", BUHID), ("Canadian_Aboriginal", CANADIAN_ABORIGINAL), + ("Carian", CARIAN), ("Caucasian_Albanian", CAUCASIAN_ALBANIAN), + ("Chakma", CHAKMA), ("Cham", CHAM), ("Cherokee", CHEROKEE), + ("Common", COMMON), ("Coptic", COPTIC), ("Cuneiform", CUNEIFORM), + ("Cypriot", CYPRIOT), ("Cyrillic", CYRILLIC), ("Deseret", DESERET), + ("Devanagari", DEVANAGARI), ("Duployan", DUPLOYAN), + ("Egyptian_Hieroglyphs", EGYPTIAN_HIEROGLYPHS), ("Elbasan", ELBASAN), + ("Ethiopic", ETHIOPIC), ("Georgian", GEORGIAN), ("Glagolitic", GLAGOLITIC), + ("Gothic", GOTHIC), ("Grantha", GRANTHA), ("Greek", GREEK), + ("Gujarati", GUJARATI), ("Gurmukhi", GURMUKHI), ("Han", HAN), + ("Hangul", HANGUL), ("Hanunoo", HANUNOO), ("Hatran", HATRAN), + ("Hebrew", HEBREW), ("Hiragana", HIRAGANA), + ("Imperial_Aramaic", IMPERIAL_ARAMAIC), ("Inherited", INHERITED), + ("Inscriptional_Pahlavi", INSCRIPTIONAL_PAHLAVI), + ("Inscriptional_Parthian", INSCRIPTIONAL_PARTHIAN), ("Javanese", JAVANESE), + ("Kaithi", KAITHI), ("Kannada", KANNADA), ("Katakana", KATAKANA), + ("Kayah_Li", KAYAH_LI), ("Kharoshthi", KHAROSHTHI), ("Khmer", KHMER), + ("Khojki", KHOJKI), ("Khudawadi", KHUDAWADI), ("Lao", LAO), + ("Latin", LATIN), ("Lepcha", LEPCHA), ("Limbu", LIMBU), + ("Linear_A", LINEAR_A), ("Linear_B", LINEAR_B), ("Lisu", LISU), + ("Lycian", LYCIAN), ("Lydian", LYDIAN), ("Mahajani", MAHAJANI), + ("Malayalam", MALAYALAM), ("Mandaic", MANDAIC), ("Manichaean", MANICHAEAN), + ("Marchen", MARCHEN), ("Masaram_Gondi", MASARAM_GONDI), + ("Meetei_Mayek", MEETEI_MAYEK), ("Mende_Kikakui", MENDE_KIKAKUI), + ("Meroitic_Cursive", MEROITIC_CURSIVE), + ("Meroitic_Hieroglyphs", MEROITIC_HIEROGLYPHS), ("Miao", MIAO), + ("Modi", MODI), ("Mongolian", MONGOLIAN), ("Mro", MRO), + ("Multani", MULTANI), ("Myanmar", MYANMAR), ("Nabataean", NABATAEAN), + ("New_Tai_Lue", NEW_TAI_LUE), ("Newa", NEWA), ("Nko", NKO), + ("Nushu", NUSHU), ("Ogham", OGHAM), ("Ol_Chiki", OL_CHIKI), + ("Old_Hungarian", OLD_HUNGARIAN), ("Old_Italic", OLD_ITALIC), + ("Old_North_Arabian", OLD_NORTH_ARABIAN), ("Old_Permic", OLD_PERMIC), + ("Old_Persian", OLD_PERSIAN), ("Old_South_Arabian", OLD_SOUTH_ARABIAN), + ("Old_Turkic", OLD_TURKIC), ("Oriya", ORIYA), ("Osage", OSAGE), + ("Osmanya", OSMANYA), ("Pahawh_Hmong", PAHAWH_HMONG), + ("Palmyrene", PALMYRENE), ("Pau_Cin_Hau", PAU_CIN_HAU), + ("Phags_Pa", PHAGS_PA), ("Phoenician", PHOENICIAN), + ("Psalter_Pahlavi", PSALTER_PAHLAVI), ("Rejang", REJANG), ("Runic", RUNIC), + ("Samaritan", SAMARITAN), ("Saurashtra", SAURASHTRA), ("Sharada", SHARADA), + ("Shavian", SHAVIAN), ("Siddham", SIDDHAM), ("SignWriting", SIGNWRITING), + ("Sinhala", SINHALA), ("Sora_Sompeng", SORA_SOMPENG), ("Soyombo", SOYOMBO), + ("Sundanese", SUNDANESE), ("Syloti_Nagri", SYLOTI_NAGRI), + ("Syriac", SYRIAC), ("Tagalog", TAGALOG), ("Tagbanwa", TAGBANWA), + ("Tai_Le", TAI_LE), ("Tai_Tham", TAI_THAM), ("Tai_Viet", TAI_VIET), + ("Takri", TAKRI), ("Tamil", TAMIL), ("Tangut", TANGUT), ("Telugu", TELUGU), + ("Thaana", THAANA), ("Thai", THAI), ("Tibetan", TIBETAN), + ("Tifinagh", TIFINAGH), ("Tirhuta", TIRHUTA), ("Ugaritic", UGARITIC), + ("Vai", VAI), ("Warang_Citi", WARANG_CITI), ("Yi", YI), + ("Zanabazar_Square", ZANABAZAR_SQUARE), +]; + +pub const ADLAM: &'static [(char, char)] = &[ + ('ـ', 'ـ'), ('𞤀', '𞥊'), ('𞥐', '𞥙'), ('𞥞', '𞥟'), +]; + +pub const AHOM: &'static [(char, char)] = &[ + ('𑜀', '𑜙'), ('𑜝', '𑜫'), ('𑜰', '𑜿'), +]; + +pub const ANATOLIAN_HIEROGLYPHS: &'static [(char, char)] = &[ + ('𔐀', '𔙆'), +]; + +pub const ARABIC: &'static [(char, char)] = &[ + ('\u{600}', '\u{604}'), ('؆', '\u{61c}'), ('؞', 'ۜ'), ('۞', 'ۿ'), + ('ݐ', 'ݿ'), ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ࣔ', '࣡'), + ('ࣣ', 'ࣿ'), ('ﭐ', '﯁'), ('ﯓ', 'ﴽ'), ('ﵐ', 'ﶏ'), + ('ﶒ', 'ﷇ'), ('ﷰ', '﷽'), ('ﹰ', 'ﹴ'), ('ﹶ', 'ﻼ'), + ('𐋠', '𐋻'), ('𐹠', '𐹾'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), + ('𞸡', '𞸢'), ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), + ('𞸴', '𞸷'), ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), + ('𞹇', '𞹇'), ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), + ('𞹑', '𞹒'), ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), + ('𞹛', '𞹛'), ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), + ('𞹤', '𞹤'), ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), + ('𞹹', '𞹼'), ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), + ('𞺡', '𞺣'), ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𞻰', '𞻱'), +]; + +pub const ARMENIAN: &'static [(char, char)] = &[ + ('Ա', 'Ֆ'), ('ՙ', '՟'), ('ա', 'և'), ('։', '֊'), ('֍', '֏'), + ('ﬓ', 'ﬗ'), +]; + +pub const AVESTAN: &'static [(char, char)] = &[ + ('𐬀', '𐬵'), ('𐬹', '𐬿'), +]; + +pub const BALINESE: &'static [(char, char)] = &[ + ('ᬀ', 'ᭋ'), ('᭐', '᭼'), +]; + +pub const BAMUM: &'static [(char, char)] = &[ + ('ꚠ', '꛷'), ('𖠀', '𖨸'), +]; + +pub const BASSA_VAH: &'static [(char, char)] = &[ + ('𖫐', '𖫭'), ('𖫰', '𖫵'), +]; + +pub const BATAK: &'static [(char, char)] = &[ + ('ᯀ', '᯳'), ('᯼', '᯿'), +]; + +pub const BENGALI: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ঀ', 'ঃ'), ('অ', 'ঌ'), + ('এ', 'ঐ'), ('ও', 'ন'), ('প', 'র'), ('ল', 'ল'), + ('শ', 'হ'), ('়', 'ৄ'), ('ে', 'ৈ'), ('ো', 'ৎ'), + ('ৗ', 'ৗ'), ('ড়', 'ঢ়'), ('য়', 'ৣ'), ('০', '৽'), + ('᳷', '᳷'), ('꣱', '꣱'), +]; + +pub const BHAIKSUKI: &'static [(char, char)] = &[ + ('𑰀', '𑰈'), ('𑰊', '𑰶'), ('𑰸', '𑱅'), ('𑱐', '𑱬'), +]; + +pub const BOPOMOFO: &'static [(char, char)] = &[ + ('˪', '˫'), ('、', '〃'), ('〈', '】'), ('〓', '〟'), + ('〪', '〭'), ('〰', '〰'), ('〷', '〷'), ('・', '・'), + ('ㄅ', 'ㄮ'), ('ㆠ', 'ㆺ'), ('﹅', '﹆'), ('。', '・'), +]; + +pub const BRAHMI: &'static [(char, char)] = &[ + ('𑀀', '𑁍'), ('𑁒', '𑁯'), ('𑁿', '𑁿'), +]; + +pub const BRAILLE: &'static [(char, char)] = &[ + ('⠀', '⣿'), +]; + +pub const BUGINESE: &'static [(char, char)] = &[ + ('ᨀ', 'ᨛ'), ('᨞', '᨟'), ('ꧏ', 'ꧏ'), +]; + +pub const BUHID: &'static [(char, char)] = &[ + ('᜵', '᜶'), ('ᝀ', 'ᝓ'), +]; + +pub const CANADIAN_ABORIGINAL: &'static [(char, char)] = &[ + ('᐀', 'ᙿ'), ('ᢰ', 'ᣵ'), +]; + +pub const CARIAN: &'static [(char, char)] = &[ + ('𐊠', '𐋐'), +]; + +pub const CAUCASIAN_ALBANIAN: &'static [(char, char)] = &[ + ('𐔰', '𐕣'), ('𐕯', '𐕯'), +]; + +pub const CHAKMA: &'static [(char, char)] = &[ + ('০', '৯'), ('၀', '၉'), ('𑄀', '𑄴'), ('𑄶', '𑅃'), +]; + +pub const CHAM: &'static [(char, char)] = &[ + ('ꨀ', 'ꨶ'), ('ꩀ', 'ꩍ'), ('꩐', '꩙'), ('꩜', '꩟'), +]; + +pub const CHEROKEE: &'static [(char, char)] = &[ + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ꭰ', 'ꮿ'), +]; + +pub const COMMON: &'static [(char, char)] = &[ + ('\u{0}', '@'), ('[', '`'), ('{', '©'), ('«', '¹'), ('»', '¿'), + ('×', '×'), ('÷', '÷'), ('ʹ', '˟'), ('˥', '˩'), ('ˬ', '˿'), + ('ʹ', 'ʹ'), (';', ';'), ('΅', '΅'), ('·', '·'), + ('\u{605}', '\u{605}'), ('\u{6dd}', '\u{6dd}'), ('\u{8e2}', '\u{8e2}'), + ('฿', '฿'), ('࿕', '࿘'), ('᛫', '᛭'), ('\u{2000}', '\u{200b}'), + ('\u{200e}', '\u{2064}'), ('\u{2066}', '⁰'), ('⁴', '⁾'), + ('₀', '₎'), ('₠', '₿'), ('℀', '℥'), ('℧', '℩'), + ('ℬ', 'ℱ'), ('ℳ', '⅍'), ('⅏', '⅟'), ('↉', '↋'), + ('←', '␦'), ('⑀', '⑊'), ('①', '⟿'), ('⤀', '⭳'), + ('⭶', '⮕'), ('⮘', '⮹'), ('⮽', '⯈'), ('⯊', '⯒'), + ('⯬', '⯯'), ('⸀', '⹂'), ('⹄', '⹉'), ('⿰', '⿻'), + ('\u{3000}', '\u{3000}'), ('〄', '〄'), ('〒', '〒'), ('〠', '〠'), + ('〶', '〶'), ('㉈', '㉟'), ('㉿', '㉿'), ('㊱', '㊿'), + ('㋌', '㋏'), ('㍱', '㍺'), ('㎀', '㏟'), ('㏿', '㏿'), + ('䷀', '䷿'), ('꜀', '꜡'), ('ꞈ', '꞊'), ('꭛', '꭛'), + ('﴾', '﴿'), ('︐', '︙'), ('︰', '﹄'), ('﹇', '﹒'), + ('﹔', '﹦'), ('﹨', '﹫'), ('\u{feff}', '\u{feff}'), ('!', '@'), + ('[', '`'), ('{', '⦆'), ('¢', '₩'), ('│', '○'), + ('\u{fff9}', '�'), ('𐆐', '𐆛'), ('𐇐', '𐇼'), ('𝀀', '𝃵'), + ('𝄀', '𝄦'), ('𝄩', '𝅦'), ('𝅪', '\u{1d17a}'), ('𝆃', '𝆄'), + ('𝆌', '𝆩'), ('𝆮', '𝇨'), ('𝌀', '𝍖'), ('𝐀', '𝑔'), + ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), ('𝒥', '𝒦'), + ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), ('𝒽', '𝓃'), + ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), ('𝔖', '𝔜'), + ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), ('𝕆', '𝕆'), + ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝟋'), ('𝟎', '𝟿'), + ('🀀', '🀫'), ('🀰', '🂓'), ('🂠', '🂮'), ('🂱', '🂿'), + ('🃁', '🃏'), ('🃑', '🃵'), ('🄀', '🄌'), ('🄐', '🄮'), + ('🄰', '🅫'), ('🅰', '🆬'), ('🇦', '🇿'), ('🈁', '🈂'), + ('🈐', '🈻'), ('🉀', '🉈'), ('🉠', '🉥'), ('🌀', '🛔'), + ('🛠', '🛬'), ('🛰', '🛸'), ('🜀', '🝳'), ('🞀', '🟔'), + ('🠀', '🠋'), ('🠐', '🡇'), ('🡐', '🡙'), ('🡠', '🢇'), + ('🢐', '🢭'), ('🤀', '🤋'), ('🤐', '🤾'), ('🥀', '🥌'), + ('🥐', '🥫'), ('🦀', '🦗'), ('🧀', '🧀'), ('🧐', '🧦'), + ('\u{e0001}', '\u{e0001}'), ('\u{e0020}', '\u{e007f}'), +]; + +pub const COPTIC: &'static [(char, char)] = &[ + ('Ϣ', 'ϯ'), ('Ⲁ', 'ⳳ'), ('⳹', '⳿'), ('𐋠', '𐋻'), +]; + +pub const CUNEIFORM: &'static [(char, char)] = &[ + ('𒀀', '𒎙'), ('𒐀', '𒑮'), ('𒑰', '𒑴'), ('𒒀', '𒕃'), +]; + +pub const CYPRIOT: &'static [(char, char)] = &[ + ('𐄀', '𐄂'), ('𐄇', '𐄳'), ('𐄷', '𐄿'), ('𐠀', '𐠅'), + ('𐠈', '𐠈'), ('𐠊', '𐠵'), ('𐠷', '𐠸'), ('𐠼', '𐠼'), + ('𐠿', '𐠿'), +]; + +pub const CYRILLIC: &'static [(char, char)] = &[ + ('Ѐ', 'ԯ'), ('ᲀ', 'ᲈ'), ('ᴫ', 'ᴫ'), ('ᵸ', 'ᵸ'), + ('ⷠ', 'ⷿ'), ('⹃', '⹃'), ('Ꙁ', 'ꚟ'), ('︮', '︯'), +]; + +pub const DESERET: &'static [(char, char)] = &[ + ('𐐀', '𐑏'), +]; + +pub const DEVANAGARI: &'static [(char, char)] = &[ + ('ऀ', 'ॿ'), ('᳐', 'ᳶ'), ('᳸', '᳹'), ('⃰', '⃰'), + ('꠰', '꠹'), ('꣠', 'ꣽ'), +]; + +pub const DUPLOYAN: &'static [(char, char)] = &[ + ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), ('𛲐', '𛲙'), + ('𛲜', '\u{1bca3}'), +]; + +pub const EGYPTIAN_HIEROGLYPHS: &'static [(char, char)] = &[ + ('𓀀', '𓐮'), +]; + +pub const ELBASAN: &'static [(char, char)] = &[ + ('𐔀', '𐔧'), +]; + +pub const ETHIOPIC: &'static [(char, char)] = &[ + ('ሀ', 'ቈ'), ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), + ('ቚ', 'ቝ'), ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), + ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), + ('ወ', 'ዖ'), ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), + ('፝', '፼'), ('ᎀ', '᎙'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), + ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), + ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('ꬁ', 'ꬆ'), + ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), +]; + +pub const GEORGIAN: &'static [(char, char)] = &[ + ('։', '։'), ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), + ('ა', 'ჿ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), +]; + +pub const GLAGOLITIC: &'static [(char, char)] = &[ + ('҄', '҄'), ('҇', '҇'), ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('⹃', '⹃'), + ('꙯', '꙯'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), ('𞀛', '𞀡'), + ('𞀣', '𞀤'), ('𞀦', '𞀪'), +]; + +pub const GOTHIC: &'static [(char, char)] = &[ + ('𐌰', '𐍊'), +]; + +pub const GRANTHA: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ப', 'ப'), ('வ', 'வ'), + ('௦', '௲'), ('᳐', '᳐'), ('᳒', '᳓'), ('ᳲ', '᳴'), + ('᳸', '᳹'), ('⃰', '⃰'), ('𑌀', '𑌃'), ('𑌅', '𑌌'), + ('𑌏', '𑌐'), ('𑌓', '𑌨'), ('𑌪', '𑌰'), ('𑌲', '𑌳'), + ('𑌵', '𑌹'), ('𑌼', '𑍄'), ('𑍇', '𑍈'), ('𑍋', '𑍍'), + ('𑍐', '𑍐'), ('𑍗', '𑍗'), ('𑍝', '𑍣'), ('𑍦', '𑍬'), + ('𑍰', '𑍴'), +]; + +pub const GREEK: &'static [(char, char)] = &[ + ('͂', '͂'), ('ͅ', 'ͅ'), ('Ͱ', 'ͳ'), ('͵', 'ͷ'), ('ͺ', 'ͽ'), + ('Ϳ', 'Ϳ'), ('΄', '΄'), ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), + ('Ύ', 'Ρ'), ('Σ', 'ϡ'), ('ϰ', 'Ͽ'), ('ᴦ', 'ᴪ'), ('ᵝ', 'ᵡ'), + ('ᵦ', 'ᵪ'), ('ᶿ', '᷁'), ('ἀ', 'ἕ'), ('Ἐ', 'Ἕ'), + ('ἠ', 'ὅ'), ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), + ('Ὓ', 'Ὓ'), ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), + ('ᾶ', 'ῄ'), ('ῆ', 'ΐ'), ('ῖ', 'Ί'), ('῝', '`'), + ('ῲ', 'ῴ'), ('ῶ', '῾'), ('Ω', 'Ω'), ('ꭥ', 'ꭥ'), + ('𐅀', '𐆎'), ('𐆠', '𐆠'), ('𝈀', '𝉅'), +]; + +pub const GUJARATI: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ઁ', 'ઃ'), ('અ', 'ઍ'), + ('એ', 'ઑ'), ('ઓ', 'ન'), ('પ', 'ર'), ('લ', 'ળ'), + ('વ', 'હ'), ('઼', 'ૅ'), ('ે', 'ૉ'), ('ો', '્'), + ('ૐ', 'ૐ'), ('ૠ', 'ૣ'), ('૦', '૱'), ('ૹ', '૿'), + ('꠰', '꠹'), +]; + +pub const GURMUKHI: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ਁ', 'ਃ'), ('ਅ', 'ਊ'), + ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), + ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), ('਼', '਼'), ('ਾ', 'ੂ'), + ('ੇ', 'ੈ'), ('ੋ', '੍'), ('ੑ', 'ੑ'), ('ਖ਼', 'ੜ'), + ('ਫ਼', 'ਫ਼'), ('੦', 'ੵ'), ('꠰', '꠹'), +]; + +pub const HAN: &'static [(char, char)] = &[ + ('⺀', '⺙'), ('⺛', '⻳'), ('⼀', '⿕'), ('、', '〃'), + ('々', '】'), ('〓', '〟'), ('〡', '〭'), ('〰', '〰'), + ('〷', '〿'), ('・', '・'), ('㆐', '㆟'), ('㇀', '㇣'), + ('㈠', '㉇'), ('㊀', '㊰'), ('㋀', '㋋'), ('㍘', '㍰'), + ('㍻', '㍿'), ('㏠', '㏾'), ('㐀', '䶵'), ('一', '鿪'), + ('豈', '舘'), ('並', '龎'), ('﹅', '﹆'), ('。', '・'), + ('𝍠', '𝍱'), ('🉐', '🉑'), ('𠀀', '𪛖'), ('𪜀', '𫜴'), + ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), ('丽', '𪘀'), +]; + +pub const HANGUL: &'static [(char, char)] = &[ + ('ᄀ', 'ᇿ'), ('、', '〃'), ('〈', '】'), ('〓', '〟'), + ('〮', '〰'), ('〷', '〷'), ('・', '・'), ('ㄱ', 'ㆎ'), + ('㈀', '㈞'), ('㉠', '㉾'), ('ꥠ', 'ꥼ'), ('가', '힣'), + ('ힰ', 'ퟆ'), ('ퟋ', 'ퟻ'), ('﹅', '﹆'), ('。', '・'), + ('ᅠ', 'ᄒ'), ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), ('ᅭ', 'ᅲ'), + ('ᅳ', 'ᅵ'), +]; + +pub const HANUNOO: &'static [(char, char)] = &[ + ('ᜠ', '᜶'), +]; + +pub const HATRAN: &'static [(char, char)] = &[ + ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐣻', '𐣿'), +]; + +pub const HEBREW: &'static [(char, char)] = &[ + ('֑', 'ׇ'), ('א', 'ת'), ('װ', '״'), ('יִ', 'זּ'), ('טּ', 'לּ'), + ('מּ', 'מּ'), ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﭏ'), +]; + +pub const HIRAGANA: &'static [(char, char)] = &[ + ('、', '〃'), ('〈', '】'), ('〓', '〟'), ('〰', '〵'), + ('〷', '〷'), ('〼', '〽'), ('ぁ', 'ゖ'), ('゙', '゠'), + ('・', 'ー'), ('﹅', '﹆'), ('。', '・'), ('ー', 'ー'), + ('゙', '゚'), ('𛀁', '𛄞'), ('🈀', '🈀'), +]; + +pub const IMPERIAL_ARAMAIC: &'static [(char, char)] = &[ + ('𐡀', '𐡕'), ('𐡗', '𐡟'), +]; + +pub const INHERITED: &'static [(char, char)] = &[ + ('̀', '́'), ('̓', '̈́'), ('͆', '͢'), ('᪰', '᪾'), ('᷂', '᷹'), + ('᷻', '᷿'), ('\u{200c}', '\u{200d}'), ('⃐', '⃯'), ('︀', '️'), + ('︠', '︭'), ('𐇽', '𐇽'), ('𝅧', '𝅩'), ('𝅻', '𝆂'), + ('𝆅', '𝆋'), ('𝆪', '𝆭'), ('󠄀', '󠇯'), +]; + +pub const INSCRIPTIONAL_PAHLAVI: &'static [(char, char)] = &[ + ('𐭠', '𐭲'), ('𐭸', '𐭿'), +]; + +pub const INSCRIPTIONAL_PARTHIAN: &'static [(char, char)] = &[ + ('𐭀', '𐭕'), ('𐭘', '𐭟'), +]; + +pub const JAVANESE: &'static [(char, char)] = &[ + ('ꦀ', '꧍'), ('ꧏ', '꧙'), ('꧞', '꧟'), +]; + +pub const KAITHI: &'static [(char, char)] = &[ + ('०', '९'), ('꠰', '꠹'), ('𑂀', '𑃁'), +]; + +pub const KANNADA: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ಀ', 'ಃ'), ('ಅ', 'ಌ'), + ('ಎ', 'ಐ'), ('ಒ', 'ನ'), ('ಪ', 'ಳ'), ('ವ', 'ಹ'), + ('಼', 'ೄ'), ('ೆ', 'ೈ'), ('ೊ', '್'), ('ೕ', 'ೖ'), + ('ೞ', 'ೞ'), ('ೠ', 'ೣ'), ('೦', '೯'), ('ೱ', 'ೲ'), + ('᳚', '᳚'), ('ᳵ', 'ᳵ'), ('꠰', '꠵'), +]; + +pub const KATAKANA: &'static [(char, char)] = &[ + ('、', '〃'), ('〈', '】'), ('〓', '〟'), ('〰', '〵'), + ('〷', '〷'), ('〼', '〽'), ('゙', '゜'), ('゠', 'ヿ'), + ('ㇰ', 'ㇿ'), ('㋐', '㋾'), ('㌀', '㍗'), ('﹅', '﹆'), + ('。', '゚'), ('𛀀', '𛀀'), +]; + +pub const KAYAH_LI: &'static [(char, char)] = &[ + ('꤀', '꤯'), +]; + +pub const KHAROSHTHI: &'static [(char, char)] = &[ + ('𐨀', '𐨃'), ('𐨅', '𐨆'), ('𐨌', '𐨓'), ('𐨕', '𐨗'), + ('𐨙', '𐨳'), ('𐨸', '𐨺'), ('𐨿', '𐩇'), ('𐩐', '𐩘'), +]; + +pub const KHMER: &'static [(char, char)] = &[ + ('ក', '៝'), ('០', '៩'), ('៰', '៹'), ('᧠', '᧿'), +]; + +pub const KHOJKI: &'static [(char, char)] = &[ + ('૦', '૯'), ('𑈀', '𑈑'), ('𑈓', '𑈾'), +]; + +pub const KHUDAWADI: &'static [(char, char)] = &[ + ('।', '॥'), ('꠰', '꠹'), ('𑊰', '𑋪'), ('𑋰', '𑋹'), +]; + +pub const LAO: &'static [(char, char)] = &[ + ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), + ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), + ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), + ('ົ', 'ຽ'), ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('່', 'ໍ'), + ('໐', '໙'), ('ໜ', 'ໟ'), +]; + +pub const LATIN: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('º', 'º'), ('À', 'Ö'), + ('Ø', 'ö'), ('ø', 'ʸ'), ('ˠ', 'ˤ'), ('ͣ', 'ͯ'), ('҅', '҆'), + ('॑', '॒'), ('჻', '჻'), ('ᴀ', 'ᴥ'), ('ᴬ', 'ᵜ'), + ('ᵢ', 'ᵥ'), ('ᵫ', 'ᵷ'), ('ᵹ', 'ᶾ'), ('Ḁ', 'ỿ'), + ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('⃰', '⃰'), + ('K', 'Å'), ('Ⅎ', 'Ⅎ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), + ('Ⱡ', 'Ɀ'), ('Ꜣ', 'ꞇ'), ('Ꞌ', 'Ɪ'), ('Ʞ', 'ꞷ'), + ('ꟷ', 'ꟿ'), ('꤮', '꤮'), ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭤ'), + ('ff', 'st'), ('A', 'Z'), ('a', 'z'), +]; + +pub const LEPCHA: &'static [(char, char)] = &[ + ('ᰀ', '᰷'), ('᰻', '᱉'), ('ᱍ', 'ᱏ'), +]; + +pub const LIMBU: &'static [(char, char)] = &[ + ('॥', '॥'), ('ᤀ', 'ᤞ'), ('ᤠ', 'ᤫ'), ('ᤰ', '᤻'), + ('᥀', '᥀'), ('᥄', '᥏'), +]; + +pub const LINEAR_A: &'static [(char, char)] = &[ + ('𐄇', '𐄳'), ('𐘀', '𐜶'), ('𐝀', '𐝕'), ('𐝠', '𐝧'), +]; + +pub const LINEAR_B: &'static [(char, char)] = &[ + ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), + ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), ('𐄀', '𐄂'), + ('𐄇', '𐄳'), ('𐄷', '𐄿'), +]; + +pub const LISU: &'static [(char, char)] = &[ + ('ꓐ', '꓿'), +]; + +pub const LYCIAN: &'static [(char, char)] = &[ + ('𐊀', '𐊜'), +]; + +pub const LYDIAN: &'static [(char, char)] = &[ + ('𐤠', '𐤹'), ('𐤿', '𐤿'), +]; + +pub const MAHAJANI: &'static [(char, char)] = &[ + ('।', '९'), ('꠰', '꠹'), ('𑅐', '𑅶'), +]; + +pub const MALAYALAM: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ഀ', 'ഃ'), ('അ', 'ഌ'), + ('എ', 'ഐ'), ('ഒ', 'ൄ'), ('െ', 'ൈ'), ('ൊ', '൏'), + ('ൔ', 'ൣ'), ('൦', 'ൿ'), ('᳚', '᳚'), +]; + +pub const MANDAIC: &'static [(char, char)] = &[ + ('ـ', 'ـ'), ('ࡀ', '࡛'), ('࡞', '࡞'), +]; + +pub const MANICHAEAN: &'static [(char, char)] = &[ + ('ـ', 'ـ'), ('𐫀', '𐫦'), ('𐫫', '𐫶'), +]; + +pub const MARCHEN: &'static [(char, char)] = &[ + ('𑱰', '𑲏'), ('𑲒', '𑲧'), ('𑲩', '𑲶'), +]; + +pub const MASARAM_GONDI: &'static [(char, char)] = &[ + ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴶'), ('𑴺', '𑴺'), + ('𑴼', '𑴽'), ('𑴿', '𑵇'), ('𑵐', '𑵙'), +]; + +pub const MEETEI_MAYEK: &'static [(char, char)] = &[ + ('ꫠ', '꫶'), ('ꯀ', '꯭'), ('꯰', '꯹'), +]; + +pub const MENDE_KIKAKUI: &'static [(char, char)] = &[ + ('𞠀', '𞣄'), ('𞣇', '𞣖'), +]; + +pub const MEROITIC_CURSIVE: &'static [(char, char)] = &[ + ('𐦠', '𐦷'), ('𐦼', '𐧏'), ('𐧒', '𐧿'), +]; + +pub const MEROITIC_HIEROGLYPHS: &'static [(char, char)] = &[ + ('𐦀', '𐦟'), +]; + +pub const MIAO: &'static [(char, char)] = &[ + ('𖼀', '𖽄'), ('𖽐', '𖽾'), ('𖾏', '𖾟'), +]; + +pub const MODI: &'static [(char, char)] = &[ + ('꠰', '꠹'), ('𑘀', '𑙄'), ('𑙐', '𑙙'), +]; + +pub const MONGOLIAN: &'static [(char, char)] = &[ + ('᠀', '\u{180e}'), ('᠐', '᠙'), ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢪ'), + ('𑙠', '𑙬'), +]; + +pub const MRO: &'static [(char, char)] = &[ + ('𖩀', '𖩞'), ('𖩠', '𖩩'), ('𖩮', '𖩯'), +]; + +pub const MULTANI: &'static [(char, char)] = &[ + ('੦', '੯'), ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), + ('𑊏', '𑊝'), ('𑊟', '𑊩'), +]; + +pub const MYANMAR: &'static [(char, char)] = &[ + ('က', '႟'), ('꤮', '꤮'), ('ꧠ', 'ꧾ'), ('ꩠ', 'ꩿ'), +]; + +pub const NABATAEAN: &'static [(char, char)] = &[ + ('𐢀', '𐢞'), ('𐢧', '𐢯'), +]; + +pub const NEW_TAI_LUE: &'static [(char, char)] = &[ + ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), ('᧐', '᧚'), ('᧞', '᧟'), +]; + +pub const NEWA: &'static [(char, char)] = &[ + ('𑐀', '𑑙'), ('𑑛', '𑑛'), ('𑑝', '𑑝'), +]; + +pub const NKO: &'static [(char, char)] = &[ + ('߀', 'ߺ'), +]; + +pub const NUSHU: &'static [(char, char)] = &[ + ('𖿡', '𖿡'), ('𛅰', '𛋻'), +]; + +pub const OGHAM: &'static [(char, char)] = &[ + ('\u{1680}', '᚜'), +]; + +pub const OL_CHIKI: &'static [(char, char)] = &[ + ('᱐', '᱿'), +]; + +pub const OLD_HUNGARIAN: &'static [(char, char)] = &[ + ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𐳺', '𐳿'), +]; + +pub const OLD_ITALIC: &'static [(char, char)] = &[ + ('𐌀', '𐌣'), ('𐌭', '𐌯'), +]; + +pub const OLD_NORTH_ARABIAN: &'static [(char, char)] = &[ + ('𐪀', '𐪟'), +]; + +pub const OLD_PERMIC: &'static [(char, char)] = &[ + ('҃', '҃'), ('𐍐', '𐍺'), +]; + +pub const OLD_PERSIAN: &'static [(char, char)] = &[ + ('𐎠', '𐏃'), ('𐏈', '𐏕'), +]; + +pub const OLD_SOUTH_ARABIAN: &'static [(char, char)] = &[ + ('𐩠', '𐩿'), +]; + +pub const OLD_TURKIC: &'static [(char, char)] = &[ + ('𐰀', '𐱈'), +]; + +pub const ORIYA: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), + ('ଏ', 'ଐ'), ('ଓ', 'ନ'), ('ପ', 'ର'), ('ଲ', 'ଳ'), + ('ଵ', 'ହ'), ('଼', 'ୄ'), ('େ', 'ୈ'), ('ୋ', '୍'), + ('ୖ', 'ୗ'), ('ଡ଼', 'ଢ଼'), ('ୟ', 'ୣ'), ('୦', '୷'), +]; + +pub const OSAGE: &'static [(char, char)] = &[ + ('𐒰', '𐓓'), ('𐓘', '𐓻'), +]; + +pub const OSMANYA: &'static [(char, char)] = &[ + ('𐒀', '𐒝'), ('𐒠', '𐒩'), +]; + +pub const PAHAWH_HMONG: &'static [(char, char)] = &[ + ('𖬀', '𖭅'), ('𖭐', '𖭙'), ('𖭛', '𖭡'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), +]; + +pub const PALMYRENE: &'static [(char, char)] = &[ + ('𐡠', '𐡿'), +]; + +pub const PAU_CIN_HAU: &'static [(char, char)] = &[ + ('𑫀', '𑫸'), +]; + +pub const PHAGS_PA: &'static [(char, char)] = &[ + ('᠂', '᠃'), ('᠅', '᠅'), ('ꡀ', '꡷'), +]; + +pub const PHOENICIAN: &'static [(char, char)] = &[ + ('𐤀', '𐤛'), ('𐤟', '𐤟'), +]; + +pub const PSALTER_PAHLAVI: &'static [(char, char)] = &[ + ('ـ', 'ـ'), ('𐮀', '𐮑'), ('𐮙', '𐮜'), ('𐮩', '𐮯'), +]; + +pub const REJANG: &'static [(char, char)] = &[ + ('ꤰ', '꥓'), ('꥟', '꥟'), +]; + +pub const RUNIC: &'static [(char, char)] = &[ + ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), +]; + +pub const SAMARITAN: &'static [(char, char)] = &[ + ('ࠀ', '࠭'), ('࠰', '࠾'), +]; + +pub const SAURASHTRA: &'static [(char, char)] = &[ + ('ꢀ', 'ꣅ'), ('꣎', '꣙'), +]; + +pub const SHARADA: &'static [(char, char)] = &[ + ('॑', '॑'), ('᳗', '᳗'), ('᳙', '᳙'), ('᳜', '᳝'), + ('᳠', '᳠'), ('𑆀', '𑇍'), ('𑇐', '𑇟'), +]; + +pub const SHAVIAN: &'static [(char, char)] = &[ + ('𐑐', '𐑿'), +]; + +pub const SIDDHAM: &'static [(char, char)] = &[ + ('𑖀', '𑖵'), ('𑖸', '𑗝'), +]; + +pub const SIGNWRITING: &'static [(char, char)] = &[ + ('𝠀', '𝪋'), ('𝪛', '𝪟'), ('𝪡', '𝪯'), +]; + +pub const SINHALA: &'static [(char, char)] = &[ + ('।', '॥'), ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), + ('ඳ', 'ර'), ('ල', 'ල'), ('ව', 'ෆ'), ('්', '්'), + ('ා', 'ු'), ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('෦', '෯'), + ('ෲ', '෴'), ('𑇡', '𑇴'), +]; + +pub const SORA_SOMPENG: &'static [(char, char)] = &[ + ('𑃐', '𑃨'), ('𑃰', '𑃹'), +]; + +pub const SOYOMBO: &'static [(char, char)] = &[ + ('𑩐', '𑪃'), ('𑪆', '𑪜'), ('𑪞', '𑪢'), +]; + +pub const SUNDANESE: &'static [(char, char)] = &[ + ('ᮀ', 'ᮿ'), ('᳀', '᳇'), +]; + +pub const SYLOTI_NAGRI: &'static [(char, char)] = &[ + ('।', '॥'), ('০', '৯'), ('ꠀ', '꠫'), +]; + +pub const SYRIAC: &'static [(char, char)] = &[ + ('،', '،'), ('؛', '\u{61c}'), ('؟', '؟'), ('ـ', 'ـ'), ('ً', 'ٕ'), + ('ٰ', 'ٰ'), ('܀', '܍'), ('\u{70f}', '݊'), ('ݍ', 'ݏ'), ('ࡠ', 'ࡪ'), +]; + +pub const TAGALOG: &'static [(char, char)] = &[ + ('ᜀ', 'ᜌ'), ('ᜎ', '᜔'), ('᜵', '᜶'), +]; + +pub const TAGBANWA: &'static [(char, char)] = &[ + ('᜵', '᜶'), ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), ('ᝲ', 'ᝳ'), +]; + +pub const TAI_LE: &'static [(char, char)] = &[ + ('၀', '၉'), ('ᥐ', 'ᥭ'), ('ᥰ', 'ᥴ'), +]; + +pub const TAI_THAM: &'static [(char, char)] = &[ + ('ᨠ', 'ᩞ'), ('᩠', '᩼'), ('᩿', '᪉'), ('᪐', '᪙'), + ('᪠', '᪭'), +]; + +pub const TAI_VIET: &'static [(char, char)] = &[ + ('ꪀ', 'ꫂ'), ('ꫛ', '꫟'), +]; + +pub const TAKRI: &'static [(char, char)] = &[ + ('।', '॥'), ('꠰', '꠹'), ('𑚀', '𑚷'), ('𑛀', '𑛉'), +]; + +pub const TAMIL: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ஂ', 'ஃ'), ('அ', 'ஊ'), + ('எ', 'ஐ'), ('ஒ', 'க'), ('ங', 'ச'), ('ஜ', 'ஜ'), + ('ஞ', 'ட'), ('ண', 'த'), ('ந', 'ப'), ('ம', 'ஹ'), + ('ா', 'ூ'), ('ெ', 'ை'), ('ொ', '்'), ('ௐ', 'ௐ'), + ('ௗ', 'ௗ'), ('௦', '௺'), ('᳚', '᳚'), ('ꣳ', 'ꣳ'), + ('𑌁', '𑌁'), ('𑌃', '𑌃'), ('𑌼', '𑌼'), +]; + +pub const TANGUT: &'static [(char, char)] = &[ + ('𖿠', '𖿠'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), +]; + +pub const TELUGU: &'static [(char, char)] = &[ + ('॑', '॒'), ('।', '॥'), ('ఀ', 'ః'), ('అ', 'ఌ'), + ('ఎ', 'ఐ'), ('ఒ', 'న'), ('ప', 'హ'), ('ఽ', 'ౄ'), + ('ె', 'ై'), ('ొ', '్'), ('ౕ', 'ౖ'), ('ౘ', 'ౚ'), + ('ౠ', 'ౣ'), ('౦', '౯'), ('౸', '౿'), ('᳚', '᳚'), +]; + +pub const THAANA: &'static [(char, char)] = &[ + ('،', '،'), ('؛', '\u{61c}'), ('؟', '؟'), ('٠', '٩'), ('ހ', 'ޱ'), + ('ﷲ', 'ﷲ'), ('﷽', '﷽'), +]; + +pub const THAI: &'static [(char, char)] = &[ + ('ก', 'ฺ'), ('เ', '๛'), +]; + +pub const TIBETAN: &'static [(char, char)] = &[ + ('ༀ', 'ཇ'), ('ཉ', 'ཬ'), ('ཱ', 'ྗ'), ('ྙ', 'ྼ'), + ('྾', '࿌'), ('࿎', '࿔'), ('࿙', '࿚'), +]; + +pub const TIFINAGH: &'static [(char, char)] = &[ + ('ⴰ', 'ⵧ'), ('ⵯ', '⵰'), ('⵿', '⵿'), +]; + +pub const TIRHUTA: &'static [(char, char)] = &[ + ('।', '॥'), ('꠰', '꠹'), ('𑒀', '𑓇'), ('𑓐', '𑓙'), +]; + +pub const UGARITIC: &'static [(char, char)] = &[ + ('𐎀', '𐎝'), ('𐎟', '𐎟'), +]; + +pub const VAI: &'static [(char, char)] = &[ + ('ꔀ', 'ꘫ'), +]; + +pub const WARANG_CITI: &'static [(char, char)] = &[ + ('𑢠', '𑣲'), ('𑣿', '𑣿'), +]; + +pub const YI: &'static [(char, char)] = &[ + ('、', '。'), ('〈', '】'), ('〔', '〛'), ('・', '・'), + ('ꀀ', 'ꒌ'), ('꒐', '꓆'), ('。', '・'), +]; + +pub const ZANABAZAR_SQUARE: &'static [(char, char)] = &[ + ('𑨀', '𑩇'), +]; diff -Nru cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/script.rs cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/script.rs --- cargo-0.25.0/vendor/regex-syntax-0.5.3/src/unicode_tables/script.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/regex-syntax-0.5.3/src/unicode_tables/script.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,765 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate script tmp/ucd-10.0.0/ --chars +// +// ucd-generate is available on crates.io. + +pub const BY_NAME: &'static [(&'static str, &'static [(char, char)])] = &[ + ("Adlam", ADLAM), ("Ahom", AHOM), + ("Anatolian_Hieroglyphs", ANATOLIAN_HIEROGLYPHS), ("Arabic", ARABIC), + ("Armenian", ARMENIAN), ("Avestan", AVESTAN), ("Balinese", BALINESE), + ("Bamum", BAMUM), ("Bassa_Vah", BASSA_VAH), ("Batak", BATAK), + ("Bengali", BENGALI), ("Bhaiksuki", BHAIKSUKI), ("Bopomofo", BOPOMOFO), + ("Brahmi", BRAHMI), ("Braille", BRAILLE), ("Buginese", BUGINESE), + ("Buhid", BUHID), ("Canadian_Aboriginal", CANADIAN_ABORIGINAL), + ("Carian", CARIAN), ("Caucasian_Albanian", CAUCASIAN_ALBANIAN), + ("Chakma", CHAKMA), ("Cham", CHAM), ("Cherokee", CHEROKEE), + ("Common", COMMON), ("Coptic", COPTIC), ("Cuneiform", CUNEIFORM), + ("Cypriot", CYPRIOT), ("Cyrillic", CYRILLIC), ("Deseret", DESERET), + ("Devanagari", DEVANAGARI), ("Duployan", DUPLOYAN), + ("Egyptian_Hieroglyphs", EGYPTIAN_HIEROGLYPHS), ("Elbasan", ELBASAN), + ("Ethiopic", ETHIOPIC), ("Georgian", GEORGIAN), ("Glagolitic", GLAGOLITIC), + ("Gothic", GOTHIC), ("Grantha", GRANTHA), ("Greek", GREEK), + ("Gujarati", GUJARATI), ("Gurmukhi", GURMUKHI), ("Han", HAN), + ("Hangul", HANGUL), ("Hanunoo", HANUNOO), ("Hatran", HATRAN), + ("Hebrew", HEBREW), ("Hiragana", HIRAGANA), + ("Imperial_Aramaic", IMPERIAL_ARAMAIC), ("Inherited", INHERITED), + ("Inscriptional_Pahlavi", INSCRIPTIONAL_PAHLAVI), + ("Inscriptional_Parthian", INSCRIPTIONAL_PARTHIAN), ("Javanese", JAVANESE), + ("Kaithi", KAITHI), ("Kannada", KANNADA), ("Katakana", KATAKANA), + ("Kayah_Li", KAYAH_LI), ("Kharoshthi", KHAROSHTHI), ("Khmer", KHMER), + ("Khojki", KHOJKI), ("Khudawadi", KHUDAWADI), ("Lao", LAO), + ("Latin", LATIN), ("Lepcha", LEPCHA), ("Limbu", LIMBU), + ("Linear_A", LINEAR_A), ("Linear_B", LINEAR_B), ("Lisu", LISU), + ("Lycian", LYCIAN), ("Lydian", LYDIAN), ("Mahajani", MAHAJANI), + ("Malayalam", MALAYALAM), ("Mandaic", MANDAIC), ("Manichaean", MANICHAEAN), + ("Marchen", MARCHEN), ("Masaram_Gondi", MASARAM_GONDI), + ("Meetei_Mayek", MEETEI_MAYEK), ("Mende_Kikakui", MENDE_KIKAKUI), + ("Meroitic_Cursive", MEROITIC_CURSIVE), + ("Meroitic_Hieroglyphs", MEROITIC_HIEROGLYPHS), ("Miao", MIAO), + ("Modi", MODI), ("Mongolian", MONGOLIAN), ("Mro", MRO), + ("Multani", MULTANI), ("Myanmar", MYANMAR), ("Nabataean", NABATAEAN), + ("New_Tai_Lue", NEW_TAI_LUE), ("Newa", NEWA), ("Nko", NKO), + ("Nushu", NUSHU), ("Ogham", OGHAM), ("Ol_Chiki", OL_CHIKI), + ("Old_Hungarian", OLD_HUNGARIAN), ("Old_Italic", OLD_ITALIC), + ("Old_North_Arabian", OLD_NORTH_ARABIAN), ("Old_Permic", OLD_PERMIC), + ("Old_Persian", OLD_PERSIAN), ("Old_South_Arabian", OLD_SOUTH_ARABIAN), + ("Old_Turkic", OLD_TURKIC), ("Oriya", ORIYA), ("Osage", OSAGE), + ("Osmanya", OSMANYA), ("Pahawh_Hmong", PAHAWH_HMONG), + ("Palmyrene", PALMYRENE), ("Pau_Cin_Hau", PAU_CIN_HAU), + ("Phags_Pa", PHAGS_PA), ("Phoenician", PHOENICIAN), + ("Psalter_Pahlavi", PSALTER_PAHLAVI), ("Rejang", REJANG), ("Runic", RUNIC), + ("Samaritan", SAMARITAN), ("Saurashtra", SAURASHTRA), ("Sharada", SHARADA), + ("Shavian", SHAVIAN), ("Siddham", SIDDHAM), ("SignWriting", SIGNWRITING), + ("Sinhala", SINHALA), ("Sora_Sompeng", SORA_SOMPENG), ("Soyombo", SOYOMBO), + ("Sundanese", SUNDANESE), ("Syloti_Nagri", SYLOTI_NAGRI), + ("Syriac", SYRIAC), ("Tagalog", TAGALOG), ("Tagbanwa", TAGBANWA), + ("Tai_Le", TAI_LE), ("Tai_Tham", TAI_THAM), ("Tai_Viet", TAI_VIET), + ("Takri", TAKRI), ("Tamil", TAMIL), ("Tangut", TANGUT), ("Telugu", TELUGU), + ("Thaana", THAANA), ("Thai", THAI), ("Tibetan", TIBETAN), + ("Tifinagh", TIFINAGH), ("Tirhuta", TIRHUTA), ("Ugaritic", UGARITIC), + ("Vai", VAI), ("Warang_Citi", WARANG_CITI), ("Yi", YI), + ("Zanabazar_Square", ZANABAZAR_SQUARE), +]; + +pub const ADLAM: &'static [(char, char)] = &[ + ('𞤀', '𞥊'), ('𞥐', '𞥙'), ('𞥞', '𞥟'), +]; + +pub const AHOM: &'static [(char, char)] = &[ + ('𑜀', '𑜙'), ('𑜝', '𑜫'), ('𑜰', '𑜿'), +]; + +pub const ANATOLIAN_HIEROGLYPHS: &'static [(char, char)] = &[ + ('𔐀', '𔙆'), +]; + +pub const ARABIC: &'static [(char, char)] = &[ + ('\u{600}', '\u{604}'), ('؆', '؋'), ('؍', 'ؚ'), ('\u{61c}', '\u{61c}'), + ('؞', '؞'), ('ؠ', 'ؿ'), ('ف', 'ي'), ('ٖ', 'ٯ'), ('ٱ', 'ۜ'), + ('۞', 'ۿ'), ('ݐ', 'ݿ'), ('ࢠ', 'ࢴ'), ('ࢶ', 'ࢽ'), ('ࣔ', '࣡'), + ('ࣣ', 'ࣿ'), ('ﭐ', '﯁'), ('ﯓ', 'ﴽ'), ('ﵐ', 'ﶏ'), + ('ﶒ', 'ﷇ'), ('ﷰ', '﷽'), ('ﹰ', 'ﹴ'), ('ﹶ', 'ﻼ'), + ('𐹠', '𐹾'), ('𞸀', '𞸃'), ('𞸅', '𞸟'), ('𞸡', '𞸢'), + ('𞸤', '𞸤'), ('𞸧', '𞸧'), ('𞸩', '𞸲'), ('𞸴', '𞸷'), + ('𞸹', '𞸹'), ('𞸻', '𞸻'), ('𞹂', '𞹂'), ('𞹇', '𞹇'), + ('𞹉', '𞹉'), ('𞹋', '𞹋'), ('𞹍', '𞹏'), ('𞹑', '𞹒'), + ('𞹔', '𞹔'), ('𞹗', '𞹗'), ('𞹙', '𞹙'), ('𞹛', '𞹛'), + ('𞹝', '𞹝'), ('𞹟', '𞹟'), ('𞹡', '𞹢'), ('𞹤', '𞹤'), + ('𞹧', '𞹪'), ('𞹬', '𞹲'), ('𞹴', '𞹷'), ('𞹹', '𞹼'), + ('𞹾', '𞹾'), ('𞺀', '𞺉'), ('𞺋', '𞺛'), ('𞺡', '𞺣'), + ('𞺥', '𞺩'), ('𞺫', '𞺻'), ('𞻰', '𞻱'), +]; + +pub const ARMENIAN: &'static [(char, char)] = &[ + ('Ա', 'Ֆ'), ('ՙ', '՟'), ('ա', 'և'), ('֊', '֊'), ('֍', '֏'), + ('ﬓ', 'ﬗ'), +]; + +pub const AVESTAN: &'static [(char, char)] = &[ + ('𐬀', '𐬵'), ('𐬹', '𐬿'), +]; + +pub const BALINESE: &'static [(char, char)] = &[ + ('ᬀ', 'ᭋ'), ('᭐', '᭼'), +]; + +pub const BAMUM: &'static [(char, char)] = &[ + ('ꚠ', '꛷'), ('𖠀', '𖨸'), +]; + +pub const BASSA_VAH: &'static [(char, char)] = &[ + ('𖫐', '𖫭'), ('𖫰', '𖫵'), +]; + +pub const BATAK: &'static [(char, char)] = &[ + ('ᯀ', '᯳'), ('᯼', '᯿'), +]; + +pub const BENGALI: &'static [(char, char)] = &[ + ('ঀ', 'ঃ'), ('অ', 'ঌ'), ('এ', 'ঐ'), ('ও', 'ন'), + ('প', 'র'), ('ল', 'ল'), ('শ', 'হ'), ('়', 'ৄ'), + ('ে', 'ৈ'), ('ো', 'ৎ'), ('ৗ', 'ৗ'), ('ড়', 'ঢ়'), + ('য়', 'ৣ'), ('০', '৽'), +]; + +pub const BHAIKSUKI: &'static [(char, char)] = &[ + ('𑰀', '𑰈'), ('𑰊', '𑰶'), ('𑰸', '𑱅'), ('𑱐', '𑱬'), +]; + +pub const BOPOMOFO: &'static [(char, char)] = &[ + ('˪', '˫'), ('ㄅ', 'ㄮ'), ('ㆠ', 'ㆺ'), +]; + +pub const BRAHMI: &'static [(char, char)] = &[ + ('𑀀', '𑁍'), ('𑁒', '𑁯'), ('𑁿', '𑁿'), +]; + +pub const BRAILLE: &'static [(char, char)] = &[ + ('⠀', '⣿'), +]; + +pub const BUGINESE: &'static [(char, char)] = &[ + ('ᨀ', 'ᨛ'), ('᨞', '᨟'), +]; + +pub const BUHID: &'static [(char, char)] = &[ + ('ᝀ', 'ᝓ'), +]; + +pub const CANADIAN_ABORIGINAL: &'static [(char, char)] = &[ + ('᐀', 'ᙿ'), ('ᢰ', 'ᣵ'), +]; + +pub const CARIAN: &'static [(char, char)] = &[ + ('𐊠', '𐋐'), +]; + +pub const CAUCASIAN_ALBANIAN: &'static [(char, char)] = &[ + ('𐔰', '𐕣'), ('𐕯', '𐕯'), +]; + +pub const CHAKMA: &'static [(char, char)] = &[ + ('𑄀', '𑄴'), ('𑄶', '𑅃'), +]; + +pub const CHAM: &'static [(char, char)] = &[ + ('ꨀ', 'ꨶ'), ('ꩀ', 'ꩍ'), ('꩐', '꩙'), ('꩜', '꩟'), +]; + +pub const CHEROKEE: &'static [(char, char)] = &[ + ('Ꭰ', 'Ᏽ'), ('ᏸ', 'ᏽ'), ('ꭰ', 'ꮿ'), +]; + +pub const COMMON: &'static [(char, char)] = &[ + ('\u{0}', '@'), ('[', '`'), ('{', '©'), ('«', '¹'), ('»', '¿'), + ('×', '×'), ('÷', '÷'), ('ʹ', '˟'), ('˥', '˩'), ('ˬ', '˿'), + ('ʹ', 'ʹ'), (';', ';'), ('΅', '΅'), ('·', '·'), ('։', '։'), + ('\u{605}', '\u{605}'), ('،', '،'), ('؛', '؛'), ('؟', '؟'), + ('ـ', 'ـ'), ('\u{6dd}', '\u{6dd}'), ('\u{8e2}', '\u{8e2}'), + ('।', '॥'), ('฿', '฿'), ('࿕', '࿘'), ('჻', '჻'), + ('᛫', '᛭'), ('᜵', '᜶'), ('᠂', '᠃'), ('᠅', '᠅'), + ('᳓', '᳓'), ('᳡', '᳡'), ('ᳩ', 'ᳬ'), ('ᳮ', 'ᳳ'), + ('ᳵ', '᳷'), ('\u{2000}', '\u{200b}'), ('\u{200e}', '\u{2064}'), + ('\u{2066}', '⁰'), ('⁴', '⁾'), ('₀', '₎'), ('₠', '₿'), + ('℀', '℥'), ('℧', '℩'), ('ℬ', 'ℱ'), ('ℳ', '⅍'), + ('⅏', '⅟'), ('↉', '↋'), ('←', '␦'), ('⑀', '⑊'), + ('①', '⟿'), ('⤀', '⭳'), ('⭶', '⮕'), ('⮘', '⮹'), + ('⮽', '⯈'), ('⯊', '⯒'), ('⯬', '⯯'), ('⸀', '⹉'), + ('⿰', '⿻'), ('\u{3000}', '〄'), ('〆', '〆'), ('〈', '〠'), + ('〰', '〷'), ('〼', '〿'), ('゛', '゜'), ('゠', '゠'), + ('・', 'ー'), ('㆐', '㆟'), ('㇀', '㇣'), ('㈠', '㉟'), + ('㉿', '㋏'), ('㍘', '㏿'), ('䷀', '䷿'), ('꜀', '꜡'), + ('ꞈ', '꞊'), ('꠰', '꠹'), ('꤮', '꤮'), ('ꧏ', 'ꧏ'), + ('꭛', '꭛'), ('﴾', '﴿'), ('︐', '︙'), ('︰', '﹒'), + ('﹔', '﹦'), ('﹨', '﹫'), ('\u{feff}', '\u{feff}'), ('!', '@'), + ('[', '`'), ('{', '・'), ('ー', 'ー'), ('゙', '゚'), + ('¢', '₩'), ('│', '○'), ('\u{fff9}', '�'), ('𐄀', '𐄂'), + ('𐄇', '𐄳'), ('𐄷', '𐄿'), ('𐆐', '𐆛'), ('𐇐', '𐇼'), + ('𐋡', '𐋻'), ('\u{1bca0}', '\u{1bca3}'), ('𝀀', '𝃵'), + ('𝄀', '𝄦'), ('𝄩', '𝅦'), ('𝅪', '\u{1d17a}'), ('𝆃', '𝆄'), + ('𝆌', '𝆩'), ('𝆮', '𝇨'), ('𝌀', '𝍖'), ('𝍠', '𝍱'), + ('𝐀', '𝑔'), ('𝑖', '𝒜'), ('𝒞', '𝒟'), ('𝒢', '𝒢'), + ('𝒥', '𝒦'), ('𝒩', '𝒬'), ('𝒮', '𝒹'), ('𝒻', '𝒻'), + ('𝒽', '𝓃'), ('𝓅', '𝔅'), ('𝔇', '𝔊'), ('𝔍', '𝔔'), + ('𝔖', '𝔜'), ('𝔞', '𝔹'), ('𝔻', '𝔾'), ('𝕀', '𝕄'), + ('𝕆', '𝕆'), ('𝕊', '𝕐'), ('𝕒', '𝚥'), ('𝚨', '𝟋'), + ('𝟎', '𝟿'), ('🀀', '🀫'), ('🀰', '🂓'), ('🂠', '🂮'), + ('🂱', '🂿'), ('🃁', '🃏'), ('🃑', '🃵'), ('🄀', '🄌'), + ('🄐', '🄮'), ('🄰', '🅫'), ('🅰', '🆬'), ('🇦', '🇿'), + ('🈁', '🈂'), ('🈐', '🈻'), ('🉀', '🉈'), ('🉐', '🉑'), + ('🉠', '🉥'), ('🌀', '🛔'), ('🛠', '🛬'), ('🛰', '🛸'), + ('🜀', '🝳'), ('🞀', '🟔'), ('🠀', '🠋'), ('🠐', '🡇'), + ('🡐', '🡙'), ('🡠', '🢇'), ('🢐', '🢭'), ('🤀', '🤋'), + ('🤐', '🤾'), ('🥀', '🥌'), ('🥐', '🥫'), ('🦀', '🦗'), + ('🧀', '🧀'), ('🧐', '🧦'), ('\u{e0001}', '\u{e0001}'), + ('\u{e0020}', '\u{e007f}'), +]; + +pub const COPTIC: &'static [(char, char)] = &[ + ('Ϣ', 'ϯ'), ('Ⲁ', 'ⳳ'), ('⳹', '⳿'), +]; + +pub const CUNEIFORM: &'static [(char, char)] = &[ + ('𒀀', '𒎙'), ('𒐀', '𒑮'), ('𒑰', '𒑴'), ('𒒀', '𒕃'), +]; + +pub const CYPRIOT: &'static [(char, char)] = &[ + ('𐠀', '𐠅'), ('𐠈', '𐠈'), ('𐠊', '𐠵'), ('𐠷', '𐠸'), + ('𐠼', '𐠼'), ('𐠿', '𐠿'), +]; + +pub const CYRILLIC: &'static [(char, char)] = &[ + ('Ѐ', '҄'), ('҇', 'ԯ'), ('ᲀ', 'ᲈ'), ('ᴫ', 'ᴫ'), ('ᵸ', 'ᵸ'), + ('ⷠ', 'ⷿ'), ('Ꙁ', 'ꚟ'), ('︮', '︯'), +]; + +pub const DESERET: &'static [(char, char)] = &[ + ('𐐀', '𐑏'), +]; + +pub const DEVANAGARI: &'static [(char, char)] = &[ + ('ऀ', 'ॐ'), ('॓', 'ॣ'), ('०', 'ॿ'), ('꣠', 'ꣽ'), +]; + +pub const DUPLOYAN: &'static [(char, char)] = &[ + ('𛰀', '𛱪'), ('𛱰', '𛱼'), ('𛲀', '𛲈'), ('𛲐', '𛲙'), + ('𛲜', '𛲟'), +]; + +pub const EGYPTIAN_HIEROGLYPHS: &'static [(char, char)] = &[ + ('𓀀', '𓐮'), +]; + +pub const ELBASAN: &'static [(char, char)] = &[ + ('𐔀', '𐔧'), +]; + +pub const ETHIOPIC: &'static [(char, char)] = &[ + ('ሀ', 'ቈ'), ('ቊ', 'ቍ'), ('ቐ', 'ቖ'), ('ቘ', 'ቘ'), + ('ቚ', 'ቝ'), ('በ', 'ኈ'), ('ኊ', 'ኍ'), ('ነ', 'ኰ'), + ('ኲ', 'ኵ'), ('ኸ', 'ኾ'), ('ዀ', 'ዀ'), ('ዂ', 'ዅ'), + ('ወ', 'ዖ'), ('ዘ', 'ጐ'), ('ጒ', 'ጕ'), ('ጘ', 'ፚ'), + ('፝', '፼'), ('ᎀ', '᎙'), ('ⶀ', 'ⶖ'), ('ⶠ', 'ⶦ'), + ('ⶨ', 'ⶮ'), ('ⶰ', 'ⶶ'), ('ⶸ', 'ⶾ'), ('ⷀ', 'ⷆ'), + ('ⷈ', 'ⷎ'), ('ⷐ', 'ⷖ'), ('ⷘ', 'ⷞ'), ('ꬁ', 'ꬆ'), + ('ꬉ', 'ꬎ'), ('ꬑ', 'ꬖ'), ('ꬠ', 'ꬦ'), ('ꬨ', 'ꬮ'), +]; + +pub const GEORGIAN: &'static [(char, char)] = &[ + ('Ⴀ', 'Ⴥ'), ('Ⴧ', 'Ⴧ'), ('Ⴭ', 'Ⴭ'), ('ა', 'ჺ'), + ('ჼ', 'ჿ'), ('ⴀ', 'ⴥ'), ('ⴧ', 'ⴧ'), ('ⴭ', 'ⴭ'), +]; + +pub const GLAGOLITIC: &'static [(char, char)] = &[ + ('Ⰰ', 'Ⱞ'), ('ⰰ', 'ⱞ'), ('𞀀', '𞀆'), ('𞀈', '𞀘'), + ('𞀛', '𞀡'), ('𞀣', '𞀤'), ('𞀦', '𞀪'), +]; + +pub const GOTHIC: &'static [(char, char)] = &[ + ('𐌰', '𐍊'), +]; + +pub const GRANTHA: &'static [(char, char)] = &[ + ('𑌀', '𑌃'), ('𑌅', '𑌌'), ('𑌏', '𑌐'), ('𑌓', '𑌨'), + ('𑌪', '𑌰'), ('𑌲', '𑌳'), ('𑌵', '𑌹'), ('𑌼', '𑍄'), + ('𑍇', '𑍈'), ('𑍋', '𑍍'), ('𑍐', '𑍐'), ('𑍗', '𑍗'), + ('𑍝', '𑍣'), ('𑍦', '𑍬'), ('𑍰', '𑍴'), +]; + +pub const GREEK: &'static [(char, char)] = &[ + ('Ͱ', 'ͳ'), ('͵', 'ͷ'), ('ͺ', 'ͽ'), ('Ϳ', 'Ϳ'), ('΄', '΄'), + ('Ά', 'Ά'), ('Έ', 'Ί'), ('Ό', 'Ό'), ('Ύ', 'Ρ'), ('Σ', 'ϡ'), + ('ϰ', 'Ͽ'), ('ᴦ', 'ᴪ'), ('ᵝ', 'ᵡ'), ('ᵦ', 'ᵪ'), + ('ᶿ', 'ᶿ'), ('ἀ', 'ἕ'), ('Ἐ', 'Ἕ'), ('ἠ', 'ὅ'), + ('Ὀ', 'Ὅ'), ('ὐ', 'ὗ'), ('Ὑ', 'Ὑ'), ('Ὓ', 'Ὓ'), + ('Ὕ', 'Ὕ'), ('Ὗ', 'ώ'), ('ᾀ', 'ᾴ'), ('ᾶ', 'ῄ'), + ('ῆ', 'ΐ'), ('ῖ', 'Ί'), ('῝', '`'), ('ῲ', 'ῴ'), + ('ῶ', '῾'), ('Ω', 'Ω'), ('ꭥ', 'ꭥ'), ('𐅀', '𐆎'), + ('𐆠', '𐆠'), ('𝈀', '𝉅'), +]; + +pub const GUJARATI: &'static [(char, char)] = &[ + ('ઁ', 'ઃ'), ('અ', 'ઍ'), ('એ', 'ઑ'), ('ઓ', 'ન'), + ('પ', 'ર'), ('લ', 'ળ'), ('વ', 'હ'), ('઼', 'ૅ'), + ('ે', 'ૉ'), ('ો', '્'), ('ૐ', 'ૐ'), ('ૠ', 'ૣ'), + ('૦', '૱'), ('ૹ', '૿'), +]; + +pub const GURMUKHI: &'static [(char, char)] = &[ + ('ਁ', 'ਃ'), ('ਅ', 'ਊ'), ('ਏ', 'ਐ'), ('ਓ', 'ਨ'), + ('ਪ', 'ਰ'), ('ਲ', 'ਲ਼'), ('ਵ', 'ਸ਼'), ('ਸ', 'ਹ'), + ('਼', '਼'), ('ਾ', 'ੂ'), ('ੇ', 'ੈ'), ('ੋ', '੍'), + ('ੑ', 'ੑ'), ('ਖ਼', 'ੜ'), ('ਫ਼', 'ਫ਼'), ('੦', 'ੵ'), +]; + +pub const HAN: &'static [(char, char)] = &[ + ('⺀', '⺙'), ('⺛', '⻳'), ('⼀', '⿕'), ('々', '々'), + ('〇', '〇'), ('〡', '〩'), ('〸', '〻'), ('㐀', '䶵'), + ('一', '鿪'), ('豈', '舘'), ('並', '龎'), ('𠀀', '𪛖'), + ('𪜀', '𫜴'), ('𫝀', '𫠝'), ('𫠠', '𬺡'), ('𬺰', '𮯠'), + ('丽', '𪘀'), +]; + +pub const HANGUL: &'static [(char, char)] = &[ + ('ᄀ', 'ᇿ'), ('〮', '〯'), ('ㄱ', 'ㆎ'), ('㈀', '㈞'), + ('㉠', '㉾'), ('ꥠ', 'ꥼ'), ('가', '힣'), ('ힰ', 'ퟆ'), + ('ퟋ', 'ퟻ'), ('ᅠ', 'ᄒ'), ('ᅡ', 'ᅦ'), ('ᅧ', 'ᅬ'), + ('ᅭ', 'ᅲ'), ('ᅳ', 'ᅵ'), +]; + +pub const HANUNOO: &'static [(char, char)] = &[ + ('ᜠ', '᜴'), +]; + +pub const HATRAN: &'static [(char, char)] = &[ + ('𐣠', '𐣲'), ('𐣴', '𐣵'), ('𐣻', '𐣿'), +]; + +pub const HEBREW: &'static [(char, char)] = &[ + ('֑', 'ׇ'), ('א', 'ת'), ('װ', '״'), ('יִ', 'זּ'), ('טּ', 'לּ'), + ('מּ', 'מּ'), ('נּ', 'סּ'), ('ףּ', 'פּ'), ('צּ', 'ﭏ'), +]; + +pub const HIRAGANA: &'static [(char, char)] = &[ + ('ぁ', 'ゖ'), ('ゝ', 'ゟ'), ('𛀁', '𛄞'), ('🈀', '🈀'), +]; + +pub const IMPERIAL_ARAMAIC: &'static [(char, char)] = &[ + ('𐡀', '𐡕'), ('𐡗', '𐡟'), +]; + +pub const INHERITED: &'static [(char, char)] = &[ + ('̀', 'ͯ'), ('҅', '҆'), ('ً', 'ٕ'), ('ٰ', 'ٰ'), ('॑', '॒'), + ('᪰', '᪾'), ('᳐', '᳒'), ('᳔', '᳠'), ('᳢', '᳨'), + ('᳭', '᳭'), ('᳴', '᳴'), ('᳸', '᳹'), ('᷀', '᷹'), + ('᷻', '᷿'), ('\u{200c}', '\u{200d}'), ('⃐', '⃰'), ('〪', '〭'), + ('゙', '゚'), ('︀', '️'), ('︠', '︭'), ('𐇽', '𐇽'), + ('𐋠', '𐋠'), ('𝅧', '𝅩'), ('𝅻', '𝆂'), ('𝆅', '𝆋'), + ('𝆪', '𝆭'), ('󠄀', '󠇯'), +]; + +pub const INSCRIPTIONAL_PAHLAVI: &'static [(char, char)] = &[ + ('𐭠', '𐭲'), ('𐭸', '𐭿'), +]; + +pub const INSCRIPTIONAL_PARTHIAN: &'static [(char, char)] = &[ + ('𐭀', '𐭕'), ('𐭘', '𐭟'), +]; + +pub const JAVANESE: &'static [(char, char)] = &[ + ('ꦀ', '꧍'), ('꧐', '꧙'), ('꧞', '꧟'), +]; + +pub const KAITHI: &'static [(char, char)] = &[ + ('𑂀', '𑃁'), +]; + +pub const KANNADA: &'static [(char, char)] = &[ + ('ಀ', 'ಃ'), ('ಅ', 'ಌ'), ('ಎ', 'ಐ'), ('ಒ', 'ನ'), + ('ಪ', 'ಳ'), ('ವ', 'ಹ'), ('಼', 'ೄ'), ('ೆ', 'ೈ'), + ('ೊ', '್'), ('ೕ', 'ೖ'), ('ೞ', 'ೞ'), ('ೠ', 'ೣ'), + ('೦', '೯'), ('ೱ', 'ೲ'), +]; + +pub const KATAKANA: &'static [(char, char)] = &[ + ('ァ', 'ヺ'), ('ヽ', 'ヿ'), ('ㇰ', 'ㇿ'), ('㋐', '㋾'), + ('㌀', '㍗'), ('ヲ', 'ッ'), ('ア', 'ン'), ('𛀀', '𛀀'), +]; + +pub const KAYAH_LI: &'static [(char, char)] = &[ + ('꤀', '꤭'), ('꤯', '꤯'), +]; + +pub const KHAROSHTHI: &'static [(char, char)] = &[ + ('𐨀', '𐨃'), ('𐨅', '𐨆'), ('𐨌', '𐨓'), ('𐨕', '𐨗'), + ('𐨙', '𐨳'), ('𐨸', '𐨺'), ('𐨿', '𐩇'), ('𐩐', '𐩘'), +]; + +pub const KHMER: &'static [(char, char)] = &[ + ('ក', '៝'), ('០', '៩'), ('៰', '៹'), ('᧠', '᧿'), +]; + +pub const KHOJKI: &'static [(char, char)] = &[ + ('𑈀', '𑈑'), ('𑈓', '𑈾'), +]; + +pub const KHUDAWADI: &'static [(char, char)] = &[ + ('𑊰', '𑋪'), ('𑋰', '𑋹'), +]; + +pub const LAO: &'static [(char, char)] = &[ + ('ກ', 'ຂ'), ('ຄ', 'ຄ'), ('ງ', 'ຈ'), ('ຊ', 'ຊ'), + ('ຍ', 'ຍ'), ('ດ', 'ທ'), ('ນ', 'ຟ'), ('ມ', 'ຣ'), + ('ລ', 'ລ'), ('ວ', 'ວ'), ('ສ', 'ຫ'), ('ອ', 'ູ'), + ('ົ', 'ຽ'), ('ເ', 'ໄ'), ('ໆ', 'ໆ'), ('່', 'ໍ'), + ('໐', '໙'), ('ໜ', 'ໟ'), +]; + +pub const LATIN: &'static [(char, char)] = &[ + ('A', 'Z'), ('a', 'z'), ('ª', 'ª'), ('º', 'º'), ('À', 'Ö'), + ('Ø', 'ö'), ('ø', 'ʸ'), ('ˠ', 'ˤ'), ('ᴀ', 'ᴥ'), ('ᴬ', 'ᵜ'), + ('ᵢ', 'ᵥ'), ('ᵫ', 'ᵷ'), ('ᵹ', 'ᶾ'), ('Ḁ', 'ỿ'), + ('ⁱ', 'ⁱ'), ('ⁿ', 'ⁿ'), ('ₐ', 'ₜ'), ('K', 'Å'), + ('Ⅎ', 'Ⅎ'), ('ⅎ', 'ⅎ'), ('Ⅰ', 'ↈ'), ('Ⱡ', 'Ɀ'), + ('Ꜣ', 'ꞇ'), ('Ꞌ', 'Ɪ'), ('Ʞ', 'ꞷ'), ('ꟷ', 'ꟿ'), + ('ꬰ', 'ꭚ'), ('ꭜ', 'ꭤ'), ('ff', 'st'), ('A', 'Z'), + ('a', 'z'), +]; + +pub const LEPCHA: &'static [(char, char)] = &[ + ('ᰀ', '᰷'), ('᰻', '᱉'), ('ᱍ', 'ᱏ'), +]; + +pub const LIMBU: &'static [(char, char)] = &[ + ('ᤀ', 'ᤞ'), ('ᤠ', 'ᤫ'), ('ᤰ', '᤻'), ('᥀', '᥀'), + ('᥄', '᥏'), +]; + +pub const LINEAR_A: &'static [(char, char)] = &[ + ('𐘀', '𐜶'), ('𐝀', '𐝕'), ('𐝠', '𐝧'), +]; + +pub const LINEAR_B: &'static [(char, char)] = &[ + ('𐀀', '𐀋'), ('𐀍', '𐀦'), ('𐀨', '𐀺'), ('𐀼', '𐀽'), + ('𐀿', '𐁍'), ('𐁐', '𐁝'), ('𐂀', '𐃺'), +]; + +pub const LISU: &'static [(char, char)] = &[ + ('ꓐ', '꓿'), +]; + +pub const LYCIAN: &'static [(char, char)] = &[ + ('𐊀', '𐊜'), +]; + +pub const LYDIAN: &'static [(char, char)] = &[ + ('𐤠', '𐤹'), ('𐤿', '𐤿'), +]; + +pub const MAHAJANI: &'static [(char, char)] = &[ + ('𑅐', '𑅶'), +]; + +pub const MALAYALAM: &'static [(char, char)] = &[ + ('ഀ', 'ഃ'), ('അ', 'ഌ'), ('എ', 'ഐ'), ('ഒ', 'ൄ'), + ('െ', 'ൈ'), ('ൊ', '൏'), ('ൔ', 'ൣ'), ('൦', 'ൿ'), +]; + +pub const MANDAIC: &'static [(char, char)] = &[ + ('ࡀ', '࡛'), ('࡞', '࡞'), +]; + +pub const MANICHAEAN: &'static [(char, char)] = &[ + ('𐫀', '𐫦'), ('𐫫', '𐫶'), +]; + +pub const MARCHEN: &'static [(char, char)] = &[ + ('𑱰', '𑲏'), ('𑲒', '𑲧'), ('𑲩', '𑲶'), +]; + +pub const MASARAM_GONDI: &'static [(char, char)] = &[ + ('𑴀', '𑴆'), ('𑴈', '𑴉'), ('𑴋', '𑴶'), ('𑴺', '𑴺'), + ('𑴼', '𑴽'), ('𑴿', '𑵇'), ('𑵐', '𑵙'), +]; + +pub const MEETEI_MAYEK: &'static [(char, char)] = &[ + ('ꫠ', '꫶'), ('ꯀ', '꯭'), ('꯰', '꯹'), +]; + +pub const MENDE_KIKAKUI: &'static [(char, char)] = &[ + ('𞠀', '𞣄'), ('𞣇', '𞣖'), +]; + +pub const MEROITIC_CURSIVE: &'static [(char, char)] = &[ + ('𐦠', '𐦷'), ('𐦼', '𐧏'), ('𐧒', '𐧿'), +]; + +pub const MEROITIC_HIEROGLYPHS: &'static [(char, char)] = &[ + ('𐦀', '𐦟'), +]; + +pub const MIAO: &'static [(char, char)] = &[ + ('𖼀', '𖽄'), ('𖽐', '𖽾'), ('𖾏', '𖾟'), +]; + +pub const MODI: &'static [(char, char)] = &[ + ('𑘀', '𑙄'), ('𑙐', '𑙙'), +]; + +pub const MONGOLIAN: &'static [(char, char)] = &[ + ('᠀', '᠁'), ('᠄', '᠄'), ('᠆', '\u{180e}'), ('᠐', '᠙'), + ('ᠠ', 'ᡷ'), ('ᢀ', 'ᢪ'), ('𑙠', '𑙬'), +]; + +pub const MRO: &'static [(char, char)] = &[ + ('𖩀', '𖩞'), ('𖩠', '𖩩'), ('𖩮', '𖩯'), +]; + +pub const MULTANI: &'static [(char, char)] = &[ + ('𑊀', '𑊆'), ('𑊈', '𑊈'), ('𑊊', '𑊍'), ('𑊏', '𑊝'), + ('𑊟', '𑊩'), +]; + +pub const MYANMAR: &'static [(char, char)] = &[ + ('က', '႟'), ('ꧠ', 'ꧾ'), ('ꩠ', 'ꩿ'), +]; + +pub const NABATAEAN: &'static [(char, char)] = &[ + ('𐢀', '𐢞'), ('𐢧', '𐢯'), +]; + +pub const NEW_TAI_LUE: &'static [(char, char)] = &[ + ('ᦀ', 'ᦫ'), ('ᦰ', 'ᧉ'), ('᧐', '᧚'), ('᧞', '᧟'), +]; + +pub const NEWA: &'static [(char, char)] = &[ + ('𑐀', '𑑙'), ('𑑛', '𑑛'), ('𑑝', '𑑝'), +]; + +pub const NKO: &'static [(char, char)] = &[ + ('߀', 'ߺ'), +]; + +pub const NUSHU: &'static [(char, char)] = &[ + ('𖿡', '𖿡'), ('𛅰', '𛋻'), +]; + +pub const OGHAM: &'static [(char, char)] = &[ + ('\u{1680}', '᚜'), +]; + +pub const OL_CHIKI: &'static [(char, char)] = &[ + ('᱐', '᱿'), +]; + +pub const OLD_HUNGARIAN: &'static [(char, char)] = &[ + ('𐲀', '𐲲'), ('𐳀', '𐳲'), ('𐳺', '𐳿'), +]; + +pub const OLD_ITALIC: &'static [(char, char)] = &[ + ('𐌀', '𐌣'), ('𐌭', '𐌯'), +]; + +pub const OLD_NORTH_ARABIAN: &'static [(char, char)] = &[ + ('𐪀', '𐪟'), +]; + +pub const OLD_PERMIC: &'static [(char, char)] = &[ + ('𐍐', '𐍺'), +]; + +pub const OLD_PERSIAN: &'static [(char, char)] = &[ + ('𐎠', '𐏃'), ('𐏈', '𐏕'), +]; + +pub const OLD_SOUTH_ARABIAN: &'static [(char, char)] = &[ + ('𐩠', '𐩿'), +]; + +pub const OLD_TURKIC: &'static [(char, char)] = &[ + ('𐰀', '𐱈'), +]; + +pub const ORIYA: &'static [(char, char)] = &[ + ('ଁ', 'ଃ'), ('ଅ', 'ଌ'), ('ଏ', 'ଐ'), ('ଓ', 'ନ'), + ('ପ', 'ର'), ('ଲ', 'ଳ'), ('ଵ', 'ହ'), ('଼', 'ୄ'), + ('େ', 'ୈ'), ('ୋ', '୍'), ('ୖ', 'ୗ'), ('ଡ଼', 'ଢ଼'), + ('ୟ', 'ୣ'), ('୦', '୷'), +]; + +pub const OSAGE: &'static [(char, char)] = &[ + ('𐒰', '𐓓'), ('𐓘', '𐓻'), +]; + +pub const OSMANYA: &'static [(char, char)] = &[ + ('𐒀', '𐒝'), ('𐒠', '𐒩'), +]; + +pub const PAHAWH_HMONG: &'static [(char, char)] = &[ + ('𖬀', '𖭅'), ('𖭐', '𖭙'), ('𖭛', '𖭡'), ('𖭣', '𖭷'), + ('𖭽', '𖮏'), +]; + +pub const PALMYRENE: &'static [(char, char)] = &[ + ('𐡠', '𐡿'), +]; + +pub const PAU_CIN_HAU: &'static [(char, char)] = &[ + ('𑫀', '𑫸'), +]; + +pub const PHAGS_PA: &'static [(char, char)] = &[ + ('ꡀ', '꡷'), +]; + +pub const PHOENICIAN: &'static [(char, char)] = &[ + ('𐤀', '𐤛'), ('𐤟', '𐤟'), +]; + +pub const PSALTER_PAHLAVI: &'static [(char, char)] = &[ + ('𐮀', '𐮑'), ('𐮙', '𐮜'), ('𐮩', '𐮯'), +]; + +pub const REJANG: &'static [(char, char)] = &[ + ('ꤰ', '꥓'), ('꥟', '꥟'), +]; + +pub const RUNIC: &'static [(char, char)] = &[ + ('ᚠ', 'ᛪ'), ('ᛮ', 'ᛸ'), +]; + +pub const SAMARITAN: &'static [(char, char)] = &[ + ('ࠀ', '࠭'), ('࠰', '࠾'), +]; + +pub const SAURASHTRA: &'static [(char, char)] = &[ + ('ꢀ', 'ꣅ'), ('꣎', '꣙'), +]; + +pub const SHARADA: &'static [(char, char)] = &[ + ('𑆀', '𑇍'), ('𑇐', '𑇟'), +]; + +pub const SHAVIAN: &'static [(char, char)] = &[ + ('𐑐', '𐑿'), +]; + +pub const SIDDHAM: &'static [(char, char)] = &[ + ('𑖀', '𑖵'), ('𑖸', '𑗝'), +]; + +pub const SIGNWRITING: &'static [(char, char)] = &[ + ('𝠀', '𝪋'), ('𝪛', '𝪟'), ('𝪡', '𝪯'), +]; + +pub const SINHALA: &'static [(char, char)] = &[ + ('ං', 'ඃ'), ('අ', 'ඖ'), ('ක', 'න'), ('ඳ', 'ර'), + ('ල', 'ල'), ('ව', 'ෆ'), ('්', '්'), ('ා', 'ු'), + ('ූ', 'ූ'), ('ෘ', 'ෟ'), ('෦', '෯'), ('ෲ', '෴'), + ('𑇡', '𑇴'), +]; + +pub const SORA_SOMPENG: &'static [(char, char)] = &[ + ('𑃐', '𑃨'), ('𑃰', '𑃹'), +]; + +pub const SOYOMBO: &'static [(char, char)] = &[ + ('𑩐', '𑪃'), ('𑪆', '𑪜'), ('𑪞', '𑪢'), +]; + +pub const SUNDANESE: &'static [(char, char)] = &[ + ('ᮀ', 'ᮿ'), ('᳀', '᳇'), +]; + +pub const SYLOTI_NAGRI: &'static [(char, char)] = &[ + ('ꠀ', '꠫'), +]; + +pub const SYRIAC: &'static [(char, char)] = &[ + ('܀', '܍'), ('\u{70f}', '݊'), ('ݍ', 'ݏ'), ('ࡠ', 'ࡪ'), +]; + +pub const TAGALOG: &'static [(char, char)] = &[ + ('ᜀ', 'ᜌ'), ('ᜎ', '᜔'), +]; + +pub const TAGBANWA: &'static [(char, char)] = &[ + ('ᝠ', 'ᝬ'), ('ᝮ', 'ᝰ'), ('ᝲ', 'ᝳ'), +]; + +pub const TAI_LE: &'static [(char, char)] = &[ + ('ᥐ', 'ᥭ'), ('ᥰ', 'ᥴ'), +]; + +pub const TAI_THAM: &'static [(char, char)] = &[ + ('ᨠ', 'ᩞ'), ('᩠', '᩼'), ('᩿', '᪉'), ('᪐', '᪙'), + ('᪠', '᪭'), +]; + +pub const TAI_VIET: &'static [(char, char)] = &[ + ('ꪀ', 'ꫂ'), ('ꫛ', '꫟'), +]; + +pub const TAKRI: &'static [(char, char)] = &[ + ('𑚀', '𑚷'), ('𑛀', '𑛉'), +]; + +pub const TAMIL: &'static [(char, char)] = &[ + ('ஂ', 'ஃ'), ('அ', 'ஊ'), ('எ', 'ஐ'), ('ஒ', 'க'), + ('ங', 'ச'), ('ஜ', 'ஜ'), ('ஞ', 'ட'), ('ண', 'த'), + ('ந', 'ப'), ('ம', 'ஹ'), ('ா', 'ூ'), ('ெ', 'ை'), + ('ொ', '்'), ('ௐ', 'ௐ'), ('ௗ', 'ௗ'), ('௦', '௺'), +]; + +pub const TANGUT: &'static [(char, char)] = &[ + ('𖿠', '𖿠'), ('𗀀', '𘟬'), ('𘠀', '𘫲'), +]; + +pub const TELUGU: &'static [(char, char)] = &[ + ('ఀ', 'ః'), ('అ', 'ఌ'), ('ఎ', 'ఐ'), ('ఒ', 'న'), + ('ప', 'హ'), ('ఽ', 'ౄ'), ('ె', 'ై'), ('ొ', '్'), + ('ౕ', 'ౖ'), ('ౘ', 'ౚ'), ('ౠ', 'ౣ'), ('౦', '౯'), + ('౸', '౿'), +]; + +pub const THAANA: &'static [(char, char)] = &[ + ('ހ', 'ޱ'), +]; + +pub const THAI: &'static [(char, char)] = &[ + ('ก', 'ฺ'), ('เ', '๛'), +]; + +pub const TIBETAN: &'static [(char, char)] = &[ + ('ༀ', 'ཇ'), ('ཉ', 'ཬ'), ('ཱ', 'ྗ'), ('ྙ', 'ྼ'), + ('྾', '࿌'), ('࿎', '࿔'), ('࿙', '࿚'), +]; + +pub const TIFINAGH: &'static [(char, char)] = &[ + ('ⴰ', 'ⵧ'), ('ⵯ', '⵰'), ('⵿', '⵿'), +]; + +pub const TIRHUTA: &'static [(char, char)] = &[ + ('𑒀', '𑓇'), ('𑓐', '𑓙'), +]; + +pub const UGARITIC: &'static [(char, char)] = &[ + ('𐎀', '𐎝'), ('𐎟', '𐎟'), +]; + +pub const VAI: &'static [(char, char)] = &[ + ('ꔀ', 'ꘫ'), +]; + +pub const WARANG_CITI: &'static [(char, char)] = &[ + ('𑢠', '𑣲'), ('𑣿', '𑣿'), +]; + +pub const YI: &'static [(char, char)] = &[ + ('ꀀ', 'ꒌ'), ('꒐', '꓆'), +]; + +pub const ZANABAZAR_SQUARE: &'static [(char, char)] = &[ + ('𑨀', '𑩇'), +]; diff -Nru cargo-0.25.0/vendor/remove_dir_all-0.3.0/.cargo-checksum.json cargo-0.26.0/vendor/remove_dir_all-0.3.0/.cargo-checksum.json --- cargo-0.25.0/vendor/remove_dir_all-0.3.0/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/remove_dir_all-0.3.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"b5d2f806b0fcdabd98acd380dc8daef485e22bcb7cddc811d1337967f2528cf5"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/remove_dir_all-0.3.0/Cargo.toml cargo-0.26.0/vendor/remove_dir_all-0.3.0/Cargo.toml --- cargo-0.25.0/vendor/remove_dir_all-0.3.0/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/remove_dir_all-0.3.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "remove_dir_all" -version = "0.3.0" -authors = ["Aaronepower <theaaronepower@gmail.com>"] -include = ["Cargo.toml", "LICENCE-APACHE", "LICENCE-MIT", "src/**/*"] -description = "A safe, reliable implementation of remove_dir_all for Windows" -readme = "README.md" -keywords = ["utility", "filesystem", "remove_dir", "windows"] -categories = ["filesystem"] -license = "MIT/Apache-2.0" -repository = "https://github.com/Aaronepower/remove_dir_all.git" -[dependencies.winapi] -version = "0.2" - -[dependencies.kernel32-sys] -version = "0.2" diff -Nru cargo-0.25.0/vendor/remove_dir_all-0.3.0/LICENCE-APACHE cargo-0.26.0/vendor/remove_dir_all-0.3.0/LICENCE-APACHE --- cargo-0.25.0/vendor/remove_dir_all-0.3.0/LICENCE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/remove_dir_all-0.3.0/LICENCE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,191 +0,0 @@ - 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 - -Copyright 2017 Aaron Power - -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. - diff -Nru cargo-0.25.0/vendor/remove_dir_all-0.3.0/LICENCE-MIT cargo-0.26.0/vendor/remove_dir_all-0.3.0/LICENCE-MIT --- cargo-0.25.0/vendor/remove_dir_all-0.3.0/LICENCE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/remove_dir_all-0.3.0/LICENCE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -Copyright (c) 2017 Aaron Power - -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. - diff -Nru cargo-0.25.0/vendor/remove_dir_all-0.3.0/src/fs.rs cargo-0.26.0/vendor/remove_dir_all-0.3.0/src/fs.rs --- cargo-0.25.0/vendor/remove_dir_all-0.3.0/src/fs.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/remove_dir_all-0.3.0/src/fs.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,252 +0,0 @@ -use std::ffi::OsString; -use std::fs::{self, File, OpenOptions}; -use std::{io, ptr}; -use std::os::windows::prelude::*; -use std::path::{Path, PathBuf}; - -use winapi::*; -use kernel::*; - -pub const VOLUME_NAME_DOS: DWORD = 0x0; - -struct RmdirContext<'a> { - base_dir: &'a Path, - readonly: bool, - counter: u64, -} - -/// Reliably removes directory and all of it's children. -/// ```rust -/// extern crate remove_dir_all; -/// -/// use remove_dir_all::*; -/// -/// fn main() { -/// remove_dir_all("./temp/").unwrap(); -/// } -/// ``` -pub fn remove_dir_all(path: &Path) -> io::Result<()> { - // On Windows it is not enough to just recursively remove the contents of a - // directory and then the directory itself. Deleting does not happen - // instantaneously, but is scheduled. - // To work around this, we move the file or directory to some `base_dir` - // right before deletion to avoid races. - // - // As `base_dir` we choose the parent dir of the directory we want to - // remove. We very probably have permission to create files here, as we - // already need write permission in this dir to delete the directory. And it - // should be on the same volume. - // - // To handle files with names like `CON` and `morse .. .`, and when a - // directory structure is so deep it needs long path names the path is first - // converted to a `//?/`-path with `get_path()`. - // - // To make sure we don't leave a moved file laying around if the process - // crashes before we can delete the file, we do all operations on an file - // handle. By opening a file with `FILE_FLAG_DELETE_ON_CLOSE` Windows will - // always delete the file when the handle closes. - // - // All files are renamed to be in the `base_dir`, and have their name - // changed to "rm-<counter>". After every rename the counter is increased. - // Rename should not overwrite possibly existing files in the base dir. So - // if it fails with `AlreadyExists`, we just increase the counter and try - // again. - // - // For read-only files and directories we first have to remove the read-only - // attribute before we can move or delete them. This also removes the - // attribute from possible hardlinks to the file, so just before closing we - // restore the read-only attribute. - // - // If 'path' points to a directory symlink or junction we should not - // recursively remove the target of the link, but only the link itself. - // - // Moving and deleting is guaranteed to succeed if we are able to open the - // file with `DELETE` permission. If others have the file open we only have - // `DELETE` permission if they have specified `FILE_SHARE_DELETE`. We can - // also delete the file now, but it will not disappear until all others have - // closed the file. But no-one can open the file after we have flagged it - // for deletion. - - // Open the path once to get the canonical path, file type and attributes. - let (path, metadata) = { - let mut opts = OpenOptions::new(); - opts.access_mode(FILE_READ_ATTRIBUTES); - opts.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | - FILE_FLAG_OPEN_REPARSE_POINT); - let file = opts.open(path)?; - (get_path(&file)?, path.metadata()?) - }; - - let mut ctx = RmdirContext { - base_dir: match path.parent() { - Some(dir) => dir, - None => return Err(io::Error::new(io::ErrorKind::PermissionDenied, - "Can't delete root directory")) - }, - readonly: metadata.permissions().readonly(), - counter: 0, - }; - - let filetype = metadata.file_type(); - if filetype.is_dir() { - if !filetype.is_symlink() { - remove_dir_all_recursive(path.as_ref(), &mut ctx) - } else { - remove_item(path.as_ref(), &mut ctx) - } - } else { - Err(io::Error::new(io::ErrorKind::PermissionDenied, "Not a directory")) - } -} - -fn remove_item(path: &Path, ctx: &mut RmdirContext) -> io::Result<()> { - if !ctx.readonly { - let mut opts = OpenOptions::new(); - opts.access_mode(DELETE); - opts.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | // delete directory - FILE_FLAG_OPEN_REPARSE_POINT | // delete symlink - FILE_FLAG_DELETE_ON_CLOSE); - let file = opts.open(path)?; - move_item(&file, ctx) - } else { - // remove read-only permision - let mut permissions = path.metadata()?.permissions(); - permissions.set_readonly(false); - - fs::set_permissions(path, permissions)?; - let file = File::open(path)?; - move_item(&file, ctx)?; - - // restore read-only flag just in case there are other hard links - let mut perm = fs::metadata(&path)?.permissions(); - perm.set_readonly(true); - fs::set_permissions(&path, perm)?; - Ok(()) - } -} - -fn move_item(file: &File, ctx: &mut RmdirContext) -> io::Result<()> { - let mut tmpname = ctx.base_dir.join(format!{"rm-{}", ctx.counter}); - ctx.counter += 1; - - // Try to rename the file. If it already exists, just retry with an other - // filename. - while let Err(err) = rename(file, &tmpname, false) { - if err.kind() != io::ErrorKind::AlreadyExists { return Err(err) }; - tmpname = ctx.base_dir.join(format!("rm-{}", ctx.counter)); - ctx.counter += 1; - } - - Ok(()) -} - -fn rename(file: &File, new: &Path, replace: bool) -> io::Result<()> { - // &self must be opened with DELETE permission - use std::iter; - #[cfg(target_arch = "x86")] - const STRUCT_SIZE: usize = 12; - #[cfg(target_arch = "x86_64")] - const STRUCT_SIZE: usize = 20; - - // FIXME: check for internal NULs in 'new' - let mut data: Vec<u16> = iter::repeat(0u16).take(STRUCT_SIZE/2) - .chain(new.as_os_str().encode_wide()) - .collect(); - data.push(0); - let size = data.len() * 2; - - unsafe { - // Thanks to alignment guarantees on Windows this works - // (8 for 32-bit and 16 for 64-bit) - let mut info = data.as_mut_ptr() as *mut FILE_RENAME_INFO; - // The type of ReplaceIfExists is BOOL, but it actually expects a - // BOOLEAN. This means true is -1, not c::TRUE. - (*info).ReplaceIfExists = if replace { -1 } else { FALSE }; - (*info).RootDirectory = ptr::null_mut(); - (*info).FileNameLength = (size - STRUCT_SIZE) as DWORD; - let result = SetFileInformationByHandle(file.as_raw_handle(), - FileRenameInfo, - data.as_mut_ptr() as *mut _ as *mut _, - size as DWORD); - - if result == 0 { - Err(io::Error::last_os_error()) - } else { - Ok(()) - } - } -} - -fn get_path(f: &File) -> io::Result<PathBuf> { - - fill_utf16_buf(|buf, sz| unsafe { - GetFinalPathNameByHandleW(f.as_raw_handle(), buf, sz, VOLUME_NAME_DOS) - }, |buf| { - PathBuf::from(OsString::from_wide(buf)) - }) -} - -fn remove_dir_all_recursive(path: &Path, ctx: &mut RmdirContext) - -> io::Result<()> { - let dir_readonly = ctx.readonly; - for child in try!(fs::read_dir(path)) { - let child = try!(child); - let child_type = try!(child.file_type()); - ctx.readonly = try!(child.metadata()).permissions().readonly(); - if child_type.is_dir() { - try!(remove_dir_all_recursive(&child.path(), ctx)); - } else { - try!(remove_item(&child.path().as_ref(), ctx)); - } - } - ctx.readonly = dir_readonly; - remove_item(path, ctx) -} - -fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> io::Result<T> - where F1: FnMut(*mut u16, DWORD) -> DWORD, - F2: FnOnce(&[u16]) -> T -{ - // Start off with a stack buf but then spill over to the heap if we end up - // needing more space. - let mut stack_buf = [0u16; 512]; - let mut heap_buf = Vec::new(); - unsafe { - let mut n = stack_buf.len(); - - loop { - let buf = if n <= stack_buf.len() { - &mut stack_buf[..] - } else { - let extra = n - heap_buf.len(); - heap_buf.reserve(extra); - heap_buf.set_len(n); - &mut heap_buf[..] - }; - - // This function is typically called on windows API functions which - // will return the correct length of the string, but these functions - // also return the `0` on error. In some cases, however, the - // returned "correct length" may actually be 0! - // - // To handle this case we call `SetLastError` to reset it to 0 and - // then check it again if we get the "0 error value". If the "last - // error" is still 0 then we interpret it as a 0 length buffer and - // not an actual error. - SetLastError(0); - let k = match f1(buf.as_mut_ptr(), n as DWORD) { - 0 if GetLastError() == 0 => 0, - 0 => return Err(io::Error::last_os_error()), - n => n, - } as usize; - if k == n && GetLastError() == ERROR_INSUFFICIENT_BUFFER { - n *= 2; - } else if k >= n { - n = k; - } else { - return Ok(f2(&buf[..k])) - } - } - } -} - diff -Nru cargo-0.25.0/vendor/remove_dir_all-0.3.0/src/lib.rs cargo-0.26.0/vendor/remove_dir_all-0.3.0/src/lib.rs --- cargo-0.25.0/vendor/remove_dir_all-0.3.0/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/remove_dir_all-0.3.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -extern crate winapi; -extern crate kernel32 as kernel; - -#[cfg(windows)] -mod fs; - -#[cfg(windows)] -pub use self::fs::remove_dir_all; - -#[cfg(not(windows))] -pub use std::fs::remove_dir_all; - diff -Nru cargo-0.25.0/vendor/remove_dir_all-0.5.0/.cargo-checksum.json cargo-0.26.0/vendor/remove_dir_all-0.5.0/.cargo-checksum.json --- cargo-0.25.0/vendor/remove_dir_all-0.5.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/remove_dir_all-0.5.0/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"dfc5b3ce5d5ea144bb04ebd093a9e14e9765bcfec866aecda9b6dec43b3d1e24"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/remove_dir_all-0.5.0/Cargo.toml cargo-0.26.0/vendor/remove_dir_all-0.5.0/Cargo.toml --- cargo-0.25.0/vendor/remove_dir_all-0.5.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/remove_dir_all-0.5.0/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,26 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "remove_dir_all" +version = "0.5.0" +authors = ["Aaronepower <theaaronepower@gmail.com>"] +include = ["Cargo.toml", "LICENCE-APACHE", "LICENCE-MIT", "src/**/*"] +description = "A safe, reliable implementation of remove_dir_all for Windows" +readme = "README.md" +keywords = ["utility", "filesystem", "remove_dir", "windows"] +categories = ["filesystem"] +license = "MIT/Apache-2.0" +repository = "https://github.com/Aaronepower/remove_dir_all.git" +[target."cfg(windows)".dependencies.winapi] +version = "0.3" +features = ["std", "errhandlingapi", "winerror", "fileapi", "winbase"] diff -Nru cargo-0.25.0/vendor/remove_dir_all-0.5.0/LICENCE-APACHE cargo-0.26.0/vendor/remove_dir_all-0.5.0/LICENCE-APACHE --- cargo-0.25.0/vendor/remove_dir_all-0.5.0/LICENCE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/remove_dir_all-0.5.0/LICENCE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,191 @@ + 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 + +Copyright 2017 Aaron Power + +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. + diff -Nru cargo-0.25.0/vendor/remove_dir_all-0.5.0/LICENCE-MIT cargo-0.26.0/vendor/remove_dir_all-0.5.0/LICENCE-MIT --- cargo-0.25.0/vendor/remove_dir_all-0.5.0/LICENCE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/remove_dir_all-0.5.0/LICENCE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,26 @@ +Copyright (c) 2017 Aaron Power + +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. + diff -Nru cargo-0.25.0/vendor/remove_dir_all-0.5.0/src/fs.rs cargo-0.26.0/vendor/remove_dir_all-0.5.0/src/fs.rs --- cargo-0.25.0/vendor/remove_dir_all-0.5.0/src/fs.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/remove_dir_all-0.5.0/src/fs.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,258 @@ +use std::ffi::OsString; +use std::fs::{self, File, OpenOptions}; +use std::{io, ptr}; +use std::os::windows::prelude::*; +use std::path::{Path, PathBuf}; + +use winapi::shared::minwindef::*; +use winapi::shared::winerror::*; +use winapi::um::errhandlingapi::*; +use winapi::um::fileapi::*; +use winapi::um::minwinbase::*; +use winapi::um::winbase::*; +use winapi::um::winnt::*; + +pub const VOLUME_NAME_DOS: DWORD = 0x0; + +struct RmdirContext<'a> { + base_dir: &'a Path, + readonly: bool, + counter: u64, +} + +/// Reliably removes directory and all of it's children. +/// ```rust +/// extern crate remove_dir_all; +/// +/// use remove_dir_all::*; +/// +/// fn main() { +/// remove_dir_all("./temp/").unwrap(); +/// } +/// ``` +pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> { + // On Windows it is not enough to just recursively remove the contents of a + // directory and then the directory itself. Deleting does not happen + // instantaneously, but is scheduled. + // To work around this, we move the file or directory to some `base_dir` + // right before deletion to avoid races. + // + // As `base_dir` we choose the parent dir of the directory we want to + // remove. We very probably have permission to create files here, as we + // already need write permission in this dir to delete the directory. And it + // should be on the same volume. + // + // To handle files with names like `CON` and `morse .. .`, and when a + // directory structure is so deep it needs long path names the path is first + // converted to a `//?/`-path with `get_path()`. + // + // To make sure we don't leave a moved file laying around if the process + // crashes before we can delete the file, we do all operations on an file + // handle. By opening a file with `FILE_FLAG_DELETE_ON_CLOSE` Windows will + // always delete the file when the handle closes. + // + // All files are renamed to be in the `base_dir`, and have their name + // changed to "rm-<counter>". After every rename the counter is increased. + // Rename should not overwrite possibly existing files in the base dir. So + // if it fails with `AlreadyExists`, we just increase the counter and try + // again. + // + // For read-only files and directories we first have to remove the read-only + // attribute before we can move or delete them. This also removes the + // attribute from possible hardlinks to the file, so just before closing we + // restore the read-only attribute. + // + // If 'path' points to a directory symlink or junction we should not + // recursively remove the target of the link, but only the link itself. + // + // Moving and deleting is guaranteed to succeed if we are able to open the + // file with `DELETE` permission. If others have the file open we only have + // `DELETE` permission if they have specified `FILE_SHARE_DELETE`. We can + // also delete the file now, but it will not disappear until all others have + // closed the file. But no-one can open the file after we have flagged it + // for deletion. + + // Open the path once to get the canonical path, file type and attributes. + let (path, metadata) = { + let path = path.as_ref(); + let mut opts = OpenOptions::new(); + opts.access_mode(FILE_READ_ATTRIBUTES); + opts.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | + FILE_FLAG_OPEN_REPARSE_POINT); + let file = opts.open(path)?; + (get_path(&file)?, path.metadata()?) + }; + + let mut ctx = RmdirContext { + base_dir: match path.parent() { + Some(dir) => dir, + None => return Err(io::Error::new(io::ErrorKind::PermissionDenied, + "Can't delete root directory")) + }, + readonly: metadata.permissions().readonly(), + counter: 0, + }; + + let filetype = metadata.file_type(); + if filetype.is_dir() { + if !filetype.is_symlink() { + remove_dir_all_recursive(path.as_ref(), &mut ctx) + } else { + remove_item(path.as_ref(), &mut ctx) + } + } else { + Err(io::Error::new(io::ErrorKind::PermissionDenied, "Not a directory")) + } +} + +fn remove_item(path: &Path, ctx: &mut RmdirContext) -> io::Result<()> { + if !ctx.readonly { + let mut opts = OpenOptions::new(); + opts.access_mode(DELETE); + opts.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | // delete directory + FILE_FLAG_OPEN_REPARSE_POINT | // delete symlink + FILE_FLAG_DELETE_ON_CLOSE); + let file = opts.open(path)?; + move_item(&file, ctx) + } else { + // remove read-only permision + let mut permissions = path.metadata()?.permissions(); + permissions.set_readonly(false); + + fs::set_permissions(path, permissions)?; + let file = File::open(path)?; + move_item(&file, ctx)?; + + // restore read-only flag just in case there are other hard links + let mut perm = fs::metadata(&path)?.permissions(); + perm.set_readonly(true); + fs::set_permissions(&path, perm)?; + Ok(()) + } +} + +fn move_item(file: &File, ctx: &mut RmdirContext) -> io::Result<()> { + let mut tmpname = ctx.base_dir.join(format!{"rm-{}", ctx.counter}); + ctx.counter += 1; + + // Try to rename the file. If it already exists, just retry with an other + // filename. + while let Err(err) = rename(file, &tmpname, false) { + if err.kind() != io::ErrorKind::AlreadyExists { return Err(err) }; + tmpname = ctx.base_dir.join(format!("rm-{}", ctx.counter)); + ctx.counter += 1; + } + + Ok(()) +} + +fn rename(file: &File, new: &Path, replace: bool) -> io::Result<()> { + // &self must be opened with DELETE permission + use std::iter; + #[cfg(target_arch = "x86")] + const STRUCT_SIZE: usize = 12; + #[cfg(target_arch = "x86_64")] + const STRUCT_SIZE: usize = 20; + + // FIXME: check for internal NULs in 'new' + let mut data: Vec<u16> = iter::repeat(0u16).take(STRUCT_SIZE/2) + .chain(new.as_os_str().encode_wide()) + .collect(); + data.push(0); + let size = data.len() * 2; + + unsafe { + // Thanks to alignment guarantees on Windows this works + // (8 for 32-bit and 16 for 64-bit) + let info = data.as_mut_ptr() as *mut FILE_RENAME_INFO; + // The type of ReplaceIfExists is BOOL, but it actually expects a + // BOOLEAN. This means true is -1, not c::TRUE. + (*info).ReplaceIfExists = if replace { -1 } else { FALSE }; + (*info).RootDirectory = ptr::null_mut(); + (*info).FileNameLength = (size - STRUCT_SIZE) as DWORD; + let result = SetFileInformationByHandle(file.as_raw_handle(), + FileRenameInfo, + data.as_mut_ptr() as *mut _ as *mut _, + size as DWORD); + + if result == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } + } +} + +fn get_path(f: &File) -> io::Result<PathBuf> { + + fill_utf16_buf(|buf, sz| unsafe { + GetFinalPathNameByHandleW(f.as_raw_handle(), buf, sz, VOLUME_NAME_DOS) + }, |buf| { + PathBuf::from(OsString::from_wide(buf)) + }) +} + +fn remove_dir_all_recursive(path: &Path, ctx: &mut RmdirContext) + -> io::Result<()> { + let dir_readonly = ctx.readonly; + for child in try!(fs::read_dir(path)) { + let child = try!(child); + let child_type = try!(child.file_type()); + ctx.readonly = try!(child.metadata()).permissions().readonly(); + if child_type.is_dir() { + try!(remove_dir_all_recursive(&child.path(), ctx)); + } else { + try!(remove_item(&child.path().as_ref(), ctx)); + } + } + ctx.readonly = dir_readonly; + remove_item(path, ctx) +} + +fn fill_utf16_buf<F1, F2, T>(mut f1: F1, f2: F2) -> io::Result<T> + where F1: FnMut(*mut u16, DWORD) -> DWORD, + F2: FnOnce(&[u16]) -> T +{ + // Start off with a stack buf but then spill over to the heap if we end up + // needing more space. + let mut stack_buf = [0u16; 512]; + let mut heap_buf = Vec::new(); + unsafe { + let mut n = stack_buf.len(); + + loop { + let buf = if n <= stack_buf.len() { + &mut stack_buf[..] + } else { + let extra = n - heap_buf.len(); + heap_buf.reserve(extra); + heap_buf.set_len(n); + &mut heap_buf[..] + }; + + // This function is typically called on windows API functions which + // will return the correct length of the string, but these functions + // also return the `0` on error. In some cases, however, the + // returned "correct length" may actually be 0! + // + // To handle this case we call `SetLastError` to reset it to 0 and + // then check it again if we get the "0 error value". If the "last + // error" is still 0 then we interpret it as a 0 length buffer and + // not an actual error. + SetLastError(0); + let k = match f1(buf.as_mut_ptr(), n as DWORD) { + 0 if GetLastError() == 0 => 0, + 0 => return Err(io::Error::last_os_error()), + n => n, + } as usize; + if k == n && GetLastError() == ERROR_INSUFFICIENT_BUFFER { + n *= 2; + } else if k >= n { + n = k; + } else { + return Ok(f2(&buf[..k])) + } + } + } +} + diff -Nru cargo-0.25.0/vendor/remove_dir_all-0.5.0/src/lib.rs cargo-0.26.0/vendor/remove_dir_all-0.5.0/src/lib.rs --- cargo-0.25.0/vendor/remove_dir_all-0.5.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/remove_dir_all-0.5.0/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,12 @@ +#[cfg(windows)] +extern crate winapi; + +#[cfg(windows)] +mod fs; + +#[cfg(windows)] +pub use self::fs::remove_dir_all; + +#[cfg(not(windows))] +pub use std::fs::remove_dir_all; + diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.6/.cargo-checksum.json cargo-0.26.0/vendor/rustc-demangle-0.1.6/.cargo-checksum.json --- cargo-0.25.0/vendor/rustc-demangle-0.1.6/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.6/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"f312457f8a4fa31d3581a6f423a70d6c33a10b95291985df55f1ff670ec10ce8"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.6/Cargo.toml cargo-0.26.0/vendor/rustc-demangle-0.1.6/Cargo.toml --- cargo-0.25.0/vendor/rustc-demangle-0.1.6/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.6/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "rustc-demangle" -version = "0.1.6" -authors = ["Alex Crichton <alex@alexcrichton.com>"] -description = "Rust compiler symbol demangling.\n" -homepage = "https://github.com/alexcrichton/rustc-demangle" -documentation = "http://alexcrichton.com/rustc-demangle" -readme = "README.md" -license = "MIT/Apache-2.0" -repository = "https://github.com/alexcrichton/rustc-demangle" diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.6/LICENSE-APACHE cargo-0.26.0/vendor/rustc-demangle-0.1.6/LICENSE-APACHE --- cargo-0.25.0/vendor/rustc-demangle-0.1.6/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.6/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.6/LICENSE-MIT cargo-0.26.0/vendor/rustc-demangle-0.1.6/LICENSE-MIT --- cargo-0.25.0/vendor/rustc-demangle-0.1.6/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.6/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 Alex Crichton - -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. diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.6/README.md cargo-0.26.0/vendor/rustc-demangle-0.1.6/README.md --- cargo-0.25.0/vendor/rustc-demangle-0.1.6/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.6/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -# rustc-demangle - -Symbol demangling for Rust - -[![Build Status](https://travis-ci.org/alexcrichton/rustc-demangle.svg?branch=master)](https://travis-ci.org/alexcrichton/rustc-demangle) - -[Documentation](http://alexcrichton.com/rustc-demangle) - -# License - -This project is 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 rustc-demangle you, as defined in the Apache-2.0 license, shall -be dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.6/src/lib.rs cargo-0.26.0/vendor/rustc-demangle-0.1.6/src/lib.rs --- cargo-0.25.0/vendor/rustc-demangle-0.1.6/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.6/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,412 +0,0 @@ -//! Demangle Rust compiler symbol names. -//! -//! This crate provides a `demangle` function which will return a `Demangle` -//! sentinel value that can be used to learn about the demangled version of a -//! symbol name. The demangled representation will be the same as the original -//! if it doesn't look like a mangled symbol name. -//! -//! `Demangle` can be formatted with the `Display` trait. The alternate -//! modifier (`#`) can be used to format the symbol name without the -//! trailing hash value. -//! -//! # Examples -//! -//! ``` -//! use rustc_demangle::demangle; -//! -//! assert_eq!(demangle("_ZN4testE").to_string(), "test"); -//! assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar"); -//! assert_eq!(demangle("foo").to_string(), "foo"); -//! // With hash -//! assert_eq!(format!("{}", demangle("_ZN3foo17h05af221e174051e9E")), "foo::h05af221e174051e9"); -//! // Without hash -//! assert_eq!(format!("{:#}", demangle("_ZN3foo17h05af221e174051e9E")), "foo"); -//! ``` - -#![no_std] -#![deny(missing_docs)] - -#[cfg(test)] -#[macro_use] -extern crate std; - -use core::fmt; - -/// Representation of a demangled symbol name. -pub struct Demangle<'a> { - original: &'a str, - inner: &'a str, - valid: bool, - /// The number of ::-separated elements in the original name. - elements: usize, -} - -/// De-mangles a Rust symbol into a more readable version -/// -/// All rust symbols by default are mangled as they contain characters that -/// cannot be represented in all object files. The mangling mechanism is similar -/// to C++'s, but Rust has a few specifics to handle items like lifetimes in -/// symbols. -/// -/// This function will take a **mangled** symbol (typically acquired from a -/// `Symbol` which is in turn resolved from a `Frame`) and then writes the -/// de-mangled version into the given `writer`. If the symbol does not look like -/// a mangled symbol, it is still written to `writer`. -/// -/// # Examples -/// -/// ``` -/// use rustc_demangle::demangle; -/// -/// assert_eq!(demangle("_ZN4testE").to_string(), "test"); -/// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar"); -/// assert_eq!(demangle("foo").to_string(), "foo"); -/// ``` - -// All rust symbols are in theory lists of "::"-separated identifiers. Some -// assemblers, however, can't handle these characters in symbol names. To get -// around this, we use C++-style mangling. The mangling method is: -// -// 1. Prefix the symbol with "_ZN" -// 2. For each element of the path, emit the length plus the element -// 3. End the path with "E" -// -// For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar". -// -// We're the ones printing our backtraces, so we can't rely on anything else to -// demangle our symbols. It's *much* nicer to look at demangled symbols, so -// this function is implemented to give us nice pretty output. -// -// Note that this demangler isn't quite as fancy as it could be. We have lots -// of other information in our symbols like hashes, version, type information, -// etc. Additionally, this doesn't handle glue symbols at all. -pub fn demangle(mut s: &str) -> Demangle { - // During ThinLTO LLVM may import and rename internal symbols, so strip out - // those endings first as they're on of the last manglings applied to symbol - // names. - let llvm = ".llvm."; - if let Some(i) = s.find(llvm) { - let candidate = &s[i + llvm.len()..]; - let all_hex = candidate.chars().all(|c| { - match c { - 'A' ... 'F' | '0' ... '9' => true, - _ => false, - } - }); - - if all_hex { - s = &s[..i]; - } - } - - // First validate the symbol. If it doesn't look like anything we're - // expecting, we just print it literally. Note that we must handle non-rust - // symbols because we could have any function in the backtrace. - let mut valid = true; - let mut inner = s; - if s.len() > 4 && s.starts_with("_ZN") && s.ends_with('E') { - inner = &s[3..s.len() - 1]; - } else if s.len() > 3 && s.starts_with("ZN") && s.ends_with('E') { - // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" - // form too. - inner = &s[2..s.len() - 1]; - } else if s.len() > 5 && s.starts_with("__ZN") && s.ends_with('E') { - // On OSX, symbols are prefixed with an extra _ - inner = &s[4..s.len() - 1]; - } else { - valid = false; - } - - // only work with ascii text - if inner.bytes().any(|c| c & 0x80 != 0) { - valid = false; - } - - let mut elements = 0; - if valid { - let mut chars = inner.chars().peekable(); - while valid { - let mut i = 0usize; - while let Some(&c) = chars.peek() { - if !c.is_digit(10) { - break - } - chars.next(); - let next = i.checked_mul(10) - .and_then(|i| i.checked_add(c as usize - '0' as usize)); - i = match next { - Some(i) => i, - None => { - valid = false; - break - } - }; - } - - if i == 0 { - valid = chars.next().is_none(); - break; - } else if chars.by_ref().take(i).count() != i { - valid = false; - } else { - elements += 1; - } - } - } - - Demangle { - inner: inner, - valid: valid, - elements: elements, - original: s, - } -} - -/// Error returned from the `try_demangle` function below when demangling fails. -#[derive(Debug, Clone)] -pub struct TryDemangleError { - _priv: (), -} - -/// The same as `demangle`, except return an `Err` if the string does not appear -/// to be a Rust symbol, rather than "demangling" the given string as a no-op. -/// -/// ``` -/// extern crate rustc_demangle; -/// -/// let not_a_rust_symbol = "la la la"; -/// -/// // The `try_demangle` function will reject strings which are not Rust symbols. -/// assert!(rustc_demangle::try_demangle(not_a_rust_symbol).is_err()); -/// -/// // While `demangle` will just pass the non-symbol through as a no-op. -/// assert_eq!(rustc_demangle::demangle(not_a_rust_symbol).as_str(), not_a_rust_symbol); -/// ``` -pub fn try_demangle(s: &str) -> Result<Demangle, TryDemangleError> { - let sym = demangle(s); - if sym.valid { - Ok(sym) - } else { - Err(TryDemangleError { _priv: () }) - } -} - -impl<'a> Demangle<'a> { - /// Returns the underlying string that's being demangled. - pub fn as_str(&self) -> &'a str { - self.original - } -} - -// Rust hashes are hex digits with an `h` prepended. -fn is_rust_hash(s: &str) -> bool { - s.starts_with('h') && s[1..].chars().all(|c| c.is_digit(16)) -} - -impl<'a> fmt::Display for Demangle<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // Alright, let's do this. - if !self.valid { - return f.write_str(self.inner); - } - - let mut inner = self.inner; - for element in 0..self.elements { - let mut rest = inner; - while rest.chars().next().unwrap().is_digit(10) { - rest = &rest[1..]; - } - let i: usize = inner[..(inner.len() - rest.len())].parse().unwrap(); - inner = &rest[i..]; - rest = &rest[..i]; - // Skip printing the hash if alternate formatting - // was requested. - if f.alternate() && element+1 == self.elements && is_rust_hash(&rest) { - break; - } - if element != 0 { - try!(f.write_str("::")); - } - if rest.starts_with("_$") { - rest = &rest[1..]; - } - while !rest.is_empty() { - if rest.starts_with('.') { - if let Some('.') = rest[1..].chars().next() { - try!(f.write_str("::")); - rest = &rest[2..]; - } else { - try!(f.write_str(".")); - rest = &rest[1..]; - } - } else if rest.starts_with('$') { - macro_rules! demangle { - ($($pat:expr => $demangled:expr),*) => ({ - $(if rest.starts_with($pat) { - try!(f.write_str($demangled)); - rest = &rest[$pat.len()..]; - } else)* - { - try!(f.write_str(rest)); - break; - } - - }) - } - - // see src/librustc/back/link.rs for these mappings - demangle! { - "$SP$" => "@", - "$BP$" => "*", - "$RF$" => "&", - "$LT$" => "<", - "$GT$" => ">", - "$LP$" => "(", - "$RP$" => ")", - "$C$" => ",", - - // in theory we can demangle any Unicode code point, but - // for simplicity we just catch the common ones. - "$u7e$" => "~", - "$u20$" => " ", - "$u27$" => "'", - "$u5b$" => "[", - "$u5d$" => "]", - "$u7b$" => "{", - "$u7d$" => "}", - "$u3b$" => ";", - "$u2b$" => "+", - "$u22$" => "\"" - } - } else { - let idx = match rest.char_indices().find(|&(_, c)| c == '$' || c == '.') { - None => rest.len(), - Some((i, _)) => i, - }; - try!(f.write_str(&rest[..idx])); - rest = &rest[idx..]; - } - } - } - - Ok(()) - } -} - -impl<'a> fmt::Debug for Demangle<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(self, f) - } -} - -#[cfg(test)] -mod tests { - use std::prelude::v1::*; - - macro_rules! t { - ($a:expr, $b:expr) => ({ - assert_eq!(super::demangle($a).to_string(), $b); - }) - } - - macro_rules! t_nohash { - ($a:expr, $b:expr) => ({ - assert_eq!(format!("{:#}", super::demangle($a)), $b); - }) - } - - #[test] - fn demangle() { - t!("test", "test"); - t!("_ZN4testE", "test"); - t!("_ZN4test", "_ZN4test"); - t!("_ZN4test1a2bcE", "test::a::bc"); - } - - #[test] - fn demangle_dollars() { - t!("_ZN4$RP$E", ")"); - t!("_ZN8$RF$testE", "&test"); - t!("_ZN8$BP$test4foobE", "*test::foob"); - t!("_ZN9$u20$test4foobE", " test::foob"); - t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>"); - } - - #[test] - fn demangle_many_dollars() { - t!("_ZN13test$u20$test4foobE", "test test::foob"); - t!("_ZN12test$BP$test4foobE", "test*test::foob"); - } - - - #[test] - fn demangle_osx() { - t!("__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E", "alloc::allocator::Layout::for_value::h02a996811f781011"); - t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", "<core::option::Option<T>>::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659"); - t!("__ZN4core5slice89_$LT$impl$u20$core..iter..traits..IntoIterator$u20$for$u20$$RF$$u27$a$u20$$u5b$T$u5d$$GT$9into_iter17h450e234d27262170E", "core::slice::<impl core::iter::traits::IntoIterator for &'a [T]>::into_iter::h450e234d27262170"); - } - - #[test] - fn demangle_windows() { - t!("ZN4testE", "test"); - t!("ZN13test$u20$test4foobE", "test test::foob"); - t!("ZN12test$RF$test4foobE", "test&test::foob"); - } - - #[test] - fn demangle_elements_beginning_with_underscore() { - t!("_ZN13_$LT$test$GT$E", "<test>"); - t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}"); - t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR"); - } - - #[test] - fn demangle_trait_impls() { - t!("_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE", - "<Test + 'static as foo::Bar<Test>>::bar"); - } - - #[test] - fn demangle_without_hash() { - let s = "_ZN3foo17h05af221e174051e9E"; - t!(s, "foo::h05af221e174051e9"); - t_nohash!(s, "foo"); - } - - #[test] - fn demangle_without_hash_edgecases() { - // One element, no hash. - t_nohash!("_ZN3fooE", "foo"); - // Two elements, no hash. - t_nohash!("_ZN3foo3barE", "foo::bar"); - // Longer-than-normal hash. - t_nohash!("_ZN3foo20h05af221e174051e9abcE", "foo"); - // Shorter-than-normal hash. - t_nohash!("_ZN3foo5h05afE", "foo"); - // Valid hash, but not at the end. - t_nohash!("_ZN17h05af221e174051e93fooE", "h05af221e174051e9::foo"); - // Not a valid hash, missing the 'h'. - t_nohash!("_ZN3foo16ffaf221e174051e9E", "foo::ffaf221e174051e9"); - // Not a valid hash, has a non-hex-digit. - t_nohash!("_ZN3foo17hg5af221e174051e9E", "foo::hg5af221e174051e9"); - } - - #[test] - fn demangle_thinlto() { - // One element, no hash. - t!("_ZN3fooE.llvm.9D1C9369", "foo"); - t_nohash!("_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9", "backtrace::foo"); - } - - #[test] - fn dont_panic() { - super::demangle("_ZN2222222222222222222222EE").to_string(); - super::demangle("_ZN5*70527e27.ll34csaғE").to_string(); - super::demangle("_ZN5*70527a54.ll34_$b.1E").to_string(); - super::demangle("\ - _ZN5~saäb4e\n\ - 2734cOsbE\n\ - 5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\ - ").to_string(); - } -} diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.6/.travis.yml cargo-0.26.0/vendor/rustc-demangle-0.1.6/.travis.yml --- cargo-0.25.0/vendor/rustc-demangle-0.1.6/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.6/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -language: rust -rust: - - stable - - beta - - nightly -sudo: false -before_script: - - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH -script: - - cargo build - - cargo test - - cargo doc -after_success: - - travis-cargo --only nightly doc-upload -notifications: - email: - on_success: never -env: - global: - secure: "VWE8DaftZLOj34USRPiq2jyFV1xWrPJP0lgMVWPGF52soyWV6L5FyMlbk00GvKH8y5h0urtuVFmInsLKz1E96eTLbD7Efa2snjSlOWMsTaWy3yq0NNuPraMWiXUkjDBxW3DTV47HN9thYA7TbrM35A0XGr7fXKl4CPT/UKEo2nNZPb2Y2XYaD6RID1sXMOvemOERGu7Lnq8dQ/PdGWWkpTV4FVsmq2wTyyZnzsEFsK0r/wqEPPHSl8r3NH6Rid9kCMw3h1d9s1eYSqzP09/fYfjy+X/6iGV9dL5WUQFL7xG7WjfZZG/e87lAxbXx+jXTlncdvXjm4BmIOYHeEMK9N5D3qE5C1gIIU+tk6ZuVKBLWMQJnAIDJKCsVdUhAXtWqbFK4djvNJUml1rIOF/CVUeynBVtacJ8nlxyh61XvDHbZGSBFBR2odEkhUaLzw/t/zqOIYd0u+mjtM4pX1nZ+ZFIMqVFsNTfVWWMDLyRVBNiAoHCdn/ug+mJJaYE3mZ2q1wPPqJVFffyaZVyg97zFO0y9v5ASHjb/7nYlIPoDGDPDUuoscuw5IYf+6CoCi7EgGqg5v7X1BsBXSYK+XfzOvrAqP31ixNGyVJEcBjAaJXwopx6KVIqWe71eHJDX68VeI0ncfCPDDQIReKA7MBhq5PzRDzr4iRHZAhNyuKgo+Fo=" diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.7/.cargo-checksum.json cargo-0.26.0/vendor/rustc-demangle-0.1.7/.cargo-checksum.json --- cargo-0.25.0/vendor/rustc-demangle-0.1.7/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.7/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"11fb43a206a04116ffd7cfcf9bcb941f8eb6cc7ff667272246b0a1c74259a3cb"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.7/Cargo.toml cargo-0.26.0/vendor/rustc-demangle-0.1.7/Cargo.toml --- cargo-0.25.0/vendor/rustc-demangle-0.1.7/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.7/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,22 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "rustc-demangle" +version = "0.1.7" +authors = ["Alex Crichton <alex@alexcrichton.com>"] +description = "Rust compiler symbol demangling.\n" +homepage = "https://github.com/alexcrichton/rustc-demangle" +documentation = "http://alexcrichton.com/rustc-demangle" +readme = "README.md" +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/rustc-demangle" diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.7/LICENSE-APACHE cargo-0.26.0/vendor/rustc-demangle-0.1.7/LICENSE-APACHE --- cargo-0.25.0/vendor/rustc-demangle-0.1.7/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.7/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.7/LICENSE-MIT cargo-0.26.0/vendor/rustc-demangle-0.1.7/LICENSE-MIT --- cargo-0.25.0/vendor/rustc-demangle-0.1.7/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.7/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +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. diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.7/README.md cargo-0.26.0/vendor/rustc-demangle-0.1.7/README.md --- cargo-0.25.0/vendor/rustc-demangle-0.1.7/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.7/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,24 @@ +# rustc-demangle + +Symbol demangling for Rust + +[![Build Status](https://travis-ci.org/alexcrichton/rustc-demangle.svg?branch=master)](https://travis-ci.org/alexcrichton/rustc-demangle) + +[Documentation](http://alexcrichton.com/rustc-demangle) + +# License + +This project is 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 rustc-demangle you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.7/src/lib.rs cargo-0.26.0/vendor/rustc-demangle-0.1.7/src/lib.rs --- cargo-0.25.0/vendor/rustc-demangle-0.1.7/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.7/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,413 @@ +//! Demangle Rust compiler symbol names. +//! +//! This crate provides a `demangle` function which will return a `Demangle` +//! sentinel value that can be used to learn about the demangled version of a +//! symbol name. The demangled representation will be the same as the original +//! if it doesn't look like a mangled symbol name. +//! +//! `Demangle` can be formatted with the `Display` trait. The alternate +//! modifier (`#`) can be used to format the symbol name without the +//! trailing hash value. +//! +//! # Examples +//! +//! ``` +//! use rustc_demangle::demangle; +//! +//! assert_eq!(demangle("_ZN4testE").to_string(), "test"); +//! assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar"); +//! assert_eq!(demangle("foo").to_string(), "foo"); +//! // With hash +//! assert_eq!(format!("{}", demangle("_ZN3foo17h05af221e174051e9E")), "foo::h05af221e174051e9"); +//! // Without hash +//! assert_eq!(format!("{:#}", demangle("_ZN3foo17h05af221e174051e9E")), "foo"); +//! ``` + +#![no_std] +#![deny(missing_docs)] + +#[cfg(test)] +#[macro_use] +extern crate std; + +use core::fmt; + +/// Representation of a demangled symbol name. +pub struct Demangle<'a> { + original: &'a str, + inner: &'a str, + valid: bool, + /// The number of ::-separated elements in the original name. + elements: usize, +} + +/// De-mangles a Rust symbol into a more readable version +/// +/// All rust symbols by default are mangled as they contain characters that +/// cannot be represented in all object files. The mangling mechanism is similar +/// to C++'s, but Rust has a few specifics to handle items like lifetimes in +/// symbols. +/// +/// This function will take a **mangled** symbol (typically acquired from a +/// `Symbol` which is in turn resolved from a `Frame`) and then writes the +/// de-mangled version into the given `writer`. If the symbol does not look like +/// a mangled symbol, it is still written to `writer`. +/// +/// # Examples +/// +/// ``` +/// use rustc_demangle::demangle; +/// +/// assert_eq!(demangle("_ZN4testE").to_string(), "test"); +/// assert_eq!(demangle("_ZN3foo3barE").to_string(), "foo::bar"); +/// assert_eq!(demangle("foo").to_string(), "foo"); +/// ``` + +// All rust symbols are in theory lists of "::"-separated identifiers. Some +// assemblers, however, can't handle these characters in symbol names. To get +// around this, we use C++-style mangling. The mangling method is: +// +// 1. Prefix the symbol with "_ZN" +// 2. For each element of the path, emit the length plus the element +// 3. End the path with "E" +// +// For example, "_ZN4testE" => "test" and "_ZN3foo3barE" => "foo::bar". +// +// We're the ones printing our backtraces, so we can't rely on anything else to +// demangle our symbols. It's *much* nicer to look at demangled symbols, so +// this function is implemented to give us nice pretty output. +// +// Note that this demangler isn't quite as fancy as it could be. We have lots +// of other information in our symbols like hashes, version, type information, +// etc. Additionally, this doesn't handle glue symbols at all. +pub fn demangle(mut s: &str) -> Demangle { + // During ThinLTO LLVM may import and rename internal symbols, so strip out + // those endings first as they're on of the last manglings applied to symbol + // names. + let llvm = ".llvm."; + if let Some(i) = s.find(llvm) { + let candidate = &s[i + llvm.len()..]; + let all_hex = candidate.chars().all(|c| { + match c { + 'A' ... 'F' | '0' ... '9' | '@' => true, + _ => false, + } + }); + + if all_hex { + s = &s[..i]; + } + } + + // First validate the symbol. If it doesn't look like anything we're + // expecting, we just print it literally. Note that we must handle non-rust + // symbols because we could have any function in the backtrace. + let mut valid = true; + let mut inner = s; + if s.len() > 4 && s.starts_with("_ZN") && s.ends_with('E') { + inner = &s[3..s.len() - 1]; + } else if s.len() > 3 && s.starts_with("ZN") && s.ends_with('E') { + // On Windows, dbghelp strips leading underscores, so we accept "ZN...E" + // form too. + inner = &s[2..s.len() - 1]; + } else if s.len() > 5 && s.starts_with("__ZN") && s.ends_with('E') { + // On OSX, symbols are prefixed with an extra _ + inner = &s[4..s.len() - 1]; + } else { + valid = false; + } + + // only work with ascii text + if inner.bytes().any(|c| c & 0x80 != 0) { + valid = false; + } + + let mut elements = 0; + if valid { + let mut chars = inner.chars().peekable(); + while valid { + let mut i = 0usize; + while let Some(&c) = chars.peek() { + if !c.is_digit(10) { + break + } + chars.next(); + let next = i.checked_mul(10) + .and_then(|i| i.checked_add(c as usize - '0' as usize)); + i = match next { + Some(i) => i, + None => { + valid = false; + break + } + }; + } + + if i == 0 { + valid = chars.next().is_none(); + break; + } else if chars.by_ref().take(i).count() != i { + valid = false; + } else { + elements += 1; + } + } + } + + Demangle { + inner: inner, + valid: valid, + elements: elements, + original: s, + } +} + +/// Error returned from the `try_demangle` function below when demangling fails. +#[derive(Debug, Clone)] +pub struct TryDemangleError { + _priv: (), +} + +/// The same as `demangle`, except return an `Err` if the string does not appear +/// to be a Rust symbol, rather than "demangling" the given string as a no-op. +/// +/// ``` +/// extern crate rustc_demangle; +/// +/// let not_a_rust_symbol = "la la la"; +/// +/// // The `try_demangle` function will reject strings which are not Rust symbols. +/// assert!(rustc_demangle::try_demangle(not_a_rust_symbol).is_err()); +/// +/// // While `demangle` will just pass the non-symbol through as a no-op. +/// assert_eq!(rustc_demangle::demangle(not_a_rust_symbol).as_str(), not_a_rust_symbol); +/// ``` +pub fn try_demangle(s: &str) -> Result<Demangle, TryDemangleError> { + let sym = demangle(s); + if sym.valid { + Ok(sym) + } else { + Err(TryDemangleError { _priv: () }) + } +} + +impl<'a> Demangle<'a> { + /// Returns the underlying string that's being demangled. + pub fn as_str(&self) -> &'a str { + self.original + } +} + +// Rust hashes are hex digits with an `h` prepended. +fn is_rust_hash(s: &str) -> bool { + s.starts_with('h') && s[1..].chars().all(|c| c.is_digit(16)) +} + +impl<'a> fmt::Display for Demangle<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Alright, let's do this. + if !self.valid { + return f.write_str(self.inner); + } + + let mut inner = self.inner; + for element in 0..self.elements { + let mut rest = inner; + while rest.chars().next().unwrap().is_digit(10) { + rest = &rest[1..]; + } + let i: usize = inner[..(inner.len() - rest.len())].parse().unwrap(); + inner = &rest[i..]; + rest = &rest[..i]; + // Skip printing the hash if alternate formatting + // was requested. + if f.alternate() && element+1 == self.elements && is_rust_hash(&rest) { + break; + } + if element != 0 { + try!(f.write_str("::")); + } + if rest.starts_with("_$") { + rest = &rest[1..]; + } + while !rest.is_empty() { + if rest.starts_with('.') { + if let Some('.') = rest[1..].chars().next() { + try!(f.write_str("::")); + rest = &rest[2..]; + } else { + try!(f.write_str(".")); + rest = &rest[1..]; + } + } else if rest.starts_with('$') { + macro_rules! demangle { + ($($pat:expr => $demangled:expr),*) => ({ + $(if rest.starts_with($pat) { + try!(f.write_str($demangled)); + rest = &rest[$pat.len()..]; + } else)* + { + try!(f.write_str(rest)); + break; + } + + }) + } + + // see src/librustc/back/link.rs for these mappings + demangle! { + "$SP$" => "@", + "$BP$" => "*", + "$RF$" => "&", + "$LT$" => "<", + "$GT$" => ">", + "$LP$" => "(", + "$RP$" => ")", + "$C$" => ",", + + // in theory we can demangle any Unicode code point, but + // for simplicity we just catch the common ones. + "$u7e$" => "~", + "$u20$" => " ", + "$u27$" => "'", + "$u5b$" => "[", + "$u5d$" => "]", + "$u7b$" => "{", + "$u7d$" => "}", + "$u3b$" => ";", + "$u2b$" => "+", + "$u22$" => "\"" + } + } else { + let idx = match rest.char_indices().find(|&(_, c)| c == '$' || c == '.') { + None => rest.len(), + Some((i, _)) => i, + }; + try!(f.write_str(&rest[..idx])); + rest = &rest[idx..]; + } + } + } + + Ok(()) + } +} + +impl<'a> fmt::Debug for Demangle<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +#[cfg(test)] +mod tests { + use std::prelude::v1::*; + + macro_rules! t { + ($a:expr, $b:expr) => ({ + assert_eq!(super::demangle($a).to_string(), $b); + }) + } + + macro_rules! t_nohash { + ($a:expr, $b:expr) => ({ + assert_eq!(format!("{:#}", super::demangle($a)), $b); + }) + } + + #[test] + fn demangle() { + t!("test", "test"); + t!("_ZN4testE", "test"); + t!("_ZN4test", "_ZN4test"); + t!("_ZN4test1a2bcE", "test::a::bc"); + } + + #[test] + fn demangle_dollars() { + t!("_ZN4$RP$E", ")"); + t!("_ZN8$RF$testE", "&test"); + t!("_ZN8$BP$test4foobE", "*test::foob"); + t!("_ZN9$u20$test4foobE", " test::foob"); + t!("_ZN35Bar$LT$$u5b$u32$u3b$$u20$4$u5d$$GT$E", "Bar<[u32; 4]>"); + } + + #[test] + fn demangle_many_dollars() { + t!("_ZN13test$u20$test4foobE", "test test::foob"); + t!("_ZN12test$BP$test4foobE", "test*test::foob"); + } + + + #[test] + fn demangle_osx() { + t!("__ZN5alloc9allocator6Layout9for_value17h02a996811f781011E", "alloc::allocator::Layout::for_value::h02a996811f781011"); + t!("__ZN38_$LT$core..option..Option$LT$T$GT$$GT$6unwrap18_MSG_FILE_LINE_COL17haf7cb8d5824ee659E", "<core::option::Option<T>>::unwrap::_MSG_FILE_LINE_COL::haf7cb8d5824ee659"); + t!("__ZN4core5slice89_$LT$impl$u20$core..iter..traits..IntoIterator$u20$for$u20$$RF$$u27$a$u20$$u5b$T$u5d$$GT$9into_iter17h450e234d27262170E", "core::slice::<impl core::iter::traits::IntoIterator for &'a [T]>::into_iter::h450e234d27262170"); + } + + #[test] + fn demangle_windows() { + t!("ZN4testE", "test"); + t!("ZN13test$u20$test4foobE", "test test::foob"); + t!("ZN12test$RF$test4foobE", "test&test::foob"); + } + + #[test] + fn demangle_elements_beginning_with_underscore() { + t!("_ZN13_$LT$test$GT$E", "<test>"); + t!("_ZN28_$u7b$$u7b$closure$u7d$$u7d$E", "{{closure}}"); + t!("_ZN15__STATIC_FMTSTRE", "__STATIC_FMTSTR"); + } + + #[test] + fn demangle_trait_impls() { + t!("_ZN71_$LT$Test$u20$$u2b$$u20$$u27$static$u20$as$u20$foo..Bar$LT$Test$GT$$GT$3barE", + "<Test + 'static as foo::Bar<Test>>::bar"); + } + + #[test] + fn demangle_without_hash() { + let s = "_ZN3foo17h05af221e174051e9E"; + t!(s, "foo::h05af221e174051e9"); + t_nohash!(s, "foo"); + } + + #[test] + fn demangle_without_hash_edgecases() { + // One element, no hash. + t_nohash!("_ZN3fooE", "foo"); + // Two elements, no hash. + t_nohash!("_ZN3foo3barE", "foo::bar"); + // Longer-than-normal hash. + t_nohash!("_ZN3foo20h05af221e174051e9abcE", "foo"); + // Shorter-than-normal hash. + t_nohash!("_ZN3foo5h05afE", "foo"); + // Valid hash, but not at the end. + t_nohash!("_ZN17h05af221e174051e93fooE", "h05af221e174051e9::foo"); + // Not a valid hash, missing the 'h'. + t_nohash!("_ZN3foo16ffaf221e174051e9E", "foo::ffaf221e174051e9"); + // Not a valid hash, has a non-hex-digit. + t_nohash!("_ZN3foo17hg5af221e174051e9E", "foo::hg5af221e174051e9"); + } + + #[test] + fn demangle_thinlto() { + // One element, no hash. + t!("_ZN3fooE.llvm.9D1C9369", "foo"); + t!("_ZN3fooE.llvm.9D1C9369@@16", "foo"); + t_nohash!("_ZN9backtrace3foo17hbb467fcdaea5d79bE.llvm.A5310EB9", "backtrace::foo"); + } + + #[test] + fn dont_panic() { + super::demangle("_ZN2222222222222222222222EE").to_string(); + super::demangle("_ZN5*70527e27.ll34csaғE").to_string(); + super::demangle("_ZN5*70527a54.ll34_$b.1E").to_string(); + super::demangle("\ + _ZN5~saäb4e\n\ + 2734cOsbE\n\ + 5usage20h)3\0\0\0\0\0\0\07e2734cOsbE\ + ").to_string(); + } +} diff -Nru cargo-0.25.0/vendor/rustc-demangle-0.1.7/.travis.yml cargo-0.26.0/vendor/rustc-demangle-0.1.7/.travis.yml --- cargo-0.25.0/vendor/rustc-demangle-0.1.7/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/rustc-demangle-0.1.7/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +language: rust +rust: + - stable + - beta + - nightly +sudo: false +before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH +script: + - cargo build + - cargo test + - cargo doc +after_success: + - travis-cargo --only nightly doc-upload +notifications: + email: + on_success: never +env: + global: + secure: "VWE8DaftZLOj34USRPiq2jyFV1xWrPJP0lgMVWPGF52soyWV6L5FyMlbk00GvKH8y5h0urtuVFmInsLKz1E96eTLbD7Efa2snjSlOWMsTaWy3yq0NNuPraMWiXUkjDBxW3DTV47HN9thYA7TbrM35A0XGr7fXKl4CPT/UKEo2nNZPb2Y2XYaD6RID1sXMOvemOERGu7Lnq8dQ/PdGWWkpTV4FVsmq2wTyyZnzsEFsK0r/wqEPPHSl8r3NH6Rid9kCMw3h1d9s1eYSqzP09/fYfjy+X/6iGV9dL5WUQFL7xG7WjfZZG/e87lAxbXx+jXTlncdvXjm4BmIOYHeEMK9N5D3qE5C1gIIU+tk6ZuVKBLWMQJnAIDJKCsVdUhAXtWqbFK4djvNJUml1rIOF/CVUeynBVtacJ8nlxyh61XvDHbZGSBFBR2odEkhUaLzw/t/zqOIYd0u+mjtM4pX1nZ+ZFIMqVFsNTfVWWMDLyRVBNiAoHCdn/ug+mJJaYE3mZ2q1wPPqJVFffyaZVyg97zFO0y9v5ASHjb/7nYlIPoDGDPDUuoscuw5IYf+6CoCi7EgGqg5v7X1BsBXSYK+XfzOvrAqP31ixNGyVJEcBjAaJXwopx6KVIqWe71eHJDX68VeI0ncfCPDDQIReKA7MBhq5PzRDzr4iRHZAhNyuKgo+Fo=" diff -Nru cargo-0.25.0/vendor/same-file-0.1.3/appveyor.yml cargo-0.26.0/vendor/same-file-0.1.3/appveyor.yml --- cargo-0.25.0/vendor/same-file-0.1.3/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-0.1.3/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -environment: - matrix: - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc - - TARGET: i686-pc-windows-gnu -install: - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" - - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - - SET PATH=%PATH%;C:\MinGW\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo build --verbose - - cargo test --verbose - -branches: - only: - - master diff -Nru cargo-0.25.0/vendor/same-file-0.1.3/.cargo-checksum.json cargo-0.26.0/vendor/same-file-0.1.3/.cargo-checksum.json --- cargo-0.25.0/vendor/same-file-0.1.3/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-0.1.3/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"d931a44fdaa43b8637009e7632a02adc4f2b2e0733c08caa4cf00e8da4a117a7"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/same-file-0.1.3/Cargo.toml cargo-0.26.0/vendor/same-file-0.1.3/Cargo.toml --- cargo-0.25.0/vendor/same-file-0.1.3/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-0.1.3/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -[package] -name = "same-file" -version = "0.1.3" #:version -authors = ["Andrew Gallant <jamslam@gmail.com>"] -description = """ -A simple crate for determining whether two file paths point to the same file. -""" -documentation = "https://docs.rs/same-file" -homepage = "https://github.com/BurntSushi/same-file" -repository = "https://github.com/BurntSushi/same-file" -readme = "README.md" -keywords = ["same", "file", "equal", "inode"] -license = "Unlicense/MIT" - -[target.'cfg(windows)'.dependencies] -kernel32-sys = "0.2" -winapi = "0.2" - -[dev-dependencies] -rand = "0.3" diff -Nru cargo-0.25.0/vendor/same-file-0.1.3/COPYING cargo-0.26.0/vendor/same-file-0.1.3/COPYING --- cargo-0.25.0/vendor/same-file-0.1.3/COPYING 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-0.1.3/COPYING 1970-01-01 00:00:00.000000000 +0000 @@ -1,27 +0,0 @@ -Copyright 2011, The Snappy-Rust Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of the copyright holder nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff -Nru cargo-0.25.0/vendor/same-file-0.1.3/examples/is_same_file.rs cargo-0.26.0/vendor/same-file-0.1.3/examples/is_same_file.rs --- cargo-0.25.0/vendor/same-file-0.1.3/examples/is_same_file.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-0.1.3/examples/is_same_file.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -extern crate same_file; - -use same_file::is_same_file; - -fn main() { - assert!(is_same_file("/bin/sh", "/usr/bin/sh").unwrap()); -} diff -Nru cargo-0.25.0/vendor/same-file-0.1.3/examples/is_stderr.rs cargo-0.26.0/vendor/same-file-0.1.3/examples/is_stderr.rs --- cargo-0.25.0/vendor/same-file-0.1.3/examples/is_stderr.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-0.1.3/examples/is_stderr.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -extern crate same_file; - -use std::io; -use std::process; - -use same_file::Handle; - -fn main() { - if let Err(err) = run() { - println!("{}", err); - process::exit(1); - } -} - -fn run() -> io::Result<()> { - // Run with `cargo run is_stderr 2> examples/stderr` to see - // interesting output. - let candidates = &[ - "examples/is_same_file.rs", - "examples/is_stderr.rs", - "examples/stderr", - ]; - let stderr_handle = try!(Handle::stderr()); - for candidate in candidates { - let handle = try!(Handle::from_path(candidate)); - if stderr_handle == handle { - println!("{:?} is stderr!", candidate); - } else { - println!("{:?} is NOT stderr!", candidate); - } - } - Ok(()) -} diff -Nru cargo-0.25.0/vendor/same-file-0.1.3/README.md cargo-0.26.0/vendor/same-file-0.1.3/README.md --- cargo-0.25.0/vendor/same-file-0.1.3/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-0.1.3/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -same-file -========= -A safe and simple **cross platform** crate to determine whether two files or -directories are the same. - -[![Linux build status](https://api.travis-ci.org/BurntSushi/same-file.png)](https://travis-ci.org/BurntSushi/same-file) -[![Windows build status](https://ci.appveyor.com/api/projects/status/github/BurntSushi/same-file?svg=true)](https://ci.appveyor.com/project/BurntSushi/same-file) -[![](http://meritbadge.herokuapp.com/same-file)](https://crates.io/crates/same-file) - -Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). - -### Documentation - -https://docs.rs/same-file - -### Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -same-file = "0.1" -``` - -and this to your crate root: - -```rust -extern crate same_file; -``` - -### Example - -The simplest use of this crate is to use the `is_same_file` function, which -takes two file paths and returns true if and only if they refer to the same -file: - -```rust -extern crate same_file; - -use same_file::is_same_file; - -fn main() { - assert!(is_same_file("/bin/sh", "/usr/bin/sh").unwrap()); -} -``` diff -Nru cargo-0.25.0/vendor/same-file-0.1.3/src/lib.rs cargo-0.26.0/vendor/same-file-0.1.3/src/lib.rs --- cargo-0.25.0/vendor/same-file-0.1.3/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-0.1.3/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,304 +0,0 @@ -/*! -This crate provides a safe and simple **cross platform** way to determine -whether two file paths refer to the same file or directory. - -Most uses of this crate should be limited to the top-level `is_same_file` -function, which takes two file paths and returns true if they refer to the -same file or directory: - -```rust,no_run -# fn example() -> ::std::io::Result<()> { -use same_file::is_same_file; - -assert!(try!(is_same_file("/bin/sh", "/usr/bin/sh"))); -# Ok(()) } example().unwrap(); -``` - -Additionally, this crate provides a `Handle` type that permits a more efficient -equality check depending on your access pattern. For example, if one wanted to -checked whether any path in a list of paths corresponded to the process' stdout -handle, then one could build a handle once for stdout. The equality check for -each file in the list then only requires one stat call instead of two. The code -might look like this: - -```rust,no_run -# fn example() -> ::std::io::Result<()> { -use same_file::Handle; - -let candidates = &[ - "examples/is_same_file.rs", - "examples/is_stderr.rs", - "examples/stderr", -]; -let stdout_handle = try!(Handle::stdout()); -for candidate in candidates { - let handle = try!(Handle::from_path(candidate)); - if stdout_handle == handle { - println!("{:?} is stdout!", candidate); - } else { - println!("{:?} is NOT stdout!", candidate); - } -} -# Ok(()) } example().unwrap(); -``` - -See `examples/is_stderr.rs` for a runnable example. Compare the output of -`cargo run is_stderr 2> examples/stderr` and `cargo run is_stderr`. -*/ - -#![deny(missing_docs)] - -#[cfg(windows)] -extern crate kernel32; -#[cfg(windows)] -extern crate winapi; - -use std::fs::File; -use std::io; -use std::path::Path; - -#[cfg(any(target_os = "redox", unix))] -use unix as imp; -#[cfg(windows)] -use win as imp; - -#[cfg(any(target_os = "redox", unix))] -mod unix; -#[cfg(windows)] -mod win; - -/// A handle to a file that can be tested for equality with other handles. -/// -/// If two files are the same, then any two handles of those files will compare -/// equal. If two files are not the same, then any two handles of those files -/// will compare not-equal. -/// -/// A handle consumes an open file resource as long as it exists. -/// -/// Note that it's possible for comparing two handles to produce a false -/// positive on some platforms. Namely, two handles can compare equal even if -/// the two handles *don't* point to the same file. -#[derive(Debug, Eq, PartialEq)] -pub struct Handle(imp::Handle); - -impl Handle { - /// Construct a handle from a path. - /// - /// Note that the underlying `File` is opened in read-only mode on all - /// platforms. - pub fn from_path<P: AsRef<Path>>(p: P) -> io::Result<Handle> { - imp::Handle::from_path(p).map(Handle) - } - - /// Construct a handle from a file. - pub fn from_file(file: File) -> io::Result<Handle> { - imp::Handle::from_file(file).map(Handle) - } - - /// Construct a handle from stdin. - pub fn stdin() -> io::Result<Handle> { - imp::Handle::stdin().map(Handle) - } - - /// Construct a handle from stdout. - pub fn stdout() -> io::Result<Handle> { - imp::Handle::stdout().map(Handle) - } - - /// Construct a handle from stderr. - pub fn stderr() -> io::Result<Handle> { - imp::Handle::stderr().map(Handle) - } - - /// Return a reference to the underlying file. - pub fn as_file(&self) -> &File { - self.0.as_file() - } - - /// Return a mutable reference to the underlying file. - pub fn as_file_mut(&mut self) -> &mut File { - self.0.as_file_mut() - } - - /// Return the underlying device number of this handle. - #[cfg(any(target_os = "redox", unix))] - pub fn dev(&self) -> u64 { - self.0.dev() - } - - /// Return the underlying inode number of this handle. - #[cfg(any(target_os = "redox", unix))] - pub fn ino(&self) -> u64 { - self.0.ino() - } -} - -/// Returns true if the two file paths may correspond to the same file. -/// -/// If there was a problem accessing either file path, then an error is -/// returned. -/// -/// Note that it's possible for this to produce a false positive on some -/// platforms. Namely, this can return true even if the two file paths *don't* -/// resolve to the same file. -/// -/// # Example -/// -/// ```rust,no_run -/// use same_file::is_same_file; -/// -/// assert!(is_same_file("./foo", "././foo").unwrap_or(false)); -/// ``` -pub fn is_same_file<P, Q>( - path1: P, - path2: Q, -) -> io::Result<bool> where P: AsRef<Path>, Q: AsRef<Path> { - Ok(try!(Handle::from_path(path1)) == try!(Handle::from_path(path2))) -} - -#[cfg(test)] -mod tests { - extern crate rand; - - use std::env; - use std::fs::{self, File}; - use std::io; - use std::path::{Path, PathBuf}; - - use self::rand::Rng; - - use super::is_same_file; - - struct TempDir(PathBuf); - - impl TempDir { - fn path<'a>(&'a self) -> &'a Path { - &self.0 - } - } - - impl Drop for TempDir { - fn drop(&mut self) { - fs::remove_dir_all(&self.0).unwrap(); - } - } - - fn tmpdir() -> TempDir { - let p = env::temp_dir(); - let mut r = self::rand::thread_rng(); - let ret = p.join(&format!("rust-{}", r.next_u32())); - fs::create_dir(&ret).unwrap(); - TempDir(ret) - } - - #[cfg(unix)] - pub fn soft_link_dir<P: AsRef<Path>, Q: AsRef<Path>>( - src: P, - dst: Q, - ) -> io::Result<()> { - use std::os::unix::fs::symlink; - symlink(src, dst) - } - - #[cfg(unix)] - pub fn soft_link_file<P: AsRef<Path>, Q: AsRef<Path>>( - src: P, - dst: Q, - ) -> io::Result<()> { - soft_link_dir(src, dst) - } - - #[cfg(windows)] - pub fn soft_link_dir<P: AsRef<Path>, Q: AsRef<Path>>( - src: P, - dst: Q, - ) -> io::Result<()> { - use std::os::windows::fs::symlink_dir; - symlink_dir(src, dst) - } - - #[cfg(windows)] - pub fn soft_link_file<P: AsRef<Path>, Q: AsRef<Path>>( - src: P, - dst: Q, - ) -> io::Result<()> { - use std::os::windows::fs::symlink_file; - symlink_file(src, dst) - } - - // These tests are rather uninteresting. The really interesting tests - // would stress the edge cases. On Unix, this might be comparing two files - // on different mount points with the same inode number. On Windows, this - // might be comparing two files whose file indices are the same on file - // systems where such things aren't guaranteed to be unique. - // - // Alas, I don't know how to create those environmental conditions. ---AG - - #[test] - fn same_file_trivial() { - let tdir = tmpdir(); - let dir = tdir.path(); - - File::create(dir.join("a")).unwrap(); - assert!(is_same_file(dir.join("a"), dir.join("a")).unwrap()); - } - - #[test] - fn same_dir_trivial() { - let tdir = tmpdir(); - let dir = tdir.path(); - - fs::create_dir(dir.join("a")).unwrap(); - assert!(is_same_file(dir.join("a"), dir.join("a")).unwrap()); - } - - #[test] - fn not_same_file_trivial() { - let tdir = tmpdir(); - let dir = tdir.path(); - - File::create(dir.join("a")).unwrap(); - File::create(dir.join("b")).unwrap(); - assert!(!is_same_file(dir.join("a"), dir.join("b")).unwrap()); - } - - #[test] - fn not_same_dir_trivial() { - let tdir = tmpdir(); - let dir = tdir.path(); - - fs::create_dir(dir.join("a")).unwrap(); - fs::create_dir(dir.join("b")).unwrap(); - assert!(!is_same_file(dir.join("a"), dir.join("b")).unwrap()); - } - - #[test] - fn same_file_hard() { - let tdir = tmpdir(); - let dir = tdir.path(); - - File::create(dir.join("a")).unwrap(); - fs::hard_link(dir.join("a"), dir.join("alink")).unwrap(); - assert!(is_same_file(dir.join("a"), dir.join("alink")).unwrap()); - } - - #[test] - fn same_file_soft() { - let tdir = tmpdir(); - let dir = tdir.path(); - - File::create(dir.join("a")).unwrap(); - soft_link_file(dir.join("a"), dir.join("alink")).unwrap(); - assert!(is_same_file(dir.join("a"), dir.join("alink")).unwrap()); - } - - #[test] - fn same_dir_soft() { - let tdir = tmpdir(); - let dir = tdir.path(); - - fs::create_dir(dir.join("a")).unwrap(); - soft_link_dir(dir.join("a"), dir.join("alink")).unwrap(); - assert!(is_same_file(dir.join("a"), dir.join("alink")).unwrap()); - } -} diff -Nru cargo-0.25.0/vendor/same-file-0.1.3/src/unix.rs cargo-0.26.0/vendor/same-file-0.1.3/src/unix.rs --- cargo-0.25.0/vendor/same-file-0.1.3/src/unix.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-0.1.3/src/unix.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,94 +0,0 @@ -use std::fs::{File, OpenOptions}; -use std::io; -use std::os::unix::fs::MetadataExt; -use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; -use std::path::Path; - -#[derive(Debug)] -pub struct Handle { - file: Option<File>, - // If is_std is true, then we don't drop the corresponding File since it - // will close the handle. - is_std: bool, - dev: u64, - ino: u64, -} - -impl Drop for Handle { - fn drop(&mut self) { - if self.is_std { - self.file.take().unwrap().into_raw_fd(); - } - } -} - -impl Eq for Handle {} - -impl PartialEq for Handle { - fn eq(&self, other: &Handle) -> bool { - (self.dev, self.ino) == (other.dev, other.ino) - } -} - -impl AsRawFd for ::Handle { - fn as_raw_fd(&self) -> RawFd { - self.0.file.as_ref().take().unwrap().as_raw_fd() - } -} - -impl IntoRawFd for ::Handle { - fn into_raw_fd(mut self) -> RawFd { - self.0.file.take().unwrap().into_raw_fd() - } -} - -impl Handle { - pub fn from_path<P: AsRef<Path>>(p: P) -> io::Result<Handle> { - Handle::from_file(try!(OpenOptions::new().read(true).open(p))) - } - - pub fn from_file(file: File) -> io::Result<Handle> { - let md = try!(file.metadata()); - Ok(Handle { - file: Some(file), - is_std: false, - dev: md.dev(), - ino: md.ino(), - }) - } - - pub fn from_std(file: File) -> io::Result<Handle> { - Handle::from_file(file).map(|mut h| { - h.is_std = true; - h - }) - } - - pub fn stdin() -> io::Result<Handle> { - Handle::from_std(unsafe { File::from_raw_fd(0) }) - } - - pub fn stdout() -> io::Result<Handle> { - Handle::from_std(unsafe { File::from_raw_fd(1) }) - } - - pub fn stderr() -> io::Result<Handle> { - Handle::from_std(unsafe { File::from_raw_fd(2) }) - } - - pub fn as_file(&self) -> &File { - self.file.as_ref().take().unwrap() - } - - pub fn as_file_mut(&mut self) -> &mut File { - self.file.as_mut().take().unwrap() - } - - pub fn dev(&self) -> u64 { - self.dev - } - - pub fn ino(&self) -> u64 { - self.ino - } -} diff -Nru cargo-0.25.0/vendor/same-file-0.1.3/src/win.rs cargo-0.26.0/vendor/same-file-0.1.3/src/win.rs --- cargo-0.25.0/vendor/same-file-0.1.3/src/win.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-0.1.3/src/win.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,185 +0,0 @@ -use std::fs::{File, OpenOptions}; -use std::io; -use std::mem; -use std::os::windows::fs::OpenOptionsExt; -use std::os::windows::io::{ - AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle, -}; -use std::path::Path; - -use kernel32::{GetFileInformationByHandle, GetStdHandle}; -use winapi::fileapi::BY_HANDLE_FILE_INFORMATION; -use winapi::minwindef::DWORD; -use winapi::winbase::{ - FILE_FLAG_BACKUP_SEMANTICS, - STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE, -}; - -// For correctness, it is critical that both file handles remain open while -// their attributes are checked for equality. In particular, the file index -// numbers on a Windows stat object are not guaranteed to remain stable over -// time. -// -// See the docs and remarks on MSDN: -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363788(v=vs.85).aspx -// -// It gets worse. It appears that the index numbers are not always -// guaranteed to be unqiue. Namely, ReFS uses 128 bit numbers for unique -// identifiers. This requires a distinct syscall to get `FILE_ID_INFO` -// documented here: -// https://msdn.microsoft.com/en-us/library/windows/desktop/hh802691(v=vs.85).aspx -// -// It seems straight-forward enough to modify this code to use -// `FILE_ID_INFO` when available (minimum Windows Server 2012), but I don't -// have access to such Windows machines. -// -// Two notes. -// -// 1. Java's NIO uses the approach implemented here and appears to ignore -// `FILE_ID_INFO` altogether. So Java's NIO and this code are -// susceptible to bugs when running on a file system where -// `nFileIndex{Low,High}` are not unique. -// -// 2. LLVM has a bug where they fetch the id of a file and continue to use -// it even after the handle has been closed, so that uniqueness is no -// longer guaranteed (when `nFileIndex{Low,High}` are unique). -// bug report: http://lists.llvm.org/pipermail/llvm-bugs/2014-December/037218.html -// -// All said and done, checking whether two files are the same on Windows -// seems quite tricky. Moreover, even if the code is technically incorrect, -// it seems like the chances of actually observing incorrect behavior are -// extremely small. Nevertheless, we mitigate this by checking size too. -// -// In the case where this code is erroneous, two files will be reported -// as equivalent when they are in fact distinct. This will cause the loop -// detection code to report a false positive, which will prevent descending -// into the offending directory. As far as failure modes goes, this isn't -// that bad. - -#[derive(Debug)] -pub struct Handle { - file: Option<File>, - // If is_std is true, then we don't drop the corresponding File since it - // will close the handle. - is_std: bool, - key: Option<Key>, -} - -#[derive(Debug, Eq, PartialEq)] -struct Key { - volume: DWORD, - idx_high: DWORD, - idx_low: DWORD, -} - -impl Drop for Handle { - fn drop(&mut self) { - if self.is_std { - self.file.take().unwrap().into_raw_handle(); - } - } -} - -impl Eq for Handle {} - -impl PartialEq for Handle { - fn eq(&self, other: &Handle) -> bool { - if self.key.is_none() || other.key.is_none() { - return false; - } - self.key == other.key - } -} - -impl AsRawHandle for ::Handle { - fn as_raw_handle(&self) -> RawHandle { - self.0.file.as_ref().take().unwrap().as_raw_handle() - } -} - -impl IntoRawHandle for ::Handle { - fn into_raw_handle(mut self) -> RawHandle { - self.0.file.take().unwrap().into_raw_handle() - } -} - -impl Handle { - pub fn from_path<P: AsRef<Path>>(p: P) -> io::Result<Handle> { - let file = try!(OpenOptions::new() - .read(true) - // Necessary in order to support opening directory paths. - .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) - .open(p)); - Handle::from_file(file) - } - - pub fn from_file(file: File) -> io::Result<Handle> { - file_info(&file).map(|info| Handle::from_file_info(file, false, info)) - } - - fn from_std_handle(file: File) -> io::Result<Handle> { - match file_info(&file) { - Ok(info) => Ok(Handle::from_file_info(file, true, info)), - // In a Windows console, if there is no pipe attached to a STD - // handle, then GetFileInformationByHandle will return an error. - // We don't really care. The only thing we care about is that - // this handle is never equivalent to any other handle, which is - // accomplished by setting key to None. - Err(_) => Ok(Handle { file: Some(file), is_std: true, key: None }), - } - } - - fn from_file_info( - file: File, - is_std: bool, - info: BY_HANDLE_FILE_INFORMATION, - ) -> Handle { - Handle { - file: Some(file), - is_std: is_std, - key: Some(Key { - volume: info.dwVolumeSerialNumber, - idx_high: info.nFileIndexHigh, - idx_low: info.nFileIndexLow, - }), - } - } - - pub fn stdin() -> io::Result<Handle> { - Handle::from_std_handle(unsafe { - File::from_raw_handle(GetStdHandle(STD_INPUT_HANDLE)) - }) - } - - pub fn stdout() -> io::Result<Handle> { - Handle::from_std_handle(unsafe { - File::from_raw_handle(GetStdHandle(STD_OUTPUT_HANDLE)) - }) - } - - pub fn stderr() -> io::Result<Handle> { - Handle::from_std_handle(unsafe { - File::from_raw_handle(GetStdHandle(STD_ERROR_HANDLE)) - }) - } - - pub fn as_file(&self) -> &File { - self.file.as_ref().take().unwrap() - } - - pub fn as_file_mut(&mut self) -> &mut File { - self.file.as_mut().take().unwrap() - } -} - -fn file_info(file: &File) -> io::Result<BY_HANDLE_FILE_INFORMATION> { - let (r, info) = unsafe { - let mut info: BY_HANDLE_FILE_INFORMATION = mem::zeroed(); - (GetFileInformationByHandle(file.as_raw_handle(), &mut info), info) - }; - if r == 0 { - Err(io::Error::last_os_error()) - } else { - Ok(info) - } -} diff -Nru cargo-0.25.0/vendor/same-file-0.1.3/.travis.yml cargo-0.26.0/vendor/same-file-0.1.3/.travis.yml --- cargo-0.25.0/vendor/same-file-0.1.3/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-0.1.3/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -language: rust -rust: - - 1.10.0 - - stable - - beta - - nightly -script: - - cargo build --verbose - - cargo test --verbose - - cargo doc - - if [ "$TRAVIS_RUST_VERSION" = "nightly" ]; then - cargo bench --verbose; - fi -branches: - only: - - master diff -Nru cargo-0.25.0/vendor/same-file-1.0.2/appveyor.yml cargo-0.26.0/vendor/same-file-1.0.2/appveyor.yml --- cargo-0.25.0/vendor/same-file-1.0.2/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-1.0.2/appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,22 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo build --verbose + - cargo test --verbose + +branches: + only: + - master diff -Nru cargo-0.25.0/vendor/same-file-1.0.2/.cargo-checksum.json cargo-0.26.0/vendor/same-file-1.0.2/.cargo-checksum.json --- cargo-0.25.0/vendor/same-file-1.0.2/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-1.0.2/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"cfb6eded0b06a0b512c8ddbcf04089138c9b4362c2f696f3c3d76039d68f3637"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/same-file-1.0.2/Cargo.toml cargo-0.26.0/vendor/same-file-1.0.2/Cargo.toml --- cargo-0.25.0/vendor/same-file-1.0.2/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-1.0.2/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "same-file" +version = "1.0.2" +authors = ["Andrew Gallant <jamslam@gmail.com>"] +description = "A simple crate for determining whether two file paths point to the same file.\n" +homepage = "https://github.com/BurntSushi/same-file" +documentation = "https://docs.rs/same-file" +readme = "README.md" +keywords = ["same", "file", "equal", "inode"] +license = "Unlicense/MIT" +repository = "https://github.com/BurntSushi/same-file" +[dev-dependencies.rand] +version = "0.4" +[target."cfg(windows)".dependencies.winapi] +version = "0.3" +features = ["std", "fileapi", "minwindef", "processenv", "winbase"] diff -Nru cargo-0.25.0/vendor/same-file-1.0.2/COPYING cargo-0.26.0/vendor/same-file-1.0.2/COPYING --- cargo-0.25.0/vendor/same-file-1.0.2/COPYING 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-1.0.2/COPYING 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,27 @@ +Copyright 2011, The Snappy-Rust Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of the copyright holder nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff -Nru cargo-0.25.0/vendor/same-file-1.0.2/examples/is_same_file.rs cargo-0.26.0/vendor/same-file-1.0.2/examples/is_same_file.rs --- cargo-0.25.0/vendor/same-file-1.0.2/examples/is_same_file.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-1.0.2/examples/is_same_file.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,13 @@ +extern crate same_file; + +use std::error::Error; +use same_file::is_same_file; + +fn try_main() -> Result<(), Box<Error>> { + assert!(is_same_file("/bin/sh", "/usr/bin/sh")?); + Ok(()) +} + +fn main() { + try_main().unwrap(); +} diff -Nru cargo-0.25.0/vendor/same-file-1.0.2/examples/is_stderr.rs cargo-0.26.0/vendor/same-file-1.0.2/examples/is_stderr.rs --- cargo-0.25.0/vendor/same-file-1.0.2/examples/is_stderr.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-1.0.2/examples/is_stderr.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,33 @@ +extern crate same_file; + +use std::io; +use std::process; + +use same_file::Handle; + +fn main() { + if let Err(err) = run() { + println!("{}", err); + process::exit(1); + } +} + +fn run() -> io::Result<()> { + // Run with `cargo run is_stderr 2> examples/stderr` to see + // interesting output. + let candidates = &[ + "examples/is_same_file.rs", + "examples/is_stderr.rs", + "examples/stderr", + ]; + let stderr_handle = Handle::stderr()?; + for candidate in candidates { + let handle = Handle::from_path(candidate)?; + if stderr_handle == handle { + println!("{:?} is stderr!", candidate); + } else { + println!("{:?} is NOT stderr!", candidate); + } + } + Ok(()) +} diff -Nru cargo-0.25.0/vendor/same-file-1.0.2/README.md cargo-0.26.0/vendor/same-file-1.0.2/README.md --- cargo-0.25.0/vendor/same-file-1.0.2/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-1.0.2/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,45 @@ +same-file +========= +A safe and simple **cross platform** crate to determine whether two files or +directories are the same. + +[![Linux build status](https://api.travis-ci.org/BurntSushi/same-file.png)](https://travis-ci.org/BurntSushi/same-file) +[![Windows build status](https://ci.appveyor.com/api/projects/status/github/BurntSushi/same-file?svg=true)](https://ci.appveyor.com/project/BurntSushi/same-file) +[![](http://meritbadge.herokuapp.com/same-file)](https://crates.io/crates/same-file) + +Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). + +### Documentation + +https://docs.rs/same-file + +### Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +same-file = "1" +``` + +and this to your crate root: + +```rust +extern crate same_file; +``` + +### Example + +The simplest use of this crate is to use the `is_same_file` function, which +takes two file paths and returns true if and only if they refer to the same +file: + +```rust +extern crate same_file; + +use same_file::is_same_file; + +fn main() { + assert!(is_same_file("/bin/sh", "/usr/bin/sh").unwrap()); +} +``` diff -Nru cargo-0.25.0/vendor/same-file-1.0.2/src/lib.rs cargo-0.26.0/vendor/same-file-1.0.2/src/lib.rs --- cargo-0.25.0/vendor/same-file-1.0.2/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-1.0.2/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,530 @@ +/*! +This crate provides a safe and simple **cross platform** way to determine +whether two file paths refer to the same file or directory. + +Most uses of this crate should be limited to the top-level [`is_same_file`] +function, which takes two file paths and returns true if they refer to the +same file or directory: + +```rust,no_run +# use std::error::Error; +use same_file::is_same_file; + +# fn try_main() -> Result<(), Box<Error>> { +assert!(is_same_file("/bin/sh", "/usr/bin/sh")?); +# Ok(()) +# } +# +# fn main() { +# try_main().unwrap(); +# } +``` + +Additionally, this crate provides a [`Handle`] type that permits a more efficient +equality check depending on your access pattern. For example, if one wanted to +check whether any path in a list of paths corresponded to the process' stdout +handle, then one could build a handle once for stdout. The equality check for +each file in the list then only requires one stat call instead of two. The code +might look like this: + +```rust,no_run +# use std::error::Error; +use same_file::Handle; + +# fn try_main() -> Result<(), Box<Error>> { +let candidates = &[ + "examples/is_same_file.rs", + "examples/is_stderr.rs", + "examples/stderr", +]; +let stdout_handle = Handle::stdout()?; +for candidate in candidates { + let handle = Handle::from_path(candidate)?; + if stdout_handle == handle { + println!("{:?} is stdout!", candidate); + } else { + println!("{:?} is NOT stdout!", candidate); + } +} +# Ok(()) +# } +# +# fn main() { +# try_main().unwrap(); +# } +``` + +See [`examples/is_stderr.rs`] for a runnable example and compare the output of: + +- `cargo run is_stderr 2> examples/stderr` and +- `cargo run is_stderr`. + +[`is_same_file`]: fn.is_same_file.html +[`Handle`]: struct.Handle.html +[`examples/is_stderr.rs`]: https://github.com/BurntSushi/same-file/blob/master/examples/is_same_file.rs + +*/ + +#![doc(html_root_url = "https://docs.rs/same-file/1.0.0")] +#![deny(missing_docs)] + +#[cfg(windows)] +extern crate winapi; + +use std::fs::File; +use std::io; +use std::path::Path; + +#[cfg(any(target_os = "redox", unix))] +use unix as imp; +#[cfg(windows)] +use win as imp; + +#[cfg(any(target_os = "redox", unix))] +mod unix; +#[cfg(windows)] +mod win; + +/// A handle to a file that can be tested for equality with other handles. +/// +/// If two files are the same, then any two handles of those files will compare +/// equal. If two files are not the same, then any two handles of those files +/// will compare not-equal. +/// +/// A handle consumes an open file resource as long as it exists. +/// +/// Equality is determined by comparing inode numbers on Unix and a combination +/// of identifier, volume serial, and file size on Windows. Note that it's +/// possible for comparing two handles to produce a false positive on some +/// platforms. Namely, two handles can compare equal even if the two handles +/// *don't* point to the same file. Check the [source] for specific +/// implementation details. +/// +/// [source]: https://github.com/BurntSushi/same-file/tree/master/src +#[derive(Debug, Eq, PartialEq)] +pub struct Handle(imp::Handle); + +impl Handle { + /// Construct a handle from a path. + /// + /// Note that the underlying [`File`] is opened in read-only mode on all + /// platforms. + /// + /// [`File`]: https://doc.rust-lang.org/std/fs/struct.File.html + /// + /// # Errors + /// This method will return an [`io::Error`] if the path cannot + /// be opened, or the file's metadata cannot be obtained. + /// The most common reasons for this are: the path does not + /// exist, or there were not enough permissions. + /// + /// [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html + /// + /// # Examples + /// Check that two paths are not the same file: + /// + /// ```rust,no_run + /// # use std::error::Error; + /// use same_file::Handle; + /// + /// # fn try_main() -> Result<(), Box<Error>> { + /// let source = Handle::from_path("./source")?; + /// let target = Handle::from_path("./target")?; + /// assert_ne!(source, target, "The files are the same."); + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn from_path<P: AsRef<Path>>(p: P) -> io::Result<Handle> { + imp::Handle::from_path(p).map(Handle) + } + + /// Construct a handle from a file. + /// + /// # Errors + /// This method will return an [`io::Error`] if the metadata for + /// the given [`File`] cannot be obtained. + /// + /// [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html + /// [`File`]: https://doc.rust-lang.org/std/fs/struct.File.html + /// + /// # Examples + /// Check that two files are not in fact the same file: + /// + /// ```rust,no_run + /// # use std::error::Error; + /// # use std::fs::File; + /// use same_file::Handle; + /// + /// # fn try_main() -> Result<(), Box<Error>> { + /// let source = File::open("./source")?; + /// let target = File::open("./target")?; + /// + /// assert_ne!( + /// Handle::from_file(source)?, + /// Handle::from_file(target)?, + /// "The files are the same." + /// ); + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn from_file(file: File) -> io::Result<Handle> { + imp::Handle::from_file(file).map(Handle) + } + + /// Construct a handle from stdin. + /// + /// # Errors + /// This method will return an [`io::Error`] if stdin cannot + /// be opened due to any I/O-related reason. + /// + /// [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html + /// + /// # Examples + /// + /// ```rust + /// # use std::error::Error; + /// use same_file::Handle; + /// + /// # fn try_main() -> Result<(), Box<Error>> { + /// let stdin = Handle::stdin()?; + /// let stdout = Handle::stdout()?; + /// let stderr = Handle::stderr()?; + /// + /// if stdin == stdout { + /// println!("stdin == stdout"); + /// } + /// if stdin == stderr { + /// println!("stdin == stderr"); + /// } + /// if stdout == stderr { + /// println!("stdout == stderr"); + /// } + /// # + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + /// + /// The output differs depending on the platform. + /// + /// On Linux: + /// + /// ```text + /// $ ./example + /// stdin == stdout + /// stdin == stderr + /// stdout == stderr + /// $ ./example > result + /// $ cat result + /// stdin == stderr + /// $ ./example > result 2>&1 + /// $ cat result + /// stdout == stderr + /// ``` + /// + /// Windows: + /// + /// ```text + /// > example + /// > example > result 2>&1 + /// > type result + /// stdout == stderr + /// ``` + pub fn stdin() -> io::Result<Handle> { + imp::Handle::stdin().map(Handle) + } + + /// Construct a handle from stdout. + /// + /// # Errors + /// This method will return an [`io::Error`] if stdout cannot + /// be opened due to any I/O-related reason. + /// + /// [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html + /// + /// # Examples + /// See the example for [`stdin()`]. + /// + /// [`stdin()`]: #method.stdin + pub fn stdout() -> io::Result<Handle> { + imp::Handle::stdout().map(Handle) + } + + /// Construct a handle from stderr. + /// + /// # Errors + /// This method will return an [`io::Error`] if stderr cannot + /// be opened due to any I/O-related reason. + /// + /// [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html + /// + /// # Examples + /// See the example for [`stdin()`]. + /// + /// [`stdin()`]: #method.stdin + pub fn stderr() -> io::Result<Handle> { + imp::Handle::stderr().map(Handle) + } + + /// Return a reference to the underlying file. + /// + /// # Examples + /// Ensure that the target file is not the same as the source one, + /// and copy the data to it: + /// + /// ```rust,no_run + /// # use std::error::Error; + /// use std::io::prelude::*; + /// use std::io::Write; + /// use std::fs::File; + /// use same_file::Handle; + /// + /// # fn try_main() -> Result<(), Box<Error>> { + /// let source = File::open("source")?; + /// let target = File::create("target")?; + /// + /// let source_handle = Handle::from_file(source)?; + /// let mut target_handle = Handle::from_file(target)?; + /// assert_ne!(source_handle, target_handle, "The files are the same."); + /// + /// let mut source = source_handle.as_file(); + /// let target = target_handle.as_file_mut(); + /// + /// let mut buffer = Vec::new(); + /// // data copy is simplified for the purposes of the example + /// source.read_to_end(&mut buffer)?; + /// target.write_all(&buffer)?; + /// # + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # try_main().unwrap(); + /// # } + /// ``` + pub fn as_file(&self) -> &File { + self.0.as_file() + } + + /// Return a mutable reference to the underlying file. + /// + /// # Examples + /// See the example for [`as_file()`]. + /// + /// [`as_file()`]: #method.as_file + pub fn as_file_mut(&mut self) -> &mut File { + self.0.as_file_mut() + } + + /// Return the underlying device number of this handle. + /// + /// Note that this only works on unix platforms. + #[cfg(any(target_os = "redox", unix))] + pub fn dev(&self) -> u64 { + self.0.dev() + } + + /// Return the underlying inode number of this handle. + /// + /// Note that this only works on unix platforms. + #[cfg(any(target_os = "redox", unix))] + pub fn ino(&self) -> u64 { + self.0.ino() + } +} + +/// Returns true if the two file paths may correspond to the same file. +/// +/// Note that it's possible for this to produce a false positive on some +/// platforms. Namely, this can return true even if the two file paths *don't* +/// resolve to the same file. +/// # Errors +/// This function will return an [`io::Error`] if any of the two paths cannot +/// be opened. The most common reasons for this are: the path does not exist, +/// or there were not enough permissions. +/// +/// [`io::Error`]: https://doc.rust-lang.org/std/io/struct.Error.html +/// +/// # Example +/// +/// ```rust,no_run +/// use same_file::is_same_file; +/// +/// assert!(is_same_file("./foo", "././foo").unwrap_or(false)); +/// ``` +pub fn is_same_file<P, Q>( + path1: P, + path2: Q, +) -> io::Result<bool> where P: AsRef<Path>, Q: AsRef<Path> { + Ok(Handle::from_path(path1)? == Handle::from_path(path2)?) +} + +#[cfg(test)] +mod tests { + extern crate rand; + + use std::env; + use std::fs::{self, File}; + use std::io; + use std::path::{Path, PathBuf}; + + use self::rand::Rng; + + use super::is_same_file; + + struct TempDir(PathBuf); + + impl TempDir { + fn path<'a>(&'a self) -> &'a Path { + &self.0 + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } + } + + fn tmpdir() -> TempDir { + let p = env::temp_dir(); + let mut r = self::rand::thread_rng(); + let ret = p.join(&format!("rust-{}", r.next_u32())); + fs::create_dir(&ret).unwrap(); + TempDir(ret) + } + + #[cfg(unix)] + pub fn soft_link_dir<P: AsRef<Path>, Q: AsRef<Path>>( + src: P, + dst: Q, + ) -> io::Result<()> { + use std::os::unix::fs::symlink; + symlink(src, dst) + } + + #[cfg(unix)] + pub fn soft_link_file<P: AsRef<Path>, Q: AsRef<Path>>( + src: P, + dst: Q, + ) -> io::Result<()> { + soft_link_dir(src, dst) + } + + #[cfg(windows)] + pub fn soft_link_dir<P: AsRef<Path>, Q: AsRef<Path>>( + src: P, + dst: Q, + ) -> io::Result<()> { + use std::os::windows::fs::symlink_dir; + symlink_dir(src, dst) + } + + #[cfg(windows)] + pub fn soft_link_file<P: AsRef<Path>, Q: AsRef<Path>>( + src: P, + dst: Q, + ) -> io::Result<()> { + use std::os::windows::fs::symlink_file; + symlink_file(src, dst) + } + + // These tests are rather uninteresting. The really interesting tests + // would stress the edge cases. On Unix, this might be comparing two files + // on different mount points with the same inode number. On Windows, this + // might be comparing two files whose file indices are the same on file + // systems where such things aren't guaranteed to be unique. + // + // Alas, I don't know how to create those environmental conditions. ---AG + + #[test] + fn same_file_trivial() { + let tdir = tmpdir(); + let dir = tdir.path(); + + File::create(dir.join("a")).unwrap(); + assert!(is_same_file(dir.join("a"), dir.join("a")).unwrap()); + } + + #[test] + fn same_dir_trivial() { + let tdir = tmpdir(); + let dir = tdir.path(); + + fs::create_dir(dir.join("a")).unwrap(); + assert!(is_same_file(dir.join("a"), dir.join("a")).unwrap()); + } + + #[test] + fn not_same_file_trivial() { + let tdir = tmpdir(); + let dir = tdir.path(); + + File::create(dir.join("a")).unwrap(); + File::create(dir.join("b")).unwrap(); + assert!(!is_same_file(dir.join("a"), dir.join("b")).unwrap()); + } + + #[test] + fn not_same_dir_trivial() { + let tdir = tmpdir(); + let dir = tdir.path(); + + fs::create_dir(dir.join("a")).unwrap(); + fs::create_dir(dir.join("b")).unwrap(); + assert!(!is_same_file(dir.join("a"), dir.join("b")).unwrap()); + } + + #[test] + fn same_file_hard() { + let tdir = tmpdir(); + let dir = tdir.path(); + + File::create(dir.join("a")).unwrap(); + fs::hard_link(dir.join("a"), dir.join("alink")).unwrap(); + assert!(is_same_file(dir.join("a"), dir.join("alink")).unwrap()); + } + + #[test] + fn same_file_soft() { + let tdir = tmpdir(); + let dir = tdir.path(); + + File::create(dir.join("a")).unwrap(); + soft_link_file(dir.join("a"), dir.join("alink")).unwrap(); + assert!(is_same_file(dir.join("a"), dir.join("alink")).unwrap()); + } + + #[test] + fn same_dir_soft() { + let tdir = tmpdir(); + let dir = tdir.path(); + + fs::create_dir(dir.join("a")).unwrap(); + soft_link_dir(dir.join("a"), dir.join("alink")).unwrap(); + assert!(is_same_file(dir.join("a"), dir.join("alink")).unwrap()); + } + + #[test] + fn test_send() { + fn assert_send<T: Send>() {} + assert_send::<super::Handle>(); + } + + #[test] + fn test_sync() { + fn assert_sync<T: Sync>() {} + assert_sync::<super::Handle>(); + } +} diff -Nru cargo-0.25.0/vendor/same-file-1.0.2/src/unix.rs cargo-0.26.0/vendor/same-file-1.0.2/src/unix.rs --- cargo-0.25.0/vendor/same-file-1.0.2/src/unix.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-1.0.2/src/unix.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,112 @@ +use std::fs::{File, OpenOptions}; +use std::hash::{Hash, Hasher}; +use std::io; +use std::os::unix::fs::MetadataExt; +use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; +use std::path::Path; + +#[derive(Debug)] +pub struct Handle { + file: Option<File>, + // If is_std is true, then we don't drop the corresponding File since it + // will close the handle. + is_std: bool, + dev: u64, + ino: u64, +} + +impl Drop for Handle { + fn drop(&mut self) { + if self.is_std { + // unwrap() will not panic. Since we were able to open an + // std stream successfully, then `file` is guaranteed to be Some() + self.file.take().unwrap().into_raw_fd(); + } + } +} + +impl Eq for Handle {} + +impl PartialEq for Handle { + fn eq(&self, other: &Handle) -> bool { + (self.dev, self.ino) == (other.dev, other.ino) + } +} + +impl AsRawFd for ::Handle { + fn as_raw_fd(&self) -> RawFd { + // unwrap() will not panic. Since we were able to open the + // file successfully, then `file` is guaranteed to be Some() + self.0.file.as_ref().take().unwrap().as_raw_fd() + } +} + +impl IntoRawFd for ::Handle { + fn into_raw_fd(mut self) -> RawFd { + // unwrap() will not panic. Since we were able to open the + // file successfully, then `file` is guaranteed to be Some() + self.0.file.take().unwrap().into_raw_fd() + } +} + +impl Hash for Handle { + fn hash<H: Hasher>(&self, state: &mut H) { + self.dev.hash(state); + self.ino.hash(state); + } +} + +impl Handle { + pub fn from_path<P: AsRef<Path>>(p: P) -> io::Result<Handle> { + Handle::from_file(OpenOptions::new().read(true).open(p)?) + } + + pub fn from_file(file: File) -> io::Result<Handle> { + let md = file.metadata()?; + Ok(Handle { + file: Some(file), + is_std: false, + dev: md.dev(), + ino: md.ino(), + }) + } + + pub fn from_std(file: File) -> io::Result<Handle> { + Handle::from_file(file).map(|mut h| { + h.is_std = true; + h + }) + } + + pub fn stdin() -> io::Result<Handle> { + Handle::from_std(unsafe { File::from_raw_fd(0) }) + } + + pub fn stdout() -> io::Result<Handle> { + Handle::from_std(unsafe { File::from_raw_fd(1) }) + } + + pub fn stderr() -> io::Result<Handle> { + Handle::from_std(unsafe { File::from_raw_fd(2) }) + } + + pub fn as_file(&self) -> &File { + // unwrap() will not panic. Since we were able to open the + // file successfully, then `file` is guaranteed to be Some() + self.file.as_ref().take().unwrap() + } + + pub fn as_file_mut(&mut self) -> &mut File { + // unwrap() will not panic. Since we were able to open the + // file successfully, then `file` is guaranteed to be Some() + self.file.as_mut().take().unwrap() + } + + pub fn dev(&self) -> u64 { + self.dev + } + + pub fn ino(&self) -> u64 { + self.ino + } +} diff -Nru cargo-0.25.0/vendor/same-file-1.0.2/src/win.rs cargo-0.26.0/vendor/same-file-1.0.2/src/win.rs --- cargo-0.25.0/vendor/same-file-1.0.2/src/win.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-1.0.2/src/win.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,209 @@ +use std::fs::{File, OpenOptions}; +use std::hash::{Hash, Hasher}; +use std::io; +use std::mem; +use std::os::windows::fs::OpenOptionsExt; +use std::os::windows::io::{ + AsRawHandle, FromRawHandle, IntoRawHandle, RawHandle, +}; +use std::path::Path; + +use winapi::shared::minwindef::DWORD; +use winapi::um::fileapi::{ + BY_HANDLE_FILE_INFORMATION, + GetFileInformationByHandle, +}; +use winapi::um::processenv::GetStdHandle; +use winapi::um::winbase::{ + FILE_FLAG_BACKUP_SEMANTICS, + STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE, +}; + +// For correctness, it is critical that both file handles remain open while +// their attributes are checked for equality. In particular, the file index +// numbers on a Windows stat object are not guaranteed to remain stable over +// time. +// +// See the docs and remarks on MSDN: +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363788(v=vs.85).aspx +// +// It gets worse. It appears that the index numbers are not always +// guaranteed to be unique. Namely, ReFS uses 128 bit numbers for unique +// identifiers. This requires a distinct syscall to get `FILE_ID_INFO` +// documented here: +// https://msdn.microsoft.com/en-us/library/windows/desktop/hh802691(v=vs.85).aspx +// +// It seems straight-forward enough to modify this code to use +// `FILE_ID_INFO` when available (minimum Windows Server 2012), but I don't +// have access to such Windows machines. +// +// Two notes. +// +// 1. Java's NIO uses the approach implemented here and appears to ignore +// `FILE_ID_INFO` altogether. So Java's NIO and this code are +// susceptible to bugs when running on a file system where +// `nFileIndex{Low,High}` are not unique. +// +// 2. LLVM has a bug where they fetch the id of a file and continue to use +// it even after the handle has been closed, so that uniqueness is no +// longer guaranteed (when `nFileIndex{Low,High}` are unique). +// bug report: http://lists.llvm.org/pipermail/llvm-bugs/2014-December/037218.html +// +// All said and done, checking whether two files are the same on Windows +// seems quite tricky. Moreover, even if the code is technically incorrect, +// it seems like the chances of actually observing incorrect behavior are +// extremely small. Nevertheless, we mitigate this by checking size too. +// +// In the case where this code is erroneous, two files will be reported +// as equivalent when they are in fact distinct. This will cause the loop +// detection code to report a false positive, which will prevent descending +// into the offending directory. As far as failure modes goes, this isn't +// that bad. + +#[derive(Debug)] +pub struct Handle { + file: Option<File>, + // If is_std is true, then we don't drop the corresponding File since it + // will close the handle. + is_std: bool, + key: Option<Key>, +} + +#[derive(Debug, Eq, PartialEq, Hash)] +struct Key { + volume: DWORD, + idx_high: DWORD, + idx_low: DWORD, +} + +impl Drop for Handle { + fn drop(&mut self) { + if self.is_std { + // unwrap() will not panic. Since we were able to open an + // std stream successfully, then `file` is guaranteed to be Some() + self.file.take().unwrap().into_raw_handle(); + } + } +} + +impl Eq for Handle {} + +impl PartialEq for Handle { + fn eq(&self, other: &Handle) -> bool { + // Need this branch to satisfy `Eq` since `Handle`s with `key.is_none()` + // wouldn't otherwise. + if self as *const Handle == other as *const Handle { + return true; + } else if self.key.is_none() || other.key.is_none() { + return false; + } + self.key == other.key + } +} + +impl AsRawHandle for ::Handle { + fn as_raw_handle(&self) -> RawHandle { + // unwrap() will not panic. Since we were able to open the + // file successfully, then `file` is guaranteed to be Some() + self.0.file.as_ref().take().unwrap().as_raw_handle() + } +} + +impl IntoRawHandle for ::Handle { + fn into_raw_handle(mut self) -> RawHandle { + // unwrap() will not panic. Since we were able to open the + // file successfully, then `file` is guaranteed to be Some() + self.0.file.take().unwrap().into_raw_handle() + } +} + +impl Hash for Handle { + fn hash<H: Hasher>(&self, state: &mut H) { + self.key.hash(state); + } +} + +impl Handle { + pub fn from_path<P: AsRef<Path>>(p: P) -> io::Result<Handle> { + let file = OpenOptions::new() + .read(true) + // Necessary in order to support opening directory paths. + .custom_flags(FILE_FLAG_BACKUP_SEMANTICS) + .open(p)?; + Handle::from_file(file) + } + + pub fn from_file(file: File) -> io::Result<Handle> { + file_info(&file).map(|info| Handle::from_file_info(file, false, info)) + } + + fn from_std_handle(file: File) -> io::Result<Handle> { + match file_info(&file) { + Ok(info) => Ok(Handle::from_file_info(file, true, info)), + // In a Windows console, if there is no pipe attached to a STD + // handle, then GetFileInformationByHandle will return an error. + // We don't really care. The only thing we care about is that + // this handle is never equivalent to any other handle, which is + // accomplished by setting key to None. + Err(_) => Ok(Handle { file: Some(file), is_std: true, key: None }), + } + } + + fn from_file_info( + file: File, + is_std: bool, + info: BY_HANDLE_FILE_INFORMATION, + ) -> Handle { + Handle { + file: Some(file), + is_std: is_std, + key: Some(Key { + volume: info.dwVolumeSerialNumber, + idx_high: info.nFileIndexHigh, + idx_low: info.nFileIndexLow, + }), + } + } + + pub fn stdin() -> io::Result<Handle> { + Handle::from_std_handle(unsafe { + File::from_raw_handle(GetStdHandle(STD_INPUT_HANDLE)) + }) + } + + pub fn stdout() -> io::Result<Handle> { + Handle::from_std_handle(unsafe { + File::from_raw_handle(GetStdHandle(STD_OUTPUT_HANDLE)) + }) + } + + pub fn stderr() -> io::Result<Handle> { + Handle::from_std_handle(unsafe { + File::from_raw_handle(GetStdHandle(STD_ERROR_HANDLE)) + }) + } + + pub fn as_file(&self) -> &File { + // unwrap() will not panic. Since we were able to open the + // file successfully, then `file` is guaranteed to be Some() + self.file.as_ref().take().unwrap() + } + + pub fn as_file_mut(&mut self) -> &mut File { + // unwrap() will not panic. Since we were able to open the + // file successfully, then `file` is guaranteed to be Some() + self.file.as_mut().take().unwrap() + } +} + +fn file_info(file: &File) -> io::Result<BY_HANDLE_FILE_INFORMATION> { + let (r, info) = unsafe { + let mut info: BY_HANDLE_FILE_INFORMATION = mem::zeroed(); + (GetFileInformationByHandle(file.as_raw_handle(), &mut info), info) + }; + if r == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(info) + } +} diff -Nru cargo-0.25.0/vendor/same-file-1.0.2/.travis.yml cargo-0.26.0/vendor/same-file-1.0.2/.travis.yml --- cargo-0.25.0/vendor/same-file-1.0.2/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/same-file-1.0.2/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,24 @@ +dist: trusty +language: rust +matrix: + include: + - os: linux + rust: 1.17.0 + - os: linux + rust: stable + - os: linux + rust: beta + - os: linux + rust: nightly + - os: osx + rust: nightly +script: + - cargo build --verbose + - cargo test --verbose + - cargo doc + - if [ "$TRAVIS_RUST_VERSION" = "nightly" ]; then + cargo bench --verbose; + fi +branches: + only: + - master diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/appveyor.yml cargo-0.26.0/vendor/schannel-0.1.10/appveyor.yml --- cargo-0.25.0/vendor/schannel-0.1.10/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,26 +0,0 @@ -environment: - matrix: - - TARGET: x86_64-pc-windows-msvc - VERSION: nightly - - TARGET: i686-pc-windows-msvc - VERSION: nightly - - TARGET: x86_64-pc-windows-gnu - VERSION: nightly - - TARGET: i686-pc-windows-gnu - VERSION: 1.10.0 - access_token: - secure: ZxcrtxQXwszRYNN6c1ZIagczEqzmQQZeYHY58izcmF0jdq/cptxJvFUoVxDmnoqj -install: - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:VERSION}-${env:TARGET}.exe" -FileName "rust-nightly.exe" - - ps: .\rust-nightly.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null - - ps: $env:PATH="$env:PATH;C:\rust\bin" - - rustc -vV - - cargo -vV - - echo install - -build: off - -test_script: - # TODO remove this loop when server 2016 lands on appveyor; related to https://github.com/steffengy/schannel-rs/issues/8 - - set RUST_BACKTRACE=1 - - ps: for($i=1; $i -le 3; $i++) { cmd /c "cargo test 2>&1"; if ($?) { break } } diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/.cargo-checksum.json cargo-0.26.0/vendor/schannel-0.1.10/.cargo-checksum.json --- cargo-0.25.0/vendor/schannel-0.1.10/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"acece75e0f987c48863a6c792ec8b7d6c4177d4a027f8ccc72f849794f437016"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/Cargo.toml cargo-0.26.0/vendor/schannel-0.1.10/Cargo.toml --- cargo-0.25.0/vendor/schannel-0.1.10/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "schannel" -version = "0.1.10" -authors = ["Steven Fackler <sfackler@gmail.com>", "Steffen Butzer <steffen.butzer@outlook.com>"] -description = "Schannel bindings for rust, allowing SSL/TLS (e.g. https) without openssl" -documentation = "https://docs.rs/schannel/0/x86_64-pc-windows-gnu/schannel/" -readme = "README.md" -keywords = ["windows", "schannel", "tls", "ssl", "https"] -license = "MIT" -repository = "https://github.com/steffengy/schannel-rs" -[dependencies.lazy_static] -version = "1.0" - -[dependencies.winapi] -version = "0.3" -features = ["lmcons", "minschannel", "securitybaseapi", "schannel", "sysinfoapi", "timezoneapi", "winbase", "wincrypt", "winerror"] diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/LICENSE.md cargo-0.26.0/vendor/schannel-0.1.10/LICENSE.md --- cargo-0.25.0/vendor/schannel-0.1.10/LICENSE.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/LICENSE.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -Copyright (c) 2015 steffengy - -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. diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/README.md cargo-0.26.0/vendor/schannel-0.1.10/README.md --- cargo-0.25.0/vendor/schannel-0.1.10/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -schannel-rs [![Build status](https://ci.appveyor.com/api/projects/status/vefyauaf0oj10swu/branch/master?svg=true)](https://ci.appveyor.com/project/steffengy/schannel-rs/branch/master) -===== - -[Documentation](https://docs.rs/schannel/0/x86_64-pc-windows-gnu/schannel/) - -Rust bindings to the Windows SChannel APIs providing TLS client and server functionality. diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/cert_chain.rs cargo-0.26.0/vendor/schannel-0.1.10/src/cert_chain.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/cert_chain.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/cert_chain.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,139 +0,0 @@ -//! Bindings to winapi's certificate-chain related APIs. - -use std::mem; -use std::slice; -use winapi::um::wincrypt; - -use cert_context::CertContext; -use Inner; - -/// A certificate chain context (consisting of multiple chains) -pub struct CertChainContext(pub wincrypt::PCERT_CHAIN_CONTEXT); - -unsafe impl Sync for CertChainContext {} -unsafe impl Send for CertChainContext {} - -impl Clone for CertChainContext { - fn clone(&self) -> Self { - let rced = unsafe { - wincrypt::CertDuplicateCertificateChain(self.0) as *mut _ - }; - CertChainContext(rced) - } -} - -impl Drop for CertChainContext { - fn drop(&mut self) { - unsafe { - wincrypt::CertFreeCertificateChain(self.0); - } - } -} - -impl CertChainContext { - /// Get the final (for a successful verification this means successful) certificate chain - /// - /// https://msdn.microsoft.com/de-de/library/windows/desktop/aa377182(v=vs.85).aspx - /// rgpChain[cChain - 1] is the final chain - pub fn final_chain(&self) -> Option<CertChain> { - if let Some(chain) = self.chains().last(){ - return Some(CertChain(chain.0, self.clone())); - } - None - } - - /// Retrieves the specified chain from the context. - pub fn get_chain(&self, index :usize) -> Option<CertChain> { - let cert_chain = unsafe { - let cert_chain = *self.0; - if index >= cert_chain.cChain as usize { - None - } else { - let chain_slice = slice::from_raw_parts( - cert_chain.rgpChain as *mut wincrypt::PCERT_SIMPLE_CHAIN, - cert_chain.cChain as usize); - Some(CertChain(chain_slice[index], self.clone())) - } - }; - return cert_chain; - } - - /// Return an iterator over all certificate chains in this context - pub fn chains(&self) -> CertificateChains { - CertificateChains { - context: self, - idx: 0 - } - } -} - -/// A (simple) certificate chain -pub struct CertChain(wincrypt::PCERT_SIMPLE_CHAIN, CertChainContext); - -impl CertChain { - /// Returns the number of certificates in the chain - pub fn len(&self) -> usize { - unsafe { - (*self.0).cElement as usize - } - } - - /// Get the n-th certificate from the current chain - pub fn get(&self, idx: usize) -> Option<CertContext> { - let elements = unsafe { - let cert_chain = *self.0; - slice::from_raw_parts( - cert_chain.rgpElement as *mut &mut wincrypt::CERT_CHAIN_ELEMENT, - cert_chain.cElement as usize) - }; - elements.get(idx).map(|el| { - let cert = unsafe { - CertContext::from_inner(el.pCertContext) - }; - let rc_cert = cert.clone(); - mem::forget(cert); - rc_cert - }) - } - - /// Return an iterator over all certificates in this chain - pub fn certificates(&self) -> Certificates { - Certificates { - chain: self, - idx: 0, - } - } -} - - -/// An iterator that iterates over all chains in a context -pub struct CertificateChains<'a> { - context: &'a CertChainContext, - idx: usize, -} - -impl<'a> Iterator for CertificateChains<'a> { - type Item = CertChain; - - fn next(&mut self) -> Option<CertChain> { - let idx = self.idx; - self.idx += 1; - self.context.get_chain(idx) - } -} - -/// An iterator that iterates over all certificates in a chain -pub struct Certificates<'a> { - chain: &'a CertChain, - idx: usize, -} - -impl<'a> Iterator for Certificates<'a> { - type Item = CertContext; - - fn next(&mut self) -> Option<CertContext> { - let idx = self.idx; - self.idx += 1; - self.chain.get(idx) - } -} diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/cert_context.rs cargo-0.26.0/vendor/schannel-0.1.10/src/cert_context.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/cert_context.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/cert_context.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,626 +0,0 @@ -//! Bindings to winapi's `PCCERT_CONTEXT` APIs. - -use std::ffi::{CStr, OsString}; -use std::io; -use std::mem; -use std::os::windows::prelude::*; -use std::ptr; -use std::slice; -use winapi::shared::minwindef as winapi; -use winapi::shared::ntdef; -use winapi::shared::winerror; -use winapi::um::wincrypt; - -use Inner; -use ncrypt_key::NcryptKey; -use crypt_prov::{CryptProv, ProviderType}; - -/// A supported hashing algorithm -pub struct HashAlgorithm(winapi::DWORD, usize); - -#[allow(missing_docs)] -impl HashAlgorithm { - pub fn md5() -> HashAlgorithm { - HashAlgorithm(wincrypt::CALG_MD5, 16) - } - - pub fn sha1() -> HashAlgorithm{ - HashAlgorithm(wincrypt::CALG_SHA1, 20) - } - - pub fn sha256() -> HashAlgorithm { - HashAlgorithm(wincrypt::CALG_SHA_256, 32) - } - - pub fn sha384() -> HashAlgorithm { - HashAlgorithm(wincrypt::CALG_SHA_384, 48) - } - - pub fn sha512() -> HashAlgorithm { - HashAlgorithm(wincrypt::CALG_SHA_512, 64) - } -} - -/// Wrapper of a winapi certificate, or a `PCCERT_CONTEXT`. -#[derive(Debug)] -pub struct CertContext(wincrypt::PCCERT_CONTEXT); - -unsafe impl Sync for CertContext {} -unsafe impl Send for CertContext {} - -impl Drop for CertContext { - fn drop(&mut self) { - unsafe { - wincrypt::CertFreeCertificateContext(self.0); - } - } -} - -impl Clone for CertContext { - fn clone(&self) -> CertContext { - unsafe { CertContext(wincrypt::CertDuplicateCertificateContext(self.0)) } - } -} - -inner!(CertContext, wincrypt::PCCERT_CONTEXT); - -impl CertContext { - /// Decodes a DER-formatted X509 certificate. - pub fn new(data: &[u8]) -> io::Result<CertContext> { - let ret = unsafe { - wincrypt::CertCreateCertificateContext(wincrypt::X509_ASN_ENCODING | - wincrypt::PKCS_7_ASN_ENCODING, - data.as_ptr(), - data.len() as winapi::DWORD) - }; - if ret.is_null() { - Err(io::Error::last_os_error()) - } else { - Ok(CertContext(ret)) - } - } - - /// Get certificate in binary DER form - pub fn to_der<'a>(&'a self) -> &'a [u8] { - self.get_encoded_bytes() - } - - /// Decodes a PEM-formatted X509 certificate. - pub fn from_pem(pem: &str) -> io::Result<CertContext> { - unsafe { - assert!(pem.len() <= winapi::DWORD::max_value() as usize); - - let mut len = 0; - let ok = wincrypt::CryptStringToBinaryA(pem.as_ptr() as ntdef::LPCSTR, - pem.len() as winapi::DWORD, - wincrypt::CRYPT_STRING_BASE64HEADER, - ptr::null_mut(), - &mut len, - ptr::null_mut(), - ptr::null_mut()); - if ok != winapi::TRUE { - return Err(io::Error::last_os_error()); - } - - let mut buf = vec![0; len as usize]; - let ok = wincrypt::CryptStringToBinaryA(pem.as_ptr() as ntdef::LPCSTR, - pem.len() as winapi::DWORD, - wincrypt::CRYPT_STRING_BASE64HEADER, - buf.as_mut_ptr(), - &mut len, - ptr::null_mut(), - ptr::null_mut()); - if ok != winapi::TRUE { - return Err(io::Error::last_os_error()); - } - - CertContext::new(&buf) - } - } - - /// Get certificate as PEM-formatted X509 certificate. - pub fn to_pem(&self) -> io::Result<String> { - unsafe { - let mut len = 0; - let ok = wincrypt::CryptBinaryToStringA( - (*self.0).pbCertEncoded, - (*self.0).cbCertEncoded, - wincrypt::CRYPT_STRING_BASE64HEADER, - ptr::null_mut(), - &mut len, - ); - if ok != winapi::TRUE { - return Err(io::Error::last_os_error()); - } - - let mut buf = vec![0; len as usize]; - let ok = wincrypt::CryptBinaryToStringA( - (*self.0).pbCertEncoded, - (*self.0).cbCertEncoded, - wincrypt::CRYPT_STRING_BASE64HEADER, - buf.as_mut_ptr(), - &mut len, - ); - if ok != winapi::TRUE { - return Err(io::Error::last_os_error()); - } - - Ok(CStr::from_ptr(buf.as_ptr()).to_string_lossy().into_owned()) - } - } - - /// Returns a hash of this certificate - pub fn fingerprint(&self, alg: HashAlgorithm) -> io::Result<Vec<u8>> { - unsafe { - let mut buf = vec![0u8; alg.1]; - let mut len = buf.len() as winapi::DWORD; - - let ret = wincrypt::CryptHashCertificate(0, - alg.0, - 0, - (*self.0).pbCertEncoded, - (*self.0).cbCertEncoded, - buf.as_mut_ptr(), - &mut len); - - if ret != winapi::TRUE { - return Err(io::Error::last_os_error()); - } - Ok(buf) - } - } - - /// Returns the sha1 hash of this certificate - /// - /// The sha1 is returned as a 20-byte array representing the bits of the - /// sha1 hash. - #[deprecated(note = "please use fingerprint instead")] - pub fn sha1(&self) -> io::Result<[u8; 20]> { - let mut out = [0u8; 20]; - out.copy_from_slice(&try!(self.fingerprint(HashAlgorithm::sha1()))); - Ok(out) - } - - /// Returns the `<SIGNATURE>/<HASH>` string representing the certificate - /// signature. - /// - /// The `<SIGNATURE>` value identifies the CNG public key - /// algorithm. The `<HASH>` value identifies the CNG hash algorithm. - /// - /// Common examples are: - /// - /// * `RSA/SHA1` - /// * `RSA/SHA256` - /// * `ECDSA/SHA256` - pub fn sign_hash_algorithms(&self) -> io::Result<String> { - self.get_string(wincrypt::CERT_SIGN_HASH_CNG_ALG_PROP_ID) - } - - /// Returns the signature hash. - pub fn signature_hash(&self) -> io::Result<Vec<u8>> { - self.get_bytes(wincrypt::CERT_SIGNATURE_HASH_PROP_ID) - } - - /// Returns the property displayed by the certificate UI. This property - /// allows the user to describe the certificate's use. - pub fn description(&self) -> io::Result<Vec<u8>> { - self.get_bytes(wincrypt::CERT_DESCRIPTION_PROP_ID) - } - - /// Returns a string that contains the display name for the certificate. - pub fn friendly_name(&self) -> io::Result<String> { - self.get_string(wincrypt::CERT_FRIENDLY_NAME_PROP_ID) - } - - /// Configures the string that contains the display name for this - /// certificate. - pub fn set_friendly_name(&self, name: &str) -> io::Result<()> { - self.set_string(wincrypt::CERT_FRIENDLY_NAME_PROP_ID, name) - } - - /// Verifies the time validity of this certificate relative to the system's - /// current time. - pub fn is_time_valid(&self) -> io::Result<bool> { - let ret = unsafe { wincrypt::CertVerifyTimeValidity(ptr::null_mut(), (*self.0).pCertInfo) }; - Ok(ret == 0) - } - - /// Returns a builder used to acquire the private key corresponding to this certificate. - pub fn private_key<'a>(&'a self) -> AcquirePrivateKeyOptions<'a> { - AcquirePrivateKeyOptions { - cert: self, - flags: 0, - } - } - - /// Deletes this certificate from its certificate store. - pub fn delete(self) -> io::Result<()> { - unsafe { - let ret = wincrypt::CertDeleteCertificateFromStore(self.0); - mem::forget(self); - if ret == winapi::TRUE { - Ok(()) - } else { - Err(io::Error::last_os_error()) - } - } - } - - /// Returns a builder used to set the private key associated with this certificate. - pub fn set_key_prov_info<'a>(&'a self) -> SetKeyProvInfo<'a> { - SetKeyProvInfo { - cert: self, - container: None, - provider: None, - type_: 0, - flags: 0, - key_spec: 0, - } - } - - /// Returns the valid uses for this certificate - pub fn valid_uses(&self) -> io::Result<ValidUses> { - unsafe { - let mut buf_len = 0; - let ok = wincrypt::CertGetEnhancedKeyUsage(self.0, 0, ptr::null_mut(), &mut buf_len); - - if ok != winapi::TRUE { - return Err(io::Error::last_os_error()); - } - - let mut buf = vec![0u8; buf_len as usize]; - let cert_enhkey_usage = buf.as_mut_ptr() as *mut wincrypt::CERT_ENHKEY_USAGE; - - let ok = wincrypt::CertGetEnhancedKeyUsage(self.0, 0, cert_enhkey_usage, &mut buf_len); - if ok != winapi::TRUE { - return Err(io::Error::last_os_error()); - } - - let use_cnt = (*cert_enhkey_usage).cUsageIdentifier; - if use_cnt == 0 { - let last_error = io::Error::last_os_error(); - match last_error.raw_os_error() { - Some(winerror::CRYPT_E_NOT_FOUND) => return Ok(ValidUses::All), - Some(0) => (), - _ => return Err(last_error), - }; - } - - let mut oids: Vec<String> = Vec::with_capacity(use_cnt as usize); - for i in 0..use_cnt { - let oid_ptr = (*cert_enhkey_usage).rgpszUsageIdentifier; - oids.push( - CStr::from_ptr(*(oid_ptr.offset(i as isize))) - .to_string_lossy() - .into_owned(), - ); - } - Ok(ValidUses::Oids(oids)) - } - } - - fn get_encoded_bytes<'a>(&'a self) -> &'a [u8] { - unsafe { - let cert_ctx = *self.0; - slice::from_raw_parts(cert_ctx.pbCertEncoded, cert_ctx.cbCertEncoded as usize) - } - } - - fn get_bytes(&self, prop: winapi::DWORD) -> io::Result<Vec<u8>> { - unsafe { - let mut len = 0; - let ret = - wincrypt::CertGetCertificateContextProperty(self.0, prop, ptr::null_mut(), &mut len); - if ret != winapi::TRUE { - return Err(io::Error::last_os_error()); - } - - let mut buf = vec![0u8; len as usize]; - let ret = wincrypt::CertGetCertificateContextProperty(self.0, - prop, - buf.as_mut_ptr() as winapi::LPVOID, - &mut len); - if ret != winapi::TRUE { - return Err(io::Error::last_os_error()); - } - Ok(buf) - } - } - - fn get_string(&self, prop: winapi::DWORD) -> io::Result<String> { - unsafe { - let mut len = 0; - let ret = - wincrypt::CertGetCertificateContextProperty(self.0, prop, ptr::null_mut(), &mut len); - if ret != winapi::TRUE { - return Err(io::Error::last_os_error()); - } - - // Divide by 2 b/c `len` is the byte length, but we're allocating - // u16 pairs which are 2 bytes each. - let amt = (len / 2) as usize; - let mut buf = vec![0u16; amt]; - let ret = wincrypt::CertGetCertificateContextProperty(self.0, - prop, - buf.as_mut_ptr() as winapi::LPVOID, - &mut len); - if ret != winapi::TRUE { - return Err(io::Error::last_os_error()); - } - - // Chop off the trailing nul byte - Ok(OsString::from_wide(&buf[..amt - 1]).into_string().unwrap()) - } - } - - fn set_string(&self, prop: winapi::DWORD, s: &str) -> io::Result<()> { - unsafe { - let data = s.encode_utf16().chain(Some(0)).collect::<Vec<_>>(); - let data = wincrypt::CRYPT_DATA_BLOB { - cbData: (data.len() * 2) as winapi::DWORD, - pbData: data.as_ptr() as *mut _, - }; - let ret = wincrypt::CertSetCertificateContextProperty(self.0, - prop, - 0, - &data as *const _ as *const _); - if ret != winapi::TRUE { - Err(io::Error::last_os_error()) - } else { - Ok(()) - } - } - } -} - -impl PartialEq for CertContext { - fn eq(&self, other: &CertContext) -> bool { - self.get_encoded_bytes() == other.get_encoded_bytes() - } -} - -/// A builder type for certificate private key lookup. -pub struct AcquirePrivateKeyOptions<'a> { - cert: &'a CertContext, - flags: winapi::DWORD, -} - -impl<'a> AcquirePrivateKeyOptions<'a> { - /// If set, the certificate's public key will be compared with the private key to ensure a - /// match. - pub fn compare_key(&mut self, compare_key: bool) -> &mut AcquirePrivateKeyOptions<'a> { - self.flag(wincrypt::CRYPT_ACQUIRE_COMPARE_KEY_FLAG, compare_key) - } - - /// If set, the lookup will not display any user interface, even if that causes the lookup to - /// fail. - pub fn silent(&mut self, silent: bool) -> &mut AcquirePrivateKeyOptions<'a> { - self.flag(wincrypt::CRYPT_ACQUIRE_SILENT_FLAG, silent) - } - - fn flag(&mut self, flag: winapi::DWORD, set: bool) -> &mut AcquirePrivateKeyOptions<'a> { - if set { - self.flags |= flag; - } else { - self.flags &= !flag; - } - self - } - - /// Acquires the private key handle. - pub fn acquire(&self) -> io::Result<PrivateKey> { - unsafe { - let flags = self.flags | wincrypt::CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG; - let mut handle = 0; - let mut spec = 0; - let mut free = winapi::FALSE; - let res = wincrypt::CryptAcquireCertificatePrivateKey(self.cert.0, - flags, - ptr::null_mut(), - &mut handle, - &mut spec, - &mut free); - if res != winapi::TRUE { - return Err(io::Error::last_os_error()); - } - assert!(free == winapi::TRUE); - if spec & wincrypt::CERT_NCRYPT_KEY_SPEC != 0 { - Ok(PrivateKey::NcryptKey(NcryptKey::from_inner(handle))) - } else { - Ok(PrivateKey::CryptProv(CryptProv::from_inner(handle))) - } - } - } -} - -/// The private key associated with a certificate context. -pub enum PrivateKey { - /// A CryptoAPI provider. - CryptProv(CryptProv), - /// A CNG provider. - NcryptKey(NcryptKey), -} - -/// A builder used to set the private key associated with a certificate. -pub struct SetKeyProvInfo<'a> { - cert: &'a CertContext, - container: Option<Vec<u16>>, - provider: Option<Vec<u16>>, - type_: winapi::DWORD, - flags: winapi::DWORD, - key_spec: winapi::DWORD, -} - -impl<'a> SetKeyProvInfo<'a> { - /// The name of the key container. - /// - /// If `type_` is not provided, this specifies the name of the key withing - /// the CNG key storage provider. - pub fn container(&mut self, container: &str) -> &mut SetKeyProvInfo<'a> { - self.container = Some(container.encode_utf16().chain(Some(0)).collect()); - self - } - - /// The name of the CSP. - /// - /// If `type_` is not provided, this contains the name of the CNG key - /// storage provider. - pub fn provider(&mut self, provider: &str) -> &mut SetKeyProvInfo<'a> { - self.provider = Some(provider.encode_utf16().chain(Some(0)).collect()); - self - } - - /// Sets the CSP type. - /// - /// If not provided, the key container is one of the CNG key storage - /// providers. - pub fn type_(&mut self, type_: ProviderType) -> &mut SetKeyProvInfo<'a> { - self.type_ = type_.as_raw(); - self - } - - /// If set, the handle to the key provider can be kept open for subsequent - /// calls to cryptographic functions. - pub fn keep_open(&mut self, keep_open: bool) -> &mut SetKeyProvInfo<'a> { - self.flag(wincrypt::CERT_SET_KEY_PROV_HANDLE_PROP_ID, keep_open) - } - - /// If set, the key container contains machine keys. - pub fn machine_keyset(&mut self, machine_keyset: bool) -> &mut SetKeyProvInfo<'a> { - self.flag(wincrypt::CRYPT_MACHINE_KEYSET, machine_keyset) - } - - /// If set, the key container will attempt to open keys without any user - /// interface prompts. - pub fn silent(&mut self, silent: bool) -> &mut SetKeyProvInfo<'a> { - self.flag(wincrypt::CRYPT_SILENT, silent) - } - - fn flag(&mut self, flag: winapi::DWORD, on: bool) -> &mut SetKeyProvInfo<'a> { - if on { - self.flags |= flag; - } else { - self.flags &= !flag; - } - self - } - - /// The specification of the private key to retrieve. - pub fn key_spec(&mut self, key_spec: KeySpec) -> &mut SetKeyProvInfo<'a> { - self.key_spec = key_spec.0; - self - } - - /// Sets the private key for this certificate. - pub fn set(&mut self) -> io::Result<()> { - unsafe { - let container = self.container.as_ref().map(|s| s.as_ptr()).unwrap_or(ptr::null()); - let provider = self.provider.as_ref().map(|s| s.as_ptr()).unwrap_or(ptr::null()); - - let info = wincrypt::CRYPT_KEY_PROV_INFO { - pwszContainerName: container as *mut _, - pwszProvName: provider as *mut _, - dwProvType: self.type_, - dwFlags: self.flags, - cProvParam: 0, - rgProvParam: ptr::null_mut(), - dwKeySpec: self.key_spec, - }; - - let res = - wincrypt::CertSetCertificateContextProperty(self.cert.0, - wincrypt::CERT_KEY_PROV_INFO_PROP_ID, - 0, - &info as *const _ as *const _); - if res == winapi::TRUE { - Ok(()) - } else { - Err(io::Error::last_os_error()) - } - } - } -} - -/// The specification of a private key. -#[derive(Copy, Clone)] -pub struct KeySpec(winapi::DWORD); - -impl KeySpec { - /// A key used to encrypt/decrypt session keys. - pub fn key_exchange() -> KeySpec { - KeySpec(wincrypt::AT_KEYEXCHANGE) - } - - /// A key used to create and verify digital signatures. - pub fn signature() -> KeySpec { - KeySpec(wincrypt::AT_SIGNATURE) - } -} - -/// Valid uses of a Certificate - All, or specific OIDs -pub enum ValidUses { - /// Certificate is valid for all uses - All, - - /// Certificate is valid for uses specified. No entries means that the certificate - /// has no valid uses. - Oids(Vec<String>), -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn decode() { - let der = include_bytes!("../test/cert.der"); - let pem = include_str!("../test/cert.pem"); - - let der = CertContext::new(der).unwrap(); - let pem = CertContext::from_pem(pem).unwrap(); - assert_eq!(der, pem); - } - - #[test] - fn certcontext_to_der() { - let der = include_bytes!("../test/cert.der"); - let cert = CertContext::new(der).unwrap(); - let der2 = CertContext::to_der(&cert); - assert_eq!(der as &[u8], der2); - } - - #[test] - fn certcontext_to_pem() { - let der = include_bytes!("../test/cert.der"); - let pem1 = include_str!("../test/cert.pem").replace("\r", ""); - - let der = CertContext::new(der).unwrap(); - let pem2 = CertContext::to_pem(&der).unwrap().replace("\r", ""); - assert_eq!(pem1, pem2); - } - - #[test] - fn fingerprint() { - let der = include_bytes!("../test/cert.der"); - let pem = include_str!("../test/cert.pem"); - - let der = CertContext::new(der).unwrap(); - let pem = CertContext::from_pem(pem).unwrap(); - - let hash = der.fingerprint(HashAlgorithm::sha1()).unwrap(); - assert_eq!(hash, vec![‎ - 0x59, 0x17, 0x2D, 0x93, 0x13, 0xE8, 0x44, 0x59, 0xBC, 0xFF, - 0x27, 0xF9, 0x67, 0xE7, 0x9E, 0x6E, 0x92, 0x17, 0xE5, 0x84 - ]); - assert_eq!(hash, pem.fingerprint(HashAlgorithm::sha1()).unwrap()); - - let hash = der.fingerprint(HashAlgorithm::sha256()).unwrap(); - assert_eq!(hash, vec![ - 0x47, 0x12, 0xB9, 0x39, 0xFB, 0xCB, 0x42, 0xA6, 0xB5, 0x10, - 0x1B, 0x42, 0x13, 0x9A, 0x25, 0xB1, 0x4F, 0x81, 0xB4, 0x18, - 0xFA, 0xCA, 0xBD, 0x37, 0x87, 0x46, 0xF1, 0x2F, 0x85, 0xCC, - 0x65, 0x44 - ]); - assert_eq!(hash, pem.fingerprint(HashAlgorithm::sha256()).unwrap()); - } -} diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/cert_store.rs cargo-0.26.0/vendor/schannel-0.1.10/src/cert_store.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/cert_store.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/cert_store.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,446 +0,0 @@ -//! Bindings to winapi's certificate-store related APIs. - -use std::cmp; -use std::ffi::OsStr; -use std::fmt; -use std::io; -use std::mem; -use std::os::windows::prelude::*; -use std::ptr; -use winapi::shared::minwindef as winapi; -use winapi::shared::ntdef; -use winapi::um::wincrypt; - -use cert_context::CertContext; -use ctl_context::CtlContext; - -use Inner; - -/// Representation of certificate store on Windows, wrapping a `HCERTSTORE`. -pub struct CertStore(wincrypt::HCERTSTORE); - -unsafe impl Sync for CertStore {} -unsafe impl Send for CertStore {} - -impl fmt::Debug for CertStore { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("CertStore").finish() - } -} - -impl Drop for CertStore { - fn drop(&mut self) { - unsafe { - wincrypt::CertCloseStore(self.0, 0); - } - } -} - -impl Clone for CertStore { - fn clone(&self) -> CertStore { - unsafe { CertStore(wincrypt::CertDuplicateStore(self.0)) } - } -} - -inner!(CertStore, wincrypt::HCERTSTORE); - -/// Argument to the `add_cert` function indicating how a certificate should be -/// added to a `CertStore`. -pub enum CertAdd { - /// The function makes no check for an existing matching certificate or link - /// to a matching certificate. A new certificate is always added to the - /// store. This can lead to duplicates in a store. - Always = wincrypt::CERT_STORE_ADD_ALWAYS as isize, - - /// If a matching certificate or a link to a matching certificate exists, - /// the operation fails. - New = wincrypt::CERT_STORE_ADD_NEW as isize, - - /// If a matching certificate or a link to a matching certificate exists and - /// the NotBefore time of the existing context is equal to or greater than - /// the NotBefore time of the new context being added, the operation fails. - /// - /// If the NotBefore time of the existing context is less than the NotBefore - /// time of the new context being added, the existing certificate or link is - /// deleted and a new certificate is created and added to the store. If a - /// matching certificate or a link to a matching certificate does not exist, - /// a new link is added. - Newer = wincrypt::CERT_STORE_ADD_NEWER as isize, - - /// If a matching certificate or a link to a matching certificate exists and - /// the NotBefore time of the existing context is equal to or greater than - /// the NotBefore time of the new context being added, the operation fails. - /// - /// If the NotBefore time of the existing context is less than the NotBefore - /// time of the new context being added, the existing context is deleted - /// before creating and adding the new context. The new added context - /// inherits properties from the existing certificate. - NewerInheritProperties = wincrypt::CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES as isize, - - /// If a link to a matching certificate exists, that existing certificate or - /// link is deleted and a new certificate is created and added to the store. - /// If a matching certificate or a link to a matching certificate does not - /// exist, a new link is added. - ReplaceExisting = wincrypt::CERT_STORE_ADD_REPLACE_EXISTING as isize, - - /// If a matching certificate exists in the store, the existing context is - /// not replaced. The existing context inherits properties from the new - /// certificate. - ReplaceExistingInheritProperties = - wincrypt::CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES as isize, - - /// If a matching certificate or a link to a matching certificate exists, - /// that existing certificate or link is used and properties from the - /// new certificate are added. The function does not fail, but it does - /// not add a new context. The existing context is duplicated and returned. - /// - /// If a matching certificate or a link to a matching certificate does - /// not exist, a new certificate is added. - UseExisting = wincrypt::CERT_STORE_ADD_USE_EXISTING as isize, -} - -impl CertStore { - /// Opens up the specified key store within the context of the current user. - /// - /// Known valid values for `which` are "Root" and "My". - pub fn open_current_user(which: &str) -> io::Result<CertStore> { - unsafe { - let data = OsStr::new(which) - .encode_wide() - .chain(Some(0)) - .collect::<Vec<_>>(); - let store = wincrypt::CertOpenStore(wincrypt::CERT_STORE_PROV_SYSTEM_W as ntdef::LPCSTR, - 0, - 0, - wincrypt::CERT_SYSTEM_STORE_CURRENT_USER, - data.as_ptr() as *mut _); - if store.is_null() { - Err(io::Error::last_os_error()) - } else { - Ok(CertStore(store)) - } - } - } - - /// Opens up the specified key store within the context of the local - /// machine. - /// - /// Known valid values for `which` are "Root" and "My". - pub fn open_local_machine(which: &str) -> io::Result<CertStore> { - unsafe { - let data = OsStr::new(which) - .encode_wide() - .chain(Some(0)) - .collect::<Vec<_>>(); - let store = wincrypt::CertOpenStore(wincrypt::CERT_STORE_PROV_SYSTEM_W as ntdef::LPCSTR, - 0, - 0, - wincrypt::CERT_SYSTEM_STORE_LOCAL_MACHINE, - data.as_ptr() as *mut _); - if store.is_null() { - Err(io::Error::last_os_error()) - } else { - Ok(CertStore(store)) - } - } - } - - /// Imports a PKCS#12-encoded key/certificate pair, returned as a - /// `CertStore` instance. - /// - /// The password must also be provided to decrypt the encoded data. - pub fn import_pkcs12(data: &[u8], - password: Option<&str>) - -> io::Result<CertStore> { - unsafe { - let mut blob = wincrypt::CRYPT_INTEGER_BLOB { - cbData: data.len() as winapi::DWORD, - pbData: data.as_ptr() as *mut u8, - }; - let password = password.map(|s| { - OsStr::new(s).encode_wide() - .chain(Some(0)) - .collect::<Vec<_>>() - }); - let password = password.as_ref().map(|s| s.as_ptr()); - let password = password.unwrap_or(ptr::null()); - let res = wincrypt::PFXImportCertStore(&mut blob, - password, - 0); - if res.is_null() { - Err(io::Error::last_os_error()) - } else { - Ok(CertStore(res)) - } - } - } - - /// Returns an iterator over the certificates in this certificate store. - pub fn certs(&mut self) -> Certs { - Certs { store: self, cur: None } - } - - /// Adds a certificate context to this store. - /// - /// This function will add the certificate specified in `cx` to this store. - /// A copy of the added certificate is returned. - pub fn add_cert(&mut self, - cx: &CertContext, - how: CertAdd) -> io::Result<CertContext> { - unsafe { - let how = how as winapi::DWORD; - let mut ret = ptr::null(); - let res = wincrypt::CertAddCertificateContextToStore(self.0, - cx.as_inner(), - how, - &mut ret); - if res != winapi::TRUE { - Err(io::Error::last_os_error()) - } else { - Ok(CertContext::from_inner(ret)) - } - } - } - - /// Exports this certificate store as a PKCS#12-encoded blob. - /// - /// The password specified will be the password used to unlock the returned - /// data. - pub fn export_pkcs12(&self, password: &str) -> io::Result<Vec<u8>> { - unsafe { - let password = password.encode_utf16().chain(Some(0)).collect::<Vec<_>>(); - let mut blob = wincrypt::CRYPT_DATA_BLOB { - cbData: 0, - pbData: 0 as *mut _, - }; - let res = wincrypt::PFXExportCertStore(self.0, - &mut blob, - password.as_ptr(), - wincrypt::EXPORT_PRIVATE_KEYS); - if res != winapi::TRUE { - return Err(io::Error::last_os_error()) - } - let mut ret = Vec::with_capacity(blob.cbData as usize); - blob.pbData = ret.as_mut_ptr(); - let res = wincrypt::PFXExportCertStore(self.0, - &mut blob, - password.as_ptr(), - wincrypt::EXPORT_PRIVATE_KEYS); - if res != winapi::TRUE { - return Err(io::Error::last_os_error()) - } - ret.set_len(blob.cbData as usize); - Ok(ret) - } - } -} - -/// An iterator over the certificates contained in a `CertStore`, returned by -/// `CertStore::iter` -pub struct Certs<'a> { - store: &'a mut CertStore, - cur: Option<CertContext>, -} - -impl<'a> Iterator for Certs<'a> { - type Item = CertContext; - - fn next(&mut self) -> Option<CertContext> { - unsafe { - let cur = self.cur.take().map(|p| { - let ptr = p.as_inner(); - mem::forget(p); - ptr - }); - let cur = cur.unwrap_or(ptr::null_mut()); - let next = wincrypt::CertEnumCertificatesInStore(self.store.0, cur); - - if next.is_null() { - self.cur = None; - None - } else { - let next = CertContext::from_inner(next); - self.cur = Some(next.clone()); - Some(next) - } - } - } -} - -/// A builder type for imports of PKCS #12 archives. -#[derive(Default)] -pub struct PfxImportOptions { - password: Option<Vec<u16>>, - flags: winapi::DWORD, -} - -impl PfxImportOptions { - /// Returns a new `PfxImportOptions` with default settings. - pub fn new() -> PfxImportOptions { - PfxImportOptions::default() - } - - /// Sets the password to be used to decrypt the archive. - pub fn password(&mut self, password: &str) -> &mut PfxImportOptions { - self.password = Some(password.encode_utf16().chain(Some(0)).collect()); - self - } - - /// If set, the private key in the archive will not be persisted. - /// - /// If not set, private keys are persisted on disk and must be manually deleted. - pub fn no_persist_key(&mut self, no_persist_key: bool) -> &mut PfxImportOptions { - self.flag(wincrypt::PKCS12_NO_PERSIST_KEY, no_persist_key) - } - - /// If set, all extended properties of the certificate will be imported. - pub fn include_extended_properties(&mut self, - include_extended_properties: bool) - -> &mut PfxImportOptions { - self.flag(wincrypt::PKCS12_INCLUDE_EXTENDED_PROPERTIES, include_extended_properties) - } - - fn flag(&mut self, flag: winapi::DWORD, set: bool) -> &mut PfxImportOptions { - if set { - self.flags |= flag; - } else { - self.flags &= !flag; - } - self - } - - /// Imports certificates from a PKCS #12 archive, returning a `CertStore` containing them. - pub fn import(&self, data: &[u8]) -> io::Result<CertStore> { - unsafe { - let mut blob = wincrypt::CRYPT_DATA_BLOB { - cbData: cmp::min(data.len(), winapi::DWORD::max_value() as usize) as winapi::DWORD, - pbData: data.as_ptr() as *const _ as *mut _, - }; - let password = self.password.as_ref().map_or(ptr::null(), |p| p.as_ptr()); - - let store = wincrypt::PFXImportCertStore(&mut blob, password, self.flags); - if store.is_null() { - return Err(io::Error::last_os_error()); - } - Ok(CertStore(store)) - } - } -} - -/// Representation of an in-memory certificate store. -/// -/// Internally this contains a `CertStore` which this type can be converted to. -pub struct Memory(CertStore); - -impl Memory { - /// Creates a new in-memory certificate store which certificates and CTLs - /// can be added to. - /// - /// Initially the returned certificate store contains no certificates. - pub fn new() -> io::Result<Memory> { - unsafe { - let store = wincrypt::CertOpenStore(wincrypt::CERT_STORE_PROV_MEMORY as ntdef::LPCSTR, - 0, - 0, - 0, - ptr::null_mut()); - if store.is_null() { - Err(io::Error::last_os_error()) - } else { - Ok(Memory(CertStore(store))) - } - } - } - - /// Adds a new certificate to this memory store. - /// - /// For example the bytes could be a DER-encoded certificate. - pub fn add_encoded_certificate(&mut self, cert: &[u8]) -> io::Result<CertContext> { - unsafe { - let mut cert_context = ptr::null(); - - let res = wincrypt::CertAddEncodedCertificateToStore((self.0).0, - wincrypt::X509_ASN_ENCODING | - wincrypt::PKCS_7_ASN_ENCODING, - cert.as_ptr() as *const _, - cert.len() as winapi::DWORD, - wincrypt::CERT_STORE_ADD_ALWAYS, - &mut cert_context); - if res == winapi::TRUE { - Ok(CertContext::from_inner(cert_context)) - } else { - Err(io::Error::last_os_error()) - } - } - } - - /// Adds a new CTL to this memory store, in its encoded form. - /// - /// This can be created through the `ctl_context::Builder` type. - pub fn add_encoded_ctl(&mut self, ctl: &[u8]) -> io::Result<CtlContext> { - unsafe { - let mut ctl_context = ptr::null(); - - let res = wincrypt::CertAddEncodedCTLToStore((self.0).0, - wincrypt::X509_ASN_ENCODING | - wincrypt::PKCS_7_ASN_ENCODING, - ctl.as_ptr() as *const _, - ctl.len() as winapi::DWORD, - wincrypt::CERT_STORE_ADD_ALWAYS, - &mut ctl_context); - if res == winapi::TRUE { - Ok(CtlContext::from_inner(ctl_context)) - } else { - Err(io::Error::last_os_error()) - } - } - } - - /// Consumes this memory store, returning the underlying `CertStore`. - pub fn into_store(self) -> CertStore { - self.0 - } -} - -#[cfg(test)] -mod test { - use super::*; - use ctl_context::CtlContext; - - #[test] - fn load() { - let cert = include_bytes!("../test/cert.der"); - let mut store = Memory::new().unwrap(); - store.add_encoded_certificate(cert).unwrap(); - } - - #[test] - fn create_ctl() { - let cert = include_bytes!("../test/self-signed.badssl.com.cer"); - let mut store = Memory::new().unwrap(); - let cert = store.add_encoded_certificate(cert).unwrap(); - - CtlContext::builder() - .certificate(cert) - .usage("1.3.6.1.4.1.311.2.2.2") - .encode_and_sign() - .unwrap(); - } - - #[test] - fn pfx_import() { - let pfx = include_bytes!("../test/identity.p12"); - let mut store = PfxImportOptions::new() - .include_extended_properties(true) - .password("mypass") - .import(pfx) - .unwrap(); - assert_eq!(store.certs().count(), 2); - let pkeys = store.certs() - .filter(|c| { - c.private_key().compare_key(true).silent(true).acquire().is_ok() - }) - .count(); - assert_eq!(pkeys, 1); - } -} diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/context_buffer.rs cargo-0.26.0/vendor/schannel-0.1.10/src/context_buffer.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/context_buffer.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/context_buffer.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -use winapi::shared::sspi; -use std::ops::Deref; -use std::slice; - -pub struct ContextBuffer(pub sspi::SecBuffer); - -impl Drop for ContextBuffer { - fn drop(&mut self) { - unsafe { - sspi::FreeContextBuffer(self.0.pvBuffer); - } - } -} - -impl Deref for ContextBuffer { - type Target = [u8]; - - fn deref(&self) -> &[u8] { - unsafe { slice::from_raw_parts(self.0.pvBuffer as *const _, self.0.cbBuffer as usize) } - } -} diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/crypt_key.rs cargo-0.26.0/vendor/schannel-0.1.10/src/crypt_key.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/crypt_key.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/crypt_key.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -//! CryptoAPI private keys. -use winapi::um::wincrypt; - -/// A handle to a key. -pub struct CryptKey(wincrypt::HCRYPTKEY); - -impl Drop for CryptKey { - fn drop(&mut self) { - unsafe { - wincrypt::CryptDestroyKey(self.0); - } - } -} - -inner!(CryptKey, wincrypt::HCRYPTKEY); diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/crypt_prov.rs cargo-0.26.0/vendor/schannel-0.1.10/src/crypt_prov.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/crypt_prov.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/crypt_prov.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,224 +0,0 @@ -//! CryptoAPI key providers. -use std::io; -use std::ptr; -use winapi::shared::minwindef as winapi; -use winapi::um::winbase; -use winapi::um::wincrypt; - -use Inner; -use crypt_key::CryptKey; - -/// A CryptoAPI handle to a provider of a key. -pub struct CryptProv(wincrypt::HCRYPTPROV); - -impl Drop for CryptProv { - fn drop(&mut self) { - unsafe { - wincrypt::CryptReleaseContext(self.0, 0); - } - } -} - -inner!(CryptProv, wincrypt::HCRYPTPROV); - -impl CryptProv { - /// Imports a key into this provider. - pub fn import<'a>(&'a mut self) -> ImportOptions<'a> { - ImportOptions { - prov: self, - flags: 0, - } - } -} - -/// A builder for `CryptProv`s. -pub struct AcquireOptions { - container: Option<Vec<u16>>, - provider: Option<Vec<u16>>, - flags: winapi::DWORD, -} - -impl AcquireOptions { - /// Returns a new builder with default settings. - pub fn new() -> AcquireOptions { - AcquireOptions { - container: None, - provider: None, - flags: 0, - } - } - - /// Sets the name for this key container. - /// - /// This should not be set if `verify_context` is set. - pub fn container(&mut self, container: &str) -> &mut AcquireOptions { - self.container = Some(container.encode_utf16().chain(Some(0)).collect()); - self - } - - /// Sets the name of the CSP to be used. - pub fn provider(&mut self, provider: &str) -> &mut AcquireOptions { - self.provider = Some(provider.encode_utf16().chain(Some(0)).collect()); - self - } - - /// If set, private keys will not be accessible or persisted. - pub fn verify_context(&mut self, verify_context: bool) -> &mut AcquireOptions { - self.flag(wincrypt::CRYPT_VERIFYCONTEXT, verify_context) - } - - /// If set, the container will be created. - pub fn new_keyset(&mut self, new_keyset: bool) -> &mut AcquireOptions { - self.flag(wincrypt::CRYPT_NEWKEYSET, new_keyset) - } - - /// If set, the container will be stored as a machine rather than user keys. - pub fn machine_keyset(&mut self, machine_keyset: bool) -> &mut AcquireOptions { - self.flag(wincrypt::CRYPT_MACHINE_KEYSET, machine_keyset) - } - - /// If set, an error will be returned if user intervention is required - /// rather than displaying a dialog. - pub fn silent(&mut self, silent: bool) -> &mut AcquireOptions { - self.flag(wincrypt::CRYPT_SILENT, silent) - } - - fn flag(&mut self, flag: winapi::DWORD, on: bool) -> &mut AcquireOptions { - if on { - self.flags |= flag; - } else { - self.flags &= !flag; - } - - self - } - - /// Acquires a container. - pub fn acquire(&self, type_: ProviderType) -> io::Result<CryptProv> { - unsafe { - let container = self.container.as_ref().map(|s| s.as_ptr()).unwrap_or(ptr::null()); - let provider = self.provider.as_ref().map(|s| s.as_ptr()).unwrap_or(ptr::null()); - - let mut prov = 0; - let res = wincrypt::CryptAcquireContextW(&mut prov, - container as *mut _, - provider as *mut _, - type_.0, - self.flags); - if res == winapi::TRUE { - Ok(CryptProv(prov)) - } else { - Err(io::Error::last_os_error()) - } - } - } -} - -/// An identifier of the type of cryptography provider to be used with a -/// container. -#[derive(Copy, Clone)] -pub struct ProviderType(winapi::DWORD); - -#[allow(missing_docs)] -impl ProviderType { - pub fn rsa_full() -> ProviderType { - ProviderType(wincrypt::PROV_RSA_FULL) - } - - pub fn rsa_aes() -> ProviderType { - ProviderType(wincrypt::PROV_RSA_AES) - } - - pub fn rsa_sig() -> ProviderType { - ProviderType(wincrypt::PROV_RSA_SIG) - } - - pub fn rsa_schannel() -> ProviderType { - ProviderType(wincrypt::PROV_RSA_SCHANNEL) - } - - pub fn dss() -> ProviderType { - ProviderType(wincrypt::PROV_DSS) - } - - pub fn dss_dh() -> ProviderType { - ProviderType(wincrypt::PROV_DSS_DH) - } - - pub fn dh_schannel() -> ProviderType { - ProviderType(wincrypt::PROV_DH_SCHANNEL) - } - - pub fn fortezza() -> ProviderType { - ProviderType(wincrypt::PROV_FORTEZZA) - } - - pub fn ms_exchange() -> ProviderType { - ProviderType(wincrypt::PROV_MS_EXCHANGE) - } - - pub fn ssl() -> ProviderType { - ProviderType(wincrypt::PROV_SSL) - } - - pub fn as_raw(&self) -> winapi::DWORD { - self.0 - } -} - -/// A builder for key imports. -pub struct ImportOptions<'a> { - prov: &'a mut CryptProv, - flags: winapi::DWORD, -} - -impl<'a> ImportOptions<'a> { - /// Imports a DER-encoded private key. - pub fn import(&mut self, der: &[u8]) -> io::Result<CryptKey> { - unsafe { - assert!(der.len() <= winapi::DWORD::max_value() as usize); - let mut buf = ptr::null_mut(); - let mut len = 0; - let res = wincrypt::CryptDecodeObjectEx(wincrypt::X509_ASN_ENCODING | - wincrypt::PKCS_7_ASN_ENCODING, - wincrypt::PKCS_RSA_PRIVATE_KEY, - der.as_ptr(), - der.len() as winapi::DWORD, - wincrypt::CRYPT_DECODE_ALLOC_FLAG, - ptr::null_mut(), - &mut buf as *mut _ as winapi::LPVOID, - &mut len); - if res == winapi::FALSE { - return Err(io::Error::last_os_error()); - } - - let mut key = 0; - let res = wincrypt::CryptImportKey(self.prov.0, buf, len, 0, self.flags, &mut key); - winbase::LocalFree(buf as *mut _); - - if res == winapi::TRUE { - Ok(CryptKey::from_inner(key)) - } else { - Err(io::Error::last_os_error()) - } - } - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn rsa_key() { - let key = include_bytes!("../test/key.key"); - - let mut context = AcquireOptions::new() - .verify_context(true) - .acquire(ProviderType::rsa_full()) - .unwrap(); - context.import() - .import(key) - .unwrap(); - } -} diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/ctl_context.rs cargo-0.26.0/vendor/schannel-0.1.10/src/ctl_context.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/ctl_context.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/ctl_context.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,187 +0,0 @@ -//! Bindings to Certificate Trust Lists (CTL) in winapi. - -#![allow(dead_code)] - -use std::io; -use std::mem; -use std::ptr; -use winapi::shared::minwindef as winapi; -use winapi::shared::ntdef; -use winapi::um::wincrypt; - -use cert_context::CertContext; -use Inner; - -lazy_static! { - static ref szOID_OIWSEC_sha1: Vec<u8> = - wincrypt::szOID_OIWSEC_sha1.bytes().chain(Some(0)).collect(); -} - -/// Wrapped `PCCTL_CONTEXT` which represents a certificate trust list to -/// Windows. -pub struct CtlContext(wincrypt::PCCTL_CONTEXT); - -unsafe impl Send for CtlContext {} -unsafe impl Sync for CtlContext {} - -impl Drop for CtlContext { - fn drop(&mut self) { - unsafe { - wincrypt::CertFreeCTLContext(self.0); - } - } -} - -impl Inner<wincrypt::PCCTL_CONTEXT> for CtlContext { - unsafe fn from_inner(t: wincrypt::PCCTL_CONTEXT) -> CtlContext { - CtlContext(t) - } - - fn as_inner(&self) -> wincrypt::PCCTL_CONTEXT { - self.0 - } - - fn get_mut(&mut self) -> &mut wincrypt::PCCTL_CONTEXT { - &mut self.0 - } -} - -impl CtlContext { - /// Returns a builder reader to create an encoded `CtlContext`. - pub fn builder() -> Builder { - Builder { - certificates: vec![], - usages: vec![], - } - } -} - -/// Used to build an encoded `CtlContext` which can be added to a `Memory` store -/// to get back the actual `CtlContext`. -pub struct Builder { - certificates: Vec<CertContext>, - usages: Vec<Vec<u8>>, -} - -impl Builder { - /// Adds a certificate to be passed to `CryptMsgEncodeAndSignCTL` later on. - pub fn certificate(&mut self, cert: CertContext) -> &mut Builder { - self.certificates.push(cert); - self - } - - /// Adds a usage string to be passed in the `SubjectUsage` field to - /// `CryptMsgEncodeAndSignCTL` later on. - pub fn usage(&mut self, usage: &str) -> &mut Builder { - let mut usage = usage.as_bytes().to_owned(); - usage.push(0); - self.usages.push(usage); - self - } - - /// Calls `CryptMsgEncodeAndSignCTL` to encode this list of certificates - /// into a CTL. - /// - /// This can later be passed to `Memory::add_encoded_ctl`. - pub fn encode_and_sign(&self) -> io::Result<Vec<u8>> { - unsafe { - let encoding = wincrypt::X509_ASN_ENCODING | wincrypt::PKCS_7_ASN_ENCODING; - - let mut usages = self.usages.iter().map(|u| u.as_ptr()).collect::<Vec<_>>(); - let mut entry_data = vec![]; - let mut entries = vec![]; - for certificate in &self.certificates { - let data = try!(cert_entry(certificate)); - entries.push(*(data.as_ptr() as *const wincrypt::CTL_ENTRY)); - entry_data.push(data); - } - - let mut ctl_info: wincrypt::CTL_INFO = mem::zeroed(); - ctl_info.dwVersion = wincrypt::CTL_V1; - ctl_info.SubjectUsage.cUsageIdentifier = usages.len() as winapi::DWORD; - ctl_info.SubjectUsage.rgpszUsageIdentifier = usages.as_mut_ptr() as *mut ntdef::LPSTR; - ctl_info.SubjectAlgorithm.pszObjId = szOID_OIWSEC_sha1.as_ptr() as ntdef::LPSTR; - ctl_info.cCTLEntry = entries.len() as winapi::DWORD; - ctl_info.rgCTLEntry = entries.as_mut_ptr(); - - let mut sign_info: wincrypt::CMSG_SIGNED_ENCODE_INFO = mem::zeroed(); - sign_info.cbSize = mem::size_of_val(&sign_info) as winapi::DWORD; - let mut encoded_certs = self.certificates - .iter() - .map(|c| { - wincrypt::CERT_BLOB { - cbData: (*c.as_inner()).cbCertEncoded, - pbData: (*c.as_inner()).pbCertEncoded, - } - }) - .collect::<Vec<_>>(); - sign_info.rgCertEncoded = encoded_certs.as_mut_ptr(); - sign_info.cCertEncoded = encoded_certs.len() as winapi::DWORD; - - let flags = wincrypt::CMSG_ENCODE_SORTED_CTL_FLAG | - wincrypt::CMSG_ENCODE_HASHED_SUBJECT_IDENTIFIER_FLAG; - - let mut size = 0; - - let res = wincrypt::CryptMsgEncodeAndSignCTL(encoding, - &mut ctl_info, - &mut sign_info, - flags, - ptr::null_mut(), - &mut size); - if res == winapi::FALSE { - return Err(io::Error::last_os_error()) - } - - let mut encoded = vec![0; size as usize]; - - let res = wincrypt::CryptMsgEncodeAndSignCTL(encoding, - &mut ctl_info, - &mut sign_info, - flags, - encoded.as_mut_ptr() as *mut winapi::BYTE, - &mut size); - if res == winapi::FALSE { - return Err(io::Error::last_os_error()) - } - - Ok(encoded) - } - } -} - -fn cert_entry(cert: &CertContext) -> io::Result<Vec<u8>> { - // FIXME: Seems to be missing since the winapi 0.3 upgrade? - const CTL_ENTRY_FROM_PROP_CHAIN_FLAG: winapi::DWORD = 1; - - unsafe { - let mut size = 0; - - let res = wincrypt::CertCreateCTLEntryFromCertificateContextProperties( - cert.as_inner(), - 0, - ptr::null_mut(), - CTL_ENTRY_FROM_PROP_CHAIN_FLAG, - ptr::null_mut(), - ptr::null_mut(), - &mut size); - if res == winapi::FALSE { - return Err(io::Error::last_os_error()); - } - - let mut entry = vec![0u8; size as usize]; - let res = wincrypt::CertCreateCTLEntryFromCertificateContextProperties( - cert.as_inner(), - 0, - ptr::null_mut(), - CTL_ENTRY_FROM_PROP_CHAIN_FLAG, - ptr::null_mut(), - entry.as_mut_ptr() as wincrypt::PCTL_ENTRY, - &mut size); - if res == winapi::FALSE { - Err(io::Error::last_os_error()) - } else { - Ok(entry) - } - } -} diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/key_handle.rs cargo-0.26.0/vendor/schannel-0.1.10/src/key_handle.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/key_handle.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/key_handle.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -//! Deprecated. -#![deprecated(note = "use cert_context::PrivateKey", since = "0.1.5")] - -#[deprecated(note = "use cert_context::PrivateKey", since = "0.1.5")] -pub use cert_context::PrivateKey as KeyHandle; diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/lib.rs cargo-0.26.0/vendor/schannel-0.1.10/src/lib.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,87 +0,0 @@ -//! Bindings to the Windows SChannel APIs. -#![cfg(windows)] -#![warn(missing_docs)] -#![allow(non_upper_case_globals)] - -extern crate winapi; - -#[macro_use] -extern crate lazy_static; - -use std::ptr; -use winapi::ctypes; -use winapi::shared::sspi; - -macro_rules! inner { - ($t:path, $raw:ty) => { - impl ::Inner<$raw> for $t { - unsafe fn from_inner(t: $raw) -> Self { - $t(t) - } - - fn as_inner(&self) -> $raw { - self.0 - } - - fn get_mut(&mut self) -> &mut $raw { - &mut self.0 - } - } - } -} - -pub mod cert_chain; -pub mod cert_context; -pub mod cert_store; -pub mod crypt_key; -pub mod crypt_prov; -/* pub */ mod ctl_context; -pub mod key_handle; -pub mod ncrypt_key; -pub mod schannel_cred; -pub mod tls_stream; - -mod context_buffer; -mod security_context; - -#[cfg(test)] -mod test; - -const ACCEPT_REQUESTS: ctypes::c_ulong = - sspi::ASC_REQ_ALLOCATE_MEMORY | sspi::ASC_REQ_CONFIDENTIALITY | - sspi::ASC_REQ_SEQUENCE_DETECT | sspi::ASC_REQ_STREAM | - sspi::ASC_REQ_REPLAY_DETECT; - -const INIT_REQUESTS: ctypes::c_ulong = - sspi::ISC_REQ_CONFIDENTIALITY | sspi::ISC_REQ_INTEGRITY | sspi::ISC_REQ_REPLAY_DETECT | - sspi::ISC_REQ_SEQUENCE_DETECT | sspi::ISC_REQ_MANUAL_CRED_VALIDATION | - sspi::ISC_REQ_ALLOCATE_MEMORY | sspi::ISC_REQ_STREAM | sspi::ISC_REQ_USE_SUPPLIED_CREDS; - -trait Inner<T> { - unsafe fn from_inner(t: T) -> Self; - - fn as_inner(&self) -> T; - - fn get_mut(&mut self) -> &mut T; -} - -unsafe fn secbuf(buftype: ctypes::c_ulong, - bytes: Option<&mut [u8]>) -> sspi::SecBuffer { - let (ptr, len) = match bytes { - Some(bytes) => (bytes.as_mut_ptr(), bytes.len() as ctypes::c_ulong), - None => (ptr::null_mut(), 0), - }; - sspi::SecBuffer { - BufferType: buftype, - cbBuffer: len, - pvBuffer: ptr as *mut ctypes::c_void, - } -} - -unsafe fn secbuf_desc(bufs: &mut [sspi::SecBuffer]) -> sspi::SecBufferDesc { - sspi::SecBufferDesc { - ulVersion: sspi::SECBUFFER_VERSION, - cBuffers: bufs.len() as ctypes::c_ulong, - pBuffers: bufs.as_mut_ptr(), - } -} diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/ncrypt_key.rs cargo-0.26.0/vendor/schannel-0.1.10/src/ncrypt_key.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/ncrypt_key.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/ncrypt_key.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -//! CNG private keys. -use winapi::um::ncrypt; - -/// A CNG handle to a key. -pub struct NcryptKey(ncrypt::NCRYPT_KEY_HANDLE); - -impl Drop for NcryptKey { - fn drop(&mut self) { - unsafe { - ncrypt::NCryptFreeObject(self.0); - } - } -} - -inner!(NcryptKey, ncrypt::NCRYPT_KEY_HANDLE); diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/schannel_cred.rs cargo-0.26.0/vendor/schannel-0.1.10/src/schannel_cred.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/schannel_cred.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/schannel_cred.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,262 +0,0 @@ -//! Schannel credentials. -use winapi::shared::{sspi, winerror}; -use winapi::shared::minwindef as winapi; -use winapi::um::{self, wincrypt}; -use std::io; -use std::mem; -use std::ptr; - -use Inner; -use cert_context::CertContext; - -lazy_static! { - static ref UNISP_NAME: Vec<u8> = um::schannel::UNISP_NAME.bytes().chain(Some(0)).collect(); -} - -/// The communication direction that an `SchannelCred` will support. -#[derive(Copy, Debug, Clone, PartialEq, Eq)] -pub enum Direction { - /// Server-side, inbound connections. - Inbound, - /// Client-side, outbound connections. - Outbound, -} - -/// Algorithms supported by Schannel. -// https://msdn.microsoft.com/en-us/library/windows/desktop/aa375549(v=vs.85).aspx -#[derive(Debug, Copy, Clone)] -#[repr(u32)] -pub enum Algorithm { - /// Advanced Encryption Standard (AES). - Aes = wincrypt::CALG_AES, - /// 128 bit AES. - Aes128 = wincrypt::CALG_AES_128, - /// 192 bit AES. - Aes192 = wincrypt::CALG_AES_192, - /// 256 bit AES. - Aes256 = wincrypt::CALG_AES_256, - /// Temporary algorithm identifier for handles of Diffie-Hellman–agreed keys. - AgreedkeyAny = wincrypt::CALG_AGREEDKEY_ANY, - /// An algorithm to create a 40-bit DES key that has parity bits and zeroed key bits to make - /// its key length 64 bits. - CylinkMek = wincrypt::CALG_CYLINK_MEK, - /// DES encryption algorithm. - Des = wincrypt::CALG_DES, - /// DESX encryption algorithm. - Desx = wincrypt::CALG_DESX, - /// Diffie-Hellman ephemeral key exchange algorithm. - DhEphem = wincrypt::CALG_DH_EPHEM, - /// Diffie-Hellman store and forward key exchange algorithm. - DhSf = wincrypt::CALG_DH_SF, - /// DSA public key signature algorithm. - DssSign = wincrypt::CALG_DSS_SIGN, - /// Elliptic curve Diffie-Hellman key exchange algorithm. - Ecdh = wincrypt::CALG_ECDH, - // https://github.com/retep998/wincrypt-rs/issues/287 - // /// Ephemeral elliptic curve Diffie-Hellman key exchange algorithm. - // EcdhEphem = wincrypt::CALG_ECDH_EPHEM, - /// Elliptic curve digital signature algorithm. - Ecdsa = wincrypt::CALG_ECDSA, - /// One way function hashing algorithm. - HashReplaceOwf = wincrypt::CALG_HASH_REPLACE_OWF, - /// Hughes MD5 hashing algorithm. - HughesMd5 = wincrypt::CALG_HUGHES_MD5, - /// HMAC keyed hash algorithm. - Hmac = wincrypt::CALG_HMAC, - /// MAC keyed hash algorithm. - Mac = wincrypt::CALG_MAC, - /// MD2 hashing algorithm. - Md2 = wincrypt::CALG_MD2, - /// MD4 hashing algorithm. - Md4 = wincrypt::CALG_MD4, - /// MD5 hashing algorithm. - Md5 = wincrypt::CALG_MD5, - /// No signature algorithm.. - NoSign = wincrypt::CALG_NO_SIGN, - /// RC2 block encryption algorithm. - Rc2 = wincrypt::CALG_RC2, - /// RC4 stream encryption algorithm. - Rc4 = wincrypt::CALG_RC4, - /// RC5 block encryption algorithm. - Rc5 = wincrypt::CALG_RC5, - /// RSA public key exchange algorithm. - RsaKeyx = wincrypt::CALG_RSA_KEYX, - /// RSA public key signature algorithm. - RsaSign = wincrypt::CALG_RSA_SIGN, - /// SHA hashing algorithm. - Sha1 = wincrypt::CALG_SHA1, - /// 256 bit SHA hashing algorithm. - Sha256 = wincrypt::CALG_SHA_256, - /// 384 bit SHA hashing algorithm. - Sha384 = wincrypt::CALG_SHA_384, - /// 512 bit SHA hashing algorithm. - Sha512 = wincrypt::CALG_SHA_512, - /// Triple DES encryption algorithm. - TripleDes = wincrypt::CALG_3DES, - /// Two-key triple DES encryption with effective key length equal to 112 bits. - TripleDes112 = wincrypt::CALG_3DES_112, - #[doc(hidden)] - __ForExtensibility, -} - -/// Protocols supported by Schannel. -#[derive(Debug, Copy, Clone)] -pub enum Protocol { - /// Secure Sockets Layer 3.0 - Ssl3, - /// Transport Layer Security 1.0 - Tls10, - /// Transport Layer Security 1.1 - Tls11, - /// Transport Layer Security 1.2 - Tls12, - #[doc(hidden)] - __ForExtensibility, -} - -impl Protocol { - fn dword(self, direction: Direction) -> winapi::DWORD { - match (self, direction) { - (Protocol::Ssl3, Direction::Inbound) => um::schannel::SP_PROT_SSL3_SERVER, - (Protocol::Tls10, Direction::Inbound) => um::schannel::SP_PROT_TLS1_0_SERVER, - (Protocol::Tls11, Direction::Inbound) => um::schannel::SP_PROT_TLS1_1_SERVER, - (Protocol::Tls12, Direction::Inbound) => um::schannel::SP_PROT_TLS1_2_SERVER, - (Protocol::Ssl3, Direction::Outbound) => um::schannel::SP_PROT_SSL3_CLIENT, - (Protocol::Tls10, Direction::Outbound) => um::schannel::SP_PROT_TLS1_0_CLIENT, - (Protocol::Tls11, Direction::Outbound) => um::schannel::SP_PROT_TLS1_1_CLIENT, - (Protocol::Tls12, Direction::Outbound) => um::schannel::SP_PROT_TLS1_2_CLIENT, - (Protocol::__ForExtensibility, _) => unreachable!(), - } - } -} - -/// A builder type for `SchannelCred`s. -#[derive(Default, Debug)] -pub struct Builder { - supported_algorithms: Option<Vec<Algorithm>>, - enabled_protocols: Option<Vec<Protocol>>, - certs: Vec<CertContext>, -} - -impl Builder { - /// Returns a new `Builder`. - pub fn new() -> Builder { - Builder::default() - } - - /// Sets the algorithms supported for credentials created from this builder. - pub fn supported_algorithms(&mut self, - supported_algorithms: &[Algorithm]) - -> &mut Builder { - assert!(supported_algorithms.iter() - .all(|a| { - match *a { - Algorithm::__ForExtensibility => false, - _ => true, - } - })); - self.supported_algorithms = Some(supported_algorithms.to_owned()); - self - } - - /// Sets the protocols enabled for credentials created from this builder. - pub fn enabled_protocols(&mut self, - enabled_protocols: &[Protocol]) - -> &mut Builder { - assert!(enabled_protocols.iter() - .all(|a| { - match *a { - Protocol::__ForExtensibility => false, - _ => true, - } - })); - self.enabled_protocols = Some(enabled_protocols.to_owned()); - self - } - - /// Add a certificate to get passed down when the credentials are acquired. - /// - /// Certificates passed here may specify a certificate that contains a - /// private key to be used in authenticating the application. Typically, - /// this is called once for each key exchange method supported by - /// servers. - /// - /// Clients often do not call this function and either depend on Schannel to - /// find an appropriate certificate or create a certificate later if needed. - pub fn cert(&mut self, cx: CertContext) -> &mut Builder { - self.certs.push(cx); - self - } - - /// Creates a new `SchannelCred`. - pub fn acquire(&self, direction: Direction) -> io::Result<SchannelCred> { - unsafe { - let mut handle = mem::zeroed(); - let mut cred_data: um::schannel::SCHANNEL_CRED = mem::zeroed(); - cred_data.dwVersion = um::schannel::SCHANNEL_CRED_VERSION; - cred_data.dwFlags = um::schannel::SCH_USE_STRONG_CRYPTO | um::schannel::SCH_CRED_NO_DEFAULT_CREDS; - if let Some(ref supported_algorithms) = self.supported_algorithms { - cred_data.cSupportedAlgs = supported_algorithms.len() as winapi::DWORD; - cred_data.palgSupportedAlgs = supported_algorithms.as_ptr() as *mut _; - } - if let Some(ref enabled_protocols) = self.enabled_protocols { - cred_data.grbitEnabledProtocols = enabled_protocols.iter() - .map(|p| p.dword(direction)) - .fold(0, |acc, p| acc | p); - } - let mut certs = self.certs.iter().map(|c| c.as_inner()).collect::<Vec<_>>(); - cred_data.cCreds = certs.len() as winapi::DWORD; - cred_data.paCred = certs.as_mut_ptr(); - - let direction = match direction { - Direction::Inbound => sspi::SECPKG_CRED_INBOUND, - Direction::Outbound => sspi::SECPKG_CRED_OUTBOUND, - }; - - match sspi::AcquireCredentialsHandleA(ptr::null_mut(), - UNISP_NAME.as_ptr() as *const _ as *mut _, - direction, - ptr::null_mut(), - &mut cred_data as *mut _ as *mut _, - None, - ptr::null_mut(), - &mut handle, - ptr::null_mut()) { - winerror::SEC_E_OK => Ok(SchannelCred(handle)), - err => Err(io::Error::from_raw_os_error(err as i32)), - } - } - } -} - -/// An SChannel credential. -pub struct SchannelCred(sspi::CredHandle); - -impl Drop for SchannelCred { - fn drop(&mut self) { - unsafe { - sspi::FreeCredentialsHandle(&mut self.0); - } - } -} - -impl Inner<sspi::CredHandle> for SchannelCred { - unsafe fn from_inner(inner: sspi::CredHandle) -> SchannelCred { - SchannelCred(inner) - } - - fn as_inner(&self) -> sspi::CredHandle { - self.0 - } - - fn get_mut(&mut self) -> &mut sspi::CredHandle { - &mut self.0 - } -} - -impl SchannelCred { - /// Returns a builder. - pub fn builder() -> Builder { - Builder::new() - } -} diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/security_context.rs cargo-0.26.0/vendor/schannel-0.1.10/src/security_context.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/security_context.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/security_context.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,107 +0,0 @@ -use winapi::shared::{sspi, winerror}; -use winapi::um::{minschannel}; -use std::mem; -use std::ptr; -use std::io; - -use {INIT_REQUESTS, Inner, secbuf, secbuf_desc}; -use cert_context::CertContext; -use context_buffer::ContextBuffer; - -use schannel_cred::SchannelCred; - -pub struct SecurityContext(sspi::CtxtHandle); - -impl Drop for SecurityContext { - fn drop(&mut self) { - unsafe { - sspi::DeleteSecurityContext(&mut self.0); - } - } -} - -impl Inner<sspi::CtxtHandle> for SecurityContext { - unsafe fn from_inner(inner: sspi::CtxtHandle) -> SecurityContext { - SecurityContext(inner) - } - - fn as_inner(&self) -> sspi::CtxtHandle { - self.0 - } - - fn get_mut(&mut self) -> &mut sspi::CtxtHandle { - &mut self.0 - } -} - -impl SecurityContext { - pub fn initialize(cred: &mut SchannelCred, - accept: bool, - domain: Option<&[u16]>) - -> io::Result<(SecurityContext, Option<ContextBuffer>)> { - unsafe { - let mut ctxt = mem::zeroed(); - - if accept { - // If we're performing an accept then we need to wait to call - // `AcceptSecurityContext` until we've actually read some data. - return Ok((SecurityContext(ctxt), None)) - } - - let domain = domain.map(|b| b.as_ptr() as *mut u16).unwrap_or(ptr::null_mut()); - - let mut outbuf = [secbuf(sspi::SECBUFFER_EMPTY, None)]; - let mut outbuf_desc = secbuf_desc(&mut outbuf); - - let mut attributes = 0; - - match sspi::InitializeSecurityContextW(cred.get_mut(), - ptr::null_mut(), - domain, - INIT_REQUESTS, - 0, - 0, - ptr::null_mut(), - 0, - &mut ctxt, - &mut outbuf_desc, - &mut attributes, - ptr::null_mut()) { - winerror::SEC_I_CONTINUE_NEEDED => { - Ok((SecurityContext(ctxt), Some(ContextBuffer(outbuf[0])))) - } - err => { - Err(io::Error::from_raw_os_error(err as i32)) - } - } - } - } - - pub fn stream_sizes(&mut self) -> io::Result<sspi::SecPkgContext_StreamSizes> { - unsafe { - let mut stream_sizes = mem::zeroed(); - let status = sspi::QueryContextAttributesW(&mut self.0, - sspi::SECPKG_ATTR_STREAM_SIZES, - &mut stream_sizes as *mut _ as *mut _); - if status == winerror::SEC_E_OK { - Ok(stream_sizes) - } else { - Err(io::Error::from_raw_os_error(status as i32)) - } - } - } - - pub fn remote_cert(&mut self) -> io::Result<CertContext> { - unsafe { - let mut cert_context = mem::zeroed(); - let status = sspi::QueryContextAttributesW(&mut self.0, - minschannel::SECPKG_ATTR_REMOTE_CERT_CONTEXT, - &mut cert_context as *mut _ as *mut _); - if status == winerror::SEC_E_OK { - Ok(CertContext::from_inner(cert_context)) - } else { - Err(io::Error::from_raw_os_error(status as i32)) - } - } - } -} diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/test.rs cargo-0.26.0/vendor/schannel-0.1.10/src/test.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/test.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/test.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,624 +0,0 @@ -use std::env; -use std::io::{self, Read, Write, Error}; -use std::mem; -use std::net::{TcpStream, TcpListener}; -use std::ptr; -use std::sync::{Once, ONCE_INIT}; -use std::thread; -use winapi::shared::minwindef as winapi; -use winapi::shared::{basetsd, ntdef, lmcons, winerror}; -use winapi::um::{minwinbase, sysinfoapi, timezoneapi, wincrypt}; - -use Inner; -use crypt_prov::{AcquireOptions, ProviderType}; -use cert_context::{CertContext, KeySpec, HashAlgorithm}; -use cert_store::{CertStore, Memory, CertAdd}; -use schannel_cred::{Direction, Protocol, Algorithm, SchannelCred}; -use tls_stream::{self, HandshakeError}; - -#[test] -fn basic() { - let creds = SchannelCred::builder().acquire(Direction::Outbound).unwrap(); - let stream = TcpStream::connect("google.com:443").unwrap(); - let mut stream = tls_stream::Builder::new() - .domain("google.com") - .connect(creds, stream) - .unwrap(); - stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); - let mut out = vec![]; - stream.read_to_end(&mut out).unwrap(); - assert!(out.starts_with(b"HTTP/1.0 200 OK") || out.starts_with(b"HTTP/1.0 302 Found")); - assert!(out.ends_with(b"</html>") || out.ends_with(b"</HTML>\r\n")); -} - -#[test] -fn invalid_algorithms() { - let creds = SchannelCred::builder() - .supported_algorithms(&[Algorithm::Rc2, Algorithm::Ecdsa]) - .acquire(Direction::Outbound); - assert_eq!(creds.err().unwrap().raw_os_error().unwrap(), - winerror::SEC_E_ALGORITHM_MISMATCH as i32); -} - -#[test] -fn valid_algorithms() { - let creds = SchannelCred::builder() - .supported_algorithms(&[Algorithm::Aes128, Algorithm::Ecdsa]) - .acquire(Direction::Outbound) - .unwrap(); - let stream = TcpStream::connect("google.com:443").unwrap(); - let mut stream = tls_stream::Builder::new() - .domain("google.com") - .connect(creds, stream) - .unwrap(); - stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); - let mut out = vec![]; - stream.read_to_end(&mut out).unwrap(); - assert!(out.starts_with(b"HTTP/1.0 200 OK") || out.starts_with(b"HTTP/1.0 302 Found")); - assert!(out.ends_with(b"</html>") || out.ends_with(b"</HTML>\r\n")); -} - -fn unwrap_handshake<S>(e: HandshakeError<S>) -> io::Error { - match e { - HandshakeError::Failure(e) => e, - HandshakeError::Interrupted(_) => panic!("not an I/O error"), - } -} - -#[test] -#[ignore] // google's inconsistent about disallowing sslv3 -fn invalid_protocol() { - let creds = SchannelCred::builder() - .enabled_protocols(&[Protocol::Ssl3]) - .acquire(Direction::Outbound) - .unwrap(); - let stream = TcpStream::connect("google.com:443").unwrap(); - let err = tls_stream::Builder::new() - .domain("google.com") - .connect(creds, stream) - .err() - .unwrap(); - let err = unwrap_handshake(err); - assert_eq!(err.raw_os_error().unwrap(), - winerror::SEC_E_UNSUPPORTED_FUNCTION as i32); -} - -#[test] -fn valid_protocol() { - let creds = SchannelCred::builder() - .enabled_protocols(&[Protocol::Tls12]) - .acquire(Direction::Outbound) - .unwrap(); - let stream = TcpStream::connect("google.com:443").unwrap(); - let mut stream = tls_stream::Builder::new() - .domain("google.com") - .connect(creds, stream) - .unwrap(); - stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); - let mut out = vec![]; - stream.read_to_end(&mut out).unwrap(); - assert!(out.starts_with(b"HTTP/1.0 200 OK") || out.starts_with(b"HTTP/1.0 302 Found")); - assert!(out.ends_with(b"</html>") || out.ends_with(b"</HTML>\r\n")); -} - -#[test] -fn expired_cert() { - let creds = SchannelCred::builder() - .acquire(Direction::Outbound) - .unwrap(); - let stream = TcpStream::connect("expired.badssl.com:443").unwrap(); - let err = tls_stream::Builder::new() - .domain("expired.badssl.com") - .connect(creds, stream) - .err() - .unwrap(); - let err = unwrap_handshake(err); - assert_eq!(err.raw_os_error().unwrap(), winerror::CERT_E_EXPIRED as i32); -} - -#[test] -fn self_signed_cert() { - let creds = SchannelCred::builder() - .acquire(Direction::Outbound) - .unwrap(); - let stream = TcpStream::connect("self-signed.badssl.com:443").unwrap(); - let err = tls_stream::Builder::new() - .domain("self-signed.badssl.com") - .connect(creds, stream) - .err() - .unwrap(); - let err = unwrap_handshake(err); - assert_eq!(err.raw_os_error().unwrap(), - winerror::CERT_E_UNTRUSTEDROOT as i32); -} - -#[test] -fn self_signed_cert_manual_trust() { - let cert = include_bytes!("../test/self-signed.badssl.com.cer"); - let mut store = Memory::new().unwrap(); - store.add_encoded_certificate(cert).unwrap(); - - let creds = SchannelCred::builder() - .acquire(Direction::Outbound) - .unwrap(); - let stream = TcpStream::connect("self-signed.badssl.com:443").unwrap(); - tls_stream::Builder::new() - .domain("self-signed.badssl.com") - .cert_store(store.into_store()) - .connect(creds, stream) - .unwrap(); -} - -#[test] -fn wrong_host_cert() { - let creds = SchannelCred::builder() - .acquire(Direction::Outbound) - .unwrap(); - let stream = TcpStream::connect("wrong.host.badssl.com:443").unwrap(); - let err = tls_stream::Builder::new() - .domain("wrong.host.badssl.com") - .connect(creds, stream) - .err() - .unwrap(); - let err = unwrap_handshake(err); - assert_eq!(err.raw_os_error().unwrap(), - winerror::CERT_E_CN_NO_MATCH as i32); -} - -#[test] -fn shutdown() { - let creds = SchannelCred::builder().acquire(Direction::Outbound).unwrap(); - let stream = TcpStream::connect("google.com:443").unwrap(); - let mut stream = tls_stream::Builder::new() - .domain("google.com") - .connect(creds, stream) - .unwrap(); - stream.shutdown().unwrap(); -} - -#[test] -fn validation_failure_is_permanent() { - let creds = SchannelCred::builder().acquire(Direction::Outbound).unwrap(); - let stream = TcpStream::connect("self-signed.badssl.com:443").unwrap(); - // temporarily switch to nonblocking to allow us to construct the stream - // without validating - stream.set_nonblocking(true).unwrap(); - let stream = tls_stream::Builder::new() - .domain("self-signed.badssl.com") - .connect(creds, stream); - let stream = match stream { - Err(HandshakeError::Interrupted(s)) => s, - _ => panic!(), - }; - stream.get_ref().set_nonblocking(false).unwrap(); - let err = unwrap_handshake(stream.handshake().err().unwrap()); - assert_eq!(err.raw_os_error().unwrap(), - winerror::CERT_E_UNTRUSTEDROOT as i32); -} - -#[test] -fn verify_callback_success() { - let creds = SchannelCred::builder() - .acquire(Direction::Outbound) - .unwrap(); - let stream = TcpStream::connect("self-signed.badssl.com:443").unwrap(); - let mut stream = tls_stream::Builder::new() - .domain("self-signed.badssl.com") - .verify_callback(|validation_result| { - assert!(validation_result.result().is_err()); - Ok(()) - }) - .connect(creds, stream) - .unwrap(); - stream.write_all(b"GET / HTTP/1.0\r\nHost: self-signed.badssl.com\r\n\r\n").unwrap(); - let mut out = vec![]; - stream.read_to_end(&mut out).unwrap(); - assert!(out.starts_with(b"HTTP/1.1 200 OK")); - assert!(out.ends_with(b"</html>\n")); -} - -#[test] -fn verify_callback_error() { - let creds = SchannelCred::builder() - .acquire(Direction::Outbound) - .unwrap(); - let stream = TcpStream::connect("google.com:443").unwrap(); - let err = tls_stream::Builder::new() - .domain("google.com") - .verify_callback(|validation_result| { - assert!(validation_result.result().is_ok()); - Err(io::Error::from_raw_os_error(winerror::CERT_E_UNTRUSTEDROOT)) - }) - .connect(creds, stream) - .err() - .unwrap(); - let err = unwrap_handshake(err); - assert_eq!(err.raw_os_error().unwrap(), - winerror::CERT_E_UNTRUSTEDROOT as i32); -} - -#[test] -fn verify_callback_gives_failed_cert() { - let creds = SchannelCred::builder() - .acquire(Direction::Outbound) - .unwrap(); - let stream = TcpStream::connect("self-signed.badssl.com:443").unwrap(); - let err = tls_stream::Builder::new() - .domain("self-signed.badssl.com") - .verify_callback(|validation_result| { - let expected_finger = vec!(100, 20, 80, 217, 74, 101, 250, 235, 59, 99, 16, 40, 216, 232, 108, 149, 67, 29, 184, 17); - assert_eq!(validation_result.failed_certificate().unwrap().fingerprint(HashAlgorithm::sha1()).unwrap(), expected_finger); - Err(io::Error::from_raw_os_error(winerror::CERT_E_UNTRUSTEDROOT)) - }) - .connect(creds, stream) - .err() - .unwrap(); - let err = unwrap_handshake(err); - assert_eq!(err.raw_os_error().unwrap(), - winerror::CERT_E_UNTRUSTEDROOT as i32); -} - -const FRIENDLY_NAME: &'static str = "schannel-rs localhost testing cert"; - -lazy_static! { - static ref szOID_RSA_SHA256RSA: Vec<u8> = - wincrypt::szOID_RSA_SHA256RSA.bytes().chain(Some(0)).collect(); -} - -fn install_certificate() -> io::Result<CertContext> { - unsafe { - let mut provider = 0; - let mut hkey = 0; - - let mut buffer = "schannel-rs test suite".encode_utf16() - .chain(Some(0)) - .collect::<Vec<_>>(); - let res = wincrypt::CryptAcquireContextW(&mut provider, - buffer.as_ptr(), - ptr::null_mut(), - wincrypt::PROV_RSA_FULL, - wincrypt::CRYPT_MACHINE_KEYSET); - if res != winapi::TRUE { - // create a new key container (since it does not exist) - let res = wincrypt::CryptAcquireContextW(&mut provider, - buffer.as_ptr(), - ptr::null_mut(), - wincrypt::PROV_RSA_FULL, - wincrypt::CRYPT_NEWKEYSET | wincrypt::CRYPT_MACHINE_KEYSET); - if res != winapi::TRUE { - return Err(Error::last_os_error()) - } - } - - // create a new keypair (RSA-2048) - let res = wincrypt::CryptGenKey(provider, - wincrypt::AT_SIGNATURE, - 0x0800<<16 | wincrypt::CRYPT_EXPORTABLE, - &mut hkey); - if res != winapi::TRUE { - return Err(Error::last_os_error()); - } - - // start creating the certificate - let name = "CN=localhost,O=schannel-rs,OU=schannel-rs,G=schannel_rs".encode_utf16() - .chain(Some(0)) - .collect::<Vec<_>>(); - let mut cname_buffer: [ntdef::WCHAR; lmcons::UNLEN as usize + 1] = mem::zeroed(); - let mut cname_len = cname_buffer.len() as winapi::DWORD; - let res = wincrypt::CertStrToNameW(wincrypt::X509_ASN_ENCODING, - name.as_ptr(), - wincrypt::CERT_X500_NAME_STR, - ptr::null_mut(), - cname_buffer.as_mut_ptr() as *mut u8, - &mut cname_len, - ptr::null_mut()); - if res != winapi::TRUE { - return Err(Error::last_os_error()); - } - - let mut subject_issuer = wincrypt::CERT_NAME_BLOB { - cbData: cname_len, - pbData: cname_buffer.as_ptr() as *mut u8, - }; - let mut key_provider = wincrypt::CRYPT_KEY_PROV_INFO { - pwszContainerName: buffer.as_mut_ptr(), - pwszProvName: ptr::null_mut(), - dwProvType: wincrypt::PROV_RSA_FULL, - dwFlags: wincrypt::CRYPT_MACHINE_KEYSET, - cProvParam: 0, - rgProvParam: ptr::null_mut(), - dwKeySpec: wincrypt::AT_SIGNATURE, - }; - let mut sig_algorithm = wincrypt::CRYPT_ALGORITHM_IDENTIFIER { - pszObjId: szOID_RSA_SHA256RSA.as_ptr() as *mut _, - Parameters: mem::zeroed(), - }; - let mut expiration_date: minwinbase::SYSTEMTIME = mem::zeroed(); - sysinfoapi::GetSystemTime(&mut expiration_date); - let mut file_time: winapi::FILETIME = mem::zeroed(); - let res = timezoneapi::SystemTimeToFileTime(&mut expiration_date, - &mut file_time); - if res != winapi::TRUE { - return Err(Error::last_os_error()); - } - let mut timestamp: u64 = file_time.dwLowDateTime as u64 | - (file_time.dwHighDateTime as u64) << 32; - // one day, timestamp unit is in 100 nanosecond intervals - timestamp += (1E9 as u64) / 100 * (60 * 60 * 24); - file_time.dwLowDateTime = timestamp as u32; - file_time.dwHighDateTime = (timestamp >> 32) as u32; - let res = timezoneapi::FileTimeToSystemTime(&file_time, - &mut expiration_date); - if res != winapi::TRUE { - return Err(Error::last_os_error()); - } - - // create a self signed certificate - let cert_context = wincrypt::CertCreateSelfSignCertificate(0 as basetsd::ULONG_PTR, - &mut subject_issuer, - 0, - &mut key_provider, - &mut sig_algorithm, - ptr::null_mut(), - &mut expiration_date, - ptr::null_mut()); - if cert_context.is_null() { - return Err(Error::last_os_error()); - } - let cert_context = CertContext::from_inner(cert_context); - try!(cert_context.set_friendly_name(FRIENDLY_NAME)); - - // install the certificate to the machine's local store - io::stdout().write_all(br#" - -The schannel-rs test suite is about to add a certificate to your set of root -and trusted certificates. This certificate should be for the domain "localhost" -with the description related to "schannel". This certificate is only valid for -one day and will be automatically deleted if you re-run the schannel-rs test -suite later. - -If you would rather not do this please cancel the addition and re-run the -test suite with SCHANNEL_RS_SKIP_SERVER_TESTS=1. - -"#).unwrap(); - try!(local_root_store().add_cert(&cert_context, CertAdd::ReplaceExisting)); - Ok(cert_context) - } -} - -fn local_root_store() -> CertStore { - if env::var("APPVEYOR").is_ok() { - CertStore::open_local_machine("Root").unwrap() - } else { - CertStore::open_current_user("Root").unwrap() - } -} - -fn localhost_cert() -> Option<CertContext> { - if env::var("SCHANNEL_RS_SKIP_SERVER_TESTS").is_ok() { - return None - } - - // Our tests need a certficiate that the system trusts to run with, and we - // do this by basically generating a certificate on the fly. This - // initialization block synchronizes tests to ensure that we only generate - // one certificate which is then used by all the tests. - // - // First we check to see if the root trust store already has one of our - // certificates, identified by the "friendly name" we set when the - // certificate was created. If it's expired, then we delete it and generate - // another. If none is found, we also generate another. - // - // Note that generating a certificate and adding it to the root trust store - // will likely trigger a prompt to the user asking if they want to do that, - // so we generate certificates that are valid for some amount of time so you - // don't have to hit the "OK" button each time you run `cargo test`. - // - // After the initialization is performed we just probe the root store again - // and find the certificate we added (or was already there). - static INIT: Once = ONCE_INIT; - INIT.call_once(|| { - for cert in local_root_store().certs() { - let name = match cert.friendly_name() { - Ok(name) => name, - Err(_) => continue, - }; - if name != FRIENDLY_NAME { - continue - } - if !cert.is_time_valid().unwrap() { - io::stdout().write_all(br#" - -The schannel-rs test suite is about to delete an old copy of one of its -certificates from your root trust store. This certificate was only valid for one -day and it is no longer needed. The host should be "localhost" and the -description should mention "schannel". - -"#).unwrap(); - cert.delete().unwrap(); - } else { - return - } - } - - install_certificate().unwrap(); - }); - - for cert in local_root_store().certs() { - let name = match cert.friendly_name() { - Ok(name) => name, - Err(_) => continue, - }; - if name == FRIENDLY_NAME { - return Some(cert) - } - } - - panic!("couldn't find a cert"); -} - -#[test] -fn accept_a_socket() { - let cert = match localhost_cert() { - Some(cert) => cert, - None => return, - }; - - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - let t = thread::spawn(move || { - let stream = TcpStream::connect(&addr).unwrap(); - let creds = SchannelCred::builder() - .acquire(Direction::Outbound).unwrap(); - let mut stream = tls_stream::Builder::new() - .domain("localhost") - .connect(creds, stream) - .unwrap(); - stream.write_all(&[1, 2, 3, 4]).unwrap(); - stream.flush().unwrap(); - assert_eq!(stream.read(&mut [0; 1024]).unwrap(), 4); - stream.shutdown().unwrap(); - }); - - let stream = listener.accept().unwrap().0; - let creds = SchannelCred::builder() - .cert(cert) - .acquire(Direction::Inbound) - .unwrap(); - let mut stream = tls_stream::Builder::new() - .accept(creds, stream) - .unwrap(); - assert_eq!(stream.read(&mut [0; 1024]).unwrap(), 4); - stream.write_all(&[1, 2, 3, 4]).unwrap(); - stream.flush().unwrap(); - let mut buf = [0; 1]; - assert_eq!(stream.read(&mut buf).unwrap(), 0); - - t.join().unwrap(); -} - -#[test] -fn accept_one_byte_at_a_time() { - let cert = match localhost_cert() { - Some(cert) => cert, - None => return, - }; - - #[derive(Debug)] - struct OneByteAtATime<S> { - inner: S, - } - - impl<S: Read> Read for OneByteAtATime<S> { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.inner.read(&mut buf[..1]) - } - } - - impl<S: Write> Write for OneByteAtATime<S> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.inner.write(&buf[..1]) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush() - } - } - - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - let t = thread::spawn(move || { - let stream = TcpStream::connect(&addr).unwrap(); - let creds = SchannelCred::builder() - .acquire(Direction::Outbound).unwrap(); - let mut stream = tls_stream::Builder::new() - .domain("localhost") - .connect(creds, OneByteAtATime { inner: stream }) - .unwrap(); - stream.write_all(&[1, 2, 3, 4]).unwrap(); - stream.flush().unwrap(); - assert_eq!(stream.read(&mut [0; 1024]).unwrap(), 4); - stream.shutdown().unwrap(); - }); - - let stream = listener.accept().unwrap().0; - let creds = SchannelCred::builder() - .cert(cert) - .acquire(Direction::Inbound) - .unwrap(); - let mut stream = tls_stream::Builder::new() - .accept(creds, OneByteAtATime { inner: stream }) - .unwrap(); - assert_eq!(stream.read(&mut [0; 1024]).unwrap(), 4); - stream.write_all(&[1, 2, 3, 4]).unwrap(); - stream.flush().unwrap(); - let mut buf = [0; 1]; - assert_eq!(stream.read(&mut buf).unwrap(), 0); - - t.join().unwrap(); -} - -#[test] -fn split_cert_key() { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let addr = listener.local_addr().unwrap(); - let t = thread::spawn(move || { - let cert = include_bytes!("../test/cert.der"); - let mut store = Memory::new().unwrap(); - store.add_encoded_certificate(cert).unwrap(); - let store = store.into_store(); - - let stream = TcpStream::connect(&addr).unwrap(); - let creds = SchannelCred::builder() - .acquire(Direction::Outbound).unwrap(); - let mut stream = tls_stream::Builder::new() - .domain("foobar.com") - .cert_store(store) - .connect(creds, stream) - .unwrap(); - stream.write_all(&[1, 2, 3, 4]).unwrap(); - stream.flush().unwrap(); - assert_eq!(stream.read(&mut [0; 1024]).unwrap(), 4); - stream.shutdown().unwrap(); - }); - - let cert = include_bytes!("../test/cert.der"); - let cert = CertContext::new(cert).unwrap(); - - let mut options = AcquireOptions::new(); - options.container("schannel-test"); - let type_ = ProviderType::rsa_full(); - - let mut container = match options.acquire(type_) { - Ok(container) => container, - Err(_) => options.new_keyset(true).acquire(type_).unwrap(), - }; - let key = include_bytes!("../test/key.key"); - container.import() - .import(key) - .unwrap(); - - cert.set_key_prov_info() - .container("schannel-test") - .type_(type_) - .keep_open(true) - .key_spec(KeySpec::key_exchange()) - .set() - .unwrap(); - - let stream = listener.accept().unwrap().0; - let creds = SchannelCred::builder() - .cert(cert) - .acquire(Direction::Inbound) - .unwrap(); - let mut stream = tls_stream::Builder::new() - .accept(creds, stream) - .unwrap(); - assert_eq!(stream.read(&mut [0; 1024]).unwrap(), 4); - stream.write_all(&[1, 2, 3, 4]).unwrap(); - stream.flush().unwrap(); - let mut buf = [0; 1]; - assert_eq!(stream.read(&mut buf).unwrap(), 0); - - t.join().unwrap(); -} diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/src/tls_stream.rs cargo-0.26.0/vendor/schannel-0.1.10/src/tls_stream.rs --- cargo-0.25.0/vendor/schannel-0.1.10/src/tls_stream.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/src/tls_stream.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,877 +0,0 @@ -//! Schannel TLS streams. -use std::any::Any; -use std::cmp; -use std::error::Error; -use std::fmt; -use std::io::{self, Read, BufRead, Write, Cursor}; -use std::mem; -use std::ptr; -use std::slice; -use std::sync::Arc; -use winapi::shared::minwindef as winapi; -use winapi::shared::{ntdef, sspi, winerror}; -use winapi::um::{self, wincrypt}; - -use {INIT_REQUESTS, ACCEPT_REQUESTS, Inner, secbuf, secbuf_desc}; -use cert_chain::{CertChain, CertChainContext}; -use cert_store::CertStore; -use cert_context::CertContext; -use security_context::SecurityContext; -use context_buffer::ContextBuffer; -use schannel_cred::SchannelCred; - -lazy_static! { - static ref szOID_PKIX_KP_SERVER_AUTH: Vec<u8> = - wincrypt::szOID_PKIX_KP_SERVER_AUTH.bytes().chain(Some(0)).collect(); - static ref szOID_SERVER_GATED_CRYPTO: Vec<u8> = - wincrypt::szOID_SERVER_GATED_CRYPTO.bytes().chain(Some(0)).collect(); - static ref szOID_SGC_NETSCAPE: Vec<u8> = - wincrypt::szOID_SGC_NETSCAPE.bytes().chain(Some(0)).collect(); -} - -/// A builder type for `TlsStream`s. -#[derive(Default)] -pub struct Builder { - domain: Option<Vec<u16>>, - verify_callback: Option<Arc<Fn(CertValidationResult) -> io::Result<()> + Sync + Send>>, - cert_store: Option<CertStore>, -} - -impl Builder { - /// Returns a new `Builder`. - pub fn new() -> Builder { - Builder::default() - } - - /// Sets the domain associated with connections created with this `Builder`. - /// - /// The domain will be used for Server Name Indication as well as - /// certificate validation. - pub fn domain(&mut self, domain: &str) -> &mut Builder { - self.domain = Some(domain.encode_utf16().chain(Some(0)).collect()); - self - } - - /// Set a verification callback to be used for connections created with this `Builder`. - /// - /// The callback is provided with an io::Result indicating if the (pre)validation was - /// successful. The Ok() variant indicates a successful validation while the Err() variant - /// contains the errorcode returned from the internal verification process. - /// The validated certificate, is accessible through the second argument of the closure. - pub fn verify_callback<F>(&mut self, callback: F) -> &mut Builder - where F: Fn(CertValidationResult) -> io::Result<()> + 'static + Sync + Send - { - self.verify_callback = Some(Arc::new(callback)); - self - } - - /// Specifies a custom certificate store which is later used when validating - /// a server's certificate. - /// - /// This option is only used for client connections and is used to construct - /// the certificate chain which the server's certificate is validated - /// against. - /// - /// Note that adding certificates here means that they are - /// implicitly trusted. - pub fn cert_store(&mut self, cert_store: CertStore) -> &mut Builder { - self.cert_store = Some(cert_store); - self - } - - /// Initialize a new TLS session where the stream provided will be - /// connecting to a remote TLS server. - /// - /// If the stream provided is a blocking stream then the entire handshake - /// will be performed if possible, but if the stream is in nonblocking mode - /// then a `HandshakeError::Interrupted` variant may be returned. This - /// type can then be extracted to later call - /// `MidHandshakeTlsStream::handshake` when data becomes available. - pub fn connect<S>(&mut self, - cred: SchannelCred, - stream: S) - -> Result<TlsStream<S>, HandshakeError<S>> - where S: Read + Write - { - self.initialize(cred, false, stream) - } - - /// Initialize a new TLS session where the stream provided will be - /// accepting a connection. - /// - /// This method will tweak the protocol for "who talks first" and also - /// currently disables validation of the client that's connecting to us. - /// - /// If the stream provided is a blocking stream then the entire handshake - /// will be performed if possible, but if the stream is in nonblocking mode - /// then a `HandshakeError::Interrupted` variant may be returned. This - /// type can then be extracted to later call - /// `MidHandshakeTlsStream::handshake` when data becomes available. - pub fn accept<S>(&mut self, - cred: SchannelCred, - stream: S) - -> Result<TlsStream<S>, HandshakeError<S>> - where S: Read + Write - { - self.initialize(cred, true, stream) - } - - fn initialize<S>(&mut self, - mut cred: SchannelCred, - accept: bool, - stream: S) - -> Result<TlsStream<S>, HandshakeError<S>> - where S: Read + Write - { - let domain = self.domain.as_ref().map(|s| &s[..]); - let (ctxt, buf) = match SecurityContext::initialize(&mut cred, - accept, - domain) { - Ok(pair) => pair, - Err(e) => return Err(HandshakeError::Failure(e)), - }; - - let stream = TlsStream { - cred: cred, - context: ctxt, - cert_store: self.cert_store.clone(), - domain: self.domain.clone(), - verify_callback: self.verify_callback.clone(), - stream: stream, - accept: accept, - accept_first: true, - state: State::Initializing { - needs_flush: false, - more_calls: true, - shutting_down: false, - validated: false, - }, - needs_read: 1, - dec_in: Cursor::new(Vec::new()), - enc_in: Cursor::new(Vec::new()), - out_buf: Cursor::new(buf.map(|b| b.to_owned()).unwrap_or(Vec::new())), - last_write_len: 0, - }; - - MidHandshakeTlsStream { - inner: stream, - }.handshake() - } -} - -enum State { - Initializing { - needs_flush: bool, - more_calls: bool, - shutting_down: bool, - validated: bool, - }, - Streaming { sizes: sspi::SecPkgContext_StreamSizes, }, - Shutdown, -} - -/// An Schannel TLS stream. -pub struct TlsStream<S> { - cred: SchannelCred, - context: SecurityContext, - cert_store: Option<CertStore>, - domain: Option<Vec<u16>>, - verify_callback: Option<Arc<Fn(CertValidationResult) -> io::Result<()> + Sync + Send>>, - stream: S, - state: State, - accept: bool, - accept_first: bool, - needs_read: usize, - // valid from position() to len() - dec_in: Cursor<Vec<u8>>, - // valid from 0 to position() - enc_in: Cursor<Vec<u8>>, - // valid from position() to len() - out_buf: Cursor<Vec<u8>>, - /// the (unencrypted) length of the last write call used to track writes - last_write_len: usize, -} - -/// ensures that a TlsStream is always Sync/Send -fn _is_sync() { - fn sync<T: Sync + Send>() {} - sync::<TlsStream<()>>(); -} - -/// A failure which can happen during the `Builder::initialize` phase, either an -/// I/O error or an intermediate stream which has not completed its handshake. -#[derive(Debug)] -pub enum HandshakeError<S> { - /// A fatal I/O error occurred - Failure(io::Error), - /// The stream connection is in progress, but the handshake is not completed - /// yet. - Interrupted(MidHandshakeTlsStream<S>), -} - -/// A struct used to wrap various cert chain validation results for callback processing. -pub struct CertValidationResult { - chain: CertChainContext, - res: i32, - chain_index: i32, - element_index: i32, -} - -impl CertValidationResult { - /// Returns the certificate that failed validation if applicable - pub fn failed_certificate(&self) -> Option<CertContext> { - if let Some(cert_chain) = self.chain.get_chain(self.chain_index as usize) { - return cert_chain.get(self.element_index as usize); - } - None - } - - /// Returns the final certificate chain in the certificate context if applicable - pub fn chain(&self) -> Option<CertChain> { - self.chain.final_chain() - } - - /// Returns the result of the built-in certificate verification process. - pub fn result(&self) -> io::Result<()> { - if self.res as u32 != winerror::ERROR_SUCCESS { - Err(io::Error::from_raw_os_error(self.res)) - } else { - Ok(()) - } - } -} - -impl<S: fmt::Debug + Any> Error for HandshakeError<S> { - fn description(&self) -> &str { - match *self { - HandshakeError::Failure(_) => "failed to perform handshake", - HandshakeError::Interrupted(_) => "interrupted performing handshake", - } - } - - fn cause(&self) -> Option<&Error> { - match *self { - HandshakeError::Failure(ref e) => Some(e), - HandshakeError::Interrupted(_) => None, - } - } -} - -impl<S: fmt::Debug + Any> fmt::Display for HandshakeError<S> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(f.write_str(self.description())); - if let Some(e) = self.cause() { - try!(write!(f, ": {}", e)); - } - Ok(()) - } -} - -/// A stream which has not yet completed its handshake. -#[derive(Debug)] -pub struct MidHandshakeTlsStream<S> { - inner: TlsStream<S>, -} - -impl<S> fmt::Debug for TlsStream<S> - where S: fmt::Debug -{ - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.debug_struct("TlsStream") - .field("stream", &self.stream) - .finish() - } -} - -impl<S> TlsStream<S> - where S: Read + Write -{ - /// Returns a reference to the wrapped stream. - pub fn get_ref(&self) -> &S { - &self.stream - } - - /// Returns a mutable reference to the wrapped stream. - pub fn get_mut(&mut self) -> &mut S { - &mut self.stream - } - - /// Returns a reference to the buffer of pending data. - /// - /// Like `BufRead::fill_buf` except that it will return an empty slice - /// rather than reading from the wrapped stream if there is no buffered - /// data. - pub fn get_buf(&self) -> &[u8] { - &self.dec_in.get_ref()[self.dec_in.position() as usize..] - } - - /// Shuts the TLS session down. - pub fn shutdown(&mut self) -> io::Result<()> { - match self.state { - State::Shutdown => return Ok(()), - State::Initializing { shutting_down: true, .. } => {} - _ => { - unsafe { - let mut token = um::schannel::SCHANNEL_SHUTDOWN; - let ptr = &mut token as *mut _ as *mut u8; - let size = mem::size_of_val(&token); - let token = slice::from_raw_parts_mut(ptr, size); - let mut buf = [secbuf(sspi::SECBUFFER_TOKEN, Some(token))]; - let mut desc = secbuf_desc(&mut buf); - - match sspi::ApplyControlToken(self.context.get_mut(), &mut desc) { - winerror::SEC_E_OK => {} - err => return Err(io::Error::from_raw_os_error(err as i32)), - } - } - - self.state = State::Initializing { - needs_flush: false, - more_calls: true, - shutting_down: true, - validated: false, - }; - self.needs_read = 0; - } - } - - self.initialize().map(|_| ()) - } - - fn step_initialize(&mut self) -> io::Result<()> { - unsafe { - let pos = self.enc_in.position() as usize; - let mut inbufs = [secbuf(sspi::SECBUFFER_TOKEN, - Some(&mut self.enc_in.get_mut()[..pos])), - secbuf(sspi::SECBUFFER_EMPTY, None)]; - let mut inbuf_desc = secbuf_desc(&mut inbufs); - - let mut outbufs = [secbuf(sspi::SECBUFFER_TOKEN, None), - secbuf(sspi::SECBUFFER_ALERT, None), - secbuf(sspi::SECBUFFER_EMPTY, None)]; - let mut outbuf_desc = secbuf_desc(&mut outbufs); - - let mut attributes = 0; - - let status = if self.accept { - let ptr = if self.accept_first { - ptr::null_mut() - } else { - self.context.get_mut() - }; - sspi::AcceptSecurityContext(self.cred.get_mut(), - ptr, - &mut inbuf_desc, - ACCEPT_REQUESTS, - 0, - self.context.get_mut(), - &mut outbuf_desc, - &mut attributes, - ptr::null_mut()) - } else { - let domain = self.domain - .as_ref() - .map(|b| b.as_ptr() as *mut u16) - .unwrap_or(ptr::null_mut()); - - sspi::InitializeSecurityContextW(self.cred.get_mut(), - self.context.get_mut(), - domain, - INIT_REQUESTS, - 0, - 0, - &mut inbuf_desc, - 0, - ptr::null_mut(), - &mut outbuf_desc, - &mut attributes, - ptr::null_mut()) - }; - - for buf in &outbufs[1..] { - if !buf.pvBuffer.is_null() { - sspi::FreeContextBuffer(buf.pvBuffer); - } - } - - match status { - winerror::SEC_I_CONTINUE_NEEDED => { - // Windows apparently doesn't like AcceptSecurityContext - // being called as if it were the second time unless the - // first call to AcceptSecurityContext succeeded with - // CONTINUE_NEEDED. - // - // In other words, if we were to set `accept_first` to - // `false` after the literal first call to - // `AcceptSecurityContext` while the call returned - // INCOMPLETE_MESSAGE, the next call would return an error. - // - // For that reason we only set `accept_first` to false here - // once we've actually successfully received the full - // "token" from the client. - self.accept_first = false; - let nread = if inbufs[1].BufferType == sspi::SECBUFFER_EXTRA { - self.enc_in.position() as usize - inbufs[1].cbBuffer as usize - } else { - self.enc_in.position() as usize - }; - let to_write = ContextBuffer(outbufs[0]); - - self.consume_enc_in(nread); - self.needs_read = (self.enc_in.position() == 0) as usize; - self.out_buf.get_mut().extend_from_slice(&to_write); - } - winerror::SEC_E_INCOMPLETE_MESSAGE => { - self.needs_read = if inbufs[1].BufferType == sspi::SECBUFFER_MISSING { - inbufs[1].cbBuffer as usize - } else { - 1 - }; - } - winerror::SEC_E_OK => { - let nread = if inbufs[1].BufferType == sspi::SECBUFFER_EXTRA { - self.enc_in.position() as usize - inbufs[1].cbBuffer as usize - } else { - self.enc_in.position() as usize - }; - let to_write = if outbufs[0].pvBuffer.is_null() { - None - } else { - Some(ContextBuffer(outbufs[0])) - }; - - self.consume_enc_in(nread); - self.needs_read = (self.enc_in.position() == 0) as usize; - if let Some(to_write) = to_write { - self.out_buf.get_mut().extend_from_slice(&to_write); - } - if self.enc_in.position() != 0 { - try!(self.decrypt()); - } - if let State::Initializing { ref mut more_calls, .. } = self.state { - *more_calls = false; - } - } - _ => { - return Err(io::Error::from_raw_os_error(status as i32)) - } - } - Ok(()) - } - } - - fn initialize(&mut self) -> io::Result<Option<sspi::SecPkgContext_StreamSizes>> { - loop { - match self.state { - State::Initializing { mut needs_flush, more_calls, shutting_down, validated } => { - if try!(self.write_out()) > 0 { - needs_flush = true; - if let State::Initializing { ref mut needs_flush, .. } = self.state { - *needs_flush = true; - } - } - - if needs_flush { - try!(self.stream.flush()); - if let State::Initializing { ref mut needs_flush, .. } = self.state { - *needs_flush = false; - } - } - - if !shutting_down && !validated { - // on the last call, we require a valid certificate - if try!(self.validate(!more_calls)) { - if let State::Initializing { ref mut validated, .. } = self.state { - *validated = true; - } - } - } - - if !more_calls { - self.state = if shutting_down { - State::Shutdown - } else { - State::Streaming { sizes: try!(self.context.stream_sizes()) } - }; - continue; - } - - if self.needs_read > 0 { - if try!(self.read_in()) == 0 { - return Err(io::Error::new(io::ErrorKind::UnexpectedEof, - "unexpected EOF during handshake")); - } - } - - try!(self.step_initialize()); - } - State::Streaming { sizes } => return Ok(Some(sizes)), - State::Shutdown => return Ok(None), - } - } - } - - /// Returns true when the certificate was succesfully verified - /// Returns false, when a verification isn't necessary (yet) - /// Returns an error when the verification failed - fn validate(&mut self, require_cert: bool) -> io::Result<bool> { - // If we're accepting connections then we don't perform any validation - // for the remote certificate, that's what they're doing! - if self.accept { - return Ok(false); - } - - let cert_context = match self.context.remote_cert() { - Err(_) if !require_cert => return Ok(false), - ret => try!(ret) - }; - - let cert_chain = unsafe { - let cert_store = self.cert_store - .as_ref() - .map(|s| s.as_inner()) - .unwrap_or(ptr::null_mut()); - - let flags = wincrypt::CERT_CHAIN_CACHE_END_CERT | - wincrypt::CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY | - wincrypt::CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT; - - let mut para: wincrypt::CERT_CHAIN_PARA = mem::zeroed(); - para.cbSize = mem::size_of_val(¶) as winapi::DWORD; - para.RequestedUsage.dwType = wincrypt::USAGE_MATCH_TYPE_OR; - - let mut identifiers = [szOID_PKIX_KP_SERVER_AUTH.as_ptr() as ntdef::LPSTR, - szOID_SERVER_GATED_CRYPTO.as_ptr() as ntdef::LPSTR, - szOID_SGC_NETSCAPE.as_ptr() as ntdef::LPSTR]; - para.RequestedUsage.Usage.cUsageIdentifier = identifiers.len() as winapi::DWORD; - para.RequestedUsage.Usage.rgpszUsageIdentifier = identifiers.as_mut_ptr(); - - let mut cert_chain = mem::zeroed(); - - let res = wincrypt::CertGetCertificateChain(ptr::null_mut(), - cert_context.as_inner(), - ptr::null_mut(), - cert_store, - &mut para, - flags, - ptr::null_mut(), - &mut cert_chain); - - if res == winapi::TRUE { - CertChainContext(cert_chain as *mut _) - } else { - return Err(io::Error::last_os_error()) - } - }; - - unsafe { - // check if we trust the root-CA explicitly - let mut para_flags = wincrypt::CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS; - if let Some(ref mut store) = self.cert_store { - if let Some(chain) = cert_chain.final_chain() { - // check if any cert of the chain is in the passed store (and therefore trusted) - if chain.certificates().any(|cert| store.certs().any(|root_cert| root_cert == cert)) { - para_flags |= wincrypt::CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG; - } - } - } - - let mut extra_para: wincrypt::SSL_EXTRA_CERT_CHAIN_POLICY_PARA = mem::zeroed(); - *extra_para.u.cbSize_mut() = mem::size_of_val(&extra_para) as winapi::DWORD; - extra_para.dwAuthType = wincrypt::AUTHTYPE_SERVER; - if let Some(ref mut name) = self.domain { - extra_para.pwszServerName = name.as_mut_ptr(); - } - - let mut para: wincrypt::CERT_CHAIN_POLICY_PARA = mem::zeroed(); - para.cbSize = mem::size_of_val(¶) as winapi::DWORD; - para.dwFlags = para_flags; - para.pvExtraPolicyPara = &mut extra_para as *mut _ as *mut _; - - let mut status: wincrypt::CERT_CHAIN_POLICY_STATUS = mem::zeroed(); - status.cbSize = mem::size_of_val(&status) as winapi::DWORD; - - let verify_chain_policy_structure = wincrypt::CERT_CHAIN_POLICY_SSL as ntdef::LPCSTR; - let res = wincrypt::CertVerifyCertificateChainPolicy(verify_chain_policy_structure, - cert_chain.0, - &mut para, - &mut status); - if res == winapi::FALSE { - return Err(io::Error::last_os_error()) - } - - let mut verify_result = if status.dwError != winerror::ERROR_SUCCESS { - Err(io::Error::from_raw_os_error(status.dwError as i32)) - } else { - Ok(()) - }; - - // check if there's a user-specified verify callback - if let Some(ref callback) = self.verify_callback { - verify_result = callback(CertValidationResult{ - chain: cert_chain, - res: status.dwError as i32, - chain_index: status.lChainIndex, - element_index: status.lElementIndex}); - } - try!(verify_result); - } - Ok(true) - } - - fn write_out(&mut self) -> io::Result<usize> { - let mut out = 0; - while self.out_buf.position() as usize != self.out_buf.get_ref().len() { - let position = self.out_buf.position() as usize; - let nwritten = try!(self.stream.write(&self.out_buf.get_ref()[position..])); - out += nwritten; - self.out_buf.set_position((position + nwritten) as u64); - } - - Ok(out) - } - - fn read_in(&mut self) -> io::Result<usize> { - let mut sum_nread = 0; - - while self.needs_read > 0 { - let existing_len = self.enc_in.position() as usize; - let min_len = cmp::max(cmp::max(1024, 2 * existing_len), self.needs_read); - if self.enc_in.get_ref().len() < min_len { - self.enc_in.get_mut().resize(min_len, 0); - } - let nread = { - let buf = &mut self.enc_in.get_mut()[existing_len..]; - try!(self.stream.read(buf)) - }; - self.enc_in.set_position((existing_len + nread) as u64); - self.needs_read = self.needs_read.saturating_sub(nread); - if nread == 0 { - break; - } - sum_nread += nread; - } - - Ok(sum_nread) - } - - fn consume_enc_in(&mut self, nread: usize) { - let size = self.enc_in.position() as usize; - assert!(size >= nread); - let count = size - nread; - - if count > 0 { - self.enc_in.get_mut().drain(..nread); - } - - self.enc_in.set_position(count as u64); - } - - fn decrypt(&mut self) -> io::Result<bool> { - unsafe { - let position = self.enc_in.position() as usize; - let mut bufs = [secbuf(sspi::SECBUFFER_DATA, - Some(&mut self.enc_in.get_mut()[..position])), - secbuf(sspi::SECBUFFER_EMPTY, None), - secbuf(sspi::SECBUFFER_EMPTY, None), - secbuf(sspi::SECBUFFER_EMPTY, None)]; - let mut bufdesc = secbuf_desc(&mut bufs); - - match sspi::DecryptMessage(self.context.get_mut(), - &mut bufdesc, - 0, - ptr::null_mut()) { - winerror::SEC_E_OK => { - let start = bufs[1].pvBuffer as usize - self.enc_in.get_ref().as_ptr() as usize; - let end = start + bufs[1].cbBuffer as usize; - self.dec_in.get_mut().clear(); - self.dec_in - .get_mut() - .extend_from_slice(&self.enc_in.get_ref()[start..end]); - self.dec_in.set_position(0); - - let nread = if bufs[3].BufferType == sspi::SECBUFFER_EXTRA { - self.enc_in.position() as usize - bufs[3].cbBuffer as usize - } else { - self.enc_in.position() as usize - }; - self.consume_enc_in(nread); - self.needs_read = (self.enc_in.position() == 0) as usize; - Ok(false) - } - winerror::SEC_E_INCOMPLETE_MESSAGE => { - self.needs_read = if bufs[1].BufferType == sspi::SECBUFFER_MISSING { - bufs[1].cbBuffer as usize - } else { - 1 - }; - Ok(false) - } - winerror::SEC_I_CONTEXT_EXPIRED => Ok(true), - winerror::SEC_I_RENEGOTIATE => { - self.state = State::Initializing { - needs_flush: false, - more_calls: true, - shutting_down: false, - validated: false, - }; - - let nread = if bufs[3].BufferType == sspi::SECBUFFER_EXTRA { - self.enc_in.position() as usize - bufs[3].cbBuffer as usize - } else { - self.enc_in.position() as usize - }; - self.consume_enc_in(nread); - self.needs_read = 0; - Ok(false) - } - e => Err(io::Error::from_raw_os_error(e as i32)), - } - } - } - - fn encrypt(&mut self, buf: &[u8], sizes: &sspi::SecPkgContext_StreamSizes) -> io::Result<()> { - assert!(buf.len() <= sizes.cbMaximumMessage as usize); - - unsafe { - let len = sizes.cbHeader as usize + buf.len() + sizes.cbTrailer as usize; - - if self.out_buf.get_ref().len() < len { - self.out_buf.get_mut().resize(len, 0); - } - - let message_start = sizes.cbHeader as usize; - self.out_buf - .get_mut()[message_start..message_start + buf.len()] - .clone_from_slice(buf); - - let mut bufs = { - let out_buf = self.out_buf.get_mut(); - let size = sizes.cbHeader as usize; - - let header = secbuf(sspi::SECBUFFER_STREAM_HEADER, - Some(&mut out_buf[..size])); - let data = secbuf(sspi::SECBUFFER_DATA, - Some(&mut out_buf[size..size + buf.len()])); - let trailer = secbuf(sspi::SECBUFFER_STREAM_TRAILER, - Some(&mut out_buf[size + buf.len()..])); - let empty = secbuf(sspi::SECBUFFER_EMPTY, None); - [header, data, trailer, empty] - }; - let mut bufdesc = secbuf_desc(&mut bufs); - - match sspi::EncryptMessage(self.context.get_mut(), 0, &mut bufdesc, 0) { - winerror::SEC_E_OK => { - let len = bufs[0].cbBuffer + bufs[1].cbBuffer + bufs[2].cbBuffer; - self.out_buf.get_mut().truncate(len as usize); - self.out_buf.set_position(0); - Ok(()) - } - err => Err(io::Error::from_raw_os_error(err as i32)), - } - } - } -} - -impl<S> MidHandshakeTlsStream<S> - where S: Read + Write, -{ - /// Returns a shared reference to the inner stream. - pub fn get_ref(&self) -> &S { - self.inner.get_ref() - } - - /// Returns a mutable reference to the inner stream. - pub fn get_mut(&mut self) -> &mut S { - self.inner.get_mut() - } - - /// Restarts the handshake process. - pub fn handshake(mut self) -> Result<TlsStream<S>, HandshakeError<S>> { - match self.inner.initialize() { - Ok(_) => Ok(self.inner), - Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { - Err(HandshakeError::Interrupted(self)) - } - Err(e) => Err(HandshakeError::Failure(e)), - } - } -} - -impl<S> Write for TlsStream<S> - where S: Read + Write -{ - /// In the case of a WouldBlock error, we expect another call - /// starting with the same input data - /// This is similar to the use of ACCEPT_MOVING_WRITE_BUFFER in openssl - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - let sizes = match try!(self.initialize()) { - Some(sizes) => sizes, - None => return Err(io::Error::from_raw_os_error(winerror::SEC_E_CONTEXT_EXPIRED as i32)), - }; - - // if we have pending output data, it must have been because a previous - // attempt to send this part of the data ran into an error. - if self.out_buf.position() == self.out_buf.get_ref().len() as u64 { - let len = cmp::min(buf.len(), sizes.cbMaximumMessage as usize); - try!(self.encrypt(&buf[..len], &sizes)); - self.last_write_len = len; - } - try!(self.write_out()); - - Ok(self.last_write_len) - } - - fn flush(&mut self) -> io::Result<()> { - // Make sure the write buffer is emptied - try!(self.write_out()); - self.stream.flush() - } -} - -impl<S> Read for TlsStream<S> - where S: Read + Write -{ - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - let nread = { - let read_buf = try!(self.fill_buf()); - let nread = cmp::min(buf.len(), read_buf.len()); - buf[..nread].copy_from_slice(&read_buf[..nread]); - nread - }; - self.consume(nread); - Ok(nread) - } -} - -impl<S> BufRead for TlsStream<S> - where S: Read + Write -{ - fn fill_buf(&mut self) -> io::Result<&[u8]> { - while self.get_buf().is_empty() { - if let None = try!(self.initialize()) { - break; - } - - if self.needs_read > 0 { - if try!(self.read_in()) == 0 { - break; - } - self.needs_read = 0; - } - - let eof = try!(self.decrypt()); - if eof { - break; - } - } - - Ok(self.get_buf()) - } - - fn consume(&mut self, amt: usize) { - let pos = self.dec_in.position() + amt as u64; - assert!(pos <= self.dec_in.get_ref().len() as u64); - self.dec_in.set_position(pos); - } -} Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/schannel-0.1.10/test/cert.der and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/schannel-0.1.10/test/cert.der differ diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/test/cert.pem cargo-0.26.0/vendor/schannel-0.1.10/test/cert.pem --- cargo-0.25.0/vendor/schannel-0.1.10/test/cert.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/test/cert.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDGzCCAgMCCQCHcfe97pgvpTANBgkqhkiG9w0BAQsFADBFMQswCQYDVQQGEwJB -VTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0 -cyBQdHkgTHRkMB4XDTE2MDgxNDE3MDAwM1oXDTI2MDgxMjE3MDAwM1owWjELMAkG -A1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0 -IFdpZGdpdHMgUHR5IEx0ZDETMBEGA1UEAwwKZm9vYmFyLmNvbTCCASIwDQYJKoZI -hvcNAQEBBQADggEPADCCAQoCggEBAKj0JYxEsxejUIX+I5GH0Hg2G0kX/y1H0+Ub -3mw2/Ja5BD/yN96/7zMSumXF8uS3SkmpyiJkbyD01TSRTqjlP7/VCBlyUIChlpLQ -mrGaijZiT/VCyPXqmcwFzXS5IOTpX1olJfW8rA41U1LCIcDUyFf6LtZ/v8rSeKr6 -TuE6SGV4WRaBm1SrjWBeHVV866CRrtSS1ieT2asFsAyOZqWhk2fakwwBDFWDhOGI -ubfO+5aq9cBJbNRlzsgB3UZs3gC0O6GzbnZ6oT0TiJMeTsXXjABLUlaq/rrqFF4Y -euZkkbHTFBMz288PUc3m3ZTcpN+E7+ZOUBRZXKD20K07NugqCzUCAwEAATANBgkq -hkiG9w0BAQsFAAOCAQEASvYHuIl5C0NHBELPpVHNuLbQsDQNKVj3a54+9q1JkiMM -6taEJYfw7K1Xjm4RoiFSHpQBh+PWZS3hToToL2Zx8JfMR5MuAirdPAy1Sia/J/qE -wQdJccqmvuLkLTSlsGbEJ/LUUgOAgrgHOZM5lUgIhCneA0/dWJ3PsN0zvn69/faY -oo1iiolWiIHWWBUSdr3jM2AJaVAsTmLh00cKaDNk37JB940xConBGSl98JPrNrf9 -dUAiT0iIBngDBdHnn/yTj+InVEFyZSKrNtiDSObFHxPcxGteHNrCPJdP1e+GqkHp -HJMRZVCQpSMzvHlofHSNgzWV1MX5h1CP4SGZdBDTfA== ------END CERTIFICATE----- Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/schannel-0.1.10/test/identity.p12 and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/schannel-0.1.10/test/identity.p12 differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/schannel-0.1.10/test/key.key and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/schannel-0.1.10/test/key.key differ diff -Nru cargo-0.25.0/vendor/schannel-0.1.10/test/key.pem cargo-0.26.0/vendor/schannel-0.1.10/test/key.pem --- cargo-0.25.0/vendor/schannel-0.1.10/test/key.pem 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.10/test/key.pem 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ ------BEGIN PRIVATE KEY----- -MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCo9CWMRLMXo1CF -/iORh9B4NhtJF/8tR9PlG95sNvyWuQQ/8jfev+8zErplxfLkt0pJqcoiZG8g9NU0 -kU6o5T+/1QgZclCAoZaS0Jqxmoo2Yk/1Qsj16pnMBc10uSDk6V9aJSX1vKwONVNS -wiHA1MhX+i7Wf7/K0niq+k7hOkhleFkWgZtUq41gXh1VfOugka7UktYnk9mrBbAM -jmaloZNn2pMMAQxVg4ThiLm3zvuWqvXASWzUZc7IAd1GbN4AtDuhs252eqE9E4iT -Hk7F14wAS1JWqv666hReGHrmZJGx0xQTM9vPD1HN5t2U3KTfhO/mTlAUWVyg9tCt -OzboKgs1AgMBAAECggEBAKLj6IOJBKXolczpzb8UkyAjAkGBektcseV07gelJ/fk -3z0LuWPv5p12E/HlXB24vU2x/ikUbbP3eMsawRzDEahQqmNmPEkYAYUAy/Qpi9GN -DYvn3LqDec4jVgeQKS+p9H2DzUpTogp8zR2//yzbuWBg2+F//xh7vU0S0RQCziPM -x7RSBgbhxSfChfEJbS2sDnzfh0jRQmoY95iFv7puet1FJtzdZ4fgCd1RqmC2lFM5 -H0eZtN/Cz19lieVs0b996DErdEBqClVZO00eYbRozCDaBzRU3ybB/dMrGJxhkkXm -wb3kWMtziH9qOYsostuHIFu8eKFLloKxFnq2R4DGxOECgYEA2KUIZISOeGJSBcLJ -JAUK2gvgXPNo4HHWIwOA9xeN3ZJlsnPlffXQNnm6t1st1V2gfMm9I2n0m/F0y2B/ -n/XGSa8bghfPA9l0c2h58lkL3JQJR/paa8ycTz+YZPrznEyN7Qa0RrJXUvZv9lQL -Hc3+FHcSHgMqDV2f2bHAEu9YGi0CgYEAx6VEIPNvrHFgjo/jk1RTuk+m0xEWQsZL -Cs+izQMr2TaeJn8LG+93AvFuYn0J0nT3WuStLPrUg8i4IhSS6lf1tId5ivIZPm4r -YwMyblBJXhnHbk7Uqodjfw/3s6V2HAu++B7hTdyVr9DFuST9uv4m8bkPV8rfX1jE -I2rAPVWvgikCgYB+wNAQP547wQrMZBLbCDg5KwmyWJfb+b6X7czexOEz6humNTjo -YZHYzY/5B1fhpk3ntQD8X1nGg5caBvOk21+QbOtjShrM3cXMYCw5JvBRtitX+Zo9 -yBEMLOE0877ki8XeEDYZxu5gk98d+D4oygUGZEQtWxyXhVepPt5qNa8OYQKBgQDH -RVgZI6KFlqzv3wMh3PutbS9wYQ+9GrtwUQuIYe/0YSW9+vSVr5E0qNKrD28sV39F -hBauXLady0yvB6YUrjMbPFW+sCMuQzyfGWPO4+g3OrfqjFiM1ZIkE0YEU9Tt7XNx -qTDtTI1D7bhNMnTnniI1B6ge0und+3XafAThs5L48QKBgQCTTpfqMt8kU3tcI9sf -0MK03y7kA76d5uw0pZbWFy7KI4qnzWutCzb+FMPWWsoFtLJLPZy//u/ZCUVFVa4d -0Y/ASNQIESVPXFLAltlLo4MSmsg1vCBsbviEEaPeEjvMrgki93pYtd/aOSgkYC1T -mEq154s5rmqh+h+XRIf7Au0SLw== ------END PRIVATE KEY----- Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/schannel-0.1.10/test/self-signed.badssl.com.cer and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/schannel-0.1.10/test/self-signed.badssl.com.cer differ diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/appveyor.yml cargo-0.26.0/vendor/schannel-0.1.11/appveyor.yml --- cargo-0.25.0/vendor/schannel-0.1.11/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,26 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + VERSION: nightly + - TARGET: i686-pc-windows-msvc + VERSION: nightly + - TARGET: x86_64-pc-windows-gnu + VERSION: nightly + - TARGET: i686-pc-windows-gnu + VERSION: 1.10.0 + access_token: + secure: ZxcrtxQXwszRYNN6c1ZIagczEqzmQQZeYHY58izcmF0jdq/cptxJvFUoVxDmnoqj +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-${env:VERSION}-${env:TARGET}.exe" -FileName "rust-nightly.exe" + - ps: .\rust-nightly.exe /VERYSILENT /NORESTART /DIR="C:\rust" | Out-Null + - ps: $env:PATH="$env:PATH;C:\rust\bin" + - rustc -vV + - cargo -vV + - echo install + +build: off + +test_script: + # TODO remove this loop when server 2016 lands on appveyor; related to https://github.com/steffengy/schannel-rs/issues/8 + - set RUST_BACKTRACE=1 + - ps: for($i=1; $i -le 3; $i++) { cmd /c "cargo test 2>&1"; if ($?) { break } } diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/.cargo-checksum.json cargo-0.26.0/vendor/schannel-0.1.11/.cargo-checksum.json --- cargo-0.25.0/vendor/schannel-0.1.11/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"fbaffce35eb61c5b00846e73128b0cd62717e7c0ec46abbec132370d013975b4"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/Cargo.toml cargo-0.26.0/vendor/schannel-0.1.11/Cargo.toml --- cargo-0.25.0/vendor/schannel-0.1.11/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "schannel" +version = "0.1.11" +authors = ["Steven Fackler <sfackler@gmail.com>", "Steffen Butzer <steffen.butzer@outlook.com>"] +description = "Schannel bindings for rust, allowing SSL/TLS (e.g. https) without openssl" +documentation = "https://docs.rs/schannel/0/x86_64-pc-windows-gnu/schannel/" +readme = "README.md" +keywords = ["windows", "schannel", "tls", "ssl", "https"] +license = "MIT" +repository = "https://github.com/steffengy/schannel-rs" +[dependencies.lazy_static] +version = "1.0" + +[dependencies.winapi] +version = "0.3" +features = ["lmcons", "minschannel", "securitybaseapi", "schannel", "sysinfoapi", "timezoneapi", "winbase", "wincrypt", "winerror"] diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/LICENSE.md cargo-0.26.0/vendor/schannel-0.1.11/LICENSE.md --- cargo-0.25.0/vendor/schannel-0.1.11/LICENSE.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/LICENSE.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,7 @@ +Copyright (c) 2015 steffengy + +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. diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/README.md cargo-0.26.0/vendor/schannel-0.1.11/README.md --- cargo-0.25.0/vendor/schannel-0.1.11/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,6 @@ +schannel-rs [![Build status](https://ci.appveyor.com/api/projects/status/vefyauaf0oj10swu/branch/master?svg=true)](https://ci.appveyor.com/project/steffengy/schannel-rs/branch/master) +===== + +[Documentation](https://docs.rs/schannel/0/x86_64-pc-windows-gnu/schannel/) + +Rust bindings to the Windows SChannel APIs providing TLS client and server functionality. diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/cert_chain.rs cargo-0.26.0/vendor/schannel-0.1.11/src/cert_chain.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/cert_chain.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/cert_chain.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,139 @@ +//! Bindings to winapi's certificate-chain related APIs. + +use std::mem; +use std::slice; +use winapi::um::wincrypt; + +use cert_context::CertContext; +use Inner; + +/// A certificate chain context (consisting of multiple chains) +pub struct CertChainContext(pub wincrypt::PCERT_CHAIN_CONTEXT); + +unsafe impl Sync for CertChainContext {} +unsafe impl Send for CertChainContext {} + +impl Clone for CertChainContext { + fn clone(&self) -> Self { + let rced = unsafe { + wincrypt::CertDuplicateCertificateChain(self.0) as *mut _ + }; + CertChainContext(rced) + } +} + +impl Drop for CertChainContext { + fn drop(&mut self) { + unsafe { + wincrypt::CertFreeCertificateChain(self.0); + } + } +} + +impl CertChainContext { + /// Get the final (for a successful verification this means successful) certificate chain + /// + /// https://msdn.microsoft.com/de-de/library/windows/desktop/aa377182(v=vs.85).aspx + /// rgpChain[cChain - 1] is the final chain + pub fn final_chain(&self) -> Option<CertChain> { + if let Some(chain) = self.chains().last(){ + return Some(CertChain(chain.0, self.clone())); + } + None + } + + /// Retrieves the specified chain from the context. + pub fn get_chain(&self, index :usize) -> Option<CertChain> { + let cert_chain = unsafe { + let cert_chain = *self.0; + if index >= cert_chain.cChain as usize { + None + } else { + let chain_slice = slice::from_raw_parts( + cert_chain.rgpChain as *mut wincrypt::PCERT_SIMPLE_CHAIN, + cert_chain.cChain as usize); + Some(CertChain(chain_slice[index], self.clone())) + } + }; + return cert_chain; + } + + /// Return an iterator over all certificate chains in this context + pub fn chains(&self) -> CertificateChains { + CertificateChains { + context: self, + idx: 0 + } + } +} + +/// A (simple) certificate chain +pub struct CertChain(wincrypt::PCERT_SIMPLE_CHAIN, CertChainContext); + +impl CertChain { + /// Returns the number of certificates in the chain + pub fn len(&self) -> usize { + unsafe { + (*self.0).cElement as usize + } + } + + /// Get the n-th certificate from the current chain + pub fn get(&self, idx: usize) -> Option<CertContext> { + let elements = unsafe { + let cert_chain = *self.0; + slice::from_raw_parts( + cert_chain.rgpElement as *mut &mut wincrypt::CERT_CHAIN_ELEMENT, + cert_chain.cElement as usize) + }; + elements.get(idx).map(|el| { + let cert = unsafe { + CertContext::from_inner(el.pCertContext) + }; + let rc_cert = cert.clone(); + mem::forget(cert); + rc_cert + }) + } + + /// Return an iterator over all certificates in this chain + pub fn certificates(&self) -> Certificates { + Certificates { + chain: self, + idx: 0, + } + } +} + + +/// An iterator that iterates over all chains in a context +pub struct CertificateChains<'a> { + context: &'a CertChainContext, + idx: usize, +} + +impl<'a> Iterator for CertificateChains<'a> { + type Item = CertChain; + + fn next(&mut self) -> Option<CertChain> { + let idx = self.idx; + self.idx += 1; + self.context.get_chain(idx) + } +} + +/// An iterator that iterates over all certificates in a chain +pub struct Certificates<'a> { + chain: &'a CertChain, + idx: usize, +} + +impl<'a> Iterator for Certificates<'a> { + type Item = CertContext; + + fn next(&mut self) -> Option<CertContext> { + let idx = self.idx; + self.idx += 1; + self.chain.get(idx) + } +} diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/cert_context.rs cargo-0.26.0/vendor/schannel-0.1.11/src/cert_context.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/cert_context.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/cert_context.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,640 @@ +//! Bindings to winapi's `PCCERT_CONTEXT` APIs. + +use std::ffi::{CStr, OsString}; +use std::io; +use std::mem; +use std::os::windows::prelude::*; +use std::ptr; +use std::slice; +use winapi::shared::minwindef as winapi; +use winapi::shared::ntdef; +use winapi::shared::winerror; +use winapi::um::wincrypt; + +use Inner; +use ncrypt_key::NcryptKey; +use crypt_prov::{CryptProv, ProviderType}; +use cert_store::CertStore; + +/// A supported hashing algorithm +pub struct HashAlgorithm(winapi::DWORD, usize); + +#[allow(missing_docs)] +impl HashAlgorithm { + pub fn md5() -> HashAlgorithm { + HashAlgorithm(wincrypt::CALG_MD5, 16) + } + + pub fn sha1() -> HashAlgorithm{ + HashAlgorithm(wincrypt::CALG_SHA1, 20) + } + + pub fn sha256() -> HashAlgorithm { + HashAlgorithm(wincrypt::CALG_SHA_256, 32) + } + + pub fn sha384() -> HashAlgorithm { + HashAlgorithm(wincrypt::CALG_SHA_384, 48) + } + + pub fn sha512() -> HashAlgorithm { + HashAlgorithm(wincrypt::CALG_SHA_512, 64) + } +} + +/// Wrapper of a winapi certificate, or a `PCCERT_CONTEXT`. +#[derive(Debug)] +pub struct CertContext(wincrypt::PCCERT_CONTEXT); + +unsafe impl Sync for CertContext {} +unsafe impl Send for CertContext {} + +impl Drop for CertContext { + fn drop(&mut self) { + unsafe { + wincrypt::CertFreeCertificateContext(self.0); + } + } +} + +impl Clone for CertContext { + fn clone(&self) -> CertContext { + unsafe { CertContext(wincrypt::CertDuplicateCertificateContext(self.0)) } + } +} + +inner!(CertContext, wincrypt::PCCERT_CONTEXT); + +impl CertContext { + /// Decodes a DER-formatted X509 certificate. + pub fn new(data: &[u8]) -> io::Result<CertContext> { + let ret = unsafe { + wincrypt::CertCreateCertificateContext(wincrypt::X509_ASN_ENCODING | + wincrypt::PKCS_7_ASN_ENCODING, + data.as_ptr(), + data.len() as winapi::DWORD) + }; + if ret.is_null() { + Err(io::Error::last_os_error()) + } else { + Ok(CertContext(ret)) + } + } + + /// Get certificate in binary DER form + pub fn to_der<'a>(&'a self) -> &'a [u8] { + self.get_encoded_bytes() + } + + /// Decodes a PEM-formatted X509 certificate. + pub fn from_pem(pem: &str) -> io::Result<CertContext> { + unsafe { + assert!(pem.len() <= winapi::DWORD::max_value() as usize); + + let mut len = 0; + let ok = wincrypt::CryptStringToBinaryA(pem.as_ptr() as ntdef::LPCSTR, + pem.len() as winapi::DWORD, + wincrypt::CRYPT_STRING_BASE64HEADER, + ptr::null_mut(), + &mut len, + ptr::null_mut(), + ptr::null_mut()); + if ok != winapi::TRUE { + return Err(io::Error::last_os_error()); + } + + let mut buf = vec![0; len as usize]; + let ok = wincrypt::CryptStringToBinaryA(pem.as_ptr() as ntdef::LPCSTR, + pem.len() as winapi::DWORD, + wincrypt::CRYPT_STRING_BASE64HEADER, + buf.as_mut_ptr(), + &mut len, + ptr::null_mut(), + ptr::null_mut()); + if ok != winapi::TRUE { + return Err(io::Error::last_os_error()); + } + + CertContext::new(&buf) + } + } + + /// Get certificate as PEM-formatted X509 certificate. + pub fn to_pem(&self) -> io::Result<String> { + unsafe { + let mut len = 0; + let ok = wincrypt::CryptBinaryToStringA( + (*self.0).pbCertEncoded, + (*self.0).cbCertEncoded, + wincrypt::CRYPT_STRING_BASE64HEADER, + ptr::null_mut(), + &mut len, + ); + if ok != winapi::TRUE { + return Err(io::Error::last_os_error()); + } + + let mut buf = vec![0; len as usize]; + let ok = wincrypt::CryptBinaryToStringA( + (*self.0).pbCertEncoded, + (*self.0).cbCertEncoded, + wincrypt::CRYPT_STRING_BASE64HEADER, + buf.as_mut_ptr(), + &mut len, + ); + if ok != winapi::TRUE { + return Err(io::Error::last_os_error()); + } + + Ok(CStr::from_ptr(buf.as_ptr()).to_string_lossy().into_owned()) + } + } + + /// Returns a hash of this certificate + pub fn fingerprint(&self, alg: HashAlgorithm) -> io::Result<Vec<u8>> { + unsafe { + let mut buf = vec![0u8; alg.1]; + let mut len = buf.len() as winapi::DWORD; + + let ret = wincrypt::CryptHashCertificate(0, + alg.0, + 0, + (*self.0).pbCertEncoded, + (*self.0).cbCertEncoded, + buf.as_mut_ptr(), + &mut len); + + if ret != winapi::TRUE { + return Err(io::Error::last_os_error()); + } + Ok(buf) + } + } + + /// Returns the sha1 hash of this certificate + /// + /// The sha1 is returned as a 20-byte array representing the bits of the + /// sha1 hash. + #[deprecated(note = "please use fingerprint instead")] + pub fn sha1(&self) -> io::Result<[u8; 20]> { + let mut out = [0u8; 20]; + out.copy_from_slice(&try!(self.fingerprint(HashAlgorithm::sha1()))); + Ok(out) + } + + /// Returns the `<SIGNATURE>/<HASH>` string representing the certificate + /// signature. + /// + /// The `<SIGNATURE>` value identifies the CNG public key + /// algorithm. The `<HASH>` value identifies the CNG hash algorithm. + /// + /// Common examples are: + /// + /// * `RSA/SHA1` + /// * `RSA/SHA256` + /// * `ECDSA/SHA256` + pub fn sign_hash_algorithms(&self) -> io::Result<String> { + self.get_string(wincrypt::CERT_SIGN_HASH_CNG_ALG_PROP_ID) + } + + /// Returns the signature hash. + pub fn signature_hash(&self) -> io::Result<Vec<u8>> { + self.get_bytes(wincrypt::CERT_SIGNATURE_HASH_PROP_ID) + } + + /// Returns the property displayed by the certificate UI. This property + /// allows the user to describe the certificate's use. + pub fn description(&self) -> io::Result<Vec<u8>> { + self.get_bytes(wincrypt::CERT_DESCRIPTION_PROP_ID) + } + + /// Returns a string that contains the display name for the certificate. + pub fn friendly_name(&self) -> io::Result<String> { + self.get_string(wincrypt::CERT_FRIENDLY_NAME_PROP_ID) + } + + /// Configures the string that contains the display name for this + /// certificate. + pub fn set_friendly_name(&self, name: &str) -> io::Result<()> { + self.set_string(wincrypt::CERT_FRIENDLY_NAME_PROP_ID, name) + } + + /// Verifies the time validity of this certificate relative to the system's + /// current time. + pub fn is_time_valid(&self) -> io::Result<bool> { + let ret = unsafe { wincrypt::CertVerifyTimeValidity(ptr::null_mut(), (*self.0).pCertInfo) }; + Ok(ret == 0) + } + + /// Returns a builder used to acquire the private key corresponding to this certificate. + pub fn private_key<'a>(&'a self) -> AcquirePrivateKeyOptions<'a> { + AcquirePrivateKeyOptions { + cert: self, + flags: 0, + } + } + + /// Deletes this certificate from its certificate store. + pub fn delete(self) -> io::Result<()> { + unsafe { + let ret = wincrypt::CertDeleteCertificateFromStore(self.0); + mem::forget(self); + if ret == winapi::TRUE { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + } + + /// Returns a builder used to set the private key associated with this certificate. + pub fn set_key_prov_info<'a>(&'a self) -> SetKeyProvInfo<'a> { + SetKeyProvInfo { + cert: self, + container: None, + provider: None, + type_: 0, + flags: 0, + key_spec: 0, + } + } + + /// Returns the valid uses for this certificate + pub fn valid_uses(&self) -> io::Result<ValidUses> { + unsafe { + let mut buf_len = 0; + let ok = wincrypt::CertGetEnhancedKeyUsage(self.0, 0, ptr::null_mut(), &mut buf_len); + + if ok != winapi::TRUE { + return Err(io::Error::last_os_error()); + } + + let mut buf = vec![0u8; buf_len as usize]; + let cert_enhkey_usage = buf.as_mut_ptr() as *mut wincrypt::CERT_ENHKEY_USAGE; + + let ok = wincrypt::CertGetEnhancedKeyUsage(self.0, 0, cert_enhkey_usage, &mut buf_len); + if ok != winapi::TRUE { + return Err(io::Error::last_os_error()); + } + + let use_cnt = (*cert_enhkey_usage).cUsageIdentifier; + if use_cnt == 0 { + let last_error = io::Error::last_os_error(); + match last_error.raw_os_error() { + Some(winerror::CRYPT_E_NOT_FOUND) => return Ok(ValidUses::All), + Some(0) => (), + _ => return Err(last_error), + }; + } + + let mut oids: Vec<String> = Vec::with_capacity(use_cnt as usize); + for i in 0..use_cnt { + let oid_ptr = (*cert_enhkey_usage).rgpszUsageIdentifier; + oids.push( + CStr::from_ptr(*(oid_ptr.offset(i as isize))) + .to_string_lossy() + .into_owned(), + ); + } + Ok(ValidUses::Oids(oids)) + } + } + + /// For a remote certificate, returns a certificate store containing any intermediate + /// certificates provided by the remote sender. + pub fn cert_store(&self) -> Option<CertStore> { + unsafe { + let chain = (*self.0).hCertStore; + if chain.is_null() { + None + } else { + Some(CertStore::from_inner(wincrypt::CertDuplicateStore(chain))) + } + } + } + + fn get_encoded_bytes<'a>(&'a self) -> &'a [u8] { + unsafe { + let cert_ctx = *self.0; + slice::from_raw_parts(cert_ctx.pbCertEncoded, cert_ctx.cbCertEncoded as usize) + } + } + + fn get_bytes(&self, prop: winapi::DWORD) -> io::Result<Vec<u8>> { + unsafe { + let mut len = 0; + let ret = + wincrypt::CertGetCertificateContextProperty(self.0, prop, ptr::null_mut(), &mut len); + if ret != winapi::TRUE { + return Err(io::Error::last_os_error()); + } + + let mut buf = vec![0u8; len as usize]; + let ret = wincrypt::CertGetCertificateContextProperty(self.0, + prop, + buf.as_mut_ptr() as winapi::LPVOID, + &mut len); + if ret != winapi::TRUE { + return Err(io::Error::last_os_error()); + } + Ok(buf) + } + } + + fn get_string(&self, prop: winapi::DWORD) -> io::Result<String> { + unsafe { + let mut len = 0; + let ret = + wincrypt::CertGetCertificateContextProperty(self.0, prop, ptr::null_mut(), &mut len); + if ret != winapi::TRUE { + return Err(io::Error::last_os_error()); + } + + // Divide by 2 b/c `len` is the byte length, but we're allocating + // u16 pairs which are 2 bytes each. + let amt = (len / 2) as usize; + let mut buf = vec![0u16; amt]; + let ret = wincrypt::CertGetCertificateContextProperty(self.0, + prop, + buf.as_mut_ptr() as winapi::LPVOID, + &mut len); + if ret != winapi::TRUE { + return Err(io::Error::last_os_error()); + } + + // Chop off the trailing nul byte + Ok(OsString::from_wide(&buf[..amt - 1]).into_string().unwrap()) + } + } + + fn set_string(&self, prop: winapi::DWORD, s: &str) -> io::Result<()> { + unsafe { + let data = s.encode_utf16().chain(Some(0)).collect::<Vec<_>>(); + let data = wincrypt::CRYPT_DATA_BLOB { + cbData: (data.len() * 2) as winapi::DWORD, + pbData: data.as_ptr() as *mut _, + }; + let ret = wincrypt::CertSetCertificateContextProperty(self.0, + prop, + 0, + &data as *const _ as *const _); + if ret != winapi::TRUE { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } + } + } +} + +impl PartialEq for CertContext { + fn eq(&self, other: &CertContext) -> bool { + self.get_encoded_bytes() == other.get_encoded_bytes() + } +} + +/// A builder type for certificate private key lookup. +pub struct AcquirePrivateKeyOptions<'a> { + cert: &'a CertContext, + flags: winapi::DWORD, +} + +impl<'a> AcquirePrivateKeyOptions<'a> { + /// If set, the certificate's public key will be compared with the private key to ensure a + /// match. + pub fn compare_key(&mut self, compare_key: bool) -> &mut AcquirePrivateKeyOptions<'a> { + self.flag(wincrypt::CRYPT_ACQUIRE_COMPARE_KEY_FLAG, compare_key) + } + + /// If set, the lookup will not display any user interface, even if that causes the lookup to + /// fail. + pub fn silent(&mut self, silent: bool) -> &mut AcquirePrivateKeyOptions<'a> { + self.flag(wincrypt::CRYPT_ACQUIRE_SILENT_FLAG, silent) + } + + fn flag(&mut self, flag: winapi::DWORD, set: bool) -> &mut AcquirePrivateKeyOptions<'a> { + if set { + self.flags |= flag; + } else { + self.flags &= !flag; + } + self + } + + /// Acquires the private key handle. + pub fn acquire(&self) -> io::Result<PrivateKey> { + unsafe { + let flags = self.flags | wincrypt::CRYPT_ACQUIRE_ALLOW_NCRYPT_KEY_FLAG; + let mut handle = 0; + let mut spec = 0; + let mut free = winapi::FALSE; + let res = wincrypt::CryptAcquireCertificatePrivateKey(self.cert.0, + flags, + ptr::null_mut(), + &mut handle, + &mut spec, + &mut free); + if res != winapi::TRUE { + return Err(io::Error::last_os_error()); + } + assert!(free == winapi::TRUE); + if spec & wincrypt::CERT_NCRYPT_KEY_SPEC != 0 { + Ok(PrivateKey::NcryptKey(NcryptKey::from_inner(handle))) + } else { + Ok(PrivateKey::CryptProv(CryptProv::from_inner(handle))) + } + } + } +} + +/// The private key associated with a certificate context. +pub enum PrivateKey { + /// A CryptoAPI provider. + CryptProv(CryptProv), + /// A CNG provider. + NcryptKey(NcryptKey), +} + +/// A builder used to set the private key associated with a certificate. +pub struct SetKeyProvInfo<'a> { + cert: &'a CertContext, + container: Option<Vec<u16>>, + provider: Option<Vec<u16>>, + type_: winapi::DWORD, + flags: winapi::DWORD, + key_spec: winapi::DWORD, +} + +impl<'a> SetKeyProvInfo<'a> { + /// The name of the key container. + /// + /// If `type_` is not provided, this specifies the name of the key withing + /// the CNG key storage provider. + pub fn container(&mut self, container: &str) -> &mut SetKeyProvInfo<'a> { + self.container = Some(container.encode_utf16().chain(Some(0)).collect()); + self + } + + /// The name of the CSP. + /// + /// If `type_` is not provided, this contains the name of the CNG key + /// storage provider. + pub fn provider(&mut self, provider: &str) -> &mut SetKeyProvInfo<'a> { + self.provider = Some(provider.encode_utf16().chain(Some(0)).collect()); + self + } + + /// Sets the CSP type. + /// + /// If not provided, the key container is one of the CNG key storage + /// providers. + pub fn type_(&mut self, type_: ProviderType) -> &mut SetKeyProvInfo<'a> { + self.type_ = type_.as_raw(); + self + } + + /// If set, the handle to the key provider can be kept open for subsequent + /// calls to cryptographic functions. + pub fn keep_open(&mut self, keep_open: bool) -> &mut SetKeyProvInfo<'a> { + self.flag(wincrypt::CERT_SET_KEY_PROV_HANDLE_PROP_ID, keep_open) + } + + /// If set, the key container contains machine keys. + pub fn machine_keyset(&mut self, machine_keyset: bool) -> &mut SetKeyProvInfo<'a> { + self.flag(wincrypt::CRYPT_MACHINE_KEYSET, machine_keyset) + } + + /// If set, the key container will attempt to open keys without any user + /// interface prompts. + pub fn silent(&mut self, silent: bool) -> &mut SetKeyProvInfo<'a> { + self.flag(wincrypt::CRYPT_SILENT, silent) + } + + fn flag(&mut self, flag: winapi::DWORD, on: bool) -> &mut SetKeyProvInfo<'a> { + if on { + self.flags |= flag; + } else { + self.flags &= !flag; + } + self + } + + /// The specification of the private key to retrieve. + pub fn key_spec(&mut self, key_spec: KeySpec) -> &mut SetKeyProvInfo<'a> { + self.key_spec = key_spec.0; + self + } + + /// Sets the private key for this certificate. + pub fn set(&mut self) -> io::Result<()> { + unsafe { + let container = self.container.as_ref().map(|s| s.as_ptr()).unwrap_or(ptr::null()); + let provider = self.provider.as_ref().map(|s| s.as_ptr()).unwrap_or(ptr::null()); + + let info = wincrypt::CRYPT_KEY_PROV_INFO { + pwszContainerName: container as *mut _, + pwszProvName: provider as *mut _, + dwProvType: self.type_, + dwFlags: self.flags, + cProvParam: 0, + rgProvParam: ptr::null_mut(), + dwKeySpec: self.key_spec, + }; + + let res = + wincrypt::CertSetCertificateContextProperty(self.cert.0, + wincrypt::CERT_KEY_PROV_INFO_PROP_ID, + 0, + &info as *const _ as *const _); + if res == winapi::TRUE { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + } +} + +/// The specification of a private key. +#[derive(Copy, Clone)] +pub struct KeySpec(winapi::DWORD); + +impl KeySpec { + /// A key used to encrypt/decrypt session keys. + pub fn key_exchange() -> KeySpec { + KeySpec(wincrypt::AT_KEYEXCHANGE) + } + + /// A key used to create and verify digital signatures. + pub fn signature() -> KeySpec { + KeySpec(wincrypt::AT_SIGNATURE) + } +} + +/// Valid uses of a Certificate - All, or specific OIDs +pub enum ValidUses { + /// Certificate is valid for all uses + All, + + /// Certificate is valid for uses specified. No entries means that the certificate + /// has no valid uses. + Oids(Vec<String>), +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn decode() { + let der = include_bytes!("../test/cert.der"); + let pem = include_str!("../test/cert.pem"); + + let der = CertContext::new(der).unwrap(); + let pem = CertContext::from_pem(pem).unwrap(); + assert_eq!(der, pem); + } + + #[test] + fn certcontext_to_der() { + let der = include_bytes!("../test/cert.der"); + let cert = CertContext::new(der).unwrap(); + let der2 = CertContext::to_der(&cert); + assert_eq!(der as &[u8], der2); + } + + #[test] + fn certcontext_to_pem() { + let der = include_bytes!("../test/cert.der"); + let pem1 = include_str!("../test/cert.pem").replace("\r", ""); + + let der = CertContext::new(der).unwrap(); + let pem2 = CertContext::to_pem(&der).unwrap().replace("\r", ""); + assert_eq!(pem1, pem2); + } + + #[test] + fn fingerprint() { + let der = include_bytes!("../test/cert.der"); + let pem = include_str!("../test/cert.pem"); + + let der = CertContext::new(der).unwrap(); + let pem = CertContext::from_pem(pem).unwrap(); + + let hash = der.fingerprint(HashAlgorithm::sha1()).unwrap(); + assert_eq!(hash, vec![‎ + 0x59, 0x17, 0x2D, 0x93, 0x13, 0xE8, 0x44, 0x59, 0xBC, 0xFF, + 0x27, 0xF9, 0x67, 0xE7, 0x9E, 0x6E, 0x92, 0x17, 0xE5, 0x84 + ]); + assert_eq!(hash, pem.fingerprint(HashAlgorithm::sha1()).unwrap()); + + let hash = der.fingerprint(HashAlgorithm::sha256()).unwrap(); + assert_eq!(hash, vec![ + 0x47, 0x12, 0xB9, 0x39, 0xFB, 0xCB, 0x42, 0xA6, 0xB5, 0x10, + 0x1B, 0x42, 0x13, 0x9A, 0x25, 0xB1, 0x4F, 0x81, 0xB4, 0x18, + 0xFA, 0xCA, 0xBD, 0x37, 0x87, 0x46, 0xF1, 0x2F, 0x85, 0xCC, + 0x65, 0x44 + ]); + assert_eq!(hash, pem.fingerprint(HashAlgorithm::sha256()).unwrap()); + } +} diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/cert_store.rs cargo-0.26.0/vendor/schannel-0.1.11/src/cert_store.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/cert_store.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/cert_store.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,446 @@ +//! Bindings to winapi's certificate-store related APIs. + +use std::cmp; +use std::ffi::OsStr; +use std::fmt; +use std::io; +use std::mem; +use std::os::windows::prelude::*; +use std::ptr; +use winapi::shared::minwindef as winapi; +use winapi::shared::ntdef; +use winapi::um::wincrypt; + +use cert_context::CertContext; +use ctl_context::CtlContext; + +use Inner; + +/// Representation of certificate store on Windows, wrapping a `HCERTSTORE`. +pub struct CertStore(wincrypt::HCERTSTORE); + +unsafe impl Sync for CertStore {} +unsafe impl Send for CertStore {} + +impl fmt::Debug for CertStore { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("CertStore").finish() + } +} + +impl Drop for CertStore { + fn drop(&mut self) { + unsafe { + wincrypt::CertCloseStore(self.0, 0); + } + } +} + +impl Clone for CertStore { + fn clone(&self) -> CertStore { + unsafe { CertStore(wincrypt::CertDuplicateStore(self.0)) } + } +} + +inner!(CertStore, wincrypt::HCERTSTORE); + +/// Argument to the `add_cert` function indicating how a certificate should be +/// added to a `CertStore`. +pub enum CertAdd { + /// The function makes no check for an existing matching certificate or link + /// to a matching certificate. A new certificate is always added to the + /// store. This can lead to duplicates in a store. + Always = wincrypt::CERT_STORE_ADD_ALWAYS as isize, + + /// If a matching certificate or a link to a matching certificate exists, + /// the operation fails. + New = wincrypt::CERT_STORE_ADD_NEW as isize, + + /// If a matching certificate or a link to a matching certificate exists and + /// the NotBefore time of the existing context is equal to or greater than + /// the NotBefore time of the new context being added, the operation fails. + /// + /// If the NotBefore time of the existing context is less than the NotBefore + /// time of the new context being added, the existing certificate or link is + /// deleted and a new certificate is created and added to the store. If a + /// matching certificate or a link to a matching certificate does not exist, + /// a new link is added. + Newer = wincrypt::CERT_STORE_ADD_NEWER as isize, + + /// If a matching certificate or a link to a matching certificate exists and + /// the NotBefore time of the existing context is equal to or greater than + /// the NotBefore time of the new context being added, the operation fails. + /// + /// If the NotBefore time of the existing context is less than the NotBefore + /// time of the new context being added, the existing context is deleted + /// before creating and adding the new context. The new added context + /// inherits properties from the existing certificate. + NewerInheritProperties = wincrypt::CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES as isize, + + /// If a link to a matching certificate exists, that existing certificate or + /// link is deleted and a new certificate is created and added to the store. + /// If a matching certificate or a link to a matching certificate does not + /// exist, a new link is added. + ReplaceExisting = wincrypt::CERT_STORE_ADD_REPLACE_EXISTING as isize, + + /// If a matching certificate exists in the store, the existing context is + /// not replaced. The existing context inherits properties from the new + /// certificate. + ReplaceExistingInheritProperties = + wincrypt::CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES as isize, + + /// If a matching certificate or a link to a matching certificate exists, + /// that existing certificate or link is used and properties from the + /// new certificate are added. The function does not fail, but it does + /// not add a new context. The existing context is duplicated and returned. + /// + /// If a matching certificate or a link to a matching certificate does + /// not exist, a new certificate is added. + UseExisting = wincrypt::CERT_STORE_ADD_USE_EXISTING as isize, +} + +impl CertStore { + /// Opens up the specified key store within the context of the current user. + /// + /// Known valid values for `which` are "Root" and "My". + pub fn open_current_user(which: &str) -> io::Result<CertStore> { + unsafe { + let data = OsStr::new(which) + .encode_wide() + .chain(Some(0)) + .collect::<Vec<_>>(); + let store = wincrypt::CertOpenStore(wincrypt::CERT_STORE_PROV_SYSTEM_W as ntdef::LPCSTR, + 0, + 0, + wincrypt::CERT_SYSTEM_STORE_CURRENT_USER, + data.as_ptr() as *mut _); + if store.is_null() { + Err(io::Error::last_os_error()) + } else { + Ok(CertStore(store)) + } + } + } + + /// Opens up the specified key store within the context of the local + /// machine. + /// + /// Known valid values for `which` are "Root" and "My". + pub fn open_local_machine(which: &str) -> io::Result<CertStore> { + unsafe { + let data = OsStr::new(which) + .encode_wide() + .chain(Some(0)) + .collect::<Vec<_>>(); + let store = wincrypt::CertOpenStore(wincrypt::CERT_STORE_PROV_SYSTEM_W as ntdef::LPCSTR, + 0, + 0, + wincrypt::CERT_SYSTEM_STORE_LOCAL_MACHINE, + data.as_ptr() as *mut _); + if store.is_null() { + Err(io::Error::last_os_error()) + } else { + Ok(CertStore(store)) + } + } + } + + /// Imports a PKCS#12-encoded key/certificate pair, returned as a + /// `CertStore` instance. + /// + /// The password must also be provided to decrypt the encoded data. + pub fn import_pkcs12(data: &[u8], + password: Option<&str>) + -> io::Result<CertStore> { + unsafe { + let mut blob = wincrypt::CRYPT_INTEGER_BLOB { + cbData: data.len() as winapi::DWORD, + pbData: data.as_ptr() as *mut u8, + }; + let password = password.map(|s| { + OsStr::new(s).encode_wide() + .chain(Some(0)) + .collect::<Vec<_>>() + }); + let password = password.as_ref().map(|s| s.as_ptr()); + let password = password.unwrap_or(ptr::null()); + let res = wincrypt::PFXImportCertStore(&mut blob, + password, + 0); + if res.is_null() { + Err(io::Error::last_os_error()) + } else { + Ok(CertStore(res)) + } + } + } + + /// Returns an iterator over the certificates in this certificate store. + pub fn certs(&self) -> Certs { + Certs { store: self, cur: None } + } + + /// Adds a certificate context to this store. + /// + /// This function will add the certificate specified in `cx` to this store. + /// A copy of the added certificate is returned. + pub fn add_cert(&mut self, + cx: &CertContext, + how: CertAdd) -> io::Result<CertContext> { + unsafe { + let how = how as winapi::DWORD; + let mut ret = ptr::null(); + let res = wincrypt::CertAddCertificateContextToStore(self.0, + cx.as_inner(), + how, + &mut ret); + if res != winapi::TRUE { + Err(io::Error::last_os_error()) + } else { + Ok(CertContext::from_inner(ret)) + } + } + } + + /// Exports this certificate store as a PKCS#12-encoded blob. + /// + /// The password specified will be the password used to unlock the returned + /// data. + pub fn export_pkcs12(&self, password: &str) -> io::Result<Vec<u8>> { + unsafe { + let password = password.encode_utf16().chain(Some(0)).collect::<Vec<_>>(); + let mut blob = wincrypt::CRYPT_DATA_BLOB { + cbData: 0, + pbData: 0 as *mut _, + }; + let res = wincrypt::PFXExportCertStore(self.0, + &mut blob, + password.as_ptr(), + wincrypt::EXPORT_PRIVATE_KEYS); + if res != winapi::TRUE { + return Err(io::Error::last_os_error()) + } + let mut ret = Vec::with_capacity(blob.cbData as usize); + blob.pbData = ret.as_mut_ptr(); + let res = wincrypt::PFXExportCertStore(self.0, + &mut blob, + password.as_ptr(), + wincrypt::EXPORT_PRIVATE_KEYS); + if res != winapi::TRUE { + return Err(io::Error::last_os_error()) + } + ret.set_len(blob.cbData as usize); + Ok(ret) + } + } +} + +/// An iterator over the certificates contained in a `CertStore`, returned by +/// `CertStore::iter` +pub struct Certs<'a> { + store: &'a CertStore, + cur: Option<CertContext>, +} + +impl<'a> Iterator for Certs<'a> { + type Item = CertContext; + + fn next(&mut self) -> Option<CertContext> { + unsafe { + let cur = self.cur.take().map(|p| { + let ptr = p.as_inner(); + mem::forget(p); + ptr + }); + let cur = cur.unwrap_or(ptr::null_mut()); + let next = wincrypt::CertEnumCertificatesInStore(self.store.0, cur); + + if next.is_null() { + self.cur = None; + None + } else { + let next = CertContext::from_inner(next); + self.cur = Some(next.clone()); + Some(next) + } + } + } +} + +/// A builder type for imports of PKCS #12 archives. +#[derive(Default)] +pub struct PfxImportOptions { + password: Option<Vec<u16>>, + flags: winapi::DWORD, +} + +impl PfxImportOptions { + /// Returns a new `PfxImportOptions` with default settings. + pub fn new() -> PfxImportOptions { + PfxImportOptions::default() + } + + /// Sets the password to be used to decrypt the archive. + pub fn password(&mut self, password: &str) -> &mut PfxImportOptions { + self.password = Some(password.encode_utf16().chain(Some(0)).collect()); + self + } + + /// If set, the private key in the archive will not be persisted. + /// + /// If not set, private keys are persisted on disk and must be manually deleted. + pub fn no_persist_key(&mut self, no_persist_key: bool) -> &mut PfxImportOptions { + self.flag(wincrypt::PKCS12_NO_PERSIST_KEY, no_persist_key) + } + + /// If set, all extended properties of the certificate will be imported. + pub fn include_extended_properties(&mut self, + include_extended_properties: bool) + -> &mut PfxImportOptions { + self.flag(wincrypt::PKCS12_INCLUDE_EXTENDED_PROPERTIES, include_extended_properties) + } + + fn flag(&mut self, flag: winapi::DWORD, set: bool) -> &mut PfxImportOptions { + if set { + self.flags |= flag; + } else { + self.flags &= !flag; + } + self + } + + /// Imports certificates from a PKCS #12 archive, returning a `CertStore` containing them. + pub fn import(&self, data: &[u8]) -> io::Result<CertStore> { + unsafe { + let mut blob = wincrypt::CRYPT_DATA_BLOB { + cbData: cmp::min(data.len(), winapi::DWORD::max_value() as usize) as winapi::DWORD, + pbData: data.as_ptr() as *const _ as *mut _, + }; + let password = self.password.as_ref().map_or(ptr::null(), |p| p.as_ptr()); + + let store = wincrypt::PFXImportCertStore(&mut blob, password, self.flags); + if store.is_null() { + return Err(io::Error::last_os_error()); + } + Ok(CertStore(store)) + } + } +} + +/// Representation of an in-memory certificate store. +/// +/// Internally this contains a `CertStore` which this type can be converted to. +pub struct Memory(CertStore); + +impl Memory { + /// Creates a new in-memory certificate store which certificates and CTLs + /// can be added to. + /// + /// Initially the returned certificate store contains no certificates. + pub fn new() -> io::Result<Memory> { + unsafe { + let store = wincrypt::CertOpenStore(wincrypt::CERT_STORE_PROV_MEMORY as ntdef::LPCSTR, + 0, + 0, + 0, + ptr::null_mut()); + if store.is_null() { + Err(io::Error::last_os_error()) + } else { + Ok(Memory(CertStore(store))) + } + } + } + + /// Adds a new certificate to this memory store. + /// + /// For example the bytes could be a DER-encoded certificate. + pub fn add_encoded_certificate(&mut self, cert: &[u8]) -> io::Result<CertContext> { + unsafe { + let mut cert_context = ptr::null(); + + let res = wincrypt::CertAddEncodedCertificateToStore((self.0).0, + wincrypt::X509_ASN_ENCODING | + wincrypt::PKCS_7_ASN_ENCODING, + cert.as_ptr() as *const _, + cert.len() as winapi::DWORD, + wincrypt::CERT_STORE_ADD_ALWAYS, + &mut cert_context); + if res == winapi::TRUE { + Ok(CertContext::from_inner(cert_context)) + } else { + Err(io::Error::last_os_error()) + } + } + } + + /// Adds a new CTL to this memory store, in its encoded form. + /// + /// This can be created through the `ctl_context::Builder` type. + pub fn add_encoded_ctl(&mut self, ctl: &[u8]) -> io::Result<CtlContext> { + unsafe { + let mut ctl_context = ptr::null(); + + let res = wincrypt::CertAddEncodedCTLToStore((self.0).0, + wincrypt::X509_ASN_ENCODING | + wincrypt::PKCS_7_ASN_ENCODING, + ctl.as_ptr() as *const _, + ctl.len() as winapi::DWORD, + wincrypt::CERT_STORE_ADD_ALWAYS, + &mut ctl_context); + if res == winapi::TRUE { + Ok(CtlContext::from_inner(ctl_context)) + } else { + Err(io::Error::last_os_error()) + } + } + } + + /// Consumes this memory store, returning the underlying `CertStore`. + pub fn into_store(self) -> CertStore { + self.0 + } +} + +#[cfg(test)] +mod test { + use super::*; + use ctl_context::CtlContext; + + #[test] + fn load() { + let cert = include_bytes!("../test/cert.der"); + let mut store = Memory::new().unwrap(); + store.add_encoded_certificate(cert).unwrap(); + } + + #[test] + fn create_ctl() { + let cert = include_bytes!("../test/self-signed.badssl.com.cer"); + let mut store = Memory::new().unwrap(); + let cert = store.add_encoded_certificate(cert).unwrap(); + + CtlContext::builder() + .certificate(cert) + .usage("1.3.6.1.4.1.311.2.2.2") + .encode_and_sign() + .unwrap(); + } + + #[test] + fn pfx_import() { + let pfx = include_bytes!("../test/identity.p12"); + let store = PfxImportOptions::new() + .include_extended_properties(true) + .password("mypass") + .import(pfx) + .unwrap(); + assert_eq!(store.certs().count(), 2); + let pkeys = store.certs() + .filter(|c| { + c.private_key().compare_key(true).silent(true).acquire().is_ok() + }) + .count(); + assert_eq!(pkeys, 1); + } +} diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/context_buffer.rs cargo-0.26.0/vendor/schannel-0.1.11/src/context_buffer.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/context_buffer.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/context_buffer.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,21 @@ +use winapi::shared::sspi; +use std::ops::Deref; +use std::slice; + +pub struct ContextBuffer(pub sspi::SecBuffer); + +impl Drop for ContextBuffer { + fn drop(&mut self) { + unsafe { + sspi::FreeContextBuffer(self.0.pvBuffer); + } + } +} + +impl Deref for ContextBuffer { + type Target = [u8]; + + fn deref(&self) -> &[u8] { + unsafe { slice::from_raw_parts(self.0.pvBuffer as *const _, self.0.cbBuffer as usize) } + } +} diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/crypt_key.rs cargo-0.26.0/vendor/schannel-0.1.11/src/crypt_key.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/crypt_key.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/crypt_key.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,15 @@ +//! CryptoAPI private keys. +use winapi::um::wincrypt; + +/// A handle to a key. +pub struct CryptKey(wincrypt::HCRYPTKEY); + +impl Drop for CryptKey { + fn drop(&mut self) { + unsafe { + wincrypt::CryptDestroyKey(self.0); + } + } +} + +inner!(CryptKey, wincrypt::HCRYPTKEY); diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/crypt_prov.rs cargo-0.26.0/vendor/schannel-0.1.11/src/crypt_prov.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/crypt_prov.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/crypt_prov.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,224 @@ +//! CryptoAPI key providers. +use std::io; +use std::ptr; +use winapi::shared::minwindef as winapi; +use winapi::um::winbase; +use winapi::um::wincrypt; + +use Inner; +use crypt_key::CryptKey; + +/// A CryptoAPI handle to a provider of a key. +pub struct CryptProv(wincrypt::HCRYPTPROV); + +impl Drop for CryptProv { + fn drop(&mut self) { + unsafe { + wincrypt::CryptReleaseContext(self.0, 0); + } + } +} + +inner!(CryptProv, wincrypt::HCRYPTPROV); + +impl CryptProv { + /// Imports a key into this provider. + pub fn import<'a>(&'a mut self) -> ImportOptions<'a> { + ImportOptions { + prov: self, + flags: 0, + } + } +} + +/// A builder for `CryptProv`s. +pub struct AcquireOptions { + container: Option<Vec<u16>>, + provider: Option<Vec<u16>>, + flags: winapi::DWORD, +} + +impl AcquireOptions { + /// Returns a new builder with default settings. + pub fn new() -> AcquireOptions { + AcquireOptions { + container: None, + provider: None, + flags: 0, + } + } + + /// Sets the name for this key container. + /// + /// This should not be set if `verify_context` is set. + pub fn container(&mut self, container: &str) -> &mut AcquireOptions { + self.container = Some(container.encode_utf16().chain(Some(0)).collect()); + self + } + + /// Sets the name of the CSP to be used. + pub fn provider(&mut self, provider: &str) -> &mut AcquireOptions { + self.provider = Some(provider.encode_utf16().chain(Some(0)).collect()); + self + } + + /// If set, private keys will not be accessible or persisted. + pub fn verify_context(&mut self, verify_context: bool) -> &mut AcquireOptions { + self.flag(wincrypt::CRYPT_VERIFYCONTEXT, verify_context) + } + + /// If set, the container will be created. + pub fn new_keyset(&mut self, new_keyset: bool) -> &mut AcquireOptions { + self.flag(wincrypt::CRYPT_NEWKEYSET, new_keyset) + } + + /// If set, the container will be stored as a machine rather than user keys. + pub fn machine_keyset(&mut self, machine_keyset: bool) -> &mut AcquireOptions { + self.flag(wincrypt::CRYPT_MACHINE_KEYSET, machine_keyset) + } + + /// If set, an error will be returned if user intervention is required + /// rather than displaying a dialog. + pub fn silent(&mut self, silent: bool) -> &mut AcquireOptions { + self.flag(wincrypt::CRYPT_SILENT, silent) + } + + fn flag(&mut self, flag: winapi::DWORD, on: bool) -> &mut AcquireOptions { + if on { + self.flags |= flag; + } else { + self.flags &= !flag; + } + + self + } + + /// Acquires a container. + pub fn acquire(&self, type_: ProviderType) -> io::Result<CryptProv> { + unsafe { + let container = self.container.as_ref().map(|s| s.as_ptr()).unwrap_or(ptr::null()); + let provider = self.provider.as_ref().map(|s| s.as_ptr()).unwrap_or(ptr::null()); + + let mut prov = 0; + let res = wincrypt::CryptAcquireContextW(&mut prov, + container as *mut _, + provider as *mut _, + type_.0, + self.flags); + if res == winapi::TRUE { + Ok(CryptProv(prov)) + } else { + Err(io::Error::last_os_error()) + } + } + } +} + +/// An identifier of the type of cryptography provider to be used with a +/// container. +#[derive(Copy, Clone)] +pub struct ProviderType(winapi::DWORD); + +#[allow(missing_docs)] +impl ProviderType { + pub fn rsa_full() -> ProviderType { + ProviderType(wincrypt::PROV_RSA_FULL) + } + + pub fn rsa_aes() -> ProviderType { + ProviderType(wincrypt::PROV_RSA_AES) + } + + pub fn rsa_sig() -> ProviderType { + ProviderType(wincrypt::PROV_RSA_SIG) + } + + pub fn rsa_schannel() -> ProviderType { + ProviderType(wincrypt::PROV_RSA_SCHANNEL) + } + + pub fn dss() -> ProviderType { + ProviderType(wincrypt::PROV_DSS) + } + + pub fn dss_dh() -> ProviderType { + ProviderType(wincrypt::PROV_DSS_DH) + } + + pub fn dh_schannel() -> ProviderType { + ProviderType(wincrypt::PROV_DH_SCHANNEL) + } + + pub fn fortezza() -> ProviderType { + ProviderType(wincrypt::PROV_FORTEZZA) + } + + pub fn ms_exchange() -> ProviderType { + ProviderType(wincrypt::PROV_MS_EXCHANGE) + } + + pub fn ssl() -> ProviderType { + ProviderType(wincrypt::PROV_SSL) + } + + pub fn as_raw(&self) -> winapi::DWORD { + self.0 + } +} + +/// A builder for key imports. +pub struct ImportOptions<'a> { + prov: &'a mut CryptProv, + flags: winapi::DWORD, +} + +impl<'a> ImportOptions<'a> { + /// Imports a DER-encoded private key. + pub fn import(&mut self, der: &[u8]) -> io::Result<CryptKey> { + unsafe { + assert!(der.len() <= winapi::DWORD::max_value() as usize); + let mut buf = ptr::null_mut(); + let mut len = 0; + let res = wincrypt::CryptDecodeObjectEx(wincrypt::X509_ASN_ENCODING | + wincrypt::PKCS_7_ASN_ENCODING, + wincrypt::PKCS_RSA_PRIVATE_KEY, + der.as_ptr(), + der.len() as winapi::DWORD, + wincrypt::CRYPT_DECODE_ALLOC_FLAG, + ptr::null_mut(), + &mut buf as *mut _ as winapi::LPVOID, + &mut len); + if res == winapi::FALSE { + return Err(io::Error::last_os_error()); + } + + let mut key = 0; + let res = wincrypt::CryptImportKey(self.prov.0, buf, len, 0, self.flags, &mut key); + winbase::LocalFree(buf as *mut _); + + if res == winapi::TRUE { + Ok(CryptKey::from_inner(key)) + } else { + Err(io::Error::last_os_error()) + } + } + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn rsa_key() { + let key = include_bytes!("../test/key.key"); + + let mut context = AcquireOptions::new() + .verify_context(true) + .acquire(ProviderType::rsa_full()) + .unwrap(); + context.import() + .import(key) + .unwrap(); + } +} diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/ctl_context.rs cargo-0.26.0/vendor/schannel-0.1.11/src/ctl_context.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/ctl_context.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/ctl_context.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,187 @@ +//! Bindings to Certificate Trust Lists (CTL) in winapi. + +#![allow(dead_code)] + +use std::io; +use std::mem; +use std::ptr; +use winapi::shared::minwindef as winapi; +use winapi::shared::ntdef; +use winapi::um::wincrypt; + +use cert_context::CertContext; +use Inner; + +lazy_static! { + static ref szOID_OIWSEC_sha1: Vec<u8> = + wincrypt::szOID_OIWSEC_sha1.bytes().chain(Some(0)).collect(); +} + +/// Wrapped `PCCTL_CONTEXT` which represents a certificate trust list to +/// Windows. +pub struct CtlContext(wincrypt::PCCTL_CONTEXT); + +unsafe impl Send for CtlContext {} +unsafe impl Sync for CtlContext {} + +impl Drop for CtlContext { + fn drop(&mut self) { + unsafe { + wincrypt::CertFreeCTLContext(self.0); + } + } +} + +impl Inner<wincrypt::PCCTL_CONTEXT> for CtlContext { + unsafe fn from_inner(t: wincrypt::PCCTL_CONTEXT) -> CtlContext { + CtlContext(t) + } + + fn as_inner(&self) -> wincrypt::PCCTL_CONTEXT { + self.0 + } + + fn get_mut(&mut self) -> &mut wincrypt::PCCTL_CONTEXT { + &mut self.0 + } +} + +impl CtlContext { + /// Returns a builder reader to create an encoded `CtlContext`. + pub fn builder() -> Builder { + Builder { + certificates: vec![], + usages: vec![], + } + } +} + +/// Used to build an encoded `CtlContext` which can be added to a `Memory` store +/// to get back the actual `CtlContext`. +pub struct Builder { + certificates: Vec<CertContext>, + usages: Vec<Vec<u8>>, +} + +impl Builder { + /// Adds a certificate to be passed to `CryptMsgEncodeAndSignCTL` later on. + pub fn certificate(&mut self, cert: CertContext) -> &mut Builder { + self.certificates.push(cert); + self + } + + /// Adds a usage string to be passed in the `SubjectUsage` field to + /// `CryptMsgEncodeAndSignCTL` later on. + pub fn usage(&mut self, usage: &str) -> &mut Builder { + let mut usage = usage.as_bytes().to_owned(); + usage.push(0); + self.usages.push(usage); + self + } + + /// Calls `CryptMsgEncodeAndSignCTL` to encode this list of certificates + /// into a CTL. + /// + /// This can later be passed to `Memory::add_encoded_ctl`. + pub fn encode_and_sign(&self) -> io::Result<Vec<u8>> { + unsafe { + let encoding = wincrypt::X509_ASN_ENCODING | wincrypt::PKCS_7_ASN_ENCODING; + + let mut usages = self.usages.iter().map(|u| u.as_ptr()).collect::<Vec<_>>(); + let mut entry_data = vec![]; + let mut entries = vec![]; + for certificate in &self.certificates { + let data = try!(cert_entry(certificate)); + entries.push(*(data.as_ptr() as *const wincrypt::CTL_ENTRY)); + entry_data.push(data); + } + + let mut ctl_info: wincrypt::CTL_INFO = mem::zeroed(); + ctl_info.dwVersion = wincrypt::CTL_V1; + ctl_info.SubjectUsage.cUsageIdentifier = usages.len() as winapi::DWORD; + ctl_info.SubjectUsage.rgpszUsageIdentifier = usages.as_mut_ptr() as *mut ntdef::LPSTR; + ctl_info.SubjectAlgorithm.pszObjId = szOID_OIWSEC_sha1.as_ptr() as ntdef::LPSTR; + ctl_info.cCTLEntry = entries.len() as winapi::DWORD; + ctl_info.rgCTLEntry = entries.as_mut_ptr(); + + let mut sign_info: wincrypt::CMSG_SIGNED_ENCODE_INFO = mem::zeroed(); + sign_info.cbSize = mem::size_of_val(&sign_info) as winapi::DWORD; + let mut encoded_certs = self.certificates + .iter() + .map(|c| { + wincrypt::CERT_BLOB { + cbData: (*c.as_inner()).cbCertEncoded, + pbData: (*c.as_inner()).pbCertEncoded, + } + }) + .collect::<Vec<_>>(); + sign_info.rgCertEncoded = encoded_certs.as_mut_ptr(); + sign_info.cCertEncoded = encoded_certs.len() as winapi::DWORD; + + let flags = wincrypt::CMSG_ENCODE_SORTED_CTL_FLAG | + wincrypt::CMSG_ENCODE_HASHED_SUBJECT_IDENTIFIER_FLAG; + + let mut size = 0; + + let res = wincrypt::CryptMsgEncodeAndSignCTL(encoding, + &mut ctl_info, + &mut sign_info, + flags, + ptr::null_mut(), + &mut size); + if res == winapi::FALSE { + return Err(io::Error::last_os_error()) + } + + let mut encoded = vec![0; size as usize]; + + let res = wincrypt::CryptMsgEncodeAndSignCTL(encoding, + &mut ctl_info, + &mut sign_info, + flags, + encoded.as_mut_ptr() as *mut winapi::BYTE, + &mut size); + if res == winapi::FALSE { + return Err(io::Error::last_os_error()) + } + + Ok(encoded) + } + } +} + +fn cert_entry(cert: &CertContext) -> io::Result<Vec<u8>> { + // FIXME: Seems to be missing since the winapi 0.3 upgrade? + const CTL_ENTRY_FROM_PROP_CHAIN_FLAG: winapi::DWORD = 1; + + unsafe { + let mut size = 0; + + let res = wincrypt::CertCreateCTLEntryFromCertificateContextProperties( + cert.as_inner(), + 0, + ptr::null_mut(), + CTL_ENTRY_FROM_PROP_CHAIN_FLAG, + ptr::null_mut(), + ptr::null_mut(), + &mut size); + if res == winapi::FALSE { + return Err(io::Error::last_os_error()); + } + + let mut entry = vec![0u8; size as usize]; + let res = wincrypt::CertCreateCTLEntryFromCertificateContextProperties( + cert.as_inner(), + 0, + ptr::null_mut(), + CTL_ENTRY_FROM_PROP_CHAIN_FLAG, + ptr::null_mut(), + entry.as_mut_ptr() as wincrypt::PCTL_ENTRY, + &mut size); + if res == winapi::FALSE { + Err(io::Error::last_os_error()) + } else { + Ok(entry) + } + } +} diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/key_handle.rs cargo-0.26.0/vendor/schannel-0.1.11/src/key_handle.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/key_handle.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/key_handle.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,5 @@ +//! Deprecated. +#![deprecated(note = "use cert_context::PrivateKey", since = "0.1.5")] + +#[deprecated(note = "use cert_context::PrivateKey", since = "0.1.5")] +pub use cert_context::PrivateKey as KeyHandle; diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/lib.rs cargo-0.26.0/vendor/schannel-0.1.11/src/lib.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,87 @@ +//! Bindings to the Windows SChannel APIs. +#![cfg(windows)] +#![warn(missing_docs)] +#![allow(non_upper_case_globals)] + +extern crate winapi; + +#[macro_use] +extern crate lazy_static; + +use std::ptr; +use winapi::ctypes; +use winapi::shared::sspi; + +macro_rules! inner { + ($t:path, $raw:ty) => { + impl ::Inner<$raw> for $t { + unsafe fn from_inner(t: $raw) -> Self { + $t(t) + } + + fn as_inner(&self) -> $raw { + self.0 + } + + fn get_mut(&mut self) -> &mut $raw { + &mut self.0 + } + } + } +} + +pub mod cert_chain; +pub mod cert_context; +pub mod cert_store; +pub mod crypt_key; +pub mod crypt_prov; +/* pub */ mod ctl_context; +pub mod key_handle; +pub mod ncrypt_key; +pub mod schannel_cred; +pub mod tls_stream; + +mod context_buffer; +mod security_context; + +#[cfg(test)] +mod test; + +const ACCEPT_REQUESTS: ctypes::c_ulong = + sspi::ASC_REQ_ALLOCATE_MEMORY | sspi::ASC_REQ_CONFIDENTIALITY | + sspi::ASC_REQ_SEQUENCE_DETECT | sspi::ASC_REQ_STREAM | + sspi::ASC_REQ_REPLAY_DETECT; + +const INIT_REQUESTS: ctypes::c_ulong = + sspi::ISC_REQ_CONFIDENTIALITY | sspi::ISC_REQ_INTEGRITY | sspi::ISC_REQ_REPLAY_DETECT | + sspi::ISC_REQ_SEQUENCE_DETECT | sspi::ISC_REQ_MANUAL_CRED_VALIDATION | + sspi::ISC_REQ_ALLOCATE_MEMORY | sspi::ISC_REQ_STREAM | sspi::ISC_REQ_USE_SUPPLIED_CREDS; + +trait Inner<T> { + unsafe fn from_inner(t: T) -> Self; + + fn as_inner(&self) -> T; + + fn get_mut(&mut self) -> &mut T; +} + +unsafe fn secbuf(buftype: ctypes::c_ulong, + bytes: Option<&mut [u8]>) -> sspi::SecBuffer { + let (ptr, len) = match bytes { + Some(bytes) => (bytes.as_mut_ptr(), bytes.len() as ctypes::c_ulong), + None => (ptr::null_mut(), 0), + }; + sspi::SecBuffer { + BufferType: buftype, + cbBuffer: len, + pvBuffer: ptr as *mut ctypes::c_void, + } +} + +unsafe fn secbuf_desc(bufs: &mut [sspi::SecBuffer]) -> sspi::SecBufferDesc { + sspi::SecBufferDesc { + ulVersion: sspi::SECBUFFER_VERSION, + cBuffers: bufs.len() as ctypes::c_ulong, + pBuffers: bufs.as_mut_ptr(), + } +} diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/ncrypt_key.rs cargo-0.26.0/vendor/schannel-0.1.11/src/ncrypt_key.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/ncrypt_key.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/ncrypt_key.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,15 @@ +//! CNG private keys. +use winapi::um::ncrypt; + +/// A CNG handle to a key. +pub struct NcryptKey(ncrypt::NCRYPT_KEY_HANDLE); + +impl Drop for NcryptKey { + fn drop(&mut self) { + unsafe { + ncrypt::NCryptFreeObject(self.0); + } + } +} + +inner!(NcryptKey, ncrypt::NCRYPT_KEY_HANDLE); diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/schannel_cred.rs cargo-0.26.0/vendor/schannel-0.1.11/src/schannel_cred.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/schannel_cred.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/schannel_cred.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,262 @@ +//! Schannel credentials. +use winapi::shared::{sspi, winerror}; +use winapi::shared::minwindef as winapi; +use winapi::um::{self, wincrypt}; +use std::io; +use std::mem; +use std::ptr; + +use Inner; +use cert_context::CertContext; + +lazy_static! { + static ref UNISP_NAME: Vec<u8> = um::schannel::UNISP_NAME.bytes().chain(Some(0)).collect(); +} + +/// The communication direction that an `SchannelCred` will support. +#[derive(Copy, Debug, Clone, PartialEq, Eq)] +pub enum Direction { + /// Server-side, inbound connections. + Inbound, + /// Client-side, outbound connections. + Outbound, +} + +/// Algorithms supported by Schannel. +// https://msdn.microsoft.com/en-us/library/windows/desktop/aa375549(v=vs.85).aspx +#[derive(Debug, Copy, Clone)] +#[repr(u32)] +pub enum Algorithm { + /// Advanced Encryption Standard (AES). + Aes = wincrypt::CALG_AES, + /// 128 bit AES. + Aes128 = wincrypt::CALG_AES_128, + /// 192 bit AES. + Aes192 = wincrypt::CALG_AES_192, + /// 256 bit AES. + Aes256 = wincrypt::CALG_AES_256, + /// Temporary algorithm identifier for handles of Diffie-Hellman–agreed keys. + AgreedkeyAny = wincrypt::CALG_AGREEDKEY_ANY, + /// An algorithm to create a 40-bit DES key that has parity bits and zeroed key bits to make + /// its key length 64 bits. + CylinkMek = wincrypt::CALG_CYLINK_MEK, + /// DES encryption algorithm. + Des = wincrypt::CALG_DES, + /// DESX encryption algorithm. + Desx = wincrypt::CALG_DESX, + /// Diffie-Hellman ephemeral key exchange algorithm. + DhEphem = wincrypt::CALG_DH_EPHEM, + /// Diffie-Hellman store and forward key exchange algorithm. + DhSf = wincrypt::CALG_DH_SF, + /// DSA public key signature algorithm. + DssSign = wincrypt::CALG_DSS_SIGN, + /// Elliptic curve Diffie-Hellman key exchange algorithm. + Ecdh = wincrypt::CALG_ECDH, + // https://github.com/retep998/wincrypt-rs/issues/287 + // /// Ephemeral elliptic curve Diffie-Hellman key exchange algorithm. + // EcdhEphem = wincrypt::CALG_ECDH_EPHEM, + /// Elliptic curve digital signature algorithm. + Ecdsa = wincrypt::CALG_ECDSA, + /// One way function hashing algorithm. + HashReplaceOwf = wincrypt::CALG_HASH_REPLACE_OWF, + /// Hughes MD5 hashing algorithm. + HughesMd5 = wincrypt::CALG_HUGHES_MD5, + /// HMAC keyed hash algorithm. + Hmac = wincrypt::CALG_HMAC, + /// MAC keyed hash algorithm. + Mac = wincrypt::CALG_MAC, + /// MD2 hashing algorithm. + Md2 = wincrypt::CALG_MD2, + /// MD4 hashing algorithm. + Md4 = wincrypt::CALG_MD4, + /// MD5 hashing algorithm. + Md5 = wincrypt::CALG_MD5, + /// No signature algorithm.. + NoSign = wincrypt::CALG_NO_SIGN, + /// RC2 block encryption algorithm. + Rc2 = wincrypt::CALG_RC2, + /// RC4 stream encryption algorithm. + Rc4 = wincrypt::CALG_RC4, + /// RC5 block encryption algorithm. + Rc5 = wincrypt::CALG_RC5, + /// RSA public key exchange algorithm. + RsaKeyx = wincrypt::CALG_RSA_KEYX, + /// RSA public key signature algorithm. + RsaSign = wincrypt::CALG_RSA_SIGN, + /// SHA hashing algorithm. + Sha1 = wincrypt::CALG_SHA1, + /// 256 bit SHA hashing algorithm. + Sha256 = wincrypt::CALG_SHA_256, + /// 384 bit SHA hashing algorithm. + Sha384 = wincrypt::CALG_SHA_384, + /// 512 bit SHA hashing algorithm. + Sha512 = wincrypt::CALG_SHA_512, + /// Triple DES encryption algorithm. + TripleDes = wincrypt::CALG_3DES, + /// Two-key triple DES encryption with effective key length equal to 112 bits. + TripleDes112 = wincrypt::CALG_3DES_112, + #[doc(hidden)] + __ForExtensibility, +} + +/// Protocols supported by Schannel. +#[derive(Debug, Copy, Clone)] +pub enum Protocol { + /// Secure Sockets Layer 3.0 + Ssl3, + /// Transport Layer Security 1.0 + Tls10, + /// Transport Layer Security 1.1 + Tls11, + /// Transport Layer Security 1.2 + Tls12, + #[doc(hidden)] + __ForExtensibility, +} + +impl Protocol { + fn dword(self, direction: Direction) -> winapi::DWORD { + match (self, direction) { + (Protocol::Ssl3, Direction::Inbound) => um::schannel::SP_PROT_SSL3_SERVER, + (Protocol::Tls10, Direction::Inbound) => um::schannel::SP_PROT_TLS1_0_SERVER, + (Protocol::Tls11, Direction::Inbound) => um::schannel::SP_PROT_TLS1_1_SERVER, + (Protocol::Tls12, Direction::Inbound) => um::schannel::SP_PROT_TLS1_2_SERVER, + (Protocol::Ssl3, Direction::Outbound) => um::schannel::SP_PROT_SSL3_CLIENT, + (Protocol::Tls10, Direction::Outbound) => um::schannel::SP_PROT_TLS1_0_CLIENT, + (Protocol::Tls11, Direction::Outbound) => um::schannel::SP_PROT_TLS1_1_CLIENT, + (Protocol::Tls12, Direction::Outbound) => um::schannel::SP_PROT_TLS1_2_CLIENT, + (Protocol::__ForExtensibility, _) => unreachable!(), + } + } +} + +/// A builder type for `SchannelCred`s. +#[derive(Default, Debug)] +pub struct Builder { + supported_algorithms: Option<Vec<Algorithm>>, + enabled_protocols: Option<Vec<Protocol>>, + certs: Vec<CertContext>, +} + +impl Builder { + /// Returns a new `Builder`. + pub fn new() -> Builder { + Builder::default() + } + + /// Sets the algorithms supported for credentials created from this builder. + pub fn supported_algorithms(&mut self, + supported_algorithms: &[Algorithm]) + -> &mut Builder { + assert!(supported_algorithms.iter() + .all(|a| { + match *a { + Algorithm::__ForExtensibility => false, + _ => true, + } + })); + self.supported_algorithms = Some(supported_algorithms.to_owned()); + self + } + + /// Sets the protocols enabled for credentials created from this builder. + pub fn enabled_protocols(&mut self, + enabled_protocols: &[Protocol]) + -> &mut Builder { + assert!(enabled_protocols.iter() + .all(|a| { + match *a { + Protocol::__ForExtensibility => false, + _ => true, + } + })); + self.enabled_protocols = Some(enabled_protocols.to_owned()); + self + } + + /// Add a certificate to get passed down when the credentials are acquired. + /// + /// Certificates passed here may specify a certificate that contains a + /// private key to be used in authenticating the application. Typically, + /// this is called once for each key exchange method supported by + /// servers. + /// + /// Clients often do not call this function and either depend on Schannel to + /// find an appropriate certificate or create a certificate later if needed. + pub fn cert(&mut self, cx: CertContext) -> &mut Builder { + self.certs.push(cx); + self + } + + /// Creates a new `SchannelCred`. + pub fn acquire(&self, direction: Direction) -> io::Result<SchannelCred> { + unsafe { + let mut handle = mem::zeroed(); + let mut cred_data: um::schannel::SCHANNEL_CRED = mem::zeroed(); + cred_data.dwVersion = um::schannel::SCHANNEL_CRED_VERSION; + cred_data.dwFlags = um::schannel::SCH_USE_STRONG_CRYPTO | um::schannel::SCH_CRED_NO_DEFAULT_CREDS; + if let Some(ref supported_algorithms) = self.supported_algorithms { + cred_data.cSupportedAlgs = supported_algorithms.len() as winapi::DWORD; + cred_data.palgSupportedAlgs = supported_algorithms.as_ptr() as *mut _; + } + if let Some(ref enabled_protocols) = self.enabled_protocols { + cred_data.grbitEnabledProtocols = enabled_protocols.iter() + .map(|p| p.dword(direction)) + .fold(0, |acc, p| acc | p); + } + let mut certs = self.certs.iter().map(|c| c.as_inner()).collect::<Vec<_>>(); + cred_data.cCreds = certs.len() as winapi::DWORD; + cred_data.paCred = certs.as_mut_ptr(); + + let direction = match direction { + Direction::Inbound => sspi::SECPKG_CRED_INBOUND, + Direction::Outbound => sspi::SECPKG_CRED_OUTBOUND, + }; + + match sspi::AcquireCredentialsHandleA(ptr::null_mut(), + UNISP_NAME.as_ptr() as *const _ as *mut _, + direction, + ptr::null_mut(), + &mut cred_data as *mut _ as *mut _, + None, + ptr::null_mut(), + &mut handle, + ptr::null_mut()) { + winerror::SEC_E_OK => Ok(SchannelCred(handle)), + err => Err(io::Error::from_raw_os_error(err as i32)), + } + } + } +} + +/// An SChannel credential. +pub struct SchannelCred(sspi::CredHandle); + +impl Drop for SchannelCred { + fn drop(&mut self) { + unsafe { + sspi::FreeCredentialsHandle(&mut self.0); + } + } +} + +impl Inner<sspi::CredHandle> for SchannelCred { + unsafe fn from_inner(inner: sspi::CredHandle) -> SchannelCred { + SchannelCred(inner) + } + + fn as_inner(&self) -> sspi::CredHandle { + self.0 + } + + fn get_mut(&mut self) -> &mut sspi::CredHandle { + &mut self.0 + } +} + +impl SchannelCred { + /// Returns a builder. + pub fn builder() -> Builder { + Builder::new() + } +} diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/security_context.rs cargo-0.26.0/vendor/schannel-0.1.11/src/security_context.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/security_context.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/security_context.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,107 @@ +use winapi::shared::{sspi, winerror}; +use winapi::um::{minschannel}; +use std::mem; +use std::ptr; +use std::io; + +use {INIT_REQUESTS, Inner, secbuf, secbuf_desc}; +use cert_context::CertContext; +use context_buffer::ContextBuffer; + +use schannel_cred::SchannelCred; + +pub struct SecurityContext(sspi::CtxtHandle); + +impl Drop for SecurityContext { + fn drop(&mut self) { + unsafe { + sspi::DeleteSecurityContext(&mut self.0); + } + } +} + +impl Inner<sspi::CtxtHandle> for SecurityContext { + unsafe fn from_inner(inner: sspi::CtxtHandle) -> SecurityContext { + SecurityContext(inner) + } + + fn as_inner(&self) -> sspi::CtxtHandle { + self.0 + } + + fn get_mut(&mut self) -> &mut sspi::CtxtHandle { + &mut self.0 + } +} + +impl SecurityContext { + pub fn initialize(cred: &mut SchannelCred, + accept: bool, + domain: Option<&[u16]>) + -> io::Result<(SecurityContext, Option<ContextBuffer>)> { + unsafe { + let mut ctxt = mem::zeroed(); + + if accept { + // If we're performing an accept then we need to wait to call + // `AcceptSecurityContext` until we've actually read some data. + return Ok((SecurityContext(ctxt), None)) + } + + let domain = domain.map(|b| b.as_ptr() as *mut u16).unwrap_or(ptr::null_mut()); + + let mut outbuf = [secbuf(sspi::SECBUFFER_EMPTY, None)]; + let mut outbuf_desc = secbuf_desc(&mut outbuf); + + let mut attributes = 0; + + match sspi::InitializeSecurityContextW(cred.get_mut(), + ptr::null_mut(), + domain, + INIT_REQUESTS, + 0, + 0, + ptr::null_mut(), + 0, + &mut ctxt, + &mut outbuf_desc, + &mut attributes, + ptr::null_mut()) { + winerror::SEC_I_CONTINUE_NEEDED => { + Ok((SecurityContext(ctxt), Some(ContextBuffer(outbuf[0])))) + } + err => { + Err(io::Error::from_raw_os_error(err as i32)) + } + } + } + } + + pub fn stream_sizes(&mut self) -> io::Result<sspi::SecPkgContext_StreamSizes> { + unsafe { + let mut stream_sizes = mem::zeroed(); + let status = sspi::QueryContextAttributesW(&mut self.0, + sspi::SECPKG_ATTR_STREAM_SIZES, + &mut stream_sizes as *mut _ as *mut _); + if status == winerror::SEC_E_OK { + Ok(stream_sizes) + } else { + Err(io::Error::from_raw_os_error(status as i32)) + } + } + } + + pub fn remote_cert(&mut self) -> io::Result<CertContext> { + unsafe { + let mut cert_context = mem::zeroed(); + let status = sspi::QueryContextAttributesW(&mut self.0, + minschannel::SECPKG_ATTR_REMOTE_CERT_CONTEXT, + &mut cert_context as *mut _ as *mut _); + if status == winerror::SEC_E_OK { + Ok(CertContext::from_inner(cert_context)) + } else { + Err(io::Error::from_raw_os_error(status as i32)) + } + } + } +} diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/test.rs cargo-0.26.0/vendor/schannel-0.1.11/src/test.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/test.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/test.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,642 @@ +use std::env; +use std::io::{self, Read, Write, Error}; +use std::mem; +use std::net::{TcpStream, TcpListener}; +use std::ptr; +use std::sync::{Once, ONCE_INIT}; +use std::thread; +use winapi::shared::minwindef as winapi; +use winapi::shared::{basetsd, ntdef, lmcons, winerror}; +use winapi::um::{minwinbase, sysinfoapi, timezoneapi, wincrypt}; + +use Inner; +use crypt_prov::{AcquireOptions, ProviderType}; +use cert_context::{CertContext, KeySpec, HashAlgorithm}; +use cert_store::{CertStore, Memory, CertAdd}; +use schannel_cred::{Direction, Protocol, Algorithm, SchannelCred}; +use tls_stream::{self, HandshakeError}; + +#[test] +fn basic() { + let creds = SchannelCred::builder().acquire(Direction::Outbound).unwrap(); + let stream = TcpStream::connect("google.com:443").unwrap(); + let mut stream = tls_stream::Builder::new() + .domain("google.com") + .connect(creds, stream) + .unwrap(); + stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); + let mut out = vec![]; + stream.read_to_end(&mut out).unwrap(); + assert!(out.starts_with(b"HTTP/1.0 200 OK") || out.starts_with(b"HTTP/1.0 302 Found")); + assert!(out.ends_with(b"</html>") || out.ends_with(b"</HTML>\r\n")); +} + +#[test] +fn invalid_algorithms() { + let creds = SchannelCred::builder() + .supported_algorithms(&[Algorithm::Rc2, Algorithm::Ecdsa]) + .acquire(Direction::Outbound); + assert_eq!(creds.err().unwrap().raw_os_error().unwrap(), + winerror::SEC_E_ALGORITHM_MISMATCH as i32); +} + +#[test] +fn valid_algorithms() { + let creds = SchannelCred::builder() + .supported_algorithms(&[Algorithm::Aes128, Algorithm::Ecdsa]) + .acquire(Direction::Outbound) + .unwrap(); + let stream = TcpStream::connect("google.com:443").unwrap(); + let mut stream = tls_stream::Builder::new() + .domain("google.com") + .connect(creds, stream) + .unwrap(); + stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); + let mut out = vec![]; + stream.read_to_end(&mut out).unwrap(); + assert!(out.starts_with(b"HTTP/1.0 200 OK") || out.starts_with(b"HTTP/1.0 302 Found")); + assert!(out.ends_with(b"</html>") || out.ends_with(b"</HTML>\r\n")); +} + +fn unwrap_handshake<S>(e: HandshakeError<S>) -> io::Error { + match e { + HandshakeError::Failure(e) => e, + HandshakeError::Interrupted(_) => panic!("not an I/O error"), + } +} + +#[test] +#[ignore] // google's inconsistent about disallowing sslv3 +fn invalid_protocol() { + let creds = SchannelCred::builder() + .enabled_protocols(&[Protocol::Ssl3]) + .acquire(Direction::Outbound) + .unwrap(); + let stream = TcpStream::connect("google.com:443").unwrap(); + let err = tls_stream::Builder::new() + .domain("google.com") + .connect(creds, stream) + .err() + .unwrap(); + let err = unwrap_handshake(err); + assert_eq!(err.raw_os_error().unwrap(), + winerror::SEC_E_UNSUPPORTED_FUNCTION as i32); +} + +#[test] +fn valid_protocol() { + let creds = SchannelCred::builder() + .enabled_protocols(&[Protocol::Tls12]) + .acquire(Direction::Outbound) + .unwrap(); + let stream = TcpStream::connect("google.com:443").unwrap(); + let mut stream = tls_stream::Builder::new() + .domain("google.com") + .connect(creds, stream) + .unwrap(); + stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); + let mut out = vec![]; + stream.read_to_end(&mut out).unwrap(); + assert!(out.starts_with(b"HTTP/1.0 200 OK") || out.starts_with(b"HTTP/1.0 302 Found")); + assert!(out.ends_with(b"</html>") || out.ends_with(b"</HTML>\r\n")); +} + +#[test] +fn valid_protocol_with_intermediate_certs() { + let creds = SchannelCred::builder() + .enabled_protocols(&[Protocol::Tls12]) + .acquire(Direction::Outbound) + .unwrap(); + let stream = TcpStream::connect("lh3.googleusercontent.com:443").unwrap(); + let mut stream = tls_stream::Builder::new() + .domain("lh3.googleusercontent.com") + .connect(creds, stream) + .unwrap(); + stream.write_all(b"GET / HTTP/1.0\r\n\r\n").unwrap(); + let mut out = vec![]; + stream.read_to_end(&mut out).unwrap(); + assert!(out.starts_with(b"HTTP/1.0 200 OK") || out.starts_with(b"HTTP/1.0 302 Found")); + assert!(out.ends_with(b"</html>") || out.ends_with(b"</HTML>\r\n")); +} + +#[test] +fn expired_cert() { + let creds = SchannelCred::builder() + .acquire(Direction::Outbound) + .unwrap(); + let stream = TcpStream::connect("expired.badssl.com:443").unwrap(); + let err = tls_stream::Builder::new() + .domain("expired.badssl.com") + .connect(creds, stream) + .err() + .unwrap(); + let err = unwrap_handshake(err); + assert_eq!(err.raw_os_error().unwrap(), winerror::CERT_E_EXPIRED as i32); +} + +#[test] +fn self_signed_cert() { + let creds = SchannelCred::builder() + .acquire(Direction::Outbound) + .unwrap(); + let stream = TcpStream::connect("self-signed.badssl.com:443").unwrap(); + let err = tls_stream::Builder::new() + .domain("self-signed.badssl.com") + .connect(creds, stream) + .err() + .unwrap(); + let err = unwrap_handshake(err); + assert_eq!(err.raw_os_error().unwrap(), + winerror::CERT_E_UNTRUSTEDROOT as i32); +} + +#[test] +fn self_signed_cert_manual_trust() { + let cert = include_bytes!("../test/self-signed.badssl.com.cer"); + let mut store = Memory::new().unwrap(); + store.add_encoded_certificate(cert).unwrap(); + + let creds = SchannelCred::builder() + .acquire(Direction::Outbound) + .unwrap(); + let stream = TcpStream::connect("self-signed.badssl.com:443").unwrap(); + tls_stream::Builder::new() + .domain("self-signed.badssl.com") + .cert_store(store.into_store()) + .connect(creds, stream) + .unwrap(); +} + +#[test] +fn wrong_host_cert() { + let creds = SchannelCred::builder() + .acquire(Direction::Outbound) + .unwrap(); + let stream = TcpStream::connect("wrong.host.badssl.com:443").unwrap(); + let err = tls_stream::Builder::new() + .domain("wrong.host.badssl.com") + .connect(creds, stream) + .err() + .unwrap(); + let err = unwrap_handshake(err); + assert_eq!(err.raw_os_error().unwrap(), + winerror::CERT_E_CN_NO_MATCH as i32); +} + +#[test] +fn shutdown() { + let creds = SchannelCred::builder().acquire(Direction::Outbound).unwrap(); + let stream = TcpStream::connect("google.com:443").unwrap(); + let mut stream = tls_stream::Builder::new() + .domain("google.com") + .connect(creds, stream) + .unwrap(); + stream.shutdown().unwrap(); +} + +#[test] +fn validation_failure_is_permanent() { + let creds = SchannelCred::builder().acquire(Direction::Outbound).unwrap(); + let stream = TcpStream::connect("self-signed.badssl.com:443").unwrap(); + // temporarily switch to nonblocking to allow us to construct the stream + // without validating + stream.set_nonblocking(true).unwrap(); + let stream = tls_stream::Builder::new() + .domain("self-signed.badssl.com") + .connect(creds, stream); + let stream = match stream { + Err(HandshakeError::Interrupted(s)) => s, + _ => panic!(), + }; + stream.get_ref().set_nonblocking(false).unwrap(); + let err = unwrap_handshake(stream.handshake().err().unwrap()); + assert_eq!(err.raw_os_error().unwrap(), + winerror::CERT_E_UNTRUSTEDROOT as i32); +} + +#[test] +fn verify_callback_success() { + let creds = SchannelCred::builder() + .acquire(Direction::Outbound) + .unwrap(); + let stream = TcpStream::connect("self-signed.badssl.com:443").unwrap(); + let mut stream = tls_stream::Builder::new() + .domain("self-signed.badssl.com") + .verify_callback(|validation_result| { + assert!(validation_result.result().is_err()); + Ok(()) + }) + .connect(creds, stream) + .unwrap(); + stream.write_all(b"GET / HTTP/1.0\r\nHost: self-signed.badssl.com\r\n\r\n").unwrap(); + let mut out = vec![]; + stream.read_to_end(&mut out).unwrap(); + assert!(out.starts_with(b"HTTP/1.1 200 OK")); + assert!(out.ends_with(b"</html>\n")); +} + +#[test] +fn verify_callback_error() { + let creds = SchannelCred::builder() + .acquire(Direction::Outbound) + .unwrap(); + let stream = TcpStream::connect("google.com:443").unwrap(); + let err = tls_stream::Builder::new() + .domain("google.com") + .verify_callback(|validation_result| { + assert!(validation_result.result().is_ok()); + Err(io::Error::from_raw_os_error(winerror::CERT_E_UNTRUSTEDROOT)) + }) + .connect(creds, stream) + .err() + .unwrap(); + let err = unwrap_handshake(err); + assert_eq!(err.raw_os_error().unwrap(), + winerror::CERT_E_UNTRUSTEDROOT as i32); +} + +#[test] +fn verify_callback_gives_failed_cert() { + let creds = SchannelCred::builder() + .acquire(Direction::Outbound) + .unwrap(); + let stream = TcpStream::connect("self-signed.badssl.com:443").unwrap(); + let err = tls_stream::Builder::new() + .domain("self-signed.badssl.com") + .verify_callback(|validation_result| { + let expected_finger = vec!(100, 20, 80, 217, 74, 101, 250, 235, 59, 99, 16, 40, 216, 232, 108, 149, 67, 29, 184, 17); + assert_eq!(validation_result.failed_certificate().unwrap().fingerprint(HashAlgorithm::sha1()).unwrap(), expected_finger); + Err(io::Error::from_raw_os_error(winerror::CERT_E_UNTRUSTEDROOT)) + }) + .connect(creds, stream) + .err() + .unwrap(); + let err = unwrap_handshake(err); + assert_eq!(err.raw_os_error().unwrap(), + winerror::CERT_E_UNTRUSTEDROOT as i32); +} + +const FRIENDLY_NAME: &'static str = "schannel-rs localhost testing cert"; + +lazy_static! { + static ref szOID_RSA_SHA256RSA: Vec<u8> = + wincrypt::szOID_RSA_SHA256RSA.bytes().chain(Some(0)).collect(); +} + +fn install_certificate() -> io::Result<CertContext> { + unsafe { + let mut provider = 0; + let mut hkey = 0; + + let mut buffer = "schannel-rs test suite".encode_utf16() + .chain(Some(0)) + .collect::<Vec<_>>(); + let res = wincrypt::CryptAcquireContextW(&mut provider, + buffer.as_ptr(), + ptr::null_mut(), + wincrypt::PROV_RSA_FULL, + wincrypt::CRYPT_MACHINE_KEYSET); + if res != winapi::TRUE { + // create a new key container (since it does not exist) + let res = wincrypt::CryptAcquireContextW(&mut provider, + buffer.as_ptr(), + ptr::null_mut(), + wincrypt::PROV_RSA_FULL, + wincrypt::CRYPT_NEWKEYSET | wincrypt::CRYPT_MACHINE_KEYSET); + if res != winapi::TRUE { + return Err(Error::last_os_error()) + } + } + + // create a new keypair (RSA-2048) + let res = wincrypt::CryptGenKey(provider, + wincrypt::AT_SIGNATURE, + 0x0800<<16 | wincrypt::CRYPT_EXPORTABLE, + &mut hkey); + if res != winapi::TRUE { + return Err(Error::last_os_error()); + } + + // start creating the certificate + let name = "CN=localhost,O=schannel-rs,OU=schannel-rs,G=schannel_rs".encode_utf16() + .chain(Some(0)) + .collect::<Vec<_>>(); + let mut cname_buffer: [ntdef::WCHAR; lmcons::UNLEN as usize + 1] = mem::zeroed(); + let mut cname_len = cname_buffer.len() as winapi::DWORD; + let res = wincrypt::CertStrToNameW(wincrypt::X509_ASN_ENCODING, + name.as_ptr(), + wincrypt::CERT_X500_NAME_STR, + ptr::null_mut(), + cname_buffer.as_mut_ptr() as *mut u8, + &mut cname_len, + ptr::null_mut()); + if res != winapi::TRUE { + return Err(Error::last_os_error()); + } + + let mut subject_issuer = wincrypt::CERT_NAME_BLOB { + cbData: cname_len, + pbData: cname_buffer.as_ptr() as *mut u8, + }; + let mut key_provider = wincrypt::CRYPT_KEY_PROV_INFO { + pwszContainerName: buffer.as_mut_ptr(), + pwszProvName: ptr::null_mut(), + dwProvType: wincrypt::PROV_RSA_FULL, + dwFlags: wincrypt::CRYPT_MACHINE_KEYSET, + cProvParam: 0, + rgProvParam: ptr::null_mut(), + dwKeySpec: wincrypt::AT_SIGNATURE, + }; + let mut sig_algorithm = wincrypt::CRYPT_ALGORITHM_IDENTIFIER { + pszObjId: szOID_RSA_SHA256RSA.as_ptr() as *mut _, + Parameters: mem::zeroed(), + }; + let mut expiration_date: minwinbase::SYSTEMTIME = mem::zeroed(); + sysinfoapi::GetSystemTime(&mut expiration_date); + let mut file_time: winapi::FILETIME = mem::zeroed(); + let res = timezoneapi::SystemTimeToFileTime(&mut expiration_date, + &mut file_time); + if res != winapi::TRUE { + return Err(Error::last_os_error()); + } + let mut timestamp: u64 = file_time.dwLowDateTime as u64 | + (file_time.dwHighDateTime as u64) << 32; + // one day, timestamp unit is in 100 nanosecond intervals + timestamp += (1E9 as u64) / 100 * (60 * 60 * 24); + file_time.dwLowDateTime = timestamp as u32; + file_time.dwHighDateTime = (timestamp >> 32) as u32; + let res = timezoneapi::FileTimeToSystemTime(&file_time, + &mut expiration_date); + if res != winapi::TRUE { + return Err(Error::last_os_error()); + } + + // create a self signed certificate + let cert_context = wincrypt::CertCreateSelfSignCertificate(0 as basetsd::ULONG_PTR, + &mut subject_issuer, + 0, + &mut key_provider, + &mut sig_algorithm, + ptr::null_mut(), + &mut expiration_date, + ptr::null_mut()); + if cert_context.is_null() { + return Err(Error::last_os_error()); + } + let cert_context = CertContext::from_inner(cert_context); + try!(cert_context.set_friendly_name(FRIENDLY_NAME)); + + // install the certificate to the machine's local store + io::stdout().write_all(br#" + +The schannel-rs test suite is about to add a certificate to your set of root +and trusted certificates. This certificate should be for the domain "localhost" +with the description related to "schannel". This certificate is only valid for +one day and will be automatically deleted if you re-run the schannel-rs test +suite later. + +If you would rather not do this please cancel the addition and re-run the +test suite with SCHANNEL_RS_SKIP_SERVER_TESTS=1. + +"#).unwrap(); + try!(local_root_store().add_cert(&cert_context, CertAdd::ReplaceExisting)); + Ok(cert_context) + } +} + +fn local_root_store() -> CertStore { + if env::var("APPVEYOR").is_ok() { + CertStore::open_local_machine("Root").unwrap() + } else { + CertStore::open_current_user("Root").unwrap() + } +} + +fn localhost_cert() -> Option<CertContext> { + if env::var("SCHANNEL_RS_SKIP_SERVER_TESTS").is_ok() { + return None + } + + // Our tests need a certficiate that the system trusts to run with, and we + // do this by basically generating a certificate on the fly. This + // initialization block synchronizes tests to ensure that we only generate + // one certificate which is then used by all the tests. + // + // First we check to see if the root trust store already has one of our + // certificates, identified by the "friendly name" we set when the + // certificate was created. If it's expired, then we delete it and generate + // another. If none is found, we also generate another. + // + // Note that generating a certificate and adding it to the root trust store + // will likely trigger a prompt to the user asking if they want to do that, + // so we generate certificates that are valid for some amount of time so you + // don't have to hit the "OK" button each time you run `cargo test`. + // + // After the initialization is performed we just probe the root store again + // and find the certificate we added (or was already there). + static INIT: Once = ONCE_INIT; + INIT.call_once(|| { + for cert in local_root_store().certs() { + let name = match cert.friendly_name() { + Ok(name) => name, + Err(_) => continue, + }; + if name != FRIENDLY_NAME { + continue + } + if !cert.is_time_valid().unwrap() { + io::stdout().write_all(br#" + +The schannel-rs test suite is about to delete an old copy of one of its +certificates from your root trust store. This certificate was only valid for one +day and it is no longer needed. The host should be "localhost" and the +description should mention "schannel". + +"#).unwrap(); + cert.delete().unwrap(); + } else { + return + } + } + + install_certificate().unwrap(); + }); + + for cert in local_root_store().certs() { + let name = match cert.friendly_name() { + Ok(name) => name, + Err(_) => continue, + }; + if name == FRIENDLY_NAME { + return Some(cert) + } + } + + panic!("couldn't find a cert"); +} + +#[test] +fn accept_a_socket() { + let cert = match localhost_cert() { + Some(cert) => cert, + None => return, + }; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let t = thread::spawn(move || { + let stream = TcpStream::connect(&addr).unwrap(); + let creds = SchannelCred::builder() + .acquire(Direction::Outbound).unwrap(); + let mut stream = tls_stream::Builder::new() + .domain("localhost") + .connect(creds, stream) + .unwrap(); + stream.write_all(&[1, 2, 3, 4]).unwrap(); + stream.flush().unwrap(); + assert_eq!(stream.read(&mut [0; 1024]).unwrap(), 4); + stream.shutdown().unwrap(); + }); + + let stream = listener.accept().unwrap().0; + let creds = SchannelCred::builder() + .cert(cert) + .acquire(Direction::Inbound) + .unwrap(); + let mut stream = tls_stream::Builder::new() + .accept(creds, stream) + .unwrap(); + assert_eq!(stream.read(&mut [0; 1024]).unwrap(), 4); + stream.write_all(&[1, 2, 3, 4]).unwrap(); + stream.flush().unwrap(); + let mut buf = [0; 1]; + assert_eq!(stream.read(&mut buf).unwrap(), 0); + + t.join().unwrap(); +} + +#[test] +fn accept_one_byte_at_a_time() { + let cert = match localhost_cert() { + Some(cert) => cert, + None => return, + }; + + #[derive(Debug)] + struct OneByteAtATime<S> { + inner: S, + } + + impl<S: Read> Read for OneByteAtATime<S> { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.inner.read(&mut buf[..1]) + } + } + + impl<S: Write> Write for OneByteAtATime<S> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.inner.write(&buf[..1]) + } + + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() + } + } + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let t = thread::spawn(move || { + let stream = TcpStream::connect(&addr).unwrap(); + let creds = SchannelCred::builder() + .acquire(Direction::Outbound).unwrap(); + let mut stream = tls_stream::Builder::new() + .domain("localhost") + .connect(creds, OneByteAtATime { inner: stream }) + .unwrap(); + stream.write_all(&[1, 2, 3, 4]).unwrap(); + stream.flush().unwrap(); + assert_eq!(stream.read(&mut [0; 1024]).unwrap(), 4); + stream.shutdown().unwrap(); + }); + + let stream = listener.accept().unwrap().0; + let creds = SchannelCred::builder() + .cert(cert) + .acquire(Direction::Inbound) + .unwrap(); + let mut stream = tls_stream::Builder::new() + .accept(creds, OneByteAtATime { inner: stream }) + .unwrap(); + assert_eq!(stream.read(&mut [0; 1024]).unwrap(), 4); + stream.write_all(&[1, 2, 3, 4]).unwrap(); + stream.flush().unwrap(); + let mut buf = [0; 1]; + assert_eq!(stream.read(&mut buf).unwrap(), 0); + + t.join().unwrap(); +} + +#[test] +fn split_cert_key() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let t = thread::spawn(move || { + let cert = include_bytes!("../test/cert.der"); + let mut store = Memory::new().unwrap(); + store.add_encoded_certificate(cert).unwrap(); + let store = store.into_store(); + + let stream = TcpStream::connect(&addr).unwrap(); + let creds = SchannelCred::builder() + .acquire(Direction::Outbound).unwrap(); + let mut stream = tls_stream::Builder::new() + .domain("foobar.com") + .cert_store(store) + .connect(creds, stream) + .unwrap(); + stream.write_all(&[1, 2, 3, 4]).unwrap(); + stream.flush().unwrap(); + assert_eq!(stream.read(&mut [0; 1024]).unwrap(), 4); + stream.shutdown().unwrap(); + }); + + let cert = include_bytes!("../test/cert.der"); + let cert = CertContext::new(cert).unwrap(); + + let mut options = AcquireOptions::new(); + options.container("schannel-test"); + let type_ = ProviderType::rsa_full(); + + let mut container = match options.acquire(type_) { + Ok(container) => container, + Err(_) => options.new_keyset(true).acquire(type_).unwrap(), + }; + let key = include_bytes!("../test/key.key"); + container.import() + .import(key) + .unwrap(); + + cert.set_key_prov_info() + .container("schannel-test") + .type_(type_) + .keep_open(true) + .key_spec(KeySpec::key_exchange()) + .set() + .unwrap(); + + let stream = listener.accept().unwrap().0; + let creds = SchannelCred::builder() + .cert(cert) + .acquire(Direction::Inbound) + .unwrap(); + let mut stream = tls_stream::Builder::new() + .accept(creds, stream) + .unwrap(); + assert_eq!(stream.read(&mut [0; 1024]).unwrap(), 4); + stream.write_all(&[1, 2, 3, 4]).unwrap(); + stream.flush().unwrap(); + let mut buf = [0; 1]; + assert_eq!(stream.read(&mut buf).unwrap(), 0); + + t.join().unwrap(); +} diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/src/tls_stream.rs cargo-0.26.0/vendor/schannel-0.1.11/src/tls_stream.rs --- cargo-0.25.0/vendor/schannel-0.1.11/src/tls_stream.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/src/tls_stream.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,884 @@ +//! Schannel TLS streams. +use std::any::Any; +use std::cmp; +use std::error::Error; +use std::fmt; +use std::io::{self, Read, BufRead, Write, Cursor}; +use std::mem; +use std::ptr; +use std::slice; +use std::sync::Arc; +use winapi::shared::minwindef as winapi; +use winapi::shared::{ntdef, sspi, winerror}; +use winapi::um::{self, wincrypt}; + +use {INIT_REQUESTS, ACCEPT_REQUESTS, Inner, secbuf, secbuf_desc}; +use cert_chain::{CertChain, CertChainContext}; +use cert_store::{CertAdd, CertStore}; +use cert_context::CertContext; +use security_context::SecurityContext; +use context_buffer::ContextBuffer; +use schannel_cred::SchannelCred; + +lazy_static! { + static ref szOID_PKIX_KP_SERVER_AUTH: Vec<u8> = + wincrypt::szOID_PKIX_KP_SERVER_AUTH.bytes().chain(Some(0)).collect(); + static ref szOID_SERVER_GATED_CRYPTO: Vec<u8> = + wincrypt::szOID_SERVER_GATED_CRYPTO.bytes().chain(Some(0)).collect(); + static ref szOID_SGC_NETSCAPE: Vec<u8> = + wincrypt::szOID_SGC_NETSCAPE.bytes().chain(Some(0)).collect(); +} + +/// A builder type for `TlsStream`s. +#[derive(Default)] +pub struct Builder { + domain: Option<Vec<u16>>, + verify_callback: Option<Arc<Fn(CertValidationResult) -> io::Result<()> + Sync + Send>>, + cert_store: Option<CertStore>, +} + +impl Builder { + /// Returns a new `Builder`. + pub fn new() -> Builder { + Builder::default() + } + + /// Sets the domain associated with connections created with this `Builder`. + /// + /// The domain will be used for Server Name Indication as well as + /// certificate validation. + pub fn domain(&mut self, domain: &str) -> &mut Builder { + self.domain = Some(domain.encode_utf16().chain(Some(0)).collect()); + self + } + + /// Set a verification callback to be used for connections created with this `Builder`. + /// + /// The callback is provided with an io::Result indicating if the (pre)validation was + /// successful. The Ok() variant indicates a successful validation while the Err() variant + /// contains the errorcode returned from the internal verification process. + /// The validated certificate, is accessible through the second argument of the closure. + pub fn verify_callback<F>(&mut self, callback: F) -> &mut Builder + where F: Fn(CertValidationResult) -> io::Result<()> + 'static + Sync + Send + { + self.verify_callback = Some(Arc::new(callback)); + self + } + + /// Specifies a custom certificate store which is later used when validating + /// a server's certificate. + /// + /// This option is only used for client connections and is used to construct + /// the certificate chain which the server's certificate is validated + /// against. + /// + /// Note that adding certificates here means that they are + /// implicitly trusted. + pub fn cert_store(&mut self, cert_store: CertStore) -> &mut Builder { + self.cert_store = Some(cert_store); + self + } + + /// Initialize a new TLS session where the stream provided will be + /// connecting to a remote TLS server. + /// + /// If the stream provided is a blocking stream then the entire handshake + /// will be performed if possible, but if the stream is in nonblocking mode + /// then a `HandshakeError::Interrupted` variant may be returned. This + /// type can then be extracted to later call + /// `MidHandshakeTlsStream::handshake` when data becomes available. + pub fn connect<S>(&mut self, + cred: SchannelCred, + stream: S) + -> Result<TlsStream<S>, HandshakeError<S>> + where S: Read + Write + { + self.initialize(cred, false, stream) + } + + /// Initialize a new TLS session where the stream provided will be + /// accepting a connection. + /// + /// This method will tweak the protocol for "who talks first" and also + /// currently disables validation of the client that's connecting to us. + /// + /// If the stream provided is a blocking stream then the entire handshake + /// will be performed if possible, but if the stream is in nonblocking mode + /// then a `HandshakeError::Interrupted` variant may be returned. This + /// type can then be extracted to later call + /// `MidHandshakeTlsStream::handshake` when data becomes available. + pub fn accept<S>(&mut self, + cred: SchannelCred, + stream: S) + -> Result<TlsStream<S>, HandshakeError<S>> + where S: Read + Write + { + self.initialize(cred, true, stream) + } + + fn initialize<S>(&mut self, + mut cred: SchannelCred, + accept: bool, + stream: S) + -> Result<TlsStream<S>, HandshakeError<S>> + where S: Read + Write + { + let domain = self.domain.as_ref().map(|s| &s[..]); + let (ctxt, buf) = match SecurityContext::initialize(&mut cred, + accept, + domain) { + Ok(pair) => pair, + Err(e) => return Err(HandshakeError::Failure(e)), + }; + + let stream = TlsStream { + cred: cred, + context: ctxt, + cert_store: self.cert_store.clone(), + domain: self.domain.clone(), + verify_callback: self.verify_callback.clone(), + stream: stream, + accept: accept, + accept_first: true, + state: State::Initializing { + needs_flush: false, + more_calls: true, + shutting_down: false, + validated: false, + }, + needs_read: 1, + dec_in: Cursor::new(Vec::new()), + enc_in: Cursor::new(Vec::new()), + out_buf: Cursor::new(buf.map(|b| b.to_owned()).unwrap_or(Vec::new())), + last_write_len: 0, + }; + + MidHandshakeTlsStream { + inner: stream, + }.handshake() + } +} + +enum State { + Initializing { + needs_flush: bool, + more_calls: bool, + shutting_down: bool, + validated: bool, + }, + Streaming { sizes: sspi::SecPkgContext_StreamSizes, }, + Shutdown, +} + +/// An Schannel TLS stream. +pub struct TlsStream<S> { + cred: SchannelCred, + context: SecurityContext, + cert_store: Option<CertStore>, + domain: Option<Vec<u16>>, + verify_callback: Option<Arc<Fn(CertValidationResult) -> io::Result<()> + Sync + Send>>, + stream: S, + state: State, + accept: bool, + accept_first: bool, + needs_read: usize, + // valid from position() to len() + dec_in: Cursor<Vec<u8>>, + // valid from 0 to position() + enc_in: Cursor<Vec<u8>>, + // valid from position() to len() + out_buf: Cursor<Vec<u8>>, + /// the (unencrypted) length of the last write call used to track writes + last_write_len: usize, +} + +/// ensures that a TlsStream is always Sync/Send +fn _is_sync() { + fn sync<T: Sync + Send>() {} + sync::<TlsStream<()>>(); +} + +/// A failure which can happen during the `Builder::initialize` phase, either an +/// I/O error or an intermediate stream which has not completed its handshake. +#[derive(Debug)] +pub enum HandshakeError<S> { + /// A fatal I/O error occurred + Failure(io::Error), + /// The stream connection is in progress, but the handshake is not completed + /// yet. + Interrupted(MidHandshakeTlsStream<S>), +} + +/// A struct used to wrap various cert chain validation results for callback processing. +pub struct CertValidationResult { + chain: CertChainContext, + res: i32, + chain_index: i32, + element_index: i32, +} + +impl CertValidationResult { + /// Returns the certificate that failed validation if applicable + pub fn failed_certificate(&self) -> Option<CertContext> { + if let Some(cert_chain) = self.chain.get_chain(self.chain_index as usize) { + return cert_chain.get(self.element_index as usize); + } + None + } + + /// Returns the final certificate chain in the certificate context if applicable + pub fn chain(&self) -> Option<CertChain> { + self.chain.final_chain() + } + + /// Returns the result of the built-in certificate verification process. + pub fn result(&self) -> io::Result<()> { + if self.res as u32 != winerror::ERROR_SUCCESS { + Err(io::Error::from_raw_os_error(self.res)) + } else { + Ok(()) + } + } +} + +impl<S: fmt::Debug + Any> Error for HandshakeError<S> { + fn description(&self) -> &str { + match *self { + HandshakeError::Failure(_) => "failed to perform handshake", + HandshakeError::Interrupted(_) => "interrupted performing handshake", + } + } + + fn cause(&self) -> Option<&Error> { + match *self { + HandshakeError::Failure(ref e) => Some(e), + HandshakeError::Interrupted(_) => None, + } + } +} + +impl<S: fmt::Debug + Any> fmt::Display for HandshakeError<S> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(f.write_str(self.description())); + if let Some(e) = self.cause() { + try!(write!(f, ": {}", e)); + } + Ok(()) + } +} + +/// A stream which has not yet completed its handshake. +#[derive(Debug)] +pub struct MidHandshakeTlsStream<S> { + inner: TlsStream<S>, +} + +impl<S> fmt::Debug for TlsStream<S> + where S: fmt::Debug +{ + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.debug_struct("TlsStream") + .field("stream", &self.stream) + .finish() + } +} + +impl<S> TlsStream<S> + where S: Read + Write +{ + /// Returns a reference to the wrapped stream. + pub fn get_ref(&self) -> &S { + &self.stream + } + + /// Returns a mutable reference to the wrapped stream. + pub fn get_mut(&mut self) -> &mut S { + &mut self.stream + } + + /// Returns a reference to the buffer of pending data. + /// + /// Like `BufRead::fill_buf` except that it will return an empty slice + /// rather than reading from the wrapped stream if there is no buffered + /// data. + pub fn get_buf(&self) -> &[u8] { + &self.dec_in.get_ref()[self.dec_in.position() as usize..] + } + + /// Shuts the TLS session down. + pub fn shutdown(&mut self) -> io::Result<()> { + match self.state { + State::Shutdown => return Ok(()), + State::Initializing { shutting_down: true, .. } => {} + _ => { + unsafe { + let mut token = um::schannel::SCHANNEL_SHUTDOWN; + let ptr = &mut token as *mut _ as *mut u8; + let size = mem::size_of_val(&token); + let token = slice::from_raw_parts_mut(ptr, size); + let mut buf = [secbuf(sspi::SECBUFFER_TOKEN, Some(token))]; + let mut desc = secbuf_desc(&mut buf); + + match sspi::ApplyControlToken(self.context.get_mut(), &mut desc) { + winerror::SEC_E_OK => {} + err => return Err(io::Error::from_raw_os_error(err as i32)), + } + } + + self.state = State::Initializing { + needs_flush: false, + more_calls: true, + shutting_down: true, + validated: false, + }; + self.needs_read = 0; + } + } + + self.initialize().map(|_| ()) + } + + fn step_initialize(&mut self) -> io::Result<()> { + unsafe { + let pos = self.enc_in.position() as usize; + let mut inbufs = [secbuf(sspi::SECBUFFER_TOKEN, + Some(&mut self.enc_in.get_mut()[..pos])), + secbuf(sspi::SECBUFFER_EMPTY, None)]; + let mut inbuf_desc = secbuf_desc(&mut inbufs); + + let mut outbufs = [secbuf(sspi::SECBUFFER_TOKEN, None), + secbuf(sspi::SECBUFFER_ALERT, None), + secbuf(sspi::SECBUFFER_EMPTY, None)]; + let mut outbuf_desc = secbuf_desc(&mut outbufs); + + let mut attributes = 0; + + let status = if self.accept { + let ptr = if self.accept_first { + ptr::null_mut() + } else { + self.context.get_mut() + }; + sspi::AcceptSecurityContext(self.cred.get_mut(), + ptr, + &mut inbuf_desc, + ACCEPT_REQUESTS, + 0, + self.context.get_mut(), + &mut outbuf_desc, + &mut attributes, + ptr::null_mut()) + } else { + let domain = self.domain + .as_ref() + .map(|b| b.as_ptr() as *mut u16) + .unwrap_or(ptr::null_mut()); + + sspi::InitializeSecurityContextW(self.cred.get_mut(), + self.context.get_mut(), + domain, + INIT_REQUESTS, + 0, + 0, + &mut inbuf_desc, + 0, + ptr::null_mut(), + &mut outbuf_desc, + &mut attributes, + ptr::null_mut()) + }; + + for buf in &outbufs[1..] { + if !buf.pvBuffer.is_null() { + sspi::FreeContextBuffer(buf.pvBuffer); + } + } + + match status { + winerror::SEC_I_CONTINUE_NEEDED => { + // Windows apparently doesn't like AcceptSecurityContext + // being called as if it were the second time unless the + // first call to AcceptSecurityContext succeeded with + // CONTINUE_NEEDED. + // + // In other words, if we were to set `accept_first` to + // `false` after the literal first call to + // `AcceptSecurityContext` while the call returned + // INCOMPLETE_MESSAGE, the next call would return an error. + // + // For that reason we only set `accept_first` to false here + // once we've actually successfully received the full + // "token" from the client. + self.accept_first = false; + let nread = if inbufs[1].BufferType == sspi::SECBUFFER_EXTRA { + self.enc_in.position() as usize - inbufs[1].cbBuffer as usize + } else { + self.enc_in.position() as usize + }; + let to_write = ContextBuffer(outbufs[0]); + + self.consume_enc_in(nread); + self.needs_read = (self.enc_in.position() == 0) as usize; + self.out_buf.get_mut().extend_from_slice(&to_write); + } + winerror::SEC_E_INCOMPLETE_MESSAGE => { + self.needs_read = if inbufs[1].BufferType == sspi::SECBUFFER_MISSING { + inbufs[1].cbBuffer as usize + } else { + 1 + }; + } + winerror::SEC_E_OK => { + let nread = if inbufs[1].BufferType == sspi::SECBUFFER_EXTRA { + self.enc_in.position() as usize - inbufs[1].cbBuffer as usize + } else { + self.enc_in.position() as usize + }; + let to_write = if outbufs[0].pvBuffer.is_null() { + None + } else { + Some(ContextBuffer(outbufs[0])) + }; + + self.consume_enc_in(nread); + self.needs_read = (self.enc_in.position() == 0) as usize; + if let Some(to_write) = to_write { + self.out_buf.get_mut().extend_from_slice(&to_write); + } + if self.enc_in.position() != 0 { + try!(self.decrypt()); + } + if let State::Initializing { ref mut more_calls, .. } = self.state { + *more_calls = false; + } + } + _ => { + return Err(io::Error::from_raw_os_error(status as i32)) + } + } + Ok(()) + } + } + + fn initialize(&mut self) -> io::Result<Option<sspi::SecPkgContext_StreamSizes>> { + loop { + match self.state { + State::Initializing { mut needs_flush, more_calls, shutting_down, validated } => { + if try!(self.write_out()) > 0 { + needs_flush = true; + if let State::Initializing { ref mut needs_flush, .. } = self.state { + *needs_flush = true; + } + } + + if needs_flush { + try!(self.stream.flush()); + if let State::Initializing { ref mut needs_flush, .. } = self.state { + *needs_flush = false; + } + } + + if !shutting_down && !validated { + // on the last call, we require a valid certificate + if try!(self.validate(!more_calls)) { + if let State::Initializing { ref mut validated, .. } = self.state { + *validated = true; + } + } + } + + if !more_calls { + self.state = if shutting_down { + State::Shutdown + } else { + State::Streaming { sizes: try!(self.context.stream_sizes()) } + }; + continue; + } + + if self.needs_read > 0 { + if try!(self.read_in()) == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, + "unexpected EOF during handshake")); + } + } + + try!(self.step_initialize()); + } + State::Streaming { sizes } => return Ok(Some(sizes)), + State::Shutdown => return Ok(None), + } + } + } + + /// Returns true when the certificate was succesfully verified + /// Returns false, when a verification isn't necessary (yet) + /// Returns an error when the verification failed + fn validate(&mut self, require_cert: bool) -> io::Result<bool> { + // If we're accepting connections then we don't perform any validation + // for the remote certificate, that's what they're doing! + if self.accept { + return Ok(false); + } + + let cert_context = match self.context.remote_cert() { + Err(_) if !require_cert => return Ok(false), + ret => try!(ret) + }; + + let cert_chain = unsafe { + let cert_store = match (cert_context.cert_store(), &self.cert_store) { + (Some(ref mut chain_certs), &Some(ref extra_certs)) => { + for extra_cert in extra_certs.certs() { + try!(chain_certs.add_cert(&extra_cert, CertAdd::ReplaceExisting)); + } + chain_certs.as_inner() + }, + (Some(chain_certs), &None) => chain_certs.as_inner(), + (None, &Some(ref extra_certs)) => extra_certs.as_inner(), + (None, &None) => ptr::null_mut() + }; + + let flags = wincrypt::CERT_CHAIN_CACHE_END_CERT | + wincrypt::CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY | + wincrypt::CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT; + + let mut para: wincrypt::CERT_CHAIN_PARA = mem::zeroed(); + para.cbSize = mem::size_of_val(¶) as winapi::DWORD; + para.RequestedUsage.dwType = wincrypt::USAGE_MATCH_TYPE_OR; + + let mut identifiers = [szOID_PKIX_KP_SERVER_AUTH.as_ptr() as ntdef::LPSTR, + szOID_SERVER_GATED_CRYPTO.as_ptr() as ntdef::LPSTR, + szOID_SGC_NETSCAPE.as_ptr() as ntdef::LPSTR]; + para.RequestedUsage.Usage.cUsageIdentifier = identifiers.len() as winapi::DWORD; + para.RequestedUsage.Usage.rgpszUsageIdentifier = identifiers.as_mut_ptr(); + + let mut cert_chain = mem::zeroed(); + + let res = wincrypt::CertGetCertificateChain(ptr::null_mut(), + cert_context.as_inner(), + ptr::null_mut(), + cert_store, + &mut para, + flags, + ptr::null_mut(), + &mut cert_chain); + + if res == winapi::TRUE { + CertChainContext(cert_chain as *mut _) + } else { + return Err(io::Error::last_os_error()) + } + }; + + unsafe { + // check if we trust the root-CA explicitly + let mut para_flags = wincrypt::CERT_CHAIN_POLICY_IGNORE_ALL_REV_UNKNOWN_FLAGS; + if let Some(ref mut store) = self.cert_store { + if let Some(chain) = cert_chain.final_chain() { + // check if any cert of the chain is in the passed store (and therefore trusted) + if chain.certificates().any(|cert| store.certs().any(|root_cert| root_cert == cert)) { + para_flags |= wincrypt::CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG; + } + } + } + + let mut extra_para: wincrypt::SSL_EXTRA_CERT_CHAIN_POLICY_PARA = mem::zeroed(); + *extra_para.u.cbSize_mut() = mem::size_of_val(&extra_para) as winapi::DWORD; + extra_para.dwAuthType = wincrypt::AUTHTYPE_SERVER; + if let Some(ref mut name) = self.domain { + extra_para.pwszServerName = name.as_mut_ptr(); + } + + let mut para: wincrypt::CERT_CHAIN_POLICY_PARA = mem::zeroed(); + para.cbSize = mem::size_of_val(¶) as winapi::DWORD; + para.dwFlags = para_flags; + para.pvExtraPolicyPara = &mut extra_para as *mut _ as *mut _; + + let mut status: wincrypt::CERT_CHAIN_POLICY_STATUS = mem::zeroed(); + status.cbSize = mem::size_of_val(&status) as winapi::DWORD; + + let verify_chain_policy_structure = wincrypt::CERT_CHAIN_POLICY_SSL as ntdef::LPCSTR; + let res = wincrypt::CertVerifyCertificateChainPolicy(verify_chain_policy_structure, + cert_chain.0, + &mut para, + &mut status); + if res == winapi::FALSE { + return Err(io::Error::last_os_error()) + } + + let mut verify_result = if status.dwError != winerror::ERROR_SUCCESS { + Err(io::Error::from_raw_os_error(status.dwError as i32)) + } else { + Ok(()) + }; + + // check if there's a user-specified verify callback + if let Some(ref callback) = self.verify_callback { + verify_result = callback(CertValidationResult{ + chain: cert_chain, + res: status.dwError as i32, + chain_index: status.lChainIndex, + element_index: status.lElementIndex}); + } + try!(verify_result); + } + Ok(true) + } + + fn write_out(&mut self) -> io::Result<usize> { + let mut out = 0; + while self.out_buf.position() as usize != self.out_buf.get_ref().len() { + let position = self.out_buf.position() as usize; + let nwritten = try!(self.stream.write(&self.out_buf.get_ref()[position..])); + out += nwritten; + self.out_buf.set_position((position + nwritten) as u64); + } + + Ok(out) + } + + fn read_in(&mut self) -> io::Result<usize> { + let mut sum_nread = 0; + + while self.needs_read > 0 { + let existing_len = self.enc_in.position() as usize; + let min_len = cmp::max(cmp::max(1024, 2 * existing_len), self.needs_read); + if self.enc_in.get_ref().len() < min_len { + self.enc_in.get_mut().resize(min_len, 0); + } + let nread = { + let buf = &mut self.enc_in.get_mut()[existing_len..]; + try!(self.stream.read(buf)) + }; + self.enc_in.set_position((existing_len + nread) as u64); + self.needs_read = self.needs_read.saturating_sub(nread); + if nread == 0 { + break; + } + sum_nread += nread; + } + + Ok(sum_nread) + } + + fn consume_enc_in(&mut self, nread: usize) { + let size = self.enc_in.position() as usize; + assert!(size >= nread); + let count = size - nread; + + if count > 0 { + self.enc_in.get_mut().drain(..nread); + } + + self.enc_in.set_position(count as u64); + } + + fn decrypt(&mut self) -> io::Result<bool> { + unsafe { + let position = self.enc_in.position() as usize; + let mut bufs = [secbuf(sspi::SECBUFFER_DATA, + Some(&mut self.enc_in.get_mut()[..position])), + secbuf(sspi::SECBUFFER_EMPTY, None), + secbuf(sspi::SECBUFFER_EMPTY, None), + secbuf(sspi::SECBUFFER_EMPTY, None)]; + let mut bufdesc = secbuf_desc(&mut bufs); + + match sspi::DecryptMessage(self.context.get_mut(), + &mut bufdesc, + 0, + ptr::null_mut()) { + winerror::SEC_E_OK => { + let start = bufs[1].pvBuffer as usize - self.enc_in.get_ref().as_ptr() as usize; + let end = start + bufs[1].cbBuffer as usize; + self.dec_in.get_mut().clear(); + self.dec_in + .get_mut() + .extend_from_slice(&self.enc_in.get_ref()[start..end]); + self.dec_in.set_position(0); + + let nread = if bufs[3].BufferType == sspi::SECBUFFER_EXTRA { + self.enc_in.position() as usize - bufs[3].cbBuffer as usize + } else { + self.enc_in.position() as usize + }; + self.consume_enc_in(nread); + self.needs_read = (self.enc_in.position() == 0) as usize; + Ok(false) + } + winerror::SEC_E_INCOMPLETE_MESSAGE => { + self.needs_read = if bufs[1].BufferType == sspi::SECBUFFER_MISSING { + bufs[1].cbBuffer as usize + } else { + 1 + }; + Ok(false) + } + winerror::SEC_I_CONTEXT_EXPIRED => Ok(true), + winerror::SEC_I_RENEGOTIATE => { + self.state = State::Initializing { + needs_flush: false, + more_calls: true, + shutting_down: false, + validated: false, + }; + + let nread = if bufs[3].BufferType == sspi::SECBUFFER_EXTRA { + self.enc_in.position() as usize - bufs[3].cbBuffer as usize + } else { + self.enc_in.position() as usize + }; + self.consume_enc_in(nread); + self.needs_read = 0; + Ok(false) + } + e => Err(io::Error::from_raw_os_error(e as i32)), + } + } + } + + fn encrypt(&mut self, buf: &[u8], sizes: &sspi::SecPkgContext_StreamSizes) -> io::Result<()> { + assert!(buf.len() <= sizes.cbMaximumMessage as usize); + + unsafe { + let len = sizes.cbHeader as usize + buf.len() + sizes.cbTrailer as usize; + + if self.out_buf.get_ref().len() < len { + self.out_buf.get_mut().resize(len, 0); + } + + let message_start = sizes.cbHeader as usize; + self.out_buf + .get_mut()[message_start..message_start + buf.len()] + .clone_from_slice(buf); + + let mut bufs = { + let out_buf = self.out_buf.get_mut(); + let size = sizes.cbHeader as usize; + + let header = secbuf(sspi::SECBUFFER_STREAM_HEADER, + Some(&mut out_buf[..size])); + let data = secbuf(sspi::SECBUFFER_DATA, + Some(&mut out_buf[size..size + buf.len()])); + let trailer = secbuf(sspi::SECBUFFER_STREAM_TRAILER, + Some(&mut out_buf[size + buf.len()..])); + let empty = secbuf(sspi::SECBUFFER_EMPTY, None); + [header, data, trailer, empty] + }; + let mut bufdesc = secbuf_desc(&mut bufs); + + match sspi::EncryptMessage(self.context.get_mut(), 0, &mut bufdesc, 0) { + winerror::SEC_E_OK => { + let len = bufs[0].cbBuffer + bufs[1].cbBuffer + bufs[2].cbBuffer; + self.out_buf.get_mut().truncate(len as usize); + self.out_buf.set_position(0); + Ok(()) + } + err => Err(io::Error::from_raw_os_error(err as i32)), + } + } + } +} + +impl<S> MidHandshakeTlsStream<S> + where S: Read + Write, +{ + /// Returns a shared reference to the inner stream. + pub fn get_ref(&self) -> &S { + self.inner.get_ref() + } + + /// Returns a mutable reference to the inner stream. + pub fn get_mut(&mut self) -> &mut S { + self.inner.get_mut() + } + + /// Restarts the handshake process. + pub fn handshake(mut self) -> Result<TlsStream<S>, HandshakeError<S>> { + match self.inner.initialize() { + Ok(_) => Ok(self.inner), + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { + Err(HandshakeError::Interrupted(self)) + } + Err(e) => Err(HandshakeError::Failure(e)), + } + } +} + +impl<S> Write for TlsStream<S> + where S: Read + Write +{ + /// In the case of a WouldBlock error, we expect another call + /// starting with the same input data + /// This is similar to the use of ACCEPT_MOVING_WRITE_BUFFER in openssl + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + let sizes = match try!(self.initialize()) { + Some(sizes) => sizes, + None => return Err(io::Error::from_raw_os_error(winerror::SEC_E_CONTEXT_EXPIRED as i32)), + }; + + // if we have pending output data, it must have been because a previous + // attempt to send this part of the data ran into an error. + if self.out_buf.position() == self.out_buf.get_ref().len() as u64 { + let len = cmp::min(buf.len(), sizes.cbMaximumMessage as usize); + try!(self.encrypt(&buf[..len], &sizes)); + self.last_write_len = len; + } + try!(self.write_out()); + + Ok(self.last_write_len) + } + + fn flush(&mut self) -> io::Result<()> { + // Make sure the write buffer is emptied + try!(self.write_out()); + self.stream.flush() + } +} + +impl<S> Read for TlsStream<S> + where S: Read + Write +{ + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + let nread = { + let read_buf = try!(self.fill_buf()); + let nread = cmp::min(buf.len(), read_buf.len()); + buf[..nread].copy_from_slice(&read_buf[..nread]); + nread + }; + self.consume(nread); + Ok(nread) + } +} + +impl<S> BufRead for TlsStream<S> + where S: Read + Write +{ + fn fill_buf(&mut self) -> io::Result<&[u8]> { + while self.get_buf().is_empty() { + if let None = try!(self.initialize()) { + break; + } + + if self.needs_read > 0 { + if try!(self.read_in()) == 0 { + break; + } + self.needs_read = 0; + } + + let eof = try!(self.decrypt()); + if eof { + break; + } + } + + Ok(self.get_buf()) + } + + fn consume(&mut self, amt: usize) { + let pos = self.dec_in.position() + amt as u64; + assert!(pos <= self.dec_in.get_ref().len() as u64); + self.dec_in.set_position(pos); + } +} Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/schannel-0.1.11/test/cert.der and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/schannel-0.1.11/test/cert.der differ diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/test/cert.pem cargo-0.26.0/vendor/schannel-0.1.11/test/cert.pem --- cargo-0.25.0/vendor/schannel-0.1.11/test/cert.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/test/cert.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDGzCCAgMCCQCHcfe97pgvpTANBgkqhkiG9w0BAQsFADBFMQswCQYDVQQGEwJB +VTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0 +cyBQdHkgTHRkMB4XDTE2MDgxNDE3MDAwM1oXDTI2MDgxMjE3MDAwM1owWjELMAkG +A1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0 +IFdpZGdpdHMgUHR5IEx0ZDETMBEGA1UEAwwKZm9vYmFyLmNvbTCCASIwDQYJKoZI +hvcNAQEBBQADggEPADCCAQoCggEBAKj0JYxEsxejUIX+I5GH0Hg2G0kX/y1H0+Ub +3mw2/Ja5BD/yN96/7zMSumXF8uS3SkmpyiJkbyD01TSRTqjlP7/VCBlyUIChlpLQ +mrGaijZiT/VCyPXqmcwFzXS5IOTpX1olJfW8rA41U1LCIcDUyFf6LtZ/v8rSeKr6 +TuE6SGV4WRaBm1SrjWBeHVV866CRrtSS1ieT2asFsAyOZqWhk2fakwwBDFWDhOGI +ubfO+5aq9cBJbNRlzsgB3UZs3gC0O6GzbnZ6oT0TiJMeTsXXjABLUlaq/rrqFF4Y +euZkkbHTFBMz288PUc3m3ZTcpN+E7+ZOUBRZXKD20K07NugqCzUCAwEAATANBgkq +hkiG9w0BAQsFAAOCAQEASvYHuIl5C0NHBELPpVHNuLbQsDQNKVj3a54+9q1JkiMM +6taEJYfw7K1Xjm4RoiFSHpQBh+PWZS3hToToL2Zx8JfMR5MuAirdPAy1Sia/J/qE +wQdJccqmvuLkLTSlsGbEJ/LUUgOAgrgHOZM5lUgIhCneA0/dWJ3PsN0zvn69/faY +oo1iiolWiIHWWBUSdr3jM2AJaVAsTmLh00cKaDNk37JB940xConBGSl98JPrNrf9 +dUAiT0iIBngDBdHnn/yTj+InVEFyZSKrNtiDSObFHxPcxGteHNrCPJdP1e+GqkHp +HJMRZVCQpSMzvHlofHSNgzWV1MX5h1CP4SGZdBDTfA== +-----END CERTIFICATE----- Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/schannel-0.1.11/test/identity.p12 and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/schannel-0.1.11/test/identity.p12 differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/schannel-0.1.11/test/key.key and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/schannel-0.1.11/test/key.key differ diff -Nru cargo-0.25.0/vendor/schannel-0.1.11/test/key.pem cargo-0.26.0/vendor/schannel-0.1.11/test/key.pem --- cargo-0.25.0/vendor/schannel-0.1.11/test/key.pem 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/schannel-0.1.11/test/key.pem 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCo9CWMRLMXo1CF +/iORh9B4NhtJF/8tR9PlG95sNvyWuQQ/8jfev+8zErplxfLkt0pJqcoiZG8g9NU0 +kU6o5T+/1QgZclCAoZaS0Jqxmoo2Yk/1Qsj16pnMBc10uSDk6V9aJSX1vKwONVNS +wiHA1MhX+i7Wf7/K0niq+k7hOkhleFkWgZtUq41gXh1VfOugka7UktYnk9mrBbAM +jmaloZNn2pMMAQxVg4ThiLm3zvuWqvXASWzUZc7IAd1GbN4AtDuhs252eqE9E4iT +Hk7F14wAS1JWqv666hReGHrmZJGx0xQTM9vPD1HN5t2U3KTfhO/mTlAUWVyg9tCt +OzboKgs1AgMBAAECggEBAKLj6IOJBKXolczpzb8UkyAjAkGBektcseV07gelJ/fk +3z0LuWPv5p12E/HlXB24vU2x/ikUbbP3eMsawRzDEahQqmNmPEkYAYUAy/Qpi9GN +DYvn3LqDec4jVgeQKS+p9H2DzUpTogp8zR2//yzbuWBg2+F//xh7vU0S0RQCziPM +x7RSBgbhxSfChfEJbS2sDnzfh0jRQmoY95iFv7puet1FJtzdZ4fgCd1RqmC2lFM5 +H0eZtN/Cz19lieVs0b996DErdEBqClVZO00eYbRozCDaBzRU3ybB/dMrGJxhkkXm +wb3kWMtziH9qOYsostuHIFu8eKFLloKxFnq2R4DGxOECgYEA2KUIZISOeGJSBcLJ +JAUK2gvgXPNo4HHWIwOA9xeN3ZJlsnPlffXQNnm6t1st1V2gfMm9I2n0m/F0y2B/ +n/XGSa8bghfPA9l0c2h58lkL3JQJR/paa8ycTz+YZPrznEyN7Qa0RrJXUvZv9lQL +Hc3+FHcSHgMqDV2f2bHAEu9YGi0CgYEAx6VEIPNvrHFgjo/jk1RTuk+m0xEWQsZL +Cs+izQMr2TaeJn8LG+93AvFuYn0J0nT3WuStLPrUg8i4IhSS6lf1tId5ivIZPm4r +YwMyblBJXhnHbk7Uqodjfw/3s6V2HAu++B7hTdyVr9DFuST9uv4m8bkPV8rfX1jE +I2rAPVWvgikCgYB+wNAQP547wQrMZBLbCDg5KwmyWJfb+b6X7czexOEz6humNTjo +YZHYzY/5B1fhpk3ntQD8X1nGg5caBvOk21+QbOtjShrM3cXMYCw5JvBRtitX+Zo9 +yBEMLOE0877ki8XeEDYZxu5gk98d+D4oygUGZEQtWxyXhVepPt5qNa8OYQKBgQDH +RVgZI6KFlqzv3wMh3PutbS9wYQ+9GrtwUQuIYe/0YSW9+vSVr5E0qNKrD28sV39F +hBauXLady0yvB6YUrjMbPFW+sCMuQzyfGWPO4+g3OrfqjFiM1ZIkE0YEU9Tt7XNx +qTDtTI1D7bhNMnTnniI1B6ge0und+3XafAThs5L48QKBgQCTTpfqMt8kU3tcI9sf +0MK03y7kA76d5uw0pZbWFy7KI4qnzWutCzb+FMPWWsoFtLJLPZy//u/ZCUVFVa4d +0Y/ASNQIESVPXFLAltlLo4MSmsg1vCBsbviEEaPeEjvMrgki93pYtd/aOSgkYC1T +mEq154s5rmqh+h+XRIf7Au0SLw== +-----END PRIVATE KEY----- Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/schannel-0.1.11/test/self-signed.badssl.com.cer and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/schannel-0.1.11/test/self-signed.badssl.com.cer differ diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.0/appveyor.yml cargo-0.26.0/vendor/scoped-tls-0.1.0/appveyor.yml --- cargo-0.25.0/vendor/scoped-tls-0.1.0/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.0/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -environment: - matrix: - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc - - TARGET: i686-pc-windows-gnu -install: - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" - - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - - SET PATH=%PATH%;C:\MinGW\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test --verbose diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.0/.cargo-checksum.json cargo-0.26.0/vendor/scoped-tls-0.1.0/.cargo-checksum.json --- cargo-0.25.0/vendor/scoped-tls-0.1.0/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"f417c22df063e9450888a7561788e9bd46d3bb3c1466435b4eccb903807f147d"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.0/Cargo.toml cargo-0.26.0/vendor/scoped-tls-0.1.0/Cargo.toml --- cargo-0.25.0/vendor/scoped-tls-0.1.0/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -[package] -name = "scoped-tls" -version = "0.1.0" -authors = ["Alex Crichton <alex@alexcrichton.com>"] -license = "MIT/Apache-2.0" -readme = "README.md" -repository = "https://github.com/alexcrichton/scoped-tls" -homepage = "https://github.com/alexcrichton/scoped-tls" -documentation = "http://alexcrichton.com/scoped-tls" -description = """ -Library implementation of the standard library's old `scoped_thread_local!` -macro for providing scoped access to thread local storage (TLS) so any type can -be stored into TLS. -""" diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.0/LICENSE-APACHE cargo-0.26.0/vendor/scoped-tls-0.1.0/LICENSE-APACHE --- cargo-0.25.0/vendor/scoped-tls-0.1.0/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.0/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.0/LICENSE-MIT cargo-0.26.0/vendor/scoped-tls-0.1.0/LICENSE-MIT --- cargo-0.25.0/vendor/scoped-tls-0.1.0/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.0/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 Alex Crichton - -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. diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.0/README.md cargo-0.26.0/vendor/scoped-tls-0.1.0/README.md --- cargo-0.25.0/vendor/scoped-tls-0.1.0/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.0/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -# scoped-tls - -[![Build Status](https://travis-ci.org/alexcrichton/scoped-tls.svg?branch=master)](https://travis-ci.org/alexcrichton/scoped-tls) -[![Build status](https://ci.appveyor.com/api/projects/status/9tatexq47i3ee13k?svg=true)](https://ci.appveyor.com/project/alexcrichton/flate2-rs) - -[Documentation](http://alexcrichton.com/scoped-tls) - -A Rust library providing the old standard library's `scoped_thread_local!` macro -as a library implementation on crates.io. - -```toml -# Cargo.toml -[dependencies] -scoped-tls = "0.1" -``` - -# License - -`scoped-tls` is primarily distributed under the terms of both the MIT license and -the Apache License (Version 2.0), with portions covered by various BSD-like -licenses. - -See LICENSE-APACHE, and LICENSE-MIT for details. diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.0/src/lib.rs cargo-0.26.0/vendor/scoped-tls-0.1.0/src/lib.rs --- cargo-0.25.0/vendor/scoped-tls-0.1.0/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,249 +0,0 @@ -// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Scoped thread-local storage -//! -//! This module provides the ability to generate *scoped* thread-local -//! variables. In this sense, scoped indicates that thread local storage -//! actually stores a reference to a value, and this reference is only placed -//! in storage for a scoped amount of time. -//! -//! There are no restrictions on what types can be placed into a scoped -//! variable, but all scoped variables are initialized to the equivalent of -//! null. Scoped thread local storage is useful when a value is present for a known -//! period of time and it is not required to relinquish ownership of the -//! contents. -//! -//! # Examples -//! -//! ``` -//! #[macro_use] -//! extern crate scoped_tls; -//! -//! scoped_thread_local!(static FOO: u32); -//! -//! # fn main() { -//! // Initially each scoped slot is empty. -//! assert!(!FOO.is_set()); -//! -//! // When inserting a value, the value is only in place for the duration -//! // of the closure specified. -//! FOO.set(&1, || { -//! FOO.with(|slot| { -//! assert_eq!(*slot, 1); -//! }); -//! }); -//! # } -//! ``` - -#![deny(missing_docs, warnings)] - -use std::cell::Cell; -use std::marker; -use std::thread::LocalKey; - -#[macro_export] -macro_rules! scoped_thread_local { - (static $name:ident: $ty:ty) => ( - static $name: $crate::ScopedKey<$ty> = $crate::ScopedKey { - inner: { - thread_local!(static FOO: ::std::cell::Cell<usize> = { - ::std::cell::Cell::new(0) - }); - &FOO - }, - _marker: ::std::marker::PhantomData, - }; - ) -} - -/// Type representing a thread local storage key corresponding to a reference -/// to the type parameter `T`. -/// -/// Keys are statically allocated and can contain a reference to an instance of -/// type `T` scoped to a particular lifetime. Keys provides two methods, `set` -/// and `with`, both of which currently use closures to control the scope of -/// their contents. -pub struct ScopedKey<T> { - #[doc(hidden)] - pub inner: &'static LocalKey<Cell<usize>>, - #[doc(hidden)] - pub _marker: marker::PhantomData<T>, -} - -unsafe impl<T> Sync for ScopedKey<T> {} - -impl<T> ScopedKey<T> { - /// Inserts a value into this scoped thread local storage slot for a - /// duration of a closure. - /// - /// While `cb` is running, the value `t` will be returned by `get` unless - /// this function is called recursively inside of `cb`. - /// - /// Upon return, this function will restore the previous value, if any - /// was available. - /// - /// # Examples - /// - /// ``` - /// #[macro_use] - /// extern crate scoped_tls; - /// - /// scoped_thread_local!(static FOO: u32); - /// - /// # fn main() { - /// FOO.set(&100, || { - /// let val = FOO.with(|v| *v); - /// assert_eq!(val, 100); - /// - /// // set can be called recursively - /// FOO.set(&101, || { - /// // ... - /// }); - /// - /// // Recursive calls restore the previous value. - /// let val = FOO.with(|v| *v); - /// assert_eq!(val, 100); - /// }); - /// # } - /// ``` - pub fn set<F, R>(&'static self, t: &T, f: F) -> R - where F: FnOnce() -> R - { - struct Reset { - key: &'static LocalKey<Cell<usize>>, - val: usize, - } - impl Drop for Reset { - fn drop(&mut self) { - self.key.with(|c| c.set(self.val)); - } - } - let prev = self.inner.with(|c| { - let prev = c.get(); - c.set(t as *const T as usize); - prev - }); - let _reset = Reset { key: self.inner, val: prev }; - f() - } - - /// Gets a value out of this scoped variable. - /// - /// This function takes a closure which receives the value of this - /// variable. - /// - /// # Panics - /// - /// This function will panic if `set` has not previously been called. - /// - /// # Examples - /// - /// ```no_run - /// #[macro_use] - /// extern crate scoped_tls; - /// - /// scoped_thread_local!(static FOO: u32); - /// - /// # fn main() { - /// FOO.with(|slot| { - /// // work with `slot` - /// # drop(slot); - /// }); - /// # } - /// ``` - pub fn with<F, R>(&'static self, f: F) -> R - where F: FnOnce(&T) -> R - { - let val = self.inner.with(|c| c.get()); - assert!(val != 0, "cannot access a scoped thread local \ - variable without calling `set` first"); - unsafe { - f(&*(val as *const T)) - } - } - - /// Test whether this TLS key has been `set` for the current thread. - pub fn is_set(&'static self) -> bool { - self.inner.with(|c| c.get() != 0) - } -} - -#[cfg(test)] -mod tests { - use std::cell::Cell; - use std::sync::mpsc::{channel, Sender}; - use std::thread; - - scoped_thread_local!(static FOO: u32); - - #[test] - fn smoke() { - scoped_thread_local!(static BAR: u32); - - assert!(!BAR.is_set()); - BAR.set(&1, || { - assert!(BAR.is_set()); - BAR.with(|slot| { - assert_eq!(*slot, 1); - }); - }); - assert!(!BAR.is_set()); - } - - #[test] - fn cell_allowed() { - scoped_thread_local!(static BAR: Cell<u32>); - - BAR.set(&Cell::new(1), || { - BAR.with(|slot| { - assert_eq!(slot.get(), 1); - }); - }); - } - - #[test] - fn scope_item_allowed() { - assert!(!FOO.is_set()); - FOO.set(&1, || { - assert!(FOO.is_set()); - FOO.with(|slot| { - assert_eq!(*slot, 1); - }); - }); - assert!(!FOO.is_set()); - } - - #[test] - fn panic_resets() { - struct Check(Sender<u32>); - impl Drop for Check { - fn drop(&mut self) { - FOO.with(|r| { - self.0.send(*r).unwrap(); - }) - } - } - - let (tx, rx) = channel(); - let t = thread::spawn(|| { - FOO.set(&1, || { - let _r = Check(tx); - - FOO.set(&2, || { - panic!() - }); - }); - }); - - assert_eq!(rx.recv().unwrap(), 1); - assert!(t.join().is_err()); - } -} diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.0/.travis.yml cargo-0.26.0/vendor/scoped-tls-0.1.0/.travis.yml --- cargo-0.25.0/vendor/scoped-tls-0.1.0/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.0/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -language: rust -rust: - - stable - - beta - - nightly -sudo: false -before_script: - - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH -script: - - cargo build - - cargo test - - cargo doc --no-deps -after_success: - - travis-cargo --only nightly doc-upload -env: - global: - secure: oVWP/awx6NPXC66CmVrkqSi3oF7jDfn9bv49KaGDQ9kOspY26ao1Iq0Xvl7VYNxbGdpniCUPEILgpeIEI4BcsFXet+1DVbLmOJrKeOxJAy8CkkUYLG6x7Wnaa77FR/TExNfMY6X7Ei3N/1ayEuCiiye5bivUCXVLy1JbTcabuwwtkrXmsWWimppm4KpKBefBKbT0/ZNQ/WyIIPdsRoPTiJnTv1U1XZbIr4TQLnrUA7fAVBCxFh3B7gnz5yn4pNYi6Gc8cmYfCZwYptGeBpBdVgqqmW/ImqjQrocMJzH8thOcNiE29ZlQsaACH2BjjLDaOktHZfaVhQF0IjUfcKJ/8v8cCZhWr5kt/ih/SXRiwF3dE6wBXL2vxSw7rSaceQDXgTAlXvTx/i4UFrzzjWgPC+HNwwvBnUrUMfF2AL2pUqnd2L2x0EdIhuAOVyPh4kmOwZAmXrERyUAQhArJGKhm8sbFHhizzPna4rEqsfVwystEXeBsFBwtmBBM3CdawE47OnpKpdlm/DH+PUty98WMYXpwDNuu8oSSybe4fyqNExDfqZ4n3H80XOxAFoXRTdWRp7zexw6YwjSMKF1TwjuGoJjW5NOT7a20PDV/jXNN5KyiKFUxMWbcZcfIdjaCOhiQp7RcHFsRFDvbUnbomrnn7k/jDKaytpKIQVY2RG0pGpY= -notifications: - email: - on_success: never -os: - - linux - - osx diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.1/appveyor.yml cargo-0.26.0/vendor/scoped-tls-0.1.1/appveyor.yml --- cargo-0.25.0/vendor/scoped-tls-0.1.1/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.1/appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,17 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --verbose diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.1/.cargo-checksum.json cargo-0.26.0/vendor/scoped-tls-0.1.1/.cargo-checksum.json --- cargo-0.25.0/vendor/scoped-tls-0.1.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.1/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"8674d439c964889e2476f474a3bf198cc9e199e77499960893bac5de7e9218a4"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.1/Cargo.toml cargo-0.26.0/vendor/scoped-tls-0.1.1/Cargo.toml --- cargo-0.25.0/vendor/scoped-tls-0.1.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.1/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "scoped-tls" +version = "0.1.1" +authors = ["Alex Crichton <alex@alexcrichton.com>"] +description = "Library implementation of the standard library's old `scoped_thread_local!`\nmacro for providing scoped access to thread local storage (TLS) so any type can\nbe stored into TLS.\n" +homepage = "https://github.com/alexcrichton/scoped-tls" +documentation = "http://alexcrichton.com/scoped-tls" +readme = "README.md" +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/scoped-tls" + +[features] +nightly = [] diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.1/LICENSE-APACHE cargo-0.26.0/vendor/scoped-tls-0.1.1/LICENSE-APACHE --- cargo-0.25.0/vendor/scoped-tls-0.1.1/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.1/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.1/LICENSE-MIT cargo-0.26.0/vendor/scoped-tls-0.1.1/LICENSE-MIT --- cargo-0.25.0/vendor/scoped-tls-0.1.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.1/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +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. diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.1/README.md cargo-0.26.0/vendor/scoped-tls-0.1.1/README.md --- cargo-0.25.0/vendor/scoped-tls-0.1.1/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.1/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,32 @@ +# scoped-tls + +[![Build Status](https://travis-ci.org/alexcrichton/scoped-tls.svg?branch=master)](https://travis-ci.org/alexcrichton/scoped-tls) +[![Build status](https://ci.appveyor.com/api/projects/status/9tatexq47i3ee13k?svg=true)](https://ci.appveyor.com/project/alexcrichton/flate2-rs) + +[Documentation](http://alexcrichton.com/scoped-tls) + +A Rust library providing the old standard library's `scoped_thread_local!` macro +as a library implementation on crates.io. + +```toml +# Cargo.toml +[dependencies] +scoped-tls = "0.1" +``` + +# License + +This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.1/src/lib.rs cargo-0.26.0/vendor/scoped-tls-0.1.1/src/lib.rs --- cargo-0.25.0/vendor/scoped-tls-0.1.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.1/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,269 @@ +// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Scoped thread-local storage +//! +//! This module provides the ability to generate *scoped* thread-local +//! variables. In this sense, scoped indicates that thread local storage +//! actually stores a reference to a value, and this reference is only placed +//! in storage for a scoped amount of time. +//! +//! There are no restrictions on what types can be placed into a scoped +//! variable, but all scoped variables are initialized to the equivalent of +//! null. Scoped thread local storage is useful when a value is present for a known +//! period of time and it is not required to relinquish ownership of the +//! contents. +//! +//! # Examples +//! +//! ``` +//! #[macro_use] +//! extern crate scoped_tls; +//! +//! scoped_thread_local!(static FOO: u32); +//! +//! # fn main() { +//! // Initially each scoped slot is empty. +//! assert!(!FOO.is_set()); +//! +//! // When inserting a value, the value is only in place for the duration +//! // of the closure specified. +//! FOO.set(&1, || { +//! FOO.with(|slot| { +//! assert_eq!(*slot, 1); +//! }); +//! }); +//! # } +//! ``` + +#![deny(missing_docs, warnings)] +#![cfg_attr(feature = "nightly", feature(macro_vis_matcher))] +#![cfg_attr(feature = "nightly", feature(allow_internal_unstable))] + +use std::cell::Cell; +use std::marker; +use std::thread::LocalKey; + +#[macro_export] +#[cfg(not(feature = "nightly"))] +macro_rules! scoped_thread_local { + (static $name:ident: $ty:ty) => ( + static $name: $crate::ScopedKey<$ty> = $crate::ScopedKey { + inner: { + thread_local!(static FOO: ::std::cell::Cell<usize> = { + ::std::cell::Cell::new(0) + }); + &FOO + }, + _marker: ::std::marker::PhantomData, + }; + ) +} + +#[macro_export] +#[allow_internal_unstable] +#[cfg(feature = "nightly")] +macro_rules! scoped_thread_local { + ($vis:vis static $name:ident: $ty:ty) => ( + $vis static $name: $crate::ScopedKey<$ty> = $crate::ScopedKey { + inner: { + thread_local!(static FOO: ::std::cell::Cell<usize> = { + ::std::cell::Cell::new(0) + }); + &FOO + }, + _marker: ::std::marker::PhantomData, + }; + ) +} + +/// Type representing a thread local storage key corresponding to a reference +/// to the type parameter `T`. +/// +/// Keys are statically allocated and can contain a reference to an instance of +/// type `T` scoped to a particular lifetime. Keys provides two methods, `set` +/// and `with`, both of which currently use closures to control the scope of +/// their contents. +pub struct ScopedKey<T> { + #[doc(hidden)] + pub inner: &'static LocalKey<Cell<usize>>, + #[doc(hidden)] + pub _marker: marker::PhantomData<T>, +} + +unsafe impl<T> Sync for ScopedKey<T> {} + +impl<T> ScopedKey<T> { + /// Inserts a value into this scoped thread local storage slot for a + /// duration of a closure. + /// + /// While `cb` is running, the value `t` will be returned by `get` unless + /// this function is called recursively inside of `cb`. + /// + /// Upon return, this function will restore the previous value, if any + /// was available. + /// + /// # Examples + /// + /// ``` + /// #[macro_use] + /// extern crate scoped_tls; + /// + /// scoped_thread_local!(static FOO: u32); + /// + /// # fn main() { + /// FOO.set(&100, || { + /// let val = FOO.with(|v| *v); + /// assert_eq!(val, 100); + /// + /// // set can be called recursively + /// FOO.set(&101, || { + /// // ... + /// }); + /// + /// // Recursive calls restore the previous value. + /// let val = FOO.with(|v| *v); + /// assert_eq!(val, 100); + /// }); + /// # } + /// ``` + pub fn set<F, R>(&'static self, t: &T, f: F) -> R + where F: FnOnce() -> R + { + struct Reset { + key: &'static LocalKey<Cell<usize>>, + val: usize, + } + impl Drop for Reset { + fn drop(&mut self) { + self.key.with(|c| c.set(self.val)); + } + } + let prev = self.inner.with(|c| { + let prev = c.get(); + c.set(t as *const T as usize); + prev + }); + let _reset = Reset { key: self.inner, val: prev }; + f() + } + + /// Gets a value out of this scoped variable. + /// + /// This function takes a closure which receives the value of this + /// variable. + /// + /// # Panics + /// + /// This function will panic if `set` has not previously been called. + /// + /// # Examples + /// + /// ```no_run + /// #[macro_use] + /// extern crate scoped_tls; + /// + /// scoped_thread_local!(static FOO: u32); + /// + /// # fn main() { + /// FOO.with(|slot| { + /// // work with `slot` + /// # drop(slot); + /// }); + /// # } + /// ``` + pub fn with<F, R>(&'static self, f: F) -> R + where F: FnOnce(&T) -> R + { + let val = self.inner.with(|c| c.get()); + assert!(val != 0, "cannot access a scoped thread local \ + variable without calling `set` first"); + unsafe { + f(&*(val as *const T)) + } + } + + /// Test whether this TLS key has been `set` for the current thread. + pub fn is_set(&'static self) -> bool { + self.inner.with(|c| c.get() != 0) + } +} + +#[cfg(test)] +mod tests { + use std::cell::Cell; + use std::sync::mpsc::{channel, Sender}; + use std::thread; + + scoped_thread_local!(static FOO: u32); + + #[test] + fn smoke() { + scoped_thread_local!(static BAR: u32); + + assert!(!BAR.is_set()); + BAR.set(&1, || { + assert!(BAR.is_set()); + BAR.with(|slot| { + assert_eq!(*slot, 1); + }); + }); + assert!(!BAR.is_set()); + } + + #[test] + fn cell_allowed() { + scoped_thread_local!(static BAR: Cell<u32>); + + BAR.set(&Cell::new(1), || { + BAR.with(|slot| { + assert_eq!(slot.get(), 1); + }); + }); + } + + #[test] + fn scope_item_allowed() { + assert!(!FOO.is_set()); + FOO.set(&1, || { + assert!(FOO.is_set()); + FOO.with(|slot| { + assert_eq!(*slot, 1); + }); + }); + assert!(!FOO.is_set()); + } + + #[test] + fn panic_resets() { + struct Check(Sender<u32>); + impl Drop for Check { + fn drop(&mut self) { + FOO.with(|r| { + self.0.send(*r).unwrap(); + }) + } + } + + let (tx, rx) = channel(); + let t = thread::spawn(|| { + FOO.set(&1, || { + let _r = Check(tx); + + FOO.set(&2, || { + panic!() + }); + }); + }); + + assert_eq!(rx.recv().unwrap(), 1); + assert!(t.join().is_err()); + } +} diff -Nru cargo-0.25.0/vendor/scoped-tls-0.1.1/.travis.yml cargo-0.26.0/vendor/scoped-tls-0.1.1/.travis.yml --- cargo-0.25.0/vendor/scoped-tls-0.1.1/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scoped-tls-0.1.1/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,29 @@ +language: rust +sudo: false + +matrix: + include: + - rust: 1.21.0 + - rust: stable + - os: osx + - rust: beta + - rust: nightly + + - rust: nightly + before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH + script: + - cargo doc --no-deps --all-features + after_success: + - travis-cargo --only nightly doc-upload + +script: + - cargo test + +env: + global: + secure: "ifNk4+dnXPIiCE4YeeIZoxWNDlQ4ElOelRXZ5tVpKbwA9nbiPXJayezfRJjCznH0FS0cyq7/6S8IY6YXR34e/yhcD7sQT9Wex3hm6SM3kklJDF7qxrz9ORLJTSRyV5cPGskuwdmly/gMkd5OnXwR5KFcS0FVw2C/CKWdCKget3+uNbmdMQrVFeoF030yv0hA0/TB0l3lV6NJi0xNzyRe6jIHWNUw8+n0Ei1w1IxZ1lfpuUowBpmKsEmt36833FTk9k4CyR/J08hhclhv8G1yhf7KxVfXq7AjjyNATyGY0oFPqW8g6mXd/31llUDskP9Cx851jWIViNKWRiWkqJlXvrd+a2X9oiqy55ZeCFFUma8jccbhqB7v0EGvxwGUC3z44NCDjM3mZL6NnDRMcd/9bxA56XZAqhFOeuOujL/Nbj0d33iWileCxc5do3iWrf1HMvTYxdL1/qWMHg4BJWbWRCQqmgpyCj6n+WwYTaZwJvLRWzK4Nm0RYq/A7oW6LTkxS5ogE4gprQ4Xwr/cG/vguIYbrYQv4nh9rn9KrDuFROOdp2TDGsryjwdx+75Ea3Ej25ZY26T6KPTgcLXpGFSNfSnQ1LnPpkhYt0LnPkx+ONfCTCi5OFYepK86cPttTkkSQJNBncCkBQ0K5KWB5Ilh6JYXRBRNienI4l414umgcv0=" + +notifications: + email: + on_success: never diff -Nru cargo-0.25.0/vendor/scopeguard-0.1.2/.cargo-checksum.json cargo-0.26.0/vendor/scopeguard-0.1.2/.cargo-checksum.json --- cargo-0.25.0/vendor/scopeguard-0.1.2/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.1.2/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"59a076157c1e2dc561d8de585151ee6965d910dd4dcb5dabb7ae3e83981a6c57"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/scopeguard-0.1.2/Cargo.toml cargo-0.26.0/vendor/scopeguard-0.1.2/Cargo.toml --- cargo-0.25.0/vendor/scopeguard-0.1.2/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.1.2/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -[package] -name = "scopeguard" -version = "0.1.2" - -license = "MIT/Apache-2.0" -repository = "https://github.com/bluss/scopeguard" -documentation = "http://bluss.github.io/scopeguard/" -authors = ["bluss"] - -description = "A RAII scope guard." - -keywords = ["scope-guard", "defer"] - diff -Nru cargo-0.25.0/vendor/scopeguard-0.1.2/LICENSE-APACHE cargo-0.26.0/vendor/scopeguard-0.1.2/LICENSE-APACHE --- cargo-0.25.0/vendor/scopeguard-0.1.2/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.1.2/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/scopeguard-0.1.2/LICENSE-MIT cargo-0.26.0/vendor/scopeguard-0.1.2/LICENSE-MIT --- cargo-0.25.0/vendor/scopeguard-0.1.2/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.1.2/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2015 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/scopeguard-0.1.2/README.rst cargo-0.26.0/vendor/scopeguard-0.1.2/README.rst --- cargo-0.25.0/vendor/scopeguard-0.1.2/README.rst 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.1.2/README.rst 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ - -scopeguard -========== - -Rust crate for a convenient RAII scope guard. - -Please read the `API documentation here`__ - -__ http://bluss.github.io/scopeguard - -|build_status|_ |crates|_ - -.. |build_status| image:: https://travis-ci.org/bluss/scopeguard.svg -.. _build_status: https://travis-ci.org/bluss/scopeguard - -.. |crates| image:: http://meritbadge.herokuapp.com/scopeguard -.. _crates: https://crates.io/crates/scopeguard - -How to use ----------- - -:: - - #[macro_use(defer)] extern crate scopeguard; - - use scopeguard::guard; - - fn f() { - defer!(println!("Called at return or panic")); - panic!(); - } - - fn g() { - let f = File::create("newfile.txt").unwrap(); - let mut file = guard(f, |f| { - // write file at return or panic - f.sync_all(); - }); - file.write("testme\n"); - } - -Recent Changes --------------- - -- 0.1.2 - - - Add macro ``defer!()`` diff -Nru cargo-0.25.0/vendor/scopeguard-0.1.2/src/lib.rs cargo-0.26.0/vendor/scopeguard-0.1.2/src/lib.rs --- cargo-0.25.0/vendor/scopeguard-0.1.2/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.1.2/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,75 +0,0 @@ -use std::ops::{Deref, DerefMut}; - -/// Macro to create a `Guard` (without any owned value). -/// -/// The macro takes one expression `$e`, which is the body of a closure -/// that will run when the scope is exited. The expression can -/// be a whole block. -#[macro_export] -macro_rules! defer { - ($e:expr) => { - let _guard = $crate::guard((), |_| $e); - } -} - -/// `Guard` is a scope guard that may own a protected value. -/// -/// If you place a guard value in a local variable, its destructor will -/// run regardless how you leave the function — regular return or panic -/// (barring abnormal incidents like aborts; so as long as destructors run). -/// -/// The guard's closure will be called with a mut ref to the held value -/// in the destructor. It's called only once. -/// -/// The `Guard` implements `Deref` so that you can access the inner value. -pub struct Guard<T, F> - where F: FnMut(&mut T) -{ - __dropfn: F, - __value: T, -} - -/// Create a new `Guard` owning `v` and with deferred closure `dropfn`. -pub fn guard<T, F>(v: T, dropfn: F) -> Guard<T, F> - where F: FnMut(&mut T) -{ - Guard{__value: v, __dropfn: dropfn} -} - -impl<T, F> Deref for Guard<T, F> - where F: FnMut(&mut T) -{ - type Target = T; - fn deref(&self) -> &T - { - &self.__value - } - -} - -impl<T, F> DerefMut for Guard<T, F> - where F: FnMut(&mut T) -{ - fn deref_mut(&mut self) -> &mut T - { - &mut self.__value - } -} - -impl<T, F> Drop for Guard<T, F> - where F: FnMut(&mut T) -{ - fn drop(&mut self) { - (self.__dropfn)(&mut self.__value) - } -} - -#[test] -fn test_defer() { - use std::cell::Cell; - - let drops = Cell::new(0); - defer!(drops.set(1000)); - assert_eq!(drops.get(), 0); -} - diff -Nru cargo-0.25.0/vendor/scopeguard-0.1.2/.travis.yml cargo-0.26.0/vendor/scopeguard-0.1.2/.travis.yml --- cargo-0.25.0/vendor/scopeguard-0.1.2/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.1.2/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -language: rust -sudo: false - -# run builds for all the trains (and more) -rust: - - stable - - beta - - nightly - -# load travis-cargo -before_script: - - | - pip install 'travis-cargo<0.2' --user && - export PATH=$HOME/.local/bin:$PATH - -# the main build -script: - - | - travis-cargo build && - travis-cargo test && - travis-cargo bench && - travis-cargo doc -after_success: - # upload the documentation (GH_TOKEN from env) - - travis-cargo --only nightly doc-upload - -env: - global: - # override the default `--features unstable` used for the nightly branch (optional) - - TRAVIS_CARGO_NIGHTLY_FEATURE="" diff -Nru cargo-0.25.0/vendor/scopeguard-0.3.3/.cargo-checksum.json cargo-0.26.0/vendor/scopeguard-0.3.3/.cargo-checksum.json --- cargo-0.25.0/vendor/scopeguard-0.3.3/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.3.3/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"94258f53601af11e6a49f722422f6e3425c52b06245a5cf9bc09908b174f5e27"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/scopeguard-0.3.3/Cargo.toml cargo-0.26.0/vendor/scopeguard-0.3.3/Cargo.toml --- cargo-0.25.0/vendor/scopeguard-0.3.3/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.3.3/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "scopeguard" +version = "0.3.3" +authors = ["bluss"] +description = "A RAII scope guard that will run a given closure when it goes out of scope,\neven if the code between panics (assuming unwinding panic).\n\nDefines the macros `defer!` and `defer_on_unwind!`; the latter only runs\nif the scope is extited through unwinding on panic.\n" +documentation = "https://docs.rs/scopeguard/" +keywords = ["scope-guard", "defer", "panic"] +categories = ["rust-patterns"] +license = "MIT/Apache-2.0" +repository = "https://github.com/bluss/scopeguard" +[package.metadata.release] +no-dev-version = true + +[features] +default = ["use_std"] +use_std = [] diff -Nru cargo-0.25.0/vendor/scopeguard-0.3.3/examples/readme.rs cargo-0.26.0/vendor/scopeguard-0.3.3/examples/readme.rs --- cargo-0.25.0/vendor/scopeguard-0.3.3/examples/readme.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.3.3/examples/readme.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,27 @@ + +#[macro_use(defer)] extern crate scopeguard; + +use scopeguard::guard; + +fn f() { + defer!(println!("Called at return or panic")); + panic!(); +} + +use std::fs::File; +use std::io::Write; + +fn g() { + let f = File::create("newfile.txt").unwrap(); + let mut file = guard(f, |f| { + // write file at return or panic + let _ = f.sync_all(); + }); + // Access the file through the scope guard itself + file.write(b"test me\n").unwrap(); +} + +fn main() { + f(); + g(); +} diff -Nru cargo-0.25.0/vendor/scopeguard-0.3.3/LICENSE-APACHE cargo-0.26.0/vendor/scopeguard-0.3.3/LICENSE-APACHE --- cargo-0.25.0/vendor/scopeguard-0.3.3/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.3.3/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/scopeguard-0.3.3/LICENSE-MIT cargo-0.26.0/vendor/scopeguard-0.3.3/LICENSE-MIT --- cargo-0.25.0/vendor/scopeguard-0.3.3/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.3.3/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2015 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/scopeguard-0.3.3/README.rst cargo-0.26.0/vendor/scopeguard-0.3.3/README.rst --- cargo-0.25.0/vendor/scopeguard-0.3.3/README.rst 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.3.3/README.rst 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,81 @@ + +scopeguard +========== + +Rust crate for a convenient RAII scope guard that will run a given closure when +it goes out of scope, even if the code between panics (assuming unwinding panic). + +The `defer!` macro and `guard` are `no_std` compatible (require only core), +but the on unwinding strategy requires linking to `std`. + +Requires Rust 1.11. + + +Please read the `API documentation here`__ + +__ https://docs.rs/scopeguard/ + +|build_status|_ |crates|_ + +.. |build_status| image:: https://travis-ci.org/bluss/scopeguard.svg +.. _build_status: https://travis-ci.org/bluss/scopeguard + +.. |crates| image:: http://meritbadge.herokuapp.com/scopeguard +.. _crates: https://crates.io/crates/scopeguard + +How to use +---------- + +.. code:: rust + + #[macro_use(defer)] extern crate scopeguard; + + use scopeguard::guard; + + fn f() { + defer!(println!("Called at return or panic")); + panic!(); + } + + use std::fs::File; + use std::io::Write; + + fn g() { + let f = File::create("newfile.txt").unwrap(); + let mut file = guard(f, |f| { + // write file at return or panic + let _ = f.sync_all(); + }); + // Access the file through the scope guard itself + file.write(b"test me\n").unwrap(); + } + +Recent Changes +-------------- + +- 0.3.3 + + - Use ``#[inline]`` on a few more functions by @stjepang (#14) + - Add examples to crate documentation + +- 0.3.2 + + - Add crate categories + +- 0.3.1 + + - Add ``defer_on_unwind!``, ``Strategy`` trait + - Rename ``Guard`` → ``ScopeGuard`` + - Add ``ScopeGuard::with_strategy``. + - ``ScopeGuard`` now implements ``Debug``. + - Require Rust 1.11 + +- 0.2.0 + + - Require Rust 1.6 + - Use `no_std` unconditionally + - No other changes + +- 0.1.2 + + - Add macro ``defer!()`` diff -Nru cargo-0.25.0/vendor/scopeguard-0.3.3/src/lib.rs cargo-0.26.0/vendor/scopeguard-0.3.3/src/lib.rs --- cargo-0.25.0/vendor/scopeguard-0.3.3/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.3.3/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,409 @@ +#![cfg_attr(not(any(test, feature = "use_std")), no_std)] + +//! A scope guard will run a given closure when it goes out of scope, +//! even if the code between panics. +//! (as long as panic doesn't abort) +//! +//! # Examples +//! +//! ## `defer!` +//! +//! Use the `defer` macro to run an operation at scope exit, +//! either regular scope exit or during unwinding from a panic. +//! +//! ``` +//! #[macro_use(defer)] extern crate scopeguard; +//! +//! use std::cell::Cell; +//! +//! fn main() { +//! // use a cell to observe drops during and after the scope guard is active +//! let drop_counter = Cell::new(0); +//! { +//! // Create a scope guard using `defer!` for the current scope +//! defer! {{ +//! drop_counter.set(1 + drop_counter.get()); +//! }}; +//! +//! // Do regular operations here in the meantime. +//! +//! // Just before scope exit: it hasn't run yet. +//! assert_eq!(drop_counter.get(), 0); +//! +//! // The following scope end is where the defer closure is called +//! } +//! assert_eq!(drop_counter.get(), 1); +//! } +//! ``` +//! +//! ## Scope Guard with Value +//! +//! If the scope guard closure needs to access an outer value that is also +//! mutated outside of the scope guard, then you may want to use the scope guard +//! with a value. The guard works like a smart pointer, so the inner value can +//! be accessed by reference or by mutable reference. +//! +//! ### 1. The guard owns a file +//! +//! In this example, the scope guard owns a file and ensures pending writes are +//! synced at scope exit. +//! +//! ``` +//! extern crate scopeguard; +//! +//! use std::fs::File; +//! use std::io::{self, Write}; +//! +//! fn try_main() -> io::Result<()> { +//! let f = File::create("newfile.txt")?; +//! let mut file = scopeguard::guard(f, |f| { +//! // ensure we flush file at return or panic +//! let _ = f.sync_all(); +//! }); +//! // Access the file through the scope guard itself +//! file.write(b"test me\n").map(|_| ()) +//! } +//! +//! fn main() { +//! try_main().unwrap(); +//! } +//! +//! ``` +//! +//! ### 2. The guard restores an invariant on scope exit +//! +//! ``` +//! extern crate scopeguard; +//! +//! use std::mem::ManuallyDrop; +//! use std::ptr; +//! +//! // This function, just for this example, takes the first element +//! // and inserts it into the assumed sorted tail of the vector. +//! // +//! // For optimization purposes we temporarily violate an invariant of the +//! // Vec, that it owns all of its elements. +//! // +//! // The safe approach is to use swap, which means two writes to memory, +//! // the optimization is to use a “hole” which uses only one write of memory +//! // for each position it moves. +//! // +//! // We *must* use a scope guard to run this code safely. We +//! // are running arbitrary user code (comparison operators) that may panic. +//! // The scope guard ensures we restore the invariant after successful +//! // exit or during unwinding from panic. +//! fn insertion_sort_first<T>(v: &mut Vec<T>) +//! where T: PartialOrd +//! { +//! struct Hole<'a, T: 'a> { +//! v: &'a mut Vec<T>, +//! index: usize, +//! value: ManuallyDrop<T>, +//! } +//! +//! unsafe { +//! // Create a moved-from location in the vector, a “hole”. +//! let value = ptr::read(&v[0]); +//! let mut hole = Hole { v: v, index: 0, value: ManuallyDrop::new(value) }; +//! +//! // Use a scope guard with a value. +//! // At scope exit, plug the hole so that the vector is fully +//! // initialized again. +//! // The scope guard owns the hole, but we can access it through the guard. +//! let mut hole_guard = scopeguard::guard(hole, |hole| { +//! // plug the hole in the vector with the value that was // taken out +//! let index = hole.index; +//! ptr::copy_nonoverlapping(&*hole.value, &mut hole.v[index], 1); +//! }); +//! +//! // run algorithm that moves the hole in the vector here +//! // move the hole until it's in a sorted position +//! for i in 1..hole_guard.v.len() { +//! if *hole_guard.value >= hole_guard.v[i] { +//! // move the element back and the hole forward +//! let index = hole_guard.index; +//! ptr::copy_nonoverlapping(&hole_guard.v[index + 1], &mut hole_guard.v[index], 1); +//! hole_guard.index += 1; +//! } else { +//! break; +//! } +//! } +//! +//! // When the scope exits here, the Vec becomes whole again! +//! } +//! } +//! +//! fn main() { +//! let string = String::from; +//! let mut data = vec![string("c"), string("a"), string("b"), string("d")]; +//! insertion_sort_first(&mut data); +//! assert_eq!(data, vec!["a", "b", "c", "d"]); +//! } +//! +//! ``` +//! +//! +//! # Crate features: +//! +//! - `use_std` +//! + Enabled by default. Enables the `OnUnwind` strategy. +//! + Disable to use `no_std`. + +#[cfg(not(any(test, feature = "use_std")))] +extern crate core as std; + +use std::fmt; +use std::marker::PhantomData; +use std::ops::{Deref, DerefMut}; + +pub trait Strategy { + /// Return `true` if the guard’s associated code should run + /// (in the context where this method is called). + fn should_run() -> bool; +} + +/// Always run on scope exit. +/// +/// “Always” run: on regular exit from a scope or on unwinding from a panic. +/// Can not run on abort, process exit, and other catastrophic events where +/// destructors don’t run. +#[derive(Debug)] +pub enum Always {} + +/// Run on scope exit through unwinding. +/// +/// Requires crate feature `use_std`. +#[cfg(feature = "use_std")] +#[derive(Debug)] +pub enum OnUnwind {} + +/// Run on regular scope exit, when not unwinding. +/// +/// Requires crate feature `use_std`. +#[cfg(feature = "use_std")] +#[derive(Debug)] +#[cfg(test)] +enum OnSuccess {} + +impl Strategy for Always { + #[inline(always)] + fn should_run() -> bool { true } +} + +#[cfg(feature = "use_std")] +impl Strategy for OnUnwind { + #[inline(always)] + fn should_run() -> bool { std::thread::panicking() } +} + +#[cfg(feature = "use_std")] +#[cfg(test)] +impl Strategy for OnSuccess { + #[inline(always)] + fn should_run() -> bool { !std::thread::panicking() } +} + +/// Macro to create a `ScopeGuard` (always run). +/// +/// The macro takes one expression `$e`, which is the body of a closure +/// that will run when the scope is exited. The expression can +/// be a whole block. +#[macro_export] +macro_rules! defer { + ($e:expr) => { + let _guard = $crate::guard((), |_| $e); + } +} + +/// Macro to create a `ScopeGuard` (run on successful scope exit). +/// +/// The macro takes one expression `$e`, which is the body of a closure +/// that will run when the scope is exited. The expression can +/// be a whole block. +/// +/// Requires crate feature `use_std`. +#[cfg(test)] +macro_rules! defer_on_success { + ($e:expr) => { + let _guard = $crate::guard_on_success((), |_| $e); + } +} + +/// Macro to create a `ScopeGuard` (run on unwinding from panic). +/// +/// The macro takes one expression `$e`, which is the body of a closure +/// that will run when the scope is exited. The expression can +/// be a whole block. +/// +/// Requires crate feature `use_std`. +#[macro_export] +macro_rules! defer_on_unwind { + ($e:expr) => { + let _guard = $crate::guard_on_unwind((), |_| $e); + } +} + +/// `ScopeGuard` is a scope guard that may own a protected value. +/// +/// If you place a guard in a local variable, the closure can +/// run regardless how you leave the scope — through regular return or panic +/// (except if panic or other code aborts; so as long as destructors run). +/// It is run only once. +/// +/// The `S` parameter for [`Strategy`](Strategy.t.html) determines if +/// the closure actually runs. +/// +/// The guard's closure will be called with a mut ref to the held value +/// in the destructor. It's called only once. +/// +/// The `ScopeGuard` implements `Deref` so that you can access the inner value. +pub struct ScopeGuard<T, F, S: Strategy = Always> + where F: FnMut(&mut T) +{ + __dropfn: F, + __value: T, + strategy: PhantomData<S>, +} +impl<T, F, S> ScopeGuard<T, F, S> + where F: FnMut(&mut T), + S: Strategy, +{ + /// Create a `ScopeGuard` that owns `v` (accessible through deref) and calls + /// `dropfn` when its destructor runs. + /// + /// The `Strategy` decides whether the scope guard's closure should run. + #[inline] + pub fn with_strategy(v: T, dropfn: F) -> ScopeGuard<T, F, S> { + ScopeGuard { + __value: v, + __dropfn: dropfn, + strategy: PhantomData, + } + } +} + + +/// Create a new `ScopeGuard` owning `v` and with deferred closure `dropfn`. +#[inline] +pub fn guard<T, F>(v: T, dropfn: F) -> ScopeGuard<T, F, Always> + where F: FnMut(&mut T) +{ + ScopeGuard::with_strategy(v, dropfn) +} + +/// Create a new `ScopeGuard` owning `v` and with deferred closure `dropfn`. +/// +/// Requires crate feature `use_std`. +#[cfg(feature = "use_std")] +#[cfg(test)] +#[inline] +fn guard_on_success<T, F>(v: T, dropfn: F) -> ScopeGuard<T, F, OnSuccess> + where F: FnMut(&mut T) +{ + ScopeGuard::with_strategy(v, dropfn) +} + +/// Create a new `ScopeGuard` owning `v` and with deferred closure `dropfn`. +/// +/// Requires crate feature `use_std`. +#[cfg(feature = "use_std")] +#[inline] +pub fn guard_on_unwind<T, F>(v: T, dropfn: F) -> ScopeGuard<T, F, OnUnwind> + where F: FnMut(&mut T) +{ + ScopeGuard::with_strategy(v, dropfn) +} + +impl<T, F, S: Strategy> Deref for ScopeGuard<T, F, S> + where F: FnMut(&mut T) +{ + type Target = T; + fn deref(&self) -> &T { + &self.__value + } + +} + +impl<T, F, S: Strategy> DerefMut for ScopeGuard<T, F, S> + where F: FnMut(&mut T) +{ + fn deref_mut(&mut self) -> &mut T { + &mut self.__value + } +} + +impl<T, F, S: Strategy> Drop for ScopeGuard<T, F, S> + where F: FnMut(&mut T) +{ + fn drop(&mut self) { + if S::should_run() { + (self.__dropfn)(&mut self.__value) + } + } +} + +impl<T, F, S> fmt::Debug for ScopeGuard<T, F, S> + where T: fmt::Debug, + F: FnMut(&mut T), + S: Strategy + fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("ScopeGuard") + .field("value", &self.__value) + .finish() + } +} + +#[cfg(test)] +mod tests { + use std::cell::Cell; + use std::panic::catch_unwind; + use std::panic::AssertUnwindSafe; + + #[test] + fn test_defer() { + let drops = Cell::new(0); + defer!(drops.set(1000)); + assert_eq!(drops.get(), 0); + } + + #[test] + fn test_defer_success_1() { + let drops = Cell::new(0); + { + defer_on_success!(drops.set(1)); + assert_eq!(drops.get(), 0); + } + assert_eq!(drops.get(), 1); + } + + #[test] + fn test_defer_success_2() { + let drops = Cell::new(0); + let _ = catch_unwind(AssertUnwindSafe(|| { + defer_on_success!(drops.set(1)); + panic!("failure") + })); + assert_eq!(drops.get(), 0); + } + + #[test] + fn test_defer_unwind_1() { + let drops = Cell::new(0); + let _ = catch_unwind(AssertUnwindSafe(|| { + defer_on_unwind!(drops.set(1)); + assert_eq!(drops.get(), 0); + panic!("failure") + })); + assert_eq!(drops.get(), 1); + } + + #[test] + fn test_defer_unwind_2() { + let drops = Cell::new(0); + { + defer_on_unwind!(drops.set(1)); + } + assert_eq!(drops.get(), 0); + } +} diff -Nru cargo-0.25.0/vendor/scopeguard-0.3.3/.travis.yml cargo-0.26.0/vendor/scopeguard-0.3.3/.travis.yml --- cargo-0.25.0/vendor/scopeguard-0.3.3/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/scopeguard-0.3.3/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,19 @@ +language: rust +sudo: false + +rust: + - 1.11.0 + - stable + - beta + - nightly + +branches: + only: + - master + +# the main build +script: + - | + cargo build --no-default-features && + cargo build && + ([ "$TRAVIS_RUST_VERSION" != "1.11.0" ] && cargo test ) || cargo test --lib diff -Nru cargo-0.25.0/vendor/semver-0.8.0/.cargo-checksum.json cargo-0.26.0/vendor/semver-0.8.0/.cargo-checksum.json --- cargo-0.25.0/vendor/semver-0.8.0/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.8.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"bee2bc909ab2d8d60dab26e8cad85b25d795b14603a0dcb627b78b9d30b6454b"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/semver-0.8.0/Cargo.toml cargo-0.26.0/vendor/semver-0.8.0/Cargo.toml --- cargo-0.25.0/vendor/semver-0.8.0/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.8.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,45 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "semver" -version = "0.8.0" -authors = ["Steve Klabnik <steve@steveklabnik.com>", "The Rust Project Developers"] -description = "Semantic version parsing and comparison.\n" -homepage = "https://docs.rs/crate/semver/" -documentation = "https://docs.rs/crate/semver/" -readme = "README.md" -license = "MIT/Apache-2.0" -repository = "https://github.com/steveklabnik/semver" -[dependencies.serde] -version = "1.0" -optional = true - -[dependencies.semver-parser] -version = "0.7.0" -[dev-dependencies.serde_derive] -version = "1.0" - -[dev-dependencies.serde_json] -version = "1.0" - -[dev-dependencies.crates-index] -version = "0.5.0" - -[dev-dependencies.tempdir] -version = "0.3.4" - -[features] -default = [] -ci = ["serde"] -[badges.travis-ci] -repository = "steveklabnik/semver" diff -Nru cargo-0.25.0/vendor/semver-0.8.0/LICENSE-APACHE cargo-0.26.0/vendor/semver-0.8.0/LICENSE-APACHE --- cargo-0.25.0/vendor/semver-0.8.0/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.8.0/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/semver-0.8.0/LICENSE-MIT cargo-0.26.0/vendor/semver-0.8.0/LICENSE-MIT --- cargo-0.25.0/vendor/semver-0.8.0/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.8.0/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/semver-0.8.0/README.md cargo-0.26.0/vendor/semver-0.8.0/README.md --- cargo-0.25.0/vendor/semver-0.8.0/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.8.0/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -semver -====== - -Semantic version parsing and comparison. - -[![Build Status](https://api.travis-ci.org/steveklabnik/semver.svg?branch=master)](https://travis-ci.org/steveklabnik/semver) - -[Documentation](https://steveklabnik.github.io/semver) - -Semantic versioning (see http://semver.org/) is a set of rules for -assigning version numbers. - -## SemVer and the Rust ecosystem - -Rust itself follows the SemVer specification, as does its standard libraries. The two are -not tied together. - -[Cargo](https://crates.io), Rust's package manager, uses SemVer to determine which versions of -packages you need installed. - -## Installation - -To use `semver`, add this to your `[dependencies]` section: - -```toml -semver = "0.7.0" -``` - -And this to your crate root: - -```rust -extern crate semver; -``` - -## Versions - -At its simplest, the `semver` crate allows you to construct `Version` objects using the `parse` -method: - -```rust -use semver::Version; - -assert!(Version::parse("1.2.3") == Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec!(), - build: vec!(), -})); -``` - -If you have multiple `Version`s, you can use the usual comparison operators to compare them: - -```rust -use semver::Version; - -assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta")); -assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0")); -``` - -## Requirements - -The `semver` crate also provides the ability to compare requirements, which are more complex -comparisons. - -For example, creating a requirement that only matches versions greater than or -equal to 1.0.0: - -```rust -use semver::Version; -use semver::VersionReq; - -let r = VersionReq::parse(">= 1.0.0").unwrap(); -let v = Version::parse("1.0.0").unwrap(); - -assert!(r.to_string() == ">= 1.0.0".to_string()); -assert!(r.matches(&v)) -``` - -It also allows parsing of `~x.y.z` and `^x.y.z` requirements as defined at -https://www.npmjs.org/doc/misc/semver.html - -**Tilde requirements** specify a minimal version with some updates: - -```notrust -~1.2.3 := >=1.2.3 <1.3.0 -~1.2 := >=1.2.0 <1.3.0 -~1 := >=1.0.0 <2.0.0 -``` - -**Caret requirements** allow SemVer compatible updates to a specified version, -`0.x` and `0.x+1` are not considered compatible, but `1.x` and `1.x+1` are. - -`0.0.x` is not considered compatible with any other version. -Missing minor and patch versions are desugared to `0` but allow flexibility for that value. - -```notrust -^1.2.3 := >=1.2.3 <2.0.0 -^0.2.3 := >=0.2.3 <0.3.0 -^0.0.3 := >=0.0.3 <0.0.4 -^0.0 := >=0.0.0 <0.1.0 -^0 := >=0.0.0 <1.0.0 -``` diff -Nru cargo-0.25.0/vendor/semver-0.8.0/src/lib.rs cargo-0.26.0/vendor/semver-0.8.0/src/lib.rs --- cargo-0.25.0/vendor/semver-0.8.0/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.8.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,182 +0,0 @@ -// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Semantic version parsing and comparison. -//! -//! Semantic versioning (see http://semver.org/) is a set of rules for -//! assigning version numbers. -//! -//! ## SemVer overview -//! -//! Given a version number MAJOR.MINOR.PATCH, increment the: -//! -//! 1. MAJOR version when you make incompatible API changes, -//! 2. MINOR version when you add functionality in a backwards-compatible -//! manner, and -//! 3. PATCH version when you make backwards-compatible bug fixes. -//! -//! Additional labels for pre-release and build metadata are available as -//! extensions to the MAJOR.MINOR.PATCH format. -//! -//! Any references to 'the spec' in this documentation refer to [version 2.0 of -//! the SemVer spec](http://semver.org/spec/v2.0.0.html). -//! -//! ## SemVer and the Rust ecosystem -//! -//! Rust itself follows the SemVer specification, as does its standard -//! libraries. The two are not tied together. -//! -//! [Cargo](http://crates.io), Rust's package manager, uses SemVer to determine -//! which versions of packages you need installed. -//! -//! ## Versions -//! -//! At its simplest, the `semver` crate allows you to construct `Version` -//! objects using the `parse` method: -//! -//! ```{rust} -//! use semver::Version; -//! -//! assert!(Version::parse("1.2.3") == Ok(Version { -//! major: 1, -//! minor: 2, -//! patch: 3, -//! pre: vec!(), -//! build: vec!(), -//! })); -//! ``` -//! -//! If you have multiple `Version`s, you can use the usual comparison operators -//! to compare them: -//! -//! ```{rust} -//! use semver::Version; -//! -//! assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta")); -//! assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0")); -//! ``` -//! -//! If you explicitly need to modify a Version, SemVer also allows you to -//! increment the major, minor, and patch numbers in accordance with the spec. -//! -//! Please note that in order to do this, you must use a mutable Version: -//! -//! ```{rust} -//! use semver::Version; -//! -//! let mut bugfix_release = Version::parse("1.0.0").unwrap(); -//! bugfix_release.increment_patch(); -//! -//! assert_eq!(Ok(bugfix_release), Version::parse("1.0.1")); -//! ``` -//! -//! When incrementing the minor version number, the patch number resets to zero -//! (in accordance with section 7 of the spec) -//! -//! ```{rust} -//! use semver::Version; -//! -//! let mut feature_release = Version::parse("1.4.6").unwrap(); -//! feature_release.increment_minor(); -//! -//! assert_eq!(Ok(feature_release), Version::parse("1.5.0")); -//! ``` -//! -//! Similarly, when incrementing the major version number, the patch and minor -//! numbers reset to zero (in accordance with section 8 of the spec) -//! -//! ```{rust} -//! use semver::Version; -//! -//! let mut chrome_release = Version::parse("41.5.5377").unwrap(); -//! chrome_release.increment_major(); -//! -//! assert_eq!(Ok(chrome_release), Version::parse("42.0.0")); -//! ``` -//! -//! ## Requirements -//! -//! The `semver` crate also provides the ability to compare requirements, which -//! are more complex comparisons. -//! -//! For example, creating a requirement that only matches versions greater than -//! or equal to 1.0.0: -//! -//! ```{rust} -//! # #![allow(unstable)] -//! use semver::Version; -//! use semver::VersionReq; -//! -//! let r = VersionReq::parse(">= 1.0.0").unwrap(); -//! let v = Version::parse("1.0.0").unwrap(); -//! -//! assert!(r.to_string() == ">= 1.0.0".to_string()); -//! assert!(r.matches(&v)) -//! ``` -//! -//! It also allows parsing of `~x.y.z` and `^x.y.z` requirements as defined at -//! https://www.npmjs.org/doc/misc/semver.html -//! -//! **Tilde requirements** specify a minimal version with some updates: -//! -//! ```notrust -//! ~1.2.3 := >=1.2.3 <1.3.0 -//! ~1.2 := >=1.2.0 <1.3.0 -//! ~1 := >=1.0.0 <2.0.0 -//! ``` -//! -//! **Caret requirements** allow SemVer compatible updates to a specified -//! verion, `0.x` and `0.x+1` are not considered compatible, but `1.x` and -//! `1.x+1` are. -//! -//! `0.0.x` is not considered compatible with any other version. -//! Missing minor and patch versions are desugared to `0` but allow flexibility -//! for that value. -//! -//! ```notrust -//! ^1.2.3 := >=1.2.3 <2.0.0 -//! ^0.2.3 := >=0.2.3 <0.3.0 -//! ^0.0.3 := >=0.0.3 <0.0.4 -//! ^0.0 := >=0.0.0 <0.1.0 -//! ^0 := >=0.0.0 <1.0.0 -//! ``` -//! -//! **Wildcard requirements** allows parsing of version requirements of the -//! formats `*`, `x.*` and `x.y.*`. -//! -//! ```notrust -//! * := >=0.0.0 -//! 1.* := >=1.0.0 <2.0.0 -//! 1.2.* := >=1.2.0 <1.3.0 -//! ``` - -#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", - html_favicon_url = "https://www.rust-lang.org/favicon.ico")] -#![deny(missing_docs)] -#![cfg_attr(test, deny(warnings))] - -extern crate semver_parser; - -// Serialization and deserialization support for version numbers -#[cfg(feature = "serde")] -extern crate serde; - -// We take the common approach of keeping our own module system private, and -// just re-exporting the interface that we want. - -pub use version::{Version, Identifier, SemVerError}; -pub use version::Identifier::{Numeric, AlphaNumeric}; -pub use version_req::{VersionReq, ReqParseError}; - -// SemVer-compliant versions. -mod version; - -// advanced version comparisons -mod version_req; diff -Nru cargo-0.25.0/vendor/semver-0.8.0/src/version_req.rs cargo-0.26.0/vendor/semver-0.8.0/src/version_req.rs --- cargo-0.25.0/vendor/semver-0.8.0/src/version_req.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.8.0/src/version_req.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,867 +0,0 @@ -// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::error::Error; -use std::fmt; -use std::result; -use std::str; - -use Version; -use version::Identifier; -use semver_parser; - -#[cfg(feature = "serde")] -use serde::ser::{Serialize, Serializer}; -#[cfg(feature = "serde")] -use serde::de::{self, Deserialize, Deserializer, Visitor}; - -use self::Op::{Ex, Gt, GtEq, Lt, LtEq, Tilde, Compatible, Wildcard}; -use self::WildcardVersion::{Major, Minor, Patch}; -use self::ReqParseError::*; - -/// A `VersionReq` is a struct containing a list of predicates that can apply to ranges of version -/// numbers. Matching operations can then be done with the `VersionReq` against a particular -/// version to see if it satisfies some or all of the constraints. -#[derive(PartialEq,Clone,Debug)] -pub struct VersionReq { - predicates: Vec<Predicate>, -} - -impl From<semver_parser::range::VersionReq> for VersionReq { - fn from(other: semver_parser::range::VersionReq) -> VersionReq { - VersionReq { predicates: other.predicates.into_iter().map(From::from).collect() } - } -} - -#[cfg(feature = "serde")] -impl Serialize for VersionReq { - fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error> - where S: Serializer - { - // Serialize VersionReq as a string. - serializer.collect_str(self) - } -} - -#[cfg(feature = "serde")] -impl<'de> Deserialize<'de> for VersionReq { - fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error> - where D: Deserializer<'de> - { - struct VersionReqVisitor; - - /// Deserialize `VersionReq` from a string. - impl<'de> Visitor<'de> for VersionReqVisitor { - type Value = VersionReq; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a SemVer version requirement as a string") - } - - fn visit_str<E>(self, v: &str) -> result::Result<Self::Value, E> - where E: de::Error - { - VersionReq::parse(v).map_err(de::Error::custom) - } - } - - deserializer.deserialize_str(VersionReqVisitor) - } -} - -#[derive(Clone, PartialEq, Debug)] -enum WildcardVersion { - Major, - Minor, - Patch, -} - -#[derive(PartialEq,Clone,Debug)] -enum Op { - Ex, // Exact - Gt, // Greater than - GtEq, // Greater than or equal to - Lt, // Less than - LtEq, // Less than or equal to - Tilde, // e.g. ~1.0.0 - Compatible, // compatible by definition of semver, indicated by ^ - Wildcard(WildcardVersion), // x.y.*, x.*, * -} - -impl From<semver_parser::range::Op> for Op { - fn from(other: semver_parser::range::Op) -> Op { - use semver_parser::range; - match other { - range::Op::Ex => Op::Ex, - range::Op::Gt => Op::Gt, - range::Op::GtEq => Op::GtEq, - range::Op::Lt => Op::Lt, - range::Op::LtEq => Op::LtEq, - range::Op::Tilde => Op::Tilde, - range::Op::Compatible => Op::Compatible, - range::Op::Wildcard(version) => { - match version { - range::WildcardVersion::Major => Op::Wildcard(WildcardVersion::Major), - range::WildcardVersion::Minor => Op::Wildcard(WildcardVersion::Minor), - range::WildcardVersion::Patch => Op::Wildcard(WildcardVersion::Patch), - } - } - } - } -} - -#[derive(PartialEq,Clone,Debug)] -struct Predicate { - op: Op, - major: u64, - minor: Option<u64>, - patch: Option<u64>, - pre: Vec<Identifier>, -} - -impl From<semver_parser::range::Predicate> for Predicate { - fn from(other: semver_parser::range::Predicate) -> Predicate { - Predicate { - op: From::from(other.op), - major: other.major, - minor: other.minor, - patch: other.patch, - pre: other.pre.into_iter().map(From::from).collect(), - } - } -} - -/// A `ReqParseError` is returned from methods which parse a string into a `VersionReq`. Each -/// enumeration is one of the possible errors that can occur. -#[derive(Clone, Debug, PartialEq)] -pub enum ReqParseError { - /// The given version requirement is invalid. - InvalidVersionRequirement, - /// You have already provided an operation, such as `=`, `~`, or `^`. Only use one. - OpAlreadySet, - /// The sigil you have written is not correct. - InvalidSigil, - /// All components of a version must be numeric. - VersionComponentsMustBeNumeric, - /// There was an error parsing an identifier. - InvalidIdentifier, - /// At least a major version is required. - MajorVersionRequired, - /// An unimplemented version requirement. - UnimplementedVersionRequirement, - /// This form of requirement is deprecated. - DeprecatedVersionRequirement(VersionReq), -} - -impl fmt::Display for ReqParseError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.description().fmt(f) - } -} - -impl Error for ReqParseError { - fn description(&self) -> &str { - match self { - &InvalidVersionRequirement => "the given version requirement is invalid", - &OpAlreadySet => { - "you have already provided an operation, such as =, ~, or ^; only use one" - }, - &InvalidSigil => "the sigil you have written is not correct", - &VersionComponentsMustBeNumeric => "version components must be numeric", - &InvalidIdentifier => "invalid identifier", - &MajorVersionRequired => "at least a major version number is required", - &UnimplementedVersionRequirement => { - "the given version requirement is not implemented, yet" - }, - &DeprecatedVersionRequirement(_) => "This requirement is deprecated", - } - } -} - -impl From<String> for ReqParseError { - fn from(other: String) -> ReqParseError { - match &*other { - "Null is not a valid VersionReq" => ReqParseError::InvalidVersionRequirement, - "VersionReq did not parse properly." => ReqParseError::OpAlreadySet, - _ => ReqParseError::InvalidVersionRequirement, - } - } -} - -impl VersionReq { - /// `any()` is a factory method which creates a `VersionReq` with no constraints. In other - /// words, any version will match against it. - /// - /// # Examples - /// - /// ``` - /// use semver::VersionReq; - /// - /// let anything = VersionReq::any(); - /// ``` - pub fn any() -> VersionReq { - VersionReq { predicates: vec![] } - } - - /// `parse()` is the main constructor of a `VersionReq`. It takes a string like `"^1.2.3"` - /// and turns it into a `VersionReq` that matches that particular constraint. - /// - /// A `Result` is returned which contains a `ReqParseError` if there was a problem parsing the - /// `VersionReq`. - /// - /// # Examples - /// - /// ``` - /// use semver::VersionReq; - /// - /// let version = VersionReq::parse("=1.2.3"); - /// let version = VersionReq::parse(">1.2.3"); - /// let version = VersionReq::parse("<1.2.3"); - /// let version = VersionReq::parse("~1.2.3"); - /// let version = VersionReq::parse("^1.2.3"); - /// let version = VersionReq::parse("1.2.3"); // synonym for ^1.2.3 - /// let version = VersionReq::parse("<=1.2.3"); - /// let version = VersionReq::parse(">=1.2.3"); - /// ``` - /// - /// This example demonstrates error handling, and will panic. - /// - /// ```should-panic - /// use semver::VersionReq; - /// - /// let version = match VersionReq::parse("not a version") { - /// Ok(version) => version, - /// Err(e) => panic!("There was a problem parsing: {}", e), - /// } - /// ``` - pub fn parse(input: &str) -> Result<VersionReq, ReqParseError> { - let res = semver_parser::range::parse(input); - - if let Ok(v) = res { - return Ok(From::from(v)); - } - - return match VersionReq::parse_deprecated(input) { - Some(v) => { - Err(ReqParseError::DeprecatedVersionRequirement(v)) - } - None => Err(From::from(res.err().unwrap())), - } - } - - fn parse_deprecated(version: &str) -> Option<VersionReq> { - return match version { - ".*" => Some(VersionReq::any()), - "0.1.0." => Some(VersionReq::parse("0.1.0").unwrap()), - "0.3.1.3" => Some(VersionReq::parse("0.3.13").unwrap()), - "0.2*" => Some(VersionReq::parse("0.2.*").unwrap()), - "*.0" => Some(VersionReq::any()), - _ => None, - } - } - - /// `exact()` is a factory method which creates a `VersionReq` with one exact constraint. - /// - /// # Examples - /// - /// ``` - /// use semver::VersionReq; - /// use semver::Version; - /// - /// let version = Version { major: 1, minor: 1, patch: 1, pre: vec![], build: vec![] }; - /// let exact = VersionReq::exact(&version); - /// ``` - pub fn exact(version: &Version) -> VersionReq { - VersionReq { predicates: vec![Predicate::exact(version)] } - } - - /// `matches()` matches a given `Version` against this `VersionReq`. - /// - /// # Examples - /// - /// ``` - /// use semver::VersionReq; - /// use semver::Version; - /// - /// let version = Version { major: 1, minor: 1, patch: 1, pre: vec![], build: vec![] }; - /// let exact = VersionReq::exact(&version); - /// - /// assert!(exact.matches(&version)); - /// ``` - pub fn matches(&self, version: &Version) -> bool { - // no predicates means anything matches - if self.predicates.is_empty() { - return true; - } - - self.predicates.iter().all(|p| p.matches(version)) && - self.predicates.iter().any(|p| p.pre_tag_is_compatible(version)) - } -} - -impl str::FromStr for VersionReq { - type Err = ReqParseError; - - fn from_str(s: &str) -> Result<VersionReq, ReqParseError> { - VersionReq::parse(s) - } -} - -impl Predicate { - fn exact(version: &Version) -> Predicate { - Predicate { - op: Ex, - major: version.major, - minor: Some(version.minor), - patch: Some(version.patch), - pre: version.pre.clone(), - } - } - - /// `matches()` takes a `Version` and determines if it matches this particular `Predicate`. - pub fn matches(&self, ver: &Version) -> bool { - match self.op { - Ex => self.is_exact(ver), - Gt => self.is_greater(ver), - GtEq => self.is_exact(ver) || self.is_greater(ver), - Lt => !self.is_exact(ver) && !self.is_greater(ver), - LtEq => !self.is_greater(ver), - Tilde => self.matches_tilde(ver), - Compatible => self.is_compatible(ver), - Wildcard(_) => self.matches_wildcard(ver), - } - } - - fn is_exact(&self, ver: &Version) -> bool { - if self.major != ver.major { - return false; - } - - match self.minor { - Some(minor) => { - if minor != ver.minor { - return false; - } - } - None => return true, - } - - match self.patch { - Some(patch) => { - if patch != ver.patch { - return false; - } - } - None => return true, - } - - if self.pre != ver.pre { - return false; - } - - true - } - - // https://docs.npmjs.com/misc/semver#prerelease-tags - fn pre_tag_is_compatible(&self, ver: &Version) -> bool { - // If a version has a prerelease tag (for example, 1.2.3-alpha.3) then it will - // only be - // allowed to satisfy comparator sets if at least one comparator with the same - // [major, - // minor, patch] tuple also has a prerelease tag. - !ver.is_prerelease() || - (self.major == ver.major && self.minor == Some(ver.minor) && - self.patch == Some(ver.patch) && !self.pre.is_empty()) - } - - fn is_greater(&self, ver: &Version) -> bool { - if self.major != ver.major { - return ver.major > self.major; - } - - match self.minor { - Some(minor) => { - if minor != ver.minor { - return ver.minor > minor; - } - } - None => return false, - } - - match self.patch { - Some(patch) => { - if patch != ver.patch { - return ver.patch > patch; - } - } - None => return false, - } - - if !self.pre.is_empty() { - return ver.pre.is_empty() || ver.pre > self.pre; - } - - false - } - - // see https://www.npmjs.org/doc/misc/semver.html for behavior - fn matches_tilde(&self, ver: &Version) -> bool { - let minor = match self.minor { - Some(n) => n, - None => return self.major == ver.major, - }; - - match self.patch { - Some(patch) => { - self.major == ver.major && minor == ver.minor && - (ver.patch > patch || (ver.patch == patch && self.pre_is_compatible(ver))) - } - None => self.major == ver.major && minor == ver.minor, - } - } - - // see https://www.npmjs.org/doc/misc/semver.html for behavior - fn is_compatible(&self, ver: &Version) -> bool { - if self.major != ver.major { - return false; - } - - let minor = match self.minor { - Some(n) => n, - None => return self.major == ver.major, - }; - - match self.patch { - Some(patch) => { - if self.major == 0 { - if minor == 0 { - ver.minor == minor && ver.patch == patch && self.pre_is_compatible(ver) - } else { - ver.minor == minor && - (ver.patch > patch || (ver.patch == patch && self.pre_is_compatible(ver))) - } - } else { - ver.minor > minor || - (ver.minor == minor && - (ver.patch > patch || (ver.patch == patch && self.pre_is_compatible(ver)))) - } - } - None => { - if self.major == 0 { - ver.minor == minor - } else { - ver.minor >= minor - } - } - } - } - - fn pre_is_compatible(&self, ver: &Version) -> bool { - ver.pre.is_empty() || ver.pre >= self.pre - } - - // see https://www.npmjs.org/doc/misc/semver.html for behavior - fn matches_wildcard(&self, ver: &Version) -> bool { - match self.op { - Wildcard(Major) => true, - Wildcard(Minor) => self.major == ver.major, - Wildcard(Patch) => { - match self.minor { - Some(minor) => self.major == ver.major && minor == ver.minor, - None => { - // minor and patch version astericks mean match on major - self.major == ver.major - } - } - } - _ => false, // unreachable - } - } -} - -impl fmt::Display for VersionReq { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - if self.predicates.is_empty() { - try!(write!(fmt, "*")); - } else { - for (i, ref pred) in self.predicates.iter().enumerate() { - if i == 0 { - try!(write!(fmt, "{}", pred)); - } else { - try!(write!(fmt, ", {}", pred)); - } - } - } - - Ok(()) - } -} - -impl fmt::Display for Predicate { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - match self.op { - Wildcard(Major) => try!(write!(fmt, "*")), - Wildcard(Minor) => try!(write!(fmt, "{}.*", self.major)), - Wildcard(Patch) => { - if let Some(minor) = self.minor { - try!(write!(fmt, "{}.{}.*", self.major, minor)) - } else { - try!(write!(fmt, "{}.*.*", self.major)) - } - } - _ => { - try!(write!(fmt, "{}{}", self.op, self.major)); - - match self.minor { - Some(v) => try!(write!(fmt, ".{}", v)), - None => (), - } - - match self.patch { - Some(v) => try!(write!(fmt, ".{}", v)), - None => (), - } - - if !self.pre.is_empty() { - try!(write!(fmt, "-")); - for (i, x) in self.pre.iter().enumerate() { - if i != 0 { - try!(write!(fmt, ".")) - } - try!(write!(fmt, "{}", x)); - } - } - } - } - - Ok(()) - } -} - -impl fmt::Display for Op { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - match *self { - Ex => try!(write!(fmt, "= ")), - Gt => try!(write!(fmt, "> ")), - GtEq => try!(write!(fmt, ">= ")), - Lt => try!(write!(fmt, "< ")), - LtEq => try!(write!(fmt, "<= ")), - Tilde => try!(write!(fmt, "~")), - Compatible => try!(write!(fmt, "^")), - // gets handled specially in Predicate::fmt - Wildcard(_) => try!(write!(fmt, "")), - } - Ok(()) - } -} - -#[cfg(test)] -mod test { - use super::{VersionReq, Op}; - use super::super::version::Version; - - fn req(s: &str) -> VersionReq { - VersionReq::parse(s).unwrap() - } - - fn version(s: &str) -> Version { - match Version::parse(s) { - Ok(v) => v, - Err(e) => panic!("`{}` is not a valid version. Reason: {:?}", s, e), - } - } - - fn assert_match(req: &VersionReq, vers: &[&str]) { - for ver in vers.iter() { - assert!(req.matches(&version(*ver)), "did not match {}", ver); - } - } - - fn assert_not_match(req: &VersionReq, vers: &[&str]) { - for ver in vers.iter() { - assert!(!req.matches(&version(*ver)), "matched {}", ver); - } - } - - #[test] - fn test_parsing_default() { - let r = req("1.0.0"); - - assert_eq!(r.to_string(), "^1.0.0".to_string()); - - assert_match(&r, &["1.0.0", "1.0.1"]); - assert_not_match(&r, &["0.9.9", "0.10.0", "0.1.0"]); - } - - #[test] - fn test_parsing_exact() { - let r = req("=1.0.0"); - - assert!(r.to_string() == "= 1.0.0".to_string()); - assert_eq!(r.to_string(), "= 1.0.0".to_string()); - - assert_match(&r, &["1.0.0"]); - assert_not_match(&r, &["1.0.1", "0.9.9", "0.10.0", "0.1.0", "1.0.0-pre"]); - - let r = req("=0.9.0"); - - assert_eq!(r.to_string(), "= 0.9.0".to_string()); - - assert_match(&r, &["0.9.0"]); - assert_not_match(&r, &["0.9.1", "1.9.0", "0.0.9"]); - - let r = req("=0.1.0-beta2.a"); - - assert_eq!(r.to_string(), "= 0.1.0-beta2.a".to_string()); - - assert_match(&r, &["0.1.0-beta2.a"]); - assert_not_match(&r, &["0.9.1", "0.1.0", "0.1.1-beta2.a", "0.1.0-beta2"]); - } - - #[test] - fn test_parse_metadata_see_issue_88_see_issue_88() { - for op in &[Op::Compatible, Op::Ex, Op::Gt, Op::GtEq, Op::Lt, Op::LtEq, Op::Tilde] { - req(&format!("{} 1.2.3+meta", op)); - } - } - - #[test] - pub fn test_parsing_greater_than() { - let r = req(">= 1.0.0"); - - assert_eq!(r.to_string(), ">= 1.0.0".to_string()); - - assert_match(&r, &["1.0.0", "2.0.0"]); - assert_not_match(&r, &["0.1.0", "0.0.1", "1.0.0-pre", "2.0.0-pre"]); - - let r = req(">= 2.1.0-alpha2"); - - assert_match(&r, &["2.1.0-alpha2", "2.1.0-alpha3", "2.1.0", "3.0.0"]); - assert_not_match(&r, - &["2.0.0", "2.1.0-alpha1", "2.0.0-alpha2", "3.0.0-alpha2"]); - } - - #[test] - pub fn test_parsing_less_than() { - let r = req("< 1.0.0"); - - assert_eq!(r.to_string(), "< 1.0.0".to_string()); - - assert_match(&r, &["0.1.0", "0.0.1"]); - assert_not_match(&r, &["1.0.0", "1.0.0-beta", "1.0.1", "0.9.9-alpha"]); - - let r = req("<= 2.1.0-alpha2"); - - assert_match(&r, &["2.1.0-alpha2", "2.1.0-alpha1", "2.0.0", "1.0.0"]); - assert_not_match(&r, - &["2.1.0", "2.2.0-alpha1", "2.0.0-alpha2", "1.0.0-alpha2"]); - } - - #[test] - pub fn test_multiple() { - let r = req("> 0.0.9, <= 2.5.3"); - assert_eq!(r.to_string(), "> 0.0.9, <= 2.5.3".to_string()); - assert_match(&r, &["0.0.10", "1.0.0", "2.5.3"]); - assert_not_match(&r, &["0.0.8", "2.5.4"]); - - let r = req("0.3.0, 0.4.0"); - assert_eq!(r.to_string(), "^0.3.0, ^0.4.0".to_string()); - assert_not_match(&r, &["0.0.8", "0.3.0", "0.4.0"]); - - let r = req("<= 0.2.0, >= 0.5.0"); - assert_eq!(r.to_string(), "<= 0.2.0, >= 0.5.0".to_string()); - assert_not_match(&r, &["0.0.8", "0.3.0", "0.5.1"]); - - let r = req("0.1.0, 0.1.4, 0.1.6"); - assert_eq!(r.to_string(), "^0.1.0, ^0.1.4, ^0.1.6".to_string()); - assert_match(&r, &["0.1.6", "0.1.9"]); - assert_not_match(&r, &["0.1.0", "0.1.4", "0.2.0"]); - - assert!(VersionReq::parse("> 0.1.0,").is_err()); - assert!(VersionReq::parse("> 0.3.0, ,").is_err()); - - let r = req(">=0.5.1-alpha3, <0.6"); - assert_eq!(r.to_string(), ">= 0.5.1-alpha3, < 0.6".to_string()); - assert_match(&r, - &["0.5.1-alpha3", "0.5.1-alpha4", "0.5.1-beta", "0.5.1", "0.5.5"]); - assert_not_match(&r, - &["0.5.1-alpha1", "0.5.2-alpha3", "0.5.5-pre", "0.5.0-pre"]); - assert_not_match(&r, &["0.6.0", "0.6.0-pre"]); - } - - #[test] - pub fn test_parsing_tilde() { - let r = req("~1"); - assert_match(&r, &["1.0.0", "1.0.1", "1.1.1"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "0.0.9"]); - - let r = req("~1.2"); - assert_match(&r, &["1.2.0", "1.2.1"]); - assert_not_match(&r, &["1.1.1", "1.3.0", "0.0.9"]); - - let r = req("~1.2.2"); - assert_match(&r, &["1.2.2", "1.2.4"]); - assert_not_match(&r, &["1.2.1", "1.9.0", "1.0.9", "2.0.1", "0.1.3"]); - - let r = req("~1.2.3-beta.2"); - assert_match(&r, &["1.2.3", "1.2.4", "1.2.3-beta.2", "1.2.3-beta.4"]); - assert_not_match(&r, &["1.3.3", "1.1.4", "1.2.3-beta.1", "1.2.4-beta.2"]); - } - - #[test] - pub fn test_parsing_compatible() { - let r = req("^1"); - assert_match(&r, &["1.1.2", "1.1.0", "1.2.1", "1.0.1"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "0.1.4"]); - assert_not_match(&r, &["1.0.0-beta1", "0.1.0-alpha", "1.0.1-pre"]); - - let r = req("^1.1"); - assert_match(&r, &["1.1.2", "1.1.0", "1.2.1"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "1.0.1", "0.1.4"]); - - let r = req("^1.1.2"); - assert_match(&r, &["1.1.2", "1.1.4", "1.2.1"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.0.1"]); - assert_not_match(&r, &["1.1.2-alpha1", "1.1.3-alpha1", "2.9.0-alpha1"]); - - let r = req("^0.1.2"); - assert_match(&r, &["0.1.2", "0.1.4"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.0.1"]); - assert_not_match(&r, &["0.1.2-beta", "0.1.3-alpha", "0.2.0-pre"]); - - let r = req("^0.5.1-alpha3"); - assert_match(&r, - &["0.5.1-alpha3", "0.5.1-alpha4", "0.5.1-beta", "0.5.1", "0.5.5"]); - assert_not_match(&r, - &["0.5.1-alpha1", "0.5.2-alpha3", "0.5.5-pre", "0.5.0-pre", "0.6.0"]); - - let r = req("^0.0.2"); - assert_match(&r, &["0.0.2"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.0.1", "0.1.4"]); - - let r = req("^0.0"); - assert_match(&r, &["0.0.2", "0.0.0"]); - assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.1.4"]); - - let r = req("^0"); - assert_match(&r, &["0.9.1", "0.0.2", "0.0.0"]); - assert_not_match(&r, &["2.9.0", "1.1.1"]); - - let r = req("^1.4.2-beta.5"); - assert_match(&r, - &["1.4.2", "1.4.3", "1.4.2-beta.5", "1.4.2-beta.6", "1.4.2-c"]); - assert_not_match(&r, - &["0.9.9", "2.0.0", "1.4.2-alpha", "1.4.2-beta.4", "1.4.3-beta.5"]); - } - - #[test] - pub fn test_parsing_wildcard() { - let r = req(""); - assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); - assert_not_match(&r, &[]); - let r = req("*"); - assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); - assert_not_match(&r, &[]); - let r = req("x"); - assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); - assert_not_match(&r, &[]); - let r = req("X"); - assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); - assert_not_match(&r, &[]); - - let r = req("1.*"); - assert_match(&r, &["1.2.0", "1.2.1", "1.1.1", "1.3.0"]); - assert_not_match(&r, &["0.0.9"]); - let r = req("1.x"); - assert_match(&r, &["1.2.0", "1.2.1", "1.1.1", "1.3.0"]); - assert_not_match(&r, &["0.0.9"]); - let r = req("1.X"); - assert_match(&r, &["1.2.0", "1.2.1", "1.1.1", "1.3.0"]); - assert_not_match(&r, &["0.0.9"]); - - let r = req("1.2.*"); - assert_match(&r, &["1.2.0", "1.2.2", "1.2.4"]); - assert_not_match(&r, &["1.9.0", "1.0.9", "2.0.1", "0.1.3"]); - let r = req("1.2.x"); - assert_match(&r, &["1.2.0", "1.2.2", "1.2.4"]); - assert_not_match(&r, &["1.9.0", "1.0.9", "2.0.1", "0.1.3"]); - let r = req("1.2.X"); - assert_match(&r, &["1.2.0", "1.2.2", "1.2.4"]); - assert_not_match(&r, &["1.9.0", "1.0.9", "2.0.1", "0.1.3"]); - } - - #[test] - pub fn test_any() { - let r = VersionReq::any(); - assert_match(&r, &["0.0.1", "0.1.0", "1.0.0"]); - } - - #[test] - pub fn test_pre() { - let r = req("=2.1.1-really.0"); - assert_match(&r, &["2.1.1-really.0"]); - } - - // #[test] - // pub fn test_parse_errors() { - // assert_eq!(Err(InvalidVersionRequirement), VersionReq::parse("\0")); - // assert_eq!(Err(OpAlreadySet), VersionReq::parse(">= >= 0.0.2")); - // assert_eq!(Err(InvalidSigil), VersionReq::parse(">== 0.0.2")); - // assert_eq!(Err(VersionComponentsMustBeNumeric), - // VersionReq::parse("a.0.0")); - // assert_eq!(Err(InvalidIdentifier), VersionReq::parse("1.0.0-")); - // assert_eq!(Err(MajorVersionRequired), VersionReq::parse(">=")); - // } - - #[test] - pub fn test_from_str() { - assert_eq!("1.0.0".parse::<VersionReq>().unwrap().to_string(), - "^1.0.0".to_string()); - assert_eq!("=1.0.0".parse::<VersionReq>().unwrap().to_string(), - "= 1.0.0".to_string()); - assert_eq!("~1".parse::<VersionReq>().unwrap().to_string(), - "~1".to_string()); - assert_eq!("~1.2".parse::<VersionReq>().unwrap().to_string(), - "~1.2".to_string()); - assert_eq!("^1".parse::<VersionReq>().unwrap().to_string(), - "^1".to_string()); - assert_eq!("^1.1".parse::<VersionReq>().unwrap().to_string(), - "^1.1".to_string()); - assert_eq!("*".parse::<VersionReq>().unwrap().to_string(), - "*".to_string()); - assert_eq!("1.*".parse::<VersionReq>().unwrap().to_string(), - "1.*".to_string()); - assert_eq!("< 1.0.0".parse::<VersionReq>().unwrap().to_string(), - "< 1.0.0".to_string()); - } - - // #[test] - // pub fn test_from_str_errors() { - // assert_eq!(Err(InvalidVersionRequirement), "\0".parse::<VersionReq>()); - // assert_eq!(Err(OpAlreadySet), ">= >= 0.0.2".parse::<VersionReq>()); - // assert_eq!(Err(InvalidSigil), ">== 0.0.2".parse::<VersionReq>()); - // assert_eq!(Err(VersionComponentsMustBeNumeric), - // "a.0.0".parse::<VersionReq>()); - // assert_eq!(Err(InvalidIdentifier), "1.0.0-".parse::<VersionReq>()); - // assert_eq!(Err(MajorVersionRequired), ">=".parse::<VersionReq>()); - // } - - #[test] - fn test_cargo3202() { - let v = "0.*.*".parse::<VersionReq>().unwrap(); - assert_eq!("0.*.*", format!("{}", v.predicates[0])); - - let v = "0.0.*".parse::<VersionReq>().unwrap(); - assert_eq!("0.0.*", format!("{}", v.predicates[0])); - - let r = req("0.*.*"); - assert_match(&r, &["0.5.0"]); - } -} diff -Nru cargo-0.25.0/vendor/semver-0.8.0/src/version.rs cargo-0.26.0/vendor/semver-0.8.0/src/version.rs --- cargo-0.25.0/vendor/semver-0.8.0/src/version.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.8.0/src/version.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,759 +0,0 @@ -// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The `version` module gives you tools to create and compare SemVer-compliant -//! versions. - -use std::cmp::{self, Ordering}; -use std::fmt; -use std::hash; -use std::error::Error; - -use std::result; -use std::str; - -use semver_parser; - -#[cfg(feature = "serde")] -use serde::ser::{Serialize, Serializer}; -#[cfg(feature = "serde")] -use serde::de::{self, Deserialize, Deserializer, Visitor}; - -/// An identifier in the pre-release or build metadata. -/// -/// See sections 9 and 10 of the spec for more about pre-release identifers and -/// build metadata. -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -pub enum Identifier { - /// An identifier that's solely numbers. - Numeric(u64), - /// An identifier with letters and numbers. - AlphaNumeric(String), -} - -impl From<semver_parser::version::Identifier> for Identifier { - fn from(other: semver_parser::version::Identifier) -> Identifier { - match other { - semver_parser::version::Identifier::Numeric(n) => Identifier::Numeric(n), - semver_parser::version::Identifier::AlphaNumeric(s) => Identifier::AlphaNumeric(s), - } - } -} - -impl fmt::Display for Identifier { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Identifier::Numeric(ref n) => fmt::Display::fmt(n, f), - Identifier::AlphaNumeric(ref s) => fmt::Display::fmt(s, f), - } - } -} - -#[cfg(feature = "serde")] -impl Serialize for Identifier { - fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error> - where S: Serializer - { - // Serialize Identifier as a number or string. - match *self { - Identifier::Numeric(n) => serializer.serialize_u64(n), - Identifier::AlphaNumeric(ref s) => serializer.serialize_str(s), - } - } -} - -#[cfg(feature = "serde")] -impl<'de> Deserialize<'de> for Identifier { - fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error> - where D: Deserializer<'de> - { - struct IdentifierVisitor; - - // Deserialize Identifier from a number or string. - impl<'de> Visitor<'de> for IdentifierVisitor { - type Value = Identifier; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a SemVer pre-release or build identifier") - } - - fn visit_u64<E>(self, numeric: u64) -> result::Result<Self::Value, E> - where E: de::Error - { - Ok(Identifier::Numeric(numeric)) - } - - fn visit_str<E>(self, alphanumeric: &str) -> result::Result<Self::Value, E> - where E: de::Error - { - Ok(Identifier::AlphaNumeric(alphanumeric.to_owned())) - } - } - - deserializer.deserialize_any(IdentifierVisitor) - } -} - -/// Represents a version number conforming to the semantic versioning scheme. -#[derive(Clone, Eq, Debug)] -pub struct Version { - /// The major version, to be incremented on incompatible changes. - pub major: u64, - /// The minor version, to be incremented when functionality is added in a - /// backwards-compatible manner. - pub minor: u64, - /// The patch version, to be incremented when backwards-compatible bug - /// fixes are made. - pub patch: u64, - /// The pre-release version identifier, if one exists. - pub pre: Vec<Identifier>, - /// The build metadata, ignored when determining version precedence. - pub build: Vec<Identifier>, -} - -impl From<semver_parser::version::Version> for Version { - fn from(other: semver_parser::version::Version) -> Version { - Version { - major: other.major, - minor: other.minor, - patch: other.patch, - pre: other.pre.into_iter().map(From::from).collect(), - build: other.build.into_iter().map(From::from).collect(), - } - } -} - -#[cfg(feature = "serde")] -impl Serialize for Version { - fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error> - where S: Serializer - { - // Serialize Version as a string. - serializer.collect_str(self) - } -} - -#[cfg(feature = "serde")] -impl<'de> Deserialize<'de> for Version { - fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error> - where D: Deserializer<'de> - { - struct VersionVisitor; - - // Deserialize Version from a string. - impl<'de> Visitor<'de> for VersionVisitor { - type Value = Version; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a SemVer version as a string") - } - - fn visit_str<E>(self, v: &str) -> result::Result<Self::Value, E> - where E: de::Error - { - Version::parse(v).map_err(de::Error::custom) - } - } - - deserializer.deserialize_str(VersionVisitor) - } -} - -/// An error type for this crate -/// -/// Currently, just a generic error. Will make this nicer later. -#[derive(Clone,PartialEq,Debug,PartialOrd)] -pub enum SemVerError { - /// An error ocurred while parsing. - ParseError(String), -} - -impl fmt::Display for SemVerError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self { - &SemVerError::ParseError(ref m) => write!(f, "{}", m), - } - } -} - -impl Error for SemVerError { - fn description(&self) -> &str { - match self { - &SemVerError::ParseError(ref m) => m, - } - } -} - -/// A Result type for errors -pub type Result<T> = result::Result<T, SemVerError>; - -impl Version { - - /// Contructs the simple case without pre or build. - pub fn new(major: u64, minor: u64, patch: u64) -> Version { - Version { - major: major, - minor: minor, - patch: patch, - pre: Vec::new(), - build: Vec::new() - } - } - - /// Parse a string into a semver object. - pub fn parse(version: &str) -> Result<Version> { - let res = semver_parser::version::parse(version); - - match res { - // Convert plain String error into proper ParseError - Err(e) => Err(SemVerError::ParseError(e)), - Ok(v) => Ok(From::from(v)), - } - } - - /// Clears the build metadata - fn clear_metadata(&mut self) { - self.build = Vec::new(); - self.pre = Vec::new(); - } - - /// Increments the patch number for this Version (Must be mutable) - pub fn increment_patch(&mut self) { - self.patch += 1; - self.clear_metadata(); - } - - /// Increments the minor version number for this Version (Must be mutable) - /// - /// As instructed by section 7 of the spec, the patch number is reset to 0. - pub fn increment_minor(&mut self) { - self.minor += 1; - self.patch = 0; - self.clear_metadata(); - } - - /// Increments the major version number for this Version (Must be mutable) - /// - /// As instructed by section 8 of the spec, the minor and patch numbers are - /// reset to 0 - pub fn increment_major(&mut self) { - self.major += 1; - self.minor = 0; - self.patch = 0; - self.clear_metadata(); - } - - /// Checks to see if the current Version is in pre-release status - pub fn is_prerelease(&self) -> bool { - !self.pre.is_empty() - } -} - -impl str::FromStr for Version { - type Err = SemVerError; - - fn from_str(s: &str) -> Result<Version> { - Version::parse(s) - } -} - -impl fmt::Display for Version { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}.{}.{}", self.major, self.minor, self.patch)); - if !self.pre.is_empty() { - try!(write!(f, "-")); - for (i, x) in self.pre.iter().enumerate() { - if i != 0 { - try!(write!(f, ".")) - } - try!(write!(f, "{}", x)); - } - } - if !self.build.is_empty() { - try!(write!(f, "+")); - for (i, x) in self.build.iter().enumerate() { - if i != 0 { - try!(write!(f, ".")) - } - try!(write!(f, "{}", x)); - } - } - Ok(()) - } -} - -impl cmp::PartialEq for Version { - #[inline] - fn eq(&self, other: &Version) -> bool { - // We should ignore build metadata here, otherwise versions v1 and v2 - // can exist such that !(v1 < v2) && !(v1 > v2) && v1 != v2, which - // violate strict total ordering rules. - self.major == other.major && self.minor == other.minor && self.patch == other.patch && - self.pre == other.pre - } -} - -impl cmp::PartialOrd for Version { - fn partial_cmp(&self, other: &Version) -> Option<Ordering> { - Some(self.cmp(other)) - } -} - -impl cmp::Ord for Version { - fn cmp(&self, other: &Version) -> Ordering { - match self.major.cmp(&other.major) { - Ordering::Equal => {} - r => return r, - } - - match self.minor.cmp(&other.minor) { - Ordering::Equal => {} - r => return r, - } - - match self.patch.cmp(&other.patch) { - Ordering::Equal => {} - r => return r, - } - - // NB: semver spec says 0.0.0-pre < 0.0.0 - // but the version of ord defined for vec - // says that [] < [pre] so we alter it here - match (self.pre.len(), other.pre.len()) { - (0, 0) => Ordering::Equal, - (0, _) => Ordering::Greater, - (_, 0) => Ordering::Less, - (_, _) => self.pre.cmp(&other.pre), - } - } -} - -impl hash::Hash for Version { - fn hash<H: hash::Hasher>(&self, into: &mut H) { - self.major.hash(into); - self.minor.hash(into); - self.patch.hash(into); - self.pre.hash(into); - } -} - -impl From<(u64,u64,u64)> for Version { - fn from(tuple: (u64,u64,u64)) -> Version { - let (major, minor, patch) = tuple; - Version::new(major, minor, patch) - } -} - -#[cfg(test)] -mod tests { - use std::result; - use super::Version; - use super::Identifier; - use super::SemVerError; - - #[test] - fn test_parse() { - fn parse_error(e: &str) -> result::Result<Version, SemVerError> { - return Err(SemVerError::ParseError(e.to_string())); - } - - assert_eq!(Version::parse(""), - parse_error("Error parsing major identifier")); - assert_eq!(Version::parse(" "), - parse_error("Error parsing major identifier")); - assert_eq!(Version::parse("1"), - parse_error("Expected dot")); - assert_eq!(Version::parse("1.2"), - parse_error("Expected dot")); - assert_eq!(Version::parse("1.2.3-"), - parse_error("Error parsing prerelease")); - assert_eq!(Version::parse("a.b.c"), - parse_error("Error parsing major identifier")); - assert_eq!(Version::parse("1.2.3 abc"), - parse_error("Extra junk after valid version: abc")); - - assert_eq!(Version::parse("1.2.3"), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: Vec::new(), - })); - - assert_eq!(Version::parse("1.2.3"), - Ok(Version::new(1,2,3))); - - assert_eq!(Version::parse(" 1.2.3 "), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: Vec::new(), - })); - assert_eq!(Version::parse("1.2.3-alpha1"), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: Vec::new(), - })); - assert_eq!(Version::parse(" 1.2.3-alpha1 "), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: Vec::new(), - })); - assert_eq!(Version::parse("1.2.3+build5"), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!(Version::parse(" 1.2.3+build5 "), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!(Version::parse("1.2.3-alpha1+build5"), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!(Version::parse(" 1.2.3-alpha1+build5 "), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!(Version::parse("1.2.3-1.alpha1.9+build5.7.3aedf "), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::Numeric(1), - Identifier::AlphaNumeric(String::from("alpha1")), - Identifier::Numeric(9), - ], - build: vec![Identifier::AlphaNumeric(String::from("build5")), - Identifier::Numeric(7), - Identifier::AlphaNumeric(String::from("3aedf")), - ], - })); - assert_eq!(Version::parse("0.4.0-beta.1+0851523"), - Ok(Version { - major: 0, - minor: 4, - patch: 0, - pre: vec![Identifier::AlphaNumeric(String::from("beta")), - Identifier::Numeric(1), - ], - build: vec![Identifier::AlphaNumeric(String::from("0851523"))], - })); - - } - - #[test] - fn test_increment_patch() { - let mut buggy_release = Version::parse("0.1.0").unwrap(); - buggy_release.increment_patch(); - assert_eq!(buggy_release, Version::parse("0.1.1").unwrap()); - } - - #[test] - fn test_increment_minor() { - let mut feature_release = Version::parse("1.4.6").unwrap(); - feature_release.increment_minor(); - assert_eq!(feature_release, Version::parse("1.5.0").unwrap()); - } - - #[test] - fn test_increment_major() { - let mut chrome_release = Version::parse("46.1.246773").unwrap(); - chrome_release.increment_major(); - assert_eq!(chrome_release, Version::parse("47.0.0").unwrap()); - } - - #[test] - fn test_increment_keep_prerelease() { - let mut release = Version::parse("1.0.0-alpha").unwrap(); - release.increment_patch(); - - assert_eq!(release, Version::parse("1.0.1").unwrap()); - - release.increment_minor(); - - assert_eq!(release, Version::parse("1.1.0").unwrap()); - - release.increment_major(); - - assert_eq!(release, Version::parse("2.0.0").unwrap()); - } - - - #[test] - fn test_increment_clear_metadata() { - let mut release = Version::parse("1.0.0+4442").unwrap(); - release.increment_patch(); - - assert_eq!(release, Version::parse("1.0.1").unwrap()); - release = Version::parse("1.0.1+hello").unwrap(); - - release.increment_minor(); - - assert_eq!(release, Version::parse("1.1.0").unwrap()); - release = Version::parse("1.1.3747+hello").unwrap(); - - release.increment_major(); - - assert_eq!(release, Version::parse("2.0.0").unwrap()); - } - - #[test] - fn test_eq() { - assert_eq!(Version::parse("1.2.3"), Version::parse("1.2.3")); - assert_eq!(Version::parse("1.2.3-alpha1"), - Version::parse("1.2.3-alpha1")); - assert_eq!(Version::parse("1.2.3+build.42"), - Version::parse("1.2.3+build.42")); - assert_eq!(Version::parse("1.2.3-alpha1+42"), - Version::parse("1.2.3-alpha1+42")); - assert_eq!(Version::parse("1.2.3+23"), Version::parse("1.2.3+42")); - } - - #[test] - fn test_ne() { - assert!(Version::parse("0.0.0") != Version::parse("0.0.1")); - assert!(Version::parse("0.0.0") != Version::parse("0.1.0")); - assert!(Version::parse("0.0.0") != Version::parse("1.0.0")); - assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta")); - } - - #[test] - fn test_show() { - assert_eq!(format!("{}", Version::parse("1.2.3").unwrap()), - "1.2.3".to_string()); - assert_eq!(format!("{}", Version::parse("1.2.3-alpha1").unwrap()), - "1.2.3-alpha1".to_string()); - assert_eq!(format!("{}", Version::parse("1.2.3+build.42").unwrap()), - "1.2.3+build.42".to_string()); - assert_eq!(format!("{}", Version::parse("1.2.3-alpha1+42").unwrap()), - "1.2.3-alpha1+42".to_string()); - } - - #[test] - fn test_to_string() { - assert_eq!(Version::parse("1.2.3").unwrap().to_string(), - "1.2.3".to_string()); - assert_eq!(Version::parse("1.2.3-alpha1").unwrap().to_string(), - "1.2.3-alpha1".to_string()); - assert_eq!(Version::parse("1.2.3+build.42").unwrap().to_string(), - "1.2.3+build.42".to_string()); - assert_eq!(Version::parse("1.2.3-alpha1+42").unwrap().to_string(), - "1.2.3-alpha1+42".to_string()); - } - - #[test] - fn test_lt() { - assert!(Version::parse("0.0.0") < Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.0.0") < Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.0") < Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.3-alpha1") < Version::parse("1.2.3")); - assert!(Version::parse("1.2.3-alpha1") < Version::parse("1.2.3-alpha2")); - assert!(!(Version::parse("1.2.3-alpha2") < Version::parse("1.2.3-alpha2"))); - assert!(!(Version::parse("1.2.3+23") < Version::parse("1.2.3+42"))); - } - - #[test] - fn test_le() { - assert!(Version::parse("0.0.0") <= Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.0.0") <= Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.0") <= Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.3-alpha1") <= Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.3-alpha2") <= Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.3+23") <= Version::parse("1.2.3+42")); - } - - #[test] - fn test_gt() { - assert!(Version::parse("1.2.3-alpha2") > Version::parse("0.0.0")); - assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.0.0")); - assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0")); - assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.3-alpha1")); - assert!(Version::parse("1.2.3") > Version::parse("1.2.3-alpha2")); - assert!(!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.3-alpha2"))); - assert!(!(Version::parse("1.2.3+23") > Version::parse("1.2.3+42"))); - } - - #[test] - fn test_ge() { - assert!(Version::parse("1.2.3-alpha2") >= Version::parse("0.0.0")); - assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.0.0")); - assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.0")); - assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.3-alpha1")); - assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.3-alpha2")); - assert!(Version::parse("1.2.3+23") >= Version::parse("1.2.3+42")); - } - - #[test] - fn test_prerelease_check() { - assert!(Version::parse("1.0.0").unwrap().is_prerelease() == false); - assert!(Version::parse("0.0.1").unwrap().is_prerelease() == false); - assert!(Version::parse("4.1.4-alpha").unwrap().is_prerelease()); - assert!(Version::parse("1.0.0-beta294296").unwrap().is_prerelease()); - } - - #[test] - fn test_spec_order() { - let vs = ["1.0.0-alpha", - "1.0.0-alpha.1", - "1.0.0-alpha.beta", - "1.0.0-beta", - "1.0.0-beta.2", - "1.0.0-beta.11", - "1.0.0-rc.1", - "1.0.0"]; - let mut i = 1; - while i < vs.len() { - let a = Version::parse(vs[i - 1]); - let b = Version::parse(vs[i]); - assert!(a < b, "nope {:?} < {:?}", a, b); - i += 1; - } - } - - #[test] - fn test_from_str() { - assert_eq!("1.2.3".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: Vec::new(), - })); - assert_eq!(" 1.2.3 ".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: Vec::new(), - })); - assert_eq!("1.2.3-alpha1".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: Vec::new(), - })); - assert_eq!(" 1.2.3-alpha1 ".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: Vec::new(), - })); - assert_eq!("1.2.3+build5".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!(" 1.2.3+build5 ".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: Vec::new(), - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!("1.2.3-alpha1+build5".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!(" 1.2.3-alpha1+build5 ".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], - build: vec![Identifier::AlphaNumeric(String::from("build5"))], - })); - assert_eq!("1.2.3-1.alpha1.9+build5.7.3aedf ".parse(), - Ok(Version { - major: 1, - minor: 2, - patch: 3, - pre: vec![Identifier::Numeric(1), - Identifier::AlphaNumeric(String::from("alpha1")), - Identifier::Numeric(9), - ], - build: vec![Identifier::AlphaNumeric(String::from("build5")), - Identifier::Numeric(7), - Identifier::AlphaNumeric(String::from("3aedf")), - ], - })); - assert_eq!("0.4.0-beta.1+0851523".parse(), - Ok(Version { - major: 0, - minor: 4, - patch: 0, - pre: vec![Identifier::AlphaNumeric(String::from("beta")), - Identifier::Numeric(1), - ], - build: vec![Identifier::AlphaNumeric(String::from("0851523"))], - })); - - } - - #[test] - fn test_from_str_errors() { - fn parse_error(e: &str) -> result::Result<Version, SemVerError> { - return Err(SemVerError::ParseError(e.to_string())); - } - - assert_eq!("".parse(), parse_error("Error parsing major identifier")); - assert_eq!(" ".parse(), parse_error("Error parsing major identifier")); - assert_eq!("1".parse(), parse_error("Expected dot")); - assert_eq!("1.2".parse(), - parse_error("Expected dot")); - assert_eq!("1.2.3-".parse(), - parse_error("Error parsing prerelease")); - assert_eq!("a.b.c".parse(), - parse_error("Error parsing major identifier")); - assert_eq!("1.2.3 abc".parse(), - parse_error("Extra junk after valid version: abc")); - } -} diff -Nru cargo-0.25.0/vendor/semver-0.8.0/tests/deprecation.rs cargo-0.26.0/vendor/semver-0.8.0/tests/deprecation.rs --- cargo-0.25.0/vendor/semver-0.8.0/tests/deprecation.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.8.0/tests/deprecation.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -extern crate semver; - -#[test] -fn test_regressions() { - use semver::VersionReq; - use semver::ReqParseError; - - let versions = vec![ - (".*", VersionReq::any()), - ("0.1.0.", VersionReq::parse("0.1.0").unwrap()), - ("0.3.1.3", VersionReq::parse("0.3.13").unwrap()), - ("0.2*", VersionReq::parse("0.2.*").unwrap()), - ("*.0", VersionReq::any()), - ]; - - for (version, requirement) in versions.into_iter() { - let parsed = VersionReq::parse(version); - let error = parsed.err().unwrap(); - - assert_eq!(ReqParseError::DeprecatedVersionRequirement(requirement), error); - } -} diff -Nru cargo-0.25.0/vendor/semver-0.8.0/tests/regression.rs cargo-0.26.0/vendor/semver-0.8.0/tests/regression.rs --- cargo-0.25.0/vendor/semver-0.8.0/tests/regression.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.8.0/tests/regression.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -extern crate semver; -extern crate crates_index; -extern crate tempdir; - -// This test checks to see if every existing crate parses successfully. Important to not break the -// Rust universe! - -#[cfg(feature = "ci")] -#[test] -fn test_regressions() { - use tempdir::TempDir; - use crates_index::Index; - use semver::Version; - - let dir = TempDir::new("semver").unwrap(); - let index = Index::new(dir.into_path()); - index.clone().unwrap(); - - for krate in index.crates() { - for version in krate.versions() { - let v = version.version(); - assert!(Version::parse(v).is_ok(), "failed: {} ({})", version.name(), v); - } - } -} diff -Nru cargo-0.25.0/vendor/semver-0.8.0/tests/serde.rs cargo-0.26.0/vendor/semver-0.8.0/tests/serde.rs --- cargo-0.25.0/vendor/semver-0.8.0/tests/serde.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.8.0/tests/serde.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,90 +0,0 @@ -#![cfg(feature = "serde")] - -#[macro_use] -extern crate serde_derive; - -extern crate semver; -extern crate serde_json; - -use semver::{Identifier, Version, VersionReq}; - -#[derive(Serialize, Deserialize, PartialEq, Debug)] -struct Identified { - name: String, - identifier: Identifier, -} - -#[derive(Serialize, Deserialize, PartialEq, Debug)] -struct Versioned { - name: String, - vers: Version, -} - -#[test] -fn serialize_identifier() { - let id = Identified { - name: "serde".to_owned(), - identifier: Identifier::Numeric(100), - }; - let j = serde_json::to_string(&id).unwrap(); - assert_eq!(j, r#"{"name":"serde","identifier":100}"#); - - let id = Identified { - name: "serde".to_owned(), - identifier: Identifier::AlphaNumeric("b100".to_owned()), - }; - let j = serde_json::to_string(&id).unwrap(); - assert_eq!(j, r#"{"name":"serde","identifier":"b100"}"#); -} - -#[test] -fn deserialize_identifier() { - let j = r#"{"name":"serde","identifier":100}"#; - let id = serde_json::from_str::<Identified>(j).unwrap(); - let expected = Identified { - name: "serde".to_owned(), - identifier: Identifier::Numeric(100), - }; - assert_eq!(id, expected); - - let j = r#"{"name":"serde","identifier":"b100"}"#; - let id = serde_json::from_str::<Identified>(j).unwrap(); - let expected = Identified { - name: "serde".to_owned(), - identifier: Identifier::AlphaNumeric("b100".to_owned()), - }; - assert_eq!(id, expected); -} - -#[test] -fn serialize_version() { - let v = Versioned { - name: "serde".to_owned(), - vers: Version::parse("1.0.0").unwrap(), - }; - let j = serde_json::to_string(&v).unwrap(); - assert_eq!(j, r#"{"name":"serde","vers":"1.0.0"}"#); -} - -#[test] -fn deserialize_version() { - let j = r#"{"name":"serde","vers":"1.0.0"}"#; - let v = serde_json::from_str::<Versioned>(j).unwrap(); - let expected = Versioned { - name: "serde".to_owned(), - vers: Version::parse("1.0.0").unwrap(), - }; - assert_eq!(v, expected); -} - -#[test] -fn serialize_versionreq() { - let v = VersionReq::exact(&Version::parse("1.0.0").unwrap()); - - assert_eq!(serde_json::to_string(&v).unwrap(), r#""= 1.0.0""#); -} - -#[test] -fn deserialize_versionreq() { - assert_eq!("1.0.0".parse::<VersionReq>().unwrap(), serde_json::from_str(r#""1.0.0""#).unwrap()); -} diff -Nru cargo-0.25.0/vendor/semver-0.8.0/.travis.yml cargo-0.26.0/vendor/semver-0.8.0/.travis.yml --- cargo-0.25.0/vendor/semver-0.8.0/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.8.0/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -language: rust -rust: - - nightly - - beta - - stable -sudo: false -script: - - cargo build --verbose - - cargo test --verbose --features ci -addons: - apt: - sources: - - kalakris-cmake - packages: - - cmake -notifications: - email: - on_success: never diff -Nru cargo-0.25.0/vendor/semver-0.9.0/.cargo-checksum.json cargo-0.26.0/vendor/semver-0.9.0/.cargo-checksum.json --- cargo-0.25.0/vendor/semver-0.9.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.9.0/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/semver-0.9.0/Cargo.toml cargo-0.26.0/vendor/semver-0.9.0/Cargo.toml --- cargo-0.25.0/vendor/semver-0.9.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.9.0/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,45 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "semver" +version = "0.9.0" +authors = ["Steve Klabnik <steve@steveklabnik.com>", "The Rust Project Developers"] +description = "Semantic version parsing and comparison.\n" +homepage = "https://docs.rs/crate/semver/" +documentation = "https://docs.rs/crate/semver/" +readme = "README.md" +license = "MIT/Apache-2.0" +repository = "https://github.com/steveklabnik/semver" +[dependencies.semver-parser] +version = "0.7.0" + +[dependencies.serde] +version = "1.0" +optional = true +[dev-dependencies.crates-index] +version = "0.5.0" + +[dev-dependencies.serde_json] +version = "1.0" + +[dev-dependencies.serde_derive] +version = "1.0" + +[dev-dependencies.tempdir] +version = "0.3.4" + +[features] +default = [] +ci = ["serde"] +[badges.travis-ci] +repository = "steveklabnik/semver" diff -Nru cargo-0.25.0/vendor/semver-0.9.0/LICENSE-APACHE cargo-0.26.0/vendor/semver-0.9.0/LICENSE-APACHE --- cargo-0.25.0/vendor/semver-0.9.0/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.9.0/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/semver-0.9.0/LICENSE-MIT cargo-0.26.0/vendor/semver-0.9.0/LICENSE-MIT --- cargo-0.25.0/vendor/semver-0.9.0/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.9.0/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/semver-0.9.0/README.md cargo-0.26.0/vendor/semver-0.9.0/README.md --- cargo-0.25.0/vendor/semver-0.9.0/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.9.0/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,103 @@ +semver +====== + +Semantic version parsing and comparison. + +[![Build Status](https://api.travis-ci.org/steveklabnik/semver.svg?branch=master)](https://travis-ci.org/steveklabnik/semver) + +[Documentation](https://steveklabnik.github.io/semver) + +Semantic versioning (see http://semver.org/) is a set of rules for +assigning version numbers. + +## SemVer and the Rust ecosystem + +Rust itself follows the SemVer specification, as does its standard libraries. The two are +not tied together. + +[Cargo](https://crates.io), Rust's package manager, uses SemVer to determine which versions of +packages you need installed. + +## Installation + +To use `semver`, add this to your `[dependencies]` section: + +```toml +semver = "0.7.0" +``` + +And this to your crate root: + +```rust +extern crate semver; +``` + +## Versions + +At its simplest, the `semver` crate allows you to construct `Version` objects using the `parse` +method: + +```rust +use semver::Version; + +assert!(Version::parse("1.2.3") == Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec!(), + build: vec!(), +})); +``` + +If you have multiple `Version`s, you can use the usual comparison operators to compare them: + +```rust +use semver::Version; + +assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta")); +assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0")); +``` + +## Requirements + +The `semver` crate also provides the ability to compare requirements, which are more complex +comparisons. + +For example, creating a requirement that only matches versions greater than or +equal to 1.0.0: + +```rust +use semver::Version; +use semver::VersionReq; + +let r = VersionReq::parse(">= 1.0.0").unwrap(); +let v = Version::parse("1.0.0").unwrap(); + +assert!(r.to_string() == ">= 1.0.0".to_string()); +assert!(r.matches(&v)) +``` + +It also allows parsing of `~x.y.z` and `^x.y.z` requirements as defined at +https://www.npmjs.org/doc/misc/semver.html + +**Tilde requirements** specify a minimal version with some updates: + +```notrust +~1.2.3 := >=1.2.3 <1.3.0 +~1.2 := >=1.2.0 <1.3.0 +~1 := >=1.0.0 <2.0.0 +``` + +**Caret requirements** allow SemVer compatible updates to a specified version, +`0.x` and `0.x+1` are not considered compatible, but `1.x` and `1.x+1` are. + +`0.0.x` is not considered compatible with any other version. +Missing minor and patch versions are desugared to `0` but allow flexibility for that value. + +```notrust +^1.2.3 := >=1.2.3 <2.0.0 +^0.2.3 := >=0.2.3 <0.3.0 +^0.0.3 := >=0.0.3 <0.0.4 +^0.0 := >=0.0.0 <0.1.0 +^0 := >=0.0.0 <1.0.0 +``` diff -Nru cargo-0.25.0/vendor/semver-0.9.0/src/lib.rs cargo-0.26.0/vendor/semver-0.9.0/src/lib.rs --- cargo-0.25.0/vendor/semver-0.9.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.9.0/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,182 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Semantic version parsing and comparison. +//! +//! Semantic versioning (see http://semver.org/) is a set of rules for +//! assigning version numbers. +//! +//! ## SemVer overview +//! +//! Given a version number MAJOR.MINOR.PATCH, increment the: +//! +//! 1. MAJOR version when you make incompatible API changes, +//! 2. MINOR version when you add functionality in a backwards-compatible +//! manner, and +//! 3. PATCH version when you make backwards-compatible bug fixes. +//! +//! Additional labels for pre-release and build metadata are available as +//! extensions to the MAJOR.MINOR.PATCH format. +//! +//! Any references to 'the spec' in this documentation refer to [version 2.0 of +//! the SemVer spec](http://semver.org/spec/v2.0.0.html). +//! +//! ## SemVer and the Rust ecosystem +//! +//! Rust itself follows the SemVer specification, as does its standard +//! libraries. The two are not tied together. +//! +//! [Cargo](http://crates.io), Rust's package manager, uses SemVer to determine +//! which versions of packages you need installed. +//! +//! ## Versions +//! +//! At its simplest, the `semver` crate allows you to construct `Version` +//! objects using the `parse` method: +//! +//! ```{rust} +//! use semver::Version; +//! +//! assert!(Version::parse("1.2.3") == Ok(Version { +//! major: 1, +//! minor: 2, +//! patch: 3, +//! pre: vec!(), +//! build: vec!(), +//! })); +//! ``` +//! +//! If you have multiple `Version`s, you can use the usual comparison operators +//! to compare them: +//! +//! ```{rust} +//! use semver::Version; +//! +//! assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta")); +//! assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0")); +//! ``` +//! +//! If you explicitly need to modify a Version, SemVer also allows you to +//! increment the major, minor, and patch numbers in accordance with the spec. +//! +//! Please note that in order to do this, you must use a mutable Version: +//! +//! ```{rust} +//! use semver::Version; +//! +//! let mut bugfix_release = Version::parse("1.0.0").unwrap(); +//! bugfix_release.increment_patch(); +//! +//! assert_eq!(Ok(bugfix_release), Version::parse("1.0.1")); +//! ``` +//! +//! When incrementing the minor version number, the patch number resets to zero +//! (in accordance with section 7 of the spec) +//! +//! ```{rust} +//! use semver::Version; +//! +//! let mut feature_release = Version::parse("1.4.6").unwrap(); +//! feature_release.increment_minor(); +//! +//! assert_eq!(Ok(feature_release), Version::parse("1.5.0")); +//! ``` +//! +//! Similarly, when incrementing the major version number, the patch and minor +//! numbers reset to zero (in accordance with section 8 of the spec) +//! +//! ```{rust} +//! use semver::Version; +//! +//! let mut chrome_release = Version::parse("41.5.5377").unwrap(); +//! chrome_release.increment_major(); +//! +//! assert_eq!(Ok(chrome_release), Version::parse("42.0.0")); +//! ``` +//! +//! ## Requirements +//! +//! The `semver` crate also provides the ability to compare requirements, which +//! are more complex comparisons. +//! +//! For example, creating a requirement that only matches versions greater than +//! or equal to 1.0.0: +//! +//! ```{rust} +//! # #![allow(unstable)] +//! use semver::Version; +//! use semver::VersionReq; +//! +//! let r = VersionReq::parse(">= 1.0.0").unwrap(); +//! let v = Version::parse("1.0.0").unwrap(); +//! +//! assert!(r.to_string() == ">= 1.0.0".to_string()); +//! assert!(r.matches(&v)) +//! ``` +//! +//! It also allows parsing of `~x.y.z` and `^x.y.z` requirements as defined at +//! https://www.npmjs.org/doc/misc/semver.html +//! +//! **Tilde requirements** specify a minimal version with some updates: +//! +//! ```notrust +//! ~1.2.3 := >=1.2.3 <1.3.0 +//! ~1.2 := >=1.2.0 <1.3.0 +//! ~1 := >=1.0.0 <2.0.0 +//! ``` +//! +//! **Caret requirements** allow SemVer compatible updates to a specified +//! verion, `0.x` and `0.x+1` are not considered compatible, but `1.x` and +//! `1.x+1` are. +//! +//! `0.0.x` is not considered compatible with any other version. +//! Missing minor and patch versions are desugared to `0` but allow flexibility +//! for that value. +//! +//! ```notrust +//! ^1.2.3 := >=1.2.3 <2.0.0 +//! ^0.2.3 := >=0.2.3 <0.3.0 +//! ^0.0.3 := >=0.0.3 <0.0.4 +//! ^0.0 := >=0.0.0 <0.1.0 +//! ^0 := >=0.0.0 <1.0.0 +//! ``` +//! +//! **Wildcard requirements** allows parsing of version requirements of the +//! formats `*`, `x.*` and `x.y.*`. +//! +//! ```notrust +//! * := >=0.0.0 +//! 1.* := >=1.0.0 <2.0.0 +//! 1.2.* := >=1.2.0 <1.3.0 +//! ``` + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico")] +#![deny(missing_docs)] +#![cfg_attr(test, deny(warnings))] + +extern crate semver_parser; + +// Serialization and deserialization support for version numbers +#[cfg(feature = "serde")] +extern crate serde; + +// We take the common approach of keeping our own module system private, and +// just re-exporting the interface that we want. + +pub use version::{Version, Identifier, SemVerError}; +pub use version::Identifier::{Numeric, AlphaNumeric}; +pub use version_req::{VersionReq, ReqParseError}; + +// SemVer-compliant versions. +mod version; + +// advanced version comparisons +mod version_req; diff -Nru cargo-0.25.0/vendor/semver-0.9.0/src/version_req.rs cargo-0.26.0/vendor/semver-0.9.0/src/version_req.rs --- cargo-0.25.0/vendor/semver-0.9.0/src/version_req.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.9.0/src/version_req.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,895 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::error::Error; +use std::fmt; +use std::result; +use std::str; + +use Version; +use version::Identifier; +use semver_parser; + +#[cfg(feature = "serde")] +use serde::ser::{Serialize, Serializer}; +#[cfg(feature = "serde")] +use serde::de::{self, Deserialize, Deserializer, Visitor}; + +use self::Op::{Ex, Gt, GtEq, Lt, LtEq, Tilde, Compatible, Wildcard}; +use self::WildcardVersion::{Major, Minor, Patch}; +use self::ReqParseError::*; + +/// A `VersionReq` is a struct containing a list of predicates that can apply to ranges of version +/// numbers. Matching operations can then be done with the `VersionReq` against a particular +/// version to see if it satisfies some or all of the constraints. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub struct VersionReq { + predicates: Vec<Predicate>, +} + +impl From<semver_parser::range::VersionReq> for VersionReq { + fn from(other: semver_parser::range::VersionReq) -> VersionReq { + VersionReq { predicates: other.predicates.into_iter().map(From::from).collect() } + } +} + +#[cfg(feature = "serde")] +impl Serialize for VersionReq { + fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error> + where S: Serializer + { + // Serialize VersionReq as a string. + serializer.collect_str(self) + } +} + +#[cfg(feature = "serde")] +impl<'de> Deserialize<'de> for VersionReq { + fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error> + where D: Deserializer<'de> + { + struct VersionReqVisitor; + + /// Deserialize `VersionReq` from a string. + impl<'de> Visitor<'de> for VersionReqVisitor { + type Value = VersionReq; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a SemVer version requirement as a string") + } + + fn visit_str<E>(self, v: &str) -> result::Result<Self::Value, E> + where E: de::Error + { + VersionReq::parse(v).map_err(de::Error::custom) + } + } + + deserializer.deserialize_str(VersionReqVisitor) + } +} + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +enum WildcardVersion { + Major, + Minor, + Patch, +} + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +enum Op { + Ex, // Exact + Gt, // Greater than + GtEq, // Greater than or equal to + Lt, // Less than + LtEq, // Less than or equal to + Tilde, // e.g. ~1.0.0 + Compatible, // compatible by definition of semver, indicated by ^ + Wildcard(WildcardVersion), // x.y.*, x.*, * +} + +impl From<semver_parser::range::Op> for Op { + fn from(other: semver_parser::range::Op) -> Op { + use semver_parser::range; + match other { + range::Op::Ex => Op::Ex, + range::Op::Gt => Op::Gt, + range::Op::GtEq => Op::GtEq, + range::Op::Lt => Op::Lt, + range::Op::LtEq => Op::LtEq, + range::Op::Tilde => Op::Tilde, + range::Op::Compatible => Op::Compatible, + range::Op::Wildcard(version) => { + match version { + range::WildcardVersion::Major => Op::Wildcard(WildcardVersion::Major), + range::WildcardVersion::Minor => Op::Wildcard(WildcardVersion::Minor), + range::WildcardVersion::Patch => Op::Wildcard(WildcardVersion::Patch), + } + } + } + } +} + +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +struct Predicate { + op: Op, + major: u64, + minor: Option<u64>, + patch: Option<u64>, + pre: Vec<Identifier>, +} + +impl From<semver_parser::range::Predicate> for Predicate { + fn from(other: semver_parser::range::Predicate) -> Predicate { + Predicate { + op: From::from(other.op), + major: other.major, + minor: other.minor, + patch: other.patch, + pre: other.pre.into_iter().map(From::from).collect(), + } + } +} + +/// A `ReqParseError` is returned from methods which parse a string into a `VersionReq`. Each +/// enumeration is one of the possible errors that can occur. +#[derive(Clone, Debug, PartialEq)] +pub enum ReqParseError { + /// The given version requirement is invalid. + InvalidVersionRequirement, + /// You have already provided an operation, such as `=`, `~`, or `^`. Only use one. + OpAlreadySet, + /// The sigil you have written is not correct. + InvalidSigil, + /// All components of a version must be numeric. + VersionComponentsMustBeNumeric, + /// There was an error parsing an identifier. + InvalidIdentifier, + /// At least a major version is required. + MajorVersionRequired, + /// An unimplemented version requirement. + UnimplementedVersionRequirement, + /// This form of requirement is deprecated. + DeprecatedVersionRequirement(VersionReq), +} + +impl fmt::Display for ReqParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.description().fmt(f) + } +} + +impl Error for ReqParseError { + fn description(&self) -> &str { + match self { + &InvalidVersionRequirement => "the given version requirement is invalid", + &OpAlreadySet => { + "you have already provided an operation, such as =, ~, or ^; only use one" + }, + &InvalidSigil => "the sigil you have written is not correct", + &VersionComponentsMustBeNumeric => "version components must be numeric", + &InvalidIdentifier => "invalid identifier", + &MajorVersionRequired => "at least a major version number is required", + &UnimplementedVersionRequirement => { + "the given version requirement is not implemented, yet" + }, + &DeprecatedVersionRequirement(_) => "This requirement is deprecated", + } + } +} + +impl From<String> for ReqParseError { + fn from(other: String) -> ReqParseError { + match &*other { + "Null is not a valid VersionReq" => ReqParseError::InvalidVersionRequirement, + "VersionReq did not parse properly." => ReqParseError::OpAlreadySet, + _ => ReqParseError::InvalidVersionRequirement, + } + } +} + +impl VersionReq { + /// `any()` is a factory method which creates a `VersionReq` with no constraints. In other + /// words, any version will match against it. + /// + /// # Examples + /// + /// ``` + /// use semver::VersionReq; + /// + /// let anything = VersionReq::any(); + /// ``` + pub fn any() -> VersionReq { + VersionReq { predicates: vec![] } + } + + /// `parse()` is the main constructor of a `VersionReq`. It takes a string like `"^1.2.3"` + /// and turns it into a `VersionReq` that matches that particular constraint. + /// + /// A `Result` is returned which contains a `ReqParseError` if there was a problem parsing the + /// `VersionReq`. + /// + /// # Examples + /// + /// ``` + /// use semver::VersionReq; + /// + /// let version = VersionReq::parse("=1.2.3"); + /// let version = VersionReq::parse(">1.2.3"); + /// let version = VersionReq::parse("<1.2.3"); + /// let version = VersionReq::parse("~1.2.3"); + /// let version = VersionReq::parse("^1.2.3"); + /// let version = VersionReq::parse("1.2.3"); // synonym for ^1.2.3 + /// let version = VersionReq::parse("<=1.2.3"); + /// let version = VersionReq::parse(">=1.2.3"); + /// ``` + /// + /// This example demonstrates error handling, and will panic. + /// + /// ```should-panic + /// use semver::VersionReq; + /// + /// let version = match VersionReq::parse("not a version") { + /// Ok(version) => version, + /// Err(e) => panic!("There was a problem parsing: {}", e), + /// } + /// ``` + pub fn parse(input: &str) -> Result<VersionReq, ReqParseError> { + let res = semver_parser::range::parse(input); + + if let Ok(v) = res { + return Ok(From::from(v)); + } + + return match VersionReq::parse_deprecated(input) { + Some(v) => { + Err(ReqParseError::DeprecatedVersionRequirement(v)) + } + None => Err(From::from(res.err().unwrap())), + } + } + + fn parse_deprecated(version: &str) -> Option<VersionReq> { + return match version { + ".*" => Some(VersionReq::any()), + "0.1.0." => Some(VersionReq::parse("0.1.0").unwrap()), + "0.3.1.3" => Some(VersionReq::parse("0.3.13").unwrap()), + "0.2*" => Some(VersionReq::parse("0.2.*").unwrap()), + "*.0" => Some(VersionReq::any()), + _ => None, + } + } + + /// `exact()` is a factory method which creates a `VersionReq` with one exact constraint. + /// + /// # Examples + /// + /// ``` + /// use semver::VersionReq; + /// use semver::Version; + /// + /// let version = Version { major: 1, minor: 1, patch: 1, pre: vec![], build: vec![] }; + /// let exact = VersionReq::exact(&version); + /// ``` + pub fn exact(version: &Version) -> VersionReq { + VersionReq { predicates: vec![Predicate::exact(version)] } + } + + /// `matches()` matches a given `Version` against this `VersionReq`. + /// + /// # Examples + /// + /// ``` + /// use semver::VersionReq; + /// use semver::Version; + /// + /// let version = Version { major: 1, minor: 1, patch: 1, pre: vec![], build: vec![] }; + /// let exact = VersionReq::exact(&version); + /// + /// assert!(exact.matches(&version)); + /// ``` + pub fn matches(&self, version: &Version) -> bool { + // no predicates means anything matches + if self.predicates.is_empty() { + return true; + } + + self.predicates.iter().all(|p| p.matches(version)) && + self.predicates.iter().any(|p| p.pre_tag_is_compatible(version)) + } +} + +impl str::FromStr for VersionReq { + type Err = ReqParseError; + + fn from_str(s: &str) -> Result<VersionReq, ReqParseError> { + VersionReq::parse(s) + } +} + +impl Predicate { + fn exact(version: &Version) -> Predicate { + Predicate { + op: Ex, + major: version.major, + minor: Some(version.minor), + patch: Some(version.patch), + pre: version.pre.clone(), + } + } + + /// `matches()` takes a `Version` and determines if it matches this particular `Predicate`. + pub fn matches(&self, ver: &Version) -> bool { + match self.op { + Ex => self.is_exact(ver), + Gt => self.is_greater(ver), + GtEq => self.is_exact(ver) || self.is_greater(ver), + Lt => !self.is_exact(ver) && !self.is_greater(ver), + LtEq => !self.is_greater(ver), + Tilde => self.matches_tilde(ver), + Compatible => self.is_compatible(ver), + Wildcard(_) => self.matches_wildcard(ver), + } + } + + fn is_exact(&self, ver: &Version) -> bool { + if self.major != ver.major { + return false; + } + + match self.minor { + Some(minor) => { + if minor != ver.minor { + return false; + } + } + None => return true, + } + + match self.patch { + Some(patch) => { + if patch != ver.patch { + return false; + } + } + None => return true, + } + + if self.pre != ver.pre { + return false; + } + + true + } + + // https://docs.npmjs.com/misc/semver#prerelease-tags + fn pre_tag_is_compatible(&self, ver: &Version) -> bool { + // If a version has a prerelease tag (for example, 1.2.3-alpha.3) then it will + // only be + // allowed to satisfy comparator sets if at least one comparator with the same + // [major, + // minor, patch] tuple also has a prerelease tag. + !ver.is_prerelease() || + (self.major == ver.major && self.minor == Some(ver.minor) && + self.patch == Some(ver.patch) && !self.pre.is_empty()) + } + + fn is_greater(&self, ver: &Version) -> bool { + if self.major != ver.major { + return ver.major > self.major; + } + + match self.minor { + Some(minor) => { + if minor != ver.minor { + return ver.minor > minor; + } + } + None => return false, + } + + match self.patch { + Some(patch) => { + if patch != ver.patch { + return ver.patch > patch; + } + } + None => return false, + } + + if !self.pre.is_empty() { + return ver.pre.is_empty() || ver.pre > self.pre; + } + + false + } + + // see https://www.npmjs.org/doc/misc/semver.html for behavior + fn matches_tilde(&self, ver: &Version) -> bool { + let minor = match self.minor { + Some(n) => n, + None => return self.major == ver.major, + }; + + match self.patch { + Some(patch) => { + self.major == ver.major && minor == ver.minor && + (ver.patch > patch || (ver.patch == patch && self.pre_is_compatible(ver))) + } + None => self.major == ver.major && minor == ver.minor, + } + } + + // see https://www.npmjs.org/doc/misc/semver.html for behavior + fn is_compatible(&self, ver: &Version) -> bool { + if self.major != ver.major { + return false; + } + + let minor = match self.minor { + Some(n) => n, + None => return self.major == ver.major, + }; + + match self.patch { + Some(patch) => { + if self.major == 0 { + if minor == 0 { + ver.minor == minor && ver.patch == patch && self.pre_is_compatible(ver) + } else { + ver.minor == minor && + (ver.patch > patch || (ver.patch == patch && self.pre_is_compatible(ver))) + } + } else { + ver.minor > minor || + (ver.minor == minor && + (ver.patch > patch || (ver.patch == patch && self.pre_is_compatible(ver)))) + } + } + None => { + if self.major == 0 { + ver.minor == minor + } else { + ver.minor >= minor + } + } + } + } + + fn pre_is_compatible(&self, ver: &Version) -> bool { + ver.pre.is_empty() || ver.pre >= self.pre + } + + // see https://www.npmjs.org/doc/misc/semver.html for behavior + fn matches_wildcard(&self, ver: &Version) -> bool { + match self.op { + Wildcard(Major) => true, + Wildcard(Minor) => self.major == ver.major, + Wildcard(Patch) => { + match self.minor { + Some(minor) => self.major == ver.major && minor == ver.minor, + None => { + // minor and patch version astericks mean match on major + self.major == ver.major + } + } + } + _ => false, // unreachable + } + } +} + +impl fmt::Display for VersionReq { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + if self.predicates.is_empty() { + try!(write!(fmt, "*")); + } else { + for (i, ref pred) in self.predicates.iter().enumerate() { + if i == 0 { + try!(write!(fmt, "{}", pred)); + } else { + try!(write!(fmt, ", {}", pred)); + } + } + } + + Ok(()) + } +} + +impl fmt::Display for Predicate { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + match self.op { + Wildcard(Major) => try!(write!(fmt, "*")), + Wildcard(Minor) => try!(write!(fmt, "{}.*", self.major)), + Wildcard(Patch) => { + if let Some(minor) = self.minor { + try!(write!(fmt, "{}.{}.*", self.major, minor)) + } else { + try!(write!(fmt, "{}.*.*", self.major)) + } + } + _ => { + try!(write!(fmt, "{}{}", self.op, self.major)); + + match self.minor { + Some(v) => try!(write!(fmt, ".{}", v)), + None => (), + } + + match self.patch { + Some(v) => try!(write!(fmt, ".{}", v)), + None => (), + } + + if !self.pre.is_empty() { + try!(write!(fmt, "-")); + for (i, x) in self.pre.iter().enumerate() { + if i != 0 { + try!(write!(fmt, ".")) + } + try!(write!(fmt, "{}", x)); + } + } + } + } + + Ok(()) + } +} + +impl fmt::Display for Op { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + match *self { + Ex => try!(write!(fmt, "= ")), + Gt => try!(write!(fmt, "> ")), + GtEq => try!(write!(fmt, ">= ")), + Lt => try!(write!(fmt, "< ")), + LtEq => try!(write!(fmt, "<= ")), + Tilde => try!(write!(fmt, "~")), + Compatible => try!(write!(fmt, "^")), + // gets handled specially in Predicate::fmt + Wildcard(_) => try!(write!(fmt, "")), + } + Ok(()) + } +} + +#[cfg(test)] +mod test { + use super::{VersionReq, Op}; + use super::super::version::Version; + use std::hash::{Hash, Hasher}; + + fn req(s: &str) -> VersionReq { + VersionReq::parse(s).unwrap() + } + + fn version(s: &str) -> Version { + match Version::parse(s) { + Ok(v) => v, + Err(e) => panic!("`{}` is not a valid version. Reason: {:?}", s, e), + } + } + + fn assert_match(req: &VersionReq, vers: &[&str]) { + for ver in vers.iter() { + assert!(req.matches(&version(*ver)), "did not match {}", ver); + } + } + + fn assert_not_match(req: &VersionReq, vers: &[&str]) { + for ver in vers.iter() { + assert!(!req.matches(&version(*ver)), "matched {}", ver); + } + } + + fn calculate_hash<T: Hash>(t: T) -> u64 { + use std::collections::hash_map::DefaultHasher; + + let mut s = DefaultHasher::new(); + t.hash(&mut s); + s.finish() + } + + #[test] + fn test_parsing_default() { + let r = req("1.0.0"); + + assert_eq!(r.to_string(), "^1.0.0".to_string()); + + assert_match(&r, &["1.0.0", "1.0.1"]); + assert_not_match(&r, &["0.9.9", "0.10.0", "0.1.0"]); + } + + #[test] + fn test_parsing_exact() { + let r = req("=1.0.0"); + + assert!(r.to_string() == "= 1.0.0".to_string()); + assert_eq!(r.to_string(), "= 1.0.0".to_string()); + + assert_match(&r, &["1.0.0"]); + assert_not_match(&r, &["1.0.1", "0.9.9", "0.10.0", "0.1.0", "1.0.0-pre"]); + + let r = req("=0.9.0"); + + assert_eq!(r.to_string(), "= 0.9.0".to_string()); + + assert_match(&r, &["0.9.0"]); + assert_not_match(&r, &["0.9.1", "1.9.0", "0.0.9"]); + + let r = req("=0.1.0-beta2.a"); + + assert_eq!(r.to_string(), "= 0.1.0-beta2.a".to_string()); + + assert_match(&r, &["0.1.0-beta2.a"]); + assert_not_match(&r, &["0.9.1", "0.1.0", "0.1.1-beta2.a", "0.1.0-beta2"]); + } + + #[test] + fn test_parse_metadata_see_issue_88_see_issue_88() { + for op in &[Op::Compatible, Op::Ex, Op::Gt, Op::GtEq, Op::Lt, Op::LtEq, Op::Tilde] { + req(&format!("{} 1.2.3+meta", op)); + } + } + + #[test] + pub fn test_parsing_greater_than() { + let r = req(">= 1.0.0"); + + assert_eq!(r.to_string(), ">= 1.0.0".to_string()); + + assert_match(&r, &["1.0.0", "2.0.0"]); + assert_not_match(&r, &["0.1.0", "0.0.1", "1.0.0-pre", "2.0.0-pre"]); + + let r = req(">= 2.1.0-alpha2"); + + assert_match(&r, &["2.1.0-alpha2", "2.1.0-alpha3", "2.1.0", "3.0.0"]); + assert_not_match(&r, + &["2.0.0", "2.1.0-alpha1", "2.0.0-alpha2", "3.0.0-alpha2"]); + } + + #[test] + pub fn test_parsing_less_than() { + let r = req("< 1.0.0"); + + assert_eq!(r.to_string(), "< 1.0.0".to_string()); + + assert_match(&r, &["0.1.0", "0.0.1"]); + assert_not_match(&r, &["1.0.0", "1.0.0-beta", "1.0.1", "0.9.9-alpha"]); + + let r = req("<= 2.1.0-alpha2"); + + assert_match(&r, &["2.1.0-alpha2", "2.1.0-alpha1", "2.0.0", "1.0.0"]); + assert_not_match(&r, + &["2.1.0", "2.2.0-alpha1", "2.0.0-alpha2", "1.0.0-alpha2"]); + } + + #[test] + pub fn test_multiple() { + let r = req("> 0.0.9, <= 2.5.3"); + assert_eq!(r.to_string(), "> 0.0.9, <= 2.5.3".to_string()); + assert_match(&r, &["0.0.10", "1.0.0", "2.5.3"]); + assert_not_match(&r, &["0.0.8", "2.5.4"]); + + let r = req("0.3.0, 0.4.0"); + assert_eq!(r.to_string(), "^0.3.0, ^0.4.0".to_string()); + assert_not_match(&r, &["0.0.8", "0.3.0", "0.4.0"]); + + let r = req("<= 0.2.0, >= 0.5.0"); + assert_eq!(r.to_string(), "<= 0.2.0, >= 0.5.0".to_string()); + assert_not_match(&r, &["0.0.8", "0.3.0", "0.5.1"]); + + let r = req("0.1.0, 0.1.4, 0.1.6"); + assert_eq!(r.to_string(), "^0.1.0, ^0.1.4, ^0.1.6".to_string()); + assert_match(&r, &["0.1.6", "0.1.9"]); + assert_not_match(&r, &["0.1.0", "0.1.4", "0.2.0"]); + + assert!(VersionReq::parse("> 0.1.0,").is_err()); + assert!(VersionReq::parse("> 0.3.0, ,").is_err()); + + let r = req(">=0.5.1-alpha3, <0.6"); + assert_eq!(r.to_string(), ">= 0.5.1-alpha3, < 0.6".to_string()); + assert_match(&r, + &["0.5.1-alpha3", "0.5.1-alpha4", "0.5.1-beta", "0.5.1", "0.5.5"]); + assert_not_match(&r, + &["0.5.1-alpha1", "0.5.2-alpha3", "0.5.5-pre", "0.5.0-pre"]); + assert_not_match(&r, &["0.6.0", "0.6.0-pre"]); + } + + #[test] + pub fn test_parsing_tilde() { + let r = req("~1"); + assert_match(&r, &["1.0.0", "1.0.1", "1.1.1"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "0.0.9"]); + + let r = req("~1.2"); + assert_match(&r, &["1.2.0", "1.2.1"]); + assert_not_match(&r, &["1.1.1", "1.3.0", "0.0.9"]); + + let r = req("~1.2.2"); + assert_match(&r, &["1.2.2", "1.2.4"]); + assert_not_match(&r, &["1.2.1", "1.9.0", "1.0.9", "2.0.1", "0.1.3"]); + + let r = req("~1.2.3-beta.2"); + assert_match(&r, &["1.2.3", "1.2.4", "1.2.3-beta.2", "1.2.3-beta.4"]); + assert_not_match(&r, &["1.3.3", "1.1.4", "1.2.3-beta.1", "1.2.4-beta.2"]); + } + + #[test] + pub fn test_parsing_compatible() { + let r = req("^1"); + assert_match(&r, &["1.1.2", "1.1.0", "1.2.1", "1.0.1"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "0.1.4"]); + assert_not_match(&r, &["1.0.0-beta1", "0.1.0-alpha", "1.0.1-pre"]); + + let r = req("^1.1"); + assert_match(&r, &["1.1.2", "1.1.0", "1.2.1"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "1.0.1", "0.1.4"]); + + let r = req("^1.1.2"); + assert_match(&r, &["1.1.2", "1.1.4", "1.2.1"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.0.1"]); + assert_not_match(&r, &["1.1.2-alpha1", "1.1.3-alpha1", "2.9.0-alpha1"]); + + let r = req("^0.1.2"); + assert_match(&r, &["0.1.2", "0.1.4"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.0.1"]); + assert_not_match(&r, &["0.1.2-beta", "0.1.3-alpha", "0.2.0-pre"]); + + let r = req("^0.5.1-alpha3"); + assert_match(&r, + &["0.5.1-alpha3", "0.5.1-alpha4", "0.5.1-beta", "0.5.1", "0.5.5"]); + assert_not_match(&r, + &["0.5.1-alpha1", "0.5.2-alpha3", "0.5.5-pre", "0.5.0-pre", "0.6.0"]); + + let r = req("^0.0.2"); + assert_match(&r, &["0.0.2"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.0.1", "0.1.4"]); + + let r = req("^0.0"); + assert_match(&r, &["0.0.2", "0.0.0"]); + assert_not_match(&r, &["0.9.1", "2.9.0", "1.1.1", "0.1.4"]); + + let r = req("^0"); + assert_match(&r, &["0.9.1", "0.0.2", "0.0.0"]); + assert_not_match(&r, &["2.9.0", "1.1.1"]); + + let r = req("^1.4.2-beta.5"); + assert_match(&r, + &["1.4.2", "1.4.3", "1.4.2-beta.5", "1.4.2-beta.6", "1.4.2-c"]); + assert_not_match(&r, + &["0.9.9", "2.0.0", "1.4.2-alpha", "1.4.2-beta.4", "1.4.3-beta.5"]); + } + + #[test] + pub fn test_parsing_wildcard() { + let r = req(""); + assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); + assert_not_match(&r, &[]); + let r = req("*"); + assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); + assert_not_match(&r, &[]); + let r = req("x"); + assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); + assert_not_match(&r, &[]); + let r = req("X"); + assert_match(&r, &["0.9.1", "2.9.0", "0.0.9", "1.0.1", "1.1.1"]); + assert_not_match(&r, &[]); + + let r = req("1.*"); + assert_match(&r, &["1.2.0", "1.2.1", "1.1.1", "1.3.0"]); + assert_not_match(&r, &["0.0.9"]); + let r = req("1.x"); + assert_match(&r, &["1.2.0", "1.2.1", "1.1.1", "1.3.0"]); + assert_not_match(&r, &["0.0.9"]); + let r = req("1.X"); + assert_match(&r, &["1.2.0", "1.2.1", "1.1.1", "1.3.0"]); + assert_not_match(&r, &["0.0.9"]); + + let r = req("1.2.*"); + assert_match(&r, &["1.2.0", "1.2.2", "1.2.4"]); + assert_not_match(&r, &["1.9.0", "1.0.9", "2.0.1", "0.1.3"]); + let r = req("1.2.x"); + assert_match(&r, &["1.2.0", "1.2.2", "1.2.4"]); + assert_not_match(&r, &["1.9.0", "1.0.9", "2.0.1", "0.1.3"]); + let r = req("1.2.X"); + assert_match(&r, &["1.2.0", "1.2.2", "1.2.4"]); + assert_not_match(&r, &["1.9.0", "1.0.9", "2.0.1", "0.1.3"]); + } + + #[test] + pub fn test_any() { + let r = VersionReq::any(); + assert_match(&r, &["0.0.1", "0.1.0", "1.0.0"]); + } + + #[test] + pub fn test_pre() { + let r = req("=2.1.1-really.0"); + assert_match(&r, &["2.1.1-really.0"]); + } + + // #[test] + // pub fn test_parse_errors() { + // assert_eq!(Err(InvalidVersionRequirement), VersionReq::parse("\0")); + // assert_eq!(Err(OpAlreadySet), VersionReq::parse(">= >= 0.0.2")); + // assert_eq!(Err(InvalidSigil), VersionReq::parse(">== 0.0.2")); + // assert_eq!(Err(VersionComponentsMustBeNumeric), + // VersionReq::parse("a.0.0")); + // assert_eq!(Err(InvalidIdentifier), VersionReq::parse("1.0.0-")); + // assert_eq!(Err(MajorVersionRequired), VersionReq::parse(">=")); + // } + + #[test] + pub fn test_from_str() { + assert_eq!("1.0.0".parse::<VersionReq>().unwrap().to_string(), + "^1.0.0".to_string()); + assert_eq!("=1.0.0".parse::<VersionReq>().unwrap().to_string(), + "= 1.0.0".to_string()); + assert_eq!("~1".parse::<VersionReq>().unwrap().to_string(), + "~1".to_string()); + assert_eq!("~1.2".parse::<VersionReq>().unwrap().to_string(), + "~1.2".to_string()); + assert_eq!("^1".parse::<VersionReq>().unwrap().to_string(), + "^1".to_string()); + assert_eq!("^1.1".parse::<VersionReq>().unwrap().to_string(), + "^1.1".to_string()); + assert_eq!("*".parse::<VersionReq>().unwrap().to_string(), + "*".to_string()); + assert_eq!("1.*".parse::<VersionReq>().unwrap().to_string(), + "1.*".to_string()); + assert_eq!("< 1.0.0".parse::<VersionReq>().unwrap().to_string(), + "< 1.0.0".to_string()); + } + + // #[test] + // pub fn test_from_str_errors() { + // assert_eq!(Err(InvalidVersionRequirement), "\0".parse::<VersionReq>()); + // assert_eq!(Err(OpAlreadySet), ">= >= 0.0.2".parse::<VersionReq>()); + // assert_eq!(Err(InvalidSigil), ">== 0.0.2".parse::<VersionReq>()); + // assert_eq!(Err(VersionComponentsMustBeNumeric), + // "a.0.0".parse::<VersionReq>()); + // assert_eq!(Err(InvalidIdentifier), "1.0.0-".parse::<VersionReq>()); + // assert_eq!(Err(MajorVersionRequired), ">=".parse::<VersionReq>()); + // } + + #[test] + fn test_cargo3202() { + let v = "0.*.*".parse::<VersionReq>().unwrap(); + assert_eq!("0.*.*", format!("{}", v.predicates[0])); + + let v = "0.0.*".parse::<VersionReq>().unwrap(); + assert_eq!("0.0.*", format!("{}", v.predicates[0])); + + let r = req("0.*.*"); + assert_match(&r, &["0.5.0"]); + } + + #[test] + fn test_eq_hash() { + assert!(req("^1") == req("^1")); + assert!(calculate_hash(req("^1")) == calculate_hash(req("^1"))); + assert!(req("^1") != req("^2")); + } + + #[test] + fn test_ordering() { + assert!(req("=1") < req("*")); + assert!(req(">1") < req("*")); + assert!(req(">=1") < req("*")); + assert!(req("<1") < req("*")); + assert!(req("<=1") < req("*")); + assert!(req("~1") < req("*")); + assert!(req("^1") < req("*")); + assert!(req("*") == req("*")); + } +} diff -Nru cargo-0.25.0/vendor/semver-0.9.0/src/version.rs cargo-0.26.0/vendor/semver-0.9.0/src/version.rs --- cargo-0.25.0/vendor/semver-0.9.0/src/version.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.9.0/src/version.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,759 @@ +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The `version` module gives you tools to create and compare SemVer-compliant +//! versions. + +use std::cmp::{self, Ordering}; +use std::fmt; +use std::hash; +use std::error::Error; + +use std::result; +use std::str; + +use semver_parser; + +#[cfg(feature = "serde")] +use serde::ser::{Serialize, Serializer}; +#[cfg(feature = "serde")] +use serde::de::{self, Deserialize, Deserializer, Visitor}; + +/// An identifier in the pre-release or build metadata. +/// +/// See sections 9 and 10 of the spec for more about pre-release identifers and +/// build metadata. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub enum Identifier { + /// An identifier that's solely numbers. + Numeric(u64), + /// An identifier with letters and numbers. + AlphaNumeric(String), +} + +impl From<semver_parser::version::Identifier> for Identifier { + fn from(other: semver_parser::version::Identifier) -> Identifier { + match other { + semver_parser::version::Identifier::Numeric(n) => Identifier::Numeric(n), + semver_parser::version::Identifier::AlphaNumeric(s) => Identifier::AlphaNumeric(s), + } + } +} + +impl fmt::Display for Identifier { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Identifier::Numeric(ref n) => fmt::Display::fmt(n, f), + Identifier::AlphaNumeric(ref s) => fmt::Display::fmt(s, f), + } + } +} + +#[cfg(feature = "serde")] +impl Serialize for Identifier { + fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error> + where S: Serializer + { + // Serialize Identifier as a number or string. + match *self { + Identifier::Numeric(n) => serializer.serialize_u64(n), + Identifier::AlphaNumeric(ref s) => serializer.serialize_str(s), + } + } +} + +#[cfg(feature = "serde")] +impl<'de> Deserialize<'de> for Identifier { + fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error> + where D: Deserializer<'de> + { + struct IdentifierVisitor; + + // Deserialize Identifier from a number or string. + impl<'de> Visitor<'de> for IdentifierVisitor { + type Value = Identifier; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a SemVer pre-release or build identifier") + } + + fn visit_u64<E>(self, numeric: u64) -> result::Result<Self::Value, E> + where E: de::Error + { + Ok(Identifier::Numeric(numeric)) + } + + fn visit_str<E>(self, alphanumeric: &str) -> result::Result<Self::Value, E> + where E: de::Error + { + Ok(Identifier::AlphaNumeric(alphanumeric.to_owned())) + } + } + + deserializer.deserialize_any(IdentifierVisitor) + } +} + +/// Represents a version number conforming to the semantic versioning scheme. +#[derive(Clone, Eq, Debug)] +pub struct Version { + /// The major version, to be incremented on incompatible changes. + pub major: u64, + /// The minor version, to be incremented when functionality is added in a + /// backwards-compatible manner. + pub minor: u64, + /// The patch version, to be incremented when backwards-compatible bug + /// fixes are made. + pub patch: u64, + /// The pre-release version identifier, if one exists. + pub pre: Vec<Identifier>, + /// The build metadata, ignored when determining version precedence. + pub build: Vec<Identifier>, +} + +impl From<semver_parser::version::Version> for Version { + fn from(other: semver_parser::version::Version) -> Version { + Version { + major: other.major, + minor: other.minor, + patch: other.patch, + pre: other.pre.into_iter().map(From::from).collect(), + build: other.build.into_iter().map(From::from).collect(), + } + } +} + +#[cfg(feature = "serde")] +impl Serialize for Version { + fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error> + where S: Serializer + { + // Serialize Version as a string. + serializer.collect_str(self) + } +} + +#[cfg(feature = "serde")] +impl<'de> Deserialize<'de> for Version { + fn deserialize<D>(deserializer: D) -> result::Result<Self, D::Error> + where D: Deserializer<'de> + { + struct VersionVisitor; + + // Deserialize Version from a string. + impl<'de> Visitor<'de> for VersionVisitor { + type Value = Version; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a SemVer version as a string") + } + + fn visit_str<E>(self, v: &str) -> result::Result<Self::Value, E> + where E: de::Error + { + Version::parse(v).map_err(de::Error::custom) + } + } + + deserializer.deserialize_str(VersionVisitor) + } +} + +/// An error type for this crate +/// +/// Currently, just a generic error. Will make this nicer later. +#[derive(Clone,PartialEq,Debug,PartialOrd)] +pub enum SemVerError { + /// An error ocurred while parsing. + ParseError(String), +} + +impl fmt::Display for SemVerError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + &SemVerError::ParseError(ref m) => write!(f, "{}", m), + } + } +} + +impl Error for SemVerError { + fn description(&self) -> &str { + match self { + &SemVerError::ParseError(ref m) => m, + } + } +} + +/// A Result type for errors +pub type Result<T> = result::Result<T, SemVerError>; + +impl Version { + + /// Contructs the simple case without pre or build. + pub fn new(major: u64, minor: u64, patch: u64) -> Version { + Version { + major: major, + minor: minor, + patch: patch, + pre: Vec::new(), + build: Vec::new() + } + } + + /// Parse a string into a semver object. + pub fn parse(version: &str) -> Result<Version> { + let res = semver_parser::version::parse(version); + + match res { + // Convert plain String error into proper ParseError + Err(e) => Err(SemVerError::ParseError(e)), + Ok(v) => Ok(From::from(v)), + } + } + + /// Clears the build metadata + fn clear_metadata(&mut self) { + self.build = Vec::new(); + self.pre = Vec::new(); + } + + /// Increments the patch number for this Version (Must be mutable) + pub fn increment_patch(&mut self) { + self.patch += 1; + self.clear_metadata(); + } + + /// Increments the minor version number for this Version (Must be mutable) + /// + /// As instructed by section 7 of the spec, the patch number is reset to 0. + pub fn increment_minor(&mut self) { + self.minor += 1; + self.patch = 0; + self.clear_metadata(); + } + + /// Increments the major version number for this Version (Must be mutable) + /// + /// As instructed by section 8 of the spec, the minor and patch numbers are + /// reset to 0 + pub fn increment_major(&mut self) { + self.major += 1; + self.minor = 0; + self.patch = 0; + self.clear_metadata(); + } + + /// Checks to see if the current Version is in pre-release status + pub fn is_prerelease(&self) -> bool { + !self.pre.is_empty() + } +} + +impl str::FromStr for Version { + type Err = SemVerError; + + fn from_str(s: &str) -> Result<Version> { + Version::parse(s) + } +} + +impl fmt::Display for Version { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + try!(write!(f, "{}.{}.{}", self.major, self.minor, self.patch)); + if !self.pre.is_empty() { + try!(write!(f, "-")); + for (i, x) in self.pre.iter().enumerate() { + if i != 0 { + try!(write!(f, ".")) + } + try!(write!(f, "{}", x)); + } + } + if !self.build.is_empty() { + try!(write!(f, "+")); + for (i, x) in self.build.iter().enumerate() { + if i != 0 { + try!(write!(f, ".")) + } + try!(write!(f, "{}", x)); + } + } + Ok(()) + } +} + +impl cmp::PartialEq for Version { + #[inline] + fn eq(&self, other: &Version) -> bool { + // We should ignore build metadata here, otherwise versions v1 and v2 + // can exist such that !(v1 < v2) && !(v1 > v2) && v1 != v2, which + // violate strict total ordering rules. + self.major == other.major && self.minor == other.minor && self.patch == other.patch && + self.pre == other.pre + } +} + +impl cmp::PartialOrd for Version { + fn partial_cmp(&self, other: &Version) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl cmp::Ord for Version { + fn cmp(&self, other: &Version) -> Ordering { + match self.major.cmp(&other.major) { + Ordering::Equal => {} + r => return r, + } + + match self.minor.cmp(&other.minor) { + Ordering::Equal => {} + r => return r, + } + + match self.patch.cmp(&other.patch) { + Ordering::Equal => {} + r => return r, + } + + // NB: semver spec says 0.0.0-pre < 0.0.0 + // but the version of ord defined for vec + // says that [] < [pre] so we alter it here + match (self.pre.len(), other.pre.len()) { + (0, 0) => Ordering::Equal, + (0, _) => Ordering::Greater, + (_, 0) => Ordering::Less, + (_, _) => self.pre.cmp(&other.pre), + } + } +} + +impl hash::Hash for Version { + fn hash<H: hash::Hasher>(&self, into: &mut H) { + self.major.hash(into); + self.minor.hash(into); + self.patch.hash(into); + self.pre.hash(into); + } +} + +impl From<(u64,u64,u64)> for Version { + fn from(tuple: (u64,u64,u64)) -> Version { + let (major, minor, patch) = tuple; + Version::new(major, minor, patch) + } +} + +#[cfg(test)] +mod tests { + use std::result; + use super::Version; + use super::Identifier; + use super::SemVerError; + + #[test] + fn test_parse() { + fn parse_error(e: &str) -> result::Result<Version, SemVerError> { + return Err(SemVerError::ParseError(e.to_string())); + } + + assert_eq!(Version::parse(""), + parse_error("Error parsing major identifier")); + assert_eq!(Version::parse(" "), + parse_error("Error parsing major identifier")); + assert_eq!(Version::parse("1"), + parse_error("Expected dot")); + assert_eq!(Version::parse("1.2"), + parse_error("Expected dot")); + assert_eq!(Version::parse("1.2.3-"), + parse_error("Error parsing prerelease")); + assert_eq!(Version::parse("a.b.c"), + parse_error("Error parsing major identifier")); + assert_eq!(Version::parse("1.2.3 abc"), + parse_error("Extra junk after valid version: abc")); + + assert_eq!(Version::parse("1.2.3"), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: Vec::new(), + })); + + assert_eq!(Version::parse("1.2.3"), + Ok(Version::new(1,2,3))); + + assert_eq!(Version::parse(" 1.2.3 "), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: Vec::new(), + })); + assert_eq!(Version::parse("1.2.3-alpha1"), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: Vec::new(), + })); + assert_eq!(Version::parse(" 1.2.3-alpha1 "), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: Vec::new(), + })); + assert_eq!(Version::parse("1.2.3+build5"), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!(Version::parse(" 1.2.3+build5 "), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!(Version::parse("1.2.3-alpha1+build5"), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!(Version::parse(" 1.2.3-alpha1+build5 "), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!(Version::parse("1.2.3-1.alpha1.9+build5.7.3aedf "), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::Numeric(1), + Identifier::AlphaNumeric(String::from("alpha1")), + Identifier::Numeric(9), + ], + build: vec![Identifier::AlphaNumeric(String::from("build5")), + Identifier::Numeric(7), + Identifier::AlphaNumeric(String::from("3aedf")), + ], + })); + assert_eq!(Version::parse("0.4.0-beta.1+0851523"), + Ok(Version { + major: 0, + minor: 4, + patch: 0, + pre: vec![Identifier::AlphaNumeric(String::from("beta")), + Identifier::Numeric(1), + ], + build: vec![Identifier::AlphaNumeric(String::from("0851523"))], + })); + + } + + #[test] + fn test_increment_patch() { + let mut buggy_release = Version::parse("0.1.0").unwrap(); + buggy_release.increment_patch(); + assert_eq!(buggy_release, Version::parse("0.1.1").unwrap()); + } + + #[test] + fn test_increment_minor() { + let mut feature_release = Version::parse("1.4.6").unwrap(); + feature_release.increment_minor(); + assert_eq!(feature_release, Version::parse("1.5.0").unwrap()); + } + + #[test] + fn test_increment_major() { + let mut chrome_release = Version::parse("46.1.246773").unwrap(); + chrome_release.increment_major(); + assert_eq!(chrome_release, Version::parse("47.0.0").unwrap()); + } + + #[test] + fn test_increment_keep_prerelease() { + let mut release = Version::parse("1.0.0-alpha").unwrap(); + release.increment_patch(); + + assert_eq!(release, Version::parse("1.0.1").unwrap()); + + release.increment_minor(); + + assert_eq!(release, Version::parse("1.1.0").unwrap()); + + release.increment_major(); + + assert_eq!(release, Version::parse("2.0.0").unwrap()); + } + + + #[test] + fn test_increment_clear_metadata() { + let mut release = Version::parse("1.0.0+4442").unwrap(); + release.increment_patch(); + + assert_eq!(release, Version::parse("1.0.1").unwrap()); + release = Version::parse("1.0.1+hello").unwrap(); + + release.increment_minor(); + + assert_eq!(release, Version::parse("1.1.0").unwrap()); + release = Version::parse("1.1.3747+hello").unwrap(); + + release.increment_major(); + + assert_eq!(release, Version::parse("2.0.0").unwrap()); + } + + #[test] + fn test_eq() { + assert_eq!(Version::parse("1.2.3"), Version::parse("1.2.3")); + assert_eq!(Version::parse("1.2.3-alpha1"), + Version::parse("1.2.3-alpha1")); + assert_eq!(Version::parse("1.2.3+build.42"), + Version::parse("1.2.3+build.42")); + assert_eq!(Version::parse("1.2.3-alpha1+42"), + Version::parse("1.2.3-alpha1+42")); + assert_eq!(Version::parse("1.2.3+23"), Version::parse("1.2.3+42")); + } + + #[test] + fn test_ne() { + assert!(Version::parse("0.0.0") != Version::parse("0.0.1")); + assert!(Version::parse("0.0.0") != Version::parse("0.1.0")); + assert!(Version::parse("0.0.0") != Version::parse("1.0.0")); + assert!(Version::parse("1.2.3-alpha") != Version::parse("1.2.3-beta")); + } + + #[test] + fn test_show() { + assert_eq!(format!("{}", Version::parse("1.2.3").unwrap()), + "1.2.3".to_string()); + assert_eq!(format!("{}", Version::parse("1.2.3-alpha1").unwrap()), + "1.2.3-alpha1".to_string()); + assert_eq!(format!("{}", Version::parse("1.2.3+build.42").unwrap()), + "1.2.3+build.42".to_string()); + assert_eq!(format!("{}", Version::parse("1.2.3-alpha1+42").unwrap()), + "1.2.3-alpha1+42".to_string()); + } + + #[test] + fn test_to_string() { + assert_eq!(Version::parse("1.2.3").unwrap().to_string(), + "1.2.3".to_string()); + assert_eq!(Version::parse("1.2.3-alpha1").unwrap().to_string(), + "1.2.3-alpha1".to_string()); + assert_eq!(Version::parse("1.2.3+build.42").unwrap().to_string(), + "1.2.3+build.42".to_string()); + assert_eq!(Version::parse("1.2.3-alpha1+42").unwrap().to_string(), + "1.2.3-alpha1+42".to_string()); + } + + #[test] + fn test_lt() { + assert!(Version::parse("0.0.0") < Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.0.0") < Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.0") < Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.3-alpha1") < Version::parse("1.2.3")); + assert!(Version::parse("1.2.3-alpha1") < Version::parse("1.2.3-alpha2")); + assert!(!(Version::parse("1.2.3-alpha2") < Version::parse("1.2.3-alpha2"))); + assert!(!(Version::parse("1.2.3+23") < Version::parse("1.2.3+42"))); + } + + #[test] + fn test_le() { + assert!(Version::parse("0.0.0") <= Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.0.0") <= Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.0") <= Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.3-alpha1") <= Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.3-alpha2") <= Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.3+23") <= Version::parse("1.2.3+42")); + } + + #[test] + fn test_gt() { + assert!(Version::parse("1.2.3-alpha2") > Version::parse("0.0.0")); + assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.0.0")); + assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.0")); + assert!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.3-alpha1")); + assert!(Version::parse("1.2.3") > Version::parse("1.2.3-alpha2")); + assert!(!(Version::parse("1.2.3-alpha2") > Version::parse("1.2.3-alpha2"))); + assert!(!(Version::parse("1.2.3+23") > Version::parse("1.2.3+42"))); + } + + #[test] + fn test_ge() { + assert!(Version::parse("1.2.3-alpha2") >= Version::parse("0.0.0")); + assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.0.0")); + assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.0")); + assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.3-alpha1")); + assert!(Version::parse("1.2.3-alpha2") >= Version::parse("1.2.3-alpha2")); + assert!(Version::parse("1.2.3+23") >= Version::parse("1.2.3+42")); + } + + #[test] + fn test_prerelease_check() { + assert!(Version::parse("1.0.0").unwrap().is_prerelease() == false); + assert!(Version::parse("0.0.1").unwrap().is_prerelease() == false); + assert!(Version::parse("4.1.4-alpha").unwrap().is_prerelease()); + assert!(Version::parse("1.0.0-beta294296").unwrap().is_prerelease()); + } + + #[test] + fn test_spec_order() { + let vs = ["1.0.0-alpha", + "1.0.0-alpha.1", + "1.0.0-alpha.beta", + "1.0.0-beta", + "1.0.0-beta.2", + "1.0.0-beta.11", + "1.0.0-rc.1", + "1.0.0"]; + let mut i = 1; + while i < vs.len() { + let a = Version::parse(vs[i - 1]); + let b = Version::parse(vs[i]); + assert!(a < b, "nope {:?} < {:?}", a, b); + i += 1; + } + } + + #[test] + fn test_from_str() { + assert_eq!("1.2.3".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: Vec::new(), + })); + assert_eq!(" 1.2.3 ".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: Vec::new(), + })); + assert_eq!("1.2.3-alpha1".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: Vec::new(), + })); + assert_eq!(" 1.2.3-alpha1 ".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: Vec::new(), + })); + assert_eq!("1.2.3+build5".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!(" 1.2.3+build5 ".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: Vec::new(), + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!("1.2.3-alpha1+build5".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!(" 1.2.3-alpha1+build5 ".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::AlphaNumeric(String::from("alpha1"))], + build: vec![Identifier::AlphaNumeric(String::from("build5"))], + })); + assert_eq!("1.2.3-1.alpha1.9+build5.7.3aedf ".parse(), + Ok(Version { + major: 1, + minor: 2, + patch: 3, + pre: vec![Identifier::Numeric(1), + Identifier::AlphaNumeric(String::from("alpha1")), + Identifier::Numeric(9), + ], + build: vec![Identifier::AlphaNumeric(String::from("build5")), + Identifier::Numeric(7), + Identifier::AlphaNumeric(String::from("3aedf")), + ], + })); + assert_eq!("0.4.0-beta.1+0851523".parse(), + Ok(Version { + major: 0, + minor: 4, + patch: 0, + pre: vec![Identifier::AlphaNumeric(String::from("beta")), + Identifier::Numeric(1), + ], + build: vec![Identifier::AlphaNumeric(String::from("0851523"))], + })); + + } + + #[test] + fn test_from_str_errors() { + fn parse_error(e: &str) -> result::Result<Version, SemVerError> { + return Err(SemVerError::ParseError(e.to_string())); + } + + assert_eq!("".parse(), parse_error("Error parsing major identifier")); + assert_eq!(" ".parse(), parse_error("Error parsing major identifier")); + assert_eq!("1".parse(), parse_error("Expected dot")); + assert_eq!("1.2".parse(), + parse_error("Expected dot")); + assert_eq!("1.2.3-".parse(), + parse_error("Error parsing prerelease")); + assert_eq!("a.b.c".parse(), + parse_error("Error parsing major identifier")); + assert_eq!("1.2.3 abc".parse(), + parse_error("Extra junk after valid version: abc")); + } +} diff -Nru cargo-0.25.0/vendor/semver-0.9.0/tests/deprecation.rs cargo-0.26.0/vendor/semver-0.9.0/tests/deprecation.rs --- cargo-0.25.0/vendor/semver-0.9.0/tests/deprecation.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.9.0/tests/deprecation.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,22 @@ +extern crate semver; + +#[test] +fn test_regressions() { + use semver::VersionReq; + use semver::ReqParseError; + + let versions = vec![ + (".*", VersionReq::any()), + ("0.1.0.", VersionReq::parse("0.1.0").unwrap()), + ("0.3.1.3", VersionReq::parse("0.3.13").unwrap()), + ("0.2*", VersionReq::parse("0.2.*").unwrap()), + ("*.0", VersionReq::any()), + ]; + + for (version, requirement) in versions.into_iter() { + let parsed = VersionReq::parse(version); + let error = parsed.err().unwrap(); + + assert_eq!(ReqParseError::DeprecatedVersionRequirement(requirement), error); + } +} diff -Nru cargo-0.25.0/vendor/semver-0.9.0/tests/regression.rs cargo-0.26.0/vendor/semver-0.9.0/tests/regression.rs --- cargo-0.25.0/vendor/semver-0.9.0/tests/regression.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.9.0/tests/regression.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +extern crate semver; +extern crate crates_index; +extern crate tempdir; + +// This test checks to see if every existing crate parses successfully. Important to not break the +// Rust universe! + +#[cfg(feature = "ci")] +#[test] +fn test_regressions() { + use tempdir::TempDir; + use crates_index::Index; + use semver::Version; + + let dir = TempDir::new("semver").unwrap(); + let index = Index::new(dir.into_path()); + index.clone().unwrap(); + + for krate in index.crates() { + for version in krate.versions() { + let v = version.version(); + assert!(Version::parse(v).is_ok(), "failed: {} ({})", version.name(), v); + } + } +} diff -Nru cargo-0.25.0/vendor/semver-0.9.0/tests/serde.rs cargo-0.26.0/vendor/semver-0.9.0/tests/serde.rs --- cargo-0.25.0/vendor/semver-0.9.0/tests/serde.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.9.0/tests/serde.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,90 @@ +#![cfg(feature = "serde")] + +#[macro_use] +extern crate serde_derive; + +extern crate semver; +extern crate serde_json; + +use semver::{Identifier, Version, VersionReq}; + +#[derive(Serialize, Deserialize, PartialEq, Debug)] +struct Identified { + name: String, + identifier: Identifier, +} + +#[derive(Serialize, Deserialize, PartialEq, Debug)] +struct Versioned { + name: String, + vers: Version, +} + +#[test] +fn serialize_identifier() { + let id = Identified { + name: "serde".to_owned(), + identifier: Identifier::Numeric(100), + }; + let j = serde_json::to_string(&id).unwrap(); + assert_eq!(j, r#"{"name":"serde","identifier":100}"#); + + let id = Identified { + name: "serde".to_owned(), + identifier: Identifier::AlphaNumeric("b100".to_owned()), + }; + let j = serde_json::to_string(&id).unwrap(); + assert_eq!(j, r#"{"name":"serde","identifier":"b100"}"#); +} + +#[test] +fn deserialize_identifier() { + let j = r#"{"name":"serde","identifier":100}"#; + let id = serde_json::from_str::<Identified>(j).unwrap(); + let expected = Identified { + name: "serde".to_owned(), + identifier: Identifier::Numeric(100), + }; + assert_eq!(id, expected); + + let j = r#"{"name":"serde","identifier":"b100"}"#; + let id = serde_json::from_str::<Identified>(j).unwrap(); + let expected = Identified { + name: "serde".to_owned(), + identifier: Identifier::AlphaNumeric("b100".to_owned()), + }; + assert_eq!(id, expected); +} + +#[test] +fn serialize_version() { + let v = Versioned { + name: "serde".to_owned(), + vers: Version::parse("1.0.0").unwrap(), + }; + let j = serde_json::to_string(&v).unwrap(); + assert_eq!(j, r#"{"name":"serde","vers":"1.0.0"}"#); +} + +#[test] +fn deserialize_version() { + let j = r#"{"name":"serde","vers":"1.0.0"}"#; + let v = serde_json::from_str::<Versioned>(j).unwrap(); + let expected = Versioned { + name: "serde".to_owned(), + vers: Version::parse("1.0.0").unwrap(), + }; + assert_eq!(v, expected); +} + +#[test] +fn serialize_versionreq() { + let v = VersionReq::exact(&Version::parse("1.0.0").unwrap()); + + assert_eq!(serde_json::to_string(&v).unwrap(), r#""= 1.0.0""#); +} + +#[test] +fn deserialize_versionreq() { + assert_eq!("1.0.0".parse::<VersionReq>().unwrap(), serde_json::from_str(r#""1.0.0""#).unwrap()); +} diff -Nru cargo-0.25.0/vendor/semver-0.9.0/.travis.yml cargo-0.26.0/vendor/semver-0.9.0/.travis.yml --- cargo-0.25.0/vendor/semver-0.9.0/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/semver-0.9.0/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,18 @@ +language: rust +rust: + - nightly + - beta + - stable +sudo: false +script: + - cargo build --verbose + - cargo test --verbose --features ci +addons: + apt: + sources: + - kalakris-cmake + packages: + - cmake +notifications: + email: + on_success: never diff -Nru cargo-0.25.0/vendor/serde-1.0.27/.cargo-checksum.json cargo-0.26.0/vendor/serde-1.0.27/.cargo-checksum.json --- cargo-0.25.0/vendor/serde-1.0.27/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"db99f3919e20faa51bb2996057f5031d8685019b5a06139b1ce761da671b8526"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/serde-1.0.27/Cargo.toml cargo-0.26.0/vendor/serde-1.0.27/Cargo.toml --- cargo-0.25.0/vendor/serde-1.0.27/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,44 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "serde" -version = "1.0.27" -authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"] -include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] -description = "A generic serialization/deserialization framework" -homepage = "https://serde.rs" -documentation = "https://docs.serde.rs/serde/" -readme = "README.md" -keywords = ["serde", "serialization", "no_std"] -categories = ["encoding"] -license = "MIT/Apache-2.0" -repository = "https://github.com/serde-rs/serde" -[dependencies.serde_derive] -version = "1.0" -optional = true -[dev-dependencies.serde_derive] -version = "1.0" - -[features] -alloc = ["unstable"] -default = ["std"] -derive = ["serde_derive"] -playground = ["serde_derive"] -rc = [] -std = [] -unstable = [] -[badges.appveyor] -repository = "serde-rs/serde" - -[badges.travis-ci] -repository = "serde-rs/serde" diff -Nru cargo-0.25.0/vendor/serde-1.0.27/LICENSE-APACHE cargo-0.26.0/vendor/serde-1.0.27/LICENSE-APACHE --- cargo-0.25.0/vendor/serde-1.0.27/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/serde-1.0.27/LICENSE-MIT cargo-0.26.0/vendor/serde-1.0.27/LICENSE-MIT --- cargo-0.25.0/vendor/serde-1.0.27/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/serde-1.0.27/README.md cargo-0.26.0/vendor/serde-1.0.27/README.md --- cargo-0.25.0/vendor/serde-1.0.27/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,102 +0,0 @@ -# Serde   [![Build Status]][travis] [![Latest Version]][crates.io] - -[Build Status]: https://api.travis-ci.org/serde-rs/serde.svg?branch=master -[travis]: https://travis-ci.org/serde-rs/serde -[Latest Version]: https://img.shields.io/crates/v/serde.svg -[crates.io]: https://crates.io/crates/serde - -**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** - ---- - -You may be looking for: - -- [An overview of Serde](https://serde.rs/) -- [Data formats supported by Serde](https://serde.rs/#data-formats) -- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html) -- [Examples](https://serde.rs/examples.html) -- [API documentation](https://docs.serde.rs/serde/) -- [Release notes](https://github.com/serde-rs/serde/releases) - -## Serde in action - -<details> -<summary> -Click to show Cargo.toml. -<a href="http://play.integer32.com/?gist=9003c5b88c1f4989941925d7190c6eec" target="_blank">Run this code in the playground.</a> -</summary> - -```toml -[dependencies] - -# The core APIs, including the Serialize and Deserialize traits. Always -# required when using Serde. -serde = "1.0" - -# Support for #[derive(Serialize, Deserialize)]. Required if you want Serde -# to work for structs and enums defined in your crate. -serde_derive = "1.0" - -# Each data format lives in its own crate; the sample code below uses JSON -# but you may be using a different one. -serde_json = "1.0" -``` - -</details> -<p></p> - -```rust -#[macro_use] -extern crate serde_derive; - -extern crate serde; -extern crate serde_json; - -#[derive(Serialize, Deserialize, Debug)] -struct Point { - x: i32, - y: i32, -} - -fn main() { - let point = Point { x: 1, y: 2 }; - - // Convert the Point to a JSON string. - let serialized = serde_json::to_string(&point).unwrap(); - - // Prints serialized = {"x":1,"y":2} - println!("serialized = {}", serialized); - - // Convert the JSON string back to a Point. - let deserialized: Point = serde_json::from_str(&serialized).unwrap(); - - // Prints deserialized = Point { x: 1, y: 2 } - println!("deserialized = {:?}", deserialized); -} -``` - -## Getting help - -Serde developers live in the #serde channel on -[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a -good resource with generally faster response time but less specific knowledge -about Serde. If IRC is not your thing or you don't get a good response, we are -happy to respond to [GitHub issues](https://github.com/serde-rs/serde/issues/new) -as well. - -## License - -Serde is 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 Serde by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/de/from_primitive.rs cargo-0.26.0/vendor/serde-1.0.27/src/de/from_primitive.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/de/from_primitive.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/de/from_primitive.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,116 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use lib::*; - -macro_rules! int_to_int { - ($dst:ident, $n:ident) => ( - if $dst::MIN as i64 <= $n as i64 && $n as i64 <= $dst::MAX as i64 { - Some($n as $dst) - } else { - None - } - ) -} - -macro_rules! int_to_uint { - ($dst:ident, $n:ident) => ( - if 0 <= $n && $n as u64 <= $dst::MAX as u64 { - Some($n as $dst) - } else { - None - } - ) -} - -macro_rules! uint_to { - ($dst:ident, $n:ident) => ( - if $n as u64 <= $dst::MAX as u64 { - Some($n as $dst) - } else { - None - } - ) -} - -pub trait FromPrimitive: Sized { - fn from_isize(n: isize) -> Option<Self>; - fn from_i8(n: i8) -> Option<Self>; - fn from_i16(n: i16) -> Option<Self>; - fn from_i32(n: i32) -> Option<Self>; - fn from_i64(n: i64) -> Option<Self>; - fn from_usize(n: usize) -> Option<Self>; - fn from_u8(n: u8) -> Option<Self>; - fn from_u16(n: u16) -> Option<Self>; - fn from_u32(n: u32) -> Option<Self>; - fn from_u64(n: u64) -> Option<Self>; -} - -macro_rules! impl_from_primitive_for_int { - ($t:ident) => ( - impl FromPrimitive for $t { - #[inline] fn from_isize(n: isize) -> Option<Self> { int_to_int!($t, n) } - #[inline] fn from_i8(n: i8) -> Option<Self> { int_to_int!($t, n) } - #[inline] fn from_i16(n: i16) -> Option<Self> { int_to_int!($t, n) } - #[inline] fn from_i32(n: i32) -> Option<Self> { int_to_int!($t, n) } - #[inline] fn from_i64(n: i64) -> Option<Self> { int_to_int!($t, n) } - #[inline] fn from_usize(n: usize) -> Option<Self> { uint_to!($t, n) } - #[inline] fn from_u8(n: u8) -> Option<Self> { uint_to!($t, n) } - #[inline] fn from_u16(n: u16) -> Option<Self> { uint_to!($t, n) } - #[inline] fn from_u32(n: u32) -> Option<Self> { uint_to!($t, n) } - #[inline] fn from_u64(n: u64) -> Option<Self> { uint_to!($t, n) } - } - ) -} - -macro_rules! impl_from_primitive_for_uint { - ($t:ident) => ( - impl FromPrimitive for $t { - #[inline] fn from_isize(n: isize) -> Option<Self> { int_to_uint!($t, n) } - #[inline] fn from_i8(n: i8) -> Option<Self> { int_to_uint!($t, n) } - #[inline] fn from_i16(n: i16) -> Option<Self> { int_to_uint!($t, n) } - #[inline] fn from_i32(n: i32) -> Option<Self> { int_to_uint!($t, n) } - #[inline] fn from_i64(n: i64) -> Option<Self> { int_to_uint!($t, n) } - #[inline] fn from_usize(n: usize) -> Option<Self> { uint_to!($t, n) } - #[inline] fn from_u8(n: u8) -> Option<Self> { uint_to!($t, n) } - #[inline] fn from_u16(n: u16) -> Option<Self> { uint_to!($t, n) } - #[inline] fn from_u32(n: u32) -> Option<Self> { uint_to!($t, n) } - #[inline] fn from_u64(n: u64) -> Option<Self> { uint_to!($t, n) } - } - ) -} - -macro_rules! impl_from_primitive_for_float { - ($t:ident) => ( - impl FromPrimitive for $t { - #[inline] fn from_isize(n: isize) -> Option<Self> { Some(n as Self) } - #[inline] fn from_i8(n: i8) -> Option<Self> { Some(n as Self) } - #[inline] fn from_i16(n: i16) -> Option<Self> { Some(n as Self) } - #[inline] fn from_i32(n: i32) -> Option<Self> { Some(n as Self) } - #[inline] fn from_i64(n: i64) -> Option<Self> { Some(n as Self) } - #[inline] fn from_usize(n: usize) -> Option<Self> { Some(n as Self) } - #[inline] fn from_u8(n: u8) -> Option<Self> { Some(n as Self) } - #[inline] fn from_u16(n: u16) -> Option<Self> { Some(n as Self) } - #[inline] fn from_u32(n: u32) -> Option<Self> { Some(n as Self) } - #[inline] fn from_u64(n: u64) -> Option<Self> { Some(n as Self) } - } - ) -} - -impl_from_primitive_for_int!(isize); -impl_from_primitive_for_int!(i8); -impl_from_primitive_for_int!(i16); -impl_from_primitive_for_int!(i32); -impl_from_primitive_for_int!(i64); -impl_from_primitive_for_uint!(usize); -impl_from_primitive_for_uint!(u8); -impl_from_primitive_for_uint!(u16); -impl_from_primitive_for_uint!(u32); -impl_from_primitive_for_uint!(u64); -impl_from_primitive_for_float!(f32); -impl_from_primitive_for_float!(f64); diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/de/ignored_any.rs cargo-0.26.0/vendor/serde-1.0.27/src/de/ignored_any.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/de/ignored_any.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/de/ignored_any.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,215 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use lib::*; - -use de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; - -/// An efficient way of discarding data from a deserializer. -/// -/// Think of this like `serde_json::Value` in that it can be deserialized from -/// any type, except that it does not store any information about the data that -/// gets deserialized. -/// -/// ```rust -/// use std::fmt; -/// use std::marker::PhantomData; -/// -/// use serde::de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqAccess, IgnoredAny}; -/// -/// /// A seed that can be used to deserialize only the `n`th element of a sequence -/// /// while efficiently discarding elements of any type before or after index `n`. -/// /// -/// /// For example to deserialize only the element at index 3: -/// /// -/// /// ```rust -/// /// NthElement::new(3).deserialize(deserializer) -/// /// ``` -/// pub struct NthElement<T> { -/// n: usize, -/// marker: PhantomData<T>, -/// } -/// -/// impl<T> NthElement<T> { -/// pub fn new(n: usize) -> Self { -/// NthElement { -/// n: n, -/// marker: PhantomData, -/// } -/// } -/// } -/// -/// impl<'de, T> Visitor<'de> for NthElement<T> -/// where T: Deserialize<'de> -/// { -/// type Value = T; -/// -/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { -/// write!(formatter, "a sequence in which we care about element {}", self.n) -/// } -/// -/// fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> -/// where A: SeqAccess<'de> -/// { -/// // Skip over the first `n` elements. -/// for i in 0..self.n { -/// // It is an error if the sequence ends before we get to element `n`. -/// if seq.next_element::<IgnoredAny>()?.is_none() { -/// return Err(de::Error::invalid_length(i, &self)); -/// } -/// } -/// -/// // Deserialize the one we care about. -/// let nth = match seq.next_element()? { -/// Some(nth) => nth, -/// None => { -/// return Err(de::Error::invalid_length(self.n, &self)); -/// } -/// }; -/// -/// // Skip over any remaining elements in the sequence after `n`. -/// while let Some(IgnoredAny) = seq.next_element()? { -/// // ignore -/// } -/// -/// Ok(nth) -/// } -/// } -/// -/// impl<'de, T> DeserializeSeed<'de> for NthElement<T> -/// where T: Deserialize<'de> -/// { -/// type Value = T; -/// -/// fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> -/// where D: Deserializer<'de> -/// { -/// deserializer.deserialize_seq(self) -/// } -/// } -/// -/// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error> -/// # where D: Deserializer<'de> -/// # { -/// // Deserialize only the sequence element at index 3 from this deserializer. -/// // The element at index 3 is required to be a string. Elements before and -/// // after index 3 are allowed to be of any type. -/// let s: String = NthElement::new(3).deserialize(deserializer)?; -/// # Ok(()) -/// # } -/// ``` -#[derive(Copy, Clone, Debug, Default)] -pub struct IgnoredAny; - -impl<'de> Visitor<'de> for IgnoredAny { - type Value = IgnoredAny; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("anything at all") - } - - #[inline] - fn visit_bool<E>(self, x: bool) -> Result<Self::Value, E> { - let _ = x; - Ok(IgnoredAny) - } - - #[inline] - fn visit_i64<E>(self, x: i64) -> Result<Self::Value, E> { - let _ = x; - Ok(IgnoredAny) - } - - #[inline] - fn visit_u64<E>(self, x: u64) -> Result<Self::Value, E> { - let _ = x; - Ok(IgnoredAny) - } - - #[inline] - fn visit_f64<E>(self, x: f64) -> Result<Self::Value, E> { - let _ = x; - Ok(IgnoredAny) - } - - #[inline] - fn visit_str<E>(self, s: &str) -> Result<Self::Value, E> - where - E: Error, - { - let _ = s; - Ok(IgnoredAny) - } - - #[inline] - fn visit_none<E>(self) -> Result<Self::Value, E> { - Ok(IgnoredAny) - } - - #[inline] - fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - IgnoredAny::deserialize(deserializer) - } - - #[inline] - fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - IgnoredAny::deserialize(deserializer) - } - - #[inline] - fn visit_unit<E>(self) -> Result<Self::Value, E> { - Ok(IgnoredAny) - } - - #[inline] - fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> - where - A: SeqAccess<'de>, - { - while let Some(IgnoredAny) = try!(seq.next_element()) { - // Gobble - } - Ok(IgnoredAny) - } - - #[inline] - fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> - where - A: MapAccess<'de>, - { - while let Some((IgnoredAny, IgnoredAny)) = try!(map.next_entry()) { - // Gobble - } - Ok(IgnoredAny) - } - - #[inline] - fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E> - where - E: Error, - { - let _ = bytes; - Ok(IgnoredAny) - } -} - -impl<'de> Deserialize<'de> for IgnoredAny { - #[inline] - fn deserialize<D>(deserializer: D) -> Result<IgnoredAny, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_ignored_any(IgnoredAny) - } -} diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/de/impls.rs cargo-0.26.0/vendor/serde-1.0.27/src/de/impls.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/de/impls.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/de/impls.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2061 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use lib::*; - -use de::{Deserialize, Deserializer, EnumAccess, Error, SeqAccess, Unexpected, VariantAccess, - Visitor}; - -#[cfg(any(feature = "std", feature = "alloc"))] -use de::MapAccess; - -use de::from_primitive::FromPrimitive; -use private::de::InPlaceSeed; - -#[cfg(any(feature = "std", feature = "alloc"))] -use private::de::size_hint; - -//////////////////////////////////////////////////////////////////////////////// - -struct UnitVisitor; - -impl<'de> Visitor<'de> for UnitVisitor { - type Value = (); - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("unit") - } - - fn visit_unit<E>(self) -> Result<(), E> - where - E: Error, - { - Ok(()) - } -} - -impl<'de> Deserialize<'de> for () { - fn deserialize<D>(deserializer: D) -> Result<(), D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_unit(UnitVisitor) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -struct BoolVisitor; - -impl<'de> Visitor<'de> for BoolVisitor { - type Value = bool; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a boolean") - } - - fn visit_bool<E>(self, v: bool) -> Result<bool, E> - where - E: Error, - { - Ok(v) - } -} - -impl<'de> Deserialize<'de> for bool { - fn deserialize<D>(deserializer: D) -> Result<bool, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_bool(BoolVisitor) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -macro_rules! visit_integer_method { - ($src_ty:ident, $method:ident, $from_method:ident, $group:ident, $group_ty:ident) => { - #[inline] - fn $method<E>(self, v: $src_ty) -> Result<Self::Value, E> - where - E: Error, - { - match FromPrimitive::$from_method(v) { - Some(v) => Ok(v), - None => Err(Error::invalid_value(Unexpected::$group(v as $group_ty), &self)), - } - } - } -} - -macro_rules! visit_float_method { - ($src_ty:ident, $method:ident) => { - #[inline] - fn $method<E>(self, v: $src_ty) -> Result<Self::Value, E> - where - E: Error, - { - Ok(v as Self::Value) - } - } -} - -macro_rules! impl_deserialize_num { - ($ty:ident, $method:ident, $($visit:ident),*) => { - impl<'de> Deserialize<'de> for $ty { - #[inline] - fn deserialize<D>(deserializer: D) -> Result<$ty, D::Error> - where - D: Deserializer<'de>, - { - struct PrimitiveVisitor; - - impl<'de> Visitor<'de> for PrimitiveVisitor { - type Value = $ty; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str(stringify!($ty)) - } - - $( - impl_deserialize_num!($visit $ty); - )* - } - - deserializer.$method(PrimitiveVisitor) - } - } - }; - - (integer $ty:ident) => { - visit_integer_method!(i8, visit_i8, from_i8, Signed, i64); - visit_integer_method!(i16, visit_i16, from_i16, Signed, i64); - visit_integer_method!(i32, visit_i32, from_i32, Signed, i64); - visit_integer_method!(i64, visit_i64, from_i64, Signed, i64); - - visit_integer_method!(u8, visit_u8, from_u8, Unsigned, u64); - visit_integer_method!(u16, visit_u16, from_u16, Unsigned, u64); - visit_integer_method!(u32, visit_u32, from_u32, Unsigned, u64); - visit_integer_method!(u64, visit_u64, from_u64, Unsigned, u64); - }; - - (float $ty:ident) => { - visit_float_method!(f32, visit_f32); - visit_float_method!(f64, visit_f64); - }; -} - -impl_deserialize_num!(i8, deserialize_i8, integer); -impl_deserialize_num!(i16, deserialize_i16, integer); -impl_deserialize_num!(i32, deserialize_i32, integer); -impl_deserialize_num!(i64, deserialize_i64, integer); -impl_deserialize_num!(isize, deserialize_i64, integer); - -impl_deserialize_num!(u8, deserialize_u8, integer); -impl_deserialize_num!(u16, deserialize_u16, integer); -impl_deserialize_num!(u32, deserialize_u32, integer); -impl_deserialize_num!(u64, deserialize_u64, integer); -impl_deserialize_num!(usize, deserialize_u64, integer); - -impl_deserialize_num!(f32, deserialize_f32, integer, float); -impl_deserialize_num!(f64, deserialize_f64, integer, float); - -//////////////////////////////////////////////////////////////////////////////// - -struct CharVisitor; - -impl<'de> Visitor<'de> for CharVisitor { - type Value = char; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a character") - } - - #[inline] - fn visit_char<E>(self, v: char) -> Result<char, E> - where - E: Error, - { - Ok(v) - } - - #[inline] - fn visit_str<E>(self, v: &str) -> Result<char, E> - where - E: Error, - { - let mut iter = v.chars(); - match (iter.next(), iter.next()) { - (Some(c), None) => Ok(c), - _ => Err(Error::invalid_value(Unexpected::Str(v), &self)), - } - } -} - -impl<'de> Deserialize<'de> for char { - #[inline] - fn deserialize<D>(deserializer: D) -> Result<char, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_char(CharVisitor) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(any(feature = "std", feature = "alloc"))] -struct StringVisitor; -#[cfg(any(feature = "std", feature = "alloc"))] -struct StringInPlaceVisitor<'a>(&'a mut String); - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'de> Visitor<'de> for StringVisitor { - type Value = String; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a string") - } - - fn visit_str<E>(self, v: &str) -> Result<String, E> - where - E: Error, - { - Ok(v.to_owned()) - } - - fn visit_string<E>(self, v: String) -> Result<String, E> - where - E: Error, - { - Ok(v) - } - - fn visit_bytes<E>(self, v: &[u8]) -> Result<String, E> - where - E: Error, - { - match str::from_utf8(v) { - Ok(s) => Ok(s.to_owned()), - Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), - } - } - - fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<String, E> - where - E: Error, - { - match String::from_utf8(v) { - Ok(s) => Ok(s), - Err(e) => Err(Error::invalid_value( - Unexpected::Bytes(&e.into_bytes()), - &self, - )), - } - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'a, 'de> Visitor<'de> for StringInPlaceVisitor<'a> { - type Value = (); - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a string") - } - - fn visit_str<E>(self, v: &str) -> Result<(), E> - where - E: Error, - { - self.0.clear(); - self.0.push_str(v); - Ok(()) - } - - fn visit_string<E>(self, v: String) -> Result<(), E> - where - E: Error, - { - *self.0 = v; - Ok(()) - } - - fn visit_bytes<E>(self, v: &[u8]) -> Result<(), E> - where - E: Error, - { - match str::from_utf8(v) { - Ok(s) => { - self.0.clear(); - self.0.push_str(s); - Ok(()) - } - Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), - } - } - - fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<(), E> - where - E: Error, - { - match String::from_utf8(v) { - Ok(s) => { - *self.0 = s; - Ok(()) - } - Err(e) => Err(Error::invalid_value( - Unexpected::Bytes(&e.into_bytes()), - &self, - )), - } - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'de> Deserialize<'de> for String { - fn deserialize<D>(deserializer: D) -> Result<String, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_string(StringVisitor) - } - - fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_string(StringInPlaceVisitor(place)) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -struct StrVisitor; - -impl<'a> Visitor<'a> for StrVisitor { - type Value = &'a str; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a borrowed string") - } - - fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> - where - E: Error, - { - Ok(v) // so easy - } - - fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> - where - E: Error, - { - str::from_utf8(v).map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self)) - } -} - -impl<'de: 'a, 'a> Deserialize<'de> for &'a str { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_str(StrVisitor) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -struct BytesVisitor; - -impl<'a> Visitor<'a> for BytesVisitor { - type Value = &'a [u8]; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a borrowed byte array") - } - - fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> - where - E: Error, - { - Ok(v) - } - - fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> - where - E: Error, - { - Ok(v.as_bytes()) - } -} - -impl<'de: 'a, 'a> Deserialize<'de> for &'a [u8] { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_bytes(BytesVisitor) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "std")] -struct CStringVisitor; - -#[cfg(feature = "std")] -impl<'de> Visitor<'de> for CStringVisitor { - type Value = CString; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("byte array") - } - - fn visit_seq<A>(self, mut seq: A) -> Result<CString, A::Error> - where - A: SeqAccess<'de>, - { - let len = size_hint::cautious(seq.size_hint()); - let mut values = Vec::with_capacity(len); - - while let Some(value) = try!(seq.next_element()) { - values.push(value); - } - - CString::new(values).map_err(Error::custom) - } - - fn visit_bytes<E>(self, v: &[u8]) -> Result<CString, E> - where - E: Error, - { - CString::new(v).map_err(Error::custom) - } - - fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<CString, E> - where - E: Error, - { - CString::new(v).map_err(Error::custom) - } - - fn visit_str<E>(self, v: &str) -> Result<CString, E> - where - E: Error, - { - CString::new(v).map_err(Error::custom) - } - - fn visit_string<E>(self, v: String) -> Result<CString, E> - where - E: Error, - { - CString::new(v).map_err(Error::custom) - } -} - -#[cfg(feature = "std")] -impl<'de> Deserialize<'de> for CString { - fn deserialize<D>(deserializer: D) -> Result<CString, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_byte_buf(CStringVisitor) - } -} - -macro_rules! forwarded_impl { - (( $($id: ident),* ), $ty: ty, $func: expr) => { - impl<'de $(, $id : Deserialize<'de>,)*> Deserialize<'de> for $ty { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - Deserialize::deserialize(deserializer).map($func) - } - } - } -} - -#[cfg(all(feature = "std", feature = "unstable"))] -forwarded_impl!((), Box<CStr>, CString::into_boxed_c_str); - -//////////////////////////////////////////////////////////////////////////////// - -struct OptionVisitor<T> { - marker: PhantomData<T>, -} - -impl<'de, T> Visitor<'de> for OptionVisitor<T> -where - T: Deserialize<'de>, -{ - type Value = Option<T>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("option") - } - - #[inline] - fn visit_unit<E>(self) -> Result<Option<T>, E> - where - E: Error, - { - Ok(None) - } - - #[inline] - fn visit_none<E>(self) -> Result<Option<T>, E> - where - E: Error, - { - Ok(None) - } - - #[inline] - fn visit_some<D>(self, deserializer: D) -> Result<Option<T>, D::Error> - where - D: Deserializer<'de>, - { - T::deserialize(deserializer).map(Some) - } -} - -impl<'de, T> Deserialize<'de> for Option<T> -where - T: Deserialize<'de>, -{ - fn deserialize<D>(deserializer: D) -> Result<Option<T>, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_option(OptionVisitor { - marker: PhantomData, - }) - } - - // The Some variant's repr is opaque, so we can't play cute tricks with its - // tag to have deserialize_in_place build the content in place unconditionally. - // - // FIXME: investigate whether branching on the old value being Some to - // deserialize_in_place the value is profitable (probably data-dependent?) -} - -//////////////////////////////////////////////////////////////////////////////// - -struct PhantomDataVisitor<T: ?Sized> { - marker: PhantomData<T>, -} - -impl<'de, T: ?Sized> Visitor<'de> for PhantomDataVisitor<T> { - type Value = PhantomData<T>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("unit") - } - - #[inline] - fn visit_unit<E>(self) -> Result<PhantomData<T>, E> - where - E: Error, - { - Ok(PhantomData) - } -} - -impl<'de, T: ?Sized> Deserialize<'de> for PhantomData<T> { - fn deserialize<D>(deserializer: D) -> Result<PhantomData<T>, D::Error> - where - D: Deserializer<'de>, - { - let visitor = PhantomDataVisitor { - marker: PhantomData, - }; - deserializer.deserialize_unit_struct("PhantomData", visitor) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(any(feature = "std", feature = "alloc"))] -macro_rules! seq_impl { - ( - $ty:ident < T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >, - $access:ident, - $ctor:expr, - $clear:expr, - $with_capacity:expr, - $reserve:expr, - $insert:expr - ) => { - impl<'de, T $(, $typaram)*> Deserialize<'de> for $ty<T $(, $typaram)*> - where - T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*, - $($typaram: $bound1 $(+ $bound2)*,)* - { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - struct SeqVisitor<T $(, $typaram)*> { - marker: PhantomData<$ty<T $(, $typaram)*>>, - } - - impl<'de, T $(, $typaram)*> Visitor<'de> for SeqVisitor<T $(, $typaram)*> - where - T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*, - $($typaram: $bound1 $(+ $bound2)*,)* - { - type Value = $ty<T $(, $typaram)*>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a sequence") - } - - #[inline] - fn visit_seq<A>(self, mut $access: A) -> Result<Self::Value, A::Error> - where - A: SeqAccess<'de>, - { - let mut values = $with_capacity; - - while let Some(value) = try!($access.next_element()) { - $insert(&mut values, value); - } - - Ok(values) - } - } - - let visitor = SeqVisitor { marker: PhantomData }; - deserializer.deserialize_seq(visitor) - } - - fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> - where - D: Deserializer<'de>, - { - struct SeqInPlaceVisitor<'a, T: 'a $(, $typaram: 'a)*>(&'a mut $ty<T $(, $typaram)*>); - - impl<'a, 'de, T $(, $typaram)*> Visitor<'de> for SeqInPlaceVisitor<'a, T $(, $typaram)*> - where - T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*, - $($typaram: $bound1 $(+ $bound2)*,)* - { - type Value = (); - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a sequence") - } - - #[inline] - fn visit_seq<A>(mut self, mut $access: A) -> Result<(), A::Error> - where - A: SeqAccess<'de>, - { - $clear(&mut self.0); - $reserve(&mut self.0, size_hint::cautious($access.size_hint())); - - // FIXME: try to overwrite old values here? (Vec, VecDeque, LinkedList) - while let Some(value) = try!($access.next_element()) { - $insert(&mut self.0, value); - } - - Ok(()) - } - } - - deserializer.deserialize_seq(SeqInPlaceVisitor(place)) - } - } - } -} - -// Dummy impl of reserve -#[cfg(any(feature = "std", feature = "alloc"))] -fn nop_reserve<T>(_seq: T, _n: usize) {} - -#[cfg(any(feature = "std", feature = "alloc"))] -seq_impl!( - BinaryHeap<T: Ord>, - seq, - BinaryHeap::new(), - BinaryHeap::clear, - BinaryHeap::with_capacity(size_hint::cautious(seq.size_hint())), - BinaryHeap::reserve, - BinaryHeap::push); - -#[cfg(any(feature = "std", feature = "alloc"))] -seq_impl!( - BTreeSet<T: Eq + Ord>, - seq, - BTreeSet::new(), - BTreeSet::clear, - BTreeSet::new(), - nop_reserve, - BTreeSet::insert); - -#[cfg(any(feature = "std", feature = "alloc"))] -seq_impl!( - LinkedList<T>, - seq, - LinkedList::new(), - LinkedList::clear, - LinkedList::new(), - nop_reserve, - LinkedList::push_back -); - -#[cfg(feature = "std")] -seq_impl!( - HashSet<T: Eq + Hash, S: BuildHasher + Default>, - seq, - HashSet::with_hasher(S::default()), - HashSet::clear, - HashSet::with_capacity_and_hasher(size_hint::cautious(seq.size_hint()), S::default()), - HashSet::reserve, - HashSet::insert); - -#[cfg(any(feature = "std", feature = "alloc"))] -seq_impl!( - Vec<T>, - seq, - Vec::new(), - Vec::clear, - Vec::with_capacity(size_hint::cautious(seq.size_hint())), - Vec::reserve, - Vec::push -); - -#[cfg(any(feature = "std", feature = "alloc"))] -seq_impl!( - VecDeque<T>, - seq, - VecDeque::new(), - VecDeque::clear, - VecDeque::with_capacity(size_hint::cautious(seq.size_hint())), - VecDeque::reserve, - VecDeque::push_back -); - -//////////////////////////////////////////////////////////////////////////////// - -struct ArrayVisitor<A> { - marker: PhantomData<A>, -} -struct ArrayInPlaceVisitor<'a, A: 'a>(&'a mut A); - -impl<A> ArrayVisitor<A> { - fn new() -> Self { - ArrayVisitor { - marker: PhantomData, - } - } -} - -impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]> { - type Value = [T; 0]; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("an empty array") - } - - #[inline] - fn visit_seq<A>(self, _: A) -> Result<[T; 0], A::Error> - where - A: SeqAccess<'de>, - { - Ok([]) - } -} - -// Does not require T: Deserialize<'de>. -impl<'de, T> Deserialize<'de> for [T; 0] { - fn deserialize<D>(deserializer: D) -> Result<[T; 0], D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_tuple(0, ArrayVisitor::<[T; 0]>::new()) - } -} - -macro_rules! array_impls { - ($($len:expr => ($($n:tt $name:ident)+))+) => { - $( - impl<'de, T> Visitor<'de> for ArrayVisitor<[T; $len]> - where - T: Deserialize<'de>, - { - type Value = [T; $len]; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str(concat!("an array of length ", $len)) - } - - #[inline] - fn visit_seq<A>(self, mut seq: A) -> Result<[T; $len], A::Error> - where - A: SeqAccess<'de>, - { - $( - let $name = match try!(seq.next_element()) { - Some(val) => val, - None => return Err(Error::invalid_length($n, &self)), - }; - )+ - - Ok([$($name),+]) - } - } - - impl<'a, 'de, T> Visitor<'de> for ArrayInPlaceVisitor<'a, [T; $len]> - where - T: Deserialize<'de>, - { - type Value = (); - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str(concat!("an array of length ", $len)) - } - - #[inline] - fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error> - where - A: SeqAccess<'de>, - { - let mut fail_idx = None; - for (idx, dest) in self.0[..].iter_mut().enumerate() { - if try!(seq.next_element_seed(InPlaceSeed(dest))).is_none() { - fail_idx = Some(idx); - break; - } - } - if let Some(idx) = fail_idx { - return Err(Error::invalid_length(idx, &self)); - } - Ok(()) - } - } - - impl<'de, T> Deserialize<'de> for [T; $len] - where - T: Deserialize<'de>, - { - fn deserialize<D>(deserializer: D) -> Result<[T; $len], D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_tuple($len, ArrayVisitor::<[T; $len]>::new()) - } - - fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_tuple($len, ArrayInPlaceVisitor(place)) - } - } - )+ - } -} - -array_impls! { - 1 => (0 a) - 2 => (0 a 1 b) - 3 => (0 a 1 b 2 c) - 4 => (0 a 1 b 2 c 3 d) - 5 => (0 a 1 b 2 c 3 d 4 e) - 6 => (0 a 1 b 2 c 3 d 4 e 5 f) - 7 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g) - 8 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h) - 9 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i) - 10 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j) - 11 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k) - 12 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l) - 13 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m) - 14 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n) - 15 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o) - 16 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p) - 17 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q) - 18 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r) - 19 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s) - 20 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t) - 21 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u) - 22 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v) - 23 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w) - 24 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x) - 25 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y) - 26 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z) - 27 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa) - 28 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab) - 29 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac) - 30 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad) - 31 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad 30 ae) - 32 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad 30 ae 31 af) -} - -//////////////////////////////////////////////////////////////////////////////// - -macro_rules! tuple_impls { - ($($len:tt => ($($n:tt $name:ident)+))+) => { - $( - impl<'de, $($name: Deserialize<'de>),+> Deserialize<'de> for ($($name,)+) { - #[inline] - fn deserialize<D>(deserializer: D) -> Result<($($name,)+), D::Error> - where - D: Deserializer<'de>, - { - struct TupleVisitor<$($name,)+> { - marker: PhantomData<($($name,)+)>, - } - - impl<'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleVisitor<$($name,)+> { - type Value = ($($name,)+); - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str(concat!("a tuple of size ", $len)) - } - - #[inline] - #[allow(non_snake_case)] - fn visit_seq<A>(self, mut seq: A) -> Result<($($name,)+), A::Error> - where - A: SeqAccess<'de>, - { - $( - let $name = match try!(seq.next_element()) { - Some(value) => value, - None => return Err(Error::invalid_length($n, &self)), - }; - )+ - - Ok(($($name,)+)) - } - } - - deserializer.deserialize_tuple($len, TupleVisitor { marker: PhantomData }) - } - - #[inline] - fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> - where - D: Deserializer<'de>, - { - struct TupleInPlaceVisitor<'a, $($name: 'a,)+>(&'a mut ($($name,)+)); - - impl<'a, 'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleInPlaceVisitor<'a, $($name,)+> { - type Value = (); - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str(concat!("a tuple of size ", $len)) - } - - #[inline] - #[allow(non_snake_case)] - fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error> - where - A: SeqAccess<'de>, - { - $( - if try!(seq.next_element_seed(InPlaceSeed(&mut (self.0).$n))).is_none() { - return Err(Error::invalid_length($n, &self)); - } - )+ - - Ok(()) - } - } - - deserializer.deserialize_tuple($len, TupleInPlaceVisitor(place)) - } - } - )+ - } -} - -tuple_impls! { - 1 => (0 T0) - 2 => (0 T0 1 T1) - 3 => (0 T0 1 T1 2 T2) - 4 => (0 T0 1 T1 2 T2 3 T3) - 5 => (0 T0 1 T1 2 T2 3 T3 4 T4) - 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5) - 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6) - 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7) - 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8) - 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9) - 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10) - 12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11) - 13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12) - 14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13) - 15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14) - 16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15) -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(any(feature = "std", feature = "alloc"))] -macro_rules! map_impl { - ( - $ty:ident < K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >, - $access:ident, - $ctor:expr, - $with_capacity:expr - ) => { - impl<'de, K, V $(, $typaram)*> Deserialize<'de> for $ty<K, V $(, $typaram)*> - where - K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*, - V: Deserialize<'de>, - $($typaram: $bound1 $(+ $bound2)*),* - { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - struct MapVisitor<K, V $(, $typaram)*> { - marker: PhantomData<$ty<K, V $(, $typaram)*>>, - } - - impl<'de, K, V $(, $typaram)*> Visitor<'de> for MapVisitor<K, V $(, $typaram)*> - where - K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*, - V: Deserialize<'de>, - $($typaram: $bound1 $(+ $bound2)*),* - { - type Value = $ty<K, V $(, $typaram)*>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a map") - } - - #[inline] - fn visit_map<A>(self, mut $access: A) -> Result<Self::Value, A::Error> - where - A: MapAccess<'de>, - { - let mut values = $with_capacity; - - while let Some((key, value)) = try!($access.next_entry()) { - values.insert(key, value); - } - - Ok(values) - } - } - - let visitor = MapVisitor { marker: PhantomData }; - deserializer.deserialize_map(visitor) - } - } - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -map_impl!( - BTreeMap<K: Ord, V>, - map, - BTreeMap::new(), - BTreeMap::new()); - -#[cfg(feature = "std")] -map_impl!( - HashMap<K: Eq + Hash, V, S: BuildHasher + Default>, - map, - HashMap::with_hasher(S::default()), - HashMap::with_capacity_and_hasher(size_hint::cautious(map.size_hint()), S::default())); - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "std")] -macro_rules! parse_ip_impl { - ($ty:ty; $size: expr) => { - impl<'de> Deserialize<'de> for $ty { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - if deserializer.is_human_readable() { - let s = try!(String::deserialize(deserializer)); - s.parse().map_err(Error::custom) - } else { - <[u8; $size]>::deserialize(deserializer).map(<$ty>::from) - } - } - } - } -} - -#[cfg(feature = "std")] -macro_rules! variant_identifier { - ( - $name_kind: ident ( $($variant: ident; $bytes: expr; $index: expr),* ) - $expecting_message: expr, - $variants_name: ident - ) => { - enum $name_kind { - $( $variant ),* - } - - static $variants_name: &'static [&'static str] = &[ $( stringify!($variant) ),*]; - - impl<'de> Deserialize<'de> for $name_kind { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - struct KindVisitor; - - impl<'de> Visitor<'de> for KindVisitor { - type Value = $name_kind; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str($expecting_message) - } - - fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E> - where - E: Error, - { - match value { - $( - $index => Ok($name_kind :: $variant), - )* - _ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self),), - } - } - - fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> - where - E: Error, - { - match value { - $( - stringify!($variant) => Ok($name_kind :: $variant), - )* - _ => Err(Error::unknown_variant(value, $variants_name)), - } - } - - fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E> - where - E: Error, - { - match value { - $( - $bytes => Ok($name_kind :: $variant), - )* - _ => { - match str::from_utf8(value) { - Ok(value) => Err(Error::unknown_variant(value, $variants_name)), - Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)), - } - } - } - } - } - - deserializer.deserialize_identifier(KindVisitor) - } - } - } -} - -#[cfg(feature = "std")] -macro_rules! deserialize_enum { - ( - $name: ident $name_kind: ident ( $($variant: ident; $bytes: expr; $index: expr),* ) - $expecting_message: expr, - $deserializer: expr - ) => { - variant_identifier!{ - $name_kind ( $($variant; $bytes; $index),* ) - $expecting_message, - VARIANTS - } - - struct EnumVisitor; - impl<'de> Visitor<'de> for EnumVisitor { - type Value = $name; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str(concat!("a ", stringify!($name))) - } - - - fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error> - where - A: EnumAccess<'de>, - { - match try!(data.variant()) { - $( - ($name_kind :: $variant, v) => v.newtype_variant().map($name :: $variant), - )* - } - } - } - $deserializer.deserialize_enum(stringify!($name), VARIANTS, EnumVisitor) - } -} - -#[cfg(feature = "std")] -impl<'de> Deserialize<'de> for net::IpAddr { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - if deserializer.is_human_readable() { - let s = try!(String::deserialize(deserializer)); - s.parse().map_err(Error::custom) - } else { - use lib::net::IpAddr; - deserialize_enum!{ - IpAddr IpAddrKind (V4; b"V4"; 0, V6; b"V6"; 1) - "`V4` or `V6`", - deserializer - } - } - } -} - -#[cfg(feature = "std")] -parse_ip_impl!(net::Ipv4Addr; 4); - -#[cfg(feature = "std")] -parse_ip_impl!(net::Ipv6Addr; 16); - -#[cfg(feature = "std")] -macro_rules! parse_socket_impl { - ($ty:ty, $new: expr) => { - impl<'de> Deserialize<'de> for $ty { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - if deserializer.is_human_readable() { - let s = try!(String::deserialize(deserializer)); - s.parse().map_err(Error::custom) - } else { - <(_, u16)>::deserialize(deserializer).map(|(ip, port)| $new(ip, port)) - } - } - } - } -} - -#[cfg(feature = "std")] -impl<'de> Deserialize<'de> for net::SocketAddr { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - if deserializer.is_human_readable() { - let s = try!(String::deserialize(deserializer)); - s.parse().map_err(Error::custom) - } else { - use lib::net::SocketAddr; - deserialize_enum!{ - SocketAddr SocketAddrKind (V4; b"V4"; 0, V6; b"V6"; 1) - "`V4` or `V6`", - deserializer - } - } - } -} - -#[cfg(feature = "std")] -parse_socket_impl!(net::SocketAddrV4, net::SocketAddrV4::new); - -#[cfg(feature = "std")] -parse_socket_impl!(net::SocketAddrV6, |ip, port| net::SocketAddrV6::new( - ip, - port, - 0, - 0 -)); - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "std")] -struct PathVisitor; - -#[cfg(feature = "std")] -impl<'a> Visitor<'a> for PathVisitor { - type Value = &'a Path; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a borrowed path") - } - - fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> - where - E: Error, - { - Ok(v.as_ref()) - } - - fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> - where - E: Error, - { - str::from_utf8(v) - .map(AsRef::as_ref) - .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self)) - } -} - -#[cfg(feature = "std")] -impl<'de: 'a, 'a> Deserialize<'de> for &'a Path { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_str(PathVisitor) - } -} - -#[cfg(feature = "std")] -struct PathBufVisitor; - -#[cfg(feature = "std")] -impl<'de> Visitor<'de> for PathBufVisitor { - type Value = PathBuf; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("path string") - } - - fn visit_str<E>(self, v: &str) -> Result<PathBuf, E> - where - E: Error, - { - Ok(From::from(v)) - } - - fn visit_string<E>(self, v: String) -> Result<PathBuf, E> - where - E: Error, - { - Ok(From::from(v)) - } -} - -#[cfg(feature = "std")] -impl<'de> Deserialize<'de> for PathBuf { - fn deserialize<D>(deserializer: D) -> Result<PathBuf, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_string(PathBufVisitor) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -// If this were outside of the serde crate, it would just use: -// -// #[derive(Deserialize)] -// #[serde(variant_identifier)] -#[cfg(all(feature = "std", any(unix, windows)))] -variant_identifier!{ - OsStringKind (Unix; b"Unix"; 0, Windows; b"Windows"; 1) - "`Unix` or `Windows`", - OSSTR_VARIANTS -} - -#[cfg(all(feature = "std", any(unix, windows)))] -struct OsStringVisitor; - -#[cfg(all(feature = "std", any(unix, windows)))] -impl<'de> Visitor<'de> for OsStringVisitor { - type Value = OsString; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("os string") - } - - #[cfg(unix)] - fn visit_enum<A>(self, data: A) -> Result<OsString, A::Error> - where - A: EnumAccess<'de>, - { - use std::os::unix::ffi::OsStringExt; - - match try!(data.variant()) { - (OsStringKind::Unix, v) => v.newtype_variant().map(OsString::from_vec), - (OsStringKind::Windows, _) => Err(Error::custom( - "cannot deserialize Windows OS string on Unix", - )), - } - } - - #[cfg(windows)] - fn visit_enum<A>(self, data: A) -> Result<OsString, A::Error> - where - A: EnumAccess<'de>, - { - use std::os::windows::ffi::OsStringExt; - - match try!(data.variant()) { - (OsStringKind::Windows, v) => v.newtype_variant::<Vec<u16>>() - .map(|vec| OsString::from_wide(&vec)), - (OsStringKind::Unix, _) => Err(Error::custom( - "cannot deserialize Unix OS string on Windows", - )), - } - } -} - -#[cfg(all(feature = "std", any(unix, windows)))] -impl<'de> Deserialize<'de> for OsString { - fn deserialize<D>(deserializer: D) -> Result<OsString, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_enum("OsString", OSSTR_VARIANTS, OsStringVisitor) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(any(feature = "std", feature = "alloc"))] -forwarded_impl!((T), Box<T>, Box::new); - -#[cfg(any(feature = "std", feature = "alloc"))] -forwarded_impl!((T), Box<[T]>, Vec::into_boxed_slice); - -#[cfg(any(feature = "std", feature = "alloc"))] -forwarded_impl!((), Box<str>, String::into_boxed_str); - -#[cfg(all(not(feature = "unstable"), feature = "rc", any(feature = "std", feature = "alloc")))] -forwarded_impl!((T), Arc<T>, Arc::new); - -#[cfg(all(not(feature = "unstable"), feature = "rc", any(feature = "std", feature = "alloc")))] -forwarded_impl!((T), Rc<T>, Rc::new); - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T> -where - T: ToOwned, - T::Owned: Deserialize<'de>, -{ - #[inline] - fn deserialize<D>(deserializer: D) -> Result<Cow<'a, T>, D::Error> - where - D: Deserializer<'de>, - { - T::Owned::deserialize(deserializer).map(Cow::Owned) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(all(feature = "unstable", feature = "rc", any(feature = "std", feature = "alloc")))] -macro_rules! box_forwarded_impl { - ($t:ident) => { - impl<'de, T: ?Sized> Deserialize<'de> for $t<T> - where - Box<T>: Deserialize<'de>, - { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - Box::deserialize(deserializer).map(Into::into) - } - } - } -} - -#[cfg(all(feature = "unstable", feature = "rc", any(feature = "std", feature = "alloc")))] -box_forwarded_impl!(Rc); - -#[cfg(all(feature = "unstable", feature = "rc", any(feature = "std", feature = "alloc")))] -box_forwarded_impl!(Arc); - -//////////////////////////////////////////////////////////////////////////////// - -impl<'de, T> Deserialize<'de> for Cell<T> -where - T: Deserialize<'de> + Copy, -{ - fn deserialize<D>(deserializer: D) -> Result<Cell<T>, D::Error> - where - D: Deserializer<'de>, - { - T::deserialize(deserializer).map(Cell::new) - } -} - -forwarded_impl!((T), RefCell<T>, RefCell::new); - -#[cfg(feature = "std")] -forwarded_impl!((T), Mutex<T>, Mutex::new); - -#[cfg(feature = "std")] -forwarded_impl!((T), RwLock<T>, RwLock::new); - -//////////////////////////////////////////////////////////////////////////////// - -// This is a cleaned-up version of the impl generated by: -// -// #[derive(Deserialize)] -// #[serde(deny_unknown_fields)] -// struct Duration { -// secs: u64, -// nanos: u32, -// } -#[cfg(feature = "std")] -impl<'de> Deserialize<'de> for Duration { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - // If this were outside of the serde crate, it would just use: - // - // #[derive(Deserialize)] - // #[serde(field_identifier, rename_all = "lowercase")] - enum Field { - Secs, - Nanos, - }; - - impl<'de> Deserialize<'de> for Field { - fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> - where - D: Deserializer<'de>, - { - struct FieldVisitor; - - impl<'de> Visitor<'de> for FieldVisitor { - type Value = Field; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("`secs` or `nanos`") - } - - fn visit_str<E>(self, value: &str) -> Result<Field, E> - where - E: Error, - { - match value { - "secs" => Ok(Field::Secs), - "nanos" => Ok(Field::Nanos), - _ => Err(Error::unknown_field(value, FIELDS)), - } - } - - fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> - where - E: Error, - { - match value { - b"secs" => Ok(Field::Secs), - b"nanos" => Ok(Field::Nanos), - _ => { - let value = String::from_utf8_lossy(value); - Err(Error::unknown_field(&value, FIELDS)) - } - } - } - } - - deserializer.deserialize_identifier(FieldVisitor) - } - } - - struct DurationVisitor; - - impl<'de> Visitor<'de> for DurationVisitor { - type Value = Duration; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("struct Duration") - } - - fn visit_seq<A>(self, mut seq: A) -> Result<Duration, A::Error> - where - A: SeqAccess<'de>, - { - let secs: u64 = match try!(seq.next_element()) { - Some(value) => value, - None => { - return Err(Error::invalid_length(0, &self)); - } - }; - let nanos: u32 = match try!(seq.next_element()) { - Some(value) => value, - None => { - return Err(Error::invalid_length(1, &self)); - } - }; - Ok(Duration::new(secs, nanos)) - } - - fn visit_map<A>(self, mut map: A) -> Result<Duration, A::Error> - where - A: MapAccess<'de>, - { - let mut secs: Option<u64> = None; - let mut nanos: Option<u32> = None; - while let Some(key) = try!(map.next_key()) { - match key { - Field::Secs => { - if secs.is_some() { - return Err(<A::Error as Error>::duplicate_field("secs")); - } - secs = Some(try!(map.next_value())); - } - Field::Nanos => { - if nanos.is_some() { - return Err(<A::Error as Error>::duplicate_field("nanos")); - } - nanos = Some(try!(map.next_value())); - } - } - } - let secs = match secs { - Some(secs) => secs, - None => return Err(<A::Error as Error>::missing_field("secs")), - }; - let nanos = match nanos { - Some(nanos) => nanos, - None => return Err(<A::Error as Error>::missing_field("nanos")), - }; - Ok(Duration::new(secs, nanos)) - } - } - - const FIELDS: &'static [&'static str] = &["secs", "nanos"]; - deserializer.deserialize_struct("Duration", FIELDS, DurationVisitor) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "std")] -impl<'de> Deserialize<'de> for SystemTime { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - // Reuse duration - enum Field { - Secs, - Nanos, - }; - - impl<'de> Deserialize<'de> for Field { - fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> - where - D: Deserializer<'de>, - { - struct FieldVisitor; - - impl<'de> Visitor<'de> for FieldVisitor { - type Value = Field; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("`secs_since_epoch` or `nanos_since_epoch`") - } - - fn visit_str<E>(self, value: &str) -> Result<Field, E> - where - E: Error, - { - match value { - "secs_since_epoch" => Ok(Field::Secs), - "nanos_since_epoch" => Ok(Field::Nanos), - _ => Err(Error::unknown_field(value, FIELDS)), - } - } - - fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> - where - E: Error, - { - match value { - b"secs_since_epoch" => Ok(Field::Secs), - b"nanos_since_epoch" => Ok(Field::Nanos), - _ => { - let value = String::from_utf8_lossy(value); - Err(Error::unknown_field(&value, FIELDS)) - } - } - } - } - - deserializer.deserialize_identifier(FieldVisitor) - } - } - - struct DurationVisitor; - - impl<'de> Visitor<'de> for DurationVisitor { - type Value = Duration; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("struct SystemTime") - } - - fn visit_seq<A>(self, mut seq: A) -> Result<Duration, A::Error> - where - A: SeqAccess<'de>, - { - let secs: u64 = match try!(seq.next_element()) { - Some(value) => value, - None => { - return Err(Error::invalid_length(0, &self)); - } - }; - let nanos: u32 = match try!(seq.next_element()) { - Some(value) => value, - None => { - return Err(Error::invalid_length(1, &self)); - } - }; - Ok(Duration::new(secs, nanos)) - } - - fn visit_map<A>(self, mut map: A) -> Result<Duration, A::Error> - where - A: MapAccess<'de>, - { - let mut secs: Option<u64> = None; - let mut nanos: Option<u32> = None; - while let Some(key) = try!(map.next_key()) { - match key { - Field::Secs => { - if secs.is_some() { - return Err(<A::Error as Error>::duplicate_field( - "secs_since_epoch", - )); - } - secs = Some(try!(map.next_value())); - } - Field::Nanos => { - if nanos.is_some() { - return Err(<A::Error as Error>::duplicate_field( - "nanos_since_epoch", - )); - } - nanos = Some(try!(map.next_value())); - } - } - } - let secs = match secs { - Some(secs) => secs, - None => return Err(<A::Error as Error>::missing_field("secs_since_epoch")), - }; - let nanos = match nanos { - Some(nanos) => nanos, - None => return Err(<A::Error as Error>::missing_field("nanos_since_epoch")), - }; - Ok(Duration::new(secs, nanos)) - } - } - - const FIELDS: &'static [&'static str] = &["secs_since_epoch", "nanos_since_epoch"]; - let duration = try!(deserializer.deserialize_struct("SystemTime", FIELDS, DurationVisitor)); - Ok(UNIX_EPOCH + duration) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -// Similar to: -// -// #[derive(Deserialize)] -// #[serde(deny_unknown_fields)] -// struct Range { -// start: u64, -// end: u32, -// } -#[cfg(feature = "std")] -impl<'de, Idx> Deserialize<'de> for ops::Range<Idx> -where - Idx: Deserialize<'de>, -{ - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - // If this were outside of the serde crate, it would just use: - // - // #[derive(Deserialize)] - // #[serde(field_identifier, rename_all = "lowercase")] - enum Field { - Start, - End, - }; - - impl<'de> Deserialize<'de> for Field { - fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> - where - D: Deserializer<'de>, - { - struct FieldVisitor; - - impl<'de> Visitor<'de> for FieldVisitor { - type Value = Field; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("`start` or `end`") - } - - fn visit_str<E>(self, value: &str) -> Result<Field, E> - where - E: Error, - { - match value { - "start" => Ok(Field::Start), - "end" => Ok(Field::End), - _ => Err(Error::unknown_field(value, FIELDS)), - } - } - - fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> - where - E: Error, - { - match value { - b"start" => Ok(Field::Start), - b"end" => Ok(Field::End), - _ => { - let value = String::from_utf8_lossy(value); - Err(Error::unknown_field(&value, FIELDS)) - } - } - } - } - - deserializer.deserialize_identifier(FieldVisitor) - } - } - - struct RangeVisitor<Idx> { - phantom: PhantomData<Idx>, - } - - impl<'de, Idx> Visitor<'de> for RangeVisitor<Idx> - where - Idx: Deserialize<'de>, - { - type Value = ops::Range<Idx>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("struct Range") - } - - fn visit_seq<A>(self, mut seq: A) -> Result<ops::Range<Idx>, A::Error> - where - A: SeqAccess<'de>, - { - let start: Idx = match try!(seq.next_element()) { - Some(value) => value, - None => { - return Err(Error::invalid_length(0, &self)); - } - }; - let end: Idx = match try!(seq.next_element()) { - Some(value) => value, - None => { - return Err(Error::invalid_length(1, &self)); - } - }; - Ok(start..end) - } - - fn visit_map<A>(self, mut map: A) -> Result<ops::Range<Idx>, A::Error> - where - A: MapAccess<'de>, - { - let mut start: Option<Idx> = None; - let mut end: Option<Idx> = None; - while let Some(key) = try!(map.next_key()) { - match key { - Field::Start => { - if start.is_some() { - return Err(<A::Error as Error>::duplicate_field("start")); - } - start = Some(try!(map.next_value())); - } - Field::End => { - if end.is_some() { - return Err(<A::Error as Error>::duplicate_field("end")); - } - end = Some(try!(map.next_value())); - } - } - } - let start = match start { - Some(start) => start, - None => return Err(<A::Error as Error>::missing_field("start")), - }; - let end = match end { - Some(end) => end, - None => return Err(<A::Error as Error>::missing_field("end")), - }; - Ok(start..end) - } - } - - const FIELDS: &'static [&'static str] = &["start", "end"]; - deserializer.deserialize_struct( - "Range", - FIELDS, - RangeVisitor { - phantom: PhantomData, - }, - ) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "unstable")] -impl<'de, T> Deserialize<'de> for NonZero<T> -where - T: Deserialize<'de> + Zeroable, -{ - fn deserialize<D>(deserializer: D) -> Result<NonZero<T>, D::Error> - where - D: Deserializer<'de>, - { - let value = try!(Deserialize::deserialize(deserializer)); - match NonZero::new(value) { - Some(nonzero) => Ok(nonzero), - None => Err(Error::custom("expected a non-zero value")), - } - } -} - -//////////////////////////////////////////////////////////////////////////////// - -impl<'de, T, E> Deserialize<'de> for Result<T, E> -where - T: Deserialize<'de>, - E: Deserialize<'de>, -{ - fn deserialize<D>(deserializer: D) -> Result<Result<T, E>, D::Error> - where - D: Deserializer<'de>, - { - // If this were outside of the serde crate, it would just use: - // - // #[derive(Deserialize)] - // #[serde(variant_identifier)] - enum Field { - Ok, - Err, - } - - impl<'de> Deserialize<'de> for Field { - #[inline] - fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> - where - D: Deserializer<'de>, - { - struct FieldVisitor; - - impl<'de> Visitor<'de> for FieldVisitor { - type Value = Field; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("`Ok` or `Err`") - } - - fn visit_u32<E>(self, value: u32) -> Result<Field, E> - where - E: Error, - { - match value { - 0 => Ok(Field::Ok), - 1 => Ok(Field::Err), - _ => Err(Error::invalid_value( - Unexpected::Unsigned(value as u64), - &self, - )), - } - } - - fn visit_str<E>(self, value: &str) -> Result<Field, E> - where - E: Error, - { - match value { - "Ok" => Ok(Field::Ok), - "Err" => Ok(Field::Err), - _ => Err(Error::unknown_variant(value, VARIANTS)), - } - } - - fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> - where - E: Error, - { - match value { - b"Ok" => Ok(Field::Ok), - b"Err" => Ok(Field::Err), - _ => match str::from_utf8(value) { - Ok(value) => Err(Error::unknown_variant(value, VARIANTS)), - Err(_) => { - Err(Error::invalid_value(Unexpected::Bytes(value), &self)) - } - }, - } - } - } - - deserializer.deserialize_identifier(FieldVisitor) - } - } - - struct ResultVisitor<T, E>(PhantomData<Result<T, E>>); - - impl<'de, T, E> Visitor<'de> for ResultVisitor<T, E> - where - T: Deserialize<'de>, - E: Deserialize<'de>, - { - type Value = Result<T, E>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("enum Result") - } - - fn visit_enum<A>(self, data: A) -> Result<Result<T, E>, A::Error> - where - A: EnumAccess<'de>, - { - match try!(data.variant()) { - (Field::Ok, v) => v.newtype_variant().map(Ok), - (Field::Err, v) => v.newtype_variant().map(Err), - } - } - } - - const VARIANTS: &'static [&'static str] = &["Ok", "Err"]; - - deserializer.deserialize_enum("Result", VARIANTS, ResultVisitor(PhantomData)) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "std")] -impl<'de, T> Deserialize<'de> for Wrapping<T> -where - T: Deserialize<'de>, -{ - fn deserialize<D>(deserializer: D) -> Result<Wrapping<T>, D::Error> - where - D: Deserializer<'de>, - { - Deserialize::deserialize(deserializer).map(Wrapping) - } -} diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/de/mod.rs cargo-0.26.0/vendor/serde-1.0.27/src/de/mod.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/de/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/de/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2044 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Generic data structure deserialization framework. -//! -//! The two most important traits in this module are [`Deserialize`] and -//! [`Deserializer`]. -//! -//! - **A type that implements `Deserialize` is a data structure** that can be -//! deserialized from any data format supported by Serde, and conversely -//! - **A type that implements `Deserializer` is a data format** that can -//! deserialize any data structure supported by Serde. -//! -//! # The Deserialize trait -//! -//! Serde provides [`Deserialize`] implementations for many Rust primitive and -//! standard library types. The complete list is below. All of these can be -//! deserialized using Serde out of the box. -//! -//! Additionally, Serde provides a procedural macro called [`serde_derive`] to -//! automatically generate [`Deserialize`] implementations for structs and enums -//! in your program. See the [codegen section of the manual] for how to use -//! this. -//! -//! In rare cases it may be necessary to implement [`Deserialize`] manually for -//! some type in your program. See the [Implementing `Deserialize`] section of -//! the manual for more about this. -//! -//! Third-party crates may provide [`Deserialize`] implementations for types -//! that they expose. For example the [`linked-hash-map`] crate provides a -//! [`LinkedHashMap<K, V>`] type that is deserializable by Serde because the -//! crate provides an implementation of [`Deserialize`] for it. -//! -//! # The Deserializer trait -//! -//! [`Deserializer`] implementations are provided by third-party crates, for -//! example [`serde_json`], [`serde_yaml`] and [`bincode`]. -//! -//! A partial list of well-maintained formats is given on the [Serde -//! website][data formats]. -//! -//! # Implementations of Deserialize provided by Serde -//! -//! This is a slightly different set of types than what is supported for -//! serialization. Some types can be serialized by Serde but not deserialized. -//! One example is `OsStr`. -//! -//! - **Primitive types**: -//! - bool -//! - i8, i16, i32, i64, isize -//! - u8, u16, u32, u64, usize -//! - f32, f64 -//! - char -//! - **Compound types**: -//! - [T; 0] through [T; 32] -//! - tuples up to size 16 -//! - **Common standard library types**: -//! - String -//! - Option\<T\> -//! - Result\<T, E\> -//! - PhantomData\<T\> -//! - **Wrapper types**: -//! - Box\<T\> -//! - Box\<[T]\> -//! - Box\<str\> -//! - Rc\<T\> -//! - Arc\<T\> -//! - Cow\<'a, T\> -//! - Cell\<T\> -//! - RefCell\<T\> -//! - Mutex\<T\> -//! - RwLock\<T\> -//! - **Collection types**: -//! - BTreeMap\<K, V\> -//! - BTreeSet\<T\> -//! - BinaryHeap\<T\> -//! - HashMap\<K, V, H\> -//! - HashSet\<T, H\> -//! - LinkedList\<T\> -//! - VecDeque\<T\> -//! - Vec\<T\> -//! - EnumSet\<T\> (unstable) -//! - **Zero-copy types**: -//! - &str -//! - &[u8] -//! - **FFI types**: -//! - CString -//! - Box\<CStr\> -//! - OsString -//! - **Miscellaneous standard library types**: -//! - Duration -//! - SystemTime -//! - Path -//! - PathBuf -//! - Range\<T\> -//! - NonZero\<T\> (unstable) -//! - **Net types**: -//! - IpAddr -//! - Ipv4Addr -//! - Ipv6Addr -//! - SocketAddr -//! - SocketAddrV4 -//! - SocketAddrV6 -//! -//! [Implementing `Deserialize`]: https://serde.rs/impl-deserialize.html -//! [`Deserialize`]: ../trait.Deserialize.html -//! [`Deserializer`]: ../trait.Deserializer.html -//! [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html -//! [`bincode`]: https://github.com/TyOverby/bincode -//! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map -//! [`serde_derive`]: https://crates.io/crates/serde_derive -//! [`serde_json`]: https://github.com/serde-rs/json -//! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml -//! [codegen section of the manual]: https://serde.rs/codegen.html -//! [data formats]: https://serde.rs/#data-formats - -use lib::*; - -//////////////////////////////////////////////////////////////////////////////// - -pub mod value; - -mod from_primitive; -mod ignored_any; -mod impls; -mod utf8; - -pub use self::ignored_any::IgnoredAny; - -//////////////////////////////////////////////////////////////////////////////// - -macro_rules! declare_error_trait { - (Error: Sized $(+ $($supertrait:ident)::+)*) => { - /// The `Error` trait allows `Deserialize` implementations to create descriptive - /// error messages belonging to the `Deserializer` against which they are - /// currently running. - /// - /// Every `Deserializer` declares an `Error` type that encompasses both - /// general-purpose deserialization errors as well as errors specific to the - /// particular deserialization format. For example the `Error` type of - /// `serde_json` can represent errors like an invalid JSON escape sequence or an - /// unterminated string literal, in addition to the error cases that are part of - /// this trait. - /// - /// Most deserializers should only need to provide the `Error::custom` method - /// and inherit the default behavior for the other methods. - pub trait Error: Sized $(+ $($supertrait)::+)* { - /// Raised when there is general error when deserializing a type. - /// - /// The message should not be capitalized and should not end with a period. - /// - /// ```rust - /// # use std::str::FromStr; - /// # - /// # struct IpAddr; - /// # - /// # impl FromStr for IpAddr { - /// # type Err = String; - /// # - /// # fn from_str(_: &str) -> Result<Self, String> { - /// # unimplemented!() - /// # } - /// # } - /// # - /// use serde::de::{self, Deserialize, Deserializer}; - /// - /// impl<'de> Deserialize<'de> for IpAddr { - /// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - /// where D: Deserializer<'de> - /// { - /// let s = try!(String::deserialize(deserializer)); - /// s.parse().map_err(de::Error::custom) - /// } - /// } - /// ``` - fn custom<T>(msg: T) -> Self - where - T: Display; - - /// Raised when a `Deserialize` receives a type different from what it was - /// expecting. - /// - /// The `unexp` argument provides information about what type was received. - /// This is the type that was present in the input file or other source data - /// of the Deserializer. - /// - /// The `exp` argument provides information about what type was being - /// expected. This is the type that is written in the program. - /// - /// For example if we try to deserialize a String out of a JSON file - /// containing an integer, the unexpected type is the integer and the - /// expected type is the string. - fn invalid_type(unexp: Unexpected, exp: &Expected) -> Self { - Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp)) - } - - /// Raised when a `Deserialize` receives a value of the right type but that - /// is wrong for some other reason. - /// - /// The `unexp` argument provides information about what value was received. - /// This is the value that was present in the input file or other source - /// data of the Deserializer. - /// - /// The `exp` argument provides information about what value was being - /// expected. This is the type that is written in the program. - /// - /// For example if we try to deserialize a String out of some binary data - /// that is not valid UTF-8, the unexpected value is the bytes and the - /// expected value is a string. - fn invalid_value(unexp: Unexpected, exp: &Expected) -> Self { - Error::custom(format_args!("invalid value: {}, expected {}", unexp, exp)) - } - - /// Raised when deserializing a sequence or map and the input data contains - /// too many or too few elements. - /// - /// The `len` argument is the number of elements encountered. The sequence - /// or map may have expected more arguments or fewer arguments. - /// - /// The `exp` argument provides information about what data was being - /// expected. For example `exp` might say that a tuple of size 6 was - /// expected. - fn invalid_length(len: usize, exp: &Expected) -> Self { - Error::custom(format_args!("invalid length {}, expected {}", len, exp)) - } - - /// Raised when a `Deserialize` enum type received a variant with an - /// unrecognized name. - fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self { - if expected.is_empty() { - Error::custom(format_args!("unknown variant `{}`, there are no variants", - variant)) - } else { - Error::custom(format_args!("unknown variant `{}`, expected {}", - variant, - OneOf { names: expected })) - } - } - - /// Raised when a `Deserialize` struct type received a field with an - /// unrecognized name. - fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self { - if expected.is_empty() { - Error::custom(format_args!("unknown field `{}`, there are no fields", - field)) - } else { - Error::custom(format_args!("unknown field `{}`, expected {}", - field, - OneOf { names: expected })) - } - } - - /// Raised when a `Deserialize` struct type expected to receive a required - /// field with a particular name but that field was not present in the - /// input. - fn missing_field(field: &'static str) -> Self { - Error::custom(format_args!("missing field `{}`", field)) - } - - /// Raised when a `Deserialize` struct type received more than one of the - /// same field. - fn duplicate_field(field: &'static str) -> Self { - Error::custom(format_args!("duplicate field `{}`", field)) - } - } - } -} - -#[cfg(feature = "std")] -declare_error_trait!(Error: Sized + error::Error); - -#[cfg(not(feature = "std"))] -declare_error_trait!(Error: Sized + Debug + Display); - -/// `Unexpected` represents an unexpected invocation of any one of the `Visitor` -/// trait methods. -/// -/// This is used as an argument to the `invalid_type`, `invalid_value`, and -/// `invalid_length` methods of the `Error` trait to build error messages. -/// -/// ```rust -/// # use std::fmt; -/// # -/// # use serde::de::{self, Unexpected, Visitor}; -/// # -/// # struct Example; -/// # -/// # impl<'de> Visitor<'de> for Example { -/// # type Value = (); -/// # -/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { -/// # write!(formatter, "definitely not a boolean") -/// # } -/// # -/// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> -/// where E: de::Error -/// { -/// Err(de::Error::invalid_type(Unexpected::Bool(v), &self)) -/// } -/// # } -/// ``` -#[derive(Copy, Clone, PartialEq, Debug)] -pub enum Unexpected<'a> { - /// The input contained a boolean value that was not expected. - Bool(bool), - - /// The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that - /// was not expected. - Unsigned(u64), - - /// The input contained a signed integer `i8`, `i16`, `i32` or `i64` that - /// was not expected. - Signed(i64), - - /// The input contained a floating point `f32` or `f64` that was not - /// expected. - Float(f64), - - /// The input contained a `char` that was not expected. - Char(char), - - /// The input contained a `&str` or `String` that was not expected. - Str(&'a str), - - /// The input contained a `&[u8]` or `Vec<u8>` that was not expected. - Bytes(&'a [u8]), - - /// The input contained a unit `()` that was not expected. - Unit, - - /// The input contained an `Option<T>` that was not expected. - Option, - - /// The input contained a newtype struct that was not expected. - NewtypeStruct, - - /// The input contained a sequence that was not expected. - Seq, - - /// The input contained a map that was not expected. - Map, - - /// The input contained an enum that was not expected. - Enum, - - /// The input contained a unit variant that was not expected. - UnitVariant, - - /// The input contained a newtype variant that was not expected. - NewtypeVariant, - - /// The input contained a tuple variant that was not expected. - TupleVariant, - - /// The input contained a struct variant that was not expected. - StructVariant, - - /// A message stating what uncategorized thing the input contained that was - /// not expected. - /// - /// The message should be a noun or noun phrase, not capitalized and without - /// a period. An example message is "unoriginal superhero". - Other(&'a str), -} - -impl<'a> fmt::Display for Unexpected<'a> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { - use self::Unexpected::*; - match *self { - Bool(b) => write!(formatter, "boolean `{}`", b), - Unsigned(i) => write!(formatter, "integer `{}`", i), - Signed(i) => write!(formatter, "integer `{}`", i), - Float(f) => write!(formatter, "floating point `{}`", f), - Char(c) => write!(formatter, "character `{}`", c), - Str(s) => write!(formatter, "string {:?}", s), - Bytes(_) => write!(formatter, "byte array"), - Unit => write!(formatter, "unit value"), - Option => write!(formatter, "Option value"), - NewtypeStruct => write!(formatter, "newtype struct"), - Seq => write!(formatter, "sequence"), - Map => write!(formatter, "map"), - Enum => write!(formatter, "enum"), - UnitVariant => write!(formatter, "unit variant"), - NewtypeVariant => write!(formatter, "newtype variant"), - TupleVariant => write!(formatter, "tuple variant"), - StructVariant => write!(formatter, "struct variant"), - Other(other) => formatter.write_str(other), - } - } -} - -/// `Expected` represents an explanation of what data a `Visitor` was expecting -/// to receive. -/// -/// This is used as an argument to the `invalid_type`, `invalid_value`, and -/// `invalid_length` methods of the `Error` trait to build error messages. The -/// message should be a noun or noun phrase that completes the sentence "This -/// Visitor expects to receive ...", for example the message could be "an -/// integer between 0 and 64". The message should not be capitalized and should -/// not end with a period. -/// -/// Within the context of a `Visitor` implementation, the `Visitor` itself -/// (`&self`) is an implementation of this trait. -/// -/// ```rust -/// # use std::fmt; -/// # -/// # use serde::de::{self, Unexpected, Visitor}; -/// # -/// # struct Example; -/// # -/// # impl<'de> Visitor<'de> for Example { -/// # type Value = (); -/// # -/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { -/// # write!(formatter, "definitely not a boolean") -/// # } -/// # -/// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> -/// where E: de::Error -/// { -/// Err(de::Error::invalid_type(Unexpected::Bool(v), &self)) -/// } -/// # } -/// ``` -/// -/// Outside of a `Visitor`, `&"..."` can be used. -/// -/// ```rust -/// # use serde::de::{self, Unexpected}; -/// # -/// # fn example<E>() -> Result<(), E> -/// # where E: de::Error -/// # { -/// # let v = true; -/// return Err(de::Error::invalid_type(Unexpected::Bool(v), &"a negative integer")); -/// # } -/// ``` -pub trait Expected { - /// Format an explanation of what data was being expected. Same signature as - /// the `Display` and `Debug` traits. - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result; -} - -impl<'de, T> Expected for T -where - T: Visitor<'de>, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - self.expecting(formatter) - } -} - -impl<'a> Expected for &'a str { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str(self) - } -} - -impl<'a> Display for Expected + 'a { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - Expected::fmt(self, formatter) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// A **data structure** that can be deserialized from any data format supported -/// by Serde. -/// -/// Serde provides `Deserialize` implementations for many Rust primitive and -/// standard library types. The complete list is [here][de]. All of these can -/// be deserialized using Serde out of the box. -/// -/// Additionally, Serde provides a procedural macro called `serde_derive` to -/// automatically generate `Deserialize` implementations for structs and enums -/// in your program. See the [codegen section of the manual][codegen] for how to -/// use this. -/// -/// In rare cases it may be necessary to implement `Deserialize` manually for -/// some type in your program. See the [Implementing -/// `Deserialize`][impl-deserialize] section of the manual for more about this. -/// -/// Third-party crates may provide `Deserialize` implementations for types that -/// they expose. For example the `linked-hash-map` crate provides a -/// `LinkedHashMap<K, V>` type that is deserializable by Serde because the crate -/// provides an implementation of `Deserialize` for it. -/// -/// [de]: https://docs.serde.rs/serde/de/index.html -/// [codegen]: https://serde.rs/codegen.html -/// [impl-deserialize]: https://serde.rs/impl-deserialize.html -pub trait Deserialize<'de>: Sized { - /// Deserialize this value from the given Serde deserializer. - /// - /// See the [Implementing `Deserialize`][impl-deserialize] section of the - /// manual for more information about how to implement this method. - /// - /// [impl-deserialize]: https://serde.rs/impl-deserialize.html - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>; - - /// Deserializes a value into `self` from the given Deserializer. - /// - /// The purpose of this method is to allow the deserializer to reuse - /// resources and avoid copies. As such, if this method returns an error, - /// `self` will be in an indeterminate state where some parts of the struct - /// have been overwritten. Although whatever state that is will be - /// memory-safe. - /// - /// This is generally useful when repeateadly deserializing values that - /// are processed one at a time, where the value of `self` doesn't matter - /// when the next deserialization occurs. - /// - /// If you manually implement this, your recursive deserializations should - /// use `deserialize_in_place`. - /// - /// This method is stable and an official public API, but hidden from the - /// documentation because it is almost never what newbies are looking for. - /// Showing it in rustdoc would cause it to be featured more prominently - /// than it deserves. - #[doc(hidden)] - fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> - where - D: Deserializer<'de>, - { - // Default implementation just delegates to `deserialize` impl. - *place = Deserialize::deserialize(deserializer)?; - Ok(()) - } -} - -/// A data structure that can be deserialized without borrowing any data from -/// the deserializer. -/// -/// This is primarily useful for trait bounds on functions. For example a -/// `from_str` function may be able to deserialize a data structure that borrows -/// from the input string, but a `from_reader` function may only deserialize -/// owned data. -/// -/// ```rust -/// # use serde::de::{Deserialize, DeserializeOwned}; -/// # use std::io::{Read, Result}; -/// # -/// # trait Ignore { -/// fn from_str<'a, T>(s: &'a str) -> Result<T> -/// where T: Deserialize<'a>; -/// -/// fn from_reader<R, T>(rdr: R) -> Result<T> -/// where R: Read, -/// T: DeserializeOwned; -/// # } -/// ``` -pub trait DeserializeOwned: for<'de> Deserialize<'de> {} -impl<T> DeserializeOwned for T -where - T: for<'de> Deserialize<'de>, -{ -} - -/// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you -/// ever find yourself looking for a way to pass data into a `Deserialize` impl, -/// this trait is the way to do it. -/// -/// As one example of stateful deserialization consider deserializing a JSON -/// array into an existing buffer. Using the `Deserialize` trait we could -/// deserialize a JSON array into a `Vec<T>` but it would be a freshly allocated -/// `Vec<T>`; there is no way for `Deserialize` to reuse a previously allocated -/// buffer. Using `DeserializeSeed` instead makes this possible as in the -/// example code below. -/// -/// The canonical API for stateless deserialization looks like this: -/// -/// ```rust -/// # use serde::Deserialize; -/// # -/// # enum Error {} -/// # -/// fn func<'de, T: Deserialize<'de>>() -> Result<T, Error> -/// # { -/// # unimplemented!() -/// # } -/// ``` -/// -/// Adjusting an API like this to support stateful deserialization is a matter -/// of accepting a seed as input: -/// -/// ```rust -/// # use serde::de::DeserializeSeed; -/// # -/// # enum Error {} -/// # -/// fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result<T::Value, Error> -/// # { -/// # let _ = seed; -/// # unimplemented!() -/// # } -/// ``` -/// -/// In practice the majority of deserialization is stateless. An API expecting a -/// seed can be appeased by passing `std::marker::PhantomData` as a seed in the -/// case of stateless deserialization. -/// -/// # Example -/// -/// Suppose we have JSON that looks like `[[1, 2], [3, 4, 5], [6]]` and we need -/// to deserialize it into a flat representation like `vec![1, 2, 3, 4, 5, 6]`. -/// Allocating a brand new `Vec<T>` for each subarray would be slow. Instead we -/// would like to allocate a single `Vec<T>` and then deserialize each subarray -/// into it. This requires stateful deserialization using the `DeserializeSeed` -/// trait. -/// -/// ```rust -/// use std::fmt; -/// use std::marker::PhantomData; -/// -/// use serde::de::{Deserialize, DeserializeSeed, Deserializer, Visitor, SeqAccess}; -/// -/// // A DeserializeSeed implementation that uses stateful deserialization to -/// // append array elements onto the end of an existing vector. The preexisting -/// // state ("seed") in this case is the Vec<T>. The `deserialize` method of -/// // `ExtendVec` will be traversing the inner arrays of the JSON input and -/// // appending each integer into the existing Vec. -/// struct ExtendVec<'a, T: 'a>(&'a mut Vec<T>); -/// -/// impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T> -/// where T: Deserialize<'de> -/// { -/// // The return type of the `deserialize` method. This implementation -/// // appends onto an existing vector but does not create any new data -/// // structure, so the return type is (). -/// type Value = (); -/// -/// fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> -/// where D: Deserializer<'de> -/// { -/// // Visitor implementation that will walk an inner array of the JSON -/// // input. -/// struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec<T>); -/// -/// impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T> -/// where T: Deserialize<'de> -/// { -/// type Value = (); -/// -/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { -/// write!(formatter, "an array of integers") -/// } -/// -/// fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error> -/// where A: SeqAccess<'de> -/// { -/// // Visit each element in the inner array and push it onto -/// // the existing vector. -/// while let Some(elem) = seq.next_element()? { -/// self.0.push(elem); -/// } -/// Ok(()) -/// } -/// } -/// -/// deserializer.deserialize_seq(ExtendVecVisitor(self.0)) -/// } -/// } -/// -/// // Visitor implementation that will walk the outer array of the JSON input. -/// struct FlattenedVecVisitor<T>(PhantomData<T>); -/// -/// impl<'de, T> Visitor<'de> for FlattenedVecVisitor<T> -/// where T: Deserialize<'de> -/// { -/// // This Visitor constructs a single Vec<T> to hold the flattened -/// // contents of the inner arrays. -/// type Value = Vec<T>; -/// -/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { -/// write!(formatter, "an array of arrays") -/// } -/// -/// fn visit_seq<A>(self, mut seq: A) -> Result<Vec<T>, A::Error> -/// where A: SeqAccess<'de> -/// { -/// // Create a single Vec to hold the flattened contents. -/// let mut vec = Vec::new(); -/// -/// // Each iteration through this loop is one inner array. -/// while let Some(()) = seq.next_element_seed(ExtendVec(&mut vec))? { -/// // Nothing to do; inner array has been appended into `vec`. -/// } -/// -/// // Return the finished vec. -/// Ok(vec) -/// } -/// } -/// -/// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error> -/// # where D: Deserializer<'de> -/// # { -/// let visitor = FlattenedVecVisitor(PhantomData); -/// let flattened: Vec<u64> = deserializer.deserialize_seq(visitor)?; -/// # Ok(()) -/// # } -/// ``` -pub trait DeserializeSeed<'de>: Sized { - /// The type produced by using this seed. - type Value; - - /// Equivalent to the more common `Deserialize::deserialize` method, except - /// with some initial piece of data (the seed) passed in. - fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>; -} - -impl<'de, T> DeserializeSeed<'de> for PhantomData<T> -where - T: Deserialize<'de>, -{ - type Value = T; - - #[inline] - fn deserialize<D>(self, deserializer: D) -> Result<T, D::Error> - where - D: Deserializer<'de>, - { - T::deserialize(deserializer) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// A **data format** that can deserialize any data structure supported by -/// Serde. -/// -/// The role of this trait is to define the deserialization half of the Serde -/// data model, which is a way to categorize every Rust data type into one of 27 -/// possible types. Each method of the `Serializer` trait corresponds to one of -/// the types of the data model. -/// -/// Implementations of `Deserialize` map themselves into this data model by -/// passing to the `Deserializer` a `Visitor` implementation that can receive -/// these various types. -/// -/// The types that make up the Serde data model are: -/// -/// - **12 primitive types** -/// - bool -/// - i8, i16, i32, i64 -/// - u8, u16, u32, u64 -/// - f32, f64 -/// - char -/// - **string** -/// - UTF-8 bytes with a length and no null terminator. -/// - When serializing, all strings are handled equally. When deserializing, -/// there are three flavors of strings: transient, owned, and borrowed. -/// - **byte array** - [u8] -/// - Similar to strings, during deserialization byte arrays can be transient, -/// owned, or borrowed. -/// - **option** -/// - Either none or some value. -/// - **unit** -/// - The type of `()` in Rust. It represents an anonymous value containing no -/// data. -/// - **unit_struct** -/// - For example `struct Unit` or `PhantomData<T>`. It represents a named value -/// containing no data. -/// - **unit_variant** -/// - For example the `E::A` and `E::B` in `enum E { A, B }`. -/// - **newtype_struct** -/// - For example `struct Millimeters(u8)`. -/// - **newtype_variant** -/// - For example the `E::N` in `enum E { N(u8) }`. -/// - **seq** -/// - A variably sized heterogeneous sequence of values, for example `Vec<T>` or -/// `HashSet<T>`. When serializing, the length may or may not be known before -/// iterating through all the data. When deserializing, the length is determined -/// by looking at the serialized data. -/// - **tuple** -/// - A statically sized heterogeneous sequence of values for which the length -/// will be known at deserialization time without looking at the serialized -/// data, for example `(u8,)` or `(String, u64, Vec<T>)` or `[u64; 10]`. -/// - **tuple_struct** -/// - A named tuple, for example `struct Rgb(u8, u8, u8)`. -/// - **tuple_variant** -/// - For example the `E::T` in `enum E { T(u8, u8) }`. -/// - **map** -/// - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`. -/// - **struct** -/// - A heterogeneous key-value pairing in which the keys are strings and will be -/// known at deserialization time without looking at the serialized data, for -/// example `struct S { r: u8, g: u8, b: u8 }`. -/// - **struct_variant** -/// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. -/// -/// The `Deserializer` trait supports two entry point styles which enables -/// different kinds of deserialization. -/// -/// 1. The `deserialize` method. Self-describing data formats like JSON are able -/// to look at the serialized data and tell what it represents. For example -/// the JSON deserializer may see an opening curly brace (`{`) and know that -/// it is seeing a map. If the data format supports -/// `Deserializer::deserialize_any`, it will drive the Visitor using whatever -/// type it sees in the input. JSON uses this approach when deserializing -/// `serde_json::Value` which is an enum that can represent any JSON -/// document. Without knowing what is in a JSON document, we can deserialize -/// it to `serde_json::Value` by going through `Deserializer::deserialize_any`. -/// -/// 2. The various `deserialize_*` methods. Non-self-describing formats like -/// Bincode need to be told what is in the input in order to deserialize it. -/// The `deserialize_*` methods are hints to the deserializer for how to -/// interpret the next piece of input. Non-self-describing formats are not -/// able to deserialize something like `serde_json::Value` which relies on -/// `Deserializer::deserialize_any`. -/// -/// When implementing `Deserialize`, you should avoid relying on -/// `Deserializer::deserialize_any` unless you need to be told by the Deserializer -/// what type is in the input. Know that relying on `Deserializer::deserialize_any` -/// means your data type will be able to deserialize from self-describing -/// formats only, ruling out Bincode and many others. -pub trait Deserializer<'de>: Sized { - /// The error type that can be returned if some error occurs during - /// deserialization. - type Error: Error; - - /// Require the `Deserializer` to figure out how to drive the visitor based - /// on what data type is in the input. - /// - /// When implementing `Deserialize`, you should avoid relying on - /// `Deserializer::deserialize_any` unless you need to be told by the - /// Deserializer what type is in the input. Know that relying on - /// `Deserializer::deserialize_any` means your data type will be able to - /// deserialize from self-describing formats only, ruling out Bincode and - /// many others. - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a `bool` value. - fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting an `i8` value. - fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting an `i16` value. - fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting an `i32` value. - fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting an `i64` value. - fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a `u8` value. - fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a `u16` value. - fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a `u32` value. - fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a `u64` value. - fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a `f32` value. - fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a `f64` value. - fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a `char` value. - fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a string value and does - /// not benefit from taking ownership of buffered data owned by the - /// `Deserializer`. - /// - /// If the `Visitor` would benefit from taking ownership of `String` data, - /// indiciate this to the `Deserializer` by using `deserialize_string` - /// instead. - fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a string value and would - /// benefit from taking ownership of buffered data owned by the - /// `Deserializer`. - /// - /// If the `Visitor` would not benefit from taking ownership of `String` - /// data, indicate that to the `Deserializer` by using `deserialize_str` - /// instead. - fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a byte array and does not - /// benefit from taking ownership of buffered data owned by the - /// `Deserializer`. - /// - /// If the `Visitor` would benefit from taking ownership of `Vec<u8>` data, - /// indicate this to the `Deserializer` by using `deserialize_byte_buf` - /// instead. - fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a byte array and would - /// benefit from taking ownership of buffered data owned by the - /// `Deserializer`. - /// - /// If the `Visitor` would not benefit from taking ownership of `Vec<u8>` - /// data, indicate that to the `Deserializer` by using `deserialize_bytes` - /// instead. - fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting an optional value. - /// - /// This allows deserializers that encode an optional value as a nullable - /// value to convert the null value into `None` and a regular value into - /// `Some(value)`. - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a unit value. - fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a unit struct with a - /// particular name. - fn deserialize_unit_struct<V>( - self, - name: &'static str, - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a newtype struct with a - /// particular name. - fn deserialize_newtype_struct<V>( - self, - name: &'static str, - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a sequence of values. - fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a sequence of values and - /// knows how many values there are without looking at the serialized data. - fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a tuple struct with a - /// particular name and number of fields. - fn deserialize_tuple_struct<V>( - self, - name: &'static str, - len: usize, - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a map of key-value pairs. - fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting a struct with a particular - /// name and fields. - fn deserialize_struct<V>( - self, - name: &'static str, - fields: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting an enum value with a - /// particular name and possible variants. - fn deserialize_enum<V>( - self, - name: &'static str, - variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type is expecting the name of a struct - /// field or the discriminant of an enum variant. - fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Hint that the `Deserialize` type needs to deserialize a value whose type - /// doesn't matter because it is ignored. - /// - /// Deserializers for non-self-describing formats may not support this mode. - fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Determine whether `Deserialize` implementations should expect to - /// deserialize their human-readable form. - /// - /// Some types have a human-readable form that may be somewhat expensive to - /// construct, as well as a binary form that is compact and efficient. - /// Generally text-based formats like JSON and YAML will prefer to use the - /// human-readable one and binary formats like Bincode will prefer the - /// compact one. - /// - /// ``` - /// # use std::ops::Add; - /// # use std::str::FromStr; - /// # - /// # struct Timestamp; - /// # - /// # impl Timestamp { - /// # const EPOCH: Timestamp = Timestamp; - /// # } - /// # - /// # impl FromStr for Timestamp { - /// # type Err = String; - /// # fn from_str(_: &str) -> Result<Self, Self::Err> { - /// # unimplemented!() - /// # } - /// # } - /// # - /// # struct Duration; - /// # - /// # impl Duration { - /// # fn seconds(_: u64) -> Self { unimplemented!() } - /// # } - /// # - /// # impl Add<Duration> for Timestamp { - /// # type Output = Timestamp; - /// # fn add(self, _: Duration) -> Self::Output { - /// # unimplemented!() - /// # } - /// # } - /// # - /// use serde::de::{self, Deserialize, Deserializer}; - /// - /// impl<'de> Deserialize<'de> for Timestamp { - /// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - /// where D: Deserializer<'de> - /// { - /// if deserializer.is_human_readable() { - /// // Deserialize from a human-readable string like "2015-05-15T17:01:00Z". - /// let s = String::deserialize(deserializer)?; - /// Timestamp::from_str(&s).map_err(de::Error::custom) - /// } else { - /// // Deserialize from a compact binary representation, seconds since - /// // the Unix epoch. - /// let n = u64::deserialize(deserializer)?; - /// Ok(Timestamp::EPOCH + Duration::seconds(n)) - /// } - /// } - /// } - /// ``` - /// - /// The default implementation of this method returns `true`. Data formats - /// may override this to `false` to request a compact form for types that - /// support one. Note that modifying this method to change a format from - /// human-readable to compact or vice versa should be regarded as a breaking - /// change, as a value serialized in human-readable mode is not required to - /// deserialize from the same data in compact mode. - #[inline] - fn is_human_readable(&self) -> bool { - true - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// This trait represents a visitor that walks through a deserializer. -/// -/// ```rust -/// # use std::fmt; -/// # -/// # use serde::de::{self, Unexpected, Visitor}; -/// # -/// /// A visitor that deserializes a long string - a string containing at least -/// /// some minimum number of bytes. -/// struct LongString { -/// min: usize, -/// } -/// -/// impl<'de> Visitor<'de> for LongString { -/// type Value = String; -/// -/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { -/// write!(formatter, "a string containing at least {} bytes", self.min) -/// } -/// -/// fn visit_str<E>(self, s: &str) -> Result<Self::Value, E> -/// where E: de::Error -/// { -/// if s.len() >= self.min { -/// Ok(s.to_owned()) -/// } else { -/// Err(de::Error::invalid_value(Unexpected::Str(s), &self)) -/// } -/// } -/// } -/// ``` -pub trait Visitor<'de>: Sized { - /// The value produced by this visitor. - type Value; - - /// Format a message stating what data this Visitor expects to receive. - /// - /// This is used in error messages. The message should complete the sentence - /// "This Visitor expects to receive ...", for example the message could be - /// "an integer between 0 and 64". The message should not be capitalized and - /// should not end with a period. - /// - /// ```rust - /// # use std::fmt; - /// # - /// # struct S { - /// # max: usize, - /// # } - /// # - /// # impl<'de> serde::de::Visitor<'de> for S { - /// # type Value = (); - /// # - /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - /// write!(formatter, "an integer between 0 and {}", self.max) - /// } - /// # } - /// ``` - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result; - - /// The input contains a boolean. - /// - /// The default implementation fails with a type error. - fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> - where - E: Error, - { - Err(Error::invalid_type(Unexpected::Bool(v), &self)) - } - - /// The input contains an `i8`. - /// - /// The default implementation forwards to [`visit_i64`]. - /// - /// [`visit_i64`]: #method.visit_i64 - fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E> - where - E: Error, - { - self.visit_i64(v as i64) - } - - /// The input contains an `i16`. - /// - /// The default implementation forwards to [`visit_i64`]. - /// - /// [`visit_i64`]: #method.visit_i64 - fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E> - where - E: Error, - { - self.visit_i64(v as i64) - } - - /// The input contains an `i32`. - /// - /// The default implementation forwards to [`visit_i64`]. - /// - /// [`visit_i64`]: #method.visit_i64 - fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E> - where - E: Error, - { - self.visit_i64(v as i64) - } - - /// The input contains an `i64`. - /// - /// The default implementation fails with a type error. - fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> - where - E: Error, - { - Err(Error::invalid_type(Unexpected::Signed(v), &self)) - } - - /// The input contains a `u8`. - /// - /// The default implementation forwards to [`visit_u64`]. - /// - /// [`visit_u64`]: #method.visit_u64 - fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E> - where - E: Error, - { - self.visit_u64(v as u64) - } - - /// The input contains a `u16`. - /// - /// The default implementation forwards to [`visit_u64`]. - /// - /// [`visit_u64`]: #method.visit_u64 - fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E> - where - E: Error, - { - self.visit_u64(v as u64) - } - - /// The input contains a `u32`. - /// - /// The default implementation forwards to [`visit_u64`]. - /// - /// [`visit_u64`]: #method.visit_u64 - fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E> - where - E: Error, - { - self.visit_u64(v as u64) - } - - /// The input contains a `u64`. - /// - /// The default implementation fails with a type error. - fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> - where - E: Error, - { - Err(Error::invalid_type(Unexpected::Unsigned(v), &self)) - } - - /// The input contains an `f32`. - /// - /// The default implementation forwards to [`visit_f64`]. - /// - /// [`visit_f64`]: #method.visit_f64 - fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E> - where - E: Error, - { - self.visit_f64(v as f64) - } - - /// The input contains an `f64`. - /// - /// The default implementation fails with a type error. - fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E> - where - E: Error, - { - Err(Error::invalid_type(Unexpected::Float(v), &self)) - } - - /// The input contains a `char`. - /// - /// The default implementation forwards to [`visit_str`] as a one-character - /// string. - /// - /// [`visit_str`]: #method.visit_str - #[inline] - fn visit_char<E>(self, v: char) -> Result<Self::Value, E> - where - E: Error, - { - self.visit_str(utf8::encode(v).as_str()) - } - - /// The input contains a string. The lifetime of the string is ephemeral and - /// it may be destroyed after this method returns. - /// - /// This method allows the `Deserializer` to avoid a copy by retaining - /// ownership of any buffered data. `Deserialize` implementations that do - /// not benefit from taking ownership of `String` data should indicate that - /// to the deserializer by using `Deserializer::deserialize_str` rather than - /// `Deserializer::deserialize_string`. - /// - /// It is never correct to implement `visit_string` without implementing - /// `visit_str`. Implement neither, both, or just `visit_str`. - fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> - where - E: Error, - { - Err(Error::invalid_type(Unexpected::Str(v), &self)) - } - - /// The input contains a string that lives at least as long as the - /// `Deserializer`. - /// - /// This enables zero-copy deserialization of strings in some formats. For - /// example JSON input containing the JSON string `"borrowed"` can be - /// deserialized with zero copying into a `&'a str` as long as the input - /// data outlives `'a`. - /// - /// The default implementation forwards to `visit_str`. - #[inline] - fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E> - where - E: Error, - { - self.visit_str(v) - } - - /// The input contains a string and ownership of the string is being given - /// to the `Visitor`. - /// - /// This method allows the `Visitor` to avoid a copy by taking ownership of - /// a string created by the `Deserializer`. `Deserialize` implementations - /// that benefit from taking ownership of `String` data should indicate that - /// to the deserializer by using `Deserializer::deserialize_string` rather - /// than `Deserializer::deserialize_str`, although not every deserializer - /// will honor such a request. - /// - /// It is never correct to implement `visit_string` without implementing - /// `visit_str`. Implement neither, both, or just `visit_str`. - /// - /// The default implementation forwards to `visit_str` and then drops the - /// `String`. - #[inline] - #[cfg(any(feature = "std", feature = "alloc"))] - fn visit_string<E>(self, v: String) -> Result<Self::Value, E> - where - E: Error, - { - self.visit_str(&v) - } - - /// The input contains a byte array. The lifetime of the byte array is - /// ephemeral and it may be destroyed after this method returns. - /// - /// This method allows the `Deserializer` to avoid a copy by retaining - /// ownership of any buffered data. `Deserialize` implementations that do - /// not benefit from taking ownership of `Vec<u8>` data should indicate that - /// to the deserializer by using `Deserializer::deserialize_bytes` rather - /// than `Deserializer::deserialize_byte_buf`. - /// - /// It is never correct to implement `visit_byte_buf` without implementing - /// `visit_bytes`. Implement neither, both, or just `visit_bytes`. - fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> - where - E: Error, - { - let _ = v; - Err(Error::invalid_type(Unexpected::Bytes(v), &self)) - } - - /// The input contains a byte array that lives at least as long as the - /// `Deserializer`. - /// - /// This enables zero-copy deserialization of bytes in some formats. For - /// example Bincode data containing bytes can be deserialized with zero - /// copying into a `&'a [u8]` as long as the input data outlives `'a`. - /// - /// The default implementation forwards to `visit_bytes`. - #[inline] - fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E> - where - E: Error, - { - self.visit_bytes(v) - } - - /// The input contains a byte array and ownership of the byte array is being - /// given to the `Visitor`. - /// - /// This method allows the `Visitor` to avoid a copy by taking ownership of - /// a byte buffer created by the `Deserializer`. `Deserialize` - /// implementations that benefit from taking ownership of `Vec<u8>` data - /// should indicate that to the deserializer by using - /// `Deserializer::deserialize_byte_buf` rather than - /// `Deserializer::deserialize_bytes`, although not every deserializer will - /// honor such a request. - /// - /// It is never correct to implement `visit_byte_buf` without implementing - /// `visit_bytes`. Implement neither, both, or just `visit_bytes`. - /// - /// The default implementation forwards to `visit_bytes` and then drops the - /// `Vec<u8>`. - #[cfg(any(feature = "std", feature = "alloc"))] - fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> - where - E: Error, - { - self.visit_bytes(&v) - } - - /// The input contains an optional that is absent. - /// - /// The default implementation fails with a type error. - fn visit_none<E>(self) -> Result<Self::Value, E> - where - E: Error, - { - Err(Error::invalid_type(Unexpected::Option, &self)) - } - - /// The input contains an optional that is present. - /// - /// The default implementation fails with a type error. - fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - let _ = deserializer; - Err(Error::invalid_type(Unexpected::Option, &self)) - } - - /// The input contains a unit `()`. - /// - /// The default implementation fails with a type error. - fn visit_unit<E>(self) -> Result<Self::Value, E> - where - E: Error, - { - Err(Error::invalid_type(Unexpected::Unit, &self)) - } - - /// The input contains a newtype struct. - /// - /// The content of the newtype struct may be read from the given - /// `Deserializer`. - /// - /// The default implementation fails with a type error. - fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - let _ = deserializer; - Err(Error::invalid_type(Unexpected::NewtypeStruct, &self)) - } - - /// The input contains a sequence of elements. - /// - /// The default implementation fails with a type error. - fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error> - where - A: SeqAccess<'de>, - { - let _ = seq; - Err(Error::invalid_type(Unexpected::Seq, &self)) - } - - /// The input contains a key-value map. - /// - /// The default implementation fails with a type error. - fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error> - where - A: MapAccess<'de>, - { - let _ = map; - Err(Error::invalid_type(Unexpected::Map, &self)) - } - - /// The input contains an enum. - /// - /// The default implementation fails with a type error. - fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error> - where - A: EnumAccess<'de>, - { - let _ = data; - Err(Error::invalid_type(Unexpected::Enum, &self)) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// Provides a `Visitor` access to each element of a sequence in the input. -/// -/// This is a trait that a `Deserializer` passes to a `Visitor` implementation, -/// which deserializes each item in a sequence. -pub trait SeqAccess<'de> { - /// The error type that can be returned if some error occurs during - /// deserialization. - type Error: Error; - - /// This returns `Ok(Some(value))` for the next value in the sequence, or - /// `Ok(None)` if there are no more remaining items. - /// - /// `Deserialize` implementations should typically use - /// `SeqAccess::next_element` instead. - fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> - where - T: DeserializeSeed<'de>; - - /// This returns `Ok(Some(value))` for the next value in the sequence, or - /// `Ok(None)` if there are no more remaining items. - /// - /// This method exists as a convenience for `Deserialize` implementations. - /// `SeqAccess` implementations should not override the default behavior. - #[inline] - fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error> - where - T: Deserialize<'de>, - { - self.next_element_seed(PhantomData) - } - - /// Returns the number of elements remaining in the sequence, if known. - #[inline] - fn size_hint(&self) -> Option<usize> { - None - } -} - -impl<'de, 'a, A> SeqAccess<'de> for &'a mut A -where - A: SeqAccess<'de>, -{ - type Error = A::Error; - - #[inline] - fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> - where - T: DeserializeSeed<'de>, - { - (**self).next_element_seed(seed) - } - - #[inline] - fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error> - where - T: Deserialize<'de>, - { - (**self).next_element() - } - - #[inline] - fn size_hint(&self) -> Option<usize> { - (**self).size_hint() - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// Provides a `Visitor` access to each entry of a map in the input. -/// -/// This is a trait that a `Deserializer` passes to a `Visitor` implementation. -pub trait MapAccess<'de> { - /// The error type that can be returned if some error occurs during - /// deserialization. - type Error: Error; - - /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)` - /// if there are no more remaining entries. - /// - /// `Deserialize` implementations should typically use - /// `MapAccess::next_key` or `MapAccess::next_entry` instead. - fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> - where - K: DeserializeSeed<'de>; - - /// This returns a `Ok(value)` for the next value in the map. - /// - /// `Deserialize` implementations should typically use - /// `MapAccess::next_value` instead. - /// - /// # Panics - /// - /// Calling `next_value_seed` before `next_key_seed` is incorrect and is - /// allowed to panic or return bogus results. - fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> - where - V: DeserializeSeed<'de>; - - /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in - /// the map, or `Ok(None)` if there are no more remaining items. - /// - /// `MapAccess` implementations should override the default behavior if a - /// more efficient implementation is possible. - /// - /// `Deserialize` implementations should typically use - /// `MapAccess::next_entry` instead. - #[inline] - fn next_entry_seed<K, V>( - &mut self, - kseed: K, - vseed: V, - ) -> Result<Option<(K::Value, V::Value)>, Self::Error> - where - K: DeserializeSeed<'de>, - V: DeserializeSeed<'de>, - { - match try!(self.next_key_seed(kseed)) { - Some(key) => { - let value = try!(self.next_value_seed(vseed)); - Ok(Some((key, value))) - } - None => Ok(None), - } - } - - /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)` - /// if there are no more remaining entries. - /// - /// This method exists as a convenience for `Deserialize` implementations. - /// `MapAccess` implementations should not override the default behavior. - #[inline] - fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error> - where - K: Deserialize<'de>, - { - self.next_key_seed(PhantomData) - } - - /// This returns a `Ok(value)` for the next value in the map. - /// - /// This method exists as a convenience for `Deserialize` implementations. - /// `MapAccess` implementations should not override the default behavior. - /// - /// # Panics - /// - /// Calling `next_value` before `next_key` is incorrect and is allowed to - /// panic or return bogus results. - #[inline] - fn next_value<V>(&mut self) -> Result<V, Self::Error> - where - V: Deserialize<'de>, - { - self.next_value_seed(PhantomData) - } - - /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in - /// the map, or `Ok(None)` if there are no more remaining items. - /// - /// This method exists as a convenience for `Deserialize` implementations. - /// `MapAccess` implementations should not override the default behavior. - #[inline] - fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error> - where - K: Deserialize<'de>, - V: Deserialize<'de>, - { - self.next_entry_seed(PhantomData, PhantomData) - } - - /// Returns the number of entries remaining in the map, if known. - #[inline] - fn size_hint(&self) -> Option<usize> { - None - } -} - -impl<'de, 'a, A> MapAccess<'de> for &'a mut A -where - A: MapAccess<'de>, -{ - type Error = A::Error; - - #[inline] - fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> - where - K: DeserializeSeed<'de>, - { - (**self).next_key_seed(seed) - } - - #[inline] - fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> - where - V: DeserializeSeed<'de>, - { - (**self).next_value_seed(seed) - } - - #[inline] - fn next_entry_seed<K, V>( - &mut self, - kseed: K, - vseed: V, - ) -> Result<Option<(K::Value, V::Value)>, Self::Error> - where - K: DeserializeSeed<'de>, - V: DeserializeSeed<'de>, - { - (**self).next_entry_seed(kseed, vseed) - } - - #[inline] - fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error> - where - K: Deserialize<'de>, - V: Deserialize<'de>, - { - (**self).next_entry() - } - - #[inline] - fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error> - where - K: Deserialize<'de>, - { - (**self).next_key() - } - - #[inline] - fn next_value<V>(&mut self) -> Result<V, Self::Error> - where - V: Deserialize<'de>, - { - (**self).next_value() - } - - #[inline] - fn size_hint(&self) -> Option<usize> { - (**self).size_hint() - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// Provides a `Visitor` access to the data of an enum in the input. -/// -/// `EnumAccess` is created by the `Deserializer` and passed to the -/// `Visitor` in order to identify which variant of an enum to deserialize. -pub trait EnumAccess<'de>: Sized { - /// The error type that can be returned if some error occurs during - /// deserialization. - type Error: Error; - /// The `Visitor` that will be used to deserialize the content of the enum - /// variant. - type Variant: VariantAccess<'de, Error = Self::Error>; - - /// `variant` is called to identify which variant to deserialize. - /// - /// `Deserialize` implementations should typically use `EnumAccess::variant` - /// instead. - fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> - where - V: DeserializeSeed<'de>; - - /// `variant` is called to identify which variant to deserialize. - /// - /// This method exists as a convenience for `Deserialize` implementations. - /// `EnumAccess` implementations should not override the default behavior. - #[inline] - fn variant<V>(self) -> Result<(V, Self::Variant), Self::Error> - where - V: Deserialize<'de>, - { - self.variant_seed(PhantomData) - } -} - -/// `VariantAccess` is a visitor that is created by the `Deserializer` and -/// passed to the `Deserialize` to deserialize the content of a particular enum -/// variant. -pub trait VariantAccess<'de>: Sized { - /// The error type that can be returned if some error occurs during - /// deserialization. Must match the error type of our `EnumAccess`. - type Error: Error; - - /// Called when deserializing a variant with no values. - /// - /// If the data contains a different type of variant, the following - /// `invalid_type` error should be constructed: - /// - /// ```rust - /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; - /// # - /// # struct X; - /// # - /// # impl<'de> VariantAccess<'de> for X { - /// # type Error = value::Error; - /// # - /// fn unit_variant(self) -> Result<(), Self::Error> { - /// // What the data actually contained; suppose it is a tuple variant. - /// let unexp = Unexpected::TupleVariant; - /// Err(de::Error::invalid_type(unexp, &"unit variant")) - /// } - /// # - /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error> - /// # where T: DeserializeSeed<'de> - /// # { unimplemented!() } - /// # - /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error> - /// # where V: Visitor<'de> - /// # { unimplemented!() } - /// # - /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error> - /// # where V: Visitor<'de> - /// # { unimplemented!() } - /// # } - /// ``` - fn unit_variant(self) -> Result<(), Self::Error>; - - /// Called when deserializing a variant with a single value. - /// - /// `Deserialize` implementations should typically use - /// `VariantAccess::newtype_variant` instead. - /// - /// If the data contains a different type of variant, the following - /// `invalid_type` error should be constructed: - /// - /// ```rust - /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; - /// # - /// # struct X; - /// # - /// # impl<'de> VariantAccess<'de> for X { - /// # type Error = value::Error; - /// # - /// # fn unit_variant(self) -> Result<(), Self::Error> { - /// # unimplemented!() - /// # } - /// # - /// fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error> - /// where T: DeserializeSeed<'de> - /// { - /// // What the data actually contained; suppose it is a unit variant. - /// let unexp = Unexpected::UnitVariant; - /// Err(de::Error::invalid_type(unexp, &"newtype variant")) - /// } - /// # - /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error> - /// # where V: Visitor<'de> - /// # { unimplemented!() } - /// # - /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error> - /// # where V: Visitor<'de> - /// # { unimplemented!() } - /// # } - /// ``` - fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error> - where - T: DeserializeSeed<'de>; - - /// Called when deserializing a variant with a single value. - /// - /// This method exists as a convenience for `Deserialize` implementations. - /// `VariantAccess` implementations should not override the default - /// behavior. - #[inline] - fn newtype_variant<T>(self) -> Result<T, Self::Error> - where - T: Deserialize<'de>, - { - self.newtype_variant_seed(PhantomData) - } - - /// Called when deserializing a tuple-like variant. - /// - /// The `len` is the number of fields expected in the tuple variant. - /// - /// If the data contains a different type of variant, the following - /// `invalid_type` error should be constructed: - /// - /// ```rust - /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; - /// # - /// # struct X; - /// # - /// # impl<'de> VariantAccess<'de> for X { - /// # type Error = value::Error; - /// # - /// # fn unit_variant(self) -> Result<(), Self::Error> { - /// # unimplemented!() - /// # } - /// # - /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error> - /// # where T: DeserializeSeed<'de> - /// # { unimplemented!() } - /// # - /// fn tuple_variant<V>(self, - /// _len: usize, - /// _visitor: V) -> Result<V::Value, Self::Error> - /// where V: Visitor<'de> - /// { - /// // What the data actually contained; suppose it is a unit variant. - /// let unexp = Unexpected::UnitVariant; - /// Err(de::Error::invalid_type(unexp, &"tuple variant")) - /// } - /// # - /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error> - /// # where V: Visitor<'de> - /// # { unimplemented!() } - /// # } - /// ``` - fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; - - /// Called when deserializing a struct-like variant. - /// - /// The `fields` are the names of the fields of the struct variant. - /// - /// If the data contains a different type of variant, the following - /// `invalid_type` error should be constructed: - /// - /// ```rust - /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; - /// # - /// # struct X; - /// # - /// # impl<'de> VariantAccess<'de> for X { - /// # type Error = value::Error; - /// # - /// # fn unit_variant(self) -> Result<(), Self::Error> { - /// # unimplemented!() - /// # } - /// # - /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error> - /// # where T: DeserializeSeed<'de> - /// # { unimplemented!() } - /// # - /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error> - /// # where V: Visitor<'de> - /// # { unimplemented!() } - /// # - /// fn struct_variant<V>(self, - /// _fields: &'static [&'static str], - /// _visitor: V) -> Result<V::Value, Self::Error> - /// where V: Visitor<'de> - /// { - /// // What the data actually contained; suppose it is a unit variant. - /// let unexp = Unexpected::UnitVariant; - /// Err(de::Error::invalid_type(unexp, &"struct variant")) - /// } - /// # } - /// ``` - fn struct_variant<V>( - self, - fields: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>; -} - -//////////////////////////////////////////////////////////////////////////////// - -/// Converts an existing value into a `Deserializer` from which other values can -/// be deserialized. -/// -/// ```rust -/// #[macro_use] -/// extern crate serde_derive; -/// -/// extern crate serde; -/// -/// use std::str::FromStr; -/// use serde::de::{value, Deserialize, IntoDeserializer}; -/// -/// #[derive(Deserialize)] -/// enum Setting { -/// On, -/// Off, -/// } -/// -/// impl FromStr for Setting { -/// type Err = value::Error; -/// -/// fn from_str(s: &str) -> Result<Self, Self::Err> { -/// Self::deserialize(s.into_deserializer()) -/// } -/// } -/// # -/// # fn main() {} -/// ``` -pub trait IntoDeserializer<'de, E: Error = value::Error> { - /// The type of the deserializer being converted into. - type Deserializer: Deserializer<'de, Error = E>; - - /// Convert this value into a deserializer. - fn into_deserializer(self) -> Self::Deserializer; -} - -//////////////////////////////////////////////////////////////////////////////// - -/// Used in error messages. -/// -/// - expected `a` -/// - expected `a` or `b` -/// - expected one of `a`, `b`, `c` -/// -/// The slice of names must not be empty. -struct OneOf { - names: &'static [&'static str], -} - -impl Display for OneOf { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match self.names.len() { - 0 => panic!(), // special case elsewhere - 1 => write!(formatter, "`{}`", self.names[0]), - 2 => write!(formatter, "`{}` or `{}`", self.names[0], self.names[1]), - _ => { - try!(write!(formatter, "one of ")); - for (i, alt) in self.names.iter().enumerate() { - if i > 0 { - try!(write!(formatter, ", ")); - } - try!(write!(formatter, "`{}`", alt)); - } - Ok(()) - } - } - } -} diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/de/utf8.rs cargo-0.26.0/vendor/serde-1.0.27/src/de/utf8.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/de/utf8.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/de/utf8.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,54 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use lib::*; - -const TAG_CONT: u8 = 0b1000_0000; -const TAG_TWO_B: u8 = 0b1100_0000; -const TAG_THREE_B: u8 = 0b1110_0000; -const TAG_FOUR_B: u8 = 0b1111_0000; -const MAX_ONE_B: u32 = 0x80; -const MAX_TWO_B: u32 = 0x800; -const MAX_THREE_B: u32 = 0x10000; - -#[inline] -pub fn encode(c: char) -> Encode { - let code = c as u32; - let mut buf = [0; 4]; - let pos = if code < MAX_ONE_B { - buf[3] = code as u8; - 3 - } else if code < MAX_TWO_B { - buf[2] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B; - buf[3] = (code & 0x3F) as u8 | TAG_CONT; - 2 - } else if code < MAX_THREE_B { - buf[1] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B; - buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; - buf[3] = (code & 0x3F) as u8 | TAG_CONT; - 1 - } else { - buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B; - buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; - buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; - buf[3] = (code & 0x3F) as u8 | TAG_CONT; - 0 - }; - Encode { buf: buf, pos: pos } -} - -pub struct Encode { - buf: [u8; 4], - pos: usize, -} - -impl Encode { - pub fn as_str(&self) -> &str { - str::from_utf8(&self.buf[self.pos..]).unwrap() - } -} diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/de/value.rs cargo-0.26.0/vendor/serde-1.0.27/src/de/value.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/de/value.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/de/value.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1303 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Building blocks for deserializing basic values using the `IntoDeserializer` -//! trait. -//! -//! ```rust -//! #[macro_use] -//! extern crate serde_derive; -//! -//! extern crate serde; -//! -//! use std::str::FromStr; -//! use serde::de::{value, Deserialize, IntoDeserializer}; -//! -//! #[derive(Deserialize)] -//! enum Setting { -//! On, -//! Off, -//! } -//! -//! impl FromStr for Setting { -//! type Err = value::Error; -//! -//! fn from_str(s: &str) -> Result<Self, Self::Err> { -//! Self::deserialize(s.into_deserializer()) -//! } -//! } -//! # -//! # fn main() {} -//! ``` - -use lib::*; - -use de::{self, Expected, IntoDeserializer, SeqAccess}; -use private::de::size_hint; -use ser; -use self::private::{First, Second}; - -//////////////////////////////////////////////////////////////////////////////// - -/// A minimal representation of all possible errors that can occur using the -/// `IntoDeserializer` trait. -#[derive(Clone, Debug, PartialEq)] -pub struct Error { - err: ErrorImpl, -} - -#[cfg(any(feature = "std", feature = "alloc"))] -type ErrorImpl = Box<str>; -#[cfg(not(any(feature = "std", feature = "alloc")))] -type ErrorImpl = (); - -impl de::Error for Error { - #[cfg(any(feature = "std", feature = "alloc"))] - fn custom<T>(msg: T) -> Self - where - T: Display, - { - Error { - err: msg.to_string().into_boxed_str(), - } - } - - #[cfg(not(any(feature = "std", feature = "alloc")))] - fn custom<T>(msg: T) -> Self - where - T: Display, - { - let _ = msg; - Error { err: () } - } -} - -impl ser::Error for Error { - fn custom<T>(msg: T) -> Self - where - T: Display, - { - de::Error::custom(msg) - } -} - -impl Display for Error { - #[cfg(any(feature = "std", feature = "alloc"))] - fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { - formatter.write_str(&self.err) - } - - #[cfg(not(any(feature = "std", feature = "alloc")))] - fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { - formatter.write_str("Serde deserialization error") - } -} - -#[cfg(feature = "std")] -impl error::Error for Error { - fn description(&self) -> &str { - &self.err - } -} - -//////////////////////////////////////////////////////////////////////////////// - -impl<'de, E> IntoDeserializer<'de, E> for () -where - E: de::Error, -{ - type Deserializer = UnitDeserializer<E>; - - fn into_deserializer(self) -> UnitDeserializer<E> { - UnitDeserializer { - marker: PhantomData, - } - } -} - -/// A deserializer holding a `()`. -#[derive(Clone, Debug)] -pub struct UnitDeserializer<E> { - marker: PhantomData<E>, -} - -impl<'de, E> de::Deserializer<'de> for UnitDeserializer<E> -where - E: de::Error, -{ - type Error = E; - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf unit unit_struct newtype_struct seq tuple tuple_struct map - struct enum identifier ignored_any - } - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - visitor.visit_unit() - } - - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - visitor.visit_none() - } -} - -//////////////////////////////////////////////////////////////////////////////// - -macro_rules! primitive_deserializer { - ($ty:ty, $doc:tt, $name:ident, $method:ident $($cast:tt)*) => { - #[doc = "A deserializer holding"] - #[doc = $doc] - #[derive(Clone, Debug)] - pub struct $name<E> { - value: $ty, - marker: PhantomData<E> - } - - impl<'de, E> IntoDeserializer<'de, E> for $ty - where - E: de::Error, - { - type Deserializer = $name<E>; - - fn into_deserializer(self) -> $name<E> { - $name { - value: self, - marker: PhantomData, - } - } - } - - impl<'de, E> de::Deserializer<'de> for $name<E> - where - E: de::Error, - { - type Error = E; - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any - } - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - visitor.$method(self.value $($cast)*) - } - } - } -} - -primitive_deserializer!(bool, "a `bool`.", BoolDeserializer, visit_bool); -primitive_deserializer!(i8, "an `i8`.", I8Deserializer, visit_i8); -primitive_deserializer!(i16, "an `i16`.", I16Deserializer, visit_i16); -primitive_deserializer!(i32, "an `i32`.", I32Deserializer, visit_i32); -primitive_deserializer!(i64, "an `i64`.", I64Deserializer, visit_i64); -primitive_deserializer!(isize, "an `isize`.", IsizeDeserializer, visit_i64 as i64); -primitive_deserializer!(u8, "a `u8`.", U8Deserializer, visit_u8); -primitive_deserializer!(u16, "a `u16`.", U16Deserializer, visit_u16); -primitive_deserializer!(u64, "a `u64`.", U64Deserializer, visit_u64); -primitive_deserializer!(usize, "a `usize`.", UsizeDeserializer, visit_u64 as u64); -primitive_deserializer!(f32, "an `f32`.", F32Deserializer, visit_f32); -primitive_deserializer!(f64, "an `f64`.", F64Deserializer, visit_f64); -primitive_deserializer!(char, "a `char`.", CharDeserializer, visit_char); - -/// A deserializer holding a `u32`. -#[derive(Clone, Debug)] -pub struct U32Deserializer<E> { - value: u32, - marker: PhantomData<E>, -} - -impl<'de, E> IntoDeserializer<'de, E> for u32 -where - E: de::Error, -{ - type Deserializer = U32Deserializer<E>; - - fn into_deserializer(self) -> U32Deserializer<E> { - U32Deserializer { - value: self, - marker: PhantomData, - } - } -} - -impl<'de, E> de::Deserializer<'de> for U32Deserializer<E> -where - E: de::Error, -{ - type Error = E; - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct - map struct identifier ignored_any - } - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - visitor.visit_u32(self.value) - } - - fn deserialize_enum<V>( - self, - name: &str, - variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - let _ = name; - let _ = variants; - visitor.visit_enum(self) - } -} - -impl<'de, E> de::EnumAccess<'de> for U32Deserializer<E> -where - E: de::Error, -{ - type Error = E; - type Variant = private::UnitOnly<E>; - - fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> - where - T: de::DeserializeSeed<'de>, - { - seed.deserialize(self).map(private::unit_only) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// A deserializer holding a `&str`. -#[derive(Clone, Debug)] -pub struct StrDeserializer<'a, E> { - value: &'a str, - marker: PhantomData<E>, -} - -impl<'de, 'a, E> IntoDeserializer<'de, E> for &'a str -where - E: de::Error, -{ - type Deserializer = StrDeserializer<'a, E>; - - fn into_deserializer(self) -> StrDeserializer<'a, E> { - StrDeserializer { - value: self, - marker: PhantomData, - } - } -} - -impl<'de, 'a, E> de::Deserializer<'de> for StrDeserializer<'a, E> -where - E: de::Error, -{ - type Error = E; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - visitor.visit_str(self.value) - } - - fn deserialize_enum<V>( - self, - name: &str, - variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - let _ = name; - let _ = variants; - visitor.visit_enum(self) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct - map struct identifier ignored_any - } -} - -impl<'de, 'a, E> de::EnumAccess<'de> for StrDeserializer<'a, E> -where - E: de::Error, -{ - type Error = E; - type Variant = private::UnitOnly<E>; - - fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> - where - T: de::DeserializeSeed<'de>, - { - seed.deserialize(self).map(private::unit_only) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// A deserializer holding a `&str` with a lifetime tied to another -/// deserializer. -#[derive(Clone, Debug)] -pub struct BorrowedStrDeserializer<'de, E> { - value: &'de str, - marker: PhantomData<E>, -} - -impl<'de, E> BorrowedStrDeserializer<'de, E> { - /// Create a new borrowed deserializer from the given string. - pub fn new(value: &'de str) -> BorrowedStrDeserializer<'de, E> { - BorrowedStrDeserializer { - value: value, - marker: PhantomData, - } - } -} - -impl<'de, E> de::Deserializer<'de> for BorrowedStrDeserializer<'de, E> -where - E: de::Error, -{ - type Error = E; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - visitor.visit_borrowed_str(self.value) - } - - fn deserialize_enum<V>( - self, - name: &str, - variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - let _ = name; - let _ = variants; - visitor.visit_enum(self) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct - map struct identifier ignored_any - } -} - -impl<'de, E> de::EnumAccess<'de> for BorrowedStrDeserializer<'de, E> -where - E: de::Error, -{ - type Error = E; - type Variant = private::UnitOnly<E>; - - fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> - where - T: de::DeserializeSeed<'de>, - { - seed.deserialize(self).map(private::unit_only) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// A deserializer holding a `String`. -#[cfg(any(feature = "std", feature = "alloc"))] -#[derive(Clone, Debug)] -pub struct StringDeserializer<E> { - value: String, - marker: PhantomData<E>, -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'de, E> IntoDeserializer<'de, E> for String -where - E: de::Error, -{ - type Deserializer = StringDeserializer<E>; - - fn into_deserializer(self) -> StringDeserializer<E> { - StringDeserializer { - value: self, - marker: PhantomData, - } - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'de, E> de::Deserializer<'de> for StringDeserializer<E> -where - E: de::Error, -{ - type Error = E; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - visitor.visit_string(self.value) - } - - fn deserialize_enum<V>( - self, - name: &str, - variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - let _ = name; - let _ = variants; - visitor.visit_enum(self) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct - map struct identifier ignored_any - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'de, 'a, E> de::EnumAccess<'de> for StringDeserializer<E> -where - E: de::Error, -{ - type Error = E; - type Variant = private::UnitOnly<E>; - - fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> - where - T: de::DeserializeSeed<'de>, - { - seed.deserialize(self).map(private::unit_only) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// A deserializer holding a `Cow<str>`. -#[cfg(any(feature = "std", feature = "alloc"))] -#[derive(Clone, Debug)] -pub struct CowStrDeserializer<'a, E> { - value: Cow<'a, str>, - marker: PhantomData<E>, -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'de, 'a, E> IntoDeserializer<'de, E> for Cow<'a, str> -where - E: de::Error, -{ - type Deserializer = CowStrDeserializer<'a, E>; - - fn into_deserializer(self) -> CowStrDeserializer<'a, E> { - CowStrDeserializer { - value: self, - marker: PhantomData, - } - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'de, 'a, E> de::Deserializer<'de> for CowStrDeserializer<'a, E> -where - E: de::Error, -{ - type Error = E; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - match self.value { - Cow::Borrowed(string) => visitor.visit_str(string), - Cow::Owned(string) => visitor.visit_string(string), - } - } - - fn deserialize_enum<V>( - self, - name: &str, - variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - let _ = name; - let _ = variants; - visitor.visit_enum(self) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct - map struct identifier ignored_any - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'de, 'a, E> de::EnumAccess<'de> for CowStrDeserializer<'a, E> -where - E: de::Error, -{ - type Error = E; - type Variant = private::UnitOnly<E>; - - fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> - where - T: de::DeserializeSeed<'de>, - { - seed.deserialize(self).map(private::unit_only) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// A deserializer holding a `&[u8]` with a lifetime tied to another -/// deserializer. -#[derive(Clone, Debug)] -pub struct BorrowedBytesDeserializer<'de, E> { - value: &'de [u8], - marker: PhantomData<E>, -} - -impl<'de, E> BorrowedBytesDeserializer<'de, E> { - /// Create a new borrowed deserializer from the given byte slice. - pub fn new(value: &'de [u8]) -> BorrowedBytesDeserializer<'de, E> { - BorrowedBytesDeserializer { - value: value, - marker: PhantomData, - } - } -} - -impl<'de, E> de::Deserializer<'de> for BorrowedBytesDeserializer<'de, E> -where - E: de::Error, -{ - type Error = E; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - visitor.visit_borrowed_bytes(self.value) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct - map struct identifier ignored_any enum - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// A deserializer that iterates over a sequence. -#[derive(Clone, Debug)] -pub struct SeqDeserializer<I, E> { - iter: iter::Fuse<I>, - count: usize, - marker: PhantomData<E>, -} - -impl<I, E> SeqDeserializer<I, E> -where - I: Iterator, -{ - /// Construct a new `SeqDeserializer<I, E>`. - pub fn new(iter: I) -> Self { - SeqDeserializer { - iter: iter.fuse(), - count: 0, - marker: PhantomData, - } - } -} - -impl<I, E> SeqDeserializer<I, E> -where - I: Iterator, - E: de::Error, -{ - /// Check for remaining elements after passing a `SeqDeserializer` to - /// `Visitor::visit_seq`. - pub fn end(mut self) -> Result<(), E> { - let mut remaining = 0; - while self.iter.next().is_some() { - remaining += 1; - } - if remaining == 0 { - Ok(()) - } else { - // First argument is the number of elements in the data, second - // argument is the number of elements expected by the Deserialize. - Err(de::Error::invalid_length( - self.count + remaining, - &ExpectedInSeq(self.count), - )) - } - } -} - -impl<'de, I, T, E> de::Deserializer<'de> for SeqDeserializer<I, E> -where - I: Iterator<Item = T>, - T: IntoDeserializer<'de, E>, - E: de::Error, -{ - type Error = E; - - fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - let v = try!(visitor.visit_seq(&mut self)); - try!(self.end()); - Ok(v) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct - map struct enum identifier ignored_any - } -} - -impl<'de, I, T, E> de::SeqAccess<'de> for SeqDeserializer<I, E> -where - I: Iterator<Item = T>, - T: IntoDeserializer<'de, E>, - E: de::Error, -{ - type Error = E; - - fn next_element_seed<V>(&mut self, seed: V) -> Result<Option<V::Value>, Self::Error> - where - V: de::DeserializeSeed<'de>, - { - match self.iter.next() { - Some(value) => { - self.count += 1; - seed.deserialize(value.into_deserializer()).map(Some) - } - None => Ok(None), - } - } - - fn size_hint(&self) -> Option<usize> { - size_hint::from_bounds(&self.iter) - } -} - -struct ExpectedInSeq(usize); - -impl Expected for ExpectedInSeq { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - if self.0 == 1 { - write!(formatter, "1 element in sequence") - } else { - write!(formatter, "{} elements in sequence", self.0) - } - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'de, T, E> IntoDeserializer<'de, E> for Vec<T> -where - T: IntoDeserializer<'de, E>, - E: de::Error, -{ - type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>; - - fn into_deserializer(self) -> Self::Deserializer { - SeqDeserializer::new(self.into_iter()) - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'de, T, E> IntoDeserializer<'de, E> for BTreeSet<T> -where - T: IntoDeserializer<'de, E> + Eq + Ord, - E: de::Error, -{ - type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>; - - fn into_deserializer(self) -> Self::Deserializer { - SeqDeserializer::new(self.into_iter()) - } -} - -#[cfg(feature = "std")] -impl<'de, T, S, E> IntoDeserializer<'de, E> for HashSet<T, S> -where - T: IntoDeserializer<'de, E> + Eq + Hash, - S: BuildHasher, - E: de::Error, -{ - type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>; - - fn into_deserializer(self) -> Self::Deserializer { - SeqDeserializer::new(self.into_iter()) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// A deserializer holding a `SeqAccess`. -#[derive(Clone, Debug)] -pub struct SeqAccessDeserializer<A> { - seq: A, -} - -impl<A> SeqAccessDeserializer<A> { - /// Construct a new `SeqAccessDeserializer<A>`. - pub fn new(seq: A) -> Self { - SeqAccessDeserializer { seq: seq } - } -} - -impl<'de, A> de::Deserializer<'de> for SeqAccessDeserializer<A> -where - A: de::SeqAccess<'de>, -{ - type Error = A::Error; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - visitor.visit_seq(self.seq) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct - map struct enum identifier ignored_any - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// A deserializer that iterates over a map. -pub struct MapDeserializer<'de, I, E> -where - I: Iterator, - I::Item: private::Pair, -{ - iter: iter::Fuse<I>, - value: Option<Second<I::Item>>, - count: usize, - lifetime: PhantomData<&'de ()>, - error: PhantomData<E>, -} - -impl<'de, I, E> MapDeserializer<'de, I, E> -where - I: Iterator, - I::Item: private::Pair, -{ - /// Construct a new `MapDeserializer<I, E>`. - pub fn new(iter: I) -> Self { - MapDeserializer { - iter: iter.fuse(), - value: None, - count: 0, - lifetime: PhantomData, - error: PhantomData, - } - } -} - -impl<'de, I, E> MapDeserializer<'de, I, E> -where - I: Iterator, - I::Item: private::Pair, - E: de::Error, -{ - /// Check for remaining elements after passing a `MapDeserializer` to - /// `Visitor::visit_map`. - pub fn end(mut self) -> Result<(), E> { - let mut remaining = 0; - while self.iter.next().is_some() { - remaining += 1; - } - if remaining == 0 { - Ok(()) - } else { - // First argument is the number of elements in the data, second - // argument is the number of elements expected by the Deserialize. - Err(de::Error::invalid_length( - self.count + remaining, - &ExpectedInMap(self.count), - )) - } - } -} - -impl<'de, I, E> MapDeserializer<'de, I, E> -where - I: Iterator, - I::Item: private::Pair, -{ - fn next_pair(&mut self) -> Option<(First<I::Item>, Second<I::Item>)> { - match self.iter.next() { - Some(kv) => { - self.count += 1; - Some(private::Pair::split(kv)) - } - None => None, - } - } -} - -impl<'de, I, E> de::Deserializer<'de> for MapDeserializer<'de, I, E> -where - I: Iterator, - I::Item: private::Pair, - First<I::Item>: IntoDeserializer<'de, E>, - Second<I::Item>: IntoDeserializer<'de, E>, - E: de::Error, -{ - type Error = E; - - fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - let value = try!(visitor.visit_map(&mut self)); - try!(self.end()); - Ok(value) - } - - fn deserialize_seq<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - let value = try!(visitor.visit_seq(&mut self)); - try!(self.end()); - Ok(value) - } - - fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - let _ = len; - self.deserialize_seq(visitor) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct tuple_struct map struct - enum identifier ignored_any - } -} - -impl<'de, I, E> de::MapAccess<'de> for MapDeserializer<'de, I, E> -where - I: Iterator, - I::Item: private::Pair, - First<I::Item>: IntoDeserializer<'de, E>, - Second<I::Item>: IntoDeserializer<'de, E>, - E: de::Error, -{ - type Error = E; - - fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> - where - T: de::DeserializeSeed<'de>, - { - match self.next_pair() { - Some((key, value)) => { - self.value = Some(value); - seed.deserialize(key.into_deserializer()).map(Some) - } - None => Ok(None), - } - } - - fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error> - where - T: de::DeserializeSeed<'de>, - { - let value = self.value.take(); - // Panic because this indicates a bug in the program rather than an - // expected failure. - let value = value.expect("MapAccess::visit_value called before visit_key"); - seed.deserialize(value.into_deserializer()) - } - - fn next_entry_seed<TK, TV>( - &mut self, - kseed: TK, - vseed: TV, - ) -> Result<Option<(TK::Value, TV::Value)>, Self::Error> - where - TK: de::DeserializeSeed<'de>, - TV: de::DeserializeSeed<'de>, - { - match self.next_pair() { - Some((key, value)) => { - let key = try!(kseed.deserialize(key.into_deserializer())); - let value = try!(vseed.deserialize(value.into_deserializer())); - Ok(Some((key, value))) - } - None => Ok(None), - } - } - - fn size_hint(&self) -> Option<usize> { - size_hint::from_bounds(&self.iter) - } -} - -impl<'de, I, E> de::SeqAccess<'de> for MapDeserializer<'de, I, E> -where - I: Iterator, - I::Item: private::Pair, - First<I::Item>: IntoDeserializer<'de, E>, - Second<I::Item>: IntoDeserializer<'de, E>, - E: de::Error, -{ - type Error = E; - - fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> - where - T: de::DeserializeSeed<'de>, - { - match self.next_pair() { - Some((k, v)) => { - let de = PairDeserializer(k, v, PhantomData); - seed.deserialize(de).map(Some) - } - None => Ok(None), - } - } - - fn size_hint(&self) -> Option<usize> { - size_hint::from_bounds(&self.iter) - } -} - -// Cannot #[derive(Clone)] because of the bound `Second<I::Item>: Clone`. -impl<'de, I, E> Clone for MapDeserializer<'de, I, E> -where - I: Iterator + Clone, - I::Item: private::Pair, - Second<I::Item>: Clone, -{ - fn clone(&self) -> Self { - MapDeserializer { - iter: self.iter.clone(), - value: self.value.clone(), - count: self.count, - lifetime: self.lifetime, - error: self.error, - } - } -} - -// Cannot #[derive(Debug)] because of the bound `Second<I::Item>: Debug`. -impl<'de, I, E> Debug for MapDeserializer<'de, I, E> -where - I: Iterator + Debug, - I::Item: private::Pair, - Second<I::Item>: Debug, -{ - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter - .debug_struct("MapDeserializer") - .field("iter", &self.iter) - .field("value", &self.value) - .field("count", &self.count) - .field("lifetime", &self.lifetime) - .field("error", &self.error) - .finish() - } -} - -// Used in the `impl SeqAccess for MapDeserializer` to visit the map as a -// sequence of pairs. -struct PairDeserializer<A, B, E>(A, B, PhantomData<E>); - -impl<'de, A, B, E> de::Deserializer<'de> for PairDeserializer<A, B, E> -where - A: IntoDeserializer<'de, E>, - B: IntoDeserializer<'de, E>, - E: de::Error, -{ - type Error = E; - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct tuple_struct map struct - enum identifier ignored_any - } - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - self.deserialize_seq(visitor) - } - - fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData); - let pair = try!(visitor.visit_seq(&mut pair_visitor)); - if pair_visitor.1.is_none() { - Ok(pair) - } else { - let remaining = pair_visitor.size_hint().unwrap(); - // First argument is the number of elements in the data, second - // argument is the number of elements expected by the Deserialize. - Err(de::Error::invalid_length(2, &ExpectedInSeq(2 - remaining))) - } - } - - fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - if len == 2 { - self.deserialize_seq(visitor) - } else { - // First argument is the number of elements in the data, second - // argument is the number of elements expected by the Deserialize. - Err(de::Error::invalid_length(2, &ExpectedInSeq(len))) - } - } -} - -struct PairVisitor<A, B, E>(Option<A>, Option<B>, PhantomData<E>); - -impl<'de, A, B, E> de::SeqAccess<'de> for PairVisitor<A, B, E> -where - A: IntoDeserializer<'de, E>, - B: IntoDeserializer<'de, E>, - E: de::Error, -{ - type Error = E; - - fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> - where - T: de::DeserializeSeed<'de>, - { - if let Some(k) = self.0.take() { - seed.deserialize(k.into_deserializer()).map(Some) - } else if let Some(v) = self.1.take() { - seed.deserialize(v.into_deserializer()).map(Some) - } else { - Ok(None) - } - } - - fn size_hint(&self) -> Option<usize> { - if self.0.is_some() { - Some(2) - } else if self.1.is_some() { - Some(1) - } else { - Some(0) - } - } -} - -struct ExpectedInMap(usize); - -impl Expected for ExpectedInMap { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - if self.0 == 1 { - write!(formatter, "1 element in map") - } else { - write!(formatter, "{} elements in map", self.0) - } - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(any(feature = "std", feature = "alloc"))] -impl<'de, K, V, E> IntoDeserializer<'de, E> for BTreeMap<K, V> -where - K: IntoDeserializer<'de, E> + Eq + Ord, - V: IntoDeserializer<'de, E>, - E: de::Error, -{ - type Deserializer = MapDeserializer<'de, <Self as IntoIterator>::IntoIter, E>; - - fn into_deserializer(self) -> Self::Deserializer { - MapDeserializer::new(self.into_iter()) - } -} - -#[cfg(feature = "std")] -impl<'de, K, V, S, E> IntoDeserializer<'de, E> for HashMap<K, V, S> -where - K: IntoDeserializer<'de, E> + Eq + Hash, - V: IntoDeserializer<'de, E>, - S: BuildHasher, - E: de::Error, -{ - type Deserializer = MapDeserializer<'de, <Self as IntoIterator>::IntoIter, E>; - - fn into_deserializer(self) -> Self::Deserializer { - MapDeserializer::new(self.into_iter()) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// A deserializer holding a `MapAccess`. -#[derive(Clone, Debug)] -pub struct MapAccessDeserializer<A> { - map: A, -} - -impl<A> MapAccessDeserializer<A> { - /// Construct a new `MapAccessDeserializer<A>`. - pub fn new(map: A) -> Self { - MapAccessDeserializer { map: map } - } -} - -impl<'de, A> de::Deserializer<'de> for MapAccessDeserializer<A> -where - A: de::MapAccess<'de>, -{ - type Error = A::Error; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - visitor.visit_map(self.map) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct - map struct enum identifier ignored_any - } -} - -//////////////////////////////////////////////////////////////////////////////// - -mod private { - use lib::*; - - use de::{self, Unexpected}; - - #[derive(Clone, Debug)] - pub struct UnitOnly<E> { - marker: PhantomData<E>, - } - - pub fn unit_only<T, E>(t: T) -> (T, UnitOnly<E>) { - ( - t, - UnitOnly { - marker: PhantomData, - }, - ) - } - - impl<'de, E> de::VariantAccess<'de> for UnitOnly<E> - where - E: de::Error, - { - type Error = E; - - fn unit_variant(self) -> Result<(), Self::Error> { - Ok(()) - } - - fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error> - where - T: de::DeserializeSeed<'de>, - { - Err(de::Error::invalid_type( - Unexpected::UnitVariant, - &"newtype variant", - )) - } - - fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - Err(de::Error::invalid_type( - Unexpected::UnitVariant, - &"tuple variant", - )) - } - - fn struct_variant<V>( - self, - _fields: &'static [&'static str], - _visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - Err(de::Error::invalid_type( - Unexpected::UnitVariant, - &"struct variant", - )) - } - } - - /// Avoid having to restate the generic types on `MapDeserializer`. The - /// `Iterator::Item` contains enough information to figure out K and V. - pub trait Pair { - type First; - type Second; - fn split(self) -> (Self::First, Self::Second); - } - - impl<A, B> Pair for (A, B) { - type First = A; - type Second = B; - fn split(self) -> (A, B) { - self - } - } - - pub type First<T> = <T as Pair>::First; - pub type Second<T> = <T as Pair>::Second; -} diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/export.rs cargo-0.26.0/vendor/serde-1.0.27/src/export.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/export.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/export.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,41 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -pub use lib::clone::Clone; -pub use lib::convert::{From, Into}; -pub use lib::default::Default; -pub use lib::fmt::{self, Formatter}; -pub use lib::marker::PhantomData; -pub use lib::option::Option::{self, None, Some}; -pub use lib::result::Result::{self, Err, Ok}; - -pub use self::string::from_utf8_lossy; - -mod string { - use lib::*; - - #[cfg(any(feature = "std", feature = "alloc"))] - pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<str> { - String::from_utf8_lossy(bytes) - } - - // The generated code calls this like: - // - // let value = &_serde::export::from_utf8_lossy(bytes); - // Err(_serde::de::Error::unknown_variant(value, VARIANTS)) - // - // so it is okay for the return type to be different from the std case as long - // as the above works. - #[cfg(not(any(feature = "std", feature = "alloc")))] - pub fn from_utf8_lossy(bytes: &[u8]) -> &str { - // Three unicode replacement characters if it fails. They look like a - // white-on-black question mark. The user will recognize it as invalid - // UTF-8. - str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}") - } -} diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/lib.rs cargo-0.26.0/vendor/serde-1.0.27/src/lib.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,280 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! # Serde -//! -//! Serde is a framework for ***ser***ializing and ***de***serializing Rust data -//! structures efficiently and generically. -//! -//! The Serde ecosystem consists of data structures that know how to serialize -//! and deserialize themselves along with data formats that know how to -//! serialize and deserialize other things. Serde provides the layer by which -//! these two groups interact with each other, allowing any supported data -//! structure to be serialized and deserialized using any supported data format. -//! -//! See the Serde website [https://serde.rs/] for additional documentation and -//! usage examples. -//! -//! [https://serde.rs/]: https://serde.rs/ -//! -//! ## Design -//! -//! Where many other languages rely on runtime reflection for serializing data, -//! Serde is instead built on Rust's powerful trait system. A data structure -//! that knows how to serialize and deserialize itself is one that implements -//! Serde's `Serialize` and `Deserialize` traits (or uses Serde's derive -//! attribute to automatically generate implementations at compile time). This -//! avoids any overhead of reflection or runtime type information. In fact in -//! many situations the interaction between data structure and data format can -//! be completely optimized away by the Rust compiler, leaving Serde -//! serialization to perform the same speed as a handwritten serializer for the -//! specific selection of data structure and data format. -//! -//! ## Data formats -//! -//! The following is a partial list of data formats that have been implemented -//! for Serde by the community. -//! -//! - [JSON], the ubiquitous JavaScript Object Notation used by many HTTP APIs. -//! - [Bincode], a compact binary format -//! used for IPC within the Servo rendering engine. -//! - [CBOR], a Concise Binary Object Representation designed for small message -//! size without the need for version negotiation. -//! - [YAML], a popular human-friendly configuration language that ain't markup -//! language. -//! - [MessagePack], an efficient binary format that resembles a compact JSON. -//! - [TOML], a minimal configuration format used by [Cargo]. -//! - [Pickle], a format common in the Python world. -//! - [Hjson], a variant of JSON designed to be readable and writable by humans. -//! - [BSON], the data storage and network transfer format used by MongoDB. -//! - [URL], the x-www-form-urlencoded format. -//! - [XML], the flexible machine-friendly W3C standard. -//! *(deserialization only)* -//! - [Envy], a way to deserialize environment variables into Rust structs. -//! *(deserialization only)* -//! - [Redis], deserialize values from Redis when using [redis-rs]. -//! *(deserialization only)* -//! -//! [JSON]: https://github.com/serde-rs/json -//! [Bincode]: https://github.com/TyOverby/bincode -//! [CBOR]: https://github.com/pyfisch/cbor -//! [YAML]: https://github.com/dtolnay/serde-yaml -//! [MessagePack]: https://github.com/3Hren/msgpack-rust -//! [TOML]: https://github.com/alexcrichton/toml-rs -//! [Pickle]: https://github.com/birkenfeld/serde-pickle -//! [Hjson]: https://github.com/laktak/hjson-rust -//! [BSON]: https://github.com/zonyitoo/bson-rs -//! [URL]: https://github.com/nox/serde_urlencoded -//! [XML]: https://github.com/RReverser/serde-xml-rs -//! [Envy]: https://github.com/softprops/envy -//! [Redis]: https://github.com/OneSignal/serde-redis -//! [Cargo]: http://doc.crates.io/manifest.html -//! [redis-rs]: https://crates.io/crates/redis - -//////////////////////////////////////////////////////////////////////////////// - -// Serde types in rustdoc of other crates get linked to here. -#![doc(html_root_url = "https://docs.rs/serde/1.0.27")] -// Support using Serde without the standard library! -#![cfg_attr(not(feature = "std"), no_std)] -// Unstable functionality only if the user asks for it. For tracking and -// discussion of these features please refer to this issue: -// -// https://github.com/serde-rs/serde/issues/812 -#![cfg_attr(feature = "unstable", feature(nonzero, specialization))] -#![cfg_attr(feature = "alloc", feature(alloc))] -#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))] -// Whitelisted clippy lints -#![cfg_attr(feature = "cargo-clippy", - allow(cast_lossless, const_static_lifetime, doc_markdown, linkedlist, - needless_pass_by_value, type_complexity, unreadable_literal, - zero_prefixed_literal))] -// Whitelisted clippy_pedantic lints -#![cfg_attr(feature = "cargo-clippy", allow( -// integer and float ser/de requires these sorts of casts - cast_possible_truncation, - cast_possible_wrap, - cast_precision_loss, - cast_sign_loss, -// simplifies some macros - invalid_upcast_comparisons, -// things are often more readable this way - option_unwrap_used, - result_unwrap_used, - shadow_reuse, - single_match_else, - stutter, - use_self, -// not practical - missing_docs_in_private_items, -// alternative is not stable - empty_enum, - use_debug, -))] -// Blacklisted Rust lints. -#![deny(missing_docs, unused_imports)] - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "alloc")] -extern crate alloc; - -#[cfg(all(feature = "unstable", feature = "std"))] -extern crate core; - -/// A facade around all the types we need from the `std`, `core`, and `alloc` -/// crates. This avoids elaborate import wrangling having to happen in every -/// module. -mod lib { - mod core { - #[cfg(feature = "std")] - pub use std::*; - #[cfg(not(feature = "std"))] - pub use core::*; - } - - pub use self::core::{cmp, iter, mem, ops, slice, str}; - pub use self::core::{isize, i16, i32, i64, i8}; - pub use self::core::{usize, u16, u32, u64, u8}; - pub use self::core::{f32, f64}; - - pub use self::core::cell::{Cell, RefCell}; - pub use self::core::clone::{self, Clone}; - pub use self::core::convert::{self, From, Into}; - pub use self::core::default::{self, Default}; - pub use self::core::fmt::{self, Debug, Display}; - pub use self::core::marker::{self, PhantomData}; - pub use self::core::option::{self, Option}; - pub use self::core::result::{self, Result}; - - #[cfg(feature = "std")] - pub use std::borrow::{Cow, ToOwned}; - #[cfg(all(feature = "alloc", not(feature = "std")))] - pub use alloc::borrow::{Cow, ToOwned}; - - #[cfg(feature = "std")] - pub use std::string::String; - #[cfg(all(feature = "alloc", not(feature = "std")))] - pub use alloc::string::{String, ToString}; - - #[cfg(feature = "std")] - pub use std::vec::Vec; - #[cfg(all(feature = "alloc", not(feature = "std")))] - pub use alloc::vec::Vec; - - #[cfg(feature = "std")] - pub use std::boxed::Box; - #[cfg(all(feature = "alloc", not(feature = "std")))] - pub use alloc::boxed::Box; - - #[cfg(all(feature = "rc", feature = "std"))] - pub use std::rc::Rc; - #[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))] - pub use alloc::rc::Rc; - - #[cfg(all(feature = "rc", feature = "std"))] - pub use std::sync::Arc; - #[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))] - pub use alloc::arc::Arc; - - #[cfg(feature = "std")] - pub use std::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; - #[cfg(all(feature = "alloc", not(feature = "std")))] - pub use alloc::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; - - #[cfg(feature = "std")] - pub use std::{error, net}; - - #[cfg(feature = "std")] - pub use std::collections::{HashMap, HashSet}; - #[cfg(feature = "std")] - pub use std::ffi::{CStr, CString, OsStr, OsString}; - #[cfg(feature = "std")] - pub use std::hash::{BuildHasher, Hash}; - #[cfg(feature = "std")] - pub use std::io::Write; - #[cfg(feature = "std")] - pub use std::num::Wrapping; - #[cfg(feature = "std")] - pub use std::path::{Path, PathBuf}; - #[cfg(feature = "std")] - pub use std::time::{Duration, SystemTime, UNIX_EPOCH}; - #[cfg(feature = "std")] - pub use std::sync::{Mutex, RwLock}; - - #[cfg(feature = "unstable")] - pub use core::nonzero::{NonZero, Zeroable}; -} - -//////////////////////////////////////////////////////////////////////////////// - -#[macro_use] -mod macros; - -pub mod ser; -pub mod de; - -#[doc(inline)] -pub use ser::{Serialize, Serializer}; -#[doc(inline)] -pub use de::{Deserialize, Deserializer}; - -// Generated code uses these to support no_std. Not public API. -#[doc(hidden)] -pub mod export; - -// Helpers used by generated code and doc tests. Not public API. -#[doc(hidden)] -pub mod private; - -// Re-export #[derive(Serialize, Deserialize)]. -// -// This is a workaround for https://github.com/rust-lang/cargo/issues/1286. -// Without this re-export, crates that put Serde derives behind a cfg_attr would -// need to use some silly feature name that depends on both serde and -// serde_derive. -// -// [features] -// serde-impls = ["serde", "serde_derive"] -// -// [dependencies] -// serde = { version = "1.0", optional = true } -// serde_derive = { version = "1.0", optional = true } -// -// # Used like this: -// # #[cfg(feature = "serde-impls")] -// # #[macro_use] -// # extern crate serde_derive; -// # -// # #[cfg_attr(feature = "serde-impls", derive(Serialize, Deserialize))] -// # struct S { /* ... */ } -// -// The re-exported derives allow crates to use "serde" as the name of their -// Serde feature which is more intuitive. -// -// [dependencies] -// serde = { version = "1.0", optional = true, features = ["derive"] } -// -// # Used like this: -// # #[cfg(feature = "serde")] -// # #[macro_use] -// # extern crate serde; -// # -// # #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -// # struct S { /* ... */ } -// -// The reason re-exporting is not enabled by default is that disabling it would -// be annoying for crates that provide handwritten impls or data formats. They -// would need to disable default features and then explicitly re-enable std. -#[cfg(feature = "serde_derive")] -#[allow(unused_imports)] -#[macro_use] -extern crate serde_derive; -#[cfg(feature = "serde_derive")] -#[doc(hidden)] -pub use serde_derive::*; diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/macros.rs cargo-0.26.0/vendor/serde-1.0.27/src/macros.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/macros.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/macros.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,242 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// Super explicit first paragraph because this shows up at the top level and -// trips up people who are just looking for basic Serialize / Deserialize -// documentation. -// -/// Helper macro when implementing the `Deserializer` part of a new data format -/// for Serde. -/// -/// Some [`Deserializer`] implementations for self-describing formats do not -/// care what hint the [`Visitor`] gives them, they just want to blindly call -/// the [`Visitor`] method corresponding to the data they can tell is in the -/// input. This requires repetitive implementations of all the [`Deserializer`] -/// trait methods. -/// -/// ```rust -/// # #[macro_use] -/// # extern crate serde; -/// # -/// # use serde::de::{value, Deserializer, Visitor}; -/// # -/// # struct MyDeserializer; -/// # -/// # impl<'de> Deserializer<'de> for MyDeserializer { -/// # type Error = value::Error; -/// # -/// # fn deserialize_any<V>(self, _: V) -> Result<V::Value, Self::Error> -/// # where V: Visitor<'de> -/// # { -/// # unimplemented!() -/// # } -/// # -/// #[inline] -/// fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> -/// where V: Visitor<'de> -/// { -/// self.deserialize_any(visitor) -/// } -/// # -/// # forward_to_deserialize_any! { -/// # i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes -/// # byte_buf option unit unit_struct newtype_struct seq tuple -/// # tuple_struct map struct enum identifier ignored_any -/// # } -/// # } -/// # -/// # fn main() {} -/// ``` -/// -/// The `forward_to_deserialize_any!` macro implements these simple forwarding -/// methods so that they forward directly to [`Deserializer::deserialize_any`]. -/// You can choose which methods to forward. -/// -/// ```rust -/// # #[macro_use] -/// # extern crate serde; -/// # -/// # use serde::de::{value, Deserializer, Visitor}; -/// # -/// # struct MyDeserializer; -/// # -/// impl<'de> Deserializer<'de> for MyDeserializer { -/// # type Error = value::Error; -/// # -/// fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> -/// where V: Visitor<'de> -/// { -/// /* ... */ -/// # let _ = visitor; -/// # unimplemented!() -/// } -/// -/// forward_to_deserialize_any! { -/// bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes -/// byte_buf option unit unit_struct newtype_struct seq tuple -/// tuple_struct map struct enum identifier ignored_any -/// } -/// } -/// # -/// # fn main() {} -/// ``` -/// -/// The macro assumes the convention that your `Deserializer` lifetime parameter -/// is called `'de` and that the `Visitor` type parameters on each method are -/// called `V`. A different type parameter and a different lifetime can be -/// specified explicitly if necessary. -/// -/// ```rust -/// # #[macro_use] -/// # extern crate serde; -/// # -/// # use std::marker::PhantomData; -/// # -/// # use serde::de::{value, Deserializer, Visitor}; -/// # -/// # struct MyDeserializer<V>(PhantomData<V>); -/// # -/// # impl<'q, V> Deserializer<'q> for MyDeserializer<V> { -/// # type Error = value::Error; -/// # -/// # fn deserialize_any<W>(self, visitor: W) -> Result<W::Value, Self::Error> -/// # where W: Visitor<'q> -/// # { -/// # unimplemented!() -/// # } -/// # -/// forward_to_deserialize_any! { -/// <W: Visitor<'q>> -/// bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes -/// byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct -/// map struct enum identifier ignored_any -/// } -/// # } -/// # -/// # fn main() {} -/// ``` -/// -/// [`Deserializer`]: trait.Deserializer.html -/// [`Visitor`]: de/trait.Visitor.html -/// [`Deserializer::deserialize_any`]: trait.Deserializer.html#tymethod.deserialize_any -#[macro_export] -macro_rules! forward_to_deserialize_any { - (<$visitor:ident: Visitor<$lifetime:tt>> $($func:ident)*) => { - $(forward_to_deserialize_any_helper!{$func<$lifetime, $visitor>})* - }; - // This case must be after the previous one. - ($($func:ident)*) => { - $(forward_to_deserialize_any_helper!{$func<'de, V>})* - }; -} - -#[doc(hidden)] -#[macro_export] -macro_rules! forward_to_deserialize_any_method { - ($func:ident<$l:tt, $v:ident>($($arg:ident : $ty:ty),*)) => { - #[inline] - fn $func<$v>(self, $($arg: $ty,)* visitor: $v) -> $crate::export::Result<$v::Value, Self::Error> - where - $v: $crate::de::Visitor<$l>, - { - $( - let _ = $arg; - )* - self.deserialize_any(visitor) - } - }; -} - -#[doc(hidden)] -#[macro_export] -macro_rules! forward_to_deserialize_any_helper { - (bool<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_bool<$l, $v>()} - }; - (i8<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_i8<$l, $v>()} - }; - (i16<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_i16<$l, $v>()} - }; - (i32<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_i32<$l, $v>()} - }; - (i64<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_i64<$l, $v>()} - }; - (u8<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_u8<$l, $v>()} - }; - (u16<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_u16<$l, $v>()} - }; - (u32<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_u32<$l, $v>()} - }; - (u64<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_u64<$l, $v>()} - }; - (f32<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_f32<$l, $v>()} - }; - (f64<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_f64<$l, $v>()} - }; - (char<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_char<$l, $v>()} - }; - (str<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_str<$l, $v>()} - }; - (string<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_string<$l, $v>()} - }; - (bytes<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_bytes<$l, $v>()} - }; - (byte_buf<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_byte_buf<$l, $v>()} - }; - (option<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_option<$l, $v>()} - }; - (unit<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_unit<$l, $v>()} - }; - (unit_struct<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_unit_struct<$l, $v>(name: &'static str)} - }; - (newtype_struct<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_newtype_struct<$l, $v>(name: &'static str)} - }; - (seq<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_seq<$l, $v>()} - }; - (tuple<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_tuple<$l, $v>(len: usize)} - }; - (tuple_struct<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_tuple_struct<$l, $v>(name: &'static str, len: usize)} - }; - (map<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_map<$l, $v>()} - }; - (struct<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_struct<$l, $v>(name: &'static str, fields: &'static [&'static str])} - }; - (enum<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_enum<$l, $v>(name: &'static str, variants: &'static [&'static str])} - }; - (identifier<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_identifier<$l, $v>()} - }; - (ignored_any<$l:tt, $v:ident>) => { - forward_to_deserialize_any_method!{deserialize_ignored_any<$l, $v>()} - }; -} diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/private/de.rs cargo-0.26.0/vendor/serde-1.0.27/src/private/de.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/private/de.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/private/de.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2064 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use lib::*; - -use de::{Deserialize, DeserializeSeed, Deserializer, Error, IntoDeserializer, Visitor}; - -#[cfg(any(feature = "std", feature = "alloc"))] -use de::Unexpected; - -#[cfg(any(feature = "std", feature = "alloc"))] -pub use self::content::{Content, ContentDeserializer, ContentRefDeserializer, - InternallyTaggedUnitVisitor, TagContentOtherField, - TagContentOtherFieldVisitor, TagOrContentField, TagOrContentFieldVisitor, - TaggedContentVisitor, UntaggedUnitVisitor}; - -/// If the missing field is of type `Option<T>` then treat is as `None`, -/// otherwise it is an error. -pub fn missing_field<'de, V, E>(field: &'static str) -> Result<V, E> -where - V: Deserialize<'de>, - E: Error, -{ - struct MissingFieldDeserializer<E>(&'static str, PhantomData<E>); - - impl<'de, E> Deserializer<'de> for MissingFieldDeserializer<E> - where - E: Error, - { - type Error = E; - - fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, E> - where - V: Visitor<'de>, - { - Err(Error::missing_field(self.0)) - } - - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E> - where - V: Visitor<'de>, - { - visitor.visit_none() - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf unit unit_struct newtype_struct seq tuple tuple_struct map - struct enum identifier ignored_any - } - } - - let deserializer = MissingFieldDeserializer(field, PhantomData); - Deserialize::deserialize(deserializer) -} - -#[cfg(any(feature = "std", feature = "alloc"))] -pub fn borrow_cow_str<'de: 'a, 'a, D>(deserializer: D) -> Result<Cow<'a, str>, D::Error> -where - D: Deserializer<'de>, -{ - struct CowStrVisitor; - - impl<'a> Visitor<'a> for CowStrVisitor { - type Value = Cow<'a, str>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a string") - } - - fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> - where - E: Error, - { - Ok(Cow::Owned(v.to_owned())) - } - - fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> - where - E: Error, - { - Ok(Cow::Borrowed(v)) - } - - fn visit_string<E>(self, v: String) -> Result<Self::Value, E> - where - E: Error, - { - Ok(Cow::Owned(v)) - } - - fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> - where - E: Error, - { - match str::from_utf8(v) { - Ok(s) => Ok(Cow::Owned(s.to_owned())), - Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), - } - } - - fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> - where - E: Error, - { - match str::from_utf8(v) { - Ok(s) => Ok(Cow::Borrowed(s)), - Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), - } - } - - fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> - where - E: Error, - { - match String::from_utf8(v) { - Ok(s) => Ok(Cow::Owned(s)), - Err(e) => Err(Error::invalid_value( - Unexpected::Bytes(&e.into_bytes()), - &self, - )), - } - } - } - - deserializer.deserialize_str(CowStrVisitor) -} - -#[cfg(any(feature = "std", feature = "alloc"))] -pub fn borrow_cow_bytes<'de: 'a, 'a, D>(deserializer: D) -> Result<Cow<'a, [u8]>, D::Error> -where - D: Deserializer<'de>, -{ - struct CowBytesVisitor; - - impl<'a> Visitor<'a> for CowBytesVisitor { - type Value = Cow<'a, [u8]>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a byte array") - } - - fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> - where - E: Error, - { - Ok(Cow::Owned(v.as_bytes().to_vec())) - } - - fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> - where - E: Error, - { - Ok(Cow::Borrowed(v.as_bytes())) - } - - fn visit_string<E>(self, v: String) -> Result<Self::Value, E> - where - E: Error, - { - Ok(Cow::Owned(v.into_bytes())) - } - - fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> - where - E: Error, - { - Ok(Cow::Owned(v.to_vec())) - } - - fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> - where - E: Error, - { - Ok(Cow::Borrowed(v)) - } - - fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> - where - E: Error, - { - Ok(Cow::Owned(v)) - } - } - - deserializer.deserialize_str(CowBytesVisitor) -} - -pub mod size_hint { - use lib::*; - - pub fn from_bounds<I>(iter: &I) -> Option<usize> - where - I: Iterator, - { - helper(iter.size_hint()) - } - - #[inline] - pub fn cautious(hint: Option<usize>) -> usize { - cmp::min(hint.unwrap_or(0), 4096) - } - - fn helper(bounds: (usize, Option<usize>)) -> Option<usize> { - match bounds { - (lower, Some(upper)) if lower == upper => Some(upper), - _ => None, - } - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -mod content { - // This module is private and nothing here should be used outside of - // generated code. - // - // We will iterate on the implementation for a few releases and only have to - // worry about backward compatibility for the `untagged` and `tag` attributes - // rather than for this entire mechanism. - // - // This issue is tracking making some of this stuff public: - // https://github.com/serde-rs/serde/issues/741 - - use lib::*; - - use de::{self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, MapAccess, SeqAccess, - Unexpected, Visitor}; - use super::size_hint; - - /// Used from generated code to buffer the contents of the Deserializer when - /// deserializing untagged enums and internally tagged enums. - /// - /// Not public API. Use serde-value instead. - #[derive(Debug)] - pub enum Content<'de> { - Bool(bool), - - U8(u8), - U16(u16), - U32(u32), - U64(u64), - - I8(i8), - I16(i16), - I32(i32), - I64(i64), - - F32(f32), - F64(f64), - - Char(char), - String(String), - Str(&'de str), - ByteBuf(Vec<u8>), - Bytes(&'de [u8]), - - None, - Some(Box<Content<'de>>), - - Unit, - Newtype(Box<Content<'de>>), - Seq(Vec<Content<'de>>), - Map(Vec<(Content<'de>, Content<'de>)>), - } - - impl<'de> Content<'de> { - fn unexpected(&self) -> Unexpected { - match *self { - Content::Bool(b) => Unexpected::Bool(b), - Content::U8(n) => Unexpected::Unsigned(n as u64), - Content::U16(n) => Unexpected::Unsigned(n as u64), - Content::U32(n) => Unexpected::Unsigned(n as u64), - Content::U64(n) => Unexpected::Unsigned(n), - Content::I8(n) => Unexpected::Signed(n as i64), - Content::I16(n) => Unexpected::Signed(n as i64), - Content::I32(n) => Unexpected::Signed(n as i64), - Content::I64(n) => Unexpected::Signed(n), - Content::F32(f) => Unexpected::Float(f as f64), - Content::F64(f) => Unexpected::Float(f), - Content::Char(c) => Unexpected::Char(c), - Content::String(ref s) => Unexpected::Str(s), - Content::Str(s) => Unexpected::Str(s), - Content::ByteBuf(ref b) => Unexpected::Bytes(b), - Content::Bytes(b) => Unexpected::Bytes(b), - Content::None | Content::Some(_) => Unexpected::Option, - Content::Unit => Unexpected::Unit, - Content::Newtype(_) => Unexpected::NewtypeStruct, - Content::Seq(_) => Unexpected::Seq, - Content::Map(_) => Unexpected::Map, - } - } - } - - impl<'de> Deserialize<'de> for Content<'de> { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: Deserializer<'de>, - { - // Untagged and internally tagged enums are only supported in - // self-describing formats. - let visitor = ContentVisitor { value: PhantomData }; - deserializer.deserialize_any(visitor) - } - } - - struct ContentVisitor<'de> { - value: PhantomData<Content<'de>>, - } - - impl<'de> ContentVisitor<'de> { - fn new() -> Self { - ContentVisitor { value: PhantomData } - } - } - - impl<'de> Visitor<'de> for ContentVisitor<'de> { - type Value = Content<'de>; - - fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.write_str("any value") - } - - fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::Bool(value)) - } - - fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::I8(value)) - } - - fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::I16(value)) - } - - fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::I32(value)) - } - - fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::I64(value)) - } - - fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::U8(value)) - } - - fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::U16(value)) - } - - fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::U32(value)) - } - - fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::U64(value)) - } - - fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::F32(value)) - } - - fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::F64(value)) - } - - fn visit_char<F>(self, value: char) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::Char(value)) - } - - fn visit_str<F>(self, value: &str) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::String(value.into())) - } - - fn visit_borrowed_str<F>(self, value: &'de str) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::Str(value)) - } - - fn visit_string<F>(self, value: String) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::String(value)) - } - - fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::ByteBuf(value.into())) - } - - fn visit_borrowed_bytes<F>(self, value: &'de [u8]) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::Bytes(value)) - } - - fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::ByteBuf(value)) - } - - fn visit_unit<F>(self) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::Unit) - } - - fn visit_none<F>(self) -> Result<Self::Value, F> - where - F: de::Error, - { - Ok(Content::None) - } - - fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v))) - } - - fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v))) - } - - fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> - where - V: SeqAccess<'de>, - { - let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint())); - while let Some(e) = try!(visitor.next_element()) { - vec.push(e); - } - Ok(Content::Seq(vec)) - } - - fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> - where - V: MapAccess<'de>, - { - let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint())); - while let Some(kv) = try!(visitor.next_entry()) { - vec.push(kv); - } - Ok(Content::Map(vec)) - } - - fn visit_enum<V>(self, _visitor: V) -> Result<Self::Value, V::Error> - where - V: EnumAccess<'de>, - { - Err(de::Error::custom( - "untagged and internally tagged enums do not support enum input", - )) - } - } - - /// This is the type of the map keys in an internally tagged enum. - /// - /// Not public API. - pub enum TagOrContent<'de> { - Tag, - Content(Content<'de>), - } - - struct TagOrContentVisitor<'de> { - name: &'static str, - value: PhantomData<TagOrContent<'de>>, - } - - impl<'de> TagOrContentVisitor<'de> { - fn new(name: &'static str) -> Self { - TagOrContentVisitor { - name: name, - value: PhantomData, - } - } - } - - impl<'de> DeserializeSeed<'de> for TagOrContentVisitor<'de> { - type Value = TagOrContent<'de>; - - fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - // Internally tagged enums are only supported in self-describing - // formats. - deserializer.deserialize_any(self) - } - } - - impl<'de> Visitor<'de> for TagOrContentVisitor<'de> { - type Value = TagOrContent<'de>; - - fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - write!(fmt, "a type tag `{}` or any other value", self.name) - } - - fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_bool(value) - .map(TagOrContent::Content) - } - - fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_i8(value) - .map(TagOrContent::Content) - } - - fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_i16(value) - .map(TagOrContent::Content) - } - - fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_i32(value) - .map(TagOrContent::Content) - } - - fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_i64(value) - .map(TagOrContent::Content) - } - - fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_u8(value) - .map(TagOrContent::Content) - } - - fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_u16(value) - .map(TagOrContent::Content) - } - - fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_u32(value) - .map(TagOrContent::Content) - } - - fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_u64(value) - .map(TagOrContent::Content) - } - - fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_f32(value) - .map(TagOrContent::Content) - } - - fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_f64(value) - .map(TagOrContent::Content) - } - - fn visit_char<F>(self, value: char) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_char(value) - .map(TagOrContent::Content) - } - - fn visit_str<F>(self, value: &str) -> Result<Self::Value, F> - where - F: de::Error, - { - if value == self.name { - Ok(TagOrContent::Tag) - } else { - ContentVisitor::new() - .visit_str(value) - .map(TagOrContent::Content) - } - } - - fn visit_borrowed_str<F>(self, value: &'de str) -> Result<Self::Value, F> - where - F: de::Error, - { - if value == self.name { - Ok(TagOrContent::Tag) - } else { - ContentVisitor::new() - .visit_borrowed_str(value) - .map(TagOrContent::Content) - } - } - - fn visit_string<F>(self, value: String) -> Result<Self::Value, F> - where - F: de::Error, - { - if value == self.name { - Ok(TagOrContent::Tag) - } else { - ContentVisitor::new() - .visit_string(value) - .map(TagOrContent::Content) - } - } - - fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F> - where - F: de::Error, - { - if value == self.name.as_bytes() { - Ok(TagOrContent::Tag) - } else { - ContentVisitor::new() - .visit_bytes(value) - .map(TagOrContent::Content) - } - } - - fn visit_borrowed_bytes<F>(self, value: &'de [u8]) -> Result<Self::Value, F> - where - F: de::Error, - { - if value == self.name.as_bytes() { - Ok(TagOrContent::Tag) - } else { - ContentVisitor::new() - .visit_borrowed_bytes(value) - .map(TagOrContent::Content) - } - } - - fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F> - where - F: de::Error, - { - if value == self.name.as_bytes() { - Ok(TagOrContent::Tag) - } else { - ContentVisitor::new() - .visit_byte_buf(value) - .map(TagOrContent::Content) - } - } - - fn visit_unit<F>(self) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_unit() - .map(TagOrContent::Content) - } - - fn visit_none<F>(self) -> Result<Self::Value, F> - where - F: de::Error, - { - ContentVisitor::new() - .visit_none() - .map(TagOrContent::Content) - } - - fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - ContentVisitor::new() - .visit_some(deserializer) - .map(TagOrContent::Content) - } - - fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - ContentVisitor::new() - .visit_newtype_struct(deserializer) - .map(TagOrContent::Content) - } - - fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error> - where - V: SeqAccess<'de>, - { - ContentVisitor::new() - .visit_seq(visitor) - .map(TagOrContent::Content) - } - - fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error> - where - V: MapAccess<'de>, - { - ContentVisitor::new() - .visit_map(visitor) - .map(TagOrContent::Content) - } - - fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error> - where - V: EnumAccess<'de>, - { - ContentVisitor::new() - .visit_enum(visitor) - .map(TagOrContent::Content) - } - } - - /// Used by generated code to deserialize an internally tagged enum. - /// - /// Not public API. - pub struct TaggedContent<'de, T> { - pub tag: T, - pub content: Content<'de>, - } - - /// Not public API. - pub struct TaggedContentVisitor<'de, T> { - tag_name: &'static str, - value: PhantomData<TaggedContent<'de, T>>, - } - - impl<'de, T> TaggedContentVisitor<'de, T> { - /// Visitor for the content of an internally tagged enum with the given tag - /// name. - pub fn new(name: &'static str) -> Self { - TaggedContentVisitor { - tag_name: name, - value: PhantomData, - } - } - } - - impl<'de, T> DeserializeSeed<'de> for TaggedContentVisitor<'de, T> - where - T: Deserialize<'de>, - { - type Value = TaggedContent<'de, T>; - - fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - // Internally tagged enums are only supported in self-describing - // formats. - deserializer.deserialize_any(self) - } - } - - impl<'de, T> Visitor<'de> for TaggedContentVisitor<'de, T> - where - T: Deserialize<'de>, - { - type Value = TaggedContent<'de, T>; - - fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.write_str("internally tagged enum") - } - - fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error> - where - S: SeqAccess<'de>, - { - let tag = match try!(seq.next_element()) { - Some(tag) => tag, - None => { - return Err(de::Error::missing_field(self.tag_name)); - } - }; - let rest = de::value::SeqAccessDeserializer::new(seq); - Ok(TaggedContent { - tag: tag, - content: try!(Content::deserialize(rest)), - }) - } - - fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error> - where - M: MapAccess<'de>, - { - let mut tag = None; - let mut vec = Vec::with_capacity(size_hint::cautious(map.size_hint())); - while let Some(k) = try!(map.next_key_seed(TagOrContentVisitor::new(self.tag_name))) { - match k { - TagOrContent::Tag => { - if tag.is_some() { - return Err(de::Error::duplicate_field(self.tag_name)); - } - tag = Some(try!(map.next_value())); - } - TagOrContent::Content(k) => { - let v = try!(map.next_value()); - vec.push((k, v)); - } - } - } - match tag { - None => Err(de::Error::missing_field(self.tag_name)), - Some(tag) => Ok(TaggedContent { - tag: tag, - content: Content::Map(vec), - }), - } - } - } - - /// Used by generated code to deserialize an adjacently tagged enum. - /// - /// Not public API. - pub enum TagOrContentField { - Tag, - Content, - } - - /// Not public API. - pub struct TagOrContentFieldVisitor { - pub tag: &'static str, - pub content: &'static str, - } - - impl<'de> DeserializeSeed<'de> for TagOrContentFieldVisitor { - type Value = TagOrContentField; - - fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_str(self) - } - } - - impl<'de> Visitor<'de> for TagOrContentFieldVisitor { - type Value = TagOrContentField; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!(formatter, "{:?} or {:?}", self.tag, self.content) - } - - fn visit_str<E>(self, field: &str) -> Result<Self::Value, E> - where - E: de::Error, - { - if field == self.tag { - Ok(TagOrContentField::Tag) - } else if field == self.content { - Ok(TagOrContentField::Content) - } else { - Err(de::Error::invalid_value(Unexpected::Str(field), &self)) - } - } - } - - /// Used by generated code to deserialize an adjacently tagged enum when - /// ignoring unrelated fields is allowed. - /// - /// Not public API. - pub enum TagContentOtherField { - Tag, - Content, - Other, - } - - /// Not public API. - pub struct TagContentOtherFieldVisitor { - pub tag: &'static str, - pub content: &'static str, - } - - impl<'de> DeserializeSeed<'de> for TagContentOtherFieldVisitor { - type Value = TagContentOtherField; - - fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - deserializer.deserialize_str(self) - } - } - - impl<'de> Visitor<'de> for TagContentOtherFieldVisitor { - type Value = TagContentOtherField; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!( - formatter, - "{:?}, {:?}, or other ignored fields", - self.tag, self.content - ) - } - - fn visit_str<E>(self, field: &str) -> Result<Self::Value, E> - where - E: de::Error, - { - if field == self.tag { - Ok(TagContentOtherField::Tag) - } else if field == self.content { - Ok(TagContentOtherField::Content) - } else { - Ok(TagContentOtherField::Other) - } - } - } - - /// Not public API - pub struct ContentDeserializer<'de, E> { - content: Content<'de>, - err: PhantomData<E>, - } - - /// Used when deserializing an internally tagged enum because the content will - /// be used exactly once. - impl<'de, E> Deserializer<'de> for ContentDeserializer<'de, E> - where - E: de::Error, - { - type Error = E; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>, - { - match self.content { - Content::Bool(v) => visitor.visit_bool(v), - Content::U8(v) => visitor.visit_u8(v), - Content::U16(v) => visitor.visit_u16(v), - Content::U32(v) => visitor.visit_u32(v), - Content::U64(v) => visitor.visit_u64(v), - Content::I8(v) => visitor.visit_i8(v), - Content::I16(v) => visitor.visit_i16(v), - Content::I32(v) => visitor.visit_i32(v), - Content::I64(v) => visitor.visit_i64(v), - Content::F32(v) => visitor.visit_f32(v), - Content::F64(v) => visitor.visit_f64(v), - Content::Char(v) => visitor.visit_char(v), - Content::String(v) => visitor.visit_string(v), - Content::Str(v) => visitor.visit_borrowed_str(v), - Content::ByteBuf(v) => visitor.visit_byte_buf(v), - Content::Bytes(v) => visitor.visit_borrowed_bytes(v), - Content::Unit => visitor.visit_unit(), - Content::None => visitor.visit_none(), - Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)), - Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)), - Content::Seq(v) => { - let seq = v.into_iter().map(ContentDeserializer::new); - let mut seq_visitor = de::value::SeqDeserializer::new(seq); - let value = try!(visitor.visit_seq(&mut seq_visitor)); - try!(seq_visitor.end()); - Ok(value) - } - Content::Map(v) => { - let map = v.into_iter() - .map(|(k, v)| (ContentDeserializer::new(k), ContentDeserializer::new(v))); - let mut map_visitor = de::value::MapDeserializer::new(map); - let value = try!(visitor.visit_map(&mut map_visitor)); - try!(map_visitor.end()); - Ok(value) - } - } - } - - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>, - { - match self.content { - Content::None => visitor.visit_none(), - Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)), - Content::Unit => visitor.visit_unit(), - _ => visitor.visit_some(self), - } - } - - fn deserialize_newtype_struct<V>( - self, - _name: &str, - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>, - { - visitor.visit_newtype_struct(self) - } - - fn deserialize_enum<V>( - self, - _name: &str, - _variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>, - { - let (variant, value) = match self.content { - Content::Map(value) => { - let mut iter = value.into_iter(); - let (variant, value) = match iter.next() { - Some(v) => v, - None => { - return Err(de::Error::invalid_value( - de::Unexpected::Map, - &"map with a single key", - )); - } - }; - // enums are encoded in json as maps with a single key:value pair - if iter.next().is_some() { - return Err(de::Error::invalid_value( - de::Unexpected::Map, - &"map with a single key", - )); - } - (variant, Some(value)) - } - s @ Content::String(_) | s @ Content::Str(_) => (s, None), - other => { - return Err(de::Error::invalid_type( - other.unexpected(), - &"string or map", - )); - } - }; - - visitor.visit_enum(EnumDeserializer { - variant: variant, - value: value, - err: PhantomData, - }) - } - - fn deserialize_unit_struct<V>( - self, - _name: &'static str, - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>, - { - match self.content { - // As a special case, allow deserializing untagged newtype - // variant containing unit struct. - // - // #[derive(Deserialize)] - // struct Info; - // - // #[derive(Deserialize)] - // #[serde(tag = "topic")] - // enum Message { - // Info(Info), - // } - // - // We want {"topic":"Info"} to deserialize even though - // ordinarily unit structs do not deserialize from empty map. - Content::Map(ref v) if v.is_empty() => visitor.visit_unit(), - _ => self.deserialize_any(visitor), - } - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf unit seq tuple tuple_struct map struct identifier - ignored_any - } - } - - impl<'de, E> ContentDeserializer<'de, E> { - /// private API, don't use - pub fn new(content: Content<'de>) -> Self { - ContentDeserializer { - content: content, - err: PhantomData, - } - } - } - - struct EnumDeserializer<'de, E> - where - E: de::Error, - { - variant: Content<'de>, - value: Option<Content<'de>>, - err: PhantomData<E>, - } - - impl<'de, E> de::EnumAccess<'de> for EnumDeserializer<'de, E> - where - E: de::Error, - { - type Error = E; - type Variant = VariantDeserializer<'de, Self::Error>; - - fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), E> - where - V: de::DeserializeSeed<'de>, - { - let visitor = VariantDeserializer { - value: self.value, - err: PhantomData, - }; - seed.deserialize(ContentDeserializer::new(self.variant)) - .map(|v| (v, visitor)) - } - } - - struct VariantDeserializer<'de, E> - where - E: de::Error, - { - value: Option<Content<'de>>, - err: PhantomData<E>, - } - - impl<'de, E> de::VariantAccess<'de> for VariantDeserializer<'de, E> - where - E: de::Error, - { - type Error = E; - - fn unit_variant(self) -> Result<(), E> { - match self.value { - Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)), - None => Ok(()), - } - } - - fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E> - where - T: de::DeserializeSeed<'de>, - { - match self.value { - Some(value) => seed.deserialize(ContentDeserializer::new(value)), - None => Err(de::Error::invalid_type( - de::Unexpected::UnitVariant, - &"newtype variant", - )), - } - } - - fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - match self.value { - Some(Content::Seq(v)) => { - de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor) - } - Some(other) => Err(de::Error::invalid_type( - other.unexpected(), - &"tuple variant", - )), - None => Err(de::Error::invalid_type( - de::Unexpected::UnitVariant, - &"tuple variant", - )), - } - } - - fn struct_variant<V>( - self, - _fields: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - match self.value { - Some(Content::Map(v)) => { - de::Deserializer::deserialize_any(MapDeserializer::new(v), visitor) - } - Some(Content::Seq(v)) => { - de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor) - } - Some(other) => Err(de::Error::invalid_type( - other.unexpected(), - &"struct variant", - )), - _ => Err(de::Error::invalid_type( - de::Unexpected::UnitVariant, - &"struct variant", - )), - } - } - } - - struct SeqDeserializer<'de, E> - where - E: de::Error, - { - iter: <Vec<Content<'de>> as IntoIterator>::IntoIter, - err: PhantomData<E>, - } - - impl<'de, E> SeqDeserializer<'de, E> - where - E: de::Error, - { - fn new(vec: Vec<Content<'de>>) -> Self { - SeqDeserializer { - iter: vec.into_iter(), - err: PhantomData, - } - } - } - - impl<'de, E> de::Deserializer<'de> for SeqDeserializer<'de, E> - where - E: de::Error, - { - type Error = E; - - #[inline] - fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - let len = self.iter.len(); - if len == 0 { - visitor.visit_unit() - } else { - let ret = try!(visitor.visit_seq(&mut self)); - let remaining = self.iter.len(); - if remaining == 0 { - Ok(ret) - } else { - Err(de::Error::invalid_length(len, &"fewer elements in array")) - } - } - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any - } - } - - impl<'de, E> de::SeqAccess<'de> for SeqDeserializer<'de, E> - where - E: de::Error, - { - type Error = E; - - fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> - where - T: de::DeserializeSeed<'de>, - { - match self.iter.next() { - Some(value) => seed.deserialize(ContentDeserializer::new(value)).map(Some), - None => Ok(None), - } - } - - fn size_hint(&self) -> Option<usize> { - size_hint::from_bounds(&self.iter) - } - } - - struct MapDeserializer<'de, E> - where - E: de::Error, - { - iter: <Vec<(Content<'de>, Content<'de>)> as IntoIterator>::IntoIter, - value: Option<Content<'de>>, - err: PhantomData<E>, - } - - impl<'de, E> MapDeserializer<'de, E> - where - E: de::Error, - { - fn new(map: Vec<(Content<'de>, Content<'de>)>) -> Self { - MapDeserializer { - iter: map.into_iter(), - value: None, - err: PhantomData, - } - } - } - - impl<'de, E> de::MapAccess<'de> for MapDeserializer<'de, E> - where - E: de::Error, - { - type Error = E; - - fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> - where - T: de::DeserializeSeed<'de>, - { - match self.iter.next() { - Some((key, value)) => { - self.value = Some(value); - seed.deserialize(ContentDeserializer::new(key)).map(Some) - } - None => Ok(None), - } - } - - fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error> - where - T: de::DeserializeSeed<'de>, - { - match self.value.take() { - Some(value) => seed.deserialize(ContentDeserializer::new(value)), - None => Err(de::Error::custom("value is missing")), - } - } - - fn size_hint(&self) -> Option<usize> { - size_hint::from_bounds(&self.iter) - } - } - - impl<'de, E> de::Deserializer<'de> for MapDeserializer<'de, E> - where - E: de::Error, - { - type Error = E; - - #[inline] - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - visitor.visit_map(self) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any - } - } - - /// Not public API. - pub struct ContentRefDeserializer<'a, 'de: 'a, E> { - content: &'a Content<'de>, - err: PhantomData<E>, - } - - /// Used when deserializing an untagged enum because the content may need to be - /// used more than once. - impl<'de, 'a, E> Deserializer<'de> for ContentRefDeserializer<'a, 'de, E> - where - E: de::Error, - { - type Error = E; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, E> - where - V: Visitor<'de>, - { - match *self.content { - Content::Bool(v) => visitor.visit_bool(v), - Content::U8(v) => visitor.visit_u8(v), - Content::U16(v) => visitor.visit_u16(v), - Content::U32(v) => visitor.visit_u32(v), - Content::U64(v) => visitor.visit_u64(v), - Content::I8(v) => visitor.visit_i8(v), - Content::I16(v) => visitor.visit_i16(v), - Content::I32(v) => visitor.visit_i32(v), - Content::I64(v) => visitor.visit_i64(v), - Content::F32(v) => visitor.visit_f32(v), - Content::F64(v) => visitor.visit_f64(v), - Content::Char(v) => visitor.visit_char(v), - Content::String(ref v) => visitor.visit_str(v), - Content::Str(v) => visitor.visit_borrowed_str(v), - Content::ByteBuf(ref v) => visitor.visit_bytes(v), - Content::Bytes(v) => visitor.visit_borrowed_bytes(v), - Content::Unit => visitor.visit_unit(), - Content::None => visitor.visit_none(), - Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), - Content::Newtype(ref v) => { - visitor.visit_newtype_struct(ContentRefDeserializer::new(v)) - } - Content::Seq(ref v) => { - let seq = v.into_iter().map(ContentRefDeserializer::new); - let mut seq_visitor = de::value::SeqDeserializer::new(seq); - let value = try!(visitor.visit_seq(&mut seq_visitor)); - try!(seq_visitor.end()); - Ok(value) - } - Content::Map(ref v) => { - let map = v.into_iter().map(|&(ref k, ref v)| { - ( - ContentRefDeserializer::new(k), - ContentRefDeserializer::new(v), - ) - }); - let mut map_visitor = de::value::MapDeserializer::new(map); - let value = try!(visitor.visit_map(&mut map_visitor)); - try!(map_visitor.end()); - Ok(value) - } - } - } - - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E> - where - V: Visitor<'de>, - { - match *self.content { - Content::None => visitor.visit_none(), - Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), - Content::Unit => visitor.visit_unit(), - _ => visitor.visit_some(self), - } - } - - fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, E> - where - V: Visitor<'de>, - { - visitor.visit_newtype_struct(self) - } - - fn deserialize_enum<V>( - self, - _name: &str, - _variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>, - { - let (variant, value) = match *self.content { - Content::Map(ref value) => { - let mut iter = value.into_iter(); - let &(ref variant, ref value) = match iter.next() { - Some(v) => v, - None => { - return Err(de::Error::invalid_value( - de::Unexpected::Map, - &"map with a single key", - )); - } - }; - // enums are encoded in json as maps with a single key:value pair - if iter.next().is_some() { - return Err(de::Error::invalid_value( - de::Unexpected::Map, - &"map with a single key", - )); - } - (variant, Some(value)) - } - ref s @ Content::String(_) | ref s @ Content::Str(_) => (s, None), - ref other => { - return Err(de::Error::invalid_type( - other.unexpected(), - &"string or map", - )); - } - }; - - visitor.visit_enum(EnumRefDeserializer { - variant: variant, - value: value, - err: PhantomData, - }) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf unit unit_struct seq tuple tuple_struct map struct - identifier ignored_any - } - } - - impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E> { - /// private API, don't use - pub fn new(content: &'a Content<'de>) -> Self { - ContentRefDeserializer { - content: content, - err: PhantomData, - } - } - } - - struct EnumRefDeserializer<'a, 'de: 'a, E> - where - E: de::Error, - { - variant: &'a Content<'de>, - value: Option<&'a Content<'de>>, - err: PhantomData<E>, - } - - impl<'de, 'a, E> de::EnumAccess<'de> for EnumRefDeserializer<'a, 'de, E> - where - E: de::Error, - { - type Error = E; - type Variant = VariantRefDeserializer<'a, 'de, Self::Error>; - - fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> - where - V: de::DeserializeSeed<'de>, - { - let visitor = VariantRefDeserializer { - value: self.value, - err: PhantomData, - }; - seed.deserialize(ContentRefDeserializer::new(self.variant)) - .map(|v| (v, visitor)) - } - } - - struct VariantRefDeserializer<'a, 'de: 'a, E> - where - E: de::Error, - { - value: Option<&'a Content<'de>>, - err: PhantomData<E>, - } - - impl<'de, 'a, E> de::VariantAccess<'de> for VariantRefDeserializer<'a, 'de, E> - where - E: de::Error, - { - type Error = E; - - fn unit_variant(self) -> Result<(), E> { - match self.value { - Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)), - None => Ok(()), - } - } - - fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E> - where - T: de::DeserializeSeed<'de>, - { - match self.value { - Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), - None => Err(de::Error::invalid_type( - de::Unexpected::UnitVariant, - &"newtype variant", - )), - } - } - - fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - match self.value { - Some(&Content::Seq(ref v)) => { - de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor) - } - Some(other) => Err(de::Error::invalid_type( - other.unexpected(), - &"tuple variant", - )), - None => Err(de::Error::invalid_type( - de::Unexpected::UnitVariant, - &"tuple variant", - )), - } - } - - fn struct_variant<V>( - self, - _fields: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - match self.value { - Some(&Content::Map(ref v)) => { - de::Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor) - } - Some(&Content::Seq(ref v)) => { - de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor) - } - Some(other) => Err(de::Error::invalid_type( - other.unexpected(), - &"struct variant", - )), - _ => Err(de::Error::invalid_type( - de::Unexpected::UnitVariant, - &"struct variant", - )), - } - } - } - - struct SeqRefDeserializer<'a, 'de: 'a, E> - where - E: de::Error, - { - iter: <&'a [Content<'de>] as IntoIterator>::IntoIter, - err: PhantomData<E>, - } - - impl<'a, 'de, E> SeqRefDeserializer<'a, 'de, E> - where - E: de::Error, - { - fn new(vec: &'a [Content<'de>]) -> Self { - SeqRefDeserializer { - iter: vec.into_iter(), - err: PhantomData, - } - } - } - - impl<'de, 'a, E> de::Deserializer<'de> for SeqRefDeserializer<'a, 'de, E> - where - E: de::Error, - { - type Error = E; - - #[inline] - fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - let len = self.iter.len(); - if len == 0 { - visitor.visit_unit() - } else { - let ret = try!(visitor.visit_seq(&mut self)); - let remaining = self.iter.len(); - if remaining == 0 { - Ok(ret) - } else { - Err(de::Error::invalid_length(len, &"fewer elements in array")) - } - } - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any - } - } - - impl<'de, 'a, E> de::SeqAccess<'de> for SeqRefDeserializer<'a, 'de, E> - where - E: de::Error, - { - type Error = E; - - fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> - where - T: de::DeserializeSeed<'de>, - { - match self.iter.next() { - Some(value) => seed.deserialize(ContentRefDeserializer::new(value)) - .map(Some), - None => Ok(None), - } - } - - fn size_hint(&self) -> Option<usize> { - size_hint::from_bounds(&self.iter) - } - } - - struct MapRefDeserializer<'a, 'de: 'a, E> - where - E: de::Error, - { - iter: <&'a [(Content<'de>, Content<'de>)] as IntoIterator>::IntoIter, - value: Option<&'a Content<'de>>, - err: PhantomData<E>, - } - - impl<'a, 'de, E> MapRefDeserializer<'a, 'de, E> - where - E: de::Error, - { - fn new(map: &'a [(Content<'de>, Content<'de>)]) -> Self { - MapRefDeserializer { - iter: map.into_iter(), - value: None, - err: PhantomData, - } - } - } - - impl<'de, 'a, E> de::MapAccess<'de> for MapRefDeserializer<'a, 'de, E> - where - E: de::Error, - { - type Error = E; - - fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> - where - T: de::DeserializeSeed<'de>, - { - match self.iter.next() { - Some(&(ref key, ref value)) => { - self.value = Some(value); - seed.deserialize(ContentRefDeserializer::new(key)).map(Some) - } - None => Ok(None), - } - } - - fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error> - where - T: de::DeserializeSeed<'de>, - { - match self.value.take() { - Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), - None => Err(de::Error::custom("value is missing")), - } - } - - fn size_hint(&self) -> Option<usize> { - size_hint::from_bounds(&self.iter) - } - } - - impl<'de, 'a, E> de::Deserializer<'de> for MapRefDeserializer<'a, 'de, E> - where - E: de::Error, - { - type Error = E; - - #[inline] - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: de::Visitor<'de>, - { - visitor.visit_map(self) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any - } - } - - impl<'de, E> de::IntoDeserializer<'de, E> for ContentDeserializer<'de, E> - where - E: de::Error, - { - type Deserializer = Self; - - fn into_deserializer(self) -> Self { - self - } - } - - impl<'de, 'a, E> de::IntoDeserializer<'de, E> for ContentRefDeserializer<'a, 'de, E> - where - E: de::Error, - { - type Deserializer = Self; - - fn into_deserializer(self) -> Self { - self - } - } - - /// Visitor for deserializing an internally tagged unit variant. - /// - /// Not public API. - pub struct InternallyTaggedUnitVisitor<'a> { - type_name: &'a str, - variant_name: &'a str, - } - - impl<'a> InternallyTaggedUnitVisitor<'a> { - /// Not public API. - pub fn new(type_name: &'a str, variant_name: &'a str) -> Self { - InternallyTaggedUnitVisitor { - type_name: type_name, - variant_name: variant_name, - } - } - } - - impl<'de, 'a> Visitor<'de> for InternallyTaggedUnitVisitor<'a> { - type Value = (); - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!( - formatter, - "unit variant {}::{}", - self.type_name, self.variant_name - ) - } - - fn visit_seq<S>(self, _: S) -> Result<(), S::Error> - where - S: SeqAccess<'de>, - { - Ok(()) - } - - fn visit_map<M>(self, _: M) -> Result<(), M::Error> - where - M: MapAccess<'de>, - { - Ok(()) - } - } - - /// Visitor for deserializing an untagged unit variant. - /// - /// Not public API. - pub struct UntaggedUnitVisitor<'a> { - type_name: &'a str, - variant_name: &'a str, - } - - impl<'a> UntaggedUnitVisitor<'a> { - /// Not public API. - pub fn new(type_name: &'a str, variant_name: &'a str) -> Self { - UntaggedUnitVisitor { - type_name: type_name, - variant_name: variant_name, - } - } - } - - impl<'de, 'a> Visitor<'de> for UntaggedUnitVisitor<'a> { - type Value = (); - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - write!( - formatter, - "unit variant {}::{}", - self.type_name, self.variant_name - ) - } - - fn visit_unit<E>(self) -> Result<(), E> - where - E: de::Error, - { - Ok(()) - } - } -} - -//////////////////////////////////////////////////////////////////////////////// - -// Like `IntoDeserializer` but also implemented for `&[u8]`. This is used for -// the newtype fallthrough case of `field_identifier`. -// -// #[derive(Deserialize)] -// #[serde(field_identifier)] -// enum F { -// A, -// B, -// Other(String), // deserialized using IdentifierDeserializer -// } -pub trait IdentifierDeserializer<'de, E: Error> { - type Deserializer: Deserializer<'de, Error = E>; - - fn from(self) -> Self::Deserializer; -} - -impl<'de, E> IdentifierDeserializer<'de, E> for u32 -where - E: Error, -{ - type Deserializer = <u32 as IntoDeserializer<'de, E>>::Deserializer; - - fn from(self) -> Self::Deserializer { - self.into_deserializer() - } -} - -pub struct StrDeserializer<'a, E> { - value: &'a str, - marker: PhantomData<E>, -} - -impl<'a, E> IdentifierDeserializer<'a, E> for &'a str -where - E: Error, -{ - type Deserializer = StrDeserializer<'a, E>; - - fn from(self) -> Self::Deserializer { - StrDeserializer { - value: self, - marker: PhantomData, - } - } -} - -impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E> -where - E: Error, -{ - type Error = E; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>, - { - visitor.visit_str(self.value) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct - map struct enum identifier ignored_any - } -} - -pub struct BytesDeserializer<'a, E> { - value: &'a [u8], - marker: PhantomData<E>, -} - -impl<'a, E> IdentifierDeserializer<'a, E> for &'a [u8] -where - E: Error, -{ - type Deserializer = BytesDeserializer<'a, E>; - - fn from(self) -> Self::Deserializer { - BytesDeserializer { - value: self, - marker: PhantomData, - } - } -} - -impl<'de, 'a, E> Deserializer<'de> for BytesDeserializer<'a, E> -where - E: Error, -{ - type Error = E; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>, - { - visitor.visit_bytes(self.value) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct - map struct enum identifier ignored_any - } -} - -/// A DeserializeSeed helper for implementing deserialize_in_place Visitors. -/// -/// Wraps a mutable reference and calls deserialize_in_place on it. -pub struct InPlaceSeed<'a, T: 'a>(pub &'a mut T); - -impl<'a, 'de, T> DeserializeSeed<'de> for InPlaceSeed<'a, T> -where - T: Deserialize<'de>, -{ - type Value = (); - fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where - D: Deserializer<'de>, - { - T::deserialize_in_place(deserializer, self.0) - } -} diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/private/macros.rs cargo-0.26.0/vendor/serde-1.0.27/src/private/macros.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/private/macros.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/private/macros.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,148 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#[doc(hidden)] -#[macro_export] -macro_rules! __private_serialize { - () => { - trait Serialize { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: $crate::Serializer; - } - }; -} - -#[doc(hidden)] -#[macro_export] -macro_rules! __private_deserialize { - () => { - trait Deserialize<'de>: Sized { - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: $crate::Deserializer<'de>; - } - }; -} - -/// Used only by Serde doc tests. Not public API. -#[doc(hidden)] -#[macro_export] -macro_rules! __serialize_unimplemented { - ($($func:ident)*) => { - $( - __serialize_unimplemented_helper!($func); - )* - }; -} - -#[doc(hidden)] -#[macro_export] -macro_rules! __serialize_unimplemented_method { - ($func:ident $(<$t:ident>)* ($($arg:ty),*) -> $ret:ident) => { - fn $func $(<$t: ?Sized + $crate::Serialize>)* (self $(, _: $arg)*) -> $crate::export::Result<Self::$ret, Self::Error> { - unimplemented!() - } - }; -} - -#[doc(hidden)] -#[macro_export] -macro_rules! __serialize_unimplemented_helper { - (bool) => { - __serialize_unimplemented_method!(serialize_bool(bool) -> Ok); - }; - (i8) => { - __serialize_unimplemented_method!(serialize_i8(i8) -> Ok); - }; - (i16) => { - __serialize_unimplemented_method!(serialize_i16(i16) -> Ok); - }; - (i32) => { - __serialize_unimplemented_method!(serialize_i32(i32) -> Ok); - }; - (i64) => { - __serialize_unimplemented_method!(serialize_i64(i64) -> Ok); - }; - (u8) => { - __serialize_unimplemented_method!(serialize_u8(u8) -> Ok); - }; - (u16) => { - __serialize_unimplemented_method!(serialize_u16(u16) -> Ok); - }; - (u32) => { - __serialize_unimplemented_method!(serialize_u32(u32) -> Ok); - }; - (u64) => { - __serialize_unimplemented_method!(serialize_u64(u64) -> Ok); - }; - (f32) => { - __serialize_unimplemented_method!(serialize_f32(f32) -> Ok); - }; - (f64) => { - __serialize_unimplemented_method!(serialize_f64(f64) -> Ok); - }; - (char) => { - __serialize_unimplemented_method!(serialize_char(char) -> Ok); - }; - (str) => { - __serialize_unimplemented_method!(serialize_str(&str) -> Ok); - }; - (bytes) => { - __serialize_unimplemented_method!(serialize_bytes(&[u8]) -> Ok); - }; - (none) => { - __serialize_unimplemented_method!(serialize_none() -> Ok); - }; - (some) => { - __serialize_unimplemented_method!(serialize_some<T>(&T) -> Ok); - }; - (unit) => { - __serialize_unimplemented_method!(serialize_unit() -> Ok); - }; - (unit_struct) => { - __serialize_unimplemented_method!(serialize_unit_struct(&str) -> Ok); - }; - (unit_variant) => { - __serialize_unimplemented_method!(serialize_unit_variant(&str, u32, &str) -> Ok); - }; - (newtype_struct) => { - __serialize_unimplemented_method!(serialize_newtype_struct<T>(&str, &T) -> Ok); - }; - (newtype_variant) => { - __serialize_unimplemented_method!(serialize_newtype_variant<T>(&str, u32, &str, &T) -> Ok); - }; - (seq) => { - type SerializeSeq = $crate::ser::Impossible<Self::Ok, Self::Error>; - __serialize_unimplemented_method!(serialize_seq(Option<usize>) -> SerializeSeq); - }; - (tuple) => { - type SerializeTuple = $crate::ser::Impossible<Self::Ok, Self::Error>; - __serialize_unimplemented_method!(serialize_tuple(usize) -> SerializeTuple); - }; - (tuple_struct) => { - type SerializeTupleStruct = $crate::ser::Impossible<Self::Ok, Self::Error>; - __serialize_unimplemented_method!(serialize_tuple_struct(&str, usize) -> SerializeTupleStruct); - }; - (tuple_variant) => { - type SerializeTupleVariant = $crate::ser::Impossible<Self::Ok, Self::Error>; - __serialize_unimplemented_method!(serialize_tuple_variant(&str, u32, &str, usize) -> SerializeTupleVariant); - }; - (map) => { - type SerializeMap = $crate::ser::Impossible<Self::Ok, Self::Error>; - __serialize_unimplemented_method!(serialize_map(Option<usize>) -> SerializeMap); - }; - (struct) => { - type SerializeStruct = $crate::ser::Impossible<Self::Ok, Self::Error>; - __serialize_unimplemented_method!(serialize_struct(&str, usize) -> SerializeStruct); - }; - (struct_variant) => { - type SerializeStructVariant = $crate::ser::Impossible<Self::Ok, Self::Error>; - __serialize_unimplemented_method!(serialize_struct_variant(&str, u32, &str, usize) -> SerializeStructVariant); - }; -} diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/private/mod.rs cargo-0.26.0/vendor/serde-1.0.27/src/private/mod.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/private/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/private/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -mod macros; - -pub mod ser; -pub mod de; diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/private/ser.rs cargo-0.26.0/vendor/serde-1.0.27/src/private/ser.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/private/ser.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/private/ser.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1030 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use lib::*; - -use ser::{self, Impossible, Serialize, SerializeMap, SerializeStruct, Serializer}; - -#[cfg(any(feature = "std", feature = "alloc"))] -use self::content::{SerializeStructVariantAsMapValue, SerializeTupleVariantAsMapValue}; - -/// Used to check that serde(getter) attributes return the expected type. -/// Not public API. -pub fn constrain<T: ?Sized>(t: &T) -> &T { - t -} - -/// Not public API. -pub fn serialize_tagged_newtype<S, T>( - serializer: S, - type_ident: &'static str, - variant_ident: &'static str, - tag: &'static str, - variant_name: &'static str, - value: &T, -) -> Result<S::Ok, S::Error> -where - S: Serializer, - T: Serialize, -{ - value.serialize(TaggedSerializer { - type_ident: type_ident, - variant_ident: variant_ident, - tag: tag, - variant_name: variant_name, - delegate: serializer, - }) -} - -struct TaggedSerializer<S> { - type_ident: &'static str, - variant_ident: &'static str, - tag: &'static str, - variant_name: &'static str, - delegate: S, -} - -enum Unsupported { - Boolean, - Integer, - Float, - Char, - String, - ByteArray, - Optional, - Unit, - Sequence, - Tuple, - TupleStruct, - #[cfg(not(any(feature = "std", feature = "alloc")))] - Enum, -} - -impl Display for Unsupported { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match *self { - Unsupported::Boolean => formatter.write_str("a boolean"), - Unsupported::Integer => formatter.write_str("an integer"), - Unsupported::Float => formatter.write_str("a float"), - Unsupported::Char => formatter.write_str("a char"), - Unsupported::String => formatter.write_str("a string"), - Unsupported::ByteArray => formatter.write_str("a byte array"), - Unsupported::Optional => formatter.write_str("an optional"), - Unsupported::Unit => formatter.write_str("unit"), - Unsupported::Sequence => formatter.write_str("a sequence"), - Unsupported::Tuple => formatter.write_str("a tuple"), - Unsupported::TupleStruct => formatter.write_str("a tuple struct"), - #[cfg(not(any(feature = "std", feature = "alloc")))] - Unsupported::Enum => formatter.write_str("an enum"), - } - } -} - -impl<S> TaggedSerializer<S> -where - S: Serializer, -{ - fn bad_type(self, what: Unsupported) -> S::Error { - ser::Error::custom(format_args!( - "cannot serialize tagged newtype variant {}::{} containing {}", - self.type_ident, self.variant_ident, what - )) - } -} - -impl<S> Serializer for TaggedSerializer<S> -where - S: Serializer, -{ - type Ok = S::Ok; - type Error = S::Error; - - type SerializeSeq = Impossible<S::Ok, S::Error>; - type SerializeTuple = Impossible<S::Ok, S::Error>; - type SerializeTupleStruct = Impossible<S::Ok, S::Error>; - type SerializeMap = S::SerializeMap; - type SerializeStruct = S::SerializeStruct; - - #[cfg(not(any(feature = "std", feature = "alloc")))] - type SerializeTupleVariant = Impossible<S::Ok, S::Error>; - #[cfg(any(feature = "std", feature = "alloc"))] - type SerializeTupleVariant = SerializeTupleVariantAsMapValue<S::SerializeMap>; - - #[cfg(not(any(feature = "std", feature = "alloc")))] - type SerializeStructVariant = Impossible<S::Ok, S::Error>; - #[cfg(any(feature = "std", feature = "alloc"))] - type SerializeStructVariant = SerializeStructVariantAsMapValue<S::SerializeMap>; - - fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Boolean)) - } - - fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Integer)) - } - - fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Float)) - } - - fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Float)) - } - - fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Char)) - } - - fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::String)) - } - - fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::ByteArray)) - } - - fn serialize_none(self) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Optional)) - } - - fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error> - where - T: Serialize, - { - Err(self.bad_type(Unsupported::Optional)) - } - - fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { - Err(self.bad_type(Unsupported::Unit)) - } - - fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> { - let mut map = try!(self.delegate.serialize_map(Some(1))); - try!(map.serialize_entry(self.tag, self.variant_name)); - map.end() - } - - fn serialize_unit_variant( - self, - _: &'static str, - _: u32, - inner_variant: &'static str, - ) -> Result<Self::Ok, Self::Error> { - let mut map = try!(self.delegate.serialize_map(Some(2))); - try!(map.serialize_entry(self.tag, self.variant_name)); - try!(map.serialize_entry(inner_variant, &())); - map.end() - } - - fn serialize_newtype_struct<T: ?Sized>( - self, - _: &'static str, - value: &T, - ) -> Result<Self::Ok, Self::Error> - where - T: Serialize, - { - value.serialize(self) - } - - fn serialize_newtype_variant<T: ?Sized>( - self, - _: &'static str, - _: u32, - inner_variant: &'static str, - inner_value: &T, - ) -> Result<Self::Ok, Self::Error> - where - T: Serialize, - { - let mut map = try!(self.delegate.serialize_map(Some(2))); - try!(map.serialize_entry(self.tag, self.variant_name)); - try!(map.serialize_entry(inner_variant, inner_value)); - map.end() - } - - fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> { - Err(self.bad_type(Unsupported::Sequence)) - } - - fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> { - Err(self.bad_type(Unsupported::Tuple)) - } - - fn serialize_tuple_struct( - self, - _: &'static str, - _: usize, - ) -> Result<Self::SerializeTupleStruct, Self::Error> { - Err(self.bad_type(Unsupported::TupleStruct)) - } - - #[cfg(not(any(feature = "std", feature = "alloc")))] - fn serialize_tuple_variant( - self, - _: &'static str, - _: u32, - _: &'static str, - _: usize, - ) -> Result<Self::SerializeTupleVariant, Self::Error> { - // Lack of push-based serialization means we need to buffer the content - // of the tuple variant, so it requires std. - Err(self.bad_type(Unsupported::Enum)) - } - - #[cfg(any(feature = "std", feature = "alloc"))] - fn serialize_tuple_variant( - self, - _: &'static str, - _: u32, - inner_variant: &'static str, - len: usize, - ) -> Result<Self::SerializeTupleVariant, Self::Error> { - let mut map = try!(self.delegate.serialize_map(Some(2))); - try!(map.serialize_entry(self.tag, self.variant_name)); - try!(map.serialize_key(inner_variant)); - Ok(SerializeTupleVariantAsMapValue::new( - map, - inner_variant, - len, - )) - } - - fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> { - let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1))); - try!(map.serialize_entry(self.tag, self.variant_name)); - Ok(map) - } - - fn serialize_struct( - self, - name: &'static str, - len: usize, - ) -> Result<Self::SerializeStruct, Self::Error> { - let mut state = try!(self.delegate.serialize_struct(name, len + 1)); - try!(state.serialize_field(self.tag, self.variant_name)); - Ok(state) - } - - #[cfg(not(any(feature = "std", feature = "alloc")))] - fn serialize_struct_variant( - self, - _: &'static str, - _: u32, - _: &'static str, - _: usize, - ) -> Result<Self::SerializeStructVariant, Self::Error> { - // Lack of push-based serialization means we need to buffer the content - // of the struct variant, so it requires std. - Err(self.bad_type(Unsupported::Enum)) - } - - #[cfg(any(feature = "std", feature = "alloc"))] - fn serialize_struct_variant( - self, - _: &'static str, - _: u32, - inner_variant: &'static str, - len: usize, - ) -> Result<Self::SerializeStructVariant, Self::Error> { - let mut map = try!(self.delegate.serialize_map(Some(2))); - try!(map.serialize_entry(self.tag, self.variant_name)); - try!(map.serialize_key(inner_variant)); - Ok(SerializeStructVariantAsMapValue::new( - map, - inner_variant, - len, - )) - } - - #[cfg(not(any(feature = "std", feature = "alloc")))] - fn collect_str<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error> - where - T: Display, - { - Err(self.bad_type(Unsupported::String)) - } -} - -/// Used only by Serde doc tests. Not public API. -#[doc(hidden)] -#[derive(Debug)] -pub struct Error; - -impl ser::Error for Error { - fn custom<T>(_: T) -> Self - where - T: Display, - { - unimplemented!() - } -} - -#[cfg(feature = "std")] -impl error::Error for Error { - fn description(&self) -> &str { - unimplemented!() - } -} - -impl Display for Error { - fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { - unimplemented!() - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -mod content { - use lib::*; - - use ser::{self, Serialize, Serializer}; - - pub struct SerializeTupleVariantAsMapValue<M> { - map: M, - name: &'static str, - fields: Vec<Content>, - } - - impl<M> SerializeTupleVariantAsMapValue<M> { - pub fn new(map: M, name: &'static str, len: usize) -> Self { - SerializeTupleVariantAsMapValue { - map: map, - name: name, - fields: Vec::with_capacity(len), - } - } - } - - impl<M> ser::SerializeTupleVariant for SerializeTupleVariantAsMapValue<M> - where - M: ser::SerializeMap, - { - type Ok = M::Ok; - type Error = M::Error; - - fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), M::Error> - where - T: Serialize, - { - let value = try!(value.serialize(ContentSerializer::<M::Error>::new())); - self.fields.push(value); - Ok(()) - } - - fn end(mut self) -> Result<M::Ok, M::Error> { - try!( - self.map - .serialize_value(&Content::TupleStruct(self.name, self.fields)) - ); - self.map.end() - } - } - - pub struct SerializeStructVariantAsMapValue<M> { - map: M, - name: &'static str, - fields: Vec<(&'static str, Content)>, - } - - impl<M> SerializeStructVariantAsMapValue<M> { - pub fn new(map: M, name: &'static str, len: usize) -> Self { - SerializeStructVariantAsMapValue { - map: map, - name: name, - fields: Vec::with_capacity(len), - } - } - } - - impl<M> ser::SerializeStructVariant for SerializeStructVariantAsMapValue<M> - where - M: ser::SerializeMap, - { - type Ok = M::Ok; - type Error = M::Error; - - fn serialize_field<T: ?Sized>( - &mut self, - key: &'static str, - value: &T, - ) -> Result<(), M::Error> - where - T: Serialize, - { - let value = try!(value.serialize(ContentSerializer::<M::Error>::new())); - self.fields.push((key, value)); - Ok(()) - } - - fn end(mut self) -> Result<M::Ok, M::Error> { - try!( - self.map - .serialize_value(&Content::Struct(self.name, self.fields)) - ); - self.map.end() - } - } - - #[derive(Debug)] - enum Content { - Bool(bool), - - U8(u8), - U16(u16), - U32(u32), - U64(u64), - - I8(i8), - I16(i16), - I32(i32), - I64(i64), - - F32(f32), - F64(f64), - - Char(char), - String(String), - Bytes(Vec<u8>), - - None, - Some(Box<Content>), - - Unit, - UnitStruct(&'static str), - UnitVariant(&'static str, u32, &'static str), - NewtypeStruct(&'static str, Box<Content>), - NewtypeVariant(&'static str, u32, &'static str, Box<Content>), - - Seq(Vec<Content>), - Tuple(Vec<Content>), - TupleStruct(&'static str, Vec<Content>), - TupleVariant(&'static str, u32, &'static str, Vec<Content>), - Map(Vec<(Content, Content)>), - Struct(&'static str, Vec<(&'static str, Content)>), - StructVariant( - &'static str, - u32, - &'static str, - Vec<(&'static str, Content)>, - ), - } - - impl Serialize for Content { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - match *self { - Content::Bool(b) => serializer.serialize_bool(b), - Content::U8(u) => serializer.serialize_u8(u), - Content::U16(u) => serializer.serialize_u16(u), - Content::U32(u) => serializer.serialize_u32(u), - Content::U64(u) => serializer.serialize_u64(u), - Content::I8(i) => serializer.serialize_i8(i), - Content::I16(i) => serializer.serialize_i16(i), - Content::I32(i) => serializer.serialize_i32(i), - Content::I64(i) => serializer.serialize_i64(i), - Content::F32(f) => serializer.serialize_f32(f), - Content::F64(f) => serializer.serialize_f64(f), - Content::Char(c) => serializer.serialize_char(c), - Content::String(ref s) => serializer.serialize_str(s), - Content::Bytes(ref b) => serializer.serialize_bytes(b), - Content::None => serializer.serialize_none(), - Content::Some(ref c) => serializer.serialize_some(&**c), - Content::Unit => serializer.serialize_unit(), - Content::UnitStruct(n) => serializer.serialize_unit_struct(n), - Content::UnitVariant(n, i, v) => serializer.serialize_unit_variant(n, i, v), - Content::NewtypeStruct(n, ref c) => serializer.serialize_newtype_struct(n, &**c), - Content::NewtypeVariant(n, i, v, ref c) => { - serializer.serialize_newtype_variant(n, i, v, &**c) - } - Content::Seq(ref elements) => elements.serialize(serializer), - Content::Tuple(ref elements) => { - use ser::SerializeTuple; - let mut tuple = try!(serializer.serialize_tuple(elements.len())); - for e in elements { - try!(tuple.serialize_element(e)); - } - tuple.end() - } - Content::TupleStruct(n, ref fields) => { - use ser::SerializeTupleStruct; - let mut ts = try!(serializer.serialize_tuple_struct(n, fields.len())); - for f in fields { - try!(ts.serialize_field(f)); - } - ts.end() - } - Content::TupleVariant(n, i, v, ref fields) => { - use ser::SerializeTupleVariant; - let mut tv = try!(serializer.serialize_tuple_variant(n, i, v, fields.len())); - for f in fields { - try!(tv.serialize_field(f)); - } - tv.end() - } - Content::Map(ref entries) => { - use ser::SerializeMap; - let mut map = try!(serializer.serialize_map(Some(entries.len()))); - for &(ref k, ref v) in entries { - try!(map.serialize_entry(k, v)); - } - map.end() - } - Content::Struct(n, ref fields) => { - use ser::SerializeStruct; - let mut s = try!(serializer.serialize_struct(n, fields.len())); - for &(k, ref v) in fields { - try!(s.serialize_field(k, v)); - } - s.end() - } - Content::StructVariant(n, i, v, ref fields) => { - use ser::SerializeStructVariant; - let mut sv = try!(serializer.serialize_struct_variant(n, i, v, fields.len())); - for &(k, ref v) in fields { - try!(sv.serialize_field(k, v)); - } - sv.end() - } - } - } - } - - struct ContentSerializer<E> { - error: PhantomData<E>, - } - - impl<E> ContentSerializer<E> { - fn new() -> Self { - ContentSerializer { error: PhantomData } - } - } - - impl<E> Serializer for ContentSerializer<E> - where - E: ser::Error, - { - type Ok = Content; - type Error = E; - - type SerializeSeq = SerializeSeq<E>; - type SerializeTuple = SerializeTuple<E>; - type SerializeTupleStruct = SerializeTupleStruct<E>; - type SerializeTupleVariant = SerializeTupleVariant<E>; - type SerializeMap = SerializeMap<E>; - type SerializeStruct = SerializeStruct<E>; - type SerializeStructVariant = SerializeStructVariant<E>; - - fn serialize_bool(self, v: bool) -> Result<Content, E> { - Ok(Content::Bool(v)) - } - - fn serialize_i8(self, v: i8) -> Result<Content, E> { - Ok(Content::I8(v)) - } - - fn serialize_i16(self, v: i16) -> Result<Content, E> { - Ok(Content::I16(v)) - } - - fn serialize_i32(self, v: i32) -> Result<Content, E> { - Ok(Content::I32(v)) - } - - fn serialize_i64(self, v: i64) -> Result<Content, E> { - Ok(Content::I64(v)) - } - - fn serialize_u8(self, v: u8) -> Result<Content, E> { - Ok(Content::U8(v)) - } - - fn serialize_u16(self, v: u16) -> Result<Content, E> { - Ok(Content::U16(v)) - } - - fn serialize_u32(self, v: u32) -> Result<Content, E> { - Ok(Content::U32(v)) - } - - fn serialize_u64(self, v: u64) -> Result<Content, E> { - Ok(Content::U64(v)) - } - - fn serialize_f32(self, v: f32) -> Result<Content, E> { - Ok(Content::F32(v)) - } - - fn serialize_f64(self, v: f64) -> Result<Content, E> { - Ok(Content::F64(v)) - } - - fn serialize_char(self, v: char) -> Result<Content, E> { - Ok(Content::Char(v)) - } - - fn serialize_str(self, value: &str) -> Result<Content, E> { - Ok(Content::String(value.to_owned())) - } - - fn serialize_bytes(self, value: &[u8]) -> Result<Content, E> { - Ok(Content::Bytes(value.to_owned())) - } - - fn serialize_none(self) -> Result<Content, E> { - Ok(Content::None) - } - - fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Content, E> - where - T: Serialize, - { - Ok(Content::Some(Box::new(try!(value.serialize(self))))) - } - - fn serialize_unit(self) -> Result<Content, E> { - Ok(Content::Unit) - } - - fn serialize_unit_struct(self, name: &'static str) -> Result<Content, E> { - Ok(Content::UnitStruct(name)) - } - - fn serialize_unit_variant( - self, - name: &'static str, - variant_index: u32, - variant: &'static str, - ) -> Result<Content, E> { - Ok(Content::UnitVariant(name, variant_index, variant)) - } - - fn serialize_newtype_struct<T: ?Sized>( - self, - name: &'static str, - value: &T, - ) -> Result<Content, E> - where - T: Serialize, - { - Ok(Content::NewtypeStruct( - name, - Box::new(try!(value.serialize(self))), - )) - } - - fn serialize_newtype_variant<T: ?Sized>( - self, - name: &'static str, - variant_index: u32, - variant: &'static str, - value: &T, - ) -> Result<Content, E> - where - T: Serialize, - { - Ok(Content::NewtypeVariant( - name, - variant_index, - variant, - Box::new(try!(value.serialize(self))), - )) - } - - fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, E> { - Ok(SerializeSeq { - elements: Vec::with_capacity(len.unwrap_or(0)), - error: PhantomData, - }) - } - - fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, E> { - Ok(SerializeTuple { - elements: Vec::with_capacity(len), - error: PhantomData, - }) - } - - fn serialize_tuple_struct( - self, - name: &'static str, - len: usize, - ) -> Result<Self::SerializeTupleStruct, E> { - Ok(SerializeTupleStruct { - name: name, - fields: Vec::with_capacity(len), - error: PhantomData, - }) - } - - fn serialize_tuple_variant( - self, - name: &'static str, - variant_index: u32, - variant: &'static str, - len: usize, - ) -> Result<Self::SerializeTupleVariant, E> { - Ok(SerializeTupleVariant { - name: name, - variant_index: variant_index, - variant: variant, - fields: Vec::with_capacity(len), - error: PhantomData, - }) - } - - fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, E> { - Ok(SerializeMap { - entries: Vec::with_capacity(len.unwrap_or(0)), - key: None, - error: PhantomData, - }) - } - - fn serialize_struct( - self, - name: &'static str, - len: usize, - ) -> Result<Self::SerializeStruct, E> { - Ok(SerializeStruct { - name: name, - fields: Vec::with_capacity(len), - error: PhantomData, - }) - } - - fn serialize_struct_variant( - self, - name: &'static str, - variant_index: u32, - variant: &'static str, - len: usize, - ) -> Result<Self::SerializeStructVariant, E> { - Ok(SerializeStructVariant { - name: name, - variant_index: variant_index, - variant: variant, - fields: Vec::with_capacity(len), - error: PhantomData, - }) - } - } - - struct SerializeSeq<E> { - elements: Vec<Content>, - error: PhantomData<E>, - } - - impl<E> ser::SerializeSeq for SerializeSeq<E> - where - E: ser::Error, - { - type Ok = Content; - type Error = E; - - fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E> - where - T: Serialize, - { - let value = try!(value.serialize(ContentSerializer::<E>::new())); - self.elements.push(value); - Ok(()) - } - - fn end(self) -> Result<Content, E> { - Ok(Content::Seq(self.elements)) - } - } - - struct SerializeTuple<E> { - elements: Vec<Content>, - error: PhantomData<E>, - } - - impl<E> ser::SerializeTuple for SerializeTuple<E> - where - E: ser::Error, - { - type Ok = Content; - type Error = E; - - fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E> - where - T: Serialize, - { - let value = try!(value.serialize(ContentSerializer::<E>::new())); - self.elements.push(value); - Ok(()) - } - - fn end(self) -> Result<Content, E> { - Ok(Content::Tuple(self.elements)) - } - } - - struct SerializeTupleStruct<E> { - name: &'static str, - fields: Vec<Content>, - error: PhantomData<E>, - } - - impl<E> ser::SerializeTupleStruct for SerializeTupleStruct<E> - where - E: ser::Error, - { - type Ok = Content; - type Error = E; - - fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E> - where - T: Serialize, - { - let value = try!(value.serialize(ContentSerializer::<E>::new())); - self.fields.push(value); - Ok(()) - } - - fn end(self) -> Result<Content, E> { - Ok(Content::TupleStruct(self.name, self.fields)) - } - } - - struct SerializeTupleVariant<E> { - name: &'static str, - variant_index: u32, - variant: &'static str, - fields: Vec<Content>, - error: PhantomData<E>, - } - - impl<E> ser::SerializeTupleVariant for SerializeTupleVariant<E> - where - E: ser::Error, - { - type Ok = Content; - type Error = E; - - fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E> - where - T: Serialize, - { - let value = try!(value.serialize(ContentSerializer::<E>::new())); - self.fields.push(value); - Ok(()) - } - - fn end(self) -> Result<Content, E> { - Ok(Content::TupleVariant( - self.name, - self.variant_index, - self.variant, - self.fields, - )) - } - } - - struct SerializeMap<E> { - entries: Vec<(Content, Content)>, - key: Option<Content>, - error: PhantomData<E>, - } - - impl<E> ser::SerializeMap for SerializeMap<E> - where - E: ser::Error, - { - type Ok = Content; - type Error = E; - - fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), E> - where - T: Serialize, - { - let key = try!(key.serialize(ContentSerializer::<E>::new())); - self.key = Some(key); - Ok(()) - } - - fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), E> - where - T: Serialize, - { - let key = self.key - .take() - .expect("serialize_value called before serialize_key"); - let value = try!(value.serialize(ContentSerializer::<E>::new())); - self.entries.push((key, value)); - Ok(()) - } - - fn end(self) -> Result<Content, E> { - Ok(Content::Map(self.entries)) - } - - fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<(), E> - where - K: Serialize, - V: Serialize, - { - let key = try!(key.serialize(ContentSerializer::<E>::new())); - let value = try!(value.serialize(ContentSerializer::<E>::new())); - self.entries.push((key, value)); - Ok(()) - } - } - - struct SerializeStruct<E> { - name: &'static str, - fields: Vec<(&'static str, Content)>, - error: PhantomData<E>, - } - - impl<E> ser::SerializeStruct for SerializeStruct<E> - where - E: ser::Error, - { - type Ok = Content; - type Error = E; - - fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E> - where - T: Serialize, - { - let value = try!(value.serialize(ContentSerializer::<E>::new())); - self.fields.push((key, value)); - Ok(()) - } - - fn end(self) -> Result<Content, E> { - Ok(Content::Struct(self.name, self.fields)) - } - } - - struct SerializeStructVariant<E> { - name: &'static str, - variant_index: u32, - variant: &'static str, - fields: Vec<(&'static str, Content)>, - error: PhantomData<E>, - } - - impl<E> ser::SerializeStructVariant for SerializeStructVariant<E> - where - E: ser::Error, - { - type Ok = Content; - type Error = E; - - fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E> - where - T: Serialize, - { - let value = try!(value.serialize(ContentSerializer::<E>::new())); - self.fields.push((key, value)); - Ok(()) - } - - fn end(self) -> Result<Content, E> { - Ok(Content::StructVariant( - self.name, - self.variant_index, - self.variant, - self.fields, - )) - } - } -} diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/ser/impls.rs cargo-0.26.0/vendor/serde-1.0.27/src/ser/impls.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/ser/impls.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/ser/impls.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,690 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use lib::*; - -use ser::{Serialize, SerializeTuple, Serializer}; - -#[cfg(feature = "std")] -use ser::Error; - -//////////////////////////////////////////////////////////////////////////////// - -macro_rules! primitive_impl { - ($ty:ident, $method:ident $($cast:tt)*) => { - impl Serialize for $ty { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - serializer.$method(*self $($cast)*) - } - } - } -} - -primitive_impl!(bool, serialize_bool); -primitive_impl!(isize, serialize_i64 as i64); -primitive_impl!(i8, serialize_i8); -primitive_impl!(i16, serialize_i16); -primitive_impl!(i32, serialize_i32); -primitive_impl!(i64, serialize_i64); -primitive_impl!(usize, serialize_u64 as u64); -primitive_impl!(u8, serialize_u8); -primitive_impl!(u16, serialize_u16); -primitive_impl!(u32, serialize_u32); -primitive_impl!(u64, serialize_u64); -primitive_impl!(f32, serialize_f32); -primitive_impl!(f64, serialize_f64); -primitive_impl!(char, serialize_char); - -//////////////////////////////////////////////////////////////////////////////// - -impl Serialize for str { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - serializer.serialize_str(self) - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -impl Serialize for String { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - serializer.serialize_str(self) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "std")] -impl Serialize for CStr { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - serializer.serialize_bytes(self.to_bytes()) - } -} - -#[cfg(feature = "std")] -impl Serialize for CString { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - serializer.serialize_bytes(self.to_bytes()) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -impl<T> Serialize for Option<T> -where - T: Serialize, -{ - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - match *self { - Some(ref value) => serializer.serialize_some(value), - None => serializer.serialize_none(), - } - } -} - -//////////////////////////////////////////////////////////////////////////////// - -impl<T: ?Sized> Serialize for PhantomData<T> { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - serializer.serialize_unit_struct("PhantomData") - } -} - -//////////////////////////////////////////////////////////////////////////////// - -// Does not require T: Serialize. -impl<T> Serialize for [T; 0] { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - try!(serializer.serialize_tuple(0)).end() - } -} - -macro_rules! array_impls { - ($($len:tt)+) => { - $( - impl<T> Serialize for [T; $len] - where - T: Serialize, - { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - let mut seq = try!(serializer.serialize_tuple($len)); - for e in self { - try!(seq.serialize_element(e)); - } - seq.end() - } - } - )+ - } -} - -array_impls!(01 02 03 04 05 06 07 08 09 10 - 11 12 13 14 15 16 17 18 19 20 - 21 22 23 24 25 26 27 28 29 30 - 31 32); - -//////////////////////////////////////////////////////////////////////////////// - -impl<T> Serialize for [T] -where - T: Serialize, -{ - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - serializer.collect_seq(self) - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -macro_rules! seq_impl { - ($ty:ident < T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound:ident)* >) => { - impl<T $(, $typaram)*> Serialize for $ty<T $(, $typaram)*> - where - T: Serialize $(+ $tbound1 $(+ $tbound2)*)*, - $($typaram: $bound,)* - { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - serializer.collect_seq(self) - } - } - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -seq_impl!(BinaryHeap<T: Ord>); - -#[cfg(any(feature = "std", feature = "alloc"))] -seq_impl!(BTreeSet<T: Ord>); - -#[cfg(feature = "std")] -seq_impl!(HashSet<T: Eq + Hash, H: BuildHasher>); - -#[cfg(any(feature = "std", feature = "alloc"))] -seq_impl!(LinkedList<T>); - -#[cfg(any(feature = "std", feature = "alloc"))] -seq_impl!(Vec<T>); - -#[cfg(any(feature = "std", feature = "alloc"))] -seq_impl!(VecDeque<T>); - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "std")] -impl<Idx> Serialize for ops::Range<Idx> -where - Idx: Serialize, -{ - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - use super::SerializeStruct; - let mut state = try!(serializer.serialize_struct("Range", 2)); - try!(state.serialize_field("start", &self.start)); - try!(state.serialize_field("end", &self.end)); - state.end() - } -} - -//////////////////////////////////////////////////////////////////////////////// - -impl Serialize for () { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - serializer.serialize_unit() - } -} - -//////////////////////////////////////////////////////////////////////////////// - -macro_rules! tuple_impls { - ($($len:expr => ($($n:tt $name:ident)+))+) => { - $( - impl<$($name),+> Serialize for ($($name,)+) - where - $($name: Serialize,)+ - { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - let mut tuple = try!(serializer.serialize_tuple($len)); - $( - try!(tuple.serialize_element(&self.$n)); - )+ - tuple.end() - } - } - )+ - } -} - -tuple_impls! { - 1 => (0 T0) - 2 => (0 T0 1 T1) - 3 => (0 T0 1 T1 2 T2) - 4 => (0 T0 1 T1 2 T2 3 T3) - 5 => (0 T0 1 T1 2 T2 3 T3 4 T4) - 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5) - 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6) - 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7) - 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8) - 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9) - 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10) - 12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11) - 13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12) - 14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13) - 15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14) - 16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15) -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(any(feature = "std", feature = "alloc"))] -macro_rules! map_impl { - ($ty:ident < K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound:ident)* >) => { - impl<K, V $(, $typaram)*> Serialize for $ty<K, V $(, $typaram)*> - where - K: Serialize $(+ $kbound1 $(+ $kbound2)*)*, - V: Serialize, - $($typaram: $bound,)* - { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - serializer.collect_map(self) - } - } - } -} - -#[cfg(any(feature = "std", feature = "alloc"))] -map_impl!(BTreeMap<K: Ord, V>); - -#[cfg(feature = "std")] -map_impl!(HashMap<K: Eq + Hash, V, H: BuildHasher>); - -//////////////////////////////////////////////////////////////////////////////// - -macro_rules! deref_impl { - ($($desc:tt)+) => { - impl $($desc)+ { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - (**self).serialize(serializer) - } - } - }; -} - -deref_impl!(<'a, T: ?Sized> Serialize for &'a T where T: Serialize); -deref_impl!(<'a, T: ?Sized> Serialize for &'a mut T where T: Serialize); - -#[cfg(any(feature = "std", feature = "alloc"))] -deref_impl!(<T: ?Sized> Serialize for Box<T> where T: Serialize); - -#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] -deref_impl!(<T: ?Sized> Serialize for Rc<T> where T: Serialize); - -#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] -deref_impl!(<T: ?Sized> Serialize for Arc<T> where T: Serialize); - -#[cfg(any(feature = "std", feature = "alloc"))] -deref_impl!(<'a, T: ?Sized> Serialize for Cow<'a, T> where T: Serialize + ToOwned); - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "unstable")] -impl<T> Serialize for NonZero<T> -where - T: Serialize + Zeroable + Clone, -{ - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - self.clone().get().serialize(serializer) - } -} - -impl<T> Serialize for Cell<T> -where - T: Serialize + Copy, -{ - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - self.get().serialize(serializer) - } -} - -impl<T> Serialize for RefCell<T> -where - T: Serialize, -{ - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - self.borrow().serialize(serializer) - } -} - -#[cfg(feature = "std")] -impl<T> Serialize for Mutex<T> -where - T: Serialize, -{ - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - match self.lock() { - Ok(locked) => locked.serialize(serializer), - Err(_) => Err(S::Error::custom("lock poison error while serializing")), - } - } -} - -#[cfg(feature = "std")] -impl<T> Serialize for RwLock<T> -where - T: Serialize, -{ - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - match self.read() { - Ok(locked) => locked.serialize(serializer), - Err(_) => Err(S::Error::custom("lock poison error while serializing")), - } - } -} - -//////////////////////////////////////////////////////////////////////////////// - -impl<T, E> Serialize for Result<T, E> -where - T: Serialize, - E: Serialize, -{ - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - match *self { - Result::Ok(ref value) => serializer.serialize_newtype_variant("Result", 0, "Ok", value), - Result::Err(ref value) => { - serializer.serialize_newtype_variant("Result", 1, "Err", value) - } - } - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "std")] -impl Serialize for Duration { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - use super::SerializeStruct; - let mut state = try!(serializer.serialize_struct("Duration", 2)); - try!(state.serialize_field("secs", &self.as_secs())); - try!(state.serialize_field("nanos", &self.subsec_nanos())); - state.end() - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "std")] -impl Serialize for SystemTime { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - use super::SerializeStruct; - let duration_since_epoch = self.duration_since(UNIX_EPOCH) - .expect("SystemTime must be later than UNIX_EPOCH"); - let mut state = try!(serializer.serialize_struct("SystemTime", 2)); - try!(state.serialize_field("secs_since_epoch", &duration_since_epoch.as_secs())); - try!(state.serialize_field("nanos_since_epoch", &duration_since_epoch.subsec_nanos())); - state.end() - } -} - -//////////////////////////////////////////////////////////////////////////////// - -/// Serialize a value that implements `Display` as a string, when that string is -/// statically known to never have more than a constant `MAX_LEN` bytes. -/// -/// Panics if the `Display` impl tries to write more than `MAX_LEN` bytes. -#[cfg(feature = "std")] -macro_rules! serialize_display_bounded_length { - ($value:expr, $max:expr, $serializer:expr) => {{ - let mut buffer: [u8; $max] = unsafe { mem::uninitialized() }; - let remaining_len = { - let mut remaining = &mut buffer[..]; - write!(remaining, "{}", $value).unwrap(); - remaining.len() - }; - let written_len = buffer.len() - remaining_len; - let written = &buffer[..written_len]; - - // write! only provides fmt::Formatter to Display implementations, which - // has methods write_str and write_char but no method to write arbitrary - // bytes. Therefore `written` must be valid UTF-8. - let written_str = unsafe { - str::from_utf8_unchecked(written) - }; - $serializer.serialize_str(written_str) - }} -} - -#[cfg(feature = "std")] -impl Serialize for net::IpAddr { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - if serializer.is_human_readable() { - match *self { - net::IpAddr::V4(ref a) => a.serialize(serializer), - net::IpAddr::V6(ref a) => a.serialize(serializer), - } - } else { - match *self { - net::IpAddr::V4(ref a) => { - serializer.serialize_newtype_variant("IpAddr", 0, "V4", a) - } - net::IpAddr::V6(ref a) => { - serializer.serialize_newtype_variant("IpAddr", 1, "V6", a) - } - } - } - } -} - -#[cfg(feature = "std")] -impl Serialize for net::Ipv4Addr { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - if serializer.is_human_readable() { - const MAX_LEN: usize = 15; - debug_assert_eq!(MAX_LEN, "101.102.103.104".len()); - serialize_display_bounded_length!(self, MAX_LEN, serializer) - } else { - self.octets().serialize(serializer) - } - } -} - -#[cfg(feature = "std")] -impl Serialize for net::Ipv6Addr { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - if serializer.is_human_readable() { - const MAX_LEN: usize = 39; - debug_assert_eq!(MAX_LEN, "1001:1002:1003:1004:1005:1006:1007:1008".len()); - serialize_display_bounded_length!(self, MAX_LEN, serializer) - } else { - self.octets().serialize(serializer) - } - } -} - -#[cfg(feature = "std")] -impl Serialize for net::SocketAddr { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - if serializer.is_human_readable() { - match *self { - net::SocketAddr::V4(ref addr) => addr.serialize(serializer), - net::SocketAddr::V6(ref addr) => addr.serialize(serializer), - } - } else { - match *self { - net::SocketAddr::V4(ref addr) => { - serializer.serialize_newtype_variant("SocketAddr", 0, "V4", addr) - } - net::SocketAddr::V6(ref addr) => { - serializer.serialize_newtype_variant("SocketAddr", 1, "V6", addr) - } - } - } - } -} - -#[cfg(feature = "std")] -impl Serialize for net::SocketAddrV4 { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - if serializer.is_human_readable() { - const MAX_LEN: usize = 21; - debug_assert_eq!(MAX_LEN, "101.102.103.104:65000".len()); - serialize_display_bounded_length!(self, MAX_LEN, serializer) - } else { - (self.ip(), self.port()).serialize(serializer) - } - } -} - -#[cfg(feature = "std")] -impl Serialize for net::SocketAddrV6 { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - if serializer.is_human_readable() { - const MAX_LEN: usize = 47; - debug_assert_eq!( - MAX_LEN, - "[1001:1002:1003:1004:1005:1006:1007:1008]:65000".len() - ); - serialize_display_bounded_length!(self, MAX_LEN, serializer) - } else { - (self.ip(), self.port()).serialize(serializer) - } - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "std")] -impl Serialize for Path { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - match self.to_str() { - Some(s) => s.serialize(serializer), - None => Err(Error::custom("path contains invalid UTF-8 characters")), - } - } -} - -#[cfg(feature = "std")] -impl Serialize for PathBuf { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - self.as_path().serialize(serializer) - } -} - -#[cfg(all(feature = "std", any(unix, windows)))] -impl Serialize for OsStr { - #[cfg(unix)] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - use std::os::unix::ffi::OsStrExt; - serializer.serialize_newtype_variant("OsString", 0, "Unix", self.as_bytes()) - } - - #[cfg(windows)] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - use std::os::windows::ffi::OsStrExt; - let val = self.encode_wide().collect::<Vec<_>>(); - serializer.serialize_newtype_variant("OsString", 1, "Windows", &val) - } -} - -#[cfg(all(feature = "std", any(unix, windows)))] -impl Serialize for OsString { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - self.as_os_str().serialize(serializer) - } -} - -//////////////////////////////////////////////////////////////////////////////// - -#[cfg(feature = "std")] -impl<T> Serialize for Wrapping<T> -where - T: Serialize, -{ - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - self.0.serialize(serializer) - } -} diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/ser/impossible.rs cargo-0.26.0/vendor/serde-1.0.27/src/ser/impossible.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/ser/impossible.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/ser/impossible.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,227 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! This module contains `Impossible` serializer and its implementations. - -use lib::*; - -use ser::{self, Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, - SerializeTuple, SerializeTupleStruct, SerializeTupleVariant}; - -/// Helper type for implementing a `Serializer` that does not support -/// serializing one of the compound types. -/// -/// This type cannot be instantiated, but implements every one of the traits -/// corresponding to the [`Serializer`] compound types: [`SerializeSeq`], -/// [`SerializeTuple`], [`SerializeTupleStruct`], [`SerializeTupleVariant`], -/// [`SerializeMap`], [`SerializeStruct`], and [`SerializeStructVariant`]. -/// -/// ```rust -/// # #[macro_use] -/// # extern crate serde; -/// # -/// # use serde::ser::{Serializer, Impossible}; -/// # use serde::private::ser::Error; -/// # -/// # struct MySerializer; -/// # -/// impl Serializer for MySerializer { -/// type Ok = (); -/// type Error = Error; -/// -/// type SerializeSeq = Impossible<(), Error>; -/// /* other associated types */ -/// -/// /// This data format does not support serializing sequences. -/// fn serialize_seq(self, -/// len: Option<usize>) -/// -> Result<Self::SerializeSeq, Error> { -/// // Given Impossible cannot be instantiated, the only -/// // thing we can do here is to return an error. -/// # stringify! { -/// Err(...) -/// # }; -/// # unimplemented!() -/// } -/// -/// /* other Serializer methods */ -/// # __serialize_unimplemented! { -/// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str bytes none some -/// # unit unit_struct unit_variant newtype_struct newtype_variant -/// # tuple tuple_struct tuple_variant map struct struct_variant -/// # } -/// } -/// # -/// # fn main() {} -/// ``` -/// -/// [`Serializer`]: trait.Serializer.html -/// [`SerializeSeq`]: trait.SerializeSeq.html -/// [`SerializeTuple`]: trait.SerializeTuple.html -/// [`SerializeTupleStruct`]: trait.SerializeTupleStruct.html -/// [`SerializeTupleVariant`]: trait.SerializeTupleVariant.html -/// [`SerializeMap`]: trait.SerializeMap.html -/// [`SerializeStruct`]: trait.SerializeStruct.html -/// [`SerializeStructVariant`]: trait.SerializeStructVariant.html -pub struct Impossible<Ok, Error> { - void: Void, - ok: PhantomData<Ok>, - error: PhantomData<Error>, -} - -enum Void {} - -impl<Ok, Error> SerializeSeq for Impossible<Ok, Error> -where - Error: ser::Error, -{ - type Ok = Ok; - type Error = Error; - - fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> - where - T: Serialize, - { - let _ = value; - match self.void {} - } - - fn end(self) -> Result<Ok, Error> { - match self.void {} - } -} - -impl<Ok, Error> SerializeTuple for Impossible<Ok, Error> -where - Error: ser::Error, -{ - type Ok = Ok; - type Error = Error; - - fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> - where - T: Serialize, - { - let _ = value; - match self.void {} - } - - fn end(self) -> Result<Ok, Error> { - match self.void {} - } -} - -impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error> -where - Error: ser::Error, -{ - type Ok = Ok; - type Error = Error; - - fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> - where - T: Serialize, - { - let _ = value; - match self.void {} - } - - fn end(self) -> Result<Ok, Error> { - match self.void {} - } -} - -impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error> -where - Error: ser::Error, -{ - type Ok = Ok; - type Error = Error; - - fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> - where - T: Serialize, - { - let _ = value; - match self.void {} - } - - fn end(self) -> Result<Ok, Error> { - match self.void {} - } -} - -impl<Ok, Error> SerializeMap for Impossible<Ok, Error> -where - Error: ser::Error, -{ - type Ok = Ok; - type Error = Error; - - fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Error> - where - T: Serialize, - { - let _ = key; - match self.void {} - } - - fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> - where - T: Serialize, - { - let _ = value; - match self.void {} - } - - fn end(self) -> Result<Ok, Error> { - match self.void {} - } -} - -impl<Ok, Error> SerializeStruct for Impossible<Ok, Error> -where - Error: ser::Error, -{ - type Ok = Ok; - type Error = Error; - - fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> - where - T: Serialize, - { - let _ = key; - let _ = value; - match self.void {} - } - - fn end(self) -> Result<Ok, Error> { - match self.void {} - } -} - -impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error> -where - Error: ser::Error, -{ - type Ok = Ok; - type Error = Error; - - fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> - where - T: Serialize, - { - let _ = key; - let _ = value; - match self.void {} - } - - fn end(self) -> Result<Ok, Error> { - match self.void {} - } -} diff -Nru cargo-0.25.0/vendor/serde-1.0.27/src/ser/mod.rs cargo-0.26.0/vendor/serde-1.0.27/src/ser/mod.rs --- cargo-0.25.0/vendor/serde-1.0.27/src/ser/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.27/src/ser/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1882 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Generic data structure serialization framework. -//! -//! The two most important traits in this module are [`Serialize`] and -//! [`Serializer`]. -//! -//! - **A type that implements `Serialize` is a data structure** that can be -//! serialized to any data format supported by Serde, and conversely -//! - **A type that implements `Serializer` is a data format** that can -//! serialize any data structure supported by Serde. -//! -//! # The Serialize trait -//! -//! Serde provides [`Serialize`] implementations for many Rust primitive and -//! standard library types. The complete list is below. All of these can be -//! serialized using Serde out of the box. -//! -//! Additionally, Serde provides a procedural macro called [`serde_derive`] to -//! automatically generate [`Serialize`] implementations for structs and enums -//! in your program. See the [codegen section of the manual] for how to use -//! this. -//! -//! In rare cases it may be necessary to implement [`Serialize`] manually for -//! some type in your program. See the [Implementing `Serialize`] section of the -//! manual for more about this. -//! -//! Third-party crates may provide [`Serialize`] implementations for types that -//! they expose. For example the [`linked-hash-map`] crate provides a -//! [`LinkedHashMap<K, V>`] type that is serializable by Serde because the crate -//! provides an implementation of [`Serialize`] for it. -//! -//! # The Serializer trait -//! -//! [`Serializer`] implementations are provided by third-party crates, for -//! example [`serde_json`], [`serde_yaml`] and [`bincode`]. -//! -//! A partial list of well-maintained formats is given on the [Serde -//! website][data formats]. -//! -//! # Implementations of Serialize provided by Serde -//! -//! - **Primitive types**: -//! - bool -//! - i8, i16, i32, i64, isize -//! - u8, u16, u32, u64, usize -//! - f32, f64 -//! - char -//! - str -//! - &T and &mut T -//! - **Compound types**: -//! - [T] -//! - [T; 0] through [T; 32] -//! - tuples up to size 16 -//! - **Common standard library types**: -//! - String -//! - Option\<T\> -//! - Result\<T, E\> -//! - PhantomData\<T\> -//! - **Wrapper types**: -//! - Box\<T\> -//! - Rc\<T\> -//! - Arc\<T\> -//! - Cow\<'a, T\> -//! - Cell\<T\> -//! - RefCell\<T\> -//! - Mutex\<T\> -//! - RwLock\<T\> -//! - **Collection types**: -//! - BTreeMap\<K, V\> -//! - BTreeSet\<T\> -//! - BinaryHeap\<T\> -//! - HashMap\<K, V, H\> -//! - HashSet\<T, H\> -//! - LinkedList\<T\> -//! - VecDeque\<T\> -//! - Vec\<T\> -//! - EnumSet\<T\> (unstable) -//! - **FFI types**: -//! - CStr -//! - CString -//! - OsStr -//! - OsString -//! - **Miscellaneous standard library types**: -//! - Duration -//! - SystemTime -//! - Path -//! - PathBuf -//! - Range\<T\> -//! - NonZero\<T\> (unstable) -//! - **Net types**: -//! - IpAddr -//! - Ipv4Addr -//! - Ipv6Addr -//! - SocketAddr -//! - SocketAddrV4 -//! - SocketAddrV6 -//! -//! [Implementing `Serialize`]: https://serde.rs/impl-serialize.html -//! [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html -//! [`Serialize`]: ../trait.Serialize.html -//! [`Serializer`]: ../trait.Serializer.html -//! [`bincode`]: https://github.com/TyOverby/bincode -//! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map -//! [`serde_derive`]: https://crates.io/crates/serde_derive -//! [`serde_json`]: https://github.com/serde-rs/json -//! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml -//! [codegen section of the manual]: https://serde.rs/codegen.html -//! [data formats]: https://serde.rs/#data-formats - -use lib::*; - -mod impls; -mod impossible; - -pub use self::impossible::Impossible; - -//////////////////////////////////////////////////////////////////////////////// - -macro_rules! declare_error_trait { - (Error: Sized $(+ $($supertrait:ident)::+)*) => { - /// Trait used by `Serialize` implementations to generically construct - /// errors belonging to the `Serializer` against which they are - /// currently running. - pub trait Error: Sized $(+ $($supertrait)::+)* { - /// Used when a [`Serialize`] implementation encounters any error - /// while serializing a type. - /// - /// The message should not be capitalized and should not end with a - /// period. - /// - /// For example, a filesystem [`Path`] may refuse to serialize - /// itself if it contains invalid UTF-8 data. - /// - /// ```rust - /// # struct Path; - /// # - /// # impl Path { - /// # fn to_str(&self) -> Option<&str> { - /// # unimplemented!() - /// # } - /// # } - /// # - /// use serde::ser::{self, Serialize, Serializer}; - /// - /// impl Serialize for Path { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// match self.to_str() { - /// Some(s) => serializer.serialize_str(s), - /// None => Err(ser::Error::custom("path contains invalid UTF-8 characters")), - /// } - /// } - /// } - /// ``` - /// - /// [`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html - /// [`Serialize`]: ../trait.Serialize.html - fn custom<T>(msg: T) -> Self - where - T: Display; - } - } -} - -#[cfg(feature = "std")] -declare_error_trait!(Error: Sized + error::Error); - -#[cfg(not(feature = "std"))] -declare_error_trait!(Error: Sized + Debug + Display); - -//////////////////////////////////////////////////////////////////////////////// - -/// A **data structure** that can be serialized into any data format supported -/// by Serde. -/// -/// Serde provides `Serialize` implementations for many Rust primitive and -/// standard library types. The complete list is [here][ser]. All of these can -/// be serialized using Serde out of the box. -/// -/// Additionally, Serde provides a procedural macro called [`serde_derive`] to -/// automatically generate `Serialize` implementations for structs and enums in -/// your program. See the [codegen section of the manual] for how to use this. -/// -/// In rare cases it may be necessary to implement `Serialize` manually for some -/// type in your program. See the [Implementing `Serialize`] section of the -/// manual for more about this. -/// -/// Third-party crates may provide `Serialize` implementations for types that -/// they expose. For example the [`linked-hash-map`] crate provides a -/// [`LinkedHashMap<K, V>`] type that is serializable by Serde because the crate -/// provides an implementation of `Serialize` for it. -/// -/// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html -/// [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html -/// [`linked-hash-map`]: https://crates.io/crates/linked-hash-map -/// [`serde_derive`]: https://crates.io/crates/serde_derive -/// [codegen section of the manual]: https://serde.rs/codegen.html -/// [ser]: https://docs.serde.rs/serde/ser/index.html -pub trait Serialize { - /// Serialize this value into the given Serde serializer. - /// - /// See the [Implementing `Serialize`] section of the manual for more - /// information about how to implement this method. - /// - /// ```rust - /// use serde::ser::{Serialize, Serializer, SerializeStruct}; - /// - /// struct Person { - /// name: String, - /// age: u8, - /// phones: Vec<String>, - /// } - /// - /// // This is what #[derive(Serialize)] would generate. - /// impl Serialize for Person { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// let mut s = serializer.serialize_struct("Person", 3)?; - /// s.serialize_field("name", &self.name)?; - /// s.serialize_field("age", &self.age)?; - /// s.serialize_field("phones", &self.phones)?; - /// s.end() - /// } - /// } - /// ``` - /// - /// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer; -} - -//////////////////////////////////////////////////////////////////////////////// - -/// A **data format** that can serialize any data structure supported by Serde. -/// -/// The role of this trait is to define the serialization half of the Serde data -/// model, which is a way to categorize every Rust data structure into one of 27 -/// possible types. Each method of the `Serializer` trait corresponds to one of -/// the types of the data model. -/// -/// Implementations of `Serialize` map themselves into this data model by -/// invoking exactly one of the `Serializer` methods. -/// -/// The types that make up the Serde data model are: -/// -/// - **12 primitive types** -/// - bool -/// - i8, i16, i32, i64 -/// - u8, u16, u32, u64 -/// - f32, f64 -/// - char -/// - **string** -/// - UTF-8 bytes with a length and no null terminator. -/// - When serializing, all strings are handled equally. When deserializing, -/// there are three flavors of strings: transient, owned, and borrowed. -/// - **byte array** - [u8] -/// - Similar to strings, during deserialization byte arrays can be transient, -/// owned, or borrowed. -/// - **option** -/// - Either none or some value. -/// - **unit** -/// - The type of `()` in Rust. It represents an anonymous value containing no -/// data. -/// - **unit_struct** -/// - For example `struct Unit` or `PhantomData<T>`. It represents a named value -/// containing no data. -/// - **unit_variant** -/// - For example the `E::A` and `E::B` in `enum E { A, B }`. -/// - **newtype_struct** -/// - For example `struct Millimeters(u8)`. -/// - **newtype_variant** -/// - For example the `E::N` in `enum E { N(u8) }`. -/// - **seq** -/// - A variably sized heterogeneous sequence of values, for example `Vec<T>` or -/// `HashSet<T>`. When serializing, the length may or may not be known before -/// iterating through all the data. When deserializing, the length is determined -/// by looking at the serialized data. -/// - **tuple** -/// - A statically sized heterogeneous sequence of values for which the length -/// will be known at deserialization time without looking at the serialized -/// data, for example `(u8,)` or `(String, u64, Vec<T>)` or `[u64; 10]`. -/// - **tuple_struct** -/// - A named tuple, for example `struct Rgb(u8, u8, u8)`. -/// - **tuple_variant** -/// - For example the `E::T` in `enum E { T(u8, u8) }`. -/// - **map** -/// - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`. -/// - **struct** -/// - A heterogeneous key-value pairing in which the keys are strings and will be -/// known at deserialization time without looking at the serialized data, for -/// example `struct S { r: u8, g: u8, b: u8 }`. -/// - **struct_variant** -/// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. -/// -/// Many Serde serializers produce text or binary data as output, for example -/// JSON or Bincode. This is not a requirement of the `Serializer` trait, and -/// there are serializers that do not produce text or binary output. One example -/// is the `serde_json::value::Serializer` (distinct from the main `serde_json` -/// serializer) that produces a `serde_json::Value` data structure in memory as -/// output. -pub trait Serializer: Sized { - /// The output type produced by this `Serializer` during successful - /// serialization. Most serializers that produce text or binary output - /// should set `Ok = ()` and serialize into an [`io::Write`] or buffer - /// contained within the `Serializer` instance. Serializers that build - /// in-memory data structures may be simplified by using `Ok` to propagate - /// the data structure around. - /// - /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html - type Ok; - - /// The error type when some error occurs during serialization. - type Error: Error; - - /// Type returned from [`serialize_seq`] for serializing the content of the - /// sequence. - /// - /// [`serialize_seq`]: #tymethod.serialize_seq - type SerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>; - - /// Type returned from [`serialize_tuple`] for serializing the content of - /// the tuple. - /// - /// [`serialize_tuple`]: #tymethod.serialize_tuple - type SerializeTuple: SerializeTuple<Ok = Self::Ok, Error = Self::Error>; - - /// Type returned from [`serialize_tuple_struct`] for serializing the - /// content of the tuple struct. - /// - /// [`serialize_tuple_struct`]: #tymethod.serialize_tuple_struct - type SerializeTupleStruct: SerializeTupleStruct<Ok = Self::Ok, Error = Self::Error>; - - /// Type returned from [`serialize_tuple_variant`] for serializing the - /// content of the tuple variant. - /// - /// [`serialize_tuple_variant`]: #tymethod.serialize_tuple_variant - type SerializeTupleVariant: SerializeTupleVariant<Ok = Self::Ok, Error = Self::Error>; - - /// Type returned from [`serialize_map`] for serializing the content of the - /// map. - /// - /// [`serialize_map`]: #tymethod.serialize_map - type SerializeMap: SerializeMap<Ok = Self::Ok, Error = Self::Error>; - - /// Type returned from [`serialize_struct`] for serializing the content of - /// the struct. - /// - /// [`serialize_struct`]: #tymethod.serialize_struct - type SerializeStruct: SerializeStruct<Ok = Self::Ok, Error = Self::Error>; - - /// Type returned from [`serialize_struct_variant`] for serializing the - /// content of the struct variant. - /// - /// [`serialize_struct_variant`]: #tymethod.serialize_struct_variant - type SerializeStructVariant: SerializeStructVariant<Ok = Self::Ok, Error = Self::Error>; - - /// Serialize a `bool` value. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for bool { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_bool(*self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>; - - /// Serialize an `i8` value. - /// - /// If the format does not differentiate between `i8` and `i64`, a - /// reasonable implementation would be to cast the value to `i64` and - /// forward to `serialize_i64`. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for i8 { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_i8(*self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>; - - /// Serialize an `i16` value. - /// - /// If the format does not differentiate between `i16` and `i64`, a - /// reasonable implementation would be to cast the value to `i64` and - /// forward to `serialize_i64`. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for i16 { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_i16(*self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>; - - /// Serialize an `i32` value. - /// - /// If the format does not differentiate between `i32` and `i64`, a - /// reasonable implementation would be to cast the value to `i64` and - /// forward to `serialize_i64`. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for i32 { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_i32(*self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>; - - /// Serialize an `i64` value. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for i64 { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_i64(*self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>; - - /// Serialize a `u8` value. - /// - /// If the format does not differentiate between `u8` and `u64`, a - /// reasonable implementation would be to cast the value to `u64` and - /// forward to `serialize_u64`. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for u8 { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_u8(*self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>; - - /// Serialize a `u16` value. - /// - /// If the format does not differentiate between `u16` and `u64`, a - /// reasonable implementation would be to cast the value to `u64` and - /// forward to `serialize_u64`. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for u16 { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_u16(*self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>; - - /// Serialize a `u32` value. - /// - /// If the format does not differentiate between `u32` and `u64`, a - /// reasonable implementation would be to cast the value to `u64` and - /// forward to `serialize_u64`. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for u32 { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_u32(*self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>; - - /// Serialize a `u64` value. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for u64 { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_u64(*self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>; - - /// Serialize an `f32` value. - /// - /// If the format does not differentiate between `f32` and `f64`, a - /// reasonable implementation would be to cast the value to `f64` and - /// forward to `serialize_f64`. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for f32 { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_f32(*self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>; - - /// Serialize an `f64` value. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for f64 { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_f64(*self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>; - - /// Serialize a character. - /// - /// If the format does not support characters, it is reasonable to serialize - /// it as a single element `str` or a `u32`. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for char { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_char(*self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>; - - /// Serialize a `&str`. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for str { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_str(self) - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error>; - - /// Serialize a chunk of raw byte data. - /// - /// Enables serializers to serialize byte slices more compactly or more - /// efficiently than other types of slices. If no efficient implementation - /// is available, a reasonable implementation would be to forward to - /// `serialize_seq`. If forwarded, the implementation looks usually just - /// like this: - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::ser::{Serializer, SerializeSeq}; - /// # use serde::private::ser::Error; - /// # - /// # struct MySerializer; - /// # - /// # impl Serializer for MySerializer { - /// # type Ok = (); - /// # type Error = Error; - /// # - /// fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> { - /// let mut seq = self.serialize_seq(Some(v.len()))?; - /// for b in v { - /// seq.serialize_element(b)?; - /// } - /// seq.end() - /// } - /// # - /// # __serialize_unimplemented! { - /// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str none some - /// # unit unit_struct unit_variant newtype_struct newtype_variant - /// # seq tuple tuple_struct tuple_variant map struct struct_variant - /// # } - /// # } - /// # - /// # fn main() {} - /// ``` - fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error>; - - /// Serialize a [`None`] value. - /// - /// ```rust - /// # extern crate serde; - /// # - /// # use serde::{Serialize, Serializer}; - /// # - /// # enum Option<T> { - /// # Some(T), - /// # None, - /// # } - /// # - /// # use Option::{Some, None}; - /// # - /// impl<T> Serialize for Option<T> - /// where T: Serialize - /// { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// match *self { - /// Some(ref value) => serializer.serialize_some(value), - /// None => serializer.serialize_none(), - /// } - /// } - /// } - /// # - /// # fn main() {} - /// ``` - /// - /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None - fn serialize_none(self) -> Result<Self::Ok, Self::Error>; - - /// Serialize a [`Some(T)`] value. - /// - /// ```rust - /// # extern crate serde; - /// # - /// # use serde::{Serialize, Serializer}; - /// # - /// # enum Option<T> { - /// # Some(T), - /// # None, - /// # } - /// # - /// # use Option::{Some, None}; - /// # - /// impl<T> Serialize for Option<T> - /// where T: Serialize - /// { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// match *self { - /// Some(ref value) => serializer.serialize_some(value), - /// None => serializer.serialize_none(), - /// } - /// } - /// } - /// # - /// # fn main() {} - /// ``` - /// - /// [`Some(T)`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some - fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> - where - T: Serialize; - - /// Serialize a `()` value. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde; - /// # - /// # use serde::Serializer; - /// # - /// # __private_serialize!(); - /// # - /// impl Serialize for () { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_unit() - /// } - /// } - /// # - /// # fn main() {} - /// ``` - fn serialize_unit(self) -> Result<Self::Ok, Self::Error>; - - /// Serialize a unit struct like `struct Unit` or `PhantomData<T>`. - /// - /// A reasonable implementation would be to forward to `serialize_unit`. - /// - /// ```rust - /// use serde::{Serialize, Serializer}; - /// - /// struct Nothing; - /// - /// impl Serialize for Nothing { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_unit_struct("Nothing") - /// } - /// } - /// ``` - fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error>; - - /// Serialize a unit variant like `E::A` in `enum E { A, B }`. - /// - /// The `name` is the name of the enum, the `variant_index` is the index of - /// this variant within the enum, and the `variant` is the name of the - /// variant. - /// - /// ```rust - /// use serde::{Serialize, Serializer}; - /// - /// enum E { - /// A, - /// B, - /// } - /// - /// impl Serialize for E { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// match *self { - /// E::A => serializer.serialize_unit_variant("E", 0, "A"), - /// E::B => serializer.serialize_unit_variant("E", 1, "B"), - /// } - /// } - /// } - /// ``` - fn serialize_unit_variant( - self, - name: &'static str, - variant_index: u32, - variant: &'static str, - ) -> Result<Self::Ok, Self::Error>; - - /// Serialize a newtype struct like `struct Millimeters(u8)`. - /// - /// Serializers are encouraged to treat newtype structs as insignificant - /// wrappers around the data they contain. A reasonable implementation would - /// be to forward to `value.serialize(self)`. - /// - /// ```rust - /// use serde::{Serialize, Serializer}; - /// - /// struct Millimeters(u8); - /// - /// impl Serialize for Millimeters { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.serialize_newtype_struct("Millimeters", &self.0) - /// } - /// } - /// ``` - fn serialize_newtype_struct<T: ?Sized>( - self, - name: &'static str, - value: &T, - ) -> Result<Self::Ok, Self::Error> - where - T: Serialize; - - /// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`. - /// - /// The `name` is the name of the enum, the `variant_index` is the index of - /// this variant within the enum, and the `variant` is the name of the - /// variant. The `value` is the data contained within this newtype variant. - /// - /// ```rust - /// use serde::{Serialize, Serializer}; - /// - /// enum E { - /// M(String), - /// N(u8), - /// } - /// - /// impl Serialize for E { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// match *self { - /// E::M(ref s) => serializer.serialize_newtype_variant("E", 0, "M", s), - /// E::N(n) => serializer.serialize_newtype_variant("E", 1, "N", &n), - /// } - /// } - /// } - /// ``` - fn serialize_newtype_variant<T: ?Sized>( - self, - name: &'static str, - variant_index: u32, - variant: &'static str, - value: &T, - ) -> Result<Self::Ok, Self::Error> - where - T: Serialize; - - /// Begin to serialize a variably sized sequence. This call must be - /// followed by zero or more calls to `serialize_element`, then a call to - /// `end`. - /// - /// The argument is the number of elements in the sequence, which may or may - /// not be computable before the sequence is iterated. Some serializers only - /// support sequences whose length is known up front. - /// - /// ```rust - /// # use std::marker::PhantomData; - /// # - /// # struct Vec<T>(PhantomData<T>); - /// # - /// # impl<T> Vec<T> { - /// # fn len(&self) -> usize { - /// # unimplemented!() - /// # } - /// # } - /// # - /// # impl<'a, T> IntoIterator for &'a Vec<T> { - /// # type Item = &'a T; - /// # type IntoIter = Box<Iterator<Item = &'a T>>; - /// # - /// # fn into_iter(self) -> Self::IntoIter { - /// # unimplemented!() - /// # } - /// # } - /// # - /// use serde::ser::{Serialize, Serializer, SerializeSeq}; - /// - /// impl<T> Serialize for Vec<T> - /// where T: Serialize - /// { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// let mut seq = serializer.serialize_seq(Some(self.len()))?; - /// for element in self { - /// seq.serialize_element(element)?; - /// } - /// seq.end() - /// } - /// } - /// ``` - fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>; - - /// Begin to serialize a statically sized sequence whose length will be - /// known at deserialization time without looking at the serialized data. - /// This call must be followed by zero or more calls to `serialize_element`, - /// then a call to `end`. - /// - /// ```rust - /// use serde::ser::{Serialize, Serializer, SerializeTuple}; - /// - /// # mod fool { - /// # trait Serialize {} - /// impl<A, B, C> Serialize for (A, B, C) - /// # {} - /// # } - /// # - /// # struct Tuple3<A, B, C>(A, B, C); - /// # - /// # impl<A, B, C> Serialize for Tuple3<A, B, C> - /// where A: Serialize, - /// B: Serialize, - /// C: Serialize - /// { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// let mut tup = serializer.serialize_tuple(3)?; - /// tup.serialize_element(&self.0)?; - /// tup.serialize_element(&self.1)?; - /// tup.serialize_element(&self.2)?; - /// tup.end() - /// } - /// } - /// ``` - /// - /// ```rust - /// use serde::ser::{Serialize, Serializer, SerializeTuple}; - /// - /// const VRAM_SIZE: usize = 386; - /// struct Vram([u16; VRAM_SIZE]); - /// - /// impl Serialize for Vram { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// let mut seq = serializer.serialize_tuple(VRAM_SIZE)?; - /// for element in &self.0[..] { - /// seq.serialize_element(element)?; - /// } - /// seq.end() - /// } - /// } - /// ``` - fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>; - - /// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This - /// call must be followed by zero or more calls to `serialize_field`, then a - /// call to `end`. - /// - /// The `name` is the name of the tuple struct and the `len` is the number - /// of data fields that will be serialized. - /// - /// ```rust - /// use serde::ser::{Serialize, Serializer, SerializeTupleStruct}; - /// - /// struct Rgb(u8, u8, u8); - /// - /// impl Serialize for Rgb { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; - /// ts.serialize_field(&self.0)?; - /// ts.serialize_field(&self.1)?; - /// ts.serialize_field(&self.2)?; - /// ts.end() - /// } - /// } - /// ``` - fn serialize_tuple_struct( - self, - name: &'static str, - len: usize, - ) -> Result<Self::SerializeTupleStruct, Self::Error>; - - /// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8) - /// }`. This call must be followed by zero or more calls to - /// `serialize_field`, then a call to `end`. - /// - /// The `name` is the name of the enum, the `variant_index` is the index of - /// this variant within the enum, the `variant` is the name of the variant, - /// and the `len` is the number of data fields that will be serialized. - /// - /// ```rust - /// use serde::ser::{Serialize, Serializer, SerializeTupleVariant}; - /// - /// enum E { - /// T(u8, u8), - /// U(String, u32, u32), - /// } - /// - /// impl Serialize for E { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// match *self { - /// E::T(ref a, ref b) => { - /// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; - /// tv.serialize_field(a)?; - /// tv.serialize_field(b)?; - /// tv.end() - /// } - /// E::U(ref a, ref b, ref c) => { - /// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?; - /// tv.serialize_field(a)?; - /// tv.serialize_field(b)?; - /// tv.serialize_field(c)?; - /// tv.end() - /// } - /// } - /// } - /// } - /// ``` - fn serialize_tuple_variant( - self, - name: &'static str, - variant_index: u32, - variant: &'static str, - len: usize, - ) -> Result<Self::SerializeTupleVariant, Self::Error>; - - /// Begin to serialize a map. This call must be followed by zero or more - /// calls to `serialize_key` and `serialize_value`, then a call to `end`. - /// - /// The argument is the number of elements in the map, which may or may not - /// be computable before the map is iterated. Some serializers only support - /// maps whose length is known up front. - /// - /// ```rust - /// # use std::marker::PhantomData; - /// # - /// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>); - /// # - /// # impl<K, V> HashMap<K, V> { - /// # fn len(&self) -> usize { - /// # unimplemented!() - /// # } - /// # } - /// # - /// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> { - /// # type Item = (&'a K, &'a V); - /// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>; - /// # - /// # fn into_iter(self) -> Self::IntoIter { - /// # unimplemented!() - /// # } - /// # } - /// # - /// use serde::ser::{Serialize, Serializer, SerializeMap}; - /// - /// impl<K, V> Serialize for HashMap<K, V> - /// where K: Serialize, - /// V: Serialize - /// { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// let mut map = serializer.serialize_map(Some(self.len()))?; - /// for (k, v) in self { - /// map.serialize_entry(k, v)?; - /// } - /// map.end() - /// } - /// } - /// ``` - fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>; - - /// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`. - /// This call must be followed by zero or more calls to `serialize_field`, - /// then a call to `end`. - /// - /// The `name` is the name of the struct and the `len` is the number of - /// data fields that will be serialized. - /// - /// ```rust - /// use serde::ser::{Serialize, Serializer, SerializeStruct}; - /// - /// struct Rgb { - /// r: u8, - /// g: u8, - /// b: u8, - /// } - /// - /// impl Serialize for Rgb { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// let mut rgb = serializer.serialize_struct("Rgb", 3)?; - /// rgb.serialize_field("r", &self.r)?; - /// rgb.serialize_field("g", &self.g)?; - /// rgb.serialize_field("b", &self.b)?; - /// rgb.end() - /// } - /// } - /// ``` - fn serialize_struct( - self, - name: &'static str, - len: usize, - ) -> Result<Self::SerializeStruct, Self::Error>; - - /// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8, - /// g: u8, b: u8 } }`. This call must be followed by zero or more calls to - /// `serialize_field`, then a call to `end`. - /// - /// The `name` is the name of the enum, the `variant_index` is the index of - /// this variant within the enum, the `variant` is the name of the variant, - /// and the `len` is the number of data fields that will be serialized. - /// - /// ```rust - /// use serde::ser::{Serialize, Serializer, SerializeStructVariant}; - /// - /// enum E { - /// S { r: u8, g: u8, b: u8 } - /// } - /// - /// impl Serialize for E { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// match *self { - /// E::S { ref r, ref g, ref b } => { - /// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; - /// sv.serialize_field("r", r)?; - /// sv.serialize_field("g", g)?; - /// sv.serialize_field("b", b)?; - /// sv.end() - /// } - /// } - /// } - /// } - /// ``` - fn serialize_struct_variant( - self, - name: &'static str, - variant_index: u32, - variant: &'static str, - len: usize, - ) -> Result<Self::SerializeStructVariant, Self::Error>; - - /// Collect an iterator as a sequence. - /// - /// The default implementation serializes each item yielded by the iterator - /// using [`serialize_seq`]. Implementors should not need to override this - /// method. - /// - /// ```rust - /// use serde::{Serialize, Serializer}; - /// - /// struct SecretlyOneHigher { - /// data: Vec<i32>, - /// } - /// - /// impl Serialize for SecretlyOneHigher { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.collect_seq(self.data.iter().map(|x| x + 1)) - /// } - /// } - /// ``` - /// - /// [`serialize_seq`]: #tymethod.serialize_seq - fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error> - where - I: IntoIterator, - <I as IntoIterator>::Item: Serialize, - { - let iter = iter.into_iter(); - let mut serializer = try!(self.serialize_seq(iter.len_hint())); - for item in iter { - try!(serializer.serialize_element(&item)); - } - serializer.end() - } - - /// Collect an iterator as a map. - /// - /// The default implementation serializes each pair yielded by the iterator - /// using [`serialize_map`]. Implementors should not need to override this - /// method. - /// - /// ```rust - /// use std::collections::BTreeSet; - /// use serde::{Serialize, Serializer}; - /// - /// struct MapToUnit { - /// keys: BTreeSet<i32>, - /// } - /// - /// // Serializes as a map in which the values are all unit. - /// impl Serialize for MapToUnit { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.collect_map(self.keys.iter().map(|k| (k, ()))) - /// } - /// } - /// ``` - /// - /// [`serialize_map`]: #tymethod.serialize_map - fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error> - where - K: Serialize, - V: Serialize, - I: IntoIterator<Item = (K, V)>, - { - let iter = iter.into_iter(); - let mut serializer = try!(self.serialize_map(iter.len_hint())); - for (key, value) in iter { - try!(serializer.serialize_entry(&key, &value)); - } - serializer.end() - } - - /// Serialize a string produced by an implementation of `Display`. - /// - /// The default implementation builds a heap-allocated [`String`] and - /// delegates to [`serialize_str`]. Serializers are encouraged to provide a - /// more efficient implementation if possible. - /// - /// ```rust - /// # struct DateTime; - /// # - /// # impl DateTime { - /// # fn naive_local(&self) -> () { () } - /// # fn offset(&self) -> () { () } - /// # } - /// # - /// use serde::{Serialize, Serializer}; - /// - /// impl Serialize for DateTime { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.collect_str(&format_args!("{:?}{:?}", - /// self.naive_local(), - /// self.offset())) - /// } - /// } - /// ``` - /// - /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html - /// [`serialize_str`]: #tymethod.serialize_str - #[cfg(any(feature = "std", feature = "alloc"))] - fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> - where - T: Display, - { - use lib::fmt::Write; - let mut string = String::new(); - write!(string, "{}", value).unwrap(); - self.serialize_str(&string) - } - - /// Serialize a string produced by an implementation of `Display`. - /// - /// Serializers that use `no_std` are required to provide an implementation - /// of this method. If no more sensible behavior is possible, the - /// implementation is expected to return an error. - /// - /// ```rust - /// # struct DateTime; - /// # - /// # impl DateTime { - /// # fn naive_local(&self) -> () { () } - /// # fn offset(&self) -> () { () } - /// # } - /// # - /// use serde::{Serialize, Serializer}; - /// - /// impl Serialize for DateTime { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// serializer.collect_str(&format_args!("{:?}{:?}", - /// self.naive_local(), - /// self.offset())) - /// } - /// } - /// ``` - #[cfg(not(any(feature = "std", feature = "alloc")))] - fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> - where - T: Display; - - /// Determine whether `Serialize` implementations should serialize in - /// human-readable form. - /// - /// Some types have a human-readable form that may be somewhat expensive to - /// construct, as well as a binary form that is compact and efficient. - /// Generally text-based formats like JSON and YAML will prefer to use the - /// human-readable one and binary formats like Bincode will prefer the - /// compact one. - /// - /// ``` - /// # use std::fmt::{self, Display}; - /// # - /// # struct Timestamp; - /// # - /// # impl Timestamp { - /// # fn seconds_since_epoch(&self) -> u64 { unimplemented!() } - /// # } - /// # - /// # impl Display for Timestamp { - /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - /// # unimplemented!() - /// # } - /// # } - /// # - /// use serde::{Serialize, Serializer}; - /// - /// impl Serialize for Timestamp { - /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - /// where S: Serializer - /// { - /// if serializer.is_human_readable() { - /// // Serialize to a human-readable string "2015-05-15T17:01:00Z". - /// self.to_string().serialize(serializer) - /// } else { - /// // Serialize to a compact binary representation. - /// self.seconds_since_epoch().serialize(serializer) - /// } - /// } - /// } - /// ``` - /// - /// The default implementation of this method returns `true`. Data formats - /// may override this to `false` to request a compact form for types that - /// support one. Note that modifying this method to change a format from - /// human-readable to compact or vice versa should be regarded as a breaking - /// change, as a value serialized in human-readable mode is not required to - /// deserialize from the same data in compact mode. - #[inline] - fn is_human_readable(&self) -> bool { - true - } -} - -/// Returned from `Serializer::serialize_seq`. -/// -/// ```rust -/// # use std::marker::PhantomData; -/// # -/// # struct Vec<T>(PhantomData<T>); -/// # -/// # impl<T> Vec<T> { -/// # fn len(&self) -> usize { -/// # unimplemented!() -/// # } -/// # } -/// # -/// # impl<'a, T> IntoIterator for &'a Vec<T> { -/// # type Item = &'a T; -/// # type IntoIter = Box<Iterator<Item = &'a T>>; -/// # fn into_iter(self) -> Self::IntoIter { -/// # unimplemented!() -/// # } -/// # } -/// # -/// use serde::ser::{Serialize, Serializer, SerializeSeq}; -/// -/// impl<T> Serialize for Vec<T> -/// where T: Serialize -/// { -/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> -/// where S: Serializer -/// { -/// let mut seq = serializer.serialize_seq(Some(self.len()))?; -/// for element in self { -/// seq.serialize_element(element)?; -/// } -/// seq.end() -/// } -/// } -/// ``` -pub trait SerializeSeq { - /// Must match the `Ok` type of our `Serializer`. - type Ok; - - /// Must match the `Error` type of our `Serializer`. - type Error: Error; - - /// Serialize a sequence element. - fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> - where - T: Serialize; - - /// Finish serializing a sequence. - fn end(self) -> Result<Self::Ok, Self::Error>; -} - -/// Returned from `Serializer::serialize_tuple`. -/// -/// ```rust -/// use serde::ser::{Serialize, Serializer, SerializeTuple}; -/// -/// # mod fool { -/// # trait Serialize {} -/// impl<A, B, C> Serialize for (A, B, C) -/// # {} -/// # } -/// # -/// # struct Tuple3<A, B, C>(A, B, C); -/// # -/// # impl<A, B, C> Serialize for Tuple3<A, B, C> -/// where A: Serialize, -/// B: Serialize, -/// C: Serialize -/// { -/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> -/// where S: Serializer -/// { -/// let mut tup = serializer.serialize_tuple(3)?; -/// tup.serialize_element(&self.0)?; -/// tup.serialize_element(&self.1)?; -/// tup.serialize_element(&self.2)?; -/// tup.end() -/// } -/// } -/// ``` -/// -/// ```rust -/// # use std::marker::PhantomData; -/// # -/// # struct Array<T>(PhantomData<T>); -/// # -/// # impl<T> Array<T> { -/// # fn len(&self) -> usize { -/// # unimplemented!() -/// # } -/// # } -/// # -/// # impl<'a, T> IntoIterator for &'a Array<T> { -/// # type Item = &'a T; -/// # type IntoIter = Box<Iterator<Item = &'a T>>; -/// # fn into_iter(self) -> Self::IntoIter { -/// # unimplemented!() -/// # } -/// # } -/// # -/// use serde::ser::{Serialize, Serializer, SerializeTuple}; -/// -/// # mod fool { -/// # trait Serialize {} -/// impl<T> Serialize for [T; 16] -/// # {} -/// # } -/// # -/// # impl<T> Serialize for Array<T> -/// where T: Serialize -/// { -/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> -/// where S: Serializer -/// { -/// let mut seq = serializer.serialize_tuple(16)?; -/// for element in self { -/// seq.serialize_element(element)?; -/// } -/// seq.end() -/// } -/// } -/// ``` -pub trait SerializeTuple { - /// Must match the `Ok` type of our `Serializer`. - type Ok; - - /// Must match the `Error` type of our `Serializer`. - type Error: Error; - - /// Serialize a tuple element. - fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> - where - T: Serialize; - - /// Finish serializing a tuple. - fn end(self) -> Result<Self::Ok, Self::Error>; -} - -/// Returned from `Serializer::serialize_tuple_struct`. -/// -/// ```rust -/// use serde::ser::{Serialize, Serializer, SerializeTupleStruct}; -/// -/// struct Rgb(u8, u8, u8); -/// -/// impl Serialize for Rgb { -/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> -/// where S: Serializer -/// { -/// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; -/// ts.serialize_field(&self.0)?; -/// ts.serialize_field(&self.1)?; -/// ts.serialize_field(&self.2)?; -/// ts.end() -/// } -/// } -/// ``` -pub trait SerializeTupleStruct { - /// Must match the `Ok` type of our `Serializer`. - type Ok; - - /// Must match the `Error` type of our `Serializer`. - type Error: Error; - - /// Serialize a tuple struct field. - fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> - where - T: Serialize; - - /// Finish serializing a tuple struct. - fn end(self) -> Result<Self::Ok, Self::Error>; -} - -/// Returned from `Serializer::serialize_tuple_variant`. -/// -/// ```rust -/// use serde::ser::{Serialize, Serializer, SerializeTupleVariant}; -/// -/// enum E { -/// T(u8, u8), -/// U(String, u32, u32), -/// } -/// -/// impl Serialize for E { -/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> -/// where S: Serializer -/// { -/// match *self { -/// E::T(ref a, ref b) => { -/// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; -/// tv.serialize_field(a)?; -/// tv.serialize_field(b)?; -/// tv.end() -/// } -/// E::U(ref a, ref b, ref c) => { -/// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?; -/// tv.serialize_field(a)?; -/// tv.serialize_field(b)?; -/// tv.serialize_field(c)?; -/// tv.end() -/// } -/// } -/// } -/// } -/// ``` -pub trait SerializeTupleVariant { - /// Must match the `Ok` type of our `Serializer`. - type Ok; - - /// Must match the `Error` type of our `Serializer`. - type Error: Error; - - /// Serialize a tuple variant field. - fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> - where - T: Serialize; - - /// Finish serializing a tuple variant. - fn end(self) -> Result<Self::Ok, Self::Error>; -} - -/// Returned from `Serializer::serialize_map`. -/// -/// ```rust -/// # use std::marker::PhantomData; -/// # -/// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>); -/// # -/// # impl<K, V> HashMap<K, V> { -/// # fn len(&self) -> usize { -/// # unimplemented!() -/// # } -/// # } -/// # -/// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> { -/// # type Item = (&'a K, &'a V); -/// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>; -/// # -/// # fn into_iter(self) -> Self::IntoIter { -/// # unimplemented!() -/// # } -/// # } -/// # -/// use serde::ser::{Serialize, Serializer, SerializeMap}; -/// -/// impl<K, V> Serialize for HashMap<K, V> -/// where K: Serialize, -/// V: Serialize -/// { -/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> -/// where S: Serializer -/// { -/// let mut map = serializer.serialize_map(Some(self.len()))?; -/// for (k, v) in self { -/// map.serialize_entry(k, v)?; -/// } -/// map.end() -/// } -/// } -/// ``` -pub trait SerializeMap { - /// Must match the `Ok` type of our `Serializer`. - type Ok; - - /// Must match the `Error` type of our `Serializer`. - type Error: Error; - - /// Serialize a map key. - /// - /// If possible, `Serialize` implementations are encouraged to use - /// `serialize_entry` instead as it may be implemented more efficiently in - /// some formats compared to a pair of calls to `serialize_key` and - /// `serialize_value`. - fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> - where - T: Serialize; - - /// Serialize a map value. - /// - /// # Panics - /// - /// Calling `serialize_value` before `serialize_key` is incorrect and is - /// allowed to panic or produce bogus results. - fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> - where - T: Serialize; - - /// Serialize a map entry consisting of a key and a value. - /// - /// Some [`Serialize`] types are not able to hold a key and value in memory - /// at the same time so `SerializeMap` implementations are required to - /// support [`serialize_key`] and [`serialize_value`] individually. The - /// `serialize_entry` method allows serializers to optimize for the case - /// where key and value are both available. [`Serialize`] implementations - /// are encouraged to use `serialize_entry` if possible. - /// - /// The default implementation delegates to [`serialize_key`] and - /// [`serialize_value`]. This is appropriate for serializers that do not - /// care about performance or are not able to optimize `serialize_entry` any - /// better than this. - /// - /// [`Serialize`]: ../trait.Serialize.html - /// [`serialize_key`]: #tymethod.serialize_key - /// [`serialize_value`]: #tymethod.serialize_value - fn serialize_entry<K: ?Sized, V: ?Sized>( - &mut self, - key: &K, - value: &V, - ) -> Result<(), Self::Error> - where - K: Serialize, - V: Serialize, - { - try!(self.serialize_key(key)); - self.serialize_value(value) - } - - /// Finish serializing a map. - fn end(self) -> Result<Self::Ok, Self::Error>; -} - -/// Returned from `Serializer::serialize_struct`. -/// -/// ```rust -/// use serde::ser::{Serialize, Serializer, SerializeStruct}; -/// -/// struct Rgb { -/// r: u8, -/// g: u8, -/// b: u8, -/// } -/// -/// impl Serialize for Rgb { -/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> -/// where S: Serializer -/// { -/// let mut rgb = serializer.serialize_struct("Rgb", 3)?; -/// rgb.serialize_field("r", &self.r)?; -/// rgb.serialize_field("g", &self.g)?; -/// rgb.serialize_field("b", &self.b)?; -/// rgb.end() -/// } -/// } -/// ``` -pub trait SerializeStruct { - /// Must match the `Ok` type of our `Serializer`. - type Ok; - - /// Must match the `Error` type of our `Serializer`. - type Error: Error; - - /// Serialize a struct field. - fn serialize_field<T: ?Sized>( - &mut self, - key: &'static str, - value: &T, - ) -> Result<(), Self::Error> - where - T: Serialize; - - /// Indicate that a struct field has been skipped. - #[inline] - fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { - let _ = key; - Ok(()) - } - - /// Finish serializing a struct. - fn end(self) -> Result<Self::Ok, Self::Error>; -} - -/// Returned from `Serializer::serialize_struct_variant`. -/// -/// ```rust -/// use serde::ser::{Serialize, Serializer, SerializeStructVariant}; -/// -/// enum E { -/// S { r: u8, g: u8, b: u8 } -/// } -/// -/// impl Serialize for E { -/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> -/// where S: Serializer -/// { -/// match *self { -/// E::S { ref r, ref g, ref b } => { -/// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; -/// sv.serialize_field("r", r)?; -/// sv.serialize_field("g", g)?; -/// sv.serialize_field("b", b)?; -/// sv.end() -/// } -/// } -/// } -/// } -/// ``` -pub trait SerializeStructVariant { - /// Must match the `Ok` type of our `Serializer`. - type Ok; - - /// Must match the `Error` type of our `Serializer`. - type Error: Error; - - /// Serialize a struct variant field. - fn serialize_field<T: ?Sized>( - &mut self, - key: &'static str, - value: &T, - ) -> Result<(), Self::Error> - where - T: Serialize; - - /// Indicate that a struct variant field has been skipped. - #[inline] - fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { - let _ = key; - Ok(()) - } - - /// Finish serializing a struct variant. - fn end(self) -> Result<Self::Ok, Self::Error>; -} - -trait LenHint: Iterator { - fn len_hint(&self) -> Option<usize>; -} - -impl<I> LenHint for I -where - I: Iterator, -{ - #[cfg(not(feature = "unstable"))] - fn len_hint(&self) -> Option<usize> { - iterator_len_hint(self) - } - - #[cfg(feature = "unstable")] - default fn len_hint(&self) -> Option<usize> { - iterator_len_hint(self) - } -} - -#[cfg(feature = "unstable")] -impl<I> LenHint for I -where - I: ExactSizeIterator, -{ - fn len_hint(&self) -> Option<usize> { - Some(self.len()) - } -} - -fn iterator_len_hint<I>(iter: &I) -> Option<usize> -where - I: Iterator, -{ - match iter.size_hint() { - (lo, Some(hi)) if lo == hi => Some(lo), - _ => None, - } -} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/.cargo-checksum.json cargo-0.26.0/vendor/serde-1.0.37/.cargo-checksum.json --- cargo-0.25.0/vendor/serde-1.0.37/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"d3bcee660dcde8f52c3765dd9ca5ee36b4bf35470a738eb0bd5a8752b0389645"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/serde-1.0.37/Cargo.toml cargo-0.26.0/vendor/serde-1.0.37/Cargo.toml --- cargo-0.25.0/vendor/serde-1.0.37/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,44 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "serde" +version = "1.0.37" +authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"] +include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] +description = "A generic serialization/deserialization framework" +homepage = "https://serde.rs" +documentation = "https://docs.serde.rs/serde/" +readme = "README.md" +keywords = ["serde", "serialization", "no_std"] +categories = ["encoding"] +license = "MIT/Apache-2.0" +repository = "https://github.com/serde-rs/serde" +[dependencies.serde_derive] +version = "1.0" +optional = true +[dev-dependencies.serde_derive] +version = "1.0" + +[features] +alloc = ["unstable"] +default = ["std"] +derive = ["serde_derive"] +playground = ["serde_derive"] +rc = [] +std = [] +unstable = [] +[badges.appveyor] +repository = "serde-rs/serde" + +[badges.travis-ci] +repository = "serde-rs/serde" diff -Nru cargo-0.25.0/vendor/serde-1.0.37/LICENSE-APACHE cargo-0.26.0/vendor/serde-1.0.37/LICENSE-APACHE --- cargo-0.25.0/vendor/serde-1.0.37/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/serde-1.0.37/LICENSE-MIT cargo-0.26.0/vendor/serde-1.0.37/LICENSE-MIT --- cargo-0.25.0/vendor/serde-1.0.37/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/serde-1.0.37/README.md cargo-0.26.0/vendor/serde-1.0.37/README.md --- cargo-0.25.0/vendor/serde-1.0.37/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,104 @@ +# Serde   [![Build Status]][travis] [![Latest Version]][crates.io] [![Rustc Version 1.13+]][rustc] + +[Build Status]: https://api.travis-ci.org/serde-rs/serde.svg?branch=master +[travis]: https://travis-ci.org/serde-rs/serde +[Latest Version]: https://img.shields.io/crates/v/serde.svg +[crates.io]: https://crates.io/crates/serde +[Rustc Version 1.13+]: https://img.shields.io/badge/rustc-1.13+-lightgray.svg +[rustc]: https://blog.rust-lang.org/2016/11/10/Rust-1.13.html + +**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** + +--- + +You may be looking for: + +- [An overview of Serde](https://serde.rs/) +- [Data formats supported by Serde](https://serde.rs/#data-formats) +- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html) +- [Examples](https://serde.rs/examples.html) +- [API documentation](https://docs.serde.rs/serde/) +- [Release notes](https://github.com/serde-rs/serde/releases) + +## Serde in action + +<details> +<summary> +Click to show Cargo.toml. +<a href="http://play.integer32.com/?gist=9003c5b88c1f4989941925d7190c6eec" target="_blank">Run this code in the playground.</a> +</summary> + +```toml +[dependencies] + +# The core APIs, including the Serialize and Deserialize traits. Always +# required when using Serde. +serde = "1.0" + +# Support for #[derive(Serialize, Deserialize)]. Required if you want Serde +# to work for structs and enums defined in your crate. +serde_derive = "1.0" + +# Each data format lives in its own crate; the sample code below uses JSON +# but you may be using a different one. +serde_json = "1.0" +``` + +</details> +<p></p> + +```rust +#[macro_use] +extern crate serde_derive; + +extern crate serde; +extern crate serde_json; + +#[derive(Serialize, Deserialize, Debug)] +struct Point { + x: i32, + y: i32, +} + +fn main() { + let point = Point { x: 1, y: 2 }; + + // Convert the Point to a JSON string. + let serialized = serde_json::to_string(&point).unwrap(); + + // Prints serialized = {"x":1,"y":2} + println!("serialized = {}", serialized); + + // Convert the JSON string back to a Point. + let deserialized: Point = serde_json::from_str(&serialized).unwrap(); + + // Prints deserialized = Point { x: 1, y: 2 } + println!("deserialized = {:?}", deserialized); +} +``` + +## Getting help + +Serde developers live in the #serde channel on +[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a +good resource with generally faster response time but less specific knowledge +about Serde. If IRC is not your thing or you don't get a good response, we are +happy to respond to [GitHub issues](https://github.com/serde-rs/serde/issues/new) +as well. + +## License + +Serde is 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 Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/de/from_primitive.rs cargo-0.26.0/vendor/serde-1.0.37/src/de/from_primitive.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/de/from_primitive.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/de/from_primitive.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,206 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use lib::*; + +macro_rules! int_to_int { + ($dst:ident, $n:ident) => { + if $dst::min_value() as i64 <= $n as i64 && $n as i64 <= $dst::max_value() as i64 { + Some($n as $dst) + } else { + None + } + }; +} + +macro_rules! int_to_uint { + ($dst:ident, $n:ident) => { + if 0 <= $n && $n as u64 <= $dst::max_value() as u64 { + Some($n as $dst) + } else { + None + } + }; +} + +macro_rules! uint_to { + ($dst:ident, $n:ident) => { + if $n as u64 <= $dst::max_value() as u64 { + Some($n as $dst) + } else { + None + } + }; +} + +pub trait FromPrimitive: Sized { + fn from_isize(n: isize) -> Option<Self>; + fn from_i8(n: i8) -> Option<Self>; + fn from_i16(n: i16) -> Option<Self>; + fn from_i32(n: i32) -> Option<Self>; + fn from_i64(n: i64) -> Option<Self>; + fn from_usize(n: usize) -> Option<Self>; + fn from_u8(n: u8) -> Option<Self>; + fn from_u16(n: u16) -> Option<Self>; + fn from_u32(n: u32) -> Option<Self>; + fn from_u64(n: u64) -> Option<Self>; +} + +macro_rules! impl_from_primitive_for_int { + ($t:ident) => { + impl FromPrimitive for $t { + #[inline] + fn from_isize(n: isize) -> Option<Self> { + int_to_int!($t, n) + } + #[inline] + fn from_i8(n: i8) -> Option<Self> { + int_to_int!($t, n) + } + #[inline] + fn from_i16(n: i16) -> Option<Self> { + int_to_int!($t, n) + } + #[inline] + fn from_i32(n: i32) -> Option<Self> { + int_to_int!($t, n) + } + #[inline] + fn from_i64(n: i64) -> Option<Self> { + int_to_int!($t, n) + } + #[inline] + fn from_usize(n: usize) -> Option<Self> { + uint_to!($t, n) + } + #[inline] + fn from_u8(n: u8) -> Option<Self> { + uint_to!($t, n) + } + #[inline] + fn from_u16(n: u16) -> Option<Self> { + uint_to!($t, n) + } + #[inline] + fn from_u32(n: u32) -> Option<Self> { + uint_to!($t, n) + } + #[inline] + fn from_u64(n: u64) -> Option<Self> { + uint_to!($t, n) + } + } + }; +} + +macro_rules! impl_from_primitive_for_uint { + ($t:ident) => { + impl FromPrimitive for $t { + #[inline] + fn from_isize(n: isize) -> Option<Self> { + int_to_uint!($t, n) + } + #[inline] + fn from_i8(n: i8) -> Option<Self> { + int_to_uint!($t, n) + } + #[inline] + fn from_i16(n: i16) -> Option<Self> { + int_to_uint!($t, n) + } + #[inline] + fn from_i32(n: i32) -> Option<Self> { + int_to_uint!($t, n) + } + #[inline] + fn from_i64(n: i64) -> Option<Self> { + int_to_uint!($t, n) + } + #[inline] + fn from_usize(n: usize) -> Option<Self> { + uint_to!($t, n) + } + #[inline] + fn from_u8(n: u8) -> Option<Self> { + uint_to!($t, n) + } + #[inline] + fn from_u16(n: u16) -> Option<Self> { + uint_to!($t, n) + } + #[inline] + fn from_u32(n: u32) -> Option<Self> { + uint_to!($t, n) + } + #[inline] + fn from_u64(n: u64) -> Option<Self> { + uint_to!($t, n) + } + } + }; +} + +macro_rules! impl_from_primitive_for_float { + ($t:ident) => { + impl FromPrimitive for $t { + #[inline] + fn from_isize(n: isize) -> Option<Self> { + Some(n as Self) + } + #[inline] + fn from_i8(n: i8) -> Option<Self> { + Some(n as Self) + } + #[inline] + fn from_i16(n: i16) -> Option<Self> { + Some(n as Self) + } + #[inline] + fn from_i32(n: i32) -> Option<Self> { + Some(n as Self) + } + #[inline] + fn from_i64(n: i64) -> Option<Self> { + Some(n as Self) + } + #[inline] + fn from_usize(n: usize) -> Option<Self> { + Some(n as Self) + } + #[inline] + fn from_u8(n: u8) -> Option<Self> { + Some(n as Self) + } + #[inline] + fn from_u16(n: u16) -> Option<Self> { + Some(n as Self) + } + #[inline] + fn from_u32(n: u32) -> Option<Self> { + Some(n as Self) + } + #[inline] + fn from_u64(n: u64) -> Option<Self> { + Some(n as Self) + } + } + }; +} + +impl_from_primitive_for_int!(isize); +impl_from_primitive_for_int!(i8); +impl_from_primitive_for_int!(i16); +impl_from_primitive_for_int!(i32); +impl_from_primitive_for_int!(i64); +impl_from_primitive_for_uint!(usize); +impl_from_primitive_for_uint!(u8); +impl_from_primitive_for_uint!(u16); +impl_from_primitive_for_uint!(u32); +impl_from_primitive_for_uint!(u64); +impl_from_primitive_for_float!(f32); +impl_from_primitive_for_float!(f64); diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/de/ignored_any.rs cargo-0.26.0/vendor/serde-1.0.37/src/de/ignored_any.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/de/ignored_any.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/de/ignored_any.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,215 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use lib::*; + +use de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Visitor}; + +/// An efficient way of discarding data from a deserializer. +/// +/// Think of this like `serde_json::Value` in that it can be deserialized from +/// any type, except that it does not store any information about the data that +/// gets deserialized. +/// +/// ```rust +/// use std::fmt; +/// use std::marker::PhantomData; +/// +/// use serde::de::{self, Deserialize, DeserializeSeed, Deserializer, Visitor, SeqAccess, IgnoredAny}; +/// +/// /// A seed that can be used to deserialize only the `n`th element of a sequence +/// /// while efficiently discarding elements of any type before or after index `n`. +/// /// +/// /// For example to deserialize only the element at index 3: +/// /// +/// /// ```rust +/// /// NthElement::new(3).deserialize(deserializer) +/// /// ``` +/// pub struct NthElement<T> { +/// n: usize, +/// marker: PhantomData<T>, +/// } +/// +/// impl<T> NthElement<T> { +/// pub fn new(n: usize) -> Self { +/// NthElement { +/// n: n, +/// marker: PhantomData, +/// } +/// } +/// } +/// +/// impl<'de, T> Visitor<'de> for NthElement<T> +/// where T: Deserialize<'de> +/// { +/// type Value = T; +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!(formatter, "a sequence in which we care about element {}", self.n) +/// } +/// +/// fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> +/// where A: SeqAccess<'de> +/// { +/// // Skip over the first `n` elements. +/// for i in 0..self.n { +/// // It is an error if the sequence ends before we get to element `n`. +/// if seq.next_element::<IgnoredAny>()?.is_none() { +/// return Err(de::Error::invalid_length(i, &self)); +/// } +/// } +/// +/// // Deserialize the one we care about. +/// let nth = match seq.next_element()? { +/// Some(nth) => nth, +/// None => { +/// return Err(de::Error::invalid_length(self.n, &self)); +/// } +/// }; +/// +/// // Skip over any remaining elements in the sequence after `n`. +/// while let Some(IgnoredAny) = seq.next_element()? { +/// // ignore +/// } +/// +/// Ok(nth) +/// } +/// } +/// +/// impl<'de, T> DeserializeSeed<'de> for NthElement<T> +/// where T: Deserialize<'de> +/// { +/// type Value = T; +/// +/// fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> +/// where D: Deserializer<'de> +/// { +/// deserializer.deserialize_seq(self) +/// } +/// } +/// +/// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error> +/// # where D: Deserializer<'de> +/// # { +/// // Deserialize only the sequence element at index 3 from this deserializer. +/// // The element at index 3 is required to be a string. Elements before and +/// // after index 3 are allowed to be of any type. +/// let s: String = NthElement::new(3).deserialize(deserializer)?; +/// # Ok(()) +/// # } +/// ``` +#[derive(Copy, Clone, Debug, Default)] +pub struct IgnoredAny; + +impl<'de> Visitor<'de> for IgnoredAny { + type Value = IgnoredAny; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("anything at all") + } + + #[inline] + fn visit_bool<E>(self, x: bool) -> Result<Self::Value, E> { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_i64<E>(self, x: i64) -> Result<Self::Value, E> { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_u64<E>(self, x: u64) -> Result<Self::Value, E> { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_f64<E>(self, x: f64) -> Result<Self::Value, E> { + let _ = x; + Ok(IgnoredAny) + } + + #[inline] + fn visit_str<E>(self, s: &str) -> Result<Self::Value, E> + where + E: Error, + { + let _ = s; + Ok(IgnoredAny) + } + + #[inline] + fn visit_none<E>(self) -> Result<Self::Value, E> { + Ok(IgnoredAny) + } + + #[inline] + fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + IgnoredAny::deserialize(deserializer) + } + + #[inline] + fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + IgnoredAny::deserialize(deserializer) + } + + #[inline] + fn visit_unit<E>(self) -> Result<Self::Value, E> { + Ok(IgnoredAny) + } + + #[inline] + fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error> + where + A: SeqAccess<'de>, + { + while let Some(IgnoredAny) = try!(seq.next_element()) { + // Gobble + } + Ok(IgnoredAny) + } + + #[inline] + fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> + where + A: MapAccess<'de>, + { + while let Some((IgnoredAny, IgnoredAny)) = try!(map.next_entry()) { + // Gobble + } + Ok(IgnoredAny) + } + + #[inline] + fn visit_bytes<E>(self, bytes: &[u8]) -> Result<Self::Value, E> + where + E: Error, + { + let _ = bytes; + Ok(IgnoredAny) + } +} + +impl<'de> Deserialize<'de> for IgnoredAny { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<IgnoredAny, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_ignored_any(IgnoredAny) + } +} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/de/impls.rs cargo-0.26.0/vendor/serde-1.0.37/src/de/impls.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/de/impls.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/de/impls.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2136 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use lib::*; + +use de::{Deserialize, Deserializer, EnumAccess, Error, SeqAccess, Unexpected, VariantAccess, + Visitor}; + +#[cfg(any(feature = "std", feature = "alloc"))] +use de::MapAccess; + +use de::from_primitive::FromPrimitive; +use private::de::InPlaceSeed; + +#[cfg(any(feature = "std", feature = "alloc"))] +use private::de::size_hint; + +//////////////////////////////////////////////////////////////////////////////// + +struct UnitVisitor; + +impl<'de> Visitor<'de> for UnitVisitor { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("unit") + } + + fn visit_unit<E>(self) -> Result<(), E> + where + E: Error, + { + Ok(()) + } +} + +impl<'de> Deserialize<'de> for () { + fn deserialize<D>(deserializer: D) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_unit(UnitVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +struct BoolVisitor; + +impl<'de> Visitor<'de> for BoolVisitor { + type Value = bool; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a boolean") + } + + fn visit_bool<E>(self, v: bool) -> Result<bool, E> + where + E: Error, + { + Ok(v) + } +} + +impl<'de> Deserialize<'de> for bool { + fn deserialize<D>(deserializer: D) -> Result<bool, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_bool(BoolVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! visit_integer_method { + ($src_ty:ident, $method:ident, $from_method:ident, $group:ident, $group_ty:ident) => { + #[inline] + fn $method<E>(self, v: $src_ty) -> Result<Self::Value, E> + where + E: Error, + { + match FromPrimitive::$from_method(v) { + Some(v) => Ok(v), + None => Err(Error::invalid_value(Unexpected::$group(v as $group_ty), &self)), + } + } + } +} + +macro_rules! visit_float_method { + ($src_ty:ident, $method:ident) => { + #[inline] + fn $method<E>(self, v: $src_ty) -> Result<Self::Value, E> + where + E: Error, + { + Ok(v as Self::Value) + } + } +} + +macro_rules! impl_deserialize_num { + ($ty:ident, $method:ident, $($visit:ident),*) => { + impl<'de> Deserialize<'de> for $ty { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<$ty, D::Error> + where + D: Deserializer<'de>, + { + struct PrimitiveVisitor; + + impl<'de> Visitor<'de> for PrimitiveVisitor { + type Value = $ty; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(stringify!($ty)) + } + + $( + impl_deserialize_num!($visit $ty); + )* + } + + deserializer.$method(PrimitiveVisitor) + } + } + }; + + (integer $ty:ident) => { + visit_integer_method!(i8, visit_i8, from_i8, Signed, i64); + visit_integer_method!(i16, visit_i16, from_i16, Signed, i64); + visit_integer_method!(i32, visit_i32, from_i32, Signed, i64); + visit_integer_method!(i64, visit_i64, from_i64, Signed, i64); + + visit_integer_method!(u8, visit_u8, from_u8, Unsigned, u64); + visit_integer_method!(u16, visit_u16, from_u16, Unsigned, u64); + visit_integer_method!(u32, visit_u32, from_u32, Unsigned, u64); + visit_integer_method!(u64, visit_u64, from_u64, Unsigned, u64); + }; + + (float $ty:ident) => { + visit_float_method!(f32, visit_f32); + visit_float_method!(f64, visit_f64); + }; +} + +impl_deserialize_num!(i8, deserialize_i8, integer); +impl_deserialize_num!(i16, deserialize_i16, integer); +impl_deserialize_num!(i32, deserialize_i32, integer); +impl_deserialize_num!(i64, deserialize_i64, integer); +impl_deserialize_num!(isize, deserialize_i64, integer); + +impl_deserialize_num!(u8, deserialize_u8, integer); +impl_deserialize_num!(u16, deserialize_u16, integer); +impl_deserialize_num!(u32, deserialize_u32, integer); +impl_deserialize_num!(u64, deserialize_u64, integer); +impl_deserialize_num!(usize, deserialize_u64, integer); + +impl_deserialize_num!(f32, deserialize_f32, integer, float); +impl_deserialize_num!(f64, deserialize_f64, integer, float); + +//////////////////////////////////////////////////////////////////////////////// + +struct CharVisitor; + +impl<'de> Visitor<'de> for CharVisitor { + type Value = char; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a character") + } + + #[inline] + fn visit_char<E>(self, v: char) -> Result<char, E> + where + E: Error, + { + Ok(v) + } + + #[inline] + fn visit_str<E>(self, v: &str) -> Result<char, E> + where + E: Error, + { + let mut iter = v.chars(); + match (iter.next(), iter.next()) { + (Some(c), None) => Ok(c), + _ => Err(Error::invalid_value(Unexpected::Str(v), &self)), + } + } +} + +impl<'de> Deserialize<'de> for char { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<char, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_char(CharVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +struct StringVisitor; +#[cfg(any(feature = "std", feature = "alloc"))] +struct StringInPlaceVisitor<'a>(&'a mut String); + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de> Visitor<'de> for StringVisitor { + type Value = String; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string") + } + + fn visit_str<E>(self, v: &str) -> Result<String, E> + where + E: Error, + { + Ok(v.to_owned()) + } + + fn visit_string<E>(self, v: String) -> Result<String, E> + where + E: Error, + { + Ok(v) + } + + fn visit_bytes<E>(self, v: &[u8]) -> Result<String, E> + where + E: Error, + { + match str::from_utf8(v) { + Ok(s) => Ok(s.to_owned()), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<String, E> + where + E: Error, + { + match String::from_utf8(v) { + Ok(s) => Ok(s), + Err(e) => Err(Error::invalid_value( + Unexpected::Bytes(&e.into_bytes()), + &self, + )), + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, 'de> Visitor<'de> for StringInPlaceVisitor<'a> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string") + } + + fn visit_str<E>(self, v: &str) -> Result<(), E> + where + E: Error, + { + self.0.clear(); + self.0.push_str(v); + Ok(()) + } + + fn visit_string<E>(self, v: String) -> Result<(), E> + where + E: Error, + { + *self.0 = v; + Ok(()) + } + + fn visit_bytes<E>(self, v: &[u8]) -> Result<(), E> + where + E: Error, + { + match str::from_utf8(v) { + Ok(s) => { + self.0.clear(); + self.0.push_str(s); + Ok(()) + } + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<(), E> + where + E: Error, + { + match String::from_utf8(v) { + Ok(s) => { + *self.0 = s; + Ok(()) + } + Err(e) => Err(Error::invalid_value( + Unexpected::Bytes(&e.into_bytes()), + &self, + )), + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de> Deserialize<'de> for String { + fn deserialize<D>(deserializer: D) -> Result<String, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_string(StringVisitor) + } + + fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_string(StringInPlaceVisitor(place)) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +struct StrVisitor; + +impl<'a> Visitor<'a> for StrVisitor { + type Value = &'a str; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a borrowed string") + } + + fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> + where + E: Error, + { + Ok(v) // so easy + } + + fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> + where + E: Error, + { + str::from_utf8(v).map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self)) + } +} + +impl<'de: 'a, 'a> Deserialize<'de> for &'a str { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_str(StrVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +struct BytesVisitor; + +impl<'a> Visitor<'a> for BytesVisitor { + type Value = &'a [u8]; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a borrowed byte array") + } + + fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> + where + E: Error, + { + Ok(v) + } + + fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> + where + E: Error, + { + Ok(v.as_bytes()) + } +} + +impl<'de: 'a, 'a> Deserialize<'de> for &'a [u8] { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_bytes(BytesVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +struct CStringVisitor; + +#[cfg(feature = "std")] +impl<'de> Visitor<'de> for CStringVisitor { + type Value = CString; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("byte array") + } + + fn visit_seq<A>(self, mut seq: A) -> Result<CString, A::Error> + where + A: SeqAccess<'de>, + { + let len = size_hint::cautious(seq.size_hint()); + let mut values = Vec::with_capacity(len); + + while let Some(value) = try!(seq.next_element()) { + values.push(value); + } + + CString::new(values).map_err(Error::custom) + } + + fn visit_bytes<E>(self, v: &[u8]) -> Result<CString, E> + where + E: Error, + { + CString::new(v).map_err(Error::custom) + } + + fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<CString, E> + where + E: Error, + { + CString::new(v).map_err(Error::custom) + } + + fn visit_str<E>(self, v: &str) -> Result<CString, E> + where + E: Error, + { + CString::new(v).map_err(Error::custom) + } + + fn visit_string<E>(self, v: String) -> Result<CString, E> + where + E: Error, + { + CString::new(v).map_err(Error::custom) + } +} + +#[cfg(feature = "std")] +impl<'de> Deserialize<'de> for CString { + fn deserialize<D>(deserializer: D) -> Result<CString, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_byte_buf(CStringVisitor) + } +} + +macro_rules! forwarded_impl { + ( + $(#[doc = $doc:tt])* + ( $($id: ident),* ), $ty: ty, $func: expr + ) => { + $(#[doc = $doc])* + impl<'de $(, $id : Deserialize<'de>,)*> Deserialize<'de> for $ty { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map($func) + } + } + } +} + +#[cfg(all(feature = "std", feature = "unstable"))] +forwarded_impl!((), Box<CStr>, CString::into_boxed_c_str); + +//////////////////////////////////////////////////////////////////////////////// + +struct OptionVisitor<T> { + marker: PhantomData<T>, +} + +impl<'de, T> Visitor<'de> for OptionVisitor<T> +where + T: Deserialize<'de>, +{ + type Value = Option<T>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("option") + } + + #[inline] + fn visit_unit<E>(self) -> Result<Option<T>, E> + where + E: Error, + { + Ok(None) + } + + #[inline] + fn visit_none<E>(self) -> Result<Option<T>, E> + where + E: Error, + { + Ok(None) + } + + #[inline] + fn visit_some<D>(self, deserializer: D) -> Result<Option<T>, D::Error> + where + D: Deserializer<'de>, + { + T::deserialize(deserializer).map(Some) + } +} + +impl<'de, T> Deserialize<'de> for Option<T> +where + T: Deserialize<'de>, +{ + fn deserialize<D>(deserializer: D) -> Result<Option<T>, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_option(OptionVisitor { + marker: PhantomData, + }) + } + + // The Some variant's repr is opaque, so we can't play cute tricks with its + // tag to have deserialize_in_place build the content in place unconditionally. + // + // FIXME: investigate whether branching on the old value being Some to + // deserialize_in_place the value is profitable (probably data-dependent?) +} + +//////////////////////////////////////////////////////////////////////////////// + +struct PhantomDataVisitor<T: ?Sized> { + marker: PhantomData<T>, +} + +impl<'de, T: ?Sized> Visitor<'de> for PhantomDataVisitor<T> { + type Value = PhantomData<T>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("unit") + } + + #[inline] + fn visit_unit<E>(self) -> Result<PhantomData<T>, E> + where + E: Error, + { + Ok(PhantomData) + } +} + +impl<'de, T: ?Sized> Deserialize<'de> for PhantomData<T> { + fn deserialize<D>(deserializer: D) -> Result<PhantomData<T>, D::Error> + where + D: Deserializer<'de>, + { + let visitor = PhantomDataVisitor { + marker: PhantomData, + }; + deserializer.deserialize_unit_struct("PhantomData", visitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +macro_rules! seq_impl { + ( + $ty:ident < T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >, + $access:ident, + $ctor:expr, + $clear:expr, + $with_capacity:expr, + $reserve:expr, + $insert:expr + ) => { + impl<'de, T $(, $typaram)*> Deserialize<'de> for $ty<T $(, $typaram)*> + where + T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*, + $($typaram: $bound1 $(+ $bound2)*,)* + { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + struct SeqVisitor<T $(, $typaram)*> { + marker: PhantomData<$ty<T $(, $typaram)*>>, + } + + impl<'de, T $(, $typaram)*> Visitor<'de> for SeqVisitor<T $(, $typaram)*> + where + T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*, + $($typaram: $bound1 $(+ $bound2)*,)* + { + type Value = $ty<T $(, $typaram)*>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } + + #[inline] + fn visit_seq<A>(self, mut $access: A) -> Result<Self::Value, A::Error> + where + A: SeqAccess<'de>, + { + let mut values = $with_capacity; + + while let Some(value) = try!($access.next_element()) { + $insert(&mut values, value); + } + + Ok(values) + } + } + + let visitor = SeqVisitor { marker: PhantomData }; + deserializer.deserialize_seq(visitor) + } + + fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + struct SeqInPlaceVisitor<'a, T: 'a $(, $typaram: 'a)*>(&'a mut $ty<T $(, $typaram)*>); + + impl<'a, 'de, T $(, $typaram)*> Visitor<'de> for SeqInPlaceVisitor<'a, T $(, $typaram)*> + where + T: Deserialize<'de> $(+ $tbound1 $(+ $tbound2)*)*, + $($typaram: $bound1 $(+ $bound2)*,)* + { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a sequence") + } + + #[inline] + fn visit_seq<A>(mut self, mut $access: A) -> Result<(), A::Error> + where + A: SeqAccess<'de>, + { + $clear(&mut self.0); + $reserve(&mut self.0, size_hint::cautious($access.size_hint())); + + // FIXME: try to overwrite old values here? (Vec, VecDeque, LinkedList) + while let Some(value) = try!($access.next_element()) { + $insert(&mut self.0, value); + } + + Ok(()) + } + } + + deserializer.deserialize_seq(SeqInPlaceVisitor(place)) + } + } + } +} + +// Dummy impl of reserve +#[cfg(any(feature = "std", feature = "alloc"))] +fn nop_reserve<T>(_seq: T, _n: usize) {} + +#[cfg(any(feature = "std", feature = "alloc"))] +seq_impl!( + BinaryHeap<T: Ord>, + seq, + BinaryHeap::new(), + BinaryHeap::clear, + BinaryHeap::with_capacity(size_hint::cautious(seq.size_hint())), + BinaryHeap::reserve, + BinaryHeap::push); + +#[cfg(any(feature = "std", feature = "alloc"))] +seq_impl!( + BTreeSet<T: Eq + Ord>, + seq, + BTreeSet::new(), + BTreeSet::clear, + BTreeSet::new(), + nop_reserve, + BTreeSet::insert); + +#[cfg(any(feature = "std", feature = "alloc"))] +seq_impl!( + LinkedList<T>, + seq, + LinkedList::new(), + LinkedList::clear, + LinkedList::new(), + nop_reserve, + LinkedList::push_back +); + +#[cfg(feature = "std")] +seq_impl!( + HashSet<T: Eq + Hash, S: BuildHasher + Default>, + seq, + HashSet::with_hasher(S::default()), + HashSet::clear, + HashSet::with_capacity_and_hasher(size_hint::cautious(seq.size_hint()), S::default()), + HashSet::reserve, + HashSet::insert); + +#[cfg(any(feature = "std", feature = "alloc"))] +seq_impl!( + Vec<T>, + seq, + Vec::new(), + Vec::clear, + Vec::with_capacity(size_hint::cautious(seq.size_hint())), + Vec::reserve, + Vec::push +); + +#[cfg(any(feature = "std", feature = "alloc"))] +seq_impl!( + VecDeque<T>, + seq, + VecDeque::new(), + VecDeque::clear, + VecDeque::with_capacity(size_hint::cautious(seq.size_hint())), + VecDeque::reserve, + VecDeque::push_back +); + +//////////////////////////////////////////////////////////////////////////////// + +struct ArrayVisitor<A> { + marker: PhantomData<A>, +} +struct ArrayInPlaceVisitor<'a, A: 'a>(&'a mut A); + +impl<A> ArrayVisitor<A> { + fn new() -> Self { + ArrayVisitor { + marker: PhantomData, + } + } +} + +impl<'de, T> Visitor<'de> for ArrayVisitor<[T; 0]> { + type Value = [T; 0]; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("an empty array") + } + + #[inline] + fn visit_seq<A>(self, _: A) -> Result<[T; 0], A::Error> + where + A: SeqAccess<'de>, + { + Ok([]) + } +} + +// Does not require T: Deserialize<'de>. +impl<'de, T> Deserialize<'de> for [T; 0] { + fn deserialize<D>(deserializer: D) -> Result<[T; 0], D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple(0, ArrayVisitor::<[T; 0]>::new()) + } +} + +macro_rules! array_impls { + ($($len:expr => ($($n:tt $name:ident)+))+) => { + $( + impl<'de, T> Visitor<'de> for ArrayVisitor<[T; $len]> + where + T: Deserialize<'de>, + { + type Value = [T; $len]; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("an array of length ", $len)) + } + + #[inline] + fn visit_seq<A>(self, mut seq: A) -> Result<[T; $len], A::Error> + where + A: SeqAccess<'de>, + { + $( + let $name = match try!(seq.next_element()) { + Some(val) => val, + None => return Err(Error::invalid_length($n, &self)), + }; + )+ + + Ok([$($name),+]) + } + } + + impl<'a, 'de, T> Visitor<'de> for ArrayInPlaceVisitor<'a, [T; $len]> + where + T: Deserialize<'de>, + { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("an array of length ", $len)) + } + + #[inline] + fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error> + where + A: SeqAccess<'de>, + { + let mut fail_idx = None; + for (idx, dest) in self.0[..].iter_mut().enumerate() { + if try!(seq.next_element_seed(InPlaceSeed(dest))).is_none() { + fail_idx = Some(idx); + break; + } + } + if let Some(idx) = fail_idx { + return Err(Error::invalid_length(idx, &self)); + } + Ok(()) + } + } + + impl<'de, T> Deserialize<'de> for [T; $len] + where + T: Deserialize<'de>, + { + fn deserialize<D>(deserializer: D) -> Result<[T; $len], D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple($len, ArrayVisitor::<[T; $len]>::new()) + } + + fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_tuple($len, ArrayInPlaceVisitor(place)) + } + } + )+ + } +} + +array_impls! { + 1 => (0 a) + 2 => (0 a 1 b) + 3 => (0 a 1 b 2 c) + 4 => (0 a 1 b 2 c 3 d) + 5 => (0 a 1 b 2 c 3 d 4 e) + 6 => (0 a 1 b 2 c 3 d 4 e 5 f) + 7 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g) + 8 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h) + 9 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i) + 10 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j) + 11 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k) + 12 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l) + 13 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m) + 14 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n) + 15 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o) + 16 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p) + 17 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q) + 18 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r) + 19 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s) + 20 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t) + 21 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u) + 22 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v) + 23 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w) + 24 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x) + 25 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y) + 26 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z) + 27 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa) + 28 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab) + 29 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac) + 30 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad) + 31 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad 30 ae) + 32 => (0 a 1 b 2 c 3 d 4 e 5 f 6 g 7 h 8 i 9 j 10 k 11 l 12 m 13 n 14 o 15 p 16 q 17 r 18 s 19 t 20 u 21 v 22 w 23 x 24 y 25 z 26 aa 27 ab 28 ac 29 ad 30 ae 31 af) +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! tuple_impls { + ($($len:tt => ($($n:tt $name:ident)+))+) => { + $( + impl<'de, $($name: Deserialize<'de>),+> Deserialize<'de> for ($($name,)+) { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<($($name,)+), D::Error> + where + D: Deserializer<'de>, + { + struct TupleVisitor<$($name,)+> { + marker: PhantomData<($($name,)+)>, + } + + impl<'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleVisitor<$($name,)+> { + type Value = ($($name,)+); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("a tuple of size ", $len)) + } + + #[inline] + #[allow(non_snake_case)] + fn visit_seq<A>(self, mut seq: A) -> Result<($($name,)+), A::Error> + where + A: SeqAccess<'de>, + { + $( + let $name = match try!(seq.next_element()) { + Some(value) => value, + None => return Err(Error::invalid_length($n, &self)), + }; + )+ + + Ok(($($name,)+)) + } + } + + deserializer.deserialize_tuple($len, TupleVisitor { marker: PhantomData }) + } + + #[inline] + fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + struct TupleInPlaceVisitor<'a, $($name: 'a,)+>(&'a mut ($($name,)+)); + + impl<'a, 'de, $($name: Deserialize<'de>),+> Visitor<'de> for TupleInPlaceVisitor<'a, $($name,)+> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("a tuple of size ", $len)) + } + + #[inline] + #[allow(non_snake_case)] + fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error> + where + A: SeqAccess<'de>, + { + $( + if try!(seq.next_element_seed(InPlaceSeed(&mut (self.0).$n))).is_none() { + return Err(Error::invalid_length($n, &self)); + } + )+ + + Ok(()) + } + } + + deserializer.deserialize_tuple($len, TupleInPlaceVisitor(place)) + } + } + )+ + } +} + +tuple_impls! { + 1 => (0 T0) + 2 => (0 T0 1 T1) + 3 => (0 T0 1 T1 2 T2) + 4 => (0 T0 1 T1 2 T2 3 T3) + 5 => (0 T0 1 T1 2 T2 3 T3 4 T4) + 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5) + 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6) + 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7) + 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8) + 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9) + 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10) + 12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11) + 13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12) + 14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13) + 15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14) + 16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15) +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +macro_rules! map_impl { + ( + $ty:ident < K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound1:ident $(+ $bound2:ident)*)* >, + $access:ident, + $ctor:expr, + $with_capacity:expr + ) => { + impl<'de, K, V $(, $typaram)*> Deserialize<'de> for $ty<K, V $(, $typaram)*> + where + K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*, + V: Deserialize<'de>, + $($typaram: $bound1 $(+ $bound2)*),* + { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + struct MapVisitor<K, V $(, $typaram)*> { + marker: PhantomData<$ty<K, V $(, $typaram)*>>, + } + + impl<'de, K, V $(, $typaram)*> Visitor<'de> for MapVisitor<K, V $(, $typaram)*> + where + K: Deserialize<'de> $(+ $kbound1 $(+ $kbound2)*)*, + V: Deserialize<'de>, + $($typaram: $bound1 $(+ $bound2)*),* + { + type Value = $ty<K, V $(, $typaram)*>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a map") + } + + #[inline] + fn visit_map<A>(self, mut $access: A) -> Result<Self::Value, A::Error> + where + A: MapAccess<'de>, + { + let mut values = $with_capacity; + + while let Some((key, value)) = try!($access.next_entry()) { + values.insert(key, value); + } + + Ok(values) + } + } + + let visitor = MapVisitor { marker: PhantomData }; + deserializer.deserialize_map(visitor) + } + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +map_impl!( + BTreeMap<K: Ord, V>, + map, + BTreeMap::new(), + BTreeMap::new()); + +#[cfg(feature = "std")] +map_impl!( + HashMap<K: Eq + Hash, V, S: BuildHasher + Default>, + map, + HashMap::with_hasher(S::default()), + HashMap::with_capacity_and_hasher(size_hint::cautious(map.size_hint()), S::default())); + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +macro_rules! parse_ip_impl { + ($ty:ty; $size:expr) => { + impl<'de> Deserialize<'de> for $ty { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + let s = try!(String::deserialize(deserializer)); + s.parse().map_err(Error::custom) + } else { + <[u8; $size]>::deserialize(deserializer).map(<$ty>::from) + } + } + } + }; +} + +#[cfg(feature = "std")] +macro_rules! variant_identifier { + ( + $name_kind: ident ( $($variant: ident; $bytes: expr; $index: expr),* ) + $expecting_message: expr, + $variants_name: ident + ) => { + enum $name_kind { + $( $variant ),* + } + + static $variants_name: &'static [&'static str] = &[ $( stringify!($variant) ),*]; + + impl<'de> Deserialize<'de> for $name_kind { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + struct KindVisitor; + + impl<'de> Visitor<'de> for KindVisitor { + type Value = $name_kind; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str($expecting_message) + } + + fn visit_u32<E>(self, value: u32) -> Result<Self::Value, E> + where + E: Error, + { + match value { + $( + $index => Ok($name_kind :: $variant), + )* + _ => Err(Error::invalid_value(Unexpected::Unsigned(value as u64), &self),), + } + } + + fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> + where + E: Error, + { + match value { + $( + stringify!($variant) => Ok($name_kind :: $variant), + )* + _ => Err(Error::unknown_variant(value, $variants_name)), + } + } + + fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E> + where + E: Error, + { + match value { + $( + $bytes => Ok($name_kind :: $variant), + )* + _ => { + match str::from_utf8(value) { + Ok(value) => Err(Error::unknown_variant(value, $variants_name)), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(value), &self)), + } + } + } + } + } + + deserializer.deserialize_identifier(KindVisitor) + } + } + } +} + +#[cfg(feature = "std")] +macro_rules! deserialize_enum { + ( + $name: ident $name_kind: ident ( $($variant: ident; $bytes: expr; $index: expr),* ) + $expecting_message: expr, + $deserializer: expr + ) => { + variant_identifier!{ + $name_kind ( $($variant; $bytes; $index),* ) + $expecting_message, + VARIANTS + } + + struct EnumVisitor; + impl<'de> Visitor<'de> for EnumVisitor { + type Value = $name; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(concat!("a ", stringify!($name))) + } + + + fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error> + where + A: EnumAccess<'de>, + { + match try!(data.variant()) { + $( + ($name_kind :: $variant, v) => v.newtype_variant().map($name :: $variant), + )* + } + } + } + $deserializer.deserialize_enum(stringify!($name), VARIANTS, EnumVisitor) + } +} + +#[cfg(feature = "std")] +impl<'de> Deserialize<'de> for net::IpAddr { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + let s = try!(String::deserialize(deserializer)); + s.parse().map_err(Error::custom) + } else { + use lib::net::IpAddr; + deserialize_enum!{ + IpAddr IpAddrKind (V4; b"V4"; 0, V6; b"V6"; 1) + "`V4` or `V6`", + deserializer + } + } + } +} + +#[cfg(feature = "std")] +parse_ip_impl!(net::Ipv4Addr; 4); + +#[cfg(feature = "std")] +parse_ip_impl!(net::Ipv6Addr; 16); + +#[cfg(feature = "std")] +macro_rules! parse_socket_impl { + ($ty:ty, $new:expr) => { + impl<'de> Deserialize<'de> for $ty { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + let s = try!(String::deserialize(deserializer)); + s.parse().map_err(Error::custom) + } else { + <(_, u16)>::deserialize(deserializer).map(|(ip, port)| $new(ip, port)) + } + } + } + }; +} + +#[cfg(feature = "std")] +impl<'de> Deserialize<'de> for net::SocketAddr { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + if deserializer.is_human_readable() { + let s = try!(String::deserialize(deserializer)); + s.parse().map_err(Error::custom) + } else { + use lib::net::SocketAddr; + deserialize_enum!{ + SocketAddr SocketAddrKind (V4; b"V4"; 0, V6; b"V6"; 1) + "`V4` or `V6`", + deserializer + } + } + } +} + +#[cfg(feature = "std")] +parse_socket_impl!(net::SocketAddrV4, net::SocketAddrV4::new); + +#[cfg(feature = "std")] +parse_socket_impl!(net::SocketAddrV6, |ip, port| net::SocketAddrV6::new( + ip, + port, + 0, + 0 +)); + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +struct PathVisitor; + +#[cfg(feature = "std")] +impl<'a> Visitor<'a> for PathVisitor { + type Value = &'a Path; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a borrowed path") + } + + fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> + where + E: Error, + { + Ok(v.as_ref()) + } + + fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> + where + E: Error, + { + str::from_utf8(v) + .map(AsRef::as_ref) + .map_err(|_| Error::invalid_value(Unexpected::Bytes(v), &self)) + } +} + +#[cfg(feature = "std")] +impl<'de: 'a, 'a> Deserialize<'de> for &'a Path { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_str(PathVisitor) + } +} + +#[cfg(feature = "std")] +struct PathBufVisitor; + +#[cfg(feature = "std")] +impl<'de> Visitor<'de> for PathBufVisitor { + type Value = PathBuf; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("path string") + } + + fn visit_str<E>(self, v: &str) -> Result<PathBuf, E> + where + E: Error, + { + Ok(From::from(v)) + } + + fn visit_string<E>(self, v: String) -> Result<PathBuf, E> + where + E: Error, + { + Ok(From::from(v)) + } +} + +#[cfg(feature = "std")] +impl<'de> Deserialize<'de> for PathBuf { + fn deserialize<D>(deserializer: D) -> Result<PathBuf, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_string(PathBufVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// If this were outside of the serde crate, it would just use: +// +// #[derive(Deserialize)] +// #[serde(variant_identifier)] +#[cfg(all(feature = "std", any(unix, windows)))] +variant_identifier!{ + OsStringKind (Unix; b"Unix"; 0, Windows; b"Windows"; 1) + "`Unix` or `Windows`", + OSSTR_VARIANTS +} + +#[cfg(all(feature = "std", any(unix, windows)))] +struct OsStringVisitor; + +#[cfg(all(feature = "std", any(unix, windows)))] +impl<'de> Visitor<'de> for OsStringVisitor { + type Value = OsString; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("os string") + } + + #[cfg(unix)] + fn visit_enum<A>(self, data: A) -> Result<OsString, A::Error> + where + A: EnumAccess<'de>, + { + use std::os::unix::ffi::OsStringExt; + + match try!(data.variant()) { + (OsStringKind::Unix, v) => v.newtype_variant().map(OsString::from_vec), + (OsStringKind::Windows, _) => Err(Error::custom( + "cannot deserialize Windows OS string on Unix", + )), + } + } + + #[cfg(windows)] + fn visit_enum<A>(self, data: A) -> Result<OsString, A::Error> + where + A: EnumAccess<'de>, + { + use std::os::windows::ffi::OsStringExt; + + match try!(data.variant()) { + (OsStringKind::Windows, v) => v.newtype_variant::<Vec<u16>>() + .map(|vec| OsString::from_wide(&vec)), + (OsStringKind::Unix, _) => Err(Error::custom( + "cannot deserialize Unix OS string on Windows", + )), + } + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +impl<'de> Deserialize<'de> for OsString { + fn deserialize<D>(deserializer: D) -> Result<OsString, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_enum("OsString", OSSTR_VARIANTS, OsStringVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +forwarded_impl!((T), Box<T>, Box::new); + +#[cfg(any(feature = "std", feature = "alloc"))] +forwarded_impl!((T), Box<[T]>, Vec::into_boxed_slice); + +#[cfg(any(feature = "std", feature = "alloc"))] +forwarded_impl!((), Box<str>, String::into_boxed_str); + +#[cfg(all(not(feature = "unstable"), feature = "rc", any(feature = "std", feature = "alloc")))] +forwarded_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Deserializing a data structure containing `Arc` will not attempt to + /// deduplicate `Arc` references to the same data. Every deserialized `Arc` + /// will end up with a strong count of 1. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + (T), Arc<T>, Arc::new +} + +#[cfg(all(not(feature = "unstable"), feature = "rc", any(feature = "std", feature = "alloc")))] +forwarded_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Deserializing a data structure containing `Rc` will not attempt to + /// deduplicate `Rc` references to the same data. Every deserialized `Rc` + /// will end up with a strong count of 1. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + (T), Rc<T>, Rc::new +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T> +where + T: ToOwned, + T::Owned: Deserialize<'de>, +{ + #[inline] + fn deserialize<D>(deserializer: D) -> Result<Cow<'a, T>, D::Error> + where + D: Deserializer<'de>, + { + T::Owned::deserialize(deserializer).map(Cow::Owned) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(all(feature = "unstable", feature = "rc", any(feature = "std", feature = "alloc")))] +macro_rules! box_forwarded_impl { + ( + $(#[doc = $doc:tt])* + $t:ident + ) => { + $(#[doc = $doc])* + impl<'de, T: ?Sized> Deserialize<'de> for $t<T> + where + Box<T>: Deserialize<'de>, + { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + Box::deserialize(deserializer).map(Into::into) + } + } + }; +} + +#[cfg(all(feature = "unstable", feature = "rc", any(feature = "std", feature = "alloc")))] +box_forwarded_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Deserializing a data structure containing `Rc` will not attempt to + /// deduplicate `Rc` references to the same data. Every deserialized `Rc` + /// will end up with a strong count of 1. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + Rc +} + +#[cfg(all(feature = "unstable", feature = "rc", any(feature = "std", feature = "alloc")))] +box_forwarded_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Deserializing a data structure containing `Arc` will not attempt to + /// deduplicate `Arc` references to the same data. Every deserialized `Arc` + /// will end up with a strong count of 1. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + Arc +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<'de, T> Deserialize<'de> for Cell<T> +where + T: Deserialize<'de> + Copy, +{ + fn deserialize<D>(deserializer: D) -> Result<Cell<T>, D::Error> + where + D: Deserializer<'de>, + { + T::deserialize(deserializer).map(Cell::new) + } +} + +forwarded_impl!((T), RefCell<T>, RefCell::new); + +#[cfg(feature = "std")] +forwarded_impl!((T), Mutex<T>, Mutex::new); + +#[cfg(feature = "std")] +forwarded_impl!((T), RwLock<T>, RwLock::new); + +//////////////////////////////////////////////////////////////////////////////// + +// This is a cleaned-up version of the impl generated by: +// +// #[derive(Deserialize)] +// #[serde(deny_unknown_fields)] +// struct Duration { +// secs: u64, +// nanos: u32, +// } +#[cfg(feature = "std")] +impl<'de> Deserialize<'de> for Duration { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(field_identifier, rename_all = "lowercase")] + enum Field { + Secs, + Nanos, + }; + + impl<'de> Deserialize<'de> for Field { + fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`secs` or `nanos`") + } + + fn visit_str<E>(self, value: &str) -> Result<Field, E> + where + E: Error, + { + match value { + "secs" => Ok(Field::Secs), + "nanos" => Ok(Field::Nanos), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> + where + E: Error, + { + match value { + b"secs" => Ok(Field::Secs), + b"nanos" => Ok(Field::Nanos), + _ => { + let value = String::from_utf8_lossy(value); + Err(Error::unknown_field(&value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + struct DurationVisitor; + + impl<'de> Visitor<'de> for DurationVisitor { + type Value = Duration; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("struct Duration") + } + + fn visit_seq<A>(self, mut seq: A) -> Result<Duration, A::Error> + where + A: SeqAccess<'de>, + { + let secs: u64 = match try!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + let nanos: u32 = match try!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(1, &self)); + } + }; + Ok(Duration::new(secs, nanos)) + } + + fn visit_map<A>(self, mut map: A) -> Result<Duration, A::Error> + where + A: MapAccess<'de>, + { + let mut secs: Option<u64> = None; + let mut nanos: Option<u32> = None; + while let Some(key) = try!(map.next_key()) { + match key { + Field::Secs => { + if secs.is_some() { + return Err(<A::Error as Error>::duplicate_field("secs")); + } + secs = Some(try!(map.next_value())); + } + Field::Nanos => { + if nanos.is_some() { + return Err(<A::Error as Error>::duplicate_field("nanos")); + } + nanos = Some(try!(map.next_value())); + } + } + } + let secs = match secs { + Some(secs) => secs, + None => return Err(<A::Error as Error>::missing_field("secs")), + }; + let nanos = match nanos { + Some(nanos) => nanos, + None => return Err(<A::Error as Error>::missing_field("nanos")), + }; + Ok(Duration::new(secs, nanos)) + } + } + + const FIELDS: &'static [&'static str] = &["secs", "nanos"]; + deserializer.deserialize_struct("Duration", FIELDS, DurationVisitor) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl<'de> Deserialize<'de> for SystemTime { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + // Reuse duration + enum Field { + Secs, + Nanos, + }; + + impl<'de> Deserialize<'de> for Field { + fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`secs_since_epoch` or `nanos_since_epoch`") + } + + fn visit_str<E>(self, value: &str) -> Result<Field, E> + where + E: Error, + { + match value { + "secs_since_epoch" => Ok(Field::Secs), + "nanos_since_epoch" => Ok(Field::Nanos), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> + where + E: Error, + { + match value { + b"secs_since_epoch" => Ok(Field::Secs), + b"nanos_since_epoch" => Ok(Field::Nanos), + _ => { + let value = String::from_utf8_lossy(value); + Err(Error::unknown_field(&value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + struct DurationVisitor; + + impl<'de> Visitor<'de> for DurationVisitor { + type Value = Duration; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("struct SystemTime") + } + + fn visit_seq<A>(self, mut seq: A) -> Result<Duration, A::Error> + where + A: SeqAccess<'de>, + { + let secs: u64 = match try!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + let nanos: u32 = match try!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(1, &self)); + } + }; + Ok(Duration::new(secs, nanos)) + } + + fn visit_map<A>(self, mut map: A) -> Result<Duration, A::Error> + where + A: MapAccess<'de>, + { + let mut secs: Option<u64> = None; + let mut nanos: Option<u32> = None; + while let Some(key) = try!(map.next_key()) { + match key { + Field::Secs => { + if secs.is_some() { + return Err(<A::Error as Error>::duplicate_field( + "secs_since_epoch", + )); + } + secs = Some(try!(map.next_value())); + } + Field::Nanos => { + if nanos.is_some() { + return Err(<A::Error as Error>::duplicate_field( + "nanos_since_epoch", + )); + } + nanos = Some(try!(map.next_value())); + } + } + } + let secs = match secs { + Some(secs) => secs, + None => return Err(<A::Error as Error>::missing_field("secs_since_epoch")), + }; + let nanos = match nanos { + Some(nanos) => nanos, + None => return Err(<A::Error as Error>::missing_field("nanos_since_epoch")), + }; + Ok(Duration::new(secs, nanos)) + } + } + + const FIELDS: &'static [&'static str] = &["secs_since_epoch", "nanos_since_epoch"]; + let duration = try!(deserializer.deserialize_struct("SystemTime", FIELDS, DurationVisitor)); + Ok(UNIX_EPOCH + duration) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Similar to: +// +// #[derive(Deserialize)] +// #[serde(deny_unknown_fields)] +// struct Range { +// start: u64, +// end: u32, +// } +#[cfg(feature = "std")] +impl<'de, Idx> Deserialize<'de> for ops::Range<Idx> +where + Idx: Deserialize<'de>, +{ + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(field_identifier, rename_all = "lowercase")] + enum Field { + Start, + End, + }; + + impl<'de> Deserialize<'de> for Field { + fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`start` or `end`") + } + + fn visit_str<E>(self, value: &str) -> Result<Field, E> + where + E: Error, + { + match value { + "start" => Ok(Field::Start), + "end" => Ok(Field::End), + _ => Err(Error::unknown_field(value, FIELDS)), + } + } + + fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> + where + E: Error, + { + match value { + b"start" => Ok(Field::Start), + b"end" => Ok(Field::End), + _ => { + let value = String::from_utf8_lossy(value); + Err(Error::unknown_field(&value, FIELDS)) + } + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + struct RangeVisitor<Idx> { + phantom: PhantomData<Idx>, + } + + impl<'de, Idx> Visitor<'de> for RangeVisitor<Idx> + where + Idx: Deserialize<'de>, + { + type Value = ops::Range<Idx>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("struct Range") + } + + fn visit_seq<A>(self, mut seq: A) -> Result<ops::Range<Idx>, A::Error> + where + A: SeqAccess<'de>, + { + let start: Idx = match try!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(0, &self)); + } + }; + let end: Idx = match try!(seq.next_element()) { + Some(value) => value, + None => { + return Err(Error::invalid_length(1, &self)); + } + }; + Ok(start..end) + } + + fn visit_map<A>(self, mut map: A) -> Result<ops::Range<Idx>, A::Error> + where + A: MapAccess<'de>, + { + let mut start: Option<Idx> = None; + let mut end: Option<Idx> = None; + while let Some(key) = try!(map.next_key()) { + match key { + Field::Start => { + if start.is_some() { + return Err(<A::Error as Error>::duplicate_field("start")); + } + start = Some(try!(map.next_value())); + } + Field::End => { + if end.is_some() { + return Err(<A::Error as Error>::duplicate_field("end")); + } + end = Some(try!(map.next_value())); + } + } + } + let start = match start { + Some(start) => start, + None => return Err(<A::Error as Error>::missing_field("start")), + }; + let end = match end { + Some(end) => end, + None => return Err(<A::Error as Error>::missing_field("end")), + }; + Ok(start..end) + } + } + + const FIELDS: &'static [&'static str] = &["start", "end"]; + deserializer.deserialize_struct( + "Range", + FIELDS, + RangeVisitor { + phantom: PhantomData, + }, + ) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "unstable")] +#[allow(deprecated)] +impl<'de, T> Deserialize<'de> for NonZero<T> +where + T: Deserialize<'de> + Zeroable, +{ + fn deserialize<D>(deserializer: D) -> Result<NonZero<T>, D::Error> + where + D: Deserializer<'de>, + { + let value = try!(Deserialize::deserialize(deserializer)); + match NonZero::new(value) { + Some(nonzero) => Ok(nonzero), + None => Err(Error::custom("expected a non-zero value")), + } + } +} + +macro_rules! nonzero_integers { + ( $( $T: ty, )+ ) => { + $( + #[cfg(feature = "unstable")] + impl<'de> Deserialize<'de> for $T { + fn deserialize<D>(deserializer: D) -> Result<$T, D::Error> + where + D: Deserializer<'de>, + { + let value = try!(Deserialize::deserialize(deserializer)); + match <$T>::new(value) { + Some(nonzero) => Ok(nonzero), + None => Err(Error::custom("expected a non-zero value")), + } + } + } + )+ + }; +} + +nonzero_integers! { + // Not including signed NonZeroI* since they might be removed + NonZeroU8, + NonZeroU16, + NonZeroU32, + NonZeroU64, + // FIXME: https://github.com/serde-rs/serde/issues/1136 NonZeroU128, + NonZeroUsize, +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<'de, T, E> Deserialize<'de> for Result<T, E> +where + T: Deserialize<'de>, + E: Deserialize<'de>, +{ + fn deserialize<D>(deserializer: D) -> Result<Result<T, E>, D::Error> + where + D: Deserializer<'de>, + { + // If this were outside of the serde crate, it would just use: + // + // #[derive(Deserialize)] + // #[serde(variant_identifier)] + enum Field { + Ok, + Err, + } + + impl<'de> Deserialize<'de> for Field { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> + where + D: Deserializer<'de>, + { + struct FieldVisitor; + + impl<'de> Visitor<'de> for FieldVisitor { + type Value = Field; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("`Ok` or `Err`") + } + + fn visit_u32<E>(self, value: u32) -> Result<Field, E> + where + E: Error, + { + match value { + 0 => Ok(Field::Ok), + 1 => Ok(Field::Err), + _ => Err(Error::invalid_value( + Unexpected::Unsigned(value as u64), + &self, + )), + } + } + + fn visit_str<E>(self, value: &str) -> Result<Field, E> + where + E: Error, + { + match value { + "Ok" => Ok(Field::Ok), + "Err" => Ok(Field::Err), + _ => Err(Error::unknown_variant(value, VARIANTS)), + } + } + + fn visit_bytes<E>(self, value: &[u8]) -> Result<Field, E> + where + E: Error, + { + match value { + b"Ok" => Ok(Field::Ok), + b"Err" => Ok(Field::Err), + _ => match str::from_utf8(value) { + Ok(value) => Err(Error::unknown_variant(value, VARIANTS)), + Err(_) => { + Err(Error::invalid_value(Unexpected::Bytes(value), &self)) + } + }, + } + } + } + + deserializer.deserialize_identifier(FieldVisitor) + } + } + + struct ResultVisitor<T, E>(PhantomData<Result<T, E>>); + + impl<'de, T, E> Visitor<'de> for ResultVisitor<T, E> + where + T: Deserialize<'de>, + E: Deserialize<'de>, + { + type Value = Result<T, E>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("enum Result") + } + + fn visit_enum<A>(self, data: A) -> Result<Result<T, E>, A::Error> + where + A: EnumAccess<'de>, + { + match try!(data.variant()) { + (Field::Ok, v) => v.newtype_variant().map(Ok), + (Field::Err, v) => v.newtype_variant().map(Err), + } + } + } + + const VARIANTS: &'static [&'static str] = &["Ok", "Err"]; + + deserializer.deserialize_enum("Result", VARIANTS, ResultVisitor(PhantomData)) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl<'de, T> Deserialize<'de> for Wrapping<T> +where + T: Deserialize<'de>, +{ + fn deserialize<D>(deserializer: D) -> Result<Wrapping<T>, D::Error> + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map(Wrapping) + } +} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/de/mod.rs cargo-0.26.0/vendor/serde-1.0.37/src/de/mod.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/de/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/de/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2045 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Generic data structure deserialization framework. +//! +//! The two most important traits in this module are [`Deserialize`] and +//! [`Deserializer`]. +//! +//! - **A type that implements `Deserialize` is a data structure** that can be +//! deserialized from any data format supported by Serde, and conversely +//! - **A type that implements `Deserializer` is a data format** that can +//! deserialize any data structure supported by Serde. +//! +//! # The Deserialize trait +//! +//! Serde provides [`Deserialize`] implementations for many Rust primitive and +//! standard library types. The complete list is below. All of these can be +//! deserialized using Serde out of the box. +//! +//! Additionally, Serde provides a procedural macro called [`serde_derive`] to +//! automatically generate [`Deserialize`] implementations for structs and enums +//! in your program. See the [codegen section of the manual] for how to use +//! this. +//! +//! In rare cases it may be necessary to implement [`Deserialize`] manually for +//! some type in your program. See the [Implementing `Deserialize`] section of +//! the manual for more about this. +//! +//! Third-party crates may provide [`Deserialize`] implementations for types +//! that they expose. For example the [`linked-hash-map`] crate provides a +//! [`LinkedHashMap<K, V>`] type that is deserializable by Serde because the +//! crate provides an implementation of [`Deserialize`] for it. +//! +//! # The Deserializer trait +//! +//! [`Deserializer`] implementations are provided by third-party crates, for +//! example [`serde_json`], [`serde_yaml`] and [`bincode`]. +//! +//! A partial list of well-maintained formats is given on the [Serde +//! website][data formats]. +//! +//! # Implementations of Deserialize provided by Serde +//! +//! This is a slightly different set of types than what is supported for +//! serialization. Some types can be serialized by Serde but not deserialized. +//! One example is `OsStr`. +//! +//! - **Primitive types**: +//! - bool +//! - i8, i16, i32, i64, isize +//! - u8, u16, u32, u64, usize +//! - f32, f64 +//! - char +//! - **Compound types**: +//! - [T; 0] through [T; 32] +//! - tuples up to size 16 +//! - **Common standard library types**: +//! - String +//! - Option\<T\> +//! - Result\<T, E\> +//! - PhantomData\<T\> +//! - **Wrapper types**: +//! - Box\<T\> +//! - Box\<[T]\> +//! - Box\<str\> +//! - Rc\<T\> +//! - Arc\<T\> +//! - Cow\<'a, T\> +//! - Cell\<T\> +//! - RefCell\<T\> +//! - Mutex\<T\> +//! - RwLock\<T\> +//! - **Collection types**: +//! - BTreeMap\<K, V\> +//! - BTreeSet\<T\> +//! - BinaryHeap\<T\> +//! - HashMap\<K, V, H\> +//! - HashSet\<T, H\> +//! - LinkedList\<T\> +//! - VecDeque\<T\> +//! - Vec\<T\> +//! - EnumSet\<T\> (unstable) +//! - **Zero-copy types**: +//! - &str +//! - &[u8] +//! - **FFI types**: +//! - CString +//! - Box\<CStr\> +//! - OsString +//! - **Miscellaneous standard library types**: +//! - Duration +//! - SystemTime +//! - Path +//! - PathBuf +//! - Range\<T\> +//! - NonZero\<T\> (unstable, deprecated) +//! - num::NonZero* (unstable) +//! - **Net types**: +//! - IpAddr +//! - Ipv4Addr +//! - Ipv6Addr +//! - SocketAddr +//! - SocketAddrV4 +//! - SocketAddrV6 +//! +//! [Implementing `Deserialize`]: https://serde.rs/impl-deserialize.html +//! [`Deserialize`]: ../trait.Deserialize.html +//! [`Deserializer`]: ../trait.Deserializer.html +//! [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html +//! [`bincode`]: https://github.com/TyOverby/bincode +//! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map +//! [`serde_derive`]: https://crates.io/crates/serde_derive +//! [`serde_json`]: https://github.com/serde-rs/json +//! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml +//! [codegen section of the manual]: https://serde.rs/codegen.html +//! [data formats]: https://serde.rs/#data-formats + +use lib::*; + +//////////////////////////////////////////////////////////////////////////////// + +pub mod value; + +mod from_primitive; +mod ignored_any; +mod impls; +mod utf8; + +pub use self::ignored_any::IgnoredAny; + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! declare_error_trait { + (Error: Sized $(+ $($supertrait:ident)::+)*) => { + /// The `Error` trait allows `Deserialize` implementations to create descriptive + /// error messages belonging to the `Deserializer` against which they are + /// currently running. + /// + /// Every `Deserializer` declares an `Error` type that encompasses both + /// general-purpose deserialization errors as well as errors specific to the + /// particular deserialization format. For example the `Error` type of + /// `serde_json` can represent errors like an invalid JSON escape sequence or an + /// unterminated string literal, in addition to the error cases that are part of + /// this trait. + /// + /// Most deserializers should only need to provide the `Error::custom` method + /// and inherit the default behavior for the other methods. + pub trait Error: Sized $(+ $($supertrait)::+)* { + /// Raised when there is general error when deserializing a type. + /// + /// The message should not be capitalized and should not end with a period. + /// + /// ```rust + /// # use std::str::FromStr; + /// # + /// # struct IpAddr; + /// # + /// # impl FromStr for IpAddr { + /// # type Err = String; + /// # + /// # fn from_str(_: &str) -> Result<Self, String> { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::de::{self, Deserialize, Deserializer}; + /// + /// impl<'de> Deserialize<'de> for IpAddr { + /// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + /// where D: Deserializer<'de> + /// { + /// let s = try!(String::deserialize(deserializer)); + /// s.parse().map_err(de::Error::custom) + /// } + /// } + /// ``` + fn custom<T>(msg: T) -> Self + where + T: Display; + + /// Raised when a `Deserialize` receives a type different from what it was + /// expecting. + /// + /// The `unexp` argument provides information about what type was received. + /// This is the type that was present in the input file or other source data + /// of the Deserializer. + /// + /// The `exp` argument provides information about what type was being + /// expected. This is the type that is written in the program. + /// + /// For example if we try to deserialize a String out of a JSON file + /// containing an integer, the unexpected type is the integer and the + /// expected type is the string. + fn invalid_type(unexp: Unexpected, exp: &Expected) -> Self { + Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp)) + } + + /// Raised when a `Deserialize` receives a value of the right type but that + /// is wrong for some other reason. + /// + /// The `unexp` argument provides information about what value was received. + /// This is the value that was present in the input file or other source + /// data of the Deserializer. + /// + /// The `exp` argument provides information about what value was being + /// expected. This is the type that is written in the program. + /// + /// For example if we try to deserialize a String out of some binary data + /// that is not valid UTF-8, the unexpected value is the bytes and the + /// expected value is a string. + fn invalid_value(unexp: Unexpected, exp: &Expected) -> Self { + Error::custom(format_args!("invalid value: {}, expected {}", unexp, exp)) + } + + /// Raised when deserializing a sequence or map and the input data contains + /// too many or too few elements. + /// + /// The `len` argument is the number of elements encountered. The sequence + /// or map may have expected more arguments or fewer arguments. + /// + /// The `exp` argument provides information about what data was being + /// expected. For example `exp` might say that a tuple of size 6 was + /// expected. + fn invalid_length(len: usize, exp: &Expected) -> Self { + Error::custom(format_args!("invalid length {}, expected {}", len, exp)) + } + + /// Raised when a `Deserialize` enum type received a variant with an + /// unrecognized name. + fn unknown_variant(variant: &str, expected: &'static [&'static str]) -> Self { + if expected.is_empty() { + Error::custom(format_args!("unknown variant `{}`, there are no variants", + variant)) + } else { + Error::custom(format_args!("unknown variant `{}`, expected {}", + variant, + OneOf { names: expected })) + } + } + + /// Raised when a `Deserialize` struct type received a field with an + /// unrecognized name. + fn unknown_field(field: &str, expected: &'static [&'static str]) -> Self { + if expected.is_empty() { + Error::custom(format_args!("unknown field `{}`, there are no fields", + field)) + } else { + Error::custom(format_args!("unknown field `{}`, expected {}", + field, + OneOf { names: expected })) + } + } + + /// Raised when a `Deserialize` struct type expected to receive a required + /// field with a particular name but that field was not present in the + /// input. + fn missing_field(field: &'static str) -> Self { + Error::custom(format_args!("missing field `{}`", field)) + } + + /// Raised when a `Deserialize` struct type received more than one of the + /// same field. + fn duplicate_field(field: &'static str) -> Self { + Error::custom(format_args!("duplicate field `{}`", field)) + } + } + } +} + +#[cfg(feature = "std")] +declare_error_trait!(Error: Sized + error::Error); + +#[cfg(not(feature = "std"))] +declare_error_trait!(Error: Sized + Debug + Display); + +/// `Unexpected` represents an unexpected invocation of any one of the `Visitor` +/// trait methods. +/// +/// This is used as an argument to the `invalid_type`, `invalid_value`, and +/// `invalid_length` methods of the `Error` trait to build error messages. +/// +/// ```rust +/// # use std::fmt; +/// # +/// # use serde::de::{self, Unexpected, Visitor}; +/// # +/// # struct Example; +/// # +/// # impl<'de> Visitor<'de> for Example { +/// # type Value = (); +/// # +/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// # write!(formatter, "definitely not a boolean") +/// # } +/// # +/// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> +/// where E: de::Error +/// { +/// Err(de::Error::invalid_type(Unexpected::Bool(v), &self)) +/// } +/// # } +/// ``` +#[derive(Copy, Clone, PartialEq, Debug)] +pub enum Unexpected<'a> { + /// The input contained a boolean value that was not expected. + Bool(bool), + + /// The input contained an unsigned integer `u8`, `u16`, `u32` or `u64` that + /// was not expected. + Unsigned(u64), + + /// The input contained a signed integer `i8`, `i16`, `i32` or `i64` that + /// was not expected. + Signed(i64), + + /// The input contained a floating point `f32` or `f64` that was not + /// expected. + Float(f64), + + /// The input contained a `char` that was not expected. + Char(char), + + /// The input contained a `&str` or `String` that was not expected. + Str(&'a str), + + /// The input contained a `&[u8]` or `Vec<u8>` that was not expected. + Bytes(&'a [u8]), + + /// The input contained a unit `()` that was not expected. + Unit, + + /// The input contained an `Option<T>` that was not expected. + Option, + + /// The input contained a newtype struct that was not expected. + NewtypeStruct, + + /// The input contained a sequence that was not expected. + Seq, + + /// The input contained a map that was not expected. + Map, + + /// The input contained an enum that was not expected. + Enum, + + /// The input contained a unit variant that was not expected. + UnitVariant, + + /// The input contained a newtype variant that was not expected. + NewtypeVariant, + + /// The input contained a tuple variant that was not expected. + TupleVariant, + + /// The input contained a struct variant that was not expected. + StructVariant, + + /// A message stating what uncategorized thing the input contained that was + /// not expected. + /// + /// The message should be a noun or noun phrase, not capitalized and without + /// a period. An example message is "unoriginal superhero". + Other(&'a str), +} + +impl<'a> fmt::Display for Unexpected<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + use self::Unexpected::*; + match *self { + Bool(b) => write!(formatter, "boolean `{}`", b), + Unsigned(i) => write!(formatter, "integer `{}`", i), + Signed(i) => write!(formatter, "integer `{}`", i), + Float(f) => write!(formatter, "floating point `{}`", f), + Char(c) => write!(formatter, "character `{}`", c), + Str(s) => write!(formatter, "string {:?}", s), + Bytes(_) => write!(formatter, "byte array"), + Unit => write!(formatter, "unit value"), + Option => write!(formatter, "Option value"), + NewtypeStruct => write!(formatter, "newtype struct"), + Seq => write!(formatter, "sequence"), + Map => write!(formatter, "map"), + Enum => write!(formatter, "enum"), + UnitVariant => write!(formatter, "unit variant"), + NewtypeVariant => write!(formatter, "newtype variant"), + TupleVariant => write!(formatter, "tuple variant"), + StructVariant => write!(formatter, "struct variant"), + Other(other) => formatter.write_str(other), + } + } +} + +/// `Expected` represents an explanation of what data a `Visitor` was expecting +/// to receive. +/// +/// This is used as an argument to the `invalid_type`, `invalid_value`, and +/// `invalid_length` methods of the `Error` trait to build error messages. The +/// message should be a noun or noun phrase that completes the sentence "This +/// Visitor expects to receive ...", for example the message could be "an +/// integer between 0 and 64". The message should not be capitalized and should +/// not end with a period. +/// +/// Within the context of a `Visitor` implementation, the `Visitor` itself +/// (`&self`) is an implementation of this trait. +/// +/// ```rust +/// # use std::fmt; +/// # +/// # use serde::de::{self, Unexpected, Visitor}; +/// # +/// # struct Example; +/// # +/// # impl<'de> Visitor<'de> for Example { +/// # type Value = (); +/// # +/// # fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// # write!(formatter, "definitely not a boolean") +/// # } +/// # +/// fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> +/// where E: de::Error +/// { +/// Err(de::Error::invalid_type(Unexpected::Bool(v), &self)) +/// } +/// # } +/// ``` +/// +/// Outside of a `Visitor`, `&"..."` can be used. +/// +/// ```rust +/// # use serde::de::{self, Unexpected}; +/// # +/// # fn example<E>() -> Result<(), E> +/// # where E: de::Error +/// # { +/// # let v = true; +/// return Err(de::Error::invalid_type(Unexpected::Bool(v), &"a negative integer")); +/// # } +/// ``` +pub trait Expected { + /// Format an explanation of what data was being expected. Same signature as + /// the `Display` and `Debug` traits. + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result; +} + +impl<'de, T> Expected for T +where + T: Visitor<'de>, +{ + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.expecting(formatter) + } +} + +impl<'a> Expected for &'a str { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self) + } +} + +impl<'a> Display for Expected + 'a { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Expected::fmt(self, formatter) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A **data structure** that can be deserialized from any data format supported +/// by Serde. +/// +/// Serde provides `Deserialize` implementations for many Rust primitive and +/// standard library types. The complete list is [here][de]. All of these can +/// be deserialized using Serde out of the box. +/// +/// Additionally, Serde provides a procedural macro called `serde_derive` to +/// automatically generate `Deserialize` implementations for structs and enums +/// in your program. See the [codegen section of the manual][codegen] for how to +/// use this. +/// +/// In rare cases it may be necessary to implement `Deserialize` manually for +/// some type in your program. See the [Implementing +/// `Deserialize`][impl-deserialize] section of the manual for more about this. +/// +/// Third-party crates may provide `Deserialize` implementations for types that +/// they expose. For example the `linked-hash-map` crate provides a +/// `LinkedHashMap<K, V>` type that is deserializable by Serde because the crate +/// provides an implementation of `Deserialize` for it. +/// +/// [de]: https://docs.serde.rs/serde/de/index.html +/// [codegen]: https://serde.rs/codegen.html +/// [impl-deserialize]: https://serde.rs/impl-deserialize.html +pub trait Deserialize<'de>: Sized { + /// Deserialize this value from the given Serde deserializer. + /// + /// See the [Implementing `Deserialize`][impl-deserialize] section of the + /// manual for more information about how to implement this method. + /// + /// [impl-deserialize]: https://serde.rs/impl-deserialize.html + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>; + + /// Deserializes a value into `self` from the given Deserializer. + /// + /// The purpose of this method is to allow the deserializer to reuse + /// resources and avoid copies. As such, if this method returns an error, + /// `self` will be in an indeterminate state where some parts of the struct + /// have been overwritten. Although whatever state that is will be + /// memory-safe. + /// + /// This is generally useful when repeatedly deserializing values that + /// are processed one at a time, where the value of `self` doesn't matter + /// when the next deserialization occurs. + /// + /// If you manually implement this, your recursive deserializations should + /// use `deserialize_in_place`. + /// + /// This method is stable and an official public API, but hidden from the + /// documentation because it is almost never what newbies are looking for. + /// Showing it in rustdoc would cause it to be featured more prominently + /// than it deserves. + #[doc(hidden)] + fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error> + where + D: Deserializer<'de>, + { + // Default implementation just delegates to `deserialize` impl. + *place = Deserialize::deserialize(deserializer)?; + Ok(()) + } +} + +/// A data structure that can be deserialized without borrowing any data from +/// the deserializer. +/// +/// This is primarily useful for trait bounds on functions. For example a +/// `from_str` function may be able to deserialize a data structure that borrows +/// from the input string, but a `from_reader` function may only deserialize +/// owned data. +/// +/// ```rust +/// # use serde::de::{Deserialize, DeserializeOwned}; +/// # use std::io::{Read, Result}; +/// # +/// # trait Ignore { +/// fn from_str<'a, T>(s: &'a str) -> Result<T> +/// where T: Deserialize<'a>; +/// +/// fn from_reader<R, T>(rdr: R) -> Result<T> +/// where R: Read, +/// T: DeserializeOwned; +/// # } +/// ``` +pub trait DeserializeOwned: for<'de> Deserialize<'de> {} +impl<T> DeserializeOwned for T +where + T: for<'de> Deserialize<'de>, +{ +} + +/// `DeserializeSeed` is the stateful form of the `Deserialize` trait. If you +/// ever find yourself looking for a way to pass data into a `Deserialize` impl, +/// this trait is the way to do it. +/// +/// As one example of stateful deserialization consider deserializing a JSON +/// array into an existing buffer. Using the `Deserialize` trait we could +/// deserialize a JSON array into a `Vec<T>` but it would be a freshly allocated +/// `Vec<T>`; there is no way for `Deserialize` to reuse a previously allocated +/// buffer. Using `DeserializeSeed` instead makes this possible as in the +/// example code below. +/// +/// The canonical API for stateless deserialization looks like this: +/// +/// ```rust +/// # use serde::Deserialize; +/// # +/// # enum Error {} +/// # +/// fn func<'de, T: Deserialize<'de>>() -> Result<T, Error> +/// # { +/// # unimplemented!() +/// # } +/// ``` +/// +/// Adjusting an API like this to support stateful deserialization is a matter +/// of accepting a seed as input: +/// +/// ```rust +/// # use serde::de::DeserializeSeed; +/// # +/// # enum Error {} +/// # +/// fn func_seed<'de, T: DeserializeSeed<'de>>(seed: T) -> Result<T::Value, Error> +/// # { +/// # let _ = seed; +/// # unimplemented!() +/// # } +/// ``` +/// +/// In practice the majority of deserialization is stateless. An API expecting a +/// seed can be appeased by passing `std::marker::PhantomData` as a seed in the +/// case of stateless deserialization. +/// +/// # Example +/// +/// Suppose we have JSON that looks like `[[1, 2], [3, 4, 5], [6]]` and we need +/// to deserialize it into a flat representation like `vec![1, 2, 3, 4, 5, 6]`. +/// Allocating a brand new `Vec<T>` for each subarray would be slow. Instead we +/// would like to allocate a single `Vec<T>` and then deserialize each subarray +/// into it. This requires stateful deserialization using the `DeserializeSeed` +/// trait. +/// +/// ```rust +/// use std::fmt; +/// use std::marker::PhantomData; +/// +/// use serde::de::{Deserialize, DeserializeSeed, Deserializer, Visitor, SeqAccess}; +/// +/// // A DeserializeSeed implementation that uses stateful deserialization to +/// // append array elements onto the end of an existing vector. The preexisting +/// // state ("seed") in this case is the Vec<T>. The `deserialize` method of +/// // `ExtendVec` will be traversing the inner arrays of the JSON input and +/// // appending each integer into the existing Vec. +/// struct ExtendVec<'a, T: 'a>(&'a mut Vec<T>); +/// +/// impl<'de, 'a, T> DeserializeSeed<'de> for ExtendVec<'a, T> +/// where T: Deserialize<'de> +/// { +/// // The return type of the `deserialize` method. This implementation +/// // appends onto an existing vector but does not create any new data +/// // structure, so the return type is (). +/// type Value = (); +/// +/// fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> +/// where D: Deserializer<'de> +/// { +/// // Visitor implementation that will walk an inner array of the JSON +/// // input. +/// struct ExtendVecVisitor<'a, T: 'a>(&'a mut Vec<T>); +/// +/// impl<'de, 'a, T> Visitor<'de> for ExtendVecVisitor<'a, T> +/// where T: Deserialize<'de> +/// { +/// type Value = (); +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!(formatter, "an array of integers") +/// } +/// +/// fn visit_seq<A>(self, mut seq: A) -> Result<(), A::Error> +/// where A: SeqAccess<'de> +/// { +/// // Visit each element in the inner array and push it onto +/// // the existing vector. +/// while let Some(elem) = seq.next_element()? { +/// self.0.push(elem); +/// } +/// Ok(()) +/// } +/// } +/// +/// deserializer.deserialize_seq(ExtendVecVisitor(self.0)) +/// } +/// } +/// +/// // Visitor implementation that will walk the outer array of the JSON input. +/// struct FlattenedVecVisitor<T>(PhantomData<T>); +/// +/// impl<'de, T> Visitor<'de> for FlattenedVecVisitor<T> +/// where T: Deserialize<'de> +/// { +/// // This Visitor constructs a single Vec<T> to hold the flattened +/// // contents of the inner arrays. +/// type Value = Vec<T>; +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!(formatter, "an array of arrays") +/// } +/// +/// fn visit_seq<A>(self, mut seq: A) -> Result<Vec<T>, A::Error> +/// where A: SeqAccess<'de> +/// { +/// // Create a single Vec to hold the flattened contents. +/// let mut vec = Vec::new(); +/// +/// // Each iteration through this loop is one inner array. +/// while let Some(()) = seq.next_element_seed(ExtendVec(&mut vec))? { +/// // Nothing to do; inner array has been appended into `vec`. +/// } +/// +/// // Return the finished vec. +/// Ok(vec) +/// } +/// } +/// +/// # fn example<'de, D>(deserializer: D) -> Result<(), D::Error> +/// # where D: Deserializer<'de> +/// # { +/// let visitor = FlattenedVecVisitor(PhantomData); +/// let flattened: Vec<u64> = deserializer.deserialize_seq(visitor)?; +/// # Ok(()) +/// # } +/// ``` +pub trait DeserializeSeed<'de>: Sized { + /// The type produced by using this seed. + type Value; + + /// Equivalent to the more common `Deserialize::deserialize` method, except + /// with some initial piece of data (the seed) passed in. + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>; +} + +impl<'de, T> DeserializeSeed<'de> for PhantomData<T> +where + T: Deserialize<'de>, +{ + type Value = T; + + #[inline] + fn deserialize<D>(self, deserializer: D) -> Result<T, D::Error> + where + D: Deserializer<'de>, + { + T::deserialize(deserializer) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A **data format** that can deserialize any data structure supported by +/// Serde. +/// +/// The role of this trait is to define the deserialization half of the Serde +/// data model, which is a way to categorize every Rust data type into one of 27 +/// possible types. Each method of the `Serializer` trait corresponds to one of +/// the types of the data model. +/// +/// Implementations of `Deserialize` map themselves into this data model by +/// passing to the `Deserializer` a `Visitor` implementation that can receive +/// these various types. +/// +/// The types that make up the Serde data model are: +/// +/// - **12 primitive types** +/// - bool +/// - i8, i16, i32, i64 +/// - u8, u16, u32, u64 +/// - f32, f64 +/// - char +/// - **string** +/// - UTF-8 bytes with a length and no null terminator. +/// - When serializing, all strings are handled equally. When deserializing, +/// there are three flavors of strings: transient, owned, and borrowed. +/// - **byte array** - [u8] +/// - Similar to strings, during deserialization byte arrays can be transient, +/// owned, or borrowed. +/// - **option** +/// - Either none or some value. +/// - **unit** +/// - The type of `()` in Rust. It represents an anonymous value containing no +/// data. +/// - **unit_struct** +/// - For example `struct Unit` or `PhantomData<T>`. It represents a named value +/// containing no data. +/// - **unit_variant** +/// - For example the `E::A` and `E::B` in `enum E { A, B }`. +/// - **newtype_struct** +/// - For example `struct Millimeters(u8)`. +/// - **newtype_variant** +/// - For example the `E::N` in `enum E { N(u8) }`. +/// - **seq** +/// - A variably sized heterogeneous sequence of values, for example `Vec<T>` or +/// `HashSet<T>`. When serializing, the length may or may not be known before +/// iterating through all the data. When deserializing, the length is determined +/// by looking at the serialized data. +/// - **tuple** +/// - A statically sized heterogeneous sequence of values for which the length +/// will be known at deserialization time without looking at the serialized +/// data, for example `(u8,)` or `(String, u64, Vec<T>)` or `[u64; 10]`. +/// - **tuple_struct** +/// - A named tuple, for example `struct Rgb(u8, u8, u8)`. +/// - **tuple_variant** +/// - For example the `E::T` in `enum E { T(u8, u8) }`. +/// - **map** +/// - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`. +/// - **struct** +/// - A heterogeneous key-value pairing in which the keys are strings and will be +/// known at deserialization time without looking at the serialized data, for +/// example `struct S { r: u8, g: u8, b: u8 }`. +/// - **struct_variant** +/// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. +/// +/// The `Deserializer` trait supports two entry point styles which enables +/// different kinds of deserialization. +/// +/// 1. The `deserialize` method. Self-describing data formats like JSON are able +/// to look at the serialized data and tell what it represents. For example +/// the JSON deserializer may see an opening curly brace (`{`) and know that +/// it is seeing a map. If the data format supports +/// `Deserializer::deserialize_any`, it will drive the Visitor using whatever +/// type it sees in the input. JSON uses this approach when deserializing +/// `serde_json::Value` which is an enum that can represent any JSON +/// document. Without knowing what is in a JSON document, we can deserialize +/// it to `serde_json::Value` by going through `Deserializer::deserialize_any`. +/// +/// 2. The various `deserialize_*` methods. Non-self-describing formats like +/// Bincode need to be told what is in the input in order to deserialize it. +/// The `deserialize_*` methods are hints to the deserializer for how to +/// interpret the next piece of input. Non-self-describing formats are not +/// able to deserialize something like `serde_json::Value` which relies on +/// `Deserializer::deserialize_any`. +/// +/// When implementing `Deserialize`, you should avoid relying on +/// `Deserializer::deserialize_any` unless you need to be told by the Deserializer +/// what type is in the input. Know that relying on `Deserializer::deserialize_any` +/// means your data type will be able to deserialize from self-describing +/// formats only, ruling out Bincode and many others. +pub trait Deserializer<'de>: Sized { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + + /// Require the `Deserializer` to figure out how to drive the visitor based + /// on what data type is in the input. + /// + /// When implementing `Deserialize`, you should avoid relying on + /// `Deserializer::deserialize_any` unless you need to be told by the + /// Deserializer what type is in the input. Know that relying on + /// `Deserializer::deserialize_any` means your data type will be able to + /// deserialize from self-describing formats only, ruling out Bincode and + /// many others. + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `bool` value. + fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i8` value. + fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i16` value. + fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i32` value. + fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an `i64` value. + fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `u8` value. + fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `u16` value. + fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `u32` value. + fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `u64` value. + fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `f32` value. + fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `f64` value. + fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a `char` value. + fn deserialize_char<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a string value and does + /// not benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would benefit from taking ownership of `String` data, + /// indiciate this to the `Deserializer` by using `deserialize_string` + /// instead. + fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a string value and would + /// benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would not benefit from taking ownership of `String` + /// data, indicate that to the `Deserializer` by using `deserialize_str` + /// instead. + fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a byte array and does not + /// benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would benefit from taking ownership of `Vec<u8>` data, + /// indicate this to the `Deserializer` by using `deserialize_byte_buf` + /// instead. + fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a byte array and would + /// benefit from taking ownership of buffered data owned by the + /// `Deserializer`. + /// + /// If the `Visitor` would not benefit from taking ownership of `Vec<u8>` + /// data, indicate that to the `Deserializer` by using `deserialize_bytes` + /// instead. + fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an optional value. + /// + /// This allows deserializers that encode an optional value as a nullable + /// value to convert the null value into `None` and a regular value into + /// `Some(value)`. + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a unit value. + fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a unit struct with a + /// particular name. + fn deserialize_unit_struct<V>( + self, + name: &'static str, + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a newtype struct with a + /// particular name. + fn deserialize_newtype_struct<V>( + self, + name: &'static str, + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a sequence of values. + fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a sequence of values and + /// knows how many values there are without looking at the serialized data. + fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a tuple struct with a + /// particular name and number of fields. + fn deserialize_tuple_struct<V>( + self, + name: &'static str, + len: usize, + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a map of key-value pairs. + fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting a struct with a particular + /// name and fields. + fn deserialize_struct<V>( + self, + name: &'static str, + fields: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting an enum value with a + /// particular name and possible variants. + fn deserialize_enum<V>( + self, + name: &'static str, + variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type is expecting the name of a struct + /// field or the discriminant of an enum variant. + fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Hint that the `Deserialize` type needs to deserialize a value whose type + /// doesn't matter because it is ignored. + /// + /// Deserializers for non-self-describing formats may not support this mode. + fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Determine whether `Deserialize` implementations should expect to + /// deserialize their human-readable form. + /// + /// Some types have a human-readable form that may be somewhat expensive to + /// construct, as well as a binary form that is compact and efficient. + /// Generally text-based formats like JSON and YAML will prefer to use the + /// human-readable one and binary formats like Bincode will prefer the + /// compact one. + /// + /// ``` + /// # use std::ops::Add; + /// # use std::str::FromStr; + /// # + /// # struct Timestamp; + /// # + /// # impl Timestamp { + /// # const EPOCH: Timestamp = Timestamp; + /// # } + /// # + /// # impl FromStr for Timestamp { + /// # type Err = String; + /// # fn from_str(_: &str) -> Result<Self, Self::Err> { + /// # unimplemented!() + /// # } + /// # } + /// # + /// # struct Duration; + /// # + /// # impl Duration { + /// # fn seconds(_: u64) -> Self { unimplemented!() } + /// # } + /// # + /// # impl Add<Duration> for Timestamp { + /// # type Output = Timestamp; + /// # fn add(self, _: Duration) -> Self::Output { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::de::{self, Deserialize, Deserializer}; + /// + /// impl<'de> Deserialize<'de> for Timestamp { + /// fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + /// where D: Deserializer<'de> + /// { + /// if deserializer.is_human_readable() { + /// // Deserialize from a human-readable string like "2015-05-15T17:01:00Z". + /// let s = String::deserialize(deserializer)?; + /// Timestamp::from_str(&s).map_err(de::Error::custom) + /// } else { + /// // Deserialize from a compact binary representation, seconds since + /// // the Unix epoch. + /// let n = u64::deserialize(deserializer)?; + /// Ok(Timestamp::EPOCH + Duration::seconds(n)) + /// } + /// } + /// } + /// ``` + /// + /// The default implementation of this method returns `true`. Data formats + /// may override this to `false` to request a compact form for types that + /// support one. Note that modifying this method to change a format from + /// human-readable to compact or vice versa should be regarded as a breaking + /// change, as a value serialized in human-readable mode is not required to + /// deserialize from the same data in compact mode. + #[inline] + fn is_human_readable(&self) -> bool { + true + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// This trait represents a visitor that walks through a deserializer. +/// +/// ```rust +/// # use std::fmt; +/// # +/// # use serde::de::{self, Unexpected, Visitor}; +/// # +/// /// A visitor that deserializes a long string - a string containing at least +/// /// some minimum number of bytes. +/// struct LongString { +/// min: usize, +/// } +/// +/// impl<'de> Visitor<'de> for LongString { +/// type Value = String; +/// +/// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { +/// write!(formatter, "a string containing at least {} bytes", self.min) +/// } +/// +/// fn visit_str<E>(self, s: &str) -> Result<Self::Value, E> +/// where E: de::Error +/// { +/// if s.len() >= self.min { +/// Ok(s.to_owned()) +/// } else { +/// Err(de::Error::invalid_value(Unexpected::Str(s), &self)) +/// } +/// } +/// } +/// ``` +pub trait Visitor<'de>: Sized { + /// The value produced by this visitor. + type Value; + + /// Format a message stating what data this Visitor expects to receive. + /// + /// This is used in error messages. The message should complete the sentence + /// "This Visitor expects to receive ...", for example the message could be + /// "an integer between 0 and 64". The message should not be capitalized and + /// should not end with a period. + /// + /// ```rust + /// # use std::fmt; + /// # + /// # struct S { + /// # max: usize, + /// # } + /// # + /// # impl<'de> serde::de::Visitor<'de> for S { + /// # type Value = (); + /// # + /// fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + /// write!(formatter, "an integer between 0 and {}", self.max) + /// } + /// # } + /// ``` + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result; + + /// The input contains a boolean. + /// + /// The default implementation fails with a type error. + fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E> + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Bool(v), &self)) + } + + /// The input contains an `i8`. + /// + /// The default implementation forwards to [`visit_i64`]. + /// + /// [`visit_i64`]: #method.visit_i64 + fn visit_i8<E>(self, v: i8) -> Result<Self::Value, E> + where + E: Error, + { + self.visit_i64(v as i64) + } + + /// The input contains an `i16`. + /// + /// The default implementation forwards to [`visit_i64`]. + /// + /// [`visit_i64`]: #method.visit_i64 + fn visit_i16<E>(self, v: i16) -> Result<Self::Value, E> + where + E: Error, + { + self.visit_i64(v as i64) + } + + /// The input contains an `i32`. + /// + /// The default implementation forwards to [`visit_i64`]. + /// + /// [`visit_i64`]: #method.visit_i64 + fn visit_i32<E>(self, v: i32) -> Result<Self::Value, E> + where + E: Error, + { + self.visit_i64(v as i64) + } + + /// The input contains an `i64`. + /// + /// The default implementation fails with a type error. + fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Signed(v), &self)) + } + + /// The input contains a `u8`. + /// + /// The default implementation forwards to [`visit_u64`]. + /// + /// [`visit_u64`]: #method.visit_u64 + fn visit_u8<E>(self, v: u8) -> Result<Self::Value, E> + where + E: Error, + { + self.visit_u64(v as u64) + } + + /// The input contains a `u16`. + /// + /// The default implementation forwards to [`visit_u64`]. + /// + /// [`visit_u64`]: #method.visit_u64 + fn visit_u16<E>(self, v: u16) -> Result<Self::Value, E> + where + E: Error, + { + self.visit_u64(v as u64) + } + + /// The input contains a `u32`. + /// + /// The default implementation forwards to [`visit_u64`]. + /// + /// [`visit_u64`]: #method.visit_u64 + fn visit_u32<E>(self, v: u32) -> Result<Self::Value, E> + where + E: Error, + { + self.visit_u64(v as u64) + } + + /// The input contains a `u64`. + /// + /// The default implementation fails with a type error. + fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Unsigned(v), &self)) + } + + /// The input contains an `f32`. + /// + /// The default implementation forwards to [`visit_f64`]. + /// + /// [`visit_f64`]: #method.visit_f64 + fn visit_f32<E>(self, v: f32) -> Result<Self::Value, E> + where + E: Error, + { + self.visit_f64(v as f64) + } + + /// The input contains an `f64`. + /// + /// The default implementation fails with a type error. + fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E> + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Float(v), &self)) + } + + /// The input contains a `char`. + /// + /// The default implementation forwards to [`visit_str`] as a one-character + /// string. + /// + /// [`visit_str`]: #method.visit_str + #[inline] + fn visit_char<E>(self, v: char) -> Result<Self::Value, E> + where + E: Error, + { + self.visit_str(utf8::encode(v).as_str()) + } + + /// The input contains a string. The lifetime of the string is ephemeral and + /// it may be destroyed after this method returns. + /// + /// This method allows the `Deserializer` to avoid a copy by retaining + /// ownership of any buffered data. `Deserialize` implementations that do + /// not benefit from taking ownership of `String` data should indicate that + /// to the deserializer by using `Deserializer::deserialize_str` rather than + /// `Deserializer::deserialize_string`. + /// + /// It is never correct to implement `visit_string` without implementing + /// `visit_str`. Implement neither, both, or just `visit_str`. + fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Str(v), &self)) + } + + /// The input contains a string that lives at least as long as the + /// `Deserializer`. + /// + /// This enables zero-copy deserialization of strings in some formats. For + /// example JSON input containing the JSON string `"borrowed"` can be + /// deserialized with zero copying into a `&'a str` as long as the input + /// data outlives `'a`. + /// + /// The default implementation forwards to `visit_str`. + #[inline] + fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E> + where + E: Error, + { + self.visit_str(v) + } + + /// The input contains a string and ownership of the string is being given + /// to the `Visitor`. + /// + /// This method allows the `Visitor` to avoid a copy by taking ownership of + /// a string created by the `Deserializer`. `Deserialize` implementations + /// that benefit from taking ownership of `String` data should indicate that + /// to the deserializer by using `Deserializer::deserialize_string` rather + /// than `Deserializer::deserialize_str`, although not every deserializer + /// will honor such a request. + /// + /// It is never correct to implement `visit_string` without implementing + /// `visit_str`. Implement neither, both, or just `visit_str`. + /// + /// The default implementation forwards to `visit_str` and then drops the + /// `String`. + #[inline] + #[cfg(any(feature = "std", feature = "alloc"))] + fn visit_string<E>(self, v: String) -> Result<Self::Value, E> + where + E: Error, + { + self.visit_str(&v) + } + + /// The input contains a byte array. The lifetime of the byte array is + /// ephemeral and it may be destroyed after this method returns. + /// + /// This method allows the `Deserializer` to avoid a copy by retaining + /// ownership of any buffered data. `Deserialize` implementations that do + /// not benefit from taking ownership of `Vec<u8>` data should indicate that + /// to the deserializer by using `Deserializer::deserialize_bytes` rather + /// than `Deserializer::deserialize_byte_buf`. + /// + /// It is never correct to implement `visit_byte_buf` without implementing + /// `visit_bytes`. Implement neither, both, or just `visit_bytes`. + fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> + where + E: Error, + { + let _ = v; + Err(Error::invalid_type(Unexpected::Bytes(v), &self)) + } + + /// The input contains a byte array that lives at least as long as the + /// `Deserializer`. + /// + /// This enables zero-copy deserialization of bytes in some formats. For + /// example Bincode data containing bytes can be deserialized with zero + /// copying into a `&'a [u8]` as long as the input data outlives `'a`. + /// + /// The default implementation forwards to `visit_bytes`. + #[inline] + fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E> + where + E: Error, + { + self.visit_bytes(v) + } + + /// The input contains a byte array and ownership of the byte array is being + /// given to the `Visitor`. + /// + /// This method allows the `Visitor` to avoid a copy by taking ownership of + /// a byte buffer created by the `Deserializer`. `Deserialize` + /// implementations that benefit from taking ownership of `Vec<u8>` data + /// should indicate that to the deserializer by using + /// `Deserializer::deserialize_byte_buf` rather than + /// `Deserializer::deserialize_bytes`, although not every deserializer will + /// honor such a request. + /// + /// It is never correct to implement `visit_byte_buf` without implementing + /// `visit_bytes`. Implement neither, both, or just `visit_bytes`. + /// + /// The default implementation forwards to `visit_bytes` and then drops the + /// `Vec<u8>`. + #[cfg(any(feature = "std", feature = "alloc"))] + fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> + where + E: Error, + { + self.visit_bytes(&v) + } + + /// The input contains an optional that is absent. + /// + /// The default implementation fails with a type error. + fn visit_none<E>(self) -> Result<Self::Value, E> + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Option, &self)) + } + + /// The input contains an optional that is present. + /// + /// The default implementation fails with a type error. + fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + let _ = deserializer; + Err(Error::invalid_type(Unexpected::Option, &self)) + } + + /// The input contains a unit `()`. + /// + /// The default implementation fails with a type error. + fn visit_unit<E>(self) -> Result<Self::Value, E> + where + E: Error, + { + Err(Error::invalid_type(Unexpected::Unit, &self)) + } + + /// The input contains a newtype struct. + /// + /// The content of the newtype struct may be read from the given + /// `Deserializer`. + /// + /// The default implementation fails with a type error. + fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + let _ = deserializer; + Err(Error::invalid_type(Unexpected::NewtypeStruct, &self)) + } + + /// The input contains a sequence of elements. + /// + /// The default implementation fails with a type error. + fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error> + where + A: SeqAccess<'de>, + { + let _ = seq; + Err(Error::invalid_type(Unexpected::Seq, &self)) + } + + /// The input contains a key-value map. + /// + /// The default implementation fails with a type error. + fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error> + where + A: MapAccess<'de>, + { + let _ = map; + Err(Error::invalid_type(Unexpected::Map, &self)) + } + + /// The input contains an enum. + /// + /// The default implementation fails with a type error. + fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error> + where + A: EnumAccess<'de>, + { + let _ = data; + Err(Error::invalid_type(Unexpected::Enum, &self)) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Provides a `Visitor` access to each element of a sequence in the input. +/// +/// This is a trait that a `Deserializer` passes to a `Visitor` implementation, +/// which deserializes each item in a sequence. +pub trait SeqAccess<'de> { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + + /// This returns `Ok(Some(value))` for the next value in the sequence, or + /// `Ok(None)` if there are no more remaining items. + /// + /// `Deserialize` implementations should typically use + /// `SeqAccess::next_element` instead. + fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where + T: DeserializeSeed<'de>; + + /// This returns `Ok(Some(value))` for the next value in the sequence, or + /// `Ok(None)` if there are no more remaining items. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `SeqAccess` implementations should not override the default behavior. + #[inline] + fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error> + where + T: Deserialize<'de>, + { + self.next_element_seed(PhantomData) + } + + /// Returns the number of elements remaining in the sequence, if known. + #[inline] + fn size_hint(&self) -> Option<usize> { + None + } +} + +impl<'de, 'a, A> SeqAccess<'de> for &'a mut A +where + A: SeqAccess<'de>, +{ + type Error = A::Error; + + #[inline] + fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where + T: DeserializeSeed<'de>, + { + (**self).next_element_seed(seed) + } + + #[inline] + fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error> + where + T: Deserialize<'de>, + { + (**self).next_element() + } + + #[inline] + fn size_hint(&self) -> Option<usize> { + (**self).size_hint() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Provides a `Visitor` access to each entry of a map in the input. +/// +/// This is a trait that a `Deserializer` passes to a `Visitor` implementation. +pub trait MapAccess<'de> { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + + /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)` + /// if there are no more remaining entries. + /// + /// `Deserialize` implementations should typically use + /// `MapAccess::next_key` or `MapAccess::next_entry` instead. + fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> + where + K: DeserializeSeed<'de>; + + /// This returns a `Ok(value)` for the next value in the map. + /// + /// `Deserialize` implementations should typically use + /// `MapAccess::next_value` instead. + /// + /// # Panics + /// + /// Calling `next_value_seed` before `next_key_seed` is incorrect and is + /// allowed to panic or return bogus results. + fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> + where + V: DeserializeSeed<'de>; + + /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in + /// the map, or `Ok(None)` if there are no more remaining items. + /// + /// `MapAccess` implementations should override the default behavior if a + /// more efficient implementation is possible. + /// + /// `Deserialize` implementations should typically use + /// `MapAccess::next_entry` instead. + #[inline] + fn next_entry_seed<K, V>( + &mut self, + kseed: K, + vseed: V, + ) -> Result<Option<(K::Value, V::Value)>, Self::Error> + where + K: DeserializeSeed<'de>, + V: DeserializeSeed<'de>, + { + match try!(self.next_key_seed(kseed)) { + Some(key) => { + let value = try!(self.next_value_seed(vseed)); + Ok(Some((key, value))) + } + None => Ok(None), + } + } + + /// This returns `Ok(Some(key))` for the next key in the map, or `Ok(None)` + /// if there are no more remaining entries. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `MapAccess` implementations should not override the default behavior. + #[inline] + fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error> + where + K: Deserialize<'de>, + { + self.next_key_seed(PhantomData) + } + + /// This returns a `Ok(value)` for the next value in the map. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `MapAccess` implementations should not override the default behavior. + /// + /// # Panics + /// + /// Calling `next_value` before `next_key` is incorrect and is allowed to + /// panic or return bogus results. + #[inline] + fn next_value<V>(&mut self) -> Result<V, Self::Error> + where + V: Deserialize<'de>, + { + self.next_value_seed(PhantomData) + } + + /// This returns `Ok(Some((key, value)))` for the next (key-value) pair in + /// the map, or `Ok(None)` if there are no more remaining items. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `MapAccess` implementations should not override the default behavior. + #[inline] + fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error> + where + K: Deserialize<'de>, + V: Deserialize<'de>, + { + self.next_entry_seed(PhantomData, PhantomData) + } + + /// Returns the number of entries remaining in the map, if known. + #[inline] + fn size_hint(&self) -> Option<usize> { + None + } +} + +impl<'de, 'a, A> MapAccess<'de> for &'a mut A +where + A: MapAccess<'de>, +{ + type Error = A::Error; + + #[inline] + fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> + where + K: DeserializeSeed<'de>, + { + (**self).next_key_seed(seed) + } + + #[inline] + fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> + where + V: DeserializeSeed<'de>, + { + (**self).next_value_seed(seed) + } + + #[inline] + fn next_entry_seed<K, V>( + &mut self, + kseed: K, + vseed: V, + ) -> Result<Option<(K::Value, V::Value)>, Self::Error> + where + K: DeserializeSeed<'de>, + V: DeserializeSeed<'de>, + { + (**self).next_entry_seed(kseed, vseed) + } + + #[inline] + fn next_entry<K, V>(&mut self) -> Result<Option<(K, V)>, Self::Error> + where + K: Deserialize<'de>, + V: Deserialize<'de>, + { + (**self).next_entry() + } + + #[inline] + fn next_key<K>(&mut self) -> Result<Option<K>, Self::Error> + where + K: Deserialize<'de>, + { + (**self).next_key() + } + + #[inline] + fn next_value<V>(&mut self) -> Result<V, Self::Error> + where + V: Deserialize<'de>, + { + (**self).next_value() + } + + #[inline] + fn size_hint(&self) -> Option<usize> { + (**self).size_hint() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Provides a `Visitor` access to the data of an enum in the input. +/// +/// `EnumAccess` is created by the `Deserializer` and passed to the +/// `Visitor` in order to identify which variant of an enum to deserialize. +pub trait EnumAccess<'de>: Sized { + /// The error type that can be returned if some error occurs during + /// deserialization. + type Error: Error; + /// The `Visitor` that will be used to deserialize the content of the enum + /// variant. + type Variant: VariantAccess<'de, Error = Self::Error>; + + /// `variant` is called to identify which variant to deserialize. + /// + /// `Deserialize` implementations should typically use `EnumAccess::variant` + /// instead. + fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + where + V: DeserializeSeed<'de>; + + /// `variant` is called to identify which variant to deserialize. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `EnumAccess` implementations should not override the default behavior. + #[inline] + fn variant<V>(self) -> Result<(V, Self::Variant), Self::Error> + where + V: Deserialize<'de>, + { + self.variant_seed(PhantomData) + } +} + +/// `VariantAccess` is a visitor that is created by the `Deserializer` and +/// passed to the `Deserialize` to deserialize the content of a particular enum +/// variant. +pub trait VariantAccess<'de>: Sized { + /// The error type that can be returned if some error occurs during + /// deserialization. Must match the error type of our `EnumAccess`. + type Error: Error; + + /// Called when deserializing a variant with no values. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```rust + /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; + /// # + /// # struct X; + /// # + /// # impl<'de> VariantAccess<'de> for X { + /// # type Error = value::Error; + /// # + /// fn unit_variant(self) -> Result<(), Self::Error> { + /// // What the data actually contained; suppose it is a tuple variant. + /// let unexp = Unexpected::TupleVariant; + /// Err(de::Error::invalid_type(unexp, &"unit variant")) + /// } + /// # + /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error> + /// # where T: DeserializeSeed<'de> + /// # { unimplemented!() } + /// # + /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error> + /// # where V: Visitor<'de> + /// # { unimplemented!() } + /// # + /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error> + /// # where V: Visitor<'de> + /// # { unimplemented!() } + /// # } + /// ``` + fn unit_variant(self) -> Result<(), Self::Error>; + + /// Called when deserializing a variant with a single value. + /// + /// `Deserialize` implementations should typically use + /// `VariantAccess::newtype_variant` instead. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```rust + /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; + /// # + /// # struct X; + /// # + /// # impl<'de> VariantAccess<'de> for X { + /// # type Error = value::Error; + /// # + /// # fn unit_variant(self) -> Result<(), Self::Error> { + /// # unimplemented!() + /// # } + /// # + /// fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error> + /// where T: DeserializeSeed<'de> + /// { + /// // What the data actually contained; suppose it is a unit variant. + /// let unexp = Unexpected::UnitVariant; + /// Err(de::Error::invalid_type(unexp, &"newtype variant")) + /// } + /// # + /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error> + /// # where V: Visitor<'de> + /// # { unimplemented!() } + /// # + /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error> + /// # where V: Visitor<'de> + /// # { unimplemented!() } + /// # } + /// ``` + fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Self::Error> + where + T: DeserializeSeed<'de>; + + /// Called when deserializing a variant with a single value. + /// + /// This method exists as a convenience for `Deserialize` implementations. + /// `VariantAccess` implementations should not override the default + /// behavior. + #[inline] + fn newtype_variant<T>(self) -> Result<T, Self::Error> + where + T: Deserialize<'de>, + { + self.newtype_variant_seed(PhantomData) + } + + /// Called when deserializing a tuple-like variant. + /// + /// The `len` is the number of fields expected in the tuple variant. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```rust + /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; + /// # + /// # struct X; + /// # + /// # impl<'de> VariantAccess<'de> for X { + /// # type Error = value::Error; + /// # + /// # fn unit_variant(self) -> Result<(), Self::Error> { + /// # unimplemented!() + /// # } + /// # + /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error> + /// # where T: DeserializeSeed<'de> + /// # { unimplemented!() } + /// # + /// fn tuple_variant<V>(self, + /// _len: usize, + /// _visitor: V) -> Result<V::Value, Self::Error> + /// where V: Visitor<'de> + /// { + /// // What the data actually contained; suppose it is a unit variant. + /// let unexp = Unexpected::UnitVariant; + /// Err(de::Error::invalid_type(unexp, &"tuple variant")) + /// } + /// # + /// # fn struct_variant<V>(self, _: &[&str], _: V) -> Result<V::Value, Self::Error> + /// # where V: Visitor<'de> + /// # { unimplemented!() } + /// # } + /// ``` + fn tuple_variant<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; + + /// Called when deserializing a struct-like variant. + /// + /// The `fields` are the names of the fields of the struct variant. + /// + /// If the data contains a different type of variant, the following + /// `invalid_type` error should be constructed: + /// + /// ```rust + /// # use serde::de::{self, value, DeserializeSeed, Visitor, VariantAccess, Unexpected}; + /// # + /// # struct X; + /// # + /// # impl<'de> VariantAccess<'de> for X { + /// # type Error = value::Error; + /// # + /// # fn unit_variant(self) -> Result<(), Self::Error> { + /// # unimplemented!() + /// # } + /// # + /// # fn newtype_variant_seed<T>(self, _: T) -> Result<T::Value, Self::Error> + /// # where T: DeserializeSeed<'de> + /// # { unimplemented!() } + /// # + /// # fn tuple_variant<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error> + /// # where V: Visitor<'de> + /// # { unimplemented!() } + /// # + /// fn struct_variant<V>(self, + /// _fields: &'static [&'static str], + /// _visitor: V) -> Result<V::Value, Self::Error> + /// where V: Visitor<'de> + /// { + /// // What the data actually contained; suppose it is a unit variant. + /// let unexp = Unexpected::UnitVariant; + /// Err(de::Error::invalid_type(unexp, &"struct variant")) + /// } + /// # } + /// ``` + fn struct_variant<V>( + self, + fields: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>; +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Converts an existing value into a `Deserializer` from which other values can +/// be deserialized. +/// +/// ```rust +/// #[macro_use] +/// extern crate serde_derive; +/// +/// extern crate serde; +/// +/// use std::str::FromStr; +/// use serde::de::{value, Deserialize, IntoDeserializer}; +/// +/// #[derive(Deserialize)] +/// enum Setting { +/// On, +/// Off, +/// } +/// +/// impl FromStr for Setting { +/// type Err = value::Error; +/// +/// fn from_str(s: &str) -> Result<Self, Self::Err> { +/// Self::deserialize(s.into_deserializer()) +/// } +/// } +/// # +/// # fn main() {} +/// ``` +pub trait IntoDeserializer<'de, E: Error = value::Error> { + /// The type of the deserializer being converted into. + type Deserializer: Deserializer<'de, Error = E>; + + /// Convert this value into a deserializer. + fn into_deserializer(self) -> Self::Deserializer; +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Used in error messages. +/// +/// - expected `a` +/// - expected `a` or `b` +/// - expected one of `a`, `b`, `c` +/// +/// The slice of names must not be empty. +struct OneOf { + names: &'static [&'static str], +} + +impl Display for OneOf { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self.names.len() { + 0 => panic!(), // special case elsewhere + 1 => write!(formatter, "`{}`", self.names[0]), + 2 => write!(formatter, "`{}` or `{}`", self.names[0], self.names[1]), + _ => { + try!(write!(formatter, "one of ")); + for (i, alt) in self.names.iter().enumerate() { + if i > 0 { + try!(write!(formatter, ", ")); + } + try!(write!(formatter, "`{}`", alt)); + } + Ok(()) + } + } + } +} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/de/utf8.rs cargo-0.26.0/vendor/serde-1.0.37/src/de/utf8.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/de/utf8.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/de/utf8.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,54 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use lib::*; + +const TAG_CONT: u8 = 0b1000_0000; +const TAG_TWO_B: u8 = 0b1100_0000; +const TAG_THREE_B: u8 = 0b1110_0000; +const TAG_FOUR_B: u8 = 0b1111_0000; +const MAX_ONE_B: u32 = 0x80; +const MAX_TWO_B: u32 = 0x800; +const MAX_THREE_B: u32 = 0x10000; + +#[inline] +pub fn encode(c: char) -> Encode { + let code = c as u32; + let mut buf = [0; 4]; + let pos = if code < MAX_ONE_B { + buf[3] = code as u8; + 3 + } else if code < MAX_TWO_B { + buf[2] = (code >> 6 & 0x1F) as u8 | TAG_TWO_B; + buf[3] = (code & 0x3F) as u8 | TAG_CONT; + 2 + } else if code < MAX_THREE_B { + buf[1] = (code >> 12 & 0x0F) as u8 | TAG_THREE_B; + buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + buf[3] = (code & 0x3F) as u8 | TAG_CONT; + 1 + } else { + buf[0] = (code >> 18 & 0x07) as u8 | TAG_FOUR_B; + buf[1] = (code >> 12 & 0x3F) as u8 | TAG_CONT; + buf[2] = (code >> 6 & 0x3F) as u8 | TAG_CONT; + buf[3] = (code & 0x3F) as u8 | TAG_CONT; + 0 + }; + Encode { buf: buf, pos: pos } +} + +pub struct Encode { + buf: [u8; 4], + pos: usize, +} + +impl Encode { + pub fn as_str(&self) -> &str { + str::from_utf8(&self.buf[self.pos..]).unwrap() + } +} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/de/value.rs cargo-0.26.0/vendor/serde-1.0.37/src/de/value.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/de/value.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/de/value.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1303 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Building blocks for deserializing basic values using the `IntoDeserializer` +//! trait. +//! +//! ```rust +//! #[macro_use] +//! extern crate serde_derive; +//! +//! extern crate serde; +//! +//! use std::str::FromStr; +//! use serde::de::{value, Deserialize, IntoDeserializer}; +//! +//! #[derive(Deserialize)] +//! enum Setting { +//! On, +//! Off, +//! } +//! +//! impl FromStr for Setting { +//! type Err = value::Error; +//! +//! fn from_str(s: &str) -> Result<Self, Self::Err> { +//! Self::deserialize(s.into_deserializer()) +//! } +//! } +//! # +//! # fn main() {} +//! ``` + +use lib::*; + +use self::private::{First, Second}; +use de::{self, Expected, IntoDeserializer, SeqAccess}; +use private::de::size_hint; +use ser; + +//////////////////////////////////////////////////////////////////////////////// + +/// A minimal representation of all possible errors that can occur using the +/// `IntoDeserializer` trait. +#[derive(Clone, Debug, PartialEq)] +pub struct Error { + err: ErrorImpl, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +type ErrorImpl = Box<str>; +#[cfg(not(any(feature = "std", feature = "alloc")))] +type ErrorImpl = (); + +impl de::Error for Error { + #[cfg(any(feature = "std", feature = "alloc"))] + fn custom<T>(msg: T) -> Self + where + T: Display, + { + Error { + err: msg.to_string().into_boxed_str(), + } + } + + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn custom<T>(msg: T) -> Self + where + T: Display, + { + let _ = msg; + Error { err: () } + } +} + +impl ser::Error for Error { + fn custom<T>(msg: T) -> Self + where + T: Display, + { + de::Error::custom(msg) + } +} + +impl Display for Error { + #[cfg(any(feature = "std", feature = "alloc"))] + fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + formatter.write_str(&self.err) + } + + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + formatter.write_str("Serde deserialization error") + } +} + +#[cfg(feature = "std")] +impl error::Error for Error { + fn description(&self) -> &str { + &self.err + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<'de, E> IntoDeserializer<'de, E> for () +where + E: de::Error, +{ + type Deserializer = UnitDeserializer<E>; + + fn into_deserializer(self) -> UnitDeserializer<E> { + UnitDeserializer { + marker: PhantomData, + } + } +} + +/// A deserializer holding a `()`. +#[derive(Clone, Debug)] +pub struct UnitDeserializer<E> { + marker: PhantomData<E>, +} + +impl<'de, E> de::Deserializer<'de> for UnitDeserializer<E> +where + E: de::Error, +{ + type Error = E; + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf unit unit_struct newtype_struct seq tuple tuple_struct map + struct enum identifier ignored_any + } + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.visit_unit() + } + + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.visit_none() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! primitive_deserializer { + ($ty:ty, $doc:tt, $name:ident, $method:ident $($cast:tt)*) => { + #[doc = "A deserializer holding"] + #[doc = $doc] + #[derive(Clone, Debug)] + pub struct $name<E> { + value: $ty, + marker: PhantomData<E> + } + + impl<'de, E> IntoDeserializer<'de, E> for $ty + where + E: de::Error, + { + type Deserializer = $name<E>; + + fn into_deserializer(self) -> $name<E> { + $name { + value: self, + marker: PhantomData, + } + } + } + + impl<'de, E> de::Deserializer<'de> for $name<E> + where + E: de::Error, + { + type Error = E; + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.$method(self.value $($cast)*) + } + } + } +} + +primitive_deserializer!(bool, "a `bool`.", BoolDeserializer, visit_bool); +primitive_deserializer!(i8, "an `i8`.", I8Deserializer, visit_i8); +primitive_deserializer!(i16, "an `i16`.", I16Deserializer, visit_i16); +primitive_deserializer!(i32, "an `i32`.", I32Deserializer, visit_i32); +primitive_deserializer!(i64, "an `i64`.", I64Deserializer, visit_i64); +primitive_deserializer!(isize, "an `isize`.", IsizeDeserializer, visit_i64 as i64); +primitive_deserializer!(u8, "a `u8`.", U8Deserializer, visit_u8); +primitive_deserializer!(u16, "a `u16`.", U16Deserializer, visit_u16); +primitive_deserializer!(u64, "a `u64`.", U64Deserializer, visit_u64); +primitive_deserializer!(usize, "a `usize`.", UsizeDeserializer, visit_u64 as u64); +primitive_deserializer!(f32, "an `f32`.", F32Deserializer, visit_f32); +primitive_deserializer!(f64, "an `f64`.", F64Deserializer, visit_f64); +primitive_deserializer!(char, "a `char`.", CharDeserializer, visit_char); + +/// A deserializer holding a `u32`. +#[derive(Clone, Debug)] +pub struct U32Deserializer<E> { + value: u32, + marker: PhantomData<E>, +} + +impl<'de, E> IntoDeserializer<'de, E> for u32 +where + E: de::Error, +{ + type Deserializer = U32Deserializer<E>; + + fn into_deserializer(self) -> U32Deserializer<E> { + U32Deserializer { + value: self, + marker: PhantomData, + } + } +} + +impl<'de, E> de::Deserializer<'de> for U32Deserializer<E> +where + E: de::Error, +{ + type Error = E; + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct identifier ignored_any + } + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.visit_u32(self.value) + } + + fn deserialize_enum<V>( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } +} + +impl<'de, E> de::EnumAccess<'de> for U32Deserializer<E> +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly<E>; + + fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `&str`. +#[derive(Clone, Debug)] +pub struct StrDeserializer<'a, E> { + value: &'a str, + marker: PhantomData<E>, +} + +impl<'de, 'a, E> IntoDeserializer<'de, E> for &'a str +where + E: de::Error, +{ + type Deserializer = StrDeserializer<'a, E>; + + fn into_deserializer(self) -> StrDeserializer<'a, E> { + StrDeserializer { + value: self, + marker: PhantomData, + } + } +} + +impl<'de, 'a, E> de::Deserializer<'de> for StrDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.visit_str(self.value) + } + + fn deserialize_enum<V>( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct identifier ignored_any + } +} + +impl<'de, 'a, E> de::EnumAccess<'de> for StrDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly<E>; + + fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `&str` with a lifetime tied to another +/// deserializer. +#[derive(Clone, Debug)] +pub struct BorrowedStrDeserializer<'de, E> { + value: &'de str, + marker: PhantomData<E>, +} + +impl<'de, E> BorrowedStrDeserializer<'de, E> { + /// Create a new borrowed deserializer from the given string. + pub fn new(value: &'de str) -> BorrowedStrDeserializer<'de, E> { + BorrowedStrDeserializer { + value: value, + marker: PhantomData, + } + } +} + +impl<'de, E> de::Deserializer<'de> for BorrowedStrDeserializer<'de, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.visit_borrowed_str(self.value) + } + + fn deserialize_enum<V>( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct identifier ignored_any + } +} + +impl<'de, E> de::EnumAccess<'de> for BorrowedStrDeserializer<'de, E> +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly<E>; + + fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `String`. +#[cfg(any(feature = "std", feature = "alloc"))] +#[derive(Clone, Debug)] +pub struct StringDeserializer<E> { + value: String, + marker: PhantomData<E>, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, E> IntoDeserializer<'de, E> for String +where + E: de::Error, +{ + type Deserializer = StringDeserializer<E>; + + fn into_deserializer(self) -> StringDeserializer<E> { + StringDeserializer { + value: self, + marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, E> de::Deserializer<'de> for StringDeserializer<E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.visit_string(self.value) + } + + fn deserialize_enum<V>( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct identifier ignored_any + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, 'a, E> de::EnumAccess<'de> for StringDeserializer<E> +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly<E>; + + fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `Cow<str>`. +#[cfg(any(feature = "std", feature = "alloc"))] +#[derive(Clone, Debug)] +pub struct CowStrDeserializer<'a, E> { + value: Cow<'a, str>, + marker: PhantomData<E>, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, 'a, E> IntoDeserializer<'de, E> for Cow<'a, str> +where + E: de::Error, +{ + type Deserializer = CowStrDeserializer<'a, E>; + + fn into_deserializer(self) -> CowStrDeserializer<'a, E> { + CowStrDeserializer { + value: self, + marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, 'a, E> de::Deserializer<'de> for CowStrDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + match self.value { + Cow::Borrowed(string) => visitor.visit_str(string), + Cow::Owned(string) => visitor.visit_string(string), + } + } + + fn deserialize_enum<V>( + self, + name: &str, + variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + let _ = name; + let _ = variants; + visitor.visit_enum(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct identifier ignored_any + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, 'a, E> de::EnumAccess<'de> for CowStrDeserializer<'a, E> +where + E: de::Error, +{ + type Error = E; + type Variant = private::UnitOnly<E>; + + fn variant_seed<T>(self, seed: T) -> Result<(T::Value, Self::Variant), Self::Error> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self).map(private::unit_only) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `&[u8]` with a lifetime tied to another +/// deserializer. +#[derive(Clone, Debug)] +pub struct BorrowedBytesDeserializer<'de, E> { + value: &'de [u8], + marker: PhantomData<E>, +} + +impl<'de, E> BorrowedBytesDeserializer<'de, E> { + /// Create a new borrowed deserializer from the given byte slice. + pub fn new(value: &'de [u8]) -> BorrowedBytesDeserializer<'de, E> { + BorrowedBytesDeserializer { + value: value, + marker: PhantomData, + } + } +} + +impl<'de, E> de::Deserializer<'de> for BorrowedBytesDeserializer<'de, E> +where + E: de::Error, +{ + type Error = E; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.visit_borrowed_bytes(self.value) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct identifier ignored_any enum + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer that iterates over a sequence. +#[derive(Clone, Debug)] +pub struct SeqDeserializer<I, E> { + iter: iter::Fuse<I>, + count: usize, + marker: PhantomData<E>, +} + +impl<I, E> SeqDeserializer<I, E> +where + I: Iterator, +{ + /// Construct a new `SeqDeserializer<I, E>`. + pub fn new(iter: I) -> Self { + SeqDeserializer { + iter: iter.fuse(), + count: 0, + marker: PhantomData, + } + } +} + +impl<I, E> SeqDeserializer<I, E> +where + I: Iterator, + E: de::Error, +{ + /// Check for remaining elements after passing a `SeqDeserializer` to + /// `Visitor::visit_seq`. + pub fn end(mut self) -> Result<(), E> { + let mut remaining = 0; + while self.iter.next().is_some() { + remaining += 1; + } + if remaining == 0 { + Ok(()) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length( + self.count + remaining, + &ExpectedInSeq(self.count), + )) + } + } +} + +impl<'de, I, T, E> de::Deserializer<'de> for SeqDeserializer<I, E> +where + I: Iterator<Item = T>, + T: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + let v = try!(visitor.visit_seq(&mut self)); + try!(self.end()); + Ok(v) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier ignored_any + } +} + +impl<'de, I, T, E> de::SeqAccess<'de> for SeqDeserializer<I, E> +where + I: Iterator<Item = T>, + T: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn next_element_seed<V>(&mut self, seed: V) -> Result<Option<V::Value>, Self::Error> + where + V: de::DeserializeSeed<'de>, + { + match self.iter.next() { + Some(value) => { + self.count += 1; + seed.deserialize(value.into_deserializer()).map(Some) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option<usize> { + size_hint::from_bounds(&self.iter) + } +} + +struct ExpectedInSeq(usize); + +impl Expected for ExpectedInSeq { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.0 == 1 { + write!(formatter, "1 element in sequence") + } else { + write!(formatter, "{} elements in sequence", self.0) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, T, E> IntoDeserializer<'de, E> for Vec<T> +where + T: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, T, E> IntoDeserializer<'de, E> for BTreeSet<T> +where + T: IntoDeserializer<'de, E> + Eq + Ord, + E: de::Error, +{ + type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} + +#[cfg(feature = "std")] +impl<'de, T, S, E> IntoDeserializer<'de, E> for HashSet<T, S> +where + T: IntoDeserializer<'de, E> + Eq + Hash, + S: BuildHasher, + E: de::Error, +{ + type Deserializer = SeqDeserializer<<Self as IntoIterator>::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + SeqDeserializer::new(self.into_iter()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `SeqAccess`. +#[derive(Clone, Debug)] +pub struct SeqAccessDeserializer<A> { + seq: A, +} + +impl<A> SeqAccessDeserializer<A> { + /// Construct a new `SeqAccessDeserializer<A>`. + pub fn new(seq: A) -> Self { + SeqAccessDeserializer { seq: seq } + } +} + +impl<'de, A> de::Deserializer<'de> for SeqAccessDeserializer<A> +where + A: de::SeqAccess<'de>, +{ + type Error = A::Error; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.visit_seq(self.seq) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier ignored_any + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer that iterates over a map. +pub struct MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, +{ + iter: iter::Fuse<I>, + value: Option<Second<I::Item>>, + count: usize, + lifetime: PhantomData<&'de ()>, + error: PhantomData<E>, +} + +impl<'de, I, E> MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, +{ + /// Construct a new `MapDeserializer<I, E>`. + pub fn new(iter: I) -> Self { + MapDeserializer { + iter: iter.fuse(), + value: None, + count: 0, + lifetime: PhantomData, + error: PhantomData, + } + } +} + +impl<'de, I, E> MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + E: de::Error, +{ + /// Check for remaining elements after passing a `MapDeserializer` to + /// `Visitor::visit_map`. + pub fn end(mut self) -> Result<(), E> { + let mut remaining = 0; + while self.iter.next().is_some() { + remaining += 1; + } + if remaining == 0 { + Ok(()) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length( + self.count + remaining, + &ExpectedInMap(self.count), + )) + } + } +} + +impl<'de, I, E> MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, +{ + fn next_pair(&mut self) -> Option<(First<I::Item>, Second<I::Item>)> { + match self.iter.next() { + Some(kv) => { + self.count += 1; + Some(private::Pair::split(kv)) + } + None => None, + } + } +} + +impl<'de, I, E> de::Deserializer<'de> for MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + First<I::Item>: IntoDeserializer<'de, E>, + Second<I::Item>: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + let value = try!(visitor.visit_map(&mut self)); + try!(self.end()); + Ok(value) + } + + fn deserialize_seq<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + let value = try!(visitor.visit_seq(&mut self)); + try!(self.end()); + Ok(value) + } + + fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + let _ = len; + self.deserialize_seq(visitor) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct tuple_struct map struct + enum identifier ignored_any + } +} + +impl<'de, I, E> de::MapAccess<'de> for MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + First<I::Item>: IntoDeserializer<'de, E>, + Second<I::Item>: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.next_pair() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(key.into_deserializer()).map(Some) + } + None => Ok(None), + } + } + + fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + let value = self.value.take(); + // Panic because this indicates a bug in the program rather than an + // expected failure. + let value = value.expect("MapAccess::visit_value called before visit_key"); + seed.deserialize(value.into_deserializer()) + } + + fn next_entry_seed<TK, TV>( + &mut self, + kseed: TK, + vseed: TV, + ) -> Result<Option<(TK::Value, TV::Value)>, Self::Error> + where + TK: de::DeserializeSeed<'de>, + TV: de::DeserializeSeed<'de>, + { + match self.next_pair() { + Some((key, value)) => { + let key = try!(kseed.deserialize(key.into_deserializer())); + let value = try!(vseed.deserialize(value.into_deserializer())); + Ok(Some((key, value))) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option<usize> { + size_hint::from_bounds(&self.iter) + } +} + +impl<'de, I, E> de::SeqAccess<'de> for MapDeserializer<'de, I, E> +where + I: Iterator, + I::Item: private::Pair, + First<I::Item>: IntoDeserializer<'de, E>, + Second<I::Item>: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.next_pair() { + Some((k, v)) => { + let de = PairDeserializer(k, v, PhantomData); + seed.deserialize(de).map(Some) + } + None => Ok(None), + } + } + + fn size_hint(&self) -> Option<usize> { + size_hint::from_bounds(&self.iter) + } +} + +// Cannot #[derive(Clone)] because of the bound `Second<I::Item>: Clone`. +impl<'de, I, E> Clone for MapDeserializer<'de, I, E> +where + I: Iterator + Clone, + I::Item: private::Pair, + Second<I::Item>: Clone, +{ + fn clone(&self) -> Self { + MapDeserializer { + iter: self.iter.clone(), + value: self.value.clone(), + count: self.count, + lifetime: self.lifetime, + error: self.error, + } + } +} + +// Cannot #[derive(Debug)] because of the bound `Second<I::Item>: Debug`. +impl<'de, I, E> Debug for MapDeserializer<'de, I, E> +where + I: Iterator + Debug, + I::Item: private::Pair, + Second<I::Item>: Debug, +{ + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter + .debug_struct("MapDeserializer") + .field("iter", &self.iter) + .field("value", &self.value) + .field("count", &self.count) + .field("lifetime", &self.lifetime) + .field("error", &self.error) + .finish() + } +} + +// Used in the `impl SeqAccess for MapDeserializer` to visit the map as a +// sequence of pairs. +struct PairDeserializer<A, B, E>(A, B, PhantomData<E>); + +impl<'de, A, B, E> de::Deserializer<'de> for PairDeserializer<A, B, E> +where + A: IntoDeserializer<'de, E>, + B: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct tuple_struct map struct + enum identifier ignored_any + } + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + let mut pair_visitor = PairVisitor(Some(self.0), Some(self.1), PhantomData); + let pair = try!(visitor.visit_seq(&mut pair_visitor)); + if pair_visitor.1.is_none() { + Ok(pair) + } else { + let remaining = pair_visitor.size_hint().unwrap(); + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(2, &ExpectedInSeq(2 - remaining))) + } + } + + fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + if len == 2 { + self.deserialize_seq(visitor) + } else { + // First argument is the number of elements in the data, second + // argument is the number of elements expected by the Deserialize. + Err(de::Error::invalid_length(2, &ExpectedInSeq(len))) + } + } +} + +struct PairVisitor<A, B, E>(Option<A>, Option<B>, PhantomData<E>); + +impl<'de, A, B, E> de::SeqAccess<'de> for PairVisitor<A, B, E> +where + A: IntoDeserializer<'de, E>, + B: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Error = E; + + fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + if let Some(k) = self.0.take() { + seed.deserialize(k.into_deserializer()).map(Some) + } else if let Some(v) = self.1.take() { + seed.deserialize(v.into_deserializer()).map(Some) + } else { + Ok(None) + } + } + + fn size_hint(&self) -> Option<usize> { + if self.0.is_some() { + Some(2) + } else if self.1.is_some() { + Some(1) + } else { + Some(0) + } + } +} + +struct ExpectedInMap(usize); + +impl Expected for ExpectedInMap { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + if self.0 == 1 { + write!(formatter, "1 element in map") + } else { + write!(formatter, "{} elements in map", self.0) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'de, K, V, E> IntoDeserializer<'de, E> for BTreeMap<K, V> +where + K: IntoDeserializer<'de, E> + Eq + Ord, + V: IntoDeserializer<'de, E>, + E: de::Error, +{ + type Deserializer = MapDeserializer<'de, <Self as IntoIterator>::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + MapDeserializer::new(self.into_iter()) + } +} + +#[cfg(feature = "std")] +impl<'de, K, V, S, E> IntoDeserializer<'de, E> for HashMap<K, V, S> +where + K: IntoDeserializer<'de, E> + Eq + Hash, + V: IntoDeserializer<'de, E>, + S: BuildHasher, + E: de::Error, +{ + type Deserializer = MapDeserializer<'de, <Self as IntoIterator>::IntoIter, E>; + + fn into_deserializer(self) -> Self::Deserializer { + MapDeserializer::new(self.into_iter()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A deserializer holding a `MapAccess`. +#[derive(Clone, Debug)] +pub struct MapAccessDeserializer<A> { + map: A, +} + +impl<A> MapAccessDeserializer<A> { + /// Construct a new `MapAccessDeserializer<A>`. + pub fn new(map: A) -> Self { + MapAccessDeserializer { map: map } + } +} + +impl<'de, A> de::Deserializer<'de> for MapAccessDeserializer<A> +where + A: de::MapAccess<'de>, +{ + type Error = A::Error; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.visit_map(self.map) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier ignored_any + } +} + +//////////////////////////////////////////////////////////////////////////////// + +mod private { + use lib::*; + + use de::{self, Unexpected}; + + #[derive(Clone, Debug)] + pub struct UnitOnly<E> { + marker: PhantomData<E>, + } + + pub fn unit_only<T, E>(t: T) -> (T, UnitOnly<E>) { + ( + t, + UnitOnly { + marker: PhantomData, + }, + ) + } + + impl<'de, E> de::VariantAccess<'de> for UnitOnly<E> + where + E: de::Error, + { + type Error = E; + + fn unit_variant(self) -> Result<(), Self::Error> { + Ok(()) + } + + fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + Err(de::Error::invalid_type( + Unexpected::UnitVariant, + &"newtype variant", + )) + } + + fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + Err(de::Error::invalid_type( + Unexpected::UnitVariant, + &"tuple variant", + )) + } + + fn struct_variant<V>( + self, + _fields: &'static [&'static str], + _visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + Err(de::Error::invalid_type( + Unexpected::UnitVariant, + &"struct variant", + )) + } + } + + /// Avoid having to restate the generic types on `MapDeserializer`. The + /// `Iterator::Item` contains enough information to figure out K and V. + pub trait Pair { + type First; + type Second; + fn split(self) -> (Self::First, Self::Second); + } + + impl<A, B> Pair for (A, B) { + type First = A; + type Second = B; + fn split(self) -> (A, B) { + self + } + } + + pub type First<T> = <T as Pair>::First; + pub type Second<T> = <T as Pair>::Second; +} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/export.rs cargo-0.26.0/vendor/serde-1.0.37/src/export.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/export.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/export.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,41 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub use lib::clone::Clone; +pub use lib::convert::{From, Into}; +pub use lib::default::Default; +pub use lib::fmt::{self, Formatter}; +pub use lib::marker::PhantomData; +pub use lib::option::Option::{self, None, Some}; +pub use lib::result::Result::{self, Err, Ok}; + +pub use self::string::from_utf8_lossy; + +mod string { + use lib::*; + + #[cfg(any(feature = "std", feature = "alloc"))] + pub fn from_utf8_lossy(bytes: &[u8]) -> Cow<str> { + String::from_utf8_lossy(bytes) + } + + // The generated code calls this like: + // + // let value = &_serde::export::from_utf8_lossy(bytes); + // Err(_serde::de::Error::unknown_variant(value, VARIANTS)) + // + // so it is okay for the return type to be different from the std case as long + // as the above works. + #[cfg(not(any(feature = "std", feature = "alloc")))] + pub fn from_utf8_lossy(bytes: &[u8]) -> &str { + // Three unicode replacement characters if it fails. They look like a + // white-on-black question mark. The user will recognize it as invalid + // UTF-8. + str::from_utf8(bytes).unwrap_or("\u{fffd}\u{fffd}\u{fffd}") + } +} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/lib.rs cargo-0.26.0/vendor/serde-1.0.37/src/lib.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,287 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! # Serde +//! +//! Serde is a framework for ***ser***ializing and ***de***serializing Rust data +//! structures efficiently and generically. +//! +//! The Serde ecosystem consists of data structures that know how to serialize +//! and deserialize themselves along with data formats that know how to +//! serialize and deserialize other things. Serde provides the layer by which +//! these two groups interact with each other, allowing any supported data +//! structure to be serialized and deserialized using any supported data format. +//! +//! See the Serde website [https://serde.rs/] for additional documentation and +//! usage examples. +//! +//! [https://serde.rs/]: https://serde.rs/ +//! +//! ## Design +//! +//! Where many other languages rely on runtime reflection for serializing data, +//! Serde is instead built on Rust's powerful trait system. A data structure +//! that knows how to serialize and deserialize itself is one that implements +//! Serde's `Serialize` and `Deserialize` traits (or uses Serde's derive +//! attribute to automatically generate implementations at compile time). This +//! avoids any overhead of reflection or runtime type information. In fact in +//! many situations the interaction between data structure and data format can +//! be completely optimized away by the Rust compiler, leaving Serde +//! serialization to perform the same speed as a handwritten serializer for the +//! specific selection of data structure and data format. +//! +//! ## Data formats +//! +//! The following is a partial list of data formats that have been implemented +//! for Serde by the community. +//! +//! - [JSON], the ubiquitous JavaScript Object Notation used by many HTTP APIs. +//! - [Bincode], a compact binary format +//! used for IPC within the Servo rendering engine. +//! - [CBOR], a Concise Binary Object Representation designed for small message +//! size without the need for version negotiation. +//! - [YAML], a popular human-friendly configuration language that ain't markup +//! language. +//! - [MessagePack], an efficient binary format that resembles a compact JSON. +//! - [TOML], a minimal configuration format used by [Cargo]. +//! - [Pickle], a format common in the Python world. +//! - [Hjson], a variant of JSON designed to be readable and writable by humans. +//! - [BSON], the data storage and network transfer format used by MongoDB. +//! - [URL], the x-www-form-urlencoded format. +//! - [XML], the flexible machine-friendly W3C standard. +//! *(deserialization only)* +//! - [Envy], a way to deserialize environment variables into Rust structs. +//! *(deserialization only)* +//! - [Redis], deserialize values from Redis when using [redis-rs]. +//! *(deserialization only)* +//! +//! [JSON]: https://github.com/serde-rs/json +//! [Bincode]: https://github.com/TyOverby/bincode +//! [CBOR]: https://github.com/pyfisch/cbor +//! [YAML]: https://github.com/dtolnay/serde-yaml +//! [MessagePack]: https://github.com/3Hren/msgpack-rust +//! [TOML]: https://github.com/alexcrichton/toml-rs +//! [Pickle]: https://github.com/birkenfeld/serde-pickle +//! [Hjson]: https://github.com/laktak/hjson-rust +//! [BSON]: https://github.com/zonyitoo/bson-rs +//! [URL]: https://github.com/nox/serde_urlencoded +//! [XML]: https://github.com/RReverser/serde-xml-rs +//! [Envy]: https://github.com/softprops/envy +//! [Redis]: https://github.com/OneSignal/serde-redis +//! [Cargo]: http://doc.crates.io/manifest.html +//! [redis-rs]: https://crates.io/crates/redis + +//////////////////////////////////////////////////////////////////////////////// + +// Serde types in rustdoc of other crates get linked to here. +#![doc(html_root_url = "https://docs.rs/serde/1.0.37")] +// Support using Serde without the standard library! +#![cfg_attr(not(feature = "std"), no_std)] +// Unstable functionality only if the user asks for it. For tracking and +// discussion of these features please refer to this issue: +// +// https://github.com/serde-rs/serde/issues/812 +#![cfg_attr(feature = "unstable", feature(nonzero, specialization))] +#![cfg_attr(feature = "alloc", feature(alloc))] +#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))] +// Whitelisted clippy lints +#![cfg_attr(feature = "cargo-clippy", + allow(cast_lossless, const_static_lifetime, doc_markdown, linkedlist, + needless_pass_by_value, redundant_field_names, type_complexity, + unreadable_literal, zero_prefixed_literal))] +// Whitelisted clippy_pedantic lints +#![cfg_attr(feature = "cargo-clippy", allow( +// integer and float ser/de requires these sorts of casts + cast_possible_truncation, + cast_possible_wrap, + cast_precision_loss, + cast_sign_loss, +// simplifies some macros + invalid_upcast_comparisons, +// things are often more readable this way + decimal_literal_representation, + option_unwrap_used, + result_unwrap_used, + shadow_reuse, + single_match_else, + stutter, + use_self, +// not practical + many_single_char_names, + missing_docs_in_private_items, + similar_names, +// alternative is not stable + empty_enum, + use_debug, +))] +// Blacklisted Rust lints. +#![deny(missing_docs, unused_imports)] + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "alloc")] +extern crate alloc; + +#[cfg(all(feature = "unstable", feature = "std"))] +extern crate core; + +/// A facade around all the types we need from the `std`, `core`, and `alloc` +/// crates. This avoids elaborate import wrangling having to happen in every +/// module. +mod lib { + mod core { + #[cfg(not(feature = "std"))] + pub use core::*; + #[cfg(feature = "std")] + pub use std::*; + } + + pub use self::core::{cmp, iter, mem, ops, slice, str}; + pub use self::core::{f32, f64}; + pub use self::core::{isize, i16, i32, i64, i8}; + pub use self::core::{usize, u16, u32, u64, u8}; + + pub use self::core::cell::{Cell, RefCell}; + pub use self::core::clone::{self, Clone}; + pub use self::core::convert::{self, From, Into}; + pub use self::core::default::{self, Default}; + pub use self::core::fmt::{self, Debug, Display}; + pub use self::core::marker::{self, PhantomData}; + pub use self::core::option::{self, Option}; + pub use self::core::result::{self, Result}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::borrow::{Cow, ToOwned}; + #[cfg(feature = "std")] + pub use std::borrow::{Cow, ToOwned}; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::string::{String, ToString}; + #[cfg(feature = "std")] + pub use std::string::String; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::vec::Vec; + #[cfg(feature = "std")] + pub use std::vec::Vec; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::boxed::Box; + #[cfg(feature = "std")] + pub use std::boxed::Box; + + #[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))] + pub use alloc::rc::Rc; + #[cfg(all(feature = "rc", feature = "std"))] + pub use std::rc::Rc; + + #[cfg(all(feature = "rc", feature = "alloc", not(feature = "std")))] + pub use alloc::arc::Arc; + #[cfg(all(feature = "rc", feature = "std"))] + pub use std::sync::Arc; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub use alloc::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; + #[cfg(feature = "std")] + pub use std::collections::{BTreeMap, BTreeSet, BinaryHeap, LinkedList, VecDeque}; + + #[cfg(feature = "std")] + pub use std::{error, net}; + + #[cfg(feature = "std")] + pub use std::collections::{HashMap, HashSet}; + #[cfg(feature = "std")] + pub use std::ffi::{CStr, CString, OsStr, OsString}; + #[cfg(feature = "std")] + pub use std::hash::{BuildHasher, Hash}; + #[cfg(feature = "std")] + pub use std::io::Write; + #[cfg(feature = "std")] + pub use std::num::Wrapping; + #[cfg(feature = "std")] + pub use std::path::{Path, PathBuf}; + #[cfg(feature = "std")] + pub use std::sync::{Mutex, RwLock}; + #[cfg(feature = "std")] + pub use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + #[cfg(feature = "unstable")] + #[allow(deprecated)] + pub use core::nonzero::{NonZero, Zeroable}; + + #[cfg(feature = "unstable")] + pub use core::num::{NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize}; +} + +//////////////////////////////////////////////////////////////////////////////// + +#[macro_use] +mod macros; + +pub mod de; +pub mod ser; + +#[doc(inline)] +pub use de::{Deserialize, Deserializer}; +#[doc(inline)] +pub use ser::{Serialize, Serializer}; + +// Generated code uses these to support no_std. Not public API. +#[doc(hidden)] +pub mod export; + +// Helpers used by generated code and doc tests. Not public API. +#[doc(hidden)] +pub mod private; + +// Re-export #[derive(Serialize, Deserialize)]. +// +// This is a workaround for https://github.com/rust-lang/cargo/issues/1286. +// Without this re-export, crates that put Serde derives behind a cfg_attr would +// need to use some silly feature name that depends on both serde and +// serde_derive. +// +// [features] +// serde-impls = ["serde", "serde_derive"] +// +// [dependencies] +// serde = { version = "1.0", optional = true } +// serde_derive = { version = "1.0", optional = true } +// +// # Used like this: +// # #[cfg(feature = "serde-impls")] +// # #[macro_use] +// # extern crate serde_derive; +// # +// # #[cfg_attr(feature = "serde-impls", derive(Serialize, Deserialize))] +// # struct S { /* ... */ } +// +// The re-exported derives allow crates to use "serde" as the name of their +// Serde feature which is more intuitive. +// +// [dependencies] +// serde = { version = "1.0", optional = true, features = ["derive"] } +// +// # Used like this: +// # #[cfg(feature = "serde")] +// # #[macro_use] +// # extern crate serde; +// # +// # #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] +// # struct S { /* ... */ } +// +// The reason re-exporting is not enabled by default is that disabling it would +// be annoying for crates that provide handwritten impls or data formats. They +// would need to disable default features and then explicitly re-enable std. +#[cfg(feature = "serde_derive")] +#[allow(unused_imports)] +#[macro_use] +extern crate serde_derive; +#[cfg(feature = "serde_derive")] +#[doc(hidden)] +pub use serde_derive::*; diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/macros.rs cargo-0.26.0/vendor/serde-1.0.37/src/macros.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/macros.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/macros.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,242 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// Super explicit first paragraph because this shows up at the top level and +// trips up people who are just looking for basic Serialize / Deserialize +// documentation. +// +/// Helper macro when implementing the `Deserializer` part of a new data format +/// for Serde. +/// +/// Some [`Deserializer`] implementations for self-describing formats do not +/// care what hint the [`Visitor`] gives them, they just want to blindly call +/// the [`Visitor`] method corresponding to the data they can tell is in the +/// input. This requires repetitive implementations of all the [`Deserializer`] +/// trait methods. +/// +/// ```rust +/// # #[macro_use] +/// # extern crate serde; +/// # +/// # use serde::de::{value, Deserializer, Visitor}; +/// # +/// # struct MyDeserializer; +/// # +/// # impl<'de> Deserializer<'de> for MyDeserializer { +/// # type Error = value::Error; +/// # +/// # fn deserialize_any<V>(self, _: V) -> Result<V::Value, Self::Error> +/// # where V: Visitor<'de> +/// # { +/// # unimplemented!() +/// # } +/// # +/// #[inline] +/// fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value, Self::Error> +/// where V: Visitor<'de> +/// { +/// self.deserialize_any(visitor) +/// } +/// # +/// # forward_to_deserialize_any! { +/// # i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes +/// # byte_buf option unit unit_struct newtype_struct seq tuple +/// # tuple_struct map struct enum identifier ignored_any +/// # } +/// # } +/// # +/// # fn main() {} +/// ``` +/// +/// The `forward_to_deserialize_any!` macro implements these simple forwarding +/// methods so that they forward directly to [`Deserializer::deserialize_any`]. +/// You can choose which methods to forward. +/// +/// ```rust +/// # #[macro_use] +/// # extern crate serde; +/// # +/// # use serde::de::{value, Deserializer, Visitor}; +/// # +/// # struct MyDeserializer; +/// # +/// impl<'de> Deserializer<'de> for MyDeserializer { +/// # type Error = value::Error; +/// # +/// fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> +/// where V: Visitor<'de> +/// { +/// /* ... */ +/// # let _ = visitor; +/// # unimplemented!() +/// } +/// +/// forward_to_deserialize_any! { +/// bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes +/// byte_buf option unit unit_struct newtype_struct seq tuple +/// tuple_struct map struct enum identifier ignored_any +/// } +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// The macro assumes the convention that your `Deserializer` lifetime parameter +/// is called `'de` and that the `Visitor` type parameters on each method are +/// called `V`. A different type parameter and a different lifetime can be +/// specified explicitly if necessary. +/// +/// ```rust +/// # #[macro_use] +/// # extern crate serde; +/// # +/// # use std::marker::PhantomData; +/// # +/// # use serde::de::{value, Deserializer, Visitor}; +/// # +/// # struct MyDeserializer<V>(PhantomData<V>); +/// # +/// # impl<'q, V> Deserializer<'q> for MyDeserializer<V> { +/// # type Error = value::Error; +/// # +/// # fn deserialize_any<W>(self, visitor: W) -> Result<W::Value, Self::Error> +/// # where W: Visitor<'q> +/// # { +/// # unimplemented!() +/// # } +/// # +/// forward_to_deserialize_any! { +/// <W: Visitor<'q>> +/// bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes +/// byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct +/// map struct enum identifier ignored_any +/// } +/// # } +/// # +/// # fn main() {} +/// ``` +/// +/// [`Deserializer`]: trait.Deserializer.html +/// [`Visitor`]: de/trait.Visitor.html +/// [`Deserializer::deserialize_any`]: trait.Deserializer.html#tymethod.deserialize_any +#[macro_export] +macro_rules! forward_to_deserialize_any { + (<$visitor:ident: Visitor<$lifetime:tt>> $($func:ident)*) => { + $(forward_to_deserialize_any_helper!{$func<$lifetime, $visitor>})* + }; + // This case must be after the previous one. + ($($func:ident)*) => { + $(forward_to_deserialize_any_helper!{$func<'de, V>})* + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! forward_to_deserialize_any_method { + ($func:ident<$l:tt, $v:ident>($($arg:ident : $ty:ty),*)) => { + #[inline] + fn $func<$v>(self, $($arg: $ty,)* visitor: $v) -> $crate::export::Result<$v::Value, Self::Error> + where + $v: $crate::de::Visitor<$l>, + { + $( + let _ = $arg; + )* + self.deserialize_any(visitor) + } + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! forward_to_deserialize_any_helper { + (bool<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_bool<$l, $v>()} + }; + (i8<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i8<$l, $v>()} + }; + (i16<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i16<$l, $v>()} + }; + (i32<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i32<$l, $v>()} + }; + (i64<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_i64<$l, $v>()} + }; + (u8<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u8<$l, $v>()} + }; + (u16<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u16<$l, $v>()} + }; + (u32<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u32<$l, $v>()} + }; + (u64<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_u64<$l, $v>()} + }; + (f32<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_f32<$l, $v>()} + }; + (f64<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_f64<$l, $v>()} + }; + (char<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_char<$l, $v>()} + }; + (str<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_str<$l, $v>()} + }; + (string<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_string<$l, $v>()} + }; + (bytes<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_bytes<$l, $v>()} + }; + (byte_buf<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_byte_buf<$l, $v>()} + }; + (option<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_option<$l, $v>()} + }; + (unit<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_unit<$l, $v>()} + }; + (unit_struct<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_unit_struct<$l, $v>(name: &'static str)} + }; + (newtype_struct<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_newtype_struct<$l, $v>(name: &'static str)} + }; + (seq<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_seq<$l, $v>()} + }; + (tuple<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_tuple<$l, $v>(len: usize)} + }; + (tuple_struct<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_tuple_struct<$l, $v>(name: &'static str, len: usize)} + }; + (map<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_map<$l, $v>()} + }; + (struct<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_struct<$l, $v>(name: &'static str, fields: &'static [&'static str])} + }; + (enum<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_enum<$l, $v>(name: &'static str, variants: &'static [&'static str])} + }; + (identifier<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_identifier<$l, $v>()} + }; + (ignored_any<$l:tt, $v:ident>) => { + forward_to_deserialize_any_method!{deserialize_ignored_any<$l, $v>()} + }; +} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/private/de.rs cargo-0.26.0/vendor/serde-1.0.37/src/private/de.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/private/de.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/private/de.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2234 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use lib::*; + +use de::{Deserialize, DeserializeSeed, Deserializer, Error, IntoDeserializer, Visitor}; + +#[cfg(any(feature = "std", feature = "alloc"))] +use de::{MapAccess, Unexpected}; + +#[cfg(any(feature = "std", feature = "alloc"))] +pub use self::content::{Content, ContentDeserializer, ContentRefDeserializer, EnumDeserializer, + InternallyTaggedUnitVisitor, TagContentOtherField, + TagContentOtherFieldVisitor, TagOrContentField, TagOrContentFieldVisitor, + TaggedContentVisitor, UntaggedUnitVisitor}; + +/// If the missing field is of type `Option<T>` then treat is as `None`, +/// otherwise it is an error. +pub fn missing_field<'de, V, E>(field: &'static str) -> Result<V, E> +where + V: Deserialize<'de>, + E: Error, +{ + struct MissingFieldDeserializer<E>(&'static str, PhantomData<E>); + + impl<'de, E> Deserializer<'de> for MissingFieldDeserializer<E> + where + E: Error, + { + type Error = E; + + fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, E> + where + V: Visitor<'de>, + { + Err(Error::missing_field(self.0)) + } + + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E> + where + V: Visitor<'de>, + { + visitor.visit_none() + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf unit unit_struct newtype_struct seq tuple tuple_struct map + struct enum identifier ignored_any + } + } + + let deserializer = MissingFieldDeserializer(field, PhantomData); + Deserialize::deserialize(deserializer) +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub fn borrow_cow_str<'de: 'a, 'a, D>(deserializer: D) -> Result<Cow<'a, str>, D::Error> +where + D: Deserializer<'de>, +{ + struct CowStrVisitor; + + impl<'a> Visitor<'a> for CowStrVisitor { + type Value = Cow<'a, str>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string") + } + + fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> + where + E: Error, + { + Ok(Cow::Owned(v.to_owned())) + } + + fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> + where + E: Error, + { + Ok(Cow::Borrowed(v)) + } + + fn visit_string<E>(self, v: String) -> Result<Self::Value, E> + where + E: Error, + { + Ok(Cow::Owned(v)) + } + + fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> + where + E: Error, + { + match str::from_utf8(v) { + Ok(s) => Ok(Cow::Owned(s.to_owned())), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> + where + E: Error, + { + match str::from_utf8(v) { + Ok(s) => Ok(Cow::Borrowed(s)), + Err(_) => Err(Error::invalid_value(Unexpected::Bytes(v), &self)), + } + } + + fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> + where + E: Error, + { + match String::from_utf8(v) { + Ok(s) => Ok(Cow::Owned(s)), + Err(e) => Err(Error::invalid_value( + Unexpected::Bytes(&e.into_bytes()), + &self, + )), + } + } + } + + deserializer.deserialize_str(CowStrVisitor) +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub fn borrow_cow_bytes<'de: 'a, 'a, D>(deserializer: D) -> Result<Cow<'a, [u8]>, D::Error> +where + D: Deserializer<'de>, +{ + struct CowBytesVisitor; + + impl<'a> Visitor<'a> for CowBytesVisitor { + type Value = Cow<'a, [u8]>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a byte array") + } + + fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> + where + E: Error, + { + Ok(Cow::Owned(v.as_bytes().to_vec())) + } + + fn visit_borrowed_str<E>(self, v: &'a str) -> Result<Self::Value, E> + where + E: Error, + { + Ok(Cow::Borrowed(v.as_bytes())) + } + + fn visit_string<E>(self, v: String) -> Result<Self::Value, E> + where + E: Error, + { + Ok(Cow::Owned(v.into_bytes())) + } + + fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> + where + E: Error, + { + Ok(Cow::Owned(v.to_vec())) + } + + fn visit_borrowed_bytes<E>(self, v: &'a [u8]) -> Result<Self::Value, E> + where + E: Error, + { + Ok(Cow::Borrowed(v)) + } + + fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E> + where + E: Error, + { + Ok(Cow::Owned(v)) + } + } + + deserializer.deserialize_bytes(CowBytesVisitor) +} + +pub mod size_hint { + use lib::*; + + pub fn from_bounds<I>(iter: &I) -> Option<usize> + where + I: Iterator, + { + helper(iter.size_hint()) + } + + #[inline] + pub fn cautious(hint: Option<usize>) -> usize { + cmp::min(hint.unwrap_or(0), 4096) + } + + fn helper(bounds: (usize, Option<usize>)) -> Option<usize> { + match bounds { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +mod content { + // This module is private and nothing here should be used outside of + // generated code. + // + // We will iterate on the implementation for a few releases and only have to + // worry about backward compatibility for the `untagged` and `tag` attributes + // rather than for this entire mechanism. + // + // This issue is tracking making some of this stuff public: + // https://github.com/serde-rs/serde/issues/741 + + use lib::*; + + use super::size_hint; + use de::{self, Deserialize, DeserializeSeed, Deserializer, EnumAccess, MapAccess, SeqAccess, + Unexpected, Visitor}; + + /// Used from generated code to buffer the contents of the Deserializer when + /// deserializing untagged enums and internally tagged enums. + /// + /// Not public API. Use serde-value instead. + #[derive(Debug)] + pub enum Content<'de> { + Bool(bool), + + U8(u8), + U16(u16), + U32(u32), + U64(u64), + + I8(i8), + I16(i16), + I32(i32), + I64(i64), + + F32(f32), + F64(f64), + + Char(char), + String(String), + Str(&'de str), + ByteBuf(Vec<u8>), + Bytes(&'de [u8]), + + None, + Some(Box<Content<'de>>), + + Unit, + Newtype(Box<Content<'de>>), + Seq(Vec<Content<'de>>), + Map(Vec<(Content<'de>, Content<'de>)>), + } + + impl<'de> Content<'de> { + pub fn as_str(&self) -> Option<&str> { + match *self { + Content::Str(x) => Some(x), + Content::String(ref x) => Some(x), + _ => None, + } + } + + fn unexpected(&self) -> Unexpected { + match *self { + Content::Bool(b) => Unexpected::Bool(b), + Content::U8(n) => Unexpected::Unsigned(n as u64), + Content::U16(n) => Unexpected::Unsigned(n as u64), + Content::U32(n) => Unexpected::Unsigned(n as u64), + Content::U64(n) => Unexpected::Unsigned(n), + Content::I8(n) => Unexpected::Signed(n as i64), + Content::I16(n) => Unexpected::Signed(n as i64), + Content::I32(n) => Unexpected::Signed(n as i64), + Content::I64(n) => Unexpected::Signed(n), + Content::F32(f) => Unexpected::Float(f as f64), + Content::F64(f) => Unexpected::Float(f), + Content::Char(c) => Unexpected::Char(c), + Content::String(ref s) => Unexpected::Str(s), + Content::Str(s) => Unexpected::Str(s), + Content::ByteBuf(ref b) => Unexpected::Bytes(b), + Content::Bytes(b) => Unexpected::Bytes(b), + Content::None | Content::Some(_) => Unexpected::Option, + Content::Unit => Unexpected::Unit, + Content::Newtype(_) => Unexpected::NewtypeStruct, + Content::Seq(_) => Unexpected::Seq, + Content::Map(_) => Unexpected::Map, + } + } + } + + impl<'de> Deserialize<'de> for Content<'de> { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + // Untagged and internally tagged enums are only supported in + // self-describing formats. + let visitor = ContentVisitor { value: PhantomData }; + deserializer.deserialize_any(visitor) + } + } + + struct ContentVisitor<'de> { + value: PhantomData<Content<'de>>, + } + + impl<'de> ContentVisitor<'de> { + fn new() -> Self { + ContentVisitor { value: PhantomData } + } + } + + impl<'de> Visitor<'de> for ContentVisitor<'de> { + type Value = Content<'de>; + + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str("any value") + } + + fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::Bool(value)) + } + + fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::I8(value)) + } + + fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::I16(value)) + } + + fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::I32(value)) + } + + fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::I64(value)) + } + + fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::U8(value)) + } + + fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::U16(value)) + } + + fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::U32(value)) + } + + fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::U64(value)) + } + + fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::F32(value)) + } + + fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::F64(value)) + } + + fn visit_char<F>(self, value: char) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::Char(value)) + } + + fn visit_str<F>(self, value: &str) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::String(value.into())) + } + + fn visit_borrowed_str<F>(self, value: &'de str) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::Str(value)) + } + + fn visit_string<F>(self, value: String) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::String(value)) + } + + fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::ByteBuf(value.into())) + } + + fn visit_borrowed_bytes<F>(self, value: &'de [u8]) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::Bytes(value)) + } + + fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::ByteBuf(value)) + } + + fn visit_unit<F>(self) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::Unit) + } + + fn visit_none<F>(self) -> Result<Self::Value, F> + where + F: de::Error, + { + Ok(Content::None) + } + + fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map(|v| Content::Some(Box::new(v))) + } + + fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + Deserialize::deserialize(deserializer).map(|v| Content::Newtype(Box::new(v))) + } + + fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> + where + V: SeqAccess<'de>, + { + let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint())); + while let Some(e) = try!(visitor.next_element()) { + vec.push(e); + } + Ok(Content::Seq(vec)) + } + + fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> + where + V: MapAccess<'de>, + { + let mut vec = Vec::with_capacity(size_hint::cautious(visitor.size_hint())); + while let Some(kv) = try!(visitor.next_entry()) { + vec.push(kv); + } + Ok(Content::Map(vec)) + } + + fn visit_enum<V>(self, _visitor: V) -> Result<Self::Value, V::Error> + where + V: EnumAccess<'de>, + { + Err(de::Error::custom( + "untagged and internally tagged enums do not support enum input", + )) + } + } + + /// This is the type of the map keys in an internally tagged enum. + /// + /// Not public API. + pub enum TagOrContent<'de> { + Tag, + Content(Content<'de>), + } + + struct TagOrContentVisitor<'de> { + name: &'static str, + value: PhantomData<TagOrContent<'de>>, + } + + impl<'de> TagOrContentVisitor<'de> { + fn new(name: &'static str) -> Self { + TagOrContentVisitor { + name: name, + value: PhantomData, + } + } + } + + impl<'de> DeserializeSeed<'de> for TagOrContentVisitor<'de> { + type Value = TagOrContent<'de>; + + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + // Internally tagged enums are only supported in self-describing + // formats. + deserializer.deserialize_any(self) + } + } + + impl<'de> Visitor<'de> for TagOrContentVisitor<'de> { + type Value = TagOrContent<'de>; + + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + write!(fmt, "a type tag `{}` or any other value", self.name) + } + + fn visit_bool<F>(self, value: bool) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_bool(value) + .map(TagOrContent::Content) + } + + fn visit_i8<F>(self, value: i8) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_i8(value) + .map(TagOrContent::Content) + } + + fn visit_i16<F>(self, value: i16) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_i16(value) + .map(TagOrContent::Content) + } + + fn visit_i32<F>(self, value: i32) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_i32(value) + .map(TagOrContent::Content) + } + + fn visit_i64<F>(self, value: i64) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_i64(value) + .map(TagOrContent::Content) + } + + fn visit_u8<F>(self, value: u8) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_u8(value) + .map(TagOrContent::Content) + } + + fn visit_u16<F>(self, value: u16) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_u16(value) + .map(TagOrContent::Content) + } + + fn visit_u32<F>(self, value: u32) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_u32(value) + .map(TagOrContent::Content) + } + + fn visit_u64<F>(self, value: u64) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_u64(value) + .map(TagOrContent::Content) + } + + fn visit_f32<F>(self, value: f32) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_f32(value) + .map(TagOrContent::Content) + } + + fn visit_f64<F>(self, value: f64) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_f64(value) + .map(TagOrContent::Content) + } + + fn visit_char<F>(self, value: char) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_char(value) + .map(TagOrContent::Content) + } + + fn visit_str<F>(self, value: &str) -> Result<Self::Value, F> + where + F: de::Error, + { + if value == self.name { + Ok(TagOrContent::Tag) + } else { + ContentVisitor::new() + .visit_str(value) + .map(TagOrContent::Content) + } + } + + fn visit_borrowed_str<F>(self, value: &'de str) -> Result<Self::Value, F> + where + F: de::Error, + { + if value == self.name { + Ok(TagOrContent::Tag) + } else { + ContentVisitor::new() + .visit_borrowed_str(value) + .map(TagOrContent::Content) + } + } + + fn visit_string<F>(self, value: String) -> Result<Self::Value, F> + where + F: de::Error, + { + if value == self.name { + Ok(TagOrContent::Tag) + } else { + ContentVisitor::new() + .visit_string(value) + .map(TagOrContent::Content) + } + } + + fn visit_bytes<F>(self, value: &[u8]) -> Result<Self::Value, F> + where + F: de::Error, + { + if value == self.name.as_bytes() { + Ok(TagOrContent::Tag) + } else { + ContentVisitor::new() + .visit_bytes(value) + .map(TagOrContent::Content) + } + } + + fn visit_borrowed_bytes<F>(self, value: &'de [u8]) -> Result<Self::Value, F> + where + F: de::Error, + { + if value == self.name.as_bytes() { + Ok(TagOrContent::Tag) + } else { + ContentVisitor::new() + .visit_borrowed_bytes(value) + .map(TagOrContent::Content) + } + } + + fn visit_byte_buf<F>(self, value: Vec<u8>) -> Result<Self::Value, F> + where + F: de::Error, + { + if value == self.name.as_bytes() { + Ok(TagOrContent::Tag) + } else { + ContentVisitor::new() + .visit_byte_buf(value) + .map(TagOrContent::Content) + } + } + + fn visit_unit<F>(self) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_unit() + .map(TagOrContent::Content) + } + + fn visit_none<F>(self) -> Result<Self::Value, F> + where + F: de::Error, + { + ContentVisitor::new() + .visit_none() + .map(TagOrContent::Content) + } + + fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + ContentVisitor::new() + .visit_some(deserializer) + .map(TagOrContent::Content) + } + + fn visit_newtype_struct<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + ContentVisitor::new() + .visit_newtype_struct(deserializer) + .map(TagOrContent::Content) + } + + fn visit_seq<V>(self, visitor: V) -> Result<Self::Value, V::Error> + where + V: SeqAccess<'de>, + { + ContentVisitor::new() + .visit_seq(visitor) + .map(TagOrContent::Content) + } + + fn visit_map<V>(self, visitor: V) -> Result<Self::Value, V::Error> + where + V: MapAccess<'de>, + { + ContentVisitor::new() + .visit_map(visitor) + .map(TagOrContent::Content) + } + + fn visit_enum<V>(self, visitor: V) -> Result<Self::Value, V::Error> + where + V: EnumAccess<'de>, + { + ContentVisitor::new() + .visit_enum(visitor) + .map(TagOrContent::Content) + } + } + + /// Used by generated code to deserialize an internally tagged enum. + /// + /// Not public API. + pub struct TaggedContent<'de, T> { + pub tag: T, + pub content: Content<'de>, + } + + /// Not public API. + pub struct TaggedContentVisitor<'de, T> { + tag_name: &'static str, + value: PhantomData<TaggedContent<'de, T>>, + } + + impl<'de, T> TaggedContentVisitor<'de, T> { + /// Visitor for the content of an internally tagged enum with the given tag + /// name. + pub fn new(name: &'static str) -> Self { + TaggedContentVisitor { + tag_name: name, + value: PhantomData, + } + } + } + + impl<'de, T> DeserializeSeed<'de> for TaggedContentVisitor<'de, T> + where + T: Deserialize<'de>, + { + type Value = TaggedContent<'de, T>; + + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + // Internally tagged enums are only supported in self-describing + // formats. + deserializer.deserialize_any(self) + } + } + + impl<'de, T> Visitor<'de> for TaggedContentVisitor<'de, T> + where + T: Deserialize<'de>, + { + type Value = TaggedContent<'de, T>; + + fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt.write_str("internally tagged enum") + } + + fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error> + where + S: SeqAccess<'de>, + { + let tag = match try!(seq.next_element()) { + Some(tag) => tag, + None => { + return Err(de::Error::missing_field(self.tag_name)); + } + }; + let rest = de::value::SeqAccessDeserializer::new(seq); + Ok(TaggedContent { + tag: tag, + content: try!(Content::deserialize(rest)), + }) + } + + fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error> + where + M: MapAccess<'de>, + { + let mut tag = None; + let mut vec = Vec::with_capacity(size_hint::cautious(map.size_hint())); + while let Some(k) = try!(map.next_key_seed(TagOrContentVisitor::new(self.tag_name))) { + match k { + TagOrContent::Tag => { + if tag.is_some() { + return Err(de::Error::duplicate_field(self.tag_name)); + } + tag = Some(try!(map.next_value())); + } + TagOrContent::Content(k) => { + let v = try!(map.next_value()); + vec.push((k, v)); + } + } + } + match tag { + None => Err(de::Error::missing_field(self.tag_name)), + Some(tag) => Ok(TaggedContent { + tag: tag, + content: Content::Map(vec), + }), + } + } + } + + /// Used by generated code to deserialize an adjacently tagged enum. + /// + /// Not public API. + pub enum TagOrContentField { + Tag, + Content, + } + + /// Not public API. + pub struct TagOrContentFieldVisitor { + pub tag: &'static str, + pub content: &'static str, + } + + impl<'de> DeserializeSeed<'de> for TagOrContentFieldVisitor { + type Value = TagOrContentField; + + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_str(self) + } + } + + impl<'de> Visitor<'de> for TagOrContentFieldVisitor { + type Value = TagOrContentField; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "{:?} or {:?}", self.tag, self.content) + } + + fn visit_str<E>(self, field: &str) -> Result<Self::Value, E> + where + E: de::Error, + { + if field == self.tag { + Ok(TagOrContentField::Tag) + } else if field == self.content { + Ok(TagOrContentField::Content) + } else { + Err(de::Error::invalid_value(Unexpected::Str(field), &self)) + } + } + } + + /// Used by generated code to deserialize an adjacently tagged enum when + /// ignoring unrelated fields is allowed. + /// + /// Not public API. + pub enum TagContentOtherField { + Tag, + Content, + Other, + } + + /// Not public API. + pub struct TagContentOtherFieldVisitor { + pub tag: &'static str, + pub content: &'static str, + } + + impl<'de> DeserializeSeed<'de> for TagContentOtherFieldVisitor { + type Value = TagContentOtherField; + + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + deserializer.deserialize_str(self) + } + } + + impl<'de> Visitor<'de> for TagContentOtherFieldVisitor { + type Value = TagContentOtherField; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!( + formatter, + "{:?}, {:?}, or other ignored fields", + self.tag, self.content + ) + } + + fn visit_str<E>(self, field: &str) -> Result<Self::Value, E> + where + E: de::Error, + { + if field == self.tag { + Ok(TagContentOtherField::Tag) + } else if field == self.content { + Ok(TagContentOtherField::Content) + } else { + Ok(TagContentOtherField::Other) + } + } + } + + /// Not public API + pub struct ContentDeserializer<'de, E> { + content: Content<'de>, + err: PhantomData<E>, + } + + /// Used when deserializing an internally tagged enum because the content will + /// be used exactly once. + impl<'de, E> Deserializer<'de> for ContentDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + match self.content { + Content::Bool(v) => visitor.visit_bool(v), + Content::U8(v) => visitor.visit_u8(v), + Content::U16(v) => visitor.visit_u16(v), + Content::U32(v) => visitor.visit_u32(v), + Content::U64(v) => visitor.visit_u64(v), + Content::I8(v) => visitor.visit_i8(v), + Content::I16(v) => visitor.visit_i16(v), + Content::I32(v) => visitor.visit_i32(v), + Content::I64(v) => visitor.visit_i64(v), + Content::F32(v) => visitor.visit_f32(v), + Content::F64(v) => visitor.visit_f64(v), + Content::Char(v) => visitor.visit_char(v), + Content::String(v) => visitor.visit_string(v), + Content::Str(v) => visitor.visit_borrowed_str(v), + Content::ByteBuf(v) => visitor.visit_byte_buf(v), + Content::Bytes(v) => visitor.visit_borrowed_bytes(v), + Content::Unit => visitor.visit_unit(), + Content::None => visitor.visit_none(), + Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)), + Content::Newtype(v) => visitor.visit_newtype_struct(ContentDeserializer::new(*v)), + Content::Seq(v) => { + let seq = v.into_iter().map(ContentDeserializer::new); + let mut seq_visitor = de::value::SeqDeserializer::new(seq); + let value = try!(visitor.visit_seq(&mut seq_visitor)); + try!(seq_visitor.end()); + Ok(value) + } + Content::Map(v) => { + let map = v.into_iter() + .map(|(k, v)| (ContentDeserializer::new(k), ContentDeserializer::new(v))); + let mut map_visitor = de::value::MapDeserializer::new(map); + let value = try!(visitor.visit_map(&mut map_visitor)); + try!(map_visitor.end()); + Ok(value) + } + } + } + + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + match self.content { + Content::None => visitor.visit_none(), + Content::Some(v) => visitor.visit_some(ContentDeserializer::new(*v)), + Content::Unit => visitor.visit_unit(), + _ => visitor.visit_some(self), + } + } + + fn deserialize_newtype_struct<V>( + self, + _name: &str, + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_enum<V>( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + let (variant, value) = match self.content { + Content::Map(value) => { + let mut iter = value.into_iter(); + let (variant, value) = match iter.next() { + Some(v) => v, + None => { + return Err(de::Error::invalid_value( + de::Unexpected::Map, + &"map with a single key", + )); + } + }; + // enums are encoded in json as maps with a single key:value pair + if iter.next().is_some() { + return Err(de::Error::invalid_value( + de::Unexpected::Map, + &"map with a single key", + )); + } + (variant, Some(value)) + } + s @ Content::String(_) | s @ Content::Str(_) => (s, None), + other => { + return Err(de::Error::invalid_type( + other.unexpected(), + &"string or map", + )); + } + }; + + visitor.visit_enum(EnumDeserializer::new(variant, value)) + } + + fn deserialize_unit_struct<V>( + self, + _name: &'static str, + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + match self.content { + // As a special case, allow deserializing untagged newtype + // variant containing unit struct. + // + // #[derive(Deserialize)] + // struct Info; + // + // #[derive(Deserialize)] + // #[serde(tag = "topic")] + // enum Message { + // Info(Info), + // } + // + // We want {"topic":"Info"} to deserialize even though + // ordinarily unit structs do not deserialize from empty map. + Content::Map(ref v) if v.is_empty() => visitor.visit_unit(), + _ => self.deserialize_any(visitor), + } + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf unit seq tuple tuple_struct map struct identifier + ignored_any + } + } + + impl<'de, E> ContentDeserializer<'de, E> { + /// private API, don't use + pub fn new(content: Content<'de>) -> Self { + ContentDeserializer { + content: content, + err: PhantomData, + } + } + } + + pub struct EnumDeserializer<'de, E> + where + E: de::Error, + { + variant: Content<'de>, + value: Option<Content<'de>>, + err: PhantomData<E>, + } + + impl<'de, E> EnumDeserializer<'de, E> + where + E: de::Error, + { + pub fn new(variant: Content<'de>, value: Option<Content<'de>>) -> EnumDeserializer<'de, E> { + EnumDeserializer { + variant: variant, + value: value, + err: PhantomData, + } + } + } + + impl<'de, E> de::EnumAccess<'de> for EnumDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + type Variant = VariantDeserializer<'de, Self::Error>; + + fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), E> + where + V: de::DeserializeSeed<'de>, + { + let visitor = VariantDeserializer { + value: self.value, + err: PhantomData, + }; + seed.deserialize(ContentDeserializer::new(self.variant)) + .map(|v| (v, visitor)) + } + } + + pub struct VariantDeserializer<'de, E> + where + E: de::Error, + { + value: Option<Content<'de>>, + err: PhantomData<E>, + } + + impl<'de, E> de::VariantAccess<'de> for VariantDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + fn unit_variant(self) -> Result<(), E> { + match self.value { + Some(value) => de::Deserialize::deserialize(ContentDeserializer::new(value)), + None => Ok(()), + } + } + + fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E> + where + T: de::DeserializeSeed<'de>, + { + match self.value { + Some(value) => seed.deserialize(ContentDeserializer::new(value)), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"newtype variant", + )), + } + } + + fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + match self.value { + Some(Content::Seq(v)) => { + de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type( + other.unexpected(), + &"tuple variant", + )), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"tuple variant", + )), + } + } + + fn struct_variant<V>( + self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + match self.value { + Some(Content::Map(v)) => { + de::Deserializer::deserialize_any(MapDeserializer::new(v), visitor) + } + Some(Content::Seq(v)) => { + de::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type( + other.unexpected(), + &"struct variant", + )), + _ => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"struct variant", + )), + } + } + } + + struct SeqDeserializer<'de, E> + where + E: de::Error, + { + iter: <Vec<Content<'de>> as IntoIterator>::IntoIter, + err: PhantomData<E>, + } + + impl<'de, E> SeqDeserializer<'de, E> + where + E: de::Error, + { + fn new(vec: Vec<Content<'de>>) -> Self { + SeqDeserializer { + iter: vec.into_iter(), + err: PhantomData, + } + } + } + + impl<'de, E> de::Deserializer<'de> for SeqDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + #[inline] + fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + let len = self.iter.len(); + if len == 0 { + visitor.visit_unit() + } else { + let ret = try!(visitor.visit_seq(&mut self)); + let remaining = self.iter.len(); + if remaining == 0 { + Ok(ret) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in array")) + } + } + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } + } + + impl<'de, E> de::SeqAccess<'de> for SeqDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.iter.next() { + Some(value) => seed.deserialize(ContentDeserializer::new(value)).map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> Option<usize> { + size_hint::from_bounds(&self.iter) + } + } + + struct MapDeserializer<'de, E> + where + E: de::Error, + { + iter: <Vec<(Content<'de>, Content<'de>)> as IntoIterator>::IntoIter, + value: Option<Content<'de>>, + err: PhantomData<E>, + } + + impl<'de, E> MapDeserializer<'de, E> + where + E: de::Error, + { + fn new(map: Vec<(Content<'de>, Content<'de>)>) -> Self { + MapDeserializer { + iter: map.into_iter(), + value: None, + err: PhantomData, + } + } + } + + impl<'de, E> de::MapAccess<'de> for MapDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.iter.next() { + Some((key, value)) => { + self.value = Some(value); + seed.deserialize(ContentDeserializer::new(key)).map(Some) + } + None => Ok(None), + } + } + + fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.value.take() { + Some(value) => seed.deserialize(ContentDeserializer::new(value)), + None => Err(de::Error::custom("value is missing")), + } + } + + fn size_hint(&self) -> Option<usize> { + size_hint::from_bounds(&self.iter) + } + } + + impl<'de, E> de::Deserializer<'de> for MapDeserializer<'de, E> + where + E: de::Error, + { + type Error = E; + + #[inline] + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.visit_map(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } + } + + /// Not public API. + pub struct ContentRefDeserializer<'a, 'de: 'a, E> { + content: &'a Content<'de>, + err: PhantomData<E>, + } + + /// Used when deserializing an untagged enum because the content may need to be + /// used more than once. + impl<'de, 'a, E> Deserializer<'de> for ContentRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Error = E; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, E> + where + V: Visitor<'de>, + { + match *self.content { + Content::Bool(v) => visitor.visit_bool(v), + Content::U8(v) => visitor.visit_u8(v), + Content::U16(v) => visitor.visit_u16(v), + Content::U32(v) => visitor.visit_u32(v), + Content::U64(v) => visitor.visit_u64(v), + Content::I8(v) => visitor.visit_i8(v), + Content::I16(v) => visitor.visit_i16(v), + Content::I32(v) => visitor.visit_i32(v), + Content::I64(v) => visitor.visit_i64(v), + Content::F32(v) => visitor.visit_f32(v), + Content::F64(v) => visitor.visit_f64(v), + Content::Char(v) => visitor.visit_char(v), + Content::String(ref v) => visitor.visit_str(v), + Content::Str(v) => visitor.visit_borrowed_str(v), + Content::ByteBuf(ref v) => visitor.visit_bytes(v), + Content::Bytes(v) => visitor.visit_borrowed_bytes(v), + Content::Unit => visitor.visit_unit(), + Content::None => visitor.visit_none(), + Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), + Content::Newtype(ref v) => { + visitor.visit_newtype_struct(ContentRefDeserializer::new(v)) + } + Content::Seq(ref v) => { + let seq = v.into_iter().map(ContentRefDeserializer::new); + let mut seq_visitor = de::value::SeqDeserializer::new(seq); + let value = try!(visitor.visit_seq(&mut seq_visitor)); + try!(seq_visitor.end()); + Ok(value) + } + Content::Map(ref v) => { + let map = v.into_iter().map(|&(ref k, ref v)| { + ( + ContentRefDeserializer::new(k), + ContentRefDeserializer::new(v), + ) + }); + let mut map_visitor = de::value::MapDeserializer::new(map); + let value = try!(visitor.visit_map(&mut map_visitor)); + try!(map_visitor.end()); + Ok(value) + } + } + } + + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, E> + where + V: Visitor<'de>, + { + match *self.content { + Content::None => visitor.visit_none(), + Content::Some(ref v) => visitor.visit_some(ContentRefDeserializer::new(v)), + Content::Unit => visitor.visit_unit(), + _ => visitor.visit_some(self), + } + } + + fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, E> + where + V: Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_enum<V>( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + let (variant, value) = match *self.content { + Content::Map(ref value) => { + let mut iter = value.into_iter(); + let &(ref variant, ref value) = match iter.next() { + Some(v) => v, + None => { + return Err(de::Error::invalid_value( + de::Unexpected::Map, + &"map with a single key", + )); + } + }; + // enums are encoded in json as maps with a single key:value pair + if iter.next().is_some() { + return Err(de::Error::invalid_value( + de::Unexpected::Map, + &"map with a single key", + )); + } + (variant, Some(value)) + } + ref s @ Content::String(_) | ref s @ Content::Str(_) => (s, None), + ref other => { + return Err(de::Error::invalid_type( + other.unexpected(), + &"string or map", + )); + } + }; + + visitor.visit_enum(EnumRefDeserializer { + variant: variant, + value: value, + err: PhantomData, + }) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf unit unit_struct seq tuple tuple_struct map struct + identifier ignored_any + } + } + + impl<'a, 'de, E> ContentRefDeserializer<'a, 'de, E> { + /// private API, don't use + pub fn new(content: &'a Content<'de>) -> Self { + ContentRefDeserializer { + content: content, + err: PhantomData, + } + } + } + + struct EnumRefDeserializer<'a, 'de: 'a, E> + where + E: de::Error, + { + variant: &'a Content<'de>, + value: Option<&'a Content<'de>>, + err: PhantomData<E>, + } + + impl<'de, 'a, E> de::EnumAccess<'de> for EnumRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Error = E; + type Variant = VariantRefDeserializer<'a, 'de, Self::Error>; + + fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + where + V: de::DeserializeSeed<'de>, + { + let visitor = VariantRefDeserializer { + value: self.value, + err: PhantomData, + }; + seed.deserialize(ContentRefDeserializer::new(self.variant)) + .map(|v| (v, visitor)) + } + } + + struct VariantRefDeserializer<'a, 'de: 'a, E> + where + E: de::Error, + { + value: Option<&'a Content<'de>>, + err: PhantomData<E>, + } + + impl<'de, 'a, E> de::VariantAccess<'de> for VariantRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Error = E; + + fn unit_variant(self) -> Result<(), E> { + match self.value { + Some(value) => de::Deserialize::deserialize(ContentRefDeserializer::new(value)), + None => Ok(()), + } + } + + fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, E> + where + T: de::DeserializeSeed<'de>, + { + match self.value { + Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"newtype variant", + )), + } + } + + fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + match self.value { + Some(&Content::Seq(ref v)) => { + de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type( + other.unexpected(), + &"tuple variant", + )), + None => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"tuple variant", + )), + } + } + + fn struct_variant<V>( + self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + match self.value { + Some(&Content::Map(ref v)) => { + de::Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor) + } + Some(&Content::Seq(ref v)) => { + de::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor) + } + Some(other) => Err(de::Error::invalid_type( + other.unexpected(), + &"struct variant", + )), + _ => Err(de::Error::invalid_type( + de::Unexpected::UnitVariant, + &"struct variant", + )), + } + } + } + + struct SeqRefDeserializer<'a, 'de: 'a, E> + where + E: de::Error, + { + iter: <&'a [Content<'de>] as IntoIterator>::IntoIter, + err: PhantomData<E>, + } + + impl<'a, 'de, E> SeqRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + fn new(vec: &'a [Content<'de>]) -> Self { + SeqRefDeserializer { + iter: vec.into_iter(), + err: PhantomData, + } + } + } + + impl<'de, 'a, E> de::Deserializer<'de> for SeqRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Error = E; + + #[inline] + fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + let len = self.iter.len(); + if len == 0 { + visitor.visit_unit() + } else { + let ret = try!(visitor.visit_seq(&mut self)); + let remaining = self.iter.len(); + if remaining == 0 { + Ok(ret) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in array")) + } + } + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } + } + + impl<'de, 'a, E> de::SeqAccess<'de> for SeqRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Error = E; + + fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.iter.next() { + Some(value) => seed.deserialize(ContentRefDeserializer::new(value)) + .map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> Option<usize> { + size_hint::from_bounds(&self.iter) + } + } + + struct MapRefDeserializer<'a, 'de: 'a, E> + where + E: de::Error, + { + iter: <&'a [(Content<'de>, Content<'de>)] as IntoIterator>::IntoIter, + value: Option<&'a Content<'de>>, + err: PhantomData<E>, + } + + impl<'a, 'de, E> MapRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + fn new(map: &'a [(Content<'de>, Content<'de>)]) -> Self { + MapRefDeserializer { + iter: map.into_iter(), + value: None, + err: PhantomData, + } + } + } + + impl<'de, 'a, E> de::MapAccess<'de> for MapRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Error = E; + + fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.iter.next() { + Some(&(ref key, ref value)) => { + self.value = Some(value); + seed.deserialize(ContentRefDeserializer::new(key)).map(Some) + } + None => Ok(None), + } + } + + fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error> + where + T: de::DeserializeSeed<'de>, + { + match self.value.take() { + Some(value) => seed.deserialize(ContentRefDeserializer::new(value)), + None => Err(de::Error::custom("value is missing")), + } + } + + fn size_hint(&self) -> Option<usize> { + size_hint::from_bounds(&self.iter) + } + } + + impl<'de, 'a, E> de::Deserializer<'de> for MapRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Error = E; + + #[inline] + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: de::Visitor<'de>, + { + visitor.visit_map(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } + } + + impl<'de, E> de::IntoDeserializer<'de, E> for ContentDeserializer<'de, E> + where + E: de::Error, + { + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } + } + + impl<'de, 'a, E> de::IntoDeserializer<'de, E> for ContentRefDeserializer<'a, 'de, E> + where + E: de::Error, + { + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } + } + + /// Visitor for deserializing an internally tagged unit variant. + /// + /// Not public API. + pub struct InternallyTaggedUnitVisitor<'a> { + type_name: &'a str, + variant_name: &'a str, + } + + impl<'a> InternallyTaggedUnitVisitor<'a> { + /// Not public API. + pub fn new(type_name: &'a str, variant_name: &'a str) -> Self { + InternallyTaggedUnitVisitor { + type_name: type_name, + variant_name: variant_name, + } + } + } + + impl<'de, 'a> Visitor<'de> for InternallyTaggedUnitVisitor<'a> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!( + formatter, + "unit variant {}::{}", + self.type_name, self.variant_name + ) + } + + fn visit_seq<S>(self, _: S) -> Result<(), S::Error> + where + S: SeqAccess<'de>, + { + Ok(()) + } + + fn visit_map<M>(self, _: M) -> Result<(), M::Error> + where + M: MapAccess<'de>, + { + Ok(()) + } + } + + /// Visitor for deserializing an untagged unit variant. + /// + /// Not public API. + pub struct UntaggedUnitVisitor<'a> { + type_name: &'a str, + variant_name: &'a str, + } + + impl<'a> UntaggedUnitVisitor<'a> { + /// Not public API. + pub fn new(type_name: &'a str, variant_name: &'a str) -> Self { + UntaggedUnitVisitor { + type_name: type_name, + variant_name: variant_name, + } + } + } + + impl<'de, 'a> Visitor<'de> for UntaggedUnitVisitor<'a> { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!( + formatter, + "unit variant {}::{}", + self.type_name, self.variant_name + ) + } + + fn visit_unit<E>(self) -> Result<(), E> + where + E: de::Error, + { + Ok(()) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Like `IntoDeserializer` but also implemented for `&[u8]`. This is used for +// the newtype fallthrough case of `field_identifier`. +// +// #[derive(Deserialize)] +// #[serde(field_identifier)] +// enum F { +// A, +// B, +// Other(String), // deserialized using IdentifierDeserializer +// } +pub trait IdentifierDeserializer<'de, E: Error> { + type Deserializer: Deserializer<'de, Error = E>; + + fn from(self) -> Self::Deserializer; +} + +impl<'de, E> IdentifierDeserializer<'de, E> for u32 +where + E: Error, +{ + type Deserializer = <u32 as IntoDeserializer<'de, E>>::Deserializer; + + fn from(self) -> Self::Deserializer { + self.into_deserializer() + } +} + +pub struct StrDeserializer<'a, E> { + value: &'a str, + marker: PhantomData<E>, +} + +impl<'a, E> IdentifierDeserializer<'a, E> for &'a str +where + E: Error, +{ + type Deserializer = StrDeserializer<'a, E>; + + fn from(self) -> Self::Deserializer { + StrDeserializer { + value: self, + marker: PhantomData, + } + } +} + +impl<'de, 'a, E> Deserializer<'de> for StrDeserializer<'a, E> +where + E: Error, +{ + type Error = E; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + visitor.visit_str(self.value) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier ignored_any + } +} + +pub struct BytesDeserializer<'a, E> { + value: &'a [u8], + marker: PhantomData<E>, +} + +impl<'a, E> IdentifierDeserializer<'a, E> for &'a [u8] +where + E: Error, +{ + type Deserializer = BytesDeserializer<'a, E>; + + fn from(self) -> Self::Deserializer { + BytesDeserializer { + value: self, + marker: PhantomData, + } + } +} + +impl<'de, 'a, E> Deserializer<'de> for BytesDeserializer<'a, E> +where + E: Error, +{ + type Error = E; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + visitor.visit_bytes(self.value) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct + map struct enum identifier ignored_any + } +} + +/// A DeserializeSeed helper for implementing deserialize_in_place Visitors. +/// +/// Wraps a mutable reference and calls deserialize_in_place on it. +pub struct InPlaceSeed<'a, T: 'a>(pub &'a mut T); + +impl<'a, 'de, T> DeserializeSeed<'de> for InPlaceSeed<'a, T> +where + T: Deserialize<'de>, +{ + type Value = (); + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: Deserializer<'de>, + { + T::deserialize_in_place(deserializer, self.0) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub struct FlatMapDeserializer<'a, 'de: 'a, E>( + pub &'a mut Vec<Option<(Content<'de>, Content<'de>)>>, + pub PhantomData<E>, +); + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, 'de, E> Deserializer<'de> for FlatMapDeserializer<'a, 'de, E> +where + E: Error, +{ + type Error = E; + + fn deserialize_any<V>(self, _: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + Err(Error::custom("can only flatten structs and maps")) + } + + fn deserialize_enum<V>( + self, + name: &'static str, + variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + for item in self.0.iter_mut() { + // items in the vector are nulled out when used. So we can only use + // an item if it's still filled in and if the field is one we care + // about. + let use_item = match *item { + None => false, + Some((ref c, _)) => c.as_str().map_or(false, |x| variants.contains(&x)), + }; + + if use_item { + let (key, value) = item.take().unwrap(); + return visitor.visit_enum(EnumDeserializer::new(key, Some(value))); + } + } + + Err(Error::custom(format_args!( + "no variant of enum {} not found in flattened data", + name + ))) + } + + fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + visitor.visit_map(FlatMapAccess::new(self.0.iter_mut(), None)) + } + + fn deserialize_struct<V>( + self, + _: &'static str, + fields: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + visitor.visit_map(FlatMapAccess::new(self.0.iter_mut(), Some(fields))) + } + + fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct seq tuple tuple_struct identifier + ignored_any + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub struct FlatMapAccess<'a, 'de: 'a, E> { + iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>, + pending_content: Option<Content<'de>>, + fields: Option<&'static [&'static str]>, + _marker: PhantomData<E>, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, 'de, E> FlatMapAccess<'a, 'de, E> { + fn new( + iter: slice::IterMut<'a, Option<(Content<'de>, Content<'de>)>>, + fields: Option<&'static [&'static str]>, + ) -> FlatMapAccess<'a, 'de, E> { + FlatMapAccess { + iter: iter, + pending_content: None, + fields: fields, + _marker: PhantomData, + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, 'de, E> MapAccess<'de> for FlatMapAccess<'a, 'de, E> +where + E: Error, +{ + type Error = E; + + fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Self::Error> + where + T: DeserializeSeed<'de>, + { + while let Some(item) = self.iter.next() { + // items in the vector are nulled out when used. So we can only use + // an item if it's still filled in and if the field is one we care + // about. In case we do not know which fields we want, we take them all. + let use_item = match *item { + None => false, + Some((ref c, _)) => { + c.as_str() + .map_or(self.fields.is_none(), |key| match self.fields { + None => true, + Some(fields) if fields.contains(&key) => true, + _ => false, + }) + } + }; + + if use_item { + let (key, content) = item.take().unwrap(); + self.pending_content = Some(content); + return seed.deserialize(ContentDeserializer::new(key)).map(Some); + } + } + Ok(None) + } + + fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Self::Error> + where + T: DeserializeSeed<'de>, + { + match self.pending_content.take() { + Some(value) => seed.deserialize(ContentDeserializer::new(value)), + None => Err(Error::custom("value is missing")), + } + } +} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/private/macros.rs cargo-0.26.0/vendor/serde-1.0.37/src/private/macros.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/private/macros.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/private/macros.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,148 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[doc(hidden)] +#[macro_export] +macro_rules! __private_serialize { + () => { + trait Serialize { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: $crate::Serializer; + } + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __private_deserialize { + () => { + trait Deserialize<'de>: Sized { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: $crate::Deserializer<'de>; + } + }; +} + +/// Used only by Serde doc tests. Not public API. +#[doc(hidden)] +#[macro_export] +macro_rules! __serialize_unimplemented { + ($($func:ident)*) => { + $( + __serialize_unimplemented_helper!($func); + )* + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __serialize_unimplemented_method { + ($func:ident $(<$t:ident>)* ($($arg:ty),*) -> $ret:ident) => { + fn $func $(<$t: ?Sized + $crate::Serialize>)* (self $(, _: $arg)*) -> $crate::export::Result<Self::$ret, Self::Error> { + unimplemented!() + } + }; +} + +#[doc(hidden)] +#[macro_export] +macro_rules! __serialize_unimplemented_helper { + (bool) => { + __serialize_unimplemented_method!(serialize_bool(bool) -> Ok); + }; + (i8) => { + __serialize_unimplemented_method!(serialize_i8(i8) -> Ok); + }; + (i16) => { + __serialize_unimplemented_method!(serialize_i16(i16) -> Ok); + }; + (i32) => { + __serialize_unimplemented_method!(serialize_i32(i32) -> Ok); + }; + (i64) => { + __serialize_unimplemented_method!(serialize_i64(i64) -> Ok); + }; + (u8) => { + __serialize_unimplemented_method!(serialize_u8(u8) -> Ok); + }; + (u16) => { + __serialize_unimplemented_method!(serialize_u16(u16) -> Ok); + }; + (u32) => { + __serialize_unimplemented_method!(serialize_u32(u32) -> Ok); + }; + (u64) => { + __serialize_unimplemented_method!(serialize_u64(u64) -> Ok); + }; + (f32) => { + __serialize_unimplemented_method!(serialize_f32(f32) -> Ok); + }; + (f64) => { + __serialize_unimplemented_method!(serialize_f64(f64) -> Ok); + }; + (char) => { + __serialize_unimplemented_method!(serialize_char(char) -> Ok); + }; + (str) => { + __serialize_unimplemented_method!(serialize_str(&str) -> Ok); + }; + (bytes) => { + __serialize_unimplemented_method!(serialize_bytes(&[u8]) -> Ok); + }; + (none) => { + __serialize_unimplemented_method!(serialize_none() -> Ok); + }; + (some) => { + __serialize_unimplemented_method!(serialize_some<T>(&T) -> Ok); + }; + (unit) => { + __serialize_unimplemented_method!(serialize_unit() -> Ok); + }; + (unit_struct) => { + __serialize_unimplemented_method!(serialize_unit_struct(&str) -> Ok); + }; + (unit_variant) => { + __serialize_unimplemented_method!(serialize_unit_variant(&str, u32, &str) -> Ok); + }; + (newtype_struct) => { + __serialize_unimplemented_method!(serialize_newtype_struct<T>(&str, &T) -> Ok); + }; + (newtype_variant) => { + __serialize_unimplemented_method!(serialize_newtype_variant<T>(&str, u32, &str, &T) -> Ok); + }; + (seq) => { + type SerializeSeq = $crate::ser::Impossible<Self::Ok, Self::Error>; + __serialize_unimplemented_method!(serialize_seq(Option<usize>) -> SerializeSeq); + }; + (tuple) => { + type SerializeTuple = $crate::ser::Impossible<Self::Ok, Self::Error>; + __serialize_unimplemented_method!(serialize_tuple(usize) -> SerializeTuple); + }; + (tuple_struct) => { + type SerializeTupleStruct = $crate::ser::Impossible<Self::Ok, Self::Error>; + __serialize_unimplemented_method!(serialize_tuple_struct(&str, usize) -> SerializeTupleStruct); + }; + (tuple_variant) => { + type SerializeTupleVariant = $crate::ser::Impossible<Self::Ok, Self::Error>; + __serialize_unimplemented_method!(serialize_tuple_variant(&str, u32, &str, usize) -> SerializeTupleVariant); + }; + (map) => { + type SerializeMap = $crate::ser::Impossible<Self::Ok, Self::Error>; + __serialize_unimplemented_method!(serialize_map(Option<usize>) -> SerializeMap); + }; + (struct) => { + type SerializeStruct = $crate::ser::Impossible<Self::Ok, Self::Error>; + __serialize_unimplemented_method!(serialize_struct(&str, usize) -> SerializeStruct); + }; + (struct_variant) => { + type SerializeStructVariant = $crate::ser::Impossible<Self::Ok, Self::Error>; + __serialize_unimplemented_method!(serialize_struct_variant(&str, u32, &str, usize) -> SerializeStructVariant); + }; +} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/private/mod.rs cargo-0.26.0/vendor/serde-1.0.37/src/private/mod.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/private/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/private/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,12 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +mod macros; + +pub mod de; +pub mod ser; diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/private/ser.rs cargo-0.26.0/vendor/serde-1.0.37/src/private/ser.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/private/ser.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/private/ser.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1335 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use lib::*; + +use ser::{self, Impossible, Serialize, SerializeMap, SerializeStruct, Serializer}; + +#[cfg(any(feature = "std", feature = "alloc"))] +use self::content::{Content, ContentSerializer, SerializeStructVariantAsMapValue, + SerializeTupleVariantAsMapValue}; + +/// Used to check that serde(getter) attributes return the expected type. +/// Not public API. +pub fn constrain<T: ?Sized>(t: &T) -> &T { + t +} + +/// Not public API. +pub fn serialize_tagged_newtype<S, T>( + serializer: S, + type_ident: &'static str, + variant_ident: &'static str, + tag: &'static str, + variant_name: &'static str, + value: &T, +) -> Result<S::Ok, S::Error> +where + S: Serializer, + T: Serialize, +{ + value.serialize(TaggedSerializer { + type_ident: type_ident, + variant_ident: variant_ident, + tag: tag, + variant_name: variant_name, + delegate: serializer, + }) +} + +struct TaggedSerializer<S> { + type_ident: &'static str, + variant_ident: &'static str, + tag: &'static str, + variant_name: &'static str, + delegate: S, +} + +enum Unsupported { + Boolean, + Integer, + Float, + Char, + String, + ByteArray, + Optional, + Unit, + #[cfg(any(feature = "std", feature = "alloc"))] + UnitStruct, + Sequence, + Tuple, + TupleStruct, + Enum, +} + +impl Display for Unsupported { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match *self { + Unsupported::Boolean => formatter.write_str("a boolean"), + Unsupported::Integer => formatter.write_str("an integer"), + Unsupported::Float => formatter.write_str("a float"), + Unsupported::Char => formatter.write_str("a char"), + Unsupported::String => formatter.write_str("a string"), + Unsupported::ByteArray => formatter.write_str("a byte array"), + Unsupported::Optional => formatter.write_str("an optional"), + Unsupported::Unit => formatter.write_str("unit"), + #[cfg(any(feature = "std", feature = "alloc"))] + Unsupported::UnitStruct => formatter.write_str("unit struct"), + Unsupported::Sequence => formatter.write_str("a sequence"), + Unsupported::Tuple => formatter.write_str("a tuple"), + Unsupported::TupleStruct => formatter.write_str("a tuple struct"), + Unsupported::Enum => formatter.write_str("an enum"), + } + } +} + +impl<S> TaggedSerializer<S> +where + S: Serializer, +{ + fn bad_type(self, what: Unsupported) -> S::Error { + ser::Error::custom(format_args!( + "cannot serialize tagged newtype variant {}::{} containing {}", + self.type_ident, self.variant_ident, what + )) + } +} + +impl<S> Serializer for TaggedSerializer<S> +where + S: Serializer, +{ + type Ok = S::Ok; + type Error = S::Error; + + type SerializeSeq = Impossible<S::Ok, S::Error>; + type SerializeTuple = Impossible<S::Ok, S::Error>; + type SerializeTupleStruct = Impossible<S::Ok, S::Error>; + type SerializeMap = S::SerializeMap; + type SerializeStruct = S::SerializeStruct; + + #[cfg(not(any(feature = "std", feature = "alloc")))] + type SerializeTupleVariant = Impossible<S::Ok, S::Error>; + #[cfg(any(feature = "std", feature = "alloc"))] + type SerializeTupleVariant = SerializeTupleVariantAsMapValue<S::SerializeMap>; + + #[cfg(not(any(feature = "std", feature = "alloc")))] + type SerializeStructVariant = Impossible<S::Ok, S::Error>; + #[cfg(any(feature = "std", feature = "alloc"))] + type SerializeStructVariant = SerializeStructVariantAsMapValue<S::SerializeMap>; + + fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Boolean)) + } + + fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Float)) + } + + fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Float)) + } + + fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Char)) + } + + fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::String)) + } + + fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::ByteArray)) + } + + fn serialize_none(self) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Optional)) + } + + fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error> + where + T: Serialize, + { + Err(self.bad_type(Unsupported::Optional)) + } + + fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Unit)) + } + + fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> { + let mut map = try!(self.delegate.serialize_map(Some(1))); + try!(map.serialize_entry(self.tag, self.variant_name)); + map.end() + } + + fn serialize_unit_variant( + self, + _: &'static str, + _: u32, + inner_variant: &'static str, + ) -> Result<Self::Ok, Self::Error> { + let mut map = try!(self.delegate.serialize_map(Some(2))); + try!(map.serialize_entry(self.tag, self.variant_name)); + try!(map.serialize_entry(inner_variant, &())); + map.end() + } + + fn serialize_newtype_struct<T: ?Sized>( + self, + _: &'static str, + value: &T, + ) -> Result<Self::Ok, Self::Error> + where + T: Serialize, + { + value.serialize(self) + } + + fn serialize_newtype_variant<T: ?Sized>( + self, + _: &'static str, + _: u32, + inner_variant: &'static str, + inner_value: &T, + ) -> Result<Self::Ok, Self::Error> + where + T: Serialize, + { + let mut map = try!(self.delegate.serialize_map(Some(2))); + try!(map.serialize_entry(self.tag, self.variant_name)); + try!(map.serialize_entry(inner_variant, inner_value)); + map.end() + } + + fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> { + Err(self.bad_type(Unsupported::Sequence)) + } + + fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> { + Err(self.bad_type(Unsupported::Tuple)) + } + + fn serialize_tuple_struct( + self, + _: &'static str, + _: usize, + ) -> Result<Self::SerializeTupleStruct, Self::Error> { + Err(self.bad_type(Unsupported::TupleStruct)) + } + + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result<Self::SerializeTupleVariant, Self::Error> { + // Lack of push-based serialization means we need to buffer the content + // of the tuple variant, so it requires std. + Err(self.bad_type(Unsupported::Enum)) + } + + #[cfg(any(feature = "std", feature = "alloc"))] + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + inner_variant: &'static str, + len: usize, + ) -> Result<Self::SerializeTupleVariant, Self::Error> { + let mut map = try!(self.delegate.serialize_map(Some(2))); + try!(map.serialize_entry(self.tag, self.variant_name)); + try!(map.serialize_key(inner_variant)); + Ok(SerializeTupleVariantAsMapValue::new( + map, + inner_variant, + len, + )) + } + + fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> { + let mut map = try!(self.delegate.serialize_map(len.map(|len| len + 1))); + try!(map.serialize_entry(self.tag, self.variant_name)); + Ok(map) + } + + fn serialize_struct( + self, + name: &'static str, + len: usize, + ) -> Result<Self::SerializeStruct, Self::Error> { + let mut state = try!(self.delegate.serialize_struct(name, len + 1)); + try!(state.serialize_field(self.tag, self.variant_name)); + Ok(state) + } + + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result<Self::SerializeStructVariant, Self::Error> { + // Lack of push-based serialization means we need to buffer the content + // of the struct variant, so it requires std. + Err(self.bad_type(Unsupported::Enum)) + } + + #[cfg(any(feature = "std", feature = "alloc"))] + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + inner_variant: &'static str, + len: usize, + ) -> Result<Self::SerializeStructVariant, Self::Error> { + let mut map = try!(self.delegate.serialize_map(Some(2))); + try!(map.serialize_entry(self.tag, self.variant_name)); + try!(map.serialize_key(inner_variant)); + Ok(SerializeStructVariantAsMapValue::new( + map, + inner_variant, + len, + )) + } + + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn collect_str<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error> + where + T: Display, + { + Err(self.bad_type(Unsupported::String)) + } +} + +/// Used only by Serde doc tests. Not public API. +#[doc(hidden)] +#[derive(Debug)] +pub struct Error; + +impl ser::Error for Error { + fn custom<T>(_: T) -> Self + where + T: Display, + { + unimplemented!() + } +} + +#[cfg(feature = "std")] +impl error::Error for Error { + fn description(&self) -> &str { + unimplemented!() + } +} + +impl Display for Error { + fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { + unimplemented!() + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +mod content { + use lib::*; + + use ser::{self, Serialize, Serializer}; + + pub struct SerializeTupleVariantAsMapValue<M> { + map: M, + name: &'static str, + fields: Vec<Content>, + } + + impl<M> SerializeTupleVariantAsMapValue<M> { + pub fn new(map: M, name: &'static str, len: usize) -> Self { + SerializeTupleVariantAsMapValue { + map: map, + name: name, + fields: Vec::with_capacity(len), + } + } + } + + impl<M> ser::SerializeTupleVariant for SerializeTupleVariantAsMapValue<M> + where + M: ser::SerializeMap, + { + type Ok = M::Ok; + type Error = M::Error; + + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), M::Error> + where + T: Serialize, + { + let value = try!(value.serialize(ContentSerializer::<M::Error>::new())); + self.fields.push(value); + Ok(()) + } + + fn end(mut self) -> Result<M::Ok, M::Error> { + try!( + self.map + .serialize_value(&Content::TupleStruct(self.name, self.fields)) + ); + self.map.end() + } + } + + pub struct SerializeStructVariantAsMapValue<M> { + map: M, + name: &'static str, + fields: Vec<(&'static str, Content)>, + } + + impl<M> SerializeStructVariantAsMapValue<M> { + pub fn new(map: M, name: &'static str, len: usize) -> Self { + SerializeStructVariantAsMapValue { + map: map, + name: name, + fields: Vec::with_capacity(len), + } + } + } + + impl<M> ser::SerializeStructVariant for SerializeStructVariantAsMapValue<M> + where + M: ser::SerializeMap, + { + type Ok = M::Ok; + type Error = M::Error; + + fn serialize_field<T: ?Sized>( + &mut self, + key: &'static str, + value: &T, + ) -> Result<(), M::Error> + where + T: Serialize, + { + let value = try!(value.serialize(ContentSerializer::<M::Error>::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(mut self) -> Result<M::Ok, M::Error> { + try!( + self.map + .serialize_value(&Content::Struct(self.name, self.fields)) + ); + self.map.end() + } + } + + #[derive(Debug)] + pub enum Content { + Bool(bool), + + U8(u8), + U16(u16), + U32(u32), + U64(u64), + + I8(i8), + I16(i16), + I32(i32), + I64(i64), + + F32(f32), + F64(f64), + + Char(char), + String(String), + Bytes(Vec<u8>), + + None, + Some(Box<Content>), + + Unit, + UnitStruct(&'static str), + UnitVariant(&'static str, u32, &'static str), + NewtypeStruct(&'static str, Box<Content>), + NewtypeVariant(&'static str, u32, &'static str, Box<Content>), + + Seq(Vec<Content>), + Tuple(Vec<Content>), + TupleStruct(&'static str, Vec<Content>), + TupleVariant(&'static str, u32, &'static str, Vec<Content>), + Map(Vec<(Content, Content)>), + Struct(&'static str, Vec<(&'static str, Content)>), + StructVariant( + &'static str, + u32, + &'static str, + Vec<(&'static str, Content)>, + ), + } + + impl Serialize for Content { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + match *self { + Content::Bool(b) => serializer.serialize_bool(b), + Content::U8(u) => serializer.serialize_u8(u), + Content::U16(u) => serializer.serialize_u16(u), + Content::U32(u) => serializer.serialize_u32(u), + Content::U64(u) => serializer.serialize_u64(u), + Content::I8(i) => serializer.serialize_i8(i), + Content::I16(i) => serializer.serialize_i16(i), + Content::I32(i) => serializer.serialize_i32(i), + Content::I64(i) => serializer.serialize_i64(i), + Content::F32(f) => serializer.serialize_f32(f), + Content::F64(f) => serializer.serialize_f64(f), + Content::Char(c) => serializer.serialize_char(c), + Content::String(ref s) => serializer.serialize_str(s), + Content::Bytes(ref b) => serializer.serialize_bytes(b), + Content::None => serializer.serialize_none(), + Content::Some(ref c) => serializer.serialize_some(&**c), + Content::Unit => serializer.serialize_unit(), + Content::UnitStruct(n) => serializer.serialize_unit_struct(n), + Content::UnitVariant(n, i, v) => serializer.serialize_unit_variant(n, i, v), + Content::NewtypeStruct(n, ref c) => serializer.serialize_newtype_struct(n, &**c), + Content::NewtypeVariant(n, i, v, ref c) => { + serializer.serialize_newtype_variant(n, i, v, &**c) + } + Content::Seq(ref elements) => elements.serialize(serializer), + Content::Tuple(ref elements) => { + use ser::SerializeTuple; + let mut tuple = try!(serializer.serialize_tuple(elements.len())); + for e in elements { + try!(tuple.serialize_element(e)); + } + tuple.end() + } + Content::TupleStruct(n, ref fields) => { + use ser::SerializeTupleStruct; + let mut ts = try!(serializer.serialize_tuple_struct(n, fields.len())); + for f in fields { + try!(ts.serialize_field(f)); + } + ts.end() + } + Content::TupleVariant(n, i, v, ref fields) => { + use ser::SerializeTupleVariant; + let mut tv = try!(serializer.serialize_tuple_variant(n, i, v, fields.len())); + for f in fields { + try!(tv.serialize_field(f)); + } + tv.end() + } + Content::Map(ref entries) => { + use ser::SerializeMap; + let mut map = try!(serializer.serialize_map(Some(entries.len()))); + for &(ref k, ref v) in entries { + try!(map.serialize_entry(k, v)); + } + map.end() + } + Content::Struct(n, ref fields) => { + use ser::SerializeStruct; + let mut s = try!(serializer.serialize_struct(n, fields.len())); + for &(k, ref v) in fields { + try!(s.serialize_field(k, v)); + } + s.end() + } + Content::StructVariant(n, i, v, ref fields) => { + use ser::SerializeStructVariant; + let mut sv = try!(serializer.serialize_struct_variant(n, i, v, fields.len())); + for &(k, ref v) in fields { + try!(sv.serialize_field(k, v)); + } + sv.end() + } + } + } + } + + pub struct ContentSerializer<E> { + error: PhantomData<E>, + } + + impl<E> ContentSerializer<E> { + pub fn new() -> Self { + ContentSerializer { error: PhantomData } + } + } + + impl<E> Serializer for ContentSerializer<E> + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + type SerializeSeq = SerializeSeq<E>; + type SerializeTuple = SerializeTuple<E>; + type SerializeTupleStruct = SerializeTupleStruct<E>; + type SerializeTupleVariant = SerializeTupleVariant<E>; + type SerializeMap = SerializeMap<E>; + type SerializeStruct = SerializeStruct<E>; + type SerializeStructVariant = SerializeStructVariant<E>; + + fn serialize_bool(self, v: bool) -> Result<Content, E> { + Ok(Content::Bool(v)) + } + + fn serialize_i8(self, v: i8) -> Result<Content, E> { + Ok(Content::I8(v)) + } + + fn serialize_i16(self, v: i16) -> Result<Content, E> { + Ok(Content::I16(v)) + } + + fn serialize_i32(self, v: i32) -> Result<Content, E> { + Ok(Content::I32(v)) + } + + fn serialize_i64(self, v: i64) -> Result<Content, E> { + Ok(Content::I64(v)) + } + + fn serialize_u8(self, v: u8) -> Result<Content, E> { + Ok(Content::U8(v)) + } + + fn serialize_u16(self, v: u16) -> Result<Content, E> { + Ok(Content::U16(v)) + } + + fn serialize_u32(self, v: u32) -> Result<Content, E> { + Ok(Content::U32(v)) + } + + fn serialize_u64(self, v: u64) -> Result<Content, E> { + Ok(Content::U64(v)) + } + + fn serialize_f32(self, v: f32) -> Result<Content, E> { + Ok(Content::F32(v)) + } + + fn serialize_f64(self, v: f64) -> Result<Content, E> { + Ok(Content::F64(v)) + } + + fn serialize_char(self, v: char) -> Result<Content, E> { + Ok(Content::Char(v)) + } + + fn serialize_str(self, value: &str) -> Result<Content, E> { + Ok(Content::String(value.to_owned())) + } + + fn serialize_bytes(self, value: &[u8]) -> Result<Content, E> { + Ok(Content::Bytes(value.to_owned())) + } + + fn serialize_none(self) -> Result<Content, E> { + Ok(Content::None) + } + + fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Content, E> + where + T: Serialize, + { + Ok(Content::Some(Box::new(try!(value.serialize(self))))) + } + + fn serialize_unit(self) -> Result<Content, E> { + Ok(Content::Unit) + } + + fn serialize_unit_struct(self, name: &'static str) -> Result<Content, E> { + Ok(Content::UnitStruct(name)) + } + + fn serialize_unit_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + ) -> Result<Content, E> { + Ok(Content::UnitVariant(name, variant_index, variant)) + } + + fn serialize_newtype_struct<T: ?Sized>( + self, + name: &'static str, + value: &T, + ) -> Result<Content, E> + where + T: Serialize, + { + Ok(Content::NewtypeStruct( + name, + Box::new(try!(value.serialize(self))), + )) + } + + fn serialize_newtype_variant<T: ?Sized>( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result<Content, E> + where + T: Serialize, + { + Ok(Content::NewtypeVariant( + name, + variant_index, + variant, + Box::new(try!(value.serialize(self))), + )) + } + + fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, E> { + Ok(SerializeSeq { + elements: Vec::with_capacity(len.unwrap_or(0)), + error: PhantomData, + }) + } + + fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, E> { + Ok(SerializeTuple { + elements: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_tuple_struct( + self, + name: &'static str, + len: usize, + ) -> Result<Self::SerializeTupleStruct, E> { + Ok(SerializeTupleStruct { + name: name, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_tuple_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result<Self::SerializeTupleVariant, E> { + Ok(SerializeTupleVariant { + name: name, + variant_index: variant_index, + variant: variant, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, E> { + Ok(SerializeMap { + entries: Vec::with_capacity(len.unwrap_or(0)), + key: None, + error: PhantomData, + }) + } + + fn serialize_struct( + self, + name: &'static str, + len: usize, + ) -> Result<Self::SerializeStruct, E> { + Ok(SerializeStruct { + name: name, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + + fn serialize_struct_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result<Self::SerializeStructVariant, E> { + Ok(SerializeStructVariant { + name: name, + variant_index: variant_index, + variant: variant, + fields: Vec::with_capacity(len), + error: PhantomData, + }) + } + } + + pub struct SerializeSeq<E> { + elements: Vec<Content>, + error: PhantomData<E>, + } + + impl<E> ser::SerializeSeq for SerializeSeq<E> + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E> + where + T: Serialize, + { + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.elements.push(value); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::Seq(self.elements)) + } + } + + pub struct SerializeTuple<E> { + elements: Vec<Content>, + error: PhantomData<E>, + } + + impl<E> ser::SerializeTuple for SerializeTuple<E> + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), E> + where + T: Serialize, + { + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.elements.push(value); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::Tuple(self.elements)) + } + } + + pub struct SerializeTupleStruct<E> { + name: &'static str, + fields: Vec<Content>, + error: PhantomData<E>, + } + + impl<E> ser::SerializeTupleStruct for SerializeTupleStruct<E> + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E> + where + T: Serialize, + { + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.fields.push(value); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::TupleStruct(self.name, self.fields)) + } + } + + pub struct SerializeTupleVariant<E> { + name: &'static str, + variant_index: u32, + variant: &'static str, + fields: Vec<Content>, + error: PhantomData<E>, + } + + impl<E> ser::SerializeTupleVariant for SerializeTupleVariant<E> + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), E> + where + T: Serialize, + { + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.fields.push(value); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::TupleVariant( + self.name, + self.variant_index, + self.variant, + self.fields, + )) + } + } + + pub struct SerializeMap<E> { + entries: Vec<(Content, Content)>, + key: Option<Content>, + error: PhantomData<E>, + } + + impl<E> ser::SerializeMap for SerializeMap<E> + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), E> + where + T: Serialize, + { + let key = try!(key.serialize(ContentSerializer::<E>::new())); + self.key = Some(key); + Ok(()) + } + + fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), E> + where + T: Serialize, + { + let key = self.key + .take() + .expect("serialize_value called before serialize_key"); + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.entries.push((key, value)); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::Map(self.entries)) + } + + fn serialize_entry<K: ?Sized, V: ?Sized>(&mut self, key: &K, value: &V) -> Result<(), E> + where + K: Serialize, + V: Serialize, + { + let key = try!(key.serialize(ContentSerializer::<E>::new())); + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.entries.push((key, value)); + Ok(()) + } + } + + pub struct SerializeStruct<E> { + name: &'static str, + fields: Vec<(&'static str, Content)>, + error: PhantomData<E>, + } + + impl<E> ser::SerializeStruct for SerializeStruct<E> + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E> + where + T: Serialize, + { + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::Struct(self.name, self.fields)) + } + } + + pub struct SerializeStructVariant<E> { + name: &'static str, + variant_index: u32, + variant: &'static str, + fields: Vec<(&'static str, Content)>, + error: PhantomData<E>, + } + + impl<E> ser::SerializeStructVariant for SerializeStructVariant<E> + where + E: ser::Error, + { + type Ok = Content; + type Error = E; + + fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), E> + where + T: Serialize, + { + let value = try!(value.serialize(ContentSerializer::<E>::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(self) -> Result<Content, E> { + Ok(Content::StructVariant( + self.name, + self.variant_index, + self.variant, + self.fields, + )) + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub struct FlatMapSerializer<'a, M: 'a>(pub &'a mut M); + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> FlatMapSerializer<'a, M> +where + M: SerializeMap + 'a, +{ + fn bad_type(self, what: Unsupported) -> M::Error { + ser::Error::custom(format_args!( + "can only flatten structs and maps (got {})", + what + )) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> Serializer for FlatMapSerializer<'a, M> +where + M: SerializeMap + 'a, +{ + type Ok = (); + type Error = M::Error; + + type SerializeSeq = Impossible<Self::Ok, M::Error>; + type SerializeTuple = Impossible<Self::Ok, M::Error>; + type SerializeTupleStruct = Impossible<Self::Ok, M::Error>; + type SerializeMap = FlatMapSerializeMap<'a, M>; + type SerializeStruct = FlatMapSerializeStruct<'a, M>; + type SerializeTupleVariant = Impossible<Self::Ok, M::Error>; + type SerializeStructVariant = FlatMapSerializeStructVariantAsMapValue<'a, M>; + + fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Boolean)) + } + + fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Integer)) + } + + fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Float)) + } + + fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Float)) + } + + fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Char)) + } + + fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::String)) + } + + fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::ByteArray)) + } + + fn serialize_none(self) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Optional)) + } + + fn serialize_some<T: ?Sized>(self, _: &T) -> Result<Self::Ok, Self::Error> + where + T: Serialize, + { + Err(self.bad_type(Unsupported::Optional)) + } + + fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Unit)) + } + + fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::UnitStruct)) + } + + fn serialize_unit_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + ) -> Result<Self::Ok, Self::Error> { + Err(self.bad_type(Unsupported::Enum)) + } + + fn serialize_newtype_struct<T: ?Sized>( + self, + _: &'static str, + value: &T, + ) -> Result<Self::Ok, Self::Error> + where + T: Serialize, + { + value.serialize(self) + } + + fn serialize_newtype_variant<T: ?Sized>( + self, + _: &'static str, + _: u32, + variant: &'static str, + value: &T, + ) -> Result<Self::Ok, Self::Error> + where + T: Serialize, + { + try!(self.0.serialize_key(variant)); + self.0.serialize_value(value) + } + + fn serialize_seq(self, _: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> { + Err(self.bad_type(Unsupported::Sequence)) + } + + fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> { + Err(self.bad_type(Unsupported::Tuple)) + } + + fn serialize_tuple_struct( + self, + _: &'static str, + _: usize, + ) -> Result<Self::SerializeTupleStruct, Self::Error> { + Err(self.bad_type(Unsupported::TupleStruct)) + } + + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> Result<Self::SerializeTupleVariant, Self::Error> { + Err(self.bad_type(Unsupported::Enum)) + } + + fn serialize_map(self, _: Option<usize>) -> Result<Self::SerializeMap, Self::Error> { + Ok(FlatMapSerializeMap(self.0)) + } + + fn serialize_struct( + self, + _: &'static str, + _: usize, + ) -> Result<Self::SerializeStruct, Self::Error> { + Ok(FlatMapSerializeStruct(self.0)) + } + + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + inner_variant: &'static str, + _: usize, + ) -> Result<Self::SerializeStructVariant, Self::Error> { + try!(self.0.serialize_key(inner_variant)); + Ok(FlatMapSerializeStructVariantAsMapValue::new( + self.0, + inner_variant, + )) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub struct FlatMapSerializeMap<'a, M: 'a>(&'a mut M); + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> ser::SerializeMap for FlatMapSerializeMap<'a, M> +where + M: SerializeMap + 'a, +{ + type Ok = (); + type Error = M::Error; + + fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> + where + T: Serialize, + { + self.0.serialize_key(key) + } + + fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> + where + T: Serialize, + { + self.0.serialize_value(value) + } + + fn end(self) -> Result<(), Self::Error> { + Ok(()) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub struct FlatMapSerializeStruct<'a, M: 'a>(&'a mut M); + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> ser::SerializeStruct for FlatMapSerializeStruct<'a, M> +where + M: SerializeMap + 'a, +{ + type Ok = (); + type Error = M::Error; + + fn serialize_field<T: ?Sized>( + &mut self, + key: &'static str, + value: &T, + ) -> Result<(), Self::Error> + where + T: Serialize, + { + self.0.serialize_entry(key, value) + } + + fn end(self) -> Result<(), Self::Error> { + Ok(()) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +pub struct FlatMapSerializeStructVariantAsMapValue<'a, M: 'a> { + map: &'a mut M, + name: &'static str, + fields: Vec<(&'static str, Content)>, +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> FlatMapSerializeStructVariantAsMapValue<'a, M> +where + M: SerializeMap + 'a, +{ + fn new(map: &'a mut M, name: &'static str) -> FlatMapSerializeStructVariantAsMapValue<'a, M> { + FlatMapSerializeStructVariantAsMapValue { + map: map, + name: name, + fields: Vec::new(), + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl<'a, M> ser::SerializeStructVariant for FlatMapSerializeStructVariantAsMapValue<'a, M> +where + M: SerializeMap + 'a, +{ + type Ok = (); + type Error = M::Error; + + fn serialize_field<T: ?Sized>( + &mut self, + key: &'static str, + value: &T, + ) -> Result<(), Self::Error> + where + T: Serialize, + { + let value = try!(value.serialize(ContentSerializer::<M::Error>::new())); + self.fields.push((key, value)); + Ok(()) + } + + fn end(self) -> Result<(), Self::Error> { + try!( + self.map + .serialize_value(&Content::Struct(self.name, self.fields)) + ); + Ok(()) + } +} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/ser/impls.rs cargo-0.26.0/vendor/serde-1.0.37/src/ser/impls.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/ser/impls.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/ser/impls.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,739 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use lib::*; + +use ser::{Serialize, SerializeTuple, Serializer}; + +#[cfg(feature = "std")] +use ser::Error; + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! primitive_impl { + ($ty:ident, $method:ident $($cast:tt)*) => { + impl Serialize for $ty { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.$method(*self $($cast)*) + } + } + } +} + +primitive_impl!(bool, serialize_bool); +primitive_impl!(isize, serialize_i64 as i64); +primitive_impl!(i8, serialize_i8); +primitive_impl!(i16, serialize_i16); +primitive_impl!(i32, serialize_i32); +primitive_impl!(i64, serialize_i64); +primitive_impl!(usize, serialize_u64 as u64); +primitive_impl!(u8, serialize_u8); +primitive_impl!(u16, serialize_u16); +primitive_impl!(u32, serialize_u32); +primitive_impl!(u64, serialize_u64); +primitive_impl!(f32, serialize_f32); +primitive_impl!(f64, serialize_f64); +primitive_impl!(char, serialize_char); + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for str { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.serialize_str(self) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +impl Serialize for String { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.serialize_str(self) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl Serialize for CStr { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.serialize_bytes(self.to_bytes()) + } +} + +#[cfg(feature = "std")] +impl Serialize for CString { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.serialize_bytes(self.to_bytes()) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<T> Serialize for Option<T> +where + T: Serialize, +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + match *self { + Some(ref value) => serializer.serialize_some(value), + None => serializer.serialize_none(), + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<T: ?Sized> Serialize for PhantomData<T> { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.serialize_unit_struct("PhantomData") + } +} + +//////////////////////////////////////////////////////////////////////////////// + +// Does not require T: Serialize. +impl<T> Serialize for [T; 0] { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + try!(serializer.serialize_tuple(0)).end() + } +} + +macro_rules! array_impls { + ($($len:tt)+) => { + $( + impl<T> Serialize for [T; $len] + where + T: Serialize, + { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + let mut seq = try!(serializer.serialize_tuple($len)); + for e in self { + try!(seq.serialize_element(e)); + } + seq.end() + } + } + )+ + } +} + +array_impls!(01 02 03 04 05 06 07 08 09 10 + 11 12 13 14 15 16 17 18 19 20 + 21 22 23 24 25 26 27 28 29 30 + 31 32); + +//////////////////////////////////////////////////////////////////////////////// + +impl<T> Serialize for [T] +where + T: Serialize, +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.collect_seq(self) + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +macro_rules! seq_impl { + ($ty:ident < T $(: $tbound1:ident $(+ $tbound2:ident)*)* $(, $typaram:ident : $bound:ident)* >) => { + impl<T $(, $typaram)*> Serialize for $ty<T $(, $typaram)*> + where + T: Serialize $(+ $tbound1 $(+ $tbound2)*)*, + $($typaram: $bound,)* + { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.collect_seq(self) + } + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +seq_impl!(BinaryHeap<T: Ord>); + +#[cfg(any(feature = "std", feature = "alloc"))] +seq_impl!(BTreeSet<T: Ord>); + +#[cfg(feature = "std")] +seq_impl!(HashSet<T: Eq + Hash, H: BuildHasher>); + +#[cfg(any(feature = "std", feature = "alloc"))] +seq_impl!(LinkedList<T>); + +#[cfg(any(feature = "std", feature = "alloc"))] +seq_impl!(Vec<T>); + +#[cfg(any(feature = "std", feature = "alloc"))] +seq_impl!(VecDeque<T>); + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl<Idx> Serialize for ops::Range<Idx> +where + Idx: Serialize, +{ + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + use super::SerializeStruct; + let mut state = try!(serializer.serialize_struct("Range", 2)); + try!(state.serialize_field("start", &self.start)); + try!(state.serialize_field("end", &self.end)); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl Serialize for () { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.serialize_unit() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! tuple_impls { + ($($len:expr => ($($n:tt $name:ident)+))+) => { + $( + impl<$($name),+> Serialize for ($($name,)+) + where + $($name: Serialize,)+ + { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + let mut tuple = try!(serializer.serialize_tuple($len)); + $( + try!(tuple.serialize_element(&self.$n)); + )+ + tuple.end() + } + } + )+ + } +} + +tuple_impls! { + 1 => (0 T0) + 2 => (0 T0 1 T1) + 3 => (0 T0 1 T1 2 T2) + 4 => (0 T0 1 T1 2 T2 3 T3) + 5 => (0 T0 1 T1 2 T2 3 T3 4 T4) + 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5) + 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6) + 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7) + 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8) + 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9) + 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10) + 12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11) + 13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12) + 14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13) + 15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14) + 16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15) +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(any(feature = "std", feature = "alloc"))] +macro_rules! map_impl { + ($ty:ident < K $(: $kbound1:ident $(+ $kbound2:ident)*)*, V $(, $typaram:ident : $bound:ident)* >) => { + impl<K, V $(, $typaram)*> Serialize for $ty<K, V $(, $typaram)*> + where + K: Serialize $(+ $kbound1 $(+ $kbound2)*)*, + V: Serialize, + $($typaram: $bound,)* + { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.collect_map(self) + } + } + } +} + +#[cfg(any(feature = "std", feature = "alloc"))] +map_impl!(BTreeMap<K: Ord, V>); + +#[cfg(feature = "std")] +map_impl!(HashMap<K: Eq + Hash, V, H: BuildHasher>); + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! deref_impl { + ( + $(#[doc = $doc:tt])* + <$($desc:tt)+ + ) => { + $(#[doc = $doc])* + impl <$($desc)+ { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + (**self).serialize(serializer) + } + } + }; +} + +deref_impl!(<'a, T: ?Sized> Serialize for &'a T where T: Serialize); +deref_impl!(<'a, T: ?Sized> Serialize for &'a mut T where T: Serialize); + +#[cfg(any(feature = "std", feature = "alloc"))] +deref_impl!(<T: ?Sized> Serialize for Box<T> where T: Serialize); + +#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] +deref_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Serializing a data structure containing `Rc` will serialize a copy of + /// the contents of the `Rc` each time the `Rc` is referenced within the + /// data structure. Serialization will not attempt to deduplicate these + /// repeated data. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + <T: ?Sized> Serialize for Rc<T> where T: Serialize +} + +#[cfg(all(feature = "rc", any(feature = "std", feature = "alloc")))] +deref_impl! { + /// This impl requires the [`"rc"`] Cargo feature of Serde. + /// + /// Serializing a data structure containing `Arc` will serialize a copy of + /// the contents of the `Arc` each time the `Arc` is referenced within the + /// data structure. Serialization will not attempt to deduplicate these + /// repeated data. + /// + /// [`"rc"`]: https://serde.rs/feature-flags.html#-features-rc + <T: ?Sized> Serialize for Arc<T> where T: Serialize +} + +#[cfg(any(feature = "std", feature = "alloc"))] +deref_impl!(<'a, T: ?Sized> Serialize for Cow<'a, T> where T: Serialize + ToOwned); + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "unstable")] +#[allow(deprecated)] +impl<T> Serialize for NonZero<T> +where + T: Serialize + Zeroable + Clone, +{ + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + self.clone().get().serialize(serializer) + } +} + +macro_rules! nonzero_integers { + ( $( $T: ident, )+ ) => { + $( + #[cfg(feature = "unstable")] + impl Serialize for $T { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + self.get().serialize(serializer) + } + } + )+ + } +} + +nonzero_integers! { + // Not including signed NonZeroI* since they might be removed + NonZeroU8, + NonZeroU16, + NonZeroU32, + NonZeroU64, + // FIXME: https://github.com/serde-rs/serde/issues/1136 NonZeroU128, + NonZeroUsize, +} + +impl<T> Serialize for Cell<T> +where + T: Serialize + Copy, +{ + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + self.get().serialize(serializer) + } +} + +impl<T> Serialize for RefCell<T> +where + T: Serialize, +{ + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + self.borrow().serialize(serializer) + } +} + +#[cfg(feature = "std")] +impl<T> Serialize for Mutex<T> +where + T: Serialize, +{ + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + match self.lock() { + Ok(locked) => locked.serialize(serializer), + Err(_) => Err(S::Error::custom("lock poison error while serializing")), + } + } +} + +#[cfg(feature = "std")] +impl<T> Serialize for RwLock<T> +where + T: Serialize, +{ + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + match self.read() { + Ok(locked) => locked.serialize(serializer), + Err(_) => Err(S::Error::custom("lock poison error while serializing")), + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +impl<T, E> Serialize for Result<T, E> +where + T: Serialize, + E: Serialize, +{ + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + match *self { + Result::Ok(ref value) => serializer.serialize_newtype_variant("Result", 0, "Ok", value), + Result::Err(ref value) => { + serializer.serialize_newtype_variant("Result", 1, "Err", value) + } + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl Serialize for Duration { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + use super::SerializeStruct; + let mut state = try!(serializer.serialize_struct("Duration", 2)); + try!(state.serialize_field("secs", &self.as_secs())); + try!(state.serialize_field("nanos", &self.subsec_nanos())); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl Serialize for SystemTime { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + use super::SerializeStruct; + let duration_since_epoch = self.duration_since(UNIX_EPOCH) + .expect("SystemTime must be later than UNIX_EPOCH"); + let mut state = try!(serializer.serialize_struct("SystemTime", 2)); + try!(state.serialize_field("secs_since_epoch", &duration_since_epoch.as_secs())); + try!(state.serialize_field("nanos_since_epoch", &duration_since_epoch.subsec_nanos())); + state.end() + } +} + +//////////////////////////////////////////////////////////////////////////////// + +/// Serialize a value that implements `Display` as a string, when that string is +/// statically known to never have more than a constant `MAX_LEN` bytes. +/// +/// Panics if the `Display` impl tries to write more than `MAX_LEN` bytes. +#[cfg(feature = "std")] +macro_rules! serialize_display_bounded_length { + ($value:expr, $max:expr, $serializer:expr) => {{ + let mut buffer: [u8; $max] = unsafe { mem::uninitialized() }; + let remaining_len = { + let mut remaining = &mut buffer[..]; + write!(remaining, "{}", $value).unwrap(); + remaining.len() + }; + let written_len = buffer.len() - remaining_len; + let written = &buffer[..written_len]; + + // write! only provides fmt::Formatter to Display implementations, which + // has methods write_str and write_char but no method to write arbitrary + // bytes. Therefore `written` must be valid UTF-8. + let written_str = unsafe { str::from_utf8_unchecked(written) }; + $serializer.serialize_str(written_str) + }}; +} + +#[cfg(feature = "std")] +impl Serialize for net::IpAddr { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + if serializer.is_human_readable() { + match *self { + net::IpAddr::V4(ref a) => a.serialize(serializer), + net::IpAddr::V6(ref a) => a.serialize(serializer), + } + } else { + match *self { + net::IpAddr::V4(ref a) => { + serializer.serialize_newtype_variant("IpAddr", 0, "V4", a) + } + net::IpAddr::V6(ref a) => { + serializer.serialize_newtype_variant("IpAddr", 1, "V6", a) + } + } + } + } +} + +#[cfg(feature = "std")] +impl Serialize for net::Ipv4Addr { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + if serializer.is_human_readable() { + const MAX_LEN: usize = 15; + debug_assert_eq!(MAX_LEN, "101.102.103.104".len()); + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } else { + self.octets().serialize(serializer) + } + } +} + +#[cfg(feature = "std")] +impl Serialize for net::Ipv6Addr { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + if serializer.is_human_readable() { + const MAX_LEN: usize = 39; + debug_assert_eq!(MAX_LEN, "1001:1002:1003:1004:1005:1006:1007:1008".len()); + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } else { + self.octets().serialize(serializer) + } + } +} + +#[cfg(feature = "std")] +impl Serialize for net::SocketAddr { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + if serializer.is_human_readable() { + match *self { + net::SocketAddr::V4(ref addr) => addr.serialize(serializer), + net::SocketAddr::V6(ref addr) => addr.serialize(serializer), + } + } else { + match *self { + net::SocketAddr::V4(ref addr) => { + serializer.serialize_newtype_variant("SocketAddr", 0, "V4", addr) + } + net::SocketAddr::V6(ref addr) => { + serializer.serialize_newtype_variant("SocketAddr", 1, "V6", addr) + } + } + } + } +} + +#[cfg(feature = "std")] +impl Serialize for net::SocketAddrV4 { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + if serializer.is_human_readable() { + const MAX_LEN: usize = 21; + debug_assert_eq!(MAX_LEN, "101.102.103.104:65000".len()); + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } else { + (self.ip(), self.port()).serialize(serializer) + } + } +} + +#[cfg(feature = "std")] +impl Serialize for net::SocketAddrV6 { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + if serializer.is_human_readable() { + const MAX_LEN: usize = 47; + debug_assert_eq!( + MAX_LEN, + "[1001:1002:1003:1004:1005:1006:1007:1008]:65000".len() + ); + serialize_display_bounded_length!(self, MAX_LEN, serializer) + } else { + (self.ip(), self.port()).serialize(serializer) + } + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl Serialize for Path { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + match self.to_str() { + Some(s) => s.serialize(serializer), + None => Err(Error::custom("path contains invalid UTF-8 characters")), + } + } +} + +#[cfg(feature = "std")] +impl Serialize for PathBuf { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + self.as_path().serialize(serializer) + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +impl Serialize for OsStr { + #[cfg(unix)] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + use std::os::unix::ffi::OsStrExt; + serializer.serialize_newtype_variant("OsString", 0, "Unix", self.as_bytes()) + } + + #[cfg(windows)] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + use std::os::windows::ffi::OsStrExt; + let val = self.encode_wide().collect::<Vec<_>>(); + serializer.serialize_newtype_variant("OsString", 1, "Windows", &val) + } +} + +#[cfg(all(feature = "std", any(unix, windows)))] +impl Serialize for OsString { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + self.as_os_str().serialize(serializer) + } +} + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "std")] +impl<T> Serialize for Wrapping<T> +where + T: Serialize, +{ + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + self.0.serialize(serializer) + } +} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/ser/impossible.rs cargo-0.26.0/vendor/serde-1.0.37/src/ser/impossible.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/ser/impossible.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/ser/impossible.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,227 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! This module contains `Impossible` serializer and its implementations. + +use lib::*; + +use ser::{self, Serialize, SerializeMap, SerializeSeq, SerializeStruct, SerializeStructVariant, + SerializeTuple, SerializeTupleStruct, SerializeTupleVariant}; + +/// Helper type for implementing a `Serializer` that does not support +/// serializing one of the compound types. +/// +/// This type cannot be instantiated, but implements every one of the traits +/// corresponding to the [`Serializer`] compound types: [`SerializeSeq`], +/// [`SerializeTuple`], [`SerializeTupleStruct`], [`SerializeTupleVariant`], +/// [`SerializeMap`], [`SerializeStruct`], and [`SerializeStructVariant`]. +/// +/// ```rust +/// # #[macro_use] +/// # extern crate serde; +/// # +/// # use serde::ser::{Serializer, Impossible}; +/// # use serde::private::ser::Error; +/// # +/// # struct MySerializer; +/// # +/// impl Serializer for MySerializer { +/// type Ok = (); +/// type Error = Error; +/// +/// type SerializeSeq = Impossible<(), Error>; +/// /* other associated types */ +/// +/// /// This data format does not support serializing sequences. +/// fn serialize_seq(self, +/// len: Option<usize>) +/// -> Result<Self::SerializeSeq, Error> { +/// // Given Impossible cannot be instantiated, the only +/// // thing we can do here is to return an error. +/// # stringify! { +/// Err(...) +/// # }; +/// # unimplemented!() +/// } +/// +/// /* other Serializer methods */ +/// # __serialize_unimplemented! { +/// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str bytes none some +/// # unit unit_struct unit_variant newtype_struct newtype_variant +/// # tuple tuple_struct tuple_variant map struct struct_variant +/// # } +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// [`Serializer`]: trait.Serializer.html +/// [`SerializeSeq`]: trait.SerializeSeq.html +/// [`SerializeTuple`]: trait.SerializeTuple.html +/// [`SerializeTupleStruct`]: trait.SerializeTupleStruct.html +/// [`SerializeTupleVariant`]: trait.SerializeTupleVariant.html +/// [`SerializeMap`]: trait.SerializeMap.html +/// [`SerializeStruct`]: trait.SerializeStruct.html +/// [`SerializeStructVariant`]: trait.SerializeStructVariant.html +pub struct Impossible<Ok, Error> { + void: Void, + ok: PhantomData<Ok>, + error: PhantomData<Error>, +} + +enum Void {} + +impl<Ok, Error> SerializeSeq for Impossible<Ok, Error> +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where + T: Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result<Ok, Error> { + match self.void {} + } +} + +impl<Ok, Error> SerializeTuple for Impossible<Ok, Error> +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where + T: Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result<Ok, Error> { + match self.void {} + } +} + +impl<Ok, Error> SerializeTupleStruct for Impossible<Ok, Error> +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where + T: Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result<Ok, Error> { + match self.void {} + } +} + +impl<Ok, Error> SerializeTupleVariant for Impossible<Ok, Error> +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where + T: Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result<Ok, Error> { + match self.void {} + } +} + +impl<Ok, Error> SerializeMap for Impossible<Ok, Error> +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Error> + where + T: Serialize, + { + let _ = key; + match self.void {} + } + + fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where + T: Serialize, + { + let _ = value; + match self.void {} + } + + fn end(self) -> Result<Ok, Error> { + match self.void {} + } +} + +impl<Ok, Error> SerializeStruct for Impossible<Ok, Error> +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> + where + T: Serialize, + { + let _ = key; + let _ = value; + match self.void {} + } + + fn end(self) -> Result<Ok, Error> { + match self.void {} + } +} + +impl<Ok, Error> SerializeStructVariant for Impossible<Ok, Error> +where + Error: ser::Error, +{ + type Ok = Ok; + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> + where + T: Serialize, + { + let _ = key; + let _ = value; + match self.void {} + } + + fn end(self) -> Result<Ok, Error> { + match self.void {} + } +} diff -Nru cargo-0.25.0/vendor/serde-1.0.37/src/ser/mod.rs cargo-0.26.0/vendor/serde-1.0.37/src/ser/mod.rs --- cargo-0.25.0/vendor/serde-1.0.37/src/ser/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde-1.0.37/src/ser/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1883 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Generic data structure serialization framework. +//! +//! The two most important traits in this module are [`Serialize`] and +//! [`Serializer`]. +//! +//! - **A type that implements `Serialize` is a data structure** that can be +//! serialized to any data format supported by Serde, and conversely +//! - **A type that implements `Serializer` is a data format** that can +//! serialize any data structure supported by Serde. +//! +//! # The Serialize trait +//! +//! Serde provides [`Serialize`] implementations for many Rust primitive and +//! standard library types. The complete list is below. All of these can be +//! serialized using Serde out of the box. +//! +//! Additionally, Serde provides a procedural macro called [`serde_derive`] to +//! automatically generate [`Serialize`] implementations for structs and enums +//! in your program. See the [codegen section of the manual] for how to use +//! this. +//! +//! In rare cases it may be necessary to implement [`Serialize`] manually for +//! some type in your program. See the [Implementing `Serialize`] section of the +//! manual for more about this. +//! +//! Third-party crates may provide [`Serialize`] implementations for types that +//! they expose. For example the [`linked-hash-map`] crate provides a +//! [`LinkedHashMap<K, V>`] type that is serializable by Serde because the crate +//! provides an implementation of [`Serialize`] for it. +//! +//! # The Serializer trait +//! +//! [`Serializer`] implementations are provided by third-party crates, for +//! example [`serde_json`], [`serde_yaml`] and [`bincode`]. +//! +//! A partial list of well-maintained formats is given on the [Serde +//! website][data formats]. +//! +//! # Implementations of Serialize provided by Serde +//! +//! - **Primitive types**: +//! - bool +//! - i8, i16, i32, i64, isize +//! - u8, u16, u32, u64, usize +//! - f32, f64 +//! - char +//! - str +//! - &T and &mut T +//! - **Compound types**: +//! - [T] +//! - [T; 0] through [T; 32] +//! - tuples up to size 16 +//! - **Common standard library types**: +//! - String +//! - Option\<T\> +//! - Result\<T, E\> +//! - PhantomData\<T\> +//! - **Wrapper types**: +//! - Box\<T\> +//! - Rc\<T\> +//! - Arc\<T\> +//! - Cow\<'a, T\> +//! - Cell\<T\> +//! - RefCell\<T\> +//! - Mutex\<T\> +//! - RwLock\<T\> +//! - **Collection types**: +//! - BTreeMap\<K, V\> +//! - BTreeSet\<T\> +//! - BinaryHeap\<T\> +//! - HashMap\<K, V, H\> +//! - HashSet\<T, H\> +//! - LinkedList\<T\> +//! - VecDeque\<T\> +//! - Vec\<T\> +//! - EnumSet\<T\> (unstable) +//! - **FFI types**: +//! - CStr +//! - CString +//! - OsStr +//! - OsString +//! - **Miscellaneous standard library types**: +//! - Duration +//! - SystemTime +//! - Path +//! - PathBuf +//! - Range\<T\> +//! - NonZero\<T\> (unstable, deprecated) +//! - num::NonZero* (unstable) +//! - **Net types**: +//! - IpAddr +//! - Ipv4Addr +//! - Ipv6Addr +//! - SocketAddr +//! - SocketAddrV4 +//! - SocketAddrV6 +//! +//! [Implementing `Serialize`]: https://serde.rs/impl-serialize.html +//! [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html +//! [`Serialize`]: ../trait.Serialize.html +//! [`Serializer`]: ../trait.Serializer.html +//! [`bincode`]: https://github.com/TyOverby/bincode +//! [`linked-hash-map`]: https://crates.io/crates/linked-hash-map +//! [`serde_derive`]: https://crates.io/crates/serde_derive +//! [`serde_json`]: https://github.com/serde-rs/json +//! [`serde_yaml`]: https://github.com/dtolnay/serde-yaml +//! [codegen section of the manual]: https://serde.rs/codegen.html +//! [data formats]: https://serde.rs/#data-formats + +use lib::*; + +mod impls; +mod impossible; + +pub use self::impossible::Impossible; + +//////////////////////////////////////////////////////////////////////////////// + +macro_rules! declare_error_trait { + (Error: Sized $(+ $($supertrait:ident)::+)*) => { + /// Trait used by `Serialize` implementations to generically construct + /// errors belonging to the `Serializer` against which they are + /// currently running. + pub trait Error: Sized $(+ $($supertrait)::+)* { + /// Used when a [`Serialize`] implementation encounters any error + /// while serializing a type. + /// + /// The message should not be capitalized and should not end with a + /// period. + /// + /// For example, a filesystem [`Path`] may refuse to serialize + /// itself if it contains invalid UTF-8 data. + /// + /// ```rust + /// # struct Path; + /// # + /// # impl Path { + /// # fn to_str(&self) -> Option<&str> { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::ser::{self, Serialize, Serializer}; + /// + /// impl Serialize for Path { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// match self.to_str() { + /// Some(s) => serializer.serialize_str(s), + /// None => Err(ser::Error::custom("path contains invalid UTF-8 characters")), + /// } + /// } + /// } + /// ``` + /// + /// [`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html + /// [`Serialize`]: ../trait.Serialize.html + fn custom<T>(msg: T) -> Self + where + T: Display; + } + } +} + +#[cfg(feature = "std")] +declare_error_trait!(Error: Sized + error::Error); + +#[cfg(not(feature = "std"))] +declare_error_trait!(Error: Sized + Debug + Display); + +//////////////////////////////////////////////////////////////////////////////// + +/// A **data structure** that can be serialized into any data format supported +/// by Serde. +/// +/// Serde provides `Serialize` implementations for many Rust primitive and +/// standard library types. The complete list is [here][ser]. All of these can +/// be serialized using Serde out of the box. +/// +/// Additionally, Serde provides a procedural macro called [`serde_derive`] to +/// automatically generate `Serialize` implementations for structs and enums in +/// your program. See the [codegen section of the manual] for how to use this. +/// +/// In rare cases it may be necessary to implement `Serialize` manually for some +/// type in your program. See the [Implementing `Serialize`] section of the +/// manual for more about this. +/// +/// Third-party crates may provide `Serialize` implementations for types that +/// they expose. For example the [`linked-hash-map`] crate provides a +/// [`LinkedHashMap<K, V>`] type that is serializable by Serde because the crate +/// provides an implementation of `Serialize` for it. +/// +/// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html +/// [`LinkedHashMap<K, V>`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html +/// [`linked-hash-map`]: https://crates.io/crates/linked-hash-map +/// [`serde_derive`]: https://crates.io/crates/serde_derive +/// [codegen section of the manual]: https://serde.rs/codegen.html +/// [ser]: https://docs.serde.rs/serde/ser/index.html +pub trait Serialize { + /// Serialize this value into the given Serde serializer. + /// + /// See the [Implementing `Serialize`] section of the manual for more + /// information about how to implement this method. + /// + /// ```rust + /// use serde::ser::{Serialize, Serializer, SerializeStruct}; + /// + /// struct Person { + /// name: String, + /// age: u8, + /// phones: Vec<String>, + /// } + /// + /// // This is what #[derive(Serialize)] would generate. + /// impl Serialize for Person { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// let mut s = serializer.serialize_struct("Person", 3)?; + /// s.serialize_field("name", &self.name)?; + /// s.serialize_field("age", &self.age)?; + /// s.serialize_field("phones", &self.phones)?; + /// s.end() + /// } + /// } + /// ``` + /// + /// [Implementing `Serialize`]: https://serde.rs/impl-serialize.html + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer; +} + +//////////////////////////////////////////////////////////////////////////////// + +/// A **data format** that can serialize any data structure supported by Serde. +/// +/// The role of this trait is to define the serialization half of the Serde data +/// model, which is a way to categorize every Rust data structure into one of 27 +/// possible types. Each method of the `Serializer` trait corresponds to one of +/// the types of the data model. +/// +/// Implementations of `Serialize` map themselves into this data model by +/// invoking exactly one of the `Serializer` methods. +/// +/// The types that make up the Serde data model are: +/// +/// - **12 primitive types** +/// - bool +/// - i8, i16, i32, i64 +/// - u8, u16, u32, u64 +/// - f32, f64 +/// - char +/// - **string** +/// - UTF-8 bytes with a length and no null terminator. +/// - When serializing, all strings are handled equally. When deserializing, +/// there are three flavors of strings: transient, owned, and borrowed. +/// - **byte array** - [u8] +/// - Similar to strings, during deserialization byte arrays can be transient, +/// owned, or borrowed. +/// - **option** +/// - Either none or some value. +/// - **unit** +/// - The type of `()` in Rust. It represents an anonymous value containing no +/// data. +/// - **unit_struct** +/// - For example `struct Unit` or `PhantomData<T>`. It represents a named value +/// containing no data. +/// - **unit_variant** +/// - For example the `E::A` and `E::B` in `enum E { A, B }`. +/// - **newtype_struct** +/// - For example `struct Millimeters(u8)`. +/// - **newtype_variant** +/// - For example the `E::N` in `enum E { N(u8) }`. +/// - **seq** +/// - A variably sized heterogeneous sequence of values, for example `Vec<T>` or +/// `HashSet<T>`. When serializing, the length may or may not be known before +/// iterating through all the data. When deserializing, the length is determined +/// by looking at the serialized data. +/// - **tuple** +/// - A statically sized heterogeneous sequence of values for which the length +/// will be known at deserialization time without looking at the serialized +/// data, for example `(u8,)` or `(String, u64, Vec<T>)` or `[u64; 10]`. +/// - **tuple_struct** +/// - A named tuple, for example `struct Rgb(u8, u8, u8)`. +/// - **tuple_variant** +/// - For example the `E::T` in `enum E { T(u8, u8) }`. +/// - **map** +/// - A heterogeneous key-value pairing, for example `BTreeMap<K, V>`. +/// - **struct** +/// - A heterogeneous key-value pairing in which the keys are strings and will be +/// known at deserialization time without looking at the serialized data, for +/// example `struct S { r: u8, g: u8, b: u8 }`. +/// - **struct_variant** +/// - For example the `E::S` in `enum E { S { r: u8, g: u8, b: u8 } }`. +/// +/// Many Serde serializers produce text or binary data as output, for example +/// JSON or Bincode. This is not a requirement of the `Serializer` trait, and +/// there are serializers that do not produce text or binary output. One example +/// is the `serde_json::value::Serializer` (distinct from the main `serde_json` +/// serializer) that produces a `serde_json::Value` data structure in memory as +/// output. +pub trait Serializer: Sized { + /// The output type produced by this `Serializer` during successful + /// serialization. Most serializers that produce text or binary output + /// should set `Ok = ()` and serialize into an [`io::Write`] or buffer + /// contained within the `Serializer` instance. Serializers that build + /// in-memory data structures may be simplified by using `Ok` to propagate + /// the data structure around. + /// + /// [`io::Write`]: https://doc.rust-lang.org/std/io/trait.Write.html + type Ok; + + /// The error type when some error occurs during serialization. + type Error: Error; + + /// Type returned from [`serialize_seq`] for serializing the content of the + /// sequence. + /// + /// [`serialize_seq`]: #tymethod.serialize_seq + type SerializeSeq: SerializeSeq<Ok = Self::Ok, Error = Self::Error>; + + /// Type returned from [`serialize_tuple`] for serializing the content of + /// the tuple. + /// + /// [`serialize_tuple`]: #tymethod.serialize_tuple + type SerializeTuple: SerializeTuple<Ok = Self::Ok, Error = Self::Error>; + + /// Type returned from [`serialize_tuple_struct`] for serializing the + /// content of the tuple struct. + /// + /// [`serialize_tuple_struct`]: #tymethod.serialize_tuple_struct + type SerializeTupleStruct: SerializeTupleStruct<Ok = Self::Ok, Error = Self::Error>; + + /// Type returned from [`serialize_tuple_variant`] for serializing the + /// content of the tuple variant. + /// + /// [`serialize_tuple_variant`]: #tymethod.serialize_tuple_variant + type SerializeTupleVariant: SerializeTupleVariant<Ok = Self::Ok, Error = Self::Error>; + + /// Type returned from [`serialize_map`] for serializing the content of the + /// map. + /// + /// [`serialize_map`]: #tymethod.serialize_map + type SerializeMap: SerializeMap<Ok = Self::Ok, Error = Self::Error>; + + /// Type returned from [`serialize_struct`] for serializing the content of + /// the struct. + /// + /// [`serialize_struct`]: #tymethod.serialize_struct + type SerializeStruct: SerializeStruct<Ok = Self::Ok, Error = Self::Error>; + + /// Type returned from [`serialize_struct_variant`] for serializing the + /// content of the struct variant. + /// + /// [`serialize_struct_variant`]: #tymethod.serialize_struct_variant + type SerializeStructVariant: SerializeStructVariant<Ok = Self::Ok, Error = Self::Error>; + + /// Serialize a `bool` value. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for bool { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_bool(*self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error>; + + /// Serialize an `i8` value. + /// + /// If the format does not differentiate between `i8` and `i64`, a + /// reasonable implementation would be to cast the value to `i64` and + /// forward to `serialize_i64`. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for i8 { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_i8(*self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error>; + + /// Serialize an `i16` value. + /// + /// If the format does not differentiate between `i16` and `i64`, a + /// reasonable implementation would be to cast the value to `i64` and + /// forward to `serialize_i64`. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for i16 { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_i16(*self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error>; + + /// Serialize an `i32` value. + /// + /// If the format does not differentiate between `i32` and `i64`, a + /// reasonable implementation would be to cast the value to `i64` and + /// forward to `serialize_i64`. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for i32 { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_i32(*self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error>; + + /// Serialize an `i64` value. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for i64 { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_i64(*self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `u8` value. + /// + /// If the format does not differentiate between `u8` and `u64`, a + /// reasonable implementation would be to cast the value to `u64` and + /// forward to `serialize_u64`. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for u8 { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_u8(*self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `u16` value. + /// + /// If the format does not differentiate between `u16` and `u64`, a + /// reasonable implementation would be to cast the value to `u64` and + /// forward to `serialize_u64`. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for u16 { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_u16(*self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `u32` value. + /// + /// If the format does not differentiate between `u32` and `u64`, a + /// reasonable implementation would be to cast the value to `u64` and + /// forward to `serialize_u64`. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for u32 { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_u32(*self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `u64` value. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for u64 { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_u64(*self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error>; + + /// Serialize an `f32` value. + /// + /// If the format does not differentiate between `f32` and `f64`, a + /// reasonable implementation would be to cast the value to `f64` and + /// forward to `serialize_f64`. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for f32 { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_f32(*self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error>; + + /// Serialize an `f64` value. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for f64 { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_f64(*self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error>; + + /// Serialize a character. + /// + /// If the format does not support characters, it is reasonable to serialize + /// it as a single element `str` or a `u32`. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for char { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_char(*self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error>; + + /// Serialize a `&str`. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for str { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_str(self) + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error>; + + /// Serialize a chunk of raw byte data. + /// + /// Enables serializers to serialize byte slices more compactly or more + /// efficiently than other types of slices. If no efficient implementation + /// is available, a reasonable implementation would be to forward to + /// `serialize_seq`. If forwarded, the implementation looks usually just + /// like this: + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::ser::{Serializer, SerializeSeq}; + /// # use serde::private::ser::Error; + /// # + /// # struct MySerializer; + /// # + /// # impl Serializer for MySerializer { + /// # type Ok = (); + /// # type Error = Error; + /// # + /// fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> { + /// let mut seq = self.serialize_seq(Some(v.len()))?; + /// for b in v { + /// seq.serialize_element(b)?; + /// } + /// seq.end() + /// } + /// # + /// # __serialize_unimplemented! { + /// # bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str none some + /// # unit unit_struct unit_variant newtype_struct newtype_variant + /// # seq tuple tuple_struct tuple_variant map struct struct_variant + /// # } + /// # } + /// # + /// # fn main() {} + /// ``` + fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error>; + + /// Serialize a [`None`] value. + /// + /// ```rust + /// # extern crate serde; + /// # + /// # use serde::{Serialize, Serializer}; + /// # + /// # enum Option<T> { + /// # Some(T), + /// # None, + /// # } + /// # + /// # use Option::{Some, None}; + /// # + /// impl<T> Serialize for Option<T> + /// where T: Serialize + /// { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// match *self { + /// Some(ref value) => serializer.serialize_some(value), + /// None => serializer.serialize_none(), + /// } + /// } + /// } + /// # + /// # fn main() {} + /// ``` + /// + /// [`None`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.None + fn serialize_none(self) -> Result<Self::Ok, Self::Error>; + + /// Serialize a [`Some(T)`] value. + /// + /// ```rust + /// # extern crate serde; + /// # + /// # use serde::{Serialize, Serializer}; + /// # + /// # enum Option<T> { + /// # Some(T), + /// # None, + /// # } + /// # + /// # use Option::{Some, None}; + /// # + /// impl<T> Serialize for Option<T> + /// where T: Serialize + /// { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// match *self { + /// Some(ref value) => serializer.serialize_some(value), + /// None => serializer.serialize_none(), + /// } + /// } + /// } + /// # + /// # fn main() {} + /// ``` + /// + /// [`Some(T)`]: https://doc.rust-lang.org/std/option/enum.Option.html#variant.Some + fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> + where + T: Serialize; + + /// Serialize a `()` value. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde; + /// # + /// # use serde::Serializer; + /// # + /// # __private_serialize!(); + /// # + /// impl Serialize for () { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_unit() + /// } + /// } + /// # + /// # fn main() {} + /// ``` + fn serialize_unit(self) -> Result<Self::Ok, Self::Error>; + + /// Serialize a unit struct like `struct Unit` or `PhantomData<T>`. + /// + /// A reasonable implementation would be to forward to `serialize_unit`. + /// + /// ```rust + /// use serde::{Serialize, Serializer}; + /// + /// struct Nothing; + /// + /// impl Serialize for Nothing { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_unit_struct("Nothing") + /// } + /// } + /// ``` + fn serialize_unit_struct(self, name: &'static str) -> Result<Self::Ok, Self::Error>; + + /// Serialize a unit variant like `E::A` in `enum E { A, B }`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, and the `variant` is the name of the + /// variant. + /// + /// ```rust + /// use serde::{Serialize, Serializer}; + /// + /// enum E { + /// A, + /// B, + /// } + /// + /// impl Serialize for E { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// match *self { + /// E::A => serializer.serialize_unit_variant("E", 0, "A"), + /// E::B => serializer.serialize_unit_variant("E", 1, "B"), + /// } + /// } + /// } + /// ``` + fn serialize_unit_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + ) -> Result<Self::Ok, Self::Error>; + + /// Serialize a newtype struct like `struct Millimeters(u8)`. + /// + /// Serializers are encouraged to treat newtype structs as insignificant + /// wrappers around the data they contain. A reasonable implementation would + /// be to forward to `value.serialize(self)`. + /// + /// ```rust + /// use serde::{Serialize, Serializer}; + /// + /// struct Millimeters(u8); + /// + /// impl Serialize for Millimeters { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.serialize_newtype_struct("Millimeters", &self.0) + /// } + /// } + /// ``` + fn serialize_newtype_struct<T: ?Sized>( + self, + name: &'static str, + value: &T, + ) -> Result<Self::Ok, Self::Error> + where + T: Serialize; + + /// Serialize a newtype variant like `E::N` in `enum E { N(u8) }`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, and the `variant` is the name of the + /// variant. The `value` is the data contained within this newtype variant. + /// + /// ```rust + /// use serde::{Serialize, Serializer}; + /// + /// enum E { + /// M(String), + /// N(u8), + /// } + /// + /// impl Serialize for E { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// match *self { + /// E::M(ref s) => serializer.serialize_newtype_variant("E", 0, "M", s), + /// E::N(n) => serializer.serialize_newtype_variant("E", 1, "N", &n), + /// } + /// } + /// } + /// ``` + fn serialize_newtype_variant<T: ?Sized>( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result<Self::Ok, Self::Error> + where + T: Serialize; + + /// Begin to serialize a variably sized sequence. This call must be + /// followed by zero or more calls to `serialize_element`, then a call to + /// `end`. + /// + /// The argument is the number of elements in the sequence, which may or may + /// not be computable before the sequence is iterated. Some serializers only + /// support sequences whose length is known up front. + /// + /// ```rust + /// # use std::marker::PhantomData; + /// # + /// # struct Vec<T>(PhantomData<T>); + /// # + /// # impl<T> Vec<T> { + /// # fn len(&self) -> usize { + /// # unimplemented!() + /// # } + /// # } + /// # + /// # impl<'a, T> IntoIterator for &'a Vec<T> { + /// # type Item = &'a T; + /// # type IntoIter = Box<Iterator<Item = &'a T>>; + /// # + /// # fn into_iter(self) -> Self::IntoIter { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::ser::{Serialize, Serializer, SerializeSeq}; + /// + /// impl<T> Serialize for Vec<T> + /// where T: Serialize + /// { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// let mut seq = serializer.serialize_seq(Some(self.len()))?; + /// for element in self { + /// seq.serialize_element(element)?; + /// } + /// seq.end() + /// } + /// } + /// ``` + fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error>; + + /// Begin to serialize a statically sized sequence whose length will be + /// known at deserialization time without looking at the serialized data. + /// This call must be followed by zero or more calls to `serialize_element`, + /// then a call to `end`. + /// + /// ```rust + /// use serde::ser::{Serialize, Serializer, SerializeTuple}; + /// + /// # mod fool { + /// # trait Serialize {} + /// impl<A, B, C> Serialize for (A, B, C) + /// # {} + /// # } + /// # + /// # struct Tuple3<A, B, C>(A, B, C); + /// # + /// # impl<A, B, C> Serialize for Tuple3<A, B, C> + /// where A: Serialize, + /// B: Serialize, + /// C: Serialize + /// { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// let mut tup = serializer.serialize_tuple(3)?; + /// tup.serialize_element(&self.0)?; + /// tup.serialize_element(&self.1)?; + /// tup.serialize_element(&self.2)?; + /// tup.end() + /// } + /// } + /// ``` + /// + /// ```rust + /// use serde::ser::{Serialize, Serializer, SerializeTuple}; + /// + /// const VRAM_SIZE: usize = 386; + /// struct Vram([u16; VRAM_SIZE]); + /// + /// impl Serialize for Vram { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// let mut seq = serializer.serialize_tuple(VRAM_SIZE)?; + /// for element in &self.0[..] { + /// seq.serialize_element(element)?; + /// } + /// seq.end() + /// } + /// } + /// ``` + fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Self::Error>; + + /// Begin to serialize a tuple struct like `struct Rgb(u8, u8, u8)`. This + /// call must be followed by zero or more calls to `serialize_field`, then a + /// call to `end`. + /// + /// The `name` is the name of the tuple struct and the `len` is the number + /// of data fields that will be serialized. + /// + /// ```rust + /// use serde::ser::{Serialize, Serializer, SerializeTupleStruct}; + /// + /// struct Rgb(u8, u8, u8); + /// + /// impl Serialize for Rgb { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; + /// ts.serialize_field(&self.0)?; + /// ts.serialize_field(&self.1)?; + /// ts.serialize_field(&self.2)?; + /// ts.end() + /// } + /// } + /// ``` + fn serialize_tuple_struct( + self, + name: &'static str, + len: usize, + ) -> Result<Self::SerializeTupleStruct, Self::Error>; + + /// Begin to serialize a tuple variant like `E::T` in `enum E { T(u8, u8) + /// }`. This call must be followed by zero or more calls to + /// `serialize_field`, then a call to `end`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, the `variant` is the name of the variant, + /// and the `len` is the number of data fields that will be serialized. + /// + /// ```rust + /// use serde::ser::{Serialize, Serializer, SerializeTupleVariant}; + /// + /// enum E { + /// T(u8, u8), + /// U(String, u32, u32), + /// } + /// + /// impl Serialize for E { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// match *self { + /// E::T(ref a, ref b) => { + /// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; + /// tv.serialize_field(a)?; + /// tv.serialize_field(b)?; + /// tv.end() + /// } + /// E::U(ref a, ref b, ref c) => { + /// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?; + /// tv.serialize_field(a)?; + /// tv.serialize_field(b)?; + /// tv.serialize_field(c)?; + /// tv.end() + /// } + /// } + /// } + /// } + /// ``` + fn serialize_tuple_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result<Self::SerializeTupleVariant, Self::Error>; + + /// Begin to serialize a map. This call must be followed by zero or more + /// calls to `serialize_key` and `serialize_value`, then a call to `end`. + /// + /// The argument is the number of elements in the map, which may or may not + /// be computable before the map is iterated. Some serializers only support + /// maps whose length is known up front. + /// + /// ```rust + /// # use std::marker::PhantomData; + /// # + /// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>); + /// # + /// # impl<K, V> HashMap<K, V> { + /// # fn len(&self) -> usize { + /// # unimplemented!() + /// # } + /// # } + /// # + /// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> { + /// # type Item = (&'a K, &'a V); + /// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>; + /// # + /// # fn into_iter(self) -> Self::IntoIter { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::ser::{Serialize, Serializer, SerializeMap}; + /// + /// impl<K, V> Serialize for HashMap<K, V> + /// where K: Serialize, + /// V: Serialize + /// { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// let mut map = serializer.serialize_map(Some(self.len()))?; + /// for (k, v) in self { + /// map.serialize_entry(k, v)?; + /// } + /// map.end() + /// } + /// } + /// ``` + fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error>; + + /// Begin to serialize a struct like `struct Rgb { r: u8, g: u8, b: u8 }`. + /// This call must be followed by zero or more calls to `serialize_field`, + /// then a call to `end`. + /// + /// The `name` is the name of the struct and the `len` is the number of + /// data fields that will be serialized. + /// + /// ```rust + /// use serde::ser::{Serialize, Serializer, SerializeStruct}; + /// + /// struct Rgb { + /// r: u8, + /// g: u8, + /// b: u8, + /// } + /// + /// impl Serialize for Rgb { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// let mut rgb = serializer.serialize_struct("Rgb", 3)?; + /// rgb.serialize_field("r", &self.r)?; + /// rgb.serialize_field("g", &self.g)?; + /// rgb.serialize_field("b", &self.b)?; + /// rgb.end() + /// } + /// } + /// ``` + fn serialize_struct( + self, + name: &'static str, + len: usize, + ) -> Result<Self::SerializeStruct, Self::Error>; + + /// Begin to serialize a struct variant like `E::S` in `enum E { S { r: u8, + /// g: u8, b: u8 } }`. This call must be followed by zero or more calls to + /// `serialize_field`, then a call to `end`. + /// + /// The `name` is the name of the enum, the `variant_index` is the index of + /// this variant within the enum, the `variant` is the name of the variant, + /// and the `len` is the number of data fields that will be serialized. + /// + /// ```rust + /// use serde::ser::{Serialize, Serializer, SerializeStructVariant}; + /// + /// enum E { + /// S { r: u8, g: u8, b: u8 } + /// } + /// + /// impl Serialize for E { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// match *self { + /// E::S { ref r, ref g, ref b } => { + /// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; + /// sv.serialize_field("r", r)?; + /// sv.serialize_field("g", g)?; + /// sv.serialize_field("b", b)?; + /// sv.end() + /// } + /// } + /// } + /// } + /// ``` + fn serialize_struct_variant( + self, + name: &'static str, + variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result<Self::SerializeStructVariant, Self::Error>; + + /// Collect an iterator as a sequence. + /// + /// The default implementation serializes each item yielded by the iterator + /// using [`serialize_seq`]. Implementors should not need to override this + /// method. + /// + /// ```rust + /// use serde::{Serialize, Serializer}; + /// + /// struct SecretlyOneHigher { + /// data: Vec<i32>, + /// } + /// + /// impl Serialize for SecretlyOneHigher { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.collect_seq(self.data.iter().map(|x| x + 1)) + /// } + /// } + /// ``` + /// + /// [`serialize_seq`]: #tymethod.serialize_seq + fn collect_seq<I>(self, iter: I) -> Result<Self::Ok, Self::Error> + where + I: IntoIterator, + <I as IntoIterator>::Item: Serialize, + { + let iter = iter.into_iter(); + let mut serializer = try!(self.serialize_seq(iter.len_hint())); + for item in iter { + try!(serializer.serialize_element(&item)); + } + serializer.end() + } + + /// Collect an iterator as a map. + /// + /// The default implementation serializes each pair yielded by the iterator + /// using [`serialize_map`]. Implementors should not need to override this + /// method. + /// + /// ```rust + /// use std::collections::BTreeSet; + /// use serde::{Serialize, Serializer}; + /// + /// struct MapToUnit { + /// keys: BTreeSet<i32>, + /// } + /// + /// // Serializes as a map in which the values are all unit. + /// impl Serialize for MapToUnit { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.collect_map(self.keys.iter().map(|k| (k, ()))) + /// } + /// } + /// ``` + /// + /// [`serialize_map`]: #tymethod.serialize_map + fn collect_map<K, V, I>(self, iter: I) -> Result<Self::Ok, Self::Error> + where + K: Serialize, + V: Serialize, + I: IntoIterator<Item = (K, V)>, + { + let iter = iter.into_iter(); + let mut serializer = try!(self.serialize_map(iter.len_hint())); + for (key, value) in iter { + try!(serializer.serialize_entry(&key, &value)); + } + serializer.end() + } + + /// Serialize a string produced by an implementation of `Display`. + /// + /// The default implementation builds a heap-allocated [`String`] and + /// delegates to [`serialize_str`]. Serializers are encouraged to provide a + /// more efficient implementation if possible. + /// + /// ```rust + /// # struct DateTime; + /// # + /// # impl DateTime { + /// # fn naive_local(&self) -> () { () } + /// # fn offset(&self) -> () { () } + /// # } + /// # + /// use serde::{Serialize, Serializer}; + /// + /// impl Serialize for DateTime { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.collect_str(&format_args!("{:?}{:?}", + /// self.naive_local(), + /// self.offset())) + /// } + /// } + /// ``` + /// + /// [`String`]: https://doc.rust-lang.org/std/string/struct.String.html + /// [`serialize_str`]: #tymethod.serialize_str + #[cfg(any(feature = "std", feature = "alloc"))] + fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> + where + T: Display, + { + use lib::fmt::Write; + let mut string = String::new(); + write!(string, "{}", value).unwrap(); + self.serialize_str(&string) + } + + /// Serialize a string produced by an implementation of `Display`. + /// + /// Serializers that use `no_std` are required to provide an implementation + /// of this method. If no more sensible behavior is possible, the + /// implementation is expected to return an error. + /// + /// ```rust + /// # struct DateTime; + /// # + /// # impl DateTime { + /// # fn naive_local(&self) -> () { () } + /// # fn offset(&self) -> () { () } + /// # } + /// # + /// use serde::{Serialize, Serializer}; + /// + /// impl Serialize for DateTime { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// serializer.collect_str(&format_args!("{:?}{:?}", + /// self.naive_local(), + /// self.offset())) + /// } + /// } + /// ``` + #[cfg(not(any(feature = "std", feature = "alloc")))] + fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok, Self::Error> + where + T: Display; + + /// Determine whether `Serialize` implementations should serialize in + /// human-readable form. + /// + /// Some types have a human-readable form that may be somewhat expensive to + /// construct, as well as a binary form that is compact and efficient. + /// Generally text-based formats like JSON and YAML will prefer to use the + /// human-readable one and binary formats like Bincode will prefer the + /// compact one. + /// + /// ``` + /// # use std::fmt::{self, Display}; + /// # + /// # struct Timestamp; + /// # + /// # impl Timestamp { + /// # fn seconds_since_epoch(&self) -> u64 { unimplemented!() } + /// # } + /// # + /// # impl Display for Timestamp { + /// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + /// # unimplemented!() + /// # } + /// # } + /// # + /// use serde::{Serialize, Serializer}; + /// + /// impl Serialize for Timestamp { + /// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + /// where S: Serializer + /// { + /// if serializer.is_human_readable() { + /// // Serialize to a human-readable string "2015-05-15T17:01:00Z". + /// self.to_string().serialize(serializer) + /// } else { + /// // Serialize to a compact binary representation. + /// self.seconds_since_epoch().serialize(serializer) + /// } + /// } + /// } + /// ``` + /// + /// The default implementation of this method returns `true`. Data formats + /// may override this to `false` to request a compact form for types that + /// support one. Note that modifying this method to change a format from + /// human-readable to compact or vice versa should be regarded as a breaking + /// change, as a value serialized in human-readable mode is not required to + /// deserialize from the same data in compact mode. + #[inline] + fn is_human_readable(&self) -> bool { + true + } +} + +/// Returned from `Serializer::serialize_seq`. +/// +/// ```rust +/// # use std::marker::PhantomData; +/// # +/// # struct Vec<T>(PhantomData<T>); +/// # +/// # impl<T> Vec<T> { +/// # fn len(&self) -> usize { +/// # unimplemented!() +/// # } +/// # } +/// # +/// # impl<'a, T> IntoIterator for &'a Vec<T> { +/// # type Item = &'a T; +/// # type IntoIter = Box<Iterator<Item = &'a T>>; +/// # fn into_iter(self) -> Self::IntoIter { +/// # unimplemented!() +/// # } +/// # } +/// # +/// use serde::ser::{Serialize, Serializer, SerializeSeq}; +/// +/// impl<T> Serialize for Vec<T> +/// where T: Serialize +/// { +/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> +/// where S: Serializer +/// { +/// let mut seq = serializer.serialize_seq(Some(self.len()))?; +/// for element in self { +/// seq.serialize_element(element)?; +/// } +/// seq.end() +/// } +/// } +/// ``` +pub trait SerializeSeq { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a sequence element. + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> + where + T: Serialize; + + /// Finish serializing a sequence. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +/// Returned from `Serializer::serialize_tuple`. +/// +/// ```rust +/// use serde::ser::{Serialize, Serializer, SerializeTuple}; +/// +/// # mod fool { +/// # trait Serialize {} +/// impl<A, B, C> Serialize for (A, B, C) +/// # {} +/// # } +/// # +/// # struct Tuple3<A, B, C>(A, B, C); +/// # +/// # impl<A, B, C> Serialize for Tuple3<A, B, C> +/// where A: Serialize, +/// B: Serialize, +/// C: Serialize +/// { +/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> +/// where S: Serializer +/// { +/// let mut tup = serializer.serialize_tuple(3)?; +/// tup.serialize_element(&self.0)?; +/// tup.serialize_element(&self.1)?; +/// tup.serialize_element(&self.2)?; +/// tup.end() +/// } +/// } +/// ``` +/// +/// ```rust +/// # use std::marker::PhantomData; +/// # +/// # struct Array<T>(PhantomData<T>); +/// # +/// # impl<T> Array<T> { +/// # fn len(&self) -> usize { +/// # unimplemented!() +/// # } +/// # } +/// # +/// # impl<'a, T> IntoIterator for &'a Array<T> { +/// # type Item = &'a T; +/// # type IntoIter = Box<Iterator<Item = &'a T>>; +/// # fn into_iter(self) -> Self::IntoIter { +/// # unimplemented!() +/// # } +/// # } +/// # +/// use serde::ser::{Serialize, Serializer, SerializeTuple}; +/// +/// # mod fool { +/// # trait Serialize {} +/// impl<T> Serialize for [T; 16] +/// # {} +/// # } +/// # +/// # impl<T> Serialize for Array<T> +/// where T: Serialize +/// { +/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> +/// where S: Serializer +/// { +/// let mut seq = serializer.serialize_tuple(16)?; +/// for element in self { +/// seq.serialize_element(element)?; +/// } +/// seq.end() +/// } +/// } +/// ``` +pub trait SerializeTuple { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a tuple element. + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> + where + T: Serialize; + + /// Finish serializing a tuple. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +/// Returned from `Serializer::serialize_tuple_struct`. +/// +/// ```rust +/// use serde::ser::{Serialize, Serializer, SerializeTupleStruct}; +/// +/// struct Rgb(u8, u8, u8); +/// +/// impl Serialize for Rgb { +/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> +/// where S: Serializer +/// { +/// let mut ts = serializer.serialize_tuple_struct("Rgb", 3)?; +/// ts.serialize_field(&self.0)?; +/// ts.serialize_field(&self.1)?; +/// ts.serialize_field(&self.2)?; +/// ts.end() +/// } +/// } +/// ``` +pub trait SerializeTupleStruct { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a tuple struct field. + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> + where + T: Serialize; + + /// Finish serializing a tuple struct. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +/// Returned from `Serializer::serialize_tuple_variant`. +/// +/// ```rust +/// use serde::ser::{Serialize, Serializer, SerializeTupleVariant}; +/// +/// enum E { +/// T(u8, u8), +/// U(String, u32, u32), +/// } +/// +/// impl Serialize for E { +/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> +/// where S: Serializer +/// { +/// match *self { +/// E::T(ref a, ref b) => { +/// let mut tv = serializer.serialize_tuple_variant("E", 0, "T", 2)?; +/// tv.serialize_field(a)?; +/// tv.serialize_field(b)?; +/// tv.end() +/// } +/// E::U(ref a, ref b, ref c) => { +/// let mut tv = serializer.serialize_tuple_variant("E", 1, "U", 3)?; +/// tv.serialize_field(a)?; +/// tv.serialize_field(b)?; +/// tv.serialize_field(c)?; +/// tv.end() +/// } +/// } +/// } +/// } +/// ``` +pub trait SerializeTupleVariant { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a tuple variant field. + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> + where + T: Serialize; + + /// Finish serializing a tuple variant. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +/// Returned from `Serializer::serialize_map`. +/// +/// ```rust +/// # use std::marker::PhantomData; +/// # +/// # struct HashMap<K, V>(PhantomData<K>, PhantomData<V>); +/// # +/// # impl<K, V> HashMap<K, V> { +/// # fn len(&self) -> usize { +/// # unimplemented!() +/// # } +/// # } +/// # +/// # impl<'a, K, V> IntoIterator for &'a HashMap<K, V> { +/// # type Item = (&'a K, &'a V); +/// # type IntoIter = Box<Iterator<Item = (&'a K, &'a V)>>; +/// # +/// # fn into_iter(self) -> Self::IntoIter { +/// # unimplemented!() +/// # } +/// # } +/// # +/// use serde::ser::{Serialize, Serializer, SerializeMap}; +/// +/// impl<K, V> Serialize for HashMap<K, V> +/// where K: Serialize, +/// V: Serialize +/// { +/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> +/// where S: Serializer +/// { +/// let mut map = serializer.serialize_map(Some(self.len()))?; +/// for (k, v) in self { +/// map.serialize_entry(k, v)?; +/// } +/// map.end() +/// } +/// } +/// ``` +pub trait SerializeMap { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a map key. + /// + /// If possible, `Serialize` implementations are encouraged to use + /// `serialize_entry` instead as it may be implemented more efficiently in + /// some formats compared to a pair of calls to `serialize_key` and + /// `serialize_value`. + fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Self::Error> + where + T: Serialize; + + /// Serialize a map value. + /// + /// # Panics + /// + /// Calling `serialize_value` before `serialize_key` is incorrect and is + /// allowed to panic or produce bogus results. + fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error> + where + T: Serialize; + + /// Serialize a map entry consisting of a key and a value. + /// + /// Some [`Serialize`] types are not able to hold a key and value in memory + /// at the same time so `SerializeMap` implementations are required to + /// support [`serialize_key`] and [`serialize_value`] individually. The + /// `serialize_entry` method allows serializers to optimize for the case + /// where key and value are both available. [`Serialize`] implementations + /// are encouraged to use `serialize_entry` if possible. + /// + /// The default implementation delegates to [`serialize_key`] and + /// [`serialize_value`]. This is appropriate for serializers that do not + /// care about performance or are not able to optimize `serialize_entry` any + /// better than this. + /// + /// [`Serialize`]: ../trait.Serialize.html + /// [`serialize_key`]: #tymethod.serialize_key + /// [`serialize_value`]: #tymethod.serialize_value + fn serialize_entry<K: ?Sized, V: ?Sized>( + &mut self, + key: &K, + value: &V, + ) -> Result<(), Self::Error> + where + K: Serialize, + V: Serialize, + { + try!(self.serialize_key(key)); + self.serialize_value(value) + } + + /// Finish serializing a map. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +/// Returned from `Serializer::serialize_struct`. +/// +/// ```rust +/// use serde::ser::{Serialize, Serializer, SerializeStruct}; +/// +/// struct Rgb { +/// r: u8, +/// g: u8, +/// b: u8, +/// } +/// +/// impl Serialize for Rgb { +/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> +/// where S: Serializer +/// { +/// let mut rgb = serializer.serialize_struct("Rgb", 3)?; +/// rgb.serialize_field("r", &self.r)?; +/// rgb.serialize_field("g", &self.g)?; +/// rgb.serialize_field("b", &self.b)?; +/// rgb.end() +/// } +/// } +/// ``` +pub trait SerializeStruct { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a struct field. + fn serialize_field<T: ?Sized>( + &mut self, + key: &'static str, + value: &T, + ) -> Result<(), Self::Error> + where + T: Serialize; + + /// Indicate that a struct field has been skipped. + #[inline] + fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { + let _ = key; + Ok(()) + } + + /// Finish serializing a struct. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +/// Returned from `Serializer::serialize_struct_variant`. +/// +/// ```rust +/// use serde::ser::{Serialize, Serializer, SerializeStructVariant}; +/// +/// enum E { +/// S { r: u8, g: u8, b: u8 } +/// } +/// +/// impl Serialize for E { +/// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> +/// where S: Serializer +/// { +/// match *self { +/// E::S { ref r, ref g, ref b } => { +/// let mut sv = serializer.serialize_struct_variant("E", 0, "S", 3)?; +/// sv.serialize_field("r", r)?; +/// sv.serialize_field("g", g)?; +/// sv.serialize_field("b", b)?; +/// sv.end() +/// } +/// } +/// } +/// } +/// ``` +pub trait SerializeStructVariant { + /// Must match the `Ok` type of our `Serializer`. + type Ok; + + /// Must match the `Error` type of our `Serializer`. + type Error: Error; + + /// Serialize a struct variant field. + fn serialize_field<T: ?Sized>( + &mut self, + key: &'static str, + value: &T, + ) -> Result<(), Self::Error> + where + T: Serialize; + + /// Indicate that a struct variant field has been skipped. + #[inline] + fn skip_field(&mut self, key: &'static str) -> Result<(), Self::Error> { + let _ = key; + Ok(()) + } + + /// Finish serializing a struct variant. + fn end(self) -> Result<Self::Ok, Self::Error>; +} + +trait LenHint: Iterator { + fn len_hint(&self) -> Option<usize>; +} + +impl<I> LenHint for I +where + I: Iterator, +{ + #[cfg(not(feature = "unstable"))] + fn len_hint(&self) -> Option<usize> { + iterator_len_hint(self) + } + + #[cfg(feature = "unstable")] + default fn len_hint(&self) -> Option<usize> { + iterator_len_hint(self) + } +} + +#[cfg(feature = "unstable")] +impl<I> LenHint for I +where + I: ExactSizeIterator, +{ + fn len_hint(&self) -> Option<usize> { + Some(self.len()) + } +} + +fn iterator_len_hint<I>(iter: &I) -> Option<usize> +where + I: Iterator, +{ + match iter.size_hint() { + (lo, Some(hi)) if lo == hi => Some(lo), + _ => None, + } +} diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.27/.cargo-checksum.json cargo-0.26.0/vendor/serde_derive-1.0.27/.cargo-checksum.json --- cargo-0.25.0/vendor/serde_derive-1.0.27/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.27/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"f4ba7591cfe93755e89eeecdbcc668885624829b020050e6aec99c2a03bd3fd0"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.27/Cargo.toml cargo-0.26.0/vendor/serde_derive-1.0.27/Cargo.toml --- cargo-0.25.0/vendor/serde_derive-1.0.27/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.27/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,46 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "serde_derive" -version = "1.0.27" -authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"] -include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] -description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]" -homepage = "https://serde.rs" -documentation = "https://serde.rs/codegen.html" -readme = "README.md" -keywords = ["serde", "serialization", "no_std"] -license = "MIT/Apache-2.0" -repository = "https://github.com/serde-rs/serde" - -[lib] -name = "serde_derive" -proc-macro = true -[dependencies.quote] -version = "0.3.8" - -[dependencies.serde_derive_internals] -version = "=0.19.0" -default-features = false - -[dependencies.syn] -version = "0.11" -features = ["visit"] -[dev-dependencies.serde] -version = "1.0" - -[features] -default = [] -deserialize_in_place = [] -[badges.travis-ci] -repository = "serde-rs/serde" diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.27/LICENSE-APACHE cargo-0.26.0/vendor/serde_derive-1.0.27/LICENSE-APACHE --- cargo-0.25.0/vendor/serde_derive-1.0.27/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.27/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.27/LICENSE-MIT cargo-0.26.0/vendor/serde_derive-1.0.27/LICENSE-MIT --- cargo-0.25.0/vendor/serde_derive-1.0.27/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.27/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.27/README.md cargo-0.26.0/vendor/serde_derive-1.0.27/README.md --- cargo-0.25.0/vendor/serde_derive-1.0.27/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.27/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,102 +0,0 @@ -# Serde   [![Build Status]][travis] [![Latest Version]][crates.io] - -[Build Status]: https://api.travis-ci.org/serde-rs/serde.svg?branch=master -[travis]: https://travis-ci.org/serde-rs/serde -[Latest Version]: https://img.shields.io/crates/v/serde.svg -[crates.io]: https://crates.io/crates/serde - -**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** - ---- - -You may be looking for: - -- [An overview of Serde](https://serde.rs/) -- [Data formats supported by Serde](https://serde.rs/#data-formats) -- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html) -- [Examples](https://serde.rs/examples.html) -- [API documentation](https://docs.serde.rs/serde/) -- [Release notes](https://github.com/serde-rs/serde/releases) - -## Serde in action - -<details> -<summary> -Click to show Cargo.toml. -<a href="http://play.integer32.com/?gist=9003c5b88c1f4989941925d7190c6eec" target="_blank">Run this code in the playground.</a> -</summary> - -```toml -[dependencies] - -# The core APIs, including the Serialize and Deserialize traits. Always -# required when using Serde. -serde = "1.0" - -# Support for #[derive(Serialize, Deserialize)]. Required if you want Serde -# to work for structs and enums defined in your crate. -serde_derive = "1.0" - -# Each data format lives in its own crate; the sample code below uses JSON -# but you may be using a different one. -serde_json = "1.0" -``` - -</details> -<p></p> - -```rust -#[macro_use] -extern crate serde_derive; - -extern crate serde; -extern crate serde_json; - -#[derive(Serialize, Deserialize, Debug)] -struct Point { - x: i32, - y: i32, -} - -fn main() { - let point = Point { x: 1, y: 2 }; - - // Convert the Point to a JSON string. - let serialized = serde_json::to_string(&point).unwrap(); - - // Prints serialized = {"x":1,"y":2} - println!("serialized = {}", serialized); - - // Convert the JSON string back to a Point. - let deserialized: Point = serde_json::from_str(&serialized).unwrap(); - - // Prints deserialized = Point { x: 1, y: 2 } - println!("deserialized = {:?}", deserialized); -} -``` - -## Getting help - -Serde developers live in the #serde channel on -[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a -good resource with generally faster response time but less specific knowledge -about Serde. If IRC is not your thing or you don't get a good response, we are -happy to respond to [GitHub issues](https://github.com/serde-rs/serde/issues/new) -as well. - -## License - -Serde is 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 Serde by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.27/src/bound.rs cargo-0.26.0/vendor/serde_derive-1.0.27/src/bound.rs --- cargo-0.25.0/vendor/serde_derive-1.0.27/src/bound.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.27/src/bound.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,258 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::collections::HashSet; - -use syn::{self, visit}; - -use internals::ast::{Body, Container}; -use internals::attr; - -macro_rules! path { - ($($path:tt)+) => { - syn::parse_path(quote!($($path)+).as_str()).unwrap() - }; -} - -// Remove the default from every type parameter because in the generated impls -// they look like associated types: "error: associated type bindings are not -// allowed here". -pub fn without_defaults(generics: &syn::Generics) -> syn::Generics { - syn::Generics { - ty_params: generics - .ty_params - .iter() - .map(|ty_param| syn::TyParam { - default: None, - ..ty_param.clone() - }) - .collect(), - ..generics.clone() - } -} - -pub fn with_where_predicates( - generics: &syn::Generics, - predicates: &[syn::WherePredicate], -) -> syn::Generics { - let mut generics = generics.clone(); - generics - .where_clause - .predicates - .extend_from_slice(predicates); - generics -} - -pub fn with_where_predicates_from_fields<F>( - cont: &Container, - generics: &syn::Generics, - from_field: F, -) -> syn::Generics -where - F: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>, -{ - let predicates = cont.body - .all_fields() - .flat_map(|field| from_field(&field.attrs)) - .flat_map(|predicates| predicates.to_vec()); - - let mut generics = generics.clone(); - generics.where_clause.predicates.extend(predicates); - generics -} - -// Puts the given bound on any generic type parameters that are used in fields -// for which filter returns true. -// -// For example, the following struct needs the bound `A: Serialize, B: Serialize`. -// -// struct S<'b, A, B: 'b, C> { -// a: A, -// b: Option<&'b B> -// #[serde(skip_serializing)] -// c: C, -// } -pub fn with_bound<F>( - cont: &Container, - generics: &syn::Generics, - filter: F, - bound: &syn::Path, -) -> syn::Generics -where - F: Fn(&attr::Field, Option<&attr::Variant>) -> bool, -{ - struct FindTyParams { - // Set of all generic type parameters on the current struct (A, B, C in - // the example). Initialized up front. - all_ty_params: HashSet<syn::Ident>, - // Set of generic type parameters used in fields for which filter - // returns true (A and B in the example). Filled in as the visitor sees - // them. - relevant_ty_params: HashSet<syn::Ident>, - } - impl visit::Visitor for FindTyParams { - fn visit_path(&mut self, path: &syn::Path) { - if let Some(seg) = path.segments.last() { - if seg.ident == "PhantomData" { - // Hardcoded exception, because PhantomData<T> implements - // Serialize and Deserialize whether or not T implements it. - return; - } - } - if !path.global && path.segments.len() == 1 { - let id = path.segments[0].ident.clone(); - if self.all_ty_params.contains(&id) { - self.relevant_ty_params.insert(id); - } - } - visit::walk_path(self, path); - } - - // Type parameter should not be considered used by a macro path. - // - // struct TypeMacro<T> { - // mac: T!(), - // marker: PhantomData<T>, - // } - fn visit_mac(&mut self, _mac: &syn::Mac) {} - } - - let all_ty_params: HashSet<_> = generics - .ty_params - .iter() - .map(|ty_param| ty_param.ident.clone()) - .collect(); - - let mut visitor = FindTyParams { - all_ty_params: all_ty_params, - relevant_ty_params: HashSet::new(), - }; - match cont.body { - Body::Enum(ref variants) => for variant in variants.iter() { - let relevant_fields = variant - .fields - .iter() - .filter(|field| filter(&field.attrs, Some(&variant.attrs))); - for field in relevant_fields { - visit::walk_ty(&mut visitor, field.ty); - } - }, - Body::Struct(_, ref fields) => { - for field in fields.iter().filter(|field| filter(&field.attrs, None)) { - visit::walk_ty(&mut visitor, field.ty); - } - } - } - - let new_predicates = generics - .ty_params - .iter() - .map(|ty_param| ty_param.ident.clone()) - .filter(|id| visitor.relevant_ty_params.contains(id)) - .map(|id| { - syn::WherePredicate::BoundPredicate(syn::WhereBoundPredicate { - bound_lifetimes: Vec::new(), - // the type parameter that is being bounded e.g. T - bounded_ty: syn::Ty::Path(None, id.into()), - // the bound e.g. Serialize - bounds: vec![ - syn::TyParamBound::Trait( - syn::PolyTraitRef { - bound_lifetimes: Vec::new(), - trait_ref: bound.clone(), - }, - syn::TraitBoundModifier::None, - ), - ], - }) - }); - - let mut generics = generics.clone(); - generics.where_clause.predicates.extend(new_predicates); - generics -} - -pub fn with_self_bound( - cont: &Container, - generics: &syn::Generics, - bound: &syn::Path, -) -> syn::Generics { - let mut generics = generics.clone(); - generics - .where_clause - .predicates - .push(syn::WherePredicate::BoundPredicate( - syn::WhereBoundPredicate { - bound_lifetimes: Vec::new(), - // the type that is being bounded e.g. MyStruct<'a, T> - bounded_ty: type_of_item(cont), - // the bound e.g. Default - bounds: vec![ - syn::TyParamBound::Trait( - syn::PolyTraitRef { - bound_lifetimes: Vec::new(), - trait_ref: bound.clone(), - }, - syn::TraitBoundModifier::None, - ), - ], - }, - )); - generics -} - -pub fn with_lifetime_bound(generics: &syn::Generics, lifetime: &str) -> syn::Generics { - let mut generics = generics.clone(); - - for lifetime_def in &mut generics.lifetimes { - lifetime_def.bounds.push(syn::Lifetime::new(lifetime)); - } - - for ty_param in &mut generics.ty_params { - ty_param - .bounds - .push(syn::TyParamBound::Region(syn::Lifetime::new(lifetime))); - } - - generics.lifetimes.push(syn::LifetimeDef { - attrs: Vec::new(), - lifetime: syn::Lifetime::new(lifetime), - bounds: Vec::new(), - }); - - generics -} - -fn type_of_item(cont: &Container) -> syn::Ty { - syn::Ty::Path( - None, - syn::Path { - global: false, - segments: vec![ - syn::PathSegment { - ident: cont.ident.clone(), - parameters: syn::PathParameters::AngleBracketed( - syn::AngleBracketedParameterData { - lifetimes: cont.generics - .lifetimes - .iter() - .map(|def| def.lifetime.clone()) - .collect(), - types: cont.generics - .ty_params - .iter() - .map(|param| syn::Ty::Path(None, param.ident.clone().into())) - .collect(), - bindings: Vec::new(), - }, - ), - }, - ], - }, - ) -} diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.27/src/de.rs cargo-0.26.0/vendor/serde_derive-1.0.27/src/de.rs --- cargo-0.25.0/vendor/serde_derive-1.0.27/src/de.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.27/src/de.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2479 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use syn::{self, Ident}; -use quote::{self, ToTokens, Tokens}; - -use bound; -use fragment::{Expr, Fragment, Match, Stmts}; -use internals::ast::{Body, Container, Field, Style, Variant}; -use internals::{self, attr}; - -use std::collections::BTreeSet; - -pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<Tokens, String> { - let ctxt = internals::Ctxt::new(); - let cont = Container::from_ast(&ctxt, input); - try!(ctxt.check()); - - let ident = &cont.ident; - let params = Parameters::new(&cont); - let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms); - let dummy_const = Ident::new(format!("_IMPL_DESERIALIZE_FOR_{}", ident)); - let body = Stmts(deserialize_body(&cont, ¶ms)); - let delife = params.borrowed.de_lifetime(); - - let impl_block = if let Some(remote) = cont.attrs.remote() { - let vis = &input.vis; - quote! { - impl #de_impl_generics #ident #ty_generics #where_clause { - #vis fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<#remote #ty_generics, __D::Error> - where __D: _serde::Deserializer<#delife> - { - #body - } - } - } - } else { - let fn_deserialize_in_place = deserialize_in_place_body(&cont, ¶ms); - - quote! { - #[automatically_derived] - impl #de_impl_generics _serde::Deserialize<#delife> for #ident #ty_generics #where_clause { - fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error> - where __D: _serde::Deserializer<#delife> - { - #body - } - - #fn_deserialize_in_place - } - } - }; - - let generated = quote! { - #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] - const #dummy_const: () = { - extern crate serde as _serde; - #impl_block - }; - }; - Ok(generated) -} - -struct Parameters { - /// Name of the type the `derive` is on. - local: syn::Ident, - - /// Path to the type the impl is for. Either a single `Ident` for local - /// types or `some::remote::Ident` for remote types. Does not include - /// generic parameters. - this: syn::Path, - - /// Generics including any explicit and inferred bounds for the impl. - generics: syn::Generics, - - /// Lifetimes borrowed from the deserializer. These will become bounds on - /// the `'de` lifetime of the deserializer. - borrowed: BorrowedLifetimes, - - /// At least one field has a serde(getter) attribute, implying that the - /// remote type has a private field. - has_getter: bool, -} - -impl Parameters { - fn new(cont: &Container) -> Self { - let local = cont.ident.clone(); - let this = match cont.attrs.remote() { - Some(remote) => remote.clone(), - None => cont.ident.clone().into(), - }; - let borrowed = borrowed_lifetimes(cont); - let generics = build_generics(cont, &borrowed); - let has_getter = cont.body.has_getter(); - - Parameters { - local: local, - this: this, - generics: generics, - borrowed: borrowed, - has_getter: has_getter, - } - } - - /// Type name to use in error messages and `&'static str` arguments to - /// various Deserializer methods. - fn type_name(&self) -> &str { - self.this.segments.last().unwrap().ident.as_ref() - } -} - -// All the generics in the input, plus a bound `T: Deserialize` for each generic -// field type that will be deserialized by us, plus a bound `T: Default` for -// each generic field type that will be set to a default value. -fn build_generics(cont: &Container, borrowed: &BorrowedLifetimes) -> syn::Generics { - let generics = bound::without_defaults(cont.generics); - - let generics = bound::with_where_predicates_from_fields(cont, &generics, attr::Field::de_bound); - - match cont.attrs.de_bound() { - Some(predicates) => bound::with_where_predicates(&generics, predicates), - None => { - let generics = match *cont.attrs.default() { - attr::Default::Default => { - bound::with_self_bound(cont, &generics, &path!(_serde::export::Default)) - } - attr::Default::None | attr::Default::Path(_) => generics, - }; - - let delife = borrowed.de_lifetime(); - let generics = bound::with_bound( - cont, - &generics, - needs_deserialize_bound, - &path!(_serde::Deserialize<#delife>), - ); - - bound::with_bound( - cont, - &generics, - requires_default, - &path!(_serde::export::Default), - ) - } - } -} - -// Fields with a `skip_deserializing` or `deserialize_with` attribute are not -// deserialized by us so we do not generate a bound. Fields with a `bound` -// attribute specify their own bound so we do not generate one. All other fields -// may need a `T: Deserialize` bound where T is the type of the field. -fn needs_deserialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool { - !field.skip_deserializing() && field.deserialize_with().is_none() && field.de_bound().is_none() - && variant.map_or(true, |variant| variant.deserialize_with().is_none()) -} - -// Fields with a `default` attribute (not `default=...`), and fields with a -// `skip_deserializing` attribute that do not also have `default=...`. -fn requires_default(field: &attr::Field, _variant: Option<&attr::Variant>) -> bool { - field.default() == &attr::Default::Default -} - -enum BorrowedLifetimes { - Borrowed(BTreeSet<syn::Lifetime>), - Static, -} - -impl BorrowedLifetimes { - fn de_lifetime(&self) -> syn::Lifetime { - match *self { - BorrowedLifetimes::Borrowed(_) => syn::Lifetime::new("'de"), - BorrowedLifetimes::Static => syn::Lifetime::new("'static"), - } - } - - fn de_lifetime_def(&self) -> Option<syn::LifetimeDef> { - match *self { - BorrowedLifetimes::Borrowed(ref bounds) => Some(syn::LifetimeDef { - attrs: Vec::new(), - lifetime: syn::Lifetime::new("'de"), - bounds: bounds.iter().cloned().collect(), - }), - BorrowedLifetimes::Static => None, - } - } -} - -// The union of lifetimes borrowed by each field of the container. -// -// These turn into bounds on the `'de` lifetime of the Deserialize impl. If -// lifetimes `'a` and `'b` are borrowed but `'c` is not, the impl is: -// -// impl<'de: 'a + 'b, 'a, 'b, 'c> Deserialize<'de> for S<'a, 'b, 'c> -// -// If any borrowed lifetime is `'static`, then `'de: 'static` would be redundant -// and we use plain `'static` instead of `'de`. -fn borrowed_lifetimes(cont: &Container) -> BorrowedLifetimes { - let mut lifetimes = BTreeSet::new(); - for field in cont.body.all_fields() { - if !field.attrs.skip_deserializing() { - lifetimes.extend(field.attrs.borrowed_lifetimes().iter().cloned()); - } - } - if lifetimes.iter().any(|b| b.ident == "'static") { - BorrowedLifetimes::Static - } else { - BorrowedLifetimes::Borrowed(lifetimes) - } -} - -fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment { - if let Some(from_type) = cont.attrs.from_type() { - deserialize_from(from_type) - } else if let attr::Identifier::No = cont.attrs.identifier() { - match cont.body { - Body::Enum(ref variants) => deserialize_enum(params, variants, &cont.attrs), - Body::Struct(Style::Struct, ref fields) => { - if fields.iter().any(|field| field.ident.is_none()) { - panic!("struct has unnamed fields"); - } - deserialize_struct(None, params, fields, &cont.attrs, None, Untagged::No) - } - Body::Struct(Style::Tuple, ref fields) | Body::Struct(Style::Newtype, ref fields) => { - if fields.iter().any(|field| field.ident.is_some()) { - panic!("tuple struct has named fields"); - } - deserialize_tuple(None, params, fields, &cont.attrs, None) - } - Body::Struct(Style::Unit, _) => deserialize_unit_struct(params, &cont.attrs), - } - } else { - match cont.body { - Body::Enum(ref variants) => { - deserialize_custom_identifier(params, variants, &cont.attrs) - } - Body::Struct(_, _) => unreachable!("checked in serde_derive_internals"), - } - } -} - -#[cfg(feature = "deserialize_in_place")] -fn deserialize_in_place_body(cont: &Container, params: &Parameters) -> Option<Stmts> { - // Only remote derives have getters, and we do not generate - // deserialize_in_place for remote derives. - assert!(!params.has_getter); - - if cont.attrs.from_type().is_some() || cont.attrs.identifier().is_some() - || cont.body - .all_fields() - .all(|f| f.attrs.deserialize_with().is_some()) - { - return None; - } - - let code = match cont.body { - Body::Struct(Style::Struct, ref fields) => { - deserialize_struct_in_place(None, params, fields, &cont.attrs, None, Untagged::No) - } - Body::Struct(Style::Tuple, ref fields) | Body::Struct(Style::Newtype, ref fields) => { - deserialize_tuple_in_place(None, params, fields, &cont.attrs, None) - } - Body::Enum(_) | Body::Struct(Style::Unit, _) => { - return None; - } - }; - - let delife = params.borrowed.de_lifetime(); - let stmts = Stmts(code); - - let fn_deserialize_in_place = quote_block! { - fn deserialize_in_place<__D>(__deserializer: __D, __place: &mut Self) -> _serde::export::Result<(), __D::Error> - where __D: _serde::Deserializer<#delife> - { - #stmts - } - }; - - Some(Stmts(fn_deserialize_in_place)) -} - -#[cfg(not(feature = "deserialize_in_place"))] -fn deserialize_in_place_body(_cont: &Container, _params: &Parameters) -> Option<Stmts> { - None -} - -fn deserialize_from(from_type: &syn::Ty) -> Fragment { - quote_block! { - _serde::export::Result::map( - <#from_type as _serde::Deserialize>::deserialize(__deserializer), - _serde::export::From::from) - } -} - -fn deserialize_unit_struct(params: &Parameters, cattrs: &attr::Container) -> Fragment { - let this = ¶ms.this; - let type_name = cattrs.name().deserialize_name(); - - let expecting = format!("unit struct {}", params.type_name()); - - quote_block! { - struct __Visitor; - - impl<'de> _serde::de::Visitor<'de> for __Visitor { - type Value = #this; - - fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { - _serde::export::Formatter::write_str(formatter, #expecting) - } - - #[inline] - fn visit_unit<__E>(self) -> _serde::export::Result<Self::Value, __E> - where __E: _serde::de::Error - { - _serde::export::Ok(#this) - } - } - - _serde::Deserializer::deserialize_unit_struct(__deserializer, #type_name, __Visitor) - } -} - -fn deserialize_tuple( - variant_ident: Option<&syn::Ident>, - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, - deserializer: Option<Tokens>, -) -> Fragment { - let this = ¶ms.this; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - // If there are getters (implying private fields), construct the local type - // and use an `Into` conversion to get the remote type. If there are no - // getters then construct the target type directly. - let construct = if params.has_getter { - let local = ¶ms.local; - quote!(#local) - } else { - quote!(#this) - }; - - let is_enum = variant_ident.is_some(); - let type_path = match variant_ident { - Some(variant_ident) => quote!(#construct::#variant_ident), - None => construct, - }; - let expecting = match variant_ident { - Some(variant_ident) => format!("tuple variant {}::{}", params.type_name(), variant_ident), - None => format!("tuple struct {}", params.type_name()), - }; - - let nfields = fields.len(); - - let visit_newtype_struct = if !is_enum && nfields == 1 { - Some(deserialize_newtype_struct(&type_path, params, &fields[0])) - } else { - None - }; - - let visit_seq = Stmts(deserialize_seq(&type_path, params, fields, false, cattrs)); - - let visitor_expr = quote! { - __Visitor { - marker: _serde::export::PhantomData::<#this #ty_generics>, - lifetime: _serde::export::PhantomData, - } - }; - let dispatch = if let Some(deserializer) = deserializer { - quote!(_serde::Deserializer::deserialize_tuple(#deserializer, #nfields, #visitor_expr)) - } else if is_enum { - quote!(_serde::de::VariantAccess::tuple_variant(__variant, #nfields, #visitor_expr)) - } else if nfields == 1 { - let type_name = cattrs.name().deserialize_name(); - quote!(_serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr)) - } else { - let type_name = cattrs.name().deserialize_name(); - quote!(_serde::Deserializer::deserialize_tuple_struct(__deserializer, #type_name, #nfields, #visitor_expr)) - }; - - let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); - let visitor_var = if all_skipped { - quote!(_) - } else { - quote!(mut __seq) - }; - - quote_block! { - struct __Visitor #de_impl_generics #where_clause { - marker: _serde::export::PhantomData<#this #ty_generics>, - lifetime: _serde::export::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { - type Value = #this #ty_generics; - - fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { - _serde::export::Formatter::write_str(formatter, #expecting) - } - - #visit_newtype_struct - - #[inline] - fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error> - where __A: _serde::de::SeqAccess<#delife> - { - #visit_seq - } - } - - #dispatch - } -} - -#[cfg(feature = "deserialize_in_place")] -fn deserialize_tuple_in_place( - variant_ident: Option<&syn::Ident>, - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, - deserializer: Option<Tokens>, -) -> Fragment { - let this = ¶ms.this; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - let is_enum = variant_ident.is_some(); - let expecting = match variant_ident { - Some(variant_ident) => format!("tuple variant {}::{}", params.type_name(), variant_ident), - None => format!("tuple struct {}", params.type_name()), - }; - - let nfields = fields.len(); - - let visit_newtype_struct = if !is_enum && nfields == 1 { - Some(deserialize_newtype_struct_in_place(params, &fields[0])) - } else { - None - }; - - let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs)); - - let visitor_expr = quote! { - __Visitor { - place: __place, - lifetime: _serde::export::PhantomData, - } - }; - - let dispatch = if let Some(deserializer) = deserializer { - quote!(_serde::Deserializer::deserialize_tuple(#deserializer, #nfields, #visitor_expr)) - } else if is_enum { - quote!(_serde::de::VariantAccess::tuple_variant(__variant, #nfields, #visitor_expr)) - } else if nfields == 1 { - let type_name = cattrs.name().deserialize_name(); - quote!(_serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr)) - } else { - let type_name = cattrs.name().deserialize_name(); - quote!(_serde::Deserializer::deserialize_tuple_struct(__deserializer, #type_name, #nfields, #visitor_expr)) - }; - - let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); - let visitor_var = if all_skipped { - quote!(_) - } else { - quote!(mut __seq) - }; - - let in_place_impl_generics = de_impl_generics.in_place(); - let in_place_ty_generics = de_ty_generics.in_place(); - let place_life = place_lifetime(); - - quote_block! { - struct __Visitor #in_place_impl_generics #where_clause { - place: &#place_life mut #this #ty_generics, - lifetime: _serde::export::PhantomData<&#delife ()>, - } - - impl #in_place_impl_generics _serde::de::Visitor<#delife> for __Visitor #in_place_ty_generics #where_clause { - type Value = (); - - fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { - _serde::export::Formatter::write_str(formatter, #expecting) - } - - #visit_newtype_struct - - #[inline] - fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error> - where __A: _serde::de::SeqAccess<#delife> - { - #visit_seq - } - } - - #dispatch - } -} - -fn deserialize_seq( - type_path: &Tokens, - params: &Parameters, - fields: &[Field], - is_struct: bool, - cattrs: &attr::Container, -) -> Fragment { - let vars = (0..fields.len()).map(field_i as fn(_) -> _); - - let deserialized_count = fields - .iter() - .filter(|field| !field.attrs.skip_deserializing()) - .count(); - let expecting = format!("tuple of {} elements", deserialized_count); - - let mut index_in_seq = 0usize; - let let_values = vars.clone().zip(fields).map(|(var, field)| { - if field.attrs.skip_deserializing() { - let default = Expr(expr_is_missing(&field, cattrs)); - quote! { - let #var = #default; - } - } else { - let visit = match field.attrs.deserialize_with() { - None => { - let field_ty = &field.ty; - quote!(try!(_serde::de::SeqAccess::next_element::<#field_ty>(&mut __seq))) - } - Some(path) => { - let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); - quote!({ - #wrapper - _serde::export::Option::map( - try!(_serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)), - |__wrap| __wrap.value) - }) - } - }; - let assign = quote! { - let #var = match #visit { - _serde::export::Some(__value) => __value, - _serde::export::None => { - return _serde::export::Err(_serde::de::Error::invalid_length(#index_in_seq, &#expecting)); - } - }; - }; - index_in_seq += 1; - assign - } - }); - - let mut result = if is_struct { - let names = fields.iter().map(|f| &f.ident); - quote! { - #type_path { #( #names: #vars ),* } - } - } else { - quote! { - #type_path ( #(#vars),* ) - } - }; - - if params.has_getter { - let this = ¶ms.this; - result = quote! { - _serde::export::Into::<#this>::into(#result) - }; - } - - let let_default = match *cattrs.default() { - attr::Default::Default => Some(quote!( - let __default: Self::Value = _serde::export::Default::default(); - )), - attr::Default::Path(ref path) => Some(quote!( - let __default: Self::Value = #path(); - )), - attr::Default::None => { - // We don't need the default value, to prevent an unused variable warning - // we'll leave the line empty. - None - } - }; - - quote_block! { - #let_default - #(#let_values)* - _serde::export::Ok(#result) - } -} - -#[cfg(feature = "deserialize_in_place")] -fn deserialize_seq_in_place( - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, -) -> Fragment { - let vars = (0..fields.len()).map(field_i as fn(_) -> _); - - let deserialized_count = fields - .iter() - .filter(|field| !field.attrs.skip_deserializing()) - .count(); - let expecting = format!("tuple of {} elements", deserialized_count); - - let mut index_in_seq = 0usize; - let write_values = vars.clone() - .zip(fields) - .enumerate() - .map(|(field_index, (_, field))| { - // If there's no field name, assume we're a tuple-struct and use a numeric index - let field_name = field - .ident - .clone() - .unwrap_or_else(|| Ident::new(field_index.to_string())); - - if field.attrs.skip_deserializing() { - let default = Expr(expr_is_missing(&field, cattrs)); - quote! { - self.place.#field_name = #default; - } - } else { - let return_invalid_length = quote! { - return _serde::export::Err(_serde::de::Error::invalid_length(#index_in_seq, &#expecting)); - }; - let write = match field.attrs.deserialize_with() { - None => { - quote! { - if let _serde::export::None = try!(_serde::de::SeqAccess::next_element_seed(&mut __seq, - _serde::private::de::InPlaceSeed(&mut self.place.#field_name))) - { - #return_invalid_length - } - } - } - Some(path) => { - let (wrapper, wrapper_ty) = - wrap_deserialize_field_with(params, field.ty, path); - quote!({ - #wrapper - match try!(_serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)) { - _serde::export::Some(__wrap) => { - self.place.#field_name = __wrap.value; - } - _serde::export::None => { - #return_invalid_length - } - } - }) - } - }; - index_in_seq += 1; - write - } - }); - - let this = ¶ms.this; - let (_, ty_generics, _) = params.generics.split_for_impl(); - let let_default = match *cattrs.default() { - attr::Default::Default => Some(quote!( - let __default: #this #ty_generics = _serde::export::Default::default(); - )), - attr::Default::Path(ref path) => Some(quote!( - let __default: #this #ty_generics = #path(); - )), - attr::Default::None => { - // We don't need the default value, to prevent an unused variable warning - // we'll leave the line empty. - None - } - }; - - quote_block! { - #let_default - #(#write_values)* - _serde::export::Ok(()) - } -} - -fn deserialize_newtype_struct(type_path: &Tokens, params: &Parameters, field: &Field) -> Tokens { - let delife = params.borrowed.de_lifetime(); - - let value = match field.attrs.deserialize_with() { - None => { - let field_ty = &field.ty; - quote! { - try!(<#field_ty as _serde::Deserialize>::deserialize(__e)) - } - } - Some(path) => { - let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); - quote!({ - #wrapper - try!(<#wrapper_ty as _serde::Deserialize>::deserialize(__e)).value - }) - } - }; - - let mut result = quote!(#type_path(#value)); - if params.has_getter { - let this = ¶ms.this; - result = quote! { - _serde::export::Into::<#this>::into(#result) - }; - } - - quote! { - #[inline] - fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::export::Result<Self::Value, __E::Error> - where __E: _serde::Deserializer<#delife> - { - _serde::export::Ok(#result) - } - } -} - -#[cfg(feature = "deserialize_in_place")] -fn deserialize_newtype_struct_in_place(params: &Parameters, field: &Field) -> Tokens { - // We do not generate deserialize_in_place if every field has a deserialize_with. - assert!(field.attrs.deserialize_with().is_none()); - - let delife = params.borrowed.de_lifetime(); - - quote! { - #[inline] - fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::export::Result<Self::Value, __E::Error> - where __E: _serde::Deserializer<#delife> - { - _serde::Deserialize::deserialize_in_place(__e, &mut self.place.0) - } - } -} - -enum Untagged { - Yes, - No, -} - -fn deserialize_struct( - variant_ident: Option<&syn::Ident>, - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, - deserializer: Option<Tokens>, - untagged: Untagged, -) -> Fragment { - let is_enum = variant_ident.is_some(); - - let this = ¶ms.this; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - // If there are getters (implying private fields), construct the local type - // and use an `Into` conversion to get the remote type. If there are no - // getters then construct the target type directly. - let construct = if params.has_getter { - let local = ¶ms.local; - quote!(#local) - } else { - quote!(#this) - }; - - let type_path = match variant_ident { - Some(variant_ident) => quote!(#construct::#variant_ident), - None => construct, - }; - let expecting = match variant_ident { - Some(variant_ident) => format!("struct variant {}::{}", params.type_name(), variant_ident), - None => format!("struct {}", params.type_name()), - }; - - let visit_seq = Stmts(deserialize_seq(&type_path, params, fields, true, cattrs)); - - let (field_visitor, fields_stmt, visit_map) = - deserialize_struct_visitor(type_path, params, fields, cattrs); - let field_visitor = Stmts(field_visitor); - let fields_stmt = Stmts(fields_stmt); - let visit_map = Stmts(visit_map); - - let visitor_expr = quote! { - __Visitor { - marker: _serde::export::PhantomData::<#this #ty_generics>, - lifetime: _serde::export::PhantomData, - } - }; - let dispatch = if let Some(deserializer) = deserializer { - quote! { - _serde::Deserializer::deserialize_any(#deserializer, #visitor_expr) - } - } else if is_enum { - quote! { - _serde::de::VariantAccess::struct_variant(__variant, FIELDS, #visitor_expr) - } - } else { - let type_name = cattrs.name().deserialize_name(); - quote! { - _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, #visitor_expr) - } - }; - - let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); - let visitor_var = if all_skipped { - quote!(_) - } else { - quote!(mut __seq) - }; - - // untagged struct variants do not get a visit_seq method - let visit_seq = match untagged { - Untagged::Yes => None, - Untagged::No => Some(quote! { - #[inline] - fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error> - where __A: _serde::de::SeqAccess<#delife> - { - #visit_seq - } - }), - }; - - quote_block! { - #field_visitor - - struct __Visitor #de_impl_generics #where_clause { - marker: _serde::export::PhantomData<#this #ty_generics>, - lifetime: _serde::export::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { - type Value = #this #ty_generics; - - fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { - _serde::export::Formatter::write_str(formatter, #expecting) - } - - #visit_seq - - #[inline] - fn visit_map<__A>(self, mut __map: __A) -> _serde::export::Result<Self::Value, __A::Error> - where __A: _serde::de::MapAccess<#delife> - { - #visit_map - } - } - - #fields_stmt - - #dispatch - } -} - -#[cfg(feature = "deserialize_in_place")] -fn deserialize_struct_in_place( - variant_ident: Option<&syn::Ident>, - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, - deserializer: Option<Tokens>, - untagged: Untagged, -) -> Fragment { - let is_enum = variant_ident.is_some(); - - let this = ¶ms.this; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - let expecting = match variant_ident { - Some(variant_ident) => format!("struct variant {}::{}", params.type_name(), variant_ident), - None => format!("struct {}", params.type_name()), - }; - - let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs)); - - let (field_visitor, fields_stmt, visit_map) = - deserialize_struct_in_place_visitor(params, fields, cattrs); - let field_visitor = Stmts(field_visitor); - let fields_stmt = Stmts(fields_stmt); - let visit_map = Stmts(visit_map); - - let visitor_expr = quote! { - __Visitor { - place: __place, - lifetime: _serde::export::PhantomData, - } - }; - let dispatch = if let Some(deserializer) = deserializer { - quote! { - _serde::Deserializer::deserialize_any(#deserializer, #visitor_expr) - } - } else if is_enum { - quote! { - _serde::de::VariantAccess::struct_variant(__variant, FIELDS, #visitor_expr) - } - } else { - let type_name = cattrs.name().deserialize_name(); - quote! { - _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, #visitor_expr) - } - }; - - let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); - let visitor_var = if all_skipped { - quote!(_) - } else { - quote!(mut __seq) - }; - - // untagged struct variants do not get a visit_seq method - let visit_seq = match untagged { - Untagged::Yes => None, - Untagged::No => Some(quote! { - #[inline] - fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error> - where __A: _serde::de::SeqAccess<#delife> - { - #visit_seq - } - }), - }; - - let in_place_impl_generics = de_impl_generics.in_place(); - let in_place_ty_generics = de_ty_generics.in_place(); - let place_life = place_lifetime(); - - quote_block! { - #field_visitor - - struct __Visitor #in_place_impl_generics #where_clause { - place: &#place_life mut #this #ty_generics, - lifetime: _serde::export::PhantomData<&#delife ()>, - } - - impl #in_place_impl_generics _serde::de::Visitor<#delife> for __Visitor #in_place_ty_generics #where_clause { - type Value = (); - - fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { - _serde::export::Formatter::write_str(formatter, #expecting) - } - - #visit_seq - - #[inline] - fn visit_map<__A>(self, mut __map: __A) -> _serde::export::Result<Self::Value, __A::Error> - where __A: _serde::de::MapAccess<#delife> - { - #visit_map - } - } - - #fields_stmt - - #dispatch - } -} - -fn deserialize_enum( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, -) -> Fragment { - match *cattrs.tag() { - attr::EnumTag::External => deserialize_externally_tagged_enum(params, variants, cattrs), - attr::EnumTag::Internal { ref tag } => { - deserialize_internally_tagged_enum(params, variants, cattrs, tag) - } - attr::EnumTag::Adjacent { - ref tag, - ref content, - } => deserialize_adjacently_tagged_enum(params, variants, cattrs, tag, content), - attr::EnumTag::None => deserialize_untagged_enum(params, variants, cattrs), - } -} - -fn deserialize_externally_tagged_enum( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, -) -> Fragment { - let this = ¶ms.this; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - let type_name = cattrs.name().deserialize_name(); - - let expecting = format!("enum {}", params.type_name()); - - let variant_names_idents: Vec<_> = variants - .iter() - .enumerate() - .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) - .map(|(i, variant)| (variant.attrs.name().deserialize_name(), field_i(i))) - .collect(); - - let variants_stmt = { - let variant_names = variant_names_idents.iter().map(|&(ref name, _)| name); - quote! { - const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ]; - } - }; - - let variant_visitor = Stmts(deserialize_generated_identifier( - variant_names_idents, - cattrs, - true, - )); - - // Match arms to extract a variant from a string - let variant_arms = variants - .iter() - .enumerate() - .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) - .map(|(i, variant)| { - let variant_name = field_i(i); - - let block = Match(deserialize_externally_tagged_variant( - params, - variant, - cattrs, - )); - - quote! { - (__Field::#variant_name, __variant) => #block - } - }); - - let all_skipped = variants - .iter() - .all(|variant| variant.attrs.skip_deserializing()); - let match_variant = if all_skipped { - // This is an empty enum like `enum Impossible {}` or an enum in which - // all variants have `#[serde(skip_deserializing)]`. - quote! { - // FIXME: Once we drop support for Rust 1.15: - // let _serde::export::Err(__err) = _serde::de::EnumAccess::variant::<__Field>(__data); - // _serde::export::Err(__err) - _serde::export::Result::map( - _serde::de::EnumAccess::variant::<__Field>(__data), - |(__impossible, _)| match __impossible {}) - } - } else { - quote! { - match try!(_serde::de::EnumAccess::variant(__data)) { - #(#variant_arms)* - } - } - }; - - quote_block! { - #variant_visitor - - struct __Visitor #de_impl_generics #where_clause { - marker: _serde::export::PhantomData<#this #ty_generics>, - lifetime: _serde::export::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { - type Value = #this #ty_generics; - - fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { - _serde::export::Formatter::write_str(formatter, #expecting) - } - - fn visit_enum<__A>(self, __data: __A) -> _serde::export::Result<Self::Value, __A::Error> - where __A: _serde::de::EnumAccess<#delife> - { - #match_variant - } - } - - #variants_stmt - - _serde::Deserializer::deserialize_enum(__deserializer, #type_name, VARIANTS, - __Visitor { - marker: _serde::export::PhantomData::<#this #ty_generics>, - lifetime: _serde::export::PhantomData, - }) - } -} - -fn deserialize_internally_tagged_enum( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, - tag: &str, -) -> Fragment { - let variant_names_idents: Vec<_> = variants - .iter() - .enumerate() - .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) - .map(|(i, variant)| (variant.attrs.name().deserialize_name(), field_i(i))) - .collect(); - - let variants_stmt = { - let variant_names = variant_names_idents.iter().map(|&(ref name, _)| name); - quote! { - const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ]; - } - }; - - let variant_visitor = Stmts(deserialize_generated_identifier( - variant_names_idents, - cattrs, - true, - )); - - // Match arms to extract a variant from a string - let variant_arms = variants - .iter() - .enumerate() - .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) - .map(|(i, variant)| { - let variant_name = field_i(i); - - let block = Match(deserialize_internally_tagged_variant( - params, - variant, - cattrs, - quote!( - _serde::private::de::ContentDeserializer::<__D::Error>::new(__tagged.content) - ), - )); - - quote! { - __Field::#variant_name => #block - } - }); - - quote_block! { - #variant_visitor - - #variants_stmt - - let __tagged = try!(_serde::Deserializer::deserialize_any( - __deserializer, - _serde::private::de::TaggedContentVisitor::<__Field>::new(#tag))); - - match __tagged.tag { - #(#variant_arms)* - } - } -} - -fn deserialize_adjacently_tagged_enum( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, - tag: &str, - content: &str, -) -> Fragment { - let this = ¶ms.this; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - let variant_names_idents: Vec<_> = variants - .iter() - .enumerate() - .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) - .map(|(i, variant)| (variant.attrs.name().deserialize_name(), field_i(i))) - .collect(); - - let variants_stmt = { - let variant_names = variant_names_idents.iter().map(|&(ref name, _)| name); - quote! { - const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ]; - } - }; - - let variant_visitor = Stmts(deserialize_generated_identifier( - variant_names_idents, - cattrs, - true, - )); - - let ref variant_arms: Vec<_> = variants - .iter() - .enumerate() - .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) - .map(|(i, variant)| { - let variant_index = field_i(i); - - let block = Match(deserialize_untagged_variant( - params, - variant, - cattrs, - quote!(__deserializer), - )); - - quote! { - __Field::#variant_index => #block - } - }) - .collect(); - - let expecting = format!("adjacently tagged enum {}", params.type_name()); - let type_name = cattrs.name().deserialize_name(); - let deny_unknown_fields = cattrs.deny_unknown_fields(); - - // If unknown fields are allowed, we pick the visitor that can step over - // those. Otherwise we pick the visitor that fails on unknown keys. - let field_visitor_ty = if deny_unknown_fields { - quote! { _serde::private::de::TagOrContentFieldVisitor } - } else { - quote! { _serde::private::de::TagContentOtherFieldVisitor } - }; - - let tag_or_content = quote! { - #field_visitor_ty { - tag: #tag, - content: #content, - } - }; - - fn is_unit(variant: &Variant) -> bool { - match variant.style { - Style::Unit => true, - Style::Struct | Style::Tuple | Style::Newtype => false, - } - } - - let mut missing_content = quote! { - _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#content)) - }; - if variants.iter().any(is_unit) { - let fallthrough = if variants.iter().all(is_unit) { - None - } else { - Some(quote! { - _ => #missing_content - }) - }; - let arms = variants - .iter() - .enumerate() - .filter(|&(_, variant)| !variant.attrs.skip_deserializing() && is_unit(variant)) - .map(|(i, variant)| { - let variant_index = field_i(i); - let variant_ident = &variant.ident; - quote! { - __Field::#variant_index => _serde::export::Ok(#this::#variant_ident), - } - }); - missing_content = quote! { - match __field { - #(#arms)* - #fallthrough - } - }; - } - - // Advance the map by one key, returning early in case of error. - let next_key = quote! { - try!(_serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)) - }; - - // When allowing unknown fields, we want to transparently step through keys - // we don't care about until we find `tag`, `content`, or run out of keys. - let next_relevant_key = if deny_unknown_fields { - next_key - } else { - quote!({ - let mut __rk : _serde::export::Option<_serde::private::de::TagOrContentField> = _serde::export::None; - while let _serde::export::Some(__k) = #next_key { - match __k { - _serde::private::de::TagContentOtherField::Other => { - try!(_serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)); - continue; - }, - _serde::private::de::TagContentOtherField::Tag => { - __rk = _serde::export::Some(_serde::private::de::TagOrContentField::Tag); - break; - } - _serde::private::de::TagContentOtherField::Content => { - __rk = _serde::export::Some(_serde::private::de::TagOrContentField::Content); - break; - } - } - } - - __rk - }) - }; - - // Step through remaining keys, looking for duplicates of previously-seen - // keys. When unknown fields are denied, any key that isn't a duplicate will - // at this point immediately produce an error. - let visit_remaining_keys = quote! { - match #next_relevant_key { - _serde::export::Some(_serde::private::de::TagOrContentField::Tag) => { - _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag)) - } - _serde::export::Some(_serde::private::de::TagOrContentField::Content) => { - _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content)) - } - _serde::export::None => _serde::export::Ok(__ret), - } - }; - - quote_block! { - #variant_visitor - - #variants_stmt - - struct __Seed #de_impl_generics #where_clause { - field: __Field, - marker: _serde::export::PhantomData<#this #ty_generics>, - lifetime: _serde::export::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Seed #de_ty_generics #where_clause { - type Value = #this #ty_generics; - - fn deserialize<__D>(self, __deserializer: __D) -> _serde::export::Result<Self::Value, __D::Error> - where __D: _serde::Deserializer<#delife> - { - match self.field { - #(#variant_arms)* - } - } - } - - struct __Visitor #de_impl_generics #where_clause { - marker: _serde::export::PhantomData<#this #ty_generics>, - lifetime: _serde::export::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { - type Value = #this #ty_generics; - - fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { - _serde::export::Formatter::write_str(formatter, #expecting) - } - - fn visit_map<__A>(self, mut __map: __A) -> _serde::export::Result<Self::Value, __A::Error> - where __A: _serde::de::MapAccess<#delife> - { - // Visit the first relevant key. - match #next_relevant_key { - // First key is the tag. - _serde::export::Some(_serde::private::de::TagOrContentField::Tag) => { - // Parse the tag. - let __field = try!(_serde::de::MapAccess::next_value(&mut __map)); - // Visit the second key. - match #next_relevant_key { - // Second key is a duplicate of the tag. - _serde::export::Some(_serde::private::de::TagOrContentField::Tag) => { - _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag)) - } - // Second key is the content. - _serde::export::Some(_serde::private::de::TagOrContentField::Content) => { - let __ret = try!(_serde::de::MapAccess::next_value_seed(&mut __map, - __Seed { - field: __field, - marker: _serde::export::PhantomData, - lifetime: _serde::export::PhantomData, - })); - // Visit remaining keys, looking for duplicates. - #visit_remaining_keys - } - // There is no second key; might be okay if the we have a unit variant. - _serde::export::None => #missing_content - } - } - // First key is the content. - _serde::export::Some(_serde::private::de::TagOrContentField::Content) => { - // Buffer up the content. - let __content = try!(_serde::de::MapAccess::next_value::<_serde::private::de::Content>(&mut __map)); - // Visit the second key. - match #next_relevant_key { - // Second key is the tag. - _serde::export::Some(_serde::private::de::TagOrContentField::Tag) => { - let __deserializer = _serde::private::de::ContentDeserializer::<__A::Error>::new(__content); - // Parse the tag. - let __ret = try!(match try!(_serde::de::MapAccess::next_value(&mut __map)) { - // Deserialize the buffered content now that we know the variant. - #(#variant_arms)* - }); - // Visit remaining keys, looking for duplicates. - #visit_remaining_keys - } - // Second key is a duplicate of the content. - _serde::export::Some(_serde::private::de::TagOrContentField::Content) => { - _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content)) - } - // There is no second key. - _serde::export::None => { - _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#tag)) - } - } - } - // There is no first key. - _serde::export::None => { - _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#tag)) - } - } - } - - fn visit_seq<__A>(self, mut __seq: __A) -> _serde::export::Result<Self::Value, __A::Error> - where __A: _serde::de::SeqAccess<#delife> - { - // Visit the first element - the tag. - match try!(_serde::de::SeqAccess::next_element(&mut __seq)) { - _serde::export::Some(__field) => { - // Visit the second element - the content. - match try!(_serde::de::SeqAccess::next_element_seed(&mut __seq, - __Seed { - field: __field, - marker: _serde::export::PhantomData, - lifetime: _serde::export::PhantomData, - })) { - _serde::export::Some(__ret) => _serde::export::Ok(__ret), - // There is no second element. - _serde::export::None => { - _serde::export::Err(_serde::de::Error::invalid_length(1, &self)) - } - } - } - // There is no first element. - _serde::export::None => { - _serde::export::Err(_serde::de::Error::invalid_length(0, &self)) - } - } - } - } - - const FIELDS: &'static [&'static str] = &[#tag, #content]; - _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, - __Visitor { - marker: _serde::export::PhantomData::<#this #ty_generics>, - lifetime: _serde::export::PhantomData, - }) - } -} - -fn deserialize_untagged_enum( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, -) -> Fragment { - let attempts = variants - .iter() - .filter(|variant| !variant.attrs.skip_deserializing()) - .map(|variant| { - Expr(deserialize_untagged_variant( - params, - variant, - cattrs, - quote!(_serde::private::de::ContentRefDeserializer::<__D::Error>::new(&__content)), - )) - }); - - // TODO this message could be better by saving the errors from the failed - // attempts. The heuristic used by TOML was to count the number of fields - // processed before an error, and use the error that happened after the - // largest number of fields. I'm not sure I like that. Maybe it would be - // better to save all the errors and combine them into one message that - // explains why none of the variants matched. - let fallthrough_msg = format!( - "data did not match any variant of untagged enum {}", - params.type_name() - ); - - quote_block! { - let __content = try!(<_serde::private::de::Content as _serde::Deserialize>::deserialize(__deserializer)); - - #( - if let _serde::export::Ok(__ok) = #attempts { - return _serde::export::Ok(__ok); - } - )* - - _serde::export::Err(_serde::de::Error::custom(#fallthrough_msg)) - } -} - -fn deserialize_externally_tagged_variant( - params: &Parameters, - variant: &Variant, - cattrs: &attr::Container, -) -> Fragment { - if let Some(path) = variant.attrs.deserialize_with() { - let (wrapper, wrapper_ty, unwrap_fn) = - wrap_deserialize_variant_with(params, &variant, path); - return quote_block! { - #wrapper - _serde::export::Result::map( - _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), #unwrap_fn) - }; - } - - let variant_ident = &variant.ident; - - match variant.style { - Style::Unit => { - let this = ¶ms.this; - quote_block! { - try!(_serde::de::VariantAccess::unit_variant(__variant)); - _serde::export::Ok(#this::#variant_ident) - } - } - Style::Newtype => { - deserialize_externally_tagged_newtype_variant(variant_ident, params, &variant.fields[0]) - } - Style::Tuple => { - deserialize_tuple(Some(variant_ident), params, &variant.fields, cattrs, None) - } - Style::Struct => deserialize_struct( - Some(variant_ident), - params, - &variant.fields, - cattrs, - None, - Untagged::No, - ), - } -} - -fn deserialize_internally_tagged_variant( - params: &Parameters, - variant: &Variant, - cattrs: &attr::Container, - deserializer: Tokens, -) -> Fragment { - if variant.attrs.deserialize_with().is_some() { - return deserialize_untagged_variant(params, variant, cattrs, deserializer); - } - - let variant_ident = &variant.ident; - - match variant.style { - Style::Unit => { - let this = ¶ms.this; - let type_name = params.type_name(); - let variant_name = variant.ident.as_ref(); - quote_block! { - try!(_serde::Deserializer::deserialize_any(#deserializer, _serde::private::de::InternallyTaggedUnitVisitor::new(#type_name, #variant_name))); - _serde::export::Ok(#this::#variant_ident) - } - } - Style::Newtype => deserialize_untagged_newtype_variant( - variant_ident, - params, - &variant.fields[0], - deserializer, - ), - Style::Struct => deserialize_struct( - Some(variant_ident), - params, - &variant.fields, - cattrs, - Some(deserializer), - Untagged::No, - ), - Style::Tuple => unreachable!("checked in serde_derive_internals"), - } -} - -fn deserialize_untagged_variant( - params: &Parameters, - variant: &Variant, - cattrs: &attr::Container, - deserializer: Tokens, -) -> Fragment { - if let Some(path) = variant.attrs.deserialize_with() { - let (wrapper, wrapper_ty, unwrap_fn) = - wrap_deserialize_variant_with(params, &variant, path); - return quote_block! { - #wrapper - _serde::export::Result::map( - <#wrapper_ty as _serde::Deserialize>::deserialize(#deserializer), #unwrap_fn) - }; - } - - let variant_ident = &variant.ident; - - match variant.style { - Style::Unit => { - let this = ¶ms.this; - let type_name = params.type_name(); - let variant_name = variant.ident.as_ref(); - quote_expr! { - _serde::export::Result::map( - _serde::Deserializer::deserialize_any( - #deserializer, - _serde::private::de::UntaggedUnitVisitor::new(#type_name, #variant_name) - ), - |()| #this::#variant_ident) - } - } - Style::Newtype => deserialize_untagged_newtype_variant( - variant_ident, - params, - &variant.fields[0], - deserializer, - ), - Style::Tuple => deserialize_tuple( - Some(variant_ident), - params, - &variant.fields, - cattrs, - Some(deserializer), - ), - Style::Struct => deserialize_struct( - Some(variant_ident), - params, - &variant.fields, - cattrs, - Some(deserializer), - Untagged::Yes, - ), - } -} - -fn deserialize_externally_tagged_newtype_variant( - variant_ident: &syn::Ident, - params: &Parameters, - field: &Field, -) -> Fragment { - let this = ¶ms.this; - match field.attrs.deserialize_with() { - None => { - let field_ty = &field.ty; - quote_expr! { - _serde::export::Result::map( - _serde::de::VariantAccess::newtype_variant::<#field_ty>(__variant), - #this::#variant_ident) - } - } - Some(path) => { - let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); - quote_block! { - #wrapper - _serde::export::Result::map( - _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), - |__wrapper| #this::#variant_ident(__wrapper.value)) - } - } - } -} - -fn deserialize_untagged_newtype_variant( - variant_ident: &syn::Ident, - params: &Parameters, - field: &Field, - deserializer: Tokens, -) -> Fragment { - let this = ¶ms.this; - match field.attrs.deserialize_with() { - None => { - let field_ty = &field.ty; - quote_expr! { - _serde::export::Result::map( - <#field_ty as _serde::Deserialize>::deserialize(#deserializer), - #this::#variant_ident) - } - } - Some(path) => { - let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); - quote_block! { - #wrapper - _serde::export::Result::map( - <#wrapper_ty as _serde::Deserialize>::deserialize(#deserializer), - |__wrapper| #this::#variant_ident(__wrapper.value)) - } - } - } -} - -fn deserialize_generated_identifier( - fields: Vec<(String, Ident)>, - cattrs: &attr::Container, - is_variant: bool, -) -> Fragment { - let this = quote!(__Field); - let field_idents: &Vec<_> = &fields.iter().map(|&(_, ref ident)| ident).collect(); - - let (ignore_variant, fallthrough) = if is_variant || cattrs.deny_unknown_fields() { - (None, None) - } else { - let ignore_variant = quote!(__ignore,); - let fallthrough = quote!(_serde::export::Ok(__Field::__ignore)); - (Some(ignore_variant), Some(fallthrough)) - }; - - let visitor_impl = Stmts(deserialize_identifier( - this, - &fields, - is_variant, - fallthrough, - )); - - quote_block! { - #[allow(non_camel_case_types)] - enum __Field { - #(#field_idents,)* - #ignore_variant - } - - struct __FieldVisitor; - - impl<'de> _serde::de::Visitor<'de> for __FieldVisitor { - type Value = __Field; - - #visitor_impl - } - - impl<'de> _serde::Deserialize<'de> for __Field { - #[inline] - fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error> - where __D: _serde::Deserializer<'de> - { - _serde::Deserializer::deserialize_identifier(__deserializer, __FieldVisitor) - } - } - } -} - -fn deserialize_custom_identifier( - params: &Parameters, - variants: &[Variant], - cattrs: &attr::Container, -) -> Fragment { - let is_variant = match cattrs.identifier() { - attr::Identifier::Variant => true, - attr::Identifier::Field => false, - attr::Identifier::No => unreachable!(), - }; - - let this = ¶ms.this; - let this = quote!(#this); - - let (ordinary, fallthrough) = if let Some(last) = variants.last() { - let last_ident = &last.ident; - if last.attrs.other() { - let ordinary = &variants[..variants.len() - 1]; - let fallthrough = quote!(_serde::export::Ok(#this::#last_ident)); - (ordinary, Some(fallthrough)) - } else if let Style::Newtype = last.style { - let ordinary = &variants[..variants.len() - 1]; - let deserializer = quote!(_serde::private::de::IdentifierDeserializer::from(__value)); - let fallthrough = quote! { - _serde::export::Result::map( - _serde::Deserialize::deserialize(#deserializer), - #this::#last_ident) - }; - (ordinary, Some(fallthrough)) - } else { - (variants, None) - } - } else { - (variants, None) - }; - - let names_idents: Vec<_> = ordinary - .iter() - .map(|variant| { - ( - variant.attrs.name().deserialize_name(), - variant.ident.clone(), - ) - }) - .collect(); - - let names = names_idents.iter().map(|&(ref name, _)| name); - - let names_const = if fallthrough.is_some() { - None - } else if is_variant { - let variants = quote! { - const VARIANTS: &'static [&'static str] = &[ #(#names),* ]; - }; - Some(variants) - } else { - let fields = quote! { - const FIELDS: &'static [&'static str] = &[ #(#names),* ]; - }; - Some(fields) - }; - - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - let visitor_impl = Stmts(deserialize_identifier( - this.clone(), - &names_idents, - is_variant, - fallthrough, - )); - - quote_block! { - #names_const - - struct __FieldVisitor #de_impl_generics #where_clause { - marker: _serde::export::PhantomData<#this #ty_generics>, - lifetime: _serde::export::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::de::Visitor<#delife> for __FieldVisitor #de_ty_generics #where_clause { - type Value = #this #ty_generics; - - #visitor_impl - } - - let __visitor = __FieldVisitor { - marker: _serde::export::PhantomData::<#this #ty_generics>, - lifetime: _serde::export::PhantomData, - }; - _serde::Deserializer::deserialize_identifier(__deserializer, __visitor) - } -} - -fn deserialize_identifier( - this: Tokens, - fields: &[(String, Ident)], - is_variant: bool, - fallthrough: Option<Tokens>, -) -> Fragment { - let field_strs = fields.iter().map(|&(ref name, _)| name); - let field_bytes = fields.iter().map(|&(ref name, _)| quote::ByteStr(name)); - - let constructors: &Vec<_> = &fields - .iter() - .map(|&(_, ref ident)| quote!(#this::#ident)) - .collect(); - - let expecting = if is_variant { - "variant identifier" - } else { - "field identifier" - }; - - let index_expecting = if is_variant { "variant" } else { "field" }; - - let variant_indices = 0u64..; - let fallthrough_msg = format!("{} index 0 <= i < {}", index_expecting, fields.len()); - let visit_index = quote! { - fn visit_u64<__E>(self, __value: u64) -> _serde::export::Result<Self::Value, __E> - where __E: _serde::de::Error - { - match __value { - #( - #variant_indices => _serde::export::Ok(#constructors), - )* - _ => _serde::export::Err(_serde::de::Error::invalid_value( - _serde::de::Unexpected::Unsigned(__value), - &#fallthrough_msg)) - } - } - }; - - let bytes_to_str = if fallthrough.is_some() { - None - } else { - let conversion = quote! { - let __value = &_serde::export::from_utf8_lossy(__value); - }; - Some(conversion) - }; - - let fallthrough_arm = if let Some(fallthrough) = fallthrough { - fallthrough - } else if is_variant { - quote! { - _serde::export::Err(_serde::de::Error::unknown_variant(__value, VARIANTS)) - } - } else { - quote! { - _serde::export::Err(_serde::de::Error::unknown_field(__value, FIELDS)) - } - }; - - quote_block! { - fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { - _serde::export::Formatter::write_str(formatter, #expecting) - } - - #visit_index - - fn visit_str<__E>(self, __value: &str) -> _serde::export::Result<Self::Value, __E> - where __E: _serde::de::Error - { - match __value { - #( - #field_strs => _serde::export::Ok(#constructors), - )* - _ => #fallthrough_arm - } - } - - fn visit_bytes<__E>(self, __value: &[u8]) -> _serde::export::Result<Self::Value, __E> - where __E: _serde::de::Error - { - match __value { - #( - #field_bytes => _serde::export::Ok(#constructors), - )* - _ => { - #bytes_to_str - #fallthrough_arm - } - } - } - } -} - -fn deserialize_struct_visitor( - struct_path: Tokens, - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, -) -> (Fragment, Fragment, Fragment) { - let field_names_idents: Vec<_> = fields - .iter() - .enumerate() - .filter(|&(_, field)| !field.attrs.skip_deserializing()) - .map(|(i, field)| (field.attrs.name().deserialize_name(), field_i(i))) - .collect(); - - let fields_stmt = { - let field_names = field_names_idents.iter().map(|&(ref name, _)| name); - quote_block! { - const FIELDS: &'static [&'static str] = &[ #(#field_names),* ]; - } - }; - - let field_visitor = deserialize_generated_identifier(field_names_idents, cattrs, false); - - let visit_map = deserialize_map(struct_path, params, fields, cattrs); - - (field_visitor, fields_stmt, visit_map) -} - -fn deserialize_map( - struct_path: Tokens, - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, -) -> Fragment { - // Create the field names for the fields. - let fields_names: Vec<_> = fields - .iter() - .enumerate() - .map(|(i, field)| (field, field_i(i))) - .collect(); - - // Declare each field that will be deserialized. - let let_values = fields_names - .iter() - .filter(|&&(field, _)| !field.attrs.skip_deserializing()) - .map(|&(field, ref name)| { - let field_ty = &field.ty; - quote! { - let mut #name: _serde::export::Option<#field_ty> = _serde::export::None; - } - }); - - // Match arms to extract a value for a field. - let value_arms = fields_names - .iter() - .filter(|&&(field, _)| !field.attrs.skip_deserializing()) - .map(|&(field, ref name)| { - let deser_name = field.attrs.name().deserialize_name(); - - let visit = match field.attrs.deserialize_with() { - None => { - let field_ty = &field.ty; - quote! { - try!(_serde::de::MapAccess::next_value::<#field_ty>(&mut __map)) - } - } - Some(path) => { - let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); - quote!({ - #wrapper - try!(_serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map)).value - }) - } - }; - quote! { - __Field::#name => { - if _serde::export::Option::is_some(&#name) { - return _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name)); - } - #name = _serde::export::Some(#visit); - } - } - }); - - // Visit ignored values to consume them - let ignored_arm = if cattrs.deny_unknown_fields() { - None - } else { - Some(quote! { - _ => { let _ = try!(_serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)); } - }) - }; - - let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); - let match_keys = if cattrs.deny_unknown_fields() && all_skipped { - quote! { - // FIXME: Once we drop support for Rust 1.15: - // let _serde::export::None::<__Field> = try!(_serde::de::MapAccess::next_key(&mut __map)); - _serde::export::Option::map( - try!(_serde::de::MapAccess::next_key::<__Field>(&mut __map)), - |__impossible| match __impossible {}); - } - } else { - quote! { - while let _serde::export::Some(__key) = try!(_serde::de::MapAccess::next_key::<__Field>(&mut __map)) { - match __key { - #(#value_arms)* - #ignored_arm - } - } - } - }; - - let extract_values = fields_names - .iter() - .filter(|&&(field, _)| !field.attrs.skip_deserializing()) - .map(|&(field, ref name)| { - let missing_expr = Match(expr_is_missing(&field, cattrs)); - - quote! { - let #name = match #name { - _serde::export::Some(#name) => #name, - _serde::export::None => #missing_expr - }; - } - }); - - let result = fields_names.iter().map(|&(field, ref name)| { - let ident = field.ident.clone().expect("struct contains unnamed fields"); - if field.attrs.skip_deserializing() { - let value = Expr(expr_is_missing(&field, cattrs)); - quote!(#ident: #value) - } else { - quote!(#ident: #name) - } - }); - - let let_default = match *cattrs.default() { - attr::Default::Default => Some(quote!( - let __default: Self::Value = _serde::export::Default::default(); - )), - attr::Default::Path(ref path) => Some(quote!( - let __default: Self::Value = #path(); - )), - attr::Default::None => { - // We don't need the default value, to prevent an unused variable warning - // we'll leave the line empty. - None - } - }; - - let mut result = quote!(#struct_path { #(#result),* }); - if params.has_getter { - let this = ¶ms.this; - result = quote! { - _serde::export::Into::<#this>::into(#result) - }; - } - - quote_block! { - #(#let_values)* - - #match_keys - - #let_default - - #(#extract_values)* - - _serde::export::Ok(#result) - } -} - -#[cfg(feature = "deserialize_in_place")] -fn deserialize_struct_in_place_visitor( - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, -) -> (Fragment, Fragment, Fragment) { - let field_names_idents: Vec<_> = fields - .iter() - .enumerate() - .filter(|&(_, field)| !field.attrs.skip_deserializing()) - .map(|(i, field)| (field.attrs.name().deserialize_name(), field_i(i))) - .collect(); - - let fields_stmt = { - let field_names = field_names_idents.iter().map(|&(ref name, _)| name); - quote_block! { - const FIELDS: &'static [&'static str] = &[ #(#field_names),* ]; - } - }; - - let field_visitor = deserialize_generated_identifier(field_names_idents, cattrs, false); - - let visit_map = deserialize_map_in_place(params, fields, cattrs); - - (field_visitor, fields_stmt, visit_map) -} - -#[cfg(feature = "deserialize_in_place")] -fn deserialize_map_in_place( - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, -) -> Fragment { - // Create the field names for the fields. - let fields_names: Vec<_> = fields - .iter() - .enumerate() - .map(|(i, field)| (field, field_i(i))) - .collect(); - - // For deserialize_in_place, declare booleans for each field that will be deserialized. - let let_flags = fields_names - .iter() - .filter(|&&(field, _)| !field.attrs.skip_deserializing()) - .map(|&(_, ref name)| { - quote! { - let mut #name: bool = false; - } - }); - - // Match arms to extract a value for a field. - let value_arms_from = fields_names - .iter() - .filter(|&&(field, _)| !field.attrs.skip_deserializing()) - .map(|&(field, ref name)| { - let deser_name = field.attrs.name().deserialize_name(); - let field_name = &field.ident; - - let visit = match field.attrs.deserialize_with() { - None => { - quote! { - try!(_serde::de::MapAccess::next_value_seed(&mut __map, _serde::private::de::InPlaceSeed(&mut self.place.#field_name))) - } - } - Some(path) => { - let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); - quote!({ - #wrapper - self.place.#field_name = try!(_serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map)).value - }) - } - }; - quote! { - __Field::#name => { - if #name { - return _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name)); - } - #visit; - #name = true; - } - } - }); - - // Visit ignored values to consume them - let ignored_arm = if cattrs.deny_unknown_fields() { - None - } else { - Some(quote! { - _ => { let _ = try!(_serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)); } - }) - }; - - let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); - - let match_keys = if cattrs.deny_unknown_fields() && all_skipped { - quote! { - // FIXME: Once we drop support for Rust 1.15: - // let _serde::export::None::<__Field> = try!(_serde::de::MapAccess::next_key(&mut __map)); - _serde::export::Option::map( - try!(_serde::de::MapAccess::next_key::<__Field>(&mut __map)), - |__impossible| match __impossible {}); - } - } else { - quote! { - while let _serde::export::Some(__key) = try!(_serde::de::MapAccess::next_key::<__Field>(&mut __map)) { - match __key { - #(#value_arms_from)* - #ignored_arm - } - } - } - }; - - let check_flags = fields_names - .iter() - .filter(|&&(field, _)| !field.attrs.skip_deserializing()) - .map(|&(field, ref name)| { - let missing_expr = expr_is_missing(&field, cattrs); - // If missing_expr unconditionally returns an error, don't try - // to assign its value to self.place. Maybe this could be handled - // more elegantly. - if missing_expr.as_ref().as_str().starts_with("return ") { - let missing_expr = Stmts(missing_expr); - quote! { - if !#name { - #missing_expr; - } - } - } else { - let field_name = &field.ident; - let missing_expr = Expr(missing_expr); - quote! { - if !#name { - self.place.#field_name = #missing_expr; - }; - } - } - }); - - let this = ¶ms.this; - let (_, _, ty_generics, _) = split_with_de_lifetime(params); - - let let_default = match *cattrs.default() { - attr::Default::Default => Some(quote!( - let __default: #this #ty_generics = _serde::export::Default::default(); - )), - attr::Default::Path(ref path) => Some(quote!( - let __default: #this #ty_generics = #path(); - )), - attr::Default::None => { - // We don't need the default value, to prevent an unused variable warning - // we'll leave the line empty. - None - } - }; - - quote_block! { - #(#let_flags)* - - #match_keys - - #let_default - - #(#check_flags)* - - _serde::export::Ok(()) - } -} - -fn field_i(i: usize) -> Ident { - Ident::new(format!("__field{}", i)) -} - -/// This function wraps the expression in `#[serde(deserialize_with = "...")]` -/// in a trait to prevent it from accessing the internal `Deserialize` state. -fn wrap_deserialize_with( - params: &Parameters, - value_ty: Tokens, - deserialize_with: &syn::Path, -) -> (Tokens, Tokens) { - let this = ¶ms.this; - let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = - split_with_de_lifetime(params); - let delife = params.borrowed.de_lifetime(); - - let wrapper = quote! { - struct __DeserializeWith #de_impl_generics #where_clause { - value: #value_ty, - phantom: _serde::export::PhantomData<#this #ty_generics>, - lifetime: _serde::export::PhantomData<&#delife ()>, - } - - impl #de_impl_generics _serde::Deserialize<#delife> for __DeserializeWith #de_ty_generics #where_clause { - fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error> - where __D: _serde::Deserializer<#delife> - { - _serde::export::Ok(__DeserializeWith { - value: try!(#deserialize_with(__deserializer)), - phantom: _serde::export::PhantomData, - lifetime: _serde::export::PhantomData, - }) - } - } - }; - - let wrapper_ty = quote!(__DeserializeWith #de_ty_generics); - - (wrapper, wrapper_ty) -} - -fn wrap_deserialize_field_with( - params: &Parameters, - field_ty: &syn::Ty, - deserialize_with: &syn::Path, -) -> (Tokens, Tokens) { - wrap_deserialize_with(params, quote!(#field_ty), deserialize_with) -} - -fn wrap_deserialize_variant_with( - params: &Parameters, - variant: &Variant, - deserialize_with: &syn::Path, -) -> (Tokens, Tokens, Tokens) { - let this = ¶ms.this; - let variant_ident = &variant.ident; - - let field_tys = variant.fields.iter().map(|field| field.ty); - let (wrapper, wrapper_ty) = - wrap_deserialize_with(params, quote!((#(#field_tys),*)), deserialize_with); - - let field_access = (0..variant.fields.len()).map(|n| Ident::new(format!("{}", n))); - let unwrap_fn = match variant.style { - Style::Struct => { - let field_idents = variant - .fields - .iter() - .map(|field| field.ident.as_ref().unwrap()); - quote!({ - |__wrap| { - #this::#variant_ident { #(#field_idents: __wrap.value.#field_access),* } - } - }) - } - Style::Tuple => quote!({ - |__wrap| { - #this::#variant_ident(#(__wrap.value.#field_access),*) - } - }), - Style::Newtype => quote!({ - |__wrap| { - #this::#variant_ident(__wrap.value) - } - }), - Style::Unit => quote!({ - |__wrap| { #this::#variant_ident } - }), - }; - - (wrapper, wrapper_ty, unwrap_fn) -} - -fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment { - match *field.attrs.default() { - attr::Default::Default => { - return quote_expr!(_serde::export::Default::default()); - } - attr::Default::Path(ref path) => { - return quote_expr!(#path()); - } - attr::Default::None => { /* below */ } - } - - match *cattrs.default() { - attr::Default::Default | attr::Default::Path(_) => { - let ident = &field.ident; - return quote_expr!(__default.#ident); - } - attr::Default::None => { /* below */ } - } - - let name = field.attrs.name().deserialize_name(); - match field.attrs.deserialize_with() { - None => { - quote_expr! { - try!(_serde::private::de::missing_field(#name)) - } - } - Some(_) => { - quote_expr! { - return _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#name)) - } - } - } -} - -struct DeImplGenerics<'a>(&'a Parameters); -#[cfg(feature = "deserialize_in_place")] -struct InPlaceImplGenerics<'a>(&'a Parameters); - -impl<'a> ToTokens for DeImplGenerics<'a> { - fn to_tokens(&self, tokens: &mut Tokens) { - let mut generics = self.0.generics.clone(); - if let Some(de_lifetime) = self.0.borrowed.de_lifetime_def() { - generics.lifetimes.insert(0, de_lifetime); - } - let (impl_generics, _, _) = generics.split_for_impl(); - impl_generics.to_tokens(tokens); - } -} - -#[cfg(feature = "deserialize_in_place")] -impl<'a> ToTokens for InPlaceImplGenerics<'a> { - fn to_tokens(&self, tokens: &mut Tokens) { - let place_lifetime = place_lifetime(); - let mut generics = self.0.generics.clone(); - - // Add lifetime for `&'place mut Self, and `'a: 'place` - for lifetime in &mut generics.lifetimes { - lifetime.bounds.push(place_lifetime.lifetime.clone()); - } - for generic in &mut generics.ty_params { - generic - .bounds - .push(syn::TyParamBound::Region(place_lifetime.lifetime.clone())); - } - generics.lifetimes.insert(0, place_lifetime); - if let Some(de_lifetime) = self.0.borrowed.de_lifetime_def() { - generics.lifetimes.insert(0, de_lifetime); - } - let (impl_generics, _, _) = generics.split_for_impl(); - impl_generics.to_tokens(tokens); - } -} - -#[cfg(feature = "deserialize_in_place")] -impl<'a> DeImplGenerics<'a> { - fn in_place(self) -> InPlaceImplGenerics<'a> { - InPlaceImplGenerics(self.0) - } -} - -struct DeTyGenerics<'a>(&'a Parameters); -#[cfg(feature = "deserialize_in_place")] -struct InPlaceTyGenerics<'a>(&'a Parameters); - -impl<'a> ToTokens for DeTyGenerics<'a> { - fn to_tokens(&self, tokens: &mut Tokens) { - let mut generics = self.0.generics.clone(); - if self.0.borrowed.de_lifetime_def().is_some() { - generics.lifetimes.insert(0, syn::LifetimeDef::new("'de")); - } - let (_, ty_generics, _) = generics.split_for_impl(); - ty_generics.to_tokens(tokens); - } -} - -#[cfg(feature = "deserialize_in_place")] -impl<'a> ToTokens for InPlaceTyGenerics<'a> { - fn to_tokens(&self, tokens: &mut Tokens) { - let mut generics = self.0.generics.clone(); - generics.lifetimes.insert(0, place_lifetime()); - - if self.0.borrowed.de_lifetime_def().is_some() { - generics.lifetimes.insert(0, syn::LifetimeDef::new("'de")); - } - let (_, ty_generics, _) = generics.split_for_impl(); - ty_generics.to_tokens(tokens); - } -} - -#[cfg(feature = "deserialize_in_place")] -impl<'a> DeTyGenerics<'a> { - fn in_place(self) -> InPlaceTyGenerics<'a> { - InPlaceTyGenerics(self.0) - } -} - -#[cfg(feature = "deserialize_in_place")] -fn place_lifetime() -> syn::LifetimeDef { - syn::LifetimeDef::new("'place") -} - -fn split_with_de_lifetime( - params: &Parameters, -) -> ( - DeImplGenerics, - DeTyGenerics, - syn::TyGenerics, - &syn::WhereClause, -) { - let de_impl_generics = DeImplGenerics(¶ms); - let de_ty_generics = DeTyGenerics(¶ms); - let (_, ty_generics, where_clause) = params.generics.split_for_impl(); - (de_impl_generics, de_ty_generics, ty_generics, where_clause) -} diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.27/src/fragment.rs cargo-0.26.0/vendor/serde_derive-1.0.27/src/fragment.rs --- cargo-0.25.0/vendor/serde_derive-1.0.27/src/fragment.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.27/src/fragment.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,84 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use quote::{ToTokens, Tokens}; - -pub enum Fragment { - /// Tokens that can be used as an expression. - Expr(Tokens), - /// Tokens that can be used inside a block. The surrounding curly braces are - /// not part of these tokens. - Block(Tokens), -} - -macro_rules! quote_expr { - ($($tt:tt)*) => { - $crate::fragment::Fragment::Expr(quote!($($tt)*)) - } -} - -macro_rules! quote_block { - ($($tt:tt)*) => { - $crate::fragment::Fragment::Block(quote!($($tt)*)) - } -} - -/// Interpolate a fragment in place of an expression. This involves surrounding -/// Block fragments in curly braces. -pub struct Expr(pub Fragment); -impl ToTokens for Expr { - fn to_tokens(&self, out: &mut Tokens) { - match self.0 { - Fragment::Expr(ref expr) => expr.to_tokens(out), - Fragment::Block(ref block) => { - out.append("{"); - block.to_tokens(out); - out.append("}"); - } - } - } -} - -/// Interpolate a fragment as the statements of a block. -pub struct Stmts(pub Fragment); -impl ToTokens for Stmts { - fn to_tokens(&self, out: &mut Tokens) { - match self.0 { - Fragment::Expr(ref expr) => expr.to_tokens(out), - Fragment::Block(ref block) => block.to_tokens(out), - } - } -} - -/// Interpolate a fragment as the value part of a `match` expression. This -/// involves putting a comma after expressions and curly braces around blocks. -pub struct Match(pub Fragment); -impl ToTokens for Match { - fn to_tokens(&self, out: &mut Tokens) { - match self.0 { - Fragment::Expr(ref expr) => { - expr.to_tokens(out); - out.append(","); - } - Fragment::Block(ref block) => { - out.append("{"); - block.to_tokens(out); - out.append("}"); - } - } - } -} - -impl AsRef<Tokens> for Fragment { - fn as_ref(&self) -> &Tokens { - match *self { - Fragment::Expr(ref expr) => expr, - Fragment::Block(ref block) => block, - } - } -} diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.27/src/lib.rs cargo-0.26.0/vendor/serde_derive-1.0.27/src/lib.rs --- cargo-0.25.0/vendor/serde_derive-1.0.27/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.27/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,64 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! This crate provides Serde's two derive macros. -//! -//! ```rust -//! # #[macro_use] -//! # extern crate serde_derive; -//! # -//! #[derive(Serialize, Deserialize)] -//! # struct S; -//! # -//! # fn main() {} -//! ``` -//! -//! Please refer to [https://serde.rs/derive.html] for how to set this up. -//! -//! [https://serde.rs/derive.html]: https://serde.rs/derive.html - -#![doc(html_root_url = "https://docs.rs/serde_derive/1.0.27")] -#![cfg_attr(feature = "cargo-clippy", allow(too_many_arguments))] -#![cfg_attr(feature = "cargo-clippy", allow(used_underscore_binding))] -// The `quote!` macro requires deep recursion. -#![recursion_limit = "192"] - -#[macro_use] -extern crate quote; -extern crate syn; - -extern crate serde_derive_internals as internals; - -extern crate proc_macro; -use proc_macro::TokenStream; - -#[macro_use] -mod bound; -#[macro_use] -mod fragment; - -mod ser; -mod de; - -#[proc_macro_derive(Serialize, attributes(serde))] -pub fn derive_serialize(input: TokenStream) -> TokenStream { - let input = syn::parse_derive_input(&input.to_string()).unwrap(); - match ser::expand_derive_serialize(&input) { - Ok(expanded) => expanded.parse().unwrap(), - Err(msg) => panic!(msg), - } -} - -#[proc_macro_derive(Deserialize, attributes(serde))] -pub fn derive_deserialize(input: TokenStream) -> TokenStream { - let input = syn::parse_derive_input(&input.to_string()).unwrap(); - match de::expand_derive_deserialize(&input) { - Ok(expanded) => expanded.parse().unwrap(), - Err(msg) => panic!(msg), - } -} diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.27/src/ser.rs cargo-0.26.0/vendor/serde_derive-1.0.27/src/ser.rs --- cargo-0.25.0/vendor/serde_derive-1.0.27/src/ser.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.27/src/ser.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1003 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use syn::{self, Ident}; -use quote::Tokens; - -use bound; -use fragment::{Fragment, Match, Stmts}; -use internals::ast::{Body, Container, Field, Style, Variant}; -use internals::{attr, Ctxt}; - -use std::u32; - -pub fn expand_derive_serialize(input: &syn::DeriveInput) -> Result<Tokens, String> { - let ctxt = Ctxt::new(); - let cont = Container::from_ast(&ctxt, input); - precondition(&ctxt, &cont); - try!(ctxt.check()); - - let ident = &cont.ident; - let params = Parameters::new(&cont); - let (impl_generics, ty_generics, where_clause) = params.generics.split_for_impl(); - let dummy_const = Ident::new(format!("_IMPL_SERIALIZE_FOR_{}", ident)); - let body = Stmts(serialize_body(&cont, ¶ms)); - - let impl_block = if let Some(remote) = cont.attrs.remote() { - let vis = &input.vis; - quote! { - impl #impl_generics #ident #ty_generics #where_clause { - #vis fn serialize<__S>(__self: &#remote #ty_generics, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error> - where __S: _serde::Serializer - { - #body - } - } - } - } else { - quote! { - #[automatically_derived] - impl #impl_generics _serde::Serialize for #ident #ty_generics #where_clause { - fn serialize<__S>(&self, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error> - where __S: _serde::Serializer - { - #body - } - } - } - }; - - let generated = quote! { - #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] - const #dummy_const: () = { - extern crate serde as _serde; - #impl_block - }; - }; - Ok(generated) -} - -fn precondition(cx: &Ctxt, cont: &Container) { - match cont.attrs.identifier() { - attr::Identifier::No => {} - attr::Identifier::Field => { - cx.error("field identifiers cannot be serialized"); - } - attr::Identifier::Variant => { - cx.error("variant identifiers cannot be serialized"); - } - } -} - -struct Parameters { - /// Variable holding the value being serialized. Either `self` for local - /// types or `__self` for remote types. - self_var: Ident, - - /// Path to the type the impl is for. Either a single `Ident` for local - /// types or `some::remote::Ident` for remote types. Does not include - /// generic parameters. - this: syn::Path, - - /// Generics including any explicit and inferred bounds for the impl. - generics: syn::Generics, - - /// Type has a `serde(remote = "...")` attribute. - is_remote: bool, -} - -impl Parameters { - fn new(cont: &Container) -> Self { - let is_remote = cont.attrs.remote().is_some(); - let self_var = if is_remote { - Ident::new("__self") - } else { - Ident::new("self") - }; - - let this = match cont.attrs.remote() { - Some(remote) => remote.clone(), - None => cont.ident.clone().into(), - }; - - let generics = build_generics(cont); - - Parameters { - self_var: self_var, - this: this, - generics: generics, - is_remote: is_remote, - } - } - - /// Type name to use in error messages and `&'static str` arguments to - /// various Serializer methods. - fn type_name(&self) -> &str { - self.this.segments.last().unwrap().ident.as_ref() - } -} - -// All the generics in the input, plus a bound `T: Serialize` for each generic -// field type that will be serialized by us. -fn build_generics(cont: &Container) -> syn::Generics { - let generics = bound::without_defaults(cont.generics); - - let generics = - bound::with_where_predicates_from_fields(cont, &generics, attr::Field::ser_bound); - - match cont.attrs.ser_bound() { - Some(predicates) => bound::with_where_predicates(&generics, predicates), - None => bound::with_bound( - cont, - &generics, - needs_serialize_bound, - &path!(_serde::Serialize), - ), - } -} - -// Fields with a `skip_serializing` or `serialize_with` attribute, or which -// belong to a variant with a `serialize_with` attribute, are not serialized by -// us so we do not generate a bound. Fields with a `bound` attribute specify -// their own bound so we do not generate one. All other fields may need a `T: -// Serialize` bound where T is the type of the field. -fn needs_serialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool { - !field.skip_serializing() && field.serialize_with().is_none() && field.ser_bound().is_none() - && variant.map_or(true, |variant| variant.serialize_with().is_none()) -} - -fn serialize_body(cont: &Container, params: &Parameters) -> Fragment { - if let Some(into_type) = cont.attrs.into_type() { - serialize_into(params, into_type) - } else { - match cont.body { - Body::Enum(ref variants) => serialize_enum(params, variants, &cont.attrs), - Body::Struct(Style::Struct, ref fields) => { - if fields.iter().any(|field| field.ident.is_none()) { - panic!("struct has unnamed fields"); - } - serialize_struct(params, fields, &cont.attrs) - } - Body::Struct(Style::Tuple, ref fields) => { - if fields.iter().any(|field| field.ident.is_some()) { - panic!("tuple struct has named fields"); - } - serialize_tuple_struct(params, fields, &cont.attrs) - } - Body::Struct(Style::Newtype, ref fields) => { - serialize_newtype_struct(params, &fields[0], &cont.attrs) - } - Body::Struct(Style::Unit, _) => serialize_unit_struct(&cont.attrs), - } - } -} - -fn serialize_into(params: &Parameters, into_type: &syn::Ty) -> Fragment { - let self_var = ¶ms.self_var; - quote_block! { - _serde::Serialize::serialize( - &_serde::export::Into::<#into_type>::into(_serde::export::Clone::clone(#self_var)), - __serializer) - } -} - -fn serialize_unit_struct(cattrs: &attr::Container) -> Fragment { - let type_name = cattrs.name().serialize_name(); - - quote_expr! { - _serde::Serializer::serialize_unit_struct(__serializer, #type_name) - } -} - -fn serialize_newtype_struct( - params: &Parameters, - field: &Field, - cattrs: &attr::Container, -) -> Fragment { - let type_name = cattrs.name().serialize_name(); - - let mut field_expr = get_field(params, field, 0); - if let Some(path) = field.attrs.serialize_with() { - field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr); - } - - quote_expr! { - _serde::Serializer::serialize_newtype_struct(__serializer, #type_name, #field_expr) - } -} - -fn serialize_tuple_struct( - params: &Parameters, - fields: &[Field], - cattrs: &attr::Container, -) -> Fragment { - let serialize_stmts = serialize_tuple_struct_visitor( - fields, - params, - false, - quote!(_serde::ser::SerializeTupleStruct::serialize_field), - ); - - let type_name = cattrs.name().serialize_name(); - let len = serialize_stmts.len(); - let let_mut = mut_if(len > 0); - - quote_block! { - let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_struct(__serializer, #type_name, #len)); - #(#serialize_stmts)* - _serde::ser::SerializeTupleStruct::end(__serde_state) - } -} - -fn serialize_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Container) -> Fragment { - assert!(fields.len() as u64 <= u32::MAX as u64); - - let serialize_fields = serialize_struct_visitor( - fields, - params, - false, - quote!(_serde::ser::SerializeStruct::serialize_field), - quote!(_serde::ser::SerializeStruct::skip_field), - ); - - let type_name = cattrs.name().serialize_name(); - - let mut serialized_fields = fields - .iter() - .filter(|&field| !field.attrs.skip_serializing()) - .peekable(); - - let let_mut = mut_if(serialized_fields.peek().is_some()); - - let len = serialized_fields - .map(|field| match field.attrs.skip_serializing_if() { - None => quote!(1), - Some(path) => { - let ident = field.ident.clone().expect("struct has unnamed fields"); - let field_expr = get_field(params, field, ident); - quote!(if #path(#field_expr) { 0 } else { 1 }) - } - }) - .fold(quote!(0), |sum, expr| quote!(#sum + #expr)); - - quote_block! { - let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct(__serializer, #type_name, #len)); - #(#serialize_fields)* - _serde::ser::SerializeStruct::end(__serde_state) - } -} - -fn serialize_enum(params: &Parameters, variants: &[Variant], cattrs: &attr::Container) -> Fragment { - assert!(variants.len() as u64 <= u32::MAX as u64); - - let self_var = ¶ms.self_var; - - let arms: Vec<_> = variants - .iter() - .enumerate() - .map(|(variant_index, variant)| { - serialize_variant(params, variant, variant_index as u32, cattrs) - }) - .collect(); - - quote_expr! { - match *#self_var { - #(#arms)* - } - } -} - -fn serialize_variant( - params: &Parameters, - variant: &Variant, - variant_index: u32, - cattrs: &attr::Container, -) -> Tokens { - let this = ¶ms.this; - let variant_ident = variant.ident.clone(); - - if variant.attrs.skip_serializing() { - let skipped_msg = format!( - "the enum variant {}::{} cannot be serialized", - params.type_name(), - variant_ident - ); - let skipped_err = quote! { - _serde::export::Err(_serde::ser::Error::custom(#skipped_msg)) - }; - let fields_pat = match variant.style { - Style::Unit => quote!(), - Style::Newtype | Style::Tuple => quote!((..)), - Style::Struct => quote!({ .. }), - }; - quote! { - #this::#variant_ident #fields_pat => #skipped_err, - } - } else { - // variant wasn't skipped - let case = match variant.style { - Style::Unit => { - quote! { - #this::#variant_ident - } - } - Style::Newtype => { - quote! { - #this::#variant_ident(ref __field0) - } - } - Style::Tuple => { - let field_names = - (0..variant.fields.len()).map(|i| Ident::new(format!("__field{}", i))); - quote! { - #this::#variant_ident(#(ref #field_names),*) - } - } - Style::Struct => { - let fields = variant - .fields - .iter() - .map(|f| f.ident.clone().expect("struct variant has unnamed fields")); - quote! { - #this::#variant_ident { #(ref #fields),* } - } - } - }; - - let body = Match(match *cattrs.tag() { - attr::EnumTag::External => { - serialize_externally_tagged_variant(params, variant, variant_index, cattrs) - } - attr::EnumTag::Internal { ref tag } => { - serialize_internally_tagged_variant(params, variant, cattrs, tag) - } - attr::EnumTag::Adjacent { - ref tag, - ref content, - } => serialize_adjacently_tagged_variant(params, variant, cattrs, tag, content), - attr::EnumTag::None => serialize_untagged_variant(params, variant, cattrs), - }); - - quote! { - #case => #body - } - } -} - -fn serialize_externally_tagged_variant( - params: &Parameters, - variant: &Variant, - variant_index: u32, - cattrs: &attr::Container, -) -> Fragment { - let type_name = cattrs.name().serialize_name(); - let variant_name = variant.attrs.name().serialize_name(); - - if let Some(path) = variant.attrs.serialize_with() { - let ser = wrap_serialize_variant_with(params, path, &variant); - return quote_expr! { - _serde::Serializer::serialize_newtype_variant( - __serializer, - #type_name, - #variant_index, - #variant_name, - #ser, - ) - }; - } - - match variant.style { - Style::Unit => { - quote_expr! { - _serde::Serializer::serialize_unit_variant( - __serializer, - #type_name, - #variant_index, - #variant_name, - ) - } - } - Style::Newtype => { - let field = &variant.fields[0]; - let mut field_expr = quote!(__field0); - if let Some(path) = field.attrs.serialize_with() { - field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr); - } - - quote_expr! { - _serde::Serializer::serialize_newtype_variant( - __serializer, - #type_name, - #variant_index, - #variant_name, - #field_expr, - ) - } - } - Style::Tuple => serialize_tuple_variant( - TupleVariant::ExternallyTagged { - type_name: type_name, - variant_index: variant_index, - variant_name: variant_name, - }, - params, - &variant.fields, - ), - Style::Struct => serialize_struct_variant( - StructVariant::ExternallyTagged { - variant_index: variant_index, - variant_name: variant_name, - }, - params, - &variant.fields, - &type_name, - ), - } -} - -fn serialize_internally_tagged_variant( - params: &Parameters, - variant: &Variant, - cattrs: &attr::Container, - tag: &str, -) -> Fragment { - let type_name = cattrs.name().serialize_name(); - let variant_name = variant.attrs.name().serialize_name(); - - let enum_ident_str = params.type_name(); - let variant_ident_str = variant.ident.as_ref(); - - if let Some(path) = variant.attrs.serialize_with() { - let ser = wrap_serialize_variant_with(params, path, &variant); - return quote_expr! { - _serde::private::ser::serialize_tagged_newtype( - __serializer, - #enum_ident_str, - #variant_ident_str, - #tag, - #variant_name, - #ser, - ) - }; - } - - match variant.style { - Style::Unit => { - quote_block! { - let mut __struct = try!(_serde::Serializer::serialize_struct( - __serializer, #type_name, 1)); - try!(_serde::ser::SerializeStruct::serialize_field( - &mut __struct, #tag, #variant_name)); - _serde::ser::SerializeStruct::end(__struct) - } - } - Style::Newtype => { - let field = &variant.fields[0]; - let mut field_expr = quote!(__field0); - if let Some(path) = field.attrs.serialize_with() { - field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr); - } - - quote_expr! { - _serde::private::ser::serialize_tagged_newtype( - __serializer, - #enum_ident_str, - #variant_ident_str, - #tag, - #variant_name, - #field_expr, - ) - } - } - Style::Struct => serialize_struct_variant( - StructVariant::InternallyTagged { - tag: tag, - variant_name: variant_name, - }, - params, - &variant.fields, - &type_name, - ), - Style::Tuple => unreachable!("checked in serde_derive_internals"), - } -} - -fn serialize_adjacently_tagged_variant( - params: &Parameters, - variant: &Variant, - cattrs: &attr::Container, - tag: &str, - content: &str, -) -> Fragment { - let this = ¶ms.this; - let type_name = cattrs.name().serialize_name(); - let variant_name = variant.attrs.name().serialize_name(); - - let inner = Stmts(if let Some(path) = variant.attrs.serialize_with() { - let ser = wrap_serialize_variant_with(params, path, &variant); - quote_expr! { - _serde::Serialize::serialize(#ser, __serializer) - } - } else { - match variant.style { - Style::Unit => { - return quote_block! { - let mut __struct = try!(_serde::Serializer::serialize_struct( - __serializer, #type_name, 1)); - try!(_serde::ser::SerializeStruct::serialize_field( - &mut __struct, #tag, #variant_name)); - _serde::ser::SerializeStruct::end(__struct) - }; - } - Style::Newtype => { - let field = &variant.fields[0]; - let mut field_expr = quote!(__field0); - if let Some(path) = field.attrs.serialize_with() { - field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr); - } - - quote_expr! { - _serde::Serialize::serialize(#field_expr, __serializer) - } - } - Style::Tuple => { - serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields) - } - Style::Struct => serialize_struct_variant( - StructVariant::Untagged, - params, - &variant.fields, - &variant_name, - ), - } - }); - - let fields_ty = variant.fields.iter().map(|f| &f.ty); - let ref fields_ident: Vec<_> = match variant.style { - Style::Unit => { - if variant.attrs.serialize_with().is_some() { - vec![] - } else { - unreachable!() - } - } - Style::Newtype => vec![Ident::new("__field0")], - Style::Tuple => (0..variant.fields.len()) - .map(|i| Ident::new(format!("__field{}", i))) - .collect(), - Style::Struct => variant - .fields - .iter() - .map(|f| f.ident.clone().expect("struct variant has unnamed fields")) - .collect(), - }; - - let (_, ty_generics, where_clause) = params.generics.split_for_impl(); - - let wrapper_generics = if let Style::Unit = variant.style { - params.generics.clone() - } else { - bound::with_lifetime_bound(¶ms.generics, "'__a") - }; - let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl(); - - quote_block! { - struct __AdjacentlyTagged #wrapper_generics #where_clause { - data: (#(&'__a #fields_ty,)*), - phantom: _serde::export::PhantomData<#this #ty_generics>, - } - - impl #wrapper_impl_generics _serde::Serialize for __AdjacentlyTagged #wrapper_ty_generics #where_clause { - fn serialize<__S>(&self, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error> - where __S: _serde::Serializer - { - let (#(#fields_ident,)*) = self.data; - #inner - } - } - - let mut __struct = try!(_serde::Serializer::serialize_struct( - __serializer, #type_name, 2)); - try!(_serde::ser::SerializeStruct::serialize_field( - &mut __struct, #tag, #variant_name)); - try!(_serde::ser::SerializeStruct::serialize_field( - &mut __struct, #content, &__AdjacentlyTagged { - data: (#(#fields_ident,)*), - phantom: _serde::export::PhantomData::<#this #ty_generics>, - })); - _serde::ser::SerializeStruct::end(__struct) - } -} - -fn serialize_untagged_variant( - params: &Parameters, - variant: &Variant, - cattrs: &attr::Container, -) -> Fragment { - if let Some(path) = variant.attrs.serialize_with() { - let ser = wrap_serialize_variant_with(params, path, &variant); - return quote_expr! { - _serde::Serialize::serialize(#ser, __serializer) - }; - } - - match variant.style { - Style::Unit => { - quote_expr! { - _serde::Serializer::serialize_unit(__serializer) - } - } - Style::Newtype => { - let field = &variant.fields[0]; - let mut field_expr = quote!(__field0); - if let Some(path) = field.attrs.serialize_with() { - field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr); - } - - quote_expr! { - _serde::Serialize::serialize(#field_expr, __serializer) - } - } - Style::Tuple => serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields), - Style::Struct => { - let type_name = cattrs.name().serialize_name(); - serialize_struct_variant(StructVariant::Untagged, params, &variant.fields, &type_name) - } - } -} - -enum TupleVariant { - ExternallyTagged { - type_name: String, - variant_index: u32, - variant_name: String, - }, - Untagged, -} - -fn serialize_tuple_variant( - context: TupleVariant, - params: &Parameters, - fields: &[Field], -) -> Fragment { - let method = match context { - TupleVariant::ExternallyTagged { .. } => { - quote!(_serde::ser::SerializeTupleVariant::serialize_field) - } - TupleVariant::Untagged => quote!(_serde::ser::SerializeTuple::serialize_element), - }; - - let serialize_stmts = serialize_tuple_struct_visitor(fields, params, true, method); - - let len = serialize_stmts.len(); - let let_mut = mut_if(len > 0); - - match context { - TupleVariant::ExternallyTagged { - type_name, - variant_index, - variant_name, - } => { - quote_block! { - let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_variant( - __serializer, - #type_name, - #variant_index, - #variant_name, - #len)); - #(#serialize_stmts)* - _serde::ser::SerializeTupleVariant::end(__serde_state) - } - } - TupleVariant::Untagged => { - quote_block! { - let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple( - __serializer, - #len)); - #(#serialize_stmts)* - _serde::ser::SerializeTuple::end(__serde_state) - } - } - } -} - -enum StructVariant<'a> { - ExternallyTagged { - variant_index: u32, - variant_name: String, - }, - InternallyTagged { - tag: &'a str, - variant_name: String, - }, - Untagged, -} - -fn serialize_struct_variant<'a>( - context: StructVariant<'a>, - params: &Parameters, - fields: &[Field], - name: &str, -) -> Fragment { - let (method, skip_method) = match context { - StructVariant::ExternallyTagged { .. } => ( - quote!(_serde::ser::SerializeStructVariant::serialize_field), - quote!(_serde::ser::SerializeStructVariant::skip_field), - ), - StructVariant::InternallyTagged { .. } | StructVariant::Untagged => ( - quote!(_serde::ser::SerializeStruct::serialize_field), - quote!(_serde::ser::SerializeStruct::skip_field), - ), - }; - - let serialize_fields = serialize_struct_visitor(fields, params, true, method, skip_method); - - let mut serialized_fields = fields - .iter() - .filter(|&field| !field.attrs.skip_serializing()) - .peekable(); - - let let_mut = mut_if(serialized_fields.peek().is_some()); - - let len = serialized_fields - .map(|field| { - let ident = field.ident.clone().expect("struct has unnamed fields"); - - match field.attrs.skip_serializing_if() { - Some(path) => quote!(if #path(#ident) { 0 } else { 1 }), - None => quote!(1), - } - }) - .fold(quote!(0), |sum, expr| quote!(#sum + #expr)); - - match context { - StructVariant::ExternallyTagged { - variant_index, - variant_name, - } => { - quote_block! { - let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct_variant( - __serializer, - #name, - #variant_index, - #variant_name, - #len, - )); - #(#serialize_fields)* - _serde::ser::SerializeStructVariant::end(__serde_state) - } - } - StructVariant::InternallyTagged { tag, variant_name } => { - quote_block! { - let mut __serde_state = try!(_serde::Serializer::serialize_struct( - __serializer, - #name, - #len + 1, - )); - try!(_serde::ser::SerializeStruct::serialize_field( - &mut __serde_state, - #tag, - #variant_name, - )); - #(#serialize_fields)* - _serde::ser::SerializeStruct::end(__serde_state) - } - } - StructVariant::Untagged => { - quote_block! { - let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct( - __serializer, - #name, - #len, - )); - #(#serialize_fields)* - _serde::ser::SerializeStruct::end(__serde_state) - } - } - } -} - -fn serialize_tuple_struct_visitor( - fields: &[Field], - params: &Parameters, - is_enum: bool, - func: Tokens, -) -> Vec<Tokens> { - fields - .iter() - .enumerate() - .map(|(i, field)| { - let mut field_expr = if is_enum { - let id = Ident::new(format!("__field{}", i)); - quote!(#id) - } else { - get_field(params, field, i) - }; - - let skip = field - .attrs - .skip_serializing_if() - .map(|path| quote!(#path(#field_expr))); - - if let Some(path) = field.attrs.serialize_with() { - field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr); - } - - let ser = quote! { - try!(#func(&mut __serde_state, #field_expr)); - }; - - match skip { - None => ser, - Some(skip) => quote!(if !#skip { #ser }), - } - }) - .collect() -} - -fn serialize_struct_visitor( - fields: &[Field], - params: &Parameters, - is_enum: bool, - func: Tokens, - skip_func: Tokens, -) -> Vec<Tokens> { - fields - .iter() - .filter(|&field| !field.attrs.skip_serializing()) - .map(|field| { - let field_ident = field.ident.clone().expect("struct has unnamed field"); - let mut field_expr = if is_enum { - quote!(#field_ident) - } else { - get_field(params, field, field_ident) - }; - - let key_expr = field.attrs.name().serialize_name(); - - let skip = field - .attrs - .skip_serializing_if() - .map(|path| quote!(#path(#field_expr))); - - if let Some(path) = field.attrs.serialize_with() { - field_expr = wrap_serialize_field_with(params, field.ty, path, field_expr); - } - - let ser = quote! { - try!(#func(&mut __serde_state, #key_expr, #field_expr)); - }; - - match skip { - None => ser, - Some(skip) => { - quote! { - if !#skip { - #ser - } else { - try!(#skip_func(&mut __serde_state, #key_expr)); - } - } - } - } - }) - .collect() -} - -fn wrap_serialize_field_with( - params: &Parameters, - field_ty: &syn::Ty, - serialize_with: &syn::Path, - field_expr: Tokens, -) -> Tokens { - wrap_serialize_with(params, serialize_with, &[field_ty], &[quote!(#field_expr)]) -} - -fn wrap_serialize_variant_with( - params: &Parameters, - serialize_with: &syn::Path, - variant: &Variant, -) -> Tokens { - let field_tys: Vec<_> = variant.fields.iter().map(|field| field.ty).collect(); - let field_exprs: Vec<_> = variant - .fields - .iter() - .enumerate() - .map(|(i, field)| { - let id = field - .ident - .as_ref() - .map_or_else(|| Ident::new(format!("__field{}", i)), |id| id.clone()); - quote!(#id) - }) - .collect(); - wrap_serialize_with( - params, - serialize_with, - field_tys.as_slice(), - field_exprs.as_slice(), - ) -} - -fn wrap_serialize_with( - params: &Parameters, - serialize_with: &syn::Path, - field_tys: &[&syn::Ty], - field_exprs: &[Tokens], -) -> Tokens { - let this = ¶ms.this; - let (_, ty_generics, where_clause) = params.generics.split_for_impl(); - - let wrapper_generics = if field_exprs.len() == 0 { - params.generics.clone() - } else { - bound::with_lifetime_bound(¶ms.generics, "'__a") - }; - let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl(); - - let field_access = (0..field_exprs.len()).map(|n| Ident::new(format!("{}", n))); - - quote!({ - struct __SerializeWith #wrapper_impl_generics #where_clause { - values: (#(&'__a #field_tys, )*), - phantom: _serde::export::PhantomData<#this #ty_generics>, - } - - impl #wrapper_impl_generics _serde::Serialize for __SerializeWith #wrapper_ty_generics #where_clause { - fn serialize<__S>(&self, __s: __S) -> _serde::export::Result<__S::Ok, __S::Error> - where __S: _serde::Serializer - { - #serialize_with(#(self.values.#field_access, )* __s) - } - } - - &__SerializeWith { - values: (#(#field_exprs, )*), - phantom: _serde::export::PhantomData::<#this #ty_generics>, - } - }) -} - -// Serialization of an empty struct results in code like: -// -// let mut __serde_state = try!(serializer.serialize_struct("S", 0)); -// _serde::ser::SerializeStruct::end(__serde_state) -// -// where we want to omit the `mut` to avoid a warning. -fn mut_if(is_mut: bool) -> Option<Tokens> { - if is_mut { - Some(quote!(mut)) - } else { - None - } -} - -fn get_field<I>(params: &Parameters, field: &Field, ident: I) -> Tokens -where - I: Into<Ident>, -{ - let self_var = ¶ms.self_var; - match (params.is_remote, field.attrs.getter()) { - (false, None) => { - let ident = ident.into(); - quote!(&#self_var.#ident) - } - (true, None) => { - let ty = field.ty; - let ident = ident.into(); - quote!(_serde::private::ser::constrain::<#ty>(&#self_var.#ident)) - } - (true, Some(getter)) => { - let ty = field.ty; - quote!(_serde::private::ser::constrain::<#ty>(&#getter(#self_var))) - } - (false, Some(_)) => { - unreachable!("getter is only allowed for remote impls"); - } - } -} diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.37/.cargo-checksum.json cargo-0.26.0/vendor/serde_derive-1.0.37/.cargo-checksum.json --- cargo-0.25.0/vendor/serde_derive-1.0.37/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.37/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"f1711ab8b208541fa8de00425f6a577d90f27bb60724d2bb5fd911314af9668f"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.37/Cargo.toml cargo-0.26.0/vendor/serde_derive-1.0.37/Cargo.toml --- cargo-0.25.0/vendor/serde_derive-1.0.37/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.37/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,49 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "serde_derive" +version = "1.0.37" +authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"] +include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] +description = "Macros 1.1 implementation of #[derive(Serialize, Deserialize)]" +homepage = "https://serde.rs" +documentation = "https://serde.rs/codegen.html" +readme = "README.md" +keywords = ["serde", "serialization", "no_std"] +license = "MIT/Apache-2.0" +repository = "https://github.com/serde-rs/serde" + +[lib] +name = "serde_derive" +proc-macro = true +[dependencies.proc-macro2] +version = "0.3" + +[dependencies.quote] +version = "0.5" + +[dependencies.serde_derive_internals] +version = "=0.23.0" +default-features = false + +[dependencies.syn] +version = "0.13" +features = ["visit"] +[dev-dependencies.serde] +version = "1.0" + +[features] +default = [] +deserialize_in_place = [] +[badges.travis-ci] +repository = "serde-rs/serde" diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.37/LICENSE-APACHE cargo-0.26.0/vendor/serde_derive-1.0.37/LICENSE-APACHE --- cargo-0.25.0/vendor/serde_derive-1.0.37/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.37/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.37/LICENSE-MIT cargo-0.26.0/vendor/serde_derive-1.0.37/LICENSE-MIT --- cargo-0.25.0/vendor/serde_derive-1.0.37/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.37/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.37/README.md cargo-0.26.0/vendor/serde_derive-1.0.37/README.md --- cargo-0.25.0/vendor/serde_derive-1.0.37/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.37/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,104 @@ +# Serde   [![Build Status]][travis] [![Latest Version]][crates.io] [![Rustc Version 1.13+]][rustc] + +[Build Status]: https://api.travis-ci.org/serde-rs/serde.svg?branch=master +[travis]: https://travis-ci.org/serde-rs/serde +[Latest Version]: https://img.shields.io/crates/v/serde.svg +[crates.io]: https://crates.io/crates/serde +[Rustc Version 1.13+]: https://img.shields.io/badge/rustc-1.13+-lightgray.svg +[rustc]: https://blog.rust-lang.org/2016/11/10/Rust-1.13.html + +**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** + +--- + +You may be looking for: + +- [An overview of Serde](https://serde.rs/) +- [Data formats supported by Serde](https://serde.rs/#data-formats) +- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html) +- [Examples](https://serde.rs/examples.html) +- [API documentation](https://docs.serde.rs/serde/) +- [Release notes](https://github.com/serde-rs/serde/releases) + +## Serde in action + +<details> +<summary> +Click to show Cargo.toml. +<a href="http://play.integer32.com/?gist=9003c5b88c1f4989941925d7190c6eec" target="_blank">Run this code in the playground.</a> +</summary> + +```toml +[dependencies] + +# The core APIs, including the Serialize and Deserialize traits. Always +# required when using Serde. +serde = "1.0" + +# Support for #[derive(Serialize, Deserialize)]. Required if you want Serde +# to work for structs and enums defined in your crate. +serde_derive = "1.0" + +# Each data format lives in its own crate; the sample code below uses JSON +# but you may be using a different one. +serde_json = "1.0" +``` + +</details> +<p></p> + +```rust +#[macro_use] +extern crate serde_derive; + +extern crate serde; +extern crate serde_json; + +#[derive(Serialize, Deserialize, Debug)] +struct Point { + x: i32, + y: i32, +} + +fn main() { + let point = Point { x: 1, y: 2 }; + + // Convert the Point to a JSON string. + let serialized = serde_json::to_string(&point).unwrap(); + + // Prints serialized = {"x":1,"y":2} + println!("serialized = {}", serialized); + + // Convert the JSON string back to a Point. + let deserialized: Point = serde_json::from_str(&serialized).unwrap(); + + // Prints deserialized = Point { x: 1, y: 2 } + println!("deserialized = {:?}", deserialized); +} +``` + +## Getting help + +Serde developers live in the #serde channel on +[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a +good resource with generally faster response time but less specific knowledge +about Serde. If IRC is not your thing or you don't get a good response, we are +happy to respond to [GitHub issues](https://github.com/serde-rs/serde/issues/new) +as well. + +## License + +Serde is 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 Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.37/src/bound.rs cargo-0.26.0/vendor/serde_derive-1.0.37/src/bound.rs --- cargo-0.25.0/vendor/serde_derive-1.0.37/src/bound.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.37/src/bound.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,292 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::collections::HashSet; + +use syn::{self, visit}; +use syn::punctuated::Punctuated; + +use internals::ast::{Data, Container}; +use internals::attr; + +use proc_macro2::Span; + +// Remove the default from every type parameter because in the generated impls +// they look like associated types: "error: associated type bindings are not +// allowed here". +pub fn without_defaults(generics: &syn::Generics) -> syn::Generics { + syn::Generics { + params: generics + .params + .iter() + .map(|param| match *param { + syn::GenericParam::Type(ref param) => { + syn::GenericParam::Type(syn::TypeParam { + eq_token: None, + default: None, + ..param.clone() + }) + } + _ => param.clone(), + }) + .collect(), + ..generics.clone() + } +} + +pub fn with_where_predicates( + generics: &syn::Generics, + predicates: &[syn::WherePredicate], +) -> syn::Generics { + let mut generics = generics.clone(); + generics.make_where_clause() + .predicates + .extend(predicates.into_iter().cloned()); + generics +} + +pub fn with_where_predicates_from_fields<F>( + cont: &Container, + generics: &syn::Generics, + from_field: F, +) -> syn::Generics +where + F: Fn(&attr::Field) -> Option<&[syn::WherePredicate]>, +{ + let predicates = cont.data + .all_fields() + .flat_map(|field| from_field(&field.attrs)) + .flat_map(|predicates| predicates.to_vec()); + + let mut generics = generics.clone(); + generics.make_where_clause() + .predicates + .extend(predicates); + generics +} + +// Puts the given bound on any generic type parameters that are used in fields +// for which filter returns true. +// +// For example, the following struct needs the bound `A: Serialize, B: Serialize`. +// +// struct S<'b, A, B: 'b, C> { +// a: A, +// b: Option<&'b B> +// #[serde(skip_serializing)] +// c: C, +// } +pub fn with_bound<F>( + cont: &Container, + generics: &syn::Generics, + filter: F, + bound: &syn::Path, +) -> syn::Generics +where + F: Fn(&attr::Field, Option<&attr::Variant>) -> bool, +{ + struct FindTyParams { + // Set of all generic type parameters on the current struct (A, B, C in + // the example). Initialized up front. + all_ty_params: HashSet<syn::Ident>, + // Set of generic type parameters used in fields for which filter + // returns true (A and B in the example). Filled in as the visitor sees + // them. + relevant_ty_params: HashSet<syn::Ident>, + } + impl<'ast> visit::Visit<'ast> for FindTyParams { + fn visit_path(&mut self, path: &syn::Path) { + if let Some(seg) = path.segments.last() { + if seg.into_value().ident == "PhantomData" { + // Hardcoded exception, because PhantomData<T> implements + // Serialize and Deserialize whether or not T implements it. + return; + } + } + if path.leading_colon.is_none() && path.segments.len() == 1 { + let id = path.segments[0].ident; + if self.all_ty_params.contains(&id) { + self.relevant_ty_params.insert(id); + } + } + visit::visit_path(self, path); + } + + // Type parameter should not be considered used by a macro path. + // + // struct TypeMacro<T> { + // mac: T!(), + // marker: PhantomData<T>, + // } + fn visit_macro(&mut self, _mac: &syn::Macro) {} + } + + let all_ty_params: HashSet<_> = generics + .params + .iter() + .filter_map(|param| match *param { + syn::GenericParam::Type(ref param) => Some(param.ident), + _ => None, + }) + .collect(); + + let mut visitor = FindTyParams { + all_ty_params: all_ty_params, + relevant_ty_params: HashSet::new(), + }; + match cont.data { + Data::Enum(ref variants) => for variant in variants.iter() { + let relevant_fields = variant + .fields + .iter() + .filter(|field| filter(&field.attrs, Some(&variant.attrs))); + for field in relevant_fields { + visit::visit_type(&mut visitor, field.ty); + } + }, + Data::Struct(_, ref fields) => { + for field in fields.iter().filter(|field| filter(&field.attrs, None)) { + visit::visit_type(&mut visitor, field.ty); + } + } + } + + let new_predicates = generics + .params + .iter() + .filter_map(|param| match *param { + syn::GenericParam::Type(ref param) => Some(param.ident), + _ => None, + }) + .filter(|id| visitor.relevant_ty_params.contains(id)) + .map(|id| { + syn::WherePredicate::Type(syn::PredicateType { + lifetimes: None, + // the type parameter that is being bounded e.g. T + bounded_ty: syn::Type::Path(syn::TypePath { + qself: None, + path: id.into(), + }), + colon_token: Default::default(), + // the bound e.g. Serialize + bounds: vec![ + syn::TypeParamBound::Trait(syn::TraitBound { + paren_token: None, + modifier: syn::TraitBoundModifier::None, + lifetimes: None, + path: bound.clone(), + }), + ].into_iter().collect(), + }) + }); + + let mut generics = generics.clone(); + generics.make_where_clause() + .predicates + .extend(new_predicates); + generics +} + +pub fn with_self_bound( + cont: &Container, + generics: &syn::Generics, + bound: &syn::Path, +) -> syn::Generics { + let mut generics = generics.clone(); + generics.make_where_clause() + .predicates + .push(syn::WherePredicate::Type(syn::PredicateType { + lifetimes: None, + // the type that is being bounded e.g. MyStruct<'a, T> + bounded_ty: type_of_item(cont), + colon_token: Default::default(), + // the bound e.g. Default + bounds: vec![ + syn::TypeParamBound::Trait(syn::TraitBound { + paren_token: None, + modifier: syn::TraitBoundModifier::None, + lifetimes: None, + path: bound.clone(), + }), + ].into_iter().collect(), + })); + generics +} + +pub fn with_lifetime_bound(generics: &syn::Generics, lifetime: &str) -> syn::Generics { + let bound = syn::Lifetime::new(lifetime, Span::call_site()); + let def = syn::LifetimeDef { + attrs: Vec::new(), + lifetime: bound, + colon_token: None, + bounds: Punctuated::new(), + }; + + let params = Some(syn::GenericParam::Lifetime(def)) + .into_iter() + .chain(generics.params + .iter() + .cloned() + .map(|mut param| { + match param { + syn::GenericParam::Lifetime(ref mut param) => { + param.bounds.push(bound); + } + syn::GenericParam::Type(ref mut param) => { + param.bounds.push(syn::TypeParamBound::Lifetime(bound)); + } + syn::GenericParam::Const(_) => {} + } + param + })) + .collect(); + + syn::Generics { + params: params, + ..generics.clone() + } +} + +fn type_of_item(cont: &Container) -> syn::Type { + syn::Type::Path(syn::TypePath { + qself: None, + path: syn::Path { + leading_colon: None, + segments: vec![ + syn::PathSegment { + ident: cont.ident, + arguments: syn::PathArguments::AngleBracketed( + syn::AngleBracketedGenericArguments { + colon2_token: None, + lt_token: Default::default(), + args: cont.generics + .params + .iter() + .map(|param| match *param { + syn::GenericParam::Type(ref param) => { + syn::GenericArgument::Type(syn::Type::Path(syn::TypePath { + qself: None, + path: param.ident.into(), + })) + } + syn::GenericParam::Lifetime(ref param) => { + syn::GenericArgument::Lifetime(param.lifetime) + } + syn::GenericParam::Const(_) => { + panic!("Serde does not support const generics yet"); + } + }) + .collect(), + gt_token: Default::default(), + }, + ), + }, + ].into_iter().collect(), + }, + }) +} diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.37/src/de.rs cargo-0.26.0/vendor/serde_derive-1.0.37/src/de.rs --- cargo-0.25.0/vendor/serde_derive-1.0.37/src/de.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.37/src/de.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2793 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use syn::{self, Ident, Index, Member}; +use syn::punctuated::Punctuated; +use syn::spanned::Spanned; +use quote::{ToTokens, Tokens}; +use proc_macro2::{Literal, Span}; + +use bound; +use fragment::{Expr, Fragment, Match, Stmts}; +use internals::ast::{Data, Container, Field, Style, Variant}; +use internals::{self, attr}; + +use std::collections::BTreeSet; + +pub fn expand_derive_deserialize(input: &syn::DeriveInput) -> Result<Tokens, String> { + let ctxt = internals::Ctxt::new(); + let cont = Container::from_ast(&ctxt, input); + try!(ctxt.check()); + + let ident = &cont.ident; + let params = Parameters::new(&cont); + let (de_impl_generics, _, ty_generics, where_clause) = split_with_de_lifetime(¶ms); + let dummy_const = Ident::new(&format!("_IMPL_DESERIALIZE_FOR_{}", ident), Span::call_site()); + let body = Stmts(deserialize_body(&cont, ¶ms)); + let delife = params.borrowed.de_lifetime(); + + let impl_block = if let Some(remote) = cont.attrs.remote() { + let vis = &input.vis; + let fun = quote_spanned!(Span::call_site()=> deserialize); + quote! { + impl #de_impl_generics #ident #ty_generics #where_clause { + #vis fn #fun<__D>(__deserializer: __D) -> _serde::export::Result<#remote #ty_generics, __D::Error> + where __D: _serde::Deserializer<#delife> + { + #body + } + } + } + } else { + let fn_deserialize_in_place = deserialize_in_place_body(&cont, ¶ms); + + quote! { + #[automatically_derived] + impl #de_impl_generics _serde::Deserialize<#delife> for #ident #ty_generics #where_clause { + fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error> + where __D: _serde::Deserializer<#delife> + { + #body + } + + #fn_deserialize_in_place + } + } + }; + + let generated = quote! { + #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] + const #dummy_const: () = { + extern crate serde as _serde; + #impl_block + }; + }; + Ok(generated) +} + +struct Parameters { + /// Name of the type the `derive` is on. + local: syn::Ident, + + /// Path to the type the impl is for. Either a single `Ident` for local + /// types or `some::remote::Ident` for remote types. Does not include + /// generic parameters. + this: syn::Path, + + /// Generics including any explicit and inferred bounds for the impl. + generics: syn::Generics, + + /// Lifetimes borrowed from the deserializer. These will become bounds on + /// the `'de` lifetime of the deserializer. + borrowed: BorrowedLifetimes, + + /// At least one field has a serde(getter) attribute, implying that the + /// remote type has a private field. + has_getter: bool, +} + +impl Parameters { + fn new(cont: &Container) -> Self { + let local = cont.ident; + let this = match cont.attrs.remote() { + Some(remote) => remote.clone(), + None => cont.ident.into(), + }; + let borrowed = borrowed_lifetimes(cont); + let generics = build_generics(cont, &borrowed); + let has_getter = cont.data.has_getter(); + + Parameters { + local: local, + this: this, + generics: generics, + borrowed: borrowed, + has_getter: has_getter, + } + } + + /// Type name to use in error messages and `&'static str` arguments to + /// various Deserializer methods. + fn type_name(&self) -> &str { + self.this.segments.last().unwrap().value().ident.as_ref() + } +} + +// All the generics in the input, plus a bound `T: Deserialize` for each generic +// field type that will be deserialized by us, plus a bound `T: Default` for +// each generic field type that will be set to a default value. +fn build_generics(cont: &Container, borrowed: &BorrowedLifetimes) -> syn::Generics { + let generics = bound::without_defaults(cont.generics); + + let generics = bound::with_where_predicates_from_fields(cont, &generics, attr::Field::de_bound); + + match cont.attrs.de_bound() { + Some(predicates) => bound::with_where_predicates(&generics, predicates), + None => { + let generics = match *cont.attrs.default() { + attr::Default::Default => { + bound::with_self_bound(cont, &generics, &parse_quote!(_serde::export::Default)) + } + attr::Default::None | attr::Default::Path(_) => generics, + }; + + let delife = borrowed.de_lifetime(); + let generics = bound::with_bound( + cont, + &generics, + needs_deserialize_bound, + &parse_quote!(_serde::Deserialize<#delife>), + ); + + bound::with_bound( + cont, + &generics, + requires_default, + &parse_quote!(_serde::export::Default), + ) + } + } +} + +// Fields with a `skip_deserializing` or `deserialize_with` attribute are not +// deserialized by us so we do not generate a bound. Fields with a `bound` +// attribute specify their own bound so we do not generate one. All other fields +// may need a `T: Deserialize` bound where T is the type of the field. +fn needs_deserialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool { + !field.skip_deserializing() && field.deserialize_with().is_none() && field.de_bound().is_none() + && variant.map_or(true, |variant| variant.deserialize_with().is_none()) +} + +// Fields with a `default` attribute (not `default=...`), and fields with a +// `skip_deserializing` attribute that do not also have `default=...`. +fn requires_default(field: &attr::Field, _variant: Option<&attr::Variant>) -> bool { + if let attr::Default::Default = *field.default() { + true + } else { + false + } +} + +enum BorrowedLifetimes { + Borrowed(BTreeSet<syn::Lifetime>), + Static, +} + +impl BorrowedLifetimes { + fn de_lifetime(&self) -> syn::Lifetime { + match *self { + BorrowedLifetimes::Borrowed(_) => syn::Lifetime::new("'de", Span::call_site()), + BorrowedLifetimes::Static => syn::Lifetime::new("'static", Span::call_site()), + } + } + + fn de_lifetime_def(&self) -> Option<syn::LifetimeDef> { + match *self { + BorrowedLifetimes::Borrowed(ref bounds) => Some(syn::LifetimeDef { + attrs: Vec::new(), + lifetime: syn::Lifetime::new("'de", Span::call_site()), + colon_token: None, + bounds: bounds.iter().cloned().collect(), + }), + BorrowedLifetimes::Static => None, + } + } +} + +// The union of lifetimes borrowed by each field of the container. +// +// These turn into bounds on the `'de` lifetime of the Deserialize impl. If +// lifetimes `'a` and `'b` are borrowed but `'c` is not, the impl is: +// +// impl<'de: 'a + 'b, 'a, 'b, 'c> Deserialize<'de> for S<'a, 'b, 'c> +// +// If any borrowed lifetime is `'static`, then `'de: 'static` would be redundant +// and we use plain `'static` instead of `'de`. +fn borrowed_lifetimes(cont: &Container) -> BorrowedLifetimes { + let mut lifetimes = BTreeSet::new(); + for field in cont.data.all_fields() { + if !field.attrs.skip_deserializing() { + lifetimes.extend(field.attrs.borrowed_lifetimes().iter().cloned()); + } + } + if lifetimes.iter().any(|b| b.to_string() == "'static") { + BorrowedLifetimes::Static + } else { + BorrowedLifetimes::Borrowed(lifetimes) + } +} + +fn deserialize_body(cont: &Container, params: &Parameters) -> Fragment { + if let Some(type_from) = cont.attrs.type_from() { + deserialize_from(type_from) + } else if let attr::Identifier::No = cont.attrs.identifier() { + match cont.data { + Data::Enum(ref variants) => deserialize_enum(params, variants, &cont.attrs), + Data::Struct(Style::Struct, ref fields) => { + if fields.iter().any(|field| field.ident.is_none()) { + panic!("struct has unnamed fields"); + } + deserialize_struct(None, params, fields, &cont.attrs, None, &Untagged::No) + } + Data::Struct(Style::Tuple, ref fields) | Data::Struct(Style::Newtype, ref fields) => { + if fields.iter().any(|field| field.ident.is_some()) { + panic!("tuple struct has named fields"); + } + deserialize_tuple(None, params, fields, &cont.attrs, None) + } + Data::Struct(Style::Unit, _) => deserialize_unit_struct(params, &cont.attrs), + } + } else { + match cont.data { + Data::Enum(ref variants) => { + deserialize_custom_identifier(params, variants, &cont.attrs) + } + Data::Struct(_, _) => unreachable!("checked in serde_derive_internals"), + } + } +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_in_place_body(cont: &Container, params: &Parameters) -> Option<Stmts> { + // Only remote derives have getters, and we do not generate + // deserialize_in_place for remote derives. + assert!(!params.has_getter); + + if cont.attrs.type_from().is_some() || cont.attrs.identifier().is_some() + || cont.data + .all_fields() + .all(|f| f.attrs.deserialize_with().is_some()) + { + return None; + } + + let code = match cont.data { + Data::Struct(Style::Struct, ref fields) => { + if let Some(code) = deserialize_struct_in_place(None, params, fields, &cont.attrs, None) { + code + } else { + return None; + } + } + Data::Struct(Style::Tuple, ref fields) | Data::Struct(Style::Newtype, ref fields) => { + deserialize_tuple_in_place(None, params, fields, &cont.attrs, None) + } + Data::Enum(_) | Data::Struct(Style::Unit, _) => { + return None; + } + }; + + let delife = params.borrowed.de_lifetime(); + let stmts = Stmts(code); + + let fn_deserialize_in_place = quote_block! { + fn deserialize_in_place<__D>(__deserializer: __D, __place: &mut Self) -> _serde::export::Result<(), __D::Error> + where __D: _serde::Deserializer<#delife> + { + #stmts + } + }; + + Some(Stmts(fn_deserialize_in_place)) +} + +#[cfg(not(feature = "deserialize_in_place"))] +fn deserialize_in_place_body(_cont: &Container, _params: &Parameters) -> Option<Stmts> { + None +} + +fn deserialize_from(type_from: &syn::Type) -> Fragment { + quote_block! { + _serde::export::Result::map( + <#type_from as _serde::Deserialize>::deserialize(__deserializer), + _serde::export::From::from) + } +} + +fn deserialize_unit_struct(params: &Parameters, cattrs: &attr::Container) -> Fragment { + let this = ¶ms.this; + let type_name = cattrs.name().deserialize_name(); + + let expecting = format!("unit struct {}", params.type_name()); + + quote_block! { + struct __Visitor; + + impl<'de> _serde::de::Visitor<'de> for __Visitor { + type Value = #this; + + fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { + _serde::export::Formatter::write_str(formatter, #expecting) + } + + #[inline] + fn visit_unit<__E>(self) -> _serde::export::Result<Self::Value, __E> + where __E: _serde::de::Error + { + _serde::export::Ok(#this) + } + } + + _serde::Deserializer::deserialize_unit_struct(__deserializer, #type_name, __Visitor) + } +} + +fn deserialize_tuple( + variant_ident: Option<&syn::Ident>, + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, + deserializer: Option<Tokens>, +) -> Fragment { + let this = ¶ms.this; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + assert!(!cattrs.has_flatten()); + + // If there are getters (implying private fields), construct the local type + // and use an `Into` conversion to get the remote type. If there are no + // getters then construct the target type directly. + let construct = if params.has_getter { + let local = ¶ms.local; + quote!(#local) + } else { + quote!(#this) + }; + + let is_enum = variant_ident.is_some(); + let type_path = match variant_ident { + Some(variant_ident) => quote!(#construct::#variant_ident), + None => construct, + }; + let expecting = match variant_ident { + Some(variant_ident) => format!("tuple variant {}::{}", params.type_name(), variant_ident), + None => format!("tuple struct {}", params.type_name()), + }; + + let nfields = fields.len(); + + let visit_newtype_struct = if !is_enum && nfields == 1 { + Some(deserialize_newtype_struct(&type_path, params, &fields[0])) + } else { + None + }; + + let visit_seq = Stmts(deserialize_seq(&type_path, params, fields, false, cattrs)); + + let visitor_expr = quote! { + __Visitor { + marker: _serde::export::PhantomData::<#this #ty_generics>, + lifetime: _serde::export::PhantomData, + } + }; + let dispatch = if let Some(deserializer) = deserializer { + quote!(_serde::Deserializer::deserialize_tuple(#deserializer, #nfields, #visitor_expr)) + } else if is_enum { + quote!(_serde::de::VariantAccess::tuple_variant(__variant, #nfields, #visitor_expr)) + } else if nfields == 1 { + let type_name = cattrs.name().deserialize_name(); + quote!(_serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr)) + } else { + let type_name = cattrs.name().deserialize_name(); + quote!(_serde::Deserializer::deserialize_tuple_struct(__deserializer, #type_name, #nfields, #visitor_expr)) + }; + + let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); + let visitor_var = if all_skipped { + quote!(_) + } else { + quote!(mut __seq) + }; + + quote_block! { + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::export::PhantomData<#this #ty_generics>, + lifetime: _serde::export::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this #ty_generics; + + fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { + _serde::export::Formatter::write_str(formatter, #expecting) + } + + #visit_newtype_struct + + #[inline] + fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error> + where __A: _serde::de::SeqAccess<#delife> + { + #visit_seq + } + } + + #dispatch + } +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_tuple_in_place( + variant_ident: Option<&syn::Ident>, + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, + deserializer: Option<Tokens>, +) -> Fragment { + let this = ¶ms.this; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + assert!(!cattrs.has_flatten()); + + let is_enum = variant_ident.is_some(); + let expecting = match variant_ident { + Some(variant_ident) => format!("tuple variant {}::{}", params.type_name(), variant_ident), + None => format!("tuple struct {}", params.type_name()), + }; + + let nfields = fields.len(); + + let visit_newtype_struct = if !is_enum && nfields == 1 { + Some(deserialize_newtype_struct_in_place(params, &fields[0])) + } else { + None + }; + + let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs)); + + let visitor_expr = quote! { + __Visitor { + place: __place, + lifetime: _serde::export::PhantomData, + } + }; + + let dispatch = if let Some(deserializer) = deserializer { + quote!(_serde::Deserializer::deserialize_tuple(#deserializer, #nfields, #visitor_expr)) + } else if is_enum { + quote!(_serde::de::VariantAccess::tuple_variant(__variant, #nfields, #visitor_expr)) + } else if nfields == 1 { + let type_name = cattrs.name().deserialize_name(); + quote!(_serde::Deserializer::deserialize_newtype_struct(__deserializer, #type_name, #visitor_expr)) + } else { + let type_name = cattrs.name().deserialize_name(); + quote!(_serde::Deserializer::deserialize_tuple_struct(__deserializer, #type_name, #nfields, #visitor_expr)) + }; + + let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); + let visitor_var = if all_skipped { + quote!(_) + } else { + quote!(mut __seq) + }; + + let in_place_impl_generics = de_impl_generics.in_place(); + let in_place_ty_generics = de_ty_generics.in_place(); + let place_life = place_lifetime(); + + quote_block! { + struct __Visitor #in_place_impl_generics #where_clause { + place: &#place_life mut #this #ty_generics, + lifetime: _serde::export::PhantomData<&#delife ()>, + } + + impl #in_place_impl_generics _serde::de::Visitor<#delife> for __Visitor #in_place_ty_generics #where_clause { + type Value = (); + + fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { + _serde::export::Formatter::write_str(formatter, #expecting) + } + + #visit_newtype_struct + + #[inline] + fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error> + where __A: _serde::de::SeqAccess<#delife> + { + #visit_seq + } + } + + #dispatch + } +} + +fn deserialize_seq( + type_path: &Tokens, + params: &Parameters, + fields: &[Field], + is_struct: bool, + cattrs: &attr::Container, +) -> Fragment { + let vars = (0..fields.len()).map(field_i as fn(_) -> _); + + // XXX: do we need an error for flattening here? + + let deserialized_count = fields + .iter() + .filter(|field| !field.attrs.skip_deserializing()) + .count(); + let expecting = format!("tuple of {} elements", deserialized_count); + + let mut index_in_seq = 0usize; + let let_values = vars.clone().zip(fields).map(|(var, field)| { + if field.attrs.skip_deserializing() { + let default = Expr(expr_is_missing(field, cattrs)); + quote! { + let #var = #default; + } + } else { + let visit = match field.attrs.deserialize_with() { + None => { + let field_ty = &field.ty; + let span = field.original.span(); + let func = quote_spanned!(span=> _serde::de::SeqAccess::next_element::<#field_ty>); + quote!(try!(#func(&mut __seq))) + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote!({ + #wrapper + _serde::export::Option::map( + try!(_serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)), + |__wrap| __wrap.value) + }) + } + }; + let assign = quote! { + let #var = match #visit { + _serde::export::Some(__value) => __value, + _serde::export::None => { + return _serde::export::Err(_serde::de::Error::invalid_length(#index_in_seq, &#expecting)); + } + }; + }; + index_in_seq += 1; + assign + } + }); + + let mut result = if is_struct { + let names = fields.iter().map(|f| &f.ident); + quote_spanned! {Span::call_site()=> + #type_path { #( #names: #vars ),* } + } + } else { + quote_spanned! {Span::call_site()=> + #type_path ( #(#vars),* ) + } + }; + + if params.has_getter { + let this = ¶ms.this; + result = quote! { + _serde::export::Into::<#this>::into(#result) + }; + } + + let let_default = match *cattrs.default() { + attr::Default::Default => Some(quote!( + let __default: Self::Value = _serde::export::Default::default(); + )), + attr::Default::Path(ref path) => Some(quote!( + let __default: Self::Value = #path(); + )), + attr::Default::None => { + // We don't need the default value, to prevent an unused variable warning + // we'll leave the line empty. + None + } + }; + + quote_block! { + #let_default + #(#let_values)* + _serde::export::Ok(#result) + } +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_seq_in_place( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Fragment { + let vars = (0..fields.len()).map(field_i as fn(_) -> _); + + // XXX: do we need an error for flattening here? + + let deserialized_count = fields + .iter() + .filter(|field| !field.attrs.skip_deserializing()) + .count(); + let expecting = format!("tuple of {} elements", deserialized_count); + + let mut index_in_seq = 0usize; + let write_values = vars.clone() + .zip(fields) + .enumerate() + .map(|(field_index, (_, field))| { + // If there's no field name, assume we're a tuple-struct and use a numeric index + let field_name = field + .ident + .map(Member::Named) + .unwrap_or_else(|| Member::Unnamed(Index { + index: field_index as u32, + span: Span::call_site(), + })); + + let dot = quote_spanned!(Span::call_site()=> .); + if field.attrs.skip_deserializing() { + let default = Expr(expr_is_missing(field, cattrs)); + quote! { + self.place #dot #field_name = #default; + } + } else { + let return_invalid_length = quote! { + return _serde::export::Err(_serde::de::Error::invalid_length(#index_in_seq, &#expecting)); + }; + let write = match field.attrs.deserialize_with() { + None => { + quote! { + if let _serde::export::None = try!(_serde::de::SeqAccess::next_element_seed(&mut __seq, + _serde::private::de::InPlaceSeed(&mut self.place #dot #field_name))) + { + #return_invalid_length + } + } + } + Some(path) => { + let (wrapper, wrapper_ty) = + wrap_deserialize_field_with(params, field.ty, path); + quote!({ + #wrapper + match try!(_serde::de::SeqAccess::next_element::<#wrapper_ty>(&mut __seq)) { + _serde::export::Some(__wrap) => { + self.place #dot #field_name = __wrap.value; + } + _serde::export::None => { + #return_invalid_length + } + } + }) + } + }; + index_in_seq += 1; + write + } + }); + + let this = ¶ms.this; + let (_, ty_generics, _) = params.generics.split_for_impl(); + let let_default = match *cattrs.default() { + attr::Default::Default => Some(quote!( + let __default: #this #ty_generics = _serde::export::Default::default(); + )), + attr::Default::Path(ref path) => Some(quote!( + let __default: #this #ty_generics = #path(); + )), + attr::Default::None => { + // We don't need the default value, to prevent an unused variable warning + // we'll leave the line empty. + None + } + }; + + quote_block! { + #let_default + #(#write_values)* + _serde::export::Ok(()) + } +} + +fn deserialize_newtype_struct(type_path: &Tokens, params: &Parameters, field: &Field) -> Tokens { + let delife = params.borrowed.de_lifetime(); + + let value = match field.attrs.deserialize_with() { + None => { + let field_ty = &field.ty; + quote! { + try!(<#field_ty as _serde::Deserialize>::deserialize(__e)) + } + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote!({ + #wrapper + try!(<#wrapper_ty as _serde::Deserialize>::deserialize(__e)).value + }) + } + }; + + let mut result = quote_spanned!(Span::call_site()=> #type_path(#value)); + if params.has_getter { + let this = ¶ms.this; + result = quote! { + _serde::export::Into::<#this>::into(#result) + }; + } + + quote! { + #[inline] + fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::export::Result<Self::Value, __E::Error> + where __E: _serde::Deserializer<#delife> + { + _serde::export::Ok(#result) + } + } +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_newtype_struct_in_place(params: &Parameters, field: &Field) -> Tokens { + // We do not generate deserialize_in_place if every field has a deserialize_with. + assert!(field.attrs.deserialize_with().is_none()); + + let delife = params.borrowed.de_lifetime(); + + let elem = quote_spanned!(Span::call_site()=> .0); + quote! { + #[inline] + fn visit_newtype_struct<__E>(self, __e: __E) -> _serde::export::Result<Self::Value, __E::Error> + where __E: _serde::Deserializer<#delife> + { + _serde::Deserialize::deserialize_in_place(__e, &mut self.place #elem) + } + } +} + +enum Untagged { + Yes, + No, +} + +fn deserialize_struct( + variant_ident: Option<&syn::Ident>, + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, + deserializer: Option<Tokens>, + untagged: &Untagged, +) -> Fragment { + let is_enum = variant_ident.is_some(); + + let this = ¶ms.this; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + // If there are getters (implying private fields), construct the local type + // and use an `Into` conversion to get the remote type. If there are no + // getters then construct the target type directly. + let construct = if params.has_getter { + let local = ¶ms.local; + quote!(#local) + } else { + quote!(#this) + }; + + let type_path = match variant_ident { + Some(variant_ident) => quote!(#construct::#variant_ident), + None => construct, + }; + let expecting = match variant_ident { + Some(variant_ident) => format!("struct variant {}::{}", params.type_name(), variant_ident), + None => format!("struct {}", params.type_name()), + }; + + let visit_seq = Stmts(deserialize_seq(&type_path, params, fields, true, cattrs)); + + let (field_visitor, fields_stmt, visit_map) = if cattrs.has_flatten() { + deserialize_struct_as_map_visitor(&type_path, params, fields, cattrs) + } else { + deserialize_struct_as_struct_visitor(&type_path, params, fields, cattrs) + }; + let field_visitor = Stmts(field_visitor); + let fields_stmt = fields_stmt.map(Stmts); + let visit_map = Stmts(visit_map); + + let visitor_expr = quote! { + __Visitor { + marker: _serde::export::PhantomData::<#this #ty_generics>, + lifetime: _serde::export::PhantomData, + } + }; + let dispatch = if let Some(deserializer) = deserializer { + quote! { + _serde::Deserializer::deserialize_any(#deserializer, #visitor_expr) + } + } else if is_enum { + quote! { + _serde::de::VariantAccess::struct_variant(__variant, FIELDS, #visitor_expr) + } + } else if cattrs.has_flatten() { + quote! { + _serde::Deserializer::deserialize_map(__deserializer, #visitor_expr) + } + } else { + let type_name = cattrs.name().deserialize_name(); + quote! { + _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, #visitor_expr) + } + }; + + let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); + let visitor_var = if all_skipped { + quote!(_) + } else { + quote!(mut __seq) + }; + + // untagged struct variants do not get a visit_seq method. The same applies to structs that + // only have a map representation. + let visit_seq = match *untagged { + Untagged::No if !cattrs.has_flatten() => Some(quote! { + #[inline] + fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error> + where __A: _serde::de::SeqAccess<#delife> + { + #visit_seq + } + }), + _ => None, + }; + + quote_block! { + #field_visitor + + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::export::PhantomData<#this #ty_generics>, + lifetime: _serde::export::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this #ty_generics; + + fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { + _serde::export::Formatter::write_str(formatter, #expecting) + } + + #visit_seq + + #[inline] + fn visit_map<__A>(self, mut __map: __A) -> _serde::export::Result<Self::Value, __A::Error> + where __A: _serde::de::MapAccess<#delife> + { + #visit_map + } + } + + #fields_stmt + + #dispatch + } +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_struct_in_place( + variant_ident: Option<&syn::Ident>, + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, + deserializer: Option<Tokens>, +) -> Option<Fragment> { + let is_enum = variant_ident.is_some(); + + // for now we do not support in_place deserialization for structs that + // are represented as map. + if cattrs.has_flatten() { + return None; + } + + let this = ¶ms.this; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + let expecting = match variant_ident { + Some(variant_ident) => format!("struct variant {}::{}", params.type_name(), variant_ident), + None => format!("struct {}", params.type_name()), + }; + + let visit_seq = Stmts(deserialize_seq_in_place(params, fields, cattrs)); + + let (field_visitor, fields_stmt, visit_map) = deserialize_struct_as_struct_in_place_visitor( + params, fields, cattrs); + + let field_visitor = Stmts(field_visitor); + let fields_stmt = Stmts(fields_stmt); + let visit_map = Stmts(visit_map); + + let visitor_expr = quote! { + __Visitor { + place: __place, + lifetime: _serde::export::PhantomData, + } + }; + let dispatch = if let Some(deserializer) = deserializer { + quote! { + _serde::Deserializer::deserialize_any(#deserializer, #visitor_expr) + } + } else if is_enum { + quote! { + _serde::de::VariantAccess::struct_variant(__variant, FIELDS, #visitor_expr) + } + } else { + let type_name = cattrs.name().deserialize_name(); + quote! { + _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, #visitor_expr) + } + }; + + let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); + let visitor_var = if all_skipped { + quote!(_) + } else { + quote!(mut __seq) + }; + + let visit_seq = quote! { + #[inline] + fn visit_seq<__A>(self, #visitor_var: __A) -> _serde::export::Result<Self::Value, __A::Error> + where __A: _serde::de::SeqAccess<#delife> + { + #visit_seq + } + }; + + let in_place_impl_generics = de_impl_generics.in_place(); + let in_place_ty_generics = de_ty_generics.in_place(); + let place_life = place_lifetime(); + + Some(quote_block! { + #field_visitor + + struct __Visitor #in_place_impl_generics #where_clause { + place: &#place_life mut #this #ty_generics, + lifetime: _serde::export::PhantomData<&#delife ()>, + } + + impl #in_place_impl_generics _serde::de::Visitor<#delife> for __Visitor #in_place_ty_generics #where_clause { + type Value = (); + + fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { + _serde::export::Formatter::write_str(formatter, #expecting) + } + + #visit_seq + + #[inline] + fn visit_map<__A>(self, mut __map: __A) -> _serde::export::Result<Self::Value, __A::Error> + where __A: _serde::de::MapAccess<#delife> + { + #visit_map + } + } + + #fields_stmt + + #dispatch + }) +} + +fn deserialize_enum( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + match *cattrs.tag() { + attr::EnumTag::External => deserialize_externally_tagged_enum(params, variants, cattrs), + attr::EnumTag::Internal { ref tag } => { + deserialize_internally_tagged_enum(params, variants, cattrs, tag) + } + attr::EnumTag::Adjacent { + ref tag, + ref content, + } => deserialize_adjacently_tagged_enum(params, variants, cattrs, tag, content), + attr::EnumTag::None => deserialize_untagged_enum(params, variants, cattrs), + } +} + +fn deserialize_externally_tagged_enum( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + let this = ¶ms.this; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + let type_name = cattrs.name().deserialize_name(); + + let expecting = format!("enum {}", params.type_name()); + + let variant_names_idents: Vec<_> = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .map(|(i, variant)| (variant.attrs.name().deserialize_name(), field_i(i))) + .collect(); + + let variants_stmt = { + let variant_names = variant_names_idents.iter().map(|&(ref name, _)| name); + quote! { + const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ]; + } + }; + + let variant_visitor = Stmts(deserialize_generated_identifier( + &variant_names_idents, + cattrs, + true, + )); + + // Match arms to extract a variant from a string + let variant_arms = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .map(|(i, variant)| { + let variant_name = field_i(i); + + let block = Match(deserialize_externally_tagged_variant( + params, + variant, + cattrs, + )); + + quote! { + (__Field::#variant_name, __variant) => #block + } + }); + + let all_skipped = variants + .iter() + .all(|variant| variant.attrs.skip_deserializing()); + let match_variant = if all_skipped { + // This is an empty enum like `enum Impossible {}` or an enum in which + // all variants have `#[serde(skip_deserializing)]`. + quote! { + // FIXME: Once we drop support for Rust 1.15: + // let _serde::export::Err(__err) = _serde::de::EnumAccess::variant::<__Field>(__data); + // _serde::export::Err(__err) + _serde::export::Result::map( + _serde::de::EnumAccess::variant::<__Field>(__data), + |(__impossible, _)| match __impossible {}) + } + } else { + quote! { + match try!(_serde::de::EnumAccess::variant(__data)) { + #(#variant_arms)* + } + } + }; + + quote_block! { + #variant_visitor + + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::export::PhantomData<#this #ty_generics>, + lifetime: _serde::export::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this #ty_generics; + + fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { + _serde::export::Formatter::write_str(formatter, #expecting) + } + + fn visit_enum<__A>(self, __data: __A) -> _serde::export::Result<Self::Value, __A::Error> + where __A: _serde::de::EnumAccess<#delife> + { + #match_variant + } + } + + #variants_stmt + + _serde::Deserializer::deserialize_enum(__deserializer, #type_name, VARIANTS, + __Visitor { + marker: _serde::export::PhantomData::<#this #ty_generics>, + lifetime: _serde::export::PhantomData, + }) + } +} + +fn deserialize_internally_tagged_enum( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, + tag: &str, +) -> Fragment { + let variant_names_idents: Vec<_> = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .map(|(i, variant)| (variant.attrs.name().deserialize_name(), field_i(i))) + .collect(); + + let variants_stmt = { + let variant_names = variant_names_idents.iter().map(|&(ref name, _)| name); + quote! { + const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ]; + } + }; + + let variant_visitor = Stmts(deserialize_generated_identifier( + &variant_names_idents, + cattrs, + true, + )); + + // Match arms to extract a variant from a string + let variant_arms = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .map(|(i, variant)| { + let variant_name = field_i(i); + + let block = Match(deserialize_internally_tagged_variant( + params, + variant, + cattrs, + quote!( + _serde::private::de::ContentDeserializer::<__D::Error>::new(__tagged.content) + ), + )); + + quote! { + __Field::#variant_name => #block + } + }); + + quote_block! { + #variant_visitor + + #variants_stmt + + let __tagged = try!(_serde::Deserializer::deserialize_any( + __deserializer, + _serde::private::de::TaggedContentVisitor::<__Field>::new(#tag))); + + match __tagged.tag { + #(#variant_arms)* + } + } +} + +fn deserialize_adjacently_tagged_enum( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, + tag: &str, + content: &str, +) -> Fragment { + let this = ¶ms.this; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + let variant_names_idents: Vec<_> = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .map(|(i, variant)| (variant.attrs.name().deserialize_name(), field_i(i))) + .collect(); + + let variants_stmt = { + let variant_names = variant_names_idents.iter().map(|&(ref name, _)| name); + quote! { + const VARIANTS: &'static [&'static str] = &[ #(#variant_names),* ]; + } + }; + + let variant_visitor = Stmts(deserialize_generated_identifier( + &variant_names_idents, + cattrs, + true, + )); + + let variant_arms: &Vec<_> = &variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing()) + .map(|(i, variant)| { + let variant_index = field_i(i); + + let block = Match(deserialize_untagged_variant( + params, + variant, + cattrs, + quote!(__deserializer), + )); + + quote! { + __Field::#variant_index => #block + } + }) + .collect(); + + let expecting = format!("adjacently tagged enum {}", params.type_name()); + let type_name = cattrs.name().deserialize_name(); + let deny_unknown_fields = cattrs.deny_unknown_fields(); + + // If unknown fields are allowed, we pick the visitor that can step over + // those. Otherwise we pick the visitor that fails on unknown keys. + let field_visitor_ty = if deny_unknown_fields { + quote! { _serde::private::de::TagOrContentFieldVisitor } + } else { + quote! { _serde::private::de::TagContentOtherFieldVisitor } + }; + + let tag_or_content = quote! { + #field_visitor_ty { + tag: #tag, + content: #content, + } + }; + + fn is_unit(variant: &Variant) -> bool { + match variant.style { + Style::Unit => true, + Style::Struct | Style::Tuple | Style::Newtype => false, + } + } + + let mut missing_content = quote! { + _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#content)) + }; + if variants.iter().any(is_unit) { + let fallthrough = if variants.iter().all(is_unit) { + None + } else { + Some(quote! { + _ => #missing_content + }) + }; + let arms = variants + .iter() + .enumerate() + .filter(|&(_, variant)| !variant.attrs.skip_deserializing() && is_unit(variant)) + .map(|(i, variant)| { + let variant_index = field_i(i); + let variant_ident = &variant.ident; + quote! { + __Field::#variant_index => _serde::export::Ok(#this::#variant_ident), + } + }); + missing_content = quote! { + match __field { + #(#arms)* + #fallthrough + } + }; + } + + // Advance the map by one key, returning early in case of error. + let next_key = quote! { + try!(_serde::de::MapAccess::next_key_seed(&mut __map, #tag_or_content)) + }; + + // When allowing unknown fields, we want to transparently step through keys + // we don't care about until we find `tag`, `content`, or run out of keys. + let next_relevant_key = if deny_unknown_fields { + next_key + } else { + quote!({ + let mut __rk : _serde::export::Option<_serde::private::de::TagOrContentField> = _serde::export::None; + while let _serde::export::Some(__k) = #next_key { + match __k { + _serde::private::de::TagContentOtherField::Other => { + try!(_serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)); + continue; + }, + _serde::private::de::TagContentOtherField::Tag => { + __rk = _serde::export::Some(_serde::private::de::TagOrContentField::Tag); + break; + } + _serde::private::de::TagContentOtherField::Content => { + __rk = _serde::export::Some(_serde::private::de::TagOrContentField::Content); + break; + } + } + } + + __rk + }) + }; + + // Step through remaining keys, looking for duplicates of previously-seen + // keys. When unknown fields are denied, any key that isn't a duplicate will + // at this point immediately produce an error. + let visit_remaining_keys = quote! { + match #next_relevant_key { + _serde::export::Some(_serde::private::de::TagOrContentField::Tag) => { + _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag)) + } + _serde::export::Some(_serde::private::de::TagOrContentField::Content) => { + _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content)) + } + _serde::export::None => _serde::export::Ok(__ret), + } + }; + + quote_block! { + #variant_visitor + + #variants_stmt + + struct __Seed #de_impl_generics #where_clause { + field: __Field, + marker: _serde::export::PhantomData<#this #ty_generics>, + lifetime: _serde::export::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::DeserializeSeed<#delife> for __Seed #de_ty_generics #where_clause { + type Value = #this #ty_generics; + + fn deserialize<__D>(self, __deserializer: __D) -> _serde::export::Result<Self::Value, __D::Error> + where __D: _serde::Deserializer<#delife> + { + match self.field { + #(#variant_arms)* + } + } + } + + struct __Visitor #de_impl_generics #where_clause { + marker: _serde::export::PhantomData<#this #ty_generics>, + lifetime: _serde::export::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::Visitor<#delife> for __Visitor #de_ty_generics #where_clause { + type Value = #this #ty_generics; + + fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { + _serde::export::Formatter::write_str(formatter, #expecting) + } + + fn visit_map<__A>(self, mut __map: __A) -> _serde::export::Result<Self::Value, __A::Error> + where __A: _serde::de::MapAccess<#delife> + { + // Visit the first relevant key. + match #next_relevant_key { + // First key is the tag. + _serde::export::Some(_serde::private::de::TagOrContentField::Tag) => { + // Parse the tag. + let __field = try!(_serde::de::MapAccess::next_value(&mut __map)); + // Visit the second key. + match #next_relevant_key { + // Second key is a duplicate of the tag. + _serde::export::Some(_serde::private::de::TagOrContentField::Tag) => { + _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#tag)) + } + // Second key is the content. + _serde::export::Some(_serde::private::de::TagOrContentField::Content) => { + let __ret = try!(_serde::de::MapAccess::next_value_seed(&mut __map, + __Seed { + field: __field, + marker: _serde::export::PhantomData, + lifetime: _serde::export::PhantomData, + })); + // Visit remaining keys, looking for duplicates. + #visit_remaining_keys + } + // There is no second key; might be okay if the we have a unit variant. + _serde::export::None => #missing_content + } + } + // First key is the content. + _serde::export::Some(_serde::private::de::TagOrContentField::Content) => { + // Buffer up the content. + let __content = try!(_serde::de::MapAccess::next_value::<_serde::private::de::Content>(&mut __map)); + // Visit the second key. + match #next_relevant_key { + // Second key is the tag. + _serde::export::Some(_serde::private::de::TagOrContentField::Tag) => { + let __deserializer = _serde::private::de::ContentDeserializer::<__A::Error>::new(__content); + // Parse the tag. + let __ret = try!(match try!(_serde::de::MapAccess::next_value(&mut __map)) { + // Deserialize the buffered content now that we know the variant. + #(#variant_arms)* + }); + // Visit remaining keys, looking for duplicates. + #visit_remaining_keys + } + // Second key is a duplicate of the content. + _serde::export::Some(_serde::private::de::TagOrContentField::Content) => { + _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#content)) + } + // There is no second key. + _serde::export::None => { + _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#tag)) + } + } + } + // There is no first key. + _serde::export::None => { + _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#tag)) + } + } + } + + fn visit_seq<__A>(self, mut __seq: __A) -> _serde::export::Result<Self::Value, __A::Error> + where __A: _serde::de::SeqAccess<#delife> + { + // Visit the first element - the tag. + match try!(_serde::de::SeqAccess::next_element(&mut __seq)) { + _serde::export::Some(__field) => { + // Visit the second element - the content. + match try!(_serde::de::SeqAccess::next_element_seed(&mut __seq, + __Seed { + field: __field, + marker: _serde::export::PhantomData, + lifetime: _serde::export::PhantomData, + })) { + _serde::export::Some(__ret) => _serde::export::Ok(__ret), + // There is no second element. + _serde::export::None => { + _serde::export::Err(_serde::de::Error::invalid_length(1, &self)) + } + } + } + // There is no first element. + _serde::export::None => { + _serde::export::Err(_serde::de::Error::invalid_length(0, &self)) + } + } + } + } + + const FIELDS: &'static [&'static str] = &[#tag, #content]; + _serde::Deserializer::deserialize_struct(__deserializer, #type_name, FIELDS, + __Visitor { + marker: _serde::export::PhantomData::<#this #ty_generics>, + lifetime: _serde::export::PhantomData, + }) + } +} + +fn deserialize_untagged_enum( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + let attempts = variants + .iter() + .filter(|variant| !variant.attrs.skip_deserializing()) + .map(|variant| { + Expr(deserialize_untagged_variant( + params, + variant, + cattrs, + quote!(_serde::private::de::ContentRefDeserializer::<__D::Error>::new(&__content)), + )) + }); + + // TODO this message could be better by saving the errors from the failed + // attempts. The heuristic used by TOML was to count the number of fields + // processed before an error, and use the error that happened after the + // largest number of fields. I'm not sure I like that. Maybe it would be + // better to save all the errors and combine them into one message that + // explains why none of the variants matched. + let fallthrough_msg = format!( + "data did not match any variant of untagged enum {}", + params.type_name() + ); + + quote_block! { + let __content = try!(<_serde::private::de::Content as _serde::Deserialize>::deserialize(__deserializer)); + + #( + if let _serde::export::Ok(__ok) = #attempts { + return _serde::export::Ok(__ok); + } + )* + + _serde::export::Err(_serde::de::Error::custom(#fallthrough_msg)) + } +} + +fn deserialize_externally_tagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, +) -> Fragment { + if let Some(path) = variant.attrs.deserialize_with() { + let (wrapper, wrapper_ty, unwrap_fn) = + wrap_deserialize_variant_with(params, variant, path); + return quote_block! { + #wrapper + _serde::export::Result::map( + _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), #unwrap_fn) + }; + } + + let variant_ident = &variant.ident; + + match variant.style { + Style::Unit => { + let this = ¶ms.this; + quote_block! { + try!(_serde::de::VariantAccess::unit_variant(__variant)); + _serde::export::Ok(#this::#variant_ident) + } + } + Style::Newtype => { + deserialize_externally_tagged_newtype_variant(variant_ident, params, &variant.fields[0]) + } + Style::Tuple => { + deserialize_tuple(Some(variant_ident), params, &variant.fields, cattrs, None) + } + Style::Struct => deserialize_struct( + Some(variant_ident), + params, + &variant.fields, + cattrs, + None, + &Untagged::No, + ), + } +} + +fn deserialize_internally_tagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, + deserializer: Tokens, +) -> Fragment { + if variant.attrs.deserialize_with().is_some() { + return deserialize_untagged_variant(params, variant, cattrs, deserializer); + } + + let variant_ident = &variant.ident; + + match variant.style { + Style::Unit => { + let this = ¶ms.this; + let type_name = params.type_name(); + let variant_name = variant.ident.as_ref(); + quote_block! { + try!(_serde::Deserializer::deserialize_any(#deserializer, _serde::private::de::InternallyTaggedUnitVisitor::new(#type_name, #variant_name))); + _serde::export::Ok(#this::#variant_ident) + } + } + Style::Newtype => deserialize_untagged_newtype_variant( + variant_ident, + params, + &variant.fields[0], + &deserializer, + ), + Style::Struct => deserialize_struct( + Some(variant_ident), + params, + &variant.fields, + cattrs, + Some(deserializer), + &Untagged::No, + ), + Style::Tuple => unreachable!("checked in serde_derive_internals"), + } +} + +fn deserialize_untagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, + deserializer: Tokens, +) -> Fragment { + if let Some(path) = variant.attrs.deserialize_with() { + let (wrapper, wrapper_ty, unwrap_fn) = + wrap_deserialize_variant_with(params, variant, path); + return quote_block! { + #wrapper + _serde::export::Result::map( + <#wrapper_ty as _serde::Deserialize>::deserialize(#deserializer), #unwrap_fn) + }; + } + + let variant_ident = &variant.ident; + + match variant.style { + Style::Unit => { + let this = ¶ms.this; + let type_name = params.type_name(); + let variant_name = variant.ident.as_ref(); + quote_expr! { + _serde::export::Result::map( + _serde::Deserializer::deserialize_any( + #deserializer, + _serde::private::de::UntaggedUnitVisitor::new(#type_name, #variant_name) + ), + |()| #this::#variant_ident) + } + } + Style::Newtype => deserialize_untagged_newtype_variant( + variant_ident, + params, + &variant.fields[0], + &deserializer, + ), + Style::Tuple => deserialize_tuple( + Some(variant_ident), + params, + &variant.fields, + cattrs, + Some(deserializer), + ), + Style::Struct => deserialize_struct( + Some(variant_ident), + params, + &variant.fields, + cattrs, + Some(deserializer), + &Untagged::Yes, + ), + } +} + +fn deserialize_externally_tagged_newtype_variant( + variant_ident: &syn::Ident, + params: &Parameters, + field: &Field, +) -> Fragment { + let this = ¶ms.this; + match field.attrs.deserialize_with() { + None => { + let field_ty = &field.ty; + quote_expr! { + _serde::export::Result::map( + _serde::de::VariantAccess::newtype_variant::<#field_ty>(__variant), + #this::#variant_ident) + } + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote_block! { + #wrapper + _serde::export::Result::map( + _serde::de::VariantAccess::newtype_variant::<#wrapper_ty>(__variant), + |__wrapper| #this::#variant_ident(__wrapper.value)) + } + } + } +} + +fn deserialize_untagged_newtype_variant( + variant_ident: &syn::Ident, + params: &Parameters, + field: &Field, + deserializer: &Tokens, +) -> Fragment { + let this = ¶ms.this; + match field.attrs.deserialize_with() { + None => { + let field_ty = &field.ty; + quote_expr! { + _serde::export::Result::map( + <#field_ty as _serde::Deserialize>::deserialize(#deserializer), + #this::#variant_ident) + } + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote_block! { + #wrapper + _serde::export::Result::map( + <#wrapper_ty as _serde::Deserialize>::deserialize(#deserializer), + |__wrapper| #this::#variant_ident(__wrapper.value)) + } + } + } +} + +fn deserialize_generated_identifier( + fields: &[(String, Ident)], + cattrs: &attr::Container, + is_variant: bool +) -> Fragment { + let this = quote!(__Field); + let field_idents: &Vec<_> = &fields.iter().map(|&(_, ref ident)| ident).collect(); + + let (ignore_variant, fallthrough) = if cattrs.has_flatten() { + let ignore_variant = quote!(__other(_serde::private::de::Content<'de>),); + let fallthrough = quote!(_serde::export::Ok(__Field::__other(__value))); + (Some(ignore_variant), Some(fallthrough)) + } else if is_variant || cattrs.deny_unknown_fields() { + (None, None) + } else { + let ignore_variant = quote!(__ignore,); + let fallthrough = quote!(_serde::export::Ok(__Field::__ignore)); + (Some(ignore_variant), Some(fallthrough)) + }; + + let visitor_impl = Stmts(deserialize_identifier( + &this, + fields, + is_variant, + fallthrough, + cattrs.has_flatten(), + )); + + let lifetime = if cattrs.has_flatten() { + Some(quote!(<'de>)) + } else { + None + }; + + quote_block! { + #[allow(non_camel_case_types)] + enum __Field #lifetime { + #(#field_idents,)* + #ignore_variant + } + + struct __FieldVisitor; + + impl<'de> _serde::de::Visitor<'de> for __FieldVisitor { + type Value = __Field #lifetime; + + #visitor_impl + } + + impl<'de> _serde::Deserialize<'de> for __Field #lifetime { + #[inline] + fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error> + where __D: _serde::Deserializer<'de> + { + _serde::Deserializer::deserialize_identifier(__deserializer, __FieldVisitor) + } + } + } +} + +fn deserialize_custom_identifier( + params: &Parameters, + variants: &[Variant], + cattrs: &attr::Container, +) -> Fragment { + let is_variant = match cattrs.identifier() { + attr::Identifier::Variant => true, + attr::Identifier::Field => false, + attr::Identifier::No => unreachable!(), + }; + + let this = ¶ms.this; + let this = quote!(#this); + + let (ordinary, fallthrough) = if let Some(last) = variants.last() { + let last_ident = &last.ident; + if last.attrs.other() { + let ordinary = &variants[..variants.len() - 1]; + let fallthrough = quote!(_serde::export::Ok(#this::#last_ident)); + (ordinary, Some(fallthrough)) + } else if let Style::Newtype = last.style { + let ordinary = &variants[..variants.len() - 1]; + let deserializer = quote!(_serde::private::de::IdentifierDeserializer::from(__value)); + let fallthrough = quote! { + _serde::export::Result::map( + _serde::Deserialize::deserialize(#deserializer), + #this::#last_ident) + }; + (ordinary, Some(fallthrough)) + } else { + (variants, None) + } + } else { + (variants, None) + }; + + let names_idents: Vec<_> = ordinary + .iter() + .map(|variant| { + ( + variant.attrs.name().deserialize_name(), + variant.ident, + ) + }) + .collect(); + + let names = names_idents.iter().map(|&(ref name, _)| name); + + let names_const = if fallthrough.is_some() { + None + } else if is_variant { + let variants = quote! { + const VARIANTS: &'static [&'static str] = &[ #(#names),* ]; + }; + Some(variants) + } else { + let fields = quote! { + const FIELDS: &'static [&'static str] = &[ #(#names),* ]; + }; + Some(fields) + }; + + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + let visitor_impl = Stmts(deserialize_identifier( + &this, + &names_idents, + is_variant, + fallthrough, + false, + )); + + quote_block! { + #names_const + + struct __FieldVisitor #de_impl_generics #where_clause { + marker: _serde::export::PhantomData<#this #ty_generics>, + lifetime: _serde::export::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::de::Visitor<#delife> for __FieldVisitor #de_ty_generics #where_clause { + type Value = #this #ty_generics; + + #visitor_impl + } + + let __visitor = __FieldVisitor { + marker: _serde::export::PhantomData::<#this #ty_generics>, + lifetime: _serde::export::PhantomData, + }; + _serde::Deserializer::deserialize_identifier(__deserializer, __visitor) + } +} + +fn deserialize_identifier( + this: &Tokens, + fields: &[(String, Ident)], + is_variant: bool, + fallthrough: Option<Tokens>, + collect_other_fields: bool +) -> Fragment { + let field_strs = fields.iter().map(|&(ref name, _)| name); + let field_borrowed_strs = fields.iter().map(|&(ref name, _)| name); + let field_bytes = fields.iter().map(|&(ref name, _)| Literal::byte_string(name.as_bytes())); + let field_borrowed_bytes = fields.iter().map(|&(ref name, _)| Literal::byte_string(name.as_bytes())); + + let constructors: &Vec<_> = &fields + .iter() + .map(|&(_, ref ident)| quote!(#this::#ident)) + .collect(); + + let expecting = if is_variant { + "variant identifier" + } else { + "field identifier" + }; + + let index_expecting = if is_variant { "variant" } else { "field" }; + + let variant_indices = 0u64..; + let fallthrough_msg = format!("{} index 0 <= i < {}", index_expecting, fields.len()); + let visit_other = if collect_other_fields { + Some(quote! { + fn visit_bool<__E>(self, __value: bool) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::Bool(__value))) + } + + fn visit_i8<__E>(self, __value: i8) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::I8(__value))) + } + + fn visit_i16<__E>(self, __value: i16) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::I16(__value))) + } + + fn visit_i32<__E>(self, __value: i32) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::I32(__value))) + } + + fn visit_i64<__E>(self, __value: i64) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::I64(__value))) + } + + fn visit_u8<__E>(self, __value: u8) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::U8(__value))) + } + + fn visit_u16<__E>(self, __value: u16) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::U16(__value))) + } + + fn visit_u32<__E>(self, __value: u32) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::U32(__value))) + } + + fn visit_u64<__E>(self, __value: u64) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::U64(__value))) + } + + fn visit_f32<__E>(self, __value: f32) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::F32(__value))) + } + + fn visit_f64<__E>(self, __value: f64) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::F64(__value))) + } + + fn visit_char<__E>(self, __value: char) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::Char(__value))) + } + + fn visit_unit<__E>(self) -> Result<Self::Value, __E> + where __E: _serde::de::Error + { + Ok(__Field::__other(_serde::private::de::Content::Unit)) + } + }) + } else { + Some(quote! { + fn visit_u64<__E>(self, __value: u64) -> _serde::export::Result<Self::Value, __E> + where __E: _serde::de::Error + { + match __value { + #( + #variant_indices => _serde::export::Ok(#constructors), + )* + _ => _serde::export::Err(_serde::de::Error::invalid_value( + _serde::de::Unexpected::Unsigned(__value), + &#fallthrough_msg)) + } + } + }) + }; + + let bytes_to_str = if fallthrough.is_some() || collect_other_fields { + None + } else { + Some(quote! { + let __value = &_serde::export::from_utf8_lossy(__value); + }) + }; + + let (value_as_str_content, value_as_borrowed_str_content, + value_as_bytes_content, value_as_borrowed_bytes_content) = if !collect_other_fields { + (None, None, None, None) + } else { + ( + Some(quote! { + let __value = _serde::private::de::Content::String(__value.to_string()); + }), + Some(quote! { + let __value = _serde::private::de::Content::Str(__value); + }), + Some(quote! { + let __value = _serde::private::de::Content::ByteBuf(__value.to_vec()); + }), + Some(quote! { + let __value = _serde::private::de::Content::Bytes(__value); + }) + ) + }; + + let fallthrough_arm = if let Some(fallthrough) = fallthrough { + fallthrough + } else if is_variant { + quote! { + _serde::export::Err(_serde::de::Error::unknown_variant(__value, VARIANTS)) + } + } else { + quote! { + _serde::export::Err(_serde::de::Error::unknown_field(__value, FIELDS)) + } + }; + + quote_block! { + fn expecting(&self, formatter: &mut _serde::export::Formatter) -> _serde::export::fmt::Result { + _serde::export::Formatter::write_str(formatter, #expecting) + } + + #visit_other + + fn visit_str<__E>(self, __value: &str) -> _serde::export::Result<Self::Value, __E> + where __E: _serde::de::Error + { + match __value { + #( + #field_strs => _serde::export::Ok(#constructors), + )* + _ => { + #value_as_str_content + #fallthrough_arm + } + } + } + + fn visit_borrowed_str<__E>(self, __value: &'de str) -> _serde::export::Result<Self::Value, __E> + where __E: _serde::de::Error + { + match __value { + #( + #field_borrowed_strs => _serde::export::Ok(#constructors), + )* + _ => { + #value_as_borrowed_str_content + #fallthrough_arm + } + } + } + + fn visit_borrowed_bytes<__E>(self, __value: &'de [u8]) -> _serde::export::Result<Self::Value, __E> + where __E: _serde::de::Error + { + match __value { + #( + #field_borrowed_bytes => _serde::export::Ok(#constructors), + )* + _ => { + #bytes_to_str + #value_as_borrowed_bytes_content + #fallthrough_arm + } + } + } + + fn visit_bytes<__E>(self, __value: &[u8]) -> _serde::export::Result<Self::Value, __E> + where __E: _serde::de::Error + { + match __value { + #( + #field_bytes => _serde::export::Ok(#constructors), + )* + _ => { + #bytes_to_str + #value_as_bytes_content + #fallthrough_arm + } + } + } + } +} + +fn deserialize_struct_as_struct_visitor( + struct_path: &Tokens, + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> (Fragment, Option<Fragment>, Fragment) { + assert!(!cattrs.has_flatten()); + + let field_names_idents: Vec<_> = fields + .iter() + .enumerate() + .filter(|&(_, field)| !field.attrs.skip_deserializing()) + .map(|(i, field)| (field.attrs.name().deserialize_name(), field_i(i))) + .collect(); + + let fields_stmt = { + let field_names = field_names_idents.iter().map(|&(ref name, _)| name); + quote_block! { + const FIELDS: &'static [&'static str] = &[ #(#field_names),* ]; + } + }; + + let field_visitor = deserialize_generated_identifier(&field_names_idents, cattrs, false); + + let visit_map = deserialize_map(struct_path, params, fields, cattrs); + + (field_visitor, Some(fields_stmt), visit_map) +} + +fn deserialize_struct_as_map_visitor( + struct_path: &Tokens, + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> (Fragment, Option<Fragment>, Fragment) { + let field_names_idents: Vec<_> = fields + .iter() + .enumerate() + .filter(|&(_, field)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) + .map(|(i, field)| (field.attrs.name().deserialize_name(), field_i(i))) + .collect(); + + let field_visitor = deserialize_generated_identifier(&field_names_idents, cattrs, false); + + let visit_map = deserialize_map(struct_path, params, fields, cattrs); + + (field_visitor, None, visit_map) +} + +fn deserialize_map( + struct_path: &Tokens, + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Fragment { + // Create the field names for the fields. + let fields_names: Vec<_> = fields + .iter() + .enumerate() + .map(|(i, field)| (field, field_i(i))) + .collect(); + + // Declare each field that will be deserialized. + let let_values = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) + .map(|&(field, ref name)| { + let field_ty = &field.ty; + quote! { + let mut #name: _serde::export::Option<#field_ty> = _serde::export::None; + } + }); + + // Collect contents for flatten fields into a buffer + let let_collect = if cattrs.has_flatten() { + Some(quote! { + let mut __collect = Vec::<Option<( + _serde::private::de::Content, + _serde::private::de::Content + )>>::new(); + }) + } else { + None + }; + + // Match arms to extract a value for a field. + let value_arms = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) + .map(|&(field, ref name)| { + let deser_name = field.attrs.name().deserialize_name(); + + let visit = match field.attrs.deserialize_with() { + None => { + let field_ty = &field.ty; + let span = field.original.span(); + let func = quote_spanned!(span=> _serde::de::MapAccess::next_value::<#field_ty>); + quote! { + try!(#func(&mut __map)) + } + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote!({ + #wrapper + try!(_serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map)).value + }) + } + }; + quote! { + __Field::#name => { + if _serde::export::Option::is_some(&#name) { + return _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name)); + } + #name = _serde::export::Some(#visit); + } + } + }); + + // Visit ignored values to consume them + let ignored_arm = if cattrs.has_flatten() { + Some(quote! { + __Field::__other(__name) => { + __collect.push(Some(( + __name, + try!(_serde::de::MapAccess::next_value(&mut __map))))); + } + }) + } else if cattrs.deny_unknown_fields() { + None + } else { + Some(quote! { + _ => { let _ = try!(_serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)); } + }) + }; + + let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); + let match_keys = if cattrs.deny_unknown_fields() && all_skipped { + quote! { + // FIXME: Once we drop support for Rust 1.15: + // let _serde::export::None::<__Field> = try!(_serde::de::MapAccess::next_key(&mut __map)); + _serde::export::Option::map( + try!(_serde::de::MapAccess::next_key::<__Field>(&mut __map)), + |__impossible| match __impossible {}); + } + } else { + quote! { + while let _serde::export::Some(__key) = try!(_serde::de::MapAccess::next_key::<__Field>(&mut __map)) { + match __key { + #(#value_arms)* + #ignored_arm + } + } + } + }; + + let extract_values = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing() && !field.attrs.flatten()) + .map(|&(field, ref name)| { + let missing_expr = Match(expr_is_missing(field, cattrs)); + + quote! { + let #name = match #name { + _serde::export::Some(#name) => #name, + _serde::export::None => #missing_expr + }; + } + }); + + let extract_collected = fields_names + .iter() + .filter(|&&(field, _)| field.attrs.flatten()) + .map(|&(field, ref name)| { + let field_ty = field.ty; + quote! { + let #name: #field_ty = try!(_serde::de::Deserialize::deserialize( + _serde::private::de::FlatMapDeserializer( + &mut __collect, + _serde::export::PhantomData))); + } + }); + + let collected_deny_unknown_fields = if cattrs.has_flatten() && cattrs.deny_unknown_fields() { + Some(quote! { + if let Some(Some((__key, _))) = __collect.into_iter().filter(|x| x.is_some()).next() { + if let Some(__key) = __key.as_str() { + return _serde::export::Err( + _serde::de::Error::custom(format_args!("unknown field `{}`", &__key))); + } else { + return _serde::export::Err( + _serde::de::Error::custom(format_args!("unexpected map key"))); + } + } + }) + } else { + None + }; + + let result = fields_names.iter().map(|&(field, ref name)| { + let ident = field.ident.expect("struct contains unnamed fields"); + if field.attrs.skip_deserializing() { + let value = Expr(expr_is_missing(field, cattrs)); + quote_spanned!(Span::call_site()=> #ident: #value) + } else { + quote_spanned!(Span::call_site()=> #ident: #name) + } + }); + + let let_default = match *cattrs.default() { + attr::Default::Default => Some(quote!( + let __default: Self::Value = _serde::export::Default::default(); + )), + attr::Default::Path(ref path) => Some(quote!( + let __default: Self::Value = #path(); + )), + attr::Default::None => { + // We don't need the default value, to prevent an unused variable warning + // we'll leave the line empty. + None + } + }; + + let mut result = quote_spanned!(Span::call_site()=> #struct_path { #(#result),* }); + if params.has_getter { + let this = ¶ms.this; + result = quote! { + _serde::export::Into::<#this>::into(#result) + }; + } + + quote_block! { + #(#let_values)* + + #let_collect + + #match_keys + + #let_default + + #(#extract_values)* + + #(#extract_collected)* + + #collected_deny_unknown_fields + + _serde::export::Ok(#result) + } +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_struct_as_struct_in_place_visitor( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> (Fragment, Fragment, Fragment) { + assert!(!cattrs.has_flatten()); + + let field_names_idents: Vec<_> = fields + .iter() + .enumerate() + .filter(|&(_, field)| !field.attrs.skip_deserializing()) + .map(|(i, field)| (field.attrs.name().deserialize_name(), field_i(i))) + .collect(); + + let fields_stmt = { + let field_names = field_names_idents.iter().map(|&(ref name, _)| name); + quote_block! { + const FIELDS: &'static [&'static str] = &[ #(#field_names),* ]; + } + }; + + let field_visitor = deserialize_generated_identifier(&field_names_idents, cattrs, false); + + let visit_map = deserialize_map_in_place(params, fields, cattrs); + + (field_visitor, fields_stmt, visit_map) +} + +#[cfg(feature = "deserialize_in_place")] +fn deserialize_map_in_place( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Fragment { + assert!(!cattrs.has_flatten()); + + // Create the field names for the fields. + let fields_names: Vec<_> = fields + .iter() + .enumerate() + .map(|(i, field)| (field, field_i(i))) + .collect(); + + // For deserialize_in_place, declare booleans for each field that will be deserialized. + let let_flags = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing()) + .map(|&(_, ref name)| { + quote! { + let mut #name: bool = false; + } + }); + + // Match arms to extract a value for a field. + let value_arms_from = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing()) + .map(|&(field, ref name)| { + let deser_name = field.attrs.name().deserialize_name(); + let field_name = &field.ident; + + let visit = match field.attrs.deserialize_with() { + None => { + quote! { + try!(_serde::de::MapAccess::next_value_seed(&mut __map, _serde::private::de::InPlaceSeed(&mut self.place.#field_name))) + } + } + Some(path) => { + let (wrapper, wrapper_ty) = wrap_deserialize_field_with(params, field.ty, path); + quote!({ + #wrapper + self.place.#field_name = try!(_serde::de::MapAccess::next_value::<#wrapper_ty>(&mut __map)).value + }) + } + }; + quote! { + __Field::#name => { + if #name { + return _serde::export::Err(<__A::Error as _serde::de::Error>::duplicate_field(#deser_name)); + } + #visit; + #name = true; + } + } + }); + + // Visit ignored values to consume them + let ignored_arm = if cattrs.deny_unknown_fields() { + None + } else { + Some(quote! { + _ => { let _ = try!(_serde::de::MapAccess::next_value::<_serde::de::IgnoredAny>(&mut __map)); } + }) + }; + + let all_skipped = fields.iter().all(|field| field.attrs.skip_deserializing()); + + let match_keys = if cattrs.deny_unknown_fields() && all_skipped { + quote! { + // FIXME: Once we drop support for Rust 1.15: + // let _serde::export::None::<__Field> = try!(_serde::de::MapAccess::next_key(&mut __map)); + _serde::export::Option::map( + try!(_serde::de::MapAccess::next_key::<__Field>(&mut __map)), + |__impossible| match __impossible {}); + } + } else { + quote! { + while let _serde::export::Some(__key) = try!(_serde::de::MapAccess::next_key::<__Field>(&mut __map)) { + match __key { + #(#value_arms_from)* + #ignored_arm + } + } + } + }; + + let check_flags = fields_names + .iter() + .filter(|&&(field, _)| !field.attrs.skip_deserializing()) + .map(|&(field, ref name)| { + let missing_expr = expr_is_missing(field, cattrs); + // If missing_expr unconditionally returns an error, don't try + // to assign its value to self.place. Maybe this could be handled + // more elegantly. + if missing_expr.as_ref().into_tokens().to_string().starts_with("return ") { + let missing_expr = Stmts(missing_expr); + quote! { + if !#name { + #missing_expr; + } + } + } else { + let field_name = &field.ident; + let missing_expr = Expr(missing_expr); + quote! { + if !#name { + self.place.#field_name = #missing_expr; + }; + } + } + }); + + let this = ¶ms.this; + let (_, _, ty_generics, _) = split_with_de_lifetime(params); + + let let_default = match *cattrs.default() { + attr::Default::Default => Some(quote!( + let __default: #this #ty_generics = _serde::export::Default::default(); + )), + attr::Default::Path(ref path) => Some(quote!( + let __default: #this #ty_generics = #path(); + )), + attr::Default::None => { + // We don't need the default value, to prevent an unused variable warning + // we'll leave the line empty. + None + } + }; + + quote_block! { + #(#let_flags)* + + #match_keys + + #let_default + + #(#check_flags)* + + _serde::export::Ok(()) + } +} + +fn field_i(i: usize) -> Ident { + Ident::new(&format!("__field{}", i), Span::call_site()) +} + +/// This function wraps the expression in `#[serde(deserialize_with = "...")]` +/// in a trait to prevent it from accessing the internal `Deserialize` state. +fn wrap_deserialize_with( + params: &Parameters, + value_ty: &Tokens, + deserialize_with: &syn::ExprPath, +) -> (Tokens, Tokens) { + let this = ¶ms.this; + let (de_impl_generics, de_ty_generics, ty_generics, where_clause) = + split_with_de_lifetime(params); + let delife = params.borrowed.de_lifetime(); + + let wrapper = quote! { + struct __DeserializeWith #de_impl_generics #where_clause { + value: #value_ty, + phantom: _serde::export::PhantomData<#this #ty_generics>, + lifetime: _serde::export::PhantomData<&#delife ()>, + } + + impl #de_impl_generics _serde::Deserialize<#delife> for __DeserializeWith #de_ty_generics #where_clause { + fn deserialize<__D>(__deserializer: __D) -> _serde::export::Result<Self, __D::Error> + where __D: _serde::Deserializer<#delife> + { + _serde::export::Ok(__DeserializeWith { + value: try!(#deserialize_with(__deserializer)), + phantom: _serde::export::PhantomData, + lifetime: _serde::export::PhantomData, + }) + } + } + }; + + let wrapper_ty = quote!(__DeserializeWith #de_ty_generics); + + (wrapper, wrapper_ty) +} + +fn wrap_deserialize_field_with( + params: &Parameters, + field_ty: &syn::Type, + deserialize_with: &syn::ExprPath, +) -> (Tokens, Tokens) { + wrap_deserialize_with(params, "e!(#field_ty), deserialize_with) +} + +fn wrap_deserialize_variant_with( + params: &Parameters, + variant: &Variant, + deserialize_with: &syn::ExprPath, +) -> (Tokens, Tokens, Tokens) { + let this = ¶ms.this; + let variant_ident = &variant.ident; + + let field_tys = variant.fields.iter().map(|field| field.ty); + let (wrapper, wrapper_ty) = + wrap_deserialize_with(params, "e!((#(#field_tys),*)), deserialize_with); + + let field_access = (0..variant.fields.len()).map(|n| Member::Unnamed(Index { + index: n as u32, + span: Span::call_site(), + })); + let unwrap_fn = match variant.style { + Style::Struct => { + let field_idents = variant + .fields + .iter() + .map(|field| field.ident.as_ref().unwrap()); + quote!({ + |__wrap| { + #this::#variant_ident { #(#field_idents: __wrap.value.#field_access),* } + } + }) + } + Style::Tuple => quote!({ + |__wrap| { + #this::#variant_ident(#(__wrap.value.#field_access),*) + } + }), + Style::Newtype => quote!({ + |__wrap| { + #this::#variant_ident(__wrap.value) + } + }), + Style::Unit => quote!({ + |__wrap| { #this::#variant_ident } + }), + }; + + (wrapper, wrapper_ty, unwrap_fn) +} + +fn expr_is_missing(field: &Field, cattrs: &attr::Container) -> Fragment { + match *field.attrs.default() { + attr::Default::Default => { + return quote_expr!(_serde::export::Default::default()); + } + attr::Default::Path(ref path) => { + return quote_expr!(#path()); + } + attr::Default::None => { /* below */ } + } + + match *cattrs.default() { + attr::Default::Default | attr::Default::Path(_) => { + let ident = &field.ident; + return quote_expr!(__default.#ident); + } + attr::Default::None => { /* below */ } + } + + let name = field.attrs.name().deserialize_name(); + match field.attrs.deserialize_with() { + None => { + let span = field.original.span(); + let func = quote_spanned!(span=> _serde::private::de::missing_field); + quote_expr! { + try!(#func(#name)) + } + } + Some(_) => { + quote_expr! { + return _serde::export::Err(<__A::Error as _serde::de::Error>::missing_field(#name)) + } + } + } +} + +struct DeImplGenerics<'a>(&'a Parameters); +#[cfg(feature = "deserialize_in_place")] +struct InPlaceImplGenerics<'a>(&'a Parameters); + +impl<'a> ToTokens for DeImplGenerics<'a> { + fn to_tokens(&self, tokens: &mut Tokens) { + let mut generics = self.0.generics.clone(); + if let Some(de_lifetime) = self.0.borrowed.de_lifetime_def() { + generics.params = Some(syn::GenericParam::Lifetime(de_lifetime)) + .into_iter() + .chain(generics.params) + .collect(); + } + let (impl_generics, _, _) = generics.split_for_impl(); + impl_generics.to_tokens(tokens); + } +} + +#[cfg(feature = "deserialize_in_place")] +impl<'a> ToTokens for InPlaceImplGenerics<'a> { + fn to_tokens(&self, tokens: &mut Tokens) { + let place_lifetime = place_lifetime(); + let mut generics = self.0.generics.clone(); + + // Add lifetime for `&'place mut Self, and `'a: 'place` + for param in &mut generics.params { + match *param { + syn::GenericParam::Lifetime(ref mut param) => { + param.bounds.push(place_lifetime.lifetime); + } + syn::GenericParam::Type(ref mut param) => { + param.bounds + .push(syn::TypeParamBound::Lifetime(place_lifetime.lifetime)); + } + syn::GenericParam::Const(_) => {} + } + } + generics.params = Some(syn::GenericParam::Lifetime(place_lifetime)) + .into_iter() + .chain(generics.params) + .collect(); + if let Some(de_lifetime) = self.0.borrowed.de_lifetime_def() { + generics.params = Some(syn::GenericParam::Lifetime(de_lifetime)) + .into_iter() + .chain(generics.params) + .collect(); + } + let (impl_generics, _, _) = generics.split_for_impl(); + impl_generics.to_tokens(tokens); + } +} + +#[cfg(feature = "deserialize_in_place")] +impl<'a> DeImplGenerics<'a> { + fn in_place(self) -> InPlaceImplGenerics<'a> { + InPlaceImplGenerics(self.0) + } +} + +struct DeTypeGenerics<'a>(&'a Parameters); +#[cfg(feature = "deserialize_in_place")] +struct InPlaceTypeGenerics<'a>(&'a Parameters); + +impl<'a> ToTokens for DeTypeGenerics<'a> { + fn to_tokens(&self, tokens: &mut Tokens) { + let mut generics = self.0.generics.clone(); + if self.0.borrowed.de_lifetime_def().is_some() { + let def = syn::LifetimeDef { + attrs: Vec::new(), + lifetime: syn::Lifetime::new("'de", Span::call_site()), + colon_token: None, + bounds: Punctuated::new(), + }; + generics.params = Some(syn::GenericParam::Lifetime(def)) + .into_iter() + .chain(generics.params) + .collect(); + } + let (_, ty_generics, _) = generics.split_for_impl(); + ty_generics.to_tokens(tokens); + } +} + +#[cfg(feature = "deserialize_in_place")] +impl<'a> ToTokens for InPlaceTypeGenerics<'a> { + fn to_tokens(&self, tokens: &mut Tokens) { + let mut generics = self.0.generics.clone(); + generics.params = Some(syn::GenericParam::Lifetime(place_lifetime())) + .into_iter() + .chain(generics.params) + .collect(); + + if self.0.borrowed.de_lifetime_def().is_some() { + let def = syn::LifetimeDef { + attrs: Vec::new(), + lifetime: syn::Lifetime::new("'de", Span::call_site()), + colon_token: None, + bounds: Punctuated::new(), + }; + generics.params = Some(syn::GenericParam::Lifetime(def)) + .into_iter() + .chain(generics.params) + .collect(); + } + let (_, ty_generics, _) = generics.split_for_impl(); + ty_generics.to_tokens(tokens); + } +} + +#[cfg(feature = "deserialize_in_place")] +impl<'a> DeTypeGenerics<'a> { + fn in_place(self) -> InPlaceTypeGenerics<'a> { + InPlaceTypeGenerics(self.0) + } +} + +#[cfg(feature = "deserialize_in_place")] +fn place_lifetime() -> syn::LifetimeDef { + syn::LifetimeDef { + attrs: Vec::new(), + lifetime: syn::Lifetime::new("'place", Span::call_site()), + colon_token: None, + bounds: Punctuated::new(), + } +} + +fn split_with_de_lifetime( + params: &Parameters, +) -> ( + DeImplGenerics, + DeTypeGenerics, + syn::TypeGenerics, + Option<&syn::WhereClause>, +) { + let de_impl_generics = DeImplGenerics(params); + let de_ty_generics = DeTypeGenerics(params); + let (_, ty_generics, where_clause) = params.generics.split_for_impl(); + (de_impl_generics, de_ty_generics, ty_generics, where_clause) +} diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.37/src/fragment.rs cargo-0.26.0/vendor/serde_derive-1.0.37/src/fragment.rs --- cargo-0.25.0/vendor/serde_derive-1.0.37/src/fragment.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.37/src/fragment.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,81 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use quote::{ToTokens, Tokens}; +use syn::token; + +pub enum Fragment { + /// Tokens that can be used as an expression. + Expr(Tokens), + /// Tokens that can be used inside a block. The surrounding curly braces are + /// not part of these tokens. + Block(Tokens), +} + +macro_rules! quote_expr { + ($($tt:tt)*) => { + $crate::fragment::Fragment::Expr(quote!($($tt)*)) + } +} + +macro_rules! quote_block { + ($($tt:tt)*) => { + $crate::fragment::Fragment::Block(quote!($($tt)*)) + } +} + +/// Interpolate a fragment in place of an expression. This involves surrounding +/// Block fragments in curly braces. +pub struct Expr(pub Fragment); +impl ToTokens for Expr { + fn to_tokens(&self, out: &mut Tokens) { + match self.0 { + Fragment::Expr(ref expr) => expr.to_tokens(out), + Fragment::Block(ref block) => { + token::Brace::default().surround(out, |out| block.to_tokens(out)); + } + } + } +} + +/// Interpolate a fragment as the statements of a block. +pub struct Stmts(pub Fragment); +impl ToTokens for Stmts { + fn to_tokens(&self, out: &mut Tokens) { + match self.0 { + Fragment::Expr(ref expr) => expr.to_tokens(out), + Fragment::Block(ref block) => block.to_tokens(out), + } + } +} + +/// Interpolate a fragment as the value part of a `match` expression. This +/// involves putting a comma after expressions and curly braces around blocks. +pub struct Match(pub Fragment); +impl ToTokens for Match { + fn to_tokens(&self, out: &mut Tokens) { + match self.0 { + Fragment::Expr(ref expr) => { + expr.to_tokens(out); + <Token![,]>::default().to_tokens(out); + } + Fragment::Block(ref block) => { + token::Brace::default().surround(out, |out| block.to_tokens(out)); + } + } + } +} + +impl AsRef<Tokens> for Fragment { + fn as_ref(&self) -> &Tokens { + match *self { + Fragment::Expr(ref expr) => expr, + Fragment::Block(ref block) => block, + } + } +} diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.37/src/lib.rs cargo-0.26.0/vendor/serde_derive-1.0.37/src/lib.rs --- cargo-0.25.0/vendor/serde_derive-1.0.37/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.37/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,76 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! This crate provides Serde's two derive macros. +//! +//! ```rust +//! # #[macro_use] +//! # extern crate serde_derive; +//! # +//! #[derive(Serialize, Deserialize)] +//! # struct S; +//! # +//! # fn main() {} +//! ``` +//! +//! Please refer to [https://serde.rs/derive.html] for how to set this up. +//! +//! [https://serde.rs/derive.html]: https://serde.rs/derive.html + +#![doc(html_root_url = "https://docs.rs/serde_derive/1.0.37")] +#![cfg_attr(feature = "cargo-clippy", allow(enum_variant_names, redundant_field_names, + too_many_arguments, used_underscore_binding))] +// The `quote!` macro requires deep recursion. +#![recursion_limit = "512"] + +#[macro_use] +extern crate quote; +#[macro_use] +extern crate syn; + +extern crate serde_derive_internals as internals; + +extern crate proc_macro; +extern crate proc_macro2; + +use proc_macro::TokenStream; +use syn::DeriveInput; + +// Quote's default is def_site but it appears call_site is likely to stabilize +// before def_site. Thus we try to use only call_site. +macro_rules! quote { + ($($tt:tt)*) => { + quote_spanned!($crate::proc_macro2::Span::call_site()=> $($tt)*) + } +} + +#[macro_use] +mod bound; +#[macro_use] +mod fragment; + +mod ser; +mod de; + +#[proc_macro_derive(Serialize, attributes(serde))] +pub fn derive_serialize(input: TokenStream) -> TokenStream { + let input: DeriveInput = syn::parse(input).unwrap(); + match ser::expand_derive_serialize(&input) { + Ok(expanded) => expanded.into(), + Err(msg) => panic!(msg), + } +} + +#[proc_macro_derive(Deserialize, attributes(serde))] +pub fn derive_deserialize(input: TokenStream) -> TokenStream { + let input: DeriveInput = syn::parse(input).unwrap(); + match de::expand_derive_deserialize(&input) { + Ok(expanded) => expanded.into(), + Err(msg) => panic!(msg), + } +} diff -Nru cargo-0.25.0/vendor/serde_derive-1.0.37/src/ser.rs cargo-0.26.0/vendor/serde_derive-1.0.37/src/ser.rs --- cargo-0.25.0/vendor/serde_derive-1.0.37/src/ser.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive-1.0.37/src/ser.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1127 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use syn::{self, Ident, Index, Member}; +use syn::spanned::Spanned; +use quote::Tokens; +use proc_macro2::Span; + +use bound; +use fragment::{Fragment, Match, Stmts}; +use internals::ast::{Data, Container, Field, Style, Variant}; +use internals::{attr, Ctxt}; + +use std::u32; + +pub fn expand_derive_serialize(input: &syn::DeriveInput) -> Result<Tokens, String> { + let ctxt = Ctxt::new(); + let cont = Container::from_ast(&ctxt, input); + precondition(&ctxt, &cont); + try!(ctxt.check()); + + let ident = &cont.ident; + let params = Parameters::new(&cont); + let (impl_generics, ty_generics, where_clause) = params.generics.split_for_impl(); + let dummy_const = Ident::new(&format!("_IMPL_SERIALIZE_FOR_{}", ident), Span::call_site()); + let body = Stmts(serialize_body(&cont, ¶ms)); + + let impl_block = if let Some(remote) = cont.attrs.remote() { + let vis = &input.vis; + let fun = quote_spanned!(Span::call_site()=> serialize); + quote! { + impl #impl_generics #ident #ty_generics #where_clause { + #vis fn #fun<__S>(__self: &#remote #ty_generics, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error> + where __S: _serde::Serializer + { + #body + } + } + } + } else { + quote! { + #[automatically_derived] + impl #impl_generics _serde::Serialize for #ident #ty_generics #where_clause { + fn serialize<__S>(&self, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error> + where __S: _serde::Serializer + { + #body + } + } + } + }; + + let generated = quote! { + #[allow(non_upper_case_globals, unused_attributes, unused_qualifications)] + const #dummy_const: () = { + extern crate serde as _serde; + #impl_block + }; + }; + Ok(generated) +} + +fn precondition(cx: &Ctxt, cont: &Container) { + match cont.attrs.identifier() { + attr::Identifier::No => {} + attr::Identifier::Field => { + cx.error("field identifiers cannot be serialized"); + } + attr::Identifier::Variant => { + cx.error("variant identifiers cannot be serialized"); + } + } +} + +struct Parameters { + /// Variable holding the value being serialized. Either `self` for local + /// types or `__self` for remote types. + self_var: Ident, + + /// Path to the type the impl is for. Either a single `Ident` for local + /// types or `some::remote::Ident` for remote types. Does not include + /// generic parameters. + this: syn::Path, + + /// Generics including any explicit and inferred bounds for the impl. + generics: syn::Generics, + + /// Type has a `serde(remote = "...")` attribute. + is_remote: bool, +} + +impl Parameters { + fn new(cont: &Container) -> Self { + let is_remote = cont.attrs.remote().is_some(); + let self_var = if is_remote { + Ident::new("__self", Span::call_site()) + } else { + Ident::new("self", Span::call_site()) + }; + + let this = match cont.attrs.remote() { + Some(remote) => remote.clone(), + None => cont.ident.into(), + }; + + let generics = build_generics(cont); + + Parameters { + self_var: self_var, + this: this, + generics: generics, + is_remote: is_remote, + } + } + + /// Type name to use in error messages and `&'static str` arguments to + /// various Serializer methods. + fn type_name(&self) -> &str { + self.this.segments.last().unwrap().value().ident.as_ref() + } +} + +// All the generics in the input, plus a bound `T: Serialize` for each generic +// field type that will be serialized by us. +fn build_generics(cont: &Container) -> syn::Generics { + let generics = bound::without_defaults(cont.generics); + + let generics = + bound::with_where_predicates_from_fields(cont, &generics, attr::Field::ser_bound); + + match cont.attrs.ser_bound() { + Some(predicates) => bound::with_where_predicates(&generics, predicates), + None => bound::with_bound( + cont, + &generics, + needs_serialize_bound, + &parse_quote!(_serde::Serialize), + ), + } +} + +// Fields with a `skip_serializing` or `serialize_with` attribute, or which +// belong to a variant with a `serialize_with` attribute, are not serialized by +// us so we do not generate a bound. Fields with a `bound` attribute specify +// their own bound so we do not generate one. All other fields may need a `T: +// Serialize` bound where T is the type of the field. +fn needs_serialize_bound(field: &attr::Field, variant: Option<&attr::Variant>) -> bool { + !field.skip_serializing() && field.serialize_with().is_none() && field.ser_bound().is_none() + && variant.map_or(true, |variant| variant.serialize_with().is_none()) +} + +fn serialize_body(cont: &Container, params: &Parameters) -> Fragment { + if let Some(type_into) = cont.attrs.type_into() { + serialize_into(params, type_into) + } else { + match cont.data { + Data::Enum(ref variants) => serialize_enum(params, variants, &cont.attrs), + Data::Struct(Style::Struct, ref fields) => { + if fields.iter().any(|field| field.ident.is_none()) { + panic!("struct has unnamed fields"); + } + serialize_struct(params, fields, &cont.attrs) + } + Data::Struct(Style::Tuple, ref fields) => { + if fields.iter().any(|field| field.ident.is_some()) { + panic!("tuple struct has named fields"); + } + serialize_tuple_struct(params, fields, &cont.attrs) + } + Data::Struct(Style::Newtype, ref fields) => { + serialize_newtype_struct(params, &fields[0], &cont.attrs) + } + Data::Struct(Style::Unit, _) => serialize_unit_struct(&cont.attrs), + } + } +} + +fn serialize_into(params: &Parameters, type_into: &syn::Type) -> Fragment { + let self_var = ¶ms.self_var; + quote_block! { + _serde::Serialize::serialize( + &_serde::export::Into::<#type_into>::into(_serde::export::Clone::clone(#self_var)), + __serializer) + } +} + +fn serialize_unit_struct(cattrs: &attr::Container) -> Fragment { + let type_name = cattrs.name().serialize_name(); + + quote_expr! { + _serde::Serializer::serialize_unit_struct(__serializer, #type_name) + } +} + +fn serialize_newtype_struct( + params: &Parameters, + field: &Field, + cattrs: &attr::Container, +) -> Fragment { + let type_name = cattrs.name().serialize_name(); + + let mut field_expr = get_member(params, field, &Member::Unnamed(Index { + index: 0, + span: Span::call_site(), + })); + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + let span = field.original.span(); + let func = quote_spanned!(span=> _serde::Serializer::serialize_newtype_struct); + quote_expr! { + #func(__serializer, #type_name, #field_expr) + } +} + +fn serialize_tuple_struct( + params: &Parameters, + fields: &[Field], + cattrs: &attr::Container, +) -> Fragment { + let serialize_stmts = serialize_tuple_struct_visitor( + fields, + params, + false, + &TupleTrait::SerializeTupleStruct, + ); + + let type_name = cattrs.name().serialize_name(); + let len = serialize_stmts.len(); + let let_mut = mut_if(len > 0); + + quote_block! { + let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_struct(__serializer, #type_name, #len)); + #(#serialize_stmts)* + _serde::ser::SerializeTupleStruct::end(__serde_state) + } +} + +fn serialize_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Container) -> Fragment { + assert!(fields.len() as u64 <= u64::from(u32::MAX)); + + if cattrs.has_flatten() { + serialize_struct_as_map(params, fields, cattrs) + } else { + serialize_struct_as_struct(params, fields, cattrs) + } +} + +fn serialize_struct_as_struct(params: &Parameters, fields: &[Field], cattrs: &attr::Container) -> Fragment { + let serialize_fields = serialize_struct_visitor( + fields, + params, + false, + &StructTrait::SerializeStruct, + ); + + let type_name = cattrs.name().serialize_name(); + + let mut serialized_fields = fields + .iter() + .filter(|&field| !field.attrs.skip_serializing()) + .peekable(); + + let let_mut = mut_if(serialized_fields.peek().is_some()); + + let len = serialized_fields + .map(|field| match field.attrs.skip_serializing_if() { + None => quote!(1), + Some(path) => { + let ident = field.ident.expect("struct has unnamed fields"); + let field_expr = get_member(params, field, &Member::Named(ident)); + quote!(if #path(#field_expr) { 0 } else { 1 }) + } + }) + .fold(quote!(0), |sum, expr| quote!(#sum + #expr)); + + quote_block! { + let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct(__serializer, #type_name, #len)); + #(#serialize_fields)* + _serde::ser::SerializeStruct::end(__serde_state) + } +} + +fn serialize_struct_as_map(params: &Parameters, fields: &[Field], cattrs: &attr::Container) -> Fragment { + let serialize_fields = serialize_struct_visitor( + fields, + params, + false, + &StructTrait::SerializeMap, + ); + + let mut serialized_fields = fields + .iter() + .filter(|&field| !field.attrs.skip_serializing()) + .peekable(); + + let let_mut = mut_if(serialized_fields.peek().is_some()); + + let len = if cattrs.has_flatten() { + quote!(_serde::export::None) + } else { + let len = serialized_fields + .map(|field| match field.attrs.skip_serializing_if() { + None => quote!(1), + Some(path) => { + let ident = field.ident.expect("struct has unnamed fields"); + let field_expr = get_member(params, field, &Member::Named(ident)); + quote!(if #path(#field_expr) { 0 } else { 1 }) + } + }) + .fold(quote!(0), |sum, expr| quote!(#sum + #expr)); + quote!(_serde::export::Some(#len)) + }; + + quote_block! { + let #let_mut __serde_state = try!(_serde::Serializer::serialize_map(__serializer, #len)); + #(#serialize_fields)* + _serde::ser::SerializeMap::end(__serde_state) + } +} + +fn serialize_enum(params: &Parameters, variants: &[Variant], cattrs: &attr::Container) -> Fragment { + assert!(variants.len() as u64 <= u64::from(u32::MAX)); + + let self_var = ¶ms.self_var; + + let arms: Vec<_> = variants + .iter() + .enumerate() + .map(|(variant_index, variant)| { + serialize_variant(params, variant, variant_index as u32, cattrs) + }) + .collect(); + + quote_expr! { + match *#self_var { + #(#arms)* + } + } +} + +fn serialize_variant( + params: &Parameters, + variant: &Variant, + variant_index: u32, + cattrs: &attr::Container, +) -> Tokens { + let this = ¶ms.this; + let variant_ident = variant.ident; + + if variant.attrs.skip_serializing() { + let skipped_msg = format!( + "the enum variant {}::{} cannot be serialized", + params.type_name(), + variant_ident + ); + let skipped_err = quote! { + _serde::export::Err(_serde::ser::Error::custom(#skipped_msg)) + }; + let fields_pat = match variant.style { + Style::Unit => quote!(), + Style::Newtype | Style::Tuple => quote!((..)), + Style::Struct => quote!({ .. }), + }; + quote! { + #this::#variant_ident #fields_pat => #skipped_err, + } + } else { + // variant wasn't skipped + let case = match variant.style { + Style::Unit => { + quote! { + #this::#variant_ident + } + } + Style::Newtype => { + quote! { + #this::#variant_ident(ref __field0) + } + } + Style::Tuple => { + let field_names = + (0..variant.fields.len()).map(|i| Ident::new(&format!("__field{}", i), Span::call_site())); + quote! { + #this::#variant_ident(#(ref #field_names),*) + } + } + Style::Struct => { + let fields = variant + .fields + .iter() + .map(|f| f.ident.expect("struct variant has unnamed fields")); + quote! { + #this::#variant_ident { #(ref #fields),* } + } + } + }; + + let body = Match(match *cattrs.tag() { + attr::EnumTag::External => { + serialize_externally_tagged_variant(params, variant, variant_index, cattrs) + } + attr::EnumTag::Internal { ref tag } => { + serialize_internally_tagged_variant(params, variant, cattrs, tag) + } + attr::EnumTag::Adjacent { + ref tag, + ref content, + } => serialize_adjacently_tagged_variant(params, variant, cattrs, tag, content), + attr::EnumTag::None => serialize_untagged_variant(params, variant, cattrs), + }); + + quote! { + #case => #body + } + } +} + +fn serialize_externally_tagged_variant( + params: &Parameters, + variant: &Variant, + variant_index: u32, + cattrs: &attr::Container, +) -> Fragment { + let type_name = cattrs.name().serialize_name(); + let variant_name = variant.attrs.name().serialize_name(); + + if let Some(path) = variant.attrs.serialize_with() { + let ser = wrap_serialize_variant_with(params, path, variant); + return quote_expr! { + _serde::Serializer::serialize_newtype_variant( + __serializer, + #type_name, + #variant_index, + #variant_name, + #ser, + ) + }; + } + + match variant.style { + Style::Unit => { + quote_expr! { + _serde::Serializer::serialize_unit_variant( + __serializer, + #type_name, + #variant_index, + #variant_name, + ) + } + } + Style::Newtype => { + let field = &variant.fields[0]; + let mut field_expr = quote!(__field0); + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + quote_expr! { + _serde::Serializer::serialize_newtype_variant( + __serializer, + #type_name, + #variant_index, + #variant_name, + #field_expr, + ) + } + } + Style::Tuple => serialize_tuple_variant( + TupleVariant::ExternallyTagged { + type_name: type_name, + variant_index: variant_index, + variant_name: variant_name, + }, + params, + &variant.fields, + ), + Style::Struct => serialize_struct_variant( + StructVariant::ExternallyTagged { + variant_index: variant_index, + variant_name: variant_name, + }, + params, + &variant.fields, + &type_name, + ), + } +} + +fn serialize_internally_tagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, + tag: &str, +) -> Fragment { + let type_name = cattrs.name().serialize_name(); + let variant_name = variant.attrs.name().serialize_name(); + + let enum_ident_str = params.type_name(); + let variant_ident_str = variant.ident.as_ref(); + + if let Some(path) = variant.attrs.serialize_with() { + let ser = wrap_serialize_variant_with(params, path, variant); + return quote_expr! { + _serde::private::ser::serialize_tagged_newtype( + __serializer, + #enum_ident_str, + #variant_ident_str, + #tag, + #variant_name, + #ser, + ) + }; + } + + match variant.style { + Style::Unit => { + quote_block! { + let mut __struct = try!(_serde::Serializer::serialize_struct( + __serializer, #type_name, 1)); + try!(_serde::ser::SerializeStruct::serialize_field( + &mut __struct, #tag, #variant_name)); + _serde::ser::SerializeStruct::end(__struct) + } + } + Style::Newtype => { + let field = &variant.fields[0]; + let mut field_expr = quote!(__field0); + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + quote_expr! { + _serde::private::ser::serialize_tagged_newtype( + __serializer, + #enum_ident_str, + #variant_ident_str, + #tag, + #variant_name, + #field_expr, + ) + } + } + Style::Struct => serialize_struct_variant( + StructVariant::InternallyTagged { + tag: tag, + variant_name: variant_name, + }, + params, + &variant.fields, + &type_name, + ), + Style::Tuple => unreachable!("checked in serde_derive_internals"), + } +} + +fn serialize_adjacently_tagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, + tag: &str, + content: &str, +) -> Fragment { + let this = ¶ms.this; + let type_name = cattrs.name().serialize_name(); + let variant_name = variant.attrs.name().serialize_name(); + + let inner = Stmts(if let Some(path) = variant.attrs.serialize_with() { + let ser = wrap_serialize_variant_with(params, path, variant); + quote_expr! { + _serde::Serialize::serialize(#ser, __serializer) + } + } else { + match variant.style { + Style::Unit => { + return quote_block! { + let mut __struct = try!(_serde::Serializer::serialize_struct( + __serializer, #type_name, 1)); + try!(_serde::ser::SerializeStruct::serialize_field( + &mut __struct, #tag, #variant_name)); + _serde::ser::SerializeStruct::end(__struct) + }; + } + Style::Newtype => { + let field = &variant.fields[0]; + let mut field_expr = quote!(__field0); + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + quote_expr! { + _serde::Serialize::serialize(#field_expr, __serializer) + } + } + Style::Tuple => { + serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields) + } + Style::Struct => serialize_struct_variant( + StructVariant::Untagged, + params, + &variant.fields, + &variant_name, + ), + } + }); + + let fields_ty = variant.fields.iter().map(|f| &f.ty); + let fields_ident: &Vec<_> = &match variant.style { + Style::Unit => { + if variant.attrs.serialize_with().is_some() { + vec![] + } else { + unreachable!() + } + } + Style::Newtype => vec![Ident::new("__field0", Span::call_site())], + Style::Tuple => (0..variant.fields.len()) + .map(|i| Ident::new(&format!("__field{}", i), Span::call_site())) + .collect(), + Style::Struct => variant + .fields + .iter() + .map(|f| f.ident.expect("struct variant has unnamed fields")) + .collect(), + }; + + let (_, ty_generics, where_clause) = params.generics.split_for_impl(); + + let wrapper_generics = if let Style::Unit = variant.style { + params.generics.clone() + } else { + bound::with_lifetime_bound(¶ms.generics, "'__a") + }; + let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl(); + + quote_block! { + struct __AdjacentlyTagged #wrapper_generics #where_clause { + data: (#(&'__a #fields_ty,)*), + phantom: _serde::export::PhantomData<#this #ty_generics>, + } + + impl #wrapper_impl_generics _serde::Serialize for __AdjacentlyTagged #wrapper_ty_generics #where_clause { + fn serialize<__S>(&self, __serializer: __S) -> _serde::export::Result<__S::Ok, __S::Error> + where __S: _serde::Serializer + { + let (#(#fields_ident,)*) = self.data; + #inner + } + } + + let mut __struct = try!(_serde::Serializer::serialize_struct( + __serializer, #type_name, 2)); + try!(_serde::ser::SerializeStruct::serialize_field( + &mut __struct, #tag, #variant_name)); + try!(_serde::ser::SerializeStruct::serialize_field( + &mut __struct, #content, &__AdjacentlyTagged { + data: (#(#fields_ident,)*), + phantom: _serde::export::PhantomData::<#this #ty_generics>, + })); + _serde::ser::SerializeStruct::end(__struct) + } +} + +fn serialize_untagged_variant( + params: &Parameters, + variant: &Variant, + cattrs: &attr::Container, +) -> Fragment { + if let Some(path) = variant.attrs.serialize_with() { + let ser = wrap_serialize_variant_with(params, path, variant); + return quote_expr! { + _serde::Serialize::serialize(#ser, __serializer) + }; + } + + match variant.style { + Style::Unit => { + quote_expr! { + _serde::Serializer::serialize_unit(__serializer) + } + } + Style::Newtype => { + let field = &variant.fields[0]; + let mut field_expr = quote!(__field0); + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + quote_expr! { + _serde::Serialize::serialize(#field_expr, __serializer) + } + } + Style::Tuple => serialize_tuple_variant(TupleVariant::Untagged, params, &variant.fields), + Style::Struct => { + let type_name = cattrs.name().serialize_name(); + serialize_struct_variant(StructVariant::Untagged, params, &variant.fields, &type_name) + } + } +} + +enum TupleVariant { + ExternallyTagged { + type_name: String, + variant_index: u32, + variant_name: String, + }, + Untagged, +} + +fn serialize_tuple_variant( + context: TupleVariant, + params: &Parameters, + fields: &[Field], +) -> Fragment { + let tuple_trait = match context { + TupleVariant::ExternallyTagged { .. } => TupleTrait::SerializeTupleVariant, + TupleVariant::Untagged => TupleTrait::SerializeTuple, + }; + + let serialize_stmts = serialize_tuple_struct_visitor(fields, params, true, &tuple_trait); + + let len = serialize_stmts.len(); + let let_mut = mut_if(len > 0); + + match context { + TupleVariant::ExternallyTagged { + type_name, + variant_index, + variant_name, + } => { + quote_block! { + let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple_variant( + __serializer, + #type_name, + #variant_index, + #variant_name, + #len)); + #(#serialize_stmts)* + _serde::ser::SerializeTupleVariant::end(__serde_state) + } + } + TupleVariant::Untagged => { + quote_block! { + let #let_mut __serde_state = try!(_serde::Serializer::serialize_tuple( + __serializer, + #len)); + #(#serialize_stmts)* + _serde::ser::SerializeTuple::end(__serde_state) + } + } + } +} + +enum StructVariant<'a> { + ExternallyTagged { + variant_index: u32, + variant_name: String, + }, + InternallyTagged { + tag: &'a str, + variant_name: String, + }, + Untagged, +} + +fn serialize_struct_variant<'a>( + context: StructVariant<'a>, + params: &Parameters, + fields: &[Field], + name: &str, +) -> Fragment { + let struct_trait = match context { + StructVariant::ExternallyTagged { .. } => ( + StructTrait::SerializeStructVariant + ), + StructVariant::InternallyTagged { .. } | StructVariant::Untagged => ( + StructTrait::SerializeStruct + ), + }; + + let serialize_fields = serialize_struct_visitor(fields, params, true, &struct_trait); + + let mut serialized_fields = fields + .iter() + .filter(|&field| !field.attrs.skip_serializing()) + .peekable(); + + let let_mut = mut_if(serialized_fields.peek().is_some()); + + let len = serialized_fields + .map(|field| { + let ident = field.ident.expect("struct has unnamed fields"); + + match field.attrs.skip_serializing_if() { + Some(path) => quote!(if #path(#ident) { 0 } else { 1 }), + None => quote!(1), + } + }) + .fold(quote!(0), |sum, expr| quote!(#sum + #expr)); + + match context { + StructVariant::ExternallyTagged { + variant_index, + variant_name, + } => { + quote_block! { + let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct_variant( + __serializer, + #name, + #variant_index, + #variant_name, + #len, + )); + #(#serialize_fields)* + _serde::ser::SerializeStructVariant::end(__serde_state) + } + } + StructVariant::InternallyTagged { tag, variant_name } => { + quote_block! { + let mut __serde_state = try!(_serde::Serializer::serialize_struct( + __serializer, + #name, + #len + 1, + )); + try!(_serde::ser::SerializeStruct::serialize_field( + &mut __serde_state, + #tag, + #variant_name, + )); + #(#serialize_fields)* + _serde::ser::SerializeStruct::end(__serde_state) + } + } + StructVariant::Untagged => { + quote_block! { + let #let_mut __serde_state = try!(_serde::Serializer::serialize_struct( + __serializer, + #name, + #len, + )); + #(#serialize_fields)* + _serde::ser::SerializeStruct::end(__serde_state) + } + } + } +} + +fn serialize_tuple_struct_visitor( + fields: &[Field], + params: &Parameters, + is_enum: bool, + tuple_trait: &TupleTrait, +) -> Vec<Tokens> { + fields + .iter() + .enumerate() + .map(|(i, field)| { + let mut field_expr = if is_enum { + let id = Ident::new(&format!("__field{}", i), Span::call_site()); + quote!(#id) + } else { + get_member(params, field, &Member::Unnamed(Index { + index: i as u32, + span: Span::call_site(), + })) + }; + + let skip = field + .attrs + .skip_serializing_if() + .map(|path| quote!(#path(#field_expr))); + + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + let span = field.original.span(); + let func = tuple_trait.serialize_element(span); + let ser = quote! { + try!(#func(&mut __serde_state, #field_expr)); + }; + + match skip { + None => ser, + Some(skip) => quote!(if !#skip { #ser }), + } + }) + .collect() +} + +fn serialize_struct_visitor( + fields: &[Field], + params: &Parameters, + is_enum: bool, + struct_trait: &StructTrait, +) -> Vec<Tokens> { + fields + .iter() + .filter(|&field| !field.attrs.skip_serializing()) + .map(|field| { + let field_ident = field.ident.expect("struct has unnamed field"); + + let mut field_expr = if is_enum { + quote!(#field_ident) + } else { + get_member(params, field, &Member::Named(field_ident)) + }; + + let key_expr = field.attrs.name().serialize_name(); + + let skip = field + .attrs + .skip_serializing_if() + .map(|path| quote!(#path(#field_expr))); + + if let Some(path) = field.attrs.serialize_with() { + field_expr = wrap_serialize_field_with(params, field.ty, path, &field_expr); + } + + let span = field.original.span(); + let ser = if field.attrs.flatten() { + quote! { + try!(_serde::Serialize::serialize(&#field_expr, _serde::private::ser::FlatMapSerializer(&mut __serde_state))); + } + } else { + let func = struct_trait.serialize_field(span); + quote! { + try!(#func(&mut __serde_state, #key_expr, #field_expr)); + } + }; + + match skip { + None => ser, + Some(skip) => { + if let Some(skip_func) = struct_trait.skip_field(span) { + quote! { + if !#skip { + #ser + } else { + try!(#skip_func(&mut __serde_state, #key_expr)); + } + } + } else { + quote! { + if !#skip { + #ser + } + } + } + } + } + }) + .collect() +} + +fn wrap_serialize_field_with( + params: &Parameters, + field_ty: &syn::Type, + serialize_with: &syn::ExprPath, + field_expr: &Tokens, +) -> Tokens { + wrap_serialize_with(params, serialize_with, &[field_ty], &[quote!(#field_expr)]) +} + +fn wrap_serialize_variant_with( + params: &Parameters, + serialize_with: &syn::ExprPath, + variant: &Variant, +) -> Tokens { + let field_tys: Vec<_> = variant.fields.iter().map(|field| field.ty).collect(); + let field_exprs: Vec<_> = variant + .fields + .iter() + .enumerate() + .map(|(i, field)| { + let id = field + .ident + .unwrap_or_else(|| Ident::new(&format!("__field{}", i), Span::call_site())); + quote!(#id) + }) + .collect(); + wrap_serialize_with( + params, + serialize_with, + field_tys.as_slice(), + field_exprs.as_slice(), + ) +} + +fn wrap_serialize_with( + params: &Parameters, + serialize_with: &syn::ExprPath, + field_tys: &[&syn::Type], + field_exprs: &[Tokens], +) -> Tokens { + let this = ¶ms.this; + let (_, ty_generics, where_clause) = params.generics.split_for_impl(); + + let wrapper_generics = if field_exprs.is_empty() { + params.generics.clone() + } else { + bound::with_lifetime_bound(¶ms.generics, "'__a") + }; + let (wrapper_impl_generics, wrapper_ty_generics, _) = wrapper_generics.split_for_impl(); + + let field_access = (0..field_exprs.len()).map(|n| Member::Unnamed(Index { + index: n as u32, + span: Span::call_site(), + })); + + quote!({ + struct __SerializeWith #wrapper_impl_generics #where_clause { + values: (#(&'__a #field_tys, )*), + phantom: _serde::export::PhantomData<#this #ty_generics>, + } + + impl #wrapper_impl_generics _serde::Serialize for __SerializeWith #wrapper_ty_generics #where_clause { + fn serialize<__S>(&self, __s: __S) -> _serde::export::Result<__S::Ok, __S::Error> + where __S: _serde::Serializer + { + #serialize_with(#(self.values.#field_access, )* __s) + } + } + + &__SerializeWith { + values: (#(#field_exprs, )*), + phantom: _serde::export::PhantomData::<#this #ty_generics>, + } + }) +} + +// Serialization of an empty struct results in code like: +// +// let mut __serde_state = try!(serializer.serialize_struct("S", 0)); +// _serde::ser::SerializeStruct::end(__serde_state) +// +// where we want to omit the `mut` to avoid a warning. +fn mut_if(is_mut: bool) -> Option<Tokens> { + if is_mut { + Some(quote!(mut)) + } else { + None + } +} + +fn get_member(params: &Parameters, field: &Field, member: &Member) -> Tokens { + let self_var = ¶ms.self_var; + match (params.is_remote, field.attrs.getter()) { + (false, None) => { + quote_spanned!(Span::call_site()=> &#self_var.#member) + } + (true, None) => { + let inner = quote_spanned!(Span::call_site()=> &#self_var.#member); + let ty = field.ty; + quote!(_serde::private::ser::constrain::<#ty>(#inner)) + } + (true, Some(getter)) => { + let ty = field.ty; + quote!(_serde::private::ser::constrain::<#ty>(&#getter(#self_var))) + } + (false, Some(_)) => { + unreachable!("getter is only allowed for remote impls"); + } + } +} + +enum StructTrait { + SerializeMap, + SerializeStruct, + SerializeStructVariant, +} + +impl StructTrait { + fn serialize_field(&self, span: Span) -> Tokens { + match *self { + StructTrait::SerializeMap => { + quote_spanned!(span=> _serde::ser::SerializeMap::serialize_entry) + } + StructTrait::SerializeStruct => { + quote_spanned!(span=> _serde::ser::SerializeStruct::serialize_field) + } + StructTrait::SerializeStructVariant => { + quote_spanned!(span=> _serde::ser::SerializeStructVariant::serialize_field) + } + } + } + + fn skip_field(&self, span: Span) -> Option<Tokens> { + match *self { + StructTrait::SerializeMap => None, + StructTrait::SerializeStruct => Some({ + quote_spanned!(span=> _serde::ser::SerializeStruct::skip_field) + }), + StructTrait::SerializeStructVariant => Some({ + quote_spanned!(span=> _serde::ser::SerializeStructVariant::skip_field) + }) + } + } +} + +enum TupleTrait { + SerializeTuple, + SerializeTupleStruct, + SerializeTupleVariant, +} + +impl TupleTrait { + fn serialize_element(&self, span: Span) -> Tokens { + match *self { + TupleTrait::SerializeTuple => { + quote_spanned!(span=> _serde::ser::SerializeTuple::serialize_element) + } + TupleTrait::SerializeTupleStruct => { + quote_spanned!(span=> _serde::ser::SerializeTupleStruct::serialize_field) + } + TupleTrait::SerializeTupleVariant => { + quote_spanned!(span=> _serde::ser::SerializeTupleVariant::serialize_field) + } + } + } +} diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.19.0/.cargo-checksum.json cargo-0.26.0/vendor/serde_derive_internals-0.19.0/.cargo-checksum.json --- cargo-0.25.0/vendor/serde_derive_internals-0.19.0/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.19.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"6e03f1c9530c3fb0a0a5c9b826bdd9246a5921ae995d75f512ac917fc4dd55b5"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.19.0/Cargo.toml cargo-0.26.0/vendor/serde_derive_internals-0.19.0/Cargo.toml --- cargo-0.25.0/vendor/serde_derive_internals-0.19.0/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.19.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "serde_derive_internals" -version = "0.19.0" -authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"] -include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] -description = "AST representation used by Serde derive macros. Unstable." -homepage = "https://serde.rs" -documentation = "https://docs.serde.rs/serde_derive_internals/" -readme = "README.md" -keywords = ["serde", "serialization"] -license = "MIT/Apache-2.0" -repository = "https://github.com/serde-rs/serde" -[dependencies.syn] -version = "0.11.10" -features = ["parsing"] -default-features = false - -[dependencies.synom] -version = "0.11" -[badges.travis-ci] -repository = "serde-rs/serde" diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.19.0/LICENSE-APACHE cargo-0.26.0/vendor/serde_derive_internals-0.19.0/LICENSE-APACHE --- cargo-0.25.0/vendor/serde_derive_internals-0.19.0/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.19.0/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.19.0/LICENSE-MIT cargo-0.26.0/vendor/serde_derive_internals-0.19.0/LICENSE-MIT --- cargo-0.25.0/vendor/serde_derive_internals-0.19.0/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.19.0/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.19.0/README.md cargo-0.26.0/vendor/serde_derive_internals-0.19.0/README.md --- cargo-0.25.0/vendor/serde_derive_internals-0.19.0/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.19.0/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,102 +0,0 @@ -# Serde   [![Build Status]][travis] [![Latest Version]][crates.io] - -[Build Status]: https://api.travis-ci.org/serde-rs/serde.svg?branch=master -[travis]: https://travis-ci.org/serde-rs/serde -[Latest Version]: https://img.shields.io/crates/v/serde.svg -[crates.io]: https://crates.io/crates/serde - -**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** - ---- - -You may be looking for: - -- [An overview of Serde](https://serde.rs/) -- [Data formats supported by Serde](https://serde.rs/#data-formats) -- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html) -- [Examples](https://serde.rs/examples.html) -- [API documentation](https://docs.serde.rs/serde/) -- [Release notes](https://github.com/serde-rs/serde/releases) - -## Serde in action - -<details> -<summary> -Click to show Cargo.toml. -<a href="http://play.integer32.com/?gist=9003c5b88c1f4989941925d7190c6eec" target="_blank">Run this code in the playground.</a> -</summary> - -```toml -[dependencies] - -# The core APIs, including the Serialize and Deserialize traits. Always -# required when using Serde. -serde = "1.0" - -# Support for #[derive(Serialize, Deserialize)]. Required if you want Serde -# to work for structs and enums defined in your crate. -serde_derive = "1.0" - -# Each data format lives in its own crate; the sample code below uses JSON -# but you may be using a different one. -serde_json = "1.0" -``` - -</details> -<p></p> - -```rust -#[macro_use] -extern crate serde_derive; - -extern crate serde; -extern crate serde_json; - -#[derive(Serialize, Deserialize, Debug)] -struct Point { - x: i32, - y: i32, -} - -fn main() { - let point = Point { x: 1, y: 2 }; - - // Convert the Point to a JSON string. - let serialized = serde_json::to_string(&point).unwrap(); - - // Prints serialized = {"x":1,"y":2} - println!("serialized = {}", serialized); - - // Convert the JSON string back to a Point. - let deserialized: Point = serde_json::from_str(&serialized).unwrap(); - - // Prints deserialized = Point { x: 1, y: 2 } - println!("deserialized = {:?}", deserialized); -} -``` - -## Getting help - -Serde developers live in the #serde channel on -[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a -good resource with generally faster response time but less specific knowledge -about Serde. If IRC is not your thing or you don't get a good response, we are -happy to respond to [GitHub issues](https://github.com/serde-rs/serde/issues/new) -as well. - -## License - -Serde is 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 Serde by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.19.0/src/ast.rs cargo-0.26.0/vendor/serde_derive_internals-0.19.0/src/ast.rs --- cargo-0.25.0/vendor/serde_derive_internals-0.19.0/src/ast.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.19.0/src/ast.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,158 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use syn; -use attr; -use check; -use Ctxt; - -pub struct Container<'a> { - pub ident: syn::Ident, - pub attrs: attr::Container, - pub body: Body<'a>, - pub generics: &'a syn::Generics, -} - -pub enum Body<'a> { - Enum(Vec<Variant<'a>>), - Struct(Style, Vec<Field<'a>>), -} - -pub struct Variant<'a> { - pub ident: syn::Ident, - pub attrs: attr::Variant, - pub style: Style, - pub fields: Vec<Field<'a>>, -} - -pub struct Field<'a> { - pub ident: Option<syn::Ident>, - pub attrs: attr::Field, - pub ty: &'a syn::Ty, -} - -#[derive(Copy, Clone)] -pub enum Style { - Struct, - Tuple, - Newtype, - Unit, -} - -impl<'a> Container<'a> { - pub fn from_ast(cx: &Ctxt, item: &'a syn::DeriveInput) -> Container<'a> { - let attrs = attr::Container::from_ast(cx, item); - - let mut body = match item.body { - syn::Body::Enum(ref variants) => { - Body::Enum(enum_from_ast(cx, variants, &attrs.default())) - } - syn::Body::Struct(ref variant_data) => { - let (style, fields) = struct_from_ast(cx, variant_data, None, &attrs.default()); - Body::Struct(style, fields) - } - }; - - match body { - Body::Enum(ref mut variants) => for ref mut variant in variants { - variant.attrs.rename_by_rule(attrs.rename_all()); - for ref mut field in &mut variant.fields { - field.attrs.rename_by_rule(variant.attrs.rename_all()); - } - }, - Body::Struct(_, ref mut fields) => for field in fields { - field.attrs.rename_by_rule(attrs.rename_all()); - }, - } - - let item = Container { - ident: item.ident.clone(), - attrs: attrs, - body: body, - generics: &item.generics, - }; - check::check(cx, &item); - item - } -} - -impl<'a> Body<'a> { - pub fn all_fields(&'a self) -> Box<Iterator<Item = &'a Field<'a>> + 'a> { - match *self { - Body::Enum(ref variants) => { - Box::new(variants.iter().flat_map(|variant| variant.fields.iter())) - } - Body::Struct(_, ref fields) => Box::new(fields.iter()), - } - } - - pub fn has_getter(&self) -> bool { - self.all_fields().any(|f| f.attrs.getter().is_some()) - } -} - -fn enum_from_ast<'a>( - cx: &Ctxt, - variants: &'a [syn::Variant], - container_default: &attr::Default, -) -> Vec<Variant<'a>> { - variants - .iter() - .map(|variant| { - let attrs = attr::Variant::from_ast(cx, variant); - let (style, fields) = - struct_from_ast(cx, &variant.data, Some(&attrs), container_default); - Variant { - ident: variant.ident.clone(), - attrs: attrs, - style: style, - fields: fields, - } - }) - .collect() -} - -fn struct_from_ast<'a>( - cx: &Ctxt, - data: &'a syn::VariantData, - attrs: Option<&attr::Variant>, - container_default: &attr::Default, -) -> (Style, Vec<Field<'a>>) { - match *data { - syn::VariantData::Struct(ref fields) => ( - Style::Struct, - fields_from_ast(cx, fields, attrs, container_default), - ), - syn::VariantData::Tuple(ref fields) if fields.len() == 1 => ( - Style::Newtype, - fields_from_ast(cx, fields, attrs, container_default), - ), - syn::VariantData::Tuple(ref fields) => ( - Style::Tuple, - fields_from_ast(cx, fields, attrs, container_default), - ), - syn::VariantData::Unit => (Style::Unit, Vec::new()), - } -} - -fn fields_from_ast<'a>( - cx: &Ctxt, - fields: &'a [syn::Field], - attrs: Option<&attr::Variant>, - container_default: &attr::Default, -) -> Vec<Field<'a>> { - fields - .iter() - .enumerate() - .map(|(i, field)| Field { - ident: field.ident.clone(), - attrs: attr::Field::from_ast(cx, i, field, attrs, container_default), - ty: &field.ty, - }) - .collect() -} diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.19.0/src/attr.rs cargo-0.26.0/vendor/serde_derive_internals-0.19.0/src/attr.rs --- cargo-0.25.0/vendor/serde_derive_internals-0.19.0/src/attr.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.19.0/src/attr.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1281 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use Ctxt; -use syn; -use syn::MetaItem::{List, NameValue, Word}; -use syn::NestedMetaItem::{Literal, MetaItem}; -use synom::IResult; -use std::collections::BTreeSet; -use std::str::FromStr; - -// This module handles parsing of `#[serde(...)]` attributes. The entrypoints -// are `attr::Container::from_ast`, `attr::Variant::from_ast`, and -// `attr::Field::from_ast`. Each returns an instance of the corresponding -// struct. Note that none of them return a Result. Unrecognized, malformed, or -// duplicated attributes result in a span_err but otherwise are ignored. The -// user will see errors simultaneously for all bad attributes in the crate -// rather than just the first. - -pub use case::RenameRule; - -struct Attr<'c, T> { - cx: &'c Ctxt, - name: &'static str, - value: Option<T>, -} - -impl<'c, T> Attr<'c, T> { - fn none(cx: &'c Ctxt, name: &'static str) -> Self { - Attr { - cx: cx, - name: name, - value: None, - } - } - - fn set(&mut self, value: T) { - if self.value.is_some() { - self.cx - .error(format!("duplicate serde attribute `{}`", self.name)); - } else { - self.value = Some(value); - } - } - - fn set_opt(&mut self, value: Option<T>) { - if let Some(value) = value { - self.set(value); - } - } - - fn set_if_none(&mut self, value: T) { - if self.value.is_none() { - self.value = Some(value); - } - } - - fn get(self) -> Option<T> { - self.value - } -} - -struct BoolAttr<'c>(Attr<'c, ()>); - -impl<'c> BoolAttr<'c> { - fn none(cx: &'c Ctxt, name: &'static str) -> Self { - BoolAttr(Attr::none(cx, name)) - } - - fn set_true(&mut self) { - self.0.set(()); - } - - fn get(&self) -> bool { - self.0.value.is_some() - } -} - -#[derive(Debug)] -pub struct Name { - serialize: String, - deserialize: String, -} - -impl Name { - /// Return the container name for the container when serializing. - pub fn serialize_name(&self) -> String { - self.serialize.clone() - } - - /// Return the container name for the container when deserializing. - pub fn deserialize_name(&self) -> String { - self.deserialize.clone() - } -} - -/// Represents container (e.g. struct) attribute information -#[derive(Debug)] -pub struct Container { - name: Name, - deny_unknown_fields: bool, - default: Default, - rename_all: RenameRule, - ser_bound: Option<Vec<syn::WherePredicate>>, - de_bound: Option<Vec<syn::WherePredicate>>, - tag: EnumTag, - from_type: Option<syn::Ty>, - into_type: Option<syn::Ty>, - remote: Option<syn::Path>, - identifier: Identifier, -} - -/// Styles of representing an enum. -#[derive(Debug)] -pub enum EnumTag { - /// The default. - /// - /// ```json - /// {"variant1": {"key1": "value1", "key2": "value2"}} - /// ``` - External, - - /// `#[serde(tag = "type")]` - /// - /// ```json - /// {"type": "variant1", "key1": "value1", "key2": "value2"} - /// ``` - Internal { tag: String }, - - /// `#[serde(tag = "t", content = "c")]` - /// - /// ```json - /// {"t": "variant1", "c": {"key1": "value1", "key2": "value2"}} - /// ``` - Adjacent { tag: String, content: String }, - - /// `#[serde(untagged)]` - /// - /// ```json - /// {"key1": "value1", "key2": "value2"} - /// ``` - None, -} - -/// Whether this enum represents the fields of a struct or the variants of an -/// enum. -#[derive(Copy, Clone, Debug)] -pub enum Identifier { - /// It does not. - No, - - /// This enum represents the fields of a struct. All of the variants must be - /// unit variants, except possibly one which is annotated with - /// `#[serde(other)]` and is a newtype variant. - Field, - - /// This enum represents the variants of an enum. All of the variants must - /// be unit variants. - Variant, -} - -impl Identifier { - pub fn is_some(self) -> bool { - match self { - Identifier::No => false, - Identifier::Field | Identifier::Variant => true, - } - } -} - -impl Container { - /// Extract out the `#[serde(...)]` attributes from an item. - pub fn from_ast(cx: &Ctxt, item: &syn::DeriveInput) -> Self { - let mut ser_name = Attr::none(cx, "rename"); - let mut de_name = Attr::none(cx, "rename"); - let mut deny_unknown_fields = BoolAttr::none(cx, "deny_unknown_fields"); - let mut default = Attr::none(cx, "default"); - let mut rename_all = Attr::none(cx, "rename_all"); - let mut ser_bound = Attr::none(cx, "bound"); - let mut de_bound = Attr::none(cx, "bound"); - let mut untagged = BoolAttr::none(cx, "untagged"); - let mut internal_tag = Attr::none(cx, "tag"); - let mut content = Attr::none(cx, "content"); - let mut from_type = Attr::none(cx, "from"); - let mut into_type = Attr::none(cx, "into"); - let mut remote = Attr::none(cx, "remote"); - let mut field_identifier = BoolAttr::none(cx, "field_identifier"); - let mut variant_identifier = BoolAttr::none(cx, "variant_identifier"); - - for meta_items in item.attrs.iter().filter_map(get_serde_meta_items) { - for meta_item in meta_items { - match meta_item { - // Parse `#[serde(rename = "foo")]` - MetaItem(NameValue(ref name, ref lit)) if name == "rename" => { - if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) { - ser_name.set(s.clone()); - de_name.set(s); - } - } - - // Parse `#[serde(rename(serialize = "foo", deserialize = "bar"))]` - MetaItem(List(ref name, ref meta_items)) if name == "rename" => { - if let Ok((ser, de)) = get_renames(cx, meta_items) { - ser_name.set_opt(ser); - de_name.set_opt(de); - } - } - - // Parse `#[serde(rename_all = "foo")]` - MetaItem(NameValue(ref name, ref lit)) if name == "rename_all" => { - if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) { - match RenameRule::from_str(&s) { - Ok(rename_rule) => rename_all.set(rename_rule), - Err(()) => cx.error(format!( - "unknown rename rule for #[serde(rename_all \ - = {:?})]", - s - )), - } - } - } - - // Parse `#[serde(deny_unknown_fields)]` - MetaItem(Word(ref name)) if name == "deny_unknown_fields" => { - deny_unknown_fields.set_true(); - } - - // Parse `#[serde(default)]` - MetaItem(Word(ref name)) if name == "default" => match item.body { - syn::Body::Struct(syn::VariantData::Struct(_)) => { - default.set(Default::Default); - } - _ => cx.error( - "#[serde(default)] can only be used on structs \ - with named fields", - ), - }, - - // Parse `#[serde(default = "...")]` - MetaItem(NameValue(ref name, ref lit)) if name == "default" => { - if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) { - match item.body { - syn::Body::Struct(syn::VariantData::Struct(_)) => { - default.set(Default::Path(path)); - } - _ => cx.error( - "#[serde(default = \"...\")] can only be used \ - on structs with named fields", - ), - } - } - } - - // Parse `#[serde(bound = "D: Serialize")]` - MetaItem(NameValue(ref name, ref lit)) if name == "bound" => { - if let Ok(where_predicates) = - parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) - { - ser_bound.set(where_predicates.clone()); - de_bound.set(where_predicates); - } - } - - // Parse `#[serde(bound(serialize = "D: Serialize", deserialize = "D: Deserialize"))]` - MetaItem(List(ref name, ref meta_items)) if name == "bound" => { - if let Ok((ser, de)) = get_where_predicates(cx, meta_items) { - ser_bound.set_opt(ser); - de_bound.set_opt(de); - } - } - - // Parse `#[serde(untagged)]` - MetaItem(Word(ref name)) if name == "untagged" => match item.body { - syn::Body::Enum(_) => { - untagged.set_true(); - } - syn::Body::Struct(_) => { - cx.error("#[serde(untagged)] can only be used on enums") - } - }, - - // Parse `#[serde(tag = "type")]` - MetaItem(NameValue(ref name, ref lit)) if name == "tag" => { - if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) { - match item.body { - syn::Body::Enum(_) => { - internal_tag.set(s); - } - syn::Body::Struct(_) => { - cx.error("#[serde(tag = \"...\")] can only be used on enums") - } - } - } - } - - // Parse `#[serde(content = "c")]` - MetaItem(NameValue(ref name, ref lit)) if name == "content" => { - if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) { - match item.body { - syn::Body::Enum(_) => { - content.set(s); - } - syn::Body::Struct(_) => cx.error( - "#[serde(content = \"...\")] can only be used on \ - enums", - ), - } - } - } - - // Parse `#[serde(from = "Type")] - MetaItem(NameValue(ref name, ref lit)) if name == "from" => { - if let Ok(from_ty) = parse_lit_into_ty(cx, name.as_ref(), lit) { - from_type.set_opt(Some(from_ty)); - } - } - - // Parse `#[serde(into = "Type")] - MetaItem(NameValue(ref name, ref lit)) if name == "into" => { - if let Ok(into_ty) = parse_lit_into_ty(cx, name.as_ref(), lit) { - into_type.set_opt(Some(into_ty)); - } - } - - // Parse `#[serde(remote = "...")]` - MetaItem(NameValue(ref name, ref lit)) if name == "remote" => { - if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) { - remote.set(path); - } - } - - // Parse `#[serde(field_identifier)]` - MetaItem(Word(ref name)) if name == "field_identifier" => { - field_identifier.set_true(); - } - - // Parse `#[serde(variant_identifier)]` - MetaItem(Word(ref name)) if name == "variant_identifier" => { - variant_identifier.set_true(); - } - - MetaItem(ref meta_item) => { - cx.error(format!( - "unknown serde container attribute `{}`", - meta_item.name() - )); - } - - Literal(_) => { - cx.error("unexpected literal in serde container attribute"); - } - } - } - } - - Container { - name: Name { - serialize: ser_name.get().unwrap_or_else(|| item.ident.to_string()), - deserialize: de_name.get().unwrap_or_else(|| item.ident.to_string()), - }, - deny_unknown_fields: deny_unknown_fields.get(), - default: default.get().unwrap_or(Default::None), - rename_all: rename_all.get().unwrap_or(RenameRule::None), - ser_bound: ser_bound.get(), - de_bound: de_bound.get(), - tag: decide_tag(cx, item, untagged, internal_tag, content), - from_type: from_type.get(), - into_type: into_type.get(), - remote: remote.get(), - identifier: decide_identifier(cx, item, field_identifier, variant_identifier), - } - } - - pub fn name(&self) -> &Name { - &self.name - } - - pub fn rename_all(&self) -> &RenameRule { - &self.rename_all - } - - pub fn deny_unknown_fields(&self) -> bool { - self.deny_unknown_fields - } - - pub fn default(&self) -> &Default { - &self.default - } - - pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> { - self.ser_bound.as_ref().map(|vec| &vec[..]) - } - - pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> { - self.de_bound.as_ref().map(|vec| &vec[..]) - } - - pub fn tag(&self) -> &EnumTag { - &self.tag - } - - pub fn from_type(&self) -> Option<&syn::Ty> { - self.from_type.as_ref() - } - - pub fn into_type(&self) -> Option<&syn::Ty> { - self.into_type.as_ref() - } - - pub fn remote(&self) -> Option<&syn::Path> { - self.remote.as_ref() - } - - pub fn identifier(&self) -> Identifier { - self.identifier - } -} - -fn decide_tag( - cx: &Ctxt, - item: &syn::DeriveInput, - untagged: BoolAttr, - internal_tag: Attr<String>, - content: Attr<String>, -) -> EnumTag { - match (untagged.get(), internal_tag.get(), content.get()) { - (false, None, None) => EnumTag::External, - (true, None, None) => EnumTag::None, - (false, Some(tag), None) => { - // Check that there are no tuple variants. - if let syn::Body::Enum(ref variants) = item.body { - for variant in variants { - match variant.data { - syn::VariantData::Struct(_) | syn::VariantData::Unit => {} - syn::VariantData::Tuple(ref fields) => { - if fields.len() != 1 { - cx.error( - "#[serde(tag = \"...\")] cannot be used with tuple \ - variants", - ); - break; - } - } - } - } - } - EnumTag::Internal { tag: tag } - } - (true, Some(_), None) => { - cx.error("enum cannot be both untagged and internally tagged"); - EnumTag::External // doesn't matter, will error - } - (false, None, Some(_)) => { - cx.error("#[serde(tag = \"...\", content = \"...\")] must be used together"); - EnumTag::External - } - (true, None, Some(_)) => { - cx.error("untagged enum cannot have #[serde(content = \"...\")]"); - EnumTag::External - } - (false, Some(tag), Some(content)) => EnumTag::Adjacent { - tag: tag, - content: content, - }, - (true, Some(_), Some(_)) => { - cx.error("untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]"); - EnumTag::External - } - } -} - -fn decide_identifier( - cx: &Ctxt, - item: &syn::DeriveInput, - field_identifier: BoolAttr, - variant_identifier: BoolAttr, -) -> Identifier { - match (&item.body, field_identifier.get(), variant_identifier.get()) { - (_, false, false) => Identifier::No, - (_, true, true) => { - cx.error("`field_identifier` and `variant_identifier` cannot both be set"); - Identifier::No - } - (&syn::Body::Struct(_), true, false) => { - cx.error("`field_identifier` can only be used on an enum"); - Identifier::No - } - (&syn::Body::Struct(_), false, true) => { - cx.error("`variant_identifier` can only be used on an enum"); - Identifier::No - } - (&syn::Body::Enum(_), true, false) => Identifier::Field, - (&syn::Body::Enum(_), false, true) => Identifier::Variant, - } -} - -/// Represents variant attribute information -#[derive(Debug)] -pub struct Variant { - name: Name, - ser_renamed: bool, - de_renamed: bool, - rename_all: RenameRule, - skip_deserializing: bool, - skip_serializing: bool, - other: bool, - serialize_with: Option<syn::Path>, - deserialize_with: Option<syn::Path>, - borrow: Option<syn::MetaItem>, -} - -impl Variant { - pub fn from_ast(cx: &Ctxt, variant: &syn::Variant) -> Self { - let mut ser_name = Attr::none(cx, "rename"); - let mut de_name = Attr::none(cx, "rename"); - let mut skip_deserializing = BoolAttr::none(cx, "skip_deserializing"); - let mut skip_serializing = BoolAttr::none(cx, "skip_serializing"); - let mut rename_all = Attr::none(cx, "rename_all"); - let mut other = BoolAttr::none(cx, "other"); - let mut serialize_with = Attr::none(cx, "serialize_with"); - let mut deserialize_with = Attr::none(cx, "deserialize_with"); - let mut borrow = Attr::none(cx, "borrow"); - - for meta_items in variant.attrs.iter().filter_map(get_serde_meta_items) { - for meta_item in meta_items { - match meta_item { - // Parse `#[serde(rename = "foo")]` - MetaItem(NameValue(ref name, ref lit)) if name == "rename" => { - if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) { - ser_name.set(s.clone()); - de_name.set(s); - } - } - - // Parse `#[serde(rename(serialize = "foo", deserialize = "bar"))]` - MetaItem(List(ref name, ref meta_items)) if name == "rename" => { - if let Ok((ser, de)) = get_renames(cx, meta_items) { - ser_name.set_opt(ser); - de_name.set_opt(de); - } - } - - // Parse `#[serde(rename_all = "foo")]` - MetaItem(NameValue(ref name, ref lit)) if name == "rename_all" => { - if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) { - match RenameRule::from_str(&s) { - Ok(rename_rule) => rename_all.set(rename_rule), - Err(()) => cx.error(format!( - "unknown rename rule for #[serde(rename_all \ - = {:?})]", - s - )), - } - } - } - - // Parse `#[serde(skip_deserializing)]` - MetaItem(Word(ref name)) if name == "skip_deserializing" => { - skip_deserializing.set_true(); - } - - // Parse `#[serde(skip_serializing)]` - MetaItem(Word(ref name)) if name == "skip_serializing" => { - skip_serializing.set_true(); - } - - // Parse `#[serde(other)]` - MetaItem(Word(ref name)) if name == "other" => { - other.set_true(); - } - - // Parse `#[serde(with = "...")]` - MetaItem(NameValue(ref name, ref lit)) if name == "with" => { - if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) { - let mut ser_path = path.clone(); - ser_path.segments.push("serialize".into()); - serialize_with.set(ser_path); - let mut de_path = path; - de_path.segments.push("deserialize".into()); - deserialize_with.set(de_path); - } - } - - // Parse `#[serde(serialize_with = "...")]` - MetaItem(NameValue(ref name, ref lit)) if name == "serialize_with" => { - if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) { - serialize_with.set(path); - } - } - - // Parse `#[serde(deserialize_with = "...")]` - MetaItem(NameValue(ref name, ref lit)) if name == "deserialize_with" => { - if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) { - deserialize_with.set(path); - } - } - - // Defer `#[serde(borrow)]` and `#[serde(borrow = "'a + 'b")]` - MetaItem(ref mi) if mi.name() == "borrow" => match variant.data { - syn::VariantData::Tuple(ref fields) if fields.len() == 1 => { - borrow.set(mi.clone()); - } - _ => { - cx.error("#[serde(borrow)] may only be used on newtype variants"); - } - }, - - MetaItem(ref meta_item) => { - cx.error(format!( - "unknown serde variant attribute `{}`", - meta_item.name() - )); - } - - Literal(_) => { - cx.error("unexpected literal in serde variant attribute"); - } - } - } - } - - let ser_name = ser_name.get(); - let ser_renamed = ser_name.is_some(); - let de_name = de_name.get(); - let de_renamed = de_name.is_some(); - Variant { - name: Name { - serialize: ser_name.unwrap_or_else(|| variant.ident.to_string()), - deserialize: de_name.unwrap_or_else(|| variant.ident.to_string()), - }, - ser_renamed: ser_renamed, - de_renamed: de_renamed, - rename_all: rename_all.get().unwrap_or(RenameRule::None), - skip_deserializing: skip_deserializing.get(), - skip_serializing: skip_serializing.get(), - other: other.get(), - serialize_with: serialize_with.get(), - deserialize_with: deserialize_with.get(), - borrow: borrow.get(), - } - } - - pub fn name(&self) -> &Name { - &self.name - } - - pub fn rename_by_rule(&mut self, rule: &RenameRule) { - if !self.ser_renamed { - self.name.serialize = rule.apply_to_variant(&self.name.serialize); - } - if !self.de_renamed { - self.name.deserialize = rule.apply_to_variant(&self.name.deserialize); - } - } - - pub fn rename_all(&self) -> &RenameRule { - &self.rename_all - } - - pub fn skip_deserializing(&self) -> bool { - self.skip_deserializing - } - - pub fn skip_serializing(&self) -> bool { - self.skip_serializing - } - - pub fn other(&self) -> bool { - self.other - } - - pub fn serialize_with(&self) -> Option<&syn::Path> { - self.serialize_with.as_ref() - } - - pub fn deserialize_with(&self) -> Option<&syn::Path> { - self.deserialize_with.as_ref() - } -} - -/// Represents field attribute information -#[derive(Debug)] -pub struct Field { - name: Name, - ser_renamed: bool, - de_renamed: bool, - skip_serializing: bool, - skip_deserializing: bool, - skip_serializing_if: Option<syn::Path>, - default: Default, - serialize_with: Option<syn::Path>, - deserialize_with: Option<syn::Path>, - ser_bound: Option<Vec<syn::WherePredicate>>, - de_bound: Option<Vec<syn::WherePredicate>>, - borrowed_lifetimes: BTreeSet<syn::Lifetime>, - getter: Option<syn::Path>, -} - -/// Represents the default to use for a field when deserializing. -#[derive(Debug, PartialEq)] -pub enum Default { - /// Field must always be specified because it does not have a default. - None, - /// The default is given by `std::default::Default::default()`. - Default, - /// The default is given by this function. - Path(syn::Path), -} - -impl Field { - /// Extract out the `#[serde(...)]` attributes from a struct field. - pub fn from_ast( - cx: &Ctxt, - index: usize, - field: &syn::Field, - attrs: Option<&Variant>, - container_default: &Default, - ) -> Self { - let mut ser_name = Attr::none(cx, "rename"); - let mut de_name = Attr::none(cx, "rename"); - let mut skip_serializing = BoolAttr::none(cx, "skip_serializing"); - let mut skip_deserializing = BoolAttr::none(cx, "skip_deserializing"); - let mut skip_serializing_if = Attr::none(cx, "skip_serializing_if"); - let mut default = Attr::none(cx, "default"); - let mut serialize_with = Attr::none(cx, "serialize_with"); - let mut deserialize_with = Attr::none(cx, "deserialize_with"); - let mut ser_bound = Attr::none(cx, "bound"); - let mut de_bound = Attr::none(cx, "bound"); - let mut borrowed_lifetimes = Attr::none(cx, "borrow"); - let mut getter = Attr::none(cx, "getter"); - - let ident = match field.ident { - Some(ref ident) => ident.to_string(), - None => index.to_string(), - }; - - let variant_borrow = attrs - .map(|variant| &variant.borrow) - .unwrap_or(&None) - .as_ref() - .map(|borrow| vec![MetaItem(borrow.clone())]); - - for meta_items in field - .attrs - .iter() - .filter_map(get_serde_meta_items) - .chain(variant_borrow) - { - for meta_item in meta_items { - match meta_item { - // Parse `#[serde(rename = "foo")]` - MetaItem(NameValue(ref name, ref lit)) if name == "rename" => { - if let Ok(s) = get_string_from_lit(cx, name.as_ref(), name.as_ref(), lit) { - ser_name.set(s.clone()); - de_name.set(s); - } - } - - // Parse `#[serde(rename(serialize = "foo", deserialize = "bar"))]` - MetaItem(List(ref name, ref meta_items)) if name == "rename" => { - if let Ok((ser, de)) = get_renames(cx, meta_items) { - ser_name.set_opt(ser); - de_name.set_opt(de); - } - } - - // Parse `#[serde(default)]` - MetaItem(Word(ref name)) if name == "default" => { - default.set(Default::Default); - } - - // Parse `#[serde(default = "...")]` - MetaItem(NameValue(ref name, ref lit)) if name == "default" => { - if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) { - default.set(Default::Path(path)); - } - } - - // Parse `#[serde(skip_serializing)]` - MetaItem(Word(ref name)) if name == "skip_serializing" => { - skip_serializing.set_true(); - } - - // Parse `#[serde(skip_deserializing)]` - MetaItem(Word(ref name)) if name == "skip_deserializing" => { - skip_deserializing.set_true(); - } - - // Parse `#[serde(skip)]` - MetaItem(Word(ref name)) if name == "skip" => { - skip_serializing.set_true(); - skip_deserializing.set_true(); - } - - // Parse `#[serde(skip_serializing_if = "...")]` - MetaItem(NameValue(ref name, ref lit)) if name == "skip_serializing_if" => { - if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) { - skip_serializing_if.set(path); - } - } - - // Parse `#[serde(serialize_with = "...")]` - MetaItem(NameValue(ref name, ref lit)) if name == "serialize_with" => { - if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) { - serialize_with.set(path); - } - } - - // Parse `#[serde(deserialize_with = "...")]` - MetaItem(NameValue(ref name, ref lit)) if name == "deserialize_with" => { - if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) { - deserialize_with.set(path); - } - } - - // Parse `#[serde(with = "...")]` - MetaItem(NameValue(ref name, ref lit)) if name == "with" => { - if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) { - let mut ser_path = path.clone(); - ser_path.segments.push("serialize".into()); - serialize_with.set(ser_path); - let mut de_path = path; - de_path.segments.push("deserialize".into()); - deserialize_with.set(de_path); - } - } - - // Parse `#[serde(bound = "D: Serialize")]` - MetaItem(NameValue(ref name, ref lit)) if name == "bound" => { - if let Ok(where_predicates) = - parse_lit_into_where(cx, name.as_ref(), name.as_ref(), lit) - { - ser_bound.set(where_predicates.clone()); - de_bound.set(where_predicates); - } - } - - // Parse `#[serde(bound(serialize = "D: Serialize", deserialize = "D: Deserialize"))]` - MetaItem(List(ref name, ref meta_items)) if name == "bound" => { - if let Ok((ser, de)) = get_where_predicates(cx, meta_items) { - ser_bound.set_opt(ser); - de_bound.set_opt(de); - } - } - - // Parse `#[serde(borrow)]` - MetaItem(Word(ref name)) if name == "borrow" => { - if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, &field.ty) { - borrowed_lifetimes.set(borrowable); - } - } - - // Parse `#[serde(borrow = "'a + 'b")]` - MetaItem(NameValue(ref name, ref lit)) if name == "borrow" => { - if let Ok(lifetimes) = parse_lit_into_lifetimes(cx, name.as_ref(), lit) { - if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, &field.ty) { - for lifetime in &lifetimes { - if !borrowable.contains(lifetime) { - cx.error(format!( - "field `{}` does not have lifetime {}", - ident, lifetime.ident - )); - } - } - borrowed_lifetimes.set(lifetimes); - } - } - } - - // Parse `#[serde(getter = "...")]` - MetaItem(NameValue(ref name, ref lit)) if name == "getter" => { - if let Ok(path) = parse_lit_into_path(cx, name.as_ref(), lit) { - getter.set(path); - } - } - - MetaItem(ref meta_item) => { - cx.error(format!( - "unknown serde field attribute `{}`", - meta_item.name() - )); - } - - Literal(_) => { - cx.error("unexpected literal in serde field attribute"); - } - } - } - } - - // Is skip_deserializing, initialize the field to Default::default() unless a different - // default is specified by `#[serde(default = "...")]` on ourselves or our container (e.g. - // the struct we are in). - if container_default == &Default::None && skip_deserializing.0.value.is_some() { - default.set_if_none(Default::Default); - } - - let mut borrowed_lifetimes = borrowed_lifetimes.get().unwrap_or_default(); - if !borrowed_lifetimes.is_empty() { - // Cow<str> and Cow<[u8]> never borrow by default: - // - // impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T> - // - // A #[serde(borrow)] attribute enables borrowing that corresponds - // roughly to these impls: - // - // impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, str> - // impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, [u8]> - if is_cow(&field.ty, "str") { - let path = syn::parse_path("_serde::private::de::borrow_cow_str").unwrap(); - deserialize_with.set_if_none(path); - } else if is_cow(&field.ty, "[u8]") { - let path = syn::parse_path("_serde::private::de::borrow_cow_bytes").unwrap(); - deserialize_with.set_if_none(path); - } - } else if is_rptr(&field.ty, "str") || is_rptr(&field.ty, "[u8]") { - // Types &str and &[u8] are always implicitly borrowed. No need for - // a #[serde(borrow)]. - borrowed_lifetimes = borrowable_lifetimes(cx, &ident, &field.ty).unwrap(); - } - - let ser_name = ser_name.get(); - let ser_renamed = ser_name.is_some(); - let de_name = de_name.get(); - let de_renamed = de_name.is_some(); - Field { - name: Name { - serialize: ser_name.unwrap_or_else(|| ident.clone()), - deserialize: de_name.unwrap_or(ident), - }, - ser_renamed: ser_renamed, - de_renamed: de_renamed, - skip_serializing: skip_serializing.get(), - skip_deserializing: skip_deserializing.get(), - skip_serializing_if: skip_serializing_if.get(), - default: default.get().unwrap_or(Default::None), - serialize_with: serialize_with.get(), - deserialize_with: deserialize_with.get(), - ser_bound: ser_bound.get(), - de_bound: de_bound.get(), - borrowed_lifetimes: borrowed_lifetimes, - getter: getter.get(), - } - } - - pub fn name(&self) -> &Name { - &self.name - } - - pub fn rename_by_rule(&mut self, rule: &RenameRule) { - if !self.ser_renamed { - self.name.serialize = rule.apply_to_field(&self.name.serialize); - } - if !self.de_renamed { - self.name.deserialize = rule.apply_to_field(&self.name.deserialize); - } - } - - pub fn skip_serializing(&self) -> bool { - self.skip_serializing - } - - pub fn skip_deserializing(&self) -> bool { - self.skip_deserializing - } - - pub fn skip_serializing_if(&self) -> Option<&syn::Path> { - self.skip_serializing_if.as_ref() - } - - pub fn default(&self) -> &Default { - &self.default - } - - pub fn serialize_with(&self) -> Option<&syn::Path> { - self.serialize_with.as_ref() - } - - pub fn deserialize_with(&self) -> Option<&syn::Path> { - self.deserialize_with.as_ref() - } - - pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> { - self.ser_bound.as_ref().map(|vec| &vec[..]) - } - - pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> { - self.de_bound.as_ref().map(|vec| &vec[..]) - } - - pub fn borrowed_lifetimes(&self) -> &BTreeSet<syn::Lifetime> { - &self.borrowed_lifetimes - } - - pub fn getter(&self) -> Option<&syn::Path> { - self.getter.as_ref() - } -} - -type SerAndDe<T> = (Option<T>, Option<T>); - -fn get_ser_and_de<T, F>( - cx: &Ctxt, - attr_name: &'static str, - items: &[syn::NestedMetaItem], - f: F, -) -> Result<SerAndDe<T>, ()> -where - F: Fn(&Ctxt, &str, &str, &syn::Lit) -> Result<T, ()>, -{ - let mut ser_item = Attr::none(cx, attr_name); - let mut de_item = Attr::none(cx, attr_name); - - for item in items { - match *item { - MetaItem(NameValue(ref name, ref lit)) if name == "serialize" => { - if let Ok(v) = f(cx, attr_name, name.as_ref(), lit) { - ser_item.set(v); - } - } - - MetaItem(NameValue(ref name, ref lit)) if name == "deserialize" => { - if let Ok(v) = f(cx, attr_name, name.as_ref(), lit) { - de_item.set(v); - } - } - - _ => { - cx.error(format!( - "malformed {0} attribute, expected `{0}(serialize = ..., \ - deserialize = ...)`", - attr_name - )); - return Err(()); - } - } - } - - Ok((ser_item.get(), de_item.get())) -} - -fn get_renames(cx: &Ctxt, items: &[syn::NestedMetaItem]) -> Result<SerAndDe<String>, ()> { - get_ser_and_de(cx, "rename", items, get_string_from_lit) -} - -fn get_where_predicates( - cx: &Ctxt, - items: &[syn::NestedMetaItem], -) -> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> { - get_ser_and_de(cx, "bound", items, parse_lit_into_where) -} - -pub fn get_serde_meta_items(attr: &syn::Attribute) -> Option<Vec<syn::NestedMetaItem>> { - match attr.value { - List(ref name, ref items) if name == "serde" => Some(items.iter().cloned().collect()), - _ => None, - } -} - -fn get_string_from_lit( - cx: &Ctxt, - attr_name: &str, - meta_item_name: &str, - lit: &syn::Lit, -) -> Result<String, ()> { - if let syn::Lit::Str(ref s, _) = *lit { - Ok(s.clone()) - } else { - cx.error(format!( - "expected serde {} attribute to be a string: `{} = \"...\"`", - attr_name, meta_item_name - )); - Err(()) - } -} - -fn parse_lit_into_path(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn::Path, ()> { - let string = try!(get_string_from_lit(cx, attr_name, attr_name, lit)); - syn::parse_path(&string).map_err(|err| cx.error(err)) -} - -fn parse_lit_into_where( - cx: &Ctxt, - attr_name: &str, - meta_item_name: &str, - lit: &syn::Lit, -) -> Result<Vec<syn::WherePredicate>, ()> { - let string = try!(get_string_from_lit(cx, attr_name, meta_item_name, lit)); - if string.is_empty() { - return Ok(Vec::new()); - } - - let where_string = format!("where {}", string); - - syn::parse_where_clause(&where_string) - .map(|wh| wh.predicates) - .map_err(|err| cx.error(err)) -} - -fn parse_lit_into_ty(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn::Ty, ()> { - let string = try!(get_string_from_lit(cx, attr_name, attr_name, lit)); - - syn::parse_type(&string).map_err(|_| { - cx.error(format!( - "failed to parse type: {} = {:?}", - attr_name, string - )) - }) -} - -// Parses a string literal like "'a + 'b + 'c" containing a nonempty list of -// lifetimes separated by `+`. -fn parse_lit_into_lifetimes( - cx: &Ctxt, - attr_name: &str, - lit: &syn::Lit, -) -> Result<BTreeSet<syn::Lifetime>, ()> { - let string = try!(get_string_from_lit(cx, attr_name, attr_name, lit)); - if string.is_empty() { - cx.error("at least one lifetime must be borrowed"); - return Err(()); - } - - named!(lifetimes -> Vec<syn::Lifetime>, - separated_nonempty_list!(punct!("+"), syn::parse::lifetime) - ); - - if let IResult::Done(rest, o) = lifetimes(&string) { - if rest.trim().is_empty() { - let mut set = BTreeSet::new(); - for lifetime in o { - if !set.insert(lifetime.clone()) { - cx.error(format!("duplicate borrowed lifetime `{}`", lifetime.ident)); - } - } - return Ok(set); - } - } - Err(cx.error(format!("failed to parse borrowed lifetimes: {:?}", string))) -} - -// Whether the type looks like it might be `std::borrow::Cow<T>` where elem="T". -// This can have false negatives and false positives. -// -// False negative: -// -// use std::borrow::Cow as Pig; -// -// #[derive(Deserialize)] -// struct S<'a> { -// #[serde(borrow)] -// pig: Pig<'a, str>, -// } -// -// False positive: -// -// type str = [i16]; -// -// #[derive(Deserialize)] -// struct S<'a> { -// #[serde(borrow)] -// cow: Cow<'a, str>, -// } -fn is_cow(ty: &syn::Ty, elem: &str) -> bool { - let path = match *ty { - syn::Ty::Path(None, ref path) => path, - _ => { - return false; - } - }; - let seg = match path.segments.last() { - Some(seg) => seg, - None => { - return false; - } - }; - let params = match seg.parameters { - syn::PathParameters::AngleBracketed(ref params) => params, - _ => { - return false; - } - }; - seg.ident == "Cow" && params.lifetimes.len() == 1 - && params.types == vec![syn::parse_type(elem).unwrap()] && params.bindings.is_empty() -} - -// Whether the type looks like it might be `&T` where elem="T". This can have -// false negatives and false positives. -// -// False negative: -// -// type Yarn = str; -// -// #[derive(Deserialize)] -// struct S<'a> { -// r: &'a Yarn, -// } -// -// False positive: -// -// type str = [i16]; -// -// #[derive(Deserialize)] -// struct S<'a> { -// r: &'a str, -// } -fn is_rptr(ty: &syn::Ty, elem: &str) -> bool { - match *ty { - syn::Ty::Rptr(Some(_), ref mut_ty) => { - mut_ty.mutability == syn::Mutability::Immutable - && mut_ty.ty == syn::parse_type(elem).unwrap() - } - _ => false, - } -} - -// All lifetimes that this type could borrow from a Deserializer. -// -// For example a type `S<'a, 'b>` could borrow `'a` and `'b`. On the other hand -// a type `for<'a> fn(&'a str)` could not borrow `'a` from the Deserializer. -// -// This is used when there is an explicit or implicit `#[serde(borrow)]` -// attribute on the field so there must be at least one borrowable lifetime. -fn borrowable_lifetimes( - cx: &Ctxt, - name: &str, - ty: &syn::Ty, -) -> Result<BTreeSet<syn::Lifetime>, ()> { - let mut lifetimes = BTreeSet::new(); - collect_lifetimes(ty, &mut lifetimes); - if lifetimes.is_empty() { - Err(cx.error(format!("field `{}` has no lifetimes to borrow", name))) - } else { - Ok(lifetimes) - } -} - -fn collect_lifetimes(ty: &syn::Ty, out: &mut BTreeSet<syn::Lifetime>) { - match *ty { - syn::Ty::Slice(ref elem) | syn::Ty::Array(ref elem, _) | syn::Ty::Paren(ref elem) => { - collect_lifetimes(elem, out); - } - syn::Ty::Ptr(ref elem) => { - collect_lifetimes(&elem.ty, out); - } - syn::Ty::Rptr(ref lifetime, ref elem) => { - out.extend(lifetime.iter().cloned()); - collect_lifetimes(&elem.ty, out); - } - syn::Ty::Tup(ref elems) => for elem in elems { - collect_lifetimes(elem, out); - }, - syn::Ty::Path(ref qself, ref path) => { - if let Some(ref qself) = *qself { - collect_lifetimes(&qself.ty, out); - } - for seg in &path.segments { - if let syn::PathParameters::AngleBracketed(ref params) = seg.parameters { - out.extend(params.lifetimes.iter().cloned()); - for ty in ¶ms.types { - collect_lifetimes(ty, out); - } - for binding in ¶ms.bindings { - collect_lifetimes(&binding.ty, out); - } - } - } - } - syn::Ty::BareFn(_) - | syn::Ty::Never - | syn::Ty::TraitObject(_) - | syn::Ty::ImplTrait(_) - | syn::Ty::Infer - | syn::Ty::Mac(_) => {} - } -} diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.19.0/src/case.rs cargo-0.26.0/vendor/serde_derive_internals-0.19.0/src/case.rs --- cargo-0.25.0/vendor/serde_derive_internals-0.19.0/src/case.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.19.0/src/case.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,186 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// See https://users.rust-lang.org/t/psa-dealing-with-warning-unused-import-std-ascii-asciiext-in-today-s-nightly/13726 -#[allow(unused_imports)] -use std::ascii::AsciiExt; - -use std::str::FromStr; - -use self::RenameRule::*; - -#[derive(Debug, PartialEq)] -pub enum RenameRule { - /// Don't apply a default rename rule. - None, - /// Rename direct children to "lowercase" style. - LowerCase, - /// Rename direct children to "UPPERCASE" style. - UPPERCASE, - /// Rename direct children to "PascalCase" style, as typically used for enum variants. - PascalCase, - /// Rename direct children to "camelCase" style. - CamelCase, - /// Rename direct children to "snake_case" style, as commonly used for fields. - SnakeCase, - /// Rename direct children to "SCREAMING_SNAKE_CASE" style, as commonly used for constants. - ScreamingSnakeCase, - /// Rename direct children to "kebab-case" style. - KebabCase, - /// Rename direct children to "SCREAMING-KEBAB-CASE" style. - ScreamingKebabCase, -} - -impl RenameRule { - pub fn apply_to_variant(&self, variant: &str) -> String { - match *self { - None | PascalCase => variant.to_owned(), - LowerCase => variant.to_ascii_lowercase(), - UPPERCASE => variant.to_ascii_uppercase(), - CamelCase => variant[..1].to_ascii_lowercase() + &variant[1..], - SnakeCase => { - let mut snake = String::new(); - for (i, ch) in variant.char_indices() { - if i > 0 && ch.is_uppercase() { - snake.push('_'); - } - snake.push(ch.to_ascii_lowercase()); - } - snake - } - ScreamingSnakeCase => SnakeCase.apply_to_variant(variant).to_ascii_uppercase(), - KebabCase => SnakeCase.apply_to_variant(variant).replace('_', "-"), - ScreamingKebabCase => ScreamingSnakeCase - .apply_to_variant(variant) - .replace('_', "-"), - } - } - - pub fn apply_to_field(&self, field: &str) -> String { - match *self { - None | LowerCase | SnakeCase => field.to_owned(), - UPPERCASE => field.to_ascii_uppercase(), - PascalCase => { - let mut pascal = String::new(); - let mut capitalize = true; - for ch in field.chars() { - if ch == '_' { - capitalize = true; - } else if capitalize { - pascal.push(ch.to_ascii_uppercase()); - capitalize = false; - } else { - pascal.push(ch); - } - } - pascal - } - CamelCase => { - let pascal = PascalCase.apply_to_field(field); - pascal[..1].to_ascii_lowercase() + &pascal[1..] - } - ScreamingSnakeCase => field.to_ascii_uppercase(), - KebabCase => field.replace('_', "-"), - ScreamingKebabCase => ScreamingSnakeCase.apply_to_field(field).replace('_', "-"), - } - } -} - -impl FromStr for RenameRule { - type Err = (); - - fn from_str(rename_all_str: &str) -> Result<Self, Self::Err> { - match rename_all_str { - "lowercase" => Ok(LowerCase), - "UPPERCASE" => Ok(UPPERCASE), - "PascalCase" => Ok(PascalCase), - "camelCase" => Ok(CamelCase), - "snake_case" => Ok(SnakeCase), - "SCREAMING_SNAKE_CASE" => Ok(ScreamingSnakeCase), - "kebab-case" => Ok(KebabCase), - "SCREAMING-KEBAB-CASE" => Ok(ScreamingKebabCase), - _ => Err(()), - } - } -} - -#[test] -fn rename_variants() { - for &(original, lower, upper, camel, snake, screaming, kebab, screaming_kebab) in &[ - ( - "Outcome", - "outcome", - "OUTCOME", - "outcome", - "outcome", - "OUTCOME", - "outcome", - "OUTCOME", - ), - ( - "VeryTasty", - "verytasty", - "VERYTASTY", - "veryTasty", - "very_tasty", - "VERY_TASTY", - "very-tasty", - "VERY-TASTY", - ), - ("A", "a", "A", "a", "a", "A", "a", "A"), - ("Z42", "z42", "Z42", "z42", "z42", "Z42", "z42", "Z42"), - ] { - assert_eq!(None.apply_to_variant(original), original); - assert_eq!(LowerCase.apply_to_variant(original), lower); - assert_eq!(UPPERCASE.apply_to_variant(original), upper); - assert_eq!(PascalCase.apply_to_variant(original), original); - assert_eq!(CamelCase.apply_to_variant(original), camel); - assert_eq!(SnakeCase.apply_to_variant(original), snake); - assert_eq!(ScreamingSnakeCase.apply_to_variant(original), screaming); - assert_eq!(KebabCase.apply_to_variant(original), kebab); - assert_eq!( - ScreamingKebabCase.apply_to_variant(original), - screaming_kebab - ); - } -} - -#[test] -fn rename_fields() { - for &(original, upper, pascal, camel, screaming, kebab, screaming_kebab) in &[ - ( - "outcome", - "OUTCOME", - "Outcome", - "outcome", - "OUTCOME", - "outcome", - "OUTCOME", - ), - ( - "very_tasty", - "VERY_TASTY", - "VeryTasty", - "veryTasty", - "VERY_TASTY", - "very-tasty", - "VERY-TASTY", - ), - ("a", "A", "A", "a", "A", "a", "A"), - ("z42", "Z42", "Z42", "z42", "Z42", "z42", "Z42"), - ] { - assert_eq!(None.apply_to_field(original), original); - assert_eq!(UPPERCASE.apply_to_field(original), upper); - assert_eq!(PascalCase.apply_to_field(original), pascal); - assert_eq!(CamelCase.apply_to_field(original), camel); - assert_eq!(SnakeCase.apply_to_field(original), original); - assert_eq!(ScreamingSnakeCase.apply_to_field(original), screaming); - assert_eq!(KebabCase.apply_to_field(original), kebab); - assert_eq!(ScreamingKebabCase.apply_to_field(original), screaming_kebab); - } -} diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.19.0/src/check.rs cargo-0.26.0/vendor/serde_derive_internals-0.19.0/src/check.rs --- cargo-0.25.0/vendor/serde_derive_internals-0.19.0/src/check.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.19.0/src/check.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,171 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use ast::{Body, Container, Style}; -use attr::Identifier; -use Ctxt; - -/// Cross-cutting checks that require looking at more than a single attrs -/// object. Simpler checks should happen when parsing and building the attrs. -pub fn check(cx: &Ctxt, cont: &Container) { - check_getter(cx, cont); - check_identifier(cx, cont); - check_variant_skip_attrs(cx, cont); -} - -/// Getters are only allowed inside structs (not enums) with the `remote` -/// attribute. -fn check_getter(cx: &Ctxt, cont: &Container) { - match cont.body { - Body::Enum(_) => { - if cont.body.has_getter() { - cx.error("#[serde(getter = \"...\")] is not allowed in an enum"); - } - } - Body::Struct(_, _) => { - if cont.body.has_getter() && cont.attrs.remote().is_none() { - cx.error( - "#[serde(getter = \"...\")] can only be used in structs \ - that have #[serde(remote = \"...\")]", - ); - } - } - } -} - -/// The `other` attribute must be used at most once and it must be the last -/// variant of an enum that has the `field_identifier` attribute. -/// -/// Inside a `variant_identifier` all variants must be unit variants. Inside a -/// `field_identifier` all but possibly one variant must be unit variants. The -/// last variant may be a newtype variant which is an implicit "other" case. -fn check_identifier(cx: &Ctxt, cont: &Container) { - let variants = match cont.body { - Body::Enum(ref variants) => variants, - Body::Struct(_, _) => { - return; - } - }; - - for (i, variant) in variants.iter().enumerate() { - match ( - variant.style, - cont.attrs.identifier(), - variant.attrs.other(), - ) { - // The `other` attribute may only be used in a field_identifier. - (_, Identifier::Variant, true) | (_, Identifier::No, true) => { - cx.error("#[serde(other)] may only be used inside a field_identifier"); - } - - // Variant with `other` attribute must be the last one. - (Style::Unit, Identifier::Field, true) => { - if i < variants.len() - 1 { - cx.error("#[serde(other)] must be the last variant"); - } - } - - // Variant with `other` attribute must be a unit variant. - (_, Identifier::Field, true) => { - cx.error("#[serde(other)] must be on a unit variant"); - } - - // Any sort of variant is allowed if this is not an identifier. - (_, Identifier::No, false) => {} - - // Unit variant without `other` attribute is always fine. - (Style::Unit, _, false) => {} - - // The last field is allowed to be a newtype catch-all. - (Style::Newtype, Identifier::Field, false) => { - if i < variants.len() - 1 { - cx.error(format!("`{}` must be the last variant", variant.ident)); - } - } - - (_, Identifier::Field, false) => { - cx.error("field_identifier may only contain unit variants"); - } - - (_, Identifier::Variant, false) => { - cx.error("variant_identifier may only contain unit variants"); - } - } - } -} - -/// Skip-(de)serializing attributes are not allowed on variants marked -/// (de)serialize_with. -fn check_variant_skip_attrs(cx: &Ctxt, cont: &Container) { - let variants = match cont.body { - Body::Enum(ref variants) => variants, - Body::Struct(_, _) => { - return; - } - }; - - for variant in variants.iter() { - if variant.attrs.serialize_with().is_some() { - if variant.attrs.skip_serializing() { - cx.error(format!( - "variant `{}` cannot have both #[serde(serialize_with)] and \ - #[serde(skip_serializing)]", - variant.ident - )); - } - - for (i, field) in variant.fields.iter().enumerate() { - let ident = field - .ident - .as_ref() - .map_or_else(|| format!("{}", i), |ident| format!("`{}`", ident)); - - if field.attrs.skip_serializing() { - cx.error(format!( - "variant `{}` cannot have both #[serde(serialize_with)] and \ - a field {} marked with #[serde(skip_serializing)]", - variant.ident, ident - )); - } - - if field.attrs.skip_serializing_if().is_some() { - cx.error(format!( - "variant `{}` cannot have both #[serde(serialize_with)] and \ - a field {} marked with #[serde(skip_serializing_if)]", - variant.ident, ident - )); - } - } - } - - if variant.attrs.deserialize_with().is_some() { - if variant.attrs.skip_deserializing() { - cx.error(format!( - "variant `{}` cannot have both #[serde(deserialize_with)] and \ - #[serde(skip_deserializing)]", - variant.ident - )); - } - - for (i, field) in variant.fields.iter().enumerate() { - if field.attrs.skip_deserializing() { - let ident = field - .ident - .as_ref() - .map_or_else(|| format!("{}", i), |ident| format!("`{}`", ident)); - - cx.error(format!( - "variant `{}` cannot have both #[serde(deserialize_with)] \ - and a field {} marked with #[serde(skip_deserializing)]", - variant.ident, ident - )); - } - } - } - } -} diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.19.0/src/ctxt.rs cargo-0.26.0/vendor/serde_derive_internals-0.19.0/src/ctxt.rs --- cargo-0.25.0/vendor/serde_derive_internals-0.19.0/src/ctxt.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.19.0/src/ctxt.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::fmt::Display; -use std::cell::RefCell; - -#[derive(Default)] -pub struct Ctxt { - errors: RefCell<Option<Vec<String>>>, -} - -impl Ctxt { - pub fn new() -> Self { - Ctxt { - errors: RefCell::new(Some(Vec::new())), - } - } - - pub fn error<T: Display>(&self, msg: T) { - self.errors - .borrow_mut() - .as_mut() - .unwrap() - .push(msg.to_string()); - } - - pub fn check(self) -> Result<(), String> { - let mut errors = self.errors.borrow_mut().take().unwrap(); - match errors.len() { - 0 => Ok(()), - 1 => Err(errors.pop().unwrap()), - n => { - let mut msg = format!("{} errors:", n); - for err in errors { - msg.push_str("\n\t# "); - msg.push_str(&err); - } - Err(msg) - } - } - } -} - -impl Drop for Ctxt { - fn drop(&mut self) { - if self.errors.borrow().is_some() { - panic!("forgot to check for errors"); - } - } -} diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.19.0/src/lib.rs cargo-0.26.0/vendor/serde_derive_internals-0.19.0/src/lib.rs --- cargo-0.25.0/vendor/serde_derive_internals-0.19.0/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.19.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,22 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![doc(html_root_url = "https://docs.rs/serde_derive_internals/0.19.0")] - -extern crate syn; -#[macro_use] -extern crate synom; - -pub mod ast; -pub mod attr; - -mod ctxt; -pub use ctxt::Ctxt; - -mod case; -mod check; diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.23.0/.cargo-checksum.json cargo-0.26.0/vendor/serde_derive_internals-0.23.0/.cargo-checksum.json --- cargo-0.25.0/vendor/serde_derive_internals-0.23.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.23.0/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"89b340a48245bc03ddba31d0ff1709c118df90edc6adabaca4aac77aea181cce"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.23.0/Cargo.toml cargo-0.26.0/vendor/serde_derive_internals-0.23.0/Cargo.toml --- cargo-0.25.0/vendor/serde_derive_internals-0.23.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.23.0/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,33 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "serde_derive_internals" +version = "0.23.0" +authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"] +include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] +description = "AST representation used by Serde derive macros. Unstable." +homepage = "https://serde.rs" +documentation = "https://docs.serde.rs/serde_derive_internals/" +readme = "README.md" +keywords = ["serde", "serialization"] +license = "MIT/Apache-2.0" +repository = "https://github.com/serde-rs/serde" +[dependencies.proc-macro2] +version = "0.3" + +[dependencies.syn] +version = "0.13" +features = ["derive", "parsing", "clone-impls"] +default-features = false +[badges.travis-ci] +repository = "serde-rs/serde" diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.23.0/LICENSE-APACHE cargo-0.26.0/vendor/serde_derive_internals-0.23.0/LICENSE-APACHE --- cargo-0.25.0/vendor/serde_derive_internals-0.23.0/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.23.0/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.23.0/LICENSE-MIT cargo-0.26.0/vendor/serde_derive_internals-0.23.0/LICENSE-MIT --- cargo-0.25.0/vendor/serde_derive_internals-0.23.0/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.23.0/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.23.0/README.md cargo-0.26.0/vendor/serde_derive_internals-0.23.0/README.md --- cargo-0.25.0/vendor/serde_derive_internals-0.23.0/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.23.0/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,104 @@ +# Serde   [![Build Status]][travis] [![Latest Version]][crates.io] [![Rustc Version 1.13+]][rustc] + +[Build Status]: https://api.travis-ci.org/serde-rs/serde.svg?branch=master +[travis]: https://travis-ci.org/serde-rs/serde +[Latest Version]: https://img.shields.io/crates/v/serde.svg +[crates.io]: https://crates.io/crates/serde +[Rustc Version 1.13+]: https://img.shields.io/badge/rustc-1.13+-lightgray.svg +[rustc]: https://blog.rust-lang.org/2016/11/10/Rust-1.13.html + +**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** + +--- + +You may be looking for: + +- [An overview of Serde](https://serde.rs/) +- [Data formats supported by Serde](https://serde.rs/#data-formats) +- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html) +- [Examples](https://serde.rs/examples.html) +- [API documentation](https://docs.serde.rs/serde/) +- [Release notes](https://github.com/serde-rs/serde/releases) + +## Serde in action + +<details> +<summary> +Click to show Cargo.toml. +<a href="http://play.integer32.com/?gist=9003c5b88c1f4989941925d7190c6eec" target="_blank">Run this code in the playground.</a> +</summary> + +```toml +[dependencies] + +# The core APIs, including the Serialize and Deserialize traits. Always +# required when using Serde. +serde = "1.0" + +# Support for #[derive(Serialize, Deserialize)]. Required if you want Serde +# to work for structs and enums defined in your crate. +serde_derive = "1.0" + +# Each data format lives in its own crate; the sample code below uses JSON +# but you may be using a different one. +serde_json = "1.0" +``` + +</details> +<p></p> + +```rust +#[macro_use] +extern crate serde_derive; + +extern crate serde; +extern crate serde_json; + +#[derive(Serialize, Deserialize, Debug)] +struct Point { + x: i32, + y: i32, +} + +fn main() { + let point = Point { x: 1, y: 2 }; + + // Convert the Point to a JSON string. + let serialized = serde_json::to_string(&point).unwrap(); + + // Prints serialized = {"x":1,"y":2} + println!("serialized = {}", serialized); + + // Convert the JSON string back to a Point. + let deserialized: Point = serde_json::from_str(&serialized).unwrap(); + + // Prints deserialized = Point { x: 1, y: 2 } + println!("deserialized = {:?}", deserialized); +} +``` + +## Getting help + +Serde developers live in the #serde channel on +[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a +good resource with generally faster response time but less specific knowledge +about Serde. If IRC is not your thing or you don't get a good response, we are +happy to respond to [GitHub issues](https://github.com/serde-rs/serde/issues/new) +as well. + +## License + +Serde is 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 Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.23.0/src/ast.rs cargo-0.26.0/vendor/serde_derive_internals-0.23.0/src/ast.rs --- cargo-0.25.0/vendor/serde_derive_internals-0.23.0/src/ast.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.23.0/src/ast.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,175 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use syn; +use attr; +use check; +use Ctxt; +use syn::punctuated::Punctuated; + +pub struct Container<'a> { + pub ident: syn::Ident, + pub attrs: attr::Container, + pub data: Data<'a>, + pub generics: &'a syn::Generics, +} + +pub enum Data<'a> { + Enum(Vec<Variant<'a>>), + Struct(Style, Vec<Field<'a>>), +} + +pub struct Variant<'a> { + pub ident: syn::Ident, + pub attrs: attr::Variant, + pub style: Style, + pub fields: Vec<Field<'a>>, +} + +pub struct Field<'a> { + pub ident: Option<syn::Ident>, + pub attrs: attr::Field, + pub ty: &'a syn::Type, + pub original: &'a syn::Field, +} + +#[derive(Copy, Clone)] +pub enum Style { + Struct, + Tuple, + Newtype, + Unit, +} + +impl<'a> Container<'a> { + pub fn from_ast(cx: &Ctxt, item: &'a syn::DeriveInput) -> Container<'a> { + let mut attrs = attr::Container::from_ast(cx, item); + + let mut data = match item.data { + syn::Data::Enum(ref data) => { + Data::Enum(enum_from_ast(cx, &data.variants, attrs.default())) + } + syn::Data::Struct(ref data) => { + let (style, fields) = struct_from_ast(cx, &data.fields, None, attrs.default()); + Data::Struct(style, fields) + } + syn::Data::Union(_) => { + panic!("Serde does not support derive for unions"); + } + }; + + let mut has_flatten = false; + match data { + Data::Enum(ref mut variants) => for variant in variants { + variant.attrs.rename_by_rule(attrs.rename_all()); + for field in &mut variant.fields { + if field.attrs.flatten() { + has_flatten = true; + } + field.attrs.rename_by_rule(variant.attrs.rename_all()); + } + }, + Data::Struct(_, ref mut fields) => for field in fields { + if field.attrs.flatten() { + has_flatten = true; + } + field.attrs.rename_by_rule(attrs.rename_all()); + }, + } + + if has_flatten { + attrs.mark_has_flatten(); + } + + let item = Container { + ident: item.ident, + attrs: attrs, + data: data, + generics: &item.generics, + }; + check::check(cx, &item); + item + } +} + +impl<'a> Data<'a> { + pub fn all_fields(&'a self) -> Box<Iterator<Item = &'a Field<'a>> + 'a> { + match *self { + Data::Enum(ref variants) => { + Box::new(variants.iter().flat_map(|variant| variant.fields.iter())) + } + Data::Struct(_, ref fields) => Box::new(fields.iter()), + } + } + + pub fn has_getter(&self) -> bool { + self.all_fields().any(|f| f.attrs.getter().is_some()) + } +} + +fn enum_from_ast<'a>( + cx: &Ctxt, + variants: &'a Punctuated<syn::Variant, Token![,]>, + container_default: &attr::Default, +) -> Vec<Variant<'a>> { + variants + .iter() + .map(|variant| { + let attrs = attr::Variant::from_ast(cx, variant); + let (style, fields) = + struct_from_ast(cx, &variant.fields, Some(&attrs), container_default); + Variant { + ident: variant.ident, + attrs: attrs, + style: style, + fields: fields, + } + }) + .collect() +} + +fn struct_from_ast<'a>( + cx: &Ctxt, + fields: &'a syn::Fields, + attrs: Option<&attr::Variant>, + container_default: &attr::Default, +) -> (Style, Vec<Field<'a>>) { + match *fields { + syn::Fields::Named(ref fields) => ( + Style::Struct, + fields_from_ast(cx, &fields.named, attrs, container_default), + ), + syn::Fields::Unnamed(ref fields) if fields.unnamed.len() == 1 => ( + Style::Newtype, + fields_from_ast(cx, &fields.unnamed, attrs, container_default), + ), + syn::Fields::Unnamed(ref fields) => ( + Style::Tuple, + fields_from_ast(cx, &fields.unnamed, attrs, container_default), + ), + syn::Fields::Unit => (Style::Unit, Vec::new()), + } +} + +fn fields_from_ast<'a>( + cx: &Ctxt, + fields: &'a Punctuated<syn::Field, Token![,]>, + attrs: Option<&attr::Variant>, + container_default: &attr::Default, +) -> Vec<Field<'a>> { + fields + .iter() + .enumerate() + .map(|(i, field)| Field { + ident: field.ident, + attrs: attr::Field::from_ast(cx, i, field, attrs, container_default), + ty: &field.ty, + original: field, + }) + .collect() +} diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.23.0/src/attr.rs cargo-0.26.0/vendor/serde_derive_internals-0.23.0/src/attr.rs --- cargo-0.25.0/vendor/serde_derive_internals-0.23.0/src/attr.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.23.0/src/attr.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1426 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use Ctxt; +use syn; +use syn::Ident; +use syn::Meta::{List, NameValue, Word}; +use syn::NestedMeta::{Literal, Meta}; +use syn::punctuated::Punctuated; +use syn::synom::{Synom, ParseError}; +use std::collections::BTreeSet; +use std::str::FromStr; +use proc_macro2::{Span, TokenStream, TokenTree, Group}; + +// This module handles parsing of `#[serde(...)]` attributes. The entrypoints +// are `attr::Container::from_ast`, `attr::Variant::from_ast`, and +// `attr::Field::from_ast`. Each returns an instance of the corresponding +// struct. Note that none of them return a Result. Unrecognized, malformed, or +// duplicated attributes result in a span_err but otherwise are ignored. The +// user will see errors simultaneously for all bad attributes in the crate +// rather than just the first. + +pub use case::RenameRule; + +#[derive(Copy, Clone)] +struct Attr<'c, T> { + cx: &'c Ctxt, + name: &'static str, + value: Option<T>, +} + +impl<'c, T> Attr<'c, T> { + fn none(cx: &'c Ctxt, name: &'static str) -> Self { + Attr { + cx: cx, + name: name, + value: None, + } + } + + fn set(&mut self, value: T) { + if self.value.is_some() { + self.cx + .error(format!("duplicate serde attribute `{}`", self.name)); + } else { + self.value = Some(value); + } + } + + fn set_opt(&mut self, value: Option<T>) { + if let Some(value) = value { + self.set(value); + } + } + + fn set_if_none(&mut self, value: T) { + if self.value.is_none() { + self.value = Some(value); + } + } + + fn get(self) -> Option<T> { + self.value + } +} + +struct BoolAttr<'c>(Attr<'c, ()>); + +impl<'c> BoolAttr<'c> { + fn none(cx: &'c Ctxt, name: &'static str) -> Self { + BoolAttr(Attr::none(cx, name)) + } + + fn set_true(&mut self) { + self.0.set(()); + } + + fn get(&self) -> bool { + self.0.value.is_some() + } +} + +pub struct Name { + serialize: String, + deserialize: String, +} + +impl Name { + /// Return the container name for the container when serializing. + pub fn serialize_name(&self) -> String { + self.serialize.clone() + } + + /// Return the container name for the container when deserializing. + pub fn deserialize_name(&self) -> String { + self.deserialize.clone() + } +} + +/// Represents container (e.g. struct) attribute information +pub struct Container { + name: Name, + deny_unknown_fields: bool, + default: Default, + rename_all: RenameRule, + ser_bound: Option<Vec<syn::WherePredicate>>, + de_bound: Option<Vec<syn::WherePredicate>>, + tag: EnumTag, + type_from: Option<syn::Type>, + type_into: Option<syn::Type>, + remote: Option<syn::Path>, + identifier: Identifier, + has_flatten: bool, +} + +/// Styles of representing an enum. +pub enum EnumTag { + /// The default. + /// + /// ```json + /// {"variant1": {"key1": "value1", "key2": "value2"}} + /// ``` + External, + + /// `#[serde(tag = "type")]` + /// + /// ```json + /// {"type": "variant1", "key1": "value1", "key2": "value2"} + /// ``` + Internal { tag: String }, + + /// `#[serde(tag = "t", content = "c")]` + /// + /// ```json + /// {"t": "variant1", "c": {"key1": "value1", "key2": "value2"}} + /// ``` + Adjacent { tag: String, content: String }, + + /// `#[serde(untagged)]` + /// + /// ```json + /// {"key1": "value1", "key2": "value2"} + /// ``` + None, +} + +/// Whether this enum represents the fields of a struct or the variants of an +/// enum. +#[derive(Copy, Clone)] +pub enum Identifier { + /// It does not. + No, + + /// This enum represents the fields of a struct. All of the variants must be + /// unit variants, except possibly one which is annotated with + /// `#[serde(other)]` and is a newtype variant. + Field, + + /// This enum represents the variants of an enum. All of the variants must + /// be unit variants. + Variant, +} + +impl Identifier { + pub fn is_some(self) -> bool { + match self { + Identifier::No => false, + Identifier::Field | Identifier::Variant => true, + } + } +} + +impl Container { + /// Extract out the `#[serde(...)]` attributes from an item. + pub fn from_ast(cx: &Ctxt, item: &syn::DeriveInput) -> Self { + let mut ser_name = Attr::none(cx, "rename"); + let mut de_name = Attr::none(cx, "rename"); + let mut deny_unknown_fields = BoolAttr::none(cx, "deny_unknown_fields"); + let mut default = Attr::none(cx, "default"); + let mut rename_all = Attr::none(cx, "rename_all"); + let mut ser_bound = Attr::none(cx, "bound"); + let mut de_bound = Attr::none(cx, "bound"); + let mut untagged = BoolAttr::none(cx, "untagged"); + let mut internal_tag = Attr::none(cx, "tag"); + let mut content = Attr::none(cx, "content"); + let mut type_from = Attr::none(cx, "from"); + let mut type_into = Attr::none(cx, "into"); + let mut remote = Attr::none(cx, "remote"); + let mut field_identifier = BoolAttr::none(cx, "field_identifier"); + let mut variant_identifier = BoolAttr::none(cx, "variant_identifier"); + + for meta_items in item.attrs.iter().filter_map(get_serde_meta_items) { + for meta_item in meta_items { + match meta_item { + // Parse `#[serde(rename = "foo")]` + Meta(NameValue(ref m)) if m.ident == "rename" => { + if let Ok(s) = get_lit_str(cx, m.ident.as_ref(), m.ident.as_ref(), &m.lit) { + ser_name.set(s.value()); + de_name.set(s.value()); + } + } + + // Parse `#[serde(rename(serialize = "foo", deserialize = "bar"))]` + Meta(List(ref m)) if m.ident == "rename" => { + if let Ok((ser, de)) = get_renames(cx, &m.nested) { + ser_name.set_opt(ser.map(syn::LitStr::value)); + de_name.set_opt(de.map(syn::LitStr::value)); + } + } + + // Parse `#[serde(rename_all = "foo")]` + Meta(NameValue(ref m)) if m.ident == "rename_all" => { + if let Ok(s) = get_lit_str(cx, m.ident.as_ref(), m.ident.as_ref(), &m.lit) { + match RenameRule::from_str(&s.value()) { + Ok(rename_rule) => rename_all.set(rename_rule), + Err(()) => cx.error(format!( + "unknown rename rule for #[serde(rename_all \ + = {:?})]", + s.value() + )), + } + } + } + + // Parse `#[serde(deny_unknown_fields)]` + Meta(Word(word)) if word == "deny_unknown_fields" => { + deny_unknown_fields.set_true(); + } + + // Parse `#[serde(default)]` + Meta(Word(word)) if word == "default" => match item.data { + syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(_), .. }) => { + default.set(Default::Default); + } + _ => cx.error( + "#[serde(default)] can only be used on structs \ + with named fields", + ), + }, + + // Parse `#[serde(default = "...")]` + Meta(NameValue(ref m)) if m.ident == "default" => { + if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) { + match item.data { + syn::Data::Struct(syn::DataStruct { fields: syn::Fields::Named(_), .. }) => { + default.set(Default::Path(path)); + } + _ => cx.error( + "#[serde(default = \"...\")] can only be used \ + on structs with named fields", + ), + } + } + } + + // Parse `#[serde(bound = "D: Serialize")]` + Meta(NameValue(ref m)) if m.ident == "bound" => { + if let Ok(where_predicates) = + parse_lit_into_where(cx, m.ident.as_ref(), m.ident.as_ref(), &m.lit) + { + ser_bound.set(where_predicates.clone()); + de_bound.set(where_predicates); + } + } + + // Parse `#[serde(bound(serialize = "D: Serialize", deserialize = "D: Deserialize"))]` + Meta(List(ref m)) if m.ident == "bound" => { + if let Ok((ser, de)) = get_where_predicates(cx, &m.nested) { + ser_bound.set_opt(ser); + de_bound.set_opt(de); + } + } + + // Parse `#[serde(untagged)]` + Meta(Word(word)) if word == "untagged" => match item.data { + syn::Data::Enum(_) => { + untagged.set_true(); + } + syn::Data::Struct(_) | syn::Data::Union(_) => { + cx.error("#[serde(untagged)] can only be used on enums") + } + }, + + // Parse `#[serde(tag = "type")]` + Meta(NameValue(ref m)) if m.ident == "tag" => { + if let Ok(s) = get_lit_str(cx, m.ident.as_ref(), m.ident.as_ref(), &m.lit) { + match item.data { + syn::Data::Enum(_) => { + internal_tag.set(s.value()); + } + syn::Data::Struct(_) | syn::Data::Union(_) => { + cx.error("#[serde(tag = \"...\")] can only be used on enums") + } + } + } + } + + // Parse `#[serde(content = "c")]` + Meta(NameValue(ref m)) if m.ident == "content" => { + if let Ok(s) = get_lit_str(cx, m.ident.as_ref(), m.ident.as_ref(), &m.lit) { + match item.data { + syn::Data::Enum(_) => { + content.set(s.value()); + } + syn::Data::Struct(_) | syn::Data::Union(_) => cx.error( + "#[serde(content = \"...\")] can only be used on \ + enums", + ), + } + } + } + + // Parse `#[serde(from = "Type")] + Meta(NameValue(ref m)) if m.ident == "from" => { + if let Ok(from_ty) = parse_lit_into_ty(cx, m.ident.as_ref(), &m.lit) { + type_from.set_opt(Some(from_ty)); + } + } + + // Parse `#[serde(into = "Type")] + Meta(NameValue(ref m)) if m.ident == "into" => { + if let Ok(into_ty) = parse_lit_into_ty(cx, m.ident.as_ref(), &m.lit) { + type_into.set_opt(Some(into_ty)); + } + } + + // Parse `#[serde(remote = "...")]` + Meta(NameValue(ref m)) if m.ident == "remote" => { + if let Ok(path) = parse_lit_into_path(cx, m.ident.as_ref(), &m.lit) { + if is_primitive_path(&path, "Self") { + remote.set(item.ident.into()); + } else { + remote.set(path); + } + } + } + + // Parse `#[serde(field_identifier)]` + Meta(Word(word)) if word == "field_identifier" => { + field_identifier.set_true(); + } + + // Parse `#[serde(variant_identifier)]` + Meta(Word(word)) if word == "variant_identifier" => { + variant_identifier.set_true(); + } + + Meta(ref meta_item) => { + cx.error(format!( + "unknown serde container attribute `{}`", + meta_item.name() + )); + } + + Literal(_) => { + cx.error("unexpected literal in serde container attribute"); + } + } + } + } + + Container { + name: Name { + serialize: ser_name.get().unwrap_or_else(|| item.ident.to_string()), + deserialize: de_name.get().unwrap_or_else(|| item.ident.to_string()), + }, + deny_unknown_fields: deny_unknown_fields.get(), + default: default.get().unwrap_or(Default::None), + rename_all: rename_all.get().unwrap_or(RenameRule::None), + ser_bound: ser_bound.get(), + de_bound: de_bound.get(), + tag: decide_tag(cx, item, &untagged, internal_tag, content), + type_from: type_from.get(), + type_into: type_into.get(), + remote: remote.get(), + identifier: decide_identifier(cx, item, &field_identifier, &variant_identifier), + has_flatten: false, + } + } + + pub fn name(&self) -> &Name { + &self.name + } + + pub fn rename_all(&self) -> &RenameRule { + &self.rename_all + } + + pub fn deny_unknown_fields(&self) -> bool { + self.deny_unknown_fields + } + + pub fn default(&self) -> &Default { + &self.default + } + + pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> { + self.ser_bound.as_ref().map(|vec| &vec[..]) + } + + pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> { + self.de_bound.as_ref().map(|vec| &vec[..]) + } + + pub fn tag(&self) -> &EnumTag { + &self.tag + } + + pub fn type_from(&self) -> Option<&syn::Type> { + self.type_from.as_ref() + } + + pub fn type_into(&self) -> Option<&syn::Type> { + self.type_into.as_ref() + } + + pub fn remote(&self) -> Option<&syn::Path> { + self.remote.as_ref() + } + + pub fn identifier(&self) -> Identifier { + self.identifier + } + + pub fn has_flatten(&self) -> bool { + self.has_flatten + } + + pub fn mark_has_flatten(&mut self) { + self.has_flatten = true; + } +} + +fn decide_tag( + cx: &Ctxt, + item: &syn::DeriveInput, + untagged: &BoolAttr, + internal_tag: Attr<String>, + content: Attr<String>, +) -> EnumTag { + match (untagged.get(), internal_tag.get(), content.get()) { + (false, None, None) => EnumTag::External, + (true, None, None) => EnumTag::None, + (false, Some(tag), None) => { + // Check that there are no tuple variants. + if let syn::Data::Enum(ref data) = item.data { + for variant in &data.variants { + match variant.fields { + syn::Fields::Named(_) | syn::Fields::Unit => {} + syn::Fields::Unnamed(ref fields) => { + if fields.unnamed.len() != 1 { + cx.error( + "#[serde(tag = \"...\")] cannot be used with tuple \ + variants", + ); + break; + } + } + } + } + } + EnumTag::Internal { tag: tag } + } + (true, Some(_), None) => { + cx.error("enum cannot be both untagged and internally tagged"); + EnumTag::External // doesn't matter, will error + } + (false, None, Some(_)) => { + cx.error("#[serde(tag = \"...\", content = \"...\")] must be used together"); + EnumTag::External + } + (true, None, Some(_)) => { + cx.error("untagged enum cannot have #[serde(content = \"...\")]"); + EnumTag::External + } + (false, Some(tag), Some(content)) => EnumTag::Adjacent { + tag: tag, + content: content, + }, + (true, Some(_), Some(_)) => { + cx.error("untagged enum cannot have #[serde(tag = \"...\", content = \"...\")]"); + EnumTag::External + } + } +} + +fn decide_identifier( + cx: &Ctxt, + item: &syn::DeriveInput, + field_identifier: &BoolAttr, + variant_identifier: &BoolAttr, +) -> Identifier { + match (&item.data, field_identifier.get(), variant_identifier.get()) { + (_, false, false) => Identifier::No, + (_, true, true) => { + cx.error("`field_identifier` and `variant_identifier` cannot both be set"); + Identifier::No + } + (&syn::Data::Enum(_), true, false) => Identifier::Field, + (&syn::Data::Enum(_), false, true) => Identifier::Variant, + (&syn::Data::Struct(_), true, false) + | (&syn::Data::Union(_), true, false) => { + cx.error("`field_identifier` can only be used on an enum"); + Identifier::No + } + (&syn::Data::Struct(_), false, true) + | (&syn::Data::Union(_), false, true) => { + cx.error("`variant_identifier` can only be used on an enum"); + Identifier::No + } + } +} + +/// Represents variant attribute information +pub struct Variant { + name: Name, + ser_renamed: bool, + de_renamed: bool, + rename_all: RenameRule, + skip_deserializing: bool, + skip_serializing: bool, + other: bool, + serialize_with: Option<syn::ExprPath>, + deserialize_with: Option<syn::ExprPath>, + borrow: Option<syn::Meta>, +} + +impl Variant { + pub fn from_ast(cx: &Ctxt, variant: &syn::Variant) -> Self { + let mut ser_name = Attr::none(cx, "rename"); + let mut de_name = Attr::none(cx, "rename"); + let mut skip_deserializing = BoolAttr::none(cx, "skip_deserializing"); + let mut skip_serializing = BoolAttr::none(cx, "skip_serializing"); + let mut rename_all = Attr::none(cx, "rename_all"); + let mut other = BoolAttr::none(cx, "other"); + let mut serialize_with = Attr::none(cx, "serialize_with"); + let mut deserialize_with = Attr::none(cx, "deserialize_with"); + let mut borrow = Attr::none(cx, "borrow"); + + for meta_items in variant.attrs.iter().filter_map(get_serde_meta_items) { + for meta_item in meta_items { + match meta_item { + // Parse `#[serde(rename = "foo")]` + Meta(NameValue(ref m)) if m.ident == "rename" => { + if let Ok(s) = get_lit_str(cx, m.ident.as_ref(), m.ident.as_ref(), &m.lit) { + ser_name.set(s.value()); + de_name.set(s.value()); + } + } + + // Parse `#[serde(rename(serialize = "foo", deserialize = "bar"))]` + Meta(List(ref m)) if m.ident == "rename" => { + if let Ok((ser, de)) = get_renames(cx, &m.nested) { + ser_name.set_opt(ser.map(syn::LitStr::value)); + de_name.set_opt(de.map(syn::LitStr::value)); + } + } + + // Parse `#[serde(rename_all = "foo")]` + Meta(NameValue(ref m)) if m.ident == "rename_all" => { + if let Ok(s) = get_lit_str(cx, m.ident.as_ref(), m.ident.as_ref(), &m.lit) { + match RenameRule::from_str(&s.value()) { + Ok(rename_rule) => rename_all.set(rename_rule), + Err(()) => cx.error(format!( + "unknown rename rule for #[serde(rename_all \ + = {:?})]", + s.value() + )), + } + } + } + + // Parse `#[serde(skip_deserializing)]` + Meta(Word(word)) if word == "skip_deserializing" => { + skip_deserializing.set_true(); + } + + // Parse `#[serde(skip_serializing)]` + Meta(Word(word)) if word == "skip_serializing" => { + skip_serializing.set_true(); + } + + // Parse `#[serde(other)]` + Meta(Word(word)) if word == "other" => { + other.set_true(); + } + + // Parse `#[serde(with = "...")]` + Meta(NameValue(ref m)) if m.ident == "with" => { + if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) { + let mut ser_path = path.clone(); + ser_path.path.segments.push(Ident::new("serialize", Span::call_site()).into()); + serialize_with.set(ser_path); + let mut de_path = path; + de_path.path.segments.push(Ident::new("deserialize", Span::call_site()).into()); + deserialize_with.set(de_path); + } + } + + // Parse `#[serde(serialize_with = "...")]` + Meta(NameValue(ref m)) if m.ident == "serialize_with" => { + if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) { + serialize_with.set(path); + } + } + + // Parse `#[serde(deserialize_with = "...")]` + Meta(NameValue(ref m)) if m.ident == "deserialize_with" => { + if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) { + deserialize_with.set(path); + } + } + + // Defer `#[serde(borrow)]` and `#[serde(borrow = "'a + 'b")]` + Meta(ref m) if m.name() == "borrow" => match variant.fields { + syn::Fields::Unnamed(ref fields) if fields.unnamed.len() == 1 => { + borrow.set(m.clone()); + } + _ => { + cx.error("#[serde(borrow)] may only be used on newtype variants"); + } + }, + + Meta(ref meta_item) => { + cx.error(format!( + "unknown serde variant attribute `{}`", + meta_item.name() + )); + } + + Literal(_) => { + cx.error("unexpected literal in serde variant attribute"); + } + } + } + } + + let ser_name = ser_name.get(); + let ser_renamed = ser_name.is_some(); + let de_name = de_name.get(); + let de_renamed = de_name.is_some(); + Variant { + name: Name { + serialize: ser_name.unwrap_or_else(|| variant.ident.to_string()), + deserialize: de_name.unwrap_or_else(|| variant.ident.to_string()), + }, + ser_renamed: ser_renamed, + de_renamed: de_renamed, + rename_all: rename_all.get().unwrap_or(RenameRule::None), + skip_deserializing: skip_deserializing.get(), + skip_serializing: skip_serializing.get(), + other: other.get(), + serialize_with: serialize_with.get(), + deserialize_with: deserialize_with.get(), + borrow: borrow.get(), + } + } + + pub fn name(&self) -> &Name { + &self.name + } + + pub fn rename_by_rule(&mut self, rule: &RenameRule) { + if !self.ser_renamed { + self.name.serialize = rule.apply_to_variant(&self.name.serialize); + } + if !self.de_renamed { + self.name.deserialize = rule.apply_to_variant(&self.name.deserialize); + } + } + + pub fn rename_all(&self) -> &RenameRule { + &self.rename_all + } + + pub fn skip_deserializing(&self) -> bool { + self.skip_deserializing + } + + pub fn skip_serializing(&self) -> bool { + self.skip_serializing + } + + pub fn other(&self) -> bool { + self.other + } + + pub fn serialize_with(&self) -> Option<&syn::ExprPath> { + self.serialize_with.as_ref() + } + + pub fn deserialize_with(&self) -> Option<&syn::ExprPath> { + self.deserialize_with.as_ref() + } +} + +/// Represents field attribute information +pub struct Field { + name: Name, + ser_renamed: bool, + de_renamed: bool, + skip_serializing: bool, + skip_deserializing: bool, + skip_serializing_if: Option<syn::ExprPath>, + default: Default, + serialize_with: Option<syn::ExprPath>, + deserialize_with: Option<syn::ExprPath>, + ser_bound: Option<Vec<syn::WherePredicate>>, + de_bound: Option<Vec<syn::WherePredicate>>, + borrowed_lifetimes: BTreeSet<syn::Lifetime>, + getter: Option<syn::ExprPath>, + flatten: bool, +} + +/// Represents the default to use for a field when deserializing. +pub enum Default { + /// Field must always be specified because it does not have a default. + None, + /// The default is given by `std::default::Default::default()`. + Default, + /// The default is given by this function. + Path(syn::ExprPath), +} + +impl Field { + /// Extract out the `#[serde(...)]` attributes from a struct field. + pub fn from_ast( + cx: &Ctxt, + index: usize, + field: &syn::Field, + attrs: Option<&Variant>, + container_default: &Default, + ) -> Self { + let mut ser_name = Attr::none(cx, "rename"); + let mut de_name = Attr::none(cx, "rename"); + let mut skip_serializing = BoolAttr::none(cx, "skip_serializing"); + let mut skip_deserializing = BoolAttr::none(cx, "skip_deserializing"); + let mut skip_serializing_if = Attr::none(cx, "skip_serializing_if"); + let mut default = Attr::none(cx, "default"); + let mut serialize_with = Attr::none(cx, "serialize_with"); + let mut deserialize_with = Attr::none(cx, "deserialize_with"); + let mut ser_bound = Attr::none(cx, "bound"); + let mut de_bound = Attr::none(cx, "bound"); + let mut borrowed_lifetimes = Attr::none(cx, "borrow"); + let mut getter = Attr::none(cx, "getter"); + let mut flatten = BoolAttr::none(cx, "flatten"); + + let ident = match field.ident { + Some(ref ident) => ident.to_string(), + None => index.to_string(), + }; + + let variant_borrow = attrs + .map(|variant| &variant.borrow) + .unwrap_or(&None) + .as_ref() + .map(|borrow| vec![Meta(borrow.clone())]); + + for meta_items in field + .attrs + .iter() + .filter_map(get_serde_meta_items) + .chain(variant_borrow) + { + for meta_item in meta_items { + match meta_item { + // Parse `#[serde(rename = "foo")]` + Meta(NameValue(ref m)) if m.ident == "rename" => { + if let Ok(s) = get_lit_str(cx, m.ident.as_ref(), m.ident.as_ref(), &m.lit) { + ser_name.set(s.value()); + de_name.set(s.value()); + } + } + + // Parse `#[serde(rename(serialize = "foo", deserialize = "bar"))]` + Meta(List(ref m)) if m.ident == "rename" => { + if let Ok((ser, de)) = get_renames(cx, &m.nested) { + ser_name.set_opt(ser.map(syn::LitStr::value)); + de_name.set_opt(de.map(syn::LitStr::value)); + } + } + + // Parse `#[serde(default)]` + Meta(Word(word)) if word == "default" => { + default.set(Default::Default); + } + + // Parse `#[serde(default = "...")]` + Meta(NameValue(ref m)) if m.ident == "default" => { + if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) { + default.set(Default::Path(path)); + } + } + + // Parse `#[serde(skip_serializing)]` + Meta(Word(word)) if word == "skip_serializing" => { + skip_serializing.set_true(); + } + + // Parse `#[serde(skip_deserializing)]` + Meta(Word(word)) if word == "skip_deserializing" => { + skip_deserializing.set_true(); + } + + // Parse `#[serde(skip)]` + Meta(Word(word)) if word == "skip" => { + skip_serializing.set_true(); + skip_deserializing.set_true(); + } + + // Parse `#[serde(skip_serializing_if = "...")]` + Meta(NameValue(ref m)) if m.ident == "skip_serializing_if" => { + if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) { + skip_serializing_if.set(path); + } + } + + // Parse `#[serde(serialize_with = "...")]` + Meta(NameValue(ref m)) if m.ident == "serialize_with" => { + if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) { + serialize_with.set(path); + } + } + + // Parse `#[serde(deserialize_with = "...")]` + Meta(NameValue(ref m)) if m.ident == "deserialize_with" => { + if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) { + deserialize_with.set(path); + } + } + + // Parse `#[serde(with = "...")]` + Meta(NameValue(ref m)) if m.ident == "with" => { + if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) { + let mut ser_path = path.clone(); + ser_path.path.segments.push(Ident::new("serialize", Span::call_site()).into()); + serialize_with.set(ser_path); + let mut de_path = path; + de_path.path.segments.push(Ident::new("deserialize", Span::call_site()).into()); + deserialize_with.set(de_path); + } + } + + // Parse `#[serde(bound = "D: Serialize")]` + Meta(NameValue(ref m)) if m.ident == "bound" => { + if let Ok(where_predicates) = + parse_lit_into_where(cx, m.ident.as_ref(), m.ident.as_ref(), &m.lit) + { + ser_bound.set(where_predicates.clone()); + de_bound.set(where_predicates); + } + } + + // Parse `#[serde(bound(serialize = "D: Serialize", deserialize = "D: Deserialize"))]` + Meta(List(ref m)) if m.ident == "bound" => { + if let Ok((ser, de)) = get_where_predicates(cx, &m.nested) { + ser_bound.set_opt(ser); + de_bound.set_opt(de); + } + } + + // Parse `#[serde(borrow)]` + Meta(Word(word)) if word == "borrow" => { + if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, &field.ty) { + borrowed_lifetimes.set(borrowable); + } + } + + // Parse `#[serde(borrow = "'a + 'b")]` + Meta(NameValue(ref m)) if m.ident == "borrow" => { + if let Ok(lifetimes) = parse_lit_into_lifetimes(cx, m.ident.as_ref(), &m.lit) { + if let Ok(borrowable) = borrowable_lifetimes(cx, &ident, &field.ty) { + for lifetime in &lifetimes { + if !borrowable.contains(lifetime) { + cx.error(format!( + "field `{}` does not have lifetime {}", + ident, lifetime + )); + } + } + borrowed_lifetimes.set(lifetimes); + } + } + } + + // Parse `#[serde(getter = "...")]` + Meta(NameValue(ref m)) if m.ident == "getter" => { + if let Ok(path) = parse_lit_into_expr_path(cx, m.ident.as_ref(), &m.lit) { + getter.set(path); + } + } + + // Parse `#[serde(flatten)]` + Meta(Word(word)) if word == "flatten" => { + flatten.set_true(); + } + + Meta(ref meta_item) => { + cx.error(format!( + "unknown serde field attribute `{}`", + meta_item.name() + )); + } + + Literal(_) => { + cx.error("unexpected literal in serde field attribute"); + } + } + } + } + + // Is skip_deserializing, initialize the field to Default::default() unless a different + // default is specified by `#[serde(default = "...")]` on ourselves or our container (e.g. + // the struct we are in). + if let Default::None = *container_default { + if skip_deserializing.0.value.is_some() { + default.set_if_none(Default::Default); + } + } + + let mut borrowed_lifetimes = borrowed_lifetimes.get().unwrap_or_default(); + if !borrowed_lifetimes.is_empty() { + // Cow<str> and Cow<[u8]> never borrow by default: + // + // impl<'de, 'a, T: ?Sized> Deserialize<'de> for Cow<'a, T> + // + // A #[serde(borrow)] attribute enables borrowing that corresponds + // roughly to these impls: + // + // impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, str> + // impl<'de: 'a, 'a> Deserialize<'de> for Cow<'a, [u8]> + if is_cow(&field.ty, is_str) { + let mut path = syn::Path { + leading_colon: None, + segments: Punctuated::new(), + }; + path.segments.push(Ident::new("_serde", Span::call_site()).into()); + path.segments.push(Ident::new("private", Span::call_site()).into()); + path.segments.push(Ident::new("de", Span::call_site()).into()); + path.segments.push(Ident::new("borrow_cow_str", Span::call_site()).into()); + let expr = syn::ExprPath { + attrs: Vec::new(), + qself: None, + path: path, + }; + deserialize_with.set_if_none(expr); + } else if is_cow(&field.ty, is_slice_u8) { + let mut path = syn::Path { + leading_colon: None, + segments: Punctuated::new(), + }; + path.segments.push(Ident::new("_serde", Span::call_site()).into()); + path.segments.push(Ident::new("private", Span::call_site()).into()); + path.segments.push(Ident::new("de", Span::call_site()).into()); + path.segments.push(Ident::new("borrow_cow_bytes", Span::call_site()).into()); + let expr = syn::ExprPath { + attrs: Vec::new(), + qself: None, + path: path, + }; + deserialize_with.set_if_none(expr); + } + } else if is_rptr(&field.ty, is_str) || is_rptr(&field.ty, is_slice_u8) { + // Types &str and &[u8] are always implicitly borrowed. No need for + // a #[serde(borrow)]. + collect_lifetimes(&field.ty, &mut borrowed_lifetimes); + } + + let ser_name = ser_name.get(); + let ser_renamed = ser_name.is_some(); + let de_name = de_name.get(); + let de_renamed = de_name.is_some(); + Field { + name: Name { + serialize: ser_name.unwrap_or_else(|| ident.clone()), + deserialize: de_name.unwrap_or(ident), + }, + ser_renamed: ser_renamed, + de_renamed: de_renamed, + skip_serializing: skip_serializing.get(), + skip_deserializing: skip_deserializing.get(), + skip_serializing_if: skip_serializing_if.get(), + default: default.get().unwrap_or(Default::None), + serialize_with: serialize_with.get(), + deserialize_with: deserialize_with.get(), + ser_bound: ser_bound.get(), + de_bound: de_bound.get(), + borrowed_lifetimes: borrowed_lifetimes, + getter: getter.get(), + flatten: flatten.get(), + } + } + + pub fn name(&self) -> &Name { + &self.name + } + + pub fn rename_by_rule(&mut self, rule: &RenameRule) { + if !self.ser_renamed { + self.name.serialize = rule.apply_to_field(&self.name.serialize); + } + if !self.de_renamed { + self.name.deserialize = rule.apply_to_field(&self.name.deserialize); + } + } + + pub fn skip_serializing(&self) -> bool { + self.skip_serializing + } + + pub fn skip_deserializing(&self) -> bool { + self.skip_deserializing + } + + pub fn skip_serializing_if(&self) -> Option<&syn::ExprPath> { + self.skip_serializing_if.as_ref() + } + + pub fn default(&self) -> &Default { + &self.default + } + + pub fn serialize_with(&self) -> Option<&syn::ExprPath> { + self.serialize_with.as_ref() + } + + pub fn deserialize_with(&self) -> Option<&syn::ExprPath> { + self.deserialize_with.as_ref() + } + + pub fn ser_bound(&self) -> Option<&[syn::WherePredicate]> { + self.ser_bound.as_ref().map(|vec| &vec[..]) + } + + pub fn de_bound(&self) -> Option<&[syn::WherePredicate]> { + self.de_bound.as_ref().map(|vec| &vec[..]) + } + + pub fn borrowed_lifetimes(&self) -> &BTreeSet<syn::Lifetime> { + &self.borrowed_lifetimes + } + + pub fn getter(&self) -> Option<&syn::ExprPath> { + self.getter.as_ref() + } + + pub fn flatten(&self) -> bool { + self.flatten + } +} + +type SerAndDe<T> = (Option<T>, Option<T>); + +fn get_ser_and_de<'a, T, F>( + cx: &Ctxt, + attr_name: &'static str, + metas: &'a Punctuated<syn::NestedMeta, Token![,]>, + f: F, +) -> Result<SerAndDe<T>, ()> +where + T: 'a, + F: Fn(&Ctxt, &str, &str, &'a syn::Lit) -> Result<T, ()>, +{ + let mut ser_meta = Attr::none(cx, attr_name); + let mut de_meta = Attr::none(cx, attr_name); + + for meta in metas { + match *meta { + Meta(NameValue(ref meta)) if meta.ident == "serialize" => { + if let Ok(v) = f(cx, attr_name, meta.ident.as_ref(), &meta.lit) { + ser_meta.set(v); + } + } + + Meta(NameValue(ref meta)) if meta.ident == "deserialize" => { + if let Ok(v) = f(cx, attr_name, meta.ident.as_ref(), &meta.lit) { + de_meta.set(v); + } + } + + _ => { + cx.error(format!( + "malformed {0} attribute, expected `{0}(serialize = ..., \ + deserialize = ...)`", + attr_name + )); + return Err(()); + } + } + } + + Ok((ser_meta.get(), de_meta.get())) +} + +fn get_renames<'a>(cx: &Ctxt, items: &'a Punctuated<syn::NestedMeta, Token![,]>) -> Result<SerAndDe<&'a syn::LitStr>, ()> { + get_ser_and_de(cx, "rename", items, get_lit_str) +} + +fn get_where_predicates( + cx: &Ctxt, + items: &Punctuated<syn::NestedMeta, Token![,]>, +) -> Result<SerAndDe<Vec<syn::WherePredicate>>, ()> { + get_ser_and_de(cx, "bound", items, parse_lit_into_where) +} + +pub fn get_serde_meta_items(attr: &syn::Attribute) -> Option<Vec<syn::NestedMeta>> { + if attr.path.segments.len() == 1 && attr.path.segments[0].ident == "serde" { + match attr.interpret_meta() { + Some(List(ref meta)) => Some(meta.nested.iter().cloned().collect()), + _ => { + // TODO: produce an error + None + } + } + } else { + None + } +} + +fn get_lit_str<'a>( + cx: &Ctxt, + attr_name: &str, + meta_item_name: &str, + lit: &'a syn::Lit, +) -> Result<&'a syn::LitStr, ()> { + if let syn::Lit::Str(ref lit) = *lit { + Ok(lit) + } else { + cx.error(format!( + "expected serde {} attribute to be a string: `{} = \"...\"`", + attr_name, meta_item_name + )); + Err(()) + } +} + +fn parse_lit_into_path(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn::Path, ()> { + let string = try!(get_lit_str(cx, attr_name, attr_name, lit)); + parse_lit_str(string).map_err(|_| cx.error(format!("failed to parse path: {:?}", string.value()))) +} + +fn parse_lit_into_expr_path(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn::ExprPath, ()> { + let string = try!(get_lit_str(cx, attr_name, attr_name, lit)); + parse_lit_str(string).map_err(|_| cx.error(format!("failed to parse path: {:?}", string.value()))) +} + +fn parse_lit_into_where( + cx: &Ctxt, + attr_name: &str, + meta_item_name: &str, + lit: &syn::Lit, +) -> Result<Vec<syn::WherePredicate>, ()> { + let string = try!(get_lit_str(cx, attr_name, meta_item_name, lit)); + if string.value().is_empty() { + return Ok(Vec::new()); + } + + let where_string = syn::LitStr::new(&format!("where {}", string.value()), string.span()); + + parse_lit_str::<syn::WhereClause>(&where_string) + .map(|wh| wh.predicates.into_iter().collect()) + .map_err(|err| cx.error(err)) +} + +fn parse_lit_into_ty(cx: &Ctxt, attr_name: &str, lit: &syn::Lit) -> Result<syn::Type, ()> { + let string = try!(get_lit_str(cx, attr_name, attr_name, lit)); + + parse_lit_str(string).map_err(|_| { + cx.error(format!( + "failed to parse type: {} = {:?}", + attr_name, string.value() + )) + }) +} + +// Parses a string literal like "'a + 'b + 'c" containing a nonempty list of +// lifetimes separated by `+`. +fn parse_lit_into_lifetimes( + cx: &Ctxt, + attr_name: &str, + lit: &syn::Lit, +) -> Result<BTreeSet<syn::Lifetime>, ()> { + let string = try!(get_lit_str(cx, attr_name, attr_name, lit)); + if string.value().is_empty() { + cx.error("at least one lifetime must be borrowed"); + return Err(()); + } + + struct BorrowedLifetimes(Punctuated<syn::Lifetime, Token![+]>); + + impl Synom for BorrowedLifetimes { + named!(parse -> Self, map!( + call!(Punctuated::parse_separated_nonempty), + BorrowedLifetimes + )); + } + + if let Ok(BorrowedLifetimes(lifetimes)) = parse_lit_str(string) { + let mut set = BTreeSet::new(); + for lifetime in lifetimes { + if !set.insert(lifetime) { + cx.error(format!("duplicate borrowed lifetime `{}`", lifetime)); + } + } + return Ok(set); + } + + cx.error(format!("failed to parse borrowed lifetimes: {:?}", string.value())); + Err(()) +} + +// Whether the type looks like it might be `std::borrow::Cow<T>` where elem="T". +// This can have false negatives and false positives. +// +// False negative: +// +// use std::borrow::Cow as Pig; +// +// #[derive(Deserialize)] +// struct S<'a> { +// #[serde(borrow)] +// pig: Pig<'a, str>, +// } +// +// False positive: +// +// type str = [i16]; +// +// #[derive(Deserialize)] +// struct S<'a> { +// #[serde(borrow)] +// cow: Cow<'a, str>, +// } +fn is_cow(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool { + let path = match *ty { + syn::Type::Path(ref ty) => &ty.path, + _ => { + return false; + } + }; + let seg = match path.segments.last() { + Some(seg) => seg.into_value(), + None => { + return false; + } + }; + let args = match seg.arguments { + syn::PathArguments::AngleBracketed(ref bracketed) => &bracketed.args, + _ => { + return false; + } + }; + seg.ident == "Cow" + && args.len() == 2 + && match (&args[0], &args[1]) { + (&syn::GenericArgument::Lifetime(_), &syn::GenericArgument::Type(ref arg)) => { + elem(arg) + } + _ => false, + } +} + +// Whether the type looks like it might be `&T` where elem="T". This can have +// false negatives and false positives. +// +// False negative: +// +// type Yarn = str; +// +// #[derive(Deserialize)] +// struct S<'a> { +// r: &'a Yarn, +// } +// +// False positive: +// +// type str = [i16]; +// +// #[derive(Deserialize)] +// struct S<'a> { +// r: &'a str, +// } +fn is_rptr(ty: &syn::Type, elem: fn(&syn::Type) -> bool) -> bool { + match *ty { + syn::Type::Reference(ref ty) => { + ty.mutability.is_none() && elem(&ty.elem) + } + _ => false, + } +} + +fn is_str(ty: &syn::Type) -> bool { + is_primitive_type(ty, "str") +} + +fn is_slice_u8(ty: &syn::Type) -> bool { + match *ty { + syn::Type::Slice(ref ty) => is_primitive_type(&ty.elem, "u8"), + _ => false, + } +} + +fn is_primitive_type(ty: &syn::Type, primitive: &str) -> bool { + match *ty { + syn::Type::Path(ref ty) => { + ty.qself.is_none() && is_primitive_path(&ty.path, primitive) + } + _ => false, + } +} + +fn is_primitive_path(path: &syn::Path, primitive: &str) -> bool { + path.leading_colon.is_none() + && path.segments.len() == 1 + && path.segments[0].ident == primitive + && path.segments[0].arguments.is_empty() +} + +// All lifetimes that this type could borrow from a Deserializer. +// +// For example a type `S<'a, 'b>` could borrow `'a` and `'b`. On the other hand +// a type `for<'a> fn(&'a str)` could not borrow `'a` from the Deserializer. +// +// This is used when there is an explicit or implicit `#[serde(borrow)]` +// attribute on the field so there must be at least one borrowable lifetime. +fn borrowable_lifetimes( + cx: &Ctxt, + name: &str, + ty: &syn::Type, +) -> Result<BTreeSet<syn::Lifetime>, ()> { + let mut lifetimes = BTreeSet::new(); + collect_lifetimes(ty, &mut lifetimes); + if lifetimes.is_empty() { + cx.error(format!("field `{}` has no lifetimes to borrow", name)); + Err(()) + } else { + Ok(lifetimes) + } +} + +fn collect_lifetimes(ty: &syn::Type, out: &mut BTreeSet<syn::Lifetime>) { + match *ty { + syn::Type::Slice(ref ty) => { + collect_lifetimes(&ty.elem, out); + } + syn::Type::Array(ref ty) => { + collect_lifetimes(&ty.elem, out); + } + syn::Type::Ptr(ref ty) => { + collect_lifetimes(&ty.elem, out); + } + syn::Type::Reference(ref ty) => { + out.extend(ty.lifetime.iter().cloned()); + collect_lifetimes(&ty.elem, out); + } + syn::Type::Tuple(ref ty) => for elem in &ty.elems { + collect_lifetimes(elem, out); + }, + syn::Type::Path(ref ty) => { + if let Some(ref qself) = ty.qself { + collect_lifetimes(&qself.ty, out); + } + for seg in &ty.path.segments { + if let syn::PathArguments::AngleBracketed(ref bracketed) = seg.arguments { + for arg in &bracketed.args { + match *arg { + syn::GenericArgument::Lifetime(ref lifetime) => { + out.insert(lifetime.clone()); + } + syn::GenericArgument::Type(ref ty) => { + collect_lifetimes(ty, out); + } + syn::GenericArgument::Binding(ref binding) => { + collect_lifetimes(&binding.ty, out); + } + syn::GenericArgument::Const(_) => {} + } + } + } + } + } + syn::Type::Paren(ref ty) => { + collect_lifetimes(&ty.elem, out); + } + syn::Type::Group(ref ty) => { + collect_lifetimes(&ty.elem, out); + } + syn::Type::BareFn(_) + | syn::Type::Never(_) + | syn::Type::TraitObject(_) + | syn::Type::ImplTrait(_) + | syn::Type::Infer(_) + | syn::Type::Macro(_) + | syn::Type::Verbatim(_) => {} + } +} + +fn parse_lit_str<T>(s: &syn::LitStr) -> Result<T, ParseError> +where + T: Synom, +{ + let tokens = try!(spanned_tokens(s)); + syn::parse2(tokens) +} + +fn spanned_tokens(s: &syn::LitStr) -> Result<TokenStream, ParseError> { + let stream = try!(syn::parse_str(&s.value())); + Ok(respan_token_stream(stream, s.span())) +} + +fn respan_token_stream(stream: TokenStream, span: Span) -> TokenStream { + stream.into_iter().map(|token| respan_token_tree(token, span)).collect() +} + +fn respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree { + if let TokenTree::Group(ref mut g) = token { + *g = Group::new(g.delimiter(), respan_token_stream(g.stream().clone(), span)); + } + token.set_span(span); + token +} diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.23.0/src/case.rs cargo-0.26.0/vendor/serde_derive_internals-0.23.0/src/case.rs --- cargo-0.25.0/vendor/serde_derive_internals-0.23.0/src/case.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.23.0/src/case.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,186 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// See https://users.rust-lang.org/t/psa-dealing-with-warning-unused-import-std-ascii-asciiext-in-today-s-nightly/13726 +#[allow(deprecated, unused_imports)] +use std::ascii::AsciiExt; + +use std::str::FromStr; + +use self::RenameRule::*; + +#[derive(PartialEq)] +pub enum RenameRule { + /// Don't apply a default rename rule. + None, + /// Rename direct children to "lowercase" style. + LowerCase, + /// Rename direct children to "UPPERCASE" style. + UPPERCASE, + /// Rename direct children to "PascalCase" style, as typically used for enum variants. + PascalCase, + /// Rename direct children to "camelCase" style. + CamelCase, + /// Rename direct children to "snake_case" style, as commonly used for fields. + SnakeCase, + /// Rename direct children to "SCREAMING_SNAKE_CASE" style, as commonly used for constants. + ScreamingSnakeCase, + /// Rename direct children to "kebab-case" style. + KebabCase, + /// Rename direct children to "SCREAMING-KEBAB-CASE" style. + ScreamingKebabCase, +} + +impl RenameRule { + pub fn apply_to_variant(&self, variant: &str) -> String { + match *self { + None | PascalCase => variant.to_owned(), + LowerCase => variant.to_ascii_lowercase(), + UPPERCASE => variant.to_ascii_uppercase(), + CamelCase => variant[..1].to_ascii_lowercase() + &variant[1..], + SnakeCase => { + let mut snake = String::new(); + for (i, ch) in variant.char_indices() { + if i > 0 && ch.is_uppercase() { + snake.push('_'); + } + snake.push(ch.to_ascii_lowercase()); + } + snake + } + ScreamingSnakeCase => SnakeCase.apply_to_variant(variant).to_ascii_uppercase(), + KebabCase => SnakeCase.apply_to_variant(variant).replace('_', "-"), + ScreamingKebabCase => ScreamingSnakeCase + .apply_to_variant(variant) + .replace('_', "-"), + } + } + + pub fn apply_to_field(&self, field: &str) -> String { + match *self { + None | LowerCase | SnakeCase => field.to_owned(), + UPPERCASE => field.to_ascii_uppercase(), + PascalCase => { + let mut pascal = String::new(); + let mut capitalize = true; + for ch in field.chars() { + if ch == '_' { + capitalize = true; + } else if capitalize { + pascal.push(ch.to_ascii_uppercase()); + capitalize = false; + } else { + pascal.push(ch); + } + } + pascal + } + CamelCase => { + let pascal = PascalCase.apply_to_field(field); + pascal[..1].to_ascii_lowercase() + &pascal[1..] + } + ScreamingSnakeCase => field.to_ascii_uppercase(), + KebabCase => field.replace('_', "-"), + ScreamingKebabCase => ScreamingSnakeCase.apply_to_field(field).replace('_', "-"), + } + } +} + +impl FromStr for RenameRule { + type Err = (); + + fn from_str(rename_all_str: &str) -> Result<Self, Self::Err> { + match rename_all_str { + "lowercase" => Ok(LowerCase), + "UPPERCASE" => Ok(UPPERCASE), + "PascalCase" => Ok(PascalCase), + "camelCase" => Ok(CamelCase), + "snake_case" => Ok(SnakeCase), + "SCREAMING_SNAKE_CASE" => Ok(ScreamingSnakeCase), + "kebab-case" => Ok(KebabCase), + "SCREAMING-KEBAB-CASE" => Ok(ScreamingKebabCase), + _ => Err(()), + } + } +} + +#[test] +fn rename_variants() { + for &(original, lower, upper, camel, snake, screaming, kebab, screaming_kebab) in &[ + ( + "Outcome", + "outcome", + "OUTCOME", + "outcome", + "outcome", + "OUTCOME", + "outcome", + "OUTCOME", + ), + ( + "VeryTasty", + "verytasty", + "VERYTASTY", + "veryTasty", + "very_tasty", + "VERY_TASTY", + "very-tasty", + "VERY-TASTY", + ), + ("A", "a", "A", "a", "a", "A", "a", "A"), + ("Z42", "z42", "Z42", "z42", "z42", "Z42", "z42", "Z42"), + ] { + assert_eq!(None.apply_to_variant(original), original); + assert_eq!(LowerCase.apply_to_variant(original), lower); + assert_eq!(UPPERCASE.apply_to_variant(original), upper); + assert_eq!(PascalCase.apply_to_variant(original), original); + assert_eq!(CamelCase.apply_to_variant(original), camel); + assert_eq!(SnakeCase.apply_to_variant(original), snake); + assert_eq!(ScreamingSnakeCase.apply_to_variant(original), screaming); + assert_eq!(KebabCase.apply_to_variant(original), kebab); + assert_eq!( + ScreamingKebabCase.apply_to_variant(original), + screaming_kebab + ); + } +} + +#[test] +fn rename_fields() { + for &(original, upper, pascal, camel, screaming, kebab, screaming_kebab) in &[ + ( + "outcome", + "OUTCOME", + "Outcome", + "outcome", + "OUTCOME", + "outcome", + "OUTCOME", + ), + ( + "very_tasty", + "VERY_TASTY", + "VeryTasty", + "veryTasty", + "VERY_TASTY", + "very-tasty", + "VERY-TASTY", + ), + ("a", "A", "A", "a", "A", "a", "A"), + ("z42", "Z42", "Z42", "z42", "Z42", "z42", "Z42"), + ] { + assert_eq!(None.apply_to_field(original), original); + assert_eq!(UPPERCASE.apply_to_field(original), upper); + assert_eq!(PascalCase.apply_to_field(original), pascal); + assert_eq!(CamelCase.apply_to_field(original), camel); + assert_eq!(SnakeCase.apply_to_field(original), original); + assert_eq!(ScreamingSnakeCase.apply_to_field(original), screaming); + assert_eq!(KebabCase.apply_to_field(original), kebab); + assert_eq!(ScreamingKebabCase.apply_to_field(original), screaming_kebab); + } +} diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.23.0/src/check.rs cargo-0.26.0/vendor/serde_derive_internals-0.23.0/src/check.rs --- cargo-0.25.0/vendor/serde_derive_internals-0.23.0/src/check.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.23.0/src/check.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,281 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use ast::{Data, Container, Style}; +use attr::{Identifier, EnumTag}; +use Ctxt; + +/// Cross-cutting checks that require looking at more than a single attrs +/// object. Simpler checks should happen when parsing and building the attrs. +pub fn check(cx: &Ctxt, cont: &Container) { + check_getter(cx, cont); + check_flatten(cx, cont); + check_identifier(cx, cont); + check_variant_skip_attrs(cx, cont); + check_internal_tag_field_name_conflict(cx, cont); + check_adjacent_tag_conflict(cx, cont); +} + +/// Getters are only allowed inside structs (not enums) with the `remote` +/// attribute. +fn check_getter(cx: &Ctxt, cont: &Container) { + match cont.data { + Data::Enum(_) => { + if cont.data.has_getter() { + cx.error("#[serde(getter = \"...\")] is not allowed in an enum"); + } + } + Data::Struct(_, _) => { + if cont.data.has_getter() && cont.attrs.remote().is_none() { + cx.error( + "#[serde(getter = \"...\")] can only be used in structs \ + that have #[serde(remote = \"...\")]", + ); + } + } + } +} + +/// Flattening has some restrictions we can test. +fn check_flatten(cx: &Ctxt, cont: &Container) { + match cont.data { + Data::Enum(_) => { + if cont.attrs.has_flatten() { + cx.error("#[serde(flatten)] cannot be used within enums"); + } + } + Data::Struct(style, _) => { + for field in cont.data.all_fields() { + if !field.attrs.flatten() { + continue; + } + match style { + Style::Tuple => { + cx.error("#[serde(flatten)] cannot be used on tuple structs"); + } + Style::Newtype => { + cx.error("#[serde(flatten)] cannot be used on newtype structs"); + } + _ => {} + } + if field.attrs.skip_serializing() { + cx.error( + "#[serde(flatten] can not be combined with \ + #[serde(skip_serializing)]" + ); + } else if field.attrs.skip_serializing_if().is_some() { + cx.error( + "#[serde(flatten] can not be combined with \ + #[serde(skip_serializing_if = \"...\")]" + ); + } else if field.attrs.skip_deserializing() { + cx.error( + "#[serde(flatten] can not be combined with \ + #[serde(skip_deserializing)]" + ); + } + } + } + } +} + +/// The `other` attribute must be used at most once and it must be the last +/// variant of an enum that has the `field_identifier` attribute. +/// +/// Inside a `variant_identifier` all variants must be unit variants. Inside a +/// `field_identifier` all but possibly one variant must be unit variants. The +/// last variant may be a newtype variant which is an implicit "other" case. +fn check_identifier(cx: &Ctxt, cont: &Container) { + let variants = match cont.data { + Data::Enum(ref variants) => variants, + Data::Struct(_, _) => { + return; + } + }; + + for (i, variant) in variants.iter().enumerate() { + match ( + variant.style, + cont.attrs.identifier(), + variant.attrs.other(), + ) { + // The `other` attribute may only be used in a field_identifier. + (_, Identifier::Variant, true) | (_, Identifier::No, true) => { + cx.error("#[serde(other)] may only be used inside a field_identifier"); + } + + // Variant with `other` attribute must be the last one. + (Style::Unit, Identifier::Field, true) => { + if i < variants.len() - 1 { + cx.error("#[serde(other)] must be the last variant"); + } + } + + // Variant with `other` attribute must be a unit variant. + (_, Identifier::Field, true) => { + cx.error("#[serde(other)] must be on a unit variant"); + } + + // Any sort of variant is allowed if this is not an identifier. + (_, Identifier::No, false) => {} + + // Unit variant without `other` attribute is always fine. + (Style::Unit, _, false) => {} + + // The last field is allowed to be a newtype catch-all. + (Style::Newtype, Identifier::Field, false) => { + if i < variants.len() - 1 { + cx.error(format!("`{}` must be the last variant", variant.ident)); + } + } + + (_, Identifier::Field, false) => { + cx.error("field_identifier may only contain unit variants"); + } + + (_, Identifier::Variant, false) => { + cx.error("variant_identifier may only contain unit variants"); + } + } + } +} + +/// Skip-(de)serializing attributes are not allowed on variants marked +/// (de)serialize_with. +fn check_variant_skip_attrs(cx: &Ctxt, cont: &Container) { + let variants = match cont.data { + Data::Enum(ref variants) => variants, + Data::Struct(_, _) => { + return; + } + }; + + for variant in variants.iter() { + if variant.attrs.serialize_with().is_some() { + if variant.attrs.skip_serializing() { + cx.error(format!( + "variant `{}` cannot have both #[serde(serialize_with)] and \ + #[serde(skip_serializing)]", + variant.ident + )); + } + + for (i, field) in variant.fields.iter().enumerate() { + let ident = field + .ident + .as_ref() + .map_or_else(|| format!("{}", i), |ident| format!("`{}`", ident)); + + if field.attrs.skip_serializing() { + cx.error(format!( + "variant `{}` cannot have both #[serde(serialize_with)] and \ + a field {} marked with #[serde(skip_serializing)]", + variant.ident, ident + )); + } + + if field.attrs.skip_serializing_if().is_some() { + cx.error(format!( + "variant `{}` cannot have both #[serde(serialize_with)] and \ + a field {} marked with #[serde(skip_serializing_if)]", + variant.ident, ident + )); + } + } + } + + if variant.attrs.deserialize_with().is_some() { + if variant.attrs.skip_deserializing() { + cx.error(format!( + "variant `{}` cannot have both #[serde(deserialize_with)] and \ + #[serde(skip_deserializing)]", + variant.ident + )); + } + + for (i, field) in variant.fields.iter().enumerate() { + if field.attrs.skip_deserializing() { + let ident = field + .ident + .as_ref() + .map_or_else(|| format!("{}", i), |ident| format!("`{}`", ident)); + + cx.error(format!( + "variant `{}` cannot have both #[serde(deserialize_with)] \ + and a field {} marked with #[serde(skip_deserializing)]", + variant.ident, ident + )); + } + } + } + } +} + +/// The tag of an internally-tagged struct variant must not be +/// the same as either one of its fields, as this would result in +/// duplicate keys in the serialized output and/or ambiguity in +/// the to-be-deserialized input. +fn check_internal_tag_field_name_conflict( + cx: &Ctxt, + cont: &Container, +) { + let variants = match cont.data { + Data::Enum(ref variants) => variants, + Data::Struct(_, _) => return, + }; + + let tag = match *cont.attrs.tag() { + EnumTag::Internal { ref tag } => tag.as_str(), + EnumTag::External | EnumTag::Adjacent { .. } | EnumTag::None => return, + }; + + let diagnose_conflict = || { + let message = format!( + "variant field name `{}` conflicts with internal tag", + tag + ); + cx.error(message); + }; + + for variant in variants { + match variant.style { + Style::Struct => { + for field in &variant.fields { + let check_ser = !field.attrs.skip_serializing(); + let check_de = !field.attrs.skip_deserializing(); + let name = field.attrs.name(); + let ser_name = name.serialize_name(); + let de_name = name.deserialize_name(); + + if check_ser && ser_name == tag || check_de && de_name == tag { + diagnose_conflict(); + return; + } + } + }, + Style::Unit | Style::Newtype | Style::Tuple => {}, + } + } +} + +/// In the case of adjacently-tagged enums, the type and the +/// contents tag must differ, for the same reason. +fn check_adjacent_tag_conflict(cx: &Ctxt, cont: &Container) { + let (type_tag, content_tag) = match *cont.attrs.tag() { + EnumTag::Adjacent { ref tag, ref content } => (tag, content), + EnumTag::Internal { .. } | EnumTag::External | EnumTag::None => return, + }; + + if type_tag == content_tag { + let message = format!( + "enum tags `{}` for type and content conflict with each other", + type_tag + ); + cx.error(message); + } +} diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.23.0/src/ctxt.rs cargo-0.26.0/vendor/serde_derive_internals-0.23.0/src/ctxt.rs --- cargo-0.25.0/vendor/serde_derive_internals-0.23.0/src/ctxt.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.23.0/src/ctxt.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,56 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::fmt::Display; +use std::cell::RefCell; +use std::thread; + +#[derive(Default)] +pub struct Ctxt { + errors: RefCell<Option<Vec<String>>>, +} + +impl Ctxt { + pub fn new() -> Self { + Ctxt { + errors: RefCell::new(Some(Vec::new())), + } + } + + pub fn error<T: Display>(&self, msg: T) { + self.errors + .borrow_mut() + .as_mut() + .unwrap() + .push(msg.to_string()); + } + + pub fn check(self) -> Result<(), String> { + let mut errors = self.errors.borrow_mut().take().unwrap(); + match errors.len() { + 0 => Ok(()), + 1 => Err(errors.pop().unwrap()), + n => { + let mut msg = format!("{} errors:", n); + for err in errors { + msg.push_str("\n\t# "); + msg.push_str(&err); + } + Err(msg) + } + } + } +} + +impl Drop for Ctxt { + fn drop(&mut self) { + if !thread::panicking() && self.errors.borrow().is_some() { + panic!("forgot to check for errors"); + } + } +} diff -Nru cargo-0.25.0/vendor/serde_derive_internals-0.23.0/src/lib.rs cargo-0.26.0/vendor/serde_derive_internals-0.23.0/src/lib.rs --- cargo-0.25.0/vendor/serde_derive_internals-0.23.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_derive_internals-0.23.0/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![doc(html_root_url = "https://docs.rs/serde_derive_internals/0.23.0")] +#![cfg_attr(feature = "cargo-clippy", allow(cyclomatic_complexity, doc_markdown, match_same_arms, + redundant_field_names))] + +#[macro_use] +extern crate syn; + +extern crate proc_macro2; + +pub mod ast; +pub mod attr; + +mod ctxt; +pub use ctxt::Ctxt; + +mod case; +mod check; diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/.cargo-checksum.json cargo-0.26.0/vendor/serde_json-1.0.13/.cargo-checksum.json --- cargo-0.25.0/vendor/serde_json-1.0.13/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"5c508584d9913df116b91505eec55610a2f5b16e9ed793c46e4d0152872b3e74"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/Cargo.toml cargo-0.26.0/vendor/serde_json-1.0.13/Cargo.toml --- cargo-0.25.0/vendor/serde_json-1.0.13/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,58 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "serde_json" +version = "1.0.13" +authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"] +include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] +description = "A JSON serialization file format" +documentation = "http://docs.serde.rs/serde_json/" +readme = "README.md" +keywords = ["json", "serde", "serialization"] +categories = ["encoding"] +license = "MIT/Apache-2.0" +repository = "https://github.com/serde-rs/json" +[dependencies.dtoa] +version = "0.4" + +[dependencies.itoa] +version = "0.4" + +[dependencies.linked-hash-map] +version = "0.5" +optional = true + +[dependencies.num-traits] +version = "0.2" +default-features = false + +[dependencies.serde] +version = "1.0" +[dev-dependencies.compiletest_rs] +version = "0.3" + +[dev-dependencies.serde_bytes] +version = "0.10" + +[dev-dependencies.serde_derive] +version = "1.0" + +[features] +arbitrary_precision = [] +default = [] +preserve_order = ["linked-hash-map"] +[badges.appveyor] +repository = "serde-rs/json" + +[badges.travis-ci] +repository = "serde-rs/json" diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/LICENSE-APACHE cargo-0.26.0/vendor/serde_json-1.0.13/LICENSE-APACHE --- cargo-0.25.0/vendor/serde_json-1.0.13/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/LICENSE-MIT cargo-0.26.0/vendor/serde_json-1.0.13/LICENSE-MIT --- cargo-0.25.0/vendor/serde_json-1.0.13/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/README.md cargo-0.26.0/vendor/serde_json-1.0.13/README.md --- cargo-0.25.0/vendor/serde_json-1.0.13/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,356 @@ +# Serde JSON   [![Build Status]][travis] [![Latest Version]][crates.io] + +[Build Status]: https://api.travis-ci.org/serde-rs/json.svg?branch=master +[travis]: https://travis-ci.org/serde-rs/json +[Latest Version]: https://img.shields.io/crates/v/serde_json.svg +[crates.io]: https://crates.io/crates/serde\_json + +**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** + +--- + +```toml +[dependencies] +serde_json = "1.0" +``` + +You may be looking for: + +- [JSON API documentation](https://docs.serde.rs/serde_json/) +- [Serde API documentation](https://docs.serde.rs/serde/) +- [Detailed documentation about Serde](https://serde.rs/) +- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html) +- [Release notes](https://github.com/serde-rs/json/releases) + +JSON is a ubiquitous open-standard format that uses human-readable text to +transmit data objects consisting of key-value pairs. + +```json,ignore +{ + "name": "John Doe", + "age": 43, + "address": { + "street": "10 Downing Street", + "city": "London" + }, + "phones": [ + "+44 1234567", + "+44 2345678" + ] +} +``` + +There are three common ways that you might find yourself needing to work +with JSON data in Rust. + + - **As text data.** An unprocessed string of JSON data that you receive on + an HTTP endpoint, read from a file, or prepare to send to a remote + server. + - **As an untyped or loosely typed representation.** Maybe you want to + check that some JSON data is valid before passing it on, but without + knowing the structure of what it contains. Or you want to do very basic + manipulations like insert a key in a particular spot. + - **As a strongly typed Rust data structure.** When you expect all or most + of your data to conform to a particular structure and want to get real + work done without JSON's loosey-goosey nature tripping you up. + +Serde JSON provides efficient, flexible, safe ways of converting data +between each of these representations. + +## Operating on untyped JSON values + +Any valid JSON data can be manipulated in the following recursive enum +representation. This data structure is [`serde_json::Value`][value]. + +```rust,ignore +enum Value { + Null, + Bool(bool), + Number(Number), + String(String), + Array(Vec<Value>), + Object(Map<String, Value>), +} +``` + +A string of JSON data can be parsed into a `serde_json::Value` by the +[`serde_json::from_str`][from_str] function. There is also +[`from_slice`][from_slice] for parsing from a byte slice &[u8] and +[`from_reader`][from_reader] for parsing from any `io::Read` like a File or +a TCP stream. + +<a href="http://play.integer32.com/?gist=a266662bc71712e080efbf25ce30f306" target="_blank"> +<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png"> +</a> + +```rust +extern crate serde_json; + +use serde_json::{Value, Error}; + +fn untyped_example() -> Result<(), Error> { + // Some JSON input data as a &str. Maybe this comes from the user. + let data = r#"{ + "name": "John Doe", + "age": 43, + "phones": [ + "+44 1234567", + "+44 2345678" + ] + }"#; + + // Parse the string of data into serde_json::Value. + let v: Value = serde_json::from_str(data)?; + + // Access parts of the data by indexing with square brackets. + println!("Please call {} at the number {}", v["name"], v["phones"][0]); + + Ok(()) +} +``` + +The result of square bracket indexing like `v["name"]` is a borrow of the data +at that index, so the type is `&Value`. A JSON map can be indexed with string +keys, while a JSON array can be indexed with integer keys. If the type of the +data is not right for the type with which it is being indexed, or if a map does +not contain the key being indexed, or if the index into a vector is out of +bounds, the returned element is `Value::Null`. + +When a `Value` is printed, it is printed as a JSON string. So in the code above, +the output looks like `Please call "John Doe" at the number "+44 1234567"`. The +quotation marks appear because `v["name"]` is a `&Value` containing a JSON +string and its JSON representation is `"John Doe"`. Printing as a plain string +without quotation marks involves converting from a JSON string to a Rust string +with [`as_str()`] or avoiding the use of `Value` as described in the following +section. + +[`as_str()`]: https://docs.serde.rs/serde_json/enum.Value.html#method.as_str + +The `Value` representation is sufficient for very basic tasks but can be tedious +to work with for anything more significant. Error handling is verbose to +implement correctly, for example imagine trying to detect the presence of +unrecognized fields in the input data. The compiler is powerless to help you +when you make a mistake, for example imagine typoing `v["name"]` as `v["nmae"]` +in one of the dozens of places it is used in your code. + +## Parsing JSON as strongly typed data structures + +Serde provides a powerful way of mapping JSON data into Rust data structures +largely automatically. + +<a href="http://play.integer32.com/?gist=cff572b80d3f078c942a2151e6020adc" target="_blank"> +<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png"> +</a> + +```rust +extern crate serde; +extern crate serde_json; + +#[macro_use] +extern crate serde_derive; + +use serde_json::Error; + +#[derive(Serialize, Deserialize)] +struct Person { + name: String, + age: u8, + phones: Vec<String>, +} + +fn typed_example() -> Result<(), Error> { + // Some JSON input data as a &str. Maybe this comes from the user. + let data = r#"{ + "name": "John Doe", + "age": 43, + "phones": [ + "+44 1234567", + "+44 2345678" + ] + }"#; + + // Parse the string of data into a Person object. This is exactly the + // same function as the one that produced serde_json::Value above, but + // now we are asking it for a Person as output. + let p: Person = serde_json::from_str(data)?; + + // Do things just like with any other Rust data structure. + println!("Please call {} at the number {}", p.name, p.phones[0]); + + Ok(()) +} +``` + +This is the same `serde_json::from_str` function as before, but this time we +assign the return value to a variable of type `Person` so Serde will +automatically interpret the input data as a `Person` and produce informative +error messages if the layout does not conform to what a `Person` is expected +to look like. + +Any type that implements Serde's `Deserialize` trait can be deserialized +this way. This includes built-in Rust standard library types like `Vec<T>` +and `HashMap<K, V>`, as well as any structs or enums annotated with +`#[derive(Deserialize)]`. + +Once we have `p` of type `Person`, our IDE and the Rust compiler can help us +use it correctly like they do for any other Rust code. The IDE can +autocomplete field names to prevent typos, which was impossible in the +`serde_json::Value` representation. And the Rust compiler can check that +when we write `p.phones[0]`, then `p.phones` is guaranteed to be a +`Vec<String>` so indexing into it makes sense and produces a `String`. + +## Constructing JSON values + +Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` +objects with very natural JSON syntax. In order to use this macro, +`serde_json` needs to be imported with the `#[macro_use]` attribute. + +<a href="http://play.integer32.com/?gist=c216d6beabd9429a6ac13b8f88938dfe" target="_blank"> +<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png"> +</a> + +```rust +#[macro_use] +extern crate serde_json; + +fn main() { + // The type of `john` is `serde_json::Value` + let john = json!({ + "name": "John Doe", + "age": 43, + "phones": [ + "+44 1234567", + "+44 2345678" + ] + }); + + println!("first phone number: {}", john["phones"][0]); + + // Convert to a string of JSON and print it out + println!("{}", john.to_string()); +} +``` + +The `Value::to_string()` function converts a `serde_json::Value` into a +`String` of JSON text. + +One neat thing about the `json!` macro is that variables and expressions can +be interpolated directly into the JSON value as you are building it. Serde +will check at compile time that the value you are interpolating is able to +be represented as JSON. + +<a href="http://play.integer32.com/?gist=aae3af4d274bd249d1c8a947076355f2" target="_blank"> +<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png"> +</a> + +```rust +let full_name = "John Doe"; +let age_last_year = 42; + +// The type of `john` is `serde_json::Value` +let john = json!({ + "name": full_name, + "age": age_last_year + 1, + "phones": [ + format!("+44 {}", random_phone()) + ] +}); +``` + +This is amazingly convenient but we have the problem we had before with +`Value` which is that the IDE and Rust compiler cannot help us if we get it +wrong. Serde JSON provides a better way of serializing strongly-typed data +structures into JSON text. + +## Creating JSON by serializing data structures + +A data structure can be converted to a JSON string by +[`serde_json::to_string`][to_string]. There is also +[`serde_json::to_vec`][to_vec] which serializes to a `Vec<u8>` and +[`serde_json::to_writer`][to_writer] which serializes to any `io::Write` +such as a File or a TCP stream. + +<a href="http://play.integer32.com/?gist=40967ece79921c77fd78ebc8f177c063" target="_blank"> +<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png"> +</a> + +```rust +extern crate serde; +extern crate serde_json; + +#[macro_use] +extern crate serde_derive; + +use serde_json::Error; + +#[derive(Serialize, Deserialize)] +struct Address { + street: String, + city: String, +} + +fn print_an_address() -> Result<(), Error> { + // Some data structure. + let address = Address { + street: "10 Downing Street".to_owned(), + city: "London".to_owned(), + }; + + // Serialize it to a JSON string. + let j = serde_json::to_string(&address)?; + + // Print, write to a file, or send to an HTTP server. + println!("{}", j); + + Ok(()) +} +``` + +Any type that implements Serde's `Serialize` trait can be serialized this +way. This includes built-in Rust standard library types like `Vec<T>` and +`HashMap<K, V>`, as well as any structs or enums annotated with +`#[derive(Serialize)]`. + +## Performance + +It is fast. You should expect in the ballpark of 500 to 1000 megabytes per +second deserialization and 600 to 900 megabytes per second serialization, +depending on the characteristics of your data. This is competitive with the +fastest C and C++ JSON libraries or even 30% faster for many use cases. +Benchmarks live in the [serde-rs/json-benchmark] repo. + +[serde-rs/json-benchmark]: https://github.com/serde-rs/json-benchmark + +## Getting help + +Serde developers live in the #serde channel on +[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a +good resource with generally faster response time but less specific knowledge +about Serde. If IRC is not your thing, we are happy to respond to [GitHub +issues](https://github.com/serde-rs/json/issues/new) as well. + +## License + +Serde JSON is 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 Serde JSON by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. + +[value]: https://docs.serde.rs/serde_json/value/enum.Value.html +[from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html +[from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html +[from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html +[to_string]: https://docs.serde.rs/serde_json/ser/fn.to_string.html +[to_vec]: https://docs.serde.rs/serde_json/ser/fn.to_vec.html +[to_writer]: https://docs.serde.rs/serde_json/ser/fn.to_writer.html +[macro]: https://docs.serde.rs/serde_json/macro.json.html diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/de.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/de.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/de.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/de.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2175 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Deserialize JSON data to a Rust data structure. + +use std::{i32, u64}; +use std::io; +use std::marker::PhantomData; + +use serde::de::{self, Expected, Unexpected}; + +use super::error::{Error, ErrorCode, Result}; + +use read::{self, Reference}; + +pub use read::{Read, IoRead, SliceRead, StrRead}; + +#[cfg(feature = "arbitrary_precision")] +use number::NumberDeserializer; + +////////////////////////////////////////////////////////////////////////////// + +/// A structure that deserializes JSON into Rust values. +pub struct Deserializer<R> { + read: R, + str_buf: Vec<u8>, + remaining_depth: u8, +} + +impl<'de, R> Deserializer<R> +where + R: read::Read<'de>, +{ + /// Create a JSON deserializer from one of the possible serde_json input + /// sources. + /// + /// Typically it is more convenient to use one of these methods instead: + /// + /// - Deserializer::from_str + /// - Deserializer::from_bytes + /// - Deserializer::from_reader + pub fn new(read: R) -> Self { + Deserializer { + read: read, + str_buf: Vec::with_capacity(128), + remaining_depth: 128, + } + } +} + +impl<R> Deserializer<read::IoRead<R>> +where + R: io::Read, +{ + /// Creates a JSON deserializer from an `io::Read`. + pub fn from_reader(reader: R) -> Self { + Deserializer::new(read::IoRead::new(reader)) + } +} + +impl<'a> Deserializer<read::SliceRead<'a>> { + /// Creates a JSON deserializer from a `&[u8]`. + pub fn from_slice(bytes: &'a [u8]) -> Self { + Deserializer::new(read::SliceRead::new(bytes)) + } +} + +impl<'a> Deserializer<read::StrRead<'a>> { + /// Creates a JSON deserializer from a `&str`. + pub fn from_str(s: &'a str) -> Self { + Deserializer::new(read::StrRead::new(s)) + } +} + +macro_rules! overflow { + ($a:ident * 10 + $b:ident, $c:expr) => { + $a >= $c / 10 && ($a > $c / 10 || $b > $c % 10) + } +} + +// Not public API. Should be pub(crate). +#[doc(hidden)] +pub enum Number { + F64(f64), + U64(u64), + I64(i64), + #[cfg(feature = "arbitrary_precision")] + String(String), +} + +impl Number { + fn visit<'de, V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + match self { + Number::F64(x) => visitor.visit_f64(x), + Number::U64(x) => visitor.visit_u64(x), + Number::I64(x) => visitor.visit_i64(x), + #[cfg(feature = "arbitrary_precision")] + Number::String(x) => { + visitor.visit_map(NumberDeserializer { + number: x.into(), + }) + }, + } + } + + fn invalid_type(self, exp: &Expected) -> Error { + match self { + Number::F64(x) => de::Error::invalid_type(Unexpected::Float(x), exp), + Number::U64(x) => de::Error::invalid_type(Unexpected::Unsigned(x), exp), + Number::I64(x) => de::Error::invalid_type(Unexpected::Signed(x), exp), + #[cfg(feature = "arbitrary_precision")] + Number::String(_) => de::Error::invalid_type(Unexpected::Other("number"), exp), + } + } +} + +impl<'de, R: Read<'de>> Deserializer<R> { + /// The `Deserializer::end` method should be called after a value has been fully deserialized. + /// This allows the `Deserializer` to validate that the input stream is at the end or that it + /// only has trailing whitespace. + pub fn end(&mut self) -> Result<()> { + match try!(self.parse_whitespace()) { + Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)), + None => Ok(()), + } + } + + /// Turn a JSON deserializer into an iterator over values of type T. + pub fn into_iter<T>(self) -> StreamDeserializer<'de, R, T> + where + T: de::Deserialize<'de>, + { + // This cannot be an implementation of std::iter::IntoIterator because + // we need the caller to choose what T is. + let offset = self.read.byte_offset(); + StreamDeserializer { + de: self, + offset: offset, + output: PhantomData, + lifetime: PhantomData, + } + } + + fn peek(&mut self) -> Result<Option<u8>> { + self.read.peek().map_err(Error::io) + } + + fn peek_or_null(&mut self) -> Result<u8> { + Ok(try!(self.peek()).unwrap_or(b'\x00')) + } + + fn eat_char(&mut self) { + self.read.discard(); + } + + fn next_char(&mut self) -> Result<Option<u8>> { + self.read.next().map_err(Error::io) + } + + fn next_char_or_null(&mut self) -> Result<u8> { + Ok(try!(self.next_char()).unwrap_or(b'\x00')) + } + + /// Error caused by a byte from next_char(). + #[cold] + fn error(&self, reason: ErrorCode) -> Error { + let pos = self.read.position(); + Error::syntax(reason, pos.line, pos.column) + } + + /// Error caused by a byte from peek(). + #[cold] + fn peek_error(&self, reason: ErrorCode) -> Error { + let pos = self.read.peek_position(); + Error::syntax(reason, pos.line, pos.column) + } + + /// Returns the first non-whitespace byte without consuming it, or `None` if + /// EOF is encountered. + fn parse_whitespace(&mut self) -> Result<Option<u8>> { + loop { + match try!(self.peek()) { + Some(b' ') | Some(b'\n') | Some(b'\t') | Some(b'\r') => { + self.eat_char(); + } + other => { + return Ok(other); + } + } + } + } + + #[cold] + fn peek_invalid_type(&mut self, exp: &Expected) -> Error { + let err = match self.peek_or_null().unwrap_or(b'\x00') { + b'n' => { + self.eat_char(); + if let Err(err) = self.parse_ident(b"ull") { + return err; + } + de::Error::invalid_type(Unexpected::Unit, exp) + } + b't' => { + self.eat_char(); + if let Err(err) = self.parse_ident(b"rue") { + return err; + } + de::Error::invalid_type(Unexpected::Bool(true), exp) + } + b'f' => { + self.eat_char(); + if let Err(err) = self.parse_ident(b"alse") { + return err; + } + de::Error::invalid_type(Unexpected::Bool(false), exp) + } + b'-' => { + self.eat_char(); + match self.parse_any_number(false) { + Ok(n) => n.invalid_type(exp), + Err(err) => return err, + } + } + b'0'...b'9' => { + match self.parse_any_number(true) { + Ok(n) => n.invalid_type(exp), + Err(err) => return err, + } + } + b'"' => { + self.eat_char(); + self.str_buf.clear(); + match self.read.parse_str(&mut self.str_buf) { + Ok(s) => de::Error::invalid_type(Unexpected::Str(&s), exp), + Err(err) => return err, + } + } + b'[' => { + de::Error::invalid_type(Unexpected::Seq, exp) + } + b'{' => { + de::Error::invalid_type(Unexpected::Map, exp) + } + _ => self.peek_error(ErrorCode::ExpectedSomeValue), + }; + + self.fix_position(err) + } + + fn deserialize_prim_number<V>(&mut self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + let peek = match try!(self.parse_whitespace()) { + Some(b) => b, + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); + } + }; + + let value = match peek { + b'-' => { + self.eat_char(); + try!(self.parse_integer(false)).visit(visitor) + } + b'0'...b'9' => try!(self.parse_integer(true)).visit(visitor), + _ => Err(self.peek_invalid_type(&visitor)), + }; + + match value { + Ok(value) => Ok(value), + Err(err) => Err(self.fix_position(err)), + } + } + + #[cold] + fn fix_position(&self, err: Error) -> Error { + err.fix_position(move |code| self.error(code)) + } + + fn parse_ident(&mut self, ident: &[u8]) -> Result<()> { + for c in ident { + if Some(*c) != try!(self.next_char()) { + return Err(self.error(ErrorCode::ExpectedSomeIdent)); + } + } + + Ok(()) + } + + fn parse_integer(&mut self, positive: bool) -> Result<Number> { + match try!(self.next_char_or_null()) { + b'0' => { + // There can be only one leading '0'. + match try!(self.peek_or_null()) { + b'0'...b'9' => Err(self.peek_error(ErrorCode::InvalidNumber)), + _ => self.parse_number(positive, 0), + } + } + c @ b'1'...b'9' => { + let mut res = (c - b'0') as u64; + + loop { + match try!(self.peek_or_null()) { + c @ b'0'...b'9' => { + self.eat_char(); + let digit = (c - b'0') as u64; + + // We need to be careful with overflow. If we can, try to keep the + // number as a `u64` until we grow too large. At that point, switch to + // parsing the value as a `f64`. + if overflow!(res * 10 + digit, u64::max_value()) { + return Ok(Number::F64(try!(self.parse_long_integer( + positive, + res, + 1, // res * 10^1 + )))); + } + + res = res * 10 + digit; + } + _ => { + return self.parse_number(positive, res); + } + } + } + } + _ => Err(self.error(ErrorCode::InvalidNumber)), + } + } + + fn parse_long_integer( + &mut self, + positive: bool, + significand: u64, + mut exponent: i32, + ) -> Result<f64> { + loop { + match try!(self.peek_or_null()) { + b'0'...b'9' => { + self.eat_char(); + // This could overflow... if your integer is gigabytes long. + // Ignore that possibility. + exponent += 1; + } + b'.' => { + return self.parse_decimal(positive, significand, exponent); + } + b'e' | b'E' => { + return self.parse_exponent(positive, significand, exponent); + } + _ => { + return self.f64_from_parts(positive, significand, exponent); + } + } + } + } + + fn parse_number(&mut self, positive: bool, significand: u64) -> Result<Number> { + Ok(match try!(self.peek_or_null()) { + b'.' => Number::F64(try!(self.parse_decimal(positive, significand, 0))), + b'e' | b'E' => Number::F64(try!(self.parse_exponent(positive, significand, 0))), + _ => { + if positive { + Number::U64(significand) + } else { + let neg = (significand as i64).wrapping_neg(); + + // Convert into a float if we underflow. + if neg > 0 { + Number::F64(-(significand as f64)) + } else { + Number::I64(neg) + } + } + } + }) + } + + fn parse_decimal( + &mut self, + positive: bool, + mut significand: u64, + mut exponent: i32, + ) -> Result<f64> { + self.eat_char(); + + let mut at_least_one_digit = false; + while let c @ b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + let digit = (c - b'0') as u64; + at_least_one_digit = true; + + if overflow!(significand * 10 + digit, u64::max_value()) { + // The next multiply/add would overflow, so just ignore all + // further digits. + while let b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + } + break; + } + + significand = significand * 10 + digit; + exponent -= 1; + } + + if !at_least_one_digit { + return Err(self.peek_error(ErrorCode::InvalidNumber)); + } + + match try!(self.peek_or_null()) { + b'e' | b'E' => self.parse_exponent(positive, significand, exponent), + _ => self.f64_from_parts(positive, significand, exponent), + } + } + + fn parse_exponent( + &mut self, + positive: bool, + significand: u64, + starting_exp: i32, + ) -> Result<f64> { + self.eat_char(); + + let pos_exp = match try!(self.peek_or_null()) { + b'+' => { + self.eat_char(); + true + } + b'-' => { + self.eat_char(); + false + } + _ => true, + }; + + // Make sure a digit follows the exponent place. + let mut exp = match try!(self.next_char_or_null()) { + c @ b'0'...b'9' => (c - b'0') as i32, + _ => { + return Err(self.error(ErrorCode::InvalidNumber)); + } + }; + + while let c @ b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + let digit = (c - b'0') as i32; + + if overflow!(exp * 10 + digit, i32::max_value()) { + return self.parse_exponent_overflow(positive, significand, pos_exp); + } + + exp = exp * 10 + digit; + } + + let final_exp = if pos_exp { + starting_exp.saturating_add(exp) + } else { + starting_exp.saturating_sub(exp) + }; + + self.f64_from_parts(positive, significand, final_exp) + } + + // This cold code should not be inlined into the middle of the hot + // exponent-parsing loop above. + #[cold] + #[inline(never)] + fn parse_exponent_overflow( + &mut self, + positive: bool, + significand: u64, + pos_exp: bool, + ) -> Result<f64> { + // Error instead of +/- infinity. + if significand != 0 && pos_exp { + return Err(self.error(ErrorCode::NumberOutOfRange)); + } + + while let b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + } + Ok(if positive { 0.0 } else { -0.0 }) + } + + // Not public API. Should be pub(crate). + #[doc(hidden)] + pub fn parse_any_signed_number(&mut self) -> Result<Number> { + let peek = match try!(self.peek()) { + Some(b) => b, + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); + } + }; + + let value = match peek { + b'-' => { + self.eat_char(); + self.parse_any_number(false) + } + b'0'...b'9' => { + self.parse_any_number(true) + } + _ => Err(self.peek_error(ErrorCode::InvalidNumber)), + }; + + let value = match try!(self.peek()) { + Some(_) => Err(self.peek_error(ErrorCode::InvalidNumber)), + None => value, + }; + + match value { + Ok(value) => Ok(value), + // The de::Error impl creates errors with unknown line and column. + // Fill in the position here by looking at the current index in the + // input. There is no way to tell whether this should call `error` + // or `peek_error` so pick the one that seems correct more often. + // Worst case, the position is off by one character. + Err(err) => Err(self.fix_position(err)), + } + } + + #[cfg(not(feature = "arbitrary_precision"))] + fn parse_any_number(&mut self, pos: bool) -> Result<Number> + { + self.parse_integer(pos) + } + + #[cfg(feature = "arbitrary_precision")] + fn parse_any_number(&mut self, pos: bool) -> Result<Number> + { + let mut buf = String::with_capacity(16); + if !pos { + buf.push('-'); + } + self.scan_integer(&mut buf)?; + Ok(Number::String(buf)) + } + + #[cfg(feature = "arbitrary_precision")] + fn scan_or_null(&mut self, buf: &mut String) -> Result<u8> { + match try!(self.next_char()) { + Some(b) => { + buf.push(b as char); + Ok(b) + } + None => { + Ok(b'\x00') + } + } + } + + #[cfg(feature = "arbitrary_precision")] + fn scan_integer(&mut self, buf: &mut String) -> Result<()> { + match try!(self.scan_or_null(buf)) { + b'0' => { + // There can be only one leading '0'. + match try!(self.peek_or_null()) { + b'0'...b'9' => { + Err(self.peek_error(ErrorCode::InvalidNumber)) + } + _ => self.scan_number(buf), + } + } + b'1'...b'9' => { + loop { + match try!(self.peek_or_null()) { + c @ b'0'...b'9' => { + self.eat_char(); + buf.push(c as char); + } + _ => { + return self.scan_number(buf); + } + } + } + } + _ => Err(self.error(ErrorCode::InvalidNumber)), + } + } + + #[cfg(feature = "arbitrary_precision")] + fn scan_number(&mut self, buf: &mut String) -> Result<()> { + match try!(self.peek_or_null()) { + b'.' => self.scan_decimal(buf), + b'e' | b'E' => self.scan_exponent(buf), + _ => Ok(()), + } + } + + #[cfg(feature = "arbitrary_precision")] + fn scan_decimal(&mut self, buf: &mut String) -> Result<()> { + self.eat_char(); + buf.push('.'); + + let mut at_least_one_digit = false; + while let c @ b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + buf.push(c as char); + at_least_one_digit = true; + } + + if !at_least_one_digit { + return Err(self.peek_error(ErrorCode::InvalidNumber)); + } + + match try!(self.peek_or_null()) { + b'e' | b'E' => self.scan_exponent(buf), + _ => Ok(()), + } + } + + #[cfg(feature = "arbitrary_precision")] + fn scan_exponent(&mut self, buf: &mut String) -> Result<()> { + self.eat_char(); + buf.push('e'); + + match try!(self.peek_or_null()) { + b'+' => { + self.eat_char(); + } + b'-' => { + self.eat_char(); + buf.push('-'); + } + _ => {} + } + + // Make sure a digit follows the exponent place. + match try!(self.scan_or_null(buf)) { + b'0'...b'9' => {} + _ => { + return Err(self.error(ErrorCode::InvalidNumber)); + } + } + + while let c @ b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + buf.push(c as char); + } + + Ok(()) + } + + fn f64_from_parts( + &mut self, + positive: bool, + significand: u64, + mut exponent: i32, + ) -> Result<f64> { + let mut f = significand as f64; + loop { + match POW10.get(exponent.abs() as usize) { + Some(&pow) => { + if exponent >= 0 { + f *= pow; + if f.is_infinite() { + return Err(self.error(ErrorCode::NumberOutOfRange)); + } + } else { + f /= pow; + } + break; + } + None => { + if f == 0.0 { + break; + } + if exponent >= 0 { + return Err(self.error(ErrorCode::NumberOutOfRange)); + } + f /= 1e308; + exponent += 308; + } + } + } + Ok(if positive { f } else { -f }) + } + + fn parse_object_colon(&mut self) -> Result<()> { + match try!(self.parse_whitespace()) { + Some(b':') => { + self.eat_char(); + Ok(()) + } + Some(_) => Err(self.peek_error(ErrorCode::ExpectedColon)), + None => Err(self.peek_error(ErrorCode::EofWhileParsingObject)), + } + } + + fn end_seq(&mut self) -> Result<()> { + match try!(self.parse_whitespace()) { + Some(b']') => { + self.eat_char(); + Ok(()) + } + Some(b',') => { + self.eat_char(); + match self.parse_whitespace() { + Ok(Some(b']')) => Err(self.peek_error(ErrorCode::TrailingComma)), + _ => Err(self.peek_error(ErrorCode::TrailingCharacters)), + } + } + Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)), + None => Err(self.peek_error(ErrorCode::EofWhileParsingList)), + } + } + + fn end_map(&mut self) -> Result<()> { + match try!(self.parse_whitespace()) { + Some(b'}') => { + self.eat_char(); + Ok(()) + } + Some(b',') => Err(self.peek_error(ErrorCode::TrailingComma)), + Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)), + None => Err(self.peek_error(ErrorCode::EofWhileParsingObject)), + } + } + + fn ignore_value(&mut self) -> Result<()> { + let peek = match try!(self.parse_whitespace()) { + Some(b) => b, + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); + } + }; + + match peek { + b'n' => { + self.eat_char(); + self.parse_ident(b"ull") + } + b't' => { + self.eat_char(); + self.parse_ident(b"rue") + } + b'f' => { + self.eat_char(); + self.parse_ident(b"alse") + } + b'-' => { + self.eat_char(); + self.ignore_integer() + } + b'0'...b'9' => { + self.ignore_integer() + } + b'"' => { + self.eat_char(); + self.read.ignore_str() + } + b'[' => { + self.remaining_depth -= 1; + if self.remaining_depth == 0 { + return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); + } + + self.eat_char(); + let res = self.ignore_seq(); + self.remaining_depth += 1; + res + } + b'{' => { + self.remaining_depth -= 1; + if self.remaining_depth == 0 { + return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); + } + + self.eat_char(); + let res = self.ignore_map(); + self.remaining_depth += 1; + res + } + _ => { + Err(self.peek_error(ErrorCode::ExpectedSomeValue)) + } + } + } + + fn ignore_integer(&mut self) -> Result<()> { + match try!(self.next_char_or_null()) { + b'0' => { + // There can be only one leading '0'. + if let b'0'...b'9' = try!(self.peek_or_null()) { + return Err(self.peek_error(ErrorCode::InvalidNumber)); + } + } + b'1'...b'9' => { + while let b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + } + } + _ => { + return Err(self.error(ErrorCode::InvalidNumber)); + } + } + + match try!(self.peek_or_null()) { + b'.' => self.ignore_decimal(), + b'e' | b'E' => self.ignore_exponent(), + _ => Ok(()), + } + } + + fn ignore_decimal(&mut self) -> Result<()> { + self.eat_char(); + + let mut at_least_one_digit = false; + while let b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + at_least_one_digit = true; + } + + if !at_least_one_digit { + return Err(self.peek_error(ErrorCode::InvalidNumber)); + } + + match try!(self.peek_or_null()) { + b'e' | b'E' => self.ignore_exponent(), + _ => Ok(()), + } + } + + fn ignore_exponent(&mut self) -> Result<()> { + self.eat_char(); + + match try!(self.peek_or_null()) { + b'+' | b'-' => self.eat_char(), + _ => {} + } + + // Make sure a digit follows the exponent place. + match try!(self.next_char_or_null()) { + b'0'...b'9' => {} + _ => { + return Err(self.error(ErrorCode::InvalidNumber)); + } + } + + while let b'0'...b'9' = try!(self.peek_or_null()) { + self.eat_char(); + } + + Ok(()) + } + + fn ignore_seq(&mut self) -> Result<()> { + let mut first = true; + + loop { + match try!(self.parse_whitespace()) { + Some(b']') => { + self.eat_char(); + return Ok(()); + } + Some(b',') if !first => { + self.eat_char(); + } + Some(_) => { + if first { + first = false; + } else { + return Err(self.peek_error(ErrorCode::ExpectedListCommaOrEnd)); + } + } + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingList)); + } + } + + try!(self.ignore_value()); + } + } + + fn ignore_map(&mut self) -> Result<()> { + let mut first = true; + + loop { + let peek = match try!(self.parse_whitespace()) { + Some(b'}') => { + self.eat_char(); + return Ok(()); + } + Some(b',') if !first => { + self.eat_char(); + try!(self.parse_whitespace()) + } + Some(b) => { + if first { + first = false; + Some(b) + } else { + return Err(self.peek_error(ErrorCode::ExpectedObjectCommaOrEnd)); + } + } + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingObject)); + } + }; + + match peek { + Some(b'"') => { + self.eat_char(); + try!(self.read.ignore_str()); + } + Some(_) => { + return Err(self.peek_error(ErrorCode::KeyMustBeAString)); + } + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingObject)); + } + } + + match try!(self.parse_whitespace()) { + Some(b':') => { + self.eat_char(); + try!(self.ignore_value()); + } + Some(_) => { + return Err(self.peek_error(ErrorCode::ExpectedColon)); + } + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingObject)); + } + } + } + } +} + +#[cfg_attr(rustfmt, rustfmt_skip)] +static POW10: [f64; 309] = + [1e000, 1e001, 1e002, 1e003, 1e004, 1e005, 1e006, 1e007, 1e008, 1e009, + 1e010, 1e011, 1e012, 1e013, 1e014, 1e015, 1e016, 1e017, 1e018, 1e019, + 1e020, 1e021, 1e022, 1e023, 1e024, 1e025, 1e026, 1e027, 1e028, 1e029, + 1e030, 1e031, 1e032, 1e033, 1e034, 1e035, 1e036, 1e037, 1e038, 1e039, + 1e040, 1e041, 1e042, 1e043, 1e044, 1e045, 1e046, 1e047, 1e048, 1e049, + 1e050, 1e051, 1e052, 1e053, 1e054, 1e055, 1e056, 1e057, 1e058, 1e059, + 1e060, 1e061, 1e062, 1e063, 1e064, 1e065, 1e066, 1e067, 1e068, 1e069, + 1e070, 1e071, 1e072, 1e073, 1e074, 1e075, 1e076, 1e077, 1e078, 1e079, + 1e080, 1e081, 1e082, 1e083, 1e084, 1e085, 1e086, 1e087, 1e088, 1e089, + 1e090, 1e091, 1e092, 1e093, 1e094, 1e095, 1e096, 1e097, 1e098, 1e099, + 1e100, 1e101, 1e102, 1e103, 1e104, 1e105, 1e106, 1e107, 1e108, 1e109, + 1e110, 1e111, 1e112, 1e113, 1e114, 1e115, 1e116, 1e117, 1e118, 1e119, + 1e120, 1e121, 1e122, 1e123, 1e124, 1e125, 1e126, 1e127, 1e128, 1e129, + 1e130, 1e131, 1e132, 1e133, 1e134, 1e135, 1e136, 1e137, 1e138, 1e139, + 1e140, 1e141, 1e142, 1e143, 1e144, 1e145, 1e146, 1e147, 1e148, 1e149, + 1e150, 1e151, 1e152, 1e153, 1e154, 1e155, 1e156, 1e157, 1e158, 1e159, + 1e160, 1e161, 1e162, 1e163, 1e164, 1e165, 1e166, 1e167, 1e168, 1e169, + 1e170, 1e171, 1e172, 1e173, 1e174, 1e175, 1e176, 1e177, 1e178, 1e179, + 1e180, 1e181, 1e182, 1e183, 1e184, 1e185, 1e186, 1e187, 1e188, 1e189, + 1e190, 1e191, 1e192, 1e193, 1e194, 1e195, 1e196, 1e197, 1e198, 1e199, + 1e200, 1e201, 1e202, 1e203, 1e204, 1e205, 1e206, 1e207, 1e208, 1e209, + 1e210, 1e211, 1e212, 1e213, 1e214, 1e215, 1e216, 1e217, 1e218, 1e219, + 1e220, 1e221, 1e222, 1e223, 1e224, 1e225, 1e226, 1e227, 1e228, 1e229, + 1e230, 1e231, 1e232, 1e233, 1e234, 1e235, 1e236, 1e237, 1e238, 1e239, + 1e240, 1e241, 1e242, 1e243, 1e244, 1e245, 1e246, 1e247, 1e248, 1e249, + 1e250, 1e251, 1e252, 1e253, 1e254, 1e255, 1e256, 1e257, 1e258, 1e259, + 1e260, 1e261, 1e262, 1e263, 1e264, 1e265, 1e266, 1e267, 1e268, 1e269, + 1e270, 1e271, 1e272, 1e273, 1e274, 1e275, 1e276, 1e277, 1e278, 1e279, + 1e280, 1e281, 1e282, 1e283, 1e284, 1e285, 1e286, 1e287, 1e288, 1e289, + 1e290, 1e291, 1e292, 1e293, 1e294, 1e295, 1e296, 1e297, 1e298, 1e299, + 1e300, 1e301, 1e302, 1e303, 1e304, 1e305, 1e306, 1e307, 1e308]; + +macro_rules! deserialize_prim_number { + ($method:ident) => { + fn $method<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.deserialize_prim_number(visitor) + } + } +} + +impl<'de, 'a, R: Read<'de>> de::Deserializer<'de> for &'a mut Deserializer<R> { + type Error = Error; + + #[inline] + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + let peek = match try!(self.parse_whitespace()) { + Some(b) => b, + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); + } + }; + + let value = match peek { + b'n' => { + self.eat_char(); + try!(self.parse_ident(b"ull")); + visitor.visit_unit() + } + b't' => { + self.eat_char(); + try!(self.parse_ident(b"rue")); + visitor.visit_bool(true) + } + b'f' => { + self.eat_char(); + try!(self.parse_ident(b"alse")); + visitor.visit_bool(false) + } + b'-' => { + self.eat_char(); + try!(self.parse_any_number(false)).visit(visitor) + } + b'0'...b'9' => { + try!(self.parse_any_number(true)).visit(visitor) + } + b'"' => { + self.eat_char(); + self.str_buf.clear(); + match try!(self.read.parse_str(&mut self.str_buf)) { + Reference::Borrowed(s) => visitor.visit_borrowed_str(s), + Reference::Copied(s) => visitor.visit_str(s), + } + } + b'[' => { + self.remaining_depth -= 1; + if self.remaining_depth == 0 { + return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); + } + + self.eat_char(); + let ret = visitor.visit_seq(SeqAccess::new(self)); + + self.remaining_depth += 1; + + match (ret, self.end_seq()) { + (Ok(ret), Ok(())) => Ok(ret), + (Err(err), _) | (_, Err(err)) => Err(err), + } + } + b'{' => { + self.remaining_depth -= 1; + if self.remaining_depth == 0 { + return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); + } + + self.eat_char(); + let ret = visitor.visit_map(MapAccess::new(self)); + + self.remaining_depth += 1; + + match (ret, self.end_map()) { + (Ok(ret), Ok(())) => Ok(ret), + (Err(err), _) | (_, Err(err)) => Err(err), + } + } + _ => Err(self.peek_error(ErrorCode::ExpectedSomeValue)), + }; + + match value { + Ok(value) => Ok(value), + // The de::Error impl creates errors with unknown line and column. + // Fill in the position here by looking at the current index in the + // input. There is no way to tell whether this should call `error` + // or `peek_error` so pick the one that seems correct more often. + // Worst case, the position is off by one character. + Err(err) => Err(self.fix_position(err)), + } + } + + fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + let peek = match try!(self.parse_whitespace()) { + Some(b) => b, + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); + } + }; + + let value = match peek { + b't' => { + self.eat_char(); + try!(self.parse_ident(b"rue")); + visitor.visit_bool(true) + } + b'f' => { + self.eat_char(); + try!(self.parse_ident(b"alse")); + visitor.visit_bool(false) + } + _ => Err(self.peek_invalid_type(&visitor)), + }; + + match value { + Ok(value) => Ok(value), + Err(err) => Err(self.fix_position(err)), + } + } + + deserialize_prim_number!(deserialize_i8); + deserialize_prim_number!(deserialize_i16); + deserialize_prim_number!(deserialize_i32); + deserialize_prim_number!(deserialize_i64); + deserialize_prim_number!(deserialize_u8); + deserialize_prim_number!(deserialize_u16); + deserialize_prim_number!(deserialize_u32); + deserialize_prim_number!(deserialize_u64); + deserialize_prim_number!(deserialize_f32); + deserialize_prim_number!(deserialize_f64); + + fn deserialize_char<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.deserialize_str(visitor) + } + + fn deserialize_str<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + let peek = match try!(self.parse_whitespace()) { + Some(b) => b, + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); + } + }; + + let value = match peek { + b'"' => { + self.eat_char(); + self.str_buf.clear(); + match try!(self.read.parse_str(&mut self.str_buf)) { + Reference::Borrowed(s) => visitor.visit_borrowed_str(s), + Reference::Copied(s) => visitor.visit_str(s), + } + } + _ => Err(self.peek_invalid_type(&visitor)), + }; + + match value { + Ok(value) => Ok(value), + Err(err) => Err(self.fix_position(err)), + } + } + + fn deserialize_string<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.deserialize_str(visitor) + } + + /// Parses a JSON string as bytes. Note that this function does not check + /// whether the bytes represent a valid UTF-8 string. + /// + /// The relevant part of the JSON specification is Section 8.2 of [RFC + /// 7159]: + /// + /// > When all the strings represented in a JSON text are composed entirely + /// > of Unicode characters (however escaped), then that JSON text is + /// > interoperable in the sense that all software implementations that + /// > parse it will agree on the contents of names and of string values in + /// > objects and arrays. + /// > + /// > However, the ABNF in this specification allows member names and string + /// > values to contain bit sequences that cannot encode Unicode characters; + /// > for example, "\uDEAD" (a single unpaired UTF-16 surrogate). Instances + /// > of this have been observed, for example, when a library truncates a + /// > UTF-16 string without checking whether the truncation split a + /// > surrogate pair. The behavior of software that receives JSON texts + /// > containing such values is unpredictable; for example, implementations + /// > might return different values for the length of a string value or even + /// > suffer fatal runtime exceptions. + /// + /// [RFC 7159]: https://tools.ietf.org/html/rfc7159 + /// + /// The behavior of serde_json is specified to fail on non-UTF-8 strings + /// when deserializing into Rust UTF-8 string types such as String, and + /// succeed with non-UTF-8 bytes when deserializing using this method. + /// + /// Escape sequences are processed as usual, and for `\uXXXX` escapes it is + /// still checked if the hex number represents a valid Unicode code point. + /// + /// # Examples + /// + /// You can use this to parse JSON strings containing invalid UTF-8 bytes. + /// + /// ```rust + /// extern crate serde_json; + /// extern crate serde_bytes; + /// + /// use serde_bytes::ByteBuf; + /// + /// fn look_at_bytes() -> Result<(), serde_json::Error> { + /// let json_data = b"\"some bytes: \xe5\x00\xe5\""; + /// let bytes: ByteBuf = serde_json::from_slice(json_data)?; + /// + /// assert_eq!(b'\xe5', bytes[12]); + /// assert_eq!(b'\0', bytes[13]); + /// assert_eq!(b'\xe5', bytes[14]); + /// + /// Ok(()) + /// } + /// # + /// # fn main() { + /// # look_at_bytes().unwrap(); + /// # } + /// ``` + /// + /// Backslash escape sequences like `\n` are still interpreted and required + /// to be valid, and `\u` escape sequences are required to represent valid + /// Unicode code points. + /// + /// ```rust + /// extern crate serde_json; + /// extern crate serde_bytes; + /// + /// use serde_bytes::ByteBuf; + /// + /// fn look_at_bytes() { + /// let json_data = b"\"invalid unicode surrogate: \\uD801\""; + /// let parsed: Result<ByteBuf, _> = serde_json::from_slice(json_data); + /// + /// assert!(parsed.is_err()); + /// + /// let expected_msg = "unexpected end of hex escape at line 1 column 35"; + /// assert_eq!(expected_msg, parsed.unwrap_err().to_string()); + /// } + /// # + /// # fn main() { + /// # look_at_bytes(); + /// # } + /// ``` + fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + let peek = match try!(self.parse_whitespace()) { + Some(b) => b, + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); + } + }; + + let value = match peek { + b'"' => { + self.eat_char(); + self.str_buf.clear(); + match try!(self.read.parse_str_raw(&mut self.str_buf)) { + Reference::Borrowed(b) => visitor.visit_borrowed_bytes(b), + Reference::Copied(b) => visitor.visit_bytes(b), + } + } + b'[' => self.deserialize_seq(visitor), + _ => Err(self.peek_invalid_type(&visitor)), + }; + + match value { + Ok(value) => Ok(value), + Err(err) => Err(self.fix_position(err)), + } + } + + #[inline] + fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.deserialize_bytes(visitor) + } + + /// Parses a `null` as a None, and any other values as a `Some(...)`. + #[inline] + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + match try!(self.parse_whitespace()) { + Some(b'n') => { + self.eat_char(); + try!(self.parse_ident(b"ull")); + visitor.visit_none() + } + _ => visitor.visit_some(self), + } + } + + fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + let peek = match try!(self.parse_whitespace()) { + Some(b) => b, + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); + } + }; + + let value = match peek { + b'n' => { + self.eat_char(); + try!(self.parse_ident(b"ull")); + visitor.visit_unit() + } + _ => Err(self.peek_invalid_type(&visitor)), + }; + + match value { + Ok(value) => Ok(value), + Err(err) => Err(self.fix_position(err)), + } + } + + fn deserialize_unit_struct<V>( + self, + _name: &'static str, + visitor: V + ) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.deserialize_unit(visitor) + } + + /// Parses a newtype struct as the underlying value. + #[inline] + fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + let peek = match try!(self.parse_whitespace()) { + Some(b) => b, + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); + } + }; + + let value = match peek { + b'[' => { + self.remaining_depth -= 1; + if self.remaining_depth == 0 { + return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); + } + + self.eat_char(); + let ret = visitor.visit_seq(SeqAccess::new(self)); + + self.remaining_depth += 1; + + match (ret, self.end_seq()) { + (Ok(ret), Ok(())) => Ok(ret), + (Err(err), _) | (_, Err(err)) => Err(err), + } + } + _ => Err(self.peek_invalid_type(&visitor)), + }; + + match value { + Ok(value) => Ok(value), + Err(err) => Err(self.fix_position(err)), + } + } + + fn deserialize_tuple<V>( + self, + _len: usize, + visitor: V + ) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_tuple_struct<V>( + self, + _name: &'static str, + _len: usize, + visitor: V + ) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.deserialize_seq(visitor) + } + + fn deserialize_map<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + let peek = match try!(self.parse_whitespace()) { + Some(b) => b, + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); + } + }; + + let value = match peek { + b'{' => { + self.remaining_depth -= 1; + if self.remaining_depth == 0 { + return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); + } + + self.eat_char(); + let ret = visitor.visit_map(MapAccess::new(self)); + + self.remaining_depth += 1; + + match (ret, self.end_map()) { + (Ok(ret), Ok(())) => Ok(ret), + (Err(err), _) | (_, Err(err)) => Err(err), + } + } + _ => Err(self.peek_invalid_type(&visitor)), + }; + + match value { + Ok(value) => Ok(value), + Err(err) => Err(self.fix_position(err)), + } + } + + fn deserialize_struct<V>( + self, + _name: &'static str, + _fields: &'static [&'static str], + visitor: V + ) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + let peek = match try!(self.parse_whitespace()) { + Some(b) => b, + None => { + return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); + } + }; + + let value = match peek { + b'[' => { + self.remaining_depth -= 1; + if self.remaining_depth == 0 { + return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); + } + + self.eat_char(); + let ret = visitor.visit_seq(SeqAccess::new(self)); + + self.remaining_depth += 1; + + match (ret, self.end_seq()) { + (Ok(ret), Ok(())) => Ok(ret), + (Err(err), _) | (_, Err(err)) => Err(err), + } + } + b'{' => { + self.remaining_depth -= 1; + if self.remaining_depth == 0 { + return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); + } + + self.eat_char(); + let ret = visitor.visit_map(MapAccess::new(self)); + + self.remaining_depth += 1; + + match (ret, self.end_map()) { + (Ok(ret), Ok(())) => Ok(ret), + (Err(err), _) | (_, Err(err)) => Err(err), + } + } + _ => Err(self.peek_invalid_type(&visitor)), + }; + + match value { + Ok(value) => Ok(value), + Err(err) => Err(self.fix_position(err)), + } + } + + /// Parses an enum as an object like `{"$KEY":$VALUE}`, where $VALUE is either a straight + /// value, a `[..]`, or a `{..}`. + #[inline] + fn deserialize_enum<V>( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + match try!(self.parse_whitespace()) { + Some(b'{') => { + self.remaining_depth -= 1; + if self.remaining_depth == 0 { + return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); + } + + self.eat_char(); + let value = try!(visitor.visit_enum(VariantAccess::new(self))); + + self.remaining_depth += 1; + + match try!(self.parse_whitespace()) { + Some(b'}') => { + self.eat_char(); + Ok(value) + } + Some(_) => Err(self.error(ErrorCode::ExpectedSomeValue)), + None => Err(self.error(ErrorCode::EofWhileParsingObject)), + } + } + Some(b'"') => visitor.visit_enum(UnitVariantAccess::new(self)), + Some(_) => Err(self.peek_error(ErrorCode::ExpectedSomeValue)), + None => Err(self.peek_error(ErrorCode::EofWhileParsingValue)), + } + } + + fn deserialize_identifier<V>( + self, + visitor: V + ) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.deserialize_str(visitor) + } + + fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + try!(self.ignore_value()); + visitor.visit_unit() + } +} + +struct SeqAccess<'a, R: 'a> { + de: &'a mut Deserializer<R>, + first: bool, +} + +impl<'a, R: 'a> SeqAccess<'a, R> { + fn new(de: &'a mut Deserializer<R>) -> Self { + SeqAccess { + de: de, + first: true, + } + } +} + +impl<'de, 'a, R: Read<'de> + 'a> de::SeqAccess<'de> for SeqAccess<'a, R> { + type Error = Error; + + fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> + where + T: de::DeserializeSeed<'de>, + { + let peek = match try!(self.de.parse_whitespace()) { + Some(b']') => { + return Ok(None); + } + Some(b',') if !self.first => { + self.de.eat_char(); + try!(self.de.parse_whitespace()) + } + Some(b) => { + if self.first { + self.first = false; + Some(b) + } else { + return Err(self.de.peek_error(ErrorCode::ExpectedListCommaOrEnd)); + } + } + None => { + return Err(self.de.peek_error(ErrorCode::EofWhileParsingList)); + } + }; + + match peek { + Some(b']') => Err(self.de.peek_error(ErrorCode::TrailingComma)), + Some(_) => Ok(Some(try!(seed.deserialize(&mut *self.de)))), + None => Err(self.de.peek_error(ErrorCode::EofWhileParsingValue)), + } + } +} + +struct MapAccess<'a, R: 'a> { + de: &'a mut Deserializer<R>, + first: bool, +} + +impl<'a, R: 'a> MapAccess<'a, R> { + fn new(de: &'a mut Deserializer<R>) -> Self { + MapAccess { + de: de, + first: true, + } + } +} + +impl<'de, 'a, R: Read<'de> + 'a> de::MapAccess<'de> for MapAccess<'a, R> { + type Error = Error; + + fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> + where + K: de::DeserializeSeed<'de>, + { + let peek = match try!(self.de.parse_whitespace()) { + Some(b'}') => { + return Ok(None); + } + Some(b',') if !self.first => { + self.de.eat_char(); + try!(self.de.parse_whitespace()) + } + Some(b) => { + if self.first { + self.first = false; + Some(b) + } else { + return Err(self.de.peek_error(ErrorCode::ExpectedObjectCommaOrEnd)); + } + } + None => { + return Err(self.de.peek_error(ErrorCode::EofWhileParsingObject)); + } + }; + + match peek { + Some(b'"') => seed.deserialize(MapKey { de: &mut *self.de }).map(Some), + Some(b'}') => Err(self.de.peek_error(ErrorCode::TrailingComma)), + Some(_) => Err(self.de.peek_error(ErrorCode::KeyMustBeAString)), + None => Err(self.de.peek_error(ErrorCode::EofWhileParsingValue)), + } + } + + fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value> + where + V: de::DeserializeSeed<'de>, + { + try!(self.de.parse_object_colon()); + + seed.deserialize(&mut *self.de) + } +} + +struct VariantAccess<'a, R: 'a> { + de: &'a mut Deserializer<R>, +} + +impl<'a, R: 'a> VariantAccess<'a, R> { + fn new(de: &'a mut Deserializer<R>) -> Self { + VariantAccess { de: de } + } +} + +impl<'de, 'a, R: Read<'de> + 'a> de::EnumAccess<'de> for VariantAccess<'a, R> { + type Error = Error; + type Variant = Self; + + fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)> + where + V: de::DeserializeSeed<'de>, + { + let val = try!(seed.deserialize(&mut *self.de)); + try!(self.de.parse_object_colon()); + Ok((val, self)) + } +} + +impl<'de, 'a, R: Read<'de> + 'a> de::VariantAccess<'de> for VariantAccess<'a, R> { + type Error = Error; + + fn unit_variant(self) -> Result<()> { + de::Deserialize::deserialize(self.de) + } + + fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value> + where + T: de::DeserializeSeed<'de>, + { + seed.deserialize(self.de) + } + + fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + de::Deserializer::deserialize_seq(self.de, visitor) + } + + fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + de::Deserializer::deserialize_struct(self.de, "", fields, visitor) + } +} + +struct UnitVariantAccess<'a, R: 'a> { + de: &'a mut Deserializer<R>, +} + +impl<'a, R: 'a> UnitVariantAccess<'a, R> { + fn new(de: &'a mut Deserializer<R>) -> Self { + UnitVariantAccess { de: de } + } +} + +impl<'de, 'a, R: Read<'de> + 'a> de::EnumAccess<'de> for UnitVariantAccess<'a, R> { + type Error = Error; + type Variant = Self; + + fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)> + where + V: de::DeserializeSeed<'de>, + { + let variant = try!(seed.deserialize(&mut *self.de)); + Ok((variant, self)) + } +} + +impl<'de, 'a, R: Read<'de> + 'a> de::VariantAccess<'de> for UnitVariantAccess<'a, R> { + type Error = Error; + + fn unit_variant(self) -> Result<()> { + Ok(()) + } + + fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value> + where + T: de::DeserializeSeed<'de>, + { + Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant"),) + } + + fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"),) + } + + fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"),) + } +} + +/// Only deserialize from this after peeking a '"' byte! Otherwise it may +/// deserialize invalid JSON successfully. +struct MapKey<'a, R: 'a> { + de: &'a mut Deserializer<R>, +} + +macro_rules! deserialize_integer_key { + ($method:ident => $visit:ident) => { + fn $method<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.de.eat_char(); + self.de.str_buf.clear(); + let string = try!(self.de.read.parse_str(&mut self.de.str_buf)); + match (string.parse(), string) { + (Ok(integer), _) => visitor.$visit(integer), + (Err(_), Reference::Borrowed(s)) => visitor.visit_borrowed_str(s), + (Err(_), Reference::Copied(s)) => visitor.visit_str(s), + } + } + } +} + +impl<'de, 'a, R> de::Deserializer<'de> for MapKey<'a, R> +where + R: Read<'de>, +{ + type Error = Error; + + #[inline] + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.de.eat_char(); + self.de.str_buf.clear(); + match try!(self.de.read.parse_str(&mut self.de.str_buf)) { + Reference::Borrowed(s) => visitor.visit_borrowed_str(s), + Reference::Copied(s) => visitor.visit_str(s), + } + } + + deserialize_integer_key!(deserialize_i8 => visit_i8); + deserialize_integer_key!(deserialize_i16 => visit_i16); + deserialize_integer_key!(deserialize_i32 => visit_i32); + deserialize_integer_key!(deserialize_i64 => visit_i64); + deserialize_integer_key!(deserialize_u8 => visit_u8); + deserialize_integer_key!(deserialize_u16 => visit_u16); + deserialize_integer_key!(deserialize_u32 => visit_u32); + deserialize_integer_key!(deserialize_u64 => visit_u64); + + #[inline] + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + // Map keys cannot be null. + visitor.visit_some(self) + } + + #[inline] + fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + #[inline] + fn deserialize_enum<V>( + self, + name: &'static str, + variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.de.deserialize_enum(name, variants, visitor) + } + + #[inline] + fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.de.deserialize_bytes(visitor) + } + + #[inline] + fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> + where + V: de::Visitor<'de>, + { + self.de.deserialize_bytes(visitor) + } + + forward_to_deserialize_any! { + bool f32 f64 char str string unit unit_struct seq tuple tuple_struct map + struct identifier ignored_any + } +} + +////////////////////////////////////////////////////////////////////////////// + +/// Iterator that deserializes a stream into multiple JSON values. +/// +/// A stream deserializer can be created from any JSON deserializer using the +/// `Deserializer::into_iter` method. +/// +/// The data can consist of any JSON value. Values need to be a self-delineating value e.g. +/// arrays, objects, or strings, or be followed by whitespace or a self-delineating value. +/// +/// ```rust +/// extern crate serde_json; +/// +/// use serde_json::{Deserializer, Value}; +/// +/// fn main() { +/// let data = "{\"k\": 3}1\"cool\"\"stuff\" 3{} [0, 1, 2]"; +/// +/// let stream = Deserializer::from_str(data).into_iter::<Value>(); +/// +/// for value in stream { +/// println!("{}", value.unwrap()); +/// } +/// } +/// ``` +pub struct StreamDeserializer<'de, R, T> { + de: Deserializer<R>, + offset: usize, + output: PhantomData<T>, + lifetime: PhantomData<&'de ()>, +} + +impl<'de, R, T> StreamDeserializer<'de, R, T> +where + R: read::Read<'de>, + T: de::Deserialize<'de>, +{ + /// Create a JSON stream deserializer from one of the possible serde_json + /// input sources. + /// + /// Typically it is more convenient to use one of these methods instead: + /// + /// - Deserializer::from_str(...).into_iter() + /// - Deserializer::from_bytes(...).into_iter() + /// - Deserializer::from_reader(...).into_iter() + pub fn new(read: R) -> Self { + let offset = read.byte_offset(); + StreamDeserializer { + de: Deserializer::new(read), + offset: offset, + output: PhantomData, + lifetime: PhantomData, + } + } + + /// Returns the number of bytes so far deserialized into a successful `T`. + /// + /// If a stream deserializer returns an EOF error, new data can be joined to + /// `old_data[stream.byte_offset()..]` to try again. + /// + /// ```rust + /// let data = b"[0] [1] ["; + /// + /// let de = serde_json::Deserializer::from_slice(data); + /// let mut stream = de.into_iter::<Vec<i32>>(); + /// assert_eq!(0, stream.byte_offset()); + /// + /// println!("{:?}", stream.next()); // [0] + /// assert_eq!(3, stream.byte_offset()); + /// + /// println!("{:?}", stream.next()); // [1] + /// assert_eq!(7, stream.byte_offset()); + /// + /// println!("{:?}", stream.next()); // error + /// assert_eq!(8, stream.byte_offset()); + /// + /// // If err.is_eof(), can join the remaining data to new data and continue. + /// let remaining = &data[stream.byte_offset()..]; + /// ``` + /// + /// *Note:* In the future this method may be changed to return the number of + /// bytes so far deserialized into a successful T *or* syntactically valid + /// JSON skipped over due to a type error. See [serde-rs/json#70] for an + /// example illustrating this. + /// + /// [serde-rs/json#70]: https://github.com/serde-rs/json/issues/70 + pub fn byte_offset(&self) -> usize { + self.offset + } + + fn peek_end_of_value(&mut self) -> Result<()> { + match try!(self.de.peek()) { + Some(b' ') | Some(b'\n') | Some(b'\t') | Some(b'\r') | + Some(b'"') | Some(b'[') | Some(b']') | Some(b'{') | + Some(b'}') | Some(b',') | Some(b':') | None => Ok(()), + Some(_) => { + let pos = self.de.read.peek_position(); + Err(Error::syntax(ErrorCode::TrailingCharacters, pos.line, pos.column)) + }, + } + } +} + +impl<'de, R, T> Iterator for StreamDeserializer<'de, R, T> +where + R: Read<'de>, + T: de::Deserialize<'de>, +{ + type Item = Result<T>; + + fn next(&mut self) -> Option<Result<T>> { + // skip whitespaces, if any + // this helps with trailing whitespaces, since whitespaces between + // values are handled for us. + match self.de.parse_whitespace() { + Ok(None) => { + self.offset = self.de.read.byte_offset(); + None + } + Ok(Some(b)) => { + // If the value does not have a clear way to show the end of the value + // (like numbers, null, true etc.) we have to look for whitespace or + // the beginning of a self-delineated value. + let self_delineated_value = match b { + b'[' | b'"' | b'{' => true, + _ => false, + }; + self.offset = self.de.read.byte_offset(); + let result = de::Deserialize::deserialize(&mut self.de); + + Some(match result { + Ok(value) => { + self.offset = self.de.read.byte_offset(); + if self_delineated_value { + Ok(value) + } else { + self.peek_end_of_value().map(|_| value) + } + } + Err(e) => Err(e) + }) + } + Err(e) => Some(Err(e)) + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +fn from_trait<'de, R, T>(read: R) -> Result<T> +where + R: Read<'de>, + T: de::Deserialize<'de>, +{ + let mut de = Deserializer::new(read); + let value = try!(de::Deserialize::deserialize(&mut de)); + + // Make sure the whole stream has been consumed. + try!(de.end()); + Ok(value) +} + +/// Deserialize an instance of type `T` from an IO stream of JSON. +/// +/// # Errors +/// +/// This conversion can fail if the structure of the input does not match the +/// structure expected by `T`, for example if `T` is a struct type but the input +/// contains something other than a JSON map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the JSON map or some number is too big to fit in the expected primitive +/// type. +/// +/// ```rust +/// #[macro_use] +/// extern crate serde_derive; +/// +/// extern crate serde; +/// extern crate serde_json; +/// +/// use std::error::Error; +/// use std::fs::File; +/// use std::path::Path; +/// +/// #[derive(Deserialize, Debug)] +/// struct User { +/// fingerprint: String, +/// location: String, +/// } +/// +/// fn read_user_from_file<P: AsRef<Path>>(path: P) -> Result<User, Box<Error>> { +/// // Open the file in read-only mode. +/// let file = File::open(path)?; +/// +/// // Read the JSON contents of the file as an instance of `User`. +/// let u = serde_json::from_reader(file)?; +/// +/// // Return the `User`. +/// Ok(u) +/// } +/// +/// fn main() { +/// # } +/// # fn fake_main() { +/// let u = read_user_from_file("test.json").unwrap(); +/// println!("{:#?}", u); +/// } +/// ``` +pub fn from_reader<R, T>(rdr: R) -> Result<T> +where + R: io::Read, + T: de::DeserializeOwned, +{ + from_trait(read::IoRead::new(rdr)) +} + +/// Deserialize an instance of type `T` from bytes of JSON text. +/// +/// # Errors +/// +/// This conversion can fail if the structure of the input does not match the +/// structure expected by `T`, for example if `T` is a struct type but the input +/// contains something other than a JSON map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the JSON map or some number is too big to fit in the expected primitive +/// type. +/// +/// ```rust +/// #[macro_use] +/// extern crate serde_derive; +/// +/// extern crate serde; +/// extern crate serde_json; +/// +/// #[derive(Deserialize, Debug)] +/// struct User { +/// fingerprint: String, +/// location: String, +/// } +/// +/// fn main() { +/// // The type of `j` is `&[u8]` +/// let j = b"{ +/// \"fingerprint\": \"0xF9BA143B95FF6D82\", +/// \"location\": \"Menlo Park, CA\" +/// }"; +/// +/// let u: User = serde_json::from_slice(j).unwrap(); +/// println!("{:#?}", u); +/// } +/// ``` +pub fn from_slice<'a, T>(v: &'a [u8]) -> Result<T> +where + T: de::Deserialize<'a>, +{ + from_trait(read::SliceRead::new(v)) +} + +/// Deserialize an instance of type `T` from a string of JSON text. +/// +/// # Errors +/// +/// This conversion can fail if the structure of the input does not match the +/// structure expected by `T`, for example if `T` is a struct type but the input +/// contains something other than a JSON map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the JSON map or some number is too big to fit in the expected primitive +/// type. +/// +/// ```rust +/// #[macro_use] +/// extern crate serde_derive; +/// +/// extern crate serde; +/// extern crate serde_json; +/// +/// #[derive(Deserialize, Debug)] +/// struct User { +/// fingerprint: String, +/// location: String, +/// } +/// +/// fn main() { +/// // The type of `j` is `&str` +/// let j = "{ +/// \"fingerprint\": \"0xF9BA143B95FF6D82\", +/// \"location\": \"Menlo Park, CA\" +/// }"; +/// +/// let u: User = serde_json::from_str(j).unwrap(); +/// println!("{:#?}", u); +/// } +/// ``` +pub fn from_str<'a, T>(s: &'a str) -> Result<T> +where + T: de::Deserialize<'a>, +{ + from_trait(read::StrRead::new(s)) +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/error.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/error.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/error.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/error.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,429 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! When serializing or deserializing JSON goes wrong. + +use std::error; +use std::fmt::{self, Debug, Display}; +use std::io; +use std::result; + +use serde::de; +use serde::ser; + +/// This type represents all possible errors that can occur when serializing or +/// deserializing JSON data. +pub struct Error { + /// This `Box` allows us to keep the size of `Error` as small as possible. A + /// larger `Error` type was substantially slower due to all the functions + /// that pass around `Result<T, Error>`. + err: Box<ErrorImpl>, +} + +/// Alias for a `Result` with the error type `serde_json::Error`. +pub type Result<T> = result::Result<T, Error>; + +impl Error { + /// One-based line number at which the error was detected. + /// + /// Characters in the first line of the input (before the first newline + /// character) are in line 1. + pub fn line(&self) -> usize { + self.err.line + } + + /// One-based column number at which the error was detected. + /// + /// The first character in the input and any characters immediately + /// following a newline character are in column 1. + /// + /// Note that errors may occur in column 0, for example if a read from an IO + /// stream fails immediately following a previously read newline character. + pub fn column(&self) -> usize { + self.err.column + } + + /// Categorizes the cause of this error. + /// + /// - `Category::Io` - failure to read or write bytes on an IO stream + /// - `Category::Syntax` - input that is not syntactically valid JSON + /// - `Category::Data` - input data that is semantically incorrect + /// - `Category::Eof` - unexpected end of the input data + pub fn classify(&self) -> Category { + match self.err.code { + ErrorCode::Message(_) => Category::Data, + ErrorCode::Io(_) => Category::Io, + ErrorCode::EofWhileParsingList | + ErrorCode::EofWhileParsingObject | + ErrorCode::EofWhileParsingString | + ErrorCode::EofWhileParsingValue => Category::Eof, + ErrorCode::ExpectedColon | + ErrorCode::ExpectedListCommaOrEnd | + ErrorCode::ExpectedObjectCommaOrEnd | + ErrorCode::ExpectedObjectOrArray | + ErrorCode::ExpectedSomeIdent | + ErrorCode::ExpectedSomeValue | + ErrorCode::ExpectedSomeString | + ErrorCode::InvalidEscape | + ErrorCode::InvalidNumber | + ErrorCode::NumberOutOfRange | + ErrorCode::InvalidUnicodeCodePoint | + ErrorCode::ControlCharacterWhileParsingString | + ErrorCode::KeyMustBeAString | + ErrorCode::LoneLeadingSurrogateInHexEscape | + ErrorCode::TrailingComma | + ErrorCode::TrailingCharacters | + ErrorCode::UnexpectedEndOfHexEscape | + ErrorCode::RecursionLimitExceeded => Category::Syntax, + } + } + + /// Returns true if this error was caused by a failure to read or write + /// bytes on an IO stream. + pub fn is_io(&self) -> bool { + self.classify() == Category::Io + } + + /// Returns true if this error was caused by input that was not + /// syntactically valid JSON. + pub fn is_syntax(&self) -> bool { + self.classify() == Category::Syntax + } + + /// Returns true if this error was caused by input data that was + /// semantically incorrect. + /// + /// For example, JSON containing a number is semantically incorrect when the + /// type being deserialized into holds a String. + pub fn is_data(&self) -> bool { + self.classify() == Category::Data + } + + /// Returns true if this error was caused by prematurely reaching the end of + /// the input data. + /// + /// Callers that process streaming input may be interested in retrying the + /// deserialization once more data is available. + pub fn is_eof(&self) -> bool { + self.classify() == Category::Eof + } +} + +/// Categorizes the cause of a `serde_json::Error`. +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum Category { + /// The error was caused by a failure to read or write bytes on an IO + /// stream. + Io, + + /// The error was caused by input that was not syntactically valid JSON. + Syntax, + + /// The error was caused by input data that was semantically incorrect. + /// + /// For example, JSON containing a number is semantically incorrect when the + /// type being deserialized into holds a String. + Data, + + /// The error was caused by prematurely reaching the end of the input data. + /// + /// Callers that process streaming input may be interested in retrying the + /// deserialization once more data is available. + Eof, +} + +#[cfg_attr(feature = "cargo-clippy", allow(fallible_impl_from))] +impl From<Error> for io::Error { + /// Convert a `serde_json::Error` into an `io::Error`. + /// + /// JSON syntax and data errors are turned into `InvalidData` IO errors. + /// EOF errors are turned into `UnexpectedEof` IO errors. + /// + /// ```rust + /// use std::io; + /// + /// enum MyError { + /// Io(io::Error), + /// Json(serde_json::Error), + /// } + /// + /// impl From<serde_json::Error> for MyError { + /// fn from(err: serde_json::Error) -> MyError { + /// use serde_json::error::Category; + /// match err.classify() { + /// Category::Io => { + /// MyError::Io(err.into()) + /// } + /// Category::Syntax | Category::Data | Category::Eof => { + /// MyError::Json(err) + /// } + /// } + /// } + /// } + /// ``` + fn from(j: Error) -> Self { + if let ErrorCode::Io(err) = j.err.code { + err + } else { + match j.classify() { + Category::Io => unreachable!(), + Category::Syntax | Category::Data => io::Error::new(io::ErrorKind::InvalidData, j), + Category::Eof => io::Error::new(io::ErrorKind::UnexpectedEof, j), + } + } + } +} + +#[derive(Debug)] +struct ErrorImpl { + code: ErrorCode, + line: usize, + column: usize, +} + +// Not public API. Should be pub(crate). +#[doc(hidden)] +#[derive(Debug)] +pub enum ErrorCode { + /// Catchall for syntax error messages + Message(Box<str>), + + /// Some IO error occurred while serializing or deserializing. + Io(io::Error), + + /// EOF while parsing a list. + EofWhileParsingList, + + /// EOF while parsing an object. + EofWhileParsingObject, + + /// EOF while parsing a string. + EofWhileParsingString, + + /// EOF while parsing a JSON value. + EofWhileParsingValue, + + /// Expected this character to be a `':'`. + ExpectedColon, + + /// Expected this character to be either a `','` or a `']'`. + ExpectedListCommaOrEnd, + + /// Expected this character to be either a `','` or a `'}'`. + ExpectedObjectCommaOrEnd, + + /// Expected this character to be either a `'{'` or a `'['`. + ExpectedObjectOrArray, + + /// Expected to parse either a `true`, `false`, or a `null`. + ExpectedSomeIdent, + + /// Expected this character to start a JSON value. + ExpectedSomeValue, + + /// Expected this character to start a JSON string. + ExpectedSomeString, + + /// Invalid hex escape code. + InvalidEscape, + + /// Invalid number. + InvalidNumber, + + /// Number is bigger than the maximum value of its type. + NumberOutOfRange, + + /// Invalid unicode code point. + InvalidUnicodeCodePoint, + + /// Control character found while parsing a string. + ControlCharacterWhileParsingString, + + /// Object key is not a string. + KeyMustBeAString, + + /// Lone leading surrogate in hex escape. + LoneLeadingSurrogateInHexEscape, + + /// JSON has a comma after the last value in an array or map. + TrailingComma, + + /// JSON has non-whitespace trailing characters after the value. + TrailingCharacters, + + /// Unexpected end of hex excape. + UnexpectedEndOfHexEscape, + + /// Encountered nesting of JSON maps and arrays more than 128 layers deep. + RecursionLimitExceeded, +} + +impl Error { + // Not public API. Should be pub(crate). + #[doc(hidden)] + pub fn syntax(code: ErrorCode, line: usize, column: usize) -> Self { + Error { + err: Box::new( + ErrorImpl { + code: code, + line: line, + column: column, + }, + ), + } + } + + // Not public API. Should be pub(crate). + // + // Update `eager_json` crate when this function changes. + #[doc(hidden)] + pub fn io(error: io::Error) -> Self { + Error { + err: Box::new( + ErrorImpl { + code: ErrorCode::Io(error), + line: 0, + column: 0, + }, + ), + } + } + + // Not public API. Should be pub(crate). + #[doc(hidden)] + pub fn fix_position<F>(self, f: F) -> Self + where + F: FnOnce(ErrorCode) -> Error, + { + if self.err.line == 0 { + f(self.err.code) + } else { + self + } + } +} + +impl Display for ErrorCode { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + ErrorCode::Message(ref msg) => f.write_str(msg), + ErrorCode::Io(ref err) => Display::fmt(err, f), + ErrorCode::EofWhileParsingList => f.write_str("EOF while parsing a list"), + ErrorCode::EofWhileParsingObject => f.write_str("EOF while parsing an object"), + ErrorCode::EofWhileParsingString => f.write_str("EOF while parsing a string"), + ErrorCode::EofWhileParsingValue => f.write_str("EOF while parsing a value"), + ErrorCode::ExpectedColon => f.write_str("expected `:`"), + ErrorCode::ExpectedListCommaOrEnd => f.write_str("expected `,` or `]`"), + ErrorCode::ExpectedObjectCommaOrEnd => f.write_str("expected `,` or `}`"), + ErrorCode::ExpectedObjectOrArray => f.write_str("expected `{` or `[`"), + ErrorCode::ExpectedSomeIdent => f.write_str("expected ident"), + ErrorCode::ExpectedSomeValue => f.write_str("expected value"), + ErrorCode::ExpectedSomeString => f.write_str("expected string"), + ErrorCode::InvalidEscape => f.write_str("invalid escape"), + ErrorCode::InvalidNumber => f.write_str("invalid number"), + ErrorCode::NumberOutOfRange => f.write_str("number out of range"), + ErrorCode::InvalidUnicodeCodePoint => f.write_str("invalid unicode code point"), + ErrorCode::ControlCharacterWhileParsingString => { + f.write_str("control character (\\u0000-\\u001F) found while parsing a string") + } + ErrorCode::KeyMustBeAString => f.write_str("key must be a string"), + ErrorCode::LoneLeadingSurrogateInHexEscape => { + f.write_str("lone leading surrogate in hex escape") + } + ErrorCode::TrailingComma => f.write_str("trailing comma"), + ErrorCode::TrailingCharacters => f.write_str("trailing characters"), + ErrorCode::UnexpectedEndOfHexEscape => f.write_str("unexpected end of hex escape"), + ErrorCode::RecursionLimitExceeded => f.write_str("recursion limit exceeded"), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match self.err.code { + ErrorCode::Io(ref err) => error::Error::description(err), + _ => { + // If you want a better message, use Display::fmt or to_string(). + "JSON error" + } + } + } + + fn cause(&self) -> Option<&error::Error> { + match self.err.code { + ErrorCode::Io(ref err) => Some(err), + _ => None, + } + } +} + +impl Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&*self.err, f) + } +} + +impl Display for ErrorImpl { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if self.line == 0 { + Display::fmt(&self.code, f) + } else { + write!( + f, + "{} at line {} column {}", + self.code, + self.line, + self.column + ) + } + } +} + +// Remove two layers of verbosity from the debug representation. Humans often +// end up seeing this representation because it is what unwrap() shows. +impl Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&*self.err, f) + } +} + +impl de::Error for Error { + fn custom<T: Display>(msg: T) -> Error { + Error { + err: Box::new( + ErrorImpl { + code: ErrorCode::Message(msg.to_string().into_boxed_str()), + line: 0, + column: 0, + }, + ), + } + } + + fn invalid_type(unexp: de::Unexpected, exp: &de::Expected) -> Self { + if let de::Unexpected::Unit = unexp { + Error::custom(format_args!("invalid type: null, expected {}", exp)) + } else { + Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp)) + } + } +} + +impl ser::Error for Error { + fn custom<T: Display>(msg: T) -> Error { + Error { + err: Box::new( + ErrorImpl { + code: ErrorCode::Message(msg.to_string().into_boxed_str()), + line: 0, + column: 0, + }, + ), + } + } +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/iter.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/iter.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/iter.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/iter.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,78 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::io; + +pub struct LineColIterator<I> { + iter: I, + + /// Index of the current line. Characters in the first line of the input + /// (before the first newline character) are in line 1. + line: usize, + + /// Index of the current column. The first character in the input and any + /// characters immediately following a newline character are in column 1. + /// The column is 0 immediately after a newline character has been read. + col: usize, + + /// Byte offset of the start of the current line. This is the sum of lenghts + /// of all previous lines. Keeping track of things this way allows efficient + /// computation of the current line, column, and byte offset while only + /// updating one of the counters in `next()` in the common case. + start_of_line: usize, +} + +impl<I> LineColIterator<I> +where + I: Iterator<Item = io::Result<u8>>, +{ + pub fn new(iter: I) -> LineColIterator<I> { + LineColIterator { + iter: iter, + line: 1, + col: 0, + start_of_line: 0, + } + } + + pub fn line(&self) -> usize { + self.line + } + + pub fn col(&self) -> usize { + self.col + } + + pub fn byte_offset(&self) -> usize { + self.start_of_line + self.col + } +} + +impl<I> Iterator for LineColIterator<I> +where + I: Iterator<Item = io::Result<u8>>, +{ + type Item = io::Result<u8>; + + fn next(&mut self) -> Option<io::Result<u8>> { + match self.iter.next() { + None => None, + Some(Ok(b'\n')) => { + self.start_of_line += self.col + 1; + self.line += 1; + self.col = 0; + Some(Ok(b'\n')) + } + Some(Ok(c)) => { + self.col += 1; + Some(Ok(c)) + } + Some(Err(e)) => Some(Err(e)), + } + } +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/lib.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/lib.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,388 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! # Serde JSON +//! +//! JSON is a ubiquitous open-standard format that uses human-readable text to +//! transmit data objects consisting of key-value pairs. +//! +//! ```json,ignore +//! { +//! "name": "John Doe", +//! "age": 43, +//! "address": { +//! "street": "10 Downing Street", +//! "city": "London" +//! }, +//! "phones": [ +//! "+44 1234567", +//! "+44 2345678" +//! ] +//! } +//! ``` +//! +//! There are three common ways that you might find yourself needing to work +//! with JSON data in Rust. +//! +//! - **As text data.** An unprocessed string of JSON data that you receive on +//! an HTTP endpoint, read from a file, or prepare to send to a remote +//! server. +//! - **As an untyped or loosely typed representation.** Maybe you want to +//! check that some JSON data is valid before passing it on, but without +//! knowing the structure of what it contains. Or you want to do very basic +//! manipulations like insert a key in a particular spot. +//! - **As a strongly typed Rust data structure.** When you expect all or most +//! of your data to conform to a particular structure and want to get real +//! work done without JSON's loosey-goosey nature tripping you up. +//! +//! Serde JSON provides efficient, flexible, safe ways of converting data +//! between each of these representations. +//! +//! # Operating on untyped JSON values +//! +//! Any valid JSON data can be manipulated in the following recursive enum +//! representation. This data structure is [`serde_json::Value`][value]. +//! +//! ```rust +//! # use serde_json::{Number, Map}; +//! # +//! # #[allow(dead_code)] +//! enum Value { +//! Null, +//! Bool(bool), +//! Number(Number), +//! String(String), +//! Array(Vec<Value>), +//! Object(Map<String, Value>), +//! } +//! ``` +//! +//! A string of JSON data can be parsed into a `serde_json::Value` by the +//! [`serde_json::from_str`][from_str] function. There is also +//! [`from_slice`][from_slice] for parsing from a byte slice &[u8] and +//! [`from_reader`][from_reader] for parsing from any `io::Read` like a File or +//! a TCP stream. +//! +//! ```rust +//! extern crate serde_json; +//! +//! use serde_json::{Value, Error}; +//! +//! fn untyped_example() -> Result<(), Error> { +//! // Some JSON input data as a &str. Maybe this comes from the user. +//! let data = r#"{ +//! "name": "John Doe", +//! "age": 43, +//! "phones": [ +//! "+44 1234567", +//! "+44 2345678" +//! ] +//! }"#; +//! +//! // Parse the string of data into serde_json::Value. +//! let v: Value = serde_json::from_str(data)?; +//! +//! // Access parts of the data by indexing with square brackets. +//! println!("Please call {} at the number {}", v["name"], v["phones"][0]); +//! +//! Ok(()) +//! } +//! # +//! # fn main() { +//! # untyped_example().unwrap(); +//! # } +//! ``` +//! +//! The result of square bracket indexing like `v["name"]` is a borrow of the +//! data at that index, so the type is `&Value`. A JSON map can be indexed with +//! string keys, while a JSON array can be indexed with integer keys. If the +//! type of the data is not right for the type with which it is being indexed, +//! or if a map does not contain the key being indexed, or if the index into a +//! vector is out of bounds, the returned element is `Value::Null`. +//! +//! When a `Value` is printed, it is printed as a JSON string. So in the code +//! above, the output looks like `Please call "John Doe" at the number "+44 +//! 1234567"`. The quotation marks appear because `v["name"]` is a `&Value` +//! containing a JSON string and its JSON representation is `"John Doe"`. +//! Printing as a plain string without quotation marks involves converting from +//! a JSON string to a Rust string with [`as_str()`] or avoiding the use of +//! `Value` as described in the following section. +//! +//! [`as_str()`]: https://docs.serde.rs/serde_json/enum.Value.html#method.as_str +//! +//! The `Value` representation is sufficient for very basic tasks but can be +//! tedious to work with for anything more significant. Error handling is +//! verbose to implement correctly, for example imagine trying to detect the +//! presence of unrecognized fields in the input data. The compiler is powerless +//! to help you when you make a mistake, for example imagine typoing `v["name"]` +//! as `v["nmae"]` in one of the dozens of places it is used in your code. +//! +//! # Parsing JSON as strongly typed data structures +//! +//! Serde provides a powerful way of mapping JSON data into Rust data structures +//! largely automatically. +//! +//! ```rust +//! extern crate serde; +//! extern crate serde_json; +//! +//! #[macro_use] +//! extern crate serde_derive; +//! +//! use serde_json::Error; +//! +//! #[derive(Serialize, Deserialize)] +//! struct Person { +//! name: String, +//! age: u8, +//! phones: Vec<String>, +//! } +//! +//! fn typed_example() -> Result<(), Error> { +//! // Some JSON input data as a &str. Maybe this comes from the user. +//! let data = r#"{ +//! "name": "John Doe", +//! "age": 43, +//! "phones": [ +//! "+44 1234567", +//! "+44 2345678" +//! ] +//! }"#; +//! +//! // Parse the string of data into a Person object. This is exactly the +//! // same function as the one that produced serde_json::Value above, but +//! // now we are asking it for a Person as output. +//! let p: Person = serde_json::from_str(data)?; +//! +//! // Do things just like with any other Rust data structure. +//! println!("Please call {} at the number {}", p.name, p.phones[0]); +//! +//! Ok(()) +//! } +//! # +//! # fn main() { +//! # typed_example().unwrap(); +//! # } +//! ``` +//! +//! This is the same `serde_json::from_str` function as before, but this time we +//! assign the return value to a variable of type `Person` so Serde will +//! automatically interpret the input data as a `Person` and produce informative +//! error messages if the layout does not conform to what a `Person` is expected +//! to look like. +//! +//! Any type that implements Serde's `Deserialize` trait can be deserialized +//! this way. This includes built-in Rust standard library types like `Vec<T>` +//! and `HashMap<K, V>`, as well as any structs or enums annotated with +//! `#[derive(Deserialize)]`. +//! +//! Once we have `p` of type `Person`, our IDE and the Rust compiler can help us +//! use it correctly like they do for any other Rust code. The IDE can +//! autocomplete field names to prevent typos, which was impossible in the +//! `serde_json::Value` representation. And the Rust compiler can check that +//! when we write `p.phones[0]`, then `p.phones` is guaranteed to be a +//! `Vec<String>` so indexing into it makes sense and produces a `String`. +//! +//! # Constructing JSON values +//! +//! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` +//! objects with very natural JSON syntax. In order to use this macro, +//! `serde_json` needs to be imported with the `#[macro_use]` attribute. +//! +//! ```rust +//! #[macro_use] +//! extern crate serde_json; +//! +//! fn main() { +//! // The type of `john` is `serde_json::Value` +//! let john = json!({ +//! "name": "John Doe", +//! "age": 43, +//! "phones": [ +//! "+44 1234567", +//! "+44 2345678" +//! ] +//! }); +//! +//! println!("first phone number: {}", john["phones"][0]); +//! +//! // Convert to a string of JSON and print it out +//! println!("{}", john.to_string()); +//! } +//! ``` +//! +//! The `Value::to_string()` function converts a `serde_json::Value` into a +//! `String` of JSON text. +//! +//! One neat thing about the `json!` macro is that variables and expressions can +//! be interpolated directly into the JSON value as you are building it. Serde +//! will check at compile time that the value you are interpolating is able to +//! be represented as JSON. +//! +//! ```rust +//! # #[macro_use] +//! # extern crate serde_json; +//! # +//! # fn random_phone() -> u16 { 0 } +//! # +//! # fn main() { +//! let full_name = "John Doe"; +//! let age_last_year = 42; +//! +//! // The type of `john` is `serde_json::Value` +//! let john = json!({ +//! "name": full_name, +//! "age": age_last_year + 1, +//! "phones": [ +//! format!("+44 {}", random_phone()) +//! ] +//! }); +//! # let _ = john; +//! # } +//! ``` +//! +//! This is amazingly convenient but we have the problem we had before with +//! `Value` which is that the IDE and Rust compiler cannot help us if we get it +//! wrong. Serde JSON provides a better way of serializing strongly-typed data +//! structures into JSON text. +//! +//! # Creating JSON by serializing data structures +//! +//! A data structure can be converted to a JSON string by +//! [`serde_json::to_string`][to_string]. There is also +//! [`serde_json::to_vec`][to_vec] which serializes to a `Vec<u8>` and +//! [`serde_json::to_writer`][to_writer] which serializes to any `io::Write` +//! such as a File or a TCP stream. +//! +//! ```rust +//! extern crate serde; +//! extern crate serde_json; +//! +//! #[macro_use] +//! extern crate serde_derive; +//! +//! use serde_json::Error; +//! +//! #[derive(Serialize, Deserialize)] +//! struct Address { +//! street: String, +//! city: String, +//! } +//! +//! fn print_an_address() -> Result<(), Error> { +//! // Some data structure. +//! let address = Address { +//! street: "10 Downing Street".to_owned(), +//! city: "London".to_owned(), +//! }; +//! +//! // Serialize it to a JSON string. +//! let j = serde_json::to_string(&address)?; +//! +//! // Print, write to a file, or send to an HTTP server. +//! println!("{}", j); +//! +//! Ok(()) +//! } +//! # +//! # fn main() { +//! # print_an_address().unwrap(); +//! # } +//! ``` +//! +//! Any type that implements Serde's `Serialize` trait can be serialized this +//! way. This includes built-in Rust standard library types like `Vec<T>` and +//! `HashMap<K, V>`, as well as any structs or enums annotated with +//! `#[derive(Serialize)]`. +//! +//! [value]: https://docs.serde.rs/serde_json/value/enum.Value.html +//! [from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html +//! [from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html +//! [from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html +//! [to_string]: https://docs.serde.rs/serde_json/ser/fn.to_string.html +//! [to_vec]: https://docs.serde.rs/serde_json/ser/fn.to_vec.html +//! [to_writer]: https://docs.serde.rs/serde_json/ser/fn.to_writer.html +//! [macro]: https://docs.serde.rs/serde_json/macro.json.html + +#![doc(html_root_url = "https://docs.rs/serde_json/1.0.13")] +#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))] +// Whitelisted clippy lints +#![cfg_attr(feature = "cargo-clippy", allow( + doc_markdown, + needless_pass_by_value, +))] +// Whitelisted clippy_pedantic lints +#![cfg_attr(feature = "cargo-clippy", allow( +// Deserializer::from_str, into_iter + should_implement_trait, +// integer and float ser/de requires these sorts of casts + cast_possible_truncation, + cast_possible_wrap, + cast_precision_loss, + cast_sign_loss, +// string ser/de uses indexing and slicing + indexing_slicing, +// things are often more readable this way + cast_lossless, + shadow_reuse, + shadow_unrelated, + single_match_else, + stutter, + use_self, +// not practical + missing_docs_in_private_items, + similar_names, +// we support older compilers + redundant_field_names, +))] + +#![deny(missing_docs)] + +extern crate num_traits; +#[macro_use] +extern crate serde; +extern crate itoa; +extern crate dtoa; +#[cfg(feature = "preserve_order")] +extern crate linked_hash_map; + +#[doc(inline)] +pub use self::de::{Deserializer, StreamDeserializer, from_reader, from_slice, from_str}; +#[doc(inline)] +pub use self::error::{Error, Result}; +#[doc(inline)] +pub use self::ser::{Serializer, to_string, to_string_pretty, to_vec, to_vec_pretty, to_writer, + to_writer_pretty}; +#[doc(inline)] +pub use self::value::{Map, Number, Value, from_value, to_value}; + +// We only use our own error type; no need for From conversions provided by the +// standard library's try! macro. This reduces lines of LLVM IR by 4%. +macro_rules! try { + ($e:expr) => { + match $e { + ::std::result::Result::Ok(val) => val, + ::std::result::Result::Err(err) => { + return ::std::result::Result::Err(err) + } + } + } +} + +#[macro_use] +mod macros; + +pub mod de; +pub mod error; +pub mod map; +pub mod ser; +pub mod value; + +mod iter; +mod number; +mod read; diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/macros.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/macros.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/macros.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/macros.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,282 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +/// Construct a `serde_json::Value` from a JSON literal. +/// +/// ```rust +/// # #[macro_use] +/// # extern crate serde_json; +/// # +/// # fn main() { +/// let value = json!({ +/// "code": 200, +/// "success": true, +/// "payload": { +/// "features": [ +/// "serde", +/// "json" +/// ] +/// } +/// }); +/// # } +/// ``` +/// +/// Variables or expressions can be interpolated into the JSON literal. Any type +/// interpolated into an array element or object value must implement Serde's +/// `Serialize` trait, while any type interpolated into a object key must +/// implement `Into<String>`. If the `Serialize` implementation of the +/// interpolated type decides to fail, or if the interpolated type contains a +/// map with non-string keys, the `json!` macro will panic. +/// +/// ```rust +/// # #[macro_use] +/// # extern crate serde_json; +/// # +/// # fn main() { +/// let code = 200; +/// let features = vec!["serde", "json"]; +/// +/// let value = json!({ +/// "code": code, +/// "success": code == 200, +/// "payload": { +/// features[0]: features[1] +/// } +/// }); +/// # } +/// ``` +/// +/// Trailing commas are allowed inside both arrays and objects. +/// +/// ```rust +/// # #[macro_use] +/// # extern crate serde_json; +/// # +/// # fn main() { +/// let value = json!([ +/// "notice", +/// "the", +/// "trailing", +/// "comma -->", +/// ]); +/// # } +/// ``` +#[macro_export] +macro_rules! json { + // Hide distracting implementation details from the generated rustdoc. + ($($json:tt)+) => { + json_internal!($($json)+) + }; +} + +// Rocket relies on this because they export their own `json!` with a different +// doc comment than ours, and various Rust bugs prevent them from calling our +// `json!` from their `json!` so they call `json_internal!` directly. Check with +// @SergioBenitez before making breaking changes to this macro. +// +// Changes are fine as long as `json_internal!` does not call any new helper +// macros and can still be invoked as `json_internal!($($json)+)`. +#[macro_export] +#[doc(hidden)] +macro_rules! json_internal { + ////////////////////////////////////////////////////////////////////////// + // TT muncher for parsing the inside of an array [...]. Produces a vec![...] + // of the elements. + // + // Must be invoked as: json_internal!(@array [] $($tt)*) + ////////////////////////////////////////////////////////////////////////// + + // Done with trailing comma. + (@array [$($elems:expr,)*]) => { + vec![$($elems,)*] + }; + + // Done without trailing comma. + (@array [$($elems:expr),*]) => { + vec![$($elems),*] + }; + + // Next element is `null`. + (@array [$($elems:expr,)*] null $($rest:tt)*) => { + json_internal!(@array [$($elems,)* json_internal!(null)] $($rest)*) + }; + + // Next element is `true`. + (@array [$($elems:expr,)*] true $($rest:tt)*) => { + json_internal!(@array [$($elems,)* json_internal!(true)] $($rest)*) + }; + + // Next element is `false`. + (@array [$($elems:expr,)*] false $($rest:tt)*) => { + json_internal!(@array [$($elems,)* json_internal!(false)] $($rest)*) + }; + + // Next element is an array. + (@array [$($elems:expr,)*] [$($array:tt)*] $($rest:tt)*) => { + json_internal!(@array [$($elems,)* json_internal!([$($array)*])] $($rest)*) + }; + + // Next element is a map. + (@array [$($elems:expr,)*] {$($map:tt)*} $($rest:tt)*) => { + json_internal!(@array [$($elems,)* json_internal!({$($map)*})] $($rest)*) + }; + + // Next element is an expression followed by comma. + (@array [$($elems:expr,)*] $next:expr, $($rest:tt)*) => { + json_internal!(@array [$($elems,)* json_internal!($next),] $($rest)*) + }; + + // Last element is an expression with no trailing comma. + (@array [$($elems:expr,)*] $last:expr) => { + json_internal!(@array [$($elems,)* json_internal!($last)]) + }; + + // Comma after the most recent element. + (@array [$($elems:expr),*] , $($rest:tt)*) => { + json_internal!(@array [$($elems,)*] $($rest)*) + }; + + ////////////////////////////////////////////////////////////////////////// + // TT muncher for parsing the inside of an object {...}. Each entry is + // inserted into the given map variable. + // + // Must be invoked as: json_internal!(@object $map () ($($tt)*) ($($tt)*)) + // + // We require two copies of the input tokens so that we can match on one + // copy and trigger errors on the other copy. + ////////////////////////////////////////////////////////////////////////// + + // Done. + (@object $object:ident () () ()) => {}; + + // Insert the current entry followed by trailing comma. + (@object $object:ident [$($key:tt)+] ($value:expr) , $($rest:tt)*) => { + $object.insert(($($key)+).into(), $value); + json_internal!(@object $object () ($($rest)*) ($($rest)*)); + }; + + // Insert the last entry without trailing comma. + (@object $object:ident [$($key:tt)+] ($value:expr)) => { + $object.insert(($($key)+).into(), $value); + }; + + // Next value is `null`. + (@object $object:ident ($($key:tt)+) (: null $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!(null)) $($rest)*); + }; + + // Next value is `true`. + (@object $object:ident ($($key:tt)+) (: true $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!(true)) $($rest)*); + }; + + // Next value is `false`. + (@object $object:ident ($($key:tt)+) (: false $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!(false)) $($rest)*); + }; + + // Next value is an array. + (@object $object:ident ($($key:tt)+) (: [$($array:tt)*] $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!([$($array)*])) $($rest)*); + }; + + // Next value is a map. + (@object $object:ident ($($key:tt)+) (: {$($map:tt)*} $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!({$($map)*})) $($rest)*); + }; + + // Next value is an expression followed by comma. + (@object $object:ident ($($key:tt)+) (: $value:expr , $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!($value)) , $($rest)*); + }; + + // Last value is an expression with no trailing comma. + (@object $object:ident ($($key:tt)+) (: $value:expr) $copy:tt) => { + json_internal!(@object $object [$($key)+] (json_internal!($value))); + }; + + // Missing value for last entry. Trigger a reasonable error message. + (@object $object:ident ($($key:tt)+) (:) $copy:tt) => { + // "unexpected end of macro invocation" + json_internal!(); + }; + + // Missing colon and value for last entry. Trigger a reasonable error + // message. + (@object $object:ident ($($key:tt)+) () $copy:tt) => { + // "unexpected end of macro invocation" + json_internal!(); + }; + + // Misplaced colon. Trigger a reasonable error message. + (@object $object:ident () (: $($rest:tt)*) ($colon:tt $($copy:tt)*)) => { + // Takes no arguments so "no rules expected the token `:`". + unimplemented!($colon); + }; + + // Found a comma inside a key. Trigger a reasonable error message. + (@object $object:ident ($($key:tt)*) (, $($rest:tt)*) ($comma:tt $($copy:tt)*)) => { + // Takes no arguments so "no rules expected the token `,`". + unimplemented!($comma); + }; + + // Key is fully parenthesized. This avoids clippy double_parens false + // positives because the parenthesization may be necessary here. + (@object $object:ident () (($key:expr) : $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object ($key) (: $($rest)*) (: $($rest)*)); + }; + + // Munch a token into the current key. + (@object $object:ident ($($key:tt)*) ($tt:tt $($rest:tt)*) $copy:tt) => { + json_internal!(@object $object ($($key)* $tt) ($($rest)*) ($($rest)*)); + }; + + ////////////////////////////////////////////////////////////////////////// + // The main implementation. + // + // Must be invoked as: json_internal!($($json)+) + ////////////////////////////////////////////////////////////////////////// + + (null) => { + $crate::Value::Null + }; + + (true) => { + $crate::Value::Bool(true) + }; + + (false) => { + $crate::Value::Bool(false) + }; + + ([]) => { + $crate::Value::Array(vec![]) + }; + + ([ $($tt:tt)+ ]) => { + $crate::Value::Array(json_internal!(@array [] $($tt)+)) + }; + + ({}) => { + $crate::Value::Object($crate::Map::new()) + }; + + ({ $($tt:tt)+ }) => { + $crate::Value::Object({ + let mut object = $crate::Map::new(); + json_internal!(@object object () ($($tt)+) ($($tt)+)); + object + }) + }; + + // Any Serialize type: numbers, strings, struct literals, variables etc. + // Must be below every other rule. + ($other:expr) => { + $crate::to_value(&$other).unwrap() + }; +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/map.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/map.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/map.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/map.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,796 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A map of String to serde_json::Value. +//! +//! By default the map is backed by a [`BTreeMap`]. Enable the `preserve_order` +//! feature of serde_json to use [`LinkedHashMap`] instead. +//! +//! [`BTreeMap`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html +//! [`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html + +use serde::{ser, de}; +use std::fmt::{self, Debug}; +use value::Value; +use std::hash::Hash; +use std::iter::FromIterator; +use std::borrow::Borrow; +use std::ops; + +#[cfg(not(feature = "preserve_order"))] +use std::collections::{BTreeMap, btree_map}; + +#[cfg(feature = "preserve_order")] +use linked_hash_map::{self, LinkedHashMap}; + +/// Represents a JSON key/value type. +pub struct Map<K, V> { + map: MapImpl<K, V>, +} + +#[cfg(not(feature = "preserve_order"))] +type MapImpl<K, V> = BTreeMap<K, V>; +#[cfg(feature = "preserve_order")] +type MapImpl<K, V> = LinkedHashMap<K, V>; + +impl Map<String, Value> { + /// Makes a new empty Map. + #[inline] + pub fn new() -> Self { + Map { map: MapImpl::new() } + } + + #[cfg(not(feature = "preserve_order"))] + /// Makes a new empty Map with the given initial capacity. + #[inline] + pub fn with_capacity(capacity: usize) -> Self { + // does not support with_capacity + let _ = capacity; + Map { map: BTreeMap::new() } + } + + #[cfg(feature = "preserve_order")] + /// Makes a new empty Map with the given initial capacity. + #[inline] + pub fn with_capacity(capacity: usize) -> Self { + Map { map: LinkedHashMap::with_capacity(capacity) } + } + + /// Clears the map, removing all values. + #[inline] + pub fn clear(&mut self) { + self.map.clear() + } + + /// Returns a reference to the value corresponding to the key. + /// + /// The key may be any borrowed form of the map's key type, but the ordering + /// on the borrowed form *must* match the ordering on the key type. + #[inline] + pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&Value> + where + String: Borrow<Q>, + Q: Ord + Eq + Hash, + { + self.map.get(key) + } + + /// Returns true if the map contains a value for the specified key. + /// + /// The key may be any borrowed form of the map's key type, but the ordering + /// on the borrowed form *must* match the ordering on the key type. + #[inline] + pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool + where + String: Borrow<Q>, + Q: Ord + Eq + Hash, + { + self.map.contains_key(key) + } + + /// Returns a mutable reference to the value corresponding to the key. + /// + /// The key may be any borrowed form of the map's key type, but the ordering + /// on the borrowed form *must* match the ordering on the key type. + #[inline] + pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut Value> + where + String: Borrow<Q>, + Q: Ord + Eq + Hash, + { + self.map.get_mut(key) + } + + /// Inserts a key-value pair into the map. + /// + /// If the map did not have this key present, `None` is returned. + /// + /// If the map did have this key present, the value is updated, and the old + /// value is returned. The key is not updated, though; this matters for + /// types that can be `==` without being identical. + #[inline] + pub fn insert(&mut self, k: String, v: Value) -> Option<Value> { + self.map.insert(k, v) + } + + /// Removes a key from the map, returning the value at the key if the key + /// was previously in the map. + /// + /// The key may be any borrowed form of the map's key type, but the ordering + /// on the borrowed form *must* match the ordering on the key type. + #[inline] + pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<Value> + where + String: Borrow<Q>, + Q: Ord + Eq + Hash, + { + self.map.remove(key) + } + + /// Gets the given key's corresponding entry in the map for in-place + /// manipulation. + pub fn entry<S>(&mut self, key: S) -> Entry + where + S: Into<String>, + { + #[cfg(not(feature = "preserve_order"))] + use std::collections::btree_map::Entry as EntryImpl; + #[cfg(feature = "preserve_order")] + use linked_hash_map::Entry as EntryImpl; + + match self.map.entry(key.into()) { + EntryImpl::Vacant(vacant) => Entry::Vacant(VacantEntry { vacant: vacant }), + EntryImpl::Occupied(occupied) => Entry::Occupied(OccupiedEntry { occupied: occupied }), + } + } + + /// Returns the number of elements in the map. + #[inline] + pub fn len(&self) -> usize { + self.map.len() + } + + /// Returns true if the map contains no elements. + #[inline] + pub fn is_empty(&self) -> bool { + self.map.is_empty() + } + + /// Gets an iterator over the entries of the map. + #[inline] + pub fn iter(&self) -> Iter { + Iter { iter: self.map.iter() } + } + + /// Gets a mutable iterator over the entries of the map. + #[inline] + pub fn iter_mut(&mut self) -> IterMut { + IterMut { iter: self.map.iter_mut() } + } + + /// Gets an iterator over the keys of the map. + #[inline] + pub fn keys(&self) -> Keys { + Keys { iter: self.map.keys() } + } + + /// Gets an iterator over the values of the map. + #[inline] + pub fn values(&self) -> Values { + Values { iter: self.map.values() } + } +} + +impl Default for Map<String, Value> { + #[inline] + fn default() -> Self { + Map { map: MapImpl::new() } + } +} + +impl Clone for Map<String, Value> { + #[inline] + fn clone(&self) -> Self { + Map { map: self.map.clone() } + } +} + +impl PartialEq for Map<String, Value> { + #[inline] + fn eq(&self, other: &Self) -> bool { + self.map.eq(&other.map) + } +} + +/// Access an element of this map. Panics if the given key is not present in the +/// map. +/// +/// ```rust +/// # use serde_json::Value; +/// # +/// # let val = &Value::String("".to_owned()); +/// # let _ = +/// match *val { +/// Value::String(ref s) => Some(s.as_str()), +/// Value::Array(ref arr) => arr[0].as_str(), +/// Value::Object(ref map) => map["type"].as_str(), +/// _ => None, +/// } +/// # ; +/// ``` +impl<'a, Q: ?Sized> ops::Index<&'a Q> for Map<String, Value> +where + String: Borrow<Q>, + Q: Ord + Eq + Hash, +{ + type Output = Value; + + fn index(&self, index: &Q) -> &Value { + self.map.index(index) + } +} + +/// Mutably access an element of this map. Panics if the given key is not +/// present in the map. +/// +/// ```rust +/// # #[macro_use] +/// # extern crate serde_json; +/// # +/// # fn main() { +/// # let mut map = serde_json::Map::new(); +/// # map.insert("key".to_owned(), serde_json::Value::Null); +/// # +/// map["key"] = json!("value"); +/// # } +/// ``` +impl<'a, Q: ?Sized> ops::IndexMut<&'a Q> for Map<String, Value> +where + String: Borrow<Q>, + Q: Ord + Eq + Hash, +{ + fn index_mut(&mut self, index: &Q) -> &mut Value { + self.map.get_mut(index).expect("no entry found for key") + } +} + +impl Debug for Map<String, Value> { + #[inline] + fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + self.map.fmt(formatter) + } +} + +impl ser::Serialize for Map<String, Value> { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: ser::Serializer, + { + use serde::ser::SerializeMap; + let mut map = try!(serializer.serialize_map(Some(self.len()))); + for (k, v) in self { + try!(map.serialize_key(k)); + try!(map.serialize_value(v)); + } + map.end() + } +} + +impl<'de> de::Deserialize<'de> for Map<String, Value> { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: de::Deserializer<'de>, + { + struct Visitor; + + impl<'de> de::Visitor<'de> for Visitor { + type Value = Map<String, Value>; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a map") + } + + #[inline] + fn visit_unit<E>(self) -> Result<Self::Value, E> + where + E: de::Error, + { + Ok(Map::new()) + } + + #[inline] + fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> + where + V: de::MapAccess<'de>, + { + let mut values = Map::new(); + + while let Some((key, value)) = try!(visitor.next_entry()) { + values.insert(key, value); + } + + Ok(values) + } + } + + deserializer.deserialize_map(Visitor) + } +} + +impl FromIterator<(String, Value)> for Map<String, Value> { + fn from_iter<T>(iter: T) -> Self + where + T: IntoIterator<Item = (String, Value)>, + { + Map { map: FromIterator::from_iter(iter) } + } +} + +impl Extend<(String, Value)> for Map<String, Value> { + fn extend<T>(&mut self, iter: T) + where + T: IntoIterator<Item = (String, Value)>, + { + self.map.extend(iter); + } +} + +macro_rules! delegate_iterator { + (($name:ident $($generics:tt)*) => $item:ty) => { + impl $($generics)* Iterator for $name $($generics)* { + type Item = $item; + #[inline] + fn next(&mut self) -> Option<Self::Item> { + self.iter.next() + } + #[inline] + fn size_hint(&self) -> (usize, Option<usize>) { + self.iter.size_hint() + } + } + + impl $($generics)* DoubleEndedIterator for $name $($generics)* { + #[inline] + fn next_back(&mut self) -> Option<Self::Item> { + self.iter.next_back() + } + } + + impl $($generics)* ExactSizeIterator for $name $($generics)* { + #[inline] + fn len(&self) -> usize { + self.iter.len() + } + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +/// A view into a single entry in a map, which may either be vacant or occupied. +/// This enum is constructed from the [`entry`] method on [`Map`]. +/// +/// [`entry`]: struct.Map.html#method.entry +/// [`Map`]: struct.Map.html +pub enum Entry<'a> { + /// A vacant Entry. + Vacant(VacantEntry<'a>), + /// An occupied Entry. + Occupied(OccupiedEntry<'a>), +} + +/// A vacant Entry. It is part of the [`Entry`] enum. +/// +/// [`Entry`]: enum.Entry.html +pub struct VacantEntry<'a> { + vacant: VacantEntryImpl<'a>, +} + +/// An occupied Entry. It is part of the [`Entry`] enum. +/// +/// [`Entry`]: enum.Entry.html +pub struct OccupiedEntry<'a> { + occupied: OccupiedEntryImpl<'a>, +} + +#[cfg(not(feature = "preserve_order"))] +type VacantEntryImpl<'a> = btree_map::VacantEntry<'a, String, Value>; +#[cfg(feature = "preserve_order")] +type VacantEntryImpl<'a> = linked_hash_map::VacantEntry<'a, String, Value>; + +#[cfg(not(feature = "preserve_order"))] +type OccupiedEntryImpl<'a> = btree_map::OccupiedEntry<'a, String, Value>; +#[cfg(feature = "preserve_order")] +type OccupiedEntryImpl<'a> = linked_hash_map::OccupiedEntry<'a, String, Value>; + +impl<'a> Entry<'a> { + /// Returns a reference to this entry's key. + /// + /// # Examples + /// + /// ```rust + /// let mut map = serde_json::Map::new(); + /// assert_eq!(map.entry("serde").key(), &"serde"); + /// ``` + pub fn key(&self) -> &String { + match *self { + Entry::Vacant(ref e) => e.key(), + Entry::Occupied(ref e) => e.key(), + } + } + + /// Ensures a value is in the entry by inserting the default if empty, and + /// returns a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let mut map = serde_json::Map::new(); + /// map.entry("serde").or_insert(json!(12)); + /// + /// assert_eq!(map["serde"], 12); + /// # } + /// ``` + pub fn or_insert(self, default: Value) -> &'a mut Value { + match self { + Entry::Vacant(entry) => entry.insert(default), + Entry::Occupied(entry) => entry.into_mut(), + } + } + + /// Ensures a value is in the entry by inserting the result of the default + /// function if empty, and returns a mutable reference to the value in the + /// entry. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let mut map = serde_json::Map::new(); + /// map.entry("serde").or_insert_with(|| json!("hoho")); + /// + /// assert_eq!(map["serde"], "hoho".to_owned()); + /// # } + /// ``` + pub fn or_insert_with<F>(self, default: F) -> &'a mut Value + where + F: FnOnce() -> Value, + { + match self { + Entry::Vacant(entry) => entry.insert(default()), + Entry::Occupied(entry) => entry.into_mut(), + } + } +} + +impl<'a> VacantEntry<'a> { + /// Gets a reference to the key that would be used when inserting a value + /// through the VacantEntry. + /// + /// # Examples + /// + /// ```rust + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// + /// match map.entry("serde") { + /// Entry::Vacant(vacant) => { + /// assert_eq!(vacant.key(), &"serde"); + /// } + /// Entry::Occupied(_) => unimplemented!(), + /// } + /// ``` + #[inline] + pub fn key(&self) -> &String { + self.vacant.key() + } + + /// Sets the value of the entry with the VacantEntry's key, and returns a + /// mutable reference to it. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// + /// match map.entry("serde") { + /// Entry::Vacant(vacant) => { + /// vacant.insert(json!("hoho")); + /// } + /// Entry::Occupied(_) => unimplemented!(), + /// } + /// # } + /// ``` + #[inline] + pub fn insert(self, value: Value) -> &'a mut Value { + self.vacant.insert(value) + } +} + +impl<'a> OccupiedEntry<'a> { + /// Gets a reference to the key in the entry. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// map.insert("serde".to_owned(), json!(12)); + /// + /// match map.entry("serde") { + /// Entry::Occupied(occupied) => { + /// assert_eq!(occupied.key(), &"serde"); + /// } + /// Entry::Vacant(_) => unimplemented!(), + /// } + /// # } + /// ``` + #[inline] + pub fn key(&self) -> &String { + self.occupied.key() + } + + /// Gets a reference to the value in the entry. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// map.insert("serde".to_owned(), json!(12)); + /// + /// match map.entry("serde") { + /// Entry::Occupied(occupied) => { + /// assert_eq!(occupied.get(), 12); + /// } + /// Entry::Vacant(_) => unimplemented!(), + /// } + /// # } + /// ``` + #[inline] + pub fn get(&self) -> &Value { + self.occupied.get() + } + + /// Gets a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// map.insert("serde".to_owned(), json!([1, 2, 3])); + /// + /// match map.entry("serde") { + /// Entry::Occupied(mut occupied) => { + /// occupied.get_mut().as_array_mut().unwrap().push(json!(4)); + /// } + /// Entry::Vacant(_) => unimplemented!(), + /// } + /// + /// assert_eq!(map["serde"].as_array().unwrap().len(), 4); + /// # } + /// ``` + #[inline] + pub fn get_mut(&mut self) -> &mut Value { + self.occupied.get_mut() + } + + /// Converts the entry into a mutable reference to its value. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// map.insert("serde".to_owned(), json!([1, 2, 3])); + /// + /// match map.entry("serde") { + /// Entry::Occupied(mut occupied) => { + /// occupied.into_mut().as_array_mut().unwrap().push(json!(4)); + /// } + /// Entry::Vacant(_) => unimplemented!(), + /// } + /// + /// assert_eq!(map["serde"].as_array().unwrap().len(), 4); + /// # } + /// ``` + #[inline] + pub fn into_mut(self) -> &'a mut Value { + self.occupied.into_mut() + } + + /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns + /// the entry's old value. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// map.insert("serde".to_owned(), json!(12)); + /// + /// match map.entry("serde") { + /// Entry::Occupied(mut occupied) => { + /// assert_eq!(occupied.insert(json!(13)), 12); + /// assert_eq!(occupied.get(), 13); + /// } + /// Entry::Vacant(_) => unimplemented!(), + /// } + /// # } + /// ``` + #[inline] + pub fn insert(&mut self, value: Value) -> Value { + self.occupied.insert(value) + } + + /// Takes the value of the entry out of the map, and returns it. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::map::Entry; + /// + /// let mut map = serde_json::Map::new(); + /// map.insert("serde".to_owned(), json!(12)); + /// + /// match map.entry("serde") { + /// Entry::Occupied(occupied) => { + /// assert_eq!(occupied.remove(), 12); + /// } + /// Entry::Vacant(_) => unimplemented!(), + /// } + /// # } + /// ``` + #[inline] + pub fn remove(self) -> Value { + self.occupied.remove() + } +} + +////////////////////////////////////////////////////////////////////////////// + +impl<'a> IntoIterator for &'a Map<String, Value> { + type Item = (&'a String, &'a Value); + type IntoIter = Iter<'a>; + #[inline] + fn into_iter(self) -> Self::IntoIter { + Iter { iter: self.map.iter() } + } +} + +/// An iterator over a serde_json::Map's entries. +pub struct Iter<'a> { + iter: IterImpl<'a>, +} + +#[cfg(not(feature = "preserve_order"))] +type IterImpl<'a> = btree_map::Iter<'a, String, Value>; +#[cfg(feature = "preserve_order")] +type IterImpl<'a> = linked_hash_map::Iter<'a, String, Value>; + +delegate_iterator!((Iter<'a>) => (&'a String, &'a Value)); + +////////////////////////////////////////////////////////////////////////////// + +impl<'a> IntoIterator for &'a mut Map<String, Value> { + type Item = (&'a String, &'a mut Value); + type IntoIter = IterMut<'a>; + #[inline] + fn into_iter(self) -> Self::IntoIter { + IterMut { iter: self.map.iter_mut() } + } +} + +/// A mutable iterator over a serde_json::Map's entries. +pub struct IterMut<'a> { + iter: IterMutImpl<'a>, +} + +#[cfg(not(feature = "preserve_order"))] +type IterMutImpl<'a> = btree_map::IterMut<'a, String, Value>; +#[cfg(feature = "preserve_order")] +type IterMutImpl<'a> = linked_hash_map::IterMut<'a, String, Value>; + +delegate_iterator!((IterMut<'a>) => (&'a String, &'a mut Value)); + +////////////////////////////////////////////////////////////////////////////// + +impl IntoIterator for Map<String, Value> { + type Item = (String, Value); + type IntoIter = IntoIter; + #[inline] + fn into_iter(self) -> Self::IntoIter { + IntoIter { iter: self.map.into_iter() } + } +} + +/// An owning iterator over a serde_json::Map's entries. +pub struct IntoIter { + iter: IntoIterImpl, +} + +#[cfg(not(feature = "preserve_order"))] +type IntoIterImpl = btree_map::IntoIter<String, Value>; +#[cfg(feature = "preserve_order")] +type IntoIterImpl = linked_hash_map::IntoIter<String, Value>; + +delegate_iterator!((IntoIter) => (String, Value)); + +////////////////////////////////////////////////////////////////////////////// + +/// An iterator over a serde_json::Map's keys. +pub struct Keys<'a> { + iter: KeysImpl<'a>, +} + +#[cfg(not(feature = "preserve_order"))] +type KeysImpl<'a> = btree_map::Keys<'a, String, Value>; +#[cfg(feature = "preserve_order")] +type KeysImpl<'a> = linked_hash_map::Keys<'a, String, Value>; + +delegate_iterator!((Keys<'a>) => &'a String); + +////////////////////////////////////////////////////////////////////////////// + +/// An iterator over a serde_json::Map's values. +pub struct Values<'a> { + iter: ValuesImpl<'a>, +} + +#[cfg(not(feature = "preserve_order"))] +type ValuesImpl<'a> = btree_map::Values<'a, String, Value>; +#[cfg(feature = "preserve_order")] +type ValuesImpl<'a> = linked_hash_map::Values<'a, String, Value>; + +delegate_iterator!((Values<'a>) => &'a Value); diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/number.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/number.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/number.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/number.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,757 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use error::Error; +use serde::de::{self, Visitor, Unexpected}; +use serde::{Serialize, Serializer, Deserialize, Deserializer}; +use std::fmt::{self, Debug, Display}; +use std::i64; +use std::str::FromStr; + +#[cfg(not(feature = "arbitrary_precision"))] +use num_traits::{NumCast}; + +#[cfg(feature = "arbitrary_precision")] +use dtoa; +#[cfg(feature = "arbitrary_precision")] +use itoa; +#[cfg(feature = "arbitrary_precision")] +use serde::de::{IntoDeserializer, MapAccess}; + +#[cfg(feature = "arbitrary_precision")] +use error::{ErrorCode}; + +#[cfg(feature = "arbitrary_precision")] +/// Not public API. Should be pub(crate). +#[doc(hidden)] +pub const SERDE_STRUCT_FIELD_NAME: &'static str = "$__serde_private_number"; + +#[cfg(feature = "arbitrary_precision")] +/// Not public API. Should be pub(crate). +#[doc(hidden)] +pub const SERDE_STRUCT_NAME: &'static str = "$__serde_private_Number"; + +/// Represents a JSON number, whether integer or floating point. +#[derive(Clone, PartialEq)] +pub struct Number { + n: N, +} + +#[cfg(not(feature = "arbitrary_precision"))] +#[derive(Copy, Clone, PartialEq)] +enum N { + PosInt(u64), + /// Always less than zero. + NegInt(i64), + /// Always finite. + Float(f64), +} + +#[cfg(feature = "arbitrary_precision")] +type N = String; + +impl Number { + /// Returns true if the `Number` is an integer between `i64::MIN` and + /// `i64::MAX`. + /// + /// For any Number on which `is_i64` returns true, `as_i64` is guaranteed to + /// return the integer value. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # use std::i64; + /// # + /// # fn main() { + /// let big = i64::MAX as u64 + 10; + /// let v = json!({ "a": 64, "b": big, "c": 256.0 }); + /// + /// assert!(v["a"].is_i64()); + /// + /// // Greater than i64::MAX. + /// assert!(!v["b"].is_i64()); + /// + /// // Numbers with a decimal point are not considered integers. + /// assert!(!v["c"].is_i64()); + /// # } + /// ``` + #[inline] + pub fn is_i64(&self) -> bool { + #[cfg(not(feature = "arbitrary_precision"))] + match self.n { + N::PosInt(v) => v <= i64::max_value() as u64, + N::NegInt(_) => true, + N::Float(_) => false, + } + #[cfg(feature = "arbitrary_precision")] + self.as_i64().is_some() + } + + /// Returns true if the `Number` is an integer between zero and `u64::MAX`. + /// + /// For any Number on which `is_u64` returns true, `as_u64` is guaranteed to + /// return the integer value. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": 64, "b": -64, "c": 256.0 }); + /// + /// assert!(v["a"].is_u64()); + /// + /// // Negative integer. + /// assert!(!v["b"].is_u64()); + /// + /// // Numbers with a decimal point are not considered integers. + /// assert!(!v["c"].is_u64()); + /// # } + /// ``` + #[inline] + pub fn is_u64(&self) -> bool { + #[cfg(not(feature = "arbitrary_precision"))] + match self.n { + N::PosInt(_) => true, + N::NegInt(_) | N::Float(_) => false, + } + #[cfg(feature = "arbitrary_precision")] + self.as_u64().is_some() + } + + /// Returns true if the `Number` can be represented by f64. + /// + /// For any Number on which `is_f64` returns true, `as_f64` is guaranteed to + /// return the floating point value. + /// + /// Currently this function returns true if and only if both `is_i64` and + /// `is_u64` return false but this is not a guarantee in the future. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": 256.0, "b": 64, "c": -64 }); + /// + /// assert!(v["a"].is_f64()); + /// + /// // Integers. + /// assert!(!v["b"].is_f64()); + /// assert!(!v["c"].is_f64()); + /// # } + /// ``` + #[inline] + pub fn is_f64(&self) -> bool { + #[cfg(not(feature = "arbitrary_precision"))] + match self.n { + N::Float(_) => true, + N::PosInt(_) | N::NegInt(_) => false, + } + #[cfg(feature = "arbitrary_precision")] + { + for c in self.n.chars() { + if c == '.' || c == 'e' || c == 'E' { + return self.n.parse::<f64>().ok() + .map_or(false, |f| f.is_finite()); + } + } + false + } + } + + /// If the `Number` is an integer, represent it as i64 if possible. Returns + /// None otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # use std::i64; + /// # + /// # fn main() { + /// let big = i64::MAX as u64 + 10; + /// let v = json!({ "a": 64, "b": big, "c": 256.0 }); + /// + /// assert_eq!(v["a"].as_i64(), Some(64)); + /// assert_eq!(v["b"].as_i64(), None); + /// assert_eq!(v["c"].as_i64(), None); + /// # } + /// ``` + #[inline] + pub fn as_i64(&self) -> Option<i64> { + #[cfg(not(feature = "arbitrary_precision"))] + match self.n { + N::PosInt(n) => NumCast::from(n), + N::NegInt(n) => Some(n), + N::Float(_) => None, + } + #[cfg(feature = "arbitrary_precision")] + self.n.parse().ok() + } + + /// If the `Number` is an integer, represent it as u64 if possible. Returns + /// None otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": 64, "b": -64, "c": 256.0 }); + /// + /// assert_eq!(v["a"].as_u64(), Some(64)); + /// assert_eq!(v["b"].as_u64(), None); + /// assert_eq!(v["c"].as_u64(), None); + /// # } + /// ``` + #[inline] + pub fn as_u64(&self) -> Option<u64> { + #[cfg(not(feature = "arbitrary_precision"))] + match self.n { + N::PosInt(n) => Some(n), + N::NegInt(n) => NumCast::from(n), + N::Float(_) => None, + } + #[cfg(feature = "arbitrary_precision")] + self.n.parse().ok() + } + + /// Represents the number as f64 if possible. Returns None otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": 256.0, "b": 64, "c": -64 }); + /// + /// assert_eq!(v["a"].as_f64(), Some(256.0)); + /// assert_eq!(v["b"].as_f64(), Some(64.0)); + /// assert_eq!(v["c"].as_f64(), Some(-64.0)); + /// # } + /// ``` + #[inline] + pub fn as_f64(&self) -> Option<f64> { + #[cfg(not(feature = "arbitrary_precision"))] + match self.n { + N::PosInt(n) => NumCast::from(n), + N::NegInt(n) => NumCast::from(n), + N::Float(n) => Some(n), + } + #[cfg(feature = "arbitrary_precision")] + self.n.parse().ok() + } + + /// Converts a finite `f64` to a `Number`. Infinite or NaN values are not JSON + /// numbers. + /// + /// ```rust + /// # use std::f64; + /// # + /// # use serde_json::Number; + /// # + /// assert!(Number::from_f64(256.0).is_some()); + /// + /// assert!(Number::from_f64(f64::NAN).is_none()); + /// ``` + #[inline] + pub fn from_f64(f: f64) -> Option<Number> { + if f.is_finite() { + let n = { + #[cfg(not(feature = "arbitrary_precision"))] + { N::Float(f) } + #[cfg(feature = "arbitrary_precision")] + { + let mut buf = Vec::new(); + dtoa::write(&mut buf, f).unwrap(); + String::from_utf8(buf).unwrap() + } + }; + Some(Number { n: n }) + } else { + None + } + } + + #[cfg(feature = "arbitrary_precision")] + /// Not public API. Only tests use this. + #[doc(hidden)] + #[inline] + pub fn from_string_unchecked(n: String) -> Self { + Number { n: n } + } +} + +impl fmt::Display for Number { + #[cfg(not(feature = "arbitrary_precision"))] + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match self.n { + N::PosInt(u) => Display::fmt(&u, formatter), + N::NegInt(i) => Display::fmt(&i, formatter), + N::Float(f) => Display::fmt(&f, formatter), + } + } + + #[cfg(feature = "arbitrary_precision")] + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&self.n, formatter) + } +} + +impl Debug for Number { + #[cfg(not(feature = "arbitrary_precision"))] + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + let mut debug = formatter.debug_tuple("Number"); + match self.n { + N::PosInt(i) => { + debug.field(&i); + } + N::NegInt(i) => { + debug.field(&i); + } + N::Float(f) => { + debug.field(&f); + } + } + debug.finish() + } + + #[cfg(feature = "arbitrary_precision")] + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + write!(formatter, "Number({})", &self.n) + } +} + +impl Serialize for Number { + #[cfg(not(feature = "arbitrary_precision"))] + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + match self.n { + N::PosInt(u) => serializer.serialize_u64(u), + N::NegInt(i) => serializer.serialize_i64(i), + N::Float(f) => serializer.serialize_f64(f), + } + } + + #[cfg(feature = "arbitrary_precision")] + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + use serde::ser::SerializeStruct; + + let mut s = serializer.serialize_struct(SERDE_STRUCT_NAME, 1)?; + s.serialize_field(SERDE_STRUCT_FIELD_NAME, &self.n)?; + s.end() + } +} + +impl<'de> Deserialize<'de> for Number { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<Number, D::Error> + where + D: Deserializer<'de>, + { + struct NumberVisitor; + + impl<'de> Visitor<'de> for NumberVisitor { + type Value = Number; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a JSON number") + } + + #[inline] + fn visit_i64<E>(self, value: i64) -> Result<Number, E> { + Ok(value.into()) + } + + #[inline] + fn visit_u64<E>(self, value: u64) -> Result<Number, E> { + Ok(value.into()) + } + + #[inline] + fn visit_f64<E>(self, value: f64) -> Result<Number, E> + where + E: de::Error, + { + Number::from_f64(value).ok_or_else(|| de::Error::custom("not a JSON number")) + } + + #[cfg(feature = "arbitrary_precision")] + #[inline] + fn visit_map<V>(self, mut visitor: V) -> Result<Number, V::Error> + where + V: de::MapAccess<'de> + { + let value = visitor.next_key::<NumberKey>()?; + if value.is_none() { + return Err(de::Error::invalid_type(Unexpected::Map, &self)); + } + let v: NumberFromString = visitor.next_value()?; + Ok(v.value) + } + } + + deserializer.deserialize_any(NumberVisitor) + } +} + +#[cfg(feature = "arbitrary_precision")] +struct NumberKey; + +#[cfg(feature = "arbitrary_precision")] +impl<'de> de::Deserialize<'de> for NumberKey { + fn deserialize<D>(deserializer: D) -> Result<NumberKey, D::Error> + where + D: de::Deserializer<'de> + { + struct FieldVisitor; + + impl<'de> de::Visitor<'de> for FieldVisitor { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a valid number field") + } + + fn visit_str<E>(self, s: &str) -> Result<(), E> + where E: de::Error + { + if s == SERDE_STRUCT_FIELD_NAME { + Ok(()) + } else { + Err(de::Error::custom("expected field with custom name")) + } + } + } + + deserializer.deserialize_identifier(FieldVisitor)?; + Ok(NumberKey) + } +} + +#[cfg(feature = "arbitrary_precision")] +pub struct NumberFromString { + pub value: Number, +} + +#[cfg(feature = "arbitrary_precision")] +impl<'de> de::Deserialize<'de> for NumberFromString { + fn deserialize<D>(deserializer: D) -> Result<NumberFromString, D::Error> + where + D: de::Deserializer<'de> + { + struct Visitor; + + impl<'de> de::Visitor<'de> for Visitor { + type Value = NumberFromString; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("string containing a number") + } + + fn visit_str<E>(self, s: &str) -> Result<NumberFromString, E> + where E: de::Error, + { + let n = try!(s.parse().map_err(de::Error::custom)); + Ok(NumberFromString { value: n }) + } + } + + deserializer.deserialize_str(Visitor) + } +} + +#[cfg(feature = "arbitrary_precision")] +fn invalid_number() -> Error { + Error::syntax(ErrorCode::InvalidNumber, 0, 0) +} + +macro_rules! deserialize_any { + (@expand [$($num_string:tt)*]) => { + #[cfg(not(feature = "arbitrary_precision"))] + #[inline] + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + match self.n { + N::PosInt(u) => visitor.visit_u64(u), + N::NegInt(i) => visitor.visit_i64(i), + N::Float(f) => visitor.visit_f64(f), + } + } + + #[cfg(feature = "arbitrary_precision")] + #[inline] + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where V: Visitor<'de> + { + if let Some(u) = self.as_u64() { + return visitor.visit_u64(u); + } else if let Some(i) = self.as_i64() { + return visitor.visit_i64(i); + } else if let Some(f) = self.as_f64() { + if f.to_string() == self.n { + return visitor.visit_f64(f); + } + } + + visitor.visit_map(NumberDeserializer { + number: Some(self.$($num_string)*), + }) + } + }; + + (owned) => { + deserialize_any!(@expand [n]); + }; + + (ref) => { + deserialize_any!(@expand [n.clone()]); + }; +} + +macro_rules! deserialize_number { + ($deserialize:ident => $visit:ident) => { + #[cfg(not(feature = "arbitrary_precision"))] + fn $deserialize<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + self.deserialize_any(visitor) + } + + #[cfg(feature = "arbitrary_precision")] + fn $deserialize<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: de::Visitor<'de>, + { + visitor.$visit(self.n.parse().map_err(|_| invalid_number())?) + } + } +} + +impl<'de> Deserializer<'de> for Number { + type Error = Error; + + deserialize_any!(owned); + + deserialize_number!(deserialize_i8 => visit_i8); + deserialize_number!(deserialize_i16 => visit_i16); + deserialize_number!(deserialize_i32 => visit_i32); + deserialize_number!(deserialize_i64 => visit_i64); + deserialize_number!(deserialize_u8 => visit_u8); + deserialize_number!(deserialize_u16 => visit_u16); + deserialize_number!(deserialize_u32 => visit_u32); + deserialize_number!(deserialize_u64 => visit_u64); + deserialize_number!(deserialize_f32 => visit_f32); + deserialize_number!(deserialize_f64 => visit_f64); + + forward_to_deserialize_any! { + bool char str string bytes byte_buf option unit unit_struct + newtype_struct seq tuple tuple_struct map struct enum identifier + ignored_any + } +} + +impl<'de, 'a> Deserializer<'de> for &'a Number { + type Error = Error; + + deserialize_any!(ref); + + deserialize_number!(deserialize_i8 => visit_i8); + deserialize_number!(deserialize_i16 => visit_i16); + deserialize_number!(deserialize_i32 => visit_i32); + deserialize_number!(deserialize_i64 => visit_i64); + deserialize_number!(deserialize_u8 => visit_u8); + deserialize_number!(deserialize_u16 => visit_u16); + deserialize_number!(deserialize_u32 => visit_u32); + deserialize_number!(deserialize_u64 => visit_u64); + deserialize_number!(deserialize_f32 => visit_f32); + deserialize_number!(deserialize_f64 => visit_f64); + + forward_to_deserialize_any! { + bool char str string bytes byte_buf option unit unit_struct + newtype_struct seq tuple tuple_struct map struct enum identifier + ignored_any + } +} + +#[cfg(feature = "arbitrary_precision")] +// Not public API. Should be pub(crate). +#[doc(hidden)] +pub struct NumberDeserializer { + pub number: Option<String>, +} + +#[cfg(feature = "arbitrary_precision")] +impl<'de> MapAccess<'de> for NumberDeserializer { + type Error = Error; + + fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> + where + K: de::DeserializeSeed<'de>, + { + if self.number.is_none() { + return Ok(None) + } + seed.deserialize(NumberFieldDeserializer).map(Some) + } + + fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> + where + V: de::DeserializeSeed<'de>, + { + seed.deserialize(self.number.take().unwrap().into_deserializer()) + } +} + +#[cfg(feature = "arbitrary_precision")] +struct NumberFieldDeserializer; + +#[cfg(feature = "arbitrary_precision")] +impl<'de> Deserializer<'de> for NumberFieldDeserializer { + type Error = Error; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: de::Visitor<'de>, + { + visitor.visit_borrowed_str(SERDE_STRUCT_FIELD_NAME) + } + + forward_to_deserialize_any! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq + bytes byte_buf map struct option unit newtype_struct + ignored_any unit_struct tuple_struct tuple enum identifier + } +} + +impl FromStr for Number { + type Err = Error; + + fn from_str(s: &str) -> Result<Self, Self::Err> { + super::de::Deserializer::from_str(s).parse_any_signed_number().map(|n| n.into()) + } +} + +impl From<super::de::Number> for Number { + fn from(value: super::de::Number) -> Self { + let n = match value { + super::de::Number::F64(f) => { + #[cfg(not(feature = "arbitrary_precision"))] + { N::Float(f) } + #[cfg(feature = "arbitrary_precision")] + { f.to_string() } + }, + super::de::Number::U64(u) => { + #[cfg(not(feature = "arbitrary_precision"))] + { N::PosInt(u) } + #[cfg(feature = "arbitrary_precision")] + { u.to_string() } + }, + super::de::Number::I64(i) => { + #[cfg(not(feature = "arbitrary_precision"))] + { N::NegInt(i) } + #[cfg(feature = "arbitrary_precision")] + { i.to_string() } + }, + #[cfg(feature = "arbitrary_precision")] + super::de::Number::String(s) => s, + }; + Number { n: n } + } +} + +macro_rules! impl_from_unsigned { + ( + $($ty:ty),* + ) => { + $( + impl From<$ty> for Number { + #[inline] + fn from(u: $ty) -> Self { + let n = { + #[cfg(not(feature = "arbitrary_precision"))] + { N::PosInt(u as u64) } + #[cfg(feature = "arbitrary_precision")] + { + let mut buf = Vec::new(); + itoa::write(&mut buf, u).unwrap(); + String::from_utf8(buf).unwrap() + } + }; + Number { n: n } + } + } + )* + }; +} + +macro_rules! impl_from_signed { + ( + $($ty:ty),* + ) => { + $( + impl From<$ty> for Number { + #[inline] + fn from(i: $ty) -> Self { + let n = { + #[cfg(not(feature = "arbitrary_precision"))] + { + if i < 0 { + N::NegInt(i as i64) + } else { + N::PosInt(i as u64) + } + } + #[cfg(feature = "arbitrary_precision")] + { + let mut buf = Vec::new(); + itoa::write(&mut buf, i).unwrap(); + String::from_utf8(buf).unwrap() + } + }; + Number { n: n } + } + } + )* + }; +} + +impl_from_unsigned!(u8, u16, u32, u64, usize); +impl_from_signed!(i8, i16, i32, i64, isize); + +impl Number { + #[cfg(not(feature = "arbitrary_precision"))] + // Not public API. Should be pub(crate). + #[doc(hidden)] + pub fn unexpected(&self) -> Unexpected { + match self.n { + N::PosInt(u) => Unexpected::Unsigned(u), + N::NegInt(i) => Unexpected::Signed(i), + N::Float(f) => Unexpected::Float(f), + } + } + + #[cfg(feature = "arbitrary_precision")] + // Not public API. Should be pub(crate). + #[doc(hidden)] + pub fn unexpected(&self) -> Unexpected { + Unexpected::Other("number") + } +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/read.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/read.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/read.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/read.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,698 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::{char, cmp, io, str}; +use std::ops::Deref; + +use iter::LineColIterator; + +use super::error::{Error, ErrorCode, Result}; + +/// Trait used by the deserializer for iterating over input. This is manually +/// "specialized" for iterating over &[u8]. Once feature(specialization) is +/// stable we can use actual specialization. +/// +/// This trait is sealed and cannot be implemented for types outside of +/// `serde_json`. +pub trait Read<'de>: private::Sealed { + #[doc(hidden)] + fn next(&mut self) -> io::Result<Option<u8>>; + #[doc(hidden)] + fn peek(&mut self) -> io::Result<Option<u8>>; + + /// Only valid after a call to peek(). Discards the peeked byte. + #[doc(hidden)] + fn discard(&mut self); + + /// Position of the most recent call to next(). + /// + /// The most recent call was probably next() and not peek(), but this method + /// should try to return a sensible result if the most recent call was + /// actually peek() because we don't always know. + /// + /// Only called in case of an error, so performance is not important. + #[doc(hidden)] + fn position(&self) -> Position; + + /// Position of the most recent call to peek(). + /// + /// The most recent call was probably peek() and not next(), but this method + /// should try to return a sensible result if the most recent call was + /// actually next() because we don't always know. + /// + /// Only called in case of an error, so performance is not important. + #[doc(hidden)] + fn peek_position(&self) -> Position; + + /// Offset from the beginning of the input to the next byte that would be + /// returned by next() or peek(). + #[doc(hidden)] + fn byte_offset(&self) -> usize; + + /// Assumes the previous byte was a quotation mark. Parses a JSON-escaped + /// string until the next quotation mark using the given scratch space if + /// necessary. The scratch space is initially empty. + #[doc(hidden)] + fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'de, 's, str>>; + + /// Assumes the previous byte was a quotation mark. Parses a JSON-escaped + /// string until the next quotation mark using the given scratch space if + /// necessary. The scratch space is initially empty. + /// + /// This function returns the raw bytes in the string with escape sequences + /// expanded but without performing unicode validation. + #[doc(hidden)] + fn parse_str_raw<'s>( + &'s mut self, + scratch: &'s mut Vec<u8>, + ) -> Result<Reference<'de, 's, [u8]>>; + + /// Assumes the previous byte was a quotation mark. Parses a JSON-escaped + /// string until the next quotation mark but discards the data. + #[doc(hidden)] + fn ignore_str(&mut self) -> Result<()>; +} + +pub struct Position { + pub line: usize, + pub column: usize, +} + +pub enum Reference<'b, 'c, T: ?Sized + 'static> { + Borrowed(&'b T), + Copied(&'c T), +} + +impl<'b, 'c, T: ?Sized + 'static> Deref for Reference<'b, 'c, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + match *self { + Reference::Borrowed(b) => b, + Reference::Copied(c) => c, + } + } +} + +/// JSON input source that reads from a std::io input stream. +pub struct IoRead<R> +where + R: io::Read, +{ + iter: LineColIterator<io::Bytes<R>>, + /// Temporary storage of peeked byte. + ch: Option<u8>, +} + +/// JSON input source that reads from a slice of bytes. +// +// This is more efficient than other iterators because peek() can be read-only +// and we can compute line/col position only if an error happens. +pub struct SliceRead<'a> { + slice: &'a [u8], + /// Index of the *next* byte that will be returned by next() or peek(). + index: usize, +} + +/// JSON input source that reads from a UTF-8 string. +// +// Able to elide UTF-8 checks by assuming that the input is valid UTF-8. +pub struct StrRead<'a> { + delegate: SliceRead<'a>, +} + +// Prevent users from implementing the Read trait. +mod private { + pub trait Sealed {} +} + +////////////////////////////////////////////////////////////////////////////// + +impl<R> IoRead<R> +where + R: io::Read, +{ + /// Create a JSON input source to read from a std::io input stream. + pub fn new(reader: R) -> Self { + IoRead { + iter: LineColIterator::new(reader.bytes()), + ch: None, + } + } +} + +impl<R> private::Sealed for IoRead<R> +where + R: io::Read, +{ +} + +impl<R> IoRead<R> +where + R: io::Read, +{ + fn parse_str_bytes<'s, T, F>( + &'s mut self, + scratch: &'s mut Vec<u8>, + validate: bool, + result: F, + ) -> Result<T> + where + T: 's, + F: FnOnce(&'s Self, &'s [u8]) -> Result<T>, + { + loop { + let ch = try!(next_or_eof(self)); + if !ESCAPE[ch as usize] { + scratch.push(ch); + continue; + } + match ch { + b'"' => { + return result(self, scratch); + } + b'\\' => { + try!(parse_escape(self, scratch)); + } + _ => { + if validate { + return error(self, ErrorCode::ControlCharacterWhileParsingString); + } + scratch.push(ch); + } + } + } + } +} + +impl<'de, R> Read<'de> for IoRead<R> +where + R: io::Read, +{ + #[inline] + fn next(&mut self) -> io::Result<Option<u8>> { + match self.ch.take() { + Some(ch) => Ok(Some(ch)), + None => { + match self.iter.next() { + Some(Err(err)) => Err(err), + Some(Ok(ch)) => Ok(Some(ch)), + None => Ok(None), + } + } + } + } + + #[inline] + fn peek(&mut self) -> io::Result<Option<u8>> { + match self.ch { + Some(ch) => Ok(Some(ch)), + None => { + match self.iter.next() { + Some(Err(err)) => Err(err), + Some(Ok(ch)) => { + self.ch = Some(ch); + Ok(self.ch) + } + None => Ok(None), + } + } + } + } + + #[inline] + fn discard(&mut self) { + self.ch = None; + } + + fn position(&self) -> Position { + Position { + line: self.iter.line(), + column: self.iter.col(), + } + } + + fn peek_position(&self) -> Position { + // The LineColIterator updates its position during peek() so it has the + // right one here. + self.position() + } + + fn byte_offset(&self) -> usize { + match self.ch { + Some(_) => self.iter.byte_offset() - 1, + None => self.iter.byte_offset(), + } + } + + fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'de, 's, str>> { + self.parse_str_bytes(scratch, true, as_str) + .map(Reference::Copied) + } + + fn parse_str_raw<'s>( + &'s mut self, + scratch: &'s mut Vec<u8>, + ) -> Result<Reference<'de, 's, [u8]>> { + self.parse_str_bytes(scratch, false, |_, bytes| Ok(bytes)) + .map(Reference::Copied) + } + + fn ignore_str(&mut self) -> Result<()> { + loop { + let ch = try!(next_or_eof(self)); + if !ESCAPE[ch as usize] { + continue; + } + match ch { + b'"' => { + return Ok(()); + } + b'\\' => { + try!(ignore_escape(self)); + } + _ => { + return error(self, ErrorCode::ControlCharacterWhileParsingString); + } + } + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +impl<'a> SliceRead<'a> { + /// Create a JSON input source to read from a slice of bytes. + pub fn new(slice: &'a [u8]) -> Self { + SliceRead { + slice: slice, + index: 0, + } + } + + fn position_of_index(&self, i: usize) -> Position { + let mut pos = Position { line: 1, column: 0 }; + for ch in &self.slice[..i] { + match *ch { + b'\n' => { + pos.line += 1; + pos.column = 0; + } + _ => { + pos.column += 1; + } + } + } + pos + } + + /// The big optimization here over IoRead is that if the string contains no + /// backslash escape sequences, the returned &str is a slice of the raw JSON + /// data so we avoid copying into the scratch space. + fn parse_str_bytes<'s, T: ?Sized, F>( + &'s mut self, + scratch: &'s mut Vec<u8>, + validate: bool, + result: F, + ) -> Result<Reference<'a, 's, T>> + where + T: 's, + F: for<'f> FnOnce(&'s Self, &'f [u8]) -> Result<&'f T>, + { + // Index of the first byte not yet copied into the scratch space. + let mut start = self.index; + + loop { + while self.index < self.slice.len() && !ESCAPE[self.slice[self.index] as usize] { + self.index += 1; + } + if self.index == self.slice.len() { + return error(self, ErrorCode::EofWhileParsingString); + } + match self.slice[self.index] { + b'"' => { + if scratch.is_empty() { + // Fast path: return a slice of the raw JSON without any + // copying. + let borrowed = &self.slice[start..self.index]; + self.index += 1; + return result(self, borrowed).map(Reference::Borrowed); + } else { + scratch.extend_from_slice(&self.slice[start..self.index]); + // "as &[u8]" is required for rustc 1.8.0 + let copied = scratch as &[u8]; + self.index += 1; + return result(self, copied).map(Reference::Copied); + } + } + b'\\' => { + scratch.extend_from_slice(&self.slice[start..self.index]); + self.index += 1; + try!(parse_escape(self, scratch)); + start = self.index; + } + _ => { + if validate { + return error(self, ErrorCode::ControlCharacterWhileParsingString); + } + self.index += 1; + } + } + } + } +} + +impl<'a> private::Sealed for SliceRead<'a> {} + +impl<'a> Read<'a> for SliceRead<'a> { + #[inline] + fn next(&mut self) -> io::Result<Option<u8>> { + // `Ok(self.slice.get(self.index).map(|ch| { self.index += 1; *ch }))` + // is about 10% slower. + Ok( + if self.index < self.slice.len() { + let ch = self.slice[self.index]; + self.index += 1; + Some(ch) + } else { + None + }, + ) + } + + #[inline] + fn peek(&mut self) -> io::Result<Option<u8>> { + // `Ok(self.slice.get(self.index).map(|ch| *ch))` is about 10% slower + // for some reason. + Ok( + if self.index < self.slice.len() { + Some(self.slice[self.index]) + } else { + None + }, + ) + } + + #[inline] + fn discard(&mut self) { + self.index += 1; + } + + fn position(&self) -> Position { + self.position_of_index(self.index) + } + + fn peek_position(&self) -> Position { + // Cap it at slice.len() just in case the most recent call was next() + // and it returned the last byte. + self.position_of_index(cmp::min(self.slice.len(), self.index + 1)) + } + + fn byte_offset(&self) -> usize { + self.index + } + + fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'a, 's, str>> { + self.parse_str_bytes(scratch, true, as_str) + } + + fn parse_str_raw<'s>( + &'s mut self, + scratch: &'s mut Vec<u8>, + ) -> Result<Reference<'a, 's, [u8]>> { + self.parse_str_bytes(scratch, false, |_, bytes| Ok(bytes)) + } + + fn ignore_str(&mut self) -> Result<()> { + loop { + while self.index < self.slice.len() && !ESCAPE[self.slice[self.index] as usize] { + self.index += 1; + } + if self.index == self.slice.len() { + return error(self, ErrorCode::EofWhileParsingString); + } + match self.slice[self.index] { + b'"' => { + self.index += 1; + return Ok(()); + } + b'\\' => { + self.index += 1; + try!(ignore_escape(self)); + } + _ => { + return error(self, ErrorCode::ControlCharacterWhileParsingString); + } + } + } + } +} + +////////////////////////////////////////////////////////////////////////////// + +impl<'a> StrRead<'a> { + /// Create a JSON input source to read from a UTF-8 string. + pub fn new(s: &'a str) -> Self { + StrRead { delegate: SliceRead::new(s.as_bytes()) } + } +} + +impl<'a> private::Sealed for StrRead<'a> {} + +impl<'a> Read<'a> for StrRead<'a> { + #[inline] + fn next(&mut self) -> io::Result<Option<u8>> { + self.delegate.next() + } + + #[inline] + fn peek(&mut self) -> io::Result<Option<u8>> { + self.delegate.peek() + } + + #[inline] + fn discard(&mut self) { + self.delegate.discard(); + } + + fn position(&self) -> Position { + self.delegate.position() + } + + fn peek_position(&self) -> Position { + self.delegate.peek_position() + } + + fn byte_offset(&self) -> usize { + self.delegate.byte_offset() + } + + fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'a, 's, str>> { + self.delegate + .parse_str_bytes( + scratch, true, |_, bytes| { + // The input is assumed to be valid UTF-8 and the \u-escapes are + // checked along the way, so don't need to check here. + Ok(unsafe { str::from_utf8_unchecked(bytes) }) + } + ) + } + + fn parse_str_raw<'s>( + &'s mut self, + scratch: &'s mut Vec<u8>, + ) -> Result<Reference<'a, 's, [u8]>> { + self.delegate.parse_str_raw(scratch) + } + + fn ignore_str(&mut self) -> Result<()> { + self.delegate.ignore_str() + } +} + +////////////////////////////////////////////////////////////////////////////// + +const CT: bool = true; // control character \x00...\x1F +const QU: bool = true; // quote \x22 +const BS: bool = true; // backslash \x5C +const O: bool = false; // allow unescaped + +// Lookup table of bytes that must be escaped. A value of true at index i means +// that byte i requires an escape sequence in the input. +#[cfg_attr(rustfmt, rustfmt_skip)] +static ESCAPE: [bool; 256] = [ + // 1 2 3 4 5 6 7 8 9 A B C D E F + CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, // 0 + CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, // 1 + O, O, QU, O, O, O, O, O, O, O, O, O, O, O, O, O, // 2 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 3 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 4 + O, O, O, O, O, O, O, O, O, O, O, O, BS, O, O, O, // 5 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 6 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 7 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 8 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 9 + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // A + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // B + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // C + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // D + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // E + O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // F +]; + +fn next_or_eof<'de, R: ?Sized + Read<'de>>(read: &mut R) -> Result<u8> { + match try!(read.next().map_err(Error::io)) { + Some(b) => Ok(b), + None => error(read, ErrorCode::EofWhileParsingString), + } +} + +fn error<'de, R: ?Sized + Read<'de>, T>(read: &R, reason: ErrorCode) -> Result<T> { + let pos = read.position(); + Err(Error::syntax(reason, pos.line, pos.column)) +} + +fn as_str<'de, 's, R: Read<'de>>(read: &R, slice: &'s [u8]) -> Result<&'s str> { + str::from_utf8(slice).or_else(|_| error(read, ErrorCode::InvalidUnicodeCodePoint)) +} + +/// Parses a JSON escape sequence and appends it into the scratch space. Assumes +/// the previous byte read was a backslash. +fn parse_escape<'de, R: Read<'de>>(read: &mut R, scratch: &mut Vec<u8>) -> Result<()> { + let ch = try!(next_or_eof(read)); + + match ch { + b'"' => scratch.push(b'"'), + b'\\' => scratch.push(b'\\'), + b'/' => scratch.push(b'/'), + b'b' => scratch.push(b'\x08'), + b'f' => scratch.push(b'\x0c'), + b'n' => scratch.push(b'\n'), + b'r' => scratch.push(b'\r'), + b't' => scratch.push(b'\t'), + b'u' => { + let c = match try!(decode_hex_escape(read)) { + 0xDC00...0xDFFF => { + return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape); + } + + // Non-BMP characters are encoded as a sequence of + // two hex escapes, representing UTF-16 surrogates. + n1 @ 0xD800...0xDBFF => { + if try!(next_or_eof(read)) != b'\\' { + return error(read, ErrorCode::UnexpectedEndOfHexEscape); + } + if try!(next_or_eof(read)) != b'u' { + return error(read, ErrorCode::UnexpectedEndOfHexEscape); + } + + let n2 = try!(decode_hex_escape(read)); + + if n2 < 0xDC00 || n2 > 0xDFFF { + return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape); + } + + let n = (((n1 - 0xD800) as u32) << 10 | (n2 - 0xDC00) as u32) + 0x1_0000; + + match char::from_u32(n) { + Some(c) => c, + None => { + return error(read, ErrorCode::InvalidUnicodeCodePoint); + } + } + } + + n => { + match char::from_u32(n as u32) { + Some(c) => c, + None => { + return error(read, ErrorCode::InvalidUnicodeCodePoint); + } + } + } + }; + + // FIXME: this allocation is required in order to be compatible with stable + // rust, which doesn't support encoding a `char` into a stack buffer. + let mut buf = String::new(); + buf.push(c); + scratch.extend(buf.bytes()); + } + _ => { + return error(read, ErrorCode::InvalidEscape); + } + } + + Ok(()) +} + +/// Parses a JSON escape sequence and discards the value. Assumes the previous +/// byte read was a backslash. +fn ignore_escape<'de, R: ?Sized + Read<'de>>(read: &mut R) -> Result<()> { + let ch = try!(next_or_eof(read)); + + match ch { + b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {} + b'u' => { + let n = match try!(decode_hex_escape(read)) { + 0xDC00...0xDFFF => { + return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape); + } + + // Non-BMP characters are encoded as a sequence of + // two hex escapes, representing UTF-16 surrogates. + n1 @ 0xD800...0xDBFF => { + if try!(next_or_eof(read)) != b'\\' { + return error(read, ErrorCode::UnexpectedEndOfHexEscape); + } + if try!(next_or_eof(read)) != b'u' { + return error(read, ErrorCode::UnexpectedEndOfHexEscape); + } + + let n2 = try!(decode_hex_escape(read)); + + if n2 < 0xDC00 || n2 > 0xDFFF { + return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape); + } + + (((n1 - 0xD800) as u32) << 10 | (n2 - 0xDC00) as u32) + 0x1_0000 + } + + n => n as u32, + }; + + if char::from_u32(n).is_none() { + return error(read, ErrorCode::InvalidUnicodeCodePoint); + } + } + _ => { + return error(read, ErrorCode::InvalidEscape); + } + } + + Ok(()) +} + +fn decode_hex_escape<'de, R: ?Sized + Read<'de>>(read: &mut R) -> Result<u16> { + let mut n = 0; + for _ in 0..4 { + n = match try!(next_or_eof(read)) { + c @ b'0'...b'9' => n * 16_u16 + ((c as u16) - (b'0' as u16)), + b'a' | b'A' => n * 16_u16 + 10_u16, + b'b' | b'B' => n * 16_u16 + 11_u16, + b'c' | b'C' => n * 16_u16 + 12_u16, + b'd' | b'D' => n * 16_u16 + 13_u16, + b'e' | b'E' => n * 16_u16 + 14_u16, + b'f' | b'F' => n * 16_u16 + 15_u16, + _ => { + return error(read, ErrorCode::InvalidEscape); + } + }; + } + Ok(n) +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/ser.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/ser.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/ser.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/ser.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2072 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Serialize a Rust data structure into JSON data. + +use std::fmt; +use std::io; +use std::num::FpCategory; +use std::str; + +use serde::ser::{self, Impossible}; +use super::error::{Error, ErrorCode, Result}; + +use itoa; +use dtoa; + +#[cfg(feature = "arbitrary_precision")] +use serde::{Serialize}; + +#[cfg(feature = "arbitrary_precision")] +use number::{SERDE_STRUCT_NAME, SERDE_STRUCT_FIELD_NAME}; + +/// A structure for serializing Rust values into JSON. +pub struct Serializer<W, F = CompactFormatter> { + writer: W, + formatter: F, +} + +impl<W> Serializer<W> +where + W: io::Write, +{ + /// Creates a new JSON serializer. + #[inline] + pub fn new(writer: W) -> Self { + Serializer::with_formatter(writer, CompactFormatter) + } +} + +impl<'a, W> Serializer<W, PrettyFormatter<'a>> +where + W: io::Write, +{ + /// Creates a new JSON pretty print serializer. + #[inline] + pub fn pretty(writer: W) -> Self { + Serializer::with_formatter(writer, PrettyFormatter::new()) + } +} + +impl<W, F> Serializer<W, F> +where + W: io::Write, + F: Formatter, +{ + /// Creates a new JSON visitor whose output will be written to the writer + /// specified. + #[inline] + pub fn with_formatter(writer: W, formatter: F) -> Self { + Serializer { + writer: writer, + formatter: formatter, + } + } + + /// Unwrap the `Writer` from the `Serializer`. + #[inline] + pub fn into_inner(self) -> W { + self.writer + } +} + +impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F> +where + W: io::Write, + F: Formatter, +{ + type Ok = (); + type Error = Error; + + type SerializeSeq = Compound<'a, W, F>; + type SerializeTuple = Compound<'a, W, F>; + type SerializeTupleStruct = Compound<'a, W, F>; + type SerializeTupleVariant = Compound<'a, W, F>; + type SerializeMap = Compound<'a, W, F>; + type SerializeStruct = Compound<'a, W, F>; + type SerializeStructVariant = Compound<'a, W, F>; + + #[inline] + fn serialize_bool(self, value: bool) -> Result<()> { + try!( + self.formatter + .write_bool(&mut self.writer, value) + .map_err(Error::io) + ); + Ok(()) + } + + #[inline] + fn serialize_i8(self, value: i8) -> Result<()> { + try!( + self.formatter + .write_i8(&mut self.writer, value) + .map_err(Error::io) + ); + Ok(()) + } + + #[inline] + fn serialize_i16(self, value: i16) -> Result<()> { + try!( + self.formatter + .write_i16(&mut self.writer, value) + .map_err(Error::io) + ); + Ok(()) + } + + #[inline] + fn serialize_i32(self, value: i32) -> Result<()> { + try!( + self.formatter + .write_i32(&mut self.writer, value) + .map_err(Error::io) + ); + Ok(()) + } + + #[inline] + fn serialize_i64(self, value: i64) -> Result<()> { + try!( + self.formatter + .write_i64(&mut self.writer, value) + .map_err(Error::io) + ); + Ok(()) + } + + #[inline] + fn serialize_u8(self, value: u8) -> Result<()> { + try!( + self.formatter + .write_u8(&mut self.writer, value) + .map_err(Error::io) + ); + Ok(()) + } + + #[inline] + fn serialize_u16(self, value: u16) -> Result<()> { + try!( + self.formatter + .write_u16(&mut self.writer, value) + .map_err(Error::io) + ); + Ok(()) + } + + #[inline] + fn serialize_u32(self, value: u32) -> Result<()> { + try!( + self.formatter + .write_u32(&mut self.writer, value) + .map_err(Error::io) + ); + Ok(()) + } + + #[inline] + fn serialize_u64(self, value: u64) -> Result<()> { + try!( + self.formatter + .write_u64(&mut self.writer, value) + .map_err(Error::io) + ); + Ok(()) + } + + #[inline] + fn serialize_f32(self, value: f32) -> Result<()> { + match value.classify() { + FpCategory::Nan | FpCategory::Infinite => { + try!( + self.formatter + .write_null(&mut self.writer) + .map_err(Error::io) + ); + } + _ => { + try!( + self.formatter + .write_f32(&mut self.writer, value) + .map_err(Error::io) + ); + } + } + Ok(()) + } + + #[inline] + fn serialize_f64(self, value: f64) -> Result<()> { + match value.classify() { + FpCategory::Nan | FpCategory::Infinite => { + try!( + self.formatter + .write_null(&mut self.writer) + .map_err(Error::io) + ); + } + _ => { + try!( + self.formatter + .write_f64(&mut self.writer, value) + .map_err(Error::io) + ); + } + } + Ok(()) + } + + #[inline] + fn serialize_char(self, value: char) -> Result<()> { + // A char encoded as UTF-8 takes 4 bytes at most. + let mut buf = [0; 4]; + self.serialize_str(value.encode_utf8(&mut buf)) + } + + #[inline] + fn serialize_str(self, value: &str) -> Result<()> { + try!(format_escaped_str(&mut self.writer, &mut self.formatter, value).map_err(Error::io)); + Ok(()) + } + + #[inline] + fn serialize_bytes(self, value: &[u8]) -> Result<()> { + use serde::ser::SerializeSeq; + let mut seq = try!(self.serialize_seq(Some(value.len()))); + for byte in value { + try!(seq.serialize_element(byte)); + } + seq.end() + } + + #[inline] + fn serialize_unit(self) -> Result<()> { + try!( + self.formatter + .write_null(&mut self.writer) + .map_err(Error::io) + ); + Ok(()) + } + + #[inline] + fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { + self.serialize_unit() + } + + #[inline] + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + ) -> Result<()> { + self.serialize_str(variant) + } + + /// Serialize newtypes without an object wrapper. + #[inline] + fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<()> + where + T: ser::Serialize, + { + value.serialize(self) + } + + #[inline] + fn serialize_newtype_variant<T: ?Sized>( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result<()> + where + T: ser::Serialize, + { + try!( + self.formatter + .begin_object(&mut self.writer) + .map_err(Error::io) + ); + try!( + self.formatter + .begin_object_key(&mut self.writer, true) + .map_err(Error::io) + ); + try!(self.serialize_str(variant)); + try!( + self.formatter + .end_object_key(&mut self.writer) + .map_err(Error::io) + ); + try!( + self.formatter + .begin_object_value(&mut self.writer) + .map_err(Error::io) + ); + try!(value.serialize(&mut *self)); + try!( + self.formatter + .end_object_value(&mut self.writer) + .map_err(Error::io) + ); + try!( + self.formatter + .end_object(&mut self.writer) + .map_err(Error::io) + ); + Ok(()) + } + + #[inline] + fn serialize_none(self) -> Result<()> { + self.serialize_unit() + } + + #[inline] + fn serialize_some<T: ?Sized>(self, value: &T) -> Result<()> + where + T: ser::Serialize, + { + value.serialize(self) + } + + #[inline] + fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> { + if len == Some(0) { + try!( + self.formatter + .begin_array(&mut self.writer) + .map_err(Error::io) + ); + try!( + self.formatter + .end_array(&mut self.writer) + .map_err(Error::io) + ); + Ok( + Compound::Map { + ser: self, + state: State::Empty, + } + ) + } else { + try!( + self.formatter + .begin_array(&mut self.writer) + .map_err(Error::io) + ); + Ok( + Compound::Map { + ser: self, + state: State::First, + } + ) + } + } + + #[inline] + fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> { + self.serialize_seq(Some(len)) + } + + #[inline] + fn serialize_tuple_struct( + self, + _name: &'static str, + len: usize, + ) -> Result<Self::SerializeTupleStruct> { + self.serialize_seq(Some(len)) + } + + #[inline] + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result<Self::SerializeTupleVariant> { + try!( + self.formatter + .begin_object(&mut self.writer) + .map_err(Error::io) + ); + try!( + self.formatter + .begin_object_key(&mut self.writer, true) + .map_err(Error::io) + ); + try!(self.serialize_str(variant)); + try!( + self.formatter + .end_object_key(&mut self.writer) + .map_err(Error::io) + ); + try!( + self.formatter + .begin_object_value(&mut self.writer) + .map_err(Error::io) + ); + self.serialize_seq(Some(len)) + } + + #[inline] + fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> { + if len == Some(0) { + try!( + self.formatter + .begin_object(&mut self.writer) + .map_err(Error::io) + ); + try!( + self.formatter + .end_object(&mut self.writer) + .map_err(Error::io) + ); + Ok( + Compound::Map { + ser: self, + state: State::Empty, + } + ) + } else { + try!( + self.formatter + .begin_object(&mut self.writer) + .map_err(Error::io) + ); + Ok( + Compound::Map { + ser: self, + state: State::First, + } + ) + } + } + + #[cfg(not(feature = "arbitrary_precision"))] + #[inline] + fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> { + self.serialize_map(Some(len)) + } + + #[cfg(feature = "arbitrary_precision")] + #[inline] + fn serialize_struct(self, name: &'static str, len: usize) -> Result<Self::SerializeStruct> { + if name == SERDE_STRUCT_NAME { + Ok(Compound::Number { ser: self }) + } else { + self.serialize_map(Some(len)) + } + } + + #[inline] + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result<Self::SerializeStructVariant> { + try!( + self.formatter + .begin_object(&mut self.writer) + .map_err(Error::io) + ); + try!( + self.formatter + .begin_object_key(&mut self.writer, true) + .map_err(Error::io) + ); + try!(self.serialize_str(variant)); + try!( + self.formatter + .end_object_key(&mut self.writer) + .map_err(Error::io) + ); + try!( + self.formatter + .begin_object_value(&mut self.writer) + .map_err(Error::io) + ); + self.serialize_map(Some(len)) + } + + fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok> + where + T: fmt::Display, + { + use std::fmt::Write; + + struct Adapter<'ser, W: 'ser, F: 'ser> { + writer: &'ser mut W, + formatter: &'ser mut F, + error: Option<io::Error>, + } + + impl<'ser, W, F> Write for Adapter<'ser, W, F> + where + W: io::Write, + F: Formatter, + { + fn write_str(&mut self, s: &str) -> fmt::Result { + assert!(self.error.is_none()); + match format_escaped_str_contents(self.writer, self.formatter, s) { + Ok(()) => Ok(()), + Err(err) => { + self.error = Some(err); + Err(fmt::Error) + } + } + } + } + + try!( + self.formatter + .begin_string(&mut self.writer) + .map_err(Error::io) + ); + { + let mut adapter = Adapter { + writer: &mut self.writer, + formatter: &mut self.formatter, + error: None, + }; + match write!(adapter, "{}", value) { + Ok(()) => assert!(adapter.error.is_none()), + Err(fmt::Error) => { + return Err(Error::io(adapter.error.expect("there should be an error"))); + } + } + } + try!( + self.formatter + .end_string(&mut self.writer) + .map_err(Error::io) + ); + Ok(()) + } +} + +#[derive(Eq, PartialEq)] +/// Not public API. Should be pub(crate). +#[doc(hidden)] +pub enum State { + Empty, + First, + Rest, +} + +/// Not public API. Should be pub(crate). +#[doc(hidden)] +pub enum Compound<'a, W: 'a, F: 'a> { + Map { + ser: &'a mut Serializer<W, F>, + state: State, + }, + #[cfg(feature = "arbitrary_precision")] + Number { + ser: &'a mut Serializer<W, F>, + }, +} + +impl<'a, W, F> ser::SerializeSeq for Compound<'a, W, F> +where + W: io::Write, + F: Formatter, +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()> + where + T: ser::Serialize, + { + match *self { + Compound::Map { ref mut ser, ref mut state } => { + try!( + ser.formatter + .begin_array_value(&mut ser.writer, *state == State::First) + .map_err(Error::io) + ); + *state = State::Rest; + try!(value.serialize(&mut **ser)); + try!( + ser.formatter + .end_array_value(&mut ser.writer) + .map_err(Error::io) + ); + Ok(()) + }, + #[cfg(feature = "arbitrary_precision")] + Compound::Number { .. } => unreachable!(), + } + } + + #[inline] + fn end(self) -> Result<()> { + match self { + Compound::Map { ser, state } => { + match state { + State::Empty => {} + _ => { + try!( + ser.formatter + .end_array(&mut ser.writer) + .map_err(Error::io) + ) + } + } + Ok(()) + }, + #[cfg(feature = "arbitrary_precision")] + Compound::Number { .. } => unreachable!(), + } + } +} + +impl<'a, W, F> ser::SerializeTuple for Compound<'a, W, F> +where + W: io::Write, + F: Formatter, +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()> + where + T: ser::Serialize, + { + ser::SerializeSeq::serialize_element(self, value) + } + + #[inline] + fn end(self) -> Result<()> { + ser::SerializeSeq::end(self) + } +} + +impl<'a, W, F> ser::SerializeTupleStruct for Compound<'a, W, F> +where + W: io::Write, + F: Formatter, +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()> + where + T: ser::Serialize, + { + ser::SerializeSeq::serialize_element(self, value) + } + + #[inline] + fn end(self) -> Result<()> { + ser::SerializeSeq::end(self) + } +} + +impl<'a, W, F> ser::SerializeTupleVariant for Compound<'a, W, F> +where + W: io::Write, + F: Formatter, +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()> + where + T: ser::Serialize, + { + ser::SerializeSeq::serialize_element(self, value) + } + + #[inline] + fn end(self) -> Result<()> { + match self { + Compound::Map { ser, state } => { + match state { + State::Empty => {} + _ => { + try!( + ser.formatter + .end_array(&mut ser.writer) + .map_err(Error::io) + ) + } + } + try!( + ser.formatter + .end_object_value(&mut ser.writer) + .map_err(Error::io) + ); + try!( + ser.formatter + .end_object(&mut ser.writer) + .map_err(Error::io) + ); + Ok(()) + }, + #[cfg(feature = "arbitrary_precision")] + Compound::Number { .. } => unreachable!(), + } + } +} + +impl<'a, W, F> ser::SerializeMap for Compound<'a, W, F> +where + W: io::Write, + F: Formatter, +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<()> + where + T: ser::Serialize, + { + match *self { + Compound::Map { ref mut ser, ref mut state } => { + try!( + ser.formatter + .begin_object_key(&mut ser.writer, *state == State::First) + .map_err(Error::io) + ); + *state = State::Rest; + + try!(key.serialize(MapKeySerializer { ser: *ser })); + + try!( + ser.formatter + .end_object_key(&mut ser.writer) + .map_err(Error::io) + ); + Ok(()) + }, + #[cfg(feature = "arbitrary_precision")] + Compound::Number { .. } => unreachable!(), + } + } + + #[inline] + fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<()> + where + T: ser::Serialize, + { + match *self { + Compound::Map { ref mut ser, .. } => { + try!( + ser.formatter + .begin_object_value(&mut ser.writer) + .map_err(Error::io) + ); + try!(value.serialize(&mut **ser)); + try!( + ser.formatter + .end_object_value(&mut ser.writer) + .map_err(Error::io) + ); + Ok(()) + }, + #[cfg(feature = "arbitrary_precision")] + Compound::Number { .. } => unreachable!(), + } + } + + #[inline] + fn end(self) -> Result<()> { + match self { + Compound::Map { ser, state } => { + match state { + State::Empty => {} + _ => { + try!( + ser.formatter + .end_object(&mut ser.writer) + .map_err(Error::io) + ) + } + } + Ok(()) + }, + #[cfg(feature = "arbitrary_precision")] + Compound::Number { .. } => unreachable!(), + } + } +} + +impl<'a, W, F> ser::SerializeStruct for Compound<'a, W, F> +where + W: io::Write, + F: Formatter, +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()> + where + T: ser::Serialize, + { + match *self { + Compound::Map { .. } => { + try!(ser::SerializeMap::serialize_key(self, key)); + ser::SerializeMap::serialize_value(self, value) + }, + #[cfg(feature = "arbitrary_precision")] + Compound::Number { ref mut ser, .. } => { + if key == SERDE_STRUCT_FIELD_NAME { + try!(value.serialize(NumberStrEmitter(&mut *ser))); + Ok(()) + } else { + Err(invalid_number()) + } + }, + } + } + + #[inline] + fn end(self) -> Result<()> { + match self { + Compound::Map { .. } => ser::SerializeMap::end(self), + #[cfg(feature = "arbitrary_precision")] + Compound::Number { .. } => Ok(()), + } + } +} + +impl<'a, W, F> ser::SerializeStructVariant for Compound<'a, W, F> +where + W: io::Write, + F: Formatter, +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()> + where + T: ser::Serialize, + { + match *self { + Compound::Map { .. } => ser::SerializeStruct::serialize_field(self, key, value), + #[cfg(feature = "arbitrary_precision")] + Compound::Number { .. } => unreachable!(), + } + } + + #[inline] + fn end(self) -> Result<()> { + match self { + Compound::Map { ser, state } => { + match state { + State::Empty => {} + _ => { + try!( + ser.formatter + .end_object(&mut ser.writer) + .map_err(Error::io) + ) + } + } + try!( + ser.formatter + .end_object_value(&mut ser.writer) + .map_err(Error::io) + ); + try!( + ser.formatter + .end_object(&mut ser.writer) + .map_err(Error::io) + ); + Ok(()) + }, + #[cfg(feature = "arbitrary_precision")] + Compound::Number { .. } => unreachable!(), + } + } +} + +struct MapKeySerializer<'a, W: 'a, F: 'a> { + ser: &'a mut Serializer<W, F>, +} + +#[cfg(feature = "arbitrary_precision")] +fn invalid_number() -> Error { + Error::syntax(ErrorCode::InvalidNumber, 0, 0) +} + +fn key_must_be_a_string() -> Error { + Error::syntax(ErrorCode::KeyMustBeAString, 0, 0) +} + +impl<'a, W, F> ser::Serializer for MapKeySerializer<'a, W, F> +where + W: io::Write, + F: Formatter, +{ + type Ok = (); + type Error = Error; + + #[inline] + fn serialize_str(self, value: &str) -> Result<()> { + self.ser.serialize_str(value) + } + + #[inline] + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + ) -> Result<()> { + self.ser.serialize_str(variant) + } + + #[inline] + fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<()> + where + T: ser::Serialize, + { + value.serialize(self) + } + + type SerializeSeq = Impossible<(), Error>; + type SerializeTuple = Impossible<(), Error>; + type SerializeTupleStruct = Impossible<(), Error>; + type SerializeTupleVariant = Impossible<(), Error>; + type SerializeMap = Impossible<(), Error>; + type SerializeStruct = Impossible<(), Error>; + type SerializeStructVariant = Impossible<(), Error>; + + fn serialize_bool(self, _value: bool) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_i8(self, value: i8) -> Result<()> { + try!( + self.ser + .formatter + .begin_string(&mut self.ser.writer) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .write_i8(&mut self.ser.writer, value) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .end_string(&mut self.ser.writer) + .map_err(Error::io) + ); + Ok(()) + } + + fn serialize_i16(self, value: i16) -> Result<()> { + try!( + self.ser + .formatter + .begin_string(&mut self.ser.writer) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .write_i16(&mut self.ser.writer, value) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .end_string(&mut self.ser.writer) + .map_err(Error::io) + ); + Ok(()) + } + + fn serialize_i32(self, value: i32) -> Result<()> { + try!( + self.ser + .formatter + .begin_string(&mut self.ser.writer) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .write_i32(&mut self.ser.writer, value) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .end_string(&mut self.ser.writer) + .map_err(Error::io) + ); + Ok(()) + } + + fn serialize_i64(self, value: i64) -> Result<()> { + try!( + self.ser + .formatter + .begin_string(&mut self.ser.writer) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .write_i64(&mut self.ser.writer, value) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .end_string(&mut self.ser.writer) + .map_err(Error::io) + ); + Ok(()) + } + + fn serialize_u8(self, value: u8) -> Result<()> { + try!( + self.ser + .formatter + .begin_string(&mut self.ser.writer) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .write_u8(&mut self.ser.writer, value) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .end_string(&mut self.ser.writer) + .map_err(Error::io) + ); + Ok(()) + } + + fn serialize_u16(self, value: u16) -> Result<()> { + try!( + self.ser + .formatter + .begin_string(&mut self.ser.writer) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .write_u16(&mut self.ser.writer, value) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .end_string(&mut self.ser.writer) + .map_err(Error::io) + ); + Ok(()) + } + + fn serialize_u32(self, value: u32) -> Result<()> { + try!( + self.ser + .formatter + .begin_string(&mut self.ser.writer) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .write_u32(&mut self.ser.writer, value) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .end_string(&mut self.ser.writer) + .map_err(Error::io) + ); + Ok(()) + } + + fn serialize_u64(self, value: u64) -> Result<()> { + try!( + self.ser + .formatter + .begin_string(&mut self.ser.writer) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .write_u64(&mut self.ser.writer, value) + .map_err(Error::io) + ); + try!( + self.ser + .formatter + .end_string(&mut self.ser.writer) + .map_err(Error::io) + ); + Ok(()) + } + + fn serialize_f32(self, _value: f32) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_f64(self, _value: f64) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_char(self, _value: char) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_bytes(self, _value: &[u8]) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_unit(self) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_newtype_variant<T: ?Sized>( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T, + ) -> Result<()> + where + T: ser::Serialize, + { + Err(key_must_be_a_string()) + } + + fn serialize_none(self) -> Result<()> { + Err(key_must_be_a_string()) + } + + fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<()> + where + T: ser::Serialize, + { + Err(key_must_be_a_string()) + } + + fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> { + Err(key_must_be_a_string()) + } + + fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { + Err(key_must_be_a_string()) + } + + fn serialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result<Self::SerializeTupleStruct> { + Err(key_must_be_a_string()) + } + + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result<Self::SerializeTupleVariant> { + Err(key_must_be_a_string()) + } + + fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> { + Err(key_must_be_a_string()) + } + + fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> { + Err(key_must_be_a_string()) + } + + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result<Self::SerializeStructVariant> { + Err(key_must_be_a_string()) + } +} + +#[cfg(feature = "arbitrary_precision")] +struct NumberStrEmitter<'a, W: 'a + io::Write, F: 'a + Formatter>(&'a mut Serializer<W, F>); + +#[cfg(feature = "arbitrary_precision")] +impl<'a, W: io::Write, F: Formatter> ser::Serializer for NumberStrEmitter<'a, W, F> { + type Ok = (); + type Error = Error; + + type SerializeSeq = Impossible<(), Error>; + type SerializeTuple = Impossible<(), Error>; + type SerializeTupleStruct = Impossible<(), Error>; + type SerializeTupleVariant = Impossible<(), Error>; + type SerializeMap = Impossible<(), Error>; + type SerializeStruct = Impossible<(), Error>; + type SerializeStructVariant = Impossible<(), Error>; + + fn serialize_bool(self, _v: bool) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_i8(self, _v: i8) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_i16(self, _v: i16) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_i32(self, _v: i32) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_i64(self, _v: i64) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_u8(self, _v: u8) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_u16(self, _v: u16) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_u32(self, _v: u32) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_u64(self, _v: u64) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_f32(self, _v: f32) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_f64(self, _v: f64) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_char(self, _v: char) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_str(self, value: &str) -> Result<Self::Ok> { + let NumberStrEmitter(serializer) = self; + serializer.formatter.write_number_str(&mut serializer.writer, value) + .map_err(Error::io) + } + + fn serialize_bytes(self, _value: &[u8]) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_none(self) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok> + where T: Serialize + { + Err(invalid_number()) + } + + fn serialize_unit(self) -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_unit_struct(self, + _name: &'static str) + -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_unit_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str) + -> Result<Self::Ok> { + Err(invalid_number()) + } + + fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, _value: &T) + -> Result<Self::Ok> + where T: Serialize, + { + Err(invalid_number()) + } + + fn serialize_newtype_variant<T: ?Sized>(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T) + -> Result<Self::Ok> + where T: Serialize, + { + Err(invalid_number()) + } + + fn serialize_seq(self, _len: Option<usize>) + -> Result<Self::SerializeSeq> { + Err(invalid_number()) + } + + fn serialize_tuple(self, _len: usize) + -> Result<Self::SerializeTuple> { + Err(invalid_number()) + } + + fn serialize_tuple_struct(self, _name: &'static str, _len: usize) + -> Result<Self::SerializeTupleStruct> { + Err(invalid_number()) + } + + fn serialize_tuple_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize) + -> Result<Self::SerializeTupleVariant> { + Err(invalid_number()) + } + + fn serialize_map(self, _len: Option<usize>) + -> Result<Self::SerializeMap> { + Err(invalid_number()) + } + + fn serialize_struct(self, _name: &'static str, _len: usize) + -> Result<Self::SerializeStruct> { + Err(invalid_number()) + } + + fn serialize_struct_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize) + -> Result<Self::SerializeStructVariant> { + Err(invalid_number()) + } +} + +/// Represents a character escape code in a type-safe manner. +pub enum CharEscape { + /// An escaped quote `"` + Quote, + /// An escaped reverse solidus `\` + ReverseSolidus, + /// An escaped solidus `/` + Solidus, + /// An escaped backspace character (usually escaped as `\b`) + Backspace, + /// An escaped form feed character (usually escaped as `\f`) + FormFeed, + /// An escaped line feed character (usually escaped as `\n`) + LineFeed, + /// An escaped carriage return character (usually escaped as `\r`) + CarriageReturn, + /// An escaped tab character (usually escaped as `\t`) + Tab, + /// An escaped ASCII plane control character (usually escaped as + /// `\u00XX` where `XX` are two hex characters) + AsciiControl(u8), +} + +impl CharEscape { + #[inline] + fn from_escape_table(escape: u8, byte: u8) -> CharEscape { + match escape { + self::BB => CharEscape::Backspace, + self::TT => CharEscape::Tab, + self::NN => CharEscape::LineFeed, + self::FF => CharEscape::FormFeed, + self::RR => CharEscape::CarriageReturn, + self::QU => CharEscape::Quote, + self::BS => CharEscape::ReverseSolidus, + self::U => CharEscape::AsciiControl(byte), + _ => unreachable!(), + } + } +} + +/// This trait abstracts away serializing the JSON control characters, which allows the user to +/// optionally pretty print the JSON output. +pub trait Formatter { + /// Writes a `null` value to the specified writer. + #[inline] + fn write_null<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + writer.write_all(b"null") + } + + /// Writes a `true` or `false` value to the specified writer. + #[inline] + fn write_bool<W: ?Sized>(&mut self, writer: &mut W, value: bool) -> io::Result<()> + where + W: io::Write, + { + let s = if value { + b"true" as &[u8] + } else { + b"false" as &[u8] + }; + writer.write_all(s) + } + + /// Writes an integer value like `-123` to the specified writer. + #[inline] + fn write_i8<W: ?Sized>(&mut self, writer: &mut W, value: i8) -> io::Result<()> + where + W: io::Write, + { + itoa::write(writer, value).map(|_| ()) + } + + /// Writes an integer value like `-123` to the specified writer. + #[inline] + fn write_i16<W: ?Sized>(&mut self, writer: &mut W, value: i16) -> io::Result<()> + where + W: io::Write, + { + itoa::write(writer, value).map(|_| ()) + } + + /// Writes an integer value like `-123` to the specified writer. + #[inline] + fn write_i32<W: ?Sized>(&mut self, writer: &mut W, value: i32) -> io::Result<()> + where + W: io::Write, + { + itoa::write(writer, value).map(|_| ()) + } + + /// Writes an integer value like `-123` to the specified writer. + #[inline] + fn write_i64<W: ?Sized>(&mut self, writer: &mut W, value: i64) -> io::Result<()> + where + W: io::Write, + { + itoa::write(writer, value).map(|_| ()) + } + + /// Writes an integer value like `123` to the specified writer. + #[inline] + fn write_u8<W: ?Sized>(&mut self, writer: &mut W, value: u8) -> io::Result<()> + where + W: io::Write, + { + itoa::write(writer, value).map(|_| ()) + } + + /// Writes an integer value like `123` to the specified writer. + #[inline] + fn write_u16<W: ?Sized>(&mut self, writer: &mut W, value: u16) -> io::Result<()> + where + W: io::Write, + { + itoa::write(writer, value).map(|_| ()) + } + + /// Writes an integer value like `123` to the specified writer. + #[inline] + fn write_u32<W: ?Sized>(&mut self, writer: &mut W, value: u32) -> io::Result<()> + where + W: io::Write, + { + itoa::write(writer, value).map(|_| ()) + } + + /// Writes an integer value like `123` to the specified writer. + #[inline] + fn write_u64<W: ?Sized>(&mut self, writer: &mut W, value: u64) -> io::Result<()> + where + W: io::Write, + { + itoa::write(writer, value).map(|_| ()) + } + + /// Writes a floating point value like `-31.26e+12` to the specified writer. + #[inline] + fn write_f32<W: ?Sized>(&mut self, writer: &mut W, value: f32) -> io::Result<()> + where + W: io::Write, + { + dtoa::write(writer, value).map(|_| ()) + } + + /// Writes a floating point value like `-31.26e+12` to the specified writer. + #[inline] + fn write_f64<W: ?Sized>(&mut self, writer: &mut W, value: f64) -> io::Result<()> + where + W: io::Write, + { + dtoa::write(writer, value).map(|_| ()) + } + + /// Writes a number that has already been rendered to a string. + #[inline] + fn write_number_str<W: ?Sized>(&mut self, writer: &mut W, value: &str) -> io::Result<()> + where W: io::Write + { + writer.write_all(value.as_bytes()) + } + + /// Called before each series of `write_string_fragment` and + /// `write_char_escape`. Writes a `"` to the specified writer. + #[inline] + fn begin_string<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + writer.write_all(b"\"") + } + + /// Called after each series of `write_string_fragment` and + /// `write_char_escape`. Writes a `"` to the specified writer. + #[inline] + fn end_string<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + writer.write_all(b"\"") + } + + /// Writes a string fragment that doesn't need any escaping to the + /// specified writer. + #[inline] + fn write_string_fragment<W: ?Sized>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()> + where + W: io::Write, + { + writer.write_all(fragment.as_bytes()) + } + + /// Writes a character escape code to the specified writer. + #[inline] + fn write_char_escape<W: ?Sized>( + &mut self, + writer: &mut W, + char_escape: CharEscape, + ) -> io::Result<()> + where + W: io::Write, + { + use self::CharEscape::*; + + let s = match char_escape { + Quote => b"\\\"", + ReverseSolidus => b"\\\\", + Solidus => b"\\/", + Backspace => b"\\b", + FormFeed => b"\\f", + LineFeed => b"\\n", + CarriageReturn => b"\\r", + Tab => b"\\t", + AsciiControl(byte) => { + static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef"; + let bytes = &[ + b'\\', + b'u', + b'0', + b'0', + HEX_DIGITS[(byte >> 4) as usize], + HEX_DIGITS[(byte & 0xF) as usize], + ]; + return writer.write_all(bytes); + } + }; + + writer.write_all(s) + } + + /// Called before every array. Writes a `[` to the specified + /// writer. + #[inline] + fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + writer.write_all(b"[") + } + + /// Called after every array. Writes a `]` to the specified + /// writer. + #[inline] + fn end_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + writer.write_all(b"]") + } + + /// Called before every array value. Writes a `,` if needed to + /// the specified writer. + #[inline] + fn begin_array_value<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> + where + W: io::Write, + { + if first { + Ok(()) + } else { + writer.write_all(b",") + } + } + + /// Called after every array value. + #[inline] + fn end_array_value<W: ?Sized>(&mut self, _writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + Ok(()) + } + + /// Called before every object. Writes a `{` to the specified + /// writer. + #[inline] + fn begin_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + writer.write_all(b"{") + } + + /// Called after every object. Writes a `}` to the specified + /// writer. + #[inline] + fn end_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + writer.write_all(b"}") + } + + /// Called before every object key. + #[inline] + fn begin_object_key<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> + where + W: io::Write, + { + if first { + Ok(()) + } else { + writer.write_all(b",") + } + } + + /// Called after every object key. A `:` should be written to the + /// specified writer by either this method or + /// `begin_object_value`. + #[inline] + fn end_object_key<W: ?Sized>(&mut self, _writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + Ok(()) + } + + /// Called before every object value. A `:` should be written to + /// the specified writer by either this method or + /// `end_object_key`. + #[inline] + fn begin_object_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + writer.write_all(b":") + } + + /// Called after every object value. + #[inline] + fn end_object_value<W: ?Sized>(&mut self, _writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + Ok(()) + } +} + +/// This structure compacts a JSON value with no extra whitespace. +#[derive(Clone, Debug)] +pub struct CompactFormatter; + +impl Formatter for CompactFormatter {} + +/// This structure pretty prints a JSON value to make it human readable. +#[derive(Clone, Debug)] +pub struct PrettyFormatter<'a> { + current_indent: usize, + has_value: bool, + indent: &'a [u8], +} + +impl<'a> PrettyFormatter<'a> { + /// Construct a pretty printer formatter that defaults to using two spaces for indentation. + pub fn new() -> Self { + PrettyFormatter::with_indent(b" ") + } + + /// Construct a pretty printer formatter that uses the `indent` string for indentation. + pub fn with_indent(indent: &'a [u8]) -> Self { + PrettyFormatter { + current_indent: 0, + has_value: false, + indent: indent, + } + } +} + +impl<'a> Default for PrettyFormatter<'a> { + fn default() -> Self { + PrettyFormatter::new() + } +} + +impl<'a> Formatter for PrettyFormatter<'a> { + #[inline] + fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + self.current_indent += 1; + self.has_value = false; + writer.write_all(b"[") + } + + #[inline] + fn end_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + self.current_indent -= 1; + + if self.has_value { + try!(writer.write_all(b"\n")); + try!(indent(writer, self.current_indent, self.indent)); + } + + writer.write_all(b"]") + } + + #[inline] + fn begin_array_value<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> + where + W: io::Write, + { + if first { + try!(writer.write_all(b"\n")); + } else { + try!(writer.write_all(b",\n")); + } + try!(indent(writer, self.current_indent, self.indent)); + Ok(()) + } + + #[inline] + fn end_array_value<W: ?Sized>(&mut self, _writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + self.has_value = true; + Ok(()) + } + + #[inline] + fn begin_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + self.current_indent += 1; + self.has_value = false; + writer.write_all(b"{") + } + + #[inline] + fn end_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + self.current_indent -= 1; + + if self.has_value { + try!(writer.write_all(b"\n")); + try!(indent(writer, self.current_indent, self.indent)); + } + + writer.write_all(b"}") + } + + #[inline] + fn begin_object_key<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> + where + W: io::Write, + { + if first { + try!(writer.write_all(b"\n")); + } else { + try!(writer.write_all(b",\n")); + } + indent(writer, self.current_indent, self.indent) + } + + #[inline] + fn begin_object_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + writer.write_all(b": ") + } + + #[inline] + fn end_object_value<W: ?Sized>(&mut self, _writer: &mut W) -> io::Result<()> + where + W: io::Write, + { + self.has_value = true; + Ok(()) + } +} + +fn format_escaped_str<W: ?Sized, F: ?Sized>( + writer: &mut W, + formatter: &mut F, + value: &str, +) -> io::Result<()> +where + W: io::Write, + F: Formatter, +{ + try!(formatter.begin_string(writer)); + try!(format_escaped_str_contents(writer, formatter, value)); + try!(formatter.end_string(writer)); + Ok(()) +} + +fn format_escaped_str_contents<W: ?Sized, F: ?Sized>( + writer: &mut W, + formatter: &mut F, + value: &str, +) -> io::Result<()> +where + W: io::Write, + F: Formatter, +{ + let bytes = value.as_bytes(); + + let mut start = 0; + + for (i, &byte) in bytes.iter().enumerate() { + let escape = ESCAPE[byte as usize]; + if escape == 0 { + continue; + } + + if start < i { + try!(formatter.write_string_fragment(writer, &value[start..i])); + } + + let char_escape = CharEscape::from_escape_table(escape, byte); + try!(formatter.write_char_escape(writer, char_escape)); + + start = i + 1; + } + + if start != bytes.len() { + try!(formatter.write_string_fragment(writer, &value[start..])); + } + + Ok(()) +} + +const BB: u8 = b'b'; // \x08 +const TT: u8 = b't'; // \x09 +const NN: u8 = b'n'; // \x0A +const FF: u8 = b'f'; // \x0C +const RR: u8 = b'r'; // \x0D +const QU: u8 = b'"'; // \x22 +const BS: u8 = b'\\'; // \x5C +const U: u8 = b'u'; // \x00...\x1F except the ones above + +// Lookup table of escape sequences. A value of b'x' at index i means that byte +// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped. +#[cfg_attr(rustfmt, rustfmt_skip)] +static ESCAPE: [u8; 256] = [ + // 1 2 3 4 5 6 7 8 9 A B C D E F + U, U, U, U, U, U, U, U, BB, TT, NN, U, FF, RR, U, U, // 0 + U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, // 1 + 0, 0, QU, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, BS, 0, 0, 0, // 5 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F +]; + +/// Serialize the given data structure as JSON into the IO stream. +/// +/// # Errors +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +#[inline] +pub fn to_writer<W, T: ?Sized>(writer: W, value: &T) -> Result<()> +where + W: io::Write, + T: ser::Serialize, +{ + let mut ser = Serializer::new(writer); + try!(value.serialize(&mut ser)); + Ok(()) +} + +/// Serialize the given data structure as pretty-printed JSON into the IO +/// stream. +/// +/// # Errors +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +#[inline] +pub fn to_writer_pretty<W, T: ?Sized>(writer: W, value: &T) -> Result<()> +where + W: io::Write, + T: ser::Serialize, +{ + let mut ser = Serializer::pretty(writer); + try!(value.serialize(&mut ser)); + Ok(()) +} + +/// Serialize the given data structure as a JSON byte vector. +/// +/// # Errors +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +#[inline] +pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>> +where + T: ser::Serialize, +{ + let mut writer = Vec::with_capacity(128); + try!(to_writer(&mut writer, value)); + Ok(writer) +} + +/// Serialize the given data structure as a pretty-printed JSON byte vector. +/// +/// # Errors +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +#[inline] +pub fn to_vec_pretty<T: ?Sized>(value: &T) -> Result<Vec<u8>> +where + T: ser::Serialize, +{ + let mut writer = Vec::with_capacity(128); + try!(to_writer_pretty(&mut writer, value)); + Ok(writer) +} + +/// Serialize the given data structure as a String of JSON. +/// +/// # Errors +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +#[inline] +pub fn to_string<T: ?Sized>(value: &T) -> Result<String> +where + T: ser::Serialize, +{ + let vec = try!(to_vec(value)); + let string = unsafe { + // We do not emit invalid UTF-8. + String::from_utf8_unchecked(vec) + }; + Ok(string) +} + +/// Serialize the given data structure as a pretty-printed String of JSON. +/// +/// # Errors +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +#[inline] +pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String> +where + T: ser::Serialize, +{ + let vec = try!(to_vec_pretty(value)); + let string = unsafe { + // We do not emit invalid UTF-8. + String::from_utf8_unchecked(vec) + }; + Ok(string) +} + +fn indent<W: ?Sized>(wr: &mut W, n: usize, s: &[u8]) -> io::Result<()> +where + W: io::Write, +{ + for _ in 0..n { + try!(wr.write_all(s)); + } + + Ok(()) +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/value/de.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/value/de.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/value/de.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/value/de.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1060 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::borrow::Cow; +use std::fmt; +use std::i64; +use std::io; +use std::slice; +use std::str; +use std::vec; + +use serde; +use serde::de::{ + Deserialize, + DeserializeSeed, + IntoDeserializer, + Visitor, + SeqAccess, + MapAccess, + EnumAccess, + VariantAccess, + Unexpected +}; + +use error::Error; +use map::Map; +use number::Number; +use value::Value; + +#[cfg(feature = "arbitrary_precision")] +use serde::de; + +#[cfg(feature = "arbitrary_precision")] +use number::{NumberFromString, SERDE_STRUCT_FIELD_NAME}; + +impl<'de> Deserialize<'de> for Value { + #[inline] + fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> + where + D: serde::Deserializer<'de>, + { + struct ValueVisitor; + + impl<'de> Visitor<'de> for ValueVisitor { + type Value = Value; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("any valid JSON value") + } + + #[inline] + fn visit_bool<E>(self, value: bool) -> Result<Value, E> { + Ok(Value::Bool(value)) + } + + #[inline] + fn visit_i64<E>(self, value: i64) -> Result<Value, E> { + Ok(Value::Number(value.into())) + } + + #[inline] + fn visit_u64<E>(self, value: u64) -> Result<Value, E> { + Ok(Value::Number(value.into())) + } + + #[inline] + fn visit_f64<E>(self, value: f64) -> Result<Value, E> { + Ok(Number::from_f64(value).map_or(Value::Null, Value::Number)) + } + + #[inline] + fn visit_str<E>(self, value: &str) -> Result<Value, E> + where + E: serde::de::Error, + { + self.visit_string(String::from(value)) + } + + #[inline] + fn visit_string<E>(self, value: String) -> Result<Value, E> { + Ok(Value::String(value)) + } + + #[inline] + fn visit_none<E>(self) -> Result<Value, E> { + Ok(Value::Null) + } + + #[inline] + fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error> + where + D: serde::Deserializer<'de>, + { + Deserialize::deserialize(deserializer) + } + + #[inline] + fn visit_unit<E>(self) -> Result<Value, E> { + Ok(Value::Null) + } + + #[inline] + fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error> + where + V: SeqAccess<'de>, + { + let mut vec = Vec::new(); + + while let Some(elem) = try!(visitor.next_element()) { + vec.push(elem); + } + + Ok(Value::Array(vec)) + } + + #[cfg(not(feature = "arbitrary_precision"))] + fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error> + where + V: MapAccess<'de>, + { + let mut values = Map::new(); + + while let Some((key, value)) = try!(visitor.next_entry()) { + values.insert(key, value); + } + + Ok(Value::Object(values)) + } + + #[cfg(feature = "arbitrary_precision")] + fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error> + where + V: MapAccess<'de>, + { + let mut key = String::new(); + let number = visitor.next_key_seed(NumberOrObject { + key: &mut key, + })?; + match number { + Some(true) => { + let number: NumberFromString = visitor.next_value()?; + return Ok(Value::Number(number.value)) + } + None => return Ok(Value::Object(Map::new())), + Some(false) => {} + } + + let mut values = Map::new(); + + values.insert(key, try!(visitor.next_value())); + while let Some((key, value)) = try!(visitor.next_entry()) { + values.insert(key, value); + } + + Ok(Value::Object(values)) + } + } + + deserializer.deserialize_any(ValueVisitor) + } +} + +struct WriterFormatter<'a, 'b: 'a> { + inner: &'a mut fmt::Formatter<'b>, +} + +impl<'a, 'b> io::Write for WriterFormatter<'a, 'b> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + fn io_error<E>(_: E) -> io::Error { + // Value does not matter because fmt::Debug and fmt::Display impls + // below just map it to fmt::Error + io::Error::new(io::ErrorKind::Other, "fmt error") + } + let s = try!(str::from_utf8(buf).map_err(io_error)); + try!(self.inner.write_str(s).map_err(io_error)); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl fmt::Display for Value { + /// Display a JSON value as a string. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let json = json!({ "city": "London", "street": "10 Downing Street" }); + /// + /// // Compact format: + /// // + /// // {"city":"London","street":"10 Downing Street"} + /// let compact = format!("{}", json); + /// assert_eq!(compact, + /// "{\"city\":\"London\",\"street\":\"10 Downing Street\"}"); + /// + /// // Pretty format: + /// // + /// // { + /// // "city": "London", + /// // "street": "10 Downing Street" + /// // } + /// let pretty = format!("{:#}", json); + /// assert_eq!(pretty, + /// "{\n \"city\": \"London\",\n \"street\": \"10 Downing Street\"\n}"); + /// # } + /// ``` + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let alternate = f.alternate(); + let mut wr = WriterFormatter { inner: f }; + if alternate { + // {:#} + super::super::ser::to_writer_pretty(&mut wr, self).map_err(|_| fmt::Error) + } else { + // {} + super::super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error) + } + } +} + +impl str::FromStr for Value { + type Err = Error; + fn from_str(s: &str) -> Result<Value, Error> { + super::super::de::from_str(s) + } +} + +macro_rules! deserialize_prim_number { + ($method:ident) => { + #[cfg(not(feature = "arbitrary_precision"))] + fn $method<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + self.deserialize_any(visitor) + } + + #[cfg(feature = "arbitrary_precision")] + fn $method<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + match self { + Value::Number(n) => n.$method(visitor), + _ => self.deserialize_any(visitor), + } + } + } +} + +impl<'de> serde::Deserializer<'de> for Value { + type Error = Error; + + #[inline] + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + match self { + Value::Null => visitor.visit_unit(), + Value::Bool(v) => visitor.visit_bool(v), + Value::Number(n) => n.deserialize_any(visitor), + Value::String(v) => visitor.visit_string(v), + Value::Array(v) => { + let len = v.len(); + let mut deserializer = SeqDeserializer::new(v); + let seq = try!(visitor.visit_seq(&mut deserializer)); + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(seq) + } else { + Err(serde::de::Error::invalid_length(len, &"fewer elements in array")) + } + } + Value::Object(v) => { + let len = v.len(); + let mut deserializer = MapDeserializer::new(v); + let map = try!(visitor.visit_map(&mut deserializer)); + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(map) + } else { + Err(serde::de::Error::invalid_length(len, &"fewer elements in map")) + } + } + } + } + + deserialize_prim_number!(deserialize_i8); + deserialize_prim_number!(deserialize_i16); + deserialize_prim_number!(deserialize_i32); + deserialize_prim_number!(deserialize_i64); + deserialize_prim_number!(deserialize_u8); + deserialize_prim_number!(deserialize_u16); + deserialize_prim_number!(deserialize_u32); + deserialize_prim_number!(deserialize_u64); + deserialize_prim_number!(deserialize_f32); + deserialize_prim_number!(deserialize_f64); + + #[inline] + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + match self { + Value::Null => visitor.visit_none(), + _ => visitor.visit_some(self), + } + } + + #[inline] + fn deserialize_enum<V>( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + let (variant, value) = match self { + Value::Object(value) => { + let mut iter = value.into_iter(); + let (variant, value) = match iter.next() { + Some(v) => v, + None => { + return Err( + serde::de::Error::invalid_value( + Unexpected::Map, + &"map with a single key", + ), + ); + } + }; + // enums are encoded in json as maps with a single key:value pair + if iter.next().is_some() { + return Err(serde::de::Error::invalid_value(Unexpected::Map, &"map with a single key"),); + } + (variant, Some(value)) + } + Value::String(variant) => (variant, None), + other => { + return Err(serde::de::Error::invalid_type(other.unexpected(), &"string or map"),); + } + }; + + visitor.visit_enum( + EnumDeserializer { + variant: variant, + value: value, + }, + ) + } + + #[inline] + fn deserialize_newtype_struct<V>( + self, + _name: &'static str, + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + forward_to_deserialize_any! { + bool char str string bytes byte_buf unit unit_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +struct EnumDeserializer { + variant: String, + value: Option<Value>, +} + +impl<'de> EnumAccess<'de> for EnumDeserializer { + type Error = Error; + type Variant = VariantDeserializer; + + fn variant_seed<V>(self, seed: V) -> Result<(V::Value, VariantDeserializer), Error> + where + V: DeserializeSeed<'de>, + { + let variant = self.variant.into_deserializer(); + let visitor = VariantDeserializer { value: self.value }; + seed.deserialize(variant).map(|v| (v, visitor)) + } +} + +struct VariantDeserializer { + value: Option<Value>, +} + +impl<'de> VariantAccess<'de> for VariantDeserializer { + type Error = Error; + + fn unit_variant(self) -> Result<(), Error> { + match self.value { + Some(value) => Deserialize::deserialize(value), + None => Ok(()), + } + } + + fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error> + where + T: DeserializeSeed<'de>, + { + match self.value { + Some(value) => seed.deserialize(value), + None => Err(serde::de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant"),), + } + } + + fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + match self.value { + Some(Value::Array(v)) => { + serde::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor) + } + Some(other) => Err(serde::de::Error::invalid_type(other.unexpected(), &"tuple variant"),), + None => Err(serde::de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"),), + } + } + + fn struct_variant<V>( + self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + match self.value { + Some(Value::Object(v)) => { + serde::Deserializer::deserialize_any(MapDeserializer::new(v), visitor) + } + Some(other) => Err(serde::de::Error::invalid_type(other.unexpected(), &"struct variant"),), + _ => Err(serde::de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"),), + } + } +} + +struct SeqDeserializer { + iter: vec::IntoIter<Value>, +} + +impl SeqDeserializer { + fn new(vec: Vec<Value>) -> Self { + SeqDeserializer { iter: vec.into_iter() } + } +} + +impl<'de> serde::Deserializer<'de> for SeqDeserializer { + type Error = Error; + + #[inline] + fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + let len = self.iter.len(); + if len == 0 { + visitor.visit_unit() + } else { + let ret = try!(visitor.visit_seq(&mut self)); + let remaining = self.iter.len(); + if remaining == 0 { + Ok(ret) + } else { + Err(serde::de::Error::invalid_length(len, &"fewer elements in array")) + } + } + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +impl<'de> SeqAccess<'de> for SeqDeserializer { + type Error = Error; + + fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> + where + T: DeserializeSeed<'de>, + { + match self.iter.next() { + Some(value) => seed.deserialize(value).map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> Option<usize> { + match self.iter.size_hint() { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } + } +} + +struct MapDeserializer { + iter: <Map<String, Value> as IntoIterator>::IntoIter, + value: Option<Value>, +} + +impl MapDeserializer { + fn new(map: Map<String, Value>) -> Self { + MapDeserializer { + iter: map.into_iter(), + value: None, + } + } +} + +impl<'de> MapAccess<'de> for MapDeserializer { + type Error = Error; + + fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> + where + T: DeserializeSeed<'de>, + { + match self.iter.next() { + Some((key, value)) => { + self.value = Some(value); + let key_de = MapKeyDeserializer { key: Cow::Owned(key) }; + seed.deserialize(key_de).map(Some) + } + None => Ok(None), + } + } + + fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Error> + where + T: DeserializeSeed<'de>, + { + match self.value.take() { + Some(value) => seed.deserialize(value), + None => Err(serde::de::Error::custom("value is missing")), + } + } + + fn size_hint(&self) -> Option<usize> { + match self.iter.size_hint() { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } + } +} + +impl<'de> serde::Deserializer<'de> for MapDeserializer { + type Error = Error; + + #[inline] + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + visitor.visit_map(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +macro_rules! deserialize_value_ref_number { + ($method:ident) => { + #[cfg(not(feature = "arbitrary_precision"))] + fn $method<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + self.deserialize_any(visitor) + } + + #[cfg(feature = "arbitrary_precision")] + fn $method<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + match *self { + Value::Number(ref n) => n.$method(visitor), + _ => self.deserialize_any(visitor), + } + } + } +} + +impl<'de> serde::Deserializer<'de> for &'de Value { + type Error = Error; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + match *self { + Value::Null => visitor.visit_unit(), + Value::Bool(v) => visitor.visit_bool(v), + Value::Number(ref n) => n.deserialize_any(visitor), + Value::String(ref v) => visitor.visit_borrowed_str(v), + Value::Array(ref v) => { + let len = v.len(); + let mut deserializer = SeqRefDeserializer::new(v); + let seq = try!(visitor.visit_seq(&mut deserializer)); + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(seq) + } else { + Err(serde::de::Error::invalid_length(len, &"fewer elements in array")) + } + } + Value::Object(ref v) => { + let len = v.len(); + let mut deserializer = MapRefDeserializer::new(v); + let map = try!(visitor.visit_map(&mut deserializer)); + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(map) + } else { + Err(serde::de::Error::invalid_length(len, &"fewer elements in map")) + } + } + } + } + + deserialize_value_ref_number!(deserialize_i8); + deserialize_value_ref_number!(deserialize_i16); + deserialize_value_ref_number!(deserialize_i32); + deserialize_value_ref_number!(deserialize_i64); + deserialize_value_ref_number!(deserialize_u8); + deserialize_value_ref_number!(deserialize_u16); + deserialize_value_ref_number!(deserialize_u32); + deserialize_value_ref_number!(deserialize_u64); + deserialize_value_ref_number!(deserialize_f32); + deserialize_value_ref_number!(deserialize_f64); + + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + match *self { + Value::Null => visitor.visit_none(), + _ => visitor.visit_some(self), + } + } + + fn deserialize_enum<V>( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + let (variant, value) = match *self { + Value::Object(ref value) => { + let mut iter = value.into_iter(); + let (variant, value) = match iter.next() { + Some(v) => v, + None => { + return Err( + serde::de::Error::invalid_value( + Unexpected::Map, + &"map with a single key", + ), + ); + } + }; + // enums are encoded in json as maps with a single key:value pair + if iter.next().is_some() { + return Err(serde::de::Error::invalid_value(Unexpected::Map, &"map with a single key"),); + } + (variant, Some(value)) + } + Value::String(ref variant) => (variant, None), + ref other => { + return Err(serde::de::Error::invalid_type(other.unexpected(), &"string or map"),); + } + }; + + visitor.visit_enum( + EnumRefDeserializer { + variant: variant, + value: value, + }, + ) + } + + #[inline] + fn deserialize_newtype_struct<V>( + self, + _name: &'static str, + visitor: V, + ) -> Result<V::Value, Self::Error> + where + V: Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + forward_to_deserialize_any! { + bool char str string bytes byte_buf unit unit_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +struct EnumRefDeserializer<'de> { + variant: &'de str, + value: Option<&'de Value>, +} + +impl<'de> EnumAccess<'de> for EnumRefDeserializer<'de> { + type Error = Error; + type Variant = VariantRefDeserializer<'de>; + + fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Error> + where + V: DeserializeSeed<'de>, + { + let variant = self.variant.into_deserializer(); + let visitor = VariantRefDeserializer { value: self.value }; + seed.deserialize(variant).map(|v| (v, visitor)) + } +} + +struct VariantRefDeserializer<'de> { + value: Option<&'de Value>, +} + +impl<'de> VariantAccess<'de> for VariantRefDeserializer<'de> { + type Error = Error; + + fn unit_variant(self) -> Result<(), Error> { + match self.value { + Some(value) => Deserialize::deserialize(value), + None => Ok(()), + } + } + + fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error> + where + T: DeserializeSeed<'de>, + { + match self.value { + Some(value) => seed.deserialize(value), + None => Err(serde::de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant"),), + } + } + + fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + match self.value { + Some(&Value::Array(ref v)) => { + serde::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor) + } + Some(other) => Err(serde::de::Error::invalid_type(other.unexpected(), &"tuple variant"),), + None => Err(serde::de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"),), + } + } + + fn struct_variant<V>( + self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + match self.value { + Some(&Value::Object(ref v)) => { + serde::Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor) + } + Some(other) => Err(serde::de::Error::invalid_type(other.unexpected(), &"struct variant"),), + _ => Err(serde::de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"),), + } + } +} + +struct SeqRefDeserializer<'de> { + iter: slice::Iter<'de, Value>, +} + +impl<'de> SeqRefDeserializer<'de> { + fn new(slice: &'de [Value]) -> Self { + SeqRefDeserializer { iter: slice.iter() } + } +} + +impl<'de> serde::Deserializer<'de> for SeqRefDeserializer<'de> { + type Error = Error; + + #[inline] + fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + let len = self.iter.len(); + if len == 0 { + visitor.visit_unit() + } else { + let ret = try!(visitor.visit_seq(&mut self)); + let remaining = self.iter.len(); + if remaining == 0 { + Ok(ret) + } else { + Err(serde::de::Error::invalid_length(len, &"fewer elements in array")) + } + } + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +impl<'de> SeqAccess<'de> for SeqRefDeserializer<'de> { + type Error = Error; + + fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> + where + T: DeserializeSeed<'de>, + { + match self.iter.next() { + Some(value) => seed.deserialize(value).map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> Option<usize> { + match self.iter.size_hint() { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } + } +} + +struct MapRefDeserializer<'de> { + iter: <&'de Map<String, Value> as IntoIterator>::IntoIter, + value: Option<&'de Value>, +} + +impl<'de> MapRefDeserializer<'de> { + fn new(map: &'de Map<String, Value>) -> Self { + MapRefDeserializer { + iter: map.into_iter(), + value: None, + } + } +} + +impl<'de> MapAccess<'de> for MapRefDeserializer<'de> { + type Error = Error; + + fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> + where + T: DeserializeSeed<'de>, + { + match self.iter.next() { + Some((key, value)) => { + self.value = Some(value); + let key_de = MapKeyDeserializer { key: Cow::Borrowed(&**key) }; + seed.deserialize(key_de).map(Some) + } + None => Ok(None), + } + } + + fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Error> + where + T: DeserializeSeed<'de>, + { + match self.value.take() { + Some(value) => seed.deserialize(value), + None => Err(serde::de::Error::custom("value is missing")), + } + } + + fn size_hint(&self) -> Option<usize> { + match self.iter.size_hint() { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } + } +} + +impl<'de> serde::Deserializer<'de> for MapRefDeserializer<'de> { + type Error = Error; + + #[inline] + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + visitor.visit_map(self) + } + + forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes + byte_buf option unit unit_struct newtype_struct seq tuple + tuple_struct map struct enum identifier ignored_any + } +} + +struct MapKeyDeserializer<'de> { + key: Cow<'de, str>, +} + +macro_rules! deserialize_integer_key { + ($method:ident => $visit:ident) => { + fn $method<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + match (self.key.parse(), self.key) { + (Ok(integer), _) => visitor.$visit(integer), + (Err(_), Cow::Borrowed(s)) => visitor.visit_borrowed_str(s), + (Err(_), Cow::Owned(s)) => visitor.visit_string(s), + } + } + } +} + +impl<'de> serde::Deserializer<'de> for MapKeyDeserializer<'de> { + type Error = Error; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + self.key.into_deserializer().deserialize_any(visitor) + } + + deserialize_integer_key!(deserialize_i8 => visit_i8); + deserialize_integer_key!(deserialize_i16 => visit_i16); + deserialize_integer_key!(deserialize_i32 => visit_i32); + deserialize_integer_key!(deserialize_i64 => visit_i64); + deserialize_integer_key!(deserialize_u8 => visit_u8); + deserialize_integer_key!(deserialize_u16 => visit_u16); + deserialize_integer_key!(deserialize_u32 => visit_u32); + deserialize_integer_key!(deserialize_u64 => visit_u64); + + #[inline] + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + // Map keys cannot be null. + visitor.visit_some(self) + } + + #[inline] + fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_enum<V>( + self, + name: &'static str, + variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, Error> + where + V: Visitor<'de>, + { + self.key.into_deserializer().deserialize_enum(name, variants, visitor) + } + + forward_to_deserialize_any! { + bool f32 f64 char str string bytes byte_buf unit unit_struct seq tuple + tuple_struct map struct identifier ignored_any + } +} + +#[cfg(feature = "arbitrary_precision")] +struct NumberOrObject<'a> { + key: &'a mut String, +} + +#[cfg(feature = "arbitrary_precision")] +impl<'a, 'de> DeserializeSeed<'de> for NumberOrObject<'a> { + type Value = bool; + + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where + D: serde::Deserializer<'de> + { + deserializer.deserialize_any(self) + } +} + +#[cfg(feature = "arbitrary_precision")] +impl<'a, 'de> Visitor<'de> for NumberOrObject<'a> { + type Value = bool; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string key") + } + + fn visit_str<E>(self, s: &str) -> Result<bool, E> + where + E: de::Error, + { + if s == SERDE_STRUCT_FIELD_NAME { + Ok(true) + } else { + self.key.push_str(s); + Ok(false) + } + } + + fn visit_string<E>(self, s: String) -> Result<bool, E> + where + E: de::Error, + { + if s == SERDE_STRUCT_FIELD_NAME { + Ok(true) + } else { + *self.key = s; + Ok(false) + } + } +} + +impl Value { + fn unexpected(&self) -> Unexpected { + match *self { + Value::Null => Unexpected::Unit, + Value::Bool(b) => Unexpected::Bool(b), + Value::Number(ref n) => n.unexpected(), + Value::String(ref s) => Unexpected::Str(s), + Value::Array(_) => Unexpected::Seq, + Value::Object(_) => Unexpected::Map, + } + } +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/value/from.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/value/from.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/value/from.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/value/from.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,266 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::borrow::Cow; + +use super::Value; +use map::Map; +use number::Number; + +macro_rules! from_integer { + ($($ty:ident)*) => { + $( + impl From<$ty> for Value { + fn from(n: $ty) -> Self { + Value::Number(n.into()) + } + } + )* + }; +} + +from_integer! { + i8 i16 i32 i64 isize + u8 u16 u32 u64 usize +} + +impl From<f32> for Value { + /// Convert 32-bit floating point number to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::Value; + /// + /// let f: f32 = 13.37; + /// let x: Value = f.into(); + /// # } + /// ``` + fn from(f: f32) -> Self { + From::from(f as f64) + } +} + +impl From<f64> for Value { + /// Convert 64-bit floating point number to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::Value; + /// + /// let f: f64 = 13.37; + /// let x: Value = f.into(); + /// # } + /// ``` + fn from(f: f64) -> Self { + Number::from_f64(f).map_or(Value::Null, Value::Number) + } +} + +impl From<bool> for Value { + /// Convert boolean to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::Value; + /// + /// let b = false; + /// let x: Value = b.into(); + /// # } + /// ``` + fn from(f: bool) -> Self { + Value::Bool(f) + } +} + +impl From<String> for Value { + /// Convert `String` to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::Value; + /// + /// let s: String = "lorem".to_string(); + /// let x: Value = s.into(); + /// # } + /// ``` + fn from(f: String) -> Self { + Value::String(f) + } +} + +impl<'a> From<&'a str> for Value { + /// Convert string slice to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::Value; + /// + /// let s: &str = "lorem"; + /// let x: Value = s.into(); + /// # } + /// ``` + fn from(f: &str) -> Self { + Value::String(f.to_string()) + } +} + +impl<'a> From<Cow<'a, str>> for Value { + /// Convert copy-on-write string to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::Value; + /// use std::borrow::Cow; + /// + /// let s: Cow<str> = Cow::Borrowed("lorem"); + /// let x: Value = s.into(); + /// # } + /// ``` + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::Value; + /// use std::borrow::Cow; + /// + /// let s: Cow<str> = Cow::Owned("lorem".to_string()); + /// let x: Value = s.into(); + /// # } + /// ``` + fn from(f: Cow<'a, str>) -> Self { + Value::String(f.into_owned()) + } +} + +impl From<Map<String, Value>> for Value { + /// Convert map (with string keys) to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::{Map, Value}; + /// + /// let mut m = Map::new(); + /// m.insert("Lorem".to_string(), "ipsum".into()); + /// let x: Value = m.into(); + /// # } + /// ``` + fn from(f: Map<String, Value>) -> Self { + Value::Object(f) + } +} + +impl<T: Into<Value>> From<Vec<T>> for Value { + /// Convert a `Vec` to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::Value; + /// + /// let v = vec!["lorem", "ipsum", "dolor"]; + /// let x: Value = v.into(); + /// # } + /// ``` + fn from(f: Vec<T>) -> Self { + Value::Array(f.into_iter().map(Into::into).collect()) + } +} + +impl<'a, T: Clone + Into<Value>> From<&'a [T]> for Value { + /// Convert a slice to `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::Value; + /// + /// let v: &[&str] = &["lorem", "ipsum", "dolor"]; + /// let x: Value = v.into(); + /// # } + /// ``` + fn from(f: &'a [T]) -> Self { + Value::Array(f.into_iter().cloned().map(Into::into).collect()) + } +} + +impl<T: Into<Value>> ::std::iter::FromIterator<T> for Value { + /// Convert an iteratable type to a `Value` + /// + /// # Examples + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::Value; + /// + /// let v = std::iter::repeat(42).take(5); + /// let x: Value = v.collect(); + /// # } + /// ``` + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use serde_json::Value; + /// + /// let v: Vec<_> = vec!["lorem", "ipsum", "dolor"]; + /// let x: Value = v.into_iter().collect(); + /// # } + /// ``` + /// + /// ```rust + /// # extern crate serde_json; + /// # + /// # fn main() { + /// use std::iter::FromIterator; + /// use serde_json::Value; + /// + /// let x: Value = Value::from_iter(vec!["lorem", "ipsum", "dolor"]); + /// # } + /// ``` + fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { + Value::Array(iter.into_iter().map(Into::into).collect()) + } +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/value/index.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/value/index.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/value/index.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/value/index.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,284 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::fmt; +use std::ops; + +use super::Value; +use map::Map; + +/// A type that can be used to index into a `serde_json::Value`. +/// +/// The [`get`] and [`get_mut`] methods of `Value` accept any type that +/// implements `Index`, as does the [square-bracket indexing operator]. This +/// trait is implemented for strings which are used as the index into a JSON +/// map, and for `usize` which is used as the index into a JSON array. +/// +/// [`get`]: ../enum.Value.html#method.get +/// [`get_mut`]: ../enum.Value.html#method.get_mut +/// [square-bracket indexing operator]: ../enum.Value.html#impl-Index%3CI%3E +/// +/// This trait is sealed and cannot be implemented for types outside of +/// `serde_json`. +/// +/// # Examples +/// +/// ```rust +/// # #[macro_use] +/// # extern crate serde_json; +/// # +/// # fn main() { +/// let data = json!({ "inner": [1, 2, 3] }); +/// +/// // Data is a JSON map so it can be indexed with a string. +/// let inner = &data["inner"]; +/// +/// // Inner is a JSON array so it can be indexed with an integer. +/// let first = &inner[0]; +/// +/// assert_eq!(first, 1); +/// # } +/// ``` +pub trait Index: private::Sealed { + /// Return None if the key is not already in the array or object. + #[doc(hidden)] + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value>; + + /// Return None if the key is not already in the array or object. + #[doc(hidden)] + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value>; + + /// Panic if array index out of bounds. If key is not already in the object, + /// insert it with a value of null. Panic if Value is a type that cannot be + /// indexed into, except if Value is null then it can be treated as an empty + /// object. + #[doc(hidden)] + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value; +} + +impl Index for usize { + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + match *v { + Value::Array(ref vec) => vec.get(*self), + _ => None, + } + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + match *v { + Value::Array(ref mut vec) => vec.get_mut(*self), + _ => None, + } + } + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { + match *v { + Value::Array(ref mut vec) => { + let len = vec.len(); + vec.get_mut(*self) + .unwrap_or_else( + || { + panic!( + "cannot access index {} of JSON array of length {}", + self, + len + ) + }, + ) + } + _ => panic!("cannot access index {} of JSON {}", self, Type(v)), + } + } +} + +impl Index for str { + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + match *v { + Value::Object(ref map) => map.get(self), + _ => None, + } + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + match *v { + Value::Object(ref mut map) => map.get_mut(self), + _ => None, + } + } + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { + if let Value::Null = *v { + *v = Value::Object(Map::new()); + } + match *v { + Value::Object(ref mut map) => { + map.entry(self.to_owned()).or_insert(Value::Null) + } + _ => panic!("cannot access key {:?} in JSON {}", self, Type(v)), + } + } +} + +impl Index for String { + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + self[..].index_into(v) + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + self[..].index_into_mut(v) + } + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { + self[..].index_or_insert(v) + } +} + +impl<'a, T: ?Sized> Index for &'a T +where + T: Index, +{ + fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { + (**self).index_into(v) + } + fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { + (**self).index_into_mut(v) + } + fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { + (**self).index_or_insert(v) + } +} + +// Prevent users from implementing the Index trait. +mod private { + pub trait Sealed {} + impl Sealed for usize {} + impl Sealed for str {} + impl Sealed for String {} + impl<'a, T: ?Sized> Sealed for &'a T + where + T: Sealed, + { + } +} + +/// Used in panic messages. +struct Type<'a>(&'a Value); + +impl<'a> fmt::Display for Type<'a> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match *self.0 { + Value::Null => formatter.write_str("null"), + Value::Bool(_) => formatter.write_str("boolean"), + Value::Number(_) => formatter.write_str("number"), + Value::String(_) => formatter.write_str("string"), + Value::Array(_) => formatter.write_str("array"), + Value::Object(_) => formatter.write_str("object"), + } + } +} + +// The usual semantics of Index is to panic on invalid indexing. +// +// That said, the usual semantics are for things like Vec and BTreeMap which +// have different use cases than Value. If you are working with a Vec, you know +// that you are working with a Vec and you can get the len of the Vec and make +// sure your indices are within bounds. The Value use cases are more +// loosey-goosey. You got some JSON from an endpoint and you want to pull values +// out of it. Outside of this Index impl, you already have the option of using +// value.as_array() and working with the Vec directly, or matching on +// Value::Array and getting the Vec directly. The Index impl means you can skip +// that and index directly into the thing using a concise syntax. You don't have +// to check the type, you don't have to check the len, it is all about what you +// expect the Value to look like. +// +// Basically the use cases that would be well served by panicking here are +// better served by using one of the other approaches: get and get_mut, +// as_array, or match. The value of this impl is that it adds a way of working +// with Value that is not well served by the existing approaches: concise and +// careless and sometimes that is exactly what you want. +impl<I> ops::Index<I> for Value +where + I: Index, +{ + type Output = Value; + + /// Index into a `serde_json::Value` using the syntax `value[0]` or + /// `value["k"]`. + /// + /// Returns `Value::Null` if the type of `self` does not match the type of + /// the index, for example if the index is a string and `self` is an array + /// or a number. Also returns `Value::Null` if the given key does not exist + /// in the map or the given index is not within the bounds of the array. + /// + /// For retrieving deeply nested values, you should have a look at the + /// `Value::pointer` method. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let data = json!({ + /// "x": { + /// "y": ["z", "zz"] + /// } + /// }); + /// + /// assert_eq!(data["x"]["y"], json!(["z", "zz"])); + /// assert_eq!(data["x"]["y"][0], json!("z")); + /// + /// assert_eq!(data["a"], json!(null)); // returns null for undefined values + /// assert_eq!(data["a"]["b"], json!(null)); // does not panic + /// # } + /// ``` + fn index(&self, index: I) -> &Value { + static NULL: Value = Value::Null; + index.index_into(self).unwrap_or(&NULL) + } +} + +impl<I> ops::IndexMut<I> for Value +where + I: Index, +{ + /// Write into a `serde_json::Value` using the syntax `value[0] = ...` or + /// `value["k"] = ...`. + /// + /// If the index is a number, the value must be an array of length bigger + /// than the index. Indexing into a value that is not an array or an array + /// that is too small will panic. + /// + /// If the index is a string, the value must be an object or null which is + /// treated like an empty object. If the key is not already present in the + /// object, it will be inserted with a value of null. Indexing into a value + /// that is neither an object nor null will panic. + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let mut data = json!({ "x": 0 }); + /// + /// // replace an existing key + /// data["x"] = json!(1); + /// + /// // insert a new key + /// data["y"] = json!([false, false, false]); + /// + /// // replace an array value + /// data["y"][0] = json!(true); + /// + /// // inserted a deeply nested key + /// data["a"]["b"]["c"]["d"] = json!(true); + /// + /// println!("{}", data); + /// # } + /// ``` + fn index_mut(&mut self, index: I) -> &mut Value { + index.index_or_insert(self) + } +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/value/mod.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/value/mod.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/value/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/value/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1080 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! The Value enum, a loosely typed way of representing any valid JSON value. +//! +//! # Constructing JSON +//! +//! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` +//! objects with very natural JSON syntax. In order to use this macro, +//! `serde_json` needs to be imported with the `#[macro_use]` attribute. +//! +//! ```rust +//! #[macro_use] +//! extern crate serde_json; +//! +//! fn main() { +//! // The type of `john` is `serde_json::Value` +//! let john = json!({ +//! "name": "John Doe", +//! "age": 43, +//! "phones": [ +//! "+44 1234567", +//! "+44 2345678" +//! ] +//! }); +//! +//! println!("first phone number: {}", john["phones"][0]); +//! +//! // Convert to a string of JSON and print it out +//! println!("{}", john.to_string()); +//! } +//! ``` +//! +//! The `Value::to_string()` function converts a `serde_json::Value` into a +//! `String` of JSON text. +//! +//! One neat thing about the `json!` macro is that variables and expressions can +//! be interpolated directly into the JSON value as you are building it. Serde +//! will check at compile time that the value you are interpolating is able to +//! be represented as JSON. +//! +//! ```rust +//! # #[macro_use] +//! # extern crate serde_json; +//! # +//! # fn random_phone() -> u16 { 0 } +//! # +//! # fn main() { +//! let full_name = "John Doe"; +//! let age_last_year = 42; +//! +//! // The type of `john` is `serde_json::Value` +//! let john = json!({ +//! "name": full_name, +//! "age": age_last_year + 1, +//! "phones": [ +//! format!("+44 {}", random_phone()) +//! ] +//! }); +//! # let _ = john; +//! # } +//! ``` +//! +//! A string of JSON data can be parsed into a `serde_json::Value` by the +//! [`serde_json::from_str`][from_str] function. There is also +//! [`from_slice`][from_slice] for parsing from a byte slice &[u8] and +//! [`from_reader`][from_reader] for parsing from any `io::Read` like a File or +//! a TCP stream. +//! +//! ```rust +//! extern crate serde_json; +//! +//! use serde_json::{Value, Error}; +//! +//! fn untyped_example() -> Result<(), Error> { +//! // Some JSON input data as a &str. Maybe this comes from the user. +//! let data = r#"{ +//! "name": "John Doe", +//! "age": 43, +//! "phones": [ +//! "+44 1234567", +//! "+44 2345678" +//! ] +//! }"#; +//! +//! // Parse the string of data into serde_json::Value. +//! let v: Value = serde_json::from_str(data)?; +//! +//! // Access parts of the data by indexing with square brackets. +//! println!("Please call {} at the number {}", v["name"], v["phones"][0]); +//! +//! Ok(()) +//! } +//! # +//! # fn main() { +//! # untyped_example().unwrap(); +//! # } +//! ``` +//! +//! [macro]: https://docs.serde.rs/serde_json/macro.json.html +//! [from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html +//! [from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html +//! [from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html + +use std::fmt::{self, Debug}; +use std::i64; +use std::mem; +use std::str; + +use serde::ser::Serialize; +use serde::de::DeserializeOwned; + +use error::Error; +pub use map::Map; +pub use number::Number; + +pub use self::index::Index; + +use self::ser::Serializer; + +/// Represents any valid JSON value. +/// +/// See the `serde_json::value` module documentation for usage examples. +#[derive(Clone, PartialEq)] +pub enum Value { + /// Represents a JSON null value. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!(null); + /// # } + /// ``` + Null, + + /// Represents a JSON boolean. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!(true); + /// # } + /// ``` + Bool(bool), + + /// Represents a JSON number, whether integer or floating point. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!(12.5); + /// # } + /// ``` + Number(Number), + + /// Represents a JSON string. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!("a string"); + /// # } + /// ``` + String(String), + + /// Represents a JSON array. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!(["an", "array"]); + /// # } + /// ``` + Array(Vec<Value>), + + /// Represents a JSON object. + /// + /// By default the map is backed by a BTreeMap. Enable the `preserve_order` + /// feature of serde_json to use LinkedHashMap instead, which preserves + /// entries in the order they are inserted into the map. In particular, this + /// allows JSON data to be deserialized into a Value and serialized to a + /// string while retaining the order of map keys in the input. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "an": "object" }); + /// # } + /// ``` + Object(Map<String, Value>), +} + +impl Debug for Value { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + match *self { + Value::Null => { + formatter.debug_tuple("Null").finish() + } + Value::Bool(v) => { + formatter.debug_tuple("Bool").field(&v).finish() + } + Value::Number(ref v) => { + Debug::fmt(v, formatter) + } + Value::String(ref v) => { + formatter.debug_tuple("String").field(v).finish() + } + Value::Array(ref v) => { + formatter.debug_tuple("Array").field(v).finish() + } + Value::Object(ref v) => { + formatter.debug_tuple("Object").field(v).finish() + } + } + } +} + +fn parse_index(s: &str) -> Option<usize> { + if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) { + return None; + } + s.parse().ok() +} + +impl Value { + /// Index into a JSON array or map. A string index can be used to access a + /// value in a map, and a usize index can be used to access an element of an + /// array. + /// + /// Returns `None` if the type of `self` does not match the type of the + /// index, for example if the index is a string and `self` is an array or a + /// number. Also returns `None` if the given key does not exist in the map + /// or the given index is not within the bounds of the array. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let object = json!({ "A": 65, "B": 66, "C": 67 }); + /// assert_eq!(*object.get("A").unwrap(), json!(65)); + /// + /// let array = json!([ "A", "B", "C" ]); + /// assert_eq!(*array.get(2).unwrap(), json!("C")); + /// + /// assert_eq!(array.get("A"), None); + /// # } + /// ``` + /// + /// Square brackets can also be used to index into a value in a more concise + /// way. This returns `Value::Null` in cases where `get` would have returned + /// `None`. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let object = json!({ + /// "A": ["a", "á", "à"], + /// "B": ["b", "b́"], + /// "C": ["c", "ć", "ć̣", "ḉ"], + /// }); + /// assert_eq!(object["B"][0], json!("b")); + /// + /// assert_eq!(object["D"], json!(null)); + /// assert_eq!(object[0]["x"]["y"]["z"], json!(null)); + /// # } + /// ``` + pub fn get<I: Index>(&self, index: I) -> Option<&Value> { + index.index_into(self) + } + + /// Mutably index into a JSON array or map. A string index can be used to + /// access a value in a map, and a usize index can be used to access an + /// element of an array. + /// + /// Returns `None` if the type of `self` does not match the type of the + /// index, for example if the index is a string and `self` is an array or a + /// number. Also returns `None` if the given key does not exist in the map + /// or the given index is not within the bounds of the array. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let mut object = json!({ "A": 65, "B": 66, "C": 67 }); + /// *object.get_mut("A").unwrap() = json!(69); + /// + /// let mut array = json!([ "A", "B", "C" ]); + /// *array.get_mut(2).unwrap() = json!("D"); + /// # } + /// ``` + pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> { + index.index_into_mut(self) + } + + /// Returns true if the `Value` is an Object. Returns false otherwise. + /// + /// For any Value on which `is_object` returns true, `as_object` and + /// `as_object_mut` are guaranteed to return the map representation of the + /// object. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let obj = json!({ "a": { "nested": true }, "b": ["an", "array"] }); + /// + /// assert!(obj.is_object()); + /// assert!(obj["a"].is_object()); + /// + /// // array, not an object + /// assert!(!obj["b"].is_object()); + /// # } + /// ``` + pub fn is_object(&self) -> bool { + self.as_object().is_some() + } + + /// If the `Value` is an Object, returns the associated Map. Returns None + /// otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": { "nested": true }, "b": ["an", "array"] }); + /// + /// // The length of `{"nested": true}` is 1 entry. + /// assert_eq!(v["a"].as_object().unwrap().len(), 1); + /// + /// // The array `["an", "array"]` is not an object. + /// assert_eq!(v["b"].as_object(), None); + /// # } + /// ``` + pub fn as_object(&self) -> Option<&Map<String, Value>> { + match *self { + Value::Object(ref map) => Some(map), + _ => None, + } + } + + /// If the `Value` is an Object, returns the associated mutable Map. + /// Returns None otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let mut v = json!({ "a": { "nested": true } }); + /// + /// v["a"].as_object_mut().unwrap().clear(); + /// assert_eq!(v, json!({ "a": {} })); + /// # } + /// + /// ``` + pub fn as_object_mut(&mut self) -> Option<&mut Map<String, Value>> { + match *self { + Value::Object(ref mut map) => Some(map), + _ => None, + } + } + + /// Returns true if the `Value` is an Array. Returns false otherwise. + /// + /// For any Value on which `is_array` returns true, `as_array` and + /// `as_array_mut` are guaranteed to return the vector representing the + /// array. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let obj = json!({ "a": ["an", "array"], "b": { "an": "object" } }); + /// + /// assert!(obj["a"].is_array()); + /// + /// // an object, not an array + /// assert!(!obj["b"].is_array()); + /// # } + /// ``` + pub fn is_array(&self) -> bool { + self.as_array().is_some() + } + + /// If the `Value` is an Array, returns the associated vector. Returns None + /// otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": ["an", "array"], "b": { "an": "object" } }); + /// + /// // The length of `["an", "array"]` is 2 elements. + /// assert_eq!(v["a"].as_array().unwrap().len(), 2); + /// + /// // The object `{"an": "object"}` is not an array. + /// assert_eq!(v["b"].as_array(), None); + /// # } + /// ``` + pub fn as_array(&self) -> Option<&Vec<Value>> { + match *self { + Value::Array(ref array) => Some(&*array), + _ => None, + } + } + + /// If the `Value` is an Array, returns the associated mutable vector. + /// Returns None otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let mut v = json!({ "a": ["an", "array"] }); + /// + /// v["a"].as_array_mut().unwrap().clear(); + /// assert_eq!(v, json!({ "a": [] })); + /// # } + /// ``` + pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> { + match *self { + Value::Array(ref mut list) => Some(list), + _ => None, + } + } + + /// Returns true if the `Value` is a String. Returns false otherwise. + /// + /// For any Value on which `is_string` returns true, `as_str` is guaranteed + /// to return the string slice. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": "some string", "b": false }); + /// + /// assert!(v["a"].is_string()); + /// + /// // The boolean `false` is not a string. + /// assert!(!v["b"].is_string()); + /// # } + /// ``` + pub fn is_string(&self) -> bool { + self.as_str().is_some() + } + + /// If the `Value` is a String, returns the associated str. Returns None + /// otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": "some string", "b": false }); + /// + /// assert_eq!(v["a"].as_str(), Some("some string")); + /// + /// // The boolean `false` is not a string. + /// assert_eq!(v["b"].as_str(), None); + /// + /// // JSON values are printed in JSON representation, so strings are in quotes. + /// // + /// // The value is: "some string" + /// println!("The value is: {}", v["a"]); + /// + /// // Rust strings are printed without quotes. + /// // + /// // The value is: some string + /// println!("The value is: {}", v["a"].as_str().unwrap()); + /// # } + /// ``` + pub fn as_str(&self) -> Option<&str> { + match *self { + Value::String(ref s) => Some(s), + _ => None, + } + } + + /// Returns true if the `Value` is a Number. Returns false otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": 1, "b": "2" }); + /// + /// assert!(v["a"].is_number()); + /// + /// // The string `"2"` is a string, not a number. + /// assert!(!v["b"].is_number()); + /// # } + /// ``` + pub fn is_number(&self) -> bool { + match *self { + Value::Number(_) => true, + _ => false, + } + } + + /// Returns true if the `Value` is an integer between `i64::MIN` and + /// `i64::MAX`. + /// + /// For any Value on which `is_i64` returns true, `as_i64` is guaranteed to + /// return the integer value. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # use std::i64; + /// # + /// # fn main() { + /// let big = i64::MAX as u64 + 10; + /// let v = json!({ "a": 64, "b": big, "c": 256.0 }); + /// + /// assert!(v["a"].is_i64()); + /// + /// // Greater than i64::MAX. + /// assert!(!v["b"].is_i64()); + /// + /// // Numbers with a decimal point are not considered integers. + /// assert!(!v["c"].is_i64()); + /// # } + /// ``` + pub fn is_i64(&self) -> bool { + match *self { + Value::Number(ref n) => n.is_i64(), + _ => false, + } + } + + /// Returns true if the `Value` is an integer between zero and `u64::MAX`. + /// + /// For any Value on which `is_u64` returns true, `as_u64` is guaranteed to + /// return the integer value. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": 64, "b": -64, "c": 256.0 }); + /// + /// assert!(v["a"].is_u64()); + /// + /// // Negative integer. + /// assert!(!v["b"].is_u64()); + /// + /// // Numbers with a decimal point are not considered integers. + /// assert!(!v["c"].is_u64()); + /// # } + /// ``` + pub fn is_u64(&self) -> bool { + match *self { + Value::Number(ref n) => n.is_u64(), + _ => false, + } + } + + /// Returns true if the `Value` is a number that can be represented by f64. + /// + /// For any Value on which `is_f64` returns true, `as_f64` is guaranteed to + /// return the floating point value. + /// + /// Currently this function returns true if and only if both `is_i64` and + /// `is_u64` return false but this is not a guarantee in the future. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": 256.0, "b": 64, "c": -64 }); + /// + /// assert!(v["a"].is_f64()); + /// + /// // Integers. + /// assert!(!v["b"].is_f64()); + /// assert!(!v["c"].is_f64()); + /// # } + /// ``` + pub fn is_f64(&self) -> bool { + match *self { + Value::Number(ref n) => n.is_f64(), + _ => false, + } + } + + /// If the `Value` is an integer, represent it as i64 if possible. Returns + /// None otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # use std::i64; + /// # + /// # fn main() { + /// let big = i64::MAX as u64 + 10; + /// let v = json!({ "a": 64, "b": big, "c": 256.0 }); + /// + /// assert_eq!(v["a"].as_i64(), Some(64)); + /// assert_eq!(v["b"].as_i64(), None); + /// assert_eq!(v["c"].as_i64(), None); + /// # } + /// ``` + pub fn as_i64(&self) -> Option<i64> { + match *self { + Value::Number(ref n) => n.as_i64(), + _ => None, + } + } + + /// If the `Value` is an integer, represent it as u64 if possible. Returns + /// None otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": 64, "b": -64, "c": 256.0 }); + /// + /// assert_eq!(v["a"].as_u64(), Some(64)); + /// assert_eq!(v["b"].as_u64(), None); + /// assert_eq!(v["c"].as_u64(), None); + /// # } + /// ``` + pub fn as_u64(&self) -> Option<u64> { + match *self { + Value::Number(ref n) => n.as_u64(), + _ => None, + } + } + + /// If the `Value` is a number, represent it as f64 if possible. Returns + /// None otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": 256.0, "b": 64, "c": -64 }); + /// + /// assert_eq!(v["a"].as_f64(), Some(256.0)); + /// assert_eq!(v["b"].as_f64(), Some(64.0)); + /// assert_eq!(v["c"].as_f64(), Some(-64.0)); + /// # } + /// ``` + pub fn as_f64(&self) -> Option<f64> { + match *self { + Value::Number(ref n) => n.as_f64(), + _ => None, + } + } + + /// Returns true if the `Value` is a Boolean. Returns false otherwise. + /// + /// For any Value on which `is_boolean` returns true, `as_bool` is + /// guaranteed to return the boolean value. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": false, "b": "false" }); + /// + /// assert!(v["a"].is_boolean()); + /// + /// // The string `"false"` is a string, not a boolean. + /// assert!(!v["b"].is_boolean()); + /// # } + /// ``` + pub fn is_boolean(&self) -> bool { + self.as_bool().is_some() + } + + /// If the `Value` is a Boolean, returns the associated bool. Returns None + /// otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": false, "b": "false" }); + /// + /// assert_eq!(v["a"].as_bool(), Some(false)); + /// + /// // The string `"false"` is a string, not a boolean. + /// assert_eq!(v["b"].as_bool(), None); + /// # } + /// ``` + pub fn as_bool(&self) -> Option<bool> { + match *self { + Value::Bool(b) => Some(b), + _ => None, + } + } + + /// Returns true if the `Value` is a Null. Returns false otherwise. + /// + /// For any Value on which `is_null` returns true, `as_null` is guaranteed + /// to return `Some(())`. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": null, "b": false }); + /// + /// assert!(v["a"].is_null()); + /// + /// // The boolean `false` is not null. + /// assert!(!v["b"].is_null()); + /// # } + /// ``` + pub fn is_null(&self) -> bool { + self.as_null().is_some() + } + + /// If the `Value` is a Null, returns (). Returns None otherwise. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let v = json!({ "a": null, "b": false }); + /// + /// assert_eq!(v["a"].as_null(), Some(())); + /// + /// // The boolean `false` is not null. + /// assert_eq!(v["b"].as_null(), None); + /// # } + /// ``` + pub fn as_null(&self) -> Option<()> { + match *self { + Value::Null => Some(()), + _ => None, + } + } + + /// Looks up a value by a JSON Pointer. + /// + /// JSON Pointer defines a string syntax for identifying a specific value + /// within a JavaScript Object Notation (JSON) document. + /// + /// A Pointer is a Unicode string with the reference tokens separated by `/`. + /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The + /// addressed value is returned and if there is no such value `None` is + /// returned. + /// + /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901). + /// + /// # Examples + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let data = json!({ + /// "x": { + /// "y": ["z", "zz"] + /// } + /// }); + /// + /// assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz")); + /// assert_eq!(data.pointer("/a/b/c"), None); + /// # } + /// ``` + pub fn pointer<'a>(&'a self, pointer: &str) -> Option<&'a Value> { + if pointer == "" { + return Some(self); + } + if !pointer.starts_with('/') { + return None; + } + let tokens = pointer + .split('/') + .skip(1) + .map(|x| x.replace("~1", "/").replace("~0", "~")); + let mut target = self; + + for token in tokens { + let target_opt = match *target { + Value::Object(ref map) => map.get(&token), + Value::Array(ref list) => parse_index(&token).and_then(|x| list.get(x)), + _ => return None, + }; + if let Some(t) = target_opt { + target = t; + } else { + return None; + } + } + Some(target) + } + + /// Looks up a value by a JSON Pointer and returns a mutable reference to + /// that value. + /// + /// JSON Pointer defines a string syntax for identifying a specific value + /// within a JavaScript Object Notation (JSON) document. + /// + /// A Pointer is a Unicode string with the reference tokens separated by `/`. + /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The + /// addressed value is returned and if there is no such value `None` is + /// returned. + /// + /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901). + /// + /// # Example of Use + /// + /// ```rust + /// extern crate serde_json; + /// + /// use serde_json::Value; + /// + /// fn main() { + /// let s = r#"{"x": 1.0, "y": 2.0}"#; + /// let mut value: Value = serde_json::from_str(s).unwrap(); + /// + /// // Check value using read-only pointer + /// assert_eq!(value.pointer("/x"), Some(&1.0.into())); + /// // Change value with direct assignment + /// *value.pointer_mut("/x").unwrap() = 1.5.into(); + /// // Check that new value was written + /// assert_eq!(value.pointer("/x"), Some(&1.5.into())); + /// + /// // "Steal" ownership of a value. Can replace with any valid Value. + /// let old_x = value.pointer_mut("/x").map(Value::take).unwrap(); + /// assert_eq!(old_x, 1.5); + /// assert_eq!(value.pointer("/x").unwrap(), &Value::Null); + /// } + /// ``` + pub fn pointer_mut<'a>(&'a mut self, pointer: &str) -> Option<&'a mut Value> { + if pointer == "" { + return Some(self); + } + if !pointer.starts_with('/') { + return None; + } + let tokens = pointer + .split('/') + .skip(1) + .map(|x| x.replace("~1", "/").replace("~0", "~")); + let mut target = self; + + for token in tokens { + // borrow checker gets confused about `target` being mutably borrowed too many times because of the loop + // this once-per-loop binding makes the scope clearer and circumvents the error + let target_once = target; + let target_opt = match *target_once { + Value::Object(ref mut map) => map.get_mut(&token), + Value::Array(ref mut list) => { + parse_index(&token).and_then(move |x| list.get_mut(x)) + } + _ => return None, + }; + if let Some(t) = target_opt { + target = t; + } else { + return None; + } + } + Some(target) + } + + /// Takes the value out of the `Value`, leaving a `Null` in its place. + /// + /// ```rust + /// # #[macro_use] + /// # extern crate serde_json; + /// # + /// # fn main() { + /// let mut v = json!({ "x": "y" }); + /// assert_eq!(v["x"].take(), json!("y")); + /// assert_eq!(v, json!({ "x": null })); + /// # } + /// ``` + pub fn take(&mut self) -> Value { + mem::replace(self, Value::Null) + } +} + +/// The default value is `Value::Null`. +/// +/// This is useful for handling omitted `Value` fields when deserializing. +/// +/// # Examples +/// +/// ```rust +/// # #[macro_use] +/// # extern crate serde_derive; +/// # +/// # extern crate serde_json; +/// # +/// use serde_json::Value; +/// +/// #[derive(Deserialize)] +/// struct Settings { +/// level: i32, +/// #[serde(default)] +/// extras: Value, +/// } +/// +/// # fn try_main() -> Result<(), serde_json::Error> { +/// let data = r#" { "level": 42 } "#; +/// let s: Settings = serde_json::from_str(data)?; +/// +/// assert_eq!(s.level, 42); +/// assert_eq!(s.extras, Value::Null); +/// # +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # try_main().unwrap() +/// # } +/// ``` +impl Default for Value { + fn default() -> Value { + Value::Null + } +} + +mod index; +mod partial_eq; +mod from; +mod ser; +mod de; + +/// Convert a `T` into `serde_json::Value` which is an enum that can represent +/// any valid JSON data. +/// +/// ```rust +/// extern crate serde; +/// +/// #[macro_use] +/// extern crate serde_derive; +/// +/// #[macro_use] +/// extern crate serde_json; +/// +/// use std::error::Error; +/// +/// #[derive(Serialize)] +/// struct User { +/// fingerprint: String, +/// location: String, +/// } +/// +/// fn compare_json_values() -> Result<(), Box<Error>> { +/// let u = User { +/// fingerprint: "0xF9BA143B95FF6D82".to_owned(), +/// location: "Menlo Park, CA".to_owned(), +/// }; +/// +/// // The type of `expected` is `serde_json::Value` +/// let expected = json!({ +/// "fingerprint": "0xF9BA143B95FF6D82", +/// "location": "Menlo Park, CA", +/// }); +/// +/// let v = serde_json::to_value(u).unwrap(); +/// assert_eq!(v, expected); +/// +/// Ok(()) +/// } +/// # +/// # fn main() { +/// # compare_json_values().unwrap(); +/// # } +/// ``` +/// +/// # Errors +/// +/// This conversion can fail if `T`'s implementation of `Serialize` decides to +/// fail, or if `T` contains a map with non-string keys. +/// +/// ```rust +/// extern crate serde_json; +/// +/// use std::collections::BTreeMap; +/// +/// fn main() { +/// // The keys in this map are vectors, not strings. +/// let mut map = BTreeMap::new(); +/// map.insert(vec![32, 64], "x86"); +/// +/// println!("{}", serde_json::to_value(map).unwrap_err()); +/// } +/// ``` +// Taking by value is more friendly to iterator adapters, option and result +// consumers, etc. See https://github.com/serde-rs/json/pull/149. +pub fn to_value<T>(value: T) -> Result<Value, Error> +where + T: Serialize, +{ + value.serialize(Serializer) +} + +/// Interpret a `serde_json::Value` as an instance of type `T`. +/// +/// This conversion can fail if the structure of the Value does not match the +/// structure expected by `T`, for example if `T` is a struct type but the Value +/// contains something other than a JSON map. It can also fail if the structure +/// is correct but `T`'s implementation of `Deserialize` decides that something +/// is wrong with the data, for example required struct fields are missing from +/// the JSON map or some number is too big to fit in the expected primitive +/// type. +/// +/// ```rust +/// #[macro_use] +/// extern crate serde_json; +/// +/// #[macro_use] +/// extern crate serde_derive; +/// +/// extern crate serde; +/// +/// #[derive(Deserialize, Debug)] +/// struct User { +/// fingerprint: String, +/// location: String, +/// } +/// +/// fn main() { +/// // The type of `j` is `serde_json::Value` +/// let j = json!({ +/// "fingerprint": "0xF9BA143B95FF6D82", +/// "location": "Menlo Park, CA" +/// }); +/// +/// let u: User = serde_json::from_value(j).unwrap(); +/// println!("{:#?}", u); +/// } +/// ``` +pub fn from_value<T>(value: Value) -> Result<T, Error> +where + T: DeserializeOwned, +{ + T::deserialize(value) +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/value/partial_eq.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/value/partial_eq.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/value/partial_eq.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/value/partial_eq.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,103 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use super::Value; + +fn eq_i64(value: &Value, other: i64) -> bool { + value.as_i64().map_or(false, |i| i == other) +} + +fn eq_u64(value: &Value, other: u64) -> bool { + value.as_u64().map_or(false, |i| i == other) +} + +fn eq_f64(value: &Value, other: f64) -> bool { + value.as_f64().map_or(false, |i| i == other) +} + +fn eq_bool(value: &Value, other: bool) -> bool { + value.as_bool().map_or(false, |i| i == other) +} + +fn eq_str(value: &Value, other: &str) -> bool { + value.as_str().map_or(false, |i| i == other) +} + +impl PartialEq<str> for Value { + fn eq(&self, other: &str) -> bool { + eq_str(self, other) + } +} + +impl<'a> PartialEq<&'a str> for Value { + fn eq(&self, other: &&str) -> bool { + eq_str(self, *other) + } +} + +impl PartialEq<Value> for str { + fn eq(&self, other: &Value) -> bool { + eq_str(other, self) + } +} + +impl<'a> PartialEq<Value> for &'a str { + fn eq(&self, other: &Value) -> bool { + eq_str(other, *self) + } +} + +impl PartialEq<String> for Value { + fn eq(&self, other: &String) -> bool { + eq_str(self, other.as_str()) + } +} + + +impl PartialEq<Value> for String { + fn eq(&self, other: &Value) -> bool { + eq_str(other, self.as_str()) + } +} + +macro_rules! partialeq_numeric { + ($($eq:ident [$($ty:ty)*])*) => { + $($( + impl PartialEq<$ty> for Value { + fn eq(&self, other: &$ty) -> bool { + $eq(self, *other as _) + } + } + + impl PartialEq<Value> for $ty { + fn eq(&self, other: &Value) -> bool { + $eq(other, *self as _) + } + } + + impl<'a> PartialEq<$ty> for &'a Value { + fn eq(&self, other: &$ty) -> bool { + $eq(*self, *other as _) + } + } + + impl<'a> PartialEq<$ty> for &'a mut Value { + fn eq(&self, other: &$ty) -> bool { + $eq(*self, *other as _) + } + } + )*)* + } +} + +partialeq_numeric! { + eq_i64[i8 i16 i32 i64 isize] + eq_u64[u8 u16 u32 u64 usize] + eq_f64[f32 f64] + eq_bool[bool] +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.13/src/value/ser.rs cargo-0.26.0/vendor/serde_json-1.0.13/src/value/ser.rs --- cargo-0.25.0/vendor/serde_json-1.0.13/src/value/ser.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.13/src/value/ser.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,817 @@ +// Copyright 2017 Serde Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use serde::{self, Serialize}; +use serde::ser::{Impossible}; + +use error::{Error, ErrorCode}; +use map::Map; +use number::Number; +use value::{Value, to_value}; + +#[cfg(feature = "arbitrary_precision")] +use serde::ser; + +#[cfg(feature = "arbitrary_precision")] +use number::{SERDE_STRUCT_NAME, SERDE_STRUCT_FIELD_NAME}; + +impl Serialize for Value { + #[inline] + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: ::serde::Serializer, + { + match *self { + Value::Null => serializer.serialize_unit(), + Value::Bool(b) => serializer.serialize_bool(b), + Value::Number(ref n) => n.serialize(serializer), + Value::String(ref s) => serializer.serialize_str(s), + Value::Array(ref v) => v.serialize(serializer), + Value::Object(ref m) => { + use serde::ser::SerializeMap; + let mut map = try!(serializer.serialize_map(Some(m.len()))); + for (k, v) in m { + try!(map.serialize_key(k)); + try!(map.serialize_value(v)); + } + map.end() + } + } + } +} + +pub struct Serializer; + +impl serde::Serializer for Serializer { + type Ok = Value; + type Error = Error; + + type SerializeSeq = SerializeVec; + type SerializeTuple = SerializeVec; + type SerializeTupleStruct = SerializeVec; + type SerializeTupleVariant = SerializeTupleVariant; + type SerializeMap = SerializeMap; + type SerializeStruct = SerializeMap; + type SerializeStructVariant = SerializeStructVariant; + + #[inline] + fn serialize_bool(self, value: bool) -> Result<Value, Error> { + Ok(Value::Bool(value)) + } + + #[inline] + fn serialize_i8(self, value: i8) -> Result<Value, Error> { + self.serialize_i64(value as i64) + } + + #[inline] + fn serialize_i16(self, value: i16) -> Result<Value, Error> { + self.serialize_i64(value as i64) + } + + #[inline] + fn serialize_i32(self, value: i32) -> Result<Value, Error> { + self.serialize_i64(value as i64) + } + + fn serialize_i64(self, value: i64) -> Result<Value, Error> { + Ok(Value::Number(value.into())) + } + + #[inline] + fn serialize_u8(self, value: u8) -> Result<Value, Error> { + self.serialize_u64(value as u64) + } + + #[inline] + fn serialize_u16(self, value: u16) -> Result<Value, Error> { + self.serialize_u64(value as u64) + } + + #[inline] + fn serialize_u32(self, value: u32) -> Result<Value, Error> { + self.serialize_u64(value as u64) + } + + #[inline] + fn serialize_u64(self, value: u64) -> Result<Value, Error> { + Ok(Value::Number(value.into())) + } + + #[inline] + fn serialize_f32(self, value: f32) -> Result<Value, Error> { + self.serialize_f64(value as f64) + } + + #[inline] + fn serialize_f64(self, value: f64) -> Result<Value, Error> { + Ok(Number::from_f64(value).map_or(Value::Null, Value::Number)) + } + + #[inline] + fn serialize_char(self, value: char) -> Result<Value, Error> { + let mut s = String::new(); + s.push(value); + self.serialize_str(&s) + } + + #[inline] + fn serialize_str(self, value: &str) -> Result<Value, Error> { + Ok(Value::String(value.to_owned())) + } + + fn serialize_bytes(self, value: &[u8]) -> Result<Value, Error> { + let vec = value.iter().map(|&b| Value::Number(b.into())).collect(); + Ok(Value::Array(vec)) + } + + #[inline] + fn serialize_unit(self) -> Result<Value, Error> { + Ok(Value::Null) + } + + #[inline] + fn serialize_unit_struct(self, _name: &'static str) -> Result<Value, Error> { + self.serialize_unit() + } + + #[inline] + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + ) -> Result<Value, Error> { + self.serialize_str(variant) + } + + #[inline] + fn serialize_newtype_struct<T: ?Sized>( + self, + _name: &'static str, + value: &T, + ) -> Result<Value, Error> + where + T: Serialize, + { + value.serialize(self) + } + + fn serialize_newtype_variant<T: ?Sized>( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result<Value, Error> + where + T: Serialize, + { + let mut values = Map::new(); + values.insert(String::from(variant), try!(to_value(&value))); + Ok(Value::Object(values)) + } + + #[inline] + fn serialize_none(self) -> Result<Value, Error> { + self.serialize_unit() + } + + #[inline] + fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, Error> + where + T: Serialize, + { + value.serialize(self) + } + + fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> { + Ok(SerializeVec { vec: Vec::with_capacity(len.unwrap_or(0)) }) + } + + fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Error> { + self.serialize_seq(Some(len)) + } + + fn serialize_tuple_struct( + self, + _name: &'static str, + len: usize, + ) -> Result<Self::SerializeTupleStruct, Error> { + self.serialize_seq(Some(len)) + } + + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + len: usize, + ) -> Result<Self::SerializeTupleVariant, Error> { + Ok( + SerializeTupleVariant { + name: String::from(variant), + vec: Vec::with_capacity(len), + }, + ) + } + + fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> { + Ok( + SerializeMap::Map { + map: Map::new(), + next_key: None, + }, + ) + } + + #[cfg(not(feature = "arbitrary_precision"))] + fn serialize_struct( + self, + _name: &'static str, + len: usize, + ) -> Result<Self::SerializeStruct, Error> { + self.serialize_map(Some(len)) + } + + #[cfg(feature = "arbitrary_precision")] + fn serialize_struct( + self, + name: &'static str, + len: usize, + ) -> Result<Self::SerializeStruct, Error> { + if name == SERDE_STRUCT_NAME { + Ok(SerializeMap::Number { out_value: None }) + } else { + self.serialize_map(Some(len)) + } + } + + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + _len: usize, + ) -> Result<Self::SerializeStructVariant, Error> { + Ok( + SerializeStructVariant { + name: String::from(variant), + map: Map::new(), + }, + ) + } +} + +pub struct SerializeVec { + vec: Vec<Value>, +} + +pub struct SerializeTupleVariant { + name: String, + vec: Vec<Value>, +} + +pub enum SerializeMap { + Map { + map: Map<String, Value>, + next_key: Option<String>, + }, + #[cfg(feature = "arbitrary_precision")] + Number { + out_value: Option<Value> + }, +} + +pub struct SerializeStructVariant { + name: String, + map: Map<String, Value>, +} + +impl serde::ser::SerializeSeq for SerializeVec { + type Ok = Value; + type Error = Error; + + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where + T: Serialize, + { + self.vec.push(try!(to_value(&value))); + Ok(()) + } + + fn end(self) -> Result<Value, Error> { + Ok(Value::Array(self.vec)) + } +} + +impl serde::ser::SerializeTuple for SerializeVec { + type Ok = Value; + type Error = Error; + + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where + T: Serialize, + { + serde::ser::SerializeSeq::serialize_element(self, value) + } + + fn end(self) -> Result<Value, Error> { + serde::ser::SerializeSeq::end(self) + } +} + +impl serde::ser::SerializeTupleStruct for SerializeVec { + type Ok = Value; + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where + T: Serialize, + { + serde::ser::SerializeSeq::serialize_element(self, value) + } + + fn end(self) -> Result<Value, Error> { + serde::ser::SerializeSeq::end(self) + } +} + +impl serde::ser::SerializeTupleVariant for SerializeTupleVariant { + type Ok = Value; + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where + T: Serialize, + { + self.vec.push(try!(to_value(&value))); + Ok(()) + } + + fn end(self) -> Result<Value, Error> { + let mut object = Map::new(); + + object.insert(self.name, Value::Array(self.vec)); + + Ok(Value::Object(object)) + } +} + +impl serde::ser::SerializeMap for SerializeMap { + type Ok = Value; + type Error = Error; + + fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Error> + where + T: Serialize, + { + match *self { + SerializeMap::Map { ref mut next_key, .. } => { + *next_key = Some(try!(key.serialize(MapKeySerializer))); + Ok(()) + }, + #[cfg(feature = "arbitrary_precision")] + SerializeMap::Number { .. } => unreachable!(), + } + } + + fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where + T: Serialize, + { + match *self { + SerializeMap::Map { ref mut map, ref mut next_key } => { + let key = next_key.take(); + // Panic because this indicates a bug in the program rather than an + // expected failure. + let key = key.expect("serialize_value called before serialize_key"); + map.insert(key, try!(to_value(&value))); + Ok(()) + }, + #[cfg(feature = "arbitrary_precision")] + SerializeMap::Number { .. } => unreachable!(), + } + } + + fn end(self) -> Result<Value, Error> { + match self { + SerializeMap::Map { map, .. } => Ok(Value::Object(map)), + #[cfg(feature = "arbitrary_precision")] + SerializeMap::Number { .. } => unreachable!(), + } + } +} + +struct MapKeySerializer; + +fn key_must_be_a_string() -> Error { + Error::syntax(ErrorCode::KeyMustBeAString, 0, 0) +} + +impl serde::Serializer for MapKeySerializer { + type Ok = String; + type Error = Error; + + type SerializeSeq = Impossible<String, Error>; + type SerializeTuple = Impossible<String, Error>; + type SerializeTupleStruct = Impossible<String, Error>; + type SerializeTupleVariant = Impossible<String, Error>; + type SerializeMap = Impossible<String, Error>; + type SerializeStruct = Impossible<String, Error>; + type SerializeStructVariant = Impossible<String, Error>; + + #[inline] + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str + ) -> Result<Self::Ok, Self::Error> { + Ok(variant.to_owned()) + } + + #[inline] + fn serialize_newtype_struct<T: ?Sized>( + self, + _name: &'static str, + value: &T + ) -> Result<Self::Ok, Self::Error> + where T: Serialize, + { + value.serialize(self) + } + + fn serialize_bool(self, _value: bool) -> Result<Self::Ok, Self::Error> { + Err(key_must_be_a_string()) + } + + fn serialize_i8(self, value: i8) -> Result<Self::Ok, Self::Error> { + Ok(value.to_string()) + } + + fn serialize_i16(self, value: i16) -> Result<Self::Ok, Self::Error> { + Ok(value.to_string()) + } + + fn serialize_i32(self, value: i32) -> Result<Self::Ok, Self::Error> { + Ok(value.to_string()) + } + + fn serialize_i64(self, value: i64) -> Result<Self::Ok, Self::Error> { + Ok(value.to_string()) + } + + fn serialize_u8(self, value: u8) -> Result<Self::Ok, Self::Error> { + Ok(value.to_string()) + } + + fn serialize_u16(self, value: u16) -> Result<Self::Ok, Self::Error> { + Ok(value.to_string()) + } + + fn serialize_u32(self, value: u32) -> Result<Self::Ok, Self::Error> { + Ok(value.to_string()) + } + + fn serialize_u64(self, value: u64) -> Result<Self::Ok, Self::Error> { + Ok(value.to_string()) + } + + fn serialize_f32(self, _value: f32) -> Result<Self::Ok, Self::Error> { + Err(key_must_be_a_string()) + } + + fn serialize_f64(self, _value: f64) -> Result<Self::Ok, Self::Error> { + Err(key_must_be_a_string()) + } + + #[inline] + fn serialize_char(self, value: char) -> Result<Self::Ok, Self::Error> { + Ok({ + let mut s = String::new(); + s.push(value); + s + }) + } + + #[inline] + fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> { + Ok(value.to_owned()) + } + + fn serialize_bytes(self, _value: &[u8]) -> Result<Self::Ok, Self::Error> { + Err(key_must_be_a_string()) + } + + fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { + Err(key_must_be_a_string()) + } + + fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> { + Err(key_must_be_a_string()) + } + + fn serialize_newtype_variant<T: ?Sized>( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T + ) -> Result<Self::Ok, Self::Error> + where T: Serialize, + { + Err(key_must_be_a_string()) + } + + fn serialize_none(self) -> Result<Self::Ok, Self::Error> { + Err(key_must_be_a_string()) + } + + fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok, Self::Error> + where + T: Serialize, + { + Err(key_must_be_a_string()) + } + + fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> { + Err(key_must_be_a_string()) + } + + fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> { + Err(key_must_be_a_string()) + } + + fn serialize_tuple_struct( + self, + _name: &'static str, + _len: usize + ) -> Result<Self::SerializeTupleStruct, Self::Error> { + Err(key_must_be_a_string()) + } + + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize + ) -> Result<Self::SerializeTupleVariant, Self::Error> { + Err(key_must_be_a_string()) + } + + fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> { + Err(key_must_be_a_string()) + } + + fn serialize_struct( + self, + _name: &'static str, + _len: usize + ) -> Result<Self::SerializeStruct, Self::Error> { + Err(key_must_be_a_string()) + } + + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize + ) -> Result<Self::SerializeStructVariant, Self::Error> { + Err(key_must_be_a_string()) + } +} + +impl serde::ser::SerializeStruct for SerializeMap { + type Ok = Value; + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> + where + T: Serialize, + { + match *self { + SerializeMap::Map { .. } => { + try!(serde::ser::SerializeMap::serialize_key(self, key)); + serde::ser::SerializeMap::serialize_value(self, value) + }, + #[cfg(feature = "arbitrary_precision")] + SerializeMap::Number { ref mut out_value } => { + if key == SERDE_STRUCT_FIELD_NAME { + *out_value = Some(value.serialize(NumberValueEmitter)?); + Ok(()) + } else { + Err(invalid_number()) + } + }, + } + } + + fn end(self) -> Result<Value, Error> { + match self { + SerializeMap::Map { .. } => serde::ser::SerializeMap::end(self), + #[cfg(feature = "arbitrary_precision")] + SerializeMap::Number { out_value, .. } => Ok(out_value.expect("number value was not emitted")), + } + } +} + +impl serde::ser::SerializeStructVariant for SerializeStructVariant { + type Ok = Value; + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> + where + T: Serialize, + { + self.map + .insert(String::from(key), try!(to_value(&value))); + Ok(()) + } + + fn end(self) -> Result<Value, Error> { + let mut object = Map::new(); + + object.insert(self.name, Value::Object(self.map)); + + Ok(Value::Object(object)) + } +} + +#[cfg(feature = "arbitrary_precision")] +struct NumberValueEmitter; + +#[cfg(feature = "arbitrary_precision")] +fn invalid_number() -> Error { + Error::syntax(ErrorCode::InvalidNumber, 0, 0) +} + +#[cfg(feature = "arbitrary_precision")] +impl ser::Serializer for NumberValueEmitter { + type Ok = Value; + type Error = Error; + + type SerializeSeq = Impossible<Value, Error>; + type SerializeTuple = Impossible<Value, Error>; + type SerializeTupleStruct = Impossible<Value, Error>; + type SerializeTupleVariant = Impossible<Value, Error>; + type SerializeMap = Impossible<Value, Error>; + type SerializeStruct = Impossible<Value, Error>; + type SerializeStructVariant = Impossible<Value, Error>; + + fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> { + let n = try!(value.to_owned().parse()); + Ok(Value::Number(n)) + } + + fn serialize_bytes(self, _value: &[u8]) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_none(self) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<Self::Ok, Self::Error> + where + T: Serialize, + { + Err(invalid_number()) + } + + fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_unit_struct(self, + _name: &'static str) + -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_unit_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str) + -> Result<Self::Ok, Self::Error> { + Err(invalid_number()) + } + + fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, _value: &T) + -> Result<Self::Ok, Self::Error> + where + T: Serialize, + { + Err(invalid_number()) + } + + fn serialize_newtype_variant<T: ?Sized>(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T) + -> Result<Self::Ok, Self::Error> + where + T: Serialize, + { + Err(invalid_number()) + } + + fn serialize_seq(self, _len: Option<usize>) + -> Result<Self::SerializeSeq, Self::Error> { + Err(invalid_number()) + } + + fn serialize_tuple(self, _len: usize) + -> Result<Self::SerializeTuple, Self::Error> { + Err(invalid_number()) + } + + fn serialize_tuple_struct(self, _name: &'static str, _len: usize) + -> Result<Self::SerializeTupleStruct, Self::Error> { + Err(invalid_number()) + } + + fn serialize_tuple_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize) + -> Result<Self::SerializeTupleVariant, Self::Error> { + Err(invalid_number()) + } + + fn serialize_map(self, _len: Option<usize>) + -> Result<Self::SerializeMap, Self::Error> { + Err(invalid_number()) + } + + fn serialize_struct(self, _name: &'static str, _len: usize) + -> Result<Self::SerializeStruct, Self::Error> { + Err(invalid_number()) + } + + fn serialize_struct_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize) + -> Result<Self::SerializeStructVariant, Self::Error> { + Err(invalid_number()) + } +} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/.cargo-checksum.json cargo-0.26.0/vendor/serde_json-1.0.9/.cargo-checksum.json --- cargo-0.25.0/vendor/serde_json-1.0.9/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"c9db7266c7d63a4c4b7fe8719656ccdd51acf1bed6124b174f933b009fb10bcb"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/Cargo.toml cargo-0.26.0/vendor/serde_json-1.0.9/Cargo.toml --- cargo-0.25.0/vendor/serde_json-1.0.9/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "serde_json" -version = "1.0.9" -authors = ["Erick Tryzelaar <erick.tryzelaar@gmail.com>", "David Tolnay <dtolnay@gmail.com>"] -include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] -description = "A JSON serialization file format" -documentation = "http://docs.serde.rs/serde_json/" -readme = "README.md" -keywords = ["json", "serde", "serialization"] -categories = ["encoding"] -license = "MIT/Apache-2.0" -repository = "https://github.com/serde-rs/json" -[dependencies.dtoa] -version = "0.4" - -[dependencies.itoa] -version = "0.3" - -[dependencies.linked-hash-map] -version = "0.5" -optional = true - -[dependencies.num-traits] -version = "0.1.32" - -[dependencies.serde] -version = "1.0" -[dev-dependencies.compiletest_rs] -version = "0.3" - -[dev-dependencies.serde_bytes] -version = "0.10" - -[dev-dependencies.serde_derive] -version = "1.0" - -[features] -default = [] -preserve_order = ["linked-hash-map"] -[badges.appveyor] -repository = "serde-rs/json" - -[badges.travis-ci] -repository = "serde-rs/json" diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/LICENSE-APACHE cargo-0.26.0/vendor/serde_json-1.0.9/LICENSE-APACHE --- cargo-0.25.0/vendor/serde_json-1.0.9/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/LICENSE-MIT cargo-0.26.0/vendor/serde_json-1.0.9/LICENSE-MIT --- cargo-0.25.0/vendor/serde_json-1.0.9/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/README.md cargo-0.26.0/vendor/serde_json-1.0.9/README.md --- cargo-0.25.0/vendor/serde_json-1.0.9/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,356 +0,0 @@ -# Serde JSON   [![Build Status]][travis] [![Latest Version]][crates.io] - -[Build Status]: https://api.travis-ci.org/serde-rs/json.svg?branch=master -[travis]: https://travis-ci.org/serde-rs/json -[Latest Version]: https://img.shields.io/crates/v/serde_json.svg -[crates.io]: https://crates.io/crates/serde\_json - -**Serde is a framework for *ser*ializing and *de*serializing Rust data structures efficiently and generically.** - ---- - -```toml -[dependencies] -serde_json = "1.0" -``` - -You may be looking for: - -- [JSON API documentation](https://docs.serde.rs/serde_json/) -- [Serde API documentation](https://docs.serde.rs/serde/) -- [Detailed documentation about Serde](https://serde.rs/) -- [Setting up `#[derive(Serialize, Deserialize)]`](https://serde.rs/codegen.html) -- [Release notes](https://github.com/serde-rs/json/releases) - -JSON is a ubiquitous open-standard format that uses human-readable text to -transmit data objects consisting of key-value pairs. - -```json,ignore -{ - "name": "John Doe", - "age": 43, - "address": { - "street": "10 Downing Street", - "city": "London" - }, - "phones": [ - "+44 1234567", - "+44 2345678" - ] -} -``` - -There are three common ways that you might find yourself needing to work -with JSON data in Rust. - - - **As text data.** An unprocessed string of JSON data that you receive on - an HTTP endpoint, read from a file, or prepare to send to a remote - server. - - **As an untyped or loosely typed representation.** Maybe you want to - check that some JSON data is valid before passing it on, but without - knowing the structure of what it contains. Or you want to do very basic - manipulations like insert a key in a particular spot. - - **As a strongly typed Rust data structure.** When you expect all or most - of your data to conform to a particular structure and want to get real - work done without JSON's loosey-goosey nature tripping you up. - -Serde JSON provides efficient, flexible, safe ways of converting data -between each of these representations. - -## Operating on untyped JSON values - -Any valid JSON data can be manipulated in the following recursive enum -representation. This data structure is [`serde_json::Value`][value]. - -```rust,ignore -enum Value { - Null, - Bool(bool), - Number(Number), - String(String), - Array(Vec<Value>), - Object(Map<String, Value>), -} -``` - -A string of JSON data can be parsed into a `serde_json::Value` by the -[`serde_json::from_str`][from_str] function. There is also -[`from_slice`][from_slice] for parsing from a byte slice &[u8] and -[`from_reader`][from_reader] for parsing from any `io::Read` like a File or -a TCP stream. - -<a href="http://play.integer32.com/?gist=a266662bc71712e080efbf25ce30f306" target="_blank"> -<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png"> -</a> - -```rust -extern crate serde_json; - -use serde_json::{Value, Error}; - -fn untyped_example() -> Result<(), Error> { - // Some JSON input data as a &str. Maybe this comes from the user. - let data = r#"{ - "name": "John Doe", - "age": 43, - "phones": [ - "+44 1234567", - "+44 2345678" - ] - }"#; - - // Parse the string of data into serde_json::Value. - let v: Value = serde_json::from_str(data)?; - - // Access parts of the data by indexing with square brackets. - println!("Please call {} at the number {}", v["name"], v["phones"][0]); - - Ok(()) -} -``` - -The result of square bracket indexing like `v["name"]` is a borrow of the data -at that index, so the type is `&Value`. A JSON map can be indexed with string -keys, while a JSON array can be indexed with integer keys. If the type of the -data is not right for the type with which it is being indexed, or if a map does -not contain the key being indexed, or if the index into a vector is out of -bounds, the returned element is `Value::Null`. - -When a `Value` is printed, it is printed as a JSON string. So in the code above, -the output looks like `Please call "John Doe" at the number "+44 1234567"`. The -quotation marks appear because `v["name"]` is a `&Value` containing a JSON -string and its JSON representation is `"John Doe"`. Printing as a plain string -without quotation marks involves converting from a JSON string to a Rust string -with [`as_str()`] or avoiding the use of `Value` as described in the following -section. - -[`as_str()`]: https://docs.serde.rs/serde_json/enum.Value.html#method.as_str - -The `Value` representation is sufficient for very basic tasks but can be tedious -to work with for anything more significant. Error handling is verbose to -implement correctly, for example imagine trying to detect the presence of -unrecognized fields in the input data. The compiler is powerless to help you -when you make a mistake, for example imagine typoing `v["name"]` as `v["nmae"]` -in one of the dozens of places it is used in your code. - -## Parsing JSON as strongly typed data structures - -Serde provides a powerful way of mapping JSON data into Rust data structures -largely automatically. - -<a href="http://play.integer32.com/?gist=cff572b80d3f078c942a2151e6020adc" target="_blank"> -<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png"> -</a> - -```rust -extern crate serde; -extern crate serde_json; - -#[macro_use] -extern crate serde_derive; - -use serde_json::Error; - -#[derive(Serialize, Deserialize)] -struct Person { - name: String, - age: u8, - phones: Vec<String>, -} - -fn typed_example() -> Result<(), Error> { - // Some JSON input data as a &str. Maybe this comes from the user. - let data = r#"{ - "name": "John Doe", - "age": 43, - "phones": [ - "+44 1234567", - "+44 2345678" - ] - }"#; - - // Parse the string of data into a Person object. This is exactly the - // same function as the one that produced serde_json::Value above, but - // now we are asking it for a Person as output. - let p: Person = serde_json::from_str(data)?; - - // Do things just like with any other Rust data structure. - println!("Please call {} at the number {}", p.name, p.phones[0]); - - Ok(()) -} -``` - -This is the same `serde_json::from_str` function as before, but this time we -assign the return value to a variable of type `Person` so Serde will -automatically interpret the input data as a `Person` and produce informative -error messages if the layout does not conform to what a `Person` is expected -to look like. - -Any type that implements Serde's `Deserialize` trait can be deserialized -this way. This includes built-in Rust standard library types like `Vec<T>` -and `HashMap<K, V>`, as well as any structs or enums annotated with -`#[derive(Deserialize)]`. - -Once we have `p` of type `Person`, our IDE and the Rust compiler can help us -use it correctly like they do for any other Rust code. The IDE can -autocomplete field names to prevent typos, which was impossible in the -`serde_json::Value` representation. And the Rust compiler can check that -when we write `p.phones[0]`, then `p.phones` is guaranteed to be a -`Vec<String>` so indexing into it makes sense and produces a `String`. - -## Constructing JSON values - -Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` -objects with very natural JSON syntax. In order to use this macro, -`serde_json` needs to be imported with the `#[macro_use]` attribute. - -<a href="http://play.integer32.com/?gist=c216d6beabd9429a6ac13b8f88938dfe" target="_blank"> -<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png"> -</a> - -```rust -#[macro_use] -extern crate serde_json; - -fn main() { - // The type of `john` is `serde_json::Value` - let john = json!({ - "name": "John Doe", - "age": 43, - "phones": [ - "+44 1234567", - "+44 2345678" - ] - }); - - println!("first phone number: {}", john["phones"][0]); - - // Convert to a string of JSON and print it out - println!("{}", john.to_string()); -} -``` - -The `Value::to_string()` function converts a `serde_json::Value` into a -`String` of JSON text. - -One neat thing about the `json!` macro is that variables and expressions can -be interpolated directly into the JSON value as you are building it. Serde -will check at compile time that the value you are interpolating is able to -be represented as JSON. - -<a href="http://play.integer32.com/?gist=aae3af4d274bd249d1c8a947076355f2" target="_blank"> -<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png"> -</a> - -```rust -let full_name = "John Doe"; -let age_last_year = 42; - -// The type of `john` is `serde_json::Value` -let john = json!({ - "name": full_name, - "age": age_last_year + 1, - "phones": [ - format!("+44 {}", random_phone()) - ] -}); -``` - -This is amazingly convenient but we have the problem we had before with -`Value` which is that the IDE and Rust compiler cannot help us if we get it -wrong. Serde JSON provides a better way of serializing strongly-typed data -structures into JSON text. - -## Creating JSON by serializing data structures - -A data structure can be converted to a JSON string by -[`serde_json::to_string`][to_string]. There is also -[`serde_json::to_vec`][to_vec] which serializes to a `Vec<u8>` and -[`serde_json::to_writer`][to_writer] which serializes to any `io::Write` -such as a File or a TCP stream. - -<a href="http://play.integer32.com/?gist=40967ece79921c77fd78ebc8f177c063" target="_blank"> -<img align="right" width="50" src="https://raw.githubusercontent.com/serde-rs/serde-rs.github.io/master/img/run.png"> -</a> - -```rust -extern crate serde; -extern crate serde_json; - -#[macro_use] -extern crate serde_derive; - -use serde_json::Error; - -#[derive(Serialize, Deserialize)] -struct Address { - street: String, - city: String, -} - -fn print_an_address() -> Result<(), Error> { - // Some data structure. - let address = Address { - street: "10 Downing Street".to_owned(), - city: "London".to_owned(), - }; - - // Serialize it to a JSON string. - let j = serde_json::to_string(&address)?; - - // Print, write to a file, or send to an HTTP server. - println!("{}", j); - - Ok(()) -} -``` - -Any type that implements Serde's `Serialize` trait can be serialized this -way. This includes built-in Rust standard library types like `Vec<T>` and -`HashMap<K, V>`, as well as any structs or enums annotated with -`#[derive(Serialize)]`. - -## Performance - -It is fast. You should expect in the ballpark of 500 to 1000 megabytes per -second deserialization and 600 to 900 megabytes per second serialization, -depending on the characteristics of your data. This is competitive with the -fastest C and C++ JSON libraries or even 30% faster for many use cases. -Benchmarks live in the [serde-rs/json-benchmark] repo. - -[serde-rs/json-benchmark]: https://github.com/serde-rs/json-benchmark - -## Getting help - -Serde developers live in the #serde channel on -[`irc.mozilla.org`](https://wiki.mozilla.org/IRC). The #rust channel is also a -good resource with generally faster response time but less specific knowledge -about Serde. If IRC is not your thing, we are happy to respond to [GitHub -issues](https://github.com/serde-rs/json/issues/new) as well. - -## License - -Serde JSON is 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 Serde JSON by you, as defined in the Apache-2.0 license, shall -be dual licensed as above, without any additional terms or conditions. - -[value]: https://docs.serde.rs/serde_json/value/enum.Value.html -[from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html -[from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html -[from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html -[to_string]: https://docs.serde.rs/serde_json/ser/fn.to_string.html -[to_vec]: https://docs.serde.rs/serde_json/ser/fn.to_vec.html -[to_writer]: https://docs.serde.rs/serde_json/ser/fn.to_writer.html -[macro]: https://docs.serde.rs/serde_json/macro.json.html diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/de.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/de.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/de.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/de.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,2047 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Deserialize JSON data to a Rust data structure. - -use std::{i32, u64}; -use std::io; -use std::marker::PhantomData; - -use serde::de::{self, Expected, Unexpected}; - -use super::error::{Error, ErrorCode, Result}; - -use read::{self, Reference}; - -pub use read::{Read, IoRead, SliceRead, StrRead}; - -////////////////////////////////////////////////////////////////////////////// - -/// A structure that deserializes JSON into Rust values. -pub struct Deserializer<R> { - read: R, - str_buf: Vec<u8>, - remaining_depth: u8, -} - -impl<'de, R> Deserializer<R> -where - R: read::Read<'de>, -{ - /// Create a JSON deserializer from one of the possible serde_json input - /// sources. - /// - /// Typically it is more convenient to use one of these methods instead: - /// - /// - Deserializer::from_str - /// - Deserializer::from_bytes - /// - Deserializer::from_reader - pub fn new(read: R) -> Self { - Deserializer { - read: read, - str_buf: Vec::with_capacity(128), - remaining_depth: 128, - } - } -} - -impl<R> Deserializer<read::IoRead<R>> -where - R: io::Read, -{ - /// Creates a JSON deserializer from an `io::Read`. - pub fn from_reader(reader: R) -> Self { - Deserializer::new(read::IoRead::new(reader)) - } -} - -impl<'a> Deserializer<read::SliceRead<'a>> { - /// Creates a JSON deserializer from a `&[u8]`. - pub fn from_slice(bytes: &'a [u8]) -> Self { - Deserializer::new(read::SliceRead::new(bytes)) - } -} - -impl<'a> Deserializer<read::StrRead<'a>> { - /// Creates a JSON deserializer from a `&str`. - pub fn from_str(s: &'a str) -> Self { - Deserializer::new(read::StrRead::new(s)) - } -} - -macro_rules! overflow { - ($a:ident * 10 + $b:ident, $c:expr) => { - $a >= $c / 10 && ($a > $c / 10 || $b > $c % 10) - } -} - -enum Number { - F64(f64), - U64(u64), - I64(i64), -} - -impl Number { - fn visit<'de, V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - match self { - Number::F64(x) => visitor.visit_f64(x), - Number::U64(x) => visitor.visit_u64(x), - Number::I64(x) => visitor.visit_i64(x), - } - } - - fn invalid_type(self, exp: &Expected) -> Error { - match self { - Number::F64(x) => de::Error::invalid_type(Unexpected::Float(x), exp), - Number::U64(x) => de::Error::invalid_type(Unexpected::Unsigned(x), exp), - Number::I64(x) => de::Error::invalid_type(Unexpected::Signed(x), exp), - } - } -} - -impl<'de, R: Read<'de>> Deserializer<R> { - /// The `Deserializer::end` method should be called after a value has been fully deserialized. - /// This allows the `Deserializer` to validate that the input stream is at the end or that it - /// only has trailing whitespace. - pub fn end(&mut self) -> Result<()> { - match try!(self.parse_whitespace()) { - Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)), - None => Ok(()), - } - } - - /// Turn a JSON deserializer into an iterator over values of type T. - pub fn into_iter<T>(self) -> StreamDeserializer<'de, R, T> - where - T: de::Deserialize<'de>, - { - // This cannot be an implementation of std::iter::IntoIterator because - // we need the caller to choose what T is. - let offset = self.read.byte_offset(); - StreamDeserializer { - de: self, - offset: offset, - output: PhantomData, - lifetime: PhantomData, - } - } - - fn peek(&mut self) -> Result<Option<u8>> { - self.read.peek().map_err(Error::io) - } - - fn peek_or_null(&mut self) -> Result<u8> { - Ok(try!(self.peek()).unwrap_or(b'\x00')) - } - - fn eat_char(&mut self) { - self.read.discard(); - } - - fn next_char(&mut self) -> Result<Option<u8>> { - self.read.next().map_err(Error::io) - } - - fn next_char_or_null(&mut self) -> Result<u8> { - Ok(try!(self.next_char()).unwrap_or(b'\x00')) - } - - /// Error caused by a byte from next_char(). - #[cold] - fn error(&self, reason: ErrorCode) -> Error { - let pos = self.read.position(); - Error::syntax(reason, pos.line, pos.column) - } - - /// Error caused by a byte from peek(). - #[cold] - fn peek_error(&self, reason: ErrorCode) -> Error { - let pos = self.read.peek_position(); - Error::syntax(reason, pos.line, pos.column) - } - - /// Returns the first non-whitespace byte without consuming it, or `None` if - /// EOF is encountered. - fn parse_whitespace(&mut self) -> Result<Option<u8>> { - loop { - match try!(self.peek()) { - Some(b' ') | Some(b'\n') | Some(b'\t') | Some(b'\r') => { - self.eat_char(); - } - other => { - return Ok(other); - } - } - } - } - - #[cold] - fn peek_invalid_type(&mut self, exp: &Expected) -> Error { - let err = match self.peek_or_null().unwrap_or(b'\x00') { - b'n' => { - self.eat_char(); - if let Err(err) = self.parse_ident(b"ull") { - return err; - } - de::Error::invalid_type(Unexpected::Unit, exp) - } - b't' => { - self.eat_char(); - if let Err(err) = self.parse_ident(b"rue") { - return err; - } - de::Error::invalid_type(Unexpected::Bool(true), exp) - } - b'f' => { - self.eat_char(); - if let Err(err) = self.parse_ident(b"alse") { - return err; - } - de::Error::invalid_type(Unexpected::Bool(false), exp) - } - b'-' => { - self.eat_char(); - match self.parse_integer(false) { - Ok(n) => n.invalid_type(exp), - Err(err) => return err, - } - } - b'0'...b'9' => { - match self.parse_integer(true) { - Ok(n) => n.invalid_type(exp), - Err(err) => return err, - } - } - b'"' => { - self.eat_char(); - self.str_buf.clear(); - match self.read.parse_str(&mut self.str_buf) { - Ok(s) => de::Error::invalid_type(Unexpected::Str(&s), exp), - Err(err) => return err, - } - } - b'[' => { - de::Error::invalid_type(Unexpected::Seq, exp) - } - b'{' => { - de::Error::invalid_type(Unexpected::Map, exp) - } - _ => self.peek_error(ErrorCode::ExpectedSomeValue), - }; - - self.fix_position(err) - } - - fn deserialize_number<V>(&mut self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - let peek = match try!(self.parse_whitespace()) { - Some(b) => b, - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); - } - }; - - let value = match peek { - b'-' => { - self.eat_char(); - try!(self.parse_integer(false)).visit(visitor) - } - b'0'...b'9' => try!(self.parse_integer(true)).visit(visitor), - _ => Err(self.peek_invalid_type(&visitor)), - }; - - match value { - Ok(value) => Ok(value), - Err(err) => Err(self.fix_position(err)), - } - } - - #[cold] - fn fix_position(&self, err: Error) -> Error { - err.fix_position(move |code| self.error(code)) - } - - fn parse_ident(&mut self, ident: &[u8]) -> Result<()> { - for c in ident { - if Some(*c) != try!(self.next_char()) { - return Err(self.error(ErrorCode::ExpectedSomeIdent)); - } - } - - Ok(()) - } - - fn parse_integer(&mut self, pos: bool) -> Result<Number> { - match try!(self.next_char_or_null()) { - b'0' => { - // There can be only one leading '0'. - match try!(self.peek_or_null()) { - b'0'...b'9' => Err(self.peek_error(ErrorCode::InvalidNumber)), - _ => self.parse_number(pos, 0), - } - } - c @ b'1'...b'9' => { - let mut res = (c - b'0') as u64; - - loop { - match try!(self.peek_or_null()) { - c @ b'0'...b'9' => { - self.eat_char(); - let digit = (c - b'0') as u64; - - // We need to be careful with overflow. If we can, try to keep the - // number as a `u64` until we grow too large. At that point, switch to - // parsing the value as a `f64`. - if overflow!(res * 10 + digit, u64::MAX) { - return Ok(Number::F64(try!(self.parse_long_integer( - pos, - res, - 1, // res * 10^1 - )))); - } - - res = res * 10 + digit; - } - _ => { - return self.parse_number(pos, res); - } - } - } - } - _ => Err(self.error(ErrorCode::InvalidNumber)), - } - } - - fn parse_long_integer( - &mut self, - pos: bool, - significand: u64, - mut exponent: i32, - ) -> Result<f64> { - loop { - match try!(self.peek_or_null()) { - b'0'...b'9' => { - self.eat_char(); - // This could overflow... if your integer is gigabytes long. - // Ignore that possibility. - exponent += 1; - } - b'.' => { - return self.parse_decimal(pos, significand, exponent); - } - b'e' | b'E' => { - return self.parse_exponent(pos, significand, exponent); - } - _ => { - return self.f64_from_parts(pos, significand, exponent); - } - } - } - } - - fn parse_number(&mut self, pos: bool, significand: u64) -> Result<Number> { - Ok(match try!(self.peek_or_null()) { - b'.' => Number::F64(try!(self.parse_decimal(pos, significand, 0))), - b'e' | b'E' => Number::F64(try!(self.parse_exponent(pos, significand, 0))), - _ => { - if pos { - Number::U64(significand) - } else { - let neg = (significand as i64).wrapping_neg(); - - // Convert into a float if we underflow. - if neg > 0 { - Number::F64(-(significand as f64)) - } else { - Number::I64(neg) - } - } - } - }) - } - - fn parse_decimal( - &mut self, - pos: bool, - mut significand: u64, - mut exponent: i32, - ) -> Result<f64> { - self.eat_char(); - - let mut at_least_one_digit = false; - while let c @ b'0'...b'9' = try!(self.peek_or_null()) { - self.eat_char(); - let digit = (c - b'0') as u64; - at_least_one_digit = true; - - if overflow!(significand * 10 + digit, u64::MAX) { - // The next multiply/add would overflow, so just ignore all - // further digits. - while let b'0'...b'9' = try!(self.peek_or_null()) { - self.eat_char(); - } - break; - } - - significand = significand * 10 + digit; - exponent -= 1; - } - - if !at_least_one_digit { - return Err(self.peek_error(ErrorCode::InvalidNumber)); - } - - match try!(self.peek_or_null()) { - b'e' | b'E' => self.parse_exponent(pos, significand, exponent), - _ => self.f64_from_parts(pos, significand, exponent), - } - } - - fn parse_exponent( - &mut self, - pos: bool, - significand: u64, - starting_exp: i32, - ) -> Result<f64> { - self.eat_char(); - - let pos_exp = match try!(self.peek_or_null()) { - b'+' => { - self.eat_char(); - true - } - b'-' => { - self.eat_char(); - false - } - _ => true, - }; - - // Make sure a digit follows the exponent place. - let mut exp = match try!(self.next_char_or_null()) { - c @ b'0'...b'9' => (c - b'0') as i32, - _ => { - return Err(self.error(ErrorCode::InvalidNumber)); - } - }; - - while let c @ b'0'...b'9' = try!(self.peek_or_null()) { - self.eat_char(); - let digit = (c - b'0') as i32; - - if overflow!(exp * 10 + digit, i32::MAX) { - return self.parse_exponent_overflow(pos, significand, pos_exp); - } - - exp = exp * 10 + digit; - } - - let final_exp = if pos_exp { - starting_exp.saturating_add(exp) - } else { - starting_exp.saturating_sub(exp) - }; - - self.f64_from_parts(pos, significand, final_exp) - } - - // This cold code should not be inlined into the middle of the hot - // exponent-parsing loop above. - #[cold] - #[inline(never)] - fn parse_exponent_overflow( - &mut self, - pos: bool, - significand: u64, - pos_exp: bool, - ) -> Result<f64> { - // Error instead of +/- infinity. - if significand != 0 && pos_exp { - return Err(self.error(ErrorCode::NumberOutOfRange)); - } - - while let b'0'...b'9' = try!(self.peek_or_null()) { - self.eat_char(); - } - Ok(if pos { 0.0 } else { -0.0 }) - } - - fn f64_from_parts( - &mut self, - pos: bool, - significand: u64, - mut exponent: i32, - ) -> Result<f64> { - let mut f = significand as f64; - loop { - match POW10.get(exponent.abs() as usize) { - Some(&pow) => { - if exponent >= 0 { - f *= pow; - if f.is_infinite() { - return Err(self.error(ErrorCode::NumberOutOfRange)); - } - } else { - f /= pow; - } - break; - } - None => { - if f == 0.0 { - break; - } - if exponent >= 0 { - return Err(self.error(ErrorCode::NumberOutOfRange)); - } - f /= 1e308; - exponent += 308; - } - } - } - Ok(if pos { f } else { -f }) - } - - fn parse_object_colon(&mut self) -> Result<()> { - match try!(self.parse_whitespace()) { - Some(b':') => { - self.eat_char(); - Ok(()) - } - Some(_) => Err(self.peek_error(ErrorCode::ExpectedColon)), - None => Err(self.peek_error(ErrorCode::EofWhileParsingObject)), - } - } - - fn end_seq(&mut self) -> Result<()> { - match try!(self.parse_whitespace()) { - Some(b']') => { - self.eat_char(); - Ok(()) - } - Some(b',') => { - self.eat_char(); - match self.parse_whitespace() { - Ok(Some(b']')) => Err(self.peek_error(ErrorCode::TrailingComma)), - _ => Err(self.peek_error(ErrorCode::TrailingCharacters)), - } - } - Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)), - None => Err(self.peek_error(ErrorCode::EofWhileParsingList)), - } - } - - fn end_map(&mut self) -> Result<()> { - match try!(self.parse_whitespace()) { - Some(b'}') => { - self.eat_char(); - Ok(()) - } - Some(b',') => Err(self.peek_error(ErrorCode::TrailingComma)), - Some(_) => Err(self.peek_error(ErrorCode::TrailingCharacters)), - None => Err(self.peek_error(ErrorCode::EofWhileParsingObject)), - } - } - - fn ignore_value(&mut self) -> Result<()> { - let peek = match try!(self.parse_whitespace()) { - Some(b) => b, - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); - } - }; - - match peek { - b'n' => { - self.eat_char(); - self.parse_ident(b"ull") - } - b't' => { - self.eat_char(); - self.parse_ident(b"rue") - } - b'f' => { - self.eat_char(); - self.parse_ident(b"alse") - } - b'-' => { - self.eat_char(); - self.ignore_integer() - } - b'0'...b'9' => { - self.ignore_integer() - } - b'"' => { - self.eat_char(); - self.read.ignore_str() - } - b'[' => { - self.remaining_depth -= 1; - if self.remaining_depth == 0 { - return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); - } - - self.eat_char(); - let res = self.ignore_seq(); - self.remaining_depth += 1; - res - } - b'{' => { - self.remaining_depth -= 1; - if self.remaining_depth == 0 { - return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); - } - - self.eat_char(); - let res = self.ignore_map(); - self.remaining_depth += 1; - res - } - _ => { - Err(self.peek_error(ErrorCode::ExpectedSomeValue)) - } - } - } - - fn ignore_integer(&mut self) -> Result<()> { - match try!(self.next_char_or_null()) { - b'0' => { - // There can be only one leading '0'. - if let b'0'...b'9' = try!(self.peek_or_null()) { - return Err(self.peek_error(ErrorCode::InvalidNumber)); - } - } - b'1'...b'9' => { - while let b'0'...b'9' = try!(self.peek_or_null()) { - self.eat_char(); - } - } - _ => { - return Err(self.error(ErrorCode::InvalidNumber)); - } - } - - match try!(self.peek_or_null()) { - b'.' => self.ignore_decimal(), - b'e' | b'E' => self.ignore_exponent(), - _ => Ok(()), - } - } - - fn ignore_decimal(&mut self) -> Result<()> { - self.eat_char(); - - let mut at_least_one_digit = false; - while let b'0'...b'9' = try!(self.peek_or_null()) { - self.eat_char(); - at_least_one_digit = true; - } - - if !at_least_one_digit { - return Err(self.peek_error(ErrorCode::InvalidNumber)); - } - - match try!(self.peek_or_null()) { - b'e' | b'E' => self.ignore_exponent(), - _ => Ok(()), - } - } - - fn ignore_exponent(&mut self) -> Result<()> { - self.eat_char(); - - match try!(self.peek_or_null()) { - b'+' | b'-' => self.eat_char(), - _ => {} - } - - // Make sure a digit follows the exponent place. - match try!(self.next_char_or_null()) { - b'0'...b'9' => {} - _ => { - return Err(self.error(ErrorCode::InvalidNumber)); - } - } - - while let b'0'...b'9' = try!(self.peek_or_null()) { - self.eat_char(); - } - - Ok(()) - } - - fn ignore_seq(&mut self) -> Result<()> { - let mut first = true; - - loop { - match try!(self.parse_whitespace()) { - Some(b']') => { - self.eat_char(); - return Ok(()); - } - Some(b',') if !first => { - self.eat_char(); - } - Some(_) => { - if first { - first = false; - } else { - return Err(self.peek_error(ErrorCode::ExpectedListCommaOrEnd)); - } - } - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingList)); - } - } - - try!(self.ignore_value()); - } - } - - fn ignore_map(&mut self) -> Result<()> { - let mut first = true; - - loop { - let peek = match try!(self.parse_whitespace()) { - Some(b'}') => { - self.eat_char(); - return Ok(()); - } - Some(b',') if !first => { - self.eat_char(); - try!(self.parse_whitespace()) - } - Some(b) => { - if first { - first = false; - Some(b) - } else { - return Err(self.peek_error(ErrorCode::ExpectedObjectCommaOrEnd)); - } - } - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingObject)); - } - }; - - match peek { - Some(b'"') => { - self.eat_char(); - try!(self.read.ignore_str()); - } - Some(_) => { - return Err(self.peek_error(ErrorCode::KeyMustBeAString)); - } - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingObject)); - } - } - - match try!(self.parse_whitespace()) { - Some(b':') => { - self.eat_char(); - try!(self.ignore_value()); - } - Some(_) => { - return Err(self.peek_error(ErrorCode::ExpectedColon)); - } - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingObject)); - } - } - } - } -} - -#[cfg_attr(rustfmt, rustfmt_skip)] -static POW10: [f64; 309] = - [1e000, 1e001, 1e002, 1e003, 1e004, 1e005, 1e006, 1e007, 1e008, 1e009, - 1e010, 1e011, 1e012, 1e013, 1e014, 1e015, 1e016, 1e017, 1e018, 1e019, - 1e020, 1e021, 1e022, 1e023, 1e024, 1e025, 1e026, 1e027, 1e028, 1e029, - 1e030, 1e031, 1e032, 1e033, 1e034, 1e035, 1e036, 1e037, 1e038, 1e039, - 1e040, 1e041, 1e042, 1e043, 1e044, 1e045, 1e046, 1e047, 1e048, 1e049, - 1e050, 1e051, 1e052, 1e053, 1e054, 1e055, 1e056, 1e057, 1e058, 1e059, - 1e060, 1e061, 1e062, 1e063, 1e064, 1e065, 1e066, 1e067, 1e068, 1e069, - 1e070, 1e071, 1e072, 1e073, 1e074, 1e075, 1e076, 1e077, 1e078, 1e079, - 1e080, 1e081, 1e082, 1e083, 1e084, 1e085, 1e086, 1e087, 1e088, 1e089, - 1e090, 1e091, 1e092, 1e093, 1e094, 1e095, 1e096, 1e097, 1e098, 1e099, - 1e100, 1e101, 1e102, 1e103, 1e104, 1e105, 1e106, 1e107, 1e108, 1e109, - 1e110, 1e111, 1e112, 1e113, 1e114, 1e115, 1e116, 1e117, 1e118, 1e119, - 1e120, 1e121, 1e122, 1e123, 1e124, 1e125, 1e126, 1e127, 1e128, 1e129, - 1e130, 1e131, 1e132, 1e133, 1e134, 1e135, 1e136, 1e137, 1e138, 1e139, - 1e140, 1e141, 1e142, 1e143, 1e144, 1e145, 1e146, 1e147, 1e148, 1e149, - 1e150, 1e151, 1e152, 1e153, 1e154, 1e155, 1e156, 1e157, 1e158, 1e159, - 1e160, 1e161, 1e162, 1e163, 1e164, 1e165, 1e166, 1e167, 1e168, 1e169, - 1e170, 1e171, 1e172, 1e173, 1e174, 1e175, 1e176, 1e177, 1e178, 1e179, - 1e180, 1e181, 1e182, 1e183, 1e184, 1e185, 1e186, 1e187, 1e188, 1e189, - 1e190, 1e191, 1e192, 1e193, 1e194, 1e195, 1e196, 1e197, 1e198, 1e199, - 1e200, 1e201, 1e202, 1e203, 1e204, 1e205, 1e206, 1e207, 1e208, 1e209, - 1e210, 1e211, 1e212, 1e213, 1e214, 1e215, 1e216, 1e217, 1e218, 1e219, - 1e220, 1e221, 1e222, 1e223, 1e224, 1e225, 1e226, 1e227, 1e228, 1e229, - 1e230, 1e231, 1e232, 1e233, 1e234, 1e235, 1e236, 1e237, 1e238, 1e239, - 1e240, 1e241, 1e242, 1e243, 1e244, 1e245, 1e246, 1e247, 1e248, 1e249, - 1e250, 1e251, 1e252, 1e253, 1e254, 1e255, 1e256, 1e257, 1e258, 1e259, - 1e260, 1e261, 1e262, 1e263, 1e264, 1e265, 1e266, 1e267, 1e268, 1e269, - 1e270, 1e271, 1e272, 1e273, 1e274, 1e275, 1e276, 1e277, 1e278, 1e279, - 1e280, 1e281, 1e282, 1e283, 1e284, 1e285, 1e286, 1e287, 1e288, 1e289, - 1e290, 1e291, 1e292, 1e293, 1e294, 1e295, 1e296, 1e297, 1e298, 1e299, - 1e300, 1e301, 1e302, 1e303, 1e304, 1e305, 1e306, 1e307, 1e308]; - -impl<'de, 'a, R: Read<'de>> de::Deserializer<'de> for &'a mut Deserializer<R> { - type Error = Error; - - #[inline] - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - let peek = match try!(self.parse_whitespace()) { - Some(b) => b, - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); - } - }; - - let value = match peek { - b'n' => { - self.eat_char(); - try!(self.parse_ident(b"ull")); - visitor.visit_unit() - } - b't' => { - self.eat_char(); - try!(self.parse_ident(b"rue")); - visitor.visit_bool(true) - } - b'f' => { - self.eat_char(); - try!(self.parse_ident(b"alse")); - visitor.visit_bool(false) - } - b'-' => { - self.eat_char(); - try!(self.parse_integer(false)).visit(visitor) - } - b'0'...b'9' => try!(self.parse_integer(true)).visit(visitor), - b'"' => { - self.eat_char(); - self.str_buf.clear(); - match try!(self.read.parse_str(&mut self.str_buf)) { - Reference::Borrowed(s) => visitor.visit_borrowed_str(s), - Reference::Copied(s) => visitor.visit_str(s), - } - } - b'[' => { - self.remaining_depth -= 1; - if self.remaining_depth == 0 { - return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); - } - - self.eat_char(); - let ret = visitor.visit_seq(SeqAccess::new(self)); - - self.remaining_depth += 1; - - match (ret, self.end_seq()) { - (Ok(ret), Ok(())) => Ok(ret), - (Err(err), _) | (_, Err(err)) => Err(err), - } - } - b'{' => { - self.remaining_depth -= 1; - if self.remaining_depth == 0 { - return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); - } - - self.eat_char(); - let ret = visitor.visit_map(MapAccess::new(self)); - - self.remaining_depth += 1; - - match (ret, self.end_map()) { - (Ok(ret), Ok(())) => Ok(ret), - (Err(err), _) | (_, Err(err)) => Err(err), - } - } - _ => Err(self.peek_error(ErrorCode::ExpectedSomeValue)), - }; - - match value { - Ok(value) => Ok(value), - // The de::Error impl creates errors with unknown line and column. - // Fill in the position here by looking at the current index in the - // input. There is no way to tell whether this should call `error` - // or `peek_error` so pick the one that seems correct more often. - // Worst case, the position is off by one character. - Err(err) => Err(self.fix_position(err)), - } - } - - fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - let peek = match try!(self.parse_whitespace()) { - Some(b) => b, - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); - } - }; - - let value = match peek { - b't' => { - self.eat_char(); - try!(self.parse_ident(b"rue")); - visitor.visit_bool(true) - } - b'f' => { - self.eat_char(); - try!(self.parse_ident(b"alse")); - visitor.visit_bool(false) - } - _ => Err(self.peek_invalid_type(&visitor)), - }; - - match value { - Ok(value) => Ok(value), - Err(err) => Err(self.fix_position(err)), - } - } - - fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_number(visitor) - } - - fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_number(visitor) - } - - fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_number(visitor) - } - - fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_number(visitor) - } - - fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_number(visitor) - } - - fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_number(visitor) - } - - fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_number(visitor) - } - - fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_number(visitor) - } - - fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_number(visitor) - } - - fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_number(visitor) - } - - fn deserialize_char<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_str(visitor) - } - - fn deserialize_str<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - let peek = match try!(self.parse_whitespace()) { - Some(b) => b, - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); - } - }; - - let value = match peek { - b'"' => { - self.eat_char(); - self.str_buf.clear(); - match try!(self.read.parse_str(&mut self.str_buf)) { - Reference::Borrowed(s) => visitor.visit_borrowed_str(s), - Reference::Copied(s) => visitor.visit_str(s), - } - } - _ => Err(self.peek_invalid_type(&visitor)), - }; - - match value { - Ok(value) => Ok(value), - Err(err) => Err(self.fix_position(err)), - } - } - - fn deserialize_string<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_str(visitor) - } - - /// Parses a JSON string as bytes. Note that this function does not check - /// whether the bytes represent a valid UTF-8 string. - /// - /// The relevant part of the JSON specification is Section 8.2 of [RFC - /// 7159]: - /// - /// > When all the strings represented in a JSON text are composed entirely - /// > of Unicode characters (however escaped), then that JSON text is - /// > interoperable in the sense that all software implementations that - /// > parse it will agree on the contents of names and of string values in - /// > objects and arrays. - /// > - /// > However, the ABNF in this specification allows member names and string - /// > values to contain bit sequences that cannot encode Unicode characters; - /// > for example, "\uDEAD" (a single unpaired UTF-16 surrogate). Instances - /// > of this have been observed, for example, when a library truncates a - /// > UTF-16 string without checking whether the truncation split a - /// > surrogate pair. The behavior of software that receives JSON texts - /// > containing such values is unpredictable; for example, implementations - /// > might return different values for the length of a string value or even - /// > suffer fatal runtime exceptions. - /// - /// [RFC 7159]: https://tools.ietf.org/html/rfc7159 - /// - /// The behavior of serde_json is specified to fail on non-UTF-8 strings - /// when deserializing into Rust UTF-8 string types such as String, and - /// succeed with non-UTF-8 bytes when deserializing using this method. - /// - /// Escape sequences are processed as usual, and for `\uXXXX` escapes it is - /// still checked if the hex number represents a valid Unicode code point. - /// - /// # Examples - /// - /// You can use this to parse JSON strings containing invalid UTF-8 bytes. - /// - /// ```rust - /// extern crate serde_json; - /// extern crate serde_bytes; - /// - /// use serde_bytes::ByteBuf; - /// - /// fn look_at_bytes() -> Result<(), serde_json::Error> { - /// let json_data = b"\"some bytes: \xe5\x00\xe5\""; - /// let bytes: ByteBuf = serde_json::from_slice(json_data)?; - /// - /// assert_eq!(b'\xe5', bytes[12]); - /// assert_eq!(b'\0', bytes[13]); - /// assert_eq!(b'\xe5', bytes[14]); - /// - /// Ok(()) - /// } - /// # - /// # fn main() { - /// # look_at_bytes().unwrap(); - /// # } - /// ``` - /// - /// Backslash escape sequences like `\n` are still interpreted and required - /// to be valid, and `\u` escape sequences are required to represent valid - /// Unicode code points. - /// - /// ```rust - /// extern crate serde_json; - /// extern crate serde_bytes; - /// - /// use serde_bytes::ByteBuf; - /// - /// fn look_at_bytes() { - /// let json_data = b"\"invalid unicode surrogate: \\uD801\""; - /// let parsed: Result<ByteBuf, _> = serde_json::from_slice(json_data); - /// - /// assert!(parsed.is_err()); - /// - /// let expected_msg = "unexpected end of hex escape at line 1 column 35"; - /// assert_eq!(expected_msg, parsed.unwrap_err().to_string()); - /// } - /// # - /// # fn main() { - /// # look_at_bytes(); - /// # } - /// ``` - fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - let peek = match try!(self.parse_whitespace()) { - Some(b) => b, - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); - } - }; - - let value = match peek { - b'"' => { - self.eat_char(); - self.str_buf.clear(); - match try!(self.read.parse_str_raw(&mut self.str_buf)) { - Reference::Borrowed(b) => visitor.visit_borrowed_bytes(b), - Reference::Copied(b) => visitor.visit_bytes(b), - } - } - b'[' => self.deserialize_seq(visitor), - _ => Err(self.peek_invalid_type(&visitor)), - }; - - match value { - Ok(value) => Ok(value), - Err(err) => Err(self.fix_position(err)), - } - } - - #[inline] - fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_bytes(visitor) - } - - /// Parses a `null` as a None, and any other values as a `Some(...)`. - #[inline] - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - match try!(self.parse_whitespace()) { - Some(b'n') => { - self.eat_char(); - try!(self.parse_ident(b"ull")); - visitor.visit_none() - } - _ => visitor.visit_some(self), - } - } - - fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - let peek = match try!(self.parse_whitespace()) { - Some(b) => b, - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); - } - }; - - let value = match peek { - b'n' => { - self.eat_char(); - try!(self.parse_ident(b"ull")); - visitor.visit_unit() - } - _ => Err(self.peek_invalid_type(&visitor)), - }; - - match value { - Ok(value) => Ok(value), - Err(err) => Err(self.fix_position(err)), - } - } - - fn deserialize_unit_struct<V>( - self, - _name: &'static str, - visitor: V - ) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_unit(visitor) - } - - /// Parses a newtype struct as the underlying value. - #[inline] - fn deserialize_newtype_struct<V>(self, _name: &str, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - visitor.visit_newtype_struct(self) - } - - fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - let peek = match try!(self.parse_whitespace()) { - Some(b) => b, - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); - } - }; - - let value = match peek { - b'[' => { - self.remaining_depth -= 1; - if self.remaining_depth == 0 { - return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); - } - - self.eat_char(); - let ret = visitor.visit_seq(SeqAccess::new(self)); - - self.remaining_depth += 1; - - match (ret, self.end_seq()) { - (Ok(ret), Ok(())) => Ok(ret), - (Err(err), _) | (_, Err(err)) => Err(err), - } - } - _ => Err(self.peek_invalid_type(&visitor)), - }; - - match value { - Ok(value) => Ok(value), - Err(err) => Err(self.fix_position(err)), - } - } - - fn deserialize_tuple<V>( - self, - _len: usize, - visitor: V - ) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_seq(visitor) - } - - fn deserialize_tuple_struct<V>( - self, - _name: &'static str, - _len: usize, - visitor: V - ) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_seq(visitor) - } - - fn deserialize_map<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - let peek = match try!(self.parse_whitespace()) { - Some(b) => b, - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); - } - }; - - let value = match peek { - b'{' => { - self.remaining_depth -= 1; - if self.remaining_depth == 0 { - return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); - } - - self.eat_char(); - let ret = visitor.visit_map(MapAccess::new(self)); - - self.remaining_depth += 1; - - match (ret, self.end_map()) { - (Ok(ret), Ok(())) => Ok(ret), - (Err(err), _) | (_, Err(err)) => Err(err), - } - } - _ => Err(self.peek_invalid_type(&visitor)), - }; - - match value { - Ok(value) => Ok(value), - Err(err) => Err(self.fix_position(err)), - } - } - - fn deserialize_struct<V>( - self, - _name: &'static str, - _fields: &'static [&'static str], - visitor: V - ) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - let peek = match try!(self.parse_whitespace()) { - Some(b) => b, - None => { - return Err(self.peek_error(ErrorCode::EofWhileParsingValue)); - } - }; - - let value = match peek { - b'[' => { - self.remaining_depth -= 1; - if self.remaining_depth == 0 { - return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); - } - - self.eat_char(); - let ret = visitor.visit_seq(SeqAccess::new(self)); - - self.remaining_depth += 1; - - match (ret, self.end_seq()) { - (Ok(ret), Ok(())) => Ok(ret), - (Err(err), _) | (_, Err(err)) => Err(err), - } - } - b'{' => { - self.remaining_depth -= 1; - if self.remaining_depth == 0 { - return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); - } - - self.eat_char(); - let ret = visitor.visit_map(MapAccess::new(self)); - - self.remaining_depth += 1; - - match (ret, self.end_map()) { - (Ok(ret), Ok(())) => Ok(ret), - (Err(err), _) | (_, Err(err)) => Err(err), - } - } - _ => Err(self.peek_invalid_type(&visitor)), - }; - - match value { - Ok(value) => Ok(value), - Err(err) => Err(self.fix_position(err)), - } - } - - /// Parses an enum as an object like `{"$KEY":$VALUE}`, where $VALUE is either a straight - /// value, a `[..]`, or a `{..}`. - #[inline] - fn deserialize_enum<V>( - self, - _name: &str, - _variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - match try!(self.parse_whitespace()) { - Some(b'{') => { - self.remaining_depth -= 1; - if self.remaining_depth == 0 { - return Err(self.peek_error(ErrorCode::RecursionLimitExceeded)); - } - - self.eat_char(); - let value = try!(visitor.visit_enum(VariantAccess::new(self))); - - self.remaining_depth += 1; - - match try!(self.parse_whitespace()) { - Some(b'}') => { - self.eat_char(); - Ok(value) - } - Some(_) => Err(self.error(ErrorCode::ExpectedSomeValue)), - None => Err(self.error(ErrorCode::EofWhileParsingObject)), - } - } - Some(b'"') => visitor.visit_enum(UnitVariantAccess::new(self)), - Some(_) => Err(self.peek_error(ErrorCode::ExpectedSomeValue)), - None => Err(self.peek_error(ErrorCode::EofWhileParsingValue)), - } - } - - fn deserialize_identifier<V>( - self, - visitor: V - ) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.deserialize_str(visitor) - } - - fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - try!(self.ignore_value()); - visitor.visit_unit() - } -} - -struct SeqAccess<'a, R: 'a> { - de: &'a mut Deserializer<R>, - first: bool, -} - -impl<'a, R: 'a> SeqAccess<'a, R> { - fn new(de: &'a mut Deserializer<R>) -> Self { - SeqAccess { - de: de, - first: true, - } - } -} - -impl<'de, 'a, R: Read<'de> + 'a> de::SeqAccess<'de> for SeqAccess<'a, R> { - type Error = Error; - - fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> - where - T: de::DeserializeSeed<'de>, - { - let peek = match try!(self.de.parse_whitespace()) { - Some(b']') => { - return Ok(None); - } - Some(b',') if !self.first => { - self.de.eat_char(); - try!(self.de.parse_whitespace()) - } - Some(b) => { - if self.first { - self.first = false; - Some(b) - } else { - return Err(self.de.peek_error(ErrorCode::ExpectedListCommaOrEnd)); - } - } - None => { - return Err(self.de.peek_error(ErrorCode::EofWhileParsingList)); - } - }; - - match peek { - Some(b']') => Err(self.de.peek_error(ErrorCode::TrailingComma)), - Some(_) => Ok(Some(try!(seed.deserialize(&mut *self.de)))), - None => Err(self.de.peek_error(ErrorCode::EofWhileParsingValue)), - } - } -} - -struct MapAccess<'a, R: 'a> { - de: &'a mut Deserializer<R>, - first: bool, -} - -impl<'a, R: 'a> MapAccess<'a, R> { - fn new(de: &'a mut Deserializer<R>) -> Self { - MapAccess { - de: de, - first: true, - } - } -} - -impl<'de, 'a, R: Read<'de> + 'a> de::MapAccess<'de> for MapAccess<'a, R> { - type Error = Error; - - fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> - where - K: de::DeserializeSeed<'de>, - { - let peek = match try!(self.de.parse_whitespace()) { - Some(b'}') => { - return Ok(None); - } - Some(b',') if !self.first => { - self.de.eat_char(); - try!(self.de.parse_whitespace()) - } - Some(b) => { - if self.first { - self.first = false; - Some(b) - } else { - return Err(self.de.peek_error(ErrorCode::ExpectedObjectCommaOrEnd)); - } - } - None => { - return Err(self.de.peek_error(ErrorCode::EofWhileParsingObject)); - } - }; - - match peek { - Some(b'"') => seed.deserialize(MapKey { de: &mut *self.de }).map(Some), - Some(b'}') => Err(self.de.peek_error(ErrorCode::TrailingComma)), - Some(_) => Err(self.de.peek_error(ErrorCode::KeyMustBeAString)), - None => Err(self.de.peek_error(ErrorCode::EofWhileParsingValue)), - } - } - - fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value> - where - V: de::DeserializeSeed<'de>, - { - try!(self.de.parse_object_colon()); - - seed.deserialize(&mut *self.de) - } -} - -struct VariantAccess<'a, R: 'a> { - de: &'a mut Deserializer<R>, -} - -impl<'a, R: 'a> VariantAccess<'a, R> { - fn new(de: &'a mut Deserializer<R>) -> Self { - VariantAccess { de: de } - } -} - -impl<'de, 'a, R: Read<'de> + 'a> de::EnumAccess<'de> for VariantAccess<'a, R> { - type Error = Error; - type Variant = Self; - - fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)> - where - V: de::DeserializeSeed<'de>, - { - let val = try!(seed.deserialize(&mut *self.de)); - try!(self.de.parse_object_colon()); - Ok((val, self)) - } -} - -impl<'de, 'a, R: Read<'de> + 'a> de::VariantAccess<'de> for VariantAccess<'a, R> { - type Error = Error; - - fn unit_variant(self) -> Result<()> { - de::Deserialize::deserialize(self.de) - } - - fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value> - where - T: de::DeserializeSeed<'de>, - { - seed.deserialize(self.de) - } - - fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - de::Deserializer::deserialize_seq(self.de, visitor) - } - - fn struct_variant<V>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - de::Deserializer::deserialize_struct(self.de, "", fields, visitor) - } -} - -struct UnitVariantAccess<'a, R: 'a> { - de: &'a mut Deserializer<R>, -} - -impl<'a, R: 'a> UnitVariantAccess<'a, R> { - fn new(de: &'a mut Deserializer<R>) -> Self { - UnitVariantAccess { de: de } - } -} - -impl<'de, 'a, R: Read<'de> + 'a> de::EnumAccess<'de> for UnitVariantAccess<'a, R> { - type Error = Error; - type Variant = Self; - - fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)> - where - V: de::DeserializeSeed<'de>, - { - let variant = try!(seed.deserialize(&mut *self.de)); - Ok((variant, self)) - } -} - -impl<'de, 'a, R: Read<'de> + 'a> de::VariantAccess<'de> for UnitVariantAccess<'a, R> { - type Error = Error; - - fn unit_variant(self) -> Result<()> { - Ok(()) - } - - fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value> - where - T: de::DeserializeSeed<'de>, - { - Err(de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant"),) - } - - fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - Err(de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"),) - } - - fn struct_variant<V>(self, _fields: &'static [&'static str], _visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - Err(de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"),) - } -} - -/// Only deserialize from this after peeking a '"' byte! Otherwise it may -/// deserialize invalid JSON successfully. -struct MapKey<'a, R: 'a> { - de: &'a mut Deserializer<R>, -} - -macro_rules! deserialize_integer_key { - ($deserialize:ident => $visit:ident) => { - fn $deserialize<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.de.eat_char(); - self.de.str_buf.clear(); - let string = try!(self.de.read.parse_str(&mut self.de.str_buf)); - match (string.parse(), string) { - (Ok(integer), _) => visitor.$visit(integer), - (Err(_), Reference::Borrowed(s)) => visitor.visit_borrowed_str(s), - (Err(_), Reference::Copied(s)) => visitor.visit_str(s), - } - } - } -} - -impl<'de, 'a, R> de::Deserializer<'de> for MapKey<'a, R> -where - R: Read<'de>, -{ - type Error = Error; - - #[inline] - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.de.eat_char(); - self.de.str_buf.clear(); - match try!(self.de.read.parse_str(&mut self.de.str_buf)) { - Reference::Borrowed(s) => visitor.visit_borrowed_str(s), - Reference::Copied(s) => visitor.visit_str(s), - } - } - - deserialize_integer_key!(deserialize_i8 => visit_i8); - deserialize_integer_key!(deserialize_i16 => visit_i16); - deserialize_integer_key!(deserialize_i32 => visit_i32); - deserialize_integer_key!(deserialize_i64 => visit_i64); - deserialize_integer_key!(deserialize_u8 => visit_u8); - deserialize_integer_key!(deserialize_u16 => visit_u16); - deserialize_integer_key!(deserialize_u32 => visit_u32); - deserialize_integer_key!(deserialize_u64 => visit_u64); - - #[inline] - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - // Map keys cannot be null. - visitor.visit_some(self) - } - - #[inline] - fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - visitor.visit_newtype_struct(self) - } - - #[inline] - fn deserialize_enum<V>( - self, - name: &'static str, - variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.de.deserialize_enum(name, variants, visitor) - } - - #[inline] - fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.de.deserialize_bytes(visitor) - } - - #[inline] - fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> - where - V: de::Visitor<'de>, - { - self.de.deserialize_bytes(visitor) - } - - forward_to_deserialize_any! { - bool f32 f64 char str string unit unit_struct seq tuple tuple_struct map - struct identifier ignored_any - } -} - -////////////////////////////////////////////////////////////////////////////// - -/// Iterator that deserializes a stream into multiple JSON values. -/// -/// A stream deserializer can be created from any JSON deserializer using the -/// `Deserializer::into_iter` method. -/// -/// The data can consist of any JSON value. Values need to be a self-delineating value e.g. -/// arrays, objects, or strings, or be followed by whitespace or a self-delineating value. -/// -/// ```rust -/// extern crate serde_json; -/// -/// use serde_json::{Deserializer, Value}; -/// -/// fn main() { -/// let data = "{\"k\": 3}1\"cool\"\"stuff\" 3{} [0, 1, 2]"; -/// -/// let stream = Deserializer::from_str(data).into_iter::<Value>(); -/// -/// for value in stream { -/// println!("{}", value.unwrap()); -/// } -/// } -/// ``` -pub struct StreamDeserializer<'de, R, T> { - de: Deserializer<R>, - offset: usize, - output: PhantomData<T>, - lifetime: PhantomData<&'de ()>, -} - -impl<'de, R, T> StreamDeserializer<'de, R, T> -where - R: read::Read<'de>, - T: de::Deserialize<'de>, -{ - /// Create a JSON stream deserializer from one of the possible serde_json - /// input sources. - /// - /// Typically it is more convenient to use one of these methods instead: - /// - /// - Deserializer::from_str(...).into_iter() - /// - Deserializer::from_bytes(...).into_iter() - /// - Deserializer::from_reader(...).into_iter() - pub fn new(read: R) -> Self { - let offset = read.byte_offset(); - StreamDeserializer { - de: Deserializer::new(read), - offset: offset, - output: PhantomData, - lifetime: PhantomData, - } - } - - /// Returns the number of bytes so far deserialized into a successful `T`. - /// - /// If a stream deserializer returns an EOF error, new data can be joined to - /// `old_data[stream.byte_offset()..]` to try again. - /// - /// ```rust - /// let data = b"[0] [1] ["; - /// - /// let de = serde_json::Deserializer::from_slice(data); - /// let mut stream = de.into_iter::<Vec<i32>>(); - /// assert_eq!(0, stream.byte_offset()); - /// - /// println!("{:?}", stream.next()); // [0] - /// assert_eq!(3, stream.byte_offset()); - /// - /// println!("{:?}", stream.next()); // [1] - /// assert_eq!(7, stream.byte_offset()); - /// - /// println!("{:?}", stream.next()); // error - /// assert_eq!(8, stream.byte_offset()); - /// - /// // If err.is_eof(), can join the remaining data to new data and continue. - /// let remaining = &data[stream.byte_offset()..]; - /// ``` - /// - /// *Note:* In the future this method may be changed to return the number of - /// bytes so far deserialized into a successful T *or* syntactically valid - /// JSON skipped over due to a type error. See [serde-rs/json#70] for an - /// example illustrating this. - /// - /// [serde-rs/json#70]: https://github.com/serde-rs/json/issues/70 - pub fn byte_offset(&self) -> usize { - self.offset - } - - fn peek_end_of_value(&mut self) -> Result<()> { - match try!(self.de.peek()) { - Some(b' ') | Some(b'\n') | Some(b'\t') | Some(b'\r') | - Some(b'"') | Some(b'[') | Some(b']') | Some(b'{') | - Some(b'}') | Some(b',') | Some(b':') | None => Ok(()), - Some(_) => { - let pos = self.de.read.peek_position(); - Err(Error::syntax(ErrorCode::TrailingCharacters, pos.line, pos.column)) - }, - } - } -} - -impl<'de, R, T> Iterator for StreamDeserializer<'de, R, T> -where - R: Read<'de>, - T: de::Deserialize<'de>, -{ - type Item = Result<T>; - - fn next(&mut self) -> Option<Result<T>> { - // skip whitespaces, if any - // this helps with trailing whitespaces, since whitespaces between - // values are handled for us. - match self.de.parse_whitespace() { - Ok(None) => { - self.offset = self.de.read.byte_offset(); - None - } - Ok(Some(b)) => { - // If the value does not have a clear way to show the end of the value - // (like numbers, null, true etc.) we have to look for whitespace or - // the beginning of a self-delineated value. - let self_delineated_value = match b { - b'[' | b'"' | b'{' => true, - _ => false, - }; - self.offset = self.de.read.byte_offset(); - let result = de::Deserialize::deserialize(&mut self.de); - - Some(match result { - Ok(value) => { - self.offset = self.de.read.byte_offset(); - if self_delineated_value { - Ok(value) - } else { - self.peek_end_of_value().map(|_| value) - } - } - Err(e) => Err(e) - }) - } - Err(e) => Some(Err(e)) - } - } -} - -////////////////////////////////////////////////////////////////////////////// - -fn from_trait<'de, R, T>(read: R) -> Result<T> -where - R: Read<'de>, - T: de::Deserialize<'de>, -{ - let mut de = Deserializer::new(read); - let value = try!(de::Deserialize::deserialize(&mut de)); - - // Make sure the whole stream has been consumed. - try!(de.end()); - Ok(value) -} - -/// Deserialize an instance of type `T` from an IO stream of JSON. -/// -/// # Errors -/// -/// This conversion can fail if the structure of the input does not match the -/// structure expected by `T`, for example if `T` is a struct type but the input -/// contains something other than a JSON map. It can also fail if the structure -/// is correct but `T`'s implementation of `Deserialize` decides that something -/// is wrong with the data, for example required struct fields are missing from -/// the JSON map or some number is too big to fit in the expected primitive -/// type. -/// -/// ```rust -/// #[macro_use] -/// extern crate serde_derive; -/// -/// extern crate serde; -/// extern crate serde_json; -/// -/// use std::error::Error; -/// use std::fs::File; -/// use std::path::Path; -/// -/// #[derive(Deserialize, Debug)] -/// struct User { -/// fingerprint: String, -/// location: String, -/// } -/// -/// fn read_user_from_file<P: AsRef<Path>>(path: P) -> Result<User, Box<Error>> { -/// // Open the file in read-only mode. -/// let file = File::open(path)?; -/// -/// // Read the JSON contents of the file as an instance of `User`. -/// let u = serde_json::from_reader(file)?; -/// -/// // Return the `User`. -/// Ok(u) -/// } -/// -/// fn main() { -/// # } -/// # fn fake_main() { -/// let u = read_user_from_file("test.json").unwrap(); -/// println!("{:#?}", u); -/// } -/// ``` -pub fn from_reader<R, T>(rdr: R) -> Result<T> -where - R: io::Read, - T: de::DeserializeOwned, -{ - from_trait(read::IoRead::new(rdr)) -} - -/// Deserialize an instance of type `T` from bytes of JSON text. -/// -/// # Errors -/// -/// This conversion can fail if the structure of the input does not match the -/// structure expected by `T`, for example if `T` is a struct type but the input -/// contains something other than a JSON map. It can also fail if the structure -/// is correct but `T`'s implementation of `Deserialize` decides that something -/// is wrong with the data, for example required struct fields are missing from -/// the JSON map or some number is too big to fit in the expected primitive -/// type. -/// -/// ```rust -/// #[macro_use] -/// extern crate serde_derive; -/// -/// extern crate serde; -/// extern crate serde_json; -/// -/// #[derive(Deserialize, Debug)] -/// struct User { -/// fingerprint: String, -/// location: String, -/// } -/// -/// fn main() { -/// // The type of `j` is `&[u8]` -/// let j = b"{ -/// \"fingerprint\": \"0xF9BA143B95FF6D82\", -/// \"location\": \"Menlo Park, CA\" -/// }"; -/// -/// let u: User = serde_json::from_slice(j).unwrap(); -/// println!("{:#?}", u); -/// } -/// ``` -pub fn from_slice<'a, T>(v: &'a [u8]) -> Result<T> -where - T: de::Deserialize<'a>, -{ - from_trait(read::SliceRead::new(v)) -} - -/// Deserialize an instance of type `T` from a string of JSON text. -/// -/// # Errors -/// -/// This conversion can fail if the structure of the input does not match the -/// structure expected by `T`, for example if `T` is a struct type but the input -/// contains something other than a JSON map. It can also fail if the structure -/// is correct but `T`'s implementation of `Deserialize` decides that something -/// is wrong with the data, for example required struct fields are missing from -/// the JSON map or some number is too big to fit in the expected primitive -/// type. -/// -/// ```rust -/// #[macro_use] -/// extern crate serde_derive; -/// -/// extern crate serde; -/// extern crate serde_json; -/// -/// #[derive(Deserialize, Debug)] -/// struct User { -/// fingerprint: String, -/// location: String, -/// } -/// -/// fn main() { -/// // The type of `j` is `&str` -/// let j = "{ -/// \"fingerprint\": \"0xF9BA143B95FF6D82\", -/// \"location\": \"Menlo Park, CA\" -/// }"; -/// -/// let u: User = serde_json::from_str(j).unwrap(); -/// println!("{:#?}", u); -/// } -/// ``` -pub fn from_str<'a, T>(s: &'a str) -> Result<T> -where - T: de::Deserialize<'a>, -{ - from_trait(read::StrRead::new(s)) -} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/error.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/error.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/error.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/error.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,420 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! When serializing or deserializing JSON goes wrong. - -use std::error; -use std::fmt::{self, Debug, Display}; -use std::io; -use std::result; - -use serde::de; -use serde::ser; - -/// This type represents all possible errors that can occur when serializing or -/// deserializing JSON data. -pub struct Error { - /// This `Box` allows us to keep the size of `Error` as small as possible. A - /// larger `Error` type was substantially slower due to all the functions - /// that pass around `Result<T, Error>`. - err: Box<ErrorImpl>, -} - -/// Alias for a `Result` with the error type `serde_json::Error`. -pub type Result<T> = result::Result<T, Error>; - -impl Error { - /// One-based line number at which the error was detected. - /// - /// Characters in the first line of the input (before the first newline - /// character) are in line 1. - pub fn line(&self) -> usize { - self.err.line - } - - /// One-based column number at which the error was detected. - /// - /// The first character in the input and any characters immediately - /// following a newline character are in column 1. - /// - /// Note that errors may occur in column 0, for example if a read from an IO - /// stream fails immediately following a previously read newline character. - pub fn column(&self) -> usize { - self.err.column - } - - /// Categorizes the cause of this error. - /// - /// - `Category::Io` - failure to read or write bytes on an IO stream - /// - `Category::Syntax` - input that is not syntactically valid JSON - /// - `Category::Data` - input data that is semantically incorrect - /// - `Category::Eof` - unexpected end of the input data - pub fn classify(&self) -> Category { - match self.err.code { - ErrorCode::Message(_) => Category::Data, - ErrorCode::Io(_) => Category::Io, - ErrorCode::EofWhileParsingList | - ErrorCode::EofWhileParsingObject | - ErrorCode::EofWhileParsingString | - ErrorCode::EofWhileParsingValue => Category::Eof, - ErrorCode::ExpectedColon | - ErrorCode::ExpectedListCommaOrEnd | - ErrorCode::ExpectedObjectCommaOrEnd | - ErrorCode::ExpectedObjectOrArray | - ErrorCode::ExpectedSomeIdent | - ErrorCode::ExpectedSomeValue | - ErrorCode::ExpectedSomeString | - ErrorCode::InvalidEscape | - ErrorCode::InvalidNumber | - ErrorCode::NumberOutOfRange | - ErrorCode::InvalidUnicodeCodePoint | - ErrorCode::KeyMustBeAString | - ErrorCode::LoneLeadingSurrogateInHexEscape | - ErrorCode::TrailingComma | - ErrorCode::TrailingCharacters | - ErrorCode::UnexpectedEndOfHexEscape | - ErrorCode::RecursionLimitExceeded => Category::Syntax, - } - } - - /// Returns true if this error was caused by a failure to read or write - /// bytes on an IO stream. - pub fn is_io(&self) -> bool { - self.classify() == Category::Io - } - - /// Returns true if this error was caused by input that was not - /// syntactically valid JSON. - pub fn is_syntax(&self) -> bool { - self.classify() == Category::Syntax - } - - /// Returns true if this error was caused by input data that was - /// semantically incorrect. - /// - /// For example, JSON containing a number is semantically incorrect when the - /// type being deserialized into holds a String. - pub fn is_data(&self) -> bool { - self.classify() == Category::Data - } - - /// Returns true if this error was caused by prematurely reaching the end of - /// the input data. - /// - /// Callers that process streaming input may be interested in retrying the - /// deserialization once more data is available. - pub fn is_eof(&self) -> bool { - self.classify() == Category::Eof - } -} - -/// Categorizes the cause of a `serde_json::Error`. -#[derive(Copy, Clone, PartialEq, Eq, Debug)] -pub enum Category { - /// The error was caused by a failure to read or write bytes on an IO - /// stream. - Io, - - /// The error was caused by input that was not syntactically valid JSON. - Syntax, - - /// The error was caused by input data that was semantically incorrect. - /// - /// For example, JSON containing a number is semantically incorrect when the - /// type being deserialized into holds a String. - Data, - - /// The error was caused by prematurely reaching the end of the input data. - /// - /// Callers that process streaming input may be interested in retrying the - /// deserialization once more data is available. - Eof, -} - -#[cfg_attr(feature = "cargo-clippy", allow(fallible_impl_from))] -impl From<Error> for io::Error { - /// Convert a `serde_json::Error` into an `io::Error`. - /// - /// JSON syntax and data errors are turned into `InvalidData` IO errors. - /// EOF errors are turned into `UnexpectedEof` IO errors. - /// - /// ```rust - /// use std::io; - /// - /// enum MyError { - /// Io(io::Error), - /// Json(serde_json::Error), - /// } - /// - /// impl From<serde_json::Error> for MyError { - /// fn from(err: serde_json::Error) -> MyError { - /// use serde_json::error::Category; - /// match err.classify() { - /// Category::Io => { - /// MyError::Io(err.into()) - /// } - /// Category::Syntax | Category::Data | Category::Eof => { - /// MyError::Json(err) - /// } - /// } - /// } - /// } - /// ``` - fn from(j: Error) -> Self { - if let ErrorCode::Io(err) = j.err.code { - err - } else { - match j.classify() { - Category::Io => unreachable!(), - Category::Syntax | Category::Data => io::Error::new(io::ErrorKind::InvalidData, j), - Category::Eof => io::Error::new(io::ErrorKind::UnexpectedEof, j), - } - } - } -} - -#[derive(Debug)] -struct ErrorImpl { - code: ErrorCode, - line: usize, - column: usize, -} - -// Not public API. Should be pub(crate). -#[doc(hidden)] -#[derive(Debug)] -pub enum ErrorCode { - /// Catchall for syntax error messages - Message(Box<str>), - - /// Some IO error occurred while serializing or deserializing. - Io(io::Error), - - /// EOF while parsing a list. - EofWhileParsingList, - - /// EOF while parsing an object. - EofWhileParsingObject, - - /// EOF while parsing a string. - EofWhileParsingString, - - /// EOF while parsing a JSON value. - EofWhileParsingValue, - - /// Expected this character to be a `':'`. - ExpectedColon, - - /// Expected this character to be either a `','` or a `']'`. - ExpectedListCommaOrEnd, - - /// Expected this character to be either a `','` or a `'}'`. - ExpectedObjectCommaOrEnd, - - /// Expected this character to be either a `'{'` or a `'['`. - ExpectedObjectOrArray, - - /// Expected to parse either a `true`, `false`, or a `null`. - ExpectedSomeIdent, - - /// Expected this character to start a JSON value. - ExpectedSomeValue, - - /// Expected this character to start a JSON string. - ExpectedSomeString, - - /// Invalid hex escape code. - InvalidEscape, - - /// Invalid number. - InvalidNumber, - - /// Number is bigger than the maximum value of its type. - NumberOutOfRange, - - /// Invalid unicode code point. - InvalidUnicodeCodePoint, - - /// Object key is not a string. - KeyMustBeAString, - - /// Lone leading surrogate in hex escape. - LoneLeadingSurrogateInHexEscape, - - /// JSON has a comma after the last value in an array or map. - TrailingComma, - - /// JSON has non-whitespace trailing characters after the value. - TrailingCharacters, - - /// Unexpected end of hex excape. - UnexpectedEndOfHexEscape, - - /// Encountered nesting of JSON maps and arrays more than 128 layers deep. - RecursionLimitExceeded, -} - -impl Error { - // Not public API. Should be pub(crate). - #[doc(hidden)] - pub fn syntax(code: ErrorCode, line: usize, column: usize) -> Self { - Error { - err: Box::new( - ErrorImpl { - code: code, - line: line, - column: column, - }, - ), - } - } - - // Not public API. Should be pub(crate). - #[doc(hidden)] - pub fn io(error: io::Error) -> Self { - Error { - err: Box::new( - ErrorImpl { - code: ErrorCode::Io(error), - line: 0, - column: 0, - }, - ), - } - } - - // Not public API. Should be pub(crate). - #[doc(hidden)] - pub fn fix_position<F>(self, f: F) -> Self - where - F: FnOnce(ErrorCode) -> Error, - { - if self.err.line == 0 { - f(self.err.code) - } else { - self - } - } -} - -impl Display for ErrorCode { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - ErrorCode::Message(ref msg) => f.write_str(msg), - ErrorCode::Io(ref err) => Display::fmt(err, f), - ErrorCode::EofWhileParsingList => f.write_str("EOF while parsing a list"), - ErrorCode::EofWhileParsingObject => f.write_str("EOF while parsing an object"), - ErrorCode::EofWhileParsingString => f.write_str("EOF while parsing a string"), - ErrorCode::EofWhileParsingValue => f.write_str("EOF while parsing a value"), - ErrorCode::ExpectedColon => f.write_str("expected `:`"), - ErrorCode::ExpectedListCommaOrEnd => f.write_str("expected `,` or `]`"), - ErrorCode::ExpectedObjectCommaOrEnd => f.write_str("expected `,` or `}`"), - ErrorCode::ExpectedObjectOrArray => f.write_str("expected `{` or `[`"), - ErrorCode::ExpectedSomeIdent => f.write_str("expected ident"), - ErrorCode::ExpectedSomeValue => f.write_str("expected value"), - ErrorCode::ExpectedSomeString => f.write_str("expected string"), - ErrorCode::InvalidEscape => f.write_str("invalid escape"), - ErrorCode::InvalidNumber => f.write_str("invalid number"), - ErrorCode::NumberOutOfRange => f.write_str("number out of range"), - ErrorCode::InvalidUnicodeCodePoint => f.write_str("invalid unicode code point"), - ErrorCode::KeyMustBeAString => f.write_str("key must be a string"), - ErrorCode::LoneLeadingSurrogateInHexEscape => { - f.write_str("lone leading surrogate in hex escape") - } - ErrorCode::TrailingComma => f.write_str("trailing comma"), - ErrorCode::TrailingCharacters => f.write_str("trailing characters"), - ErrorCode::UnexpectedEndOfHexEscape => f.write_str("unexpected end of hex escape"), - ErrorCode::RecursionLimitExceeded => f.write_str("recursion limit exceeded"), - } - } -} - -impl error::Error for Error { - fn description(&self) -> &str { - match self.err.code { - ErrorCode::Io(ref err) => error::Error::description(err), - _ => { - // If you want a better message, use Display::fmt or to_string(). - "JSON error" - } - } - } - - fn cause(&self) -> Option<&error::Error> { - match self.err.code { - ErrorCode::Io(ref err) => Some(err), - _ => None, - } - } -} - -impl Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - Display::fmt(&*self.err, f) - } -} - -impl Display for ErrorImpl { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if self.line == 0 { - Display::fmt(&self.code, f) - } else { - write!( - f, - "{} at line {} column {}", - self.code, - self.line, - self.column - ) - } - } -} - -// Remove two layers of verbosity from the debug representation. Humans often -// end up seeing this representation because it is what unwrap() shows. -impl Debug for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - Debug::fmt(&*self.err, f) - } -} - -impl de::Error for Error { - fn custom<T: Display>(msg: T) -> Error { - Error { - err: Box::new( - ErrorImpl { - code: ErrorCode::Message(msg.to_string().into_boxed_str()), - line: 0, - column: 0, - }, - ), - } - } - - fn invalid_type(unexp: de::Unexpected, exp: &de::Expected) -> Self { - if let de::Unexpected::Unit = unexp { - Error::custom(format_args!("invalid type: null, expected {}", exp)) - } else { - Error::custom(format_args!("invalid type: {}, expected {}", unexp, exp)) - } - } -} - -impl ser::Error for Error { - fn custom<T: Display>(msg: T) -> Error { - Error { - err: Box::new( - ErrorImpl { - code: ErrorCode::Message(msg.to_string().into_boxed_str()), - line: 0, - column: 0, - }, - ), - } - } -} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/iter.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/iter.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/iter.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/iter.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,78 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::io; - -pub struct LineColIterator<I> { - iter: I, - - /// Index of the current line. Characters in the first line of the input - /// (before the first newline character) are in line 1. - line: usize, - - /// Index of the current column. The first character in the input and any - /// characters immediately following a newline character are in column 1. - /// The column is 0 immediately after a newline character has been read. - col: usize, - - /// Byte offset of the start of the current line. This is the sum of lenghts - /// of all previous lines. Keeping track of things this way allows efficient - /// computation of the current line, column, and byte offset while only - /// updating one of the counters in `next()` in the common case. - start_of_line: usize, -} - -impl<I> LineColIterator<I> -where - I: Iterator<Item = io::Result<u8>>, -{ - pub fn new(iter: I) -> LineColIterator<I> { - LineColIterator { - iter: iter, - line: 1, - col: 0, - start_of_line: 0, - } - } - - pub fn line(&self) -> usize { - self.line - } - - pub fn col(&self) -> usize { - self.col - } - - pub fn byte_offset(&self) -> usize { - self.start_of_line + self.col - } -} - -impl<I> Iterator for LineColIterator<I> -where - I: Iterator<Item = io::Result<u8>>, -{ - type Item = io::Result<u8>; - - fn next(&mut self) -> Option<io::Result<u8>> { - match self.iter.next() { - None => None, - Some(Ok(b'\n')) => { - self.start_of_line += self.col + 1; - self.line += 1; - self.col = 0; - Some(Ok(b'\n')) - } - Some(Ok(c)) => { - self.col += 1; - Some(Ok(c)) - } - Some(Err(e)) => Some(Err(e)), - } - } -} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/lib.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/lib.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,385 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! # Serde JSON -//! -//! JSON is a ubiquitous open-standard format that uses human-readable text to -//! transmit data objects consisting of key-value pairs. -//! -//! ```json,ignore -//! { -//! "name": "John Doe", -//! "age": 43, -//! "address": { -//! "street": "10 Downing Street", -//! "city": "London" -//! }, -//! "phones": [ -//! "+44 1234567", -//! "+44 2345678" -//! ] -//! } -//! ``` -//! -//! There are three common ways that you might find yourself needing to work -//! with JSON data in Rust. -//! -//! - **As text data.** An unprocessed string of JSON data that you receive on -//! an HTTP endpoint, read from a file, or prepare to send to a remote -//! server. -//! - **As an untyped or loosely typed representation.** Maybe you want to -//! check that some JSON data is valid before passing it on, but without -//! knowing the structure of what it contains. Or you want to do very basic -//! manipulations like insert a key in a particular spot. -//! - **As a strongly typed Rust data structure.** When you expect all or most -//! of your data to conform to a particular structure and want to get real -//! work done without JSON's loosey-goosey nature tripping you up. -//! -//! Serde JSON provides efficient, flexible, safe ways of converting data -//! between each of these representations. -//! -//! # Operating on untyped JSON values -//! -//! Any valid JSON data can be manipulated in the following recursive enum -//! representation. This data structure is [`serde_json::Value`][value]. -//! -//! ```rust -//! # use serde_json::{Number, Map}; -//! # -//! # #[allow(dead_code)] -//! enum Value { -//! Null, -//! Bool(bool), -//! Number(Number), -//! String(String), -//! Array(Vec<Value>), -//! Object(Map<String, Value>), -//! } -//! ``` -//! -//! A string of JSON data can be parsed into a `serde_json::Value` by the -//! [`serde_json::from_str`][from_str] function. There is also -//! [`from_slice`][from_slice] for parsing from a byte slice &[u8] and -//! [`from_reader`][from_reader] for parsing from any `io::Read` like a File or -//! a TCP stream. -//! -//! ```rust -//! extern crate serde_json; -//! -//! use serde_json::{Value, Error}; -//! -//! fn untyped_example() -> Result<(), Error> { -//! // Some JSON input data as a &str. Maybe this comes from the user. -//! let data = r#"{ -//! "name": "John Doe", -//! "age": 43, -//! "phones": [ -//! "+44 1234567", -//! "+44 2345678" -//! ] -//! }"#; -//! -//! // Parse the string of data into serde_json::Value. -//! let v: Value = serde_json::from_str(data)?; -//! -//! // Access parts of the data by indexing with square brackets. -//! println!("Please call {} at the number {}", v["name"], v["phones"][0]); -//! -//! Ok(()) -//! } -//! # -//! # fn main() { -//! # untyped_example().unwrap(); -//! # } -//! ``` -//! -//! The result of square bracket indexing like `v["name"]` is a borrow of the -//! data at that index, so the type is `&Value`. A JSON map can be indexed with -//! string keys, while a JSON array can be indexed with integer keys. If the -//! type of the data is not right for the type with which it is being indexed, -//! or if a map does not contain the key being indexed, or if the index into a -//! vector is out of bounds, the returned element is `Value::Null`. -//! -//! When a `Value` is printed, it is printed as a JSON string. So in the code -//! above, the output looks like `Please call "John Doe" at the number "+44 -//! 1234567"`. The quotation marks appear because `v["name"]` is a `&Value` -//! containing a JSON string and its JSON representation is `"John Doe"`. -//! Printing as a plain string without quotation marks involves converting from -//! a JSON string to a Rust string with [`as_str()`] or avoiding the use of -//! `Value` as described in the following section. -//! -//! [`as_str()`]: https://docs.serde.rs/serde_json/enum.Value.html#method.as_str -//! -//! The `Value` representation is sufficient for very basic tasks but can be -//! tedious to work with for anything more significant. Error handling is -//! verbose to implement correctly, for example imagine trying to detect the -//! presence of unrecognized fields in the input data. The compiler is powerless -//! to help you when you make a mistake, for example imagine typoing `v["name"]` -//! as `v["nmae"]` in one of the dozens of places it is used in your code. -//! -//! # Parsing JSON as strongly typed data structures -//! -//! Serde provides a powerful way of mapping JSON data into Rust data structures -//! largely automatically. -//! -//! ```rust -//! extern crate serde; -//! extern crate serde_json; -//! -//! #[macro_use] -//! extern crate serde_derive; -//! -//! use serde_json::Error; -//! -//! #[derive(Serialize, Deserialize)] -//! struct Person { -//! name: String, -//! age: u8, -//! phones: Vec<String>, -//! } -//! -//! fn typed_example() -> Result<(), Error> { -//! // Some JSON input data as a &str. Maybe this comes from the user. -//! let data = r#"{ -//! "name": "John Doe", -//! "age": 43, -//! "phones": [ -//! "+44 1234567", -//! "+44 2345678" -//! ] -//! }"#; -//! -//! // Parse the string of data into a Person object. This is exactly the -//! // same function as the one that produced serde_json::Value above, but -//! // now we are asking it for a Person as output. -//! let p: Person = serde_json::from_str(data)?; -//! -//! // Do things just like with any other Rust data structure. -//! println!("Please call {} at the number {}", p.name, p.phones[0]); -//! -//! Ok(()) -//! } -//! # -//! # fn main() { -//! # typed_example().unwrap(); -//! # } -//! ``` -//! -//! This is the same `serde_json::from_str` function as before, but this time we -//! assign the return value to a variable of type `Person` so Serde will -//! automatically interpret the input data as a `Person` and produce informative -//! error messages if the layout does not conform to what a `Person` is expected -//! to look like. -//! -//! Any type that implements Serde's `Deserialize` trait can be deserialized -//! this way. This includes built-in Rust standard library types like `Vec<T>` -//! and `HashMap<K, V>`, as well as any structs or enums annotated with -//! `#[derive(Deserialize)]`. -//! -//! Once we have `p` of type `Person`, our IDE and the Rust compiler can help us -//! use it correctly like they do for any other Rust code. The IDE can -//! autocomplete field names to prevent typos, which was impossible in the -//! `serde_json::Value` representation. And the Rust compiler can check that -//! when we write `p.phones[0]`, then `p.phones` is guaranteed to be a -//! `Vec<String>` so indexing into it makes sense and produces a `String`. -//! -//! # Constructing JSON values -//! -//! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` -//! objects with very natural JSON syntax. In order to use this macro, -//! `serde_json` needs to be imported with the `#[macro_use]` attribute. -//! -//! ```rust -//! #[macro_use] -//! extern crate serde_json; -//! -//! fn main() { -//! // The type of `john` is `serde_json::Value` -//! let john = json!({ -//! "name": "John Doe", -//! "age": 43, -//! "phones": [ -//! "+44 1234567", -//! "+44 2345678" -//! ] -//! }); -//! -//! println!("first phone number: {}", john["phones"][0]); -//! -//! // Convert to a string of JSON and print it out -//! println!("{}", john.to_string()); -//! } -//! ``` -//! -//! The `Value::to_string()` function converts a `serde_json::Value` into a -//! `String` of JSON text. -//! -//! One neat thing about the `json!` macro is that variables and expressions can -//! be interpolated directly into the JSON value as you are building it. Serde -//! will check at compile time that the value you are interpolating is able to -//! be represented as JSON. -//! -//! ```rust -//! # #[macro_use] -//! # extern crate serde_json; -//! # -//! # fn random_phone() -> u16 { 0 } -//! # -//! # fn main() { -//! let full_name = "John Doe"; -//! let age_last_year = 42; -//! -//! // The type of `john` is `serde_json::Value` -//! let john = json!({ -//! "name": full_name, -//! "age": age_last_year + 1, -//! "phones": [ -//! format!("+44 {}", random_phone()) -//! ] -//! }); -//! # let _ = john; -//! # } -//! ``` -//! -//! This is amazingly convenient but we have the problem we had before with -//! `Value` which is that the IDE and Rust compiler cannot help us if we get it -//! wrong. Serde JSON provides a better way of serializing strongly-typed data -//! structures into JSON text. -//! -//! # Creating JSON by serializing data structures -//! -//! A data structure can be converted to a JSON string by -//! [`serde_json::to_string`][to_string]. There is also -//! [`serde_json::to_vec`][to_vec] which serializes to a `Vec<u8>` and -//! [`serde_json::to_writer`][to_writer] which serializes to any `io::Write` -//! such as a File or a TCP stream. -//! -//! ```rust -//! extern crate serde; -//! extern crate serde_json; -//! -//! #[macro_use] -//! extern crate serde_derive; -//! -//! use serde_json::Error; -//! -//! #[derive(Serialize, Deserialize)] -//! struct Address { -//! street: String, -//! city: String, -//! } -//! -//! fn print_an_address() -> Result<(), Error> { -//! // Some data structure. -//! let address = Address { -//! street: "10 Downing Street".to_owned(), -//! city: "London".to_owned(), -//! }; -//! -//! // Serialize it to a JSON string. -//! let j = serde_json::to_string(&address)?; -//! -//! // Print, write to a file, or send to an HTTP server. -//! println!("{}", j); -//! -//! Ok(()) -//! } -//! # -//! # fn main() { -//! # print_an_address().unwrap(); -//! # } -//! ``` -//! -//! Any type that implements Serde's `Serialize` trait can be serialized this -//! way. This includes built-in Rust standard library types like `Vec<T>` and -//! `HashMap<K, V>`, as well as any structs or enums annotated with -//! `#[derive(Serialize)]`. -//! -//! [value]: https://docs.serde.rs/serde_json/value/enum.Value.html -//! [from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html -//! [from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html -//! [from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html -//! [to_string]: https://docs.serde.rs/serde_json/ser/fn.to_string.html -//! [to_vec]: https://docs.serde.rs/serde_json/ser/fn.to_vec.html -//! [to_writer]: https://docs.serde.rs/serde_json/ser/fn.to_writer.html -//! [macro]: https://docs.serde.rs/serde_json/macro.json.html - -#![doc(html_root_url = "https://docs.rs/serde_json/1.0.9")] -#![cfg_attr(feature = "cargo-clippy", deny(clippy, clippy_pedantic))] -// Whitelisted clippy lints -#![cfg_attr(feature = "cargo-clippy", allow( - doc_markdown, - needless_pass_by_value, -))] -// Whitelisted clippy_pedantic lints -#![cfg_attr(feature = "cargo-clippy", allow( -// Deserializer::from_str, into_iter - should_implement_trait, -// integer and float ser/de requires these sorts of casts - cast_possible_truncation, - cast_possible_wrap, - cast_precision_loss, - cast_sign_loss, -// string ser/de uses indexing and slicing - indexing_slicing, -// things are often more readable this way - cast_lossless, - shadow_reuse, - shadow_unrelated, - single_match_else, - stutter, - use_self, -// not practical - missing_docs_in_private_items, -))] - -#![deny(missing_docs)] - -extern crate num_traits; -#[macro_use] -extern crate serde; -extern crate itoa; -extern crate dtoa; -#[cfg(feature = "preserve_order")] -extern crate linked_hash_map; - -#[doc(inline)] -pub use self::de::{Deserializer, StreamDeserializer, from_reader, from_slice, from_str}; -#[doc(inline)] -pub use self::error::{Error, Result}; -#[doc(inline)] -pub use self::ser::{Serializer, to_string, to_string_pretty, to_vec, to_vec_pretty, to_writer, - to_writer_pretty}; -#[doc(inline)] -pub use self::value::{Map, Number, Value, from_value, to_value}; - -// We only use our own error type; no need for From conversions provided by the -// standard library's try! macro. This reduces lines of LLVM IR by 4%. -macro_rules! try { - ($e:expr) => { - match $e { - ::std::result::Result::Ok(val) => val, - ::std::result::Result::Err(err) => { - return ::std::result::Result::Err(err) - } - } - } -} - -#[macro_use] -mod macros; - -pub mod de; -pub mod error; -pub mod map; -pub mod ser; -pub mod value; - -mod iter; -mod number; -mod read; diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/macros.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/macros.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/macros.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/macros.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,282 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/// Construct a `serde_json::Value` from a JSON literal. -/// -/// ```rust -/// # #[macro_use] -/// # extern crate serde_json; -/// # -/// # fn main() { -/// let value = json!({ -/// "code": 200, -/// "success": true, -/// "payload": { -/// "features": [ -/// "serde", -/// "json" -/// ] -/// } -/// }); -/// # } -/// ``` -/// -/// Variables or expressions can be interpolated into the JSON literal. Any type -/// interpolated into an array element or object value must implement Serde's -/// `Serialize` trait, while any type interpolated into a object key must -/// implement `Into<String>`. If the `Serialize` implementation of the -/// interpolated type decides to fail, or if the interpolated type contains a -/// map with non-string keys, the `json!` macro will panic. -/// -/// ```rust -/// # #[macro_use] -/// # extern crate serde_json; -/// # -/// # fn main() { -/// let code = 200; -/// let features = vec!["serde", "json"]; -/// -/// let value = json!({ -/// "code": code, -/// "success": code == 200, -/// "payload": { -/// features[0]: features[1] -/// } -/// }); -/// # } -/// ``` -/// -/// Trailing commas are allowed inside both arrays and objects. -/// -/// ```rust -/// # #[macro_use] -/// # extern crate serde_json; -/// # -/// # fn main() { -/// let value = json!([ -/// "notice", -/// "the", -/// "trailing", -/// "comma -->", -/// ]); -/// # } -/// ``` -#[macro_export] -macro_rules! json { - // Hide distracting implementation details from the generated rustdoc. - ($($json:tt)+) => { - json_internal!($($json)+) - }; -} - -// Rocket relies on this because they export their own `json!` with a different -// doc comment than ours, and various Rust bugs prevent them from calling our -// `json!` from their `json!` so they call `json_internal!` directly. Check with -// @SergioBenitez before making breaking changes to this macro. -// -// Changes are fine as long as `json_internal!` does not call any new helper -// macros and can still be invoked as `json_internal!($($json)+)`. -#[macro_export] -#[doc(hidden)] -macro_rules! json_internal { - ////////////////////////////////////////////////////////////////////////// - // TT muncher for parsing the inside of an array [...]. Produces a vec![...] - // of the elements. - // - // Must be invoked as: json_internal!(@array [] $($tt)*) - ////////////////////////////////////////////////////////////////////////// - - // Done with trailing comma. - (@array [$($elems:expr,)*]) => { - vec![$($elems,)*] - }; - - // Done without trailing comma. - (@array [$($elems:expr),*]) => { - vec![$($elems),*] - }; - - // Next element is `null`. - (@array [$($elems:expr,)*] null $($rest:tt)*) => { - json_internal!(@array [$($elems,)* json_internal!(null)] $($rest)*) - }; - - // Next element is `true`. - (@array [$($elems:expr,)*] true $($rest:tt)*) => { - json_internal!(@array [$($elems,)* json_internal!(true)] $($rest)*) - }; - - // Next element is `false`. - (@array [$($elems:expr,)*] false $($rest:tt)*) => { - json_internal!(@array [$($elems,)* json_internal!(false)] $($rest)*) - }; - - // Next element is an array. - (@array [$($elems:expr,)*] [$($array:tt)*] $($rest:tt)*) => { - json_internal!(@array [$($elems,)* json_internal!([$($array)*])] $($rest)*) - }; - - // Next element is a map. - (@array [$($elems:expr,)*] {$($map:tt)*} $($rest:tt)*) => { - json_internal!(@array [$($elems,)* json_internal!({$($map)*})] $($rest)*) - }; - - // Next element is an expression followed by comma. - (@array [$($elems:expr,)*] $next:expr, $($rest:tt)*) => { - json_internal!(@array [$($elems,)* json_internal!($next),] $($rest)*) - }; - - // Last element is an expression with no trailing comma. - (@array [$($elems:expr,)*] $last:expr) => { - json_internal!(@array [$($elems,)* json_internal!($last)]) - }; - - // Comma after the most recent element. - (@array [$($elems:expr),*] , $($rest:tt)*) => { - json_internal!(@array [$($elems,)*] $($rest)*) - }; - - ////////////////////////////////////////////////////////////////////////// - // TT muncher for parsing the inside of an object {...}. Each entry is - // inserted into the given map variable. - // - // Must be invoked as: json_internal!(@object $map () ($($tt)*) ($($tt)*)) - // - // We require two copies of the input tokens so that we can match on one - // copy and trigger errors on the other copy. - ////////////////////////////////////////////////////////////////////////// - - // Done. - (@object $object:ident () () ()) => {}; - - // Insert the current entry followed by trailing comma. - (@object $object:ident [$($key:tt)+] ($value:expr) , $($rest:tt)*) => { - $object.insert(($($key)+).into(), $value); - json_internal!(@object $object () ($($rest)*) ($($rest)*)); - }; - - // Insert the last entry without trailing comma. - (@object $object:ident [$($key:tt)+] ($value:expr)) => { - $object.insert(($($key)+).into(), $value); - }; - - // Next value is `null`. - (@object $object:ident ($($key:tt)+) (: null $($rest:tt)*) $copy:tt) => { - json_internal!(@object $object [$($key)+] (json_internal!(null)) $($rest)*); - }; - - // Next value is `true`. - (@object $object:ident ($($key:tt)+) (: true $($rest:tt)*) $copy:tt) => { - json_internal!(@object $object [$($key)+] (json_internal!(true)) $($rest)*); - }; - - // Next value is `false`. - (@object $object:ident ($($key:tt)+) (: false $($rest:tt)*) $copy:tt) => { - json_internal!(@object $object [$($key)+] (json_internal!(false)) $($rest)*); - }; - - // Next value is an array. - (@object $object:ident ($($key:tt)+) (: [$($array:tt)*] $($rest:tt)*) $copy:tt) => { - json_internal!(@object $object [$($key)+] (json_internal!([$($array)*])) $($rest)*); - }; - - // Next value is a map. - (@object $object:ident ($($key:tt)+) (: {$($map:tt)*} $($rest:tt)*) $copy:tt) => { - json_internal!(@object $object [$($key)+] (json_internal!({$($map)*})) $($rest)*); - }; - - // Next value is an expression followed by comma. - (@object $object:ident ($($key:tt)+) (: $value:expr , $($rest:tt)*) $copy:tt) => { - json_internal!(@object $object [$($key)+] (json_internal!($value)) , $($rest)*); - }; - - // Last value is an expression with no trailing comma. - (@object $object:ident ($($key:tt)+) (: $value:expr) $copy:tt) => { - json_internal!(@object $object [$($key)+] (json_internal!($value))); - }; - - // Missing value for last entry. Trigger a reasonable error message. - (@object $object:ident ($($key:tt)+) (:) $copy:tt) => { - // "unexpected end of macro invocation" - json_internal!(); - }; - - // Missing colon and value for last entry. Trigger a reasonable error - // message. - (@object $object:ident ($($key:tt)+) () $copy:tt) => { - // "unexpected end of macro invocation" - json_internal!(); - }; - - // Misplaced colon. Trigger a reasonable error message. - (@object $object:ident () (: $($rest:tt)*) ($colon:tt $($copy:tt)*)) => { - // Takes no arguments so "no rules expected the token `:`". - unimplemented!($colon); - }; - - // Found a comma inside a key. Trigger a reasonable error message. - (@object $object:ident ($($key:tt)*) (, $($rest:tt)*) ($comma:tt $($copy:tt)*)) => { - // Takes no arguments so "no rules expected the token `,`". - unimplemented!($comma); - }; - - // Key is fully parenthesized. This avoids clippy double_parens false - // positives because the parenthesization may be necessary here. - (@object $object:ident () (($key:expr) : $($rest:tt)*) $copy:tt) => { - json_internal!(@object $object ($key) (: $($rest)*) (: $($rest)*)); - }; - - // Munch a token into the current key. - (@object $object:ident ($($key:tt)*) ($tt:tt $($rest:tt)*) $copy:tt) => { - json_internal!(@object $object ($($key)* $tt) ($($rest)*) ($($rest)*)); - }; - - ////////////////////////////////////////////////////////////////////////// - // The main implementation. - // - // Must be invoked as: json_internal!($($json)+) - ////////////////////////////////////////////////////////////////////////// - - (null) => { - $crate::Value::Null - }; - - (true) => { - $crate::Value::Bool(true) - }; - - (false) => { - $crate::Value::Bool(false) - }; - - ([]) => { - $crate::Value::Array(vec![]) - }; - - ([ $($tt:tt)+ ]) => { - $crate::Value::Array(json_internal!(@array [] $($tt)+)) - }; - - ({}) => { - $crate::Value::Object($crate::Map::new()) - }; - - ({ $($tt:tt)+ }) => { - $crate::Value::Object({ - let mut object = $crate::Map::new(); - json_internal!(@object object () ($($tt)+) ($($tt)+)); - object - }) - }; - - // Any Serialize type: numbers, strings, struct literals, variables etc. - // Must be below every other rule. - ($other:expr) => { - $crate::to_value(&$other).unwrap() - }; -} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/map.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/map.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/map.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/map.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,796 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A map of String to serde_json::Value. -//! -//! By default the map is backed by a [`BTreeMap`]. Enable the `preserve_order` -//! feature of serde_json to use [`LinkedHashMap`] instead. -//! -//! [`BTreeMap`]: https://doc.rust-lang.org/std/collections/struct.BTreeMap.html -//! [`LinkedHashMap`]: https://docs.rs/linked-hash-map/*/linked_hash_map/struct.LinkedHashMap.html - -use serde::{ser, de}; -use std::fmt::{self, Debug}; -use value::Value; -use std::hash::Hash; -use std::iter::FromIterator; -use std::borrow::Borrow; -use std::ops; - -#[cfg(not(feature = "preserve_order"))] -use std::collections::{BTreeMap, btree_map}; - -#[cfg(feature = "preserve_order")] -use linked_hash_map::{self, LinkedHashMap}; - -/// Represents a JSON key/value type. -pub struct Map<K, V> { - map: MapImpl<K, V>, -} - -#[cfg(not(feature = "preserve_order"))] -type MapImpl<K, V> = BTreeMap<K, V>; -#[cfg(feature = "preserve_order")] -type MapImpl<K, V> = LinkedHashMap<K, V>; - -impl Map<String, Value> { - /// Makes a new empty Map. - #[inline] - pub fn new() -> Self { - Map { map: MapImpl::new() } - } - - #[cfg(not(feature = "preserve_order"))] - /// Makes a new empty Map with the given initial capacity. - #[inline] - pub fn with_capacity(capacity: usize) -> Self { - // does not support with_capacity - let _ = capacity; - Map { map: BTreeMap::new() } - } - - #[cfg(feature = "preserve_order")] - /// Makes a new empty Map with the given initial capacity. - #[inline] - pub fn with_capacity(capacity: usize) -> Self { - Map { map: LinkedHashMap::with_capacity(capacity) } - } - - /// Clears the map, removing all values. - #[inline] - pub fn clear(&mut self) { - self.map.clear() - } - - /// Returns a reference to the value corresponding to the key. - /// - /// The key may be any borrowed form of the map's key type, but the ordering - /// on the borrowed form *must* match the ordering on the key type. - #[inline] - pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&Value> - where - String: Borrow<Q>, - Q: Ord + Eq + Hash, - { - self.map.get(key) - } - - /// Returns true if the map contains a value for the specified key. - /// - /// The key may be any borrowed form of the map's key type, but the ordering - /// on the borrowed form *must* match the ordering on the key type. - #[inline] - pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool - where - String: Borrow<Q>, - Q: Ord + Eq + Hash, - { - self.map.contains_key(key) - } - - /// Returns a mutable reference to the value corresponding to the key. - /// - /// The key may be any borrowed form of the map's key type, but the ordering - /// on the borrowed form *must* match the ordering on the key type. - #[inline] - pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut Value> - where - String: Borrow<Q>, - Q: Ord + Eq + Hash, - { - self.map.get_mut(key) - } - - /// Inserts a key-value pair into the map. - /// - /// If the map did not have this key present, `None` is returned. - /// - /// If the map did have this key present, the value is updated, and the old - /// value is returned. The key is not updated, though; this matters for - /// types that can be `==` without being identical. - #[inline] - pub fn insert(&mut self, k: String, v: Value) -> Option<Value> { - self.map.insert(k, v) - } - - /// Removes a key from the map, returning the value at the key if the key - /// was previously in the map. - /// - /// The key may be any borrowed form of the map's key type, but the ordering - /// on the borrowed form *must* match the ordering on the key type. - #[inline] - pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<Value> - where - String: Borrow<Q>, - Q: Ord + Eq + Hash, - { - self.map.remove(key) - } - - /// Gets the given key's corresponding entry in the map for in-place - /// manipulation. - pub fn entry<S>(&mut self, key: S) -> Entry - where - S: Into<String>, - { - #[cfg(not(feature = "preserve_order"))] - use std::collections::btree_map::Entry as EntryImpl; - #[cfg(feature = "preserve_order")] - use linked_hash_map::Entry as EntryImpl; - - match self.map.entry(key.into()) { - EntryImpl::Vacant(vacant) => Entry::Vacant(VacantEntry { vacant: vacant }), - EntryImpl::Occupied(occupied) => Entry::Occupied(OccupiedEntry { occupied: occupied }), - } - } - - /// Returns the number of elements in the map. - #[inline] - pub fn len(&self) -> usize { - self.map.len() - } - - /// Returns true if the map contains no elements. - #[inline] - pub fn is_empty(&self) -> bool { - self.map.is_empty() - } - - /// Gets an iterator over the entries of the map. - #[inline] - pub fn iter(&self) -> Iter { - Iter { iter: self.map.iter() } - } - - /// Gets a mutable iterator over the entries of the map. - #[inline] - pub fn iter_mut(&mut self) -> IterMut { - IterMut { iter: self.map.iter_mut() } - } - - /// Gets an iterator over the keys of the map. - #[inline] - pub fn keys(&self) -> Keys { - Keys { iter: self.map.keys() } - } - - /// Gets an iterator over the values of the map. - #[inline] - pub fn values(&self) -> Values { - Values { iter: self.map.values() } - } -} - -impl Default for Map<String, Value> { - #[inline] - fn default() -> Self { - Map { map: MapImpl::new() } - } -} - -impl Clone for Map<String, Value> { - #[inline] - fn clone(&self) -> Self { - Map { map: self.map.clone() } - } -} - -impl PartialEq for Map<String, Value> { - #[inline] - fn eq(&self, other: &Self) -> bool { - self.map.eq(&other.map) - } -} - -/// Access an element of this map. Panics if the given key is not present in the -/// map. -/// -/// ```rust -/// # use serde_json::Value; -/// # -/// # let val = &Value::String("".to_owned()); -/// # let _ = -/// match *val { -/// Value::String(ref s) => Some(s.as_str()), -/// Value::Array(ref arr) => arr[0].as_str(), -/// Value::Object(ref map) => map["type"].as_str(), -/// _ => None, -/// } -/// # ; -/// ``` -impl<'a, Q: ?Sized> ops::Index<&'a Q> for Map<String, Value> -where - String: Borrow<Q>, - Q: Ord + Eq + Hash, -{ - type Output = Value; - - fn index(&self, index: &Q) -> &Value { - self.map.index(index) - } -} - -/// Mutably access an element of this map. Panics if the given key is not -/// present in the map. -/// -/// ```rust -/// # #[macro_use] -/// # extern crate serde_json; -/// # -/// # fn main() { -/// # let mut map = serde_json::Map::new(); -/// # map.insert("key".to_owned(), serde_json::Value::Null); -/// # -/// map["key"] = json!("value"); -/// # } -/// ``` -impl<'a, Q: ?Sized> ops::IndexMut<&'a Q> for Map<String, Value> -where - String: Borrow<Q>, - Q: Ord + Eq + Hash, -{ - fn index_mut(&mut self, index: &Q) -> &mut Value { - self.map.get_mut(index).expect("no entry found for key") - } -} - -impl Debug for Map<String, Value> { - #[inline] - fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { - self.map.fmt(formatter) - } -} - -impl ser::Serialize for Map<String, Value> { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: ser::Serializer, - { - use serde::ser::SerializeMap; - let mut map = try!(serializer.serialize_map(Some(self.len()))); - for (k, v) in self { - try!(map.serialize_key(k)); - try!(map.serialize_value(v)); - } - map.end() - } -} - -impl<'de> de::Deserialize<'de> for Map<String, Value> { - #[inline] - fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> - where - D: de::Deserializer<'de>, - { - struct Visitor; - - impl<'de> de::Visitor<'de> for Visitor { - type Value = Map<String, Value>; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a map") - } - - #[inline] - fn visit_unit<E>(self) -> Result<Self::Value, E> - where - E: de::Error, - { - Ok(Map::new()) - } - - #[inline] - fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> - where - V: de::MapAccess<'de>, - { - let mut values = Map::new(); - - while let Some((key, value)) = try!(visitor.next_entry()) { - values.insert(key, value); - } - - Ok(values) - } - } - - deserializer.deserialize_map(Visitor) - } -} - -impl FromIterator<(String, Value)> for Map<String, Value> { - fn from_iter<T>(iter: T) -> Self - where - T: IntoIterator<Item = (String, Value)>, - { - Map { map: FromIterator::from_iter(iter) } - } -} - -impl Extend<(String, Value)> for Map<String, Value> { - fn extend<T>(&mut self, iter: T) - where - T: IntoIterator<Item = (String, Value)>, - { - self.map.extend(iter); - } -} - -macro_rules! delegate_iterator { - (($name:ident $($generics:tt)*) => $item:ty) => { - impl $($generics)* Iterator for $name $($generics)* { - type Item = $item; - #[inline] - fn next(&mut self) -> Option<Self::Item> { - self.iter.next() - } - #[inline] - fn size_hint(&self) -> (usize, Option<usize>) { - self.iter.size_hint() - } - } - - impl $($generics)* DoubleEndedIterator for $name $($generics)* { - #[inline] - fn next_back(&mut self) -> Option<Self::Item> { - self.iter.next_back() - } - } - - impl $($generics)* ExactSizeIterator for $name $($generics)* { - #[inline] - fn len(&self) -> usize { - self.iter.len() - } - } - } -} - -////////////////////////////////////////////////////////////////////////////// - -/// A view into a single entry in a map, which may either be vacant or occupied. -/// This enum is constructed from the [`entry`] method on [`Map`]. -/// -/// [`entry`]: struct.Map.html#method.entry -/// [`Map`]: struct.Map.html -pub enum Entry<'a> { - /// A vacant Entry. - Vacant(VacantEntry<'a>), - /// An occupied Entry. - Occupied(OccupiedEntry<'a>), -} - -/// A vacant Entry. It is part of the [`Entry`] enum. -/// -/// [`Entry`]: enum.Entry.html -pub struct VacantEntry<'a> { - vacant: VacantEntryImpl<'a>, -} - -/// An occupied Entry. It is part of the [`Entry`] enum. -/// -/// [`Entry`]: enum.Entry.html -pub struct OccupiedEntry<'a> { - occupied: OccupiedEntryImpl<'a>, -} - -#[cfg(not(feature = "preserve_order"))] -type VacantEntryImpl<'a> = btree_map::VacantEntry<'a, String, Value>; -#[cfg(feature = "preserve_order")] -type VacantEntryImpl<'a> = linked_hash_map::VacantEntry<'a, String, Value>; - -#[cfg(not(feature = "preserve_order"))] -type OccupiedEntryImpl<'a> = btree_map::OccupiedEntry<'a, String, Value>; -#[cfg(feature = "preserve_order")] -type OccupiedEntryImpl<'a> = linked_hash_map::OccupiedEntry<'a, String, Value>; - -impl<'a> Entry<'a> { - /// Returns a reference to this entry's key. - /// - /// # Examples - /// - /// ```rust - /// let mut map = serde_json::Map::new(); - /// assert_eq!(map.entry("serde").key(), &"serde"); - /// ``` - pub fn key(&self) -> &String { - match *self { - Entry::Vacant(ref e) => e.key(), - Entry::Occupied(ref e) => e.key(), - } - } - - /// Ensures a value is in the entry by inserting the default if empty, and - /// returns a mutable reference to the value in the entry. - /// - /// # Examples - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let mut map = serde_json::Map::new(); - /// map.entry("serde").or_insert(json!(12)); - /// - /// assert_eq!(map["serde"], 12); - /// # } - /// ``` - pub fn or_insert(self, default: Value) -> &'a mut Value { - match self { - Entry::Vacant(entry) => entry.insert(default), - Entry::Occupied(entry) => entry.into_mut(), - } - } - - /// Ensures a value is in the entry by inserting the result of the default - /// function if empty, and returns a mutable reference to the value in the - /// entry. - /// - /// # Examples - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let mut map = serde_json::Map::new(); - /// map.entry("serde").or_insert_with(|| json!("hoho")); - /// - /// assert_eq!(map["serde"], "hoho".to_owned()); - /// # } - /// ``` - pub fn or_insert_with<F>(self, default: F) -> &'a mut Value - where - F: FnOnce() -> Value, - { - match self { - Entry::Vacant(entry) => entry.insert(default()), - Entry::Occupied(entry) => entry.into_mut(), - } - } -} - -impl<'a> VacantEntry<'a> { - /// Gets a reference to the key that would be used when inserting a value - /// through the VacantEntry. - /// - /// # Examples - /// - /// ```rust - /// use serde_json::map::Entry; - /// - /// let mut map = serde_json::Map::new(); - /// - /// match map.entry("serde") { - /// Entry::Vacant(vacant) => { - /// assert_eq!(vacant.key(), &"serde"); - /// } - /// Entry::Occupied(_) => unimplemented!(), - /// } - /// ``` - #[inline] - pub fn key(&self) -> &String { - self.vacant.key() - } - - /// Sets the value of the entry with the VacantEntry's key, and returns a - /// mutable reference to it. - /// - /// # Examples - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::map::Entry; - /// - /// let mut map = serde_json::Map::new(); - /// - /// match map.entry("serde") { - /// Entry::Vacant(vacant) => { - /// vacant.insert(json!("hoho")); - /// } - /// Entry::Occupied(_) => unimplemented!(), - /// } - /// # } - /// ``` - #[inline] - pub fn insert(self, value: Value) -> &'a mut Value { - self.vacant.insert(value) - } -} - -impl<'a> OccupiedEntry<'a> { - /// Gets a reference to the key in the entry. - /// - /// # Examples - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::map::Entry; - /// - /// let mut map = serde_json::Map::new(); - /// map.insert("serde".to_owned(), json!(12)); - /// - /// match map.entry("serde") { - /// Entry::Occupied(occupied) => { - /// assert_eq!(occupied.key(), &"serde"); - /// } - /// Entry::Vacant(_) => unimplemented!(), - /// } - /// # } - /// ``` - #[inline] - pub fn key(&self) -> &String { - self.occupied.key() - } - - /// Gets a reference to the value in the entry. - /// - /// # Examples - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::map::Entry; - /// - /// let mut map = serde_json::Map::new(); - /// map.insert("serde".to_owned(), json!(12)); - /// - /// match map.entry("serde") { - /// Entry::Occupied(occupied) => { - /// assert_eq!(occupied.get(), 12); - /// } - /// Entry::Vacant(_) => unimplemented!(), - /// } - /// # } - /// ``` - #[inline] - pub fn get(&self) -> &Value { - self.occupied.get() - } - - /// Gets a mutable reference to the value in the entry. - /// - /// # Examples - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::map::Entry; - /// - /// let mut map = serde_json::Map::new(); - /// map.insert("serde".to_owned(), json!([1, 2, 3])); - /// - /// match map.entry("serde") { - /// Entry::Occupied(mut occupied) => { - /// occupied.get_mut().as_array_mut().unwrap().push(json!(4)); - /// } - /// Entry::Vacant(_) => unimplemented!(), - /// } - /// - /// assert_eq!(map["serde"].as_array().unwrap().len(), 4); - /// # } - /// ``` - #[inline] - pub fn get_mut(&mut self) -> &mut Value { - self.occupied.get_mut() - } - - /// Converts the entry into a mutable reference to its value. - /// - /// # Examples - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::map::Entry; - /// - /// let mut map = serde_json::Map::new(); - /// map.insert("serde".to_owned(), json!([1, 2, 3])); - /// - /// match map.entry("serde") { - /// Entry::Occupied(mut occupied) => { - /// occupied.into_mut().as_array_mut().unwrap().push(json!(4)); - /// } - /// Entry::Vacant(_) => unimplemented!(), - /// } - /// - /// assert_eq!(map["serde"].as_array().unwrap().len(), 4); - /// # } - /// ``` - #[inline] - pub fn into_mut(self) -> &'a mut Value { - self.occupied.into_mut() - } - - /// Sets the value of the entry with the `OccupiedEntry`'s key, and returns - /// the entry's old value. - /// - /// # Examples - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::map::Entry; - /// - /// let mut map = serde_json::Map::new(); - /// map.insert("serde".to_owned(), json!(12)); - /// - /// match map.entry("serde") { - /// Entry::Occupied(mut occupied) => { - /// assert_eq!(occupied.insert(json!(13)), 12); - /// assert_eq!(occupied.get(), 13); - /// } - /// Entry::Vacant(_) => unimplemented!(), - /// } - /// # } - /// ``` - #[inline] - pub fn insert(&mut self, value: Value) -> Value { - self.occupied.insert(value) - } - - /// Takes the value of the entry out of the map, and returns it. - /// - /// # Examples - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::map::Entry; - /// - /// let mut map = serde_json::Map::new(); - /// map.insert("serde".to_owned(), json!(12)); - /// - /// match map.entry("serde") { - /// Entry::Occupied(occupied) => { - /// assert_eq!(occupied.remove(), 12); - /// } - /// Entry::Vacant(_) => unimplemented!(), - /// } - /// # } - /// ``` - #[inline] - pub fn remove(self) -> Value { - self.occupied.remove() - } -} - -////////////////////////////////////////////////////////////////////////////// - -impl<'a> IntoIterator for &'a Map<String, Value> { - type Item = (&'a String, &'a Value); - type IntoIter = Iter<'a>; - #[inline] - fn into_iter(self) -> Self::IntoIter { - Iter { iter: self.map.iter() } - } -} - -/// An iterator over a serde_json::Map's entries. -pub struct Iter<'a> { - iter: IterImpl<'a>, -} - -#[cfg(not(feature = "preserve_order"))] -type IterImpl<'a> = btree_map::Iter<'a, String, Value>; -#[cfg(feature = "preserve_order")] -type IterImpl<'a> = linked_hash_map::Iter<'a, String, Value>; - -delegate_iterator!((Iter<'a>) => (&'a String, &'a Value)); - -////////////////////////////////////////////////////////////////////////////// - -impl<'a> IntoIterator for &'a mut Map<String, Value> { - type Item = (&'a String, &'a mut Value); - type IntoIter = IterMut<'a>; - #[inline] - fn into_iter(self) -> Self::IntoIter { - IterMut { iter: self.map.iter_mut() } - } -} - -/// A mutable iterator over a serde_json::Map's entries. -pub struct IterMut<'a> { - iter: IterMutImpl<'a>, -} - -#[cfg(not(feature = "preserve_order"))] -type IterMutImpl<'a> = btree_map::IterMut<'a, String, Value>; -#[cfg(feature = "preserve_order")] -type IterMutImpl<'a> = linked_hash_map::IterMut<'a, String, Value>; - -delegate_iterator!((IterMut<'a>) => (&'a String, &'a mut Value)); - -////////////////////////////////////////////////////////////////////////////// - -impl IntoIterator for Map<String, Value> { - type Item = (String, Value); - type IntoIter = IntoIter; - #[inline] - fn into_iter(self) -> Self::IntoIter { - IntoIter { iter: self.map.into_iter() } - } -} - -/// An owning iterator over a serde_json::Map's entries. -pub struct IntoIter { - iter: IntoIterImpl, -} - -#[cfg(not(feature = "preserve_order"))] -type IntoIterImpl = btree_map::IntoIter<String, Value>; -#[cfg(feature = "preserve_order")] -type IntoIterImpl = linked_hash_map::IntoIter<String, Value>; - -delegate_iterator!((IntoIter) => (String, Value)); - -////////////////////////////////////////////////////////////////////////////// - -/// An iterator over a serde_json::Map's keys. -pub struct Keys<'a> { - iter: KeysImpl<'a>, -} - -#[cfg(not(feature = "preserve_order"))] -type KeysImpl<'a> = btree_map::Keys<'a, String, Value>; -#[cfg(feature = "preserve_order")] -type KeysImpl<'a> = linked_hash_map::Keys<'a, String, Value>; - -delegate_iterator!((Keys<'a>) => &'a String); - -////////////////////////////////////////////////////////////////////////////// - -/// An iterator over a serde_json::Map's values. -pub struct Values<'a> { - iter: ValuesImpl<'a>, -} - -#[cfg(not(feature = "preserve_order"))] -type ValuesImpl<'a> = btree_map::Values<'a, String, Value>; -#[cfg(feature = "preserve_order")] -type ValuesImpl<'a> = linked_hash_map::Values<'a, String, Value>; - -delegate_iterator!((Values<'a>) => &'a Value); diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/number.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/number.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/number.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/number.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,388 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use error::Error; -use num_traits::NumCast; -use serde::de::{self, Visitor, Unexpected}; -use serde::{Serialize, Serializer, Deserialize, Deserializer}; -use std::fmt::{self, Debug, Display}; -use std::i64; - -/// Represents a JSON number, whether integer or floating point. -#[derive(Clone, PartialEq)] -pub struct Number { - n: N, -} - -#[derive(Copy, Clone, PartialEq)] -enum N { - PosInt(u64), - /// Always less than zero. - NegInt(i64), - /// Always finite. - Float(f64), -} - -impl Number { - /// Returns true if the `Number` is an integer between `i64::MIN` and - /// `i64::MAX`. - /// - /// For any Number on which `is_i64` returns true, `as_i64` is guaranteed to - /// return the integer value. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # use std::i64; - /// # - /// # fn main() { - /// let big = i64::MAX as u64 + 10; - /// let v = json!({ "a": 64, "b": big, "c": 256.0 }); - /// - /// assert!(v["a"].is_i64()); - /// - /// // Greater than i64::MAX. - /// assert!(!v["b"].is_i64()); - /// - /// // Numbers with a decimal point are not considered integers. - /// assert!(!v["c"].is_i64()); - /// # } - /// ``` - #[inline] - pub fn is_i64(&self) -> bool { - match self.n { - N::PosInt(v) => v <= i64::MAX as u64, - N::NegInt(_) => true, - N::Float(_) => false, - } - } - - /// Returns true if the `Number` is an integer between zero and `u64::MAX`. - /// - /// For any Number on which `is_u64` returns true, `as_u64` is guaranteed to - /// return the integer value. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": 64, "b": -64, "c": 256.0 }); - /// - /// assert!(v["a"].is_u64()); - /// - /// // Negative integer. - /// assert!(!v["b"].is_u64()); - /// - /// // Numbers with a decimal point are not considered integers. - /// assert!(!v["c"].is_u64()); - /// # } - /// ``` - #[inline] - pub fn is_u64(&self) -> bool { - match self.n { - N::PosInt(_) => true, - N::NegInt(_) | N::Float(_) => false, - } - } - - /// Returns true if the `Number` can be represented by f64. - /// - /// For any Number on which `is_f64` returns true, `as_f64` is guaranteed to - /// return the floating point value. - /// - /// Currently this function returns true if and only if both `is_i64` and - /// `is_u64` return false but this is not a guarantee in the future. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": 256.0, "b": 64, "c": -64 }); - /// - /// assert!(v["a"].is_f64()); - /// - /// // Integers. - /// assert!(!v["b"].is_f64()); - /// assert!(!v["c"].is_f64()); - /// # } - /// ``` - #[inline] - pub fn is_f64(&self) -> bool { - match self.n { - N::Float(_) => true, - N::PosInt(_) | N::NegInt(_) => false, - } - } - - /// If the `Number` is an integer, represent it as i64 if possible. Returns - /// None otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # use std::i64; - /// # - /// # fn main() { - /// let big = i64::MAX as u64 + 10; - /// let v = json!({ "a": 64, "b": big, "c": 256.0 }); - /// - /// assert_eq!(v["a"].as_i64(), Some(64)); - /// assert_eq!(v["b"].as_i64(), None); - /// assert_eq!(v["c"].as_i64(), None); - /// # } - /// ``` - #[inline] - pub fn as_i64(&self) -> Option<i64> { - match self.n { - N::PosInt(n) => NumCast::from(n), - N::NegInt(n) => Some(n), - N::Float(_) => None, - } - } - - /// If the `Number` is an integer, represent it as u64 if possible. Returns - /// None otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": 64, "b": -64, "c": 256.0 }); - /// - /// assert_eq!(v["a"].as_u64(), Some(64)); - /// assert_eq!(v["b"].as_u64(), None); - /// assert_eq!(v["c"].as_u64(), None); - /// # } - /// ``` - #[inline] - pub fn as_u64(&self) -> Option<u64> { - match self.n { - N::PosInt(n) => Some(n), - N::NegInt(n) => NumCast::from(n), - N::Float(_) => None, - } - } - - /// Represents the number as f64 if possible. Returns None otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": 256.0, "b": 64, "c": -64 }); - /// - /// assert_eq!(v["a"].as_f64(), Some(256.0)); - /// assert_eq!(v["b"].as_f64(), Some(64.0)); - /// assert_eq!(v["c"].as_f64(), Some(-64.0)); - /// # } - /// ``` - #[inline] - pub fn as_f64(&self) -> Option<f64> { - match self.n { - N::PosInt(n) => NumCast::from(n), - N::NegInt(n) => NumCast::from(n), - N::Float(n) => Some(n), - } - } - - /// Converts a finite `f64` to a `Number`. Infinite or NaN values are not JSON - /// numbers. - /// - /// ```rust - /// # use std::f64; - /// # - /// # use serde_json::Number; - /// # - /// assert!(Number::from_f64(256.0).is_some()); - /// - /// assert!(Number::from_f64(f64::NAN).is_none()); - /// ``` - #[inline] - pub fn from_f64(f: f64) -> Option<Number> { - if f.is_finite() { - Some(Number { n: N::Float(f) }) - } else { - None - } - } -} - -impl fmt::Display for Number { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match self.n { - N::PosInt(i) => Display::fmt(&i, formatter), - N::NegInt(i) => Display::fmt(&i, formatter), - N::Float(f) => Display::fmt(&f, formatter), - } - } -} - -impl Debug for Number { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - let mut debug = formatter.debug_tuple("Number"); - match self.n { - N::PosInt(i) => { - debug.field(&i); - } - N::NegInt(i) => { - debug.field(&i); - } - N::Float(f) => { - debug.field(&f); - } - } - debug.finish() - } -} - -impl Serialize for Number { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: Serializer, - { - match self.n { - N::PosInt(i) => serializer.serialize_u64(i), - N::NegInt(i) => serializer.serialize_i64(i), - N::Float(f) => serializer.serialize_f64(f), - } - } -} - -impl<'de> Deserialize<'de> for Number { - #[inline] - fn deserialize<D>(deserializer: D) -> Result<Number, D::Error> - where - D: Deserializer<'de>, - { - struct NumberVisitor; - - impl<'de> Visitor<'de> for NumberVisitor { - type Value = Number; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a number") - } - - #[inline] - fn visit_i64<E>(self, value: i64) -> Result<Number, E> { - Ok(value.into()) - } - - #[inline] - fn visit_u64<E>(self, value: u64) -> Result<Number, E> { - Ok(value.into()) - } - - #[inline] - fn visit_f64<E>(self, value: f64) -> Result<Number, E> - where - E: de::Error, - { - Number::from_f64(value).ok_or_else(|| de::Error::custom("not a JSON number")) - } - } - - deserializer.deserialize_any(NumberVisitor) - } -} - -impl<'de> Deserializer<'de> for Number { - type Error = Error; - - #[inline] - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - match self.n { - N::PosInt(i) => visitor.visit_u64(i), - N::NegInt(i) => visitor.visit_i64(i), - N::Float(f) => visitor.visit_f64(f), - } - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any - } -} - -impl<'de, 'a> Deserializer<'de> for &'a Number { - type Error = Error; - - #[inline] - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - match self.n { - N::PosInt(i) => visitor.visit_u64(i), - N::NegInt(i) => visitor.visit_i64(i), - N::Float(f) => visitor.visit_f64(f), - } - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any - } -} - -macro_rules! from_signed { - ($($signed_ty:ident)*) => { - $( - impl From<$signed_ty> for Number { - #[inline] - fn from(i: $signed_ty) -> Self { - if i < 0 { - Number { n: N::NegInt(i as i64) } - } else { - Number { n: N::PosInt(i as u64) } - } - } - } - )* - }; -} - -macro_rules! from_unsigned { - ($($unsigned_ty:ident)*) => { - $( - impl From<$unsigned_ty> for Number { - #[inline] - fn from(u: $unsigned_ty) -> Self { - Number { n: N::PosInt(u as u64) } - } - } - )* - }; -} - -from_signed!(i8 i16 i32 i64 isize); -from_unsigned!(u8 u16 u32 u64 usize); - -impl Number { - // Not public API. Should be pub(crate). - #[doc(hidden)] - pub fn unexpected(&self) -> Unexpected { - match self.n { - N::PosInt(u) => Unexpected::Unsigned(u), - N::NegInt(i) => Unexpected::Signed(i), - N::Float(f) => Unexpected::Float(f), - } - } -} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/read.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/read.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/read.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/read.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,698 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::{char, cmp, io, str}; -use std::ops::Deref; - -use iter::LineColIterator; - -use super::error::{Error, ErrorCode, Result}; - -/// Trait used by the deserializer for iterating over input. This is manually -/// "specialized" for iterating over &[u8]. Once feature(specialization) is -/// stable we can use actual specialization. -/// -/// This trait is sealed and cannot be implemented for types outside of -/// `serde_json`. -pub trait Read<'de>: private::Sealed { - #[doc(hidden)] - fn next(&mut self) -> io::Result<Option<u8>>; - #[doc(hidden)] - fn peek(&mut self) -> io::Result<Option<u8>>; - - /// Only valid after a call to peek(). Discards the peeked byte. - #[doc(hidden)] - fn discard(&mut self); - - /// Position of the most recent call to next(). - /// - /// The most recent call was probably next() and not peek(), but this method - /// should try to return a sensible result if the most recent call was - /// actually peek() because we don't always know. - /// - /// Only called in case of an error, so performance is not important. - #[doc(hidden)] - fn position(&self) -> Position; - - /// Position of the most recent call to peek(). - /// - /// The most recent call was probably peek() and not next(), but this method - /// should try to return a sensible result if the most recent call was - /// actually next() because we don't always know. - /// - /// Only called in case of an error, so performance is not important. - #[doc(hidden)] - fn peek_position(&self) -> Position; - - /// Offset from the beginning of the input to the next byte that would be - /// returned by next() or peek(). - #[doc(hidden)] - fn byte_offset(&self) -> usize; - - /// Assumes the previous byte was a quotation mark. Parses a JSON-escaped - /// string until the next quotation mark using the given scratch space if - /// necessary. The scratch space is initially empty. - #[doc(hidden)] - fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'de, 's, str>>; - - /// Assumes the previous byte was a quotation mark. Parses a JSON-escaped - /// string until the next quotation mark using the given scratch space if - /// necessary. The scratch space is initially empty. - /// - /// This function returns the raw bytes in the string with escape sequences - /// expanded but without performing unicode validation. - #[doc(hidden)] - fn parse_str_raw<'s>( - &'s mut self, - scratch: &'s mut Vec<u8>, - ) -> Result<Reference<'de, 's, [u8]>>; - - /// Assumes the previous byte was a quotation mark. Parses a JSON-escaped - /// string until the next quotation mark but discards the data. - #[doc(hidden)] - fn ignore_str(&mut self) -> Result<()>; -} - -pub struct Position { - pub line: usize, - pub column: usize, -} - -pub enum Reference<'b, 'c, T: ?Sized + 'static> { - Borrowed(&'b T), - Copied(&'c T), -} - -impl<'b, 'c, T: ?Sized + 'static> Deref for Reference<'b, 'c, T> { - type Target = T; - - fn deref(&self) -> &Self::Target { - match *self { - Reference::Borrowed(b) => b, - Reference::Copied(c) => c, - } - } -} - -/// JSON input source that reads from a std::io input stream. -pub struct IoRead<R> -where - R: io::Read, -{ - iter: LineColIterator<io::Bytes<R>>, - /// Temporary storage of peeked byte. - ch: Option<u8>, -} - -/// JSON input source that reads from a slice of bytes. -// -// This is more efficient than other iterators because peek() can be read-only -// and we can compute line/col position only if an error happens. -pub struct SliceRead<'a> { - slice: &'a [u8], - /// Index of the *next* byte that will be returned by next() or peek(). - index: usize, -} - -/// JSON input source that reads from a UTF-8 string. -// -// Able to elide UTF-8 checks by assuming that the input is valid UTF-8. -pub struct StrRead<'a> { - delegate: SliceRead<'a>, -} - -// Prevent users from implementing the Read trait. -mod private { - pub trait Sealed {} -} - -////////////////////////////////////////////////////////////////////////////// - -impl<R> IoRead<R> -where - R: io::Read, -{ - /// Create a JSON input source to read from a std::io input stream. - pub fn new(reader: R) -> Self { - IoRead { - iter: LineColIterator::new(reader.bytes()), - ch: None, - } - } -} - -impl<R> private::Sealed for IoRead<R> -where - R: io::Read, -{ -} - -impl<R> IoRead<R> -where - R: io::Read, -{ - fn parse_str_bytes<'s, T, F>( - &'s mut self, - scratch: &'s mut Vec<u8>, - validate: bool, - result: F, - ) -> Result<T> - where - T: 's, - F: FnOnce(&'s Self, &'s [u8]) -> Result<T>, - { - loop { - let ch = try!(next_or_eof(self)); - if !ESCAPE[ch as usize] { - scratch.push(ch); - continue; - } - match ch { - b'"' => { - return result(self, scratch); - } - b'\\' => { - try!(parse_escape(self, scratch)); - } - _ => { - if validate { - return error(self, ErrorCode::InvalidUnicodeCodePoint); - } - scratch.push(ch); - } - } - } - } -} - -impl<'de, R> Read<'de> for IoRead<R> -where - R: io::Read, -{ - #[inline] - fn next(&mut self) -> io::Result<Option<u8>> { - match self.ch.take() { - Some(ch) => Ok(Some(ch)), - None => { - match self.iter.next() { - Some(Err(err)) => Err(err), - Some(Ok(ch)) => Ok(Some(ch)), - None => Ok(None), - } - } - } - } - - #[inline] - fn peek(&mut self) -> io::Result<Option<u8>> { - match self.ch { - Some(ch) => Ok(Some(ch)), - None => { - match self.iter.next() { - Some(Err(err)) => Err(err), - Some(Ok(ch)) => { - self.ch = Some(ch); - Ok(self.ch) - } - None => Ok(None), - } - } - } - } - - #[inline] - fn discard(&mut self) { - self.ch = None; - } - - fn position(&self) -> Position { - Position { - line: self.iter.line(), - column: self.iter.col(), - } - } - - fn peek_position(&self) -> Position { - // The LineColIterator updates its position during peek() so it has the - // right one here. - self.position() - } - - fn byte_offset(&self) -> usize { - match self.ch { - Some(_) => self.iter.byte_offset() - 1, - None => self.iter.byte_offset(), - } - } - - fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'de, 's, str>> { - self.parse_str_bytes(scratch, true, as_str) - .map(Reference::Copied) - } - - fn parse_str_raw<'s>( - &'s mut self, - scratch: &'s mut Vec<u8>, - ) -> Result<Reference<'de, 's, [u8]>> { - self.parse_str_bytes(scratch, false, |_, bytes| Ok(bytes)) - .map(Reference::Copied) - } - - fn ignore_str(&mut self) -> Result<()> { - loop { - let ch = try!(next_or_eof(self)); - if !ESCAPE[ch as usize] { - continue; - } - match ch { - b'"' => { - return Ok(()); - } - b'\\' => { - try!(ignore_escape(self)); - } - _ => { - return error(self, ErrorCode::InvalidUnicodeCodePoint); - } - } - } - } -} - -////////////////////////////////////////////////////////////////////////////// - -impl<'a> SliceRead<'a> { - /// Create a JSON input source to read from a slice of bytes. - pub fn new(slice: &'a [u8]) -> Self { - SliceRead { - slice: slice, - index: 0, - } - } - - fn position_of_index(&self, i: usize) -> Position { - let mut pos = Position { line: 1, column: 0 }; - for ch in &self.slice[..i] { - match *ch { - b'\n' => { - pos.line += 1; - pos.column = 0; - } - _ => { - pos.column += 1; - } - } - } - pos - } - - /// The big optimization here over IoRead is that if the string contains no - /// backslash escape sequences, the returned &str is a slice of the raw JSON - /// data so we avoid copying into the scratch space. - fn parse_str_bytes<'s, T: ?Sized, F>( - &'s mut self, - scratch: &'s mut Vec<u8>, - validate: bool, - result: F, - ) -> Result<Reference<'a, 's, T>> - where - T: 's, - F: for<'f> FnOnce(&'s Self, &'f [u8]) -> Result<&'f T>, - { - // Index of the first byte not yet copied into the scratch space. - let mut start = self.index; - - loop { - while self.index < self.slice.len() && !ESCAPE[self.slice[self.index] as usize] { - self.index += 1; - } - if self.index == self.slice.len() { - return error(self, ErrorCode::EofWhileParsingString); - } - match self.slice[self.index] { - b'"' => { - if scratch.is_empty() { - // Fast path: return a slice of the raw JSON without any - // copying. - let borrowed = &self.slice[start..self.index]; - self.index += 1; - return result(self, borrowed).map(Reference::Borrowed); - } else { - scratch.extend_from_slice(&self.slice[start..self.index]); - // "as &[u8]" is required for rustc 1.8.0 - let copied = scratch as &[u8]; - self.index += 1; - return result(self, copied).map(Reference::Copied); - } - } - b'\\' => { - scratch.extend_from_slice(&self.slice[start..self.index]); - self.index += 1; - try!(parse_escape(self, scratch)); - start = self.index; - } - _ => { - if validate { - return error(self, ErrorCode::InvalidUnicodeCodePoint); - } - self.index += 1; - } - } - } - } -} - -impl<'a> private::Sealed for SliceRead<'a> {} - -impl<'a> Read<'a> for SliceRead<'a> { - #[inline] - fn next(&mut self) -> io::Result<Option<u8>> { - // `Ok(self.slice.get(self.index).map(|ch| { self.index += 1; *ch }))` - // is about 10% slower. - Ok( - if self.index < self.slice.len() { - let ch = self.slice[self.index]; - self.index += 1; - Some(ch) - } else { - None - }, - ) - } - - #[inline] - fn peek(&mut self) -> io::Result<Option<u8>> { - // `Ok(self.slice.get(self.index).map(|ch| *ch))` is about 10% slower - // for some reason. - Ok( - if self.index < self.slice.len() { - Some(self.slice[self.index]) - } else { - None - }, - ) - } - - #[inline] - fn discard(&mut self) { - self.index += 1; - } - - fn position(&self) -> Position { - self.position_of_index(self.index) - } - - fn peek_position(&self) -> Position { - // Cap it at slice.len() just in case the most recent call was next() - // and it returned the last byte. - self.position_of_index(cmp::min(self.slice.len(), self.index + 1)) - } - - fn byte_offset(&self) -> usize { - self.index - } - - fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'a, 's, str>> { - self.parse_str_bytes(scratch, true, as_str) - } - - fn parse_str_raw<'s>( - &'s mut self, - scratch: &'s mut Vec<u8>, - ) -> Result<Reference<'a, 's, [u8]>> { - self.parse_str_bytes(scratch, false, |_, bytes| Ok(bytes)) - } - - fn ignore_str(&mut self) -> Result<()> { - loop { - while self.index < self.slice.len() && !ESCAPE[self.slice[self.index] as usize] { - self.index += 1; - } - if self.index == self.slice.len() { - return error(self, ErrorCode::EofWhileParsingString); - } - match self.slice[self.index] { - b'"' => { - self.index += 1; - return Ok(()); - } - b'\\' => { - self.index += 1; - try!(ignore_escape(self)); - } - _ => { - return error(self, ErrorCode::InvalidUnicodeCodePoint); - } - } - } - } -} - -////////////////////////////////////////////////////////////////////////////// - -impl<'a> StrRead<'a> { - /// Create a JSON input source to read from a UTF-8 string. - pub fn new(s: &'a str) -> Self { - StrRead { delegate: SliceRead::new(s.as_bytes()) } - } -} - -impl<'a> private::Sealed for StrRead<'a> {} - -impl<'a> Read<'a> for StrRead<'a> { - #[inline] - fn next(&mut self) -> io::Result<Option<u8>> { - self.delegate.next() - } - - #[inline] - fn peek(&mut self) -> io::Result<Option<u8>> { - self.delegate.peek() - } - - #[inline] - fn discard(&mut self) { - self.delegate.discard(); - } - - fn position(&self) -> Position { - self.delegate.position() - } - - fn peek_position(&self) -> Position { - self.delegate.peek_position() - } - - fn byte_offset(&self) -> usize { - self.delegate.byte_offset() - } - - fn parse_str<'s>(&'s mut self, scratch: &'s mut Vec<u8>) -> Result<Reference<'a, 's, str>> { - self.delegate - .parse_str_bytes( - scratch, true, |_, bytes| { - // The input is assumed to be valid UTF-8 and the \u-escapes are - // checked along the way, so don't need to check here. - Ok(unsafe { str::from_utf8_unchecked(bytes) }) - } - ) - } - - fn parse_str_raw<'s>( - &'s mut self, - scratch: &'s mut Vec<u8>, - ) -> Result<Reference<'a, 's, [u8]>> { - self.delegate.parse_str_raw(scratch) - } - - fn ignore_str(&mut self) -> Result<()> { - self.delegate.ignore_str() - } -} - -////////////////////////////////////////////////////////////////////////////// - -const CT: bool = true; // control character \x00...\x1F -const QU: bool = true; // quote \x22 -const BS: bool = true; // backslash \x5C -const O: bool = false; // allow unescaped - -// Lookup table of bytes that must be escaped. A value of true at index i means -// that byte i requires an escape sequence in the input. -#[cfg_attr(rustfmt, rustfmt_skip)] -static ESCAPE: [bool; 256] = [ - // 1 2 3 4 5 6 7 8 9 A B C D E F - CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, // 0 - CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, CT, // 1 - O, O, QU, O, O, O, O, O, O, O, O, O, O, O, O, O, // 2 - O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 3 - O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 4 - O, O, O, O, O, O, O, O, O, O, O, O, BS, O, O, O, // 5 - O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 6 - O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 7 - O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 8 - O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // 9 - O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // A - O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // B - O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // C - O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // D - O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // E - O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, // F -]; - -fn next_or_eof<'de, R: ?Sized + Read<'de>>(read: &mut R) -> Result<u8> { - match try!(read.next().map_err(Error::io)) { - Some(b) => Ok(b), - None => error(read, ErrorCode::EofWhileParsingString), - } -} - -fn error<'de, R: ?Sized + Read<'de>, T>(read: &R, reason: ErrorCode) -> Result<T> { - let pos = read.position(); - Err(Error::syntax(reason, pos.line, pos.column)) -} - -fn as_str<'de, 's, R: Read<'de>>(read: &R, slice: &'s [u8]) -> Result<&'s str> { - str::from_utf8(slice).or_else(|_| error(read, ErrorCode::InvalidUnicodeCodePoint)) -} - -/// Parses a JSON escape sequence and appends it into the scratch space. Assumes -/// the previous byte read was a backslash. -fn parse_escape<'de, R: Read<'de>>(read: &mut R, scratch: &mut Vec<u8>) -> Result<()> { - let ch = try!(next_or_eof(read)); - - match ch { - b'"' => scratch.push(b'"'), - b'\\' => scratch.push(b'\\'), - b'/' => scratch.push(b'/'), - b'b' => scratch.push(b'\x08'), - b'f' => scratch.push(b'\x0c'), - b'n' => scratch.push(b'\n'), - b'r' => scratch.push(b'\r'), - b't' => scratch.push(b'\t'), - b'u' => { - let c = match try!(decode_hex_escape(read)) { - 0xDC00...0xDFFF => { - return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape); - } - - // Non-BMP characters are encoded as a sequence of - // two hex escapes, representing UTF-16 surrogates. - n1 @ 0xD800...0xDBFF => { - if try!(next_or_eof(read)) != b'\\' { - return error(read, ErrorCode::UnexpectedEndOfHexEscape); - } - if try!(next_or_eof(read)) != b'u' { - return error(read, ErrorCode::UnexpectedEndOfHexEscape); - } - - let n2 = try!(decode_hex_escape(read)); - - if n2 < 0xDC00 || n2 > 0xDFFF { - return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape); - } - - let n = (((n1 - 0xD800) as u32) << 10 | (n2 - 0xDC00) as u32) + 0x1_0000; - - match char::from_u32(n) { - Some(c) => c, - None => { - return error(read, ErrorCode::InvalidUnicodeCodePoint); - } - } - } - - n => { - match char::from_u32(n as u32) { - Some(c) => c, - None => { - return error(read, ErrorCode::InvalidUnicodeCodePoint); - } - } - } - }; - - // FIXME: this allocation is required in order to be compatible with stable - // rust, which doesn't support encoding a `char` into a stack buffer. - let mut buf = String::new(); - buf.push(c); - scratch.extend(buf.bytes()); - } - _ => { - return error(read, ErrorCode::InvalidEscape); - } - } - - Ok(()) -} - -/// Parses a JSON escape sequence and discards the value. Assumes the previous -/// byte read was a backslash. -fn ignore_escape<'de, R: ?Sized + Read<'de>>(read: &mut R) -> Result<()> { - let ch = try!(next_or_eof(read)); - - match ch { - b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't' => {} - b'u' => { - let n = match try!(decode_hex_escape(read)) { - 0xDC00...0xDFFF => { - return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape); - } - - // Non-BMP characters are encoded as a sequence of - // two hex escapes, representing UTF-16 surrogates. - n1 @ 0xD800...0xDBFF => { - if try!(next_or_eof(read)) != b'\\' { - return error(read, ErrorCode::UnexpectedEndOfHexEscape); - } - if try!(next_or_eof(read)) != b'u' { - return error(read, ErrorCode::UnexpectedEndOfHexEscape); - } - - let n2 = try!(decode_hex_escape(read)); - - if n2 < 0xDC00 || n2 > 0xDFFF { - return error(read, ErrorCode::LoneLeadingSurrogateInHexEscape); - } - - (((n1 - 0xD800) as u32) << 10 | (n2 - 0xDC00) as u32) + 0x1_0000 - } - - n => n as u32, - }; - - if char::from_u32(n).is_none() { - return error(read, ErrorCode::InvalidUnicodeCodePoint); - } - } - _ => { - return error(read, ErrorCode::InvalidEscape); - } - } - - Ok(()) -} - -fn decode_hex_escape<'de, R: ?Sized + Read<'de>>(read: &mut R) -> Result<u16> { - let mut n = 0; - for _ in 0..4 { - n = match try!(next_or_eof(read)) { - c @ b'0'...b'9' => n * 16_u16 + ((c as u16) - (b'0' as u16)), - b'a' | b'A' => n * 16_u16 + 10_u16, - b'b' | b'B' => n * 16_u16 + 11_u16, - b'c' | b'C' => n * 16_u16 + 12_u16, - b'd' | b'D' => n * 16_u16 + 13_u16, - b'e' | b'E' => n * 16_u16 + 14_u16, - b'f' | b'F' => n * 16_u16 + 15_u16, - _ => { - return error(read, ErrorCode::InvalidEscape); - } - }; - } - Ok(n) -} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/ser.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/ser.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/ser.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/ser.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1821 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Serialize a Rust data structure into JSON data. - -use std::fmt; -use std::io; -use std::num::FpCategory; -use std::str; - -use serde::ser::{self, Impossible}; -use super::error::{Error, ErrorCode, Result}; - -use itoa; -use dtoa; - -/// A structure for serializing Rust values into JSON. -pub struct Serializer<W, F = CompactFormatter> { - writer: W, - formatter: F, -} - -impl<W> Serializer<W> -where - W: io::Write, -{ - /// Creates a new JSON serializer. - #[inline] - pub fn new(writer: W) -> Self { - Serializer::with_formatter(writer, CompactFormatter) - } -} - -impl<'a, W> Serializer<W, PrettyFormatter<'a>> -where - W: io::Write, -{ - /// Creates a new JSON pretty print serializer. - #[inline] - pub fn pretty(writer: W) -> Self { - Serializer::with_formatter(writer, PrettyFormatter::new()) - } -} - -impl<W, F> Serializer<W, F> -where - W: io::Write, - F: Formatter, -{ - /// Creates a new JSON visitor whose output will be written to the writer - /// specified. - #[inline] - pub fn with_formatter(writer: W, formatter: F) -> Self { - Serializer { - writer: writer, - formatter: formatter, - } - } - - /// Unwrap the `Writer` from the `Serializer`. - #[inline] - pub fn into_inner(self) -> W { - self.writer - } -} - -impl<'a, W, F> ser::Serializer for &'a mut Serializer<W, F> -where - W: io::Write, - F: Formatter, -{ - type Ok = (); - type Error = Error; - - type SerializeSeq = Compound<'a, W, F>; - type SerializeTuple = Compound<'a, W, F>; - type SerializeTupleStruct = Compound<'a, W, F>; - type SerializeTupleVariant = Compound<'a, W, F>; - type SerializeMap = Compound<'a, W, F>; - type SerializeStruct = Compound<'a, W, F>; - type SerializeStructVariant = Compound<'a, W, F>; - - #[inline] - fn serialize_bool(self, value: bool) -> Result<()> { - try!( - self.formatter - .write_bool(&mut self.writer, value) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn serialize_i8(self, value: i8) -> Result<()> { - try!( - self.formatter - .write_i8(&mut self.writer, value) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn serialize_i16(self, value: i16) -> Result<()> { - try!( - self.formatter - .write_i16(&mut self.writer, value) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn serialize_i32(self, value: i32) -> Result<()> { - try!( - self.formatter - .write_i32(&mut self.writer, value) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn serialize_i64(self, value: i64) -> Result<()> { - try!( - self.formatter - .write_i64(&mut self.writer, value) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn serialize_u8(self, value: u8) -> Result<()> { - try!( - self.formatter - .write_u8(&mut self.writer, value) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn serialize_u16(self, value: u16) -> Result<()> { - try!( - self.formatter - .write_u16(&mut self.writer, value) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn serialize_u32(self, value: u32) -> Result<()> { - try!( - self.formatter - .write_u32(&mut self.writer, value) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn serialize_u64(self, value: u64) -> Result<()> { - try!( - self.formatter - .write_u64(&mut self.writer, value) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn serialize_f32(self, value: f32) -> Result<()> { - match value.classify() { - FpCategory::Nan | FpCategory::Infinite => { - try!( - self.formatter - .write_null(&mut self.writer) - .map_err(Error::io) - ); - } - _ => { - try!( - self.formatter - .write_f32(&mut self.writer, value) - .map_err(Error::io) - ); - } - } - Ok(()) - } - - #[inline] - fn serialize_f64(self, value: f64) -> Result<()> { - match value.classify() { - FpCategory::Nan | FpCategory::Infinite => { - try!( - self.formatter - .write_null(&mut self.writer) - .map_err(Error::io) - ); - } - _ => { - try!( - self.formatter - .write_f64(&mut self.writer, value) - .map_err(Error::io) - ); - } - } - Ok(()) - } - - #[inline] - fn serialize_char(self, value: char) -> Result<()> { - // A char encoded as UTF-8 takes 4 bytes at most. - let mut buf = [0; 4]; - self.serialize_str(value.encode_utf8(&mut buf)) - } - - #[inline] - fn serialize_str(self, value: &str) -> Result<()> { - try!(format_escaped_str(&mut self.writer, &mut self.formatter, value).map_err(Error::io)); - Ok(()) - } - - #[inline] - fn serialize_bytes(self, value: &[u8]) -> Result<()> { - use serde::ser::SerializeSeq; - let mut seq = try!(self.serialize_seq(Some(value.len()))); - for byte in value { - try!(seq.serialize_element(byte)); - } - seq.end() - } - - #[inline] - fn serialize_unit(self) -> Result<()> { - try!( - self.formatter - .write_null(&mut self.writer) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { - self.serialize_unit() - } - - #[inline] - fn serialize_unit_variant( - self, - _name: &'static str, - _variant_index: u32, - variant: &'static str, - ) -> Result<()> { - self.serialize_str(variant) - } - - /// Serialize newtypes without an object wrapper. - #[inline] - fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<()> - where - T: ser::Serialize, - { - value.serialize(self) - } - - #[inline] - fn serialize_newtype_variant<T: ?Sized>( - self, - _name: &'static str, - _variant_index: u32, - variant: &'static str, - value: &T, - ) -> Result<()> - where - T: ser::Serialize, - { - try!( - self.formatter - .begin_object(&mut self.writer) - .map_err(Error::io) - ); - try!( - self.formatter - .begin_object_key(&mut self.writer, true) - .map_err(Error::io) - ); - try!(self.serialize_str(variant)); - try!( - self.formatter - .end_object_key(&mut self.writer) - .map_err(Error::io) - ); - try!( - self.formatter - .begin_object_value(&mut self.writer) - .map_err(Error::io) - ); - try!(value.serialize(&mut *self)); - try!( - self.formatter - .end_object_value(&mut self.writer) - .map_err(Error::io) - ); - try!( - self.formatter - .end_object(&mut self.writer) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn serialize_none(self) -> Result<()> { - self.serialize_unit() - } - - #[inline] - fn serialize_some<T: ?Sized>(self, value: &T) -> Result<()> - where - T: ser::Serialize, - { - value.serialize(self) - } - - #[inline] - fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> { - if len == Some(0) { - try!( - self.formatter - .begin_array(&mut self.writer) - .map_err(Error::io) - ); - try!( - self.formatter - .end_array(&mut self.writer) - .map_err(Error::io) - ); - Ok( - Compound { - ser: self, - state: State::Empty, - }, - ) - } else { - try!( - self.formatter - .begin_array(&mut self.writer) - .map_err(Error::io) - ); - Ok( - Compound { - ser: self, - state: State::First, - }, - ) - } - } - - #[inline] - fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple> { - self.serialize_seq(Some(len)) - } - - #[inline] - fn serialize_tuple_struct( - self, - _name: &'static str, - len: usize, - ) -> Result<Self::SerializeTupleStruct> { - self.serialize_seq(Some(len)) - } - - #[inline] - fn serialize_tuple_variant( - self, - _name: &'static str, - _variant_index: u32, - variant: &'static str, - len: usize, - ) -> Result<Self::SerializeTupleVariant> { - try!( - self.formatter - .begin_object(&mut self.writer) - .map_err(Error::io) - ); - try!( - self.formatter - .begin_object_key(&mut self.writer, true) - .map_err(Error::io) - ); - try!(self.serialize_str(variant)); - try!( - self.formatter - .end_object_key(&mut self.writer) - .map_err(Error::io) - ); - try!( - self.formatter - .begin_object_value(&mut self.writer) - .map_err(Error::io) - ); - self.serialize_seq(Some(len)) - } - - #[inline] - fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> { - if len == Some(0) { - try!( - self.formatter - .begin_object(&mut self.writer) - .map_err(Error::io) - ); - try!( - self.formatter - .end_object(&mut self.writer) - .map_err(Error::io) - ); - Ok( - Compound { - ser: self, - state: State::Empty, - }, - ) - } else { - try!( - self.formatter - .begin_object(&mut self.writer) - .map_err(Error::io) - ); - Ok( - Compound { - ser: self, - state: State::First, - }, - ) - } - } - - #[inline] - fn serialize_struct(self, _name: &'static str, len: usize) -> Result<Self::SerializeStruct> { - self.serialize_map(Some(len)) - } - - #[inline] - fn serialize_struct_variant( - self, - _name: &'static str, - _variant_index: u32, - variant: &'static str, - len: usize, - ) -> Result<Self::SerializeStructVariant> { - try!( - self.formatter - .begin_object(&mut self.writer) - .map_err(Error::io) - ); - try!( - self.formatter - .begin_object_key(&mut self.writer, true) - .map_err(Error::io) - ); - try!(self.serialize_str(variant)); - try!( - self.formatter - .end_object_key(&mut self.writer) - .map_err(Error::io) - ); - try!( - self.formatter - .begin_object_value(&mut self.writer) - .map_err(Error::io) - ); - self.serialize_map(Some(len)) - } - - fn collect_str<T: ?Sized>(self, value: &T) -> Result<Self::Ok> - where - T: fmt::Display, - { - use std::fmt::Write; - - struct Adapter<'ser, W: 'ser, F: 'ser> { - writer: &'ser mut W, - formatter: &'ser mut F, - error: Option<io::Error>, - } - - impl<'ser, W, F> Write for Adapter<'ser, W, F> - where - W: io::Write, - F: Formatter, - { - fn write_str(&mut self, s: &str) -> fmt::Result { - assert!(self.error.is_none()); - match format_escaped_str_contents(self.writer, self.formatter, s) { - Ok(()) => Ok(()), - Err(err) => { - self.error = Some(err); - Err(fmt::Error) - } - } - } - } - - try!( - self.formatter - .begin_string(&mut self.writer) - .map_err(Error::io) - ); - { - let mut adapter = Adapter { - writer: &mut self.writer, - formatter: &mut self.formatter, - error: None, - }; - match write!(adapter, "{}", value) { - Ok(()) => assert!(adapter.error.is_none()), - Err(fmt::Error) => { - return Err(Error::io(adapter.error.expect("there should be an error"))); - } - } - } - try!( - self.formatter - .end_string(&mut self.writer) - .map_err(Error::io) - ); - Ok(()) - } -} - -#[doc(hidden)] -#[derive(Eq, PartialEq)] -pub enum State { - Empty, - First, - Rest, -} - -#[doc(hidden)] -pub struct Compound<'a, W: 'a, F: 'a> { - ser: &'a mut Serializer<W, F>, - state: State, -} - -impl<'a, W, F> ser::SerializeSeq for Compound<'a, W, F> -where - W: io::Write, - F: Formatter, -{ - type Ok = (); - type Error = Error; - - #[inline] - fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()> - where - T: ser::Serialize, - { - try!( - self.ser - .formatter - .begin_array_value(&mut self.ser.writer, self.state == State::First) - .map_err(Error::io) - ); - self.state = State::Rest; - try!(value.serialize(&mut *self.ser)); - try!( - self.ser - .formatter - .end_array_value(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn end(self) -> Result<()> { - match self.state { - State::Empty => {} - _ => { - try!( - self.ser - .formatter - .end_array(&mut self.ser.writer) - .map_err(Error::io) - ) - } - } - Ok(()) - } -} - -impl<'a, W, F> ser::SerializeTuple for Compound<'a, W, F> -where - W: io::Write, - F: Formatter, -{ - type Ok = (); - type Error = Error; - - #[inline] - fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<()> - where - T: ser::Serialize, - { - ser::SerializeSeq::serialize_element(self, value) - } - - #[inline] - fn end(self) -> Result<()> { - ser::SerializeSeq::end(self) - } -} - -impl<'a, W, F> ser::SerializeTupleStruct for Compound<'a, W, F> -where - W: io::Write, - F: Formatter, -{ - type Ok = (); - type Error = Error; - - #[inline] - fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()> - where - T: ser::Serialize, - { - ser::SerializeSeq::serialize_element(self, value) - } - - #[inline] - fn end(self) -> Result<()> { - ser::SerializeSeq::end(self) - } -} - -impl<'a, W, F> ser::SerializeTupleVariant for Compound<'a, W, F> -where - W: io::Write, - F: Formatter, -{ - type Ok = (); - type Error = Error; - - #[inline] - fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<()> - where - T: ser::Serialize, - { - ser::SerializeSeq::serialize_element(self, value) - } - - #[inline] - fn end(self) -> Result<()> { - match self.state { - State::Empty => {} - _ => { - try!( - self.ser - .formatter - .end_array(&mut self.ser.writer) - .map_err(Error::io) - ) - } - } - try!( - self.ser - .formatter - .end_object_value(&mut self.ser.writer) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .end_object(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } -} - -impl<'a, W, F> ser::SerializeMap for Compound<'a, W, F> -where - W: io::Write, - F: Formatter, -{ - type Ok = (); - type Error = Error; - - #[inline] - fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<()> - where - T: ser::Serialize, - { - try!( - self.ser - .formatter - .begin_object_key(&mut self.ser.writer, self.state == State::First) - .map_err(Error::io) - ); - self.state = State::Rest; - - try!(key.serialize(MapKeySerializer { ser: self.ser })); - - try!( - self.ser - .formatter - .end_object_key(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<()> - where - T: ser::Serialize, - { - try!( - self.ser - .formatter - .begin_object_value(&mut self.ser.writer) - .map_err(Error::io) - ); - try!(value.serialize(&mut *self.ser)); - try!( - self.ser - .formatter - .end_object_value(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } - - #[inline] - fn end(self) -> Result<()> { - match self.state { - State::Empty => {} - _ => { - try!( - self.ser - .formatter - .end_object(&mut self.ser.writer) - .map_err(Error::io) - ) - } - } - Ok(()) - } -} - -impl<'a, W, F> ser::SerializeStruct for Compound<'a, W, F> -where - W: io::Write, - F: Formatter, -{ - type Ok = (); - type Error = Error; - - #[inline] - fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()> - where - T: ser::Serialize, - { - try!(ser::SerializeMap::serialize_key(self, key)); - ser::SerializeMap::serialize_value(self, value) - } - - #[inline] - fn end(self) -> Result<()> { - ser::SerializeMap::end(self) - } -} - -impl<'a, W, F> ser::SerializeStructVariant for Compound<'a, W, F> -where - W: io::Write, - F: Formatter, -{ - type Ok = (); - type Error = Error; - - #[inline] - fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<()> - where - T: ser::Serialize, - { - ser::SerializeStruct::serialize_field(self, key, value) - } - - #[inline] - fn end(self) -> Result<()> { - match self.state { - State::Empty => {} - _ => { - try!( - self.ser - .formatter - .end_object(&mut self.ser.writer) - .map_err(Error::io) - ) - } - } - try!( - self.ser - .formatter - .end_object_value(&mut self.ser.writer) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .end_object(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } -} - -struct MapKeySerializer<'a, W: 'a, F: 'a> { - ser: &'a mut Serializer<W, F>, -} - -fn key_must_be_a_string() -> Error { - Error::syntax(ErrorCode::KeyMustBeAString, 0, 0) -} - -impl<'a, W, F> ser::Serializer for MapKeySerializer<'a, W, F> -where - W: io::Write, - F: Formatter, -{ - type Ok = (); - type Error = Error; - - #[inline] - fn serialize_str(self, value: &str) -> Result<()> { - self.ser.serialize_str(value) - } - - #[inline] - fn serialize_unit_variant( - self, - _name: &'static str, - _variant_index: u32, - variant: &'static str, - ) -> Result<()> { - self.ser.serialize_str(variant) - } - - #[inline] - fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) -> Result<()> - where - T: ser::Serialize, - { - value.serialize(self) - } - - type SerializeSeq = Impossible<(), Error>; - type SerializeTuple = Impossible<(), Error>; - type SerializeTupleStruct = Impossible<(), Error>; - type SerializeTupleVariant = Impossible<(), Error>; - type SerializeMap = Impossible<(), Error>; - type SerializeStruct = Impossible<(), Error>; - type SerializeStructVariant = Impossible<(), Error>; - - fn serialize_bool(self, _value: bool) -> Result<()> { - Err(key_must_be_a_string()) - } - - fn serialize_i8(self, value: i8) -> Result<()> { - try!( - self.ser - .formatter - .begin_string(&mut self.ser.writer) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .write_i8(&mut self.ser.writer, value) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .end_string(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } - - fn serialize_i16(self, value: i16) -> Result<()> { - try!( - self.ser - .formatter - .begin_string(&mut self.ser.writer) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .write_i16(&mut self.ser.writer, value) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .end_string(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } - - fn serialize_i32(self, value: i32) -> Result<()> { - try!( - self.ser - .formatter - .begin_string(&mut self.ser.writer) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .write_i32(&mut self.ser.writer, value) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .end_string(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } - - fn serialize_i64(self, value: i64) -> Result<()> { - try!( - self.ser - .formatter - .begin_string(&mut self.ser.writer) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .write_i64(&mut self.ser.writer, value) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .end_string(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } - - fn serialize_u8(self, value: u8) -> Result<()> { - try!( - self.ser - .formatter - .begin_string(&mut self.ser.writer) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .write_u8(&mut self.ser.writer, value) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .end_string(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } - - fn serialize_u16(self, value: u16) -> Result<()> { - try!( - self.ser - .formatter - .begin_string(&mut self.ser.writer) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .write_u16(&mut self.ser.writer, value) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .end_string(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } - - fn serialize_u32(self, value: u32) -> Result<()> { - try!( - self.ser - .formatter - .begin_string(&mut self.ser.writer) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .write_u32(&mut self.ser.writer, value) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .end_string(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } - - fn serialize_u64(self, value: u64) -> Result<()> { - try!( - self.ser - .formatter - .begin_string(&mut self.ser.writer) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .write_u64(&mut self.ser.writer, value) - .map_err(Error::io) - ); - try!( - self.ser - .formatter - .end_string(&mut self.ser.writer) - .map_err(Error::io) - ); - Ok(()) - } - - fn serialize_f32(self, _value: f32) -> Result<()> { - Err(key_must_be_a_string()) - } - - fn serialize_f64(self, _value: f64) -> Result<()> { - Err(key_must_be_a_string()) - } - - fn serialize_char(self, _value: char) -> Result<()> { - Err(key_must_be_a_string()) - } - - fn serialize_bytes(self, _value: &[u8]) -> Result<()> { - Err(key_must_be_a_string()) - } - - fn serialize_unit(self) -> Result<()> { - Err(key_must_be_a_string()) - } - - fn serialize_unit_struct(self, _name: &'static str) -> Result<()> { - Err(key_must_be_a_string()) - } - - fn serialize_newtype_variant<T: ?Sized>( - self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _value: &T, - ) -> Result<()> - where - T: ser::Serialize, - { - Err(key_must_be_a_string()) - } - - fn serialize_none(self) -> Result<()> { - Err(key_must_be_a_string()) - } - - fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<()> - where - T: ser::Serialize, - { - Err(key_must_be_a_string()) - } - - fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> { - Err(key_must_be_a_string()) - } - - fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { - Err(key_must_be_a_string()) - } - - fn serialize_tuple_struct( - self, - _name: &'static str, - _len: usize, - ) -> Result<Self::SerializeTupleStruct> { - Err(key_must_be_a_string()) - } - - fn serialize_tuple_variant( - self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize, - ) -> Result<Self::SerializeTupleVariant> { - Err(key_must_be_a_string()) - } - - fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> { - Err(key_must_be_a_string()) - } - - fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> { - Err(key_must_be_a_string()) - } - - fn serialize_struct_variant( - self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize, - ) -> Result<Self::SerializeStructVariant> { - Err(key_must_be_a_string()) - } -} - -/// Represents a character escape code in a type-safe manner. -pub enum CharEscape { - /// An escaped quote `"` - Quote, - /// An escaped reverse solidus `\` - ReverseSolidus, - /// An escaped solidus `/` - Solidus, - /// An escaped backspace character (usually escaped as `\b`) - Backspace, - /// An escaped form feed character (usually escaped as `\f`) - FormFeed, - /// An escaped line feed character (usually escaped as `\n`) - LineFeed, - /// An escaped carriage return character (usually escaped as `\r`) - CarriageReturn, - /// An escaped tab character (usually escaped as `\t`) - Tab, - /// An escaped ASCII plane control character (usually escaped as - /// `\u00XX` where `XX` are two hex characters) - AsciiControl(u8), -} - -impl CharEscape { - #[inline] - fn from_escape_table(escape: u8, byte: u8) -> CharEscape { - match escape { - self::BB => CharEscape::Backspace, - self::TT => CharEscape::Tab, - self::NN => CharEscape::LineFeed, - self::FF => CharEscape::FormFeed, - self::RR => CharEscape::CarriageReturn, - self::QU => CharEscape::Quote, - self::BS => CharEscape::ReverseSolidus, - self::U => CharEscape::AsciiControl(byte), - _ => unreachable!(), - } - } -} - -/// This trait abstracts away serializing the JSON control characters, which allows the user to -/// optionally pretty print the JSON output. -pub trait Formatter { - /// Writes a `null` value to the specified writer. - #[inline] - fn write_null<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - writer.write_all(b"null") - } - - /// Writes a `true` or `false` value to the specified writer. - #[inline] - fn write_bool<W: ?Sized>(&mut self, writer: &mut W, value: bool) -> io::Result<()> - where - W: io::Write, - { - let s = if value { - b"true" as &[u8] - } else { - b"false" as &[u8] - }; - writer.write_all(s) - } - - /// Writes an integer value like `-123` to the specified writer. - #[inline] - fn write_i8<W: ?Sized>(&mut self, writer: &mut W, value: i8) -> io::Result<()> - where - W: io::Write, - { - itoa::write(writer, value).map(|_| ()) - } - - /// Writes an integer value like `-123` to the specified writer. - #[inline] - fn write_i16<W: ?Sized>(&mut self, writer: &mut W, value: i16) -> io::Result<()> - where - W: io::Write, - { - itoa::write(writer, value).map(|_| ()) - } - - /// Writes an integer value like `-123` to the specified writer. - #[inline] - fn write_i32<W: ?Sized>(&mut self, writer: &mut W, value: i32) -> io::Result<()> - where - W: io::Write, - { - itoa::write(writer, value).map(|_| ()) - } - - /// Writes an integer value like `-123` to the specified writer. - #[inline] - fn write_i64<W: ?Sized>(&mut self, writer: &mut W, value: i64) -> io::Result<()> - where - W: io::Write, - { - itoa::write(writer, value).map(|_| ()) - } - - /// Writes an integer value like `123` to the specified writer. - #[inline] - fn write_u8<W: ?Sized>(&mut self, writer: &mut W, value: u8) -> io::Result<()> - where - W: io::Write, - { - itoa::write(writer, value).map(|_| ()) - } - - /// Writes an integer value like `123` to the specified writer. - #[inline] - fn write_u16<W: ?Sized>(&mut self, writer: &mut W, value: u16) -> io::Result<()> - where - W: io::Write, - { - itoa::write(writer, value).map(|_| ()) - } - - /// Writes an integer value like `123` to the specified writer. - #[inline] - fn write_u32<W: ?Sized>(&mut self, writer: &mut W, value: u32) -> io::Result<()> - where - W: io::Write, - { - itoa::write(writer, value).map(|_| ()) - } - - /// Writes an integer value like `123` to the specified writer. - #[inline] - fn write_u64<W: ?Sized>(&mut self, writer: &mut W, value: u64) -> io::Result<()> - where - W: io::Write, - { - itoa::write(writer, value).map(|_| ()) - } - - /// Writes a floating point value like `-31.26e+12` to the specified writer. - #[inline] - fn write_f32<W: ?Sized>(&mut self, writer: &mut W, value: f32) -> io::Result<()> - where - W: io::Write, - { - dtoa::write(writer, value).map(|_| ()) - } - - /// Writes a floating point value like `-31.26e+12` to the specified writer. - #[inline] - fn write_f64<W: ?Sized>(&mut self, writer: &mut W, value: f64) -> io::Result<()> - where - W: io::Write, - { - dtoa::write(writer, value).map(|_| ()) - } - - /// Called before each series of `write_string_fragment` and - /// `write_char_escape`. Writes a `"` to the specified writer. - #[inline] - fn begin_string<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - writer.write_all(b"\"") - } - - /// Called after each series of `write_string_fragment` and - /// `write_char_escape`. Writes a `"` to the specified writer. - #[inline] - fn end_string<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - writer.write_all(b"\"") - } - - /// Writes a string fragment that doesn't need any escaping to the - /// specified writer. - #[inline] - fn write_string_fragment<W: ?Sized>(&mut self, writer: &mut W, fragment: &str) -> io::Result<()> - where - W: io::Write, - { - writer.write_all(fragment.as_bytes()) - } - - /// Writes a character escape code to the specified writer. - #[inline] - fn write_char_escape<W: ?Sized>( - &mut self, - writer: &mut W, - char_escape: CharEscape, - ) -> io::Result<()> - where - W: io::Write, - { - use self::CharEscape::*; - - let s = match char_escape { - Quote => b"\\\"", - ReverseSolidus => b"\\\\", - Solidus => b"\\/", - Backspace => b"\\b", - FormFeed => b"\\f", - LineFeed => b"\\n", - CarriageReturn => b"\\r", - Tab => b"\\t", - AsciiControl(byte) => { - static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef"; - let bytes = &[ - b'\\', - b'u', - b'0', - b'0', - HEX_DIGITS[(byte >> 4) as usize], - HEX_DIGITS[(byte & 0xF) as usize], - ]; - return writer.write_all(bytes); - } - }; - - writer.write_all(s) - } - - /// Called before every array. Writes a `[` to the specified - /// writer. - #[inline] - fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - writer.write_all(b"[") - } - - /// Called after every array. Writes a `]` to the specified - /// writer. - #[inline] - fn end_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - writer.write_all(b"]") - } - - /// Called before every array value. Writes a `,` if needed to - /// the specified writer. - #[inline] - fn begin_array_value<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> - where - W: io::Write, - { - if first { - Ok(()) - } else { - writer.write_all(b",") - } - } - - /// Called after every array value. - #[inline] - fn end_array_value<W: ?Sized>(&mut self, _writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - Ok(()) - } - - /// Called before every object. Writes a `{` to the specified - /// writer. - #[inline] - fn begin_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - writer.write_all(b"{") - } - - /// Called after every object. Writes a `}` to the specified - /// writer. - #[inline] - fn end_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - writer.write_all(b"}") - } - - /// Called before every object key. - #[inline] - fn begin_object_key<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> - where - W: io::Write, - { - if first { - Ok(()) - } else { - writer.write_all(b",") - } - } - - /// Called after every object key. A `:` should be written to the - /// specified writer by either this method or - /// `begin_object_value`. - #[inline] - fn end_object_key<W: ?Sized>(&mut self, _writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - Ok(()) - } - - /// Called before every object value. A `:` should be written to - /// the specified writer by either this method or - /// `end_object_key`. - #[inline] - fn begin_object_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - writer.write_all(b":") - } - - /// Called after every object value. - #[inline] - fn end_object_value<W: ?Sized>(&mut self, _writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - Ok(()) - } -} - -/// This structure compacts a JSON value with no extra whitespace. -#[derive(Clone, Debug)] -pub struct CompactFormatter; - -impl Formatter for CompactFormatter {} - -/// This structure pretty prints a JSON value to make it human readable. -#[derive(Clone, Debug)] -pub struct PrettyFormatter<'a> { - current_indent: usize, - has_value: bool, - indent: &'a [u8], -} - -impl<'a> PrettyFormatter<'a> { - /// Construct a pretty printer formatter that defaults to using two spaces for indentation. - pub fn new() -> Self { - PrettyFormatter::with_indent(b" ") - } - - /// Construct a pretty printer formatter that uses the `indent` string for indentation. - pub fn with_indent(indent: &'a [u8]) -> Self { - PrettyFormatter { - current_indent: 0, - has_value: false, - indent: indent, - } - } -} - -impl<'a> Default for PrettyFormatter<'a> { - fn default() -> Self { - PrettyFormatter::new() - } -} - -impl<'a> Formatter for PrettyFormatter<'a> { - #[inline] - fn begin_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - self.current_indent += 1; - self.has_value = false; - writer.write_all(b"[") - } - - #[inline] - fn end_array<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - self.current_indent -= 1; - - if self.has_value { - try!(writer.write_all(b"\n")); - try!(indent(writer, self.current_indent, self.indent)); - } - - writer.write_all(b"]") - } - - #[inline] - fn begin_array_value<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> - where - W: io::Write, - { - if first { - try!(writer.write_all(b"\n")); - } else { - try!(writer.write_all(b",\n")); - } - try!(indent(writer, self.current_indent, self.indent)); - Ok(()) - } - - #[inline] - fn end_array_value<W: ?Sized>(&mut self, _writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - self.has_value = true; - Ok(()) - } - - #[inline] - fn begin_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - self.current_indent += 1; - self.has_value = false; - writer.write_all(b"{") - } - - #[inline] - fn end_object<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - self.current_indent -= 1; - - if self.has_value { - try!(writer.write_all(b"\n")); - try!(indent(writer, self.current_indent, self.indent)); - } - - writer.write_all(b"}") - } - - #[inline] - fn begin_object_key<W: ?Sized>(&mut self, writer: &mut W, first: bool) -> io::Result<()> - where - W: io::Write, - { - if first { - try!(writer.write_all(b"\n")); - } else { - try!(writer.write_all(b",\n")); - } - indent(writer, self.current_indent, self.indent) - } - - #[inline] - fn begin_object_value<W: ?Sized>(&mut self, writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - writer.write_all(b": ") - } - - #[inline] - fn end_object_value<W: ?Sized>(&mut self, _writer: &mut W) -> io::Result<()> - where - W: io::Write, - { - self.has_value = true; - Ok(()) - } -} - -fn format_escaped_str<W: ?Sized, F: ?Sized>( - writer: &mut W, - formatter: &mut F, - value: &str, -) -> io::Result<()> -where - W: io::Write, - F: Formatter, -{ - try!(formatter.begin_string(writer)); - try!(format_escaped_str_contents(writer, formatter, value)); - try!(formatter.end_string(writer)); - Ok(()) -} - -fn format_escaped_str_contents<W: ?Sized, F: ?Sized>( - writer: &mut W, - formatter: &mut F, - value: &str, -) -> io::Result<()> -where - W: io::Write, - F: Formatter, -{ - let bytes = value.as_bytes(); - - let mut start = 0; - - for (i, &byte) in bytes.iter().enumerate() { - let escape = ESCAPE[byte as usize]; - if escape == 0 { - continue; - } - - if start < i { - try!(formatter.write_string_fragment(writer, &value[start..i])); - } - - let char_escape = CharEscape::from_escape_table(escape, byte); - try!(formatter.write_char_escape(writer, char_escape)); - - start = i + 1; - } - - if start != bytes.len() { - try!(formatter.write_string_fragment(writer, &value[start..])); - } - - Ok(()) -} - -const BB: u8 = b'b'; // \x08 -const TT: u8 = b't'; // \x09 -const NN: u8 = b'n'; // \x0A -const FF: u8 = b'f'; // \x0C -const RR: u8 = b'r'; // \x0D -const QU: u8 = b'"'; // \x22 -const BS: u8 = b'\\'; // \x5C -const U: u8 = b'u'; // \x00...\x1F except the ones above - -// Lookup table of escape sequences. A value of b'x' at index i means that byte -// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped. -#[cfg_attr(rustfmt, rustfmt_skip)] -static ESCAPE: [u8; 256] = [ - // 1 2 3 4 5 6 7 8 9 A B C D E F - U, U, U, U, U, U, U, U, BB, TT, NN, U, FF, RR, U, U, // 0 - U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, U, // 1 - 0, 0, QU, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 4 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, BS, 0, 0, 0, // 5 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 6 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 7 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F -]; - -/// Serialize the given data structure as JSON into the IO stream. -/// -/// # Errors -/// -/// Serialization can fail if `T`'s implementation of `Serialize` decides to -/// fail, or if `T` contains a map with non-string keys. -#[inline] -pub fn to_writer<W, T: ?Sized>(writer: W, value: &T) -> Result<()> -where - W: io::Write, - T: ser::Serialize, -{ - let mut ser = Serializer::new(writer); - try!(value.serialize(&mut ser)); - Ok(()) -} - -/// Serialize the given data structure as pretty-printed JSON into the IO -/// stream. -/// -/// # Errors -/// -/// Serialization can fail if `T`'s implementation of `Serialize` decides to -/// fail, or if `T` contains a map with non-string keys. -#[inline] -pub fn to_writer_pretty<W, T: ?Sized>(writer: W, value: &T) -> Result<()> -where - W: io::Write, - T: ser::Serialize, -{ - let mut ser = Serializer::pretty(writer); - try!(value.serialize(&mut ser)); - Ok(()) -} - -/// Serialize the given data structure as a JSON byte vector. -/// -/// # Errors -/// -/// Serialization can fail if `T`'s implementation of `Serialize` decides to -/// fail, or if `T` contains a map with non-string keys. -#[inline] -pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>> -where - T: ser::Serialize, -{ - let mut writer = Vec::with_capacity(128); - try!(to_writer(&mut writer, value)); - Ok(writer) -} - -/// Serialize the given data structure as a pretty-printed JSON byte vector. -/// -/// # Errors -/// -/// Serialization can fail if `T`'s implementation of `Serialize` decides to -/// fail, or if `T` contains a map with non-string keys. -#[inline] -pub fn to_vec_pretty<T: ?Sized>(value: &T) -> Result<Vec<u8>> -where - T: ser::Serialize, -{ - let mut writer = Vec::with_capacity(128); - try!(to_writer_pretty(&mut writer, value)); - Ok(writer) -} - -/// Serialize the given data structure as a String of JSON. -/// -/// # Errors -/// -/// Serialization can fail if `T`'s implementation of `Serialize` decides to -/// fail, or if `T` contains a map with non-string keys. -#[inline] -pub fn to_string<T: ?Sized>(value: &T) -> Result<String> -where - T: ser::Serialize, -{ - let vec = try!(to_vec(value)); - let string = unsafe { - // We do not emit invalid UTF-8. - String::from_utf8_unchecked(vec) - }; - Ok(string) -} - -/// Serialize the given data structure as a pretty-printed String of JSON. -/// -/// # Errors -/// -/// Serialization can fail if `T`'s implementation of `Serialize` decides to -/// fail, or if `T` contains a map with non-string keys. -#[inline] -pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String> -where - T: ser::Serialize, -{ - let vec = try!(to_vec_pretty(value)); - let string = unsafe { - // We do not emit invalid UTF-8. - String::from_utf8_unchecked(vec) - }; - Ok(string) -} - -fn indent<W: ?Sized>(wr: &mut W, n: usize, s: &[u8]) -> io::Result<()> -where - W: io::Write, -{ - for _ in 0..n { - try!(wr.write_all(s)); - } - - Ok(()) -} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/value/de.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/value/de.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/value/de.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/value/de.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,909 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::borrow::Cow; -use std::fmt; -use std::i64; -use std::io; -use std::slice; -use std::str; -use std::vec; - -use serde; -use serde::de::{ - Deserialize, - DeserializeSeed, - IntoDeserializer, - Visitor, - SeqAccess, - MapAccess, - EnumAccess, - VariantAccess, - Unexpected -}; - -use error::Error; -use map::Map; -use number::Number; -use value::Value; - -impl<'de> Deserialize<'de> for Value { - #[inline] - fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> - where - D: serde::Deserializer<'de>, - { - struct ValueVisitor; - - impl<'de> Visitor<'de> for ValueVisitor { - type Value = Value; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("any valid JSON value") - } - - #[inline] - fn visit_bool<E>(self, value: bool) -> Result<Value, E> { - Ok(Value::Bool(value)) - } - - #[inline] - fn visit_i64<E>(self, value: i64) -> Result<Value, E> { - Ok(Value::Number(value.into())) - } - - #[inline] - fn visit_u64<E>(self, value: u64) -> Result<Value, E> { - Ok(Value::Number(value.into())) - } - - #[inline] - fn visit_f64<E>(self, value: f64) -> Result<Value, E> { - Ok(Number::from_f64(value).map_or(Value::Null, Value::Number)) - } - - #[inline] - fn visit_str<E>(self, value: &str) -> Result<Value, E> - where - E: serde::de::Error, - { - self.visit_string(String::from(value)) - } - - #[inline] - fn visit_string<E>(self, value: String) -> Result<Value, E> { - Ok(Value::String(value)) - } - - #[inline] - fn visit_none<E>(self) -> Result<Value, E> { - Ok(Value::Null) - } - - #[inline] - fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error> - where - D: serde::Deserializer<'de>, - { - Deserialize::deserialize(deserializer) - } - - #[inline] - fn visit_unit<E>(self) -> Result<Value, E> { - Ok(Value::Null) - } - - #[inline] - fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error> - where - V: SeqAccess<'de>, - { - let mut vec = Vec::new(); - - while let Some(elem) = try!(visitor.next_element()) { - vec.push(elem); - } - - Ok(Value::Array(vec)) - } - - fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error> - where - V: MapAccess<'de>, - { - let mut values = Map::new(); - - while let Some((key, value)) = try!(visitor.next_entry()) { - values.insert(key, value); - } - - Ok(Value::Object(values)) - } - } - - deserializer.deserialize_any(ValueVisitor) - } -} - -struct WriterFormatter<'a, 'b: 'a> { - inner: &'a mut fmt::Formatter<'b>, -} - -impl<'a, 'b> io::Write for WriterFormatter<'a, 'b> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - fn io_error<E>(_: E) -> io::Error { - // Value does not matter because fmt::Debug and fmt::Display impls - // below just map it to fmt::Error - io::Error::new(io::ErrorKind::Other, "fmt error") - } - let s = try!(str::from_utf8(buf).map_err(io_error)); - try!(self.inner.write_str(s).map_err(io_error)); - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -impl fmt::Display for Value { - /// Display a JSON value as a string. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let json = json!({ "city": "London", "street": "10 Downing Street" }); - /// - /// // Compact format: - /// // - /// // {"city":"London","street":"10 Downing Street"} - /// let compact = format!("{}", json); - /// assert_eq!(compact, - /// "{\"city\":\"London\",\"street\":\"10 Downing Street\"}"); - /// - /// // Pretty format: - /// // - /// // { - /// // "city": "London", - /// // "street": "10 Downing Street" - /// // } - /// let pretty = format!("{:#}", json); - /// assert_eq!(pretty, - /// "{\n \"city\": \"London\",\n \"street\": \"10 Downing Street\"\n}"); - /// # } - /// ``` - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let alternate = f.alternate(); - let mut wr = WriterFormatter { inner: f }; - if alternate { - // {:#} - super::super::ser::to_writer_pretty(&mut wr, self).map_err(|_| fmt::Error) - } else { - // {} - super::super::ser::to_writer(&mut wr, self).map_err(|_| fmt::Error) - } - } -} - -impl str::FromStr for Value { - type Err = Error; - fn from_str(s: &str) -> Result<Value, Error> { - super::super::de::from_str(s) - } -} - -impl<'de> serde::Deserializer<'de> for Value { - type Error = Error; - - #[inline] - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - match self { - Value::Null => visitor.visit_unit(), - Value::Bool(v) => visitor.visit_bool(v), - Value::Number(n) => n.deserialize_any(visitor), - Value::String(v) => visitor.visit_string(v), - Value::Array(v) => { - let len = v.len(); - let mut deserializer = SeqDeserializer::new(v); - let seq = try!(visitor.visit_seq(&mut deserializer)); - let remaining = deserializer.iter.len(); - if remaining == 0 { - Ok(seq) - } else { - Err(serde::de::Error::invalid_length(len, &"fewer elements in array")) - } - } - Value::Object(v) => { - let len = v.len(); - let mut deserializer = MapDeserializer::new(v); - let map = try!(visitor.visit_map(&mut deserializer)); - let remaining = deserializer.iter.len(); - if remaining == 0 { - Ok(map) - } else { - Err(serde::de::Error::invalid_length(len, &"fewer elements in map")) - } - } - } - } - - #[inline] - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - match self { - Value::Null => visitor.visit_none(), - _ => visitor.visit_some(self), - } - } - - #[inline] - fn deserialize_enum<V>( - self, - _name: &str, - _variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - let (variant, value) = match self { - Value::Object(value) => { - let mut iter = value.into_iter(); - let (variant, value) = match iter.next() { - Some(v) => v, - None => { - return Err( - serde::de::Error::invalid_value( - Unexpected::Map, - &"map with a single key", - ), - ); - } - }; - // enums are encoded in json as maps with a single key:value pair - if iter.next().is_some() { - return Err(serde::de::Error::invalid_value(Unexpected::Map, &"map with a single key"),); - } - (variant, Some(value)) - } - Value::String(variant) => (variant, None), - other => { - return Err(serde::de::Error::invalid_type(other.unexpected(), &"string or map"),); - } - }; - - visitor.visit_enum( - EnumDeserializer { - variant: variant, - value: value, - }, - ) - } - - #[inline] - fn deserialize_newtype_struct<V>( - self, - _name: &'static str, - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>, - { - visitor.visit_newtype_struct(self) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf unit unit_struct seq tuple tuple_struct map struct identifier - ignored_any - } -} - -struct EnumDeserializer { - variant: String, - value: Option<Value>, -} - -impl<'de> EnumAccess<'de> for EnumDeserializer { - type Error = Error; - type Variant = VariantDeserializer; - - fn variant_seed<V>(self, seed: V) -> Result<(V::Value, VariantDeserializer), Error> - where - V: DeserializeSeed<'de>, - { - let variant = self.variant.into_deserializer(); - let visitor = VariantDeserializer { value: self.value }; - seed.deserialize(variant).map(|v| (v, visitor)) - } -} - -struct VariantDeserializer { - value: Option<Value>, -} - -impl<'de> VariantAccess<'de> for VariantDeserializer { - type Error = Error; - - fn unit_variant(self) -> Result<(), Error> { - match self.value { - Some(value) => Deserialize::deserialize(value), - None => Ok(()), - } - } - - fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error> - where - T: DeserializeSeed<'de>, - { - match self.value { - Some(value) => seed.deserialize(value), - None => Err(serde::de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant"),), - } - } - - fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - match self.value { - Some(Value::Array(v)) => { - serde::Deserializer::deserialize_any(SeqDeserializer::new(v), visitor) - } - Some(other) => Err(serde::de::Error::invalid_type(other.unexpected(), &"tuple variant"),), - None => Err(serde::de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"),), - } - } - - fn struct_variant<V>( - self, - _fields: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - match self.value { - Some(Value::Object(v)) => { - serde::Deserializer::deserialize_any(MapDeserializer::new(v), visitor) - } - Some(other) => Err(serde::de::Error::invalid_type(other.unexpected(), &"struct variant"),), - _ => Err(serde::de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"),), - } - } -} - -struct SeqDeserializer { - iter: vec::IntoIter<Value>, -} - -impl SeqDeserializer { - fn new(vec: Vec<Value>) -> Self { - SeqDeserializer { iter: vec.into_iter() } - } -} - -impl<'de> serde::Deserializer<'de> for SeqDeserializer { - type Error = Error; - - #[inline] - fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - let len = self.iter.len(); - if len == 0 { - visitor.visit_unit() - } else { - let ret = try!(visitor.visit_seq(&mut self)); - let remaining = self.iter.len(); - if remaining == 0 { - Ok(ret) - } else { - Err(serde::de::Error::invalid_length(len, &"fewer elements in array")) - } - } - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any - } -} - -impl<'de> SeqAccess<'de> for SeqDeserializer { - type Error = Error; - - fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> - where - T: DeserializeSeed<'de>, - { - match self.iter.next() { - Some(value) => seed.deserialize(value).map(Some), - None => Ok(None), - } - } - - fn size_hint(&self) -> Option<usize> { - match self.iter.size_hint() { - (lower, Some(upper)) if lower == upper => Some(upper), - _ => None, - } - } -} - -struct MapDeserializer { - iter: <Map<String, Value> as IntoIterator>::IntoIter, - value: Option<Value>, -} - -impl MapDeserializer { - fn new(map: Map<String, Value>) -> Self { - MapDeserializer { - iter: map.into_iter(), - value: None, - } - } -} - -impl<'de> MapAccess<'de> for MapDeserializer { - type Error = Error; - - fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> - where - T: DeserializeSeed<'de>, - { - match self.iter.next() { - Some((key, value)) => { - self.value = Some(value); - let key_de = MapKeyDeserializer { key: Cow::Owned(key) }; - seed.deserialize(key_de).map(Some) - } - None => Ok(None), - } - } - - fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Error> - where - T: DeserializeSeed<'de>, - { - match self.value.take() { - Some(value) => seed.deserialize(value), - None => Err(serde::de::Error::custom("value is missing")), - } - } - - fn size_hint(&self) -> Option<usize> { - match self.iter.size_hint() { - (lower, Some(upper)) if lower == upper => Some(upper), - _ => None, - } - } -} - -impl<'de> serde::Deserializer<'de> for MapDeserializer { - type Error = Error; - - #[inline] - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - visitor.visit_map(self) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any - } -} - -impl<'de> serde::Deserializer<'de> for &'de Value { - type Error = Error; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - match *self { - Value::Null => visitor.visit_unit(), - Value::Bool(v) => visitor.visit_bool(v), - Value::Number(ref n) => n.deserialize_any(visitor), - Value::String(ref v) => visitor.visit_borrowed_str(v), - Value::Array(ref v) => { - let len = v.len(); - let mut deserializer = SeqRefDeserializer::new(v); - let seq = try!(visitor.visit_seq(&mut deserializer)); - let remaining = deserializer.iter.len(); - if remaining == 0 { - Ok(seq) - } else { - Err(serde::de::Error::invalid_length(len, &"fewer elements in array")) - } - } - Value::Object(ref v) => { - let len = v.len(); - let mut deserializer = MapRefDeserializer::new(v); - let map = try!(visitor.visit_map(&mut deserializer)); - let remaining = deserializer.iter.len(); - if remaining == 0 { - Ok(map) - } else { - Err(serde::de::Error::invalid_length(len, &"fewer elements in map")) - } - } - } - } - - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - match *self { - Value::Null => visitor.visit_none(), - _ => visitor.visit_some(self), - } - } - - fn deserialize_enum<V>( - self, - _name: &str, - _variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - let (variant, value) = match *self { - Value::Object(ref value) => { - let mut iter = value.into_iter(); - let (variant, value) = match iter.next() { - Some(v) => v, - None => { - return Err( - serde::de::Error::invalid_value( - Unexpected::Map, - &"map with a single key", - ), - ); - } - }; - // enums are encoded in json as maps with a single key:value pair - if iter.next().is_some() { - return Err(serde::de::Error::invalid_value(Unexpected::Map, &"map with a single key"),); - } - (variant, Some(value)) - } - Value::String(ref variant) => (variant, None), - ref other => { - return Err(serde::de::Error::invalid_type(other.unexpected(), &"string or map"),); - } - }; - - visitor.visit_enum( - EnumRefDeserializer { - variant: variant, - value: value, - }, - ) - } - - #[inline] - fn deserialize_newtype_struct<V>( - self, - _name: &'static str, - visitor: V, - ) -> Result<V::Value, Self::Error> - where - V: Visitor<'de>, - { - visitor.visit_newtype_struct(self) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf unit unit_struct seq tuple tuple_struct map struct identifier - ignored_any - } -} - -struct EnumRefDeserializer<'de> { - variant: &'de str, - value: Option<&'de Value>, -} - -impl<'de> EnumAccess<'de> for EnumRefDeserializer<'de> { - type Error = Error; - type Variant = VariantRefDeserializer<'de>; - - fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Error> - where - V: DeserializeSeed<'de>, - { - let variant = self.variant.into_deserializer(); - let visitor = VariantRefDeserializer { value: self.value }; - seed.deserialize(variant).map(|v| (v, visitor)) - } -} - -struct VariantRefDeserializer<'de> { - value: Option<&'de Value>, -} - -impl<'de> VariantAccess<'de> for VariantRefDeserializer<'de> { - type Error = Error; - - fn unit_variant(self) -> Result<(), Error> { - match self.value { - Some(value) => Deserialize::deserialize(value), - None => Ok(()), - } - } - - fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value, Error> - where - T: DeserializeSeed<'de>, - { - match self.value { - Some(value) => seed.deserialize(value), - None => Err(serde::de::Error::invalid_type(Unexpected::UnitVariant, &"newtype variant"),), - } - } - - fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - match self.value { - Some(&Value::Array(ref v)) => { - serde::Deserializer::deserialize_any(SeqRefDeserializer::new(v), visitor) - } - Some(other) => Err(serde::de::Error::invalid_type(other.unexpected(), &"tuple variant"),), - None => Err(serde::de::Error::invalid_type(Unexpected::UnitVariant, &"tuple variant"),), - } - } - - fn struct_variant<V>( - self, - _fields: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - match self.value { - Some(&Value::Object(ref v)) => { - serde::Deserializer::deserialize_any(MapRefDeserializer::new(v), visitor) - } - Some(other) => Err(serde::de::Error::invalid_type(other.unexpected(), &"struct variant"),), - _ => Err(serde::de::Error::invalid_type(Unexpected::UnitVariant, &"struct variant"),), - } - } -} - -struct SeqRefDeserializer<'de> { - iter: slice::Iter<'de, Value>, -} - -impl<'de> SeqRefDeserializer<'de> { - fn new(slice: &'de [Value]) -> Self { - SeqRefDeserializer { iter: slice.iter() } - } -} - -impl<'de> serde::Deserializer<'de> for SeqRefDeserializer<'de> { - type Error = Error; - - #[inline] - fn deserialize_any<V>(mut self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - let len = self.iter.len(); - if len == 0 { - visitor.visit_unit() - } else { - let ret = try!(visitor.visit_seq(&mut self)); - let remaining = self.iter.len(); - if remaining == 0 { - Ok(ret) - } else { - Err(serde::de::Error::invalid_length(len, &"fewer elements in array")) - } - } - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any - } -} - -impl<'de> SeqAccess<'de> for SeqRefDeserializer<'de> { - type Error = Error; - - fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> - where - T: DeserializeSeed<'de>, - { - match self.iter.next() { - Some(value) => seed.deserialize(value).map(Some), - None => Ok(None), - } - } - - fn size_hint(&self) -> Option<usize> { - match self.iter.size_hint() { - (lower, Some(upper)) if lower == upper => Some(upper), - _ => None, - } - } -} - -struct MapRefDeserializer<'de> { - iter: <&'de Map<String, Value> as IntoIterator>::IntoIter, - value: Option<&'de Value>, -} - -impl<'de> MapRefDeserializer<'de> { - fn new(map: &'de Map<String, Value>) -> Self { - MapRefDeserializer { - iter: map.into_iter(), - value: None, - } - } -} - -impl<'de> MapAccess<'de> for MapRefDeserializer<'de> { - type Error = Error; - - fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, Error> - where - T: DeserializeSeed<'de>, - { - match self.iter.next() { - Some((key, value)) => { - self.value = Some(value); - let key_de = MapKeyDeserializer { key: Cow::Borrowed(&**key) }; - seed.deserialize(key_de).map(Some) - } - None => Ok(None), - } - } - - fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, Error> - where - T: DeserializeSeed<'de>, - { - match self.value.take() { - Some(value) => seed.deserialize(value), - None => Err(serde::de::Error::custom("value is missing")), - } - } - - fn size_hint(&self) -> Option<usize> { - match self.iter.size_hint() { - (lower, Some(upper)) if lower == upper => Some(upper), - _ => None, - } - } -} - -impl<'de> serde::Deserializer<'de> for MapRefDeserializer<'de> { - type Error = Error; - - #[inline] - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - visitor.visit_map(self) - } - - forward_to_deserialize_any! { - bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes - byte_buf option unit unit_struct newtype_struct seq tuple - tuple_struct map struct enum identifier ignored_any - } -} - -struct MapKeyDeserializer<'de> { - key: Cow<'de, str>, -} - -macro_rules! deserialize_integer_key { - ($deserialize:ident => $visit:ident) => { - fn $deserialize<V>(self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - match (self.key.parse(), self.key) { - (Ok(integer), _) => visitor.$visit(integer), - (Err(_), Cow::Borrowed(s)) => visitor.visit_borrowed_str(s), - (Err(_), Cow::Owned(s)) => visitor.visit_string(s), - } - } - } -} - -impl<'de> serde::Deserializer<'de> for MapKeyDeserializer<'de> { - type Error = Error; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - self.key.into_deserializer().deserialize_any(visitor) - } - - deserialize_integer_key!(deserialize_i8 => visit_i8); - deserialize_integer_key!(deserialize_i16 => visit_i16); - deserialize_integer_key!(deserialize_i32 => visit_i32); - deserialize_integer_key!(deserialize_i64 => visit_i64); - deserialize_integer_key!(deserialize_u8 => visit_u8); - deserialize_integer_key!(deserialize_u16 => visit_u16); - deserialize_integer_key!(deserialize_u32 => visit_u32); - deserialize_integer_key!(deserialize_u64 => visit_u64); - - #[inline] - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - // Map keys cannot be null. - visitor.visit_some(self) - } - - #[inline] - fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - visitor.visit_newtype_struct(self) - } - - fn deserialize_enum<V>( - self, - name: &'static str, - variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, Error> - where - V: Visitor<'de>, - { - self.key.into_deserializer().deserialize_enum(name, variants, visitor) - } - - forward_to_deserialize_any! { - bool f32 f64 char str string bytes byte_buf unit unit_struct seq tuple - tuple_struct map struct identifier ignored_any - } -} - -impl Value { - fn unexpected(&self) -> Unexpected { - match *self { - Value::Null => Unexpected::Unit, - Value::Bool(b) => Unexpected::Bool(b), - Value::Number(ref n) => n.unexpected(), - Value::String(ref s) => Unexpected::Str(s), - Value::Array(_) => Unexpected::Seq, - Value::Object(_) => Unexpected::Map, - } - } -} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/value/from.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/value/from.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/value/from.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/value/from.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,268 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::borrow::Cow; - -use super::Value; -use map::Map; -use number::Number; - -macro_rules! from_integer { - ($($ty:ident)*) => { - $( - impl From<$ty> for Value { - fn from(n: $ty) -> Self { - Value::Number(n.into()) - } - } - )* - }; -} - -from_integer! { - i8 i16 i32 i64 isize - u8 u16 u32 u64 usize -} - -impl From<f32> for Value { - /// Convert 32-bit floating point number to `Value` - /// - /// # Examples - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::Value; - /// - /// let f: f32 = 13.37; - /// let x: Value = f.into(); - /// # } - /// ``` - fn from(f: f32) -> Self { - From::from(f as f64) - } -} - -impl From<f64> for Value { - /// Convert 64-bit floating point number to `Value` - /// - /// # Examples - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::Value; - /// - /// let f: f64 = 13.37; - /// let x: Value = f.into(); - /// # } - /// ``` - fn from(f: f64) -> Self { - Number::from_f64(f).map_or(Value::Null, Value::Number) - } -} - -impl From<bool> for Value { - /// Convert boolean to `Value` - /// - /// # Examples - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::Value; - /// - /// let b = false; - /// let x: Value = b.into(); - /// # } - /// ``` - fn from(f: bool) -> Self { - Value::Bool(f) - } -} - -impl From<String> for Value { - /// Convert `String` to `Value` - /// - /// # Examples - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::Value; - /// - /// let s: String = "lorem".to_string(); - /// let x: Value = s.into(); - /// # } - /// ``` - fn from(f: String) -> Self { - Value::String(f) - } -} - -impl<'a> From<&'a str> for Value { - /// Convert string slice to `Value` - /// - /// # Examples - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::Value; - /// - /// let s: &str = "lorem"; - /// let x: Value = s.into(); - /// # } - /// ``` - fn from(f: &str) -> Self { - Value::String(f.to_string()) - } -} - -impl<'a> From<Cow<'a, str>> for Value { - /// Convert copy-on-write string to `Value` - /// - /// # Examples - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::Value; - /// use std::borrow::Cow; - /// - /// let s: Cow<str> = Cow::Borrowed("lorem"); - /// let x: Value = s.into(); - /// # } - /// ``` - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::Value; - /// use std::borrow::Cow; - /// - /// let s: Cow<str> = Cow::Owned("lorem".to_string()); - /// let x: Value = s.into(); - /// # } - /// ``` - fn from(f: Cow<'a, str>) -> Self { - Value::String(f.to_string()) - } -} - -impl From<Map<String, Value>> for Value { - /// Convert map (with string keys) to `Value` - /// - /// # Examples - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::{Map, Value}; - /// - /// let mut m = Map::new(); - /// m.insert("Lorem".to_string(), "ipsum".into()); - /// let x: Value = m.into(); - /// # } - /// ``` - fn from(f: Map<String, Value>) -> Self { - Value::Object(f) - } -} - -impl<T: Into<Value>> From<Vec<T>> for Value { - /// Convert a `Vec` to `Value` - /// - /// # Examples - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::Value; - /// - /// let v = vec!["lorem", "ipsum", "dolor"]; - /// let x: Value = v.into(); - /// # } - /// ``` - fn from(f: Vec<T>) -> Self { - Value::Array(f.into_iter().map(Into::into).collect()) - } -} - -impl<'a, T: Clone + Into<Value>> From<&'a [T]> for Value { - /// Convert a slice to `Value` - /// - /// # Examples - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::Value; - /// - /// let v: &[&str] = &["lorem", "ipsum", "dolor"]; - /// let x: Value = v.into(); - /// # } - /// ``` - fn from(f: &'a [T]) -> Self { - Value::Array(f.into_iter().cloned().map(Into::into).collect()) - } -} - -impl<T: Into<Value>> ::std::iter::FromIterator<T> for Value { - /// Convert an iteratable type to a `Value` - /// - /// # Examples - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::Value; - /// - /// let v = std::iter::repeat(42).take(5); - /// let x: Value = v.collect(); - /// # } - /// ``` - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use serde_json::Value; - /// - /// let v: Vec<_> = vec!["lorem", "ipsum", "dolor"]; - /// let x: Value = v.into_iter().collect(); - /// # } - /// ``` - /// - /// ```rust - /// # extern crate serde_json; - /// # - /// # fn main() { - /// use std::iter::FromIterator; - /// use serde_json::Value; - /// - /// let x: Value = Value::from_iter(vec!["lorem", "ipsum", "dolor"]); - /// # } - /// ``` - fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self { - let vec: Vec<Value> = iter.into_iter().map(|x| x.into()).collect(); - - Value::Array(vec) - } -} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/value/index.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/value/index.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/value/index.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/value/index.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,286 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::fmt; -use std::ops; - -use super::Value; -use map::Map; - -/// A type that can be used to index into a `serde_json::Value`. -/// -/// The [`get`] and [`get_mut`] methods of `Value` accept any type that -/// implements `Index`, as does the [square-bracket indexing operator]. This -/// trait is implemented for strings which are used as the index into a JSON -/// map, and for `usize` which is used as the index into a JSON array. -/// -/// [`get`]: ../enum.Value.html#method.get -/// [`get_mut`]: ../enum.Value.html#method.get_mut -/// [square-bracket indexing operator]: ../enum.Value.html#impl-Index%3CI%3E -/// -/// This trait is sealed and cannot be implemented for types outside of -/// `serde_json`. -/// -/// # Examples -/// -/// ```rust -/// # #[macro_use] -/// # extern crate serde_json; -/// # -/// # fn main() { -/// let data = json!({ "inner": [1, 2, 3] }); -/// -/// // Data is a JSON map so it can be indexed with a string. -/// let inner = &data["inner"]; -/// -/// // Inner is a JSON array so it can be indexed with an integer. -/// let first = &inner[0]; -/// -/// assert_eq!(first, 1); -/// # } -/// ``` -pub trait Index: private::Sealed { - /// Return None if the key is not already in the array or object. - #[doc(hidden)] - fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value>; - - /// Return None if the key is not already in the array or object. - #[doc(hidden)] - fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value>; - - /// Panic if array index out of bounds. If key is not already in the object, - /// insert it with a value of null. Panic if Value is a type that cannot be - /// indexed into, except if Value is null then it can be treated as an empty - /// object. - #[doc(hidden)] - fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value; -} - -impl Index for usize { - fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { - match *v { - Value::Array(ref vec) => vec.get(*self), - _ => None, - } - } - fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { - match *v { - Value::Array(ref mut vec) => vec.get_mut(*self), - _ => None, - } - } - fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { - match *v { - Value::Array(ref mut vec) => { - let len = vec.len(); - vec.get_mut(*self) - .unwrap_or_else( - || { - panic!( - "cannot access index {} of JSON array of length {}", - self, - len - ) - }, - ) - } - _ => panic!("cannot access index {} of JSON {}", self, Type(v)), - } - } -} - -impl Index for str { - fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { - match *v { - Value::Object(ref map) => map.get(self), - _ => None, - } - } - fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { - match *v { - Value::Object(ref mut map) => map.get_mut(self), - _ => None, - } - } - fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { - if let Value::Null = *v { - let mut map = Map::new(); - map.insert(self.to_owned(), Value::Null); - *v = Value::Object(map); - } - match *v { - Value::Object(ref mut map) => { - map.entry(self.to_owned()).or_insert(Value::Null) - } - _ => panic!("cannot access key {:?} in JSON {}", self, Type(v)), - } - } -} - -impl Index for String { - fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { - self[..].index_into(v) - } - fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { - self[..].index_into_mut(v) - } - fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { - self[..].index_or_insert(v) - } -} - -impl<'a, T: ?Sized> Index for &'a T -where - T: Index, -{ - fn index_into<'v>(&self, v: &'v Value) -> Option<&'v Value> { - (**self).index_into(v) - } - fn index_into_mut<'v>(&self, v: &'v mut Value) -> Option<&'v mut Value> { - (**self).index_into_mut(v) - } - fn index_or_insert<'v>(&self, v: &'v mut Value) -> &'v mut Value { - (**self).index_or_insert(v) - } -} - -// Prevent users from implementing the Index trait. -mod private { - pub trait Sealed {} - impl Sealed for usize {} - impl Sealed for str {} - impl Sealed for String {} - impl<'a, T: ?Sized> Sealed for &'a T - where - T: Sealed, - { - } -} - -/// Used in panic messages. -struct Type<'a>(&'a Value); - -impl<'a> fmt::Display for Type<'a> { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match *self.0 { - Value::Null => formatter.write_str("null"), - Value::Bool(_) => formatter.write_str("boolean"), - Value::Number(_) => formatter.write_str("number"), - Value::String(_) => formatter.write_str("string"), - Value::Array(_) => formatter.write_str("array"), - Value::Object(_) => formatter.write_str("object"), - } - } -} - -// The usual semantics of Index is to panic on invalid indexing. -// -// That said, the usual semantics are for things like Vec and BTreeMap which -// have different use cases than Value. If you are working with a Vec, you know -// that you are working with a Vec and you can get the len of the Vec and make -// sure your indices are within bounds. The Value use cases are more -// loosey-goosey. You got some JSON from an endpoint and you want to pull values -// out of it. Outside of this Index impl, you already have the option of using -// value.as_array() and working with the Vec directly, or matching on -// Value::Array and getting the Vec directly. The Index impl means you can skip -// that and index directly into the thing using a concise syntax. You don't have -// to check the type, you don't have to check the len, it is all about what you -// expect the Value to look like. -// -// Basically the use cases that would be well served by panicking here are -// better served by using one of the other approaches: get and get_mut, -// as_array, or match. The value of this impl is that it adds a way of working -// with Value that is not well served by the existing approaches: concise and -// careless and sometimes that is exactly what you want. -impl<I> ops::Index<I> for Value -where - I: Index, -{ - type Output = Value; - - /// Index into a `serde_json::Value` using the syntax `value[0]` or - /// `value["k"]`. - /// - /// Returns `Value::Null` if the type of `self` does not match the type of - /// the index, for example if the index is a string and `self` is an array - /// or a number. Also returns `Value::Null` if the given key does not exist - /// in the map or the given index is not within the bounds of the array. - /// - /// For retrieving deeply nested values, you should have a look at the - /// `Value::pointer` method. - /// - /// # Examples - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let data = json!({ - /// "x": { - /// "y": ["z", "zz"] - /// } - /// }); - /// - /// assert_eq!(data["x"]["y"], json!(["z", "zz"])); - /// assert_eq!(data["x"]["y"][0], json!("z")); - /// - /// assert_eq!(data["a"], json!(null)); // returns null for undefined values - /// assert_eq!(data["a"]["b"], json!(null)); // does not panic - /// # } - /// ``` - fn index(&self, index: I) -> &Value { - static NULL: Value = Value::Null; - index.index_into(self).unwrap_or(&NULL) - } -} - -impl<I> ops::IndexMut<I> for Value -where - I: Index, -{ - /// Write into a `serde_json::Value` using the syntax `value[0] = ...` or - /// `value["k"] = ...`. - /// - /// If the index is a number, the value must be an array of length bigger - /// than the index. Indexing into a value that is not an array or an array - /// that is too small will panic. - /// - /// If the index is a string, the value must be an object or null which is - /// treated like an empty object. If the key is not already present in the - /// object, it will be inserted with a value of null. Indexing into a value - /// that is neither an object nor null will panic. - /// - /// # Examples - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let mut data = json!({ "x": 0 }); - /// - /// // replace an existing key - /// data["x"] = json!(1); - /// - /// // insert a new key - /// data["y"] = json!([false, false, false]); - /// - /// // replace an array value - /// data["y"][0] = json!(true); - /// - /// // inserted a deeply nested key - /// data["a"]["b"]["c"]["d"] = json!(true); - /// - /// println!("{}", data); - /// # } - /// ``` - fn index_mut(&mut self, index: I) -> &mut Value { - index.index_or_insert(self) - } -} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/value/mod.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/value/mod.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/value/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/value/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1064 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! The Value enum, a loosely typed way of representing any valid JSON value. -//! -//! # Constructing JSON -//! -//! Serde JSON provides a [`json!` macro][macro] to build `serde_json::Value` -//! objects with very natural JSON syntax. In order to use this macro, -//! `serde_json` needs to be imported with the `#[macro_use]` attribute. -//! -//! ```rust -//! #[macro_use] -//! extern crate serde_json; -//! -//! fn main() { -//! // The type of `john` is `serde_json::Value` -//! let john = json!({ -//! "name": "John Doe", -//! "age": 43, -//! "phones": [ -//! "+44 1234567", -//! "+44 2345678" -//! ] -//! }); -//! -//! println!("first phone number: {}", john["phones"][0]); -//! -//! // Convert to a string of JSON and print it out -//! println!("{}", john.to_string()); -//! } -//! ``` -//! -//! The `Value::to_string()` function converts a `serde_json::Value` into a -//! `String` of JSON text. -//! -//! One neat thing about the `json!` macro is that variables and expressions can -//! be interpolated directly into the JSON value as you are building it. Serde -//! will check at compile time that the value you are interpolating is able to -//! be represented as JSON. -//! -//! ```rust -//! # #[macro_use] -//! # extern crate serde_json; -//! # -//! # fn random_phone() -> u16 { 0 } -//! # -//! # fn main() { -//! let full_name = "John Doe"; -//! let age_last_year = 42; -//! -//! // The type of `john` is `serde_json::Value` -//! let john = json!({ -//! "name": full_name, -//! "age": age_last_year + 1, -//! "phones": [ -//! format!("+44 {}", random_phone()) -//! ] -//! }); -//! # let _ = john; -//! # } -//! ``` -//! -//! A string of JSON data can be parsed into a `serde_json::Value` by the -//! [`serde_json::from_str`][from_str] function. There is also -//! [`from_slice`][from_slice] for parsing from a byte slice &[u8] and -//! [`from_reader`][from_reader] for parsing from any `io::Read` like a File or -//! a TCP stream. -//! -//! ```rust -//! extern crate serde_json; -//! -//! use serde_json::{Value, Error}; -//! -//! fn untyped_example() -> Result<(), Error> { -//! // Some JSON input data as a &str. Maybe this comes from the user. -//! let data = r#"{ -//! "name": "John Doe", -//! "age": 43, -//! "phones": [ -//! "+44 1234567", -//! "+44 2345678" -//! ] -//! }"#; -//! -//! // Parse the string of data into serde_json::Value. -//! let v: Value = serde_json::from_str(data)?; -//! -//! // Access parts of the data by indexing with square brackets. -//! println!("Please call {} at the number {}", v["name"], v["phones"][0]); -//! -//! Ok(()) -//! } -//! # -//! # fn main() { -//! # untyped_example().unwrap(); -//! # } -//! ``` -//! -//! [macro]: https://docs.serde.rs/serde_json/macro.json.html -//! [from_str]: https://docs.serde.rs/serde_json/de/fn.from_str.html -//! [from_slice]: https://docs.serde.rs/serde_json/de/fn.from_slice.html -//! [from_reader]: https://docs.serde.rs/serde_json/de/fn.from_reader.html - -use std::fmt::{self, Debug}; -use std::i64; -use std::str; - -use serde::ser::Serialize; -use serde::de::DeserializeOwned; - -use error::Error; -pub use map::Map; -pub use number::Number; - -pub use self::index::Index; - -use self::ser::Serializer; - -/// Represents any valid JSON value. -/// -/// See the `serde_json::value` module documentation for usage examples. -#[derive(Clone, PartialEq)] -pub enum Value { - /// Represents a JSON null value. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!(null); - /// # } - /// ``` - Null, - - /// Represents a JSON boolean. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!(true); - /// # } - /// ``` - Bool(bool), - - /// Represents a JSON number, whether integer or floating point. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!(12.5); - /// # } - /// ``` - Number(Number), - - /// Represents a JSON string. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!("a string"); - /// # } - /// ``` - String(String), - - /// Represents a JSON array. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!(["an", "array"]); - /// # } - /// ``` - Array(Vec<Value>), - - /// Represents a JSON object. - /// - /// By default the map is backed by a BTreeMap. Enable the `preserve_order` - /// feature of serde_json to use LinkedHashMap instead, which preserves - /// entries in the order they are inserted into the map. In particular, this - /// allows JSON data to be deserialized into a Value and serialized to a - /// string while retaining the order of map keys in the input. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "an": "object" }); - /// # } - /// ``` - Object(Map<String, Value>), -} - -impl Debug for Value { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - match *self { - Value::Null => { - formatter.debug_tuple("Null").finish() - } - Value::Bool(v) => { - formatter.debug_tuple("Bool").field(&v).finish() - } - Value::Number(ref v) => { - Debug::fmt(v, formatter) - } - Value::String(ref v) => { - formatter.debug_tuple("String").field(v).finish() - } - Value::Array(ref v) => { - formatter.debug_tuple("Array").field(v).finish() - } - Value::Object(ref v) => { - formatter.debug_tuple("Object").field(v).finish() - } - } - } -} - -fn parse_index(s: &str) -> Option<usize> { - if s.starts_with('+') || (s.starts_with('0') && s.len() != 1) { - return None; - } - s.parse().ok() -} - -impl Value { - /// Index into a JSON array or map. A string index can be used to access a - /// value in a map, and a usize index can be used to access an element of an - /// array. - /// - /// Returns `None` if the type of `self` does not match the type of the - /// index, for example if the index is a string and `self` is an array or a - /// number. Also returns `None` if the given key does not exist in the map - /// or the given index is not within the bounds of the array. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let object = json!({ "A": 65, "B": 66, "C": 67 }); - /// assert_eq!(*object.get("A").unwrap(), json!(65)); - /// - /// let array = json!([ "A", "B", "C" ]); - /// assert_eq!(*array.get(2).unwrap(), json!("C")); - /// - /// assert_eq!(array.get("A"), None); - /// # } - /// ``` - /// - /// Square brackets can also be used to index into a value in a more concise - /// way. This returns `Value::Null` in cases where `get` would have returned - /// `None`. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let object = json!({ - /// "A": ["a", "á", "à"], - /// "B": ["b", "b́"], - /// "C": ["c", "ć", "ć̣", "ḉ"], - /// }); - /// assert_eq!(object["B"][0], json!("b")); - /// - /// assert_eq!(object["D"], json!(null)); - /// assert_eq!(object[0]["x"]["y"]["z"], json!(null)); - /// # } - /// ``` - pub fn get<I: Index>(&self, index: I) -> Option<&Value> { - index.index_into(self) - } - - /// Mutably index into a JSON array or map. A string index can be used to - /// access a value in a map, and a usize index can be used to access an - /// element of an array. - /// - /// Returns `None` if the type of `self` does not match the type of the - /// index, for example if the index is a string and `self` is an array or a - /// number. Also returns `None` if the given key does not exist in the map - /// or the given index is not within the bounds of the array. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let mut object = json!({ "A": 65, "B": 66, "C": 67 }); - /// *object.get_mut("A").unwrap() = json!(69); - /// - /// let mut array = json!([ "A", "B", "C" ]); - /// *array.get_mut(2).unwrap() = json!("D"); - /// # } - /// ``` - pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> { - index.index_into_mut(self) - } - - /// Returns true if the `Value` is an Object. Returns false otherwise. - /// - /// For any Value on which `is_object` returns true, `as_object` and - /// `as_object_mut` are guaranteed to return the map representation of the - /// object. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let obj = json!({ "a": { "nested": true }, "b": ["an", "array"] }); - /// - /// assert!(obj.is_object()); - /// assert!(obj["a"].is_object()); - /// - /// // array, not an object - /// assert!(!obj["b"].is_object()); - /// # } - /// ``` - pub fn is_object(&self) -> bool { - self.as_object().is_some() - } - - /// If the `Value` is an Object, returns the associated Map. Returns None - /// otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": { "nested": true }, "b": ["an", "array"] }); - /// - /// // The length of `{"nested": true}` is 1 entry. - /// assert_eq!(v["a"].as_object().unwrap().len(), 1); - /// - /// // The array `["an", "array"]` is not an object. - /// assert_eq!(v["b"].as_object(), None); - /// # } - /// ``` - pub fn as_object(&self) -> Option<&Map<String, Value>> { - match *self { - Value::Object(ref map) => Some(map), - _ => None, - } - } - - /// If the `Value` is an Object, returns the associated mutable Map. - /// Returns None otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let mut v = json!({ "a": { "nested": true } }); - /// - /// v["a"].as_object_mut().unwrap().clear(); - /// assert_eq!(v, json!({ "a": {} })); - /// # } - /// - /// ``` - pub fn as_object_mut(&mut self) -> Option<&mut Map<String, Value>> { - match *self { - Value::Object(ref mut map) => Some(map), - _ => None, - } - } - - /// Returns true if the `Value` is an Array. Returns false otherwise. - /// - /// For any Value on which `is_array` returns true, `as_array` and - /// `as_array_mut` are guaranteed to return the vector representing the - /// array. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let obj = json!({ "a": ["an", "array"], "b": { "an": "object" } }); - /// - /// assert!(obj["a"].is_array()); - /// - /// // an object, not an array - /// assert!(!obj["b"].is_array()); - /// # } - /// ``` - pub fn is_array(&self) -> bool { - self.as_array().is_some() - } - - /// If the `Value` is an Array, returns the associated vector. Returns None - /// otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": ["an", "array"], "b": { "an": "object" } }); - /// - /// // The length of `["an", "array"]` is 2 elements. - /// assert_eq!(v["a"].as_array().unwrap().len(), 2); - /// - /// // The object `{"an": "object"}` is not an array. - /// assert_eq!(v["b"].as_array(), None); - /// # } - /// ``` - pub fn as_array(&self) -> Option<&Vec<Value>> { - match *self { - Value::Array(ref array) => Some(&*array), - _ => None, - } - } - - /// If the `Value` is an Array, returns the associated mutable vector. - /// Returns None otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let mut v = json!({ "a": ["an", "array"] }); - /// - /// v["a"].as_array_mut().unwrap().clear(); - /// assert_eq!(v, json!({ "a": [] })); - /// # } - /// ``` - pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> { - match *self { - Value::Array(ref mut list) => Some(list), - _ => None, - } - } - - /// Returns true if the `Value` is a String. Returns false otherwise. - /// - /// For any Value on which `is_string` returns true, `as_str` is guaranteed - /// to return the string slice. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": "some string", "b": false }); - /// - /// assert!(v["a"].is_string()); - /// - /// // The boolean `false` is not a string. - /// assert!(!v["b"].is_string()); - /// # } - /// ``` - pub fn is_string(&self) -> bool { - self.as_str().is_some() - } - - /// If the `Value` is a String, returns the associated str. Returns None - /// otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": "some string", "b": false }); - /// - /// assert_eq!(v["a"].as_str(), Some("some string")); - /// - /// // The boolean `false` is not a string. - /// assert_eq!(v["b"].as_str(), None); - /// - /// // JSON values are printed in JSON representation, so strings are in quotes. - /// // - /// // The value is: "some string" - /// println!("The value is: {}", v["a"]); - /// - /// // Rust strings are printed without quotes. - /// // - /// // The value is: some string - /// println!("The value is: {}", v["a"].as_str().unwrap()); - /// # } - /// ``` - pub fn as_str(&self) -> Option<&str> { - match *self { - Value::String(ref s) => Some(s), - _ => None, - } - } - - /// Returns true if the `Value` is a Number. Returns false otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": 1, "b": "2" }); - /// - /// assert!(v["a"].is_number()); - /// - /// // The string `"2"` is a string, not a number. - /// assert!(!v["b"].is_number()); - /// # } - /// ``` - pub fn is_number(&self) -> bool { - match *self { - Value::Number(_) => true, - _ => false, - } - } - - /// Returns true if the `Value` is an integer between `i64::MIN` and - /// `i64::MAX`. - /// - /// For any Value on which `is_i64` returns true, `as_i64` is guaranteed to - /// return the integer value. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # use std::i64; - /// # - /// # fn main() { - /// let big = i64::MAX as u64 + 10; - /// let v = json!({ "a": 64, "b": big, "c": 256.0 }); - /// - /// assert!(v["a"].is_i64()); - /// - /// // Greater than i64::MAX. - /// assert!(!v["b"].is_i64()); - /// - /// // Numbers with a decimal point are not considered integers. - /// assert!(!v["c"].is_i64()); - /// # } - /// ``` - pub fn is_i64(&self) -> bool { - match *self { - Value::Number(ref n) => n.is_i64(), - _ => false, - } - } - - /// Returns true if the `Value` is an integer between zero and `u64::MAX`. - /// - /// For any Value on which `is_u64` returns true, `as_u64` is guaranteed to - /// return the integer value. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": 64, "b": -64, "c": 256.0 }); - /// - /// assert!(v["a"].is_u64()); - /// - /// // Negative integer. - /// assert!(!v["b"].is_u64()); - /// - /// // Numbers with a decimal point are not considered integers. - /// assert!(!v["c"].is_u64()); - /// # } - /// ``` - pub fn is_u64(&self) -> bool { - match *self { - Value::Number(ref n) => n.is_u64(), - _ => false, - } - } - - /// Returns true if the `Value` is a number that can be represented by f64. - /// - /// For any Value on which `is_f64` returns true, `as_f64` is guaranteed to - /// return the floating point value. - /// - /// Currently this function returns true if and only if both `is_i64` and - /// `is_u64` return false but this is not a guarantee in the future. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": 256.0, "b": 64, "c": -64 }); - /// - /// assert!(v["a"].is_f64()); - /// - /// // Integers. - /// assert!(!v["b"].is_f64()); - /// assert!(!v["c"].is_f64()); - /// # } - /// ``` - pub fn is_f64(&self) -> bool { - match *self { - Value::Number(ref n) => n.is_f64(), - _ => false, - } - } - - /// If the `Value` is an integer, represent it as i64 if possible. Returns - /// None otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # use std::i64; - /// # - /// # fn main() { - /// let big = i64::MAX as u64 + 10; - /// let v = json!({ "a": 64, "b": big, "c": 256.0 }); - /// - /// assert_eq!(v["a"].as_i64(), Some(64)); - /// assert_eq!(v["b"].as_i64(), None); - /// assert_eq!(v["c"].as_i64(), None); - /// # } - /// ``` - pub fn as_i64(&self) -> Option<i64> { - match *self { - Value::Number(ref n) => n.as_i64(), - _ => None, - } - } - - /// If the `Value` is an integer, represent it as u64 if possible. Returns - /// None otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": 64, "b": -64, "c": 256.0 }); - /// - /// assert_eq!(v["a"].as_u64(), Some(64)); - /// assert_eq!(v["b"].as_u64(), None); - /// assert_eq!(v["c"].as_u64(), None); - /// # } - /// ``` - pub fn as_u64(&self) -> Option<u64> { - match *self { - Value::Number(ref n) => n.as_u64(), - _ => None, - } - } - - /// If the `Value` is a number, represent it as f64 if possible. Returns - /// None otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": 256.0, "b": 64, "c": -64 }); - /// - /// assert_eq!(v["a"].as_f64(), Some(256.0)); - /// assert_eq!(v["b"].as_f64(), Some(64.0)); - /// assert_eq!(v["c"].as_f64(), Some(-64.0)); - /// # } - /// ``` - pub fn as_f64(&self) -> Option<f64> { - match *self { - Value::Number(ref n) => n.as_f64(), - _ => None, - } - } - - /// Returns true if the `Value` is a Boolean. Returns false otherwise. - /// - /// For any Value on which `is_boolean` returns true, `as_bool` is - /// guaranteed to return the boolean value. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": false, "b": "false" }); - /// - /// assert!(v["a"].is_boolean()); - /// - /// // The string `"false"` is a string, not a boolean. - /// assert!(!v["b"].is_boolean()); - /// # } - /// ``` - pub fn is_boolean(&self) -> bool { - self.as_bool().is_some() - } - - /// If the `Value` is a Boolean, returns the associated bool. Returns None - /// otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": false, "b": "false" }); - /// - /// assert_eq!(v["a"].as_bool(), Some(false)); - /// - /// // The string `"false"` is a string, not a boolean. - /// assert_eq!(v["b"].as_bool(), None); - /// # } - /// ``` - pub fn as_bool(&self) -> Option<bool> { - match *self { - Value::Bool(b) => Some(b), - _ => None, - } - } - - /// Returns true if the `Value` is a Null. Returns false otherwise. - /// - /// For any Value on which `is_null` returns true, `as_null` is guaranteed - /// to return `Some(())`. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": null, "b": false }); - /// - /// assert!(v["a"].is_null()); - /// - /// // The boolean `false` is not null. - /// assert!(!v["b"].is_null()); - /// # } - /// ``` - pub fn is_null(&self) -> bool { - self.as_null().is_some() - } - - /// If the `Value` is a Null, returns (). Returns None otherwise. - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let v = json!({ "a": null, "b": false }); - /// - /// assert_eq!(v["a"].as_null(), Some(())); - /// - /// // The boolean `false` is not null. - /// assert_eq!(v["b"].as_null(), None); - /// # } - /// ``` - pub fn as_null(&self) -> Option<()> { - match *self { - Value::Null => Some(()), - _ => None, - } - } - - /// Looks up a value by a JSON Pointer. - /// - /// JSON Pointer defines a string syntax for identifying a specific value - /// within a JavaScript Object Notation (JSON) document. - /// - /// A Pointer is a Unicode string with the reference tokens separated by `/`. - /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The - /// addressed value is returned and if there is no such value `None` is - /// returned. - /// - /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901). - /// - /// # Examples - /// - /// ```rust - /// # #[macro_use] - /// # extern crate serde_json; - /// # - /// # fn main() { - /// let data = json!({ - /// "x": { - /// "y": ["z", "zz"] - /// } - /// }); - /// - /// assert_eq!(data.pointer("/x/y/1").unwrap(), &json!("zz")); - /// assert_eq!(data.pointer("/a/b/c"), None); - /// # } - /// ``` - pub fn pointer<'a>(&'a self, pointer: &str) -> Option<&'a Value> { - if pointer == "" { - return Some(self); - } - if !pointer.starts_with('/') { - return None; - } - let tokens = pointer - .split('/') - .skip(1) - .map(|x| x.replace("~1", "/").replace("~0", "~")); - let mut target = self; - - for token in tokens { - let target_opt = match *target { - Value::Object(ref map) => map.get(&token), - Value::Array(ref list) => parse_index(&token).and_then(|x| list.get(x)), - _ => return None, - }; - if let Some(t) = target_opt { - target = t; - } else { - return None; - } - } - Some(target) - } - - /// Looks up a value by a JSON Pointer and returns a mutable reference to - /// that value. - /// - /// JSON Pointer defines a string syntax for identifying a specific value - /// within a JavaScript Object Notation (JSON) document. - /// - /// A Pointer is a Unicode string with the reference tokens separated by `/`. - /// Inside tokens `/` is replaced by `~1` and `~` is replaced by `~0`. The - /// addressed value is returned and if there is no such value `None` is - /// returned. - /// - /// For more information read [RFC6901](https://tools.ietf.org/html/rfc6901). - /// - /// # Example of Use - /// - /// ```rust - /// extern crate serde_json; - /// - /// use serde_json::Value; - /// use std::mem; - /// - /// fn main() { - /// let s = r#"{"x": 1.0, "y": 2.0}"#; - /// let mut value: Value = serde_json::from_str(s).unwrap(); - /// - /// // Check value using read-only pointer - /// assert_eq!(value.pointer("/x"), Some(&1.0.into())); - /// // Change value with direct assignment - /// *value.pointer_mut("/x").unwrap() = 1.5.into(); - /// // Check that new value was written - /// assert_eq!(value.pointer("/x"), Some(&1.5.into())); - /// - /// // "Steal" ownership of a value. Can replace with any valid Value. - /// let old_x = value.pointer_mut("/x").map(|x| mem::replace(x, Value::Null)).unwrap(); - /// assert_eq!(old_x, 1.5); - /// assert_eq!(value.pointer("/x").unwrap(), &Value::Null); - /// } - /// ``` - pub fn pointer_mut<'a>(&'a mut self, pointer: &str) -> Option<&'a mut Value> { - if pointer == "" { - return Some(self); - } - if !pointer.starts_with('/') { - return None; - } - let tokens = pointer - .split('/') - .skip(1) - .map(|x| x.replace("~1", "/").replace("~0", "~")); - let mut target = self; - - for token in tokens { - // borrow checker gets confused about `target` being mutably borrowed too many times because of the loop - // this once-per-loop binding makes the scope clearer and circumvents the error - let target_once = target; - let target_opt = match *target_once { - Value::Object(ref mut map) => map.get_mut(&token), - Value::Array(ref mut list) => { - parse_index(&token).and_then(move |x| list.get_mut(x)) - } - _ => return None, - }; - if let Some(t) = target_opt { - target = t; - } else { - return None; - } - } - Some(target) - } -} - -/// The default value is `Value::Null`. -/// -/// This is useful for handling omitted `Value` fields when deserializing. -/// -/// # Examples -/// -/// ```rust -/// # #[macro_use] -/// # extern crate serde_derive; -/// # -/// # extern crate serde_json; -/// # -/// use serde_json::Value; -/// -/// #[derive(Deserialize)] -/// struct Settings { -/// level: i32, -/// #[serde(default)] -/// extras: Value, -/// } -/// -/// # fn try_main() -> Result<(), serde_json::Error> { -/// let data = r#" { "level": 42 } "#; -/// let s: Settings = serde_json::from_str(data)?; -/// -/// assert_eq!(s.level, 42); -/// assert_eq!(s.extras, Value::Null); -/// # -/// # Ok(()) -/// # } -/// # -/// # fn main() { -/// # try_main().unwrap() -/// # } -/// ``` -impl Default for Value { - fn default() -> Value { - Value::Null - } -} - -mod index; -mod partial_eq; -mod from; -mod ser; -mod de; - -/// Convert a `T` into `serde_json::Value` which is an enum that can represent -/// any valid JSON data. -/// -/// ```rust -/// extern crate serde; -/// -/// #[macro_use] -/// extern crate serde_derive; -/// -/// #[macro_use] -/// extern crate serde_json; -/// -/// use std::error::Error; -/// -/// #[derive(Serialize)] -/// struct User { -/// fingerprint: String, -/// location: String, -/// } -/// -/// fn compare_json_values() -> Result<(), Box<Error>> { -/// let u = User { -/// fingerprint: "0xF9BA143B95FF6D82".to_owned(), -/// location: "Menlo Park, CA".to_owned(), -/// }; -/// -/// // The type of `expected` is `serde_json::Value` -/// let expected = json!({ -/// "fingerprint": "0xF9BA143B95FF6D82", -/// "location": "Menlo Park, CA", -/// }); -/// -/// let v = serde_json::to_value(u).unwrap(); -/// assert_eq!(v, expected); -/// -/// Ok(()) -/// } -/// # -/// # fn main() { -/// # compare_json_values().unwrap(); -/// # } -/// ``` -/// -/// # Errors -/// -/// This conversion can fail if `T`'s implementation of `Serialize` decides to -/// fail, or if `T` contains a map with non-string keys. -/// -/// ```rust -/// extern crate serde_json; -/// -/// use std::collections::BTreeMap; -/// -/// fn main() { -/// // The keys in this map are vectors, not strings. -/// let mut map = BTreeMap::new(); -/// map.insert(vec![32, 64], "x86"); -/// -/// println!("{}", serde_json::to_value(map).unwrap_err()); -/// } -/// ``` -// Taking by value is more friendly to iterator adapters, option and result -// consumers, etc. See https://github.com/serde-rs/json/pull/149. -pub fn to_value<T>(value: T) -> Result<Value, Error> -where - T: Serialize, -{ - value.serialize(Serializer) -} - -/// Interpret a `serde_json::Value` as an instance of type `T`. -/// -/// This conversion can fail if the structure of the Value does not match the -/// structure expected by `T`, for example if `T` is a struct type but the Value -/// contains something other than a JSON map. It can also fail if the structure -/// is correct but `T`'s implementation of `Deserialize` decides that something -/// is wrong with the data, for example required struct fields are missing from -/// the JSON map or some number is too big to fit in the expected primitive -/// type. -/// -/// ```rust -/// #[macro_use] -/// extern crate serde_json; -/// -/// #[macro_use] -/// extern crate serde_derive; -/// -/// extern crate serde; -/// -/// #[derive(Deserialize, Debug)] -/// struct User { -/// fingerprint: String, -/// location: String, -/// } -/// -/// fn main() { -/// // The type of `j` is `serde_json::Value` -/// let j = json!({ -/// "fingerprint": "0xF9BA143B95FF6D82", -/// "location": "Menlo Park, CA" -/// }); -/// -/// let u: User = serde_json::from_value(j).unwrap(); -/// println!("{:#?}", u); -/// } -/// ``` -pub fn from_value<T>(value: Value) -> Result<T, Error> -where - T: DeserializeOwned, -{ - T::deserialize(value) -} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/value/partial_eq.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/value/partial_eq.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/value/partial_eq.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/value/partial_eq.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use super::Value; - -fn eq_i64(value: &Value, other: i64) -> bool { - value.as_i64().map_or(false, |i| i == other) -} - -fn eq_u64(value: &Value, other: u64) -> bool { - value.as_u64().map_or(false, |i| i == other) -} - -fn eq_f64(value: &Value, other: f64) -> bool { - value.as_f64().map_or(false, |i| i == other) -} - -fn eq_bool(value: &Value, other: bool) -> bool { - value.as_bool().map_or(false, |i| i == other) -} - -fn eq_str(value: &Value, other: &str) -> bool { - value.as_str().map_or(false, |i| i == other) -} - -impl PartialEq<str> for Value { - fn eq(&self, other: &str) -> bool { - eq_str(self, other) - } -} - -impl<'a> PartialEq<&'a str> for Value { - fn eq(&self, other: &&str) -> bool { - eq_str(self, *other) - } -} - -impl PartialEq<Value> for str { - fn eq(&self, other: &Value) -> bool { - eq_str(other, self) - } -} - -impl<'a> PartialEq<Value> for &'a str { - fn eq(&self, other: &Value) -> bool { - eq_str(other, *self) - } -} - -impl PartialEq<String> for Value { - fn eq(&self, other: &String) -> bool { - eq_str(self, other.as_str()) - } -} - - -impl PartialEq<Value> for String { - fn eq(&self, other: &Value) -> bool { - eq_str(other, self.as_str()) - } -} - -macro_rules! partialeq_numeric { - ($($eq:ident [$($ty:ty)*])*) => { - $($( - impl PartialEq<$ty> for Value { - fn eq(&self, other: &$ty) -> bool { - $eq(self, *other as _) - } - } - - impl PartialEq<Value> for $ty { - fn eq(&self, other: &Value) -> bool { - $eq(other, *self as _) - } - } - - impl<'a> PartialEq<$ty> for &'a Value { - fn eq(&self, other: &$ty) -> bool { - $eq(*self, *other as _) - } - } - - impl<'a> PartialEq<$ty> for &'a mut Value { - fn eq(&self, other: &$ty) -> bool { - $eq(*self, *other as _) - } - } - )*)* - } -} - -partialeq_numeric! { - eq_i64[i8 i16 i32 i64 isize] - eq_u64[u8 u16 u32 u64 usize] - eq_f64[f32 f64] - eq_bool[bool] -} diff -Nru cargo-0.25.0/vendor/serde_json-1.0.9/src/value/ser.rs cargo-0.26.0/vendor/serde_json-1.0.9/src/value/ser.rs --- cargo-0.25.0/vendor/serde_json-1.0.9/src/value/ser.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/serde_json-1.0.9/src/value/ser.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,419 +0,0 @@ -// Copyright 2017 Serde Developers -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use serde::{self, Serialize}; - -use error::{Error, ErrorCode}; -use map::Map; -use number::Number; -use value::{Value, to_value}; - -impl Serialize for Value { - #[inline] - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where - S: ::serde::Serializer, - { - match *self { - Value::Null => serializer.serialize_unit(), - Value::Bool(b) => serializer.serialize_bool(b), - Value::Number(ref n) => n.serialize(serializer), - Value::String(ref s) => serializer.serialize_str(s), - Value::Array(ref v) => v.serialize(serializer), - Value::Object(ref m) => { - use serde::ser::SerializeMap; - let mut map = try!(serializer.serialize_map(Some(m.len()))); - for (k, v) in m { - try!(map.serialize_key(k)); - try!(map.serialize_value(v)); - } - map.end() - } - } - } -} - -pub struct Serializer; - -impl serde::Serializer for Serializer { - type Ok = Value; - type Error = Error; - - type SerializeSeq = SerializeVec; - type SerializeTuple = SerializeVec; - type SerializeTupleStruct = SerializeVec; - type SerializeTupleVariant = SerializeTupleVariant; - type SerializeMap = SerializeMap; - type SerializeStruct = SerializeMap; - type SerializeStructVariant = SerializeStructVariant; - - #[inline] - fn serialize_bool(self, value: bool) -> Result<Value, Error> { - Ok(Value::Bool(value)) - } - - #[inline] - fn serialize_i8(self, value: i8) -> Result<Value, Error> { - self.serialize_i64(value as i64) - } - - #[inline] - fn serialize_i16(self, value: i16) -> Result<Value, Error> { - self.serialize_i64(value as i64) - } - - #[inline] - fn serialize_i32(self, value: i32) -> Result<Value, Error> { - self.serialize_i64(value as i64) - } - - fn serialize_i64(self, value: i64) -> Result<Value, Error> { - Ok(Value::Number(value.into())) - } - - #[inline] - fn serialize_u8(self, value: u8) -> Result<Value, Error> { - self.serialize_u64(value as u64) - } - - #[inline] - fn serialize_u16(self, value: u16) -> Result<Value, Error> { - self.serialize_u64(value as u64) - } - - #[inline] - fn serialize_u32(self, value: u32) -> Result<Value, Error> { - self.serialize_u64(value as u64) - } - - #[inline] - fn serialize_u64(self, value: u64) -> Result<Value, Error> { - Ok(Value::Number(value.into())) - } - - #[inline] - fn serialize_f32(self, value: f32) -> Result<Value, Error> { - self.serialize_f64(value as f64) - } - - #[inline] - fn serialize_f64(self, value: f64) -> Result<Value, Error> { - Ok(Number::from_f64(value).map_or(Value::Null, Value::Number)) - } - - #[inline] - fn serialize_char(self, value: char) -> Result<Value, Error> { - let mut s = String::new(); - s.push(value); - self.serialize_str(&s) - } - - #[inline] - fn serialize_str(self, value: &str) -> Result<Value, Error> { - Ok(Value::String(value.to_owned())) - } - - fn serialize_bytes(self, value: &[u8]) -> Result<Value, Error> { - let vec = value.iter().map(|&b| Value::Number(b.into())).collect(); - Ok(Value::Array(vec)) - } - - #[inline] - fn serialize_unit(self) -> Result<Value, Error> { - Ok(Value::Null) - } - - #[inline] - fn serialize_unit_struct(self, _name: &'static str) -> Result<Value, Error> { - self.serialize_unit() - } - - #[inline] - fn serialize_unit_variant( - self, - _name: &'static str, - _variant_index: u32, - variant: &'static str, - ) -> Result<Value, Error> { - self.serialize_str(variant) - } - - #[inline] - fn serialize_newtype_struct<T: ?Sized>( - self, - _name: &'static str, - value: &T, - ) -> Result<Value, Error> - where - T: Serialize, - { - value.serialize(self) - } - - fn serialize_newtype_variant<T: ?Sized>( - self, - _name: &'static str, - _variant_index: u32, - variant: &'static str, - value: &T, - ) -> Result<Value, Error> - where - T: Serialize, - { - let mut values = Map::new(); - values.insert(String::from(variant), try!(to_value(&value))); - Ok(Value::Object(values)) - } - - #[inline] - fn serialize_none(self) -> Result<Value, Error> { - self.serialize_unit() - } - - #[inline] - fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, Error> - where - T: Serialize, - { - value.serialize(self) - } - - fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Error> { - Ok(SerializeVec { vec: Vec::with_capacity(len.unwrap_or(0)) }) - } - - fn serialize_tuple(self, len: usize) -> Result<Self::SerializeTuple, Error> { - self.serialize_seq(Some(len)) - } - - fn serialize_tuple_struct( - self, - _name: &'static str, - len: usize, - ) -> Result<Self::SerializeTupleStruct, Error> { - self.serialize_seq(Some(len)) - } - - fn serialize_tuple_variant( - self, - _name: &'static str, - _variant_index: u32, - variant: &'static str, - len: usize, - ) -> Result<Self::SerializeTupleVariant, Error> { - Ok( - SerializeTupleVariant { - name: String::from(variant), - vec: Vec::with_capacity(len), - }, - ) - } - - fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Error> { - Ok( - SerializeMap { - map: Map::new(), - next_key: None, - }, - ) - } - - fn serialize_struct( - self, - _name: &'static str, - len: usize, - ) -> Result<Self::SerializeStruct, Error> { - self.serialize_map(Some(len)) - } - - fn serialize_struct_variant( - self, - _name: &'static str, - _variant_index: u32, - variant: &'static str, - _len: usize, - ) -> Result<Self::SerializeStructVariant, Error> { - Ok( - SerializeStructVariant { - name: String::from(variant), - map: Map::new(), - }, - ) - } -} - -#[doc(hidden)] -pub struct SerializeVec { - vec: Vec<Value>, -} - -#[doc(hidden)] -pub struct SerializeTupleVariant { - name: String, - vec: Vec<Value>, -} - -#[doc(hidden)] -pub struct SerializeMap { - map: Map<String, Value>, - next_key: Option<String>, -} - -#[doc(hidden)] -pub struct SerializeStructVariant { - name: String, - map: Map<String, Value>, -} - -impl serde::ser::SerializeSeq for SerializeVec { - type Ok = Value; - type Error = Error; - - fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> - where - T: Serialize, - { - self.vec.push(try!(to_value(&value))); - Ok(()) - } - - fn end(self) -> Result<Value, Error> { - Ok(Value::Array(self.vec)) - } -} - -impl serde::ser::SerializeTuple for SerializeVec { - type Ok = Value; - type Error = Error; - - fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> - where - T: Serialize, - { - serde::ser::SerializeSeq::serialize_element(self, value) - } - - fn end(self) -> Result<Value, Error> { - serde::ser::SerializeSeq::end(self) - } -} - -impl serde::ser::SerializeTupleStruct for SerializeVec { - type Ok = Value; - type Error = Error; - - fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> - where - T: Serialize, - { - serde::ser::SerializeSeq::serialize_element(self, value) - } - - fn end(self) -> Result<Value, Error> { - serde::ser::SerializeSeq::end(self) - } -} - -impl serde::ser::SerializeTupleVariant for SerializeTupleVariant { - type Ok = Value; - type Error = Error; - - fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> - where - T: Serialize, - { - self.vec.push(try!(to_value(&value))); - Ok(()) - } - - fn end(self) -> Result<Value, Error> { - let mut object = Map::new(); - - object.insert(self.name, Value::Array(self.vec)); - - Ok(Value::Object(object)) - } -} - -impl serde::ser::SerializeMap for SerializeMap { - type Ok = Value; - type Error = Error; - - fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), Error> - where - T: Serialize, - { - match try!(to_value(&key)) { - Value::String(s) => self.next_key = Some(s), - Value::Number(n) => { - if n.is_u64() || n.is_i64() { - self.next_key = Some(n.to_string()) - } else { - return Err(Error::syntax(ErrorCode::KeyMustBeAString, 0, 0)); - } - } - _ => return Err(Error::syntax(ErrorCode::KeyMustBeAString, 0, 0)), - }; - Ok(()) - } - - fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> - where - T: Serialize, - { - let key = self.next_key.take(); - // Panic because this indicates a bug in the program rather than an - // expected failure. - let key = key.expect("serialize_value called before serialize_key"); - self.map.insert(key, try!(to_value(&value))); - Ok(()) - } - - fn end(self) -> Result<Value, Error> { - Ok(Value::Object(self.map)) - } -} - -impl serde::ser::SerializeStruct for SerializeMap { - type Ok = Value; - type Error = Error; - - fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> - where - T: Serialize, - { - try!(serde::ser::SerializeMap::serialize_key(self, key)); - serde::ser::SerializeMap::serialize_value(self, value) - } - - fn end(self) -> Result<Value, Error> { - serde::ser::SerializeMap::end(self) - } -} - -impl serde::ser::SerializeStructVariant for SerializeStructVariant { - type Ok = Value; - type Error = Error; - - fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), Error> - where - T: Serialize, - { - self.map - .insert(String::from(key), try!(to_value(&value))); - Ok(()) - } - - fn end(self) -> Result<Value, Error> { - let mut object = Map::new(); - - object.insert(self.name, Value::Object(self.map)); - - Ok(Value::Object(object)) - } -} diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.3/.cargo-checksum.json cargo-0.26.0/vendor/shell-escape-0.1.3/.cargo-checksum.json --- cargo-0.25.0/vendor/shell-escape-0.1.3/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.3/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"dd5cc96481d54583947bfe88bf30c23d53f883c6cd0145368b69989d97b84ef8"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.3/Cargo.toml cargo-0.26.0/vendor/shell-escape-0.1.3/Cargo.toml --- cargo-0.25.0/vendor/shell-escape-0.1.3/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.3/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ -[package] -name = "shell-escape" -version = "0.1.3" -authors = ["Steven Fackler <sfackler@gmail.com>"] -license = "MIT/Apache-2.0" -repository = "https://github.com/sfackler/shell-escape" -documentation = "https://docs.rs/shell-escape/0.1.3/shell_escape" -description = "Escape characters that may have a special meaning in a shell" - -[dependencies] diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.3/LICENSE-APACHE cargo-0.26.0/vendor/shell-escape-0.1.3/LICENSE-APACHE --- cargo-0.25.0/vendor/shell-escape-0.1.3/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.3/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.3/LICENSE-MIT cargo-0.26.0/vendor/shell-escape-0.1.3/LICENSE-MIT --- cargo-0.25.0/vendor/shell-escape-0.1.3/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.3/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.3/README.md cargo-0.26.0/vendor/shell-escape-0.1.3/README.md --- cargo-0.25.0/vendor/shell-escape-0.1.3/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.3/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -# shell-escape - -[![Build Status](https://travis-ci.org/sfackler/shell-escape.svg?branch=master)](https://travis-ci.org/sfackler/shell-escape) - -[Documentation](https://docs.rs/shell-escape) - -Escape characters that may have a special meaning in a shell. - -## 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. diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.3/src/lib.rs cargo-0.26.0/vendor/shell-escape-0.1.3/src/lib.rs --- cargo-0.25.0/vendor/shell-escape-0.1.3/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.3/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,132 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -//! Escape characters that may have special meaning in a shell. -#![doc(html_root_url="https://docs.rs/shell-escape/0.1.3")] - -use std::borrow::Cow; -use std::env; - -/// Escape characters that may have special meaning in a shell. -pub fn escape(s: Cow<str>) -> Cow<str> { - if cfg!(unix) || env::var("MSYSTEM").is_ok() { - unix::escape(s) - } else { - windows::escape(s) - } -} - -/// Windows-specific escaping. -pub mod windows { - use std::borrow::Cow; - use std::iter::repeat; - - /// Escape for the windows cmd.exe shell. - /// - /// See [here][msdn] for more information. - /// - /// [msdn]: http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx - pub fn escape(s: Cow<str>) -> Cow<str> { - let mut needs_escape = false; - for ch in s.chars() { - match ch { - '"' | '\t' | '\n' | ' ' => needs_escape = true, - _ => {} - } - } - if !needs_escape { - return s - } - let mut es = String::with_capacity(s.len()); - es.push('"'); - let mut chars = s.chars().peekable(); - loop { - let mut nslashes = 0; - while let Some(&'\\') = chars.peek() { - chars.next(); - nslashes += 1; - } - - match chars.next() { - Some('"') => { - es.extend(repeat('\\').take(nslashes * 2 + 1)); - es.push('"'); - } - Some(c) => { - es.extend(repeat('\\').take(nslashes)); - es.push(c); - } - None => { - es.extend(repeat('\\').take(nslashes * 2)); - break; - } - } - - } - es.push('"'); - es.into() - } - - #[test] - fn test_escape() { - assert_eq!(escape("--aaa=bbb-ccc".into()), "--aaa=bbb-ccc"); - assert_eq!(escape("linker=gcc -L/foo -Wl,bar".into()), - r#""linker=gcc -L/foo -Wl,bar""#); - assert_eq!(escape(r#"--features="default""#.into()), - r#""--features=\"default\"""#); - assert_eq!(escape(r#"\path\to\my documents\"#.into()), - r#""\path\to\my documents\\""#); - } -} - -/// Unix-specific escaping. -pub mod unix { - use std::borrow::Cow; - - fn non_whitelisted(ch: char) -> bool { - match ch { - 'a'...'z' | 'A'...'Z' | '0'...'9' | '-' | '_' | '=' | '/' | ',' | '.' => false, - _ => true, - } - } - - /// Escape characters that may have special meaning in a shell, including spaces. - pub fn escape(s: Cow<str>) -> Cow<str> { - if !s.contains(non_whitelisted) { - return s; - } - - let mut es = String::with_capacity(s.len() + 2); - es.push('\''); - for ch in s.chars() { - match ch { - '\'' | '!' => { - es.push_str("'\\"); - es.push(ch); - es.push('\''); - } - _ => es.push(ch), - } - } - es.push('\''); - es.into() - } - - #[test] - fn test_escape() { - assert_eq!( - escape("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_=/,.".into()), - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_=/,."); - assert_eq!(escape("--aaa=bbb-ccc".into()), "--aaa=bbb-ccc"); - assert_eq!(escape("linker=gcc -L/foo -Wl,bar".into()), r#"'linker=gcc -L/foo -Wl,bar'"#); - assert_eq!(escape(r#"--features="default""#.into()), r#"'--features="default"'"#); - assert_eq!(escape(r#"'!\$`\\\n "#.into()), r#"''\'''\!'\$`\\\n '"#); - } -} - diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.3/.travis.yml cargo-0.26.0/vendor/shell-escape-0.1.3/.travis.yml --- cargo-0.25.0/vendor/shell-escape-0.1.3/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.3/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -language: rust -cache: cargo -rust: -- nightly -- 1.13.0 -script: -- cargo test diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.4/.cargo-checksum.json cargo-0.26.0/vendor/shell-escape-0.1.4/.cargo-checksum.json --- cargo-0.25.0/vendor/shell-escape-0.1.4/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.4/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"170a13e64f2a51b77a45702ba77287f5c6829375b04a69cf2222acd17d0cfab9"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.4/Cargo.toml cargo-0.26.0/vendor/shell-escape-0.1.4/Cargo.toml --- cargo-0.25.0/vendor/shell-escape-0.1.4/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.4/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,21 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "shell-escape" +version = "0.1.4" +authors = ["Steven Fackler <sfackler@gmail.com>"] +description = "Escape characters that may have a special meaning in a shell" +license = "MIT/Apache-2.0" +repository = "https://github.com/sfackler/shell-escape" + +[dependencies] diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.4/LICENSE-APACHE cargo-0.26.0/vendor/shell-escape-0.1.4/LICENSE-APACHE --- cargo-0.25.0/vendor/shell-escape-0.1.4/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.4/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.4/LICENSE-MIT cargo-0.26.0/vendor/shell-escape-0.1.4/LICENSE-MIT --- cargo-0.25.0/vendor/shell-escape-0.1.4/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.4/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.4/README.md cargo-0.26.0/vendor/shell-escape-0.1.4/README.md --- cargo-0.25.0/vendor/shell-escape-0.1.4/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.4/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,23 @@ +# shell-escape + +[![Build Status](https://travis-ci.org/sfackler/shell-escape.svg?branch=master)](https://travis-ci.org/sfackler/shell-escape) + +[Documentation](https://docs.rs/shell-escape) + +Escape characters that may have a special meaning in a shell. + +## 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. diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.4/src/lib.rs cargo-0.26.0/vendor/shell-escape-0.1.4/src/lib.rs --- cargo-0.25.0/vendor/shell-escape-0.1.4/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.4/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,133 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +//! Escape characters that may have special meaning in a shell. +#![doc(html_root_url="https://docs.rs/shell-escape/0.1")] + +use std::borrow::Cow; +use std::env; + +/// Escape characters that may have special meaning in a shell. +pub fn escape(s: Cow<str>) -> Cow<str> { + if cfg!(unix) || env::var("MSYSTEM").is_ok() { + unix::escape(s) + } else { + windows::escape(s) + } +} + +/// Windows-specific escaping. +pub mod windows { + use std::borrow::Cow; + use std::iter::repeat; + + /// Escape for the windows cmd.exe shell. + /// + /// See [here][msdn] for more information. + /// + /// [msdn]: http://blogs.msdn.com/b/twistylittlepassagesallalike/archive/2011/04/23/everyone-quotes-arguments-the-wrong-way.aspx + pub fn escape(s: Cow<str>) -> Cow<str> { + let mut needs_escape = false; + for ch in s.chars() { + match ch { + '"' | '\t' | '\n' | ' ' => needs_escape = true, + _ => {} + } + } + if !needs_escape { + return s + } + let mut es = String::with_capacity(s.len()); + es.push('"'); + let mut chars = s.chars().peekable(); + loop { + let mut nslashes = 0; + while let Some(&'\\') = chars.peek() { + chars.next(); + nslashes += 1; + } + + match chars.next() { + Some('"') => { + es.extend(repeat('\\').take(nslashes * 2 + 1)); + es.push('"'); + } + Some(c) => { + es.extend(repeat('\\').take(nslashes)); + es.push(c); + } + None => { + es.extend(repeat('\\').take(nslashes * 2)); + break; + } + } + + } + es.push('"'); + es.into() + } + + #[test] + fn test_escape() { + assert_eq!(escape("--aaa=bbb-ccc".into()), "--aaa=bbb-ccc"); + assert_eq!(escape("linker=gcc -L/foo -Wl,bar".into()), + r#""linker=gcc -L/foo -Wl,bar""#); + assert_eq!(escape(r#"--features="default""#.into()), + r#""--features=\"default\"""#); + assert_eq!(escape(r#"\path\to\my documents\"#.into()), + r#""\path\to\my documents\\""#); + } +} + +/// Unix-specific escaping. +pub mod unix { + use std::borrow::Cow; + + fn non_whitelisted(ch: char) -> bool { + match ch { + 'a'...'z' | 'A'...'Z' | '0'...'9' | '-' | '_' | '=' | '/' | ',' | '.' | '+' => false, + _ => true, + } + } + + /// Escape characters that may have special meaning in a shell, including spaces. + pub fn escape(s: Cow<str>) -> Cow<str> { + if !s.contains(non_whitelisted) { + return s; + } + + let mut es = String::with_capacity(s.len() + 2); + es.push('\''); + for ch in s.chars() { + match ch { + '\'' | '!' => { + es.push_str("'\\"); + es.push(ch); + es.push('\''); + } + _ => es.push(ch), + } + } + es.push('\''); + es.into() + } + + #[test] + fn test_escape() { + assert_eq!( + escape("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_=/,.+".into()), + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_=/,.+" + ); + assert_eq!(escape("--aaa=bbb-ccc".into()), "--aaa=bbb-ccc"); + assert_eq!(escape("linker=gcc -L/foo -Wl,bar".into()), r#"'linker=gcc -L/foo -Wl,bar'"#); + assert_eq!(escape(r#"--features="default""#.into()), r#"'--features="default"'"#); + assert_eq!(escape(r#"'!\$`\\\n "#.into()), r#"''\'''\!'\$`\\\n '"#); + } +} + diff -Nru cargo-0.25.0/vendor/shell-escape-0.1.4/.travis.yml cargo-0.26.0/vendor/shell-escape-0.1.4/.travis.yml --- cargo-0.25.0/vendor/shell-escape-0.1.4/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/shell-escape-0.1.4/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,7 @@ +language: rust +cache: cargo +rust: +- nightly +- 1.13.0 +script: +- cargo test diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/.appveyor.yml cargo-0.26.0/vendor/socket2-0.3.1/.appveyor.yml --- cargo-0.25.0/vendor/socket2-0.3.1/.appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/.appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -environment: - matrix: - - TARGET: x86_64-pc-windows-msvc -install: - - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe - - rustup-init.exe -y --default-host x86_64-pc-windows-msvc - - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - - if NOT "%TARGET%" == "x86_64-pc-windows-msvc" rustup target add %TARGET% - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test - - cargo test --features reuseport diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/.cargo-checksum.json cargo-0.26.0/vendor/socket2-0.3.1/.cargo-checksum.json --- cargo-0.25.0/vendor/socket2-0.3.1/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"a76b792959eba82f021c9028c8ecb6396f085268d6d46af2ed96a829cc758d7c"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/Cargo.toml cargo-0.26.0/vendor/socket2-0.3.1/Cargo.toml --- cargo-0.25.0/vendor/socket2-0.3.1/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "socket2" -version = "0.3.1" -authors = ["Alex Crichton <alex@alexcrichton.com>"] -description = "Utilities for handling networking sockets with a maximal amount of configuration\npossible intended.\n" -homepage = "https://github.com/alexcrichton/socket2-rs" -readme = "README.md" -license = "MIT/Apache-2.0" -repository = "https://github.com/alexcrichton/socket2-rs" -[package.metadata.docs.rs] -all-features = true -[dev-dependencies.tempdir] -version = "0.3" - -[features] -pair = [] -reuseport = [] -unix = [] -[target."cfg(unix)".dependencies.cfg-if] -version = "0.1" - -[target."cfg(unix)".dependencies.libc] -version = "0.2.14" -[target."cfg(windows)".dependencies.winapi] -version = "0.3.3" -features = ["handleapi", "ws2def", "ws2ipdef", "ws2tcpip", "minwindef"] diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/LICENSE-APACHE cargo-0.26.0/vendor/socket2-0.3.1/LICENSE-APACHE --- cargo-0.25.0/vendor/socket2-0.3.1/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/LICENSE-MIT cargo-0.26.0/vendor/socket2-0.3.1/LICENSE-MIT --- cargo-0.25.0/vendor/socket2-0.3.1/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 Alex Crichton - -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. diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/README.md cargo-0.26.0/vendor/socket2-0.3.1/README.md --- cargo-0.25.0/vendor/socket2-0.3.1/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -# socket2-rs - -[![Build Status](https://travis-ci.org/alexcrichton/socket2-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/socket2-rs) -[![Build status](https://ci.appveyor.com/api/projects/status/hovebj1gr4bgm3d9?svg=true)](https://ci.appveyor.com/project/alexcrichton/socket2-rs) - -[Documentation](https://docs.rs/socket2) - -# License - -This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/src/lib.rs cargo-0.26.0/vendor/socket2-0.3.1/src/lib.rs --- cargo-0.25.0/vendor/socket2-0.3.1/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,132 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Utilities for handling sockets -//! -//! This crate is sort of an evolution of the `net2` crate after seeing the -//! issues on it over time. The intention of this crate is to provide as direct -//! as possible access to the system's functionality for sockets as possible. No -//! extra fluff (e.g. multiple syscalls or builders) provided in this crate. As -//! a result using this crate can be a little wordy, but it should give you -//! maximal flexibility over configuration of sockets. -//! -//! # Examples -//! -//! ```no_run -//! use std::net::SocketAddr; -//! use socket2::{Socket, Domain, Type}; -//! -//! // create a TCP listener bound to two addresses -//! let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); -//! -//! socket.bind(&"127.0.0.1:12345".parse::<SocketAddr>().unwrap().into()).unwrap(); -//! socket.bind(&"127.0.0.1:12346".parse::<SocketAddr>().unwrap().into()).unwrap(); -//! socket.listen(128).unwrap(); -//! -//! let listener = socket.into_tcp_listener(); -//! // ... -//! ``` - -#![doc(html_root_url = "https://docs.rs/socket2/0.3")] -#![deny(missing_docs)] - -#[cfg(unix)] extern crate libc; -#[cfg(unix)] #[macro_use] extern crate cfg_if; - -#[cfg(windows)] extern crate winapi; - -#[cfg(test)] extern crate tempdir; - -use utils::NetInt; - -#[cfg(unix)] use libc::{sockaddr_storage, socklen_t}; -#[cfg(windows)] use winapi::shared::ws2def::SOCKADDR_STORAGE as sockaddr_storage; -#[cfg(windows)] use winapi::um::ws2tcpip::socklen_t; - -mod sockaddr; -mod socket; -mod utils; - -#[cfg(unix)] #[path = "sys/unix/mod.rs"] mod sys; -#[cfg(windows)] #[path = "sys/windows.rs"] mod sys; - -/// Newtype, owned, wrapper around a system socket. -/// -/// This type simply wraps an instance of a file descriptor (`c_int`) on Unix -/// and an instance of `SOCKET` on Windows. This is the main type exported by -/// this crate and is intended to mirror the raw semantics of sockets on -/// platforms as closely as possible. Almost all methods correspond to -/// precisely one libc or OS API call which is essentially just a "Rustic -/// translation" of what's below. -/// -/// # Examples -/// -/// ```no_run -/// use std::net::SocketAddr; -/// use socket2::{Socket, Domain, Type, SockAddr}; -/// -/// // create a TCP listener bound to two addresses -/// let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); -/// -/// socket.bind(&"127.0.0.1:12345".parse::<SocketAddr>().unwrap().into()).unwrap(); -/// socket.bind(&"127.0.0.1:12346".parse::<SocketAddr>().unwrap().into()).unwrap(); -/// socket.listen(128).unwrap(); -/// -/// let listener = socket.into_tcp_listener(); -/// // ... -/// ``` -pub struct Socket { - inner: sys::Socket, -} - -/// The address of a socket. -/// -/// `SockAddr`s may be constructed directly to and from the standard library -/// `SocketAddr`, `SocketAddrV4`, and `SocketAddrV6` types. -pub struct SockAddr { - storage: sockaddr_storage, - len: socklen_t, -} - -/// Specification of the communication domain for a socket. -/// -/// This is a newtype wrapper around an integer which provides a nicer API in -/// addition to an injection point for documentation. Convenience constructors -/// such as `Domain::ipv4`, `Domain::ipv6`, etc, are provided to avoid reaching -/// into libc for various constants. -/// -/// This type is freely interconvertible with the `i32` type, however, if a raw -/// value needs to be provided. -#[derive(Copy, Clone)] -pub struct Domain(i32); - -/// Specification of communication semantics on a socket. -/// -/// This is a newtype wrapper around an integer which provides a nicer API in -/// addition to an injection point for documentation. Convenience constructors -/// such as `Type::stream`, `Type::dgram`, etc, are provided to avoid reaching -/// into libc for various constants. -/// -/// This type is freely interconvertible with the `i32` type, however, if a raw -/// value needs to be provided. -#[derive(Copy, Clone)] -pub struct Type(i32); - -/// Protocol specification used for creating sockets via `Socket::new`. -/// -/// This is a newtype wrapper around an integer which provides a nicer API in -/// addition to an injection point for documentation. -/// -/// This type is freely interconvertible with the `i32` type, however, if a raw -/// value needs to be provided. -#[derive(Copy, Clone)] -pub struct Protocol(i32); - -fn hton<I: NetInt>(i: I) -> I { i.to_be() } diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/src/sockaddr.rs cargo-0.26.0/vendor/socket2-0.3.1/src/sockaddr.rs --- cargo-0.25.0/vendor/socket2-0.3.1/src/sockaddr.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/src/sockaddr.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,200 +0,0 @@ -use std::fmt; -use std::mem; -use std::net::{SocketAddrV4, SocketAddrV6, SocketAddr}; -use std::ptr; - -#[cfg(unix)] -use libc::{sockaddr, sockaddr_storage, sockaddr_in, sockaddr_in6, sa_family_t, socklen_t, AF_INET, - AF_INET6}; -#[cfg(windows)] -use winapi::shared::ws2def::{ - SOCKADDR as sockaddr, SOCKADDR_STORAGE as sockaddr_storage, - SOCKADDR_IN as sockaddr_in, - ADDRESS_FAMILY as sa_family_t, AF_INET, AF_INET6 -}; -#[cfg(windows)] -use winapi::um::ws2tcpip::socklen_t; -#[cfg(windows)] -use winapi::shared::ws2ipdef::{SOCKADDR_IN6_LH as sockaddr_in6}; - -use SockAddr; - -impl fmt::Debug for SockAddr { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - let mut builder = fmt.debug_struct("SockAddr"); - builder.field("family", &self.family()); - if let Some(addr) = self.as_inet() { - builder.field("inet", &addr); - } else if let Some(addr) = self.as_inet6() { - builder.field("inet6", &addr); - } - builder.finish() - } -} - -impl SockAddr { - /// Constructs a `SockAddr` from its raw components. - pub unsafe fn from_raw_parts(addr: *const sockaddr, len: socklen_t) -> SockAddr { - let mut storage = mem::uninitialized::<sockaddr_storage>(); - ptr::copy_nonoverlapping(addr as *const _ as *const u8, - &mut storage as *mut _ as *mut u8, - len as usize); - - SockAddr { - storage: storage, - len: len, - } - } - - /// Constructs a `SockAddr` with the family `AF_UNIX` and the provided path. - /// - /// This function is only available on Unix when the `unix` feature is - /// enabled. - /// - /// # Failure - /// - /// Returns an error if the path is longer than `SUN_LEN`. - #[cfg(all(unix, feature = "unix"))] - pub fn unix<P>(path: P) -> ::std::io::Result<SockAddr> - where P: AsRef<::std::path::Path> - { - use std::cmp::Ordering; - use std::io; - use std::os::unix::ffi::OsStrExt; - use libc::{sockaddr_un, AF_UNIX, c_char}; - - unsafe { - let mut addr = mem::zeroed::<sockaddr_un>(); - addr.sun_family = AF_UNIX as sa_family_t; - - let bytes = path.as_ref().as_os_str().as_bytes(); - - match (bytes.get(0), bytes.len().cmp(&addr.sun_path.len())) { - // Abstract paths don't need a null terminator - (Some(&0), Ordering::Greater) => { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "path must be no longer than SUN_LEN")); - } - (Some(&0), _) => {} - (_, Ordering::Greater) | (_, Ordering::Equal) => { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "path must be shorter than SUN_LEN")); - } - _ => {} - } - - for (dst, src) in addr.sun_path.iter_mut().zip(bytes) { - *dst = *src as c_char; - } - // null byte for pathname is already there since we zeroed up front - - let base = &addr as *const _ as usize; - let path = &addr.sun_path as *const _ as usize; - let sun_path_offset = path - base; - - let mut len = sun_path_offset + bytes.len(); - match bytes.get(0) { - Some(&0) | None => {} - Some(_) => len += 1, - } - Ok(SockAddr::from_raw_parts(&addr as *const _ as *const _, len as socklen_t)) - } - } - - unsafe fn as_<T>(&self, family: sa_family_t) -> Option<T> { - if self.storage.ss_family != family { - return None; - } - - Some(mem::transmute_copy(&self.storage)) - } - - /// Returns this address as a `SocketAddrV4` if it is in the `AF_INET` - /// family. - pub fn as_inet(&self) -> Option<SocketAddrV4> { - unsafe { self.as_(AF_INET as sa_family_t) } - } - - /// Returns this address as a `SocketAddrV4` if it is in the `AF_INET6` - /// family. - pub fn as_inet6(&self) -> Option<SocketAddrV6> { - unsafe { self.as_(AF_INET6 as sa_family_t) } - } - - /// Returns this address's family. - pub fn family(&self) -> sa_family_t { - self.storage.ss_family - } - - /// Returns the size of this address in bytes. - pub fn len(&self) -> socklen_t { - self.len - } - - /// Returns a raw pointer to the address. - pub fn as_ptr(&self) -> *const sockaddr { - &self.storage as *const _ as *const _ - } -} - -// SocketAddrV4 and SocketAddrV6 are just wrappers around sockaddr_in and sockaddr_in6 - -// check to make sure that the sizes at least match up -fn _size_checks(v4: SocketAddrV4, v6: SocketAddrV6) { - unsafe { - mem::transmute::<SocketAddrV4, sockaddr_in>(v4); - mem::transmute::<SocketAddrV6, sockaddr_in6>(v6); - } -} - -impl From<SocketAddrV4> for SockAddr { - fn from(addr: SocketAddrV4) -> SockAddr { - unsafe { - SockAddr::from_raw_parts(&addr as *const _ as *const _, - mem::size_of::<SocketAddrV4>() as socklen_t) - } - } -} - -impl From<SocketAddrV6> for SockAddr { - fn from(addr: SocketAddrV6) -> SockAddr { - unsafe { - SockAddr::from_raw_parts(&addr as *const _ as *const _, - mem::size_of::<SocketAddrV6>() as socklen_t) - } - } -} - -impl From<SocketAddr> for SockAddr { - fn from(addr: SocketAddr) -> SockAddr { - match addr { - SocketAddr::V4(addr) => addr.into(), - SocketAddr::V6(addr) => addr.into(), - } - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn inet() { - let raw = "127.0.0.1:80".parse::<SocketAddrV4>().unwrap(); - let addr = SockAddr::from(raw); - assert!(addr.as_inet6().is_none()); - let addr = addr.as_inet().unwrap(); - assert_eq!(raw, addr); - } - - #[test] - fn inet6() { - let raw = "[2001:db8::ff00:42:8329]:80" - .parse::<SocketAddrV6>() - .unwrap(); - let addr = SockAddr::from(raw); - assert!(addr.as_inet().is_none()); - let addr = addr.as_inet6().unwrap(); - assert_eq!(raw, addr); - } -} diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/src/socket.rs cargo-0.26.0/vendor/socket2-0.3.1/src/socket.rs --- cargo-0.25.0/vendor/socket2-0.3.1/src/socket.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/src/socket.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,892 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::fmt; -use std::io::{self, Read, Write}; -use std::net::{self, Ipv4Addr, Ipv6Addr, Shutdown}; -use std::time::Duration; -#[cfg(all(unix, feature = "unix"))] -use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream}; - -#[cfg(unix)] -use libc as c; -#[cfg(windows)] -use winapi::shared::ws2def as c; - -use sys; -use {Socket, Protocol, Domain, Type, SockAddr}; - -impl Socket { - /// Creates a new socket ready to be configured. - /// - /// This function corresponds to `socket(2)` and simply creates a new - /// socket, no other configuration is done and further functions must be - /// invoked to configure this socket. - pub fn new(domain: Domain, - type_: Type, - protocol: Option<Protocol>) -> io::Result<Socket> { - let protocol = protocol.map(|p| p.0).unwrap_or(0); - Ok(Socket { - inner: sys::Socket::new(domain.0, type_.0, protocol)?, - }) - } - - /// Creates a pair of sockets which are connected to each other. - /// - /// This function corresponds to `socketpair(2)`. - /// - /// This function is only available on Unix when the `pair` feature is - /// enabled. - #[cfg(all(unix, feature = "pair"))] - pub fn pair(domain: Domain, - type_: Type, - protocol: Option<Protocol>) -> io::Result<(Socket, Socket)> { - let protocol = protocol.map(|p| p.0).unwrap_or(0); - let sockets = sys::Socket::pair(domain.0, type_.0, protocol)?; - Ok((Socket { inner: sockets.0 }, Socket { inner: sockets.1 })) - } - - /// Consumes this `Socket`, converting it to a `TcpStream`. - pub fn into_tcp_stream(self) -> net::TcpStream { - self.into() - } - - /// Consumes this `Socket`, converting it to a `TcpListener`. - pub fn into_tcp_listener(self) -> net::TcpListener { - self.into() - } - - /// Consumes this `Socket`, converting it to a `UdpSocket`. - pub fn into_udp_socket(self) -> net::UdpSocket { - self.into() - } - - /// Consumes this `Socket`, converting it into a `UnixStream`. - /// - /// This function is only available on Unix when the `unix` feature is - /// enabled. - #[cfg(all(unix, feature = "unix"))] - pub fn into_unix_stream(self) -> UnixStream { - self.into() - } - - /// Consumes this `Socket`, converting it into a `UnixListener`. - /// - /// This function is only available on Unix when the `unix` feature is - /// enabled. - #[cfg(all(unix, feature = "unix"))] - pub fn into_unix_listener(self) -> UnixListener { - self.into() - } - - /// Consumes this `Socket`, converting it into a `UnixDatagram`. - /// - /// This function is only available on Unix when the `unix` feature is - /// enabled. - #[cfg(all(unix, feature = "unix"))] - pub fn into_unix_datagram(self) -> UnixDatagram { - self.into() - } - - /// Initiate a connection on this socket to the specified address. - /// - /// This function directly corresponds to the connect(2) function on Windows - /// and Unix. - /// - /// An error will be returned if `listen` or `connect` has already been - /// called on this builder. - pub fn connect(&self, addr: &SockAddr) -> io::Result<()> { - self.inner.connect(addr) - } - - /// Initiate a connection on this socket to the specified address, only - /// only waiting for a certain period of time for the connection to be - /// established. - /// - /// Unlike many other methods on `Socket`, this does *not* correspond to a - /// single C function. It sets the socket to nonblocking mode, connects via - /// connect(2), and then waits for the connection to complete with poll(2) - /// on Unix and select on Windows. When the connection is complete, the - /// socket is set back to blocking mode. On Unix, this will loop over - /// `EINTR` errors. - /// - /// # Warnings - /// - /// The nonblocking state of the socket is overridden by this function - - /// it will be returned in blocking mode on success, and in an indeterminate - /// state on failure. - /// - /// If the connection request times out, it may still be processing in the - /// background - a second call to `connect` or `connect_timeout` may fail. - pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> { - self.inner.connect_timeout(addr, timeout) - } - - /// Binds this socket to the specified address. - /// - /// This function directly corresponds to the bind(2) function on Windows - /// and Unix. - pub fn bind(&self, addr: &SockAddr) -> io::Result<()> { - self.inner.bind(addr) - } - - /// Mark a socket as ready to accept incoming connection requests using - /// accept() - /// - /// This function directly corresponds to the listen(2) function on Windows - /// and Unix. - /// - /// An error will be returned if `listen` or `connect` has already been - /// called on this builder. - pub fn listen(&self, backlog: i32) -> io::Result<()> { - self.inner.listen(backlog) - } - - /// Accept a new incoming connection from this listener. - /// - /// This function will block the calling thread until a new connection is - /// established. When established, the corresponding `Socket` and the - /// remote peer's address will be returned. - pub fn accept(&self) -> io::Result<(Socket, SockAddr)> { - self.inner.accept().map(|(socket, addr)| { - (Socket { inner: socket }, addr) - }) - } - - /// Returns the socket address of the local half of this TCP connection. - pub fn local_addr(&self) -> io::Result<SockAddr> { - self.inner.local_addr() - } - - /// Returns the socket address of the remote peer of this TCP connection. - pub fn peer_addr(&self) -> io::Result<SockAddr> { - self.inner.peer_addr() - } - - /// Creates a new independently owned handle to the underlying socket. - /// - /// The returned `TcpStream` is a reference to the same stream that this - /// object references. Both handles will read and write the same stream of - /// data, and options set on one stream will be propagated to the other - /// stream. - pub fn try_clone(&self) -> io::Result<Socket> { - self.inner.try_clone().map(|s| Socket { inner: s }) - } - - /// Get the value of the `SO_ERROR` option on this socket. - /// - /// This will retrieve the stored error in the underlying socket, clearing - /// the field in the process. This can be useful for checking errors between - /// calls. - pub fn take_error(&self) -> io::Result<Option<io::Error>> { - self.inner.take_error() - } - - /// Moves this TCP stream into or out of nonblocking mode. - /// - /// On Unix this corresponds to calling fcntl, and on Windows this - /// corresponds to calling ioctlsocket. - pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { - self.inner.set_nonblocking(nonblocking) - } - - /// Shuts down the read, write, or both halves of this connection. - /// - /// This function will cause all pending and future I/O on the specified - /// portions to return immediately with an appropriate value. - pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { - self.inner.shutdown(how) - } - - /// Receives data on the socket from the remote address to which it is - /// connected. - /// - /// The [`connect`] method will connect this socket to a remote address. This - /// method will fail if the socket is not connected. - /// - /// [`connect`]: #method.connect - pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> { - self.inner.recv(buf) - } - - /// Receives data on the socket from the remote adress to which it is - /// connected, without removing that data from the queue. On success, - /// returns the number of bytes peeked. - /// - /// Successive calls return the same data. This is accomplished by passing - /// `MSG_PEEK` as a flag to the underlying `recv` system call. - pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> { - self.inner.peek(buf) - } - - /// Receives data from the socket. On success, returns the number of bytes - /// read and the address from whence the data came. - pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { - self.inner.recv_from(buf) - } - - /// Receives data from the socket, without removing it from the queue. - /// - /// Successive calls return the same data. This is accomplished by passing - /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call. - /// - /// On success, returns the number of bytes peeked and the address from - /// whence the data came. - pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { - self.inner.peek_from(buf) - } - - /// Sends data on the socket to a connected peer. - /// - /// This is typically used on TCP sockets or datagram sockets which have - /// been connected. - /// - /// On success returns the number of bytes that were sent. - pub fn send(&self, buf: &[u8]) -> io::Result<usize> { - self.inner.send(buf) - } - - /// Sends data on the socket to the given address. On success, returns the - /// number of bytes written. - /// - /// This is typically used on UDP or datagram-oriented sockets. On success - /// returns the number of bytes that were sent. - pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> { - self.inner.send_to(buf, addr) - } - - // ================================================ - - /// Gets the value of the `IP_TTL` option for this socket. - /// - /// For more information about this option, see [`set_ttl`][link]. - /// - /// [link]: #method.set_ttl - pub fn ttl(&self) -> io::Result<u32> { - self.inner.ttl() - } - - /// Sets the value for the `IP_TTL` option on this socket. - /// - /// This value sets the time-to-live field that is used in every packet sent - /// from this socket. - pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { - self.inner.set_ttl(ttl) - } - - /// Gets the value of the `IPV6_V6ONLY` option for this socket. - /// - /// For more information about this option, see [`set_only_v6`][link]. - /// - /// [link]: #method.set_only_v6 - pub fn only_v6(&self) -> io::Result<bool> { - self.inner.only_v6() - } - - /// Sets the value for the `IPV6_V6ONLY` option on this socket. - /// - /// If this is set to `true` then the socket is restricted to sending and - /// receiving IPv6 packets only. In this case two IPv4 and IPv6 applications - /// can bind the same port at the same time. - /// - /// If this is set to `false` then the socket can be used to send and - /// receive packets from an IPv4-mapped IPv6 address. - pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { - self.inner.set_only_v6(only_v6) - } - - /// Returns the read timeout of this socket. - /// - /// If the timeout is `None`, then `read` calls will block indefinitely. - pub fn read_timeout(&self) -> io::Result<Option<Duration>> { - self.inner.read_timeout() - } - - /// Sets the read timeout to the timeout specified. - /// - /// If the value specified is `None`, then `read` calls will block - /// indefinitely. It is an error to pass the zero `Duration` to this - /// method. - pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.inner.set_read_timeout(dur) - } - - /// Returns the write timeout of this socket. - /// - /// If the timeout is `None`, then `write` calls will block indefinitely. - pub fn write_timeout(&self) -> io::Result<Option<Duration>> { - self.inner.write_timeout() - } - - /// Sets the write timeout to the timeout specified. - /// - /// If the value specified is `None`, then `write` calls will block - /// indefinitely. It is an error to pass the zero `Duration` to this - /// method. - pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - self.inner.set_write_timeout(dur) - } - - /// Gets the value of the `TCP_NODELAY` option on this socket. - /// - /// For more information about this option, see [`set_nodelay`][link]. - /// - /// [link]: #method.set_nodelay - pub fn nodelay(&self) -> io::Result<bool> { - self.inner.nodelay() - } - - /// Sets the value of the `TCP_NODELAY` option on this socket. - /// - /// If set, this option disables the Nagle algorithm. This means that - /// segments are always sent as soon as possible, even if there is only a - /// small amount of data. When not set, data is buffered until there is a - /// sufficient amount to send out, thereby avoiding the frequent sending of - /// small packets. - pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { - self.inner.set_nodelay(nodelay) - } - - /// Sets the value of the `SO_BROADCAST` option for this socket. - /// - /// When enabled, this socket is allowed to send packets to a broadcast - /// address. - pub fn broadcast(&self) -> io::Result<bool> { - self.inner.broadcast() - } - - /// Gets the value of the `SO_BROADCAST` option for this socket. - /// - /// For more information about this option, see - /// [`set_broadcast`][link]. - /// - /// [link]: #method.set_broadcast - pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { - self.inner.set_broadcast(broadcast) - } - - /// Gets the value of the `IP_MULTICAST_TTL` option for this socket. - /// - /// For more information about this option, see - /// [`set_multicast_ttl_v4`][link]. - /// - /// [link]: #method.set_multicast_ttl_v4 - pub fn multicast_loop_v4(&self) -> io::Result<bool> { - self.inner.multicast_loop_v4() - } - - /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket. - /// - /// If enabled, multicast packets will be looped back to the local socket. - /// Note that this may not have any affect on IPv6 sockets. - pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> { - self.inner.set_multicast_loop_v4(multicast_loop_v4) - } - - /// Gets the value of the `IP_MULTICAST_TTL` option for this socket. - /// - /// For more information about this option, see - /// [`set_multicast_ttl_v4`][link]. - /// - /// [link]: #method.set_multicast_ttl_v4 - pub fn multicast_ttl_v4(&self) -> io::Result<u32> { - self.inner.multicast_ttl_v4() - } - - /// Sets the value of the `IP_MULTICAST_TTL` option for this socket. - /// - /// Indicates the time-to-live value of outgoing multicast packets for - /// this socket. The default value is 1 which means that multicast packets - /// don't leave the local network unless explicitly requested. - /// - /// Note that this may not have any affect on IPv6 sockets. - pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> { - self.inner.set_multicast_ttl_v4(multicast_ttl_v4) - } - - /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket. - /// - /// For more information about this option, see - /// [`set_multicast_loop_v6`][link]. - /// - /// [link]: #method.set_multicast_loop_v6 - pub fn multicast_loop_v6(&self) -> io::Result<bool> { - self.inner.multicast_loop_v6() - } - - /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket. - /// - /// Controls whether this socket sees the multicast packets it sends itself. - /// Note that this may not have any affect on IPv4 sockets. - pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> { - self.inner.set_multicast_loop_v6(multicast_loop_v6) - } - - - /// Executes an operation of the `IP_ADD_MEMBERSHIP` type. - /// - /// This function specifies a new multicast group for this socket to join. - /// The address must be a valid multicast address, and `interface` is the - /// address of the local interface with which the system should join the - /// multicast group. If it's equal to `INADDR_ANY` then an appropriate - /// interface is chosen by the system. - pub fn join_multicast_v4(&self, - multiaddr: &Ipv4Addr, - interface: &Ipv4Addr) -> io::Result<()> { - self.inner.join_multicast_v4(multiaddr, interface) - } - - /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type. - /// - /// This function specifies a new multicast group for this socket to join. - /// The address must be a valid multicast address, and `interface` is the - /// index of the interface to join/leave (or 0 to indicate any interface). - pub fn join_multicast_v6(&self, - multiaddr: &Ipv6Addr, - interface: u32) -> io::Result<()> { - self.inner.join_multicast_v6(multiaddr, interface) - } - - /// Executes an operation of the `IP_DROP_MEMBERSHIP` type. - /// - /// For more information about this option, see - /// [`join_multicast_v4`][link]. - /// - /// [link]: #method.join_multicast_v4 - pub fn leave_multicast_v4(&self, - multiaddr: &Ipv4Addr, - interface: &Ipv4Addr) -> io::Result<()> { - self.inner.leave_multicast_v4(multiaddr, interface) - } - - /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type. - /// - /// For more information about this option, see - /// [`join_multicast_v6`][link]. - /// - /// [link]: #method.join_multicast_v6 - pub fn leave_multicast_v6(&self, - multiaddr: &Ipv6Addr, - interface: u32) -> io::Result<()> { - self.inner.leave_multicast_v6(multiaddr, interface) - } - - /// Reads the linger duration for this socket by getting the SO_LINGER - /// option - pub fn linger(&self) -> io::Result<Option<Duration>> { - self.inner.linger() - } - - /// Sets the linger duration of this socket by setting the SO_LINGER option - pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> { - self.inner.set_linger(dur) - } - - /// Check the `SO_REUSEADDR` option on this socket. - pub fn reuse_address(&self) -> io::Result<bool> { - self.inner.reuse_address() - } - - /// Set value for the `SO_REUSEADDR` option on this socket. - /// - /// This indicates that futher calls to `bind` may allow reuse of local - /// addresses. For IPv4 sockets this means that a socket may bind even when - /// there's a socket already listening on this port. - pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> { - self.inner.set_reuse_address(reuse) - } - - /// Gets the value of the `SO_RCVBUF` option on this socket. - /// - /// For more information about this option, see - /// [`set_recv_buffer_size`][link]. - /// - /// [link]: #method.set_recv_buffer_size - pub fn recv_buffer_size(&self) -> io::Result<usize> { - self.inner.recv_buffer_size() - } - - /// Sets the value of the `SO_RCVBUF` option on this socket. - /// - /// Changes the size of the operating system's receive buffer associated - /// with the socket. - pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { - self.inner.set_recv_buffer_size(size) - } - - /// Gets the value of the `SO_SNDBUF` option on this socket. - /// - /// For more information about this option, see [`set_send_buffer`][link]. - /// - /// [link]: #method.set_send_buffer - pub fn send_buffer_size(&self) -> io::Result<usize> { - self.inner.send_buffer_size() - } - - /// Sets the value of the `SO_SNDBUF` option on this socket. - /// - /// Changes the size of the operating system's send buffer associated with - /// the socket. - pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { - self.inner.set_send_buffer_size(size) - } - - /// Returns whether keepalive messages are enabled on this socket, and if so - /// the duration of time between them. - /// - /// For more information about this option, see [`set_keepalive`][link]. - /// - /// [link]: #method.set_keepalive - pub fn keepalive(&self) -> io::Result<Option<Duration>> { - self.inner.keepalive() - } - - /// Sets whether keepalive messages are enabled to be sent on this socket. - /// - /// On Unix, this option will set the `SO_KEEPALIVE` as well as the - /// `TCP_KEEPALIVE` or `TCP_KEEPIDLE` option (depending on your platform). - /// On Windows, this will set the `SIO_KEEPALIVE_VALS` option. - /// - /// If `None` is specified then keepalive messages are disabled, otherwise - /// the duration specified will be the time to remain idle before sending a - /// TCP keepalive probe. - /// - /// Some platforms specify this value in seconds, so sub-second - /// specifications may be omitted. - pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> { - self.inner.set_keepalive(keepalive) - } - - /// Check the value of the `SO_REUSEPORT` option on this socket. - /// - /// This function is only available on Unix when the `reuseport` feature is - /// enabled. - #[cfg(all(unix, feature = "reuseport"))] - pub fn reuse_port(&self) -> io::Result<bool> { - self.inner.reuse_port() - } - - /// Set value for the `SO_REUSEPORT` option on this socket. - /// - /// This indicates that futher calls to `bind` may allow reuse of local - /// addresses. For IPv4 sockets this means that a socket may bind even when - /// there's a socket already listening on this port. - /// - /// This function is only available on Unix when the `reuseport` feature is - /// enabled. - #[cfg(all(unix, feature = "reuseport"))] - pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> { - self.inner.set_reuse_port(reuse) - } -} - -impl Read for Socket { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.inner.read(buf) - } -} - -impl<'a> Read for &'a Socket { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - (&self.inner).read(buf) - } -} - -impl Write for Socket { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.inner.write(buf) - } - - fn flush(&mut self) -> io::Result<()> { - self.inner.flush() - } -} - -impl<'a> Write for &'a Socket { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - (&self.inner).write(buf) - } - - fn flush(&mut self) -> io::Result<()> { - (&self.inner).flush() - } -} - -impl fmt::Debug for Socket { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.inner.fmt(f) - } -} - -impl From<net::TcpStream> for Socket { - fn from(socket: net::TcpStream) -> Socket { - Socket { inner: socket.into() } - } -} - -impl From<net::TcpListener> for Socket { - fn from(socket: net::TcpListener) -> Socket { - Socket { inner: socket.into() } - } -} - -impl From<net::UdpSocket> for Socket { - fn from(socket: net::UdpSocket) -> Socket { - Socket { inner: socket.into() } - } -} - -#[cfg(all(unix, feature = "unix"))] -impl From<UnixStream> for Socket { - fn from(socket: UnixStream) -> Socket { - Socket { inner: socket.into() } - } -} - -#[cfg(all(unix, feature = "unix"))] -impl From<UnixListener> for Socket { - fn from(socket: UnixListener) -> Socket { - Socket { inner: socket.into() } - } -} - -#[cfg(all(unix, feature = "unix"))] -impl From<UnixDatagram> for Socket { - fn from(socket: UnixDatagram) -> Socket { - Socket { inner: socket.into() } - } -} - -impl From<Socket> for net::TcpStream { - fn from(socket: Socket) -> net::TcpStream { - socket.inner.into() - } -} - -impl From<Socket> for net::TcpListener { - fn from(socket: Socket) -> net::TcpListener { - socket.inner.into() - } -} - -impl From<Socket> for net::UdpSocket { - fn from(socket: Socket) -> net::UdpSocket { - socket.inner.into() - } -} - -#[cfg(all(unix, feature = "unix"))] -impl From<Socket> for UnixStream { - fn from(socket: Socket) -> UnixStream { - socket.inner.into() - } -} - -#[cfg(all(unix, feature = "unix"))] -impl From<Socket> for UnixListener { - fn from(socket: Socket) -> UnixListener { - socket.inner.into() - } -} - -#[cfg(all(unix, feature = "unix"))] -impl From<Socket> for UnixDatagram { - fn from(socket: Socket) -> UnixDatagram { - socket.inner.into() - } -} - -impl Domain { - /// Domain for IPv4 communication, corresponding to `AF_INET`. - pub fn ipv4() -> Domain { - Domain(c::AF_INET) - } - - /// Domain for IPv6 communication, corresponding to `AF_INET6`. - pub fn ipv6() -> Domain { - Domain(c::AF_INET6) - } - - /// Domain for Unix socket communication, corresponding to `AF_UNIX`. - /// - /// This function is only available on Unix when the `unix` feature is - /// activated. - #[cfg(all(unix, feature = "unix"))] - pub fn unix() -> Domain { - Domain(c::AF_UNIX) - } -} - -impl From<i32> for Domain { - fn from(a: i32) -> Domain { - Domain(a) - } -} - -impl From<Domain> for i32 { - fn from(a: Domain) -> i32 { - a.into() - } -} - -impl Type { - /// Type corresponding to `SOCK_STREAM` - /// - /// Used for protocols such as TCP. - pub fn stream() -> Type { - Type(c::SOCK_STREAM) - } - - /// Type corresponding to `SOCK_DGRAM` - /// - /// Used for protocols such as UDP. - pub fn dgram() -> Type { - Type(c::SOCK_DGRAM) - } - - /// Type corresponding to `SOCK_SEQPACKET` - pub fn seqpacket() -> Type { - Type(c::SOCK_SEQPACKET) - } - - /// Type corresponding to `SOCK_RAW` - pub fn raw() -> Type { - Type(c::SOCK_RAW) - } -} - -impl ::Protocol { - /// Protocol corresponding to `ICMPv4` - pub fn icmpv4() -> Self { - ::Protocol(sys::IPPROTO_ICMP) - } - - /// Protocol corresponding to `ICMPv6` - pub fn icmpv6() -> Self { - ::Protocol(sys::IPPROTO_ICMPV6) - } - - /// Protocol corresponding to `TCP` - pub fn tcp() -> Self { - ::Protocol(sys::IPPROTO_TCP) - } - - /// Protocol corresponding to `UDP` - pub fn udp() -> Self { - ::Protocol(sys::IPPROTO_UDP) - } -} - -impl From<i32> for Type { - fn from(a: i32) -> Type { - Type(a) - } -} - -impl From<Type> for i32 { - fn from(a: Type) -> i32 { - a.into() - } -} - -impl From<i32> for Protocol { - fn from(a: i32) -> Protocol { - Protocol(a) - } -} - -impl From<Protocol> for i32 { - fn from(a: Protocol) -> i32 { - a.into() - } -} - -#[cfg(test)] -mod test { - use std::net::SocketAddr; - - use super::*; - - #[test] - fn connect_timeout_unrouteable() { - // this IP is unroutable, so connections should always time out - let addr = "10.255.255.1:80".parse::<SocketAddr>().unwrap().into(); - - let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); - match socket.connect_timeout(&addr, Duration::from_millis(250)) { - Ok(_) => panic!("unexpected success"), - Err(ref e) if e.kind() == io::ErrorKind::TimedOut => {} - Err(e) => panic!("unexpected error {}", e), - } - } - - #[test] - fn connect_timeout_unbound() { - // bind and drop a socket to track down a "probably unassigned" port - let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); - let addr = "127.0.0.1:0".parse::<SocketAddr>().unwrap().into(); - socket.bind(&addr).unwrap(); - let addr = socket.local_addr().unwrap(); - drop(socket); - - let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); - match socket.connect_timeout(&addr, Duration::from_millis(250)) { - Ok(_) => panic!("unexpected success"), - Err(ref e) if e.kind() == io::ErrorKind::ConnectionRefused || - e.kind() == io::ErrorKind::TimedOut => {}, - Err(e) => panic!("unexpected error {}", e), - } - } - - #[test] - fn connect_timeout_valid() { - let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); - socket.bind(&"127.0.0.1:0".parse::<SocketAddr>().unwrap().into()).unwrap(); - socket.listen(128).unwrap(); - - let addr = socket.local_addr().unwrap(); - - let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); - socket.connect_timeout(&addr, Duration::from_millis(250)).unwrap(); - } - - #[test] - #[cfg(all(unix, feature = "pair", feature = "unix"))] - fn pair() { - let (mut a, mut b) = Socket::pair(Domain::unix(), Type::stream(), None).unwrap(); - a.write_all(b"hello world").unwrap(); - let mut buf = [0; 11]; - b.read_exact(&mut buf).unwrap(); - assert_eq!(buf, &b"hello world"[..]); - } - - #[test] - #[cfg(all(unix, feature = "unix"))] - fn unix() { - use tempdir::TempDir; - - let dir = TempDir::new("unix").unwrap(); - let addr = SockAddr::unix(dir.path().join("sock")).unwrap(); - - let listener = Socket::new(Domain::unix(), Type::stream(), None).unwrap(); - listener.bind(&addr).unwrap(); - listener.listen(10).unwrap(); - - let mut a = Socket::new(Domain::unix(), Type::stream(), None).unwrap(); - a.connect(&addr).unwrap(); - - let mut b = listener.accept().unwrap().0; - - a.write_all(b"hello world").unwrap(); - let mut buf = [0; 11]; - b.read_exact(&mut buf).unwrap(); - assert_eq!(buf, &b"hello world"[..]); - } -} diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/src/sys/unix/mod.rs cargo-0.26.0/vendor/socket2-0.3.1/src/sys/unix/mod.rs --- cargo-0.25.0/vendor/socket2-0.3.1/src/sys/unix/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/src/sys/unix/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1036 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::cmp; -use std::fmt; -use std::io::{Read, Write, ErrorKind}; -use std::io; -use std::mem; -use std::net::Shutdown; -use std::net::{self, Ipv4Addr, Ipv6Addr}; -use std::ops::Neg; -use std::os::unix::prelude::*; -use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; -use std::time::{Duration, Instant}; -#[cfg(feature = "unix")] -use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream}; - -use libc::{self, c_void, c_int, socklen_t, ssize_t}; - -cfg_if! { - if #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd", target_os = "netbsd", - target_os = "solaris", target_os = "haiku"))] { - use libc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP; - use libc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP; - } else { - use libc::IPV6_ADD_MEMBERSHIP; - use libc::IPV6_DROP_MEMBERSHIP; - } -} - -cfg_if! { - if #[cfg(any(target_os = "linux", target_os = "android", - target_os = "dragonfly", target_os = "freebsd", - target_os = "openbsd", target_os = "netbsd", - target_os = "haiku", target_os = "bitrig"))] { - use libc::MSG_NOSIGNAL; - } else { - const MSG_NOSIGNAL: c_int = 0x0; - } -} - -cfg_if! { - if #[cfg(any(target_os = "macos", target_os = "ios"))] { - use libc::TCP_KEEPALIVE as KEEPALIVE_OPTION; - } else if #[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "haiku"))] { - use libc::SO_KEEPALIVE as KEEPALIVE_OPTION; - } else { - use libc::TCP_KEEPIDLE as KEEPALIVE_OPTION; - } -} - -use SockAddr; -use utils::One; - -pub const IPPROTO_ICMP: i32 = libc::IPPROTO_ICMP; -pub const IPPROTO_ICMPV6: i32 = libc::IPPROTO_ICMPV6; -pub const IPPROTO_TCP: i32 = libc::IPPROTO_TCP; -pub const IPPROTO_UDP: i32 = libc::IPPROTO_UDP; - -#[macro_use] -#[cfg(target_os = "linux")] -mod weak; - -pub struct Socket { - fd: c_int, -} - -impl Socket { - pub fn new(family: c_int, ty: c_int, protocol: c_int) -> io::Result<Socket> { - unsafe { - // On linux we first attempt to pass the SOCK_CLOEXEC flag to - // atomically create the socket and set it as CLOEXEC. Support for - // this option, however, was added in 2.6.27, and we still support - // 2.6.18 as a kernel, so if the returned error is EINVAL we - // fallthrough to the fallback. - #[cfg(target_os = "linux")] { - match cvt(libc::socket(family, ty | libc::SOCK_CLOEXEC, protocol)) { - Ok(fd) => return Ok(Socket::from_raw_fd(fd)), - Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} - Err(e) => return Err(e), - } - } - - let fd = cvt(libc::socket(family, ty, protocol))?; - let fd = Socket::from_raw_fd(fd); - set_cloexec(fd.as_raw_fd())?; - #[cfg(target_os = "macos")] { - fd.setsockopt(libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1i32)?; - } - Ok(fd) - } - } - - pub fn pair(family: c_int, ty: c_int, protocol: c_int) -> io::Result<(Socket, Socket)> { - unsafe { - let mut fds = [0, 0]; - cvt(libc::socketpair(family, ty, protocol, fds.as_mut_ptr()))?; - let fds = (Socket::from_raw_fd(fds[0]), Socket::from_raw_fd(fds[1])); - set_cloexec(fds.0.as_raw_fd())?; - set_cloexec(fds.1.as_raw_fd())?; - #[cfg(target_os = "macos")] { - fds.0.setsockopt(libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1i32)?; - fds.1.setsockopt(libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1i32)?; - } - Ok(fds) - } - } - - pub fn bind(&self, addr: &SockAddr) -> io::Result<()> { - unsafe { - cvt(libc::bind(self.fd, addr.as_ptr(), addr.len() as _)).map(|_| ()) - } - } - - pub fn listen(&self, backlog: i32) -> io::Result<()> { - unsafe { - cvt(libc::listen(self.fd, backlog)).map(|_| ()) - } - } - - pub fn connect(&self, addr: &SockAddr) -> io::Result<()> { - unsafe { - cvt(libc::connect(self.fd, addr.as_ptr(), addr.len())).map(|_| ()) - } - } - - pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> { - self.set_nonblocking(true)?; - let r = self.connect(addr); - self.set_nonblocking(false)?; - - match r { - Ok(()) => return Ok(()), - // there's no io::ErrorKind conversion registered for EINPROGRESS :( - Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {} - Err(e) => return Err(e), - } - - let mut pollfd = libc::pollfd { - fd: self.fd, - events: libc::POLLOUT, - revents: 0, - }; - - if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); - } - - let start = Instant::now(); - - loop { - let elapsed = start.elapsed(); - if elapsed >= timeout { - return Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out")); - } - - let timeout = timeout - elapsed; - let mut timeout = timeout.as_secs() - .saturating_mul(1_000) - .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000); - if timeout == 0 { - timeout = 1; - } - - let timeout = cmp::min(timeout, c_int::max_value() as u64) as c_int; - - match unsafe { libc::poll(&mut pollfd, 1, timeout) } { - -1 => { - let err = io::Error::last_os_error(); - if err.kind() != io::ErrorKind::Interrupted { - return Err(err); - } - } - 0 => return Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out")), - _ => { - // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look - // for POLLHUP rather than read readiness - if pollfd.revents & libc::POLLHUP != 0 { - let e = self.take_error()? - .unwrap_or_else(|| { - io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP") - }); - return Err(e); - } - return Ok(()); - } - } - } - } - - pub fn local_addr(&self) -> io::Result<SockAddr> { - unsafe { - let mut storage: libc::sockaddr_storage = mem::zeroed(); - let mut len = mem::size_of_val(&storage) as libc::socklen_t; - cvt(libc::getsockname(self.fd, - &mut storage as *mut _ as *mut _, - &mut len))?; - Ok(SockAddr::from_raw_parts(&storage as *const _ as *const _, len)) - } - } - - pub fn peer_addr(&self) -> io::Result<SockAddr> { - unsafe { - let mut storage: libc::sockaddr_storage = mem::zeroed(); - let mut len = mem::size_of_val(&storage) as libc::socklen_t; - cvt(libc::getpeername(self.fd, - &mut storage as *mut _ as *mut _, - &mut len))?; - Ok(SockAddr::from_raw_parts(&storage as *const _ as *const _, len)) - } - } - - pub fn try_clone(&self) -> io::Result<Socket> { - // implementation lifted from libstd - #[cfg(any(target_os = "android", target_os = "haiku"))] - use libc::F_DUPFD as F_DUPFD_CLOEXEC; - #[cfg(not(any(target_os = "android", target_os = "haiku")))] - use libc::F_DUPFD_CLOEXEC; - - static CLOEXEC_FAILED: AtomicBool = ATOMIC_BOOL_INIT; - unsafe { - if !CLOEXEC_FAILED.load(Ordering::Relaxed) { - match cvt(libc::fcntl(self.fd, F_DUPFD_CLOEXEC, 0)) { - Ok(fd) => { - let fd = Socket::from_raw_fd(fd); - if cfg!(target_os = "linux") { - set_cloexec(fd.as_raw_fd())?; - } - return Ok(fd) - } - Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => { - CLOEXEC_FAILED.store(true, Ordering::Relaxed); - } - Err(e) => return Err(e), - } - } - let fd = cvt(libc::fcntl(self.fd, libc::F_DUPFD, 0))?; - let fd = Socket::from_raw_fd(fd); - set_cloexec(fd.as_raw_fd())?; - Ok(fd) - } - } - - #[allow(unused_mut)] - pub fn accept(&self) -> io::Result<(Socket, SockAddr)> { - let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() }; - let mut len = mem::size_of_val(&storage) as socklen_t; - - let mut socket = None; - #[cfg(target_os = "linux")] { - weak! { - fn accept4(c_int, *mut libc::sockaddr, *mut socklen_t, c_int) -> c_int - } - if let Some(f) = accept4.get() { - let res = cvt_r(|| unsafe { - f(self.fd, - &mut storage as *mut _ as *mut _, - &mut len, - libc::SOCK_CLOEXEC) - }); - match res { - Ok(fd) => socket = Some(Socket { fd: fd }), - Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {} - Err(e) => return Err(e), - } - } - } - - let socket = match socket { - Some(socket) => socket, - None => unsafe { - let fd = cvt_r(|| { - libc::accept(self.fd, - &mut storage as *mut _ as *mut _, - &mut len) - })?; - let fd = Socket::from_raw_fd(fd); - set_cloexec(fd.as_raw_fd())?; - fd - } - }; - let addr = unsafe { SockAddr::from_raw_parts(&storage as *const _ as *const _, len) }; - Ok((socket, addr)) - } - - pub fn take_error(&self) -> io::Result<Option<io::Error>> { - unsafe { - let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_ERROR)?; - if raw == 0 { - Ok(None) - } else { - Ok(Some(io::Error::from_raw_os_error(raw as i32))) - } - } - } - - pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { - unsafe { - let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?; - let new = if nonblocking { - previous | libc::O_NONBLOCK - } else { - previous & !libc::O_NONBLOCK - }; - if new != previous { - cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?; - } - Ok(()) - } - } - - pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { - let how = match how { - Shutdown::Write => libc::SHUT_WR, - Shutdown::Read => libc::SHUT_RD, - Shutdown::Both => libc::SHUT_RDWR, - }; - cvt(unsafe { libc::shutdown(self.fd, how) })?; - Ok(()) - } - - pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> { - unsafe { - let n = cvt({ - libc::recv(self.fd, - buf.as_mut_ptr() as *mut c_void, - cmp::min(buf.len(), max_len()), - 0) - })?; - Ok(n as usize) - } - } - - pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> { - unsafe { - let n = cvt({ - libc::recv(self.fd, - buf.as_mut_ptr() as *mut c_void, - cmp::min(buf.len(), max_len()), - libc::MSG_PEEK) - })?; - Ok(n as usize) - } - } - - pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { - self.recvfrom(buf, 0) - } - - pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { - self.recvfrom(buf, libc::MSG_PEEK) - } - - fn recvfrom(&self, buf: &mut [u8], flags: c_int) - -> io::Result<(usize, SockAddr)> { - unsafe { - let mut storage: libc::sockaddr_storage = mem::zeroed(); - let mut addrlen = mem::size_of_val(&storage) as socklen_t; - - let n = cvt({ - libc::recvfrom(self.fd, - buf.as_mut_ptr() as *mut c_void, - cmp::min(buf.len(), max_len()), - flags, - &mut storage as *mut _ as *mut _, - &mut addrlen) - })?; - let addr = SockAddr::from_raw_parts(&storage as *const _ as *const _, addrlen); - Ok((n as usize, addr)) - } - } - - pub fn send(&self, buf: &[u8]) -> io::Result<usize> { - unsafe { - let n = cvt({ - libc::send(self.fd, - buf.as_ptr() as *const c_void, - cmp::min(buf.len(), max_len()), - MSG_NOSIGNAL) - })?; - Ok(n as usize) - } - } - - pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> { - unsafe { - let n = cvt({ - libc::sendto(self.fd, - buf.as_ptr() as *const c_void, - cmp::min(buf.len(), max_len()), - MSG_NOSIGNAL, - addr.as_ptr(), - addr.len()) - })?; - Ok(n as usize) - } - } - - // ================================================ - - pub fn ttl(&self) -> io::Result<u32> { - unsafe { - let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_TTL)?; - Ok(raw as u32) - } - } - - pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { - unsafe { - self.setsockopt(libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int) - } - } - - pub fn only_v6(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, - libc::IPV6_V6ONLY)?; - Ok(raw != 0) - } - } - - pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { - unsafe { - self.setsockopt(libc::IPPROTO_IPV6, - libc::IPV6_V6ONLY, - only_v6 as c_int) - } - } - - pub fn read_timeout(&self) -> io::Result<Option<Duration>> { - unsafe { - Ok(timeval2dur(self.getsockopt(libc::SOL_SOCKET, libc::SO_RCVTIMEO)?)) - } - } - - pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - unsafe { - self.setsockopt(libc::SOL_SOCKET, - libc::SO_RCVTIMEO, - dur2timeval(dur)?) - } - } - - pub fn write_timeout(&self) -> io::Result<Option<Duration>> { - unsafe { - Ok(timeval2dur(self.getsockopt(libc::SOL_SOCKET, libc::SO_SNDTIMEO)?)) - } - } - - pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - unsafe { - self.setsockopt(libc::SOL_SOCKET, - libc::SO_SNDTIMEO, - dur2timeval(dur)?) - } - } - - pub fn nodelay(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(libc::IPPROTO_TCP, - libc::TCP_NODELAY)?; - Ok(raw != 0) - } - } - - pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { - unsafe { - self.setsockopt(libc::IPPROTO_TCP, - libc::TCP_NODELAY, - nodelay as c_int) - } - } - - pub fn broadcast(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(libc::SOL_SOCKET, - libc::SO_BROADCAST)?; - Ok(raw != 0) - } - } - - pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { - unsafe { - self.setsockopt(libc::SOL_SOCKET, - libc::SO_BROADCAST, - broadcast as c_int) - } - } - - pub fn multicast_loop_v4(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(libc::IPPROTO_IP, - libc::IP_MULTICAST_LOOP)?; - Ok(raw != 0) - } - } - - pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> { - unsafe { - self.setsockopt(libc::IPPROTO_IP, - libc::IP_MULTICAST_LOOP, - multicast_loop_v4 as c_int) - } - } - - pub fn multicast_ttl_v4(&self) -> io::Result<u32> { - unsafe { - let raw: c_int = self.getsockopt(libc::IPPROTO_IP, - libc::IP_MULTICAST_TTL)?; - Ok(raw as u32) - } - } - - pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> { - unsafe { - self.setsockopt(libc::IPPROTO_IP, - libc::IP_MULTICAST_TTL, - multicast_ttl_v4 as c_int) - } - } - - pub fn multicast_loop_v6(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, - libc::IPV6_MULTICAST_LOOP)?; - Ok(raw != 0) - } - } - - pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> { - unsafe { - self.setsockopt(libc::IPPROTO_IPV6, - libc::IPV6_MULTICAST_LOOP, - multicast_loop_v6 as c_int) - } - } - - pub fn join_multicast_v4(&self, - multiaddr: &Ipv4Addr, - interface: &Ipv4Addr) -> io::Result<()> { - let multiaddr = to_s_addr(multiaddr); - let interface = to_s_addr(interface); - let mreq = libc::ip_mreq { - imr_multiaddr: libc::in_addr { s_addr: multiaddr }, - imr_interface: libc::in_addr { s_addr: interface }, - }; - unsafe { - self.setsockopt(libc::IPPROTO_IP, libc::IP_ADD_MEMBERSHIP, mreq) - } - } - - pub fn join_multicast_v6(&self, - multiaddr: &Ipv6Addr, - interface: u32) -> io::Result<()> { - let multiaddr = to_in6_addr(multiaddr); - let mreq = libc::ipv6_mreq { - ipv6mr_multiaddr: multiaddr, - ipv6mr_interface: to_ipv6mr_interface(interface), - }; - unsafe { - self.setsockopt(libc::IPPROTO_IP, IPV6_ADD_MEMBERSHIP, mreq) - } - } - - pub fn leave_multicast_v4(&self, - multiaddr: &Ipv4Addr, - interface: &Ipv4Addr) -> io::Result<()> { - let multiaddr = to_s_addr(multiaddr); - let interface = to_s_addr(interface); - let mreq = libc::ip_mreq { - imr_multiaddr: libc::in_addr { s_addr: multiaddr }, - imr_interface: libc::in_addr { s_addr: interface }, - }; - unsafe { - self.setsockopt(libc::IPPROTO_IP, libc::IP_DROP_MEMBERSHIP, mreq) - } - } - - pub fn leave_multicast_v6(&self, - multiaddr: &Ipv6Addr, - interface: u32) -> io::Result<()> { - let multiaddr = to_in6_addr(multiaddr); - let mreq = libc::ipv6_mreq { - ipv6mr_multiaddr: multiaddr, - ipv6mr_interface: to_ipv6mr_interface(interface), - }; - unsafe { - self.setsockopt(libc::IPPROTO_IP, IPV6_DROP_MEMBERSHIP, mreq) - } - } - - pub fn linger(&self) -> io::Result<Option<Duration>> { - unsafe { - Ok(linger2dur(self.getsockopt(libc::SOL_SOCKET, libc::SO_LINGER)?)) - } - } - - pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> { - unsafe { - self.setsockopt(libc::SOL_SOCKET, libc::SO_LINGER, dur2linger(dur)) - } - } - - pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> { - unsafe { - self.setsockopt(libc::SOL_SOCKET, libc::SO_REUSEADDR, reuse as c_int) - } - } - - pub fn reuse_address(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(libc::SOL_SOCKET, - libc::SO_REUSEADDR)?; - Ok(raw != 0) - } - } - - pub fn recv_buffer_size(&self) -> io::Result<usize> { - unsafe { - let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_RCVBUF)?; - Ok(raw as usize) - } - } - - pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { - unsafe { - // TODO: casting usize to a c_int should be a checked cast - self.setsockopt(libc::SOL_SOCKET, libc::SO_RCVBUF, size as c_int) - } - } - - pub fn send_buffer_size(&self) -> io::Result<usize> { - unsafe { - let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_SNDBUF)?; - Ok(raw as usize) - } - } - - pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { - unsafe { - // TODO: casting usize to a c_int should be a checked cast - self.setsockopt(libc::SOL_SOCKET, libc::SO_SNDBUF, size as c_int) - } - } - - pub fn keepalive(&self) -> io::Result<Option<Duration>> { - unsafe { - let raw: c_int = self.getsockopt(libc::SOL_SOCKET, - libc::SO_KEEPALIVE)?; - if raw == 0 { - return Ok(None) - } - let secs: c_int = self.getsockopt(libc::IPPROTO_TCP, - KEEPALIVE_OPTION)?; - Ok(Some(Duration::new(secs as u64, 0))) - } - } - - pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> { - unsafe { - self.setsockopt(libc::SOL_SOCKET, - libc::SO_KEEPALIVE, - keepalive.is_some() as c_int)?; - if let Some(dur) = keepalive { - // TODO: checked cast here - self.setsockopt(libc::IPPROTO_TCP, - KEEPALIVE_OPTION, - (dur.as_secs() / 1000) as c_int)?; - } - Ok(()) - } - } - - #[cfg(all(unix, feature = "reuseport"))] - pub fn reuse_port(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(libc::SOL_SOCKET, - libc::SO_REUSEPORT)?; - Ok(raw != 0) - } - } - - #[cfg(all(unix, feature = "reuseport"))] - pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> { - unsafe { - self.setsockopt(libc::SOL_SOCKET, libc::SO_REUSEPORT, reuse as c_int) - } - } - - unsafe fn setsockopt<T>(&self, - opt: c_int, - val: c_int, - payload: T) -> io::Result<()> - where T: Copy, - { - let payload = &payload as *const T as *const c_void; - cvt(libc::setsockopt(self.fd, - opt, - val, - payload, - mem::size_of::<T>() as libc::socklen_t))?; - Ok(()) - } - - unsafe fn getsockopt<T: Copy>(&self, opt: c_int, val: c_int) -> io::Result<T> { - let mut slot: T = mem::zeroed(); - let mut len = mem::size_of::<T>() as libc::socklen_t; - cvt(libc::getsockopt(self.fd, - opt, - val, - &mut slot as *mut _ as *mut _, - &mut len))?; - assert_eq!(len as usize, mem::size_of::<T>()); - Ok(slot) - } -} - -impl Read for Socket { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - <&Socket>::read(&mut &*self, buf) - } -} - -impl<'a> Read for &'a Socket { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - unsafe { - let n = cvt({ - libc::read(self.fd, - buf.as_mut_ptr() as *mut c_void, - cmp::min(buf.len(), max_len())) - })?; - Ok(n as usize) - } - } -} - -impl Write for Socket { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - <&Socket>::write(&mut &*self, buf) - } - - fn flush(&mut self) -> io::Result<()> { - <&Socket>::flush(&mut &*self) - } -} - -impl<'a> Write for &'a Socket { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.send(buf) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -impl fmt::Debug for Socket { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut f = f.debug_struct("Socket"); - f.field("fd", &self.fd); - if let Ok(addr) = self.local_addr() { - f.field("local_addr", &addr); - } - if let Ok(addr) = self.peer_addr() { - f.field("peer_addr", &addr); - } - f.finish() - } -} - -impl AsRawFd for Socket { - fn as_raw_fd(&self) -> c_int { - self.fd - } -} - -impl IntoRawFd for Socket { - fn into_raw_fd(self) -> c_int { - let fd = self.fd; - mem::forget(self); - return fd - } -} - -impl FromRawFd for Socket { - unsafe fn from_raw_fd(fd: c_int) -> Socket { - Socket { fd: fd } - } -} - -impl AsRawFd for ::Socket { - fn as_raw_fd(&self) -> c_int { - self.inner.as_raw_fd() - } -} - -impl IntoRawFd for ::Socket { - fn into_raw_fd(self) -> c_int { - self.inner.into_raw_fd() - } -} - -impl FromRawFd for ::Socket { - unsafe fn from_raw_fd(fd: c_int) -> ::Socket { - ::Socket { inner: Socket::from_raw_fd(fd) } - } -} - -impl Drop for Socket { - fn drop(&mut self) { - unsafe { - let _ = libc::close(self.fd); - } - } -} - -impl From<Socket> for net::TcpStream { - fn from(socket: Socket) -> net::TcpStream { - unsafe { net::TcpStream::from_raw_fd(socket.into_raw_fd()) } - } -} - -impl From<Socket> for net::TcpListener { - fn from(socket: Socket) -> net::TcpListener { - unsafe { net::TcpListener::from_raw_fd(socket.into_raw_fd()) } - } -} - -impl From<Socket> for net::UdpSocket { - fn from(socket: Socket) -> net::UdpSocket { - unsafe { net::UdpSocket::from_raw_fd(socket.into_raw_fd()) } - } -} - -#[cfg(all(unix, feature = "unix"))] -impl From<Socket> for UnixStream { - fn from(socket: Socket) -> UnixStream { - unsafe { UnixStream::from_raw_fd(socket.into_raw_fd()) } - } -} - -#[cfg(all(unix, feature = "unix"))] -impl From<Socket> for UnixListener { - fn from(socket: Socket) -> UnixListener { - unsafe { UnixListener::from_raw_fd(socket.into_raw_fd()) } - } -} - -#[cfg(all(unix, feature = "unix"))] -impl From<Socket> for UnixDatagram { - fn from(socket: Socket) -> UnixDatagram { - unsafe { UnixDatagram::from_raw_fd(socket.into_raw_fd()) } - } -} - -impl From<net::TcpStream> for Socket { - fn from(socket: net::TcpStream) -> Socket { - unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } - } -} - -impl From<net::TcpListener> for Socket { - fn from(socket: net::TcpListener) -> Socket { - unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } - } -} - -impl From<net::UdpSocket> for Socket { - fn from(socket: net::UdpSocket) -> Socket { - unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } - } -} - -#[cfg(all(unix, feature = "unix"))] -impl From<UnixStream> for Socket { - fn from(socket: UnixStream) -> Socket { - unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } - } -} - -#[cfg(all(unix, feature = "unix"))] -impl From<UnixListener> for Socket { - fn from(socket: UnixListener) -> Socket { - unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } - } -} - -#[cfg(all(unix, feature = "unix"))] -impl From<UnixDatagram> for Socket { - fn from(socket: UnixDatagram) -> Socket { - unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } - } -} - -fn max_len() -> usize { - // The maximum read limit on most posix-like systems is `SSIZE_MAX`, - // with the man page quoting that if the count of bytes to read is - // greater than `SSIZE_MAX` the result is "unspecified". - // - // On macOS, however, apparently the 64-bit libc is either buggy or - // intentionally showing odd behavior by rejecting any read with a size - // larger than or equal to INT_MAX. To handle both of these the read - // size is capped on both platforms. - if cfg!(target_os = "macos") { - <c_int>::max_value() as usize - 1 - } else { - <ssize_t>::max_value() as usize - } -} - -fn cvt<T: One + PartialEq + Neg<Output=T>>(t: T) -> io::Result<T> { - let one: T = T::one(); - if t == -one { - Err(io::Error::last_os_error()) - } else { - Ok(t) - } -} - -fn cvt_r<F, T>(mut f: F) -> io::Result<T> - where F: FnMut() -> T, - T: One + PartialEq + Neg<Output=T> -{ - loop { - match cvt(f()) { - Err(ref e) if e.kind() == ErrorKind::Interrupted => {} - other => return other, - } - } -} - -fn set_cloexec(fd: c_int) -> io::Result<()> { - unsafe { - let previous = cvt(libc::fcntl(fd, libc::F_GETFD))?; - let new = previous | libc::FD_CLOEXEC; - if new != previous { - cvt(libc::fcntl(fd, libc::F_SETFD, new))?; - } - Ok(()) - } -} - -fn dur2timeval(dur: Option<Duration>) -> io::Result<libc::timeval> { - match dur { - Some(dur) => { - if dur.as_secs() == 0 && dur.subsec_nanos() == 0 { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); - } - - let secs = if dur.as_secs() > libc::time_t::max_value() as u64 { - libc::time_t::max_value() - } else { - dur.as_secs() as libc::time_t - }; - let mut timeout = libc::timeval { - tv_sec: secs, - tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t, - }; - if timeout.tv_sec == 0 && timeout.tv_usec == 0 { - timeout.tv_usec = 1; - } - Ok(timeout) - } - None => { - Ok(libc::timeval { - tv_sec: 0, - tv_usec: 0, - }) - } - } -} - -fn timeval2dur(raw: libc::timeval) -> Option<Duration> { - if raw.tv_sec == 0 && raw.tv_usec == 0 { - None - } else { - let sec = raw.tv_sec as u64; - let nsec = (raw.tv_usec as u32) * 1000; - Some(Duration::new(sec, nsec)) - } -} - -fn to_s_addr(addr: &Ipv4Addr) -> libc::in_addr_t { - let octets = addr.octets(); - ::hton(((octets[0] as libc::in_addr_t) << 24) | - ((octets[1] as libc::in_addr_t) << 16) | - ((octets[2] as libc::in_addr_t) << 8) | - ((octets[3] as libc::in_addr_t) << 0)) -} - -fn to_in6_addr(addr: &Ipv6Addr) -> libc::in6_addr { - let mut ret: libc::in6_addr = unsafe { mem::zeroed() }; - ret.s6_addr = addr.octets(); - return ret -} - -#[cfg(target_os = "android")] -fn to_ipv6mr_interface(value: u32) -> c_int { - value as c_int -} - -#[cfg(not(target_os = "android"))] -fn to_ipv6mr_interface(value: u32) -> libc::c_uint { - value as libc::c_uint -} - -fn linger2dur(linger_opt: libc::linger) -> Option<Duration> { - if linger_opt.l_onoff == 0 { - None - } else { - Some(Duration::from_secs(linger_opt.l_linger as u64)) - } -} - -fn dur2linger(dur: Option<Duration>) -> libc::linger { - match dur { - Some(d) => { - libc::linger { - l_onoff: 1, - l_linger: d.as_secs() as c_int, - } - } - None => libc::linger { l_onoff: 0, l_linger: 0 }, - } -} diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/src/sys/unix/weak.rs cargo-0.26.0/vendor/socket2-0.3.1/src/sys/unix/weak.rs --- cargo-0.25.0/vendor/socket2-0.3.1/src/sys/unix/weak.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/src/sys/unix/weak.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,60 +0,0 @@ -// Copyright 2016 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::marker; -use std::mem; -use std::sync::atomic::{AtomicUsize, Ordering}; - -use libc; - -macro_rules! weak { - (fn $name:ident($($t:ty),*) -> $ret:ty) => ( - #[allow(bad_style)] - static $name: ::sys::weak::Weak<unsafe extern fn($($t),*) -> $ret> = - ::sys::weak::Weak { - name: concat!(stringify!($name), "\0"), - addr: ::std::sync::atomic::ATOMIC_USIZE_INIT, - _marker: ::std::marker::PhantomData, - }; - ) -} - -pub struct Weak<F> { - pub name: &'static str, - pub addr: AtomicUsize, - pub _marker: marker::PhantomData<F>, -} - -impl<F> Weak<F> { - pub fn get(&self) -> Option<&F> { - assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>()); - unsafe { - if self.addr.load(Ordering::SeqCst) == 0 { - let ptr = match fetch(self.name) { - 1 => 1, - n => n, - }; - self.addr.store(ptr, Ordering::SeqCst); - } - if self.addr.load(Ordering::SeqCst) == 1 { - None - } else { - mem::transmute::<&AtomicUsize, Option<&F>>(&self.addr) - } - } - } -} - -unsafe fn fetch(name: &str) -> usize { - let name = name.as_bytes(); - assert_eq!(name[name.len() - 1], 0); - libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _) as usize -} - diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/src/sys/windows.rs cargo-0.26.0/vendor/socket2-0.3.1/src/sys/windows.rs --- cargo-0.25.0/vendor/socket2-0.3.1/src/sys/windows.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/src/sys/windows.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,932 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::cmp; -use std::fmt; -use std::io::{Read, Write}; -use std::io; -use std::mem; -use std::net::Shutdown; -use std::net::{self, Ipv4Addr, Ipv6Addr}; -use std::os::windows::prelude::*; -use std::ptr; -use std::sync::{Once, ONCE_INIT}; -use std::time::Duration; - -use winapi::ctypes::{c_char, c_int, c_long, c_ulong}; -use winapi::shared::inaddr::*; -use winapi::shared::in6addr::*; -use winapi::shared::minwindef::DWORD; -use winapi::shared::ntdef::{HANDLE, ULONG}; -use winapi::shared::ws2def::*; -use winapi::shared::ws2def; -use winapi::shared::ws2ipdef::*; -use winapi::um::handleapi::SetHandleInformation; -use winapi::um::processthreadsapi::GetCurrentProcessId; -use winapi::um::winbase::INFINITE; -use winapi::um::winsock2 as sock; - -use SockAddr; - -const HANDLE_FLAG_INHERIT: DWORD = 0x00000001; -const MSG_PEEK: c_int = 0x2; -const SD_BOTH: c_int = 2; -const SD_RECEIVE: c_int = 0; -const SD_SEND: c_int = 1; -const SIO_KEEPALIVE_VALS: DWORD = 0x98000004; -const WSA_FLAG_OVERLAPPED: DWORD = 0x01; - -pub const IPPROTO_ICMP: i32 = ws2def::IPPROTO_ICMP as i32; -pub const IPPROTO_ICMPV6: i32 = ws2def::IPPROTO_ICMPV6 as i32; -pub const IPPROTO_TCP: i32 = ws2def::IPPROTO_TCP as i32; -pub const IPPROTO_UDP: i32 = ws2def::IPPROTO_UDP as i32; - -#[repr(C)] -struct tcp_keepalive { - onoff: c_ulong, - keepalivetime: c_ulong, - keepaliveinterval: c_ulong, -} - -fn init() { - static INIT: Once = ONCE_INIT; - - INIT.call_once(|| { - // Initialize winsock through the standard library by just creating a - // dummy socket. Whether this is successful or not we drop the result as - // libstd will be sure to have initialized winsock. - let _ = net::UdpSocket::bind("127.0.0.1:34254"); - }); -} - -fn last_error() -> io::Error { - io::Error::from_raw_os_error(unsafe { sock::WSAGetLastError() }) -} - -pub struct Socket { - socket: sock::SOCKET, -} - -impl Socket { - pub fn new(family: c_int, ty: c_int, protocol: c_int) -> io::Result<Socket> { - init(); - unsafe { - let socket = match sock::WSASocketW(family, - ty, - protocol, - ptr::null_mut(), - 0, - WSA_FLAG_OVERLAPPED) { - sock::INVALID_SOCKET => return Err(last_error()), - socket => socket, - }; - let socket = Socket::from_raw_socket(socket as RawSocket); - socket.set_no_inherit()?; - Ok(socket) - } - } - - pub fn bind(&self, addr: &SockAddr) -> io::Result<()> { - unsafe { - if sock::bind(self.socket, addr.as_ptr(), addr.len()) == 0 { - Ok(()) - } else { - Err(last_error()) - } - } - } - - pub fn listen(&self, backlog: i32) -> io::Result<()> { - unsafe { - if sock::listen(self.socket, backlog) == 0 { - Ok(()) - } else { - Err(last_error()) - } - } - } - - pub fn connect(&self, addr: &SockAddr) -> io::Result<()> { - unsafe { - if sock::connect(self.socket, addr.as_ptr(), addr.len()) == 0 { - Ok(()) - } else { - Err(last_error()) - } - } - } - - pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> { - self.set_nonblocking(true)?; - let r = self.connect(addr); - self.set_nonblocking(false)?; - - match r { - Ok(()) => return Ok(()), - Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {} - Err(e) => return Err(e), - } - - if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); - } - - let mut timeout = sock::timeval { - tv_sec: timeout.as_secs() as c_long, - tv_usec: (timeout.subsec_nanos() / 1000) as c_long, - }; - if timeout.tv_sec == 0 && timeout.tv_usec == 0 { - timeout.tv_usec = 1; - } - - let fds = unsafe { - let mut fds = mem::zeroed::<sock::fd_set>(); - fds.fd_count = 1; - fds.fd_array[0] = self.socket; - fds - }; - - let mut writefds = fds; - let mut errorfds = fds; - - match unsafe { sock::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout) } { - sock::SOCKET_ERROR => return Err(io::Error::last_os_error()), - 0 => return Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out")), - _ => { - if writefds.fd_count != 1 { - if let Some(e) = self.take_error()? { - return Err(e); - } - } - Ok(()) - } - } - } - - pub fn local_addr(&self) -> io::Result<SockAddr> { - unsafe { - let mut storage: SOCKADDR_STORAGE = mem::zeroed(); - let mut len = mem::size_of_val(&storage) as c_int; - if sock::getsockname(self.socket, - &mut storage as *mut _ as *mut _, - &mut len) != 0 { - return Err(last_error()) - } - Ok(SockAddr::from_raw_parts(&storage as *const _ as *const _, len)) - } - } - - pub fn peer_addr(&self) -> io::Result<SockAddr> { - unsafe { - let mut storage: SOCKADDR_STORAGE = mem::zeroed(); - let mut len = mem::size_of_val(&storage) as c_int; - if sock::getpeername(self.socket, - &mut storage as *mut _ as *mut _, - &mut len) != 0 { - return Err(last_error()) - } - Ok(SockAddr::from_raw_parts(&storage as *const _ as *const _, len)) - } - } - - pub fn try_clone(&self) -> io::Result<Socket> { - unsafe { - let mut info: sock::WSAPROTOCOL_INFOW = mem::zeroed(); - let r = sock::WSADuplicateSocketW(self.socket, - GetCurrentProcessId(), - &mut info); - if r != 0 { - return Err(io::Error::last_os_error()) - } - let socket = sock::WSASocketW(info.iAddressFamily, - info.iSocketType, - info.iProtocol, - &mut info, - 0, - WSA_FLAG_OVERLAPPED); - let socket = match socket { - sock::INVALID_SOCKET => return Err(last_error()), - n => Socket::from_raw_socket(n as RawSocket), - }; - socket.set_no_inherit()?; - Ok(socket) - } - } - - pub fn accept(&self) -> io::Result<(Socket, SockAddr)> { - unsafe { - let mut storage: SOCKADDR_STORAGE = mem::zeroed(); - let mut len = mem::size_of_val(&storage) as c_int; - let socket = { - sock::accept(self.socket, - &mut storage as *mut _ as *mut _, - &mut len) - }; - let socket = match socket { - sock::INVALID_SOCKET => return Err(last_error()), - socket => Socket::from_raw_socket(socket as RawSocket), - }; - socket.set_no_inherit()?; - let addr = SockAddr::from_raw_parts(&storage as *const _ as *const _, len); - Ok((socket, addr)) - } - } - - pub fn take_error(&self) -> io::Result<Option<io::Error>> { - unsafe { - let raw: c_int = self.getsockopt(SOL_SOCKET, SO_ERROR)?; - if raw == 0 { - Ok(None) - } else { - Ok(Some(io::Error::from_raw_os_error(raw as i32))) - } - } - } - - pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { - unsafe { - let mut nonblocking = nonblocking as c_ulong; - let r = sock::ioctlsocket(self.socket, - sock::FIONBIO as c_int, - &mut nonblocking); - if r == 0 { - Ok(()) - } else { - Err(io::Error::last_os_error()) - } - } - } - - pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { - - let how = match how { - Shutdown::Write => SD_SEND, - Shutdown::Read => SD_RECEIVE, - Shutdown::Both => SD_BOTH, - }; - if unsafe { sock::shutdown(self.socket, how) == 0 } { - Ok(()) - } else { - Err(last_error()) - } - } - - pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> { - unsafe { - let n = { - sock::recv(self.socket, - buf.as_mut_ptr() as *mut c_char, - clamp(buf.len()), - 0) - }; - match n { - sock::SOCKET_ERROR if sock::WSAGetLastError() == sock::WSAESHUTDOWN as i32 => Ok(0), - sock::SOCKET_ERROR => Err(last_error()), - n => Ok(n as usize) - } - } - } - - pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> { - unsafe { - let n = { - sock::recv(self.socket, - buf.as_mut_ptr() as *mut c_char, - clamp(buf.len()), - MSG_PEEK) - }; - match n { - sock::SOCKET_ERROR if sock::WSAGetLastError() == sock::WSAESHUTDOWN as i32 => Ok(0), - sock::SOCKET_ERROR => Err(last_error()), - n => Ok(n as usize) - } - } - } - - pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { - self.recvfrom(buf, 0) - } - - pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { - self.recvfrom(buf, MSG_PEEK) - } - - fn recvfrom(&self, buf: &mut [u8], flags: c_int) - -> io::Result<(usize, SockAddr)> { - unsafe { - let mut storage: SOCKADDR_STORAGE = mem::zeroed(); - let mut addrlen = mem::size_of_val(&storage) as c_int; - - let n = { - sock::recvfrom(self.socket, - buf.as_mut_ptr() as *mut c_char, - clamp(buf.len()), - flags, - &mut storage as *mut _ as *mut _, - &mut addrlen) - }; - let n = match n { - sock::SOCKET_ERROR if sock::WSAGetLastError() == sock::WSAESHUTDOWN as i32 => 0, - sock::SOCKET_ERROR => return Err(last_error()), - n => n as usize, - }; - let addr = SockAddr::from_raw_parts(&storage as *const _ as *const _, addrlen); - Ok((n, addr)) - } - } - - pub fn send(&self, buf: &[u8]) -> io::Result<usize> { - unsafe { - let n = { - sock::send(self.socket, - buf.as_ptr() as *const c_char, - clamp(buf.len()), - 0) - }; - if n == sock::SOCKET_ERROR { - Err(last_error()) - } else { - Ok(n as usize) - } - } - } - - pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> { - unsafe { - let n = { - sock::sendto(self.socket, - buf.as_ptr() as *const c_char, - clamp(buf.len()), - 0, - addr.as_ptr(), - addr.len()) - }; - if n == sock::SOCKET_ERROR { - Err(last_error()) - } else { - Ok(n as usize) - } - } - } - - // ================================================ - - pub fn ttl(&self) -> io::Result<u32> { - unsafe { - let raw: c_int = self.getsockopt(IPPROTO_IP, IP_TTL)?; - Ok(raw as u32) - } - } - - pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { - unsafe { - self.setsockopt(IPPROTO_IP, IP_TTL, ttl as c_int) - } - } - - pub fn only_v6(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(IPPROTO_IPV6 as c_int, - IPV6_V6ONLY)?; - Ok(raw != 0) - } - } - - pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { - unsafe { - self.setsockopt(IPPROTO_IPV6 as c_int, - IPV6_V6ONLY, - only_v6 as c_int) - } - } - - pub fn read_timeout(&self) -> io::Result<Option<Duration>> { - unsafe { - Ok(ms2dur(self.getsockopt(SOL_SOCKET, SO_RCVTIMEO)?)) - } - } - - pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - unsafe { - self.setsockopt(SOL_SOCKET, SO_RCVTIMEO, dur2ms(dur)?) - } - } - - pub fn write_timeout(&self) -> io::Result<Option<Duration>> { - unsafe { - Ok(ms2dur(self.getsockopt(SOL_SOCKET, SO_SNDTIMEO)?)) - } - } - - pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { - unsafe { - self.setsockopt(SOL_SOCKET, SO_SNDTIMEO, dur2ms(dur)?) - } - } - - pub fn nodelay(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(IPPROTO_TCP, - TCP_NODELAY)?; - Ok(raw != 0) - } - } - - pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { - unsafe { - self.setsockopt(IPPROTO_TCP, - TCP_NODELAY, - nodelay as c_int) - } - } - - pub fn broadcast(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(SOL_SOCKET, SO_BROADCAST)?; - Ok(raw != 0) - } - } - - pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { - unsafe { - self.setsockopt(SOL_SOCKET, SO_BROADCAST, broadcast as c_int) - } - } - - pub fn multicast_loop_v4(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(IPPROTO_IP, IP_MULTICAST_LOOP)?; - Ok(raw != 0) - } - } - - pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> { - unsafe { - self.setsockopt(IPPROTO_IP, - IP_MULTICAST_LOOP, - multicast_loop_v4 as c_int) - } - } - - pub fn multicast_ttl_v4(&self) -> io::Result<u32> { - unsafe { - let raw: c_int = self.getsockopt(IPPROTO_IP, IP_MULTICAST_TTL)?; - Ok(raw as u32) - } - } - - pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> { - unsafe { - self.setsockopt(IPPROTO_IP, - IP_MULTICAST_TTL, - multicast_ttl_v4 as c_int) - } - } - - pub fn multicast_loop_v6(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(IPPROTO_IPV6 as c_int, - IPV6_MULTICAST_LOOP)?; - Ok(raw != 0) - } - } - - pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> { - unsafe { - self.setsockopt(IPPROTO_IPV6 as c_int, - IPV6_MULTICAST_LOOP, - multicast_loop_v6 as c_int) - } - } - - pub fn join_multicast_v4(&self, - multiaddr: &Ipv4Addr, - interface: &Ipv4Addr) -> io::Result<()> { - let multiaddr = to_s_addr(multiaddr); - let interface = to_s_addr(interface); - let mreq = IP_MREQ { - imr_multiaddr: IN_ADDR { S_un: multiaddr }, - imr_interface: IN_ADDR { S_un: interface }, - }; - unsafe { - self.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) - } - } - - pub fn join_multicast_v6(&self, - multiaddr: &Ipv6Addr, - interface: u32) -> io::Result<()> { - let multiaddr = to_in6_addr(multiaddr); - let mreq = IPV6_MREQ { - ipv6mr_multiaddr: multiaddr, - ipv6mr_interface: interface, - }; - unsafe { - self.setsockopt(IPPROTO_IP, IPV6_ADD_MEMBERSHIP, mreq) - } - } - - pub fn leave_multicast_v4(&self, - multiaddr: &Ipv4Addr, - interface: &Ipv4Addr) -> io::Result<()> { - let multiaddr = to_s_addr(multiaddr); - let interface = to_s_addr(interface); - let mreq = IP_MREQ { - imr_multiaddr: IN_ADDR { S_un: multiaddr }, - imr_interface: IN_ADDR { S_un: interface }, - }; - unsafe { - self.setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP, mreq) - } - } - - pub fn leave_multicast_v6(&self, - multiaddr: &Ipv6Addr, - interface: u32) -> io::Result<()> { - let multiaddr = to_in6_addr(multiaddr); - let mreq = IPV6_MREQ { - ipv6mr_multiaddr: multiaddr, - ipv6mr_interface: interface, - }; - unsafe { - self.setsockopt(IPPROTO_IP, IPV6_DROP_MEMBERSHIP, mreq) - } - } - - pub fn linger(&self) -> io::Result<Option<Duration>> { - unsafe { - Ok(linger2dur(self.getsockopt(SOL_SOCKET, SO_LINGER)?)) - } - } - - pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> { - unsafe { - self.setsockopt(SOL_SOCKET, SO_LINGER, dur2linger(dur)) - } - } - - pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> { - unsafe { - self.setsockopt(SOL_SOCKET, SO_REUSEADDR, reuse as c_int) - } - } - - pub fn reuse_address(&self) -> io::Result<bool> { - unsafe { - let raw: c_int = self.getsockopt(SOL_SOCKET, SO_REUSEADDR)?; - Ok(raw != 0) - } - } - - pub fn recv_buffer_size(&self) -> io::Result<usize> { - unsafe { - let raw: c_int = self.getsockopt(SOL_SOCKET, SO_RCVBUF)?; - Ok(raw as usize) - } - } - - pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { - unsafe { - // TODO: casting usize to a c_int should be a checked cast - self.setsockopt(SOL_SOCKET, SO_RCVBUF, size as c_int) - } - } - - pub fn send_buffer_size(&self) -> io::Result<usize> { - unsafe { - let raw: c_int = self.getsockopt(SOL_SOCKET, SO_SNDBUF)?; - Ok(raw as usize) - } - } - - pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { - unsafe { - // TODO: casting usize to a c_int should be a checked cast - self.setsockopt(SOL_SOCKET, SO_SNDBUF, size as c_int) - } - } - - pub fn keepalive(&self) -> io::Result<Option<Duration>> { - let mut ka = tcp_keepalive { - onoff: 0, - keepalivetime: 0, - keepaliveinterval: 0, - }; - let n = unsafe { - sock::WSAIoctl(self.socket, - SIO_KEEPALIVE_VALS, - 0 as *mut _, - 0, - &mut ka as *mut _ as *mut _, - mem::size_of_val(&ka) as DWORD, - 0 as *mut _, - 0 as *mut _, - None) - }; - if n == 0 { - Ok(if ka.onoff == 0 { - None - } else if ka.keepaliveinterval == 0 { - None - } else { - let seconds = ka.keepaliveinterval / 1000; - let nanos = (ka.keepaliveinterval % 1000) * 1_000_000; - Some(Duration::new(seconds as u64, nanos as u32)) - }) - } else { - Err(last_error()) - } - } - - pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> { - let ms = dur2ms(keepalive)?; - // TODO: checked casts here - let ka = tcp_keepalive { - onoff: keepalive.is_some() as c_ulong, - keepalivetime: ms as c_ulong, - keepaliveinterval: ms as c_ulong, - }; - let n = unsafe { - sock::WSAIoctl(self.socket, - SIO_KEEPALIVE_VALS, - &ka as *const _ as *mut _, - mem::size_of_val(&ka) as DWORD, - 0 as *mut _, - 0, - 0 as *mut _, - 0 as *mut _, - None) - }; - if n == 0 { - Ok(()) - } else { - Err(last_error()) - } - } - - unsafe fn setsockopt<T>(&self, - opt: c_int, - val: c_int, - payload: T) -> io::Result<()> - where T: Copy, - { - let payload = &payload as *const T as *const c_char; - if sock::setsockopt(self.socket, - opt, - val, - payload, - mem::size_of::<T>() as c_int) == 0 { - Ok(()) - } else { - Err(last_error()) - } - } - - unsafe fn getsockopt<T: Copy>(&self, opt: c_int, val: c_int) -> io::Result<T> { - let mut slot: T = mem::zeroed(); - let mut len = mem::size_of::<T>() as c_int; - if sock::getsockopt(self.socket, - opt, - val, - &mut slot as *mut _ as *mut _, - &mut len) == 0 { - assert_eq!(len as usize, mem::size_of::<T>()); - Ok(slot) - } else { - Err(last_error()) - } - } - - fn set_no_inherit(&self) -> io::Result<()> { - unsafe { - let r = SetHandleInformation(self.socket as HANDLE, - HANDLE_FLAG_INHERIT, - 0); - if r == 0 { - Err(io::Error::last_os_error()) - } else { - Ok(()) - } - } - } -} - -impl Read for Socket { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - <&Socket>::read(&mut &*self, buf) - } -} - -impl<'a> Read for &'a Socket { - fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { - self.recv(buf) - } -} - -impl Write for Socket { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - <&Socket>::write(&mut &*self, buf) - } - - fn flush(&mut self) -> io::Result<()> { - <&Socket>::flush(&mut &*self) - } -} - -impl<'a> Write for &'a Socket { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.send(buf) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -impl fmt::Debug for Socket { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut f = f.debug_struct("Socket"); - f.field("socket", &self.socket); - if let Ok(addr) = self.local_addr() { - f.field("local_addr", &addr); - } - if let Ok(addr) = self.peer_addr() { - f.field("peer_addr", &addr); - } - f.finish() - } -} - -impl AsRawSocket for Socket { - fn as_raw_socket(&self) -> RawSocket { - self.socket as RawSocket - } -} - -impl IntoRawSocket for Socket { - fn into_raw_socket(self) -> RawSocket { - let socket = self.socket; - mem::forget(self); - socket as RawSocket - } -} - -impl FromRawSocket for Socket { - unsafe fn from_raw_socket(socket: RawSocket) -> Socket { - Socket { socket: socket as sock::SOCKET } - } -} - -impl AsRawSocket for ::Socket { - fn as_raw_socket(&self) -> RawSocket { - self.inner.as_raw_socket() - } -} - -impl IntoRawSocket for ::Socket { - fn into_raw_socket(self) -> RawSocket { - self.inner.into_raw_socket() - } -} - -impl FromRawSocket for ::Socket { - unsafe fn from_raw_socket(socket: RawSocket) -> ::Socket { - ::Socket { inner: Socket::from_raw_socket(socket) } - } -} - -impl Drop for Socket { - fn drop(&mut self) { - unsafe { - let _ = sock::closesocket(self.socket); - } - } -} - -impl From<Socket> for net::TcpStream { - fn from(socket: Socket) -> net::TcpStream { - unsafe { net::TcpStream::from_raw_socket(socket.into_raw_socket()) } - } -} - -impl From<Socket> for net::TcpListener { - fn from(socket: Socket) -> net::TcpListener { - unsafe { net::TcpListener::from_raw_socket(socket.into_raw_socket()) } - } -} - -impl From<Socket> for net::UdpSocket { - fn from(socket: Socket) -> net::UdpSocket { - unsafe { net::UdpSocket::from_raw_socket(socket.into_raw_socket()) } - } -} - -impl From<net::TcpStream> for Socket { - fn from(socket: net::TcpStream) -> Socket { - unsafe { Socket::from_raw_socket(socket.into_raw_socket()) } - } -} - -impl From<net::TcpListener> for Socket { - fn from(socket: net::TcpListener) -> Socket { - unsafe { Socket::from_raw_socket(socket.into_raw_socket()) } - } -} - -impl From<net::UdpSocket> for Socket { - fn from(socket: net::UdpSocket) -> Socket { - unsafe { Socket::from_raw_socket(socket.into_raw_socket()) } - } -} - -fn clamp(input: usize) -> c_int { - cmp::min(input, <c_int>::max_value() as usize) as c_int -} - -fn dur2ms(dur: Option<Duration>) -> io::Result<DWORD> { - match dur { - Some(dur) => { - // Note that a duration is a (u64, u32) (seconds, nanoseconds) - // pair, and the timeouts in windows APIs are typically u32 - // milliseconds. To translate, we have two pieces to take care of: - // - // * Nanosecond precision is rounded up - // * Greater than u32::MAX milliseconds (50 days) is rounded up to - // INFINITE (never time out). - let ms = dur.as_secs().checked_mul(1000).and_then(|ms| { - ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000) - }).and_then(|ms| { - ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 {1} else {0}) - }).map(|ms| { - if ms > <DWORD>::max_value() as u64 { - INFINITE - } else { - ms as DWORD - } - }).unwrap_or(INFINITE); - if ms == 0 { - return Err(io::Error::new(io::ErrorKind::InvalidInput, - "cannot set a 0 duration timeout")); - } - Ok(ms) - } - None => Ok(0), - } -} - -fn ms2dur(raw: DWORD) -> Option<Duration> { - if raw == 0 { - None - } else { - let secs = raw / 1000; - let nsec = (raw % 1000) * 1000000; - Some(Duration::new(secs as u64, nsec as u32)) - } -} - -fn to_s_addr(addr: &Ipv4Addr) -> in_addr_S_un { - let octets = addr.octets(); - let res = ::hton(((octets[0] as ULONG) << 24) | - ((octets[1] as ULONG) << 16) | - ((octets[2] as ULONG) << 8) | - ((octets[3] as ULONG) << 0)); - let mut new_addr: in_addr_S_un = unsafe { mem::zeroed() }; - unsafe { *(new_addr.S_addr_mut()) = res }; - new_addr -} - -fn to_in6_addr(addr: &Ipv6Addr) -> in6_addr { - let mut ret_addr: in6_addr_u = unsafe { mem::zeroed() }; - unsafe { *(ret_addr.Byte_mut()) = addr.octets() }; - let mut ret: in6_addr = unsafe { mem::zeroed() }; - ret.u = ret_addr; - ret -} - -fn linger2dur(linger_opt: sock::linger) -> Option<Duration> { - if linger_opt.l_onoff == 0 { - None - } else { - Some(Duration::from_secs(linger_opt.l_linger as u64)) - } -} - -fn dur2linger(dur: Option<Duration>) -> sock::linger { - match dur { - Some(d) => { - sock::linger { - l_onoff: 1, - l_linger: d.as_secs() as u16, - } - } - None => sock::linger { l_onoff: 0, l_linger: 0 }, - } -} diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/src/utils.rs cargo-0.26.0/vendor/socket2-0.3.1/src/utils.rs --- cargo-0.25.0/vendor/socket2-0.3.1/src/utils.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/src/utils.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - - -#[doc(hidden)] -pub trait NetInt { - fn from_be(i: Self) -> Self; - fn to_be(&self) -> Self; -} -macro_rules! doit { - ($($t:ident)*) => ($(impl NetInt for $t { - fn from_be(i: Self) -> Self { <$t>::from_be(i) } - fn to_be(&self) -> Self { <$t>::to_be(*self) } - })*) -} -doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } - -#[doc(hidden)] -pub trait One { - fn one() -> Self; -} - -macro_rules! one { - ($($t:ident)*) => ($( - impl One for $t { fn one() -> $t { 1 } } - )*) -} - -one! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } - - -#[doc(hidden)] -pub trait Zero { - fn zero() -> Self; -} - -macro_rules! zero { - ($($t:ident)*) => ($( - impl Zero for $t { fn zero() -> $t { 0 } } - )*) -} - -zero! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } - diff -Nru cargo-0.25.0/vendor/socket2-0.3.1/.travis.yml cargo-0.26.0/vendor/socket2-0.3.1/.travis.yml --- cargo-0.25.0/vendor/socket2-0.3.1/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.1/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -language: rust -sudo: false - -matrix: - include: - - rust: 1.21.0 - - rust: stable - - os: osx - - rust: beta - - rust: nightly - - - rust: nightly - before_script: - - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH - script: - - cargo doc --no-deps --all-features - after_success: - - travis-cargo --only nightly doc-upload - -script: - - cargo test - - cargo test --features "reuseport unix pair" - -env: - global: - secure: "qibsiOrfM/GjYgYFXycSqKMwIK9ZR4cvHZsSqTtqrtxGq5Q7jTwMqdDl8KHDgX1a4it4tGay+7joex8k2zL6OQ+FljQGQq54EDiGw82HWix/fBpOMjMszw+GEDMG/9hUSb6HFdzAKLPAsBRvIs2QteJ60GhL/w4Z/EmfHlVKMnVsYUjfBf5BNlkv8yFvRMY6QqL+F85N7dDQ7JAgdiP79jR7LP8IlCEu/8pgSrf9pSqAHSC1Co1CaN8uhhMlcIIOZ5qYAK4Xty26r2EDzPm5Lw2Bd7a4maN0x+Be2DJvrnX30QkJNNU1XhxYkeZEeUCYAlUhBE5nBHpyyrbAxv+rJodPeyRl5EVpyqi8htPVmcnuA2XpNoHCud7CnzxaFytGvAC5kp0EgS7f3ac4hTnZXCfP0CvnT5UyWfWv9yLwQycdYcAsV4TnKxVAw4ykApGey+h0dyIM2VnzRPOo9D2ZS+JpzPHtx/PXD7aN7IungfTj4PmT+i00QNzkzJR9BqYKmEDBUcz6MLctg4D6xChhN8Go4hvk22F0RVyvEg1MAvXc07EKeWXG/VZ+H2frcPEceMGRBBHiOfOEE/2utNYgvIcmQxd1hvbm3cQOIjeXU2rGneN86cSmx7zNlfOyJUoBfsgGvSEzRxUueibUCaujB/El70HGrMlTnXeERiyd/2Y=" - -notifications: - email: - on_success: never diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/.appveyor.yml cargo-0.26.0/vendor/socket2-0.3.4/.appveyor.yml --- cargo-0.25.0/vendor/socket2-0.3.4/.appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/.appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,16 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc +install: + - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe + - rustup-init.exe -y --default-host x86_64-pc-windows-msvc + - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin + - if NOT "%TARGET%" == "x86_64-pc-windows-msvc" rustup target add %TARGET% + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test + - cargo test --features reuseport diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/.cargo-checksum.json cargo-0.26.0/vendor/socket2-0.3.4/.cargo-checksum.json --- cargo-0.25.0/vendor/socket2-0.3.4/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"71ebbe82fcdd697244ba7fe6e05e63b5c45910c3927e28469a04947494ff48d8"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/Cargo.toml cargo-0.26.0/vendor/socket2-0.3.4/Cargo.toml --- cargo-0.25.0/vendor/socket2-0.3.4/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,38 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "socket2" +version = "0.3.4" +authors = ["Alex Crichton <alex@alexcrichton.com>"] +description = "Utilities for handling networking sockets with a maximal amount of configuration\npossible intended.\n" +homepage = "https://github.com/alexcrichton/socket2-rs" +readme = "README.md" +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/socket2-rs" +[package.metadata.docs.rs] +all-features = true +[dev-dependencies.tempdir] +version = "0.3" + +[features] +pair = [] +reuseport = [] +unix = [] +[target."cfg(unix)".dependencies.cfg-if] +version = "0.1" + +[target."cfg(unix)".dependencies.libc] +version = "0.2.37" +[target."cfg(windows)".dependencies.winapi] +version = "0.3.3" +features = ["handleapi", "ws2def", "ws2ipdef", "ws2tcpip", "minwindef"] diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/LICENSE-APACHE cargo-0.26.0/vendor/socket2-0.3.4/LICENSE-APACHE --- cargo-0.25.0/vendor/socket2-0.3.4/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/LICENSE-MIT cargo-0.26.0/vendor/socket2-0.3.4/LICENSE-MIT --- cargo-0.25.0/vendor/socket2-0.3.4/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +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. diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/README.md cargo-0.26.0/vendor/socket2-0.3.4/README.md --- cargo-0.25.0/vendor/socket2-0.3.4/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,23 @@ +# socket2-rs + +[![Build Status](https://travis-ci.org/alexcrichton/socket2-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/socket2-rs) +[![Build status](https://ci.appveyor.com/api/projects/status/hovebj1gr4bgm3d9?svg=true)](https://ci.appveyor.com/project/alexcrichton/socket2-rs) + +[Documentation](https://docs.rs/socket2) + +# License + +This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/src/lib.rs cargo-0.26.0/vendor/socket2-0.3.4/src/lib.rs --- cargo-0.25.0/vendor/socket2-0.3.4/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,150 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Utilities for handling sockets +//! +//! This crate is sort of an evolution of the `net2` crate after seeing the +//! issues on it over time. The intention of this crate is to provide as direct +//! as possible access to the system's functionality for sockets as possible. No +//! extra fluff (e.g. multiple syscalls or builders) provided in this crate. As +//! a result using this crate can be a little wordy, but it should give you +//! maximal flexibility over configuration of sockets. +//! +//! # Examples +//! +//! ```no_run +//! use std::net::SocketAddr; +//! use socket2::{Socket, Domain, Type}; +//! +//! // create a TCP listener bound to two addresses +//! let socket = Socket::new(Domain::ipv6(), Type::stream(), None).unwrap(); +//! +//! socket.bind(&"[::1]:12345".parse::<SocketAddr>().unwrap().into()).unwrap(); +//! socket.set_only_v6(false); +//! socket.listen(128).unwrap(); +//! +//! let listener = socket.into_tcp_listener(); +//! // ... +//! ``` + +#![doc(html_root_url = "https://docs.rs/socket2/0.3")] +#![deny(missing_docs)] + +#[cfg(unix)] +#[macro_use] +extern crate cfg_if; +#[cfg(unix)] +extern crate libc; + +#[cfg(windows)] +extern crate winapi; + +#[cfg(test)] +extern crate tempdir; + +use utils::NetInt; + +#[cfg(unix)] +use libc::{sockaddr_storage, socklen_t}; +#[cfg(windows)] +use winapi::shared::ws2def::SOCKADDR_STORAGE as sockaddr_storage; +#[cfg(windows)] +use winapi::um::ws2tcpip::socklen_t; + +mod sockaddr; +mod socket; +mod utils; + +#[cfg(unix)] +#[path = "sys/unix/mod.rs"] +mod sys; +#[cfg(windows)] +#[path = "sys/windows.rs"] +mod sys; + +/// Newtype, owned, wrapper around a system socket. +/// +/// This type simply wraps an instance of a file descriptor (`c_int`) on Unix +/// and an instance of `SOCKET` on Windows. This is the main type exported by +/// this crate and is intended to mirror the raw semantics of sockets on +/// platforms as closely as possible. Almost all methods correspond to +/// precisely one libc or OS API call which is essentially just a "Rustic +/// translation" of what's below. +/// +/// # Examples +/// +/// ```no_run +/// use std::net::SocketAddr; +/// use socket2::{Socket, Domain, Type, SockAddr}; +/// +/// // create a TCP listener bound to two addresses +/// let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); +/// +/// socket.bind(&"127.0.0.1:12345".parse::<SocketAddr>().unwrap().into()).unwrap(); +/// socket.bind(&"127.0.0.1:12346".parse::<SocketAddr>().unwrap().into()).unwrap(); +/// socket.listen(128).unwrap(); +/// +/// let listener = socket.into_tcp_listener(); +/// // ... +/// ``` +pub struct Socket { + inner: sys::Socket, +} + +/// The address of a socket. +/// +/// `SockAddr`s may be constructed directly to and from the standard library +/// `SocketAddr`, `SocketAddrV4`, and `SocketAddrV6` types. +pub struct SockAddr { + storage: sockaddr_storage, + len: socklen_t, +} + +/// Specification of the communication domain for a socket. +/// +/// This is a newtype wrapper around an integer which provides a nicer API in +/// addition to an injection point for documentation. Convenience constructors +/// such as `Domain::ipv4`, `Domain::ipv6`, etc, are provided to avoid reaching +/// into libc for various constants. +/// +/// This type is freely interconvertible with the `i32` type, however, if a raw +/// value needs to be provided. +#[derive(Copy, Clone)] +pub struct Domain(i32); + +/// Specification of communication semantics on a socket. +/// +/// This is a newtype wrapper around an integer which provides a nicer API in +/// addition to an injection point for documentation. Convenience constructors +/// such as `Type::stream`, `Type::dgram`, etc, are provided to avoid reaching +/// into libc for various constants. +/// +/// This type is freely interconvertible with the `i32` type, however, if a raw +/// value needs to be provided. +#[derive(Copy, Clone)] +pub struct Type(i32); + +/// Protocol specification used for creating sockets via `Socket::new`. +/// +/// This is a newtype wrapper around an integer which provides a nicer API in +/// addition to an injection point for documentation. +/// +/// This type is freely interconvertible with the `i32` type, however, if a raw +/// value needs to be provided. +#[derive(Copy, Clone)] +pub struct Protocol(i32); + +fn hton<I: NetInt>(i: I) -> I { + i.to_be() +} + +fn ntoh<I: NetInt>(i: I) -> I { + I::from_be(i) +} diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/src/sockaddr.rs cargo-0.26.0/vendor/socket2-0.3.4/src/sockaddr.rs --- cargo-0.25.0/vendor/socket2-0.3.4/src/sockaddr.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/src/sockaddr.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,212 @@ +use std::fmt; +use std::mem; +use std::net::{SocketAddr, SocketAddrV4, SocketAddrV6}; +use std::ptr; + +#[cfg(unix)] +use libc::{sa_family_t, sockaddr, sockaddr_in, sockaddr_storage, socklen_t, AF_INET6, + sockaddr_in6, AF_INET}; +#[cfg(windows)] +use winapi::shared::ws2def::{ADDRESS_FAMILY as sa_family_t, AF_INET6, SOCKADDR as sockaddr, + SOCKADDR_IN as sockaddr_in, SOCKADDR_STORAGE as sockaddr_storage, + AF_INET}; +#[cfg(windows)] +use winapi::um::ws2tcpip::socklen_t; +#[cfg(windows)] +use winapi::shared::ws2ipdef::SOCKADDR_IN6_LH as sockaddr_in6; + +use SockAddr; + +impl fmt::Debug for SockAddr { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + let mut builder = fmt.debug_struct("SockAddr"); + builder.field("family", &self.family()); + if let Some(addr) = self.as_inet() { + builder.field("inet", &addr); + } else if let Some(addr) = self.as_inet6() { + builder.field("inet6", &addr); + } + builder.finish() + } +} + +impl SockAddr { + /// Constructs a `SockAddr` from its raw components. + pub unsafe fn from_raw_parts(addr: *const sockaddr, len: socklen_t) -> SockAddr { + let mut storage = mem::uninitialized::<sockaddr_storage>(); + ptr::copy_nonoverlapping( + addr as *const _ as *const u8, + &mut storage as *mut _ as *mut u8, + len as usize, + ); + + SockAddr { + storage: storage, + len: len, + } + } + + /// Constructs a `SockAddr` with the family `AF_UNIX` and the provided path. + /// + /// This function is only available on Unix when the `unix` feature is + /// enabled. + /// + /// # Failure + /// + /// Returns an error if the path is longer than `SUN_LEN`. + #[cfg(all(unix, feature = "unix"))] + pub fn unix<P>(path: P) -> ::std::io::Result<SockAddr> + where + P: AsRef<::std::path::Path>, + { + use std::cmp::Ordering; + use std::io; + use std::os::unix::ffi::OsStrExt; + use libc::{c_char, sockaddr_un, AF_UNIX}; + + unsafe { + let mut addr = mem::zeroed::<sockaddr_un>(); + addr.sun_family = AF_UNIX as sa_family_t; + + let bytes = path.as_ref().as_os_str().as_bytes(); + + match (bytes.get(0), bytes.len().cmp(&addr.sun_path.len())) { + // Abstract paths don't need a null terminator + (Some(&0), Ordering::Greater) => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "path must be no longer than SUN_LEN", + )); + } + (Some(&0), _) => {} + (_, Ordering::Greater) | (_, Ordering::Equal) => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "path must be shorter than SUN_LEN", + )); + } + _ => {} + } + + for (dst, src) in addr.sun_path.iter_mut().zip(bytes) { + *dst = *src as c_char; + } + // null byte for pathname is already there since we zeroed up front + + let base = &addr as *const _ as usize; + let path = &addr.sun_path as *const _ as usize; + let sun_path_offset = path - base; + + let mut len = sun_path_offset + bytes.len(); + match bytes.get(0) { + Some(&0) | None => {} + Some(_) => len += 1, + } + Ok(SockAddr::from_raw_parts( + &addr as *const _ as *const _, + len as socklen_t, + )) + } + } + + unsafe fn as_<T>(&self, family: sa_family_t) -> Option<T> { + if self.storage.ss_family != family { + return None; + } + + Some(mem::transmute_copy(&self.storage)) + } + + /// Returns this address as a `SocketAddrV4` if it is in the `AF_INET` + /// family. + pub fn as_inet(&self) -> Option<SocketAddrV4> { + unsafe { self.as_(AF_INET as sa_family_t) } + } + + /// Returns this address as a `SocketAddrV4` if it is in the `AF_INET6` + /// family. + pub fn as_inet6(&self) -> Option<SocketAddrV6> { + unsafe { self.as_(AF_INET6 as sa_family_t) } + } + + /// Returns this address's family. + pub fn family(&self) -> sa_family_t { + self.storage.ss_family + } + + /// Returns the size of this address in bytes. + pub fn len(&self) -> socklen_t { + self.len + } + + /// Returns a raw pointer to the address. + pub fn as_ptr(&self) -> *const sockaddr { + &self.storage as *const _ as *const _ + } +} + +// SocketAddrV4 and SocketAddrV6 are just wrappers around sockaddr_in and sockaddr_in6 + +// check to make sure that the sizes at least match up +fn _size_checks(v4: SocketAddrV4, v6: SocketAddrV6) { + unsafe { + mem::transmute::<SocketAddrV4, sockaddr_in>(v4); + mem::transmute::<SocketAddrV6, sockaddr_in6>(v6); + } +} + +impl From<SocketAddrV4> for SockAddr { + fn from(addr: SocketAddrV4) -> SockAddr { + unsafe { + SockAddr::from_raw_parts( + &addr as *const _ as *const _, + mem::size_of::<SocketAddrV4>() as socklen_t, + ) + } + } +} + +impl From<SocketAddrV6> for SockAddr { + fn from(addr: SocketAddrV6) -> SockAddr { + unsafe { + SockAddr::from_raw_parts( + &addr as *const _ as *const _, + mem::size_of::<SocketAddrV6>() as socklen_t, + ) + } + } +} + +impl From<SocketAddr> for SockAddr { + fn from(addr: SocketAddr) -> SockAddr { + match addr { + SocketAddr::V4(addr) => addr.into(), + SocketAddr::V6(addr) => addr.into(), + } + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn inet() { + let raw = "127.0.0.1:80".parse::<SocketAddrV4>().unwrap(); + let addr = SockAddr::from(raw); + assert!(addr.as_inet6().is_none()); + let addr = addr.as_inet().unwrap(); + assert_eq!(raw, addr); + } + + #[test] + fn inet6() { + let raw = "[2001:db8::ff00:42:8329]:80" + .parse::<SocketAddrV6>() + .unwrap(); + let addr = SockAddr::from(raw); + assert!(addr.as_inet().is_none()); + let addr = addr.as_inet6().unwrap(); + assert_eq!(raw, addr); + } +} diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/src/socket.rs cargo-0.26.0/vendor/socket2-0.3.4/src/socket.rs --- cargo-0.25.0/vendor/socket2-0.3.4/src/socket.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/src/socket.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,973 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::fmt; +use std::io::{self, Read, Write}; +use std::net::{self, Ipv4Addr, Ipv6Addr, Shutdown}; +use std::time::Duration; +#[cfg(all(unix, feature = "unix"))] +use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream}; + +#[cfg(unix)] +use libc as c; +#[cfg(windows)] +use winapi::shared::ws2def as c; + +use sys; +use {Domain, Protocol, SockAddr, Socket, Type}; + +impl Socket { + /// Creates a new socket ready to be configured. + /// + /// This function corresponds to `socket(2)` and simply creates a new + /// socket, no other configuration is done and further functions must be + /// invoked to configure this socket. + pub fn new(domain: Domain, type_: Type, protocol: Option<Protocol>) -> io::Result<Socket> { + let protocol = protocol.map(|p| p.0).unwrap_or(0); + Ok(Socket { + inner: sys::Socket::new(domain.0, type_.0, protocol)?, + }) + } + + /// Creates a pair of sockets which are connected to each other. + /// + /// This function corresponds to `socketpair(2)`. + /// + /// This function is only available on Unix when the `pair` feature is + /// enabled. + #[cfg(all(unix, feature = "pair"))] + pub fn pair( + domain: Domain, + type_: Type, + protocol: Option<Protocol>, + ) -> io::Result<(Socket, Socket)> { + let protocol = protocol.map(|p| p.0).unwrap_or(0); + let sockets = sys::Socket::pair(domain.0, type_.0, protocol)?; + Ok((Socket { inner: sockets.0 }, Socket { inner: sockets.1 })) + } + + /// Consumes this `Socket`, converting it to a `TcpStream`. + pub fn into_tcp_stream(self) -> net::TcpStream { + self.into() + } + + /// Consumes this `Socket`, converting it to a `TcpListener`. + pub fn into_tcp_listener(self) -> net::TcpListener { + self.into() + } + + /// Consumes this `Socket`, converting it to a `UdpSocket`. + pub fn into_udp_socket(self) -> net::UdpSocket { + self.into() + } + + /// Consumes this `Socket`, converting it into a `UnixStream`. + /// + /// This function is only available on Unix when the `unix` feature is + /// enabled. + #[cfg(all(unix, feature = "unix"))] + pub fn into_unix_stream(self) -> UnixStream { + self.into() + } + + /// Consumes this `Socket`, converting it into a `UnixListener`. + /// + /// This function is only available on Unix when the `unix` feature is + /// enabled. + #[cfg(all(unix, feature = "unix"))] + pub fn into_unix_listener(self) -> UnixListener { + self.into() + } + + /// Consumes this `Socket`, converting it into a `UnixDatagram`. + /// + /// This function is only available on Unix when the `unix` feature is + /// enabled. + #[cfg(all(unix, feature = "unix"))] + pub fn into_unix_datagram(self) -> UnixDatagram { + self.into() + } + + /// Initiate a connection on this socket to the specified address. + /// + /// This function directly corresponds to the connect(2) function on Windows + /// and Unix. + /// + /// An error will be returned if `listen` or `connect` has already been + /// called on this builder. + pub fn connect(&self, addr: &SockAddr) -> io::Result<()> { + self.inner.connect(addr) + } + + /// Initiate a connection on this socket to the specified address, only + /// only waiting for a certain period of time for the connection to be + /// established. + /// + /// Unlike many other methods on `Socket`, this does *not* correspond to a + /// single C function. It sets the socket to nonblocking mode, connects via + /// connect(2), and then waits for the connection to complete with poll(2) + /// on Unix and select on Windows. When the connection is complete, the + /// socket is set back to blocking mode. On Unix, this will loop over + /// `EINTR` errors. + /// + /// # Warnings + /// + /// The nonblocking state of the socket is overridden by this function - + /// it will be returned in blocking mode on success, and in an indeterminate + /// state on failure. + /// + /// If the connection request times out, it may still be processing in the + /// background - a second call to `connect` or `connect_timeout` may fail. + pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> { + self.inner.connect_timeout(addr, timeout) + } + + /// Binds this socket to the specified address. + /// + /// This function directly corresponds to the bind(2) function on Windows + /// and Unix. + pub fn bind(&self, addr: &SockAddr) -> io::Result<()> { + self.inner.bind(addr) + } + + /// Mark a socket as ready to accept incoming connection requests using + /// accept() + /// + /// This function directly corresponds to the listen(2) function on Windows + /// and Unix. + /// + /// An error will be returned if `listen` or `connect` has already been + /// called on this builder. + pub fn listen(&self, backlog: i32) -> io::Result<()> { + self.inner.listen(backlog) + } + + /// Accept a new incoming connection from this listener. + /// + /// This function will block the calling thread until a new connection is + /// established. When established, the corresponding `Socket` and the + /// remote peer's address will be returned. + pub fn accept(&self) -> io::Result<(Socket, SockAddr)> { + self.inner + .accept() + .map(|(socket, addr)| (Socket { inner: socket }, addr)) + } + + /// Returns the socket address of the local half of this TCP connection. + pub fn local_addr(&self) -> io::Result<SockAddr> { + self.inner.local_addr() + } + + /// Returns the socket address of the remote peer of this TCP connection. + pub fn peer_addr(&self) -> io::Result<SockAddr> { + self.inner.peer_addr() + } + + /// Creates a new independently owned handle to the underlying socket. + /// + /// The returned `TcpStream` is a reference to the same stream that this + /// object references. Both handles will read and write the same stream of + /// data, and options set on one stream will be propagated to the other + /// stream. + pub fn try_clone(&self) -> io::Result<Socket> { + self.inner.try_clone().map(|s| Socket { inner: s }) + } + + /// Get the value of the `SO_ERROR` option on this socket. + /// + /// This will retrieve the stored error in the underlying socket, clearing + /// the field in the process. This can be useful for checking errors between + /// calls. + pub fn take_error(&self) -> io::Result<Option<io::Error>> { + self.inner.take_error() + } + + /// Moves this TCP stream into or out of nonblocking mode. + /// + /// On Unix this corresponds to calling fcntl, and on Windows this + /// corresponds to calling ioctlsocket. + pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + self.inner.set_nonblocking(nonblocking) + } + + /// Shuts down the read, write, or both halves of this connection. + /// + /// This function will cause all pending and future I/O on the specified + /// portions to return immediately with an appropriate value. + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + self.inner.shutdown(how) + } + + /// Receives data on the socket from the remote address to which it is + /// connected. + /// + /// The [`connect`] method will connect this socket to a remote address. This + /// method will fail if the socket is not connected. + /// + /// [`connect`]: #method.connect + pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> { + self.inner.recv(buf) + } + + /// Receives data on the socket from the remote adress to which it is + /// connected, without removing that data from the queue. On success, + /// returns the number of bytes peeked. + /// + /// Successive calls return the same data. This is accomplished by passing + /// `MSG_PEEK` as a flag to the underlying `recv` system call. + pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> { + self.inner.peek(buf) + } + + /// Receives data from the socket. On success, returns the number of bytes + /// read and the address from whence the data came. + pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { + self.inner.recv_from(buf) + } + + /// Receives data from the socket, without removing it from the queue. + /// + /// Successive calls return the same data. This is accomplished by passing + /// `MSG_PEEK` as a flag to the underlying `recvfrom` system call. + /// + /// On success, returns the number of bytes peeked and the address from + /// whence the data came. + pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { + self.inner.peek_from(buf) + } + + /// Sends data on the socket to a connected peer. + /// + /// This is typically used on TCP sockets or datagram sockets which have + /// been connected. + /// + /// On success returns the number of bytes that were sent. + pub fn send(&self, buf: &[u8]) -> io::Result<usize> { + self.inner.send(buf) + } + + /// Sends data on the socket to the given address. On success, returns the + /// number of bytes written. + /// + /// This is typically used on UDP or datagram-oriented sockets. On success + /// returns the number of bytes that were sent. + pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> { + self.inner.send_to(buf, addr) + } + + // ================================================ + + /// Gets the value of the `IP_TTL` option for this socket. + /// + /// For more information about this option, see [`set_ttl`][link]. + /// + /// [link]: #method.set_ttl + pub fn ttl(&self) -> io::Result<u32> { + self.inner.ttl() + } + + /// Sets the value for the `IP_TTL` option on this socket. + /// + /// This value sets the time-to-live field that is used in every packet sent + /// from this socket. + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + self.inner.set_ttl(ttl) + } + + /// Gets the value of the `IPV6_UNICAST_HOPS` option for this socket. + /// + /// Specifies the hop limit for ipv6 unicast packets + pub fn unicast_hops_v6(&self) -> io::Result<u32> { + self.inner.unicast_hops_v6() + } + + /// Sets the value for the `IPV6_UNICAST_HOPS` option on this socket. + /// + /// Specifies the hop limit for ipv6 unicast packets + pub fn set_unicast_hops_v6(&self, ttl: u32) -> io::Result<()> { + self.inner.set_unicast_hops_v6(ttl) + } + + /// Gets the value of the `IPV6_V6ONLY` option for this socket. + /// + /// For more information about this option, see [`set_only_v6`][link]. + /// + /// [link]: #method.set_only_v6 + pub fn only_v6(&self) -> io::Result<bool> { + self.inner.only_v6() + } + + /// Sets the value for the `IPV6_V6ONLY` option on this socket. + /// + /// If this is set to `true` then the socket is restricted to sending and + /// receiving IPv6 packets only. In this case two IPv4 and IPv6 applications + /// can bind the same port at the same time. + /// + /// If this is set to `false` then the socket can be used to send and + /// receive packets from an IPv4-mapped IPv6 address. + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + self.inner.set_only_v6(only_v6) + } + + /// Returns the read timeout of this socket. + /// + /// If the timeout is `None`, then `read` calls will block indefinitely. + pub fn read_timeout(&self) -> io::Result<Option<Duration>> { + self.inner.read_timeout() + } + + /// Sets the read timeout to the timeout specified. + /// + /// If the value specified is `None`, then `read` calls will block + /// indefinitely. It is an error to pass the zero `Duration` to this + /// method. + pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.inner.set_read_timeout(dur) + } + + /// Returns the write timeout of this socket. + /// + /// If the timeout is `None`, then `write` calls will block indefinitely. + pub fn write_timeout(&self) -> io::Result<Option<Duration>> { + self.inner.write_timeout() + } + + /// Sets the write timeout to the timeout specified. + /// + /// If the value specified is `None`, then `write` calls will block + /// indefinitely. It is an error to pass the zero `Duration` to this + /// method. + pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + self.inner.set_write_timeout(dur) + } + + /// Gets the value of the `TCP_NODELAY` option on this socket. + /// + /// For more information about this option, see [`set_nodelay`][link]. + /// + /// [link]: #method.set_nodelay + pub fn nodelay(&self) -> io::Result<bool> { + self.inner.nodelay() + } + + /// Sets the value of the `TCP_NODELAY` option on this socket. + /// + /// If set, this option disables the Nagle algorithm. This means that + /// segments are always sent as soon as possible, even if there is only a + /// small amount of data. When not set, data is buffered until there is a + /// sufficient amount to send out, thereby avoiding the frequent sending of + /// small packets. + pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + self.inner.set_nodelay(nodelay) + } + + /// Sets the value of the `SO_BROADCAST` option for this socket. + /// + /// When enabled, this socket is allowed to send packets to a broadcast + /// address. + pub fn broadcast(&self) -> io::Result<bool> { + self.inner.broadcast() + } + + /// Gets the value of the `SO_BROADCAST` option for this socket. + /// + /// For more information about this option, see + /// [`set_broadcast`][link]. + /// + /// [link]: #method.set_broadcast + pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { + self.inner.set_broadcast(broadcast) + } + + /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_loop_v4`][link]. + /// + /// [link]: #method.set_multicast_loop_v4 + pub fn multicast_loop_v4(&self) -> io::Result<bool> { + self.inner.multicast_loop_v4() + } + + /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket. + /// + /// If enabled, multicast packets will be looped back to the local socket. + /// Note that this may not have any affect on IPv6 sockets. + pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> { + self.inner.set_multicast_loop_v4(multicast_loop_v4) + } + + /// Gets the value of the `IP_MULTICAST_TTL` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_ttl_v4`][link]. + /// + /// [link]: #method.set_multicast_ttl_v4 + pub fn multicast_ttl_v4(&self) -> io::Result<u32> { + self.inner.multicast_ttl_v4() + } + + /// Sets the value of the `IP_MULTICAST_TTL` option for this socket. + /// + /// Indicates the time-to-live value of outgoing multicast packets for + /// this socket. The default value is 1 which means that multicast packets + /// don't leave the local network unless explicitly requested. + /// + /// Note that this may not have any affect on IPv6 sockets. + pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> { + self.inner.set_multicast_ttl_v4(multicast_ttl_v4) + } + + /// Gets the value of the `IPV6_MULTICAST_HOPS` option for this socket + /// + /// For more information about this option, see + /// [`set_multicast_hops_v6`][link]. + /// + /// [link]: #method.set_multicast_hops_v6 + pub fn multicast_hops_v6(&self) -> io::Result<u32> { + self.inner.multicast_hops_v6() + } + + /// Sets the value of the `IPV6_MULTICAST_HOPS` option for this socket + /// + /// Indicates the number of "routers" multicast packets will transit for + /// this socket. The default value is 1 which means that multicast packets + /// don't leave the local network unless explicitly requested. + pub fn set_multicast_hops_v6(&self, hops: u32) -> io::Result<()> { + self.inner.set_multicast_hops_v6(hops) + } + + /// Gets the value of the `IP_MULTICAST_IF` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_if_v4`][link]. + /// + /// [link]: #method.set_multicast_if_v4 + /// + /// Returns the interface to use for routing multicast packets. + pub fn multicast_if_v4(&self) -> io::Result<Ipv4Addr> { + self.inner.multicast_if_v4() + } + + /// Sets the value of the `IP_MULTICAST_IF` option for this socket. + /// + /// Specifies the interface to use for routing multicast packets. + pub fn set_multicast_if_v4(&self, interface: &Ipv4Addr) -> io::Result<()> { + self.inner.set_multicast_if_v4(interface) + } + + /// Gets the value of the `IPV6_MULTICAST_IF` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_if_v6`][link]. + /// + /// [link]: #method.set_multicast_if_v6 + /// + /// Returns the interface to use for routing multicast packets. + pub fn multicast_if_v6(&self) -> io::Result<u32> { + self.inner.multicast_if_v6() + } + + /// Sets the value of the `IPV6_MULTICAST_IF` option for this socket. + /// + /// Specifies the interface to use for routing multicast packets. Unlike ipv4, this + /// is generally required in ipv6 contexts where network routing prefixes may + /// overlap. + pub fn set_multicast_if_v6(&self, interface: u32) -> io::Result<()> { + self.inner.set_multicast_if_v6(interface) + } + + /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket. + /// + /// For more information about this option, see + /// [`set_multicast_loop_v6`][link]. + /// + /// [link]: #method.set_multicast_loop_v6 + pub fn multicast_loop_v6(&self) -> io::Result<bool> { + self.inner.multicast_loop_v6() + } + + /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket. + /// + /// Controls whether this socket sees the multicast packets it sends itself. + /// Note that this may not have any affect on IPv4 sockets. + pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> { + self.inner.set_multicast_loop_v6(multicast_loop_v6) + } + + /// Executes an operation of the `IP_ADD_MEMBERSHIP` type. + /// + /// This function specifies a new multicast group for this socket to join. + /// The address must be a valid multicast address, and `interface` is the + /// address of the local interface with which the system should join the + /// multicast group. If it's equal to `INADDR_ANY` then an appropriate + /// interface is chosen by the system. + pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + self.inner.join_multicast_v4(multiaddr, interface) + } + + /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type. + /// + /// This function specifies a new multicast group for this socket to join. + /// The address must be a valid multicast address, and `interface` is the + /// index of the interface to join/leave (or 0 to indicate any interface). + pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + self.inner.join_multicast_v6(multiaddr, interface) + } + + /// Executes an operation of the `IP_DROP_MEMBERSHIP` type. + /// + /// For more information about this option, see + /// [`join_multicast_v4`][link]. + /// + /// [link]: #method.join_multicast_v4 + pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + self.inner.leave_multicast_v4(multiaddr, interface) + } + + /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type. + /// + /// For more information about this option, see + /// [`join_multicast_v6`][link]. + /// + /// [link]: #method.join_multicast_v6 + pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + self.inner.leave_multicast_v6(multiaddr, interface) + } + + /// Reads the linger duration for this socket by getting the SO_LINGER + /// option + pub fn linger(&self) -> io::Result<Option<Duration>> { + self.inner.linger() + } + + /// Sets the linger duration of this socket by setting the SO_LINGER option + pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> { + self.inner.set_linger(dur) + } + + /// Check the `SO_REUSEADDR` option on this socket. + pub fn reuse_address(&self) -> io::Result<bool> { + self.inner.reuse_address() + } + + /// Set value for the `SO_REUSEADDR` option on this socket. + /// + /// This indicates that futher calls to `bind` may allow reuse of local + /// addresses. For IPv4 sockets this means that a socket may bind even when + /// there's a socket already listening on this port. + pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> { + self.inner.set_reuse_address(reuse) + } + + /// Gets the value of the `SO_RCVBUF` option on this socket. + /// + /// For more information about this option, see + /// [`set_recv_buffer_size`][link]. + /// + /// [link]: #method.set_recv_buffer_size + pub fn recv_buffer_size(&self) -> io::Result<usize> { + self.inner.recv_buffer_size() + } + + /// Sets the value of the `SO_RCVBUF` option on this socket. + /// + /// Changes the size of the operating system's receive buffer associated + /// with the socket. + pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { + self.inner.set_recv_buffer_size(size) + } + + /// Gets the value of the `SO_SNDBUF` option on this socket. + /// + /// For more information about this option, see [`set_send_buffer`][link]. + /// + /// [link]: #method.set_send_buffer + pub fn send_buffer_size(&self) -> io::Result<usize> { + self.inner.send_buffer_size() + } + + /// Sets the value of the `SO_SNDBUF` option on this socket. + /// + /// Changes the size of the operating system's send buffer associated with + /// the socket. + pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { + self.inner.set_send_buffer_size(size) + } + + /// Returns whether keepalive messages are enabled on this socket, and if so + /// the duration of time between them. + /// + /// For more information about this option, see [`set_keepalive`][link]. + /// + /// [link]: #method.set_keepalive + pub fn keepalive(&self) -> io::Result<Option<Duration>> { + self.inner.keepalive() + } + + /// Sets whether keepalive messages are enabled to be sent on this socket. + /// + /// On Unix, this option will set the `SO_KEEPALIVE` as well as the + /// `TCP_KEEPALIVE` or `TCP_KEEPIDLE` option (depending on your platform). + /// On Windows, this will set the `SIO_KEEPALIVE_VALS` option. + /// + /// If `None` is specified then keepalive messages are disabled, otherwise + /// the duration specified will be the time to remain idle before sending a + /// TCP keepalive probe. + /// + /// Some platforms specify this value in seconds, so sub-second + /// specifications may be omitted. + pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> { + self.inner.set_keepalive(keepalive) + } + + /// Check the value of the `SO_REUSEPORT` option on this socket. + /// + /// This function is only available on Unix when the `reuseport` feature is + /// enabled. + #[cfg(all(unix, feature = "reuseport"))] + pub fn reuse_port(&self) -> io::Result<bool> { + self.inner.reuse_port() + } + + /// Set value for the `SO_REUSEPORT` option on this socket. + /// + /// This indicates that futher calls to `bind` may allow reuse of local + /// addresses. For IPv4 sockets this means that a socket may bind even when + /// there's a socket already listening on this port. + /// + /// This function is only available on Unix when the `reuseport` feature is + /// enabled. + #[cfg(all(unix, feature = "reuseport"))] + pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> { + self.inner.set_reuse_port(reuse) + } +} + +impl Read for Socket { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.inner.read(buf) + } +} + +impl<'a> Read for &'a Socket { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + (&self.inner).read(buf) + } +} + +impl Write for Socket { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.inner.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() + } +} + +impl<'a> Write for &'a Socket { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + (&self.inner).write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + (&self.inner).flush() + } +} + +impl fmt::Debug for Socket { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} + +impl From<net::TcpStream> for Socket { + fn from(socket: net::TcpStream) -> Socket { + Socket { + inner: socket.into(), + } + } +} + +impl From<net::TcpListener> for Socket { + fn from(socket: net::TcpListener) -> Socket { + Socket { + inner: socket.into(), + } + } +} + +impl From<net::UdpSocket> for Socket { + fn from(socket: net::UdpSocket) -> Socket { + Socket { + inner: socket.into(), + } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<UnixStream> for Socket { + fn from(socket: UnixStream) -> Socket { + Socket { + inner: socket.into(), + } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<UnixListener> for Socket { + fn from(socket: UnixListener) -> Socket { + Socket { + inner: socket.into(), + } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<UnixDatagram> for Socket { + fn from(socket: UnixDatagram) -> Socket { + Socket { + inner: socket.into(), + } + } +} + +impl From<Socket> for net::TcpStream { + fn from(socket: Socket) -> net::TcpStream { + socket.inner.into() + } +} + +impl From<Socket> for net::TcpListener { + fn from(socket: Socket) -> net::TcpListener { + socket.inner.into() + } +} + +impl From<Socket> for net::UdpSocket { + fn from(socket: Socket) -> net::UdpSocket { + socket.inner.into() + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<Socket> for UnixStream { + fn from(socket: Socket) -> UnixStream { + socket.inner.into() + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<Socket> for UnixListener { + fn from(socket: Socket) -> UnixListener { + socket.inner.into() + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<Socket> for UnixDatagram { + fn from(socket: Socket) -> UnixDatagram { + socket.inner.into() + } +} + +impl Domain { + /// Domain for IPv4 communication, corresponding to `AF_INET`. + pub fn ipv4() -> Domain { + Domain(c::AF_INET) + } + + /// Domain for IPv6 communication, corresponding to `AF_INET6`. + pub fn ipv6() -> Domain { + Domain(c::AF_INET6) + } + + /// Domain for Unix socket communication, corresponding to `AF_UNIX`. + /// + /// This function is only available on Unix when the `unix` feature is + /// activated. + #[cfg(all(unix, feature = "unix"))] + pub fn unix() -> Domain { + Domain(c::AF_UNIX) + } +} + +impl From<i32> for Domain { + fn from(a: i32) -> Domain { + Domain(a) + } +} + +impl From<Domain> for i32 { + fn from(a: Domain) -> i32 { + a.into() + } +} + +impl Type { + /// Type corresponding to `SOCK_STREAM` + /// + /// Used for protocols such as TCP. + pub fn stream() -> Type { + Type(c::SOCK_STREAM) + } + + /// Type corresponding to `SOCK_DGRAM` + /// + /// Used for protocols such as UDP. + pub fn dgram() -> Type { + Type(c::SOCK_DGRAM) + } + + /// Type corresponding to `SOCK_SEQPACKET` + pub fn seqpacket() -> Type { + Type(c::SOCK_SEQPACKET) + } + + /// Type corresponding to `SOCK_RAW` + pub fn raw() -> Type { + Type(c::SOCK_RAW) + } +} + +impl ::Protocol { + /// Protocol corresponding to `ICMPv4` + pub fn icmpv4() -> Self { + ::Protocol(sys::IPPROTO_ICMP) + } + + /// Protocol corresponding to `ICMPv6` + pub fn icmpv6() -> Self { + ::Protocol(sys::IPPROTO_ICMPV6) + } + + /// Protocol corresponding to `TCP` + pub fn tcp() -> Self { + ::Protocol(sys::IPPROTO_TCP) + } + + /// Protocol corresponding to `UDP` + pub fn udp() -> Self { + ::Protocol(sys::IPPROTO_UDP) + } +} + +impl From<i32> for Type { + fn from(a: i32) -> Type { + Type(a) + } +} + +impl From<Type> for i32 { + fn from(a: Type) -> i32 { + a.into() + } +} + +impl From<i32> for Protocol { + fn from(a: i32) -> Protocol { + Protocol(a) + } +} + +impl From<Protocol> for i32 { + fn from(a: Protocol) -> i32 { + a.into() + } +} + +#[cfg(test)] +mod test { + use std::net::SocketAddr; + + use super::*; + + #[test] + fn connect_timeout_unrouteable() { + // this IP is unroutable, so connections should always time out + let addr = "10.255.255.1:80".parse::<SocketAddr>().unwrap().into(); + + let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); + match socket.connect_timeout(&addr, Duration::from_millis(250)) { + Ok(_) => panic!("unexpected success"), + Err(ref e) if e.kind() == io::ErrorKind::TimedOut => {} + Err(e) => panic!("unexpected error {}", e), + } + } + + #[test] + fn connect_timeout_unbound() { + // bind and drop a socket to track down a "probably unassigned" port + let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); + let addr = "127.0.0.1:0".parse::<SocketAddr>().unwrap().into(); + socket.bind(&addr).unwrap(); + let addr = socket.local_addr().unwrap(); + drop(socket); + + let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); + match socket.connect_timeout(&addr, Duration::from_millis(250)) { + Ok(_) => panic!("unexpected success"), + Err(ref e) + if e.kind() == io::ErrorKind::ConnectionRefused + || e.kind() == io::ErrorKind::TimedOut => {} + Err(e) => panic!("unexpected error {}", e), + } + } + + #[test] + fn connect_timeout_valid() { + let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); + socket + .bind(&"127.0.0.1:0".parse::<SocketAddr>().unwrap().into()) + .unwrap(); + socket.listen(128).unwrap(); + + let addr = socket.local_addr().unwrap(); + + let socket = Socket::new(Domain::ipv4(), Type::stream(), None).unwrap(); + socket + .connect_timeout(&addr, Duration::from_millis(250)) + .unwrap(); + } + + #[test] + #[cfg(all(unix, feature = "pair", feature = "unix"))] + fn pair() { + let (mut a, mut b) = Socket::pair(Domain::unix(), Type::stream(), None).unwrap(); + a.write_all(b"hello world").unwrap(); + let mut buf = [0; 11]; + b.read_exact(&mut buf).unwrap(); + assert_eq!(buf, &b"hello world"[..]); + } + + #[test] + #[cfg(all(unix, feature = "unix"))] + fn unix() { + use tempdir::TempDir; + + let dir = TempDir::new("unix").unwrap(); + let addr = SockAddr::unix(dir.path().join("sock")).unwrap(); + + let listener = Socket::new(Domain::unix(), Type::stream(), None).unwrap(); + listener.bind(&addr).unwrap(); + listener.listen(10).unwrap(); + + let mut a = Socket::new(Domain::unix(), Type::stream(), None).unwrap(); + a.connect(&addr).unwrap(); + + let mut b = listener.accept().unwrap().0; + + a.write_all(b"hello world").unwrap(); + let mut buf = [0; 11]; + b.read_exact(&mut buf).unwrap(); + assert_eq!(buf, &b"hello world"[..]); + } +} diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/src/sys/unix/mod.rs cargo-0.26.0/vendor/socket2-0.3.4/src/sys/unix/mod.rs --- cargo-0.25.0/vendor/socket2-0.3.4/src/sys/unix/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/src/sys/unix/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1114 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cmp; +use std::fmt; +use std::io::{ErrorKind, Read, Write}; +use std::io; +use std::mem; +use std::net::Shutdown; +use std::net::{self, Ipv4Addr, Ipv6Addr}; +use std::ops::Neg; +use std::os::unix::prelude::*; +use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; +use std::time::{Duration, Instant}; +#[cfg(feature = "unix")] +use std::os::unix::net::{UnixDatagram, UnixListener, UnixStream}; + +use libc::{self, c_int, c_void, socklen_t, ssize_t}; + +cfg_if! { + if #[cfg(any(target_os = "dragonfly", target_os = "freebsd", + target_os = "ios", target_os = "macos", + target_os = "openbsd", target_os = "netbsd", + target_os = "solaris", target_os = "haiku"))] { + use libc::IPV6_JOIN_GROUP as IPV6_ADD_MEMBERSHIP; + use libc::IPV6_LEAVE_GROUP as IPV6_DROP_MEMBERSHIP; + } else { + use libc::IPV6_ADD_MEMBERSHIP; + use libc::IPV6_DROP_MEMBERSHIP; + } +} + +cfg_if! { + if #[cfg(any(target_os = "linux", target_os = "android", + target_os = "dragonfly", target_os = "freebsd", + target_os = "openbsd", target_os = "netbsd", + target_os = "haiku", target_os = "bitrig"))] { + use libc::MSG_NOSIGNAL; + } else { + const MSG_NOSIGNAL: c_int = 0x0; + } +} + +cfg_if! { + if #[cfg(any(target_os = "macos", target_os = "ios"))] { + use libc::TCP_KEEPALIVE as KEEPALIVE_OPTION; + } else if #[cfg(any(target_os = "openbsd", target_os = "netbsd", target_os = "haiku"))] { + use libc::SO_KEEPALIVE as KEEPALIVE_OPTION; + } else { + use libc::TCP_KEEPIDLE as KEEPALIVE_OPTION; + } +} + +use SockAddr; +use utils::One; + +pub const IPPROTO_ICMP: i32 = libc::IPPROTO_ICMP; +pub const IPPROTO_ICMPV6: i32 = libc::IPPROTO_ICMPV6; +pub const IPPROTO_TCP: i32 = libc::IPPROTO_TCP; +pub const IPPROTO_UDP: i32 = libc::IPPROTO_UDP; + +#[macro_use] +#[cfg(target_os = "linux")] +mod weak; + +pub struct Socket { + fd: c_int, +} + +impl Socket { + pub fn new(family: c_int, ty: c_int, protocol: c_int) -> io::Result<Socket> { + unsafe { + // On linux we first attempt to pass the SOCK_CLOEXEC flag to + // atomically create the socket and set it as CLOEXEC. Support for + // this option, however, was added in 2.6.27, and we still support + // 2.6.18 as a kernel, so if the returned error is EINVAL we + // fallthrough to the fallback. + #[cfg(target_os = "linux")] + { + match cvt(libc::socket(family, ty | libc::SOCK_CLOEXEC, protocol)) { + Ok(fd) => return Ok(Socket::from_raw_fd(fd)), + Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => {} + Err(e) => return Err(e), + } + } + + let fd = cvt(libc::socket(family, ty, protocol))?; + let fd = Socket::from_raw_fd(fd); + set_cloexec(fd.as_raw_fd())?; + #[cfg(target_os = "macos")] + { + fd.setsockopt(libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1i32)?; + } + Ok(fd) + } + } + + pub fn pair(family: c_int, ty: c_int, protocol: c_int) -> io::Result<(Socket, Socket)> { + unsafe { + let mut fds = [0, 0]; + cvt(libc::socketpair(family, ty, protocol, fds.as_mut_ptr()))?; + let fds = (Socket::from_raw_fd(fds[0]), Socket::from_raw_fd(fds[1])); + set_cloexec(fds.0.as_raw_fd())?; + set_cloexec(fds.1.as_raw_fd())?; + #[cfg(target_os = "macos")] + { + fds.0 + .setsockopt(libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1i32)?; + fds.1 + .setsockopt(libc::SOL_SOCKET, libc::SO_NOSIGPIPE, 1i32)?; + } + Ok(fds) + } + } + + pub fn bind(&self, addr: &SockAddr) -> io::Result<()> { + unsafe { cvt(libc::bind(self.fd, addr.as_ptr(), addr.len() as _)).map(|_| ()) } + } + + pub fn listen(&self, backlog: i32) -> io::Result<()> { + unsafe { cvt(libc::listen(self.fd, backlog)).map(|_| ()) } + } + + pub fn connect(&self, addr: &SockAddr) -> io::Result<()> { + unsafe { cvt(libc::connect(self.fd, addr.as_ptr(), addr.len())).map(|_| ()) } + } + + pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> { + self.set_nonblocking(true)?; + let r = self.connect(addr); + self.set_nonblocking(false)?; + + match r { + Ok(()) => return Ok(()), + // there's no io::ErrorKind conversion registered for EINPROGRESS :( + Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {} + Err(e) => return Err(e), + } + + let mut pollfd = libc::pollfd { + fd: self.fd, + events: libc::POLLOUT, + revents: 0, + }; + + if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); + } + + let start = Instant::now(); + + loop { + let elapsed = start.elapsed(); + if elapsed >= timeout { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "connection timed out", + )); + } + + let timeout = timeout - elapsed; + let mut timeout = timeout + .as_secs() + .saturating_mul(1_000) + .saturating_add(timeout.subsec_nanos() as u64 / 1_000_000); + if timeout == 0 { + timeout = 1; + } + + let timeout = cmp::min(timeout, c_int::max_value() as u64) as c_int; + + match unsafe { libc::poll(&mut pollfd, 1, timeout) } { + -1 => { + let err = io::Error::last_os_error(); + if err.kind() != io::ErrorKind::Interrupted { + return Err(err); + } + } + 0 => { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "connection timed out", + )) + } + _ => { + // linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look + // for POLLHUP rather than read readiness + if pollfd.revents & libc::POLLHUP != 0 { + let e = self.take_error()?.unwrap_or_else(|| { + io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP") + }); + return Err(e); + } + return Ok(()); + } + } + } + } + + pub fn local_addr(&self) -> io::Result<SockAddr> { + unsafe { + let mut storage: libc::sockaddr_storage = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as libc::socklen_t; + cvt(libc::getsockname( + self.fd, + &mut storage as *mut _ as *mut _, + &mut len, + ))?; + Ok(SockAddr::from_raw_parts( + &storage as *const _ as *const _, + len, + )) + } + } + + pub fn peer_addr(&self) -> io::Result<SockAddr> { + unsafe { + let mut storage: libc::sockaddr_storage = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as libc::socklen_t; + cvt(libc::getpeername( + self.fd, + &mut storage as *mut _ as *mut _, + &mut len, + ))?; + Ok(SockAddr::from_raw_parts( + &storage as *const _ as *const _, + len, + )) + } + } + + pub fn try_clone(&self) -> io::Result<Socket> { + // implementation lifted from libstd + #[cfg(any(target_os = "android", target_os = "haiku"))] + use libc::F_DUPFD as F_DUPFD_CLOEXEC; + #[cfg(not(any(target_os = "android", target_os = "haiku")))] + use libc::F_DUPFD_CLOEXEC; + + static CLOEXEC_FAILED: AtomicBool = ATOMIC_BOOL_INIT; + unsafe { + if !CLOEXEC_FAILED.load(Ordering::Relaxed) { + match cvt(libc::fcntl(self.fd, F_DUPFD_CLOEXEC, 0)) { + Ok(fd) => { + let fd = Socket::from_raw_fd(fd); + if cfg!(target_os = "linux") { + set_cloexec(fd.as_raw_fd())?; + } + return Ok(fd); + } + Err(ref e) if e.raw_os_error() == Some(libc::EINVAL) => { + CLOEXEC_FAILED.store(true, Ordering::Relaxed); + } + Err(e) => return Err(e), + } + } + let fd = cvt(libc::fcntl(self.fd, libc::F_DUPFD, 0))?; + let fd = Socket::from_raw_fd(fd); + set_cloexec(fd.as_raw_fd())?; + Ok(fd) + } + } + + #[allow(unused_mut)] + pub fn accept(&self) -> io::Result<(Socket, SockAddr)> { + let mut storage: libc::sockaddr_storage = unsafe { mem::zeroed() }; + let mut len = mem::size_of_val(&storage) as socklen_t; + + let mut socket = None; + #[cfg(target_os = "linux")] + { + weak! { + fn accept4(c_int, *mut libc::sockaddr, *mut socklen_t, c_int) -> c_int + } + if let Some(f) = accept4.get() { + let res = cvt_r(|| unsafe { + f( + self.fd, + &mut storage as *mut _ as *mut _, + &mut len, + libc::SOCK_CLOEXEC, + ) + }); + match res { + Ok(fd) => socket = Some(Socket { fd: fd }), + Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {} + Err(e) => return Err(e), + } + } + } + + let socket = match socket { + Some(socket) => socket, + None => unsafe { + let fd = + cvt_r(|| libc::accept(self.fd, &mut storage as *mut _ as *mut _, &mut len))?; + let fd = Socket::from_raw_fd(fd); + set_cloexec(fd.as_raw_fd())?; + fd + }, + }; + let addr = unsafe { SockAddr::from_raw_parts(&storage as *const _ as *const _, len) }; + Ok((socket, addr)) + } + + pub fn take_error(&self) -> io::Result<Option<io::Error>> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_ERROR)?; + if raw == 0 { + Ok(None) + } else { + Ok(Some(io::Error::from_raw_os_error(raw as i32))) + } + } + } + + pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + unsafe { + let previous = cvt(libc::fcntl(self.fd, libc::F_GETFL))?; + let new = if nonblocking { + previous | libc::O_NONBLOCK + } else { + previous & !libc::O_NONBLOCK + }; + if new != previous { + cvt(libc::fcntl(self.fd, libc::F_SETFL, new))?; + } + Ok(()) + } + } + + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + let how = match how { + Shutdown::Write => libc::SHUT_WR, + Shutdown::Read => libc::SHUT_RD, + Shutdown::Both => libc::SHUT_RDWR, + }; + cvt(unsafe { libc::shutdown(self.fd, how) })?; + Ok(()) + } + + pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::recv( + self.fd, + buf.as_mut_ptr() as *mut c_void, + cmp::min(buf.len(), max_len()), + 0, + ) + })?; + Ok(n as usize) + } + } + + pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::recv( + self.fd, + buf.as_mut_ptr() as *mut c_void, + cmp::min(buf.len(), max_len()), + libc::MSG_PEEK, + ) + })?; + Ok(n as usize) + } + } + + pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { + self.recvfrom(buf, 0) + } + + pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { + self.recvfrom(buf, libc::MSG_PEEK) + } + + fn recvfrom(&self, buf: &mut [u8], flags: c_int) -> io::Result<(usize, SockAddr)> { + unsafe { + let mut storage: libc::sockaddr_storage = mem::zeroed(); + let mut addrlen = mem::size_of_val(&storage) as socklen_t; + + let n = cvt({ + libc::recvfrom( + self.fd, + buf.as_mut_ptr() as *mut c_void, + cmp::min(buf.len(), max_len()), + flags, + &mut storage as *mut _ as *mut _, + &mut addrlen, + ) + })?; + let addr = SockAddr::from_raw_parts(&storage as *const _ as *const _, addrlen); + Ok((n as usize, addr)) + } + } + + pub fn send(&self, buf: &[u8]) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::send( + self.fd, + buf.as_ptr() as *const c_void, + cmp::min(buf.len(), max_len()), + MSG_NOSIGNAL, + ) + })?; + Ok(n as usize) + } + } + + pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::sendto( + self.fd, + buf.as_ptr() as *const c_void, + cmp::min(buf.len(), max_len()), + MSG_NOSIGNAL, + addr.as_ptr(), + addr.len(), + ) + })?; + Ok(n as usize) + } + } + + // ================================================ + + pub fn ttl(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_TTL)?; + Ok(raw as u32) + } + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_TTL, ttl as c_int) } + } + + pub fn unicast_hops_v6(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_UNICAST_HOPS)?; + Ok(raw as u32) + } + } + + pub fn set_unicast_hops_v6(&self, hops: u32) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IPV6 as c_int, + libc::IPV6_UNICAST_HOPS, + hops as c_int, + ) + } + } + + pub fn only_v6(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_V6ONLY)?; + Ok(raw != 0) + } + } + + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::IPPROTO_IPV6, libc::IPV6_V6ONLY, only_v6 as c_int) } + } + + pub fn read_timeout(&self) -> io::Result<Option<Duration>> { + unsafe { + Ok(timeval2dur(self.getsockopt( + libc::SOL_SOCKET, + libc::SO_RCVTIMEO, + )?)) + } + } + + pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_RCVTIMEO, dur2timeval(dur)?) } + } + + pub fn write_timeout(&self) -> io::Result<Option<Duration>> { + unsafe { + Ok(timeval2dur(self.getsockopt( + libc::SOL_SOCKET, + libc::SO_SNDTIMEO, + )?)) + } + } + + pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_SNDTIMEO, dur2timeval(dur)?) } + } + + pub fn nodelay(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_TCP, libc::TCP_NODELAY)?; + Ok(raw != 0) + } + } + + pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::IPPROTO_TCP, libc::TCP_NODELAY, nodelay as c_int) } + } + + pub fn broadcast(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_BROADCAST)?; + Ok(raw != 0) + } + } + + pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_BROADCAST, broadcast as c_int) } + } + + pub fn multicast_loop_v4(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_LOOP)?; + Ok(raw != 0) + } + } + + pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IP, + libc::IP_MULTICAST_LOOP, + multicast_loop_v4 as c_int, + ) + } + } + + pub fn multicast_ttl_v4(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_TTL)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IP, + libc::IP_MULTICAST_TTL, + multicast_ttl_v4 as c_int, + ) + } + } + + pub fn multicast_hops_v6(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_HOPS)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_hops_v6(&self, hops: u32) -> io::Result<()> { + unsafe { self.setsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_HOPS, hops as c_int) } + } + + pub fn multicast_if_v4(&self) -> io::Result<Ipv4Addr> { + unsafe { + let imr_interface: libc::in_addr = + self.getsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_IF)?; + Ok(from_s_addr(imr_interface.s_addr)) + } + } + + pub fn set_multicast_if_v4(&self, interface: &Ipv4Addr) -> io::Result<()> { + let interface = to_s_addr(interface); + let imr_interface = libc::in_addr { s_addr: interface }; + + unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_MULTICAST_IF, imr_interface) } + } + + pub fn multicast_if_v6(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_IF)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_if_v6(&self, interface: u32) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IPV6, + libc::IPV6_MULTICAST_IF, + interface as c_int, + ) + } + } + + pub fn multicast_loop_v6(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::IPPROTO_IPV6, libc::IPV6_MULTICAST_LOOP)?; + Ok(raw != 0) + } + } + + pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::IPPROTO_IPV6, + libc::IPV6_MULTICAST_LOOP, + multicast_loop_v6 as c_int, + ) + } + } + + pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + let multiaddr = to_s_addr(multiaddr); + let interface = to_s_addr(interface); + let mreq = libc::ip_mreq { + imr_multiaddr: libc::in_addr { s_addr: multiaddr }, + imr_interface: libc::in_addr { s_addr: interface }, + }; + unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_ADD_MEMBERSHIP, mreq) } + } + + pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + let multiaddr = to_in6_addr(multiaddr); + let mreq = libc::ipv6_mreq { + ipv6mr_multiaddr: multiaddr, + ipv6mr_interface: to_ipv6mr_interface(interface), + }; + unsafe { self.setsockopt(libc::IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, mreq) } + } + + pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + let multiaddr = to_s_addr(multiaddr); + let interface = to_s_addr(interface); + let mreq = libc::ip_mreq { + imr_multiaddr: libc::in_addr { s_addr: multiaddr }, + imr_interface: libc::in_addr { s_addr: interface }, + }; + unsafe { self.setsockopt(libc::IPPROTO_IP, libc::IP_DROP_MEMBERSHIP, mreq) } + } + + pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + let multiaddr = to_in6_addr(multiaddr); + let mreq = libc::ipv6_mreq { + ipv6mr_multiaddr: multiaddr, + ipv6mr_interface: to_ipv6mr_interface(interface), + }; + unsafe { self.setsockopt(libc::IPPROTO_IPV6, IPV6_DROP_MEMBERSHIP, mreq) } + } + + pub fn linger(&self) -> io::Result<Option<Duration>> { + unsafe { + Ok(linger2dur(self.getsockopt( + libc::SOL_SOCKET, + libc::SO_LINGER, + )?)) + } + } + + pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_LINGER, dur2linger(dur)) } + } + + pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_REUSEADDR, reuse as c_int) } + } + + pub fn reuse_address(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_REUSEADDR)?; + Ok(raw != 0) + } + } + + pub fn recv_buffer_size(&self) -> io::Result<usize> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_RCVBUF)?; + Ok(raw as usize) + } + } + + pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { + unsafe { + // TODO: casting usize to a c_int should be a checked cast + self.setsockopt(libc::SOL_SOCKET, libc::SO_RCVBUF, size as c_int) + } + } + + pub fn send_buffer_size(&self) -> io::Result<usize> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_SNDBUF)?; + Ok(raw as usize) + } + } + + pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { + unsafe { + // TODO: casting usize to a c_int should be a checked cast + self.setsockopt(libc::SOL_SOCKET, libc::SO_SNDBUF, size as c_int) + } + } + + pub fn keepalive(&self) -> io::Result<Option<Duration>> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_KEEPALIVE)?; + if raw == 0 { + return Ok(None); + } + let secs: c_int = self.getsockopt(libc::IPPROTO_TCP, KEEPALIVE_OPTION)?; + Ok(Some(Duration::new(secs as u64, 0))) + } + } + + pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> { + unsafe { + self.setsockopt( + libc::SOL_SOCKET, + libc::SO_KEEPALIVE, + keepalive.is_some() as c_int, + )?; + if let Some(dur) = keepalive { + // TODO: checked cast here + self.setsockopt( + libc::IPPROTO_TCP, + KEEPALIVE_OPTION, + (dur.as_secs() / 1000) as c_int, + )?; + } + Ok(()) + } + } + + #[cfg(all(unix, feature = "reuseport"))] + pub fn reuse_port(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(libc::SOL_SOCKET, libc::SO_REUSEPORT)?; + Ok(raw != 0) + } + } + + #[cfg(all(unix, feature = "reuseport"))] + pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> { + unsafe { self.setsockopt(libc::SOL_SOCKET, libc::SO_REUSEPORT, reuse as c_int) } + } + + unsafe fn setsockopt<T>(&self, opt: c_int, val: c_int, payload: T) -> io::Result<()> + where + T: Copy, + { + let payload = &payload as *const T as *const c_void; + cvt(libc::setsockopt( + self.fd, + opt, + val, + payload, + mem::size_of::<T>() as libc::socklen_t, + ))?; + Ok(()) + } + + unsafe fn getsockopt<T: Copy>(&self, opt: c_int, val: c_int) -> io::Result<T> { + let mut slot: T = mem::zeroed(); + let mut len = mem::size_of::<T>() as libc::socklen_t; + cvt(libc::getsockopt( + self.fd, + opt, + val, + &mut slot as *mut _ as *mut _, + &mut len, + ))?; + assert_eq!(len as usize, mem::size_of::<T>()); + Ok(slot) + } +} + +impl Read for Socket { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + <&Socket>::read(&mut &*self, buf) + } +} + +impl<'a> Read for &'a Socket { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + unsafe { + let n = cvt({ + libc::read( + self.fd, + buf.as_mut_ptr() as *mut c_void, + cmp::min(buf.len(), max_len()), + ) + })?; + Ok(n as usize) + } + } +} + +impl Write for Socket { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + <&Socket>::write(&mut &*self, buf) + } + + fn flush(&mut self) -> io::Result<()> { + <&Socket>::flush(&mut &*self) + } +} + +impl<'a> Write for &'a Socket { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.send(buf) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl fmt::Debug for Socket { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_struct("Socket"); + f.field("fd", &self.fd); + if let Ok(addr) = self.local_addr() { + f.field("local_addr", &addr); + } + if let Ok(addr) = self.peer_addr() { + f.field("peer_addr", &addr); + } + f.finish() + } +} + +impl AsRawFd for Socket { + fn as_raw_fd(&self) -> c_int { + self.fd + } +} + +impl IntoRawFd for Socket { + fn into_raw_fd(self) -> c_int { + let fd = self.fd; + mem::forget(self); + return fd; + } +} + +impl FromRawFd for Socket { + unsafe fn from_raw_fd(fd: c_int) -> Socket { + Socket { fd: fd } + } +} + +impl AsRawFd for ::Socket { + fn as_raw_fd(&self) -> c_int { + self.inner.as_raw_fd() + } +} + +impl IntoRawFd for ::Socket { + fn into_raw_fd(self) -> c_int { + self.inner.into_raw_fd() + } +} + +impl FromRawFd for ::Socket { + unsafe fn from_raw_fd(fd: c_int) -> ::Socket { + ::Socket { + inner: Socket::from_raw_fd(fd), + } + } +} + +impl Drop for Socket { + fn drop(&mut self) { + unsafe { + let _ = libc::close(self.fd); + } + } +} + +impl From<Socket> for net::TcpStream { + fn from(socket: Socket) -> net::TcpStream { + unsafe { net::TcpStream::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<Socket> for net::TcpListener { + fn from(socket: Socket) -> net::TcpListener { + unsafe { net::TcpListener::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<Socket> for net::UdpSocket { + fn from(socket: Socket) -> net::UdpSocket { + unsafe { net::UdpSocket::from_raw_fd(socket.into_raw_fd()) } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<Socket> for UnixStream { + fn from(socket: Socket) -> UnixStream { + unsafe { UnixStream::from_raw_fd(socket.into_raw_fd()) } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<Socket> for UnixListener { + fn from(socket: Socket) -> UnixListener { + unsafe { UnixListener::from_raw_fd(socket.into_raw_fd()) } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<Socket> for UnixDatagram { + fn from(socket: Socket) -> UnixDatagram { + unsafe { UnixDatagram::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<net::TcpStream> for Socket { + fn from(socket: net::TcpStream) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<net::TcpListener> for Socket { + fn from(socket: net::TcpListener) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +impl From<net::UdpSocket> for Socket { + fn from(socket: net::UdpSocket) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<UnixStream> for Socket { + fn from(socket: UnixStream) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<UnixListener> for Socket { + fn from(socket: UnixListener) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +#[cfg(all(unix, feature = "unix"))] +impl From<UnixDatagram> for Socket { + fn from(socket: UnixDatagram) -> Socket { + unsafe { Socket::from_raw_fd(socket.into_raw_fd()) } + } +} + +fn max_len() -> usize { + // The maximum read limit on most posix-like systems is `SSIZE_MAX`, + // with the man page quoting that if the count of bytes to read is + // greater than `SSIZE_MAX` the result is "unspecified". + // + // On macOS, however, apparently the 64-bit libc is either buggy or + // intentionally showing odd behavior by rejecting any read with a size + // larger than or equal to INT_MAX. To handle both of these the read + // size is capped on both platforms. + if cfg!(target_os = "macos") { + <c_int>::max_value() as usize - 1 + } else { + <ssize_t>::max_value() as usize + } +} + +fn cvt<T: One + PartialEq + Neg<Output = T>>(t: T) -> io::Result<T> { + let one: T = T::one(); + if t == -one { + Err(io::Error::last_os_error()) + } else { + Ok(t) + } +} + +fn cvt_r<F, T>(mut f: F) -> io::Result<T> +where + F: FnMut() -> T, + T: One + PartialEq + Neg<Output = T>, +{ + loop { + match cvt(f()) { + Err(ref e) if e.kind() == ErrorKind::Interrupted => {} + other => return other, + } + } +} + +fn set_cloexec(fd: c_int) -> io::Result<()> { + unsafe { + let previous = cvt(libc::fcntl(fd, libc::F_GETFD))?; + let new = previous | libc::FD_CLOEXEC; + if new != previous { + cvt(libc::fcntl(fd, libc::F_SETFD, new))?; + } + Ok(()) + } +} + +fn dur2timeval(dur: Option<Duration>) -> io::Result<libc::timeval> { + match dur { + Some(dur) => { + if dur.as_secs() == 0 && dur.subsec_nanos() == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); + } + + let secs = if dur.as_secs() > libc::time_t::max_value() as u64 { + libc::time_t::max_value() + } else { + dur.as_secs() as libc::time_t + }; + let mut timeout = libc::timeval { + tv_sec: secs, + tv_usec: (dur.subsec_nanos() / 1000) as libc::suseconds_t, + }; + if timeout.tv_sec == 0 && timeout.tv_usec == 0 { + timeout.tv_usec = 1; + } + Ok(timeout) + } + None => Ok(libc::timeval { + tv_sec: 0, + tv_usec: 0, + }), + } +} + +fn timeval2dur(raw: libc::timeval) -> Option<Duration> { + if raw.tv_sec == 0 && raw.tv_usec == 0 { + None + } else { + let sec = raw.tv_sec as u64; + let nsec = (raw.tv_usec as u32) * 1000; + Some(Duration::new(sec, nsec)) + } +} + +fn to_s_addr(addr: &Ipv4Addr) -> libc::in_addr_t { + let octets = addr.octets(); + ::hton( + ((octets[0] as libc::in_addr_t) << 24) | ((octets[1] as libc::in_addr_t) << 16) + | ((octets[2] as libc::in_addr_t) << 8) | ((octets[3] as libc::in_addr_t) << 0), + ) +} + +fn from_s_addr(in_addr: libc::in_addr_t) -> Ipv4Addr { + let h_addr = ::ntoh(in_addr); + + let a: u8 = (h_addr >> 24) as u8; + let b: u8 = (h_addr >> 16) as u8; + let c: u8 = (h_addr >> 8) as u8; + let d: u8 = (h_addr >> 0) as u8; + + Ipv4Addr::new(a, b, c, d) +} + +fn to_in6_addr(addr: &Ipv6Addr) -> libc::in6_addr { + let mut ret: libc::in6_addr = unsafe { mem::zeroed() }; + ret.s6_addr = addr.octets(); + return ret; +} + +#[cfg(target_os = "android")] +fn to_ipv6mr_interface(value: u32) -> c_int { + value as c_int +} + +#[cfg(not(target_os = "android"))] +fn to_ipv6mr_interface(value: u32) -> libc::c_uint { + value as libc::c_uint +} + +fn linger2dur(linger_opt: libc::linger) -> Option<Duration> { + if linger_opt.l_onoff == 0 { + None + } else { + Some(Duration::from_secs(linger_opt.l_linger as u64)) + } +} + +fn dur2linger(dur: Option<Duration>) -> libc::linger { + match dur { + Some(d) => libc::linger { + l_onoff: 1, + l_linger: d.as_secs() as c_int, + }, + None => libc::linger { + l_onoff: 0, + l_linger: 0, + }, + } +} + +#[test] +fn test_ip() { + let ip = Ipv4Addr::new(127, 0, 0, 1); + assert_eq!(ip, from_s_addr(to_s_addr(&ip))); +} diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/src/sys/unix/weak.rs cargo-0.26.0/vendor/socket2-0.3.4/src/sys/unix/weak.rs --- cargo-0.25.0/vendor/socket2-0.3.4/src/sys/unix/weak.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/src/sys/unix/weak.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,59 @@ +// Copyright 2016 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::marker; +use std::mem; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use libc; + +macro_rules! weak { + (fn $name:ident($($t:ty),*) -> $ret:ty) => ( + #[allow(bad_style)] + static $name: ::sys::weak::Weak<unsafe extern fn($($t),*) -> $ret> = + ::sys::weak::Weak { + name: concat!(stringify!($name), "\0"), + addr: ::std::sync::atomic::ATOMIC_USIZE_INIT, + _marker: ::std::marker::PhantomData, + }; + ) +} + +pub struct Weak<F> { + pub name: &'static str, + pub addr: AtomicUsize, + pub _marker: marker::PhantomData<F>, +} + +impl<F> Weak<F> { + pub fn get(&self) -> Option<&F> { + assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>()); + unsafe { + if self.addr.load(Ordering::SeqCst) == 0 { + let ptr = match fetch(self.name) { + 1 => 1, + n => n, + }; + self.addr.store(ptr, Ordering::SeqCst); + } + if self.addr.load(Ordering::SeqCst) == 1 { + None + } else { + mem::transmute::<&AtomicUsize, Option<&F>>(&self.addr) + } + } + } +} + +unsafe fn fetch(name: &str) -> usize { + let name = name.as_bytes(); + assert_eq!(name[name.len() - 1], 0); + libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr() as *const _) as usize +} diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/src/sys/windows.rs cargo-0.26.0/vendor/socket2-0.3.4/src/sys/windows.rs --- cargo-0.25.0/vendor/socket2-0.3.4/src/sys/windows.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/src/sys/windows.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,971 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cmp; +use std::fmt; +use std::io::{Read, Write}; +use std::io; +use std::mem; +use std::net::Shutdown; +use std::net::{self, Ipv4Addr, Ipv6Addr}; +use std::os::windows::prelude::*; +use std::ptr; +use std::sync::{Once, ONCE_INIT}; +use std::time::Duration; + +use winapi::ctypes::{c_char, c_int, c_long, c_ulong}; +use winapi::shared::inaddr::*; +use winapi::shared::in6addr::*; +use winapi::shared::minwindef::DWORD; +use winapi::shared::ntdef::{HANDLE, ULONG}; +use winapi::shared::ws2def::*; +use winapi::shared::ws2def; +use winapi::shared::ws2ipdef::*; +use winapi::um::handleapi::SetHandleInformation; +use winapi::um::processthreadsapi::GetCurrentProcessId; +use winapi::um::winbase::INFINITE; +use winapi::um::winsock2 as sock; + +use SockAddr; + +const HANDLE_FLAG_INHERIT: DWORD = 0x00000001; +const MSG_PEEK: c_int = 0x2; +const SD_BOTH: c_int = 2; +const SD_RECEIVE: c_int = 0; +const SD_SEND: c_int = 1; +const SIO_KEEPALIVE_VALS: DWORD = 0x98000004; +const WSA_FLAG_OVERLAPPED: DWORD = 0x01; + +pub const IPPROTO_ICMP: i32 = ws2def::IPPROTO_ICMP as i32; +pub const IPPROTO_ICMPV6: i32 = ws2def::IPPROTO_ICMPV6 as i32; +pub const IPPROTO_TCP: i32 = ws2def::IPPROTO_TCP as i32; +pub const IPPROTO_UDP: i32 = ws2def::IPPROTO_UDP as i32; + +#[repr(C)] +struct tcp_keepalive { + onoff: c_ulong, + keepalivetime: c_ulong, + keepaliveinterval: c_ulong, +} + +fn init() { + static INIT: Once = ONCE_INIT; + + INIT.call_once(|| { + // Initialize winsock through the standard library by just creating a + // dummy socket. Whether this is successful or not we drop the result as + // libstd will be sure to have initialized winsock. + let _ = net::UdpSocket::bind("127.0.0.1:34254"); + }); +} + +fn last_error() -> io::Error { + io::Error::from_raw_os_error(unsafe { sock::WSAGetLastError() }) +} + +pub struct Socket { + socket: sock::SOCKET, +} + +impl Socket { + pub fn new(family: c_int, ty: c_int, protocol: c_int) -> io::Result<Socket> { + init(); + unsafe { + let socket = match sock::WSASocketW( + family, + ty, + protocol, + ptr::null_mut(), + 0, + WSA_FLAG_OVERLAPPED, + ) { + sock::INVALID_SOCKET => return Err(last_error()), + socket => socket, + }; + let socket = Socket::from_raw_socket(socket as RawSocket); + socket.set_no_inherit()?; + Ok(socket) + } + } + + pub fn bind(&self, addr: &SockAddr) -> io::Result<()> { + unsafe { + if sock::bind(self.socket, addr.as_ptr(), addr.len()) == 0 { + Ok(()) + } else { + Err(last_error()) + } + } + } + + pub fn listen(&self, backlog: i32) -> io::Result<()> { + unsafe { + if sock::listen(self.socket, backlog) == 0 { + Ok(()) + } else { + Err(last_error()) + } + } + } + + pub fn connect(&self, addr: &SockAddr) -> io::Result<()> { + unsafe { + if sock::connect(self.socket, addr.as_ptr(), addr.len()) == 0 { + Ok(()) + } else { + Err(last_error()) + } + } + } + + pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> { + self.set_nonblocking(true)?; + let r = self.connect(addr); + self.set_nonblocking(false)?; + + match r { + Ok(()) => return Ok(()), + Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {} + Err(e) => return Err(e), + } + + if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); + } + + let mut timeout = sock::timeval { + tv_sec: timeout.as_secs() as c_long, + tv_usec: (timeout.subsec_nanos() / 1000) as c_long, + }; + if timeout.tv_sec == 0 && timeout.tv_usec == 0 { + timeout.tv_usec = 1; + } + + let fds = unsafe { + let mut fds = mem::zeroed::<sock::fd_set>(); + fds.fd_count = 1; + fds.fd_array[0] = self.socket; + fds + }; + + let mut writefds = fds; + let mut errorfds = fds; + + match unsafe { sock::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout) } { + sock::SOCKET_ERROR => return Err(io::Error::last_os_error()), + 0 => { + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "connection timed out", + )) + } + _ => { + if writefds.fd_count != 1 { + if let Some(e) = self.take_error()? { + return Err(e); + } + } + Ok(()) + } + } + } + + pub fn local_addr(&self) -> io::Result<SockAddr> { + unsafe { + let mut storage: SOCKADDR_STORAGE = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as c_int; + if sock::getsockname(self.socket, &mut storage as *mut _ as *mut _, &mut len) != 0 { + return Err(last_error()); + } + Ok(SockAddr::from_raw_parts( + &storage as *const _ as *const _, + len, + )) + } + } + + pub fn peer_addr(&self) -> io::Result<SockAddr> { + unsafe { + let mut storage: SOCKADDR_STORAGE = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as c_int; + if sock::getpeername(self.socket, &mut storage as *mut _ as *mut _, &mut len) != 0 { + return Err(last_error()); + } + Ok(SockAddr::from_raw_parts( + &storage as *const _ as *const _, + len, + )) + } + } + + pub fn try_clone(&self) -> io::Result<Socket> { + unsafe { + let mut info: sock::WSAPROTOCOL_INFOW = mem::zeroed(); + let r = sock::WSADuplicateSocketW(self.socket, GetCurrentProcessId(), &mut info); + if r != 0 { + return Err(io::Error::last_os_error()); + } + let socket = sock::WSASocketW( + info.iAddressFamily, + info.iSocketType, + info.iProtocol, + &mut info, + 0, + WSA_FLAG_OVERLAPPED, + ); + let socket = match socket { + sock::INVALID_SOCKET => return Err(last_error()), + n => Socket::from_raw_socket(n as RawSocket), + }; + socket.set_no_inherit()?; + Ok(socket) + } + } + + pub fn accept(&self) -> io::Result<(Socket, SockAddr)> { + unsafe { + let mut storage: SOCKADDR_STORAGE = mem::zeroed(); + let mut len = mem::size_of_val(&storage) as c_int; + let socket = { sock::accept(self.socket, &mut storage as *mut _ as *mut _, &mut len) }; + let socket = match socket { + sock::INVALID_SOCKET => return Err(last_error()), + socket => Socket::from_raw_socket(socket as RawSocket), + }; + socket.set_no_inherit()?; + let addr = SockAddr::from_raw_parts(&storage as *const _ as *const _, len); + Ok((socket, addr)) + } + } + + pub fn take_error(&self) -> io::Result<Option<io::Error>> { + unsafe { + let raw: c_int = self.getsockopt(SOL_SOCKET, SO_ERROR)?; + if raw == 0 { + Ok(None) + } else { + Ok(Some(io::Error::from_raw_os_error(raw as i32))) + } + } + } + + pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { + unsafe { + let mut nonblocking = nonblocking as c_ulong; + let r = sock::ioctlsocket(self.socket, sock::FIONBIO as c_int, &mut nonblocking); + if r == 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } + } + + pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { + let how = match how { + Shutdown::Write => SD_SEND, + Shutdown::Read => SD_RECEIVE, + Shutdown::Both => SD_BOTH, + }; + if unsafe { sock::shutdown(self.socket, how) == 0 } { + Ok(()) + } else { + Err(last_error()) + } + } + + pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> { + unsafe { + let n = { + sock::recv( + self.socket, + buf.as_mut_ptr() as *mut c_char, + clamp(buf.len()), + 0, + ) + }; + match n { + sock::SOCKET_ERROR if sock::WSAGetLastError() == sock::WSAESHUTDOWN as i32 => Ok(0), + sock::SOCKET_ERROR => Err(last_error()), + n => Ok(n as usize), + } + } + } + + pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> { + unsafe { + let n = { + sock::recv( + self.socket, + buf.as_mut_ptr() as *mut c_char, + clamp(buf.len()), + MSG_PEEK, + ) + }; + match n { + sock::SOCKET_ERROR if sock::WSAGetLastError() == sock::WSAESHUTDOWN as i32 => Ok(0), + sock::SOCKET_ERROR => Err(last_error()), + n => Ok(n as usize), + } + } + } + + pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { + self.recvfrom(buf, 0) + } + + pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SockAddr)> { + self.recvfrom(buf, MSG_PEEK) + } + + fn recvfrom(&self, buf: &mut [u8], flags: c_int) -> io::Result<(usize, SockAddr)> { + unsafe { + let mut storage: SOCKADDR_STORAGE = mem::zeroed(); + let mut addrlen = mem::size_of_val(&storage) as c_int; + + let n = { + sock::recvfrom( + self.socket, + buf.as_mut_ptr() as *mut c_char, + clamp(buf.len()), + flags, + &mut storage as *mut _ as *mut _, + &mut addrlen, + ) + }; + let n = match n { + sock::SOCKET_ERROR if sock::WSAGetLastError() == sock::WSAESHUTDOWN as i32 => 0, + sock::SOCKET_ERROR => return Err(last_error()), + n => n as usize, + }; + let addr = SockAddr::from_raw_parts(&storage as *const _ as *const _, addrlen); + Ok((n, addr)) + } + } + + pub fn send(&self, buf: &[u8]) -> io::Result<usize> { + unsafe { + let n = { + sock::send( + self.socket, + buf.as_ptr() as *const c_char, + clamp(buf.len()), + 0, + ) + }; + if n == sock::SOCKET_ERROR { + Err(last_error()) + } else { + Ok(n as usize) + } + } + } + + pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> { + unsafe { + let n = { + sock::sendto( + self.socket, + buf.as_ptr() as *const c_char, + clamp(buf.len()), + 0, + addr.as_ptr(), + addr.len(), + ) + }; + if n == sock::SOCKET_ERROR { + Err(last_error()) + } else { + Ok(n as usize) + } + } + } + + // ================================================ + + pub fn ttl(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IP, IP_TTL)?; + Ok(raw as u32) + } + } + + pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IP, IP_TTL, ttl as c_int) } + } + + pub fn unicast_hops_v6(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IPV6 as c_int, IPV6_UNICAST_HOPS)?; + Ok(raw as u32) + } + } + + pub fn set_unicast_hops_v6(&self, hops: u32) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IPV6 as c_int, IPV6_UNICAST_HOPS, hops as c_int) } + } + + pub fn only_v6(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IPV6 as c_int, IPV6_V6ONLY)?; + Ok(raw != 0) + } + } + + pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IPV6 as c_int, IPV6_V6ONLY, only_v6 as c_int) } + } + + pub fn read_timeout(&self) -> io::Result<Option<Duration>> { + unsafe { Ok(ms2dur(self.getsockopt(SOL_SOCKET, SO_RCVTIMEO)?)) } + } + + pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(SOL_SOCKET, SO_RCVTIMEO, dur2ms(dur)?) } + } + + pub fn write_timeout(&self) -> io::Result<Option<Duration>> { + unsafe { Ok(ms2dur(self.getsockopt(SOL_SOCKET, SO_SNDTIMEO)?)) } + } + + pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(SOL_SOCKET, SO_SNDTIMEO, dur2ms(dur)?) } + } + + pub fn nodelay(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_TCP, TCP_NODELAY)?; + Ok(raw != 0) + } + } + + pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_TCP, TCP_NODELAY, nodelay as c_int) } + } + + pub fn broadcast(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(SOL_SOCKET, SO_BROADCAST)?; + Ok(raw != 0) + } + } + + pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { + unsafe { self.setsockopt(SOL_SOCKET, SO_BROADCAST, broadcast as c_int) } + } + + pub fn multicast_loop_v4(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IP, IP_MULTICAST_LOOP)?; + Ok(raw != 0) + } + } + + pub fn set_multicast_loop_v4(&self, multicast_loop_v4: bool) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IP, IP_MULTICAST_LOOP, multicast_loop_v4 as c_int) } + } + + pub fn multicast_ttl_v4(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IP, IP_MULTICAST_TTL)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_ttl_v4(&self, multicast_ttl_v4: u32) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, multicast_ttl_v4 as c_int) } + } + + pub fn multicast_hops_v6(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IPV6 as c_int, IPV6_MULTICAST_HOPS)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_hops_v6(&self, hops: u32) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IPV6 as c_int, IPV6_MULTICAST_HOPS, hops as c_int) } + } + + pub fn multicast_if_v4(&self) -> io::Result<Ipv4Addr> { + unsafe { + let imr_interface: IN_ADDR = self.getsockopt(IPPROTO_IP, IP_MULTICAST_IF)?; + Ok(from_s_addr(imr_interface.S_un)) + } + } + + pub fn set_multicast_if_v4(&self, interface: &Ipv4Addr) -> io::Result<()> { + let interface = to_s_addr(interface); + let imr_interface = IN_ADDR { S_un: interface }; + + unsafe { self.setsockopt(IPPROTO_IP, IP_MULTICAST_IF, imr_interface) } + } + + pub fn multicast_if_v6(&self) -> io::Result<u32> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IPV6 as c_int, IPV6_MULTICAST_IF)?; + Ok(raw as u32) + } + } + + pub fn set_multicast_if_v6(&self, interface: u32) -> io::Result<()> { + unsafe { self.setsockopt(IPPROTO_IPV6 as c_int, IPV6_MULTICAST_IF, interface as c_int) } + } + + pub fn multicast_loop_v6(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(IPPROTO_IPV6 as c_int, IPV6_MULTICAST_LOOP)?; + Ok(raw != 0) + } + } + + pub fn set_multicast_loop_v6(&self, multicast_loop_v6: bool) -> io::Result<()> { + unsafe { + self.setsockopt( + IPPROTO_IPV6 as c_int, + IPV6_MULTICAST_LOOP, + multicast_loop_v6 as c_int, + ) + } + } + + pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + let multiaddr = to_s_addr(multiaddr); + let interface = to_s_addr(interface); + let mreq = IP_MREQ { + imr_multiaddr: IN_ADDR { S_un: multiaddr }, + imr_interface: IN_ADDR { S_un: interface }, + }; + unsafe { self.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq) } + } + + pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + let multiaddr = to_in6_addr(multiaddr); + let mreq = IPV6_MREQ { + ipv6mr_multiaddr: multiaddr, + ipv6mr_interface: interface, + }; + unsafe { self.setsockopt(IPPROTO_IP, IPV6_ADD_MEMBERSHIP, mreq) } + } + + pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { + let multiaddr = to_s_addr(multiaddr); + let interface = to_s_addr(interface); + let mreq = IP_MREQ { + imr_multiaddr: IN_ADDR { S_un: multiaddr }, + imr_interface: IN_ADDR { S_un: interface }, + }; + unsafe { self.setsockopt(IPPROTO_IP, IP_DROP_MEMBERSHIP, mreq) } + } + + pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { + let multiaddr = to_in6_addr(multiaddr); + let mreq = IPV6_MREQ { + ipv6mr_multiaddr: multiaddr, + ipv6mr_interface: interface, + }; + unsafe { self.setsockopt(IPPROTO_IP, IPV6_DROP_MEMBERSHIP, mreq) } + } + + pub fn linger(&self) -> io::Result<Option<Duration>> { + unsafe { Ok(linger2dur(self.getsockopt(SOL_SOCKET, SO_LINGER)?)) } + } + + pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> { + unsafe { self.setsockopt(SOL_SOCKET, SO_LINGER, dur2linger(dur)) } + } + + pub fn set_reuse_address(&self, reuse: bool) -> io::Result<()> { + unsafe { self.setsockopt(SOL_SOCKET, SO_REUSEADDR, reuse as c_int) } + } + + pub fn reuse_address(&self) -> io::Result<bool> { + unsafe { + let raw: c_int = self.getsockopt(SOL_SOCKET, SO_REUSEADDR)?; + Ok(raw != 0) + } + } + + pub fn recv_buffer_size(&self) -> io::Result<usize> { + unsafe { + let raw: c_int = self.getsockopt(SOL_SOCKET, SO_RCVBUF)?; + Ok(raw as usize) + } + } + + pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> { + unsafe { + // TODO: casting usize to a c_int should be a checked cast + self.setsockopt(SOL_SOCKET, SO_RCVBUF, size as c_int) + } + } + + pub fn send_buffer_size(&self) -> io::Result<usize> { + unsafe { + let raw: c_int = self.getsockopt(SOL_SOCKET, SO_SNDBUF)?; + Ok(raw as usize) + } + } + + pub fn set_send_buffer_size(&self, size: usize) -> io::Result<()> { + unsafe { + // TODO: casting usize to a c_int should be a checked cast + self.setsockopt(SOL_SOCKET, SO_SNDBUF, size as c_int) + } + } + + pub fn keepalive(&self) -> io::Result<Option<Duration>> { + let mut ka = tcp_keepalive { + onoff: 0, + keepalivetime: 0, + keepaliveinterval: 0, + }; + let n = unsafe { + sock::WSAIoctl( + self.socket, + SIO_KEEPALIVE_VALS, + 0 as *mut _, + 0, + &mut ka as *mut _ as *mut _, + mem::size_of_val(&ka) as DWORD, + 0 as *mut _, + 0 as *mut _, + None, + ) + }; + if n == 0 { + Ok(if ka.onoff == 0 { + None + } else if ka.keepaliveinterval == 0 { + None + } else { + let seconds = ka.keepaliveinterval / 1000; + let nanos = (ka.keepaliveinterval % 1000) * 1_000_000; + Some(Duration::new(seconds as u64, nanos as u32)) + }) + } else { + Err(last_error()) + } + } + + pub fn set_keepalive(&self, keepalive: Option<Duration>) -> io::Result<()> { + let ms = dur2ms(keepalive)?; + // TODO: checked casts here + let ka = tcp_keepalive { + onoff: keepalive.is_some() as c_ulong, + keepalivetime: ms as c_ulong, + keepaliveinterval: ms as c_ulong, + }; + let n = unsafe { + sock::WSAIoctl( + self.socket, + SIO_KEEPALIVE_VALS, + &ka as *const _ as *mut _, + mem::size_of_val(&ka) as DWORD, + 0 as *mut _, + 0, + 0 as *mut _, + 0 as *mut _, + None, + ) + }; + if n == 0 { + Ok(()) + } else { + Err(last_error()) + } + } + + unsafe fn setsockopt<T>(&self, opt: c_int, val: c_int, payload: T) -> io::Result<()> + where + T: Copy, + { + let payload = &payload as *const T as *const c_char; + if sock::setsockopt(self.socket, opt, val, payload, mem::size_of::<T>() as c_int) == 0 { + Ok(()) + } else { + Err(last_error()) + } + } + + unsafe fn getsockopt<T: Copy>(&self, opt: c_int, val: c_int) -> io::Result<T> { + let mut slot: T = mem::zeroed(); + let mut len = mem::size_of::<T>() as c_int; + if sock::getsockopt( + self.socket, + opt, + val, + &mut slot as *mut _ as *mut _, + &mut len, + ) == 0 + { + assert_eq!(len as usize, mem::size_of::<T>()); + Ok(slot) + } else { + Err(last_error()) + } + } + + fn set_no_inherit(&self) -> io::Result<()> { + unsafe { + let r = SetHandleInformation(self.socket as HANDLE, HANDLE_FLAG_INHERIT, 0); + if r == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } + } + } +} + +impl Read for Socket { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + <&Socket>::read(&mut &*self, buf) + } +} + +impl<'a> Read for &'a Socket { + fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.recv(buf) + } +} + +impl Write for Socket { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + <&Socket>::write(&mut &*self, buf) + } + + fn flush(&mut self) -> io::Result<()> { + <&Socket>::flush(&mut &*self) + } +} + +impl<'a> Write for &'a Socket { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.send(buf) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl fmt::Debug for Socket { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_struct("Socket"); + f.field("socket", &self.socket); + if let Ok(addr) = self.local_addr() { + f.field("local_addr", &addr); + } + if let Ok(addr) = self.peer_addr() { + f.field("peer_addr", &addr); + } + f.finish() + } +} + +impl AsRawSocket for Socket { + fn as_raw_socket(&self) -> RawSocket { + self.socket as RawSocket + } +} + +impl IntoRawSocket for Socket { + fn into_raw_socket(self) -> RawSocket { + let socket = self.socket; + mem::forget(self); + socket as RawSocket + } +} + +impl FromRawSocket for Socket { + unsafe fn from_raw_socket(socket: RawSocket) -> Socket { + Socket { + socket: socket as sock::SOCKET, + } + } +} + +impl AsRawSocket for ::Socket { + fn as_raw_socket(&self) -> RawSocket { + self.inner.as_raw_socket() + } +} + +impl IntoRawSocket for ::Socket { + fn into_raw_socket(self) -> RawSocket { + self.inner.into_raw_socket() + } +} + +impl FromRawSocket for ::Socket { + unsafe fn from_raw_socket(socket: RawSocket) -> ::Socket { + ::Socket { + inner: Socket::from_raw_socket(socket), + } + } +} + +impl Drop for Socket { + fn drop(&mut self) { + unsafe { + let _ = sock::closesocket(self.socket); + } + } +} + +impl From<Socket> for net::TcpStream { + fn from(socket: Socket) -> net::TcpStream { + unsafe { net::TcpStream::from_raw_socket(socket.into_raw_socket()) } + } +} + +impl From<Socket> for net::TcpListener { + fn from(socket: Socket) -> net::TcpListener { + unsafe { net::TcpListener::from_raw_socket(socket.into_raw_socket()) } + } +} + +impl From<Socket> for net::UdpSocket { + fn from(socket: Socket) -> net::UdpSocket { + unsafe { net::UdpSocket::from_raw_socket(socket.into_raw_socket()) } + } +} + +impl From<net::TcpStream> for Socket { + fn from(socket: net::TcpStream) -> Socket { + unsafe { Socket::from_raw_socket(socket.into_raw_socket()) } + } +} + +impl From<net::TcpListener> for Socket { + fn from(socket: net::TcpListener) -> Socket { + unsafe { Socket::from_raw_socket(socket.into_raw_socket()) } + } +} + +impl From<net::UdpSocket> for Socket { + fn from(socket: net::UdpSocket) -> Socket { + unsafe { Socket::from_raw_socket(socket.into_raw_socket()) } + } +} + +fn clamp(input: usize) -> c_int { + cmp::min(input, <c_int>::max_value() as usize) as c_int +} + +fn dur2ms(dur: Option<Duration>) -> io::Result<DWORD> { + match dur { + Some(dur) => { + // Note that a duration is a (u64, u32) (seconds, nanoseconds) + // pair, and the timeouts in windows APIs are typically u32 + // milliseconds. To translate, we have two pieces to take care of: + // + // * Nanosecond precision is rounded up + // * Greater than u32::MAX milliseconds (50 days) is rounded up to + // INFINITE (never time out). + let ms = dur.as_secs() + .checked_mul(1000) + .and_then(|ms| ms.checked_add((dur.subsec_nanos() as u64) / 1_000_000)) + .and_then(|ms| { + ms.checked_add(if dur.subsec_nanos() % 1_000_000 > 0 { + 1 + } else { + 0 + }) + }) + .map(|ms| { + if ms > <DWORD>::max_value() as u64 { + INFINITE + } else { + ms as DWORD + } + }) + .unwrap_or(INFINITE); + if ms == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "cannot set a 0 duration timeout", + )); + } + Ok(ms) + } + None => Ok(0), + } +} + +fn ms2dur(raw: DWORD) -> Option<Duration> { + if raw == 0 { + None + } else { + let secs = raw / 1000; + let nsec = (raw % 1000) * 1000000; + Some(Duration::new(secs as u64, nsec as u32)) + } +} + +fn to_s_addr(addr: &Ipv4Addr) -> in_addr_S_un { + let octets = addr.octets(); + let res = ::hton( + ((octets[0] as ULONG) << 24) | ((octets[1] as ULONG) << 16) | ((octets[2] as ULONG) << 8) + | ((octets[3] as ULONG) << 0), + ); + let mut new_addr: in_addr_S_un = unsafe { mem::zeroed() }; + unsafe { *(new_addr.S_addr_mut()) = res }; + new_addr +} + +fn from_s_addr(in_addr: in_addr_S_un) -> Ipv4Addr { + let h_addr = ::ntoh(unsafe { *in_addr.S_addr() }); + + let a: u8 = (h_addr >> 24) as u8; + let b: u8 = (h_addr >> 16) as u8; + let c: u8 = (h_addr >> 8) as u8; + let d: u8 = (h_addr >> 0) as u8; + + Ipv4Addr::new(a, b, c, d) +} + +fn to_in6_addr(addr: &Ipv6Addr) -> in6_addr { + let mut ret_addr: in6_addr_u = unsafe { mem::zeroed() }; + unsafe { *(ret_addr.Byte_mut()) = addr.octets() }; + let mut ret: in6_addr = unsafe { mem::zeroed() }; + ret.u = ret_addr; + ret +} + +fn linger2dur(linger_opt: sock::linger) -> Option<Duration> { + if linger_opt.l_onoff == 0 { + None + } else { + Some(Duration::from_secs(linger_opt.l_linger as u64)) + } +} + +fn dur2linger(dur: Option<Duration>) -> sock::linger { + match dur { + Some(d) => sock::linger { + l_onoff: 1, + l_linger: d.as_secs() as u16, + }, + None => sock::linger { + l_onoff: 0, + l_linger: 0, + }, + } +} + +#[test] +fn test_ip() { + let ip = Ipv4Addr::new(127, 0, 0, 1); + assert_eq!(ip, from_s_addr(to_s_addr(&ip))); +} diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/src/utils.rs cargo-0.26.0/vendor/socket2-0.3.4/src/utils.rs --- cargo-0.25.0/vendor/socket2-0.3.4/src/utils.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/src/utils.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,48 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[doc(hidden)] +pub trait NetInt { + fn from_be(i: Self) -> Self; + fn to_be(&self) -> Self; +} +macro_rules! doit { + ($($t:ident)*) => ($(impl NetInt for $t { + fn from_be(i: Self) -> Self { <$t>::from_be(i) } + fn to_be(&self) -> Self { <$t>::to_be(*self) } + })*) +} +doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } + +#[doc(hidden)] +pub trait One { + fn one() -> Self; +} + +macro_rules! one { + ($($t:ident)*) => ($( + impl One for $t { fn one() -> $t { 1 } } + )*) +} + +one! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } + +#[doc(hidden)] +pub trait Zero { + fn zero() -> Self; +} + +macro_rules! zero { + ($($t:ident)*) => ($( + impl Zero for $t { fn zero() -> $t { 0 } } + )*) +} + +zero! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } diff -Nru cargo-0.25.0/vendor/socket2-0.3.4/.travis.yml cargo-0.26.0/vendor/socket2-0.3.4/.travis.yml --- cargo-0.25.0/vendor/socket2-0.3.4/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/socket2-0.3.4/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,30 @@ +language: rust +sudo: false + +matrix: + include: + - rust: 1.21.0 + - rust: stable + - os: osx + - rust: beta + - rust: nightly + + - rust: nightly + before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH + script: + - cargo doc --no-deps --all-features + after_success: + - travis-cargo --only nightly doc-upload + +script: + - cargo test + - cargo test --features "reuseport unix pair" + +env: + global: + secure: "qibsiOrfM/GjYgYFXycSqKMwIK9ZR4cvHZsSqTtqrtxGq5Q7jTwMqdDl8KHDgX1a4it4tGay+7joex8k2zL6OQ+FljQGQq54EDiGw82HWix/fBpOMjMszw+GEDMG/9hUSb6HFdzAKLPAsBRvIs2QteJ60GhL/w4Z/EmfHlVKMnVsYUjfBf5BNlkv8yFvRMY6QqL+F85N7dDQ7JAgdiP79jR7LP8IlCEu/8pgSrf9pSqAHSC1Co1CaN8uhhMlcIIOZ5qYAK4Xty26r2EDzPm5Lw2Bd7a4maN0x+Be2DJvrnX30QkJNNU1XhxYkeZEeUCYAlUhBE5nBHpyyrbAxv+rJodPeyRl5EVpyqi8htPVmcnuA2XpNoHCud7CnzxaFytGvAC5kp0EgS7f3ac4hTnZXCfP0CvnT5UyWfWv9yLwQycdYcAsV4TnKxVAw4ykApGey+h0dyIM2VnzRPOo9D2ZS+JpzPHtx/PXD7aN7IungfTj4PmT+i00QNzkzJR9BqYKmEDBUcz6MLctg4D6xChhN8Go4hvk22F0RVyvEg1MAvXc07EKeWXG/VZ+H2frcPEceMGRBBHiOfOEE/2utNYgvIcmQxd1hvbm3cQOIjeXU2rGneN86cSmx7zNlfOyJUoBfsgGvSEzRxUueibUCaujB/El70HGrMlTnXeERiyd/2Y=" + +notifications: + email: + on_success: never diff -Nru cargo-0.25.0/vendor/syn-0.13.1/.cargo-checksum.json cargo-0.26.0/vendor/syn-0.13.1/.cargo-checksum.json --- cargo-0.25.0/vendor/syn-0.13.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"91b52877572087400e83d24b9178488541e3d535259e04ff17a63df1e5ceff59"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/syn-0.13.1/Cargo.toml cargo-0.26.0/vendor/syn-0.13.1/Cargo.toml --- cargo-0.25.0/vendor/syn-0.13.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,59 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "syn" +version = "0.13.1" +authors = ["David Tolnay <dtolnay@gmail.com>"] +include = ["/Cargo.toml", "/src/**/*.rs", "/README.md", "/LICENSE-APACHE", "/LICENSE-MIT"] +description = "Nom parser for Rust source code" +documentation = "https://docs.rs/syn" +readme = "README.md" +categories = ["development-tools::procedural-macro-helpers"] +license = "MIT/Apache-2.0" +repository = "https://github.com/dtolnay/syn" +[package.metadata.docs.rs] +all-features = true + +[[example]] +name = "dump-syntax" +path = "examples/dump-syntax/main.rs" +required-features = ["full", "parsing", "extra-traits"] +[dependencies.proc-macro2] +version = "0.3" +default-features = false + +[dependencies.quote] +version = "0.5" +optional = true +default-features = false + +[dependencies.unicode-xid] +version = "0.1" +[dev-dependencies.rayon] +version = "1.0.0" + +[dev-dependencies.walkdir] +version = "2" + +[features] +clone-impls = [] +default = ["derive", "parsing", "printing", "clone-impls", "proc-macro"] +derive = [] +extra-traits = [] +fold = [] +full = [] +parsing = [] +printing = ["quote"] +proc-macro = ["proc-macro2/proc-macro", "quote/proc-macro"] +visit = [] +visit-mut = [] diff -Nru cargo-0.25.0/vendor/syn-0.13.1/LICENSE-APACHE cargo-0.26.0/vendor/syn-0.13.1/LICENSE-APACHE --- cargo-0.25.0/vendor/syn-0.13.1/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/syn-0.13.1/LICENSE-MIT cargo-0.26.0/vendor/syn-0.13.1/LICENSE-MIT --- cargo-0.25.0/vendor/syn-0.13.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2018 Syn 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. diff -Nru cargo-0.25.0/vendor/syn-0.13.1/README.md cargo-0.26.0/vendor/syn-0.13.1/README.md --- cargo-0.25.0/vendor/syn-0.13.1/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,278 @@ +Nom parser for Rust source code +=============================== + +[![Build Status](https://api.travis-ci.org/dtolnay/syn.svg?branch=master)](https://travis-ci.org/dtolnay/syn) +[![Latest Version](https://img.shields.io/crates/v/syn.svg)](https://crates.io/crates/syn) +[![Rust Documentation](https://img.shields.io/badge/api-rustdoc-blue.svg)](https://docs.rs/syn/0.13/syn/) +[![Rustc Version 1.15+](https://img.shields.io/badge/rustc-1.15+-lightgray.svg)](https://blog.rust-lang.org/2017/02/02/Rust-1.15.html) + +Syn is a parsing library for parsing a stream of Rust tokens into a syntax tree +of Rust source code. + +Currently this library is geared toward the [custom derive] use case but +contains some APIs that may be useful for Rust procedural macros more generally. + +[custom derive]: https://github.com/rust-lang/rfcs/blob/master/text/1681-macros-1.1.md + +- **Data structures** — Syn provides a complete syntax tree that can represent + any valid Rust source code. The syntax tree is rooted at [`syn::File`] which + represents a full source file, but there are other entry points that may be + useful to procedural macros including [`syn::Item`], [`syn::Expr`] and + [`syn::Type`]. + +- **Custom derives** — Of particular interest to custom derives is + [`syn::DeriveInput`] which is any of the three legal input items to a derive + macro. An example below shows using this type in a library that can derive + implementations of a trait of your own. + +- **Parser combinators** — Parsing in Syn is built on a suite of public parser + combinator macros that you can use for parsing any token-based syntax you + dream up within a `functionlike!(...)` procedural macro. Every syntax tree + node defined by Syn is individually parsable and may be used as a building + block for custom syntaxes, or you may do it all yourself working from the most + primitive tokens. + +- **Location information** — Every token parsed by Syn is associated with a + `Span` that tracks line and column information back to the source of that + token. These spans allow a procedural macro to display detailed error messages + pointing to all the right places in the user's code. There is an example of + this below. + +- **Feature flags** — Functionality is aggressively feature gated so your + procedural macros enable only what they need, and do not pay in compile time + for all the rest. + +[`syn::File`]: https://docs.rs/syn/0.13/syn/struct.File.html +[`syn::Item`]: https://docs.rs/syn/0.13/syn/enum.Item.html +[`syn::Expr`]: https://docs.rs/syn/0.13/syn/enum.Expr.html +[`syn::Type`]: https://docs.rs/syn/0.13/syn/enum.Type.html +[`syn::DeriveInput`]: https://docs.rs/syn/0.13/syn/struct.DeriveInput.html + +If you get stuck with anything involving procedural macros in Rust I am happy to +provide help even if the issue is not related to Syn. Please file a ticket in +this repo. + +*Version requirement: Syn supports any compiler version back to Rust's very +first support for procedural macros in Rust 1.15.0. Some features especially +around error reporting are only available in newer compilers or on the nightly +channel.* + +## Example of a custom derive + +The canonical custom derive using Syn looks like this. We write an ordinary Rust +function tagged with a `proc_macro_derive` attribute and the name of the trait +we are deriving. Any time that derive appears in the user's code, the Rust +compiler passes their data structure as tokens into our macro. We get to execute +arbitrary Rust code to figure out what to do with those tokens, then hand some +tokens back to the compiler to compile into the user's crate. + +[`TokenStream`]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html + +```toml +[dependencies] +syn = "0.13" +quote = "0.5" + +[lib] +proc-macro = true +``` + +```rust +extern crate proc_macro; +extern crate syn; + +#[macro_use] +extern crate quote; + +use proc_macro::TokenStream; +use syn::DeriveInput; + +#[proc_macro_derive(MyMacro)] +pub fn my_macro(input: TokenStream) -> TokenStream { + // Parse the input tokens into a syntax tree + let input: DeriveInput = syn::parse(input).unwrap(); + + // Build the output, possibly using quasi-quotation + let expanded = quote! { + // ... + }; + + // Hand the output tokens back to the compiler + expanded.into() +} +``` + +The [`heapsize`] example directory shows a complete working Macros 1.1 +implementation of a custom derive. It works on any Rust compiler \>=1.15.0. The +example derives a `HeapSize` trait which computes an estimate of the amount of +heap memory owned by a value. + +[`heapsize`]: examples/heapsize + +```rust +pub trait HeapSize { + /// Total number of bytes of heap memory owned by `self`. + fn heap_size_of_children(&self) -> usize; +} +``` + +The custom derive allows users to write `#[derive(HeapSize)]` on data structures +in their program. + +```rust +#[derive(HeapSize)] +struct Demo<'a, T: ?Sized> { + a: Box<T>, + b: u8, + c: &'a str, + d: String, +} +``` + +## Spans and error reporting + +The [`heapsize2`] example directory is an extension of the `heapsize` example +that demonstrates some of the hygiene and error reporting properties of Macros +2.0. This example currently requires a nightly Rust compiler \>=1.24.0-nightly +but we are working to stabilize all of the APIs involved. + +[`heapsize2`]: examples/heapsize2 + +The token-based procedural macro API provides great control over where the +compiler's error messages are displayed in user code. Consider the error the +user sees if one of their field types does not implement `HeapSize`. + +```rust +#[derive(HeapSize)] +struct Broken { + ok: String, + bad: std::thread::Thread, +} +``` + +In the Macros 1.1 string-based procedural macro world, the resulting error would +point unhelpfully to the invocation of the derive macro and not to the actual +problematic field. + +``` +error[E0599]: no method named `heap_size_of_children` found for type `std::thread::Thread` in the current scope + --> src/main.rs:4:10 + | +4 | #[derive(HeapSize)] + | ^^^^^^^^ +``` + +By tracking span information all the way through the expansion of a procedural +macro as shown in the `heapsize2` example, token-based macros in Syn are able to +trigger errors that directly pinpoint the source of the problem. + +``` +error[E0277]: the trait bound `std::thread::Thread: HeapSize` is not satisfied + --> src/main.rs:7:5 + | +7 | bad: std::thread::Thread, + | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `std::thread::Thread` +``` + +## Parsing a custom syntax using combinators + +The [`lazy-static`] example directory shows the implementation of a +`functionlike!(...)` procedural macro in which the input tokens are parsed using +[`nom`]-style parser combinators. + +[`lazy-static`]: examples/lazy-static +[`nom`]: https://github.com/Geal/nom + +The example reimplements the popular `lazy_static` crate from crates.io as a +procedural macro. + +``` +lazy_static! { + static ref USERNAME: Regex = Regex::new("^[a-z0-9_-]{3,16}$").unwrap(); +} +``` + +The implementation shows how to trigger custom warnings and error messages on +the macro input. + +``` +warning: come on, pick a more creative name + --> src/main.rs:10:16 + | +10 | static ref FOO: String = "lazy_static".to_owned(); + | ^^^ +``` + +## Debugging + +When developing a procedural macro it can be helpful to look at what the +generated code looks like. Use `cargo rustc -- -Zunstable-options +--pretty=expanded` or the [`cargo expand`] subcommand. + +[`cargo expand`]: https://github.com/dtolnay/cargo-expand + +To show the expanded code for some crate that uses your procedural macro, run +`cargo expand` from that crate. To show the expanded code for one of your own +test cases, run `cargo expand --test the_test_case` where the last argument is +the name of the test file without the `.rs` extension. + +This write-up by Brandon W Maister discusses debugging in more detail: +[Debugging Rust's new Custom Derive system][debugging]. + +[debugging]: https://quodlibetor.github.io/posts/debugging-rusts-new-custom-derive-system/ + +## Optional features + +Syn puts a lot of functionality behind optional features in order to optimize +compile time for the most common use cases. The following features are +available. + +- **`derive`** *(enabled by default)* — Data structures for representing the + possible input to a custom derive, including structs and enums and types. +- **`full`** — Data structures for representing the syntax tree of all valid + Rust source code, including items and expressions. +- **`parsing`** *(enabled by default)* — Ability to parse input tokens into a + syntax tree node of a chosen type. +- **`printing`** *(enabled by default)* — Ability to print a syntax tree node as + tokens of Rust source code. +- **`visit`** — Trait for traversing a syntax tree. +- **`visit-mut`** — Trait for traversing and mutating in place a syntax tree. +- **`fold`** — Trait for transforming an owned syntax tree. +- **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree + types. +- **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree + types. + +## Nightly features + +By default Syn uses the [`proc-macro2`] crate to emulate the nightly compiler's +procedural macro API in a stable way that works all the way back to Rust 1.15.0. +This shim makes it possible to write code without regard for whether the current +compiler version supports the features we use. + +[`proc-macro2`]: https://github.com/alexcrichton/proc-macro2 + +On a nightly compiler, to eliminate the stable shim and use the compiler's +`proc-macro` directly, add `proc-macro2` to your Cargo.toml and set its +`"nightly"` feature which bypasses the stable shim. + +```toml +[dependencies] +syn = "0.13" +proc-macro2 = { version = "0.3", features = ["nightly"] } +``` + +## 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 this crate by you, as defined in the Apache-2.0 license, shall +be dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/attr.rs cargo-0.26.0/vendor/syn-0.13.1/src/attr.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/attr.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/attr.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,556 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use super::*; +use punctuated::Punctuated; + +use std::iter; + +use proc_macro2::{Delimiter, Spacing, TokenStream, TokenTree}; + +#[cfg(feature = "extra-traits")] +use std::hash::{Hash, Hasher}; +#[cfg(feature = "extra-traits")] +use tt::TokenStreamHelper; + +ast_struct! { + /// An attribute like `#[repr(transparent)]`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// # Syntax + /// + /// Rust has six types of attributes. + /// + /// - Outer attributes like `#[repr(transparent)]`. These appear outside or + /// in front of the item they describe. + /// - Inner attributes like `#![feature(proc_macro)]`. These appear inside + /// of the item they describe, usually a module. + /// - Outer doc comments like `/// # Example`. + /// - Inner doc comments like `//! Please file an issue`. + /// - Outer block comments `/** # Example */`. + /// - Inner block comments `/*! Please file an issue */`. + /// + /// The `style` field of type `AttrStyle` distinguishes whether an attribute + /// is outer or inner. Doc comments and block comments are promoted to + /// attributes that have `is_sugared_doc` set to true, as this is how they + /// are processed by the compiler and by `macro_rules!` macros. + /// + /// The `path` field gives the possibly colon-delimited path against which + /// the attribute is resolved. It is equal to `"doc"` for desugared doc + /// comments. The `tts` field contains the rest of the attribute body as + /// tokens. + /// + /// ```text + /// #[derive(Copy)] #[crate::precondition x < 5] + /// ^^^^^^~~~~~~ ^^^^^^^^^^^^^^^^^^^ ~~~~~ + /// path tts path tts + /// ``` + /// + /// Use the [`interpret_meta`] method to try parsing the tokens of an + /// attribute into the structured representation that is used by convention + /// across most Rust libraries. + /// + /// [`interpret_meta`]: #method.interpret_meta + pub struct Attribute #manual_extra_traits { + pub pound_token: Token![#], + pub style: AttrStyle, + pub bracket_token: token::Bracket, + pub path: Path, + pub tts: TokenStream, + pub is_sugared_doc: bool, + } +} + +#[cfg(feature = "extra-traits")] +impl Eq for Attribute {} + +#[cfg(feature = "extra-traits")] +impl PartialEq for Attribute { + fn eq(&self, other: &Self) -> bool { + self.style == other.style && self.pound_token == other.pound_token + && self.bracket_token == other.bracket_token && self.path == other.path + && TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) + && self.is_sugared_doc == other.is_sugared_doc + } +} + +#[cfg(feature = "extra-traits")] +impl Hash for Attribute { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.style.hash(state); + self.pound_token.hash(state); + self.bracket_token.hash(state); + self.path.hash(state); + TokenStreamHelper(&self.tts).hash(state); + self.is_sugared_doc.hash(state); + } +} + +impl Attribute { + /// Parses the tokens after the path as a [`Meta`](enum.Meta.html) if + /// possible. + pub fn interpret_meta(&self) -> Option<Meta> { + let name = if self.path.segments.len() == 1 { + &self.path.segments.first().unwrap().value().ident + } else { + return None; + }; + + if self.tts.is_empty() { + return Some(Meta::Word(*name)); + } + + let tts = self.tts.clone().into_iter().collect::<Vec<_>>(); + + if tts.len() == 1 { + if let Some(meta) = Attribute::extract_meta_list(*name, &tts[0]) { + return Some(meta); + } + } + + if tts.len() == 2 { + if let Some(meta) = Attribute::extract_name_value(*name, &tts[0], &tts[1]) { + return Some(meta); + } + } + + None + } + + fn extract_meta_list(ident: Ident, tt: &TokenTree) -> Option<Meta> { + let g = match *tt { + TokenTree::Group(ref g) => g, + _ => return None, + }; + if g.delimiter() != Delimiter::Parenthesis { + return None + } + let tokens = g.stream().clone().into_iter().collect::<Vec<_>>(); + let nested = match list_of_nested_meta_items_from_tokens(&tokens) { + Some(n) => n, + None => return None, + }; + Some(Meta::List(MetaList { + paren_token: token::Paren(g.span()), + ident: ident, + nested: nested, + })) + } + + fn extract_name_value(ident: Ident, a: &TokenTree, b: &TokenTree) -> Option<Meta> { + let a = match *a { + TokenTree::Op(ref o) => o, + _ => return None, + }; + if a.spacing() != Spacing::Alone { + return None + } + if a.op() != '=' { + return None + } + + match *b { + TokenTree::Literal(ref l) if !l.to_string().starts_with('/') => { + Some(Meta::NameValue(MetaNameValue { + ident: ident, + eq_token: Token![=]([a.span()]), + lit: Lit::new(l.clone()), + })) + } + TokenTree::Term(ref term) => { + match term.as_str() { + v @ "true" | v @ "false" => { + Some(Meta::NameValue(MetaNameValue { + ident: ident, + eq_token: Token![=]([a.span()]), + lit: Lit::Bool(LitBool { + value: v == "true", + span: b.span(), + }), + })) + }, + _ => None , + } + } + _ => None, + } + } +} + +fn nested_meta_item_from_tokens(tts: &[TokenTree]) -> Option<(NestedMeta, &[TokenTree])> { + assert!(!tts.is_empty()); + + match tts[0] { + TokenTree::Literal(ref lit) => { + if lit.to_string().starts_with('/') { + None + } else { + let lit = Lit::new(lit.clone()); + Some((NestedMeta::Literal(lit), &tts[1..])) + } + } + + TokenTree::Term(sym) => { + let ident = Ident::new(sym.as_str(), sym.span()); + if tts.len() >= 3 { + if let Some(meta) = Attribute::extract_name_value(ident, &tts[1], &tts[2]) { + return Some((NestedMeta::Meta(meta), &tts[3..])) + } + } + + if tts.len() >= 2 { + if let Some(meta) = Attribute::extract_meta_list(ident, &tts[1]) { + return Some((NestedMeta::Meta(meta), &tts[2..])) + } + } + + Some((Meta::Word(ident).into(), &tts[1..])) + } + + _ => None, + } +} + +fn list_of_nested_meta_items_from_tokens( + mut tts: &[TokenTree], +) -> Option<Punctuated<NestedMeta, Token![,]>> { + let mut nested_meta_items = Punctuated::new(); + let mut first = true; + + while !tts.is_empty() { + let prev_comma = if first { + first = false; + None + } else if let TokenTree::Op(ref op) = tts[0] { + if op.spacing() != Spacing::Alone { + return None + } + if op.op() != ',' { + return None + } + let tok = Token![,]([op.span()]); + tts = &tts[1..]; + if tts.is_empty() { + break; + } + Some(tok) + } else { + return None; + }; + let (nested, rest) = match nested_meta_item_from_tokens(tts) { + Some(pair) => pair, + None => return None, + }; + if let Some(comma) = prev_comma { + nested_meta_items.push_punct(comma); + } + nested_meta_items.push_value(nested); + tts = rest; + } + + Some(nested_meta_items) +} + +ast_enum! { + /// Distinguishes between attributes that decorate an item and attributes + /// that are contained within an item. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// # Outer attributes + /// + /// - `#[repr(transparent)]` + /// - `/// # Example` + /// - `/** Please file an issue */` + /// + /// # Inner attributes + /// + /// - `#![feature(proc_macro)]` + /// - `//! # Example` + /// - `/*! Please file an issue */` + #[cfg_attr(feature = "clone-impls", derive(Copy))] + pub enum AttrStyle { + Outer, + Inner(Token![!]), + } +} + +ast_enum_of_structs! { + /// Content of a compile-time structured attribute. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// ## Word + /// + /// A meta word is like the `test` in `#[test]`. + /// + /// ## List + /// + /// A meta list is like the `derive(Copy)` in `#[derive(Copy)]`. + /// + /// ## NameValue + /// + /// A name-value meta is like the `path = "..."` in `#[path = + /// "sys/windows.rs"]`. + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum Meta { + pub Word(Ident), + /// A structured list within an attribute, like `derive(Copy, Clone)`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub List(MetaList { + pub ident: Ident, + pub paren_token: token::Paren, + pub nested: Punctuated<NestedMeta, Token![,]>, + }), + /// A name-value pair within an attribute, like `feature = "nightly"`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub NameValue(MetaNameValue { + pub ident: Ident, + pub eq_token: Token![=], + pub lit: Lit, + }), + } +} + +impl Meta { + /// Returns the identifier that begins this structured meta item. + /// + /// For example this would return the `test` in `#[test]`, the `derive` in + /// `#[derive(Copy)]`, and the `path` in `#[path = "sys/windows.rs"]`. + pub fn name(&self) -> Ident { + match *self { + Meta::Word(ref meta) => *meta, + Meta::List(ref meta) => meta.ident, + Meta::NameValue(ref meta) => meta.ident, + } + } +} + +ast_enum_of_structs! { + /// Element of a compile-time attribute list. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub enum NestedMeta { + /// A structured meta item, like the `Copy` in `#[derive(Copy)]` which + /// would be a nested `Meta::Word`. + pub Meta(Meta), + + /// A Rust literal, like the `"new_name"` in `#[rename("new_name")]`. + pub Literal(Lit), + } +} + +pub trait FilterAttrs<'a> { + type Ret: Iterator<Item = &'a Attribute>; + + fn outer(self) -> Self::Ret; + fn inner(self) -> Self::Ret; +} + +impl<'a, T> FilterAttrs<'a> for T +where + T: IntoIterator<Item = &'a Attribute>, +{ + type Ret = iter::Filter<T::IntoIter, fn(&&Attribute) -> bool>; + + fn outer(self) -> Self::Ret { + fn is_outer(attr: &&Attribute) -> bool { + match attr.style { + AttrStyle::Outer => true, + _ => false, + } + } + self.into_iter().filter(is_outer) + } + + fn inner(self) -> Self::Ret { + fn is_inner(attr: &&Attribute) -> bool { + match attr.style { + AttrStyle::Inner(_) => true, + _ => false, + } + } + self.into_iter().filter(is_inner) + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + use buffer::Cursor; + use parse_error; + use synom::PResult; + use proc_macro2::{Literal, Spacing, Span, TokenTree, Op}; + + fn eq(span: Span) -> TokenTree { + let mut op = Op::new('=', Spacing::Alone); + op.set_span(span); + op.into() + } + + impl Attribute { + named!(pub parse_inner -> Self, alt!( + do_parse!( + pound: punct!(#) >> + bang: punct!(!) >> + path_and_tts: brackets!(tuple!( + call!(Path::parse_mod_style), + syn!(TokenStream) + )) >> + ({ + let (bracket, (path, tts)) = path_and_tts; + + Attribute { + style: AttrStyle::Inner(bang), + path: path, + tts: tts, + is_sugared_doc: false, + pound_token: pound, + bracket_token: bracket, + } + }) + ) + | + map!( + call!(lit_doc_comment, Comment::Inner), + |lit| { + let span = lit.span(); + Attribute { + style: AttrStyle::Inner(<Token![!]>::new(span)), + path: Ident::new("doc", span).into(), + tts: vec![ + eq(span), + lit, + ].into_iter().collect(), + is_sugared_doc: true, + pound_token: <Token![#]>::new(span), + bracket_token: token::Bracket(span), + } + } + ) + )); + + named!(pub parse_outer -> Self, alt!( + do_parse!( + pound: punct!(#) >> + path_and_tts: brackets!(tuple!( + call!(Path::parse_mod_style), + syn!(TokenStream) + )) >> + ({ + let (bracket, (path, tts)) = path_and_tts; + + Attribute { + style: AttrStyle::Outer, + path: path, + tts: tts, + is_sugared_doc: false, + pound_token: pound, + bracket_token: bracket, + } + }) + ) + | + map!( + call!(lit_doc_comment, Comment::Outer), + |lit| { + let span = lit.span(); + Attribute { + style: AttrStyle::Outer, + path: Ident::new("doc", span).into(), + tts: vec![ + eq(span), + lit, + ].into_iter().collect(), + is_sugared_doc: true, + pound_token: <Token![#]>::new(span), + bracket_token: token::Bracket(span), + } + } + ) + )); + } + + enum Comment { + Inner, + Outer, + } + + fn lit_doc_comment(input: Cursor, style: Comment) -> PResult<TokenTree> { + match input.literal() { + Some((lit, rest)) => { + let string = lit.to_string(); + let ok = match style { + Comment::Inner => string.starts_with("//!") || string.starts_with("/*!"), + Comment::Outer => string.starts_with("///") || string.starts_with("/**"), + }; + if ok { + let mut new = Literal::string(&string); + new.set_span(lit.span()); + Ok((new.into(), rest)) + } else { + parse_error() + } + } + _ => parse_error(), + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use quote::{ToTokens, Tokens}; + + impl ToTokens for Attribute { + fn to_tokens(&self, tokens: &mut Tokens) { + self.pound_token.to_tokens(tokens); + if let AttrStyle::Inner(ref b) = self.style { + b.to_tokens(tokens); + } + self.bracket_token.surround(tokens, |tokens| { + self.path.to_tokens(tokens); + self.tts.to_tokens(tokens); + }); + } + } + + impl ToTokens for MetaList { + fn to_tokens(&self, tokens: &mut Tokens) { + self.ident.to_tokens(tokens); + self.paren_token.surround(tokens, |tokens| { + self.nested.to_tokens(tokens); + }) + } + } + + impl ToTokens for MetaNameValue { + fn to_tokens(&self, tokens: &mut Tokens) { + self.ident.to_tokens(tokens); + self.eq_token.to_tokens(tokens); + self.lit.to_tokens(tokens); + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/buffer.rs cargo-0.26.0/vendor/syn-0.13.1/src/buffer.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/buffer.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/buffer.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,460 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A stably addressed token buffer supporting efficient traversal based on a +//! cheaply copyable cursor. +//! +//! The [`Synom`] trait is implemented for syntax tree types that can be parsed +//! from one of these token cursors. +//! +//! [`Synom`]: ../synom/trait.Synom.html +//! +//! *This module is available if Syn is built with the `"parsing"` feature.* +//! +//! # Example +//! +//! This example shows a basic token parser for parsing a token stream without +//! using Syn's parser combinator macros. +//! +//! ``` +//! #![feature(proc_macro)] +//! +//! extern crate syn; +//! extern crate proc_macro; +//! +//! #[macro_use] +//! extern crate quote; +//! +//! use syn::{token, ExprTuple}; +//! use syn::buffer::{Cursor, TokenBuffer}; +//! use syn::spanned::Spanned; +//! use syn::synom::Synom; +//! use proc_macro::{Diagnostic, Span, TokenStream}; +//! +//! /// A basic token parser for parsing a token stream without using Syn's +//! /// parser combinator macros. +//! pub struct Parser<'a> { +//! cursor: Cursor<'a>, +//! } +//! +//! impl<'a> Parser<'a> { +//! pub fn new(cursor: Cursor<'a>) -> Self { +//! Parser { cursor } +//! } +//! +//! pub fn current_span(&self) -> Span { +//! self.cursor.span().unstable() +//! } +//! +//! pub fn parse<T: Synom>(&mut self) -> Result<T, Diagnostic> { +//! let (val, rest) = T::parse(self.cursor) +//! .map_err(|e| match T::description() { +//! Some(desc) => { +//! self.current_span().error(format!("{}: expected {}", e, desc)) +//! } +//! None => { +//! self.current_span().error(e.to_string()) +//! } +//! })?; +//! +//! self.cursor = rest; +//! Ok(val) +//! } +//! +//! pub fn expect_eof(&mut self) -> Result<(), Diagnostic> { +//! if !self.cursor.eof() { +//! return Err(self.current_span().error("trailing characters; expected eof")); +//! } +//! +//! Ok(()) +//! } +//! } +//! +//! fn eval(input: TokenStream) -> Result<TokenStream, Diagnostic> { +//! let buffer = TokenBuffer::new(input); +//! let mut parser = Parser::new(buffer.begin()); +//! +//! // Parse some syntax tree types out of the input tokens. In this case we +//! // expect something like: +//! // +//! // (a, b, c) = (1, 2, 3) +//! let a = parser.parse::<ExprTuple>()?; +//! parser.parse::<token::Eq>()?; +//! let b = parser.parse::<ExprTuple>()?; +//! parser.expect_eof()?; +//! +//! // Perform some validation and report errors. +//! let (a_len, b_len) = (a.elems.len(), b.elems.len()); +//! if a_len != b_len { +//! let diag = b.span().unstable() +//! .error(format!("expected {} element(s), got {}", a_len, b_len)) +//! .span_note(a.span().unstable(), "because of this"); +//! +//! return Err(diag); +//! } +//! +//! // Build the output tokens. +//! let out = quote! { +//! println!("All good! Received two tuples of size {}", #a_len); +//! }; +//! +//! Ok(out.into()) +//! } +//! # +//! # extern crate proc_macro2; +//! # +//! # // This method exists on proc_macro2::Span but is behind the "nightly" +//! # // feature. +//! # trait ToUnstableSpan { +//! # fn unstable(&self) -> Span; +//! # } +//! # +//! # impl ToUnstableSpan for proc_macro2::Span { +//! # fn unstable(&self) -> Span { +//! # unimplemented!() +//! # } +//! # } +//! # +//! # fn main() {} +//! ``` + +// This module is heavily commented as it contains the only unsafe code in Syn, +// and caution should be used when editing it. The public-facing interface is +// 100% safe but the implementation is fragile internally. + +#[cfg(feature = "proc-macro")] +use proc_macro as pm; +use proc_macro2::{Delimiter, Literal, Span, Term, TokenStream}; +use proc_macro2::{Group, TokenTree, Op}; + +use std::ptr; +use std::marker::PhantomData; + +#[cfg(synom_verbose_trace)] +use std::fmt::{self, Debug}; + +/// Internal type which is used instead of `TokenTree` to represent a token tree +/// within a `TokenBuffer`. +enum Entry { + // Mimicking types from proc-macro. + Group(Span, Delimiter, TokenBuffer), + Term(Term), + Op(Op), + Literal(Literal), + // End entries contain a raw pointer to the entry from the containing + // token tree, or null if this is the outermost level. + End(*const Entry), +} + +/// A buffer that can be efficiently traversed multiple times, unlike +/// `TokenStream` which requires a deep copy in order to traverse more than +/// once. +/// +/// See the [module documentation] for an example of `TokenBuffer` in action. +/// +/// [module documentation]: index.html +/// +/// *This type is available if Syn is built with the `"parsing"` feature.* +pub struct TokenBuffer { + // NOTE: Do not derive clone on this - there are raw pointers inside which + // will be messed up. Moving the `TokenBuffer` itself is safe as the actual + // backing slices won't be moved. + data: Box<[Entry]>, +} + +impl TokenBuffer { + // NOTE: DO NOT MUTATE THE `Vec` RETURNED FROM THIS FUNCTION ONCE IT + // RETURNS, THE ADDRESS OF ITS BACKING MEMORY MUST REMAIN STABLE. + fn inner_new(stream: TokenStream, up: *const Entry) -> TokenBuffer { + // Build up the entries list, recording the locations of any Groups + // in the list to be processed later. + let mut entries = Vec::new(); + let mut seqs = Vec::new(); + for tt in stream { + match tt { + TokenTree::Term(sym) => { + entries.push(Entry::Term(sym)); + } + TokenTree::Op(op) => { + entries.push(Entry::Op(op)); + } + TokenTree::Literal(l) => { + entries.push(Entry::Literal(l)); + } + TokenTree::Group(g) => { + // Record the index of the interesting entry, and store an + // `End(null)` there temporarially. + seqs.push((entries.len(), g.span(), g.delimiter(), g.stream().clone())); + entries.push(Entry::End(ptr::null())); + } + } + } + // Add an `End` entry to the end with a reference to the enclosing token + // stream which was passed in. + entries.push(Entry::End(up)); + + // NOTE: This is done to ensure that we don't accidentally modify the + // length of the backing buffer. The backing buffer must remain at a + // constant address after this point, as we are going to store a raw + // pointer into it. + let mut entries = entries.into_boxed_slice(); + for (idx, span, delim, seq_stream) in seqs { + // We know that this index refers to one of the temporary + // `End(null)` entries, and we know that the last entry is + // `End(up)`, so the next index is also valid. + let seq_up = &entries[idx + 1] as *const Entry; + + // The end entry stored at the end of this Entry::Group should + // point to the Entry which follows the Group in the list. + let inner = Self::inner_new(seq_stream, seq_up); + entries[idx] = Entry::Group(span, delim, inner); + } + + TokenBuffer { data: entries } + } + + /// Creates a `TokenBuffer` containing all the tokens from the input + /// `TokenStream`. + #[cfg(feature = "proc-macro")] + pub fn new(stream: pm::TokenStream) -> TokenBuffer { + Self::new2(stream.into()) + } + + /// Creates a `TokenBuffer` containing all the tokens from the input + /// `TokenStream`. + pub fn new2(stream: TokenStream) -> TokenBuffer { + Self::inner_new(stream, ptr::null()) + } + + /// Creates a cursor referencing the first token in the buffer and able to + /// traverse until the end of the buffer. + pub fn begin(&self) -> Cursor { + unsafe { Cursor::create(&self.data[0], &self.data[self.data.len() - 1]) } + } +} + +/// A cheaply copyable cursor into a `TokenBuffer`. +/// +/// This cursor holds a shared reference into the immutable data which is used +/// internally to represent a `TokenStream`, and can be efficiently manipulated +/// and copied around. +/// +/// An empty `Cursor` can be created directly, or one may create a `TokenBuffer` +/// object and get a cursor to its first token with `begin()`. +/// +/// Two cursors are equal if they have the same location in the same input +/// stream, and have the same scope. +/// +/// See the [module documentation] for an example of a `Cursor` in action. +/// +/// [module documentation]: index.html +/// +/// *This type is available if Syn is built with the `"parsing"` feature.* +#[derive(Copy, Clone, Eq, PartialEq)] +pub struct Cursor<'a> { + /// The current entry which the `Cursor` is pointing at. + ptr: *const Entry, + /// This is the only `Entry::End(..)` object which this cursor is allowed to + /// point at. All other `End` objects are skipped over in `Cursor::create`. + scope: *const Entry, + /// This uses the &'a reference which guarantees that these pointers are + /// still valid. + marker: PhantomData<&'a Entry>, +} + +impl<'a> Cursor<'a> { + /// Creates a cursor referencing a static empty TokenStream. + pub fn empty() -> Self { + // It's safe in this situation for us to put an `Entry` object in global + // storage, despite it not actually being safe to send across threads + // (`Term` is a reference into a thread-local table). This is because + // this entry never includes a `Term` object. + // + // This wrapper struct allows us to break the rules and put a `Sync` + // object in global storage. + struct UnsafeSyncEntry(Entry); + unsafe impl Sync for UnsafeSyncEntry {} + static EMPTY_ENTRY: UnsafeSyncEntry = UnsafeSyncEntry(Entry::End(0 as *const Entry)); + + Cursor { + ptr: &EMPTY_ENTRY.0, + scope: &EMPTY_ENTRY.0, + marker: PhantomData, + } + } + + /// This create method intelligently exits non-explicitly-entered + /// `None`-delimited scopes when the cursor reaches the end of them, + /// allowing for them to be treated transparently. + unsafe fn create(mut ptr: *const Entry, scope: *const Entry) -> Self { + // NOTE: If we're looking at a `End(..)`, we want to advance the cursor + // past it, unless `ptr == scope`, which means that we're at the edge of + // our cursor's scope. We should only have `ptr != scope` at the exit + // from None-delimited groups entered with `ignore_none`. + while let Entry::End(exit) = *ptr { + if ptr == scope { + break; + } + ptr = exit; + } + + Cursor { + ptr: ptr, + scope: scope, + marker: PhantomData, + } + } + + /// Get the current entry. + fn entry(self) -> &'a Entry { + unsafe { &*self.ptr } + } + + /// Bump the cursor to point at the next token after the current one. This + /// is undefined behavior if the cursor is currently looking at an + /// `Entry::End`. + unsafe fn bump(self) -> Cursor<'a> { + Cursor::create(self.ptr.offset(1), self.scope) + } + + /// If the cursor is looking at a `None`-delimited group, move it to look at + /// the first token inside instead. If the group is empty, this will move + /// the cursor past the `None`-delimited group. + /// + /// WARNING: This mutates its argument. + fn ignore_none(&mut self) { + if let Entry::Group(_, Delimiter::None, ref buf) = *self.entry() { + // NOTE: We call `Cursor::create` here to make sure that situations + // where we should immediately exit the span after entering it are + // handled correctly. + unsafe { + *self = Cursor::create(&buf.data[0], self.scope); + } + } + } + + /// Checks whether the cursor is currently pointing at the end of its valid + /// scope. + #[inline] + pub fn eof(self) -> bool { + // We're at eof if we're at the end of our scope. + self.ptr == self.scope + } + + /// If the cursor is pointing at a `Group` with the given delimiter, returns + /// a cursor into that group and one pointing to the next `TokenTree`. + pub fn group(mut self, delim: Delimiter) -> Option<(Cursor<'a>, Span, Cursor<'a>)> { + // If we're not trying to enter a none-delimited group, we want to + // ignore them. We have to make sure to _not_ ignore them when we want + // to enter them, of course. For obvious reasons. + if delim != Delimiter::None { + self.ignore_none(); + } + + if let Entry::Group(span, group_delim, ref buf) = *self.entry() { + if group_delim == delim { + return Some((buf.begin(), span, unsafe { self.bump() })); + } + } + + None + } + + /// If the cursor is pointing at a `Term`, returns it along with a cursor + /// pointing at the next `TokenTree`. + pub fn term(mut self) -> Option<(Term, Cursor<'a>)> { + self.ignore_none(); + match *self.entry() { + Entry::Term(term) => Some((term, unsafe { self.bump() })), + _ => None, + } + } + + /// If the cursor is pointing at an `Op`, returns it along with a cursor + /// pointing at the next `TokenTree`. + pub fn op(mut self) -> Option<(Op, Cursor<'a>)> { + self.ignore_none(); + match *self.entry() { + Entry::Op(op) => Some((op, unsafe { self.bump() })), + _ => None, + } + } + + /// If the cursor is pointing at a `Literal`, return it along with a cursor + /// pointing at the next `TokenTree`. + pub fn literal(mut self) -> Option<(Literal, Cursor<'a>)> { + self.ignore_none(); + match *self.entry() { + Entry::Literal(ref lit) => Some((lit.clone(), unsafe { self.bump() })), + _ => None, + } + } + + /// Copies all remaining tokens visible from this cursor into a + /// `TokenStream`. + pub fn token_stream(self) -> TokenStream { + let mut tts = Vec::new(); + let mut cursor = self; + while let Some((tt, rest)) = cursor.token_tree() { + tts.push(tt); + cursor = rest; + } + tts.into_iter().collect() + } + + /// If the cursor is pointing at a `TokenTree`, returns it along with a + /// cursor pointing at the next `TokenTree`. + /// + /// Returns `None` if the cursor has reached the end of its stream. + /// + /// This method does not treat `None`-delimited groups as transparent, and + /// will return a `Group(None, ..)` if the cursor is looking at one. + pub fn token_tree(self) -> Option<(TokenTree, Cursor<'a>)> { + let tree = match *self.entry() { + Entry::Group(span, delim, ref buf) => { + let stream = buf.begin().token_stream(); + let mut g = Group::new(delim, stream); + g.set_span(span); + TokenTree::from(g) + } + Entry::Literal(ref lit) => lit.clone().into(), + Entry::Term(term) => term.into(), + Entry::Op(op) => op.into(), + Entry::End(..) => { + return None; + } + }; + + Some((tree, unsafe { self.bump() })) + } + + /// Returns the `Span` of the current token, or `Span::call_site()` if this + /// cursor points to eof. + pub fn span(self) -> Span { + match *self.entry() { + Entry::Group(span, ..) => span, + Entry::Literal(ref l) => l.span(), + Entry::Term(t) => t.span(), + Entry::Op(o) => o.span(), + Entry::End(..) => Span::call_site(), + } + } +} + +// We do a custom implementation for `Debug` as the default implementation is +// pretty useless. +#[cfg(synom_verbose_trace)] +impl<'a> Debug for Cursor<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // Print what the cursor is currently looking at. + // This will look like Cursor("some remaining tokens here") + f.debug_tuple("Cursor") + .field(&self.token_stream().to_string()) + .finish() + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/data.rs cargo-0.26.0/vendor/syn-0.13.1/src/data.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/data.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/data.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,390 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use super::*; +use punctuated::Punctuated; + +ast_struct! { + /// An enum variant. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct Variant { + /// Attributes tagged on the variant. + pub attrs: Vec<Attribute>, + + /// Name of the variant. + pub ident: Ident, + + /// Content stored in the variant. + pub fields: Fields, + + /// Explicit discriminant: `Variant = 1` + pub discriminant: Option<(Token![=], Expr)>, + } +} + +ast_enum_of_structs! { + /// Data stored within an enum variant or struct. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum Fields { + /// Named fields of a struct or struct variant such as `Point { x: f64, + /// y: f64 }`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Named(FieldsNamed { + pub brace_token: token::Brace, + pub named: Punctuated<Field, Token![,]>, + }), + + /// Unnamed fields of a tuple struct or tuple variant such as `Some(T)`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Unnamed(FieldsUnnamed { + pub paren_token: token::Paren, + pub unnamed: Punctuated<Field, Token![,]>, + }), + + /// Unit struct or unit variant such as `None`. + pub Unit, + } +} + +impl Fields { + /// Get an iterator over the [`Field`] items in this object. This iterator + /// can be used to iterate over a named or unnamed struct or variant's + /// fields uniformly. + /// + /// [`Field`]: struct.Field.html + pub fn iter(&self) -> punctuated::Iter<Field> { + match *self { + Fields::Unit => punctuated::Iter::private_empty(), + Fields::Named(ref f) => f.named.iter(), + Fields::Unnamed(ref f) => f.unnamed.iter(), + } + } +} + +impl<'a> IntoIterator for &'a Fields { + type Item = &'a Field; + type IntoIter = punctuated::Iter<'a, Field>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +ast_struct! { + /// A field of a struct or enum variant. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct Field { + /// Attributes tagged on the field. + pub attrs: Vec<Attribute>, + + /// Visibility of the field. + pub vis: Visibility, + + /// Name of the field, if any. + /// + /// Fields of tuple structs have no names. + pub ident: Option<Ident>, + + pub colon_token: Option<Token![:]>, + + /// Type of the field. + pub ty: Type, + } +} + +ast_enum_of_structs! { + /// The visibility level of an item: inherited or `pub` or + /// `pub(restricted)`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum Visibility { + /// A public visibility level: `pub`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Public(VisPublic { + pub pub_token: Token![pub], + }), + + /// A crate-level visibility: `crate`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Crate(VisCrate { + pub crate_token: Token![crate], + }), + + /// A visibility level restricted to some path: `pub(self)` or + /// `pub(super)` or `pub(crate)` or `pub(in some::module)`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Restricted(VisRestricted { + pub pub_token: Token![pub], + pub paren_token: token::Paren, + pub in_token: Option<Token![in]>, + pub path: Box<Path>, + }), + + /// An inherited visibility, which usually means private. + pub Inherited, + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + + use synom::Synom; + + impl Synom for Variant { + named!(parse -> Self, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + id: syn!(Ident) >> + fields: alt!( + syn!(FieldsNamed) => { Fields::Named } + | + syn!(FieldsUnnamed) => { Fields::Unnamed } + | + epsilon!() => { |_| Fields::Unit } + ) >> + disr: option!(tuple!(punct!(=), syn!(Expr))) >> + (Variant { + ident: id, + attrs: attrs, + fields: fields, + discriminant: disr, + }) + )); + + fn description() -> Option<&'static str> { + Some("enum variant") + } + } + + impl Synom for FieldsNamed { + named!(parse -> Self, map!( + braces!(call!(Punctuated::parse_terminated_with, Field::parse_named)), + |(brace, fields)| FieldsNamed { + brace_token: brace, + named: fields, + } + )); + + fn description() -> Option<&'static str> { + Some("named fields in a struct or struct variant") + } + } + + impl Synom for FieldsUnnamed { + named!(parse -> Self, map!( + parens!(call!(Punctuated::parse_terminated_with, Field::parse_unnamed)), + |(paren, fields)| FieldsUnnamed { + paren_token: paren, + unnamed: fields, + } + )); + + fn description() -> Option<&'static str> { + Some("unnamed fields in a tuple struct or tuple variant") + } + } + + impl Field { + named!(pub parse_named -> Self, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + id: syn!(Ident) >> + colon: punct!(:) >> + ty: syn!(Type) >> + (Field { + ident: Some(id), + vis: vis, + attrs: attrs, + ty: ty, + colon_token: Some(colon), + }) + )); + + named!(pub parse_unnamed -> Self, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + ty: syn!(Type) >> + (Field { + ident: None, + colon_token: None, + vis: vis, + attrs: attrs, + ty: ty, + }) + )); + } + + impl Synom for Visibility { + named!(parse -> Self, alt!( + do_parse!( + pub_token: keyword!(pub) >> + other: parens!(keyword!(crate)) >> + (Visibility::Restricted(VisRestricted { + pub_token: pub_token, + paren_token: other.0, + in_token: None, + path: Box::new(other.1.into()), + })) + ) + | + keyword!(crate) => { |tok| { + Visibility::Crate(VisCrate { + crate_token: tok, + }) + } } + | + do_parse!( + pub_token: keyword!(pub) >> + other: parens!(keyword!(self)) >> + (Visibility::Restricted(VisRestricted { + pub_token: pub_token, + paren_token: other.0, + in_token: None, + path: Box::new(other.1.into()), + })) + ) + | + do_parse!( + pub_token: keyword!(pub) >> + other: parens!(keyword!(super)) >> + (Visibility::Restricted(VisRestricted { + pub_token: pub_token, + paren_token: other.0, + in_token: None, + path: Box::new(other.1.into()), + })) + ) + | + do_parse!( + pub_token: keyword!(pub) >> + other: parens!(do_parse!( + in_tok: keyword!(in) >> + restricted: call!(Path::parse_mod_style) >> + (in_tok, restricted) + )) >> + (Visibility::Restricted(VisRestricted { + pub_token: pub_token, + paren_token: other.0, + in_token: Some((other.1).0), + path: Box::new((other.1).1), + })) + ) + | + keyword!(pub) => { |tok| { + Visibility::Public(VisPublic { + pub_token: tok, + }) + } } + | + epsilon!() => { |_| Visibility::Inherited } + )); + + fn description() -> Option<&'static str> { + Some("visibility qualifier such as `pub`") + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use quote::{ToTokens, Tokens}; + + impl ToTokens for Variant { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(&self.attrs); + self.ident.to_tokens(tokens); + self.fields.to_tokens(tokens); + if let Some((ref eq_token, ref disc)) = self.discriminant { + eq_token.to_tokens(tokens); + disc.to_tokens(tokens); + } + } + } + + impl ToTokens for FieldsNamed { + fn to_tokens(&self, tokens: &mut Tokens) { + self.brace_token.surround(tokens, |tokens| { + self.named.to_tokens(tokens); + }); + } + } + + impl ToTokens for FieldsUnnamed { + fn to_tokens(&self, tokens: &mut Tokens) { + self.paren_token.surround(tokens, |tokens| { + self.unnamed.to_tokens(tokens); + }); + } + } + + impl ToTokens for Field { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(&self.attrs); + self.vis.to_tokens(tokens); + if let Some(ref ident) = self.ident { + ident.to_tokens(tokens); + TokensOrDefault(&self.colon_token).to_tokens(tokens); + } + self.ty.to_tokens(tokens); + } + } + + impl ToTokens for VisPublic { + fn to_tokens(&self, tokens: &mut Tokens) { + self.pub_token.to_tokens(tokens) + } + } + + impl ToTokens for VisCrate { + fn to_tokens(&self, tokens: &mut Tokens) { + self.crate_token.to_tokens(tokens); + } + } + + impl ToTokens for VisRestricted { + fn to_tokens(&self, tokens: &mut Tokens) { + self.pub_token.to_tokens(tokens); + self.paren_token.surround(tokens, |tokens| { + // XXX: If we have a path which is not "self" or "super" or + // "crate", automatically add the "in" token. + self.in_token.to_tokens(tokens); + self.path.to_tokens(tokens); + }); + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/derive.rs cargo-0.26.0/vendor/syn-0.13.1/src/derive.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/derive.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/derive.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,210 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use super::*; +use punctuated::Punctuated; + +ast_struct! { + /// Data structure sent to a `proc_macro_derive` macro. + /// + /// *This type is available if Syn is built with the `"derive"` feature.* + pub struct DeriveInput { + /// Attributes tagged on the whole struct or enum. + pub attrs: Vec<Attribute>, + + /// Visibility of the struct or enum. + pub vis: Visibility, + + /// Name of the struct or enum. + pub ident: Ident, + + /// Generics required to complete the definition. + pub generics: Generics, + + /// Data within the struct or enum. + pub data: Data, + } +} + +ast_enum_of_structs! { + /// The storage of a struct, enum or union data structure. + /// + /// *This type is available if Syn is built with the `"derive"` feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum Data { + /// A struct input to a `proc_macro_derive` macro. + /// + /// *This type is available if Syn is built with the `"derive"` + /// feature.* + pub Struct(DataStruct { + pub struct_token: Token![struct], + pub fields: Fields, + pub semi_token: Option<Token![;]>, + }), + + /// An enum input to a `proc_macro_derive` macro. + /// + /// *This type is available if Syn is built with the `"derive"` + /// feature.* + pub Enum(DataEnum { + pub enum_token: Token![enum], + pub brace_token: token::Brace, + pub variants: Punctuated<Variant, Token![,]>, + }), + + /// A tagged union input to a `proc_macro_derive` macro. + /// + /// *This type is available if Syn is built with the `"derive"` + /// feature.* + pub Union(DataUnion { + pub union_token: Token![union], + pub fields: FieldsNamed, + }), + } + + do_not_generate_to_tokens +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + + use synom::Synom; + + impl Synom for DeriveInput { + named!(parse -> Self, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + which: alt!( + keyword!(struct) => { Ok } + | + keyword!(enum) => { Err } + ) >> + id: syn!(Ident) >> + generics: syn!(Generics) >> + item: switch!(value!(which), + Ok(s) => map!(data_struct, move |(wh, fields, semi)| DeriveInput { + ident: id, + vis: vis, + attrs: attrs, + generics: Generics { + where_clause: wh, + .. generics + }, + data: Data::Struct(DataStruct { + struct_token: s, + fields: fields, + semi_token: semi, + }), + }) + | + Err(e) => map!(data_enum, move |(wh, brace, variants)| DeriveInput { + ident: id, + vis: vis, + attrs: attrs, + generics: Generics { + where_clause: wh, + .. generics + }, + data: Data::Enum(DataEnum { + variants: variants, + brace_token: brace, + enum_token: e, + }), + }) + ) >> + (item) + )); + + fn description() -> Option<&'static str> { + Some("derive input") + } + } + + named!(data_struct -> (Option<WhereClause>, Fields, Option<Token![;]>), alt!( + do_parse!( + wh: option!(syn!(WhereClause)) >> + fields: syn!(FieldsNamed) >> + (wh, Fields::Named(fields), None) + ) + | + do_parse!( + fields: syn!(FieldsUnnamed) >> + wh: option!(syn!(WhereClause)) >> + semi: punct!(;) >> + (wh, Fields::Unnamed(fields), Some(semi)) + ) + | + do_parse!( + wh: option!(syn!(WhereClause)) >> + semi: punct!(;) >> + (wh, Fields::Unit, Some(semi)) + ) + )); + + named!(data_enum -> (Option<WhereClause>, token::Brace, Punctuated<Variant, Token![,]>), do_parse!( + wh: option!(syn!(WhereClause)) >> + data: braces!(Punctuated::parse_terminated) >> + (wh, data.0, data.1) + )); +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use attr::FilterAttrs; + use quote::{ToTokens, Tokens}; + + impl ToTokens for DeriveInput { + fn to_tokens(&self, tokens: &mut Tokens) { + for attr in self.attrs.outer() { + attr.to_tokens(tokens); + } + self.vis.to_tokens(tokens); + match self.data { + Data::Struct(ref d) => d.struct_token.to_tokens(tokens), + Data::Enum(ref d) => d.enum_token.to_tokens(tokens), + Data::Union(ref d) => d.union_token.to_tokens(tokens), + } + self.ident.to_tokens(tokens); + self.generics.to_tokens(tokens); + match self.data { + Data::Struct(ref data) => match data.fields { + Fields::Named(ref fields) => { + self.generics.where_clause.to_tokens(tokens); + fields.to_tokens(tokens); + } + Fields::Unnamed(ref fields) => { + fields.to_tokens(tokens); + self.generics.where_clause.to_tokens(tokens); + TokensOrDefault(&data.semi_token).to_tokens(tokens); + } + Fields::Unit => { + self.generics.where_clause.to_tokens(tokens); + TokensOrDefault(&data.semi_token).to_tokens(tokens); + } + }, + Data::Enum(ref data) => { + self.generics.where_clause.to_tokens(tokens); + data.brace_token.surround(tokens, |tokens| { + data.variants.to_tokens(tokens); + }); + } + Data::Union(ref data) => { + self.generics.where_clause.to_tokens(tokens); + data.fields.to_tokens(tokens); + } + } + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/error.rs cargo-0.26.0/vendor/syn-0.13.1/src/error.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/error.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/error.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,60 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::error::Error; +use buffer::Cursor; +use std::fmt::{self, Display}; + +/// The result of a `Synom` parser. +/// +/// Refer to the [module documentation] for details about parsing in Syn. +/// +/// [module documentation]: index.html +/// +/// *This type is available if Syn is built with the `"parsing"` feature.* +pub type PResult<'a, O> = Result<(O, Cursor<'a>), ParseError>; + +/// An error with a default error message. +/// +/// NOTE: We should provide better error messages in the future. +pub fn parse_error<O>() -> PResult<'static, O> { + Err(ParseError(None)) +} + +/// Error returned when a `Synom` parser cannot parse the input tokens. +/// +/// Refer to the [module documentation] for details about parsing in Syn. +/// +/// [module documentation]: index.html +/// +/// *This type is available if Syn is built with the `"parsing"` feature.* +#[derive(Debug)] +pub struct ParseError(Option<String>); + +impl Error for ParseError { + fn description(&self) -> &str { + match self.0 { + Some(ref desc) => desc, + None => "failed to parse", + } + } +} + +impl Display for ParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(self.description(), f) + } +} + +impl ParseError { + // For syn use only. Not public API. + #[doc(hidden)] + pub fn new<T: Into<String>>(msg: T) -> Self { + ParseError(Some(msg.into())) + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/expr.rs cargo-0.26.0/vendor/syn-0.13.1/src/expr.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/expr.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/expr.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3580 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use super::*; +use punctuated::Punctuated; +use proc_macro2::{Span, TokenStream}; +#[cfg(feature = "extra-traits")] +use std::hash::{Hash, Hasher}; +#[cfg(feature = "extra-traits")] +use tt::TokenStreamHelper; +#[cfg(feature = "full")] +use std::mem; + +ast_enum_of_structs! { + /// A Rust expression. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// # Syntax tree enums + /// + /// This type is a syntax tree enum. In Syn this and other syntax tree enums + /// are designed to be traversed using the following rebinding idiom. + /// + /// ``` + /// # use syn::Expr; + /// # + /// # fn example(expr: Expr) { + /// # const IGNORE: &str = stringify! { + /// let expr: Expr = /* ... */; + /// # }; + /// match expr { + /// Expr::MethodCall(expr) => { + /// /* ... */ + /// } + /// Expr::Cast(expr) => { + /// /* ... */ + /// } + /// Expr::IfLet(expr) => { + /// /* ... */ + /// } + /// /* ... */ + /// # _ => {} + /// } + /// # } + /// ``` + /// + /// We begin with a variable `expr` of type `Expr` that has no fields + /// (because it is an enum), and by matching on it and rebinding a variable + /// with the same name `expr` we effectively imbue our variable with all of + /// the data fields provided by the variant that it turned out to be. So for + /// example above if we ended up in the `MethodCall` case then we get to use + /// `expr.receiver`, `expr.args` etc; if we ended up in the `IfLet` case we + /// get to use `expr.pat`, `expr.then_branch`, `expr.else_branch`. + /// + /// The pattern is similar if the input expression is borrowed: + /// + /// ``` + /// # use syn::Expr; + /// # + /// # fn example(expr: &Expr) { + /// match *expr { + /// Expr::MethodCall(ref expr) => { + /// # } + /// # _ => {} + /// # } + /// # } + /// ``` + /// + /// This approach avoids repeating the variant names twice on every line. + /// + /// ``` + /// # use syn::{Expr, ExprMethodCall}; + /// # + /// # fn example(expr: Expr) { + /// # match expr { + /// Expr::MethodCall(ExprMethodCall { method, args, .. }) => { // repetitive + /// # } + /// # _ => {} + /// # } + /// # } + /// ``` + /// + /// In general, the name to which a syntax tree enum variant is bound should + /// be a suitable name for the complete syntax tree enum type. + /// + /// ``` + /// # use syn::{Expr, ExprField}; + /// # + /// # fn example(discriminant: &ExprField) { + /// // Binding is called `base` which is the name I would use if I were + /// // assigning `*discriminant.base` without an `if let`. + /// if let Expr::Tuple(ref base) = *discriminant.base { + /// # } + /// # } + /// ``` + /// + /// A sign that you may not be choosing the right variable names is if you + /// see names getting repeated in your code, like accessing + /// `receiver.receiver` or `pat.pat` or `cond.cond`. + pub enum Expr { + /// A box expression: `box f`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Box(ExprBox #full { + pub attrs: Vec<Attribute>, + pub box_token: Token![box], + pub expr: Box<Expr>, + }), + + /// A placement expression: `place <- value`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub InPlace(ExprInPlace #full { + pub attrs: Vec<Attribute>, + pub place: Box<Expr>, + pub arrow_token: Token![<-], + pub value: Box<Expr>, + }), + + /// A slice literal expression: `[a, b, c, d]`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Array(ExprArray #full { + pub attrs: Vec<Attribute>, + pub bracket_token: token::Bracket, + pub elems: Punctuated<Expr, Token![,]>, + }), + + /// A function call expression: `invoke(a, b)`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Call(ExprCall { + pub attrs: Vec<Attribute>, + pub func: Box<Expr>, + pub paren_token: token::Paren, + pub args: Punctuated<Expr, Token![,]>, + }), + + /// A method call expression: `x.foo::<T>(a, b)`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub MethodCall(ExprMethodCall #full { + pub attrs: Vec<Attribute>, + pub receiver: Box<Expr>, + pub dot_token: Token![.], + pub method: Ident, + pub turbofish: Option<MethodTurbofish>, + pub paren_token: token::Paren, + pub args: Punctuated<Expr, Token![,]>, + }), + + /// A tuple expression: `(a, b, c, d)`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Tuple(ExprTuple #full { + pub attrs: Vec<Attribute>, + pub paren_token: token::Paren, + pub elems: Punctuated<Expr, Token![,]>, + }), + + /// A binary operation: `a + b`, `a * b`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Binary(ExprBinary { + pub attrs: Vec<Attribute>, + pub left: Box<Expr>, + pub op: BinOp, + pub right: Box<Expr>, + }), + + /// A unary operation: `!x`, `*x`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Unary(ExprUnary { + pub attrs: Vec<Attribute>, + pub op: UnOp, + pub expr: Box<Expr>, + }), + + /// A literal in place of an expression: `1`, `"foo"`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Lit(ExprLit { + pub attrs: Vec<Attribute>, + pub lit: Lit, + }), + + /// A cast expression: `foo as f64`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Cast(ExprCast { + pub attrs: Vec<Attribute>, + pub expr: Box<Expr>, + pub as_token: Token![as], + pub ty: Box<Type>, + }), + + /// A type ascription expression: `foo: f64`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Type(ExprType #full { + pub attrs: Vec<Attribute>, + pub expr: Box<Expr>, + pub colon_token: Token![:], + pub ty: Box<Type>, + }), + + /// An `if` expression with an optional `else` block: `if expr { ... } + /// else { ... }`. + /// + /// The `else` branch expression may only be an `If`, `IfLet`, or + /// `Block` expression, not any of the other types of expression. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub If(ExprIf #full { + pub attrs: Vec<Attribute>, + pub if_token: Token![if], + pub cond: Box<Expr>, + pub then_branch: Block, + pub else_branch: Option<(Token![else], Box<Expr>)>, + }), + + /// An `if let` expression with an optional `else` block: `if let pat = + /// expr { ... } else { ... }`. + /// + /// The `else` branch expression may only be an `If`, `IfLet`, or + /// `Block` expression, not any of the other types of expression. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub IfLet(ExprIfLet #full { + pub attrs: Vec<Attribute>, + pub if_token: Token![if], + pub let_token: Token![let], + pub pats: Punctuated<Pat, Token![|]>, + pub eq_token: Token![=], + pub expr: Box<Expr>, + pub then_branch: Block, + pub else_branch: Option<(Token![else], Box<Expr>)>, + }), + + /// A while loop: `while expr { ... }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub While(ExprWhile #full { + pub attrs: Vec<Attribute>, + pub label: Option<Label>, + pub while_token: Token![while], + pub cond: Box<Expr>, + pub body: Block, + }), + + /// A while-let loop: `while let pat = expr { ... }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub WhileLet(ExprWhileLet #full { + pub attrs: Vec<Attribute>, + pub label: Option<Label>, + pub while_token: Token![while], + pub let_token: Token![let], + pub pats: Punctuated<Pat, Token![|]>, + pub eq_token: Token![=], + pub expr: Box<Expr>, + pub body: Block, + }), + + /// A for loop: `for pat in expr { ... }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub ForLoop(ExprForLoop #full { + pub attrs: Vec<Attribute>, + pub label: Option<Label>, + pub for_token: Token![for], + pub pat: Box<Pat>, + pub in_token: Token![in], + pub expr: Box<Expr>, + pub body: Block, + }), + + /// Conditionless loop: `loop { ... }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Loop(ExprLoop #full { + pub attrs: Vec<Attribute>, + pub label: Option<Label>, + pub loop_token: Token![loop], + pub body: Block, + }), + + /// A `match` expression: `match n { Some(n) => {}, None => {} }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Match(ExprMatch #full { + pub attrs: Vec<Attribute>, + pub match_token: Token![match], + pub expr: Box<Expr>, + pub brace_token: token::Brace, + pub arms: Vec<Arm>, + }), + + /// A closure expression: `|a, b| a + b`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Closure(ExprClosure #full { + pub attrs: Vec<Attribute>, + pub movability: Option<Token![static]>, + pub capture: Option<Token![move]>, + pub or1_token: Token![|], + pub inputs: Punctuated<FnArg, Token![,]>, + pub or2_token: Token![|], + pub output: ReturnType, + pub body: Box<Expr>, + }), + + /// An unsafe block: `unsafe { ... }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Unsafe(ExprUnsafe #full { + pub attrs: Vec<Attribute>, + pub unsafe_token: Token![unsafe], + pub block: Block, + }), + + /// A blocked scope: `{ ... }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Block(ExprBlock #full { + pub attrs: Vec<Attribute>, + pub block: Block, + }), + + /// An assignment expression: `a = compute()`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Assign(ExprAssign #full { + pub attrs: Vec<Attribute>, + pub left: Box<Expr>, + pub eq_token: Token![=], + pub right: Box<Expr>, + }), + + /// A compound assignment expression: `counter += 1`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub AssignOp(ExprAssignOp #full { + pub attrs: Vec<Attribute>, + pub left: Box<Expr>, + pub op: BinOp, + pub right: Box<Expr>, + }), + + /// Access of a named struct field (`obj.k`) or unnamed tuple struct + /// field (`obj.0`). + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Field(ExprField #full { + pub attrs: Vec<Attribute>, + pub base: Box<Expr>, + pub dot_token: Token![.], + pub member: Member, + }), + + /// A square bracketed indexing expression: `vector[2]`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Index(ExprIndex { + pub attrs: Vec<Attribute>, + pub expr: Box<Expr>, + pub bracket_token: token::Bracket, + pub index: Box<Expr>, + }), + + /// A range expression: `1..2`, `1..`, `..2`, `1..=2`, `..=2`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Range(ExprRange #full { + pub attrs: Vec<Attribute>, + pub from: Option<Box<Expr>>, + pub limits: RangeLimits, + pub to: Option<Box<Expr>>, + }), + + /// A path like `std::mem::replace` possibly containing generic + /// parameters and a qualified self-type. + /// + /// A plain identifier like `x` is a path of length 1. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Path(ExprPath { + pub attrs: Vec<Attribute>, + pub qself: Option<QSelf>, + pub path: Path, + }), + + /// A referencing operation: `&a` or `&mut a`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Reference(ExprReference #full { + pub attrs: Vec<Attribute>, + pub and_token: Token![&], + pub mutability: Option<Token![mut]>, + pub expr: Box<Expr>, + }), + + /// A `break`, with an optional label to break and an optional + /// expression. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Break(ExprBreak #full { + pub attrs: Vec<Attribute>, + pub break_token: Token![break], + pub label: Option<Lifetime>, + pub expr: Option<Box<Expr>>, + }), + + /// A `continue`, with an optional label. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Continue(ExprContinue #full { + pub attrs: Vec<Attribute>, + pub continue_token: Token![continue], + pub label: Option<Lifetime>, + }), + + /// A `return`, with an optional value to be returned. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Return(ExprReturn #full { + pub attrs: Vec<Attribute>, + pub return_token: Token![return], + pub expr: Option<Box<Expr>>, + }), + + /// A macro invocation expression: `format!("{}", q)`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Macro(ExprMacro #full { + pub attrs: Vec<Attribute>, + pub mac: Macro, + }), + + /// A struct literal expression: `Point { x: 1, y: 1 }`. + /// + /// The `rest` provides the value of the remaining fields as in `S { a: + /// 1, b: 1, ..rest }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Struct(ExprStruct #full { + pub attrs: Vec<Attribute>, + pub path: Path, + pub brace_token: token::Brace, + pub fields: Punctuated<FieldValue, Token![,]>, + pub dot2_token: Option<Token![..]>, + pub rest: Option<Box<Expr>>, + }), + + /// An array literal constructed from one repeated element: `[0u8; N]`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Repeat(ExprRepeat #full { + pub attrs: Vec<Attribute>, + pub bracket_token: token::Bracket, + pub expr: Box<Expr>, + pub semi_token: Token![;], + pub len: Box<Expr>, + }), + + /// A parenthesized expression: `(a + b)`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Paren(ExprParen { + pub attrs: Vec<Attribute>, + pub paren_token: token::Paren, + pub expr: Box<Expr>, + }), + + /// An expression contained within invisible delimiters. + /// + /// This variant is important for faithfully representing the precedence + /// of expressions and is related to `None`-delimited spans in a + /// `TokenStream`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Group(ExprGroup #full { + pub attrs: Vec<Attribute>, + pub group_token: token::Group, + pub expr: Box<Expr>, + }), + + /// A try-expression: `expr?`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Try(ExprTry #full { + pub attrs: Vec<Attribute>, + pub expr: Box<Expr>, + pub question_token: Token![?], + }), + + /// A catch expression: `do catch { ... }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Catch(ExprCatch #full { + pub attrs: Vec<Attribute>, + pub do_token: Token![do], + pub catch_token: Token![catch], + pub block: Block, + }), + + /// A yield expression: `yield expr`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Yield(ExprYield #full { + pub attrs: Vec<Attribute>, + pub yield_token: Token![yield], + pub expr: Option<Box<Expr>>, + }), + + /// Tokens in expression position not interpreted by Syn. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Verbatim(ExprVerbatim #manual_extra_traits { + pub tts: TokenStream, + }), + } +} + +#[cfg(feature = "extra-traits")] +impl Eq for ExprVerbatim {} + +#[cfg(feature = "extra-traits")] +impl PartialEq for ExprVerbatim { + fn eq(&self, other: &Self) -> bool { + TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) + } +} + +#[cfg(feature = "extra-traits")] +impl Hash for ExprVerbatim { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + TokenStreamHelper(&self.tts).hash(state); + } +} + +impl Expr { + // Not public API. + #[doc(hidden)] + #[cfg(feature = "full")] + pub fn replace_attrs(&mut self, new: Vec<Attribute>) -> Vec<Attribute> { + match *self { + Expr::Box(ExprBox { ref mut attrs, .. }) + | Expr::InPlace(ExprInPlace { ref mut attrs, .. }) + | Expr::Array(ExprArray { ref mut attrs, .. }) + | Expr::Call(ExprCall { ref mut attrs, .. }) + | Expr::MethodCall(ExprMethodCall { ref mut attrs, .. }) + | Expr::Tuple(ExprTuple { ref mut attrs, .. }) + | Expr::Binary(ExprBinary { ref mut attrs, .. }) + | Expr::Unary(ExprUnary { ref mut attrs, .. }) + | Expr::Lit(ExprLit { ref mut attrs, .. }) + | Expr::Cast(ExprCast { ref mut attrs, .. }) + | Expr::Type(ExprType { ref mut attrs, .. }) + | Expr::If(ExprIf { ref mut attrs, .. }) + | Expr::IfLet(ExprIfLet { ref mut attrs, .. }) + | Expr::While(ExprWhile { ref mut attrs, .. }) + | Expr::WhileLet(ExprWhileLet { ref mut attrs, .. }) + | Expr::ForLoop(ExprForLoop { ref mut attrs, .. }) + | Expr::Loop(ExprLoop { ref mut attrs, .. }) + | Expr::Match(ExprMatch { ref mut attrs, .. }) + | Expr::Closure(ExprClosure { ref mut attrs, .. }) + | Expr::Unsafe(ExprUnsafe { ref mut attrs, .. }) + | Expr::Block(ExprBlock { ref mut attrs, .. }) + | Expr::Assign(ExprAssign { ref mut attrs, .. }) + | Expr::AssignOp(ExprAssignOp { ref mut attrs, .. }) + | Expr::Field(ExprField { ref mut attrs, .. }) + | Expr::Index(ExprIndex { ref mut attrs, .. }) + | Expr::Range(ExprRange { ref mut attrs, .. }) + | Expr::Path(ExprPath { ref mut attrs, .. }) + | Expr::Reference(ExprReference { ref mut attrs, .. }) + | Expr::Break(ExprBreak { ref mut attrs, .. }) + | Expr::Continue(ExprContinue { ref mut attrs, .. }) + | Expr::Return(ExprReturn { ref mut attrs, .. }) + | Expr::Macro(ExprMacro { ref mut attrs, .. }) + | Expr::Struct(ExprStruct { ref mut attrs, .. }) + | Expr::Repeat(ExprRepeat { ref mut attrs, .. }) + | Expr::Paren(ExprParen { ref mut attrs, .. }) + | Expr::Group(ExprGroup { ref mut attrs, .. }) + | Expr::Try(ExprTry { ref mut attrs, .. }) + | Expr::Catch(ExprCatch { ref mut attrs, .. }) + | Expr::Yield(ExprYield { ref mut attrs, .. }) => mem::replace(attrs, new), + Expr::Verbatim(_) => { + // TODO + Vec::new() + } + } + } +} + +ast_enum! { + /// A struct or tuple struct field accessed in a struct literal or field + /// expression. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub enum Member { + /// A named field like `self.x`. + Named(Ident), + /// An unnamed field like `self.0`. + Unnamed(Index), + } +} + +ast_struct! { + /// The index of an unnamed tuple struct field. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct Index #manual_extra_traits { + pub index: u32, + pub span: Span, + } +} + +impl From<usize> for Index { + fn from(index: usize) -> Index { + assert!(index < std::u32::MAX as usize); + Index { + index: index as u32, + span: Span::call_site(), + } + } +} + +#[cfg(feature = "extra-traits")] +impl Eq for Index {} + +#[cfg(feature = "extra-traits")] +impl PartialEq for Index { + fn eq(&self, other: &Self) -> bool { + self.index == other.index + } +} + +#[cfg(feature = "extra-traits")] +impl Hash for Index { + fn hash<H: Hasher>(&self, state: &mut H) { + self.index.hash(state); + } +} + +#[cfg(feature = "full")] +ast_struct! { + /// The `::<>` explicit type parameters passed to a method call: + /// `parse::<u64>()`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub struct MethodTurbofish { + pub colon2_token: Token![::], + pub lt_token: Token![<], + pub args: Punctuated<GenericMethodArgument, Token![,]>, + pub gt_token: Token![>], + } +} + +#[cfg(feature = "full")] +ast_enum! { + /// An individual generic argument to a method, like `T`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub enum GenericMethodArgument { + /// A type argument. + Type(Type), + /// A const expression. Must be inside of a block. + /// + /// NOTE: Identity expressions are represented as Type arguments, as + /// they are indistinguishable syntactically. + Const(Expr), + } +} + +#[cfg(feature = "full")] +ast_struct! { + /// A field-value pair in a struct literal. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub struct FieldValue { + /// Attributes tagged on the field. + pub attrs: Vec<Attribute>, + + /// Name or index of the field. + pub member: Member, + + /// The colon in `Struct { x: x }`. If written in shorthand like + /// `Struct { x }`, there is no colon. + pub colon_token: Option<Token![:]>, + + /// Value of the field. + pub expr: Expr, + } +} + +#[cfg(feature = "full")] +ast_struct! { + /// A lifetime labeling a `for`, `while`, or `loop`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub struct Label { + pub name: Lifetime, + pub colon_token: Token![:], + } +} + +#[cfg(feature = "full")] +ast_struct! { + /// A braced block containing Rust statements. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub struct Block { + pub brace_token: token::Brace, + /// Statements in a block + pub stmts: Vec<Stmt>, + } +} + +#[cfg(feature = "full")] +ast_enum! { + /// A statement, usually ending in a semicolon. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub enum Stmt { + /// A local (let) binding. + Local(Local), + + /// An item definition. + Item(Item), + + /// Expr without trailing semicolon. + Expr(Expr), + + /// Expression with trailing semicolon. + Semi(Expr, Token![;]), + } +} + +#[cfg(feature = "full")] +ast_struct! { + /// A local `let` binding: `let x: u64 = s.parse()?`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub struct Local { + pub attrs: Vec<Attribute>, + pub let_token: Token![let], + pub pats: Punctuated<Pat, Token![|]>, + pub ty: Option<(Token![:], Box<Type>)>, + pub init: Option<(Token![=], Box<Expr>)>, + pub semi_token: Token![;], + } +} + +#[cfg(feature = "full")] +ast_enum_of_structs! { + /// A pattern in a local binding, function signature, match expression, or + /// various other places. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + // Clippy false positive + // https://github.com/Manishearth/rust-clippy/issues/1241 + #[cfg_attr(feature = "cargo-clippy", allow(enum_variant_names))] + pub enum Pat { + /// A pattern that matches any value: `_`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Wild(PatWild { + pub underscore_token: Token![_], + }), + + /// A pattern that binds a new variable: `ref mut binding @ SUBPATTERN`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Ident(PatIdent { + pub by_ref: Option<Token![ref]>, + pub mutability: Option<Token![mut]>, + pub ident: Ident, + pub subpat: Option<(Token![@], Box<Pat>)>, + }), + + /// A struct or struct variant pattern: `Variant { x, y, .. }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Struct(PatStruct { + pub path: Path, + pub brace_token: token::Brace, + pub fields: Punctuated<FieldPat, Token![,]>, + pub dot2_token: Option<Token![..]>, + }), + + /// A tuple struct or tuple variant pattern: `Variant(x, y, .., z)`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub TupleStruct(PatTupleStruct { + pub path: Path, + pub pat: PatTuple, + }), + + /// A path pattern like `Color::Red`, optionally qualified with a + /// self-type. + /// + /// Unquailfied path patterns can legally refer to variants, structs, + /// constants or associated constants. Quailfied path patterns like + /// `<A>::B::C` and `<A as Trait>::B::C` can only legally refer to + /// associated constants. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Path(PatPath { + pub qself: Option<QSelf>, + pub path: Path, + }), + + /// A tuple pattern: `(a, b)`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Tuple(PatTuple { + pub paren_token: token::Paren, + pub front: Punctuated<Pat, Token![,]>, + pub dot2_token: Option<Token![..]>, + pub comma_token: Option<Token![,]>, + pub back: Punctuated<Pat, Token![,]>, + }), + + /// A box pattern: `box v`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Box(PatBox { + pub box_token: Token![box], + pub pat: Box<Pat>, + }), + + /// A reference pattern: `&mut (first, second)`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Ref(PatRef { + pub and_token: Token![&], + pub mutability: Option<Token![mut]>, + pub pat: Box<Pat>, + }), + + /// A literal pattern: `0`. + /// + /// This holds an `Expr` rather than a `Lit` because negative numbers + /// are represented as an `Expr::Unary`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Lit(PatLit { + pub expr: Box<Expr>, + }), + + /// A range pattern: `1..=2`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Range(PatRange { + pub lo: Box<Expr>, + pub limits: RangeLimits, + pub hi: Box<Expr>, + }), + + /// A dynamically sized slice pattern: `[a, b, i.., y, z]`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Slice(PatSlice { + pub bracket_token: token::Bracket, + pub front: Punctuated<Pat, Token![,]>, + pub middle: Option<Box<Pat>>, + pub dot2_token: Option<Token![..]>, + pub comma_token: Option<Token![,]>, + pub back: Punctuated<Pat, Token![,]>, + }), + + /// A macro in expression position. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Macro(PatMacro { + pub mac: Macro, + }), + + /// Tokens in pattern position not interpreted by Syn. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Verbatim(PatVerbatim #manual_extra_traits { + pub tts: TokenStream, + }), + } +} + +#[cfg(all(feature = "full", feature = "extra-traits"))] +impl Eq for PatVerbatim {} + +#[cfg(all(feature = "full", feature = "extra-traits"))] +impl PartialEq for PatVerbatim { + fn eq(&self, other: &Self) -> bool { + TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) + } +} + +#[cfg(all(feature = "full", feature = "extra-traits"))] +impl Hash for PatVerbatim { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + TokenStreamHelper(&self.tts).hash(state); + } +} + +#[cfg(feature = "full")] +ast_struct! { + /// One arm of a `match` expression: `0...10 => { return true; }`. + /// + /// As in: + /// + /// ```rust + /// # fn f() -> bool { + /// # let n = 0; + /// match n { + /// 0...10 => { + /// return true; + /// } + /// // ... + /// # _ => {} + /// } + /// # false + /// # } + /// ``` + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub struct Arm { + pub attrs: Vec<Attribute>, + pub leading_vert: Option<Token![|]>, + pub pats: Punctuated<Pat, Token![|]>, + pub guard: Option<(Token![if], Box<Expr>)>, + pub fat_arrow_token: Token![=>], + pub body: Box<Expr>, + pub comma: Option<Token![,]>, + } +} + +#[cfg(feature = "full")] +ast_enum! { + /// Limit types of a range, inclusive or exclusive. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + #[cfg_attr(feature = "clone-impls", derive(Copy))] + pub enum RangeLimits { + /// Inclusive at the beginning, exclusive at the end. + HalfOpen(Token![..]), + /// Inclusive at the beginning and end. + Closed(Token![..=]), + } +} + +#[cfg(feature = "full")] +ast_struct! { + /// A single field in a struct pattern. + /// + /// Patterns like the fields of Foo `{ x, ref y, ref mut z }` are treated + /// the same as `x: x, y: ref y, z: ref mut z` but there is no colon token. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub struct FieldPat { + pub attrs: Vec<Attribute>, + pub member: Member, + pub colon_token: Option<Token![:]>, + pub pat: Box<Pat>, + } +} + +#[cfg(any(feature = "parsing", feature = "printing"))] +#[cfg(feature = "full")] +fn arm_expr_requires_comma(expr: &Expr) -> bool { + // see https://github.com/rust-lang/rust/blob/eb8f2586e + // /src/libsyntax/parse/classify.rs#L17-L37 + match *expr { + Expr::Unsafe(..) + | Expr::Block(..) + | Expr::If(..) + | Expr::IfLet(..) + | Expr::Match(..) + | Expr::While(..) + | Expr::WhileLet(..) + | Expr::Loop(..) + | Expr::ForLoop(..) + | Expr::Catch(..) => false, + _ => true, + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + use path::parsing::qpath; + #[cfg(feature = "full")] + use path::parsing::ty_no_eq_after; + + #[cfg(feature = "full")] + use proc_macro2::TokenStream; + use synom::Synom; + use buffer::Cursor; + #[cfg(feature = "full")] + use parse_error; + use synom::PResult; + + // When we're parsing expressions which occur before blocks, like in an if + // statement's condition, we cannot parse a struct literal. + // + // Struct literals are ambiguous in certain positions + // https://github.com/rust-lang/rfcs/pull/92 + macro_rules! ambiguous_expr { + ($i:expr, $allow_struct:ident) => { + ambiguous_expr($i, $allow_struct, true) + }; + } + + // When we are parsing an optional suffix expression, we cannot allow blocks + // if structs are not allowed. + // + // Example: + // + // if break {} {} + // + // is ambiguous between: + // + // if (break {}) {} + // if (break) {} {} + #[cfg(feature = "full")] + macro_rules! opt_ambiguous_expr { + ($i:expr, $allow_struct:ident) => { + option!($i, call!(ambiguous_expr, $allow_struct, $allow_struct)) + }; + } + + impl Synom for Expr { + named!(parse -> Self, ambiguous_expr!(true)); + + fn description() -> Option<&'static str> { + Some("expression") + } + } + + #[cfg(feature = "full")] + named!(expr_no_struct -> Expr, ambiguous_expr!(false)); + + // Parse an arbitrary expression. + #[cfg(feature = "full")] + fn ambiguous_expr(i: Cursor, allow_struct: bool, allow_block: bool) -> PResult<Expr> { + call!(i, assign_expr, allow_struct, allow_block) + } + + #[cfg(not(feature = "full"))] + fn ambiguous_expr(i: Cursor, allow_struct: bool, allow_block: bool) -> PResult<Expr> { + // NOTE: We intentionally skip assign_expr, placement_expr, and + // range_expr, as they are not parsed in non-full mode. + call!(i, or_expr, allow_struct, allow_block) + } + + // Parse a left-associative binary operator. + macro_rules! binop { + ( + $name: ident, + $next: ident, + $submac: ident!( $($args:tt)* ) + ) => { + named!($name(allow_struct: bool, allow_block: bool) -> Expr, do_parse!( + mut e: call!($next, allow_struct, allow_block) >> + many0!(do_parse!( + op: $submac!($($args)*) >> + rhs: call!($next, allow_struct, true) >> + ({ + e = ExprBinary { + attrs: Vec::new(), + left: Box::new(e.into()), + op: op, + right: Box::new(rhs.into()), + }.into(); + }) + )) >> + (e) + )); + } + } + + // <placement> = <placement> .. + // <placement> += <placement> .. + // <placement> -= <placement> .. + // <placement> *= <placement> .. + // <placement> /= <placement> .. + // <placement> %= <placement> .. + // <placement> ^= <placement> .. + // <placement> &= <placement> .. + // <placement> |= <placement> .. + // <placement> <<= <placement> .. + // <placement> >>= <placement> .. + // + // NOTE: This operator is right-associative. + #[cfg(feature = "full")] + named!(assign_expr(allow_struct: bool, allow_block: bool) -> Expr, do_parse!( + mut e: call!(placement_expr, allow_struct, allow_block) >> + alt!( + do_parse!( + eq: punct!(=) >> + // Recurse into self to parse right-associative operator. + rhs: call!(assign_expr, allow_struct, true) >> + ({ + e = ExprAssign { + attrs: Vec::new(), + left: Box::new(e), + eq_token: eq, + right: Box::new(rhs), + }.into(); + }) + ) + | + do_parse!( + op: call!(BinOp::parse_assign_op) >> + // Recurse into self to parse right-associative operator. + rhs: call!(assign_expr, allow_struct, true) >> + ({ + e = ExprAssignOp { + attrs: Vec::new(), + left: Box::new(e), + op: op, + right: Box::new(rhs), + }.into(); + }) + ) + | + epsilon!() + ) >> + (e) + )); + + // <range> <- <range> .. + // + // NOTE: The `in place { expr }` version of this syntax is parsed in + // `atom_expr`, not here. + // + // NOTE: This operator is right-associative. + #[cfg(feature = "full")] + named!(placement_expr(allow_struct: bool, allow_block: bool) -> Expr, do_parse!( + mut e: call!(range_expr, allow_struct, allow_block) >> + alt!( + do_parse!( + arrow: punct!(<-) >> + // Recurse into self to parse right-associative operator. + rhs: call!(placement_expr, allow_struct, true) >> + ({ + e = ExprInPlace { + attrs: Vec::new(), + // op: BinOp::Place(larrow), + place: Box::new(e), + arrow_token: arrow, + value: Box::new(rhs), + }.into(); + }) + ) + | + epsilon!() + ) >> + (e) + )); + + // <or> ... <or> .. + // <or> .. <or> .. + // <or> .. + // + // NOTE: This is currently parsed oddly - I'm not sure of what the exact + // rules are for parsing these expressions are, but this is not correct. + // For example, `a .. b .. c` is not a legal expression. It should not + // be parsed as either `(a .. b) .. c` or `a .. (b .. c)` apparently. + // + // NOTE: The form of ranges which don't include a preceding expression are + // parsed by `atom_expr`, rather than by this function. + #[cfg(feature = "full")] + named!(range_expr(allow_struct: bool, allow_block: bool) -> Expr, do_parse!( + mut e: call!(or_expr, allow_struct, allow_block) >> + many0!(do_parse!( + limits: syn!(RangeLimits) >> + // We don't want to allow blocks here if we don't allow structs. See + // the reasoning for `opt_ambiguous_expr!` above. + hi: option!(call!(or_expr, allow_struct, allow_struct)) >> + ({ + e = ExprRange { + attrs: Vec::new(), + from: Some(Box::new(e)), + limits: limits, + to: hi.map(|e| Box::new(e)), + }.into(); + }) + )) >> + (e) + )); + + // <and> || <and> ... + binop!(or_expr, and_expr, map!(punct!(||), BinOp::Or)); + + // <compare> && <compare> ... + binop!(and_expr, compare_expr, map!(punct!(&&), BinOp::And)); + + // <bitor> == <bitor> ... + // <bitor> != <bitor> ... + // <bitor> >= <bitor> ... + // <bitor> <= <bitor> ... + // <bitor> > <bitor> ... + // <bitor> < <bitor> ... + // + // NOTE: This operator appears to be parsed as left-associative, but errors + // if it is used in a non-associative manner. + binop!( + compare_expr, + bitor_expr, + alt!( + punct!(==) => { BinOp::Eq } + | + punct!(!=) => { BinOp::Ne } + | + // must be above Lt + punct!(<=) => { BinOp::Le } + | + // must be above Gt + punct!(>=) => { BinOp::Ge } + | + do_parse!( + // Make sure that we don't eat the < part of a <- operator + not!(punct!(<-)) >> + t: punct!(<) >> + (BinOp::Lt(t)) + ) + | + punct!(>) => { BinOp::Gt } + ) + ); + + // <bitxor> | <bitxor> ... + binop!( + bitor_expr, + bitxor_expr, + do_parse!(not!(punct!(||)) >> not!(punct!(|=)) >> t: punct!(|) >> (BinOp::BitOr(t))) + ); + + // <bitand> ^ <bitand> ... + binop!( + bitxor_expr, + bitand_expr, + do_parse!( + // NOTE: Make sure we aren't looking at ^=. + not!(punct!(^=)) >> t: punct!(^) >> (BinOp::BitXor(t)) + ) + ); + + // <shift> & <shift> ... + binop!( + bitand_expr, + shift_expr, + do_parse!( + // NOTE: Make sure we aren't looking at && or &=. + not!(punct!(&&)) >> not!(punct!(&=)) >> t: punct!(&) >> (BinOp::BitAnd(t)) + ) + ); + + // <arith> << <arith> ... + // <arith> >> <arith> ... + binop!( + shift_expr, + arith_expr, + alt!( + punct!(<<) => { BinOp::Shl } + | + punct!(>>) => { BinOp::Shr } + ) + ); + + // <term> + <term> ... + // <term> - <term> ... + binop!( + arith_expr, + term_expr, + alt!( + punct!(+) => { BinOp::Add } + | + punct!(-) => { BinOp::Sub } + ) + ); + + // <cast> * <cast> ... + // <cast> / <cast> ... + // <cast> % <cast> ... + binop!( + term_expr, + cast_expr, + alt!( + punct!(*) => { BinOp::Mul } + | + punct!(/) => { BinOp::Div } + | + punct!(%) => { BinOp::Rem } + ) + ); + + // <unary> as <ty> + // <unary> : <ty> + #[cfg(feature = "full")] + named!(cast_expr(allow_struct: bool, allow_block: bool) -> Expr, do_parse!( + mut e: call!(unary_expr, allow_struct, allow_block) >> + many0!(alt!( + do_parse!( + as_: keyword!(as) >> + // We can't accept `A + B` in cast expressions, as it's + // ambiguous with the + expression. + ty: call!(Type::without_plus) >> + ({ + e = ExprCast { + attrs: Vec::new(), + expr: Box::new(e), + as_token: as_, + ty: Box::new(ty), + }.into(); + }) + ) + | + do_parse!( + colon: punct!(:) >> + // We can't accept `A + B` in cast expressions, as it's + // ambiguous with the + expression. + ty: call!(Type::without_plus) >> + ({ + e = ExprType { + attrs: Vec::new(), + expr: Box::new(e), + colon_token: colon, + ty: Box::new(ty), + }.into(); + }) + ) + )) >> + (e) + )); + + // <unary> as <ty> + #[cfg(not(feature = "full"))] + named!(cast_expr(allow_struct: bool, allow_block: bool) -> Expr, do_parse!( + mut e: call!(unary_expr, allow_struct, allow_block) >> + many0!(do_parse!( + as_: keyword!(as) >> + // We can't accept `A + B` in cast expressions, as it's + // ambiguous with the + expression. + ty: call!(Type::without_plus) >> + ({ + e = ExprCast { + attrs: Vec::new(), + expr: Box::new(e), + as_token: as_, + ty: Box::new(ty), + }.into(); + }) + )) >> + (e) + )); + + // <UnOp> <trailer> + // & <trailer> + // &mut <trailer> + // box <trailer> + #[cfg(feature = "full")] + named!(unary_expr(allow_struct: bool, allow_block: bool) -> Expr, alt!( + do_parse!( + op: syn!(UnOp) >> + expr: call!(unary_expr, allow_struct, true) >> + (ExprUnary { + attrs: Vec::new(), + op: op, + expr: Box::new(expr), + }.into()) + ) + | + do_parse!( + and: punct!(&) >> + mutability: option!(keyword!(mut)) >> + expr: call!(unary_expr, allow_struct, true) >> + (ExprReference { + attrs: Vec::new(), + and_token: and, + mutability: mutability, + expr: Box::new(expr), + }.into()) + ) + | + do_parse!( + box_: keyword!(box) >> + expr: call!(unary_expr, allow_struct, true) >> + (ExprBox { + attrs: Vec::new(), + box_token: box_, + expr: Box::new(expr), + }.into()) + ) + | + call!(trailer_expr, allow_struct, allow_block) + )); + + // XXX: This duplication is ugly + #[cfg(not(feature = "full"))] + named!(unary_expr(allow_struct: bool, allow_block: bool) -> Expr, alt!( + do_parse!( + op: syn!(UnOp) >> + expr: call!(unary_expr, allow_struct, true) >> + (ExprUnary { + attrs: Vec::new(), + op: op, + expr: Box::new(expr), + }.into()) + ) + | + call!(trailer_expr, allow_struct, allow_block) + )); + + // <atom> (..<args>) ... + // <atom> . <ident> (..<args>) ... + // <atom> . <ident> ... + // <atom> . <lit> ... + // <atom> [ <expr> ] ... + // <atom> ? ... + #[cfg(feature = "full")] + named!(trailer_expr(allow_struct: bool, allow_block: bool) -> Expr, do_parse!( + mut e: call!(atom_expr, allow_struct, allow_block) >> + many0!(alt!( + tap!(args: and_call => { + let (paren, args) = args; + e = ExprCall { + attrs: Vec::new(), + func: Box::new(e), + args: args, + paren_token: paren, + }.into(); + }) + | + tap!(more: and_method_call => { + let mut call = more; + call.receiver = Box::new(e); + e = call.into(); + }) + | + tap!(field: and_field => { + let (token, member) = field; + e = ExprField { + attrs: Vec::new(), + base: Box::new(e), + dot_token: token, + member: member, + }.into(); + }) + | + tap!(i: and_index => { + let (bracket, i) = i; + e = ExprIndex { + attrs: Vec::new(), + expr: Box::new(e), + bracket_token: bracket, + index: Box::new(i), + }.into(); + }) + | + tap!(question: punct!(?) => { + e = ExprTry { + attrs: Vec::new(), + expr: Box::new(e), + question_token: question, + }.into(); + }) + )) >> + (e) + )); + + // XXX: Duplication == ugly + #[cfg(not(feature = "full"))] + named!(trailer_expr(allow_struct: bool, allow_block: bool) -> Expr, do_parse!( + mut e: call!(atom_expr, allow_struct, allow_block) >> + many0!(alt!( + tap!(args: and_call => { + e = ExprCall { + attrs: Vec::new(), + func: Box::new(e), + paren_token: args.0, + args: args.1, + }.into(); + }) + | + tap!(i: and_index => { + e = ExprIndex { + attrs: Vec::new(), + expr: Box::new(e), + bracket_token: i.0, + index: Box::new(i.1), + }.into(); + }) + )) >> + (e) + )); + + // Parse all atomic expressions which don't have to worry about precedence + // interactions, as they are fully contained. + #[cfg(feature = "full")] + named!(atom_expr(allow_struct: bool, allow_block: bool) -> Expr, alt!( + syn!(ExprGroup) => { Expr::Group } // must be placed first + | + syn!(ExprLit) => { Expr::Lit } // must be before expr_struct + | + // must be before expr_path + cond_reduce!(allow_struct, syn!(ExprStruct)) => { Expr::Struct } + | + syn!(ExprParen) => { Expr::Paren } // must be before expr_tup + | + syn!(ExprMacro) => { Expr::Macro } // must be before expr_path + | + call!(expr_break, allow_struct) // must be before expr_path + | + syn!(ExprContinue) => { Expr::Continue } // must be before expr_path + | + call!(expr_ret, allow_struct) // must be before expr_path + | + syn!(ExprArray) => { Expr::Array } + | + syn!(ExprTuple) => { Expr::Tuple } + | + syn!(ExprIf) => { Expr::If } + | + syn!(ExprIfLet) => { Expr::IfLet } + | + syn!(ExprWhile) => { Expr::While } + | + syn!(ExprWhileLet) => { Expr::WhileLet } + | + syn!(ExprForLoop) => { Expr::ForLoop } + | + syn!(ExprLoop) => { Expr::Loop } + | + syn!(ExprMatch) => { Expr::Match } + | + syn!(ExprCatch) => { Expr::Catch } + | + syn!(ExprYield) => { Expr::Yield } + | + syn!(ExprUnsafe) => { Expr::Unsafe } + | + call!(expr_closure, allow_struct) + | + cond_reduce!(allow_block, syn!(ExprBlock)) => { Expr::Block } + | + // NOTE: This is the prefix-form of range + call!(expr_range, allow_struct) + | + syn!(ExprPath) => { Expr::Path } + | + syn!(ExprRepeat) => { Expr::Repeat } + )); + + #[cfg(not(feature = "full"))] + named!(atom_expr(_allow_struct: bool, _allow_block: bool) -> Expr, alt!( + syn!(ExprLit) => { Expr::Lit } + | + syn!(ExprParen) => { Expr::Paren } + | + syn!(ExprPath) => { Expr::Path } + )); + + #[cfg(feature = "full")] + named!(expr_nosemi -> Expr, map!(alt!( + syn!(ExprIf) => { Expr::If } + | + syn!(ExprIfLet) => { Expr::IfLet } + | + syn!(ExprWhile) => { Expr::While } + | + syn!(ExprWhileLet) => { Expr::WhileLet } + | + syn!(ExprForLoop) => { Expr::ForLoop } + | + syn!(ExprLoop) => { Expr::Loop } + | + syn!(ExprMatch) => { Expr::Match } + | + syn!(ExprCatch) => { Expr::Catch } + | + syn!(ExprYield) => { Expr::Yield } + | + syn!(ExprUnsafe) => { Expr::Unsafe } + | + syn!(ExprBlock) => { Expr::Block } + ), Expr::from)); + + impl Synom for ExprLit { + named!(parse -> Self, do_parse!( + lit: syn!(Lit) >> + (ExprLit { + attrs: Vec::new(), + lit: lit, + }) + )); + + fn description() -> Option<&'static str> { + Some("literal") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprMacro { + named!(parse -> Self, do_parse!( + mac: syn!(Macro) >> + (ExprMacro { + attrs: Vec::new(), + mac: mac, + }) + )); + + fn description() -> Option<&'static str> { + Some("macro invocation expression") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprGroup { + named!(parse -> Self, do_parse!( + e: grouped!(syn!(Expr)) >> + (ExprGroup { + attrs: Vec::new(), + expr: Box::new(e.1), + group_token: e.0, + }) + )); + + fn description() -> Option<&'static str> { + Some("expression surrounded by invisible delimiters") + } + } + + impl Synom for ExprParen { + named!(parse -> Self, do_parse!( + e: parens!(syn!(Expr)) >> + (ExprParen { + attrs: Vec::new(), + paren_token: e.0, + expr: Box::new(e.1), + }) + )); + + fn description() -> Option<&'static str> { + Some("parenthesized expression") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprArray { + named!(parse -> Self, do_parse!( + elems: brackets!(Punctuated::parse_terminated) >> + (ExprArray { + attrs: Vec::new(), + bracket_token: elems.0, + elems: elems.1, + }) + )); + + fn description() -> Option<&'static str> { + Some("array expression") + } + } + + named!(and_call -> (token::Paren, Punctuated<Expr, Token![,]>), + parens!(Punctuated::parse_terminated)); + + #[cfg(feature = "full")] + named!(and_method_call -> ExprMethodCall, do_parse!( + dot: punct!(.) >> + method: syn!(Ident) >> + turbofish: option!(tuple!( + punct!(::), + punct!(<), + call!(Punctuated::parse_terminated), + punct!(>) + )) >> + args: parens!(Punctuated::parse_terminated) >> + ({ + ExprMethodCall { + attrs: Vec::new(), + // this expr will get overwritten after being returned + receiver: Box::new(Expr::Verbatim(ExprVerbatim { + tts: TokenStream::empty(), + })), + + method: method, + turbofish: turbofish.map(|fish| MethodTurbofish { + colon2_token: fish.0, + lt_token: fish.1, + args: fish.2, + gt_token: fish.3, + }), + args: args.1, + paren_token: args.0, + dot_token: dot, + } + }) + )); + + #[cfg(feature = "full")] + impl Synom for GenericMethodArgument { + // TODO parse const generics as well + named!(parse -> Self, map!(ty_no_eq_after, GenericMethodArgument::Type)); + + fn description() -> Option<&'static str> { + Some("generic method argument") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprTuple { + named!(parse -> Self, do_parse!( + elems: parens!(Punctuated::parse_terminated) >> + (ExprTuple { + attrs: Vec::new(), + elems: elems.1, + paren_token: elems.0, + }) + )); + + fn description() -> Option<&'static str> { + Some("tuple") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprIfLet { + named!(parse -> Self, do_parse!( + if_: keyword!(if) >> + let_: keyword!(let) >> + pats: call!(Punctuated::parse_separated_nonempty) >> + eq: punct!(=) >> + cond: expr_no_struct >> + then_block: braces!(Block::parse_within) >> + else_block: option!(else_block) >> + (ExprIfLet { + attrs: Vec::new(), + pats: pats, + let_token: let_, + eq_token: eq, + expr: Box::new(cond), + then_branch: Block { + brace_token: then_block.0, + stmts: then_block.1, + }, + if_token: if_, + else_branch: else_block, + }) + )); + + fn description() -> Option<&'static str> { + Some("`if let` expression") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprIf { + named!(parse -> Self, do_parse!( + if_: keyword!(if) >> + cond: expr_no_struct >> + then_block: braces!(Block::parse_within) >> + else_block: option!(else_block) >> + (ExprIf { + attrs: Vec::new(), + cond: Box::new(cond), + then_branch: Block { + brace_token: then_block.0, + stmts: then_block.1, + }, + if_token: if_, + else_branch: else_block, + }) + )); + + fn description() -> Option<&'static str> { + Some("`if` expression") + } + } + + #[cfg(feature = "full")] + named!(else_block -> (Token![else], Box<Expr>), do_parse!( + else_: keyword!(else) >> + expr: alt!( + syn!(ExprIf) => { Expr::If } + | + syn!(ExprIfLet) => { Expr::IfLet } + | + do_parse!( + else_block: braces!(Block::parse_within) >> + (Expr::Block(ExprBlock { + attrs: Vec::new(), + block: Block { + brace_token: else_block.0, + stmts: else_block.1, + }, + })) + ) + ) >> + (else_, Box::new(expr)) + )); + + #[cfg(feature = "full")] + impl Synom for ExprForLoop { + named!(parse -> Self, do_parse!( + label: option!(syn!(Label)) >> + for_: keyword!(for) >> + pat: syn!(Pat) >> + in_: keyword!(in) >> + expr: expr_no_struct >> + loop_block: syn!(Block) >> + (ExprForLoop { + attrs: Vec::new(), + for_token: for_, + in_token: in_, + pat: Box::new(pat), + expr: Box::new(expr), + body: loop_block, + label: label, + }) + )); + + fn description() -> Option<&'static str> { + Some("`for` loop") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprLoop { + named!(parse -> Self, do_parse!( + label: option!(syn!(Label)) >> + loop_: keyword!(loop) >> + loop_block: syn!(Block) >> + (ExprLoop { + attrs: Vec::new(), + loop_token: loop_, + body: loop_block, + label: label, + }) + )); + + fn description() -> Option<&'static str> { + Some("`loop`") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprMatch { + named!(parse -> Self, do_parse!( + match_: keyword!(match) >> + obj: expr_no_struct >> + res: braces!(many0!(Arm::parse)) >> + (ExprMatch { + attrs: Vec::new(), + expr: Box::new(obj), + match_token: match_, + brace_token: res.0, + arms: res.1, + }) + )); + + fn description() -> Option<&'static str> { + Some("`match` expression") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprCatch { + named!(parse -> Self, do_parse!( + do_: keyword!(do) >> + catch_: keyword!(catch) >> + catch_block: syn!(Block) >> + (ExprCatch { + attrs: Vec::new(), + block: catch_block, + do_token: do_, + catch_token: catch_, + }) + )); + + fn description() -> Option<&'static str> { + Some("`catch` expression") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprYield { + named!(parse -> Self, do_parse!( + yield_: keyword!(yield) >> + expr: option!(syn!(Expr)) >> + (ExprYield { + attrs: Vec::new(), + yield_token: yield_, + expr: expr.map(Box::new), + }) + )); + + fn description() -> Option<&'static str> { + Some("`yield` expression") + } + } + + #[cfg(feature = "full")] + impl Synom for Arm { + named!(parse -> Self, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + leading_vert: option!(punct!(|)) >> + pats: call!(Punctuated::parse_separated_nonempty) >> + guard: option!(tuple!(keyword!(if), syn!(Expr))) >> + fat_arrow: punct!(=>) >> + body: do_parse!( + expr: alt!(expr_nosemi | syn!(Expr)) >> + comma: switch!(value!(arm_expr_requires_comma(&expr)), + true => alt!( + input_end!() => { |_| None } + | + punct!(,) => { Some } + ) + | + false => option!(punct!(,)) + ) >> + (expr, comma) + ) >> + (Arm { + fat_arrow_token: fat_arrow, + attrs: attrs, + leading_vert: leading_vert, + pats: pats, + guard: guard.map(|(if_, guard)| (if_, Box::new(guard))), + body: Box::new(body.0), + comma: body.1, + }) + )); + + fn description() -> Option<&'static str> { + Some("`match` arm") + } + } + + #[cfg(feature = "full")] + named!(expr_closure(allow_struct: bool) -> Expr, do_parse!( + movability: option!(keyword!(static)) >> + capture: option!(keyword!(move)) >> + or1: punct!(|) >> + inputs: call!(Punctuated::parse_terminated_with, fn_arg) >> + or2: punct!(|) >> + ret_and_body: alt!( + do_parse!( + arrow: punct!(->) >> + ty: syn!(Type) >> + body: syn!(Block) >> + (ReturnType::Type(arrow, Box::new(ty)), + Expr::Block(ExprBlock { + attrs: Vec::new(), + block: body, + })) + ) + | + map!(ambiguous_expr!(allow_struct), |e| (ReturnType::Default, e)) + ) >> + (ExprClosure { + attrs: Vec::new(), + movability: movability, + capture: capture, + or1_token: or1, + inputs: inputs, + or2_token: or2, + output: ret_and_body.0, + body: Box::new(ret_and_body.1), + }.into()) + )); + + #[cfg(feature = "full")] + named!(fn_arg -> FnArg, do_parse!( + pat: syn!(Pat) >> + ty: option!(tuple!(punct!(:), syn!(Type))) >> + ({ + if let Some((colon, ty)) = ty { + FnArg::Captured(ArgCaptured { + pat: pat, + colon_token: colon, + ty: ty, + }) + } else { + FnArg::Inferred(pat) + } + }) + )); + + #[cfg(feature = "full")] + impl Synom for ExprWhile { + named!(parse -> Self, do_parse!( + label: option!(syn!(Label)) >> + while_: keyword!(while) >> + cond: expr_no_struct >> + while_block: syn!(Block) >> + (ExprWhile { + attrs: Vec::new(), + while_token: while_, + cond: Box::new(cond), + body: while_block, + label: label, + }) + )); + + fn description() -> Option<&'static str> { + Some("`while` expression") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprWhileLet { + named!(parse -> Self, do_parse!( + label: option!(syn!(Label)) >> + while_: keyword!(while) >> + let_: keyword!(let) >> + pats: call!(Punctuated::parse_separated_nonempty) >> + eq: punct!(=) >> + value: expr_no_struct >> + while_block: syn!(Block) >> + (ExprWhileLet { + attrs: Vec::new(), + eq_token: eq, + let_token: let_, + while_token: while_, + pats: pats, + expr: Box::new(value), + body: while_block, + label: label, + }) + )); + + fn description() -> Option<&'static str> { + Some("`while let` expression") + } + } + + #[cfg(feature = "full")] + impl Synom for Label { + named!(parse -> Self, do_parse!( + name: syn!(Lifetime) >> + colon: punct!(:) >> + (Label { + name: name, + colon_token: colon, + }) + )); + + fn description() -> Option<&'static str> { + Some("`while let` expression") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprContinue { + named!(parse -> Self, do_parse!( + cont: keyword!(continue) >> + label: option!(syn!(Lifetime)) >> + (ExprContinue { + attrs: Vec::new(), + continue_token: cont, + label: label, + }) + )); + + fn description() -> Option<&'static str> { + Some("`continue`") + } + } + + #[cfg(feature = "full")] + named!(expr_break(allow_struct: bool) -> Expr, do_parse!( + break_: keyword!(break) >> + label: option!(syn!(Lifetime)) >> + // We can't allow blocks after a `break` expression when we wouldn't + // allow structs, as this expression is ambiguous. + val: opt_ambiguous_expr!(allow_struct) >> + (ExprBreak { + attrs: Vec::new(), + label: label, + expr: val.map(Box::new), + break_token: break_, + }.into()) + )); + + #[cfg(feature = "full")] + named!(expr_ret(allow_struct: bool) -> Expr, do_parse!( + return_: keyword!(return) >> + // NOTE: return is greedy and eats blocks after it even when in a + // position where structs are not allowed, such as in if statement + // conditions. For example: + // + // if return { println!("A") } {} // Prints "A" + ret_value: option!(ambiguous_expr!(allow_struct)) >> + (ExprReturn { + attrs: Vec::new(), + expr: ret_value.map(Box::new), + return_token: return_, + }.into()) + )); + + #[cfg(feature = "full")] + impl Synom for ExprStruct { + named!(parse -> Self, do_parse!( + path: syn!(Path) >> + data: braces!(do_parse!( + fields: call!(Punctuated::parse_terminated) >> + base: option!(cond!(fields.empty_or_trailing(), do_parse!( + dots: punct!(..) >> + base: syn!(Expr) >> + (dots, base) + ))) >> + (fields, base) + )) >> + ({ + let (brace, (fields, base)) = data; + let (dots, rest) = match base.and_then(|b| b) { + Some((dots, base)) => (Some(dots), Some(base)), + None => (None, None), + }; + ExprStruct { + attrs: Vec::new(), + brace_token: brace, + path: path, + fields: fields, + dot2_token: dots, + rest: rest.map(Box::new), + } + }) + )); + + fn description() -> Option<&'static str> { + Some("struct literal expression") + } + } + + #[cfg(feature = "full")] + impl Synom for FieldValue { + named!(parse -> Self, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + field_value: alt!( + tuple!(syn!(Member), map!(punct!(:), Some), syn!(Expr)) + | + map!(syn!(Ident), |name| ( + Member::Named(name), + None, + Expr::Path(ExprPath { + attrs: Vec::new(), + qself: None, + path: name.into(), + }), + )) + ) >> + (FieldValue { + attrs: attrs, + member: field_value.0, + colon_token: field_value.1, + expr: field_value.2, + }) + )); + + fn description() -> Option<&'static str> { + Some("field-value pair: `field: value`") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprRepeat { + named!(parse -> Self, do_parse!( + data: brackets!(do_parse!( + value: syn!(Expr) >> + semi: punct!(;) >> + times: syn!(Expr) >> + (value, semi, times) + )) >> + (ExprRepeat { + attrs: Vec::new(), + expr: Box::new((data.1).0), + len: Box::new((data.1).2), + bracket_token: data.0, + semi_token: (data.1).1, + }) + )); + + fn description() -> Option<&'static str> { + Some("repeated array literal: `[val; N]`") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprUnsafe { + named!(parse -> Self, do_parse!( + unsafe_: keyword!(unsafe) >> + b: syn!(Block) >> + (ExprUnsafe { + attrs: Vec::new(), + unsafe_token: unsafe_, + block: b, + }) + )); + + fn description() -> Option<&'static str> { + Some("unsafe block: `unsafe { .. }`") + } + } + + #[cfg(feature = "full")] + impl Synom for ExprBlock { + named!(parse -> Self, do_parse!( + b: syn!(Block) >> + (ExprBlock { + attrs: Vec::new(), + block: b, + }) + )); + + fn description() -> Option<&'static str> { + Some("block: `{ .. }`") + } + } + + #[cfg(feature = "full")] + named!(expr_range(allow_struct: bool) -> Expr, do_parse!( + limits: syn!(RangeLimits) >> + hi: opt_ambiguous_expr!(allow_struct) >> + (ExprRange { + attrs: Vec::new(), + from: None, + to: hi.map(Box::new), + limits: limits, + }.into()) + )); + + #[cfg(feature = "full")] + impl Synom for RangeLimits { + named!(parse -> Self, alt!( + // Must come before Dot2 + punct!(..=) => { RangeLimits::Closed } + | + // Must come before Dot2 + punct!(...) => { |dot3| RangeLimits::Closed(Token![..=](dot3.0)) } + | + punct!(..) => { RangeLimits::HalfOpen } + )); + + fn description() -> Option<&'static str> { + Some("range limit: `..`, `...` or `..=`") + } + } + + impl Synom for ExprPath { + named!(parse -> Self, do_parse!( + pair: qpath >> + (ExprPath { + attrs: Vec::new(), + qself: pair.0, + path: pair.1, + }) + )); + + fn description() -> Option<&'static str> { + Some("path: `a::b::c`") + } + } + + #[cfg(feature = "full")] + named!(and_field -> (Token![.], Member), tuple!(punct!(.), syn!(Member))); + + named!(and_index -> (token::Bracket, Expr), brackets!(syn!(Expr))); + + #[cfg(feature = "full")] + impl Synom for Block { + named!(parse -> Self, do_parse!( + stmts: braces!(Block::parse_within) >> + (Block { + brace_token: stmts.0, + stmts: stmts.1, + }) + )); + + fn description() -> Option<&'static str> { + Some("block: `{ .. }`") + } + } + + #[cfg(feature = "full")] + impl Block { + named!(pub parse_within -> Vec<Stmt>, do_parse!( + many0!(punct!(;)) >> + mut standalone: many0!(do_parse!( + stmt: syn!(Stmt) >> + many0!(punct!(;)) >> + (stmt) + )) >> + last: option!(do_parse!( + attrs: many0!(Attribute::parse_outer) >> + mut e: syn!(Expr) >> + ({ + e.replace_attrs(attrs); + Stmt::Expr(e) + }) + )) >> + (match last { + None => standalone, + Some(last) => { + standalone.push(last); + standalone + } + }) + )); + } + + #[cfg(feature = "full")] + impl Synom for Stmt { + named!(parse -> Self, alt!( + stmt_mac + | + stmt_local + | + stmt_item + | + stmt_blockexpr + | + stmt_expr + )); + + fn description() -> Option<&'static str> { + Some("statement") + } + } + + #[cfg(feature = "full")] + named!(stmt_mac -> Stmt, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + what: call!(Path::parse_mod_style) >> + bang: punct!(!) >> + // Only parse braces here; paren and bracket will get parsed as + // expression statements + data: braces!(syn!(TokenStream)) >> + semi: option!(punct!(;)) >> + (Stmt::Item(Item::Macro(ItemMacro { + attrs: attrs, + ident: None, + mac: Macro { + path: what, + bang_token: bang, + delimiter: MacroDelimiter::Brace(data.0), + tts: data.1, + }, + semi_token: semi, + }))) + )); + + #[cfg(feature = "full")] + named!(stmt_local -> Stmt, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + let_: keyword!(let) >> + pats: call!(Punctuated::parse_separated_nonempty) >> + ty: option!(tuple!(punct!(:), syn!(Type))) >> + init: option!(tuple!(punct!(=), syn!(Expr))) >> + semi: punct!(;) >> + (Stmt::Local(Local { + attrs: attrs, + let_token: let_, + pats: pats, + ty: ty.map(|(colon, ty)| (colon, Box::new(ty))), + init: init.map(|(eq, expr)| (eq, Box::new(expr))), + semi_token: semi, + })) + )); + + #[cfg(feature = "full")] + named!(stmt_item -> Stmt, map!(syn!(Item), |i| Stmt::Item(i))); + + #[cfg(feature = "full")] + named!(stmt_blockexpr -> Stmt, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + mut e: expr_nosemi >> + // If the next token is a `.` or a `?` it is special-cased to parse as + // an expression instead of a blockexpression. + not!(punct!(.)) >> + not!(punct!(?)) >> + semi: option!(punct!(;)) >> + ({ + e.replace_attrs(attrs); + if let Some(semi) = semi { + Stmt::Semi(e, semi) + } else { + Stmt::Expr(e) + } + }) + )); + + #[cfg(feature = "full")] + named!(stmt_expr -> Stmt, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + mut e: syn!(Expr) >> + semi: punct!(;) >> + ({ + e.replace_attrs(attrs); + Stmt::Semi(e, semi) + }) + )); + + #[cfg(feature = "full")] + impl Synom for Pat { + named!(parse -> Self, alt!( + syn!(PatWild) => { Pat::Wild } // must be before pat_ident + | + syn!(PatBox) => { Pat::Box } // must be before pat_ident + | + syn!(PatRange) => { Pat::Range } // must be before pat_lit + | + syn!(PatTupleStruct) => { Pat::TupleStruct } // must be before pat_ident + | + syn!(PatStruct) => { Pat::Struct } // must be before pat_ident + | + syn!(PatMacro) => { Pat::Macro } // must be before pat_ident + | + syn!(PatLit) => { Pat::Lit } // must be before pat_ident + | + syn!(PatIdent) => { Pat::Ident } // must be before pat_path + | + syn!(PatPath) => { Pat::Path } + | + syn!(PatTuple) => { Pat::Tuple } + | + syn!(PatRef) => { Pat::Ref } + | + syn!(PatSlice) => { Pat::Slice } + )); + + fn description() -> Option<&'static str> { + Some("pattern") + } + } + + #[cfg(feature = "full")] + impl Synom for PatWild { + named!(parse -> Self, map!( + punct!(_), + |u| PatWild { underscore_token: u } + )); + + fn description() -> Option<&'static str> { + Some("wild pattern: `_`") + } + } + + #[cfg(feature = "full")] + impl Synom for PatBox { + named!(parse -> Self, do_parse!( + boxed: keyword!(box) >> + pat: syn!(Pat) >> + (PatBox { + pat: Box::new(pat), + box_token: boxed, + }) + )); + + fn description() -> Option<&'static str> { + Some("box pattern") + } + } + + #[cfg(feature = "full")] + impl Synom for PatIdent { + named!(parse -> Self, do_parse!( + by_ref: option!(keyword!(ref)) >> + mutability: option!(keyword!(mut)) >> + name: alt!( + syn!(Ident) + | + keyword!(self) => { Into::into } + ) >> + not!(punct!(<)) >> + not!(punct!(::)) >> + subpat: option!(tuple!(punct!(@), syn!(Pat))) >> + (PatIdent { + by_ref: by_ref, + mutability: mutability, + ident: name, + subpat: subpat.map(|(at, pat)| (at, Box::new(pat))), + }) + )); + + fn description() -> Option<&'static str> { + Some("pattern identifier binding") + } + } + + #[cfg(feature = "full")] + impl Synom for PatTupleStruct { + named!(parse -> Self, do_parse!( + path: syn!(Path) >> + tuple: syn!(PatTuple) >> + (PatTupleStruct { + path: path, + pat: tuple, + }) + )); + + fn description() -> Option<&'static str> { + Some("tuple struct pattern") + } + } + + #[cfg(feature = "full")] + impl Synom for PatStruct { + named!(parse -> Self, do_parse!( + path: syn!(Path) >> + data: braces!(do_parse!( + fields: call!(Punctuated::parse_terminated) >> + base: option!(cond!(fields.empty_or_trailing(), punct!(..))) >> + (fields, base) + )) >> + (PatStruct { + path: path, + fields: (data.1).0, + brace_token: data.0, + dot2_token: (data.1).1.and_then(|m| m), + }) + )); + + fn description() -> Option<&'static str> { + Some("struct pattern") + } + } + + #[cfg(feature = "full")] + impl Synom for FieldPat { + named!(parse -> Self, alt!( + do_parse!( + member: syn!(Member) >> + colon: punct!(:) >> + pat: syn!(Pat) >> + (FieldPat { + member: member, + pat: Box::new(pat), + attrs: Vec::new(), + colon_token: Some(colon), + }) + ) + | + do_parse!( + boxed: option!(keyword!(box)) >> + by_ref: option!(keyword!(ref)) >> + mutability: option!(keyword!(mut)) >> + ident: syn!(Ident) >> + ({ + let mut pat: Pat = PatIdent { + by_ref: by_ref, + mutability: mutability, + ident: ident, + subpat: None, + }.into(); + if let Some(boxed) = boxed { + pat = PatBox { + pat: Box::new(pat), + box_token: boxed, + }.into(); + } + FieldPat { + member: Member::Named(ident), + pat: Box::new(pat), + attrs: Vec::new(), + colon_token: None, + } + }) + ) + )); + + fn description() -> Option<&'static str> { + Some("field pattern") + } + } + + #[cfg(feature = "full")] + impl Synom for Member { + named!(parse -> Self, alt!( + syn!(Ident) => { Member::Named } + | + syn!(Index) => { Member::Unnamed } + )); + + fn description() -> Option<&'static str> { + Some("field member") + } + } + + #[cfg(feature = "full")] + impl Synom for Index { + named!(parse -> Self, do_parse!( + lit: syn!(LitInt) >> + ({ + if let IntSuffix::None = lit.suffix() { + Index { index: lit.value() as u32, span: lit.span() } + } else { + return parse_error(); + } + }) + )); + + fn description() -> Option<&'static str> { + Some("field index") + } + } + + #[cfg(feature = "full")] + impl Synom for PatPath { + named!(parse -> Self, map!( + syn!(ExprPath), + |p| PatPath { qself: p.qself, path: p.path } + )); + + fn description() -> Option<&'static str> { + Some("path pattern") + } + } + + #[cfg(feature = "full")] + impl Synom for PatTuple { + named!(parse -> Self, do_parse!( + data: parens!(do_parse!( + front: call!(Punctuated::parse_terminated) >> + dotdot: option!(cond_reduce!(front.empty_or_trailing(), + tuple!(punct!(..), option!(punct!(,))) + )) >> + back: cond!(match dotdot { + Some((_, Some(_))) => true, + _ => false, + }, + Punctuated::parse_terminated) >> + (front, dotdot, back) + )) >> + ({ + let (parens, (front, dotdot, back)) = data; + let (dotdot, trailing) = match dotdot { + Some((a, b)) => (Some(a), Some(b)), + None => (None, None), + }; + PatTuple { + paren_token: parens, + front: front, + dot2_token: dotdot, + comma_token: trailing.unwrap_or_default(), + back: back.unwrap_or_default(), + } + }) + )); + + fn description() -> Option<&'static str> { + Some("tuple pattern") + } + } + + #[cfg(feature = "full")] + impl Synom for PatRef { + named!(parse -> Self, do_parse!( + and: punct!(&) >> + mutability: option!(keyword!(mut)) >> + pat: syn!(Pat) >> + (PatRef { + pat: Box::new(pat), + mutability: mutability, + and_token: and, + }) + )); + + fn description() -> Option<&'static str> { + Some("reference pattern") + } + } + + #[cfg(feature = "full")] + impl Synom for PatLit { + named!(parse -> Self, do_parse!( + lit: pat_lit_expr >> + (if let Expr::Path(_) = lit { + return parse_error(); // these need to be parsed by pat_path + } else { + PatLit { + expr: Box::new(lit), + } + }) + )); + + fn description() -> Option<&'static str> { + Some("literal pattern") + } + } + + #[cfg(feature = "full")] + impl Synom for PatRange { + named!(parse -> Self, do_parse!( + lo: pat_lit_expr >> + limits: syn!(RangeLimits) >> + hi: pat_lit_expr >> + (PatRange { + lo: Box::new(lo), + hi: Box::new(hi), + limits: limits, + }) + )); + + fn description() -> Option<&'static str> { + Some("range pattern") + } + } + + #[cfg(feature = "full")] + named!(pat_lit_expr -> Expr, do_parse!( + neg: option!(punct!(-)) >> + v: alt!( + syn!(ExprLit) => { Expr::Lit } + | + syn!(ExprPath) => { Expr::Path } + ) >> + (if let Some(neg) = neg { + Expr::Unary(ExprUnary { + attrs: Vec::new(), + op: UnOp::Neg(neg), + expr: Box::new(v) + }) + } else { + v + }) + )); + + #[cfg(feature = "full")] + impl Synom for PatSlice { + named!(parse -> Self, map!( + brackets!(do_parse!( + before: call!(Punctuated::parse_terminated) >> + middle: option!(do_parse!( + dots: punct!(..) >> + trailing: option!(punct!(,)) >> + (dots, trailing) + )) >> + after: cond!( + match middle { + Some((_, ref trailing)) => trailing.is_some(), + _ => false, + }, + Punctuated::parse_terminated + ) >> + (before, middle, after) + )), + |(brackets, (before, middle, after))| { + let mut before: Punctuated<Pat, Token![,]> = before; + let after: Option<Punctuated<Pat, Token![,]>> = after; + let middle: Option<(Token![..], Option<Token![,]>)> = middle; + PatSlice { + dot2_token: middle.as_ref().map(|m| Token![..]((m.0).0)), + comma_token: middle.as_ref().and_then(|m| { + m.1.as_ref().map(|m| Token![,](m.0)) + }), + bracket_token: brackets, + middle: middle.and_then(|_| { + if before.empty_or_trailing() { + None + } else { + Some(Box::new(before.pop().unwrap().into_value())) + } + }), + front: before, + back: after.unwrap_or_default(), + } + } + )); + + fn description() -> Option<&'static str> { + Some("slice pattern") + } + } + + #[cfg(feature = "full")] + impl Synom for PatMacro { + named!(parse -> Self, map!(syn!(Macro), |mac| PatMacro { mac: mac })); + + fn description() -> Option<&'static str> { + Some("macro pattern") + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + #[cfg(feature = "full")] + use attr::FilterAttrs; + use quote::{ToTokens, Tokens}; + use proc_macro2::Literal; + + // If the given expression is a bare `ExprStruct`, wraps it in parenthesis + // before appending it to `Tokens`. + #[cfg(feature = "full")] + fn wrap_bare_struct(tokens: &mut Tokens, e: &Expr) { + if let Expr::Struct(_) = *e { + token::Paren::default().surround(tokens, |tokens| { + e.to_tokens(tokens); + }); + } else { + e.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + fn attrs_to_tokens(attrs: &[Attribute], tokens: &mut Tokens) { + tokens.append_all(attrs.outer()); + } + + #[cfg(not(feature = "full"))] + fn attrs_to_tokens(_attrs: &[Attribute], _tokens: &mut Tokens) {} + + #[cfg(feature = "full")] + impl ToTokens for ExprBox { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.box_token.to_tokens(tokens); + self.expr.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprInPlace { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.place.to_tokens(tokens); + self.arrow_token.to_tokens(tokens); + self.value.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprArray { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.bracket_token.surround(tokens, |tokens| { + self.elems.to_tokens(tokens); + }) + } + } + + impl ToTokens for ExprCall { + fn to_tokens(&self, tokens: &mut Tokens) { + attrs_to_tokens(&self.attrs, tokens); + self.func.to_tokens(tokens); + self.paren_token.surround(tokens, |tokens| { + self.args.to_tokens(tokens); + }) + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprMethodCall { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.receiver.to_tokens(tokens); + self.dot_token.to_tokens(tokens); + self.method.to_tokens(tokens); + self.turbofish.to_tokens(tokens); + self.paren_token.surround(tokens, |tokens| { + self.args.to_tokens(tokens); + }); + } + } + + #[cfg(feature = "full")] + impl ToTokens for MethodTurbofish { + fn to_tokens(&self, tokens: &mut Tokens) { + self.colon2_token.to_tokens(tokens); + self.lt_token.to_tokens(tokens); + self.args.to_tokens(tokens); + self.gt_token.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for GenericMethodArgument { + fn to_tokens(&self, tokens: &mut Tokens) { + match *self { + GenericMethodArgument::Type(ref t) => t.to_tokens(tokens), + GenericMethodArgument::Const(ref c) => c.to_tokens(tokens), + } + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprTuple { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.paren_token.surround(tokens, |tokens| { + self.elems.to_tokens(tokens); + // If we only have one argument, we need a trailing comma to + // distinguish ExprTuple from ExprParen. + if self.elems.len() == 1 && !self.elems.trailing_punct() { + <Token![,]>::default().to_tokens(tokens); + } + }) + } + } + + impl ToTokens for ExprBinary { + fn to_tokens(&self, tokens: &mut Tokens) { + attrs_to_tokens(&self.attrs, tokens); + self.left.to_tokens(tokens); + self.op.to_tokens(tokens); + self.right.to_tokens(tokens); + } + } + + impl ToTokens for ExprUnary { + fn to_tokens(&self, tokens: &mut Tokens) { + attrs_to_tokens(&self.attrs, tokens); + self.op.to_tokens(tokens); + self.expr.to_tokens(tokens); + } + } + + impl ToTokens for ExprLit { + fn to_tokens(&self, tokens: &mut Tokens) { + attrs_to_tokens(&self.attrs, tokens); + self.lit.to_tokens(tokens); + } + } + + impl ToTokens for ExprCast { + fn to_tokens(&self, tokens: &mut Tokens) { + attrs_to_tokens(&self.attrs, tokens); + self.expr.to_tokens(tokens); + self.as_token.to_tokens(tokens); + self.ty.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprType { + fn to_tokens(&self, tokens: &mut Tokens) { + attrs_to_tokens(&self.attrs, tokens); + self.expr.to_tokens(tokens); + self.colon_token.to_tokens(tokens); + self.ty.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + fn maybe_wrap_else(tokens: &mut Tokens, else_: &Option<(Token![else], Box<Expr>)>) { + if let Some((ref else_token, ref else_)) = *else_ { + else_token.to_tokens(tokens); + + // If we are not one of the valid expressions to exist in an else + // clause, wrap ourselves in a block. + match **else_ { + Expr::If(_) | Expr::IfLet(_) | Expr::Block(_) => { + else_.to_tokens(tokens); + } + _ => { + token::Brace::default().surround(tokens, |tokens| { + else_.to_tokens(tokens); + }); + } + } + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprIf { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.if_token.to_tokens(tokens); + wrap_bare_struct(tokens, &self.cond); + self.then_branch.to_tokens(tokens); + maybe_wrap_else(tokens, &self.else_branch); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprIfLet { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.if_token.to_tokens(tokens); + self.let_token.to_tokens(tokens); + self.pats.to_tokens(tokens); + self.eq_token.to_tokens(tokens); + wrap_bare_struct(tokens, &self.expr); + self.then_branch.to_tokens(tokens); + maybe_wrap_else(tokens, &self.else_branch); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprWhile { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.label.to_tokens(tokens); + self.while_token.to_tokens(tokens); + wrap_bare_struct(tokens, &self.cond); + self.body.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprWhileLet { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.label.to_tokens(tokens); + self.while_token.to_tokens(tokens); + self.let_token.to_tokens(tokens); + self.pats.to_tokens(tokens); + self.eq_token.to_tokens(tokens); + wrap_bare_struct(tokens, &self.expr); + self.body.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprForLoop { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.label.to_tokens(tokens); + self.for_token.to_tokens(tokens); + self.pat.to_tokens(tokens); + self.in_token.to_tokens(tokens); + wrap_bare_struct(tokens, &self.expr); + self.body.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprLoop { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.label.to_tokens(tokens); + self.loop_token.to_tokens(tokens); + self.body.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprMatch { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.match_token.to_tokens(tokens); + wrap_bare_struct(tokens, &self.expr); + self.brace_token.surround(tokens, |tokens| { + for (i, arm) in self.arms.iter().enumerate() { + arm.to_tokens(tokens); + // Ensure that we have a comma after a non-block arm, except + // for the last one. + let is_last = i == self.arms.len() - 1; + if !is_last && arm_expr_requires_comma(&arm.body) && arm.comma.is_none() { + <Token![,]>::default().to_tokens(tokens); + } + } + }); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprCatch { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.do_token.to_tokens(tokens); + self.catch_token.to_tokens(tokens); + self.block.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprYield { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.yield_token.to_tokens(tokens); + self.expr.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprClosure { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.movability.to_tokens(tokens); + self.capture.to_tokens(tokens); + self.or1_token.to_tokens(tokens); + for input in self.inputs.pairs() { + match **input.value() { + FnArg::Captured(ArgCaptured { + ref pat, + ty: Type::Infer(_), + .. + }) => { + pat.to_tokens(tokens); + } + _ => input.value().to_tokens(tokens), + } + input.punct().to_tokens(tokens); + } + self.or2_token.to_tokens(tokens); + self.output.to_tokens(tokens); + self.body.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprUnsafe { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.unsafe_token.to_tokens(tokens); + self.block.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprBlock { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.block.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprAssign { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.left.to_tokens(tokens); + self.eq_token.to_tokens(tokens); + self.right.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprAssignOp { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.left.to_tokens(tokens); + self.op.to_tokens(tokens); + self.right.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprField { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.base.to_tokens(tokens); + self.dot_token.to_tokens(tokens); + self.member.to_tokens(tokens); + } + } + + impl ToTokens for Member { + fn to_tokens(&self, tokens: &mut Tokens) { + match *self { + Member::Named(ident) => ident.to_tokens(tokens), + Member::Unnamed(ref index) => index.to_tokens(tokens), + } + } + } + + impl ToTokens for Index { + fn to_tokens(&self, tokens: &mut Tokens) { + let mut lit = Literal::i64_unsuffixed(i64::from(self.index)); + lit.set_span(self.span); + tokens.append(lit); + } + } + + impl ToTokens for ExprIndex { + fn to_tokens(&self, tokens: &mut Tokens) { + attrs_to_tokens(&self.attrs, tokens); + self.expr.to_tokens(tokens); + self.bracket_token.surround(tokens, |tokens| { + self.index.to_tokens(tokens); + }); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprRange { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.from.to_tokens(tokens); + match self.limits { + RangeLimits::HalfOpen(ref t) => t.to_tokens(tokens), + RangeLimits::Closed(ref t) => t.to_tokens(tokens), + } + self.to.to_tokens(tokens); + } + } + + impl ToTokens for ExprPath { + fn to_tokens(&self, tokens: &mut Tokens) { + attrs_to_tokens(&self.attrs, tokens); + ::PathTokens(&self.qself, &self.path).to_tokens(tokens) + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprReference { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.and_token.to_tokens(tokens); + self.mutability.to_tokens(tokens); + self.expr.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprBreak { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.break_token.to_tokens(tokens); + self.label.to_tokens(tokens); + self.expr.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprContinue { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.continue_token.to_tokens(tokens); + self.label.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprReturn { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.return_token.to_tokens(tokens); + self.expr.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprMacro { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.mac.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprStruct { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.path.to_tokens(tokens); + self.brace_token.surround(tokens, |tokens| { + self.fields.to_tokens(tokens); + if self.rest.is_some() { + TokensOrDefault(&self.dot2_token).to_tokens(tokens); + self.rest.to_tokens(tokens); + } + }) + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprRepeat { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.bracket_token.surround(tokens, |tokens| { + self.expr.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + self.len.to_tokens(tokens); + }) + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprGroup { + fn to_tokens(&self, tokens: &mut Tokens) { + attrs_to_tokens(&self.attrs, tokens); + self.group_token.surround(tokens, |tokens| { + self.expr.to_tokens(tokens); + }); + } + } + + impl ToTokens for ExprParen { + fn to_tokens(&self, tokens: &mut Tokens) { + attrs_to_tokens(&self.attrs, tokens); + self.paren_token.surround(tokens, |tokens| { + self.expr.to_tokens(tokens); + }); + } + } + + #[cfg(feature = "full")] + impl ToTokens for ExprTry { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.expr.to_tokens(tokens); + self.question_token.to_tokens(tokens); + } + } + + impl ToTokens for ExprVerbatim { + fn to_tokens(&self, tokens: &mut Tokens) { + self.tts.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for Label { + fn to_tokens(&self, tokens: &mut Tokens) { + self.name.to_tokens(tokens); + self.colon_token.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for FieldValue { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.member.to_tokens(tokens); + if let Some(ref colon_token) = self.colon_token { + colon_token.to_tokens(tokens); + self.expr.to_tokens(tokens); + } + } + } + + #[cfg(feature = "full")] + impl ToTokens for Arm { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(&self.attrs); + self.leading_vert.to_tokens(tokens); + self.pats.to_tokens(tokens); + if let Some((ref if_token, ref guard)) = self.guard { + if_token.to_tokens(tokens); + guard.to_tokens(tokens); + } + self.fat_arrow_token.to_tokens(tokens); + self.body.to_tokens(tokens); + self.comma.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatWild { + fn to_tokens(&self, tokens: &mut Tokens) { + self.underscore_token.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatIdent { + fn to_tokens(&self, tokens: &mut Tokens) { + self.by_ref.to_tokens(tokens); + self.mutability.to_tokens(tokens); + self.ident.to_tokens(tokens); + if let Some((ref at_token, ref subpat)) = self.subpat { + at_token.to_tokens(tokens); + subpat.to_tokens(tokens); + } + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatStruct { + fn to_tokens(&self, tokens: &mut Tokens) { + self.path.to_tokens(tokens); + self.brace_token.surround(tokens, |tokens| { + self.fields.to_tokens(tokens); + // NOTE: We need a comma before the dot2 token if it is present. + if !self.fields.empty_or_trailing() && self.dot2_token.is_some() { + <Token![,]>::default().to_tokens(tokens); + } + self.dot2_token.to_tokens(tokens); + }); + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatTupleStruct { + fn to_tokens(&self, tokens: &mut Tokens) { + self.path.to_tokens(tokens); + self.pat.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatPath { + fn to_tokens(&self, tokens: &mut Tokens) { + ::PathTokens(&self.qself, &self.path).to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatTuple { + fn to_tokens(&self, tokens: &mut Tokens) { + self.paren_token.surround(tokens, |tokens| { + self.front.to_tokens(tokens); + if let Some(ref dot2_token) = self.dot2_token { + if !self.front.empty_or_trailing() { + // Ensure there is a comma before the .. token. + <Token![,]>::default().to_tokens(tokens); + } + dot2_token.to_tokens(tokens); + self.comma_token.to_tokens(tokens); + if self.comma_token.is_none() && !self.back.is_empty() { + // Ensure there is a comma after the .. token. + <Token![,]>::default().to_tokens(tokens); + } + } + self.back.to_tokens(tokens); + }); + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatBox { + fn to_tokens(&self, tokens: &mut Tokens) { + self.box_token.to_tokens(tokens); + self.pat.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatRef { + fn to_tokens(&self, tokens: &mut Tokens) { + self.and_token.to_tokens(tokens); + self.mutability.to_tokens(tokens); + self.pat.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatLit { + fn to_tokens(&self, tokens: &mut Tokens) { + self.expr.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatRange { + fn to_tokens(&self, tokens: &mut Tokens) { + self.lo.to_tokens(tokens); + match self.limits { + RangeLimits::HalfOpen(ref t) => t.to_tokens(tokens), + RangeLimits::Closed(ref t) => Token![...](t.0).to_tokens(tokens), + } + self.hi.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatSlice { + fn to_tokens(&self, tokens: &mut Tokens) { + // XXX: This is a mess, and it will be so easy to screw it up. How + // do we make this correct itself better? + self.bracket_token.surround(tokens, |tokens| { + self.front.to_tokens(tokens); + + // If we need a comma before the middle or standalone .. token, + // then make sure it's present. + if !self.front.empty_or_trailing() + && (self.middle.is_some() || self.dot2_token.is_some()) + { + <Token![,]>::default().to_tokens(tokens); + } + + // If we have an identifier, we always need a .. token. + if self.middle.is_some() { + self.middle.to_tokens(tokens); + TokensOrDefault(&self.dot2_token).to_tokens(tokens); + } else if self.dot2_token.is_some() { + self.dot2_token.to_tokens(tokens); + } + + // Make sure we have a comma before the back half. + if !self.back.is_empty() { + TokensOrDefault(&self.comma_token).to_tokens(tokens); + self.back.to_tokens(tokens); + } else { + self.comma_token.to_tokens(tokens); + } + }) + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatMacro { + fn to_tokens(&self, tokens: &mut Tokens) { + self.mac.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for PatVerbatim { + fn to_tokens(&self, tokens: &mut Tokens) { + self.tts.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for FieldPat { + fn to_tokens(&self, tokens: &mut Tokens) { + if let Some(ref colon_token) = self.colon_token { + self.member.to_tokens(tokens); + colon_token.to_tokens(tokens); + } + self.pat.to_tokens(tokens); + } + } + + #[cfg(feature = "full")] + impl ToTokens for Block { + fn to_tokens(&self, tokens: &mut Tokens) { + self.brace_token.surround(tokens, |tokens| { + tokens.append_all(&self.stmts); + }); + } + } + + #[cfg(feature = "full")] + impl ToTokens for Stmt { + fn to_tokens(&self, tokens: &mut Tokens) { + match *self { + Stmt::Local(ref local) => local.to_tokens(tokens), + Stmt::Item(ref item) => item.to_tokens(tokens), + Stmt::Expr(ref expr) => expr.to_tokens(tokens), + Stmt::Semi(ref expr, ref semi) => { + expr.to_tokens(tokens); + semi.to_tokens(tokens); + } + } + } + } + + #[cfg(feature = "full")] + impl ToTokens for Local { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.let_token.to_tokens(tokens); + self.pats.to_tokens(tokens); + if let Some((ref colon_token, ref ty)) = self.ty { + colon_token.to_tokens(tokens); + ty.to_tokens(tokens); + } + if let Some((ref eq_token, ref init)) = self.init { + eq_token.to_tokens(tokens); + init.to_tokens(tokens); + } + self.semi_token.to_tokens(tokens); + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/file.rs cargo-0.26.0/vendor/syn-0.13.1/src/file.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/file.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/file.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,122 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use super::*; + +ast_struct! { + /// A complete file of Rust source code. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + /// + /// # Example + /// + /// Parse a Rust source file into a `syn::File` and print out a debug + /// representation of the syntax tree. + /// + /// ``` + /// extern crate syn; + /// + /// use std::env; + /// use std::fs::File; + /// use std::io::Read; + /// use std::process; + /// + /// fn main() { + /// # } + /// # + /// # fn fake_main() { + /// let mut args = env::args(); + /// let _ = args.next(); // executable name + /// + /// let filename = match (args.next(), args.next()) { + /// (Some(filename), None) => filename, + /// _ => { + /// eprintln!("Usage: dump-syntax path/to/filename.rs"); + /// process::exit(1); + /// } + /// }; + /// + /// let mut file = File::open(&filename).expect("Unable to open file"); + /// + /// let mut src = String::new(); + /// file.read_to_string(&mut src).expect("Unable to read file"); + /// + /// let syntax = syn::parse_file(&src).expect("Unable to parse file"); + /// println!("{:#?}", syntax); + /// } + /// ``` + /// + /// Running with its own source code as input, this program prints output + /// that begins with: + /// + /// ```text + /// File { + /// shebang: None, + /// attrs: [], + /// items: [ + /// ExternCrate( + /// ItemExternCrate { + /// attrs: [], + /// vis: Inherited, + /// extern_token: Extern, + /// crate_token: Crate, + /// ident: Ident { + /// term: Term( + /// "syn" + /// ), + /// span: Span + /// }, + /// rename: None, + /// semi_token: Semi + /// } + /// ), + /// ... + /// ``` + pub struct File { + pub shebang: Option<String>, + pub attrs: Vec<Attribute>, + pub items: Vec<Item>, + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + + use synom::Synom; + + impl Synom for File { + named!(parse -> Self, do_parse!( + attrs: many0!(Attribute::parse_inner) >> + items: many0!(Item::parse) >> + (File { + shebang: None, + attrs: attrs, + items: items, + }) + )); + + fn description() -> Option<&'static str> { + Some("crate") + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use attr::FilterAttrs; + use quote::{ToTokens, Tokens}; + + impl ToTokens for File { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.inner()); + tokens.append_all(&self.items); + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/gen/fold.rs cargo-0.26.0/vendor/syn-0.13.1/src/gen/fold.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/gen/fold.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/gen/fold.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2972 @@ +// THIS FILE IS AUTOMATICALLY GENERATED; DO NOT EDIT + +#![cfg_attr(rustfmt, rustfmt_skip)] + +// Unreachable code is generated sometimes without the full feature. +#![allow(unreachable_code)] +#![cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))] + +use *; +#[cfg(any(feature = "full", feature = "derive"))] +use token::{Brace, Bracket, Paren, Group}; +use proc_macro2::Span; +#[cfg(any(feature = "full", feature = "derive"))] +use gen::helper::fold::*; + + +#[cfg(feature = "full")] +macro_rules! full { + ($e:expr) => { $e } +} + +#[cfg(all(feature = "derive", not(feature = "full")))] +macro_rules! full { + ($e:expr) => { unreachable!() } +} + + +/// Syntax tree traversal to transform the nodes of an owned syntax tree. +/// +/// See the [module documentation] for details. +/// +/// [module documentation]: index.html +/// +/// *This trait is available if Syn is built with the `"fold"` feature.* +pub trait Fold { +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_abi(&mut self, i: Abi) -> Abi { fold_abi(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_angle_bracketed_generic_arguments(&mut self, i: AngleBracketedGenericArguments) -> AngleBracketedGenericArguments { fold_angle_bracketed_generic_arguments(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_arg_captured(&mut self, i: ArgCaptured) -> ArgCaptured { fold_arg_captured(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_arg_self(&mut self, i: ArgSelf) -> ArgSelf { fold_arg_self(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_arg_self_ref(&mut self, i: ArgSelfRef) -> ArgSelfRef { fold_arg_self_ref(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_arm(&mut self, i: Arm) -> Arm { fold_arm(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_attr_style(&mut self, i: AttrStyle) -> AttrStyle { fold_attr_style(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_attribute(&mut self, i: Attribute) -> Attribute { fold_attribute(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_bare_fn_arg(&mut self, i: BareFnArg) -> BareFnArg { fold_bare_fn_arg(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_bare_fn_arg_name(&mut self, i: BareFnArgName) -> BareFnArgName { fold_bare_fn_arg_name(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_bin_op(&mut self, i: BinOp) -> BinOp { fold_bin_op(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_binding(&mut self, i: Binding) -> Binding { fold_binding(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_block(&mut self, i: Block) -> Block { fold_block(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_bound_lifetimes(&mut self, i: BoundLifetimes) -> BoundLifetimes { fold_bound_lifetimes(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_const_param(&mut self, i: ConstParam) -> ConstParam { fold_const_param(self, i) } +# [ cfg ( feature = "derive" ) ] +fn fold_data(&mut self, i: Data) -> Data { fold_data(self, i) } +# [ cfg ( feature = "derive" ) ] +fn fold_data_enum(&mut self, i: DataEnum) -> DataEnum { fold_data_enum(self, i) } +# [ cfg ( feature = "derive" ) ] +fn fold_data_struct(&mut self, i: DataStruct) -> DataStruct { fold_data_struct(self, i) } +# [ cfg ( feature = "derive" ) ] +fn fold_data_union(&mut self, i: DataUnion) -> DataUnion { fold_data_union(self, i) } +# [ cfg ( feature = "derive" ) ] +fn fold_derive_input(&mut self, i: DeriveInput) -> DeriveInput { fold_derive_input(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr(&mut self, i: Expr) -> Expr { fold_expr(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_array(&mut self, i: ExprArray) -> ExprArray { fold_expr_array(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_assign(&mut self, i: ExprAssign) -> ExprAssign { fold_expr_assign(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_assign_op(&mut self, i: ExprAssignOp) -> ExprAssignOp { fold_expr_assign_op(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_binary(&mut self, i: ExprBinary) -> ExprBinary { fold_expr_binary(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_block(&mut self, i: ExprBlock) -> ExprBlock { fold_expr_block(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_box(&mut self, i: ExprBox) -> ExprBox { fold_expr_box(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_break(&mut self, i: ExprBreak) -> ExprBreak { fold_expr_break(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_call(&mut self, i: ExprCall) -> ExprCall { fold_expr_call(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_cast(&mut self, i: ExprCast) -> ExprCast { fold_expr_cast(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_catch(&mut self, i: ExprCatch) -> ExprCatch { fold_expr_catch(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_closure(&mut self, i: ExprClosure) -> ExprClosure { fold_expr_closure(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_continue(&mut self, i: ExprContinue) -> ExprContinue { fold_expr_continue(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_field(&mut self, i: ExprField) -> ExprField { fold_expr_field(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_for_loop(&mut self, i: ExprForLoop) -> ExprForLoop { fold_expr_for_loop(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_group(&mut self, i: ExprGroup) -> ExprGroup { fold_expr_group(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_if(&mut self, i: ExprIf) -> ExprIf { fold_expr_if(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_if_let(&mut self, i: ExprIfLet) -> ExprIfLet { fold_expr_if_let(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_in_place(&mut self, i: ExprInPlace) -> ExprInPlace { fold_expr_in_place(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_index(&mut self, i: ExprIndex) -> ExprIndex { fold_expr_index(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_lit(&mut self, i: ExprLit) -> ExprLit { fold_expr_lit(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_loop(&mut self, i: ExprLoop) -> ExprLoop { fold_expr_loop(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_macro(&mut self, i: ExprMacro) -> ExprMacro { fold_expr_macro(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_match(&mut self, i: ExprMatch) -> ExprMatch { fold_expr_match(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_method_call(&mut self, i: ExprMethodCall) -> ExprMethodCall { fold_expr_method_call(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_paren(&mut self, i: ExprParen) -> ExprParen { fold_expr_paren(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_path(&mut self, i: ExprPath) -> ExprPath { fold_expr_path(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_range(&mut self, i: ExprRange) -> ExprRange { fold_expr_range(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_reference(&mut self, i: ExprReference) -> ExprReference { fold_expr_reference(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_repeat(&mut self, i: ExprRepeat) -> ExprRepeat { fold_expr_repeat(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_return(&mut self, i: ExprReturn) -> ExprReturn { fold_expr_return(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_struct(&mut self, i: ExprStruct) -> ExprStruct { fold_expr_struct(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_try(&mut self, i: ExprTry) -> ExprTry { fold_expr_try(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_tuple(&mut self, i: ExprTuple) -> ExprTuple { fold_expr_tuple(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_type(&mut self, i: ExprType) -> ExprType { fold_expr_type(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_unary(&mut self, i: ExprUnary) -> ExprUnary { fold_expr_unary(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_unsafe(&mut self, i: ExprUnsafe) -> ExprUnsafe { fold_expr_unsafe(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_verbatim(&mut self, i: ExprVerbatim) -> ExprVerbatim { fold_expr_verbatim(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_while(&mut self, i: ExprWhile) -> ExprWhile { fold_expr_while(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_while_let(&mut self, i: ExprWhileLet) -> ExprWhileLet { fold_expr_while_let(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_expr_yield(&mut self, i: ExprYield) -> ExprYield { fold_expr_yield(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_field(&mut self, i: Field) -> Field { fold_field(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_field_pat(&mut self, i: FieldPat) -> FieldPat { fold_field_pat(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_field_value(&mut self, i: FieldValue) -> FieldValue { fold_field_value(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_fields(&mut self, i: Fields) -> Fields { fold_fields(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_fields_named(&mut self, i: FieldsNamed) -> FieldsNamed { fold_fields_named(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_fields_unnamed(&mut self, i: FieldsUnnamed) -> FieldsUnnamed { fold_fields_unnamed(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_file(&mut self, i: File) -> File { fold_file(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_fn_arg(&mut self, i: FnArg) -> FnArg { fold_fn_arg(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_fn_decl(&mut self, i: FnDecl) -> FnDecl { fold_fn_decl(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_foreign_item(&mut self, i: ForeignItem) -> ForeignItem { fold_foreign_item(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_foreign_item_fn(&mut self, i: ForeignItemFn) -> ForeignItemFn { fold_foreign_item_fn(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_foreign_item_static(&mut self, i: ForeignItemStatic) -> ForeignItemStatic { fold_foreign_item_static(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_foreign_item_type(&mut self, i: ForeignItemType) -> ForeignItemType { fold_foreign_item_type(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_foreign_item_verbatim(&mut self, i: ForeignItemVerbatim) -> ForeignItemVerbatim { fold_foreign_item_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_generic_argument(&mut self, i: GenericArgument) -> GenericArgument { fold_generic_argument(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_generic_method_argument(&mut self, i: GenericMethodArgument) -> GenericMethodArgument { fold_generic_method_argument(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_generic_param(&mut self, i: GenericParam) -> GenericParam { fold_generic_param(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_generics(&mut self, i: Generics) -> Generics { fold_generics(self, i) } + +fn fold_ident(&mut self, i: Ident) -> Ident { fold_ident(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_impl_item(&mut self, i: ImplItem) -> ImplItem { fold_impl_item(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_impl_item_const(&mut self, i: ImplItemConst) -> ImplItemConst { fold_impl_item_const(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_impl_item_macro(&mut self, i: ImplItemMacro) -> ImplItemMacro { fold_impl_item_macro(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_impl_item_method(&mut self, i: ImplItemMethod) -> ImplItemMethod { fold_impl_item_method(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_impl_item_type(&mut self, i: ImplItemType) -> ImplItemType { fold_impl_item_type(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_impl_item_verbatim(&mut self, i: ImplItemVerbatim) -> ImplItemVerbatim { fold_impl_item_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_index(&mut self, i: Index) -> Index { fold_index(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item(&mut self, i: Item) -> Item { fold_item(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_const(&mut self, i: ItemConst) -> ItemConst { fold_item_const(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_enum(&mut self, i: ItemEnum) -> ItemEnum { fold_item_enum(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_extern_crate(&mut self, i: ItemExternCrate) -> ItemExternCrate { fold_item_extern_crate(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_fn(&mut self, i: ItemFn) -> ItemFn { fold_item_fn(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_foreign_mod(&mut self, i: ItemForeignMod) -> ItemForeignMod { fold_item_foreign_mod(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_impl(&mut self, i: ItemImpl) -> ItemImpl { fold_item_impl(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_macro(&mut self, i: ItemMacro) -> ItemMacro { fold_item_macro(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_macro2(&mut self, i: ItemMacro2) -> ItemMacro2 { fold_item_macro2(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_mod(&mut self, i: ItemMod) -> ItemMod { fold_item_mod(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_static(&mut self, i: ItemStatic) -> ItemStatic { fold_item_static(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_struct(&mut self, i: ItemStruct) -> ItemStruct { fold_item_struct(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_trait(&mut self, i: ItemTrait) -> ItemTrait { fold_item_trait(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_type(&mut self, i: ItemType) -> ItemType { fold_item_type(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_union(&mut self, i: ItemUnion) -> ItemUnion { fold_item_union(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_use(&mut self, i: ItemUse) -> ItemUse { fold_item_use(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_item_verbatim(&mut self, i: ItemVerbatim) -> ItemVerbatim { fold_item_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_label(&mut self, i: Label) -> Label { fold_label(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_lifetime(&mut self, i: Lifetime) -> Lifetime { fold_lifetime(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_lifetime_def(&mut self, i: LifetimeDef) -> LifetimeDef { fold_lifetime_def(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_lit(&mut self, i: Lit) -> Lit { fold_lit(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_lit_bool(&mut self, i: LitBool) -> LitBool { fold_lit_bool(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_lit_byte(&mut self, i: LitByte) -> LitByte { fold_lit_byte(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_lit_byte_str(&mut self, i: LitByteStr) -> LitByteStr { fold_lit_byte_str(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_lit_char(&mut self, i: LitChar) -> LitChar { fold_lit_char(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_lit_float(&mut self, i: LitFloat) -> LitFloat { fold_lit_float(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_lit_int(&mut self, i: LitInt) -> LitInt { fold_lit_int(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_lit_str(&mut self, i: LitStr) -> LitStr { fold_lit_str(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_lit_verbatim(&mut self, i: LitVerbatim) -> LitVerbatim { fold_lit_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_local(&mut self, i: Local) -> Local { fold_local(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_macro(&mut self, i: Macro) -> Macro { fold_macro(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_macro_delimiter(&mut self, i: MacroDelimiter) -> MacroDelimiter { fold_macro_delimiter(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_member(&mut self, i: Member) -> Member { fold_member(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_meta(&mut self, i: Meta) -> Meta { fold_meta(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_meta_list(&mut self, i: MetaList) -> MetaList { fold_meta_list(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_meta_name_value(&mut self, i: MetaNameValue) -> MetaNameValue { fold_meta_name_value(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_method_sig(&mut self, i: MethodSig) -> MethodSig { fold_method_sig(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_method_turbofish(&mut self, i: MethodTurbofish) -> MethodTurbofish { fold_method_turbofish(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_nested_meta(&mut self, i: NestedMeta) -> NestedMeta { fold_nested_meta(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_parenthesized_generic_arguments(&mut self, i: ParenthesizedGenericArguments) -> ParenthesizedGenericArguments { fold_parenthesized_generic_arguments(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat(&mut self, i: Pat) -> Pat { fold_pat(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_box(&mut self, i: PatBox) -> PatBox { fold_pat_box(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_ident(&mut self, i: PatIdent) -> PatIdent { fold_pat_ident(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_lit(&mut self, i: PatLit) -> PatLit { fold_pat_lit(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_macro(&mut self, i: PatMacro) -> PatMacro { fold_pat_macro(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_path(&mut self, i: PatPath) -> PatPath { fold_pat_path(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_range(&mut self, i: PatRange) -> PatRange { fold_pat_range(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_ref(&mut self, i: PatRef) -> PatRef { fold_pat_ref(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_slice(&mut self, i: PatSlice) -> PatSlice { fold_pat_slice(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_struct(&mut self, i: PatStruct) -> PatStruct { fold_pat_struct(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_tuple(&mut self, i: PatTuple) -> PatTuple { fold_pat_tuple(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_tuple_struct(&mut self, i: PatTupleStruct) -> PatTupleStruct { fold_pat_tuple_struct(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_verbatim(&mut self, i: PatVerbatim) -> PatVerbatim { fold_pat_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_pat_wild(&mut self, i: PatWild) -> PatWild { fold_pat_wild(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_path(&mut self, i: Path) -> Path { fold_path(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_path_arguments(&mut self, i: PathArguments) -> PathArguments { fold_path_arguments(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_path_segment(&mut self, i: PathSegment) -> PathSegment { fold_path_segment(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_predicate_eq(&mut self, i: PredicateEq) -> PredicateEq { fold_predicate_eq(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_predicate_lifetime(&mut self, i: PredicateLifetime) -> PredicateLifetime { fold_predicate_lifetime(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_predicate_type(&mut self, i: PredicateType) -> PredicateType { fold_predicate_type(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_qself(&mut self, i: QSelf) -> QSelf { fold_qself(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_range_limits(&mut self, i: RangeLimits) -> RangeLimits { fold_range_limits(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_return_type(&mut self, i: ReturnType) -> ReturnType { fold_return_type(self, i) } + +fn fold_span(&mut self, i: Span) -> Span { fold_span(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn fold_stmt(&mut self, i: Stmt) -> Stmt { fold_stmt(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_trait_bound(&mut self, i: TraitBound) -> TraitBound { fold_trait_bound(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_trait_bound_modifier(&mut self, i: TraitBoundModifier) -> TraitBoundModifier { fold_trait_bound_modifier(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_trait_item(&mut self, i: TraitItem) -> TraitItem { fold_trait_item(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_trait_item_const(&mut self, i: TraitItemConst) -> TraitItemConst { fold_trait_item_const(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_trait_item_macro(&mut self, i: TraitItemMacro) -> TraitItemMacro { fold_trait_item_macro(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_trait_item_method(&mut self, i: TraitItemMethod) -> TraitItemMethod { fold_trait_item_method(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_trait_item_type(&mut self, i: TraitItemType) -> TraitItemType { fold_trait_item_type(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_trait_item_verbatim(&mut self, i: TraitItemVerbatim) -> TraitItemVerbatim { fold_trait_item_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type(&mut self, i: Type) -> Type { fold_type(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_array(&mut self, i: TypeArray) -> TypeArray { fold_type_array(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_bare_fn(&mut self, i: TypeBareFn) -> TypeBareFn { fold_type_bare_fn(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_group(&mut self, i: TypeGroup) -> TypeGroup { fold_type_group(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_impl_trait(&mut self, i: TypeImplTrait) -> TypeImplTrait { fold_type_impl_trait(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_infer(&mut self, i: TypeInfer) -> TypeInfer { fold_type_infer(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_macro(&mut self, i: TypeMacro) -> TypeMacro { fold_type_macro(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_never(&mut self, i: TypeNever) -> TypeNever { fold_type_never(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_param(&mut self, i: TypeParam) -> TypeParam { fold_type_param(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_param_bound(&mut self, i: TypeParamBound) -> TypeParamBound { fold_type_param_bound(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_paren(&mut self, i: TypeParen) -> TypeParen { fold_type_paren(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_path(&mut self, i: TypePath) -> TypePath { fold_type_path(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_ptr(&mut self, i: TypePtr) -> TypePtr { fold_type_ptr(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_reference(&mut self, i: TypeReference) -> TypeReference { fold_type_reference(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_slice(&mut self, i: TypeSlice) -> TypeSlice { fold_type_slice(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_trait_object(&mut self, i: TypeTraitObject) -> TypeTraitObject { fold_type_trait_object(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_tuple(&mut self, i: TypeTuple) -> TypeTuple { fold_type_tuple(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_type_verbatim(&mut self, i: TypeVerbatim) -> TypeVerbatim { fold_type_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_un_op(&mut self, i: UnOp) -> UnOp { fold_un_op(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_use_glob(&mut self, i: UseGlob) -> UseGlob { fold_use_glob(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_use_group(&mut self, i: UseGroup) -> UseGroup { fold_use_group(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_use_name(&mut self, i: UseName) -> UseName { fold_use_name(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_use_path(&mut self, i: UsePath) -> UsePath { fold_use_path(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_use_rename(&mut self, i: UseRename) -> UseRename { fold_use_rename(self, i) } +# [ cfg ( feature = "full" ) ] +fn fold_use_tree(&mut self, i: UseTree) -> UseTree { fold_use_tree(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_variant(&mut self, i: Variant) -> Variant { fold_variant(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_vis_crate(&mut self, i: VisCrate) -> VisCrate { fold_vis_crate(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_vis_public(&mut self, i: VisPublic) -> VisPublic { fold_vis_public(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_vis_restricted(&mut self, i: VisRestricted) -> VisRestricted { fold_vis_restricted(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_visibility(&mut self, i: Visibility) -> Visibility { fold_visibility(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_where_clause(&mut self, i: WhereClause) -> WhereClause { fold_where_clause(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn fold_where_predicate(&mut self, i: WherePredicate) -> WherePredicate { fold_where_predicate(self, i) } + +} + +macro_rules! fold_span_only { + ($f:ident : $t:ident) => { + pub fn $f<V: Fold + ?Sized>(_visitor: &mut V, mut _i: $t) -> $t { + let span = _visitor.fold_span(_i.span()); + _i.set_span(span); + _i + } + } +} + +fold_span_only!(fold_ident: Ident); +#[cfg(any(feature = "full", feature = "derive"))] +fold_span_only!(fold_lifetime: Lifetime); +#[cfg(any(feature = "full", feature = "derive"))] +fold_span_only!(fold_lit_byte: LitByte); +#[cfg(any(feature = "full", feature = "derive"))] +fold_span_only!(fold_lit_byte_str: LitByteStr); +#[cfg(any(feature = "full", feature = "derive"))] +fold_span_only!(fold_lit_char: LitChar); +#[cfg(any(feature = "full", feature = "derive"))] +fold_span_only!(fold_lit_float: LitFloat); +#[cfg(any(feature = "full", feature = "derive"))] +fold_span_only!(fold_lit_int: LitInt); +#[cfg(any(feature = "full", feature = "derive"))] +fold_span_only!(fold_lit_str: LitStr); + +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_abi<V: Fold + ?Sized>(_visitor: &mut V, _i: Abi) -> Abi { + Abi { + extern_token: Token ! [ extern ](tokens_helper(_visitor, &(_i . extern_token).0)), + name: (_i . name).map(|it| { _visitor.fold_lit_str(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_angle_bracketed_generic_arguments<V: Fold + ?Sized>(_visitor: &mut V, _i: AngleBracketedGenericArguments) -> AngleBracketedGenericArguments { + AngleBracketedGenericArguments { + colon2_token: (_i . colon2_token).map(|it| { Token ! [ :: ](tokens_helper(_visitor, &(it).0)) }), + lt_token: Token ! [ < ](tokens_helper(_visitor, &(_i . lt_token).0)), + args: FoldHelper::lift(_i . args, |it| { _visitor.fold_generic_argument(it) }), + gt_token: Token ! [ > ](tokens_helper(_visitor, &(_i . gt_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_arg_captured<V: Fold + ?Sized>(_visitor: &mut V, _i: ArgCaptured) -> ArgCaptured { + ArgCaptured { + pat: _visitor.fold_pat(_i . pat), + colon_token: Token ! [ : ](tokens_helper(_visitor, &(_i . colon_token).0)), + ty: _visitor.fold_type(_i . ty), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_arg_self<V: Fold + ?Sized>(_visitor: &mut V, _i: ArgSelf) -> ArgSelf { + ArgSelf { + mutability: (_i . mutability).map(|it| { Token ! [ mut ](tokens_helper(_visitor, &(it).0)) }), + self_token: Token ! [ self ](tokens_helper(_visitor, &(_i . self_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_arg_self_ref<V: Fold + ?Sized>(_visitor: &mut V, _i: ArgSelfRef) -> ArgSelfRef { + ArgSelfRef { + and_token: Token ! [ & ](tokens_helper(_visitor, &(_i . and_token).0)), + lifetime: (_i . lifetime).map(|it| { _visitor.fold_lifetime(it) }), + mutability: (_i . mutability).map(|it| { Token ! [ mut ](tokens_helper(_visitor, &(it).0)) }), + self_token: Token ! [ self ](tokens_helper(_visitor, &(_i . self_token).0)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_arm<V: Fold + ?Sized>(_visitor: &mut V, _i: Arm) -> Arm { + Arm { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + leading_vert: (_i . leading_vert).map(|it| { Token ! [ | ](tokens_helper(_visitor, &(it).0)) }), + pats: FoldHelper::lift(_i . pats, |it| { _visitor.fold_pat(it) }), + guard: (_i . guard).map(|it| { ( + Token ! [ if ](tokens_helper(_visitor, &(( it ) . 0).0)), + Box::new(_visitor.fold_expr(* ( it ) . 1)), + ) }), + fat_arrow_token: Token ! [ => ](tokens_helper(_visitor, &(_i . fat_arrow_token).0)), + body: Box::new(_visitor.fold_expr(* _i . body)), + comma: (_i . comma).map(|it| { Token ! [ , ](tokens_helper(_visitor, &(it).0)) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_attr_style<V: Fold + ?Sized>(_visitor: &mut V, _i: AttrStyle) -> AttrStyle { + match _i { + AttrStyle::Outer => { AttrStyle::Outer } + AttrStyle::Inner(_binding_0, ) => { + AttrStyle::Inner ( + Token ! [ ! ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_attribute<V: Fold + ?Sized>(_visitor: &mut V, _i: Attribute) -> Attribute { + Attribute { + pound_token: Token ! [ # ](tokens_helper(_visitor, &(_i . pound_token).0)), + style: _visitor.fold_attr_style(_i . style), + bracket_token: Bracket(tokens_helper(_visitor, &(_i . bracket_token).0)), + path: _visitor.fold_path(_i . path), + tts: _i . tts, + is_sugared_doc: _i . is_sugared_doc, + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_bare_fn_arg<V: Fold + ?Sized>(_visitor: &mut V, _i: BareFnArg) -> BareFnArg { + BareFnArg { + name: (_i . name).map(|it| { ( + _visitor.fold_bare_fn_arg_name(( it ) . 0), + Token ! [ : ](tokens_helper(_visitor, &(( it ) . 1).0)), + ) }), + ty: _visitor.fold_type(_i . ty), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_bare_fn_arg_name<V: Fold + ?Sized>(_visitor: &mut V, _i: BareFnArgName) -> BareFnArgName { + match _i { + BareFnArgName::Named(_binding_0, ) => { + BareFnArgName::Named ( + _visitor.fold_ident(_binding_0), + ) + } + BareFnArgName::Wild(_binding_0, ) => { + BareFnArgName::Wild ( + Token ! [ _ ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_bin_op<V: Fold + ?Sized>(_visitor: &mut V, _i: BinOp) -> BinOp { + match _i { + BinOp::Add(_binding_0, ) => { + BinOp::Add ( + Token ! [ + ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Sub(_binding_0, ) => { + BinOp::Sub ( + Token ! [ - ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Mul(_binding_0, ) => { + BinOp::Mul ( + Token ! [ * ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Div(_binding_0, ) => { + BinOp::Div ( + Token ! [ / ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Rem(_binding_0, ) => { + BinOp::Rem ( + Token ! [ % ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::And(_binding_0, ) => { + BinOp::And ( + Token ! [ && ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Or(_binding_0, ) => { + BinOp::Or ( + Token ! [ || ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::BitXor(_binding_0, ) => { + BinOp::BitXor ( + Token ! [ ^ ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::BitAnd(_binding_0, ) => { + BinOp::BitAnd ( + Token ! [ & ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::BitOr(_binding_0, ) => { + BinOp::BitOr ( + Token ! [ | ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Shl(_binding_0, ) => { + BinOp::Shl ( + Token ! [ << ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Shr(_binding_0, ) => { + BinOp::Shr ( + Token ! [ >> ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Eq(_binding_0, ) => { + BinOp::Eq ( + Token ! [ == ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Lt(_binding_0, ) => { + BinOp::Lt ( + Token ! [ < ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Le(_binding_0, ) => { + BinOp::Le ( + Token ! [ <= ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Ne(_binding_0, ) => { + BinOp::Ne ( + Token ! [ != ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Ge(_binding_0, ) => { + BinOp::Ge ( + Token ! [ >= ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::Gt(_binding_0, ) => { + BinOp::Gt ( + Token ! [ > ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::AddEq(_binding_0, ) => { + BinOp::AddEq ( + Token ! [ += ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::SubEq(_binding_0, ) => { + BinOp::SubEq ( + Token ! [ -= ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::MulEq(_binding_0, ) => { + BinOp::MulEq ( + Token ! [ *= ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::DivEq(_binding_0, ) => { + BinOp::DivEq ( + Token ! [ /= ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::RemEq(_binding_0, ) => { + BinOp::RemEq ( + Token ! [ %= ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::BitXorEq(_binding_0, ) => { + BinOp::BitXorEq ( + Token ! [ ^= ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::BitAndEq(_binding_0, ) => { + BinOp::BitAndEq ( + Token ! [ &= ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::BitOrEq(_binding_0, ) => { + BinOp::BitOrEq ( + Token ! [ |= ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::ShlEq(_binding_0, ) => { + BinOp::ShlEq ( + Token ! [ <<= ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + BinOp::ShrEq(_binding_0, ) => { + BinOp::ShrEq ( + Token ! [ >>= ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_binding<V: Fold + ?Sized>(_visitor: &mut V, _i: Binding) -> Binding { + Binding { + ident: _visitor.fold_ident(_i . ident), + eq_token: Token ! [ = ](tokens_helper(_visitor, &(_i . eq_token).0)), + ty: _visitor.fold_type(_i . ty), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_block<V: Fold + ?Sized>(_visitor: &mut V, _i: Block) -> Block { + Block { + brace_token: Brace(tokens_helper(_visitor, &(_i . brace_token).0)), + stmts: FoldHelper::lift(_i . stmts, |it| { _visitor.fold_stmt(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_bound_lifetimes<V: Fold + ?Sized>(_visitor: &mut V, _i: BoundLifetimes) -> BoundLifetimes { + BoundLifetimes { + for_token: Token ! [ for ](tokens_helper(_visitor, &(_i . for_token).0)), + lt_token: Token ! [ < ](tokens_helper(_visitor, &(_i . lt_token).0)), + lifetimes: FoldHelper::lift(_i . lifetimes, |it| { _visitor.fold_lifetime_def(it) }), + gt_token: Token ! [ > ](tokens_helper(_visitor, &(_i . gt_token).0)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_const_param<V: Fold + ?Sized>(_visitor: &mut V, _i: ConstParam) -> ConstParam { + ConstParam { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + const_token: Token ! [ const ](tokens_helper(_visitor, &(_i . const_token).0)), + ident: _visitor.fold_ident(_i . ident), + colon_token: Token ! [ : ](tokens_helper(_visitor, &(_i . colon_token).0)), + ty: _visitor.fold_type(_i . ty), + eq_token: (_i . eq_token).map(|it| { Token ! [ = ](tokens_helper(_visitor, &(it).0)) }), + default: (_i . default).map(|it| { _visitor.fold_expr(it) }), + } +} +# [ cfg ( feature = "derive" ) ] +pub fn fold_data<V: Fold + ?Sized>(_visitor: &mut V, _i: Data) -> Data { + match _i { + Data::Struct(_binding_0, ) => { + Data::Struct ( + _visitor.fold_data_struct(_binding_0), + ) + } + Data::Enum(_binding_0, ) => { + Data::Enum ( + _visitor.fold_data_enum(_binding_0), + ) + } + Data::Union(_binding_0, ) => { + Data::Union ( + _visitor.fold_data_union(_binding_0), + ) + } + } +} +# [ cfg ( feature = "derive" ) ] +pub fn fold_data_enum<V: Fold + ?Sized>(_visitor: &mut V, _i: DataEnum) -> DataEnum { + DataEnum { + enum_token: Token ! [ enum ](tokens_helper(_visitor, &(_i . enum_token).0)), + brace_token: Brace(tokens_helper(_visitor, &(_i . brace_token).0)), + variants: FoldHelper::lift(_i . variants, |it| { _visitor.fold_variant(it) }), + } +} +# [ cfg ( feature = "derive" ) ] +pub fn fold_data_struct<V: Fold + ?Sized>(_visitor: &mut V, _i: DataStruct) -> DataStruct { + DataStruct { + struct_token: Token ! [ struct ](tokens_helper(_visitor, &(_i . struct_token).0)), + fields: _visitor.fold_fields(_i . fields), + semi_token: (_i . semi_token).map(|it| { Token ! [ ; ](tokens_helper(_visitor, &(it).0)) }), + } +} +# [ cfg ( feature = "derive" ) ] +pub fn fold_data_union<V: Fold + ?Sized>(_visitor: &mut V, _i: DataUnion) -> DataUnion { + DataUnion { + union_token: Token ! [ union ](tokens_helper(_visitor, &(_i . union_token).0)), + fields: _visitor.fold_fields_named(_i . fields), + } +} +# [ cfg ( feature = "derive" ) ] +pub fn fold_derive_input<V: Fold + ?Sized>(_visitor: &mut V, _i: DeriveInput) -> DeriveInput { + DeriveInput { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + ident: _visitor.fold_ident(_i . ident), + generics: _visitor.fold_generics(_i . generics), + data: _visitor.fold_data(_i . data), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr<V: Fold + ?Sized>(_visitor: &mut V, _i: Expr) -> Expr { + match _i { + Expr::Box(_binding_0, ) => { + Expr::Box ( + full!(_visitor.fold_expr_box(_binding_0)), + ) + } + Expr::InPlace(_binding_0, ) => { + Expr::InPlace ( + full!(_visitor.fold_expr_in_place(_binding_0)), + ) + } + Expr::Array(_binding_0, ) => { + Expr::Array ( + full!(_visitor.fold_expr_array(_binding_0)), + ) + } + Expr::Call(_binding_0, ) => { + Expr::Call ( + _visitor.fold_expr_call(_binding_0), + ) + } + Expr::MethodCall(_binding_0, ) => { + Expr::MethodCall ( + full!(_visitor.fold_expr_method_call(_binding_0)), + ) + } + Expr::Tuple(_binding_0, ) => { + Expr::Tuple ( + full!(_visitor.fold_expr_tuple(_binding_0)), + ) + } + Expr::Binary(_binding_0, ) => { + Expr::Binary ( + _visitor.fold_expr_binary(_binding_0), + ) + } + Expr::Unary(_binding_0, ) => { + Expr::Unary ( + _visitor.fold_expr_unary(_binding_0), + ) + } + Expr::Lit(_binding_0, ) => { + Expr::Lit ( + _visitor.fold_expr_lit(_binding_0), + ) + } + Expr::Cast(_binding_0, ) => { + Expr::Cast ( + _visitor.fold_expr_cast(_binding_0), + ) + } + Expr::Type(_binding_0, ) => { + Expr::Type ( + full!(_visitor.fold_expr_type(_binding_0)), + ) + } + Expr::If(_binding_0, ) => { + Expr::If ( + full!(_visitor.fold_expr_if(_binding_0)), + ) + } + Expr::IfLet(_binding_0, ) => { + Expr::IfLet ( + full!(_visitor.fold_expr_if_let(_binding_0)), + ) + } + Expr::While(_binding_0, ) => { + Expr::While ( + full!(_visitor.fold_expr_while(_binding_0)), + ) + } + Expr::WhileLet(_binding_0, ) => { + Expr::WhileLet ( + full!(_visitor.fold_expr_while_let(_binding_0)), + ) + } + Expr::ForLoop(_binding_0, ) => { + Expr::ForLoop ( + full!(_visitor.fold_expr_for_loop(_binding_0)), + ) + } + Expr::Loop(_binding_0, ) => { + Expr::Loop ( + full!(_visitor.fold_expr_loop(_binding_0)), + ) + } + Expr::Match(_binding_0, ) => { + Expr::Match ( + full!(_visitor.fold_expr_match(_binding_0)), + ) + } + Expr::Closure(_binding_0, ) => { + Expr::Closure ( + full!(_visitor.fold_expr_closure(_binding_0)), + ) + } + Expr::Unsafe(_binding_0, ) => { + Expr::Unsafe ( + full!(_visitor.fold_expr_unsafe(_binding_0)), + ) + } + Expr::Block(_binding_0, ) => { + Expr::Block ( + full!(_visitor.fold_expr_block(_binding_0)), + ) + } + Expr::Assign(_binding_0, ) => { + Expr::Assign ( + full!(_visitor.fold_expr_assign(_binding_0)), + ) + } + Expr::AssignOp(_binding_0, ) => { + Expr::AssignOp ( + full!(_visitor.fold_expr_assign_op(_binding_0)), + ) + } + Expr::Field(_binding_0, ) => { + Expr::Field ( + full!(_visitor.fold_expr_field(_binding_0)), + ) + } + Expr::Index(_binding_0, ) => { + Expr::Index ( + _visitor.fold_expr_index(_binding_0), + ) + } + Expr::Range(_binding_0, ) => { + Expr::Range ( + full!(_visitor.fold_expr_range(_binding_0)), + ) + } + Expr::Path(_binding_0, ) => { + Expr::Path ( + _visitor.fold_expr_path(_binding_0), + ) + } + Expr::Reference(_binding_0, ) => { + Expr::Reference ( + full!(_visitor.fold_expr_reference(_binding_0)), + ) + } + Expr::Break(_binding_0, ) => { + Expr::Break ( + full!(_visitor.fold_expr_break(_binding_0)), + ) + } + Expr::Continue(_binding_0, ) => { + Expr::Continue ( + full!(_visitor.fold_expr_continue(_binding_0)), + ) + } + Expr::Return(_binding_0, ) => { + Expr::Return ( + full!(_visitor.fold_expr_return(_binding_0)), + ) + } + Expr::Macro(_binding_0, ) => { + Expr::Macro ( + full!(_visitor.fold_expr_macro(_binding_0)), + ) + } + Expr::Struct(_binding_0, ) => { + Expr::Struct ( + full!(_visitor.fold_expr_struct(_binding_0)), + ) + } + Expr::Repeat(_binding_0, ) => { + Expr::Repeat ( + full!(_visitor.fold_expr_repeat(_binding_0)), + ) + } + Expr::Paren(_binding_0, ) => { + Expr::Paren ( + _visitor.fold_expr_paren(_binding_0), + ) + } + Expr::Group(_binding_0, ) => { + Expr::Group ( + full!(_visitor.fold_expr_group(_binding_0)), + ) + } + Expr::Try(_binding_0, ) => { + Expr::Try ( + full!(_visitor.fold_expr_try(_binding_0)), + ) + } + Expr::Catch(_binding_0, ) => { + Expr::Catch ( + full!(_visitor.fold_expr_catch(_binding_0)), + ) + } + Expr::Yield(_binding_0, ) => { + Expr::Yield ( + full!(_visitor.fold_expr_yield(_binding_0)), + ) + } + Expr::Verbatim(_binding_0, ) => { + Expr::Verbatim ( + _visitor.fold_expr_verbatim(_binding_0), + ) + } + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_array<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprArray) -> ExprArray { + ExprArray { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + bracket_token: Bracket(tokens_helper(_visitor, &(_i . bracket_token).0)), + elems: FoldHelper::lift(_i . elems, |it| { _visitor.fold_expr(it) }), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_assign<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprAssign) -> ExprAssign { + ExprAssign { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + left: Box::new(_visitor.fold_expr(* _i . left)), + eq_token: Token ! [ = ](tokens_helper(_visitor, &(_i . eq_token).0)), + right: Box::new(_visitor.fold_expr(* _i . right)), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_assign_op<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprAssignOp) -> ExprAssignOp { + ExprAssignOp { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + left: Box::new(_visitor.fold_expr(* _i . left)), + op: _visitor.fold_bin_op(_i . op), + right: Box::new(_visitor.fold_expr(* _i . right)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_binary<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprBinary) -> ExprBinary { + ExprBinary { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + left: Box::new(_visitor.fold_expr(* _i . left)), + op: _visitor.fold_bin_op(_i . op), + right: Box::new(_visitor.fold_expr(* _i . right)), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_block<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprBlock) -> ExprBlock { + ExprBlock { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + block: _visitor.fold_block(_i . block), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_box<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprBox) -> ExprBox { + ExprBox { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + box_token: Token ! [ box ](tokens_helper(_visitor, &(_i . box_token).0)), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_break<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprBreak) -> ExprBreak { + ExprBreak { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + break_token: Token ! [ break ](tokens_helper(_visitor, &(_i . break_token).0)), + label: (_i . label).map(|it| { _visitor.fold_lifetime(it) }), + expr: (_i . expr).map(|it| { Box::new(_visitor.fold_expr(* it)) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_call<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprCall) -> ExprCall { + ExprCall { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + func: Box::new(_visitor.fold_expr(* _i . func)), + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + args: FoldHelper::lift(_i . args, |it| { _visitor.fold_expr(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_cast<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprCast) -> ExprCast { + ExprCast { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + as_token: Token ! [ as ](tokens_helper(_visitor, &(_i . as_token).0)), + ty: Box::new(_visitor.fold_type(* _i . ty)), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_catch<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprCatch) -> ExprCatch { + ExprCatch { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + do_token: Token ! [ do ](tokens_helper(_visitor, &(_i . do_token).0)), + catch_token: Token ! [ catch ](tokens_helper(_visitor, &(_i . catch_token).0)), + block: _visitor.fold_block(_i . block), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_closure<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprClosure) -> ExprClosure { + ExprClosure { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + movability: (_i . movability).map(|it| { Token ! [ static ](tokens_helper(_visitor, &(it).0)) }), + capture: (_i . capture).map(|it| { Token ! [ move ](tokens_helper(_visitor, &(it).0)) }), + or1_token: Token ! [ | ](tokens_helper(_visitor, &(_i . or1_token).0)), + inputs: FoldHelper::lift(_i . inputs, |it| { _visitor.fold_fn_arg(it) }), + or2_token: Token ! [ | ](tokens_helper(_visitor, &(_i . or2_token).0)), + output: _visitor.fold_return_type(_i . output), + body: Box::new(_visitor.fold_expr(* _i . body)), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_continue<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprContinue) -> ExprContinue { + ExprContinue { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + continue_token: Token ! [ continue ](tokens_helper(_visitor, &(_i . continue_token).0)), + label: (_i . label).map(|it| { _visitor.fold_lifetime(it) }), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_field<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprField) -> ExprField { + ExprField { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + base: Box::new(_visitor.fold_expr(* _i . base)), + dot_token: Token ! [ . ](tokens_helper(_visitor, &(_i . dot_token).0)), + member: _visitor.fold_member(_i . member), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_for_loop<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprForLoop) -> ExprForLoop { + ExprForLoop { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + label: (_i . label).map(|it| { _visitor.fold_label(it) }), + for_token: Token ! [ for ](tokens_helper(_visitor, &(_i . for_token).0)), + pat: Box::new(_visitor.fold_pat(* _i . pat)), + in_token: Token ! [ in ](tokens_helper(_visitor, &(_i . in_token).0)), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + body: _visitor.fold_block(_i . body), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_group<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprGroup) -> ExprGroup { + ExprGroup { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + group_token: Group(tokens_helper(_visitor, &(_i . group_token).0)), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_if<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprIf) -> ExprIf { + ExprIf { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + if_token: Token ! [ if ](tokens_helper(_visitor, &(_i . if_token).0)), + cond: Box::new(_visitor.fold_expr(* _i . cond)), + then_branch: _visitor.fold_block(_i . then_branch), + else_branch: (_i . else_branch).map(|it| { ( + Token ! [ else ](tokens_helper(_visitor, &(( it ) . 0).0)), + Box::new(_visitor.fold_expr(* ( it ) . 1)), + ) }), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_if_let<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprIfLet) -> ExprIfLet { + ExprIfLet { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + if_token: Token ! [ if ](tokens_helper(_visitor, &(_i . if_token).0)), + let_token: Token ! [ let ](tokens_helper(_visitor, &(_i . let_token).0)), + pats: FoldHelper::lift(_i . pats, |it| { _visitor.fold_pat(it) }), + eq_token: Token ! [ = ](tokens_helper(_visitor, &(_i . eq_token).0)), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + then_branch: _visitor.fold_block(_i . then_branch), + else_branch: (_i . else_branch).map(|it| { ( + Token ! [ else ](tokens_helper(_visitor, &(( it ) . 0).0)), + Box::new(_visitor.fold_expr(* ( it ) . 1)), + ) }), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_in_place<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprInPlace) -> ExprInPlace { + ExprInPlace { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + place: Box::new(_visitor.fold_expr(* _i . place)), + arrow_token: Token ! [ <- ](tokens_helper(_visitor, &(_i . arrow_token).0)), + value: Box::new(_visitor.fold_expr(* _i . value)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_index<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprIndex) -> ExprIndex { + ExprIndex { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + bracket_token: Bracket(tokens_helper(_visitor, &(_i . bracket_token).0)), + index: Box::new(_visitor.fold_expr(* _i . index)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_lit<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprLit) -> ExprLit { + ExprLit { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + lit: _visitor.fold_lit(_i . lit), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_loop<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprLoop) -> ExprLoop { + ExprLoop { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + label: (_i . label).map(|it| { _visitor.fold_label(it) }), + loop_token: Token ! [ loop ](tokens_helper(_visitor, &(_i . loop_token).0)), + body: _visitor.fold_block(_i . body), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_macro<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprMacro) -> ExprMacro { + ExprMacro { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + mac: _visitor.fold_macro(_i . mac), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_match<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprMatch) -> ExprMatch { + ExprMatch { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + match_token: Token ! [ match ](tokens_helper(_visitor, &(_i . match_token).0)), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + brace_token: Brace(tokens_helper(_visitor, &(_i . brace_token).0)), + arms: FoldHelper::lift(_i . arms, |it| { _visitor.fold_arm(it) }), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_method_call<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprMethodCall) -> ExprMethodCall { + ExprMethodCall { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + receiver: Box::new(_visitor.fold_expr(* _i . receiver)), + dot_token: Token ! [ . ](tokens_helper(_visitor, &(_i . dot_token).0)), + method: _visitor.fold_ident(_i . method), + turbofish: (_i . turbofish).map(|it| { _visitor.fold_method_turbofish(it) }), + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + args: FoldHelper::lift(_i . args, |it| { _visitor.fold_expr(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_paren<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprParen) -> ExprParen { + ExprParen { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_path<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprPath) -> ExprPath { + ExprPath { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + qself: (_i . qself).map(|it| { _visitor.fold_qself(it) }), + path: _visitor.fold_path(_i . path), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_range<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprRange) -> ExprRange { + ExprRange { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + from: (_i . from).map(|it| { Box::new(_visitor.fold_expr(* it)) }), + limits: _visitor.fold_range_limits(_i . limits), + to: (_i . to).map(|it| { Box::new(_visitor.fold_expr(* it)) }), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_reference<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprReference) -> ExprReference { + ExprReference { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + and_token: Token ! [ & ](tokens_helper(_visitor, &(_i . and_token).0)), + mutability: (_i . mutability).map(|it| { Token ! [ mut ](tokens_helper(_visitor, &(it).0)) }), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_repeat<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprRepeat) -> ExprRepeat { + ExprRepeat { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + bracket_token: Bracket(tokens_helper(_visitor, &(_i . bracket_token).0)), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + len: Box::new(_visitor.fold_expr(* _i . len)), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_return<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprReturn) -> ExprReturn { + ExprReturn { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + return_token: Token ! [ return ](tokens_helper(_visitor, &(_i . return_token).0)), + expr: (_i . expr).map(|it| { Box::new(_visitor.fold_expr(* it)) }), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_struct<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprStruct) -> ExprStruct { + ExprStruct { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + path: _visitor.fold_path(_i . path), + brace_token: Brace(tokens_helper(_visitor, &(_i . brace_token).0)), + fields: FoldHelper::lift(_i . fields, |it| { _visitor.fold_field_value(it) }), + dot2_token: (_i . dot2_token).map(|it| { Token ! [ .. ](tokens_helper(_visitor, &(it).0)) }), + rest: (_i . rest).map(|it| { Box::new(_visitor.fold_expr(* it)) }), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_try<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprTry) -> ExprTry { + ExprTry { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + question_token: Token ! [ ? ](tokens_helper(_visitor, &(_i . question_token).0)), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_tuple<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprTuple) -> ExprTuple { + ExprTuple { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + elems: FoldHelper::lift(_i . elems, |it| { _visitor.fold_expr(it) }), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_type<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprType) -> ExprType { + ExprType { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + colon_token: Token ! [ : ](tokens_helper(_visitor, &(_i . colon_token).0)), + ty: Box::new(_visitor.fold_type(* _i . ty)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_unary<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprUnary) -> ExprUnary { + ExprUnary { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + op: _visitor.fold_un_op(_i . op), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_unsafe<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprUnsafe) -> ExprUnsafe { + ExprUnsafe { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + unsafe_token: Token ! [ unsafe ](tokens_helper(_visitor, &(_i . unsafe_token).0)), + block: _visitor.fold_block(_i . block), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprVerbatim) -> ExprVerbatim { + ExprVerbatim { + tts: _i . tts, + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_while<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprWhile) -> ExprWhile { + ExprWhile { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + label: (_i . label).map(|it| { _visitor.fold_label(it) }), + while_token: Token ! [ while ](tokens_helper(_visitor, &(_i . while_token).0)), + cond: Box::new(_visitor.fold_expr(* _i . cond)), + body: _visitor.fold_block(_i . body), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_while_let<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprWhileLet) -> ExprWhileLet { + ExprWhileLet { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + label: (_i . label).map(|it| { _visitor.fold_label(it) }), + while_token: Token ! [ while ](tokens_helper(_visitor, &(_i . while_token).0)), + let_token: Token ! [ let ](tokens_helper(_visitor, &(_i . let_token).0)), + pats: FoldHelper::lift(_i . pats, |it| { _visitor.fold_pat(it) }), + eq_token: Token ! [ = ](tokens_helper(_visitor, &(_i . eq_token).0)), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + body: _visitor.fold_block(_i . body), + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_expr_yield<V: Fold + ?Sized>(_visitor: &mut V, _i: ExprYield) -> ExprYield { + ExprYield { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + yield_token: Token ! [ yield ](tokens_helper(_visitor, &(_i . yield_token).0)), + expr: (_i . expr).map(|it| { Box::new(_visitor.fold_expr(* it)) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_field<V: Fold + ?Sized>(_visitor: &mut V, _i: Field) -> Field { + Field { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + ident: (_i . ident).map(|it| { _visitor.fold_ident(it) }), + colon_token: (_i . colon_token).map(|it| { Token ! [ : ](tokens_helper(_visitor, &(it).0)) }), + ty: _visitor.fold_type(_i . ty), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_field_pat<V: Fold + ?Sized>(_visitor: &mut V, _i: FieldPat) -> FieldPat { + FieldPat { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + member: _visitor.fold_member(_i . member), + colon_token: (_i . colon_token).map(|it| { Token ! [ : ](tokens_helper(_visitor, &(it).0)) }), + pat: Box::new(_visitor.fold_pat(* _i . pat)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_field_value<V: Fold + ?Sized>(_visitor: &mut V, _i: FieldValue) -> FieldValue { + FieldValue { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + member: _visitor.fold_member(_i . member), + colon_token: (_i . colon_token).map(|it| { Token ! [ : ](tokens_helper(_visitor, &(it).0)) }), + expr: _visitor.fold_expr(_i . expr), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_fields<V: Fold + ?Sized>(_visitor: &mut V, _i: Fields) -> Fields { + match _i { + Fields::Named(_binding_0, ) => { + Fields::Named ( + _visitor.fold_fields_named(_binding_0), + ) + } + Fields::Unnamed(_binding_0, ) => { + Fields::Unnamed ( + _visitor.fold_fields_unnamed(_binding_0), + ) + } + Fields::Unit => { Fields::Unit } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_fields_named<V: Fold + ?Sized>(_visitor: &mut V, _i: FieldsNamed) -> FieldsNamed { + FieldsNamed { + brace_token: Brace(tokens_helper(_visitor, &(_i . brace_token).0)), + named: FoldHelper::lift(_i . named, |it| { _visitor.fold_field(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_fields_unnamed<V: Fold + ?Sized>(_visitor: &mut V, _i: FieldsUnnamed) -> FieldsUnnamed { + FieldsUnnamed { + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + unnamed: FoldHelper::lift(_i . unnamed, |it| { _visitor.fold_field(it) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_file<V: Fold + ?Sized>(_visitor: &mut V, _i: File) -> File { + File { + shebang: _i . shebang, + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + items: FoldHelper::lift(_i . items, |it| { _visitor.fold_item(it) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_fn_arg<V: Fold + ?Sized>(_visitor: &mut V, _i: FnArg) -> FnArg { + match _i { + FnArg::SelfRef(_binding_0, ) => { + FnArg::SelfRef ( + _visitor.fold_arg_self_ref(_binding_0), + ) + } + FnArg::SelfValue(_binding_0, ) => { + FnArg::SelfValue ( + _visitor.fold_arg_self(_binding_0), + ) + } + FnArg::Captured(_binding_0, ) => { + FnArg::Captured ( + _visitor.fold_arg_captured(_binding_0), + ) + } + FnArg::Inferred(_binding_0, ) => { + FnArg::Inferred ( + _visitor.fold_pat(_binding_0), + ) + } + FnArg::Ignored(_binding_0, ) => { + FnArg::Ignored ( + _visitor.fold_type(_binding_0), + ) + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_fn_decl<V: Fold + ?Sized>(_visitor: &mut V, _i: FnDecl) -> FnDecl { + FnDecl { + fn_token: Token ! [ fn ](tokens_helper(_visitor, &(_i . fn_token).0)), + generics: _visitor.fold_generics(_i . generics), + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + inputs: FoldHelper::lift(_i . inputs, |it| { _visitor.fold_fn_arg(it) }), + variadic: (_i . variadic).map(|it| { Token ! [ ... ](tokens_helper(_visitor, &(it).0)) }), + output: _visitor.fold_return_type(_i . output), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_foreign_item<V: Fold + ?Sized>(_visitor: &mut V, _i: ForeignItem) -> ForeignItem { + match _i { + ForeignItem::Fn(_binding_0, ) => { + ForeignItem::Fn ( + _visitor.fold_foreign_item_fn(_binding_0), + ) + } + ForeignItem::Static(_binding_0, ) => { + ForeignItem::Static ( + _visitor.fold_foreign_item_static(_binding_0), + ) + } + ForeignItem::Type(_binding_0, ) => { + ForeignItem::Type ( + _visitor.fold_foreign_item_type(_binding_0), + ) + } + ForeignItem::Verbatim(_binding_0, ) => { + ForeignItem::Verbatim ( + _visitor.fold_foreign_item_verbatim(_binding_0), + ) + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_foreign_item_fn<V: Fold + ?Sized>(_visitor: &mut V, _i: ForeignItemFn) -> ForeignItemFn { + ForeignItemFn { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + ident: _visitor.fold_ident(_i . ident), + decl: Box::new(_visitor.fold_fn_decl(* _i . decl)), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_foreign_item_static<V: Fold + ?Sized>(_visitor: &mut V, _i: ForeignItemStatic) -> ForeignItemStatic { + ForeignItemStatic { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + static_token: Token ! [ static ](tokens_helper(_visitor, &(_i . static_token).0)), + mutability: (_i . mutability).map(|it| { Token ! [ mut ](tokens_helper(_visitor, &(it).0)) }), + ident: _visitor.fold_ident(_i . ident), + colon_token: Token ! [ : ](tokens_helper(_visitor, &(_i . colon_token).0)), + ty: Box::new(_visitor.fold_type(* _i . ty)), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_foreign_item_type<V: Fold + ?Sized>(_visitor: &mut V, _i: ForeignItemType) -> ForeignItemType { + ForeignItemType { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + type_token: Token ! [ type ](tokens_helper(_visitor, &(_i . type_token).0)), + ident: _visitor.fold_ident(_i . ident), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_foreign_item_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: ForeignItemVerbatim) -> ForeignItemVerbatim { + ForeignItemVerbatim { + tts: _i . tts, + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_generic_argument<V: Fold + ?Sized>(_visitor: &mut V, _i: GenericArgument) -> GenericArgument { + match _i { + GenericArgument::Lifetime(_binding_0, ) => { + GenericArgument::Lifetime ( + _visitor.fold_lifetime(_binding_0), + ) + } + GenericArgument::Type(_binding_0, ) => { + GenericArgument::Type ( + _visitor.fold_type(_binding_0), + ) + } + GenericArgument::Binding(_binding_0, ) => { + GenericArgument::Binding ( + _visitor.fold_binding(_binding_0), + ) + } + GenericArgument::Const(_binding_0, ) => { + GenericArgument::Const ( + _visitor.fold_expr(_binding_0), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_generic_method_argument<V: Fold + ?Sized>(_visitor: &mut V, _i: GenericMethodArgument) -> GenericMethodArgument { + match _i { + GenericMethodArgument::Type(_binding_0, ) => { + GenericMethodArgument::Type ( + _visitor.fold_type(_binding_0), + ) + } + GenericMethodArgument::Const(_binding_0, ) => { + GenericMethodArgument::Const ( + _visitor.fold_expr(_binding_0), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_generic_param<V: Fold + ?Sized>(_visitor: &mut V, _i: GenericParam) -> GenericParam { + match _i { + GenericParam::Type(_binding_0, ) => { + GenericParam::Type ( + _visitor.fold_type_param(_binding_0), + ) + } + GenericParam::Lifetime(_binding_0, ) => { + GenericParam::Lifetime ( + _visitor.fold_lifetime_def(_binding_0), + ) + } + GenericParam::Const(_binding_0, ) => { + GenericParam::Const ( + _visitor.fold_const_param(_binding_0), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_generics<V: Fold + ?Sized>(_visitor: &mut V, _i: Generics) -> Generics { + Generics { + lt_token: (_i . lt_token).map(|it| { Token ! [ < ](tokens_helper(_visitor, &(it).0)) }), + params: FoldHelper::lift(_i . params, |it| { _visitor.fold_generic_param(it) }), + gt_token: (_i . gt_token).map(|it| { Token ! [ > ](tokens_helper(_visitor, &(it).0)) }), + where_clause: (_i . where_clause).map(|it| { _visitor.fold_where_clause(it) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_impl_item<V: Fold + ?Sized>(_visitor: &mut V, _i: ImplItem) -> ImplItem { + match _i { + ImplItem::Const(_binding_0, ) => { + ImplItem::Const ( + _visitor.fold_impl_item_const(_binding_0), + ) + } + ImplItem::Method(_binding_0, ) => { + ImplItem::Method ( + _visitor.fold_impl_item_method(_binding_0), + ) + } + ImplItem::Type(_binding_0, ) => { + ImplItem::Type ( + _visitor.fold_impl_item_type(_binding_0), + ) + } + ImplItem::Macro(_binding_0, ) => { + ImplItem::Macro ( + _visitor.fold_impl_item_macro(_binding_0), + ) + } + ImplItem::Verbatim(_binding_0, ) => { + ImplItem::Verbatim ( + _visitor.fold_impl_item_verbatim(_binding_0), + ) + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_impl_item_const<V: Fold + ?Sized>(_visitor: &mut V, _i: ImplItemConst) -> ImplItemConst { + ImplItemConst { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + defaultness: (_i . defaultness).map(|it| { Token ! [ default ](tokens_helper(_visitor, &(it).0)) }), + const_token: Token ! [ const ](tokens_helper(_visitor, &(_i . const_token).0)), + ident: _visitor.fold_ident(_i . ident), + colon_token: Token ! [ : ](tokens_helper(_visitor, &(_i . colon_token).0)), + ty: _visitor.fold_type(_i . ty), + eq_token: Token ! [ = ](tokens_helper(_visitor, &(_i . eq_token).0)), + expr: _visitor.fold_expr(_i . expr), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_impl_item_macro<V: Fold + ?Sized>(_visitor: &mut V, _i: ImplItemMacro) -> ImplItemMacro { + ImplItemMacro { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + mac: _visitor.fold_macro(_i . mac), + semi_token: (_i . semi_token).map(|it| { Token ! [ ; ](tokens_helper(_visitor, &(it).0)) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_impl_item_method<V: Fold + ?Sized>(_visitor: &mut V, _i: ImplItemMethod) -> ImplItemMethod { + ImplItemMethod { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + defaultness: (_i . defaultness).map(|it| { Token ! [ default ](tokens_helper(_visitor, &(it).0)) }), + sig: _visitor.fold_method_sig(_i . sig), + block: _visitor.fold_block(_i . block), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_impl_item_type<V: Fold + ?Sized>(_visitor: &mut V, _i: ImplItemType) -> ImplItemType { + ImplItemType { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + defaultness: (_i . defaultness).map(|it| { Token ! [ default ](tokens_helper(_visitor, &(it).0)) }), + type_token: Token ! [ type ](tokens_helper(_visitor, &(_i . type_token).0)), + ident: _visitor.fold_ident(_i . ident), + generics: _visitor.fold_generics(_i . generics), + eq_token: Token ! [ = ](tokens_helper(_visitor, &(_i . eq_token).0)), + ty: _visitor.fold_type(_i . ty), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_impl_item_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: ImplItemVerbatim) -> ImplItemVerbatim { + ImplItemVerbatim { + tts: _i . tts, + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_index<V: Fold + ?Sized>(_visitor: &mut V, _i: Index) -> Index { + Index { + index: _i . index, + span: _visitor.fold_span(_i . span), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item<V: Fold + ?Sized>(_visitor: &mut V, _i: Item) -> Item { + match _i { + Item::ExternCrate(_binding_0, ) => { + Item::ExternCrate ( + _visitor.fold_item_extern_crate(_binding_0), + ) + } + Item::Use(_binding_0, ) => { + Item::Use ( + _visitor.fold_item_use(_binding_0), + ) + } + Item::Static(_binding_0, ) => { + Item::Static ( + _visitor.fold_item_static(_binding_0), + ) + } + Item::Const(_binding_0, ) => { + Item::Const ( + _visitor.fold_item_const(_binding_0), + ) + } + Item::Fn(_binding_0, ) => { + Item::Fn ( + _visitor.fold_item_fn(_binding_0), + ) + } + Item::Mod(_binding_0, ) => { + Item::Mod ( + _visitor.fold_item_mod(_binding_0), + ) + } + Item::ForeignMod(_binding_0, ) => { + Item::ForeignMod ( + _visitor.fold_item_foreign_mod(_binding_0), + ) + } + Item::Type(_binding_0, ) => { + Item::Type ( + _visitor.fold_item_type(_binding_0), + ) + } + Item::Struct(_binding_0, ) => { + Item::Struct ( + _visitor.fold_item_struct(_binding_0), + ) + } + Item::Enum(_binding_0, ) => { + Item::Enum ( + _visitor.fold_item_enum(_binding_0), + ) + } + Item::Union(_binding_0, ) => { + Item::Union ( + _visitor.fold_item_union(_binding_0), + ) + } + Item::Trait(_binding_0, ) => { + Item::Trait ( + _visitor.fold_item_trait(_binding_0), + ) + } + Item::Impl(_binding_0, ) => { + Item::Impl ( + _visitor.fold_item_impl(_binding_0), + ) + } + Item::Macro(_binding_0, ) => { + Item::Macro ( + _visitor.fold_item_macro(_binding_0), + ) + } + Item::Macro2(_binding_0, ) => { + Item::Macro2 ( + _visitor.fold_item_macro2(_binding_0), + ) + } + Item::Verbatim(_binding_0, ) => { + Item::Verbatim ( + _visitor.fold_item_verbatim(_binding_0), + ) + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_const<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemConst) -> ItemConst { + ItemConst { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + const_token: Token ! [ const ](tokens_helper(_visitor, &(_i . const_token).0)), + ident: _visitor.fold_ident(_i . ident), + colon_token: Token ! [ : ](tokens_helper(_visitor, &(_i . colon_token).0)), + ty: Box::new(_visitor.fold_type(* _i . ty)), + eq_token: Token ! [ = ](tokens_helper(_visitor, &(_i . eq_token).0)), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_enum<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemEnum) -> ItemEnum { + ItemEnum { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + enum_token: Token ! [ enum ](tokens_helper(_visitor, &(_i . enum_token).0)), + ident: _visitor.fold_ident(_i . ident), + generics: _visitor.fold_generics(_i . generics), + brace_token: Brace(tokens_helper(_visitor, &(_i . brace_token).0)), + variants: FoldHelper::lift(_i . variants, |it| { _visitor.fold_variant(it) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_extern_crate<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemExternCrate) -> ItemExternCrate { + ItemExternCrate { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + extern_token: Token ! [ extern ](tokens_helper(_visitor, &(_i . extern_token).0)), + crate_token: Token ! [ crate ](tokens_helper(_visitor, &(_i . crate_token).0)), + ident: _visitor.fold_ident(_i . ident), + rename: (_i . rename).map(|it| { ( + Token ! [ as ](tokens_helper(_visitor, &(( it ) . 0).0)), + _visitor.fold_ident(( it ) . 1), + ) }), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_fn<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemFn) -> ItemFn { + ItemFn { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + constness: (_i . constness).map(|it| { Token ! [ const ](tokens_helper(_visitor, &(it).0)) }), + unsafety: (_i . unsafety).map(|it| { Token ! [ unsafe ](tokens_helper(_visitor, &(it).0)) }), + abi: (_i . abi).map(|it| { _visitor.fold_abi(it) }), + ident: _visitor.fold_ident(_i . ident), + decl: Box::new(_visitor.fold_fn_decl(* _i . decl)), + block: Box::new(_visitor.fold_block(* _i . block)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_foreign_mod<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemForeignMod) -> ItemForeignMod { + ItemForeignMod { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + abi: _visitor.fold_abi(_i . abi), + brace_token: Brace(tokens_helper(_visitor, &(_i . brace_token).0)), + items: FoldHelper::lift(_i . items, |it| { _visitor.fold_foreign_item(it) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_impl<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemImpl) -> ItemImpl { + ItemImpl { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + defaultness: (_i . defaultness).map(|it| { Token ! [ default ](tokens_helper(_visitor, &(it).0)) }), + unsafety: (_i . unsafety).map(|it| { Token ! [ unsafe ](tokens_helper(_visitor, &(it).0)) }), + impl_token: Token ! [ impl ](tokens_helper(_visitor, &(_i . impl_token).0)), + generics: _visitor.fold_generics(_i . generics), + trait_: (_i . trait_).map(|it| { ( + (( it ) . 0).map(|it| { Token ! [ ! ](tokens_helper(_visitor, &(it).0)) }), + _visitor.fold_path(( it ) . 1), + Token ! [ for ](tokens_helper(_visitor, &(( it ) . 2).0)), + ) }), + self_ty: Box::new(_visitor.fold_type(* _i . self_ty)), + brace_token: Brace(tokens_helper(_visitor, &(_i . brace_token).0)), + items: FoldHelper::lift(_i . items, |it| { _visitor.fold_impl_item(it) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_macro<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemMacro) -> ItemMacro { + ItemMacro { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + ident: (_i . ident).map(|it| { _visitor.fold_ident(it) }), + mac: _visitor.fold_macro(_i . mac), + semi_token: (_i . semi_token).map(|it| { Token ! [ ; ](tokens_helper(_visitor, &(it).0)) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_macro2<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemMacro2) -> ItemMacro2 { + ItemMacro2 { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + macro_token: Token ! [ macro ](tokens_helper(_visitor, &(_i . macro_token).0)), + ident: _visitor.fold_ident(_i . ident), + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + args: _i . args, + brace_token: Brace(tokens_helper(_visitor, &(_i . brace_token).0)), + body: _i . body, + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_mod<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemMod) -> ItemMod { + ItemMod { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + mod_token: Token ! [ mod ](tokens_helper(_visitor, &(_i . mod_token).0)), + ident: _visitor.fold_ident(_i . ident), + content: (_i . content).map(|it| { ( + Brace(tokens_helper(_visitor, &(( it ) . 0).0)), + FoldHelper::lift(( it ) . 1, |it| { _visitor.fold_item(it) }), + ) }), + semi: (_i . semi).map(|it| { Token ! [ ; ](tokens_helper(_visitor, &(it).0)) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_static<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemStatic) -> ItemStatic { + ItemStatic { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + static_token: Token ! [ static ](tokens_helper(_visitor, &(_i . static_token).0)), + mutability: (_i . mutability).map(|it| { Token ! [ mut ](tokens_helper(_visitor, &(it).0)) }), + ident: _visitor.fold_ident(_i . ident), + colon_token: Token ! [ : ](tokens_helper(_visitor, &(_i . colon_token).0)), + ty: Box::new(_visitor.fold_type(* _i . ty)), + eq_token: Token ! [ = ](tokens_helper(_visitor, &(_i . eq_token).0)), + expr: Box::new(_visitor.fold_expr(* _i . expr)), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_struct<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemStruct) -> ItemStruct { + ItemStruct { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + struct_token: Token ! [ struct ](tokens_helper(_visitor, &(_i . struct_token).0)), + ident: _visitor.fold_ident(_i . ident), + generics: _visitor.fold_generics(_i . generics), + fields: _visitor.fold_fields(_i . fields), + semi_token: (_i . semi_token).map(|it| { Token ! [ ; ](tokens_helper(_visitor, &(it).0)) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_trait<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemTrait) -> ItemTrait { + ItemTrait { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + unsafety: (_i . unsafety).map(|it| { Token ! [ unsafe ](tokens_helper(_visitor, &(it).0)) }), + auto_token: (_i . auto_token).map(|it| { Token ! [ auto ](tokens_helper(_visitor, &(it).0)) }), + trait_token: Token ! [ trait ](tokens_helper(_visitor, &(_i . trait_token).0)), + ident: _visitor.fold_ident(_i . ident), + generics: _visitor.fold_generics(_i . generics), + colon_token: (_i . colon_token).map(|it| { Token ! [ : ](tokens_helper(_visitor, &(it).0)) }), + supertraits: FoldHelper::lift(_i . supertraits, |it| { _visitor.fold_type_param_bound(it) }), + brace_token: Brace(tokens_helper(_visitor, &(_i . brace_token).0)), + items: FoldHelper::lift(_i . items, |it| { _visitor.fold_trait_item(it) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_type<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemType) -> ItemType { + ItemType { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + type_token: Token ! [ type ](tokens_helper(_visitor, &(_i . type_token).0)), + ident: _visitor.fold_ident(_i . ident), + generics: _visitor.fold_generics(_i . generics), + eq_token: Token ! [ = ](tokens_helper(_visitor, &(_i . eq_token).0)), + ty: Box::new(_visitor.fold_type(* _i . ty)), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_union<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemUnion) -> ItemUnion { + ItemUnion { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + union_token: Token ! [ union ](tokens_helper(_visitor, &(_i . union_token).0)), + ident: _visitor.fold_ident(_i . ident), + generics: _visitor.fold_generics(_i . generics), + fields: _visitor.fold_fields_named(_i . fields), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_use<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemUse) -> ItemUse { + ItemUse { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + vis: _visitor.fold_visibility(_i . vis), + use_token: Token ! [ use ](tokens_helper(_visitor, &(_i . use_token).0)), + leading_colon: (_i . leading_colon).map(|it| { Token ! [ :: ](tokens_helper(_visitor, &(it).0)) }), + tree: _visitor.fold_use_tree(_i . tree), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_item_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: ItemVerbatim) -> ItemVerbatim { + ItemVerbatim { + tts: _i . tts, + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_label<V: Fold + ?Sized>(_visitor: &mut V, _i: Label) -> Label { + Label { + name: _visitor.fold_lifetime(_i . name), + colon_token: Token ! [ : ](tokens_helper(_visitor, &(_i . colon_token).0)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_lifetime_def<V: Fold + ?Sized>(_visitor: &mut V, _i: LifetimeDef) -> LifetimeDef { + LifetimeDef { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + lifetime: _visitor.fold_lifetime(_i . lifetime), + colon_token: (_i . colon_token).map(|it| { Token ! [ : ](tokens_helper(_visitor, &(it).0)) }), + bounds: FoldHelper::lift(_i . bounds, |it| { _visitor.fold_lifetime(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_lit<V: Fold + ?Sized>(_visitor: &mut V, _i: Lit) -> Lit { + match _i { + Lit::Str(_binding_0, ) => { + Lit::Str ( + _visitor.fold_lit_str(_binding_0), + ) + } + Lit::ByteStr(_binding_0, ) => { + Lit::ByteStr ( + _visitor.fold_lit_byte_str(_binding_0), + ) + } + Lit::Byte(_binding_0, ) => { + Lit::Byte ( + _visitor.fold_lit_byte(_binding_0), + ) + } + Lit::Char(_binding_0, ) => { + Lit::Char ( + _visitor.fold_lit_char(_binding_0), + ) + } + Lit::Int(_binding_0, ) => { + Lit::Int ( + _visitor.fold_lit_int(_binding_0), + ) + } + Lit::Float(_binding_0, ) => { + Lit::Float ( + _visitor.fold_lit_float(_binding_0), + ) + } + Lit::Bool(_binding_0, ) => { + Lit::Bool ( + _visitor.fold_lit_bool(_binding_0), + ) + } + Lit::Verbatim(_binding_0, ) => { + Lit::Verbatim ( + _visitor.fold_lit_verbatim(_binding_0), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_lit_bool<V: Fold + ?Sized>(_visitor: &mut V, _i: LitBool) -> LitBool { + LitBool { + value: _i . value, + span: _visitor.fold_span(_i . span), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_lit_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: LitVerbatim) -> LitVerbatim { + LitVerbatim { + token: _i . token, + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_local<V: Fold + ?Sized>(_visitor: &mut V, _i: Local) -> Local { + Local { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + let_token: Token ! [ let ](tokens_helper(_visitor, &(_i . let_token).0)), + pats: FoldHelper::lift(_i . pats, |it| { _visitor.fold_pat(it) }), + ty: (_i . ty).map(|it| { ( + Token ! [ : ](tokens_helper(_visitor, &(( it ) . 0).0)), + Box::new(_visitor.fold_type(* ( it ) . 1)), + ) }), + init: (_i . init).map(|it| { ( + Token ! [ = ](tokens_helper(_visitor, &(( it ) . 0).0)), + Box::new(_visitor.fold_expr(* ( it ) . 1)), + ) }), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_macro<V: Fold + ?Sized>(_visitor: &mut V, _i: Macro) -> Macro { + Macro { + path: _visitor.fold_path(_i . path), + bang_token: Token ! [ ! ](tokens_helper(_visitor, &(_i . bang_token).0)), + delimiter: _visitor.fold_macro_delimiter(_i . delimiter), + tts: _i . tts, + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_macro_delimiter<V: Fold + ?Sized>(_visitor: &mut V, _i: MacroDelimiter) -> MacroDelimiter { + match _i { + MacroDelimiter::Paren(_binding_0, ) => { + MacroDelimiter::Paren ( + Paren(tokens_helper(_visitor, &(_binding_0).0)), + ) + } + MacroDelimiter::Brace(_binding_0, ) => { + MacroDelimiter::Brace ( + Brace(tokens_helper(_visitor, &(_binding_0).0)), + ) + } + MacroDelimiter::Bracket(_binding_0, ) => { + MacroDelimiter::Bracket ( + Bracket(tokens_helper(_visitor, &(_binding_0).0)), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_member<V: Fold + ?Sized>(_visitor: &mut V, _i: Member) -> Member { + match _i { + Member::Named(_binding_0, ) => { + Member::Named ( + _visitor.fold_ident(_binding_0), + ) + } + Member::Unnamed(_binding_0, ) => { + Member::Unnamed ( + _visitor.fold_index(_binding_0), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_meta<V: Fold + ?Sized>(_visitor: &mut V, _i: Meta) -> Meta { + match _i { + Meta::Word(_binding_0, ) => { + Meta::Word ( + _visitor.fold_ident(_binding_0), + ) + } + Meta::List(_binding_0, ) => { + Meta::List ( + _visitor.fold_meta_list(_binding_0), + ) + } + Meta::NameValue(_binding_0, ) => { + Meta::NameValue ( + _visitor.fold_meta_name_value(_binding_0), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_meta_list<V: Fold + ?Sized>(_visitor: &mut V, _i: MetaList) -> MetaList { + MetaList { + ident: _visitor.fold_ident(_i . ident), + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + nested: FoldHelper::lift(_i . nested, |it| { _visitor.fold_nested_meta(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_meta_name_value<V: Fold + ?Sized>(_visitor: &mut V, _i: MetaNameValue) -> MetaNameValue { + MetaNameValue { + ident: _visitor.fold_ident(_i . ident), + eq_token: Token ! [ = ](tokens_helper(_visitor, &(_i . eq_token).0)), + lit: _visitor.fold_lit(_i . lit), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_method_sig<V: Fold + ?Sized>(_visitor: &mut V, _i: MethodSig) -> MethodSig { + MethodSig { + constness: (_i . constness).map(|it| { Token ! [ const ](tokens_helper(_visitor, &(it).0)) }), + unsafety: (_i . unsafety).map(|it| { Token ! [ unsafe ](tokens_helper(_visitor, &(it).0)) }), + abi: (_i . abi).map(|it| { _visitor.fold_abi(it) }), + ident: _visitor.fold_ident(_i . ident), + decl: _visitor.fold_fn_decl(_i . decl), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_method_turbofish<V: Fold + ?Sized>(_visitor: &mut V, _i: MethodTurbofish) -> MethodTurbofish { + MethodTurbofish { + colon2_token: Token ! [ :: ](tokens_helper(_visitor, &(_i . colon2_token).0)), + lt_token: Token ! [ < ](tokens_helper(_visitor, &(_i . lt_token).0)), + args: FoldHelper::lift(_i . args, |it| { _visitor.fold_generic_method_argument(it) }), + gt_token: Token ! [ > ](tokens_helper(_visitor, &(_i . gt_token).0)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_nested_meta<V: Fold + ?Sized>(_visitor: &mut V, _i: NestedMeta) -> NestedMeta { + match _i { + NestedMeta::Meta(_binding_0, ) => { + NestedMeta::Meta ( + _visitor.fold_meta(_binding_0), + ) + } + NestedMeta::Literal(_binding_0, ) => { + NestedMeta::Literal ( + _visitor.fold_lit(_binding_0), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_parenthesized_generic_arguments<V: Fold + ?Sized>(_visitor: &mut V, _i: ParenthesizedGenericArguments) -> ParenthesizedGenericArguments { + ParenthesizedGenericArguments { + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + inputs: FoldHelper::lift(_i . inputs, |it| { _visitor.fold_type(it) }), + output: _visitor.fold_return_type(_i . output), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat<V: Fold + ?Sized>(_visitor: &mut V, _i: Pat) -> Pat { + match _i { + Pat::Wild(_binding_0, ) => { + Pat::Wild ( + _visitor.fold_pat_wild(_binding_0), + ) + } + Pat::Ident(_binding_0, ) => { + Pat::Ident ( + _visitor.fold_pat_ident(_binding_0), + ) + } + Pat::Struct(_binding_0, ) => { + Pat::Struct ( + _visitor.fold_pat_struct(_binding_0), + ) + } + Pat::TupleStruct(_binding_0, ) => { + Pat::TupleStruct ( + _visitor.fold_pat_tuple_struct(_binding_0), + ) + } + Pat::Path(_binding_0, ) => { + Pat::Path ( + _visitor.fold_pat_path(_binding_0), + ) + } + Pat::Tuple(_binding_0, ) => { + Pat::Tuple ( + _visitor.fold_pat_tuple(_binding_0), + ) + } + Pat::Box(_binding_0, ) => { + Pat::Box ( + _visitor.fold_pat_box(_binding_0), + ) + } + Pat::Ref(_binding_0, ) => { + Pat::Ref ( + _visitor.fold_pat_ref(_binding_0), + ) + } + Pat::Lit(_binding_0, ) => { + Pat::Lit ( + _visitor.fold_pat_lit(_binding_0), + ) + } + Pat::Range(_binding_0, ) => { + Pat::Range ( + _visitor.fold_pat_range(_binding_0), + ) + } + Pat::Slice(_binding_0, ) => { + Pat::Slice ( + _visitor.fold_pat_slice(_binding_0), + ) + } + Pat::Macro(_binding_0, ) => { + Pat::Macro ( + _visitor.fold_pat_macro(_binding_0), + ) + } + Pat::Verbatim(_binding_0, ) => { + Pat::Verbatim ( + _visitor.fold_pat_verbatim(_binding_0), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_box<V: Fold + ?Sized>(_visitor: &mut V, _i: PatBox) -> PatBox { + PatBox { + box_token: Token ! [ box ](tokens_helper(_visitor, &(_i . box_token).0)), + pat: Box::new(_visitor.fold_pat(* _i . pat)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_ident<V: Fold + ?Sized>(_visitor: &mut V, _i: PatIdent) -> PatIdent { + PatIdent { + by_ref: (_i . by_ref).map(|it| { Token ! [ ref ](tokens_helper(_visitor, &(it).0)) }), + mutability: (_i . mutability).map(|it| { Token ! [ mut ](tokens_helper(_visitor, &(it).0)) }), + ident: _visitor.fold_ident(_i . ident), + subpat: (_i . subpat).map(|it| { ( + Token ! [ @ ](tokens_helper(_visitor, &(( it ) . 0).0)), + Box::new(_visitor.fold_pat(* ( it ) . 1)), + ) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_lit<V: Fold + ?Sized>(_visitor: &mut V, _i: PatLit) -> PatLit { + PatLit { + expr: Box::new(_visitor.fold_expr(* _i . expr)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_macro<V: Fold + ?Sized>(_visitor: &mut V, _i: PatMacro) -> PatMacro { + PatMacro { + mac: _visitor.fold_macro(_i . mac), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_path<V: Fold + ?Sized>(_visitor: &mut V, _i: PatPath) -> PatPath { + PatPath { + qself: (_i . qself).map(|it| { _visitor.fold_qself(it) }), + path: _visitor.fold_path(_i . path), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_range<V: Fold + ?Sized>(_visitor: &mut V, _i: PatRange) -> PatRange { + PatRange { + lo: Box::new(_visitor.fold_expr(* _i . lo)), + limits: _visitor.fold_range_limits(_i . limits), + hi: Box::new(_visitor.fold_expr(* _i . hi)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_ref<V: Fold + ?Sized>(_visitor: &mut V, _i: PatRef) -> PatRef { + PatRef { + and_token: Token ! [ & ](tokens_helper(_visitor, &(_i . and_token).0)), + mutability: (_i . mutability).map(|it| { Token ! [ mut ](tokens_helper(_visitor, &(it).0)) }), + pat: Box::new(_visitor.fold_pat(* _i . pat)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_slice<V: Fold + ?Sized>(_visitor: &mut V, _i: PatSlice) -> PatSlice { + PatSlice { + bracket_token: Bracket(tokens_helper(_visitor, &(_i . bracket_token).0)), + front: FoldHelper::lift(_i . front, |it| { _visitor.fold_pat(it) }), + middle: (_i . middle).map(|it| { Box::new(_visitor.fold_pat(* it)) }), + dot2_token: (_i . dot2_token).map(|it| { Token ! [ .. ](tokens_helper(_visitor, &(it).0)) }), + comma_token: (_i . comma_token).map(|it| { Token ! [ , ](tokens_helper(_visitor, &(it).0)) }), + back: FoldHelper::lift(_i . back, |it| { _visitor.fold_pat(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_struct<V: Fold + ?Sized>(_visitor: &mut V, _i: PatStruct) -> PatStruct { + PatStruct { + path: _visitor.fold_path(_i . path), + brace_token: Brace(tokens_helper(_visitor, &(_i . brace_token).0)), + fields: FoldHelper::lift(_i . fields, |it| { _visitor.fold_field_pat(it) }), + dot2_token: (_i . dot2_token).map(|it| { Token ! [ .. ](tokens_helper(_visitor, &(it).0)) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_tuple<V: Fold + ?Sized>(_visitor: &mut V, _i: PatTuple) -> PatTuple { + PatTuple { + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + front: FoldHelper::lift(_i . front, |it| { _visitor.fold_pat(it) }), + dot2_token: (_i . dot2_token).map(|it| { Token ! [ .. ](tokens_helper(_visitor, &(it).0)) }), + comma_token: (_i . comma_token).map(|it| { Token ! [ , ](tokens_helper(_visitor, &(it).0)) }), + back: FoldHelper::lift(_i . back, |it| { _visitor.fold_pat(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_tuple_struct<V: Fold + ?Sized>(_visitor: &mut V, _i: PatTupleStruct) -> PatTupleStruct { + PatTupleStruct { + path: _visitor.fold_path(_i . path), + pat: _visitor.fold_pat_tuple(_i . pat), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: PatVerbatim) -> PatVerbatim { + PatVerbatim { + tts: _i . tts, + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_pat_wild<V: Fold + ?Sized>(_visitor: &mut V, _i: PatWild) -> PatWild { + PatWild { + underscore_token: Token ! [ _ ](tokens_helper(_visitor, &(_i . underscore_token).0)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_path<V: Fold + ?Sized>(_visitor: &mut V, _i: Path) -> Path { + Path { + leading_colon: (_i . leading_colon).map(|it| { Token ! [ :: ](tokens_helper(_visitor, &(it).0)) }), + segments: FoldHelper::lift(_i . segments, |it| { _visitor.fold_path_segment(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_path_arguments<V: Fold + ?Sized>(_visitor: &mut V, _i: PathArguments) -> PathArguments { + match _i { + PathArguments::None => { PathArguments::None } + PathArguments::AngleBracketed(_binding_0, ) => { + PathArguments::AngleBracketed ( + _visitor.fold_angle_bracketed_generic_arguments(_binding_0), + ) + } + PathArguments::Parenthesized(_binding_0, ) => { + PathArguments::Parenthesized ( + _visitor.fold_parenthesized_generic_arguments(_binding_0), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_path_segment<V: Fold + ?Sized>(_visitor: &mut V, _i: PathSegment) -> PathSegment { + PathSegment { + ident: _visitor.fold_ident(_i . ident), + arguments: _visitor.fold_path_arguments(_i . arguments), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_predicate_eq<V: Fold + ?Sized>(_visitor: &mut V, _i: PredicateEq) -> PredicateEq { + PredicateEq { + lhs_ty: _visitor.fold_type(_i . lhs_ty), + eq_token: Token ! [ = ](tokens_helper(_visitor, &(_i . eq_token).0)), + rhs_ty: _visitor.fold_type(_i . rhs_ty), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_predicate_lifetime<V: Fold + ?Sized>(_visitor: &mut V, _i: PredicateLifetime) -> PredicateLifetime { + PredicateLifetime { + lifetime: _visitor.fold_lifetime(_i . lifetime), + colon_token: (_i . colon_token).map(|it| { Token ! [ : ](tokens_helper(_visitor, &(it).0)) }), + bounds: FoldHelper::lift(_i . bounds, |it| { _visitor.fold_lifetime(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_predicate_type<V: Fold + ?Sized>(_visitor: &mut V, _i: PredicateType) -> PredicateType { + PredicateType { + lifetimes: (_i . lifetimes).map(|it| { _visitor.fold_bound_lifetimes(it) }), + bounded_ty: _visitor.fold_type(_i . bounded_ty), + colon_token: Token ! [ : ](tokens_helper(_visitor, &(_i . colon_token).0)), + bounds: FoldHelper::lift(_i . bounds, |it| { _visitor.fold_type_param_bound(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_qself<V: Fold + ?Sized>(_visitor: &mut V, _i: QSelf) -> QSelf { + QSelf { + lt_token: Token ! [ < ](tokens_helper(_visitor, &(_i . lt_token).0)), + ty: Box::new(_visitor.fold_type(* _i . ty)), + position: _i . position, + as_token: (_i . as_token).map(|it| { Token ! [ as ](tokens_helper(_visitor, &(it).0)) }), + gt_token: Token ! [ > ](tokens_helper(_visitor, &(_i . gt_token).0)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_range_limits<V: Fold + ?Sized>(_visitor: &mut V, _i: RangeLimits) -> RangeLimits { + match _i { + RangeLimits::HalfOpen(_binding_0, ) => { + RangeLimits::HalfOpen ( + Token ! [ .. ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + RangeLimits::Closed(_binding_0, ) => { + RangeLimits::Closed ( + Token ! [ ..= ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_return_type<V: Fold + ?Sized>(_visitor: &mut V, _i: ReturnType) -> ReturnType { + match _i { + ReturnType::Default => { ReturnType::Default } + ReturnType::Type(_binding_0, _binding_1, ) => { + ReturnType::Type ( + Token ! [ -> ](tokens_helper(_visitor, &(_binding_0).0)), + Box::new(_visitor.fold_type(* _binding_1)), + ) + } + } +} + +pub fn fold_span<V: Fold + ?Sized>(_visitor: &mut V, _i: Span) -> Span { + _i +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn fold_stmt<V: Fold + ?Sized>(_visitor: &mut V, _i: Stmt) -> Stmt { + match _i { + Stmt::Local(_binding_0, ) => { + Stmt::Local ( + _visitor.fold_local(_binding_0), + ) + } + Stmt::Item(_binding_0, ) => { + Stmt::Item ( + _visitor.fold_item(_binding_0), + ) + } + Stmt::Expr(_binding_0, ) => { + Stmt::Expr ( + _visitor.fold_expr(_binding_0), + ) + } + Stmt::Semi(_binding_0, _binding_1, ) => { + Stmt::Semi ( + _visitor.fold_expr(_binding_0), + Token ! [ ; ](tokens_helper(_visitor, &(_binding_1).0)), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_trait_bound<V: Fold + ?Sized>(_visitor: &mut V, _i: TraitBound) -> TraitBound { + TraitBound { + paren_token: (_i . paren_token).map(|it| { Paren(tokens_helper(_visitor, &(it).0)) }), + modifier: _visitor.fold_trait_bound_modifier(_i . modifier), + lifetimes: (_i . lifetimes).map(|it| { _visitor.fold_bound_lifetimes(it) }), + path: _visitor.fold_path(_i . path), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_trait_bound_modifier<V: Fold + ?Sized>(_visitor: &mut V, _i: TraitBoundModifier) -> TraitBoundModifier { + match _i { + TraitBoundModifier::None => { TraitBoundModifier::None } + TraitBoundModifier::Maybe(_binding_0, ) => { + TraitBoundModifier::Maybe ( + Token ! [ ? ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_trait_item<V: Fold + ?Sized>(_visitor: &mut V, _i: TraitItem) -> TraitItem { + match _i { + TraitItem::Const(_binding_0, ) => { + TraitItem::Const ( + _visitor.fold_trait_item_const(_binding_0), + ) + } + TraitItem::Method(_binding_0, ) => { + TraitItem::Method ( + _visitor.fold_trait_item_method(_binding_0), + ) + } + TraitItem::Type(_binding_0, ) => { + TraitItem::Type ( + _visitor.fold_trait_item_type(_binding_0), + ) + } + TraitItem::Macro(_binding_0, ) => { + TraitItem::Macro ( + _visitor.fold_trait_item_macro(_binding_0), + ) + } + TraitItem::Verbatim(_binding_0, ) => { + TraitItem::Verbatim ( + _visitor.fold_trait_item_verbatim(_binding_0), + ) + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_trait_item_const<V: Fold + ?Sized>(_visitor: &mut V, _i: TraitItemConst) -> TraitItemConst { + TraitItemConst { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + const_token: Token ! [ const ](tokens_helper(_visitor, &(_i . const_token).0)), + ident: _visitor.fold_ident(_i . ident), + colon_token: Token ! [ : ](tokens_helper(_visitor, &(_i . colon_token).0)), + ty: _visitor.fold_type(_i . ty), + default: (_i . default).map(|it| { ( + Token ! [ = ](tokens_helper(_visitor, &(( it ) . 0).0)), + _visitor.fold_expr(( it ) . 1), + ) }), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_trait_item_macro<V: Fold + ?Sized>(_visitor: &mut V, _i: TraitItemMacro) -> TraitItemMacro { + TraitItemMacro { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + mac: _visitor.fold_macro(_i . mac), + semi_token: (_i . semi_token).map(|it| { Token ! [ ; ](tokens_helper(_visitor, &(it).0)) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_trait_item_method<V: Fold + ?Sized>(_visitor: &mut V, _i: TraitItemMethod) -> TraitItemMethod { + TraitItemMethod { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + sig: _visitor.fold_method_sig(_i . sig), + default: (_i . default).map(|it| { _visitor.fold_block(it) }), + semi_token: (_i . semi_token).map(|it| { Token ! [ ; ](tokens_helper(_visitor, &(it).0)) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_trait_item_type<V: Fold + ?Sized>(_visitor: &mut V, _i: TraitItemType) -> TraitItemType { + TraitItemType { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + type_token: Token ! [ type ](tokens_helper(_visitor, &(_i . type_token).0)), + ident: _visitor.fold_ident(_i . ident), + generics: _visitor.fold_generics(_i . generics), + colon_token: (_i . colon_token).map(|it| { Token ! [ : ](tokens_helper(_visitor, &(it).0)) }), + bounds: FoldHelper::lift(_i . bounds, |it| { _visitor.fold_type_param_bound(it) }), + default: (_i . default).map(|it| { ( + Token ! [ = ](tokens_helper(_visitor, &(( it ) . 0).0)), + _visitor.fold_type(( it ) . 1), + ) }), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_trait_item_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: TraitItemVerbatim) -> TraitItemVerbatim { + TraitItemVerbatim { + tts: _i . tts, + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type<V: Fold + ?Sized>(_visitor: &mut V, _i: Type) -> Type { + match _i { + Type::Slice(_binding_0, ) => { + Type::Slice ( + _visitor.fold_type_slice(_binding_0), + ) + } + Type::Array(_binding_0, ) => { + Type::Array ( + _visitor.fold_type_array(_binding_0), + ) + } + Type::Ptr(_binding_0, ) => { + Type::Ptr ( + _visitor.fold_type_ptr(_binding_0), + ) + } + Type::Reference(_binding_0, ) => { + Type::Reference ( + _visitor.fold_type_reference(_binding_0), + ) + } + Type::BareFn(_binding_0, ) => { + Type::BareFn ( + _visitor.fold_type_bare_fn(_binding_0), + ) + } + Type::Never(_binding_0, ) => { + Type::Never ( + _visitor.fold_type_never(_binding_0), + ) + } + Type::Tuple(_binding_0, ) => { + Type::Tuple ( + _visitor.fold_type_tuple(_binding_0), + ) + } + Type::Path(_binding_0, ) => { + Type::Path ( + _visitor.fold_type_path(_binding_0), + ) + } + Type::TraitObject(_binding_0, ) => { + Type::TraitObject ( + _visitor.fold_type_trait_object(_binding_0), + ) + } + Type::ImplTrait(_binding_0, ) => { + Type::ImplTrait ( + _visitor.fold_type_impl_trait(_binding_0), + ) + } + Type::Paren(_binding_0, ) => { + Type::Paren ( + _visitor.fold_type_paren(_binding_0), + ) + } + Type::Group(_binding_0, ) => { + Type::Group ( + _visitor.fold_type_group(_binding_0), + ) + } + Type::Infer(_binding_0, ) => { + Type::Infer ( + _visitor.fold_type_infer(_binding_0), + ) + } + Type::Macro(_binding_0, ) => { + Type::Macro ( + _visitor.fold_type_macro(_binding_0), + ) + } + Type::Verbatim(_binding_0, ) => { + Type::Verbatim ( + _visitor.fold_type_verbatim(_binding_0), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_array<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeArray) -> TypeArray { + TypeArray { + bracket_token: Bracket(tokens_helper(_visitor, &(_i . bracket_token).0)), + elem: Box::new(_visitor.fold_type(* _i . elem)), + semi_token: Token ! [ ; ](tokens_helper(_visitor, &(_i . semi_token).0)), + len: _visitor.fold_expr(_i . len), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_bare_fn<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeBareFn) -> TypeBareFn { + TypeBareFn { + unsafety: (_i . unsafety).map(|it| { Token ! [ unsafe ](tokens_helper(_visitor, &(it).0)) }), + abi: (_i . abi).map(|it| { _visitor.fold_abi(it) }), + fn_token: Token ! [ fn ](tokens_helper(_visitor, &(_i . fn_token).0)), + lifetimes: (_i . lifetimes).map(|it| { _visitor.fold_bound_lifetimes(it) }), + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + inputs: FoldHelper::lift(_i . inputs, |it| { _visitor.fold_bare_fn_arg(it) }), + variadic: (_i . variadic).map(|it| { Token ! [ ... ](tokens_helper(_visitor, &(it).0)) }), + output: _visitor.fold_return_type(_i . output), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_group<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeGroup) -> TypeGroup { + TypeGroup { + group_token: Group(tokens_helper(_visitor, &(_i . group_token).0)), + elem: Box::new(_visitor.fold_type(* _i . elem)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_impl_trait<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeImplTrait) -> TypeImplTrait { + TypeImplTrait { + impl_token: Token ! [ impl ](tokens_helper(_visitor, &(_i . impl_token).0)), + bounds: FoldHelper::lift(_i . bounds, |it| { _visitor.fold_type_param_bound(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_infer<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeInfer) -> TypeInfer { + TypeInfer { + underscore_token: Token ! [ _ ](tokens_helper(_visitor, &(_i . underscore_token).0)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_macro<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeMacro) -> TypeMacro { + TypeMacro { + mac: _visitor.fold_macro(_i . mac), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_never<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeNever) -> TypeNever { + TypeNever { + bang_token: Token ! [ ! ](tokens_helper(_visitor, &(_i . bang_token).0)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_param<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeParam) -> TypeParam { + TypeParam { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + ident: _visitor.fold_ident(_i . ident), + colon_token: (_i . colon_token).map(|it| { Token ! [ : ](tokens_helper(_visitor, &(it).0)) }), + bounds: FoldHelper::lift(_i . bounds, |it| { _visitor.fold_type_param_bound(it) }), + eq_token: (_i . eq_token).map(|it| { Token ! [ = ](tokens_helper(_visitor, &(it).0)) }), + default: (_i . default).map(|it| { _visitor.fold_type(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_param_bound<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeParamBound) -> TypeParamBound { + match _i { + TypeParamBound::Trait(_binding_0, ) => { + TypeParamBound::Trait ( + _visitor.fold_trait_bound(_binding_0), + ) + } + TypeParamBound::Lifetime(_binding_0, ) => { + TypeParamBound::Lifetime ( + _visitor.fold_lifetime(_binding_0), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_paren<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeParen) -> TypeParen { + TypeParen { + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + elem: Box::new(_visitor.fold_type(* _i . elem)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_path<V: Fold + ?Sized>(_visitor: &mut V, _i: TypePath) -> TypePath { + TypePath { + qself: (_i . qself).map(|it| { _visitor.fold_qself(it) }), + path: _visitor.fold_path(_i . path), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_ptr<V: Fold + ?Sized>(_visitor: &mut V, _i: TypePtr) -> TypePtr { + TypePtr { + star_token: Token ! [ * ](tokens_helper(_visitor, &(_i . star_token).0)), + const_token: (_i . const_token).map(|it| { Token ! [ const ](tokens_helper(_visitor, &(it).0)) }), + mutability: (_i . mutability).map(|it| { Token ! [ mut ](tokens_helper(_visitor, &(it).0)) }), + elem: Box::new(_visitor.fold_type(* _i . elem)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_reference<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeReference) -> TypeReference { + TypeReference { + and_token: Token ! [ & ](tokens_helper(_visitor, &(_i . and_token).0)), + lifetime: (_i . lifetime).map(|it| { _visitor.fold_lifetime(it) }), + mutability: (_i . mutability).map(|it| { Token ! [ mut ](tokens_helper(_visitor, &(it).0)) }), + elem: Box::new(_visitor.fold_type(* _i . elem)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_slice<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeSlice) -> TypeSlice { + TypeSlice { + bracket_token: Bracket(tokens_helper(_visitor, &(_i . bracket_token).0)), + elem: Box::new(_visitor.fold_type(* _i . elem)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_trait_object<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeTraitObject) -> TypeTraitObject { + TypeTraitObject { + dyn_token: (_i . dyn_token).map(|it| { Token ! [ dyn ](tokens_helper(_visitor, &(it).0)) }), + bounds: FoldHelper::lift(_i . bounds, |it| { _visitor.fold_type_param_bound(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_tuple<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeTuple) -> TypeTuple { + TypeTuple { + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + elems: FoldHelper::lift(_i . elems, |it| { _visitor.fold_type(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_type_verbatim<V: Fold + ?Sized>(_visitor: &mut V, _i: TypeVerbatim) -> TypeVerbatim { + TypeVerbatim { + tts: _i . tts, + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_un_op<V: Fold + ?Sized>(_visitor: &mut V, _i: UnOp) -> UnOp { + match _i { + UnOp::Deref(_binding_0, ) => { + UnOp::Deref ( + Token ! [ * ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + UnOp::Not(_binding_0, ) => { + UnOp::Not ( + Token ! [ ! ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + UnOp::Neg(_binding_0, ) => { + UnOp::Neg ( + Token ! [ - ](tokens_helper(_visitor, &(_binding_0).0)), + ) + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_use_glob<V: Fold + ?Sized>(_visitor: &mut V, _i: UseGlob) -> UseGlob { + UseGlob { + star_token: Token ! [ * ](tokens_helper(_visitor, &(_i . star_token).0)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_use_group<V: Fold + ?Sized>(_visitor: &mut V, _i: UseGroup) -> UseGroup { + UseGroup { + brace_token: Brace(tokens_helper(_visitor, &(_i . brace_token).0)), + items: FoldHelper::lift(_i . items, |it| { _visitor.fold_use_tree(it) }), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_use_name<V: Fold + ?Sized>(_visitor: &mut V, _i: UseName) -> UseName { + UseName { + ident: _visitor.fold_ident(_i . ident), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_use_path<V: Fold + ?Sized>(_visitor: &mut V, _i: UsePath) -> UsePath { + UsePath { + ident: _visitor.fold_ident(_i . ident), + colon2_token: Token ! [ :: ](tokens_helper(_visitor, &(_i . colon2_token).0)), + tree: Box::new(_visitor.fold_use_tree(* _i . tree)), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_use_rename<V: Fold + ?Sized>(_visitor: &mut V, _i: UseRename) -> UseRename { + UseRename { + ident: _visitor.fold_ident(_i . ident), + as_token: Token ! [ as ](tokens_helper(_visitor, &(_i . as_token).0)), + rename: _visitor.fold_ident(_i . rename), + } +} +# [ cfg ( feature = "full" ) ] +pub fn fold_use_tree<V: Fold + ?Sized>(_visitor: &mut V, _i: UseTree) -> UseTree { + match _i { + UseTree::Path(_binding_0, ) => { + UseTree::Path ( + _visitor.fold_use_path(_binding_0), + ) + } + UseTree::Name(_binding_0, ) => { + UseTree::Name ( + _visitor.fold_use_name(_binding_0), + ) + } + UseTree::Rename(_binding_0, ) => { + UseTree::Rename ( + _visitor.fold_use_rename(_binding_0), + ) + } + UseTree::Glob(_binding_0, ) => { + UseTree::Glob ( + _visitor.fold_use_glob(_binding_0), + ) + } + UseTree::Group(_binding_0, ) => { + UseTree::Group ( + _visitor.fold_use_group(_binding_0), + ) + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_variant<V: Fold + ?Sized>(_visitor: &mut V, _i: Variant) -> Variant { + Variant { + attrs: FoldHelper::lift(_i . attrs, |it| { _visitor.fold_attribute(it) }), + ident: _visitor.fold_ident(_i . ident), + fields: _visitor.fold_fields(_i . fields), + discriminant: (_i . discriminant).map(|it| { ( + Token ! [ = ](tokens_helper(_visitor, &(( it ) . 0).0)), + _visitor.fold_expr(( it ) . 1), + ) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_vis_crate<V: Fold + ?Sized>(_visitor: &mut V, _i: VisCrate) -> VisCrate { + VisCrate { + crate_token: Token ! [ crate ](tokens_helper(_visitor, &(_i . crate_token).0)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_vis_public<V: Fold + ?Sized>(_visitor: &mut V, _i: VisPublic) -> VisPublic { + VisPublic { + pub_token: Token ! [ pub ](tokens_helper(_visitor, &(_i . pub_token).0)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_vis_restricted<V: Fold + ?Sized>(_visitor: &mut V, _i: VisRestricted) -> VisRestricted { + VisRestricted { + pub_token: Token ! [ pub ](tokens_helper(_visitor, &(_i . pub_token).0)), + paren_token: Paren(tokens_helper(_visitor, &(_i . paren_token).0)), + in_token: (_i . in_token).map(|it| { Token ! [ in ](tokens_helper(_visitor, &(it).0)) }), + path: Box::new(_visitor.fold_path(* _i . path)), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_visibility<V: Fold + ?Sized>(_visitor: &mut V, _i: Visibility) -> Visibility { + match _i { + Visibility::Public(_binding_0, ) => { + Visibility::Public ( + _visitor.fold_vis_public(_binding_0), + ) + } + Visibility::Crate(_binding_0, ) => { + Visibility::Crate ( + _visitor.fold_vis_crate(_binding_0), + ) + } + Visibility::Restricted(_binding_0, ) => { + Visibility::Restricted ( + _visitor.fold_vis_restricted(_binding_0), + ) + } + Visibility::Inherited => { Visibility::Inherited } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_where_clause<V: Fold + ?Sized>(_visitor: &mut V, _i: WhereClause) -> WhereClause { + WhereClause { + where_token: Token ! [ where ](tokens_helper(_visitor, &(_i . where_token).0)), + predicates: FoldHelper::lift(_i . predicates, |it| { _visitor.fold_where_predicate(it) }), + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn fold_where_predicate<V: Fold + ?Sized>(_visitor: &mut V, _i: WherePredicate) -> WherePredicate { + match _i { + WherePredicate::Type(_binding_0, ) => { + WherePredicate::Type ( + _visitor.fold_predicate_type(_binding_0), + ) + } + WherePredicate::Lifetime(_binding_0, ) => { + WherePredicate::Lifetime ( + _visitor.fold_predicate_lifetime(_binding_0), + ) + } + WherePredicate::Eq(_binding_0, ) => { + WherePredicate::Eq ( + _visitor.fold_predicate_eq(_binding_0), + ) + } + } +} + diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/gen/visit_mut.rs cargo-0.26.0/vendor/syn-0.13.1/src/gen/visit_mut.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/gen/visit_mut.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/gen/visit_mut.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2288 @@ +// THIS FILE IS AUTOMATICALLY GENERATED; DO NOT EDIT + +#![cfg_attr(rustfmt, rustfmt_skip)] + +#![cfg_attr(feature = "cargo-clippy", allow(match_same_arms))] + +use *; +#[cfg(any(feature = "full", feature = "derive"))] +use punctuated::Punctuated; +use proc_macro2::Span; +#[cfg(any(feature = "full", feature = "derive"))] +use gen::helper::visit_mut::*; + + +#[cfg(feature = "full")] +macro_rules! full { + ($e:expr) => { $e } +} + +#[cfg(all(feature = "derive", not(feature = "full")))] +macro_rules! full { + ($e:expr) => { unreachable!() } +} + + +/// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in +/// place. +/// +/// See the [module documentation] for details. +/// +/// [module documentation]: index.html +/// +/// *This trait is available if Syn is built with the `"visit-mut"` feature.* +pub trait VisitMut { +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_abi_mut(&mut self, i: &mut Abi) { visit_abi_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_angle_bracketed_generic_arguments_mut(&mut self, i: &mut AngleBracketedGenericArguments) { visit_angle_bracketed_generic_arguments_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_arg_captured_mut(&mut self, i: &mut ArgCaptured) { visit_arg_captured_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_arg_self_mut(&mut self, i: &mut ArgSelf) { visit_arg_self_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_arg_self_ref_mut(&mut self, i: &mut ArgSelfRef) { visit_arg_self_ref_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_arm_mut(&mut self, i: &mut Arm) { visit_arm_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_attr_style_mut(&mut self, i: &mut AttrStyle) { visit_attr_style_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_attribute_mut(&mut self, i: &mut Attribute) { visit_attribute_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_bare_fn_arg_mut(&mut self, i: &mut BareFnArg) { visit_bare_fn_arg_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_bare_fn_arg_name_mut(&mut self, i: &mut BareFnArgName) { visit_bare_fn_arg_name_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_bin_op_mut(&mut self, i: &mut BinOp) { visit_bin_op_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_binding_mut(&mut self, i: &mut Binding) { visit_binding_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_block_mut(&mut self, i: &mut Block) { visit_block_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_bound_lifetimes_mut(&mut self, i: &mut BoundLifetimes) { visit_bound_lifetimes_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_const_param_mut(&mut self, i: &mut ConstParam) { visit_const_param_mut(self, i) } +# [ cfg ( feature = "derive" ) ] +fn visit_data_mut(&mut self, i: &mut Data) { visit_data_mut(self, i) } +# [ cfg ( feature = "derive" ) ] +fn visit_data_enum_mut(&mut self, i: &mut DataEnum) { visit_data_enum_mut(self, i) } +# [ cfg ( feature = "derive" ) ] +fn visit_data_struct_mut(&mut self, i: &mut DataStruct) { visit_data_struct_mut(self, i) } +# [ cfg ( feature = "derive" ) ] +fn visit_data_union_mut(&mut self, i: &mut DataUnion) { visit_data_union_mut(self, i) } +# [ cfg ( feature = "derive" ) ] +fn visit_derive_input_mut(&mut self, i: &mut DeriveInput) { visit_derive_input_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_mut(&mut self, i: &mut Expr) { visit_expr_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_array_mut(&mut self, i: &mut ExprArray) { visit_expr_array_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_assign_mut(&mut self, i: &mut ExprAssign) { visit_expr_assign_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_assign_op_mut(&mut self, i: &mut ExprAssignOp) { visit_expr_assign_op_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_binary_mut(&mut self, i: &mut ExprBinary) { visit_expr_binary_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_block_mut(&mut self, i: &mut ExprBlock) { visit_expr_block_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_box_mut(&mut self, i: &mut ExprBox) { visit_expr_box_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_break_mut(&mut self, i: &mut ExprBreak) { visit_expr_break_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_call_mut(&mut self, i: &mut ExprCall) { visit_expr_call_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_cast_mut(&mut self, i: &mut ExprCast) { visit_expr_cast_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_catch_mut(&mut self, i: &mut ExprCatch) { visit_expr_catch_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_closure_mut(&mut self, i: &mut ExprClosure) { visit_expr_closure_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_continue_mut(&mut self, i: &mut ExprContinue) { visit_expr_continue_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_field_mut(&mut self, i: &mut ExprField) { visit_expr_field_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_for_loop_mut(&mut self, i: &mut ExprForLoop) { visit_expr_for_loop_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_group_mut(&mut self, i: &mut ExprGroup) { visit_expr_group_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_if_mut(&mut self, i: &mut ExprIf) { visit_expr_if_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_if_let_mut(&mut self, i: &mut ExprIfLet) { visit_expr_if_let_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_in_place_mut(&mut self, i: &mut ExprInPlace) { visit_expr_in_place_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_index_mut(&mut self, i: &mut ExprIndex) { visit_expr_index_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_lit_mut(&mut self, i: &mut ExprLit) { visit_expr_lit_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_loop_mut(&mut self, i: &mut ExprLoop) { visit_expr_loop_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_macro_mut(&mut self, i: &mut ExprMacro) { visit_expr_macro_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_match_mut(&mut self, i: &mut ExprMatch) { visit_expr_match_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_method_call_mut(&mut self, i: &mut ExprMethodCall) { visit_expr_method_call_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_paren_mut(&mut self, i: &mut ExprParen) { visit_expr_paren_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_path_mut(&mut self, i: &mut ExprPath) { visit_expr_path_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_range_mut(&mut self, i: &mut ExprRange) { visit_expr_range_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_reference_mut(&mut self, i: &mut ExprReference) { visit_expr_reference_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_repeat_mut(&mut self, i: &mut ExprRepeat) { visit_expr_repeat_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_return_mut(&mut self, i: &mut ExprReturn) { visit_expr_return_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_struct_mut(&mut self, i: &mut ExprStruct) { visit_expr_struct_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_try_mut(&mut self, i: &mut ExprTry) { visit_expr_try_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_tuple_mut(&mut self, i: &mut ExprTuple) { visit_expr_tuple_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_type_mut(&mut self, i: &mut ExprType) { visit_expr_type_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_unary_mut(&mut self, i: &mut ExprUnary) { visit_expr_unary_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_unsafe_mut(&mut self, i: &mut ExprUnsafe) { visit_expr_unsafe_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_verbatim_mut(&mut self, i: &mut ExprVerbatim) { visit_expr_verbatim_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_while_mut(&mut self, i: &mut ExprWhile) { visit_expr_while_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_while_let_mut(&mut self, i: &mut ExprWhileLet) { visit_expr_while_let_mut(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_yield_mut(&mut self, i: &mut ExprYield) { visit_expr_yield_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_field_mut(&mut self, i: &mut Field) { visit_field_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_field_pat_mut(&mut self, i: &mut FieldPat) { visit_field_pat_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_field_value_mut(&mut self, i: &mut FieldValue) { visit_field_value_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_fields_mut(&mut self, i: &mut Fields) { visit_fields_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_fields_named_mut(&mut self, i: &mut FieldsNamed) { visit_fields_named_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_fields_unnamed_mut(&mut self, i: &mut FieldsUnnamed) { visit_fields_unnamed_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_file_mut(&mut self, i: &mut File) { visit_file_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_fn_arg_mut(&mut self, i: &mut FnArg) { visit_fn_arg_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_fn_decl_mut(&mut self, i: &mut FnDecl) { visit_fn_decl_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_foreign_item_mut(&mut self, i: &mut ForeignItem) { visit_foreign_item_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_foreign_item_fn_mut(&mut self, i: &mut ForeignItemFn) { visit_foreign_item_fn_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_foreign_item_static_mut(&mut self, i: &mut ForeignItemStatic) { visit_foreign_item_static_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_foreign_item_type_mut(&mut self, i: &mut ForeignItemType) { visit_foreign_item_type_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_foreign_item_verbatim_mut(&mut self, i: &mut ForeignItemVerbatim) { visit_foreign_item_verbatim_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_generic_argument_mut(&mut self, i: &mut GenericArgument) { visit_generic_argument_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_generic_method_argument_mut(&mut self, i: &mut GenericMethodArgument) { visit_generic_method_argument_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_generic_param_mut(&mut self, i: &mut GenericParam) { visit_generic_param_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_generics_mut(&mut self, i: &mut Generics) { visit_generics_mut(self, i) } + +fn visit_ident_mut(&mut self, i: &mut Ident) { visit_ident_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_impl_item_mut(&mut self, i: &mut ImplItem) { visit_impl_item_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_impl_item_const_mut(&mut self, i: &mut ImplItemConst) { visit_impl_item_const_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_impl_item_macro_mut(&mut self, i: &mut ImplItemMacro) { visit_impl_item_macro_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_impl_item_method_mut(&mut self, i: &mut ImplItemMethod) { visit_impl_item_method_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_impl_item_type_mut(&mut self, i: &mut ImplItemType) { visit_impl_item_type_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_impl_item_verbatim_mut(&mut self, i: &mut ImplItemVerbatim) { visit_impl_item_verbatim_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_index_mut(&mut self, i: &mut Index) { visit_index_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_mut(&mut self, i: &mut Item) { visit_item_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_const_mut(&mut self, i: &mut ItemConst) { visit_item_const_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_enum_mut(&mut self, i: &mut ItemEnum) { visit_item_enum_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_extern_crate_mut(&mut self, i: &mut ItemExternCrate) { visit_item_extern_crate_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_fn_mut(&mut self, i: &mut ItemFn) { visit_item_fn_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_foreign_mod_mut(&mut self, i: &mut ItemForeignMod) { visit_item_foreign_mod_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_impl_mut(&mut self, i: &mut ItemImpl) { visit_item_impl_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_macro_mut(&mut self, i: &mut ItemMacro) { visit_item_macro_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_macro2_mut(&mut self, i: &mut ItemMacro2) { visit_item_macro2_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_mod_mut(&mut self, i: &mut ItemMod) { visit_item_mod_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_static_mut(&mut self, i: &mut ItemStatic) { visit_item_static_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_struct_mut(&mut self, i: &mut ItemStruct) { visit_item_struct_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_trait_mut(&mut self, i: &mut ItemTrait) { visit_item_trait_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_type_mut(&mut self, i: &mut ItemType) { visit_item_type_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_union_mut(&mut self, i: &mut ItemUnion) { visit_item_union_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_use_mut(&mut self, i: &mut ItemUse) { visit_item_use_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_verbatim_mut(&mut self, i: &mut ItemVerbatim) { visit_item_verbatim_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_label_mut(&mut self, i: &mut Label) { visit_label_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lifetime_mut(&mut self, i: &mut Lifetime) { visit_lifetime_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lifetime_def_mut(&mut self, i: &mut LifetimeDef) { visit_lifetime_def_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_mut(&mut self, i: &mut Lit) { visit_lit_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_bool_mut(&mut self, i: &mut LitBool) { visit_lit_bool_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_byte_mut(&mut self, i: &mut LitByte) { visit_lit_byte_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_byte_str_mut(&mut self, i: &mut LitByteStr) { visit_lit_byte_str_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_char_mut(&mut self, i: &mut LitChar) { visit_lit_char_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_float_mut(&mut self, i: &mut LitFloat) { visit_lit_float_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_int_mut(&mut self, i: &mut LitInt) { visit_lit_int_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_str_mut(&mut self, i: &mut LitStr) { visit_lit_str_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_verbatim_mut(&mut self, i: &mut LitVerbatim) { visit_lit_verbatim_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_local_mut(&mut self, i: &mut Local) { visit_local_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_macro_mut(&mut self, i: &mut Macro) { visit_macro_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_macro_delimiter_mut(&mut self, i: &mut MacroDelimiter) { visit_macro_delimiter_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_member_mut(&mut self, i: &mut Member) { visit_member_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_meta_mut(&mut self, i: &mut Meta) { visit_meta_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_meta_list_mut(&mut self, i: &mut MetaList) { visit_meta_list_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_meta_name_value_mut(&mut self, i: &mut MetaNameValue) { visit_meta_name_value_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_method_sig_mut(&mut self, i: &mut MethodSig) { visit_method_sig_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_method_turbofish_mut(&mut self, i: &mut MethodTurbofish) { visit_method_turbofish_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_nested_meta_mut(&mut self, i: &mut NestedMeta) { visit_nested_meta_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_parenthesized_generic_arguments_mut(&mut self, i: &mut ParenthesizedGenericArguments) { visit_parenthesized_generic_arguments_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_mut(&mut self, i: &mut Pat) { visit_pat_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_box_mut(&mut self, i: &mut PatBox) { visit_pat_box_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_ident_mut(&mut self, i: &mut PatIdent) { visit_pat_ident_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_lit_mut(&mut self, i: &mut PatLit) { visit_pat_lit_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_macro_mut(&mut self, i: &mut PatMacro) { visit_pat_macro_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_path_mut(&mut self, i: &mut PatPath) { visit_pat_path_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_range_mut(&mut self, i: &mut PatRange) { visit_pat_range_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_ref_mut(&mut self, i: &mut PatRef) { visit_pat_ref_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_slice_mut(&mut self, i: &mut PatSlice) { visit_pat_slice_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_struct_mut(&mut self, i: &mut PatStruct) { visit_pat_struct_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_tuple_mut(&mut self, i: &mut PatTuple) { visit_pat_tuple_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_tuple_struct_mut(&mut self, i: &mut PatTupleStruct) { visit_pat_tuple_struct_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_verbatim_mut(&mut self, i: &mut PatVerbatim) { visit_pat_verbatim_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_wild_mut(&mut self, i: &mut PatWild) { visit_pat_wild_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_path_mut(&mut self, i: &mut Path) { visit_path_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_path_arguments_mut(&mut self, i: &mut PathArguments) { visit_path_arguments_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_path_segment_mut(&mut self, i: &mut PathSegment) { visit_path_segment_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_predicate_eq_mut(&mut self, i: &mut PredicateEq) { visit_predicate_eq_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_predicate_lifetime_mut(&mut self, i: &mut PredicateLifetime) { visit_predicate_lifetime_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_predicate_type_mut(&mut self, i: &mut PredicateType) { visit_predicate_type_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_qself_mut(&mut self, i: &mut QSelf) { visit_qself_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_range_limits_mut(&mut self, i: &mut RangeLimits) { visit_range_limits_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_return_type_mut(&mut self, i: &mut ReturnType) { visit_return_type_mut(self, i) } + +fn visit_span_mut(&mut self, i: &mut Span) { visit_span_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_stmt_mut(&mut self, i: &mut Stmt) { visit_stmt_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_trait_bound_mut(&mut self, i: &mut TraitBound) { visit_trait_bound_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_trait_bound_modifier_mut(&mut self, i: &mut TraitBoundModifier) { visit_trait_bound_modifier_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_trait_item_mut(&mut self, i: &mut TraitItem) { visit_trait_item_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_trait_item_const_mut(&mut self, i: &mut TraitItemConst) { visit_trait_item_const_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_trait_item_macro_mut(&mut self, i: &mut TraitItemMacro) { visit_trait_item_macro_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_trait_item_method_mut(&mut self, i: &mut TraitItemMethod) { visit_trait_item_method_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_trait_item_type_mut(&mut self, i: &mut TraitItemType) { visit_trait_item_type_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_trait_item_verbatim_mut(&mut self, i: &mut TraitItemVerbatim) { visit_trait_item_verbatim_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_mut(&mut self, i: &mut Type) { visit_type_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_array_mut(&mut self, i: &mut TypeArray) { visit_type_array_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_bare_fn_mut(&mut self, i: &mut TypeBareFn) { visit_type_bare_fn_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_group_mut(&mut self, i: &mut TypeGroup) { visit_type_group_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_impl_trait_mut(&mut self, i: &mut TypeImplTrait) { visit_type_impl_trait_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_infer_mut(&mut self, i: &mut TypeInfer) { visit_type_infer_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_macro_mut(&mut self, i: &mut TypeMacro) { visit_type_macro_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_never_mut(&mut self, i: &mut TypeNever) { visit_type_never_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_param_mut(&mut self, i: &mut TypeParam) { visit_type_param_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_param_bound_mut(&mut self, i: &mut TypeParamBound) { visit_type_param_bound_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_paren_mut(&mut self, i: &mut TypeParen) { visit_type_paren_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_path_mut(&mut self, i: &mut TypePath) { visit_type_path_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_ptr_mut(&mut self, i: &mut TypePtr) { visit_type_ptr_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_reference_mut(&mut self, i: &mut TypeReference) { visit_type_reference_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_slice_mut(&mut self, i: &mut TypeSlice) { visit_type_slice_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_trait_object_mut(&mut self, i: &mut TypeTraitObject) { visit_type_trait_object_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_tuple_mut(&mut self, i: &mut TypeTuple) { visit_type_tuple_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_verbatim_mut(&mut self, i: &mut TypeVerbatim) { visit_type_verbatim_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_un_op_mut(&mut self, i: &mut UnOp) { visit_un_op_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_use_glob_mut(&mut self, i: &mut UseGlob) { visit_use_glob_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_use_group_mut(&mut self, i: &mut UseGroup) { visit_use_group_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_use_name_mut(&mut self, i: &mut UseName) { visit_use_name_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_use_path_mut(&mut self, i: &mut UsePath) { visit_use_path_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_use_rename_mut(&mut self, i: &mut UseRename) { visit_use_rename_mut(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_use_tree_mut(&mut self, i: &mut UseTree) { visit_use_tree_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_variant_mut(&mut self, i: &mut Variant) { visit_variant_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_vis_crate_mut(&mut self, i: &mut VisCrate) { visit_vis_crate_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_vis_public_mut(&mut self, i: &mut VisPublic) { visit_vis_public_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_vis_restricted_mut(&mut self, i: &mut VisRestricted) { visit_vis_restricted_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_visibility_mut(&mut self, i: &mut Visibility) { visit_visibility_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_where_clause_mut(&mut self, i: &mut WhereClause) { visit_where_clause_mut(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_where_predicate_mut(&mut self, i: &mut WherePredicate) { visit_where_predicate_mut(self, i) } + +} + +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_abi_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Abi) { + tokens_helper(_visitor, &mut (& mut _i . extern_token).0); + if let Some(ref mut it) = _i . name { _visitor.visit_lit_str_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_angle_bracketed_generic_arguments_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut AngleBracketedGenericArguments) { + if let Some(ref mut it) = _i . colon2_token { tokens_helper(_visitor, &mut (it).0) }; + tokens_helper(_visitor, &mut (& mut _i . lt_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . args) { let it = el.value_mut(); _visitor.visit_generic_argument_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . gt_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_arg_captured_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ArgCaptured) { + _visitor.visit_pat_mut(& mut _i . pat); + tokens_helper(_visitor, &mut (& mut _i . colon_token).0); + _visitor.visit_type_mut(& mut _i . ty); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_arg_self_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ArgSelf) { + if let Some(ref mut it) = _i . mutability { tokens_helper(_visitor, &mut (it).0) }; + tokens_helper(_visitor, &mut (& mut _i . self_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_arg_self_ref_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ArgSelfRef) { + tokens_helper(_visitor, &mut (& mut _i . and_token).0); + if let Some(ref mut it) = _i . lifetime { _visitor.visit_lifetime_mut(it) }; + if let Some(ref mut it) = _i . mutability { tokens_helper(_visitor, &mut (it).0) }; + tokens_helper(_visitor, &mut (& mut _i . self_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_arm_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Arm) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + if let Some(ref mut it) = _i . leading_vert { tokens_helper(_visitor, &mut (it).0) }; + for mut el in Punctuated::pairs_mut(& mut _i . pats) { let it = el.value_mut(); _visitor.visit_pat_mut(it) }; + if let Some(ref mut it) = _i . guard { + tokens_helper(_visitor, &mut (& mut ( it ) . 0).0); + _visitor.visit_expr_mut(& mut * ( it ) . 1); + }; + tokens_helper(_visitor, &mut (& mut _i . fat_arrow_token).0); + _visitor.visit_expr_mut(& mut * _i . body); + if let Some(ref mut it) = _i . comma { tokens_helper(_visitor, &mut (it).0) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_attr_style_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut AttrStyle) { + match *_i { + AttrStyle::Outer => { } + AttrStyle::Inner(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_attribute_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Attribute) { + tokens_helper(_visitor, &mut (& mut _i . pound_token).0); + _visitor.visit_attr_style_mut(& mut _i . style); + tokens_helper(_visitor, &mut (& mut _i . bracket_token).0); + _visitor.visit_path_mut(& mut _i . path); + // Skipped field _i . tts; + // Skipped field _i . is_sugared_doc; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_bare_fn_arg_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut BareFnArg) { + if let Some(ref mut it) = _i . name { + _visitor.visit_bare_fn_arg_name_mut(& mut ( it ) . 0); + tokens_helper(_visitor, &mut (& mut ( it ) . 1).0); + }; + _visitor.visit_type_mut(& mut _i . ty); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_bare_fn_arg_name_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut BareFnArgName) { + match *_i { + BareFnArgName::Named(ref mut _binding_0, ) => { + _visitor.visit_ident_mut(_binding_0); + } + BareFnArgName::Wild(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_bin_op_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut BinOp) { + match *_i { + BinOp::Add(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Sub(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Mul(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Div(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Rem(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::And(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Or(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::BitXor(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::BitAnd(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::BitOr(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Shl(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Shr(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Eq(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Lt(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Le(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Ne(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Ge(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::Gt(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::AddEq(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::SubEq(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::MulEq(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::DivEq(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::RemEq(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::BitXorEq(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::BitAndEq(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::BitOrEq(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::ShlEq(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + BinOp::ShrEq(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_binding_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Binding) { + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . eq_token).0); + _visitor.visit_type_mut(& mut _i . ty); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_block_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Block) { + tokens_helper(_visitor, &mut (& mut _i . brace_token).0); + for it in & mut _i . stmts { _visitor.visit_stmt_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_bound_lifetimes_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut BoundLifetimes) { + tokens_helper(_visitor, &mut (& mut _i . for_token).0); + tokens_helper(_visitor, &mut (& mut _i . lt_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . lifetimes) { let it = el.value_mut(); _visitor.visit_lifetime_def_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . gt_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_const_param_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ConstParam) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . const_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . colon_token).0); + _visitor.visit_type_mut(& mut _i . ty); + if let Some(ref mut it) = _i . eq_token { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . default { _visitor.visit_expr_mut(it) }; +} +# [ cfg ( feature = "derive" ) ] +pub fn visit_data_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Data) { + match *_i { + Data::Struct(ref mut _binding_0, ) => { + _visitor.visit_data_struct_mut(_binding_0); + } + Data::Enum(ref mut _binding_0, ) => { + _visitor.visit_data_enum_mut(_binding_0); + } + Data::Union(ref mut _binding_0, ) => { + _visitor.visit_data_union_mut(_binding_0); + } + } +} +# [ cfg ( feature = "derive" ) ] +pub fn visit_data_enum_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut DataEnum) { + tokens_helper(_visitor, &mut (& mut _i . enum_token).0); + tokens_helper(_visitor, &mut (& mut _i . brace_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . variants) { let it = el.value_mut(); _visitor.visit_variant_mut(it) }; +} +# [ cfg ( feature = "derive" ) ] +pub fn visit_data_struct_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut DataStruct) { + tokens_helper(_visitor, &mut (& mut _i . struct_token).0); + _visitor.visit_fields_mut(& mut _i . fields); + if let Some(ref mut it) = _i . semi_token { tokens_helper(_visitor, &mut (it).0) }; +} +# [ cfg ( feature = "derive" ) ] +pub fn visit_data_union_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut DataUnion) { + tokens_helper(_visitor, &mut (& mut _i . union_token).0); + _visitor.visit_fields_named_mut(& mut _i . fields); +} +# [ cfg ( feature = "derive" ) ] +pub fn visit_derive_input_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut DeriveInput) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_generics_mut(& mut _i . generics); + _visitor.visit_data_mut(& mut _i . data); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Expr) { + match *_i { + Expr::Box(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_box_mut(_binding_0)); + } + Expr::InPlace(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_in_place_mut(_binding_0)); + } + Expr::Array(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_array_mut(_binding_0)); + } + Expr::Call(ref mut _binding_0, ) => { + _visitor.visit_expr_call_mut(_binding_0); + } + Expr::MethodCall(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_method_call_mut(_binding_0)); + } + Expr::Tuple(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_tuple_mut(_binding_0)); + } + Expr::Binary(ref mut _binding_0, ) => { + _visitor.visit_expr_binary_mut(_binding_0); + } + Expr::Unary(ref mut _binding_0, ) => { + _visitor.visit_expr_unary_mut(_binding_0); + } + Expr::Lit(ref mut _binding_0, ) => { + _visitor.visit_expr_lit_mut(_binding_0); + } + Expr::Cast(ref mut _binding_0, ) => { + _visitor.visit_expr_cast_mut(_binding_0); + } + Expr::Type(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_type_mut(_binding_0)); + } + Expr::If(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_if_mut(_binding_0)); + } + Expr::IfLet(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_if_let_mut(_binding_0)); + } + Expr::While(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_while_mut(_binding_0)); + } + Expr::WhileLet(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_while_let_mut(_binding_0)); + } + Expr::ForLoop(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_for_loop_mut(_binding_0)); + } + Expr::Loop(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_loop_mut(_binding_0)); + } + Expr::Match(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_match_mut(_binding_0)); + } + Expr::Closure(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_closure_mut(_binding_0)); + } + Expr::Unsafe(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_unsafe_mut(_binding_0)); + } + Expr::Block(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_block_mut(_binding_0)); + } + Expr::Assign(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_assign_mut(_binding_0)); + } + Expr::AssignOp(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_assign_op_mut(_binding_0)); + } + Expr::Field(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_field_mut(_binding_0)); + } + Expr::Index(ref mut _binding_0, ) => { + _visitor.visit_expr_index_mut(_binding_0); + } + Expr::Range(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_range_mut(_binding_0)); + } + Expr::Path(ref mut _binding_0, ) => { + _visitor.visit_expr_path_mut(_binding_0); + } + Expr::Reference(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_reference_mut(_binding_0)); + } + Expr::Break(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_break_mut(_binding_0)); + } + Expr::Continue(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_continue_mut(_binding_0)); + } + Expr::Return(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_return_mut(_binding_0)); + } + Expr::Macro(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_macro_mut(_binding_0)); + } + Expr::Struct(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_struct_mut(_binding_0)); + } + Expr::Repeat(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_repeat_mut(_binding_0)); + } + Expr::Paren(ref mut _binding_0, ) => { + _visitor.visit_expr_paren_mut(_binding_0); + } + Expr::Group(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_group_mut(_binding_0)); + } + Expr::Try(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_try_mut(_binding_0)); + } + Expr::Catch(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_catch_mut(_binding_0)); + } + Expr::Yield(ref mut _binding_0, ) => { + full!(_visitor.visit_expr_yield_mut(_binding_0)); + } + Expr::Verbatim(ref mut _binding_0, ) => { + _visitor.visit_expr_verbatim_mut(_binding_0); + } + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_array_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprArray) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . bracket_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . elems) { let it = el.value_mut(); _visitor.visit_expr_mut(it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_assign_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprAssign) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_expr_mut(& mut * _i . left); + tokens_helper(_visitor, &mut (& mut _i . eq_token).0); + _visitor.visit_expr_mut(& mut * _i . right); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_assign_op_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprAssignOp) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_expr_mut(& mut * _i . left); + _visitor.visit_bin_op_mut(& mut _i . op); + _visitor.visit_expr_mut(& mut * _i . right); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_binary_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprBinary) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_expr_mut(& mut * _i . left); + _visitor.visit_bin_op_mut(& mut _i . op); + _visitor.visit_expr_mut(& mut * _i . right); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_block_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprBlock) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_block_mut(& mut _i . block); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_box_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprBox) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . box_token).0); + _visitor.visit_expr_mut(& mut * _i . expr); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_break_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprBreak) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . break_token).0); + if let Some(ref mut it) = _i . label { _visitor.visit_lifetime_mut(it) }; + if let Some(ref mut it) = _i . expr { _visitor.visit_expr_mut(& mut * * it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_call_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprCall) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_expr_mut(& mut * _i . func); + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . args) { let it = el.value_mut(); _visitor.visit_expr_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_cast_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprCast) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_expr_mut(& mut * _i . expr); + tokens_helper(_visitor, &mut (& mut _i . as_token).0); + _visitor.visit_type_mut(& mut * _i . ty); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_catch_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprCatch) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . do_token).0); + tokens_helper(_visitor, &mut (& mut _i . catch_token).0); + _visitor.visit_block_mut(& mut _i . block); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_closure_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprClosure) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + if let Some(ref mut it) = _i . movability { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . capture { tokens_helper(_visitor, &mut (it).0) }; + tokens_helper(_visitor, &mut (& mut _i . or1_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . inputs) { let it = el.value_mut(); _visitor.visit_fn_arg_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . or2_token).0); + _visitor.visit_return_type_mut(& mut _i . output); + _visitor.visit_expr_mut(& mut * _i . body); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_continue_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprContinue) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . continue_token).0); + if let Some(ref mut it) = _i . label { _visitor.visit_lifetime_mut(it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_field_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprField) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_expr_mut(& mut * _i . base); + tokens_helper(_visitor, &mut (& mut _i . dot_token).0); + _visitor.visit_member_mut(& mut _i . member); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_for_loop_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprForLoop) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + if let Some(ref mut it) = _i . label { _visitor.visit_label_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . for_token).0); + _visitor.visit_pat_mut(& mut * _i . pat); + tokens_helper(_visitor, &mut (& mut _i . in_token).0); + _visitor.visit_expr_mut(& mut * _i . expr); + _visitor.visit_block_mut(& mut _i . body); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_group_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprGroup) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . group_token).0); + _visitor.visit_expr_mut(& mut * _i . expr); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_if_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprIf) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . if_token).0); + _visitor.visit_expr_mut(& mut * _i . cond); + _visitor.visit_block_mut(& mut _i . then_branch); + if let Some(ref mut it) = _i . else_branch { + tokens_helper(_visitor, &mut (& mut ( it ) . 0).0); + _visitor.visit_expr_mut(& mut * ( it ) . 1); + }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_if_let_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprIfLet) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . if_token).0); + tokens_helper(_visitor, &mut (& mut _i . let_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . pats) { let it = el.value_mut(); _visitor.visit_pat_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . eq_token).0); + _visitor.visit_expr_mut(& mut * _i . expr); + _visitor.visit_block_mut(& mut _i . then_branch); + if let Some(ref mut it) = _i . else_branch { + tokens_helper(_visitor, &mut (& mut ( it ) . 0).0); + _visitor.visit_expr_mut(& mut * ( it ) . 1); + }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_in_place_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprInPlace) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_expr_mut(& mut * _i . place); + tokens_helper(_visitor, &mut (& mut _i . arrow_token).0); + _visitor.visit_expr_mut(& mut * _i . value); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_index_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprIndex) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_expr_mut(& mut * _i . expr); + tokens_helper(_visitor, &mut (& mut _i . bracket_token).0); + _visitor.visit_expr_mut(& mut * _i . index); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_lit_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprLit) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_lit_mut(& mut _i . lit); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_loop_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprLoop) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + if let Some(ref mut it) = _i . label { _visitor.visit_label_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . loop_token).0); + _visitor.visit_block_mut(& mut _i . body); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprMacro) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_macro_mut(& mut _i . mac); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_match_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprMatch) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . match_token).0); + _visitor.visit_expr_mut(& mut * _i . expr); + tokens_helper(_visitor, &mut (& mut _i . brace_token).0); + for it in & mut _i . arms { _visitor.visit_arm_mut(it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_method_call_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprMethodCall) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_expr_mut(& mut * _i . receiver); + tokens_helper(_visitor, &mut (& mut _i . dot_token).0); + _visitor.visit_ident_mut(& mut _i . method); + if let Some(ref mut it) = _i . turbofish { _visitor.visit_method_turbofish_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . args) { let it = el.value_mut(); _visitor.visit_expr_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_paren_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprParen) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + _visitor.visit_expr_mut(& mut * _i . expr); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_path_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprPath) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + if let Some(ref mut it) = _i . qself { _visitor.visit_qself_mut(it) }; + _visitor.visit_path_mut(& mut _i . path); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_range_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprRange) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + if let Some(ref mut it) = _i . from { _visitor.visit_expr_mut(& mut * * it) }; + _visitor.visit_range_limits_mut(& mut _i . limits); + if let Some(ref mut it) = _i . to { _visitor.visit_expr_mut(& mut * * it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_reference_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprReference) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . and_token).0); + if let Some(ref mut it) = _i . mutability { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_expr_mut(& mut * _i . expr); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_repeat_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprRepeat) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . bracket_token).0); + _visitor.visit_expr_mut(& mut * _i . expr); + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); + _visitor.visit_expr_mut(& mut * _i . len); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_return_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprReturn) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . return_token).0); + if let Some(ref mut it) = _i . expr { _visitor.visit_expr_mut(& mut * * it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_struct_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprStruct) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_path_mut(& mut _i . path); + tokens_helper(_visitor, &mut (& mut _i . brace_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . fields) { let it = el.value_mut(); _visitor.visit_field_value_mut(it) }; + if let Some(ref mut it) = _i . dot2_token { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . rest { _visitor.visit_expr_mut(& mut * * it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_try_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprTry) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_expr_mut(& mut * _i . expr); + tokens_helper(_visitor, &mut (& mut _i . question_token).0); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_tuple_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprTuple) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . elems) { let it = el.value_mut(); _visitor.visit_expr_mut(it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprType) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_expr_mut(& mut * _i . expr); + tokens_helper(_visitor, &mut (& mut _i . colon_token).0); + _visitor.visit_type_mut(& mut * _i . ty); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_unary_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprUnary) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_un_op_mut(& mut _i . op); + _visitor.visit_expr_mut(& mut * _i . expr); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_unsafe_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprUnsafe) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . unsafe_token).0); + _visitor.visit_block_mut(& mut _i . block); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_while_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprWhile) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + if let Some(ref mut it) = _i . label { _visitor.visit_label_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . while_token).0); + _visitor.visit_expr_mut(& mut * _i . cond); + _visitor.visit_block_mut(& mut _i . body); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_while_let_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprWhileLet) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + if let Some(ref mut it) = _i . label { _visitor.visit_label_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . while_token).0); + tokens_helper(_visitor, &mut (& mut _i . let_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . pats) { let it = el.value_mut(); _visitor.visit_pat_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . eq_token).0); + _visitor.visit_expr_mut(& mut * _i . expr); + _visitor.visit_block_mut(& mut _i . body); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_yield_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ExprYield) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . yield_token).0); + if let Some(ref mut it) = _i . expr { _visitor.visit_expr_mut(& mut * * it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_field_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Field) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + if let Some(ref mut it) = _i . ident { _visitor.visit_ident_mut(it) }; + if let Some(ref mut it) = _i . colon_token { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_type_mut(& mut _i . ty); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_field_pat_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut FieldPat) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_member_mut(& mut _i . member); + if let Some(ref mut it) = _i . colon_token { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_pat_mut(& mut * _i . pat); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_field_value_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut FieldValue) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_member_mut(& mut _i . member); + if let Some(ref mut it) = _i . colon_token { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_expr_mut(& mut _i . expr); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_fields_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Fields) { + match *_i { + Fields::Named(ref mut _binding_0, ) => { + _visitor.visit_fields_named_mut(_binding_0); + } + Fields::Unnamed(ref mut _binding_0, ) => { + _visitor.visit_fields_unnamed_mut(_binding_0); + } + Fields::Unit => { } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_fields_named_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut FieldsNamed) { + tokens_helper(_visitor, &mut (& mut _i . brace_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . named) { let it = el.value_mut(); _visitor.visit_field_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_fields_unnamed_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut FieldsUnnamed) { + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . unnamed) { let it = el.value_mut(); _visitor.visit_field_mut(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_file_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut File) { + // Skipped field _i . shebang; + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + for it in & mut _i . items { _visitor.visit_item_mut(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_fn_arg_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut FnArg) { + match *_i { + FnArg::SelfRef(ref mut _binding_0, ) => { + _visitor.visit_arg_self_ref_mut(_binding_0); + } + FnArg::SelfValue(ref mut _binding_0, ) => { + _visitor.visit_arg_self_mut(_binding_0); + } + FnArg::Captured(ref mut _binding_0, ) => { + _visitor.visit_arg_captured_mut(_binding_0); + } + FnArg::Inferred(ref mut _binding_0, ) => { + _visitor.visit_pat_mut(_binding_0); + } + FnArg::Ignored(ref mut _binding_0, ) => { + _visitor.visit_type_mut(_binding_0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_fn_decl_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut FnDecl) { + tokens_helper(_visitor, &mut (& mut _i . fn_token).0); + _visitor.visit_generics_mut(& mut _i . generics); + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . inputs) { let it = el.value_mut(); _visitor.visit_fn_arg_mut(it) }; + if let Some(ref mut it) = _i . variadic { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_return_type_mut(& mut _i . output); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_foreign_item_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ForeignItem) { + match *_i { + ForeignItem::Fn(ref mut _binding_0, ) => { + _visitor.visit_foreign_item_fn_mut(_binding_0); + } + ForeignItem::Static(ref mut _binding_0, ) => { + _visitor.visit_foreign_item_static_mut(_binding_0); + } + ForeignItem::Type(ref mut _binding_0, ) => { + _visitor.visit_foreign_item_type_mut(_binding_0); + } + ForeignItem::Verbatim(ref mut _binding_0, ) => { + _visitor.visit_foreign_item_verbatim_mut(_binding_0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_foreign_item_fn_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ForeignItemFn) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_fn_decl_mut(& mut * _i . decl); + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_foreign_item_static_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ForeignItemStatic) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + tokens_helper(_visitor, &mut (& mut _i . static_token).0); + if let Some(ref mut it) = _i . mutability { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . colon_token).0); + _visitor.visit_type_mut(& mut * _i . ty); + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_foreign_item_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ForeignItemType) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + tokens_helper(_visitor, &mut (& mut _i . type_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_foreign_item_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ForeignItemVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_generic_argument_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut GenericArgument) { + match *_i { + GenericArgument::Lifetime(ref mut _binding_0, ) => { + _visitor.visit_lifetime_mut(_binding_0); + } + GenericArgument::Type(ref mut _binding_0, ) => { + _visitor.visit_type_mut(_binding_0); + } + GenericArgument::Binding(ref mut _binding_0, ) => { + _visitor.visit_binding_mut(_binding_0); + } + GenericArgument::Const(ref mut _binding_0, ) => { + _visitor.visit_expr_mut(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_generic_method_argument_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut GenericMethodArgument) { + match *_i { + GenericMethodArgument::Type(ref mut _binding_0, ) => { + _visitor.visit_type_mut(_binding_0); + } + GenericMethodArgument::Const(ref mut _binding_0, ) => { + _visitor.visit_expr_mut(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_generic_param_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut GenericParam) { + match *_i { + GenericParam::Type(ref mut _binding_0, ) => { + _visitor.visit_type_param_mut(_binding_0); + } + GenericParam::Lifetime(ref mut _binding_0, ) => { + _visitor.visit_lifetime_def_mut(_binding_0); + } + GenericParam::Const(ref mut _binding_0, ) => { + _visitor.visit_const_param_mut(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_generics_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Generics) { + if let Some(ref mut it) = _i . lt_token { tokens_helper(_visitor, &mut (it).0) }; + for mut el in Punctuated::pairs_mut(& mut _i . params) { let it = el.value_mut(); _visitor.visit_generic_param_mut(it) }; + if let Some(ref mut it) = _i . gt_token { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . where_clause { _visitor.visit_where_clause_mut(it) }; +} + +pub fn visit_ident_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Ident) { + // Skipped field _i . term; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_impl_item_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ImplItem) { + match *_i { + ImplItem::Const(ref mut _binding_0, ) => { + _visitor.visit_impl_item_const_mut(_binding_0); + } + ImplItem::Method(ref mut _binding_0, ) => { + _visitor.visit_impl_item_method_mut(_binding_0); + } + ImplItem::Type(ref mut _binding_0, ) => { + _visitor.visit_impl_item_type_mut(_binding_0); + } + ImplItem::Macro(ref mut _binding_0, ) => { + _visitor.visit_impl_item_macro_mut(_binding_0); + } + ImplItem::Verbatim(ref mut _binding_0, ) => { + _visitor.visit_impl_item_verbatim_mut(_binding_0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_impl_item_const_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ImplItemConst) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + if let Some(ref mut it) = _i . defaultness { tokens_helper(_visitor, &mut (it).0) }; + tokens_helper(_visitor, &mut (& mut _i . const_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . colon_token).0); + _visitor.visit_type_mut(& mut _i . ty); + tokens_helper(_visitor, &mut (& mut _i . eq_token).0); + _visitor.visit_expr_mut(& mut _i . expr); + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_impl_item_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ImplItemMacro) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_macro_mut(& mut _i . mac); + if let Some(ref mut it) = _i . semi_token { tokens_helper(_visitor, &mut (it).0) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_impl_item_method_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ImplItemMethod) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + if let Some(ref mut it) = _i . defaultness { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_method_sig_mut(& mut _i . sig); + _visitor.visit_block_mut(& mut _i . block); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_impl_item_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ImplItemType) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + if let Some(ref mut it) = _i . defaultness { tokens_helper(_visitor, &mut (it).0) }; + tokens_helper(_visitor, &mut (& mut _i . type_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_generics_mut(& mut _i . generics); + tokens_helper(_visitor, &mut (& mut _i . eq_token).0); + _visitor.visit_type_mut(& mut _i . ty); + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_impl_item_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ImplItemVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_index_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Index) { + // Skipped field _i . index; + _visitor.visit_span_mut(& mut _i . span); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Item) { + match *_i { + Item::ExternCrate(ref mut _binding_0, ) => { + _visitor.visit_item_extern_crate_mut(_binding_0); + } + Item::Use(ref mut _binding_0, ) => { + _visitor.visit_item_use_mut(_binding_0); + } + Item::Static(ref mut _binding_0, ) => { + _visitor.visit_item_static_mut(_binding_0); + } + Item::Const(ref mut _binding_0, ) => { + _visitor.visit_item_const_mut(_binding_0); + } + Item::Fn(ref mut _binding_0, ) => { + _visitor.visit_item_fn_mut(_binding_0); + } + Item::Mod(ref mut _binding_0, ) => { + _visitor.visit_item_mod_mut(_binding_0); + } + Item::ForeignMod(ref mut _binding_0, ) => { + _visitor.visit_item_foreign_mod_mut(_binding_0); + } + Item::Type(ref mut _binding_0, ) => { + _visitor.visit_item_type_mut(_binding_0); + } + Item::Struct(ref mut _binding_0, ) => { + _visitor.visit_item_struct_mut(_binding_0); + } + Item::Enum(ref mut _binding_0, ) => { + _visitor.visit_item_enum_mut(_binding_0); + } + Item::Union(ref mut _binding_0, ) => { + _visitor.visit_item_union_mut(_binding_0); + } + Item::Trait(ref mut _binding_0, ) => { + _visitor.visit_item_trait_mut(_binding_0); + } + Item::Impl(ref mut _binding_0, ) => { + _visitor.visit_item_impl_mut(_binding_0); + } + Item::Macro(ref mut _binding_0, ) => { + _visitor.visit_item_macro_mut(_binding_0); + } + Item::Macro2(ref mut _binding_0, ) => { + _visitor.visit_item_macro2_mut(_binding_0); + } + Item::Verbatim(ref mut _binding_0, ) => { + _visitor.visit_item_verbatim_mut(_binding_0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_const_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemConst) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + tokens_helper(_visitor, &mut (& mut _i . const_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . colon_token).0); + _visitor.visit_type_mut(& mut * _i . ty); + tokens_helper(_visitor, &mut (& mut _i . eq_token).0); + _visitor.visit_expr_mut(& mut * _i . expr); + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_enum_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemEnum) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + tokens_helper(_visitor, &mut (& mut _i . enum_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_generics_mut(& mut _i . generics); + tokens_helper(_visitor, &mut (& mut _i . brace_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . variants) { let it = el.value_mut(); _visitor.visit_variant_mut(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_extern_crate_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemExternCrate) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + tokens_helper(_visitor, &mut (& mut _i . extern_token).0); + tokens_helper(_visitor, &mut (& mut _i . crate_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + if let Some(ref mut it) = _i . rename { + tokens_helper(_visitor, &mut (& mut ( it ) . 0).0); + _visitor.visit_ident_mut(& mut ( it ) . 1); + }; + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_fn_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemFn) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + if let Some(ref mut it) = _i . constness { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . unsafety { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . abi { _visitor.visit_abi_mut(it) }; + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_fn_decl_mut(& mut * _i . decl); + _visitor.visit_block_mut(& mut * _i . block); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_foreign_mod_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemForeignMod) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_abi_mut(& mut _i . abi); + tokens_helper(_visitor, &mut (& mut _i . brace_token).0); + for it in & mut _i . items { _visitor.visit_foreign_item_mut(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_impl_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemImpl) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + if let Some(ref mut it) = _i . defaultness { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . unsafety { tokens_helper(_visitor, &mut (it).0) }; + tokens_helper(_visitor, &mut (& mut _i . impl_token).0); + _visitor.visit_generics_mut(& mut _i . generics); + if let Some(ref mut it) = _i . trait_ { + if let Some(ref mut it) = ( it ) . 0 { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_path_mut(& mut ( it ) . 1); + tokens_helper(_visitor, &mut (& mut ( it ) . 2).0); + }; + _visitor.visit_type_mut(& mut * _i . self_ty); + tokens_helper(_visitor, &mut (& mut _i . brace_token).0); + for it in & mut _i . items { _visitor.visit_impl_item_mut(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemMacro) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + if let Some(ref mut it) = _i . ident { _visitor.visit_ident_mut(it) }; + _visitor.visit_macro_mut(& mut _i . mac); + if let Some(ref mut it) = _i . semi_token { tokens_helper(_visitor, &mut (it).0) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_macro2_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemMacro2) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + tokens_helper(_visitor, &mut (& mut _i . macro_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + // Skipped field _i . args; + tokens_helper(_visitor, &mut (& mut _i . brace_token).0); + // Skipped field _i . body; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_mod_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemMod) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + tokens_helper(_visitor, &mut (& mut _i . mod_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + if let Some(ref mut it) = _i . content { + tokens_helper(_visitor, &mut (& mut ( it ) . 0).0); + for it in & mut ( it ) . 1 { _visitor.visit_item_mut(it) }; + }; + if let Some(ref mut it) = _i . semi { tokens_helper(_visitor, &mut (it).0) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_static_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemStatic) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + tokens_helper(_visitor, &mut (& mut _i . static_token).0); + if let Some(ref mut it) = _i . mutability { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . colon_token).0); + _visitor.visit_type_mut(& mut * _i . ty); + tokens_helper(_visitor, &mut (& mut _i . eq_token).0); + _visitor.visit_expr_mut(& mut * _i . expr); + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_struct_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemStruct) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + tokens_helper(_visitor, &mut (& mut _i . struct_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_generics_mut(& mut _i . generics); + _visitor.visit_fields_mut(& mut _i . fields); + if let Some(ref mut it) = _i . semi_token { tokens_helper(_visitor, &mut (it).0) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_trait_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemTrait) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + if let Some(ref mut it) = _i . unsafety { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . auto_token { tokens_helper(_visitor, &mut (it).0) }; + tokens_helper(_visitor, &mut (& mut _i . trait_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_generics_mut(& mut _i . generics); + if let Some(ref mut it) = _i . colon_token { tokens_helper(_visitor, &mut (it).0) }; + for mut el in Punctuated::pairs_mut(& mut _i . supertraits) { let it = el.value_mut(); _visitor.visit_type_param_bound_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . brace_token).0); + for it in & mut _i . items { _visitor.visit_trait_item_mut(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemType) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + tokens_helper(_visitor, &mut (& mut _i . type_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_generics_mut(& mut _i . generics); + tokens_helper(_visitor, &mut (& mut _i . eq_token).0); + _visitor.visit_type_mut(& mut * _i . ty); + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_union_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemUnion) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + tokens_helper(_visitor, &mut (& mut _i . union_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_generics_mut(& mut _i . generics); + _visitor.visit_fields_named_mut(& mut _i . fields); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_use_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemUse) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_visibility_mut(& mut _i . vis); + tokens_helper(_visitor, &mut (& mut _i . use_token).0); + if let Some(ref mut it) = _i . leading_colon { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_use_tree_mut(& mut _i . tree); + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ItemVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_label_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Label) { + _visitor.visit_lifetime_mut(& mut _i . name); + tokens_helper(_visitor, &mut (& mut _i . colon_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lifetime_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Lifetime) { + // Skipped field _i . term; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lifetime_def_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LifetimeDef) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_lifetime_mut(& mut _i . lifetime); + if let Some(ref mut it) = _i . colon_token { tokens_helper(_visitor, &mut (it).0) }; + for mut el in Punctuated::pairs_mut(& mut _i . bounds) { let it = el.value_mut(); _visitor.visit_lifetime_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Lit) { + match *_i { + Lit::Str(ref mut _binding_0, ) => { + _visitor.visit_lit_str_mut(_binding_0); + } + Lit::ByteStr(ref mut _binding_0, ) => { + _visitor.visit_lit_byte_str_mut(_binding_0); + } + Lit::Byte(ref mut _binding_0, ) => { + _visitor.visit_lit_byte_mut(_binding_0); + } + Lit::Char(ref mut _binding_0, ) => { + _visitor.visit_lit_char_mut(_binding_0); + } + Lit::Int(ref mut _binding_0, ) => { + _visitor.visit_lit_int_mut(_binding_0); + } + Lit::Float(ref mut _binding_0, ) => { + _visitor.visit_lit_float_mut(_binding_0); + } + Lit::Bool(ref mut _binding_0, ) => { + _visitor.visit_lit_bool_mut(_binding_0); + } + Lit::Verbatim(ref mut _binding_0, ) => { + _visitor.visit_lit_verbatim_mut(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_bool_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitBool) { + // Skipped field _i . value; + _visitor.visit_span_mut(& mut _i . span); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_byte_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitByte) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_byte_str_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitByteStr) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_char_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitChar) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_float_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitFloat) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_int_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitInt) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_str_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitStr) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut LitVerbatim) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_local_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Local) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . let_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . pats) { let it = el.value_mut(); _visitor.visit_pat_mut(it) }; + if let Some(ref mut it) = _i . ty { + tokens_helper(_visitor, &mut (& mut ( it ) . 0).0); + _visitor.visit_type_mut(& mut * ( it ) . 1); + }; + if let Some(ref mut it) = _i . init { + tokens_helper(_visitor, &mut (& mut ( it ) . 0).0); + _visitor.visit_expr_mut(& mut * ( it ) . 1); + }; + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Macro) { + _visitor.visit_path_mut(& mut _i . path); + tokens_helper(_visitor, &mut (& mut _i . bang_token).0); + _visitor.visit_macro_delimiter_mut(& mut _i . delimiter); + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_macro_delimiter_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut MacroDelimiter) { + match *_i { + MacroDelimiter::Paren(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + MacroDelimiter::Brace(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + MacroDelimiter::Bracket(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_member_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Member) { + match *_i { + Member::Named(ref mut _binding_0, ) => { + _visitor.visit_ident_mut(_binding_0); + } + Member::Unnamed(ref mut _binding_0, ) => { + _visitor.visit_index_mut(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_meta_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Meta) { + match *_i { + Meta::Word(ref mut _binding_0, ) => { + _visitor.visit_ident_mut(_binding_0); + } + Meta::List(ref mut _binding_0, ) => { + _visitor.visit_meta_list_mut(_binding_0); + } + Meta::NameValue(ref mut _binding_0, ) => { + _visitor.visit_meta_name_value_mut(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_meta_list_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut MetaList) { + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . nested) { let it = el.value_mut(); _visitor.visit_nested_meta_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_meta_name_value_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut MetaNameValue) { + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . eq_token).0); + _visitor.visit_lit_mut(& mut _i . lit); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_method_sig_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut MethodSig) { + if let Some(ref mut it) = _i . constness { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . unsafety { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . abi { _visitor.visit_abi_mut(it) }; + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_fn_decl_mut(& mut _i . decl); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_method_turbofish_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut MethodTurbofish) { + tokens_helper(_visitor, &mut (& mut _i . colon2_token).0); + tokens_helper(_visitor, &mut (& mut _i . lt_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . args) { let it = el.value_mut(); _visitor.visit_generic_method_argument_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . gt_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_nested_meta_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut NestedMeta) { + match *_i { + NestedMeta::Meta(ref mut _binding_0, ) => { + _visitor.visit_meta_mut(_binding_0); + } + NestedMeta::Literal(ref mut _binding_0, ) => { + _visitor.visit_lit_mut(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_parenthesized_generic_arguments_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ParenthesizedGenericArguments) { + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . inputs) { let it = el.value_mut(); _visitor.visit_type_mut(it) }; + _visitor.visit_return_type_mut(& mut _i . output); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Pat) { + match *_i { + Pat::Wild(ref mut _binding_0, ) => { + _visitor.visit_pat_wild_mut(_binding_0); + } + Pat::Ident(ref mut _binding_0, ) => { + _visitor.visit_pat_ident_mut(_binding_0); + } + Pat::Struct(ref mut _binding_0, ) => { + _visitor.visit_pat_struct_mut(_binding_0); + } + Pat::TupleStruct(ref mut _binding_0, ) => { + _visitor.visit_pat_tuple_struct_mut(_binding_0); + } + Pat::Path(ref mut _binding_0, ) => { + _visitor.visit_pat_path_mut(_binding_0); + } + Pat::Tuple(ref mut _binding_0, ) => { + _visitor.visit_pat_tuple_mut(_binding_0); + } + Pat::Box(ref mut _binding_0, ) => { + _visitor.visit_pat_box_mut(_binding_0); + } + Pat::Ref(ref mut _binding_0, ) => { + _visitor.visit_pat_ref_mut(_binding_0); + } + Pat::Lit(ref mut _binding_0, ) => { + _visitor.visit_pat_lit_mut(_binding_0); + } + Pat::Range(ref mut _binding_0, ) => { + _visitor.visit_pat_range_mut(_binding_0); + } + Pat::Slice(ref mut _binding_0, ) => { + _visitor.visit_pat_slice_mut(_binding_0); + } + Pat::Macro(ref mut _binding_0, ) => { + _visitor.visit_pat_macro_mut(_binding_0); + } + Pat::Verbatim(ref mut _binding_0, ) => { + _visitor.visit_pat_verbatim_mut(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_box_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatBox) { + tokens_helper(_visitor, &mut (& mut _i . box_token).0); + _visitor.visit_pat_mut(& mut * _i . pat); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_ident_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatIdent) { + if let Some(ref mut it) = _i . by_ref { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . mutability { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_ident_mut(& mut _i . ident); + if let Some(ref mut it) = _i . subpat { + tokens_helper(_visitor, &mut (& mut ( it ) . 0).0); + _visitor.visit_pat_mut(& mut * ( it ) . 1); + }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_lit_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatLit) { + _visitor.visit_expr_mut(& mut * _i . expr); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatMacro) { + _visitor.visit_macro_mut(& mut _i . mac); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_path_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatPath) { + if let Some(ref mut it) = _i . qself { _visitor.visit_qself_mut(it) }; + _visitor.visit_path_mut(& mut _i . path); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_range_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatRange) { + _visitor.visit_expr_mut(& mut * _i . lo); + _visitor.visit_range_limits_mut(& mut _i . limits); + _visitor.visit_expr_mut(& mut * _i . hi); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_ref_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatRef) { + tokens_helper(_visitor, &mut (& mut _i . and_token).0); + if let Some(ref mut it) = _i . mutability { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_pat_mut(& mut * _i . pat); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_slice_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatSlice) { + tokens_helper(_visitor, &mut (& mut _i . bracket_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . front) { let it = el.value_mut(); _visitor.visit_pat_mut(it) }; + if let Some(ref mut it) = _i . middle { _visitor.visit_pat_mut(& mut * * it) }; + if let Some(ref mut it) = _i . dot2_token { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . comma_token { tokens_helper(_visitor, &mut (it).0) }; + for mut el in Punctuated::pairs_mut(& mut _i . back) { let it = el.value_mut(); _visitor.visit_pat_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_struct_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatStruct) { + _visitor.visit_path_mut(& mut _i . path); + tokens_helper(_visitor, &mut (& mut _i . brace_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . fields) { let it = el.value_mut(); _visitor.visit_field_pat_mut(it) }; + if let Some(ref mut it) = _i . dot2_token { tokens_helper(_visitor, &mut (it).0) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_tuple_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatTuple) { + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . front) { let it = el.value_mut(); _visitor.visit_pat_mut(it) }; + if let Some(ref mut it) = _i . dot2_token { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . comma_token { tokens_helper(_visitor, &mut (it).0) }; + for mut el in Punctuated::pairs_mut(& mut _i . back) { let it = el.value_mut(); _visitor.visit_pat_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_tuple_struct_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatTupleStruct) { + _visitor.visit_path_mut(& mut _i . path); + _visitor.visit_pat_tuple_mut(& mut _i . pat); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_wild_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PatWild) { + tokens_helper(_visitor, &mut (& mut _i . underscore_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_path_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Path) { + if let Some(ref mut it) = _i . leading_colon { tokens_helper(_visitor, &mut (it).0) }; + for mut el in Punctuated::pairs_mut(& mut _i . segments) { let it = el.value_mut(); _visitor.visit_path_segment_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_path_arguments_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PathArguments) { + match *_i { + PathArguments::None => { } + PathArguments::AngleBracketed(ref mut _binding_0, ) => { + _visitor.visit_angle_bracketed_generic_arguments_mut(_binding_0); + } + PathArguments::Parenthesized(ref mut _binding_0, ) => { + _visitor.visit_parenthesized_generic_arguments_mut(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_path_segment_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PathSegment) { + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_path_arguments_mut(& mut _i . arguments); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_predicate_eq_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PredicateEq) { + _visitor.visit_type_mut(& mut _i . lhs_ty); + tokens_helper(_visitor, &mut (& mut _i . eq_token).0); + _visitor.visit_type_mut(& mut _i . rhs_ty); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_predicate_lifetime_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PredicateLifetime) { + _visitor.visit_lifetime_mut(& mut _i . lifetime); + if let Some(ref mut it) = _i . colon_token { tokens_helper(_visitor, &mut (it).0) }; + for mut el in Punctuated::pairs_mut(& mut _i . bounds) { let it = el.value_mut(); _visitor.visit_lifetime_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_predicate_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut PredicateType) { + if let Some(ref mut it) = _i . lifetimes { _visitor.visit_bound_lifetimes_mut(it) }; + _visitor.visit_type_mut(& mut _i . bounded_ty); + tokens_helper(_visitor, &mut (& mut _i . colon_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . bounds) { let it = el.value_mut(); _visitor.visit_type_param_bound_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_qself_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut QSelf) { + tokens_helper(_visitor, &mut (& mut _i . lt_token).0); + _visitor.visit_type_mut(& mut * _i . ty); + // Skipped field _i . position; + if let Some(ref mut it) = _i . as_token { tokens_helper(_visitor, &mut (it).0) }; + tokens_helper(_visitor, &mut (& mut _i . gt_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_range_limits_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut RangeLimits) { + match *_i { + RangeLimits::HalfOpen(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + RangeLimits::Closed(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_return_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut ReturnType) { + match *_i { + ReturnType::Default => { } + ReturnType::Type(ref mut _binding_0, ref mut _binding_1, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + _visitor.visit_type_mut(& mut * * _binding_1); + } + } +} + +pub fn visit_span_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Span) { +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_stmt_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Stmt) { + match *_i { + Stmt::Local(ref mut _binding_0, ) => { + _visitor.visit_local_mut(_binding_0); + } + Stmt::Item(ref mut _binding_0, ) => { + _visitor.visit_item_mut(_binding_0); + } + Stmt::Expr(ref mut _binding_0, ) => { + _visitor.visit_expr_mut(_binding_0); + } + Stmt::Semi(ref mut _binding_0, ref mut _binding_1, ) => { + _visitor.visit_expr_mut(_binding_0); + tokens_helper(_visitor, &mut (_binding_1).0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_trait_bound_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitBound) { + if let Some(ref mut it) = _i . paren_token { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_trait_bound_modifier_mut(& mut _i . modifier); + if let Some(ref mut it) = _i . lifetimes { _visitor.visit_bound_lifetimes_mut(it) }; + _visitor.visit_path_mut(& mut _i . path); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_trait_bound_modifier_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitBoundModifier) { + match *_i { + TraitBoundModifier::None => { } + TraitBoundModifier::Maybe(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_trait_item_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitItem) { + match *_i { + TraitItem::Const(ref mut _binding_0, ) => { + _visitor.visit_trait_item_const_mut(_binding_0); + } + TraitItem::Method(ref mut _binding_0, ) => { + _visitor.visit_trait_item_method_mut(_binding_0); + } + TraitItem::Type(ref mut _binding_0, ) => { + _visitor.visit_trait_item_type_mut(_binding_0); + } + TraitItem::Macro(ref mut _binding_0, ) => { + _visitor.visit_trait_item_macro_mut(_binding_0); + } + TraitItem::Verbatim(ref mut _binding_0, ) => { + _visitor.visit_trait_item_verbatim_mut(_binding_0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_trait_item_const_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitItemConst) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . const_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . colon_token).0); + _visitor.visit_type_mut(& mut _i . ty); + if let Some(ref mut it) = _i . default { + tokens_helper(_visitor, &mut (& mut ( it ) . 0).0); + _visitor.visit_expr_mut(& mut ( it ) . 1); + }; + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_trait_item_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitItemMacro) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_macro_mut(& mut _i . mac); + if let Some(ref mut it) = _i . semi_token { tokens_helper(_visitor, &mut (it).0) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_trait_item_method_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitItemMethod) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_method_sig_mut(& mut _i . sig); + if let Some(ref mut it) = _i . default { _visitor.visit_block_mut(it) }; + if let Some(ref mut it) = _i . semi_token { tokens_helper(_visitor, &mut (it).0) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_trait_item_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitItemType) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . type_token).0); + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_generics_mut(& mut _i . generics); + if let Some(ref mut it) = _i . colon_token { tokens_helper(_visitor, &mut (it).0) }; + for mut el in Punctuated::pairs_mut(& mut _i . bounds) { let it = el.value_mut(); _visitor.visit_type_param_bound_mut(it) }; + if let Some(ref mut it) = _i . default { + tokens_helper(_visitor, &mut (& mut ( it ) . 0).0); + _visitor.visit_type_mut(& mut ( it ) . 1); + }; + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_trait_item_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TraitItemVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Type) { + match *_i { + Type::Slice(ref mut _binding_0, ) => { + _visitor.visit_type_slice_mut(_binding_0); + } + Type::Array(ref mut _binding_0, ) => { + _visitor.visit_type_array_mut(_binding_0); + } + Type::Ptr(ref mut _binding_0, ) => { + _visitor.visit_type_ptr_mut(_binding_0); + } + Type::Reference(ref mut _binding_0, ) => { + _visitor.visit_type_reference_mut(_binding_0); + } + Type::BareFn(ref mut _binding_0, ) => { + _visitor.visit_type_bare_fn_mut(_binding_0); + } + Type::Never(ref mut _binding_0, ) => { + _visitor.visit_type_never_mut(_binding_0); + } + Type::Tuple(ref mut _binding_0, ) => { + _visitor.visit_type_tuple_mut(_binding_0); + } + Type::Path(ref mut _binding_0, ) => { + _visitor.visit_type_path_mut(_binding_0); + } + Type::TraitObject(ref mut _binding_0, ) => { + _visitor.visit_type_trait_object_mut(_binding_0); + } + Type::ImplTrait(ref mut _binding_0, ) => { + _visitor.visit_type_impl_trait_mut(_binding_0); + } + Type::Paren(ref mut _binding_0, ) => { + _visitor.visit_type_paren_mut(_binding_0); + } + Type::Group(ref mut _binding_0, ) => { + _visitor.visit_type_group_mut(_binding_0); + } + Type::Infer(ref mut _binding_0, ) => { + _visitor.visit_type_infer_mut(_binding_0); + } + Type::Macro(ref mut _binding_0, ) => { + _visitor.visit_type_macro_mut(_binding_0); + } + Type::Verbatim(ref mut _binding_0, ) => { + _visitor.visit_type_verbatim_mut(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_array_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeArray) { + tokens_helper(_visitor, &mut (& mut _i . bracket_token).0); + _visitor.visit_type_mut(& mut * _i . elem); + tokens_helper(_visitor, &mut (& mut _i . semi_token).0); + _visitor.visit_expr_mut(& mut _i . len); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_bare_fn_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeBareFn) { + if let Some(ref mut it) = _i . unsafety { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . abi { _visitor.visit_abi_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . fn_token).0); + if let Some(ref mut it) = _i . lifetimes { _visitor.visit_bound_lifetimes_mut(it) }; + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . inputs) { let it = el.value_mut(); _visitor.visit_bare_fn_arg_mut(it) }; + if let Some(ref mut it) = _i . variadic { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_return_type_mut(& mut _i . output); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_group_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeGroup) { + tokens_helper(_visitor, &mut (& mut _i . group_token).0); + _visitor.visit_type_mut(& mut * _i . elem); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_impl_trait_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeImplTrait) { + tokens_helper(_visitor, &mut (& mut _i . impl_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . bounds) { let it = el.value_mut(); _visitor.visit_type_param_bound_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_infer_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeInfer) { + tokens_helper(_visitor, &mut (& mut _i . underscore_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_macro_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeMacro) { + _visitor.visit_macro_mut(& mut _i . mac); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_never_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeNever) { + tokens_helper(_visitor, &mut (& mut _i . bang_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_param_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeParam) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_ident_mut(& mut _i . ident); + if let Some(ref mut it) = _i . colon_token { tokens_helper(_visitor, &mut (it).0) }; + for mut el in Punctuated::pairs_mut(& mut _i . bounds) { let it = el.value_mut(); _visitor.visit_type_param_bound_mut(it) }; + if let Some(ref mut it) = _i . eq_token { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . default { _visitor.visit_type_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_param_bound_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeParamBound) { + match *_i { + TypeParamBound::Trait(ref mut _binding_0, ) => { + _visitor.visit_trait_bound_mut(_binding_0); + } + TypeParamBound::Lifetime(ref mut _binding_0, ) => { + _visitor.visit_lifetime_mut(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_paren_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeParen) { + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + _visitor.visit_type_mut(& mut * _i . elem); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_path_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypePath) { + if let Some(ref mut it) = _i . qself { _visitor.visit_qself_mut(it) }; + _visitor.visit_path_mut(& mut _i . path); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_ptr_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypePtr) { + tokens_helper(_visitor, &mut (& mut _i . star_token).0); + if let Some(ref mut it) = _i . const_token { tokens_helper(_visitor, &mut (it).0) }; + if let Some(ref mut it) = _i . mutability { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_type_mut(& mut * _i . elem); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_reference_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeReference) { + tokens_helper(_visitor, &mut (& mut _i . and_token).0); + if let Some(ref mut it) = _i . lifetime { _visitor.visit_lifetime_mut(it) }; + if let Some(ref mut it) = _i . mutability { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_type_mut(& mut * _i . elem); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_slice_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeSlice) { + tokens_helper(_visitor, &mut (& mut _i . bracket_token).0); + _visitor.visit_type_mut(& mut * _i . elem); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_trait_object_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeTraitObject) { + if let Some(ref mut it) = _i . dyn_token { tokens_helper(_visitor, &mut (it).0) }; + for mut el in Punctuated::pairs_mut(& mut _i . bounds) { let it = el.value_mut(); _visitor.visit_type_param_bound_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_tuple_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeTuple) { + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . elems) { let it = el.value_mut(); _visitor.visit_type_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_verbatim_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut TypeVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_un_op_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UnOp) { + match *_i { + UnOp::Deref(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + UnOp::Not(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + UnOp::Neg(ref mut _binding_0, ) => { + tokens_helper(_visitor, &mut (_binding_0).0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_use_glob_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UseGlob) { + tokens_helper(_visitor, &mut (& mut _i . star_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_use_group_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UseGroup) { + tokens_helper(_visitor, &mut (& mut _i . brace_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . items) { let it = el.value_mut(); _visitor.visit_use_tree_mut(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_use_name_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UseName) { + _visitor.visit_ident_mut(& mut _i . ident); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_use_path_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UsePath) { + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . colon2_token).0); + _visitor.visit_use_tree_mut(& mut * _i . tree); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_use_rename_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UseRename) { + _visitor.visit_ident_mut(& mut _i . ident); + tokens_helper(_visitor, &mut (& mut _i . as_token).0); + _visitor.visit_ident_mut(& mut _i . rename); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_use_tree_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut UseTree) { + match *_i { + UseTree::Path(ref mut _binding_0, ) => { + _visitor.visit_use_path_mut(_binding_0); + } + UseTree::Name(ref mut _binding_0, ) => { + _visitor.visit_use_name_mut(_binding_0); + } + UseTree::Rename(ref mut _binding_0, ) => { + _visitor.visit_use_rename_mut(_binding_0); + } + UseTree::Glob(ref mut _binding_0, ) => { + _visitor.visit_use_glob_mut(_binding_0); + } + UseTree::Group(ref mut _binding_0, ) => { + _visitor.visit_use_group_mut(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_variant_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Variant) { + for it in & mut _i . attrs { _visitor.visit_attribute_mut(it) }; + _visitor.visit_ident_mut(& mut _i . ident); + _visitor.visit_fields_mut(& mut _i . fields); + if let Some(ref mut it) = _i . discriminant { + tokens_helper(_visitor, &mut (& mut ( it ) . 0).0); + _visitor.visit_expr_mut(& mut ( it ) . 1); + }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_vis_crate_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut VisCrate) { + tokens_helper(_visitor, &mut (& mut _i . crate_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_vis_public_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut VisPublic) { + tokens_helper(_visitor, &mut (& mut _i . pub_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_vis_restricted_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut VisRestricted) { + tokens_helper(_visitor, &mut (& mut _i . pub_token).0); + tokens_helper(_visitor, &mut (& mut _i . paren_token).0); + if let Some(ref mut it) = _i . in_token { tokens_helper(_visitor, &mut (it).0) }; + _visitor.visit_path_mut(& mut * _i . path); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_visibility_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut Visibility) { + match *_i { + Visibility::Public(ref mut _binding_0, ) => { + _visitor.visit_vis_public_mut(_binding_0); + } + Visibility::Crate(ref mut _binding_0, ) => { + _visitor.visit_vis_crate_mut(_binding_0); + } + Visibility::Restricted(ref mut _binding_0, ) => { + _visitor.visit_vis_restricted_mut(_binding_0); + } + Visibility::Inherited => { } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_where_clause_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut WhereClause) { + tokens_helper(_visitor, &mut (& mut _i . where_token).0); + for mut el in Punctuated::pairs_mut(& mut _i . predicates) { let it = el.value_mut(); _visitor.visit_where_predicate_mut(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_where_predicate_mut<V: VisitMut + ?Sized>(_visitor: &mut V, _i: &mut WherePredicate) { + match *_i { + WherePredicate::Type(ref mut _binding_0, ) => { + _visitor.visit_predicate_type_mut(_binding_0); + } + WherePredicate::Lifetime(ref mut _binding_0, ) => { + _visitor.visit_predicate_lifetime_mut(_binding_0); + } + WherePredicate::Eq(ref mut _binding_0, ) => { + _visitor.visit_predicate_eq_mut(_binding_0); + } + } +} + diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/gen/visit.rs cargo-0.26.0/vendor/syn-0.13.1/src/gen/visit.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/gen/visit.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/gen/visit.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2287 @@ +// THIS FILE IS AUTOMATICALLY GENERATED; DO NOT EDIT + +#![cfg_attr(rustfmt, rustfmt_skip)] + +#![cfg_attr(feature = "cargo-clippy", allow(match_same_arms))] + +use *; +#[cfg(any(feature = "full", feature = "derive"))] +use punctuated::Punctuated; +use proc_macro2::Span; +#[cfg(any(feature = "full", feature = "derive"))] +use gen::helper::visit::*; + + +#[cfg(feature = "full")] +macro_rules! full { + ($e:expr) => { $e } +} + +#[cfg(all(feature = "derive", not(feature = "full")))] +macro_rules! full { + ($e:expr) => { unreachable!() } +} + + +/// Syntax tree traversal to walk a shared borrow of a syntax tree. +/// +/// See the [module documentation] for details. +/// +/// [module documentation]: index.html +/// +/// *This trait is available if Syn is built with the `"visit"` feature.* +pub trait Visit<'ast> { +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_abi(&mut self, i: &'ast Abi) { visit_abi(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_angle_bracketed_generic_arguments(&mut self, i: &'ast AngleBracketedGenericArguments) { visit_angle_bracketed_generic_arguments(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_arg_captured(&mut self, i: &'ast ArgCaptured) { visit_arg_captured(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_arg_self(&mut self, i: &'ast ArgSelf) { visit_arg_self(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_arg_self_ref(&mut self, i: &'ast ArgSelfRef) { visit_arg_self_ref(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_arm(&mut self, i: &'ast Arm) { visit_arm(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_attr_style(&mut self, i: &'ast AttrStyle) { visit_attr_style(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_attribute(&mut self, i: &'ast Attribute) { visit_attribute(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_bare_fn_arg(&mut self, i: &'ast BareFnArg) { visit_bare_fn_arg(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_bare_fn_arg_name(&mut self, i: &'ast BareFnArgName) { visit_bare_fn_arg_name(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_bin_op(&mut self, i: &'ast BinOp) { visit_bin_op(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_binding(&mut self, i: &'ast Binding) { visit_binding(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_block(&mut self, i: &'ast Block) { visit_block(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_bound_lifetimes(&mut self, i: &'ast BoundLifetimes) { visit_bound_lifetimes(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_const_param(&mut self, i: &'ast ConstParam) { visit_const_param(self, i) } +# [ cfg ( feature = "derive" ) ] +fn visit_data(&mut self, i: &'ast Data) { visit_data(self, i) } +# [ cfg ( feature = "derive" ) ] +fn visit_data_enum(&mut self, i: &'ast DataEnum) { visit_data_enum(self, i) } +# [ cfg ( feature = "derive" ) ] +fn visit_data_struct(&mut self, i: &'ast DataStruct) { visit_data_struct(self, i) } +# [ cfg ( feature = "derive" ) ] +fn visit_data_union(&mut self, i: &'ast DataUnion) { visit_data_union(self, i) } +# [ cfg ( feature = "derive" ) ] +fn visit_derive_input(&mut self, i: &'ast DeriveInput) { visit_derive_input(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr(&mut self, i: &'ast Expr) { visit_expr(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_array(&mut self, i: &'ast ExprArray) { visit_expr_array(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_assign(&mut self, i: &'ast ExprAssign) { visit_expr_assign(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_assign_op(&mut self, i: &'ast ExprAssignOp) { visit_expr_assign_op(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_binary(&mut self, i: &'ast ExprBinary) { visit_expr_binary(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_block(&mut self, i: &'ast ExprBlock) { visit_expr_block(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_box(&mut self, i: &'ast ExprBox) { visit_expr_box(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_break(&mut self, i: &'ast ExprBreak) { visit_expr_break(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_call(&mut self, i: &'ast ExprCall) { visit_expr_call(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_cast(&mut self, i: &'ast ExprCast) { visit_expr_cast(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_catch(&mut self, i: &'ast ExprCatch) { visit_expr_catch(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_closure(&mut self, i: &'ast ExprClosure) { visit_expr_closure(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_continue(&mut self, i: &'ast ExprContinue) { visit_expr_continue(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_field(&mut self, i: &'ast ExprField) { visit_expr_field(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_for_loop(&mut self, i: &'ast ExprForLoop) { visit_expr_for_loop(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_group(&mut self, i: &'ast ExprGroup) { visit_expr_group(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_if(&mut self, i: &'ast ExprIf) { visit_expr_if(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_if_let(&mut self, i: &'ast ExprIfLet) { visit_expr_if_let(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_in_place(&mut self, i: &'ast ExprInPlace) { visit_expr_in_place(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_index(&mut self, i: &'ast ExprIndex) { visit_expr_index(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_lit(&mut self, i: &'ast ExprLit) { visit_expr_lit(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_loop(&mut self, i: &'ast ExprLoop) { visit_expr_loop(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_macro(&mut self, i: &'ast ExprMacro) { visit_expr_macro(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_match(&mut self, i: &'ast ExprMatch) { visit_expr_match(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_method_call(&mut self, i: &'ast ExprMethodCall) { visit_expr_method_call(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_paren(&mut self, i: &'ast ExprParen) { visit_expr_paren(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_path(&mut self, i: &'ast ExprPath) { visit_expr_path(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_range(&mut self, i: &'ast ExprRange) { visit_expr_range(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_reference(&mut self, i: &'ast ExprReference) { visit_expr_reference(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_repeat(&mut self, i: &'ast ExprRepeat) { visit_expr_repeat(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_return(&mut self, i: &'ast ExprReturn) { visit_expr_return(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_struct(&mut self, i: &'ast ExprStruct) { visit_expr_struct(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_try(&mut self, i: &'ast ExprTry) { visit_expr_try(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_tuple(&mut self, i: &'ast ExprTuple) { visit_expr_tuple(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_type(&mut self, i: &'ast ExprType) { visit_expr_type(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_unary(&mut self, i: &'ast ExprUnary) { visit_expr_unary(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_unsafe(&mut self, i: &'ast ExprUnsafe) { visit_expr_unsafe(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_verbatim(&mut self, i: &'ast ExprVerbatim) { visit_expr_verbatim(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_while(&mut self, i: &'ast ExprWhile) { visit_expr_while(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_while_let(&mut self, i: &'ast ExprWhileLet) { visit_expr_while_let(self, i) } +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_expr_yield(&mut self, i: &'ast ExprYield) { visit_expr_yield(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_field(&mut self, i: &'ast Field) { visit_field(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_field_pat(&mut self, i: &'ast FieldPat) { visit_field_pat(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_field_value(&mut self, i: &'ast FieldValue) { visit_field_value(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_fields(&mut self, i: &'ast Fields) { visit_fields(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_fields_named(&mut self, i: &'ast FieldsNamed) { visit_fields_named(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_fields_unnamed(&mut self, i: &'ast FieldsUnnamed) { visit_fields_unnamed(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_file(&mut self, i: &'ast File) { visit_file(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_fn_arg(&mut self, i: &'ast FnArg) { visit_fn_arg(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_fn_decl(&mut self, i: &'ast FnDecl) { visit_fn_decl(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_foreign_item(&mut self, i: &'ast ForeignItem) { visit_foreign_item(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_foreign_item_fn(&mut self, i: &'ast ForeignItemFn) { visit_foreign_item_fn(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_foreign_item_static(&mut self, i: &'ast ForeignItemStatic) { visit_foreign_item_static(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_foreign_item_type(&mut self, i: &'ast ForeignItemType) { visit_foreign_item_type(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_foreign_item_verbatim(&mut self, i: &'ast ForeignItemVerbatim) { visit_foreign_item_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_generic_argument(&mut self, i: &'ast GenericArgument) { visit_generic_argument(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_generic_method_argument(&mut self, i: &'ast GenericMethodArgument) { visit_generic_method_argument(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_generic_param(&mut self, i: &'ast GenericParam) { visit_generic_param(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_generics(&mut self, i: &'ast Generics) { visit_generics(self, i) } + +fn visit_ident(&mut self, i: &'ast Ident) { visit_ident(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_impl_item(&mut self, i: &'ast ImplItem) { visit_impl_item(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_impl_item_const(&mut self, i: &'ast ImplItemConst) { visit_impl_item_const(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_impl_item_macro(&mut self, i: &'ast ImplItemMacro) { visit_impl_item_macro(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_impl_item_method(&mut self, i: &'ast ImplItemMethod) { visit_impl_item_method(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_impl_item_type(&mut self, i: &'ast ImplItemType) { visit_impl_item_type(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_impl_item_verbatim(&mut self, i: &'ast ImplItemVerbatim) { visit_impl_item_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_index(&mut self, i: &'ast Index) { visit_index(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item(&mut self, i: &'ast Item) { visit_item(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_const(&mut self, i: &'ast ItemConst) { visit_item_const(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_enum(&mut self, i: &'ast ItemEnum) { visit_item_enum(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_extern_crate(&mut self, i: &'ast ItemExternCrate) { visit_item_extern_crate(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_fn(&mut self, i: &'ast ItemFn) { visit_item_fn(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_foreign_mod(&mut self, i: &'ast ItemForeignMod) { visit_item_foreign_mod(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_impl(&mut self, i: &'ast ItemImpl) { visit_item_impl(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_macro(&mut self, i: &'ast ItemMacro) { visit_item_macro(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_macro2(&mut self, i: &'ast ItemMacro2) { visit_item_macro2(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_mod(&mut self, i: &'ast ItemMod) { visit_item_mod(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_static(&mut self, i: &'ast ItemStatic) { visit_item_static(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_struct(&mut self, i: &'ast ItemStruct) { visit_item_struct(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_trait(&mut self, i: &'ast ItemTrait) { visit_item_trait(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_type(&mut self, i: &'ast ItemType) { visit_item_type(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_union(&mut self, i: &'ast ItemUnion) { visit_item_union(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_use(&mut self, i: &'ast ItemUse) { visit_item_use(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_item_verbatim(&mut self, i: &'ast ItemVerbatim) { visit_item_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_label(&mut self, i: &'ast Label) { visit_label(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lifetime(&mut self, i: &'ast Lifetime) { visit_lifetime(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lifetime_def(&mut self, i: &'ast LifetimeDef) { visit_lifetime_def(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit(&mut self, i: &'ast Lit) { visit_lit(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_bool(&mut self, i: &'ast LitBool) { visit_lit_bool(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_byte(&mut self, i: &'ast LitByte) { visit_lit_byte(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_byte_str(&mut self, i: &'ast LitByteStr) { visit_lit_byte_str(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_char(&mut self, i: &'ast LitChar) { visit_lit_char(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_float(&mut self, i: &'ast LitFloat) { visit_lit_float(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_int(&mut self, i: &'ast LitInt) { visit_lit_int(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_str(&mut self, i: &'ast LitStr) { visit_lit_str(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_lit_verbatim(&mut self, i: &'ast LitVerbatim) { visit_lit_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_local(&mut self, i: &'ast Local) { visit_local(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_macro(&mut self, i: &'ast Macro) { visit_macro(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_macro_delimiter(&mut self, i: &'ast MacroDelimiter) { visit_macro_delimiter(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_member(&mut self, i: &'ast Member) { visit_member(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_meta(&mut self, i: &'ast Meta) { visit_meta(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_meta_list(&mut self, i: &'ast MetaList) { visit_meta_list(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_meta_name_value(&mut self, i: &'ast MetaNameValue) { visit_meta_name_value(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_method_sig(&mut self, i: &'ast MethodSig) { visit_method_sig(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_method_turbofish(&mut self, i: &'ast MethodTurbofish) { visit_method_turbofish(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_nested_meta(&mut self, i: &'ast NestedMeta) { visit_nested_meta(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_parenthesized_generic_arguments(&mut self, i: &'ast ParenthesizedGenericArguments) { visit_parenthesized_generic_arguments(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat(&mut self, i: &'ast Pat) { visit_pat(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_box(&mut self, i: &'ast PatBox) { visit_pat_box(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_ident(&mut self, i: &'ast PatIdent) { visit_pat_ident(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_lit(&mut self, i: &'ast PatLit) { visit_pat_lit(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_macro(&mut self, i: &'ast PatMacro) { visit_pat_macro(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_path(&mut self, i: &'ast PatPath) { visit_pat_path(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_range(&mut self, i: &'ast PatRange) { visit_pat_range(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_ref(&mut self, i: &'ast PatRef) { visit_pat_ref(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_slice(&mut self, i: &'ast PatSlice) { visit_pat_slice(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_struct(&mut self, i: &'ast PatStruct) { visit_pat_struct(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_tuple(&mut self, i: &'ast PatTuple) { visit_pat_tuple(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_tuple_struct(&mut self, i: &'ast PatTupleStruct) { visit_pat_tuple_struct(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_verbatim(&mut self, i: &'ast PatVerbatim) { visit_pat_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_pat_wild(&mut self, i: &'ast PatWild) { visit_pat_wild(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_path(&mut self, i: &'ast Path) { visit_path(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_path_arguments(&mut self, i: &'ast PathArguments) { visit_path_arguments(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_path_segment(&mut self, i: &'ast PathSegment) { visit_path_segment(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_predicate_eq(&mut self, i: &'ast PredicateEq) { visit_predicate_eq(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_predicate_lifetime(&mut self, i: &'ast PredicateLifetime) { visit_predicate_lifetime(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_predicate_type(&mut self, i: &'ast PredicateType) { visit_predicate_type(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_qself(&mut self, i: &'ast QSelf) { visit_qself(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_range_limits(&mut self, i: &'ast RangeLimits) { visit_range_limits(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_return_type(&mut self, i: &'ast ReturnType) { visit_return_type(self, i) } + +fn visit_span(&mut self, i: &'ast Span) { visit_span(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +fn visit_stmt(&mut self, i: &'ast Stmt) { visit_stmt(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_trait_bound(&mut self, i: &'ast TraitBound) { visit_trait_bound(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_trait_bound_modifier(&mut self, i: &'ast TraitBoundModifier) { visit_trait_bound_modifier(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_trait_item(&mut self, i: &'ast TraitItem) { visit_trait_item(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_trait_item_const(&mut self, i: &'ast TraitItemConst) { visit_trait_item_const(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_trait_item_macro(&mut self, i: &'ast TraitItemMacro) { visit_trait_item_macro(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_trait_item_method(&mut self, i: &'ast TraitItemMethod) { visit_trait_item_method(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_trait_item_type(&mut self, i: &'ast TraitItemType) { visit_trait_item_type(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_trait_item_verbatim(&mut self, i: &'ast TraitItemVerbatim) { visit_trait_item_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type(&mut self, i: &'ast Type) { visit_type(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_array(&mut self, i: &'ast TypeArray) { visit_type_array(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_bare_fn(&mut self, i: &'ast TypeBareFn) { visit_type_bare_fn(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_group(&mut self, i: &'ast TypeGroup) { visit_type_group(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_impl_trait(&mut self, i: &'ast TypeImplTrait) { visit_type_impl_trait(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_infer(&mut self, i: &'ast TypeInfer) { visit_type_infer(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_macro(&mut self, i: &'ast TypeMacro) { visit_type_macro(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_never(&mut self, i: &'ast TypeNever) { visit_type_never(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_param(&mut self, i: &'ast TypeParam) { visit_type_param(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_param_bound(&mut self, i: &'ast TypeParamBound) { visit_type_param_bound(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_paren(&mut self, i: &'ast TypeParen) { visit_type_paren(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_path(&mut self, i: &'ast TypePath) { visit_type_path(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_ptr(&mut self, i: &'ast TypePtr) { visit_type_ptr(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_reference(&mut self, i: &'ast TypeReference) { visit_type_reference(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_slice(&mut self, i: &'ast TypeSlice) { visit_type_slice(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_trait_object(&mut self, i: &'ast TypeTraitObject) { visit_type_trait_object(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_tuple(&mut self, i: &'ast TypeTuple) { visit_type_tuple(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_type_verbatim(&mut self, i: &'ast TypeVerbatim) { visit_type_verbatim(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_un_op(&mut self, i: &'ast UnOp) { visit_un_op(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_use_glob(&mut self, i: &'ast UseGlob) { visit_use_glob(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_use_group(&mut self, i: &'ast UseGroup) { visit_use_group(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_use_name(&mut self, i: &'ast UseName) { visit_use_name(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_use_path(&mut self, i: &'ast UsePath) { visit_use_path(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_use_rename(&mut self, i: &'ast UseRename) { visit_use_rename(self, i) } +# [ cfg ( feature = "full" ) ] +fn visit_use_tree(&mut self, i: &'ast UseTree) { visit_use_tree(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_variant(&mut self, i: &'ast Variant) { visit_variant(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_vis_crate(&mut self, i: &'ast VisCrate) { visit_vis_crate(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_vis_public(&mut self, i: &'ast VisPublic) { visit_vis_public(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_vis_restricted(&mut self, i: &'ast VisRestricted) { visit_vis_restricted(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_visibility(&mut self, i: &'ast Visibility) { visit_visibility(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_where_clause(&mut self, i: &'ast WhereClause) { visit_where_clause(self, i) } +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +fn visit_where_predicate(&mut self, i: &'ast WherePredicate) { visit_where_predicate(self, i) } + +} + +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_abi<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Abi) { + tokens_helper(_visitor, &(& _i . extern_token).0); + if let Some(ref it) = _i . name { _visitor.visit_lit_str(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_angle_bracketed_generic_arguments<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast AngleBracketedGenericArguments) { + if let Some(ref it) = _i . colon2_token { tokens_helper(_visitor, &(it).0) }; + tokens_helper(_visitor, &(& _i . lt_token).0); + for el in Punctuated::pairs(& _i . args) { let it = el.value(); _visitor.visit_generic_argument(it) }; + tokens_helper(_visitor, &(& _i . gt_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_arg_captured<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ArgCaptured) { + _visitor.visit_pat(& _i . pat); + tokens_helper(_visitor, &(& _i . colon_token).0); + _visitor.visit_type(& _i . ty); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_arg_self<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ArgSelf) { + if let Some(ref it) = _i . mutability { tokens_helper(_visitor, &(it).0) }; + tokens_helper(_visitor, &(& _i . self_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_arg_self_ref<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ArgSelfRef) { + tokens_helper(_visitor, &(& _i . and_token).0); + if let Some(ref it) = _i . lifetime { _visitor.visit_lifetime(it) }; + if let Some(ref it) = _i . mutability { tokens_helper(_visitor, &(it).0) }; + tokens_helper(_visitor, &(& _i . self_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_arm<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Arm) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + if let Some(ref it) = _i . leading_vert { tokens_helper(_visitor, &(it).0) }; + for el in Punctuated::pairs(& _i . pats) { let it = el.value(); _visitor.visit_pat(it) }; + if let Some(ref it) = _i . guard { + tokens_helper(_visitor, &(& ( it ) . 0).0); + _visitor.visit_expr(& * ( it ) . 1); + }; + tokens_helper(_visitor, &(& _i . fat_arrow_token).0); + _visitor.visit_expr(& * _i . body); + if let Some(ref it) = _i . comma { tokens_helper(_visitor, &(it).0) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_attr_style<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast AttrStyle) { + match *_i { + AttrStyle::Outer => { } + AttrStyle::Inner(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_attribute<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Attribute) { + tokens_helper(_visitor, &(& _i . pound_token).0); + _visitor.visit_attr_style(& _i . style); + tokens_helper(_visitor, &(& _i . bracket_token).0); + _visitor.visit_path(& _i . path); + // Skipped field _i . tts; + // Skipped field _i . is_sugared_doc; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_bare_fn_arg<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast BareFnArg) { + if let Some(ref it) = _i . name { + _visitor.visit_bare_fn_arg_name(& ( it ) . 0); + tokens_helper(_visitor, &(& ( it ) . 1).0); + }; + _visitor.visit_type(& _i . ty); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_bare_fn_arg_name<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast BareFnArgName) { + match *_i { + BareFnArgName::Named(ref _binding_0, ) => { + _visitor.visit_ident(_binding_0); + } + BareFnArgName::Wild(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_bin_op<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast BinOp) { + match *_i { + BinOp::Add(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Sub(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Mul(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Div(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Rem(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::And(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Or(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::BitXor(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::BitAnd(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::BitOr(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Shl(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Shr(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Eq(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Lt(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Le(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Ne(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Ge(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::Gt(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::AddEq(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::SubEq(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::MulEq(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::DivEq(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::RemEq(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::BitXorEq(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::BitAndEq(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::BitOrEq(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::ShlEq(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + BinOp::ShrEq(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_binding<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Binding) { + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . eq_token).0); + _visitor.visit_type(& _i . ty); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_block<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Block) { + tokens_helper(_visitor, &(& _i . brace_token).0); + for it in & _i . stmts { _visitor.visit_stmt(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_bound_lifetimes<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast BoundLifetimes) { + tokens_helper(_visitor, &(& _i . for_token).0); + tokens_helper(_visitor, &(& _i . lt_token).0); + for el in Punctuated::pairs(& _i . lifetimes) { let it = el.value(); _visitor.visit_lifetime_def(it) }; + tokens_helper(_visitor, &(& _i . gt_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_const_param<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ConstParam) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . const_token).0); + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . colon_token).0); + _visitor.visit_type(& _i . ty); + if let Some(ref it) = _i . eq_token { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . default { _visitor.visit_expr(it) }; +} +# [ cfg ( feature = "derive" ) ] +pub fn visit_data<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Data) { + match *_i { + Data::Struct(ref _binding_0, ) => { + _visitor.visit_data_struct(_binding_0); + } + Data::Enum(ref _binding_0, ) => { + _visitor.visit_data_enum(_binding_0); + } + Data::Union(ref _binding_0, ) => { + _visitor.visit_data_union(_binding_0); + } + } +} +# [ cfg ( feature = "derive" ) ] +pub fn visit_data_enum<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast DataEnum) { + tokens_helper(_visitor, &(& _i . enum_token).0); + tokens_helper(_visitor, &(& _i . brace_token).0); + for el in Punctuated::pairs(& _i . variants) { let it = el.value(); _visitor.visit_variant(it) }; +} +# [ cfg ( feature = "derive" ) ] +pub fn visit_data_struct<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast DataStruct) { + tokens_helper(_visitor, &(& _i . struct_token).0); + _visitor.visit_fields(& _i . fields); + if let Some(ref it) = _i . semi_token { tokens_helper(_visitor, &(it).0) }; +} +# [ cfg ( feature = "derive" ) ] +pub fn visit_data_union<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast DataUnion) { + tokens_helper(_visitor, &(& _i . union_token).0); + _visitor.visit_fields_named(& _i . fields); +} +# [ cfg ( feature = "derive" ) ] +pub fn visit_derive_input<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast DeriveInput) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + _visitor.visit_ident(& _i . ident); + _visitor.visit_generics(& _i . generics); + _visitor.visit_data(& _i . data); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Expr) { + match *_i { + Expr::Box(ref _binding_0, ) => { + full!(_visitor.visit_expr_box(_binding_0)); + } + Expr::InPlace(ref _binding_0, ) => { + full!(_visitor.visit_expr_in_place(_binding_0)); + } + Expr::Array(ref _binding_0, ) => { + full!(_visitor.visit_expr_array(_binding_0)); + } + Expr::Call(ref _binding_0, ) => { + _visitor.visit_expr_call(_binding_0); + } + Expr::MethodCall(ref _binding_0, ) => { + full!(_visitor.visit_expr_method_call(_binding_0)); + } + Expr::Tuple(ref _binding_0, ) => { + full!(_visitor.visit_expr_tuple(_binding_0)); + } + Expr::Binary(ref _binding_0, ) => { + _visitor.visit_expr_binary(_binding_0); + } + Expr::Unary(ref _binding_0, ) => { + _visitor.visit_expr_unary(_binding_0); + } + Expr::Lit(ref _binding_0, ) => { + _visitor.visit_expr_lit(_binding_0); + } + Expr::Cast(ref _binding_0, ) => { + _visitor.visit_expr_cast(_binding_0); + } + Expr::Type(ref _binding_0, ) => { + full!(_visitor.visit_expr_type(_binding_0)); + } + Expr::If(ref _binding_0, ) => { + full!(_visitor.visit_expr_if(_binding_0)); + } + Expr::IfLet(ref _binding_0, ) => { + full!(_visitor.visit_expr_if_let(_binding_0)); + } + Expr::While(ref _binding_0, ) => { + full!(_visitor.visit_expr_while(_binding_0)); + } + Expr::WhileLet(ref _binding_0, ) => { + full!(_visitor.visit_expr_while_let(_binding_0)); + } + Expr::ForLoop(ref _binding_0, ) => { + full!(_visitor.visit_expr_for_loop(_binding_0)); + } + Expr::Loop(ref _binding_0, ) => { + full!(_visitor.visit_expr_loop(_binding_0)); + } + Expr::Match(ref _binding_0, ) => { + full!(_visitor.visit_expr_match(_binding_0)); + } + Expr::Closure(ref _binding_0, ) => { + full!(_visitor.visit_expr_closure(_binding_0)); + } + Expr::Unsafe(ref _binding_0, ) => { + full!(_visitor.visit_expr_unsafe(_binding_0)); + } + Expr::Block(ref _binding_0, ) => { + full!(_visitor.visit_expr_block(_binding_0)); + } + Expr::Assign(ref _binding_0, ) => { + full!(_visitor.visit_expr_assign(_binding_0)); + } + Expr::AssignOp(ref _binding_0, ) => { + full!(_visitor.visit_expr_assign_op(_binding_0)); + } + Expr::Field(ref _binding_0, ) => { + full!(_visitor.visit_expr_field(_binding_0)); + } + Expr::Index(ref _binding_0, ) => { + _visitor.visit_expr_index(_binding_0); + } + Expr::Range(ref _binding_0, ) => { + full!(_visitor.visit_expr_range(_binding_0)); + } + Expr::Path(ref _binding_0, ) => { + _visitor.visit_expr_path(_binding_0); + } + Expr::Reference(ref _binding_0, ) => { + full!(_visitor.visit_expr_reference(_binding_0)); + } + Expr::Break(ref _binding_0, ) => { + full!(_visitor.visit_expr_break(_binding_0)); + } + Expr::Continue(ref _binding_0, ) => { + full!(_visitor.visit_expr_continue(_binding_0)); + } + Expr::Return(ref _binding_0, ) => { + full!(_visitor.visit_expr_return(_binding_0)); + } + Expr::Macro(ref _binding_0, ) => { + full!(_visitor.visit_expr_macro(_binding_0)); + } + Expr::Struct(ref _binding_0, ) => { + full!(_visitor.visit_expr_struct(_binding_0)); + } + Expr::Repeat(ref _binding_0, ) => { + full!(_visitor.visit_expr_repeat(_binding_0)); + } + Expr::Paren(ref _binding_0, ) => { + _visitor.visit_expr_paren(_binding_0); + } + Expr::Group(ref _binding_0, ) => { + full!(_visitor.visit_expr_group(_binding_0)); + } + Expr::Try(ref _binding_0, ) => { + full!(_visitor.visit_expr_try(_binding_0)); + } + Expr::Catch(ref _binding_0, ) => { + full!(_visitor.visit_expr_catch(_binding_0)); + } + Expr::Yield(ref _binding_0, ) => { + full!(_visitor.visit_expr_yield(_binding_0)); + } + Expr::Verbatim(ref _binding_0, ) => { + _visitor.visit_expr_verbatim(_binding_0); + } + } +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_array<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprArray) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . bracket_token).0); + for el in Punctuated::pairs(& _i . elems) { let it = el.value(); _visitor.visit_expr(it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_assign<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprAssign) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_expr(& * _i . left); + tokens_helper(_visitor, &(& _i . eq_token).0); + _visitor.visit_expr(& * _i . right); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_assign_op<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprAssignOp) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_expr(& * _i . left); + _visitor.visit_bin_op(& _i . op); + _visitor.visit_expr(& * _i . right); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_binary<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprBinary) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_expr(& * _i . left); + _visitor.visit_bin_op(& _i . op); + _visitor.visit_expr(& * _i . right); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_block<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprBlock) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_block(& _i . block); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_box<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprBox) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . box_token).0); + _visitor.visit_expr(& * _i . expr); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_break<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprBreak) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . break_token).0); + if let Some(ref it) = _i . label { _visitor.visit_lifetime(it) }; + if let Some(ref it) = _i . expr { _visitor.visit_expr(& * * it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_call<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprCall) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_expr(& * _i . func); + tokens_helper(_visitor, &(& _i . paren_token).0); + for el in Punctuated::pairs(& _i . args) { let it = el.value(); _visitor.visit_expr(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_cast<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprCast) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_expr(& * _i . expr); + tokens_helper(_visitor, &(& _i . as_token).0); + _visitor.visit_type(& * _i . ty); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_catch<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprCatch) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . do_token).0); + tokens_helper(_visitor, &(& _i . catch_token).0); + _visitor.visit_block(& _i . block); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_closure<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprClosure) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + if let Some(ref it) = _i . movability { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . capture { tokens_helper(_visitor, &(it).0) }; + tokens_helper(_visitor, &(& _i . or1_token).0); + for el in Punctuated::pairs(& _i . inputs) { let it = el.value(); _visitor.visit_fn_arg(it) }; + tokens_helper(_visitor, &(& _i . or2_token).0); + _visitor.visit_return_type(& _i . output); + _visitor.visit_expr(& * _i . body); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_continue<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprContinue) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . continue_token).0); + if let Some(ref it) = _i . label { _visitor.visit_lifetime(it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_field<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprField) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_expr(& * _i . base); + tokens_helper(_visitor, &(& _i . dot_token).0); + _visitor.visit_member(& _i . member); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_for_loop<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprForLoop) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + if let Some(ref it) = _i . label { _visitor.visit_label(it) }; + tokens_helper(_visitor, &(& _i . for_token).0); + _visitor.visit_pat(& * _i . pat); + tokens_helper(_visitor, &(& _i . in_token).0); + _visitor.visit_expr(& * _i . expr); + _visitor.visit_block(& _i . body); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_group<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprGroup) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . group_token).0); + _visitor.visit_expr(& * _i . expr); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_if<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprIf) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . if_token).0); + _visitor.visit_expr(& * _i . cond); + _visitor.visit_block(& _i . then_branch); + if let Some(ref it) = _i . else_branch { + tokens_helper(_visitor, &(& ( it ) . 0).0); + _visitor.visit_expr(& * ( it ) . 1); + }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_if_let<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprIfLet) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . if_token).0); + tokens_helper(_visitor, &(& _i . let_token).0); + for el in Punctuated::pairs(& _i . pats) { let it = el.value(); _visitor.visit_pat(it) }; + tokens_helper(_visitor, &(& _i . eq_token).0); + _visitor.visit_expr(& * _i . expr); + _visitor.visit_block(& _i . then_branch); + if let Some(ref it) = _i . else_branch { + tokens_helper(_visitor, &(& ( it ) . 0).0); + _visitor.visit_expr(& * ( it ) . 1); + }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_in_place<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprInPlace) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_expr(& * _i . place); + tokens_helper(_visitor, &(& _i . arrow_token).0); + _visitor.visit_expr(& * _i . value); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_index<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprIndex) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_expr(& * _i . expr); + tokens_helper(_visitor, &(& _i . bracket_token).0); + _visitor.visit_expr(& * _i . index); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_lit<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprLit) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_lit(& _i . lit); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_loop<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprLoop) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + if let Some(ref it) = _i . label { _visitor.visit_label(it) }; + tokens_helper(_visitor, &(& _i . loop_token).0); + _visitor.visit_block(& _i . body); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_macro<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprMacro) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_macro(& _i . mac); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_match<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprMatch) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . match_token).0); + _visitor.visit_expr(& * _i . expr); + tokens_helper(_visitor, &(& _i . brace_token).0); + for it in & _i . arms { _visitor.visit_arm(it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_method_call<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprMethodCall) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_expr(& * _i . receiver); + tokens_helper(_visitor, &(& _i . dot_token).0); + _visitor.visit_ident(& _i . method); + if let Some(ref it) = _i . turbofish { _visitor.visit_method_turbofish(it) }; + tokens_helper(_visitor, &(& _i . paren_token).0); + for el in Punctuated::pairs(& _i . args) { let it = el.value(); _visitor.visit_expr(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_paren<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprParen) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . paren_token).0); + _visitor.visit_expr(& * _i . expr); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_path<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprPath) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + if let Some(ref it) = _i . qself { _visitor.visit_qself(it) }; + _visitor.visit_path(& _i . path); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_range<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprRange) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + if let Some(ref it) = _i . from { _visitor.visit_expr(& * * it) }; + _visitor.visit_range_limits(& _i . limits); + if let Some(ref it) = _i . to { _visitor.visit_expr(& * * it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_reference<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprReference) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . and_token).0); + if let Some(ref it) = _i . mutability { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_expr(& * _i . expr); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_repeat<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprRepeat) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . bracket_token).0); + _visitor.visit_expr(& * _i . expr); + tokens_helper(_visitor, &(& _i . semi_token).0); + _visitor.visit_expr(& * _i . len); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_return<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprReturn) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . return_token).0); + if let Some(ref it) = _i . expr { _visitor.visit_expr(& * * it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_struct<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprStruct) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_path(& _i . path); + tokens_helper(_visitor, &(& _i . brace_token).0); + for el in Punctuated::pairs(& _i . fields) { let it = el.value(); _visitor.visit_field_value(it) }; + if let Some(ref it) = _i . dot2_token { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . rest { _visitor.visit_expr(& * * it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_try<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprTry) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_expr(& * _i . expr); + tokens_helper(_visitor, &(& _i . question_token).0); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_tuple<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprTuple) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . paren_token).0); + for el in Punctuated::pairs(& _i . elems) { let it = el.value(); _visitor.visit_expr(it) }; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_type<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprType) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_expr(& * _i . expr); + tokens_helper(_visitor, &(& _i . colon_token).0); + _visitor.visit_type(& * _i . ty); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_unary<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprUnary) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_un_op(& _i . op); + _visitor.visit_expr(& * _i . expr); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_unsafe<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprUnsafe) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . unsafe_token).0); + _visitor.visit_block(& _i . block); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_verbatim<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_while<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprWhile) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + if let Some(ref it) = _i . label { _visitor.visit_label(it) }; + tokens_helper(_visitor, &(& _i . while_token).0); + _visitor.visit_expr(& * _i . cond); + _visitor.visit_block(& _i . body); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_while_let<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprWhileLet) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + if let Some(ref it) = _i . label { _visitor.visit_label(it) }; + tokens_helper(_visitor, &(& _i . while_token).0); + tokens_helper(_visitor, &(& _i . let_token).0); + for el in Punctuated::pairs(& _i . pats) { let it = el.value(); _visitor.visit_pat(it) }; + tokens_helper(_visitor, &(& _i . eq_token).0); + _visitor.visit_expr(& * _i . expr); + _visitor.visit_block(& _i . body); +} +# [ cfg ( feature = "full" ) ] # [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_expr_yield<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ExprYield) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . yield_token).0); + if let Some(ref it) = _i . expr { _visitor.visit_expr(& * * it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_field<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Field) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + if let Some(ref it) = _i . ident { _visitor.visit_ident(it) }; + if let Some(ref it) = _i . colon_token { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_type(& _i . ty); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_field_pat<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast FieldPat) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_member(& _i . member); + if let Some(ref it) = _i . colon_token { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_pat(& * _i . pat); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_field_value<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast FieldValue) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_member(& _i . member); + if let Some(ref it) = _i . colon_token { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_expr(& _i . expr); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_fields<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Fields) { + match *_i { + Fields::Named(ref _binding_0, ) => { + _visitor.visit_fields_named(_binding_0); + } + Fields::Unnamed(ref _binding_0, ) => { + _visitor.visit_fields_unnamed(_binding_0); + } + Fields::Unit => { } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_fields_named<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast FieldsNamed) { + tokens_helper(_visitor, &(& _i . brace_token).0); + for el in Punctuated::pairs(& _i . named) { let it = el.value(); _visitor.visit_field(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_fields_unnamed<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast FieldsUnnamed) { + tokens_helper(_visitor, &(& _i . paren_token).0); + for el in Punctuated::pairs(& _i . unnamed) { let it = el.value(); _visitor.visit_field(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_file<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast File) { + // Skipped field _i . shebang; + for it in & _i . attrs { _visitor.visit_attribute(it) }; + for it in & _i . items { _visitor.visit_item(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_fn_arg<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast FnArg) { + match *_i { + FnArg::SelfRef(ref _binding_0, ) => { + _visitor.visit_arg_self_ref(_binding_0); + } + FnArg::SelfValue(ref _binding_0, ) => { + _visitor.visit_arg_self(_binding_0); + } + FnArg::Captured(ref _binding_0, ) => { + _visitor.visit_arg_captured(_binding_0); + } + FnArg::Inferred(ref _binding_0, ) => { + _visitor.visit_pat(_binding_0); + } + FnArg::Ignored(ref _binding_0, ) => { + _visitor.visit_type(_binding_0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_fn_decl<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast FnDecl) { + tokens_helper(_visitor, &(& _i . fn_token).0); + _visitor.visit_generics(& _i . generics); + tokens_helper(_visitor, &(& _i . paren_token).0); + for el in Punctuated::pairs(& _i . inputs) { let it = el.value(); _visitor.visit_fn_arg(it) }; + if let Some(ref it) = _i . variadic { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_return_type(& _i . output); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_foreign_item<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ForeignItem) { + match *_i { + ForeignItem::Fn(ref _binding_0, ) => { + _visitor.visit_foreign_item_fn(_binding_0); + } + ForeignItem::Static(ref _binding_0, ) => { + _visitor.visit_foreign_item_static(_binding_0); + } + ForeignItem::Type(ref _binding_0, ) => { + _visitor.visit_foreign_item_type(_binding_0); + } + ForeignItem::Verbatim(ref _binding_0, ) => { + _visitor.visit_foreign_item_verbatim(_binding_0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_foreign_item_fn<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ForeignItemFn) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + _visitor.visit_ident(& _i . ident); + _visitor.visit_fn_decl(& * _i . decl); + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_foreign_item_static<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ForeignItemStatic) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + tokens_helper(_visitor, &(& _i . static_token).0); + if let Some(ref it) = _i . mutability { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . colon_token).0); + _visitor.visit_type(& * _i . ty); + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_foreign_item_type<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ForeignItemType) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + tokens_helper(_visitor, &(& _i . type_token).0); + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_foreign_item_verbatim<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ForeignItemVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_generic_argument<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast GenericArgument) { + match *_i { + GenericArgument::Lifetime(ref _binding_0, ) => { + _visitor.visit_lifetime(_binding_0); + } + GenericArgument::Type(ref _binding_0, ) => { + _visitor.visit_type(_binding_0); + } + GenericArgument::Binding(ref _binding_0, ) => { + _visitor.visit_binding(_binding_0); + } + GenericArgument::Const(ref _binding_0, ) => { + _visitor.visit_expr(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_generic_method_argument<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast GenericMethodArgument) { + match *_i { + GenericMethodArgument::Type(ref _binding_0, ) => { + _visitor.visit_type(_binding_0); + } + GenericMethodArgument::Const(ref _binding_0, ) => { + _visitor.visit_expr(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_generic_param<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast GenericParam) { + match *_i { + GenericParam::Type(ref _binding_0, ) => { + _visitor.visit_type_param(_binding_0); + } + GenericParam::Lifetime(ref _binding_0, ) => { + _visitor.visit_lifetime_def(_binding_0); + } + GenericParam::Const(ref _binding_0, ) => { + _visitor.visit_const_param(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_generics<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Generics) { + if let Some(ref it) = _i . lt_token { tokens_helper(_visitor, &(it).0) }; + for el in Punctuated::pairs(& _i . params) { let it = el.value(); _visitor.visit_generic_param(it) }; + if let Some(ref it) = _i . gt_token { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . where_clause { _visitor.visit_where_clause(it) }; +} + +pub fn visit_ident<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Ident) { + // Skipped field _i . term; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_impl_item<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ImplItem) { + match *_i { + ImplItem::Const(ref _binding_0, ) => { + _visitor.visit_impl_item_const(_binding_0); + } + ImplItem::Method(ref _binding_0, ) => { + _visitor.visit_impl_item_method(_binding_0); + } + ImplItem::Type(ref _binding_0, ) => { + _visitor.visit_impl_item_type(_binding_0); + } + ImplItem::Macro(ref _binding_0, ) => { + _visitor.visit_impl_item_macro(_binding_0); + } + ImplItem::Verbatim(ref _binding_0, ) => { + _visitor.visit_impl_item_verbatim(_binding_0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_impl_item_const<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ImplItemConst) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + if let Some(ref it) = _i . defaultness { tokens_helper(_visitor, &(it).0) }; + tokens_helper(_visitor, &(& _i . const_token).0); + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . colon_token).0); + _visitor.visit_type(& _i . ty); + tokens_helper(_visitor, &(& _i . eq_token).0); + _visitor.visit_expr(& _i . expr); + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_impl_item_macro<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ImplItemMacro) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_macro(& _i . mac); + if let Some(ref it) = _i . semi_token { tokens_helper(_visitor, &(it).0) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_impl_item_method<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ImplItemMethod) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + if let Some(ref it) = _i . defaultness { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_method_sig(& _i . sig); + _visitor.visit_block(& _i . block); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_impl_item_type<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ImplItemType) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + if let Some(ref it) = _i . defaultness { tokens_helper(_visitor, &(it).0) }; + tokens_helper(_visitor, &(& _i . type_token).0); + _visitor.visit_ident(& _i . ident); + _visitor.visit_generics(& _i . generics); + tokens_helper(_visitor, &(& _i . eq_token).0); + _visitor.visit_type(& _i . ty); + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_impl_item_verbatim<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ImplItemVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_index<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Index) { + // Skipped field _i . index; + _visitor.visit_span(& _i . span); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Item) { + match *_i { + Item::ExternCrate(ref _binding_0, ) => { + _visitor.visit_item_extern_crate(_binding_0); + } + Item::Use(ref _binding_0, ) => { + _visitor.visit_item_use(_binding_0); + } + Item::Static(ref _binding_0, ) => { + _visitor.visit_item_static(_binding_0); + } + Item::Const(ref _binding_0, ) => { + _visitor.visit_item_const(_binding_0); + } + Item::Fn(ref _binding_0, ) => { + _visitor.visit_item_fn(_binding_0); + } + Item::Mod(ref _binding_0, ) => { + _visitor.visit_item_mod(_binding_0); + } + Item::ForeignMod(ref _binding_0, ) => { + _visitor.visit_item_foreign_mod(_binding_0); + } + Item::Type(ref _binding_0, ) => { + _visitor.visit_item_type(_binding_0); + } + Item::Struct(ref _binding_0, ) => { + _visitor.visit_item_struct(_binding_0); + } + Item::Enum(ref _binding_0, ) => { + _visitor.visit_item_enum(_binding_0); + } + Item::Union(ref _binding_0, ) => { + _visitor.visit_item_union(_binding_0); + } + Item::Trait(ref _binding_0, ) => { + _visitor.visit_item_trait(_binding_0); + } + Item::Impl(ref _binding_0, ) => { + _visitor.visit_item_impl(_binding_0); + } + Item::Macro(ref _binding_0, ) => { + _visitor.visit_item_macro(_binding_0); + } + Item::Macro2(ref _binding_0, ) => { + _visitor.visit_item_macro2(_binding_0); + } + Item::Verbatim(ref _binding_0, ) => { + _visitor.visit_item_verbatim(_binding_0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_const<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemConst) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + tokens_helper(_visitor, &(& _i . const_token).0); + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . colon_token).0); + _visitor.visit_type(& * _i . ty); + tokens_helper(_visitor, &(& _i . eq_token).0); + _visitor.visit_expr(& * _i . expr); + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_enum<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemEnum) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + tokens_helper(_visitor, &(& _i . enum_token).0); + _visitor.visit_ident(& _i . ident); + _visitor.visit_generics(& _i . generics); + tokens_helper(_visitor, &(& _i . brace_token).0); + for el in Punctuated::pairs(& _i . variants) { let it = el.value(); _visitor.visit_variant(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_extern_crate<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemExternCrate) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + tokens_helper(_visitor, &(& _i . extern_token).0); + tokens_helper(_visitor, &(& _i . crate_token).0); + _visitor.visit_ident(& _i . ident); + if let Some(ref it) = _i . rename { + tokens_helper(_visitor, &(& ( it ) . 0).0); + _visitor.visit_ident(& ( it ) . 1); + }; + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_fn<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemFn) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + if let Some(ref it) = _i . constness { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . unsafety { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . abi { _visitor.visit_abi(it) }; + _visitor.visit_ident(& _i . ident); + _visitor.visit_fn_decl(& * _i . decl); + _visitor.visit_block(& * _i . block); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_foreign_mod<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemForeignMod) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_abi(& _i . abi); + tokens_helper(_visitor, &(& _i . brace_token).0); + for it in & _i . items { _visitor.visit_foreign_item(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_impl<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemImpl) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + if let Some(ref it) = _i . defaultness { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . unsafety { tokens_helper(_visitor, &(it).0) }; + tokens_helper(_visitor, &(& _i . impl_token).0); + _visitor.visit_generics(& _i . generics); + if let Some(ref it) = _i . trait_ { + if let Some(ref it) = ( it ) . 0 { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_path(& ( it ) . 1); + tokens_helper(_visitor, &(& ( it ) . 2).0); + }; + _visitor.visit_type(& * _i . self_ty); + tokens_helper(_visitor, &(& _i . brace_token).0); + for it in & _i . items { _visitor.visit_impl_item(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_macro<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemMacro) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + if let Some(ref it) = _i . ident { _visitor.visit_ident(it) }; + _visitor.visit_macro(& _i . mac); + if let Some(ref it) = _i . semi_token { tokens_helper(_visitor, &(it).0) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_macro2<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemMacro2) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + tokens_helper(_visitor, &(& _i . macro_token).0); + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . paren_token).0); + // Skipped field _i . args; + tokens_helper(_visitor, &(& _i . brace_token).0); + // Skipped field _i . body; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_mod<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemMod) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + tokens_helper(_visitor, &(& _i . mod_token).0); + _visitor.visit_ident(& _i . ident); + if let Some(ref it) = _i . content { + tokens_helper(_visitor, &(& ( it ) . 0).0); + for it in & ( it ) . 1 { _visitor.visit_item(it) }; + }; + if let Some(ref it) = _i . semi { tokens_helper(_visitor, &(it).0) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_static<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemStatic) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + tokens_helper(_visitor, &(& _i . static_token).0); + if let Some(ref it) = _i . mutability { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . colon_token).0); + _visitor.visit_type(& * _i . ty); + tokens_helper(_visitor, &(& _i . eq_token).0); + _visitor.visit_expr(& * _i . expr); + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_struct<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemStruct) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + tokens_helper(_visitor, &(& _i . struct_token).0); + _visitor.visit_ident(& _i . ident); + _visitor.visit_generics(& _i . generics); + _visitor.visit_fields(& _i . fields); + if let Some(ref it) = _i . semi_token { tokens_helper(_visitor, &(it).0) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_trait<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemTrait) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + if let Some(ref it) = _i . unsafety { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . auto_token { tokens_helper(_visitor, &(it).0) }; + tokens_helper(_visitor, &(& _i . trait_token).0); + _visitor.visit_ident(& _i . ident); + _visitor.visit_generics(& _i . generics); + if let Some(ref it) = _i . colon_token { tokens_helper(_visitor, &(it).0) }; + for el in Punctuated::pairs(& _i . supertraits) { let it = el.value(); _visitor.visit_type_param_bound(it) }; + tokens_helper(_visitor, &(& _i . brace_token).0); + for it in & _i . items { _visitor.visit_trait_item(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_type<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemType) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + tokens_helper(_visitor, &(& _i . type_token).0); + _visitor.visit_ident(& _i . ident); + _visitor.visit_generics(& _i . generics); + tokens_helper(_visitor, &(& _i . eq_token).0); + _visitor.visit_type(& * _i . ty); + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_union<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemUnion) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + tokens_helper(_visitor, &(& _i . union_token).0); + _visitor.visit_ident(& _i . ident); + _visitor.visit_generics(& _i . generics); + _visitor.visit_fields_named(& _i . fields); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_use<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemUse) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_visibility(& _i . vis); + tokens_helper(_visitor, &(& _i . use_token).0); + if let Some(ref it) = _i . leading_colon { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_use_tree(& _i . tree); + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_item_verbatim<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ItemVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_label<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Label) { + _visitor.visit_lifetime(& _i . name); + tokens_helper(_visitor, &(& _i . colon_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lifetime<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Lifetime) { + // Skipped field _i . term; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lifetime_def<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LifetimeDef) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_lifetime(& _i . lifetime); + if let Some(ref it) = _i . colon_token { tokens_helper(_visitor, &(it).0) }; + for el in Punctuated::pairs(& _i . bounds) { let it = el.value(); _visitor.visit_lifetime(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Lit) { + match *_i { + Lit::Str(ref _binding_0, ) => { + _visitor.visit_lit_str(_binding_0); + } + Lit::ByteStr(ref _binding_0, ) => { + _visitor.visit_lit_byte_str(_binding_0); + } + Lit::Byte(ref _binding_0, ) => { + _visitor.visit_lit_byte(_binding_0); + } + Lit::Char(ref _binding_0, ) => { + _visitor.visit_lit_char(_binding_0); + } + Lit::Int(ref _binding_0, ) => { + _visitor.visit_lit_int(_binding_0); + } + Lit::Float(ref _binding_0, ) => { + _visitor.visit_lit_float(_binding_0); + } + Lit::Bool(ref _binding_0, ) => { + _visitor.visit_lit_bool(_binding_0); + } + Lit::Verbatim(ref _binding_0, ) => { + _visitor.visit_lit_verbatim(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_bool<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitBool) { + // Skipped field _i . value; + _visitor.visit_span(& _i . span); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_byte<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitByte) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_byte_str<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitByteStr) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_char<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitChar) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_float<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitFloat) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_int<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitInt) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_str<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitStr) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_lit_verbatim<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast LitVerbatim) { + // Skipped field _i . token; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_local<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Local) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . let_token).0); + for el in Punctuated::pairs(& _i . pats) { let it = el.value(); _visitor.visit_pat(it) }; + if let Some(ref it) = _i . ty { + tokens_helper(_visitor, &(& ( it ) . 0).0); + _visitor.visit_type(& * ( it ) . 1); + }; + if let Some(ref it) = _i . init { + tokens_helper(_visitor, &(& ( it ) . 0).0); + _visitor.visit_expr(& * ( it ) . 1); + }; + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_macro<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Macro) { + _visitor.visit_path(& _i . path); + tokens_helper(_visitor, &(& _i . bang_token).0); + _visitor.visit_macro_delimiter(& _i . delimiter); + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_macro_delimiter<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast MacroDelimiter) { + match *_i { + MacroDelimiter::Paren(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + MacroDelimiter::Brace(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + MacroDelimiter::Bracket(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_member<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Member) { + match *_i { + Member::Named(ref _binding_0, ) => { + _visitor.visit_ident(_binding_0); + } + Member::Unnamed(ref _binding_0, ) => { + _visitor.visit_index(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_meta<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Meta) { + match *_i { + Meta::Word(ref _binding_0, ) => { + _visitor.visit_ident(_binding_0); + } + Meta::List(ref _binding_0, ) => { + _visitor.visit_meta_list(_binding_0); + } + Meta::NameValue(ref _binding_0, ) => { + _visitor.visit_meta_name_value(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_meta_list<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast MetaList) { + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . paren_token).0); + for el in Punctuated::pairs(& _i . nested) { let it = el.value(); _visitor.visit_nested_meta(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_meta_name_value<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast MetaNameValue) { + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . eq_token).0); + _visitor.visit_lit(& _i . lit); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_method_sig<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast MethodSig) { + if let Some(ref it) = _i . constness { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . unsafety { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . abi { _visitor.visit_abi(it) }; + _visitor.visit_ident(& _i . ident); + _visitor.visit_fn_decl(& _i . decl); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_method_turbofish<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast MethodTurbofish) { + tokens_helper(_visitor, &(& _i . colon2_token).0); + tokens_helper(_visitor, &(& _i . lt_token).0); + for el in Punctuated::pairs(& _i . args) { let it = el.value(); _visitor.visit_generic_method_argument(it) }; + tokens_helper(_visitor, &(& _i . gt_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_nested_meta<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast NestedMeta) { + match *_i { + NestedMeta::Meta(ref _binding_0, ) => { + _visitor.visit_meta(_binding_0); + } + NestedMeta::Literal(ref _binding_0, ) => { + _visitor.visit_lit(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_parenthesized_generic_arguments<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ParenthesizedGenericArguments) { + tokens_helper(_visitor, &(& _i . paren_token).0); + for el in Punctuated::pairs(& _i . inputs) { let it = el.value(); _visitor.visit_type(it) }; + _visitor.visit_return_type(& _i . output); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Pat) { + match *_i { + Pat::Wild(ref _binding_0, ) => { + _visitor.visit_pat_wild(_binding_0); + } + Pat::Ident(ref _binding_0, ) => { + _visitor.visit_pat_ident(_binding_0); + } + Pat::Struct(ref _binding_0, ) => { + _visitor.visit_pat_struct(_binding_0); + } + Pat::TupleStruct(ref _binding_0, ) => { + _visitor.visit_pat_tuple_struct(_binding_0); + } + Pat::Path(ref _binding_0, ) => { + _visitor.visit_pat_path(_binding_0); + } + Pat::Tuple(ref _binding_0, ) => { + _visitor.visit_pat_tuple(_binding_0); + } + Pat::Box(ref _binding_0, ) => { + _visitor.visit_pat_box(_binding_0); + } + Pat::Ref(ref _binding_0, ) => { + _visitor.visit_pat_ref(_binding_0); + } + Pat::Lit(ref _binding_0, ) => { + _visitor.visit_pat_lit(_binding_0); + } + Pat::Range(ref _binding_0, ) => { + _visitor.visit_pat_range(_binding_0); + } + Pat::Slice(ref _binding_0, ) => { + _visitor.visit_pat_slice(_binding_0); + } + Pat::Macro(ref _binding_0, ) => { + _visitor.visit_pat_macro(_binding_0); + } + Pat::Verbatim(ref _binding_0, ) => { + _visitor.visit_pat_verbatim(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_box<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatBox) { + tokens_helper(_visitor, &(& _i . box_token).0); + _visitor.visit_pat(& * _i . pat); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_ident<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatIdent) { + if let Some(ref it) = _i . by_ref { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . mutability { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_ident(& _i . ident); + if let Some(ref it) = _i . subpat { + tokens_helper(_visitor, &(& ( it ) . 0).0); + _visitor.visit_pat(& * ( it ) . 1); + }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_lit<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatLit) { + _visitor.visit_expr(& * _i . expr); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_macro<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatMacro) { + _visitor.visit_macro(& _i . mac); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_path<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatPath) { + if let Some(ref it) = _i . qself { _visitor.visit_qself(it) }; + _visitor.visit_path(& _i . path); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_range<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatRange) { + _visitor.visit_expr(& * _i . lo); + _visitor.visit_range_limits(& _i . limits); + _visitor.visit_expr(& * _i . hi); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_ref<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatRef) { + tokens_helper(_visitor, &(& _i . and_token).0); + if let Some(ref it) = _i . mutability { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_pat(& * _i . pat); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_slice<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatSlice) { + tokens_helper(_visitor, &(& _i . bracket_token).0); + for el in Punctuated::pairs(& _i . front) { let it = el.value(); _visitor.visit_pat(it) }; + if let Some(ref it) = _i . middle { _visitor.visit_pat(& * * it) }; + if let Some(ref it) = _i . dot2_token { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . comma_token { tokens_helper(_visitor, &(it).0) }; + for el in Punctuated::pairs(& _i . back) { let it = el.value(); _visitor.visit_pat(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_struct<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatStruct) { + _visitor.visit_path(& _i . path); + tokens_helper(_visitor, &(& _i . brace_token).0); + for el in Punctuated::pairs(& _i . fields) { let it = el.value(); _visitor.visit_field_pat(it) }; + if let Some(ref it) = _i . dot2_token { tokens_helper(_visitor, &(it).0) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_tuple<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatTuple) { + tokens_helper(_visitor, &(& _i . paren_token).0); + for el in Punctuated::pairs(& _i . front) { let it = el.value(); _visitor.visit_pat(it) }; + if let Some(ref it) = _i . dot2_token { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . comma_token { tokens_helper(_visitor, &(it).0) }; + for el in Punctuated::pairs(& _i . back) { let it = el.value(); _visitor.visit_pat(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_tuple_struct<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatTupleStruct) { + _visitor.visit_path(& _i . path); + _visitor.visit_pat_tuple(& _i . pat); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_verbatim<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_pat_wild<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PatWild) { + tokens_helper(_visitor, &(& _i . underscore_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_path<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Path) { + if let Some(ref it) = _i . leading_colon { tokens_helper(_visitor, &(it).0) }; + for el in Punctuated::pairs(& _i . segments) { let it = el.value(); _visitor.visit_path_segment(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_path_arguments<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PathArguments) { + match *_i { + PathArguments::None => { } + PathArguments::AngleBracketed(ref _binding_0, ) => { + _visitor.visit_angle_bracketed_generic_arguments(_binding_0); + } + PathArguments::Parenthesized(ref _binding_0, ) => { + _visitor.visit_parenthesized_generic_arguments(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_path_segment<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PathSegment) { + _visitor.visit_ident(& _i . ident); + _visitor.visit_path_arguments(& _i . arguments); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_predicate_eq<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PredicateEq) { + _visitor.visit_type(& _i . lhs_ty); + tokens_helper(_visitor, &(& _i . eq_token).0); + _visitor.visit_type(& _i . rhs_ty); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_predicate_lifetime<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PredicateLifetime) { + _visitor.visit_lifetime(& _i . lifetime); + if let Some(ref it) = _i . colon_token { tokens_helper(_visitor, &(it).0) }; + for el in Punctuated::pairs(& _i . bounds) { let it = el.value(); _visitor.visit_lifetime(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_predicate_type<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast PredicateType) { + if let Some(ref it) = _i . lifetimes { _visitor.visit_bound_lifetimes(it) }; + _visitor.visit_type(& _i . bounded_ty); + tokens_helper(_visitor, &(& _i . colon_token).0); + for el in Punctuated::pairs(& _i . bounds) { let it = el.value(); _visitor.visit_type_param_bound(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_qself<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast QSelf) { + tokens_helper(_visitor, &(& _i . lt_token).0); + _visitor.visit_type(& * _i . ty); + // Skipped field _i . position; + if let Some(ref it) = _i . as_token { tokens_helper(_visitor, &(it).0) }; + tokens_helper(_visitor, &(& _i . gt_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_range_limits<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast RangeLimits) { + match *_i { + RangeLimits::HalfOpen(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + RangeLimits::Closed(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_return_type<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast ReturnType) { + match *_i { + ReturnType::Default => { } + ReturnType::Type(ref _binding_0, ref _binding_1, ) => { + tokens_helper(_visitor, &(_binding_0).0); + _visitor.visit_type(& * * _binding_1); + } + } +} + +pub fn visit_span<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Span) { +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] # [ cfg ( feature = "full" ) ] +pub fn visit_stmt<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Stmt) { + match *_i { + Stmt::Local(ref _binding_0, ) => { + _visitor.visit_local(_binding_0); + } + Stmt::Item(ref _binding_0, ) => { + _visitor.visit_item(_binding_0); + } + Stmt::Expr(ref _binding_0, ) => { + _visitor.visit_expr(_binding_0); + } + Stmt::Semi(ref _binding_0, ref _binding_1, ) => { + _visitor.visit_expr(_binding_0); + tokens_helper(_visitor, &(_binding_1).0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_trait_bound<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TraitBound) { + if let Some(ref it) = _i . paren_token { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_trait_bound_modifier(& _i . modifier); + if let Some(ref it) = _i . lifetimes { _visitor.visit_bound_lifetimes(it) }; + _visitor.visit_path(& _i . path); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_trait_bound_modifier<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TraitBoundModifier) { + match *_i { + TraitBoundModifier::None => { } + TraitBoundModifier::Maybe(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_trait_item<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TraitItem) { + match *_i { + TraitItem::Const(ref _binding_0, ) => { + _visitor.visit_trait_item_const(_binding_0); + } + TraitItem::Method(ref _binding_0, ) => { + _visitor.visit_trait_item_method(_binding_0); + } + TraitItem::Type(ref _binding_0, ) => { + _visitor.visit_trait_item_type(_binding_0); + } + TraitItem::Macro(ref _binding_0, ) => { + _visitor.visit_trait_item_macro(_binding_0); + } + TraitItem::Verbatim(ref _binding_0, ) => { + _visitor.visit_trait_item_verbatim(_binding_0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_trait_item_const<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TraitItemConst) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . const_token).0); + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . colon_token).0); + _visitor.visit_type(& _i . ty); + if let Some(ref it) = _i . default { + tokens_helper(_visitor, &(& ( it ) . 0).0); + _visitor.visit_expr(& ( it ) . 1); + }; + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_trait_item_macro<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TraitItemMacro) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_macro(& _i . mac); + if let Some(ref it) = _i . semi_token { tokens_helper(_visitor, &(it).0) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_trait_item_method<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TraitItemMethod) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_method_sig(& _i . sig); + if let Some(ref it) = _i . default { _visitor.visit_block(it) }; + if let Some(ref it) = _i . semi_token { tokens_helper(_visitor, &(it).0) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_trait_item_type<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TraitItemType) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + tokens_helper(_visitor, &(& _i . type_token).0); + _visitor.visit_ident(& _i . ident); + _visitor.visit_generics(& _i . generics); + if let Some(ref it) = _i . colon_token { tokens_helper(_visitor, &(it).0) }; + for el in Punctuated::pairs(& _i . bounds) { let it = el.value(); _visitor.visit_type_param_bound(it) }; + if let Some(ref it) = _i . default { + tokens_helper(_visitor, &(& ( it ) . 0).0); + _visitor.visit_type(& ( it ) . 1); + }; + tokens_helper(_visitor, &(& _i . semi_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_trait_item_verbatim<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TraitItemVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Type) { + match *_i { + Type::Slice(ref _binding_0, ) => { + _visitor.visit_type_slice(_binding_0); + } + Type::Array(ref _binding_0, ) => { + _visitor.visit_type_array(_binding_0); + } + Type::Ptr(ref _binding_0, ) => { + _visitor.visit_type_ptr(_binding_0); + } + Type::Reference(ref _binding_0, ) => { + _visitor.visit_type_reference(_binding_0); + } + Type::BareFn(ref _binding_0, ) => { + _visitor.visit_type_bare_fn(_binding_0); + } + Type::Never(ref _binding_0, ) => { + _visitor.visit_type_never(_binding_0); + } + Type::Tuple(ref _binding_0, ) => { + _visitor.visit_type_tuple(_binding_0); + } + Type::Path(ref _binding_0, ) => { + _visitor.visit_type_path(_binding_0); + } + Type::TraitObject(ref _binding_0, ) => { + _visitor.visit_type_trait_object(_binding_0); + } + Type::ImplTrait(ref _binding_0, ) => { + _visitor.visit_type_impl_trait(_binding_0); + } + Type::Paren(ref _binding_0, ) => { + _visitor.visit_type_paren(_binding_0); + } + Type::Group(ref _binding_0, ) => { + _visitor.visit_type_group(_binding_0); + } + Type::Infer(ref _binding_0, ) => { + _visitor.visit_type_infer(_binding_0); + } + Type::Macro(ref _binding_0, ) => { + _visitor.visit_type_macro(_binding_0); + } + Type::Verbatim(ref _binding_0, ) => { + _visitor.visit_type_verbatim(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_array<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeArray) { + tokens_helper(_visitor, &(& _i . bracket_token).0); + _visitor.visit_type(& * _i . elem); + tokens_helper(_visitor, &(& _i . semi_token).0); + _visitor.visit_expr(& _i . len); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_bare_fn<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeBareFn) { + if let Some(ref it) = _i . unsafety { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . abi { _visitor.visit_abi(it) }; + tokens_helper(_visitor, &(& _i . fn_token).0); + if let Some(ref it) = _i . lifetimes { _visitor.visit_bound_lifetimes(it) }; + tokens_helper(_visitor, &(& _i . paren_token).0); + for el in Punctuated::pairs(& _i . inputs) { let it = el.value(); _visitor.visit_bare_fn_arg(it) }; + if let Some(ref it) = _i . variadic { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_return_type(& _i . output); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_group<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeGroup) { + tokens_helper(_visitor, &(& _i . group_token).0); + _visitor.visit_type(& * _i . elem); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_impl_trait<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeImplTrait) { + tokens_helper(_visitor, &(& _i . impl_token).0); + for el in Punctuated::pairs(& _i . bounds) { let it = el.value(); _visitor.visit_type_param_bound(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_infer<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeInfer) { + tokens_helper(_visitor, &(& _i . underscore_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_macro<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeMacro) { + _visitor.visit_macro(& _i . mac); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_never<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeNever) { + tokens_helper(_visitor, &(& _i . bang_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_param<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeParam) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_ident(& _i . ident); + if let Some(ref it) = _i . colon_token { tokens_helper(_visitor, &(it).0) }; + for el in Punctuated::pairs(& _i . bounds) { let it = el.value(); _visitor.visit_type_param_bound(it) }; + if let Some(ref it) = _i . eq_token { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . default { _visitor.visit_type(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_param_bound<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeParamBound) { + match *_i { + TypeParamBound::Trait(ref _binding_0, ) => { + _visitor.visit_trait_bound(_binding_0); + } + TypeParamBound::Lifetime(ref _binding_0, ) => { + _visitor.visit_lifetime(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_paren<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeParen) { + tokens_helper(_visitor, &(& _i . paren_token).0); + _visitor.visit_type(& * _i . elem); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_path<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypePath) { + if let Some(ref it) = _i . qself { _visitor.visit_qself(it) }; + _visitor.visit_path(& _i . path); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_ptr<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypePtr) { + tokens_helper(_visitor, &(& _i . star_token).0); + if let Some(ref it) = _i . const_token { tokens_helper(_visitor, &(it).0) }; + if let Some(ref it) = _i . mutability { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_type(& * _i . elem); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_reference<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeReference) { + tokens_helper(_visitor, &(& _i . and_token).0); + if let Some(ref it) = _i . lifetime { _visitor.visit_lifetime(it) }; + if let Some(ref it) = _i . mutability { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_type(& * _i . elem); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_slice<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeSlice) { + tokens_helper(_visitor, &(& _i . bracket_token).0); + _visitor.visit_type(& * _i . elem); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_trait_object<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeTraitObject) { + if let Some(ref it) = _i . dyn_token { tokens_helper(_visitor, &(it).0) }; + for el in Punctuated::pairs(& _i . bounds) { let it = el.value(); _visitor.visit_type_param_bound(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_tuple<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeTuple) { + tokens_helper(_visitor, &(& _i . paren_token).0); + for el in Punctuated::pairs(& _i . elems) { let it = el.value(); _visitor.visit_type(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_type_verbatim<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast TypeVerbatim) { + // Skipped field _i . tts; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_un_op<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UnOp) { + match *_i { + UnOp::Deref(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + UnOp::Not(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + UnOp::Neg(ref _binding_0, ) => { + tokens_helper(_visitor, &(_binding_0).0); + } + } +} +# [ cfg ( feature = "full" ) ] +pub fn visit_use_glob<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UseGlob) { + tokens_helper(_visitor, &(& _i . star_token).0); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_use_group<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UseGroup) { + tokens_helper(_visitor, &(& _i . brace_token).0); + for el in Punctuated::pairs(& _i . items) { let it = el.value(); _visitor.visit_use_tree(it) }; +} +# [ cfg ( feature = "full" ) ] +pub fn visit_use_name<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UseName) { + _visitor.visit_ident(& _i . ident); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_use_path<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UsePath) { + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . colon2_token).0); + _visitor.visit_use_tree(& * _i . tree); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_use_rename<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UseRename) { + _visitor.visit_ident(& _i . ident); + tokens_helper(_visitor, &(& _i . as_token).0); + _visitor.visit_ident(& _i . rename); +} +# [ cfg ( feature = "full" ) ] +pub fn visit_use_tree<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast UseTree) { + match *_i { + UseTree::Path(ref _binding_0, ) => { + _visitor.visit_use_path(_binding_0); + } + UseTree::Name(ref _binding_0, ) => { + _visitor.visit_use_name(_binding_0); + } + UseTree::Rename(ref _binding_0, ) => { + _visitor.visit_use_rename(_binding_0); + } + UseTree::Glob(ref _binding_0, ) => { + _visitor.visit_use_glob(_binding_0); + } + UseTree::Group(ref _binding_0, ) => { + _visitor.visit_use_group(_binding_0); + } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_variant<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Variant) { + for it in & _i . attrs { _visitor.visit_attribute(it) }; + _visitor.visit_ident(& _i . ident); + _visitor.visit_fields(& _i . fields); + if let Some(ref it) = _i . discriminant { + tokens_helper(_visitor, &(& ( it ) . 0).0); + _visitor.visit_expr(& ( it ) . 1); + }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_vis_crate<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast VisCrate) { + tokens_helper(_visitor, &(& _i . crate_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_vis_public<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast VisPublic) { + tokens_helper(_visitor, &(& _i . pub_token).0); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_vis_restricted<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast VisRestricted) { + tokens_helper(_visitor, &(& _i . pub_token).0); + tokens_helper(_visitor, &(& _i . paren_token).0); + if let Some(ref it) = _i . in_token { tokens_helper(_visitor, &(it).0) }; + _visitor.visit_path(& * _i . path); +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_visibility<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast Visibility) { + match *_i { + Visibility::Public(ref _binding_0, ) => { + _visitor.visit_vis_public(_binding_0); + } + Visibility::Crate(ref _binding_0, ) => { + _visitor.visit_vis_crate(_binding_0); + } + Visibility::Restricted(ref _binding_0, ) => { + _visitor.visit_vis_restricted(_binding_0); + } + Visibility::Inherited => { } + } +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_where_clause<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast WhereClause) { + tokens_helper(_visitor, &(& _i . where_token).0); + for el in Punctuated::pairs(& _i . predicates) { let it = el.value(); _visitor.visit_where_predicate(it) }; +} +# [ cfg ( any ( feature = "full" , feature = "derive" ) ) ] +pub fn visit_where_predicate<'ast, V: Visit<'ast> + ?Sized>(_visitor: &mut V, _i: &'ast WherePredicate) { + match *_i { + WherePredicate::Type(ref _binding_0, ) => { + _visitor.visit_predicate_type(_binding_0); + } + WherePredicate::Lifetime(ref _binding_0, ) => { + _visitor.visit_predicate_lifetime(_binding_0); + } + WherePredicate::Eq(ref _binding_0, ) => { + _visitor.visit_predicate_eq(_binding_0); + } + } +} + diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/generics.rs cargo-0.26.0/vendor/syn-0.13.1/src/generics.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/generics.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/generics.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1012 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use super::*; +use punctuated::{Iter, IterMut, Punctuated}; + +ast_struct! { + /// Lifetimes and type parameters attached to a declaration of a function, + /// enum, trait, etc. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + #[derive(Default)] + pub struct Generics { + pub lt_token: Option<Token![<]>, + pub params: Punctuated<GenericParam, Token![,]>, + pub gt_token: Option<Token![>]>, + pub where_clause: Option<WhereClause>, + } +} + +ast_enum_of_structs! { + /// A generic type parameter, lifetime, or const generic: `T: Into<String>`, + /// `'a: 'b`, `const LEN: usize`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum GenericParam { + /// A generic type parameter: `T: Into<String>`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Type(TypeParam { + pub attrs: Vec<Attribute>, + pub ident: Ident, + pub colon_token: Option<Token![:]>, + pub bounds: Punctuated<TypeParamBound, Token![+]>, + pub eq_token: Option<Token![=]>, + pub default: Option<Type>, + }), + + /// A lifetime definition: `'a: 'b + 'c + 'd`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Lifetime(LifetimeDef { + pub attrs: Vec<Attribute>, + pub lifetime: Lifetime, + pub colon_token: Option<Token![:]>, + pub bounds: Punctuated<Lifetime, Token![+]>, + }), + + /// A const generic parameter: `const LENGTH: usize`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Const(ConstParam { + pub attrs: Vec<Attribute>, + pub const_token: Token![const], + pub ident: Ident, + pub colon_token: Token![:], + pub ty: Type, + pub eq_token: Option<Token![=]>, + pub default: Option<Expr>, + }), + } +} + +impl Generics { + /// Returns an + /// <code + /// style="padding-right:0;">Iterator<Item = &</code><a + /// href="struct.TypeParam.html"><code + /// style="padding-left:0;padding-right:0;">TypeParam</code></a><code + /// style="padding-left:0;">></code> + /// over the type parameters in `self.params`. + pub fn type_params(&self) -> TypeParams { + TypeParams(self.params.iter()) + } + + /// Returns an + /// <code + /// style="padding-right:0;">Iterator<Item = &mut </code><a + /// href="struct.TypeParam.html"><code + /// style="padding-left:0;padding-right:0;">TypeParam</code></a><code + /// style="padding-left:0;">></code> + /// over the type parameters in `self.params`. + pub fn type_params_mut(&mut self) -> TypeParamsMut { + TypeParamsMut(self.params.iter_mut()) + } + + /// Returns an + /// <code + /// style="padding-right:0;">Iterator<Item = &</code><a + /// href="struct.LifetimeDef.html"><code + /// style="padding-left:0;padding-right:0;">LifetimeDef</code></a><code + /// style="padding-left:0;">></code> + /// over the lifetime parameters in `self.params`. + pub fn lifetimes(&self) -> Lifetimes { + Lifetimes(self.params.iter()) + } + + /// Returns an + /// <code + /// style="padding-right:0;">Iterator<Item = &mut </code><a + /// href="struct.LifetimeDef.html"><code + /// style="padding-left:0;padding-right:0;">LifetimeDef</code></a><code + /// style="padding-left:0;">></code> + /// over the lifetime parameters in `self.params`. + pub fn lifetimes_mut(&mut self) -> LifetimesMut { + LifetimesMut(self.params.iter_mut()) + } + + /// Returns an + /// <code + /// style="padding-right:0;">Iterator<Item = &</code><a + /// href="struct.ConstParam.html"><code + /// style="padding-left:0;padding-right:0;">ConstParam</code></a><code + /// style="padding-left:0;">></code> + /// over the constant parameters in `self.params`. + pub fn const_params(&self) -> ConstParams { + ConstParams(self.params.iter()) + } + + /// Returns an + /// <code + /// style="padding-right:0;">Iterator<Item = &mut </code><a + /// href="struct.ConstParam.html"><code + /// style="padding-left:0;padding-right:0;">ConstParam</code></a><code + /// style="padding-left:0;">></code> + /// over the constant parameters in `self.params`. + pub fn const_params_mut(&mut self) -> ConstParamsMut { + ConstParamsMut(self.params.iter_mut()) + } + + /// Initializes an empty `where`-clause if there is not one present already. + pub fn make_where_clause(&mut self) -> &mut WhereClause { + // This is Option::get_or_insert_with in Rust 1.20. + if self.where_clause.is_none() { + self.where_clause = Some(WhereClause { + where_token: Default::default(), + predicates: Punctuated::new(), + }); + } + match self.where_clause { + Some(ref mut where_clause) => where_clause, + None => unreachable!(), + } + } +} + +pub struct TypeParams<'a>(Iter<'a, GenericParam>); + +impl<'a> Iterator for TypeParams<'a> { + type Item = &'a TypeParam; + + fn next(&mut self) -> Option<Self::Item> { + // FIXME: Remove this when ? on Option is stable + let next = match self.0.next() { + Some(item) => item, + None => return None, + }; + if let GenericParam::Type(ref type_param) = *next { + Some(type_param) + } else { + self.next() + } + } +} + +pub struct TypeParamsMut<'a>(IterMut<'a, GenericParam>); + +impl<'a> Iterator for TypeParamsMut<'a> { + type Item = &'a mut TypeParam; + + fn next(&mut self) -> Option<Self::Item> { + // FIXME: Remove this when ? on Option is stable + let next = match self.0.next() { + Some(item) => item, + None => return None, + }; + if let GenericParam::Type(ref mut type_param) = *next { + Some(type_param) + } else { + self.next() + } + } +} + +pub struct Lifetimes<'a>(Iter<'a, GenericParam>); + +impl<'a> Iterator for Lifetimes<'a> { + type Item = &'a LifetimeDef; + + fn next(&mut self) -> Option<Self::Item> { + // FIXME: Remove this when ? on Option is stable + let next = match self.0.next() { + Some(item) => item, + None => return None, + }; + if let GenericParam::Lifetime(ref lifetime) = *next { + Some(lifetime) + } else { + self.next() + } + } +} + +pub struct LifetimesMut<'a>(IterMut<'a, GenericParam>); + +impl<'a> Iterator for LifetimesMut<'a> { + type Item = &'a mut LifetimeDef; + + fn next(&mut self) -> Option<Self::Item> { + // FIXME: Remove this when ? on Option is stable + let next = match self.0.next() { + Some(item) => item, + None => return None, + }; + if let GenericParam::Lifetime(ref mut lifetime) = *next { + Some(lifetime) + } else { + self.next() + } + } +} + +pub struct ConstParams<'a>(Iter<'a, GenericParam>); + +impl<'a> Iterator for ConstParams<'a> { + type Item = &'a ConstParam; + + fn next(&mut self) -> Option<Self::Item> { + // FIXME: Remove this when ? on Option is stable + let next = match self.0.next() { + Some(item) => item, + None => return None, + }; + if let GenericParam::Const(ref const_param) = *next { + Some(const_param) + } else { + self.next() + } + } +} + +pub struct ConstParamsMut<'a>(IterMut<'a, GenericParam>); + +impl<'a> Iterator for ConstParamsMut<'a> { + type Item = &'a mut ConstParam; + + fn next(&mut self) -> Option<Self::Item> { + // FIXME: Remove this when ? on Option is stable + let next = match self.0.next() { + Some(item) => item, + None => return None, + }; + if let GenericParam::Const(ref mut const_param) = *next { + Some(const_param) + } else { + self.next() + } + } +} + +/// Returned by `Generics::split_for_impl`. +/// +/// *This type is available if Syn is built with the `"derive"` or `"full"` +/// feature and the `"printing"` feature.* +#[cfg(feature = "printing")] +#[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] +#[cfg_attr(feature = "clone-impls", derive(Clone))] +pub struct ImplGenerics<'a>(&'a Generics); + +/// Returned by `Generics::split_for_impl`. +/// +/// *This type is available if Syn is built with the `"derive"` or `"full"` +/// feature and the `"printing"` feature.* +#[cfg(feature = "printing")] +#[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] +#[cfg_attr(feature = "clone-impls", derive(Clone))] +pub struct TypeGenerics<'a>(&'a Generics); + +/// Returned by `TypeGenerics::as_turbofish`. +/// +/// *This type is available if Syn is built with the `"derive"` or `"full"` +/// feature and the `"printing"` feature.* +#[cfg(feature = "printing")] +#[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] +#[cfg_attr(feature = "clone-impls", derive(Clone))] +pub struct Turbofish<'a>(&'a Generics); + +#[cfg(feature = "printing")] +impl Generics { + /// Split a type's generics into the pieces required for impl'ing a trait + /// for that type. + /// + /// ``` + /// # extern crate syn; + /// # #[macro_use] + /// # extern crate quote; + /// # fn main() { + /// # let generics: syn::Generics = Default::default(); + /// # let name = syn::Ident::from("MyType"); + /// let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); + /// quote! { + /// impl #impl_generics MyTrait for #name #ty_generics #where_clause { + /// // ... + /// } + /// } + /// # ; + /// # } + /// ``` + /// + /// *This method is available if Syn is built with the `"derive"` or + /// `"full"` feature and the `"printing"` feature.* + pub fn split_for_impl(&self) -> (ImplGenerics, TypeGenerics, Option<&WhereClause>) { + ( + ImplGenerics(self), + TypeGenerics(self), + self.where_clause.as_ref(), + ) + } +} + +#[cfg(feature = "printing")] +impl<'a> TypeGenerics<'a> { + /// Turn a type's generics like `<X, Y>` into a turbofish like `::<X, Y>`. + /// + /// *This method is available if Syn is built with the `"derive"` or + /// `"full"` feature and the `"printing"` feature.* + pub fn as_turbofish(&self) -> Turbofish { + Turbofish(self.0) + } +} + +ast_struct! { + /// A set of bound lifetimes: `for<'a, 'b, 'c>`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + #[derive(Default)] + pub struct BoundLifetimes { + pub for_token: Token![for], + pub lt_token: Token![<], + pub lifetimes: Punctuated<LifetimeDef, Token![,]>, + pub gt_token: Token![>], + } +} + +impl LifetimeDef { + pub fn new(lifetime: Lifetime) -> Self { + LifetimeDef { + attrs: Vec::new(), + lifetime: lifetime, + colon_token: None, + bounds: Punctuated::new(), + } + } +} + +impl From<Ident> for TypeParam { + fn from(ident: Ident) -> Self { + TypeParam { + attrs: vec![], + ident: ident, + colon_token: None, + bounds: Punctuated::new(), + eq_token: None, + default: None, + } + } +} + +ast_enum_of_structs! { + /// A trait or lifetime used as a bound on a type parameter. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub enum TypeParamBound { + pub Trait(TraitBound), + pub Lifetime(Lifetime), + } +} + +ast_struct! { + /// A trait used as a bound on a type parameter. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct TraitBound { + pub paren_token: Option<token::Paren>, + pub modifier: TraitBoundModifier, + /// The `for<'a>` in `for<'a> Foo<&'a T>` + pub lifetimes: Option<BoundLifetimes>, + /// The `Foo<&'a T>` in `for<'a> Foo<&'a T>` + pub path: Path, + } +} + +ast_enum! { + /// A modifier on a trait bound, currently only used for the `?` in + /// `?Sized`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + #[cfg_attr(feature = "clone-impls", derive(Copy))] + pub enum TraitBoundModifier { + None, + Maybe(Token![?]), + } +} + +ast_struct! { + /// A `where` clause in a definition: `where T: Deserialize<'de>, D: + /// 'static`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct WhereClause { + pub where_token: Token![where], + pub predicates: Punctuated<WherePredicate, Token![,]>, + } +} + +ast_enum_of_structs! { + /// A single predicate in a `where` clause: `T: Deserialize<'de>`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum WherePredicate { + /// A type predicate in a `where` clause: `for<'c> Foo<'c>: Trait<'c>`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Type(PredicateType { + /// Any lifetimes from a `for` binding + pub lifetimes: Option<BoundLifetimes>, + /// The type being bounded + pub bounded_ty: Type, + pub colon_token: Token![:], + /// Trait and lifetime bounds (`Clone+Send+'static`) + pub bounds: Punctuated<TypeParamBound, Token![+]>, + }), + + /// A lifetime predicate in a `where` clause: `'a: 'b + 'c`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Lifetime(PredicateLifetime { + pub lifetime: Lifetime, + pub colon_token: Option<Token![:]>, + pub bounds: Punctuated<Lifetime, Token![+]>, + }), + + /// An equality predicate in a `where` clause (unsupported). + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Eq(PredicateEq { + pub lhs_ty: Type, + pub eq_token: Token![=], + pub rhs_ty: Type, + }), + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + + use synom::Synom; + use punctuated::Pair; + + impl Synom for Generics { + named!(parse -> Self, map!( + alt!( + do_parse!( + lt: punct!(<) >> + lifetimes: call!(Punctuated::<LifetimeDef, Token![,]>::parse_terminated) >> + ty_params: cond!( + lifetimes.empty_or_trailing(), + Punctuated::<TypeParam, Token![,]>::parse_terminated + ) >> + gt: punct!(>) >> + (lifetimes, ty_params, Some(lt), Some(gt)) + ) + | + epsilon!() => { |_| (Punctuated::new(), None, None, None) } + ), + |(lifetimes, ty_params, lt, gt)| Generics { + lt_token: lt, + params: lifetimes.into_pairs() + .map(Pair::into_tuple) + .map(|(life, comma)| Pair::new(GenericParam::Lifetime(life), comma)) + .chain(ty_params.unwrap_or_default() + .into_pairs() + .map(Pair::into_tuple) + .map(|(ty, comma)| Pair::new(GenericParam::Type(ty), comma))) + .collect(), + gt_token: gt, + where_clause: None, + } + )); + + fn description() -> Option<&'static str> { + Some("generic parameters in declaration") + } + } + + impl Synom for GenericParam { + named!(parse -> Self, alt!( + syn!(TypeParam) => { GenericParam::Type } + | + syn!(LifetimeDef) => { GenericParam::Lifetime } + | + syn!(ConstParam) => { GenericParam::Const } + )); + + fn description() -> Option<&'static str> { + Some("generic parameter") + } + } + + impl Synom for LifetimeDef { + named!(parse -> Self, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + life: syn!(Lifetime) >> + colon: option!(punct!(:)) >> + bounds: cond!( + colon.is_some(), + Punctuated::parse_separated_nonempty + ) >> + (LifetimeDef { + attrs: attrs, + lifetime: life, + bounds: bounds.unwrap_or_default(), + colon_token: colon, + }) + )); + + fn description() -> Option<&'static str> { + Some("lifetime definition") + } + } + + impl Synom for BoundLifetimes { + named!(parse -> Self, do_parse!( + for_: keyword!(for) >> + lt: punct!(<) >> + lifetimes: call!(Punctuated::parse_terminated) >> + gt: punct!(>) >> + (BoundLifetimes { + for_token: for_, + lt_token: lt, + gt_token: gt, + lifetimes: lifetimes, + }) + )); + + fn description() -> Option<&'static str> { + Some("bound lifetimes") + } + } + + impl Synom for TypeParam { + named!(parse -> Self, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + id: syn!(Ident) >> + colon: option!(punct!(:)) >> + bounds: cond!( + colon.is_some(), + Punctuated::parse_separated_nonempty + ) >> + default: option!(do_parse!( + eq: punct!(=) >> + ty: syn!(Type) >> + (eq, ty) + )) >> + (TypeParam { + attrs: attrs, + ident: id, + bounds: bounds.unwrap_or_default(), + colon_token: colon, + eq_token: default.as_ref().map(|d| Token![=]((d.0).0)), + default: default.map(|d| d.1), + }) + )); + + fn description() -> Option<&'static str> { + Some("type parameter") + } + } + + impl Synom for TypeParamBound { + named!(parse -> Self, alt!( + syn!(Lifetime) => { TypeParamBound::Lifetime } + | + syn!(TraitBound) => { TypeParamBound::Trait } + | + parens!(syn!(TraitBound)) => {|(parens, mut bound)| { + bound.paren_token = Some(parens); + TypeParamBound::Trait(bound) + }} + )); + + fn description() -> Option<&'static str> { + Some("type parameter bound") + } + } + + impl Synom for TraitBound { + named!(parse -> Self, do_parse!( + modifier: syn!(TraitBoundModifier) >> + lifetimes: option!(syn!(BoundLifetimes)) >> + mut path: syn!(Path) >> + parenthesized: option!(cond_reduce!( + path.segments.last().unwrap().value().arguments.is_empty(), + syn!(ParenthesizedGenericArguments) + )) >> + ({ + if let Some(parenthesized) = parenthesized { + let parenthesized = PathArguments::Parenthesized(parenthesized); + path.segments.last_mut().unwrap().value_mut().arguments = parenthesized; + } + TraitBound { + paren_token: None, + modifier: modifier, + lifetimes: lifetimes, + path: path, + } + }) + )); + + fn description() -> Option<&'static str> { + Some("trait bound") + } + } + + impl Synom for TraitBoundModifier { + named!(parse -> Self, alt!( + punct!(?) => { TraitBoundModifier::Maybe } + | + epsilon!() => { |_| TraitBoundModifier::None } + )); + + fn description() -> Option<&'static str> { + Some("trait bound modifier") + } + } + + impl Synom for ConstParam { + named!(parse -> Self, do_parse!( + attrs: many0!(Attribute::parse_outer) >> + const_: keyword!(const) >> + ident: syn!(Ident) >> + colon: punct!(:) >> + ty: syn!(Type) >> + eq_def: option!(tuple!(punct!(=), syn!(Expr))) >> + ({ + let (eq_token, default) = match eq_def { + Some((eq_token, default)) => (Some(eq_token), Some(default)), + None => (None, None), + }; + ConstParam { + attrs: attrs, + const_token: const_, + ident: ident, + colon_token: colon, + ty: ty, + eq_token: eq_token, + default: default, + } + }) + )); + + fn description() -> Option<&'static str> { + Some("generic `const` parameter") + } + } + + impl Synom for WhereClause { + named!(parse -> Self, do_parse!( + where_: keyword!(where) >> + predicates: call!(Punctuated::parse_terminated) >> + (WhereClause { + predicates: predicates, + where_token: where_, + }) + )); + + fn description() -> Option<&'static str> { + Some("where clause") + } + } + + impl Synom for WherePredicate { + named!(parse -> Self, alt!( + do_parse!( + ident: syn!(Lifetime) >> + colon: option!(punct!(:)) >> + bounds: cond!( + colon.is_some(), + Punctuated::parse_separated + ) >> + (WherePredicate::Lifetime(PredicateLifetime { + lifetime: ident, + bounds: bounds.unwrap_or_default(), + colon_token: colon, + })) + ) + | + do_parse!( + lifetimes: option!(syn!(BoundLifetimes)) >> + bounded_ty: syn!(Type) >> + colon: punct!(:) >> + bounds: call!(Punctuated::parse_separated_nonempty) >> + (WherePredicate::Type(PredicateType { + lifetimes: lifetimes, + bounded_ty: bounded_ty, + bounds: bounds, + colon_token: colon, + })) + ) + )); + + fn description() -> Option<&'static str> { + Some("predicate in where clause") + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use attr::FilterAttrs; + use quote::{ToTokens, Tokens}; + + impl ToTokens for Generics { + fn to_tokens(&self, tokens: &mut Tokens) { + if self.params.is_empty() { + return; + } + + TokensOrDefault(&self.lt_token).to_tokens(tokens); + + // Print lifetimes before types and consts, regardless of their + // order in self.params. + // + // TODO: ordering rules for const parameters vs type parameters have + // not been settled yet. https://github.com/rust-lang/rust/issues/44580 + let mut trailing_or_empty = true; + for param in self.params.pairs() { + if let GenericParam::Lifetime(_) = **param.value() { + param.to_tokens(tokens); + trailing_or_empty = param.punct().is_some(); + } + } + for param in self.params.pairs() { + match **param.value() { + GenericParam::Type(_) | GenericParam::Const(_) => { + if !trailing_or_empty { + <Token![,]>::default().to_tokens(tokens); + trailing_or_empty = true; + } + param.to_tokens(tokens); + } + GenericParam::Lifetime(_) => {} + } + } + + TokensOrDefault(&self.gt_token).to_tokens(tokens); + } + } + + impl<'a> ToTokens for ImplGenerics<'a> { + fn to_tokens(&self, tokens: &mut Tokens) { + if self.0.params.is_empty() { + return; + } + + TokensOrDefault(&self.0.lt_token).to_tokens(tokens); + + // Print lifetimes before types and consts, regardless of their + // order in self.params. + // + // TODO: ordering rules for const parameters vs type parameters have + // not been settled yet. https://github.com/rust-lang/rust/issues/44580 + let mut trailing_or_empty = true; + for param in self.0.params.pairs() { + if let GenericParam::Lifetime(_) = **param.value() { + param.to_tokens(tokens); + trailing_or_empty = param.punct().is_some(); + } + } + for param in self.0.params.pairs() { + if let GenericParam::Lifetime(_) = **param.value() { + continue; + } + if !trailing_or_empty { + <Token![,]>::default().to_tokens(tokens); + trailing_or_empty = true; + } + match **param.value() { + GenericParam::Lifetime(_) => unreachable!(), + GenericParam::Type(ref param) => { + // Leave off the type parameter defaults + tokens.append_all(param.attrs.outer()); + param.ident.to_tokens(tokens); + if !param.bounds.is_empty() { + TokensOrDefault(¶m.colon_token).to_tokens(tokens); + param.bounds.to_tokens(tokens); + } + } + GenericParam::Const(ref param) => { + // Leave off the const parameter defaults + tokens.append_all(param.attrs.outer()); + param.const_token.to_tokens(tokens); + param.ident.to_tokens(tokens); + param.colon_token.to_tokens(tokens); + param.ty.to_tokens(tokens); + } + } + param.punct().to_tokens(tokens); + } + + TokensOrDefault(&self.0.gt_token).to_tokens(tokens); + } + } + + impl<'a> ToTokens for TypeGenerics<'a> { + fn to_tokens(&self, tokens: &mut Tokens) { + if self.0.params.is_empty() { + return; + } + + TokensOrDefault(&self.0.lt_token).to_tokens(tokens); + + // Print lifetimes before types and consts, regardless of their + // order in self.params. + // + // TODO: ordering rules for const parameters vs type parameters have + // not been settled yet. https://github.com/rust-lang/rust/issues/44580 + let mut trailing_or_empty = true; + for param in self.0.params.pairs() { + if let GenericParam::Lifetime(ref def) = **param.value() { + // Leave off the lifetime bounds and attributes + def.lifetime.to_tokens(tokens); + param.punct().to_tokens(tokens); + trailing_or_empty = param.punct().is_some(); + } + } + for param in self.0.params.pairs() { + if let GenericParam::Lifetime(_) = **param.value() { + continue; + } + if !trailing_or_empty { + <Token![,]>::default().to_tokens(tokens); + trailing_or_empty = true; + } + match **param.value() { + GenericParam::Lifetime(_) => unreachable!(), + GenericParam::Type(ref param) => { + // Leave off the type parameter defaults + param.ident.to_tokens(tokens); + } + GenericParam::Const(ref param) => { + // Leave off the const parameter defaults + param.ident.to_tokens(tokens); + } + } + param.punct().to_tokens(tokens); + } + + TokensOrDefault(&self.0.gt_token).to_tokens(tokens); + } + } + + impl<'a> ToTokens for Turbofish<'a> { + fn to_tokens(&self, tokens: &mut Tokens) { + if !self.0.params.is_empty() { + <Token![::]>::default().to_tokens(tokens); + TypeGenerics(self.0).to_tokens(tokens); + } + } + } + + impl ToTokens for BoundLifetimes { + fn to_tokens(&self, tokens: &mut Tokens) { + self.for_token.to_tokens(tokens); + self.lt_token.to_tokens(tokens); + self.lifetimes.to_tokens(tokens); + self.gt_token.to_tokens(tokens); + } + } + + impl ToTokens for LifetimeDef { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.lifetime.to_tokens(tokens); + if !self.bounds.is_empty() { + TokensOrDefault(&self.colon_token).to_tokens(tokens); + self.bounds.to_tokens(tokens); + } + } + } + + impl ToTokens for TypeParam { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.ident.to_tokens(tokens); + if !self.bounds.is_empty() { + TokensOrDefault(&self.colon_token).to_tokens(tokens); + self.bounds.to_tokens(tokens); + } + if self.default.is_some() { + TokensOrDefault(&self.eq_token).to_tokens(tokens); + self.default.to_tokens(tokens); + } + } + } + + impl ToTokens for TraitBound { + fn to_tokens(&self, tokens: &mut Tokens) { + let to_tokens = |tokens: &mut Tokens| { + self.modifier.to_tokens(tokens); + self.lifetimes.to_tokens(tokens); + self.path.to_tokens(tokens); + }; + match self.paren_token { + Some(ref paren) => paren.surround(tokens, to_tokens), + None => to_tokens(tokens), + } + } + } + + impl ToTokens for TraitBoundModifier { + fn to_tokens(&self, tokens: &mut Tokens) { + match *self { + TraitBoundModifier::None => {} + TraitBoundModifier::Maybe(ref t) => t.to_tokens(tokens), + } + } + } + + impl ToTokens for ConstParam { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.const_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.colon_token.to_tokens(tokens); + self.ty.to_tokens(tokens); + if self.default.is_some() { + TokensOrDefault(&self.eq_token).to_tokens(tokens); + self.default.to_tokens(tokens); + } + } + } + + impl ToTokens for WhereClause { + fn to_tokens(&self, tokens: &mut Tokens) { + if !self.predicates.is_empty() { + self.where_token.to_tokens(tokens); + self.predicates.to_tokens(tokens); + } + } + } + + impl ToTokens for PredicateType { + fn to_tokens(&self, tokens: &mut Tokens) { + self.lifetimes.to_tokens(tokens); + self.bounded_ty.to_tokens(tokens); + self.colon_token.to_tokens(tokens); + self.bounds.to_tokens(tokens); + } + } + + impl ToTokens for PredicateLifetime { + fn to_tokens(&self, tokens: &mut Tokens) { + self.lifetime.to_tokens(tokens); + if !self.bounds.is_empty() { + TokensOrDefault(&self.colon_token).to_tokens(tokens); + self.bounds.to_tokens(tokens); + } + } + } + + impl ToTokens for PredicateEq { + fn to_tokens(&self, tokens: &mut Tokens) { + self.lhs_ty.to_tokens(tokens); + self.eq_token.to_tokens(tokens); + self.rhs_ty.to_tokens(tokens); + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/gen_helper.rs cargo-0.26.0/vendor/syn-0.13.1/src/gen_helper.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/gen_helper.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/gen_helper.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,165 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[cfg(feature = "fold")] +pub mod fold { + use punctuated::{Pair, Punctuated}; + use fold::Fold; + use proc_macro2::Span; + + pub trait FoldHelper { + type Item; + fn lift<F>(self, f: F) -> Self + where + F: FnMut(Self::Item) -> Self::Item; + } + + impl<T> FoldHelper for Vec<T> { + type Item = T; + fn lift<F>(self, f: F) -> Self + where + F: FnMut(Self::Item) -> Self::Item, + { + self.into_iter().map(f).collect() + } + } + + impl<T, U> FoldHelper for Punctuated<T, U> { + type Item = T; + fn lift<F>(self, mut f: F) -> Self + where + F: FnMut(Self::Item) -> Self::Item, + { + self.into_pairs() + .map(Pair::into_tuple) + .map(|(t, u)| Pair::new(f(t), u)) + .collect() + } + } + + pub fn tokens_helper<F: Fold + ?Sized, S: Spans>(folder: &mut F, spans: &S) -> S { + spans.fold(folder) + } + + pub trait Spans { + fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self; + } + + impl Spans for Span { + fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self { + folder.fold_span(*self) + } + } + + impl Spans for [Span; 1] { + fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self { + [folder.fold_span(self[0])] + } + } + + impl Spans for [Span; 2] { + fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self { + [folder.fold_span(self[0]), folder.fold_span(self[1])] + } + } + + impl Spans for [Span; 3] { + fn fold<F: Fold + ?Sized>(&self, folder: &mut F) -> Self { + [ + folder.fold_span(self[0]), + folder.fold_span(self[1]), + folder.fold_span(self[2]), + ] + } + } +} + +#[cfg(feature = "visit")] +pub mod visit { + use proc_macro2::Span; + use visit::Visit; + + pub fn tokens_helper<'ast, V: Visit<'ast> + ?Sized, S: Spans>( + visitor: &mut V, + spans: &'ast S, + ) { + spans.visit(visitor); + } + + pub trait Spans { + fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V); + } + + impl Spans for Span { + fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V) { + visitor.visit_span(self); + } + } + + impl Spans for [Span; 1] { + fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V) { + visitor.visit_span(&self[0]); + } + } + + impl Spans for [Span; 2] { + fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V) { + visitor.visit_span(&self[0]); + visitor.visit_span(&self[1]); + } + } + + impl Spans for [Span; 3] { + fn visit<'ast, V: Visit<'ast> + ?Sized>(&'ast self, visitor: &mut V) { + visitor.visit_span(&self[0]); + visitor.visit_span(&self[1]); + visitor.visit_span(&self[2]); + } + } +} + +#[cfg(feature = "visit-mut")] +pub mod visit_mut { + use proc_macro2::Span; + use visit_mut::VisitMut; + + pub fn tokens_helper<V: VisitMut + ?Sized, S: Spans>(visitor: &mut V, spans: &mut S) { + spans.visit_mut(visitor); + } + + pub trait Spans { + fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V); + } + + impl Spans for Span { + fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V) { + visitor.visit_span_mut(self); + } + } + + impl Spans for [Span; 1] { + fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V) { + visitor.visit_span_mut(&mut self[0]); + } + } + + impl Spans for [Span; 2] { + fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V) { + visitor.visit_span_mut(&mut self[0]); + visitor.visit_span_mut(&mut self[1]); + } + } + + impl Spans for [Span; 3] { + fn visit_mut<V: VisitMut + ?Sized>(&mut self, visitor: &mut V) { + visitor.visit_span_mut(&mut self[0]); + visitor.visit_span_mut(&mut self[1]); + visitor.visit_span_mut(&mut self[2]); + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/ident.rs cargo-0.26.0/vendor/syn-0.13.1/src/ident.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/ident.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/ident.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,296 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::borrow::Cow; +use std::cmp::Ordering; +use std::fmt::{self, Display}; +use std::hash::{Hash, Hasher}; + +use proc_macro2::Term; +use unicode_xid::UnicodeXID; + +use proc_macro2::Span; + +/// A word of Rust code, which may be a keyword or legal variable name. +/// +/// An identifier consists of at least one Unicode code point, the first of +/// which has the XID_Start property and the rest of which have the XID_Continue +/// property. An underscore may be used as the first character as long as it is +/// not the only character. +/// +/// - The empty string is not an identifier. Use `Option<Ident>`. +/// - An underscore by itself is not an identifier. Use +/// `Token![_]` instead. +/// - A lifetime is not an identifier. Use `syn::Lifetime` instead. +/// +/// An identifier constructed with `Ident::new` is permitted to be a Rust +/// keyword, though parsing one through its [`Synom`] implementation rejects +/// Rust keywords. +/// +/// [`Synom`]: synom/trait.Synom.html +/// +/// # Examples +/// +/// A new ident can be created from a string using the `Ident::from` function. +/// Idents produced by `Ident::from` are set to resolve at the procedural macro +/// *def site* by default. A different span can be provided explicitly by using +/// `Ident::new`. +/// +/// ```rust +/// extern crate syn; +/// extern crate proc_macro2; +/// +/// use syn::Ident; +/// use proc_macro2::Span; +/// +/// fn main() { +/// let def_ident = Ident::from("definitely"); +/// let call_ident = Ident::new("calligraphy", Span::call_site()); +/// +/// println!("{} {}", def_ident, call_ident); +/// } +/// ``` +/// +/// An ident can be interpolated into a token stream using the `quote!` macro. +/// +/// ```rust +/// #[macro_use] +/// extern crate quote; +/// +/// extern crate syn; +/// use syn::Ident; +/// +/// fn main() { +/// let ident = Ident::from("demo"); +/// +/// // Create a variable binding whose name is this ident. +/// let expanded = quote! { let #ident = 10; }; +/// +/// // Create a variable binding with a slightly different name. +/// let temp_ident = Ident::from(format!("new_{}", ident)); +/// let expanded = quote! { let #temp_ident = 10; }; +/// } +/// ``` +/// +/// A string representation of the ident is available through the `as_ref()` and +/// `to_string()` methods. +/// +/// ```rust +/// # use syn::Ident; +/// # let ident = Ident::from("another_identifier"); +/// # +/// // Examine the ident as a &str. +/// let ident_str = ident.as_ref(); +/// if ident_str.len() > 60 { +/// println!("Very long identifier: {}", ident_str) +/// } +/// +/// // Create a String from the ident. +/// let ident_string = ident.to_string(); +/// give_away(ident_string); +/// +/// fn give_away(s: String) { /* ... */ } +/// ``` +#[derive(Copy, Clone, Debug)] +pub struct Ident { + term: Term, +} + +impl Ident { + /// Creates an ident with the given string representation. + /// + /// # Panics + /// + /// Panics if the input string is neither a keyword nor a legal variable + /// name. + pub fn new(s: &str, span: Span) -> Self { + if s.is_empty() { + panic!("ident is not allowed to be empty; use Option<Ident>"); + } + + if s.starts_with('\'') { + panic!("ident is not allowed to be a lifetime; use syn::Lifetime"); + } + + if s == "_" { + panic!("`_` is not a valid ident; use syn::token::Underscore"); + } + + if s.bytes().all(|digit| digit >= b'0' && digit <= b'9') { + panic!("ident cannot be a number, use syn::Index instead"); + } + + fn xid_ok(s: &str) -> bool { + let mut chars = s.chars(); + let first = chars.next().unwrap(); + if !(UnicodeXID::is_xid_start(first) || first == '_') { + return false; + } + for ch in chars { + if !UnicodeXID::is_xid_continue(ch) { + return false; + } + } + true + } + + if !xid_ok(s) { + panic!("{:?} is not a valid ident", s); + } + + Ident { + term: Term::new(s, span), + } + } + + pub fn span(&self) -> Span { + self.term.span() + } + + pub fn set_span(&mut self, span: Span) { + self.term.set_span(span); + } +} + +impl<'a> From<&'a str> for Ident { + fn from(s: &str) -> Self { + Ident::new(s, Span::call_site()) + } +} + +impl From<Token![self]> for Ident { + fn from(tok: Token![self]) -> Self { + Ident::new("self", tok.0) + } +} + +impl From<Token![Self]> for Ident { + fn from(tok: Token![Self]) -> Self { + Ident::new("Self", tok.0) + } +} + +impl From<Token![super]> for Ident { + fn from(tok: Token![super]) -> Self { + Ident::new("super", tok.0) + } +} + +impl From<Token![crate]> for Ident { + fn from(tok: Token![crate]) -> Self { + Ident::new("crate", tok.0) + } +} + +impl<'a> From<Cow<'a, str>> for Ident { + fn from(s: Cow<'a, str>) -> Self { + Ident::new(&s, Span::call_site()) + } +} + +impl From<String> for Ident { + fn from(s: String) -> Self { + Ident::new(&s, Span::call_site()) + } +} + +impl AsRef<str> for Ident { + fn as_ref(&self) -> &str { + self.term.as_str() + } +} + +impl Display for Ident { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.term.as_str().fmt(formatter) + } +} + +impl<T: ?Sized> PartialEq<T> for Ident +where + T: AsRef<str>, +{ + fn eq(&self, other: &T) -> bool { + self.as_ref() == other.as_ref() + } +} + +impl Eq for Ident {} + +impl PartialOrd for Ident { + fn partial_cmp(&self, other: &Ident) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for Ident { + fn cmp(&self, other: &Ident) -> Ordering { + self.as_ref().cmp(other.as_ref()) + } +} + +impl Hash for Ident { + fn hash<H: Hasher>(&self, h: &mut H) { + self.as_ref().hash(h); + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + use synom::Synom; + use buffer::Cursor; + use parse_error; + use synom::PResult; + + impl Synom for Ident { + fn parse(input: Cursor) -> PResult<Self> { + let (term, rest) = match input.term() { + Some(term) => term, + _ => return parse_error(), + }; + if term.as_str().starts_with('\'') { + return parse_error(); + } + match term.as_str() { + // From https://doc.rust-lang.org/grammar.html#keywords + "abstract" | "alignof" | "as" | "become" | "box" | "break" | "const" + | "continue" | "crate" | "do" | "else" | "enum" | "extern" | "false" | "final" + | "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" | "macro" | "match" + | "mod" | "move" | "mut" | "offsetof" | "override" | "priv" | "proc" | "pub" + | "pure" | "ref" | "return" | "Self" | "self" | "sizeof" | "static" | "struct" + | "super" | "trait" | "true" | "type" | "typeof" | "unsafe" | "unsized" | "use" + | "virtual" | "where" | "while" | "yield" => return parse_error(), + _ => {} + } + + Ok(( + Ident { + term: term, + }, + rest, + )) + } + + fn description() -> Option<&'static str> { + Some("identifier") + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use quote::{ToTokens, Tokens}; + + impl ToTokens for Ident { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append(self.term); + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/item.rs cargo-0.26.0/vendor/syn-0.13.1/src/item.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/item.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/item.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,2033 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use super::*; +use derive::{Data, DeriveInput}; +use punctuated::Punctuated; +use proc_macro2::TokenStream; +use token::{Brace, Paren}; + +#[cfg(feature = "extra-traits")] +use tt::TokenStreamHelper; +#[cfg(feature = "extra-traits")] +use std::hash::{Hash, Hasher}; + +ast_enum_of_structs! { + /// Things that can appear directly inside of a module or scope. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum Item { + /// An `extern crate` item: `extern crate serde`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub ExternCrate(ItemExternCrate { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub extern_token: Token![extern], + pub crate_token: Token![crate], + pub ident: Ident, + pub rename: Option<(Token![as], Ident)>, + pub semi_token: Token![;], + }), + + /// A use declaration: `use std::collections::HashMap`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Use(ItemUse { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub use_token: Token![use], + pub leading_colon: Option<Token![::]>, + pub tree: UseTree, + pub semi_token: Token![;], + }), + + /// A static item: `static BIKE: Shed = Shed(42)`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Static(ItemStatic { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub static_token: Token![static], + pub mutability: Option<Token![mut]>, + pub ident: Ident, + pub colon_token: Token![:], + pub ty: Box<Type>, + pub eq_token: Token![=], + pub expr: Box<Expr>, + pub semi_token: Token![;], + }), + + /// A constant item: `const MAX: u16 = 65535`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Const(ItemConst { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub const_token: Token![const], + pub ident: Ident, + pub colon_token: Token![:], + pub ty: Box<Type>, + pub eq_token: Token![=], + pub expr: Box<Expr>, + pub semi_token: Token![;], + }), + + /// A free-standing function: `fn process(n: usize) -> Result<()> { ... + /// }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Fn(ItemFn { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub constness: Option<Token![const]>, + pub unsafety: Option<Token![unsafe]>, + pub abi: Option<Abi>, + pub ident: Ident, + pub decl: Box<FnDecl>, + pub block: Box<Block>, + }), + + /// A module or module declaration: `mod m` or `mod m { ... }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Mod(ItemMod { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub mod_token: Token![mod], + pub ident: Ident, + pub content: Option<(token::Brace, Vec<Item>)>, + pub semi: Option<Token![;]>, + }), + + /// A block of foreign items: `extern "C" { ... }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub ForeignMod(ItemForeignMod { + pub attrs: Vec<Attribute>, + pub abi: Abi, + pub brace_token: token::Brace, + pub items: Vec<ForeignItem>, + }), + + /// A type alias: `type Result<T> = std::result::Result<T, MyError>`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Type(ItemType { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub type_token: Token![type], + pub ident: Ident, + pub generics: Generics, + pub eq_token: Token![=], + pub ty: Box<Type>, + pub semi_token: Token![;], + }), + + /// A struct definition: `struct Foo<A> { x: A }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Struct(ItemStruct { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub struct_token: Token![struct], + pub ident: Ident, + pub generics: Generics, + pub fields: Fields, + pub semi_token: Option<Token![;]>, + }), + + /// An enum definition: `enum Foo<A, B> { C<A>, D<B> }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Enum(ItemEnum { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub enum_token: Token![enum], + pub ident: Ident, + pub generics: Generics, + pub brace_token: token::Brace, + pub variants: Punctuated<Variant, Token![,]>, + }), + + /// A union definition: `union Foo<A, B> { x: A, y: B }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Union(ItemUnion { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub union_token: Token![union], + pub ident: Ident, + pub generics: Generics, + pub fields: FieldsNamed, + }), + + /// A trait definition: `pub trait Iterator { ... }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Trait(ItemTrait { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub unsafety: Option<Token![unsafe]>, + pub auto_token: Option<Token![auto]>, + pub trait_token: Token![trait], + pub ident: Ident, + pub generics: Generics, + pub colon_token: Option<Token![:]>, + pub supertraits: Punctuated<TypeParamBound, Token![+]>, + pub brace_token: token::Brace, + pub items: Vec<TraitItem>, + }), + + /// An impl block providing trait or associated items: `impl<A> Trait + /// for Data<A> { ... }`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Impl(ItemImpl { + pub attrs: Vec<Attribute>, + pub defaultness: Option<Token![default]>, + pub unsafety: Option<Token![unsafe]>, + pub impl_token: Token![impl], + pub generics: Generics, + /// Trait this impl implements. + pub trait_: Option<(Option<Token![!]>, Path, Token![for])>, + /// The Self type of the impl. + pub self_ty: Box<Type>, + pub brace_token: token::Brace, + pub items: Vec<ImplItem>, + }), + + /// A macro invocation, which includes `macro_rules!` definitions. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Macro(ItemMacro { + pub attrs: Vec<Attribute>, + /// The `example` in `macro_rules! example { ... }`. + pub ident: Option<Ident>, + pub mac: Macro, + pub semi_token: Option<Token![;]>, + }), + + /// A 2.0-style declarative macro introduced by the `macro` keyword. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Macro2(ItemMacro2 #manual_extra_traits { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub macro_token: Token![macro], + pub ident: Ident, + pub paren_token: Paren, + pub args: TokenStream, + pub brace_token: Brace, + pub body: TokenStream, + }), + + /// Tokens forming an item not interpreted by Syn. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Verbatim(ItemVerbatim #manual_extra_traits { + pub tts: TokenStream, + }), + } +} + +#[cfg(feature = "extra-traits")] +impl Eq for ItemMacro2 {} + +#[cfg(feature = "extra-traits")] +impl PartialEq for ItemMacro2 { + fn eq(&self, other: &Self) -> bool { + self.attrs == other.attrs && self.vis == other.vis && self.macro_token == other.macro_token + && self.ident == other.ident && self.paren_token == other.paren_token + && TokenStreamHelper(&self.args) == TokenStreamHelper(&other.args) + && self.brace_token == other.brace_token + && TokenStreamHelper(&self.body) == TokenStreamHelper(&other.body) + } +} + +#[cfg(feature = "extra-traits")] +impl Hash for ItemMacro2 { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.attrs.hash(state); + self.vis.hash(state); + self.macro_token.hash(state); + self.ident.hash(state); + self.paren_token.hash(state); + TokenStreamHelper(&self.args).hash(state); + self.brace_token.hash(state); + TokenStreamHelper(&self.body).hash(state); + } +} + +#[cfg(feature = "extra-traits")] +impl Eq for ItemVerbatim {} + +#[cfg(feature = "extra-traits")] +impl PartialEq for ItemVerbatim { + fn eq(&self, other: &Self) -> bool { + TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) + } +} + +#[cfg(feature = "extra-traits")] +impl Hash for ItemVerbatim { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + TokenStreamHelper(&self.tts).hash(state); + } +} + +impl From<DeriveInput> for Item { + fn from(input: DeriveInput) -> Item { + match input.data { + Data::Struct(data) => Item::Struct(ItemStruct { + attrs: input.attrs, + vis: input.vis, + struct_token: data.struct_token, + ident: input.ident, + generics: input.generics, + fields: data.fields, + semi_token: data.semi_token, + }), + Data::Enum(data) => Item::Enum(ItemEnum { + attrs: input.attrs, + vis: input.vis, + enum_token: data.enum_token, + ident: input.ident, + generics: input.generics, + brace_token: data.brace_token, + variants: data.variants, + }), + Data::Union(data) => Item::Union(ItemUnion { + attrs: input.attrs, + vis: input.vis, + union_token: data.union_token, + ident: input.ident, + generics: input.generics, + fields: data.fields, + }), + } + } +} + +ast_enum_of_structs! { + /// A suffix of an import tree in a `use` item: `Type as Renamed` or `*`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum UseTree { + /// A path prefix of imports in a `use` item: `std::...`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Path(UsePath { + pub ident: Ident, + pub colon2_token: Token![::], + pub tree: Box<UseTree>, + }), + + /// An identifier imported by a `use` item: `HashMap`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Name(UseName { + pub ident: Ident, + }), + + /// An renamed identifier imported by a `use` item: `HashMap as Map`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Rename(UseRename { + pub ident: Ident, + pub as_token: Token![as], + pub rename: Ident, + }), + + /// A glob import in a `use` item: `*`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Glob(UseGlob { + pub star_token: Token![*], + }), + + /// A braced group of imports in a `use` item: `{A, B, C}`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Group(UseGroup { + pub brace_token: token::Brace, + pub items: Punctuated<UseTree, Token![,]>, + }), + } +} + +ast_enum_of_structs! { + /// An item within an `extern` block. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum ForeignItem { + /// A foreign function in an `extern` block. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Fn(ForeignItemFn { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub ident: Ident, + pub decl: Box<FnDecl>, + pub semi_token: Token![;], + }), + + /// A foreign static item in an `extern` block: `static ext: u8`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Static(ForeignItemStatic { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub static_token: Token![static], + pub mutability: Option<Token![mut]>, + pub ident: Ident, + pub colon_token: Token![:], + pub ty: Box<Type>, + pub semi_token: Token![;], + }), + + /// A foreign type in an `extern` block: `type void`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Type(ForeignItemType { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub type_token: Token![type], + pub ident: Ident, + pub semi_token: Token![;], + }), + + /// Tokens in an `extern` block not interpreted by Syn. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Verbatim(ForeignItemVerbatim #manual_extra_traits { + pub tts: TokenStream, + }), + } +} + +#[cfg(feature = "extra-traits")] +impl Eq for ForeignItemVerbatim {} + +#[cfg(feature = "extra-traits")] +impl PartialEq for ForeignItemVerbatim { + fn eq(&self, other: &Self) -> bool { + TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) + } +} + +#[cfg(feature = "extra-traits")] +impl Hash for ForeignItemVerbatim { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + TokenStreamHelper(&self.tts).hash(state); + } +} + +ast_enum_of_structs! { + /// An item declaration within the definition of a trait. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum TraitItem { + /// An associated constant within the definition of a trait. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Const(TraitItemConst { + pub attrs: Vec<Attribute>, + pub const_token: Token![const], + pub ident: Ident, + pub colon_token: Token![:], + pub ty: Type, + pub default: Option<(Token![=], Expr)>, + pub semi_token: Token![;], + }), + + /// A trait method within the definition of a trait. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Method(TraitItemMethod { + pub attrs: Vec<Attribute>, + pub sig: MethodSig, + pub default: Option<Block>, + pub semi_token: Option<Token![;]>, + }), + + /// An associated type within the definition of a trait. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Type(TraitItemType { + pub attrs: Vec<Attribute>, + pub type_token: Token![type], + pub ident: Ident, + pub generics: Generics, + pub colon_token: Option<Token![:]>, + pub bounds: Punctuated<TypeParamBound, Token![+]>, + pub default: Option<(Token![=], Type)>, + pub semi_token: Token![;], + }), + + /// A macro invocation within the definition of a trait. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Macro(TraitItemMacro { + pub attrs: Vec<Attribute>, + pub mac: Macro, + pub semi_token: Option<Token![;]>, + }), + + /// Tokens within the definition of a trait not interpreted by Syn. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Verbatim(TraitItemVerbatim #manual_extra_traits { + pub tts: TokenStream, + }), + } +} + +#[cfg(feature = "extra-traits")] +impl Eq for TraitItemVerbatim {} + +#[cfg(feature = "extra-traits")] +impl PartialEq for TraitItemVerbatim { + fn eq(&self, other: &Self) -> bool { + TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) + } +} + +#[cfg(feature = "extra-traits")] +impl Hash for TraitItemVerbatim { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + TokenStreamHelper(&self.tts).hash(state); + } +} + +ast_enum_of_structs! { + /// An item within an impl block. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum ImplItem { + /// An associated constant within an impl block. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Const(ImplItemConst { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub defaultness: Option<Token![default]>, + pub const_token: Token![const], + pub ident: Ident, + pub colon_token: Token![:], + pub ty: Type, + pub eq_token: Token![=], + pub expr: Expr, + pub semi_token: Token![;], + }), + + /// A method within an impl block. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Method(ImplItemMethod { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub defaultness: Option<Token![default]>, + pub sig: MethodSig, + pub block: Block, + }), + + /// An associated type within an impl block. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Type(ImplItemType { + pub attrs: Vec<Attribute>, + pub vis: Visibility, + pub defaultness: Option<Token![default]>, + pub type_token: Token![type], + pub ident: Ident, + pub generics: Generics, + pub eq_token: Token![=], + pub ty: Type, + pub semi_token: Token![;], + }), + + /// A macro invocation within an impl block. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Macro(ImplItemMacro { + pub attrs: Vec<Attribute>, + pub mac: Macro, + pub semi_token: Option<Token![;]>, + }), + + /// Tokens within an impl block not interpreted by Syn. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Verbatim(ImplItemVerbatim #manual_extra_traits { + pub tts: TokenStream, + }), + } +} + +#[cfg(feature = "extra-traits")] +impl Eq for ImplItemVerbatim {} + +#[cfg(feature = "extra-traits")] +impl PartialEq for ImplItemVerbatim { + fn eq(&self, other: &Self) -> bool { + TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) + } +} + +#[cfg(feature = "extra-traits")] +impl Hash for ImplItemVerbatim { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + TokenStreamHelper(&self.tts).hash(state); + } +} + +ast_struct! { + /// A method's signature in a trait or implementation: `unsafe fn + /// initialize(&self)`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub struct MethodSig { + pub constness: Option<Token![const]>, + pub unsafety: Option<Token![unsafe]>, + pub abi: Option<Abi>, + pub ident: Ident, + pub decl: FnDecl, + } +} + +ast_struct! { + /// Header of a function declaration, without including the body. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub struct FnDecl { + pub fn_token: Token![fn], + pub generics: Generics, + pub paren_token: token::Paren, + pub inputs: Punctuated<FnArg, Token![,]>, + pub variadic: Option<Token![...]>, + pub output: ReturnType, + } +} + +ast_enum_of_structs! { + /// An argument in a function signature: the `n: usize` in `fn f(n: usize)`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum FnArg { + /// Self captured by reference in a function signature: `&self` or `&mut + /// self`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub SelfRef(ArgSelfRef { + pub and_token: Token![&], + pub lifetime: Option<Lifetime>, + pub mutability: Option<Token![mut]>, + pub self_token: Token![self], + }), + + /// Self captured by value in a function signature: `self` or `mut + /// self`. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub SelfValue(ArgSelf { + pub mutability: Option<Token![mut]>, + pub self_token: Token![self], + }), + + /// An explicitly typed pattern captured by a function signature. + /// + /// *This type is available if Syn is built with the `"full"` feature.* + pub Captured(ArgCaptured { + pub pat: Pat, + pub colon_token: Token![:], + pub ty: Type, + }), + + /// A pattern whose type is inferred captured by a function signature. + pub Inferred(Pat), + /// A type not bound to any pattern in a function signature. + pub Ignored(Type), + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + + use synom::Synom; + + impl_synom!(Item "item" alt!( + syn!(ItemExternCrate) => { Item::ExternCrate } + | + syn!(ItemUse) => { Item::Use } + | + syn!(ItemStatic) => { Item::Static } + | + syn!(ItemConst) => { Item::Const } + | + syn!(ItemFn) => { Item::Fn } + | + syn!(ItemMod) => { Item::Mod } + | + syn!(ItemForeignMod) => { Item::ForeignMod } + | + syn!(ItemType) => { Item::Type } + | + syn!(ItemStruct) => { Item::Struct } + | + syn!(ItemEnum) => { Item::Enum } + | + syn!(ItemUnion) => { Item::Union } + | + syn!(ItemTrait) => { Item::Trait } + | + syn!(ItemImpl) => { Item::Impl } + | + syn!(ItemMacro) => { Item::Macro } + | + syn!(ItemMacro2) => { Item::Macro2 } + )); + + impl_synom!(ItemMacro "macro item" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + what: call!(Path::parse_mod_style) >> + bang: punct!(!) >> + ident: option!(syn!(Ident)) >> + body: call!(tt::delimited) >> + semi: cond!(!is_brace(&body.0), punct!(;)) >> + (ItemMacro { + attrs: attrs, + ident: ident, + mac: Macro { + path: what, + bang_token: bang, + delimiter: body.0, + tts: body.1, + }, + semi_token: semi, + }) + )); + + // TODO: figure out the actual grammar; is body required to be braced? + impl_synom!(ItemMacro2 "macro2 item" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + macro_: keyword!(macro) >> + ident: syn!(Ident) >> + args: call!(tt::parenthesized) >> + body: call!(tt::braced) >> + (ItemMacro2 { + attrs: attrs, + vis: vis, + macro_token: macro_, + ident: ident, + paren_token: args.0, + args: args.1, + brace_token: body.0, + body: body.1, + }) + )); + + impl_synom!(ItemExternCrate "extern crate item" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + extern_: keyword!(extern) >> + crate_: keyword!(crate) >> + ident: syn!(Ident) >> + rename: option!(tuple!(keyword!(as), syn!(Ident))) >> + semi: punct!(;) >> + (ItemExternCrate { + attrs: attrs, + vis: vis, + extern_token: extern_, + crate_token: crate_, + ident: ident, + rename: rename, + semi_token: semi, + }) + )); + + impl_synom!(ItemUse "use item" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + use_: keyword!(use) >> + leading_colon: option!(punct!(::)) >> + tree: syn!(UseTree) >> + semi: punct!(;) >> + (ItemUse { + attrs: attrs, + vis: vis, + use_token: use_, + leading_colon: leading_colon, + tree: tree, + semi_token: semi, + }) + )); + + named!(use_element -> Ident, alt!( + syn!(Ident) + | + keyword!(self) => { Into::into } + | + keyword!(super) => { Into::into } + | + keyword!(crate) => { Into::into } + )); + + impl_synom!(UseTree "use tree" alt!( + syn!(UseRename) => { UseTree::Rename } + | + syn!(UsePath) => { UseTree::Path } + | + syn!(UseName) => { UseTree::Name } + | + syn!(UseGlob) => { UseTree::Glob } + | + syn!(UseGroup) => { UseTree::Group } + )); + + impl_synom!(UsePath "use path" do_parse!( + ident: call!(use_element) >> + colon2_token: punct!(::) >> + tree: syn!(UseTree) >> + (UsePath { + ident: ident, + colon2_token: colon2_token, + tree: Box::new(tree), + }) + )); + + impl_synom!(UseName "use name" do_parse!( + ident: call!(use_element) >> + (UseName { + ident: ident, + }) + )); + + impl_synom!(UseRename "use rename" do_parse!( + ident: call!(use_element) >> + as_token: keyword!(as) >> + rename: syn!(Ident) >> + (UseRename { + ident: ident, + as_token: as_token, + rename: rename, + }) + )); + + impl_synom!(UseGlob "use glob" do_parse!( + star: punct!(*) >> + (UseGlob { + star_token: star, + }) + )); + + impl_synom!(UseGroup "use group" do_parse!( + list: braces!(Punctuated::parse_terminated) >> + (UseGroup { + brace_token: list.0, + items: list.1, + }) + )); + + impl_synom!(ItemStatic "static item" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + static_: keyword!(static) >> + mutability: option!(keyword!(mut)) >> + ident: syn!(Ident) >> + colon: punct!(:) >> + ty: syn!(Type) >> + eq: punct!(=) >> + value: syn!(Expr) >> + semi: punct!(;) >> + (ItemStatic { + attrs: attrs, + vis: vis, + static_token: static_, + mutability: mutability, + ident: ident, + colon_token: colon, + ty: Box::new(ty), + eq_token: eq, + expr: Box::new(value), + semi_token: semi, + }) + )); + + impl_synom!(ItemConst "const item" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + const_: keyword!(const) >> + ident: syn!(Ident) >> + colon: punct!(:) >> + ty: syn!(Type) >> + eq: punct!(=) >> + value: syn!(Expr) >> + semi: punct!(;) >> + (ItemConst { + attrs: attrs, + vis: vis, + const_token: const_, + ident: ident, + colon_token: colon, + ty: Box::new(ty), + eq_token: eq, + expr: Box::new(value), + semi_token: semi, + }) + )); + + impl_synom!(ItemFn "fn item" do_parse!( + outer_attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + constness: option!(keyword!(const)) >> + unsafety: option!(keyword!(unsafe)) >> + abi: option!(syn!(Abi)) >> + fn_: keyword!(fn) >> + ident: syn!(Ident) >> + generics: syn!(Generics) >> + inputs: parens!(Punctuated::parse_terminated) >> + ret: syn!(ReturnType) >> + where_clause: option!(syn!(WhereClause)) >> + inner_attrs_stmts: braces!(tuple!( + many0!(Attribute::parse_inner), + call!(Block::parse_within) + )) >> + (ItemFn { + attrs: { + let mut attrs = outer_attrs; + attrs.extend((inner_attrs_stmts.1).0); + attrs + }, + vis: vis, + constness: constness, + unsafety: unsafety, + abi: abi, + decl: Box::new(FnDecl { + fn_token: fn_, + paren_token: inputs.0, + inputs: inputs.1, + output: ret, + variadic: None, + generics: Generics { + where_clause: where_clause, + .. generics + }, + }), + ident: ident, + block: Box::new(Block { + brace_token: inner_attrs_stmts.0, + stmts: (inner_attrs_stmts.1).1, + }), + }) + )); + + impl Synom for FnArg { + named!(parse -> Self, alt!( + do_parse!( + and: punct!(&) >> + lt: option!(syn!(Lifetime)) >> + mutability: option!(keyword!(mut)) >> + self_: keyword!(self) >> + not!(punct!(:)) >> + (ArgSelfRef { + lifetime: lt, + mutability: mutability, + and_token: and, + self_token: self_, + }.into()) + ) + | + do_parse!( + mutability: option!(keyword!(mut)) >> + self_: keyword!(self) >> + not!(punct!(:)) >> + (ArgSelf { + mutability: mutability, + self_token: self_, + }.into()) + ) + | + do_parse!( + pat: syn!(Pat) >> + colon: punct!(:) >> + ty: syn!(Type) >> + (ArgCaptured { + pat: pat, + ty: ty, + colon_token: colon, + }.into()) + ) + | + syn!(Type) => { FnArg::Ignored } + )); + + fn description() -> Option<&'static str> { + Some("function argument") + } + } + + impl_synom!(ItemMod "mod item" do_parse!( + outer_attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + mod_: keyword!(mod) >> + ident: syn!(Ident) >> + content_semi: alt!( + punct!(;) => {|semi| ( + Vec::new(), + None, + Some(semi), + )} + | + braces!( + tuple!( + many0!(Attribute::parse_inner), + many0!(Item::parse) + ) + ) => {|(brace, (inner_attrs, items))| ( + inner_attrs, + Some((brace, items)), + None, + )} + ) >> + (ItemMod { + attrs: { + let mut attrs = outer_attrs; + attrs.extend(content_semi.0); + attrs + }, + vis: vis, + mod_token: mod_, + ident: ident, + content: content_semi.1, + semi: content_semi.2, + }) + )); + + impl_synom!(ItemForeignMod "foreign mod item" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + abi: syn!(Abi) >> + items: braces!(many0!(ForeignItem::parse)) >> + (ItemForeignMod { + attrs: attrs, + abi: abi, + brace_token: items.0, + items: items.1, + }) + )); + + impl_synom!(ForeignItem "foreign item" alt!( + syn!(ForeignItemFn) => { ForeignItem::Fn } + | + syn!(ForeignItemStatic) => { ForeignItem::Static } + | + syn!(ForeignItemType) => { ForeignItem::Type } + )); + + impl_synom!(ForeignItemFn "foreign function" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + fn_: keyword!(fn) >> + ident: syn!(Ident) >> + generics: syn!(Generics) >> + inputs: parens!(do_parse!( + args: call!(Punctuated::parse_terminated) >> + variadic: option!(cond_reduce!(args.empty_or_trailing(), punct!(...))) >> + (args, variadic) + )) >> + ret: syn!(ReturnType) >> + where_clause: option!(syn!(WhereClause)) >> + semi: punct!(;) >> + ({ + let (parens, (inputs, variadic)) = inputs; + ForeignItemFn { + ident: ident, + attrs: attrs, + semi_token: semi, + decl: Box::new(FnDecl { + fn_token: fn_, + paren_token: parens, + inputs: inputs, + variadic: variadic, + output: ret, + generics: Generics { + where_clause: where_clause, + .. generics + }, + }), + vis: vis, + } + }) + )); + + impl_synom!(ForeignItemStatic "foreign static" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + static_: keyword!(static) >> + mutability: option!(keyword!(mut)) >> + ident: syn!(Ident) >> + colon: punct!(:) >> + ty: syn!(Type) >> + semi: punct!(;) >> + (ForeignItemStatic { + ident: ident, + attrs: attrs, + semi_token: semi, + ty: Box::new(ty), + mutability: mutability, + static_token: static_, + colon_token: colon, + vis: vis, + }) + )); + + impl_synom!(ForeignItemType "foreign type" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + type_: keyword!(type) >> + ident: syn!(Ident) >> + semi: punct!(;) >> + (ForeignItemType { + attrs: attrs, + vis: vis, + type_token: type_, + ident: ident, + semi_token: semi, + }) + )); + + impl_synom!(ItemType "type item" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + type_: keyword!(type) >> + ident: syn!(Ident) >> + generics: syn!(Generics) >> + where_clause: option!(syn!(WhereClause)) >> + eq: punct!(=) >> + ty: syn!(Type) >> + semi: punct!(;) >> + (ItemType { + attrs: attrs, + vis: vis, + type_token: type_, + ident: ident, + generics: Generics { + where_clause: where_clause, + ..generics + }, + eq_token: eq, + ty: Box::new(ty), + semi_token: semi, + }) + )); + + impl_synom!(ItemStruct "struct item" switch!( + map!(syn!(DeriveInput), Into::into), + Item::Struct(item) => value!(item) + | + _ => reject!() + )); + + impl_synom!(ItemEnum "enum item" switch!( + map!(syn!(DeriveInput), Into::into), + Item::Enum(item) => value!(item) + | + _ => reject!() + )); + + impl_synom!(ItemUnion "union item" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + union_: keyword!(union) >> + ident: syn!(Ident) >> + generics: syn!(Generics) >> + where_clause: option!(syn!(WhereClause)) >> + fields: syn!(FieldsNamed) >> + (ItemUnion { + attrs: attrs, + vis: vis, + union_token: union_, + ident: ident, + generics: Generics { + where_clause: where_clause, + .. generics + }, + fields: fields, + }) + )); + + impl_synom!(ItemTrait "trait item" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + unsafety: option!(keyword!(unsafe)) >> + auto_: option!(keyword!(auto)) >> + trait_: keyword!(trait) >> + ident: syn!(Ident) >> + generics: syn!(Generics) >> + colon: option!(punct!(:)) >> + bounds: cond!(colon.is_some(), Punctuated::parse_separated_nonempty) >> + where_clause: option!(syn!(WhereClause)) >> + body: braces!(many0!(TraitItem::parse)) >> + (ItemTrait { + attrs: attrs, + vis: vis, + unsafety: unsafety, + auto_token: auto_, + trait_token: trait_, + ident: ident, + generics: Generics { + where_clause: where_clause, + .. generics + }, + colon_token: colon, + supertraits: bounds.unwrap_or_default(), + brace_token: body.0, + items: body.1, + }) + )); + + impl_synom!(TraitItem "trait item" alt!( + syn!(TraitItemConst) => { TraitItem::Const } + | + syn!(TraitItemMethod) => { TraitItem::Method } + | + syn!(TraitItemType) => { TraitItem::Type } + | + syn!(TraitItemMacro) => { TraitItem::Macro } + )); + + impl_synom!(TraitItemConst "const trait item" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + const_: keyword!(const) >> + ident: syn!(Ident) >> + colon: punct!(:) >> + ty: syn!(Type) >> + default: option!(tuple!(punct!(=), syn!(Expr))) >> + semi: punct!(;) >> + (TraitItemConst { + attrs: attrs, + const_token: const_, + ident: ident, + colon_token: colon, + ty: ty, + default: default, + semi_token: semi, + }) + )); + + impl_synom!(TraitItemMethod "method trait item" do_parse!( + outer_attrs: many0!(Attribute::parse_outer) >> + constness: option!(keyword!(const)) >> + unsafety: option!(keyword!(unsafe)) >> + abi: option!(syn!(Abi)) >> + fn_: keyword!(fn) >> + ident: syn!(Ident) >> + generics: syn!(Generics) >> + inputs: parens!(Punctuated::parse_terminated) >> + ret: syn!(ReturnType) >> + where_clause: option!(syn!(WhereClause)) >> + body: option!(braces!( + tuple!(many0!(Attribute::parse_inner), + call!(Block::parse_within)) + )) >> + semi: cond!(body.is_none(), punct!(;)) >> + ({ + let (inner_attrs, stmts) = match body { + Some((b, (inner_attrs, stmts))) => (inner_attrs, Some((stmts, b))), + None => (Vec::new(), None), + }; + TraitItemMethod { + attrs: { + let mut attrs = outer_attrs; + attrs.extend(inner_attrs); + attrs + }, + sig: MethodSig { + constness: constness, + unsafety: unsafety, + abi: abi, + ident: ident, + decl: FnDecl { + inputs: inputs.1, + output: ret, + fn_token: fn_, + paren_token: inputs.0, + variadic: None, + generics: Generics { + where_clause: where_clause, + .. generics + }, + }, + }, + default: stmts.map(|stmts| { + Block { + stmts: stmts.0, + brace_token: stmts.1, + } + }), + semi_token: semi, + } + }) + )); + + impl_synom!(TraitItemType "trait item type" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + type_: keyword!(type) >> + ident: syn!(Ident) >> + generics: syn!(Generics) >> + colon: option!(punct!(:)) >> + bounds: cond!(colon.is_some(), Punctuated::parse_separated_nonempty) >> + where_clause: option!(syn!(WhereClause)) >> + default: option!(tuple!(punct!(=), syn!(Type))) >> + semi: punct!(;) >> + (TraitItemType { + attrs: attrs, + type_token: type_, + ident: ident, + generics: Generics { + where_clause: where_clause, + .. generics + }, + colon_token: colon, + bounds: bounds.unwrap_or_default(), + default: default, + semi_token: semi, + }) + )); + + impl_synom!(TraitItemMacro "trait item macro" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + mac: syn!(Macro) >> + semi: cond!(!is_brace(&mac.delimiter), punct!(;)) >> + (TraitItemMacro { + attrs: attrs, + mac: mac, + semi_token: semi, + }) + )); + + impl_synom!(ItemImpl "impl item" do_parse!( + outer_attrs: many0!(Attribute::parse_outer) >> + defaultness: option!(keyword!(default)) >> + unsafety: option!(keyword!(unsafe)) >> + impl_: keyword!(impl) >> + generics: syn!(Generics) >> + polarity_path: alt!( + do_parse!( + polarity: option!(punct!(!)) >> + path: syn!(Path) >> + for_: keyword!(for) >> + (Some((polarity, path, for_))) + ) + | + epsilon!() => { |_| None } + ) >> + self_ty: syn!(Type) >> + where_clause: option!(syn!(WhereClause)) >> + inner: braces!(tuple!( + many0!(Attribute::parse_inner), + many0!(ImplItem::parse) + )) >> + (ItemImpl { + attrs: { + let mut attrs = outer_attrs; + attrs.extend((inner.1).0); + attrs + }, + defaultness: defaultness, + unsafety: unsafety, + impl_token: impl_, + generics: Generics { + where_clause: where_clause, + .. generics + }, + trait_: polarity_path, + self_ty: Box::new(self_ty), + brace_token: inner.0, + items: (inner.1).1, + }) + )); + + impl_synom!(ImplItem "item in impl block" alt!( + syn!(ImplItemConst) => { ImplItem::Const } + | + syn!(ImplItemMethod) => { ImplItem::Method } + | + syn!(ImplItemType) => { ImplItem::Type } + | + syn!(ImplItemMacro) => { ImplItem::Macro } + )); + + impl_synom!(ImplItemConst "const item in impl block" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + defaultness: option!(keyword!(default)) >> + const_: keyword!(const) >> + ident: syn!(Ident) >> + colon: punct!(:) >> + ty: syn!(Type) >> + eq: punct!(=) >> + value: syn!(Expr) >> + semi: punct!(;) >> + (ImplItemConst { + attrs: attrs, + vis: vis, + defaultness: defaultness, + const_token: const_, + ident: ident, + colon_token: colon, + ty: ty, + eq_token: eq, + expr: value, + semi_token: semi, + }) + )); + + impl_synom!(ImplItemMethod "method in impl block" do_parse!( + outer_attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + defaultness: option!(keyword!(default)) >> + constness: option!(keyword!(const)) >> + unsafety: option!(keyword!(unsafe)) >> + abi: option!(syn!(Abi)) >> + fn_: keyword!(fn) >> + ident: syn!(Ident) >> + generics: syn!(Generics) >> + inputs: parens!(Punctuated::parse_terminated) >> + ret: syn!(ReturnType) >> + where_clause: option!(syn!(WhereClause)) >> + inner_attrs_stmts: braces!(tuple!( + many0!(Attribute::parse_inner), + call!(Block::parse_within) + )) >> + (ImplItemMethod { + attrs: { + let mut attrs = outer_attrs; + attrs.extend((inner_attrs_stmts.1).0); + attrs + }, + vis: vis, + defaultness: defaultness, + sig: MethodSig { + constness: constness, + unsafety: unsafety, + abi: abi, + ident: ident, + decl: FnDecl { + fn_token: fn_, + paren_token: inputs.0, + inputs: inputs.1, + output: ret, + generics: Generics { + where_clause: where_clause, + .. generics + }, + variadic: None, + }, + }, + block: Block { + brace_token: inner_attrs_stmts.0, + stmts: (inner_attrs_stmts.1).1, + }, + }) + )); + + impl_synom!(ImplItemType "type in impl block" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + vis: syn!(Visibility) >> + defaultness: option!(keyword!(default)) >> + type_: keyword!(type) >> + ident: syn!(Ident) >> + generics: syn!(Generics) >> + eq: punct!(=) >> + ty: syn!(Type) >> + semi: punct!(;) >> + (ImplItemType { + attrs: attrs, + vis: vis, + defaultness: defaultness, + type_token: type_, + ident: ident, + generics: generics, + eq_token: eq, + ty: ty, + semi_token: semi, + }) + )); + + impl_synom!(ImplItemMacro "macro in impl block" do_parse!( + attrs: many0!(Attribute::parse_outer) >> + mac: syn!(Macro) >> + semi: cond!(!is_brace(&mac.delimiter), punct!(;)) >> + (ImplItemMacro { + attrs: attrs, + mac: mac, + semi_token: semi, + }) + )); + + fn is_brace(delimiter: &MacroDelimiter) -> bool { + match *delimiter { + MacroDelimiter::Brace(_) => true, + MacroDelimiter::Paren(_) | MacroDelimiter::Bracket(_) => false, + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use attr::FilterAttrs; + use quote::{ToTokens, Tokens}; + + impl ToTokens for ItemExternCrate { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.extern_token.to_tokens(tokens); + self.crate_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + if let Some((ref as_token, ref rename)) = self.rename { + as_token.to_tokens(tokens); + rename.to_tokens(tokens); + } + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for ItemUse { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.use_token.to_tokens(tokens); + self.leading_colon.to_tokens(tokens); + self.tree.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for ItemStatic { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.static_token.to_tokens(tokens); + self.mutability.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.colon_token.to_tokens(tokens); + self.ty.to_tokens(tokens); + self.eq_token.to_tokens(tokens); + self.expr.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for ItemConst { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.const_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.colon_token.to_tokens(tokens); + self.ty.to_tokens(tokens); + self.eq_token.to_tokens(tokens); + self.expr.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for ItemFn { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.constness.to_tokens(tokens); + self.unsafety.to_tokens(tokens); + self.abi.to_tokens(tokens); + NamedDecl(&self.decl, self.ident).to_tokens(tokens); + self.block.brace_token.surround(tokens, |tokens| { + tokens.append_all(self.attrs.inner()); + tokens.append_all(&self.block.stmts); + }); + } + } + + impl ToTokens for ItemMod { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.mod_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + if let Some((ref brace, ref items)) = self.content { + brace.surround(tokens, |tokens| { + tokens.append_all(self.attrs.inner()); + tokens.append_all(items); + }); + } else { + TokensOrDefault(&self.semi).to_tokens(tokens); + } + } + } + + impl ToTokens for ItemForeignMod { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.abi.to_tokens(tokens); + self.brace_token.surround(tokens, |tokens| { + tokens.append_all(&self.items); + }); + } + } + + impl ToTokens for ItemType { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.type_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.generics.to_tokens(tokens); + self.generics.where_clause.to_tokens(tokens); + self.eq_token.to_tokens(tokens); + self.ty.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for ItemEnum { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.enum_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.generics.to_tokens(tokens); + self.generics.where_clause.to_tokens(tokens); + self.brace_token.surround(tokens, |tokens| { + self.variants.to_tokens(tokens); + }); + } + } + + impl ToTokens for ItemStruct { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.struct_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.generics.to_tokens(tokens); + match self.fields { + Fields::Named(ref fields) => { + self.generics.where_clause.to_tokens(tokens); + fields.to_tokens(tokens); + } + Fields::Unnamed(ref fields) => { + fields.to_tokens(tokens); + self.generics.where_clause.to_tokens(tokens); + TokensOrDefault(&self.semi_token).to_tokens(tokens); + } + Fields::Unit => { + self.generics.where_clause.to_tokens(tokens); + TokensOrDefault(&self.semi_token).to_tokens(tokens); + } + } + } + } + + impl ToTokens for ItemUnion { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.union_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.generics.to_tokens(tokens); + self.generics.where_clause.to_tokens(tokens); + self.fields.to_tokens(tokens); + } + } + + impl ToTokens for ItemTrait { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.unsafety.to_tokens(tokens); + self.auto_token.to_tokens(tokens); + self.trait_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.generics.to_tokens(tokens); + if !self.supertraits.is_empty() { + TokensOrDefault(&self.colon_token).to_tokens(tokens); + self.supertraits.to_tokens(tokens); + } + self.generics.where_clause.to_tokens(tokens); + self.brace_token.surround(tokens, |tokens| { + tokens.append_all(&self.items); + }); + } + } + + impl ToTokens for ItemImpl { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.defaultness.to_tokens(tokens); + self.unsafety.to_tokens(tokens); + self.impl_token.to_tokens(tokens); + self.generics.to_tokens(tokens); + if let Some((ref polarity, ref path, ref for_token)) = self.trait_ { + polarity.to_tokens(tokens); + path.to_tokens(tokens); + for_token.to_tokens(tokens); + } + self.self_ty.to_tokens(tokens); + self.generics.where_clause.to_tokens(tokens); + self.brace_token.surround(tokens, |tokens| { + tokens.append_all(self.attrs.inner()); + tokens.append_all(&self.items); + }); + } + } + + impl ToTokens for ItemMacro { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.mac.path.to_tokens(tokens); + self.mac.bang_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + match self.mac.delimiter { + MacroDelimiter::Paren(ref paren) => { + paren.surround(tokens, |tokens| self.mac.tts.to_tokens(tokens)); + } + MacroDelimiter::Brace(ref brace) => { + brace.surround(tokens, |tokens| self.mac.tts.to_tokens(tokens)); + } + MacroDelimiter::Bracket(ref bracket) => { + bracket.surround(tokens, |tokens| self.mac.tts.to_tokens(tokens)); + } + } + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for ItemMacro2 { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.macro_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.paren_token.surround(tokens, |tokens| { + self.args.to_tokens(tokens); + }); + self.brace_token.surround(tokens, |tokens| { + self.body.to_tokens(tokens); + }); + } + } + + impl ToTokens for ItemVerbatim { + fn to_tokens(&self, tokens: &mut Tokens) { + self.tts.to_tokens(tokens); + } + } + + impl ToTokens for UsePath { + fn to_tokens(&self, tokens: &mut Tokens) { + self.ident.to_tokens(tokens); + self.colon2_token.to_tokens(tokens); + self.tree.to_tokens(tokens); + } + } + + impl ToTokens for UseName { + fn to_tokens(&self, tokens: &mut Tokens) { + self.ident.to_tokens(tokens); + } + } + + impl ToTokens for UseRename { + fn to_tokens(&self, tokens: &mut Tokens) { + self.ident.to_tokens(tokens); + self.as_token.to_tokens(tokens); + self.rename.to_tokens(tokens); + } + } + + impl ToTokens for UseGlob { + fn to_tokens(&self, tokens: &mut Tokens) { + self.star_token.to_tokens(tokens); + } + } + + impl ToTokens for UseGroup { + fn to_tokens(&self, tokens: &mut Tokens) { + self.brace_token.surround(tokens, |tokens| { + self.items.to_tokens(tokens); + }); + } + } + + impl ToTokens for TraitItemConst { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.const_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.colon_token.to_tokens(tokens); + self.ty.to_tokens(tokens); + if let Some((ref eq_token, ref default)) = self.default { + eq_token.to_tokens(tokens); + default.to_tokens(tokens); + } + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for TraitItemMethod { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.sig.to_tokens(tokens); + match self.default { + Some(ref block) => { + block.brace_token.surround(tokens, |tokens| { + tokens.append_all(self.attrs.inner()); + tokens.append_all(&block.stmts); + }); + } + None => { + TokensOrDefault(&self.semi_token).to_tokens(tokens); + } + } + } + } + + impl ToTokens for TraitItemType { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.type_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.generics.to_tokens(tokens); + if !self.bounds.is_empty() { + TokensOrDefault(&self.colon_token).to_tokens(tokens); + self.bounds.to_tokens(tokens); + } + self.generics.where_clause.to_tokens(tokens); + if let Some((ref eq_token, ref default)) = self.default { + eq_token.to_tokens(tokens); + default.to_tokens(tokens); + } + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for TraitItemMacro { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.mac.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for TraitItemVerbatim { + fn to_tokens(&self, tokens: &mut Tokens) { + self.tts.to_tokens(tokens); + } + } + + impl ToTokens for ImplItemConst { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.defaultness.to_tokens(tokens); + self.const_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.colon_token.to_tokens(tokens); + self.ty.to_tokens(tokens); + self.eq_token.to_tokens(tokens); + self.expr.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for ImplItemMethod { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.defaultness.to_tokens(tokens); + self.sig.to_tokens(tokens); + self.block.brace_token.surround(tokens, |tokens| { + tokens.append_all(self.attrs.inner()); + tokens.append_all(&self.block.stmts); + }); + } + } + + impl ToTokens for ImplItemType { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.defaultness.to_tokens(tokens); + self.type_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.generics.to_tokens(tokens); + self.eq_token.to_tokens(tokens); + self.ty.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for ImplItemMacro { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.mac.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for ImplItemVerbatim { + fn to_tokens(&self, tokens: &mut Tokens) { + self.tts.to_tokens(tokens); + } + } + + impl ToTokens for ForeignItemFn { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + NamedDecl(&self.decl, self.ident).to_tokens(tokens); + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for ForeignItemStatic { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.static_token.to_tokens(tokens); + self.mutability.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.colon_token.to_tokens(tokens); + self.ty.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for ForeignItemType { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.attrs.outer()); + self.vis.to_tokens(tokens); + self.type_token.to_tokens(tokens); + self.ident.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + } + } + + impl ToTokens for ForeignItemVerbatim { + fn to_tokens(&self, tokens: &mut Tokens) { + self.tts.to_tokens(tokens); + } + } + + impl ToTokens for MethodSig { + fn to_tokens(&self, tokens: &mut Tokens) { + self.constness.to_tokens(tokens); + self.unsafety.to_tokens(tokens); + self.abi.to_tokens(tokens); + NamedDecl(&self.decl, self.ident).to_tokens(tokens); + } + } + + struct NamedDecl<'a>(&'a FnDecl, Ident); + + impl<'a> ToTokens for NamedDecl<'a> { + fn to_tokens(&self, tokens: &mut Tokens) { + self.0.fn_token.to_tokens(tokens); + self.1.to_tokens(tokens); + self.0.generics.to_tokens(tokens); + self.0.paren_token.surround(tokens, |tokens| { + self.0.inputs.to_tokens(tokens); + if self.0.variadic.is_some() && !self.0.inputs.empty_or_trailing() { + <Token![,]>::default().to_tokens(tokens); + } + self.0.variadic.to_tokens(tokens); + }); + self.0.output.to_tokens(tokens); + self.0.generics.where_clause.to_tokens(tokens); + } + } + + impl ToTokens for ArgSelfRef { + fn to_tokens(&self, tokens: &mut Tokens) { + self.and_token.to_tokens(tokens); + self.lifetime.to_tokens(tokens); + self.mutability.to_tokens(tokens); + self.self_token.to_tokens(tokens); + } + } + + impl ToTokens for ArgSelf { + fn to_tokens(&self, tokens: &mut Tokens) { + self.mutability.to_tokens(tokens); + self.self_token.to_tokens(tokens); + } + } + + impl ToTokens for ArgCaptured { + fn to_tokens(&self, tokens: &mut Tokens) { + self.pat.to_tokens(tokens); + self.colon_token.to_tokens(tokens); + self.ty.to_tokens(tokens); + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/lib.rs cargo-0.26.0/vendor/syn-0.13.1/src/lib.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,724 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Syn is a parsing library for parsing a stream of Rust tokens into a syntax +//! tree of Rust source code. +//! +//! Currently this library is geared toward the [custom derive] use case but +//! contains some APIs that may be useful for Rust procedural macros more +//! generally. +//! +//! [custom derive]: https://github.com/rust-lang/rfcs/blob/master/text/1681-macros-1.1.md +//! +//! - **Data structures** — Syn provides a complete syntax tree that can +//! represent any valid Rust source code. The syntax tree is rooted at +//! [`syn::File`] which represents a full source file, but there are other +//! entry points that may be useful to procedural macros including +//! [`syn::Item`], [`syn::Expr`] and [`syn::Type`]. +//! +//! - **Custom derives** — Of particular interest to custom derives is +//! [`syn::DeriveInput`] which is any of the three legal input items to a +//! derive macro. An example below shows using this type in a library that can +//! derive implementations of a trait of your own. +//! +//! - **Parser combinators** — Parsing in Syn is built on a suite of public +//! parser combinator macros that you can use for parsing any token-based +//! syntax you dream up within a `functionlike!(...)` procedural macro. Every +//! syntax tree node defined by Syn is individually parsable and may be used +//! as a building block for custom syntaxes, or you may do it all yourself +//! working from the most primitive tokens. +//! +//! - **Location information** — Every token parsed by Syn is associated with a +//! `Span` that tracks line and column information back to the source of that +//! token. These spans allow a procedural macro to display detailed error +//! messages pointing to all the right places in the user's code. There is an +//! example of this below. +//! +//! - **Feature flags** — Functionality is aggressively feature gated so your +//! procedural macros enable only what they need, and do not pay in compile +//! time for all the rest. +//! +//! [`syn::File`]: struct.File.html +//! [`syn::Item`]: enum.Item.html +//! [`syn::Expr`]: enum.Expr.html +//! [`syn::Type`]: enum.Type.html +//! [`syn::DeriveInput`]: struct.DeriveInput.html +//! +//! *Version requirement: Syn supports any compiler version back to Rust's very +//! first support for procedural macros in Rust 1.15.0. Some features especially +//! around error reporting are only available in newer compilers or on the +//! nightly channel.* +//! +//! ## Example of a custom derive +//! +//! The canonical custom derive using Syn looks like this. We write an ordinary +//! Rust function tagged with a `proc_macro_derive` attribute and the name of +//! the trait we are deriving. Any time that derive appears in the user's code, +//! the Rust compiler passes their data structure as tokens into our macro. We +//! get to execute arbitrary Rust code to figure out what to do with those +//! tokens, then hand some tokens back to the compiler to compile into the +//! user's crate. +//! +//! [`TokenStream`]: https://doc.rust-lang.org/proc_macro/struct.TokenStream.html +//! +//! ```toml +//! [dependencies] +//! syn = "0.13" +//! quote = "0.5" +//! +//! [lib] +//! proc-macro = true +//! ``` +//! +//! ```rust +//! extern crate proc_macro; +//! extern crate syn; +//! +//! #[macro_use] +//! extern crate quote; +//! +//! use proc_macro::TokenStream; +//! use syn::DeriveInput; +//! +//! # const IGNORE_TOKENS: &str = stringify! { +//! #[proc_macro_derive(MyMacro)] +//! # }; +//! pub fn my_macro(input: TokenStream) -> TokenStream { +//! // Parse the input tokens into a syntax tree +//! let input: DeriveInput = syn::parse(input).unwrap(); +//! +//! // Build the output, possibly using quasi-quotation +//! let expanded = quote! { +//! // ... +//! }; +//! +//! // Hand the output tokens back to the compiler +//! expanded.into() +//! } +//! # +//! # fn main() {} +//! ``` +//! +//! The [`heapsize`] example directory shows a complete working Macros 1.1 +//! implementation of a custom derive. It works on any Rust compiler \>=1.15.0. +//! The example derives a `HeapSize` trait which computes an estimate of the +//! amount of heap memory owned by a value. +//! +//! [`heapsize`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize +//! +//! ```rust +//! pub trait HeapSize { +//! /// Total number of bytes of heap memory owned by `self`. +//! fn heap_size_of_children(&self) -> usize; +//! } +//! ``` +//! +//! The custom derive allows users to write `#[derive(HeapSize)]` on data +//! structures in their program. +//! +//! ```rust +//! # const IGNORE_TOKENS: &str = stringify! { +//! #[derive(HeapSize)] +//! # }; +//! struct Demo<'a, T: ?Sized> { +//! a: Box<T>, +//! b: u8, +//! c: &'a str, +//! d: String, +//! } +//! ``` +//! +//! ## Spans and error reporting +//! +//! The [`heapsize2`] example directory is an extension of the `heapsize` +//! example that demonstrates some of the hygiene and error reporting properties +//! of Macros 2.0. This example currently requires a nightly Rust compiler +//! \>=1.24.0-nightly but we are working to stabilize all of the APIs involved. +//! +//! [`heapsize2`]: https://github.com/dtolnay/syn/tree/master/examples/heapsize2 +//! +//! The token-based procedural macro API provides great control over where the +//! compiler's error messages are displayed in user code. Consider the error the +//! user sees if one of their field types does not implement `HeapSize`. +//! +//! ```rust +//! # const IGNORE_TOKENS: &str = stringify! { +//! #[derive(HeapSize)] +//! # }; +//! struct Broken { +//! ok: String, +//! bad: std::thread::Thread, +//! } +//! ``` +//! +//! In the Macros 1.1 string-based procedural macro world, the resulting error +//! would point unhelpfully to the invocation of the derive macro and not to the +//! actual problematic field. +//! +//! ```text +//! error[E0599]: no method named `heap_size_of_children` found for type `std::thread::Thread` in the current scope +//! --> src/main.rs:4:10 +//! | +//! 4 | #[derive(HeapSize)] +//! | ^^^^^^^^ +//! ``` +//! +//! By tracking span information all the way through the expansion of a +//! procedural macro as shown in the `heapsize2` example, token-based macros in +//! Syn are able to trigger errors that directly pinpoint the source of the +//! problem. +//! +//! ```text +//! error[E0277]: the trait bound `std::thread::Thread: HeapSize` is not satisfied +//! --> src/main.rs:7:5 +//! | +//! 7 | bad: std::thread::Thread, +//! | ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `HeapSize` is not implemented for `Thread` +//! ``` +//! +//! ## Parsing a custom syntax using combinators +//! +//! The [`lazy-static`] example directory shows the implementation of a +//! `functionlike!(...)` procedural macro in which the input tokens are parsed +//! using [`nom`]-style parser combinators. +//! +//! [`lazy-static`]: https://github.com/dtolnay/syn/tree/master/examples/lazy-static +//! [`nom`]: https://github.com/Geal/nom +//! +//! The example reimplements the popular `lazy_static` crate from crates.io as a +//! procedural macro. +//! +//! ``` +//! # macro_rules! lazy_static { +//! # ($($tt:tt)*) => {} +//! # } +//! # +//! lazy_static! { +//! static ref USERNAME: Regex = Regex::new("^[a-z0-9_-]{3,16}$").unwrap(); +//! } +//! ``` +//! +//! The implementation shows how to trigger custom warnings and error messages +//! on the macro input. +//! +//! ```text +//! warning: come on, pick a more creative name +//! --> src/main.rs:10:16 +//! | +//! 10 | static ref FOO: String = "lazy_static".to_owned(); +//! | ^^^ +//! ``` +//! +//! ## Debugging +//! +//! When developing a procedural macro it can be helpful to look at what the +//! generated code looks like. Use `cargo rustc -- -Zunstable-options +//! --pretty=expanded` or the [`cargo expand`] subcommand. +//! +//! [`cargo expand`]: https://github.com/dtolnay/cargo-expand +//! +//! To show the expanded code for some crate that uses your procedural macro, +//! run `cargo expand` from that crate. To show the expanded code for one of +//! your own test cases, run `cargo expand --test the_test_case` where the last +//! argument is the name of the test file without the `.rs` extension. +//! +//! This write-up by Brandon W Maister discusses debugging in more detail: +//! [Debugging Rust's new Custom Derive system][debugging]. +//! +//! [debugging]: https://quodlibetor.github.io/posts/debugging-rusts-new-custom-derive-system/ +//! +//! ## Optional features +//! +//! Syn puts a lot of functionality behind optional features in order to +//! optimize compile time for the most common use cases. The following features +//! are available. +//! +//! - **`derive`** *(enabled by default)* — Data structures for representing the +//! possible input to a custom derive, including structs and enums and types. +//! - **`full`** — Data structures for representing the syntax tree of all valid +//! Rust source code, including items and expressions. +//! - **`parsing`** *(enabled by default)* — Ability to parse input tokens into +//! a syntax tree node of a chosen type. +//! - **`printing`** *(enabled by default)* — Ability to print a syntax tree +//! node as tokens of Rust source code. +//! - **`visit`** — Trait for traversing a syntax tree. +//! - **`visit-mut`** — Trait for traversing and mutating in place a syntax +//! tree. +//! - **`fold`** — Trait for transforming an owned syntax tree. +//! - **`clone-impls`** *(enabled by default)* — Clone impls for all syntax tree +//! types. +//! - **`extra-traits`** — Debug, Eq, PartialEq, Hash impls for all syntax tree +//! types. + +// Syn types in rustdoc of other crates get linked to here. +#![doc(html_root_url = "https://docs.rs/syn/0.13.1")] +#![cfg_attr(feature = "cargo-clippy", + allow(const_static_lifetime, doc_markdown, large_enum_variant, match_bool, + redundant_closure, needless_pass_by_value, redundant_field_names))] + +extern crate proc_macro2; +#[cfg(feature = "proc-macro")] +extern crate proc_macro; +extern crate unicode_xid; + +#[cfg(feature = "printing")] +extern crate quote; + +#[cfg(feature = "parsing")] +#[macro_use] +#[doc(hidden)] +pub mod parsers; + +#[macro_use] +mod macros; + +#[macro_use] +pub mod token; + +#[cfg(any(feature = "full", feature = "derive"))] +mod attr; +#[cfg(any(feature = "full", feature = "derive"))] +pub use attr::{AttrStyle, Attribute, Meta, MetaList, MetaNameValue, NestedMeta}; + +#[cfg(any(feature = "full", feature = "derive"))] +mod data; +#[cfg(any(feature = "full", feature = "derive"))] +pub use data::{Field, Fields, FieldsNamed, FieldsUnnamed, Variant, VisCrate, VisPublic, + VisRestricted, Visibility}; + +#[cfg(any(feature = "full", feature = "derive"))] +mod expr; +#[cfg(any(feature = "full", feature = "derive"))] +pub use expr::{Expr, ExprReference, ExprArray, ExprAssign, ExprAssignOp, ExprBinary, ExprBlock, + ExprBox, ExprBreak, ExprCall, ExprCast, ExprCatch, ExprClosure, ExprContinue, + ExprField, ExprForLoop, ExprGroup, ExprIf, ExprIfLet, ExprInPlace, ExprIndex, + ExprLit, ExprLoop, ExprMacro, ExprMatch, ExprMethodCall, ExprParen, ExprPath, + ExprRange, ExprRepeat, ExprReturn, ExprStruct, ExprTry, ExprTuple, ExprType, + ExprUnary, ExprUnsafe, ExprVerbatim, ExprWhile, ExprWhileLet, ExprYield, Index, + Member}; + +#[cfg(feature = "full")] +pub use expr::{Arm, Block, FieldPat, FieldValue, GenericMethodArgument, Label, Local, + MethodTurbofish, Pat, PatBox, PatIdent, PatLit, PatMacro, PatPath, PatRange, + PatRef, PatSlice, PatStruct, PatTuple, PatTupleStruct, PatVerbatim, PatWild, + RangeLimits, Stmt}; + +#[cfg(any(feature = "full", feature = "derive"))] +mod generics; +#[cfg(any(feature = "full", feature = "derive"))] +pub use generics::{BoundLifetimes, ConstParam, GenericParam, Generics, LifetimeDef, PredicateEq, + PredicateLifetime, PredicateType, TraitBound, TraitBoundModifier, TypeParam, + TypeParamBound, WhereClause, WherePredicate}; +#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] +pub use generics::{ImplGenerics, Turbofish, TypeGenerics}; + +mod ident; +pub use ident::Ident; + +#[cfg(feature = "full")] +mod item; +#[cfg(feature = "full")] +pub use item::{ArgCaptured, ArgSelf, ArgSelfRef, FnArg, FnDecl, ForeignItem, ForeignItemFn, + ForeignItemStatic, ForeignItemType, ForeignItemVerbatim, ImplItem, ImplItemConst, + ImplItemMacro, ImplItemMethod, ImplItemType, ImplItemVerbatim, Item, ItemConst, + ItemEnum, ItemExternCrate, ItemFn, ItemForeignMod, ItemImpl, ItemMacro, ItemMacro2, + ItemMod, ItemStatic, ItemStruct, ItemTrait, ItemType, ItemUnion, ItemUse, + ItemVerbatim, MethodSig, TraitItem, TraitItemConst, TraitItemMacro, + TraitItemMethod, TraitItemType, TraitItemVerbatim, UseGlob, UseGroup, UseName, + UsePath, UseRename, UseTree}; + +#[cfg(feature = "full")] +mod file; +#[cfg(feature = "full")] +pub use file::File; + +#[cfg(any(feature = "full", feature = "derive"))] +mod lifetime; +#[cfg(any(feature = "full", feature = "derive"))] +pub use lifetime::Lifetime; + +#[cfg(any(feature = "full", feature = "derive"))] +mod lit; +#[cfg(any(feature = "full", feature = "derive"))] +pub use lit::{FloatSuffix, IntSuffix, Lit, LitBool, LitByte, LitByteStr, LitChar, LitFloat, + LitInt, LitStr, LitVerbatim, StrStyle}; + +#[cfg(any(feature = "full", feature = "derive"))] +mod mac; +#[cfg(any(feature = "full", feature = "derive"))] +pub use mac::{Macro, MacroDelimiter}; + +#[cfg(any(feature = "full", feature = "derive"))] +mod derive; +#[cfg(feature = "derive")] +pub use derive::{Data, DataEnum, DataStruct, DataUnion, DeriveInput}; + +#[cfg(any(feature = "full", feature = "derive"))] +mod op; +#[cfg(any(feature = "full", feature = "derive"))] +pub use op::{BinOp, UnOp}; + +#[cfg(any(feature = "full", feature = "derive"))] +mod ty; +#[cfg(any(feature = "full", feature = "derive"))] +pub use ty::{Abi, BareFnArg, BareFnArgName, ReturnType, Type, TypeArray, TypeBareFn, TypeGroup, + TypeImplTrait, TypeInfer, TypeMacro, TypeNever, TypeParen, TypePath, TypePtr, + TypeReference, TypeSlice, TypeTraitObject, TypeTuple, TypeVerbatim}; + +#[cfg(any(feature = "full", feature = "derive"))] +mod path; +#[cfg(any(feature = "full", feature = "derive"))] +pub use path::{AngleBracketedGenericArguments, Binding, GenericArgument, + ParenthesizedGenericArguments, Path, PathArguments, PathSegment, QSelf}; +#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] +pub use path::PathTokens; + +#[cfg(feature = "parsing")] +pub mod buffer; +#[cfg(feature = "parsing")] +pub mod synom; +pub mod punctuated; +#[cfg(any(feature = "full", feature = "derive"))] +mod tt; + +// Not public API except the `parse_quote!` macro. +#[cfg(feature = "parsing")] +#[doc(hidden)] +pub mod parse_quote; + +#[cfg(all(feature = "parsing", feature = "printing"))] +pub mod spanned; + +mod gen { + /// Syntax tree traversal to walk a shared borrow of a syntax tree. + /// + /// Each method of the [`Visit`] trait is a hook that can be overridden to + /// customize the behavior when visiting the corresponding type of node. By + /// default, every method recursively visits the substructure of the input + /// by invoking the right visitor method of each of its fields. + /// + /// [`Visit`]: trait.Visit.html + /// + /// ```rust + /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; + /// # + /// pub trait Visit<'ast> { + /// /* ... */ + /// + /// fn visit_expr_binary(&mut self, node: &'ast ExprBinary) { + /// for attr in &node.attrs { + /// self.visit_attribute(attr); + /// } + /// self.visit_expr(&*node.left); + /// self.visit_bin_op(&node.op); + /// self.visit_expr(&*node.right); + /// } + /// + /// /* ... */ + /// # fn visit_attribute(&mut self, node: &'ast Attribute); + /// # fn visit_expr(&mut self, node: &'ast Expr); + /// # fn visit_bin_op(&mut self, node: &'ast BinOp); + /// } + /// ``` + /// + /// *This module is available if Syn is built with the `"visit"` feature.* + #[cfg(feature = "visit")] + pub mod visit; + + + /// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in + /// place. + /// + /// Each method of the [`VisitMut`] trait is a hook that can be overridden + /// to customize the behavior when mutating the corresponding type of node. + /// By default, every method recursively visits the substructure of the + /// input by invoking the right visitor method of each of its fields. + /// + /// [`VisitMut`]: trait.VisitMut.html + /// + /// ```rust + /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; + /// # + /// pub trait VisitMut { + /// /* ... */ + /// + /// fn visit_expr_binary_mut(&mut self, node: &mut ExprBinary) { + /// for attr in &mut node.attrs { + /// self.visit_attribute_mut(attr); + /// } + /// self.visit_expr_mut(&mut *node.left); + /// self.visit_bin_op_mut(&mut node.op); + /// self.visit_expr_mut(&mut *node.right); + /// } + /// + /// /* ... */ + /// # fn visit_attribute_mut(&mut self, node: &mut Attribute); + /// # fn visit_expr_mut(&mut self, node: &mut Expr); + /// # fn visit_bin_op_mut(&mut self, node: &mut BinOp); + /// } + /// ``` + /// + /// *This module is available if Syn is built with the `"visit-mut"` + /// feature.* + #[cfg(feature = "visit-mut")] + pub mod visit_mut; + + /// Syntax tree traversal to transform the nodes of an owned syntax tree. + /// + /// Each method of the [`Fold`] trait is a hook that can be overridden to + /// customize the behavior when transforming the corresponding type of node. + /// By default, every method recursively visits the substructure of the + /// input by invoking the right visitor method of each of its fields. + /// + /// [`Fold`]: trait.Fold.html + /// + /// ```rust + /// # use syn::{Attribute, BinOp, Expr, ExprBinary}; + /// # + /// pub trait Fold { + /// /* ... */ + /// + /// fn fold_expr_binary(&mut self, node: ExprBinary) -> ExprBinary { + /// ExprBinary { + /// attrs: node.attrs + /// .into_iter() + /// .map(|attr| self.fold_attribute(attr)) + /// .collect(), + /// left: Box::new(self.fold_expr(*node.left)), + /// op: self.fold_bin_op(node.op), + /// right: Box::new(self.fold_expr(*node.right)), + /// } + /// } + /// + /// /* ... */ + /// # fn fold_attribute(&mut self, node: Attribute) -> Attribute; + /// # fn fold_expr(&mut self, node: Expr) -> Expr; + /// # fn fold_bin_op(&mut self, node: BinOp) -> BinOp; + /// } + /// ``` + /// + /// *This module is available if Syn is built with the `"fold"` feature.* + #[cfg(feature = "fold")] + pub mod fold; + + #[cfg(any(feature = "full", feature = "derive"))] + #[path = "../gen_helper.rs"] + mod helper; +} +pub use gen::*; + +//////////////////////////////////////////////////////////////////////////////// + +#[cfg(feature = "parsing")] +use synom::{Synom, Parser}; + +#[cfg(feature = "parsing")] +mod error; +#[cfg(feature = "parsing")] +use error::ParseError; + +// Not public API. +#[cfg(feature = "parsing")] +#[doc(hidden)] +pub use error::parse_error; + +/// Parse tokens of source code into the chosen syntax tree node. +/// +/// This is preferred over parsing a string because tokens are able to preserve +/// information about where in the user's code they were originally written (the +/// "span" of the token), possibly allowing the compiler to produce better error +/// messages. +/// +/// This function parses a `proc_macro::TokenStream` which is the type used for +/// interop with the compiler in a procedural macro. To parse a +/// `proc_macro2::TokenStream`, use [`syn::parse2`] instead. +/// +/// [`syn::parse2`]: fn.parse2.html +/// +/// *This function is available if Syn is built with the `"parsing"` feature.* +/// +/// # Examples +/// +/// ```rust +/// extern crate proc_macro; +/// use proc_macro::TokenStream; +/// +/// extern crate syn; +/// +/// #[macro_use] +/// extern crate quote; +/// +/// use syn::DeriveInput; +/// +/// # const IGNORE_TOKENS: &str = stringify! { +/// #[proc_macro_derive(MyMacro)] +/// # }; +/// pub fn my_macro(input: TokenStream) -> TokenStream { +/// // Parse the tokens into a syntax tree +/// let ast: DeriveInput = syn::parse(input).unwrap(); +/// +/// // Build the output, possibly using quasi-quotation +/// let expanded = quote! { +/// /* ... */ +/// }; +/// +/// // Convert into a token stream and return it +/// expanded.into() +/// } +/// # +/// # fn main() {} +/// ``` +#[cfg(all(feature = "parsing", feature = "proc-macro"))] +pub fn parse<T>(tokens: proc_macro::TokenStream) -> Result<T, ParseError> +where + T: Synom, +{ + parse2(tokens.into()) +} + +/// Parse a proc-macro2 token stream into the chosen syntax tree node. +/// +/// This function parses a `proc_macro2::TokenStream` which is commonly useful +/// when the input comes from a node of the Syn syntax tree, for example the tts +/// of a [`Macro`] node. When in a procedural macro parsing the +/// `proc_macro::TokenStream` provided by the compiler, use [`syn::parse`] +/// instead. +/// +/// [`Macro`]: struct.Macro.html +/// [`syn::parse`]: fn.parse.html +/// +/// *This function is available if Syn is built with the `"parsing"` feature.* +#[cfg(feature = "parsing")] +pub fn parse2<T>(tokens: proc_macro2::TokenStream) -> Result<T, ParseError> +where + T: Synom, +{ + let parser = T::parse; + parser.parse2(tokens).map_err(|err| { + match T::description() { + Some(s) => ParseError::new(format!("failed to parse {}: {}", s, err)), + None => err, + } + }) +} + +/// Parse a string of Rust code into the chosen syntax tree node. +/// +/// *This function is available if Syn is built with the `"parsing"` feature.* +/// +/// # Hygiene +/// +/// Every span in the resulting syntax tree will be set to resolve at the macro +/// call site. +/// +/// # Examples +/// +/// ```rust +/// extern crate syn; +/// # +/// # +/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>; +/// +/// use syn::Expr; +/// +/// fn run() -> Result<()> { +/// let code = "assert_eq!(u8::max_value(), 255)"; +/// let expr = syn::parse_str::<Expr>(code)?; +/// println!("{:#?}", expr); +/// Ok(()) +/// } +/// # +/// # fn main() { run().unwrap() } +/// ``` +#[cfg(feature = "parsing")] +pub fn parse_str<T: Synom>(s: &str) -> Result<T, ParseError> { + match s.parse() { + Ok(tts) => parse2(tts), + Err(_) => Err(ParseError::new("error while lexing input string")), + } +} + +// FIXME the name parse_file makes it sound like you might pass in a path to a +// file, rather than the content. +/// Parse the content of a file of Rust code. +/// +/// This is different from `syn::parse_str::<File>(content)` in two ways: +/// +/// - It discards a leading byte order mark `\u{FEFF}` if the file has one. +/// - It preserves the shebang line of the file, such as `#!/usr/bin/env rustx`. +/// +/// If present, either of these would be an error using `from_str`. +/// +/// *This function is available if Syn is built with the `"parsing"` and `"full"` features.* +/// +/// # Examples +/// +/// ```rust,no_run +/// extern crate syn; +/// # +/// # +/// # type Result<T> = std::result::Result<T, Box<std::error::Error>>; +/// +/// use std::fs::File; +/// use std::io::Read; +/// +/// fn run() -> Result<()> { +/// let mut file = File::open("path/to/code.rs")?; +/// let mut content = String::new(); +/// file.read_to_string(&mut content)?; +/// +/// let ast = syn::parse_file(&content)?; +/// if let Some(shebang) = ast.shebang { +/// println!("{}", shebang); +/// } +/// println!("{} items", ast.items.len()); +/// +/// Ok(()) +/// } +/// # +/// # fn main() { run().unwrap() } +/// ``` +#[cfg(all(feature = "parsing", feature = "full"))] +pub fn parse_file(mut content: &str) -> Result<File, ParseError> { + // Strip the BOM if it is present + const BOM: &'static str = "\u{feff}"; + if content.starts_with(BOM) { + content = &content[BOM.len()..]; + } + + let mut shebang = None; + if content.starts_with("#!") && !content.starts_with("#![") { + if let Some(idx) = content.find('\n') { + shebang = Some(content[..idx].to_string()); + content = &content[idx..]; + } else { + shebang = Some(content.to_string()); + content = ""; + } + } + + let mut file: File = parse_str(content)?; + file.shebang = shebang; + Ok(file) +} + +#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] +struct TokensOrDefault<'a, T: 'a>(&'a Option<T>); + +#[cfg(all(any(feature = "full", feature = "derive"), feature = "printing"))] +impl<'a, T> quote::ToTokens for TokensOrDefault<'a, T> +where + T: quote::ToTokens + Default, +{ + fn to_tokens(&self, tokens: &mut quote::Tokens) { + match *self.0 { + Some(ref t) => t.to_tokens(tokens), + None => T::default().to_tokens(tokens), + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/lifetime.rs cargo-0.26.0/vendor/syn-0.13.1/src/lifetime.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/lifetime.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/lifetime.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,155 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::cmp::Ordering; +use std::fmt::{self, Display}; +use std::hash::{Hash, Hasher}; + +use proc_macro2::{Span, Term}; +use unicode_xid::UnicodeXID; + +/// A Rust lifetime: `'a`. +/// +/// Lifetime names must conform to the following rules: +/// +/// - Must start with an apostrophe. +/// - Must not consist of just an apostrophe: `'`. +/// - Character after the apostrophe must be `_` or a Unicode code point with +/// the XID_Start property. +/// - All following characters must be Unicode code points with the XID_Continue +/// property. +/// +/// *This type is available if Syn is built with the `"derive"` or `"full"` +/// feature.* +#[cfg_attr(feature = "extra-traits", derive(Debug))] +#[derive(Copy, Clone)] +pub struct Lifetime { + term: Term, +} + +impl Lifetime { + pub fn new(s: &str, span: Span) -> Self { + if !s.starts_with('\'') { + panic!( + "lifetime name must start with apostrophe as in \"'a\", \ + got {:?}", + s + ); + } + + if s == "'" { + panic!("lifetime name must not be empty"); + } + + fn xid_ok(s: &str) -> bool { + let mut chars = s.chars(); + let first = chars.next().unwrap(); + if !(UnicodeXID::is_xid_start(first) || first == '_') { + return false; + } + for ch in chars { + if !UnicodeXID::is_xid_continue(ch) { + return false; + } + } + true + } + + if !xid_ok(&s[1..]) { + panic!("{:?} is not a valid lifetime name", s); + } + + Lifetime { + term: Term::new(s, span), + } + } + + pub fn span(&self) -> Span { + self.term.span() + } + + pub fn set_span(&mut self, span: Span) { + self.term.set_span(span); + } +} + +impl Display for Lifetime { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + self.term.as_str().fmt(formatter) + } +} + +impl PartialEq for Lifetime { + fn eq(&self, other: &Lifetime) -> bool { + self.term.as_str() == other.term.as_str() + } +} + +impl Eq for Lifetime {} + +impl PartialOrd for Lifetime { + fn partial_cmp(&self, other: &Lifetime) -> Option<Ordering> { + Some(self.cmp(other)) + } +} + +impl Ord for Lifetime { + fn cmp(&self, other: &Lifetime) -> Ordering { + self.term.as_str().cmp(other.term.as_str()) + } +} + +impl Hash for Lifetime { + fn hash<H: Hasher>(&self, h: &mut H) { + self.term.as_str().hash(h) + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + use synom::Synom; + use buffer::Cursor; + use parse_error; + use synom::PResult; + + impl Synom for Lifetime { + fn parse(input: Cursor) -> PResult<Self> { + let (term, rest) = match input.term() { + Some(term) => term, + _ => return parse_error(), + }; + if !term.as_str().starts_with('\'') { + return parse_error(); + } + + Ok(( + Lifetime { + term: term, + }, + rest, + )) + } + + fn description() -> Option<&'static str> { + Some("lifetime") + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use quote::{ToTokens, Tokens}; + + impl ToTokens for Lifetime { + fn to_tokens(&self, tokens: &mut Tokens) { + self.term.to_tokens(tokens); + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/lit.rs cargo-0.26.0/vendor/syn-0.13.1/src/lit.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/lit.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/lit.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1047 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use proc_macro2::{Literal, Span}; +use std::str; + +#[cfg(feature = "printing")] +use proc_macro2::Term; + +#[cfg(feature = "parsing")] +use proc_macro2::TokenStream; +#[cfg(feature = "parsing")] +use {ParseError, Synom}; + +#[cfg(any(feature = "printing", feature = "parsing", feature = "derive"))] +use proc_macro2::TokenTree; + +#[cfg(feature = "extra-traits")] +use std::hash::{Hash, Hasher}; + +ast_enum_of_structs! { + /// A Rust literal such as a string or integer or boolean. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum Lit { + /// A UTF-8 string literal: `"foo"`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Str(LitStr #manual_extra_traits { + token: Literal, + }), + + /// A byte string literal: `b"foo"`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub ByteStr(LitByteStr #manual_extra_traits { + token: Literal, + }), + + /// A byte literal: `b'f'`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Byte(LitByte #manual_extra_traits { + token: Literal, + }), + + /// A character literal: `'a'`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Char(LitChar #manual_extra_traits { + token: Literal, + }), + + /// An integer literal: `1` or `1u16`. + /// + /// Holds up to 64 bits of data. Use `LitVerbatim` for any larger + /// integer literal. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Int(LitInt #manual_extra_traits { + token: Literal, + }), + + /// A floating point literal: `1f64` or `1.0e10f64`. + /// + /// Must be finite. May not be infinte or NaN. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Float(LitFloat #manual_extra_traits { + token: Literal, + }), + + /// A boolean literal: `true` or `false`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Bool(LitBool #manual_extra_traits { + pub value: bool, + pub span: Span, + }), + + /// A raw token literal not interpreted by Syn, possibly because it + /// represents an integer larger than 64 bits. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Verbatim(LitVerbatim #manual_extra_traits { + pub token: Literal, + }), + } +} + +impl LitStr { + pub fn new(value: &str, span: Span) -> Self { + let mut lit = Literal::string(value); + lit.set_span(span); + LitStr { + token: lit, + } + } + + pub fn value(&self) -> String { + value::parse_lit_str(&self.token.to_string()) + } + + /// Parse a syntax tree node from the content of this string literal. + /// + /// All spans in the syntax tree will point to the span of this `LitStr`. + #[cfg(feature = "parsing")] + pub fn parse<T: Synom>(&self) -> Result<T, ParseError> { + use proc_macro2::Group; + + // Parse string literal into a token stream with every span equal to the + // original literal's span. + fn spanned_tokens(s: &LitStr) -> Result<TokenStream, ParseError> { + let stream = ::parse_str(&s.value())?; + Ok(respan_token_stream(stream, s.span())) + } + + // Token stream with every span replaced by the given one. + fn respan_token_stream(stream: TokenStream, span: Span) -> TokenStream { + stream.into_iter().map(|token| respan_token_tree(token, span)).collect() + } + + // Token tree with every span replaced by the given one. + fn respan_token_tree(mut token: TokenTree, span: Span) -> TokenTree { + match token { + TokenTree::Group(ref mut g) => { + let stream = respan_token_stream(g.stream().clone(), span); + *g = Group::new(g.delimiter(), stream); + g.set_span(span); + } + ref mut other => other.set_span(span), + } + token + } + + spanned_tokens(self).and_then(::parse2) + } + + pub fn span(&self) -> Span { + self.token.span() + } + + pub fn set_span(&mut self, span: Span) { + self.token.set_span(span) + } +} + +impl LitByteStr { + pub fn new(value: &[u8], span: Span) -> Self { + let mut token = Literal::byte_string(value); + token.set_span(span); + LitByteStr { token: token } + } + + pub fn value(&self) -> Vec<u8> { + value::parse_lit_byte_str(&self.token.to_string()) + } + + pub fn span(&self) -> Span { + self.token.span() + } + + pub fn set_span(&mut self, span: Span) { + self.token.set_span(span) + } +} + +impl LitByte { + pub fn new(value: u8, span: Span) -> Self { + let mut token = Literal::u8_suffixed(value); + token.set_span(span); + LitByte { token: token } + } + + pub fn value(&self) -> u8 { + value::parse_lit_byte(&self.token.to_string()) + } + + pub fn span(&self) -> Span { + self.token.span() + } + + pub fn set_span(&mut self, span: Span) { + self.token.set_span(span) + } +} + +impl LitChar { + pub fn new(value: char, span: Span) -> Self { + let mut token = Literal::character(value); + token.set_span(span); + LitChar { token: token } + } + + pub fn value(&self) -> char { + value::parse_lit_char(&self.token.to_string()) + } + + pub fn span(&self) -> Span { + self.token.span() + } + + pub fn set_span(&mut self, span: Span) { + self.token.set_span(span) + } +} + +impl LitInt { + pub fn new(value: u64, suffix: IntSuffix, span: Span) -> Self { + let mut token = match suffix { + IntSuffix::Isize => Literal::isize_suffixed(value as isize), + IntSuffix::I8 => Literal::i8_suffixed(value as i8), + IntSuffix::I16 => Literal::i16_suffixed(value as i16), + IntSuffix::I32 => Literal::i32_suffixed(value as i32), + IntSuffix::I64 => Literal::i64_suffixed(value as i64), + IntSuffix::I128 => value::to_literal(&format!("{}i128", value)), + IntSuffix::Usize => Literal::usize_suffixed(value as usize), + IntSuffix::U8 => Literal::u8_suffixed(value as u8), + IntSuffix::U16 => Literal::u16_suffixed(value as u16), + IntSuffix::U32 => Literal::u32_suffixed(value as u32), + IntSuffix::U64 => Literal::u64_suffixed(value), + IntSuffix::U128 => value::to_literal(&format!("{}u128", value)), + IntSuffix::None => Literal::u64_unsuffixed(value), + }; + token.set_span(span); + LitInt { token: token } + } + + pub fn value(&self) -> u64 { + value::parse_lit_int(&self.token.to_string()).unwrap() + } + + pub fn suffix(&self) -> IntSuffix { + let value = self.token.to_string(); + for (s, suffix) in vec![ + ("i8", IntSuffix::I8), + ("i16", IntSuffix::I16), + ("i32", IntSuffix::I32), + ("i64", IntSuffix::I64), + ("i128", IntSuffix::I128), + ("isize", IntSuffix::Isize), + ("u8", IntSuffix::U8), + ("u16", IntSuffix::U16), + ("u32", IntSuffix::U32), + ("u64", IntSuffix::U64), + ("u128", IntSuffix::U128), + ("usize", IntSuffix::Usize), + ] { + if value.ends_with(s) { + return suffix; + } + } + IntSuffix::None + } + + pub fn span(&self) -> Span { + self.token.span() + } + + pub fn set_span(&mut self, span: Span) { + self.token.set_span(span) + } +} + +impl LitFloat { + pub fn new(value: f64, suffix: FloatSuffix, span: Span) -> Self { + let mut token = match suffix { + FloatSuffix::F32 => Literal::f32_suffixed(value as f32), + FloatSuffix::F64 => Literal::f64_suffixed(value), + FloatSuffix::None => Literal::f64_unsuffixed(value), + }; + token.set_span(span); + LitFloat { token: token } + } + + pub fn value(&self) -> f64 { + value::parse_lit_float(&self.token.to_string()) + } + + pub fn suffix(&self) -> FloatSuffix { + let value = self.token.to_string(); + for (s, suffix) in vec![("f32", FloatSuffix::F32), ("f64", FloatSuffix::F64)] { + if value.ends_with(s) { + return suffix; + } + } + FloatSuffix::None + } + + pub fn span(&self) -> Span { + self.token.span() + } + + pub fn set_span(&mut self, span: Span) { + self.token.set_span(span) + } +} + +macro_rules! lit_extra_traits { + ($ty:ident, $field:ident) => { + #[cfg(feature = "extra-traits")] + impl Eq for $ty {} + + #[cfg(feature = "extra-traits")] + impl PartialEq for $ty { + fn eq(&self, other: &Self) -> bool { + self.$field.to_string() == other.$field.to_string() + } + } + + #[cfg(feature = "extra-traits")] + impl Hash for $ty { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.$field.to_string().hash(state); + } + } + } +} + +impl LitVerbatim { + pub fn span(&self) -> Span { + self.token.span() + } + + pub fn set_span(&mut self, span: Span) { + self.token.set_span(span) + } +} + +lit_extra_traits!(LitStr, token); +lit_extra_traits!(LitByteStr, token); +lit_extra_traits!(LitByte, token); +lit_extra_traits!(LitChar, token); +lit_extra_traits!(LitInt, token); +lit_extra_traits!(LitFloat, token); +lit_extra_traits!(LitBool, value); +lit_extra_traits!(LitVerbatim, token); + +ast_enum! { + /// The style of a string literal, either plain quoted or a raw string like + /// `r##"data"##`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub enum StrStyle #no_visit { + /// An ordinary string like `"data"`. + Cooked, + /// A raw string like `r##"data"##`. + /// + /// The unsigned integer is the number of `#` symbols used. + Raw(usize), + } +} + +ast_enum! { + /// The suffix on an integer literal if any, like the `u8` in `127u8`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub enum IntSuffix #no_visit { + I8, + I16, + I32, + I64, + I128, + Isize, + U8, + U16, + U32, + U64, + U128, + Usize, + None, + } +} + +ast_enum! { + /// The suffix on a floating point literal if any, like the `f32` in + /// `1.0f32`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub enum FloatSuffix #no_visit { + F32, + F64, + None, + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + use synom::Synom; + use buffer::Cursor; + use parse_error; + use synom::PResult; + + impl Synom for Lit { + fn parse(input: Cursor) -> PResult<Self> { + match input.literal() { + Some((lit, rest)) => { + if lit.to_string().starts_with('/') { + // Doc comment literal which is not a Syn literal + parse_error() + } else { + Ok((Lit::new(lit), rest)) + } + } + _ => match input.term() { + Some((term, rest)) => Ok(( + Lit::Bool(LitBool { + value: if term.as_str() == "true" { + true + } else if term.as_str() == "false" { + false + } else { + return parse_error(); + }, + span: term.span(), + }), + rest, + )), + _ => parse_error(), + }, + } + } + + fn description() -> Option<&'static str> { + Some("literal") + } + } + + impl_synom!(LitStr "string literal" switch!( + syn!(Lit), + Lit::Str(lit) => value!(lit) + | + _ => reject!() + )); + + impl_synom!(LitByteStr "byte string literal" switch!( + syn!(Lit), + Lit::ByteStr(lit) => value!(lit) + | + _ => reject!() + )); + + impl_synom!(LitByte "byte literal" switch!( + syn!(Lit), + Lit::Byte(lit) => value!(lit) + | + _ => reject!() + )); + + impl_synom!(LitChar "character literal" switch!( + syn!(Lit), + Lit::Char(lit) => value!(lit) + | + _ => reject!() + )); + + impl_synom!(LitInt "integer literal" switch!( + syn!(Lit), + Lit::Int(lit) => value!(lit) + | + _ => reject!() + )); + + impl_synom!(LitFloat "floating point literal" switch!( + syn!(Lit), + Lit::Float(lit) => value!(lit) + | + _ => reject!() + )); + + impl_synom!(LitBool "boolean literal" switch!( + syn!(Lit), + Lit::Bool(lit) => value!(lit) + | + _ => reject!() + )); +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use quote::{ToTokens, Tokens}; + + impl ToTokens for LitStr { + fn to_tokens(&self, tokens: &mut Tokens) { + self.token.to_tokens(tokens); + } + } + + impl ToTokens for LitByteStr { + fn to_tokens(&self, tokens: &mut Tokens) { + self.token.to_tokens(tokens); + } + } + + impl ToTokens for LitByte { + fn to_tokens(&self, tokens: &mut Tokens) { + self.token.to_tokens(tokens); + } + } + + impl ToTokens for LitChar { + fn to_tokens(&self, tokens: &mut Tokens) { + self.token.to_tokens(tokens); + } + } + + impl ToTokens for LitInt { + fn to_tokens(&self, tokens: &mut Tokens) { + self.token.to_tokens(tokens); + } + } + + impl ToTokens for LitFloat { + fn to_tokens(&self, tokens: &mut Tokens) { + self.token.to_tokens(tokens); + } + } + + impl ToTokens for LitBool { + fn to_tokens(&self, tokens: &mut Tokens) { + let s = if self.value { "true" } else { "false" }; + tokens.append(Term::new(s, self.span)); + } + } + + impl ToTokens for LitVerbatim { + fn to_tokens(&self, tokens: &mut Tokens) { + self.token.to_tokens(tokens); + } + } +} + +mod value { + use super::*; + use std::char; + use std::ops::{Index, RangeFrom}; + use proc_macro2::TokenStream; + + impl Lit { + /// Interpret a Syn literal from a proc-macro2 literal. + /// + /// Not all proc-macro2 literals are valid Syn literals. In particular, + /// doc comments are considered by proc-macro2 to be literals but in Syn + /// they are [`Attribute`]. + /// + /// [`Attribute`]: struct.Attribute.html + /// + /// # Panics + /// + /// Panics if the input is a doc comment literal. + pub fn new(token: Literal) -> Self { + let value = token.to_string(); + + match value::byte(&value, 0) { + b'"' | b'r' => { + return Lit::Str(LitStr { + token: token, + }) + } + b'b' => match value::byte(&value, 1) { + b'"' | b'r' => { + return Lit::ByteStr(LitByteStr { + token: token, + }) + } + b'\'' => { + return Lit::Byte(LitByte { + token: token, + }) + } + _ => {} + }, + b'\'' => { + return Lit::Char(LitChar { + token: token, + }) + } + b'0'...b'9' => if number_is_int(&value) { + return Lit::Int(LitInt { + token: token, + }); + } else if number_is_float(&value) { + return Lit::Float(LitFloat { + token: token, + }); + } else { + // number overflow + return Lit::Verbatim(LitVerbatim { + token: token, + }); + }, + _ => if value == "true" || value == "false" { + return Lit::Bool(LitBool { + value: value == "true", + span: token.span(), + }); + }, + } + + panic!("Unrecognized literal: {}", value); + } + } + + fn number_is_int(value: &str) -> bool { + if number_is_float(value) { + false + } else { + value::parse_lit_int(value).is_some() + } + } + + fn number_is_float(value: &str) -> bool { + if value.contains('.') { + true + } else if value.starts_with("0x") || value.ends_with("size") { + false + } else { + value.contains('e') || value.contains('E') + } + } + + /// Get the byte at offset idx, or a default of `b'\0'` if we're looking + /// past the end of the input buffer. + pub fn byte<S: AsRef<[u8]> + ?Sized>(s: &S, idx: usize) -> u8 { + let s = s.as_ref(); + if idx < s.len() { + s[idx] + } else { + 0 + } + } + + fn next_chr(s: &str) -> char { + s.chars().next().unwrap_or('\0') + } + + pub fn parse_lit_str(s: &str) -> String { + match byte(s, 0) { + b'"' => parse_lit_str_cooked(s), + b'r' => parse_lit_str_raw(s), + _ => unreachable!(), + } + } + + // Clippy false positive + // https://github.com/rust-lang-nursery/rust-clippy/issues/2329 + #[cfg_attr(feature = "cargo-clippy", allow(needless_continue))] + fn parse_lit_str_cooked(mut s: &str) -> String { + assert_eq!(byte(s, 0), b'"'); + s = &s[1..]; + + let mut out = String::new(); + 'outer: loop { + let ch = match byte(s, 0) { + b'"' => break, + b'\\' => { + let b = byte(s, 1); + s = &s[2..]; + match b { + b'x' => { + let (byte, rest) = backslash_x(s); + s = rest; + assert!(byte <= 0x80, "Invalid \\x byte in string literal"); + char::from_u32(u32::from(byte)).unwrap() + } + b'u' => { + let (chr, rest) = backslash_u(s); + s = rest; + chr + } + b'n' => '\n', + b'r' => '\r', + b't' => '\t', + b'\\' => '\\', + b'0' => '\0', + b'\'' => '\'', + b'"' => '"', + b'\r' | b'\n' => loop { + let ch = next_chr(s); + if ch.is_whitespace() { + s = &s[ch.len_utf8()..]; + } else { + continue 'outer; + } + }, + b => panic!("unexpected byte {:?} after \\ character in byte literal", b), + } + } + b'\r' => { + assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string"); + s = &s[2..]; + '\n' + } + _ => { + let ch = next_chr(s); + s = &s[ch.len_utf8()..]; + ch + } + }; + out.push(ch); + } + + assert_eq!(s, "\""); + out + } + + fn parse_lit_str_raw(mut s: &str) -> String { + assert_eq!(byte(s, 0), b'r'); + s = &s[1..]; + + let mut pounds = 0; + while byte(s, pounds) == b'#' { + pounds += 1; + } + assert_eq!(byte(s, pounds), b'"'); + assert_eq!(byte(s, s.len() - pounds - 1), b'"'); + for end in s[s.len() - pounds..].bytes() { + assert_eq!(end, b'#'); + } + + s[pounds + 1..s.len() - pounds - 1].to_owned() + } + + pub fn parse_lit_byte_str(s: &str) -> Vec<u8> { + assert_eq!(byte(s, 0), b'b'); + match byte(s, 1) { + b'"' => parse_lit_byte_str_cooked(s), + b'r' => parse_lit_byte_str_raw(s), + _ => unreachable!(), + } + } + + // Clippy false positive + // https://github.com/rust-lang-nursery/rust-clippy/issues/2329 + #[cfg_attr(feature = "cargo-clippy", allow(needless_continue))] + fn parse_lit_byte_str_cooked(mut s: &str) -> Vec<u8> { + assert_eq!(byte(s, 0), b'b'); + assert_eq!(byte(s, 1), b'"'); + s = &s[2..]; + + // We're going to want to have slices which don't respect codepoint boundaries. + let mut s = s.as_bytes(); + + let mut out = Vec::new(); + 'outer: loop { + let byte = match byte(s, 0) { + b'"' => break, + b'\\' => { + let b = byte(s, 1); + s = &s[2..]; + match b { + b'x' => { + let (b, rest) = backslash_x(s); + s = rest; + b + } + b'n' => b'\n', + b'r' => b'\r', + b't' => b'\t', + b'\\' => b'\\', + b'0' => b'\0', + b'\'' => b'\'', + b'"' => b'"', + b'\r' | b'\n' => loop { + let byte = byte(s, 0); + let ch = char::from_u32(u32::from(byte)).unwrap(); + if ch.is_whitespace() { + s = &s[1..]; + } else { + continue 'outer; + } + }, + b => panic!("unexpected byte {:?} after \\ character in byte literal", b), + } + } + b'\r' => { + assert_eq!(byte(s, 1), b'\n', "Bare CR not allowed in string"); + s = &s[2..]; + b'\n' + } + b => { + s = &s[1..]; + b + } + }; + out.push(byte); + } + + assert_eq!(s, b"\""); + out + } + + fn parse_lit_byte_str_raw(s: &str) -> Vec<u8> { + assert_eq!(byte(s, 0), b'b'); + parse_lit_str_raw(&s[1..]).into_bytes() + } + + pub fn parse_lit_byte(s: &str) -> u8 { + assert_eq!(byte(s, 0), b'b'); + assert_eq!(byte(s, 1), b'\''); + + // We're going to want to have slices which don't respect codepoint boundaries. + let mut s = s[2..].as_bytes(); + + let b = match byte(s, 0) { + b'\\' => { + let b = byte(s, 1); + s = &s[2..]; + match b { + b'x' => { + let (b, rest) = backslash_x(s); + s = rest; + b + } + b'n' => b'\n', + b'r' => b'\r', + b't' => b'\t', + b'\\' => b'\\', + b'0' => b'\0', + b'\'' => b'\'', + b'"' => b'"', + b => panic!("unexpected byte {:?} after \\ character in byte literal", b), + } + } + b => { + s = &s[1..]; + b + } + }; + + assert_eq!(byte(s, 0), b'\''); + b + } + + pub fn parse_lit_char(mut s: &str) -> char { + assert_eq!(byte(s, 0), b'\''); + s = &s[1..]; + + let ch = match byte(s, 0) { + b'\\' => { + let b = byte(s, 1); + s = &s[2..]; + match b { + b'x' => { + let (byte, rest) = backslash_x(s); + s = rest; + assert!(byte <= 0x80, "Invalid \\x byte in string literal"); + char::from_u32(u32::from(byte)).unwrap() + } + b'u' => { + let (chr, rest) = backslash_u(s); + s = rest; + chr + } + b'n' => '\n', + b'r' => '\r', + b't' => '\t', + b'\\' => '\\', + b'0' => '\0', + b'\'' => '\'', + b'"' => '"', + b => panic!("unexpected byte {:?} after \\ character in byte literal", b), + } + } + _ => { + let ch = next_chr(s); + s = &s[ch.len_utf8()..]; + ch + } + }; + assert_eq!(s, "\'", "Expected end of char literal"); + ch + } + + fn backslash_x<S>(s: &S) -> (u8, &S) + where + S: Index<RangeFrom<usize>, Output = S> + AsRef<[u8]> + ?Sized, + { + let mut ch = 0; + let b0 = byte(s, 0); + let b1 = byte(s, 1); + ch += 0x10 * match b0 { + b'0'...b'9' => b0 - b'0', + b'a'...b'f' => 10 + (b0 - b'a'), + b'A'...b'F' => 10 + (b0 - b'A'), + _ => panic!("unexpected non-hex character after \\x"), + }; + ch += match b1 { + b'0'...b'9' => b1 - b'0', + b'a'...b'f' => 10 + (b1 - b'a'), + b'A'...b'F' => 10 + (b1 - b'A'), + _ => panic!("unexpected non-hex character after \\x"), + }; + (ch, &s[2..]) + } + + fn backslash_u(mut s: &str) -> (char, &str) { + if byte(s, 0) != b'{' { + panic!("expected {{ after \\u"); + } + s = &s[1..]; + + let mut ch = 0; + for _ in 0..6 { + let b = byte(s, 0); + match b { + b'0'...b'9' => { + ch *= 0x10; + ch += u32::from(b - b'0'); + s = &s[1..]; + } + b'a'...b'f' => { + ch *= 0x10; + ch += u32::from(10 + b - b'a'); + s = &s[1..]; + } + b'A'...b'F' => { + ch *= 0x10; + ch += u32::from(10 + b - b'A'); + s = &s[1..]; + } + b'}' => break, + _ => panic!("unexpected non-hex character after \\u"), + } + } + assert!(byte(s, 0) == b'}'); + s = &s[1..]; + + if let Some(ch) = char::from_u32(ch) { + (ch, s) + } else { + panic!("character code {:x} is not a valid unicode character", ch); + } + } + + pub fn parse_lit_int(mut s: &str) -> Option<u64> { + let base = match (byte(s, 0), byte(s, 1)) { + (b'0', b'x') => { + s = &s[2..]; + 16 + } + (b'0', b'o') => { + s = &s[2..]; + 8 + } + (b'0', b'b') => { + s = &s[2..]; + 2 + } + (b'0'...b'9', _) => 10, + _ => unreachable!(), + }; + + let mut value = 0u64; + loop { + let b = byte(s, 0); + let digit = match b { + b'0'...b'9' => u64::from(b - b'0'), + b'a'...b'f' if base > 10 => 10 + u64::from(b - b'a'), + b'A'...b'F' if base > 10 => 10 + u64::from(b - b'A'), + b'_' => { + s = &s[1..]; + continue; + } + // NOTE: Looking at a floating point literal, we don't want to + // consider these integers. + b'.' if base == 10 => return None, + b'e' | b'E' if base == 10 => return None, + _ => break, + }; + + if digit >= base { + panic!("Unexpected digit {:x} out of base range", digit); + } + + value = match value.checked_mul(base) { + Some(value) => value, + None => return None, + }; + value = match value.checked_add(digit) { + Some(value) => value, + None => return None, + }; + s = &s[1..]; + } + + Some(value) + } + + pub fn parse_lit_float(input: &str) -> f64 { + // Rust's floating point literals are very similar to the ones parsed by + // the standard library, except that rust's literals can contain + // ignorable underscores. Let's remove those underscores. + let mut bytes = input.to_owned().into_bytes(); + let mut write = 0; + for read in 0..bytes.len() { + if bytes[read] == b'_' { + continue; // Don't increase write + } + if write != read { + let x = bytes[read]; + bytes[write] = x; + } + write += 1; + } + bytes.truncate(write); + let input = String::from_utf8(bytes).unwrap(); + let end = input.find('f').unwrap_or_else(|| input.len()); + input[..end].parse().unwrap() + } + + pub fn to_literal(s: &str) -> Literal { + let stream = s.parse::<TokenStream>().unwrap(); + match stream.into_iter().next().unwrap() { + TokenTree::Literal(l) => l, + _ => unreachable!(), + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/macros.rs cargo-0.26.0/vendor/syn-0.13.1/src/macros.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/macros.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/macros.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,186 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[cfg(any(feature = "full", feature = "derive"))] +macro_rules! ast_struct { + ( + $(#[$attr:meta])* + pub struct $name:ident #full $($rest:tt)* + ) => { + #[cfg(feature = "full")] + $(#[$attr])* + #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] + #[cfg_attr(feature = "clone-impls", derive(Clone))] + pub struct $name $($rest)* + + #[cfg(not(feature = "full"))] + $(#[$attr])* + #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] + #[cfg_attr(feature = "clone-impls", derive(Clone))] + pub struct $name { + _noconstruct: (), + } + }; + + ( + $(#[$attr:meta])* + pub struct $name:ident #manual_extra_traits $($rest:tt)* + ) => { + $(#[$attr])* + #[cfg_attr(feature = "extra-traits", derive(Debug))] + #[cfg_attr(feature = "clone-impls", derive(Clone))] + pub struct $name $($rest)* + }; + + ( + $(#[$attr:meta])* + pub struct $name:ident $($rest:tt)* + ) => { + $(#[$attr])* + #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] + #[cfg_attr(feature = "clone-impls", derive(Clone))] + pub struct $name $($rest)* + }; +} + +#[cfg(any(feature = "full", feature = "derive"))] +macro_rules! ast_enum { + ( + $(#[$enum_attr:meta])* + pub enum $name:ident $(# $tags:ident)* { $($variants:tt)* } + ) => ( + $(#[$enum_attr])* + #[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] + #[cfg_attr(feature = "clone-impls", derive(Clone))] + pub enum $name { + $($variants)* + } + ) +} + +#[cfg(any(feature = "full", feature = "derive"))] +macro_rules! ast_enum_of_structs { + ( + $(#[$enum_attr:meta])* + pub enum $name:ident { + $( + $(#[$variant_attr:meta])* + pub $variant:ident $( ($member:ident $($rest:tt)*) )*, + )* + } + + $($remaining:tt)* + ) => ( + ast_enum! { + $(#[$enum_attr])* + pub enum $name { + $( + $(#[$variant_attr])* + $variant $( ($member) )*, + )* + } + } + + $( + maybe_ast_struct! { + $(#[$variant_attr])* + $( + pub struct $member $($rest)* + )* + } + + $( + impl From<$member> for $name { + fn from(e: $member) -> $name { + $name::$variant(e) + } + } + )* + )* + + #[cfg(feature = "printing")] + generate_to_tokens! { + $($remaining)* + () + tokens + $name { $($variant $( [$($rest)*] )*,)* } + } + ) +} + +#[cfg(all(feature = "printing", any(feature = "full", feature = "derive")))] +macro_rules! generate_to_tokens { + (do_not_generate_to_tokens $($foo:tt)*) => (); + + (($($arms:tt)*) $tokens:ident $name:ident { $variant:ident, $($next:tt)*}) => { + generate_to_tokens!( + ($($arms)* $name::$variant => {}) + $tokens $name { $($next)* } + ); + }; + + (($($arms:tt)*) $tokens:ident $name:ident { $variant:ident [$($rest:tt)*], $($next:tt)*}) => { + generate_to_tokens!( + ($($arms)* $name::$variant(ref _e) => to_tokens_call!(_e, $tokens, $($rest)*),) + $tokens $name { $($next)* } + ); + }; + + (($($arms:tt)*) $tokens:ident $name:ident {}) => { + impl ::quote::ToTokens for $name { + fn to_tokens(&self, $tokens: &mut ::quote::Tokens) { + match *self { + $($arms)* + } + } + } + }; +} + +#[cfg(all(feature = "printing", feature = "full"))] +macro_rules! to_tokens_call { + ($e:ident, $tokens:ident, $($rest:tt)*) => { + $e.to_tokens($tokens) + }; +} + +#[cfg(all(feature = "printing", feature = "derive", not(feature = "full")))] +macro_rules! to_tokens_call { + // If the variant is marked as #full, don't auto-generate to-tokens for it. + ($e:ident, $tokens:ident, #full $($rest:tt)*) => { + unreachable!() + }; + ($e:ident, $tokens:ident, $($rest:tt)*) => { + $e.to_tokens($tokens) + }; +} + +#[cfg(any(feature = "full", feature = "derive"))] +macro_rules! maybe_ast_struct { + ( + $(#[$attr:meta])* + $( + pub struct $name:ident + )* + ) => (); + + ($($rest:tt)*) => (ast_struct! { $($rest)* }); +} + +#[cfg(all(feature = "parsing", any(feature = "full", feature = "derive")))] +macro_rules! impl_synom { + ($t:ident $description:tt $($parser:tt)+) => { + impl Synom for $t { + named!(parse -> Self, $($parser)+); + + fn description() -> Option<&'static str> { + Some($description) + } + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/mac.rs cargo-0.26.0/vendor/syn-0.13.1/src/mac.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/mac.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/mac.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,115 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use super::*; +use proc_macro2::TokenStream; +use token::{Brace, Bracket, Paren}; + +#[cfg(feature = "extra-traits")] +use std::hash::{Hash, Hasher}; +#[cfg(feature = "extra-traits")] +use tt::TokenStreamHelper; + +ast_struct! { + /// A macro invocation: `println!("{}", mac)`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct Macro #manual_extra_traits { + pub path: Path, + pub bang_token: Token![!], + pub delimiter: MacroDelimiter, + pub tts: TokenStream, + } +} + +ast_enum! { + /// A grouping token that surrounds a macro body: `m!(...)` or `m!{...}` or `m![...]`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub enum MacroDelimiter { + Paren(Paren), + Brace(Brace), + Bracket(Bracket), + } +} + +#[cfg(feature = "extra-traits")] +impl Eq for Macro {} + +#[cfg(feature = "extra-traits")] +impl PartialEq for Macro { + fn eq(&self, other: &Self) -> bool { + self.path == other.path && self.bang_token == other.bang_token + && self.delimiter == other.delimiter + && TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) + } +} + +#[cfg(feature = "extra-traits")] +impl Hash for Macro { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + self.path.hash(state); + self.bang_token.hash(state); + self.delimiter.hash(state); + TokenStreamHelper(&self.tts).hash(state); + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + + use synom::Synom; + + impl Synom for Macro { + named!(parse -> Self, do_parse!( + what: call!(Path::parse_mod_style) >> + bang: punct!(!) >> + body: call!(tt::delimited) >> + (Macro { + path: what, + bang_token: bang, + delimiter: body.0, + tts: body.1, + }) + )); + + fn description() -> Option<&'static str> { + Some("macro invocation") + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use quote::{ToTokens, Tokens}; + + impl ToTokens for Macro { + fn to_tokens(&self, tokens: &mut Tokens) { + self.path.to_tokens(tokens); + self.bang_token.to_tokens(tokens); + match self.delimiter { + MacroDelimiter::Paren(ref paren) => { + paren.surround(tokens, |tokens| self.tts.to_tokens(tokens)); + } + MacroDelimiter::Brace(ref brace) => { + brace.surround(tokens, |tokens| self.tts.to_tokens(tokens)); + } + MacroDelimiter::Bracket(ref bracket) => { + bracket.surround(tokens, |tokens| self.tts.to_tokens(tokens)); + } + } + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/op.rs cargo-0.26.0/vendor/syn-0.13.1/src/op.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/op.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/op.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,223 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +ast_enum! { + /// A binary operator: `+`, `+=`, `&`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + #[cfg_attr(feature = "clone-impls", derive(Copy))] + pub enum BinOp { + /// The `+` operator (addition) + Add(Token![+]), + /// The `-` operator (subtraction) + Sub(Token![-]), + /// The `*` operator (multiplication) + Mul(Token![*]), + /// The `/` operator (division) + Div(Token![/]), + /// The `%` operator (modulus) + Rem(Token![%]), + /// The `&&` operator (logical and) + And(Token![&&]), + /// The `||` operator (logical or) + Or(Token![||]), + /// The `^` operator (bitwise xor) + BitXor(Token![^]), + /// The `&` operator (bitwise and) + BitAnd(Token![&]), + /// The `|` operator (bitwise or) + BitOr(Token![|]), + /// The `<<` operator (shift left) + Shl(Token![<<]), + /// The `>>` operator (shift right) + Shr(Token![>>]), + /// The `==` operator (equality) + Eq(Token![==]), + /// The `<` operator (less than) + Lt(Token![<]), + /// The `<=` operator (less than or equal to) + Le(Token![<=]), + /// The `!=` operator (not equal to) + Ne(Token![!=]), + /// The `>=` operator (greater than or equal to) + Ge(Token![>=]), + /// The `>` operator (greater than) + Gt(Token![>]), + /// The `+=` operator + AddEq(Token![+=]), + /// The `-=` operator + SubEq(Token![-=]), + /// The `*=` operator + MulEq(Token![*=]), + /// The `/=` operator + DivEq(Token![/=]), + /// The `%=` operator + RemEq(Token![%=]), + /// The `^=` operator + BitXorEq(Token![^=]), + /// The `&=` operator + BitAndEq(Token![&=]), + /// The `|=` operator + BitOrEq(Token![|=]), + /// The `<<=` operator + ShlEq(Token![<<=]), + /// The `>>=` operator + ShrEq(Token![>>=]), + } +} + +ast_enum! { + /// A unary operator: `*`, `!`, `-`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + #[cfg_attr(feature = "clone-impls", derive(Copy))] + pub enum UnOp { + /// The `*` operator for dereferencing + Deref(Token![*]), + /// The `!` operator for logical inversion + Not(Token![!]), + /// The `-` operator for negation + Neg(Token![-]), + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + use synom::Synom; + + impl BinOp { + named!(pub parse_binop -> Self, alt!( + punct!(&&) => { BinOp::And } + | + punct!(||) => { BinOp::Or } + | + punct!(<<) => { BinOp::Shl } + | + punct!(>>) => { BinOp::Shr } + | + punct!(==) => { BinOp::Eq } + | + punct!(<=) => { BinOp::Le } + | + punct!(!=) => { BinOp::Ne } + | + punct!(>=) => { BinOp::Ge } + | + punct!(+) => { BinOp::Add } + | + punct!(-) => { BinOp::Sub } + | + punct!(*) => { BinOp::Mul } + | + punct!(/) => { BinOp::Div } + | + punct!(%) => { BinOp::Rem } + | + punct!(^) => { BinOp::BitXor } + | + punct!(&) => { BinOp::BitAnd } + | + punct!(|) => { BinOp::BitOr } + | + punct!(<) => { BinOp::Lt } + | + punct!(>) => { BinOp::Gt } + )); + + #[cfg(feature = "full")] + named!(pub parse_assign_op -> Self, alt!( + punct!(+=) => { BinOp::AddEq } + | + punct!(-=) => { BinOp::SubEq } + | + punct!(*=) => { BinOp::MulEq } + | + punct!(/=) => { BinOp::DivEq } + | + punct!(%=) => { BinOp::RemEq } + | + punct!(^=) => { BinOp::BitXorEq } + | + punct!(&=) => { BinOp::BitAndEq } + | + punct!(|=) => { BinOp::BitOrEq } + | + punct!(<<=) => { BinOp::ShlEq } + | + punct!(>>=) => { BinOp::ShrEq } + )); + } + + impl Synom for UnOp { + named!(parse -> Self, alt!( + punct!(*) => { UnOp::Deref } + | + punct!(!) => { UnOp::Not } + | + punct!(-) => { UnOp::Neg } + )); + + fn description() -> Option<&'static str> { + Some("unary operator: `*`, `!`, or `-`") + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use quote::{ToTokens, Tokens}; + + impl ToTokens for BinOp { + fn to_tokens(&self, tokens: &mut Tokens) { + match *self { + BinOp::Add(ref t) => t.to_tokens(tokens), + BinOp::Sub(ref t) => t.to_tokens(tokens), + BinOp::Mul(ref t) => t.to_tokens(tokens), + BinOp::Div(ref t) => t.to_tokens(tokens), + BinOp::Rem(ref t) => t.to_tokens(tokens), + BinOp::And(ref t) => t.to_tokens(tokens), + BinOp::Or(ref t) => t.to_tokens(tokens), + BinOp::BitXor(ref t) => t.to_tokens(tokens), + BinOp::BitAnd(ref t) => t.to_tokens(tokens), + BinOp::BitOr(ref t) => t.to_tokens(tokens), + BinOp::Shl(ref t) => t.to_tokens(tokens), + BinOp::Shr(ref t) => t.to_tokens(tokens), + BinOp::Eq(ref t) => t.to_tokens(tokens), + BinOp::Lt(ref t) => t.to_tokens(tokens), + BinOp::Le(ref t) => t.to_tokens(tokens), + BinOp::Ne(ref t) => t.to_tokens(tokens), + BinOp::Ge(ref t) => t.to_tokens(tokens), + BinOp::Gt(ref t) => t.to_tokens(tokens), + BinOp::AddEq(ref t) => t.to_tokens(tokens), + BinOp::SubEq(ref t) => t.to_tokens(tokens), + BinOp::MulEq(ref t) => t.to_tokens(tokens), + BinOp::DivEq(ref t) => t.to_tokens(tokens), + BinOp::RemEq(ref t) => t.to_tokens(tokens), + BinOp::BitXorEq(ref t) => t.to_tokens(tokens), + BinOp::BitAndEq(ref t) => t.to_tokens(tokens), + BinOp::BitOrEq(ref t) => t.to_tokens(tokens), + BinOp::ShlEq(ref t) => t.to_tokens(tokens), + BinOp::ShrEq(ref t) => t.to_tokens(tokens), + } + } + } + + impl ToTokens for UnOp { + fn to_tokens(&self, tokens: &mut Tokens) { + match *self { + UnOp::Deref(ref t) => t.to_tokens(tokens), + UnOp::Not(ref t) => t.to_tokens(tokens), + UnOp::Neg(ref t) => t.to_tokens(tokens), + } + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/parse_quote.rs cargo-0.26.0/vendor/syn-0.13.1/src/parse_quote.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/parse_quote.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/parse_quote.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,160 @@ +/// Quasi-quotation macro that accepts input like the [`quote!`] macro but uses +/// type inference to figure out a return type for those tokens. +/// +/// [`quote!`]: https://docs.rs/quote/0.4/quote/index.html +/// +/// The return type can be any syntax tree node that implements the [`Synom`] +/// trait. +/// +/// [`Synom`]: synom/trait.Synom.html +/// +/// ``` +/// #[macro_use] +/// extern crate syn; +/// +/// #[macro_use] +/// extern crate quote; +/// +/// use syn::Stmt; +/// +/// fn main() { +/// let name = quote!(v); +/// let ty = quote!(u8); +/// +/// let stmt: Stmt = parse_quote! { +/// let #name: #ty = Default::default(); +/// }; +/// +/// println!("{:#?}", stmt); +/// } +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature, +/// although interpolation of syntax tree nodes into the quoted tokens is only +/// supported if Syn is built with the `"printing"` feature as well.* +/// +/// # Example +/// +/// The following helper function adds a bound `T: HeapSize` to every type +/// parameter `T` in the input generics. +/// +/// ``` +/// # #[macro_use] +/// # extern crate syn; +/// # +/// # #[macro_use] +/// # extern crate quote; +/// # +/// # use syn::{Generics, GenericParam}; +/// # +/// // Add a bound `T: HeapSize` to every type parameter T. +/// fn add_trait_bounds(mut generics: Generics) -> Generics { +/// for param in &mut generics.params { +/// if let GenericParam::Type(ref mut type_param) = *param { +/// type_param.bounds.push(parse_quote!(HeapSize)); +/// } +/// } +/// generics +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// # Special cases +/// +/// This macro can parse the following additional types as a special case even +/// though they do not implement the `Synom` trait. +/// +/// - [`Attribute`] — parses one attribute, allowing either outer like `#[...]` +/// or inner like `#![...]` +/// - [`Punctuated<T, P>`] — parses zero or more `T` separated by punctuation +/// `P` with optional trailing punctuation +/// +/// [`Attribute`]: struct.Attribute.html +/// [`Punctuated<T, P>`]: punctuated/struct.Punctuated.html +/// +/// # Panics +/// +/// Panics if the tokens fail to parse as the expected syntax tree type. The +/// caller is responsible for ensuring that the input tokens are syntactically +/// valid. +#[macro_export] +macro_rules! parse_quote { + ($($tt:tt)*) => { + $crate::parse_quote::parse($crate::parse_quote::From::from(quote!($($tt)*))) + }; +} + +//////////////////////////////////////////////////////////////////////////////// +// Can parse any type that implements Synom. + +use synom::{Synom, Parser, PResult}; +use buffer::Cursor; +use proc_macro2::TokenStream; + +// Not public API. +#[doc(hidden)] +pub use std::convert::From; + +// Not public API. +#[doc(hidden)] +pub fn parse<T: ParseQuote>(token_stream: TokenStream) -> T { + let parser = T::parse; + match parser.parse2(token_stream) { + Ok(t) => t, + Err(err) => match T::description() { + Some(s) => panic!("failed to parse {}: {}", s, err), + None => panic!("{}", err), + } + } +} + +// Not public API. +#[doc(hidden)] +pub trait ParseQuote: Sized { + fn parse(input: Cursor) -> PResult<Self>; + fn description() -> Option<&'static str>; +} + +impl<T> ParseQuote for T where T: Synom { + fn parse(input: Cursor) -> PResult<Self> { + <T as Synom>::parse(input) + } + + fn description() -> Option<&'static str> { + <T as Synom>::description() + } +} + +//////////////////////////////////////////////////////////////////////////////// +// Any other types that we want `parse_quote!` to be able to parse. + +use punctuated::Punctuated; + +#[cfg(any(feature = "full", feature = "derive"))] +use Attribute; + +impl<T, P> ParseQuote for Punctuated<T, P> +where + T: Synom, + P: Synom, +{ + named!(parse -> Self, call!(Punctuated::parse_terminated)); + + fn description() -> Option<&'static str> { + Some("punctuated sequence") + } +} + +#[cfg(any(feature = "full", feature = "derive"))] +impl ParseQuote for Attribute { + named!(parse -> Self, alt!( + call!(Attribute::parse_outer) + | + call!(Attribute::parse_inner) + )); + + fn description() -> Option<&'static str> { + Some("attribute") + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/parsers.rs cargo-0.26.0/vendor/syn-0.13.1/src/parsers.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/parsers.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/parsers.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1384 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use buffer::Cursor; +use parse_error; +use synom::PResult; + +/// Define a parser function with the signature expected by syn parser +/// combinators. +/// +/// The function may be the `parse` function of the [`Synom`] trait, or it may +/// be a free-standing function with an arbitrary name. When implementing the +/// `Synom` trait, the function name is `parse` and the return type is `Self`. +/// +/// [`Synom`]: synom/trait.Synom.html +/// +/// - **Syntax:** `named!(NAME -> TYPE, PARSER)` or `named!(pub NAME -> TYPE, PARSER)` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::Type; +/// use syn::punctuated::Punctuated; +/// use syn::synom::Synom; +/// +/// /// Parses one or more Rust types separated by commas. +/// /// +/// /// Example: `String, Vec<T>, [u8; LEN + 1]` +/// named!(pub comma_separated_types -> Punctuated<Type, Token![,]>, +/// call!(Punctuated::parse_separated_nonempty) +/// ); +/// +/// /// The same function as a `Synom` implementation. +/// struct CommaSeparatedTypes { +/// types: Punctuated<Type, Token![,]>, +/// } +/// +/// impl Synom for CommaSeparatedTypes { +/// /// As the default behavior, we want there to be at least 1 type. +/// named!(parse -> Self, do_parse!( +/// types: call!(Punctuated::parse_separated_nonempty) >> +/// (CommaSeparatedTypes { types }) +/// )); +/// } +/// +/// impl CommaSeparatedTypes { +/// /// A separate parser that the user can invoke explicitly which allows +/// /// for parsing 0 or more types, rather than the default 1 or more. +/// named!(pub parse0 -> Self, do_parse!( +/// types: call!(Punctuated::parse_separated) >> +/// (CommaSeparatedTypes { types }) +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! named { + ($name:ident -> $o:ty, $submac:ident!( $($args:tt)* )) => { + fn $name(i: $crate::buffer::Cursor) -> $crate::synom::PResult<$o> { + $submac!(i, $($args)*) + } + }; + + (pub $name:ident -> $o:ty, $submac:ident!( $($args:tt)* )) => { + pub fn $name(i: $crate::buffer::Cursor) -> $crate::synom::PResult<$o> { + $submac!(i, $($args)*) + } + }; + + // These two variants are for defining named parsers which have custom + // arguments, and are called with `call!()` + ($name:ident($($params:tt)*) -> $o:ty, $submac:ident!( $($args:tt)* )) => { + fn $name(i: $crate::buffer::Cursor, $($params)*) -> $crate::synom::PResult<$o> { + $submac!(i, $($args)*) + } + }; + + (pub $name:ident($($params:tt)*) -> $o:ty, $submac:ident!( $($args:tt)* )) => { + pub fn $name(i: $crate::buffer::Cursor, $($params)*) -> $crate::synom::PResult<$o> { + $submac!(i, $($args)*) + } + }; +} + +#[cfg(synom_verbose_trace)] +#[macro_export] +macro_rules! call { + ($i:expr, $fun:expr $(, $args:expr)*) => {{ + let i = $i; + eprintln!(concat!(" -> ", stringify!($fun), " @ {:?}"), i); + let r = $fun(i $(, $args)*); + match r { + Ok((_, i)) => eprintln!(concat!("OK ", stringify!($fun), " @ {:?}"), i), + Err(_) => eprintln!(concat!("ERR ", stringify!($fun), " @ {:?}"), i), + } + r + }}; +} + +/// Invoke the given parser function with zero or more arguments. +/// +/// - **Syntax:** `call!(FN, ARGS...)` +/// +/// where the signature of the function is `fn(Cursor, ARGS...) -> PResult<T>` +/// +/// - **Output:** `T`, the result of invoking the function `FN` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::Type; +/// use syn::punctuated::Punctuated; +/// use syn::synom::Synom; +/// +/// /// Parses one or more Rust types separated by commas. +/// /// +/// /// Example: `String, Vec<T>, [u8; LEN + 1]` +/// struct CommaSeparatedTypes { +/// types: Punctuated<Type, Token![,]>, +/// } +/// +/// impl Synom for CommaSeparatedTypes { +/// named!(parse -> Self, do_parse!( +/// types: call!(Punctuated::parse_separated_nonempty) >> +/// (CommaSeparatedTypes { types }) +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[cfg(not(synom_verbose_trace))] +#[macro_export] +macro_rules! call { + ($i:expr, $fun:expr $(, $args:expr)*) => { + $fun($i $(, $args)*) + }; +} + +/// Transform the result of a parser by applying a function or closure. +/// +/// - **Syntax:** `map!(THING, FN)` +/// - **Output:** the return type of function FN applied to THING +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::{Expr, ExprIf}; +/// +/// /// Extracts the branch condition of an `if`-expression. +/// fn get_cond(if_: ExprIf) -> Expr { +/// *if_.cond +/// } +/// +/// /// Parses a full `if`-expression but returns the condition part only. +/// /// +/// /// Example: `if x > 0xFF { "big" } else { "small" }` +/// /// The return would be the expression `x > 0xFF`. +/// named!(if_condition -> Expr, +/// map!(syn!(ExprIf), get_cond) +/// ); +/// +/// /// Equivalent using a closure. +/// named!(if_condition2 -> Expr, +/// map!(syn!(ExprIf), |if_| *if_.cond) +/// ); +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! map { + ($i:expr, $submac:ident!( $($args:tt)* ), $g:expr) => { + match $submac!($i, $($args)*) { + ::std::result::Result::Err(err) => + ::std::result::Result::Err(err), + ::std::result::Result::Ok((o, i)) => + ::std::result::Result::Ok(($crate::parsers::invoke($g, o), i)), + } + }; + + ($i:expr, $f:expr, $g:expr) => { + map!($i, call!($f), $g) + }; +} + +// Somehow this helps with type inference in `map!` and `alt!`. +// +// Not public API. +#[doc(hidden)] +pub fn invoke<T, R, F: FnOnce(T) -> R>(f: F, t: T) -> R { + f(t) +} + +/// Invert the result of a parser by parsing successfully if the given parser +/// fails to parse and vice versa. +/// +/// Does not consume any of the input. +/// +/// - **Syntax:** `not!(THING)` +/// - **Output:** `()` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::{Expr, Ident}; +/// +/// /// Parses any expression that does not begin with a `-` minus sign. +/// named!(not_negative_expr -> Expr, do_parse!( +/// not!(punct!(-)) >> +/// e: syn!(Expr) >> +/// (e) +/// )); +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! not { + ($i:expr, $submac:ident!( $($args:tt)* )) => { + match $submac!($i, $($args)*) { + ::std::result::Result::Ok(_) => $crate::parse_error(), + ::std::result::Result::Err(_) => + ::std::result::Result::Ok(((), $i)), + } + }; +} + +/// Execute a parser only if a condition is met, otherwise return None. +/// +/// If you are familiar with nom, this is nom's `cond_with_error` parser. +/// +/// - **Syntax:** `cond!(CONDITION, THING)` +/// - **Output:** `Some(THING)` if the condition is true, else `None` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::{Ident, MacroDelimiter}; +/// use syn::token::{Paren, Bracket, Brace}; +/// use syn::synom::Synom; +/// +/// /// Parses a macro call with empty input. If the macro is written with +/// /// parentheses or brackets, a trailing semicolon is required. +/// /// +/// /// Example: `my_macro!{}` or `my_macro!();` or `my_macro![];` +/// struct EmptyMacroCall { +/// name: Ident, +/// bang_token: Token![!], +/// empty_body: MacroDelimiter, +/// semi_token: Option<Token![;]>, +/// } +/// +/// fn requires_semi(delimiter: &MacroDelimiter) -> bool { +/// match *delimiter { +/// MacroDelimiter::Paren(_) | MacroDelimiter::Bracket(_) => true, +/// MacroDelimiter::Brace(_) => false, +/// } +/// } +/// +/// impl Synom for EmptyMacroCall { +/// named!(parse -> Self, do_parse!( +/// name: syn!(Ident) >> +/// bang_token: punct!(!) >> +/// empty_body: alt!( +/// parens!(epsilon!()) => { |d| MacroDelimiter::Paren(d.0) } +/// | +/// brackets!(epsilon!()) => { |d| MacroDelimiter::Bracket(d.0) } +/// | +/// braces!(epsilon!()) => { |d| MacroDelimiter::Brace(d.0) } +/// ) >> +/// semi_token: cond!(requires_semi(&empty_body), punct!(;)) >> +/// (EmptyMacroCall { +/// name, +/// bang_token, +/// empty_body, +/// semi_token, +/// }) +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! cond { + ($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => { + if $cond { + match $submac!($i, $($args)*) { + ::std::result::Result::Ok((o, i)) => + ::std::result::Result::Ok((::std::option::Option::Some(o), i)), + ::std::result::Result::Err(x) => ::std::result::Result::Err(x), + } + } else { + ::std::result::Result::Ok((::std::option::Option::None, $i)) + } + }; + + ($i:expr, $cond:expr, $f:expr) => { + cond!($i, $cond, call!($f)) + }; +} + +/// Execute a parser only if a condition is met, otherwise fail to parse. +/// +/// This is typically used inside of [`option!`] or [`alt!`]. +/// +/// [`option!`]: macro.option.html +/// [`alt!`]: macro.alt.html +/// +/// - **Syntax:** `cond_reduce!(CONDITION, THING)` +/// - **Output:** `THING` +/// +/// The subparser may be omitted in which case it defaults to [`epsilon!`]. +/// +/// [`epsilon!`]: macro.epsilon.html +/// +/// - **Syntax:** `cond_reduce!(CONDITION)` +/// - **Output:** `()` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::Type; +/// use syn::token::Paren; +/// use syn::punctuated::Punctuated; +/// use syn::synom::Synom; +/// +/// /// Parses a possibly variadic function signature. +/// /// +/// /// Example: `fn(A) or `fn(A, B, C, ...)` or `fn(...)` +/// /// Rejected: `fn(A, B...)` +/// struct VariadicFn { +/// fn_token: Token![fn], +/// paren_token: Paren, +/// types: Punctuated<Type, Token![,]>, +/// variadic: Option<Token![...]>, +/// } +/// +/// // Example of using `cond_reduce!` inside of `option!`. +/// impl Synom for VariadicFn { +/// named!(parse -> Self, do_parse!( +/// fn_token: keyword!(fn) >> +/// params: parens!(do_parse!( +/// types: call!(Punctuated::parse_terminated) >> +/// // Allow, but do not require, an ending `...` but only if the +/// // preceding list of types is empty or ends with a trailing comma. +/// variadic: option!(cond_reduce!(types.empty_or_trailing(), punct!(...))) >> +/// (types, variadic) +/// )) >> +/// ({ +/// let (paren_token, (types, variadic)) = params; +/// VariadicFn { +/// fn_token, +/// paren_token, +/// types, +/// variadic, +/// } +/// }) +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! cond_reduce { + ($i:expr, $cond:expr, $submac:ident!( $($args:tt)* )) => { + if $cond { + $submac!($i, $($args)*) + } else { + $crate::parse_error() + } + }; + + ($i:expr, $cond:expr) => { + cond_reduce!($i, $cond, epsilon!()) + }; + + ($i:expr, $cond:expr, $f:expr) => { + cond_reduce!($i, $cond, call!($f)) + }; +} + +/// Parse zero or more values using the given parser. +/// +/// - **Syntax:** `many0!(THING)` +/// - **Output:** `Vec<THING>` +/// +/// You may also be looking for: +/// +/// - `call!(Punctuated::parse_separated)` - zero or more values with separator +/// - `call!(Punctuated::parse_separated_nonempty)` - one or more values +/// - `call!(Punctuated::parse_terminated)` - zero or more, allows trailing separator +/// - `call!(Punctuated::parse_terminated_nonempty)` - one or more +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::{Ident, Item}; +/// use syn::token::Brace; +/// use syn::synom::Synom; +/// +/// /// Parses a module containing zero or more Rust items. +/// /// +/// /// Example: `mod m { type Result<T> = ::std::result::Result<T, MyError>; }` +/// struct SimpleMod { +/// mod_token: Token![mod], +/// name: Ident, +/// brace_token: Brace, +/// items: Vec<Item>, +/// } +/// +/// impl Synom for SimpleMod { +/// named!(parse -> Self, do_parse!( +/// mod_token: keyword!(mod) >> +/// name: syn!(Ident) >> +/// body: braces!(many0!(syn!(Item))) >> +/// (SimpleMod { +/// mod_token, +/// name, +/// brace_token: body.0, +/// items: body.1, +/// }) +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! many0 { + ($i:expr, $submac:ident!( $($args:tt)* )) => {{ + let ret; + let mut res = ::std::vec::Vec::new(); + let mut input = $i; + + loop { + if input.eof() { + ret = ::std::result::Result::Ok((res, input)); + break; + } + + match $submac!(input, $($args)*) { + ::std::result::Result::Err(_) => { + ret = ::std::result::Result::Ok((res, input)); + break; + } + ::std::result::Result::Ok((o, i)) => { + // loop trip must always consume (otherwise infinite loops) + if i == input { + ret = $crate::parse_error(); + break; + } + + res.push(o); + input = i; + } + } + } + + ret + }}; + + ($i:expr, $f:expr) => { + $crate::parsers::many0($i, $f) + }; +} + +// Improve compile time by compiling this loop only once per type it is used +// with. +// +// Not public API. +#[doc(hidden)] +pub fn many0<T>(mut input: Cursor, f: fn(Cursor) -> PResult<T>) -> PResult<Vec<T>> { + let mut res = Vec::new(); + + loop { + if input.eof() { + return Ok((res, input)); + } + + match f(input) { + Err(_) => { + return Ok((res, input)); + } + Ok((o, i)) => { + // loop trip must always consume (otherwise infinite loops) + if i == input { + return parse_error(); + } + + res.push(o); + input = i; + } + } + } +} + +/// Pattern-match the result of a parser to select which other parser to run. +/// +/// - **Syntax:** `switch!(TARGET, PAT1 => THEN1 | PAT2 => THEN2 | ...)` +/// - **Output:** `T`, the return type of `THEN1` and `THEN2` and ... +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::Ident; +/// use syn::token::Brace; +/// use syn::synom::Synom; +/// +/// /// Parse a unit struct or enum: either `struct S;` or `enum E { V }`. +/// enum UnitType { +/// Struct { +/// struct_token: Token![struct], +/// name: Ident, +/// semi_token: Token![;], +/// }, +/// Enum { +/// enum_token: Token![enum], +/// name: Ident, +/// brace_token: Brace, +/// variant: Ident, +/// }, +/// } +/// +/// enum StructOrEnum { +/// Struct(Token![struct]), +/// Enum(Token![enum]), +/// } +/// +/// impl Synom for StructOrEnum { +/// named!(parse -> Self, alt!( +/// keyword!(struct) => { StructOrEnum::Struct } +/// | +/// keyword!(enum) => { StructOrEnum::Enum } +/// )); +/// } +/// +/// impl Synom for UnitType { +/// named!(parse -> Self, do_parse!( +/// which: syn!(StructOrEnum) >> +/// name: syn!(Ident) >> +/// item: switch!(value!(which), +/// StructOrEnum::Struct(struct_token) => map!( +/// punct!(;), +/// |semi_token| UnitType::Struct { +/// struct_token, +/// name, +/// semi_token, +/// } +/// ) +/// | +/// StructOrEnum::Enum(enum_token) => map!( +/// braces!(syn!(Ident)), +/// |(brace_token, variant)| UnitType::Enum { +/// enum_token, +/// name, +/// brace_token, +/// variant, +/// } +/// ) +/// ) >> +/// (item) +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! switch { + ($i:expr, $submac:ident!( $($args:tt)* ), $($p:pat => $subrule:ident!( $($args2:tt)* ))|* ) => { + match $submac!($i, $($args)*) { + ::std::result::Result::Err(err) => ::std::result::Result::Err(err), + ::std::result::Result::Ok((o, i)) => match o { + $( + $p => $subrule!(i, $($args2)*), + )* + } + } + }; +} + +/// Produce the given value without parsing anything. +/// +/// This can be needed where you have an existing parsed value but a parser +/// macro's syntax expects you to provide a submacro, such as in the first +/// argument of [`switch!`] or one of the branches of [`alt!`]. +/// +/// [`switch!`]: macro.switch.html +/// [`alt!`]: macro.alt.html +/// +/// - **Syntax:** `value!(VALUE)` +/// - **Output:** `VALUE` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::Ident; +/// use syn::token::Brace; +/// use syn::synom::Synom; +/// +/// /// Parse a unit struct or enum: either `struct S;` or `enum E { V }`. +/// enum UnitType { +/// Struct { +/// struct_token: Token![struct], +/// name: Ident, +/// semi_token: Token![;], +/// }, +/// Enum { +/// enum_token: Token![enum], +/// name: Ident, +/// brace_token: Brace, +/// variant: Ident, +/// }, +/// } +/// +/// enum StructOrEnum { +/// Struct(Token![struct]), +/// Enum(Token![enum]), +/// } +/// +/// impl Synom for StructOrEnum { +/// named!(parse -> Self, alt!( +/// keyword!(struct) => { StructOrEnum::Struct } +/// | +/// keyword!(enum) => { StructOrEnum::Enum } +/// )); +/// } +/// +/// impl Synom for UnitType { +/// named!(parse -> Self, do_parse!( +/// which: syn!(StructOrEnum) >> +/// name: syn!(Ident) >> +/// item: switch!(value!(which), +/// StructOrEnum::Struct(struct_token) => map!( +/// punct!(;), +/// |semi_token| UnitType::Struct { +/// struct_token, +/// name, +/// semi_token, +/// } +/// ) +/// | +/// StructOrEnum::Enum(enum_token) => map!( +/// braces!(syn!(Ident)), +/// |(brace_token, variant)| UnitType::Enum { +/// enum_token, +/// name, +/// brace_token, +/// variant, +/// } +/// ) +/// ) >> +/// (item) +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! value { + ($i:expr, $res:expr) => { + ::std::result::Result::Ok(($res, $i)) + }; +} + +/// Unconditionally fail to parse anything. +/// +/// This may be useful in rejecting some arms of a `switch!` parser. +/// +/// - **Syntax:** `reject!()` +/// - **Output:** never succeeds +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::Item; +/// +/// // Parse any item, except for a module. +/// named!(almost_any_item -> Item, +/// switch!(syn!(Item), +/// Item::Mod(_) => reject!() +/// | +/// ok => value!(ok) +/// ) +/// ); +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! reject { + ($i:expr,) => {{ + let _ = $i; + $crate::parse_error() + }} +} + +/// Run a series of parsers and produce all of the results in a tuple. +/// +/// - **Syntax:** `tuple!(A, B, C, ...)` +/// - **Output:** `(A, B, C, ...)` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::Type; +/// +/// named!(two_types -> (Type, Type), tuple!(syn!(Type), syn!(Type))); +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! tuple { + ($i:expr, $($rest:tt)*) => { + tuple_parser!($i, (), $($rest)*) + }; +} + +// Internal parser, do not use directly. +#[doc(hidden)] +#[macro_export] +macro_rules! tuple_parser { + ($i:expr, ($($parsed:tt),*), $e:ident, $($rest:tt)*) => { + tuple_parser!($i, ($($parsed),*), call!($e), $($rest)*) + }; + + ($i:expr, (), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => { + match $submac!($i, $($args)*) { + ::std::result::Result::Err(err) => + ::std::result::Result::Err(err), + ::std::result::Result::Ok((o, i)) => + tuple_parser!(i, (o), $($rest)*), + } + }; + + ($i:expr, ($($parsed:tt)*), $submac:ident!( $($args:tt)* ), $($rest:tt)*) => { + match $submac!($i, $($args)*) { + ::std::result::Result::Err(err) => + ::std::result::Result::Err(err), + ::std::result::Result::Ok((o, i)) => + tuple_parser!(i, ($($parsed)* , o), $($rest)*), + } + }; + + ($i:expr, ($($parsed:tt),*), $e:ident) => { + tuple_parser!($i, ($($parsed),*), call!($e)) + }; + + ($i:expr, (), $submac:ident!( $($args:tt)* )) => { + $submac!($i, $($args)*) + }; + + ($i:expr, ($($parsed:expr),*), $submac:ident!( $($args:tt)* )) => { + match $submac!($i, $($args)*) { + ::std::result::Result::Err(err) => + ::std::result::Result::Err(err), + ::std::result::Result::Ok((o, i)) => + ::std::result::Result::Ok((($($parsed),*, o), i)), + } + }; + + ($i:expr, ($($parsed:expr),*)) => { + ::std::result::Result::Ok((($($parsed),*), $i)) + }; +} + +/// Run a series of parsers, returning the result of the first one which +/// succeeds. +/// +/// Optionally allows for the result to be transformed. +/// +/// - **Syntax:** `alt!(THING1 | THING2 => { FUNC } | ...)` +/// - **Output:** `T`, the return type of `THING1` and `FUNC(THING2)` and ... +/// +/// # Example +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::Ident; +/// +/// // Parse any identifier token, or the `!` token in which case the +/// // identifier is treated as `"BANG"`. +/// named!(ident_or_bang -> Ident, alt!( +/// syn!(Ident) +/// | +/// punct!(!) => { |_| "BANG".into() } +/// )); +/// # +/// # fn main() {} +/// ``` +/// +/// The `alt!` macro is most commonly seen when parsing a syntax tree enum such +/// as the [`Item`] enum. +/// +/// [`Item`]: enum.Item.html +/// +/// ``` +/// # #[macro_use] +/// # extern crate syn; +/// # +/// # use syn::synom::Synom; +/// # +/// # struct Item; +/// # +/// impl Synom for Item { +/// named!(parse -> Self, alt!( +/// # epsilon!() => { |_| unimplemented!() } +/// # )); +/// # } +/// # +/// # mod example { +/// # use syn::*; +/// # +/// # named!(parse -> Item, alt!( +/// syn!(ItemExternCrate) => { Item::ExternCrate } +/// | +/// syn!(ItemUse) => { Item::Use } +/// | +/// syn!(ItemStatic) => { Item::Static } +/// | +/// syn!(ItemConst) => { Item::Const } +/// | +/// /* ... */ +/// # syn!(ItemFn) => { Item::Fn } +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! alt { + ($i:expr, $e:ident | $($rest:tt)*) => { + alt!($i, call!($e) | $($rest)*) + }; + + ($i:expr, $subrule:ident!( $($args:tt)*) | $($rest:tt)*) => { + match $subrule!($i, $($args)*) { + res @ ::std::result::Result::Ok(_) => res, + _ => alt!($i, $($rest)*) + } + }; + + ($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr } | $($rest:tt)+) => { + match $subrule!($i, $($args)*) { + ::std::result::Result::Ok((o, i)) => + ::std::result::Result::Ok(($crate::parsers::invoke($gen, o), i)), + ::std::result::Result::Err(_) => alt!($i, $($rest)*), + } + }; + + ($i:expr, $e:ident => { $gen:expr } | $($rest:tt)*) => { + alt!($i, call!($e) => { $gen } | $($rest)*) + }; + + ($i:expr, $e:ident => { $gen:expr }) => { + alt!($i, call!($e) => { $gen }) + }; + + ($i:expr, $subrule:ident!( $($args:tt)* ) => { $gen:expr }) => { + match $subrule!($i, $($args)*) { + ::std::result::Result::Ok((o, i)) => + ::std::result::Result::Ok(($crate::parsers::invoke($gen, o), i)), + ::std::result::Result::Err(err) => + ::std::result::Result::Err(err), + } + }; + + ($i:expr, $e:ident) => { + alt!($i, call!($e)) + }; + + ($i:expr, $subrule:ident!( $($args:tt)*)) => { + $subrule!($i, $($args)*) + }; +} + +/// Run a series of parsers, optionally naming each intermediate result, +/// followed by a step to combine the intermediate results. +/// +/// Produces the result of evaluating the final expression in parentheses with +/// all of the previously named results bound. +/// +/// - **Syntax:** `do_parse!(name: THING1 >> THING2 >> (RESULT))` +/// - **Output:** `RESULT` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// extern crate proc_macro2; +/// +/// use syn::Ident; +/// use syn::token::Paren; +/// use syn::synom::Synom; +/// use proc_macro2::TokenStream; +/// +/// /// Parse a macro invocation that uses `(` `)` parentheses. +/// /// +/// /// Example: `stringify!($args)`. +/// struct Macro { +/// name: Ident, +/// bang_token: Token![!], +/// paren_token: Paren, +/// tts: TokenStream, +/// } +/// +/// impl Synom for Macro { +/// named!(parse -> Self, do_parse!( +/// name: syn!(Ident) >> +/// bang_token: punct!(!) >> +/// body: parens!(syn!(TokenStream)) >> +/// (Macro { +/// name, +/// bang_token, +/// paren_token: body.0, +/// tts: body.1, +/// }) +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! do_parse { + ($i:expr, ( $($rest:expr),* )) => { + ::std::result::Result::Ok((( $($rest),* ), $i)) + }; + + ($i:expr, $e:ident >> $($rest:tt)*) => { + do_parse!($i, call!($e) >> $($rest)*) + }; + + ($i:expr, $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => { + match $submac!($i, $($args)*) { + ::std::result::Result::Err(err) => + ::std::result::Result::Err(err), + ::std::result::Result::Ok((_, i)) => + do_parse!(i, $($rest)*), + } + }; + + ($i:expr, $field:ident : $e:ident >> $($rest:tt)*) => { + do_parse!($i, $field: call!($e) >> $($rest)*) + }; + + ($i:expr, $field:ident : $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => { + match $submac!($i, $($args)*) { + ::std::result::Result::Err(err) => + ::std::result::Result::Err(err), + ::std::result::Result::Ok((o, i)) => { + let $field = o; + do_parse!(i, $($rest)*) + }, + } + }; + + ($i:expr, mut $field:ident : $e:ident >> $($rest:tt)*) => { + do_parse!($i, mut $field: call!($e) >> $($rest)*) + }; + + ($i:expr, mut $field:ident : $submac:ident!( $($args:tt)* ) >> $($rest:tt)*) => { + match $submac!($i, $($args)*) { + ::std::result::Result::Err(err) => + ::std::result::Result::Err(err), + ::std::result::Result::Ok((o, i)) => { + let mut $field = o; + do_parse!(i, $($rest)*) + }, + } + }; +} + +/// Parse nothing and succeed only if the end of the enclosing block has been +/// reached. +/// +/// The enclosing block may be the full input if we are parsing at the top +/// level, or the surrounding parenthesis/bracket/brace if we are parsing within +/// those. +/// +/// - **Syntax:** `input_end!()` +/// - **Output:** `()` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::Expr; +/// use syn::synom::Synom; +/// +/// /// Parses any Rust expression followed either by a semicolon or by the end +/// /// of the input. +/// /// +/// /// For example `many0!(syn!(TerminatedExpr))` would successfully parse the +/// /// following input into three expressions. +/// /// +/// /// 1 + 1; second.two(); third!() +/// /// +/// /// Similarly within a block, `braced!(many0!(syn!(TerminatedExpr)))` would +/// /// successfully parse three expressions. +/// /// +/// /// { 1 + 1; second.two(); third!() } +/// struct TerminatedExpr { +/// expr: Expr, +/// semi_token: Option<Token![;]>, +/// } +/// +/// impl Synom for TerminatedExpr { +/// named!(parse -> Self, do_parse!( +/// expr: syn!(Expr) >> +/// semi_token: alt!( +/// input_end!() => { |_| None } +/// | +/// punct!(;) => { Some } +/// ) >> +/// (TerminatedExpr { +/// expr, +/// semi_token, +/// }) +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! input_end { + ($i:expr,) => { + $crate::parsers::input_end($i) + }; +} + +// Not a public API +#[doc(hidden)] +pub fn input_end(input: Cursor) -> PResult<'static, ()> { + if input.eof() { + Ok(((), Cursor::empty())) + } else { + parse_error() + } +} + +/// Turn a failed parse into `None` and a successful parse into `Some`. +/// +/// A failed parse consumes none of the input. +/// +/// - **Syntax:** `option!(THING)` +/// - **Output:** `Option<THING>` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::{Label, Block}; +/// use syn::synom::Synom; +/// +/// /// Parses a Rust loop. Equivalent to syn::ExprLoop. +/// /// +/// /// Examples: +/// /// loop { println!("y"); } +/// /// 'x: loop { break 'x; } +/// struct ExprLoop { +/// label: Option<Label>, +/// loop_token: Token![loop], +/// body: Block, +/// } +/// +/// impl Synom for ExprLoop { +/// named!(parse -> Self, do_parse!( +/// // Loop may or may not have a label. +/// label: option!(syn!(Label)) >> +/// loop_token: keyword!(loop) >> +/// body: syn!(Block) >> +/// (ExprLoop { +/// label, +/// loop_token, +/// body, +/// }) +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! option { + ($i:expr, $submac:ident!( $($args:tt)* )) => { + match $submac!($i, $($args)*) { + ::std::result::Result::Ok((o, i)) => + ::std::result::Result::Ok((Some(o), i)), + ::std::result::Result::Err(_) => + ::std::result::Result::Ok((None, $i)), + } + }; + + ($i:expr, $f:expr) => { + option!($i, call!($f)); + }; +} + +/// Parses nothing and always succeeds. +/// +/// This can be useful as a fallthrough case in [`alt!`], as shown below. Also +/// useful for parsing empty delimiters using [`parens!`] or [`brackets!`] or +/// [`braces!`] by parsing for example `braces!(epsilon!())` for an empty `{}`. +/// +/// [`alt!`]: macro.alt.html +/// [`parens!`]: macro.parens.html +/// [`brackets!`]: macro.brackets.html +/// [`braces!`]: macro.braces.html +/// +/// - **Syntax:** `epsilon!()` +/// - **Output:** `()` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::synom::Synom; +/// +/// enum Mutability { +/// Mutable(Token![mut]), +/// Immutable, +/// } +/// +/// impl Synom for Mutability { +/// named!(parse -> Self, alt!( +/// keyword!(mut) => { Mutability::Mutable } +/// | +/// epsilon!() => { |_| Mutability::Immutable } +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! epsilon { + ($i:expr,) => { + ::std::result::Result::Ok(((), $i)) + }; +} + +/// Run a parser, binding the result to a name, and then evaluating an +/// expression. +/// +/// Discards the result of the expression and parser. +/// +/// - **Syntax:** `tap!(NAME : THING => EXPR)` +/// - **Output:** `()` +#[doc(hidden)] +#[macro_export] +macro_rules! tap { + ($i:expr, $name:ident : $submac:ident!( $($args:tt)* ) => $e:expr) => { + match $submac!($i, $($args)*) { + ::std::result::Result::Ok((o, i)) => { + let $name = o; + $e; + ::std::result::Result::Ok(((), i)) + } + ::std::result::Result::Err(err) => + ::std::result::Result::Err(err), + } + }; + + ($i:expr, $name:ident : $f:expr => $e:expr) => { + tap!($i, $name: call!($f) => $e); + }; +} + +/// Parse any type that implements the `Synom` trait. +/// +/// Any type implementing [`Synom`] can be used with this parser, whether the +/// implementation is provided by Syn or is one that you write. +/// +/// [`Synom`]: synom/trait.Synom.html +/// +/// - **Syntax:** `syn!(TYPE)` +/// - **Output:** `TYPE` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::{Ident, Item}; +/// use syn::token::Brace; +/// use syn::synom::Synom; +/// +/// /// Parses a module containing zero or more Rust items. +/// /// +/// /// Example: `mod m { type Result<T> = ::std::result::Result<T, MyError>; }` +/// struct SimpleMod { +/// mod_token: Token![mod], +/// name: Ident, +/// brace_token: Brace, +/// items: Vec<Item>, +/// } +/// +/// impl Synom for SimpleMod { +/// named!(parse -> Self, do_parse!( +/// mod_token: keyword!(mod) >> +/// name: syn!(Ident) >> +/// body: braces!(many0!(syn!(Item))) >> +/// (SimpleMod { +/// mod_token, +/// name, +/// brace_token: body.0, +/// items: body.1, +/// }) +/// )); +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! syn { + ($i:expr, $t:ty) => { + <$t as $crate::synom::Synom>::parse($i) + }; +} + +/// Parse inside of `(` `)` parentheses. +/// +/// This macro parses a set of balanced parentheses and invokes a sub-parser on +/// the content inside. The sub-parser is required to consume all tokens within +/// the parentheses in order for this parser to return successfully. +/// +/// - **Syntax:** `parens!(CONTENT)` +/// - **Output:** `(token::Paren, CONTENT)` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::Expr; +/// use syn::token::Paren; +/// +/// /// Parses an expression inside of parentheses. +/// /// +/// /// Example: `(1 + 1)` +/// named!(expr_paren -> (Paren, Expr), parens!(syn!(Expr))); +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! parens { + ($i:expr, $submac:ident!( $($args:tt)* )) => { + $crate::token::Paren::parse($i, |i| $submac!(i, $($args)*)) + }; + + ($i:expr, $f:expr) => { + parens!($i, call!($f)); + }; +} + +/// Parse inside of `[` `]` square brackets. +/// +/// This macro parses a set of balanced brackets and invokes a sub-parser on the +/// content inside. The sub-parser is required to consume all tokens within the +/// brackets in order for this parser to return successfully. +/// +/// - **Syntax:** `brackets!(CONTENT)` +/// - **Output:** `(token::Bracket, CONTENT)` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::Expr; +/// use syn::token::Bracket; +/// +/// /// Parses an expression inside of brackets. +/// /// +/// /// Example: `[1 + 1]` +/// named!(expr_paren -> (Bracket, Expr), brackets!(syn!(Expr))); +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! brackets { + ($i:expr, $submac:ident!( $($args:tt)* )) => { + $crate::token::Bracket::parse($i, |i| $submac!(i, $($args)*)) + }; + + ($i:expr, $f:expr) => { + brackets!($i, call!($f)); + }; +} + +/// Parse inside of `{` `}` curly braces. +/// +/// This macro parses a set of balanced braces and invokes a sub-parser on the +/// content inside. The sub-parser is required to consume all tokens within the +/// braces in order for this parser to return successfully. +/// +/// - **Syntax:** `braces!(CONTENT)` +/// - **Output:** `(token::Brace, CONTENT)` +/// +/// ```rust +/// #[macro_use] +/// extern crate syn; +/// +/// use syn::Expr; +/// use syn::token::Brace; +/// +/// /// Parses an expression inside of braces. +/// /// +/// /// Example: `{1 + 1}` +/// named!(expr_paren -> (Brace, Expr), braces!(syn!(Expr))); +/// # +/// # fn main() {} +/// ``` +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[macro_export] +macro_rules! braces { + ($i:expr, $submac:ident!( $($args:tt)* )) => { + $crate::token::Brace::parse($i, |i| $submac!(i, $($args)*)) + }; + + ($i:expr, $f:expr) => { + braces!($i, call!($f)); + }; +} + +// Not public API. +#[doc(hidden)] +#[macro_export] +macro_rules! grouped { + ($i:expr, $submac:ident!( $($args:tt)* )) => { + $crate::token::Group::parse($i, |i| $submac!(i, $($args)*)) + }; + + ($i:expr, $f:expr) => { + grouped!($i, call!($f)); + }; +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/path.rs cargo-0.26.0/vendor/syn-0.13.1/src/path.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/path.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/path.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,572 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use punctuated::Punctuated; +use super::*; + +ast_struct! { + /// A path at which a named item is exported: `std::collections::HashMap`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct Path { + pub leading_colon: Option<Token![::]>, + pub segments: Punctuated<PathSegment, Token![::]>, + } +} + +impl Path { + pub fn global(&self) -> bool { + self.leading_colon.is_some() + } +} + +/// A helper for printing a self-type qualified path as tokens. +/// +/// ```rust +/// extern crate syn; +/// extern crate quote; +/// +/// use syn::{QSelf, Path, PathTokens}; +/// use quote::{Tokens, ToTokens}; +/// +/// struct MyNode { +/// qself: Option<QSelf>, +/// path: Path, +/// } +/// +/// impl ToTokens for MyNode { +/// fn to_tokens(&self, tokens: &mut Tokens) { +/// PathTokens(&self.qself, &self.path).to_tokens(tokens); +/// } +/// } +/// # +/// # fn main() {} +/// ``` +/// +/// *This type is available if Syn is built with the `"derive"` or `"full"` +/// feature and the `"printing"` feature.* +#[cfg(feature = "printing")] +#[cfg_attr(feature = "extra-traits", derive(Debug, Eq, PartialEq, Hash))] +#[cfg_attr(feature = "clone-impls", derive(Clone))] +pub struct PathTokens<'a>(pub &'a Option<QSelf>, pub &'a Path); + +impl<T> From<T> for Path +where + T: Into<PathSegment>, +{ + fn from(segment: T) -> Self { + let mut path = Path { + leading_colon: None, + segments: Punctuated::new(), + }; + path.segments.push_value(segment.into()); + path + } +} + +ast_struct! { + /// A segment of a path together with any path arguments on that segment. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct PathSegment { + pub ident: Ident, + pub arguments: PathArguments, + } +} + +impl<T> From<T> for PathSegment +where + T: Into<Ident>, +{ + fn from(ident: T) -> Self { + PathSegment { + ident: ident.into(), + arguments: PathArguments::None, + } + } +} + +ast_enum! { + /// Angle bracketed or parenthesized arguments of a path segment. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// ## Angle bracketed + /// + /// The `<'a, T>` in `std::slice::iter<'a, T>`. + /// + /// ## Parenthesized + /// + /// The `(A, B) -> C` in `Fn(A, B) -> C`. + pub enum PathArguments { + None, + /// The `<'a, T>` in `std::slice::iter<'a, T>`. + AngleBracketed(AngleBracketedGenericArguments), + /// The `(A, B) -> C` in `Fn(A, B) -> C`. + Parenthesized(ParenthesizedGenericArguments), + } +} + +impl Default for PathArguments { + fn default() -> Self { + PathArguments::None + } +} + +impl PathArguments { + pub fn is_empty(&self) -> bool { + match *self { + PathArguments::None => true, + PathArguments::AngleBracketed(ref bracketed) => bracketed.args.is_empty(), + PathArguments::Parenthesized(_) => false, + } + } +} + +ast_enum! { + /// An individual generic argument, like `'a`, `T`, or `Item = T`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub enum GenericArgument { + /// A lifetime argument. + Lifetime(Lifetime), + /// A type argument. + Type(Type), + /// A binding (equality constraint) on an associated type: the `Item = + /// u8` in `Iterator<Item = u8>`. + Binding(Binding), + /// A const expression. Must be inside of a block. + /// + /// NOTE: Identity expressions are represented as Type arguments, as + /// they are indistinguishable syntactically. + Const(Expr), + } +} + +ast_struct! { + /// Angle bracketed arguments of a path segment: the `<K, V>` in `HashMap<K, + /// V>`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct AngleBracketedGenericArguments { + pub colon2_token: Option<Token![::]>, + pub lt_token: Token![<], + pub args: Punctuated<GenericArgument, Token![,]>, + pub gt_token: Token![>], + } +} + +ast_struct! { + /// A binding (equality constraint) on an associated type: `Item = u8`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct Binding { + pub ident: Ident, + pub eq_token: Token![=], + pub ty: Type, + } +} + +ast_struct! { + /// Arguments of a function path segment: the `(A, B) -> C` in `Fn(A,B) -> + /// C`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct ParenthesizedGenericArguments { + pub paren_token: token::Paren, + /// `(A, B)` + pub inputs: Punctuated<Type, Token![,]>, + /// `C` + pub output: ReturnType, + } +} + +ast_struct! { + /// The explicit Self type in a qualified path: the `T` in `<T as + /// Display>::fmt`. + /// + /// The actual path, including the trait and the associated item, is stored + /// separately. The `position` field represents the index of the associated + /// item qualified with this Self type. + /// + /// ```text + /// <Vec<T> as a::b::Trait>::AssociatedItem + /// ^~~~~~ ~~~~~~~~~~~~~~^ + /// ty position = 3 + /// + /// <Vec<T>>::AssociatedItem + /// ^~~~~~ ^ + /// ty position = 0 + /// ``` + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct QSelf { + pub lt_token: Token![<], + pub ty: Box<Type>, + pub position: usize, + pub as_token: Option<Token![as]>, + pub gt_token: Token![>], + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + use synom::Synom; + + impl Synom for Path { + named!(parse -> Self, do_parse!( + colon: option!(punct!(::)) >> + segments: call!(Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty) >> + cond_reduce!(segments.first().map_or(true, |seg| seg.value().ident != "dyn")) >> + (Path { + leading_colon: colon, + segments: segments, + }) + )); + + fn description() -> Option<&'static str> { + Some("path") + } + } + + #[cfg(not(feature = "full"))] + impl Synom for GenericArgument { + named!(parse -> Self, alt!( + call!(ty_no_eq_after) => { GenericArgument::Type } + | + syn!(Lifetime) => { GenericArgument::Lifetime } + | + syn!(Binding) => { GenericArgument::Binding } + )); + } + + #[cfg(feature = "full")] + impl Synom for GenericArgument { + named!(parse -> Self, alt!( + call!(ty_no_eq_after) => { GenericArgument::Type } + | + syn!(Lifetime) => { GenericArgument::Lifetime } + | + syn!(Binding) => { GenericArgument::Binding } + | + syn!(ExprLit) => { |l| GenericArgument::Const(Expr::Lit(l)) } + | + syn!(ExprBlock) => { |b| GenericArgument::Const(Expr::Block(b)) } + )); + + fn description() -> Option<&'static str> { + Some("generic argument") + } + } + + impl Synom for AngleBracketedGenericArguments { + named!(parse -> Self, do_parse!( + colon2: option!(punct!(::)) >> + lt: punct!(<) >> + args: call!(Punctuated::parse_terminated) >> + gt: punct!(>) >> + (AngleBracketedGenericArguments { + colon2_token: colon2, + lt_token: lt, + args: args, + gt_token: gt, + }) + )); + + fn description() -> Option<&'static str> { + Some("angle bracketed generic arguments") + } + } + + impl Synom for ParenthesizedGenericArguments { + named!(parse -> Self, do_parse!( + data: parens!(Punctuated::parse_terminated) >> + output: syn!(ReturnType) >> + (ParenthesizedGenericArguments { + paren_token: data.0, + inputs: data.1, + output: output, + }) + )); + + fn description() -> Option<&'static str> { + Some("parenthesized generic arguments: `Foo(A, B, ..) -> T`") + } + } + + impl Synom for PathSegment { + named!(parse -> Self, alt!( + do_parse!( + ident: syn!(Ident) >> + arguments: syn!(AngleBracketedGenericArguments) >> + (PathSegment { + ident: ident, + arguments: PathArguments::AngleBracketed(arguments), + }) + ) + | + mod_style_path_segment + )); + + fn description() -> Option<&'static str> { + Some("path segment") + } + } + + impl Synom for Binding { + named!(parse -> Self, do_parse!( + id: syn!(Ident) >> + eq: punct!(=) >> + ty: syn!(Type) >> + (Binding { + ident: id, + eq_token: eq, + ty: ty, + }) + )); + + fn description() -> Option<&'static str> { + Some("associated type binding") + } + } + + impl Path { + named!(pub parse_mod_style -> Self, do_parse!( + colon: option!(punct!(::)) >> + segments: call!(Punctuated::parse_separated_nonempty_with, + mod_style_path_segment) >> + (Path { + leading_colon: colon, + segments: segments, + }) + )); + } + + named!(mod_style_path_segment -> PathSegment, alt!( + syn!(Ident) => { Into::into } + | + keyword!(super) => { Into::into } + | + keyword!(self) => { Into::into } + | + keyword!(Self) => { Into::into } + | + keyword!(crate) => { Into::into } + )); + + named!(pub qpath -> (Option<QSelf>, Path), alt!( + map!(syn!(Path), |p| (None, p)) + | + do_parse!( + lt: punct!(<) >> + this: syn!(Type) >> + path: option!(tuple!(keyword!(as), syn!(Path))) >> + gt: punct!(>) >> + colon2: punct!(::) >> + rest: call!(Punctuated::parse_separated_nonempty) >> + ({ + let (pos, as_, path) = match path { + Some((as_, mut path)) => { + let pos = path.segments.len(); + path.segments.push_punct(colon2); + path.segments.extend(rest.into_pairs()); + (pos, Some(as_), path) + } + None => { + (0, None, Path { + leading_colon: Some(colon2), + segments: rest, + }) + } + }; + (Some(QSelf { + lt_token: lt, + ty: Box::new(this), + position: pos, + as_token: as_, + gt_token: gt, + }), path) + }) + ) + | + map!(keyword!(self), |s| (None, s.into())) + )); + + named!(pub ty_no_eq_after -> Type, do_parse!( + ty: syn!(Type) >> + not!(punct!(=)) >> + (ty) + )); +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use quote::{ToTokens, Tokens}; + + impl ToTokens for Path { + fn to_tokens(&self, tokens: &mut Tokens) { + self.leading_colon.to_tokens(tokens); + self.segments.to_tokens(tokens); + } + } + + impl ToTokens for PathSegment { + fn to_tokens(&self, tokens: &mut Tokens) { + self.ident.to_tokens(tokens); + self.arguments.to_tokens(tokens); + } + } + + impl ToTokens for PathArguments { + fn to_tokens(&self, tokens: &mut Tokens) { + match *self { + PathArguments::None => {} + PathArguments::AngleBracketed(ref arguments) => { + arguments.to_tokens(tokens); + } + PathArguments::Parenthesized(ref arguments) => { + arguments.to_tokens(tokens); + } + } + } + } + + impl ToTokens for GenericArgument { + #[cfg_attr(feature = "cargo-clippy", allow(match_same_arms))] + fn to_tokens(&self, tokens: &mut Tokens) { + match *self { + GenericArgument::Lifetime(ref lt) => lt.to_tokens(tokens), + GenericArgument::Type(ref ty) => ty.to_tokens(tokens), + GenericArgument::Binding(ref tb) => tb.to_tokens(tokens), + GenericArgument::Const(ref e) => match *e { + Expr::Lit(_) => e.to_tokens(tokens), + + // NOTE: We should probably support parsing blocks with only + // expressions in them without the full feature for const + // generics. + #[cfg(feature = "full")] + Expr::Block(_) => e.to_tokens(tokens), + + // ERROR CORRECTION: Add braces to make sure that the + // generated code is valid. + _ => token::Brace::default().surround(tokens, |tokens| { + e.to_tokens(tokens); + }), + }, + } + } + } + + impl ToTokens for AngleBracketedGenericArguments { + fn to_tokens(&self, tokens: &mut Tokens) { + self.colon2_token.to_tokens(tokens); + self.lt_token.to_tokens(tokens); + + // Print lifetimes before types and consts, all before bindings, + // regardless of their order in self.args. + // + // TODO: ordering rules for const arguments vs type arguments have + // not been settled yet. https://github.com/rust-lang/rust/issues/44580 + let mut trailing_or_empty = true; + for param in self.args.pairs() { + if let GenericArgument::Lifetime(_) = **param.value() { + param.to_tokens(tokens); + trailing_or_empty = param.punct().is_some(); + } + } + for param in self.args.pairs() { + match **param.value() { + GenericArgument::Type(_) | GenericArgument::Const(_) => { + if !trailing_or_empty { + <Token![,]>::default().to_tokens(tokens); + } + param.to_tokens(tokens); + trailing_or_empty = param.punct().is_some(); + } + GenericArgument::Lifetime(_) | GenericArgument::Binding(_) => {} + } + } + for param in self.args.pairs() { + if let GenericArgument::Binding(_) = **param.value() { + if !trailing_or_empty { + <Token![,]>::default().to_tokens(tokens); + trailing_or_empty = true; + } + param.to_tokens(tokens); + } + } + + self.gt_token.to_tokens(tokens); + } + } + + impl ToTokens for Binding { + fn to_tokens(&self, tokens: &mut Tokens) { + self.ident.to_tokens(tokens); + self.eq_token.to_tokens(tokens); + self.ty.to_tokens(tokens); + } + } + + impl ToTokens for ParenthesizedGenericArguments { + fn to_tokens(&self, tokens: &mut Tokens) { + self.paren_token.surround(tokens, |tokens| { + self.inputs.to_tokens(tokens); + }); + self.output.to_tokens(tokens); + } + } + + impl<'a> ToTokens for PathTokens<'a> { + fn to_tokens(&self, tokens: &mut Tokens) { + let qself = match *self.0 { + Some(ref qself) => qself, + None => return self.1.to_tokens(tokens), + }; + qself.lt_token.to_tokens(tokens); + qself.ty.to_tokens(tokens); + + // XXX: Gross. + let pos = if qself.position > 0 && qself.position >= self.1.segments.len() { + self.1.segments.len() - 1 + } else { + qself.position + }; + let mut segments = self.1.segments.pairs(); + if pos > 0 { + TokensOrDefault(&qself.as_token).to_tokens(tokens); + self.1.leading_colon.to_tokens(tokens); + for (i, segment) in segments.by_ref().take(pos).enumerate() { + if i + 1 == pos { + segment.value().to_tokens(tokens); + qself.gt_token.to_tokens(tokens); + segment.punct().to_tokens(tokens); + } else { + segment.to_tokens(tokens); + } + } + } else { + qself.gt_token.to_tokens(tokens); + self.1.leading_colon.to_tokens(tokens); + } + for segment in segments { + segment.to_tokens(tokens); + } + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/punctuated.rs cargo-0.26.0/vendor/syn-0.13.1/src/punctuated.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/punctuated.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/punctuated.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,699 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A punctuated sequence of syntax tree nodes separated by punctuation. +//! +//! Lots of things in Rust are punctuated sequences. +//! +//! - The fields of a struct are `Punctuated<Field, Token![,]>`. +//! - The segments of a path are `Punctuated<PathSegment, Token![::]>`. +//! - The bounds on a generic parameter are `Punctuated<TypeParamBound, Token![+]>`. +//! - The arguments to a function call are `Punctuated<Expr, Token![,]>`. +//! +//! This module provides a common representation for these punctuated sequences +//! in the form of the [`Punctuated<T, P>`] type. We store a vector of pairs of +//! syntax tree node + punctuation, where every node in the sequence is followed +//! by punctuation except for possibly the final one. +//! +//! [`Punctuated<T, P>`]: struct.Punctuated.html +//! +//! ```text +//! a_function_call(arg1, arg2, arg3); +//! ^^^^^ ~~~~~ ^^^^ +//! ``` + +#[cfg(any(feature = "full", feature = "derive"))] +use std::iter; +use std::iter::FromIterator; +use std::ops::{Index, IndexMut}; +use std::slice; +use std::vec; +#[cfg(feature = "extra-traits")] +use std::fmt::{self, Debug}; + +#[cfg(feature = "parsing")] +use synom::{Synom, PResult}; +#[cfg(feature = "parsing")] +use buffer::Cursor; +#[cfg(feature = "parsing")] +use parse_error; + +/// A punctuated sequence of syntax tree nodes of type `T` separated by +/// punctuation of type `P`. +/// +/// Refer to the [module documentation] for details about punctuated sequences. +/// +/// [module documentation]: index.html +#[cfg_attr(feature = "extra-traits", derive(Eq, PartialEq, Hash))] +#[cfg_attr(feature = "clone-impls", derive(Clone))] +pub struct Punctuated<T, P> { + inner: Vec<(T, Option<P>)>, +} + +impl<T, P> Punctuated<T, P> { + /// Creates an empty punctuated sequence. + pub fn new() -> Punctuated<T, P> { + Punctuated { inner: Vec::new() } + } + + /// Determines whether this punctuated sequence is empty, meaning it + /// contains no syntax tree nodes or punctuation. + pub fn is_empty(&self) -> bool { + self.inner.len() == 0 + } + + /// Returns the number of syntax tree nodes in this punctuated sequence. + /// + /// This is the number of nodes of type `T`, not counting the punctuation of + /// type `P`. + pub fn len(&self) -> usize { + self.inner.len() + } + + /// Borrows the first punctuated pair in this sequence. + pub fn first(&self) -> Option<Pair<&T, &P>> { + self.inner.first().map(|&(ref t, ref d)| match *d { + Some(ref d) => Pair::Punctuated(t, d), + None => Pair::End(t), + }) + } + + /// Borrows the last punctuated pair in this sequence. + pub fn last(&self) -> Option<Pair<&T, &P>> { + self.inner.last().map(|&(ref t, ref d)| match *d { + Some(ref d) => Pair::Punctuated(t, d), + None => Pair::End(t), + }) + } + + /// Mutably borrows the last punctuated pair in this sequence. + pub fn last_mut(&mut self) -> Option<Pair<&mut T, &mut P>> { + self.inner + .last_mut() + .map(|&mut (ref mut t, ref mut d)| match *d { + Some(ref mut d) => Pair::Punctuated(t, d), + None => Pair::End(t), + }) + } + + /// Returns an iterator over borrowed syntax tree nodes of type `&T`. + pub fn iter(&self) -> Iter<T> { + Iter { + inner: Box::new(PrivateIter { + inner: self.inner.iter(), + }), + } + } + + /// Returns an iterator over mutably borrowed syntax tree nodes of type + /// `&mut T`. + pub fn iter_mut(&mut self) -> IterMut<T> { + IterMut { + inner: Box::new(PrivateIterMut { + inner: self.inner.iter_mut(), + }), + } + } + + /// Returns an iterator over the contents of this sequence as borrowed + /// punctuated pairs. + pub fn pairs(&self) -> Pairs<T, P> { + Pairs { + inner: self.inner.iter(), + } + } + + /// Returns an iterator over the contents of this sequence as mutably + /// borrowed punctuated pairs. + pub fn pairs_mut(&mut self) -> PairsMut<T, P> { + PairsMut { + inner: self.inner.iter_mut(), + } + } + + /// Returns an iterator over the contents of this sequence as owned + /// punctuated pairs. + pub fn into_pairs(self) -> IntoPairs<T, P> { + IntoPairs { + inner: self.inner.into_iter(), + } + } + + /// Appends a syntax tree node onto the end of this punctuated sequence. The + /// sequence must previously have a trailing punctuation. + /// + /// Use [`push`] instead if the punctuated sequence may or may not already + /// have trailing punctuation. + /// + /// [`push`]: #method.push + /// + /// # Panics + /// + /// Panics if the sequence does not already have a trailing punctuation when + /// this method is called. + pub fn push_value(&mut self, value: T) { + assert!(self.empty_or_trailing()); + self.inner.push((value, None)); + } + + /// Appends a trailing punctuation onto the end of this punctuated sequence. + /// The sequence must be non-empty and must not already have trailing + /// punctuation. + /// + /// # Panics + /// + /// Panics if the sequence is empty or already has a trailing punctuation. + pub fn push_punct(&mut self, punctuation: P) { + assert!(!self.is_empty()); + let last = self.inner.last_mut().unwrap(); + assert!(last.1.is_none()); + last.1 = Some(punctuation); + } + + /// Removes the last punctuated pair from this sequence, or `None` if the + /// sequence is empty. + pub fn pop(&mut self) -> Option<Pair<T, P>> { + self.inner.pop().map(|(t, d)| Pair::new(t, d)) + } + + /// Determines whether this punctuated sequence ends with a trailing + /// punctuation. + pub fn trailing_punct(&self) -> bool { + self.inner + .last() + .map(|last| last.1.is_some()) + .unwrap_or(false) + } + + /// Returns true if either this `Punctuated` is empty, or it has a trailing + /// punctuation. + /// + /// Equivalent to `punctuated.is_empty() || punctuated.trailing_punct()`. + pub fn empty_or_trailing(&self) -> bool { + self.inner + .last() + .map(|last| last.1.is_some()) + .unwrap_or(true) + } +} + +impl<T, P> Punctuated<T, P> +where + P: Default, +{ + /// Appends a syntax tree node onto the end of this punctuated sequence. + /// + /// If there is not a trailing punctuation in this sequence when this method + /// is called, the default value of punctuation type `P` is inserted before + /// the given value of type `T`. + pub fn push(&mut self, value: T) { + if !self.empty_or_trailing() { + self.push_punct(Default::default()); + } + self.push_value(value); + } + + /// Inserts an element at position `index`. + /// + /// # Panics + /// + /// Panics if `index` is greater than the number of elements previously in + /// this punctuated sequence. + pub fn insert(&mut self, index: usize, value: T) { + assert!(index <= self.len()); + + if index == self.len() { + self.push(value); + } else { + self.inner.insert(index, (value, Some(Default::default()))); + } + } +} + +#[cfg(feature = "extra-traits")] +impl<T: Debug, P: Debug> Debug for Punctuated<T, P> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt(f) + } +} + +impl<T, P> FromIterator<T> for Punctuated<T, P> +where + P: Default, +{ + fn from_iter<I: IntoIterator<Item = T>>(i: I) -> Self { + let mut ret = Punctuated::new(); + ret.extend(i); + ret + } +} + +impl<T, P> Extend<T> for Punctuated<T, P> +where + P: Default, +{ + fn extend<I: IntoIterator<Item = T>>(&mut self, i: I) { + for value in i { + self.push(value); + } + } +} + +impl<T, P> FromIterator<Pair<T, P>> for Punctuated<T, P> { + fn from_iter<I: IntoIterator<Item = Pair<T, P>>>(i: I) -> Self { + let mut ret = Punctuated::new(); + ret.extend(i); + ret + } +} + +impl<T, P> Extend<Pair<T, P>> for Punctuated<T, P> { + fn extend<I: IntoIterator<Item = Pair<T, P>>>(&mut self, i: I) { + for pair in i { + match pair { + Pair::Punctuated(a, b) => self.inner.push((a, Some(b))), + Pair::End(a) => self.inner.push((a, None)), + } + } + } +} + +impl<T, P> IntoIterator for Punctuated<T, P> { + type Item = T; + type IntoIter = IntoIter<T, P>; + + fn into_iter(self) -> Self::IntoIter { + IntoIter { + inner: self.inner.into_iter(), + } + } +} + +impl<'a, T, P> IntoIterator for &'a Punctuated<T, P> { + type Item = &'a T; + type IntoIter = Iter<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + Punctuated::iter(self) + } +} + +impl<'a, T, P> IntoIterator for &'a mut Punctuated<T, P> { + type Item = &'a mut T; + type IntoIter = IterMut<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + Punctuated::iter_mut(self) + } +} + +impl<T, P> Default for Punctuated<T, P> { + fn default() -> Self { + Punctuated::new() + } +} + +/// An iterator over borrowed pairs of type `Pair<&T, &P>`. +/// +/// Refer to the [module documentation] for details about punctuated sequences. +/// +/// [module documentation]: index.html +pub struct Pairs<'a, T: 'a, P: 'a> { + inner: slice::Iter<'a, (T, Option<P>)>, +} + +impl<'a, T, P> Iterator for Pairs<'a, T, P> { + type Item = Pair<&'a T, &'a P>; + + fn next(&mut self) -> Option<Self::Item> { + self.inner.next().map(|pair| match pair.1 { + Some(ref p) => Pair::Punctuated(&pair.0, p), + None => Pair::End(&pair.0), + }) + } +} + +/// An iterator over mutably borrowed pairs of type `Pair<&mut T, &mut P>`. +/// +/// Refer to the [module documentation] for details about punctuated sequences. +/// +/// [module documentation]: index.html +pub struct PairsMut<'a, T: 'a, P: 'a> { + inner: slice::IterMut<'a, (T, Option<P>)>, +} + +impl<'a, T, P> Iterator for PairsMut<'a, T, P> { + type Item = Pair<&'a mut T, &'a mut P>; + + fn next(&mut self) -> Option<Self::Item> { + self.inner.next().map(|pair| match pair.1 { + Some(ref mut p) => Pair::Punctuated(&mut pair.0, p), + None => Pair::End(&mut pair.0), + }) + } +} + +/// An iterator over owned pairs of type `Pair<T, P>`. +/// +/// Refer to the [module documentation] for details about punctuated sequences. +/// +/// [module documentation]: index.html +pub struct IntoPairs<T, P> { + inner: vec::IntoIter<(T, Option<P>)>, +} + +impl<T, P> Iterator for IntoPairs<T, P> { + type Item = Pair<T, P>; + + fn next(&mut self) -> Option<Self::Item> { + self.inner.next().map(|pair| match pair.1 { + Some(p) => Pair::Punctuated(pair.0, p), + None => Pair::End(pair.0), + }) + } +} + +/// An iterator over owned values of type `T`. +/// +/// Refer to the [module documentation] for details about punctuated sequences. +/// +/// [module documentation]: index.html +pub struct IntoIter<T, P> { + inner: vec::IntoIter<(T, Option<P>)>, +} + +impl<T, P> Iterator for IntoIter<T, P> { + type Item = T; + + fn next(&mut self) -> Option<Self::Item> { + self.inner.next().map(|pair| pair.0) + } +} + +/// An iterator over borrowed values of type `&T`. +/// +/// Refer to the [module documentation] for details about punctuated sequences. +/// +/// [module documentation]: index.html +pub struct Iter<'a, T: 'a> { + inner: Box<Iterator<Item = &'a T> + 'a>, +} + +struct PrivateIter<'a, T: 'a, P: 'a> { + inner: slice::Iter<'a, (T, Option<P>)>, +} + +#[cfg(any(feature = "full", feature = "derive"))] +impl<'a, T> Iter<'a, T> { + // Not public API. + #[doc(hidden)] + pub fn private_empty() -> Self { + Iter { + inner: Box::new(iter::empty()), + } + } +} + +impl<'a, T> Iterator for Iter<'a, T> { + type Item = &'a T; + + fn next(&mut self) -> Option<Self::Item> { + self.inner.next() + } +} + +impl<'a, T, P> Iterator for PrivateIter<'a, T, P> { + type Item = &'a T; + + fn next(&mut self) -> Option<Self::Item> { + self.inner.next().map(|pair| &pair.0) + } +} + +/// An iterator over mutably borrowed values of type `&mut T`. +/// +/// Refer to the [module documentation] for details about punctuated sequences. +/// +/// [module documentation]: index.html +pub struct IterMut<'a, T: 'a> { + inner: Box<Iterator<Item = &'a mut T> + 'a>, +} + +struct PrivateIterMut<'a, T: 'a, P: 'a> { + inner: slice::IterMut<'a, (T, Option<P>)>, +} + +impl<'a, T> Iterator for IterMut<'a, T> { + type Item = &'a mut T; + + fn next(&mut self) -> Option<Self::Item> { + self.inner.next() + } +} + +impl<'a, T, P> Iterator for PrivateIterMut<'a, T, P> { + type Item = &'a mut T; + + fn next(&mut self) -> Option<Self::Item> { + self.inner.next().map(|pair| &mut pair.0) + } +} + +/// A single syntax tree node of type `T` followed by its trailing punctuation +/// of type `P` if any. +/// +/// Refer to the [module documentation] for details about punctuated sequences. +/// +/// [module documentation]: index.html +pub enum Pair<T, P> { + Punctuated(T, P), + End(T), +} + +impl<T, P> Pair<T, P> { + /// Extracts the syntax tree node from this punctuated pair, discarding the + /// following punctuation. + pub fn into_value(self) -> T { + match self { + Pair::Punctuated(t, _) | Pair::End(t) => t, + } + } + + /// Borrows the syntax tree node from this punctuated pair. + pub fn value(&self) -> &T { + match *self { + Pair::Punctuated(ref t, _) | Pair::End(ref t) => t, + } + } + + /// Mutably borrows the syntax tree node from this punctuated pair. + pub fn value_mut(&mut self) -> &mut T { + match *self { + Pair::Punctuated(ref mut t, _) | Pair::End(ref mut t) => t, + } + } + + /// Borrows the punctuation from this punctuated pair, unless this pair is + /// the final one and there is no trailing punctuation. + pub fn punct(&self) -> Option<&P> { + match *self { + Pair::Punctuated(_, ref d) => Some(d), + Pair::End(_) => None, + } + } + + /// Creates a punctuated pair out of a syntax tree node and an optional + /// following punctuation. + pub fn new(t: T, d: Option<P>) -> Self { + match d { + Some(d) => Pair::Punctuated(t, d), + None => Pair::End(t), + } + } + + /// Produces this punctuated pair as a tuple of syntax tree node and + /// optional following punctuation. + pub fn into_tuple(self) -> (T, Option<P>) { + match self { + Pair::Punctuated(t, d) => (t, Some(d)), + Pair::End(t) => (t, None), + } + } +} + +impl<T, P> Index<usize> for Punctuated<T, P> { + type Output = T; + + fn index(&self, index: usize) -> &Self::Output { + &self.inner[index].0 + } +} + +impl<T, P> IndexMut<usize> for Punctuated<T, P> { + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + &mut self.inner[index].0 + } +} + +#[cfg(feature = "parsing")] +impl<T, P> Punctuated<T, P> +where + T: Synom, + P: Synom, +{ + /// Parse **zero or more** syntax tree nodes with punctuation in between and + /// **no trailing** punctuation. + pub fn parse_separated(input: Cursor) -> PResult<Self> { + Self::parse_separated_with(input, T::parse) + } + + /// Parse **one or more** syntax tree nodes with punctuation in bewteen and + /// **no trailing** punctuation. + /// allowing trailing punctuation. + pub fn parse_separated_nonempty(input: Cursor) -> PResult<Self> { + Self::parse_separated_nonempty_with(input, T::parse) + } + + /// Parse **zero or more** syntax tree nodes with punctuation in between and + /// **optional trailing** punctuation. + pub fn parse_terminated(input: Cursor) -> PResult<Self> { + Self::parse_terminated_with(input, T::parse) + } + + /// Parse **one or more** syntax tree nodes with punctuation in between and + /// **optional trailing** punctuation. + pub fn parse_terminated_nonempty(input: Cursor) -> PResult<Self> { + Self::parse_terminated_nonempty_with(input, T::parse) + } +} + +#[cfg(feature = "parsing")] +impl<T, P> Punctuated<T, P> +where + P: Synom, +{ + /// Parse **zero or more** syntax tree nodes using the given parser with + /// punctuation in between and **no trailing** punctuation. + pub fn parse_separated_with( + input: Cursor, + parse: fn(Cursor) -> PResult<T>, + ) -> PResult<Self> { + Self::parse(input, parse, false) + } + + /// Parse **one or more** syntax tree nodes using the given parser with + /// punctuation in between and **no trailing** punctuation. + pub fn parse_separated_nonempty_with( + input: Cursor, + parse: fn(Cursor) -> PResult<T>, + ) -> PResult<Self> { + match Self::parse(input, parse, false) { + Ok((ref b, _)) if b.is_empty() => parse_error(), + other => other, + } + } + + /// Parse **zero or more** syntax tree nodes using the given parser with + /// punctuation in between and **optional trailing** punctuation. + pub fn parse_terminated_with( + input: Cursor, + parse: fn(Cursor) -> PResult<T>, + ) -> PResult<Self> { + Self::parse(input, parse, true) + } + + /// Parse **one or more** syntax tree nodes using the given parser with + /// punctuation in between and **optional trailing** punctuation. + pub fn parse_terminated_nonempty_with( + input: Cursor, + parse: fn(Cursor) -> PResult<T>, + ) -> PResult<Self> { + match Self::parse(input, parse, true) { + Ok((ref b, _)) if b.is_empty() => parse_error(), + other => other, + } + } + + fn parse( + mut input: Cursor, + parse: fn(Cursor) -> PResult<T>, + terminated: bool, + ) -> PResult<Self> { + let mut res = Punctuated::new(); + + // get the first element + match parse(input) { + Err(_) => Ok((res, input)), + Ok((o, i)) => { + if i == input { + return parse_error(); + } + input = i; + res.push_value(o); + + // get the separator first + while let Ok((s, i2)) = P::parse(input) { + if i2 == input { + break; + } + + // get the element next + if let Ok((o3, i3)) = parse(i2) { + if i3 == i2 { + break; + } + res.push_punct(s); + res.push_value(o3); + input = i3; + } else { + break; + } + } + if terminated { + if let Ok((sep, after)) = P::parse(input) { + res.push_punct(sep); + input = after; + } + } + Ok((res, input)) + } + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use quote::{ToTokens, Tokens}; + + impl<T, P> ToTokens for Punctuated<T, P> + where + T: ToTokens, + P: ToTokens, + { + fn to_tokens(&self, tokens: &mut Tokens) { + tokens.append_all(self.pairs()) + } + } + + impl<T, P> ToTokens for Pair<T, P> + where + T: ToTokens, + P: ToTokens, + { + fn to_tokens(&self, tokens: &mut Tokens) { + match *self { + Pair::Punctuated(ref a, ref b) => { + a.to_tokens(tokens); + b.to_tokens(tokens); + } + Pair::End(ref a) => a.to_tokens(tokens), + } + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/spanned.rs cargo-0.26.0/vendor/syn-0.13.1/src/spanned.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/spanned.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/spanned.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,144 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A trait that can provide the `Span` of the complete contents of a syntax +//! tree node. +//! +//! *This module is available if Syn is built with both the `"parsing"` and +//! `"printing"` features.* +//! +//! # Example +//! +//! Suppose in a procedural macro we have a [`Type`] that we want to assert +//! implements the [`Sync`] trait. Maybe this is the type of one of the fields +//! of a struct for which we are deriving a trait implementation, and we need to +//! be able to pass a reference to one of those fields across threads. +//! +//! [`Type`]: ../enum.Type.html +//! [`Sync`]: https://doc.rust-lang.org/std/marker/trait.Sync.html +//! +//! If the field type does *not* implement `Sync` as required, we want the +//! compiler to report an error pointing out exactly which type it was. +//! +//! The following macro code takes a variable `ty` of type `Type` and produces a +//! static assertion that `Sync` is implemented for that type. +//! +//! ``` +//! #[macro_use] +//! extern crate quote; +//! +//! extern crate syn; +//! extern crate proc_macro; +//! extern crate proc_macro2; +//! +//! use syn::Type; +//! use syn::spanned::Spanned; +//! use proc_macro::TokenStream; +//! use proc_macro2::Span; +//! +//! # const IGNORE_TOKENS: &str = stringify! { +//! #[proc_macro_derive(MyMacro)] +//! # }; +//! pub fn my_macro(input: TokenStream) -> TokenStream { +//! # let ty = get_a_type(); +//! /* ... */ +//! +//! let assert_sync = quote_spanned! {ty.span()=> +//! struct _AssertSync where #ty: Sync; +//! }; +//! +//! /* ... */ +//! # input +//! } +//! # +//! # fn get_a_type() -> Type { +//! # unimplemented!() +//! # } +//! # +//! # fn main() {} +//! ``` +//! +//! By inserting this `assert_sync` fragment into the output code generated by +//! our macro, the user's code will fail to compile if `ty` does not implement +//! `Sync`. The errors they would see look like the following. +//! +//! ```text +//! error[E0277]: the trait bound `*const i32: std::marker::Sync` is not satisfied +//! --> src/main.rs:10:21 +//! | +//! 10 | bad_field: *const i32, +//! | ^^^^^^^^^^ `*const i32` cannot be shared between threads safely +//! ``` +//! +//! In this technique, using the `Type`'s span for the error message makes the +//! error appear in the correct place underlining the right type. + +use proc_macro2::{Span, TokenStream}; +use quote::{ToTokens, Tokens}; + +/// A trait that can provide the `Span` of the complete contents of a syntax +/// tree node. +/// +/// This trait is automatically implemented for all types that implement +/// [`ToTokens`] from the `quote` crate. +/// +/// [`ToTokens`]: https://docs.rs/quote/0.4/quote/trait.ToTokens.html +/// +/// See the [module documentation] for an example. +/// +/// [module documentation]: index.html +/// +/// *This trait is available if Syn is built with both the `"parsing"` and +/// `"printing"` features.* +pub trait Spanned { + /// Returns a `Span` covering the complete contents of this syntax tree + /// node, or [`Span::call_site()`] if this node is empty. + /// + /// [`Span::call_site()`]: https://docs.rs/proc-macro2/0.2/proc_macro2/struct.Span.html#method.call_site + fn span(&self) -> Span; +} + +impl<T> Spanned for T +where + T: ToTokens, +{ + #[cfg(procmacro2_semver_exempt)] + fn span(&self) -> Span { + let mut tokens = Tokens::new(); + self.to_tokens(&mut tokens); + let token_stream = TokenStream::from(tokens); + let mut iter = token_stream.into_iter(); + let mut span = match iter.next() { + Some(tt) => tt.span(), + None => { + return Span::call_site(); + } + }; + for tt in iter { + if let Some(joined) = span.join(tt.span()) { + span = joined; + } + } + span + } + + #[cfg(not(procmacro2_semver_exempt))] + fn span(&self) -> Span { + let mut tokens = Tokens::new(); + self.to_tokens(&mut tokens); + let token_stream = TokenStream::from(tokens); + let mut iter = token_stream.into_iter(); + + // We can't join spans without procmacro2_semver_exempt so just grab the + // first one. + match iter.next() { + Some(tt) => tt.span(), + None => Span::call_site(), + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/synom.rs cargo-0.26.0/vendor/syn-0.13.1/src/synom.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/synom.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/synom.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,263 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Parsing interface for parsing a token stream into a syntax tree node. +//! +//! Parsing in Syn is built on parser functions that take in a [`Cursor`] and +//! produce a [`PResult<T>`] where `T` is some syntax tree node. `Cursor` is a +//! cheaply copyable cursor over a range of tokens in a token stream, and +//! `PResult` is a result that packages together a parsed syntax tree node `T` +//! with a stream of remaining unparsed tokens after `T` represented as another +//! `Cursor`, or a [`ParseError`] if parsing failed. +//! +//! [`Cursor`]: ../buffer/index.html +//! [`PResult<T>`]: type.PResult.html +//! [`ParseError`]: struct.ParseError.html +//! +//! This `Cursor`- and `PResult`-based interface is convenient for parser +//! combinators and parser implementations, but not necessarily when you just +//! have some tokens that you want to parse. For that we expose the following +//! two entry points. +//! +//! ## The `syn::parse*` functions +//! +//! The [`syn::parse`], [`syn::parse2`], and [`syn::parse_str`] functions serve +//! as an entry point for parsing syntax tree nodes that can be parsed in an +//! obvious default way. These functions can return any syntax tree node that +//! implements the [`Synom`] trait, which includes most types in Syn. +//! +//! [`syn::parse`]: ../fn.parse.html +//! [`syn::parse2`]: ../fn.parse2.html +//! [`syn::parse_str`]: ../fn.parse_str.html +//! [`Synom`]: trait.Synom.html +//! +//! ``` +//! use syn::Type; +//! +//! # fn run_parser() -> Result<(), syn::synom::ParseError> { +//! let t: Type = syn::parse_str("std::collections::HashMap<String, Value>")?; +//! # Ok(()) +//! # } +//! # +//! # fn main() { +//! # run_parser().unwrap(); +//! # } +//! ``` +//! +//! The [`parse_quote!`] macro also uses this approach. +//! +//! [`parse_quote!`]: ../macro.parse_quote.html +//! +//! ## The `Parser` trait +//! +//! Some types can be parsed in several ways depending on context. For example +//! an [`Attribute`] can be either "outer" like `#[...]` or "inner" like +//! `#![...]` and parsing the wrong one would be a bug. Similarly [`Punctuated`] +//! may or may not allow trailing punctuation, and parsing it the wrong way +//! would either reject valid input or accept invalid input. +//! +//! [`Attribute`]: ../struct.Attribute.html +//! [`Punctuated`]: ../punctuated/index.html +//! +//! The `Synom` trait is not implemented in these cases because there is no good +//! behavior to consider the default. +//! +//! ```ignore +//! // Can't parse `Punctuated` without knowing whether trailing punctuation +//! // should be allowed in this context. +//! let path: Punctuated<PathSegment, Token![::]> = syn::parse(tokens)?; +//! ``` +//! +//! In these cases the types provide a choice of parser functions rather than a +//! single `Synom` implementation, and those parser functions can be invoked +//! through the [`Parser`] trait. +//! +//! [`Parser`]: trait.Parser.html +//! +//! ``` +//! # #[macro_use] +//! # extern crate syn; +//! # +//! # extern crate proc_macro2; +//! # use proc_macro2::TokenStream; +//! # +//! use syn::synom::Parser; +//! use syn::punctuated::Punctuated; +//! use syn::{PathSegment, Expr, Attribute}; +//! +//! # fn run_parsers() -> Result<(), syn::synom::ParseError> { +//! # let tokens = TokenStream::empty().into(); +//! // Parse a nonempty sequence of path segments separated by `::` punctuation +//! // with no trailing punctuation. +//! let parser = Punctuated::<PathSegment, Token![::]>::parse_separated_nonempty; +//! let path = parser.parse(tokens)?; +//! +//! # let tokens = TokenStream::empty().into(); +//! // Parse a possibly empty sequence of expressions terminated by commas with +//! // an optional trailing punctuation. +//! let parser = Punctuated::<Expr, Token![,]>::parse_terminated; +//! let args = parser.parse(tokens)?; +//! +//! # let tokens = TokenStream::empty().into(); +//! // Parse zero or more outer attributes but not inner attributes. +//! named!(outer_attrs -> Vec<Attribute>, many0!(Attribute::parse_outer)); +//! let attrs = outer_attrs.parse(tokens)?; +//! # +//! # Ok(()) +//! # } +//! # +//! # fn main() {} +//! ``` +//! +//! # Implementing a parser function +//! +//! Parser functions are usually implemented using the [`nom`]-style parser +//! combinator macros provided by Syn, but may also be implemented without +//! macros be using the low-level [`Cursor`] API directly. +//! +//! [`nom`]: https://github.com/Geal/nom +//! +//! The following parser combinator macros are available and a `Synom` parsing +//! example is provided for each one. +//! +//! - [`alt!`](../macro.alt.html) +//! - [`braces!`](../macro.braces.html) +//! - [`brackets!`](../macro.brackets.html) +//! - [`call!`](../macro.call.html) +//! - [`cond!`](../macro.cond.html) +//! - [`cond_reduce!`](../macro.cond_reduce.html) +//! - [`do_parse!`](../macro.do_parse.html) +//! - [`epsilon!`](../macro.epsilon.html) +//! - [`input_end!`](../macro.input_end.html) +//! - [`keyword!`](../macro.keyword.html) +//! - [`many0!`](../macro.many0.html) +//! - [`map!`](../macro.map.html) +//! - [`not!`](../macro.not.html) +//! - [`option!`](../macro.option.html) +//! - [`parens!`](../macro.parens.html) +//! - [`punct!`](../macro.punct.html) +//! - [`reject!`](../macro.reject.html) +//! - [`switch!`](../macro.switch.html) +//! - [`syn!`](../macro.syn.html) +//! - [`tuple!`](../macro.tuple.html) +//! - [`value!`](../macro.value.html) +//! +//! *This module is available if Syn is built with the `"parsing"` feature.* + +#[cfg(feature = "proc-macro")] +use proc_macro; +use proc_macro2; + +pub use error::{PResult, ParseError}; + +use buffer::{Cursor, TokenBuffer}; + +/// Parsing interface implemented by all types that can be parsed in a default +/// way from a token stream. +/// +/// Refer to the [module documentation] for details about parsing in Syn. +/// +/// [module documentation]: index.html +/// +/// *This trait is available if Syn is built with the `"parsing"` feature.* +pub trait Synom: Sized { + fn parse(input: Cursor) -> PResult<Self>; + + /// A short name of the type being parsed. + /// + /// The description should only be used for a simple name. It should not + /// contain newlines or sentence-ending punctuation, to facilitate embedding in + /// larger user-facing strings. Syn will use this description when building + /// error messages about parse failures. + /// + /// # Examples + /// + /// ``` + /// # use syn::buffer::Cursor; + /// # use syn::synom::{Synom, PResult}; + /// # + /// struct ExprMacro { + /// // ... + /// } + /// + /// impl Synom for ExprMacro { + /// # fn parse(input: Cursor) -> PResult<Self> { unimplemented!() } + /// // fn parse(...) -> ... { ... } + /// + /// fn description() -> Option<&'static str> { + /// // Will result in messages like + /// // + /// // "failed to parse macro invocation expression: $reason" + /// Some("macro invocation expression") + /// } + /// } + /// ``` + fn description() -> Option<&'static str> { + None + } +} + +impl Synom for proc_macro2::TokenStream { + fn parse(input: Cursor) -> PResult<Self> { + Ok((input.token_stream(), Cursor::empty())) + } + + fn description() -> Option<&'static str> { + Some("arbitrary token stream") + } +} + +/// Parser that can parse Rust tokens into a particular syntax tree node. +/// +/// Refer to the [module documentation] for details about parsing in Syn. +/// +/// [module documentation]: index.html +/// +/// *This trait is available if Syn is built with the `"parsing"` feature.* +pub trait Parser: Sized { + type Output; + + /// Parse a proc-macro2 token stream into the chosen syntax tree node. + fn parse2(self, tokens: proc_macro2::TokenStream) -> Result<Self::Output, ParseError>; + + /// Parse tokens of source code into the chosen syntax tree node. + #[cfg(feature = "proc-macro")] + fn parse(self, tokens: proc_macro::TokenStream) -> Result<Self::Output, ParseError> { + self.parse2(tokens.into()) + } + + /// Parse a string of Rust code into the chosen syntax tree node. + /// + /// # Hygiene + /// + /// Every span in the resulting syntax tree will be set to resolve at the + /// macro call site. + fn parse_str(self, s: &str) -> Result<Self::Output, ParseError> { + match s.parse() { + Ok(tts) => self.parse2(tts), + Err(_) => Err(ParseError::new("error while lexing input string")), + } + } +} + +impl<F, T> Parser for F where F: FnOnce(Cursor) -> PResult<T> { + type Output = T; + + fn parse2(self, tokens: proc_macro2::TokenStream) -> Result<T, ParseError> { + let buf = TokenBuffer::new2(tokens); + let (t, rest) = self(buf.begin())?; + if rest.eof() { + Ok(t) + } else if rest == buf.begin() { + // parsed nothing + Err(ParseError::new("failed to parse anything")) + } else { + Err(ParseError::new("failed to parse all tokens")) + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/token.rs cargo-0.26.0/vendor/syn-0.13.1/src/token.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/token.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/token.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,773 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Tokens representing Rust punctuation, keywords, and delimiters. +//! +//! The type names in this module can be difficult to keep straight, so we +//! prefer to use the [`Token!`] macro instead. This is a type-macro that +//! expands to the token type of the given token. +//! +//! [`Token!`]: ../macro.Token.html +//! +//! # Example +//! +//! The [`ItemStatic`] syntax tree node is defined like this. +//! +//! [`ItemStatic`]: ../struct.ItemStatic.html +//! +//! ``` +//! # #[macro_use] +//! # extern crate syn; +//! # +//! # use syn::{Attribute, Visibility, Ident, Type, Expr}; +//! # +//! pub struct ItemStatic { +//! pub attrs: Vec<Attribute>, +//! pub vis: Visibility, +//! pub static_token: Token![static], +//! pub mutability: Option<Token![mut]>, +//! pub ident: Ident, +//! pub colon_token: Token![:], +//! pub ty: Box<Type>, +//! pub eq_token: Token![=], +//! pub expr: Box<Expr>, +//! pub semi_token: Token![;], +//! } +//! # +//! # fn main() {} +//! ``` +//! +//! # Parsing +//! +//! These tokens can be parsed using the [`Synom`] trait and the parser +//! combinator macros [`punct!`], [`keyword!`], [`parens!`], [`braces!`], and +//! [`brackets!`]. +//! +//! [`Synom`]: ../synom/trait.Synom.html +//! [`punct!`]: ../macro.punct.html +//! [`keyword!`]: ../macro.keyword.html +//! [`parens!`]: ../macro.parens.html +//! [`braces!`]: ../macro.braces.html +//! [`brackets!`]: ../macro.brackets.html +//! +//! ``` +//! #[macro_use] +//! extern crate syn; +//! +//! use syn::synom::Synom; +//! use syn::{Attribute, Visibility, Ident, Type, Expr}; +//! # +//! # struct ItemStatic; +//! # use syn::ItemStatic as SynItemStatic; +//! +//! // Parse the ItemStatic struct shown above. +//! impl Synom for ItemStatic { +//! named!(parse -> Self, do_parse!( +//! # (ItemStatic) +//! # )); +//! # } +//! # +//! # mod example { +//! # use super::*; +//! # use super::SynItemStatic as ItemStatic; +//! # +//! # named!(parse -> ItemStatic, do_parse!( +//! attrs: many0!(Attribute::parse_outer) >> +//! vis: syn!(Visibility) >> +//! static_token: keyword!(static) >> +//! mutability: option!(keyword!(mut)) >> +//! ident: syn!(Ident) >> +//! colon_token: punct!(:) >> +//! ty: syn!(Type) >> +//! eq_token: punct!(=) >> +//! expr: syn!(Expr) >> +//! semi_token: punct!(;) >> +//! (ItemStatic { +//! attrs, vis, static_token, mutability, ident, colon_token, +//! ty: Box::new(ty), eq_token, expr: Box::new(expr), semi_token, +//! }) +//! )); +//! } +//! # +//! # fn main() {} +//! ``` + +use proc_macro2::Span; + +macro_rules! tokens { + ( + punct: { + $($punct:tt pub struct $punct_name:ident/$len:tt #[$punct_doc:meta])* + } + delimiter: { + $($delimiter:tt pub struct $delimiter_name:ident #[$delimiter_doc:meta])* + } + keyword: { + $($keyword:tt pub struct $keyword_name:ident #[$keyword_doc:meta])* + } + ) => ( + $(token_punct! { #[$punct_doc] $punct pub struct $punct_name/$len })* + $(token_delimiter! { #[$delimiter_doc] $delimiter pub struct $delimiter_name })* + $(token_keyword! { #[$keyword_doc] $keyword pub struct $keyword_name })* + ) +} + +macro_rules! token_punct { + (#[$doc:meta] $s:tt pub struct $name:ident/$len:tt) => { + #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))] + #[$doc] + /// + /// Don't try to remember the name of this type -- use the [`Token!`] + /// macro instead. + /// + /// [`Token!`]: index.html + pub struct $name(pub [Span; $len]); + + impl $name { + pub fn new(span: Span) -> Self { + $name([span; $len]) + } + } + + impl ::std::default::Default for $name { + fn default() -> Self { + $name([Span::call_site(); $len]) + } + } + + #[cfg(feature = "extra-traits")] + impl ::std::fmt::Debug for $name { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + f.write_str(stringify!($name)) + } + } + + #[cfg(feature = "extra-traits")] + impl ::std::cmp::Eq for $name {} + + #[cfg(feature = "extra-traits")] + impl ::std::cmp::PartialEq for $name { + fn eq(&self, _other: &$name) -> bool { + true + } + } + + #[cfg(feature = "extra-traits")] + impl ::std::hash::Hash for $name { + fn hash<H>(&self, _state: &mut H) + where H: ::std::hash::Hasher + {} + } + + #[cfg(feature = "printing")] + impl ::quote::ToTokens for $name { + fn to_tokens(&self, tokens: &mut ::quote::Tokens) { + printing::punct($s, &self.0, tokens); + } + } + + #[cfg(feature = "parsing")] + impl ::Synom for $name { + fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> { + parsing::punct($s, tokens, $name) + } + + fn description() -> Option<&'static str> { + Some(concat!("`", $s, "`")) + } + } + + impl From<Span> for $name { + fn from(span: Span) -> Self { + $name([span; $len]) + } + } + } +} + +macro_rules! token_keyword { + (#[$doc:meta] $s:tt pub struct $name:ident) => { + #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))] + #[$doc] + /// + /// Don't try to remember the name of this type -- use the [`Token!`] + /// macro instead. + /// + /// [`Token!`]: index.html + pub struct $name(pub Span); + + impl ::std::default::Default for $name { + fn default() -> Self { + $name(Span::call_site()) + } + } + + #[cfg(feature = "extra-traits")] + impl ::std::fmt::Debug for $name { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + f.write_str(stringify!($name)) + } + } + + #[cfg(feature = "extra-traits")] + impl ::std::cmp::Eq for $name {} + + #[cfg(feature = "extra-traits")] + impl ::std::cmp::PartialEq for $name { + fn eq(&self, _other: &$name) -> bool { + true + } + } + + #[cfg(feature = "extra-traits")] + impl ::std::hash::Hash for $name { + fn hash<H>(&self, _state: &mut H) + where H: ::std::hash::Hasher + {} + } + + #[cfg(feature = "printing")] + impl ::quote::ToTokens for $name { + fn to_tokens(&self, tokens: &mut ::quote::Tokens) { + printing::keyword($s, &self.0, tokens); + } + } + + #[cfg(feature = "parsing")] + impl ::Synom for $name { + fn parse(tokens: $crate::buffer::Cursor) -> $crate::synom::PResult<$name> { + parsing::keyword($s, tokens, $name) + } + + fn description() -> Option<&'static str> { + Some(concat!("`", $s, "`")) + } + } + + impl From<Span> for $name { + fn from(span: Span) -> Self { + $name(span) + } + } + } +} + +macro_rules! token_delimiter { + (#[$doc:meta] $s:tt pub struct $name:ident) => { + #[cfg_attr(feature = "clone-impls", derive(Copy, Clone))] + #[$doc] + pub struct $name(pub Span); + + impl ::std::default::Default for $name { + fn default() -> Self { + $name(Span::call_site()) + } + } + + #[cfg(feature = "extra-traits")] + impl ::std::fmt::Debug for $name { + fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { + f.write_str(stringify!($name)) + } + } + + #[cfg(feature = "extra-traits")] + impl ::std::cmp::Eq for $name {} + + #[cfg(feature = "extra-traits")] + impl ::std::cmp::PartialEq for $name { + fn eq(&self, _other: &$name) -> bool { + true + } + } + + #[cfg(feature = "extra-traits")] + impl ::std::hash::Hash for $name { + fn hash<H>(&self, _state: &mut H) + where H: ::std::hash::Hasher + {} + } + + impl $name { + #[cfg(feature = "printing")] + pub fn surround<F>(&self, + tokens: &mut ::quote::Tokens, + f: F) + where F: FnOnce(&mut ::quote::Tokens) + { + printing::delim($s, &self.0, tokens, f); + } + + #[cfg(feature = "parsing")] + pub fn parse<F, R>(tokens: $crate::buffer::Cursor, f: F) -> $crate::synom::PResult<($name, R)> + where F: FnOnce($crate::buffer::Cursor) -> $crate::synom::PResult<R> + { + parsing::delim($s, tokens, $name, f) + } + } + + impl From<Span> for $name { + fn from(span: Span) -> Self { + $name(span) + } + } + } +} + +tokens! { + punct: { + "+" pub struct Add/1 /// `+` + "+=" pub struct AddEq/2 /// `+=` + "&" pub struct And/1 /// `&` + "&&" pub struct AndAnd/2 /// `&&` + "&=" pub struct AndEq/2 /// `&=` + "@" pub struct At/1 /// `@` + "!" pub struct Bang/1 /// `!` + "^" pub struct Caret/1 /// `^` + "^=" pub struct CaretEq/2 /// `^=` + ":" pub struct Colon/1 /// `:` + "::" pub struct Colon2/2 /// `::` + "," pub struct Comma/1 /// `,` + "/" pub struct Div/1 /// `/` + "/=" pub struct DivEq/2 /// `/=` + "." pub struct Dot/1 /// `.` + ".." pub struct Dot2/2 /// `..` + "..." pub struct Dot3/3 /// `...` + "..=" pub struct DotDotEq/3 /// `..=` + "=" pub struct Eq/1 /// `=` + "==" pub struct EqEq/2 /// `==` + ">=" pub struct Ge/2 /// `>=` + ">" pub struct Gt/1 /// `>` + "<=" pub struct Le/2 /// `<=` + "<" pub struct Lt/1 /// `<` + "*=" pub struct MulEq/2 /// `*=` + "!=" pub struct Ne/2 /// `!=` + "|" pub struct Or/1 /// `|` + "|=" pub struct OrEq/2 /// `|=` + "||" pub struct OrOr/2 /// `||` + "#" pub struct Pound/1 /// `#` + "?" pub struct Question/1 /// `?` + "->" pub struct RArrow/2 /// `->` + "<-" pub struct LArrow/2 /// `<-` + "%" pub struct Rem/1 /// `%` + "%=" pub struct RemEq/2 /// `%=` + "=>" pub struct FatArrow/2 /// `=>` + ";" pub struct Semi/1 /// `;` + "<<" pub struct Shl/2 /// `<<` + "<<=" pub struct ShlEq/3 /// `<<=` + ">>" pub struct Shr/2 /// `>>` + ">>=" pub struct ShrEq/3 /// `>>=` + "*" pub struct Star/1 /// `*` + "-" pub struct Sub/1 /// `-` + "-=" pub struct SubEq/2 /// `-=` + "_" pub struct Underscore/1 /// `_` + } + delimiter: { + "{" pub struct Brace /// `{...}` + "[" pub struct Bracket /// `[...]` + "(" pub struct Paren /// `(...)` + " " pub struct Group /// None-delimited group + } + keyword: { + "as" pub struct As /// `as` + "auto" pub struct Auto /// `auto` + "box" pub struct Box /// `box` + "break" pub struct Break /// `break` + "Self" pub struct CapSelf /// `Self` + "catch" pub struct Catch /// `catch` + "const" pub struct Const /// `const` + "continue" pub struct Continue /// `continue` + "crate" pub struct Crate /// `crate` + "default" pub struct Default /// `default` + "do" pub struct Do /// `do` + "dyn" pub struct Dyn /// `dyn` + "else" pub struct Else /// `else` + "enum" pub struct Enum /// `enum` + "extern" pub struct Extern /// `extern` + "fn" pub struct Fn /// `fn` + "for" pub struct For /// `for` + "if" pub struct If /// `if` + "impl" pub struct Impl /// `impl` + "in" pub struct In /// `in` + "let" pub struct Let /// `let` + "loop" pub struct Loop /// `loop` + "macro" pub struct Macro /// `macro` + "match" pub struct Match /// `match` + "mod" pub struct Mod /// `mod` + "move" pub struct Move /// `move` + "mut" pub struct Mut /// `mut` + "pub" pub struct Pub /// `pub` + "ref" pub struct Ref /// `ref` + "return" pub struct Return /// `return` + "self" pub struct Self_ /// `self` + "static" pub struct Static /// `static` + "struct" pub struct Struct /// `struct` + "super" pub struct Super /// `super` + "trait" pub struct Trait /// `trait` + "type" pub struct Type /// `type` + "union" pub struct Union /// `union` + "unsafe" pub struct Unsafe /// `unsafe` + "use" pub struct Use /// `use` + "where" pub struct Where /// `where` + "while" pub struct While /// `while` + "yield" pub struct Yield /// `yield` + } +} + +/// A type-macro that expands to the name of the Rust type representation of a +/// given token. +/// +/// See the [token module] documentation for details and examples. +/// +/// [token module]: token/index.html +// Unfortunate duplication due to a rustdoc bug. +// https://github.com/rust-lang/rust/issues/45939 +#[macro_export] +macro_rules! Token { + (+) => { $crate::token::Add }; + (+=) => { $crate::token::AddEq }; + (&) => { $crate::token::And }; + (&&) => { $crate::token::AndAnd }; + (&=) => { $crate::token::AndEq }; + (@) => { $crate::token::At }; + (!) => { $crate::token::Bang }; + (^) => { $crate::token::Caret }; + (^=) => { $crate::token::CaretEq }; + (:) => { $crate::token::Colon }; + (::) => { $crate::token::Colon2 }; + (,) => { $crate::token::Comma }; + (/) => { $crate::token::Div }; + (/=) => { $crate::token::DivEq }; + (.) => { $crate::token::Dot }; + (..) => { $crate::token::Dot2 }; + (...) => { $crate::token::Dot3 }; + (..=) => { $crate::token::DotDotEq }; + (=) => { $crate::token::Eq }; + (==) => { $crate::token::EqEq }; + (>=) => { $crate::token::Ge }; + (>) => { $crate::token::Gt }; + (<=) => { $crate::token::Le }; + (<) => { $crate::token::Lt }; + (*=) => { $crate::token::MulEq }; + (!=) => { $crate::token::Ne }; + (|) => { $crate::token::Or }; + (|=) => { $crate::token::OrEq }; + (||) => { $crate::token::OrOr }; + (#) => { $crate::token::Pound }; + (?) => { $crate::token::Question }; + (->) => { $crate::token::RArrow }; + (<-) => { $crate::token::LArrow }; + (%) => { $crate::token::Rem }; + (%=) => { $crate::token::RemEq }; + (=>) => { $crate::token::FatArrow }; + (;) => { $crate::token::Semi }; + (<<) => { $crate::token::Shl }; + (<<=) => { $crate::token::ShlEq }; + (>>) => { $crate::token::Shr }; + (>>=) => { $crate::token::ShrEq }; + (*) => { $crate::token::Star }; + (-) => { $crate::token::Sub }; + (-=) => { $crate::token::SubEq }; + (_) => { $crate::token::Underscore }; + (as) => { $crate::token::As }; + (auto) => { $crate::token::Auto }; + (box) => { $crate::token::Box }; + (break) => { $crate::token::Break }; + (Self) => { $crate::token::CapSelf }; + (catch) => { $crate::token::Catch }; + (const) => { $crate::token::Const }; + (continue) => { $crate::token::Continue }; + (crate) => { $crate::token::Crate }; + (default) => { $crate::token::Default }; + (do) => { $crate::token::Do }; + (dyn) => { $crate::token::Dyn }; + (else) => { $crate::token::Else }; + (enum) => { $crate::token::Enum }; + (extern) => { $crate::token::Extern }; + (fn) => { $crate::token::Fn }; + (for) => { $crate::token::For }; + (if) => { $crate::token::If }; + (impl) => { $crate::token::Impl }; + (in) => { $crate::token::In }; + (let) => { $crate::token::Let }; + (loop) => { $crate::token::Loop }; + (macro) => { $crate::token::Macro }; + (match) => { $crate::token::Match }; + (mod) => { $crate::token::Mod }; + (move) => { $crate::token::Move }; + (mut) => { $crate::token::Mut }; + (pub) => { $crate::token::Pub }; + (ref) => { $crate::token::Ref }; + (return) => { $crate::token::Return }; + (self) => { $crate::token::Self_ }; + (static) => { $crate::token::Static }; + (struct) => { $crate::token::Struct }; + (super) => { $crate::token::Super }; + (trait) => { $crate::token::Trait }; + (type) => { $crate::token::Type }; + (union) => { $crate::token::Union }; + (unsafe) => { $crate::token::Unsafe }; + (use) => { $crate::token::Use }; + (where) => { $crate::token::Where }; + (while) => { $crate::token::While }; + (yield) => { $crate::token::Yield }; +} + +/// Parse a single Rust punctuation token. +/// +/// See the [token module] documentation for details and examples. +/// +/// [token module]: token/index.html +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[cfg(feature = "parsing")] +#[macro_export] +macro_rules! punct { + ($i:expr, +) => { call!($i, <$crate::token::Add as $crate::synom::Synom>::parse) }; + ($i:expr, +=) => { call!($i, <$crate::token::AddEq as $crate::synom::Synom>::parse) }; + ($i:expr, &) => { call!($i, <$crate::token::And as $crate::synom::Synom>::parse) }; + ($i:expr, &&) => { call!($i, <$crate::token::AndAnd as $crate::synom::Synom>::parse) }; + ($i:expr, &=) => { call!($i, <$crate::token::AndEq as $crate::synom::Synom>::parse) }; + ($i:expr, @) => { call!($i, <$crate::token::At as $crate::synom::Synom>::parse) }; + ($i:expr, !) => { call!($i, <$crate::token::Bang as $crate::synom::Synom>::parse) }; + ($i:expr, ^) => { call!($i, <$crate::token::Caret as $crate::synom::Synom>::parse) }; + ($i:expr, ^=) => { call!($i, <$crate::token::CaretEq as $crate::synom::Synom>::parse) }; + ($i:expr, :) => { call!($i, <$crate::token::Colon as $crate::synom::Synom>::parse) }; + ($i:expr, ::) => { call!($i, <$crate::token::Colon2 as $crate::synom::Synom>::parse) }; + ($i:expr, ,) => { call!($i, <$crate::token::Comma as $crate::synom::Synom>::parse) }; + ($i:expr, /) => { call!($i, <$crate::token::Div as $crate::synom::Synom>::parse) }; + ($i:expr, /=) => { call!($i, <$crate::token::DivEq as $crate::synom::Synom>::parse) }; + ($i:expr, .) => { call!($i, <$crate::token::Dot as $crate::synom::Synom>::parse) }; + ($i:expr, ..) => { call!($i, <$crate::token::Dot2 as $crate::synom::Synom>::parse) }; + ($i:expr, ...) => { call!($i, <$crate::token::Dot3 as $crate::synom::Synom>::parse) }; + ($i:expr, ..=) => { call!($i, <$crate::token::DotDotEq as $crate::synom::Synom>::parse) }; + ($i:expr, =) => { call!($i, <$crate::token::Eq as $crate::synom::Synom>::parse) }; + ($i:expr, ==) => { call!($i, <$crate::token::EqEq as $crate::synom::Synom>::parse) }; + ($i:expr, >=) => { call!($i, <$crate::token::Ge as $crate::synom::Synom>::parse) }; + ($i:expr, >) => { call!($i, <$crate::token::Gt as $crate::synom::Synom>::parse) }; + ($i:expr, <=) => { call!($i, <$crate::token::Le as $crate::synom::Synom>::parse) }; + ($i:expr, <) => { call!($i, <$crate::token::Lt as $crate::synom::Synom>::parse) }; + ($i:expr, *=) => { call!($i, <$crate::token::MulEq as $crate::synom::Synom>::parse) }; + ($i:expr, !=) => { call!($i, <$crate::token::Ne as $crate::synom::Synom>::parse) }; + ($i:expr, |) => { call!($i, <$crate::token::Or as $crate::synom::Synom>::parse) }; + ($i:expr, |=) => { call!($i, <$crate::token::OrEq as $crate::synom::Synom>::parse) }; + ($i:expr, ||) => { call!($i, <$crate::token::OrOr as $crate::synom::Synom>::parse) }; + ($i:expr, #) => { call!($i, <$crate::token::Pound as $crate::synom::Synom>::parse) }; + ($i:expr, ?) => { call!($i, <$crate::token::Question as $crate::synom::Synom>::parse) }; + ($i:expr, ->) => { call!($i, <$crate::token::RArrow as $crate::synom::Synom>::parse) }; + ($i:expr, <-) => { call!($i, <$crate::token::LArrow as $crate::synom::Synom>::parse) }; + ($i:expr, %) => { call!($i, <$crate::token::Rem as $crate::synom::Synom>::parse) }; + ($i:expr, %=) => { call!($i, <$crate::token::RemEq as $crate::synom::Synom>::parse) }; + ($i:expr, =>) => { call!($i, <$crate::token::FatArrow as $crate::synom::Synom>::parse) }; + ($i:expr, ;) => { call!($i, <$crate::token::Semi as $crate::synom::Synom>::parse) }; + ($i:expr, <<) => { call!($i, <$crate::token::Shl as $crate::synom::Synom>::parse) }; + ($i:expr, <<=) => { call!($i, <$crate::token::ShlEq as $crate::synom::Synom>::parse) }; + ($i:expr, >>) => { call!($i, <$crate::token::Shr as $crate::synom::Synom>::parse) }; + ($i:expr, >>=) => { call!($i, <$crate::token::ShrEq as $crate::synom::Synom>::parse) }; + ($i:expr, *) => { call!($i, <$crate::token::Star as $crate::synom::Synom>::parse) }; + ($i:expr, -) => { call!($i, <$crate::token::Sub as $crate::synom::Synom>::parse) }; + ($i:expr, -=) => { call!($i, <$crate::token::SubEq as $crate::synom::Synom>::parse) }; + ($i:expr, _) => { call!($i, <$crate::token::Underscore as $crate::synom::Synom>::parse) }; +} + +/// Parse a single Rust keyword token. +/// +/// See the [token module] documentation for details and examples. +/// +/// [token module]: token/index.html +/// +/// *This macro is available if Syn is built with the `"parsing"` feature.* +#[cfg(feature = "parsing")] +#[macro_export] +macro_rules! keyword { + ($i:expr, as) => { call!($i, <$crate::token::As as $crate::synom::Synom>::parse) }; + ($i:expr, auto) => { call!($i, <$crate::token::Auto as $crate::synom::Synom>::parse) }; + ($i:expr, box) => { call!($i, <$crate::token::Box as $crate::synom::Synom>::parse) }; + ($i:expr, break) => { call!($i, <$crate::token::Break as $crate::synom::Synom>::parse) }; + ($i:expr, Self) => { call!($i, <$crate::token::CapSelf as $crate::synom::Synom>::parse) }; + ($i:expr, catch) => { call!($i, <$crate::token::Catch as $crate::synom::Synom>::parse) }; + ($i:expr, const) => { call!($i, <$crate::token::Const as $crate::synom::Synom>::parse) }; + ($i:expr, continue) => { call!($i, <$crate::token::Continue as $crate::synom::Synom>::parse) }; + ($i:expr, crate) => { call!($i, <$crate::token::Crate as $crate::synom::Synom>::parse) }; + ($i:expr, default) => { call!($i, <$crate::token::Default as $crate::synom::Synom>::parse) }; + ($i:expr, do) => { call!($i, <$crate::token::Do as $crate::synom::Synom>::parse) }; + ($i:expr, dyn) => { call!($i, <$crate::token::Dyn as $crate::synom::Synom>::parse) }; + ($i:expr, else) => { call!($i, <$crate::token::Else as $crate::synom::Synom>::parse) }; + ($i:expr, enum) => { call!($i, <$crate::token::Enum as $crate::synom::Synom>::parse) }; + ($i:expr, extern) => { call!($i, <$crate::token::Extern as $crate::synom::Synom>::parse) }; + ($i:expr, fn) => { call!($i, <$crate::token::Fn as $crate::synom::Synom>::parse) }; + ($i:expr, for) => { call!($i, <$crate::token::For as $crate::synom::Synom>::parse) }; + ($i:expr, if) => { call!($i, <$crate::token::If as $crate::synom::Synom>::parse) }; + ($i:expr, impl) => { call!($i, <$crate::token::Impl as $crate::synom::Synom>::parse) }; + ($i:expr, in) => { call!($i, <$crate::token::In as $crate::synom::Synom>::parse) }; + ($i:expr, let) => { call!($i, <$crate::token::Let as $crate::synom::Synom>::parse) }; + ($i:expr, loop) => { call!($i, <$crate::token::Loop as $crate::synom::Synom>::parse) }; + ($i:expr, macro) => { call!($i, <$crate::token::Macro as $crate::synom::Synom>::parse) }; + ($i:expr, match) => { call!($i, <$crate::token::Match as $crate::synom::Synom>::parse) }; + ($i:expr, mod) => { call!($i, <$crate::token::Mod as $crate::synom::Synom>::parse) }; + ($i:expr, move) => { call!($i, <$crate::token::Move as $crate::synom::Synom>::parse) }; + ($i:expr, mut) => { call!($i, <$crate::token::Mut as $crate::synom::Synom>::parse) }; + ($i:expr, pub) => { call!($i, <$crate::token::Pub as $crate::synom::Synom>::parse) }; + ($i:expr, ref) => { call!($i, <$crate::token::Ref as $crate::synom::Synom>::parse) }; + ($i:expr, return) => { call!($i, <$crate::token::Return as $crate::synom::Synom>::parse) }; + ($i:expr, self) => { call!($i, <$crate::token::Self_ as $crate::synom::Synom>::parse) }; + ($i:expr, static) => { call!($i, <$crate::token::Static as $crate::synom::Synom>::parse) }; + ($i:expr, struct) => { call!($i, <$crate::token::Struct as $crate::synom::Synom>::parse) }; + ($i:expr, super) => { call!($i, <$crate::token::Super as $crate::synom::Synom>::parse) }; + ($i:expr, trait) => { call!($i, <$crate::token::Trait as $crate::synom::Synom>::parse) }; + ($i:expr, type) => { call!($i, <$crate::token::Type as $crate::synom::Synom>::parse) }; + ($i:expr, union) => { call!($i, <$crate::token::Union as $crate::synom::Synom>::parse) }; + ($i:expr, unsafe) => { call!($i, <$crate::token::Unsafe as $crate::synom::Synom>::parse) }; + ($i:expr, use) => { call!($i, <$crate::token::Use as $crate::synom::Synom>::parse) }; + ($i:expr, where) => { call!($i, <$crate::token::Where as $crate::synom::Synom>::parse) }; + ($i:expr, while) => { call!($i, <$crate::token::While as $crate::synom::Synom>::parse) }; + ($i:expr, yield) => { call!($i, <$crate::token::Yield as $crate::synom::Synom>::parse) }; +} + +#[cfg(feature = "parsing")] +mod parsing { + use proc_macro2::{Delimiter, Spacing, Span}; + + use buffer::Cursor; + use parse_error; + use synom::PResult; + + pub trait FromSpans: Sized { + fn from_spans(spans: &[Span]) -> Self; + } + + impl FromSpans for [Span; 1] { + fn from_spans(spans: &[Span]) -> Self { + [spans[0]] + } + } + + impl FromSpans for [Span; 2] { + fn from_spans(spans: &[Span]) -> Self { + [spans[0], spans[1]] + } + } + + impl FromSpans for [Span; 3] { + fn from_spans(spans: &[Span]) -> Self { + [spans[0], spans[1], spans[2]] + } + } + + pub fn punct<'a, T, R>(s: &str, mut tokens: Cursor<'a>, new: fn(T) -> R) -> PResult<'a, R> + where + T: FromSpans, + { + let mut spans = [Span::call_site(); 3]; + assert!(s.len() <= spans.len()); + let chars = s.chars(); + + for (i, (ch, slot)) in chars.zip(&mut spans).enumerate() { + match tokens.op() { + Some((op, rest)) if op.op() == ch => { + if i != s.len() - 1 { + match op.spacing() { + Spacing::Joint => {} + _ => return parse_error(), + } + } + *slot = op.span(); + tokens = rest; + } + _ => return parse_error(), + } + } + Ok((new(T::from_spans(&spans)), tokens)) + } + + pub fn keyword<'a, T>(keyword: &str, tokens: Cursor<'a>, new: fn(Span) -> T) -> PResult<'a, T> { + if let Some((term, rest)) = tokens.term() { + if term.as_str() == keyword { + return Ok((new(term.span()), rest)); + } + } + parse_error() + } + + pub fn delim<'a, F, R, T>( + delim: &str, + tokens: Cursor<'a>, + new: fn(Span) -> T, + f: F, + ) -> PResult<'a, (T, R)> + where + F: FnOnce(Cursor) -> PResult<R>, + { + // NOTE: We should support none-delimited sequences here. + let delim = match delim { + "(" => Delimiter::Parenthesis, + "{" => Delimiter::Brace, + "[" => Delimiter::Bracket, + " " => Delimiter::None, + _ => panic!("unknown delimiter: {}", delim), + }; + + if let Some((inside, span, rest)) = tokens.group(delim) { + match f(inside) { + Ok((ret, remaining)) => { + if remaining.eof() { + return Ok(((new(span), ret), rest)); + } + } + Err(err) => return Err(err), + } + } + parse_error() + } +} + +#[cfg(feature = "printing")] +mod printing { + use proc_macro2::{Delimiter, Spacing, Span, Term, Op, Group}; + use quote::Tokens; + + pub fn punct(s: &str, spans: &[Span], tokens: &mut Tokens) { + assert_eq!(s.len(), spans.len()); + + let mut chars = s.chars(); + let mut spans = spans.iter(); + let ch = chars.next_back().unwrap(); + let span = spans.next_back().unwrap(); + for (ch, span) in chars.zip(spans) { + let mut op = Op::new(ch, Spacing::Joint); + op.set_span(*span); + tokens.append(op); + } + + let mut op = Op::new(ch, Spacing::Alone); + op.set_span(*span); + tokens.append(op); + } + + pub fn keyword(s: &str, span: &Span, tokens: &mut Tokens) { + tokens.append(Term::new(s, *span)); + } + + pub fn delim<F>(s: &str, span: &Span, tokens: &mut Tokens, f: F) + where + F: FnOnce(&mut Tokens), + { + let delim = match s { + "(" => Delimiter::Parenthesis, + "[" => Delimiter::Bracket, + "{" => Delimiter::Brace, + " " => Delimiter::None, + _ => panic!("unknown delimiter: {}", s), + }; + let mut inner = Tokens::new(); + f(&mut inner); + let mut g = Group::new(delim, inner.into()); + g.set_span(*span); + tokens.append(g); + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/tt.rs cargo-0.26.0/vendor/syn-0.13.1/src/tt.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/tt.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/tt.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,170 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[cfg(feature = "parsing")] +use buffer::Cursor; +#[cfg(feature = "parsing")] +use synom::PResult; +#[cfg(feature = "parsing")] +use token::{Brace, Bracket, Paren}; +#[cfg(feature = "parsing")] +use {parse_error, MacroDelimiter}; + +#[cfg(feature = "extra-traits")] +use std::hash::{Hash, Hasher}; + +#[cfg(any(feature = "parsing", feature = "extra-traits"))] +use proc_macro2::{Delimiter, TokenStream, TokenTree}; + +#[cfg(feature = "parsing")] +pub fn delimited(input: Cursor) -> PResult<(MacroDelimiter, TokenStream)> { + if let Some((TokenTree::Group(g), rest)) = input.token_tree() { + let span = g.span(); + let delimiter = match g.delimiter() { + Delimiter::Parenthesis => MacroDelimiter::Paren(Paren(span)), + Delimiter::Brace => MacroDelimiter::Brace(Brace(span)), + Delimiter::Bracket => MacroDelimiter::Bracket(Bracket(span)), + Delimiter::None => return parse_error(), + }; + + return Ok(((delimiter, g.stream().clone()), rest)) + } + parse_error() +} + +#[cfg(all(feature = "full", feature = "parsing"))] +pub fn braced(input: Cursor) -> PResult<(Brace, TokenStream)> { + if let Some((TokenTree::Group(g), rest)) = input.token_tree() { + if g.delimiter() == Delimiter::Brace { + return Ok(((Brace(g.span()), g.stream().clone()), rest)) + } + } + parse_error() +} + +#[cfg(all(feature = "full", feature = "parsing"))] +pub fn parenthesized(input: Cursor) -> PResult<(Paren, TokenStream)> { + if let Some((TokenTree::Group(g), rest)) = input.token_tree() { + if g.delimiter() == Delimiter::Parenthesis { + return Ok(((Paren(g.span()), g.stream().clone()), rest)) + } + } + parse_error() +} + +#[cfg(feature = "extra-traits")] +pub struct TokenTreeHelper<'a>(pub &'a TokenTree); + +#[cfg(feature = "extra-traits")] +impl<'a> PartialEq for TokenTreeHelper<'a> { + fn eq(&self, other: &Self) -> bool { + use proc_macro2::Spacing; + + match (self.0, other.0) { + (&TokenTree::Group(ref g1), &TokenTree::Group(ref g2)) => { + match (g1.delimiter(), g2.delimiter()) { + (Delimiter::Parenthesis, Delimiter::Parenthesis) + | (Delimiter::Brace, Delimiter::Brace) + | (Delimiter::Bracket, Delimiter::Bracket) + | (Delimiter::None, Delimiter::None) => {} + _ => return false, + } + + let s1 = g1.stream().clone().into_iter(); + let mut s2 = g2.stream().clone().into_iter(); + + for item1 in s1 { + let item2 = match s2.next() { + Some(item) => item, + None => return false, + }; + if TokenTreeHelper(&item1) != TokenTreeHelper(&item2) { + return false; + } + } + s2.next().is_none() + } + (&TokenTree::Op(ref o1), &TokenTree::Op(ref o2)) => { + o1.op() == o2.op() && match (o1.spacing(), o2.spacing()) { + (Spacing::Alone, Spacing::Alone) | (Spacing::Joint, Spacing::Joint) => true, + _ => false, + } + } + (&TokenTree::Literal(ref l1), &TokenTree::Literal(ref l2)) => { + l1.to_string() == l2.to_string() + } + (&TokenTree::Term(ref s1), &TokenTree::Term(ref s2)) => s1.as_str() == s2.as_str(), + _ => false, + } + } +} + +#[cfg(feature = "extra-traits")] +impl<'a> Hash for TokenTreeHelper<'a> { + fn hash<H: Hasher>(&self, h: &mut H) { + use proc_macro2::Spacing; + + match *self.0 { + TokenTree::Group(ref g) => { + 0u8.hash(h); + match g.delimiter() { + Delimiter::Parenthesis => 0u8.hash(h), + Delimiter::Brace => 1u8.hash(h), + Delimiter::Bracket => 2u8.hash(h), + Delimiter::None => 3u8.hash(h), + } + + for item in g.stream().clone() { + TokenTreeHelper(&item).hash(h); + } + 0xffu8.hash(h); // terminator w/ a variant we don't normally hash + } + TokenTree::Op(ref op) => { + 1u8.hash(h); + op.op().hash(h); + match op.spacing() { + Spacing::Alone => 0u8.hash(h), + Spacing::Joint => 1u8.hash(h), + } + } + TokenTree::Literal(ref lit) => (2u8, lit.to_string()).hash(h), + TokenTree::Term(ref word) => (3u8, word.as_str()).hash(h), + } + } +} + +#[cfg(feature = "extra-traits")] +pub struct TokenStreamHelper<'a>(pub &'a TokenStream); + +#[cfg(feature = "extra-traits")] +impl<'a> PartialEq for TokenStreamHelper<'a> { + fn eq(&self, other: &Self) -> bool { + let left = self.0.clone().into_iter().collect::<Vec<_>>(); + let right = other.0.clone().into_iter().collect::<Vec<_>>(); + if left.len() != right.len() { + return false; + } + for (a, b) in left.into_iter().zip(right) { + if TokenTreeHelper(&a) != TokenTreeHelper(&b) { + return false; + } + } + true + } +} + +#[cfg(feature = "extra-traits")] +impl<'a> Hash for TokenStreamHelper<'a> { + fn hash<H: Hasher>(&self, state: &mut H) { + let tts = self.0.clone().into_iter().collect::<Vec<_>>(); + tts.len().hash(state); + for tt in tts { + TokenTreeHelper(&tt).hash(state); + } + } +} diff -Nru cargo-0.25.0/vendor/syn-0.13.1/src/ty.rs cargo-0.26.0/vendor/syn-0.13.1/src/ty.rs --- cargo-0.25.0/vendor/syn-0.13.1/src/ty.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/syn-0.13.1/src/ty.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,811 @@ +// Copyright 2018 Syn Developers +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use punctuated::Punctuated; +use super::*; +use proc_macro2::TokenStream; +#[cfg(feature = "extra-traits")] +use std::hash::{Hash, Hasher}; +#[cfg(feature = "extra-traits")] +use tt::TokenStreamHelper; + +ast_enum_of_structs! { + /// The possible types that a Rust value could have. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + /// + /// # Syntax tree enum + /// + /// This type is a [syntax tree enum]. + /// + /// [syntax tree enum]: enum.Expr.html#syntax-tree-enums + pub enum Type { + /// A dynamically sized slice type: `[T]`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Slice(TypeSlice { + pub bracket_token: token::Bracket, + pub elem: Box<Type>, + }), + + /// A fixed size array type: `[T; n]`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Array(TypeArray { + pub bracket_token: token::Bracket, + pub elem: Box<Type>, + pub semi_token: Token![;], + pub len: Expr, + }), + + /// A raw pointer type: `*const T` or `*mut T`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Ptr(TypePtr { + pub star_token: Token![*], + pub const_token: Option<Token![const]>, + pub mutability: Option<Token![mut]>, + pub elem: Box<Type>, + }), + + /// A reference type: `&'a T` or `&'a mut T`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Reference(TypeReference { + pub and_token: Token![&], + pub lifetime: Option<Lifetime>, + pub mutability: Option<Token![mut]>, + pub elem: Box<Type>, + }), + + /// A bare function type: `fn(usize) -> bool`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub BareFn(TypeBareFn { + pub unsafety: Option<Token![unsafe]>, + pub abi: Option<Abi>, + pub fn_token: Token![fn], + pub lifetimes: Option<BoundLifetimes>, + pub paren_token: token::Paren, + pub inputs: Punctuated<BareFnArg, Token![,]>, + pub variadic: Option<Token![...]>, + pub output: ReturnType, + }), + + /// The never type: `!`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Never(TypeNever { + pub bang_token: Token![!], + }), + + /// A tuple type: `(A, B, C, String)`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Tuple(TypeTuple { + pub paren_token: token::Paren, + pub elems: Punctuated<Type, Token![,]>, + }), + + /// A path like `std::slice::Iter`, optionally qualified with a + /// self-type as in `<Vec<T> as SomeTrait>::Associated`. + /// + /// Type arguments are stored in the Path itself. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Path(TypePath { + pub qself: Option<QSelf>, + pub path: Path, + }), + + /// A trait object type `Bound1 + Bound2 + Bound3` where `Bound` is a + /// trait or a lifetime. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub TraitObject(TypeTraitObject { + pub dyn_token: Option<Token![dyn]>, + pub bounds: Punctuated<TypeParamBound, Token![+]>, + }), + + /// An `impl Bound1 + Bound2 + Bound3` type where `Bound` is a trait or + /// a lifetime. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub ImplTrait(TypeImplTrait { + pub impl_token: Token![impl], + pub bounds: Punctuated<TypeParamBound, Token![+]>, + }), + + /// A parenthesized type equivalent to the inner type. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Paren(TypeParen { + pub paren_token: token::Paren, + pub elem: Box<Type>, + }), + + /// A type contained within invisible delimiters. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Group(TypeGroup { + pub group_token: token::Group, + pub elem: Box<Type>, + }), + + /// Indication that a type should be inferred by the compiler: `_`. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Infer(TypeInfer { + pub underscore_token: Token![_], + }), + + /// A macro in the type position. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Macro(TypeMacro { + pub mac: Macro, + }), + + /// Tokens in type position not interpreted by Syn. + /// + /// *This type is available if Syn is built with the `"derive"` or + /// `"full"` feature.* + pub Verbatim(TypeVerbatim #manual_extra_traits { + pub tts: TokenStream, + }), + } +} + +#[cfg(feature = "extra-traits")] +impl Eq for TypeVerbatim {} + +#[cfg(feature = "extra-traits")] +impl PartialEq for TypeVerbatim { + fn eq(&self, other: &Self) -> bool { + TokenStreamHelper(&self.tts) == TokenStreamHelper(&other.tts) + } +} + +#[cfg(feature = "extra-traits")] +impl Hash for TypeVerbatim { + fn hash<H>(&self, state: &mut H) + where + H: Hasher, + { + TokenStreamHelper(&self.tts).hash(state); + } +} + +ast_struct! { + /// The binary interface of a function: `extern "C"`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct Abi { + pub extern_token: Token![extern], + pub name: Option<LitStr>, + } +} + +ast_struct! { + /// An argument in a function type: the `usize` in `fn(usize) -> bool`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub struct BareFnArg { + pub name: Option<(BareFnArgName, Token![:])>, + pub ty: Type, + } +} + +ast_enum! { + /// Name of an argument in a function type: the `n` in `fn(n: usize)`. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub enum BareFnArgName { + /// Argument given a name. + Named(Ident), + /// Argument not given a name, matched with `_`. + Wild(Token![_]), + } +} + +ast_enum! { + /// Return type of a function signature. + /// + /// *This type is available if Syn is built with the `"derive"` or `"full"` + /// feature.* + pub enum ReturnType { + /// Return type is not specified. + /// + /// Functions default to `()` and closures default to type inference. + Default, + /// A particular type is returned. + Type(Token![->], Box<Type>), + } +} + +#[cfg(feature = "parsing")] +pub mod parsing { + use super::*; + use synom::Synom; + use path::parsing::qpath; + + impl Synom for Type { + named!(parse -> Self, call!(ambig_ty, true)); + + fn description() -> Option<&'static str> { + Some("type") + } + } + + impl Type { + /// In some positions, types may not contain the `+` character, to + /// disambiguate them. For example in the expression `1 as T`, T may not + /// contain a `+` character. + /// + /// This parser does not allow a `+`, while the default parser does. + named!(pub without_plus -> Self, call!(ambig_ty, false)); + } + + named!(ambig_ty(allow_plus: bool) -> Type, alt!( + syn!(TypeGroup) => { Type::Group } + | + // must be before TypeTuple + call!(TypeParen::parse, allow_plus) => { Type::Paren } + | + // must be before TypePath + syn!(TypeMacro) => { Type::Macro } + | + // must be before TypeTraitObject + call!(TypePath::parse, allow_plus) => { Type::Path } + | + // Don't try parsing more than one trait bound if we aren't allowing it. + // must be before TypeTuple + call!(TypeTraitObject::parse, allow_plus) => { Type::TraitObject } + | + syn!(TypeSlice) => { Type::Slice } + | + syn!(TypeArray) => { Type::Array } + | + syn!(TypePtr) => { Type::Ptr } + | + syn!(TypeReference) => { Type::Reference } + | + syn!(TypeBareFn) => { Type::BareFn } + | + syn!(TypeNever) => { Type::Never } + | + syn!(TypeTuple) => { Type::Tuple } + | + syn!(TypeImplTrait) => { Type::ImplTrait } + | + syn!(TypeInfer) => { Type::Infer } + )); + + impl Synom for TypeSlice { + named!(parse -> Self, map!( + brackets!(syn!(Type)), + |(b, ty)| TypeSlice { + elem: Box::new(ty), + bracket_token: b, + } + )); + + fn description() -> Option<&'static str> { + Some("slice type") + } + } + + impl Synom for TypeArray { + named!(parse -> Self, map!( + brackets!(do_parse!( + elem: syn!(Type) >> + semi: punct!(;) >> + len: syn!(Expr) >> + (elem, semi, len) + )), + |(brackets, (elem, semi, len))| { + TypeArray { + elem: Box::new(elem), + len: len, + bracket_token: brackets, + semi_token: semi, + } + } + )); + + fn description() -> Option<&'static str> { + Some("array type") + } + } + + impl Synom for TypePtr { + named!(parse -> Self, do_parse!( + star: punct!(*) >> + mutability: alt!( + keyword!(const) => { |c| (None, Some(c)) } + | + keyword!(mut) => { |m| (Some(m), None) } + ) >> + target: call!(Type::without_plus) >> + (TypePtr { + const_token: mutability.1, + star_token: star, + mutability: mutability.0, + elem: Box::new(target), + }) + )); + + fn description() -> Option<&'static str> { + Some("raw pointer type") + } + } + + impl Synom for TypeReference { + named!(parse -> Self, do_parse!( + amp: punct!(&) >> + life: option!(syn!(Lifetime)) >> + mutability: option!(keyword!(mut)) >> + // & binds tighter than +, so we don't allow + here. + target: call!(Type::without_plus) >> + (TypeReference { + lifetime: life, + mutability: mutability, + elem: Box::new(target), + and_token: amp, + }) + )); + + fn description() -> Option<&'static str> { + Some("reference type") + } + } + + impl Synom for TypeBareFn { + named!(parse -> Self, do_parse!( + lifetimes: option!(syn!(BoundLifetimes)) >> + unsafety: option!(keyword!(unsafe)) >> + abi: option!(syn!(Abi)) >> + fn_: keyword!(fn) >> + parens: parens!(do_parse!( + inputs: call!(Punctuated::parse_terminated) >> + variadic: option!(cond_reduce!(inputs.empty_or_trailing(), punct!(...))) >> + (inputs, variadic) + )) >> + output: syn!(ReturnType) >> + (TypeBareFn { + unsafety: unsafety, + abi: abi, + lifetimes: lifetimes, + output: output, + variadic: (parens.1).1, + fn_token: fn_, + paren_token: parens.0, + inputs: (parens.1).0, + }) + )); + + fn description() -> Option<&'static str> { + Some("`fn` type") + } + } + + impl Synom for TypeNever { + named!(parse -> Self, map!( + punct!(!), + |b| TypeNever { bang_token: b } + )); + + fn description() -> Option<&'static str> { + Some("never type: `!`") + } + } + + impl Synom for TypeInfer { + named!(parse -> Self, map!( + punct!(_), + |u| TypeInfer { underscore_token: u } + )); + + fn description() -> Option<&'static str> { + Some("inferred type: `_`") + } + } + + impl Synom for TypeTuple { + named!(parse -> Self, do_parse!( + data: parens!(Punctuated::parse_terminated) >> + (TypeTuple { + paren_token: data.0, + elems: data.1, + }) + )); + + fn description() -> Option<&'static str> { + Some("tuple type") + } + } + + impl Synom for TypeMacro { + named!(parse -> Self, map!(syn!(Macro), |mac| TypeMacro { mac: mac })); + + fn description() -> Option<&'static str> { + Some("macro invocation") + } + } + + impl Synom for TypePath { + named!(parse -> Self, call!(Self::parse, false)); + + fn description() -> Option<&'static str> { + Some("type path") + } + } + + impl TypePath { + named!(parse(allow_plus: bool) -> Self, do_parse!( + qpath: qpath >> + parenthesized: option!(cond_reduce!( + qpath.1.segments.last().unwrap().value().arguments.is_empty(), + syn!(ParenthesizedGenericArguments) + )) >> + cond!(allow_plus, not!(punct!(+))) >> + ({ + let (qself, mut path) = qpath; + if let Some(parenthesized) = parenthesized { + let parenthesized = PathArguments::Parenthesized(parenthesized); + path.segments.last_mut().unwrap().value_mut().arguments = parenthesized; + } + TypePath { qself: qself, path: path } + }) + )); + } + + impl Synom for ReturnType { + named!(parse -> Self, alt!( + do_parse!( + arrow: punct!(->) >> + ty: syn!(Type) >> + (ReturnType::Type(arrow, Box::new(ty))) + ) + | + epsilon!() => { |_| ReturnType::Default } + )); + + fn description() -> Option<&'static str> { + Some("return type") + } + } + + impl Synom for TypeTraitObject { + named!(parse -> Self, call!(Self::parse, true)); + + fn description() -> Option<&'static str> { + Some("trait object type") + } + } + + fn at_least_one_type(bounds: &Punctuated<TypeParamBound, Token![+]>) -> bool { + for bound in bounds { + if let TypeParamBound::Trait(_) = *bound { + return true; + } + } + false + } + + impl TypeTraitObject { + named!(pub without_plus -> Self, call!(Self::parse, false)); + + // Only allow multiple trait references if allow_plus is true. + named!(parse(allow_plus: bool) -> Self, do_parse!( + dyn_token: option!(keyword!(dyn)) >> + bounds: alt!( + cond_reduce!(allow_plus, Punctuated::parse_terminated_nonempty) + | + syn!(TypeParamBound) => {|x| { + let mut bounds = Punctuated::new(); + bounds.push_value(x); + bounds + }} + ) >> + // Just lifetimes like `'a + 'b` is not a TraitObject. + cond_reduce!(at_least_one_type(&bounds)) >> + (TypeTraitObject { + dyn_token: dyn_token, + bounds: bounds, + }) + )); + } + + impl Synom for TypeImplTrait { + named!(parse -> Self, do_parse!( + impl_: keyword!(impl) >> + // NOTE: rust-lang/rust#34511 includes discussion about whether or + // not + should be allowed in ImplTrait directly without (). + elem: call!(Punctuated::parse_terminated_nonempty) >> + (TypeImplTrait { + impl_token: impl_, + bounds: elem, + }) + )); + + fn description() -> Option<&'static str> { + Some("`impl Trait` type") + } + } + + impl Synom for TypeGroup { + named!(parse -> Self, do_parse!( + data: grouped!(syn!(Type)) >> + (TypeGroup { + group_token: data.0, + elem: Box::new(data.1), + }) + )); + + fn description() -> Option<&'static str> { + Some("type surrounded by invisible delimiters") + } + } + + impl Synom for TypeParen { + named!(parse -> Self, call!(Self::parse, false)); + + fn description() -> Option<&'static str> { + Some("parenthesized type") + } + } + + impl TypeParen { + named!(parse(allow_plus: bool) -> Self, do_parse!( + data: parens!(syn!(Type)) >> + cond!(allow_plus, not!(punct!(+))) >> + (TypeParen { + paren_token: data.0, + elem: Box::new(data.1), + }) + )); + } + + impl Synom for BareFnArg { + named!(parse -> Self, do_parse!( + name: option!(do_parse!( + name: syn!(BareFnArgName) >> + not!(punct!(::)) >> + colon: punct!(:) >> + (name, colon) + )) >> + ty: syn!(Type) >> + (BareFnArg { + name: name, + ty: ty, + }) + )); + + fn description() -> Option<&'static str> { + Some("function type argument") + } + } + + impl Synom for BareFnArgName { + named!(parse -> Self, alt!( + map!(syn!(Ident), BareFnArgName::Named) + | + map!(punct!(_), BareFnArgName::Wild) + )); + + fn description() -> Option<&'static str> { + Some("function argument name") + } + } + + impl Synom for Abi { + named!(parse -> Self, do_parse!( + extern_: keyword!(extern) >> + name: option!(syn!(LitStr)) >> + (Abi { + extern_token: extern_, + name: name, + }) + )); + + fn description() -> Option<&'static str> { + Some("`extern` ABI qualifier") + } + } +} + +#[cfg(feature = "printing")] +mod printing { + use super::*; + use quote::{ToTokens, Tokens}; + + impl ToTokens for TypeSlice { + fn to_tokens(&self, tokens: &mut Tokens) { + self.bracket_token.surround(tokens, |tokens| { + self.elem.to_tokens(tokens); + }); + } + } + + impl ToTokens for TypeArray { + fn to_tokens(&self, tokens: &mut Tokens) { + self.bracket_token.surround(tokens, |tokens| { + self.elem.to_tokens(tokens); + self.semi_token.to_tokens(tokens); + self.len.to_tokens(tokens); + }); + } + } + + impl ToTokens for TypePtr { + fn to_tokens(&self, tokens: &mut Tokens) { + self.star_token.to_tokens(tokens); + match self.mutability { + Some(ref tok) => tok.to_tokens(tokens), + None => { + TokensOrDefault(&self.const_token).to_tokens(tokens); + } + } + self.elem.to_tokens(tokens); + } + } + + impl ToTokens for TypeReference { + fn to_tokens(&self, tokens: &mut Tokens) { + self.and_token.to_tokens(tokens); + self.lifetime.to_tokens(tokens); + self.mutability.to_tokens(tokens); + self.elem.to_tokens(tokens); + } + } + + impl ToTokens for TypeBareFn { + fn to_tokens(&self, tokens: &mut Tokens) { + self.lifetimes.to_tokens(tokens); + self.unsafety.to_tokens(tokens); + self.abi.to_tokens(tokens); + self.fn_token.to_tokens(tokens); + self.paren_token.surround(tokens, |tokens| { + self.inputs.to_tokens(tokens); + if let Some(ref variadic) = self.variadic { + if !self.inputs.empty_or_trailing() { + let span = variadic.0[0]; + <Token![,]>::new(span).to_tokens(tokens); + } + variadic.to_tokens(tokens); + } + }); + self.output.to_tokens(tokens); + } + } + + impl ToTokens for TypeNever { + fn to_tokens(&self, tokens: &mut Tokens) { + self.bang_token.to_tokens(tokens); + } + } + + impl ToTokens for TypeTuple { + fn to_tokens(&self, tokens: &mut Tokens) { + self.paren_token.surround(tokens, |tokens| { + self.elems.to_tokens(tokens); + }); + } + } + + impl ToTokens for TypePath { + fn to_tokens(&self, tokens: &mut Tokens) { + PathTokens(&self.qself, &self.path).to_tokens(tokens); + } + } + + impl ToTokens for TypeTraitObject { + fn to_tokens(&self, tokens: &mut Tokens) { + self.dyn_token.to_tokens(tokens); + self.bounds.to_tokens(tokens); + } + } + + impl ToTokens for TypeImplTrait { + fn to_tokens(&self, tokens: &mut Tokens) { + self.impl_token.to_tokens(tokens); + self.bounds.to_tokens(tokens); + } + } + + impl ToTokens for TypeGroup { + fn to_tokens(&self, tokens: &mut Tokens) { + self.group_token.surround(tokens, |tokens| { + self.elem.to_tokens(tokens); + }); + } + } + + impl ToTokens for TypeParen { + fn to_tokens(&self, tokens: &mut Tokens) { + self.paren_token.surround(tokens, |tokens| { + self.elem.to_tokens(tokens); + }); + } + } + + impl ToTokens for TypeInfer { + fn to_tokens(&self, tokens: &mut Tokens) { + self.underscore_token.to_tokens(tokens); + } + } + + impl ToTokens for TypeMacro { + fn to_tokens(&self, tokens: &mut Tokens) { + self.mac.to_tokens(tokens); + } + } + + impl ToTokens for TypeVerbatim { + fn to_tokens(&self, tokens: &mut Tokens) { + self.tts.to_tokens(tokens); + } + } + + impl ToTokens for ReturnType { + fn to_tokens(&self, tokens: &mut Tokens) { + match *self { + ReturnType::Default => {} + ReturnType::Type(ref arrow, ref ty) => { + arrow.to_tokens(tokens); + ty.to_tokens(tokens); + } + } + } + } + + impl ToTokens for BareFnArg { + fn to_tokens(&self, tokens: &mut Tokens) { + if let Some((ref name, ref colon)) = self.name { + name.to_tokens(tokens); + colon.to_tokens(tokens); + } + self.ty.to_tokens(tokens); + } + } + + impl ToTokens for BareFnArgName { + fn to_tokens(&self, tokens: &mut Tokens) { + match *self { + BareFnArgName::Named(ref t) => t.to_tokens(tokens), + BareFnArgName::Wild(ref t) => t.to_tokens(tokens), + } + } + } + + impl ToTokens for Abi { + fn to_tokens(&self, tokens: &mut Tokens) { + self.extern_token.to_tokens(tokens); + self.name.to_tokens(tokens); + } + } +} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/appveyor.yml cargo-0.26.0/vendor/tar-0.4.14/appveyor.yml --- cargo-0.25.0/vendor/tar-0.4.14/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,20 +0,0 @@ -environment: - matrix: - - TARGET: x86_64-pc-windows-gnu - MSYS_BITS: 64 - - TARGET: i686-pc-windows-gnu - MSYS_BITS: 32 - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc -install: - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" - - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - - if defined MSYS_BITS set PATH=%PATH%;C:\msys64\mingw%MSYS_BITS%\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test --verbose --target %TARGET% diff -Nru cargo-0.25.0/vendor/tar-0.4.14/.cargo-checksum.json cargo-0.26.0/vendor/tar-0.4.14/.cargo-checksum.json --- cargo-0.25.0/vendor/tar-0.4.14/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"1605d3388ceb50252952ffebab4b5dc43017ead7e4481b175961c283bb951195"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/tar-0.4.14/Cargo.toml cargo-0.26.0/vendor/tar-0.4.14/Cargo.toml --- cargo-0.25.0/vendor/tar-0.4.14/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,38 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "tar" -version = "0.4.14" -authors = ["Alex Crichton <alex@alexcrichton.com>"] -description = "A Rust implementation of a TAR file reader and writer. This library does not\ncurrently handle compression, but it is abstract over all I/O readers and\nwriters. Additionally, great lengths are taken to ensure that the entire\ncontents are never required to be entirely resident in memory all at once.\n" -homepage = "https://github.com/alexcrichton/tar-rs" -documentation = "https://docs.rs/tar" -readme = "README.md" -keywords = ["tar", "tarfile", "encoding"] -license = "MIT/Apache-2.0" -repository = "https://github.com/alexcrichton/tar-rs" -[dependencies.filetime] -version = "0.1.5" -[dev-dependencies.tempdir] -version = "0.3" - -[features] -default = ["xattr"] -[target."cfg(target_os = \"redox\")".dependencies.redox_syscall] -version = "0.1" -[target."cfg(unix)".dependencies.libc] -version = "0.2" - -[target."cfg(unix)".dependencies.xattr] -version = "0.1.7" -optional = true diff -Nru cargo-0.25.0/vendor/tar-0.4.14/examples/extract_file.rs cargo-0.26.0/vendor/tar-0.4.14/examples/extract_file.rs --- cargo-0.25.0/vendor/tar-0.4.14/examples/extract_file.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/examples/extract_file.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -//! An example of extracting a file in an archive. -//! -//! Takes a tarball on standard input, looks for an entry with a listed file -//! name as the first argument provided, and then prints the contents of that -//! file to stdout. - -extern crate tar; - -use std::io::{stdin, stdout, copy}; -use std::env::args_os; -use std::path::Path; - -use tar::Archive; - -fn main() { - let first_arg = args_os().skip(1).next().unwrap(); - let filename = Path::new(&first_arg); - let mut ar = Archive::new(stdin()); - for file in ar.entries().unwrap() { - let mut f = file.unwrap(); - if f.path().unwrap() == filename { - copy(&mut f, &mut stdout()).unwrap(); - } - } -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/examples/list.rs cargo-0.26.0/vendor/tar-0.4.14/examples/list.rs --- cargo-0.25.0/vendor/tar-0.4.14/examples/list.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/examples/list.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -//! An example of listing the file names of entries in an archive. -//! -//! Takes a tarball on stdin and prints out all of the entries inside. - -extern crate tar; - -use std::io::stdin; - -use tar::Archive; - -fn main() { - let mut ar = Archive::new(stdin()); - for file in ar.entries().unwrap() { - let f = file.unwrap(); - println!("{}", f.path().unwrap().display()); - } -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/examples/raw_list.rs cargo-0.26.0/vendor/tar-0.4.14/examples/raw_list.rs --- cargo-0.25.0/vendor/tar-0.4.14/examples/raw_list.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/examples/raw_list.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -//! An example of listing raw entries in an archive. -//! -//! Takes a tarball on stdin and prints out all of the entries inside. - -extern crate tar; - -use std::io::stdin; - -use tar::Archive; - -fn main() { - let mut ar = Archive::new(stdin()); - for (i, file) in ar.entries().unwrap().raw(true).enumerate() { - println!("-------------------------- Entry {}", i); - let mut f = file.unwrap(); - println!("path: {}", f.path().unwrap().display()); - println!("size: {}", f.header().size().unwrap()); - println!("entry size: {}", f.header().entry_size().unwrap()); - println!("link name: {:?}", f.link_name().unwrap()); - println!("file type: {:x}", f.header().entry_type().as_byte()); - println!("mode: {:o}", f.header().mode().unwrap()); - println!("uid: {}", f.header().uid().unwrap()); - println!("gid: {}", f.header().gid().unwrap()); - println!("mtime: {}", f.header().mtime().unwrap()); - println!("username: {:?}", f.header().username().unwrap()); - println!("groupname: {:?}", f.header().groupname().unwrap()); - - if f.header().as_ustar().is_some() { - println!("kind: UStar"); - } else if f.header().as_gnu().is_some() { - println!("kind: GNU"); - } else { - println!("kind: normal"); - } - - if let Ok(Some(extensions)) = f.pax_extensions() { - println!("pax extensions:"); - for e in extensions { - let e = e.unwrap(); - println!("\t{:?} = {:?}", - String::from_utf8_lossy(e.key_bytes()), - String::from_utf8_lossy(e.value_bytes())); - } - } - } -} - diff -Nru cargo-0.25.0/vendor/tar-0.4.14/examples/write.rs cargo-0.26.0/vendor/tar-0.4.14/examples/write.rs --- cargo-0.25.0/vendor/tar-0.4.14/examples/write.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/examples/write.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -extern crate tar; - -use std::fs::File; -use tar::Builder; - -fn main() { - let file = File::create("foo.tar").unwrap(); - let mut a = Builder::new(file); - - a.append_path("README.md").unwrap(); - a.append_file("lib.rs", &mut File::open("src/lib.rs").unwrap()).unwrap(); -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/LICENSE-APACHE cargo-0.26.0/vendor/tar-0.4.14/LICENSE-APACHE --- cargo-0.25.0/vendor/tar-0.4.14/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/tar-0.4.14/LICENSE-MIT cargo-0.26.0/vendor/tar-0.4.14/LICENSE-MIT --- cargo-0.25.0/vendor/tar-0.4.14/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 Alex Crichton - -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. diff -Nru cargo-0.25.0/vendor/tar-0.4.14/README.md cargo-0.26.0/vendor/tar-0.4.14/README.md --- cargo-0.25.0/vendor/tar-0.4.14/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,80 +0,0 @@ -# tar-rs - -[![Build Status](https://travis-ci.org/alexcrichton/tar-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/tar-rs) -[![Build status](https://ci.appveyor.com/api/projects/status/0udgokm2fc6ljorj?svg=true)](https://ci.appveyor.com/project/alexcrichton/tar-rs) -[![Coverage Status](https://coveralls.io/repos/alexcrichton/tar-rs/badge.svg?branch=master&service=github)](https://coveralls.io/github/alexcrichton/tar-rs?branch=master) - -[Documentation](https://docs.rs/tar) - -A tar archive reading/writing library for Rust. - -```toml -# Cargo.toml -[dependencies] -tar = "0.4" -``` - -## Reading an archive - -```rust,no_run -extern crate tar; - -use std::io::prelude::*; -use std::fs::File; -use tar::Archive; - -fn main() { - let file = File::open("foo.tar").unwrap(); - let mut a = Archive::new(file); - - for file in a.entries().unwrap() { - // Make sure there wasn't an I/O error - let mut file = file.unwrap(); - - // Inspect metadata about the file - println!("{:?}", file.header().path().unwrap()); - println!("{}", file.header().size().unwrap()); - - // files implement the Read trait - let mut s = String::new(); - file.read_to_string(&mut s).unwrap(); - println!("{}", s); - } -} - -``` - -## Writing an archive - -```rust,no_run -extern crate tar; - -use std::io::prelude::*; -use std::fs::File; -use tar::Builder; - -fn main() { - let file = File::create("foo.tar").unwrap(); - let mut a = Builder::new(file); - - a.append_path("file1.txt").unwrap(); - a.append_file("file2.txt", &mut File::open("file3.txt").unwrap()).unwrap(); -} -``` - -# License - -This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be -dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/tar-0.4.14/src/archive.rs cargo-0.26.0/vendor/tar-0.4.14/src/archive.rs --- cargo-0.25.0/vendor/tar-0.4.14/src/archive.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/src/archive.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,431 +0,0 @@ -use std::cell::{RefCell, Cell}; -use std::cmp; -use std::io::prelude::*; -use std::io; -use std::marker; -use std::path::Path; - -use entry::{EntryFields, EntryIo}; -use error::TarError; -use other; -use {Entry, Header, GnuSparseHeader, GnuExtSparseHeader}; - -/// A top-level representation of an archive file. -/// -/// This archive can have an entry added to it and it can be iterated over. -pub struct Archive<R: ?Sized + Read> { - inner: ArchiveInner<R>, -} - -pub struct ArchiveInner<R: ?Sized> { - pos: Cell<u64>, - unpack_xattrs: bool, - preserve_permissions: bool, - obj: RefCell<::AlignHigher<R>>, -} - -/// An iterator over the entries of an archive. -pub struct Entries<'a, R: 'a + Read> { - fields: EntriesFields<'a>, - _ignored: marker::PhantomData<&'a Archive<R>>, -} - -struct EntriesFields<'a> { - archive: &'a Archive<Read + 'a>, - next: u64, - done: bool, - raw: bool, -} - -impl<R: Read> Archive<R> { - /// Create a new archive with the underlying object as the reader. - pub fn new(obj: R) -> Archive<R> { - Archive { - inner: ArchiveInner { - unpack_xattrs: false, - preserve_permissions: false, - obj: RefCell::new(::AlignHigher(0, obj)), - pos: Cell::new(0), - }, - } - } - - /// Unwrap this archive, returning the underlying object. - pub fn into_inner(self) -> R { - self.inner.obj.into_inner().1 - } - - /// Construct an iterator over the entries in this archive. - /// - /// Note that care must be taken to consider each entry within an archive in - /// sequence. If entries are processed out of sequence (from what the - /// iterator returns), then the contents read for each entry may be - /// corrupted. - pub fn entries(&mut self) -> io::Result<Entries<R>> { - let me: &mut Archive<Read> = self; - me._entries().map(|fields| { - Entries { fields: fields, _ignored: marker::PhantomData } - }) - } - - /// Unpacks the contents tarball into the specified `dst`. - /// - /// This function will iterate over the entire contents of this tarball, - /// extracting each file in turn to the location specified by the entry's - /// path name. - /// - /// This operation is relatively sensitive in that it will not write files - /// outside of the path specified by `dst`. Files in the archive which have - /// a '..' in their path are skipped during the unpacking process. - /// - /// # Examples - /// - /// ```no_run - /// use std::fs::File; - /// use tar::Archive; - /// - /// let mut ar = Archive::new(File::open("foo.tar").unwrap()); - /// ar.unpack("foo").unwrap(); - /// ``` - pub fn unpack<P: AsRef<Path>>(&mut self, dst: P) -> io::Result<()> { - let me: &mut Archive<Read> = self; - me._unpack(dst.as_ref()) - } - - /// Indicate whether extended file attributes (xattrs on Unix) are preserved - /// when unpacking this archive. - /// - /// This flag is disabled by default and is currently only implemented on - /// Unix using xattr support. This may eventually be implemented for - /// Windows, however, if other archive implementations are found which do - /// this as well. - pub fn set_unpack_xattrs(&mut self, unpack_xattrs: bool) { - self.inner.unpack_xattrs = unpack_xattrs; - } - - /// Indicate whether extended permissions (like suid on Unix) are preserved - /// when unpacking this entry. - /// - /// This flag is disabled by default and is currently only implemented on - /// Unix. - pub fn set_preserve_permissions(&mut self, preserve: bool) { - self.inner.preserve_permissions = preserve; - } -} - -impl<'a> Archive<Read + 'a> { - fn _entries(&mut self) -> io::Result<EntriesFields> { - if self.inner.pos.get() != 0 { - return Err(other("cannot call entries unless archive is at \ - position 0")) - } - Ok(EntriesFields { - archive: self, - done: false, - next: 0, - raw: false, - }) - } - - fn _unpack(&mut self, dst: &Path) -> io::Result<()> { - for entry in try!(self._entries()) { - let mut file = try!(entry.map_err(|e| { - TarError::new("failed to iterate over archive", e) - })); - try!(file.unpack_in(dst)); - } - Ok(()) - } - - fn skip(&self, mut amt: u64) -> io::Result<()> { - let mut buf = [0u8; 4096 * 8]; - while amt > 0 { - let n = cmp::min(amt, buf.len() as u64); - let n = try!((&self.inner).read(&mut buf[..n as usize])); - if n == 0 { - return Err(other("unexpected EOF during skip")) - } - amt -= n as u64; - } - Ok(()) - } -} - -impl<'a, R: Read> Entries<'a, R> { - /// Indicates whether this iterator will return raw entries or not. - /// - /// If the raw list of entries are returned, then no preprocessing happens - /// on account of this library, for example taking into accout GNU long name - /// or long link archive members. Raw iteration is disabled by default. - pub fn raw(self, raw: bool) -> Entries<'a, R> { - Entries { - fields: EntriesFields { - raw: raw, - ..self.fields - }, - _ignored: marker::PhantomData, - } - } -} -impl<'a, R: Read> Iterator for Entries<'a, R> { - type Item = io::Result<Entry<'a, R>>; - - fn next(&mut self) -> Option<io::Result<Entry<'a, R>>> { - self.fields.next().map(|result| { - result.map(|e| EntryFields::from(e).into_entry()) - }) - } -} - -impl<'a> EntriesFields<'a> { - fn next_entry_raw(&mut self) -> io::Result<Option<Entry<'a, io::Empty>>> { - // Seek to the start of the next header in the archive - let delta = self.next - self.archive.inner.pos.get(); - try!(self.archive.skip(delta)); - - let header_pos = self.next; - let mut header = Header::new_old(); - try!(read_all(&mut &self.archive.inner, header.as_mut_bytes())); - self.next += 512; - - // If we have an all 0 block, then this should be the start of the end - // of the archive. A block of 0s is never valid as a header (because of - // the checksum), so if it's all zero it must be the first of the two - // end blocks - if header.as_bytes().iter().all(|i| *i == 0) { - try!(read_all(&mut &self.archive.inner, - header.as_mut_bytes())); - self.next += 512; - return if header.as_bytes().iter().all(|i| *i == 0) { - Ok(None) - } else { - Err(other("found block of 0s not followed by a second \ - block of 0s")) - } - } - - // Make sure the checksum is ok - let sum = header.as_bytes()[..148].iter() - .chain(&header.as_bytes()[156..]) - .fold(0, |a, b| a + (*b as u32)) + 8 * 32; - let cksum = try!(header.cksum()); - if sum != cksum { - return Err(other("archive header checksum mismatch")) - } - - let file_pos = self.next; - let size = try!(header.entry_size()); - - let ret = EntryFields { - size: size, - header_pos: header_pos, - file_pos: file_pos, - data: vec![EntryIo::Data((&self.archive.inner).take(size))], - header: header, - long_pathname: None, - long_linkname: None, - pax_extensions: None, - unpack_xattrs: self.archive.inner.unpack_xattrs, - preserve_permissions: self.archive.inner.preserve_permissions, - }; - - // Store where the next entry is, rounding up by 512 bytes (the size of - // a header); - let size = (size + 511) & !(512 - 1); - self.next += size; - - Ok(Some(ret.into_entry())) - } - - fn next_entry(&mut self) -> io::Result<Option<Entry<'a, io::Empty>>> { - if self.raw { - return self.next_entry_raw() - } - - let mut gnu_longname = None; - let mut gnu_longlink = None; - let mut pax_extensions = None; - let mut processed = 0; - loop { - processed += 1; - let entry = match try!(self.next_entry_raw()) { - Some(entry) => entry, - None if processed > 1 => { - return Err(other("members found describing a future member \ - but no future member found")) - } - None => return Ok(None), - }; - - if entry.header().as_gnu().is_some() && - entry.header().entry_type().is_gnu_longname() { - if gnu_longname.is_some() { - return Err(other("two long name entries describing \ - the same member")) - } - gnu_longname = Some(try!(EntryFields::from(entry).read_all())); - continue - } - - if entry.header().as_gnu().is_some() && - entry.header().entry_type().is_gnu_longlink() { - if gnu_longlink.is_some() { - return Err(other("two long name entries describing \ - the same member")) - } - gnu_longlink = Some(try!(EntryFields::from(entry).read_all())); - continue - } - - if entry.header().as_ustar().is_some() && - entry.header().entry_type().is_pax_local_extensions() { - if pax_extensions.is_some() { - return Err(other("two pax extensions entries describing \ - the same member")) - } - pax_extensions = Some(try!(EntryFields::from(entry).read_all())); - continue - } - - let mut fields = EntryFields::from(entry); - fields.long_pathname = gnu_longname; - fields.long_linkname = gnu_longlink; - fields.pax_extensions = pax_extensions; - try!(self.parse_sparse_header(&mut fields)); - return Ok(Some(fields.into_entry())) - } - } - - fn parse_sparse_header(&mut self, - entry: &mut EntryFields<'a>) -> io::Result<()> { - if !entry.header.entry_type().is_gnu_sparse() { - return Ok(()) - } - let gnu = match entry.header.as_gnu() { - Some(gnu) => gnu, - None => return Err(other("sparse entry type listed but not GNU header")), - }; - - // Sparse files are represented internally as a list of blocks that are - // read. Blocks are either a bunch of 0's or they're data from the - // underlying archive. - // - // Blocks of a sparse file are described by the `GnuSparseHeader` - // structure, some of which are contained in `GnuHeader` but some of - // which may also be contained after the first header in further - // headers. - // - // We read off all the blocks here and use the `add_block` function to - // incrementally add them to the list of I/O block (in `entry.data`). - // The `add_block` function also validates that each chunk comes after - // the previous, we don't overrun the end of the file, and each block is - // aligned to a 512-byte boundary in the archive itself. - // - // At the end we verify that the sparse file size (`Header::size`) is - // the same as the current offset (described by the list of blocks) as - // well as the amount of data read equals the size of the entry - // (`Header::entry_size`). - entry.data.truncate(0); - - let mut cur = 0; - let mut remaining = entry.size; - { - let data = &mut entry.data; - let reader = &self.archive.inner; - let size = entry.size; - let mut add_block = |block: &GnuSparseHeader| -> io::Result<_> { - if block.is_empty() { - return Ok(()) - } - let off = try!(block.offset()); - let len = try!(block.length()); - - if (size - remaining) % 512 != 0 { - return Err(other("previous block in sparse file was not \ - aligned to 512-byte boundary")) - } else if off < cur { - return Err(other("out of order or overlapping sparse \ - blocks")) - } else if cur < off { - let block = io::repeat(0).take(off - cur); - data.push(EntryIo::Pad(block)); - } - cur = try!(off.checked_add(len).ok_or_else(|| { - other("more bytes listed in sparse file than u64 can hold") - })); - remaining = try!(remaining.checked_sub(len).ok_or_else(|| { - other("sparse file consumed more data than the header \ - listed") - })); - data.push(EntryIo::Data(reader.take(len))); - Ok(()) - }; - for block in gnu.sparse.iter() { - try!(add_block(block)) - } - if gnu.is_extended() { - let mut ext = GnuExtSparseHeader::new(); - ext.isextended[0] = 1; - while ext.is_extended() { - try!(read_all(&mut &self.archive.inner, ext.as_mut_bytes())); - self.next += 512; - for block in ext.sparse.iter() { - try!(add_block(block)); - } - } - } - } - if cur != try!(gnu.real_size()) { - return Err(other("mismatch in sparse file chunks and \ - size in header")) - } - entry.size = cur; - if remaining > 0 { - return Err(other("mismatch in sparse file chunks and \ - entry size in header")) - } - Ok(()) - } -} - -impl<'a> Iterator for EntriesFields<'a> { - type Item = io::Result<Entry<'a, io::Empty>>; - - fn next(&mut self) -> Option<io::Result<Entry<'a, io::Empty>>> { - if self.done { - None - } else { - match self.next_entry() { - Ok(Some(e)) => Some(Ok(e)), - Ok(None) => { - self.done = true; - None - } - Err(e) => { - self.done = true; - Some(Err(e)) - } - } - } - } -} - -impl<'a, R: ?Sized + Read> Read for &'a ArchiveInner<R> { - fn read(&mut self, into: &mut [u8]) -> io::Result<usize> { - self.obj.borrow_mut().read(into).map(|i| { - self.pos.set(self.pos.get() + i as u64); - i - }) - } -} - -fn read_all<R: Read>(r: &mut R, buf: &mut [u8]) -> io::Result<()> { - let mut read = 0; - while read < buf.len() { - match try!(r.read(&mut buf[read..])) { - 0 => return Err(other("failed to read entire block")), - n => read += n, - } - } - Ok(()) -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/src/builder.rs cargo-0.26.0/vendor/tar-0.4.14/src/builder.rs --- cargo-0.25.0/vendor/tar-0.4.14/src/builder.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/src/builder.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,410 +0,0 @@ -use std::io; -use std::path::Path; -use std::io::prelude::*; -use std::fs; -use std::borrow::Cow; - -use {EntryType, Header, other}; -use header::{bytes2path, HeaderMode, path2bytes}; - -/// A structure for building archives -/// -/// This structure has methods for building up an archive from scratch into any -/// arbitrary writer. -pub struct Builder<W: Write> { - mode: HeaderMode, - follow: bool, - finished: bool, - obj: Option<W>, -} - -impl<W: Write> Builder<W> { - /// Create a new archive builder with the underlying object as the - /// destination of all data written. The builder will use - /// `HeaderMode::Complete` by default. - pub fn new(obj: W) -> Builder<W> { - Builder { - mode: HeaderMode::Complete, - follow: true, - finished: false, - obj: Some(obj), - } - } - - fn inner(&mut self) -> &mut W { - self.obj.as_mut().unwrap() - } - - /// Changes the HeaderMode that will be used when reading fs Metadata for - /// methods that implicitly read metadata for an input Path. Notably, this - /// does _not_ apply to `append(Header)`. - pub fn mode(&mut self, mode: HeaderMode) { - self.mode = mode; - } - - /// Follow symlinks, archiving the contents of the file they point to rather - /// than adding a symlink to the archive. Defaults to true. - pub fn follow_symlinks(&mut self, follow: bool) { - self.follow = follow; - } - - /// Unwrap this archive, returning the underlying object. - /// - /// This function will finish writing the archive if the `finish` function - /// hasn't yet been called, returning any I/O error which happens during - /// that operation. - pub fn into_inner(mut self) -> io::Result<W> { - if !self.finished { - try!(self.finish()); - } - Ok(self.obj.take().unwrap()) - } - - /// Adds a new entry to this archive. - /// - /// This function will append the header specified, followed by contents of - /// the stream specified by `data`. To produce a valid archive the `size` - /// field of `header` must be the same as the length of the stream that's - /// being written. Additionally the checksum for the header should have been - /// set via the `set_cksum` method. - /// - /// Note that this will not attempt to seek the archive to a valid position, - /// so if the archive is in the middle of a read or some other similar - /// operation then this may corrupt the archive. - /// - /// Also note that after all entries have been written to an archive the - /// `finish` function needs to be called to finish writing the archive. - /// - /// # Errors - /// - /// This function will return an error for any intermittent I/O error which - /// occurs when either reading or writing. - /// - /// # Examples - /// - /// ``` - /// use tar::{Builder, Header}; - /// - /// let mut header = Header::new_gnu(); - /// header.set_path("foo").unwrap(); - /// header.set_size(4); - /// header.set_cksum(); - /// - /// let mut data: &[u8] = &[1, 2, 3, 4]; - /// - /// let mut ar = Builder::new(Vec::new()); - /// ar.append(&header, data).unwrap(); - /// let data = ar.into_inner().unwrap(); - /// ``` - pub fn append<R: Read>(&mut self, header: &Header, mut data: R) - -> io::Result<()> { - append(self.inner(), header, &mut data) - } - - /// Adds a new entry to this archive with the specified path. - /// - /// This function will set the specified path in the given header, which may - /// require appending a GNU long-name extension entry to the archive first. - /// The checksum for the header will be automatically updated via the - /// `set_cksum` method after setting the path. No other metadata in the - /// header will be modified. - /// - /// Then it will append the header, followed by contents of the stream - /// specified by `data`. To produce a valid archive the `size` field of - /// `header` must be the same as the length of the stream that's being - /// written. - /// - /// Note that this will not attempt to seek the archive to a valid position, - /// so if the archive is in the middle of a read or some other similar - /// operation then this may corrupt the archive. - /// - /// Also note that after all entries have been written to an archive the - /// `finish` function needs to be called to finish writing the archive. - /// - /// # Errors - /// - /// This function will return an error for any intermittent I/O error which - /// occurs when either reading or writing. - /// - /// # Examples - /// - /// ``` - /// use tar::{Builder, Header}; - /// - /// let mut header = Header::new_gnu(); - /// header.set_size(4); - /// header.set_cksum(); - /// - /// let mut data: &[u8] = &[1, 2, 3, 4]; - /// - /// let mut ar = Builder::new(Vec::new()); - /// ar.append_data(&mut header, "really/long/path/to/foo", data).unwrap(); - /// let data = ar.into_inner().unwrap(); - /// ``` - pub fn append_data<P: AsRef<Path>, R: Read>(&mut self, header: &mut Header, path: P, data: R) - -> io::Result<()> { - try!(prepare_header(self.inner(), header, path.as_ref())); - header.set_cksum(); - self.append(&header, data) - } - - /// Adds a file on the local filesystem to this archive. - /// - /// This function will open the file specified by `path` and insert the file - /// into the archive with the appropriate metadata set, returning any I/O - /// error which occurs while writing. The path name for the file inside of - /// this archive will be the same as `path`, and it is required that the - /// path is a relative path. - /// - /// Note that this will not attempt to seek the archive to a valid position, - /// so if the archive is in the middle of a read or some other similar - /// operation then this may corrupt the archive. - /// - /// Also note that after all files have been written to an archive the - /// `finish` function needs to be called to finish writing the archive. - /// - /// # Examples - /// - /// ```no_run - /// use tar::Builder; - /// - /// let mut ar = Builder::new(Vec::new()); - /// - /// ar.append_path("foo/bar.txt").unwrap(); - /// ``` - pub fn append_path<P: AsRef<Path>>(&mut self, path: P) -> io::Result<()> { - let mode = self.mode.clone(); - let follow = self.follow; - append_path(self.inner(), path.as_ref(), mode, follow) - } - - /// Adds a file to this archive with the given path as the name of the file - /// in the archive. - /// - /// This will use the metadata of `file` to populate a `Header`, and it will - /// then append the file to the archive with the name `path`. - /// - /// Note that this will not attempt to seek the archive to a valid position, - /// so if the archive is in the middle of a read or some other similar - /// operation then this may corrupt the archive. - /// - /// Also note that after all files have been written to an archive the - /// `finish` function needs to be called to finish writing the archive. - /// - /// # Examples - /// - /// ```no_run - /// use std::fs::File; - /// use tar::Builder; - /// - /// let mut ar = Builder::new(Vec::new()); - /// - /// // Open the file at one location, but insert it into the archive with a - /// // different name. - /// let mut f = File::open("foo/bar/baz.txt").unwrap(); - /// ar.append_file("bar/baz.txt", &mut f).unwrap(); - /// ``` - pub fn append_file<P: AsRef<Path>>(&mut self, path: P, file: &mut fs::File) - -> io::Result<()> { - let mode = self.mode.clone(); - append_file(self.inner(), path.as_ref(), file, mode) - } - - /// Adds a directory to this archive with the given path as the name of the - /// directory in the archive. - /// - /// This will use `stat` to populate a `Header`, and it will then append the - /// directory to the archive with the name `path`. - /// - /// Note that this will not attempt to seek the archive to a valid position, - /// so if the archive is in the middle of a read or some other similar - /// operation then this may corrupt the archive. - /// - /// Also note that after all files have been written to an archive the - /// `finish` function needs to be called to finish writing the archive. - /// - /// # Examples - /// - /// ``` - /// use std::fs; - /// use tar::Builder; - /// - /// let mut ar = Builder::new(Vec::new()); - /// - /// // Use the directory at one location, but insert it into the archive - /// // with a different name. - /// ar.append_dir("bardir", ".").unwrap(); - /// ``` - pub fn append_dir<P, Q>(&mut self, path: P, src_path: Q) -> io::Result<()> - where P: AsRef<Path>, Q: AsRef<Path> - { - let mode = self.mode.clone(); - append_dir(self.inner(), path.as_ref(), src_path.as_ref(), mode) - } - - /// Adds a directory and all of its contents (recursively) to this archive - /// with the given path as the name of the directory in the archive. - /// - /// Note that this will not attempt to seek the archive to a valid position, - /// so if the archive is in the middle of a read or some other similar - /// operation then this may corrupt the archive. - /// - /// Also note that after all files have been written to an archive the - /// `finish` function needs to be called to finish writing the archive. - /// - /// # Examples - /// - /// ``` - /// use std::fs; - /// use tar::Builder; - /// - /// let mut ar = Builder::new(Vec::new()); - /// - /// // Use the directory at one location, but insert it into the archive - /// // with a different name. - /// ar.append_dir_all("bardir", ".").unwrap(); - /// ``` - pub fn append_dir_all<P, Q>(&mut self, path: P, src_path: Q) -> io::Result<()> - where P: AsRef<Path>, Q: AsRef<Path> - { - let mode = self.mode.clone(); - let follow = self.follow; - append_dir_all(self.inner(), path.as_ref(), src_path.as_ref(), mode, follow) - } - - /// Finish writing this archive, emitting the termination sections. - /// - /// This function should only be called when the archive has been written - /// entirely and if an I/O error happens the underlying object still needs - /// to be acquired. - /// - /// In most situations the `into_inner` method should be preferred. - pub fn finish(&mut self) -> io::Result<()> { - if self.finished { - return Ok(()) - } - self.finished = true; - self.inner().write_all(&[0; 1024]) - } -} - -fn append(mut dst: &mut Write, - header: &Header, - mut data: &mut Read) -> io::Result<()> { - try!(dst.write_all(header.as_bytes())); - let len = try!(io::copy(&mut data, &mut dst)); - - // Pad with zeros if necessary. - let buf = [0; 512]; - let remaining = 512 - (len % 512); - if remaining < 512 { - try!(dst.write_all(&buf[..remaining as usize])); - } - - Ok(()) -} - -fn append_path(dst: &mut Write, path: &Path, mode: HeaderMode, follow: bool) -> io::Result<()> { - let stat = if follow { - try!(fs::metadata(path)) - } else { - try!(fs::symlink_metadata(path)) - }; - if stat.is_file() { - append_fs(dst, path, &stat, &mut try!(fs::File::open(path)), mode, None) - } else if stat.is_dir() { - append_fs(dst, path, &stat, &mut io::empty(), mode, None) - } else if stat.file_type().is_symlink() { - let link_name = try!(fs::read_link(path)); - append_fs(dst, path, &stat, &mut io::empty(), mode, Some(&link_name)) - } else { - Err(other("path has unknown file type")) - } -} - -fn append_file(dst: &mut Write, path: &Path, file: &mut fs::File, mode: HeaderMode) - -> io::Result<()> { - let stat = try!(file.metadata()); - append_fs(dst, path, &stat, file, mode, None) -} - -fn append_dir(dst: &mut Write, path: &Path, src_path: &Path, mode: HeaderMode) -> io::Result<()> { - let stat = try!(fs::metadata(src_path)); - append_fs(dst, path, &stat, &mut io::empty(), mode, None) -} - -fn prepare_header(dst: &mut Write, header: &mut Header, path: &Path) -> io::Result<()> { - // Try to encode the path directly in the header, but if it ends up not - // working (e.g. it's too long) then use the GNU-specific long name - // extension by emitting an entry which indicates that it's the filename - if let Err(e) = header.set_path(path) { - let data = try!(path2bytes(&path)); - let max = header.as_old().name.len(); - if data.len() < max { - return Err(e) - } - let mut header2 = Header::new_gnu(); - header2.as_gnu_mut().unwrap().name[..13].clone_from_slice(b"././@LongLink"); - header2.set_mode(0o644); - header2.set_uid(0); - header2.set_gid(0); - header2.set_mtime(0); - header2.set_size((data.len() + 1) as u64); - header2.set_entry_type(EntryType::new(b'L')); - header2.set_cksum(); - let mut data2 = data.chain(io::repeat(0).take(0)); - try!(append(dst, &header2, &mut data2)); - // Truncate the path to store in the header we're about to emit to - // ensure we've got something at least mentioned. - let path = try!(bytes2path(Cow::Borrowed(&data[..max]))); - try!(header.set_path(&path)); - } - Ok(()) -} - -fn append_fs(dst: &mut Write, - path: &Path, - meta: &fs::Metadata, - read: &mut Read, - mode: HeaderMode, - link_name: Option<&Path>) -> io::Result<()> { - let mut header = Header::new_gnu(); - - try!(prepare_header(dst, &mut header, path)); - header.set_metadata_in_mode(meta, mode); - if let Some(link_name) = link_name { - try!(header.set_link_name(link_name)); - } - header.set_cksum(); - append(dst, &header, read) -} - -fn append_dir_all(dst: &mut Write, path: &Path, src_path: &Path, mode: HeaderMode, follow: bool) -> io::Result<()> { - let mut stack = vec![(src_path.to_path_buf(), true, false)]; - while let Some((src, is_dir, is_symlink)) = stack.pop() { - let dest = path.join(src.strip_prefix(&src_path).unwrap()); - if is_dir { - for entry in try!(fs::read_dir(&src)) { - let entry = try!(entry); - let file_type = try!(entry.file_type()); - stack.push((entry.path(), file_type.is_dir(), file_type.is_symlink())); - } - if dest != Path::new("") { - try!(append_dir(dst, &dest, &src, mode)); - } - } else if !follow && is_symlink { - let stat = try!(fs::symlink_metadata(&src)); - let link_name = try!(fs::read_link(&src)); - try!(append_fs(dst, &dest, &stat, &mut io::empty(), mode, Some(&link_name))); - } else { - try!(append_file(dst, &dest, &mut try!(fs::File::open(src)), mode)); - } - } - Ok(()) -} - -impl<W: Write> Drop for Builder<W> { - fn drop(&mut self) { - let _ = self.finish(); - } -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/src/entry.rs cargo-0.26.0/vendor/tar-0.4.14/src/entry.rs --- cargo-0.25.0/vendor/tar-0.4.14/src/entry.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/src/entry.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,563 +0,0 @@ -use std::borrow::Cow; -use std::cmp; -use std::fs; -use std::io::prelude::*; -use std::io::{self, Error, ErrorKind, SeekFrom}; -use std::marker; -use std::path::{Component, Path}; - -use filetime::{self, FileTime}; - -use {Header, Archive, PaxExtensions}; -use archive::ArchiveInner; -use error::TarError; -use header::bytes2path; -use other; -use pax::pax_extensions; - -/// A read-only view into an entry of an archive. -/// -/// This structure is a window into a portion of a borrowed archive which can -/// be inspected. It acts as a file handle by implementing the Reader trait. An -/// entry cannot be rewritten once inserted into an archive. -pub struct Entry<'a, R: 'a + Read> { - fields: EntryFields<'a>, - _ignored: marker::PhantomData<&'a Archive<R>>, -} - -// private implementation detail of `Entry`, but concrete (no type parameters) -// and also all-public to be constructed from other modules. -pub struct EntryFields<'a> { - pub long_pathname: Option<Vec<u8>>, - pub long_linkname: Option<Vec<u8>>, - pub pax_extensions: Option<Vec<u8>>, - pub header: Header, - pub size: u64, - pub header_pos: u64, - pub file_pos: u64, - pub data: Vec<EntryIo<'a>>, - pub unpack_xattrs: bool, - pub preserve_permissions: bool, -} - -pub enum EntryIo<'a> { - Pad(io::Take<io::Repeat>), - Data(io::Take<&'a ArchiveInner<Read + 'a>>), -} - -impl<'a, R: Read> Entry<'a, R> { - /// Returns the path name for this entry. - /// - /// This method may fail if the pathname is not valid unicode and this is - /// called on a Windows platform. - /// - /// Note that this function will convert any `\` characters to directory - /// separators, and it will not always return the same value as - /// `self.header().path()` as some archive formats have support for longer - /// path names described in separate entries. - /// - /// It is recommended to use this method instead of inspecting the `header` - /// directly to ensure that various archive formats are handled correctly. - pub fn path(&self) -> io::Result<Cow<Path>> { - self.fields.path() - } - - /// Returns the raw bytes listed for this entry. - /// - /// Note that this function will convert any `\` characters to directory - /// separators, and it will not always return the same value as - /// `self.header().path_bytes()` as some archive formats have support for - /// longer path names described in separate entries. - pub fn path_bytes(&self) -> Cow<[u8]> { - self.fields.path_bytes() - } - - /// Returns the link name for this entry, if any is found. - /// - /// This method may fail if the pathname is not valid unicode and this is - /// called on a Windows platform. `Ok(None)` being returned, however, - /// indicates that the link name was not present. - /// - /// Note that this function will convert any `\` characters to directory - /// separators, and it will not always return the same value as - /// `self.header().link_name()` as some archive formats have support for - /// longer path names described in separate entries. - /// - /// It is recommended to use this method instead of inspecting the `header` - /// directly to ensure that various archive formats are handled correctly. - pub fn link_name(&self) -> io::Result<Option<Cow<Path>>> { - self.fields.link_name() - } - - /// Returns the link name for this entry, in bytes, if listed. - /// - /// Note that this will not always return the same value as - /// `self.header().link_name_bytes()` as some archive formats have support for - /// longer path names described in separate entries. - pub fn link_name_bytes(&self) -> Option<Cow<[u8]>> { - self.fields.link_name_bytes() - } - - /// Returns an iterator over the pax extensions contained in this entry. - /// - /// Pax extensions are a form of archive where extra metadata is stored in - /// key/value pairs in entries before the entry they're intended to - /// describe. For example this can be used to describe long file name or - /// other metadata like atime/ctime/mtime in more precision. - /// - /// The returned iterator will yield key/value pairs for each extension. - /// - /// `None` will be returned if this entry does not indicate that it itself - /// contains extensions, or if there were no previous extensions describing - /// it. - /// - /// Note that global pax extensions are intended to be applied to all - /// archive entries. - /// - /// Also note that this function will read the entire entry if the entry - /// itself is a list of extensions. - pub fn pax_extensions(&mut self) -> io::Result<Option<PaxExtensions>> { - self.fields.pax_extensions() - } - - /// Returns access to the header of this entry in the archive. - /// - /// This provides access to the the metadata for this entry in the archive. - pub fn header(&self) -> &Header { - &self.fields.header - } - - /// Returns the starting position, in bytes, of the header of this entry in - /// the archive. - /// - /// The header is always a contiguous section of 512 bytes, so if the - /// underlying reader implements `Seek`, then the slice from `header_pos` to - /// `header_pos + 512` contains the raw header bytes. - pub fn raw_header_position(&self) -> u64 { - self.fields.header_pos - } - - /// Returns the starting position, in bytes, of the file of this entry in - /// the archive. - /// - /// If the file of this entry is continuous (e.g. not a sparse file), and - /// if the underlying reader implements `Seek`, then the slice from - /// `file_pos` to `file_pos + entry_size` contains the raw file bytes. - pub fn raw_file_position(&self) -> u64 { - self.fields.file_pos - } - - /// Writes this file to the specified location. - /// - /// This function will write the entire contents of this file into the - /// location specified by `dst`. Metadata will also be propagated to the - /// path `dst`. - /// - /// This function will create a file at the path `dst`, and it is required - /// that the intermediate directories are created. Any existing file at the - /// location `dst` will be overwritten. - /// - /// > **Note**: This function does not have as many sanity checks as - /// > `Archive::unpack` or `Entry::unpack_in`. As a result if you're - /// > thinking of unpacking untrusted tarballs you may want to review the - /// > implementations of the previous two functions and perhaps implement - /// > similar logic yourself. - /// - /// # Examples - /// - /// ```no_run - /// use std::fs::File; - /// use tar::Archive; - /// - /// let mut ar = Archive::new(File::open("foo.tar").unwrap()); - /// - /// for (i, file) in ar.entries().unwrap().enumerate() { - /// let mut file = file.unwrap(); - /// file.unpack(format!("file-{}", i)).unwrap(); - /// } - /// ``` - pub fn unpack<P: AsRef<Path>>(&mut self, dst: P) -> io::Result<()> { - self.fields.unpack(None, dst.as_ref()) - } - - /// Extracts this file under the specified path, avoiding security issues. - /// - /// This function will write the entire contents of this file into the - /// location obtained by appending the path of this file in the archive to - /// `dst`, creating any intermediate directories if needed. Metadata will - /// also be propagated to the path `dst`. Any existing file at the location - /// `dst` will be overwritten. - /// - /// This function carefully avoids writing outside of `dst`. If the file has - /// a '..' in its path, this function will skip it and return false. - /// - /// # Examples - /// - /// ```no_run - /// use std::fs::File; - /// use tar::Archive; - /// - /// let mut ar = Archive::new(File::open("foo.tar").unwrap()); - /// - /// for (i, file) in ar.entries().unwrap().enumerate() { - /// let mut file = file.unwrap(); - /// file.unpack_in("target").unwrap(); - /// } - /// ``` - pub fn unpack_in<P: AsRef<Path>>(&mut self, dst: P) -> io::Result<bool> { - self.fields.unpack_in(dst.as_ref()) - } - - /// Indicate whether extended file attributes (xattrs on Unix) are preserved - /// when unpacking this entry. - /// - /// This flag is disabled by default and is currently only implemented on - /// Unix using xattr support. This may eventually be implemented for - /// Windows, however, if other archive implementations are found which do - /// this as well. - pub fn set_unpack_xattrs(&mut self, unpack_xattrs: bool) { - self.fields.unpack_xattrs = unpack_xattrs; - } - - /// Indicate whether extended permissions (like suid on Unix) are preserved - /// when unpacking this entry. - /// - /// This flag is disabled by default and is currently only implemented on - /// Unix. - pub fn set_preserve_permissions(&mut self, preserve: bool) { - self.fields.preserve_permissions = preserve; - } -} - -impl<'a, R: Read> Read for Entry<'a, R> { - fn read(&mut self, into: &mut [u8]) -> io::Result<usize> { - self.fields.read(into) - } -} - -impl<'a> EntryFields<'a> { - pub fn from<R: Read>(entry: Entry<R>) -> EntryFields { - entry.fields - } - - pub fn into_entry<R: Read>(self) -> Entry<'a, R> { - Entry { - fields: self, - _ignored: marker::PhantomData, - } - } - - pub fn read_all(&mut self) -> io::Result<Vec<u8>> { - // Preallocate some data but don't let ourselves get too crazy now. - let cap = cmp::min(self.size, 128 * 1024); - let mut v = Vec::with_capacity(cap as usize); - self.read_to_end(&mut v).map(|_| v) - } - - fn path(&self) -> io::Result<Cow<Path>> { - bytes2path(self.path_bytes()) - } - - fn path_bytes(&self) -> Cow<[u8]> { - match self.long_pathname { - Some(ref bytes) => { - if let Some(&0) = bytes.last() { - Cow::Borrowed(&bytes[..bytes.len() - 1]) - } else { - Cow::Borrowed(bytes) - } - } - None => self.header.path_bytes(), - } - } - - fn link_name(&self) -> io::Result<Option<Cow<Path>>> { - match self.link_name_bytes() { - Some(bytes) => bytes2path(bytes).map(Some), - None => Ok(None), - } - } - - fn link_name_bytes(&self) -> Option<Cow<[u8]>> { - match self.long_linkname { - Some(ref bytes) => { - if let Some(&0) = bytes.last() { - Some(Cow::Borrowed(&bytes[..bytes.len() - 1])) - } else { - Some(Cow::Borrowed(bytes)) - } - } - None => self.header.link_name_bytes(), - } - } - - fn pax_extensions(&mut self) -> io::Result<Option<PaxExtensions>> { - if self.pax_extensions.is_none() { - if !self.header.entry_type().is_pax_global_extensions() && - !self.header.entry_type().is_pax_local_extensions() { - return Ok(None) - } - self.pax_extensions = Some(try!(self.read_all())); - } - Ok(Some(pax_extensions(self.pax_extensions.as_ref().unwrap()))) - } - - fn unpack_in(&mut self, dst: &Path) -> io::Result<bool> { - // Notes regarding bsdtar 2.8.3 / libarchive 2.8.3: - // * Leading '/'s are trimmed. For example, `///test` is treated as - // `test`. - // * If the filename contains '..', then the file is skipped when - // extracting the tarball. - // * '//' within a filename is effectively skipped. An error is - // logged, but otherwise the effect is as if any two or more - // adjacent '/'s within the filename were consolidated into one - // '/'. - // - // Most of this is handled by the `path` module of the standard - // library, but we specially handle a few cases here as well. - - let mut file_dst = dst.to_path_buf(); - { - let path = try!(self.path().map_err(|e| { - TarError::new("invalid path in entry header", e) - })); - for part in path.components() { - match part { - // Leading '/' characters, root paths, and '.' - // components are just ignored and treated as "empty - // components" - Component::Prefix(..) | - Component::RootDir | - Component::CurDir => continue, - - // If any part of the filename is '..', then skip over - // unpacking the file to prevent directory traversal - // security issues. See, e.g.: CVE-2001-1267, - // CVE-2002-0399, CVE-2005-1918, CVE-2007-4131 - Component::ParentDir => return Ok(false), - - Component::Normal(part) => file_dst.push(part), - } - } - } - - // Skip cases where only slashes or '.' parts were seen, because - // this is effectively an empty filename. - if *dst == *file_dst { - return Ok(true); - } - - // Skip entries without a parent (i.e. outside of FS root) - let parent = match file_dst.parent() { - Some(p) => p, - None => return Ok(false), - }; - - if !parent.exists() { - try!(fs::create_dir_all(&parent).map_err(|e| { - TarError::new(&format!("failed to create `{}`", - parent.display()), e) - })); - } - - // Abort if target (canonical) parent is outside of `dst` - let canon_parent = try!(parent.canonicalize()); - let canon_target = try!(dst.canonicalize()); - if !canon_parent.starts_with(&canon_target) { - return Err(TarError::new("trying to unpack outside of destination path", - Error::new(ErrorKind::Other, "Invalid argument")).into()); - } - - try!(self.unpack(Some(&canon_target), &file_dst).map_err(|e| { - TarError::new(&format!("failed to unpack `{}`", - file_dst.display()), e) - })); - - Ok(true) - } - - /// Returns access to the header of this entry in the archive. - fn unpack(&mut self, - target_base: Option<&Path>, - dst: &Path) -> io::Result<()> { - let kind = self.header.entry_type(); - if kind.is_dir() { - // If the directory already exists just let it slide - let prev = fs::metadata(&dst); - if prev.map(|m| m.is_dir()).unwrap_or(false) { - return Ok(()) - } - return fs::create_dir(&dst) - } else if kind.is_hard_link() || kind.is_symlink() { - let src = match try!(self.link_name()) { - Some(name) => name, - None => return Err(other("hard link listed but no link \ - name found")) - }; - - if src.iter().count() == 0 { - return Err(other("symlink destination is empty")) - } - - return if kind.is_hard_link() { - let link_src = match target_base { - None => src.into_owned(), - Some(ref p) => p.join(src), - }; - fs::hard_link(&link_src, dst) - } else { - symlink(&src, dst) - }; - - #[cfg(windows)] - fn symlink(src: &Path, dst: &Path) -> io::Result<()> { - ::std::os::windows::fs::symlink_file(src, dst) - } - #[cfg(any(unix, target_os = "redox"))] - fn symlink(src: &Path, dst: &Path) -> io::Result<()> { - ::std::os::unix::fs::symlink(src, dst) - } - } else if kind.is_pax_global_extensions() || - kind.is_pax_local_extensions() || - kind.is_gnu_longname() || - kind.is_gnu_longlink() { - return Ok(()) - }; - - // Note the lack of `else` clause above. According to the FreeBSD - // documentation: - // - // > A POSIX-compliant implementation must treat any unrecognized - // > typeflag value as a regular file. - // - // As a result if we don't recognize the kind we just write out the file - // as we would normally. - - try!(fs::File::create(dst).and_then(|mut f| { - for io in self.data.drain(..) { - match io { - EntryIo::Data(mut d) => { - let expected = d.limit(); - if try!(io::copy(&mut d, &mut f)) != expected { - return Err(other("failed to write entire file")); - } - } - EntryIo::Pad(d) => { - // TODO: checked cast to i64 - let to = SeekFrom::Current(d.limit() as i64); - let size = try!(f.seek(to)); - try!(f.set_len(size)); - } - } - } - Ok(()) - }).map_err(|e| { - let header = self.header.path_bytes(); - TarError::new(&format!("failed to unpack `{}` into `{}`", - String::from_utf8_lossy(&header), - dst.display()), e) - })); - - if let Ok(mtime) = self.header.mtime() { - let mtime = FileTime::from_seconds_since_1970(mtime, 0); - try!(filetime::set_file_times(dst, mtime, mtime).map_err(|e| { - TarError::new(&format!("failed to set mtime for `{}`", - dst.display()), e) - })); - } - if let Ok(mode) = self.header.mode() { - try!(set_perms(dst, mode, self.preserve_permissions).map_err(|e| { - TarError::new(&format!("failed to set permissions to {:o} \ - for `{}`", mode, dst.display()), e) - })); - } - if self.unpack_xattrs { - try!(set_xattrs(self, dst)); - } - return Ok(()); - - #[cfg(any(unix, target_os = "redox"))] - fn set_perms(dst: &Path, mode: u32, preserve: bool) -> io::Result<()> { - use std::os::unix::prelude::*; - - let mode = if preserve { - mode - } else { - mode & 0o777 - }; - - let perm = fs::Permissions::from_mode(mode as _); - fs::set_permissions(dst, perm) - } - #[cfg(windows)] - fn set_perms(dst: &Path, mode: u32, _preserve: bool) -> io::Result<()> { - let mut perm = try!(fs::metadata(dst)).permissions(); - perm.set_readonly(mode & 0o200 != 0o200); - fs::set_permissions(dst, perm) - } - - #[cfg(all(unix, feature = "xattr"))] - fn set_xattrs(me: &mut EntryFields, dst: &Path) -> io::Result<()> { - use std::os::unix::prelude::*; - use std::ffi::OsStr; - use xattr; - - let exts = match me.pax_extensions() { - Ok(Some(e)) => e, - _ => return Ok(()), - }; - let exts = exts.filter_map(|e| e.ok()).filter_map(|e| { - let key = e.key_bytes(); - let prefix = b"SCHILY.xattr."; - if key.starts_with(prefix) { - Some((&key[prefix.len()..], e)) - } else { - None - } - }).map(|(key, e)| { - (OsStr::from_bytes(key), e.value_bytes()) - }); - - for (key, value) in exts { - try!(xattr::set(dst, key, value).map_err(|e| { - TarError::new(&format!("failed to set extended \ - attributes to {}. \ - Xattrs: key={:?}, value={:?}.", - dst.display(), - key, - String::from_utf8_lossy(value)), - e) - })); - } - - Ok(()) - } - // Windows does not completely support posix xattrs - // https://en.wikipedia.org/wiki/Extended_file_attributes#Windows_NT - #[cfg(any(windows, target_os = "redox", not(feature = "xattr")))] - fn set_xattrs(_: &mut EntryFields, _: &Path) -> io::Result<()> { - Ok(()) - } - } -} - -impl<'a> Read for EntryFields<'a> { - fn read(&mut self, into: &mut [u8]) -> io::Result<usize> { - loop { - match self.data.get_mut(0).map(|io| io.read(into)) { - Some(Ok(0)) => { self.data.remove(0); } - Some(r) => return r, - None => return Ok(0), - } - } - } -} - -impl<'a> Read for EntryIo<'a> { - fn read(&mut self, into: &mut [u8]) -> io::Result<usize> { - match *self { - EntryIo::Pad(ref mut io) => io.read(into), - EntryIo::Data(ref mut io) => io.read(into), - } - } -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/src/entry_type.rs cargo-0.26.0/vendor/tar-0.4.14/src/entry_type.rs --- cargo-0.25.0/vendor/tar-0.4.14/src/entry_type.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/src/entry_type.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,194 +0,0 @@ -// See https://en.wikipedia.org/wiki/Tar_%28computing%29#UStar_format -/// Indicate for the type of file described by a header. -/// -/// Each `Header` has an `entry_type` method returning an instance of this type -/// which can be used to inspect what the header is describing. - -/// A non-exhaustive enum representing the possible entry types -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub enum EntryType { - /// Regular file - Regular, - /// Hard link - Link, - /// Symbolic link - Symlink, - /// Character device - Char, - /// Block device - Block, - /// Directory - Directory, - /// Named pipe (fifo) - Fifo, - /// Implementation-defined 'high-performance' type, treated as regular file - Continuous, - /// GNU extension - long file name - GNULongName, - /// GNU extension - long link name (link target) - GNULongLink, - /// GNU extension - sparse file - GNUSparse, - /// Global extended header - XGlobalHeader, - /// Extended Header - XHeader, - /// Hints that destructuring should not be exhaustive. - /// - /// This enum may grow additional variants, so this makes sure clients - /// don't count on exhaustive matching. (Otherwise, adding a new variant - /// could break existing code.) - #[doc(hidden)] - __Nonexhaustive(u8), -} - -impl EntryType { - /// Creates a new entry type from a raw byte. - /// - /// Note that the other named constructors of entry type may be more - /// appropriate to create a file type from. - pub fn new(byte: u8) -> EntryType { - match byte { - b'\x00' | - b'0' => EntryType::Regular, - b'1' => EntryType::Link, - b'2' => EntryType::Symlink, - b'3' => EntryType::Char, - b'4' => EntryType::Block, - b'5' => EntryType::Directory, - b'6' => EntryType::Fifo, - b'7' => EntryType::Continuous, - b'x' => EntryType::XHeader, - b'g' => EntryType::XGlobalHeader, - b'L' => EntryType::GNULongName, - b'K' => EntryType::GNULongLink, - b'S' => EntryType::GNUSparse, - b => EntryType::__Nonexhaustive(b), - } - } - - /// Returns the raw underlying byte that this entry type represents. - pub fn as_byte(&self) -> u8 { - match *self { - EntryType::Regular => b'0', - EntryType::Link => b'1', - EntryType::Symlink => b'2', - EntryType::Char => b'3', - EntryType::Block => b'4', - EntryType::Directory => b'5', - EntryType::Fifo => b'6', - EntryType::Continuous => b'7', - EntryType::XHeader => b'x', - EntryType::XGlobalHeader => b'g', - EntryType::GNULongName => b'L', - EntryType::GNULongLink => b'K', - EntryType::GNUSparse => b'S', - EntryType::__Nonexhaustive(b) => b, - } - } - - /// Creates a new entry type representing a regular file. - pub fn file() -> EntryType { - EntryType::Regular - } - - /// Creates a new entry type representing a hard link. - pub fn hard_link() -> EntryType { - EntryType::Link - } - - /// Creates a new entry type representing a symlink. - pub fn symlink() -> EntryType { - EntryType::Symlink - } - - /// Creates a new entry type representing a character special device. - pub fn character_special() -> EntryType { - EntryType::Char - } - - /// Creates a new entry type representing a block special device. - pub fn block_special() -> EntryType { - EntryType::Block - } - - /// Creates a new entry type representing a directory. - pub fn dir() -> EntryType { - EntryType::Directory - } - - /// Creates a new entry type representing a FIFO. - pub fn fifo() -> EntryType { - EntryType::Fifo - } - - /// Creates a new entry type representing a contiguous file. - pub fn contiguous() -> EntryType { - EntryType::Continuous - } - - /// Returns whether this type represents a regular file. - pub fn is_file(&self) -> bool { - self == &EntryType::Regular - } - - /// Returns whether this type represents a hard link. - pub fn is_hard_link(&self) -> bool { - self == &EntryType::Link - } - - /// Returns whether this type represents a symlink. - pub fn is_symlink(&self) -> bool { - self == &EntryType::Symlink - } - - /// Returns whether this type represents a character special device. - pub fn is_character_special(&self) -> bool { - self == &EntryType::Char - } - - /// Returns whether this type represents a block special device. - pub fn is_block_special(&self) -> bool { - self == &EntryType::Block - } - - /// Returns whether this type represents a directory. - pub fn is_dir(&self) -> bool { - self == &EntryType::Directory - } - - /// Returns whether this type represents a FIFO. - pub fn is_fifo(&self) -> bool { - self == &EntryType::Fifo - } - - /// Returns whether this type represents a contiguous file. - pub fn is_contiguous(&self) -> bool { - self == &EntryType::Continuous - } - - /// Returns whether this type represents a GNU long name header. - pub fn is_gnu_longname(&self) -> bool { - self == &EntryType::GNULongName - } - - /// Returns whether this type represents a GNU sparse header. - pub fn is_gnu_sparse(&self) -> bool { - self == &EntryType::GNUSparse - } - - /// Returns whether this type represents a GNU long link header. - pub fn is_gnu_longlink(&self) -> bool { - self == &EntryType::GNULongLink - } - - /// Returns whether this type represents a GNU long name header. - pub fn is_pax_global_extensions(&self) -> bool { - self == &EntryType::XGlobalHeader - } - - /// Returns whether this type represents a GNU long link header. - pub fn is_pax_local_extensions(&self) -> bool { - self == &EntryType::XHeader - } -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/src/error.rs cargo-0.26.0/vendor/tar-0.4.14/src/error.rs --- cargo-0.25.0/vendor/tar-0.4.14/src/error.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/src/error.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,40 +0,0 @@ -use std::error; -use std::fmt; -use std::io::{self, Error}; - -#[derive(Debug)] -pub struct TarError { - desc: String, - io: io::Error, -} - -impl TarError { - pub fn new(desc: &str, err: Error) -> TarError { - TarError { - desc: desc.to_string(), - io: err, - } - } -} - -impl error::Error for TarError { - fn description(&self) -> &str { - &self.desc - } - - fn cause(&self) -> Option<&error::Error> { - Some(&self.io) - } -} - -impl fmt::Display for TarError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.desc.fmt(f) - } -} - -impl From<TarError> for Error { - fn from(t: TarError) -> Error { - Error::new(t.io.kind(), t) - } -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/src/header.rs cargo-0.26.0/vendor/tar-0.4.14/src/header.rs --- cargo-0.25.0/vendor/tar-0.4.14/src/header.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/src/header.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1343 +0,0 @@ -#[cfg(any(unix, target_os = "redox"))] use std::os::unix::prelude::*; -#[cfg(windows)] use std::os::windows::prelude::*; - -use std::borrow::Cow; -use std::fmt; -use std::fs; -use std::io; -use std::iter::repeat; -use std::iter; -use std::mem; -use std::path::{Path, PathBuf, Component}; -use std::str; - -use EntryType; -use other; - -/// Representation of the header of an entry in an archive -#[repr(C)] -#[allow(missing_docs)] -pub struct Header { - bytes: [u8; 512], -} - -/// Declares the information that should be included when filling a Header -/// from filesystem metadata. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -pub enum HeaderMode { - /// All supported metadata, including mod/access times and ownership will - /// be included. - Complete, - - /// Only metadata that is directly relevant to the identity of a file will - /// be included. In particular, ownership and mod/access times are excluded. - Deterministic, - - #[doc(hidden)] - __Nonexhaustive, -} - -/// Representation of the header of an entry in an archive -#[repr(C)] -#[allow(missing_docs)] -pub struct OldHeader { - pub name: [u8; 100], - pub mode: [u8; 8], - pub uid: [u8; 8], - pub gid: [u8; 8], - pub size: [u8; 12], - pub mtime: [u8; 12], - pub cksum: [u8; 8], - pub linkflag: [u8; 1], - pub linkname: [u8; 100], - pub pad: [u8; 255], -} - -/// Representation of the header of an entry in an archive -#[repr(C)] -#[allow(missing_docs)] -pub struct UstarHeader { - pub name: [u8; 100], - pub mode: [u8; 8], - pub uid: [u8; 8], - pub gid: [u8; 8], - pub size: [u8; 12], - pub mtime: [u8; 12], - pub cksum: [u8; 8], - pub typeflag: [u8; 1], - pub linkname: [u8; 100], - - // UStar format - pub magic: [u8; 6], - pub version: [u8; 2], - pub uname: [u8; 32], - pub gname: [u8; 32], - pub dev_major: [u8; 8], - pub dev_minor: [u8; 8], - pub prefix: [u8; 155], - pub pad: [u8; 12], -} - -/// Representation of the header of an entry in an archive -#[repr(C)] -#[allow(missing_docs)] -pub struct GnuHeader { - pub name: [u8; 100], - pub mode: [u8; 8], - pub uid: [u8; 8], - pub gid: [u8; 8], - pub size: [u8; 12], - pub mtime: [u8; 12], - pub cksum: [u8; 8], - pub typeflag: [u8; 1], - pub linkname: [u8; 100], - - // GNU format - pub magic: [u8; 6], - pub version: [u8; 2], - pub uname: [u8; 32], - pub gname: [u8; 32], - pub dev_major: [u8; 8], - pub dev_minor: [u8; 8], - pub atime: [u8; 12], - pub ctime: [u8; 12], - pub offset: [u8; 12], - pub longnames: [u8; 4], - pub unused: [u8; 1], - pub sparse: [GnuSparseHeader; 4], - pub isextended: [u8; 1], - pub realsize: [u8; 12], - pub pad: [u8; 17], -} - -/// Description of the header of a spare entry. -/// -/// Specifies the offset/number of bytes of a chunk of data in octal. -#[repr(C)] -#[allow(missing_docs)] -pub struct GnuSparseHeader { - pub offset: [u8; 12], - pub numbytes: [u8; 12], -} - -/// Representation of the entry found to represent extended GNU sparse files. -/// -/// When a `GnuHeader` has the `isextended` flag set to `1` then the contents of -/// the next entry will be one of these headers. -#[repr(C)] -#[allow(missing_docs)] -pub struct GnuExtSparseHeader { - pub sparse: [GnuSparseHeader; 21], - pub isextended: [u8; 1], - pub padding: [u8; 7], -} - -impl Header { - /// Creates a new blank GNU header. - /// - /// The GNU style header is the default for this library and allows various - /// extensions such as long path names, long link names, and setting the - /// atime/ctime metadata attributes of files. - pub fn new_gnu() -> Header { - let mut header = Header { bytes: [0; 512] }; - unsafe { - let gnu = cast_mut::<_, GnuHeader>(&mut header); - gnu.magic = *b"ustar "; - gnu.version = *b" \0"; - } - header.set_mtime(0); - header - } - - /// Creates a new blank UStar header. - /// - /// The UStar style header is an extension of the original archive header - /// which enables some extra metadata along with storing a longer (but not - /// too long) path name. - /// - /// UStar is also the basis used for pax archives. - pub fn new_ustar() -> Header { - let mut header = Header { bytes: [0; 512] }; - unsafe { - let gnu = cast_mut::<_, UstarHeader>(&mut header); - gnu.magic = *b"ustar\0"; - gnu.version = *b"00"; - } - header.set_mtime(0); - header - } - - /// Creates a new blank old header. - /// - /// This header format is the original archive header format which all other - /// versions are compatible with (e.g. they are a superset). This header - /// format limits the path name limit and isn't able to contain extra - /// metadata like atime/ctime. - pub fn new_old() -> Header { - let mut header = Header { bytes: [0; 512] }; - header.set_mtime(0); - header - } - - fn is_ustar(&self) -> bool { - let ustar = unsafe { cast::<_, UstarHeader>(self) }; - ustar.magic[..] == b"ustar\0"[..] && ustar.version[..] == b"00"[..] - } - - fn is_gnu(&self) -> bool { - let ustar = unsafe { cast::<_, UstarHeader>(self) }; - ustar.magic[..] == b"ustar "[..] && ustar.version[..] == b" \0"[..] - } - - /// View this archive header as a raw "old" archive header. - /// - /// This view will always succeed as all archive header formats will fill - /// out at least the fields specified in the old header format. - pub fn as_old(&self) -> &OldHeader { - unsafe { cast(self) } - } - - /// Same as `as_old`, but the mutable version. - pub fn as_old_mut(&mut self) -> &mut OldHeader { - unsafe { cast_mut(self) } - } - - /// View this archive header as a raw UStar archive header. - /// - /// The UStar format is an extension to the tar archive format which enables - /// longer pathnames and a few extra attributes such as the group and user - /// name. - /// - /// This cast may not succeed as this function will test whether the - /// magic/version fields of the UStar format have the appropriate values, - /// returning `None` if they aren't correct. - pub fn as_ustar(&self) -> Option<&UstarHeader> { - if self.is_ustar() {Some(unsafe { cast(self) })} else {None} - } - - /// Same as `as_ustar_mut`, but the mutable version. - pub fn as_ustar_mut(&mut self) -> Option<&mut UstarHeader> { - if self.is_ustar() {Some(unsafe { cast_mut(self) })} else {None} - } - - /// View this archive header as a raw GNU archive header. - /// - /// The GNU format is an extension to the tar archive format which enables - /// longer pathnames and a few extra attributes such as the group and user - /// name. - /// - /// This cast may not succeed as this function will test whether the - /// magic/version fields of the GNU format have the appropriate values, - /// returning `None` if they aren't correct. - pub fn as_gnu(&self) -> Option<&GnuHeader> { - if self.is_gnu() {Some(unsafe { cast(self) })} else {None} - } - - /// Same as `as_gnu`, but the mutable version. - pub fn as_gnu_mut(&mut self) -> Option<&mut GnuHeader> { - if self.is_gnu() {Some(unsafe { cast_mut(self) })} else {None} - } - - /// Returns a view into this header as a byte array. - pub fn as_bytes(&self) -> &[u8; 512] { - &self.bytes - } - - /// Returns a view into this header as a byte array. - pub fn as_mut_bytes(&mut self) -> &mut [u8; 512] { - &mut self.bytes - } - - /// Blanket sets the metadata in this header from the metadata argument - /// provided. - /// - /// This is useful for initializing a `Header` from the OS's metadata from a - /// file. By default, this will use `HeaderMode::Complete` to include all - /// metadata. - pub fn set_metadata(&mut self, meta: &fs::Metadata) { - self.fill_from(meta, HeaderMode::Complete); - } - - /// Sets only the metadata relevant to the given HeaderMode in this header - /// from the metadata argument provided. - pub fn set_metadata_in_mode(&mut self, meta: &fs::Metadata, mode: HeaderMode) { - self.fill_from(meta, mode); - } - - /// Returns the size of entry's data this header represents. - /// - /// This is different from `Header::size` for sparse files, which have - /// some longer `size()` but shorter `entry_size()`. The `entry_size()` - /// listed here should be the number of bytes in the archive this header - /// describes. - /// - /// May return an error if the field is corrupted. - pub fn entry_size(&self) -> io::Result<u64> { - octal_from(&self.as_old().size) - } - - /// Returns the file size this header represents. - /// - /// May return an error if the field is corrupted. - pub fn size(&self) -> io::Result<u64> { - if self.entry_type().is_gnu_sparse() { - self.as_gnu().ok_or_else(|| { - other("sparse header was not a gnu header") - }).and_then(|h| h.real_size()) - } else { - self.entry_size() - } - } - - /// Encodes the `size` argument into the size field of this header. - pub fn set_size(&mut self, size: u64) { - octal_into(&mut self.as_old_mut().size, size) - } - - /// Returns the raw path name stored in this header. - /// - /// This method may fail if the pathname is not valid unicode and this is - /// called on a Windows platform. - /// - /// Note that this function will convert any `\` characters to directory - /// separators. - pub fn path(&self) -> io::Result<Cow<Path>> { - bytes2path(self.path_bytes()) - } - - /// Returns the pathname stored in this header as a byte array. - /// - /// This function is guaranteed to succeed, but you may wish to call the - /// `path` method to convert to a `Path`. - /// - /// Note that this function will convert any `\` characters to directory - /// separators. - pub fn path_bytes(&self) -> Cow<[u8]> { - if let Some(ustar) = self.as_ustar() { - ustar.path_bytes() - } else { - let name = truncate(&self.as_old().name); - Cow::Borrowed(name) - } - } - - /// Sets the path name for this header. - /// - /// This function will set the pathname listed in this header, encoding it - /// in the appropriate format. May fail if the path is too long or if the - /// path specified is not unicode and this is a Windows platform. - pub fn set_path<P: AsRef<Path>>(&mut self, p: P) -> io::Result<()> { - self._set_path(p.as_ref()) - } - - fn _set_path(&mut self, path: &Path) -> io::Result<()> { - if let Some(ustar) = self.as_ustar_mut() { - return ustar.set_path(path) - } - copy_path_into(&mut self.as_old_mut().name, path, false) - } - - /// Returns the link name stored in this header, if any is found. - /// - /// This method may fail if the pathname is not valid unicode and this is - /// called on a Windows platform. `Ok(None)` being returned, however, - /// indicates that the link name was not present. - /// - /// Note that this function will convert any `\` characters to directory - /// separators. - pub fn link_name(&self) -> io::Result<Option<Cow<Path>>> { - match self.link_name_bytes() { - Some(bytes) => bytes2path(bytes).map(Some), - None => Ok(None), - } - } - - /// Returns the link name stored in this header as a byte array, if any. - /// - /// This function is guaranteed to succeed, but you may wish to call the - /// `link_name` method to convert to a `Path`. - /// - /// Note that this function will convert any `\` characters to directory - /// separators. - pub fn link_name_bytes(&self) -> Option<Cow<[u8]>> { - let old = self.as_old(); - if old.linkname[0] != 0 { - Some(Cow::Borrowed(truncate(&old.linkname))) - } else { - None - } - } - - /// Sets the path name for this header. - /// - /// This function will set the pathname listed in this header, encoding it - /// in the appropriate format. May fail if the path is too long or if the - /// path specified is not unicode and this is a Windows platform. - pub fn set_link_name<P: AsRef<Path>>(&mut self, p: P) -> io::Result<()> { - self._set_link_name(p.as_ref()) - } - - fn _set_link_name(&mut self, path: &Path) -> io::Result<()> { - copy_path_into(&mut self.as_old_mut().linkname, path, true) - } - - /// Returns the mode bits for this file - /// - /// May return an error if the field is corrupted. - pub fn mode(&self) -> io::Result<u32> { - octal_from(&self.as_old().mode).map(|u| u as u32) - } - - /// Encodes the `mode` provided into this header. - pub fn set_mode(&mut self, mode: u32) { - octal_into(&mut self.as_old_mut().mode, mode); - } - - /// Returns the value of the owner's user ID field - /// - /// May return an error if the field is corrupted. - pub fn uid(&self) -> io::Result<u32> { - octal_from(&self.as_old().uid).map(|u| u as u32) - } - - /// Encodes the `uid` provided into this header. - pub fn set_uid(&mut self, uid: u32) { - octal_into(&mut self.as_old_mut().uid, uid); - } - - /// Returns the value of the group's user ID field - pub fn gid(&self) -> io::Result<u32> { - octal_from(&self.as_old().gid).map(|u| u as u32) - } - - /// Encodes the `gid` provided into this header. - pub fn set_gid(&mut self, gid: u32) { - octal_into(&mut self.as_old_mut().gid, gid); - } - - /// Returns the last modification time in Unix time format - pub fn mtime(&self) -> io::Result<u64> { - octal_from(&self.as_old().mtime) - } - - /// Encodes the `mtime` provided into this header. - /// - /// Note that this time is typically a number of seconds passed since - /// January 1, 1970. - pub fn set_mtime(&mut self, mtime: u64) { - octal_into(&mut self.as_old_mut().mtime, mtime); - } - - /// Return the user name of the owner of this file. - /// - /// A return value of `Ok(Some(..))` indicates that the user name was - /// present and was valid utf-8, `Ok(None)` indicates that the user name is - /// not present in this archive format, and `Err` indicates that the user - /// name was present but was not valid utf-8. - pub fn username(&self) -> Result<Option<&str>, str::Utf8Error> { - match self.username_bytes() { - Some(bytes) => str::from_utf8(bytes).map(Some), - None => Ok(None), - } - } - - /// Returns the user name of the owner of this file, if present. - /// - /// A return value of `None` indicates that the user name is not present in - /// this header format. - pub fn username_bytes(&self) -> Option<&[u8]> { - if let Some(ustar) = self.as_ustar() { - Some(ustar.username_bytes()) - } else if let Some(gnu) = self.as_gnu() { - Some(gnu.username_bytes()) - } else { - None - } - } - - /// Sets the username inside this header. - /// - /// This function will return an error if this header format cannot encode a - /// user name or the name is too long. - pub fn set_username(&mut self, name: &str) -> io::Result<()> { - if let Some(ustar) = self.as_ustar_mut() { - return ustar.set_username(name) - } - if let Some(gnu) = self.as_gnu_mut() { - gnu.set_username(name) - } else { - Err(other("not a ustar or gnu archive, cannot set username")) - } - } - - /// Return the group name of the owner of this file. - /// - /// A return value of `Ok(Some(..))` indicates that the group name was - /// present and was valid utf-8, `Ok(None)` indicates that the group name is - /// not present in this archive format, and `Err` indicates that the group - /// name was present but was not valid utf-8. - pub fn groupname(&self) -> Result<Option<&str>, str::Utf8Error> { - match self.groupname_bytes() { - Some(bytes) => str::from_utf8(bytes).map(Some), - None => Ok(None), - } - } - - /// Returns the group name of the owner of this file, if present. - /// - /// A return value of `None` indicates that the group name is not present in - /// this header format. - pub fn groupname_bytes(&self) -> Option<&[u8]> { - if let Some(ustar) = self.as_ustar() { - Some(ustar.groupname_bytes()) - } else if let Some(gnu) = self.as_gnu() { - Some(gnu.groupname_bytes()) - } else { - None - } - } - - /// Sets the group name inside this header. - /// - /// This function will return an error if this header format cannot encode a - /// group name or the name is too long. - pub fn set_groupname(&mut self, name: &str) -> io::Result<()> { - if let Some(ustar) = self.as_ustar_mut() { - return ustar.set_groupname(name) - } - if let Some(gnu) = self.as_gnu_mut() { - gnu.set_groupname(name) - } else { - Err(other("not a ustar or gnu archive, cannot set groupname")) - } - } - - /// Returns the device major number, if present. - /// - /// This field may not be present in all archives, and it may not be - /// correctly formed in all archives. `Ok(Some(..))` means it was present - /// and correctly decoded, `Ok(None)` indicates that this header format does - /// not include the device major number, and `Err` indicates that it was - /// present and failed to decode. - pub fn device_major(&self) -> io::Result<Option<u32>> { - if let Some(ustar) = self.as_ustar() { - ustar.device_major().map(Some) - } else if let Some(gnu) = self.as_gnu() { - gnu.device_major().map(Some) - } else { - Ok(None) - } - } - - /// Encodes the value `major` into the dev_major field of this header. - /// - /// This function will return an error if this header format cannot encode a - /// major device number. - pub fn set_device_major(&mut self, major: u32) -> io::Result<()> { - if let Some(ustar) = self.as_ustar_mut() { - return Ok(ustar.set_device_major(major)) - } - if let Some(gnu) = self.as_gnu_mut() { - Ok(gnu.set_device_major(major)) - } else { - Err(other("not a ustar or gnu archive, cannot set dev_major")) - } - } - - /// Returns the device minor number, if present. - /// - /// This field may not be present in all archives, and it may not be - /// correctly formed in all archives. `Ok(Some(..))` means it was present - /// and correctly decoded, `Ok(None)` indicates that this header format does - /// not include the device minor number, and `Err` indicates that it was - /// present and failed to decode. - pub fn device_minor(&self) -> io::Result<Option<u32>> { - if let Some(ustar) = self.as_ustar() { - ustar.device_minor().map(Some) - } else if let Some(gnu) = self.as_gnu() { - gnu.device_minor().map(Some) - } else { - Ok(None) - } - } - - /// Encodes the value `minor` into the dev_minor field of this header. - /// - /// This function will return an error if this header format cannot encode a - /// minor device number. - pub fn set_device_minor(&mut self, minor: u32) -> io::Result<()> { - if let Some(ustar) = self.as_ustar_mut() { - return Ok(ustar.set_device_minor(minor)) - } - if let Some(gnu) = self.as_gnu_mut() { - Ok(gnu.set_device_minor(minor)) - } else { - Err(other("not a ustar or gnu archive, cannot set dev_minor")) - } - } - - /// Returns the type of file described by this header. - pub fn entry_type(&self) -> EntryType { - EntryType::new(self.as_old().linkflag[0]) - } - - /// Sets the type of file that will be described by this header. - pub fn set_entry_type(&mut self, ty: EntryType) { - self.as_old_mut().linkflag = [ty.as_byte()]; - } - - /// Returns the checksum field of this header. - /// - /// May return an error if the field is corrupted. - pub fn cksum(&self) -> io::Result<u32> { - octal_from(&self.as_old().cksum).map(|u| u as u32) - } - - /// Sets the checksum field of this header based on the current fields in - /// this header. - pub fn set_cksum(&mut self) { - let cksum = self.calculate_cksum(); - octal_into(&mut self.as_old_mut().cksum, cksum); - } - - fn calculate_cksum(&self) -> u32 { - let old = self.as_old(); - let start = old as *const _ as usize; - let cksum_start = old.cksum.as_ptr() as *const _ as usize; - let offset = cksum_start - start; - let len = old.cksum.len(); - self.bytes[0..offset].iter() - .chain(iter::repeat(&b' ').take(len)) - .chain(&self.bytes[offset + len..]) - .fold(0, |a, b| a + (*b as u32)) - } - - fn fill_from(&mut self, meta: &fs::Metadata, mode: HeaderMode) { - self.fill_platform_from(meta, mode); - // Set size of directories to zero - self.set_size(if meta.is_dir() || meta.file_type().is_symlink() { 0 } else { meta.len() }); - if let Some(ustar) = self.as_ustar_mut() { - ustar.set_device_major(0); - ustar.set_device_minor(0); - } - if let Some(gnu) = self.as_gnu_mut() { - gnu.set_device_major(0); - gnu.set_device_minor(0); - } - } - - #[cfg(any(unix, target_os = "redox"))] - fn fill_platform_from(&mut self, meta: &fs::Metadata, mode: HeaderMode) { - match mode { - HeaderMode::Complete => { - self.set_mtime(meta.mtime() as u64); - self.set_uid(meta.uid() as u32); - self.set_gid(meta.gid() as u32); - self.set_mode(meta.mode() as u32); - }, - HeaderMode::Deterministic => { - self.set_mtime(0); - self.set_uid(0); - self.set_gid(0); - - // Use a default umask value, but propagate the (user) execute bit. - let fs_mode = - if meta.is_dir() || (0o100 & meta.mode() == 0o100) { - 0o755 - } else { - 0o644 - }; - self.set_mode(fs_mode); - }, - HeaderMode::__Nonexhaustive => panic!(), - } - - // Note that if we are a GNU header we *could* set atime/ctime, except - // the `tar` utility doesn't do that by default and it causes problems - // with 7-zip [1]. - // - // It's always possible to fill them out manually, so we just don't fill - // it out automatically here. - // - // [1]: https://github.com/alexcrichton/tar-rs/issues/70 - - // TODO: need to bind more file types - self.set_entry_type(entry_type(meta.mode())); - - #[cfg(not(target_os = "redox"))] - fn entry_type(mode: u32) -> EntryType { - use libc; - match mode as libc::mode_t & libc::S_IFMT { - libc::S_IFREG => EntryType::file(), - libc::S_IFLNK => EntryType::symlink(), - libc::S_IFCHR => EntryType::character_special(), - libc::S_IFBLK => EntryType::block_special(), - libc::S_IFDIR => EntryType::dir(), - libc::S_IFIFO => EntryType::fifo(), - _ => EntryType::new(b' '), - } - } - - #[cfg(target_os = "redox")] - fn entry_type(mode: u32) -> EntryType { - use syscall; - match mode as u16 & syscall::MODE_TYPE { - syscall::MODE_FILE => EntryType::file(), - syscall::MODE_SYMLINK => EntryType::symlink(), - syscall::MODE_DIR => EntryType::dir(), - _ => EntryType::new(b' '), - } - } - } - - #[cfg(windows)] - fn fill_platform_from(&mut self, meta: &fs::Metadata, mode: HeaderMode) { - // There's no concept of a file mode on windows, so do a best approximation here. - match mode { - HeaderMode::Complete => { - self.set_uid(0); - self.set_gid(0); - // The dates listed in tarballs are always seconds relative to - // January 1, 1970. On Windows, however, the timestamps are returned as - // dates relative to January 1, 1601 (in 100ns intervals), so we need to - // add in some offset for those dates. - let mtime = (meta.last_write_time() / (1_000_000_000 / 100)) - 11644473600; - self.set_mtime(mtime); - let fs_mode = { - const FILE_ATTRIBUTE_READONLY: u32 = 0x00000001; - let readonly = meta.file_attributes() & FILE_ATTRIBUTE_READONLY; - match (meta.is_dir(), readonly != 0) { - (true, false) => 0o755, - (true, true) => 0o555, - (false, false) => 0o644, - (false, true) => 0o444, - } - }; - self.set_mode(fs_mode); - }, - HeaderMode::Deterministic => { - self.set_uid(0); - self.set_gid(0); - self.set_mtime(0); - let fs_mode = - if meta.is_dir() { - 0o755 - } else { - 0o644 - }; - self.set_mode(fs_mode); - }, - HeaderMode::__Nonexhaustive => panic!(), - } - - let ft = meta.file_type(); - self.set_entry_type(if ft.is_dir() { - EntryType::dir() - } else if ft.is_file() { - EntryType::file() - } else if ft.is_symlink() { - EntryType::symlink() - } else { - EntryType::new(b' ') - }); - } - - fn debug_fields(&self, b: &mut fmt::DebugStruct) { - if let Ok(entry_size) = self.entry_size() { - b.field("entry_size", &entry_size); - } - if let Ok(size) = self.size() { - b.field("size", &size); - } - if let Ok(path) = self.path() { - b.field("path", &path); - } - if let Ok(link_name) = self.link_name() { - b.field("link_name", &link_name); - } - if let Ok(mode) = self.mode() { - b.field("mode", &DebugAsOctal(mode)); - } - if let Ok(uid) = self.uid() { - b.field("uid", &uid); - } - if let Ok(gid) = self.gid() { - b.field("gid", &gid); - } - if let Ok(mtime) = self.mtime() { - b.field("mtime", &mtime); - } - if let Ok(username) = self.username() { - b.field("username", &username); - } - if let Ok(groupname) = self.groupname() { - b.field("groupname", &groupname); - } - if let Ok(device_major) = self.device_major() { - b.field("device_major", &device_major); - } - if let Ok(device_minor) = self.device_minor() { - b.field("device_minor", &device_minor); - } - if let Ok(cksum) = self.cksum() { - b.field("cksum", &cksum); - b.field("cksum_valid", &(cksum == self.calculate_cksum())); - } - } -} - -struct DebugAsOctal<T>(T); - -impl<T: fmt::Octal> fmt::Debug for DebugAsOctal<T> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Octal::fmt(&self.0, f) - } -} - -unsafe fn cast<T, U>(a: &T) -> &U { - assert_eq!(mem::size_of_val(a), mem::size_of::<U>()); - assert_eq!(mem::align_of_val(a), mem::align_of::<U>()); - &*(a as *const T as *const U) -} - -unsafe fn cast_mut<T, U>(a: &mut T) -> &mut U { - assert_eq!(mem::size_of_val(a), mem::size_of::<U>()); - assert_eq!(mem::align_of_val(a), mem::align_of::<U>()); - &mut *(a as *mut T as *mut U) -} - -impl Clone for Header { - fn clone(&self) -> Header { - Header { bytes: self.bytes } - } -} - -impl fmt::Debug for Header { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if let Some(me) = self.as_ustar() { - me.fmt(f) - } else if let Some(me) = self.as_gnu() { - me.fmt(f) - } else { - self.as_old().fmt(f) - } - } -} - -impl OldHeader { - /// Views this as a normal `Header` - pub fn as_header(&self) -> &Header { - unsafe { cast(self) } - } - - /// Views this as a normal `Header` - pub fn as_header_mut(&mut self) -> &mut Header { - unsafe { cast_mut(self) } - } -} - -impl fmt::Debug for OldHeader { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut f = f.debug_struct("OldHeader"); - self.as_header().debug_fields(&mut f); - f.finish() - } -} - -impl UstarHeader { - /// See `Header::path_bytes` - pub fn path_bytes(&self) -> Cow<[u8]> { - if self.prefix[0] == 0 && !self.name.contains(&b'\\') { - Cow::Borrowed(truncate(&self.name)) - } else { - let mut bytes = Vec::new(); - let prefix = truncate(&self.prefix); - if prefix.len() > 0 { - bytes.extend_from_slice(prefix); - bytes.push(b'/'); - } - bytes.extend_from_slice(truncate(&self.name)); - Cow::Owned(bytes) - } - } - - /// See `Header::set_path` - pub fn set_path<P: AsRef<Path>>(&mut self, p: P) -> io::Result<()> { - self._set_path(p.as_ref()) - } - - fn _set_path(&mut self, path: &Path) -> io::Result<()> { - // This can probably be optimized quite a bit more, but for now just do - // something that's relatively easy and readable. - // - // First up, if the path fits within `self.name` then we just shove it - // in there. If not then we try to split it between some existing path - // components where it can fit in name/prefix. To do that we peel off - // enough until the path fits in `prefix`, then we try to put both - // halves into their destination. - let bytes = try!(path2bytes(path)); - let (maxnamelen, maxprefixlen) = (self.name.len(), self.prefix.len()); - if bytes.len() <= maxnamelen { - try!(copy_path_into(&mut self.name, path, false)); - } else { - let mut prefix = path; - let mut prefixlen; - loop { - match prefix.parent() { - Some(parent) => prefix = parent, - None => return Err(other("path cannot be split to be \ - inserted into archive")), - } - prefixlen = try!(path2bytes(prefix)).len(); - if prefixlen <= maxprefixlen { - break - } - } - try!(copy_path_into(&mut self.prefix, prefix, false)); - let path = try!(bytes2path(Cow::Borrowed(&bytes[prefixlen + 1..]))); - try!(copy_path_into(&mut self.name, &path, false)); - } - Ok(()) - } - - /// See `Header::username_bytes` - pub fn username_bytes(&self) -> &[u8] { - truncate(&self.uname) - } - - /// See `Header::set_username` - pub fn set_username(&mut self, name: &str) -> io::Result<()> { - copy_into(&mut self.uname, name.as_bytes()) - } - - /// See `Header::groupname_bytes` - pub fn groupname_bytes(&self) -> &[u8] { - truncate(&self.gname) - } - - /// See `Header::set_groupname` - pub fn set_groupname(&mut self, name: &str) -> io::Result<()> { - copy_into(&mut self.gname, name.as_bytes()) - } - - /// See `Header::device_major` - pub fn device_major(&self) -> io::Result<u32> { - octal_from(&self.dev_major).map(|u| u as u32) - } - - /// See `Header::set_device_major` - pub fn set_device_major(&mut self, major: u32) { - octal_into(&mut self.dev_major, major); - } - - /// See `Header::device_minor` - pub fn device_minor(&self) -> io::Result<u32> { - octal_from(&self.dev_minor).map(|u| u as u32) - } - - /// See `Header::set_device_minor` - pub fn set_device_minor(&mut self, minor: u32) { - octal_into(&mut self.dev_minor, minor); - } - - /// Views this as a normal `Header` - pub fn as_header(&self) -> &Header { - unsafe { cast(self) } - } - - /// Views this as a normal `Header` - pub fn as_header_mut(&mut self) -> &mut Header { - unsafe { cast_mut(self) } - } -} - -impl fmt::Debug for UstarHeader { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut f = f.debug_struct("UstarHeader"); - self.as_header().debug_fields(&mut f); - f.finish() - } -} - -impl GnuHeader { - /// See `Header::username_bytes` - pub fn username_bytes(&self) -> &[u8] { - truncate(&self.uname) - } - - /// See `Header::set_username` - pub fn set_username(&mut self, name: &str) -> io::Result<()> { - copy_into(&mut self.uname, name.as_bytes()) - } - - /// See `Header::groupname_bytes` - pub fn groupname_bytes(&self) -> &[u8] { - truncate(&self.gname) - } - - /// See `Header::set_groupname` - pub fn set_groupname(&mut self, name: &str) -> io::Result<()> { - copy_into(&mut self.gname, name.as_bytes()) - } - - /// See `Header::device_major` - pub fn device_major(&self) -> io::Result<u32> { - octal_from(&self.dev_major).map(|u| u as u32) - } - - /// See `Header::set_device_major` - pub fn set_device_major(&mut self, major: u32) { - octal_into(&mut self.dev_major, major); - } - - /// See `Header::device_minor` - pub fn device_minor(&self) -> io::Result<u32> { - octal_from(&self.dev_minor).map(|u| u as u32) - } - - /// See `Header::set_device_minor` - pub fn set_device_minor(&mut self, minor: u32) { - octal_into(&mut self.dev_minor, minor); - } - - /// Returns the last modification time in Unix time format - pub fn atime(&self) -> io::Result<u64> { - octal_from(&self.atime) - } - - /// Encodes the `atime` provided into this header. - /// - /// Note that this time is typically a number of seconds passed since - /// January 1, 1970. - pub fn set_atime(&mut self, atime: u64) { - octal_into(&mut self.atime, atime); - } - - /// Returns the last modification time in Unix time format - pub fn ctime(&self) -> io::Result<u64> { - octal_from(&self.ctime) - } - - /// Encodes the `ctime` provided into this header. - /// - /// Note that this time is typically a number of seconds passed since - /// January 1, 1970. - pub fn set_ctime(&mut self, ctime: u64) { - octal_into(&mut self.ctime, ctime); - } - - /// Returns the "real size" of the file this header represents. - /// - /// This is applicable for sparse files where the returned size here is the - /// size of the entire file after the sparse regions have been filled in. - pub fn real_size(&self) -> io::Result<u64> { - octal_from(&self.realsize) - } - - /// Indicates whether this header will be followed by additional - /// sparse-header records. - /// - /// Note that this is handled internally by this library, and is likely only - /// interesting if a `raw` iterator is being used. - pub fn is_extended(&self) -> bool { - self.isextended[0] == 1 - } - - /// Views this as a normal `Header` - pub fn as_header(&self) -> &Header { - unsafe { cast(self) } - } - - /// Views this as a normal `Header` - pub fn as_header_mut(&mut self) -> &mut Header { - unsafe { cast_mut(self) } - } -} - -impl fmt::Debug for GnuHeader { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut f = f.debug_struct("GnuHeader"); - self.as_header().debug_fields(&mut f); - if let Ok(atime) = self.atime() { - f.field("atime", &atime); - } - if let Ok(ctime) = self.ctime() { - f.field("ctime", &ctime); - } - f.field("is_extended", &self.is_extended()) - .field("sparse", &DebugSparseHeaders(&self.sparse)) - .finish() - } -} - -struct DebugSparseHeaders<'a>(&'a [GnuSparseHeader]); - -impl<'a> fmt::Debug for DebugSparseHeaders<'a> { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut f = f.debug_list(); - for header in self.0 { - if !header.is_empty() { - f.entry(header); - } - } - f.finish() - } -} - -impl GnuSparseHeader { - /// Returns true if block is empty - pub fn is_empty(&self) -> bool { - self.offset[0] == 0 || self.numbytes[0] == 0 - } - - /// Offset of the block from the start of the file - /// - /// Returns `Err` for a malformed `offset` field. - pub fn offset(&self) -> io::Result<u64> { - octal_from(&self.offset) - } - - /// Length of the block - /// - /// Returns `Err` for a malformed `numbytes` field. - pub fn length(&self) -> io::Result<u64> { - octal_from(&self.numbytes) - } -} - -impl fmt::Debug for GnuSparseHeader { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut f = f.debug_struct("GnuSparseHeader"); - if let Ok(offset) = self.offset() { - f.field("offset", &offset); - } - if let Ok(length) = self.length() { - f.field("length", &length); - } - f.finish() - } -} - -impl GnuExtSparseHeader { - /// Crates a new zero'd out sparse header entry. - pub fn new() -> GnuExtSparseHeader { - unsafe { mem::zeroed() } - } - - /// Returns a view into this header as a byte array. - pub fn as_bytes(&self) -> &[u8; 512] { - debug_assert_eq!(mem::size_of_val(self), 512); - unsafe { mem::transmute(self) } - } - - /// Returns a view into this header as a byte array. - pub fn as_mut_bytes(&mut self) -> &mut [u8; 512] { - debug_assert_eq!(mem::size_of_val(self), 512); - unsafe { mem::transmute(self) } - } - - /// Returns a slice of the underlying sparse headers. - /// - /// Some headers may represent empty chunks of both the offset and numbytes - /// fields are 0. - pub fn sparse(&self) -> &[GnuSparseHeader; 21] { - &self.sparse - } - - /// Indicates if another sparse header should be following this one. - pub fn is_extended(&self) -> bool { - self.isextended[0] == 1 - } -} - -impl Default for GnuExtSparseHeader { - fn default() -> Self { - Self::new() - } -} - -fn octal_from(slice: &[u8]) -> io::Result<u64> { - if slice[0] & 0x80 != 0 { - // number is expressed in binary as a GNU numeric extension - - // see https://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5&manpath=FreeBSD+8-current - // under section "Numeric Extensions" - let mut total = (slice[0] ^ 0x80) as u64; - let mut index = 1; - while index < slice.len() { - total <<= 8; - total |= slice[index] as u64; - index += 1; - } - Ok(total) - } else { - let num = match str::from_utf8(truncate(slice)) { - Ok(n) => n, - Err(_) => return Err(other("numeric field did not have utf-8 text")), - }; - match u64::from_str_radix(num.trim(), 8) { - Ok(n) => Ok(n), - Err(_) => Err(other("numeric field was not a number")) - } - } -} - -fn octal_into<T: fmt::Octal>(dst: &mut [u8], val: T) { - let o = format!("{:o}", val); - let value = o.bytes().rev().chain(repeat(b'0')); - for (slot, value) in dst.iter_mut().rev().skip(1).zip(value) { - *slot = value; - } -} - -fn truncate(slice: &[u8]) -> &[u8] { - match slice.iter().position(|i| *i == 0) { - Some(i) => &slice[..i], - None => slice, - } -} - -/// Copies `bytes` into the `slot` provided, returning an error if the `bytes` -/// array is too long or if it contains any nul bytes. -fn copy_into(slot: &mut [u8], bytes: &[u8]) -> io::Result<()> { - if bytes.len() > slot.len() { - Err(other("provided value is too long")) - } else if bytes.iter().any(|b| *b == 0) { - Err(other("provided value contains a nul byte")) - } else { - for (slot, val) in slot.iter_mut().zip(bytes.iter().chain(Some(&0))) { - *slot = *val; - } - Ok(()) - } -} - -/// Copies `path` into the `slot` provided -/// -/// Returns an error if: -/// -/// * the path is too long to fit -/// * a nul byte was found -/// * an invalid path component is encountered (e.g. a root path or parent dir) -/// * the path itself is empty -fn copy_path_into(mut slot: &mut [u8], - path: &Path, - is_link_name: bool) -> io::Result<()> { - let mut emitted = false; - let mut needs_slash = false; - for component in path.components() { - let bytes = try!(path2bytes(Path::new(component.as_os_str()))); - match (component, is_link_name) { - (Component::Prefix(..), false) | - (Component::RootDir, false) => { - return Err(other("paths in archives must be relative")) - } - (Component::ParentDir, false) => { - return Err(other("paths in archives must not have `..`")) - } - // Allow "./" as the path - (Component::CurDir, false) if path.components().count() == 1 => {}, - (Component::CurDir, false) => continue, - (Component::Normal(_), _) | - (_, true) => {} - }; - if needs_slash { - try!(copy(&mut slot, b"/")); - } - if bytes.contains(&b'/') { - if let Component::Normal(..) = component { - return Err(other("path component in archive cannot contain `/`")) - } - } - try!(copy(&mut slot, &*bytes)); - if &*bytes != b"/" { - needs_slash = true; - } - emitted = true; - } - if !emitted { - return Err(other("paths in archives must have at least one component")) - } - if ends_with_slash(path) { - try!(copy(&mut slot, &[b'/'])); - } - return Ok(()); - - fn copy(slot: &mut &mut [u8], bytes: &[u8]) -> io::Result<()> { - try!(copy_into(*slot, bytes)); - let tmp = mem::replace(slot, &mut []); - *slot = &mut tmp[bytes.len()..]; - Ok(()) - } -} - -#[cfg(windows)] -fn ends_with_slash(p: &Path) -> bool { - let last = p.as_os_str().encode_wide().last(); - last == Some(b'/' as u16) || last == Some(b'\\' as u16) -} - -#[cfg(any(unix, target_os = "redox"))] -fn ends_with_slash(p: &Path) -> bool { - p.as_os_str().as_bytes().ends_with(&[b'/']) -} - -#[cfg(windows)] -pub fn path2bytes(p: &Path) -> io::Result<Cow<[u8]>> { - p.as_os_str().to_str().map(|s| s.as_bytes()).ok_or_else(|| { - other("path was not valid unicode") - }).map(|bytes| { - if bytes.contains(&b'\\') { - // Normalize to Unix-style path separators - let mut bytes = bytes.to_owned(); - for b in &mut bytes { - if *b == b'\\' { - *b = b'/'; - } - } - Cow::Owned(bytes) - } else { - Cow::Borrowed(bytes) - } - }) -} - -#[cfg(any(unix, target_os = "redox"))] -pub fn path2bytes(p: &Path) -> io::Result<Cow<[u8]>> { - Ok(p.as_os_str().as_bytes()).map(Cow::Borrowed) -} - -#[cfg(windows)] -pub fn bytes2path(bytes: Cow<[u8]>) -> io::Result<Cow<Path>> { - return match bytes { - Cow::Borrowed(bytes) => { - let s = try!(str::from_utf8(bytes).map_err(|_| { - not_unicode() - })); - Ok(Cow::Borrowed(Path::new(s))) - } - Cow::Owned(bytes) => { - let s = try!(String::from_utf8(bytes).map_err(|_| { - not_unicode() - })); - Ok(Cow::Owned(PathBuf::from(s))) - } - }; - - fn not_unicode() -> io::Error { - other("only unicode paths are supported on windows") - } -} - -#[cfg(any(unix, target_os = "redox"))] -pub fn bytes2path(bytes: Cow<[u8]>) -> io::Result<Cow<Path>> { - use std::ffi::{OsStr, OsString}; - - Ok(match bytes { - Cow::Borrowed(bytes) => Cow::Borrowed({ - Path::new(OsStr::from_bytes(bytes)) - }), - Cow::Owned(bytes) => Cow::Owned({ - PathBuf::from(OsString::from_vec(bytes)) - }) - }) -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/src/lib.rs cargo-0.26.0/vendor/tar-0.4.14/src/lib.rs --- cargo-0.25.0/vendor/tar-0.4.14/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,71 +0,0 @@ -//! A library for reading and writing TAR archives -//! -//! This library provides utilities necessary to manage [TAR archives][1] -//! abstracted over a reader or writer. Great strides are taken to ensure that -//! an archive is never required to be fully resident in memory, and all objects -//! provide largely a streaming interface to read bytes from. -//! -//! [1]: http://en.wikipedia.org/wiki/Tar_%28computing%29 - -// More docs about the detailed tar format can also be found here: -// http://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5&manpath=FreeBSD+8-current - -// NB: some of the coding patterns and idioms here may seem a little strange. -// This is currently attempting to expose a super generic interface while -// also not forcing clients to codegen the entire crate each time they use -// it. To that end lots of work is done to ensure that concrete -// implementations are all found in this crate and the generic functions are -// all just super thin wrappers (e.g. easy to codegen). - -#![doc(html_root_url = "https://docs.rs/tar/0.4")] -#![deny(missing_docs)] -#![cfg_attr(test, deny(warnings))] - -#[cfg(unix)] -extern crate libc; -extern crate filetime; -#[cfg(all(unix, feature = "xattr"))] -extern crate xattr; -#[cfg(target_os = "redox")] -extern crate syscall; - -use std::io::{Error, ErrorKind}; -use std::ops::{Deref, DerefMut}; - -pub use header::{Header, HeaderMode, OldHeader, UstarHeader, GnuHeader, GnuSparseHeader}; -pub use header::{GnuExtSparseHeader}; -pub use entry_type::EntryType; -pub use entry::Entry; -pub use archive::{Archive, Entries}; -pub use builder::Builder; -pub use pax::{PaxExtensions, PaxExtension}; - -mod archive; -mod builder; -mod entry; -mod entry_type; -mod error; -mod header; -mod pax; - -// FIXME(rust-lang/rust#26403): -// Right now there's a bug when a DST struct's last field has more -// alignment than the rest of a structure, causing invalid pointers to be -// created when it's casted around at runtime. To work around this we force -// our DST struct to instead have a forcibly higher alignment via a -// synthesized u64 (hopefully the largest alignment we'll run into in -// practice), and this should hopefully ensure that the pointers all work -// out. -struct AlignHigher<R: ?Sized>(u64, R); - -impl<R: ?Sized> Deref for AlignHigher<R> { - type Target = R; - fn deref(&self) -> &R { &self.1 } -} -impl<R: ?Sized> DerefMut for AlignHigher<R> { - fn deref_mut(&mut self) -> &mut R { &mut self.1 } -} - -fn other(msg: &str) -> Error { - Error::new(ErrorKind::Other, msg) -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/src/pax.rs cargo-0.26.0/vendor/tar-0.4.14/src/pax.rs --- cargo-0.25.0/vendor/tar-0.4.14/src/pax.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/src/pax.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,83 +0,0 @@ -use std::io; -use std::str; -use std::slice; - -use other; - -/// An iterator over the pax extensions in an archive entry. -/// -/// This iterator yields structures which can themselves be parsed into -/// key/value pairs. -pub struct PaxExtensions<'entry> { - data: slice::Split<'entry, u8, fn(&u8) -> bool>, -} - -/// A key/value pair corresponding to a pax extension. -pub struct PaxExtension<'entry> { - key: &'entry [u8], - value: &'entry [u8], -} - -pub fn pax_extensions(a: &[u8]) -> PaxExtensions { - fn is_newline(a: &u8) -> bool { *a == b'\n' } - PaxExtensions { data: a.split(is_newline) } -} - -impl<'entry> Iterator for PaxExtensions<'entry> { - type Item = io::Result<PaxExtension<'entry>>; - - fn next(&mut self) -> Option<io::Result<PaxExtension<'entry>>> { - let line = match self.data.next() { - Some(line) if line.is_empty() => return None, - Some(line) => line, - None => return None, - }; - - Some(line.iter().position(|b| *b == b' ').and_then(|i| { - str::from_utf8(&line[..i]).ok().and_then(|len| { - len.parse::<usize>().ok().map(|j| (i + 1, j)) - }) - }).and_then(|(kvstart, reported_len)| { - if line.len() + 1 == reported_len { - line[kvstart..].iter().position(|b| *b == b'=').map(|equals| { - (kvstart, equals) - }) - } else { - None - } - }).map(|(kvstart, equals)| { - PaxExtension { - key: &line[kvstart..kvstart + equals], - value: &line[kvstart + equals + 1..], - } - }).ok_or_else(|| { - other("malformed pax extension") - })) - } -} - -impl<'entry> PaxExtension<'entry> { - /// Returns the key for this key/value pair parsed as a string. - /// - /// May fail if the key isn't actually utf-8. - pub fn key(&self) -> Result<&'entry str, str::Utf8Error> { - str::from_utf8(self.key) - } - - /// Returns the underlying raw bytes for the key of this key/value pair. - pub fn key_bytes(&self) -> &'entry [u8] { - self.key - } - - /// Returns the value for this key/value pair parsed as a string. - /// - /// May fail if the value isn't actually utf-8. - pub fn value(&self) -> Result<&'entry str, str::Utf8Error> { - str::from_utf8(self.value) - } - - /// Returns the underlying raw bytes for this value of this key/value pair. - pub fn value_bytes(&self) -> &'entry [u8] { - self.value - } -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/tests/all.rs cargo-0.26.0/vendor/tar-0.4.14/tests/all.rs --- cargo-0.25.0/vendor/tar-0.4.14/tests/all.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/tests/all.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,803 +0,0 @@ -extern crate filetime; -extern crate tar; -extern crate tempdir; -#[cfg(all(unix, feature = "xattr"))] -extern crate xattr; - -use std::fs::{self, File}; -use std::io::prelude::*; -use std::io::{self, Cursor}; -use std::iter::repeat; -use std::path::{Path, PathBuf}; - -use filetime::FileTime; -use self::tempdir::TempDir; -use tar::{Archive, Builder, Header, EntryType}; - -macro_rules! t { - ($e:expr) => (match $e { - Ok(v) => v, - Err(e) => panic!("{} returned {}", stringify!($e), e), - }) -} - -macro_rules! tar { - ($e:expr) => (&include_bytes!(concat!("archives/", $e))[..]) -} - -mod header; - -#[test] -fn simple() { - let mut ar = Archive::new(Cursor::new(tar!("simple.tar"))); - for entry in t!(ar.entries()) { - t!(entry); - } - let mut ar = Archive::new(Cursor::new(tar!("simple.tar"))); - for entry in t!(ar.entries()) { - t!(entry); - } -} - -#[test] -fn header_impls() { - let mut ar = Archive::new(Cursor::new(tar!("simple.tar"))); - let hn = Header::new_old(); - let hnb = hn.as_bytes(); - for file in t!(ar.entries()) { - let file = t!(file); - let h1 = file.header(); - let h1b = h1.as_bytes(); - let h2 = h1.clone(); - let h2b = h2.as_bytes(); - assert!(h1b[..] == h2b[..] && h2b[..] != hnb[..]) - } -} - -#[test] -fn reading_files() { - let rdr = Cursor::new(tar!("reading_files.tar")); - let mut ar = Archive::new(rdr); - let mut entries = t!(ar.entries()); - - let mut a = t!(entries.next().unwrap()); - assert_eq!(&*a.header().path_bytes(), b"a"); - let mut s = String::new(); - t!(a.read_to_string(&mut s)); - assert_eq!(s, "a\na\na\na\na\na\na\na\na\na\na\n"); - - let mut b = t!(entries.next().unwrap()); - assert_eq!(&*b.header().path_bytes(), b"b"); - s.truncate(0); - t!(b.read_to_string(&mut s)); - assert_eq!(s, "b\nb\nb\nb\nb\nb\nb\nb\nb\nb\nb\n"); - - assert!(entries.next().is_none()); -} - -#[test] -fn writing_files() { - let mut ar = Builder::new(Vec::new()); - let td = t!(TempDir::new("tar-rs")); - - let path = td.path().join("test"); - t!(t!(File::create(&path)).write_all(b"test")); - - t!(ar.append_file("test2", &mut t!(File::open(&path)))); - - let data = t!(ar.into_inner()); - let mut ar = Archive::new(Cursor::new(data)); - let mut entries = t!(ar.entries()); - let mut f = t!(entries.next().unwrap()); - - assert_eq!(&*f.header().path_bytes(), b"test2"); - assert_eq!(f.header().size().unwrap(), 4); - let mut s = String::new(); - t!(f.read_to_string(&mut s)); - assert_eq!(s, "test"); - - assert!(entries.next().is_none()); -} - -#[test] -fn large_filename() { - let mut ar = Builder::new(Vec::new()); - let td = t!(TempDir::new("tar-rs")); - - let path = td.path().join("test"); - t!(t!(File::create(&path)).write_all(b"test")); - - let filename = repeat("abcd/").take(50).collect::<String>(); - let mut header = Header::new_ustar(); - header.set_path(&filename).unwrap(); - header.set_metadata(&t!(fs::metadata(&path))); - header.set_cksum(); - t!(ar.append(&header, &b"test"[..])); - let too_long = repeat("abcd").take(200).collect::<String>(); - t!(ar.append_file(&too_long, &mut t!(File::open(&path)))); - t!(ar.append_data(&mut header, &too_long, &b"test"[..])); - - let rd = Cursor::new(t!(ar.into_inner())); - let mut ar = Archive::new(rd); - let mut entries = t!(ar.entries()); - - // The short entry added with `append` - let mut f = entries.next().unwrap().unwrap(); - assert_eq!(&*f.header().path_bytes(), filename.as_bytes()); - assert_eq!(f.header().size().unwrap(), 4); - let mut s = String::new(); - t!(f.read_to_string(&mut s)); - assert_eq!(s, "test"); - - // The long entry added with `append_file` - let mut f = entries.next().unwrap().unwrap(); - assert_eq!(&*f.path_bytes(), too_long.as_bytes()); - assert_eq!(f.header().size().unwrap(), 4); - let mut s = String::new(); - t!(f.read_to_string(&mut s)); - assert_eq!(s, "test"); - - // The long entry added with `append_data` - let mut f = entries.next().unwrap().unwrap(); - assert!(f.header().path_bytes().len() < too_long.len()); - assert_eq!(&*f.path_bytes(), too_long.as_bytes()); - assert_eq!(f.header().size().unwrap(), 4); - let mut s = String::new(); - t!(f.read_to_string(&mut s)); - assert_eq!(s, "test"); - - assert!(entries.next().is_none()); -} - -#[test] -fn reading_entries() { - let rdr = Cursor::new(tar!("reading_files.tar")); - let mut ar = Archive::new(rdr); - let mut entries = t!(ar.entries()); - let mut a = t!(entries.next().unwrap()); - assert_eq!(&*a.header().path_bytes(), b"a"); - let mut s = String::new(); - t!(a.read_to_string(&mut s)); - assert_eq!(s, "a\na\na\na\na\na\na\na\na\na\na\n"); - s.truncate(0); - t!(a.read_to_string(&mut s)); - assert_eq!(s, ""); - let mut b = t!(entries.next().unwrap()); - - assert_eq!(&*b.header().path_bytes(), b"b"); - s.truncate(0); - t!(b.read_to_string(&mut s)); - assert_eq!(s, "b\nb\nb\nb\nb\nb\nb\nb\nb\nb\nb\n"); - assert!(entries.next().is_none()); -} - -fn check_dirtree(td: &TempDir) { - let dir_a = td.path().join("a"); - let dir_b = td.path().join("a/b"); - let file_c = td.path().join("a/c"); - assert!(fs::metadata(&dir_a).map(|m| m.is_dir()).unwrap_or(false)); - assert!(fs::metadata(&dir_b).map(|m| m.is_dir()).unwrap_or(false)); - assert!(fs::metadata(&file_c).map(|m| m.is_file()).unwrap_or(false)); -} - -#[test] -fn extracting_directories() { - let td = t!(TempDir::new("tar-rs")); - let rdr = Cursor::new(tar!("directory.tar")); - let mut ar = Archive::new(rdr); - t!(ar.unpack(td.path())); - check_dirtree(&td); -} - -#[test] -#[cfg(all(unix, feature = "xattr"))] -fn xattrs() { - // If /tmp is a tmpfs, xattr will fail - // The xattr crate's unit tests also use /var/tmp for this reason - let td = t!(TempDir::new_in("/var/tmp", "tar-rs")); - let rdr = Cursor::new(tar!("xattrs.tar")); - let mut ar = Archive::new(rdr); - ar.set_unpack_xattrs(true); - t!(ar.unpack(td.path())); - - let val = xattr::get(td.path().join("a/b"), "user.pax.flags").unwrap(); - assert_eq!(val, "epm".as_bytes()); -} - -#[test] -#[cfg(all(unix, feature = "xattr"))] -fn no_xattrs() { - let td = t!(TempDir::new("tar-rs")); - let rdr = Cursor::new(tar!("xattrs.tar")); - let mut ar = Archive::new(rdr); - ar.set_unpack_xattrs(false); - t!(ar.unpack(td.path())); - - xattr::get(td.path().join("a/b"), "user.pax.flags").unwrap_err(); -} - -#[test] -fn writing_and_extracting_directories() { - let td = t!(TempDir::new("tar-rs")); - - let mut ar = Builder::new(Vec::new()); - let tmppath = td.path().join("tmpfile"); - t!(t!(File::create(&tmppath)).write_all(b"c")); - t!(ar.append_dir("a", ".")); - t!(ar.append_dir("a/b", ".")); - t!(ar.append_file("a/c", &mut t!(File::open(&tmppath)))); - t!(ar.finish()); - - let rdr = Cursor::new(t!(ar.into_inner())); - let mut ar = Archive::new(rdr); - t!(ar.unpack(td.path())); - check_dirtree(&td); -} - -#[test] -fn writing_directories_recursively() { - let td = t!(TempDir::new("tar-rs")); - - let base_dir = td.path().join("base"); - t!(fs::create_dir(&base_dir)); - t!(t!(File::create(base_dir.join("file1"))).write_all(b"file1")); - let sub_dir = base_dir.join("sub"); - t!(fs::create_dir(&sub_dir)); - t!(t!(File::create(sub_dir.join("file2"))).write_all(b"file2")); - - let mut ar = Builder::new(Vec::new()); - t!(ar.append_dir_all("foobar", base_dir)); - let data = t!(ar.into_inner()); - - let mut ar = Archive::new(Cursor::new(data)); - t!(ar.unpack(td.path())); - let base_dir = td.path().join("foobar"); - assert!(fs::metadata(&base_dir).map(|m| m.is_dir()).unwrap_or(false)); - let file1_path = base_dir.join("file1"); - assert!(fs::metadata(&file1_path).map(|m| m.is_file()).unwrap_or(false)); - let sub_dir = base_dir.join("sub"); - assert!(fs::metadata(&sub_dir).map(|m| m.is_dir()).unwrap_or(false)); - let file2_path = sub_dir.join("file2"); - assert!(fs::metadata(&file2_path).map(|m| m.is_file()).unwrap_or(false)); -} - -#[test] -fn append_dir_all_blank_dest() { - let td = t!(TempDir::new("tar-rs")); - - let base_dir = td.path().join("base"); - t!(fs::create_dir(&base_dir)); - t!(t!(File::create(base_dir.join("file1"))).write_all(b"file1")); - let sub_dir = base_dir.join("sub"); - t!(fs::create_dir(&sub_dir)); - t!(t!(File::create(sub_dir.join("file2"))).write_all(b"file2")); - - let mut ar = Builder::new(Vec::new()); - t!(ar.append_dir_all("", base_dir)); - let data = t!(ar.into_inner()); - - let mut ar = Archive::new(Cursor::new(data)); - t!(ar.unpack(td.path())); - let base_dir = td.path(); - assert!(fs::metadata(&base_dir).map(|m| m.is_dir()).unwrap_or(false)); - let file1_path = base_dir.join("file1"); - assert!(fs::metadata(&file1_path).map(|m| m.is_file()).unwrap_or(false)); - let sub_dir = base_dir.join("sub"); - assert!(fs::metadata(&sub_dir).map(|m| m.is_dir()).unwrap_or(false)); - let file2_path = sub_dir.join("file2"); - assert!(fs::metadata(&file2_path).map(|m| m.is_file()).unwrap_or(false)); -} - -#[test] -fn append_dir_all_does_not_work_on_non_directory() { - let td = t!(TempDir::new("tar-rs")); - let path = td.path().join("test"); - t!(t!(File::create(&path)).write_all(b"test")); - - let mut ar = Builder::new(Vec::new()); - let result = ar.append_dir_all("test", path); - assert!(result.is_err()); -} - -#[test] -fn extracting_duplicate_dirs() { - let td = t!(TempDir::new("tar-rs")); - let rdr = Cursor::new(tar!("duplicate_dirs.tar")); - let mut ar = Archive::new(rdr); - t!(ar.unpack(td.path())); - - let some_dir = td.path().join("some_dir"); - assert!(fs::metadata(&some_dir).map(|m| m.is_dir()).unwrap_or(false)); -} - -#[test] -fn handling_incorrect_file_size() { - let td = t!(TempDir::new("tar-rs")); - - let mut ar = Builder::new(Vec::new()); - - let path = td.path().join("tmpfile"); - t!(File::create(&path)); - let mut file = t!(File::open(&path)); - let mut header = Header::new_old(); - t!(header.set_path("somepath")); - header.set_metadata(&t!(file.metadata())); - header.set_size(2048); // past the end of file null blocks - header.set_cksum(); - t!(ar.append(&header, &mut file)); - - // Extracting - let rdr = Cursor::new(t!(ar.into_inner())); - let mut ar = Archive::new(rdr); - assert!(ar.unpack(td.path()).is_err()); - - // Iterating - let rdr = Cursor::new(ar.into_inner().into_inner()); - let mut ar = Archive::new(rdr); - assert!(t!(ar.entries()).any(|fr| fr.is_err())); -} - -#[test] -fn extracting_malicious_tarball() { - let td = t!(TempDir::new("tar-rs")); - - let mut evil_tar = Vec::new(); - - { - let mut a = Builder::new(&mut evil_tar); - let mut append = |path: &str| { - let mut header = Header::new_gnu(); - assert!(header.set_path(path).is_err(), - "was ok: {:?}", path); - { - let h = header.as_gnu_mut().unwrap(); - for (a, b) in h.name.iter_mut().zip(path.as_bytes()) { - *a = *b; - } - } - header.set_size(1); - header.set_cksum(); - t!(a.append(&header, io::repeat(1).take(1))); - }; - append("/tmp/abs_evil.txt"); - append("//tmp/abs_evil2.txt"); - append("///tmp/abs_evil3.txt"); - append("/./tmp/abs_evil4.txt"); - append("//./tmp/abs_evil5.txt"); - append("///./tmp/abs_evil6.txt"); - append("/../tmp/rel_evil.txt"); - append("../rel_evil2.txt"); - append("./../rel_evil3.txt"); - append("some/../../rel_evil4.txt"); - append(""); - append("././//./.."); - append(".."); - append("/////////.."); - append("/////////"); - } - - let mut ar = Archive::new(&evil_tar[..]); - t!(ar.unpack(td.path())); - - assert!(fs::metadata("/tmp/abs_evil.txt").is_err()); - assert!(fs::metadata("/tmp/abs_evil.txt2").is_err()); - assert!(fs::metadata("/tmp/abs_evil.txt3").is_err()); - assert!(fs::metadata("/tmp/abs_evil.txt4").is_err()); - assert!(fs::metadata("/tmp/abs_evil.txt5").is_err()); - assert!(fs::metadata("/tmp/abs_evil.txt6").is_err()); - assert!(fs::metadata("/tmp/rel_evil.txt").is_err()); - assert!(fs::metadata("/tmp/rel_evil.txt").is_err()); - assert!(fs::metadata(td.path().join("../tmp/rel_evil.txt")).is_err()); - assert!(fs::metadata(td.path().join("../rel_evil2.txt")).is_err()); - assert!(fs::metadata(td.path().join("../rel_evil3.txt")).is_err()); - assert!(fs::metadata(td.path().join("../rel_evil4.txt")).is_err()); - - // The `some` subdirectory should not be created because the only - // filename that references this has '..'. - assert!(fs::metadata(td.path().join("some")).is_err()); - - // The `tmp` subdirectory should be created and within this - // subdirectory, there should be files named `abs_evil.txt` through - // `abs_evil6.txt`. - assert!(fs::metadata(td.path().join("tmp")).map(|m| m.is_dir()) - .unwrap_or(false)); - assert!(fs::metadata(td.path().join("tmp/abs_evil.txt")) - .map(|m| m.is_file()).unwrap_or(false)); - assert!(fs::metadata(td.path().join("tmp/abs_evil2.txt")) - .map(|m| m.is_file()).unwrap_or(false)); - assert!(fs::metadata(td.path().join("tmp/abs_evil3.txt")) - .map(|m| m.is_file()).unwrap_or(false)); - assert!(fs::metadata(td.path().join("tmp/abs_evil4.txt")) - .map(|m| m.is_file()).unwrap_or(false)); - assert!(fs::metadata(td.path().join("tmp/abs_evil5.txt")) - .map(|m| m.is_file()).unwrap_or(false)); - assert!(fs::metadata(td.path().join("tmp/abs_evil6.txt")) - .map(|m| m.is_file()).unwrap_or(false)); -} - -#[test] -fn octal_spaces() { - let rdr = Cursor::new(tar!("spaces.tar")); - let mut ar = Archive::new(rdr); - - let entry = ar.entries().unwrap().next().unwrap().unwrap(); - assert_eq!(entry.header().mode().unwrap() & 0o777, 0o777); - assert_eq!(entry.header().uid().unwrap(), 0); - assert_eq!(entry.header().gid().unwrap(), 0); - assert_eq!(entry.header().size().unwrap(), 2); - assert_eq!(entry.header().mtime().unwrap(), 0o12440016664); - assert_eq!(entry.header().cksum().unwrap(), 0o4253); -} - -#[test] -fn extracting_malformed_tar_null_blocks() { - let td = t!(TempDir::new("tar-rs")); - - let mut ar = Builder::new(Vec::new()); - - let path1 = td.path().join("tmpfile1"); - let path2 = td.path().join("tmpfile2"); - t!(File::create(&path1)); - t!(File::create(&path2)); - t!(ar.append_file("tmpfile1", &mut t!(File::open(&path1)))); - let mut data = t!(ar.into_inner()); - let amt = data.len(); - data.truncate(amt - 512); - let mut ar = Builder::new(data); - t!(ar.append_file("tmpfile2", &mut t!(File::open(&path2)))); - t!(ar.finish()); - - let data = t!(ar.into_inner()); - let mut ar = Archive::new(&data[..]); - assert!(ar.unpack(td.path()).is_err()); -} - -#[test] -fn empty_filename() -{ - let td = t!(TempDir::new("tar-rs")); - let rdr = Cursor::new(tar!("empty_filename.tar")); - let mut ar = Archive::new(rdr); - assert!(ar.unpack(td.path()).is_err()); -} - -#[test] -fn file_times() { - let td = t!(TempDir::new("tar-rs")); - let rdr = Cursor::new(tar!("file_times.tar")); - let mut ar = Archive::new(rdr); - t!(ar.unpack(td.path())); - - let meta = fs::metadata(td.path().join("a")).unwrap(); - let mtime = FileTime::from_last_modification_time(&meta); - let atime = FileTime::from_last_access_time(&meta); - assert_eq!(mtime.seconds_relative_to_1970(), 1000000000); - assert_eq!(mtime.nanoseconds(), 0); - assert_eq!(atime.seconds_relative_to_1970(), 1000000000); - assert_eq!(atime.nanoseconds(), 0); -} - -#[test] -fn backslash_treated_well() { - // Insert a file into an archive with a backslash - let td = t!(TempDir::new("tar-rs")); - let mut ar = Builder::new(Vec::<u8>::new()); - t!(ar.append_dir("foo\\bar", td.path())); - let mut ar = Archive::new(Cursor::new(t!(ar.into_inner()))); - let f = t!(t!(ar.entries()).next().unwrap()); - if cfg!(unix) { - assert_eq!(t!(f.header().path()).to_str(), Some("foo\\bar")); - } else { - assert_eq!(t!(f.header().path()).to_str(), Some("foo/bar")); - } - - // Unpack an archive with a backslash in the name - let mut ar = Builder::new(Vec::<u8>::new()); - let mut header = Header::new_gnu(); - header.set_metadata(&t!(fs::metadata(td.path()))); - header.set_size(0); - for (a, b) in header.as_old_mut().name.iter_mut().zip(b"foo\\bar\x00") { - *a = *b; - } - header.set_cksum(); - t!(ar.append(&header, &mut io::empty())); - let data = t!(ar.into_inner()); - let mut ar = Archive::new(&data[..]); - let f = t!(t!(ar.entries()).next().unwrap()); - assert_eq!(t!(f.header().path()).to_str(), Some("foo\\bar")); - - let mut ar = Archive::new(&data[..]); - t!(ar.unpack(td.path())); - assert!(fs::metadata(td.path().join("foo\\bar")).is_ok()); -} - -#[cfg(unix)] -#[test] -fn nul_bytes_in_path() { - use std::os::unix::prelude::*; - use std::ffi::OsStr; - - let nul_path = OsStr::from_bytes(b"foo\0"); - let td = t!(TempDir::new("tar-rs")); - let mut ar = Builder::new(Vec::<u8>::new()); - let err = ar.append_dir(nul_path, td.path()).unwrap_err(); - assert!(err.to_string().contains("contains a nul byte")); -} - -#[test] -fn links() { - let mut ar = Archive::new(Cursor::new(tar!("link.tar"))); - let mut entries = t!(ar.entries()); - let link = t!(entries.next().unwrap()); - assert_eq!(t!(link.header().link_name()).as_ref().map(|p| &**p), - Some(Path::new("file"))); - let other = t!(entries.next().unwrap()); - assert!(t!(other.header().link_name()).is_none()); -} - -#[test] -#[cfg(unix)] // making symlinks on windows is hard -fn unpack_links() { - let td = t!(TempDir::new("tar-rs")); - let mut ar = Archive::new(Cursor::new(tar!("link.tar"))); - t!(ar.unpack(td.path())); - - let md = t!(fs::symlink_metadata(td.path().join("lnk"))); - assert!(md.file_type().is_symlink()); - assert_eq!(&*t!(fs::read_link(td.path().join("lnk"))), - Path::new("file")); - t!(File::open(td.path().join("lnk"))); -} - -#[test] -fn pax_simple() { - let mut ar = Archive::new(tar!("pax.tar")); - let mut entries = t!(ar.entries()); - - let mut first = t!(entries.next().unwrap()); - let mut attributes = t!(first.pax_extensions()).unwrap(); - let first = t!(attributes.next().unwrap()); - let second = t!(attributes.next().unwrap()); - let third = t!(attributes.next().unwrap()); - assert!(attributes.next().is_none()); - - assert_eq!(first.key(), Ok("mtime")); - assert_eq!(first.value(), Ok("1453146164.953123768")); - assert_eq!(second.key(), Ok("atime")); - assert_eq!(second.value(), Ok("1453251915.24892486")); - assert_eq!(third.key(), Ok("ctime")); - assert_eq!(third.value(), Ok("1453146164.953123768")); -} - -#[test] -fn long_name_trailing_nul() { - let mut b = Builder::new(Vec::<u8>::new()); - - let mut h = Header::new_gnu(); - t!(h.set_path("././@LongLink")); - h.set_size(4); - h.set_entry_type(EntryType::new(b'L')); - h.set_cksum(); - t!(b.append(&h, "foo\0".as_bytes())); - let mut h = Header::new_gnu(); - - t!(h.set_path("bar")); - h.set_size(6); - h.set_entry_type(EntryType::file()); - h.set_cksum(); - t!(b.append(&h, "foobar".as_bytes())); - - let contents = t!(b.into_inner()); - let mut a = Archive::new(&contents[..]); - - let e = t!(t!(a.entries()).next().unwrap()); - assert_eq!(&*e.path_bytes(), b"foo"); -} - -#[test] -fn long_linkname_trailing_nul() { - let mut b = Builder::new(Vec::<u8>::new()); - - let mut h = Header::new_gnu(); - t!(h.set_path("././@LongLink")); - h.set_size(4); - h.set_entry_type(EntryType::new(b'K')); - h.set_cksum(); - t!(b.append(&h, "foo\0".as_bytes())); - let mut h = Header::new_gnu(); - - t!(h.set_path("bar")); - h.set_size(6); - h.set_entry_type(EntryType::file()); - h.set_cksum(); - t!(b.append(&h, "foobar".as_bytes())); - - let contents = t!(b.into_inner()); - let mut a = Archive::new(&contents[..]); - - let e = t!(t!(a.entries()).next().unwrap()); - assert_eq!(&*e.link_name_bytes().unwrap(), b"foo"); -} - -#[test] -fn encoded_long_name_has_trailing_nul() { - let td = t!(TempDir::new("tar-rs")); - let path = td.path().join("foo"); - t!(t!(File::create(&path)).write_all(b"test")); - - let mut b = Builder::new(Vec::<u8>::new()); - let long = repeat("abcd").take(200).collect::<String>(); - - t!(b.append_file(&long, &mut t!(File::open(&path)))); - - let contents = t!(b.into_inner()); - let mut a = Archive::new(&contents[..]); - - let mut e = t!(t!(a.entries()).raw(true).next().unwrap()); - let mut name = Vec::new(); - t!(e.read_to_end(&mut name)); - assert_eq!(name[name.len() - 1], 0); - - let header_name = &e.header().as_gnu().unwrap().name; - assert!(header_name.starts_with(b"././@LongLink\x00")); -} - -#[test] -fn reading_sparse() { - let rdr = Cursor::new(tar!("sparse.tar")); - let mut ar = Archive::new(rdr); - let mut entries = t!(ar.entries()); - - let mut a = t!(entries.next().unwrap()); - let mut s = String::new(); - assert_eq!(&*a.header().path_bytes(), b"sparse_begin.txt"); - t!(a.read_to_string(&mut s)); - assert_eq!(&s[..5], "test\n"); - assert!(s[5..].chars().all(|x| x == '\u{0}')); - - let mut a = t!(entries.next().unwrap()); - let mut s = String::new(); - assert_eq!(&*a.header().path_bytes(), b"sparse_end.txt"); - t!(a.read_to_string(&mut s)); - assert!(s[..s.len() - 9].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[s.len() - 9..], "test_end\n"); - - let mut a = t!(entries.next().unwrap()); - let mut s = String::new(); - assert_eq!(&*a.header().path_bytes(), b"sparse_ext.txt"); - t!(a.read_to_string(&mut s)); - assert!(s[..0x1000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x1000..0x1000+5], "text\n"); - assert!(s[0x1000+5..0x3000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x3000..0x3000+5], "text\n"); - assert!(s[0x3000+5..0x5000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x5000..0x5000+5], "text\n"); - assert!(s[0x5000+5..0x7000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x7000..0x7000+5], "text\n"); - assert!(s[0x7000+5..0x9000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x9000..0x9000+5], "text\n"); - assert!(s[0x9000+5..0xb000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0xb000..0xb000+5], "text\n"); - - let mut a = t!(entries.next().unwrap()); - let mut s = String::new(); - assert_eq!(&*a.header().path_bytes(), b"sparse.txt"); - t!(a.read_to_string(&mut s)); - assert!(s[..0x1000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x1000..0x1000+6], "hello\n"); - assert!(s[0x1000+6..0x2fa0].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x2fa0..0x2fa0+6], "world\n"); - assert!(s[0x2fa0+6..0x4000].chars().all(|x| x == '\u{0}')); - - assert!(entries.next().is_none()); -} - -#[test] -fn extract_sparse() { - let rdr = Cursor::new(tar!("sparse.tar")); - let mut ar = Archive::new(rdr); - let td = t!(TempDir::new("tar-rs")); - t!(ar.unpack(td.path())); - - let mut s = String::new(); - t!(t!(File::open(td.path().join("sparse_begin.txt"))).read_to_string(&mut s)); - assert_eq!(&s[..5], "test\n"); - assert!(s[5..].chars().all(|x| x == '\u{0}')); - - s.truncate(0); - t!(t!(File::open(td.path().join("sparse_end.txt"))).read_to_string(&mut s)); - assert!(s[..s.len() - 9].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[s.len() - 9..], "test_end\n"); - - s.truncate(0); - t!(t!(File::open(td.path().join("sparse_ext.txt"))).read_to_string(&mut s)); - assert!(s[..0x1000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x1000..0x1000+5], "text\n"); - assert!(s[0x1000+5..0x3000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x3000..0x3000+5], "text\n"); - assert!(s[0x3000+5..0x5000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x5000..0x5000+5], "text\n"); - assert!(s[0x5000+5..0x7000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x7000..0x7000+5], "text\n"); - assert!(s[0x7000+5..0x9000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x9000..0x9000+5], "text\n"); - assert!(s[0x9000+5..0xb000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0xb000..0xb000+5], "text\n"); - - s.truncate(0); - t!(t!(File::open(td.path().join("sparse.txt"))).read_to_string(&mut s)); - assert!(s[..0x1000].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x1000..0x1000+6], "hello\n"); - assert!(s[0x1000+6..0x2fa0].chars().all(|x| x == '\u{0}')); - assert_eq!(&s[0x2fa0..0x2fa0+6], "world\n"); - assert!(s[0x2fa0+6..0x4000].chars().all(|x| x == '\u{0}')); -} - -#[test] -fn path_separators() { - let mut ar = Builder::new(Vec::new()); - let td = t!(TempDir::new("tar-rs")); - - let path = td.path().join("test"); - t!(t!(File::create(&path)).write_all(b"test")); - - let short_path: PathBuf = repeat("abcd").take(2).collect(); - let long_path: PathBuf = repeat("abcd").take(50).collect(); - - // Make sure UStar headers normalize to Unix path separators - let mut header = Header::new_ustar(); - - t!(header.set_path(&short_path)); - assert_eq!(t!(header.path()), short_path); - assert!(!header.path_bytes().contains(&b'\\')); - - t!(header.set_path(&long_path)); - assert_eq!(t!(header.path()), long_path); - assert!(!header.path_bytes().contains(&b'\\')); - - // Make sure GNU headers normalize to Unix path separators, - // including the `@LongLink` fallback used by `append_file`. - t!(ar.append_file(&short_path, &mut t!(File::open(&path)))); - t!(ar.append_file(&long_path, &mut t!(File::open(&path)))); - - let rd = Cursor::new(t!(ar.into_inner())); - let mut ar = Archive::new(rd); - let mut entries = t!(ar.entries()); - - let entry = t!(entries.next().unwrap()); - assert_eq!(t!(entry.path()), short_path); - assert!(!entry.path_bytes().contains(&b'\\')); - - let entry = t!(entries.next().unwrap()); - assert_eq!(t!(entry.path()), long_path); - assert!(!entry.path_bytes().contains(&b'\\')); - - assert!(entries.next().is_none()); -} - -#[test] -#[cfg(unix)] -fn append_path_symlink() { - use std::os::unix::fs::symlink; - use std::env; - use std::borrow::Cow; - - let mut ar = Builder::new(Vec::new()); - ar.follow_symlinks(false); - let td = t!(TempDir::new("tar-rs")); - - t!(env::set_current_dir(td.path())); - t!(symlink("testdest", "test")); - t!(ar.append_path("test")); - - let rd = Cursor::new(t!(ar.into_inner())); - let mut ar = Archive::new(rd); - let mut entries = t!(ar.entries()); - - let entry = t!(entries.next().unwrap()); - assert_eq!(t!(entry.path()), Path::new("test")); - assert_eq!(t!(entry.link_name()), Some(Cow::from(Path::new("testdest")))); - assert_eq!(t!(entry.header().size()), 0); - - assert!(entries.next().is_none()); -} Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.14/tests/archives/directory.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.14/tests/archives/directory.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.14/tests/archives/duplicate_dirs.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.14/tests/archives/duplicate_dirs.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.14/tests/archives/empty_filename.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.14/tests/archives/empty_filename.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.14/tests/archives/file_times.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.14/tests/archives/file_times.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.14/tests/archives/link.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.14/tests/archives/link.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.14/tests/archives/pax.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.14/tests/archives/pax.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.14/tests/archives/reading_files.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.14/tests/archives/reading_files.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.14/tests/archives/simple.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.14/tests/archives/simple.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.14/tests/archives/spaces.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.14/tests/archives/spaces.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.14/tests/archives/sparse.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.14/tests/archives/sparse.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.14/tests/archives/xattrs.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.14/tests/archives/xattrs.tar differ diff -Nru cargo-0.25.0/vendor/tar-0.4.14/tests/entry.rs cargo-0.26.0/vendor/tar-0.4.14/tests/entry.rs --- cargo-0.25.0/vendor/tar-0.4.14/tests/entry.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/tests/entry.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,249 +0,0 @@ -extern crate tar; -extern crate tempdir; - -use std::fs::File; - -use tempdir::TempDir; - -macro_rules! t { - ($e:expr) => (match $e { - Ok(v) => v, - Err(e) => panic!("{} returned {}", stringify!($e), e), - }) -} - -#[test] -fn absolute_symlink() { - let mut ar = tar::Builder::new(Vec::new()); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Symlink); - t!(header.set_path("foo")); - t!(header.set_link_name("/bar")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let bytes = t!(ar.into_inner()); - let mut ar = tar::Archive::new(&bytes[..]); - - let td = t!(TempDir::new("tar")); - t!(ar.unpack(td.path())); - - t!(td.path().join("foo").symlink_metadata()); - - let mut ar = tar::Archive::new(&bytes[..]); - let mut entries = t!(ar.entries()); - let entry = t!(entries.next().unwrap()); - assert_eq!(&*entry.link_name_bytes().unwrap(), b"/bar"); -} - -#[test] -fn absolute_hardlink() { - let td = t!(TempDir::new("tar")); - let mut ar = tar::Builder::new(Vec::new()); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Regular); - t!(header.set_path("foo")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Link); - t!(header.set_path("bar")); - // This absolute path under tempdir will be created at unpack time - t!(header.set_link_name(td.path().join("foo"))); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let bytes = t!(ar.into_inner()); - let mut ar = tar::Archive::new(&bytes[..]); - - t!(ar.unpack(td.path())); - t!(td.path().join("foo").metadata()); - t!(td.path().join("bar").metadata()); -} - -#[test] -fn relative_hardlink() { - let mut ar = tar::Builder::new(Vec::new()); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Regular); - t!(header.set_path("foo")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Link); - t!(header.set_path("bar")); - t!(header.set_link_name("foo")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let bytes = t!(ar.into_inner()); - let mut ar = tar::Archive::new(&bytes[..]); - - let td = t!(TempDir::new("tar")); - t!(ar.unpack(td.path())); - t!(td.path().join("foo").metadata()); - t!(td.path().join("bar").metadata()); -} - -#[test] -fn absolute_link_deref_error() { - let mut ar = tar::Builder::new(Vec::new()); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Symlink); - t!(header.set_path("foo")); - t!(header.set_link_name("/")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Regular); - t!(header.set_path("foo/bar")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let bytes = t!(ar.into_inner()); - let mut ar = tar::Archive::new(&bytes[..]); - - let td = t!(TempDir::new("tar")); - assert!(ar.unpack(td.path()).is_err()); - t!(td.path().join("foo").symlink_metadata()); - assert!(File::open(td.path().join("foo").join("bar")).is_err()); -} - -#[test] -fn relative_link_deref_error() { - let mut ar = tar::Builder::new(Vec::new()); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Symlink); - t!(header.set_path("foo")); - t!(header.set_link_name("../../../../")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Regular); - t!(header.set_path("foo/bar")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let bytes = t!(ar.into_inner()); - let mut ar = tar::Archive::new(&bytes[..]); - - let td = t!(TempDir::new("tar")); - assert!(ar.unpack(td.path()).is_err()); - t!(td.path().join("foo").symlink_metadata()); - assert!(File::open(td.path().join("foo").join("bar")).is_err()); -} - -#[test] -fn modify_link_just_created() { - let mut ar = tar::Builder::new(Vec::new()); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Symlink); - t!(header.set_path("foo")); - t!(header.set_link_name("bar")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Regular); - t!(header.set_path("bar/foo")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Regular); - t!(header.set_path("foo/bar")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let bytes = t!(ar.into_inner()); - let mut ar = tar::Archive::new(&bytes[..]); - - let td = t!(TempDir::new("tar")); - t!(ar.unpack(td.path())); - - t!(File::open(td.path().join("bar/foo"))); - t!(File::open(td.path().join("bar/bar"))); - t!(File::open(td.path().join("foo/foo"))); - t!(File::open(td.path().join("foo/bar"))); -} - -#[test] -fn parent_paths_error() { - let mut ar = tar::Builder::new(Vec::new()); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Symlink); - t!(header.set_path("foo")); - t!(header.set_link_name("..")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Regular); - t!(header.set_path("foo/bar")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let bytes = t!(ar.into_inner()); - let mut ar = tar::Archive::new(&bytes[..]); - - let td = t!(TempDir::new("tar")); - assert!(ar.unpack(td.path()).is_err()); - t!(td.path().join("foo").symlink_metadata()); - assert!(File::open(td.path().join("foo").join("bar")).is_err()); -} - -#[test] -#[cfg(unix)] -fn good_parent_paths_ok() { - use std::path::PathBuf; - let mut ar = tar::Builder::new(Vec::new()); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Symlink); - t!(header.set_path(PathBuf::from("foo").join("bar"))); - t!(header.set_link_name(PathBuf::from("..").join("bar"))); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let mut header = tar::Header::new_gnu(); - header.set_size(0); - header.set_entry_type(tar::EntryType::Regular); - t!(header.set_path("bar")); - header.set_cksum(); - t!(ar.append(&header, &[][..])); - - let bytes = t!(ar.into_inner()); - let mut ar = tar::Archive::new(&bytes[..]); - - let td = t!(TempDir::new("tar")); - t!(ar.unpack(td.path())); - t!(td.path().join("foo").join("bar").read_link()); - let dst = t!(td.path().join("foo").join("bar").canonicalize()); - t!(File::open(dst)); -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/tests/header/mod.rs cargo-0.26.0/vendor/tar-0.4.14/tests/header/mod.rs --- cargo-0.25.0/vendor/tar-0.4.14/tests/header/mod.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/tests/header/mod.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,213 +0,0 @@ -use std::fs::{self, File}; -use std::io::{self, Write}; -use std::path::Path; -use std::{iter, mem, thread, time}; - -use tempdir::TempDir; - -use tar::{Header, HeaderMode, GnuHeader}; - -#[test] -fn default_gnu() { - let mut h = Header::new_gnu(); - assert!(h.as_gnu().is_some()); - assert!(h.as_gnu_mut().is_some()); - assert!(h.as_ustar().is_none()); - assert!(h.as_ustar_mut().is_none()); -} - -#[test] -fn goto_old() { - let mut h = Header::new_old(); - assert!(h.as_gnu().is_none()); - assert!(h.as_gnu_mut().is_none()); - assert!(h.as_ustar().is_none()); - assert!(h.as_ustar_mut().is_none()); -} - -#[test] -fn goto_ustar() { - let mut h = Header::new_ustar(); - assert!(h.as_gnu().is_none()); - assert!(h.as_gnu_mut().is_none()); - assert!(h.as_ustar().is_some()); - assert!(h.as_ustar_mut().is_some()); -} - -#[test] -fn link_name() { - let mut h = Header::new_gnu(); - t!(h.set_link_name("foo")); - assert_eq!(t!(h.link_name()).unwrap().to_str(), Some("foo")); - t!(h.set_link_name("../foo")); - assert_eq!(t!(h.link_name()).unwrap().to_str(), Some("../foo")); - t!(h.set_link_name("foo/bar")); - assert_eq!(t!(h.link_name()).unwrap().to_str(), Some("foo/bar")); - t!(h.set_link_name("foo\\ba")); - if cfg!(windows) { - assert_eq!(t!(h.link_name()).unwrap().to_str(), Some("foo/ba")); - } else { - assert_eq!(t!(h.link_name()).unwrap().to_str(), Some("foo\\ba")); - } - - let name = "foo\\bar\0"; - for (slot, val) in h.as_old_mut().linkname.iter_mut().zip(name.as_bytes()) { - *slot = *val; - } - assert_eq!(t!(h.link_name()).unwrap().to_str(), Some("foo\\bar")); - - assert!(h.set_link_name("\0").is_err()); -} - -#[test] -fn mtime() { - let h = Header::new_gnu(); - assert_eq!(t!(h.mtime()), 0); - - let h = Header::new_ustar(); - assert_eq!(t!(h.mtime()), 0); - - let h = Header::new_old(); - assert_eq!(t!(h.mtime()), 0); -} - -#[test] -fn user_and_group_name() { - let mut h = Header::new_gnu(); - t!(h.set_username("foo")); - t!(h.set_groupname("bar")); - assert_eq!(t!(h.username()), Some("foo")); - assert_eq!(t!(h.groupname()), Some("bar")); - - h = Header::new_ustar(); - t!(h.set_username("foo")); - t!(h.set_groupname("bar")); - assert_eq!(t!(h.username()), Some("foo")); - assert_eq!(t!(h.groupname()), Some("bar")); - - h = Header::new_old(); - assert_eq!(t!(h.username()), None); - assert_eq!(t!(h.groupname()), None); - assert!(h.set_username("foo").is_err()); - assert!(h.set_groupname("foo").is_err()); -} - -#[test] -fn dev_major_minor() { - let mut h = Header::new_gnu(); - t!(h.set_device_major(1)); - t!(h.set_device_minor(2)); - assert_eq!(t!(h.device_major()), Some(1)); - assert_eq!(t!(h.device_minor()), Some(2)); - - h = Header::new_ustar(); - t!(h.set_device_major(1)); - t!(h.set_device_minor(2)); - assert_eq!(t!(h.device_major()), Some(1)); - assert_eq!(t!(h.device_minor()), Some(2)); - - h.as_ustar_mut().unwrap().dev_minor[0] = 0x7f; - h.as_ustar_mut().unwrap().dev_major[0] = 0x7f; - assert!(h.device_major().is_err()); - assert!(h.device_minor().is_err()); - - h.as_ustar_mut().unwrap().dev_minor[0] = b'g'; - h.as_ustar_mut().unwrap().dev_major[0] = b'h'; - assert!(h.device_major().is_err()); - assert!(h.device_minor().is_err()); - - h = Header::new_old(); - assert_eq!(t!(h.device_major()), None); - assert_eq!(t!(h.device_minor()), None); - assert!(h.set_device_major(1).is_err()); - assert!(h.set_device_minor(1).is_err()); -} - -#[test] -fn set_path() { - let mut h = Header::new_gnu(); - t!(h.set_path("foo")); - assert_eq!(t!(h.path()).to_str(), Some("foo")); - t!(h.set_path("foo/")); - assert_eq!(t!(h.path()).to_str(), Some("foo/")); - t!(h.set_path("foo/bar")); - assert_eq!(t!(h.path()).to_str(), Some("foo/bar")); - t!(h.set_path("foo\\bar")); - if cfg!(windows) { - assert_eq!(t!(h.path()).to_str(), Some("foo/bar")); - } else { - assert_eq!(t!(h.path()).to_str(), Some("foo\\bar")); - } - - let long_name = iter::repeat("foo").take(100).collect::<String>(); - let medium1 = iter::repeat("foo").take(52).collect::<String>(); - let medium2 = iter::repeat("fo/").take(52).collect::<String>(); - - assert!(h.set_path(&long_name).is_err()); - assert!(h.set_path(&medium1).is_err()); - assert!(h.set_path(&medium2).is_err()); - assert!(h.set_path("\0").is_err()); - - h = Header::new_ustar(); - t!(h.set_path("foo")); - assert_eq!(t!(h.path()).to_str(), Some("foo")); - - assert!(h.set_path(&long_name).is_err()); - assert!(h.set_path(&medium1).is_err()); - t!(h.set_path(&medium2)); - assert_eq!(t!(h.path()).to_str(), Some(&medium2[..])); -} - -#[test] -fn set_ustar_path_hard() { - let mut h = Header::new_ustar(); - let p = Path::new("a").join(&vec!["a"; 100].join("")); - t!(h.set_path(&p)); - assert_eq!(t!(h.path()), p); -} - -#[test] -fn set_metadata_deterministic() { - let td = t!(TempDir::new("tar-rs")); - let tmppath = td.path().join("tmpfile"); - - fn mk_header(path: &Path, readonly: bool) -> Result<Header, io::Error> { - let mut file = t!(File::create(path)); - t!(file.write_all(b"c")); - let mut perms = t!(file.metadata()).permissions(); - perms.set_readonly(readonly); - t!(fs::set_permissions(path, perms)); - let mut h = Header::new_ustar(); - h.set_metadata_in_mode(&t!(path.metadata()), HeaderMode::Deterministic); - Ok(h) - } - - // Create "the same" File twice in a row, one second apart, with differing readonly values. - let one = t!(mk_header(tmppath.as_path(), false)); - thread::sleep(time::Duration::from_millis(1050)); - let two = t!(mk_header(tmppath.as_path(), true)); - - // Always expected to match. - assert_eq!(t!(one.size()), t!(two.size())); - assert_eq!(t!(one.path()), t!(two.path())); - assert_eq!(t!(one.mode()), t!(two.mode())); - - // Would not match without `Deterministic`. - assert_eq!(t!(one.mtime()), t!(two.mtime())); - // TODO: No great way to validate that these would not be filled, but - // check them anyway. - assert_eq!(t!(one.uid()), t!(two.uid())); - assert_eq!(t!(one.gid()), t!(two.gid())); -} - -#[test] -fn extended_numeric_format() { - let mut h: GnuHeader = unsafe { mem::zeroed() }; - h.size = [0x80, 0, 0, 0, 0, 0, 0, 0x02, 0, 0, 0, 0]; - assert_eq!(h.as_header().entry_size().unwrap(), 0x0200000000); - // TODO uids can be up to 63 bits technically - h.uid = [0x80, 0x00, 0x00, 0x00, 0x12, 0x34, 0x56, 0x78]; - assert_eq!(h.as_header().uid().unwrap(), 0x12345678); - h.mtime = [0x80, 0, 0, 0, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]; - assert_eq!(h.as_header().mtime().unwrap(), 0x0123456789abcdef); -} diff -Nru cargo-0.25.0/vendor/tar-0.4.14/.travis.yml cargo-0.26.0/vendor/tar-0.4.14/.travis.yml --- cargo-0.25.0/vendor/tar-0.4.14/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.14/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -language: rust -rust: - - stable - - beta - - nightly -env: - global: - - RUSTFLAGS='-C link-dead-code' -sudo: false -before_script: - - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH -script: - - cargo build --verbose - - cargo test --verbose - - cargo test --verbose --no-default-features - - cargo clean && cargo build - - rustdoc --test README.md -L target/debug -L target/debug/deps - - cargo doc --no-deps -after_success: - - travis-cargo --only nightly doc-upload - - travis-cargo coveralls --no-sudo -notifications: - email: - on_success: never -addons: - apt: - packages: - - libcurl4-openssl-dev - - libelf-dev - - libdw-dev -env: - global: - secure: "BkV2h2/dkKFUBhdiN3CvUt/zVdIsLhqlVIpS5uV5mQNyiQyZQ+czCmxvAoBF0r6ER6gdbUwvtBVTZ9fT+JmdpxcRJB7/oJ535MYRVkng13GjmDjj3y4KbGZdKsXgNpWPk5EbpFYZ6VdJ6LnEOBEE2aWbAbHwXgWxDCQtlgTeoXQ=" diff -Nru cargo-0.25.0/vendor/tar-0.4.15/appveyor.yml cargo-0.26.0/vendor/tar-0.4.15/appveyor.yml --- cargo-0.25.0/vendor/tar-0.4.15/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-gnu + MSYS_BITS: 64 + - TARGET: i686-pc-windows-gnu + MSYS_BITS: 32 + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - if defined MSYS_BITS set PATH=%PATH%;C:\msys64\mingw%MSYS_BITS%\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --verbose --target %TARGET% diff -Nru cargo-0.25.0/vendor/tar-0.4.15/.cargo-checksum.json cargo-0.26.0/vendor/tar-0.4.15/.cargo-checksum.json --- cargo-0.25.0/vendor/tar-0.4.15/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"6af6b94659f9a571bf769a5b71f54079393585ee0bfdd71b691be22d7d6b1d18"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/tar-0.4.15/Cargo.toml cargo-0.26.0/vendor/tar-0.4.15/Cargo.toml --- cargo-0.25.0/vendor/tar-0.4.15/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,38 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "tar" +version = "0.4.15" +authors = ["Alex Crichton <alex@alexcrichton.com>"] +description = "A Rust implementation of a TAR file reader and writer. This library does not\ncurrently handle compression, but it is abstract over all I/O readers and\nwriters. Additionally, great lengths are taken to ensure that the entire\ncontents are never required to be entirely resident in memory all at once.\n" +homepage = "https://github.com/alexcrichton/tar-rs" +documentation = "https://docs.rs/tar" +readme = "README.md" +keywords = ["tar", "tarfile", "encoding"] +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/tar-rs" +[dependencies.filetime] +version = "0.2" +[dev-dependencies.tempdir] +version = "0.3" + +[features] +default = ["xattr"] +[target."cfg(target_os = \"redox\")".dependencies.redox_syscall] +version = "0.1" +[target."cfg(unix)".dependencies.libc] +version = "0.2" + +[target."cfg(unix)".dependencies.xattr] +version = "0.2" +optional = true diff -Nru cargo-0.25.0/vendor/tar-0.4.15/examples/extract_file.rs cargo-0.26.0/vendor/tar-0.4.15/examples/extract_file.rs --- cargo-0.25.0/vendor/tar-0.4.15/examples/extract_file.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/examples/extract_file.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +//! An example of extracting a file in an archive. +//! +//! Takes a tarball on standard input, looks for an entry with a listed file +//! name as the first argument provided, and then prints the contents of that +//! file to stdout. + +extern crate tar; + +use std::io::{stdin, stdout, copy}; +use std::env::args_os; +use std::path::Path; + +use tar::Archive; + +fn main() { + let first_arg = args_os().skip(1).next().unwrap(); + let filename = Path::new(&first_arg); + let mut ar = Archive::new(stdin()); + for file in ar.entries().unwrap() { + let mut f = file.unwrap(); + if f.path().unwrap() == filename { + copy(&mut f, &mut stdout()).unwrap(); + } + } +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/examples/list.rs cargo-0.26.0/vendor/tar-0.4.15/examples/list.rs --- cargo-0.25.0/vendor/tar-0.4.15/examples/list.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/examples/list.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,17 @@ +//! An example of listing the file names of entries in an archive. +//! +//! Takes a tarball on stdin and prints out all of the entries inside. + +extern crate tar; + +use std::io::stdin; + +use tar::Archive; + +fn main() { + let mut ar = Archive::new(stdin()); + for file in ar.entries().unwrap() { + let f = file.unwrap(); + println!("{}", f.path().unwrap().display()); + } +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/examples/raw_list.rs cargo-0.26.0/vendor/tar-0.4.15/examples/raw_list.rs --- cargo-0.25.0/vendor/tar-0.4.15/examples/raw_list.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/examples/raw_list.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,47 @@ +//! An example of listing raw entries in an archive. +//! +//! Takes a tarball on stdin and prints out all of the entries inside. + +extern crate tar; + +use std::io::stdin; + +use tar::Archive; + +fn main() { + let mut ar = Archive::new(stdin()); + for (i, file) in ar.entries().unwrap().raw(true).enumerate() { + println!("-------------------------- Entry {}", i); + let mut f = file.unwrap(); + println!("path: {}", f.path().unwrap().display()); + println!("size: {}", f.header().size().unwrap()); + println!("entry size: {}", f.header().entry_size().unwrap()); + println!("link name: {:?}", f.link_name().unwrap()); + println!("file type: {:x}", f.header().entry_type().as_byte()); + println!("mode: {:o}", f.header().mode().unwrap()); + println!("uid: {}", f.header().uid().unwrap()); + println!("gid: {}", f.header().gid().unwrap()); + println!("mtime: {}", f.header().mtime().unwrap()); + println!("username: {:?}", f.header().username().unwrap()); + println!("groupname: {:?}", f.header().groupname().unwrap()); + + if f.header().as_ustar().is_some() { + println!("kind: UStar"); + } else if f.header().as_gnu().is_some() { + println!("kind: GNU"); + } else { + println!("kind: normal"); + } + + if let Ok(Some(extensions)) = f.pax_extensions() { + println!("pax extensions:"); + for e in extensions { + let e = e.unwrap(); + println!("\t{:?} = {:?}", + String::from_utf8_lossy(e.key_bytes()), + String::from_utf8_lossy(e.value_bytes())); + } + } + } +} + diff -Nru cargo-0.25.0/vendor/tar-0.4.15/examples/write.rs cargo-0.26.0/vendor/tar-0.4.15/examples/write.rs --- cargo-0.25.0/vendor/tar-0.4.15/examples/write.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/examples/write.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,12 @@ +extern crate tar; + +use std::fs::File; +use tar::Builder; + +fn main() { + let file = File::create("foo.tar").unwrap(); + let mut a = Builder::new(file); + + a.append_path("README.md").unwrap(); + a.append_file("lib.rs", &mut File::open("src/lib.rs").unwrap()).unwrap(); +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/LICENSE-APACHE cargo-0.26.0/vendor/tar-0.4.15/LICENSE-APACHE --- cargo-0.25.0/vendor/tar-0.4.15/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/tar-0.4.15/LICENSE-MIT cargo-0.26.0/vendor/tar-0.4.15/LICENSE-MIT --- cargo-0.25.0/vendor/tar-0.4.15/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +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. diff -Nru cargo-0.25.0/vendor/tar-0.4.15/README.md cargo-0.26.0/vendor/tar-0.4.15/README.md --- cargo-0.25.0/vendor/tar-0.4.15/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,80 @@ +# tar-rs + +[![Build Status](https://travis-ci.org/alexcrichton/tar-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/tar-rs) +[![Build status](https://ci.appveyor.com/api/projects/status/0udgokm2fc6ljorj?svg=true)](https://ci.appveyor.com/project/alexcrichton/tar-rs) +[![Coverage Status](https://coveralls.io/repos/alexcrichton/tar-rs/badge.svg?branch=master&service=github)](https://coveralls.io/github/alexcrichton/tar-rs?branch=master) + +[Documentation](https://docs.rs/tar) + +A tar archive reading/writing library for Rust. + +```toml +# Cargo.toml +[dependencies] +tar = "0.4" +``` + +## Reading an archive + +```rust,no_run +extern crate tar; + +use std::io::prelude::*; +use std::fs::File; +use tar::Archive; + +fn main() { + let file = File::open("foo.tar").unwrap(); + let mut a = Archive::new(file); + + for file in a.entries().unwrap() { + // Make sure there wasn't an I/O error + let mut file = file.unwrap(); + + // Inspect metadata about the file + println!("{:?}", file.header().path().unwrap()); + println!("{}", file.header().size().unwrap()); + + // files implement the Read trait + let mut s = String::new(); + file.read_to_string(&mut s).unwrap(); + println!("{}", s); + } +} + +``` + +## Writing an archive + +```rust,no_run +extern crate tar; + +use std::io::prelude::*; +use std::fs::File; +use tar::Builder; + +fn main() { + let file = File::create("foo.tar").unwrap(); + let mut a = Builder::new(file); + + a.append_path("file1.txt").unwrap(); + a.append_file("file2.txt", &mut File::open("file3.txt").unwrap()).unwrap(); +} +``` + +# License + +This project is 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 Serde by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/tar-0.4.15/src/archive.rs cargo-0.26.0/vendor/tar-0.4.15/src/archive.rs --- cargo-0.25.0/vendor/tar-0.4.15/src/archive.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/src/archive.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,431 @@ +use std::cell::{RefCell, Cell}; +use std::cmp; +use std::io::prelude::*; +use std::io; +use std::marker; +use std::path::Path; + +use entry::{EntryFields, EntryIo}; +use error::TarError; +use other; +use {Entry, Header, GnuSparseHeader, GnuExtSparseHeader}; + +/// A top-level representation of an archive file. +/// +/// This archive can have an entry added to it and it can be iterated over. +pub struct Archive<R: ?Sized + Read> { + inner: ArchiveInner<R>, +} + +pub struct ArchiveInner<R: ?Sized> { + pos: Cell<u64>, + unpack_xattrs: bool, + preserve_permissions: bool, + obj: RefCell<::AlignHigher<R>>, +} + +/// An iterator over the entries of an archive. +pub struct Entries<'a, R: 'a + Read> { + fields: EntriesFields<'a>, + _ignored: marker::PhantomData<&'a Archive<R>>, +} + +struct EntriesFields<'a> { + archive: &'a Archive<Read + 'a>, + next: u64, + done: bool, + raw: bool, +} + +impl<R: Read> Archive<R> { + /// Create a new archive with the underlying object as the reader. + pub fn new(obj: R) -> Archive<R> { + Archive { + inner: ArchiveInner { + unpack_xattrs: false, + preserve_permissions: false, + obj: RefCell::new(::AlignHigher(0, obj)), + pos: Cell::new(0), + }, + } + } + + /// Unwrap this archive, returning the underlying object. + pub fn into_inner(self) -> R { + self.inner.obj.into_inner().1 + } + + /// Construct an iterator over the entries in this archive. + /// + /// Note that care must be taken to consider each entry within an archive in + /// sequence. If entries are processed out of sequence (from what the + /// iterator returns), then the contents read for each entry may be + /// corrupted. + pub fn entries(&mut self) -> io::Result<Entries<R>> { + let me: &mut Archive<Read> = self; + me._entries().map(|fields| { + Entries { fields: fields, _ignored: marker::PhantomData } + }) + } + + /// Unpacks the contents tarball into the specified `dst`. + /// + /// This function will iterate over the entire contents of this tarball, + /// extracting each file in turn to the location specified by the entry's + /// path name. + /// + /// This operation is relatively sensitive in that it will not write files + /// outside of the path specified by `dst`. Files in the archive which have + /// a '..' in their path are skipped during the unpacking process. + /// + /// # Examples + /// + /// ```no_run + /// use std::fs::File; + /// use tar::Archive; + /// + /// let mut ar = Archive::new(File::open("foo.tar").unwrap()); + /// ar.unpack("foo").unwrap(); + /// ``` + pub fn unpack<P: AsRef<Path>>(&mut self, dst: P) -> io::Result<()> { + let me: &mut Archive<Read> = self; + me._unpack(dst.as_ref()) + } + + /// Indicate whether extended file attributes (xattrs on Unix) are preserved + /// when unpacking this archive. + /// + /// This flag is disabled by default and is currently only implemented on + /// Unix using xattr support. This may eventually be implemented for + /// Windows, however, if other archive implementations are found which do + /// this as well. + pub fn set_unpack_xattrs(&mut self, unpack_xattrs: bool) { + self.inner.unpack_xattrs = unpack_xattrs; + } + + /// Indicate whether extended permissions (like suid on Unix) are preserved + /// when unpacking this entry. + /// + /// This flag is disabled by default and is currently only implemented on + /// Unix. + pub fn set_preserve_permissions(&mut self, preserve: bool) { + self.inner.preserve_permissions = preserve; + } +} + +impl<'a> Archive<Read + 'a> { + fn _entries(&mut self) -> io::Result<EntriesFields> { + if self.inner.pos.get() != 0 { + return Err(other("cannot call entries unless archive is at \ + position 0")) + } + Ok(EntriesFields { + archive: self, + done: false, + next: 0, + raw: false, + }) + } + + fn _unpack(&mut self, dst: &Path) -> io::Result<()> { + for entry in try!(self._entries()) { + let mut file = try!(entry.map_err(|e| { + TarError::new("failed to iterate over archive", e) + })); + try!(file.unpack_in(dst)); + } + Ok(()) + } + + fn skip(&self, mut amt: u64) -> io::Result<()> { + let mut buf = [0u8; 4096 * 8]; + while amt > 0 { + let n = cmp::min(amt, buf.len() as u64); + let n = try!((&self.inner).read(&mut buf[..n as usize])); + if n == 0 { + return Err(other("unexpected EOF during skip")) + } + amt -= n as u64; + } + Ok(()) + } +} + +impl<'a, R: Read> Entries<'a, R> { + /// Indicates whether this iterator will return raw entries or not. + /// + /// If the raw list of entries are returned, then no preprocessing happens + /// on account of this library, for example taking into accout GNU long name + /// or long link archive members. Raw iteration is disabled by default. + pub fn raw(self, raw: bool) -> Entries<'a, R> { + Entries { + fields: EntriesFields { + raw: raw, + ..self.fields + }, + _ignored: marker::PhantomData, + } + } +} +impl<'a, R: Read> Iterator for Entries<'a, R> { + type Item = io::Result<Entry<'a, R>>; + + fn next(&mut self) -> Option<io::Result<Entry<'a, R>>> { + self.fields.next().map(|result| { + result.map(|e| EntryFields::from(e).into_entry()) + }) + } +} + +impl<'a> EntriesFields<'a> { + fn next_entry_raw(&mut self) -> io::Result<Option<Entry<'a, io::Empty>>> { + // Seek to the start of the next header in the archive + let delta = self.next - self.archive.inner.pos.get(); + try!(self.archive.skip(delta)); + + let header_pos = self.next; + let mut header = Header::new_old(); + try!(read_all(&mut &self.archive.inner, header.as_mut_bytes())); + self.next += 512; + + // If we have an all 0 block, then this should be the start of the end + // of the archive. A block of 0s is never valid as a header (because of + // the checksum), so if it's all zero it must be the first of the two + // end blocks + if header.as_bytes().iter().all(|i| *i == 0) { + try!(read_all(&mut &self.archive.inner, + header.as_mut_bytes())); + self.next += 512; + return if header.as_bytes().iter().all(|i| *i == 0) { + Ok(None) + } else { + Err(other("found block of 0s not followed by a second \ + block of 0s")) + } + } + + // Make sure the checksum is ok + let sum = header.as_bytes()[..148].iter() + .chain(&header.as_bytes()[156..]) + .fold(0, |a, b| a + (*b as u32)) + 8 * 32; + let cksum = try!(header.cksum()); + if sum != cksum { + return Err(other("archive header checksum mismatch")) + } + + let file_pos = self.next; + let size = try!(header.entry_size()); + + let ret = EntryFields { + size: size, + header_pos: header_pos, + file_pos: file_pos, + data: vec![EntryIo::Data((&self.archive.inner).take(size))], + header: header, + long_pathname: None, + long_linkname: None, + pax_extensions: None, + unpack_xattrs: self.archive.inner.unpack_xattrs, + preserve_permissions: self.archive.inner.preserve_permissions, + }; + + // Store where the next entry is, rounding up by 512 bytes (the size of + // a header); + let size = (size + 511) & !(512 - 1); + self.next += size; + + Ok(Some(ret.into_entry())) + } + + fn next_entry(&mut self) -> io::Result<Option<Entry<'a, io::Empty>>> { + if self.raw { + return self.next_entry_raw() + } + + let mut gnu_longname = None; + let mut gnu_longlink = None; + let mut pax_extensions = None; + let mut processed = 0; + loop { + processed += 1; + let entry = match try!(self.next_entry_raw()) { + Some(entry) => entry, + None if processed > 1 => { + return Err(other("members found describing a future member \ + but no future member found")) + } + None => return Ok(None), + }; + + if entry.header().as_gnu().is_some() && + entry.header().entry_type().is_gnu_longname() { + if gnu_longname.is_some() { + return Err(other("two long name entries describing \ + the same member")) + } + gnu_longname = Some(try!(EntryFields::from(entry).read_all())); + continue + } + + if entry.header().as_gnu().is_some() && + entry.header().entry_type().is_gnu_longlink() { + if gnu_longlink.is_some() { + return Err(other("two long name entries describing \ + the same member")) + } + gnu_longlink = Some(try!(EntryFields::from(entry).read_all())); + continue + } + + if entry.header().as_ustar().is_some() && + entry.header().entry_type().is_pax_local_extensions() { + if pax_extensions.is_some() { + return Err(other("two pax extensions entries describing \ + the same member")) + } + pax_extensions = Some(try!(EntryFields::from(entry).read_all())); + continue + } + + let mut fields = EntryFields::from(entry); + fields.long_pathname = gnu_longname; + fields.long_linkname = gnu_longlink; + fields.pax_extensions = pax_extensions; + try!(self.parse_sparse_header(&mut fields)); + return Ok(Some(fields.into_entry())) + } + } + + fn parse_sparse_header(&mut self, + entry: &mut EntryFields<'a>) -> io::Result<()> { + if !entry.header.entry_type().is_gnu_sparse() { + return Ok(()) + } + let gnu = match entry.header.as_gnu() { + Some(gnu) => gnu, + None => return Err(other("sparse entry type listed but not GNU header")), + }; + + // Sparse files are represented internally as a list of blocks that are + // read. Blocks are either a bunch of 0's or they're data from the + // underlying archive. + // + // Blocks of a sparse file are described by the `GnuSparseHeader` + // structure, some of which are contained in `GnuHeader` but some of + // which may also be contained after the first header in further + // headers. + // + // We read off all the blocks here and use the `add_block` function to + // incrementally add them to the list of I/O block (in `entry.data`). + // The `add_block` function also validates that each chunk comes after + // the previous, we don't overrun the end of the file, and each block is + // aligned to a 512-byte boundary in the archive itself. + // + // At the end we verify that the sparse file size (`Header::size`) is + // the same as the current offset (described by the list of blocks) as + // well as the amount of data read equals the size of the entry + // (`Header::entry_size`). + entry.data.truncate(0); + + let mut cur = 0; + let mut remaining = entry.size; + { + let data = &mut entry.data; + let reader = &self.archive.inner; + let size = entry.size; + let mut add_block = |block: &GnuSparseHeader| -> io::Result<_> { + if block.is_empty() { + return Ok(()) + } + let off = try!(block.offset()); + let len = try!(block.length()); + + if (size - remaining) % 512 != 0 { + return Err(other("previous block in sparse file was not \ + aligned to 512-byte boundary")) + } else if off < cur { + return Err(other("out of order or overlapping sparse \ + blocks")) + } else if cur < off { + let block = io::repeat(0).take(off - cur); + data.push(EntryIo::Pad(block)); + } + cur = try!(off.checked_add(len).ok_or_else(|| { + other("more bytes listed in sparse file than u64 can hold") + })); + remaining = try!(remaining.checked_sub(len).ok_or_else(|| { + other("sparse file consumed more data than the header \ + listed") + })); + data.push(EntryIo::Data(reader.take(len))); + Ok(()) + }; + for block in gnu.sparse.iter() { + try!(add_block(block)) + } + if gnu.is_extended() { + let mut ext = GnuExtSparseHeader::new(); + ext.isextended[0] = 1; + while ext.is_extended() { + try!(read_all(&mut &self.archive.inner, ext.as_mut_bytes())); + self.next += 512; + for block in ext.sparse.iter() { + try!(add_block(block)); + } + } + } + } + if cur != try!(gnu.real_size()) { + return Err(other("mismatch in sparse file chunks and \ + size in header")) + } + entry.size = cur; + if remaining > 0 { + return Err(other("mismatch in sparse file chunks and \ + entry size in header")) + } + Ok(()) + } +} + +impl<'a> Iterator for EntriesFields<'a> { + type Item = io::Result<Entry<'a, io::Empty>>; + + fn next(&mut self) -> Option<io::Result<Entry<'a, io::Empty>>> { + if self.done { + None + } else { + match self.next_entry() { + Ok(Some(e)) => Some(Ok(e)), + Ok(None) => { + self.done = true; + None + } + Err(e) => { + self.done = true; + Some(Err(e)) + } + } + } + } +} + +impl<'a, R: ?Sized + Read> Read for &'a ArchiveInner<R> { + fn read(&mut self, into: &mut [u8]) -> io::Result<usize> { + self.obj.borrow_mut().read(into).map(|i| { + self.pos.set(self.pos.get() + i as u64); + i + }) + } +} + +fn read_all<R: Read>(r: &mut R, buf: &mut [u8]) -> io::Result<()> { + let mut read = 0; + while read < buf.len() { + match try!(r.read(&mut buf[read..])) { + 0 => return Err(other("failed to read entire block")), + n => read += n, + } + } + Ok(()) +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/src/builder.rs cargo-0.26.0/vendor/tar-0.4.15/src/builder.rs --- cargo-0.25.0/vendor/tar-0.4.15/src/builder.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/src/builder.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,416 @@ +use std::io; +use std::path::Path; +use std::io::prelude::*; +use std::fs; +use std::borrow::Cow; + +use {EntryType, Header, other}; +use header::{bytes2path, HeaderMode, path2bytes}; + +/// A structure for building archives +/// +/// This structure has methods for building up an archive from scratch into any +/// arbitrary writer. +pub struct Builder<W: Write> { + mode: HeaderMode, + follow: bool, + finished: bool, + obj: Option<W>, +} + +impl<W: Write> Builder<W> { + /// Create a new archive builder with the underlying object as the + /// destination of all data written. The builder will use + /// `HeaderMode::Complete` by default. + pub fn new(obj: W) -> Builder<W> { + Builder { + mode: HeaderMode::Complete, + follow: true, + finished: false, + obj: Some(obj), + } + } + + fn inner(&mut self) -> &mut W { + self.obj.as_mut().unwrap() + } + + /// Changes the HeaderMode that will be used when reading fs Metadata for + /// methods that implicitly read metadata for an input Path. Notably, this + /// does _not_ apply to `append(Header)`. + pub fn mode(&mut self, mode: HeaderMode) { + self.mode = mode; + } + + /// Follow symlinks, archiving the contents of the file they point to rather + /// than adding a symlink to the archive. Defaults to true. + pub fn follow_symlinks(&mut self, follow: bool) { + self.follow = follow; + } + + /// Unwrap this archive, returning the underlying object. + /// + /// This function will finish writing the archive if the `finish` function + /// hasn't yet been called, returning any I/O error which happens during + /// that operation. + pub fn into_inner(mut self) -> io::Result<W> { + if !self.finished { + try!(self.finish()); + } + Ok(self.obj.take().unwrap()) + } + + /// Adds a new entry to this archive. + /// + /// This function will append the header specified, followed by contents of + /// the stream specified by `data`. To produce a valid archive the `size` + /// field of `header` must be the same as the length of the stream that's + /// being written. Additionally the checksum for the header should have been + /// set via the `set_cksum` method. + /// + /// Note that this will not attempt to seek the archive to a valid position, + /// so if the archive is in the middle of a read or some other similar + /// operation then this may corrupt the archive. + /// + /// Also note that after all entries have been written to an archive the + /// `finish` function needs to be called to finish writing the archive. + /// + /// # Errors + /// + /// This function will return an error for any intermittent I/O error which + /// occurs when either reading or writing. + /// + /// # Examples + /// + /// ``` + /// use tar::{Builder, Header}; + /// + /// let mut header = Header::new_gnu(); + /// header.set_path("foo").unwrap(); + /// header.set_size(4); + /// header.set_cksum(); + /// + /// let mut data: &[u8] = &[1, 2, 3, 4]; + /// + /// let mut ar = Builder::new(Vec::new()); + /// ar.append(&header, data).unwrap(); + /// let data = ar.into_inner().unwrap(); + /// ``` + pub fn append<R: Read>(&mut self, header: &Header, mut data: R) + -> io::Result<()> { + append(self.inner(), header, &mut data) + } + + /// Adds a new entry to this archive with the specified path. + /// + /// This function will set the specified path in the given header, which may + /// require appending a GNU long-name extension entry to the archive first. + /// The checksum for the header will be automatically updated via the + /// `set_cksum` method after setting the path. No other metadata in the + /// header will be modified. + /// + /// Then it will append the header, followed by contents of the stream + /// specified by `data`. To produce a valid archive the `size` field of + /// `header` must be the same as the length of the stream that's being + /// written. + /// + /// Note that this will not attempt to seek the archive to a valid position, + /// so if the archive is in the middle of a read or some other similar + /// operation then this may corrupt the archive. + /// + /// Also note that after all entries have been written to an archive the + /// `finish` function needs to be called to finish writing the archive. + /// + /// # Errors + /// + /// This function will return an error for any intermittent I/O error which + /// occurs when either reading or writing. + /// + /// # Examples + /// + /// ``` + /// use tar::{Builder, Header}; + /// + /// let mut header = Header::new_gnu(); + /// header.set_size(4); + /// header.set_cksum(); + /// + /// let mut data: &[u8] = &[1, 2, 3, 4]; + /// + /// let mut ar = Builder::new(Vec::new()); + /// ar.append_data(&mut header, "really/long/path/to/foo", data).unwrap(); + /// let data = ar.into_inner().unwrap(); + /// ``` + pub fn append_data<P: AsRef<Path>, R: Read>(&mut self, header: &mut Header, path: P, data: R) + -> io::Result<()> { + try!(prepare_header(self.inner(), header, path.as_ref())); + header.set_cksum(); + self.append(&header, data) + } + + /// Adds a file on the local filesystem to this archive. + /// + /// This function will open the file specified by `path` and insert the file + /// into the archive with the appropriate metadata set, returning any I/O + /// error which occurs while writing. The path name for the file inside of + /// this archive will be the same as `path`, and it is required that the + /// path is a relative path. + /// + /// Note that this will not attempt to seek the archive to a valid position, + /// so if the archive is in the middle of a read or some other similar + /// operation then this may corrupt the archive. + /// + /// Also note that after all files have been written to an archive the + /// `finish` function needs to be called to finish writing the archive. + /// + /// # Examples + /// + /// ```no_run + /// use tar::Builder; + /// + /// let mut ar = Builder::new(Vec::new()); + /// + /// ar.append_path("foo/bar.txt").unwrap(); + /// ``` + pub fn append_path<P: AsRef<Path>>(&mut self, path: P) -> io::Result<()> { + let mode = self.mode.clone(); + let follow = self.follow; + append_path(self.inner(), path.as_ref(), mode, follow) + } + + /// Adds a file to this archive with the given path as the name of the file + /// in the archive. + /// + /// This will use the metadata of `file` to populate a `Header`, and it will + /// then append the file to the archive with the name `path`. + /// + /// Note that this will not attempt to seek the archive to a valid position, + /// so if the archive is in the middle of a read or some other similar + /// operation then this may corrupt the archive. + /// + /// Also note that after all files have been written to an archive the + /// `finish` function needs to be called to finish writing the archive. + /// + /// # Examples + /// + /// ```no_run + /// use std::fs::File; + /// use tar::Builder; + /// + /// let mut ar = Builder::new(Vec::new()); + /// + /// // Open the file at one location, but insert it into the archive with a + /// // different name. + /// let mut f = File::open("foo/bar/baz.txt").unwrap(); + /// ar.append_file("bar/baz.txt", &mut f).unwrap(); + /// ``` + pub fn append_file<P: AsRef<Path>>(&mut self, path: P, file: &mut fs::File) + -> io::Result<()> { + let mode = self.mode.clone(); + append_file(self.inner(), path.as_ref(), file, mode) + } + + /// Adds a directory to this archive with the given path as the name of the + /// directory in the archive. + /// + /// This will use `stat` to populate a `Header`, and it will then append the + /// directory to the archive with the name `path`. + /// + /// Note that this will not attempt to seek the archive to a valid position, + /// so if the archive is in the middle of a read or some other similar + /// operation then this may corrupt the archive. + /// + /// Also note that after all files have been written to an archive the + /// `finish` function needs to be called to finish writing the archive. + /// + /// # Examples + /// + /// ``` + /// use std::fs; + /// use tar::Builder; + /// + /// let mut ar = Builder::new(Vec::new()); + /// + /// // Use the directory at one location, but insert it into the archive + /// // with a different name. + /// ar.append_dir("bardir", ".").unwrap(); + /// ``` + pub fn append_dir<P, Q>(&mut self, path: P, src_path: Q) -> io::Result<()> + where P: AsRef<Path>, Q: AsRef<Path> + { + let mode = self.mode.clone(); + append_dir(self.inner(), path.as_ref(), src_path.as_ref(), mode) + } + + /// Adds a directory and all of its contents (recursively) to this archive + /// with the given path as the name of the directory in the archive. + /// + /// Note that this will not attempt to seek the archive to a valid position, + /// so if the archive is in the middle of a read or some other similar + /// operation then this may corrupt the archive. + /// + /// Also note that after all files have been written to an archive the + /// `finish` function needs to be called to finish writing the archive. + /// + /// # Examples + /// + /// ``` + /// use std::fs; + /// use tar::Builder; + /// + /// let mut ar = Builder::new(Vec::new()); + /// + /// // Use the directory at one location, but insert it into the archive + /// // with a different name. + /// ar.append_dir_all("bardir", ".").unwrap(); + /// ``` + pub fn append_dir_all<P, Q>(&mut self, path: P, src_path: Q) -> io::Result<()> + where P: AsRef<Path>, Q: AsRef<Path> + { + let mode = self.mode.clone(); + let follow = self.follow; + append_dir_all(self.inner(), path.as_ref(), src_path.as_ref(), mode, follow) + } + + /// Finish writing this archive, emitting the termination sections. + /// + /// This function should only be called when the archive has been written + /// entirely and if an I/O error happens the underlying object still needs + /// to be acquired. + /// + /// In most situations the `into_inner` method should be preferred. + pub fn finish(&mut self) -> io::Result<()> { + if self.finished { + return Ok(()) + } + self.finished = true; + self.inner().write_all(&[0; 1024]) + } +} + +fn append(mut dst: &mut Write, + header: &Header, + mut data: &mut Read) -> io::Result<()> { + try!(dst.write_all(header.as_bytes())); + let len = try!(io::copy(&mut data, &mut dst)); + + // Pad with zeros if necessary. + let buf = [0; 512]; + let remaining = 512 - (len % 512); + if remaining < 512 { + try!(dst.write_all(&buf[..remaining as usize])); + } + + Ok(()) +} + +fn append_path(dst: &mut Write, path: &Path, mode: HeaderMode, follow: bool) -> io::Result<()> { + let stat = if follow { + try!(fs::metadata(path).map_err(|err| io::Error::new( + err.kind(), + format!("{} when getting metadata for {}", err, path.display()), + ))) + } else { + try!(fs::symlink_metadata(path).map_err(|err| io::Error::new( + err.kind(), + format!("{} when getting metadata for {}", err, path.display()), + ))) + }; + if stat.is_file() { + append_fs(dst, path, &stat, &mut try!(fs::File::open(path)), mode, None) + } else if stat.is_dir() { + append_fs(dst, path, &stat, &mut io::empty(), mode, None) + } else if stat.file_type().is_symlink() { + let link_name = try!(fs::read_link(path)); + append_fs(dst, path, &stat, &mut io::empty(), mode, Some(&link_name)) + } else { + Err(other(&format!("{} has unknown file type", path.display()))) + } +} + +fn append_file(dst: &mut Write, path: &Path, file: &mut fs::File, mode: HeaderMode) + -> io::Result<()> { + let stat = try!(file.metadata()); + append_fs(dst, path, &stat, file, mode, None) +} + +fn append_dir(dst: &mut Write, path: &Path, src_path: &Path, mode: HeaderMode) -> io::Result<()> { + let stat = try!(fs::metadata(src_path)); + append_fs(dst, path, &stat, &mut io::empty(), mode, None) +} + +fn prepare_header(dst: &mut Write, header: &mut Header, path: &Path) -> io::Result<()> { + // Try to encode the path directly in the header, but if it ends up not + // working (e.g. it's too long) then use the GNU-specific long name + // extension by emitting an entry which indicates that it's the filename + if let Err(e) = header.set_path(path) { + let data = try!(path2bytes(&path)); + let max = header.as_old().name.len(); + if data.len() < max { + return Err(e) + } + let mut header2 = Header::new_gnu(); + header2.as_gnu_mut().unwrap().name[..13].clone_from_slice(b"././@LongLink"); + header2.set_mode(0o644); + header2.set_uid(0); + header2.set_gid(0); + header2.set_mtime(0); + header2.set_size((data.len() + 1) as u64); + header2.set_entry_type(EntryType::new(b'L')); + header2.set_cksum(); + let mut data2 = data.chain(io::repeat(0).take(0)); + try!(append(dst, &header2, &mut data2)); + // Truncate the path to store in the header we're about to emit to + // ensure we've got something at least mentioned. + let path = try!(bytes2path(Cow::Borrowed(&data[..max]))); + try!(header.set_path(&path)); + } + Ok(()) +} + +fn append_fs(dst: &mut Write, + path: &Path, + meta: &fs::Metadata, + read: &mut Read, + mode: HeaderMode, + link_name: Option<&Path>) -> io::Result<()> { + let mut header = Header::new_gnu(); + + try!(prepare_header(dst, &mut header, path)); + header.set_metadata_in_mode(meta, mode); + if let Some(link_name) = link_name { + try!(header.set_link_name(link_name)); + } + header.set_cksum(); + append(dst, &header, read) +} + +fn append_dir_all(dst: &mut Write, path: &Path, src_path: &Path, mode: HeaderMode, follow: bool) -> io::Result<()> { + let mut stack = vec![(src_path.to_path_buf(), true, false)]; + while let Some((src, is_dir, is_symlink)) = stack.pop() { + let dest = path.join(src.strip_prefix(&src_path).unwrap()); + if is_dir { + for entry in try!(fs::read_dir(&src)) { + let entry = try!(entry); + let file_type = try!(entry.file_type()); + stack.push((entry.path(), file_type.is_dir(), file_type.is_symlink())); + } + if dest != Path::new("") { + try!(append_dir(dst, &dest, &src, mode)); + } + } else if !follow && is_symlink { + let stat = try!(fs::symlink_metadata(&src)); + let link_name = try!(fs::read_link(&src)); + try!(append_fs(dst, &dest, &stat, &mut io::empty(), mode, Some(&link_name))); + } else { + try!(append_file(dst, &dest, &mut try!(fs::File::open(src)), mode)); + } + } + Ok(()) +} + +impl<W: Write> Drop for Builder<W> { + fn drop(&mut self) { + let _ = self.finish(); + } +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/src/entry.rs cargo-0.26.0/vendor/tar-0.4.15/src/entry.rs --- cargo-0.25.0/vendor/tar-0.4.15/src/entry.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/src/entry.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,609 @@ +use std::borrow::Cow; +use std::cmp; +use std::fs; +use std::io::prelude::*; +use std::io::{self, Error, ErrorKind, SeekFrom}; +use std::marker; +use std::path::{Component, Path}; + +use filetime::{self, FileTime}; + +use {Header, Archive, PaxExtensions}; +use archive::ArchiveInner; +use error::TarError; +use header::bytes2path; +use other; +use pax::pax_extensions; + +/// A read-only view into an entry of an archive. +/// +/// This structure is a window into a portion of a borrowed archive which can +/// be inspected. It acts as a file handle by implementing the Reader trait. An +/// entry cannot be rewritten once inserted into an archive. +pub struct Entry<'a, R: 'a + Read> { + fields: EntryFields<'a>, + _ignored: marker::PhantomData<&'a Archive<R>>, +} + +// private implementation detail of `Entry`, but concrete (no type parameters) +// and also all-public to be constructed from other modules. +pub struct EntryFields<'a> { + pub long_pathname: Option<Vec<u8>>, + pub long_linkname: Option<Vec<u8>>, + pub pax_extensions: Option<Vec<u8>>, + pub header: Header, + pub size: u64, + pub header_pos: u64, + pub file_pos: u64, + pub data: Vec<EntryIo<'a>>, + pub unpack_xattrs: bool, + pub preserve_permissions: bool, +} + +pub enum EntryIo<'a> { + Pad(io::Take<io::Repeat>), + Data(io::Take<&'a ArchiveInner<Read + 'a>>), +} + +impl<'a, R: Read> Entry<'a, R> { + /// Returns the path name for this entry. + /// + /// This method may fail if the pathname is not valid unicode and this is + /// called on a Windows platform. + /// + /// Note that this function will convert any `\` characters to directory + /// separators, and it will not always return the same value as + /// `self.header().path()` as some archive formats have support for longer + /// path names described in separate entries. + /// + /// It is recommended to use this method instead of inspecting the `header` + /// directly to ensure that various archive formats are handled correctly. + pub fn path(&self) -> io::Result<Cow<Path>> { + self.fields.path() + } + + /// Returns the raw bytes listed for this entry. + /// + /// Note that this function will convert any `\` characters to directory + /// separators, and it will not always return the same value as + /// `self.header().path_bytes()` as some archive formats have support for + /// longer path names described in separate entries. + pub fn path_bytes(&self) -> Cow<[u8]> { + self.fields.path_bytes() + } + + /// Returns the link name for this entry, if any is found. + /// + /// This method may fail if the pathname is not valid unicode and this is + /// called on a Windows platform. `Ok(None)` being returned, however, + /// indicates that the link name was not present. + /// + /// Note that this function will convert any `\` characters to directory + /// separators, and it will not always return the same value as + /// `self.header().link_name()` as some archive formats have support for + /// longer path names described in separate entries. + /// + /// It is recommended to use this method instead of inspecting the `header` + /// directly to ensure that various archive formats are handled correctly. + pub fn link_name(&self) -> io::Result<Option<Cow<Path>>> { + self.fields.link_name() + } + + /// Returns the link name for this entry, in bytes, if listed. + /// + /// Note that this will not always return the same value as + /// `self.header().link_name_bytes()` as some archive formats have support for + /// longer path names described in separate entries. + pub fn link_name_bytes(&self) -> Option<Cow<[u8]>> { + self.fields.link_name_bytes() + } + + /// Returns an iterator over the pax extensions contained in this entry. + /// + /// Pax extensions are a form of archive where extra metadata is stored in + /// key/value pairs in entries before the entry they're intended to + /// describe. For example this can be used to describe long file name or + /// other metadata like atime/ctime/mtime in more precision. + /// + /// The returned iterator will yield key/value pairs for each extension. + /// + /// `None` will be returned if this entry does not indicate that it itself + /// contains extensions, or if there were no previous extensions describing + /// it. + /// + /// Note that global pax extensions are intended to be applied to all + /// archive entries. + /// + /// Also note that this function will read the entire entry if the entry + /// itself is a list of extensions. + pub fn pax_extensions(&mut self) -> io::Result<Option<PaxExtensions>> { + self.fields.pax_extensions() + } + + /// Returns access to the header of this entry in the archive. + /// + /// This provides access to the the metadata for this entry in the archive. + pub fn header(&self) -> &Header { + &self.fields.header + } + + /// Returns the starting position, in bytes, of the header of this entry in + /// the archive. + /// + /// The header is always a contiguous section of 512 bytes, so if the + /// underlying reader implements `Seek`, then the slice from `header_pos` to + /// `header_pos + 512` contains the raw header bytes. + pub fn raw_header_position(&self) -> u64 { + self.fields.header_pos + } + + /// Returns the starting position, in bytes, of the file of this entry in + /// the archive. + /// + /// If the file of this entry is continuous (e.g. not a sparse file), and + /// if the underlying reader implements `Seek`, then the slice from + /// `file_pos` to `file_pos + entry_size` contains the raw file bytes. + pub fn raw_file_position(&self) -> u64 { + self.fields.file_pos + } + + /// Writes this file to the specified location. + /// + /// This function will write the entire contents of this file into the + /// location specified by `dst`. Metadata will also be propagated to the + /// path `dst`. + /// + /// This function will create a file at the path `dst`, and it is required + /// that the intermediate directories are created. Any existing file at the + /// location `dst` will be overwritten. + /// + /// > **Note**: This function does not have as many sanity checks as + /// > `Archive::unpack` or `Entry::unpack_in`. As a result if you're + /// > thinking of unpacking untrusted tarballs you may want to review the + /// > implementations of the previous two functions and perhaps implement + /// > similar logic yourself. + /// + /// # Examples + /// + /// ```no_run + /// use std::fs::File; + /// use tar::Archive; + /// + /// let mut ar = Archive::new(File::open("foo.tar").unwrap()); + /// + /// for (i, file) in ar.entries().unwrap().enumerate() { + /// let mut file = file.unwrap(); + /// file.unpack(format!("file-{}", i)).unwrap(); + /// } + /// ``` + pub fn unpack<P: AsRef<Path>>(&mut self, dst: P) -> io::Result<()> { + self.fields.unpack(None, dst.as_ref()) + } + + /// Extracts this file under the specified path, avoiding security issues. + /// + /// This function will write the entire contents of this file into the + /// location obtained by appending the path of this file in the archive to + /// `dst`, creating any intermediate directories if needed. Metadata will + /// also be propagated to the path `dst`. Any existing file at the location + /// `dst` will be overwritten. + /// + /// This function carefully avoids writing outside of `dst`. If the file has + /// a '..' in its path, this function will skip it and return false. + /// + /// # Examples + /// + /// ```no_run + /// use std::fs::File; + /// use tar::Archive; + /// + /// let mut ar = Archive::new(File::open("foo.tar").unwrap()); + /// + /// for (i, file) in ar.entries().unwrap().enumerate() { + /// let mut file = file.unwrap(); + /// file.unpack_in("target").unwrap(); + /// } + /// ``` + pub fn unpack_in<P: AsRef<Path>>(&mut self, dst: P) -> io::Result<bool> { + self.fields.unpack_in(dst.as_ref()) + } + + /// Indicate whether extended file attributes (xattrs on Unix) are preserved + /// when unpacking this entry. + /// + /// This flag is disabled by default and is currently only implemented on + /// Unix using xattr support. This may eventually be implemented for + /// Windows, however, if other archive implementations are found which do + /// this as well. + pub fn set_unpack_xattrs(&mut self, unpack_xattrs: bool) { + self.fields.unpack_xattrs = unpack_xattrs; + } + + /// Indicate whether extended permissions (like suid on Unix) are preserved + /// when unpacking this entry. + /// + /// This flag is disabled by default and is currently only implemented on + /// Unix. + pub fn set_preserve_permissions(&mut self, preserve: bool) { + self.fields.preserve_permissions = preserve; + } +} + +impl<'a, R: Read> Read for Entry<'a, R> { + fn read(&mut self, into: &mut [u8]) -> io::Result<usize> { + self.fields.read(into) + } +} + +impl<'a> EntryFields<'a> { + pub fn from<R: Read>(entry: Entry<R>) -> EntryFields { + entry.fields + } + + pub fn into_entry<R: Read>(self) -> Entry<'a, R> { + Entry { + fields: self, + _ignored: marker::PhantomData, + } + } + + pub fn read_all(&mut self) -> io::Result<Vec<u8>> { + // Preallocate some data but don't let ourselves get too crazy now. + let cap = cmp::min(self.size, 128 * 1024); + let mut v = Vec::with_capacity(cap as usize); + self.read_to_end(&mut v).map(|_| v) + } + + fn path(&self) -> io::Result<Cow<Path>> { + bytes2path(self.path_bytes()) + } + + fn path_bytes(&self) -> Cow<[u8]> { + match self.long_pathname { + Some(ref bytes) => { + if let Some(&0) = bytes.last() { + Cow::Borrowed(&bytes[..bytes.len() - 1]) + } else { + Cow::Borrowed(bytes) + } + } + None => self.header.path_bytes(), + } + } + + /// Gets the path in a "lossy" way, used for error reporting ONLY. + fn path_lossy(&self) -> String { + String::from_utf8_lossy(&self.path_bytes()).to_string() + } + + fn link_name(&self) -> io::Result<Option<Cow<Path>>> { + match self.link_name_bytes() { + Some(bytes) => bytes2path(bytes).map(Some), + None => Ok(None), + } + } + + fn link_name_bytes(&self) -> Option<Cow<[u8]>> { + match self.long_linkname { + Some(ref bytes) => { + if let Some(&0) = bytes.last() { + Some(Cow::Borrowed(&bytes[..bytes.len() - 1])) + } else { + Some(Cow::Borrowed(bytes)) + } + } + None => self.header.link_name_bytes(), + } + } + + fn pax_extensions(&mut self) -> io::Result<Option<PaxExtensions>> { + if self.pax_extensions.is_none() { + if !self.header.entry_type().is_pax_global_extensions() && + !self.header.entry_type().is_pax_local_extensions() { + return Ok(None) + } + self.pax_extensions = Some(try!(self.read_all())); + } + Ok(Some(pax_extensions(self.pax_extensions.as_ref().unwrap()))) + } + + fn unpack_in(&mut self, dst: &Path) -> io::Result<bool> { + // Notes regarding bsdtar 2.8.3 / libarchive 2.8.3: + // * Leading '/'s are trimmed. For example, `///test` is treated as + // `test`. + // * If the filename contains '..', then the file is skipped when + // extracting the tarball. + // * '//' within a filename is effectively skipped. An error is + // logged, but otherwise the effect is as if any two or more + // adjacent '/'s within the filename were consolidated into one + // '/'. + // + // Most of this is handled by the `path` module of the standard + // library, but we specially handle a few cases here as well. + + let mut file_dst = dst.to_path_buf(); + { + let path = try!(self.path().map_err(|e| { + TarError::new(&format!("invalid path in entry header: {}", self.path_lossy()), e) + })); + for part in path.components() { + match part { + // Leading '/' characters, root paths, and '.' + // components are just ignored and treated as "empty + // components" + Component::Prefix(..) | + Component::RootDir | + Component::CurDir => continue, + + // If any part of the filename is '..', then skip over + // unpacking the file to prevent directory traversal + // security issues. See, e.g.: CVE-2001-1267, + // CVE-2002-0399, CVE-2005-1918, CVE-2007-4131 + Component::ParentDir => return Ok(false), + + Component::Normal(part) => file_dst.push(part), + } + } + } + + // Skip cases where only slashes or '.' parts were seen, because + // this is effectively an empty filename. + if *dst == *file_dst { + return Ok(true); + } + + // Skip entries without a parent (i.e. outside of FS root) + let parent = match file_dst.parent() { + Some(p) => p, + None => return Ok(false), + }; + + if !parent.exists() { + try!(fs::create_dir_all(&parent).map_err(|e| { + TarError::new(&format!("failed to create `{}`", + parent.display()), e) + })); + } + + // Abort if target (canonical) parent is outside of `dst` + let canon_parent = try!(parent.canonicalize().map_err(|err| { + Error::new( + err.kind(), + format!("{} while canonicalizing {}", err, parent.display()), + ) + })); + let canon_target = try!(dst.canonicalize().map_err(|err| { + Error::new( + err.kind(), + format!("{} while canonicalizing {}", err, dst.display()), + ) + })); + if !canon_parent.starts_with(&canon_target) { + let err = TarError::new( + &format!( + "trying to unpack outside of destination path: {}", + canon_target.display() + ), + // TODO: use ErrorKind::InvalidInput here? (minor breaking change) + Error::new(ErrorKind::Other, "Invalid argument"), + ); + return Err(err.into()); + } + + try!(self.unpack(Some(&canon_target), &file_dst).map_err(|e| { + TarError::new(&format!("failed to unpack `{}`", file_dst.display()), e) + })); + + Ok(true) + } + + /// Returns access to the header of this entry in the archive. + fn unpack(&mut self, + target_base: Option<&Path>, + dst: &Path) -> io::Result<()> { + let kind = self.header.entry_type(); + if kind.is_dir() { + // If the directory already exists just let it slide + let prev = fs::metadata(&dst); + if prev.map(|m| m.is_dir()).unwrap_or(false) { + return Ok(()) + } + return fs::create_dir(&dst).map_err(|err| Error::new( + err.kind(), + format!("{} when creating dir {}", err, dst.display()) + )); + } else if kind.is_hard_link() || kind.is_symlink() { + let src = match try!(self.link_name()) { + Some(name) => name, + None => return Err(other(&format!( + "hard link listed for {} but no link name found", + String::from_utf8_lossy(self.header.as_bytes()) + ))), + }; + + if src.iter().count() == 0 { + return Err(other(&format!( + "symlink destination for {} is empty", + String::from_utf8_lossy(self.header.as_bytes()) + ))); + } + + return if kind.is_hard_link() { + let link_src = match target_base { + None => src.into_owned(), + Some(ref p) => p.join(src), + }; + fs::hard_link(&link_src, dst).map_err(|err| Error::new( + err.kind(), + format!( + "{} when hard linking {} to {}", + err, + link_src.display(), + dst.display() + ) + )) + } else { + symlink(&src, dst).map_err(|err| Error::new( + err.kind(), + format!( + "{} when symlinking {} to {}", + err, + src.display(), + dst.display() + ) + )) + }; + + #[cfg(windows)] + fn symlink(src: &Path, dst: &Path) -> io::Result<()> { + ::std::os::windows::fs::symlink_file(src, dst) + } + + #[cfg(any(unix, target_os = "redox"))] + fn symlink(src: &Path, dst: &Path) -> io::Result<()> { + ::std::os::unix::fs::symlink(src, dst) + } + } else if kind.is_pax_global_extensions() || + kind.is_pax_local_extensions() || + kind.is_gnu_longname() || + kind.is_gnu_longlink() { + return Ok(()) + }; + + // Note the lack of `else` clause above. According to the FreeBSD + // documentation: + // + // > A POSIX-compliant implementation must treat any unrecognized + // > typeflag value as a regular file. + // + // As a result if we don't recognize the kind we just write out the file + // as we would normally. + + try!(fs::File::create(dst).and_then(|mut f| { + for io in self.data.drain(..) { + match io { + EntryIo::Data(mut d) => { + let expected = d.limit(); + if try!(io::copy(&mut d, &mut f)) != expected { + return Err(other("failed to write entire file")); + } + } + EntryIo::Pad(d) => { + // TODO: checked cast to i64 + let to = SeekFrom::Current(d.limit() as i64); + let size = try!(f.seek(to)); + try!(f.set_len(size)); + } + } + } + Ok(()) + }).map_err(|e| { + let header = self.header.path_bytes(); + TarError::new(&format!("failed to unpack `{}` into `{}`", + String::from_utf8_lossy(&header), + dst.display()), e) + })); + + if let Ok(mtime) = self.header.mtime() { + let mtime = FileTime::from_unix_time(mtime as i64, 0); + try!(filetime::set_file_times(dst, mtime, mtime).map_err(|e| { + TarError::new(&format!("failed to set mtime for `{}`", + dst.display()), e) + })); + } + if let Ok(mode) = self.header.mode() { + try!(set_perms(dst, mode, self.preserve_permissions).map_err(|e| { + TarError::new(&format!("failed to set permissions to {:o} \ + for `{}`", mode, dst.display()), e) + })); + } + if self.unpack_xattrs { + try!(set_xattrs(self, dst)); + } + return Ok(()); + + #[cfg(any(unix, target_os = "redox"))] + fn set_perms(dst: &Path, mode: u32, preserve: bool) -> io::Result<()> { + use std::os::unix::prelude::*; + + let mode = if preserve { + mode + } else { + mode & 0o777 + }; + + let perm = fs::Permissions::from_mode(mode as _); + fs::set_permissions(dst, perm) + } + #[cfg(windows)] + fn set_perms(dst: &Path, mode: u32, _preserve: bool) -> io::Result<()> { + let mut perm = try!(fs::metadata(dst)).permissions(); + perm.set_readonly(mode & 0o200 != 0o200); + fs::set_permissions(dst, perm) + } + + #[cfg(all(unix, feature = "xattr"))] + fn set_xattrs(me: &mut EntryFields, dst: &Path) -> io::Result<()> { + use std::os::unix::prelude::*; + use std::ffi::OsStr; + use xattr; + + let exts = match me.pax_extensions() { + Ok(Some(e)) => e, + _ => return Ok(()), + }; + let exts = exts.filter_map(|e| e.ok()).filter_map(|e| { + let key = e.key_bytes(); + let prefix = b"SCHILY.xattr."; + if key.starts_with(prefix) { + Some((&key[prefix.len()..], e)) + } else { + None + } + }).map(|(key, e)| { + (OsStr::from_bytes(key), e.value_bytes()) + }); + + for (key, value) in exts { + try!(xattr::set(dst, key, value).map_err(|e| { + TarError::new(&format!("failed to set extended \ + attributes to {}. \ + Xattrs: key={:?}, value={:?}.", + dst.display(), + key, + String::from_utf8_lossy(value)), + e) + })); + } + + Ok(()) + } + // Windows does not completely support posix xattrs + // https://en.wikipedia.org/wiki/Extended_file_attributes#Windows_NT + #[cfg(any(windows, target_os = "redox", not(feature = "xattr")))] + fn set_xattrs(_: &mut EntryFields, _: &Path) -> io::Result<()> { + Ok(()) + } + } +} + +impl<'a> Read for EntryFields<'a> { + fn read(&mut self, into: &mut [u8]) -> io::Result<usize> { + loop { + match self.data.get_mut(0).map(|io| io.read(into)) { + Some(Ok(0)) => { self.data.remove(0); } + Some(r) => return r, + None => return Ok(0), + } + } + } +} + +impl<'a> Read for EntryIo<'a> { + fn read(&mut self, into: &mut [u8]) -> io::Result<usize> { + match *self { + EntryIo::Pad(ref mut io) => io.read(into), + EntryIo::Data(ref mut io) => io.read(into), + } + } +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/src/entry_type.rs cargo-0.26.0/vendor/tar-0.4.15/src/entry_type.rs --- cargo-0.25.0/vendor/tar-0.4.15/src/entry_type.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/src/entry_type.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,194 @@ +// See https://en.wikipedia.org/wiki/Tar_%28computing%29#UStar_format +/// Indicate for the type of file described by a header. +/// +/// Each `Header` has an `entry_type` method returning an instance of this type +/// which can be used to inspect what the header is describing. + +/// A non-exhaustive enum representing the possible entry types +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum EntryType { + /// Regular file + Regular, + /// Hard link + Link, + /// Symbolic link + Symlink, + /// Character device + Char, + /// Block device + Block, + /// Directory + Directory, + /// Named pipe (fifo) + Fifo, + /// Implementation-defined 'high-performance' type, treated as regular file + Continuous, + /// GNU extension - long file name + GNULongName, + /// GNU extension - long link name (link target) + GNULongLink, + /// GNU extension - sparse file + GNUSparse, + /// Global extended header + XGlobalHeader, + /// Extended Header + XHeader, + /// Hints that destructuring should not be exhaustive. + /// + /// This enum may grow additional variants, so this makes sure clients + /// don't count on exhaustive matching. (Otherwise, adding a new variant + /// could break existing code.) + #[doc(hidden)] + __Nonexhaustive(u8), +} + +impl EntryType { + /// Creates a new entry type from a raw byte. + /// + /// Note that the other named constructors of entry type may be more + /// appropriate to create a file type from. + pub fn new(byte: u8) -> EntryType { + match byte { + b'\x00' | + b'0' => EntryType::Regular, + b'1' => EntryType::Link, + b'2' => EntryType::Symlink, + b'3' => EntryType::Char, + b'4' => EntryType::Block, + b'5' => EntryType::Directory, + b'6' => EntryType::Fifo, + b'7' => EntryType::Continuous, + b'x' => EntryType::XHeader, + b'g' => EntryType::XGlobalHeader, + b'L' => EntryType::GNULongName, + b'K' => EntryType::GNULongLink, + b'S' => EntryType::GNUSparse, + b => EntryType::__Nonexhaustive(b), + } + } + + /// Returns the raw underlying byte that this entry type represents. + pub fn as_byte(&self) -> u8 { + match *self { + EntryType::Regular => b'0', + EntryType::Link => b'1', + EntryType::Symlink => b'2', + EntryType::Char => b'3', + EntryType::Block => b'4', + EntryType::Directory => b'5', + EntryType::Fifo => b'6', + EntryType::Continuous => b'7', + EntryType::XHeader => b'x', + EntryType::XGlobalHeader => b'g', + EntryType::GNULongName => b'L', + EntryType::GNULongLink => b'K', + EntryType::GNUSparse => b'S', + EntryType::__Nonexhaustive(b) => b, + } + } + + /// Creates a new entry type representing a regular file. + pub fn file() -> EntryType { + EntryType::Regular + } + + /// Creates a new entry type representing a hard link. + pub fn hard_link() -> EntryType { + EntryType::Link + } + + /// Creates a new entry type representing a symlink. + pub fn symlink() -> EntryType { + EntryType::Symlink + } + + /// Creates a new entry type representing a character special device. + pub fn character_special() -> EntryType { + EntryType::Char + } + + /// Creates a new entry type representing a block special device. + pub fn block_special() -> EntryType { + EntryType::Block + } + + /// Creates a new entry type representing a directory. + pub fn dir() -> EntryType { + EntryType::Directory + } + + /// Creates a new entry type representing a FIFO. + pub fn fifo() -> EntryType { + EntryType::Fifo + } + + /// Creates a new entry type representing a contiguous file. + pub fn contiguous() -> EntryType { + EntryType::Continuous + } + + /// Returns whether this type represents a regular file. + pub fn is_file(&self) -> bool { + self == &EntryType::Regular + } + + /// Returns whether this type represents a hard link. + pub fn is_hard_link(&self) -> bool { + self == &EntryType::Link + } + + /// Returns whether this type represents a symlink. + pub fn is_symlink(&self) -> bool { + self == &EntryType::Symlink + } + + /// Returns whether this type represents a character special device. + pub fn is_character_special(&self) -> bool { + self == &EntryType::Char + } + + /// Returns whether this type represents a block special device. + pub fn is_block_special(&self) -> bool { + self == &EntryType::Block + } + + /// Returns whether this type represents a directory. + pub fn is_dir(&self) -> bool { + self == &EntryType::Directory + } + + /// Returns whether this type represents a FIFO. + pub fn is_fifo(&self) -> bool { + self == &EntryType::Fifo + } + + /// Returns whether this type represents a contiguous file. + pub fn is_contiguous(&self) -> bool { + self == &EntryType::Continuous + } + + /// Returns whether this type represents a GNU long name header. + pub fn is_gnu_longname(&self) -> bool { + self == &EntryType::GNULongName + } + + /// Returns whether this type represents a GNU sparse header. + pub fn is_gnu_sparse(&self) -> bool { + self == &EntryType::GNUSparse + } + + /// Returns whether this type represents a GNU long link header. + pub fn is_gnu_longlink(&self) -> bool { + self == &EntryType::GNULongLink + } + + /// Returns whether this type represents a GNU long name header. + pub fn is_pax_global_extensions(&self) -> bool { + self == &EntryType::XGlobalHeader + } + + /// Returns whether this type represents a GNU long link header. + pub fn is_pax_local_extensions(&self) -> bool { + self == &EntryType::XHeader + } +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/src/error.rs cargo-0.26.0/vendor/tar-0.4.15/src/error.rs --- cargo-0.25.0/vendor/tar-0.4.15/src/error.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/src/error.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,40 @@ +use std::error; +use std::fmt; +use std::io::{self, Error}; + +#[derive(Debug)] +pub struct TarError { + desc: String, + io: io::Error, +} + +impl TarError { + pub fn new(desc: &str, err: Error) -> TarError { + TarError { + desc: desc.to_string(), + io: err, + } + } +} + +impl error::Error for TarError { + fn description(&self) -> &str { + &self.desc + } + + fn cause(&self) -> Option<&error::Error> { + Some(&self.io) + } +} + +impl fmt::Display for TarError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.desc.fmt(f) + } +} + +impl From<TarError> for Error { + fn from(t: TarError) -> Error { + Error::new(t.io.kind(), t) + } +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/src/header.rs cargo-0.26.0/vendor/tar-0.4.15/src/header.rs --- cargo-0.25.0/vendor/tar-0.4.15/src/header.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/src/header.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1459 @@ +#[cfg(any(unix, target_os = "redox"))] use std::os::unix::prelude::*; +#[cfg(windows)] use std::os::windows::prelude::*; + +use std::borrow::Cow; +use std::fmt; +use std::fs; +use std::io; +use std::iter::repeat; +use std::iter; +use std::mem; +use std::path::{Path, PathBuf, Component}; +use std::str; + +use EntryType; +use other; + +/// Representation of the header of an entry in an archive +#[repr(C)] +#[allow(missing_docs)] +pub struct Header { + bytes: [u8; 512], +} + +/// Declares the information that should be included when filling a Header +/// from filesystem metadata. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum HeaderMode { + /// All supported metadata, including mod/access times and ownership will + /// be included. + Complete, + + /// Only metadata that is directly relevant to the identity of a file will + /// be included. In particular, ownership and mod/access times are excluded. + Deterministic, + + #[doc(hidden)] + __Nonexhaustive, +} + +/// Representation of the header of an entry in an archive +#[repr(C)] +#[allow(missing_docs)] +pub struct OldHeader { + pub name: [u8; 100], + pub mode: [u8; 8], + pub uid: [u8; 8], + pub gid: [u8; 8], + pub size: [u8; 12], + pub mtime: [u8; 12], + pub cksum: [u8; 8], + pub linkflag: [u8; 1], + pub linkname: [u8; 100], + pub pad: [u8; 255], +} + +/// Representation of the header of an entry in an archive +#[repr(C)] +#[allow(missing_docs)] +pub struct UstarHeader { + pub name: [u8; 100], + pub mode: [u8; 8], + pub uid: [u8; 8], + pub gid: [u8; 8], + pub size: [u8; 12], + pub mtime: [u8; 12], + pub cksum: [u8; 8], + pub typeflag: [u8; 1], + pub linkname: [u8; 100], + + // UStar format + pub magic: [u8; 6], + pub version: [u8; 2], + pub uname: [u8; 32], + pub gname: [u8; 32], + pub dev_major: [u8; 8], + pub dev_minor: [u8; 8], + pub prefix: [u8; 155], + pub pad: [u8; 12], +} + +/// Representation of the header of an entry in an archive +#[repr(C)] +#[allow(missing_docs)] +pub struct GnuHeader { + pub name: [u8; 100], + pub mode: [u8; 8], + pub uid: [u8; 8], + pub gid: [u8; 8], + pub size: [u8; 12], + pub mtime: [u8; 12], + pub cksum: [u8; 8], + pub typeflag: [u8; 1], + pub linkname: [u8; 100], + + // GNU format + pub magic: [u8; 6], + pub version: [u8; 2], + pub uname: [u8; 32], + pub gname: [u8; 32], + pub dev_major: [u8; 8], + pub dev_minor: [u8; 8], + pub atime: [u8; 12], + pub ctime: [u8; 12], + pub offset: [u8; 12], + pub longnames: [u8; 4], + pub unused: [u8; 1], + pub sparse: [GnuSparseHeader; 4], + pub isextended: [u8; 1], + pub realsize: [u8; 12], + pub pad: [u8; 17], +} + +/// Description of the header of a spare entry. +/// +/// Specifies the offset/number of bytes of a chunk of data in octal. +#[repr(C)] +#[allow(missing_docs)] +pub struct GnuSparseHeader { + pub offset: [u8; 12], + pub numbytes: [u8; 12], +} + +/// Representation of the entry found to represent extended GNU sparse files. +/// +/// When a `GnuHeader` has the `isextended` flag set to `1` then the contents of +/// the next entry will be one of these headers. +#[repr(C)] +#[allow(missing_docs)] +pub struct GnuExtSparseHeader { + pub sparse: [GnuSparseHeader; 21], + pub isextended: [u8; 1], + pub padding: [u8; 7], +} + +impl Header { + /// Creates a new blank GNU header. + /// + /// The GNU style header is the default for this library and allows various + /// extensions such as long path names, long link names, and setting the + /// atime/ctime metadata attributes of files. + pub fn new_gnu() -> Header { + let mut header = Header { bytes: [0; 512] }; + unsafe { + let gnu = cast_mut::<_, GnuHeader>(&mut header); + gnu.magic = *b"ustar "; + gnu.version = *b" \0"; + } + header.set_mtime(0); + header + } + + /// Creates a new blank UStar header. + /// + /// The UStar style header is an extension of the original archive header + /// which enables some extra metadata along with storing a longer (but not + /// too long) path name. + /// + /// UStar is also the basis used for pax archives. + pub fn new_ustar() -> Header { + let mut header = Header { bytes: [0; 512] }; + unsafe { + let gnu = cast_mut::<_, UstarHeader>(&mut header); + gnu.magic = *b"ustar\0"; + gnu.version = *b"00"; + } + header.set_mtime(0); + header + } + + /// Creates a new blank old header. + /// + /// This header format is the original archive header format which all other + /// versions are compatible with (e.g. they are a superset). This header + /// format limits the path name limit and isn't able to contain extra + /// metadata like atime/ctime. + pub fn new_old() -> Header { + let mut header = Header { bytes: [0; 512] }; + header.set_mtime(0); + header + } + + fn is_ustar(&self) -> bool { + let ustar = unsafe { cast::<_, UstarHeader>(self) }; + ustar.magic[..] == b"ustar\0"[..] && ustar.version[..] == b"00"[..] + } + + fn is_gnu(&self) -> bool { + let ustar = unsafe { cast::<_, UstarHeader>(self) }; + ustar.magic[..] == b"ustar "[..] && ustar.version[..] == b" \0"[..] + } + + /// View this archive header as a raw "old" archive header. + /// + /// This view will always succeed as all archive header formats will fill + /// out at least the fields specified in the old header format. + pub fn as_old(&self) -> &OldHeader { + unsafe { cast(self) } + } + + /// Same as `as_old`, but the mutable version. + pub fn as_old_mut(&mut self) -> &mut OldHeader { + unsafe { cast_mut(self) } + } + + /// View this archive header as a raw UStar archive header. + /// + /// The UStar format is an extension to the tar archive format which enables + /// longer pathnames and a few extra attributes such as the group and user + /// name. + /// + /// This cast may not succeed as this function will test whether the + /// magic/version fields of the UStar format have the appropriate values, + /// returning `None` if they aren't correct. + pub fn as_ustar(&self) -> Option<&UstarHeader> { + if self.is_ustar() {Some(unsafe { cast(self) })} else {None} + } + + /// Same as `as_ustar_mut`, but the mutable version. + pub fn as_ustar_mut(&mut self) -> Option<&mut UstarHeader> { + if self.is_ustar() {Some(unsafe { cast_mut(self) })} else {None} + } + + /// View this archive header as a raw GNU archive header. + /// + /// The GNU format is an extension to the tar archive format which enables + /// longer pathnames and a few extra attributes such as the group and user + /// name. + /// + /// This cast may not succeed as this function will test whether the + /// magic/version fields of the GNU format have the appropriate values, + /// returning `None` if they aren't correct. + pub fn as_gnu(&self) -> Option<&GnuHeader> { + if self.is_gnu() {Some(unsafe { cast(self) })} else {None} + } + + /// Same as `as_gnu`, but the mutable version. + pub fn as_gnu_mut(&mut self) -> Option<&mut GnuHeader> { + if self.is_gnu() {Some(unsafe { cast_mut(self) })} else {None} + } + + /// Treats the given byte slice as a header. + /// + /// Panics if the length of the passed slice is not equal to 512. + pub fn from_byte_slice(bytes: &[u8]) -> &Header { + assert_eq!(bytes.len(), mem::size_of::<Header>()); + assert_eq!(mem::align_of_val(bytes), mem::align_of::<Header>()); + unsafe { &*(bytes.as_ptr() as * const Header) } + } + + /// Returns a view into this header as a byte array. + pub fn as_bytes(&self) -> &[u8; 512] { + &self.bytes + } + + /// Returns a view into this header as a byte array. + pub fn as_mut_bytes(&mut self) -> &mut [u8; 512] { + &mut self.bytes + } + + /// Blanket sets the metadata in this header from the metadata argument + /// provided. + /// + /// This is useful for initializing a `Header` from the OS's metadata from a + /// file. By default, this will use `HeaderMode::Complete` to include all + /// metadata. + pub fn set_metadata(&mut self, meta: &fs::Metadata) { + self.fill_from(meta, HeaderMode::Complete); + } + + /// Sets only the metadata relevant to the given HeaderMode in this header + /// from the metadata argument provided. + pub fn set_metadata_in_mode(&mut self, meta: &fs::Metadata, mode: HeaderMode) { + self.fill_from(meta, mode); + } + + /// Returns the size of entry's data this header represents. + /// + /// This is different from `Header::size` for sparse files, which have + /// some longer `size()` but shorter `entry_size()`. The `entry_size()` + /// listed here should be the number of bytes in the archive this header + /// describes. + /// + /// May return an error if the field is corrupted. + pub fn entry_size(&self) -> io::Result<u64> { + octal_from(&self.as_old().size).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting size for {}", err, self.path_lossy()), + )) + } + + /// Returns the file size this header represents. + /// + /// May return an error if the field is corrupted. + pub fn size(&self) -> io::Result<u64> { + if self.entry_type().is_gnu_sparse() { + self.as_gnu().ok_or_else(|| { + other("sparse header was not a gnu header") + }).and_then(|h| h.real_size()) + } else { + self.entry_size() + } + } + + /// Encodes the `size` argument into the size field of this header. + pub fn set_size(&mut self, size: u64) { + octal_into(&mut self.as_old_mut().size, size) + } + + /// Returns the raw path name stored in this header. + /// + /// This method may fail if the pathname is not valid unicode and this is + /// called on a Windows platform. + /// + /// Note that this function will convert any `\` characters to directory + /// separators. + pub fn path(&self) -> io::Result<Cow<Path>> { + bytes2path(self.path_bytes()) + } + + /// Returns the pathname stored in this header as a byte array. + /// + /// This function is guaranteed to succeed, but you may wish to call the + /// `path` method to convert to a `Path`. + /// + /// Note that this function will convert any `\` characters to directory + /// separators. + pub fn path_bytes(&self) -> Cow<[u8]> { + if let Some(ustar) = self.as_ustar() { + ustar.path_bytes() + } else { + let name = truncate(&self.as_old().name); + Cow::Borrowed(name) + } + } + + /// Gets the path in a "lossy" way, used for error reporting ONLY. + fn path_lossy(&self) -> String { + String::from_utf8_lossy(&self.path_bytes()).to_string() + } + + /// Sets the path name for this header. + /// + /// This function will set the pathname listed in this header, encoding it + /// in the appropriate format. May fail if the path is too long or if the + /// path specified is not unicode and this is a Windows platform. + pub fn set_path<P: AsRef<Path>>(&mut self, p: P) -> io::Result<()> { + self._set_path(p.as_ref()) + } + + fn _set_path(&mut self, path: &Path) -> io::Result<()> { + if let Some(ustar) = self.as_ustar_mut() { + return ustar.set_path(path) + } + copy_path_into(&mut self.as_old_mut().name, path, false) + .map_err(|err| io::Error::new( + err.kind(), + format!( "{} when setting path for {}", err, self.path_lossy()), + )) + } + + /// Returns the link name stored in this header, if any is found. + /// + /// This method may fail if the pathname is not valid unicode and this is + /// called on a Windows platform. `Ok(None)` being returned, however, + /// indicates that the link name was not present. + /// + /// Note that this function will convert any `\` characters to directory + /// separators. + pub fn link_name(&self) -> io::Result<Option<Cow<Path>>> { + match self.link_name_bytes() { + Some(bytes) => bytes2path(bytes).map(Some), + None => Ok(None), + } + } + + /// Returns the link name stored in this header as a byte array, if any. + /// + /// This function is guaranteed to succeed, but you may wish to call the + /// `link_name` method to convert to a `Path`. + /// + /// Note that this function will convert any `\` characters to directory + /// separators. + pub fn link_name_bytes(&self) -> Option<Cow<[u8]>> { + let old = self.as_old(); + if old.linkname[0] != 0 { + Some(Cow::Borrowed(truncate(&old.linkname))) + } else { + None + } + } + + /// Sets the path name for this header. + /// + /// This function will set the pathname listed in this header, encoding it + /// in the appropriate format. May fail if the path is too long or if the + /// path specified is not unicode and this is a Windows platform. + pub fn set_link_name<P: AsRef<Path>>(&mut self, p: P) -> io::Result<()> { + self._set_link_name(p.as_ref()) + } + + fn _set_link_name(&mut self, path: &Path) -> io::Result<()> { + copy_path_into(&mut self.as_old_mut().linkname, path, true) + .map_err(|err| io::Error::new( + err.kind(), + format!( "{} when setting link name for {}", err, self.path_lossy()), + )) + } + + /// Returns the mode bits for this file + /// + /// May return an error if the field is corrupted. + pub fn mode(&self) -> io::Result<u32> { + octal_from(&self.as_old().mode).map(|u| u as u32).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting mode for {}", err, self.path_lossy()), + )) + } + + /// Encodes the `mode` provided into this header. + pub fn set_mode(&mut self, mode: u32) { + octal_into(&mut self.as_old_mut().mode, mode); + } + + /// Returns the value of the owner's user ID field + /// + /// May return an error if the field is corrupted. + pub fn uid(&self) -> io::Result<u32> { + octal_from(&self.as_old().uid).map(|u| u as u32).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting uid for {}", err, self.path_lossy()), + )) + } + + /// Encodes the `uid` provided into this header. + pub fn set_uid(&mut self, uid: u32) { + octal_into(&mut self.as_old_mut().uid, uid); + } + + /// Returns the value of the group's user ID field + pub fn gid(&self) -> io::Result<u32> { + octal_from(&self.as_old().gid).map(|u| u as u32).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting gid for {}", err, self.path_lossy()), + )) + } + + /// Encodes the `gid` provided into this header. + pub fn set_gid(&mut self, gid: u32) { + octal_into(&mut self.as_old_mut().gid, gid); + } + + /// Returns the last modification time in Unix time format + pub fn mtime(&self) -> io::Result<u64> { + octal_from(&self.as_old().mtime).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting mtime for {}", err, self.path_lossy()), + )) + } + + /// Encodes the `mtime` provided into this header. + /// + /// Note that this time is typically a number of seconds passed since + /// January 1, 1970. + pub fn set_mtime(&mut self, mtime: u64) { + octal_into(&mut self.as_old_mut().mtime, mtime); + } + + /// Return the user name of the owner of this file. + /// + /// A return value of `Ok(Some(..))` indicates that the user name was + /// present and was valid utf-8, `Ok(None)` indicates that the user name is + /// not present in this archive format, and `Err` indicates that the user + /// name was present but was not valid utf-8. + pub fn username(&self) -> Result<Option<&str>, str::Utf8Error> { + match self.username_bytes() { + Some(bytes) => str::from_utf8(bytes).map(Some), + None => Ok(None), + } + } + + /// Returns the user name of the owner of this file, if present. + /// + /// A return value of `None` indicates that the user name is not present in + /// this header format. + pub fn username_bytes(&self) -> Option<&[u8]> { + if let Some(ustar) = self.as_ustar() { + Some(ustar.username_bytes()) + } else if let Some(gnu) = self.as_gnu() { + Some(gnu.username_bytes()) + } else { + None + } + } + + /// Sets the username inside this header. + /// + /// This function will return an error if this header format cannot encode a + /// user name or the name is too long. + pub fn set_username(&mut self, name: &str) -> io::Result<()> { + if let Some(ustar) = self.as_ustar_mut() { + return ustar.set_username(name) + } + if let Some(gnu) = self.as_gnu_mut() { + gnu.set_username(name) + } else { + Err(other("not a ustar or gnu archive, cannot set username")) + } + } + + /// Return the group name of the owner of this file. + /// + /// A return value of `Ok(Some(..))` indicates that the group name was + /// present and was valid utf-8, `Ok(None)` indicates that the group name is + /// not present in this archive format, and `Err` indicates that the group + /// name was present but was not valid utf-8. + pub fn groupname(&self) -> Result<Option<&str>, str::Utf8Error> { + match self.groupname_bytes() { + Some(bytes) => str::from_utf8(bytes).map(Some), + None => Ok(None), + } + } + + /// Returns the group name of the owner of this file, if present. + /// + /// A return value of `None` indicates that the group name is not present in + /// this header format. + pub fn groupname_bytes(&self) -> Option<&[u8]> { + if let Some(ustar) = self.as_ustar() { + Some(ustar.groupname_bytes()) + } else if let Some(gnu) = self.as_gnu() { + Some(gnu.groupname_bytes()) + } else { + None + } + } + + /// Sets the group name inside this header. + /// + /// This function will return an error if this header format cannot encode a + /// group name or the name is too long. + pub fn set_groupname(&mut self, name: &str) -> io::Result<()> { + if let Some(ustar) = self.as_ustar_mut() { + return ustar.set_groupname(name) + } + if let Some(gnu) = self.as_gnu_mut() { + gnu.set_groupname(name) + } else { + Err(other("not a ustar or gnu archive, cannot set groupname")) + } + } + + /// Returns the device major number, if present. + /// + /// This field may not be present in all archives, and it may not be + /// correctly formed in all archives. `Ok(Some(..))` means it was present + /// and correctly decoded, `Ok(None)` indicates that this header format does + /// not include the device major number, and `Err` indicates that it was + /// present and failed to decode. + pub fn device_major(&self) -> io::Result<Option<u32>> { + if let Some(ustar) = self.as_ustar() { + ustar.device_major().map(Some) + } else if let Some(gnu) = self.as_gnu() { + gnu.device_major().map(Some) + } else { + Ok(None) + } + } + + /// Encodes the value `major` into the dev_major field of this header. + /// + /// This function will return an error if this header format cannot encode a + /// major device number. + pub fn set_device_major(&mut self, major: u32) -> io::Result<()> { + if let Some(ustar) = self.as_ustar_mut() { + return Ok(ustar.set_device_major(major)) + } + if let Some(gnu) = self.as_gnu_mut() { + Ok(gnu.set_device_major(major)) + } else { + Err(other("not a ustar or gnu archive, cannot set dev_major")) + } + } + + /// Returns the device minor number, if present. + /// + /// This field may not be present in all archives, and it may not be + /// correctly formed in all archives. `Ok(Some(..))` means it was present + /// and correctly decoded, `Ok(None)` indicates that this header format does + /// not include the device minor number, and `Err` indicates that it was + /// present and failed to decode. + pub fn device_minor(&self) -> io::Result<Option<u32>> { + if let Some(ustar) = self.as_ustar() { + ustar.device_minor().map(Some) + } else if let Some(gnu) = self.as_gnu() { + gnu.device_minor().map(Some) + } else { + Ok(None) + } + } + + /// Encodes the value `minor` into the dev_minor field of this header. + /// + /// This function will return an error if this header format cannot encode a + /// minor device number. + pub fn set_device_minor(&mut self, minor: u32) -> io::Result<()> { + if let Some(ustar) = self.as_ustar_mut() { + return Ok(ustar.set_device_minor(minor)) + } + if let Some(gnu) = self.as_gnu_mut() { + Ok(gnu.set_device_minor(minor)) + } else { + Err(other("not a ustar or gnu archive, cannot set dev_minor")) + } + } + + /// Returns the type of file described by this header. + pub fn entry_type(&self) -> EntryType { + EntryType::new(self.as_old().linkflag[0]) + } + + /// Sets the type of file that will be described by this header. + pub fn set_entry_type(&mut self, ty: EntryType) { + self.as_old_mut().linkflag = [ty.as_byte()]; + } + + /// Returns the checksum field of this header. + /// + /// May return an error if the field is corrupted. + pub fn cksum(&self) -> io::Result<u32> { + octal_from(&self.as_old().cksum).map(|u| u as u32).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting cksum for {}", err, self.path_lossy()), + )) + } + + /// Sets the checksum field of this header based on the current fields in + /// this header. + pub fn set_cksum(&mut self) { + let cksum = self.calculate_cksum(); + octal_into(&mut self.as_old_mut().cksum, cksum); + } + + fn calculate_cksum(&self) -> u32 { + let old = self.as_old(); + let start = old as *const _ as usize; + let cksum_start = old.cksum.as_ptr() as *const _ as usize; + let offset = cksum_start - start; + let len = old.cksum.len(); + self.bytes[0..offset].iter() + .chain(iter::repeat(&b' ').take(len)) + .chain(&self.bytes[offset + len..]) + .fold(0, |a, b| a + (*b as u32)) + } + + fn fill_from(&mut self, meta: &fs::Metadata, mode: HeaderMode) { + self.fill_platform_from(meta, mode); + // Set size of directories to zero + self.set_size(if meta.is_dir() || meta.file_type().is_symlink() { 0 } else { meta.len() }); + if let Some(ustar) = self.as_ustar_mut() { + ustar.set_device_major(0); + ustar.set_device_minor(0); + } + if let Some(gnu) = self.as_gnu_mut() { + gnu.set_device_major(0); + gnu.set_device_minor(0); + } + } + + #[cfg(any(unix, target_os = "redox"))] + fn fill_platform_from(&mut self, meta: &fs::Metadata, mode: HeaderMode) { + match mode { + HeaderMode::Complete => { + self.set_mtime(meta.mtime() as u64); + self.set_uid(meta.uid() as u32); + self.set_gid(meta.gid() as u32); + self.set_mode(meta.mode() as u32); + }, + HeaderMode::Deterministic => { + self.set_mtime(0); + self.set_uid(0); + self.set_gid(0); + + // Use a default umask value, but propagate the (user) execute bit. + let fs_mode = + if meta.is_dir() || (0o100 & meta.mode() == 0o100) { + 0o755 + } else { + 0o644 + }; + self.set_mode(fs_mode); + }, + HeaderMode::__Nonexhaustive => panic!(), + } + + // Note that if we are a GNU header we *could* set atime/ctime, except + // the `tar` utility doesn't do that by default and it causes problems + // with 7-zip [1]. + // + // It's always possible to fill them out manually, so we just don't fill + // it out automatically here. + // + // [1]: https://github.com/alexcrichton/tar-rs/issues/70 + + // TODO: need to bind more file types + self.set_entry_type(entry_type(meta.mode())); + + #[cfg(not(target_os = "redox"))] + fn entry_type(mode: u32) -> EntryType { + use libc; + match mode as libc::mode_t & libc::S_IFMT { + libc::S_IFREG => EntryType::file(), + libc::S_IFLNK => EntryType::symlink(), + libc::S_IFCHR => EntryType::character_special(), + libc::S_IFBLK => EntryType::block_special(), + libc::S_IFDIR => EntryType::dir(), + libc::S_IFIFO => EntryType::fifo(), + _ => EntryType::new(b' '), + } + } + + #[cfg(target_os = "redox")] + fn entry_type(mode: u32) -> EntryType { + use syscall; + match mode as u16 & syscall::MODE_TYPE { + syscall::MODE_FILE => EntryType::file(), + syscall::MODE_SYMLINK => EntryType::symlink(), + syscall::MODE_DIR => EntryType::dir(), + _ => EntryType::new(b' '), + } + } + } + + #[cfg(windows)] + fn fill_platform_from(&mut self, meta: &fs::Metadata, mode: HeaderMode) { + // There's no concept of a file mode on windows, so do a best approximation here. + match mode { + HeaderMode::Complete => { + self.set_uid(0); + self.set_gid(0); + // The dates listed in tarballs are always seconds relative to + // January 1, 1970. On Windows, however, the timestamps are returned as + // dates relative to January 1, 1601 (in 100ns intervals), so we need to + // add in some offset for those dates. + let mtime = (meta.last_write_time() / (1_000_000_000 / 100)) - 11644473600; + self.set_mtime(mtime); + let fs_mode = { + const FILE_ATTRIBUTE_READONLY: u32 = 0x00000001; + let readonly = meta.file_attributes() & FILE_ATTRIBUTE_READONLY; + match (meta.is_dir(), readonly != 0) { + (true, false) => 0o755, + (true, true) => 0o555, + (false, false) => 0o644, + (false, true) => 0o444, + } + }; + self.set_mode(fs_mode); + }, + HeaderMode::Deterministic => { + self.set_uid(0); + self.set_gid(0); + self.set_mtime(0); + let fs_mode = + if meta.is_dir() { + 0o755 + } else { + 0o644 + }; + self.set_mode(fs_mode); + }, + HeaderMode::__Nonexhaustive => panic!(), + } + + let ft = meta.file_type(); + self.set_entry_type(if ft.is_dir() { + EntryType::dir() + } else if ft.is_file() { + EntryType::file() + } else if ft.is_symlink() { + EntryType::symlink() + } else { + EntryType::new(b' ') + }); + } + + fn debug_fields(&self, b: &mut fmt::DebugStruct) { + if let Ok(entry_size) = self.entry_size() { + b.field("entry_size", &entry_size); + } + if let Ok(size) = self.size() { + b.field("size", &size); + } + if let Ok(path) = self.path() { + b.field("path", &path); + } + if let Ok(link_name) = self.link_name() { + b.field("link_name", &link_name); + } + if let Ok(mode) = self.mode() { + b.field("mode", &DebugAsOctal(mode)); + } + if let Ok(uid) = self.uid() { + b.field("uid", &uid); + } + if let Ok(gid) = self.gid() { + b.field("gid", &gid); + } + if let Ok(mtime) = self.mtime() { + b.field("mtime", &mtime); + } + if let Ok(username) = self.username() { + b.field("username", &username); + } + if let Ok(groupname) = self.groupname() { + b.field("groupname", &groupname); + } + if let Ok(device_major) = self.device_major() { + b.field("device_major", &device_major); + } + if let Ok(device_minor) = self.device_minor() { + b.field("device_minor", &device_minor); + } + if let Ok(cksum) = self.cksum() { + b.field("cksum", &cksum); + b.field("cksum_valid", &(cksum == self.calculate_cksum())); + } + } +} + +struct DebugAsOctal<T>(T); + +impl<T: fmt::Octal> fmt::Debug for DebugAsOctal<T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Octal::fmt(&self.0, f) + } +} + +unsafe fn cast<T, U>(a: &T) -> &U { + assert_eq!(mem::size_of_val(a), mem::size_of::<U>()); + assert_eq!(mem::align_of_val(a), mem::align_of::<U>()); + &*(a as *const T as *const U) +} + +unsafe fn cast_mut<T, U>(a: &mut T) -> &mut U { + assert_eq!(mem::size_of_val(a), mem::size_of::<U>()); + assert_eq!(mem::align_of_val(a), mem::align_of::<U>()); + &mut *(a as *mut T as *mut U) +} + +impl Clone for Header { + fn clone(&self) -> Header { + Header { bytes: self.bytes } + } +} + +impl fmt::Debug for Header { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if let Some(me) = self.as_ustar() { + me.fmt(f) + } else if let Some(me) = self.as_gnu() { + me.fmt(f) + } else { + self.as_old().fmt(f) + } + } +} + +impl OldHeader { + /// Views this as a normal `Header` + pub fn as_header(&self) -> &Header { + unsafe { cast(self) } + } + + /// Views this as a normal `Header` + pub fn as_header_mut(&mut self) -> &mut Header { + unsafe { cast_mut(self) } + } +} + +impl fmt::Debug for OldHeader { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_struct("OldHeader"); + self.as_header().debug_fields(&mut f); + f.finish() + } +} + +impl UstarHeader { + /// See `Header::path_bytes` + pub fn path_bytes(&self) -> Cow<[u8]> { + if self.prefix[0] == 0 && !self.name.contains(&b'\\') { + Cow::Borrowed(truncate(&self.name)) + } else { + let mut bytes = Vec::new(); + let prefix = truncate(&self.prefix); + if prefix.len() > 0 { + bytes.extend_from_slice(prefix); + bytes.push(b'/'); + } + bytes.extend_from_slice(truncate(&self.name)); + Cow::Owned(bytes) + } + } + + /// Gets the path in a "lossy" way, used for error reporting ONLY. + fn path_lossy(&self) -> String { + String::from_utf8_lossy(&self.path_bytes()).to_string() + } + + /// See `Header::set_path` + pub fn set_path<P: AsRef<Path>>(&mut self, p: P) -> io::Result<()> { + self._set_path(p.as_ref()) + } + + fn _set_path(&mut self, path: &Path) -> io::Result<()> { + // This can probably be optimized quite a bit more, but for now just do + // something that's relatively easy and readable. + // + // First up, if the path fits within `self.name` then we just shove it + // in there. If not then we try to split it between some existing path + // components where it can fit in name/prefix. To do that we peel off + // enough until the path fits in `prefix`, then we try to put both + // halves into their destination. + let bytes = try!(path2bytes(path)); + let (maxnamelen, maxprefixlen) = (self.name.len(), self.prefix.len()); + if bytes.len() <= maxnamelen { + try!(copy_path_into(&mut self.name, path, false) + .map_err(|err| io::Error::new( + err.kind(), + format!( "{} when setting path for {}", err, self.path_lossy()), + ))); + } else { + let mut prefix = path; + let mut prefixlen; + loop { + match prefix.parent() { + Some(parent) => prefix = parent, + None => return Err(other(&format!( + "path cannot be split to be inserted into archive: {}", path.display() + ))), + } + prefixlen = try!(path2bytes(prefix)).len(); + if prefixlen <= maxprefixlen { + break + } + } + try!(copy_path_into(&mut self.prefix, prefix, false) + .map_err(|err| io::Error::new( + err.kind(), + format!( "{} when setting path for {}", err, self.path_lossy()), + ))); + let path = try!(bytes2path(Cow::Borrowed(&bytes[prefixlen + 1..]))); + try!(copy_path_into(&mut self.name, &path, false) + .map_err(|err| io::Error::new( + err.kind(), + format!( "{} when setting path for {}", err, self.path_lossy()), + ))); + } + Ok(()) + } + + /// See `Header::username_bytes` + pub fn username_bytes(&self) -> &[u8] { + truncate(&self.uname) + } + + /// See `Header::set_username` + pub fn set_username(&mut self, name: &str) -> io::Result<()> { + copy_into(&mut self.uname, name.as_bytes()).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when setting username for {}", err, self.path_lossy()), + )) + } + + /// See `Header::groupname_bytes` + pub fn groupname_bytes(&self) -> &[u8] { + truncate(&self.gname) + } + + /// See `Header::set_groupname` + pub fn set_groupname(&mut self, name: &str) -> io::Result<()> { + copy_into(&mut self.gname, name.as_bytes()).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when setting groupname for {}", err, self.path_lossy()), + )) + } + + /// See `Header::device_major` + pub fn device_major(&self) -> io::Result<u32> { + octal_from(&self.dev_major).map(|u| u as u32).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting device_major for {}", err, self.path_lossy()), + )) + } + + /// See `Header::set_device_major` + pub fn set_device_major(&mut self, major: u32) { + octal_into(&mut self.dev_major, major); + } + + /// See `Header::device_minor` + pub fn device_minor(&self) -> io::Result<u32> { + octal_from(&self.dev_minor).map(|u| u as u32).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting device_minor for {}", err, self.path_lossy()), + )) + } + + /// See `Header::set_device_minor` + pub fn set_device_minor(&mut self, minor: u32) { + octal_into(&mut self.dev_minor, minor); + } + + /// Views this as a normal `Header` + pub fn as_header(&self) -> &Header { + unsafe { cast(self) } + } + + /// Views this as a normal `Header` + pub fn as_header_mut(&mut self) -> &mut Header { + unsafe { cast_mut(self) } + } +} + +impl fmt::Debug for UstarHeader { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_struct("UstarHeader"); + self.as_header().debug_fields(&mut f); + f.finish() + } +} + +impl GnuHeader { + /// See `Header::username_bytes` + pub fn username_bytes(&self) -> &[u8] { + truncate(&self.uname) + } + + /// Gets the fullname (group:user) in a "lossy" way, used for error reporting ONLY. + fn fullname_lossy(&self) -> String { + format!( + "{}:{}", + String::from_utf8_lossy(&self.groupname_bytes()), + String::from_utf8_lossy(&self.username_bytes()), + ) + } + + /// See `Header::set_username` + pub fn set_username(&mut self, name: &str) -> io::Result<()> { + copy_into(&mut self.uname, name.as_bytes()).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when setting username for {}", err, self.fullname_lossy()), + )) + } + + /// See `Header::groupname_bytes` + pub fn groupname_bytes(&self) -> &[u8] { + truncate(&self.gname) + } + + /// See `Header::set_groupname` + pub fn set_groupname(&mut self, name: &str) -> io::Result<()> { + copy_into(&mut self.gname, name.as_bytes()).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when setting groupname for {}", err, self.fullname_lossy()), + )) + } + + /// See `Header::device_major` + pub fn device_major(&self) -> io::Result<u32> { + octal_from(&self.dev_major).map(|u| u as u32).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting device_major for {}", err, self.fullname_lossy()), + )) + } + + /// See `Header::set_device_major` + pub fn set_device_major(&mut self, major: u32) { + octal_into(&mut self.dev_major, major); + } + + /// See `Header::device_minor` + pub fn device_minor(&self) -> io::Result<u32> { + octal_from(&self.dev_minor).map(|u| u as u32).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting device_minor for {}", err, self.fullname_lossy()), + )) + } + + /// See `Header::set_device_minor` + pub fn set_device_minor(&mut self, minor: u32) { + octal_into(&mut self.dev_minor, minor); + } + + /// Returns the last modification time in Unix time format + pub fn atime(&self) -> io::Result<u64> { + octal_from(&self.atime).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting atime for {}", err, self.fullname_lossy()), + )) + } + + /// Encodes the `atime` provided into this header. + /// + /// Note that this time is typically a number of seconds passed since + /// January 1, 1970. + pub fn set_atime(&mut self, atime: u64) { + octal_into(&mut self.atime, atime); + } + + /// Returns the last modification time in Unix time format + pub fn ctime(&self) -> io::Result<u64> { + octal_from(&self.ctime).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting ctime for {}", err, self.fullname_lossy()), + )) + } + + /// Encodes the `ctime` provided into this header. + /// + /// Note that this time is typically a number of seconds passed since + /// January 1, 1970. + pub fn set_ctime(&mut self, ctime: u64) { + octal_into(&mut self.ctime, ctime); + } + + /// Returns the "real size" of the file this header represents. + /// + /// This is applicable for sparse files where the returned size here is the + /// size of the entire file after the sparse regions have been filled in. + pub fn real_size(&self) -> io::Result<u64> { + octal_from(&self.realsize).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting real_size for {}", err, self.fullname_lossy()), + )) + } + + /// Indicates whether this header will be followed by additional + /// sparse-header records. + /// + /// Note that this is handled internally by this library, and is likely only + /// interesting if a `raw` iterator is being used. + pub fn is_extended(&self) -> bool { + self.isextended[0] == 1 + } + + /// Views this as a normal `Header` + pub fn as_header(&self) -> &Header { + unsafe { cast(self) } + } + + /// Views this as a normal `Header` + pub fn as_header_mut(&mut self) -> &mut Header { + unsafe { cast_mut(self) } + } +} + +impl fmt::Debug for GnuHeader { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_struct("GnuHeader"); + self.as_header().debug_fields(&mut f); + if let Ok(atime) = self.atime() { + f.field("atime", &atime); + } + if let Ok(ctime) = self.ctime() { + f.field("ctime", &ctime); + } + f.field("is_extended", &self.is_extended()) + .field("sparse", &DebugSparseHeaders(&self.sparse)) + .finish() + } +} + +struct DebugSparseHeaders<'a>(&'a [GnuSparseHeader]); + +impl<'a> fmt::Debug for DebugSparseHeaders<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_list(); + for header in self.0 { + if !header.is_empty() { + f.entry(header); + } + } + f.finish() + } +} + +impl GnuSparseHeader { + /// Returns true if block is empty + pub fn is_empty(&self) -> bool { + self.offset[0] == 0 || self.numbytes[0] == 0 + } + + /// Offset of the block from the start of the file + /// + /// Returns `Err` for a malformed `offset` field. + pub fn offset(&self) -> io::Result<u64> { + octal_from(&self.offset).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting offset from sparce header", err), + )) + } + + /// Length of the block + /// + /// Returns `Err` for a malformed `numbytes` field. + pub fn length(&self) -> io::Result<u64> { + octal_from(&self.numbytes).map_err(|err| io::Error::new( + err.kind(), + format!( "{} when getting length from sparse header", err), + )) + } +} + +impl fmt::Debug for GnuSparseHeader { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let mut f = f.debug_struct("GnuSparseHeader"); + if let Ok(offset) = self.offset() { + f.field("offset", &offset); + } + if let Ok(length) = self.length() { + f.field("length", &length); + } + f.finish() + } +} + +impl GnuExtSparseHeader { + /// Crates a new zero'd out sparse header entry. + pub fn new() -> GnuExtSparseHeader { + unsafe { mem::zeroed() } + } + + /// Returns a view into this header as a byte array. + pub fn as_bytes(&self) -> &[u8; 512] { + debug_assert_eq!(mem::size_of_val(self), 512); + unsafe { mem::transmute(self) } + } + + /// Returns a view into this header as a byte array. + pub fn as_mut_bytes(&mut self) -> &mut [u8; 512] { + debug_assert_eq!(mem::size_of_val(self), 512); + unsafe { mem::transmute(self) } + } + + /// Returns a slice of the underlying sparse headers. + /// + /// Some headers may represent empty chunks of both the offset and numbytes + /// fields are 0. + pub fn sparse(&self) -> &[GnuSparseHeader; 21] { + &self.sparse + } + + /// Indicates if another sparse header should be following this one. + pub fn is_extended(&self) -> bool { + self.isextended[0] == 1 + } +} + +impl Default for GnuExtSparseHeader { + fn default() -> Self { + Self::new() + } +} + +fn octal_from(slice: &[u8]) -> io::Result<u64> { + if slice[0] & 0x80 != 0 { + // number is expressed in binary as a GNU numeric extension - + // see https://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5&manpath=FreeBSD+8-current + // under section "Numeric Extensions" + let mut total = (slice[0] ^ 0x80) as u64; + let mut index = 1; + while index < slice.len() { + total <<= 8; + total |= slice[index] as u64; + index += 1; + } + Ok(total) + } else { + let trun = truncate(slice); + let num = match str::from_utf8(trun) { + Ok(n) => n, + Err(_) => return Err(other( + &format!("numeric field did not have utf-8 text: {}", String::from_utf8_lossy(trun)) + )), + }; + match u64::from_str_radix(num.trim(), 8) { + Ok(n) => Ok(n), + Err(_) => Err(other(&format!("numeric field was not a number: {}", num))), + } + } +} + +fn octal_into<T: fmt::Octal>(dst: &mut [u8], val: T) { + let o = format!("{:o}", val); + let value = o.bytes().rev().chain(repeat(b'0')); + for (slot, value) in dst.iter_mut().rev().skip(1).zip(value) { + *slot = value; + } +} + +fn truncate(slice: &[u8]) -> &[u8] { + match slice.iter().position(|i| *i == 0) { + Some(i) => &slice[..i], + None => slice, + } +} + +/// Copies `bytes` into the `slot` provided, returning an error if the `bytes` +/// array is too long or if it contains any nul bytes. +fn copy_into(slot: &mut [u8], bytes: &[u8]) -> io::Result<()> { + if bytes.len() > slot.len() { + Err(other("provided value is too long")) + } else if bytes.iter().any(|b| *b == 0) { + Err(other("provided value contains a nul byte")) + } else { + for (slot, val) in slot.iter_mut().zip(bytes.iter().chain(Some(&0))) { + *slot = *val; + } + Ok(()) + } +} + +/// Copies `path` into the `slot` provided +/// +/// Returns an error if: +/// +/// * the path is too long to fit +/// * a nul byte was found +/// * an invalid path component is encountered (e.g. a root path or parent dir) +/// * the path itself is empty +fn copy_path_into(mut slot: &mut [u8], + path: &Path, + is_link_name: bool) -> io::Result<()> { + let mut emitted = false; + let mut needs_slash = false; + for component in path.components() { + let bytes = try!(path2bytes(Path::new(component.as_os_str()))); + match (component, is_link_name) { + (Component::Prefix(..), false) | + (Component::RootDir, false) => { + return Err(other("paths in archives must be relative")) + } + (Component::ParentDir, false) => { + return Err(other("paths in archives must not have `..`")) + } + // Allow "./" as the path + (Component::CurDir, false) if path.components().count() == 1 => {}, + (Component::CurDir, false) => continue, + (Component::Normal(_), _) | + (_, true) => {} + }; + if needs_slash { + try!(copy(&mut slot, b"/")); + } + if bytes.contains(&b'/') { + if let Component::Normal(..) = component { + return Err(other("path component in archive cannot contain `/`")) + } + } + try!(copy(&mut slot, &*bytes)); + if &*bytes != b"/" { + needs_slash = true; + } + emitted = true; + } + if !emitted { + return Err(other("paths in archives must have at least one component")) + } + if ends_with_slash(path) { + try!(copy(&mut slot, &[b'/'])); + } + return Ok(()); + + fn copy(slot: &mut &mut [u8], bytes: &[u8]) -> io::Result<()> { + try!(copy_into(*slot, bytes)); + let tmp = mem::replace(slot, &mut []); + *slot = &mut tmp[bytes.len()..]; + Ok(()) + } +} + +#[cfg(windows)] +fn ends_with_slash(p: &Path) -> bool { + let last = p.as_os_str().encode_wide().last(); + last == Some(b'/' as u16) || last == Some(b'\\' as u16) +} + +#[cfg(any(unix, target_os = "redox"))] +fn ends_with_slash(p: &Path) -> bool { + p.as_os_str().as_bytes().ends_with(&[b'/']) +} + +#[cfg(windows)] +pub fn path2bytes(p: &Path) -> io::Result<Cow<[u8]>> { + p.as_os_str().to_str().map(|s| s.as_bytes()).ok_or_else(|| { + other(&format!("path {} was not valid unicode", p.display())) + }).map(|bytes| { + if bytes.contains(&b'\\') { + // Normalize to Unix-style path separators + let mut bytes = bytes.to_owned(); + for b in &mut bytes { + if *b == b'\\' { + *b = b'/'; + } + } + Cow::Owned(bytes) + } else { + Cow::Borrowed(bytes) + } + }) +} + +#[cfg(any(unix, target_os = "redox"))] +/// On unix this will never fail +pub fn path2bytes(p: &Path) -> io::Result<Cow<[u8]>> { + Ok(p.as_os_str().as_bytes()).map(Cow::Borrowed) +} + +#[cfg(windows)] +/// On windows we cannot accept non-unicode bytes because it +/// is impossible to convert it to UTF-16. +pub fn bytes2path(bytes: Cow<[u8]>) -> io::Result<Cow<Path>> { + return match bytes { + Cow::Borrowed(bytes) => { + let s = try!(str::from_utf8(bytes).map_err(|_| { + not_unicode(bytes) + })); + Ok(Cow::Borrowed(Path::new(s))) + } + Cow::Owned(bytes) => { + let s = try!(String::from_utf8(bytes).map_err(|uerr| { + not_unicode(&uerr.into_bytes()) + })); + Ok(Cow::Owned(PathBuf::from(s))) + } + }; + + fn not_unicode(v: &[u8]) -> io::Error { + other(&format!( + "only unicode paths are supported on windows: {}", + String::from_utf8_lossy(v) + )) + } +} + +#[cfg(any(unix, target_os = "redox"))] +/// On unix this operation can never fail. +pub fn bytes2path(bytes: Cow<[u8]>) -> io::Result<Cow<Path>> { + use std::ffi::{OsStr, OsString}; + + Ok(match bytes { + Cow::Borrowed(bytes) => Cow::Borrowed({ + Path::new(OsStr::from_bytes(bytes)) + }), + Cow::Owned(bytes) => Cow::Owned({ + PathBuf::from(OsString::from_vec(bytes)) + }) + }) +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/src/lib.rs cargo-0.26.0/vendor/tar-0.4.15/src/lib.rs --- cargo-0.25.0/vendor/tar-0.4.15/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,71 @@ +//! A library for reading and writing TAR archives +//! +//! This library provides utilities necessary to manage [TAR archives][1] +//! abstracted over a reader or writer. Great strides are taken to ensure that +//! an archive is never required to be fully resident in memory, and all objects +//! provide largely a streaming interface to read bytes from. +//! +//! [1]: http://en.wikipedia.org/wiki/Tar_%28computing%29 + +// More docs about the detailed tar format can also be found here: +// http://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5&manpath=FreeBSD+8-current + +// NB: some of the coding patterns and idioms here may seem a little strange. +// This is currently attempting to expose a super generic interface while +// also not forcing clients to codegen the entire crate each time they use +// it. To that end lots of work is done to ensure that concrete +// implementations are all found in this crate and the generic functions are +// all just super thin wrappers (e.g. easy to codegen). + +#![doc(html_root_url = "https://docs.rs/tar/0.4")] +#![deny(missing_docs)] +#![cfg_attr(test, deny(warnings))] + +#[cfg(unix)] +extern crate libc; +extern crate filetime; +#[cfg(all(unix, feature = "xattr"))] +extern crate xattr; +#[cfg(target_os = "redox")] +extern crate syscall; + +use std::io::{Error, ErrorKind}; +use std::ops::{Deref, DerefMut}; + +pub use header::{Header, HeaderMode, OldHeader, UstarHeader, GnuHeader, GnuSparseHeader}; +pub use header::{GnuExtSparseHeader}; +pub use entry_type::EntryType; +pub use entry::Entry; +pub use archive::{Archive, Entries}; +pub use builder::Builder; +pub use pax::{PaxExtensions, PaxExtension}; + +mod archive; +mod builder; +mod entry; +mod entry_type; +mod error; +mod header; +mod pax; + +// FIXME(rust-lang/rust#26403): +// Right now there's a bug when a DST struct's last field has more +// alignment than the rest of a structure, causing invalid pointers to be +// created when it's casted around at runtime. To work around this we force +// our DST struct to instead have a forcibly higher alignment via a +// synthesized u64 (hopefully the largest alignment we'll run into in +// practice), and this should hopefully ensure that the pointers all work +// out. +struct AlignHigher<R: ?Sized>(u64, R); + +impl<R: ?Sized> Deref for AlignHigher<R> { + type Target = R; + fn deref(&self) -> &R { &self.1 } +} +impl<R: ?Sized> DerefMut for AlignHigher<R> { + fn deref_mut(&mut self) -> &mut R { &mut self.1 } +} + +fn other(msg: &str) -> Error { + Error::new(ErrorKind::Other, msg) +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/src/pax.rs cargo-0.26.0/vendor/tar-0.4.15/src/pax.rs --- cargo-0.25.0/vendor/tar-0.4.15/src/pax.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/src/pax.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,83 @@ +use std::io; +use std::str; +use std::slice; + +use other; + +/// An iterator over the pax extensions in an archive entry. +/// +/// This iterator yields structures which can themselves be parsed into +/// key/value pairs. +pub struct PaxExtensions<'entry> { + data: slice::Split<'entry, u8, fn(&u8) -> bool>, +} + +/// A key/value pair corresponding to a pax extension. +pub struct PaxExtension<'entry> { + key: &'entry [u8], + value: &'entry [u8], +} + +pub fn pax_extensions(a: &[u8]) -> PaxExtensions { + fn is_newline(a: &u8) -> bool { *a == b'\n' } + PaxExtensions { data: a.split(is_newline) } +} + +impl<'entry> Iterator for PaxExtensions<'entry> { + type Item = io::Result<PaxExtension<'entry>>; + + fn next(&mut self) -> Option<io::Result<PaxExtension<'entry>>> { + let line = match self.data.next() { + Some(line) if line.is_empty() => return None, + Some(line) => line, + None => return None, + }; + + Some(line.iter().position(|b| *b == b' ').and_then(|i| { + str::from_utf8(&line[..i]).ok().and_then(|len| { + len.parse::<usize>().ok().map(|j| (i + 1, j)) + }) + }).and_then(|(kvstart, reported_len)| { + if line.len() + 1 == reported_len { + line[kvstart..].iter().position(|b| *b == b'=').map(|equals| { + (kvstart, equals) + }) + } else { + None + } + }).map(|(kvstart, equals)| { + PaxExtension { + key: &line[kvstart..kvstart + equals], + value: &line[kvstart + equals + 1..], + } + }).ok_or_else(|| { + other("malformed pax extension") + })) + } +} + +impl<'entry> PaxExtension<'entry> { + /// Returns the key for this key/value pair parsed as a string. + /// + /// May fail if the key isn't actually utf-8. + pub fn key(&self) -> Result<&'entry str, str::Utf8Error> { + str::from_utf8(self.key) + } + + /// Returns the underlying raw bytes for the key of this key/value pair. + pub fn key_bytes(&self) -> &'entry [u8] { + self.key + } + + /// Returns the value for this key/value pair parsed as a string. + /// + /// May fail if the value isn't actually utf-8. + pub fn value(&self) -> Result<&'entry str, str::Utf8Error> { + str::from_utf8(self.value) + } + + /// Returns the underlying raw bytes for this value of this key/value pair. + pub fn value_bytes(&self) -> &'entry [u8] { + self.value + } +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/tests/all.rs cargo-0.26.0/vendor/tar-0.4.15/tests/all.rs --- cargo-0.25.0/vendor/tar-0.4.15/tests/all.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/tests/all.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,805 @@ +extern crate filetime; +extern crate tar; +extern crate tempdir; +#[cfg(all(unix, feature = "xattr"))] +extern crate xattr; + +use std::fs::{self, File}; +use std::io::prelude::*; +use std::io::{self, Cursor}; +use std::iter::repeat; +use std::path::{Path, PathBuf}; + +use filetime::FileTime; +use self::tempdir::TempDir; +use tar::{Archive, Builder, Header, EntryType}; + +macro_rules! t { + ($e:expr) => (match $e { + Ok(v) => v, + Err(e) => panic!("{} returned {}", stringify!($e), e), + }) +} + +macro_rules! tar { + ($e:expr) => (&include_bytes!(concat!("archives/", $e))[..]) +} + +mod header; + +#[test] +fn simple() { + let mut ar = Archive::new(Cursor::new(tar!("simple.tar"))); + for entry in t!(ar.entries()) { + t!(entry); + } + let mut ar = Archive::new(Cursor::new(tar!("simple.tar"))); + for entry in t!(ar.entries()) { + t!(entry); + } +} + +#[test] +fn header_impls() { + let mut ar = Archive::new(Cursor::new(tar!("simple.tar"))); + let hn = Header::new_old(); + let hnb = hn.as_bytes(); + for file in t!(ar.entries()) { + let file = t!(file); + let h1 = file.header(); + let h1b = h1.as_bytes(); + let h2 = h1.clone(); + let h2b = h2.as_bytes(); + assert!(h1b[..] == h2b[..] && h2b[..] != hnb[..]) + } +} + +#[test] +fn reading_files() { + let rdr = Cursor::new(tar!("reading_files.tar")); + let mut ar = Archive::new(rdr); + let mut entries = t!(ar.entries()); + + let mut a = t!(entries.next().unwrap()); + assert_eq!(&*a.header().path_bytes(), b"a"); + let mut s = String::new(); + t!(a.read_to_string(&mut s)); + assert_eq!(s, "a\na\na\na\na\na\na\na\na\na\na\n"); + + let mut b = t!(entries.next().unwrap()); + assert_eq!(&*b.header().path_bytes(), b"b"); + s.truncate(0); + t!(b.read_to_string(&mut s)); + assert_eq!(s, "b\nb\nb\nb\nb\nb\nb\nb\nb\nb\nb\n"); + + assert!(entries.next().is_none()); +} + +#[test] +fn writing_files() { + let mut ar = Builder::new(Vec::new()); + let td = t!(TempDir::new("tar-rs")); + + let path = td.path().join("test"); + t!(t!(File::create(&path)).write_all(b"test")); + + t!(ar.append_file("test2", &mut t!(File::open(&path)))); + + let data = t!(ar.into_inner()); + let mut ar = Archive::new(Cursor::new(data)); + let mut entries = t!(ar.entries()); + let mut f = t!(entries.next().unwrap()); + + assert_eq!(&*f.header().path_bytes(), b"test2"); + assert_eq!(f.header().size().unwrap(), 4); + let mut s = String::new(); + t!(f.read_to_string(&mut s)); + assert_eq!(s, "test"); + + assert!(entries.next().is_none()); +} + +#[test] +fn large_filename() { + let mut ar = Builder::new(Vec::new()); + let td = t!(TempDir::new("tar-rs")); + + let path = td.path().join("test"); + t!(t!(File::create(&path)).write_all(b"test")); + + let filename = repeat("abcd/").take(50).collect::<String>(); + let mut header = Header::new_ustar(); + header.set_path(&filename).unwrap(); + header.set_metadata(&t!(fs::metadata(&path))); + header.set_cksum(); + t!(ar.append(&header, &b"test"[..])); + let too_long = repeat("abcd").take(200).collect::<String>(); + t!(ar.append_file(&too_long, &mut t!(File::open(&path)))); + t!(ar.append_data(&mut header, &too_long, &b"test"[..])); + + let rd = Cursor::new(t!(ar.into_inner())); + let mut ar = Archive::new(rd); + let mut entries = t!(ar.entries()); + + // The short entry added with `append` + let mut f = entries.next().unwrap().unwrap(); + assert_eq!(&*f.header().path_bytes(), filename.as_bytes()); + assert_eq!(f.header().size().unwrap(), 4); + let mut s = String::new(); + t!(f.read_to_string(&mut s)); + assert_eq!(s, "test"); + + // The long entry added with `append_file` + let mut f = entries.next().unwrap().unwrap(); + assert_eq!(&*f.path_bytes(), too_long.as_bytes()); + assert_eq!(f.header().size().unwrap(), 4); + let mut s = String::new(); + t!(f.read_to_string(&mut s)); + assert_eq!(s, "test"); + + // The long entry added with `append_data` + let mut f = entries.next().unwrap().unwrap(); + assert!(f.header().path_bytes().len() < too_long.len()); + assert_eq!(&*f.path_bytes(), too_long.as_bytes()); + assert_eq!(f.header().size().unwrap(), 4); + let mut s = String::new(); + t!(f.read_to_string(&mut s)); + assert_eq!(s, "test"); + + assert!(entries.next().is_none()); +} + +#[test] +fn reading_entries() { + let rdr = Cursor::new(tar!("reading_files.tar")); + let mut ar = Archive::new(rdr); + let mut entries = t!(ar.entries()); + let mut a = t!(entries.next().unwrap()); + assert_eq!(&*a.header().path_bytes(), b"a"); + let mut s = String::new(); + t!(a.read_to_string(&mut s)); + assert_eq!(s, "a\na\na\na\na\na\na\na\na\na\na\n"); + s.truncate(0); + t!(a.read_to_string(&mut s)); + assert_eq!(s, ""); + let mut b = t!(entries.next().unwrap()); + + assert_eq!(&*b.header().path_bytes(), b"b"); + s.truncate(0); + t!(b.read_to_string(&mut s)); + assert_eq!(s, "b\nb\nb\nb\nb\nb\nb\nb\nb\nb\nb\n"); + assert!(entries.next().is_none()); +} + +fn check_dirtree(td: &TempDir) { + let dir_a = td.path().join("a"); + let dir_b = td.path().join("a/b"); + let file_c = td.path().join("a/c"); + assert!(fs::metadata(&dir_a).map(|m| m.is_dir()).unwrap_or(false)); + assert!(fs::metadata(&dir_b).map(|m| m.is_dir()).unwrap_or(false)); + assert!(fs::metadata(&file_c).map(|m| m.is_file()).unwrap_or(false)); +} + +#[test] +fn extracting_directories() { + let td = t!(TempDir::new("tar-rs")); + let rdr = Cursor::new(tar!("directory.tar")); + let mut ar = Archive::new(rdr); + t!(ar.unpack(td.path())); + check_dirtree(&td); +} + +#[test] +#[cfg(all(unix, feature = "xattr"))] +fn xattrs() { + // If /tmp is a tmpfs, xattr will fail + // The xattr crate's unit tests also use /var/tmp for this reason + let td = t!(TempDir::new_in("/var/tmp", "tar-rs")); + let rdr = Cursor::new(tar!("xattrs.tar")); + let mut ar = Archive::new(rdr); + ar.set_unpack_xattrs(true); + t!(ar.unpack(td.path())); + + let val = xattr::get(td.path().join("a/b"), "user.pax.flags").unwrap(); + assert_eq!(val.unwrap(), "epm".as_bytes()); +} + +#[test] +#[cfg(all(unix, feature = "xattr"))] +fn no_xattrs() { + // If /tmp is a tmpfs, xattr will fail + // The xattr crate's unit tests also use /var/tmp for this reason + let td = t!(TempDir::new_in("/var/tmp", "tar-rs")); + let rdr = Cursor::new(tar!("xattrs.tar")); + let mut ar = Archive::new(rdr); + ar.set_unpack_xattrs(false); + t!(ar.unpack(td.path())); + + assert_eq!(xattr::get(td.path().join("a/b"), "user.pax.flags").unwrap(), None); +} + +#[test] +fn writing_and_extracting_directories() { + let td = t!(TempDir::new("tar-rs")); + + let mut ar = Builder::new(Vec::new()); + let tmppath = td.path().join("tmpfile"); + t!(t!(File::create(&tmppath)).write_all(b"c")); + t!(ar.append_dir("a", ".")); + t!(ar.append_dir("a/b", ".")); + t!(ar.append_file("a/c", &mut t!(File::open(&tmppath)))); + t!(ar.finish()); + + let rdr = Cursor::new(t!(ar.into_inner())); + let mut ar = Archive::new(rdr); + t!(ar.unpack(td.path())); + check_dirtree(&td); +} + +#[test] +fn writing_directories_recursively() { + let td = t!(TempDir::new("tar-rs")); + + let base_dir = td.path().join("base"); + t!(fs::create_dir(&base_dir)); + t!(t!(File::create(base_dir.join("file1"))).write_all(b"file1")); + let sub_dir = base_dir.join("sub"); + t!(fs::create_dir(&sub_dir)); + t!(t!(File::create(sub_dir.join("file2"))).write_all(b"file2")); + + let mut ar = Builder::new(Vec::new()); + t!(ar.append_dir_all("foobar", base_dir)); + let data = t!(ar.into_inner()); + + let mut ar = Archive::new(Cursor::new(data)); + t!(ar.unpack(td.path())); + let base_dir = td.path().join("foobar"); + assert!(fs::metadata(&base_dir).map(|m| m.is_dir()).unwrap_or(false)); + let file1_path = base_dir.join("file1"); + assert!(fs::metadata(&file1_path).map(|m| m.is_file()).unwrap_or(false)); + let sub_dir = base_dir.join("sub"); + assert!(fs::metadata(&sub_dir).map(|m| m.is_dir()).unwrap_or(false)); + let file2_path = sub_dir.join("file2"); + assert!(fs::metadata(&file2_path).map(|m| m.is_file()).unwrap_or(false)); +} + +#[test] +fn append_dir_all_blank_dest() { + let td = t!(TempDir::new("tar-rs")); + + let base_dir = td.path().join("base"); + t!(fs::create_dir(&base_dir)); + t!(t!(File::create(base_dir.join("file1"))).write_all(b"file1")); + let sub_dir = base_dir.join("sub"); + t!(fs::create_dir(&sub_dir)); + t!(t!(File::create(sub_dir.join("file2"))).write_all(b"file2")); + + let mut ar = Builder::new(Vec::new()); + t!(ar.append_dir_all("", base_dir)); + let data = t!(ar.into_inner()); + + let mut ar = Archive::new(Cursor::new(data)); + t!(ar.unpack(td.path())); + let base_dir = td.path(); + assert!(fs::metadata(&base_dir).map(|m| m.is_dir()).unwrap_or(false)); + let file1_path = base_dir.join("file1"); + assert!(fs::metadata(&file1_path).map(|m| m.is_file()).unwrap_or(false)); + let sub_dir = base_dir.join("sub"); + assert!(fs::metadata(&sub_dir).map(|m| m.is_dir()).unwrap_or(false)); + let file2_path = sub_dir.join("file2"); + assert!(fs::metadata(&file2_path).map(|m| m.is_file()).unwrap_or(false)); +} + +#[test] +fn append_dir_all_does_not_work_on_non_directory() { + let td = t!(TempDir::new("tar-rs")); + let path = td.path().join("test"); + t!(t!(File::create(&path)).write_all(b"test")); + + let mut ar = Builder::new(Vec::new()); + let result = ar.append_dir_all("test", path); + assert!(result.is_err()); +} + +#[test] +fn extracting_duplicate_dirs() { + let td = t!(TempDir::new("tar-rs")); + let rdr = Cursor::new(tar!("duplicate_dirs.tar")); + let mut ar = Archive::new(rdr); + t!(ar.unpack(td.path())); + + let some_dir = td.path().join("some_dir"); + assert!(fs::metadata(&some_dir).map(|m| m.is_dir()).unwrap_or(false)); +} + +#[test] +fn handling_incorrect_file_size() { + let td = t!(TempDir::new("tar-rs")); + + let mut ar = Builder::new(Vec::new()); + + let path = td.path().join("tmpfile"); + t!(File::create(&path)); + let mut file = t!(File::open(&path)); + let mut header = Header::new_old(); + t!(header.set_path("somepath")); + header.set_metadata(&t!(file.metadata())); + header.set_size(2048); // past the end of file null blocks + header.set_cksum(); + t!(ar.append(&header, &mut file)); + + // Extracting + let rdr = Cursor::new(t!(ar.into_inner())); + let mut ar = Archive::new(rdr); + assert!(ar.unpack(td.path()).is_err()); + + // Iterating + let rdr = Cursor::new(ar.into_inner().into_inner()); + let mut ar = Archive::new(rdr); + assert!(t!(ar.entries()).any(|fr| fr.is_err())); +} + +#[test] +fn extracting_malicious_tarball() { + let td = t!(TempDir::new("tar-rs")); + + let mut evil_tar = Vec::new(); + + { + let mut a = Builder::new(&mut evil_tar); + let mut append = |path: &str| { + let mut header = Header::new_gnu(); + assert!(header.set_path(path).is_err(), + "was ok: {:?}", path); + { + let h = header.as_gnu_mut().unwrap(); + for (a, b) in h.name.iter_mut().zip(path.as_bytes()) { + *a = *b; + } + } + header.set_size(1); + header.set_cksum(); + t!(a.append(&header, io::repeat(1).take(1))); + }; + append("/tmp/abs_evil.txt"); + append("//tmp/abs_evil2.txt"); + append("///tmp/abs_evil3.txt"); + append("/./tmp/abs_evil4.txt"); + append("//./tmp/abs_evil5.txt"); + append("///./tmp/abs_evil6.txt"); + append("/../tmp/rel_evil.txt"); + append("../rel_evil2.txt"); + append("./../rel_evil3.txt"); + append("some/../../rel_evil4.txt"); + append(""); + append("././//./.."); + append(".."); + append("/////////.."); + append("/////////"); + } + + let mut ar = Archive::new(&evil_tar[..]); + t!(ar.unpack(td.path())); + + assert!(fs::metadata("/tmp/abs_evil.txt").is_err()); + assert!(fs::metadata("/tmp/abs_evil.txt2").is_err()); + assert!(fs::metadata("/tmp/abs_evil.txt3").is_err()); + assert!(fs::metadata("/tmp/abs_evil.txt4").is_err()); + assert!(fs::metadata("/tmp/abs_evil.txt5").is_err()); + assert!(fs::metadata("/tmp/abs_evil.txt6").is_err()); + assert!(fs::metadata("/tmp/rel_evil.txt").is_err()); + assert!(fs::metadata("/tmp/rel_evil.txt").is_err()); + assert!(fs::metadata(td.path().join("../tmp/rel_evil.txt")).is_err()); + assert!(fs::metadata(td.path().join("../rel_evil2.txt")).is_err()); + assert!(fs::metadata(td.path().join("../rel_evil3.txt")).is_err()); + assert!(fs::metadata(td.path().join("../rel_evil4.txt")).is_err()); + + // The `some` subdirectory should not be created because the only + // filename that references this has '..'. + assert!(fs::metadata(td.path().join("some")).is_err()); + + // The `tmp` subdirectory should be created and within this + // subdirectory, there should be files named `abs_evil.txt` through + // `abs_evil6.txt`. + assert!(fs::metadata(td.path().join("tmp")).map(|m| m.is_dir()) + .unwrap_or(false)); + assert!(fs::metadata(td.path().join("tmp/abs_evil.txt")) + .map(|m| m.is_file()).unwrap_or(false)); + assert!(fs::metadata(td.path().join("tmp/abs_evil2.txt")) + .map(|m| m.is_file()).unwrap_or(false)); + assert!(fs::metadata(td.path().join("tmp/abs_evil3.txt")) + .map(|m| m.is_file()).unwrap_or(false)); + assert!(fs::metadata(td.path().join("tmp/abs_evil4.txt")) + .map(|m| m.is_file()).unwrap_or(false)); + assert!(fs::metadata(td.path().join("tmp/abs_evil5.txt")) + .map(|m| m.is_file()).unwrap_or(false)); + assert!(fs::metadata(td.path().join("tmp/abs_evil6.txt")) + .map(|m| m.is_file()).unwrap_or(false)); +} + +#[test] +fn octal_spaces() { + let rdr = Cursor::new(tar!("spaces.tar")); + let mut ar = Archive::new(rdr); + + let entry = ar.entries().unwrap().next().unwrap().unwrap(); + assert_eq!(entry.header().mode().unwrap() & 0o777, 0o777); + assert_eq!(entry.header().uid().unwrap(), 0); + assert_eq!(entry.header().gid().unwrap(), 0); + assert_eq!(entry.header().size().unwrap(), 2); + assert_eq!(entry.header().mtime().unwrap(), 0o12440016664); + assert_eq!(entry.header().cksum().unwrap(), 0o4253); +} + +#[test] +fn extracting_malformed_tar_null_blocks() { + let td = t!(TempDir::new("tar-rs")); + + let mut ar = Builder::new(Vec::new()); + + let path1 = td.path().join("tmpfile1"); + let path2 = td.path().join("tmpfile2"); + t!(File::create(&path1)); + t!(File::create(&path2)); + t!(ar.append_file("tmpfile1", &mut t!(File::open(&path1)))); + let mut data = t!(ar.into_inner()); + let amt = data.len(); + data.truncate(amt - 512); + let mut ar = Builder::new(data); + t!(ar.append_file("tmpfile2", &mut t!(File::open(&path2)))); + t!(ar.finish()); + + let data = t!(ar.into_inner()); + let mut ar = Archive::new(&data[..]); + assert!(ar.unpack(td.path()).is_err()); +} + +#[test] +fn empty_filename() +{ + let td = t!(TempDir::new("tar-rs")); + let rdr = Cursor::new(tar!("empty_filename.tar")); + let mut ar = Archive::new(rdr); + assert!(ar.unpack(td.path()).is_err()); +} + +#[test] +fn file_times() { + let td = t!(TempDir::new("tar-rs")); + let rdr = Cursor::new(tar!("file_times.tar")); + let mut ar = Archive::new(rdr); + t!(ar.unpack(td.path())); + + let meta = fs::metadata(td.path().join("a")).unwrap(); + let mtime = FileTime::from_last_modification_time(&meta); + let atime = FileTime::from_last_access_time(&meta); + assert_eq!(mtime.unix_seconds(), 1000000000); + assert_eq!(mtime.nanoseconds(), 0); + assert_eq!(atime.unix_seconds(), 1000000000); + assert_eq!(atime.nanoseconds(), 0); +} + +#[test] +fn backslash_treated_well() { + // Insert a file into an archive with a backslash + let td = t!(TempDir::new("tar-rs")); + let mut ar = Builder::new(Vec::<u8>::new()); + t!(ar.append_dir("foo\\bar", td.path())); + let mut ar = Archive::new(Cursor::new(t!(ar.into_inner()))); + let f = t!(t!(ar.entries()).next().unwrap()); + if cfg!(unix) { + assert_eq!(t!(f.header().path()).to_str(), Some("foo\\bar")); + } else { + assert_eq!(t!(f.header().path()).to_str(), Some("foo/bar")); + } + + // Unpack an archive with a backslash in the name + let mut ar = Builder::new(Vec::<u8>::new()); + let mut header = Header::new_gnu(); + header.set_metadata(&t!(fs::metadata(td.path()))); + header.set_size(0); + for (a, b) in header.as_old_mut().name.iter_mut().zip(b"foo\\bar\x00") { + *a = *b; + } + header.set_cksum(); + t!(ar.append(&header, &mut io::empty())); + let data = t!(ar.into_inner()); + let mut ar = Archive::new(&data[..]); + let f = t!(t!(ar.entries()).next().unwrap()); + assert_eq!(t!(f.header().path()).to_str(), Some("foo\\bar")); + + let mut ar = Archive::new(&data[..]); + t!(ar.unpack(td.path())); + assert!(fs::metadata(td.path().join("foo\\bar")).is_ok()); +} + +#[cfg(unix)] +#[test] +fn nul_bytes_in_path() { + use std::os::unix::prelude::*; + use std::ffi::OsStr; + + let nul_path = OsStr::from_bytes(b"foo\0"); + let td = t!(TempDir::new("tar-rs")); + let mut ar = Builder::new(Vec::<u8>::new()); + let err = ar.append_dir(nul_path, td.path()).unwrap_err(); + assert!(err.to_string().contains("contains a nul byte")); +} + +#[test] +fn links() { + let mut ar = Archive::new(Cursor::new(tar!("link.tar"))); + let mut entries = t!(ar.entries()); + let link = t!(entries.next().unwrap()); + assert_eq!(t!(link.header().link_name()).as_ref().map(|p| &**p), + Some(Path::new("file"))); + let other = t!(entries.next().unwrap()); + assert!(t!(other.header().link_name()).is_none()); +} + +#[test] +#[cfg(unix)] // making symlinks on windows is hard +fn unpack_links() { + let td = t!(TempDir::new("tar-rs")); + let mut ar = Archive::new(Cursor::new(tar!("link.tar"))); + t!(ar.unpack(td.path())); + + let md = t!(fs::symlink_metadata(td.path().join("lnk"))); + assert!(md.file_type().is_symlink()); + assert_eq!(&*t!(fs::read_link(td.path().join("lnk"))), + Path::new("file")); + t!(File::open(td.path().join("lnk"))); +} + +#[test] +fn pax_simple() { + let mut ar = Archive::new(tar!("pax.tar")); + let mut entries = t!(ar.entries()); + + let mut first = t!(entries.next().unwrap()); + let mut attributes = t!(first.pax_extensions()).unwrap(); + let first = t!(attributes.next().unwrap()); + let second = t!(attributes.next().unwrap()); + let third = t!(attributes.next().unwrap()); + assert!(attributes.next().is_none()); + + assert_eq!(first.key(), Ok("mtime")); + assert_eq!(first.value(), Ok("1453146164.953123768")); + assert_eq!(second.key(), Ok("atime")); + assert_eq!(second.value(), Ok("1453251915.24892486")); + assert_eq!(third.key(), Ok("ctime")); + assert_eq!(third.value(), Ok("1453146164.953123768")); +} + +#[test] +fn long_name_trailing_nul() { + let mut b = Builder::new(Vec::<u8>::new()); + + let mut h = Header::new_gnu(); + t!(h.set_path("././@LongLink")); + h.set_size(4); + h.set_entry_type(EntryType::new(b'L')); + h.set_cksum(); + t!(b.append(&h, "foo\0".as_bytes())); + let mut h = Header::new_gnu(); + + t!(h.set_path("bar")); + h.set_size(6); + h.set_entry_type(EntryType::file()); + h.set_cksum(); + t!(b.append(&h, "foobar".as_bytes())); + + let contents = t!(b.into_inner()); + let mut a = Archive::new(&contents[..]); + + let e = t!(t!(a.entries()).next().unwrap()); + assert_eq!(&*e.path_bytes(), b"foo"); +} + +#[test] +fn long_linkname_trailing_nul() { + let mut b = Builder::new(Vec::<u8>::new()); + + let mut h = Header::new_gnu(); + t!(h.set_path("././@LongLink")); + h.set_size(4); + h.set_entry_type(EntryType::new(b'K')); + h.set_cksum(); + t!(b.append(&h, "foo\0".as_bytes())); + let mut h = Header::new_gnu(); + + t!(h.set_path("bar")); + h.set_size(6); + h.set_entry_type(EntryType::file()); + h.set_cksum(); + t!(b.append(&h, "foobar".as_bytes())); + + let contents = t!(b.into_inner()); + let mut a = Archive::new(&contents[..]); + + let e = t!(t!(a.entries()).next().unwrap()); + assert_eq!(&*e.link_name_bytes().unwrap(), b"foo"); +} + +#[test] +fn encoded_long_name_has_trailing_nul() { + let td = t!(TempDir::new("tar-rs")); + let path = td.path().join("foo"); + t!(t!(File::create(&path)).write_all(b"test")); + + let mut b = Builder::new(Vec::<u8>::new()); + let long = repeat("abcd").take(200).collect::<String>(); + + t!(b.append_file(&long, &mut t!(File::open(&path)))); + + let contents = t!(b.into_inner()); + let mut a = Archive::new(&contents[..]); + + let mut e = t!(t!(a.entries()).raw(true).next().unwrap()); + let mut name = Vec::new(); + t!(e.read_to_end(&mut name)); + assert_eq!(name[name.len() - 1], 0); + + let header_name = &e.header().as_gnu().unwrap().name; + assert!(header_name.starts_with(b"././@LongLink\x00")); +} + +#[test] +fn reading_sparse() { + let rdr = Cursor::new(tar!("sparse.tar")); + let mut ar = Archive::new(rdr); + let mut entries = t!(ar.entries()); + + let mut a = t!(entries.next().unwrap()); + let mut s = String::new(); + assert_eq!(&*a.header().path_bytes(), b"sparse_begin.txt"); + t!(a.read_to_string(&mut s)); + assert_eq!(&s[..5], "test\n"); + assert!(s[5..].chars().all(|x| x == '\u{0}')); + + let mut a = t!(entries.next().unwrap()); + let mut s = String::new(); + assert_eq!(&*a.header().path_bytes(), b"sparse_end.txt"); + t!(a.read_to_string(&mut s)); + assert!(s[..s.len() - 9].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[s.len() - 9..], "test_end\n"); + + let mut a = t!(entries.next().unwrap()); + let mut s = String::new(); + assert_eq!(&*a.header().path_bytes(), b"sparse_ext.txt"); + t!(a.read_to_string(&mut s)); + assert!(s[..0x1000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x1000..0x1000+5], "text\n"); + assert!(s[0x1000+5..0x3000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x3000..0x3000+5], "text\n"); + assert!(s[0x3000+5..0x5000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x5000..0x5000+5], "text\n"); + assert!(s[0x5000+5..0x7000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x7000..0x7000+5], "text\n"); + assert!(s[0x7000+5..0x9000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x9000..0x9000+5], "text\n"); + assert!(s[0x9000+5..0xb000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0xb000..0xb000+5], "text\n"); + + let mut a = t!(entries.next().unwrap()); + let mut s = String::new(); + assert_eq!(&*a.header().path_bytes(), b"sparse.txt"); + t!(a.read_to_string(&mut s)); + assert!(s[..0x1000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x1000..0x1000+6], "hello\n"); + assert!(s[0x1000+6..0x2fa0].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x2fa0..0x2fa0+6], "world\n"); + assert!(s[0x2fa0+6..0x4000].chars().all(|x| x == '\u{0}')); + + assert!(entries.next().is_none()); +} + +#[test] +fn extract_sparse() { + let rdr = Cursor::new(tar!("sparse.tar")); + let mut ar = Archive::new(rdr); + let td = t!(TempDir::new("tar-rs")); + t!(ar.unpack(td.path())); + + let mut s = String::new(); + t!(t!(File::open(td.path().join("sparse_begin.txt"))).read_to_string(&mut s)); + assert_eq!(&s[..5], "test\n"); + assert!(s[5..].chars().all(|x| x == '\u{0}')); + + s.truncate(0); + t!(t!(File::open(td.path().join("sparse_end.txt"))).read_to_string(&mut s)); + assert!(s[..s.len() - 9].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[s.len() - 9..], "test_end\n"); + + s.truncate(0); + t!(t!(File::open(td.path().join("sparse_ext.txt"))).read_to_string(&mut s)); + assert!(s[..0x1000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x1000..0x1000+5], "text\n"); + assert!(s[0x1000+5..0x3000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x3000..0x3000+5], "text\n"); + assert!(s[0x3000+5..0x5000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x5000..0x5000+5], "text\n"); + assert!(s[0x5000+5..0x7000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x7000..0x7000+5], "text\n"); + assert!(s[0x7000+5..0x9000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x9000..0x9000+5], "text\n"); + assert!(s[0x9000+5..0xb000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0xb000..0xb000+5], "text\n"); + + s.truncate(0); + t!(t!(File::open(td.path().join("sparse.txt"))).read_to_string(&mut s)); + assert!(s[..0x1000].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x1000..0x1000+6], "hello\n"); + assert!(s[0x1000+6..0x2fa0].chars().all(|x| x == '\u{0}')); + assert_eq!(&s[0x2fa0..0x2fa0+6], "world\n"); + assert!(s[0x2fa0+6..0x4000].chars().all(|x| x == '\u{0}')); +} + +#[test] +fn path_separators() { + let mut ar = Builder::new(Vec::new()); + let td = t!(TempDir::new("tar-rs")); + + let path = td.path().join("test"); + t!(t!(File::create(&path)).write_all(b"test")); + + let short_path: PathBuf = repeat("abcd").take(2).collect(); + let long_path: PathBuf = repeat("abcd").take(50).collect(); + + // Make sure UStar headers normalize to Unix path separators + let mut header = Header::new_ustar(); + + t!(header.set_path(&short_path)); + assert_eq!(t!(header.path()), short_path); + assert!(!header.path_bytes().contains(&b'\\')); + + t!(header.set_path(&long_path)); + assert_eq!(t!(header.path()), long_path); + assert!(!header.path_bytes().contains(&b'\\')); + + // Make sure GNU headers normalize to Unix path separators, + // including the `@LongLink` fallback used by `append_file`. + t!(ar.append_file(&short_path, &mut t!(File::open(&path)))); + t!(ar.append_file(&long_path, &mut t!(File::open(&path)))); + + let rd = Cursor::new(t!(ar.into_inner())); + let mut ar = Archive::new(rd); + let mut entries = t!(ar.entries()); + + let entry = t!(entries.next().unwrap()); + assert_eq!(t!(entry.path()), short_path); + assert!(!entry.path_bytes().contains(&b'\\')); + + let entry = t!(entries.next().unwrap()); + assert_eq!(t!(entry.path()), long_path); + assert!(!entry.path_bytes().contains(&b'\\')); + + assert!(entries.next().is_none()); +} + +#[test] +#[cfg(unix)] +fn append_path_symlink() { + use std::os::unix::fs::symlink; + use std::env; + use std::borrow::Cow; + + let mut ar = Builder::new(Vec::new()); + ar.follow_symlinks(false); + let td = t!(TempDir::new("tar-rs")); + + t!(env::set_current_dir(td.path())); + t!(symlink("testdest", "test")); + t!(ar.append_path("test")); + + let rd = Cursor::new(t!(ar.into_inner())); + let mut ar = Archive::new(rd); + let mut entries = t!(ar.entries()); + + let entry = t!(entries.next().unwrap()); + assert_eq!(t!(entry.path()), Path::new("test")); + assert_eq!(t!(entry.link_name()), Some(Cow::from(Path::new("testdest")))); + assert_eq!(t!(entry.header().size()), 0); + + assert!(entries.next().is_none()); +} Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.15/tests/archives/directory.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.15/tests/archives/directory.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.15/tests/archives/duplicate_dirs.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.15/tests/archives/duplicate_dirs.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.15/tests/archives/empty_filename.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.15/tests/archives/empty_filename.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.15/tests/archives/file_times.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.15/tests/archives/file_times.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.15/tests/archives/link.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.15/tests/archives/link.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.15/tests/archives/pax.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.15/tests/archives/pax.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.15/tests/archives/reading_files.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.15/tests/archives/reading_files.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.15/tests/archives/simple.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.15/tests/archives/simple.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.15/tests/archives/spaces.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.15/tests/archives/spaces.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.15/tests/archives/sparse.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.15/tests/archives/sparse.tar differ Binary files /tmp/tmpiV2tG_/C2CRIz95wk/cargo-0.25.0/vendor/tar-0.4.15/tests/archives/xattrs.tar and /tmp/tmpiV2tG_/BehdPWVvSE/cargo-0.26.0/vendor/tar-0.4.15/tests/archives/xattrs.tar differ diff -Nru cargo-0.25.0/vendor/tar-0.4.15/tests/entry.rs cargo-0.26.0/vendor/tar-0.4.15/tests/entry.rs --- cargo-0.25.0/vendor/tar-0.4.15/tests/entry.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/tests/entry.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,249 @@ +extern crate tar; +extern crate tempdir; + +use std::fs::File; + +use tempdir::TempDir; + +macro_rules! t { + ($e:expr) => (match $e { + Ok(v) => v, + Err(e) => panic!("{} returned {}", stringify!($e), e), + }) +} + +#[test] +fn absolute_symlink() { + let mut ar = tar::Builder::new(Vec::new()); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Symlink); + t!(header.set_path("foo")); + t!(header.set_link_name("/bar")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let bytes = t!(ar.into_inner()); + let mut ar = tar::Archive::new(&bytes[..]); + + let td = t!(TempDir::new("tar")); + t!(ar.unpack(td.path())); + + t!(td.path().join("foo").symlink_metadata()); + + let mut ar = tar::Archive::new(&bytes[..]); + let mut entries = t!(ar.entries()); + let entry = t!(entries.next().unwrap()); + assert_eq!(&*entry.link_name_bytes().unwrap(), b"/bar"); +} + +#[test] +fn absolute_hardlink() { + let td = t!(TempDir::new("tar")); + let mut ar = tar::Builder::new(Vec::new()); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Regular); + t!(header.set_path("foo")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Link); + t!(header.set_path("bar")); + // This absolute path under tempdir will be created at unpack time + t!(header.set_link_name(td.path().join("foo"))); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let bytes = t!(ar.into_inner()); + let mut ar = tar::Archive::new(&bytes[..]); + + t!(ar.unpack(td.path())); + t!(td.path().join("foo").metadata()); + t!(td.path().join("bar").metadata()); +} + +#[test] +fn relative_hardlink() { + let mut ar = tar::Builder::new(Vec::new()); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Regular); + t!(header.set_path("foo")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Link); + t!(header.set_path("bar")); + t!(header.set_link_name("foo")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let bytes = t!(ar.into_inner()); + let mut ar = tar::Archive::new(&bytes[..]); + + let td = t!(TempDir::new("tar")); + t!(ar.unpack(td.path())); + t!(td.path().join("foo").metadata()); + t!(td.path().join("bar").metadata()); +} + +#[test] +fn absolute_link_deref_error() { + let mut ar = tar::Builder::new(Vec::new()); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Symlink); + t!(header.set_path("foo")); + t!(header.set_link_name("/")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Regular); + t!(header.set_path("foo/bar")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let bytes = t!(ar.into_inner()); + let mut ar = tar::Archive::new(&bytes[..]); + + let td = t!(TempDir::new("tar")); + assert!(ar.unpack(td.path()).is_err()); + t!(td.path().join("foo").symlink_metadata()); + assert!(File::open(td.path().join("foo").join("bar")).is_err()); +} + +#[test] +fn relative_link_deref_error() { + let mut ar = tar::Builder::new(Vec::new()); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Symlink); + t!(header.set_path("foo")); + t!(header.set_link_name("../../../../")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Regular); + t!(header.set_path("foo/bar")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let bytes = t!(ar.into_inner()); + let mut ar = tar::Archive::new(&bytes[..]); + + let td = t!(TempDir::new("tar")); + assert!(ar.unpack(td.path()).is_err()); + t!(td.path().join("foo").symlink_metadata()); + assert!(File::open(td.path().join("foo").join("bar")).is_err()); +} + +#[test] +fn modify_link_just_created() { + let mut ar = tar::Builder::new(Vec::new()); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Symlink); + t!(header.set_path("foo")); + t!(header.set_link_name("bar")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Regular); + t!(header.set_path("bar/foo")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Regular); + t!(header.set_path("foo/bar")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let bytes = t!(ar.into_inner()); + let mut ar = tar::Archive::new(&bytes[..]); + + let td = t!(TempDir::new("tar")); + t!(ar.unpack(td.path())); + + t!(File::open(td.path().join("bar/foo"))); + t!(File::open(td.path().join("bar/bar"))); + t!(File::open(td.path().join("foo/foo"))); + t!(File::open(td.path().join("foo/bar"))); +} + +#[test] +fn parent_paths_error() { + let mut ar = tar::Builder::new(Vec::new()); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Symlink); + t!(header.set_path("foo")); + t!(header.set_link_name("..")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Regular); + t!(header.set_path("foo/bar")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let bytes = t!(ar.into_inner()); + let mut ar = tar::Archive::new(&bytes[..]); + + let td = t!(TempDir::new("tar")); + assert!(ar.unpack(td.path()).is_err()); + t!(td.path().join("foo").symlink_metadata()); + assert!(File::open(td.path().join("foo").join("bar")).is_err()); +} + +#[test] +#[cfg(unix)] +fn good_parent_paths_ok() { + use std::path::PathBuf; + let mut ar = tar::Builder::new(Vec::new()); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Symlink); + t!(header.set_path(PathBuf::from("foo").join("bar"))); + t!(header.set_link_name(PathBuf::from("..").join("bar"))); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let mut header = tar::Header::new_gnu(); + header.set_size(0); + header.set_entry_type(tar::EntryType::Regular); + t!(header.set_path("bar")); + header.set_cksum(); + t!(ar.append(&header, &[][..])); + + let bytes = t!(ar.into_inner()); + let mut ar = tar::Archive::new(&bytes[..]); + + let td = t!(TempDir::new("tar")); + t!(ar.unpack(td.path())); + t!(td.path().join("foo").join("bar").read_link()); + let dst = t!(td.path().join("foo").join("bar").canonicalize()); + t!(File::open(dst)); +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/tests/header/mod.rs cargo-0.26.0/vendor/tar-0.4.15/tests/header/mod.rs --- cargo-0.25.0/vendor/tar-0.4.15/tests/header/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/tests/header/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,221 @@ +use std::fs::{self, File}; +use std::io::{self, Write}; +use std::path::Path; +use std::{iter, mem, thread, time}; + +use tempdir::TempDir; + +use tar::{Header, HeaderMode, GnuHeader}; + +#[test] +fn default_gnu() { + let mut h = Header::new_gnu(); + assert!(h.as_gnu().is_some()); + assert!(h.as_gnu_mut().is_some()); + assert!(h.as_ustar().is_none()); + assert!(h.as_ustar_mut().is_none()); +} + +#[test] +fn goto_old() { + let mut h = Header::new_old(); + assert!(h.as_gnu().is_none()); + assert!(h.as_gnu_mut().is_none()); + assert!(h.as_ustar().is_none()); + assert!(h.as_ustar_mut().is_none()); +} + +#[test] +fn goto_ustar() { + let mut h = Header::new_ustar(); + assert!(h.as_gnu().is_none()); + assert!(h.as_gnu_mut().is_none()); + assert!(h.as_ustar().is_some()); + assert!(h.as_ustar_mut().is_some()); +} + +#[test] +fn link_name() { + let mut h = Header::new_gnu(); + t!(h.set_link_name("foo")); + assert_eq!(t!(h.link_name()).unwrap().to_str(), Some("foo")); + t!(h.set_link_name("../foo")); + assert_eq!(t!(h.link_name()).unwrap().to_str(), Some("../foo")); + t!(h.set_link_name("foo/bar")); + assert_eq!(t!(h.link_name()).unwrap().to_str(), Some("foo/bar")); + t!(h.set_link_name("foo\\ba")); + if cfg!(windows) { + assert_eq!(t!(h.link_name()).unwrap().to_str(), Some("foo/ba")); + } else { + assert_eq!(t!(h.link_name()).unwrap().to_str(), Some("foo\\ba")); + } + + let name = "foo\\bar\0"; + for (slot, val) in h.as_old_mut().linkname.iter_mut().zip(name.as_bytes()) { + *slot = *val; + } + assert_eq!(t!(h.link_name()).unwrap().to_str(), Some("foo\\bar")); + + assert!(h.set_link_name("\0").is_err()); +} + +#[test] +fn mtime() { + let h = Header::new_gnu(); + assert_eq!(t!(h.mtime()), 0); + + let h = Header::new_ustar(); + assert_eq!(t!(h.mtime()), 0); + + let h = Header::new_old(); + assert_eq!(t!(h.mtime()), 0); +} + +#[test] +fn user_and_group_name() { + let mut h = Header::new_gnu(); + t!(h.set_username("foo")); + t!(h.set_groupname("bar")); + assert_eq!(t!(h.username()), Some("foo")); + assert_eq!(t!(h.groupname()), Some("bar")); + + h = Header::new_ustar(); + t!(h.set_username("foo")); + t!(h.set_groupname("bar")); + assert_eq!(t!(h.username()), Some("foo")); + assert_eq!(t!(h.groupname()), Some("bar")); + + h = Header::new_old(); + assert_eq!(t!(h.username()), None); + assert_eq!(t!(h.groupname()), None); + assert!(h.set_username("foo").is_err()); + assert!(h.set_groupname("foo").is_err()); +} + +#[test] +fn dev_major_minor() { + let mut h = Header::new_gnu(); + t!(h.set_device_major(1)); + t!(h.set_device_minor(2)); + assert_eq!(t!(h.device_major()), Some(1)); + assert_eq!(t!(h.device_minor()), Some(2)); + + h = Header::new_ustar(); + t!(h.set_device_major(1)); + t!(h.set_device_minor(2)); + assert_eq!(t!(h.device_major()), Some(1)); + assert_eq!(t!(h.device_minor()), Some(2)); + + h.as_ustar_mut().unwrap().dev_minor[0] = 0x7f; + h.as_ustar_mut().unwrap().dev_major[0] = 0x7f; + assert!(h.device_major().is_err()); + assert!(h.device_minor().is_err()); + + h.as_ustar_mut().unwrap().dev_minor[0] = b'g'; + h.as_ustar_mut().unwrap().dev_major[0] = b'h'; + assert!(h.device_major().is_err()); + assert!(h.device_minor().is_err()); + + h = Header::new_old(); + assert_eq!(t!(h.device_major()), None); + assert_eq!(t!(h.device_minor()), None); + assert!(h.set_device_major(1).is_err()); + assert!(h.set_device_minor(1).is_err()); +} + +#[test] +fn set_path() { + let mut h = Header::new_gnu(); + t!(h.set_path("foo")); + assert_eq!(t!(h.path()).to_str(), Some("foo")); + t!(h.set_path("foo/")); + assert_eq!(t!(h.path()).to_str(), Some("foo/")); + t!(h.set_path("foo/bar")); + assert_eq!(t!(h.path()).to_str(), Some("foo/bar")); + t!(h.set_path("foo\\bar")); + if cfg!(windows) { + assert_eq!(t!(h.path()).to_str(), Some("foo/bar")); + } else { + assert_eq!(t!(h.path()).to_str(), Some("foo\\bar")); + } + + let long_name = iter::repeat("foo").take(100).collect::<String>(); + let medium1 = iter::repeat("foo").take(52).collect::<String>(); + let medium2 = iter::repeat("fo/").take(52).collect::<String>(); + + assert!(h.set_path(&long_name).is_err()); + assert!(h.set_path(&medium1).is_err()); + assert!(h.set_path(&medium2).is_err()); + assert!(h.set_path("\0").is_err()); + + h = Header::new_ustar(); + t!(h.set_path("foo")); + assert_eq!(t!(h.path()).to_str(), Some("foo")); + + assert!(h.set_path(&long_name).is_err()); + assert!(h.set_path(&medium1).is_err()); + t!(h.set_path(&medium2)); + assert_eq!(t!(h.path()).to_str(), Some(&medium2[..])); +} + +#[test] +fn set_ustar_path_hard() { + let mut h = Header::new_ustar(); + let p = Path::new("a").join(&vec!["a"; 100].join("")); + t!(h.set_path(&p)); + assert_eq!(t!(h.path()), p); +} + +#[test] +fn set_metadata_deterministic() { + let td = t!(TempDir::new("tar-rs")); + let tmppath = td.path().join("tmpfile"); + + fn mk_header(path: &Path, readonly: bool) -> Result<Header, io::Error> { + let mut file = t!(File::create(path)); + t!(file.write_all(b"c")); + let mut perms = t!(file.metadata()).permissions(); + perms.set_readonly(readonly); + t!(fs::set_permissions(path, perms)); + let mut h = Header::new_ustar(); + h.set_metadata_in_mode(&t!(path.metadata()), HeaderMode::Deterministic); + Ok(h) + } + + // Create "the same" File twice in a row, one second apart, with differing readonly values. + let one = t!(mk_header(tmppath.as_path(), false)); + thread::sleep(time::Duration::from_millis(1050)); + let two = t!(mk_header(tmppath.as_path(), true)); + + // Always expected to match. + assert_eq!(t!(one.size()), t!(two.size())); + assert_eq!(t!(one.path()), t!(two.path())); + assert_eq!(t!(one.mode()), t!(two.mode())); + + // Would not match without `Deterministic`. + assert_eq!(t!(one.mtime()), t!(two.mtime())); + // TODO: No great way to validate that these would not be filled, but + // check them anyway. + assert_eq!(t!(one.uid()), t!(two.uid())); + assert_eq!(t!(one.gid()), t!(two.gid())); +} + +#[test] +fn extended_numeric_format() { + let mut h: GnuHeader = unsafe { mem::zeroed() }; + h.size = [0x80, 0, 0, 0, 0, 0, 0, 0x02, 0, 0, 0, 0]; + assert_eq!(h.as_header().entry_size().unwrap(), 0x0200000000); + // TODO uids can be up to 63 bits technically + h.uid = [0x80, 0x00, 0x00, 0x00, 0x12, 0x34, 0x56, 0x78]; + assert_eq!(h.as_header().uid().unwrap(), 0x12345678); + h.mtime = [0x80, 0, 0, 0, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]; + assert_eq!(h.as_header().mtime().unwrap(), 0x0123456789abcdef); +} + +#[test] +fn byte_slice_conversion() { + let h = Header::new_gnu(); + let b: &[u8] = h.as_bytes(); + let b_conv: &[u8] = Header::from_byte_slice(h.as_bytes()).as_bytes(); + assert_eq!(b, b_conv); +} diff -Nru cargo-0.25.0/vendor/tar-0.4.15/.travis.yml cargo-0.26.0/vendor/tar-0.4.15/.travis.yml --- cargo-0.25.0/vendor/tar-0.4.15/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tar-0.4.15/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,34 @@ +language: rust +rust: + - stable + - beta + - nightly + - 1.21.0 +env: + global: + - RUSTFLAGS='-C link-dead-code' +sudo: false +before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH +script: + - cargo build --verbose + - cargo test --verbose + - cargo test --verbose --no-default-features + - cargo clean && cargo build + - rustdoc --test README.md -L target/debug -L target/debug/deps + - cargo doc --no-deps +after_success: + - travis-cargo --only nightly doc-upload + - travis-cargo coveralls --no-sudo +notifications: + email: + on_success: never +addons: + apt: + packages: + - libcurl4-openssl-dev + - libelf-dev + - libdw-dev +env: + global: + secure: "BkV2h2/dkKFUBhdiN3CvUt/zVdIsLhqlVIpS5uV5mQNyiQyZQ+czCmxvAoBF0r6ER6gdbUwvtBVTZ9fT+JmdpxcRJB7/oJ535MYRVkng13GjmDjj3y4KbGZdKsXgNpWPk5EbpFYZ6VdJ6LnEOBEE2aWbAbHwXgWxDCQtlgTeoXQ=" diff -Nru cargo-0.25.0/vendor/tempdir-0.3.6/appveyor.yml cargo-0.26.0/vendor/tempdir-0.3.6/appveyor.yml --- cargo-0.25.0/vendor/tempdir-0.3.6/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.6/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -environment: - matrix: - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc - - TARGET: i686-pc-windows-gnu -install: - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" - - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - - SET PATH=%PATH%;C:\MinGW\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo test --verbose diff -Nru cargo-0.25.0/vendor/tempdir-0.3.6/.cargo-checksum.json cargo-0.26.0/vendor/tempdir-0.3.6/.cargo-checksum.json --- cargo-0.25.0/vendor/tempdir-0.3.6/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.6/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"f73eebdb68c14bcb24aef74ea96079830e7fa7b31a6106e42ea7ee887c1e134e"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/tempdir-0.3.6/Cargo.toml cargo-0.26.0/vendor/tempdir-0.3.6/Cargo.toml --- cargo-0.25.0/vendor/tempdir-0.3.6/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.6/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "tempdir" -version = "0.3.6" -authors = ["The Rust Project Developers"] -description = "A library for managing a temporary directory and deleting all contents when it's\ndropped.\n" -homepage = "https://github.com/rust-lang/tempdir" -documentation = "https://doc.rust-lang.org/tempdir" -readme = "README.md" -keywords = ["fs", "file", "filesystem"] -categories = ["filesystem"] -license = "MIT/Apache-2.0" -repository = "https://github.com/rust-lang/tempdir" -[dependencies.rand] -version = "0.4" - -[dependencies.remove_dir_all] -version = "0.3" -[badges.appveyor] -repository = "rust-lang-libs/tempdir" - -[badges.travis-ci] -repository = "rust-lang-nursery/tempdir" diff -Nru cargo-0.25.0/vendor/tempdir-0.3.6/LICENSE-APACHE cargo-0.26.0/vendor/tempdir-0.3.6/LICENSE-APACHE --- cargo-0.25.0/vendor/tempdir-0.3.6/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.6/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/tempdir-0.3.6/LICENSE-MIT cargo-0.26.0/vendor/tempdir-0.3.6/LICENSE-MIT --- cargo-0.25.0/vendor/tempdir-0.3.6/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.6/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/tempdir-0.3.6/README.md cargo-0.26.0/vendor/tempdir-0.3.6/README.md --- cargo-0.25.0/vendor/tempdir-0.3.6/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.6/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -tempdir -======= - -A Rust library for creating a temporary directory and deleting its entire -contents when the directory is dropped. - -[![Build Status](https://travis-ci.org/rust-lang-nursery/tempdir.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/tempdir) -[![Build status](https://ci.appveyor.com/api/projects/status/2mp24396db5t4hul/branch/master?svg=true)](https://ci.appveyor.com/project/rust-lang-libs/tempdir/branch/master) - -[Documentation](https://doc.rust-lang.org/tempdir) - -## Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -tempdir = "0.3" -``` - -and this to your crate root: - -```rust -extern crate tempdir; -``` - -## Example - -This sample method does the following: - -1. Create a temporary directory in the default location with the given prefix. -2. Determine a file path in the directory and print it out. -3. Create a file inside the temp folder. -4. Write to the file and sync it to disk. -5. Close the directory, deleting the contents in the process. - -```rust -use std::io::{self, Write}; -use std::fs::File; -use tempdir::TempDir; - -fn write_temp_folder_with_files() -> io::Result<()> { - let dir = TempDir::new("my_directory_prefix")?; - let file_path = dir.path().join("foo.txt"); - println!("{:?}", file_path); - - let mut f = File::create(file_path)?; - f.write_all(b"Hello, world!")?; - f.sync_all()?; - dir.close()?; - - Ok(()) -} -``` - -**Note:** Closing the directory is actually optional, as it would be done on -drop. The benefit of closing here is that it allows possible errors to be -handled. diff -Nru cargo-0.25.0/vendor/tempdir-0.3.6/src/lib.rs cargo-0.26.0/vendor/tempdir-0.3.6/src/lib.rs --- cargo-0.25.0/vendor/tempdir-0.3.6/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.6/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,360 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", - html_favicon_url = "https://www.rust-lang.org/favicon.ico", - html_root_url = "https://docs.rs/tempdir/0.3.6")] -#![cfg_attr(test, deny(warnings))] - -//! Temporary directories of files. -//! -//! The [`TempDir`] type creates a directory on the file system that -//! is deleted once it goes out of scope. At construction, the -//! `TempDir` creates a new directory with a randomly generated name -//! and a prefix of your choosing. -//! -//! [`TempDir`]: struct.TempDir.html -//! [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html -//! -//! # Examples -//! -//! ``` -//! extern crate tempdir; -//! -//! use std::fs::File; -//! use std::io::{self, Write}; -//! use tempdir::TempDir; -//! -//! fn main() { -//! if let Err(_) = run() { -//! ::std::process::exit(1); -//! } -//! } -//! -//! fn run() -> Result<(), io::Error> { -//! // Create a directory inside of `std::env::temp_dir()`, named with -//! // the prefix "example". -//! let tmp_dir = TempDir::new("example")?; -//! let file_path = tmp_dir.path().join("my-temporary-note.txt"); -//! let mut tmp_file = File::create(file_path)?; -//! writeln!(tmp_file, "Brian was here. Briefly.")?; -//! -//! // By closing the `TempDir` explicitly, we can check that it has -//! // been deleted successfully. If we don't close it explicitly, -//! // the directory will still be deleted when `tmp_dir` goes out -//! // of scope, but we won't know whether deleting the directory -//! // succeeded. -//! drop(tmp_file); -//! tmp_dir.close()?; -//! Ok(()) -//! } -//! ``` - -extern crate rand; -extern crate remove_dir_all; - -use std::env; -use std::io::{self, Error, ErrorKind}; -use std::fmt; -use std::fs; -use std::path::{self, PathBuf, Path}; -use rand::{thread_rng, Rng}; -use remove_dir_all::remove_dir_all; - -/// A directory in the filesystem that is automatically deleted when -/// it goes out of scope. -/// -/// The [`TempDir`] type creates a directory on the file system that -/// is deleted once it goes out of scope. At construction, the -/// `TempDir` creates a new directory with a randomly generated name, -/// and with a prefix of your choosing. -/// -/// The default constructor, [`TempDir::new`], creates directories in -/// the location returned by [`std::env::temp_dir()`], but `TempDir` -/// can be configured to manage a temporary directory in any location -/// by constructing with [`TempDir::new_in`]. -/// -/// After creating a `TempDir`, work with the file system by doing -/// standard [`std::fs`] file system operations on its [`Path`], -/// which can be retrieved with [`TempDir::path`]. Once the `TempDir` -/// value is dropped, the directory at the path will be deleted, along -/// with any files and directories it contains. It is your responsibility -/// to ensure that no further file system operations are attempted -/// inside the temporary directory once it has been deleted. -/// -/// Various platform-specific conditions may cause `TempDir` to fail -/// to delete the underlying directory. It's important to ensure that -/// handles (like [`File`] and [`ReadDir`]) to files inside the -/// directory are dropped before the `TempDir` goes out of scope. The -/// `TempDir` destructor will silently ignore any errors in deleting -/// the directory; to instead handle errors call [`TempDir::close`]. -/// -/// Note that if the program exits before the `TempDir` destructor is -/// run, such as via [`std::process::exit`], by segfaulting, or by -/// receiving a signal like `SIGINT`, then the temporary directory -/// will not be deleted. -/// -/// [`File`]: http://doc.rust-lang.org/std/fs/struct.File.html -/// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html -/// [`ReadDir`]: http://doc.rust-lang.org/std/fs/struct.ReadDir.html -/// [`TempDir::close`]: struct.TempDir.html#method.close -/// [`TempDir::new`]: struct.TempDir.html#method.new -/// [`TempDir::new_in`]: struct.TempDir.html#method.new_in -/// [`TempDir::path`]: struct.TempDir.html#method.path -/// [`TempDir`]: struct.TempDir.html -/// [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html -/// [`std::fs`]: http://doc.rust-lang.org/std/fs/index.html -/// [`std::process::exit`]: http://doc.rust-lang.org/std/process/fn.exit.html -pub struct TempDir { - path: Option<PathBuf>, -} - -// How many times should we (re)try finding an unused random name? It should be -// enough that an attacker will run out of luck before we run out of patience. -const NUM_RETRIES: u32 = 1 << 31; -// How many characters should we include in a random file name? It needs to -// be enough to dissuade an attacker from trying to preemptively create names -// of that length, but not so huge that we unnecessarily drain the random number -// generator of entropy. -const NUM_RAND_CHARS: usize = 12; - -impl TempDir { - /// Attempts to make a temporary directory inside of `env::temp_dir()` whose - /// name will have the prefix, `prefix`. The directory and - /// everything inside it will be automatically deleted once the - /// returned `TempDir` is destroyed. - /// - /// # Errors - /// - /// If the directory can not be created, `Err` is returned. - /// - /// # Examples - /// - /// ``` - /// use std::fs::File; - /// use std::io::Write; - /// use tempdir::TempDir; - /// - /// # use std::io; - /// # fn run() -> Result<(), io::Error> { - /// // Create a directory inside of `std::env::temp_dir()`, named with - /// // the prefix, "example". - /// let tmp_dir = TempDir::new("example")?; - /// let file_path = tmp_dir.path().join("my-temporary-note.txt"); - /// let mut tmp_file = File::create(file_path)?; - /// writeln!(tmp_file, "Brian was here. Briefly.")?; - /// - /// // `tmp_dir` goes out of scope, the directory as well as - /// // `tmp_file` will be deleted here. - /// # Ok(()) - /// # } - /// ``` - pub fn new(prefix: &str) -> io::Result<TempDir> { - TempDir::new_in(&env::temp_dir(), prefix) - } - - /// Attempts to make a temporary directory inside of `tmpdir` - /// whose name will have the prefix `prefix`. The directory and - /// everything inside it will be automatically deleted once the - /// returned `TempDir` is destroyed. - /// - /// # Errors - /// - /// If the directory can not be created, `Err` is returned. - /// - /// # Examples - /// - /// ``` - /// use std::fs::{self, File}; - /// use std::io::Write; - /// use tempdir::TempDir; - /// - /// # use std::io; - /// # fn run() -> Result<(), io::Error> { - /// // Create a directory inside of the current directory, named with - /// // the prefix, "example". - /// let tmp_dir = TempDir::new_in(".", "example")?; - /// let file_path = tmp_dir.path().join("my-temporary-note.txt"); - /// let mut tmp_file = File::create(file_path)?; - /// writeln!(tmp_file, "Brian was here. Briefly.")?; - /// # Ok(()) - /// # } - /// ``` - pub fn new_in<P: AsRef<Path>>(tmpdir: P, prefix: &str) -> io::Result<TempDir> { - let storage; - let mut tmpdir = tmpdir.as_ref(); - if !tmpdir.is_absolute() { - let cur_dir = env::current_dir()?; - storage = cur_dir.join(tmpdir); - tmpdir = &storage; - // return TempDir::new_in(&cur_dir.join(tmpdir), prefix); - } - - let mut rng = thread_rng(); - for _ in 0..NUM_RETRIES { - let suffix: String = rng.gen_ascii_chars().take(NUM_RAND_CHARS).collect(); - let leaf = if !prefix.is_empty() { - format!("{}.{}", prefix, suffix) - } else { - // If we're given an empty string for a prefix, then creating a - // directory starting with "." would lead to it being - // semi-invisible on some systems. - suffix - }; - let path = tmpdir.join(&leaf); - match fs::create_dir(&path) { - Ok(_) => return Ok(TempDir { path: Some(path) }), - Err(ref e) if e.kind() == ErrorKind::AlreadyExists => {} - Err(e) => return Err(e), - } - } - - Err(Error::new(ErrorKind::AlreadyExists, - "too many temporary directories already exist")) - } - - /// Accesses the [`Path`] to the temporary directory. - /// - /// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html - /// - /// # Examples - /// - /// ``` - /// use tempdir::TempDir; - /// - /// # use std::io; - /// # fn run() -> Result<(), io::Error> { - /// let tmp_path; - /// - /// { - /// let tmp_dir = TempDir::new("example")?; - /// tmp_path = tmp_dir.path().to_owned(); - /// - /// // Check that the temp directory actually exists. - /// assert!(tmp_path.exists()); - /// - /// // End of `tmp_dir` scope, directory will be deleted - /// } - /// - /// // Temp directory should be deleted by now - /// assert_eq!(tmp_path.exists(), false); - /// # Ok(()) - /// # } - /// ``` - pub fn path(&self) -> &path::Path { - self.path.as_ref().unwrap() - } - - /// Unwraps the [`Path`] contained in the `TempDir` and - /// returns it. This destroys the `TempDir` without deleting the - /// directory represented by the returned `Path`. - /// - /// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html - /// - /// # Examples - /// - /// ``` - /// use std::fs; - /// use tempdir::TempDir; - /// - /// # use std::io; - /// # fn run() -> Result<(), io::Error> { - /// let tmp_dir = TempDir::new("example")?; - /// - /// // Convert `tmp_dir` into a `Path`, destroying the `TempDir` - /// // without deleting the directory. - /// let tmp_path = tmp_dir.into_path(); - /// - /// // Delete the temporary directory ourselves. - /// fs::remove_dir_all(tmp_path)?; - /// # Ok(()) - /// # } - /// ``` - pub fn into_path(mut self) -> PathBuf { - self.path.take().unwrap() - } - - /// Closes and removes the temporary directory, returing a `Result`. - /// - /// Although `TempDir` removes the directory on drop, in the destructor - /// any errors are ignored. To detect errors cleaning up the temporary - /// directory, call `close` instead. - /// - /// # Errors - /// - /// This function may return a variety of [`std::io::Error`]s that result from deleting - /// the files and directories contained with the temporary directory, - /// as well as from deleting the temporary directory itself. These errors - /// may be platform specific. - /// - /// [`std::io::Error`]: http://doc.rust-lang.org/std/io/struct.Error.html - /// - /// # Examples - /// - /// ``` - /// use std::fs::File; - /// use std::io::Write; - /// use tempdir::TempDir; - /// - /// # use std::io; - /// # fn run() -> Result<(), io::Error> { - /// // Create a directory inside of `std::env::temp_dir()`, named with - /// // the prefix, "example". - /// let tmp_dir = TempDir::new("example")?; - /// let file_path = tmp_dir.path().join("my-temporary-note.txt"); - /// let mut tmp_file = File::create(file_path)?; - /// writeln!(tmp_file, "Brian was here. Briefly.")?; - /// - /// // By closing the `TempDir` explicitly we can check that it has - /// // been deleted successfully. If we don't close it explicitly, - /// // the directory will still be deleted when `tmp_dir` goes out - /// // of scope, but we won't know whether deleting the directory - /// // succeeded. - /// drop(tmp_file); - /// tmp_dir.close()?; - /// # Ok(()) - /// # } - /// ``` - pub fn close(mut self) -> io::Result<()> { - let result = remove_dir_all(self.path()); - - // Prevent the Drop impl from removing the dir a second time. - self.path = None; - - result - } -} - -impl AsRef<Path> for TempDir { - fn as_ref(&self) -> &Path { - self.path() - } -} - -impl fmt::Debug for TempDir { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.debug_struct("TempDir") - .field("path", &self.path()) - .finish() - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - // Path is `None` if `close()` or `into_path()` has been called. - if let Some(ref p) = self.path { - let _ = remove_dir_all(p); - } - } -} - -// the tests for this module need to change the path using change_dir, -// and this doesn't play nicely with other tests so these unit tests are located -// in src/test/run-pass/tempfile.rs diff -Nru cargo-0.25.0/vendor/tempdir-0.3.6/tests/smoke.rs cargo-0.26.0/vendor/tempdir-0.3.6/tests/smoke.rs --- cargo-0.25.0/vendor/tempdir-0.3.6/tests/smoke.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.6/tests/smoke.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,229 +0,0 @@ -// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or -// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license -// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -extern crate tempdir; - -use std::env; -use std::fs; -use std::path::Path; -use std::sync::mpsc::channel; -use std::thread; - -use tempdir::TempDir; - -macro_rules! t { - ($e:expr) => (match $e { Ok(n) => n, Err(e) => panic!("error: {}", e) }) -} - -trait PathExt { - fn exists(&self) -> bool; - fn is_dir(&self) -> bool; -} - -impl PathExt for Path { - fn exists(&self) -> bool { fs::metadata(self).is_ok() } - fn is_dir(&self) -> bool { - fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false) - } -} - -fn test_tempdir() { - let path = { - let p = t!(TempDir::new_in(&Path::new("."), "foobar")); - let p = p.path(); - assert!(p.to_str().unwrap().contains("foobar")); - p.to_path_buf() - }; - assert!(!path.exists()); -} - -fn test_rm_tempdir() { - let (tx, rx) = channel(); - let f = move|| -> () { - let tmp = t!(TempDir::new("test_rm_tempdir")); - tx.send(tmp.path().to_path_buf()).unwrap(); - panic!("panic to unwind past `tmp`"); - }; - let _ = thread::spawn(f).join(); - let path = rx.recv().unwrap(); - assert!(!path.exists()); - - let tmp = t!(TempDir::new("test_rm_tempdir")); - let path = tmp.path().to_path_buf(); - let f = move|| -> () { - let _tmp = tmp; - panic!("panic to unwind past `tmp`"); - }; - let _ = thread::spawn(f).join(); - assert!(!path.exists()); - - let path; - { - let f = move || { - t!(TempDir::new("test_rm_tempdir")) - }; - - let tmp = thread::spawn(f).join().unwrap(); - path = tmp.path().to_path_buf(); - assert!(path.exists()); - } - assert!(!path.exists()); - - let path; - { - let tmp = t!(TempDir::new("test_rm_tempdir")); - path = tmp.into_path(); - } - assert!(path.exists()); - t!(fs::remove_dir_all(&path)); - assert!(!path.exists()); -} - -fn test_rm_tempdir_close() { - let (tx, rx) = channel(); - let f = move|| -> () { - let tmp = t!(TempDir::new("test_rm_tempdir")); - tx.send(tmp.path().to_path_buf()).unwrap(); - t!(tmp.close()); - panic!("panic when unwinding past `tmp`"); - }; - let _ = thread::spawn(f).join(); - let path = rx.recv().unwrap(); - assert!(!path.exists()); - - let tmp = t!(TempDir::new("test_rm_tempdir")); - let path = tmp.path().to_path_buf(); - let f = move|| -> () { - let tmp = tmp; - t!(tmp.close()); - panic!("panic when unwinding past `tmp`"); - }; - let _ = thread::spawn(f).join(); - assert!(!path.exists()); - - let path; - { - let f = move || { - t!(TempDir::new("test_rm_tempdir")) - }; - - let tmp = thread::spawn(f).join().unwrap(); - path = tmp.path().to_path_buf(); - assert!(path.exists()); - t!(tmp.close()); - } - assert!(!path.exists()); - - let path; - { - let tmp = t!(TempDir::new("test_rm_tempdir")); - path = tmp.into_path(); - } - assert!(path.exists()); - t!(fs::remove_dir_all(&path)); - assert!(!path.exists()); -} - -// Ideally these would be in std::os but then core would need -// to depend on std -fn recursive_mkdir_rel() { - let path = Path::new("frob"); - let cwd = env::current_dir().unwrap(); - println!("recursive_mkdir_rel: Making: {} in cwd {} [{}]", path.display(), - cwd.display(), path.exists()); - t!(fs::create_dir(&path)); - assert!(path.is_dir()); - t!(fs::create_dir_all(&path)); - assert!(path.is_dir()); -} - -fn recursive_mkdir_dot() { - let dot = Path::new("."); - t!(fs::create_dir_all(&dot)); - let dotdot = Path::new(".."); - t!(fs::create_dir_all(&dotdot)); -} - -fn recursive_mkdir_rel_2() { - let path = Path::new("./frob/baz"); - let cwd = env::current_dir().unwrap(); - println!("recursive_mkdir_rel_2: Making: {} in cwd {} [{}]", path.display(), - cwd.display(), path.exists()); - t!(fs::create_dir_all(&path)); - assert!(path.is_dir()); - assert!(path.parent().unwrap().is_dir()); - let path2 = Path::new("quux/blat"); - println!("recursive_mkdir_rel_2: Making: {} in cwd {}", path2.display(), - cwd.display()); - t!(fs::create_dir("quux")); - t!(fs::create_dir_all(&path2)); - assert!(path2.is_dir()); - assert!(path2.parent().unwrap().is_dir()); -} - -// Ideally this would be in core, but needs TempFile -pub fn test_remove_dir_all_ok() { - let tmpdir = t!(TempDir::new("test")); - let tmpdir = tmpdir.path(); - let root = tmpdir.join("foo"); - - println!("making {}", root.display()); - t!(fs::create_dir(&root)); - t!(fs::create_dir(&root.join("foo"))); - t!(fs::create_dir(&root.join("foo").join("bar"))); - t!(fs::create_dir(&root.join("foo").join("bar").join("blat"))); - t!(fs::remove_dir_all(&root)); - assert!(!root.exists()); - assert!(!root.join("bar").exists()); - assert!(!root.join("bar").join("blat").exists()); -} - -pub fn dont_double_panic() { - let r: Result<(), _> = thread::spawn(move|| { - let tmpdir = TempDir::new("test").unwrap(); - // Remove the temporary directory so that TempDir sees - // an error on drop - t!(fs::remove_dir(tmpdir.path())); - // Panic. If TempDir panics *again* due to the rmdir - // error then the process will abort. - panic!(); - }).join(); - assert!(r.is_err()); -} - -fn in_tmpdir<F>(f: F) where F: FnOnce() { - let tmpdir = t!(TempDir::new("test")); - assert!(env::set_current_dir(tmpdir.path()).is_ok()); - - f(); -} - -pub fn pass_as_asref_path() { - let tempdir = t!(TempDir::new("test")); - takes_asref_path(&tempdir); - - fn takes_asref_path<T: AsRef<Path>>(path: T) { - let path = path.as_ref(); - assert!(path.exists()); - } -} - -#[test] -fn main() { - in_tmpdir(test_tempdir); - in_tmpdir(test_rm_tempdir); - in_tmpdir(test_rm_tempdir_close); - in_tmpdir(recursive_mkdir_rel); - in_tmpdir(recursive_mkdir_dot); - in_tmpdir(recursive_mkdir_rel_2); - in_tmpdir(test_remove_dir_all_ok); - in_tmpdir(dont_double_panic); - in_tmpdir(pass_as_asref_path); -} diff -Nru cargo-0.25.0/vendor/tempdir-0.3.6/.travis.yml cargo-0.26.0/vendor/tempdir-0.3.6/.travis.yml --- cargo-0.25.0/vendor/tempdir-0.3.6/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.6/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -notifications: - email: - on_success: never - -language: rust -sudo: false - -matrix: - include: - - rust: stable - - os: osx - - rust: beta - - rust: nightly - - - rust: nightly - before_script: - - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH - script: - - cargo doc --no-deps --all-features - after_success: - - travis-cargo --only nightly doc-upload - -env: - global: - secure: "iENCKNKfyveEXk+OofJDnxGfeVnxHovvLsrtl7eUBev6YGIIlUISZliyCvBrSkZKTeLfdDEP+Q5Mv9tVOMAx/FNiKB9V07WFDahD6xvz+qd3k790gdzgy+0LcNKskBVzDK62zCofvknGVbQa9f5iimhu+wKs9bb+WCxicVWmeRo=" - -notifications: - email: - on_success: never diff -Nru cargo-0.25.0/vendor/tempdir-0.3.7/appveyor.yml cargo-0.26.0/vendor/tempdir-0.3.7/appveyor.yml --- cargo-0.25.0/vendor/tempdir-0.3.7/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.7/appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,17 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo test --verbose diff -Nru cargo-0.25.0/vendor/tempdir-0.3.7/.cargo-checksum.json cargo-0.26.0/vendor/tempdir-0.3.7/.cargo-checksum.json --- cargo-0.25.0/vendor/tempdir-0.3.7/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.7/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/tempdir-0.3.7/Cargo.toml cargo-0.26.0/vendor/tempdir-0.3.7/Cargo.toml --- cargo-0.25.0/vendor/tempdir-0.3.7/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.7/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,34 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "tempdir" +version = "0.3.7" +authors = ["The Rust Project Developers"] +description = "A library for managing a temporary directory and deleting all contents when it's\ndropped.\n" +homepage = "https://github.com/rust-lang/tempdir" +documentation = "https://doc.rust-lang.org/tempdir" +readme = "README.md" +keywords = ["fs", "file", "filesystem"] +categories = ["filesystem"] +license = "MIT/Apache-2.0" +repository = "https://github.com/rust-lang/tempdir" +[dependencies.rand] +version = "0.4" + +[dependencies.remove_dir_all] +version = "0.5" +[badges.appveyor] +repository = "rust-lang-libs/tempdir" + +[badges.travis-ci] +repository = "rust-lang-nursery/tempdir" diff -Nru cargo-0.25.0/vendor/tempdir-0.3.7/LICENSE-APACHE cargo-0.26.0/vendor/tempdir-0.3.7/LICENSE-APACHE --- cargo-0.25.0/vendor/tempdir-0.3.7/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.7/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/tempdir-0.3.7/LICENSE-MIT cargo-0.26.0/vendor/tempdir-0.3.7/LICENSE-MIT --- cargo-0.25.0/vendor/tempdir-0.3.7/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.7/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/tempdir-0.3.7/README.md cargo-0.26.0/vendor/tempdir-0.3.7/README.md --- cargo-0.25.0/vendor/tempdir-0.3.7/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.7/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,62 @@ +tempdir +======= + +A Rust library for creating a temporary directory and deleting its entire +contents when the directory is dropped. + +[![Build Status](https://travis-ci.org/rust-lang-nursery/tempdir.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/tempdir) +[![Build status](https://ci.appveyor.com/api/projects/status/2mp24396db5t4hul/branch/master?svg=true)](https://ci.appveyor.com/project/rust-lang-libs/tempdir/branch/master) + +[Documentation](https://doc.rust-lang.org/tempdir) + +## Deprecation Note + +The `tempdir` crate is being merged into [`tempfile`](https://github.com/Stebalien/tempfile). Please see [this issue](https://github.com/Stebalien/tempfile/issues/43) to track progress and direct new issues and pull requests to `tempfile`. + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +tempdir = "0.3" +``` + +and this to your crate root: + +```rust +extern crate tempdir; +``` + +## Example + +This sample method does the following: + +1. Create a temporary directory in the default location with the given prefix. +2. Determine a file path in the directory and print it out. +3. Create a file inside the temp folder. +4. Write to the file and sync it to disk. +5. Close the directory, deleting the contents in the process. + +```rust +use std::io::{self, Write}; +use std::fs::File; +use tempdir::TempDir; + +fn write_temp_folder_with_files() -> io::Result<()> { + let dir = TempDir::new("my_directory_prefix")?; + let file_path = dir.path().join("foo.txt"); + println!("{:?}", file_path); + + let mut f = File::create(file_path)?; + f.write_all(b"Hello, world!")?; + f.sync_all()?; + dir.close()?; + + Ok(()) +} +``` + +**Note:** Closing the directory is actually optional, as it would be done on +drop. The benefit of closing here is that it allows possible errors to be +handled. diff -Nru cargo-0.25.0/vendor/tempdir-0.3.7/src/lib.rs cargo-0.26.0/vendor/tempdir-0.3.7/src/lib.rs --- cargo-0.25.0/vendor/tempdir-0.3.7/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.7/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,360 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", + html_favicon_url = "https://www.rust-lang.org/favicon.ico", + html_root_url = "https://docs.rs/tempdir/0.3.7")] +#![cfg_attr(test, deny(warnings))] + +//! Temporary directories of files. +//! +//! The [`TempDir`] type creates a directory on the file system that +//! is deleted once it goes out of scope. At construction, the +//! `TempDir` creates a new directory with a randomly generated name +//! and a prefix of your choosing. +//! +//! [`TempDir`]: struct.TempDir.html +//! [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html +//! +//! # Examples +//! +//! ``` +//! extern crate tempdir; +//! +//! use std::fs::File; +//! use std::io::{self, Write}; +//! use tempdir::TempDir; +//! +//! fn main() { +//! if let Err(_) = run() { +//! ::std::process::exit(1); +//! } +//! } +//! +//! fn run() -> Result<(), io::Error> { +//! // Create a directory inside of `std::env::temp_dir()`, named with +//! // the prefix "example". +//! let tmp_dir = TempDir::new("example")?; +//! let file_path = tmp_dir.path().join("my-temporary-note.txt"); +//! let mut tmp_file = File::create(file_path)?; +//! writeln!(tmp_file, "Brian was here. Briefly.")?; +//! +//! // By closing the `TempDir` explicitly, we can check that it has +//! // been deleted successfully. If we don't close it explicitly, +//! // the directory will still be deleted when `tmp_dir` goes out +//! // of scope, but we won't know whether deleting the directory +//! // succeeded. +//! drop(tmp_file); +//! tmp_dir.close()?; +//! Ok(()) +//! } +//! ``` + +extern crate rand; +extern crate remove_dir_all; + +use std::env; +use std::io::{self, Error, ErrorKind}; +use std::fmt; +use std::fs; +use std::path::{self, PathBuf, Path}; +use rand::{thread_rng, Rng}; +use remove_dir_all::remove_dir_all; + +/// A directory in the filesystem that is automatically deleted when +/// it goes out of scope. +/// +/// The [`TempDir`] type creates a directory on the file system that +/// is deleted once it goes out of scope. At construction, the +/// `TempDir` creates a new directory with a randomly generated name, +/// and with a prefix of your choosing. +/// +/// The default constructor, [`TempDir::new`], creates directories in +/// the location returned by [`std::env::temp_dir()`], but `TempDir` +/// can be configured to manage a temporary directory in any location +/// by constructing with [`TempDir::new_in`]. +/// +/// After creating a `TempDir`, work with the file system by doing +/// standard [`std::fs`] file system operations on its [`Path`], +/// which can be retrieved with [`TempDir::path`]. Once the `TempDir` +/// value is dropped, the directory at the path will be deleted, along +/// with any files and directories it contains. It is your responsibility +/// to ensure that no further file system operations are attempted +/// inside the temporary directory once it has been deleted. +/// +/// Various platform-specific conditions may cause `TempDir` to fail +/// to delete the underlying directory. It's important to ensure that +/// handles (like [`File`] and [`ReadDir`]) to files inside the +/// directory are dropped before the `TempDir` goes out of scope. The +/// `TempDir` destructor will silently ignore any errors in deleting +/// the directory; to instead handle errors call [`TempDir::close`]. +/// +/// Note that if the program exits before the `TempDir` destructor is +/// run, such as via [`std::process::exit`], by segfaulting, or by +/// receiving a signal like `SIGINT`, then the temporary directory +/// will not be deleted. +/// +/// [`File`]: http://doc.rust-lang.org/std/fs/struct.File.html +/// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html +/// [`ReadDir`]: http://doc.rust-lang.org/std/fs/struct.ReadDir.html +/// [`TempDir::close`]: struct.TempDir.html#method.close +/// [`TempDir::new`]: struct.TempDir.html#method.new +/// [`TempDir::new_in`]: struct.TempDir.html#method.new_in +/// [`TempDir::path`]: struct.TempDir.html#method.path +/// [`TempDir`]: struct.TempDir.html +/// [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html +/// [`std::fs`]: http://doc.rust-lang.org/std/fs/index.html +/// [`std::process::exit`]: http://doc.rust-lang.org/std/process/fn.exit.html +pub struct TempDir { + path: Option<PathBuf>, +} + +// How many times should we (re)try finding an unused random name? It should be +// enough that an attacker will run out of luck before we run out of patience. +const NUM_RETRIES: u32 = 1 << 31; +// How many characters should we include in a random file name? It needs to +// be enough to dissuade an attacker from trying to preemptively create names +// of that length, but not so huge that we unnecessarily drain the random number +// generator of entropy. +const NUM_RAND_CHARS: usize = 12; + +impl TempDir { + /// Attempts to make a temporary directory inside of `env::temp_dir()` whose + /// name will have the prefix, `prefix`. The directory and + /// everything inside it will be automatically deleted once the + /// returned `TempDir` is destroyed. + /// + /// # Errors + /// + /// If the directory can not be created, `Err` is returned. + /// + /// # Examples + /// + /// ``` + /// use std::fs::File; + /// use std::io::Write; + /// use tempdir::TempDir; + /// + /// # use std::io; + /// # fn run() -> Result<(), io::Error> { + /// // Create a directory inside of `std::env::temp_dir()`, named with + /// // the prefix, "example". + /// let tmp_dir = TempDir::new("example")?; + /// let file_path = tmp_dir.path().join("my-temporary-note.txt"); + /// let mut tmp_file = File::create(file_path)?; + /// writeln!(tmp_file, "Brian was here. Briefly.")?; + /// + /// // `tmp_dir` goes out of scope, the directory as well as + /// // `tmp_file` will be deleted here. + /// # Ok(()) + /// # } + /// ``` + pub fn new(prefix: &str) -> io::Result<TempDir> { + TempDir::new_in(&env::temp_dir(), prefix) + } + + /// Attempts to make a temporary directory inside of `tmpdir` + /// whose name will have the prefix `prefix`. The directory and + /// everything inside it will be automatically deleted once the + /// returned `TempDir` is destroyed. + /// + /// # Errors + /// + /// If the directory can not be created, `Err` is returned. + /// + /// # Examples + /// + /// ``` + /// use std::fs::{self, File}; + /// use std::io::Write; + /// use tempdir::TempDir; + /// + /// # use std::io; + /// # fn run() -> Result<(), io::Error> { + /// // Create a directory inside of the current directory, named with + /// // the prefix, "example". + /// let tmp_dir = TempDir::new_in(".", "example")?; + /// let file_path = tmp_dir.path().join("my-temporary-note.txt"); + /// let mut tmp_file = File::create(file_path)?; + /// writeln!(tmp_file, "Brian was here. Briefly.")?; + /// # Ok(()) + /// # } + /// ``` + pub fn new_in<P: AsRef<Path>>(tmpdir: P, prefix: &str) -> io::Result<TempDir> { + let storage; + let mut tmpdir = tmpdir.as_ref(); + if !tmpdir.is_absolute() { + let cur_dir = env::current_dir()?; + storage = cur_dir.join(tmpdir); + tmpdir = &storage; + // return TempDir::new_in(&cur_dir.join(tmpdir), prefix); + } + + let mut rng = thread_rng(); + for _ in 0..NUM_RETRIES { + let suffix: String = rng.gen_ascii_chars().take(NUM_RAND_CHARS).collect(); + let leaf = if !prefix.is_empty() { + format!("{}.{}", prefix, suffix) + } else { + // If we're given an empty string for a prefix, then creating a + // directory starting with "." would lead to it being + // semi-invisible on some systems. + suffix + }; + let path = tmpdir.join(&leaf); + match fs::create_dir(&path) { + Ok(_) => return Ok(TempDir { path: Some(path) }), + Err(ref e) if e.kind() == ErrorKind::AlreadyExists => {} + Err(e) => return Err(e), + } + } + + Err(Error::new(ErrorKind::AlreadyExists, + "too many temporary directories already exist")) + } + + /// Accesses the [`Path`] to the temporary directory. + /// + /// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html + /// + /// # Examples + /// + /// ``` + /// use tempdir::TempDir; + /// + /// # use std::io; + /// # fn run() -> Result<(), io::Error> { + /// let tmp_path; + /// + /// { + /// let tmp_dir = TempDir::new("example")?; + /// tmp_path = tmp_dir.path().to_owned(); + /// + /// // Check that the temp directory actually exists. + /// assert!(tmp_path.exists()); + /// + /// // End of `tmp_dir` scope, directory will be deleted + /// } + /// + /// // Temp directory should be deleted by now + /// assert_eq!(tmp_path.exists(), false); + /// # Ok(()) + /// # } + /// ``` + pub fn path(&self) -> &path::Path { + self.path.as_ref().unwrap() + } + + /// Unwraps the [`Path`] contained in the `TempDir` and + /// returns it. This destroys the `TempDir` without deleting the + /// directory represented by the returned `Path`. + /// + /// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html + /// + /// # Examples + /// + /// ``` + /// use std::fs; + /// use tempdir::TempDir; + /// + /// # use std::io; + /// # fn run() -> Result<(), io::Error> { + /// let tmp_dir = TempDir::new("example")?; + /// + /// // Convert `tmp_dir` into a `Path`, destroying the `TempDir` + /// // without deleting the directory. + /// let tmp_path = tmp_dir.into_path(); + /// + /// // Delete the temporary directory ourselves. + /// fs::remove_dir_all(tmp_path)?; + /// # Ok(()) + /// # } + /// ``` + pub fn into_path(mut self) -> PathBuf { + self.path.take().unwrap() + } + + /// Closes and removes the temporary directory, returing a `Result`. + /// + /// Although `TempDir` removes the directory on drop, in the destructor + /// any errors are ignored. To detect errors cleaning up the temporary + /// directory, call `close` instead. + /// + /// # Errors + /// + /// This function may return a variety of [`std::io::Error`]s that result from deleting + /// the files and directories contained with the temporary directory, + /// as well as from deleting the temporary directory itself. These errors + /// may be platform specific. + /// + /// [`std::io::Error`]: http://doc.rust-lang.org/std/io/struct.Error.html + /// + /// # Examples + /// + /// ``` + /// use std::fs::File; + /// use std::io::Write; + /// use tempdir::TempDir; + /// + /// # use std::io; + /// # fn run() -> Result<(), io::Error> { + /// // Create a directory inside of `std::env::temp_dir()`, named with + /// // the prefix, "example". + /// let tmp_dir = TempDir::new("example")?; + /// let file_path = tmp_dir.path().join("my-temporary-note.txt"); + /// let mut tmp_file = File::create(file_path)?; + /// writeln!(tmp_file, "Brian was here. Briefly.")?; + /// + /// // By closing the `TempDir` explicitly we can check that it has + /// // been deleted successfully. If we don't close it explicitly, + /// // the directory will still be deleted when `tmp_dir` goes out + /// // of scope, but we won't know whether deleting the directory + /// // succeeded. + /// drop(tmp_file); + /// tmp_dir.close()?; + /// # Ok(()) + /// # } + /// ``` + pub fn close(mut self) -> io::Result<()> { + let result = remove_dir_all(self.path()); + + // Prevent the Drop impl from removing the dir a second time. + self.path = None; + + result + } +} + +impl AsRef<Path> for TempDir { + fn as_ref(&self) -> &Path { + self.path() + } +} + +impl fmt::Debug for TempDir { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_struct("TempDir") + .field("path", &self.path()) + .finish() + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + // Path is `None` if `close()` or `into_path()` has been called. + if let Some(ref p) = self.path { + let _ = remove_dir_all(p); + } + } +} + +// the tests for this module need to change the path using change_dir, +// and this doesn't play nicely with other tests so these unit tests are located +// in src/test/run-pass/tempfile.rs diff -Nru cargo-0.25.0/vendor/tempdir-0.3.7/tests/smoke.rs cargo-0.26.0/vendor/tempdir-0.3.7/tests/smoke.rs --- cargo-0.25.0/vendor/tempdir-0.3.7/tests/smoke.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.7/tests/smoke.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,229 @@ +// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +extern crate tempdir; + +use std::env; +use std::fs; +use std::path::Path; +use std::sync::mpsc::channel; +use std::thread; + +use tempdir::TempDir; + +macro_rules! t { + ($e:expr) => (match $e { Ok(n) => n, Err(e) => panic!("error: {}", e) }) +} + +trait PathExt { + fn exists(&self) -> bool; + fn is_dir(&self) -> bool; +} + +impl PathExt for Path { + fn exists(&self) -> bool { fs::metadata(self).is_ok() } + fn is_dir(&self) -> bool { + fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false) + } +} + +fn test_tempdir() { + let path = { + let p = t!(TempDir::new_in(&Path::new("."), "foobar")); + let p = p.path(); + assert!(p.to_str().unwrap().contains("foobar")); + p.to_path_buf() + }; + assert!(!path.exists()); +} + +fn test_rm_tempdir() { + let (tx, rx) = channel(); + let f = move|| -> () { + let tmp = t!(TempDir::new("test_rm_tempdir")); + tx.send(tmp.path().to_path_buf()).unwrap(); + panic!("panic to unwind past `tmp`"); + }; + let _ = thread::spawn(f).join(); + let path = rx.recv().unwrap(); + assert!(!path.exists()); + + let tmp = t!(TempDir::new("test_rm_tempdir")); + let path = tmp.path().to_path_buf(); + let f = move|| -> () { + let _tmp = tmp; + panic!("panic to unwind past `tmp`"); + }; + let _ = thread::spawn(f).join(); + assert!(!path.exists()); + + let path; + { + let f = move || { + t!(TempDir::new("test_rm_tempdir")) + }; + + let tmp = thread::spawn(f).join().unwrap(); + path = tmp.path().to_path_buf(); + assert!(path.exists()); + } + assert!(!path.exists()); + + let path; + { + let tmp = t!(TempDir::new("test_rm_tempdir")); + path = tmp.into_path(); + } + assert!(path.exists()); + t!(fs::remove_dir_all(&path)); + assert!(!path.exists()); +} + +fn test_rm_tempdir_close() { + let (tx, rx) = channel(); + let f = move|| -> () { + let tmp = t!(TempDir::new("test_rm_tempdir")); + tx.send(tmp.path().to_path_buf()).unwrap(); + t!(tmp.close()); + panic!("panic when unwinding past `tmp`"); + }; + let _ = thread::spawn(f).join(); + let path = rx.recv().unwrap(); + assert!(!path.exists()); + + let tmp = t!(TempDir::new("test_rm_tempdir")); + let path = tmp.path().to_path_buf(); + let f = move|| -> () { + let tmp = tmp; + t!(tmp.close()); + panic!("panic when unwinding past `tmp`"); + }; + let _ = thread::spawn(f).join(); + assert!(!path.exists()); + + let path; + { + let f = move || { + t!(TempDir::new("test_rm_tempdir")) + }; + + let tmp = thread::spawn(f).join().unwrap(); + path = tmp.path().to_path_buf(); + assert!(path.exists()); + t!(tmp.close()); + } + assert!(!path.exists()); + + let path; + { + let tmp = t!(TempDir::new("test_rm_tempdir")); + path = tmp.into_path(); + } + assert!(path.exists()); + t!(fs::remove_dir_all(&path)); + assert!(!path.exists()); +} + +// Ideally these would be in std::os but then core would need +// to depend on std +fn recursive_mkdir_rel() { + let path = Path::new("frob"); + let cwd = env::current_dir().unwrap(); + println!("recursive_mkdir_rel: Making: {} in cwd {} [{}]", path.display(), + cwd.display(), path.exists()); + t!(fs::create_dir(&path)); + assert!(path.is_dir()); + t!(fs::create_dir_all(&path)); + assert!(path.is_dir()); +} + +fn recursive_mkdir_dot() { + let dot = Path::new("."); + t!(fs::create_dir_all(&dot)); + let dotdot = Path::new(".."); + t!(fs::create_dir_all(&dotdot)); +} + +fn recursive_mkdir_rel_2() { + let path = Path::new("./frob/baz"); + let cwd = env::current_dir().unwrap(); + println!("recursive_mkdir_rel_2: Making: {} in cwd {} [{}]", path.display(), + cwd.display(), path.exists()); + t!(fs::create_dir_all(&path)); + assert!(path.is_dir()); + assert!(path.parent().unwrap().is_dir()); + let path2 = Path::new("quux/blat"); + println!("recursive_mkdir_rel_2: Making: {} in cwd {}", path2.display(), + cwd.display()); + t!(fs::create_dir("quux")); + t!(fs::create_dir_all(&path2)); + assert!(path2.is_dir()); + assert!(path2.parent().unwrap().is_dir()); +} + +// Ideally this would be in core, but needs TempFile +pub fn test_remove_dir_all_ok() { + let tmpdir = t!(TempDir::new("test")); + let tmpdir = tmpdir.path(); + let root = tmpdir.join("foo"); + + println!("making {}", root.display()); + t!(fs::create_dir(&root)); + t!(fs::create_dir(&root.join("foo"))); + t!(fs::create_dir(&root.join("foo").join("bar"))); + t!(fs::create_dir(&root.join("foo").join("bar").join("blat"))); + t!(fs::remove_dir_all(&root)); + assert!(!root.exists()); + assert!(!root.join("bar").exists()); + assert!(!root.join("bar").join("blat").exists()); +} + +pub fn dont_double_panic() { + let r: Result<(), _> = thread::spawn(move|| { + let tmpdir = TempDir::new("test").unwrap(); + // Remove the temporary directory so that TempDir sees + // an error on drop + t!(fs::remove_dir(tmpdir.path())); + // Panic. If TempDir panics *again* due to the rmdir + // error then the process will abort. + panic!(); + }).join(); + assert!(r.is_err()); +} + +fn in_tmpdir<F>(f: F) where F: FnOnce() { + let tmpdir = t!(TempDir::new("test")); + assert!(env::set_current_dir(tmpdir.path()).is_ok()); + + f(); +} + +pub fn pass_as_asref_path() { + let tempdir = t!(TempDir::new("test")); + takes_asref_path(&tempdir); + + fn takes_asref_path<T: AsRef<Path>>(path: T) { + let path = path.as_ref(); + assert!(path.exists()); + } +} + +#[test] +fn main() { + in_tmpdir(test_tempdir); + in_tmpdir(test_rm_tempdir); + in_tmpdir(test_rm_tempdir_close); + in_tmpdir(recursive_mkdir_rel); + in_tmpdir(recursive_mkdir_dot); + in_tmpdir(recursive_mkdir_rel_2); + in_tmpdir(test_remove_dir_all_ok); + in_tmpdir(dont_double_panic); + in_tmpdir(pass_as_asref_path); +} diff -Nru cargo-0.25.0/vendor/tempdir-0.3.7/.travis.yml cargo-0.26.0/vendor/tempdir-0.3.7/.travis.yml --- cargo-0.25.0/vendor/tempdir-0.3.7/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/tempdir-0.3.7/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,29 @@ +notifications: + email: + on_success: never + +language: rust +sudo: false + +matrix: + include: + - rust: stable + - os: osx + - rust: beta + - rust: nightly + + - rust: nightly + before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH + script: + - cargo doc --no-deps --all-features + after_success: + - travis-cargo --only nightly doc-upload + +env: + global: + secure: "iENCKNKfyveEXk+OofJDnxGfeVnxHovvLsrtl7eUBev6YGIIlUISZliyCvBrSkZKTeLfdDEP+Q5Mv9tVOMAx/FNiKB9V07WFDahD6xvz+qd3k790gdzgy+0LcNKskBVzDK62zCofvknGVbQa9f5iimhu+wKs9bb+WCxicVWmeRo=" + +notifications: + email: + on_success: never diff -Nru cargo-0.25.0/vendor/termcolor-0.3.5/.cargo-checksum.json cargo-0.26.0/vendor/termcolor-0.3.5/.cargo-checksum.json --- cargo-0.25.0/vendor/termcolor-0.3.5/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.5/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"56c456352e44f9f91f774ddeeed27c1ec60a2455ed66d692059acfb1d731bda1"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/termcolor-0.3.5/Cargo.toml cargo-0.26.0/vendor/termcolor-0.3.5/Cargo.toml --- cargo-0.25.0/vendor/termcolor-0.3.5/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.5/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "termcolor" -version = "0.3.5" -authors = ["Andrew Gallant <jamslam@gmail.com>"] -description = "A simple cross platform library for writing colored text to a terminal.\n" -homepage = "https://github.com/BurntSushi/ripgrep/tree/master/termcolor" -documentation = "https://docs.rs/termcolor" -readme = "README.md" -keywords = ["windows", "win", "color", "ansi", "console"] -license = "Unlicense/MIT" -repository = "https://github.com/BurntSushi/ripgrep/tree/master/termcolor" - -[lib] -name = "termcolor" -bench = false -[target."cfg(windows)".dependencies.wincolor] -version = "0.1.6" diff -Nru cargo-0.25.0/vendor/termcolor-0.3.5/COPYING cargo-0.26.0/vendor/termcolor-0.3.5/COPYING --- cargo-0.25.0/vendor/termcolor-0.3.5/COPYING 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.5/COPYING 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -This project is dual-licensed under the Unlicense and MIT licenses. - -You may use this code under the terms of either license. diff -Nru cargo-0.25.0/vendor/termcolor-0.3.5/LICENSE-MIT cargo-0.26.0/vendor/termcolor-0.3.5/LICENSE-MIT --- cargo-0.25.0/vendor/termcolor-0.3.5/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.5/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Andrew Gallant - -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. diff -Nru cargo-0.25.0/vendor/termcolor-0.3.5/README.md cargo-0.26.0/vendor/termcolor-0.3.5/README.md --- cargo-0.25.0/vendor/termcolor-0.3.5/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.5/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,86 +0,0 @@ -termcolor -========= -A simple cross platform library for writing colored text to a terminal. This -library writes colored text either using standard ANSI escape sequences or -by interacting with the Windows console. Several convenient abstractions -are provided for use in single-threaded or multi-threaded command line -applications. - -[![Linux build status](https://api.travis-ci.org/BurntSushi/ripgrep.png)](https://travis-ci.org/BurntSushi/ripgrep) -[![Windows build status](https://ci.appveyor.com/api/projects/status/github/BurntSushi/ripgrep?svg=true)](https://ci.appveyor.com/project/BurntSushi/ripgrep) -[![](https://img.shields.io/crates/v/termcolor.svg)](https://crates.io/crates/termcolor) - -Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). - -### Documentation - -[https://docs.rs/termcolor](https://docs.rs/termcolor) - -### Usage - -Add this to your `Cargo.toml`: - -```toml -[dependencies] -termcolor = "0.3" -``` - -and this to your crate root: - -```rust -extern crate termcolor; -``` - -### Organization - -The `WriteColor` trait extends the `io::Write` trait with methods for setting -colors or resetting them. - -`StandardStream` and `StandardStreamLock` both satisfy `WriteColor` and are -analogous to `std::io::Stdout` and `std::io::StdoutLock`, or `std::io::Stderr` -and `std::io::StderrLock`. - -`Buffer` is an in memory buffer that supports colored text. In a parallel -program, each thread might write to its own buffer. A buffer can be printed to -stdout or stderr using a `BufferWriter`. The advantage of this design is that -each thread can work in parallel on a buffer without having to synchronize -access to global resources such as the Windows console. Moreover, this design -also prevents interleaving of buffer output. - -`Ansi` and `NoColor` both satisfy `WriteColor` for arbitrary implementors of -`io::Write`. These types are useful when you know exactly what you need. An -analogous type for the Windows console is not provided since it cannot exist. - -### Example: using `StandardStream` - -The `StandardStream` type in this crate works similarly to `std::io::Stdout`, -except it is augmented with methods for coloring by the `WriteColor` trait. -For example, to write some green text: - -```rust -use std::io::Write; -use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; - -let mut stdout = StandardStream::stdout(ColorChoice::Always); -stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?; -writeln!(&mut stdout, "green text!")?; -``` - -### Example: using `BufferWriter` - -A `BufferWriter` can create buffers and write buffers to stdout or stderr. It -does *not* implement `io::Write` or `WriteColor` itself. Instead, `Buffer` -implements `io::Write` and `io::WriteColor`. - -This example shows how to print some green text to stderr. - -```rust -use std::io::Write; -use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor}; - -let mut bufwtr = BufferWriter::stderr(ColorChoice::Always); -let mut buffer = bufwtr.buffer(); -buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?; -writeln!(&mut buffer, "green text!")?; -bufwtr.print(&buffer)?; -``` diff -Nru cargo-0.25.0/vendor/termcolor-0.3.5/src/lib.rs cargo-0.26.0/vendor/termcolor-0.3.5/src/lib.rs --- cargo-0.25.0/vendor/termcolor-0.3.5/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.5/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1697 +0,0 @@ -/*! -This crate provides a cross platform abstraction for writing colored text to -a terminal. Colors are written using either ANSI escape sequences or by -communicating with a Windows console. Much of this API was motivated by use -inside command line applications, where colors or styles can be configured -by the end user and/or the environment. - -This crate also provides platform independent support for writing colored text -to an in memory buffer. While this is easy to do with ANSI escape sequences -(because they are in the buffer themselves), it is trickier to do with the -Windows console API, which requires synchronous communication. - -# Organization - -The `WriteColor` trait extends the `io::Write` trait with methods for setting -colors or resetting them. - -`StandardStream` and `StandardStreamLock` both satisfy `WriteColor` and are -analogous to `std::io::Stdout` and `std::io::StdoutLock`, or `std::io::Stderr` -and `std::io::StderrLock`. - -`Buffer` is an in memory buffer that supports colored text. In a parallel -program, each thread might write to its own buffer. A buffer can be printed to -using a `BufferWriter`. The advantage of this design is that each thread can -work in parallel on a buffer without having to synchronize access to global -resources such as the Windows console. Moreover, this design also prevents -interleaving of buffer output. - -`Ansi` and `NoColor` both satisfy `WriteColor` for arbitrary implementors of -`io::Write`. These types are useful when you know exactly what you need. An -analogous type for the Windows console is not provided since it cannot exist. - -# Example: using `StandardStream` - -The `StandardStream` type in this crate works similarly to `std::io::Stdout`, -except it is augmented with methods for coloring by the `WriteColor` trait. -For example, to write some green text: - -```rust,no_run -# fn test() -> Result<(), Box<::std::error::Error>> { -use std::io::Write; -use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; - -let mut stdout = StandardStream::stdout(ColorChoice::Always); -stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?; -writeln!(&mut stdout, "green text!")?; -# Ok(()) } -``` - -# Example: using `BufferWriter` - -A `BufferWriter` can create buffers and write buffers to stdout or stderr. It -does *not* implement `io::Write` or `WriteColor` itself. Instead, `Buffer` -implements `io::Write` and `io::WriteColor`. - -This example shows how to print some green text to stderr. - -```rust,no_run -# fn test() -> Result<(), Box<::std::error::Error>> { -use std::io::Write; -use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor}; - -let mut bufwtr = BufferWriter::stderr(ColorChoice::Always); -let mut buffer = bufwtr.buffer(); -buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?; -writeln!(&mut buffer, "green text!")?; -bufwtr.print(&buffer)?; -# Ok(()) } -``` -*/ - -#![deny(missing_docs)] - -#[cfg(windows)] -extern crate wincolor; - -use std::env; -use std::error; -use std::fmt; -use std::io::{self, Write}; -use std::str::FromStr; -#[cfg(windows)] -use std::sync::{Mutex, MutexGuard}; -use std::sync::atomic::{AtomicBool, Ordering}; - -/// This trait describes the behavior of writers that support colored output. -pub trait WriteColor: io::Write { - /// Returns true if and only if the underlying writer supports colors. - fn supports_color(&self) -> bool; - - /// Set the color settings of the writer. - /// - /// Subsequent writes to this writer will use these settings until either - /// `reset` is called or new color settings are set. - /// - /// If there was a problem setting the color settings, then an error is - /// returned. - fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()>; - - /// Reset the current color settings to their original settings. - /// - /// If there was a problem resetting the color settings, then an error is - /// returned. - fn reset(&mut self) -> io::Result<()>; -} - -impl<'a, T: ?Sized + WriteColor> WriteColor for &'a mut T { - fn supports_color(&self) -> bool { (&**self).supports_color() } - fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { - (&mut **self).set_color(spec) - } - fn reset(&mut self) -> io::Result<()> { (&mut **self).reset() } -} - -/// ColorChoice represents the color preferences of an end user. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum ColorChoice { - /// Try very hard to emit colors. This includes emitting ANSI colors - /// on Windows if the console API is unavailable. - Always, - /// AlwaysAnsi is like Always, except it never tries to use anything other - /// than emitting ANSI color codes. - AlwaysAnsi, - /// Try to use colors, but don't force the issue. If the console isn't - /// available on Windows, or if TERM=dumb, for example, then don't use - /// colors. - Auto, - /// Never emit colors. - Never, -} - -impl ColorChoice { - /// Returns true if we should attempt to write colored output. - #[cfg(not(windows))] - fn should_attempt_color(&self) -> bool { - match *self { - ColorChoice::Always => true, - ColorChoice::AlwaysAnsi => true, - ColorChoice::Never => false, - ColorChoice::Auto => { - match env::var("TERM") { - Err(_) => false, - Ok(k) => k != "dumb", - } - } - } - } - - /// Returns true if we should attempt to write colored output. - #[cfg(windows)] - fn should_attempt_color(&self) -> bool { - match *self { - ColorChoice::Always => true, - ColorChoice::AlwaysAnsi => true, - ColorChoice::Never => false, - ColorChoice::Auto => { - match env::var("TERM") { - Err(_) => true, - Ok(k) => k != "dumb", - } - } - } - } - - /// Returns true if this choice should forcefully use ANSI color codes. - /// - /// It's possible that ANSI is still the correct choice even if this - /// returns false. - #[cfg(windows)] - fn should_ansi(&self) -> bool { - match *self { - ColorChoice::Always => false, - ColorChoice::AlwaysAnsi => true, - ColorChoice::Never => false, - ColorChoice::Auto => { - match env::var("TERM") { - Err(_) => false, - // cygwin doesn't seem to support ANSI escape sequences - // and instead has its own variety. However, the Windows - // console API may be available. - Ok(k) => k != "dumb" && k != "cygwin", - } - } - } - } -} - -/// `std::io` implements `Stdout` and `Stderr` (and their `Lock` variants) as -/// separate types, which makes it difficult to abstract over them. We use -/// some simple internal enum types to work around this. - -enum StandardStreamType { - Stdout, - Stderr, -} - -enum IoStandardStream { - Stdout(io::Stdout), - Stderr(io::Stderr), -} - -impl IoStandardStream { - fn new(sty: StandardStreamType) -> IoStandardStream { - match sty { - StandardStreamType::Stdout => { - IoStandardStream::Stdout(io::stdout()) - } - StandardStreamType::Stderr => { - IoStandardStream::Stderr(io::stderr()) - } - } - } - - fn lock(&self) -> IoStandardStreamLock { - match *self { - IoStandardStream::Stdout(ref s) => { - IoStandardStreamLock::StdoutLock(s.lock()) - } - IoStandardStream::Stderr(ref s) => { - IoStandardStreamLock::StderrLock(s.lock()) - } - } - } -} - -impl io::Write for IoStandardStream { - fn write(&mut self, b: &[u8]) -> io::Result<usize> { - match *self { - IoStandardStream::Stdout(ref mut s) => s.write(b), - IoStandardStream::Stderr(ref mut s) => s.write(b), - } - } - - fn flush(&mut self) -> io::Result<()> { - match *self { - IoStandardStream::Stdout(ref mut s) => s.flush(), - IoStandardStream::Stderr(ref mut s) => s.flush(), - } - } -} - -// Same rigmarole for the locked variants of the standard streams. - -enum IoStandardStreamLock<'a> { - StdoutLock(io::StdoutLock<'a>), - StderrLock(io::StderrLock<'a>), -} - -impl<'a> io::Write for IoStandardStreamLock<'a> { - fn write(&mut self, b: &[u8]) -> io::Result<usize> { - match *self { - IoStandardStreamLock::StdoutLock(ref mut s) => s.write(b), - IoStandardStreamLock::StderrLock(ref mut s) => s.write(b), - } - } - - fn flush(&mut self) -> io::Result<()> { - match *self { - IoStandardStreamLock::StdoutLock(ref mut s) => s.flush(), - IoStandardStreamLock::StderrLock(ref mut s) => s.flush(), - } - } -} - -/// Satisfies `io::Write` and `WriteColor`, and supports optional coloring -/// to either of the standard output streams, stdout and stderr. -pub struct StandardStream { - wtr: LossyStandardStream<WriterInner<IoStandardStream>>, -} - -/// `StandardStreamLock` is a locked reference to a `StandardStream`. -/// -/// This implements the `io::Write` and `WriteColor` traits, and is constructed -/// via the `Write::lock` method. -/// -/// The lifetime `'a` refers to the lifetime of the corresponding -/// `StandardStream`. -pub struct StandardStreamLock<'a> { - wtr: LossyStandardStream<WriterInnerLock<'a, IoStandardStreamLock<'a>>>, -} - -/// WriterInner is a (limited) generic representation of a writer. It is -/// limited because W should only ever be stdout/stderr on Windows. -enum WriterInner<W> { - NoColor(NoColor<W>), - Ansi(Ansi<W>), - #[cfg(windows)] - Windows { wtr: W, console: Mutex<wincolor::Console> }, -} - -/// WriterInnerLock is a (limited) generic representation of a writer. It is -/// limited because W should only ever be stdout/stderr on Windows. -enum WriterInnerLock<'a, W> { - NoColor(NoColor<W>), - Ansi(Ansi<W>), - /// What a gross hack. On Windows, we need to specify a lifetime for the - /// console when in a locked state, but obviously don't need to do that - /// on Unix, which makes the `'a` unused. To satisfy the compiler, we need - /// a PhantomData. - #[allow(dead_code)] - Unreachable(::std::marker::PhantomData<&'a ()>), - #[cfg(windows)] - Windows { wtr: W, console: MutexGuard<'a, wincolor::Console> }, -} - -impl StandardStream { - /// Create a new `StandardStream` with the given color preferences. - /// - /// The specific color/style settings can be configured when writing via - /// the `WriteColor` trait. - #[cfg(not(windows))] - fn create(sty: StandardStreamType, choice: ColorChoice) -> StandardStream { - let wtr = - if choice.should_attempt_color() { - WriterInner::Ansi(Ansi(IoStandardStream::new(sty))) - } else { - WriterInner::NoColor(NoColor(IoStandardStream::new(sty))) - }; - StandardStream { wtr: LossyStandardStream::new(wtr) } - } - - /// Create a new `StandardStream` with the given color preferences. - /// - /// If coloring is desired and a Windows console could not be found, then - /// ANSI escape sequences are used instead. - /// - /// The specific color/style settings can be configured when writing via - /// the `WriteColor` trait. - #[cfg(windows)] - fn create(sty: StandardStreamType, choice: ColorChoice) -> StandardStream { - let mut con = match sty { - StandardStreamType::Stdout => wincolor::Console::stdout(), - StandardStreamType::Stderr => wincolor::Console::stderr(), - }; - let is_win_console = con.is_ok(); - let is_console_virtual = con.as_mut().map(|con| { - con.set_virtual_terminal_processing(true).is_ok() - }).unwrap_or(false); - let wtr = - if choice.should_attempt_color() { - if choice.should_ansi() || is_console_virtual { - WriterInner::Ansi(Ansi(IoStandardStream::new(sty))) - } else if let Ok(console) = con { - WriterInner::Windows { - wtr: IoStandardStream::new(sty), - console: Mutex::new(console), - } - } else { - WriterInner::Ansi(Ansi(IoStandardStream::new(sty))) - } - } else { - WriterInner::NoColor(NoColor(IoStandardStream::new(sty))) - }; - StandardStream { - wtr: LossyStandardStream::new(wtr).is_console(is_win_console), - } - } - - /// Create a new `StandardStream` with the given color preferences that - /// writes to standard output. - /// - /// On Windows, if coloring is desired and a Windows console could not be - /// found, then ANSI escape sequences are used instead. - /// - /// The specific color/style settings can be configured when writing via - /// the `WriteColor` trait. - pub fn stdout(choice: ColorChoice) -> StandardStream { - StandardStream::create(StandardStreamType::Stdout, choice) - } - - /// Create a new `StandardStream` with the given color preferences that - /// writes to standard error. - /// - /// On Windows, if coloring is desired and a Windows console could not be - /// found, then ANSI escape sequences are used instead. - /// - /// The specific color/style settings can be configured when writing via - /// the `WriteColor` trait. - pub fn stderr(choice: ColorChoice) -> StandardStream { - StandardStream::create(StandardStreamType::Stderr, choice) - } - - /// Lock the underlying writer. - /// - /// The lock guard returned also satisfies `io::Write` and - /// `WriteColor`. - /// - /// This method is **not reentrant**. It may panic if `lock` is called - /// while a `StandardStreamLock` is still alive. - pub fn lock(&self) -> StandardStreamLock { - StandardStreamLock::from_stream(self) - } -} - -impl<'a> StandardStreamLock<'a> { - #[cfg(not(windows))] - fn from_stream(stream: &StandardStream) -> StandardStreamLock { - let locked = match *stream.wtr.get_ref() { - WriterInner::NoColor(ref w) => { - WriterInnerLock::NoColor(NoColor(w.0.lock())) - } - WriterInner::Ansi(ref w) => { - WriterInnerLock::Ansi(Ansi(w.0.lock())) - } - }; - StandardStreamLock { wtr: stream.wtr.wrap(locked) } - } - - #[cfg(windows)] - fn from_stream(stream: &StandardStream) -> StandardStreamLock { - let locked = match *stream.wtr.get_ref() { - WriterInner::NoColor(ref w) => { - WriterInnerLock::NoColor(NoColor(w.0.lock())) - } - WriterInner::Ansi(ref w) => { - WriterInnerLock::Ansi(Ansi(w.0.lock())) - } - #[cfg(windows)] - WriterInner::Windows { ref wtr, ref console } => { - WriterInnerLock::Windows { - wtr: wtr.lock(), - console: console.lock().unwrap(), - } - } - }; - StandardStreamLock { wtr: stream.wtr.wrap(locked) } - } -} - -impl io::Write for StandardStream { - fn write(&mut self, b: &[u8]) -> io::Result<usize> { self.wtr.write(b) } - fn flush(&mut self) -> io::Result<()> { self.wtr.flush() } -} - -impl WriteColor for StandardStream { - fn supports_color(&self) -> bool { self.wtr.supports_color() } - fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { - self.wtr.set_color(spec) - } - fn reset(&mut self) -> io::Result<()> { self.wtr.reset() } -} - -impl<'a> io::Write for StandardStreamLock<'a> { - fn write(&mut self, b: &[u8]) -> io::Result<usize> { self.wtr.write(b) } - fn flush(&mut self) -> io::Result<()> { self.wtr.flush() } -} - -impl<'a> WriteColor for StandardStreamLock<'a> { - fn supports_color(&self) -> bool { self.wtr.supports_color() } - fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { - self.wtr.set_color(spec) - } - fn reset(&mut self) -> io::Result<()> { self.wtr.reset() } -} - -impl<W: io::Write> io::Write for WriterInner<W> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - match *self { - WriterInner::NoColor(ref mut wtr) => wtr.write(buf), - WriterInner::Ansi(ref mut wtr) => wtr.write(buf), - #[cfg(windows)] - WriterInner::Windows { ref mut wtr, .. } => wtr.write(buf), - } - } - - fn flush(&mut self) -> io::Result<()> { - match *self { - WriterInner::NoColor(ref mut wtr) => wtr.flush(), - WriterInner::Ansi(ref mut wtr) => wtr.flush(), - #[cfg(windows)] - WriterInner::Windows { ref mut wtr, .. } => wtr.flush(), - } - } -} - -impl<W: io::Write> WriteColor for WriterInner<W> { - fn supports_color(&self) -> bool { - match *self { - WriterInner::NoColor(_) => false, - WriterInner::Ansi(_) => true, - #[cfg(windows)] - WriterInner::Windows { .. } => true, - } - } - - fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { - match *self { - WriterInner::NoColor(ref mut wtr) => wtr.set_color(spec), - WriterInner::Ansi(ref mut wtr) => wtr.set_color(spec), - #[cfg(windows)] - WriterInner::Windows { ref mut wtr, ref console } => { - wtr.flush()?; - let mut console = console.lock().unwrap(); - spec.write_console(&mut *console) - } - } - } - - fn reset(&mut self) -> io::Result<()> { - match *self { - WriterInner::NoColor(ref mut wtr) => wtr.reset(), - WriterInner::Ansi(ref mut wtr) => wtr.reset(), - #[cfg(windows)] - WriterInner::Windows { ref mut wtr, ref mut console } => { - wtr.flush()?; - console.lock().unwrap().reset()?; - Ok(()) - } - } - } -} - -impl<'a, W: io::Write> io::Write for WriterInnerLock<'a, W> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - match *self { - WriterInnerLock::Unreachable(_) => unreachable!(), - WriterInnerLock::NoColor(ref mut wtr) => wtr.write(buf), - WriterInnerLock::Ansi(ref mut wtr) => wtr.write(buf), - #[cfg(windows)] - WriterInnerLock::Windows { ref mut wtr, .. } => wtr.write(buf), - } - } - - fn flush(&mut self) -> io::Result<()> { - match *self { - WriterInnerLock::Unreachable(_) => unreachable!(), - WriterInnerLock::NoColor(ref mut wtr) => wtr.flush(), - WriterInnerLock::Ansi(ref mut wtr) => wtr.flush(), - #[cfg(windows)] - WriterInnerLock::Windows { ref mut wtr, .. } => wtr.flush(), - } - } -} - -impl<'a, W: io::Write> WriteColor for WriterInnerLock<'a, W> { - fn supports_color(&self) -> bool { - match *self { - WriterInnerLock::Unreachable(_) => unreachable!(), - WriterInnerLock::NoColor(_) => false, - WriterInnerLock::Ansi(_) => true, - #[cfg(windows)] - WriterInnerLock::Windows { .. } => true, - } - } - - fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { - match *self { - WriterInnerLock::Unreachable(_) => unreachable!(), - WriterInnerLock::NoColor(ref mut wtr) => wtr.set_color(spec), - WriterInnerLock::Ansi(ref mut wtr) => wtr.set_color(spec), - #[cfg(windows)] - WriterInnerLock::Windows { ref mut wtr, ref mut console } => { - wtr.flush()?; - spec.write_console(console) - } - } - } - - fn reset(&mut self) -> io::Result<()> { - match *self { - WriterInnerLock::Unreachable(_) => unreachable!(), - WriterInnerLock::NoColor(ref mut wtr) => wtr.reset(), - WriterInnerLock::Ansi(ref mut wtr) => wtr.reset(), - #[cfg(windows)] - WriterInnerLock::Windows { ref mut wtr, ref mut console } => { - wtr.flush()?; - console.reset()?; - Ok(()) - } - } - } -} - -/// Writes colored buffers to stdout or stderr. -/// -/// Writable buffers can be obtained by calling `buffer` on a `BufferWriter`. -/// -/// This writer works with terminals that support ANSI escape sequences or -/// with a Windows console. -/// -/// It is intended for a `BufferWriter` to be put in an `Arc` and written to -/// from multiple threads simultaneously. -pub struct BufferWriter { - stream: LossyStandardStream<IoStandardStream>, - printed: AtomicBool, - separator: Option<Vec<u8>>, - color_choice: ColorChoice, - #[cfg(windows)] - console: Option<Mutex<wincolor::Console>>, -} - -impl BufferWriter { - /// Create a new `BufferWriter` that writes to a standard stream with the - /// given color preferences. - /// - /// The specific color/style settings can be configured when writing to - /// the buffers themselves. - #[cfg(not(windows))] - fn create(sty: StandardStreamType, choice: ColorChoice) -> BufferWriter { - BufferWriter { - stream: LossyStandardStream::new(IoStandardStream::new(sty)), - printed: AtomicBool::new(false), - separator: None, - color_choice: choice, - } - } - - /// Create a new `BufferWriter` that writes to a standard stream with the - /// given color preferences. - /// - /// If coloring is desired and a Windows console could not be found, then - /// ANSI escape sequences are used instead. - /// - /// The specific color/style settings can be configured when writing to - /// the buffers themselves. - #[cfg(windows)] - fn create(sty: StandardStreamType, choice: ColorChoice) -> BufferWriter { - let mut con = match sty { - StandardStreamType::Stdout => wincolor::Console::stdout(), - StandardStreamType::Stderr => wincolor::Console::stderr(), - }.ok(); - let is_console_virtual = con.as_mut().map(|con| { - con.set_virtual_terminal_processing(true).is_ok() - }).unwrap_or(false); - // If we can enable ANSI on Windows, then we don't need the console - // anymore. - if is_console_virtual { - con = None; - } - let stream = LossyStandardStream::new(IoStandardStream::new(sty)) - .is_console(con.is_some()); - BufferWriter { - stream: stream, - printed: AtomicBool::new(false), - separator: None, - color_choice: choice, - console: con.map(Mutex::new), - } - } - - /// Create a new `BufferWriter` that writes to stdout with the given - /// color preferences. - /// - /// On Windows, if coloring is desired and a Windows console could not be - /// found, then ANSI escape sequences are used instead. - /// - /// The specific color/style settings can be configured when writing to - /// the buffers themselves. - pub fn stdout(choice: ColorChoice) -> BufferWriter { - BufferWriter::create(StandardStreamType::Stdout, choice) - } - - /// Create a new `BufferWriter` that writes to stderr with the given - /// color preferences. - /// - /// On Windows, if coloring is desired and a Windows console could not be - /// found, then ANSI escape sequences are used instead. - /// - /// The specific color/style settings can be configured when writing to - /// the buffers themselves. - pub fn stderr(choice: ColorChoice) -> BufferWriter { - BufferWriter::create(StandardStreamType::Stderr, choice) - } - - /// If set, the separator given is printed between buffers. By default, no - /// separator is printed. - /// - /// The default value is `None`. - pub fn separator(&mut self, sep: Option<Vec<u8>>) { - self.separator = sep; - } - - /// Creates a new `Buffer` with the current color preferences. - /// - /// A `Buffer` satisfies both `io::Write` and `WriteColor`. A `Buffer` can - /// be printed using the `print` method. - #[cfg(not(windows))] - pub fn buffer(&self) -> Buffer { - Buffer::new(self.color_choice) - } - - /// Creates a new `Buffer` with the current color preferences. - /// - /// A `Buffer` satisfies both `io::Write` and `WriteColor`. A `Buffer` can - /// be printed using the `print` method. - #[cfg(windows)] - pub fn buffer(&self) -> Buffer { - Buffer::new(self.color_choice, self.console.is_some()) - } - - /// Prints the contents of the given buffer. - /// - /// It is safe to call this from multiple threads simultaneously. In - /// particular, all buffers are written atomically. No interleaving will - /// occur. - pub fn print(&self, buf: &Buffer) -> io::Result<()> { - if buf.is_empty() { - return Ok(()); - } - let mut stream = self.stream.wrap(self.stream.get_ref().lock()); - if let Some(ref sep) = self.separator { - if self.printed.load(Ordering::SeqCst) { - stream.write_all(sep)?; - stream.write_all(b"\n")?; - } - } - match buf.0 { - BufferInner::NoColor(ref b) => stream.write_all(&b.0)?, - BufferInner::Ansi(ref b) => stream.write_all(&b.0)?, - #[cfg(windows)] - BufferInner::Windows(ref b) => { - // We guarantee by construction that we have a console here. - // Namely, a BufferWriter is the only way to produce a Buffer. - let console_mutex = self.console.as_ref() - .expect("got Windows buffer but have no Console"); - let mut console = console_mutex.lock().unwrap(); - b.print(&mut *console, &mut stream)?; - } - } - self.printed.store(true, Ordering::SeqCst); - Ok(()) - } -} - -/// Write colored text to memory. -/// -/// `Buffer` is a platform independent abstraction for printing colored text to -/// an in memory buffer. When the buffer is printed using a `BufferWriter`, the -/// color information will be applied to the output device (a tty on Unix and a -/// console on Windows). -/// -/// A `Buffer` is typically created by calling the `BufferWriter.buffer` -/// method, which will take color preferences and the environment into -/// account. However, buffers can also be manually created using `no_color`, -/// `ansi` or `console` (on Windows). -pub struct Buffer(BufferInner); - -/// BufferInner is an enumeration of different buffer types. -enum BufferInner { - /// No coloring information should be applied. This ignores all coloring - /// directives. - NoColor(NoColor<Vec<u8>>), - /// Apply coloring using ANSI escape sequences embedded into the buffer. - Ansi(Ansi<Vec<u8>>), - /// Apply coloring using the Windows console APIs. This buffer saves - /// color information in memory and only interacts with the console when - /// the buffer is printed. - #[cfg(windows)] - Windows(WindowsBuffer), -} - -impl Buffer { - /// Create a new buffer with the given color settings. - #[cfg(not(windows))] - fn new(choice: ColorChoice) -> Buffer { - if choice.should_attempt_color() { - Buffer::ansi() - } else { - Buffer::no_color() - } - } - - /// Create a new buffer with the given color settings. - /// - /// On Windows, one can elect to create a buffer capable of being written - /// to a console. Only enable it if a console is available. - /// - /// If coloring is desired and `console` is false, then ANSI escape - /// sequences are used instead. - #[cfg(windows)] - fn new(choice: ColorChoice, console: bool) -> Buffer { - if choice.should_attempt_color() { - if !console || choice.should_ansi() { - Buffer::ansi() - } else { - Buffer::console() - } - } else { - Buffer::no_color() - } - } - - /// Create a buffer that drops all color information. - pub fn no_color() -> Buffer { - Buffer(BufferInner::NoColor(NoColor(vec![]))) - } - - /// Create a buffer that uses ANSI escape sequences. - pub fn ansi() -> Buffer { - Buffer(BufferInner::Ansi(Ansi(vec![]))) - } - - /// Create a buffer that can be written to a Windows console. - #[cfg(windows)] - pub fn console() -> Buffer { - Buffer(BufferInner::Windows(WindowsBuffer::new())) - } - - /// Returns true if and only if this buffer is empty. - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// Returns the length of this buffer in bytes. - pub fn len(&self) -> usize { - match self.0 { - BufferInner::NoColor(ref b) => b.0.len(), - BufferInner::Ansi(ref b) => b.0.len(), - #[cfg(windows)] - BufferInner::Windows(ref b) => b.buf.len(), - } - } - - /// Clears this buffer. - pub fn clear(&mut self) { - match self.0 { - BufferInner::NoColor(ref mut b) => b.0.clear(), - BufferInner::Ansi(ref mut b) => b.0.clear(), - #[cfg(windows)] - BufferInner::Windows(ref mut b) => b.clear(), - } - } - - /// Consume this buffer and return the underlying raw data. - /// - /// On Windows, this unrecoverably drops all color information associated - /// with the buffer. - pub fn into_inner(self) -> Vec<u8> { - match self.0 { - BufferInner::NoColor(b) => b.0, - BufferInner::Ansi(b) => b.0, - #[cfg(windows)] - BufferInner::Windows(b) => b.buf, - } - } - - /// Return the underlying data of the buffer. - pub fn as_slice(&self) -> &[u8] { - match self.0 { - BufferInner::NoColor(ref b) => &b.0, - BufferInner::Ansi(ref b) => &b.0, - #[cfg(windows)] - BufferInner::Windows(ref b) => &b.buf, - } - } - - /// Return the underlying data of the buffer as a mutable slice. - pub fn as_mut_slice(&mut self) -> &mut [u8] { - match self.0 { - BufferInner::NoColor(ref mut b) => &mut b.0, - BufferInner::Ansi(ref mut b) => &mut b.0, - #[cfg(windows)] - BufferInner::Windows(ref mut b) => &mut b.buf, - } - } -} - -impl io::Write for Buffer { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - match self.0 { - BufferInner::NoColor(ref mut w) => w.write(buf), - BufferInner::Ansi(ref mut w) => w.write(buf), - #[cfg(windows)] - BufferInner::Windows(ref mut w) => w.write(buf), - } - } - - fn flush(&mut self) -> io::Result<()> { - match self.0 { - BufferInner::NoColor(ref mut w) => w.flush(), - BufferInner::Ansi(ref mut w) => w.flush(), - #[cfg(windows)] - BufferInner::Windows(ref mut w) => w.flush(), - } - } -} - -impl WriteColor for Buffer { - fn supports_color(&self) -> bool { - match self.0 { - BufferInner::NoColor(_) => false, - BufferInner::Ansi(_) => true, - #[cfg(windows)] - BufferInner::Windows(_) => true, - } - } - - fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { - match self.0 { - BufferInner::NoColor(ref mut w) => w.set_color(spec), - BufferInner::Ansi(ref mut w) => w.set_color(spec), - #[cfg(windows)] - BufferInner::Windows(ref mut w) => w.set_color(spec), - } - } - - fn reset(&mut self) -> io::Result<()> { - match self.0 { - BufferInner::NoColor(ref mut w) => w.reset(), - BufferInner::Ansi(ref mut w) => w.reset(), - #[cfg(windows)] - BufferInner::Windows(ref mut w) => w.reset(), - } - } -} - -/// Satisfies `WriteColor` but ignores all color options. -pub struct NoColor<W>(W); - -impl<W: Write> NoColor<W> { - /// Create a new writer that satisfies `WriteColor` but drops all color - /// information. - pub fn new(wtr: W) -> NoColor<W> { NoColor(wtr) } - - /// Consume this `NoColor` value and return the inner writer. - pub fn into_inner(self) -> W { self.0 } - - /// Return a reference to the inner writer. - pub fn get_ref(&self) -> &W { &self.0 } - - /// Return a mutable reference to the inner writer. - pub fn get_mut(&mut self) -> &mut W { &mut self.0 } -} - -impl<W: io::Write> io::Write for NoColor<W> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.0.write(buf) - } - - fn flush(&mut self) -> io::Result<()> { - self.0.flush() - } -} - -impl<W: io::Write> WriteColor for NoColor<W> { - fn supports_color(&self) -> bool { false } - fn set_color(&mut self, _: &ColorSpec) -> io::Result<()> { Ok(()) } - fn reset(&mut self) -> io::Result<()> { Ok(()) } -} - -/// Satisfies `WriteColor` using standard ANSI escape sequences. -pub struct Ansi<W>(W); - -impl<W: Write> Ansi<W> { - /// Create a new writer that satisfies `WriteColor` using standard ANSI - /// escape sequences. - pub fn new(wtr: W) -> Ansi<W> { Ansi(wtr) } - - /// Consume this `Ansi` value and return the inner writer. - pub fn into_inner(self) -> W { self.0 } - - /// Return a reference to the inner writer. - pub fn get_ref(&self) -> &W { &self.0 } - - /// Return a mutable reference to the inner writer. - pub fn get_mut(&mut self) -> &mut W { &mut self.0 } -} - -impl<W: io::Write> io::Write for Ansi<W> { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.0.write(buf) - } - - fn flush(&mut self) -> io::Result<()> { - self.0.flush() - } -} - -impl<W: io::Write> WriteColor for Ansi<W> { - fn supports_color(&self) -> bool { true } - - fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { - self.reset()?; - if let Some(ref c) = spec.fg_color { - self.write_color(true, c, spec.intense)?; - } - if let Some(ref c) = spec.bg_color { - self.write_color(false, c, spec.intense)?; - } - if spec.bold { - self.write_str("\x1B[1m")?; - } - if spec.underline { - self.write_str("\x1B[4m")?; - } - Ok(()) - } - - fn reset(&mut self) -> io::Result<()> { - self.write_str("\x1B[0m") - } -} - -impl<W: io::Write> Ansi<W> { - fn write_str(&mut self, s: &str) -> io::Result<()> { - self.write_all(s.as_bytes()) - } - - fn write_color( - &mut self, - fg: bool, - c: &Color, - intense: bool, - ) -> io::Result<()> { - macro_rules! write_intense { - ($clr:expr) => { - if fg { - self.write_str(concat!("\x1B[38;5;", $clr, "m")) - } else { - self.write_str(concat!("\x1B[48;5;", $clr, "m")) - } - } - } - macro_rules! write_normal { - ($clr:expr) => { - if fg { - self.write_str(concat!("\x1B[3", $clr, "m")) - } else { - self.write_str(concat!("\x1B[4", $clr, "m")) - } - } - } - macro_rules! write_var_ansi_code { - ($pre:expr, $($code:expr),+) => {{ - // The loop generates at worst a literal of the form - // '255,255,255m' which is 12-bytes. - // The largest `pre` expression we currently use is 7 bytes. - // This gives us the maximum of 19-bytes for our work buffer. - let pre_len = $pre.len(); - assert!(pre_len <= 7); - let mut fmt = [0u8; 19]; - fmt[..pre_len].copy_from_slice($pre); - let mut i = pre_len - 1; - $( - let c1: u8 = ($code / 100) % 10; - let c2: u8 = ($code / 10) % 10; - let c3: u8 = $code % 10; - let mut printed = false; - - if c1 != 0 { - printed = true; - i += 1; - fmt[i] = b'0' + c1; - } - if c2 != 0 || printed { - i += 1; - fmt[i] = b'0' + c2; - } - // If we received a zero value we must still print a value. - i += 1; - fmt[i] = b'0' + c3; - i += 1; - fmt[i] = b';'; - )+ - - fmt[i] = b'm'; - self.write_all(&fmt[0..i+1]) - }} - } - macro_rules! write_custom { - ($ansi256:expr) => { - if fg { - write_var_ansi_code!(b"\x1B[38;5;", $ansi256) - } else { - write_var_ansi_code!(b"\x1B[48;5;", $ansi256) - } - }; - - ($r:expr, $g:expr, $b:expr) => {{ - if fg { - write_var_ansi_code!(b"\x1B[38;2;", $r, $g, $b) - } else { - write_var_ansi_code!(b"\x1B[48;2;", $r, $g, $b) - } - }}; - } - if intense { - match *c { - Color::Black => write_intense!("8"), - Color::Blue => write_intense!("12"), - Color::Green => write_intense!("10"), - Color::Red => write_intense!("9"), - Color::Cyan => write_intense!("14"), - Color::Magenta => write_intense!("13"), - Color::Yellow => write_intense!("11"), - Color::White => write_intense!("15"), - Color::Ansi256(c) => write_custom!(c), - Color::Rgb(r, g, b) => write_custom!(r, g, b), - Color::__Nonexhaustive => unreachable!(), - } - } else { - match *c { - Color::Black => write_normal!("0"), - Color::Blue => write_normal!("4"), - Color::Green => write_normal!("2"), - Color::Red => write_normal!("1"), - Color::Cyan => write_normal!("6"), - Color::Magenta => write_normal!("5"), - Color::Yellow => write_normal!("3"), - Color::White => write_normal!("7"), - Color::Ansi256(c) => write_custom!(c), - Color::Rgb(r, g, b) => write_custom!(r, g, b), - Color::__Nonexhaustive => unreachable!(), - } - } - } -} - -/// An in-memory buffer that provides Windows console coloring. -/// -/// This doesn't actually communicate with the Windows console. Instead, it -/// acts like a normal buffer but also saves the color information associated -/// with positions in the buffer. It is only when the buffer is written to the -/// console that coloring is actually applied. -/// -/// This is roughly isomorphic to the ANSI based approach (i.e., -/// `Ansi<Vec<u8>>`), except with ANSI, the color information is embedded -/// directly into the buffer. -/// -/// Note that there is no way to write something generic like -/// `WindowsConsole<W: io::Write>` since coloring on Windows is tied -/// specifically to the console APIs, and therefore can't work on arbitrary -/// writers. -#[cfg(windows)] -#[derive(Clone, Debug)] -struct WindowsBuffer { - /// The actual content that should be printed. - buf: Vec<u8>, - /// A sequence of position oriented color specifications. Namely, each - /// element is a position and a color spec, where the color spec should - /// be applied at the position inside of `buf`. - /// - /// A missing color spec implies the underlying console should be reset. - colors: Vec<(usize, Option<ColorSpec>)>, -} - -#[cfg(windows)] -impl WindowsBuffer { - /// Create a new empty buffer for Windows console coloring. - fn new() -> WindowsBuffer { - WindowsBuffer { - buf: vec![], - colors: vec![], - } - } - - /// Push the given color specification into this buffer. - /// - /// This has the effect of setting the given color information at the - /// current position in the buffer. - fn push(&mut self, spec: Option<ColorSpec>) { - let pos = self.buf.len(); - self.colors.push((pos, spec)); - } - - /// Print the contents to the given stream handle, and use the console - /// for coloring. - fn print( - &self, - console: &mut wincolor::Console, - stream: &mut LossyStandardStream<IoStandardStreamLock>, - ) -> io::Result<()> { - let mut last = 0; - for &(pos, ref spec) in &self.colors { - stream.write_all(&self.buf[last..pos])?; - stream.flush()?; - last = pos; - match *spec { - None => console.reset()?, - Some(ref spec) => spec.write_console(console)?, - } - } - stream.write_all(&self.buf[last..])?; - stream.flush() - } - - /// Clear the buffer. - fn clear(&mut self) { - self.buf.clear(); - self.colors.clear(); - } -} - -#[cfg(windows)] -impl io::Write for WindowsBuffer { - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.buf.extend_from_slice(buf); - Ok(buf.len()) - } - - fn flush(&mut self) -> io::Result<()> { - Ok(()) - } -} - -#[cfg(windows)] -impl WriteColor for WindowsBuffer { - fn supports_color(&self) -> bool { true } - - fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { - self.push(Some(spec.clone())); - Ok(()) - } - - fn reset(&mut self) -> io::Result<()> { - self.push(None); - Ok(()) - } -} - -/// A color specification. -#[derive(Clone, Debug, Default, Eq, PartialEq)] -pub struct ColorSpec { - fg_color: Option<Color>, - bg_color: Option<Color>, - bold: bool, - intense: bool, - underline: bool, -} - -impl ColorSpec { - /// Create a new color specification that has no colors or styles. - pub fn new() -> ColorSpec { - ColorSpec::default() - } - - /// Get the foreground color. - pub fn fg(&self) -> Option<&Color> { self.fg_color.as_ref() } - - /// Set the foreground color. - pub fn set_fg(&mut self, color: Option<Color>) -> &mut ColorSpec { - self.fg_color = color; - self - } - - /// Get the background color. - pub fn bg(&self) -> Option<&Color> { self.bg_color.as_ref() } - - /// Set the background color. - pub fn set_bg(&mut self, color: Option<Color>) -> &mut ColorSpec { - self.bg_color = color; - self - } - - /// Get whether this is bold or not. - /// - /// Note that the bold setting has no effect in a Windows console. - pub fn bold(&self) -> bool { self.bold } - - /// Set whether the text is bolded or not. - /// - /// Note that the bold setting has no effect in a Windows console. - pub fn set_bold(&mut self, yes: bool) -> &mut ColorSpec { - self.bold = yes; - self - } - - /// Get whether this is underline or not. - /// - /// Note that the underline setting has no effect in a Windows console. - pub fn underline(&self) -> bool { self.underline } - - /// Set whether the text is underlined or not. - /// - /// Note that the underline setting has no effect in a Windows console. - pub fn set_underline(&mut self, yes: bool) -> &mut ColorSpec { - self.underline = yes; - self - } - - /// Get whether this is intense or not. - /// - /// On Unix-like systems, this will output the ANSI escape sequence - /// that will print a high-intensity version of the color - /// specified. - /// - /// On Windows systems, this will output the ANSI escape sequence - /// that will print a brighter version of the color specified. - pub fn intense(&self) -> bool { self.intense } - - /// Set whether the text is intense or not. - /// - /// On Unix-like systems, this will output the ANSI escape sequence - /// that will print a high-intensity version of the color - /// specified. - /// - /// On Windows systems, this will output the ANSI escape sequence - /// that will print a brighter version of the color specified. - pub fn set_intense(&mut self, yes: bool) -> &mut ColorSpec { - self.intense = yes; - self - } - - /// Returns true if this color specification has no colors or styles. - pub fn is_none(&self) -> bool { - self.fg_color.is_none() && self.bg_color.is_none() - && !self.bold && !self.underline - } - - /// Clears this color specification so that it has no color/style settings. - pub fn clear(&mut self) { - self.fg_color = None; - self.bg_color = None; - self.bold = false; - self.underline = false; - } - - /// Writes this color spec to the given Windows console. - #[cfg(windows)] - fn write_console( - &self, - console: &mut wincolor::Console, - ) -> io::Result<()> { - use wincolor::Intense; - - let intense = if self.intense { Intense::Yes } else { Intense::No }; - - let fg_color = self.fg_color.as_ref().and_then(|c| c.to_windows()); - if let Some(color) = fg_color { - console.fg(intense, color)?; - } - - let bg_color = self.bg_color.as_ref().and_then(|c| c.to_windows()); - if let Some(color) = bg_color { - console.bg(intense, color)?; - } - Ok(()) - } -} - -/// The set of available colors for the terminal foreground/background. -/// -/// The `Ansi256` and `Rgb` colors will only output the correct codes when -/// paired with the `Ansi` `WriteColor` implementation. -/// -/// The `Ansi256` and `Rgb` color types are not supported when writing colors -/// on Windows using the console. If they are used on Windows, then they are -/// silently ignored and no colors will be emitted. -/// -/// This set may expand over time. -/// -/// This type has a `FromStr` impl that can parse colors from their human -/// readable form. The format is as follows: -/// -/// 1. Any of the explicitly listed colors in English. They are matched -/// case insensitively. -/// 2. A single 8-bit integer, in either decimal or hexadecimal format. -/// 3. A triple of 8-bit integers separated by a comma, where each integer is -/// in decimal or hexadecimal format. -/// -/// Hexadecimal numbers are written with a `0x` prefix. -#[allow(missing_docs)] -#[derive(Clone, Debug, Eq, PartialEq)] -pub enum Color { - Black, - Blue, - Green, - Red, - Cyan, - Magenta, - Yellow, - White, - Ansi256(u8), - Rgb(u8, u8, u8), - #[doc(hidden)] - __Nonexhaustive, -} - -impl Color { - /// Translate this color to a wincolor::Color. - #[cfg(windows)] - fn to_windows(&self) -> Option<wincolor::Color> { - match *self { - Color::Black => Some(wincolor::Color::Black), - Color::Blue => Some(wincolor::Color::Blue), - Color::Green => Some(wincolor::Color::Green), - Color::Red => Some(wincolor::Color::Red), - Color::Cyan => Some(wincolor::Color::Cyan), - Color::Magenta => Some(wincolor::Color::Magenta), - Color::Yellow => Some(wincolor::Color::Yellow), - Color::White => Some(wincolor::Color::White), - Color::Ansi256(_) => None, - Color::Rgb(_, _, _) => None, - Color::__Nonexhaustive => unreachable!(), - } - } - - /// Parses a numeric color string, either ANSI or RGB. - fn from_str_numeric(s: &str) -> Result<Color, ParseColorError> { - // The "ansi256" format is a single number (decimal or hex) - // corresponding to one of 256 colors. - // - // The "rgb" format is a triple of numbers (decimal or hex) delimited - // by a comma corresponding to one of 256^3 colors. - - fn parse_number(s: &str) -> Option<u8> { - use std::u8; - - if s.starts_with("0x") { - u8::from_str_radix(&s[2..], 16).ok() - } else { - u8::from_str_radix(s, 10).ok() - } - } - - let codes: Vec<&str> = s.split(',').collect(); - if codes.len() == 1 { - if let Some(n) = parse_number(&codes[0]) { - Ok(Color::Ansi256(n)) - } else { - if s.chars().all(|c| c.is_digit(16)) { - Err(ParseColorError { - kind: ParseColorErrorKind::InvalidAnsi256, - given: s.to_string(), - }) - } else { - Err(ParseColorError { - kind: ParseColorErrorKind::InvalidName, - given: s.to_string(), - }) - } - } - } else if codes.len() == 3 { - let mut v = vec![]; - for code in codes { - let n = parse_number(code).ok_or_else(|| { - ParseColorError { - kind: ParseColorErrorKind::InvalidRgb, - given: s.to_string(), - } - })?; - v.push(n); - } - Ok(Color::Rgb(v[0], v[1], v[2])) - } else { - Err(if s.contains(",") { - ParseColorError { - kind: ParseColorErrorKind::InvalidRgb, - given: s.to_string(), - } - } else { - ParseColorError { - kind: ParseColorErrorKind::InvalidName, - given: s.to_string(), - } - }) - } - } -} - -/// An error from parsing an invalid color specification. -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct ParseColorError { - kind: ParseColorErrorKind, - given: String, -} - -#[derive(Clone, Debug, Eq, PartialEq)] -enum ParseColorErrorKind { - InvalidName, - InvalidAnsi256, - InvalidRgb, -} - -impl ParseColorError { - /// Return the string that couldn't be parsed as a valid color. - pub fn invalid(&self) -> &str { &self.given } -} - -impl error::Error for ParseColorError { - fn description(&self) -> &str { - use self::ParseColorErrorKind::*; - match self.kind { - InvalidName => "unrecognized color name", - InvalidAnsi256 => "invalid ansi256 color number", - InvalidRgb => "invalid RGB color triple", - } - } -} - -impl fmt::Display for ParseColorError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use self::ParseColorErrorKind::*; - match self.kind { - InvalidName => { - write!(f, "unrecognized color name '{}'. Choose from: \ - black, blue, green, red, cyan, magenta, yellow, \ - white", - self.given) - } - InvalidAnsi256 => { - write!(f, "unrecognized ansi256 color number, \ - should be '[0-255]' (or a hex number), but is '{}'", - self.given) - } - InvalidRgb => { - write!(f, "unrecognized RGB color triple, \ - should be '[0-255],[0-255],[0-255]' (or a hex \ - triple), but is '{}'", self.given) - } - } - } -} - -impl FromStr for Color { - type Err = ParseColorError; - - fn from_str(s: &str) -> Result<Color, ParseColorError> { - match &*s.to_lowercase() { - "black" => Ok(Color::Black), - "blue" => Ok(Color::Blue), - "green" => Ok(Color::Green), - "red" => Ok(Color::Red), - "cyan" => Ok(Color::Cyan), - "magenta" => Ok(Color::Magenta), - "yellow" => Ok(Color::Yellow), - "white" => Ok(Color::White), - _ => Color::from_str_numeric(s), - } - } -} - -struct LossyStandardStream<W> { - wtr: W, - #[cfg(windows)] - is_console: bool, -} - -impl<W: io::Write> LossyStandardStream<W> { - #[cfg(not(windows))] - fn new(wtr: W) -> LossyStandardStream<W> { - LossyStandardStream { wtr: wtr } - } - - #[cfg(windows)] - fn new(wtr: W) -> LossyStandardStream<W> { - LossyStandardStream { wtr: wtr, is_console: false } - } - - #[cfg(not(windows))] - fn wrap<Q: io::Write>(&self, wtr: Q) -> LossyStandardStream<Q> { - LossyStandardStream::new(wtr) - } - - #[cfg(windows)] - fn wrap<Q: io::Write>(&self, wtr: Q) -> LossyStandardStream<Q> { - LossyStandardStream::new(wtr).is_console(self.is_console) - } - - #[cfg(windows)] - fn is_console(mut self, yes: bool) -> LossyStandardStream<W> { - self.is_console = yes; - self - } - - fn get_ref(&self) -> &W { - &self.wtr - } -} - -impl<W: WriteColor> WriteColor for LossyStandardStream<W> { - fn supports_color(&self) -> bool { self.wtr.supports_color() } - fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { - self.wtr.set_color(spec) - } - fn reset(&mut self) -> io::Result<()> { self.wtr.reset() } -} - -impl<W: io::Write> io::Write for LossyStandardStream<W> { - #[cfg(not(windows))] - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - self.wtr.write(buf) - } - - #[cfg(windows)] - fn write(&mut self, buf: &[u8]) -> io::Result<usize> { - if self.is_console { - write_lossy_utf8(&mut self.wtr, buf) - } else { - self.wtr.write(buf) - } - } - - fn flush(&mut self) -> io::Result<()> { - self.wtr.flush() - } -} - -#[cfg(windows)] -fn write_lossy_utf8<W: io::Write>(mut w: W, buf: &[u8]) -> io::Result<usize> { - match ::std::str::from_utf8(buf) { - Ok(s) => w.write(s.as_bytes()), - Err(ref e) if e.valid_up_to() == 0 => { - w.write(b"\xEF\xBF\xBD")?; - Ok(1) - } - Err(e) => w.write(&buf[..e.valid_up_to()]), - } -} - -#[cfg(test)] -mod tests { - use super::{ - Ansi, Color, ParseColorError, ParseColorErrorKind, StandardStream, - }; - - fn assert_is_send<T: Send>() {} - - #[test] - fn standard_stream_is_send() { - assert_is_send::<StandardStream>(); - } - - #[test] - fn test_simple_parse_ok() { - let color = "green".parse::<Color>(); - assert_eq!(color, Ok(Color::Green)); - } - - #[test] - fn test_256_parse_ok() { - let color = "7".parse::<Color>(); - assert_eq!(color, Ok(Color::Ansi256(7))); - - let color = "32".parse::<Color>(); - assert_eq!(color, Ok(Color::Ansi256(32))); - - let color = "0xFF".parse::<Color>(); - assert_eq!(color, Ok(Color::Ansi256(0xFF))); - } - - #[test] - fn test_256_parse_err_out_of_range() { - let color = "256".parse::<Color>(); - assert_eq!(color, Err(ParseColorError { - kind: ParseColorErrorKind::InvalidAnsi256, - given: "256".to_string(), - })); - } - - #[test] - fn test_rgb_parse_ok() { - let color = "0,0,0".parse::<Color>(); - assert_eq!(color, Ok(Color::Rgb(0, 0, 0))); - - let color = "0,128,255".parse::<Color>(); - assert_eq!(color, Ok(Color::Rgb(0, 128, 255))); - - let color = "0x0,0x0,0x0".parse::<Color>(); - assert_eq!(color, Ok(Color::Rgb(0, 0, 0))); - - let color = "0x33,0x66,0xFF".parse::<Color>(); - assert_eq!(color, Ok(Color::Rgb(0x33, 0x66, 0xFF))); - } - - #[test] - fn test_rgb_parse_err_out_of_range() { - let color = "0,0,256".parse::<Color>(); - assert_eq!(color, Err(ParseColorError { - kind: ParseColorErrorKind::InvalidRgb, - given: "0,0,256".to_string(), - })); - } - - #[test] - fn test_rgb_parse_err_bad_format() { - let color = "0,0".parse::<Color>(); - assert_eq!(color, Err(ParseColorError { - kind: ParseColorErrorKind::InvalidRgb, - given: "0,0".to_string(), - })); - - let color = "not_a_color".parse::<Color>(); - assert_eq!(color, Err(ParseColorError { - kind: ParseColorErrorKind::InvalidName, - given: "not_a_color".to_string(), - })); - } - - #[test] - fn test_var_ansi_write_rgb() { - let mut buf = Ansi::new(vec![]); - let _ = buf.write_color(true, &Color::Rgb(254, 253, 255), false); - assert_eq!(buf.0, b"\x1B[38;2;254;253;255m"); - } - - #[test] - fn test_var_ansi_write_256() { - let mut buf = Ansi::new(vec![]); - let _ = buf.write_color(false, &Color::Ansi256(7), false); - assert_eq!(buf.0, b"\x1B[48;5;7m"); - - let mut buf = Ansi::new(vec![]); - let _ = buf.write_color(false, &Color::Ansi256(208), false); - assert_eq!(buf.0, b"\x1B[48;5;208m"); - } -} diff -Nru cargo-0.25.0/vendor/termcolor-0.3.5/UNLICENSE cargo-0.26.0/vendor/termcolor-0.3.5/UNLICENSE --- cargo-0.25.0/vendor/termcolor-0.3.5/UNLICENSE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.5/UNLICENSE 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -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 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. - -For more information, please refer to <http://unlicense.org/> diff -Nru cargo-0.25.0/vendor/termcolor-0.3.6/.cargo-checksum.json cargo-0.26.0/vendor/termcolor-0.3.6/.cargo-checksum.json --- cargo-0.25.0/vendor/termcolor-0.3.6/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.6/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"adc4587ead41bf016f11af03e55a624c06568b5a19db4e90fde573d805074f83"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/termcolor-0.3.6/Cargo.toml cargo-0.26.0/vendor/termcolor-0.3.6/Cargo.toml --- cargo-0.25.0/vendor/termcolor-0.3.6/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.6/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,29 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "termcolor" +version = "0.3.6" +authors = ["Andrew Gallant <jamslam@gmail.com>"] +description = "A simple cross platform library for writing colored text to a terminal.\n" +homepage = "https://github.com/BurntSushi/ripgrep/tree/master/termcolor" +documentation = "https://docs.rs/termcolor" +readme = "README.md" +keywords = ["windows", "win", "color", "ansi", "console"] +license = "Unlicense/MIT" +repository = "https://github.com/BurntSushi/ripgrep/tree/master/termcolor" + +[lib] +name = "termcolor" +bench = false +[target."cfg(windows)".dependencies.wincolor] +version = "0.1.6" diff -Nru cargo-0.25.0/vendor/termcolor-0.3.6/COPYING cargo-0.26.0/vendor/termcolor-0.3.6/COPYING --- cargo-0.25.0/vendor/termcolor-0.3.6/COPYING 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.6/COPYING 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3 @@ +This project is dual-licensed under the Unlicense and MIT licenses. + +You may use this code under the terms of either license. diff -Nru cargo-0.25.0/vendor/termcolor-0.3.6/LICENSE-MIT cargo-0.26.0/vendor/termcolor-0.3.6/LICENSE-MIT --- cargo-0.25.0/vendor/termcolor-0.3.6/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.6/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +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. diff -Nru cargo-0.25.0/vendor/termcolor-0.3.6/README.md cargo-0.26.0/vendor/termcolor-0.3.6/README.md --- cargo-0.25.0/vendor/termcolor-0.3.6/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.6/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,86 @@ +termcolor +========= +A simple cross platform library for writing colored text to a terminal. This +library writes colored text either using standard ANSI escape sequences or +by interacting with the Windows console. Several convenient abstractions +are provided for use in single-threaded or multi-threaded command line +applications. + +[![Linux build status](https://api.travis-ci.org/BurntSushi/ripgrep.png)](https://travis-ci.org/BurntSushi/ripgrep) +[![Windows build status](https://ci.appveyor.com/api/projects/status/github/BurntSushi/ripgrep?svg=true)](https://ci.appveyor.com/project/BurntSushi/ripgrep) +[![](https://img.shields.io/crates/v/termcolor.svg)](https://crates.io/crates/termcolor) + +Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). + +### Documentation + +[https://docs.rs/termcolor](https://docs.rs/termcolor) + +### Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +termcolor = "0.3" +``` + +and this to your crate root: + +```rust +extern crate termcolor; +``` + +### Organization + +The `WriteColor` trait extends the `io::Write` trait with methods for setting +colors or resetting them. + +`StandardStream` and `StandardStreamLock` both satisfy `WriteColor` and are +analogous to `std::io::Stdout` and `std::io::StdoutLock`, or `std::io::Stderr` +and `std::io::StderrLock`. + +`Buffer` is an in memory buffer that supports colored text. In a parallel +program, each thread might write to its own buffer. A buffer can be printed to +stdout or stderr using a `BufferWriter`. The advantage of this design is that +each thread can work in parallel on a buffer without having to synchronize +access to global resources such as the Windows console. Moreover, this design +also prevents interleaving of buffer output. + +`Ansi` and `NoColor` both satisfy `WriteColor` for arbitrary implementors of +`io::Write`. These types are useful when you know exactly what you need. An +analogous type for the Windows console is not provided since it cannot exist. + +### Example: using `StandardStream` + +The `StandardStream` type in this crate works similarly to `std::io::Stdout`, +except it is augmented with methods for coloring by the `WriteColor` trait. +For example, to write some green text: + +```rust +use std::io::Write; +use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; + +let mut stdout = StandardStream::stdout(ColorChoice::Always); +stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?; +writeln!(&mut stdout, "green text!")?; +``` + +### Example: using `BufferWriter` + +A `BufferWriter` can create buffers and write buffers to stdout or stderr. It +does *not* implement `io::Write` or `WriteColor` itself. Instead, `Buffer` +implements `io::Write` and `termcolor::WriteColor`. + +This example shows how to print some green text to stderr. + +```rust +use std::io::Write; +use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor}; + +let mut bufwtr = BufferWriter::stderr(ColorChoice::Always); +let mut buffer = bufwtr.buffer(); +buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?; +writeln!(&mut buffer, "green text!")?; +bufwtr.print(&buffer)?; +``` diff -Nru cargo-0.25.0/vendor/termcolor-0.3.6/src/lib.rs cargo-0.26.0/vendor/termcolor-0.3.6/src/lib.rs --- cargo-0.25.0/vendor/termcolor-0.3.6/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.6/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1697 @@ +/*! +This crate provides a cross platform abstraction for writing colored text to +a terminal. Colors are written using either ANSI escape sequences or by +communicating with a Windows console. Much of this API was motivated by use +inside command line applications, where colors or styles can be configured +by the end user and/or the environment. + +This crate also provides platform independent support for writing colored text +to an in memory buffer. While this is easy to do with ANSI escape sequences +(because they are in the buffer themselves), it is trickier to do with the +Windows console API, which requires synchronous communication. + +# Organization + +The `WriteColor` trait extends the `io::Write` trait with methods for setting +colors or resetting them. + +`StandardStream` and `StandardStreamLock` both satisfy `WriteColor` and are +analogous to `std::io::Stdout` and `std::io::StdoutLock`, or `std::io::Stderr` +and `std::io::StderrLock`. + +`Buffer` is an in memory buffer that supports colored text. In a parallel +program, each thread might write to its own buffer. A buffer can be printed to +using a `BufferWriter`. The advantage of this design is that each thread can +work in parallel on a buffer without having to synchronize access to global +resources such as the Windows console. Moreover, this design also prevents +interleaving of buffer output. + +`Ansi` and `NoColor` both satisfy `WriteColor` for arbitrary implementors of +`io::Write`. These types are useful when you know exactly what you need. An +analogous type for the Windows console is not provided since it cannot exist. + +# Example: using `StandardStream` + +The `StandardStream` type in this crate works similarly to `std::io::Stdout`, +except it is augmented with methods for coloring by the `WriteColor` trait. +For example, to write some green text: + +```rust,no_run +# fn test() -> Result<(), Box<::std::error::Error>> { +use std::io::Write; +use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; + +let mut stdout = StandardStream::stdout(ColorChoice::Always); +stdout.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?; +writeln!(&mut stdout, "green text!")?; +# Ok(()) } +``` + +# Example: using `BufferWriter` + +A `BufferWriter` can create buffers and write buffers to stdout or stderr. It +does *not* implement `io::Write` or `WriteColor` itself. Instead, `Buffer` +implements `io::Write` and `io::WriteColor`. + +This example shows how to print some green text to stderr. + +```rust,no_run +# fn test() -> Result<(), Box<::std::error::Error>> { +use std::io::Write; +use termcolor::{BufferWriter, Color, ColorChoice, ColorSpec, WriteColor}; + +let mut bufwtr = BufferWriter::stderr(ColorChoice::Always); +let mut buffer = bufwtr.buffer(); +buffer.set_color(ColorSpec::new().set_fg(Some(Color::Green)))?; +writeln!(&mut buffer, "green text!")?; +bufwtr.print(&buffer)?; +# Ok(()) } +``` +*/ + +#![deny(missing_docs)] + +#[cfg(windows)] +extern crate wincolor; + +use std::env; +use std::error; +use std::fmt; +use std::io::{self, Write}; +use std::str::FromStr; +#[cfg(windows)] +use std::sync::{Mutex, MutexGuard}; +use std::sync::atomic::{AtomicBool, Ordering}; + +/// This trait describes the behavior of writers that support colored output. +pub trait WriteColor: io::Write { + /// Returns true if and only if the underlying writer supports colors. + fn supports_color(&self) -> bool; + + /// Set the color settings of the writer. + /// + /// Subsequent writes to this writer will use these settings until either + /// `reset` is called or new color settings are set. + /// + /// If there was a problem setting the color settings, then an error is + /// returned. + fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()>; + + /// Reset the current color settings to their original settings. + /// + /// If there was a problem resetting the color settings, then an error is + /// returned. + fn reset(&mut self) -> io::Result<()>; +} + +impl<'a, T: ?Sized + WriteColor> WriteColor for &'a mut T { + fn supports_color(&self) -> bool { (&**self).supports_color() } + fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { + (&mut **self).set_color(spec) + } + fn reset(&mut self) -> io::Result<()> { (&mut **self).reset() } +} + +/// ColorChoice represents the color preferences of an end user. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ColorChoice { + /// Try very hard to emit colors. This includes emitting ANSI colors + /// on Windows if the console API is unavailable. + Always, + /// AlwaysAnsi is like Always, except it never tries to use anything other + /// than emitting ANSI color codes. + AlwaysAnsi, + /// Try to use colors, but don't force the issue. If the console isn't + /// available on Windows, or if TERM=dumb, for example, then don't use + /// colors. + Auto, + /// Never emit colors. + Never, +} + +impl ColorChoice { + /// Returns true if we should attempt to write colored output. + #[cfg(not(windows))] + fn should_attempt_color(&self) -> bool { + match *self { + ColorChoice::Always => true, + ColorChoice::AlwaysAnsi => true, + ColorChoice::Never => false, + ColorChoice::Auto => { + match env::var("TERM") { + Err(_) => false, + Ok(k) => k != "dumb", + } + } + } + } + + /// Returns true if we should attempt to write colored output. + #[cfg(windows)] + fn should_attempt_color(&self) -> bool { + match *self { + ColorChoice::Always => true, + ColorChoice::AlwaysAnsi => true, + ColorChoice::Never => false, + ColorChoice::Auto => { + match env::var("TERM") { + Err(_) => true, + Ok(k) => k != "dumb", + } + } + } + } + + /// Returns true if this choice should forcefully use ANSI color codes. + /// + /// It's possible that ANSI is still the correct choice even if this + /// returns false. + #[cfg(windows)] + fn should_ansi(&self) -> bool { + match *self { + ColorChoice::Always => false, + ColorChoice::AlwaysAnsi => true, + ColorChoice::Never => false, + ColorChoice::Auto => { + match env::var("TERM") { + Err(_) => false, + // cygwin doesn't seem to support ANSI escape sequences + // and instead has its own variety. However, the Windows + // console API may be available. + Ok(k) => k != "dumb" && k != "cygwin", + } + } + } + } +} + +/// `std::io` implements `Stdout` and `Stderr` (and their `Lock` variants) as +/// separate types, which makes it difficult to abstract over them. We use +/// some simple internal enum types to work around this. + +enum StandardStreamType { + Stdout, + Stderr, +} + +enum IoStandardStream { + Stdout(io::Stdout), + Stderr(io::Stderr), +} + +impl IoStandardStream { + fn new(sty: StandardStreamType) -> IoStandardStream { + match sty { + StandardStreamType::Stdout => { + IoStandardStream::Stdout(io::stdout()) + } + StandardStreamType::Stderr => { + IoStandardStream::Stderr(io::stderr()) + } + } + } + + fn lock(&self) -> IoStandardStreamLock { + match *self { + IoStandardStream::Stdout(ref s) => { + IoStandardStreamLock::StdoutLock(s.lock()) + } + IoStandardStream::Stderr(ref s) => { + IoStandardStreamLock::StderrLock(s.lock()) + } + } + } +} + +impl io::Write for IoStandardStream { + fn write(&mut self, b: &[u8]) -> io::Result<usize> { + match *self { + IoStandardStream::Stdout(ref mut s) => s.write(b), + IoStandardStream::Stderr(ref mut s) => s.write(b), + } + } + + fn flush(&mut self) -> io::Result<()> { + match *self { + IoStandardStream::Stdout(ref mut s) => s.flush(), + IoStandardStream::Stderr(ref mut s) => s.flush(), + } + } +} + +// Same rigmarole for the locked variants of the standard streams. + +enum IoStandardStreamLock<'a> { + StdoutLock(io::StdoutLock<'a>), + StderrLock(io::StderrLock<'a>), +} + +impl<'a> io::Write for IoStandardStreamLock<'a> { + fn write(&mut self, b: &[u8]) -> io::Result<usize> { + match *self { + IoStandardStreamLock::StdoutLock(ref mut s) => s.write(b), + IoStandardStreamLock::StderrLock(ref mut s) => s.write(b), + } + } + + fn flush(&mut self) -> io::Result<()> { + match *self { + IoStandardStreamLock::StdoutLock(ref mut s) => s.flush(), + IoStandardStreamLock::StderrLock(ref mut s) => s.flush(), + } + } +} + +/// Satisfies `io::Write` and `WriteColor`, and supports optional coloring +/// to either of the standard output streams, stdout and stderr. +pub struct StandardStream { + wtr: LossyStandardStream<WriterInner<IoStandardStream>>, +} + +/// `StandardStreamLock` is a locked reference to a `StandardStream`. +/// +/// This implements the `io::Write` and `WriteColor` traits, and is constructed +/// via the `Write::lock` method. +/// +/// The lifetime `'a` refers to the lifetime of the corresponding +/// `StandardStream`. +pub struct StandardStreamLock<'a> { + wtr: LossyStandardStream<WriterInnerLock<'a, IoStandardStreamLock<'a>>>, +} + +/// WriterInner is a (limited) generic representation of a writer. It is +/// limited because W should only ever be stdout/stderr on Windows. +enum WriterInner<W> { + NoColor(NoColor<W>), + Ansi(Ansi<W>), + #[cfg(windows)] + Windows { wtr: W, console: Mutex<wincolor::Console> }, +} + +/// WriterInnerLock is a (limited) generic representation of a writer. It is +/// limited because W should only ever be stdout/stderr on Windows. +enum WriterInnerLock<'a, W> { + NoColor(NoColor<W>), + Ansi(Ansi<W>), + /// What a gross hack. On Windows, we need to specify a lifetime for the + /// console when in a locked state, but obviously don't need to do that + /// on Unix, which makes the `'a` unused. To satisfy the compiler, we need + /// a PhantomData. + #[allow(dead_code)] + Unreachable(::std::marker::PhantomData<&'a ()>), + #[cfg(windows)] + Windows { wtr: W, console: MutexGuard<'a, wincolor::Console> }, +} + +impl StandardStream { + /// Create a new `StandardStream` with the given color preferences. + /// + /// The specific color/style settings can be configured when writing via + /// the `WriteColor` trait. + #[cfg(not(windows))] + fn create(sty: StandardStreamType, choice: ColorChoice) -> StandardStream { + let wtr = + if choice.should_attempt_color() { + WriterInner::Ansi(Ansi(IoStandardStream::new(sty))) + } else { + WriterInner::NoColor(NoColor(IoStandardStream::new(sty))) + }; + StandardStream { wtr: LossyStandardStream::new(wtr) } + } + + /// Create a new `StandardStream` with the given color preferences. + /// + /// If coloring is desired and a Windows console could not be found, then + /// ANSI escape sequences are used instead. + /// + /// The specific color/style settings can be configured when writing via + /// the `WriteColor` trait. + #[cfg(windows)] + fn create(sty: StandardStreamType, choice: ColorChoice) -> StandardStream { + let mut con = match sty { + StandardStreamType::Stdout => wincolor::Console::stdout(), + StandardStreamType::Stderr => wincolor::Console::stderr(), + }; + let is_win_console = con.is_ok(); + let is_console_virtual = con.as_mut().map(|con| { + con.set_virtual_terminal_processing(true).is_ok() + }).unwrap_or(false); + let wtr = + if choice.should_attempt_color() { + if choice.should_ansi() || is_console_virtual { + WriterInner::Ansi(Ansi(IoStandardStream::new(sty))) + } else if let Ok(console) = con { + WriterInner::Windows { + wtr: IoStandardStream::new(sty), + console: Mutex::new(console), + } + } else { + WriterInner::Ansi(Ansi(IoStandardStream::new(sty))) + } + } else { + WriterInner::NoColor(NoColor(IoStandardStream::new(sty))) + }; + StandardStream { + wtr: LossyStandardStream::new(wtr).is_console(is_win_console), + } + } + + /// Create a new `StandardStream` with the given color preferences that + /// writes to standard output. + /// + /// On Windows, if coloring is desired and a Windows console could not be + /// found, then ANSI escape sequences are used instead. + /// + /// The specific color/style settings can be configured when writing via + /// the `WriteColor` trait. + pub fn stdout(choice: ColorChoice) -> StandardStream { + StandardStream::create(StandardStreamType::Stdout, choice) + } + + /// Create a new `StandardStream` with the given color preferences that + /// writes to standard error. + /// + /// On Windows, if coloring is desired and a Windows console could not be + /// found, then ANSI escape sequences are used instead. + /// + /// The specific color/style settings can be configured when writing via + /// the `WriteColor` trait. + pub fn stderr(choice: ColorChoice) -> StandardStream { + StandardStream::create(StandardStreamType::Stderr, choice) + } + + /// Lock the underlying writer. + /// + /// The lock guard returned also satisfies `io::Write` and + /// `WriteColor`. + /// + /// This method is **not reentrant**. It may panic if `lock` is called + /// while a `StandardStreamLock` is still alive. + pub fn lock(&self) -> StandardStreamLock { + StandardStreamLock::from_stream(self) + } +} + +impl<'a> StandardStreamLock<'a> { + #[cfg(not(windows))] + fn from_stream(stream: &StandardStream) -> StandardStreamLock { + let locked = match *stream.wtr.get_ref() { + WriterInner::NoColor(ref w) => { + WriterInnerLock::NoColor(NoColor(w.0.lock())) + } + WriterInner::Ansi(ref w) => { + WriterInnerLock::Ansi(Ansi(w.0.lock())) + } + }; + StandardStreamLock { wtr: stream.wtr.wrap(locked) } + } + + #[cfg(windows)] + fn from_stream(stream: &StandardStream) -> StandardStreamLock { + let locked = match *stream.wtr.get_ref() { + WriterInner::NoColor(ref w) => { + WriterInnerLock::NoColor(NoColor(w.0.lock())) + } + WriterInner::Ansi(ref w) => { + WriterInnerLock::Ansi(Ansi(w.0.lock())) + } + #[cfg(windows)] + WriterInner::Windows { ref wtr, ref console } => { + WriterInnerLock::Windows { + wtr: wtr.lock(), + console: console.lock().unwrap(), + } + } + }; + StandardStreamLock { wtr: stream.wtr.wrap(locked) } + } +} + +impl io::Write for StandardStream { + fn write(&mut self, b: &[u8]) -> io::Result<usize> { self.wtr.write(b) } + fn flush(&mut self) -> io::Result<()> { self.wtr.flush() } +} + +impl WriteColor for StandardStream { + fn supports_color(&self) -> bool { self.wtr.supports_color() } + fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { + self.wtr.set_color(spec) + } + fn reset(&mut self) -> io::Result<()> { self.wtr.reset() } +} + +impl<'a> io::Write for StandardStreamLock<'a> { + fn write(&mut self, b: &[u8]) -> io::Result<usize> { self.wtr.write(b) } + fn flush(&mut self) -> io::Result<()> { self.wtr.flush() } +} + +impl<'a> WriteColor for StandardStreamLock<'a> { + fn supports_color(&self) -> bool { self.wtr.supports_color() } + fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { + self.wtr.set_color(spec) + } + fn reset(&mut self) -> io::Result<()> { self.wtr.reset() } +} + +impl<W: io::Write> io::Write for WriterInner<W> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + match *self { + WriterInner::NoColor(ref mut wtr) => wtr.write(buf), + WriterInner::Ansi(ref mut wtr) => wtr.write(buf), + #[cfg(windows)] + WriterInner::Windows { ref mut wtr, .. } => wtr.write(buf), + } + } + + fn flush(&mut self) -> io::Result<()> { + match *self { + WriterInner::NoColor(ref mut wtr) => wtr.flush(), + WriterInner::Ansi(ref mut wtr) => wtr.flush(), + #[cfg(windows)] + WriterInner::Windows { ref mut wtr, .. } => wtr.flush(), + } + } +} + +impl<W: io::Write> WriteColor for WriterInner<W> { + fn supports_color(&self) -> bool { + match *self { + WriterInner::NoColor(_) => false, + WriterInner::Ansi(_) => true, + #[cfg(windows)] + WriterInner::Windows { .. } => true, + } + } + + fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { + match *self { + WriterInner::NoColor(ref mut wtr) => wtr.set_color(spec), + WriterInner::Ansi(ref mut wtr) => wtr.set_color(spec), + #[cfg(windows)] + WriterInner::Windows { ref mut wtr, ref console } => { + wtr.flush()?; + let mut console = console.lock().unwrap(); + spec.write_console(&mut *console) + } + } + } + + fn reset(&mut self) -> io::Result<()> { + match *self { + WriterInner::NoColor(ref mut wtr) => wtr.reset(), + WriterInner::Ansi(ref mut wtr) => wtr.reset(), + #[cfg(windows)] + WriterInner::Windows { ref mut wtr, ref mut console } => { + wtr.flush()?; + console.lock().unwrap().reset()?; + Ok(()) + } + } + } +} + +impl<'a, W: io::Write> io::Write for WriterInnerLock<'a, W> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + match *self { + WriterInnerLock::Unreachable(_) => unreachable!(), + WriterInnerLock::NoColor(ref mut wtr) => wtr.write(buf), + WriterInnerLock::Ansi(ref mut wtr) => wtr.write(buf), + #[cfg(windows)] + WriterInnerLock::Windows { ref mut wtr, .. } => wtr.write(buf), + } + } + + fn flush(&mut self) -> io::Result<()> { + match *self { + WriterInnerLock::Unreachable(_) => unreachable!(), + WriterInnerLock::NoColor(ref mut wtr) => wtr.flush(), + WriterInnerLock::Ansi(ref mut wtr) => wtr.flush(), + #[cfg(windows)] + WriterInnerLock::Windows { ref mut wtr, .. } => wtr.flush(), + } + } +} + +impl<'a, W: io::Write> WriteColor for WriterInnerLock<'a, W> { + fn supports_color(&self) -> bool { + match *self { + WriterInnerLock::Unreachable(_) => unreachable!(), + WriterInnerLock::NoColor(_) => false, + WriterInnerLock::Ansi(_) => true, + #[cfg(windows)] + WriterInnerLock::Windows { .. } => true, + } + } + + fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { + match *self { + WriterInnerLock::Unreachable(_) => unreachable!(), + WriterInnerLock::NoColor(ref mut wtr) => wtr.set_color(spec), + WriterInnerLock::Ansi(ref mut wtr) => wtr.set_color(spec), + #[cfg(windows)] + WriterInnerLock::Windows { ref mut wtr, ref mut console } => { + wtr.flush()?; + spec.write_console(console) + } + } + } + + fn reset(&mut self) -> io::Result<()> { + match *self { + WriterInnerLock::Unreachable(_) => unreachable!(), + WriterInnerLock::NoColor(ref mut wtr) => wtr.reset(), + WriterInnerLock::Ansi(ref mut wtr) => wtr.reset(), + #[cfg(windows)] + WriterInnerLock::Windows { ref mut wtr, ref mut console } => { + wtr.flush()?; + console.reset()?; + Ok(()) + } + } + } +} + +/// Writes colored buffers to stdout or stderr. +/// +/// Writable buffers can be obtained by calling `buffer` on a `BufferWriter`. +/// +/// This writer works with terminals that support ANSI escape sequences or +/// with a Windows console. +/// +/// It is intended for a `BufferWriter` to be put in an `Arc` and written to +/// from multiple threads simultaneously. +pub struct BufferWriter { + stream: LossyStandardStream<IoStandardStream>, + printed: AtomicBool, + separator: Option<Vec<u8>>, + color_choice: ColorChoice, + #[cfg(windows)] + console: Option<Mutex<wincolor::Console>>, +} + +impl BufferWriter { + /// Create a new `BufferWriter` that writes to a standard stream with the + /// given color preferences. + /// + /// The specific color/style settings can be configured when writing to + /// the buffers themselves. + #[cfg(not(windows))] + fn create(sty: StandardStreamType, choice: ColorChoice) -> BufferWriter { + BufferWriter { + stream: LossyStandardStream::new(IoStandardStream::new(sty)), + printed: AtomicBool::new(false), + separator: None, + color_choice: choice, + } + } + + /// Create a new `BufferWriter` that writes to a standard stream with the + /// given color preferences. + /// + /// If coloring is desired and a Windows console could not be found, then + /// ANSI escape sequences are used instead. + /// + /// The specific color/style settings can be configured when writing to + /// the buffers themselves. + #[cfg(windows)] + fn create(sty: StandardStreamType, choice: ColorChoice) -> BufferWriter { + let mut con = match sty { + StandardStreamType::Stdout => wincolor::Console::stdout(), + StandardStreamType::Stderr => wincolor::Console::stderr(), + }.ok(); + let is_console_virtual = con.as_mut().map(|con| { + con.set_virtual_terminal_processing(true).is_ok() + }).unwrap_or(false); + // If we can enable ANSI on Windows, then we don't need the console + // anymore. + if is_console_virtual { + con = None; + } + let stream = LossyStandardStream::new(IoStandardStream::new(sty)) + .is_console(con.is_some()); + BufferWriter { + stream: stream, + printed: AtomicBool::new(false), + separator: None, + color_choice: choice, + console: con.map(Mutex::new), + } + } + + /// Create a new `BufferWriter` that writes to stdout with the given + /// color preferences. + /// + /// On Windows, if coloring is desired and a Windows console could not be + /// found, then ANSI escape sequences are used instead. + /// + /// The specific color/style settings can be configured when writing to + /// the buffers themselves. + pub fn stdout(choice: ColorChoice) -> BufferWriter { + BufferWriter::create(StandardStreamType::Stdout, choice) + } + + /// Create a new `BufferWriter` that writes to stderr with the given + /// color preferences. + /// + /// On Windows, if coloring is desired and a Windows console could not be + /// found, then ANSI escape sequences are used instead. + /// + /// The specific color/style settings can be configured when writing to + /// the buffers themselves. + pub fn stderr(choice: ColorChoice) -> BufferWriter { + BufferWriter::create(StandardStreamType::Stderr, choice) + } + + /// If set, the separator given is printed between buffers. By default, no + /// separator is printed. + /// + /// The default value is `None`. + pub fn separator(&mut self, sep: Option<Vec<u8>>) { + self.separator = sep; + } + + /// Creates a new `Buffer` with the current color preferences. + /// + /// A `Buffer` satisfies both `io::Write` and `WriteColor`. A `Buffer` can + /// be printed using the `print` method. + #[cfg(not(windows))] + pub fn buffer(&self) -> Buffer { + Buffer::new(self.color_choice) + } + + /// Creates a new `Buffer` with the current color preferences. + /// + /// A `Buffer` satisfies both `io::Write` and `WriteColor`. A `Buffer` can + /// be printed using the `print` method. + #[cfg(windows)] + pub fn buffer(&self) -> Buffer { + Buffer::new(self.color_choice, self.console.is_some()) + } + + /// Prints the contents of the given buffer. + /// + /// It is safe to call this from multiple threads simultaneously. In + /// particular, all buffers are written atomically. No interleaving will + /// occur. + pub fn print(&self, buf: &Buffer) -> io::Result<()> { + if buf.is_empty() { + return Ok(()); + } + let mut stream = self.stream.wrap(self.stream.get_ref().lock()); + if let Some(ref sep) = self.separator { + if self.printed.load(Ordering::SeqCst) { + stream.write_all(sep)?; + stream.write_all(b"\n")?; + } + } + match buf.0 { + BufferInner::NoColor(ref b) => stream.write_all(&b.0)?, + BufferInner::Ansi(ref b) => stream.write_all(&b.0)?, + #[cfg(windows)] + BufferInner::Windows(ref b) => { + // We guarantee by construction that we have a console here. + // Namely, a BufferWriter is the only way to produce a Buffer. + let console_mutex = self.console.as_ref() + .expect("got Windows buffer but have no Console"); + let mut console = console_mutex.lock().unwrap(); + b.print(&mut *console, &mut stream)?; + } + } + self.printed.store(true, Ordering::SeqCst); + Ok(()) + } +} + +/// Write colored text to memory. +/// +/// `Buffer` is a platform independent abstraction for printing colored text to +/// an in memory buffer. When the buffer is printed using a `BufferWriter`, the +/// color information will be applied to the output device (a tty on Unix and a +/// console on Windows). +/// +/// A `Buffer` is typically created by calling the `BufferWriter.buffer` +/// method, which will take color preferences and the environment into +/// account. However, buffers can also be manually created using `no_color`, +/// `ansi` or `console` (on Windows). +pub struct Buffer(BufferInner); + +/// BufferInner is an enumeration of different buffer types. +enum BufferInner { + /// No coloring information should be applied. This ignores all coloring + /// directives. + NoColor(NoColor<Vec<u8>>), + /// Apply coloring using ANSI escape sequences embedded into the buffer. + Ansi(Ansi<Vec<u8>>), + /// Apply coloring using the Windows console APIs. This buffer saves + /// color information in memory and only interacts with the console when + /// the buffer is printed. + #[cfg(windows)] + Windows(WindowsBuffer), +} + +impl Buffer { + /// Create a new buffer with the given color settings. + #[cfg(not(windows))] + fn new(choice: ColorChoice) -> Buffer { + if choice.should_attempt_color() { + Buffer::ansi() + } else { + Buffer::no_color() + } + } + + /// Create a new buffer with the given color settings. + /// + /// On Windows, one can elect to create a buffer capable of being written + /// to a console. Only enable it if a console is available. + /// + /// If coloring is desired and `console` is false, then ANSI escape + /// sequences are used instead. + #[cfg(windows)] + fn new(choice: ColorChoice, console: bool) -> Buffer { + if choice.should_attempt_color() { + if !console || choice.should_ansi() { + Buffer::ansi() + } else { + Buffer::console() + } + } else { + Buffer::no_color() + } + } + + /// Create a buffer that drops all color information. + pub fn no_color() -> Buffer { + Buffer(BufferInner::NoColor(NoColor(vec![]))) + } + + /// Create a buffer that uses ANSI escape sequences. + pub fn ansi() -> Buffer { + Buffer(BufferInner::Ansi(Ansi(vec![]))) + } + + /// Create a buffer that can be written to a Windows console. + #[cfg(windows)] + pub fn console() -> Buffer { + Buffer(BufferInner::Windows(WindowsBuffer::new())) + } + + /// Returns true if and only if this buffer is empty. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns the length of this buffer in bytes. + pub fn len(&self) -> usize { + match self.0 { + BufferInner::NoColor(ref b) => b.0.len(), + BufferInner::Ansi(ref b) => b.0.len(), + #[cfg(windows)] + BufferInner::Windows(ref b) => b.buf.len(), + } + } + + /// Clears this buffer. + pub fn clear(&mut self) { + match self.0 { + BufferInner::NoColor(ref mut b) => b.0.clear(), + BufferInner::Ansi(ref mut b) => b.0.clear(), + #[cfg(windows)] + BufferInner::Windows(ref mut b) => b.clear(), + } + } + + /// Consume this buffer and return the underlying raw data. + /// + /// On Windows, this unrecoverably drops all color information associated + /// with the buffer. + pub fn into_inner(self) -> Vec<u8> { + match self.0 { + BufferInner::NoColor(b) => b.0, + BufferInner::Ansi(b) => b.0, + #[cfg(windows)] + BufferInner::Windows(b) => b.buf, + } + } + + /// Return the underlying data of the buffer. + pub fn as_slice(&self) -> &[u8] { + match self.0 { + BufferInner::NoColor(ref b) => &b.0, + BufferInner::Ansi(ref b) => &b.0, + #[cfg(windows)] + BufferInner::Windows(ref b) => &b.buf, + } + } + + /// Return the underlying data of the buffer as a mutable slice. + pub fn as_mut_slice(&mut self) -> &mut [u8] { + match self.0 { + BufferInner::NoColor(ref mut b) => &mut b.0, + BufferInner::Ansi(ref mut b) => &mut b.0, + #[cfg(windows)] + BufferInner::Windows(ref mut b) => &mut b.buf, + } + } +} + +impl io::Write for Buffer { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + match self.0 { + BufferInner::NoColor(ref mut w) => w.write(buf), + BufferInner::Ansi(ref mut w) => w.write(buf), + #[cfg(windows)] + BufferInner::Windows(ref mut w) => w.write(buf), + } + } + + fn flush(&mut self) -> io::Result<()> { + match self.0 { + BufferInner::NoColor(ref mut w) => w.flush(), + BufferInner::Ansi(ref mut w) => w.flush(), + #[cfg(windows)] + BufferInner::Windows(ref mut w) => w.flush(), + } + } +} + +impl WriteColor for Buffer { + fn supports_color(&self) -> bool { + match self.0 { + BufferInner::NoColor(_) => false, + BufferInner::Ansi(_) => true, + #[cfg(windows)] + BufferInner::Windows(_) => true, + } + } + + fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { + match self.0 { + BufferInner::NoColor(ref mut w) => w.set_color(spec), + BufferInner::Ansi(ref mut w) => w.set_color(spec), + #[cfg(windows)] + BufferInner::Windows(ref mut w) => w.set_color(spec), + } + } + + fn reset(&mut self) -> io::Result<()> { + match self.0 { + BufferInner::NoColor(ref mut w) => w.reset(), + BufferInner::Ansi(ref mut w) => w.reset(), + #[cfg(windows)] + BufferInner::Windows(ref mut w) => w.reset(), + } + } +} + +/// Satisfies `WriteColor` but ignores all color options. +pub struct NoColor<W>(W); + +impl<W: Write> NoColor<W> { + /// Create a new writer that satisfies `WriteColor` but drops all color + /// information. + pub fn new(wtr: W) -> NoColor<W> { NoColor(wtr) } + + /// Consume this `NoColor` value and return the inner writer. + pub fn into_inner(self) -> W { self.0 } + + /// Return a reference to the inner writer. + pub fn get_ref(&self) -> &W { &self.0 } + + /// Return a mutable reference to the inner writer. + pub fn get_mut(&mut self) -> &mut W { &mut self.0 } +} + +impl<W: io::Write> io::Write for NoColor<W> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.0.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } +} + +impl<W: io::Write> WriteColor for NoColor<W> { + fn supports_color(&self) -> bool { false } + fn set_color(&mut self, _: &ColorSpec) -> io::Result<()> { Ok(()) } + fn reset(&mut self) -> io::Result<()> { Ok(()) } +} + +/// Satisfies `WriteColor` using standard ANSI escape sequences. +pub struct Ansi<W>(W); + +impl<W: Write> Ansi<W> { + /// Create a new writer that satisfies `WriteColor` using standard ANSI + /// escape sequences. + pub fn new(wtr: W) -> Ansi<W> { Ansi(wtr) } + + /// Consume this `Ansi` value and return the inner writer. + pub fn into_inner(self) -> W { self.0 } + + /// Return a reference to the inner writer. + pub fn get_ref(&self) -> &W { &self.0 } + + /// Return a mutable reference to the inner writer. + pub fn get_mut(&mut self) -> &mut W { &mut self.0 } +} + +impl<W: io::Write> io::Write for Ansi<W> { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.0.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } +} + +impl<W: io::Write> WriteColor for Ansi<W> { + fn supports_color(&self) -> bool { true } + + fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { + self.reset()?; + if spec.bold { + self.write_str("\x1B[1m")?; + } + if spec.underline { + self.write_str("\x1B[4m")?; + } + if let Some(ref c) = spec.fg_color { + self.write_color(true, c, spec.intense)?; + } + if let Some(ref c) = spec.bg_color { + self.write_color(false, c, spec.intense)?; + } + Ok(()) + } + + fn reset(&mut self) -> io::Result<()> { + self.write_str("\x1B[0m") + } +} + +impl<W: io::Write> Ansi<W> { + fn write_str(&mut self, s: &str) -> io::Result<()> { + self.write_all(s.as_bytes()) + } + + fn write_color( + &mut self, + fg: bool, + c: &Color, + intense: bool, + ) -> io::Result<()> { + macro_rules! write_intense { + ($clr:expr) => { + if fg { + self.write_str(concat!("\x1B[38;5;", $clr, "m")) + } else { + self.write_str(concat!("\x1B[48;5;", $clr, "m")) + } + } + } + macro_rules! write_normal { + ($clr:expr) => { + if fg { + self.write_str(concat!("\x1B[3", $clr, "m")) + } else { + self.write_str(concat!("\x1B[4", $clr, "m")) + } + } + } + macro_rules! write_var_ansi_code { + ($pre:expr, $($code:expr),+) => {{ + // The loop generates at worst a literal of the form + // '255,255,255m' which is 12-bytes. + // The largest `pre` expression we currently use is 7 bytes. + // This gives us the maximum of 19-bytes for our work buffer. + let pre_len = $pre.len(); + assert!(pre_len <= 7); + let mut fmt = [0u8; 19]; + fmt[..pre_len].copy_from_slice($pre); + let mut i = pre_len - 1; + $( + let c1: u8 = ($code / 100) % 10; + let c2: u8 = ($code / 10) % 10; + let c3: u8 = $code % 10; + let mut printed = false; + + if c1 != 0 { + printed = true; + i += 1; + fmt[i] = b'0' + c1; + } + if c2 != 0 || printed { + i += 1; + fmt[i] = b'0' + c2; + } + // If we received a zero value we must still print a value. + i += 1; + fmt[i] = b'0' + c3; + i += 1; + fmt[i] = b';'; + )+ + + fmt[i] = b'm'; + self.write_all(&fmt[0..i+1]) + }} + } + macro_rules! write_custom { + ($ansi256:expr) => { + if fg { + write_var_ansi_code!(b"\x1B[38;5;", $ansi256) + } else { + write_var_ansi_code!(b"\x1B[48;5;", $ansi256) + } + }; + + ($r:expr, $g:expr, $b:expr) => {{ + if fg { + write_var_ansi_code!(b"\x1B[38;2;", $r, $g, $b) + } else { + write_var_ansi_code!(b"\x1B[48;2;", $r, $g, $b) + } + }}; + } + if intense { + match *c { + Color::Black => write_intense!("8"), + Color::Blue => write_intense!("12"), + Color::Green => write_intense!("10"), + Color::Red => write_intense!("9"), + Color::Cyan => write_intense!("14"), + Color::Magenta => write_intense!("13"), + Color::Yellow => write_intense!("11"), + Color::White => write_intense!("15"), + Color::Ansi256(c) => write_custom!(c), + Color::Rgb(r, g, b) => write_custom!(r, g, b), + Color::__Nonexhaustive => unreachable!(), + } + } else { + match *c { + Color::Black => write_normal!("0"), + Color::Blue => write_normal!("4"), + Color::Green => write_normal!("2"), + Color::Red => write_normal!("1"), + Color::Cyan => write_normal!("6"), + Color::Magenta => write_normal!("5"), + Color::Yellow => write_normal!("3"), + Color::White => write_normal!("7"), + Color::Ansi256(c) => write_custom!(c), + Color::Rgb(r, g, b) => write_custom!(r, g, b), + Color::__Nonexhaustive => unreachable!(), + } + } + } +} + +/// An in-memory buffer that provides Windows console coloring. +/// +/// This doesn't actually communicate with the Windows console. Instead, it +/// acts like a normal buffer but also saves the color information associated +/// with positions in the buffer. It is only when the buffer is written to the +/// console that coloring is actually applied. +/// +/// This is roughly isomorphic to the ANSI based approach (i.e., +/// `Ansi<Vec<u8>>`), except with ANSI, the color information is embedded +/// directly into the buffer. +/// +/// Note that there is no way to write something generic like +/// `WindowsConsole<W: io::Write>` since coloring on Windows is tied +/// specifically to the console APIs, and therefore can't work on arbitrary +/// writers. +#[cfg(windows)] +#[derive(Clone, Debug)] +struct WindowsBuffer { + /// The actual content that should be printed. + buf: Vec<u8>, + /// A sequence of position oriented color specifications. Namely, each + /// element is a position and a color spec, where the color spec should + /// be applied at the position inside of `buf`. + /// + /// A missing color spec implies the underlying console should be reset. + colors: Vec<(usize, Option<ColorSpec>)>, +} + +#[cfg(windows)] +impl WindowsBuffer { + /// Create a new empty buffer for Windows console coloring. + fn new() -> WindowsBuffer { + WindowsBuffer { + buf: vec![], + colors: vec![], + } + } + + /// Push the given color specification into this buffer. + /// + /// This has the effect of setting the given color information at the + /// current position in the buffer. + fn push(&mut self, spec: Option<ColorSpec>) { + let pos = self.buf.len(); + self.colors.push((pos, spec)); + } + + /// Print the contents to the given stream handle, and use the console + /// for coloring. + fn print( + &self, + console: &mut wincolor::Console, + stream: &mut LossyStandardStream<IoStandardStreamLock>, + ) -> io::Result<()> { + let mut last = 0; + for &(pos, ref spec) in &self.colors { + stream.write_all(&self.buf[last..pos])?; + stream.flush()?; + last = pos; + match *spec { + None => console.reset()?, + Some(ref spec) => spec.write_console(console)?, + } + } + stream.write_all(&self.buf[last..])?; + stream.flush() + } + + /// Clear the buffer. + fn clear(&mut self) { + self.buf.clear(); + self.colors.clear(); + } +} + +#[cfg(windows)] +impl io::Write for WindowsBuffer { + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.buf.extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[cfg(windows)] +impl WriteColor for WindowsBuffer { + fn supports_color(&self) -> bool { true } + + fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { + self.push(Some(spec.clone())); + Ok(()) + } + + fn reset(&mut self) -> io::Result<()> { + self.push(None); + Ok(()) + } +} + +/// A color specification. +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct ColorSpec { + fg_color: Option<Color>, + bg_color: Option<Color>, + bold: bool, + intense: bool, + underline: bool, +} + +impl ColorSpec { + /// Create a new color specification that has no colors or styles. + pub fn new() -> ColorSpec { + ColorSpec::default() + } + + /// Get the foreground color. + pub fn fg(&self) -> Option<&Color> { self.fg_color.as_ref() } + + /// Set the foreground color. + pub fn set_fg(&mut self, color: Option<Color>) -> &mut ColorSpec { + self.fg_color = color; + self + } + + /// Get the background color. + pub fn bg(&self) -> Option<&Color> { self.bg_color.as_ref() } + + /// Set the background color. + pub fn set_bg(&mut self, color: Option<Color>) -> &mut ColorSpec { + self.bg_color = color; + self + } + + /// Get whether this is bold or not. + /// + /// Note that the bold setting has no effect in a Windows console. + pub fn bold(&self) -> bool { self.bold } + + /// Set whether the text is bolded or not. + /// + /// Note that the bold setting has no effect in a Windows console. + pub fn set_bold(&mut self, yes: bool) -> &mut ColorSpec { + self.bold = yes; + self + } + + /// Get whether this is underline or not. + /// + /// Note that the underline setting has no effect in a Windows console. + pub fn underline(&self) -> bool { self.underline } + + /// Set whether the text is underlined or not. + /// + /// Note that the underline setting has no effect in a Windows console. + pub fn set_underline(&mut self, yes: bool) -> &mut ColorSpec { + self.underline = yes; + self + } + + /// Get whether this is intense or not. + /// + /// On Unix-like systems, this will output the ANSI escape sequence + /// that will print a high-intensity version of the color + /// specified. + /// + /// On Windows systems, this will output the ANSI escape sequence + /// that will print a brighter version of the color specified. + pub fn intense(&self) -> bool { self.intense } + + /// Set whether the text is intense or not. + /// + /// On Unix-like systems, this will output the ANSI escape sequence + /// that will print a high-intensity version of the color + /// specified. + /// + /// On Windows systems, this will output the ANSI escape sequence + /// that will print a brighter version of the color specified. + pub fn set_intense(&mut self, yes: bool) -> &mut ColorSpec { + self.intense = yes; + self + } + + /// Returns true if this color specification has no colors or styles. + pub fn is_none(&self) -> bool { + self.fg_color.is_none() && self.bg_color.is_none() + && !self.bold && !self.underline + } + + /// Clears this color specification so that it has no color/style settings. + pub fn clear(&mut self) { + self.fg_color = None; + self.bg_color = None; + self.bold = false; + self.underline = false; + } + + /// Writes this color spec to the given Windows console. + #[cfg(windows)] + fn write_console( + &self, + console: &mut wincolor::Console, + ) -> io::Result<()> { + use wincolor::Intense; + + let intense = if self.intense { Intense::Yes } else { Intense::No }; + + let fg_color = self.fg_color.as_ref().and_then(|c| c.to_windows()); + if let Some(color) = fg_color { + console.fg(intense, color)?; + } + + let bg_color = self.bg_color.as_ref().and_then(|c| c.to_windows()); + if let Some(color) = bg_color { + console.bg(intense, color)?; + } + Ok(()) + } +} + +/// The set of available colors for the terminal foreground/background. +/// +/// The `Ansi256` and `Rgb` colors will only output the correct codes when +/// paired with the `Ansi` `WriteColor` implementation. +/// +/// The `Ansi256` and `Rgb` color types are not supported when writing colors +/// on Windows using the console. If they are used on Windows, then they are +/// silently ignored and no colors will be emitted. +/// +/// This set may expand over time. +/// +/// This type has a `FromStr` impl that can parse colors from their human +/// readable form. The format is as follows: +/// +/// 1. Any of the explicitly listed colors in English. They are matched +/// case insensitively. +/// 2. A single 8-bit integer, in either decimal or hexadecimal format. +/// 3. A triple of 8-bit integers separated by a comma, where each integer is +/// in decimal or hexadecimal format. +/// +/// Hexadecimal numbers are written with a `0x` prefix. +#[allow(missing_docs)] +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Color { + Black, + Blue, + Green, + Red, + Cyan, + Magenta, + Yellow, + White, + Ansi256(u8), + Rgb(u8, u8, u8), + #[doc(hidden)] + __Nonexhaustive, +} + +impl Color { + /// Translate this color to a wincolor::Color. + #[cfg(windows)] + fn to_windows(&self) -> Option<wincolor::Color> { + match *self { + Color::Black => Some(wincolor::Color::Black), + Color::Blue => Some(wincolor::Color::Blue), + Color::Green => Some(wincolor::Color::Green), + Color::Red => Some(wincolor::Color::Red), + Color::Cyan => Some(wincolor::Color::Cyan), + Color::Magenta => Some(wincolor::Color::Magenta), + Color::Yellow => Some(wincolor::Color::Yellow), + Color::White => Some(wincolor::Color::White), + Color::Ansi256(_) => None, + Color::Rgb(_, _, _) => None, + Color::__Nonexhaustive => unreachable!(), + } + } + + /// Parses a numeric color string, either ANSI or RGB. + fn from_str_numeric(s: &str) -> Result<Color, ParseColorError> { + // The "ansi256" format is a single number (decimal or hex) + // corresponding to one of 256 colors. + // + // The "rgb" format is a triple of numbers (decimal or hex) delimited + // by a comma corresponding to one of 256^3 colors. + + fn parse_number(s: &str) -> Option<u8> { + use std::u8; + + if s.starts_with("0x") { + u8::from_str_radix(&s[2..], 16).ok() + } else { + u8::from_str_radix(s, 10).ok() + } + } + + let codes: Vec<&str> = s.split(',').collect(); + if codes.len() == 1 { + if let Some(n) = parse_number(&codes[0]) { + Ok(Color::Ansi256(n)) + } else { + if s.chars().all(|c| c.is_digit(16)) { + Err(ParseColorError { + kind: ParseColorErrorKind::InvalidAnsi256, + given: s.to_string(), + }) + } else { + Err(ParseColorError { + kind: ParseColorErrorKind::InvalidName, + given: s.to_string(), + }) + } + } + } else if codes.len() == 3 { + let mut v = vec![]; + for code in codes { + let n = parse_number(code).ok_or_else(|| { + ParseColorError { + kind: ParseColorErrorKind::InvalidRgb, + given: s.to_string(), + } + })?; + v.push(n); + } + Ok(Color::Rgb(v[0], v[1], v[2])) + } else { + Err(if s.contains(",") { + ParseColorError { + kind: ParseColorErrorKind::InvalidRgb, + given: s.to_string(), + } + } else { + ParseColorError { + kind: ParseColorErrorKind::InvalidName, + given: s.to_string(), + } + }) + } + } +} + +/// An error from parsing an invalid color specification. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct ParseColorError { + kind: ParseColorErrorKind, + given: String, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +enum ParseColorErrorKind { + InvalidName, + InvalidAnsi256, + InvalidRgb, +} + +impl ParseColorError { + /// Return the string that couldn't be parsed as a valid color. + pub fn invalid(&self) -> &str { &self.given } +} + +impl error::Error for ParseColorError { + fn description(&self) -> &str { + use self::ParseColorErrorKind::*; + match self.kind { + InvalidName => "unrecognized color name", + InvalidAnsi256 => "invalid ansi256 color number", + InvalidRgb => "invalid RGB color triple", + } + } +} + +impl fmt::Display for ParseColorError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use self::ParseColorErrorKind::*; + match self.kind { + InvalidName => { + write!(f, "unrecognized color name '{}'. Choose from: \ + black, blue, green, red, cyan, magenta, yellow, \ + white", + self.given) + } + InvalidAnsi256 => { + write!(f, "unrecognized ansi256 color number, \ + should be '[0-255]' (or a hex number), but is '{}'", + self.given) + } + InvalidRgb => { + write!(f, "unrecognized RGB color triple, \ + should be '[0-255],[0-255],[0-255]' (or a hex \ + triple), but is '{}'", self.given) + } + } + } +} + +impl FromStr for Color { + type Err = ParseColorError; + + fn from_str(s: &str) -> Result<Color, ParseColorError> { + match &*s.to_lowercase() { + "black" => Ok(Color::Black), + "blue" => Ok(Color::Blue), + "green" => Ok(Color::Green), + "red" => Ok(Color::Red), + "cyan" => Ok(Color::Cyan), + "magenta" => Ok(Color::Magenta), + "yellow" => Ok(Color::Yellow), + "white" => Ok(Color::White), + _ => Color::from_str_numeric(s), + } + } +} + +struct LossyStandardStream<W> { + wtr: W, + #[cfg(windows)] + is_console: bool, +} + +impl<W: io::Write> LossyStandardStream<W> { + #[cfg(not(windows))] + fn new(wtr: W) -> LossyStandardStream<W> { + LossyStandardStream { wtr: wtr } + } + + #[cfg(windows)] + fn new(wtr: W) -> LossyStandardStream<W> { + LossyStandardStream { wtr: wtr, is_console: false } + } + + #[cfg(not(windows))] + fn wrap<Q: io::Write>(&self, wtr: Q) -> LossyStandardStream<Q> { + LossyStandardStream::new(wtr) + } + + #[cfg(windows)] + fn wrap<Q: io::Write>(&self, wtr: Q) -> LossyStandardStream<Q> { + LossyStandardStream::new(wtr).is_console(self.is_console) + } + + #[cfg(windows)] + fn is_console(mut self, yes: bool) -> LossyStandardStream<W> { + self.is_console = yes; + self + } + + fn get_ref(&self) -> &W { + &self.wtr + } +} + +impl<W: WriteColor> WriteColor for LossyStandardStream<W> { + fn supports_color(&self) -> bool { self.wtr.supports_color() } + fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> { + self.wtr.set_color(spec) + } + fn reset(&mut self) -> io::Result<()> { self.wtr.reset() } +} + +impl<W: io::Write> io::Write for LossyStandardStream<W> { + #[cfg(not(windows))] + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + self.wtr.write(buf) + } + + #[cfg(windows)] + fn write(&mut self, buf: &[u8]) -> io::Result<usize> { + if self.is_console { + write_lossy_utf8(&mut self.wtr, buf) + } else { + self.wtr.write(buf) + } + } + + fn flush(&mut self) -> io::Result<()> { + self.wtr.flush() + } +} + +#[cfg(windows)] +fn write_lossy_utf8<W: io::Write>(mut w: W, buf: &[u8]) -> io::Result<usize> { + match ::std::str::from_utf8(buf) { + Ok(s) => w.write(s.as_bytes()), + Err(ref e) if e.valid_up_to() == 0 => { + w.write(b"\xEF\xBF\xBD")?; + Ok(1) + } + Err(e) => w.write(&buf[..e.valid_up_to()]), + } +} + +#[cfg(test)] +mod tests { + use super::{ + Ansi, Color, ParseColorError, ParseColorErrorKind, StandardStream, + }; + + fn assert_is_send<T: Send>() {} + + #[test] + fn standard_stream_is_send() { + assert_is_send::<StandardStream>(); + } + + #[test] + fn test_simple_parse_ok() { + let color = "green".parse::<Color>(); + assert_eq!(color, Ok(Color::Green)); + } + + #[test] + fn test_256_parse_ok() { + let color = "7".parse::<Color>(); + assert_eq!(color, Ok(Color::Ansi256(7))); + + let color = "32".parse::<Color>(); + assert_eq!(color, Ok(Color::Ansi256(32))); + + let color = "0xFF".parse::<Color>(); + assert_eq!(color, Ok(Color::Ansi256(0xFF))); + } + + #[test] + fn test_256_parse_err_out_of_range() { + let color = "256".parse::<Color>(); + assert_eq!(color, Err(ParseColorError { + kind: ParseColorErrorKind::InvalidAnsi256, + given: "256".to_string(), + })); + } + + #[test] + fn test_rgb_parse_ok() { + let color = "0,0,0".parse::<Color>(); + assert_eq!(color, Ok(Color::Rgb(0, 0, 0))); + + let color = "0,128,255".parse::<Color>(); + assert_eq!(color, Ok(Color::Rgb(0, 128, 255))); + + let color = "0x0,0x0,0x0".parse::<Color>(); + assert_eq!(color, Ok(Color::Rgb(0, 0, 0))); + + let color = "0x33,0x66,0xFF".parse::<Color>(); + assert_eq!(color, Ok(Color::Rgb(0x33, 0x66, 0xFF))); + } + + #[test] + fn test_rgb_parse_err_out_of_range() { + let color = "0,0,256".parse::<Color>(); + assert_eq!(color, Err(ParseColorError { + kind: ParseColorErrorKind::InvalidRgb, + given: "0,0,256".to_string(), + })); + } + + #[test] + fn test_rgb_parse_err_bad_format() { + let color = "0,0".parse::<Color>(); + assert_eq!(color, Err(ParseColorError { + kind: ParseColorErrorKind::InvalidRgb, + given: "0,0".to_string(), + })); + + let color = "not_a_color".parse::<Color>(); + assert_eq!(color, Err(ParseColorError { + kind: ParseColorErrorKind::InvalidName, + given: "not_a_color".to_string(), + })); + } + + #[test] + fn test_var_ansi_write_rgb() { + let mut buf = Ansi::new(vec![]); + let _ = buf.write_color(true, &Color::Rgb(254, 253, 255), false); + assert_eq!(buf.0, b"\x1B[38;2;254;253;255m"); + } + + #[test] + fn test_var_ansi_write_256() { + let mut buf = Ansi::new(vec![]); + let _ = buf.write_color(false, &Color::Ansi256(7), false); + assert_eq!(buf.0, b"\x1B[48;5;7m"); + + let mut buf = Ansi::new(vec![]); + let _ = buf.write_color(false, &Color::Ansi256(208), false); + assert_eq!(buf.0, b"\x1B[48;5;208m"); + } +} diff -Nru cargo-0.25.0/vendor/termcolor-0.3.6/UNLICENSE cargo-0.26.0/vendor/termcolor-0.3.6/UNLICENSE --- cargo-0.25.0/vendor/termcolor-0.3.6/UNLICENSE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/termcolor-0.3.6/UNLICENSE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +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 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. + +For more information, please refer to <http://unlicense.org/> diff -Nru cargo-0.25.0/vendor/toml-0.4.5/.cargo-checksum.json cargo-0.26.0/vendor/toml-0.4.5/.cargo-checksum.json --- cargo-0.25.0/vendor/toml-0.4.5/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"a7540f4ffc193e0d3c94121edb19b055670d369f77d5804db11ae053a45b6e7e"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/toml-0.4.5/Cargo.toml cargo-0.26.0/vendor/toml-0.4.5/Cargo.toml --- cargo-0.25.0/vendor/toml-0.4.5/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "toml" -version = "0.4.5" -authors = ["Alex Crichton <alex@alexcrichton.com>"] -description = "A native Rust encoder and decoder of TOML-formatted files and streams. Provides\nimplementations of the standard Serialize/Deserialize traits for TOML data to\nfacilitate deserializing and serializing Rust structures.\n" -homepage = "https://github.com/alexcrichton/toml-rs" -documentation = "https://docs.rs/toml" -readme = "README.md" -keywords = ["encoding"] -categories = ["config", "encoding", "parser-implementations"] -license = "MIT/Apache-2.0" -repository = "https://github.com/alexcrichton/toml-rs" -[dependencies.serde] -version = "1.0" -[dev-dependencies.serde_derive] -version = "1.0" - -[dev-dependencies.serde_json] -version = "1.0" -[badges.travis-ci] -repository = "alexcrichton/toml-rs" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/examples/decode.rs cargo-0.26.0/vendor/toml-0.4.5/examples/decode.rs --- cargo-0.25.0/vendor/toml-0.4.5/examples/decode.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/examples/decode.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,56 +0,0 @@ -//! An example showing off the usage of `Deserialize` to automatically decode -//! TOML into a Rust `struct` - -#![deny(warnings)] - -extern crate toml; -extern crate serde; -#[macro_use] -extern crate serde_derive; - -/// This is what we're going to decode into. Each field is optional, meaning -/// that it doesn't have to be present in TOML. -#[derive(Debug, Deserialize)] -struct Config { - global_string: Option<String>, - global_integer: Option<u64>, - server: Option<ServerConfig>, - peers: Option<Vec<PeerConfig>>, -} - -/// Sub-structs are decoded from tables, so this will decode from the `[server]` -/// table. -/// -/// Again, each field is optional, meaning they don't have to be present. -#[derive(Debug, Deserialize)] -struct ServerConfig { - ip: Option<String>, - port: Option<u64>, -} - -#[derive(Debug, Deserialize)] -struct PeerConfig { - ip: Option<String>, - port: Option<u64>, -} - -fn main() { - let toml_str = r#" - global_string = "test" - global_integer = 5 - - [server] - ip = "127.0.0.1" - port = 80 - - [[peers]] - ip = "127.0.0.1" - port = 8080 - - [[peers]] - ip = "127.0.0.1" - "#; - - let decoded: Config = toml::from_str(toml_str).unwrap(); - println!("{:#?}", decoded); -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/examples/toml2json.rs cargo-0.26.0/vendor/toml-0.4.5/examples/toml2json.rs --- cargo-0.25.0/vendor/toml-0.4.5/examples/toml2json.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/examples/toml2json.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,51 +0,0 @@ -#![deny(warnings)] - -extern crate toml; -extern crate serde_json; - -use std::fs::File; -use std::env; -use std::io; -use std::io::prelude::*; - -use toml::Value as Toml; -use serde_json::Value as Json; - -fn main() { - let mut args = env::args(); - let mut input = String::new(); - if args.len() > 1 { - let name = args.nth(1).unwrap(); - File::open(&name).and_then(|mut f| { - f.read_to_string(&mut input) - }).unwrap(); - } else { - io::stdin().read_to_string(&mut input).unwrap(); - } - - match input.parse() { - Ok(toml) => { - let json = convert(toml); - println!("{}", serde_json::to_string_pretty(&json).unwrap()); - } - Err(error) => println!("failed to parse TOML: {}", error), - } -} - -fn convert(toml: Toml) -> Json { - match toml { - Toml::String(s) => Json::String(s), - Toml::Integer(i) => Json::Number(i.into()), - Toml::Float(f) => { - let n = serde_json::Number::from_f64(f) - .expect("float infinite and nan not allowed"); - Json::Number(n) - } - Toml::Boolean(b) => Json::Bool(b), - Toml::Array(arr) => Json::Array(arr.into_iter().map(convert).collect()), - Toml::Table(table) => Json::Object(table.into_iter().map(|(k, v)| { - (k, convert(v)) - }).collect()), - Toml::Datetime(dt) => Json::String(dt.to_string()), - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/LICENSE-APACHE cargo-0.26.0/vendor/toml-0.4.5/LICENSE-APACHE --- cargo-0.25.0/vendor/toml-0.4.5/LICENSE-APACHE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 @@ -1,201 +0,0 @@ - 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. diff -Nru cargo-0.25.0/vendor/toml-0.4.5/LICENSE-MIT cargo-0.26.0/vendor/toml-0.4.5/LICENSE-MIT --- cargo-0.25.0/vendor/toml-0.4.5/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -Copyright (c) 2014 Alex Crichton - -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. diff -Nru cargo-0.25.0/vendor/toml-0.4.5/README.md cargo-0.26.0/vendor/toml-0.4.5/README.md --- cargo-0.25.0/vendor/toml-0.4.5/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,31 +0,0 @@ -# toml-rs - -[![Build Status](https://travis-ci.org/alexcrichton/toml-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/toml-rs) -[![Coverage Status](https://coveralls.io/repos/alexcrichton/toml-rs/badge.svg?branch=master&service=github)](https://coveralls.io/github/alexcrichton/toml-rs?branch=master) -[![Latest Version](https://img.shields.io/crates/v/toml.svg)](https://crates.io/crates/toml) -[![Documentation](https://docs.rs/toml/badge.svg)](https://docs.rs/toml) - -A [TOML][toml] decoder and encoder for Rust. This library is currently compliant -with the v0.4.0 version of TOML. This library will also likely continue to stay -up to date with the TOML specification as changes happen. - -[toml]: https://github.com/toml-lang/toml - -```toml -# Cargo.toml -[dependencies] -toml = "0.4" -``` - -This crate also supports serialization/deserialization through the -[serde](https://serde.rs) crate on crates.io. Currently the older `rustc-serialize` -crate is not supported in the 0.3+ series of the `toml` crate, but 0.2 can be -used for that support. - -# License - -`toml-rs` is primarily distributed under the terms of both the MIT license and -the Apache License (Version 2.0), with portions covered by various BSD-like -licenses. - -See LICENSE-APACHE, and LICENSE-MIT for details. diff -Nru cargo-0.25.0/vendor/toml-0.4.5/src/datetime.rs cargo-0.26.0/vendor/toml-0.4.5/src/datetime.rs --- cargo-0.25.0/vendor/toml-0.4.5/src/datetime.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/src/datetime.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,425 +0,0 @@ -use std::fmt; -use std::str::{self, FromStr}; -use std::error; - -use serde::{de, ser}; - -/// A parsed TOML datetime value -/// -/// This structure is intended to represent the datetime primitive type that can -/// be encoded into TOML documents. This type is a parsed version that contains -/// all metadata internally. -/// -/// Currently this type is intentionally conservative and only supports -/// `to_string` as an accessor. Over time though it's intended that it'll grow -/// more support! -/// -/// Note that if you're using `Deserialize` to deserialize a TOML document, you -/// can use this as a placeholder for where you're expecting a datetime to be -/// specified. -/// -/// Also note though that while this type implements `Serialize` and -/// `Deserialize` it's only recommended to use this type with the TOML format, -/// otherwise encoded in other formats it may look a little odd. -#[derive(PartialEq, Clone)] -pub struct Datetime { - date: Option<Date>, - time: Option<Time>, - offset: Option<Offset>, -} - -/// Error returned from parsing a `Datetime` in the `FromStr` implementation. -#[derive(Debug, Clone)] -pub struct DatetimeParseError { - _private: (), -} - -// Currently serde itself doesn't have a datetime type, so we map our `Datetime` -// to a special valid in the serde data model. Namely one with thiese special -// fields/struct names. -// -// In general the TOML encoder/decoder will catch this and not literally emit -// these strings but rather emit datetimes as they're intended. -pub const SERDE_STRUCT_FIELD_NAME: &'static str = "$__toml_private_datetime"; -pub const SERDE_STRUCT_NAME: &'static str = "$__toml_private_Datetime"; - -#[derive(PartialEq, Clone)] -struct Date { - year: u16, - month: u8, - day: u8, -} - -#[derive(PartialEq, Clone)] -struct Time { - hour: u8, - minute: u8, - second: u8, - nanosecond: u32, -} - -#[derive(PartialEq, Clone)] -enum Offset { - Z, - Custom { hours: i8, minutes: u8 }, -} - -impl fmt::Debug for Datetime { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(self, f) - } -} - -impl fmt::Display for Datetime { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if let Some(ref date) = self.date { - write!(f, "{}", date)?; - } - if let Some(ref time) = self.time { - if self.date.is_some() { - write!(f, "T")?; - } - write!(f, "{}", time)?; - } - if let Some(ref offset) = self.offset { - write!(f, "{}", offset)?; - } - Ok(()) - } -} - -impl fmt::Display for Date { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day) - } -} - -impl fmt::Display for Time { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)?; - if self.nanosecond != 0 { - let s = format!("{:09}", self.nanosecond); - write!(f, ".{}", s.trim_right_matches('0'))?; - } - Ok(()) - } -} - -impl fmt::Display for Offset { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Offset::Z => write!(f, "Z"), - Offset::Custom { hours, minutes } => { - write!(f, "{:+03}:{:02}", hours, minutes) - } - } - } -} - -impl FromStr for Datetime { - type Err = DatetimeParseError; - - fn from_str(date: &str) -> Result<Datetime, DatetimeParseError> { - // Accepted formats: - // - // 0000-00-00T00:00:00.00Z - // 0000-00-00T00:00:00.00 - // 0000-00-00 - // 00:00:00.00 - if date.len() < 3 { - return Err(DatetimeParseError { _private: () }) - } - let mut offset_allowed = true; - let mut chars = date.chars(); - - // First up, parse the full date if we can - let full_date = if chars.clone().nth(2) == Some(':') { - offset_allowed = false; - None - } else { - let y1 = digit(&mut chars)? as u16; - let y2 = digit(&mut chars)? as u16; - let y3 = digit(&mut chars)? as u16; - let y4 = digit(&mut chars)? as u16; - - match chars.next() { - Some('-') => {} - _ => return Err(DatetimeParseError { _private: () }), - } - - let m1 = digit(&mut chars)?; - let m2 = digit(&mut chars)?; - - match chars.next() { - Some('-') => {} - _ => return Err(DatetimeParseError { _private: () }), - } - - let d1 = digit(&mut chars)?; - let d2 = digit(&mut chars)?; - - let date = Date { - year: y1 * 1000 + y2 * 100 + y3 * 10 + y4, - month: m1 * 10 + m2, - day: d1 * 10 + d2, - }; - - if date.month < 1 || date.month > 12 { - return Err(DatetimeParseError { _private: () }) - } - if date.day < 1 || date.day > 31 { - return Err(DatetimeParseError { _private: () }) - } - - Some(date) - }; - - // Next parse the "partial-time" if available - let partial_time = if full_date.is_some() && - chars.clone().next() == Some('T') { - chars.next(); - true - } else { - full_date.is_none() - }; - - let time = if partial_time { - let h1 = digit(&mut chars)?; - let h2 = digit(&mut chars)?; - match chars.next() { - Some(':') => {} - _ => return Err(DatetimeParseError { _private: () }), - } - let m1 = digit(&mut chars)?; - let m2 = digit(&mut chars)?; - match chars.next() { - Some(':') => {} - _ => return Err(DatetimeParseError { _private: () }), - } - let s1 = digit(&mut chars)?; - let s2 = digit(&mut chars)?; - - let mut nanosecond = 0; - if chars.clone().next() == Some('.') { - chars.next(); - let whole = chars.as_str(); - - let mut end = whole.len(); - for (i, byte) in whole.bytes().enumerate() { - match byte { - b'0' ... b'9' => { - if i < 9 { - let p = 10_u32.pow(8 - i as u32); - nanosecond += p * (byte - b'0') as u32; - } - } - _ => { - end = i; - break; - } - } - } - if end == 0 { - return Err(DatetimeParseError { _private: () }) - } - chars = whole[end..].chars(); - } - - let time = Time { - hour: h1 * 10 + h2, - minute: m1 * 10 + m2, - second: s1 * 10 + s2, - nanosecond: nanosecond, - }; - - if time.hour > 24 { - return Err(DatetimeParseError { _private: () }) - } - if time.minute > 59 { - return Err(DatetimeParseError { _private: () }) - } - if time.second > 59 { - return Err(DatetimeParseError { _private: () }) - } - if time.nanosecond > 999_999_999 { - return Err(DatetimeParseError { _private: () }) - } - - Some(time) - } else { - offset_allowed = false; - None - }; - - // And finally, parse the offset - let offset = if offset_allowed { - let next = chars.clone().next(); - if next == Some('Z') { - chars.next(); - Some(Offset::Z) - } else if next.is_none() { - None - } else { - let sign = match next { - Some('+') => 1, - Some('-') => -1, - _ => return Err(DatetimeParseError { _private: () }), - }; - chars.next(); - let h1 = digit(&mut chars)? as i8; - let h2 = digit(&mut chars)? as i8; - match chars.next() { - Some(':') => {} - _ => return Err(DatetimeParseError { _private: () }), - } - let m1 = digit(&mut chars)?; - let m2 = digit(&mut chars)?; - - Some(Offset::Custom { - hours: sign * (h1 * 10 + h2), - minutes: m1 * 10 + m2, - }) - } - } else { - None - }; - - // Return an error if we didn't hit eof, otherwise return our parsed - // date - if chars.next().is_some() { - return Err(DatetimeParseError { _private: () }) - } - - Ok(Datetime { - date: full_date, - time: time, - offset: offset, - }) - } -} - -fn digit(chars: &mut str::Chars) -> Result<u8, DatetimeParseError> { - match chars.next() { - Some(c) if '0' <= c && c <= '9' => Ok(c as u8 - b'0'), - _ => Err(DatetimeParseError { _private: () }), - } -} - -impl ser::Serialize for Datetime { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where S: ser::Serializer - { - use serde::ser::SerializeStruct; - - let mut s = serializer.serialize_struct(SERDE_STRUCT_NAME, 1)?; - s.serialize_field(SERDE_STRUCT_FIELD_NAME, &self.to_string())?; - s.end() - } -} - -impl<'de> de::Deserialize<'de> for Datetime { - fn deserialize<D>(deserializer: D) -> Result<Datetime, D::Error> - where D: de::Deserializer<'de> - { - struct DatetimeVisitor; - - impl<'de> de::Visitor<'de> for DatetimeVisitor { - type Value = Datetime; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a TOML datetime") - } - - fn visit_map<V>(self, mut visitor: V) -> Result<Datetime, V::Error> - where V: de::MapAccess<'de> - { - let value = visitor.next_key::<DatetimeKey>()?; - if value.is_none() { - return Err(de::Error::custom("datetime key not found")) - } - let v: DatetimeFromString = visitor.next_value()?; - Ok(v.value) - - } - } - - static FIELDS: [&'static str; 1] = [SERDE_STRUCT_FIELD_NAME]; - deserializer.deserialize_struct(SERDE_STRUCT_NAME, - &FIELDS, - DatetimeVisitor) - } -} - -struct DatetimeKey; - -impl<'de> de::Deserialize<'de> for DatetimeKey { - fn deserialize<D>(deserializer: D) -> Result<DatetimeKey, D::Error> - where D: de::Deserializer<'de> - { - struct FieldVisitor; - - impl<'de> de::Visitor<'de> for FieldVisitor { - type Value = (); - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a valid datetime field") - } - - fn visit_str<E>(self, s: &str) -> Result<(), E> - where E: de::Error - { - if s == SERDE_STRUCT_FIELD_NAME { - Ok(()) - } else { - Err(de::Error::custom("expected field with custom name")) - } - } - } - - deserializer.deserialize_identifier(FieldVisitor)?; - Ok(DatetimeKey) - } -} - -pub struct DatetimeFromString { - pub value: Datetime, -} - -impl<'de> de::Deserialize<'de> for DatetimeFromString { - fn deserialize<D>(deserializer: D) -> Result<DatetimeFromString, D::Error> - where D: de::Deserializer<'de> - { - struct Visitor; - - impl<'de> de::Visitor<'de> for Visitor { - type Value = DatetimeFromString; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("string containing a datetime") - } - - fn visit_str<E>(self, s: &str) -> Result<DatetimeFromString, E> - where E: de::Error, - { - match s.parse() { - Ok(date) => Ok(DatetimeFromString { value: date }), - Err(e) => Err(de::Error::custom(e)), - } - } - } - - deserializer.deserialize_str(Visitor) - } -} - -impl fmt::Display for DatetimeParseError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - "failed to parse datetime".fmt(f) - } -} - -impl error::Error for DatetimeParseError { - fn description(&self) -> &str { - "failed to parse datetime" - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/src/de.rs cargo-0.26.0/vendor/toml-0.4.5/src/de.rs --- cargo-0.25.0/vendor/toml-0.4.5/src/de.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/src/de.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1327 +0,0 @@ -//! Deserializing TOML into Rust structures. -//! -//! This module contains all the Serde support for deserializing TOML documents -//! into Rust structures. Note that some top-level functions here are also -//! provided at the top of the crate. - -use std::borrow::Cow; -use std::error; -use std::fmt; -use std::str; -use std::vec; - -use serde::de; -use serde::de::IntoDeserializer; - -use tokens::{Tokenizer, Token, Error as TokenError}; -use datetime::{SERDE_STRUCT_FIELD_NAME, SERDE_STRUCT_NAME}; - -/// Deserializes a byte slice into a type. -/// -/// This function will attempt to interpret `bytes` as UTF-8 data and then -/// deserialize `T` from the TOML document provided. -pub fn from_slice<'de, T>(bytes: &'de [u8]) -> Result<T, Error> - where T: de::Deserialize<'de>, -{ - match str::from_utf8(bytes) { - Ok(s) => from_str(s), - Err(e) => Err(Error::custom(e.to_string())), - } -} - -/// Deserializes a string into a type. -/// -/// This function will attempt to interpret `s` as a TOML document and -/// deserialize `T` from the document. -/// -/// # Examples -/// -/// ``` -/// #[macro_use] -/// extern crate serde_derive; -/// extern crate toml; -/// -/// #[derive(Deserialize)] -/// struct Config { -/// title: String, -/// owner: Owner, -/// } -/// -/// #[derive(Deserialize)] -/// struct Owner { -/// name: String, -/// } -/// -/// fn main() { -/// let config: Config = toml::from_str(r#" -/// title = 'TOML Example' -/// -/// [owner] -/// name = 'Lisa' -/// "#).unwrap(); -/// -/// assert_eq!(config.title, "TOML Example"); -/// assert_eq!(config.owner.name, "Lisa"); -/// } -/// ``` -pub fn from_str<'de, T>(s: &'de str) -> Result<T, Error> - where T: de::Deserialize<'de>, -{ - let mut d = Deserializer::new(s); - let ret = T::deserialize(&mut d)?; - d.end()?; - Ok(ret) -} - -/// Errors that can occur when deserializing a type. -#[derive(Debug, Clone)] -pub struct Error { - inner: Box<ErrorInner>, -} - -#[derive(Debug, Clone)] -struct ErrorInner { - kind: ErrorKind, - line: Option<usize>, - col: usize, - message: String, - key: Vec<String>, -} - -/// Errors that can occur when deserializing a type. -#[derive(Debug, Clone)] -enum ErrorKind { - /// EOF was reached when looking for a value - UnexpectedEof, - - /// An invalid character not allowed in a string was found - InvalidCharInString(char), - - /// An invalid character was found as an escape - InvalidEscape(char), - - /// An invalid character was found in a hex escape - InvalidHexEscape(char), - - /// An invalid escape value was specified in a hex escape in a string. - /// - /// Valid values are in the plane of unicode codepoints. - InvalidEscapeValue(u32), - - /// A newline in a string was encountered when one was not allowed. - NewlineInString, - - /// An unexpected character was encountered, typically when looking for a - /// value. - Unexpected(char), - - /// An unterminated string was found where EOF was found before the ending - /// EOF mark. - UnterminatedString, - - /// A newline was found in a table key. - NewlineInTableKey, - - /// A number failed to parse - NumberInvalid, - - /// A date or datetime was invalid - DateInvalid, - - /// Wanted one sort of token, but found another. - Wanted { - /// Expected token type - expected: &'static str, - /// Actually found token type - found: &'static str, - }, - - /// An array was decoded but the types inside of it were mixed, which is - /// disallowed by TOML. - MixedArrayType, - - /// A duplicate table definition was found. - DuplicateTable(String), - - /// A previously defined table was redefined as an array. - RedefineAsArray, - - /// An empty table key was found. - EmptyTableKey, - - /// A custom error which could be generated when deserializing a particular - /// type. - Custom, - - /// A struct was expected but something else was found - ExpectedString, - - #[doc(hidden)] - __Nonexhaustive, -} - -/// Deserialization implementation for TOML. -pub struct Deserializer<'a> { - require_newline_after_table: bool, - input: &'a str, - tokens: Tokenizer<'a>, -} - -impl<'de, 'b> de::Deserializer<'de> for &'b mut Deserializer<'de> { - type Error = Error; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> - where V: de::Visitor<'de>, - { - let mut tables = Vec::new(); - let mut cur_table = Table { - at: 0, - header: Vec::new(), - values: None, - array: false, - }; - - while let Some(line) = self.line()? { - match line { - Line::Table { at, mut header, array } => { - if !cur_table.header.is_empty() || cur_table.values.is_some() { - tables.push(cur_table); - } - cur_table = Table { - at: at, - header: Vec::new(), - values: Some(Vec::new()), - array: array, - }; - loop { - let part = header.next().map_err(|e| { - self.token_error(e) - }); - match part? { - Some(part) => cur_table.header.push(part), - None => break, - } - } - } - Line::KeyValue(key, value) => { - if cur_table.values.is_none() { - cur_table.values = Some(Vec::new()); - } - cur_table.values.as_mut().unwrap().push((key, value)); - } - } - } - if !cur_table.header.is_empty() || cur_table.values.is_some() { - tables.push(cur_table); - } - - visitor.visit_map(MapVisitor { - values: Vec::new().into_iter(), - next_value: None, - depth: 0, - cur: 0, - cur_parent: 0, - max: tables.len(), - tables: &mut tables, - array: false, - de: self, - }) - } - - fn deserialize_enum<V>( - self, - _name: &'static str, - _variants: &'static [&'static str], - visitor: V - ) -> Result<V::Value, Error> - where V: de::Visitor<'de> - { - if let Some(next) = self.next()? { - match next { - Token::String { val, .. } => { - visitor.visit_enum(val.into_deserializer()) - }, - _ => Err(Error::from_kind(ErrorKind::ExpectedString)) - } - } else { - Err(Error::from_kind(ErrorKind::UnexpectedEof)) - } - } - - forward_to_deserialize_any! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq - bytes byte_buf map struct unit newtype_struct - ignored_any unit_struct tuple_struct tuple option identifier - } -} - -struct Table<'a> { - at: usize, - header: Vec<Cow<'a, str>>, - values: Option<Vec<(Cow<'a, str>, Value<'a>)>>, - array: bool, -} - -#[doc(hidden)] -pub struct MapVisitor<'de: 'b, 'b> { - values: vec::IntoIter<(Cow<'de, str>, Value<'de>)>, - next_value: Option<(Cow<'de, str>, Value<'de>)>, - depth: usize, - cur: usize, - cur_parent: usize, - max: usize, - tables: &'b mut [Table<'de>], - array: bool, - de: &'b mut Deserializer<'de>, -} - -impl<'de, 'b> de::MapAccess<'de> for MapVisitor<'de, 'b> { - type Error = Error; - - fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> - where K: de::DeserializeSeed<'de>, - { - if self.cur_parent == self.max || self.cur == self.max { - return Ok(None) - } - - loop { - assert!(self.next_value.is_none()); - if let Some((key, value)) = self.values.next() { - let ret = seed.deserialize(StrDeserializer::new(key.clone()))?; - self.next_value = Some((key, value)); - return Ok(Some(ret)) - } - - let next_table = { - let prefix = &self.tables[self.cur_parent].header[..self.depth]; - self.tables[self.cur..self.max].iter().enumerate().find(|&(_, t)| { - if t.values.is_none() { - return false - } - match t.header.get(..self.depth) { - Some(header) => header == prefix, - None => false, - } - }).map(|(i, _)| i + self.cur) - }; - - let pos = match next_table { - Some(pos) => pos, - None => return Ok(None), - }; - self.cur = pos; - - // Test to see if we're duplicating our parent's table, and if so - // then this is an error in the toml format - if self.cur_parent != pos && - self.tables[self.cur_parent].header == self.tables[pos].header { - let at = self.tables[pos].at; - let name = self.tables[pos].header.join("."); - return Err(self.de.error(at, ErrorKind::DuplicateTable(name))) - } - - let table = &mut self.tables[pos]; - - // If we're not yet at the appropriate depth for this table then we - // just next the next portion of its header and then continue - // decoding. - if self.depth != table.header.len() { - let key = &table.header[self.depth]; - let key = seed.deserialize(StrDeserializer::new(key.clone()))?; - return Ok(Some(key)) - } - - // Rule out cases like: - // - // [[foo.bar]] - // [[foo]] - if table.array { - let kind = ErrorKind::RedefineAsArray; - return Err(self.de.error(table.at, kind)) - } - - self.values = table.values.take().expect("Unable to read table values").into_iter(); - } - } - - fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> - where V: de::DeserializeSeed<'de>, - { - if let Some((k, v)) = self.next_value.take() { - match seed.deserialize(ValueDeserializer::new(v)) { - Ok(v) => return Ok(v), - Err(mut e) => { - e.add_key_context(&k); - return Err(e) - } - } - } - - let array = self.tables[self.cur].array && - self.depth == self.tables[self.cur].header.len() - 1; - self.cur += 1; - let res = seed.deserialize(MapVisitor { - values: Vec::new().into_iter(), - next_value: None, - depth: self.depth + if array {0} else {1}, - cur_parent: self.cur - 1, - cur: 0, - max: self.max, - array: array, - tables: &mut *self.tables, - de: &mut *self.de, - }); - res.map_err(|mut e| { - e.add_key_context(&self.tables[self.cur - 1].header[self.depth]); - e - }) - } -} - -impl<'de, 'b> de::SeqAccess<'de> for MapVisitor<'de, 'b> { - type Error = Error; - - fn next_element_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> - where K: de::DeserializeSeed<'de>, - { - assert!(self.next_value.is_none()); - assert!(self.values.next().is_none()); - - if self.cur_parent == self.max { - return Ok(None) - } - - let next = self.tables[..self.max] - .iter() - .enumerate() - .skip(self.cur_parent + 1) - .find(|&(_, table)| { - table.array && table.header == self.tables[self.cur_parent].header - }).map(|p| p.0) - .unwrap_or(self.max); - - let ret = seed.deserialize(MapVisitor { - values: self.tables[self.cur_parent].values.take().expect("Unable to read table values").into_iter(), - next_value: None, - depth: self.depth + 1, - cur_parent: self.cur_parent, - max: next, - cur: 0, - array: false, - tables: &mut self.tables, - de: &mut self.de, - })?; - self.cur_parent = next; - Ok(Some(ret)) - } -} - -impl<'de, 'b> de::Deserializer<'de> for MapVisitor<'de, 'b> { - type Error = Error; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> - where V: de::Visitor<'de>, - { - if self.array { - visitor.visit_seq(self) - } else { - visitor.visit_map(self) - } - } - - // `None` is interpreted as a missing field so be sure to implement `Some` - // as a present field. - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error> - where V: de::Visitor<'de>, - { - visitor.visit_some(self) - } - - fn deserialize_newtype_struct<V>( - self, - _name: &'static str, - visitor: V - ) -> Result<V::Value, Error> - where V: de::Visitor<'de> - { - visitor.visit_newtype_struct(self) - } - - forward_to_deserialize_any! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq - bytes byte_buf map struct unit identifier - ignored_any unit_struct tuple_struct tuple enum - } -} - -struct StrDeserializer<'a> { - key: Cow<'a, str>, -} - -impl<'a> StrDeserializer<'a> { - fn new(key: Cow<'a, str>) -> StrDeserializer<'a> { - StrDeserializer { - key: key, - } - } -} - -impl<'de> de::Deserializer<'de> for StrDeserializer<'de> { - type Error = Error; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> - where V: de::Visitor<'de>, - { - match self.key { - Cow::Borrowed(s) => visitor.visit_borrowed_str(s), - Cow::Owned(s) => visitor.visit_string(s), - } - } - - forward_to_deserialize_any! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq - bytes byte_buf map struct option unit newtype_struct - ignored_any unit_struct tuple_struct tuple enum identifier - } -} - -struct ValueDeserializer<'a> { - value: Value<'a>, -} - -impl<'a> ValueDeserializer<'a> { - fn new(value: Value<'a>) -> ValueDeserializer<'a> { - ValueDeserializer { - value: value, - } - } -} - -impl<'de> de::Deserializer<'de> for ValueDeserializer<'de> { - type Error = Error; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> - where V: de::Visitor<'de>, - { - match self.value { - Value::Integer(i) => visitor.visit_i64(i), - Value::Boolean(b) => visitor.visit_bool(b), - Value::Float(f) => visitor.visit_f64(f), - Value::String(Cow::Borrowed(s)) => visitor.visit_borrowed_str(s), - Value::String(Cow::Owned(s)) => visitor.visit_string(s), - Value::Datetime(s) => visitor.visit_map(DatetimeDeserializer { - date: s, - visited: false, - }), - Value::Array(values) => { - let mut s = de::value::SeqDeserializer::new(values.into_iter()); - let ret = visitor.visit_seq(&mut s)?; - s.end()?; - Ok(ret) - } - Value::InlineTable(values) => { - visitor.visit_map(InlineTableDeserializer { - values: values.into_iter(), - next_value: None, - }) - } - } - } - - fn deserialize_struct<V>(self, - name: &'static str, - fields: &'static [&'static str], - visitor: V) -> Result<V::Value, Error> - where V: de::Visitor<'de>, - { - if name == SERDE_STRUCT_NAME && fields == &[SERDE_STRUCT_FIELD_NAME] { - if let Value::Datetime(s) = self.value { - return visitor.visit_map(DatetimeDeserializer { - date: s, - visited: false, - }) - } - } - - self.deserialize_any(visitor) - } - - // `None` is interpreted as a missing field so be sure to implement `Some` - // as a present field. - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error> - where V: de::Visitor<'de>, - { - visitor.visit_some(self) - } - - fn deserialize_enum<V>( - self, - _name: &'static str, - _variants: &'static [&'static str], - visitor: V - ) -> Result<V::Value, Error> - where V: de::Visitor<'de> - { - match self.value { - Value::String(val) => visitor.visit_enum(val.into_deserializer()), - _ => Err(Error::from_kind(ErrorKind::ExpectedString)) - } - } - - fn deserialize_newtype_struct<V>( - self, - _name: &'static str, - visitor: V - ) -> Result<V::Value, Error> - where V: de::Visitor<'de> - { - visitor.visit_newtype_struct(self) - } - - forward_to_deserialize_any! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq - bytes byte_buf map unit identifier - ignored_any unit_struct tuple_struct tuple - } -} - -impl<'de> de::IntoDeserializer<'de, Error> for Value<'de> { - type Deserializer = ValueDeserializer<'de>; - - fn into_deserializer(self) -> Self::Deserializer { - ValueDeserializer::new(self) - } -} - -struct DatetimeDeserializer<'a> { - visited: bool, - date: &'a str, -} - -impl<'de> de::MapAccess<'de> for DatetimeDeserializer<'de> { - type Error = Error; - - fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> - where K: de::DeserializeSeed<'de>, - { - if self.visited { - return Ok(None) - } - self.visited = true; - seed.deserialize(DatetimeFieldDeserializer).map(Some) - } - - fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> - where V: de::DeserializeSeed<'de>, - { - seed.deserialize(StrDeserializer::new(self.date.into())) - } -} - -struct DatetimeFieldDeserializer; - -impl<'de> de::Deserializer<'de> for DatetimeFieldDeserializer { - type Error = Error; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> - where V: de::Visitor<'de>, - { - visitor.visit_borrowed_str(SERDE_STRUCT_FIELD_NAME) - } - - forward_to_deserialize_any! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq - bytes byte_buf map struct option unit newtype_struct - ignored_any unit_struct tuple_struct tuple enum identifier - } -} - -struct InlineTableDeserializer<'a> { - values: vec::IntoIter<(Cow<'a, str>, Value<'a>)>, - next_value: Option<Value<'a>>, -} - -impl<'de> de::MapAccess<'de> for InlineTableDeserializer<'de> { - type Error = Error; - - fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> - where K: de::DeserializeSeed<'de>, - { - let (key, value) = match self.values.next() { - Some(pair) => pair, - None => return Ok(None), - }; - self.next_value = Some(value); - seed.deserialize(StrDeserializer::new(key)).map(Some) - } - - fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> - where V: de::DeserializeSeed<'de>, - { - let value = self.next_value.take().expect("Unable to read table values"); - seed.deserialize(ValueDeserializer::new(value)) - } -} - - -impl<'a> Deserializer<'a> { - /// Creates a new deserializer which will be deserializing the string - /// provided. - pub fn new(input: &'a str) -> Deserializer<'a> { - Deserializer { - tokens: Tokenizer::new(input), - input: input, - require_newline_after_table: true, - } - } - - /// The `Deserializer::end` method should be called after a value has been - /// fully deserialized. This allows the `Deserializer` to validate that the - /// input stream is at the end or that it only has trailing - /// whitespace/comments. - pub fn end(&mut self) -> Result<(), Error> { - Ok(()) - } - - /// Historical versions of toml-rs accidentally allowed a newline after a - /// table definition, but the TOML spec requires a newline after a table - /// definition header. - /// - /// This option can be set to `false` (the default is `true`) to emulate - /// this behavior for backwards compatibility with older toml-rs versions. - pub fn set_require_newline_after_table(&mut self, require: bool) { - self.require_newline_after_table = require; - } - - fn line(&mut self) -> Result<Option<Line<'a>>, Error> { - loop { - self.eat_whitespace()?; - if self.eat_comment()? { - continue - } - if self.eat(Token::Newline)? { - continue - } - break - } - - match self.peek()? { - Some(Token::LeftBracket) => self.table_header().map(Some), - Some(_) => self.key_value().map(Some), - None => Ok(None), - } - } - - fn table_header(&mut self) -> Result<Line<'a>, Error> { - let start = self.tokens.current(); - self.expect(Token::LeftBracket)?; - let array = self.eat(Token::LeftBracket)?; - let ret = Header::new(self.tokens.clone(), - array, - self.require_newline_after_table); - if self.require_newline_after_table { - self.tokens.skip_to_newline(); - } else { - loop { - match self.next()? { - Some(Token::RightBracket) => { - if array { - self.eat(Token::RightBracket)?; - } - break - } - Some(Token::Newline) | - None => break, - _ => {} - } - } - self.eat_whitespace()?; - } - Ok(Line::Table { at: start, header: ret, array: array }) - } - - fn key_value(&mut self) -> Result<Line<'a>, Error> { - let key = self.table_key()?; - self.eat_whitespace()?; - self.expect(Token::Equals)?; - self.eat_whitespace()?; - - let value = self.value()?; - self.eat_whitespace()?; - if !self.eat_comment()? { - self.eat_newline_or_eof()?; - } - - Ok(Line::KeyValue(key, value)) - } - - fn value(&mut self) -> Result<Value<'a>, Error> { - let at = self.tokens.current(); - let value = match self.next()? { - Some(Token::String { val, .. }) => Value::String(val), - Some(Token::Keylike("true")) => Value::Boolean(true), - Some(Token::Keylike("false")) => Value::Boolean(false), - Some(Token::Keylike(key)) => self.number_or_date(key)?, - Some(Token::Plus) => self.number_leading_plus()?, - Some(Token::LeftBrace) => self.inline_table().map(Value::InlineTable)?, - Some(Token::LeftBracket) => self.array().map(Value::Array)?, - Some(token) => { - return Err(self.error(at, ErrorKind::Wanted { - expected: "a value", - found: token.describe(), - })) - } - None => return Err(self.eof()), - }; - Ok(value) - } - - fn number_or_date(&mut self, s: &'a str) -> Result<Value<'a>, Error> { - if s.contains('T') || (s.len() > 1 && s[1..].contains('-')) && - !s.contains("e-") { - self.datetime(s, false).map(Value::Datetime) - } else if self.eat(Token::Colon)? { - self.datetime(s, true).map(Value::Datetime) - } else { - self.number(s) - } - } - - fn number(&mut self, s: &'a str) -> Result<Value<'a>, Error> { - if s.contains('e') || s.contains('E') { - self.float(s, None).map(Value::Float) - } else if self.eat(Token::Period)? { - let at = self.tokens.current(); - match self.next()? { - Some(Token::Keylike(after)) => { - self.float(s, Some(after)).map(Value::Float) - } - _ => Err(self.error(at, ErrorKind::NumberInvalid)), - } - } else { - self.integer(s).map(Value::Integer) - } - } - - fn number_leading_plus(&mut self) -> Result<Value<'a>, Error> { - let start = self.tokens.current(); - match self.next()? { - Some(Token::Keylike(s)) => self.number(s), - _ => Err(self.error(start, ErrorKind::NumberInvalid)), - } - } - - fn integer(&self, s: &'a str) -> Result<i64, Error> { - let (prefix, suffix) = self.parse_integer(s, true, false)?; - let start = self.tokens.substr_offset(s); - if suffix != "" { - return Err(self.error(start, ErrorKind::NumberInvalid)) - } - prefix.replace("_", "").trim_left_matches('+').parse().map_err(|_e| { - self.error(start, ErrorKind::NumberInvalid) - }) - } - - fn parse_integer(&self, - s: &'a str, - allow_sign: bool, - allow_leading_zeros: bool) - -> Result<(&'a str, &'a str), Error> { - let start = self.tokens.substr_offset(s); - - let mut first = true; - let mut first_zero = false; - let mut underscore = false; - let mut end = s.len(); - for (i, c) in s.char_indices() { - let at = i + start; - if i == 0 && (c == '+' || c == '-') && allow_sign { - continue - } - - match c { - '0' if first => first_zero = true, - '0' ... '9' if !first && first_zero && !allow_leading_zeros => { - return Err(self.error(at, ErrorKind::NumberInvalid)) - } - '0' ... '9' => underscore = false, - '_' if first => { - return Err(self.error(at, ErrorKind::NumberInvalid)) - } - '_' if !underscore => underscore = true, - _ => { - end = i; - break - } - - } - first = false; - } - if first || underscore { - return Err(self.error(start, ErrorKind::NumberInvalid)) - } - Ok((&s[..end], &s[end..])) - } - - fn float(&mut self, s: &'a str, after_decimal: Option<&'a str>) - -> Result<f64, Error> { - let (integral, mut suffix) = self.parse_integer(s, true, false)?; - let start = self.tokens.substr_offset(integral); - - let mut fraction = None; - if let Some(after) = after_decimal { - if suffix != "" { - return Err(self.error(start, ErrorKind::NumberInvalid)) - } - let (a, b) = self.parse_integer(after, false, true)?; - fraction = Some(a); - suffix = b; - } - - let mut exponent = None; - if suffix.starts_with('e') || suffix.starts_with('E') { - let (a, b) = if suffix.len() == 1 { - self.eat(Token::Plus)?; - match self.next()? { - Some(Token::Keylike(s)) => { - self.parse_integer(s, false, false)? - } - _ => return Err(self.error(start, ErrorKind::NumberInvalid)), - } - } else { - self.parse_integer(&suffix[1..], true, false)? - }; - if b != "" { - return Err(self.error(start, ErrorKind::NumberInvalid)) - } - exponent = Some(a); - } - - let mut number = integral.trim_left_matches('+') - .chars() - .filter(|c| *c != '_') - .collect::<String>(); - if let Some(fraction) = fraction { - number.push_str("."); - number.extend(fraction.chars().filter(|c| *c != '_')); - } - if let Some(exponent) = exponent { - number.push_str("E"); - number.extend(exponent.chars().filter(|c| *c != '_')); - } - number.parse().map_err(|_e| { - self.error(start, ErrorKind::NumberInvalid) - }).and_then(|n: f64| { - if n.is_finite() { - Ok(n) - } else { - Err(self.error(start, ErrorKind::NumberInvalid)) - } - }) - } - - fn datetime(&mut self, date: &'a str, colon_eaten: bool) - -> Result<&'a str, Error> { - let start = self.tokens.substr_offset(date); - if colon_eaten || self.eat(Token::Colon)? { - // minutes - match self.next()? { - Some(Token::Keylike(_)) => {} - _ => return Err(self.error(start, ErrorKind::DateInvalid)), - } - // Seconds - self.expect(Token::Colon)?; - match self.next()? { - Some(Token::Keylike(_)) => {} - _ => return Err(self.error(start, ErrorKind::DateInvalid)), - } - // Fractional seconds - if self.eat(Token::Period)? { - match self.next()? { - Some(Token::Keylike(_)) => {} - _ => return Err(self.error(start, ErrorKind::DateInvalid)), - } - } - - // offset - if self.eat(Token::Plus)? { - match self.next()? { - Some(Token::Keylike(_)) => {} - _ => return Err(self.error(start, ErrorKind::DateInvalid)), - } - } - if self.eat(Token::Colon)? { - match self.next()? { - Some(Token::Keylike(_)) => {} - _ => return Err(self.error(start, ErrorKind::DateInvalid)), - } - } - } - let end = self.tokens.current(); - Ok(&self.tokens.input()[start..end]) - } - - // TODO(#140): shouldn't buffer up this entire table in memory, it'd be - // great to defer parsing everything until later. - fn inline_table(&mut self) -> Result<Vec<(Cow<'a, str>, Value<'a>)>, Error> { - let mut ret = Vec::new(); - self.eat_whitespace()?; - if self.eat(Token::RightBrace)? { - return Ok(ret) - } - loop { - let key = self.table_key()?; - self.eat_whitespace()?; - self.expect(Token::Equals)?; - self.eat_whitespace()?; - ret.push((key, self.value()?)); - - self.eat_whitespace()?; - if self.eat(Token::RightBrace)? { - return Ok(ret) - } - self.expect(Token::Comma)?; - self.eat_whitespace()?; - } - } - - // TODO(#140): shouldn't buffer up this entire array in memory, it'd be - // great to defer parsing everything until later. - fn array(&mut self) -> Result<Vec<Value<'a>>, Error> { - let mut ret = Vec::new(); - - let intermediate = |me: &mut Deserializer| { - loop { - me.eat_whitespace()?; - if !me.eat(Token::Newline)? && !me.eat_comment()? { - break - } - } - Ok(()) - }; - - loop { - intermediate(self)?; - if self.eat(Token::RightBracket)? { - return Ok(ret) - } - let at = self.tokens.current(); - let value = self.value()?; - if let Some(last) = ret.last() { - if !value.same_type(last) { - return Err(self.error(at, ErrorKind::MixedArrayType)) - } - } - ret.push(value); - intermediate(self)?; - if !self.eat(Token::Comma)? { - break - } - } - intermediate(self)?; - self.expect(Token::RightBracket)?; - Ok(ret) - } - - fn table_key(&mut self) -> Result<Cow<'a, str>, Error> { - self.tokens.table_key().map_err(|e| self.token_error(e)) - } - - fn eat_whitespace(&mut self) -> Result<(), Error> { - self.tokens.eat_whitespace().map_err(|e| self.token_error(e)) - } - - fn eat_comment(&mut self) -> Result<bool, Error> { - self.tokens.eat_comment().map_err(|e| self.token_error(e)) - } - - fn eat_newline_or_eof(&mut self) -> Result<(), Error> { - self.tokens.eat_newline_or_eof().map_err(|e| self.token_error(e)) - } - - fn eat(&mut self, expected: Token<'a>) -> Result<bool, Error> { - self.tokens.eat(expected).map_err(|e| self.token_error(e)) - } - - fn expect(&mut self, expected: Token<'a>) -> Result<(), Error> { - self.tokens.expect(expected).map_err(|e| self.token_error(e)) - } - - fn next(&mut self) -> Result<Option<Token<'a>>, Error> { - self.tokens.next().map_err(|e| self.token_error(e)) - } - - fn peek(&mut self) -> Result<Option<Token<'a>>, Error> { - self.tokens.peek().map_err(|e| self.token_error(e)) - } - - fn eof(&self) -> Error { - self.error(self.input.len(), ErrorKind::UnexpectedEof) - } - - fn token_error(&self, error: TokenError) -> Error { - match error { - TokenError::InvalidCharInString(at, ch) => { - self.error(at, ErrorKind::InvalidCharInString(ch)) - } - TokenError::InvalidEscape(at, ch) => { - self.error(at, ErrorKind::InvalidEscape(ch)) - } - TokenError::InvalidEscapeValue(at, v) => { - self.error(at, ErrorKind::InvalidEscapeValue(v)) - } - TokenError::InvalidHexEscape(at, ch) => { - self.error(at, ErrorKind::InvalidHexEscape(ch)) - } - TokenError::NewlineInString(at) => { - self.error(at, ErrorKind::NewlineInString) - } - TokenError::Unexpected(at, ch) => { - self.error(at, ErrorKind::Unexpected(ch)) - } - TokenError::UnterminatedString(at) => { - self.error(at, ErrorKind::UnterminatedString) - } - TokenError::NewlineInTableKey(at) => { - self.error(at, ErrorKind::NewlineInTableKey) - } - TokenError::Wanted { at, expected, found } => { - self.error(at, ErrorKind::Wanted { expected: expected, found: found }) - } - TokenError::EmptyTableKey(at) => { - self.error(at, ErrorKind::EmptyTableKey) - } - } - } - - fn error(&self, at: usize, kind: ErrorKind) -> Error { - let mut err = Error::from_kind(kind); - let (line, col) = self.to_linecol(at); - err.inner.line = Some(line); - err.inner.col = col; - err - } - - /// Converts a byte offset from an error message to a (line, column) pair - /// - /// All indexes are 0-based. - fn to_linecol(&self, offset: usize) -> (usize, usize) { - let mut cur = 0; - for (i, line) in self.input.lines().enumerate() { - if cur + line.len() + 1 > offset { - return (i, offset - cur) - } - cur += line.len() + 1; - } - (self.input.lines().count(), 0) - } -} - -impl Error { - /// Produces a (line, column) pair of the position of the error if available - /// - /// All indexes are 0-based. - pub fn line_col(&self) -> Option<(usize, usize)> { - self.inner.line.map(|line| (line, self.inner.col)) - } - - fn from_kind(kind: ErrorKind) -> Error { - Error { - inner: Box::new(ErrorInner { - kind: kind, - line: None, - col: 0, - message: String::new(), - key: Vec::new(), - }), - } - } - - fn custom(s: String) -> Error { - Error { - inner: Box::new(ErrorInner { - kind: ErrorKind::Custom, - line: None, - col: 0, - message: s, - key: Vec::new(), - }), - } - } - - /// Do not call this method, it may be removed at any time, it's just an - /// internal implementation detail. - #[doc(hidden)] - pub fn add_key_context(&mut self, key: &str) { - self.inner.key.insert(0, key.to_string()); - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.inner.kind { - ErrorKind::UnexpectedEof => "unexpected eof encountered".fmt(f)?, - ErrorKind::InvalidCharInString(c) => { - write!(f, "invalid character in string: `{}`", - c.escape_default().collect::<String>())? - } - ErrorKind::InvalidEscape(c) => { - write!(f, "invalid escape character in string: `{}`", - c.escape_default().collect::<String>())? - } - ErrorKind::InvalidHexEscape(c) => { - write!(f, "invalid hex escape character in string: `{}`", - c.escape_default().collect::<String>())? - } - ErrorKind::InvalidEscapeValue(c) => { - write!(f, "invalid escape value: `{}`", c)? - } - ErrorKind::NewlineInString => "newline in string found".fmt(f)?, - ErrorKind::Unexpected(ch) => { - write!(f, "unexpected character found: `{}`", - ch.escape_default().collect::<String>())? - } - ErrorKind::UnterminatedString => "unterminated string".fmt(f)?, - ErrorKind::NewlineInTableKey => "found newline in table key".fmt(f)?, - ErrorKind::Wanted { expected, found } => { - write!(f, "expected {}, found {}", expected, found)? - } - ErrorKind::NumberInvalid => "invalid number".fmt(f)?, - ErrorKind::DateInvalid => "invalid date".fmt(f)?, - ErrorKind::MixedArrayType => "mixed types in an array".fmt(f)?, - ErrorKind::DuplicateTable(ref s) => { - write!(f, "redefinition of table `{}`", s)?; - } - ErrorKind::RedefineAsArray => "table redefined as array".fmt(f)?, - ErrorKind::EmptyTableKey => "empty table key found".fmt(f)?, - ErrorKind::Custom => self.inner.message.fmt(f)?, - ErrorKind::ExpectedString => "expected string".fmt(f)?, - ErrorKind::__Nonexhaustive => panic!(), - } - - if !self.inner.key.is_empty() { - write!(f, " for key `")?; - for (i, k) in self.inner.key.iter().enumerate() { - if i > 0 { - write!(f, ".")?; - } - write!(f, "{}", k)?; - } - write!(f, "`")?; - } - - if let Some(line) = self.inner.line { - write!(f, " at line {}", line + 1)?; - } - - Ok(()) - } -} - -impl error::Error for Error { - fn description(&self) -> &str { - match self.inner.kind { - ErrorKind::UnexpectedEof => "unexpected eof encountered", - ErrorKind::InvalidCharInString(_) => "invalid char in string", - ErrorKind::InvalidEscape(_) => "invalid escape in string", - ErrorKind::InvalidHexEscape(_) => "invalid hex escape in string", - ErrorKind::InvalidEscapeValue(_) => "invalid escape value in string", - ErrorKind::NewlineInString => "newline in string found", - ErrorKind::Unexpected(_) => "unexpected or invalid character", - ErrorKind::UnterminatedString => "unterminated string", - ErrorKind::NewlineInTableKey => "found newline in table key", - ErrorKind::Wanted { .. } => "expected a token but found another", - ErrorKind::NumberInvalid => "invalid number", - ErrorKind::DateInvalid => "invalid date", - ErrorKind::MixedArrayType => "mixed types in an array", - ErrorKind::DuplicateTable(_) => "duplicate table", - ErrorKind::RedefineAsArray => "table redefined as array", - ErrorKind::EmptyTableKey => "empty table key found", - ErrorKind::Custom => "a custom error", - ErrorKind::ExpectedString => "expected string", - ErrorKind::__Nonexhaustive => panic!(), - } - } -} - -impl de::Error for Error { - fn custom<T: fmt::Display>(msg: T) -> Error { - Error::custom(msg.to_string()) - } -} - -enum Line<'a> { - Table { at: usize, header: Header<'a>, array: bool }, - KeyValue(Cow<'a, str>, Value<'a>), -} - -struct Header<'a> { - first: bool, - array: bool, - require_newline_after_table: bool, - tokens: Tokenizer<'a>, -} - -impl<'a> Header<'a> { - fn new(tokens: Tokenizer<'a>, - array: bool, - require_newline_after_table: bool) -> Header<'a> { - Header { - first: true, - array: array, - tokens: tokens, - require_newline_after_table: require_newline_after_table, - } - } - - fn next(&mut self) -> Result<Option<Cow<'a, str>>, TokenError> { - self.tokens.eat_whitespace()?; - - if self.first || self.tokens.eat(Token::Period)? { - self.first = false; - self.tokens.eat_whitespace()?; - self.tokens.table_key().map(Some) - } else { - self.tokens.expect(Token::RightBracket)?; - if self.array { - self.tokens.expect(Token::RightBracket)?; - } - - self.tokens.eat_whitespace()?; - if self.require_newline_after_table { - if !self.tokens.eat_comment()? { - self.tokens.eat_newline_or_eof()?; - } - } - Ok(None) - } - } -} - -#[derive(Debug)] -enum Value<'a> { - Integer(i64), - Float(f64), - Boolean(bool), - String(Cow<'a, str>), - Datetime(&'a str), - Array(Vec<Value<'a>>), - InlineTable(Vec<(Cow<'a, str>, Value<'a>)>), -} - -impl<'a> Value<'a> { - fn same_type(&self, other: &Value<'a>) -> bool { - match (self, other) { - (&Value::String(..), &Value::String(..)) | - (&Value::Integer(..), &Value::Integer(..)) | - (&Value::Float(..), &Value::Float(..)) | - (&Value::Boolean(..), &Value::Boolean(..)) | - (&Value::Datetime(..), &Value::Datetime(..)) | - (&Value::Array(..), &Value::Array(..)) | - (&Value::InlineTable(..), &Value::InlineTable(..)) => true, - - _ => false, - } - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/src/lib.rs cargo-0.26.0/vendor/toml-0.4.5/src/lib.rs --- cargo-0.25.0/vendor/toml-0.4.5/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,168 +0,0 @@ -//! A [TOML]-parsing library -//! -//! This library implements a [TOML] v0.4.0 compatible parser, -//! primarily supporting the [`serde`] library for encoding/decoding -//! various types in Rust. -//! -//! TOML itself is a simple, ergonomic, and readable configuration format: -//! -//! ```toml -//! [package] -//! name = "toml" -//! version = "0.4.2" -//! authors = ["Alex Crichton <alex@alexcrichton.com>"] -//! -//! [dependencies] -//! serde = "1.0" -//! ``` -//! -//! The TOML format tends to be relatively common throughout the Rust community -//! for configuration, notably being used by [Cargo], Rust's package manager. -//! -//! ## TOML values -//! -//! A value in TOML is represented with the `Value` enum in this crate: -//! -//! ```rust,ignore -//! pub enum Value { -//! String(String), -//! Integer(i64), -//! Float(f64), -//! Boolean(bool), -//! Datetime(Datetime), -//! Array(Array), -//! Table(Table), -//! } -//! ``` -//! -//! TOML is similar to JSON with the notable addition of a `Datetime` -//! type. In general, TOML and JSON are interchangeable in terms of -//! formats. -//! -//! ## Parsing TOML -//! -//! The easiest way to parse a TOML document is via the `Value` type: -//! -//! ```rust -//! use toml::Value; -//! -//! let value = "foo = 'bar'".parse::<Value>().unwrap(); -//! -//! assert_eq!(value["foo"].as_str(), Some("bar")); -//! ``` -//! -//! The `Value` type implements a number of convenience methods and -//! traits; the example above uses `FromStr` to parse a `str` into a -//! `Value`. -//! -//! ## Deserialization and Serialization -//! -//! This crate supports [`serde`] 1.0 with a number of -//! implementations of the `Deserialize`, `Serialize`, `Deserializer`, and -//! `Serializer` traits. Namely, you'll find: -//! -//! * `Deserialize for Value` -//! * `Serialize for Value` -//! * `Deserialize for Datetime` -//! * `Serialize for Datetime` -//! * `Deserializer for de::Deserializer` -//! * `Serializer for ser::Serializer` -//! * `Deserializer for Value` -//! -//! This means that you can use Serde to deserialize/serialize the -//! `Value` type as well as the `Datetime` type in this crate. You can also -//! use the `Deserializer`, `Serializer`, or `Value` type itself to act as -//! a deserializer/serializer for arbitrary types. -//! -//! An example of deserializing with TOML is: -//! -//! ```rust -//! #[macro_use] -//! extern crate serde_derive; -//! extern crate toml; -//! -//! #[derive(Deserialize)] -//! struct Config { -//! ip: String, -//! port: Option<u16>, -//! keys: Keys, -//! } -//! -//! #[derive(Deserialize)] -//! struct Keys { -//! github: String, -//! travis: Option<String>, -//! } -//! -//! fn main() { -//! let config: Config = toml::from_str(r#" -//! ip = '127.0.0.1' -//! -//! [keys] -//! github = 'xxxxxxxxxxxxxxxxx' -//! travis = 'yyyyyyyyyyyyyyyyy' -//! "#).unwrap(); -//! -//! assert_eq!(config.ip, "127.0.0.1"); -//! assert_eq!(config.port, None); -//! assert_eq!(config.keys.github, "xxxxxxxxxxxxxxxxx"); -//! assert_eq!(config.keys.travis.as_ref().unwrap(), "yyyyyyyyyyyyyyyyy"); -//! } -//! ``` -//! -//! You can serialize types in a similar fashion: -//! -//! ```rust -//! #[macro_use] -//! extern crate serde_derive; -//! extern crate toml; -//! -//! #[derive(Serialize)] -//! struct Config { -//! ip: String, -//! port: Option<u16>, -//! keys: Keys, -//! } -//! -//! #[derive(Serialize)] -//! struct Keys { -//! github: String, -//! travis: Option<String>, -//! } -//! -//! fn main() { -//! let config = Config { -//! ip: "127.0.0.1".to_string(), -//! port: None, -//! keys: Keys { -//! github: "xxxxxxxxxxxxxxxxx".to_string(), -//! travis: Some("yyyyyyyyyyyyyyyyy".to_string()), -//! }, -//! }; -//! -//! let toml = toml::to_string(&config).unwrap(); -//! } -//! ``` -//! -//! [TOML]: https://github.com/toml-lang/toml -//! [Cargo]: https://crates.io/ -//! [`serde`]: https://serde.rs/ - -#![doc(html_root_url = "https://docs.rs/toml/0.4")] -#![deny(missing_docs)] - -#[macro_use] -extern crate serde; - -pub mod value; -#[doc(no_inline)] -pub use value::Value; -mod datetime; - -pub mod ser; -#[doc(no_inline)] -pub use ser::{to_string, to_string_pretty, to_vec, Serializer}; -pub mod de; -#[doc(no_inline)] -pub use de::{from_slice, from_str, Deserializer}; -mod tokens; diff -Nru cargo-0.25.0/vendor/toml-0.4.5/src/ser.rs cargo-0.26.0/vendor/toml-0.4.5/src/ser.rs --- cargo-0.25.0/vendor/toml-0.4.5/src/ser.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/src/ser.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1714 +0,0 @@ -//! Serializing Rust structures into TOML. -//! -//! This module contains all the Serde support for serializing Rust structures -//! into TOML documents (as strings). Note that some top-level functions here -//! are also provided at the top of the crate. -//! -//! Note that the TOML format has a restriction that if a table itself contains -//! tables, all keys with non-table values must be emitted first. This is -//! typically easy to ensure happens when you're defining a `struct` as you can -//! reorder the fields manually, but when working with maps (such as `BTreeMap` -//! or `HashMap`) this can lead to serialization errors. In those situations you -//! may use the `tables_last` function in this module like so: -//! -//! ```rust -//! # #[macro_use] extern crate serde_derive; -//! # extern crate toml; -//! # use std::collections::HashMap; -//! #[derive(Serialize)] -//! struct Manifest { -//! package: Package, -//! #[serde(serialize_with = "toml::ser::tables_last")] -//! dependencies: HashMap<String, Dependency>, -//! } -//! # type Package = String; -//! # type Dependency = String; -//! # fn main() {} -//! ``` - -use std::cell::Cell; -use std::error; -use std::fmt::{self, Write}; -use std::marker; -use std::rc::Rc; - -use serde::ser; -use datetime::{SERDE_STRUCT_FIELD_NAME, SERDE_STRUCT_NAME}; - -/// Serialize the given data structure as a TOML byte vector. -/// -/// Serialization can fail if `T`'s implementation of `Serialize` decides to -/// fail, if `T` contains a map with non-string keys, or if `T` attempts to -/// serialize an unsupported datatype such as an enum, tuple, or tuple struct. -pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>, Error> - where T: ser::Serialize, -{ - to_string(value).map(|e| e.into_bytes()) -} - -/// Serialize the given data structure as a String of TOML. -/// -/// Serialization can fail if `T`'s implementation of `Serialize` decides to -/// fail, if `T` contains a map with non-string keys, or if `T` attempts to -/// serialize an unsupported datatype such as an enum, tuple, or tuple struct. -/// -/// # Examples -/// -/// ``` -/// #[macro_use] -/// extern crate serde_derive; -/// extern crate toml; -/// -/// #[derive(Serialize)] -/// struct Config { -/// database: Database, -/// } -/// -/// #[derive(Serialize)] -/// struct Database { -/// ip: String, -/// port: Vec<u16>, -/// connection_max: u32, -/// enabled: bool, -/// } -/// -/// fn main() { -/// let config = Config { -/// database: Database { -/// ip: "192.168.1.1".to_string(), -/// port: vec![8001, 8002, 8003], -/// connection_max: 5000, -/// enabled: false, -/// }, -/// }; -/// -/// let toml = toml::to_string(&config).unwrap(); -/// println!("{}", toml) -/// } -/// ``` -pub fn to_string<T: ?Sized>(value: &T) -> Result<String, Error> - where T: ser::Serialize, -{ - let mut dst = String::with_capacity(128); - value.serialize(&mut Serializer::new(&mut dst))?; - Ok(dst) -} - -/// Serialize the given data structure as a "pretty" String of TOML. -/// -/// This is identical to `to_string` except the output string has a more -/// "pretty" output. See `Serializer::pretty` for more details. -pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String, Error> - where T: ser::Serialize, -{ - let mut dst = String::with_capacity(128); - value.serialize(&mut Serializer::pretty(&mut dst))?; - Ok(dst) -} - -/// Errors that can occur when serializing a type. -#[derive(Debug, PartialEq, Eq, Clone)] -pub enum Error { - /// Indicates that a Rust type was requested to be serialized but it was not - /// supported. - /// - /// Currently the TOML format does not support serializing types such as - /// enums, tuples and tuple structs. - UnsupportedType, - - /// The key of all TOML maps must be strings, but serialization was - /// attempted where the key of a map was not a string. - KeyNotString, - - /// An error that we never omit but keep for backwards compatibility - #[doc(hidden)] - KeyNewline, - - /// Arrays in TOML must have a homogenous type, but a heterogeneous array - /// was emitted. - ArrayMixedType, - - /// All values in a TOML table must be emitted before further tables are - /// emitted. If a value is emitted *after* a table then this error is - /// generated. - ValueAfterTable, - - /// A serialized date was invalid. - DateInvalid, - - /// A serialized number was invalid. - NumberInvalid, - - /// None was attempted to be serialized, but it's not supported. - UnsupportedNone, - - /// A custom error which could be generated when serializing a particular - /// type. - Custom(String), - - #[doc(hidden)] - __Nonexhaustive, -} - -#[derive(Debug, Default, Clone)] -#[doc(hidden)] -/// Internal place for holding array setings -struct ArraySettings { - indent: usize, - trailing_comma: bool, -} - -impl ArraySettings { - fn pretty() -> ArraySettings { - ArraySettings { - indent: 4, - trailing_comma: true, - } - } -} - -#[doc(hidden)] -#[derive(Debug, Default, Clone)] -/// String settings -struct StringSettings { - /// Whether to use literal strings when possible - literal: bool, -} - -impl StringSettings { - fn pretty() -> StringSettings { - StringSettings { - literal: true, - } - } -} - -#[derive(Debug, Default, Clone)] -#[doc(hidden)] -/// Internal struct for holding serialization settings -struct Settings { - array: Option<ArraySettings>, - string: Option<StringSettings>, -} - -/// Serialization implementation for TOML. -/// -/// This structure implements serialization support for TOML to serialize an -/// arbitrary type to TOML. Note that the TOML format does not support all -/// datatypes in Rust, such as enums, tuples, and tuple structs. These types -/// will generate an error when serialized. -/// -/// Currently a serializer always writes its output to an in-memory `String`, -/// which is passed in when creating the serializer itself. -pub struct Serializer<'a> { - dst: &'a mut String, - state: State<'a>, - settings: Rc<Settings>, -} - -#[derive(Debug, Clone)] -enum State<'a> { - Table { - key: &'a str, - parent: &'a State<'a>, - first: &'a Cell<bool>, - table_emitted: &'a Cell<bool>, - }, - Array { - parent: &'a State<'a>, - first: &'a Cell<bool>, - type_: &'a Cell<Option<&'static str>>, - len: Option<usize>, - }, - End, -} - -#[doc(hidden)] -pub struct SerializeSeq<'a: 'b, 'b> { - ser: &'b mut Serializer<'a>, - first: Cell<bool>, - type_: Cell<Option<&'static str>>, - len: Option<usize>, -} - -#[doc(hidden)] -pub enum SerializeTable<'a: 'b, 'b> { - Datetime(&'b mut Serializer<'a>), - Table { - ser: &'b mut Serializer<'a>, - key: String, - first: Cell<bool>, - table_emitted: Cell<bool>, - } -} - -impl<'a> Serializer<'a> { - /// Creates a new serializer which will emit TOML into the buffer provided. - /// - /// The serializer can then be used to serialize a type after which the data - /// will be present in `dst`. - pub fn new(dst: &'a mut String) -> Serializer<'a> { - Serializer { - dst: dst, - state: State::End, - settings: Rc::new(Settings::default()), - } - } - - /// Instantiate a "pretty" formatter - /// - /// By default this will use: - /// - /// - pretty strings: strings with newlines will use the `'''` syntax. See - /// `Serializer::pretty_string` - /// - pretty arrays: each item in arrays will be on a newline, have an indentation of 4 and - /// have a trailing comma. See `Serializer::pretty_array` - pub fn pretty(dst: &'a mut String) -> Serializer<'a> { - Serializer { - dst: dst, - state: State::End, - settings: Rc::new(Settings { - array: Some(ArraySettings::pretty()), - string: Some(StringSettings::pretty()), - }), - } - } - - /// Enable or Disable pretty strings - /// - /// If enabled, literal strings will be used when possible and strings with - /// one or more newlines will use triple quotes (i.e.: `'''` or `"""`) - /// - /// # Examples - /// - /// Instead of: - /// - /// ```toml,ignore - /// single = "no newlines" - /// text = "\nfoo\nbar\n" - /// ``` - /// - /// You will have: - /// - /// ```toml,ignore - /// single = 'no newlines' - /// text = ''' - /// foo - /// bar - /// ''' - /// ``` - pub fn pretty_string(&mut self, value: bool) -> &mut Self { - Rc::get_mut(&mut self.settings).unwrap().string = if value { - Some(StringSettings::pretty()) - } else { - None - }; - self - } - - /// Enable or Disable Literal strings for pretty strings - /// - /// If enabled, literal strings will be used when possible and strings with - /// one or more newlines will use triple quotes (i.e.: `'''` or `"""`) - /// - /// If disabled, literal strings will NEVER be used and strings with one or - /// more newlines will use `"""` - /// - /// # Examples - /// - /// Instead of: - /// - /// ```toml,ignore - /// single = "no newlines" - /// text = "\nfoo\nbar\n" - /// ``` - /// - /// You will have: - /// - /// ```toml,ignore - /// single = "no newlines" - /// text = """ - /// foo - /// bar - /// """ - /// ``` - pub fn pretty_string_literal(&mut self, value: bool) -> &mut Self { - let use_default = if let &mut Some(ref mut s) = &mut Rc::get_mut(&mut self.settings) - .unwrap().string { - s.literal = value; - false - } else { - true - }; - - if use_default { - let mut string = StringSettings::pretty(); - string.literal = value; - Rc::get_mut(&mut self.settings).unwrap().string = Some(string); - } - self - } - - /// Enable or Disable pretty arrays - /// - /// If enabled, arrays will always have each item on their own line. - /// - /// Some specific features can be controlled via other builder methods: - /// - /// - `Serializer::pretty_array_indent`: set the indent to a value other - /// than 4. - /// - `Serializer::pretty_array_trailing_comma`: enable/disable the trailing - /// comma on the last item. - /// - /// # Examples - /// - /// Instead of: - /// - /// ```toml,ignore - /// array = ["foo", "bar"] - /// ``` - /// - /// You will have: - /// - /// ```toml,ignore - /// array = [ - /// "foo", - /// "bar", - /// ] - /// ``` - pub fn pretty_array(&mut self, value: bool) -> &mut Self { - Rc::get_mut(&mut self.settings).unwrap().array = if value { - Some(ArraySettings::pretty()) - } else { - None - }; - self - } - - /// Set the indent for pretty arrays - /// - /// See `Serializer::pretty_array` for more details. - pub fn pretty_array_indent(&mut self, value: usize) -> &mut Self { - let use_default = if let &mut Some(ref mut a) = &mut Rc::get_mut(&mut self.settings) - .unwrap().array { - a.indent = value; - false - } else { - true - }; - - if use_default { - let mut array = ArraySettings::pretty(); - array.indent = value; - Rc::get_mut(&mut self.settings).unwrap().array = Some(array); - } - self - } - - /// Specify whether to use a trailing comma when serializing pretty arrays - /// - /// See `Serializer::pretty_array` for more details. - pub fn pretty_array_trailing_comma(&mut self, value: bool) -> &mut Self { - let use_default = if let &mut Some(ref mut a) = &mut Rc::get_mut(&mut self.settings) - .unwrap().array { - a.trailing_comma = value; - false - } else { - true - }; - - if use_default { - let mut array = ArraySettings::pretty(); - array.trailing_comma = value; - Rc::get_mut(&mut self.settings).unwrap().array = Some(array); - } - self - } - - fn display<T: fmt::Display>(&mut self, - t: T, - type_: &'static str) -> Result<(), Error> { - self.emit_key(type_)?; - drop(write!(self.dst, "{}", t)); - if let State::Table { .. } = self.state { - self.dst.push_str("\n"); - } - Ok(()) - } - - fn emit_key(&mut self, type_: &'static str) -> Result<(), Error> { - self.array_type(type_)?; - let state = self.state.clone(); - self._emit_key(&state) - } - - // recursive implementation of `emit_key` above - fn _emit_key(&mut self, state: &State) -> Result<(), Error> { - match *state { - State::End => Ok(()), - State::Array { parent, first, type_, len } => { - assert!(type_.get().is_some()); - if first.get() { - self._emit_key(parent)?; - } - self.emit_array(first, len) - } - State::Table { parent, first, table_emitted, key } => { - if table_emitted.get() { - return Err(Error::ValueAfterTable) - } - if first.get() { - self.emit_table_header(parent)?; - first.set(false); - } - self.escape_key(key)?; - self.dst.push_str(" = "); - Ok(()) - } - } - } - - fn emit_array(&mut self, first: &Cell<bool>, len: Option<usize>) -> Result<(), Error> { - match (len, &self.settings.array) { - (Some(0...1), _) | (_, &None) => { - if first.get() { - self.dst.push_str("[") - } else { - self.dst.push_str(", ") - } - }, - (_, &Some(ref a)) => { - if first.get() { - self.dst.push_str("[\n") - } else { - self.dst.push_str(",\n") - } - for _ in 0..a.indent { - self.dst.push_str(" "); - } - }, - } - Ok(()) - } - - fn array_type(&mut self, type_: &'static str) -> Result<(), Error> { - let prev = match self.state { - State::Array { type_, .. } => type_, - _ => return Ok(()), - }; - if let Some(prev) = prev.get() { - if prev != type_ { - return Err(Error::ArrayMixedType) - } - } else { - prev.set(Some(type_)); - } - Ok(()) - } - - fn escape_key(&mut self, key: &str) -> Result<(), Error> { - let ok = key.chars().all(|c| { - match c { - 'a' ... 'z' | - 'A' ... 'Z' | - '0' ... '9' | - '-' | '_' => true, - _ => false, - } - }); - if ok { - drop(write!(self.dst, "{}", key)); - } else { - self.emit_str(key, true)?; - } - Ok(()) - } - - fn emit_str(&mut self, value: &str, is_key: bool) -> Result<(), Error> { - #[derive(PartialEq)] - enum Type { - NewlineTripple, - OnelineTripple, - OnelineSingle, - } - - enum Repr { - /// represent as a literal string (using '') - Literal(String, Type), - /// represent the std way (using "") - Std(Type), - } - - fn do_pretty(value: &str) -> Repr { - // For doing pretty prints we store in a new String - // because there are too many cases where pretty cannot - // work. We need to determine: - // - if we are a "multi-line" pretty (if there are \n) - // - if ['''] appears if multi or ['] if single - // - if there are any invalid control characters - // - // Doing it any other way would require multiple passes - // to determine if a pretty string works or not. - let mut out = String::with_capacity(value.len() * 2); - let mut ty = Type::OnelineSingle; - // found consecutive single quotes - let mut max_found_singles = 0; - let mut found_singles = 0; - let mut can_be_pretty = true; - - for ch in value.chars() { - if can_be_pretty { - if ch == '\'' { - found_singles += 1; - if found_singles >= 3 { - can_be_pretty = false; - } - } else { - if found_singles > max_found_singles { - max_found_singles = found_singles; - } - found_singles = 0 - } - match ch { - '\t' => {}, - '\n' => ty = Type::NewlineTripple, - // note that the following are invalid: \b \f \r - c if c < '\u{1f}' => can_be_pretty = false, // Invalid control character - _ => {} - } - out.push(ch); - } else { - // the string cannot be represented as pretty, - // still check if it should be multiline - if ch == '\n' { - ty = Type::NewlineTripple; - } - } - } - if !can_be_pretty { - debug_assert!(ty != Type::OnelineTripple); - return Repr::Std(ty); - } - if found_singles > max_found_singles { - max_found_singles = found_singles; - } - debug_assert!(max_found_singles < 3); - if ty == Type::OnelineSingle && max_found_singles >= 1 { - // no newlines, but must use ''' because it has ' in it - ty = Type::OnelineTripple; - } - Repr::Literal(out, ty) - } - - let repr = if !is_key && self.settings.string.is_some() { - match (&self.settings.string, do_pretty(value)) { - (&Some(StringSettings { literal: false, .. }), Repr::Literal(_, ty)) => - Repr::Std(ty), - (_, r @ _) => r, - } - } else { - Repr::Std(Type::OnelineSingle) - }; - match repr { - Repr::Literal(literal, ty) => { - // A pretty string - match ty { - Type::NewlineTripple => self.dst.push_str("'''\n"), - Type::OnelineTripple => self.dst.push_str("'''"), - Type::OnelineSingle => self.dst.push('\''), - } - self.dst.push_str(&literal); - match ty { - Type::OnelineSingle => self.dst.push('\''), - _ => self.dst.push_str("'''"), - } - }, - Repr::Std(ty) => { - match ty { - Type::NewlineTripple => self.dst.push_str("\"\"\"\n"), - // note: OnelineTripple can happen if do_pretty wants to do - // '''it's one line''' - // but settings.string.literal == false - Type::OnelineSingle | - Type::OnelineTripple => self.dst.push('"'), - } - for ch in value.chars() { - match ch { - '\u{8}' => self.dst.push_str("\\b"), - '\u{9}' => self.dst.push_str("\\t"), - '\u{a}' => { - match ty { - Type::NewlineTripple => self.dst.push('\n'), - Type::OnelineSingle => self.dst.push_str("\\n"), - _ => unreachable!(), - } - }, - '\u{c}' => self.dst.push_str("\\f"), - '\u{d}' => self.dst.push_str("\\r"), - '\u{22}' => self.dst.push_str("\\\""), - '\u{5c}' => self.dst.push_str("\\\\"), - c if c < '\u{1f}' => drop(write!(self.dst, "\\u{:04X}", ch as u32)), - ch => self.dst.push(ch), - } - } - match ty { - Type::NewlineTripple => self.dst.push_str("\"\"\""), - Type::OnelineSingle | Type::OnelineTripple => self.dst.push('"'), - } - }, - } - Ok(()) - } - - fn emit_table_header(&mut self, state: &State) -> Result<(), Error> { - let array_of_tables = match *state { - State::End => return Ok(()), - State::Array { .. } => true, - _ => false, - }; - - // Unlike [..]s, we can't omit [[..]] ancestors, so be sure to emit table - // headers for them. - let mut p = state; - if let State::Array { first, parent, .. } = *state { - if first.get() { - p = parent; - } - } - while let State::Table { first, parent, .. } = *p { - p = parent; - if !first.get() { - break; - } - if let State::Array { parent: &State::Table {..}, ..} = *parent { - self.emit_table_header(parent)?; - break; - } - } - - match *state { - State::Table { first, .. } => { - if !first.get() { - // Newline if we are a table that is not the first - // table in the document. - self.dst.push('\n'); - } - }, - State::Array { parent, first, .. } => { - if !first.get() { - // Always newline if we are not the first item in the - // table-array - self.dst.push('\n'); - } else if let State::Table { first, .. } = *parent { - if !first.get() { - // Newline if we are not the first item in the document - self.dst.push('\n'); - } - } - }, - _ => {} - } - self.dst.push_str("["); - if array_of_tables { - self.dst.push_str("["); - } - self.emit_key_part(state)?; - if array_of_tables { - self.dst.push_str("]"); - } - self.dst.push_str("]\n"); - Ok(()) - } - - fn emit_key_part(&mut self, key: &State) -> Result<bool, Error> { - match *key { - State::Array { parent, .. } => self.emit_key_part(parent), - State::End => Ok(true), - State::Table { key, parent, table_emitted, .. } => { - table_emitted.set(true); - let first = self.emit_key_part(parent)?; - if !first { - self.dst.push_str("."); - } - self.escape_key(key)?; - Ok(false) - } - } - } -} - -impl<'a, 'b> ser::Serializer for &'b mut Serializer<'a> { - type Ok = (); - type Error = Error; - type SerializeSeq = SerializeSeq<'a, 'b>; - type SerializeTuple = ser::Impossible<(), Error>; - type SerializeTupleStruct = ser::Impossible<(), Error>; - type SerializeTupleVariant = ser::Impossible<(), Error>; - type SerializeMap = SerializeTable<'a, 'b>; - type SerializeStruct = SerializeTable<'a, 'b>; - type SerializeStructVariant = ser::Impossible<(), Error>; - - fn serialize_bool(self, v: bool) -> Result<(), Self::Error> { - self.display(v, "bool") - } - - fn serialize_i8(self, v: i8) -> Result<(), Self::Error> { - self.display(v, "integer") - } - - fn serialize_i16(self, v: i16) -> Result<(), Self::Error> { - self.display(v, "integer") - } - - fn serialize_i32(self, v: i32) -> Result<(), Self::Error> { - self.display(v, "integer") - } - - fn serialize_i64(self, v: i64) -> Result<(), Self::Error> { - self.display(v, "integer") - } - - fn serialize_u8(self, v: u8) -> Result<(), Self::Error> { - self.display(v, "integer") - } - - fn serialize_u16(self, v: u16) -> Result<(), Self::Error> { - self.display(v, "integer") - } - - fn serialize_u32(self, v: u32) -> Result<(), Self::Error> { - self.display(v, "integer") - } - - fn serialize_u64(self, v: u64) -> Result<(), Self::Error> { - self.display(v, "integer") - } - - fn serialize_f32(mut self, v: f32) -> Result<(), Self::Error> { - if !v.is_finite() { - return Err(Error::NumberInvalid); - } - - self.emit_key("float")?; - drop(write!(self.dst, "{}", v)); - if v % 1.0 == 0.0 { - drop(write!(self.dst, ".0")); - } - if let State::Table { .. } = self.state { - self.dst.push_str("\n"); - } - Ok(()) - } - - fn serialize_f64(mut self, v: f64) -> Result<(), Self::Error> { - if !v.is_finite() { - return Err(Error::NumberInvalid); - } - - self.emit_key("float")?; - drop(write!(self.dst, "{}", v)); - if v % 1.0 == 0.0 { - drop(write!(self.dst, ".0")); - } - if let State::Table { .. } = self.state { - self.dst.push_str("\n"); - } - Ok(()) - } - - fn serialize_char(self, v: char) -> Result<(), Self::Error> { - let mut buf = [0; 4]; - self.serialize_str(v.encode_utf8(&mut buf)) - } - - fn serialize_str(mut self, value: &str) -> Result<(), Self::Error> { - self.emit_key("string")?; - self.emit_str(value, false)?; - if let State::Table { .. } = self.state { - self.dst.push_str("\n"); - } - Ok(()) - } - - fn serialize_bytes(self, value: &[u8]) -> Result<(), Self::Error> { - use serde::ser::Serialize; - value.serialize(self) - } - - fn serialize_none(self) -> Result<(), Self::Error> { - Err(Error::UnsupportedNone) - } - - fn serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Self::Error> - where T: ser::Serialize - { - value.serialize(self) - } - - fn serialize_unit(self) -> Result<(), Self::Error> { - Err(Error::UnsupportedType) - } - - fn serialize_unit_struct(self, - _name: &'static str) - -> Result<(), Self::Error> { - Err(Error::UnsupportedType) - } - - fn serialize_unit_variant(self, - _name: &'static str, - _variant_index: u32, - variant: &'static str) - -> Result<(), Self::Error> { - self.serialize_str(variant) - } - - fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) - -> Result<(), Self::Error> - where T: ser::Serialize, - { - value.serialize(self) - } - - fn serialize_newtype_variant<T: ?Sized>(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _value: &T) - -> Result<(), Self::Error> - where T: ser::Serialize, - { - Err(Error::UnsupportedType) - } - - fn serialize_seq(mut self, len: Option<usize>) - -> Result<Self::SerializeSeq, Self::Error> { - self.array_type("array")?; - Ok(SerializeSeq { - ser: self, - first: Cell::new(true), - type_: Cell::new(None), - len: len, - }) - } - - fn serialize_tuple(self, _len: usize) - -> Result<Self::SerializeTuple, Self::Error> { - Err(Error::UnsupportedType) - } - - fn serialize_tuple_struct(self, _name: &'static str, _len: usize) - -> Result<Self::SerializeTupleStruct, Self::Error> { - Err(Error::UnsupportedType) - } - - fn serialize_tuple_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result<Self::SerializeTupleVariant, Self::Error> { - Err(Error::UnsupportedType) - } - - fn serialize_map(mut self, _len: Option<usize>) - -> Result<Self::SerializeMap, Self::Error> { - self.array_type("table")?; - Ok(SerializeTable::Table { - ser: self, - key: String::new(), - first: Cell::new(true), - table_emitted: Cell::new(false), - }) - } - - fn serialize_struct(mut self, name: &'static str, _len: usize) - -> Result<Self::SerializeStruct, Self::Error> { - if name == SERDE_STRUCT_NAME { - self.array_type("datetime")?; - Ok(SerializeTable::Datetime(self)) - } else { - self.array_type("table")?; - Ok(SerializeTable::Table { - ser: self, - key: String::new(), - first: Cell::new(true), - table_emitted: Cell::new(false), - }) - } - } - - fn serialize_struct_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result<Self::SerializeStructVariant, Self::Error> { - Err(Error::UnsupportedType) - } -} - -impl<'a, 'b> ser::SerializeSeq for SerializeSeq<'a, 'b> { - type Ok = (); - type Error = Error; - - fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> - where T: ser::Serialize, - { - value.serialize(&mut Serializer { - dst: &mut *self.ser.dst, - state: State::Array { - parent: &self.ser.state, - first: &self.first, - type_: &self.type_, - len: self.len, - }, - settings: self.ser.settings.clone(), - })?; - self.first.set(false); - Ok(()) - } - - fn end(self) -> Result<(), Error> { - match self.type_.get() { - Some("table") => return Ok(()), - Some(_) => { - match (self.len, &self.ser.settings.array) { - (Some(0...1), _) | (_, &None) => { - self.ser.dst.push_str("]"); - }, - (_, &Some(ref a)) => { - if a.trailing_comma { - self.ser.dst.push_str(","); - } - self.ser.dst.push_str("\n]"); - }, - } - } - None => { - assert!(self.first.get()); - self.ser.emit_key("array")?; - self.ser.dst.push_str("[]") - } - } - if let State::Table { .. } = self.ser.state { - self.ser.dst.push_str("\n"); - } - Ok(()) - } -} - -impl<'a, 'b> ser::SerializeMap for SerializeTable<'a, 'b> { - type Ok = (); - type Error = Error; - - fn serialize_key<T: ?Sized>(&mut self, input: &T) -> Result<(), Error> - where T: ser::Serialize, - { - match *self { - SerializeTable::Datetime(_) => panic!(), // shouldn't be possible - SerializeTable::Table { ref mut key, .. } => { - key.truncate(0); - *key = input.serialize(StringExtractor)?; - } - } - Ok(()) - } - - fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> - where T: ser::Serialize, - { - match *self { - SerializeTable::Datetime(_) => panic!(), // shouldn't be possible - SerializeTable::Table { - ref mut ser, - ref key, - ref first, - ref table_emitted, - .. - } => { - let res = value.serialize(&mut Serializer { - dst: &mut *ser.dst, - state: State::Table { - key: key, - parent: &ser.state, - first: first, - table_emitted: table_emitted, - }, - settings: ser.settings.clone(), - }); - match res { - Ok(()) => first.set(false), - Err(Error::UnsupportedNone) => {}, - Err(e) => return Err(e), - } - } - } - Ok(()) - } - - fn end(self) -> Result<(), Error> { - match self { - SerializeTable::Datetime(_) => panic!(), // shouldn't be possible - SerializeTable::Table { mut ser, first, .. } => { - if first.get() { - let state = ser.state.clone(); - ser.emit_table_header(&state)?; - } - } - } - Ok(()) - } -} - -impl<'a, 'b> ser::SerializeStruct for SerializeTable<'a, 'b> { - type Ok = (); - type Error = Error; - - fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) - -> Result<(), Error> - where T: ser::Serialize, - { - match *self { - SerializeTable::Datetime(ref mut ser) => { - if key == SERDE_STRUCT_FIELD_NAME { - value.serialize(DateStrEmitter(&mut *ser))?; - } else { - return Err(Error::DateInvalid) - } - } - SerializeTable::Table { - ref mut ser, - ref first, - ref table_emitted, - .. - } => { - let res = value.serialize(&mut Serializer { - dst: &mut *ser.dst, - state: State::Table { - key: key, - parent: &ser.state, - first: first, - table_emitted: table_emitted, - }, - settings: ser.settings.clone(), - }); - match res { - Ok(()) => first.set(false), - Err(Error::UnsupportedNone) => {}, - Err(e) => return Err(e), - } - } - } - Ok(()) - } - - fn end(self) -> Result<(), Error> { - match self { - SerializeTable::Datetime(_) => {}, - SerializeTable::Table { mut ser, first, .. } => { - if first.get() { - let state = ser.state.clone(); - ser.emit_table_header(&state)?; - } - } - } - Ok(()) - } -} - -struct DateStrEmitter<'a: 'b, 'b>(&'b mut Serializer<'a>); - -impl<'a, 'b> ser::Serializer for DateStrEmitter<'a, 'b> { - type Ok = (); - type Error = Error; - type SerializeSeq = ser::Impossible<(), Error>; - type SerializeTuple = ser::Impossible<(), Error>; - type SerializeTupleStruct = ser::Impossible<(), Error>; - type SerializeTupleVariant = ser::Impossible<(), Error>; - type SerializeMap = ser::Impossible<(), Error>; - type SerializeStruct = ser::Impossible<(), Error>; - type SerializeStructVariant = ser::Impossible<(), Error>; - - fn serialize_bool(self, _v: bool) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_i8(self, _v: i8) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_i16(self, _v: i16) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_i32(self, _v: i32) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_i64(self, _v: i64) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_u8(self, _v: u8) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_u16(self, _v: u16) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_u32(self, _v: u32) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_u64(self, _v: u64) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_f32(self, _v: f32) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_f64(self, _v: f64) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_char(self, _v: char) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_str(self, value: &str) -> Result<(), Self::Error> { - self.0.display(value, "datetime")?; - Ok(()) - } - - fn serialize_bytes(self, _value: &[u8]) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_none(self) -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<(), Self::Error> - where T: ser::Serialize - { - Err(Error::KeyNotString) - } - - fn serialize_unit(self) -> Result<(), Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_unit_struct(self, - _name: &'static str) - -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_unit_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str) - -> Result<(), Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, _value: &T) - -> Result<(), Self::Error> - where T: ser::Serialize, - { - Err(Error::DateInvalid) - } - - fn serialize_newtype_variant<T: ?Sized>(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _value: &T) - -> Result<(), Self::Error> - where T: ser::Serialize, - { - Err(Error::DateInvalid) - } - - fn serialize_seq(self, _len: Option<usize>) - -> Result<Self::SerializeSeq, Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_tuple(self, _len: usize) - -> Result<Self::SerializeTuple, Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_tuple_struct(self, _name: &'static str, _len: usize) - -> Result<Self::SerializeTupleStruct, Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_tuple_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result<Self::SerializeTupleVariant, Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_map(self, _len: Option<usize>) - -> Result<Self::SerializeMap, Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_struct(self, _name: &'static str, _len: usize) - -> Result<Self::SerializeStruct, Self::Error> { - Err(Error::DateInvalid) - } - - fn serialize_struct_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result<Self::SerializeStructVariant, Self::Error> { - Err(Error::DateInvalid) - } -} - -struct StringExtractor; - -impl ser::Serializer for StringExtractor { - type Ok = String; - type Error = Error; - type SerializeSeq = ser::Impossible<String, Error>; - type SerializeTuple = ser::Impossible<String, Error>; - type SerializeTupleStruct = ser::Impossible<String, Error>; - type SerializeTupleVariant = ser::Impossible<String, Error>; - type SerializeMap = ser::Impossible<String, Error>; - type SerializeStruct = ser::Impossible<String, Error>; - type SerializeStructVariant = ser::Impossible<String, Error>; - - fn serialize_bool(self, _v: bool) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_i8(self, _v: i8) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_i16(self, _v: i16) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_i32(self, _v: i32) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_i64(self, _v: i64) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_u8(self, _v: u8) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_u16(self, _v: u16) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_u32(self, _v: u32) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_u64(self, _v: u64) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_f32(self, _v: f32) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_f64(self, _v: f64) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_char(self, _v: char) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_str(self, value: &str) -> Result<String, Self::Error> { - Ok(value.to_string()) - } - - fn serialize_bytes(self, _value: &[u8]) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_none(self) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<String, Self::Error> - where T: ser::Serialize - { - Err(Error::KeyNotString) - } - - fn serialize_unit(self) -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_unit_struct(self, - _name: &'static str) - -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_unit_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str) - -> Result<String, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, _value: &T) - -> Result<String, Self::Error> - where T: ser::Serialize, - { - Err(Error::KeyNotString) - } - - fn serialize_newtype_variant<T: ?Sized>(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _value: &T) - -> Result<String, Self::Error> - where T: ser::Serialize, - { - Err(Error::KeyNotString) - } - - fn serialize_seq(self, _len: Option<usize>) - -> Result<Self::SerializeSeq, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_tuple(self, _len: usize) - -> Result<Self::SerializeTuple, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_tuple_struct(self, _name: &'static str, _len: usize) - -> Result<Self::SerializeTupleStruct, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_tuple_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result<Self::SerializeTupleVariant, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_map(self, _len: Option<usize>) - -> Result<Self::SerializeMap, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_struct(self, _name: &'static str, _len: usize) - -> Result<Self::SerializeStruct, Self::Error> { - Err(Error::KeyNotString) - } - - fn serialize_struct_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result<Self::SerializeStructVariant, Self::Error> { - Err(Error::KeyNotString) - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Error::UnsupportedType => "unsupported Rust type".fmt(f), - Error::KeyNotString => "map key was not a string".fmt(f), - Error::ArrayMixedType => "arrays cannot have mixed types".fmt(f), - Error::ValueAfterTable => "values must be emitted before tables".fmt(f), - Error::DateInvalid => "a serialized date was invalid".fmt(f), - Error::NumberInvalid => "a serialized number was invalid".fmt(f), - Error::UnsupportedNone => "unsupported None value".fmt(f), - Error::Custom(ref s) => s.fmt(f), - Error::KeyNewline => unreachable!(), - Error::__Nonexhaustive => panic!(), - } - } -} - -impl error::Error for Error { - fn description(&self) -> &str { - match *self { - Error::UnsupportedType => "unsupported Rust type", - Error::KeyNotString => "map key was not a string", - Error::ArrayMixedType => "arrays cannot have mixed types", - Error::ValueAfterTable => "values must be emitted before tables", - Error::DateInvalid => "a serialized date was invalid", - Error::NumberInvalid => "a serialized number was invalid", - Error::UnsupportedNone => "unsupported None value", - Error::Custom(_) => "custom error", - Error::KeyNewline => unreachable!(), - Error::__Nonexhaustive => panic!(), - } - } -} - -impl ser::Error for Error { - fn custom<T: fmt::Display>(msg: T) -> Error { - Error::Custom(msg.to_string()) - } -} - -enum Category { - Primitive, - Array, - Table, -} - -/// Convenience function to serialize items in a map in an order valid with -/// TOML. -/// -/// TOML carries the restriction that keys in a table must be serialized last if -/// their value is a table itself. This isn't always easy to guarantee, so this -/// helper can be used like so: -/// -/// ```rust -/// # #[macro_use] extern crate serde_derive; -/// # extern crate toml; -/// # use std::collections::HashMap; -/// #[derive(Serialize)] -/// struct Manifest { -/// package: Package, -/// #[serde(serialize_with = "toml::ser::tables_last")] -/// dependencies: HashMap<String, Dependency>, -/// } -/// # type Package = String; -/// # type Dependency = String; -/// # fn main() {} -/// ``` -pub fn tables_last<'a, I, K, V, S>(data: &'a I, serializer: S) - -> Result<S::Ok, S::Error> - where &'a I: IntoIterator<Item = (K, V)>, - K: ser::Serialize, - V: ser::Serialize, - S: ser::Serializer -{ - use serde::ser::SerializeMap; - - let mut map = serializer.serialize_map(None)?; - for (k, v) in data { - if let Category::Primitive = v.serialize(Categorize::new())? { - map.serialize_entry(&k, &v)?; - } - } - for (k, v) in data { - if let Category::Array = v.serialize(Categorize::new())? { - map.serialize_entry(&k, &v)?; - } - } - for (k, v) in data { - if let Category::Table = v.serialize(Categorize::new())? { - map.serialize_entry(&k, &v)?; - } - } - map.end() -} - -struct Categorize<E>(marker::PhantomData<E>); - -impl<E> Categorize<E> { - fn new() -> Self { - Categorize(marker::PhantomData) - } -} - -impl<E: ser::Error> ser::Serializer for Categorize<E> { - type Ok = Category; - type Error = E; - type SerializeSeq = Self; - type SerializeTuple = ser::Impossible<Category, E>; - type SerializeTupleStruct = ser::Impossible<Category, E>; - type SerializeTupleVariant = ser::Impossible<Category, E>; - type SerializeMap = Self; - type SerializeStruct = Self; - type SerializeStructVariant = ser::Impossible<Category, E>; - - fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> { - Ok(Category::Primitive) - } - - fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> { - Ok(Category::Array) - } - - fn serialize_none(self) -> Result<Self::Ok, Self::Error> { - Err(ser::Error::custom("unsupported")) - } - - fn serialize_some<T: ?Sized + ser::Serialize>(self, v: &T) -> Result<Self::Ok, Self::Error> { - v.serialize(self) - } - - fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { - Err(ser::Error::custom("unsupported")) - } - - fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> { - Err(ser::Error::custom("unsupported")) - } - - fn serialize_unit_variant(self, _: &'static str, _: u32, _: &'static str) -> Result<Self::Ok, Self::Error> { - Err(ser::Error::custom("unsupported")) - } - - fn serialize_newtype_struct<T: ?Sized + ser::Serialize>(self, _: &'static str, v: &T) -> Result<Self::Ok, Self::Error> { - v.serialize(self) - } - - fn serialize_newtype_variant<T: ?Sized + ser::Serialize>(self, _: &'static str, _: u32, _: &'static str, _: &T) -> Result<Self::Ok, Self::Error> { - Err(ser::Error::custom("unsupported")) - } - - fn serialize_seq(self, _: Option<usize>) -> Result<Self, Self::Error> { - Ok(self) - } - - fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> { - Err(ser::Error::custom("unsupported")) - } - - fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result<Self::SerializeTupleStruct, Self::Error> { - Err(ser::Error::custom("unsupported")) - } - - fn serialize_tuple_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result<Self::SerializeTupleVariant, Self::Error> { - Err(ser::Error::custom("unsupported")) - } - - fn serialize_map(self, _: Option<usize>) -> Result<Self, Self::Error> { - Ok(self) - } - - fn serialize_struct(self, _: &'static str, _: usize) -> Result<Self, Self::Error> { - Ok(self) - } - - fn serialize_struct_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result<Self::SerializeStructVariant, Self::Error> { - Err(ser::Error::custom("unsupported")) - } -} - -impl<E: ser::Error> ser::SerializeSeq for Categorize<E> { - type Ok = Category; - type Error = E; - - fn serialize_element<T: ?Sized + ser::Serialize>(&mut self, _: &T) - -> Result<(), Self::Error> { - Ok(()) - } - - fn end(self) -> Result<Self::Ok, Self::Error> { - Ok(Category::Array) - } -} - -impl<E: ser::Error> ser::SerializeMap for Categorize<E> { - type Ok = Category; - type Error = E; - - fn serialize_key<T: ?Sized + ser::Serialize>(&mut self, _: &T) - -> Result<(), Self::Error> { - Ok(()) - } - - fn serialize_value<T: ?Sized + ser::Serialize>(&mut self, _: &T) - -> Result<(), Self::Error> { - Ok(()) - } - - fn end(self) -> Result<Self::Ok, Self::Error> { - Ok(Category::Table) - } -} - -impl<E: ser::Error> ser::SerializeStruct for Categorize<E> { - type Ok = Category; - type Error = E; - - fn serialize_field<T: ?Sized>(&mut self, - _: &'static str, - _: &T) -> Result<(), Self::Error> - where T: ser::Serialize, - { - Ok(()) - } - - fn end(self) -> Result<Self::Ok, Self::Error> { - Ok(Category::Table) - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/src/tokens.rs cargo-0.26.0/vendor/toml-0.4.5/src/tokens.rs --- cargo-0.25.0/vendor/toml-0.4.5/src/tokens.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/src/tokens.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,620 +0,0 @@ -use std::borrow::Cow; -use std::char; -use std::str; -use std::string; - -use self::Token::*; - -#[derive(Eq, PartialEq, Debug)] -pub enum Token<'a> { - Whitespace(&'a str), - Newline, - Comment(&'a str), - - Equals, - Period, - Comma, - Colon, - Plus, - LeftBrace, - RightBrace, - LeftBracket, - RightBracket, - - Keylike(&'a str), - String { src: &'a str, val: Cow<'a, str> }, -} - -#[derive(Eq, PartialEq, Debug)] -pub enum Error { - InvalidCharInString(usize, char), - InvalidEscape(usize, char), - InvalidHexEscape(usize, char), - InvalidEscapeValue(usize, u32), - NewlineInString(usize), - Unexpected(usize, char), - UnterminatedString(usize), - NewlineInTableKey(usize), - EmptyTableKey(usize), - Wanted { at: usize, expected: &'static str, found: &'static str }, -} - -#[derive(Clone)] -pub struct Tokenizer<'a> { - input: &'a str, - chars: CrlfFold<'a>, -} - -#[derive(Clone)] -struct CrlfFold<'a> { - chars: str::CharIndices<'a>, -} - -#[derive(Debug)] -enum MaybeString { - NotEscaped(usize), - Owned(string::String), -} - -impl<'a> Tokenizer<'a> { - pub fn new(input: &'a str) -> Tokenizer<'a> { - let mut t = Tokenizer { - input: input, - chars: CrlfFold { - chars: input.char_indices(), - }, - }; - // Eat utf-8 BOM - t.eatc('\u{feff}'); - t - } - - pub fn next(&mut self) -> Result<Option<Token<'a>>, Error> { - let token = match self.chars.next() { - Some((_, '\n')) => Newline, - Some((start, ' ')) => self.whitespace_token(start), - Some((start, '\t')) => self.whitespace_token(start), - Some((start, '#')) => self.comment_token(start), - Some((_, '=')) => Equals, - Some((_, '.')) => Period, - Some((_, ',')) => Comma, - Some((_, ':')) => Colon, - Some((_, '+')) => Plus, - Some((_, '{')) => LeftBrace, - Some((_, '}')) => RightBrace, - Some((_, '[')) => LeftBracket, - Some((_, ']')) => RightBracket, - Some((start, '\'')) => return self.literal_string(start).map(Some), - Some((start, '"')) => return self.basic_string(start).map(Some), - Some((start, ch)) if is_keylike(ch) => self.keylike(start), - - Some((start, ch)) => return Err(Error::Unexpected(start, ch)), - None => return Ok(None), - }; - Ok(Some(token)) - } - - pub fn peek(&mut self) -> Result<Option<Token<'a>>, Error> { - self.clone().next() - } - - pub fn eat(&mut self, expected: Token<'a>) -> Result<bool, Error> { - match self.peek()? { - Some(ref found) if expected == *found => {} - Some(_) => return Ok(false), - None => return Ok(false), - } - drop(self.next()); - Ok(true) - } - - pub fn expect(&mut self, expected: Token<'a>) -> Result<(), Error> { - let current = self.current(); - match self.next()? { - Some(found) => { - if expected == found { - Ok(()) - } else { - Err(Error::Wanted { - at: current, - expected: expected.describe(), - found: found.describe(), - }) - } - } - None => { - Err(Error::Wanted { - at: self.input.len(), - expected: expected.describe(), - found: "eof", - }) - } - } - } - - pub fn table_key(&mut self) -> Result<Cow<'a, str>, Error> { - let current = self.current(); - match self.next()? { - Some(Token::Keylike(k)) => Ok(k.into()), - Some(Token::String { src, val }) => { - let offset = self.substr_offset(src); - if val == "" { - return Err(Error::EmptyTableKey(offset)) - } - match src.find('\n') { - None => Ok(val), - Some(i) => Err(Error::NewlineInTableKey(offset + i)), - } - } - Some(other) => { - Err(Error::Wanted { - at: current, - expected: "a table key", - found: other.describe(), - }) - } - None => { - Err(Error::Wanted { - at: self.input.len(), - expected: "a table key", - found: "eof", - }) - } - } - } - - pub fn eat_whitespace(&mut self) -> Result<(), Error> { - while self.eatc(' ') || self.eatc('\t') { - // ... - } - Ok(()) - } - - pub fn eat_comment(&mut self) -> Result<bool, Error> { - if !self.eatc('#') { - return Ok(false) - } - drop(self.comment_token(0)); - self.eat_newline_or_eof().map(|()| true) - } - - pub fn eat_newline_or_eof(&mut self) -> Result<(), Error> { - let current = self.current(); - match self.next()? { - None | - Some(Token::Newline) => Ok(()), - Some(other) => { - Err(Error::Wanted { - at: current, - expected: "newline", - found: other.describe(), - }) - } - } - } - - pub fn skip_to_newline(&mut self) { - loop { - match self.chars.next() { - Some((_, '\n')) | - None => break, - _ => {} - } - } - } - - fn eatc(&mut self, ch: char) -> bool { - match self.chars.clone().next() { - Some((_, ch2)) if ch == ch2 => { - self.chars.next(); - true - } - _ => false, - } - } - - pub fn current(&mut self) -> usize { - self.chars.clone().next().map(|i| i.0).unwrap_or(self.input.len()) - } - - pub fn input(&self) -> &'a str { - self.input - } - - fn whitespace_token(&mut self, start: usize) -> Token<'a> { - while self.eatc(' ') || self.eatc('\t') { - // ... - } - Whitespace(&self.input[start..self.current()]) - } - - fn comment_token(&mut self, start: usize) -> Token<'a> { - while let Some((_, ch)) = self.chars.clone().next() { - if ch != '\t' && (ch < '\u{20}' || ch > '\u{10ffff}') { - break - } - self.chars.next(); - } - Comment(&self.input[start..self.current()]) - } - - fn read_string(&mut self, - delim: char, - start: usize, - new_ch: &mut FnMut(&mut Tokenizer, &mut MaybeString, - bool, usize, char) - -> Result<(), Error>) - -> Result<Token<'a>, Error> { - let mut multiline = false; - if self.eatc(delim) { - if self.eatc(delim) { - multiline = true; - } else { - return Ok(String { - src: &self.input[start..start+2], - val: Cow::Borrowed(""), - }) - } - } - let mut val = MaybeString::NotEscaped(self.current()); - let mut n = 0; - 'outer: loop { - n += 1; - match self.chars.next() { - Some((i, '\n')) => { - if multiline { - if self.input.as_bytes()[i] == b'\r' { - val.to_owned(&self.input[..i]); - } - if n == 1 { - val = MaybeString::NotEscaped(self.current()); - } else { - val.push('\n'); - } - continue - } else { - return Err(Error::NewlineInString(i)) - } - } - Some((i, ch)) if ch == delim => { - if multiline { - for _ in 0..2 { - if !self.eatc(delim) { - val.push(delim); - continue 'outer - } - } - } - return Ok(String { - src: &self.input[start..self.current()], - val: val.into_cow(&self.input[..i]), - }) - } - Some((i, c)) => try!(new_ch(self, &mut val, multiline, i, c)), - None => return Err(Error::UnterminatedString(start)) - } - } - } - - fn literal_string(&mut self, start: usize) -> Result<Token<'a>, Error> { - self.read_string('\'', start, &mut |_me, val, _multi, i, ch| { - if ch == '\u{09}' || ('\u{20}' <= ch && ch <= '\u{10ffff}') { - val.push(ch); - Ok(()) - } else { - Err(Error::InvalidCharInString(i, ch)) - } - }) - } - - fn basic_string(&mut self, start: usize) -> Result<Token<'a>, Error> { - self.read_string('"', start, &mut |me, val, multi, i, ch| { - match ch { - '\\' => { - val.to_owned(&me.input[..i]); - match me.chars.next() { - Some((_, '"')) => val.push('"'), - Some((_, '\\')) => val.push('\\'), - Some((_, 'b')) => val.push('\u{8}'), - Some((_, 'f')) => val.push('\u{c}'), - Some((_, 'n')) => val.push('\n'), - Some((_, 'r')) => val.push('\r'), - Some((_, 't')) => val.push('\t'), - Some((i, c @ 'u')) | - Some((i, c @ 'U')) => { - let len = if c == 'u' {4} else {8}; - val.push(try!(me.hex(start, i, len))); - } - Some((_, '\n')) if multi => { - while let Some((_, ch)) = me.chars.clone().next() { - match ch { - ' ' | '\t' | '\n' => { - me.chars.next(); - } - _ => break, - } - } - } - Some((i, c)) => return Err(Error::InvalidEscape(i, c)), - None => return Err(Error::UnterminatedString(start)), - } - Ok(()) - } - ch if '\u{20}' <= ch && ch <= '\u{10ffff}' => { - val.push(ch); - Ok(()) - } - _ => Err(Error::InvalidCharInString(i, ch)) - } - }) - } - - fn hex(&mut self, start: usize, i: usize, len: usize) -> Result<char, Error> { - let mut val = 0; - for _ in 0..len { - match self.chars.next() { - Some((_, ch)) if '0' <= ch && ch <= '9' => { - val = val * 16 + (ch as u32 - '0' as u32); - } - Some((_, ch)) if 'A' <= ch && ch <= 'F' => { - val = val * 16 + (ch as u32 - 'A' as u32) + 10; - } - Some((i, ch)) => return Err(Error::InvalidHexEscape(i, ch)), - None => return Err(Error::UnterminatedString(start)), - } - } - match char::from_u32(val) { - Some(ch) => Ok(ch), - None => Err(Error::InvalidEscapeValue(i, val)), - } - } - - fn keylike(&mut self, start: usize) -> Token<'a> { - while let Some((_, ch)) = self.chars.clone().next() { - if !is_keylike(ch) { - break - } - self.chars.next(); - } - Keylike(&self.input[start..self.current()]) - } - - pub fn substr_offset(&self, s: &'a str) -> usize { - assert!(s.len() <= self.input.len()); - let a = self.input.as_ptr() as usize; - let b = s.as_ptr() as usize; - assert!(a <= b); - b - a - } -} - -impl<'a> Iterator for CrlfFold<'a> { - type Item = (usize, char); - - fn next(&mut self) -> Option<(usize, char)> { - self.chars.next().map(|(i, c)| { - if c == '\r' { - let mut attempt = self.chars.clone(); - if let Some((_, '\n')) = attempt.next() { - self.chars = attempt; - return (i, '\n') - } - } - (i, c) - }) - } -} - -impl MaybeString { - fn push(&mut self, ch: char) { - match *self { - MaybeString::NotEscaped(..) => {} - MaybeString::Owned(ref mut s) => s.push(ch), - } - } - - fn to_owned(&mut self, input: &str) { - match *self { - MaybeString::NotEscaped(start) => { - *self = MaybeString::Owned(input[start..].to_owned()); - } - MaybeString::Owned(..) => {} - } - } - - fn into_cow(self, input: &str) -> Cow<str> { - match self { - MaybeString::NotEscaped(start) => Cow::Borrowed(&input[start..]), - MaybeString::Owned(s) => Cow::Owned(s), - } - } -} - -fn is_keylike(ch: char) -> bool { - ('A' <= ch && ch <= 'Z') || - ('a' <= ch && ch <= 'z') || - ('0' <= ch && ch <= '9') || - ch == '-' || - ch == '_' -} - -impl<'a> Token<'a> { - pub fn describe(&self) -> &'static str { - match *self { - Token::Keylike(_) => "an identifier", - Token::Equals => "an equals", - Token::Period => "a period", - Token::Comment(_) => "a comment", - Token::Newline => "a newline", - Token::Whitespace(_) => "whitespace", - Token::Comma => "a comma", - Token::RightBrace => "a right brace", - Token::LeftBrace => "a left brace", - Token::RightBracket => "a right bracket", - Token::LeftBracket => "a left bracket", - Token::String { .. } => "a string", - Token::Colon => "a colon", - Token::Plus => "a plus", - } - } -} - -#[cfg(test)] -mod tests { - use std::borrow::Cow; - use super::{Tokenizer, Token, Error}; - - fn err(input: &str, err: Error) { - let mut t = Tokenizer::new(input); - let token = t.next().unwrap_err(); - assert_eq!(token, err); - assert!(t.next().unwrap().is_none()); - } - - #[test] - fn literal_strings() { - fn t(input: &str, val: &str) { - let mut t = Tokenizer::new(input); - let token = t.next().unwrap().unwrap(); - assert_eq!(token, Token::String { - src: input, - val: Cow::Borrowed(val), - }); - assert!(t.next().unwrap().is_none()); - } - - t("''", ""); - t("''''''", ""); - t("'''\n'''", ""); - t("'a'", "a"); - t("'\"a'", "\"a"); - t("''''a'''", "'a"); - t("'''\n'a\n'''", "'a\n"); - t("'''a\n'a\r\n'''", "a\n'a\n"); - } - - #[test] - fn basic_strings() { - fn t(input: &str, val: &str) { - let mut t = Tokenizer::new(input); - let token = t.next().unwrap().unwrap(); - assert_eq!(token, Token::String { - src: input, - val: Cow::Borrowed(val), - }); - assert!(t.next().unwrap().is_none()); - } - - t(r#""""#, ""); - t(r#""""""""#, ""); - t(r#""a""#, "a"); - t(r#""""a""""#, "a"); - t(r#""\t""#, "\t"); - t(r#""\u0000""#, "\0"); - t(r#""\U00000000""#, "\0"); - t(r#""\U000A0000""#, "\u{A0000}"); - t(r#""\\t""#, "\\t"); - t("\"\"\"\\\n\"\"\"", ""); - t("\"\"\"\\\n \t \t \\\r\n \t \n \t \r\n\"\"\"", ""); - t(r#""\r""#, "\r"); - t(r#""\n""#, "\n"); - t(r#""\b""#, "\u{8}"); - t(r#""a\fa""#, "a\u{c}a"); - t(r#""\"a""#, "\"a"); - t("\"\"\"\na\"\"\"", "a"); - t("\"\"\"\n\"\"\"", ""); - err(r#""\a"#, Error::InvalidEscape(2, 'a')); - err("\"\\\n", Error::InvalidEscape(2, '\n')); - err("\"\\\r\n", Error::InvalidEscape(2, '\n')); - err("\"\\", Error::UnterminatedString(0)); - err("\"\u{0}", Error::InvalidCharInString(1, '\u{0}')); - err(r#""\U00""#, Error::InvalidHexEscape(5, '"')); - err(r#""\U00"#, Error::UnterminatedString(0)); - err(r#""\uD800"#, Error::InvalidEscapeValue(2, 0xd800)); - err(r#""\UFFFFFFFF"#, Error::InvalidEscapeValue(2, 0xffffffff)); - } - - #[test] - fn keylike() { - fn t(input: &str) { - let mut t = Tokenizer::new(input); - let token = t.next().unwrap().unwrap(); - assert_eq!(token, Token::Keylike(input)); - assert!(t.next().unwrap().is_none()); - } - t("foo"); - t("0bar"); - t("bar0"); - t("1234"); - t("a-b"); - t("a_B"); - t("-_-"); - t("___"); - } - - #[test] - fn all() { - fn t(input: &str, expected: &[Token]) { - let mut tokens = Tokenizer::new(input); - let mut actual = Vec::new(); - while let Some(token) = tokens.next().unwrap() { - actual.push(token); - } - for (a, b) in actual.iter().zip(expected) { - assert_eq!(a, b); - } - assert_eq!(actual.len(), expected.len()); - } - - t(" a ", &[ - Token::Whitespace(" "), - Token::Keylike("a"), - Token::Whitespace(" "), - ]); - - t(" a\t [[]] \t [] {} , . =\n# foo \r\n#foo \n ", &[ - Token::Whitespace(" "), - Token::Keylike("a"), - Token::Whitespace("\t "), - Token::LeftBracket, - Token::LeftBracket, - Token::RightBracket, - Token::RightBracket, - Token::Whitespace(" \t "), - Token::LeftBracket, - Token::RightBracket, - Token::Whitespace(" "), - Token::LeftBrace, - Token::RightBrace, - Token::Whitespace(" "), - Token::Comma, - Token::Whitespace(" "), - Token::Period, - Token::Whitespace(" "), - Token::Equals, - Token::Newline, - Token::Comment("# foo "), - Token::Newline, - Token::Comment("#foo "), - Token::Newline, - Token::Whitespace(" "), - ]); - } - - #[test] - fn bare_cr_bad() { - err("\r", Error::Unexpected(0, '\r')); - err("'\n", Error::NewlineInString(1)); - err("'\u{0}", Error::InvalidCharInString(1, '\u{0}')); - err("'", Error::UnterminatedString(0)); - err("\u{0}", Error::Unexpected(0, '\u{0}')); - } - - #[test] - fn bad_comment() { - let mut t = Tokenizer::new("#\u{0}"); - t.next().unwrap().unwrap(); - assert_eq!(t.next(), Err(Error::Unexpected(1, '\u{0}'))); - assert!(t.next().unwrap().is_none()); - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/src/value.rs cargo-0.26.0/vendor/toml-0.4.5/src/value.rs --- cargo-0.25.0/vendor/toml-0.4.5/src/value.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/src/value.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,946 +0,0 @@ -//! Definition of a TOML value - -use std::collections::{BTreeMap, HashMap}; -use std::hash::Hash; -use std::fmt; -use std::ops; -use std::str::FromStr; -use std::vec; - -use serde::ser; -use serde::de; -use serde::de::IntoDeserializer; - -pub use datetime::{Datetime, DatetimeParseError}; -use datetime::{DatetimeFromString, SERDE_STRUCT_FIELD_NAME}; - -/// Representation of a TOML value. -#[derive(PartialEq, Clone, Debug)] -pub enum Value { - /// Represents a TOML string - String(String), - /// Represents a TOML integer - Integer(i64), - /// Represents a TOML float - Float(f64), - /// Represents a TOML boolean - Boolean(bool), - /// Represents a TOML datetime - Datetime(Datetime), - /// Represents a TOML array - Array(Array), - /// Represents a TOML table - Table(Table), -} - -/// Type representing a TOML array, payload of the `Value::Array` variant -pub type Array = Vec<Value>; - -/// Type representing a TOML table, payload of the `Value::Table` variant -pub type Table = BTreeMap<String, Value>; - -impl Value { - /// Convert a `T` into `toml::Value` which is an enum that can represent - /// any valid TOML data. - /// - /// This conversion can fail if `T`'s implementation of `Serialize` decides to - /// fail, or if `T` contains a map with non-string keys. - pub fn try_from<T>(value: T) -> Result<Value, ::ser::Error> - where T: ser::Serialize, - { - value.serialize(Serializer) - } - - /// Interpret a `toml::Value` as an instance of type `T`. - /// - /// This conversion can fail if the structure of the `Value` does not match the - /// structure expected by `T`, for example if `T` is a struct type but the - /// `Value` contains something other than a TOML table. It can also fail if the - /// structure is correct but `T`'s implementation of `Deserialize` decides that - /// something is wrong with the data, for example required struct fields are - /// missing from the TOML map or some number is too big to fit in the expected - /// primitive type. - pub fn try_into<'de, T>(self) -> Result<T, ::de::Error> - where T: de::Deserialize<'de>, - { - de::Deserialize::deserialize(self) - } - - /// Index into a TOML array or map. A string index can be used to access a - /// value in a map, and a usize index can be used to access an element of an - /// array. - /// - /// Returns `None` if the type of `self` does not match the type of the - /// index, for example if the index is a string and `self` is an array or a - /// number. Also returns `None` if the given key does not exist in the map - /// or the given index is not within the bounds of the array. - pub fn get<I: Index>(&self, index: I) -> Option<&Value> { - index.index(self) - } - - /// Mutably index into a TOML array or map. A string index can be used to - /// access a value in a map, and a usize index can be used to access an - /// element of an array. - /// - /// Returns `None` if the type of `self` does not match the type of the - /// index, for example if the index is a string and `self` is an array or a - /// number. Also returns `None` if the given key does not exist in the map - /// or the given index is not within the bounds of the array. - pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> { - index.index_mut(self) - } - - /// Extracts the integer value if it is an integer. - pub fn as_integer(&self) -> Option<i64> { - match *self { Value::Integer(i) => Some(i), _ => None } - } - - /// Tests whether this value is an integer - pub fn is_integer(&self) -> bool { - self.as_integer().is_some() - } - - /// Extracts the float value if it is a float. - pub fn as_float(&self) -> Option<f64> { - match *self { Value::Float(f) => Some(f), _ => None } - } - - /// Tests whether this value is a float - pub fn is_float(&self) -> bool { - self.as_float().is_some() - } - - /// Extracts the boolean value if it is a boolean. - pub fn as_bool(&self) -> Option<bool> { - match *self { Value::Boolean(b) => Some(b), _ => None } - } - - /// Tests whether this value is a boolean - pub fn is_bool(&self) -> bool { - self.as_bool().is_some() - } - - /// Extracts the string of this value if it is a string. - pub fn as_str(&self) -> Option<&str> { - match *self { Value::String(ref s) => Some(&**s), _ => None } - } - - /// Tests if this value is a string - pub fn is_str(&self) -> bool { - self.as_str().is_some() - } - - /// Extracts the datetime value if it is a datetime. - /// - /// Note that a parsed TOML value will only contain ISO 8601 dates. An - /// example date is: - /// - /// ```notrust - /// 1979-05-27T07:32:00Z - /// ``` - pub fn as_datetime(&self) -> Option<&Datetime> { - match *self { Value::Datetime(ref s) => Some(s), _ => None } - } - - /// Tests whether this value is a datetime - pub fn is_datetime(&self) -> bool { - self.as_datetime().is_some() - } - - /// Extracts the array value if it is an array. - pub fn as_array(&self) -> Option<&Vec<Value>> { - match *self { Value::Array(ref s) => Some(s), _ => None } - } - - /// Extracts the array value if it is an array. - pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> { - match *self { Value::Array(ref mut s) => Some(s), _ => None } - } - - /// Tests whether this value is an array - pub fn is_array(&self) -> bool { - self.as_array().is_some() - } - - /// Extracts the table value if it is a table. - pub fn as_table(&self) -> Option<&Table> { - match *self { Value::Table(ref s) => Some(s), _ => None } - } - - /// Extracts the table value if it is a table. - pub fn as_table_mut(&mut self) -> Option<&mut Table> { - match *self { Value::Table(ref mut s) => Some(s), _ => None } - } - - /// Extracts the table value if it is a table. - pub fn is_table(&self) -> bool { - self.as_table().is_some() - } - - /// Tests whether this and another value have the same type. - pub fn same_type(&self, other: &Value) -> bool { - match (self, other) { - (&Value::String(..), &Value::String(..)) | - (&Value::Integer(..), &Value::Integer(..)) | - (&Value::Float(..), &Value::Float(..)) | - (&Value::Boolean(..), &Value::Boolean(..)) | - (&Value::Datetime(..), &Value::Datetime(..)) | - (&Value::Array(..), &Value::Array(..)) | - (&Value::Table(..), &Value::Table(..)) => true, - - _ => false, - } - } - - /// Returns a human-readable representation of the type of this value. - pub fn type_str(&self) -> &'static str { - match *self { - Value::String(..) => "string", - Value::Integer(..) => "integer", - Value::Float(..) => "float", - Value::Boolean(..) => "boolean", - Value::Datetime(..) => "datetime", - Value::Array(..) => "array", - Value::Table(..) => "table", - } - } -} - -impl<I> ops::Index<I> for Value where I: Index { - type Output = Value; - - fn index(&self, index: I) -> &Value { - self.get(index).expect("index not found") - } -} - -impl<I> ops::IndexMut<I> for Value where I: Index { - fn index_mut(&mut self, index: I) -> &mut Value { - self.get_mut(index).expect("index not found") - } -} - -impl<'a> From<&'a str> for Value { - #[inline] - fn from(val: &'a str) -> Value { - Value::String(val.to_string()) - } -} - -impl<V: Into<Value>> From<Vec<V>> for Value { - fn from(val: Vec<V>) -> Value { - Value::Array(val.into_iter().map(|v| v.into()).collect()) - } -} - -impl<S: Into<String>, V: Into<Value>> From<BTreeMap<S, V>> for Value { - fn from(val: BTreeMap<S, V>) -> Value { - let table = val.into_iter() - .map(|(s, v)| (s.into(), v.into())) - .collect(); - - Value::Table(table) - } -} - -impl<S: Into<String> + Hash + Eq, V: Into<Value>> From<HashMap<S, V>> for Value { - fn from(val: HashMap<S, V>) -> Value { - let table = val.into_iter() - .map(|(s, v)| (s.into(), v.into())) - .collect(); - - Value::Table(table) - } -} - -macro_rules! impl_into_value { - ($variant:ident : $T:ty) => { - impl From<$T> for Value { - #[inline] - fn from(val: $T) -> Value { - Value::$variant(val.into()) - } - } - } -} - -impl_into_value!(String: String); -impl_into_value!(Integer: i64); -impl_into_value!(Integer: i32); -impl_into_value!(Integer: i8); -impl_into_value!(Integer: u8); -impl_into_value!(Integer: u32); -impl_into_value!(Float: f64); -impl_into_value!(Float: f32); -impl_into_value!(Boolean: bool); -impl_into_value!(Datetime: Datetime); - -/// Types that can be used to index a `toml::Value` -/// -/// Currently this is implemented for `usize` to index arrays and `str` to index -/// tables. -/// -/// This trait is sealed and not intended for implementation outside of the -/// `toml` crate. -pub trait Index: Sealed { - #[doc(hidden)] - fn index<'a>(&self, val: &'a Value) -> Option<&'a Value>; - #[doc(hidden)] - fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value>; -} - -/// An implementation detail that should not be implemented, this will change in -/// the future and break code otherwise. -#[doc(hidden)] -pub trait Sealed {} -impl Sealed for usize {} -impl Sealed for str {} -impl Sealed for String {} -impl<'a, T: Sealed + ?Sized> Sealed for &'a T {} - -impl Index for usize { - fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { - match *val { - Value::Array(ref a) => a.get(*self), - _ => None, - } - } - - fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { - match *val { - Value::Array(ref mut a) => a.get_mut(*self), - _ => None, - } - } -} - -impl Index for str { - fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { - match *val { - Value::Table(ref a) => a.get(self), - _ => None, - } - } - - fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { - match *val { - Value::Table(ref mut a) => a.get_mut(self), - _ => None, - } - } -} - -impl Index for String { - fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { - self[..].index(val) - } - - fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { - self[..].index_mut(val) - } -} - -impl<'s, T: ?Sized> Index for &'s T where T: Index { - fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { - (**self).index(val) - } - - fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { - (**self).index_mut(val) - } -} - -impl fmt::Display for Value { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - ::ser::to_string(self).expect("Unable to represent value as string").fmt(f) - } -} - -impl FromStr for Value { - type Err = ::de::Error; - fn from_str(s: &str) -> Result<Value, Self::Err> { - ::from_str(s) - } -} - -impl ser::Serialize for Value { - fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> - where S: ser::Serializer - { - use serde::ser::SerializeMap; - - match *self { - Value::String(ref s) => serializer.serialize_str(s), - Value::Integer(i) => serializer.serialize_i64(i), - Value::Float(f) => serializer.serialize_f64(f), - Value::Boolean(b) => serializer.serialize_bool(b), - Value::Datetime(ref s) => s.serialize(serializer), - Value::Array(ref a) => a.serialize(serializer), - Value::Table(ref t) => { - let mut map = serializer.serialize_map(Some(t.len()))?; - // Be sure to visit non-tables first (and also non - // array-of-tables) as all keys must be emitted first. - for (k, v) in t { - if !v.is_table() && !v.is_array() || - (v.as_array().map(|a| !a.iter().any(|v| v.is_table())).unwrap_or(false)) { - map.serialize_entry(k, v)?; - } - } - for (k, v) in t { - if v.as_array().map(|a| a.iter().any(|v| v.is_table())).unwrap_or(false) { - map.serialize_entry(k, v)?; - } - } - for (k, v) in t { - if v.is_table() { - map.serialize_entry(k, v)?; - } - } - map.end() - } - } - } -} - -impl<'de> de::Deserialize<'de> for Value { - fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> - where D: de::Deserializer<'de>, - { - struct ValueVisitor; - - impl<'de> de::Visitor<'de> for ValueVisitor { - type Value = Value; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("any valid TOML value") - } - - fn visit_bool<E>(self, value: bool) -> Result<Value, E> { - Ok(Value::Boolean(value)) - } - - fn visit_i64<E>(self, value: i64) -> Result<Value, E> { - Ok(Value::Integer(value)) - } - - fn visit_f64<E>(self, value: f64) -> Result<Value, E> { - Ok(Value::Float(value)) - } - - fn visit_str<E>(self, value: &str) -> Result<Value, E> { - Ok(Value::String(value.into())) - } - - fn visit_string<E>(self, value: String) -> Result<Value, E> { - Ok(Value::String(value)) - } - - fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error> - where D: de::Deserializer<'de>, - { - de::Deserialize::deserialize(deserializer) - } - - fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error> - where V: de::SeqAccess<'de>, - { - let mut vec = Vec::new(); - while let Some(elem) = try!(visitor.next_element()) { - vec.push(elem); - } - Ok(Value::Array(vec)) - } - - fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error> - where V: de::MapAccess<'de>, - { - let mut key = String::new(); - let datetime = visitor.next_key_seed(DatetimeOrTable { - key: &mut key, - })?; - match datetime { - Some(true) => { - let date: DatetimeFromString = visitor.next_value()?; - return Ok(Value::Datetime(date.value)) - } - None => return Ok(Value::Table(BTreeMap::new())), - Some(false) => {} - } - let mut map = BTreeMap::new(); - map.insert(key, visitor.next_value()?); - while let Some(key) = visitor.next_key()? { - if map.contains_key(&key) { - let msg = format!("duplicate key: `{}`", key); - return Err(de::Error::custom(msg)) - } - map.insert(key, visitor.next_value()?); - } - Ok(Value::Table(map)) - } - } - - deserializer.deserialize_any(ValueVisitor) - } -} - -impl<'de> de::Deserializer<'de> for Value { - type Error = ::de::Error; - - fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, ::de::Error> - where V: de::Visitor<'de>, - { - match self { - Value::Boolean(v) => visitor.visit_bool(v), - Value::Integer(n) => visitor.visit_i64(n), - Value::Float(n) => visitor.visit_f64(n), - Value::String(v) => visitor.visit_string(v), - Value::Datetime(v) => visitor.visit_string(v.to_string()), - Value::Array(v) => { - let len = v.len(); - let mut deserializer = SeqDeserializer::new(v); - let seq = visitor.visit_seq(&mut deserializer)?; - let remaining = deserializer.iter.len(); - if remaining == 0 { - Ok(seq) - } else { - Err(de::Error::invalid_length(len, &"fewer elements in array")) - } - } - Value::Table(v) => { - let len = v.len(); - let mut deserializer = MapDeserializer::new(v); - let map = visitor.visit_map(&mut deserializer)?; - let remaining = deserializer.iter.len(); - if remaining == 0 { - Ok(map) - } else { - Err(de::Error::invalid_length(len, &"fewer elements in map")) - } - } - } - } - - #[inline] - fn deserialize_enum<V>( - self, - _name: &str, - _variants: &'static [&'static str], - visitor: V, - ) -> Result<V::Value, ::de::Error> - where - V: de::Visitor<'de>, - { - match self { - Value::String(variant) => visitor.visit_enum(variant.into_deserializer()), - _ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"string only")), - } - } - - // `None` is interpreted as a missing field so be sure to implement `Some` - // as a present field. - fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, ::de::Error> - where V: de::Visitor<'de>, - { - visitor.visit_some(self) - } - - fn deserialize_newtype_struct<V>( - self, - _name: &'static str, - visitor: V - ) -> Result<V::Value, ::de::Error> - where V: de::Visitor<'de> - { - visitor.visit_newtype_struct(self) - } - - forward_to_deserialize_any! { - bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq - bytes byte_buf map unit_struct tuple_struct struct - tuple ignored_any identifier - } -} - -struct SeqDeserializer { - iter: vec::IntoIter<Value>, -} - -impl SeqDeserializer { - fn new(vec: Vec<Value>) -> Self { - SeqDeserializer { - iter: vec.into_iter(), - } - } -} - -impl<'de> de::SeqAccess<'de> for SeqDeserializer { - type Error = ::de::Error; - - fn next_element_seed<T>(&mut self, seed: T) - -> Result<Option<T::Value>, ::de::Error> - where T: de::DeserializeSeed<'de>, - { - match self.iter.next() { - Some(value) => seed.deserialize(value).map(Some), - None => Ok(None), - } - } - - fn size_hint(&self) -> Option<usize> { - match self.iter.size_hint() { - (lower, Some(upper)) if lower == upper => Some(upper), - _ => None, - } - } -} - -struct MapDeserializer { - iter: <BTreeMap<String, Value> as IntoIterator>::IntoIter, - value: Option<(String, Value)>, -} - -impl MapDeserializer { - fn new(map: BTreeMap<String, Value>) -> Self { - MapDeserializer { - iter: map.into_iter(), - value: None, - } - } -} - -impl<'de> de::MapAccess<'de> for MapDeserializer { - type Error = ::de::Error; - - fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, ::de::Error> - where T: de::DeserializeSeed<'de>, - { - match self.iter.next() { - Some((key, value)) => { - self.value = Some((key.clone(), value)); - seed.deserialize(Value::String(key)).map(Some) - } - None => Ok(None), - } - } - - fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, ::de::Error> - where T: de::DeserializeSeed<'de>, - { - let (key, res) = match self.value.take() { - Some((key, value)) => (key, seed.deserialize(value)), - None => return Err(de::Error::custom("value is missing")), - }; - res.map_err(|mut error| { - error.add_key_context(&key); - error - }) - } - - fn size_hint(&self) -> Option<usize> { - match self.iter.size_hint() { - (lower, Some(upper)) if lower == upper => Some(upper), - _ => None, - } - } -} - -impl<'de> de::IntoDeserializer<'de, ::de::Error> for Value { - type Deserializer = Self; - - fn into_deserializer(self) -> Self { - self - } -} - -struct Serializer; - -impl ser::Serializer for Serializer { - type Ok = Value; - type Error = ::ser::Error; - - type SerializeSeq = SerializeVec; - type SerializeTuple = ser::Impossible<Value, ::ser::Error>; - type SerializeTupleStruct = ser::Impossible<Value, ::ser::Error>; - type SerializeTupleVariant = ser::Impossible<Value, ::ser::Error>; - type SerializeMap = SerializeMap; - type SerializeStruct = SerializeMap; - type SerializeStructVariant = ser::Impossible<Value, ::ser::Error>; - - fn serialize_bool(self, value: bool) -> Result<Value, ::ser::Error> { - Ok(Value::Boolean(value)) - } - - fn serialize_i8(self, value: i8) -> Result<Value, ::ser::Error> { - self.serialize_i64(value.into()) - } - - fn serialize_i16(self, value: i16) -> Result<Value, ::ser::Error> { - self.serialize_i64(value.into()) - } - - fn serialize_i32(self, value: i32) -> Result<Value, ::ser::Error> { - self.serialize_i64(value.into()) - } - - fn serialize_i64(self, value: i64) -> Result<Value, ::ser::Error> { - Ok(Value::Integer(value.into())) - } - - fn serialize_u8(self, value: u8) -> Result<Value, ::ser::Error> { - self.serialize_i64(value.into()) - } - - fn serialize_u16(self, value: u16) -> Result<Value, ::ser::Error> { - self.serialize_i64(value.into()) - } - - fn serialize_u32(self, value: u32) -> Result<Value, ::ser::Error> { - self.serialize_i64(value.into()) - } - - fn serialize_u64(self, value: u64) -> Result<Value, ::ser::Error> { - if value <= i64::max_value() as u64 { - self.serialize_i64(value as i64) - } else { - Err(ser::Error::custom("u64 value was too large")) - } - } - - fn serialize_f32(self, value: f32) -> Result<Value, ::ser::Error> { - self.serialize_f64(value.into()) - } - - fn serialize_f64(self, value: f64) -> Result<Value, ::ser::Error> { - Ok(Value::Float(value)) - } - - fn serialize_char(self, value: char) -> Result<Value, ::ser::Error> { - let mut s = String::new(); - s.push(value); - self.serialize_str(&s) - } - - fn serialize_str(self, value: &str) -> Result<Value, ::ser::Error> { - Ok(Value::String(value.to_owned())) - } - - fn serialize_bytes(self, value: &[u8]) -> Result<Value, ::ser::Error> { - let vec = value.iter().map(|&b| Value::Integer(b.into())).collect(); - Ok(Value::Array(vec)) - } - - fn serialize_unit(self) -> Result<Value, ::ser::Error> { - Err(::ser::Error::UnsupportedType) - } - - fn serialize_unit_struct(self, _name: &'static str) - -> Result<Value, ::ser::Error> { - Err(::ser::Error::UnsupportedType) - } - - fn serialize_unit_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str) - -> Result<Value, ::ser::Error> { - self.serialize_str(_variant) - } - - fn serialize_newtype_struct<T: ?Sized>(self, - _name: &'static str, - value: &T) - -> Result<Value, ::ser::Error> - where T: ser::Serialize, - { - value.serialize(self) - } - - fn serialize_newtype_variant<T: ?Sized>(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _value: &T) - -> Result<Value, ::ser::Error> - where T: ser::Serialize, - { - Err(::ser::Error::UnsupportedType) - } - - fn serialize_none(self) -> Result<Value, ::ser::Error> { - Err(::ser::Error::UnsupportedNone) - } - - fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, ::ser::Error> - where T: ser::Serialize, - { - value.serialize(self) - } - - fn serialize_seq(self, len: Option<usize>) - -> Result<Self::SerializeSeq, ::ser::Error> - { - Ok(SerializeVec { - vec: Vec::with_capacity(len.unwrap_or(0)) - }) - } - - fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, ::ser::Error> { - Err(::ser::Error::UnsupportedType) - } - - fn serialize_tuple_struct(self, _name: &'static str, _len: usize) - -> Result<Self::SerializeTupleStruct, ::ser::Error> { - Err(::ser::Error::UnsupportedType) - } - - fn serialize_tuple_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result<Self::SerializeTupleVariant, ::ser::Error> - { - Err(::ser::Error::UnsupportedType) - } - - fn serialize_map(self, _len: Option<usize>) - -> Result<Self::SerializeMap, ::ser::Error> - { - Ok(SerializeMap { - map: BTreeMap::new(), - next_key: None, - }) - } - - fn serialize_struct(self, _name: &'static str, len: usize) - -> Result<Self::SerializeStruct, ::ser::Error> { - self.serialize_map(Some(len)) - } - - fn serialize_struct_variant(self, - _name: &'static str, - _variant_index: u32, - _variant: &'static str, - _len: usize) - -> Result<Self::SerializeStructVariant, ::ser::Error> - { - Err(::ser::Error::UnsupportedType) - } -} - -struct SerializeVec { - vec: Vec<Value>, -} - -struct SerializeMap { - map: BTreeMap<String, Value>, - next_key: Option<String>, -} - -impl ser::SerializeSeq for SerializeVec { - type Ok = Value; - type Error = ::ser::Error; - - fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error> - where T: ser::Serialize - { - self.vec.push(Value::try_from(value)?); - Ok(()) - } - - fn end(self) -> Result<Value, ::ser::Error> { - Ok(Value::Array(self.vec)) - } -} - -impl ser::SerializeMap for SerializeMap { - type Ok = Value; - type Error = ::ser::Error; - - fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), ::ser::Error> - where T: ser::Serialize - { - match Value::try_from(key)? { - Value::String(s) => self.next_key = Some(s), - _ => return Err(::ser::Error::KeyNotString), - }; - Ok(()) - } - - fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error> - where T: ser::Serialize - { - let key = self.next_key.take(); - let key = key.expect("serialize_value called before serialize_key"); - match Value::try_from(value) { - Ok(value) => { self.map.insert(key, value); } - Err(::ser::Error::UnsupportedNone) => {} - Err(e) => return Err(e), - } - Ok(()) - } - - fn end(self) -> Result<Value, ::ser::Error> { - Ok(Value::Table(self.map)) - } -} - -impl ser::SerializeStruct for SerializeMap { - type Ok = Value; - type Error = ::ser::Error; - - fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), ::ser::Error> - where T: ser::Serialize - { - try!(ser::SerializeMap::serialize_key(self, key)); - ser::SerializeMap::serialize_value(self, value) - } - - fn end(self) -> Result<Value, ::ser::Error> { - ser::SerializeMap::end(self) - } -} - -struct DatetimeOrTable<'a> { - key: &'a mut String, -} - -impl<'a, 'de> de::DeserializeSeed<'de> for DatetimeOrTable<'a> { - type Value = bool; - - fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> - where D: de::Deserializer<'de> - { - deserializer.deserialize_any(self) - } -} - -impl<'a, 'de> de::Visitor<'de> for DatetimeOrTable<'a> { - type Value = bool; - - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str("a string key") - } - - fn visit_str<E>(self, s: &str) -> Result<bool, E> - where E: de::Error, - { - if s == SERDE_STRUCT_FIELD_NAME { - Ok(true) - } else { - self.key.push_str(s); - Ok(false) - } - } - - fn visit_string<E>(self, s: String) -> Result<bool, E> - where E: de::Error, - { - if s == SERDE_STRUCT_FIELD_NAME { - Ok(true) - } else { - *self.key = s; - Ok(false) - } - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/backcompat.rs cargo-0.26.0/vendor/toml-0.4.5/tests/backcompat.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/backcompat.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/backcompat.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -extern crate toml; -extern crate serde; - -use serde::de::Deserialize; - -#[test] -fn main() { - let s = " - [a] foo = 1 - [[b]] foo = 1 - "; - assert!(s.parse::<toml::Value>().is_err()); - - let mut d = toml::de::Deserializer::new(s); - d.set_require_newline_after_table(false); - let value = toml::Value::deserialize(&mut d).unwrap(); - assert_eq!(value["a"]["foo"].as_integer(), Some(1)); - assert_eq!(value["b"][0]["foo"].as_integer(), Some(1)); -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/datetime.rs cargo-0.26.0/vendor/toml-0.4.5/tests/datetime.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/datetime.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/datetime.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,58 +0,0 @@ -extern crate toml; - -use std::str::FromStr; - -use toml::Value; - -#[test] -fn times() { - fn good(s: &str) { - let to_parse = format!("foo = {}", s); - let value = Value::from_str(&to_parse).unwrap(); - assert_eq!(value["foo"].as_datetime().unwrap().to_string(), s); - } - - good("1997-09-09T09:09:09Z"); - good("1997-09-09T09:09:09+09:09"); - good("1997-09-09T09:09:09-09:09"); - good("1997-09-09T09:09:09"); - good("1997-09-09"); - good("09:09:09"); - good("1997-09-09T09:09:09.09Z"); - good("1997-09-09T09:09:09.09+09:09"); - good("1997-09-09T09:09:09.09-09:09"); - good("1997-09-09T09:09:09.09"); - good("09:09:09.09"); -} - -#[test] -fn bad_times() { - fn bad(s: &str) { - let to_parse = format!("foo = {}", s); - assert!(Value::from_str(&to_parse).is_err()); - } - - bad("199-09-09"); - bad("199709-09"); - bad("1997-9-09"); - bad("1997-09-9"); - bad("1997-09-0909:09:09"); - bad("1997-09-09T09:09:09."); - bad("T"); - bad("T."); - bad("TZ"); - bad("1997-09-09T09:09:09.09+"); - bad("1997-09-09T09:09:09.09+09"); - bad("1997-09-09T09:09:09.09+09:9"); - bad("1997-09-09T09:09:09.09+0909"); - bad("1997-09-09T09:09:09.09-"); - bad("1997-09-09T09:09:09.09-09"); - bad("1997-09-09T09:09:09.09-09:9"); - bad("1997-09-09T09:09:09.09-0909"); - - bad("1997-00-09T09:09:09.09Z"); - bad("1997-09-00T09:09:09.09Z"); - bad("1997-09-09T30:09:09.09Z"); - bad("1997-09-09T12:69:09.09Z"); - bad("1997-09-09T12:09:69.09Z"); -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/display.rs cargo-0.26.0/vendor/toml-0.4.5/tests/display.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/display.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/display.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,103 +0,0 @@ -extern crate toml; - -use std::collections::BTreeMap; - -use toml::Value::{String, Integer, Float, Boolean, Array, Table}; - -macro_rules! map( ($($k:expr => $v:expr),*) => ({ - let mut _m = BTreeMap::new(); - $(_m.insert($k.to_string(), $v);)* - _m -}) ); - -#[test] -fn simple_show() { - assert_eq!(String("foo".to_string()).to_string(), - "\"foo\""); - assert_eq!(Integer(10).to_string(), - "10"); - assert_eq!(Float(10.0).to_string(), - "10.0"); - assert_eq!(Float(2.4).to_string(), - "2.4"); - assert_eq!(Boolean(true).to_string(), - "true"); - assert_eq!(Array(vec![]).to_string(), - "[]"); - assert_eq!(Array(vec![Integer(1), Integer(2)]).to_string(), - "[1, 2]"); -} - -#[test] -fn table() { - assert_eq!(Table(map! { }).to_string(), - ""); - assert_eq!(Table(map! { - "test" => Integer(2), - "test2" => Integer(3) }).to_string(), - "test = 2\ntest2 = 3\n"); - assert_eq!(Table(map! { - "test" => Integer(2), - "test2" => Table(map! { - "test" => String("wut".to_string()) - }) - }).to_string(), - "test = 2\n\ - \n\ - [test2]\n\ - test = \"wut\"\n"); - assert_eq!(Table(map! { - "test" => Integer(2), - "test2" => Table(map! { - "test" => String("wut".to_string()) - }) - }).to_string(), - "test = 2\n\ - \n\ - [test2]\n\ - test = \"wut\"\n"); - assert_eq!(Table(map! { - "test" => Integer(2), - "test2" => Array(vec![Table(map! { - "test" => String("wut".to_string()) - })]) - }).to_string(), - "test = 2\n\ - \n\ - [[test2]]\n\ - test = \"wut\"\n"); - assert_eq!(Table(map! { - "foo.bar" => Integer(2), - "foo\"bar" => Integer(2) - }).to_string(), - "\"foo\\\"bar\" = 2\n\ - \"foo.bar\" = 2\n"); - assert_eq!(Table(map! { - "test" => Integer(2), - "test2" => Array(vec![Table(map! { - "test" => Array(vec![Integer(2)]) - })]) - }).to_string(), - "test = 2\n\ - \n\ - [[test2]]\n\ - test = [2]\n"); - let table = Table(map! { - "test" => Integer(2), - "test2" => Array(vec![Table(map! { - "test" => Array(vec![Array(vec![Integer(2), Integer(3)]), - Array(vec![String("foo".to_string()), String("bar".to_string())])]) - })]) - }); - assert_eq!(table.to_string(), - "test = 2\n\ - \n\ - [[test2]]\n\ - test = [[2, 3], [\"foo\", \"bar\"]]\n"); - assert_eq!(Table(map! { - "test" => Array(vec![Integer(2)]), - "test2" => Integer(2) - }).to_string(), - "test = [2]\n\ - test2 = 2\n"); -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/display-tricky.rs cargo-0.26.0/vendor/toml-0.4.5/tests/display-tricky.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/display-tricky.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/display-tricky.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,49 +0,0 @@ -extern crate toml; -#[macro_use] extern crate serde_derive; - -#[derive(Debug, Serialize, Deserialize)] -pub struct Recipe { - pub name: String, - pub description: Option<String>, - #[serde(default)] - pub modules: Vec<Modules>, - #[serde(default)] - pub packages: Vec<Packages> -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct Modules { - pub name: String, - pub version: Option<String> -} - -#[derive(Debug, Serialize, Deserialize)] -pub struct Packages { - pub name: String, - pub version: Option<String> -} - -#[test] -fn both_ends() { - let recipe_works = toml::from_str::<Recipe>(r#" - name = "testing" - description = "example" - modules = [] - - [[packages]] - name = "base" - "#).unwrap(); - toml::to_string(&recipe_works).unwrap(); - - let recipe_fails = toml::from_str::<Recipe>(r#" - name = "testing" - description = "example" - packages = [] - - [[modules]] - name = "base" - "#).unwrap(); - - let recipe_toml = toml::Value::try_from(recipe_fails).unwrap(); - recipe_toml.to_string(); -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/formatting.rs cargo-0.26.0/vendor/toml-0.4.5/tests/formatting.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/formatting.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/formatting.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,55 +0,0 @@ -extern crate serde; -#[macro_use] -extern crate serde_derive; -extern crate toml; - -use toml::to_string; - -#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)] -struct User { - pub name: String, - pub surname: String, -} - -#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)] -struct Users { - pub user: Vec<User>, -} - -#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)] -struct TwoUsers { - pub user0: User, - pub user1: User, -} - -#[test] -fn no_unnecessary_newlines_array() { - assert!(!to_string(&Users { - user: vec![ - User { - name: "John".to_string(), - surname: "Doe".to_string(), - }, - User { - name: "Jane".to_string(), - surname: "Dough".to_string(), - }, - ], - }).unwrap() - .starts_with("\n")); -} - -#[test] -fn no_unnecessary_newlines_table() { - assert!(!to_string(&TwoUsers { - user0: User { - name: "John".to_string(), - surname: "Doe".to_string(), - }, - user1: User { - name: "Jane".to_string(), - surname: "Dough".to_string(), - }, - }).unwrap() - .starts_with("\n")); -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/array-mixed-types-arrays-and-ints.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/array-mixed-types-arrays-and-ints.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/array-mixed-types-arrays-and-ints.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/array-mixed-types-arrays-and-ints.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -arrays-and-ints = [1, ["Arrays are not integers."]] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/array-mixed-types-ints-and-floats.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/array-mixed-types-ints-and-floats.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/array-mixed-types-ints-and-floats.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/array-mixed-types-ints-and-floats.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -ints-and-floats = [1, 1.1] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/array-mixed-types-strings-and-ints.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/array-mixed-types-strings-and-ints.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/array-mixed-types-strings-and-ints.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/array-mixed-types-strings-and-ints.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -strings-and-ints = ["hi", 42] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-no-leads.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-no-leads.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-no-leads.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-no-leads.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -no-leads = 1987-7-05T17:45:00Z diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-no-secs.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-no-secs.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-no-secs.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-no-secs.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -no-secs = 1987-07-05T17:45Z diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-no-t.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-no-t.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-no-t.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-no-t.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -no-t = 1987-07-0517:45:00Z diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-with-milli.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-with-milli.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-with-milli.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/datetime-malformed-with-milli.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -with-milli = 1987-07-5T17:45:00.12Z diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/duplicate-keys.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/duplicate-keys.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/duplicate-keys.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/duplicate-keys.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -dupe = false -dupe = true diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/duplicate-key-table.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/duplicate-key-table.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/duplicate-key-table.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/duplicate-key-table.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -[fruit] -type = "apple" - -[fruit.type] -apple = "yes" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/duplicate-tables.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/duplicate-tables.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/duplicate-tables.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/duplicate-tables.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -[a] -[a] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/empty-implicit-table.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/empty-implicit-table.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/empty-implicit-table.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/empty-implicit-table.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -[naughty..naughty] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/empty-table.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/empty-table.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/empty-table.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/empty-table.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -[] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/float-no-leading-zero.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/float-no-leading-zero.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/float-no-leading-zero.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/float-no-leading-zero.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -answer = .12345 -neganswer = -.12345 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/float-no-trailing-digits.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/float-no-trailing-digits.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/float-no-trailing-digits.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/float-no-trailing-digits.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -answer = 1. -neganswer = -1. diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-after-array.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-after-array.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-after-array.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-after-array.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -[[agencies]] owner = "S Cjelli" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-after-table.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-after-table.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-after-table.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-after-table.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -[history] guard = "sleeping" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-empty.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-empty.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-empty.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-empty.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ - = 1 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-hash.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-hash.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-hash.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-hash.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -a# = 1 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-newline.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-newline.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-newline.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-newline.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -a -= 1 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-open-bracket.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-open-bracket.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-open-bracket.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-open-bracket.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -[abc = 1 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-single-open-bracket.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-single-open-bracket.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-single-open-bracket.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-single-open-bracket.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -[ \ No newline at end of file diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-space.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-space.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-space.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-space.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -a b = 1 \ No newline at end of file diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-start-bracket.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-start-bracket.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-start-bracket.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-start-bracket.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -[a] -[xyz = 5 -[b] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-two-equals.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-two-equals.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/key-two-equals.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/key-two-equals.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -key= = 1 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/string-bad-byte-escape.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/string-bad-byte-escape.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/string-bad-byte-escape.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/string-bad-byte-escape.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -naughty = "\xAg" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/string-bad-escape.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/string-bad-escape.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/string-bad-escape.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/string-bad-escape.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -invalid-escape = "This string has a bad \a escape character." diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/string-byte-escapes.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/string-byte-escapes.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/string-byte-escapes.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/string-byte-escapes.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -answer = "\x33" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/string-no-close.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/string-no-close.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/string-no-close.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/string-no-close.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -no-ending-quote = "One time, at band camp diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-array-implicit.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-array-implicit.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-array-implicit.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-array-implicit.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -# This test is a bit tricky. It should fail because the first use of -# `[[albums.songs]]` without first declaring `albums` implies that `albums` -# must be a table. The alternative would be quite weird. Namely, it wouldn't -# comply with the TOML spec: "Each double-bracketed sub-table will belong to -# the most *recently* defined table element *above* it." -# -# This is in contrast to the *valid* test, table-array-implicit where -# `[[albums.songs]]` works by itself, so long as `[[albums]]` isn't declared -# later. (Although, `[albums]` could be.) -[[albums.songs]] -name = "Glory Days" - -[[albums]] -name = "Born in the USA" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-array-malformed-bracket.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-array-malformed-bracket.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-array-malformed-bracket.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-array-malformed-bracket.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -[[albums] -name = "Born to Run" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-array-malformed-empty.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-array-malformed-empty.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-array-malformed-empty.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-array-malformed-empty.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -[[]] -name = "Born to Run" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-empty.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-empty.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-empty.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-empty.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -[] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-nested-brackets-close.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-nested-brackets-close.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-nested-brackets-close.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-nested-brackets-close.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -[a]b] -zyx = 42 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-nested-brackets-open.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-nested-brackets-open.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-nested-brackets-open.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-nested-brackets-open.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -[a[b] -zyx = 42 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-whitespace.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-whitespace.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-whitespace.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-whitespace.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -[invalid key] \ No newline at end of file diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-with-pound.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-with-pound.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/table-with-pound.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/table-with-pound.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -[key#group] -answer = 42 \ No newline at end of file diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/text-after-array-entries.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/text-after-array-entries.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/text-after-array-entries.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/text-after-array-entries.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -array = [ - "Is there life after an array separator?", No - "Entry" -] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/text-after-integer.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/text-after-integer.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/text-after-integer.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/text-after-integer.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -answer = 42 the ultimate answer? diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/text-after-string.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/text-after-string.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/text-after-string.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/text-after-string.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -string = "Is there life after strings?" No. diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/text-after-table.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/text-after-table.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/text-after-table.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/text-after-table.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -[error] this shouldn't be here diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/text-before-array-separator.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/text-before-array-separator.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/text-before-array-separator.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/text-before-array-separator.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -array = [ - "Is there life before an array separator?" No, - "Entry" -] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/text-in-array.toml cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/text-in-array.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid/text-in-array.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid/text-in-array.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -array = [ - "Entry 1", - I don't belong, - "Entry 2", -] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid-encoder/array-mixed-types-ints-and-floats.json cargo-0.26.0/vendor/toml-0.4.5/tests/invalid-encoder/array-mixed-types-ints-and-floats.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid-encoder/array-mixed-types-ints-and-floats.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid-encoder/array-mixed-types-ints-and-floats.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,15 +0,0 @@ -{ - "ints-and-floats": { - "type": "array", - "value": [ - { - "type": "integer", - "value": "1" - }, - { - "type": "float", - "value": "1.1" - } - ] - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid-encoder-misc.rs cargo-0.26.0/vendor/toml-0.4.5/tests/invalid-encoder-misc.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid-encoder-misc.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid-encoder-misc.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -extern crate toml; - -use std::f64; - -#[test] -fn test_invalid_float_encode() { - fn bad(value: toml::Value) { - assert!(toml::to_string(&value).is_err()); - } - - bad(toml::Value::Float(f64::INFINITY)); - bad(toml::Value::Float(f64::NEG_INFINITY)); - bad(toml::Value::Float(f64::NAN)); -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid-misc.rs cargo-0.26.0/vendor/toml-0.4.5/tests/invalid-misc.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid-misc.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid-misc.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -extern crate toml; - -#[test] -fn bad() { - fn bad(s: &str) { - assert!(s.parse::<toml::Value>().is_err()); - } - - bad("a = 01"); - bad("a = 1__1"); - bad("a = 1_"); - bad("''"); - bad("a = nan"); - bad("a = -inf"); - bad("a = inf"); - bad("a = 9e99999"); -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/invalid.rs cargo-0.26.0/vendor/toml-0.4.5/tests/invalid.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/invalid.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/invalid.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,98 +0,0 @@ -extern crate toml; - -fn run(toml: &str) { - println!("test if invalid:\n{}", toml); - if let Ok(e) = toml.parse::<toml::Value>() { - panic!("parsed to: {:#?}", e); - } -} - -macro_rules! test( ($name:ident, $toml:expr) => ( - #[test] - fn $name() { run($toml); } -) ); - -test!(array_mixed_types_arrays_and_ints, - include_str!("invalid/array-mixed-types-arrays-and-ints.toml")); -test!(array_mixed_types_ints_and_floats, - include_str!("invalid/array-mixed-types-ints-and-floats.toml")); -test!(array_mixed_types_strings_and_ints, - include_str!("invalid/array-mixed-types-strings-and-ints.toml")); -test!(datetime_malformed_no_leads, - include_str!("invalid/datetime-malformed-no-leads.toml")); -test!(datetime_malformed_no_secs, - include_str!("invalid/datetime-malformed-no-secs.toml")); -test!(datetime_malformed_no_t, - include_str!("invalid/datetime-malformed-no-t.toml")); -test!(datetime_malformed_with_milli, - include_str!("invalid/datetime-malformed-with-milli.toml")); -test!(duplicate_keys, - include_str!("invalid/duplicate-keys.toml")); -test!(duplicate_key_table, - include_str!("invalid/duplicate-key-table.toml")); -test!(duplicate_tables, - include_str!("invalid/duplicate-tables.toml")); -test!(empty_implicit_table, - include_str!("invalid/empty-implicit-table.toml")); -test!(empty_table, - include_str!("invalid/empty-table.toml")); -test!(float_no_leading_zero, - include_str!("invalid/float-no-leading-zero.toml")); -test!(float_no_trailing_digits, - include_str!("invalid/float-no-trailing-digits.toml")); -test!(key_after_array, - include_str!("invalid/key-after-array.toml")); -test!(key_after_table, - include_str!("invalid/key-after-table.toml")); -test!(key_empty, - include_str!("invalid/key-empty.toml")); -test!(key_hash, - include_str!("invalid/key-hash.toml")); -test!(key_newline, - include_str!("invalid/key-newline.toml")); -test!(key_open_bracket, - include_str!("invalid/key-open-bracket.toml")); -test!(key_single_open_bracket, - include_str!("invalid/key-single-open-bracket.toml")); -test!(key_space, - include_str!("invalid/key-space.toml")); -test!(key_start_bracket, - include_str!("invalid/key-start-bracket.toml")); -test!(key_two_equals, - include_str!("invalid/key-two-equals.toml")); -test!(string_bad_byte_escape, - include_str!("invalid/string-bad-byte-escape.toml")); -test!(string_bad_escape, - include_str!("invalid/string-bad-escape.toml")); -test!(string_byte_escapes, - include_str!("invalid/string-byte-escapes.toml")); -test!(string_no_close, - include_str!("invalid/string-no-close.toml")); -test!(table_array_implicit, - include_str!("invalid/table-array-implicit.toml")); -test!(table_array_malformed_bracket, - include_str!("invalid/table-array-malformed-bracket.toml")); -test!(table_array_malformed_empty, - include_str!("invalid/table-array-malformed-empty.toml")); -test!(table_empty, - include_str!("invalid/table-empty.toml")); -test!(table_nested_brackets_close, - include_str!("invalid/table-nested-brackets-close.toml")); -test!(table_nested_brackets_open, - include_str!("invalid/table-nested-brackets-open.toml")); -test!(table_whitespace, - include_str!("invalid/table-whitespace.toml")); -test!(table_with_pound, - include_str!("invalid/table-with-pound.toml")); -test!(text_after_array_entries, - include_str!("invalid/text-after-array-entries.toml")); -test!(text_after_integer, - include_str!("invalid/text-after-integer.toml")); -test!(text_after_string, - include_str!("invalid/text-after-string.toml")); -test!(text_after_table, - include_str!("invalid/text-after-table.toml")); -test!(text_before_array_separator, - include_str!("invalid/text-before-array-separator.toml")); -test!(text_in_array, - include_str!("invalid/text-in-array.toml")); diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/parser.rs cargo-0.26.0/vendor/toml-0.4.5/tests/parser.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/parser.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/parser.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,495 +0,0 @@ -extern crate toml; - -use toml::Value; - -macro_rules! bad { - ($s:expr, $msg:expr) => ({ - match $s.parse::<Value>() { - Ok(s) => panic!("successfully parsed as {}", s), - Err(e) => { - let e = e.to_string(); - assert!(e.contains($msg), "error: {}", e); - } - } - }) -} - -#[test] -fn crlf() { - "\ -[project]\r\n\ -\r\n\ -name = \"splay\"\r\n\ -version = \"0.1.0\"\r\n\ -authors = [\"alex@crichton.co\"]\r\n\ -\r\n\ -[[lib]]\r\n\ -\r\n\ -path = \"lib.rs\"\r\n\ -name = \"splay\"\r\n\ -description = \"\"\"\ -A Rust implementation of a TAR file reader and writer. This library does not\r\n\ -currently handle compression, but it is abstract over all I/O readers and\r\n\ -writers. Additionally, great lengths are taken to ensure that the entire\r\n\ -contents are never required to be entirely resident in memory all at once.\r\n\ -\"\"\"\ -".parse::<Value>().unwrap(); -} - -#[test] -fn fun_with_strings() { - let table = r#" -bar = "\U00000000" -key1 = "One\nTwo" -key2 = """One\nTwo""" -key3 = """ -One -Two""" - -key4 = "The quick brown fox jumps over the lazy dog." -key5 = """ -The quick brown \ - - -fox jumps over \ -the lazy dog.""" -key6 = """\ - The quick brown \ - fox jumps over \ - the lazy dog.\ - """ -# What you see is what you get. -winpath = 'C:\Users\nodejs\templates' -winpath2 = '\\ServerX\admin$\system32\' -quoted = 'Tom "Dubs" Preston-Werner' -regex = '<\i\c*\s*>' - -regex2 = '''I [dw]on't need \d{2} apples''' -lines = ''' -The first newline is -trimmed in raw strings. -All other whitespace -is preserved. -''' -"#.parse::<Value>().unwrap(); - assert_eq!(table["bar"].as_str(), Some("\0")); - assert_eq!(table["key1"].as_str(), Some("One\nTwo")); - assert_eq!(table["key2"].as_str(), Some("One\nTwo")); - assert_eq!(table["key3"].as_str(), Some("One\nTwo")); - - let msg = "The quick brown fox jumps over the lazy dog."; - assert_eq!(table["key4"].as_str(), Some(msg)); - assert_eq!(table["key5"].as_str(), Some(msg)); - assert_eq!(table["key6"].as_str(), Some(msg)); - - assert_eq!(table["winpath"].as_str(), Some(r"C:\Users\nodejs\templates")); - assert_eq!(table["winpath2"].as_str(), Some(r"\\ServerX\admin$\system32\")); - assert_eq!(table["quoted"].as_str(), Some(r#"Tom "Dubs" Preston-Werner"#)); - assert_eq!(table["regex"].as_str(), Some(r"<\i\c*\s*>")); - assert_eq!(table["regex2"].as_str(), Some(r"I [dw]on't need \d{2} apples")); - assert_eq!(table["lines"].as_str(), - Some("The first newline is\n\ - trimmed in raw strings.\n\ - All other whitespace\n\ - is preserved.\n")); -} - -#[test] -fn tables_in_arrays() { - let table = r#" -[[foo]] -#… -[foo.bar] -#… - -[[foo]] # ... -#… -[foo.bar] -#... -"#.parse::<Value>().unwrap(); - table["foo"][0]["bar"].as_table().unwrap(); - table["foo"][1]["bar"].as_table().unwrap(); -} - -#[test] -fn empty_table() { - let table = r#" -[foo]"#.parse::<Value>().unwrap(); - table["foo"].as_table().unwrap(); -} - -#[test] -fn fruit() { - let table = r#" -[[fruit]] -name = "apple" - -[fruit.physical] -color = "red" -shape = "round" - -[[fruit.variety]] -name = "red delicious" - -[[fruit.variety]] -name = "granny smith" - -[[fruit]] -name = "banana" - -[[fruit.variety]] -name = "plantain" -"#.parse::<Value>().unwrap(); - assert_eq!(table["fruit"][0]["name"].as_str(), Some("apple")); - assert_eq!(table["fruit"][0]["physical"]["color"].as_str(), Some("red")); - assert_eq!(table["fruit"][0]["physical"]["shape"].as_str(), Some("round")); - assert_eq!(table["fruit"][0]["variety"][0]["name"].as_str(), Some("red delicious")); - assert_eq!(table["fruit"][0]["variety"][1]["name"].as_str(), Some("granny smith")); - assert_eq!(table["fruit"][1]["name"].as_str(), Some("banana")); - assert_eq!(table["fruit"][1]["variety"][0]["name"].as_str(), Some("plantain")); -} - -#[test] -fn stray_cr() { - "\r".parse::<Value>().unwrap_err(); - "a = [ \r ]".parse::<Value>().unwrap_err(); - "a = \"\"\"\r\"\"\"".parse::<Value>().unwrap_err(); - "a = \"\"\"\\ \r \"\"\"".parse::<Value>().unwrap_err(); - "a = '''\r'''".parse::<Value>().unwrap_err(); - "a = '\r'".parse::<Value>().unwrap_err(); - "a = \"\r\"".parse::<Value>().unwrap_err(); -} - -#[test] -fn blank_literal_string() { - let table = "foo = ''".parse::<Value>().unwrap(); - assert_eq!(table["foo"].as_str(), Some("")); -} - -#[test] -fn many_blank() { - let table = "foo = \"\"\"\n\n\n\"\"\"".parse::<Value>().unwrap(); - assert_eq!(table["foo"].as_str(), Some("\n\n")); -} - -#[test] -fn literal_eats_crlf() { - let table = " - foo = \"\"\"\\\r\n\"\"\" - bar = \"\"\"\\\r\n \r\n \r\n a\"\"\" - ".parse::<Value>().unwrap(); - assert_eq!(table["foo"].as_str(), Some("")); - assert_eq!(table["bar"].as_str(), Some("a")); -} - -#[test] -fn string_no_newline() { - "a = \"\n\"".parse::<Value>().unwrap_err(); - "a = '\n'".parse::<Value>().unwrap_err(); -} - -#[test] -fn bad_leading_zeros() { - "a = 00".parse::<Value>().unwrap_err(); - "a = -00".parse::<Value>().unwrap_err(); - "a = +00".parse::<Value>().unwrap_err(); - "a = 00.0".parse::<Value>().unwrap_err(); - "a = -00.0".parse::<Value>().unwrap_err(); - "a = +00.0".parse::<Value>().unwrap_err(); - "a = 9223372036854775808".parse::<Value>().unwrap_err(); - "a = -9223372036854775809".parse::<Value>().unwrap_err(); -} - -#[test] -fn bad_floats() { - "a = 0.".parse::<Value>().unwrap_err(); - "a = 0.e".parse::<Value>().unwrap_err(); - "a = 0.E".parse::<Value>().unwrap_err(); - "a = 0.0E".parse::<Value>().unwrap_err(); - "a = 0.0e".parse::<Value>().unwrap_err(); - "a = 0.0e-".parse::<Value>().unwrap_err(); - "a = 0.0e+".parse::<Value>().unwrap_err(); - "a = 0.0e+00".parse::<Value>().unwrap_err(); -} - -#[test] -fn floats() { - macro_rules! t { - ($actual:expr, $expected:expr) => ({ - let f = format!("foo = {}", $actual); - println!("{}", f); - let a = f.parse::<Value>().unwrap(); - assert_eq!(a["foo"].as_float().unwrap(), $expected); - }) - } - - t!("1.0", 1.0); - t!("1.0e0", 1.0); - t!("1.0e+0", 1.0); - t!("1.0e-0", 1.0); - t!("1.001e-0", 1.001); - t!("2e10", 2e10); - t!("2e+10", 2e10); - t!("2e-10", 2e-10); - t!("2_0.0", 20.0); - t!("2_0.0_0e1_0", 20.0e10); - t!("2_0.1_0e1_0", 20.1e10); -} - -#[test] -fn bare_key_names() { - let a = " - foo = 3 - foo_3 = 3 - foo_-2--3--r23f--4-f2-4 = 3 - _ = 3 - - = 3 - 8 = 8 - \"a\" = 3 - \"!\" = 3 - \"a^b\" = 3 - \"\\\"\" = 3 - \"character encoding\" = \"value\" - 'ʎǝʞ' = \"value\" - ".parse::<Value>().unwrap(); - &a["foo"]; - &a["-"]; - &a["_"]; - &a["8"]; - &a["foo_3"]; - &a["foo_-2--3--r23f--4-f2-4"]; - &a["a"]; - &a["!"]; - &a["\""]; - &a["character encoding"]; - &a["ʎǝʞ"]; -} - -#[test] -fn bad_keys() { - "key\n=3".parse::<Value>().unwrap_err(); - "key=\n3".parse::<Value>().unwrap_err(); - "key|=3".parse::<Value>().unwrap_err(); - "\"\"=3".parse::<Value>().unwrap_err(); - "=3".parse::<Value>().unwrap_err(); - "\"\"|=3".parse::<Value>().unwrap_err(); - "\"\n\"|=3".parse::<Value>().unwrap_err(); - "\"\r\"|=3".parse::<Value>().unwrap_err(); -} - -#[test] -fn bad_table_names() { - "[]".parse::<Value>().unwrap_err(); - "[.]".parse::<Value>().unwrap_err(); - "[\"\".\"\"]".parse::<Value>().unwrap_err(); - "[a.]".parse::<Value>().unwrap_err(); - "[\"\"]".parse::<Value>().unwrap_err(); - "[!]".parse::<Value>().unwrap_err(); - "[\"\n\"]".parse::<Value>().unwrap_err(); - "[a.b]\n[a.\"b\"]".parse::<Value>().unwrap_err(); - "[']".parse::<Value>().unwrap_err(); - "[''']".parse::<Value>().unwrap_err(); - "['''''']".parse::<Value>().unwrap_err(); - "['\n']".parse::<Value>().unwrap_err(); - "['\r\n']".parse::<Value>().unwrap_err(); -} - -#[test] -fn table_names() { - let a = " - [a.\"b\"] - [\"f f\"] - [\"f.f\"] - [\"\\\"\"] - ['a.a'] - ['\"\"'] - ".parse::<Value>().unwrap(); - println!("{:?}", a); - &a["a"]["b"]; - &a["f f"]; - &a["f.f"]; - &a["\""]; - &a["\"\""]; -} - -#[test] -fn invalid_bare_numeral() { - "4".parse::<Value>().unwrap_err(); -} - -#[test] -fn inline_tables() { - "a = {}".parse::<Value>().unwrap(); - "a = {b=1}".parse::<Value>().unwrap(); - "a = { b = 1 }".parse::<Value>().unwrap(); - "a = {a=1,b=2}".parse::<Value>().unwrap(); - "a = {a=1,b=2,c={}}".parse::<Value>().unwrap(); - "a = {a=1,}".parse::<Value>().unwrap_err(); - "a = {,}".parse::<Value>().unwrap_err(); - "a = {a=1,a=1}".parse::<Value>().unwrap_err(); - "a = {\n}".parse::<Value>().unwrap_err(); - "a = {".parse::<Value>().unwrap_err(); - "a = {a=[\n]}".parse::<Value>().unwrap(); - "a = {\"a\"=[\n]}".parse::<Value>().unwrap(); - "a = [\n{},\n{},\n]".parse::<Value>().unwrap(); -} - -#[test] -fn number_underscores() { - macro_rules! t { - ($actual:expr, $expected:expr) => ({ - let f = format!("foo = {}", $actual); - let table = f.parse::<Value>().unwrap(); - assert_eq!(table["foo"].as_integer().unwrap(), $expected); - }) - } - - t!("1_0", 10); - t!("1_0_0", 100); - t!("1_000", 1000); - t!("+1_000", 1000); - t!("-1_000", -1000); -} - -#[test] -fn bad_underscores() { - bad!("foo = 0_", "invalid number"); - bad!("foo = 0__0", "invalid number"); - bad!("foo = __0", "invalid number"); - bad!("foo = 1_0_", "invalid number"); -} - -#[test] -fn bad_unicode_codepoint() { - bad!("foo = \"\\uD800\"", "invalid escape value"); -} - -#[test] -fn bad_strings() { - bad!("foo = \"\\uxx\"", "invalid hex escape"); - bad!("foo = \"\\u\"", "invalid hex escape"); - bad!("foo = \"\\", "unterminated"); - bad!("foo = '", "unterminated"); -} - -#[test] -fn empty_string() { - assert_eq!("foo = \"\"".parse::<Value>() - .unwrap()["foo"] - .as_str() - .unwrap(), - ""); -} - -#[test] -fn booleans() { - let table = "foo = true".parse::<Value>().unwrap(); - assert_eq!(table["foo"].as_bool(), Some(true)); - - let table = "foo = false".parse::<Value>().unwrap(); - assert_eq!(table["foo"].as_bool(), Some(false)); - - assert!("foo = true2".parse::<Value>().is_err()); - assert!("foo = false2".parse::<Value>().is_err()); - assert!("foo = t1".parse::<Value>().is_err()); - assert!("foo = f2".parse::<Value>().is_err()); -} - -#[test] -fn bad_nesting() { - bad!(" - a = [2] - [[a]] - b = 5 - ", "duplicate key: `a`"); - bad!(" - a = 1 - [a.b] - ", "duplicate key: `a`"); - bad!(" - a = [] - [a.b] - ", "duplicate key: `a`"); - bad!(" - a = [] - [[a.b]] - ", "duplicate key: `a`"); - bad!(" - [a] - b = { c = 2, d = {} } - [a.b] - c = 2 - ", "duplicate key: `b`"); -} - -#[test] -fn bad_table_redefine() { - bad!(" - [a] - foo=\"bar\" - [a.b] - foo=\"bar\" - [a] - ", "redefinition of table `a`"); - bad!(" - [a] - foo=\"bar\" - b = { foo = \"bar\" } - [a] - ", "redefinition of table `a`"); - bad!(" - [a] - b = {} - [a.b] - ", "duplicate key: `b`"); - - bad!(" - [a] - b = {} - [a] - ", "redefinition of table `a`"); -} - -#[test] -fn datetimes() { - macro_rules! t { - ($actual:expr) => ({ - let f = format!("foo = {}", $actual); - let toml = f.parse::<Value>().expect(&format!("failed: {}", f)); - assert_eq!(toml["foo"].as_datetime().unwrap().to_string(), $actual); - }) - } - - t!("2016-09-09T09:09:09Z"); - t!("2016-09-09T09:09:09.1Z"); - t!("2016-09-09T09:09:09.2+10:00"); - t!("2016-09-09T09:09:09.123456789-02:00"); - bad!("foo = 2016-09-09T09:09:09.Z", "failed to parse date"); - bad!("foo = 2016-9-09T09:09:09Z", "failed to parse date"); - bad!("foo = 2016-09-09T09:09:09+2:00", "failed to parse date"); - bad!("foo = 2016-09-09T09:09:09-2:00", "failed to parse date"); - bad!("foo = 2016-09-09T09:09:09Z-2:00", "failed to parse date"); -} - -#[test] -fn require_newline_after_value() { - bad!("0=0r=false", "invalid number at line 1"); - bad!(r#" -0=""o=""m=""r=""00="0"q="""0"""e="""0""" -"#, "expected newline"); - bad!(r#" -[[0000l0]] -0="0"[[0000l0]] -0="0"[[0000l0]] -0="0"l="0" -"#, "expected newline"); - bad!(r#" -0=[0]00=[0,0,0]t=["0","0","0"]s=[1000-00-00T00:00:00Z,2000-00-00T00:00:00Z] -"#, "expected newline"); - bad!(r#" -0=0r0=0r=false -"#, "invalid number at line 2"); - bad!(r#" -0=0r0=0r=falsefal=false -"#, "invalid number at line 2"); -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/pretty.rs cargo-0.26.0/vendor/toml-0.4.5/tests/pretty.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/pretty.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/pretty.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,308 +0,0 @@ -extern crate toml; -extern crate serde; - -use serde::ser::Serialize; - -const NO_PRETTY: &'static str = "\ -[example] -array = [\"item 1\", \"item 2\"] -empty = [] -oneline = \"this has no newlines.\" -text = \"\\nthis is the first line\\nthis is the second line\\n\" -"; - -#[test] -fn no_pretty() { - let toml = NO_PRETTY; - let value: toml::Value = toml::from_str(toml).unwrap(); - let mut result = String::with_capacity(128); - value.serialize(&mut toml::Serializer::new(&mut result)).unwrap(); - println!("EXPECTED:\n{}", toml); - println!("\nRESULT:\n{}", result); - assert_eq!(toml, &result); -} - -#[test] -fn disable_pretty() { - let toml = NO_PRETTY; - let value: toml::Value = toml::from_str(toml).unwrap(); - let mut result = String::with_capacity(128); - { - let mut serializer = toml::Serializer::pretty(&mut result); - serializer.pretty_string(false); - serializer.pretty_array(false); - value.serialize(&mut serializer).unwrap(); - } - println!("EXPECTED:\n{}", toml); - println!("\nRESULT:\n{}", result); - assert_eq!(toml, &result); -} - -const PRETTY_STD: &'static str = "\ -[example] -array = [ - 'item 1', - 'item 2', -] -empty = [] -one = ['one'] -oneline = 'this has no newlines.' -text = ''' -this is the first line -this is the second line -''' -"; - -#[test] -fn pretty_std() { - let toml = PRETTY_STD; - let value: toml::Value = toml::from_str(toml).unwrap(); - let mut result = String::with_capacity(128); - value.serialize(&mut toml::Serializer::pretty(&mut result)).unwrap(); - println!("EXPECTED:\n{}", toml); - println!("\nRESULT:\n{}", result); - assert_eq!(toml, &result); -} - - -const PRETTY_INDENT_2: &'static str = "\ -[example] -array = [ - 'item 1', - 'item 2', -] -empty = [] -one = ['one'] -oneline = 'this has no newlines.' -text = ''' -this is the first line -this is the second line -''' -three = [ - 'one', - 'two', - 'three', -] -"; - -#[test] -fn pretty_indent_2() { - let toml = PRETTY_INDENT_2; - let value: toml::Value = toml::from_str(toml).unwrap(); - let mut result = String::with_capacity(128); - { - let mut serializer = toml::Serializer::pretty(&mut result); - serializer.pretty_array_indent(2); - value.serialize(&mut serializer).unwrap(); - } - println!(">> Result:\n{}", result); - assert_eq!(toml, &result); -} - -const PRETTY_INDENT_2_OTHER: &'static str = "\ -[example] -array = [ - \"item 1\", - \"item 2\", -] -empty = [] -oneline = \"this has no newlines.\" -text = \"\\nthis is the first line\\nthis is the second line\\n\" -"; - - -#[test] -/// Test pretty indent when gotten the other way -fn pretty_indent_2_other() { - let toml = PRETTY_INDENT_2_OTHER; - let value: toml::Value = toml::from_str(toml).unwrap(); - let mut result = String::with_capacity(128); - { - let mut serializer = toml::Serializer::new(&mut result); - serializer.pretty_array_indent(2); - value.serialize(&mut serializer).unwrap(); - } - assert_eq!(toml, &result); -} - - -const PRETTY_ARRAY_NO_COMMA: &'static str = "\ -[example] -array = [ - \"item 1\", - \"item 2\" -] -empty = [] -oneline = \"this has no newlines.\" -text = \"\\nthis is the first line\\nthis is the second line\\n\" -"; -#[test] -/// Test pretty indent when gotten the other way -fn pretty_indent_array_no_comma() { - let toml = PRETTY_ARRAY_NO_COMMA; - let value: toml::Value = toml::from_str(toml).unwrap(); - let mut result = String::with_capacity(128); - { - let mut serializer = toml::Serializer::new(&mut result); - serializer.pretty_array_trailing_comma(false); - value.serialize(&mut serializer).unwrap(); - } - assert_eq!(toml, &result); -} - - -const PRETTY_NO_STRING: &'static str = "\ -[example] -array = [ - \"item 1\", - \"item 2\", -] -empty = [] -oneline = \"this has no newlines.\" -text = \"\\nthis is the first line\\nthis is the second line\\n\" -"; -#[test] -/// Test pretty indent when gotten the other way -fn pretty_no_string() { - let toml = PRETTY_NO_STRING; - let value: toml::Value = toml::from_str(toml).unwrap(); - let mut result = String::with_capacity(128); - { - let mut serializer = toml::Serializer::pretty(&mut result); - serializer.pretty_string(false); - value.serialize(&mut serializer).unwrap(); - } - assert_eq!(toml, &result); -} - -const PRETTY_TRICKY: &'static str = r##"[example] -f = "\f" -glass = ''' -Nothing too unusual, except that I can eat glass in: -- Greek: Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα. -- Polish: Mogę jeść szkło, i mi nie szkodzi. -- Hindi: मैं काँच खा सकता हूँ, मुझे उस से कोई पीडा नहीं होती. -- Japanese: 私はガラスを食べられます。それは私を傷つけません。 -''' -r = "\r" -r_newline = """ -\r -""" -single = '''this is a single line but has '' cuz it's tricky''' -single_tricky = "single line with ''' in it" -tabs = ''' -this is pretty standard - except for some tabs right here -''' -text = """ -this is the first line. -This has a ''' in it and \"\"\" cuz it's tricky yo -Also ' and \" because why not -this is the fourth line -""" -"##; - -#[test] -fn pretty_tricky() { - let toml = PRETTY_TRICKY; - let value: toml::Value = toml::from_str(toml).unwrap(); - let mut result = String::with_capacity(128); - value.serialize(&mut toml::Serializer::pretty(&mut result)).unwrap(); - println!("EXPECTED:\n{}", toml); - println!("\nRESULT:\n{}", result); - assert_eq!(toml, &result); -} - -const PRETTY_TABLE_ARRAY: &'static str = r##"[[array]] -key = 'foo' - -[[array]] -key = 'bar' - -[abc] -doc = 'this is a table' - -[example] -single = 'this is a single line string' -"##; - -#[test] -fn pretty_table_array() { - let toml = PRETTY_TABLE_ARRAY; - let value: toml::Value = toml::from_str(toml).unwrap(); - let mut result = String::with_capacity(128); - value.serialize(&mut toml::Serializer::pretty(&mut result)).unwrap(); - println!("EXPECTED:\n{}", toml); - println!("\nRESULT:\n{}", result); - assert_eq!(toml, &result); -} - -const TABLE_ARRAY: &'static str = r##"[[array]] -key = "foo" - -[[array]] -key = "bar" - -[abc] -doc = "this is a table" - -[example] -single = "this is a single line string" -"##; - -#[test] -fn table_array() { - let toml = TABLE_ARRAY; - let value: toml::Value = toml::from_str(toml).unwrap(); - let mut result = String::with_capacity(128); - value.serialize(&mut toml::Serializer::new(&mut result)).unwrap(); - println!("EXPECTED:\n{}", toml); - println!("\nRESULT:\n{}", result); - assert_eq!(toml, &result); -} - -const PRETTY_TRICKY_NON_LITERAL: &'static str = r##"[example] -f = "\f" -glass = """ -Nothing too unusual, except that I can eat glass in: -- Greek: Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα. -- Polish: Mogę jeść szkło, i mi nie szkodzi. -- Hindi: मैं काँच खा सकता हूँ, मुझे उस से कोई पीडा नहीं होती. -- Japanese: 私はガラスを食べられます。それは私を傷つけません。 -""" -plain = """ -This has a couple of lines -Because it likes to. -""" -r = "\r" -r_newline = """ -\r -""" -single = "this is a single line but has '' cuz it's tricky" -single_tricky = "single line with ''' in it" -tabs = """ -this is pretty standard -\texcept for some \ttabs right here -""" -text = """ -this is the first line. -This has a ''' in it and \"\"\" cuz it's tricky yo -Also ' and \" because why not -this is the fourth line -""" -"##; - -#[test] -fn pretty_tricky_non_literal() { - let toml = PRETTY_TRICKY_NON_LITERAL; - let value: toml::Value = toml::from_str(toml).unwrap(); - let mut result = String::with_capacity(128); - { - let mut serializer = toml::Serializer::pretty(&mut result); - serializer.pretty_string_literal(false); - value.serialize(&mut serializer).unwrap(); - } - println!("EXPECTED:\n{}", toml); - println!("\nRESULT:\n{}", result); - assert_eq!(toml, &result); -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/README.md cargo-0.26.0/vendor/toml-0.4.5/tests/README.md --- cargo-0.25.0/vendor/toml-0.4.5/tests/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -Tests are from https://github.com/BurntSushi/toml-test diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/serde.rs cargo-0.26.0/vendor/toml-0.4.5/tests/serde.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/serde.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/serde.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,578 +0,0 @@ -extern crate serde; -extern crate toml; -#[macro_use] -extern crate serde_derive; - -use std::collections::{BTreeMap, HashSet}; -use serde::{Deserialize, Deserializer}; - -use toml::Value; -use toml::Value::{Table, Integer, Array, Float}; - -macro_rules! t { - ($e:expr) => (match $e { - Ok(t) => t, - Err(e) => panic!("{} failed with {}", stringify!($e), e), - }) -} - -macro_rules! equivalent { - ($literal:expr, $toml:expr,) => ({ - let toml = $toml; - let literal = $literal; - - // In/out of Value is equivalent - println!("try_from"); - assert_eq!(t!(Value::try_from(literal.clone())), toml); - println!("try_into"); - assert_eq!(literal, t!(toml.clone().try_into())); - - // Through a string equivalent - println!("to_string(literal)"); - assert_eq!(t!(toml::to_string(&literal)), toml.to_string()); - println!("to_string(toml)"); - assert_eq!(t!(toml::to_string(&toml)), toml.to_string()); - println!("literal, from_str(toml)"); - assert_eq!(literal, t!(toml::from_str(&toml.to_string()))); - println!("toml, from_str(toml)"); - assert_eq!(toml, t!(toml::from_str(&toml.to_string()))); - }) -} - -macro_rules! error { - ($ty:ty, $toml:expr, $error:expr) => ({ - println!("attempting parsing"); - match toml::from_str::<$ty>(&$toml.to_string()) { - Ok(_) => panic!("successful"), - Err(e) => { - assert!(e.to_string().contains($error), - "bad error: {}", e); - } - } - - println!("attempting toml decoding"); - match $toml.try_into::<$ty>() { - Ok(_) => panic!("successful"), - Err(e) => { - assert!(e.to_string().contains($error), - "bad error: {}", e); - } - } - }) -} - -macro_rules! map( ($($k:ident: $v:expr),*) => ({ - let mut _m = BTreeMap::new(); - $(_m.insert(stringify!($k).to_string(), $v);)* - _m -}) ); - -#[test] -fn smoke() { - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo { a: isize } - - equivalent!( - Foo { a: 2 }, - Table(map! { a: Integer(2) }), - ); -} - -#[test] -fn smoke_hyphen() { - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo { - a_b: isize, - } - - equivalent! { - Foo { a_b: 2 }, - Table(map! { a_b: Integer(2) }), - } - - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo2 { - #[serde(rename = "a-b")] - a_b: isize, - } - - let mut m = BTreeMap::new(); - m.insert("a-b".to_string(), Integer(2)); - equivalent! { - Foo2 { a_b: 2 }, - Table(m), - } -} - -#[test] -fn nested() { - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo { a: isize, b: Bar } - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Bar { a: String } - - equivalent! { - Foo { a: 2, b: Bar { a: "test".to_string() } }, - Table(map! { - a: Integer(2), - b: Table(map! { - a: Value::String("test".to_string()) - }) - }), - } -} - -#[test] -fn application_decode_error() { - #[derive(PartialEq, Debug)] - struct Range10(usize); - impl<'de> Deserialize<'de> for Range10 { - fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Range10, D::Error> { - let x: usize = try!(Deserialize::deserialize(d)); - if x > 10 { - Err(serde::de::Error::custom("more than 10")) - } else { - Ok(Range10(x)) - } - } - } - let d_good = Integer(5); - let d_bad1 = Value::String("not an isize".to_string()); - let d_bad2 = Integer(11); - - assert_eq!(Range10(5), d_good.try_into().unwrap()); - - let err1: Result<Range10, _> = d_bad1.try_into(); - assert!(err1.is_err()); - let err2: Result<Range10, _> = d_bad2.try_into(); - assert!(err2.is_err()); -} - -#[test] -fn array() { - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo { a: Vec<isize> } - - equivalent! { - Foo { a: vec![1, 2, 3, 4] }, - Table(map! { - a: Array(vec![ - Integer(1), - Integer(2), - Integer(3), - Integer(4) - ]) - }), - }; -} - -#[test] -fn inner_structs_with_options() { - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo { - a: Option<Box<Foo>>, - b: Bar, - } - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Bar { - a: String, - b: f64, - } - - equivalent! { - Foo { - a: Some(Box::new(Foo { - a: None, - b: Bar { a: "foo".to_string(), b: 4.5 }, - })), - b: Bar { a: "bar".to_string(), b: 1.0 }, - }, - Table(map! { - a: Table(map! { - b: Table(map! { - a: Value::String("foo".to_string()), - b: Float(4.5) - }) - }), - b: Table(map! { - a: Value::String("bar".to_string()), - b: Float(1.0) - }) - }), - } -} - -#[test] -fn hashmap() { - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo { - set: HashSet<char>, - map: BTreeMap<String, isize>, - } - - equivalent! { - Foo { - map: { - let mut m = BTreeMap::new(); - m.insert("foo".to_string(), 10); - m.insert("bar".to_string(), 4); - m - }, - set: { - let mut s = HashSet::new(); - s.insert('a'); - s - }, - }, - Table(map! { - map: Table(map! { - foo: Integer(10), - bar: Integer(4) - }), - set: Array(vec![Value::String("a".to_string())]) - }), - } -} - -#[test] -fn table_array() { - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo { a: Vec<Bar>, } - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Bar { a: isize } - - equivalent! { - Foo { a: vec![Bar { a: 1 }, Bar { a: 2 }] }, - Table(map! { - a: Array(vec![ - Table(map!{ a: Integer(1) }), - Table(map!{ a: Integer(2) }), - ]) - }), - } -} - -#[test] -fn type_errors() { - #[derive(Deserialize)] - #[allow(dead_code)] - struct Foo { bar: isize } - - error! { - Foo, - Table(map! { - bar: Value::String("a".to_string()) - }), - "invalid type: string \"a\", expected isize for key `bar`" - } - - #[derive(Deserialize)] - #[allow(dead_code)] - struct Bar { foo: Foo } - - error! { - Bar, - Table(map! { - foo: Table(map! { - bar: Value::String("a".to_string()) - }) - }), - "invalid type: string \"a\", expected isize for key `foo.bar`" - } -} - -#[test] -fn missing_errors() { - #[derive(Serialize, Deserialize, PartialEq, Debug)] - struct Foo { bar: isize } - - error! { - Foo, - Table(map! { }), - "missing field `bar`" - } -} - -#[test] -fn parse_enum() { - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo { a: E } - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - #[serde(untagged)] - enum E { - Bar(isize), - Baz(String), - Last(Foo2), - } - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo2 { - test: String, - } - - equivalent! { - Foo { a: E::Bar(10) }, - Table(map! { a: Integer(10) }), - } - - equivalent! { - Foo { a: E::Baz("foo".to_string()) }, - Table(map! { a: Value::String("foo".to_string()) }), - } - - equivalent! { - Foo { a: E::Last(Foo2 { test: "test".to_string() }) }, - Table(map! { a: Table(map! { test: Value::String("test".to_string()) }) }), - } -} - -#[test] -fn parse_enum_string() { - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo { a: Sort } - - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - #[serde(rename_all = "lowercase")] - enum Sort { - Asc, - Desc, - } - - equivalent! { - Foo { a: Sort::Desc }, - Table(map! { a: Value::String("desc".to_string()) }), - } - -} - -// #[test] -// fn unused_fields() { -// #[derive(Serialize, Deserialize, PartialEq, Debug)] -// struct Foo { a: isize } -// -// let v = Foo { a: 2 }; -// let mut d = Decoder::new(Table(map! { -// a, Integer(2), -// b, Integer(5) -// })); -// assert_eq!(v, t!(Deserialize::deserialize(&mut d))); -// -// assert_eq!(d.toml, Some(Table(map! { -// b, Integer(5) -// }))); -// } -// -// #[test] -// fn unused_fields2() { -// #[derive(Serialize, Deserialize, PartialEq, Debug)] -// struct Foo { a: Bar } -// #[derive(Serialize, Deserialize, PartialEq, Debug)] -// struct Bar { a: isize } -// -// let v = Foo { a: Bar { a: 2 } }; -// let mut d = Decoder::new(Table(map! { -// a, Table(map! { -// a, Integer(2), -// b, Integer(5) -// }) -// })); -// assert_eq!(v, t!(Deserialize::deserialize(&mut d))); -// -// assert_eq!(d.toml, Some(Table(map! { -// a, Table(map! { -// b, Integer(5) -// }) -// }))); -// } -// -// #[test] -// fn unused_fields3() { -// #[derive(Serialize, Deserialize, PartialEq, Debug)] -// struct Foo { a: Bar } -// #[derive(Serialize, Deserialize, PartialEq, Debug)] -// struct Bar { a: isize } -// -// let v = Foo { a: Bar { a: 2 } }; -// let mut d = Decoder::new(Table(map! { -// a, Table(map! { -// a, Integer(2) -// }) -// })); -// assert_eq!(v, t!(Deserialize::deserialize(&mut d))); -// -// assert_eq!(d.toml, None); -// } -// -// #[test] -// fn unused_fields4() { -// #[derive(Serialize, Deserialize, PartialEq, Debug)] -// struct Foo { a: BTreeMap<String, String> } -// -// let v = Foo { a: map! { a, "foo".to_string() } }; -// let mut d = Decoder::new(Table(map! { -// a, Table(map! { -// a, Value::String("foo".to_string()) -// }) -// })); -// assert_eq!(v, t!(Deserialize::deserialize(&mut d))); -// -// assert_eq!(d.toml, None); -// } -// -// #[test] -// fn unused_fields5() { -// #[derive(Serialize, Deserialize, PartialEq, Debug)] -// struct Foo { a: Vec<String> } -// -// let v = Foo { a: vec!["a".to_string()] }; -// let mut d = Decoder::new(Table(map! { -// a, Array(vec![Value::String("a".to_string())]) -// })); -// assert_eq!(v, t!(Deserialize::deserialize(&mut d))); -// -// assert_eq!(d.toml, None); -// } -// -// #[test] -// fn unused_fields6() { -// #[derive(Serialize, Deserialize, PartialEq, Debug)] -// struct Foo { a: Option<Vec<String>> } -// -// let v = Foo { a: Some(vec![]) }; -// let mut d = Decoder::new(Table(map! { -// a, Array(vec![]) -// })); -// assert_eq!(v, t!(Deserialize::deserialize(&mut d))); -// -// assert_eq!(d.toml, None); -// } -// -// #[test] -// fn unused_fields7() { -// #[derive(Serialize, Deserialize, PartialEq, Debug)] -// struct Foo { a: Vec<Bar> } -// #[derive(Serialize, Deserialize, PartialEq, Debug)] -// struct Bar { a: isize } -// -// let v = Foo { a: vec![Bar { a: 1 }] }; -// let mut d = Decoder::new(Table(map! { -// a, Array(vec![Table(map! { -// a, Integer(1), -// b, Integer(2) -// })]) -// })); -// assert_eq!(v, t!(Deserialize::deserialize(&mut d))); -// -// assert_eq!(d.toml, Some(Table(map! { -// a, Array(vec![Table(map! { -// b, Integer(2) -// })]) -// }))); -// } - -#[test] -fn empty_arrays() { - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo { a: Vec<Bar> } - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Bar; - - equivalent! { - Foo { a: vec![] }, - Table(map! {a: Array(Vec::new())}), - } -} - -#[test] -fn empty_arrays2() { - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Foo { a: Option<Vec<Bar>> } - #[derive(Serialize, Deserialize, PartialEq, Debug, Clone)] - struct Bar; - - equivalent! { - Foo { a: None }, - Table(map! {}), - } - - equivalent!{ - Foo { a: Some(vec![]) }, - Table(map! { a: Array(vec![]) }), - } -} - -#[test] -fn extra_keys() { - #[derive(Serialize, Deserialize)] - struct Foo { a: isize } - - let toml = Table(map! { a: Integer(2), b: Integer(2) }); - assert!(toml.clone().try_into::<Foo>().is_ok()); - assert!(toml::from_str::<Foo>(&toml.to_string()).is_ok()); -} - -#[test] -fn newtypes() { - #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct A { - b: B - } - - #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct B(u32); - - equivalent! { - A { b: B(2) }, - Table(map! { b: Integer(2) }), - } -} - -#[test] -fn newtypes2() { - #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct A { - b: B - } - - #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct B(Option<C>); - - #[derive(Deserialize, Serialize, PartialEq, Debug, Clone)] - struct C { - x: u32, - y: u32, - z: u32 - } - - equivalent! { - A { b: B(Some(C { x: 0, y: 1, z: 2 })) }, - Table(map! { - b: Table(map! { - x: Integer(0), - y: Integer(1), - z: Integer(2) - }) - }), - } -} - -#[derive(Debug, Default, PartialEq, Serialize, Deserialize)] -struct CanBeEmpty { - a: Option<String>, - b: Option<String>, -} - -#[test] -fn table_structs_empty() { - let text = "[bar]\n\n[baz]\n\n[bazv]\na = \"foo\"\n\n[foo]\n"; - let value: BTreeMap<String, CanBeEmpty> = toml::from_str(text).unwrap(); - let mut expected: BTreeMap<String, CanBeEmpty> = BTreeMap::new(); - expected.insert("bar".to_string(), CanBeEmpty::default()); - expected.insert("baz".to_string(), CanBeEmpty::default()); - expected.insert( - "bazv".to_string(), - CanBeEmpty {a: Some("foo".to_string()), b: None}, - ); - expected.insert("foo".to_string(), CanBeEmpty::default()); - assert_eq!(value, expected); - assert_eq!(toml::to_string(&value).unwrap(), text); -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/tables-last.rs cargo-0.26.0/vendor/toml-0.4.5/tests/tables-last.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/tables-last.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/tables-last.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -#[macro_use] -extern crate serde_derive; -extern crate toml; - -use std::collections::HashMap; - -#[derive(Serialize)] -struct A { - #[serde(serialize_with = "toml::ser::tables_last")] - vals: HashMap<&'static str, Value>, -} - -#[derive(Serialize)] -#[serde(untagged)] -enum Value { - Map(HashMap<&'static str, &'static str>), - Int(i32), -} - -#[test] -fn always_works() { - let mut a = A { vals: HashMap::new() }; - a.vals.insert("foo", Value::Int(0)); - - let mut sub = HashMap::new(); - sub.insert("foo", "bar"); - a.vals.insert("bar", Value::Map(sub)); - - toml::to_string(&a).unwrap(); -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/array-empty.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/array-empty.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/array-empty.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/array-empty.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -{ - "thevoid": { "type": "array", "value": [ - {"type": "array", "value": [ - {"type": "array", "value": [ - {"type": "array", "value": [ - {"type": "array", "value": []} - ]} - ]} - ]} - ]} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/array-empty.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/array-empty.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/array-empty.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/array-empty.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -thevoid = [[[[[]]]]] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/array-nospaces.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/array-nospaces.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/array-nospaces.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/array-nospaces.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ -{ - "ints": { - "type": "array", - "value": [ - {"type": "integer", "value": "1"}, - {"type": "integer", "value": "2"}, - {"type": "integer", "value": "3"} - ] - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/array-nospaces.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/array-nospaces.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/array-nospaces.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/array-nospaces.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -ints = [1,2,3] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/arrays-hetergeneous.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/arrays-hetergeneous.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/arrays-hetergeneous.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/arrays-hetergeneous.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,19 +0,0 @@ -{ - "mixed": { - "type": "array", - "value": [ - {"type": "array", "value": [ - {"type": "integer", "value": "1"}, - {"type": "integer", "value": "2"} - ]}, - {"type": "array", "value": [ - {"type": "string", "value": "a"}, - {"type": "string", "value": "b"} - ]}, - {"type": "array", "value": [ - {"type": "float", "value": "1.1"}, - {"type": "float", "value": "2.1"} - ]} - ] - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/arrays-hetergeneous.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/arrays-hetergeneous.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/arrays-hetergeneous.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/arrays-hetergeneous.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -mixed = [[1, 2], ["a", "b"], [1.1, 2.1]] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/arrays.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/arrays.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/arrays.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/arrays.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,34 +0,0 @@ -{ - "ints": { - "type": "array", - "value": [ - {"type": "integer", "value": "1"}, - {"type": "integer", "value": "2"}, - {"type": "integer", "value": "3"} - ] - }, - "floats": { - "type": "array", - "value": [ - {"type": "float", "value": "1.1"}, - {"type": "float", "value": "2.1"}, - {"type": "float", "value": "3.1"} - ] - }, - "strings": { - "type": "array", - "value": [ - {"type": "string", "value": "a"}, - {"type": "string", "value": "b"}, - {"type": "string", "value": "c"} - ] - }, - "dates": { - "type": "array", - "value": [ - {"type": "datetime", "value": "1987-07-05T17:45:00Z"}, - {"type": "datetime", "value": "1979-05-27T07:32:00Z"}, - {"type": "datetime", "value": "2006-06-01T11:00:00Z"} - ] - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/arrays-nested.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/arrays-nested.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/arrays-nested.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/arrays-nested.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -{ - "nest": { - "type": "array", - "value": [ - {"type": "array", "value": [ - {"type": "string", "value": "a"} - ]}, - {"type": "array", "value": [ - {"type": "string", "value": "b"} - ]} - ] - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/arrays-nested.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/arrays-nested.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/arrays-nested.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/arrays-nested.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -nest = [["a"], ["b"]] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/arrays.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/arrays.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/arrays.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/arrays.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -ints = [1, 2, 3] -floats = [1.1, 2.1, 3.1] -strings = ["a", "b", "c"] -dates = [ - 1987-07-05T17:45:00Z, - 1979-05-27T07:32:00Z, - 2006-06-01T11:00:00Z, -] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/bool.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/bool.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/bool.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/bool.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -{ - "f": {"type": "bool", "value": "false"}, - "t": {"type": "bool", "value": "true"} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/bool.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/bool.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/bool.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/bool.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -t = true -f = false diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/comments-everywhere.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/comments-everywhere.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/comments-everywhere.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/comments-everywhere.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -{ - "group": { - "answer": {"type": "integer", "value": "42"}, - "more": { - "type": "array", - "value": [ - {"type": "integer", "value": "42"}, - {"type": "integer", "value": "42"} - ] - } - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/comments-everywhere.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/comments-everywhere.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/comments-everywhere.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/comments-everywhere.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -# Top comment. - # Top comment. -# Top comment. - -# [no-extraneous-groups-please] - -[group] # Comment -answer = 42 # Comment -# no-extraneous-keys-please = 999 -# Inbetween comment. -more = [ # Comment - # What about multiple # comments? - # Can you handle it? - # - # Evil. -# Evil. - 42, 42, # Comments within arrays are fun. - # What about multiple # comments? - # Can you handle it? - # - # Evil. -# Evil. -# ] Did I fool you? -] # Hopefully not. diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/datetime.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/datetime.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/datetime.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/datetime.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -{ - "bestdayever": {"type": "datetime", "value": "1987-07-05T17:45:00Z"} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/datetime.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/datetime.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/datetime.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/datetime.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -bestdayever = 1987-07-05T17:45:00Z diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/datetime-truncate.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/datetime-truncate.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/datetime-truncate.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/datetime-truncate.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -{ - "bestdayever": { - "type": "datetime", - "value": "1987-07-05T17:45:00.123456789Z" - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/datetime-truncate.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/datetime-truncate.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/datetime-truncate.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/datetime-truncate.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -bestdayever = 1987-07-05T17:45:00.123456789012345Z diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/empty.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/empty.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/empty.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/empty.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example2.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example2.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example2.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example2.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"clients":{"data":{"type":"array","value":[{"type":"array","value":[{"type":"string","value":"gamma"},{"type":"string","value":"delta"}]},{"type":"array","value":[{"type":"integer","value":"1"},{"type":"integer","value":"2"}]}]},"hosts":{"type":"array","value":[{"type":"string","value":"alpha"},{"type":"string","value":"omega"}]}},"database":{"connection_max":{"type":"integer","value":"5000"},"enabled":{"type":"bool","value":"true"},"ports":{"type":"array","value":[{"type":"integer","value":"8001"},{"type":"integer","value":"8001"},{"type":"integer","value":"8002"}]},"server":{"type":"string","value":"192.168.1.1"}},"owner":{"bio":{"type":"string","value":"GitHub Cofounder \u0026 CEO\nLikes tater tots and beer."},"dob":{"type":"datetime","value":"1979-05-27T07:32:00Z"},"name":{"type":"string","value":"Tom Preston-Werner"},"organization":{"type":"string","value":"GitHub"}},"products":[{"name":{"type":"string","value":"Hammer"},"sku":{"type":"integer","value":"738594937"}},{"color":{"type":"string","value":"gray"},"name":{"type":"string","value":"Nail"},"sku":{"type":"integer","value":"284758393"}}],"servers":{"alpha":{"dc":{"type":"string","value":"eqdc10"},"ip":{"type":"string","value":"10.0.0.1"}},"beta":{"country":{"type":"string","value":"中国"},"dc":{"type":"string","value":"eqdc10"},"ip":{"type":"string","value":"10.0.0.2"}}},"title":{"type":"string","value":"TOML Example"}} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example2.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example2.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example2.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example2.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,47 +0,0 @@ -# This is a TOML document. Boom. - -title = "TOML Example" - -[owner] -name = "Tom Preston-Werner" -organization = "GitHub" -bio = "GitHub Cofounder & CEO\nLikes tater tots and beer." -dob = 1979-05-27T07:32:00Z # First class dates? Why not? - -[database] -server = "192.168.1.1" -ports = [ 8001, 8001, 8002 ] -connection_max = 5000 -enabled = true - -[servers] - - # You can indent as you please. Tabs or spaces. TOML don't care. - [servers.alpha] - ip = "10.0.0.1" - dc = "eqdc10" - - [servers.beta] - ip = "10.0.0.2" - dc = "eqdc10" - country = "中国" # This should be parsed as UTF-8 - -[clients] -data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it - -# Line breaks are OK when inside arrays -hosts = [ - "alpha", - "omega" -] - -# Products - - [[products]] - name = "Hammer" - sku = 738594937 - - [[products]] - name = "Nail" - sku = 284758393 - color = "gray" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example-bom.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example-bom.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example-bom.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example-bom.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -best-day-ever = 1987-07-05T17:45:00Z - -[numtheory] -boring = false -perfection = [6, 28, 496] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -{ - "best-day-ever": {"type": "datetime", "value": "1987-07-05T17:45:00Z"}, - "numtheory": { - "boring": {"type": "bool", "value": "false"}, - "perfection": { - "type": "array", - "value": [ - {"type": "integer", "value": "6"}, - {"type": "integer", "value": "28"}, - {"type": "integer", "value": "496"} - ] - } - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -best-day-ever = 1987-07-05T17:45:00Z - -[numtheory] -boring = false -perfection = [6, 28, 496] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example-v0.3.0.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example-v0.3.0.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example-v0.3.0.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example-v0.3.0.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"Array":{"key1":{"type":"array","value":[{"type":"integer","value":"1"},{"type":"integer","value":"2"},{"type":"integer","value":"3"}]},"key2":{"type":"array","value":[{"type":"string","value":"red"},{"type":"string","value":"yellow"},{"type":"string","value":"green"}]},"key3":{"type":"array","value":[{"type":"array","value":[{"type":"integer","value":"1"},{"type":"integer","value":"2"}]},{"type":"array","value":[{"type":"integer","value":"3"},{"type":"integer","value":"4"},{"type":"integer","value":"5"}]}]},"key4":{"type":"array","value":[{"type":"array","value":[{"type":"integer","value":"1"},{"type":"integer","value":"2"}]},{"type":"array","value":[{"type":"string","value":"a"},{"type":"string","value":"b"},{"type":"string","value":"c"}]}]},"key5":{"type":"array","value":[{"type":"integer","value":"1"},{"type":"integer","value":"2"},{"type":"integer","value":"3"}]},"key6":{"type":"array","value":[{"type":"integer","value":"1"},{"type":"integer","value":"2"}]}},"Booleans":{"False":{"type":"bool","value":"false"},"True":{"type":"bool","value":"true"}},"Datetime":{"key1":{"type":"datetime","value":"1979-05-27T07:32:00Z"}},"Float":{"both":{},"exponent":{},"fractional":{"key1":{"type":"float","value":"1.0"},"key2":{"type":"float","value":"3.1415"},"key3":{"type":"float","value":"-0.01"}}},"Integer":{"key1":{"type":"integer","value":"99"},"key2":{"type":"integer","value":"42"},"key3":{"type":"integer","value":"0"},"key4":{"type":"integer","value":"-17"}},"String":{"Literal":{"Multiline":{"lines":{"type":"string","value":"The first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n"},"regex2":{"type":"string","value":"I [dw]on't need \\d{2} apples"}},"quoted":{"type":"string","value":"Tom \"Dubs\" Preston-Werner"},"regex":{"type":"string","value":"\u003c\\i\\c*\\s*\u003e"},"winpath":{"type":"string","value":"C:\\Users\\nodejs\\templates"},"winpath2":{"type":"string","value":"\\\\ServerX\\admin$\\system32\\"}},"Multiline":{"key1":{"type":"string","value":"One\nTwo"},"key2":{"type":"string","value":"One\nTwo"},"key3":{"type":"string","value":"One\nTwo"}},"Multilined":{"Singleline":{"key1":{"type":"string","value":"The quick brown fox jumps over the lazy dog."},"key2":{"type":"string","value":"The quick brown fox jumps over the lazy dog."},"key3":{"type":"string","value":"The quick brown fox jumps over the lazy dog."}}},"basic":{"type":"string","value":"I'm a string. \"You can quote me\". Name\u0009José\nLocation\u0009SF."}},"Table":{"key":{"type":"string","value":"value"}},"dog":{"tater":{"type":{"type":"string","value":"pug"}}},"fruit":[{"name":{"type":"string","value":"apple"},"physical":{"color":{"type":"string","value":"red"},"shape":{"type":"string","value":"round"}},"variety":[{"name":{"type":"string","value":"red delicious"}},{"name":{"type":"string","value":"granny smith"}}]},{"name":{"type":"string","value":"banana"},"variety":[{"name":{"type":"string","value":"plantain"}}]}],"products":[{"name":{"type":"string","value":"Hammer"},"sku":{"type":"integer","value":"738594937"}},{},{"color":{"type":"string","value":"gray"},"name":{"type":"string","value":"Nail"},"sku":{"type":"integer","value":"284758393"}}],"x":{"y":{"z":{"w":{}}}}} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example-v0.3.0.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example-v0.3.0.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example-v0.3.0.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example-v0.3.0.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,182 +0,0 @@ -# Comment -# I am a comment. Hear me roar. Roar. - -# Table -# Tables (also known as hash tables or dictionaries) are collections of key/value pairs. -# They appear in square brackets on a line by themselves. - -[Table] - -key = "value" # Yeah, you can do this. - -# Nested tables are denoted by table names with dots in them. Name your tables whatever crap you please, just don't use #, ., [ or ]. - -[dog.tater] -type = "pug" - -# You don't need to specify all the super-tables if you don't want to. TOML knows how to do it for you. - -# [x] you -# [x.y] don't -# [x.y.z] need these -[x.y.z.w] # for this to work - -# String -# There are four ways to express strings: basic, multi-line basic, literal, and multi-line literal. -# All strings must contain only valid UTF-8 characters. - -[String] -basic = "I'm a string. \"You can quote me\". Name\tJos\u00E9\nLocation\tSF." - -[String.Multiline] - -# The following strings are byte-for-byte equivalent: -key1 = "One\nTwo" -key2 = """One\nTwo""" -key3 = """ -One -Two""" - -[String.Multilined.Singleline] - -# The following strings are byte-for-byte equivalent: -key1 = "The quick brown fox jumps over the lazy dog." - -key2 = """ -The quick brown \ - - - fox jumps over \ - the lazy dog.""" - -key3 = """\ - The quick brown \ - fox jumps over \ - the lazy dog.\ - """ - -[String.Literal] - -# What you see is what you get. -winpath = 'C:\Users\nodejs\templates' -winpath2 = '\\ServerX\admin$\system32\' -quoted = 'Tom "Dubs" Preston-Werner' -regex = '<\i\c*\s*>' - - -[String.Literal.Multiline] - -regex2 = '''I [dw]on't need \d{2} apples''' -lines = ''' -The first newline is -trimmed in raw strings. - All other whitespace - is preserved. -''' - -# Integer -# Integers are whole numbers. Positive numbers may be prefixed with a plus sign. -# Negative numbers are prefixed with a minus sign. - -[Integer] -key1 = +99 -key2 = 42 -key3 = 0 -key4 = -17 - -# Float -# A float consists of an integer part (which may be prefixed with a plus or minus sign) -# followed by a fractional part and/or an exponent part. - -[Float.fractional] - -# fractional -key1 = +1.0 -key2 = 3.1415 -key3 = -0.01 - -[Float.exponent] - -# exponent -#key1 = 5e+22 -#key2 = 1e6 -#key3 = -2E-2 - -[Float.both] - -# both -#key = 6.626e-34 - -# Boolean -# Booleans are just the tokens you're used to. Always lowercase. - -[Booleans] -True = true -False = false - -# Datetime -# Datetimes are RFC 3339 dates. - -[Datetime] -key1 = 1979-05-27T07:32:00Z -#key2 = 1979-05-27T00:32:00-07:00 -#key3 = 1979-05-27T00:32:00.999999-07:00 - -# Array -# Arrays are square brackets with other primitives inside. Whitespace is ignored. Elements are separated by commas. Data types may not be mixed. - -[Array] -key1 = [ 1, 2, 3 ] -key2 = [ "red", "yellow", "green" ] -key3 = [ [ 1, 2 ], [3, 4, 5] ] -key4 = [ [ 1, 2 ], ["a", "b", "c"] ] # this is ok - -#Arrays can also be multiline. So in addition to ignoring whitespace, arrays also ignore newlines between the brackets. -# Terminating commas are ok before the closing bracket. - -key5 = [ - 1, 2, 3 -] -key6 = [ - 1, - 2, # this is ok -] - -# Array of Tables -# These can be expressed by using a table name in double brackets. -# Each table with the same double bracketed name will be an element in the array. -# The tables are inserted in the order encountered. - -[[products]] -name = "Hammer" -sku = 738594937 - -[[products]] - -[[products]] -name = "Nail" -sku = 284758393 -color = "gray" - - -# You can create nested arrays of tables as well. - -[[fruit]] - name = "apple" - - [fruit.physical] - color = "red" - shape = "round" - - [[fruit.variety]] - name = "red delicious" - - [[fruit.variety]] - name = "granny smith" - -[[fruit]] - name = "banana" - - [[fruit.variety]] - name = "plantain" - diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example-v0.4.0.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example-v0.4.0.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example-v0.4.0.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example-v0.4.0.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"array":{"key1":{"type":"array","value":[{"type":"integer","value":"1"},{"type":"integer","value":"2"},{"type":"integer","value":"3"}]},"key2":{"type":"array","value":[{"type":"string","value":"red"},{"type":"string","value":"yellow"},{"type":"string","value":"green"}]},"key3":{"type":"array","value":[{"type":"array","value":[{"type":"integer","value":"1"},{"type":"integer","value":"2"}]},{"type":"array","value":[{"type":"integer","value":"3"},{"type":"integer","value":"4"},{"type":"integer","value":"5"}]}]},"key4":{"type":"array","value":[{"type":"array","value":[{"type":"integer","value":"1"},{"type":"integer","value":"2"}]},{"type":"array","value":[{"type":"string","value":"a"},{"type":"string","value":"b"},{"type":"string","value":"c"}]}]},"key5":{"type":"array","value":[{"type":"integer","value":"1"},{"type":"integer","value":"2"},{"type":"integer","value":"3"}]},"key6":{"type":"array","value":[{"type":"integer","value":"1"},{"type":"integer","value":"2"}]}},"boolean":{"False":{"type":"bool","value":"false"},"True":{"type":"bool","value":"true"}},"datetime":{},"float":{"both":{},"exponent":{},"fractional":{"key1":{"type":"float","value":"1.0"},"key2":{"type":"float","value":"3.1415"},"key3":{"type":"float","value":"-0.01"}},"underscores":{}},"fruit":[{"name":{"type":"string","value":"apple"},"physical":{"color":{"type":"string","value":"red"},"shape":{"type":"string","value":"round"}},"variety":[{"name":{"type":"string","value":"red delicious"}},{"name":{"type":"string","value":"granny smith"}}]},{"name":{"type":"string","value":"banana"},"variety":[{"name":{"type":"string","value":"plantain"}}]}],"integer":{"key1":{"type":"integer","value":"99"},"key2":{"type":"integer","value":"42"},"key3":{"type":"integer","value":"0"},"key4":{"type":"integer","value":"-17"},"underscores":{"key1":{"type":"integer","value":"1000"},"key2":{"type":"integer","value":"5349221"},"key3":{"type":"integer","value":"12345"}}},"products":[{"name":{"type":"string","value":"Hammer"},"sku":{"type":"integer","value":"738594937"}},{},{"color":{"type":"string","value":"gray"},"name":{"type":"string","value":"Nail"},"sku":{"type":"integer","value":"284758393"}}],"string":{"basic":{"basic":{"type":"string","value":"I'm a string. \"You can quote me\". Name\u0009José\nLocation\u0009SF."}},"literal":{"multiline":{"lines":{"type":"string","value":"The first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n"},"regex2":{"type":"string","value":"I [dw]on't need \\d{2} apples"}},"quoted":{"type":"string","value":"Tom \"Dubs\" Preston-Werner"},"regex":{"type":"string","value":"\u003c\\i\\c*\\s*\u003e"},"winpath":{"type":"string","value":"C:\\Users\\nodejs\\templates"},"winpath2":{"type":"string","value":"\\\\ServerX\\admin$\\system32\\"}},"multiline":{"continued":{"key1":{"type":"string","value":"The quick brown fox jumps over the lazy dog."},"key2":{"type":"string","value":"The quick brown fox jumps over the lazy dog."},"key3":{"type":"string","value":"The quick brown fox jumps over the lazy dog."}},"key1":{"type":"string","value":"One\nTwo"},"key2":{"type":"string","value":"One\nTwo"},"key3":{"type":"string","value":"One\nTwo"}}},"table":{"inline":{"name":{"first":{"type":"string","value":"Tom"},"last":{"type":"string","value":"Preston-Werner"}},"point":{"x":{"type":"integer","value":"1"},"y":{"type":"integer","value":"2"}}},"key":{"type":"string","value":"value"},"subtable":{"key":{"type":"string","value":"another value"}}},"x":{"y":{"z":{"w":{}}}}} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example-v0.4.0.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example-v0.4.0.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/example-v0.4.0.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/example-v0.4.0.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,235 +0,0 @@ -################################################################################ -## Comment - -# Speak your mind with the hash symbol. They go from the symbol to the end of -# the line. - - -################################################################################ -## Table - -# Tables (also known as hash tables or dictionaries) are collections of -# key/value pairs. They appear in square brackets on a line by themselves. - -[table] - -key = "value" # Yeah, you can do this. - -# Nested tables are denoted by table names with dots in them. Name your tables -# whatever crap you please, just don't use #, ., [ or ]. - -[table.subtable] - -key = "another value" - -# You don't need to specify all the super-tables if you don't want to. TOML -# knows how to do it for you. - -# [x] you -# [x.y] don't -# [x.y.z] need these -[x.y.z.w] # for this to work - - -################################################################################ -## Inline Table - -# Inline tables provide a more compact syntax for expressing tables. They are -# especially useful for grouped data that can otherwise quickly become verbose. -# Inline tables are enclosed in curly braces `{` and `}`. No newlines are -# allowed between the curly braces unless they are valid within a value. - -[table.inline] - -name = { first = "Tom", last = "Preston-Werner" } -point = { x = 1, y = 2 } - - -################################################################################ -## String - -# There are four ways to express strings: basic, multi-line basic, literal, and -# multi-line literal. All strings must contain only valid UTF-8 characters. - -[string.basic] - -basic = "I'm a string. \"You can quote me\". Name\tJos\u00E9\nLocation\tSF." - -[string.multiline] - -# The following strings are byte-for-byte equivalent: -key1 = "One\nTwo" -key2 = """One\nTwo""" -key3 = """ -One -Two""" - -[string.multiline.continued] - -# The following strings are byte-for-byte equivalent: -key1 = "The quick brown fox jumps over the lazy dog." - -key2 = """ -The quick brown \ - - - fox jumps over \ - the lazy dog.""" - -key3 = """\ - The quick brown \ - fox jumps over \ - the lazy dog.\ - """ - -[string.literal] - -# What you see is what you get. -winpath = 'C:\Users\nodejs\templates' -winpath2 = '\\ServerX\admin$\system32\' -quoted = 'Tom "Dubs" Preston-Werner' -regex = '<\i\c*\s*>' - - -[string.literal.multiline] - -regex2 = '''I [dw]on't need \d{2} apples''' -lines = ''' -The first newline is -trimmed in raw strings. - All other whitespace - is preserved. -''' - - -################################################################################ -## Integer - -# Integers are whole numbers. Positive numbers may be prefixed with a plus sign. -# Negative numbers are prefixed with a minus sign. - -[integer] - -key1 = +99 -key2 = 42 -key3 = 0 -key4 = -17 - -[integer.underscores] - -# For large numbers, you may use underscores to enhance readability. Each -# underscore must be surrounded by at least one digit. -key1 = 1_000 -key2 = 5_349_221 -key3 = 1_2_3_4_5 # valid but inadvisable - - -################################################################################ -## Float - -# A float consists of an integer part (which may be prefixed with a plus or -# minus sign) followed by a fractional part and/or an exponent part. - -[float.fractional] - -key1 = +1.0 -key2 = 3.1415 -key3 = -0.01 - -[float.exponent] - -[float.both] - -[float.underscores] - - -################################################################################ -## Boolean - -# Booleans are just the tokens you're used to. Always lowercase. - -[boolean] - -True = true -False = false - - -################################################################################ -## Datetime - -# Datetimes are RFC 3339 dates. - -[datetime] - -#key1 = 1979-05-27T07:32:00Z -#key2 = 1979-05-27T00:32:00-07:00 -#key3 = 1979-05-27T00:32:00.999999-07:00 - - -################################################################################ -## Array - -# Arrays are square brackets with other primitives inside. Whitespace is -# ignored. Elements are separated by commas. Data types may not be mixed. - -[array] - -key1 = [ 1, 2, 3 ] -key2 = [ "red", "yellow", "green" ] -key3 = [ [ 1, 2 ], [3, 4, 5] ] -key4 = [ [ 1, 2 ], ["a", "b", "c"] ] # this is ok - -# Arrays can also be multiline. So in addition to ignoring whitespace, arrays -# also ignore newlines between the brackets. Terminating commas are ok before -# the closing bracket. - -key5 = [ - 1, 2, 3 -] -key6 = [ - 1, - 2, # this is ok -] - - -################################################################################ -## Array of Tables - -# These can be expressed by using a table name in double brackets. Each table -# with the same double bracketed name will be an element in the array. The -# tables are inserted in the order encountered. - -[[products]] - -name = "Hammer" -sku = 738594937 - -[[products]] - -[[products]] - -name = "Nail" -sku = 284758393 -color = "gray" - - -# You can create nested arrays of tables as well. - -[[fruit]] - name = "apple" - - [fruit.physical] - color = "red" - shape = "round" - - [[fruit.variety]] - name = "red delicious" - - [[fruit.variety]] - name = "granny smith" - -[[fruit]] - name = "banana" - - [[fruit.variety]] - name = "plantain" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/float.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/float.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/float.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/float.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -{ - "pi": {"type": "float", "value": "3.14"}, - "negpi": {"type": "float", "value": "-3.14"} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/float.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/float.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/float.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/float.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -pi = 3.14 -negpi = -3.14 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/hard_example.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/hard_example.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/hard_example.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/hard_example.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"the":{"hard":{"another_test_string":{"type":"string","value":" Same thing, but with a string #"},"bit#":{"multi_line_array":{"type":"array","value":[{"type":"string","value":"]"}]},"what?":{"type":"string","value":"You don't think some user won't do that?"}},"harder_test_string":{"type":"string","value":" And when \"'s are in the string, along with # \""},"test_array":{"type":"array","value":[{"type":"string","value":"] "},{"type":"string","value":" # "}]},"test_array2":{"type":"array","value":[{"type":"string","value":"Test #11 ]proved that"},{"type":"string","value":"Experiment #9 was a success"}]}},"test_string":{"type":"string","value":"You'll hate me after this - #"}}} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/hard_example.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/hard_example.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/hard_example.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/hard_example.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,33 +0,0 @@ -# Test file for TOML -# Only this one tries to emulate a TOML file written by a user of the kind of parser writers probably hate -# This part you'll really hate - -[the] -test_string = "You'll hate me after this - #" # " Annoying, isn't it? - - [the.hard] - test_array = [ "] ", " # "] # ] There you go, parse this! - test_array2 = [ "Test #11 ]proved that", "Experiment #9 was a success" ] - # You didn't think it'd as easy as chucking out the last #, did you? - another_test_string = " Same thing, but with a string #" - harder_test_string = " And when \"'s are in the string, along with # \"" # "and comments are there too" - # Things will get harder - - [the.hard."bit#"] - "what?" = "You don't think some user won't do that?" - multi_line_array = [ - "]", - # ] Oh yes I did - ] - -# Each of the following keygroups/key value pairs should produce an error. Uncomment to them to test - -#[error] if you didn't catch this, your parser is broken -#string = "Anything other than tabs, spaces and newline after a keygroup or key value pair has ended should produce an error unless it is a comment" like this -#array = [ -# "This might most likely happen in multiline arrays", -# Like here, -# "or here, -# and here" -# ] End of array comment, forgot the # -#number = 3.14 pi <--again forgot the # diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-after.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-after.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-after.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-after.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ -{ - "a": { - "better": {"type": "integer", "value": "43"}, - "b": { - "c": { - "answer": {"type": "integer", "value": "42"} - } - } - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-after.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-after.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-after.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-after.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -[a.b.c] -answer = 42 - -[a] -better = 43 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-before.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-before.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-before.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-before.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ -{ - "a": { - "better": {"type": "integer", "value": "43"}, - "b": { - "c": { - "answer": {"type": "integer", "value": "42"} - } - } - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-before.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-before.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-before.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/implicit-and-explicit-before.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -[a] -better = 43 - -[a.b.c] -answer = 42 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/implicit-groups.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/implicit-groups.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/implicit-groups.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/implicit-groups.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ -{ - "a": { - "b": { - "c": { - "answer": {"type": "integer", "value": "42"} - } - } - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/implicit-groups.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/implicit-groups.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/implicit-groups.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/implicit-groups.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -[a.b.c] -answer = 42 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/integer.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/integer.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/integer.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/integer.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -{ - "answer": {"type": "integer", "value": "42"}, - "neganswer": {"type": "integer", "value": "-42"} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/integer.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/integer.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/integer.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/integer.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -answer = 42 -neganswer = -42 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-equals-nospace.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-equals-nospace.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-equals-nospace.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-equals-nospace.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -{ - "answer": {"type": "integer", "value": "42"} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-equals-nospace.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-equals-nospace.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-equals-nospace.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-equals-nospace.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -answer=42 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-quote-newline.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-quote-newline.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-quote-newline.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-quote-newline.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -{ - "\n": {"type": "integer", "value": "1"} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-quote-newline.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-quote-newline.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-quote-newline.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-quote-newline.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -"\n" = 1 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-space.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-space.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-space.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-space.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -{ - "a b": {"type": "integer", "value": "1"} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-space.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-space.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-space.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-space.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -"a b" = 1 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-special-chars.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-special-chars.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-special-chars.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-special-chars.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -{ - "~!@#$^&*()_+-`1234567890[]\\|/?><.,;:'": { - "type": "integer", "value": "1" - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-special-chars.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-special-chars.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-special-chars.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-special-chars.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -"~!@#$^&*()_+-`1234567890[]\\|/?><.,;:'" = 1 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-with-pound.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-with-pound.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-with-pound.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-with-pound.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -{ - "key#name": {"type": "integer", "value": "5"} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-with-pound.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-with-pound.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/key-with-pound.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/key-with-pound.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -"key#name" = 5 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/long-float.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/long-float.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/long-float.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/long-float.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -{ - "longpi": {"type": "float", "value": "3.141592653589793"}, - "neglongpi": {"type": "float", "value": "-3.141592653589793"} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/long-float.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/long-float.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/long-float.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/long-float.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -longpi = 3.141592653589793 -neglongpi = -3.141592653589793 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/long-integer.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/long-integer.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/long-integer.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/long-integer.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,4 +0,0 @@ -{ - "answer": {"type": "integer", "value": "9223372036854775807"}, - "neganswer": {"type": "integer", "value": "-9223372036854775808"} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/long-integer.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/long-integer.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/long-integer.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/long-integer.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -answer = 9223372036854775807 -neganswer = -9223372036854775808 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/multiline-string.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/multiline-string.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/multiline-string.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/multiline-string.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -{ - "multiline_empty_one": { - "type": "string", - "value": "" - }, - "multiline_empty_two": { - "type": "string", - "value": "" - }, - "multiline_empty_three": { - "type": "string", - "value": "" - }, - "multiline_empty_four": { - "type": "string", - "value": "" - }, - "equivalent_one": { - "type": "string", - "value": "The quick brown fox jumps over the lazy dog." - }, - "equivalent_two": { - "type": "string", - "value": "The quick brown fox jumps over the lazy dog." - }, - "equivalent_three": { - "type": "string", - "value": "The quick brown fox jumps over the lazy dog." - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/multiline-string.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/multiline-string.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/multiline-string.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/multiline-string.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -multiline_empty_one = """""" -multiline_empty_two = """ -""" -multiline_empty_three = """\ - """ -multiline_empty_four = """\ - \ - \ - """ - -equivalent_one = "The quick brown fox jumps over the lazy dog." -equivalent_two = """ -The quick brown \ - - - fox jumps over \ - the lazy dog.""" - -equivalent_three = """\ - The quick brown \ - fox jumps over \ - the lazy dog.\ - """ diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/raw-multiline-string.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/raw-multiline-string.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/raw-multiline-string.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/raw-multiline-string.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -{ - "oneline": { - "type": "string", - "value": "This string has a ' quote character." - }, - "firstnl": { - "type": "string", - "value": "This string has a ' quote character." - }, - "multiline": { - "type": "string", - "value": "This string\nhas ' a quote character\nand more than\none newline\nin it." - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/raw-multiline-string.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/raw-multiline-string.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/raw-multiline-string.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/raw-multiline-string.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,9 +0,0 @@ -oneline = '''This string has a ' quote character.''' -firstnl = ''' -This string has a ' quote character.''' -multiline = ''' -This string -has ' a quote character -and more than -one newline -in it.''' diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/raw-string.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/raw-string.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/raw-string.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/raw-string.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,30 +0,0 @@ -{ - "backspace": { - "type": "string", - "value": "This string has a \\b backspace character." - }, - "tab": { - "type": "string", - "value": "This string has a \\t tab character." - }, - "newline": { - "type": "string", - "value": "This string has a \\n new line character." - }, - "formfeed": { - "type": "string", - "value": "This string has a \\f form feed character." - }, - "carriage": { - "type": "string", - "value": "This string has a \\r carriage return character." - }, - "slash": { - "type": "string", - "value": "This string has a \\/ slash character." - }, - "backslash": { - "type": "string", - "value": "This string has a \\\\ backslash character." - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/raw-string.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/raw-string.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/raw-string.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/raw-string.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -backspace = 'This string has a \b backspace character.' -tab = 'This string has a \t tab character.' -newline = 'This string has a \n new line character.' -formfeed = 'This string has a \f form feed character.' -carriage = 'This string has a \r carriage return character.' -slash = 'This string has a \/ slash character.' -backslash = 'This string has a \\ backslash character.' diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-empty.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-empty.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-empty.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-empty.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -{ - "answer": { - "type": "string", - "value": "" - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-empty.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-empty.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-empty.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-empty.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -answer = "" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-escapes.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-escapes.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-escapes.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-escapes.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,50 +0,0 @@ -{ - "backspace": { - "type": "string", - "value": "This string has a \u0008 backspace character." - }, - "tab": { - "type": "string", - "value": "This string has a \u0009 tab character." - }, - "newline": { - "type": "string", - "value": "This string has a \u000A new line character." - }, - "formfeed": { - "type": "string", - "value": "This string has a \u000C form feed character." - }, - "carriage": { - "type": "string", - "value": "This string has a \u000D carriage return character." - }, - "quote": { - "type": "string", - "value": "This string has a \u0022 quote character." - }, - "slash": { - "type": "string", - "value": "This string has a \u002F slash character." - }, - "backslash": { - "type": "string", - "value": "This string has a \u005C backslash character." - }, - "notunicode1": { - "type": "string", - "value": "This string does not have a unicode \\u escape." - }, - "notunicode2": { - "type": "string", - "value": "This string does not have a unicode \u005Cu escape." - }, - "notunicode3": { - "type": "string", - "value": "This string does not have a unicode \\u0075 escape." - }, - "notunicode4": { - "type": "string", - "value": "This string does not have a unicode \\\u0075 escape." - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-escapes.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-escapes.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-escapes.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-escapes.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,12 +0,0 @@ -backspace = "This string has a \b backspace character." -tab = "This string has a \t tab character." -newline = "This string has a \n new line character." -formfeed = "This string has a \f form feed character." -carriage = "This string has a \r carriage return character." -quote = "This string has a \" quote character." -slash = "This string has a / slash character." -backslash = "This string has a \\ backslash character." -notunicode1 = "This string does not have a unicode \\u escape." -notunicode2 = "This string does not have a unicode \u005Cu escape." -notunicode3 = "This string does not have a unicode \\u0075 escape." -notunicode4 = "This string does not have a unicode \\\u0075 escape." diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-simple.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-simple.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-simple.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-simple.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -{ - "answer": { - "type": "string", - "value": "You are not drinking enough whisky." - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-simple.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-simple.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-simple.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-simple.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -answer = "You are not drinking enough whisky." diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-with-pound.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-with-pound.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-with-pound.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-with-pound.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -{ - "pound": {"type": "string", "value": "We see no # comments here."}, - "poundcomment": { - "type": "string", - "value": "But there are # some comments here." - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-with-pound.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-with-pound.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/string-with-pound.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/string-with-pound.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -pound = "We see no # comments here." -poundcomment = "But there are # some comments here." # Did I # mess you up? diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-implicit.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-implicit.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-implicit.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-implicit.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,7 +0,0 @@ -{ - "albums": { - "songs": [ - {"name": {"type": "string", "value": "Glory Days"}} - ] - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-implicit.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-implicit.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-implicit.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-implicit.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -[[albums.songs]] -name = "Glory Days" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-many.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-many.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-many.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-many.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,16 +0,0 @@ -{ - "people": [ - { - "first_name": {"type": "string", "value": "Bruce"}, - "last_name": {"type": "string", "value": "Springsteen"} - }, - { - "first_name": {"type": "string", "value": "Eric"}, - "last_name": {"type": "string", "value": "Clapton"} - }, - { - "first_name": {"type": "string", "value": "Bob"}, - "last_name": {"type": "string", "value": "Seger"} - } - ] -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-many.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-many.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-many.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-many.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ -[[people]] -first_name = "Bruce" -last_name = "Springsteen" - -[[people]] -first_name = "Eric" -last_name = "Clapton" - -[[people]] -first_name = "Bob" -last_name = "Seger" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-nest.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-nest.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-nest.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-nest.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,18 +0,0 @@ -{ - "albums": [ - { - "name": {"type": "string", "value": "Born to Run"}, - "songs": [ - {"name": {"type": "string", "value": "Jungleland"}}, - {"name": {"type": "string", "value": "Meeting Across the River"}} - ] - }, - { - "name": {"type": "string", "value": "Born in the USA"}, - "songs": [ - {"name": {"type": "string", "value": "Glory Days"}}, - {"name": {"type": "string", "value": "Dancing in the Dark"}} - ] - } - ] -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-nest-no-keys.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-nest-no-keys.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-nest-no-keys.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-nest-no-keys.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -{ - "albums": [ - { - "songs": [{}, {}] - } - ], - "artists": [ - { - "home": { - "address": {} - } - } - ] -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-nest-no-keys.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-nest-no-keys.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-nest-no-keys.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-nest-no-keys.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,6 +0,0 @@ -[[ albums ]] - [[ albums.songs ]] - [[ albums.songs ]] - -[[ artists ]] - [ artists.home.address ] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-nest.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-nest.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-nest.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-nest.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,17 +0,0 @@ -[[albums]] -name = "Born to Run" - - [[albums.songs]] - name = "Jungleland" - - [[albums.songs]] - name = "Meeting Across the River" - -[[albums]] -name = "Born in the USA" - - [[albums.songs]] - name = "Glory Days" - - [[albums.songs]] - name = "Dancing in the Dark" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-one.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-one.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-one.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-one.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,8 +0,0 @@ -{ - "people": [ - { - "first_name": {"type": "string", "value": "Bruce"}, - "last_name": {"type": "string", "value": "Springsteen"} - } - ] -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-one.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-one.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-array-one.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-array-one.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -[[people]] -first_name = "Bruce" -last_name = "Springsteen" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-empty.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-empty.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-empty.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-empty.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -{ - "a": {} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-empty.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-empty.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-empty.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-empty.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -[a] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-multi-empty.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-multi-empty.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-multi-empty.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-multi-empty.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -{ - "a": { "b": {} }, - "b": {}, - "c": { "a": {} } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-multi-empty.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-multi-empty.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-multi-empty.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-multi-empty.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -[a] -[a.b] -[b] -[c] -[c.a] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-sub-empty.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-sub-empty.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-sub-empty.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-sub-empty.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -{ - "a": { "b": {} } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-sub-empty.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-sub-empty.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-sub-empty.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-sub-empty.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -[a] -[a.b] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-whitespace.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-whitespace.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-whitespace.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-whitespace.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -{ - "valid key": {} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-whitespace.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-whitespace.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-whitespace.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-whitespace.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -["valid key"] diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-with-pound.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-with-pound.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-with-pound.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-with-pound.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -{ - "key#group": { - "answer": {"type": "integer", "value": "42"} - } -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-with-pound.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-with-pound.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/table-with-pound.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/table-with-pound.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,2 +0,0 @@ -["key#group"] -answer = 42 diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/unicode-escape.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/unicode-escape.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/unicode-escape.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/unicode-escape.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,5 +0,0 @@ -{ - "answer1": {"type": "string", "value": "\u000B"}, - "answer4": {"type": "string", "value": "\u03B4α"}, - "answer8": {"type": "string", "value": "\u03B4β"} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/unicode-escape.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/unicode-escape.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/unicode-escape.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/unicode-escape.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -answer1 = "\u000B" -answer4 = "\u03B4α" -answer8 = "\U000003B4β" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/unicode-literal.json cargo-0.26.0/vendor/toml-0.4.5/tests/valid/unicode-literal.json --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/unicode-literal.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/unicode-literal.json 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -{ - "answer": {"type": "string", "value": "δ"} -} diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid/unicode-literal.toml cargo-0.26.0/vendor/toml-0.4.5/tests/valid/unicode-literal.toml --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid/unicode-literal.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid/unicode-literal.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -answer = "δ" diff -Nru cargo-0.25.0/vendor/toml-0.4.5/tests/valid.rs cargo-0.26.0/vendor/toml-0.4.5/tests/valid.rs --- cargo-0.25.0/vendor/toml-0.4.5/tests/valid.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/tests/valid.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,249 +0,0 @@ -extern crate toml; -extern crate serde; -extern crate serde_json; - -use toml::{Value as Toml, to_string_pretty}; -use serde::ser::Serialize; -use serde_json::Value as Json; - -fn to_json(toml: toml::Value) -> Json { - fn doit(s: &str, json: Json) -> Json { - let mut map = serde_json::Map::new(); - map.insert("type".to_string(), Json::String(s.to_string())); - map.insert("value".to_string(), json); - Json::Object(map) - } - - match toml { - Toml::String(s) => doit("string", Json::String(s)), - Toml::Integer(i) => doit("integer", Json::String(i.to_string())), - Toml::Float(f) => doit("float", Json::String({ - let s = format!("{:.15}", f); - let s = format!("{}", s.trim_right_matches('0')); - if s.ends_with('.') {format!("{}0", s)} else {s} - })), - Toml::Boolean(b) => doit("bool", Json::String(format!("{}", b))), - Toml::Datetime(s) => doit("datetime", Json::String(s.to_string())), - Toml::Array(arr) => { - let is_table = match arr.first() { - Some(&Toml::Table(..)) => true, - _ => false, - }; - let json = Json::Array(arr.into_iter().map(to_json).collect()); - if is_table {json} else {doit("array", json)} - } - Toml::Table(table) => { - let mut map = serde_json::Map::new(); - for (k, v) in table { - map.insert(k, to_json(v)); - } - Json::Object(map) - } - } -} - -fn run_pretty(toml: Toml) { - // Assert toml == json - println!("### pretty round trip parse."); - - // standard pretty - let toml_raw = to_string_pretty(&toml).expect("to string"); - let toml2 = toml_raw.parse().expect("from string"); - assert_eq!(toml, toml2); - - // pretty with indent 2 - let mut result = String::with_capacity(128); - { - let mut serializer = toml::Serializer::pretty(&mut result); - serializer.pretty_array_indent(2); - toml.serialize(&mut serializer).expect("to string"); - } - assert_eq!(toml, result.parse().expect("from str")); - result.clear(); - { - let mut serializer = toml::Serializer::new(&mut result); - serializer.pretty_array_trailing_comma(false); - toml.serialize(&mut serializer).expect("to string"); - } - assert_eq!(toml, result.parse().expect("from str")); - result.clear(); - { - let mut serializer = toml::Serializer::pretty(&mut result); - serializer.pretty_string(false); - toml.serialize(&mut serializer).expect("to string"); - assert_eq!(toml, toml2); - } - assert_eq!(toml, result.parse().expect("from str")); - result.clear(); - { - let mut serializer = toml::Serializer::pretty(&mut result); - serializer.pretty_array(false); - toml.serialize(&mut serializer).expect("to string"); - assert_eq!(toml, toml2); - } - assert_eq!(toml, result.parse().expect("from str")); -} - -fn run(toml_raw: &str, json_raw: &str) { - println!("parsing:\n{}", toml_raw); - let toml: Toml = toml_raw.parse().unwrap(); - let json: Json = json_raw.parse().unwrap(); - - // Assert toml == json - let toml_json = to_json(toml.clone()); - assert!(json == toml_json, - "expected\n{}\ngot\n{}\n", - serde_json::to_string_pretty(&json).unwrap(), - serde_json::to_string_pretty(&toml_json).unwrap()); - - // Assert round trip - println!("round trip parse: {}", toml); - let toml2 = toml.to_string().parse().unwrap(); - assert_eq!(toml, toml2); - run_pretty(toml); -} - -macro_rules! test( ($name:ident, $toml:expr, $json:expr) => ( - #[test] - fn $name() { run($toml, $json); } -) ); - -test!(array_empty, - include_str!("valid/array-empty.toml"), - include_str!("valid/array-empty.json")); -test!(array_nospaces, - include_str!("valid/array-nospaces.toml"), - include_str!("valid/array-nospaces.json")); -test!(arrays_hetergeneous, - include_str!("valid/arrays-hetergeneous.toml"), - include_str!("valid/arrays-hetergeneous.json")); -test!(arrays, - include_str!("valid/arrays.toml"), - include_str!("valid/arrays.json")); -test!(arrays_nested, - include_str!("valid/arrays-nested.toml"), - include_str!("valid/arrays-nested.json")); -test!(empty, - include_str!("valid/empty.toml"), - include_str!("valid/empty.json")); -test!(bool, - include_str!("valid/bool.toml"), - include_str!("valid/bool.json")); -test!(datetime, - include_str!("valid/datetime.toml"), - include_str!("valid/datetime.json")); -test!(example, - include_str!("valid/example.toml"), - include_str!("valid/example.json")); -test!(float, - include_str!("valid/float.toml"), - include_str!("valid/float.json")); -test!(implicit_and_explicit_after, - include_str!("valid/implicit-and-explicit-after.toml"), - include_str!("valid/implicit-and-explicit-after.json")); -test!(implicit_and_explicit_before, - include_str!("valid/implicit-and-explicit-before.toml"), - include_str!("valid/implicit-and-explicit-before.json")); -test!(implicit_groups, - include_str!("valid/implicit-groups.toml"), - include_str!("valid/implicit-groups.json")); -test!(integer, - include_str!("valid/integer.toml"), - include_str!("valid/integer.json")); -test!(key_equals_nospace, - include_str!("valid/key-equals-nospace.toml"), - include_str!("valid/key-equals-nospace.json")); -test!(key_space, - include_str!("valid/key-space.toml"), - include_str!("valid/key-space.json")); -test!(key_special_chars, - include_str!("valid/key-special-chars.toml"), - include_str!("valid/key-special-chars.json")); -test!(key_with_pound, - include_str!("valid/key-with-pound.toml"), - include_str!("valid/key-with-pound.json")); -test!(long_float, - include_str!("valid/long-float.toml"), - include_str!("valid/long-float.json")); -test!(long_integer, - include_str!("valid/long-integer.toml"), - include_str!("valid/long-integer.json")); -test!(multiline_string, - include_str!("valid/multiline-string.toml"), - include_str!("valid/multiline-string.json")); -test!(raw_multiline_string, - include_str!("valid/raw-multiline-string.toml"), - include_str!("valid/raw-multiline-string.json")); -test!(raw_string, - include_str!("valid/raw-string.toml"), - include_str!("valid/raw-string.json")); -test!(string_empty, - include_str!("valid/string-empty.toml"), - include_str!("valid/string-empty.json")); -test!(string_escapes, - include_str!("valid/string-escapes.toml"), - include_str!("valid/string-escapes.json")); -test!(string_simple, - include_str!("valid/string-simple.toml"), - include_str!("valid/string-simple.json")); -test!(string_with_pound, - include_str!("valid/string-with-pound.toml"), - include_str!("valid/string-with-pound.json")); -test!(table_array_implicit, - include_str!("valid/table-array-implicit.toml"), - include_str!("valid/table-array-implicit.json")); -test!(table_array_many, - include_str!("valid/table-array-many.toml"), - include_str!("valid/table-array-many.json")); -test!(table_array_nest, - include_str!("valid/table-array-nest.toml"), - include_str!("valid/table-array-nest.json")); -test!(table_array_one, - include_str!("valid/table-array-one.toml"), - include_str!("valid/table-array-one.json")); -test!(table_empty, - include_str!("valid/table-empty.toml"), - include_str!("valid/table-empty.json")); -test!(table_sub_empty, - include_str!("valid/table-sub-empty.toml"), - include_str!("valid/table-sub-empty.json")); -test!(table_multi_empty, - include_str!("valid/table-multi-empty.toml"), - include_str!("valid/table-multi-empty.json")); -test!(table_whitespace, - include_str!("valid/table-whitespace.toml"), - include_str!("valid/table-whitespace.json")); -test!(table_with_pound, - include_str!("valid/table-with-pound.toml"), - include_str!("valid/table-with-pound.json")); -test!(unicode_escape, - include_str!("valid/unicode-escape.toml"), - include_str!("valid/unicode-escape.json")); -test!(unicode_literal, - include_str!("valid/unicode-literal.toml"), - include_str!("valid/unicode-literal.json")); -test!(hard_example, - include_str!("valid/hard_example.toml"), - include_str!("valid/hard_example.json")); -test!(example2, - include_str!("valid/example2.toml"), - include_str!("valid/example2.json")); -test!(example3, - include_str!("valid/example-v0.3.0.toml"), - include_str!("valid/example-v0.3.0.json")); -test!(example4, - include_str!("valid/example-v0.4.0.toml"), - include_str!("valid/example-v0.4.0.json")); -test!(example_bom, - include_str!("valid/example-bom.toml"), - include_str!("valid/example.json")); - -test!(datetime_truncate, - include_str!("valid/datetime-truncate.toml"), - include_str!("valid/datetime-truncate.json")); -test!(key_quote_newline, - include_str!("valid/key-quote-newline.toml"), - include_str!("valid/key-quote-newline.json")); -test!(table_array_nest_no_keys, - include_str!("valid/table-array-nest-no-keys.toml"), - include_str!("valid/table-array-nest-no-keys.json")); diff -Nru cargo-0.25.0/vendor/toml-0.4.5/.travis.yml cargo-0.26.0/vendor/toml-0.4.5/.travis.yml --- cargo-0.25.0/vendor/toml-0.4.5/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.5/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,29 +0,0 @@ -language: rust -rust: - - 1.15.0 - - stable - - beta - - nightly -sudo: false -before_script: - - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH -script: - - cargo test - - rustdoc --test README.md -L target - - test "$TRAVIS_RUST_VERSION" != "1.15.0" && cargo doc --no-deps || echo "skipping cargo doc" -after_success: - - travis-cargo --only nightly doc-upload - - travis-cargo coveralls --no-sudo -env: - global: - secure: "IDm3Oc3bmIL4/6zixovwkuTkbinqWnKdLfeuKTtHqT4ZbVy+rxTDQBgLGfVngymjciHWkJnvQ8/2nT3/KW4MPNY9Sqt3NfWvO7vj9cXypeNeJ4xFrVK49F7CMM4KTCeSMlDKR1C0TVYGgxFIViLtBw/imivl9fk6J489eKv36sA=" - -notifications: - email: - on_success: never -addons: - apt: - packages: - - libcurl4-openssl-dev - - libelf-dev - - libdw-dev diff -Nru cargo-0.25.0/vendor/toml-0.4.6/.cargo-checksum.json cargo-0.26.0/vendor/toml-0.4.6/.cargo-checksum.json --- cargo-0.25.0/vendor/toml-0.4.6/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"a0263c6c02c4db6c8f7681f9fd35e90de799ebd4cfdeab77a38f4ff6b3d8c0d9"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/toml-0.4.6/Cargo.toml cargo-0.26.0/vendor/toml-0.4.6/Cargo.toml --- cargo-0.25.0/vendor/toml-0.4.6/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,33 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "toml" +version = "0.4.6" +authors = ["Alex Crichton <alex@alexcrichton.com>"] +description = "A native Rust encoder and decoder of TOML-formatted files and streams. Provides\nimplementations of the standard Serialize/Deserialize traits for TOML data to\nfacilitate deserializing and serializing Rust structures.\n" +homepage = "https://github.com/alexcrichton/toml-rs" +documentation = "https://docs.rs/toml" +readme = "README.md" +keywords = ["encoding"] +categories = ["config", "encoding", "parser-implementations"] +license = "MIT/Apache-2.0" +repository = "https://github.com/alexcrichton/toml-rs" +[dependencies.serde] +version = "1.0" +[dev-dependencies.serde_derive] +version = "1.0" + +[dev-dependencies.serde_json] +version = "1.0" +[badges.travis-ci] +repository = "alexcrichton/toml-rs" diff -Nru cargo-0.25.0/vendor/toml-0.4.6/examples/decode.rs cargo-0.26.0/vendor/toml-0.4.6/examples/decode.rs --- cargo-0.25.0/vendor/toml-0.4.6/examples/decode.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/examples/decode.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,55 @@ +//! An example showing off the usage of `Deserialize` to automatically decode +//! TOML into a Rust `struct` + +#![deny(warnings)] + +extern crate toml; +#[macro_use] +extern crate serde_derive; + +/// This is what we're going to decode into. Each field is optional, meaning +/// that it doesn't have to be present in TOML. +#[derive(Debug, Deserialize)] +struct Config { + global_string: Option<String>, + global_integer: Option<u64>, + server: Option<ServerConfig>, + peers: Option<Vec<PeerConfig>>, +} + +/// Sub-structs are decoded from tables, so this will decode from the `[server]` +/// table. +/// +/// Again, each field is optional, meaning they don't have to be present. +#[derive(Debug, Deserialize)] +struct ServerConfig { + ip: Option<String>, + port: Option<u64>, +} + +#[derive(Debug, Deserialize)] +struct PeerConfig { + ip: Option<String>, + port: Option<u64>, +} + +fn main() { + let toml_str = r#" + global_string = "test" + global_integer = 5 + + [server] + ip = "127.0.0.1" + port = 80 + + [[peers]] + ip = "127.0.0.1" + port = 8080 + + [[peers]] + ip = "127.0.0.1" + "#; + + let decoded: Config = toml::from_str(toml_str).unwrap(); + println!("{:#?}", decoded); +} diff -Nru cargo-0.25.0/vendor/toml-0.4.6/examples/toml2json.rs cargo-0.26.0/vendor/toml-0.4.6/examples/toml2json.rs --- cargo-0.25.0/vendor/toml-0.4.6/examples/toml2json.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/examples/toml2json.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,51 @@ +#![deny(warnings)] + +extern crate toml; +extern crate serde_json; + +use std::fs::File; +use std::env; +use std::io; +use std::io::prelude::*; + +use toml::Value as Toml; +use serde_json::Value as Json; + +fn main() { + let mut args = env::args(); + let mut input = String::new(); + if args.len() > 1 { + let name = args.nth(1).unwrap(); + File::open(&name).and_then(|mut f| { + f.read_to_string(&mut input) + }).unwrap(); + } else { + io::stdin().read_to_string(&mut input).unwrap(); + } + + match input.parse() { + Ok(toml) => { + let json = convert(toml); + println!("{}", serde_json::to_string_pretty(&json).unwrap()); + } + Err(error) => println!("failed to parse TOML: {}", error), + } +} + +fn convert(toml: Toml) -> Json { + match toml { + Toml::String(s) => Json::String(s), + Toml::Integer(i) => Json::Number(i.into()), + Toml::Float(f) => { + let n = serde_json::Number::from_f64(f) + .expect("float infinite and nan not allowed"); + Json::Number(n) + } + Toml::Boolean(b) => Json::Bool(b), + Toml::Array(arr) => Json::Array(arr.into_iter().map(convert).collect()), + Toml::Table(table) => Json::Object(table.into_iter().map(|(k, v)| { + (k, convert(v)) + }).collect()), + Toml::Datetime(dt) => Json::String(dt.to_string()), + } +} diff -Nru cargo-0.25.0/vendor/toml-0.4.6/LICENSE-APACHE cargo-0.26.0/vendor/toml-0.4.6/LICENSE-APACHE --- cargo-0.25.0/vendor/toml-0.4.6/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/toml-0.4.6/LICENSE-MIT cargo-0.26.0/vendor/toml-0.4.6/LICENSE-MIT --- cargo-0.25.0/vendor/toml-0.4.6/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +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. diff -Nru cargo-0.25.0/vendor/toml-0.4.6/README.md cargo-0.26.0/vendor/toml-0.4.6/README.md --- cargo-0.25.0/vendor/toml-0.4.6/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,40 @@ +# toml-rs + +[![Build Status](https://travis-ci.org/alexcrichton/toml-rs.svg?branch=master)](https://travis-ci.org/alexcrichton/toml-rs) +[![Coverage Status](https://coveralls.io/repos/alexcrichton/toml-rs/badge.svg?branch=master&service=github)](https://coveralls.io/github/alexcrichton/toml-rs?branch=master) +[![Latest Version](https://img.shields.io/crates/v/toml.svg)](https://crates.io/crates/toml) +[![Documentation](https://docs.rs/toml/badge.svg)](https://docs.rs/toml) + +A [TOML][toml] decoder and encoder for Rust. This library is currently compliant +with the v0.4.0 version of TOML. This library will also likely continue to stay +up to date with the TOML specification as changes happen. + +[toml]: https://github.com/toml-lang/toml + +```toml +# Cargo.toml +[dependencies] +toml = "0.4" +``` + +This crate also supports serialization/deserialization through the +[serde](https://serde.rs) crate on crates.io. Currently the older `rustc-serialize` +crate is not supported in the 0.3+ series of the `toml` crate, but 0.2 can be +used for that support. + +# License + +This project is 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 toml-rs by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff -Nru cargo-0.25.0/vendor/toml-0.4.6/src/datetime.rs cargo-0.26.0/vendor/toml-0.4.6/src/datetime.rs --- cargo-0.25.0/vendor/toml-0.4.6/src/datetime.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/src/datetime.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,425 @@ +use std::fmt; +use std::str::{self, FromStr}; +use std::error; + +use serde::{de, ser}; + +/// A parsed TOML datetime value +/// +/// This structure is intended to represent the datetime primitive type that can +/// be encoded into TOML documents. This type is a parsed version that contains +/// all metadata internally. +/// +/// Currently this type is intentionally conservative and only supports +/// `to_string` as an accessor. Over time though it's intended that it'll grow +/// more support! +/// +/// Note that if you're using `Deserialize` to deserialize a TOML document, you +/// can use this as a placeholder for where you're expecting a datetime to be +/// specified. +/// +/// Also note though that while this type implements `Serialize` and +/// `Deserialize` it's only recommended to use this type with the TOML format, +/// otherwise encoded in other formats it may look a little odd. +#[derive(PartialEq, Clone)] +pub struct Datetime { + date: Option<Date>, + time: Option<Time>, + offset: Option<Offset>, +} + +/// Error returned from parsing a `Datetime` in the `FromStr` implementation. +#[derive(Debug, Clone)] +pub struct DatetimeParseError { + _private: (), +} + +// Currently serde itself doesn't have a datetime type, so we map our `Datetime` +// to a special valid in the serde data model. Namely one with thiese special +// fields/struct names. +// +// In general the TOML encoder/decoder will catch this and not literally emit +// these strings but rather emit datetimes as they're intended. +pub const SERDE_STRUCT_FIELD_NAME: &'static str = "$__toml_private_datetime"; +pub const SERDE_STRUCT_NAME: &'static str = "$__toml_private_Datetime"; + +#[derive(PartialEq, Clone)] +struct Date { + year: u16, + month: u8, + day: u8, +} + +#[derive(PartialEq, Clone)] +struct Time { + hour: u8, + minute: u8, + second: u8, + nanosecond: u32, +} + +#[derive(PartialEq, Clone)] +enum Offset { + Z, + Custom { hours: i8, minutes: u8 }, +} + +impl fmt::Debug for Datetime { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl fmt::Display for Datetime { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if let Some(ref date) = self.date { + write!(f, "{}", date)?; + } + if let Some(ref time) = self.time { + if self.date.is_some() { + write!(f, "T")?; + } + write!(f, "{}", time)?; + } + if let Some(ref offset) = self.offset { + write!(f, "{}", offset)?; + } + Ok(()) + } +} + +impl fmt::Display for Date { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day) + } +} + +impl fmt::Display for Time { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)?; + if self.nanosecond != 0 { + let s = format!("{:09}", self.nanosecond); + write!(f, ".{}", s.trim_right_matches('0'))?; + } + Ok(()) + } +} + +impl fmt::Display for Offset { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Offset::Z => write!(f, "Z"), + Offset::Custom { hours, minutes } => { + write!(f, "{:+03}:{:02}", hours, minutes) + } + } + } +} + +impl FromStr for Datetime { + type Err = DatetimeParseError; + + fn from_str(date: &str) -> Result<Datetime, DatetimeParseError> { + // Accepted formats: + // + // 0000-00-00T00:00:00.00Z + // 0000-00-00T00:00:00.00 + // 0000-00-00 + // 00:00:00.00 + if date.len() < 3 { + return Err(DatetimeParseError { _private: () }) + } + let mut offset_allowed = true; + let mut chars = date.chars(); + + // First up, parse the full date if we can + let full_date = if chars.clone().nth(2) == Some(':') { + offset_allowed = false; + None + } else { + let y1 = digit(&mut chars)? as u16; + let y2 = digit(&mut chars)? as u16; + let y3 = digit(&mut chars)? as u16; + let y4 = digit(&mut chars)? as u16; + + match chars.next() { + Some('-') => {} + _ => return Err(DatetimeParseError { _private: () }), + } + + let m1 = digit(&mut chars)?; + let m2 = digit(&mut chars)?; + + match chars.next() { + Some('-') => {} + _ => return Err(DatetimeParseError { _private: () }), + } + + let d1 = digit(&mut chars)?; + let d2 = digit(&mut chars)?; + + let date = Date { + year: y1 * 1000 + y2 * 100 + y3 * 10 + y4, + month: m1 * 10 + m2, + day: d1 * 10 + d2, + }; + + if date.month < 1 || date.month > 12 { + return Err(DatetimeParseError { _private: () }) + } + if date.day < 1 || date.day > 31 { + return Err(DatetimeParseError { _private: () }) + } + + Some(date) + }; + + // Next parse the "partial-time" if available + let partial_time = if full_date.is_some() && + chars.clone().next() == Some('T') { + chars.next(); + true + } else { + full_date.is_none() + }; + + let time = if partial_time { + let h1 = digit(&mut chars)?; + let h2 = digit(&mut chars)?; + match chars.next() { + Some(':') => {} + _ => return Err(DatetimeParseError { _private: () }), + } + let m1 = digit(&mut chars)?; + let m2 = digit(&mut chars)?; + match chars.next() { + Some(':') => {} + _ => return Err(DatetimeParseError { _private: () }), + } + let s1 = digit(&mut chars)?; + let s2 = digit(&mut chars)?; + + let mut nanosecond = 0; + if chars.clone().next() == Some('.') { + chars.next(); + let whole = chars.as_str(); + + let mut end = whole.len(); + for (i, byte) in whole.bytes().enumerate() { + match byte { + b'0' ... b'9' => { + if i < 9 { + let p = 10_u32.pow(8 - i as u32); + nanosecond += p * (byte - b'0') as u32; + } + } + _ => { + end = i; + break; + } + } + } + if end == 0 { + return Err(DatetimeParseError { _private: () }) + } + chars = whole[end..].chars(); + } + + let time = Time { + hour: h1 * 10 + h2, + minute: m1 * 10 + m2, + second: s1 * 10 + s2, + nanosecond: nanosecond, + }; + + if time.hour > 24 { + return Err(DatetimeParseError { _private: () }) + } + if time.minute > 59 { + return Err(DatetimeParseError { _private: () }) + } + if time.second > 59 { + return Err(DatetimeParseError { _private: () }) + } + if time.nanosecond > 999_999_999 { + return Err(DatetimeParseError { _private: () }) + } + + Some(time) + } else { + offset_allowed = false; + None + }; + + // And finally, parse the offset + let offset = if offset_allowed { + let next = chars.clone().next(); + if next == Some('Z') { + chars.next(); + Some(Offset::Z) + } else if next.is_none() { + None + } else { + let sign = match next { + Some('+') => 1, + Some('-') => -1, + _ => return Err(DatetimeParseError { _private: () }), + }; + chars.next(); + let h1 = digit(&mut chars)? as i8; + let h2 = digit(&mut chars)? as i8; + match chars.next() { + Some(':') => {} + _ => return Err(DatetimeParseError { _private: () }), + } + let m1 = digit(&mut chars)?; + let m2 = digit(&mut chars)?; + + Some(Offset::Custom { + hours: sign * (h1 * 10 + h2), + minutes: m1 * 10 + m2, + }) + } + } else { + None + }; + + // Return an error if we didn't hit eof, otherwise return our parsed + // date + if chars.next().is_some() { + return Err(DatetimeParseError { _private: () }) + } + + Ok(Datetime { + date: full_date, + time: time, + offset: offset, + }) + } +} + +fn digit(chars: &mut str::Chars) -> Result<u8, DatetimeParseError> { + match chars.next() { + Some(c) if '0' <= c && c <= '9' => Ok(c as u8 - b'0'), + _ => Err(DatetimeParseError { _private: () }), + } +} + +impl ser::Serialize for Datetime { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: ser::Serializer + { + use serde::ser::SerializeStruct; + + let mut s = serializer.serialize_struct(SERDE_STRUCT_NAME, 1)?; + s.serialize_field(SERDE_STRUCT_FIELD_NAME, &self.to_string())?; + s.end() + } +} + +impl<'de> de::Deserialize<'de> for Datetime { + fn deserialize<D>(deserializer: D) -> Result<Datetime, D::Error> + where D: de::Deserializer<'de> + { + struct DatetimeVisitor; + + impl<'de> de::Visitor<'de> for DatetimeVisitor { + type Value = Datetime; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a TOML datetime") + } + + fn visit_map<V>(self, mut visitor: V) -> Result<Datetime, V::Error> + where V: de::MapAccess<'de> + { + let value = visitor.next_key::<DatetimeKey>()?; + if value.is_none() { + return Err(de::Error::custom("datetime key not found")) + } + let v: DatetimeFromString = visitor.next_value()?; + Ok(v.value) + + } + } + + static FIELDS: [&'static str; 1] = [SERDE_STRUCT_FIELD_NAME]; + deserializer.deserialize_struct(SERDE_STRUCT_NAME, + &FIELDS, + DatetimeVisitor) + } +} + +struct DatetimeKey; + +impl<'de> de::Deserialize<'de> for DatetimeKey { + fn deserialize<D>(deserializer: D) -> Result<DatetimeKey, D::Error> + where D: de::Deserializer<'de> + { + struct FieldVisitor; + + impl<'de> de::Visitor<'de> for FieldVisitor { + type Value = (); + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a valid datetime field") + } + + fn visit_str<E>(self, s: &str) -> Result<(), E> + where E: de::Error + { + if s == SERDE_STRUCT_FIELD_NAME { + Ok(()) + } else { + Err(de::Error::custom("expected field with custom name")) + } + } + } + + deserializer.deserialize_identifier(FieldVisitor)?; + Ok(DatetimeKey) + } +} + +pub struct DatetimeFromString { + pub value: Datetime, +} + +impl<'de> de::Deserialize<'de> for DatetimeFromString { + fn deserialize<D>(deserializer: D) -> Result<DatetimeFromString, D::Error> + where D: de::Deserializer<'de> + { + struct Visitor; + + impl<'de> de::Visitor<'de> for Visitor { + type Value = DatetimeFromString; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("string containing a datetime") + } + + fn visit_str<E>(self, s: &str) -> Result<DatetimeFromString, E> + where E: de::Error, + { + match s.parse() { + Ok(date) => Ok(DatetimeFromString { value: date }), + Err(e) => Err(de::Error::custom(e)), + } + } + } + + deserializer.deserialize_str(Visitor) + } +} + +impl fmt::Display for DatetimeParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "failed to parse datetime".fmt(f) + } +} + +impl error::Error for DatetimeParseError { + fn description(&self) -> &str { + "failed to parse datetime" + } +} diff -Nru cargo-0.25.0/vendor/toml-0.4.6/src/de.rs cargo-0.26.0/vendor/toml-0.4.6/src/de.rs --- cargo-0.25.0/vendor/toml-0.4.6/src/de.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/src/de.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1327 @@ +//! Deserializing TOML into Rust structures. +//! +//! This module contains all the Serde support for deserializing TOML documents +//! into Rust structures. Note that some top-level functions here are also +//! provided at the top of the crate. + +use std::borrow::Cow; +use std::error; +use std::fmt; +use std::str; +use std::vec; + +use serde::de; +use serde::de::IntoDeserializer; + +use tokens::{Tokenizer, Token, Error as TokenError}; +use datetime::{SERDE_STRUCT_FIELD_NAME, SERDE_STRUCT_NAME}; + +/// Deserializes a byte slice into a type. +/// +/// This function will attempt to interpret `bytes` as UTF-8 data and then +/// deserialize `T` from the TOML document provided. +pub fn from_slice<'de, T>(bytes: &'de [u8]) -> Result<T, Error> + where T: de::Deserialize<'de>, +{ + match str::from_utf8(bytes) { + Ok(s) => from_str(s), + Err(e) => Err(Error::custom(e.to_string())), + } +} + +/// Deserializes a string into a type. +/// +/// This function will attempt to interpret `s` as a TOML document and +/// deserialize `T` from the document. +/// +/// # Examples +/// +/// ``` +/// #[macro_use] +/// extern crate serde_derive; +/// extern crate toml; +/// +/// #[derive(Deserialize)] +/// struct Config { +/// title: String, +/// owner: Owner, +/// } +/// +/// #[derive(Deserialize)] +/// struct Owner { +/// name: String, +/// } +/// +/// fn main() { +/// let config: Config = toml::from_str(r#" +/// title = 'TOML Example' +/// +/// [owner] +/// name = 'Lisa' +/// "#).unwrap(); +/// +/// assert_eq!(config.title, "TOML Example"); +/// assert_eq!(config.owner.name, "Lisa"); +/// } +/// ``` +pub fn from_str<'de, T>(s: &'de str) -> Result<T, Error> + where T: de::Deserialize<'de>, +{ + let mut d = Deserializer::new(s); + let ret = T::deserialize(&mut d)?; + d.end()?; + Ok(ret) +} + +/// Errors that can occur when deserializing a type. +#[derive(Debug, Clone)] +pub struct Error { + inner: Box<ErrorInner>, +} + +#[derive(Debug, Clone)] +struct ErrorInner { + kind: ErrorKind, + line: Option<usize>, + col: usize, + message: String, + key: Vec<String>, +} + +/// Errors that can occur when deserializing a type. +#[derive(Debug, Clone)] +enum ErrorKind { + /// EOF was reached when looking for a value + UnexpectedEof, + + /// An invalid character not allowed in a string was found + InvalidCharInString(char), + + /// An invalid character was found as an escape + InvalidEscape(char), + + /// An invalid character was found in a hex escape + InvalidHexEscape(char), + + /// An invalid escape value was specified in a hex escape in a string. + /// + /// Valid values are in the plane of unicode codepoints. + InvalidEscapeValue(u32), + + /// A newline in a string was encountered when one was not allowed. + NewlineInString, + + /// An unexpected character was encountered, typically when looking for a + /// value. + Unexpected(char), + + /// An unterminated string was found where EOF was found before the ending + /// EOF mark. + UnterminatedString, + + /// A newline was found in a table key. + NewlineInTableKey, + + /// A number failed to parse + NumberInvalid, + + /// A date or datetime was invalid + DateInvalid, + + /// Wanted one sort of token, but found another. + Wanted { + /// Expected token type + expected: &'static str, + /// Actually found token type + found: &'static str, + }, + + /// An array was decoded but the types inside of it were mixed, which is + /// disallowed by TOML. + MixedArrayType, + + /// A duplicate table definition was found. + DuplicateTable(String), + + /// A previously defined table was redefined as an array. + RedefineAsArray, + + /// An empty table key was found. + EmptyTableKey, + + /// A custom error which could be generated when deserializing a particular + /// type. + Custom, + + /// A struct was expected but something else was found + ExpectedString, + + #[doc(hidden)] + __Nonexhaustive, +} + +/// Deserialization implementation for TOML. +pub struct Deserializer<'a> { + require_newline_after_table: bool, + input: &'a str, + tokens: Tokenizer<'a>, +} + +impl<'de, 'b> de::Deserializer<'de> for &'b mut Deserializer<'de> { + type Error = Error; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor<'de>, + { + let mut tables = Vec::new(); + let mut cur_table = Table { + at: 0, + header: Vec::new(), + values: None, + array: false, + }; + + while let Some(line) = self.line()? { + match line { + Line::Table { at, mut header, array } => { + if !cur_table.header.is_empty() || cur_table.values.is_some() { + tables.push(cur_table); + } + cur_table = Table { + at: at, + header: Vec::new(), + values: Some(Vec::new()), + array: array, + }; + loop { + let part = header.next().map_err(|e| { + self.token_error(e) + }); + match part? { + Some(part) => cur_table.header.push(part), + None => break, + } + } + } + Line::KeyValue(key, value) => { + if cur_table.values.is_none() { + cur_table.values = Some(Vec::new()); + } + cur_table.values.as_mut().unwrap().push((key, value)); + } + } + } + if !cur_table.header.is_empty() || cur_table.values.is_some() { + tables.push(cur_table); + } + + visitor.visit_map(MapVisitor { + values: Vec::new().into_iter(), + next_value: None, + depth: 0, + cur: 0, + cur_parent: 0, + max: tables.len(), + tables: &mut tables, + array: false, + de: self, + }) + } + + fn deserialize_enum<V>( + self, + _name: &'static str, + _variants: &'static [&'static str], + visitor: V + ) -> Result<V::Value, Error> + where V: de::Visitor<'de> + { + if let Some(next) = self.next()? { + match next { + Token::String { val, .. } => { + visitor.visit_enum(val.into_deserializer()) + }, + _ => Err(Error::from_kind(ErrorKind::ExpectedString)) + } + } else { + Err(Error::from_kind(ErrorKind::UnexpectedEof)) + } + } + + forward_to_deserialize_any! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq + bytes byte_buf map struct unit newtype_struct + ignored_any unit_struct tuple_struct tuple option identifier + } +} + +struct Table<'a> { + at: usize, + header: Vec<Cow<'a, str>>, + values: Option<Vec<(Cow<'a, str>, Value<'a>)>>, + array: bool, +} + +#[doc(hidden)] +pub struct MapVisitor<'de: 'b, 'b> { + values: vec::IntoIter<(Cow<'de, str>, Value<'de>)>, + next_value: Option<(Cow<'de, str>, Value<'de>)>, + depth: usize, + cur: usize, + cur_parent: usize, + max: usize, + tables: &'b mut [Table<'de>], + array: bool, + de: &'b mut Deserializer<'de>, +} + +impl<'de, 'b> de::MapAccess<'de> for MapVisitor<'de, 'b> { + type Error = Error; + + fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> + where K: de::DeserializeSeed<'de>, + { + if self.cur_parent == self.max || self.cur == self.max { + return Ok(None) + } + + loop { + assert!(self.next_value.is_none()); + if let Some((key, value)) = self.values.next() { + let ret = seed.deserialize(StrDeserializer::new(key.clone()))?; + self.next_value = Some((key, value)); + return Ok(Some(ret)) + } + + let next_table = { + let prefix = &self.tables[self.cur_parent].header[..self.depth]; + self.tables[self.cur..self.max].iter().enumerate().find(|&(_, t)| { + if t.values.is_none() { + return false + } + match t.header.get(..self.depth) { + Some(header) => header == prefix, + None => false, + } + }).map(|(i, _)| i + self.cur) + }; + + let pos = match next_table { + Some(pos) => pos, + None => return Ok(None), + }; + self.cur = pos; + + // Test to see if we're duplicating our parent's table, and if so + // then this is an error in the toml format + if self.cur_parent != pos && + self.tables[self.cur_parent].header == self.tables[pos].header { + let at = self.tables[pos].at; + let name = self.tables[pos].header.join("."); + return Err(self.de.error(at, ErrorKind::DuplicateTable(name))) + } + + let table = &mut self.tables[pos]; + + // If we're not yet at the appropriate depth for this table then we + // just next the next portion of its header and then continue + // decoding. + if self.depth != table.header.len() { + let key = &table.header[self.depth]; + let key = seed.deserialize(StrDeserializer::new(key.clone()))?; + return Ok(Some(key)) + } + + // Rule out cases like: + // + // [[foo.bar]] + // [[foo]] + if table.array { + let kind = ErrorKind::RedefineAsArray; + return Err(self.de.error(table.at, kind)) + } + + self.values = table.values.take().expect("Unable to read table values").into_iter(); + } + } + + fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> + where V: de::DeserializeSeed<'de>, + { + if let Some((k, v)) = self.next_value.take() { + match seed.deserialize(ValueDeserializer::new(v)) { + Ok(v) => return Ok(v), + Err(mut e) => { + e.add_key_context(&k); + return Err(e) + } + } + } + + let array = self.tables[self.cur].array && + self.depth == self.tables[self.cur].header.len() - 1; + self.cur += 1; + let res = seed.deserialize(MapVisitor { + values: Vec::new().into_iter(), + next_value: None, + depth: self.depth + if array {0} else {1}, + cur_parent: self.cur - 1, + cur: 0, + max: self.max, + array: array, + tables: &mut *self.tables, + de: &mut *self.de, + }); + res.map_err(|mut e| { + e.add_key_context(&self.tables[self.cur - 1].header[self.depth]); + e + }) + } +} + +impl<'de, 'b> de::SeqAccess<'de> for MapVisitor<'de, 'b> { + type Error = Error; + + fn next_element_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> + where K: de::DeserializeSeed<'de>, + { + assert!(self.next_value.is_none()); + assert!(self.values.next().is_none()); + + if self.cur_parent == self.max { + return Ok(None) + } + + let next = self.tables[..self.max] + .iter() + .enumerate() + .skip(self.cur_parent + 1) + .find(|&(_, table)| { + table.array && table.header == self.tables[self.cur_parent].header + }).map(|p| p.0) + .unwrap_or(self.max); + + let ret = seed.deserialize(MapVisitor { + values: self.tables[self.cur_parent].values.take().expect("Unable to read table values").into_iter(), + next_value: None, + depth: self.depth + 1, + cur_parent: self.cur_parent, + max: next, + cur: 0, + array: false, + tables: &mut self.tables, + de: &mut self.de, + })?; + self.cur_parent = next; + Ok(Some(ret)) + } +} + +impl<'de, 'b> de::Deserializer<'de> for MapVisitor<'de, 'b> { + type Error = Error; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor<'de>, + { + if self.array { + visitor.visit_seq(self) + } else { + visitor.visit_map(self) + } + } + + // `None` is interpreted as a missing field so be sure to implement `Some` + // as a present field. + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor<'de>, + { + visitor.visit_some(self) + } + + fn deserialize_newtype_struct<V>( + self, + _name: &'static str, + visitor: V + ) -> Result<V::Value, Error> + where V: de::Visitor<'de> + { + visitor.visit_newtype_struct(self) + } + + forward_to_deserialize_any! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq + bytes byte_buf map struct unit identifier + ignored_any unit_struct tuple_struct tuple enum + } +} + +struct StrDeserializer<'a> { + key: Cow<'a, str>, +} + +impl<'a> StrDeserializer<'a> { + fn new(key: Cow<'a, str>) -> StrDeserializer<'a> { + StrDeserializer { + key: key, + } + } +} + +impl<'de> de::Deserializer<'de> for StrDeserializer<'de> { + type Error = Error; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor<'de>, + { + match self.key { + Cow::Borrowed(s) => visitor.visit_borrowed_str(s), + Cow::Owned(s) => visitor.visit_string(s), + } + } + + forward_to_deserialize_any! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq + bytes byte_buf map struct option unit newtype_struct + ignored_any unit_struct tuple_struct tuple enum identifier + } +} + +struct ValueDeserializer<'a> { + value: Value<'a>, +} + +impl<'a> ValueDeserializer<'a> { + fn new(value: Value<'a>) -> ValueDeserializer<'a> { + ValueDeserializer { + value: value, + } + } +} + +impl<'de> de::Deserializer<'de> for ValueDeserializer<'de> { + type Error = Error; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor<'de>, + { + match self.value { + Value::Integer(i) => visitor.visit_i64(i), + Value::Boolean(b) => visitor.visit_bool(b), + Value::Float(f) => visitor.visit_f64(f), + Value::String(Cow::Borrowed(s)) => visitor.visit_borrowed_str(s), + Value::String(Cow::Owned(s)) => visitor.visit_string(s), + Value::Datetime(s) => visitor.visit_map(DatetimeDeserializer { + date: s, + visited: false, + }), + Value::Array(values) => { + let mut s = de::value::SeqDeserializer::new(values.into_iter()); + let ret = visitor.visit_seq(&mut s)?; + s.end()?; + Ok(ret) + } + Value::InlineTable(values) => { + visitor.visit_map(InlineTableDeserializer { + values: values.into_iter(), + next_value: None, + }) + } + } + } + + fn deserialize_struct<V>(self, + name: &'static str, + fields: &'static [&'static str], + visitor: V) -> Result<V::Value, Error> + where V: de::Visitor<'de>, + { + if name == SERDE_STRUCT_NAME && fields == &[SERDE_STRUCT_FIELD_NAME] { + if let Value::Datetime(s) = self.value { + return visitor.visit_map(DatetimeDeserializer { + date: s, + visited: false, + }) + } + } + + self.deserialize_any(visitor) + } + + // `None` is interpreted as a missing field so be sure to implement `Some` + // as a present field. + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor<'de>, + { + visitor.visit_some(self) + } + + fn deserialize_enum<V>( + self, + _name: &'static str, + _variants: &'static [&'static str], + visitor: V + ) -> Result<V::Value, Error> + where V: de::Visitor<'de> + { + match self.value { + Value::String(val) => visitor.visit_enum(val.into_deserializer()), + _ => Err(Error::from_kind(ErrorKind::ExpectedString)) + } + } + + fn deserialize_newtype_struct<V>( + self, + _name: &'static str, + visitor: V + ) -> Result<V::Value, Error> + where V: de::Visitor<'de> + { + visitor.visit_newtype_struct(self) + } + + forward_to_deserialize_any! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq + bytes byte_buf map unit identifier + ignored_any unit_struct tuple_struct tuple + } +} + +impl<'de> de::IntoDeserializer<'de, Error> for Value<'de> { + type Deserializer = ValueDeserializer<'de>; + + fn into_deserializer(self) -> Self::Deserializer { + ValueDeserializer::new(self) + } +} + +struct DatetimeDeserializer<'a> { + visited: bool, + date: &'a str, +} + +impl<'de> de::MapAccess<'de> for DatetimeDeserializer<'de> { + type Error = Error; + + fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> + where K: de::DeserializeSeed<'de>, + { + if self.visited { + return Ok(None) + } + self.visited = true; + seed.deserialize(DatetimeFieldDeserializer).map(Some) + } + + fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> + where V: de::DeserializeSeed<'de>, + { + seed.deserialize(StrDeserializer::new(self.date.into())) + } +} + +struct DatetimeFieldDeserializer; + +impl<'de> de::Deserializer<'de> for DatetimeFieldDeserializer { + type Error = Error; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, Error> + where V: de::Visitor<'de>, + { + visitor.visit_borrowed_str(SERDE_STRUCT_FIELD_NAME) + } + + forward_to_deserialize_any! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string seq + bytes byte_buf map struct option unit newtype_struct + ignored_any unit_struct tuple_struct tuple enum identifier + } +} + +struct InlineTableDeserializer<'a> { + values: vec::IntoIter<(Cow<'a, str>, Value<'a>)>, + next_value: Option<Value<'a>>, +} + +impl<'de> de::MapAccess<'de> for InlineTableDeserializer<'de> { + type Error = Error; + + fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Error> + where K: de::DeserializeSeed<'de>, + { + let (key, value) = match self.values.next() { + Some(pair) => pair, + None => return Ok(None), + }; + self.next_value = Some(value); + seed.deserialize(StrDeserializer::new(key)).map(Some) + } + + fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Error> + where V: de::DeserializeSeed<'de>, + { + let value = self.next_value.take().expect("Unable to read table values"); + seed.deserialize(ValueDeserializer::new(value)) + } +} + + +impl<'a> Deserializer<'a> { + /// Creates a new deserializer which will be deserializing the string + /// provided. + pub fn new(input: &'a str) -> Deserializer<'a> { + Deserializer { + tokens: Tokenizer::new(input), + input: input, + require_newline_after_table: true, + } + } + + /// The `Deserializer::end` method should be called after a value has been + /// fully deserialized. This allows the `Deserializer` to validate that the + /// input stream is at the end or that it only has trailing + /// whitespace/comments. + pub fn end(&mut self) -> Result<(), Error> { + Ok(()) + } + + /// Historical versions of toml-rs accidentally allowed a newline after a + /// table definition, but the TOML spec requires a newline after a table + /// definition header. + /// + /// This option can be set to `false` (the default is `true`) to emulate + /// this behavior for backwards compatibility with older toml-rs versions. + pub fn set_require_newline_after_table(&mut self, require: bool) { + self.require_newline_after_table = require; + } + + fn line(&mut self) -> Result<Option<Line<'a>>, Error> { + loop { + self.eat_whitespace()?; + if self.eat_comment()? { + continue + } + if self.eat(Token::Newline)? { + continue + } + break + } + + match self.peek()? { + Some(Token::LeftBracket) => self.table_header().map(Some), + Some(_) => self.key_value().map(Some), + None => Ok(None), + } + } + + fn table_header(&mut self) -> Result<Line<'a>, Error> { + let start = self.tokens.current(); + self.expect(Token::LeftBracket)?; + let array = self.eat(Token::LeftBracket)?; + let ret = Header::new(self.tokens.clone(), + array, + self.require_newline_after_table); + if self.require_newline_after_table { + self.tokens.skip_to_newline(); + } else { + loop { + match self.next()? { + Some(Token::RightBracket) => { + if array { + self.eat(Token::RightBracket)?; + } + break + } + Some(Token::Newline) | + None => break, + _ => {} + } + } + self.eat_whitespace()?; + } + Ok(Line::Table { at: start, header: ret, array: array }) + } + + fn key_value(&mut self) -> Result<Line<'a>, Error> { + let key = self.table_key()?; + self.eat_whitespace()?; + self.expect(Token::Equals)?; + self.eat_whitespace()?; + + let value = self.value()?; + self.eat_whitespace()?; + if !self.eat_comment()? { + self.eat_newline_or_eof()?; + } + + Ok(Line::KeyValue(key, value)) + } + + fn value(&mut self) -> Result<Value<'a>, Error> { + let at = self.tokens.current(); + let value = match self.next()? { + Some(Token::String { val, .. }) => Value::String(val), + Some(Token::Keylike("true")) => Value::Boolean(true), + Some(Token::Keylike("false")) => Value::Boolean(false), + Some(Token::Keylike(key)) => self.number_or_date(key)?, + Some(Token::Plus) => self.number_leading_plus()?, + Some(Token::LeftBrace) => self.inline_table().map(Value::InlineTable)?, + Some(Token::LeftBracket) => self.array().map(Value::Array)?, + Some(token) => { + return Err(self.error(at, ErrorKind::Wanted { + expected: "a value", + found: token.describe(), + })) + } + None => return Err(self.eof()), + }; + Ok(value) + } + + fn number_or_date(&mut self, s: &'a str) -> Result<Value<'a>, Error> { + if s.contains('T') || (s.len() > 1 && s[1..].contains('-')) && + !s.contains("e-") { + self.datetime(s, false).map(Value::Datetime) + } else if self.eat(Token::Colon)? { + self.datetime(s, true).map(Value::Datetime) + } else { + self.number(s) + } + } + + fn number(&mut self, s: &'a str) -> Result<Value<'a>, Error> { + if s.contains('e') || s.contains('E') { + self.float(s, None).map(Value::Float) + } else if self.eat(Token::Period)? { + let at = self.tokens.current(); + match self.next()? { + Some(Token::Keylike(after)) => { + self.float(s, Some(after)).map(Value::Float) + } + _ => Err(self.error(at, ErrorKind::NumberInvalid)), + } + } else { + self.integer(s).map(Value::Integer) + } + } + + fn number_leading_plus(&mut self) -> Result<Value<'a>, Error> { + let start = self.tokens.current(); + match self.next()? { + Some(Token::Keylike(s)) => self.number(s), + _ => Err(self.error(start, ErrorKind::NumberInvalid)), + } + } + + fn integer(&self, s: &'a str) -> Result<i64, Error> { + let (prefix, suffix) = self.parse_integer(s, true, false)?; + let start = self.tokens.substr_offset(s); + if suffix != "" { + return Err(self.error(start, ErrorKind::NumberInvalid)) + } + prefix.replace("_", "").trim_left_matches('+').parse().map_err(|_e| { + self.error(start, ErrorKind::NumberInvalid) + }) + } + + fn parse_integer(&self, + s: &'a str, + allow_sign: bool, + allow_leading_zeros: bool) + -> Result<(&'a str, &'a str), Error> { + let start = self.tokens.substr_offset(s); + + let mut first = true; + let mut first_zero = false; + let mut underscore = false; + let mut end = s.len(); + for (i, c) in s.char_indices() { + let at = i + start; + if i == 0 && (c == '+' || c == '-') && allow_sign { + continue + } + + match c { + '0' if first => first_zero = true, + '0' ... '9' if !first && first_zero && !allow_leading_zeros => { + return Err(self.error(at, ErrorKind::NumberInvalid)) + } + '0' ... '9' => underscore = false, + '_' if first => { + return Err(self.error(at, ErrorKind::NumberInvalid)) + } + '_' if !underscore => underscore = true, + _ => { + end = i; + break + } + + } + first = false; + } + if first || underscore { + return Err(self.error(start, ErrorKind::NumberInvalid)) + } + Ok((&s[..end], &s[end..])) + } + + fn float(&mut self, s: &'a str, after_decimal: Option<&'a str>) + -> Result<f64, Error> { + let (integral, mut suffix) = self.parse_integer(s, true, false)?; + let start = self.tokens.substr_offset(integral); + + let mut fraction = None; + if let Some(after) = after_decimal { + if suffix != "" { + return Err(self.error(start, ErrorKind::NumberInvalid)) + } + let (a, b) = self.parse_integer(after, false, true)?; + fraction = Some(a); + suffix = b; + } + + let mut exponent = None; + if suffix.starts_with('e') || suffix.starts_with('E') { + let (a, b) = if suffix.len() == 1 { + self.eat(Token::Plus)?; + match self.next()? { + Some(Token::Keylike(s)) => { + self.parse_integer(s, false, false)? + } + _ => return Err(self.error(start, ErrorKind::NumberInvalid)), + } + } else { + self.parse_integer(&suffix[1..], true, false)? + }; + if b != "" { + return Err(self.error(start, ErrorKind::NumberInvalid)) + } + exponent = Some(a); + } + + let mut number = integral.trim_left_matches('+') + .chars() + .filter(|c| *c != '_') + .collect::<String>(); + if let Some(fraction) = fraction { + number.push_str("."); + number.extend(fraction.chars().filter(|c| *c != '_')); + } + if let Some(exponent) = exponent { + number.push_str("E"); + number.extend(exponent.chars().filter(|c| *c != '_')); + } + number.parse().map_err(|_e| { + self.error(start, ErrorKind::NumberInvalid) + }).and_then(|n: f64| { + if n.is_finite() { + Ok(n) + } else { + Err(self.error(start, ErrorKind::NumberInvalid)) + } + }) + } + + fn datetime(&mut self, date: &'a str, colon_eaten: bool) + -> Result<&'a str, Error> { + let start = self.tokens.substr_offset(date); + if colon_eaten || self.eat(Token::Colon)? { + // minutes + match self.next()? { + Some(Token::Keylike(_)) => {} + _ => return Err(self.error(start, ErrorKind::DateInvalid)), + } + // Seconds + self.expect(Token::Colon)?; + match self.next()? { + Some(Token::Keylike(_)) => {} + _ => return Err(self.error(start, ErrorKind::DateInvalid)), + } + // Fractional seconds + if self.eat(Token::Period)? { + match self.next()? { + Some(Token::Keylike(_)) => {} + _ => return Err(self.error(start, ErrorKind::DateInvalid)), + } + } + + // offset + if self.eat(Token::Plus)? { + match self.next()? { + Some(Token::Keylike(_)) => {} + _ => return Err(self.error(start, ErrorKind::DateInvalid)), + } + } + if self.eat(Token::Colon)? { + match self.next()? { + Some(Token::Keylike(_)) => {} + _ => return Err(self.error(start, ErrorKind::DateInvalid)), + } + } + } + let end = self.tokens.current(); + Ok(&self.tokens.input()[start..end]) + } + + // TODO(#140): shouldn't buffer up this entire table in memory, it'd be + // great to defer parsing everything until later. + fn inline_table(&mut self) -> Result<Vec<(Cow<'a, str>, Value<'a>)>, Error> { + let mut ret = Vec::new(); + self.eat_whitespace()?; + if self.eat(Token::RightBrace)? { + return Ok(ret) + } + loop { + let key = self.table_key()?; + self.eat_whitespace()?; + self.expect(Token::Equals)?; + self.eat_whitespace()?; + ret.push((key, self.value()?)); + + self.eat_whitespace()?; + if self.eat(Token::RightBrace)? { + return Ok(ret) + } + self.expect(Token::Comma)?; + self.eat_whitespace()?; + } + } + + // TODO(#140): shouldn't buffer up this entire array in memory, it'd be + // great to defer parsing everything until later. + fn array(&mut self) -> Result<Vec<Value<'a>>, Error> { + let mut ret = Vec::new(); + + let intermediate = |me: &mut Deserializer| { + loop { + me.eat_whitespace()?; + if !me.eat(Token::Newline)? && !me.eat_comment()? { + break + } + } + Ok(()) + }; + + loop { + intermediate(self)?; + if self.eat(Token::RightBracket)? { + return Ok(ret) + } + let at = self.tokens.current(); + let value = self.value()?; + if let Some(last) = ret.last() { + if !value.same_type(last) { + return Err(self.error(at, ErrorKind::MixedArrayType)) + } + } + ret.push(value); + intermediate(self)?; + if !self.eat(Token::Comma)? { + break + } + } + intermediate(self)?; + self.expect(Token::RightBracket)?; + Ok(ret) + } + + fn table_key(&mut self) -> Result<Cow<'a, str>, Error> { + self.tokens.table_key().map_err(|e| self.token_error(e)) + } + + fn eat_whitespace(&mut self) -> Result<(), Error> { + self.tokens.eat_whitespace().map_err(|e| self.token_error(e)) + } + + fn eat_comment(&mut self) -> Result<bool, Error> { + self.tokens.eat_comment().map_err(|e| self.token_error(e)) + } + + fn eat_newline_or_eof(&mut self) -> Result<(), Error> { + self.tokens.eat_newline_or_eof().map_err(|e| self.token_error(e)) + } + + fn eat(&mut self, expected: Token<'a>) -> Result<bool, Error> { + self.tokens.eat(expected).map_err(|e| self.token_error(e)) + } + + fn expect(&mut self, expected: Token<'a>) -> Result<(), Error> { + self.tokens.expect(expected).map_err(|e| self.token_error(e)) + } + + fn next(&mut self) -> Result<Option<Token<'a>>, Error> { + self.tokens.next().map_err(|e| self.token_error(e)) + } + + fn peek(&mut self) -> Result<Option<Token<'a>>, Error> { + self.tokens.peek().map_err(|e| self.token_error(e)) + } + + fn eof(&self) -> Error { + self.error(self.input.len(), ErrorKind::UnexpectedEof) + } + + fn token_error(&self, error: TokenError) -> Error { + match error { + TokenError::InvalidCharInString(at, ch) => { + self.error(at, ErrorKind::InvalidCharInString(ch)) + } + TokenError::InvalidEscape(at, ch) => { + self.error(at, ErrorKind::InvalidEscape(ch)) + } + TokenError::InvalidEscapeValue(at, v) => { + self.error(at, ErrorKind::InvalidEscapeValue(v)) + } + TokenError::InvalidHexEscape(at, ch) => { + self.error(at, ErrorKind::InvalidHexEscape(ch)) + } + TokenError::NewlineInString(at) => { + self.error(at, ErrorKind::NewlineInString) + } + TokenError::Unexpected(at, ch) => { + self.error(at, ErrorKind::Unexpected(ch)) + } + TokenError::UnterminatedString(at) => { + self.error(at, ErrorKind::UnterminatedString) + } + TokenError::NewlineInTableKey(at) => { + self.error(at, ErrorKind::NewlineInTableKey) + } + TokenError::Wanted { at, expected, found } => { + self.error(at, ErrorKind::Wanted { expected: expected, found: found }) + } + TokenError::EmptyTableKey(at) => { + self.error(at, ErrorKind::EmptyTableKey) + } + } + } + + fn error(&self, at: usize, kind: ErrorKind) -> Error { + let mut err = Error::from_kind(kind); + let (line, col) = self.to_linecol(at); + err.inner.line = Some(line); + err.inner.col = col; + err + } + + /// Converts a byte offset from an error message to a (line, column) pair + /// + /// All indexes are 0-based. + fn to_linecol(&self, offset: usize) -> (usize, usize) { + let mut cur = 0; + for (i, line) in self.input.lines().enumerate() { + if cur + line.len() + 1 > offset { + return (i, offset - cur) + } + cur += line.len() + 1; + } + (self.input.lines().count(), 0) + } +} + +impl Error { + /// Produces a (line, column) pair of the position of the error if available + /// + /// All indexes are 0-based. + pub fn line_col(&self) -> Option<(usize, usize)> { + self.inner.line.map(|line| (line, self.inner.col)) + } + + fn from_kind(kind: ErrorKind) -> Error { + Error { + inner: Box::new(ErrorInner { + kind: kind, + line: None, + col: 0, + message: String::new(), + key: Vec::new(), + }), + } + } + + fn custom(s: String) -> Error { + Error { + inner: Box::new(ErrorInner { + kind: ErrorKind::Custom, + line: None, + col: 0, + message: s, + key: Vec::new(), + }), + } + } + + /// Do not call this method, it may be removed at any time, it's just an + /// internal implementation detail. + #[doc(hidden)] + pub fn add_key_context(&mut self, key: &str) { + self.inner.key.insert(0, key.to_string()); + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.inner.kind { + ErrorKind::UnexpectedEof => "unexpected eof encountered".fmt(f)?, + ErrorKind::InvalidCharInString(c) => { + write!(f, "invalid character in string: `{}`", + c.escape_default().collect::<String>())? + } + ErrorKind::InvalidEscape(c) => { + write!(f, "invalid escape character in string: `{}`", + c.escape_default().collect::<String>())? + } + ErrorKind::InvalidHexEscape(c) => { + write!(f, "invalid hex escape character in string: `{}`", + c.escape_default().collect::<String>())? + } + ErrorKind::InvalidEscapeValue(c) => { + write!(f, "invalid escape value: `{}`", c)? + } + ErrorKind::NewlineInString => "newline in string found".fmt(f)?, + ErrorKind::Unexpected(ch) => { + write!(f, "unexpected character found: `{}`", + ch.escape_default().collect::<String>())? + } + ErrorKind::UnterminatedString => "unterminated string".fmt(f)?, + ErrorKind::NewlineInTableKey => "found newline in table key".fmt(f)?, + ErrorKind::Wanted { expected, found } => { + write!(f, "expected {}, found {}", expected, found)? + } + ErrorKind::NumberInvalid => "invalid number".fmt(f)?, + ErrorKind::DateInvalid => "invalid date".fmt(f)?, + ErrorKind::MixedArrayType => "mixed types in an array".fmt(f)?, + ErrorKind::DuplicateTable(ref s) => { + write!(f, "redefinition of table `{}`", s)?; + } + ErrorKind::RedefineAsArray => "table redefined as array".fmt(f)?, + ErrorKind::EmptyTableKey => "empty table key found".fmt(f)?, + ErrorKind::Custom => self.inner.message.fmt(f)?, + ErrorKind::ExpectedString => "expected string".fmt(f)?, + ErrorKind::__Nonexhaustive => panic!(), + } + + if !self.inner.key.is_empty() { + write!(f, " for key `")?; + for (i, k) in self.inner.key.iter().enumerate() { + if i > 0 { + write!(f, ".")?; + } + write!(f, "{}", k)?; + } + write!(f, "`")?; + } + + if let Some(line) = self.inner.line { + write!(f, " at line {}", line + 1)?; + } + + Ok(()) + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match self.inner.kind { + ErrorKind::UnexpectedEof => "unexpected eof encountered", + ErrorKind::InvalidCharInString(_) => "invalid char in string", + ErrorKind::InvalidEscape(_) => "invalid escape in string", + ErrorKind::InvalidHexEscape(_) => "invalid hex escape in string", + ErrorKind::InvalidEscapeValue(_) => "invalid escape value in string", + ErrorKind::NewlineInString => "newline in string found", + ErrorKind::Unexpected(_) => "unexpected or invalid character", + ErrorKind::UnterminatedString => "unterminated string", + ErrorKind::NewlineInTableKey => "found newline in table key", + ErrorKind::Wanted { .. } => "expected a token but found another", + ErrorKind::NumberInvalid => "invalid number", + ErrorKind::DateInvalid => "invalid date", + ErrorKind::MixedArrayType => "mixed types in an array", + ErrorKind::DuplicateTable(_) => "duplicate table", + ErrorKind::RedefineAsArray => "table redefined as array", + ErrorKind::EmptyTableKey => "empty table key found", + ErrorKind::Custom => "a custom error", + ErrorKind::ExpectedString => "expected string", + ErrorKind::__Nonexhaustive => panic!(), + } + } +} + +impl de::Error for Error { + fn custom<T: fmt::Display>(msg: T) -> Error { + Error::custom(msg.to_string()) + } +} + +enum Line<'a> { + Table { at: usize, header: Header<'a>, array: bool }, + KeyValue(Cow<'a, str>, Value<'a>), +} + +struct Header<'a> { + first: bool, + array: bool, + require_newline_after_table: bool, + tokens: Tokenizer<'a>, +} + +impl<'a> Header<'a> { + fn new(tokens: Tokenizer<'a>, + array: bool, + require_newline_after_table: bool) -> Header<'a> { + Header { + first: true, + array: array, + tokens: tokens, + require_newline_after_table: require_newline_after_table, + } + } + + fn next(&mut self) -> Result<Option<Cow<'a, str>>, TokenError> { + self.tokens.eat_whitespace()?; + + if self.first || self.tokens.eat(Token::Period)? { + self.first = false; + self.tokens.eat_whitespace()?; + self.tokens.table_key().map(Some) + } else { + self.tokens.expect(Token::RightBracket)?; + if self.array { + self.tokens.expect(Token::RightBracket)?; + } + + self.tokens.eat_whitespace()?; + if self.require_newline_after_table { + if !self.tokens.eat_comment()? { + self.tokens.eat_newline_or_eof()?; + } + } + Ok(None) + } + } +} + +#[derive(Debug)] +enum Value<'a> { + Integer(i64), + Float(f64), + Boolean(bool), + String(Cow<'a, str>), + Datetime(&'a str), + Array(Vec<Value<'a>>), + InlineTable(Vec<(Cow<'a, str>, Value<'a>)>), +} + +impl<'a> Value<'a> { + fn same_type(&self, other: &Value<'a>) -> bool { + match (self, other) { + (&Value::String(..), &Value::String(..)) | + (&Value::Integer(..), &Value::Integer(..)) | + (&Value::Float(..), &Value::Float(..)) | + (&Value::Boolean(..), &Value::Boolean(..)) | + (&Value::Datetime(..), &Value::Datetime(..)) | + (&Value::Array(..), &Value::Array(..)) | + (&Value::InlineTable(..), &Value::InlineTable(..)) => true, + + _ => false, + } + } +} diff -Nru cargo-0.25.0/vendor/toml-0.4.6/src/lib.rs cargo-0.26.0/vendor/toml-0.4.6/src/lib.rs --- cargo-0.25.0/vendor/toml-0.4.6/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,171 @@ +//! A [TOML]-parsing library +//! +//! This library implements a [TOML] v0.4.0 compatible parser, +//! primarily supporting the [`serde`] library for encoding/decoding +//! various types in Rust. +//! +//! TOML itself is a simple, ergonomic, and readable configuration format: +//! +//! ```toml +//! [package] +//! name = "toml" +//! version = "0.4.2" +//! authors = ["Alex Crichton <alex@alexcrichton.com>"] +//! +//! [dependencies] +//! serde = "1.0" +//! ``` +//! +//! The TOML format tends to be relatively common throughout the Rust community +//! for configuration, notably being used by [Cargo], Rust's package manager. +//! +//! ## TOML values +//! +//! A value in TOML is represented with the `Value` enum in this crate: +//! +//! ```rust,ignore +//! pub enum Value { +//! String(String), +//! Integer(i64), +//! Float(f64), +//! Boolean(bool), +//! Datetime(Datetime), +//! Array(Array), +//! Table(Table), +//! } +//! ``` +//! +//! TOML is similar to JSON with the notable addition of a `Datetime` +//! type. In general, TOML and JSON are interchangeable in terms of +//! formats. +//! +//! ## Parsing TOML +//! +//! The easiest way to parse a TOML document is via the `Value` type: +//! +//! ```rust +//! use toml::Value; +//! +//! let value = "foo = 'bar'".parse::<Value>().unwrap(); +//! +//! assert_eq!(value["foo"].as_str(), Some("bar")); +//! ``` +//! +//! The `Value` type implements a number of convenience methods and +//! traits; the example above uses `FromStr` to parse a `str` into a +//! `Value`. +//! +//! ## Deserialization and Serialization +//! +//! This crate supports [`serde`] 1.0 with a number of +//! implementations of the `Deserialize`, `Serialize`, `Deserializer`, and +//! `Serializer` traits. Namely, you'll find: +//! +//! * `Deserialize for Value` +//! * `Serialize for Value` +//! * `Deserialize for Datetime` +//! * `Serialize for Datetime` +//! * `Deserializer for de::Deserializer` +//! * `Serializer for ser::Serializer` +//! * `Deserializer for Value` +//! +//! This means that you can use Serde to deserialize/serialize the +//! `Value` type as well as the `Datetime` type in this crate. You can also +//! use the `Deserializer`, `Serializer`, or `Value` type itself to act as +//! a deserializer/serializer for arbitrary types. +//! +//! An example of deserializing with TOML is: +//! +//! ```rust +//! #[macro_use] +//! extern crate serde_derive; +//! extern crate toml; +//! +//! #[derive(Deserialize)] +//! struct Config { +//! ip: String, +//! port: Option<u16>, +//! keys: Keys, +//! } +//! +//! #[derive(Deserialize)] +//! struct Keys { +//! github: String, +//! travis: Option<String>, +//! } +//! +//! fn main() { +//! let config: Config = toml::from_str(r#" +//! ip = '127.0.0.1' +//! +//! [keys] +//! github = 'xxxxxxxxxxxxxxxxx' +//! travis = 'yyyyyyyyyyyyyyyyy' +//! "#).unwrap(); +//! +//! assert_eq!(config.ip, "127.0.0.1"); +//! assert_eq!(config.port, None); +//! assert_eq!(config.keys.github, "xxxxxxxxxxxxxxxxx"); +//! assert_eq!(config.keys.travis.as_ref().unwrap(), "yyyyyyyyyyyyyyyyy"); +//! } +//! ``` +//! +//! You can serialize types in a similar fashion: +//! +//! ```rust +//! #[macro_use] +//! extern crate serde_derive; +//! extern crate toml; +//! +//! #[derive(Serialize)] +//! struct Config { +//! ip: String, +//! port: Option<u16>, +//! keys: Keys, +//! } +//! +//! #[derive(Serialize)] +//! struct Keys { +//! github: String, +//! travis: Option<String>, +//! } +//! +//! fn main() { +//! let config = Config { +//! ip: "127.0.0.1".to_string(), +//! port: None, +//! keys: Keys { +//! github: "xxxxxxxxxxxxxxxxx".to_string(), +//! travis: Some("yyyyyyyyyyyyyyyyy".to_string()), +//! }, +//! }; +//! +//! let toml = toml::to_string(&config).unwrap(); +//! } +//! ``` +//! +//! [TOML]: https://github.com/toml-lang/toml +//! [Cargo]: https://crates.io/ +//! [`serde`]: https://serde.rs/ + +#![doc(html_root_url = "https://docs.rs/toml/0.4")] +#![deny(missing_docs)] + +#[macro_use] +extern crate serde; + +pub mod value; +#[doc(no_inline)] +pub use value::Value; +mod datetime; + +pub mod ser; +#[doc(no_inline)] +pub use ser::{to_string, to_string_pretty, to_vec, Serializer}; +pub mod de; +#[doc(no_inline)] +pub use de::{from_slice, from_str, Deserializer}; +mod tokens; + +#[doc(hidden)] +pub mod macros; diff -Nru cargo-0.25.0/vendor/toml-0.4.6/src/macros.rs cargo-0.26.0/vendor/toml-0.4.6/src/macros.rs --- cargo-0.25.0/vendor/toml-0.4.6/src/macros.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/src/macros.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,373 @@ +pub use serde::de::{Deserialize, IntoDeserializer}; + +use value::{Value, Table, Array}; + +/// Construct a [`toml::Value`] from TOML syntax. +/// +/// [`toml::Value`]: value/enum.Value.html +/// +/// ```rust +/// #[macro_use] +/// extern crate toml; +/// +/// fn main() { +/// let cargo_toml = toml! { +/// [package] +/// name = "toml" +/// version = "0.4.5" +/// authors = ["Alex Crichton <alex@alexcrichton.com>"] +/// +/// [badges] +/// travis-ci = { repository = "alexcrichton/toml-rs" } +/// +/// [dependencies] +/// serde = "1.0" +/// +/// [dev-dependencies] +/// serde_derive = "1.0" +/// serde_json = "1.0" +/// }; +/// +/// println!("{:#?}", cargo_toml); +/// } +/// ``` +#[macro_export] +macro_rules! toml { + ($($toml:tt)+) => {{ + let table = $crate::value::Table::new(); + let mut root = $crate::Value::Table(table); + toml_internal!(@toplevel root [] $($toml)+); + root + }}; +} + +// TT-muncher to parse TOML syntax into a toml::Value. +// +// @toplevel -- Parse tokens outside of an inline table or inline array. In +// this state, `[table headers]` and `[[array headers]]` are +// allowed and `key = value` pairs are not separated by commas. +// +// @topleveldatetime -- Helper to parse a Datetime from string and insert it +// into a table, continuing in the @toplevel state. +// +// @path -- Turn a path segment into a string. Segments that look like idents +// are stringified, while quoted segments like `"cfg(windows)"` +// are not. +// +// @value -- Parse the value part of a `key = value` pair, which may be a +// primitive or inline table or inline array. +// +// @table -- Parse the contents of an inline table, returning them as a +// toml::Value::Table. +// +// @tabledatetime -- Helper to parse a Datetime from string and insert it +// into a table, continuing in the @table state. +// +// @array -- Parse the contents of an inline array, returning them as a +// toml::Value::Array. +// +// @arraydatetime -- Helper to parse a Datetime from string and push it into +// an array, continuing in the @array state. +// +// @trailingcomma -- Helper to append a comma to a sequence of tokens if the +// sequence is non-empty and does not already end in a trailing +// comma. +// +#[macro_export] +#[doc(hidden)] +macro_rules! toml_internal { + // Base case, no elements remaining. + (@toplevel $root:ident [$($path:tt)*]) => {}; + + // Parse negative number `key = -value`. + (@toplevel $root:ident [$($path:tt)*] $($k:tt)-+ = - $v:tt $($rest:tt)*) => { + toml_internal!(@toplevel $root [$($path)*] $($k)-+ = (-$v) $($rest)*); + }; + + // Parse offset datetime `key = 1979-05-27T00:32:00.999999-07:00`. + (@toplevel $root:ident [$($path:tt)*] $($k:tt)-+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt . $frac:tt - $tzh:tt : $tzm:tt $($rest:tt)*) => { + toml_internal!(@topleveldatetime $root [$($path)*] $($k)-+ = ($yr - $mo - $dhr : $min : $sec . $frac - $tzh : $tzm) $($rest)*); + }; + + // Parse offset datetime `key = 1979-05-27T00:32:00-07:00`. + (@toplevel $root:ident [$($path:tt)*] $($k:tt)-+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt - $tzh:tt : $tzm:tt $($rest:tt)*) => { + toml_internal!(@topleveldatetime $root [$($path)*] $($k)-+ = ($yr - $mo - $dhr : $min : $sec - $tzh : $tzm) $($rest)*); + }; + + // Parse local datetime `key = 1979-05-27T00:32:00.999999`. + (@toplevel $root:ident [$($path:tt)*] $($k:tt)-+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt . $frac:tt $($rest:tt)*) => { + toml_internal!(@topleveldatetime $root [$($path)*] $($k)-+ = ($yr - $mo - $dhr : $min : $sec . $frac) $($rest)*); + }; + + // Parse offset datetime `key = 1979-05-27T07:32:00Z` and local datetime `key = 1979-05-27T07:32:00`. + (@toplevel $root:ident [$($path:tt)*] $($k:tt)-+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt $($rest:tt)*) => { + toml_internal!(@topleveldatetime $root [$($path)*] $($k)-+ = ($yr - $mo - $dhr : $min : $sec) $($rest)*); + }; + + // Parse local date `key = 1979-05-27`. + (@toplevel $root:ident [$($path:tt)*] $($k:tt)-+ = $yr:tt - $mo:tt - $day:tt $($rest:tt)*) => { + toml_internal!(@topleveldatetime $root [$($path)*] $($k)-+ = ($yr - $mo - $day) $($rest)*); + }; + + // Parse local time `key = 00:32:00.999999`. + (@toplevel $root:ident [$($path:tt)*] $($k:tt)-+ = $hr:tt : $min:tt : $sec:tt . $frac:tt $($rest:tt)*) => { + toml_internal!(@topleveldatetime $root [$($path)*] $($k)-+ = ($hr : $min : $sec . $frac) $($rest)*); + }; + + // Parse local time `key = 07:32:00`. + (@toplevel $root:ident [$($path:tt)*] $($k:tt)-+ = $hr:tt : $min:tt : $sec:tt $($rest:tt)*) => { + toml_internal!(@topleveldatetime $root [$($path)*] $($k)-+ = ($hr : $min : $sec) $($rest)*); + }; + + // Parse any other `key = value` including string, inline array, inline + // table, number, and boolean. + (@toplevel $root:ident [$($path:tt)*] $($k:tt)-+ = $v:tt $($rest:tt)*) => { + $crate::macros::insert_toml( + &mut $root, + &[$($path)* &concat!($("-", toml_internal!(@path $k),)+)[1..]], + toml_internal!(@value $v)); + toml_internal!(@toplevel $root [$($path)*] $($rest)*); + }; + + // Parse array header `[[bin]]`. + (@toplevel $root:ident $oldpath:tt [[$($($path:tt)-+).+]] $($rest:tt)*) => { + $crate::macros::push_toml( + &mut $root, + &[$(&concat!($("-", toml_internal!(@path $path),)+)[1..],)+]); + toml_internal!(@toplevel $root [$(&concat!($("-", toml_internal!(@path $path),)+)[1..],)+] $($rest)*); + }; + + // Parse table header `[patch.crates-io]`. + (@toplevel $root:ident $oldpath:tt [$($($path:tt)-+).+] $($rest:tt)*) => { + $crate::macros::insert_toml( + &mut $root, + &[$(&concat!($("-", toml_internal!(@path $path),)+)[1..],)+], + $crate::Value::Table($crate::value::Table::new())); + toml_internal!(@toplevel $root [$(&concat!($("-", toml_internal!(@path $path),)+)[1..],)+] $($rest)*); + }; + + // Parse datetime from string and insert into table. + (@topleveldatetime $root:ident [$($path:tt)*] $($k:tt)-+ = ($($datetime:tt)+) $($rest:tt)*) => { + $crate::macros::insert_toml( + &mut $root, + &[$($path)* &concat!($("-", toml_internal!(@path $k),)+)[1..]], + $crate::Value::Datetime(concat!($(stringify!($datetime)),+).parse().unwrap())); + toml_internal!(@toplevel $root [$($path)*] $($rest)*); + }; + + // Turn a path segment into a string. + (@path $ident:ident) => { + stringify!($ident) + }; + + // For a path segment that is not an ident, expect that it is already a + // quoted string, like in `[target."cfg(windows)".dependencies]`. + (@path $quoted:tt) => { + $quoted + }; + + // Construct a Value from an inline table. + (@value { $($inline:tt)* }) => {{ + let mut table = $crate::value::Table::new(); + toml_internal!(@trailingcomma (@table table) $($inline)*); + $crate::Value::Table(table) + }}; + + // Construct a Value from an inline array. + (@value [ $($inline:tt)* ]) => {{ + let mut array = $crate::value::Array::new(); + toml_internal!(@trailingcomma (@array array) $($inline)*); + $crate::Value::Array(array) + }}; + + // Construct a Value from any other type, probably string or boolean or number. + (@value $v:tt) => {{ + // TODO: Implement this with something like serde_json::to_value instead. + let de = $crate::macros::IntoDeserializer::<$crate::de::Error>::into_deserializer($v); + <$crate::Value as $crate::macros::Deserialize>::deserialize(de).unwrap() + }}; + + // Base case of inline table. + (@table $root:ident) => {}; + + // Parse negative number `key = -value`. + (@table $root:ident $($k:tt)-+ = - $v:tt , $($rest:tt)*) => { + toml_internal!(@table $root $($k)-+ = (-$v) , $($rest)*); + }; + + // Parse offset datetime `key = 1979-05-27T00:32:00.999999-07:00`. + (@table $root:ident $($k:tt)-+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt . $frac:tt - $tzh:tt : $tzm:tt , $($rest:tt)*) => { + toml_internal!(@tabledatetime $root $($k)-+ = ($yr - $mo - $dhr : $min : $sec . $frac - $tzh : $tzm) $($rest)*); + }; + + // Parse offset datetime `key = 1979-05-27T00:32:00-07:00`. + (@table $root:ident $($k:tt)-+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt - $tzh:tt : $tzm:tt , $($rest:tt)*) => { + toml_internal!(@tabledatetime $root $($k)-+ = ($yr - $mo - $dhr : $min : $sec - $tzh : $tzm) $($rest)*); + }; + + // Parse local datetime `key = 1979-05-27T00:32:00.999999`. + (@table $root:ident $($k:tt)-+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt . $frac:tt , $($rest:tt)*) => { + toml_internal!(@tabledatetime $root $($k)-+ = ($yr - $mo - $dhr : $min : $sec . $frac) $($rest)*); + }; + + // Parse offset datetime `key = 1979-05-27T07:32:00Z` and local datetime `key = 1979-05-27T07:32:00`. + (@table $root:ident $($k:tt)-+ = $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt , $($rest:tt)*) => { + toml_internal!(@tabledatetime $root $($k)-+ = ($yr - $mo - $dhr : $min : $sec) $($rest)*); + }; + + // Parse local date `key = 1979-05-27`. + (@table $root:ident $($k:tt)-+ = $yr:tt - $mo:tt - $day:tt , $($rest:tt)*) => { + toml_internal!(@tabledatetime $root $($k)-+ = ($yr - $mo - $day) $($rest)*); + }; + + // Parse local time `key = 00:32:00.999999`. + (@table $root:ident $($k:tt)-+ = $hr:tt : $min:tt : $sec:tt . $frac:tt , $($rest:tt)*) => { + toml_internal!(@tabledatetime $root $($k)-+ = ($hr : $min : $sec . $frac) $($rest)*); + }; + + // Parse local time `key = 07:32:00`. + (@table $root:ident $($k:tt)-+ = $hr:tt : $min:tt : $sec:tt , $($rest:tt)*) => { + toml_internal!(@tabledatetime $root $($k)-+ = ($hr : $min : $sec) $($rest)*); + }; + + // Parse any other type, probably string or boolean or number. + (@table $root:ident $($k:tt)-+ = $v:tt , $($rest:tt)*) => { + $root.insert( + concat!($("-", toml_internal!(@path $k),)+)[1..].to_owned(), + toml_internal!(@value $v)); + toml_internal!(@table $root $($rest)*); + }; + + // Parse a Datetime from string and continue in @table state. + (@tabledatetime $root:ident $($k:tt)-+ = ($($datetime:tt)*) $($rest:tt)*) => { + $root.insert( + concat!($("-", toml_internal!(@path $k),)+)[1..].to_owned(), + $crate::Value::Datetime(concat!($(stringify!($datetime)),+).parse().unwrap())); + toml_internal!(@table $root $($rest)*); + }; + + // Base case of inline array. + (@array $root:ident) => {}; + + // Parse negative number `-value`. + (@array $root:ident - $v:tt , $($rest:tt)*) => { + toml_internal!(@array $root (-$v) , $($rest)*); + }; + + // Parse offset datetime `1979-05-27T00:32:00.999999-07:00`. + (@array $root:ident $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt . $frac:tt - $tzh:tt : $tzm:tt , $($rest:tt)*) => { + toml_internal!(@arraydatetime $root ($yr - $mo - $dhr : $min : $sec . $frac - $tzh : $tzm) $($rest)*); + }; + + // Parse offset datetime `1979-05-27T00:32:00-07:00`. + (@array $root:ident $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt - $tzh:tt : $tzm:tt , $($rest:tt)*) => { + toml_internal!(@arraydatetime $root ($yr - $mo - $dhr : $min : $sec - $tzh : $tzm) $($rest)*); + }; + + // Parse local datetime `1979-05-27T00:32:00.999999`. + (@array $root:ident $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt . $frac:tt , $($rest:tt)*) => { + toml_internal!(@arraydatetime $root ($yr - $mo - $dhr : $min : $sec . $frac) $($rest)*); + }; + + // Parse offset datetime `1979-05-27T07:32:00Z` and local datetime `1979-05-27T07:32:00`. + (@array $root:ident $yr:tt - $mo:tt - $dhr:tt : $min:tt : $sec:tt , $($rest:tt)*) => { + toml_internal!(@arraydatetime $root ($yr - $mo - $dhr : $min : $sec) $($rest)*); + }; + + // Parse local date `1979-05-27`. + (@array $root:ident $yr:tt - $mo:tt - $day:tt , $($rest:tt)*) => { + toml_internal!(@arraydatetime $root ($yr - $mo - $day) $($rest)*); + }; + + // Parse local time `00:32:00.999999`. + (@array $root:ident $hr:tt : $min:tt : $sec:tt . $frac:tt , $($rest:tt)*) => { + toml_internal!(@arraydatetime $root ($hr : $min : $sec . $frac) $($rest)*); + }; + + // Parse local time `07:32:00`. + (@array $root:ident $hr:tt : $min:tt : $sec:tt , $($rest:tt)*) => { + toml_internal!(@arraydatetime $root ($hr : $min : $sec) $($rest)*); + }; + + // Parse any other type, probably string or boolean or number. + (@array $root:ident $v:tt , $($rest:tt)*) => { + $root.push(toml_internal!(@value $v)); + toml_internal!(@array $root $($rest)*); + }; + + // Parse a Datetime from string and continue in @array state. + (@arraydatetime $root:ident ($($datetime:tt)*) $($rest:tt)*) => { + $root.push($crate::Value::Datetime(concat!($(stringify!($datetime)),+).parse().unwrap())); + toml_internal!(@array $root $($rest)*); + }; + + // No trailing comma required if the tokens are empty. + (@trailingcomma ($($args:tt)*)) => { + toml_internal!($($args)*); + }; + + // Tokens end with a trailing comma, do not append another one. + (@trailingcomma ($($args:tt)*) ,) => { + toml_internal!($($args)* ,); + }; + + // Tokens end with something other than comma, append a trailing comma. + (@trailingcomma ($($args:tt)*) $last:tt) => { + toml_internal!($($args)* $last ,); + }; + + // Not yet at the last token. + (@trailingcomma ($($args:tt)*) $first:tt $($rest:tt)+) => { + toml_internal!(@trailingcomma ($($args)* $first) $($rest)+); + }; +} + +// Called when parsing a `key = value` pair. +// Inserts an entry into the table at the given path. +pub fn insert_toml(root: &mut Value, path: &[&str], value: Value) { + *traverse(root, path) = value; +} + +// Called when parsing an `[[array header]]`. +// Pushes an empty table onto the array at the given path. +pub fn push_toml(root: &mut Value, path: &[&str]) { + let target = traverse(root, path); + if !target.is_array() { + *target = Value::Array(Array::new()); + } + target.as_array_mut().unwrap().push(Value::Table(Table::new())); +} + +fn traverse<'a>(root: &'a mut Value, path: &[&str]) -> &'a mut Value { + let mut cur = root; + for &key in path { + // Lexical lifetimes :D + let cur1 = cur; + let cur2; + + // From the TOML spec: + // + // > Each double-bracketed sub-table will belong to the most recently + // > defined table element above it. + if cur1.is_array() { + cur2 = cur1.as_array_mut().unwrap().last_mut().unwrap(); + } else { + cur2 = cur1; + }; + + // We are about to index into this value, so it better be a table. + if !cur2.is_table() { + *cur2 = Value::Table(Table::new()); + } + + if !cur2.as_table().unwrap().contains_key(key) { + // Insert an empty table for the next loop iteration to point to. + let empty = Value::Table(Table::new()); + cur2.as_table_mut().unwrap().insert(key.to_owned(), empty); + } + + // Step into the current table. + cur = cur2.as_table_mut().unwrap().get_mut(key).unwrap(); + } + cur +} diff -Nru cargo-0.25.0/vendor/toml-0.4.6/src/ser.rs cargo-0.26.0/vendor/toml-0.4.6/src/ser.rs --- cargo-0.25.0/vendor/toml-0.4.6/src/ser.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/src/ser.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1714 @@ +//! Serializing Rust structures into TOML. +//! +//! This module contains all the Serde support for serializing Rust structures +//! into TOML documents (as strings). Note that some top-level functions here +//! are also provided at the top of the crate. +//! +//! Note that the TOML format has a restriction that if a table itself contains +//! tables, all keys with non-table values must be emitted first. This is +//! typically easy to ensure happens when you're defining a `struct` as you can +//! reorder the fields manually, but when working with maps (such as `BTreeMap` +//! or `HashMap`) this can lead to serialization errors. In those situations you +//! may use the `tables_last` function in this module like so: +//! +//! ```rust +//! # #[macro_use] extern crate serde_derive; +//! # extern crate toml; +//! # use std::collections::HashMap; +//! #[derive(Serialize)] +//! struct Manifest { +//! package: Package, +//! #[serde(serialize_with = "toml::ser::tables_last")] +//! dependencies: HashMap<String, Dependency>, +//! } +//! # type Package = String; +//! # type Dependency = String; +//! # fn main() {} +//! ``` + +use std::cell::Cell; +use std::error; +use std::fmt::{self, Write}; +use std::marker; +use std::rc::Rc; + +use serde::ser; +use datetime::{SERDE_STRUCT_FIELD_NAME, SERDE_STRUCT_NAME}; + +/// Serialize the given data structure as a TOML byte vector. +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, if `T` contains a map with non-string keys, or if `T` attempts to +/// serialize an unsupported datatype such as an enum, tuple, or tuple struct. +pub fn to_vec<T: ?Sized>(value: &T) -> Result<Vec<u8>, Error> + where T: ser::Serialize, +{ + to_string(value).map(|e| e.into_bytes()) +} + +/// Serialize the given data structure as a String of TOML. +/// +/// Serialization can fail if `T`'s implementation of `Serialize` decides to +/// fail, if `T` contains a map with non-string keys, or if `T` attempts to +/// serialize an unsupported datatype such as an enum, tuple, or tuple struct. +/// +/// # Examples +/// +/// ``` +/// #[macro_use] +/// extern crate serde_derive; +/// extern crate toml; +/// +/// #[derive(Serialize)] +/// struct Config { +/// database: Database, +/// } +/// +/// #[derive(Serialize)] +/// struct Database { +/// ip: String, +/// port: Vec<u16>, +/// connection_max: u32, +/// enabled: bool, +/// } +/// +/// fn main() { +/// let config = Config { +/// database: Database { +/// ip: "192.168.1.1".to_string(), +/// port: vec![8001, 8002, 8003], +/// connection_max: 5000, +/// enabled: false, +/// }, +/// }; +/// +/// let toml = toml::to_string(&config).unwrap(); +/// println!("{}", toml) +/// } +/// ``` +pub fn to_string<T: ?Sized>(value: &T) -> Result<String, Error> + where T: ser::Serialize, +{ + let mut dst = String::with_capacity(128); + value.serialize(&mut Serializer::new(&mut dst))?; + Ok(dst) +} + +/// Serialize the given data structure as a "pretty" String of TOML. +/// +/// This is identical to `to_string` except the output string has a more +/// "pretty" output. See `Serializer::pretty` for more details. +pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String, Error> + where T: ser::Serialize, +{ + let mut dst = String::with_capacity(128); + value.serialize(&mut Serializer::pretty(&mut dst))?; + Ok(dst) +} + +/// Errors that can occur when serializing a type. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum Error { + /// Indicates that a Rust type was requested to be serialized but it was not + /// supported. + /// + /// Currently the TOML format does not support serializing types such as + /// enums, tuples and tuple structs. + UnsupportedType, + + /// The key of all TOML maps must be strings, but serialization was + /// attempted where the key of a map was not a string. + KeyNotString, + + /// An error that we never omit but keep for backwards compatibility + #[doc(hidden)] + KeyNewline, + + /// Arrays in TOML must have a homogenous type, but a heterogeneous array + /// was emitted. + ArrayMixedType, + + /// All values in a TOML table must be emitted before further tables are + /// emitted. If a value is emitted *after* a table then this error is + /// generated. + ValueAfterTable, + + /// A serialized date was invalid. + DateInvalid, + + /// A serialized number was invalid. + NumberInvalid, + + /// None was attempted to be serialized, but it's not supported. + UnsupportedNone, + + /// A custom error which could be generated when serializing a particular + /// type. + Custom(String), + + #[doc(hidden)] + __Nonexhaustive, +} + +#[derive(Debug, Default, Clone)] +#[doc(hidden)] +/// Internal place for holding array setings +struct ArraySettings { + indent: usize, + trailing_comma: bool, +} + +impl ArraySettings { + fn pretty() -> ArraySettings { + ArraySettings { + indent: 4, + trailing_comma: true, + } + } +} + +#[doc(hidden)] +#[derive(Debug, Default, Clone)] +/// String settings +struct StringSettings { + /// Whether to use literal strings when possible + literal: bool, +} + +impl StringSettings { + fn pretty() -> StringSettings { + StringSettings { + literal: true, + } + } +} + +#[derive(Debug, Default, Clone)] +#[doc(hidden)] +/// Internal struct for holding serialization settings +struct Settings { + array: Option<ArraySettings>, + string: Option<StringSettings>, +} + +/// Serialization implementation for TOML. +/// +/// This structure implements serialization support for TOML to serialize an +/// arbitrary type to TOML. Note that the TOML format does not support all +/// datatypes in Rust, such as enums, tuples, and tuple structs. These types +/// will generate an error when serialized. +/// +/// Currently a serializer always writes its output to an in-memory `String`, +/// which is passed in when creating the serializer itself. +pub struct Serializer<'a> { + dst: &'a mut String, + state: State<'a>, + settings: Rc<Settings>, +} + +#[derive(Debug, Clone)] +enum State<'a> { + Table { + key: &'a str, + parent: &'a State<'a>, + first: &'a Cell<bool>, + table_emitted: &'a Cell<bool>, + }, + Array { + parent: &'a State<'a>, + first: &'a Cell<bool>, + type_: &'a Cell<Option<&'static str>>, + len: Option<usize>, + }, + End, +} + +#[doc(hidden)] +pub struct SerializeSeq<'a: 'b, 'b> { + ser: &'b mut Serializer<'a>, + first: Cell<bool>, + type_: Cell<Option<&'static str>>, + len: Option<usize>, +} + +#[doc(hidden)] +pub enum SerializeTable<'a: 'b, 'b> { + Datetime(&'b mut Serializer<'a>), + Table { + ser: &'b mut Serializer<'a>, + key: String, + first: Cell<bool>, + table_emitted: Cell<bool>, + } +} + +impl<'a> Serializer<'a> { + /// Creates a new serializer which will emit TOML into the buffer provided. + /// + /// The serializer can then be used to serialize a type after which the data + /// will be present in `dst`. + pub fn new(dst: &'a mut String) -> Serializer<'a> { + Serializer { + dst: dst, + state: State::End, + settings: Rc::new(Settings::default()), + } + } + + /// Instantiate a "pretty" formatter + /// + /// By default this will use: + /// + /// - pretty strings: strings with newlines will use the `'''` syntax. See + /// `Serializer::pretty_string` + /// - pretty arrays: each item in arrays will be on a newline, have an indentation of 4 and + /// have a trailing comma. See `Serializer::pretty_array` + pub fn pretty(dst: &'a mut String) -> Serializer<'a> { + Serializer { + dst: dst, + state: State::End, + settings: Rc::new(Settings { + array: Some(ArraySettings::pretty()), + string: Some(StringSettings::pretty()), + }), + } + } + + /// Enable or Disable pretty strings + /// + /// If enabled, literal strings will be used when possible and strings with + /// one or more newlines will use triple quotes (i.e.: `'''` or `"""`) + /// + /// # Examples + /// + /// Instead of: + /// + /// ```toml,ignore + /// single = "no newlines" + /// text = "\nfoo\nbar\n" + /// ``` + /// + /// You will have: + /// + /// ```toml,ignore + /// single = 'no newlines' + /// text = ''' + /// foo + /// bar + /// ''' + /// ``` + pub fn pretty_string(&mut self, value: bool) -> &mut Self { + Rc::get_mut(&mut self.settings).unwrap().string = if value { + Some(StringSettings::pretty()) + } else { + None + }; + self + } + + /// Enable or Disable Literal strings for pretty strings + /// + /// If enabled, literal strings will be used when possible and strings with + /// one or more newlines will use triple quotes (i.e.: `'''` or `"""`) + /// + /// If disabled, literal strings will NEVER be used and strings with one or + /// more newlines will use `"""` + /// + /// # Examples + /// + /// Instead of: + /// + /// ```toml,ignore + /// single = "no newlines" + /// text = "\nfoo\nbar\n" + /// ``` + /// + /// You will have: + /// + /// ```toml,ignore + /// single = "no newlines" + /// text = """ + /// foo + /// bar + /// """ + /// ``` + pub fn pretty_string_literal(&mut self, value: bool) -> &mut Self { + let use_default = if let &mut Some(ref mut s) = &mut Rc::get_mut(&mut self.settings) + .unwrap().string { + s.literal = value; + false + } else { + true + }; + + if use_default { + let mut string = StringSettings::pretty(); + string.literal = value; + Rc::get_mut(&mut self.settings).unwrap().string = Some(string); + } + self + } + + /// Enable or Disable pretty arrays + /// + /// If enabled, arrays will always have each item on their own line. + /// + /// Some specific features can be controlled via other builder methods: + /// + /// - `Serializer::pretty_array_indent`: set the indent to a value other + /// than 4. + /// - `Serializer::pretty_array_trailing_comma`: enable/disable the trailing + /// comma on the last item. + /// + /// # Examples + /// + /// Instead of: + /// + /// ```toml,ignore + /// array = ["foo", "bar"] + /// ``` + /// + /// You will have: + /// + /// ```toml,ignore + /// array = [ + /// "foo", + /// "bar", + /// ] + /// ``` + pub fn pretty_array(&mut self, value: bool) -> &mut Self { + Rc::get_mut(&mut self.settings).unwrap().array = if value { + Some(ArraySettings::pretty()) + } else { + None + }; + self + } + + /// Set the indent for pretty arrays + /// + /// See `Serializer::pretty_array` for more details. + pub fn pretty_array_indent(&mut self, value: usize) -> &mut Self { + let use_default = if let &mut Some(ref mut a) = &mut Rc::get_mut(&mut self.settings) + .unwrap().array { + a.indent = value; + false + } else { + true + }; + + if use_default { + let mut array = ArraySettings::pretty(); + array.indent = value; + Rc::get_mut(&mut self.settings).unwrap().array = Some(array); + } + self + } + + /// Specify whether to use a trailing comma when serializing pretty arrays + /// + /// See `Serializer::pretty_array` for more details. + pub fn pretty_array_trailing_comma(&mut self, value: bool) -> &mut Self { + let use_default = if let &mut Some(ref mut a) = &mut Rc::get_mut(&mut self.settings) + .unwrap().array { + a.trailing_comma = value; + false + } else { + true + }; + + if use_default { + let mut array = ArraySettings::pretty(); + array.trailing_comma = value; + Rc::get_mut(&mut self.settings).unwrap().array = Some(array); + } + self + } + + fn display<T: fmt::Display>(&mut self, + t: T, + type_: &'static str) -> Result<(), Error> { + self.emit_key(type_)?; + drop(write!(self.dst, "{}", t)); + if let State::Table { .. } = self.state { + self.dst.push_str("\n"); + } + Ok(()) + } + + fn emit_key(&mut self, type_: &'static str) -> Result<(), Error> { + self.array_type(type_)?; + let state = self.state.clone(); + self._emit_key(&state) + } + + // recursive implementation of `emit_key` above + fn _emit_key(&mut self, state: &State) -> Result<(), Error> { + match *state { + State::End => Ok(()), + State::Array { parent, first, type_, len } => { + assert!(type_.get().is_some()); + if first.get() { + self._emit_key(parent)?; + } + self.emit_array(first, len) + } + State::Table { parent, first, table_emitted, key } => { + if table_emitted.get() { + return Err(Error::ValueAfterTable) + } + if first.get() { + self.emit_table_header(parent)?; + first.set(false); + } + self.escape_key(key)?; + self.dst.push_str(" = "); + Ok(()) + } + } + } + + fn emit_array(&mut self, first: &Cell<bool>, len: Option<usize>) -> Result<(), Error> { + match (len, &self.settings.array) { + (Some(0...1), _) | (_, &None) => { + if first.get() { + self.dst.push_str("[") + } else { + self.dst.push_str(", ") + } + }, + (_, &Some(ref a)) => { + if first.get() { + self.dst.push_str("[\n") + } else { + self.dst.push_str(",\n") + } + for _ in 0..a.indent { + self.dst.push_str(" "); + } + }, + } + Ok(()) + } + + fn array_type(&mut self, type_: &'static str) -> Result<(), Error> { + let prev = match self.state { + State::Array { type_, .. } => type_, + _ => return Ok(()), + }; + if let Some(prev) = prev.get() { + if prev != type_ { + return Err(Error::ArrayMixedType) + } + } else { + prev.set(Some(type_)); + } + Ok(()) + } + + fn escape_key(&mut self, key: &str) -> Result<(), Error> { + let ok = key.chars().all(|c| { + match c { + 'a' ... 'z' | + 'A' ... 'Z' | + '0' ... '9' | + '-' | '_' => true, + _ => false, + } + }); + if ok { + drop(write!(self.dst, "{}", key)); + } else { + self.emit_str(key, true)?; + } + Ok(()) + } + + fn emit_str(&mut self, value: &str, is_key: bool) -> Result<(), Error> { + #[derive(PartialEq)] + enum Type { + NewlineTripple, + OnelineTripple, + OnelineSingle, + } + + enum Repr { + /// represent as a literal string (using '') + Literal(String, Type), + /// represent the std way (using "") + Std(Type), + } + + fn do_pretty(value: &str) -> Repr { + // For doing pretty prints we store in a new String + // because there are too many cases where pretty cannot + // work. We need to determine: + // - if we are a "multi-line" pretty (if there are \n) + // - if ['''] appears if multi or ['] if single + // - if there are any invalid control characters + // + // Doing it any other way would require multiple passes + // to determine if a pretty string works or not. + let mut out = String::with_capacity(value.len() * 2); + let mut ty = Type::OnelineSingle; + // found consecutive single quotes + let mut max_found_singles = 0; + let mut found_singles = 0; + let mut can_be_pretty = true; + + for ch in value.chars() { + if can_be_pretty { + if ch == '\'' { + found_singles += 1; + if found_singles >= 3 { + can_be_pretty = false; + } + } else { + if found_singles > max_found_singles { + max_found_singles = found_singles; + } + found_singles = 0 + } + match ch { + '\t' => {}, + '\n' => ty = Type::NewlineTripple, + // note that the following are invalid: \b \f \r + c if c < '\u{1f}' => can_be_pretty = false, // Invalid control character + _ => {} + } + out.push(ch); + } else { + // the string cannot be represented as pretty, + // still check if it should be multiline + if ch == '\n' { + ty = Type::NewlineTripple; + } + } + } + if !can_be_pretty { + debug_assert!(ty != Type::OnelineTripple); + return Repr::Std(ty); + } + if found_singles > max_found_singles { + max_found_singles = found_singles; + } + debug_assert!(max_found_singles < 3); + if ty == Type::OnelineSingle && max_found_singles >= 1 { + // no newlines, but must use ''' because it has ' in it + ty = Type::OnelineTripple; + } + Repr::Literal(out, ty) + } + + let repr = if !is_key && self.settings.string.is_some() { + match (&self.settings.string, do_pretty(value)) { + (&Some(StringSettings { literal: false, .. }), Repr::Literal(_, ty)) => + Repr::Std(ty), + (_, r @ _) => r, + } + } else { + Repr::Std(Type::OnelineSingle) + }; + match repr { + Repr::Literal(literal, ty) => { + // A pretty string + match ty { + Type::NewlineTripple => self.dst.push_str("'''\n"), + Type::OnelineTripple => self.dst.push_str("'''"), + Type::OnelineSingle => self.dst.push('\''), + } + self.dst.push_str(&literal); + match ty { + Type::OnelineSingle => self.dst.push('\''), + _ => self.dst.push_str("'''"), + } + }, + Repr::Std(ty) => { + match ty { + Type::NewlineTripple => self.dst.push_str("\"\"\"\n"), + // note: OnelineTripple can happen if do_pretty wants to do + // '''it's one line''' + // but settings.string.literal == false + Type::OnelineSingle | + Type::OnelineTripple => self.dst.push('"'), + } + for ch in value.chars() { + match ch { + '\u{8}' => self.dst.push_str("\\b"), + '\u{9}' => self.dst.push_str("\\t"), + '\u{a}' => { + match ty { + Type::NewlineTripple => self.dst.push('\n'), + Type::OnelineSingle => self.dst.push_str("\\n"), + _ => unreachable!(), + } + }, + '\u{c}' => self.dst.push_str("\\f"), + '\u{d}' => self.dst.push_str("\\r"), + '\u{22}' => self.dst.push_str("\\\""), + '\u{5c}' => self.dst.push_str("\\\\"), + c if c < '\u{1f}' => drop(write!(self.dst, "\\u{:04X}", ch as u32)), + ch => self.dst.push(ch), + } + } + match ty { + Type::NewlineTripple => self.dst.push_str("\"\"\""), + Type::OnelineSingle | Type::OnelineTripple => self.dst.push('"'), + } + }, + } + Ok(()) + } + + fn emit_table_header(&mut self, state: &State) -> Result<(), Error> { + let array_of_tables = match *state { + State::End => return Ok(()), + State::Array { .. } => true, + _ => false, + }; + + // Unlike [..]s, we can't omit [[..]] ancestors, so be sure to emit table + // headers for them. + let mut p = state; + if let State::Array { first, parent, .. } = *state { + if first.get() { + p = parent; + } + } + while let State::Table { first, parent, .. } = *p { + p = parent; + if !first.get() { + break; + } + if let State::Array { parent: &State::Table {..}, ..} = *parent { + self.emit_table_header(parent)?; + break; + } + } + + match *state { + State::Table { first, .. } => { + if !first.get() { + // Newline if we are a table that is not the first + // table in the document. + self.dst.push('\n'); + } + }, + State::Array { parent, first, .. } => { + if !first.get() { + // Always newline if we are not the first item in the + // table-array + self.dst.push('\n'); + } else if let State::Table { first, .. } = *parent { + if !first.get() { + // Newline if we are not the first item in the document + self.dst.push('\n'); + } + } + }, + _ => {} + } + self.dst.push_str("["); + if array_of_tables { + self.dst.push_str("["); + } + self.emit_key_part(state)?; + if array_of_tables { + self.dst.push_str("]"); + } + self.dst.push_str("]\n"); + Ok(()) + } + + fn emit_key_part(&mut self, key: &State) -> Result<bool, Error> { + match *key { + State::Array { parent, .. } => self.emit_key_part(parent), + State::End => Ok(true), + State::Table { key, parent, table_emitted, .. } => { + table_emitted.set(true); + let first = self.emit_key_part(parent)?; + if !first { + self.dst.push_str("."); + } + self.escape_key(key)?; + Ok(false) + } + } + } +} + +impl<'a, 'b> ser::Serializer for &'b mut Serializer<'a> { + type Ok = (); + type Error = Error; + type SerializeSeq = SerializeSeq<'a, 'b>; + type SerializeTuple = ser::Impossible<(), Error>; + type SerializeTupleStruct = ser::Impossible<(), Error>; + type SerializeTupleVariant = ser::Impossible<(), Error>; + type SerializeMap = SerializeTable<'a, 'b>; + type SerializeStruct = SerializeTable<'a, 'b>; + type SerializeStructVariant = ser::Impossible<(), Error>; + + fn serialize_bool(self, v: bool) -> Result<(), Self::Error> { + self.display(v, "bool") + } + + fn serialize_i8(self, v: i8) -> Result<(), Self::Error> { + self.display(v, "integer") + } + + fn serialize_i16(self, v: i16) -> Result<(), Self::Error> { + self.display(v, "integer") + } + + fn serialize_i32(self, v: i32) -> Result<(), Self::Error> { + self.display(v, "integer") + } + + fn serialize_i64(self, v: i64) -> Result<(), Self::Error> { + self.display(v, "integer") + } + + fn serialize_u8(self, v: u8) -> Result<(), Self::Error> { + self.display(v, "integer") + } + + fn serialize_u16(self, v: u16) -> Result<(), Self::Error> { + self.display(v, "integer") + } + + fn serialize_u32(self, v: u32) -> Result<(), Self::Error> { + self.display(v, "integer") + } + + fn serialize_u64(self, v: u64) -> Result<(), Self::Error> { + self.display(v, "integer") + } + + fn serialize_f32(self, v: f32) -> Result<(), Self::Error> { + if !v.is_finite() { + return Err(Error::NumberInvalid); + } + + self.emit_key("float")?; + drop(write!(self.dst, "{}", v)); + if v % 1.0 == 0.0 { + drop(write!(self.dst, ".0")); + } + if let State::Table { .. } = self.state { + self.dst.push_str("\n"); + } + Ok(()) + } + + fn serialize_f64(self, v: f64) -> Result<(), Self::Error> { + if !v.is_finite() { + return Err(Error::NumberInvalid); + } + + self.emit_key("float")?; + drop(write!(self.dst, "{}", v)); + if v % 1.0 == 0.0 { + drop(write!(self.dst, ".0")); + } + if let State::Table { .. } = self.state { + self.dst.push_str("\n"); + } + Ok(()) + } + + fn serialize_char(self, v: char) -> Result<(), Self::Error> { + let mut buf = [0; 4]; + self.serialize_str(v.encode_utf8(&mut buf)) + } + + fn serialize_str(self, value: &str) -> Result<(), Self::Error> { + self.emit_key("string")?; + self.emit_str(value, false)?; + if let State::Table { .. } = self.state { + self.dst.push_str("\n"); + } + Ok(()) + } + + fn serialize_bytes(self, value: &[u8]) -> Result<(), Self::Error> { + use serde::ser::Serialize; + value.serialize(self) + } + + fn serialize_none(self) -> Result<(), Self::Error> { + Err(Error::UnsupportedNone) + } + + fn serialize_some<T: ?Sized>(self, value: &T) -> Result<(), Self::Error> + where T: ser::Serialize + { + value.serialize(self) + } + + fn serialize_unit(self) -> Result<(), Self::Error> { + Err(Error::UnsupportedType) + } + + fn serialize_unit_struct(self, + _name: &'static str) + -> Result<(), Self::Error> { + Err(Error::UnsupportedType) + } + + fn serialize_unit_variant(self, + _name: &'static str, + _variant_index: u32, + variant: &'static str) + -> Result<(), Self::Error> { + self.serialize_str(variant) + } + + fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, value: &T) + -> Result<(), Self::Error> + where T: ser::Serialize, + { + value.serialize(self) + } + + fn serialize_newtype_variant<T: ?Sized>(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T) + -> Result<(), Self::Error> + where T: ser::Serialize, + { + Err(Error::UnsupportedType) + } + + fn serialize_seq(self, len: Option<usize>) + -> Result<Self::SerializeSeq, Self::Error> { + self.array_type("array")?; + Ok(SerializeSeq { + ser: self, + first: Cell::new(true), + type_: Cell::new(None), + len: len, + }) + } + + fn serialize_tuple(self, _len: usize) + -> Result<Self::SerializeTuple, Self::Error> { + Err(Error::UnsupportedType) + } + + fn serialize_tuple_struct(self, _name: &'static str, _len: usize) + -> Result<Self::SerializeTupleStruct, Self::Error> { + Err(Error::UnsupportedType) + } + + fn serialize_tuple_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize) + -> Result<Self::SerializeTupleVariant, Self::Error> { + Err(Error::UnsupportedType) + } + + fn serialize_map(self, _len: Option<usize>) + -> Result<Self::SerializeMap, Self::Error> { + self.array_type("table")?; + Ok(SerializeTable::Table { + ser: self, + key: String::new(), + first: Cell::new(true), + table_emitted: Cell::new(false), + }) + } + + fn serialize_struct(self, name: &'static str, _len: usize) + -> Result<Self::SerializeStruct, Self::Error> { + if name == SERDE_STRUCT_NAME { + self.array_type("datetime")?; + Ok(SerializeTable::Datetime(self)) + } else { + self.array_type("table")?; + Ok(SerializeTable::Table { + ser: self, + key: String::new(), + first: Cell::new(true), + table_emitted: Cell::new(false), + }) + } + } + + fn serialize_struct_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize) + -> Result<Self::SerializeStructVariant, Self::Error> { + Err(Error::UnsupportedType) + } +} + +impl<'a, 'b> ser::SerializeSeq for SerializeSeq<'a, 'b> { + type Ok = (); + type Error = Error; + + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where T: ser::Serialize, + { + value.serialize(&mut Serializer { + dst: &mut *self.ser.dst, + state: State::Array { + parent: &self.ser.state, + first: &self.first, + type_: &self.type_, + len: self.len, + }, + settings: self.ser.settings.clone(), + })?; + self.first.set(false); + Ok(()) + } + + fn end(self) -> Result<(), Error> { + match self.type_.get() { + Some("table") => return Ok(()), + Some(_) => { + match (self.len, &self.ser.settings.array) { + (Some(0...1), _) | (_, &None) => { + self.ser.dst.push_str("]"); + }, + (_, &Some(ref a)) => { + if a.trailing_comma { + self.ser.dst.push_str(","); + } + self.ser.dst.push_str("\n]"); + }, + } + } + None => { + assert!(self.first.get()); + self.ser.emit_key("array")?; + self.ser.dst.push_str("[]") + } + } + if let State::Table { .. } = self.ser.state { + self.ser.dst.push_str("\n"); + } + Ok(()) + } +} + +impl<'a, 'b> ser::SerializeMap for SerializeTable<'a, 'b> { + type Ok = (); + type Error = Error; + + fn serialize_key<T: ?Sized>(&mut self, input: &T) -> Result<(), Error> + where T: ser::Serialize, + { + match *self { + SerializeTable::Datetime(_) => panic!(), // shouldn't be possible + SerializeTable::Table { ref mut key, .. } => { + key.truncate(0); + *key = input.serialize(StringExtractor)?; + } + } + Ok(()) + } + + fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), Error> + where T: ser::Serialize, + { + match *self { + SerializeTable::Datetime(_) => panic!(), // shouldn't be possible + SerializeTable::Table { + ref mut ser, + ref key, + ref first, + ref table_emitted, + .. + } => { + let res = value.serialize(&mut Serializer { + dst: &mut *ser.dst, + state: State::Table { + key: key, + parent: &ser.state, + first: first, + table_emitted: table_emitted, + }, + settings: ser.settings.clone(), + }); + match res { + Ok(()) => first.set(false), + Err(Error::UnsupportedNone) => {}, + Err(e) => return Err(e), + } + } + } + Ok(()) + } + + fn end(self) -> Result<(), Error> { + match self { + SerializeTable::Datetime(_) => panic!(), // shouldn't be possible + SerializeTable::Table { ser, first, .. } => { + if first.get() { + let state = ser.state.clone(); + ser.emit_table_header(&state)?; + } + } + } + Ok(()) + } +} + +impl<'a, 'b> ser::SerializeStruct for SerializeTable<'a, 'b> { + type Ok = (); + type Error = Error; + + fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) + -> Result<(), Error> + where T: ser::Serialize, + { + match *self { + SerializeTable::Datetime(ref mut ser) => { + if key == SERDE_STRUCT_FIELD_NAME { + value.serialize(DateStrEmitter(&mut *ser))?; + } else { + return Err(Error::DateInvalid) + } + } + SerializeTable::Table { + ref mut ser, + ref first, + ref table_emitted, + .. + } => { + let res = value.serialize(&mut Serializer { + dst: &mut *ser.dst, + state: State::Table { + key: key, + parent: &ser.state, + first: first, + table_emitted: table_emitted, + }, + settings: ser.settings.clone(), + }); + match res { + Ok(()) => first.set(false), + Err(Error::UnsupportedNone) => {}, + Err(e) => return Err(e), + } + } + } + Ok(()) + } + + fn end(self) -> Result<(), Error> { + match self { + SerializeTable::Datetime(_) => {}, + SerializeTable::Table { ser, first, .. } => { + if first.get() { + let state = ser.state.clone(); + ser.emit_table_header(&state)?; + } + } + } + Ok(()) + } +} + +struct DateStrEmitter<'a: 'b, 'b>(&'b mut Serializer<'a>); + +impl<'a, 'b> ser::Serializer for DateStrEmitter<'a, 'b> { + type Ok = (); + type Error = Error; + type SerializeSeq = ser::Impossible<(), Error>; + type SerializeTuple = ser::Impossible<(), Error>; + type SerializeTupleStruct = ser::Impossible<(), Error>; + type SerializeTupleVariant = ser::Impossible<(), Error>; + type SerializeMap = ser::Impossible<(), Error>; + type SerializeStruct = ser::Impossible<(), Error>; + type SerializeStructVariant = ser::Impossible<(), Error>; + + fn serialize_bool(self, _v: bool) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_i8(self, _v: i8) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_i16(self, _v: i16) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_i32(self, _v: i32) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_i64(self, _v: i64) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_u8(self, _v: u8) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_u16(self, _v: u16) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_u32(self, _v: u32) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_u64(self, _v: u64) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_f32(self, _v: f32) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_f64(self, _v: f64) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_char(self, _v: char) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_str(self, value: &str) -> Result<(), Self::Error> { + self.0.display(value, "datetime")?; + Ok(()) + } + + fn serialize_bytes(self, _value: &[u8]) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_none(self) -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<(), Self::Error> + where T: ser::Serialize + { + Err(Error::KeyNotString) + } + + fn serialize_unit(self) -> Result<(), Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_unit_struct(self, + _name: &'static str) + -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_unit_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str) + -> Result<(), Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, _value: &T) + -> Result<(), Self::Error> + where T: ser::Serialize, + { + Err(Error::DateInvalid) + } + + fn serialize_newtype_variant<T: ?Sized>(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T) + -> Result<(), Self::Error> + where T: ser::Serialize, + { + Err(Error::DateInvalid) + } + + fn serialize_seq(self, _len: Option<usize>) + -> Result<Self::SerializeSeq, Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_tuple(self, _len: usize) + -> Result<Self::SerializeTuple, Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_tuple_struct(self, _name: &'static str, _len: usize) + -> Result<Self::SerializeTupleStruct, Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_tuple_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize) + -> Result<Self::SerializeTupleVariant, Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_map(self, _len: Option<usize>) + -> Result<Self::SerializeMap, Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_struct(self, _name: &'static str, _len: usize) + -> Result<Self::SerializeStruct, Self::Error> { + Err(Error::DateInvalid) + } + + fn serialize_struct_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize) + -> Result<Self::SerializeStructVariant, Self::Error> { + Err(Error::DateInvalid) + } +} + +struct StringExtractor; + +impl ser::Serializer for StringExtractor { + type Ok = String; + type Error = Error; + type SerializeSeq = ser::Impossible<String, Error>; + type SerializeTuple = ser::Impossible<String, Error>; + type SerializeTupleStruct = ser::Impossible<String, Error>; + type SerializeTupleVariant = ser::Impossible<String, Error>; + type SerializeMap = ser::Impossible<String, Error>; + type SerializeStruct = ser::Impossible<String, Error>; + type SerializeStructVariant = ser::Impossible<String, Error>; + + fn serialize_bool(self, _v: bool) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_i8(self, _v: i8) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_i16(self, _v: i16) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_i32(self, _v: i32) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_i64(self, _v: i64) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_u8(self, _v: u8) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_u16(self, _v: u16) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_u32(self, _v: u32) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_u64(self, _v: u64) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_f32(self, _v: f32) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_f64(self, _v: f64) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_char(self, _v: char) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_str(self, value: &str) -> Result<String, Self::Error> { + Ok(value.to_string()) + } + + fn serialize_bytes(self, _value: &[u8]) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_none(self) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_some<T: ?Sized>(self, _value: &T) -> Result<String, Self::Error> + where T: ser::Serialize + { + Err(Error::KeyNotString) + } + + fn serialize_unit(self) -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_unit_struct(self, + _name: &'static str) + -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_unit_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str) + -> Result<String, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_newtype_struct<T: ?Sized>(self, _name: &'static str, _value: &T) + -> Result<String, Self::Error> + where T: ser::Serialize, + { + Err(Error::KeyNotString) + } + + fn serialize_newtype_variant<T: ?Sized>(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T) + -> Result<String, Self::Error> + where T: ser::Serialize, + { + Err(Error::KeyNotString) + } + + fn serialize_seq(self, _len: Option<usize>) + -> Result<Self::SerializeSeq, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_tuple(self, _len: usize) + -> Result<Self::SerializeTuple, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_tuple_struct(self, _name: &'static str, _len: usize) + -> Result<Self::SerializeTupleStruct, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_tuple_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize) + -> Result<Self::SerializeTupleVariant, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_map(self, _len: Option<usize>) + -> Result<Self::SerializeMap, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_struct(self, _name: &'static str, _len: usize) + -> Result<Self::SerializeStruct, Self::Error> { + Err(Error::KeyNotString) + } + + fn serialize_struct_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize) + -> Result<Self::SerializeStructVariant, Self::Error> { + Err(Error::KeyNotString) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + Error::UnsupportedType => "unsupported Rust type".fmt(f), + Error::KeyNotString => "map key was not a string".fmt(f), + Error::ArrayMixedType => "arrays cannot have mixed types".fmt(f), + Error::ValueAfterTable => "values must be emitted before tables".fmt(f), + Error::DateInvalid => "a serialized date was invalid".fmt(f), + Error::NumberInvalid => "a serialized number was invalid".fmt(f), + Error::UnsupportedNone => "unsupported None value".fmt(f), + Error::Custom(ref s) => s.fmt(f), + Error::KeyNewline => unreachable!(), + Error::__Nonexhaustive => panic!(), + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::UnsupportedType => "unsupported Rust type", + Error::KeyNotString => "map key was not a string", + Error::ArrayMixedType => "arrays cannot have mixed types", + Error::ValueAfterTable => "values must be emitted before tables", + Error::DateInvalid => "a serialized date was invalid", + Error::NumberInvalid => "a serialized number was invalid", + Error::UnsupportedNone => "unsupported None value", + Error::Custom(_) => "custom error", + Error::KeyNewline => unreachable!(), + Error::__Nonexhaustive => panic!(), + } + } +} + +impl ser::Error for Error { + fn custom<T: fmt::Display>(msg: T) -> Error { + Error::Custom(msg.to_string()) + } +} + +enum Category { + Primitive, + Array, + Table, +} + +/// Convenience function to serialize items in a map in an order valid with +/// TOML. +/// +/// TOML carries the restriction that keys in a table must be serialized last if +/// their value is a table itself. This isn't always easy to guarantee, so this +/// helper can be used like so: +/// +/// ```rust +/// # #[macro_use] extern crate serde_derive; +/// # extern crate toml; +/// # use std::collections::HashMap; +/// #[derive(Serialize)] +/// struct Manifest { +/// package: Package, +/// #[serde(serialize_with = "toml::ser::tables_last")] +/// dependencies: HashMap<String, Dependency>, +/// } +/// # type Package = String; +/// # type Dependency = String; +/// # fn main() {} +/// ``` +pub fn tables_last<'a, I, K, V, S>(data: &'a I, serializer: S) + -> Result<S::Ok, S::Error> + where &'a I: IntoIterator<Item = (K, V)>, + K: ser::Serialize, + V: ser::Serialize, + S: ser::Serializer +{ + use serde::ser::SerializeMap; + + let mut map = serializer.serialize_map(None)?; + for (k, v) in data { + if let Category::Primitive = v.serialize(Categorize::new())? { + map.serialize_entry(&k, &v)?; + } + } + for (k, v) in data { + if let Category::Array = v.serialize(Categorize::new())? { + map.serialize_entry(&k, &v)?; + } + } + for (k, v) in data { + if let Category::Table = v.serialize(Categorize::new())? { + map.serialize_entry(&k, &v)?; + } + } + map.end() +} + +struct Categorize<E>(marker::PhantomData<E>); + +impl<E> Categorize<E> { + fn new() -> Self { + Categorize(marker::PhantomData) + } +} + +impl<E: ser::Error> ser::Serializer for Categorize<E> { + type Ok = Category; + type Error = E; + type SerializeSeq = Self; + type SerializeTuple = ser::Impossible<Category, E>; + type SerializeTupleStruct = ser::Impossible<Category, E>; + type SerializeTupleVariant = ser::Impossible<Category, E>; + type SerializeMap = Self; + type SerializeStruct = Self; + type SerializeStructVariant = ser::Impossible<Category, E>; + + fn serialize_bool(self, _: bool) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_i8(self, _: i8) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_i16(self, _: i16) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_i32(self, _: i32) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_i64(self, _: i64) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_u8(self, _: u8) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_u16(self, _: u16) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_u32(self, _: u32) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_u64(self, _: u64) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_f32(self, _: f32) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_f64(self, _: f64) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_char(self, _: char) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_str(self, _: &str) -> Result<Self::Ok, Self::Error> { + Ok(Category::Primitive) + } + + fn serialize_bytes(self, _: &[u8]) -> Result<Self::Ok, Self::Error> { + Ok(Category::Array) + } + + fn serialize_none(self) -> Result<Self::Ok, Self::Error> { + Err(ser::Error::custom("unsupported")) + } + + fn serialize_some<T: ?Sized + ser::Serialize>(self, v: &T) -> Result<Self::Ok, Self::Error> { + v.serialize(self) + } + + fn serialize_unit(self) -> Result<Self::Ok, Self::Error> { + Err(ser::Error::custom("unsupported")) + } + + fn serialize_unit_struct(self, _: &'static str) -> Result<Self::Ok, Self::Error> { + Err(ser::Error::custom("unsupported")) + } + + fn serialize_unit_variant(self, _: &'static str, _: u32, _: &'static str) -> Result<Self::Ok, Self::Error> { + Err(ser::Error::custom("unsupported")) + } + + fn serialize_newtype_struct<T: ?Sized + ser::Serialize>(self, _: &'static str, v: &T) -> Result<Self::Ok, Self::Error> { + v.serialize(self) + } + + fn serialize_newtype_variant<T: ?Sized + ser::Serialize>(self, _: &'static str, _: u32, _: &'static str, _: &T) -> Result<Self::Ok, Self::Error> { + Err(ser::Error::custom("unsupported")) + } + + fn serialize_seq(self, _: Option<usize>) -> Result<Self, Self::Error> { + Ok(self) + } + + fn serialize_tuple(self, _: usize) -> Result<Self::SerializeTuple, Self::Error> { + Err(ser::Error::custom("unsupported")) + } + + fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result<Self::SerializeTupleStruct, Self::Error> { + Err(ser::Error::custom("unsupported")) + } + + fn serialize_tuple_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result<Self::SerializeTupleVariant, Self::Error> { + Err(ser::Error::custom("unsupported")) + } + + fn serialize_map(self, _: Option<usize>) -> Result<Self, Self::Error> { + Ok(self) + } + + fn serialize_struct(self, _: &'static str, _: usize) -> Result<Self, Self::Error> { + Ok(self) + } + + fn serialize_struct_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result<Self::SerializeStructVariant, Self::Error> { + Err(ser::Error::custom("unsupported")) + } +} + +impl<E: ser::Error> ser::SerializeSeq for Categorize<E> { + type Ok = Category; + type Error = E; + + fn serialize_element<T: ?Sized + ser::Serialize>(&mut self, _: &T) + -> Result<(), Self::Error> { + Ok(()) + } + + fn end(self) -> Result<Self::Ok, Self::Error> { + Ok(Category::Array) + } +} + +impl<E: ser::Error> ser::SerializeMap for Categorize<E> { + type Ok = Category; + type Error = E; + + fn serialize_key<T: ?Sized + ser::Serialize>(&mut self, _: &T) + -> Result<(), Self::Error> { + Ok(()) + } + + fn serialize_value<T: ?Sized + ser::Serialize>(&mut self, _: &T) + -> Result<(), Self::Error> { + Ok(()) + } + + fn end(self) -> Result<Self::Ok, Self::Error> { + Ok(Category::Table) + } +} + +impl<E: ser::Error> ser::SerializeStruct for Categorize<E> { + type Ok = Category; + type Error = E; + + fn serialize_field<T: ?Sized>(&mut self, + _: &'static str, + _: &T) -> Result<(), Self::Error> + where T: ser::Serialize, + { + Ok(()) + } + + fn end(self) -> Result<Self::Ok, Self::Error> { + Ok(Category::Table) + } +} diff -Nru cargo-0.25.0/vendor/toml-0.4.6/src/tokens.rs cargo-0.26.0/vendor/toml-0.4.6/src/tokens.rs --- cargo-0.25.0/vendor/toml-0.4.6/src/tokens.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/src/tokens.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,620 @@ +use std::borrow::Cow; +use std::char; +use std::str; +use std::string; + +use self::Token::*; + +#[derive(Eq, PartialEq, Debug)] +pub enum Token<'a> { + Whitespace(&'a str), + Newline, + Comment(&'a str), + + Equals, + Period, + Comma, + Colon, + Plus, + LeftBrace, + RightBrace, + LeftBracket, + RightBracket, + + Keylike(&'a str), + String { src: &'a str, val: Cow<'a, str> }, +} + +#[derive(Eq, PartialEq, Debug)] +pub enum Error { + InvalidCharInString(usize, char), + InvalidEscape(usize, char), + InvalidHexEscape(usize, char), + InvalidEscapeValue(usize, u32), + NewlineInString(usize), + Unexpected(usize, char), + UnterminatedString(usize), + NewlineInTableKey(usize), + EmptyTableKey(usize), + Wanted { at: usize, expected: &'static str, found: &'static str }, +} + +#[derive(Clone)] +pub struct Tokenizer<'a> { + input: &'a str, + chars: CrlfFold<'a>, +} + +#[derive(Clone)] +struct CrlfFold<'a> { + chars: str::CharIndices<'a>, +} + +#[derive(Debug)] +enum MaybeString { + NotEscaped(usize), + Owned(string::String), +} + +impl<'a> Tokenizer<'a> { + pub fn new(input: &'a str) -> Tokenizer<'a> { + let mut t = Tokenizer { + input: input, + chars: CrlfFold { + chars: input.char_indices(), + }, + }; + // Eat utf-8 BOM + t.eatc('\u{feff}'); + t + } + + pub fn next(&mut self) -> Result<Option<Token<'a>>, Error> { + let token = match self.chars.next() { + Some((_, '\n')) => Newline, + Some((start, ' ')) => self.whitespace_token(start), + Some((start, '\t')) => self.whitespace_token(start), + Some((start, '#')) => self.comment_token(start), + Some((_, '=')) => Equals, + Some((_, '.')) => Period, + Some((_, ',')) => Comma, + Some((_, ':')) => Colon, + Some((_, '+')) => Plus, + Some((_, '{')) => LeftBrace, + Some((_, '}')) => RightBrace, + Some((_, '[')) => LeftBracket, + Some((_, ']')) => RightBracket, + Some((start, '\'')) => return self.literal_string(start).map(Some), + Some((start, '"')) => return self.basic_string(start).map(Some), + Some((start, ch)) if is_keylike(ch) => self.keylike(start), + + Some((start, ch)) => return Err(Error::Unexpected(start, ch)), + None => return Ok(None), + }; + Ok(Some(token)) + } + + pub fn peek(&mut self) -> Result<Option<Token<'a>>, Error> { + self.clone().next() + } + + pub fn eat(&mut self, expected: Token<'a>) -> Result<bool, Error> { + match self.peek()? { + Some(ref found) if expected == *found => {} + Some(_) => return Ok(false), + None => return Ok(false), + } + drop(self.next()); + Ok(true) + } + + pub fn expect(&mut self, expected: Token<'a>) -> Result<(), Error> { + let current = self.current(); + match self.next()? { + Some(found) => { + if expected == found { + Ok(()) + } else { + Err(Error::Wanted { + at: current, + expected: expected.describe(), + found: found.describe(), + }) + } + } + None => { + Err(Error::Wanted { + at: self.input.len(), + expected: expected.describe(), + found: "eof", + }) + } + } + } + + pub fn table_key(&mut self) -> Result<Cow<'a, str>, Error> { + let current = self.current(); + match self.next()? { + Some(Token::Keylike(k)) => Ok(k.into()), + Some(Token::String { src, val }) => { + let offset = self.substr_offset(src); + if val == "" { + return Err(Error::EmptyTableKey(offset)) + } + match src.find('\n') { + None => Ok(val), + Some(i) => Err(Error::NewlineInTableKey(offset + i)), + } + } + Some(other) => { + Err(Error::Wanted { + at: current, + expected: "a table key", + found: other.describe(), + }) + } + None => { + Err(Error::Wanted { + at: self.input.len(), + expected: "a table key", + found: "eof", + }) + } + } + } + + pub fn eat_whitespace(&mut self) -> Result<(), Error> { + while self.eatc(' ') || self.eatc('\t') { + // ... + } + Ok(()) + } + + pub fn eat_comment(&mut self) -> Result<bool, Error> { + if !self.eatc('#') { + return Ok(false) + } + drop(self.comment_token(0)); + self.eat_newline_or_eof().map(|()| true) + } + + pub fn eat_newline_or_eof(&mut self) -> Result<(), Error> { + let current = self.current(); + match self.next()? { + None | + Some(Token::Newline) => Ok(()), + Some(other) => { + Err(Error::Wanted { + at: current, + expected: "newline", + found: other.describe(), + }) + } + } + } + + pub fn skip_to_newline(&mut self) { + loop { + match self.chars.next() { + Some((_, '\n')) | + None => break, + _ => {} + } + } + } + + fn eatc(&mut self, ch: char) -> bool { + match self.chars.clone().next() { + Some((_, ch2)) if ch == ch2 => { + self.chars.next(); + true + } + _ => false, + } + } + + pub fn current(&mut self) -> usize { + self.chars.clone().next().map(|i| i.0).unwrap_or(self.input.len()) + } + + pub fn input(&self) -> &'a str { + self.input + } + + fn whitespace_token(&mut self, start: usize) -> Token<'a> { + while self.eatc(' ') || self.eatc('\t') { + // ... + } + Whitespace(&self.input[start..self.current()]) + } + + fn comment_token(&mut self, start: usize) -> Token<'a> { + while let Some((_, ch)) = self.chars.clone().next() { + if ch != '\t' && (ch < '\u{20}' || ch > '\u{10ffff}') { + break + } + self.chars.next(); + } + Comment(&self.input[start..self.current()]) + } + + fn read_string(&mut self, + delim: char, + start: usize, + new_ch: &mut FnMut(&mut Tokenizer, &mut MaybeString, + bool, usize, char) + -> Result<(), Error>) + -> Result<Token<'a>, Error> { + let mut multiline = false; + if self.eatc(delim) { + if self.eatc(delim) { + multiline = true; + } else { + return Ok(String { + src: &self.input[start..start+2], + val: Cow::Borrowed(""), + }) + } + } + let mut val = MaybeString::NotEscaped(self.current()); + let mut n = 0; + 'outer: loop { + n += 1; + match self.chars.next() { + Some((i, '\n')) => { + if multiline { + if self.input.as_bytes()[i] == b'\r' { + val.to_owned(&self.input[..i]); + } + if n == 1 { + val = MaybeString::NotEscaped(self.current()); + } else { + val.push('\n'); + } + continue + } else { + return Err(Error::NewlineInString(i)) + } + } + Some((i, ch)) if ch == delim => { + if multiline { + for _ in 0..2 { + if !self.eatc(delim) { + val.push(delim); + continue 'outer + } + } + } + return Ok(String { + src: &self.input[start..self.current()], + val: val.into_cow(&self.input[..i]), + }) + } + Some((i, c)) => try!(new_ch(self, &mut val, multiline, i, c)), + None => return Err(Error::UnterminatedString(start)) + } + } + } + + fn literal_string(&mut self, start: usize) -> Result<Token<'a>, Error> { + self.read_string('\'', start, &mut |_me, val, _multi, i, ch| { + if ch == '\u{09}' || ('\u{20}' <= ch && ch <= '\u{10ffff}') { + val.push(ch); + Ok(()) + } else { + Err(Error::InvalidCharInString(i, ch)) + } + }) + } + + fn basic_string(&mut self, start: usize) -> Result<Token<'a>, Error> { + self.read_string('"', start, &mut |me, val, multi, i, ch| { + match ch { + '\\' => { + val.to_owned(&me.input[..i]); + match me.chars.next() { + Some((_, '"')) => val.push('"'), + Some((_, '\\')) => val.push('\\'), + Some((_, 'b')) => val.push('\u{8}'), + Some((_, 'f')) => val.push('\u{c}'), + Some((_, 'n')) => val.push('\n'), + Some((_, 'r')) => val.push('\r'), + Some((_, 't')) => val.push('\t'), + Some((i, c @ 'u')) | + Some((i, c @ 'U')) => { + let len = if c == 'u' {4} else {8}; + val.push(try!(me.hex(start, i, len))); + } + Some((_, '\n')) if multi => { + while let Some((_, ch)) = me.chars.clone().next() { + match ch { + ' ' | '\t' | '\n' => { + me.chars.next(); + } + _ => break, + } + } + } + Some((i, c)) => return Err(Error::InvalidEscape(i, c)), + None => return Err(Error::UnterminatedString(start)), + } + Ok(()) + } + ch if '\u{20}' <= ch && ch <= '\u{10ffff}' => { + val.push(ch); + Ok(()) + } + _ => Err(Error::InvalidCharInString(i, ch)) + } + }) + } + + fn hex(&mut self, start: usize, i: usize, len: usize) -> Result<char, Error> { + let mut val = 0; + for _ in 0..len { + match self.chars.next() { + Some((_, ch)) if '0' <= ch && ch <= '9' => { + val = val * 16 + (ch as u32 - '0' as u32); + } + Some((_, ch)) if 'A' <= ch && ch <= 'F' => { + val = val * 16 + (ch as u32 - 'A' as u32) + 10; + } + Some((i, ch)) => return Err(Error::InvalidHexEscape(i, ch)), + None => return Err(Error::UnterminatedString(start)), + } + } + match char::from_u32(val) { + Some(ch) => Ok(ch), + None => Err(Error::InvalidEscapeValue(i, val)), + } + } + + fn keylike(&mut self, start: usize) -> Token<'a> { + while let Some((_, ch)) = self.chars.clone().next() { + if !is_keylike(ch) { + break + } + self.chars.next(); + } + Keylike(&self.input[start..self.current()]) + } + + pub fn substr_offset(&self, s: &'a str) -> usize { + assert!(s.len() <= self.input.len()); + let a = self.input.as_ptr() as usize; + let b = s.as_ptr() as usize; + assert!(a <= b); + b - a + } +} + +impl<'a> Iterator for CrlfFold<'a> { + type Item = (usize, char); + + fn next(&mut self) -> Option<(usize, char)> { + self.chars.next().map(|(i, c)| { + if c == '\r' { + let mut attempt = self.chars.clone(); + if let Some((_, '\n')) = attempt.next() { + self.chars = attempt; + return (i, '\n') + } + } + (i, c) + }) + } +} + +impl MaybeString { + fn push(&mut self, ch: char) { + match *self { + MaybeString::NotEscaped(..) => {} + MaybeString::Owned(ref mut s) => s.push(ch), + } + } + + fn to_owned(&mut self, input: &str) { + match *self { + MaybeString::NotEscaped(start) => { + *self = MaybeString::Owned(input[start..].to_owned()); + } + MaybeString::Owned(..) => {} + } + } + + fn into_cow(self, input: &str) -> Cow<str> { + match self { + MaybeString::NotEscaped(start) => Cow::Borrowed(&input[start..]), + MaybeString::Owned(s) => Cow::Owned(s), + } + } +} + +fn is_keylike(ch: char) -> bool { + ('A' <= ch && ch <= 'Z') || + ('a' <= ch && ch <= 'z') || + ('0' <= ch && ch <= '9') || + ch == '-' || + ch == '_' +} + +impl<'a> Token<'a> { + pub fn describe(&self) -> &'static str { + match *self { + Token::Keylike(_) => "an identifier", + Token::Equals => "an equals", + Token::Period => "a period", + Token::Comment(_) => "a comment", + Token::Newline => "a newline", + Token::Whitespace(_) => "whitespace", + Token::Comma => "a comma", + Token::RightBrace => "a right brace", + Token::LeftBrace => "a left brace", + Token::RightBracket => "a right bracket", + Token::LeftBracket => "a left bracket", + Token::String { .. } => "a string", + Token::Colon => "a colon", + Token::Plus => "a plus", + } + } +} + +#[cfg(test)] +mod tests { + use std::borrow::Cow; + use super::{Tokenizer, Token, Error}; + + fn err(input: &str, err: Error) { + let mut t = Tokenizer::new(input); + let token = t.next().unwrap_err(); + assert_eq!(token, err); + assert!(t.next().unwrap().is_none()); + } + + #[test] + fn literal_strings() { + fn t(input: &str, val: &str) { + let mut t = Tokenizer::new(input); + let token = t.next().unwrap().unwrap(); + assert_eq!(token, Token::String { + src: input, + val: Cow::Borrowed(val), + }); + assert!(t.next().unwrap().is_none()); + } + + t("''", ""); + t("''''''", ""); + t("'''\n'''", ""); + t("'a'", "a"); + t("'\"a'", "\"a"); + t("''''a'''", "'a"); + t("'''\n'a\n'''", "'a\n"); + t("'''a\n'a\r\n'''", "a\n'a\n"); + } + + #[test] + fn basic_strings() { + fn t(input: &str, val: &str) { + let mut t = Tokenizer::new(input); + let token = t.next().unwrap().unwrap(); + assert_eq!(token, Token::String { + src: input, + val: Cow::Borrowed(val), + }); + assert!(t.next().unwrap().is_none()); + } + + t(r#""""#, ""); + t(r#""""""""#, ""); + t(r#""a""#, "a"); + t(r#""""a""""#, "a"); + t(r#""\t""#, "\t"); + t(r#""\u0000""#, "\0"); + t(r#""\U00000000""#, "\0"); + t(r#""\U000A0000""#, "\u{A0000}"); + t(r#""\\t""#, "\\t"); + t("\"\"\"\\\n\"\"\"", ""); + t("\"\"\"\\\n \t \t \\\r\n \t \n \t \r\n\"\"\"", ""); + t(r#""\r""#, "\r"); + t(r#""\n""#, "\n"); + t(r#""\b""#, "\u{8}"); + t(r#""a\fa""#, "a\u{c}a"); + t(r#""\"a""#, "\"a"); + t("\"\"\"\na\"\"\"", "a"); + t("\"\"\"\n\"\"\"", ""); + err(r#""\a"#, Error::InvalidEscape(2, 'a')); + err("\"\\\n", Error::InvalidEscape(2, '\n')); + err("\"\\\r\n", Error::InvalidEscape(2, '\n')); + err("\"\\", Error::UnterminatedString(0)); + err("\"\u{0}", Error::InvalidCharInString(1, '\u{0}')); + err(r#""\U00""#, Error::InvalidHexEscape(5, '"')); + err(r#""\U00"#, Error::UnterminatedString(0)); + err(r#""\uD800"#, Error::InvalidEscapeValue(2, 0xd800)); + err(r#""\UFFFFFFFF"#, Error::InvalidEscapeValue(2, 0xffffffff)); + } + + #[test] + fn keylike() { + fn t(input: &str) { + let mut t = Tokenizer::new(input); + let token = t.next().unwrap().unwrap(); + assert_eq!(token, Token::Keylike(input)); + assert!(t.next().unwrap().is_none()); + } + t("foo"); + t("0bar"); + t("bar0"); + t("1234"); + t("a-b"); + t("a_B"); + t("-_-"); + t("___"); + } + + #[test] + fn all() { + fn t(input: &str, expected: &[Token]) { + let mut tokens = Tokenizer::new(input); + let mut actual = Vec::new(); + while let Some(token) = tokens.next().unwrap() { + actual.push(token); + } + for (a, b) in actual.iter().zip(expected) { + assert_eq!(a, b); + } + assert_eq!(actual.len(), expected.len()); + } + + t(" a ", &[ + Token::Whitespace(" "), + Token::Keylike("a"), + Token::Whitespace(" "), + ]); + + t(" a\t [[]] \t [] {} , . =\n# foo \r\n#foo \n ", &[ + Token::Whitespace(" "), + Token::Keylike("a"), + Token::Whitespace("\t "), + Token::LeftBracket, + Token::LeftBracket, + Token::RightBracket, + Token::RightBracket, + Token::Whitespace(" \t "), + Token::LeftBracket, + Token::RightBracket, + Token::Whitespace(" "), + Token::LeftBrace, + Token::RightBrace, + Token::Whitespace(" "), + Token::Comma, + Token::Whitespace(" "), + Token::Period, + Token::Whitespace(" "), + Token::Equals, + Token::Newline, + Token::Comment("# foo "), + Token::Newline, + Token::Comment("#foo "), + Token::Newline, + Token::Whitespace(" "), + ]); + } + + #[test] + fn bare_cr_bad() { + err("\r", Error::Unexpected(0, '\r')); + err("'\n", Error::NewlineInString(1)); + err("'\u{0}", Error::InvalidCharInString(1, '\u{0}')); + err("'", Error::UnterminatedString(0)); + err("\u{0}", Error::Unexpected(0, '\u{0}')); + } + + #[test] + fn bad_comment() { + let mut t = Tokenizer::new("#\u{0}"); + t.next().unwrap().unwrap(); + assert_eq!(t.next(), Err(Error::Unexpected(1, '\u{0}'))); + assert!(t.next().unwrap().is_none()); + } +} diff -Nru cargo-0.25.0/vendor/toml-0.4.6/src/value.rs cargo-0.26.0/vendor/toml-0.4.6/src/value.rs --- cargo-0.25.0/vendor/toml-0.4.6/src/value.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/src/value.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,946 @@ +//! Definition of a TOML value + +use std::collections::{BTreeMap, HashMap}; +use std::hash::Hash; +use std::fmt; +use std::ops; +use std::str::FromStr; +use std::vec; + +use serde::ser; +use serde::de; +use serde::de::IntoDeserializer; + +pub use datetime::{Datetime, DatetimeParseError}; +use datetime::{DatetimeFromString, SERDE_STRUCT_FIELD_NAME}; + +/// Representation of a TOML value. +#[derive(PartialEq, Clone, Debug)] +pub enum Value { + /// Represents a TOML string + String(String), + /// Represents a TOML integer + Integer(i64), + /// Represents a TOML float + Float(f64), + /// Represents a TOML boolean + Boolean(bool), + /// Represents a TOML datetime + Datetime(Datetime), + /// Represents a TOML array + Array(Array), + /// Represents a TOML table + Table(Table), +} + +/// Type representing a TOML array, payload of the `Value::Array` variant +pub type Array = Vec<Value>; + +/// Type representing a TOML table, payload of the `Value::Table` variant +pub type Table = BTreeMap<String, Value>; + +impl Value { + /// Convert a `T` into `toml::Value` which is an enum that can represent + /// any valid TOML data. + /// + /// This conversion can fail if `T`'s implementation of `Serialize` decides to + /// fail, or if `T` contains a map with non-string keys. + pub fn try_from<T>(value: T) -> Result<Value, ::ser::Error> + where T: ser::Serialize, + { + value.serialize(Serializer) + } + + /// Interpret a `toml::Value` as an instance of type `T`. + /// + /// This conversion can fail if the structure of the `Value` does not match the + /// structure expected by `T`, for example if `T` is a struct type but the + /// `Value` contains something other than a TOML table. It can also fail if the + /// structure is correct but `T`'s implementation of `Deserialize` decides that + /// something is wrong with the data, for example required struct fields are + /// missing from the TOML map or some number is too big to fit in the expected + /// primitive type. + pub fn try_into<'de, T>(self) -> Result<T, ::de::Error> + where T: de::Deserialize<'de>, + { + de::Deserialize::deserialize(self) + } + + /// Index into a TOML array or map. A string index can be used to access a + /// value in a map, and a usize index can be used to access an element of an + /// array. + /// + /// Returns `None` if the type of `self` does not match the type of the + /// index, for example if the index is a string and `self` is an array or a + /// number. Also returns `None` if the given key does not exist in the map + /// or the given index is not within the bounds of the array. + pub fn get<I: Index>(&self, index: I) -> Option<&Value> { + index.index(self) + } + + /// Mutably index into a TOML array or map. A string index can be used to + /// access a value in a map, and a usize index can be used to access an + /// element of an array. + /// + /// Returns `None` if the type of `self` does not match the type of the + /// index, for example if the index is a string and `self` is an array or a + /// number. Also returns `None` if the given key does not exist in the map + /// or the given index is not within the bounds of the array. + pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> { + index.index_mut(self) + } + + /// Extracts the integer value if it is an integer. + pub fn as_integer(&self) -> Option<i64> { + match *self { Value::Integer(i) => Some(i), _ => None } + } + + /// Tests whether this value is an integer. + pub fn is_integer(&self) -> bool { + self.as_integer().is_some() + } + + /// Extracts the float value if it is a float. + pub fn as_float(&self) -> Option<f64> { + match *self { Value::Float(f) => Some(f), _ => None } + } + + /// Tests whether this value is a float. + pub fn is_float(&self) -> bool { + self.as_float().is_some() + } + + /// Extracts the boolean value if it is a boolean. + pub fn as_bool(&self) -> Option<bool> { + match *self { Value::Boolean(b) => Some(b), _ => None } + } + + /// Tests whether this value is a boolean. + pub fn is_bool(&self) -> bool { + self.as_bool().is_some() + } + + /// Extracts the string of this value if it is a string. + pub fn as_str(&self) -> Option<&str> { + match *self { Value::String(ref s) => Some(&**s), _ => None } + } + + /// Tests if this value is a string. + pub fn is_str(&self) -> bool { + self.as_str().is_some() + } + + /// Extracts the datetime value if it is a datetime. + /// + /// Note that a parsed TOML value will only contain ISO 8601 dates. An + /// example date is: + /// + /// ```notrust + /// 1979-05-27T07:32:00Z + /// ``` + pub fn as_datetime(&self) -> Option<&Datetime> { + match *self { Value::Datetime(ref s) => Some(s), _ => None } + } + + /// Tests whether this value is a datetime. + pub fn is_datetime(&self) -> bool { + self.as_datetime().is_some() + } + + /// Extracts the array value if it is an array. + pub fn as_array(&self) -> Option<&Vec<Value>> { + match *self { Value::Array(ref s) => Some(s), _ => None } + } + + /// Extracts the array value if it is an array. + pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> { + match *self { Value::Array(ref mut s) => Some(s), _ => None } + } + + /// Tests whether this value is an array. + pub fn is_array(&self) -> bool { + self.as_array().is_some() + } + + /// Extracts the table value if it is a table. + pub fn as_table(&self) -> Option<&Table> { + match *self { Value::Table(ref s) => Some(s), _ => None } + } + + /// Extracts the table value if it is a table. + pub fn as_table_mut(&mut self) -> Option<&mut Table> { + match *self { Value::Table(ref mut s) => Some(s), _ => None } + } + + /// Tests whether this value is a table. + pub fn is_table(&self) -> bool { + self.as_table().is_some() + } + + /// Tests whether this and another value have the same type. + pub fn same_type(&self, other: &Value) -> bool { + match (self, other) { + (&Value::String(..), &Value::String(..)) | + (&Value::Integer(..), &Value::Integer(..)) | + (&Value::Float(..), &Value::Float(..)) | + (&Value::Boolean(..), &Value::Boolean(..)) | + (&Value::Datetime(..), &Value::Datetime(..)) | + (&Value::Array(..), &Value::Array(..)) | + (&Value::Table(..), &Value::Table(..)) => true, + + _ => false, + } + } + + /// Returns a human-readable representation of the type of this value. + pub fn type_str(&self) -> &'static str { + match *self { + Value::String(..) => "string", + Value::Integer(..) => "integer", + Value::Float(..) => "float", + Value::Boolean(..) => "boolean", + Value::Datetime(..) => "datetime", + Value::Array(..) => "array", + Value::Table(..) => "table", + } + } +} + +impl<I> ops::Index<I> for Value where I: Index { + type Output = Value; + + fn index(&self, index: I) -> &Value { + self.get(index).expect("index not found") + } +} + +impl<I> ops::IndexMut<I> for Value where I: Index { + fn index_mut(&mut self, index: I) -> &mut Value { + self.get_mut(index).expect("index not found") + } +} + +impl<'a> From<&'a str> for Value { + #[inline] + fn from(val: &'a str) -> Value { + Value::String(val.to_string()) + } +} + +impl<V: Into<Value>> From<Vec<V>> for Value { + fn from(val: Vec<V>) -> Value { + Value::Array(val.into_iter().map(|v| v.into()).collect()) + } +} + +impl<S: Into<String>, V: Into<Value>> From<BTreeMap<S, V>> for Value { + fn from(val: BTreeMap<S, V>) -> Value { + let table = val.into_iter() + .map(|(s, v)| (s.into(), v.into())) + .collect(); + + Value::Table(table) + } +} + +impl<S: Into<String> + Hash + Eq, V: Into<Value>> From<HashMap<S, V>> for Value { + fn from(val: HashMap<S, V>) -> Value { + let table = val.into_iter() + .map(|(s, v)| (s.into(), v.into())) + .collect(); + + Value::Table(table) + } +} + +macro_rules! impl_into_value { + ($variant:ident : $T:ty) => { + impl From<$T> for Value { + #[inline] + fn from(val: $T) -> Value { + Value::$variant(val.into()) + } + } + } +} + +impl_into_value!(String: String); +impl_into_value!(Integer: i64); +impl_into_value!(Integer: i32); +impl_into_value!(Integer: i8); +impl_into_value!(Integer: u8); +impl_into_value!(Integer: u32); +impl_into_value!(Float: f64); +impl_into_value!(Float: f32); +impl_into_value!(Boolean: bool); +impl_into_value!(Datetime: Datetime); + +/// Types that can be used to index a `toml::Value` +/// +/// Currently this is implemented for `usize` to index arrays and `str` to index +/// tables. +/// +/// This trait is sealed and not intended for implementation outside of the +/// `toml` crate. +pub trait Index: Sealed { + #[doc(hidden)] + fn index<'a>(&self, val: &'a Value) -> Option<&'a Value>; + #[doc(hidden)] + fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value>; +} + +/// An implementation detail that should not be implemented, this will change in +/// the future and break code otherwise. +#[doc(hidden)] +pub trait Sealed {} +impl Sealed for usize {} +impl Sealed for str {} +impl Sealed for String {} +impl<'a, T: Sealed + ?Sized> Sealed for &'a T {} + +impl Index for usize { + fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { + match *val { + Value::Array(ref a) => a.get(*self), + _ => None, + } + } + + fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { + match *val { + Value::Array(ref mut a) => a.get_mut(*self), + _ => None, + } + } +} + +impl Index for str { + fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { + match *val { + Value::Table(ref a) => a.get(self), + _ => None, + } + } + + fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { + match *val { + Value::Table(ref mut a) => a.get_mut(self), + _ => None, + } + } +} + +impl Index for String { + fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { + self[..].index(val) + } + + fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { + self[..].index_mut(val) + } +} + +impl<'s, T: ?Sized> Index for &'s T where T: Index { + fn index<'a>(&self, val: &'a Value) -> Option<&'a Value> { + (**self).index(val) + } + + fn index_mut<'a>(&self, val: &'a mut Value) -> Option<&'a mut Value> { + (**self).index_mut(val) + } +} + +impl fmt::Display for Value { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + ::ser::to_string(self).expect("Unable to represent value as string").fmt(f) + } +} + +impl FromStr for Value { + type Err = ::de::Error; + fn from_str(s: &str) -> Result<Value, Self::Err> { + ::from_str(s) + } +} + +impl ser::Serialize for Value { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where S: ser::Serializer + { + use serde::ser::SerializeMap; + + match *self { + Value::String(ref s) => serializer.serialize_str(s), + Value::Integer(i) => serializer.serialize_i64(i), + Value::Float(f) => serializer.serialize_f64(f), + Value::Boolean(b) => serializer.serialize_bool(b), + Value::Datetime(ref s) => s.serialize(serializer), + Value::Array(ref a) => a.serialize(serializer), + Value::Table(ref t) => { + let mut map = serializer.serialize_map(Some(t.len()))?; + // Be sure to visit non-tables first (and also non + // array-of-tables) as all keys must be emitted first. + for (k, v) in t { + if !v.is_table() && !v.is_array() || + (v.as_array().map(|a| !a.iter().any(|v| v.is_table())).unwrap_or(false)) { + map.serialize_entry(k, v)?; + } + } + for (k, v) in t { + if v.as_array().map(|a| a.iter().any(|v| v.is_table())).unwrap_or(false) { + map.serialize_entry(k, v)?; + } + } + for (k, v) in t { + if v.is_table() { + map.serialize_entry(k, v)?; + } + } + map.end() + } + } + } +} + +impl<'de> de::Deserialize<'de> for Value { + fn deserialize<D>(deserializer: D) -> Result<Value, D::Error> + where D: de::Deserializer<'de>, + { + struct ValueVisitor; + + impl<'de> de::Visitor<'de> for ValueVisitor { + type Value = Value; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("any valid TOML value") + } + + fn visit_bool<E>(self, value: bool) -> Result<Value, E> { + Ok(Value::Boolean(value)) + } + + fn visit_i64<E>(self, value: i64) -> Result<Value, E> { + Ok(Value::Integer(value)) + } + + fn visit_f64<E>(self, value: f64) -> Result<Value, E> { + Ok(Value::Float(value)) + } + + fn visit_str<E>(self, value: &str) -> Result<Value, E> { + Ok(Value::String(value.into())) + } + + fn visit_string<E>(self, value: String) -> Result<Value, E> { + Ok(Value::String(value)) + } + + fn visit_some<D>(self, deserializer: D) -> Result<Value, D::Error> + where D: de::Deserializer<'de>, + { + de::Deserialize::deserialize(deserializer) + } + + fn visit_seq<V>(self, mut visitor: V) -> Result<Value, V::Error> + where V: de::SeqAccess<'de>, + { + let mut vec = Vec::new(); + while let Some(elem) = try!(visitor.next_element()) { + vec.push(elem); + } + Ok(Value::Array(vec)) + } + + fn visit_map<V>(self, mut visitor: V) -> Result<Value, V::Error> + where V: de::MapAccess<'de>, + { + let mut key = String::new(); + let datetime = visitor.next_key_seed(DatetimeOrTable { + key: &mut key, + })?; + match datetime { + Some(true) => { + let date: DatetimeFromString = visitor.next_value()?; + return Ok(Value::Datetime(date.value)) + } + None => return Ok(Value::Table(BTreeMap::new())), + Some(false) => {} + } + let mut map = BTreeMap::new(); + map.insert(key, visitor.next_value()?); + while let Some(key) = visitor.next_key()? { + if map.contains_key(&key) { + let msg = format!("duplicate key: `{}`", key); + return Err(de::Error::custom(msg)) + } + map.insert(key, visitor.next_value()?); + } + Ok(Value::Table(map)) + } + } + + deserializer.deserialize_any(ValueVisitor) + } +} + +impl<'de> de::Deserializer<'de> for Value { + type Error = ::de::Error; + + fn deserialize_any<V>(self, visitor: V) -> Result<V::Value, ::de::Error> + where V: de::Visitor<'de>, + { + match self { + Value::Boolean(v) => visitor.visit_bool(v), + Value::Integer(n) => visitor.visit_i64(n), + Value::Float(n) => visitor.visit_f64(n), + Value::String(v) => visitor.visit_string(v), + Value::Datetime(v) => visitor.visit_string(v.to_string()), + Value::Array(v) => { + let len = v.len(); + let mut deserializer = SeqDeserializer::new(v); + let seq = visitor.visit_seq(&mut deserializer)?; + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(seq) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in array")) + } + } + Value::Table(v) => { + let len = v.len(); + let mut deserializer = MapDeserializer::new(v); + let map = visitor.visit_map(&mut deserializer)?; + let remaining = deserializer.iter.len(); + if remaining == 0 { + Ok(map) + } else { + Err(de::Error::invalid_length(len, &"fewer elements in map")) + } + } + } + } + + #[inline] + fn deserialize_enum<V>( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result<V::Value, ::de::Error> + where + V: de::Visitor<'de>, + { + match self { + Value::String(variant) => visitor.visit_enum(variant.into_deserializer()), + _ => Err(de::Error::invalid_type(de::Unexpected::UnitVariant, &"string only")), + } + } + + // `None` is interpreted as a missing field so be sure to implement `Some` + // as a present field. + fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, ::de::Error> + where V: de::Visitor<'de>, + { + visitor.visit_some(self) + } + + fn deserialize_newtype_struct<V>( + self, + _name: &'static str, + visitor: V + ) -> Result<V::Value, ::de::Error> + where V: de::Visitor<'de> + { + visitor.visit_newtype_struct(self) + } + + forward_to_deserialize_any! { + bool u8 u16 u32 u64 i8 i16 i32 i64 f32 f64 char str string unit seq + bytes byte_buf map unit_struct tuple_struct struct + tuple ignored_any identifier + } +} + +struct SeqDeserializer { + iter: vec::IntoIter<Value>, +} + +impl SeqDeserializer { + fn new(vec: Vec<Value>) -> Self { + SeqDeserializer { + iter: vec.into_iter(), + } + } +} + +impl<'de> de::SeqAccess<'de> for SeqDeserializer { + type Error = ::de::Error; + + fn next_element_seed<T>(&mut self, seed: T) + -> Result<Option<T::Value>, ::de::Error> + where T: de::DeserializeSeed<'de>, + { + match self.iter.next() { + Some(value) => seed.deserialize(value).map(Some), + None => Ok(None), + } + } + + fn size_hint(&self) -> Option<usize> { + match self.iter.size_hint() { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } + } +} + +struct MapDeserializer { + iter: <BTreeMap<String, Value> as IntoIterator>::IntoIter, + value: Option<(String, Value)>, +} + +impl MapDeserializer { + fn new(map: BTreeMap<String, Value>) -> Self { + MapDeserializer { + iter: map.into_iter(), + value: None, + } + } +} + +impl<'de> de::MapAccess<'de> for MapDeserializer { + type Error = ::de::Error; + + fn next_key_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>, ::de::Error> + where T: de::DeserializeSeed<'de>, + { + match self.iter.next() { + Some((key, value)) => { + self.value = Some((key.clone(), value)); + seed.deserialize(Value::String(key)).map(Some) + } + None => Ok(None), + } + } + + fn next_value_seed<T>(&mut self, seed: T) -> Result<T::Value, ::de::Error> + where T: de::DeserializeSeed<'de>, + { + let (key, res) = match self.value.take() { + Some((key, value)) => (key, seed.deserialize(value)), + None => return Err(de::Error::custom("value is missing")), + }; + res.map_err(|mut error| { + error.add_key_context(&key); + error + }) + } + + fn size_hint(&self) -> Option<usize> { + match self.iter.size_hint() { + (lower, Some(upper)) if lower == upper => Some(upper), + _ => None, + } + } +} + +impl<'de> de::IntoDeserializer<'de, ::de::Error> for Value { + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +struct Serializer; + +impl ser::Serializer for Serializer { + type Ok = Value; + type Error = ::ser::Error; + + type SerializeSeq = SerializeVec; + type SerializeTuple = ser::Impossible<Value, ::ser::Error>; + type SerializeTupleStruct = ser::Impossible<Value, ::ser::Error>; + type SerializeTupleVariant = ser::Impossible<Value, ::ser::Error>; + type SerializeMap = SerializeMap; + type SerializeStruct = SerializeMap; + type SerializeStructVariant = ser::Impossible<Value, ::ser::Error>; + + fn serialize_bool(self, value: bool) -> Result<Value, ::ser::Error> { + Ok(Value::Boolean(value)) + } + + fn serialize_i8(self, value: i8) -> Result<Value, ::ser::Error> { + self.serialize_i64(value.into()) + } + + fn serialize_i16(self, value: i16) -> Result<Value, ::ser::Error> { + self.serialize_i64(value.into()) + } + + fn serialize_i32(self, value: i32) -> Result<Value, ::ser::Error> { + self.serialize_i64(value.into()) + } + + fn serialize_i64(self, value: i64) -> Result<Value, ::ser::Error> { + Ok(Value::Integer(value.into())) + } + + fn serialize_u8(self, value: u8) -> Result<Value, ::ser::Error> { + self.serialize_i64(value.into()) + } + + fn serialize_u16(self, value: u16) -> Result<Value, ::ser::Error> { + self.serialize_i64(value.into()) + } + + fn serialize_u32(self, value: u32) -> Result<Value, ::ser::Error> { + self.serialize_i64(value.into()) + } + + fn serialize_u64(self, value: u64) -> Result<Value, ::ser::Error> { + if value <= i64::max_value() as u64 { + self.serialize_i64(value as i64) + } else { + Err(ser::Error::custom("u64 value was too large")) + } + } + + fn serialize_f32(self, value: f32) -> Result<Value, ::ser::Error> { + self.serialize_f64(value.into()) + } + + fn serialize_f64(self, value: f64) -> Result<Value, ::ser::Error> { + Ok(Value::Float(value)) + } + + fn serialize_char(self, value: char) -> Result<Value, ::ser::Error> { + let mut s = String::new(); + s.push(value); + self.serialize_str(&s) + } + + fn serialize_str(self, value: &str) -> Result<Value, ::ser::Error> { + Ok(Value::String(value.to_owned())) + } + + fn serialize_bytes(self, value: &[u8]) -> Result<Value, ::ser::Error> { + let vec = value.iter().map(|&b| Value::Integer(b.into())).collect(); + Ok(Value::Array(vec)) + } + + fn serialize_unit(self) -> Result<Value, ::ser::Error> { + Err(::ser::Error::UnsupportedType) + } + + fn serialize_unit_struct(self, _name: &'static str) + -> Result<Value, ::ser::Error> { + Err(::ser::Error::UnsupportedType) + } + + fn serialize_unit_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str) + -> Result<Value, ::ser::Error> { + self.serialize_str(_variant) + } + + fn serialize_newtype_struct<T: ?Sized>(self, + _name: &'static str, + value: &T) + -> Result<Value, ::ser::Error> + where T: ser::Serialize, + { + value.serialize(self) + } + + fn serialize_newtype_variant<T: ?Sized>(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T) + -> Result<Value, ::ser::Error> + where T: ser::Serialize, + { + Err(::ser::Error::UnsupportedType) + } + + fn serialize_none(self) -> Result<Value, ::ser::Error> { + Err(::ser::Error::UnsupportedNone) + } + + fn serialize_some<T: ?Sized>(self, value: &T) -> Result<Value, ::ser::Error> + where T: ser::Serialize, + { + value.serialize(self) + } + + fn serialize_seq(self, len: Option<usize>) + -> Result<Self::SerializeSeq, ::ser::Error> + { + Ok(SerializeVec { + vec: Vec::with_capacity(len.unwrap_or(0)) + }) + } + + fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, ::ser::Error> { + Err(::ser::Error::UnsupportedType) + } + + fn serialize_tuple_struct(self, _name: &'static str, _len: usize) + -> Result<Self::SerializeTupleStruct, ::ser::Error> { + Err(::ser::Error::UnsupportedType) + } + + fn serialize_tuple_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize) + -> Result<Self::SerializeTupleVariant, ::ser::Error> + { + Err(::ser::Error::UnsupportedType) + } + + fn serialize_map(self, _len: Option<usize>) + -> Result<Self::SerializeMap, ::ser::Error> + { + Ok(SerializeMap { + map: BTreeMap::new(), + next_key: None, + }) + } + + fn serialize_struct(self, _name: &'static str, len: usize) + -> Result<Self::SerializeStruct, ::ser::Error> { + self.serialize_map(Some(len)) + } + + fn serialize_struct_variant(self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize) + -> Result<Self::SerializeStructVariant, ::ser::Error> + { + Err(::ser::Error::UnsupportedType) + } +} + +struct SerializeVec { + vec: Vec<Value>, +} + +struct SerializeMap { + map: BTreeMap<String, Value>, + next_key: Option<String>, +} + +impl ser::SerializeSeq for SerializeVec { + type Ok = Value; + type Error = ::ser::Error; + + fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error> + where T: ser::Serialize + { + self.vec.push(Value::try_from(value)?); + Ok(()) + } + + fn end(self) -> Result<Value, ::ser::Error> { + Ok(Value::Array(self.vec)) + } +} + +impl ser::SerializeMap for SerializeMap { + type Ok = Value; + type Error = ::ser::Error; + + fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<(), ::ser::Error> + where T: ser::Serialize + { + match Value::try_from(key)? { + Value::String(s) => self.next_key = Some(s), + _ => return Err(::ser::Error::KeyNotString), + }; + Ok(()) + } + + fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<(), ::ser::Error> + where T: ser::Serialize + { + let key = self.next_key.take(); + let key = key.expect("serialize_value called before serialize_key"); + match Value::try_from(value) { + Ok(value) => { self.map.insert(key, value); } + Err(::ser::Error::UnsupportedNone) => {} + Err(e) => return Err(e), + } + Ok(()) + } + + fn end(self) -> Result<Value, ::ser::Error> { + Ok(Value::Table(self.map)) + } +} + +impl ser::SerializeStruct for SerializeMap { + type Ok = Value; + type Error = ::ser::Error; + + fn serialize_field<T: ?Sized>(&mut self, key: &'static str, value: &T) -> Result<(), ::ser::Error> + where T: ser::Serialize + { + try!(ser::SerializeMap::serialize_key(self, key)); + ser::SerializeMap::serialize_value(self, value) + } + + fn end(self) -> Result<Value, ::ser::Error> { + ser::SerializeMap::end(self) + } +} + +struct DatetimeOrTable<'a> { + key: &'a mut String, +} + +impl<'a, 'de> de::DeserializeSeed<'de> for DatetimeOrTable<'a> { + type Value = bool; + + fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error> + where D: de::Deserializer<'de> + { + deserializer.deserialize_any(self) + } +} + +impl<'a, 'de> de::Visitor<'de> for DatetimeOrTable<'a> { + type Value = bool; + + fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str("a string key") + } + + fn visit_str<E>(self, s: &str) -> Result<bool, E> + where E: de::Error, + { + if s == SERDE_STRUCT_FIELD_NAME { + Ok(true) + } else { + self.key.push_str(s); + Ok(false) + } + } + + fn visit_string<E>(self, s: String) -> Result<bool, E> + where E: de::Error, + { + if s == SERDE_STRUCT_FIELD_NAME { + Ok(true) + } else { + *self.key = s; + Ok(false) + } + } +} diff -Nru cargo-0.25.0/vendor/toml-0.4.6/.travis.yml cargo-0.26.0/vendor/toml-0.4.6/.travis.yml --- cargo-0.25.0/vendor/toml-0.4.6/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/toml-0.4.6/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,30 @@ +language: rust +rust: + - 1.15.0 + - stable + - beta + - nightly +sudo: false +before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH +script: + - cargo test + - cargo test --manifest-path test-suite/Cargo.toml + - rustdoc --test README.md -L target + - test "$TRAVIS_RUST_VERSION" != "1.15.0" && cargo doc --no-deps || echo "skipping cargo doc" +after_success: + - travis-cargo --only nightly doc-upload + - travis-cargo coveralls --no-sudo +env: + global: + secure: "IDm3Oc3bmIL4/6zixovwkuTkbinqWnKdLfeuKTtHqT4ZbVy+rxTDQBgLGfVngymjciHWkJnvQ8/2nT3/KW4MPNY9Sqt3NfWvO7vj9cXypeNeJ4xFrVK49F7CMM4KTCeSMlDKR1C0TVYGgxFIViLtBw/imivl9fk6J489eKv36sA=" + +notifications: + email: + on_success: never +addons: + apt: + packages: + - libcurl4-openssl-dev + - libelf-dev + - libdw-dev diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/.cargo-checksum.json cargo-0.26.0/vendor/ucd-util-0.1.1/.cargo-checksum.json --- cargo-0.25.0/vendor/ucd-util-0.1.1/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"fd2be2d6639d0f8fe6cdda291ad456e23629558d466e2789d2c3e9892bda285d"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/Cargo.toml cargo-0.26.0/vendor/ucd-util-0.1.1/Cargo.toml --- cargo-0.25.0/vendor/ucd-util-0.1.1/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,23 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "ucd-util" +version = "0.1.1" +authors = ["Andrew Gallant <jamslam@gmail.com>"] +description = "A small utility library for working with the Unicode character database.\n" +homepage = "https://github.com/BurntSushi/rucd" +documentation = "https://github.com/BurntSushi/rucd" +readme = "README.md" +keywords = ["unicode", "database", "character", "property"] +license = "MIT/Apache-2.0" +repository = "https://github.com/BurntSushi/rucd" diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/LICENSE-APACHE cargo-0.26.0/vendor/ucd-util-0.1.1/LICENSE-APACHE --- cargo-0.25.0/vendor/ucd-util-0.1.1/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/LICENSE-MIT cargo-0.26.0/vendor/ucd-util-0.1.1/LICENSE-MIT --- cargo-0.25.0/vendor/ucd-util-0.1.1/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +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. diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/README.md cargo-0.26.0/vendor/ucd-util-0.1.1/README.md --- cargo-0.25.0/vendor/ucd-util-0.1.1/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,23 @@ +ucd-util +======== +A library for small auxiliary Unicode functions. This includes things like +symbol or character name canonicalization, ideograph name generation and helper +functions for searching property name and value tables. + +[![Linux build status](https://api.travis-ci.org/BurntSushi/ucd-generate.png)](https://travis-ci.org/BurntSushi/ucd-generate) +[![](http://meritbadge.herokuapp.com/ucd-generate)](https://crates.io/crates/ucd-util) + + +### Documentation + +https://docs.rs/ucd-util + + +### License + +This project is 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. diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/src/hangul.rs cargo-0.26.0/vendor/ucd-util-0.1.1/src/hangul.rs --- cargo-0.25.0/vendor/ucd-util-0.1.1/src/hangul.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/src/hangul.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,105 @@ +use unicode_tables::jamo_short_name::JAMO_SHORT_NAME; + +// This implementation should correspond to the algorithms described in +// Unicode 3.12. + +/// A set of ranges that corresponds to the set of all Hangul syllable +/// codepoints. +/// +/// These ranges are defined in Unicode 4.8 Table 4-13. +pub const RANGE_HANGUL_SYLLABLE: &'static [(u32, u32)] = &[ + (0xAC00, 0xD7A3), +]; + +const S_BASE: u32 = 0xAC00; +const L_BASE: u32 = 0x1100; +const V_BASE: u32 = 0x1161; +const T_BASE: u32 = 0x11A7; +const T_COUNT: u32 = 28; +const N_COUNT: u32 = 588; + +/// Return the character name of the given precomposed Hangul codepoint. +/// +/// If the given codepoint does not correspond to a precomposed Hangul +/// codepoint in the inclusive range `AC00..D7A3`, then this returns `None`. +/// +/// This implements the algorithms described in Unicode 3.12 and Unicode 4.8. +pub fn hangul_name(cp: u32) -> Option<String> { + let mut name = "HANGUL SYLLABLE ".to_string(); + let (lpart, vpart, tpart) = match hangul_full_canonical_decomposition(cp) { + None => return None, + Some(triple) => triple, + }; + + name.push_str(jamo_short_name(lpart)); + name.push_str(jamo_short_name(vpart)); + name.push_str(tpart.map_or("", jamo_short_name)); + Some(name) +} + +/// Return the full canonical decomposition of the given precomposed Hangul +/// codepoint. +/// +/// If the decomposition does not have any trailing consonant, then the third +/// part of the tuple returned is `None`. +/// +/// If the given codepoint does not correspond to a precomposed Hangul +/// codepoint in the inclusive range `AC00..D7A3`, then this returns `None`. +/// +/// This implements the algorithms described in Unicode 3.12 and Unicode 4.8. +pub fn hangul_full_canonical_decomposition( + cp: u32, +) -> Option<(u32, u32, Option<u32>)> { + if !(0xAC00 <= cp && cp <= 0xD7A3) { + return None; + } + + let s_index = cp - S_BASE; + let l_index = s_index / N_COUNT; + let v_index = (s_index % N_COUNT) / T_COUNT; + let t_index = s_index % T_COUNT; + + let l_part = L_BASE + l_index; + let v_part = V_BASE + v_index; + let t_part = + if t_index == 0 { + None + } else { + Some(T_BASE + t_index) + }; + Some((l_part, v_part, t_part)) +} + +fn jamo_short_name(cp: u32) -> &'static str { + let i = JAMO_SHORT_NAME.binary_search_by_key(&cp, |p| p.0).unwrap(); + JAMO_SHORT_NAME[i].1 +} + +#[cfg(test)] +mod tests { + use super::{hangul_name, hangul_full_canonical_decomposition}; + + #[test] + fn canon_decomp() { + assert_eq!( + hangul_full_canonical_decomposition(0xD4DB), + Some((0x1111, 0x1171, Some(0x11B6)))); + } + + #[test] + fn name() { + assert_eq!(hangul_name(0xD4DB).unwrap(), "HANGUL SYLLABLE PWILH"); + } + + #[test] + fn all() { + for cp in 0xAC00..(0xD7A3 + 1) { + hangul_name(cp).unwrap(); + } + } + + #[test] + fn invalid() { + assert!(hangul_name(0).is_none()); + } +} diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/src/ideograph.rs cargo-0.26.0/vendor/ucd-util-0.1.1/src/ideograph.rs --- cargo-0.25.0/vendor/ucd-util-0.1.1/src/ideograph.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/src/ideograph.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,83 @@ +/// A set of ranges that corresponds to the set of all ideograph codepoints. +/// +/// These ranges are defined in Unicode 4.8 Table 4-13. +pub const RANGE_IDEOGRAPH: &'static [(u32, u32)] = &[ + (0x3400, 0x4DB5), + (0x4E00, 0x9FD5), + (0x4E00, 0x9FD5), + (0x20000, 0x2A6D6), + (0x2A700, 0x2B734), + (0x2B740, 0x2B81D), + (0x2B820, 0x2CEA1), + (0x17000, 0x187EC), + (0xF900, 0xFA6D), + (0xFA70, 0xFAD9), + (0x2F800, 0x2FA1D), +]; + +/// Return the character name of the given ideograph codepoint. +/// +/// This operation is only defined on ideographic codepoints. This includes +/// precisely the following inclusive ranges: +/// +/// * `3400..4DB5` +/// * `4E00..9FD5` +/// * `20000..2A6D6` +/// * `2A700..2B734` +/// * `2B740..2B81D` +/// * `2B820..2CEA1` +/// * `17000..187EC` +/// * `F900..FA6D` +/// * `FA70..FAD9` +/// * `2F800..2FA1D` +/// +/// If the given codepoint is not in any of the above ranges, then `None` is +/// returned. +/// +/// This implements the algorithm described in Unicode 4.8. +pub fn ideograph_name(cp: u32) -> Option<String> { + // This match should be in sync with the `RANGE_IDEOGRAPH` constant. + match cp { + 0x3400...0x4DB5 + | 0x4E00...0x9FD5 + | 0x20000...0x2A6D6 + | 0x2A700...0x2B734 + | 0x2B740...0x2B81D + | 0x2B820...0x2CEA1 => { + Some(format!("CJK UNIFIED IDEOGRAPH-{:04X}", cp)) + } + 0x17000...0x187EC => { + Some(format!("TANGUT IDEOGRAPH-{:04X}", cp)) + } + 0xF900...0xFA6D | 0xFA70...0xFAD9 | 0x2F800...0x2FA1D => { + Some(format!("CJK COMPATIBILITY IDEOGRAPH-{:04X}", cp)) + } + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::ideograph_name; + + #[test] + fn name() { + assert_eq!( + ideograph_name(0x4E00).unwrap(), + "CJK UNIFIED IDEOGRAPH-4E00"); + assert_eq!( + ideograph_name(0x9FD5).unwrap(), + "CJK UNIFIED IDEOGRAPH-9FD5"); + assert_eq!( + ideograph_name(0x17000).unwrap(), + "TANGUT IDEOGRAPH-17000"); + assert_eq!( + ideograph_name(0xF900).unwrap(), + "CJK COMPATIBILITY IDEOGRAPH-F900"); + } + + #[test] + fn invalid() { + assert!(ideograph_name(0).is_none()); + } +} diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/src/lib.rs cargo-0.26.0/vendor/ucd-util-0.1.1/src/lib.rs --- cargo-0.25.0/vendor/ucd-util-0.1.1/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,28 @@ +/*! +The `ucd-util` crate contains a smattering of utility functions that implement +various algorithms specified by Unicode. There is no specific goal for +exhaustiveness. Instead, implementations should be added on an as-needed basis. + +A *current* design constraint of this crate is that it should not bring in any +large Unicode tables. For example, to use the various property name and value +canonicalization functions, you'll need to supply your own table, which can +be generated using `ucd-generate`. +*/ + +#![deny(missing_docs)] + +mod hangul; +mod ideograph; +mod name; +mod property; +mod unicode_tables; + +pub use hangul::{ + RANGE_HANGUL_SYLLABLE, hangul_name, hangul_full_canonical_decomposition, +}; +pub use ideograph::{RANGE_IDEOGRAPH, ideograph_name}; +pub use name::{character_name_normalize, symbolic_name_normalize}; +pub use property::{ + PropertyTable, PropertyValueTable, PropertyValues, + canonical_property_name, property_values, canonical_property_value, +}; diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/src/name.rs cargo-0.26.0/vendor/ucd-util-0.1.1/src/name.rs --- cargo-0.25.0/vendor/ucd-util-0.1.1/src/name.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/src/name.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,180 @@ +/// Normalize the given character name in place according to UAX44-LM2. +/// +/// See: http://unicode.org/reports/tr44/#UAX44-LM2 +pub fn character_name_normalize(string: &mut String) { + let bytes = unsafe { + // SAFETY: `character_name_normalize_bytes` guarantees that + // `bytes[..len]` is valid UTF-8. + string.as_mut_vec() + }; + let len = character_name_normalize_bytes(bytes).len(); + bytes.truncate(len); +} + +/// Normalize the given character name in place according to UAX44-LM2. +/// +/// The slice returned is guaranteed to be valid UTF-8 for all possible values +/// of `slice`. +/// +/// See: http://unicode.org/reports/tr44/#UAX44-LM2 +fn character_name_normalize_bytes(slice: &mut [u8]) -> &mut [u8] { + // According to Unicode 4.8, character names consist only of Latin + // capital letters A to Z, ASCII digits, ASCII space or ASCII hypen. + // Therefore, we can do very simplistic case folding and operate on the + // raw bytes, since everything is ASCII. Note that we don't actually know + // whether `slice` is all ASCII or not, so we drop all non-ASCII bytes. + let mut next_write = 0; + let mut prev_space = true; + for i in 0..slice.len() { + // SAFETY ARGUMENT: To guarantee that the resulting slice is valid + // UTF-8, we ensure that the slice contains only ASCII bytes. In + // particular, we drop every non-ASCII byte from the normalized string. + let b = slice[i]; + if b == b' ' { + prev_space = true; + continue; + } else if b == b'_' { + // Drop the underscore. + } else if b == b'-' { + let mut keep_hyphen = prev_space || slice.get(i+1) == Some(&b' '); + // We want to keep the hypen only if it isn't medial, which means + // it has at least one adjacent space character. However, there + // is one exception. We need to keep the hypen in the character + // (U+1180) named `HANGUL JUNGSEONG O-E`. So we check for that + // here. + let rest_e = slice[i+1..] == b"E"[..] || slice[i+1..] == b"e"[..]; + if !keep_hyphen && rest_e { + keep_hyphen = slice[..next_write] == b"hanguljungseongo"[..]; + } + if keep_hyphen { + slice[next_write] = b; + next_write += 1; + } + } else if b'A' <= b && b <= b'Z' { + slice[next_write] = b + (b'a' - b'A'); + next_write += 1; + } else if b <= 0x7F { + slice[next_write] = b; + next_write += 1; + } + prev_space = false; + } + &mut slice[..next_write] +} + +/// Normalize the given symbolic name in place according to UAX44-LM3. +/// +/// A "symbolic name" typically corresponds to property names and property +/// value aliases. Note, though, that it should not be applied to property +/// string values. +/// +/// See: http://unicode.org/reports/tr44/#UAX44-LM2 +pub fn symbolic_name_normalize(string: &mut String) { + let bytes = unsafe { + // SAFETY: `symbolic_name_normalize_bytes` guarantees that + // `bytes[..len]` is valid UTF-8. + string.as_mut_vec() + }; + let len = symbolic_name_normalize_bytes(bytes).len(); + bytes.truncate(len); +} + +/// Normalize the given symbolic name in place according to UAX44-LM3. +/// +/// A "symbolic name" typically corresponds to property names and property +/// value aliases. Note, though, that it should not be applied to property +/// string values. +/// +/// The slice returned is guaranteed to be valid UTF-8 for all possible values +/// of `slice`. +/// +/// See: http://unicode.org/reports/tr44/#UAX44-LM3 +fn symbolic_name_normalize_bytes(slice: &mut [u8]) -> &mut [u8] { + // I couldn't find a place in the standard that specified that property + // names/aliases had a particular structure (unlike character names), but + // we assume that it's ASCII only and drop anything that isn't ASCII. + let mut start = 0; + if slice.len() >= 2 { + // Ignore any "is" prefix. + let starts_with_is = + slice[0..2] == b"is"[..] + || slice[0..2] == b"IS"[..] + || slice[0..2] == b"iS"[..] + || slice[0..2] == b"Is"[..]; + if starts_with_is { + start = 2; + } + } + let mut next_write = 0; + for i in start..slice.len() { + // SAFETY ARGUMENT: To guarantee that the resulting slice is valid + // UTF-8, we ensure that the slice contains only ASCII bytes. In + // particular, we drop every non-ASCII byte from the normalized string. + let b = slice[i]; + if b == b' ' || b == b'_' || b == b'-' { + continue; + } else if b'A' <= b && b <= b'Z' { + slice[next_write] = b + (b'a' - b'A'); + next_write += 1; + } else if b <= 0x7F { + slice[next_write] = b; + next_write += 1; + } + } + &mut slice[..next_write] +} + +#[cfg(test)] +mod tests { + use super::{ + character_name_normalize, character_name_normalize_bytes, + symbolic_name_normalize, symbolic_name_normalize_bytes, + }; + + fn char_norm(s: &str) -> String { + let mut s = s.to_string(); + character_name_normalize(&mut s); + s + } + + fn sym_norm(s: &str) -> String { + let mut s = s.to_string(); + symbolic_name_normalize(&mut s); + s + } + + #[test] + fn char_normalize() { + assert_eq!(char_norm("HANGUL JUNGSEONG O-E"), "hanguljungseongo-e"); + assert_eq!(char_norm("zero-width space"), "zerowidthspace"); + assert_eq!(char_norm("zerowidthspace"), "zerowidthspace"); + assert_eq!(char_norm("ZERO WIDTH SPACE"), "zerowidthspace"); + assert_eq!(char_norm("TIBETAN MARK TSA -PHRU"), "tibetanmarktsa-phru"); + } + + #[test] + fn sym_normalize() { + assert_eq!(sym_norm("Line_Break"), "linebreak"); + assert_eq!(sym_norm("Line-break"), "linebreak"); + assert_eq!(sym_norm("linebreak"), "linebreak"); + assert_eq!(sym_norm("BA"), "ba"); + assert_eq!(sym_norm("ba"), "ba"); + assert_eq!(sym_norm("Greek"), "greek"); + assert_eq!(sym_norm("isGreek"), "greek"); + assert_eq!(sym_norm("IS_Greek"), "greek"); + } + + #[test] + fn valid_utf8_character() { + let mut x = b"abc\xFFxyz".to_vec(); + let y = character_name_normalize_bytes(&mut x); + assert_eq!(y, b"abcxyz"); + } + + #[test] + fn valid_utf8_symbolic() { + let mut x = b"abc\xFFxyz".to_vec(); + let y = symbolic_name_normalize_bytes(&mut x); + assert_eq!(y, b"abcxyz"); + } +} diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/src/property.rs cargo-0.26.0/vendor/ucd-util-0.1.1/src/property.rs --- cargo-0.25.0/vendor/ucd-util-0.1.1/src/property.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/src/property.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,124 @@ +/// The type of a property name table. +/// +/// A property name table is a sequence of sorted tuples, where the first +/// value in each tuple is a normalized property name and the second value of +/// each tuple is the corresponding canonical property name. +pub type PropertyTable = &'static [(&'static str, &'static str)]; + +/// Find the canonical property name for the given normalized property name. +/// +/// If no such property exists, then `None` is returned. +/// +/// The normalized property name must have been normalized according to +/// UAX44 LM3, which can be done using `symbolic_name_normalize`. +pub fn canonical_property_name( + property_table: PropertyTable, + normalized_property_name: &str, +) -> Option<&'static str> { + property_table + .binary_search_by_key(&normalized_property_name, |&(n, _)| n) + .ok() + .map(|i| property_table[i].1) +} + +/// Type of a property value table. +/// +/// A property value table maps property names to a mapping of property values, +/// where the mapping of property values is represented by a sequence of +/// tuples. The first element of each tuple is a normalized property value +/// while the second element of each tuple is the corresponding canonical +/// property value. +/// +/// Note that a property value table only includes values for properties that +/// are catalogs, enumerations or binary properties. Properties that have +/// string values (such as case or decomposition mappings), numeric values +/// or are miscellaneous are not represented in this table. +pub type PropertyValueTable = &'static [(&'static str, PropertyValues)]; + +/// A mapping of property values for a specific property. +/// +/// The first element of each tuple is a normalized property value while the +/// second element of each tuple is the corresponding canonical property +/// value. +pub type PropertyValues = &'static [(&'static str, &'static str)]; + +/// Find the set of possible property values for a given property. +/// +/// The set returned is a mapping expressed as a sorted list of tuples. +/// The first element of each tuple is a normalized property value while the +/// second element of each tuple is the corresponding canonical property +/// value. +/// +/// If no such property exists, then `None` is returned. +/// +/// The given property name must be in its canonical form, which can be +/// found using `canonical_property_name`. +pub fn property_values( + property_value_table: PropertyValueTable, + canonical_property_name: &str, +) -> Option<PropertyValues> { + property_value_table + .binary_search_by_key(&canonical_property_name, |&(n, _)| n) + .ok() + .map(|i| property_value_table[i].1) +} + +/// Find the canonical property value for the given normalized property +/// value. +/// +/// The given property values should correspond to the values for the property +/// under question, which can be found using `property_values`. +/// +/// If no such property value exists, then `None` is returned. +/// +/// The normalized property value must have been normalized according to +/// UAX44 LM3, which can be done using `symbolic_name_normalize`. +pub fn canonical_property_value( + property_values: PropertyValues, + normalized_property_value: &str, +) -> Option<&'static str> { + // This is cute. The types line up, so why not? + canonical_property_name(property_values, normalized_property_value) +} + + +#[cfg(test)] +mod tests { + use unicode_tables::property_names::PROPERTY_NAMES; + use unicode_tables::property_values::PROPERTY_VALUES; + + use super::{ + canonical_property_name, property_values, canonical_property_value, + }; + + #[test] + fn canonical_property_name_1() { + assert_eq!( + canonical_property_name(PROPERTY_NAMES, "gc"), + Some("General_Category")); + assert_eq!( + canonical_property_name(PROPERTY_NAMES, "generalcategory"), + Some("General_Category")); + assert_eq!( + canonical_property_name(PROPERTY_NAMES, "g c"), + None); + } + + #[test] + fn property_values_1() { + assert_eq!( + property_values(PROPERTY_VALUES, "White_Space"), + Some(&[ + ("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ][..])); + } + + #[test] + fn canonical_property_value_1() { + let values = property_values(PROPERTY_VALUES, "White_Space").unwrap(); + assert_eq!(canonical_property_value(values, "false"), Some("No")); + assert_eq!(canonical_property_value(values, "t"), Some("Yes")); + assert_eq!(canonical_property_value(values, "F"), None); + } +} diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/src/unicode_tables/jamo_short_name.rs cargo-0.26.0/vendor/ucd-util-0.1.1/src/unicode_tables/jamo_short_name.rs --- cargo-0.25.0/vendor/ucd-util-0.1.1/src/unicode_tables/jamo_short_name.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/src/unicode_tables/jamo_short_name.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,22 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate jamo-short-name tmp/ucd-10.0.0/ +// +// ucd-generate is available on crates.io. + +pub const JAMO_SHORT_NAME: &'static [(u32, &'static str)] = &[ + (4352, "G"), (4353, "GG"), (4354, "N"), (4355, "D"), (4356, "DD"), + (4357, "R"), (4358, "M"), (4359, "B"), (4360, "BB"), (4361, "S"), + (4362, "SS"), (4363, ""), (4364, "J"), (4365, "JJ"), (4366, "C"), + (4367, "K"), (4368, "T"), (4369, "P"), (4370, "H"), (4449, "A"), + (4450, "AE"), (4451, "YA"), (4452, "YAE"), (4453, "EO"), (4454, "E"), + (4455, "YEO"), (4456, "YE"), (4457, "O"), (4458, "WA"), (4459, "WAE"), + (4460, "OE"), (4461, "YO"), (4462, "U"), (4463, "WEO"), (4464, "WE"), + (4465, "WI"), (4466, "YU"), (4467, "EU"), (4468, "YI"), (4469, "I"), + (4520, "G"), (4521, "GG"), (4522, "GS"), (4523, "N"), (4524, "NJ"), + (4525, "NH"), (4526, "D"), (4527, "L"), (4528, "LG"), (4529, "LM"), + (4530, "LB"), (4531, "LS"), (4532, "LT"), (4533, "LP"), (4534, "LH"), + (4535, "M"), (4536, "B"), (4537, "BS"), (4538, "S"), (4539, "SS"), + (4540, "NG"), (4541, "J"), (4542, "C"), (4543, "K"), (4544, "T"), + (4545, "P"), (4546, "H"), +]; diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/src/unicode_tables/mod.rs cargo-0.26.0/vendor/ucd-util-0.1.1/src/unicode_tables/mod.rs --- cargo-0.25.0/vendor/ucd-util-0.1.1/src/unicode_tables/mod.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/src/unicode_tables/mod.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,5 @@ +pub mod jamo_short_name; +#[cfg(test)] +pub mod property_names; +#[cfg(test)] +pub mod property_values; diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/src/unicode_tables/property_names.rs cargo-0.26.0/vendor/ucd-util-0.1.1/src/unicode_tables/property_names.rs --- cargo-0.25.0/vendor/ucd-util-0.1.1/src/unicode_tables/property_names.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/src/unicode_tables/property_names.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,146 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate property-names tmp/ucd-10.0.0/ +// +// ucd-generate is available on crates.io. + +pub const PROPERTY_NAMES: &'static [(&'static str, &'static str)] = &[ + ("age", "Age"), ("ahex", "ASCII_Hex_Digit"), ("alpha", "Alphabetic"), + ("alphabetic", "Alphabetic"), ("asciihexdigit", "ASCII_Hex_Digit"), + ("bc", "Bidi_Class"), ("bidic", "Bidi_Control"), + ("bidiclass", "Bidi_Class"), ("bidicontrol", "Bidi_Control"), + ("bidim", "Bidi_Mirrored"), ("bidimirrored", "Bidi_Mirrored"), + ("bidimirroringglyph", "Bidi_Mirroring_Glyph"), + ("bidipairedbracket", "Bidi_Paired_Bracket"), + ("bidipairedbrackettype", "Bidi_Paired_Bracket_Type"), ("blk", "Block"), + ("block", "Block"), ("bmg", "Bidi_Mirroring_Glyph"), + ("bpb", "Bidi_Paired_Bracket"), ("bpt", "Bidi_Paired_Bracket_Type"), + ("c", "ISO_Comment"), + ("canonicalcombiningclass", "Canonical_Combining_Class"), + ("cased", "Cased"), ("casefolding", "Case_Folding"), + ("caseignorable", "Case_Ignorable"), ("ccc", "Canonical_Combining_Class"), + ("ce", "Composition_Exclusion"), ("cf", "Case_Folding"), + ("changeswhencasefolded", "Changes_When_Casefolded"), + ("changeswhencasemapped", "Changes_When_Casemapped"), + ("changeswhenlowercased", "Changes_When_Lowercased"), + ("changeswhennfkccasefolded", "Changes_When_NFKC_Casefolded"), + ("changeswhentitlecased", "Changes_When_Titlecased"), + ("changeswhenuppercased", "Changes_When_Uppercased"), + ("ci", "Case_Ignorable"), ("cjkaccountingnumeric", "kAccountingNumeric"), + ("cjkcompatibilityvariant", "kCompatibilityVariant"), + ("cjkiicore", "kIICore"), ("cjkirggsource", "kIRG_GSource"), + ("cjkirghsource", "kIRG_HSource"), ("cjkirgjsource", "kIRG_JSource"), + ("cjkirgkpsource", "kIRG_KPSource"), ("cjkirgksource", "kIRG_KSource"), + ("cjkirgmsource", "kIRG_MSource"), ("cjkirgtsource", "kIRG_TSource"), + ("cjkirgusource", "kIRG_USource"), ("cjkirgvsource", "kIRG_VSource"), + ("cjkothernumeric", "kOtherNumeric"), + ("cjkprimarynumeric", "kPrimaryNumeric"), ("cjkrsunicode", "kRSUnicode"), + ("compex", "Full_Composition_Exclusion"), + ("compositionexclusion", "Composition_Exclusion"), + ("cwcf", "Changes_When_Casefolded"), ("cwcm", "Changes_When_Casemapped"), + ("cwkcf", "Changes_When_NFKC_Casefolded"), + ("cwl", "Changes_When_Lowercased"), ("cwt", "Changes_When_Titlecased"), + ("cwu", "Changes_When_Uppercased"), ("dash", "Dash"), + ("decompositionmapping", "Decomposition_Mapping"), + ("decompositiontype", "Decomposition_Type"), + ("defaultignorablecodepoint", "Default_Ignorable_Code_Point"), + ("dep", "Deprecated"), ("deprecated", "Deprecated"), + ("di", "Default_Ignorable_Code_Point"), ("dia", "Diacritic"), + ("diacritic", "Diacritic"), ("dm", "Decomposition_Mapping"), + ("dt", "Decomposition_Type"), ("ea", "East_Asian_Width"), + ("eastasianwidth", "East_Asian_Width"), ("expandsonnfc", "Expands_On_NFC"), + ("expandsonnfd", "Expands_On_NFD"), ("expandsonnfkc", "Expands_On_NFKC"), + ("expandsonnfkd", "Expands_On_NFKD"), ("ext", "Extender"), + ("extender", "Extender"), ("fcnfkc", "FC_NFKC_Closure"), + ("fcnfkcclosure", "FC_NFKC_Closure"), + ("fullcompositionexclusion", "Full_Composition_Exclusion"), + ("gc", "General_Category"), ("gcb", "Grapheme_Cluster_Break"), + ("generalcategory", "General_Category"), ("graphemebase", "Grapheme_Base"), + ("graphemeclusterbreak", "Grapheme_Cluster_Break"), + ("graphemeextend", "Grapheme_Extend"), ("graphemelink", "Grapheme_Link"), + ("grbase", "Grapheme_Base"), ("grext", "Grapheme_Extend"), + ("grlink", "Grapheme_Link"), ("hangulsyllabletype", "Hangul_Syllable_Type"), + ("hex", "Hex_Digit"), ("hexdigit", "Hex_Digit"), + ("hst", "Hangul_Syllable_Type"), ("hyphen", "Hyphen"), + ("idc", "ID_Continue"), ("idcontinue", "ID_Continue"), + ("ideo", "Ideographic"), ("ideographic", "Ideographic"), + ("ids", "ID_Start"), ("idsb", "IDS_Binary_Operator"), + ("idsbinaryoperator", "IDS_Binary_Operator"), + ("idst", "IDS_Trinary_Operator"), ("idstart", "ID_Start"), + ("idstrinaryoperator", "IDS_Trinary_Operator"), + ("indicpositionalcategory", "Indic_Positional_Category"), + ("indicsyllabiccategory", "Indic_Syllabic_Category"), + ("inpc", "Indic_Positional_Category"), ("insc", "Indic_Syllabic_Category"), + ("jamoshortname", "Jamo_Short_Name"), ("jg", "Joining_Group"), + ("joinc", "Join_Control"), ("joincontrol", "Join_Control"), + ("joininggroup", "Joining_Group"), ("joiningtype", "Joining_Type"), + ("jsn", "Jamo_Short_Name"), ("jt", "Joining_Type"), + ("kaccountingnumeric", "kAccountingNumeric"), + ("kcompatibilityvariant", "kCompatibilityVariant"), ("kiicore", "kIICore"), + ("kirggsource", "kIRG_GSource"), ("kirghsource", "kIRG_HSource"), + ("kirgjsource", "kIRG_JSource"), ("kirgkpsource", "kIRG_KPSource"), + ("kirgksource", "kIRG_KSource"), ("kirgmsource", "kIRG_MSource"), + ("kirgtsource", "kIRG_TSource"), ("kirgusource", "kIRG_USource"), + ("kirgvsource", "kIRG_VSource"), ("kothernumeric", "kOtherNumeric"), + ("kprimarynumeric", "kPrimaryNumeric"), ("krsunicode", "kRSUnicode"), + ("lb", "Line_Break"), ("lc", "Lowercase_Mapping"), + ("linebreak", "Line_Break"), ("loe", "Logical_Order_Exception"), + ("logicalorderexception", "Logical_Order_Exception"), + ("lower", "Lowercase"), ("lowercase", "Lowercase"), + ("lowercasemapping", "Lowercase_Mapping"), ("math", "Math"), ("na", "Name"), + ("na1", "Unicode_1_Name"), ("name", "Name"), ("namealias", "Name_Alias"), + ("nchar", "Noncharacter_Code_Point"), ("nfcqc", "NFC_Quick_Check"), + ("nfcquickcheck", "NFC_Quick_Check"), ("nfdqc", "NFD_Quick_Check"), + ("nfdquickcheck", "NFD_Quick_Check"), ("nfkccasefold", "NFKC_Casefold"), + ("nfkccf", "NFKC_Casefold"), ("nfkcqc", "NFKC_Quick_Check"), + ("nfkcquickcheck", "NFKC_Quick_Check"), ("nfkdqc", "NFKD_Quick_Check"), + ("nfkdquickcheck", "NFKD_Quick_Check"), + ("noncharactercodepoint", "Noncharacter_Code_Point"), + ("nt", "Numeric_Type"), ("numerictype", "Numeric_Type"), + ("numericvalue", "Numeric_Value"), ("nv", "Numeric_Value"), + ("oalpha", "Other_Alphabetic"), ("ocomment", "ISO_Comment"), + ("odi", "Other_Default_Ignorable_Code_Point"), + ("ogrext", "Other_Grapheme_Extend"), ("oidc", "Other_ID_Continue"), + ("oids", "Other_ID_Start"), ("olower", "Other_Lowercase"), + ("omath", "Other_Math"), ("otheralphabetic", "Other_Alphabetic"), + ("otherdefaultignorablecodepoint", "Other_Default_Ignorable_Code_Point"), + ("othergraphemeextend", "Other_Grapheme_Extend"), + ("otheridcontinue", "Other_ID_Continue"), + ("otheridstart", "Other_ID_Start"), ("otherlowercase", "Other_Lowercase"), + ("othermath", "Other_Math"), ("otheruppercase", "Other_Uppercase"), + ("oupper", "Other_Uppercase"), ("patsyn", "Pattern_Syntax"), + ("patternsyntax", "Pattern_Syntax"), + ("patternwhitespace", "Pattern_White_Space"), + ("patws", "Pattern_White_Space"), ("pcm", "Prepended_Concatenation_Mark"), + ("prependedconcatenationmark", "Prepended_Concatenation_Mark"), + ("qmark", "Quotation_Mark"), ("quotationmark", "Quotation_Mark"), + ("radical", "Radical"), ("regionalindicator", "Regional_Indicator"), + ("ri", "Regional_Indicator"), ("sb", "Sentence_Break"), ("sc", "Script"), + ("scf", "Simple_Case_Folding"), ("script", "Script"), + ("scriptextensions", "Script_Extensions"), ("scx", "Script_Extensions"), + ("sd", "Soft_Dotted"), ("sentencebreak", "Sentence_Break"), + ("sentenceterminal", "Sentence_Terminal"), ("sfc", "Simple_Case_Folding"), + ("simplecasefolding", "Simple_Case_Folding"), + ("simplelowercasemapping", "Simple_Lowercase_Mapping"), + ("simpletitlecasemapping", "Simple_Titlecase_Mapping"), + ("simpleuppercasemapping", "Simple_Uppercase_Mapping"), + ("slc", "Simple_Lowercase_Mapping"), ("softdotted", "Soft_Dotted"), + ("space", "White_Space"), ("stc", "Simple_Titlecase_Mapping"), + ("sterm", "Sentence_Terminal"), ("suc", "Simple_Uppercase_Mapping"), + ("tc", "Titlecase_Mapping"), ("term", "Terminal_Punctuation"), + ("terminalpunctuation", "Terminal_Punctuation"), + ("titlecasemapping", "Titlecase_Mapping"), ("uc", "Uppercase_Mapping"), + ("uideo", "Unified_Ideograph"), ("unicode1name", "Unicode_1_Name"), + ("unicoderadicalstroke", "kRSUnicode"), + ("unifiedideograph", "Unified_Ideograph"), ("upper", "Uppercase"), + ("uppercase", "Uppercase"), ("uppercasemapping", "Uppercase_Mapping"), + ("urs", "kRSUnicode"), ("variationselector", "Variation_Selector"), + ("verticalorientation", "Vertical_Orientation"), + ("vo", "Vertical_Orientation"), ("vs", "Variation_Selector"), + ("wb", "Word_Break"), ("whitespace", "White_Space"), + ("wordbreak", "Word_Break"), ("wspace", "White_Space"), + ("xidc", "XID_Continue"), ("xidcontinue", "XID_Continue"), + ("xids", "XID_Start"), ("xidstart", "XID_Start"), + ("xonfc", "Expands_On_NFC"), ("xonfd", "Expands_On_NFD"), + ("xonfkc", "Expands_On_NFKC"), ("xonfkd", "Expands_On_NFKD"), +]; diff -Nru cargo-0.25.0/vendor/ucd-util-0.1.1/src/unicode_tables/property_values.rs cargo-0.26.0/vendor/ucd-util-0.1.1/src/unicode_tables/property_values.rs --- cargo-0.25.0/vendor/ucd-util-0.1.1/src/unicode_tables/property_values.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/ucd-util-0.1.1/src/unicode_tables/property_values.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,992 @@ +// DO NOT EDIT THIS FILE. IT WAS AUTOMATICALLY GENERATED BY: +// +// ucd-generate property-values tmp/ucd-10.0.0/ +// +// ucd-generate is available on crates.io. + +pub const PROPERTY_VALUES: &'static [(&'static str, &'static [(&'static str, &'static str)])] = &[ + ("ASCII_Hex_Digit", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Age", &[("1.1", "V1_1"), ("10.0", "V10_0"), ("2.0", "V2_0"), + ("2.1", "V2_1"), ("3.0", "V3_0"), ("3.1", "V3_1"), ("3.2", "V3_2"), + ("4.0", "V4_0"), ("4.1", "V4_1"), ("5.0", "V5_0"), ("5.1", "V5_1"), + ("5.2", "V5_2"), ("6.0", "V6_0"), ("6.1", "V6_1"), ("6.2", "V6_2"), + ("6.3", "V6_3"), ("7.0", "V7_0"), ("8.0", "V8_0"), ("9.0", "V9_0"), + ("na", "Unassigned"), ("unassigned", "Unassigned"), ("v100", "V10_0"), + ("v11", "V1_1"), ("v20", "V2_0"), ("v21", "V2_1"), ("v30", "V3_0"), + ("v31", "V3_1"), ("v32", "V3_2"), ("v40", "V4_0"), ("v41", "V4_1"), + ("v50", "V5_0"), ("v51", "V5_1"), ("v52", "V5_2"), ("v60", "V6_0"), + ("v61", "V6_1"), ("v62", "V6_2"), ("v63", "V6_3"), ("v70", "V7_0"), + ("v80", "V8_0"), ("v90", "V9_0"), ]), + + ("Alphabetic", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Bidi_Class", &[("al", "Arabic_Letter"), ("an", "Arabic_Number"), + ("arabicletter", "Arabic_Letter"), ("arabicnumber", "Arabic_Number"), + ("b", "Paragraph_Separator"), ("bn", "Boundary_Neutral"), + ("boundaryneutral", "Boundary_Neutral"), + ("commonseparator", "Common_Separator"), ("cs", "Common_Separator"), + ("en", "European_Number"), ("es", "European_Separator"), + ("et", "European_Terminator"), ("europeannumber", "European_Number"), + ("europeanseparator", "European_Separator"), + ("europeanterminator", "European_Terminator"), + ("firststrongisolate", "First_Strong_Isolate"), + ("fsi", "First_Strong_Isolate"), ("l", "Left_To_Right"), + ("lefttoright", "Left_To_Right"), + ("lefttorightembedding", "Left_To_Right_Embedding"), + ("lefttorightisolate", "Left_To_Right_Isolate"), + ("lefttorightoverride", "Left_To_Right_Override"), + ("lre", "Left_To_Right_Embedding"), ("lri", "Left_To_Right_Isolate"), + ("lro", "Left_To_Right_Override"), ("nonspacingmark", "Nonspacing_Mark"), + ("nsm", "Nonspacing_Mark"), ("on", "Other_Neutral"), + ("otherneutral", "Other_Neutral"), + ("paragraphseparator", "Paragraph_Separator"), + ("pdf", "Pop_Directional_Format"), ("pdi", "Pop_Directional_Isolate"), + ("popdirectionalformat", "Pop_Directional_Format"), + ("popdirectionalisolate", "Pop_Directional_Isolate"), + ("r", "Right_To_Left"), ("righttoleft", "Right_To_Left"), + ("righttoleftembedding", "Right_To_Left_Embedding"), + ("righttoleftisolate", "Right_To_Left_Isolate"), + ("righttoleftoverride", "Right_To_Left_Override"), + ("rle", "Right_To_Left_Embedding"), ("rli", "Right_To_Left_Isolate"), + ("rlo", "Right_To_Left_Override"), ("s", "Segment_Separator"), + ("segmentseparator", "Segment_Separator"), ("whitespace", "White_Space"), + ("ws", "White_Space"), ]), + + ("Bidi_Control", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Bidi_Mirrored", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Bidi_Paired_Bracket_Type", &[("c", "Close"), ("close", "Close"), + ("n", "None"), ("none", "None"), ("o", "Open"), ("open", "Open"), ]), + + ("Block", &[("adlam", "Adlam"), ("aegeannumbers", "Aegean_Numbers"), + ("ahom", "Ahom"), ("alchemical", "Alchemical_Symbols"), + ("alchemicalsymbols", "Alchemical_Symbols"), + ("alphabeticpf", "Alphabetic_Presentation_Forms"), + ("alphabeticpresentationforms", "Alphabetic_Presentation_Forms"), + ("anatolianhieroglyphs", "Anatolian_Hieroglyphs"), + ("ancientgreekmusic", "Ancient_Greek_Musical_Notation"), + ("ancientgreekmusicalnotation", "Ancient_Greek_Musical_Notation"), + ("ancientgreeknumbers", "Ancient_Greek_Numbers"), + ("ancientsymbols", "Ancient_Symbols"), ("arabic", "Arabic"), + ("arabicexta", "Arabic_Extended_A"), + ("arabicextendeda", "Arabic_Extended_A"), + ("arabicmath", "Arabic_Mathematical_Alphabetic_Symbols"), + ("arabicmathematicalalphabeticsymbols", "Arabic_Mathematical_Alphabetic_Symbols"), + ("arabicpfa", "Arabic_Presentation_Forms_A"), + ("arabicpfb", "Arabic_Presentation_Forms_B"), + ("arabicpresentationformsa", "Arabic_Presentation_Forms_A"), + ("arabicpresentationformsb", "Arabic_Presentation_Forms_B"), + ("arabicsup", "Arabic_Supplement"), + ("arabicsupplement", "Arabic_Supplement"), ("armenian", "Armenian"), + ("arrows", "Arrows"), ("ascii", "Basic_Latin"), ("avestan", "Avestan"), + ("balinese", "Balinese"), ("bamum", "Bamum"), + ("bamumsup", "Bamum_Supplement"), ("bamumsupplement", "Bamum_Supplement"), + ("basiclatin", "Basic_Latin"), ("bassavah", "Bassa_Vah"), + ("batak", "Batak"), ("bengali", "Bengali"), ("bhaiksuki", "Bhaiksuki"), + ("blockelements", "Block_Elements"), ("bopomofo", "Bopomofo"), + ("bopomofoext", "Bopomofo_Extended"), + ("bopomofoextended", "Bopomofo_Extended"), ("boxdrawing", "Box_Drawing"), + ("brahmi", "Brahmi"), ("braille", "Braille_Patterns"), + ("braillepatterns", "Braille_Patterns"), ("buginese", "Buginese"), + ("buhid", "Buhid"), ("byzantinemusic", "Byzantine_Musical_Symbols"), + ("byzantinemusicalsymbols", "Byzantine_Musical_Symbols"), + ("canadiansyllabics", "Unified_Canadian_Aboriginal_Syllabics"), + ("carian", "Carian"), ("caucasianalbanian", "Caucasian_Albanian"), + ("chakma", "Chakma"), ("cham", "Cham"), ("cherokee", "Cherokee"), + ("cherokeesup", "Cherokee_Supplement"), + ("cherokeesupplement", "Cherokee_Supplement"), + ("cjk", "CJK_Unified_Ideographs"), ("cjkcompat", "CJK_Compatibility"), + ("cjkcompatforms", "CJK_Compatibility_Forms"), + ("cjkcompatibility", "CJK_Compatibility"), + ("cjkcompatibilityforms", "CJK_Compatibility_Forms"), + ("cjkcompatibilityideographs", "CJK_Compatibility_Ideographs"), + ("cjkcompatibilityideographssupplement", "CJK_Compatibility_Ideographs_Supplement"), + ("cjkcompatideographs", "CJK_Compatibility_Ideographs"), + ("cjkcompatideographssup", "CJK_Compatibility_Ideographs_Supplement"), + ("cjkexta", "CJK_Unified_Ideographs_Extension_A"), + ("cjkextb", "CJK_Unified_Ideographs_Extension_B"), + ("cjkextc", "CJK_Unified_Ideographs_Extension_C"), + ("cjkextd", "CJK_Unified_Ideographs_Extension_D"), + ("cjkexte", "CJK_Unified_Ideographs_Extension_E"), + ("cjkextf", "CJK_Unified_Ideographs_Extension_F"), + ("cjkradicalssup", "CJK_Radicals_Supplement"), + ("cjkradicalssupplement", "CJK_Radicals_Supplement"), + ("cjkstrokes", "CJK_Strokes"), + ("cjksymbols", "CJK_Symbols_And_Punctuation"), + ("cjksymbolsandpunctuation", "CJK_Symbols_And_Punctuation"), + ("cjkunifiedideographs", "CJK_Unified_Ideographs"), + ("cjkunifiedideographsextensiona", "CJK_Unified_Ideographs_Extension_A"), + ("cjkunifiedideographsextensionb", "CJK_Unified_Ideographs_Extension_B"), + ("cjkunifiedideographsextensionc", "CJK_Unified_Ideographs_Extension_C"), + ("cjkunifiedideographsextensiond", "CJK_Unified_Ideographs_Extension_D"), + ("cjkunifiedideographsextensione", "CJK_Unified_Ideographs_Extension_E"), + ("cjkunifiedideographsextensionf", "CJK_Unified_Ideographs_Extension_F"), + ("combiningdiacriticalmarks", "Combining_Diacritical_Marks"), + ("combiningdiacriticalmarksextended", "Combining_Diacritical_Marks_Extended"), + ("combiningdiacriticalmarksforsymbols", "Combining_Diacritical_Marks_For_Symbols"), + ("combiningdiacriticalmarkssupplement", "Combining_Diacritical_Marks_Supplement"), + ("combininghalfmarks", "Combining_Half_Marks"), + ("combiningmarksforsymbols", "Combining_Diacritical_Marks_For_Symbols"), + ("commonindicnumberforms", "Common_Indic_Number_Forms"), + ("compatjamo", "Hangul_Compatibility_Jamo"), + ("controlpictures", "Control_Pictures"), ("coptic", "Coptic"), + ("copticepactnumbers", "Coptic_Epact_Numbers"), + ("countingrod", "Counting_Rod_Numerals"), + ("countingrodnumerals", "Counting_Rod_Numerals"), + ("cuneiform", "Cuneiform"), + ("cuneiformnumbers", "Cuneiform_Numbers_And_Punctuation"), + ("cuneiformnumbersandpunctuation", "Cuneiform_Numbers_And_Punctuation"), + ("currencysymbols", "Currency_Symbols"), + ("cypriotsyllabary", "Cypriot_Syllabary"), ("cyrillic", "Cyrillic"), + ("cyrillicexta", "Cyrillic_Extended_A"), + ("cyrillicextb", "Cyrillic_Extended_B"), + ("cyrillicextc", "Cyrillic_Extended_C"), + ("cyrillicextendeda", "Cyrillic_Extended_A"), + ("cyrillicextendedb", "Cyrillic_Extended_B"), + ("cyrillicextendedc", "Cyrillic_Extended_C"), + ("cyrillicsup", "Cyrillic_Supplement"), + ("cyrillicsupplement", "Cyrillic_Supplement"), + ("cyrillicsupplementary", "Cyrillic_Supplement"), ("deseret", "Deseret"), + ("devanagari", "Devanagari"), ("devanagariext", "Devanagari_Extended"), + ("devanagariextended", "Devanagari_Extended"), + ("diacriticals", "Combining_Diacritical_Marks"), + ("diacriticalsext", "Combining_Diacritical_Marks_Extended"), + ("diacriticalsforsymbols", "Combining_Diacritical_Marks_For_Symbols"), + ("diacriticalssup", "Combining_Diacritical_Marks_Supplement"), + ("dingbats", "Dingbats"), ("domino", "Domino_Tiles"), + ("dominotiles", "Domino_Tiles"), ("duployan", "Duployan"), + ("earlydynasticcuneiform", "Early_Dynastic_Cuneiform"), + ("egyptianhieroglyphs", "Egyptian_Hieroglyphs"), ("elbasan", "Elbasan"), + ("emoticons", "Emoticons"), ("enclosedalphanum", "Enclosed_Alphanumerics"), + ("enclosedalphanumerics", "Enclosed_Alphanumerics"), + ("enclosedalphanumericsupplement", "Enclosed_Alphanumeric_Supplement"), + ("enclosedalphanumsup", "Enclosed_Alphanumeric_Supplement"), + ("enclosedcjk", "Enclosed_CJK_Letters_And_Months"), + ("enclosedcjklettersandmonths", "Enclosed_CJK_Letters_And_Months"), + ("enclosedideographicsup", "Enclosed_Ideographic_Supplement"), + ("enclosedideographicsupplement", "Enclosed_Ideographic_Supplement"), + ("ethiopic", "Ethiopic"), ("ethiopicext", "Ethiopic_Extended"), + ("ethiopicexta", "Ethiopic_Extended_A"), + ("ethiopicextended", "Ethiopic_Extended"), + ("ethiopicextendeda", "Ethiopic_Extended_A"), + ("ethiopicsup", "Ethiopic_Supplement"), + ("ethiopicsupplement", "Ethiopic_Supplement"), + ("generalpunctuation", "General_Punctuation"), + ("geometricshapes", "Geometric_Shapes"), + ("geometricshapesext", "Geometric_Shapes_Extended"), + ("geometricshapesextended", "Geometric_Shapes_Extended"), + ("georgian", "Georgian"), ("georgiansup", "Georgian_Supplement"), + ("georgiansupplement", "Georgian_Supplement"), ("glagolitic", "Glagolitic"), + ("glagoliticsup", "Glagolitic_Supplement"), + ("glagoliticsupplement", "Glagolitic_Supplement"), ("gothic", "Gothic"), + ("grantha", "Grantha"), ("greek", "Greek_And_Coptic"), + ("greekandcoptic", "Greek_And_Coptic"), ("greekext", "Greek_Extended"), + ("greekextended", "Greek_Extended"), ("gujarati", "Gujarati"), + ("gurmukhi", "Gurmukhi"), + ("halfandfullforms", "Halfwidth_And_Fullwidth_Forms"), + ("halfmarks", "Combining_Half_Marks"), + ("halfwidthandfullwidthforms", "Halfwidth_And_Fullwidth_Forms"), + ("hangul", "Hangul_Syllables"), + ("hangulcompatibilityjamo", "Hangul_Compatibility_Jamo"), + ("hanguljamo", "Hangul_Jamo"), + ("hanguljamoextendeda", "Hangul_Jamo_Extended_A"), + ("hanguljamoextendedb", "Hangul_Jamo_Extended_B"), + ("hangulsyllables", "Hangul_Syllables"), ("hanunoo", "Hanunoo"), + ("hatran", "Hatran"), ("hebrew", "Hebrew"), + ("highprivateusesurrogates", "High_Private_Use_Surrogates"), + ("highpusurrogates", "High_Private_Use_Surrogates"), + ("highsurrogates", "High_Surrogates"), ("hiragana", "Hiragana"), + ("idc", "Ideographic_Description_Characters"), + ("ideographicdescriptioncharacters", "Ideographic_Description_Characters"), + ("ideographicsymbols", "Ideographic_Symbols_And_Punctuation"), + ("ideographicsymbolsandpunctuation", "Ideographic_Symbols_And_Punctuation"), + ("imperialaramaic", "Imperial_Aramaic"), + ("indicnumberforms", "Common_Indic_Number_Forms"), + ("inscriptionalpahlavi", "Inscriptional_Pahlavi"), + ("inscriptionalparthian", "Inscriptional_Parthian"), + ("ipaext", "IPA_Extensions"), ("ipaextensions", "IPA_Extensions"), + ("jamo", "Hangul_Jamo"), ("jamoexta", "Hangul_Jamo_Extended_A"), + ("jamoextb", "Hangul_Jamo_Extended_B"), ("javanese", "Javanese"), + ("kaithi", "Kaithi"), ("kanaexta", "Kana_Extended_A"), + ("kanaextendeda", "Kana_Extended_A"), ("kanasup", "Kana_Supplement"), + ("kanasupplement", "Kana_Supplement"), ("kanbun", "Kanbun"), + ("kangxi", "Kangxi_Radicals"), ("kangxiradicals", "Kangxi_Radicals"), + ("kannada", "Kannada"), ("katakana", "Katakana"), + ("katakanaext", "Katakana_Phonetic_Extensions"), + ("katakanaphoneticextensions", "Katakana_Phonetic_Extensions"), + ("kayahli", "Kayah_Li"), ("kharoshthi", "Kharoshthi"), ("khmer", "Khmer"), + ("khmersymbols", "Khmer_Symbols"), ("khojki", "Khojki"), + ("khudawadi", "Khudawadi"), ("lao", "Lao"), + ("latin1", "Latin_1_Supplement"), ("latin1sup", "Latin_1_Supplement"), + ("latin1supplement", "Latin_1_Supplement"), + ("latinexta", "Latin_Extended_A"), + ("latinextadditional", "Latin_Extended_Additional"), + ("latinextb", "Latin_Extended_B"), ("latinextc", "Latin_Extended_C"), + ("latinextd", "Latin_Extended_D"), ("latinexte", "Latin_Extended_E"), + ("latinextendeda", "Latin_Extended_A"), + ("latinextendedadditional", "Latin_Extended_Additional"), + ("latinextendedb", "Latin_Extended_B"), + ("latinextendedc", "Latin_Extended_C"), + ("latinextendedd", "Latin_Extended_D"), + ("latinextendede", "Latin_Extended_E"), ("lepcha", "Lepcha"), + ("letterlikesymbols", "Letterlike_Symbols"), ("limbu", "Limbu"), + ("lineara", "Linear_A"), ("linearbideograms", "Linear_B_Ideograms"), + ("linearbsyllabary", "Linear_B_Syllabary"), ("lisu", "Lisu"), + ("lowsurrogates", "Low_Surrogates"), ("lycian", "Lycian"), + ("lydian", "Lydian"), ("mahajani", "Mahajani"), + ("mahjong", "Mahjong_Tiles"), ("mahjongtiles", "Mahjong_Tiles"), + ("malayalam", "Malayalam"), ("mandaic", "Mandaic"), + ("manichaean", "Manichaean"), ("marchen", "Marchen"), + ("masaramgondi", "Masaram_Gondi"), + ("mathalphanum", "Mathematical_Alphanumeric_Symbols"), + ("mathematicalalphanumericsymbols", "Mathematical_Alphanumeric_Symbols"), + ("mathematicaloperators", "Mathematical_Operators"), + ("mathoperators", "Mathematical_Operators"), + ("meeteimayek", "Meetei_Mayek"), + ("meeteimayekext", "Meetei_Mayek_Extensions"), + ("meeteimayekextensions", "Meetei_Mayek_Extensions"), + ("mendekikakui", "Mende_Kikakui"), ("meroiticcursive", "Meroitic_Cursive"), + ("meroitichieroglyphs", "Meroitic_Hieroglyphs"), ("miao", "Miao"), + ("miscarrows", "Miscellaneous_Symbols_And_Arrows"), + ("miscellaneousmathematicalsymbolsa", "Miscellaneous_Mathematical_Symbols_A"), + ("miscellaneousmathematicalsymbolsb", "Miscellaneous_Mathematical_Symbols_B"), + ("miscellaneoussymbols", "Miscellaneous_Symbols"), + ("miscellaneoussymbolsandarrows", "Miscellaneous_Symbols_And_Arrows"), + ("miscellaneoussymbolsandpictographs", "Miscellaneous_Symbols_And_Pictographs"), + ("miscellaneoustechnical", "Miscellaneous_Technical"), + ("miscmathsymbolsa", "Miscellaneous_Mathematical_Symbols_A"), + ("miscmathsymbolsb", "Miscellaneous_Mathematical_Symbols_B"), + ("miscpictographs", "Miscellaneous_Symbols_And_Pictographs"), + ("miscsymbols", "Miscellaneous_Symbols"), + ("misctechnical", "Miscellaneous_Technical"), ("modi", "Modi"), + ("modifierletters", "Spacing_Modifier_Letters"), + ("modifiertoneletters", "Modifier_Tone_Letters"), + ("mongolian", "Mongolian"), ("mongoliansup", "Mongolian_Supplement"), + ("mongoliansupplement", "Mongolian_Supplement"), ("mro", "Mro"), + ("multani", "Multani"), ("music", "Musical_Symbols"), + ("musicalsymbols", "Musical_Symbols"), ("myanmar", "Myanmar"), + ("myanmarexta", "Myanmar_Extended_A"), + ("myanmarextb", "Myanmar_Extended_B"), + ("myanmarextendeda", "Myanmar_Extended_A"), + ("myanmarextendedb", "Myanmar_Extended_B"), ("nabataean", "Nabataean"), + ("nb", "No_Block"), ("newa", "Newa"), ("newtailue", "New_Tai_Lue"), + ("nko", "NKo"), ("noblock", "No_Block"), ("numberforms", "Number_Forms"), + ("nushu", "Nushu"), ("ocr", "Optical_Character_Recognition"), + ("ogham", "Ogham"), ("olchiki", "Ol_Chiki"), + ("oldhungarian", "Old_Hungarian"), ("olditalic", "Old_Italic"), + ("oldnortharabian", "Old_North_Arabian"), ("oldpermic", "Old_Permic"), + ("oldpersian", "Old_Persian"), ("oldsoutharabian", "Old_South_Arabian"), + ("oldturkic", "Old_Turkic"), + ("opticalcharacterrecognition", "Optical_Character_Recognition"), + ("oriya", "Oriya"), ("ornamentaldingbats", "Ornamental_Dingbats"), + ("osage", "Osage"), ("osmanya", "Osmanya"), ("pahawhhmong", "Pahawh_Hmong"), + ("palmyrene", "Palmyrene"), ("paucinhau", "Pau_Cin_Hau"), + ("phagspa", "Phags_Pa"), ("phaistos", "Phaistos_Disc"), + ("phaistosdisc", "Phaistos_Disc"), ("phoenician", "Phoenician"), + ("phoneticext", "Phonetic_Extensions"), + ("phoneticextensions", "Phonetic_Extensions"), + ("phoneticextensionssupplement", "Phonetic_Extensions_Supplement"), + ("phoneticextsup", "Phonetic_Extensions_Supplement"), + ("playingcards", "Playing_Cards"), ("privateuse", "Private_Use_Area"), + ("privateusearea", "Private_Use_Area"), + ("psalterpahlavi", "Psalter_Pahlavi"), ("pua", "Private_Use_Area"), + ("punctuation", "General_Punctuation"), ("rejang", "Rejang"), + ("rumi", "Rumi_Numeral_Symbols"), + ("ruminumeralsymbols", "Rumi_Numeral_Symbols"), ("runic", "Runic"), + ("samaritan", "Samaritan"), ("saurashtra", "Saurashtra"), + ("sharada", "Sharada"), ("shavian", "Shavian"), + ("shorthandformatcontrols", "Shorthand_Format_Controls"), + ("siddham", "Siddham"), ("sinhala", "Sinhala"), + ("sinhalaarchaicnumbers", "Sinhala_Archaic_Numbers"), + ("smallforms", "Small_Form_Variants"), + ("smallformvariants", "Small_Form_Variants"), + ("sorasompeng", "Sora_Sompeng"), ("soyombo", "Soyombo"), + ("spacingmodifierletters", "Spacing_Modifier_Letters"), + ("specials", "Specials"), ("sundanese", "Sundanese"), + ("sundanesesup", "Sundanese_Supplement"), + ("sundanesesupplement", "Sundanese_Supplement"), + ("suparrowsa", "Supplemental_Arrows_A"), + ("suparrowsb", "Supplemental_Arrows_B"), + ("suparrowsc", "Supplemental_Arrows_C"), + ("superandsub", "Superscripts_And_Subscripts"), + ("superscriptsandsubscripts", "Superscripts_And_Subscripts"), + ("supmathoperators", "Supplemental_Mathematical_Operators"), + ("supplementalarrowsa", "Supplemental_Arrows_A"), + ("supplementalarrowsb", "Supplemental_Arrows_B"), + ("supplementalarrowsc", "Supplemental_Arrows_C"), + ("supplementalmathematicaloperators", "Supplemental_Mathematical_Operators"), + ("supplementalpunctuation", "Supplemental_Punctuation"), + ("supplementalsymbolsandpictographs", "Supplemental_Symbols_And_Pictographs"), + ("supplementaryprivateuseareaa", "Supplementary_Private_Use_Area_A"), + ("supplementaryprivateuseareab", "Supplementary_Private_Use_Area_B"), + ("suppuaa", "Supplementary_Private_Use_Area_A"), + ("suppuab", "Supplementary_Private_Use_Area_B"), + ("suppunctuation", "Supplemental_Punctuation"), + ("supsymbolsandpictographs", "Supplemental_Symbols_And_Pictographs"), + ("suttonsignwriting", "Sutton_SignWriting"), + ("sylotinagri", "Syloti_Nagri"), ("syriac", "Syriac"), + ("syriacsup", "Syriac_Supplement"), + ("syriacsupplement", "Syriac_Supplement"), ("tagalog", "Tagalog"), + ("tagbanwa", "Tagbanwa"), ("tags", "Tags"), ("taile", "Tai_Le"), + ("taitham", "Tai_Tham"), ("taiviet", "Tai_Viet"), + ("taixuanjing", "Tai_Xuan_Jing_Symbols"), + ("taixuanjingsymbols", "Tai_Xuan_Jing_Symbols"), ("takri", "Takri"), + ("tamil", "Tamil"), ("tangut", "Tangut"), + ("tangutcomponents", "Tangut_Components"), ("telugu", "Telugu"), + ("thaana", "Thaana"), ("thai", "Thai"), ("tibetan", "Tibetan"), + ("tifinagh", "Tifinagh"), ("tirhuta", "Tirhuta"), + ("transportandmap", "Transport_And_Map_Symbols"), + ("transportandmapsymbols", "Transport_And_Map_Symbols"), + ("ucas", "Unified_Canadian_Aboriginal_Syllabics"), + ("ucasext", "Unified_Canadian_Aboriginal_Syllabics_Extended"), + ("ugaritic", "Ugaritic"), + ("unifiedcanadianaboriginalsyllabics", "Unified_Canadian_Aboriginal_Syllabics"), + ("unifiedcanadianaboriginalsyllabicsextended", "Unified_Canadian_Aboriginal_Syllabics_Extended"), + ("vai", "Vai"), ("variationselectors", "Variation_Selectors"), + ("variationselectorssupplement", "Variation_Selectors_Supplement"), + ("vedicext", "Vedic_Extensions"), ("vedicextensions", "Vedic_Extensions"), + ("verticalforms", "Vertical_Forms"), ("vs", "Variation_Selectors"), + ("vssup", "Variation_Selectors_Supplement"), ("warangciti", "Warang_Citi"), + ("yijing", "Yijing_Hexagram_Symbols"), + ("yijinghexagramsymbols", "Yijing_Hexagram_Symbols"), + ("yiradicals", "Yi_Radicals"), ("yisyllables", "Yi_Syllables"), + ("zanabazarsquare", "Zanabazar_Square"), ]), + + ("Canonical_Combining_Class", &[("", "Iota_Subscript"), + ("0", "Not_Reordered"), ("1", "Overlay"), ("10", "CCC10"), + ("103", "CCC103"), ("107", "CCC107"), ("11", "CCC11"), ("118", "CCC118"), + ("12", "CCC12"), ("122", "CCC122"), ("129", "CCC129"), ("13", "CCC13"), + ("130", "CCC130"), ("132", "CCC132"), ("133", "CCC133"), ("14", "CCC14"), + ("15", "CCC15"), ("16", "CCC16"), ("17", "CCC17"), ("18", "CCC18"), + ("19", "CCC19"), ("20", "CCC20"), ("200", "Attached_Below_Left"), + ("202", "Attached_Below"), ("21", "CCC21"), ("214", "Attached_Above"), + ("216", "Attached_Above_Right"), ("218", "Below_Left"), ("22", "CCC22"), + ("220", "Below"), ("222", "Below_Right"), ("224", "Left"), ("226", "Right"), + ("228", "Above_Left"), ("23", "CCC23"), ("230", "Above"), + ("232", "Above_Right"), ("233", "Double_Below"), ("234", "Double_Above"), + ("24", "CCC24"), ("240", "Iota_Subscript"), ("25", "CCC25"), + ("26", "CCC26"), ("27", "CCC27"), ("28", "CCC28"), ("29", "CCC29"), + ("30", "CCC30"), ("31", "CCC31"), ("32", "CCC32"), ("33", "CCC33"), + ("34", "CCC34"), ("35", "CCC35"), ("36", "CCC36"), ("7", "Nukta"), + ("8", "Kana_Voicing"), ("84", "CCC84"), ("9", "Virama"), ("91", "CCC91"), + ("a", "Above"), ("above", "Above"), ("aboveleft", "Above_Left"), + ("aboveright", "Above_Right"), ("al", "Above_Left"), ("ar", "Above_Right"), + ("ata", "Attached_Above"), ("atar", "Attached_Above_Right"), + ("atb", "Attached_Below"), ("atbl", "Attached_Below_Left"), + ("attachedabove", "Attached_Above"), + ("attachedaboveright", "Attached_Above_Right"), + ("attachedbelow", "Attached_Below"), + ("attachedbelowleft", "Attached_Below_Left"), ("b", "Below"), + ("below", "Below"), ("belowleft", "Below_Left"), + ("belowright", "Below_Right"), ("bl", "Below_Left"), ("br", "Below_Right"), + ("ccc10", "CCC10"), ("ccc103", "CCC103"), ("ccc107", "CCC107"), + ("ccc11", "CCC11"), ("ccc118", "CCC118"), ("ccc12", "CCC12"), + ("ccc122", "CCC122"), ("ccc129", "CCC129"), ("ccc13", "CCC13"), + ("ccc130", "CCC130"), ("ccc132", "CCC132"), ("ccc133", "CCC133"), + ("ccc14", "CCC14"), ("ccc15", "CCC15"), ("ccc16", "CCC16"), + ("ccc17", "CCC17"), ("ccc18", "CCC18"), ("ccc19", "CCC19"), + ("ccc20", "CCC20"), ("ccc21", "CCC21"), ("ccc22", "CCC22"), + ("ccc23", "CCC23"), ("ccc24", "CCC24"), ("ccc25", "CCC25"), + ("ccc26", "CCC26"), ("ccc27", "CCC27"), ("ccc28", "CCC28"), + ("ccc29", "CCC29"), ("ccc30", "CCC30"), ("ccc31", "CCC31"), + ("ccc32", "CCC32"), ("ccc33", "CCC33"), ("ccc34", "CCC34"), + ("ccc35", "CCC35"), ("ccc36", "CCC36"), ("ccc84", "CCC84"), + ("ccc91", "CCC91"), ("da", "Double_Above"), ("db", "Double_Below"), + ("doubleabove", "Double_Above"), ("doublebelow", "Double_Below"), + ("iotasubscript", "Iota_Subscript"), ("kanavoicing", "Kana_Voicing"), + ("kv", "Kana_Voicing"), ("l", "Left"), ("left", "Left"), ("nk", "Nukta"), + ("notreordered", "Not_Reordered"), ("nr", "Not_Reordered"), + ("nukta", "Nukta"), ("ov", "Overlay"), ("overlay", "Overlay"), + ("r", "Right"), ("right", "Right"), ("virama", "Virama"), ("vr", "Virama"), + ]), + + ("Case_Ignorable", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Cased", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Changes_When_Casefolded", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Changes_When_Casemapped", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Changes_When_Lowercased", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Changes_When_NFKC_Casefolded", &[("f", "No"), ("false", "No"), + ("n", "No"), ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), + ("yes", "Yes"), ]), + + ("Changes_When_Titlecased", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Changes_When_Uppercased", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Composition_Exclusion", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Dash", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Decomposition_Type", &[("can", "Canonical"), ("canonical", "Canonical"), + ("circle", "Circle"), ("com", "Compat"), ("compat", "Compat"), + ("enc", "Circle"), ("fin", "Final"), ("final", "Final"), ("font", "Font"), + ("fra", "Fraction"), ("fraction", "Fraction"), ("init", "Initial"), + ("initial", "Initial"), ("med", "Medial"), ("medial", "Medial"), + ("nar", "Narrow"), ("narrow", "Narrow"), ("nb", "Nobreak"), + ("nobreak", "Nobreak"), ("none", "None"), ("o", "Isolated"), + ("olated", "Isolated"), ("small", "Small"), ("sml", "Small"), + ("sqr", "Square"), ("square", "Square"), ("sub", "Sub"), ("sup", "Super"), + ("super", "Super"), ("vert", "Vertical"), ("vertical", "Vertical"), + ("wide", "Wide"), ]), + + ("Default_Ignorable_Code_Point", &[("f", "No"), ("false", "No"), + ("n", "No"), ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), + ("yes", "Yes"), ]), + + ("Deprecated", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Diacritic", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("East_Asian_Width", &[("a", "Ambiguous"), ("ambiguous", "Ambiguous"), + ("f", "Fullwidth"), ("fullwidth", "Fullwidth"), ("h", "Halfwidth"), + ("halfwidth", "Halfwidth"), ("n", "Neutral"), ("na", "Narrow"), + ("narrow", "Narrow"), ("neutral", "Neutral"), ("w", "Wide"), + ("wide", "Wide"), ]), + + ("Expands_On_NFC", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Expands_On_NFD", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Expands_On_NFKC", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Expands_On_NFKD", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Extender", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Full_Composition_Exclusion", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("General_Category", &[("c", "Other"), ("casedletter", "Cased_Letter"), + ("cc", "Control"), ("cf", "Format"), + ("closepunctuation", "Close_Punctuation"), ("cn", "Unassigned"), + ("cntrl", "Control"), ("co", "Private_Use"), ("combiningmark", "Mark"), + ("connectorpunctuation", "Connector_Punctuation"), ("control", "Control"), + ("cs", "Surrogate"), ("currencysymbol", "Currency_Symbol"), + ("dashpunctuation", "Dash_Punctuation"), + ("decimalnumber", "Decimal_Number"), ("digit", "Decimal_Number"), + ("enclosingmark", "Enclosing_Mark"), + ("finalpunctuation", "Final_Punctuation"), ("format", "Format"), + ("initialpunctuation", "Initial_Punctuation"), ("l", "Letter"), + ("lc", "Cased_Letter"), ("letter", "Letter"), + ("letternumber", "Letter_Number"), ("lineseparator", "Line_Separator"), + ("ll", "Lowercase_Letter"), ("lm", "Modifier_Letter"), + ("lo", "Other_Letter"), ("lowercaseletter", "Lowercase_Letter"), + ("lt", "Titlecase_Letter"), ("lu", "Uppercase_Letter"), ("m", "Mark"), + ("mark", "Mark"), ("mathsymbol", "Math_Symbol"), ("mc", "Spacing_Mark"), + ("me", "Enclosing_Mark"), ("mn", "Nonspacing_Mark"), + ("modifierletter", "Modifier_Letter"), + ("modifiersymbol", "Modifier_Symbol"), ("n", "Number"), + ("nd", "Decimal_Number"), ("nl", "Letter_Number"), ("no", "Other_Number"), + ("nonspacingmark", "Nonspacing_Mark"), ("number", "Number"), + ("openpunctuation", "Open_Punctuation"), ("other", "Other"), + ("otherletter", "Other_Letter"), ("othernumber", "Other_Number"), + ("otherpunctuation", "Other_Punctuation"), ("othersymbol", "Other_Symbol"), + ("p", "Punctuation"), ("paragraphseparator", "Paragraph_Separator"), + ("pc", "Connector_Punctuation"), ("pd", "Dash_Punctuation"), + ("pe", "Close_Punctuation"), ("pf", "Final_Punctuation"), + ("pi", "Initial_Punctuation"), ("po", "Other_Punctuation"), + ("privateuse", "Private_Use"), ("ps", "Open_Punctuation"), + ("punct", "Punctuation"), ("punctuation", "Punctuation"), ("s", "Symbol"), + ("sc", "Currency_Symbol"), ("separator", "Separator"), + ("sk", "Modifier_Symbol"), ("sm", "Math_Symbol"), ("so", "Other_Symbol"), + ("spaceseparator", "Space_Separator"), ("spacingmark", "Spacing_Mark"), + ("surrogate", "Surrogate"), ("symbol", "Symbol"), + ("titlecaseletter", "Titlecase_Letter"), ("unassigned", "Unassigned"), + ("uppercaseletter", "Uppercase_Letter"), ("z", "Separator"), + ("zl", "Line_Separator"), ("zp", "Paragraph_Separator"), + ("zs", "Space_Separator"), ]), + + ("Grapheme_Base", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Grapheme_Cluster_Break", &[("cn", "Control"), ("control", "Control"), + ("cr", "CR"), ("eb", "E_Base"), ("ebase", "E_Base"), + ("ebasegaz", "E_Base_GAZ"), ("ebg", "E_Base_GAZ"), ("em", "E_Modifier"), + ("emodifier", "E_Modifier"), ("ex", "Extend"), ("extend", "Extend"), + ("gaz", "Glue_After_Zwj"), ("glueafterzwj", "Glue_After_Zwj"), ("l", "L"), + ("lf", "LF"), ("lv", "LV"), ("lvt", "LVT"), ("other", "Other"), + ("pp", "Prepend"), ("prepend", "Prepend"), + ("regionalindicator", "Regional_Indicator"), ("ri", "Regional_Indicator"), + ("sm", "SpacingMark"), ("spacingmark", "SpacingMark"), ("t", "T"), + ("v", "V"), ("xx", "Other"), ("zwj", "ZWJ"), ]), + + ("Grapheme_Extend", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Grapheme_Link", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Hangul_Syllable_Type", &[("l", "Leading_Jamo"), + ("leadingjamo", "Leading_Jamo"), ("lv", "LV_Syllable"), + ("lvsyllable", "LV_Syllable"), ("lvt", "LVT_Syllable"), + ("lvtsyllable", "LVT_Syllable"), ("na", "Not_Applicable"), + ("notapplicable", "Not_Applicable"), ("t", "Trailing_Jamo"), + ("trailingjamo", "Trailing_Jamo"), ("v", "Vowel_Jamo"), + ("voweljamo", "Vowel_Jamo"), ]), + + ("Hex_Digit", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Hyphen", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("IDS_Binary_Operator", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("IDS_Trinary_Operator", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("ID_Continue", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("ID_Start", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Ideographic", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Indic_Positional_Category", &[("bottom", "Bottom"), + ("bottomandleft", "Bottom_And_Left"), + ("bottomandright", "Bottom_And_Right"), ("left", "Left"), + ("leftandright", "Left_And_Right"), ("na", "NA"), + ("overstruck", "Overstruck"), ("right", "Right"), ("top", "Top"), + ("topandbottom", "Top_And_Bottom"), + ("topandbottomandright", "Top_And_Bottom_And_Right"), + ("topandleft", "Top_And_Left"), + ("topandleftandright", "Top_And_Left_And_Right"), + ("topandright", "Top_And_Right"), ("visualorderleft", "Visual_Order_Left"), + ]), + + ("Indic_Syllabic_Category", &[("avagraha", "Avagraha"), ("bindu", "Bindu"), + ("brahmijoiningnumber", "Brahmi_Joining_Number"), + ("cantillationmark", "Cantillation_Mark"), ("consonant", "Consonant"), + ("consonantdead", "Consonant_Dead"), ("consonantfinal", "Consonant_Final"), + ("consonantheadletter", "Consonant_Head_Letter"), + ("consonantkiller", "Consonant_Killer"), + ("consonantmedial", "Consonant_Medial"), + ("consonantplaceholder", "Consonant_Placeholder"), + ("consonantprecedingrepha", "Consonant_Preceding_Repha"), + ("consonantprefixed", "Consonant_Prefixed"), + ("consonantsubjoined", "Consonant_Subjoined"), + ("consonantsucceedingrepha", "Consonant_Succeeding_Repha"), + ("consonantwithstacker", "Consonant_With_Stacker"), + ("geminationmark", "Gemination_Mark"), + ("invisiblestacker", "Invisible_Stacker"), ("joiner", "Joiner"), + ("modifyingletter", "Modifying_Letter"), ("nonjoiner", "Non_Joiner"), + ("nukta", "Nukta"), ("number", "Number"), ("numberjoiner", "Number_Joiner"), + ("other", "Other"), ("purekiller", "Pure_Killer"), + ("registershifter", "Register_Shifter"), + ("syllablemodifier", "Syllable_Modifier"), ("toneletter", "Tone_Letter"), + ("tonemark", "Tone_Mark"), ("virama", "Virama"), ("visarga", "Visarga"), + ("vowel", "Vowel"), ("voweldependent", "Vowel_Dependent"), + ("vowelindependent", "Vowel_Independent"), ]), + + ("Jamo_Short_Name", &[("a", "A"), ("ae", "AE"), ("b", "B"), ("bb", "BB"), + ("bs", "BS"), ("c", "C"), ("d", "D"), ("dd", "DD"), ("e", "E"), + ("eo", "EO"), ("eu", "EU"), ("g", "G"), ("gg", "GG"), ("gs", "GS"), + ("h", "H"), ("i", "I"), ("j", "J"), ("jj", "JJ"), ("k", "K"), ("l", "L"), + ("lb", "LB"), ("lg", "LG"), ("lh", "LH"), ("lm", "LM"), ("lp", "LP"), + ("ls", "LS"), ("lt", "LT"), ("m", "M"), ("n", "N"), ("ng", "NG"), + ("nh", "NH"), ("nj", "NJ"), ("o", "O"), ("oe", "OE"), ("p", "P"), + ("r", "R"), ("s", "S"), ("ss", "SS"), ("t", "T"), ("u", "U"), ("wa", "WA"), + ("wae", "WAE"), ("we", "WE"), ("weo", "WEO"), ("wi", "WI"), ("ya", "YA"), + ("yae", "YAE"), ("ye", "YE"), ("yeo", "YEO"), ("yi", "YI"), ("yo", "YO"), + ("yu", "YU"), ]), + + ("Join_Control", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Joining_Group", &[("africanfeh", "African_Feh"), + ("africannoon", "African_Noon"), ("africanqaf", "African_Qaf"), + ("ain", "Ain"), ("alaph", "Alaph"), ("alef", "Alef"), ("beh", "Beh"), + ("beth", "Beth"), ("burushaskiyehbarree", "Burushaski_Yeh_Barree"), + ("dal", "Dal"), ("dalathrish", "Dalath_Rish"), ("e", "E"), + ("farsiyeh", "Farsi_Yeh"), ("fe", "Fe"), ("feh", "Feh"), + ("finalsemkath", "Final_Semkath"), ("gaf", "Gaf"), ("gamal", "Gamal"), + ("hah", "Hah"), ("hamzaonhehgoal", "Hamza_On_Heh_Goal"), ("he", "He"), + ("heh", "Heh"), ("hehgoal", "Heh_Goal"), ("heth", "Heth"), ("kaf", "Kaf"), + ("kaph", "Kaph"), ("khaph", "Khaph"), ("knottedheh", "Knotted_Heh"), + ("lam", "Lam"), ("lamadh", "Lamadh"), ("malayalambha", "Malayalam_Bha"), + ("malayalamja", "Malayalam_Ja"), ("malayalamlla", "Malayalam_Lla"), + ("malayalamllla", "Malayalam_Llla"), ("malayalamnga", "Malayalam_Nga"), + ("malayalamnna", "Malayalam_Nna"), ("malayalamnnna", "Malayalam_Nnna"), + ("malayalamnya", "Malayalam_Nya"), ("malayalamra", "Malayalam_Ra"), + ("malayalamssa", "Malayalam_Ssa"), ("malayalamtta", "Malayalam_Tta"), + ("manichaeanaleph", "Manichaean_Aleph"), + ("manichaeanayin", "Manichaean_Ayin"), + ("manichaeanbeth", "Manichaean_Beth"), + ("manichaeandaleth", "Manichaean_Daleth"), + ("manichaeandhamedh", "Manichaean_Dhamedh"), + ("manichaeanfive", "Manichaean_Five"), + ("manichaeangimel", "Manichaean_Gimel"), + ("manichaeanheth", "Manichaean_Heth"), + ("manichaeanhundred", "Manichaean_Hundred"), + ("manichaeankaph", "Manichaean_Kaph"), + ("manichaeanlamedh", "Manichaean_Lamedh"), + ("manichaeanmem", "Manichaean_Mem"), ("manichaeannun", "Manichaean_Nun"), + ("manichaeanone", "Manichaean_One"), ("manichaeanpe", "Manichaean_Pe"), + ("manichaeanqoph", "Manichaean_Qoph"), + ("manichaeanresh", "Manichaean_Resh"), + ("manichaeansadhe", "Manichaean_Sadhe"), + ("manichaeansamekh", "Manichaean_Samekh"), + ("manichaeantaw", "Manichaean_Taw"), ("manichaeanten", "Manichaean_Ten"), + ("manichaeanteth", "Manichaean_Teth"), + ("manichaeanthamedh", "Manichaean_Thamedh"), + ("manichaeantwenty", "Manichaean_Twenty"), + ("manichaeanwaw", "Manichaean_Waw"), ("manichaeanyodh", "Manichaean_Yodh"), + ("manichaeanzayin", "Manichaean_Zayin"), ("meem", "Meem"), ("mim", "Mim"), + ("nojoininggroup", "No_Joining_Group"), ("noon", "Noon"), ("nun", "Nun"), + ("nya", "Nya"), ("pe", "Pe"), ("qaf", "Qaf"), ("qaph", "Qaph"), + ("reh", "Reh"), ("reversedpe", "Reversed_Pe"), + ("rohingyayeh", "Rohingya_Yeh"), ("sad", "Sad"), ("sadhe", "Sadhe"), + ("seen", "Seen"), ("semkath", "Semkath"), ("shin", "Shin"), + ("straightwaw", "Straight_Waw"), ("swashkaf", "Swash_Kaf"), + ("syriacwaw", "Syriac_Waw"), ("tah", "Tah"), ("taw", "Taw"), + ("tehmarbuta", "Teh_Marbuta"), ("tehmarbutagoal", "Hamza_On_Heh_Goal"), + ("teth", "Teth"), ("waw", "Waw"), ("yeh", "Yeh"), + ("yehbarree", "Yeh_Barree"), ("yehwithtail", "Yeh_With_Tail"), + ("yudh", "Yudh"), ("yudhhe", "Yudh_He"), ("zain", "Zain"), + ("zhain", "Zhain"), ]), + + ("Joining_Type", &[("c", "Join_Causing"), ("d", "Dual_Joining"), + ("dualjoining", "Dual_Joining"), ("joincausing", "Join_Causing"), + ("l", "Left_Joining"), ("leftjoining", "Left_Joining"), + ("nonjoining", "Non_Joining"), ("r", "Right_Joining"), + ("rightjoining", "Right_Joining"), ("t", "Transparent"), + ("transparent", "Transparent"), ("u", "Non_Joining"), ]), + + ("Line_Break", &[("", "Infix_Numeric"), ("ai", "Ambiguous"), + ("al", "Alphabetic"), ("alphabetic", "Alphabetic"), + ("ambiguous", "Ambiguous"), ("b2", "Break_Both"), ("ba", "Break_After"), + ("bb", "Break_Before"), ("bk", "Mandatory_Break"), + ("breakafter", "Break_After"), ("breakbefore", "Break_Before"), + ("breakboth", "Break_Both"), ("breaksymbols", "Break_Symbols"), + ("carriagereturn", "Carriage_Return"), ("cb", "Contingent_Break"), + ("cj", "Conditional_Japanese_Starter"), ("cl", "Close_Punctuation"), + ("closeparenthesis", "Close_Parenthesis"), + ("closepunctuation", "Close_Punctuation"), ("cm", "Combining_Mark"), + ("combiningmark", "Combining_Mark"), ("complexcontext", "Complex_Context"), + ("conditionaljapanesestarter", "Conditional_Japanese_Starter"), + ("contingentbreak", "Contingent_Break"), ("cp", "Close_Parenthesis"), + ("cr", "Carriage_Return"), ("eb", "E_Base"), ("ebase", "E_Base"), + ("em", "E_Modifier"), ("emodifier", "E_Modifier"), ("ex", "Exclamation"), + ("exclamation", "Exclamation"), ("gl", "Glue"), ("glue", "Glue"), + ("h2", "H2"), ("h3", "H3"), ("hebrewletter", "Hebrew_Letter"), + ("hl", "Hebrew_Letter"), ("hy", "Hyphen"), ("hyphen", "Hyphen"), + ("id", "Ideographic"), ("ideographic", "Ideographic"), + ("in", "Inseparable"), ("infixnumeric", "Infix_Numeric"), + ("inseparable", "Inseparable"), ("inseperable", "Inseparable"), + ("jl", "JL"), ("jt", "JT"), ("jv", "JV"), ("lf", "Line_Feed"), + ("linefeed", "Line_Feed"), ("mandatorybreak", "Mandatory_Break"), + ("nextline", "Next_Line"), ("nl", "Next_Line"), + ("nonstarter", "Nonstarter"), ("ns", "Nonstarter"), ("nu", "Numeric"), + ("numeric", "Numeric"), ("op", "Open_Punctuation"), + ("openpunctuation", "Open_Punctuation"), ("po", "Postfix_Numeric"), + ("postfixnumeric", "Postfix_Numeric"), ("pr", "Prefix_Numeric"), + ("prefixnumeric", "Prefix_Numeric"), ("qu", "Quotation"), + ("quotation", "Quotation"), ("regionalindicator", "Regional_Indicator"), + ("ri", "Regional_Indicator"), ("sa", "Complex_Context"), + ("sg", "Surrogate"), ("sp", "Space"), ("space", "Space"), + ("surrogate", "Surrogate"), ("sy", "Break_Symbols"), ("unknown", "Unknown"), + ("wj", "Word_Joiner"), ("wordjoiner", "Word_Joiner"), ("xx", "Unknown"), + ("zw", "ZWSpace"), ("zwj", "ZWJ"), ("zwspace", "ZWSpace"), ]), + + ("Logical_Order_Exception", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Lowercase", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Math", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("NFC_Quick_Check", &[("m", "Maybe"), ("maybe", "Maybe"), ("n", "No"), + ("no", "No"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("NFD_Quick_Check", &[("n", "No"), ("no", "No"), ("y", "Yes"), + ("yes", "Yes"), ]), + + ("NFKC_Quick_Check", &[("m", "Maybe"), ("maybe", "Maybe"), ("n", "No"), + ("no", "No"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("NFKD_Quick_Check", &[("n", "No"), ("no", "No"), ("y", "Yes"), + ("yes", "Yes"), ]), + + ("Noncharacter_Code_Point", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Numeric_Type", &[("de", "Decimal"), ("decimal", "Decimal"), + ("di", "Digit"), ("digit", "Digit"), ("none", "None"), ("nu", "Numeric"), + ("numeric", "Numeric"), ]), + + ("Other_Alphabetic", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Other_Default_Ignorable_Code_Point", &[("f", "No"), ("false", "No"), + ("n", "No"), ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), + ("yes", "Yes"), ]), + + ("Other_Grapheme_Extend", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Other_ID_Continue", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Other_ID_Start", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Other_Lowercase", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Other_Math", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Other_Uppercase", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Pattern_Syntax", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Pattern_White_Space", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Prepended_Concatenation_Mark", &[("f", "No"), ("false", "No"), + ("n", "No"), ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), + ("yes", "Yes"), ]), + + ("Quotation_Mark", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Radical", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Regional_Indicator", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Script", &[("adlam", "Adlam"), ("adlm", "Adlam"), + ("aghb", "Caucasian_Albanian"), ("ahom", "Ahom"), + ("anatolianhieroglyphs", "Anatolian_Hieroglyphs"), ("arab", "Arabic"), + ("arabic", "Arabic"), ("armenian", "Armenian"), + ("armi", "Imperial_Aramaic"), ("armn", "Armenian"), ("avestan", "Avestan"), + ("avst", "Avestan"), ("bali", "Balinese"), ("balinese", "Balinese"), + ("bamu", "Bamum"), ("bamum", "Bamum"), ("bass", "Bassa_Vah"), + ("bassavah", "Bassa_Vah"), ("batak", "Batak"), ("batk", "Batak"), + ("beng", "Bengali"), ("bengali", "Bengali"), ("bhaiksuki", "Bhaiksuki"), + ("bhks", "Bhaiksuki"), ("bopo", "Bopomofo"), ("bopomofo", "Bopomofo"), + ("brah", "Brahmi"), ("brahmi", "Brahmi"), ("brai", "Braille"), + ("braille", "Braille"), ("bugi", "Buginese"), ("buginese", "Buginese"), + ("buhd", "Buhid"), ("buhid", "Buhid"), ("cakm", "Chakma"), + ("canadianaboriginal", "Canadian_Aboriginal"), + ("cans", "Canadian_Aboriginal"), ("cari", "Carian"), ("carian", "Carian"), + ("caucasianalbanian", "Caucasian_Albanian"), ("chakma", "Chakma"), + ("cham", "Cham"), ("cher", "Cherokee"), ("cherokee", "Cherokee"), + ("common", "Common"), ("copt", "Coptic"), ("coptic", "Coptic"), + ("cprt", "Cypriot"), ("cuneiform", "Cuneiform"), ("cypriot", "Cypriot"), + ("cyrillic", "Cyrillic"), ("cyrl", "Cyrillic"), ("deseret", "Deseret"), + ("deva", "Devanagari"), ("devanagari", "Devanagari"), ("dsrt", "Deseret"), + ("dupl", "Duployan"), ("duployan", "Duployan"), + ("egyp", "Egyptian_Hieroglyphs"), + ("egyptianhieroglyphs", "Egyptian_Hieroglyphs"), ("elba", "Elbasan"), + ("elbasan", "Elbasan"), ("ethi", "Ethiopic"), ("ethiopic", "Ethiopic"), + ("geor", "Georgian"), ("georgian", "Georgian"), ("glag", "Glagolitic"), + ("glagolitic", "Glagolitic"), ("gonm", "Masaram_Gondi"), ("goth", "Gothic"), + ("gothic", "Gothic"), ("gran", "Grantha"), ("grantha", "Grantha"), + ("greek", "Greek"), ("grek", "Greek"), ("gujarati", "Gujarati"), + ("gujr", "Gujarati"), ("gurmukhi", "Gurmukhi"), ("guru", "Gurmukhi"), + ("han", "Han"), ("hang", "Hangul"), ("hangul", "Hangul"), ("hani", "Han"), + ("hano", "Hanunoo"), ("hanunoo", "Hanunoo"), ("hatr", "Hatran"), + ("hatran", "Hatran"), ("hebr", "Hebrew"), ("hebrew", "Hebrew"), + ("hira", "Hiragana"), ("hiragana", "Hiragana"), + ("hluw", "Anatolian_Hieroglyphs"), ("hmng", "Pahawh_Hmong"), + ("hrkt", "Katakana_Or_Hiragana"), ("hung", "Old_Hungarian"), + ("imperialaramaic", "Imperial_Aramaic"), ("inherited", "Inherited"), + ("inscriptionalpahlavi", "Inscriptional_Pahlavi"), + ("inscriptionalparthian", "Inscriptional_Parthian"), ("ital", "Old_Italic"), + ("java", "Javanese"), ("javanese", "Javanese"), ("kaithi", "Kaithi"), + ("kali", "Kayah_Li"), ("kana", "Katakana"), ("kannada", "Kannada"), + ("katakana", "Katakana"), ("katakanaorhiragana", "Katakana_Or_Hiragana"), + ("kayahli", "Kayah_Li"), ("khar", "Kharoshthi"), + ("kharoshthi", "Kharoshthi"), ("khmer", "Khmer"), ("khmr", "Khmer"), + ("khoj", "Khojki"), ("khojki", "Khojki"), ("khudawadi", "Khudawadi"), + ("knda", "Kannada"), ("kthi", "Kaithi"), ("lana", "Tai_Tham"), + ("lao", "Lao"), ("laoo", "Lao"), ("latin", "Latin"), ("latn", "Latin"), + ("lepc", "Lepcha"), ("lepcha", "Lepcha"), ("limb", "Limbu"), + ("limbu", "Limbu"), ("lina", "Linear_A"), ("linb", "Linear_B"), + ("lineara", "Linear_A"), ("linearb", "Linear_B"), ("lisu", "Lisu"), + ("lyci", "Lycian"), ("lycian", "Lycian"), ("lydi", "Lydian"), + ("lydian", "Lydian"), ("mahajani", "Mahajani"), ("mahj", "Mahajani"), + ("malayalam", "Malayalam"), ("mand", "Mandaic"), ("mandaic", "Mandaic"), + ("mani", "Manichaean"), ("manichaean", "Manichaean"), ("marc", "Marchen"), + ("marchen", "Marchen"), ("masaramgondi", "Masaram_Gondi"), + ("meeteimayek", "Meetei_Mayek"), ("mend", "Mende_Kikakui"), + ("mendekikakui", "Mende_Kikakui"), ("merc", "Meroitic_Cursive"), + ("mero", "Meroitic_Hieroglyphs"), ("meroiticcursive", "Meroitic_Cursive"), + ("meroitichieroglyphs", "Meroitic_Hieroglyphs"), ("miao", "Miao"), + ("mlym", "Malayalam"), ("modi", "Modi"), ("mong", "Mongolian"), + ("mongolian", "Mongolian"), ("mro", "Mro"), ("mroo", "Mro"), + ("mtei", "Meetei_Mayek"), ("mult", "Multani"), ("multani", "Multani"), + ("myanmar", "Myanmar"), ("mymr", "Myanmar"), ("nabataean", "Nabataean"), + ("narb", "Old_North_Arabian"), ("nbat", "Nabataean"), ("newa", "Newa"), + ("newtailue", "New_Tai_Lue"), ("nko", "Nko"), ("nkoo", "Nko"), + ("nshu", "Nushu"), ("nushu", "Nushu"), ("ogam", "Ogham"), + ("ogham", "Ogham"), ("olchiki", "Ol_Chiki"), ("olck", "Ol_Chiki"), + ("oldhungarian", "Old_Hungarian"), ("olditalic", "Old_Italic"), + ("oldnortharabian", "Old_North_Arabian"), ("oldpermic", "Old_Permic"), + ("oldpersian", "Old_Persian"), ("oldsoutharabian", "Old_South_Arabian"), + ("oldturkic", "Old_Turkic"), ("oriya", "Oriya"), ("orkh", "Old_Turkic"), + ("orya", "Oriya"), ("osage", "Osage"), ("osge", "Osage"), + ("osma", "Osmanya"), ("osmanya", "Osmanya"), + ("pahawhhmong", "Pahawh_Hmong"), ("palm", "Palmyrene"), + ("palmyrene", "Palmyrene"), ("pauc", "Pau_Cin_Hau"), + ("paucinhau", "Pau_Cin_Hau"), ("perm", "Old_Permic"), ("phag", "Phags_Pa"), + ("phagspa", "Phags_Pa"), ("phli", "Inscriptional_Pahlavi"), + ("phlp", "Psalter_Pahlavi"), ("phnx", "Phoenician"), + ("phoenician", "Phoenician"), ("plrd", "Miao"), + ("prti", "Inscriptional_Parthian"), ("psalterpahlavi", "Psalter_Pahlavi"), + ("qaac", "Coptic"), ("qaai", "Inherited"), ("rejang", "Rejang"), + ("rjng", "Rejang"), ("runic", "Runic"), ("runr", "Runic"), + ("samaritan", "Samaritan"), ("samr", "Samaritan"), + ("sarb", "Old_South_Arabian"), ("saur", "Saurashtra"), + ("saurashtra", "Saurashtra"), ("sgnw", "SignWriting"), + ("sharada", "Sharada"), ("shavian", "Shavian"), ("shaw", "Shavian"), + ("shrd", "Sharada"), ("sidd", "Siddham"), ("siddham", "Siddham"), + ("signwriting", "SignWriting"), ("sind", "Khudawadi"), ("sinh", "Sinhala"), + ("sinhala", "Sinhala"), ("sora", "Sora_Sompeng"), + ("sorasompeng", "Sora_Sompeng"), ("soyo", "Soyombo"), + ("soyombo", "Soyombo"), ("sund", "Sundanese"), ("sundanese", "Sundanese"), + ("sylo", "Syloti_Nagri"), ("sylotinagri", "Syloti_Nagri"), + ("syrc", "Syriac"), ("syriac", "Syriac"), ("tagalog", "Tagalog"), + ("tagb", "Tagbanwa"), ("tagbanwa", "Tagbanwa"), ("taile", "Tai_Le"), + ("taitham", "Tai_Tham"), ("taiviet", "Tai_Viet"), ("takr", "Takri"), + ("takri", "Takri"), ("tale", "Tai_Le"), ("talu", "New_Tai_Lue"), + ("tamil", "Tamil"), ("taml", "Tamil"), ("tang", "Tangut"), + ("tangut", "Tangut"), ("tavt", "Tai_Viet"), ("telu", "Telugu"), + ("telugu", "Telugu"), ("tfng", "Tifinagh"), ("tglg", "Tagalog"), + ("thaa", "Thaana"), ("thaana", "Thaana"), ("thai", "Thai"), + ("tibetan", "Tibetan"), ("tibt", "Tibetan"), ("tifinagh", "Tifinagh"), + ("tirh", "Tirhuta"), ("tirhuta", "Tirhuta"), ("ugar", "Ugaritic"), + ("ugaritic", "Ugaritic"), ("unknown", "Unknown"), ("vai", "Vai"), + ("vaii", "Vai"), ("wara", "Warang_Citi"), ("warangciti", "Warang_Citi"), + ("xpeo", "Old_Persian"), ("xsux", "Cuneiform"), ("yi", "Yi"), + ("yiii", "Yi"), ("zanabazarsquare", "Zanabazar_Square"), + ("zanb", "Zanabazar_Square"), ("zinh", "Inherited"), ("zyyy", "Common"), + ("zzzz", "Unknown"), ]), + + ("Sentence_Break", &[("at", "ATerm"), ("aterm", "ATerm"), ("cl", "Close"), + ("close", "Close"), ("cr", "CR"), ("ex", "Extend"), ("extend", "Extend"), + ("fo", "Format"), ("format", "Format"), ("le", "OLetter"), ("lf", "LF"), + ("lo", "Lower"), ("lower", "Lower"), ("nu", "Numeric"), + ("numeric", "Numeric"), ("oletter", "OLetter"), ("other", "Other"), + ("sc", "SContinue"), ("scontinue", "SContinue"), ("se", "Sep"), + ("sep", "Sep"), ("sp", "Sp"), ("st", "STerm"), ("sterm", "STerm"), + ("up", "Upper"), ("upper", "Upper"), ("xx", "Other"), ]), + + ("Sentence_Terminal", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Soft_Dotted", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Terminal_Punctuation", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Unified_Ideograph", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Uppercase", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Variation_Selector", &[("f", "No"), ("false", "No"), ("n", "No"), + ("no", "No"), ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), + ]), + + ("Vertical_Orientation", &[("r", "Rotated"), ("rotated", "Rotated"), + ("tr", "Transformed_Rotated"), + ("transformedrotated", "Transformed_Rotated"), + ("transformedupright", "Transformed_Upright"), + ("tu", "Transformed_Upright"), ("u", "Upright"), ("upright", "Upright"), ]), + + ("White_Space", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("Word_Break", &[("aletter", "ALetter"), ("cr", "CR"), + ("doublequote", "Double_Quote"), ("dq", "Double_Quote"), ("eb", "E_Base"), + ("ebase", "E_Base"), ("ebasegaz", "E_Base_GAZ"), ("ebg", "E_Base_GAZ"), + ("em", "E_Modifier"), ("emodifier", "E_Modifier"), ("ex", "ExtendNumLet"), + ("extend", "Extend"), ("extendnumlet", "ExtendNumLet"), ("fo", "Format"), + ("format", "Format"), ("gaz", "Glue_After_Zwj"), + ("glueafterzwj", "Glue_After_Zwj"), ("hebrewletter", "Hebrew_Letter"), + ("hl", "Hebrew_Letter"), ("ka", "Katakana"), ("katakana", "Katakana"), + ("le", "ALetter"), ("lf", "LF"), ("mb", "MidNumLet"), + ("midletter", "MidLetter"), ("midnum", "MidNum"), + ("midnumlet", "MidNumLet"), ("ml", "MidLetter"), ("mn", "MidNum"), + ("newline", "Newline"), ("nl", "Newline"), ("nu", "Numeric"), + ("numeric", "Numeric"), ("other", "Other"), + ("regionalindicator", "Regional_Indicator"), ("ri", "Regional_Indicator"), + ("singlequote", "Single_Quote"), ("sq", "Single_Quote"), ("xx", "Other"), + ("zwj", "ZWJ"), ]), + + ("XID_Continue", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), + + ("XID_Start", &[("f", "No"), ("false", "No"), ("n", "No"), ("no", "No"), + ("t", "Yes"), ("true", "Yes"), ("y", "Yes"), ("yes", "Yes"), ]), +]; diff -Nru cargo-0.25.0/vendor/unicode-xid-0.1.0/.cargo-checksum.json cargo-0.26.0/vendor/unicode-xid-0.1.0/.cargo-checksum.json --- cargo-0.25.0/vendor/unicode-xid-0.1.0/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/unicode-xid-0.1.0/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/unicode-xid-0.1.0/Cargo.toml cargo-0.26.0/vendor/unicode-xid-0.1.0/Cargo.toml --- cargo-0.25.0/vendor/unicode-xid-0.1.0/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/unicode-xid-0.1.0/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,26 @@ +[package] + +name = "unicode-xid" +version = "0.1.0" +authors = ["erick.tryzelaar <erick.tryzelaar@gmail.com>", + "kwantam <kwantam@gmail.com>", + ] + +homepage = "https://github.com/unicode-rs/unicode-xid" +repository = "https://github.com/unicode-rs/unicode-xid" +documentation = "https://unicode-rs.github.io/unicode-xid" +license = "MIT/Apache-2.0" +keywords = ["text", "unicode", "xid"] +readme = "README.md" +description = """ +Determine whether characters have the XID_Start +or XID_Continue properties according to +Unicode Standard Annex #31. +""" + +exclude = [ "target/*", "Cargo.lock" ] + +[features] +default = [] +no_std = [] +bench = [] diff -Nru cargo-0.25.0/vendor/unicode-xid-0.1.0/COPYRIGHT cargo-0.26.0/vendor/unicode-xid-0.1.0/COPYRIGHT --- cargo-0.25.0/vendor/unicode-xid-0.1.0/COPYRIGHT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/unicode-xid-0.1.0/COPYRIGHT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,7 @@ +Licensed under the Apache License, Version 2.0 +<LICENSE-APACHE or +http://www.apache.org/licenses/LICENSE-2.0> or the MIT +license <LICENSE-MIT or http://opensource.org/licenses/MIT>, +at your option. All files in the project carrying such +notice may not be copied, modified, or distributed except +according to those terms. diff -Nru cargo-0.25.0/vendor/unicode-xid-0.1.0/LICENSE-APACHE cargo-0.26.0/vendor/unicode-xid-0.1.0/LICENSE-APACHE --- cargo-0.25.0/vendor/unicode-xid-0.1.0/LICENSE-APACHE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/unicode-xid-0.1.0/LICENSE-APACHE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,201 @@ + 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. diff -Nru cargo-0.25.0/vendor/unicode-xid-0.1.0/LICENSE-MIT cargo-0.26.0/vendor/unicode-xid-0.1.0/LICENSE-MIT --- cargo-0.25.0/vendor/unicode-xid-0.1.0/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/unicode-xid-0.1.0/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +Copyright (c) 2015 The Rust Project 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. diff -Nru cargo-0.25.0/vendor/unicode-xid-0.1.0/README.md cargo-0.26.0/vendor/unicode-xid-0.1.0/README.md --- cargo-0.25.0/vendor/unicode-xid-0.1.0/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/unicode-xid-0.1.0/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,34 @@ +# unicode-xid + +Determine if a `char` is a valid identifier for a parser and/or lexer according to +[Unicode Standard Annex #31](http://www.unicode.org/reports/tr31/) rules. + +[![Build Status](https://travis-ci.org/unicode-rs/unicode-xid.svg)](https://travis-ci.org/unicode-rs/unicode-xid) + +[Documentation](https://unicode-rs.github.io/unicode-xid/unicode_xid/index.html) + +```rust +extern crate unicode_xid; + +use unicode_xid::UnicodeXID; + +fn main() { + let ch = 'a'; + println!("Is {} a valid start of an identifier? {}", ch, UnicodeXID::is_xid_start(ch)); +} +``` + +# features + +unicode-xid supports a `no_std` feature. This eliminates dependence +on std, and instead uses equivalent functions from core. + +# crates.io + +You can use this package in your project by adding the following +to your `Cargo.toml`: + +```toml +[dependencies] +unicode-xid = "0.0.4" +``` diff -Nru cargo-0.25.0/vendor/unicode-xid-0.1.0/scripts/unicode.py cargo-0.26.0/vendor/unicode-xid-0.1.0/scripts/unicode.py --- cargo-0.25.0/vendor/unicode-xid-0.1.0/scripts/unicode.py 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/unicode-xid-0.1.0/scripts/unicode.py 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,187 @@ +#!/usr/bin/env python +# +# Copyright 2011-2015 The Rust Project Developers. See the COPYRIGHT +# file at the top-level directory of this distribution and at +# http://rust-lang.org/COPYRIGHT. +# +# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +# option. This file may not be copied, modified, or distributed +# except according to those terms. + +# This script uses the following Unicode tables: +# - DerivedCoreProperties.txt +# - ReadMe.txt +# +# Since this should not require frequent updates, we just store this +# out-of-line and check the unicode.rs file into git. + +import fileinput, re, os, sys + +preamble = '''// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// NOTE: The following code was generated by "scripts/unicode.py", do not edit directly + +#![allow(missing_docs, non_upper_case_globals, non_snake_case)] +''' + +def fetch(f): + if not os.path.exists(os.path.basename(f)): + os.system("curl -O http://www.unicode.org/Public/UNIDATA/%s" + % f) + + if not os.path.exists(os.path.basename(f)): + sys.stderr.write("cannot load %s" % f) + exit(1) + +def group_cat(cat): + cat_out = [] + letters = sorted(set(cat)) + cur_start = letters.pop(0) + cur_end = cur_start + for letter in letters: + assert letter > cur_end, \ + "cur_end: %s, letter: %s" % (hex(cur_end), hex(letter)) + if letter == cur_end + 1: + cur_end = letter + else: + cat_out.append((cur_start, cur_end)) + cur_start = cur_end = letter + cat_out.append((cur_start, cur_end)) + return cat_out + +def ungroup_cat(cat): + cat_out = [] + for (lo, hi) in cat: + while lo <= hi: + cat_out.append(lo) + lo += 1 + return cat_out + +def format_table_content(f, content, indent): + line = " "*indent + first = True + for chunk in content.split(","): + if len(line) + len(chunk) < 98: + if first: + line += chunk + else: + line += ", " + chunk + first = False + else: + f.write(line + ",\n") + line = " "*indent + chunk + f.write(line) + +def load_properties(f, interestingprops): + fetch(f) + props = {} + re1 = re.compile("^ *([0-9A-F]+) *; *(\w+)") + re2 = re.compile("^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+)") + + for line in fileinput.input(os.path.basename(f)): + prop = None + d_lo = 0 + d_hi = 0 + m = re1.match(line) + if m: + d_lo = m.group(1) + d_hi = m.group(1) + prop = m.group(2) + else: + m = re2.match(line) + if m: + d_lo = m.group(1) + d_hi = m.group(2) + prop = m.group(3) + else: + continue + if interestingprops and prop not in interestingprops: + continue + d_lo = int(d_lo, 16) + d_hi = int(d_hi, 16) + if prop not in props: + props[prop] = [] + props[prop].append((d_lo, d_hi)) + + # optimize if possible + for prop in props: + props[prop] = group_cat(ungroup_cat(props[prop])) + + return props + +def escape_char(c): + return "'\\u{%x}'" % c + +def emit_bsearch_range_table(f): + f.write(""" +fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { + use core::cmp::Ordering::{Equal, Less, Greater}; + + r.binary_search_by(|&(lo,hi)| { + if lo <= c && c <= hi { Equal } + else if hi < c { Less } + else { Greater } + }).is_ok() +}\n +""") + +def emit_table(f, name, t_data, t_type = "&'static [(char, char)]", is_pub=True, + pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1])), is_const=True): + pub_string = "const" + if not is_const: + pub_string = "let" + if is_pub: + pub_string = "pub " + pub_string + f.write(" %s %s: %s = &[\n" % (pub_string, name, t_type)) + data = "" + first = True + for dat in t_data: + if not first: + data += "," + first = False + data += pfun(dat) + format_table_content(f, data, 8) + f.write("\n ];\n\n") + +def emit_property_module(f, mod, tbl, emit): + f.write("pub mod %s {\n" % mod) + for cat in sorted(emit): + emit_table(f, "%s_table" % cat, tbl[cat]) + f.write(" pub fn %s(c: char) -> bool {\n" % cat) + f.write(" super::bsearch_range_table(c, %s_table)\n" % cat) + f.write(" }\n\n") + f.write("}\n\n") + +if __name__ == "__main__": + r = "tables.rs" + if os.path.exists(r): + os.remove(r) + with open(r, "w") as rf: + # write the file's preamble + rf.write(preamble) + + # download and parse all the data + fetch("ReadMe.txt") + with open("ReadMe.txt") as readme: + pattern = "for Version (\d+)\.(\d+)\.(\d+) of the Unicode" + unicode_version = re.search(pattern, readme.read()).groups() + rf.write(""" +/// The version of [Unicode](http://www.unicode.org/) +/// that this version of unicode-xid is based on. +pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s); +""" % unicode_version) + emit_bsearch_range_table(rf) + + want_derived = ["XID_Start", "XID_Continue"] + derived = load_properties("DerivedCoreProperties.txt", want_derived) + emit_property_module(rf, "derived_property", derived, want_derived) diff -Nru cargo-0.25.0/vendor/unicode-xid-0.1.0/src/lib.rs cargo-0.26.0/vendor/unicode-xid-0.1.0/src/lib.rs --- cargo-0.25.0/vendor/unicode-xid-0.1.0/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/unicode-xid-0.1.0/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,87 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Determine if a `char` is a valid identifier for a parser and/or lexer according to +//! [Unicode Standard Annex #31](http://www.unicode.org/reports/tr31/) rules. +//! +//! ```rust +//! extern crate unicode_xid; +//! +//! use unicode_xid::UnicodeXID; +//! +//! fn main() { +//! let ch = 'a'; +//! println!("Is {} a valid start of an identifier? {}", ch, UnicodeXID::is_xid_start(ch)); +//! } +//! ``` +//! +//! # features +//! +//! unicode-xid supports a `no_std` feature. This eliminates dependence +//! on std, and instead uses equivalent functions from core. +//! +//! # crates.io +//! +//! You can use this package in your project by adding the following +//! to your `Cargo.toml`: +//! +//! ```toml +//! [dependencies] +//! unicode-xid = "0.0.4" +//! ``` + +#![deny(missing_docs, unsafe_code)] +#![doc(html_logo_url = "https://unicode-rs.github.io/unicode-rs_sm.png", + html_favicon_url = "https://unicode-rs.github.io/unicode-rs_sm.png")] + +#![no_std] +#![cfg_attr(feature = "bench", feature(test, unicode))] + +#[cfg(test)] +#[macro_use] +extern crate std; + +#[cfg(feature = "bench")] +extern crate test; + +use tables::derived_property; +pub use tables::UNICODE_VERSION; + +mod tables; + +#[cfg(test)] +mod tests; + +/// Methods for determining if a character is a valid identifier character. +pub trait UnicodeXID { + /// Returns whether the specified character satisfies the 'XID_Start' + /// Unicode property. + /// + /// 'XID_Start' is a Unicode Derived Property specified in + /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), + /// mostly similar to ID_Start but modified for closure under NFKx. + fn is_xid_start(self) -> bool; + + /// Returns whether the specified `char` satisfies the 'XID_Continue' + /// Unicode property. + /// + /// 'XID_Continue' is a Unicode Derived Property specified in + /// [UAX #31](http://unicode.org/reports/tr31/#NFKC_Modifications), + /// mostly similar to 'ID_Continue' but modified for closure under NFKx. + fn is_xid_continue(self) -> bool; +} + +impl UnicodeXID for char { + #[inline] + fn is_xid_start(self) -> bool { derived_property::XID_Start(self) } + + #[inline] + fn is_xid_continue(self) -> bool { derived_property::XID_Continue(self) } +} diff -Nru cargo-0.25.0/vendor/unicode-xid-0.1.0/src/tables.rs cargo-0.26.0/vendor/unicode-xid-0.1.0/src/tables.rs --- cargo-0.25.0/vendor/unicode-xid-0.1.0/src/tables.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/unicode-xid-0.1.0/src/tables.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,426 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// NOTE: The following code was generated by "scripts/unicode.py", do not edit directly + +#![allow(missing_docs, non_upper_case_globals, non_snake_case)] + +/// The version of [Unicode](http://www.unicode.org/) +/// that this version of unicode-xid is based on. +pub const UNICODE_VERSION: (u64, u64, u64) = (9, 0, 0); + +fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { + use core::cmp::Ordering::{Equal, Less, Greater}; + + r.binary_search_by(|&(lo,hi)| { + if lo <= c && c <= hi { Equal } + else if hi < c { Less } + else { Greater } + }).is_ok() +} + +pub mod derived_property { + pub const XID_Continue_table: &'static [(char, char)] = &[ + ('\u{30}', '\u{39}'), ('\u{41}', '\u{5a}'), ('\u{5f}', '\u{5f}'), ('\u{61}', '\u{7a}'), + ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), ('\u{b7}', '\u{b7}'), ('\u{ba}', '\u{ba}'), + ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{2c1}'), ('\u{2c6}', '\u{2d1}'), + ('\u{2e0}', '\u{2e4}'), ('\u{2ec}', '\u{2ec}'), ('\u{2ee}', '\u{2ee}'), ('\u{300}', + '\u{374}'), ('\u{376}', '\u{377}'), ('\u{37b}', '\u{37d}'), ('\u{37f}', '\u{37f}'), + ('\u{386}', '\u{38a}'), ('\u{38c}', '\u{38c}'), ('\u{38e}', '\u{3a1}'), ('\u{3a3}', + '\u{3f5}'), ('\u{3f7}', '\u{481}'), ('\u{483}', '\u{487}'), ('\u{48a}', '\u{52f}'), + ('\u{531}', '\u{556}'), ('\u{559}', '\u{559}'), ('\u{561}', '\u{587}'), ('\u{591}', + '\u{5bd}'), ('\u{5bf}', '\u{5bf}'), ('\u{5c1}', '\u{5c2}'), ('\u{5c4}', '\u{5c5}'), + ('\u{5c7}', '\u{5c7}'), ('\u{5d0}', '\u{5ea}'), ('\u{5f0}', '\u{5f2}'), ('\u{610}', + '\u{61a}'), ('\u{620}', '\u{669}'), ('\u{66e}', '\u{6d3}'), ('\u{6d5}', '\u{6dc}'), + ('\u{6df}', '\u{6e8}'), ('\u{6ea}', '\u{6fc}'), ('\u{6ff}', '\u{6ff}'), ('\u{710}', + '\u{74a}'), ('\u{74d}', '\u{7b1}'), ('\u{7c0}', '\u{7f5}'), ('\u{7fa}', '\u{7fa}'), + ('\u{800}', '\u{82d}'), ('\u{840}', '\u{85b}'), ('\u{8a0}', '\u{8b4}'), ('\u{8b6}', + '\u{8bd}'), ('\u{8d4}', '\u{8e1}'), ('\u{8e3}', '\u{963}'), ('\u{966}', '\u{96f}'), + ('\u{971}', '\u{983}'), ('\u{985}', '\u{98c}'), ('\u{98f}', '\u{990}'), ('\u{993}', + '\u{9a8}'), ('\u{9aa}', '\u{9b0}'), ('\u{9b2}', '\u{9b2}'), ('\u{9b6}', '\u{9b9}'), + ('\u{9bc}', '\u{9c4}'), ('\u{9c7}', '\u{9c8}'), ('\u{9cb}', '\u{9ce}'), ('\u{9d7}', + '\u{9d7}'), ('\u{9dc}', '\u{9dd}'), ('\u{9df}', '\u{9e3}'), ('\u{9e6}', '\u{9f1}'), + ('\u{a01}', '\u{a03}'), ('\u{a05}', '\u{a0a}'), ('\u{a0f}', '\u{a10}'), ('\u{a13}', + '\u{a28}'), ('\u{a2a}', '\u{a30}'), ('\u{a32}', '\u{a33}'), ('\u{a35}', '\u{a36}'), + ('\u{a38}', '\u{a39}'), ('\u{a3c}', '\u{a3c}'), ('\u{a3e}', '\u{a42}'), ('\u{a47}', + '\u{a48}'), ('\u{a4b}', '\u{a4d}'), ('\u{a51}', '\u{a51}'), ('\u{a59}', '\u{a5c}'), + ('\u{a5e}', '\u{a5e}'), ('\u{a66}', '\u{a75}'), ('\u{a81}', '\u{a83}'), ('\u{a85}', + '\u{a8d}'), ('\u{a8f}', '\u{a91}'), ('\u{a93}', '\u{aa8}'), ('\u{aaa}', '\u{ab0}'), + ('\u{ab2}', '\u{ab3}'), ('\u{ab5}', '\u{ab9}'), ('\u{abc}', '\u{ac5}'), ('\u{ac7}', + '\u{ac9}'), ('\u{acb}', '\u{acd}'), ('\u{ad0}', '\u{ad0}'), ('\u{ae0}', '\u{ae3}'), + ('\u{ae6}', '\u{aef}'), ('\u{af9}', '\u{af9}'), ('\u{b01}', '\u{b03}'), ('\u{b05}', + '\u{b0c}'), ('\u{b0f}', '\u{b10}'), ('\u{b13}', '\u{b28}'), ('\u{b2a}', '\u{b30}'), + ('\u{b32}', '\u{b33}'), ('\u{b35}', '\u{b39}'), ('\u{b3c}', '\u{b44}'), ('\u{b47}', + '\u{b48}'), ('\u{b4b}', '\u{b4d}'), ('\u{b56}', '\u{b57}'), ('\u{b5c}', '\u{b5d}'), + ('\u{b5f}', '\u{b63}'), ('\u{b66}', '\u{b6f}'), ('\u{b71}', '\u{b71}'), ('\u{b82}', + '\u{b83}'), ('\u{b85}', '\u{b8a}'), ('\u{b8e}', '\u{b90}'), ('\u{b92}', '\u{b95}'), + ('\u{b99}', '\u{b9a}'), ('\u{b9c}', '\u{b9c}'), ('\u{b9e}', '\u{b9f}'), ('\u{ba3}', + '\u{ba4}'), ('\u{ba8}', '\u{baa}'), ('\u{bae}', '\u{bb9}'), ('\u{bbe}', '\u{bc2}'), + ('\u{bc6}', '\u{bc8}'), ('\u{bca}', '\u{bcd}'), ('\u{bd0}', '\u{bd0}'), ('\u{bd7}', + '\u{bd7}'), ('\u{be6}', '\u{bef}'), ('\u{c00}', '\u{c03}'), ('\u{c05}', '\u{c0c}'), + ('\u{c0e}', '\u{c10}'), ('\u{c12}', '\u{c28}'), ('\u{c2a}', '\u{c39}'), ('\u{c3d}', + '\u{c44}'), ('\u{c46}', '\u{c48}'), ('\u{c4a}', '\u{c4d}'), ('\u{c55}', '\u{c56}'), + ('\u{c58}', '\u{c5a}'), ('\u{c60}', '\u{c63}'), ('\u{c66}', '\u{c6f}'), ('\u{c80}', + '\u{c83}'), ('\u{c85}', '\u{c8c}'), ('\u{c8e}', '\u{c90}'), ('\u{c92}', '\u{ca8}'), + ('\u{caa}', '\u{cb3}'), ('\u{cb5}', '\u{cb9}'), ('\u{cbc}', '\u{cc4}'), ('\u{cc6}', + '\u{cc8}'), ('\u{cca}', '\u{ccd}'), ('\u{cd5}', '\u{cd6}'), ('\u{cde}', '\u{cde}'), + ('\u{ce0}', '\u{ce3}'), ('\u{ce6}', '\u{cef}'), ('\u{cf1}', '\u{cf2}'), ('\u{d01}', + '\u{d03}'), ('\u{d05}', '\u{d0c}'), ('\u{d0e}', '\u{d10}'), ('\u{d12}', '\u{d3a}'), + ('\u{d3d}', '\u{d44}'), ('\u{d46}', '\u{d48}'), ('\u{d4a}', '\u{d4e}'), ('\u{d54}', + '\u{d57}'), ('\u{d5f}', '\u{d63}'), ('\u{d66}', '\u{d6f}'), ('\u{d7a}', '\u{d7f}'), + ('\u{d82}', '\u{d83}'), ('\u{d85}', '\u{d96}'), ('\u{d9a}', '\u{db1}'), ('\u{db3}', + '\u{dbb}'), ('\u{dbd}', '\u{dbd}'), ('\u{dc0}', '\u{dc6}'), ('\u{dca}', '\u{dca}'), + ('\u{dcf}', '\u{dd4}'), ('\u{dd6}', '\u{dd6}'), ('\u{dd8}', '\u{ddf}'), ('\u{de6}', + '\u{def}'), ('\u{df2}', '\u{df3}'), ('\u{e01}', '\u{e3a}'), ('\u{e40}', '\u{e4e}'), + ('\u{e50}', '\u{e59}'), ('\u{e81}', '\u{e82}'), ('\u{e84}', '\u{e84}'), ('\u{e87}', + '\u{e88}'), ('\u{e8a}', '\u{e8a}'), ('\u{e8d}', '\u{e8d}'), ('\u{e94}', '\u{e97}'), + ('\u{e99}', '\u{e9f}'), ('\u{ea1}', '\u{ea3}'), ('\u{ea5}', '\u{ea5}'), ('\u{ea7}', + '\u{ea7}'), ('\u{eaa}', '\u{eab}'), ('\u{ead}', '\u{eb9}'), ('\u{ebb}', '\u{ebd}'), + ('\u{ec0}', '\u{ec4}'), ('\u{ec6}', '\u{ec6}'), ('\u{ec8}', '\u{ecd}'), ('\u{ed0}', + '\u{ed9}'), ('\u{edc}', '\u{edf}'), ('\u{f00}', '\u{f00}'), ('\u{f18}', '\u{f19}'), + ('\u{f20}', '\u{f29}'), ('\u{f35}', '\u{f35}'), ('\u{f37}', '\u{f37}'), ('\u{f39}', + '\u{f39}'), ('\u{f3e}', '\u{f47}'), ('\u{f49}', '\u{f6c}'), ('\u{f71}', '\u{f84}'), + ('\u{f86}', '\u{f97}'), ('\u{f99}', '\u{fbc}'), ('\u{fc6}', '\u{fc6}'), ('\u{1000}', + '\u{1049}'), ('\u{1050}', '\u{109d}'), ('\u{10a0}', '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), + ('\u{10cd}', '\u{10cd}'), ('\u{10d0}', '\u{10fa}'), ('\u{10fc}', '\u{1248}'), ('\u{124a}', + '\u{124d}'), ('\u{1250}', '\u{1256}'), ('\u{1258}', '\u{1258}'), ('\u{125a}', '\u{125d}'), + ('\u{1260}', '\u{1288}'), ('\u{128a}', '\u{128d}'), ('\u{1290}', '\u{12b0}'), ('\u{12b2}', + '\u{12b5}'), ('\u{12b8}', '\u{12be}'), ('\u{12c0}', '\u{12c0}'), ('\u{12c2}', '\u{12c5}'), + ('\u{12c8}', '\u{12d6}'), ('\u{12d8}', '\u{1310}'), ('\u{1312}', '\u{1315}'), ('\u{1318}', + '\u{135a}'), ('\u{135d}', '\u{135f}'), ('\u{1369}', '\u{1371}'), ('\u{1380}', '\u{138f}'), + ('\u{13a0}', '\u{13f5}'), ('\u{13f8}', '\u{13fd}'), ('\u{1401}', '\u{166c}'), ('\u{166f}', + '\u{167f}'), ('\u{1681}', '\u{169a}'), ('\u{16a0}', '\u{16ea}'), ('\u{16ee}', '\u{16f8}'), + ('\u{1700}', '\u{170c}'), ('\u{170e}', '\u{1714}'), ('\u{1720}', '\u{1734}'), ('\u{1740}', + '\u{1753}'), ('\u{1760}', '\u{176c}'), ('\u{176e}', '\u{1770}'), ('\u{1772}', '\u{1773}'), + ('\u{1780}', '\u{17d3}'), ('\u{17d7}', '\u{17d7}'), ('\u{17dc}', '\u{17dd}'), ('\u{17e0}', + '\u{17e9}'), ('\u{180b}', '\u{180d}'), ('\u{1810}', '\u{1819}'), ('\u{1820}', '\u{1877}'), + ('\u{1880}', '\u{18aa}'), ('\u{18b0}', '\u{18f5}'), ('\u{1900}', '\u{191e}'), ('\u{1920}', + '\u{192b}'), ('\u{1930}', '\u{193b}'), ('\u{1946}', '\u{196d}'), ('\u{1970}', '\u{1974}'), + ('\u{1980}', '\u{19ab}'), ('\u{19b0}', '\u{19c9}'), ('\u{19d0}', '\u{19da}'), ('\u{1a00}', + '\u{1a1b}'), ('\u{1a20}', '\u{1a5e}'), ('\u{1a60}', '\u{1a7c}'), ('\u{1a7f}', '\u{1a89}'), + ('\u{1a90}', '\u{1a99}'), ('\u{1aa7}', '\u{1aa7}'), ('\u{1ab0}', '\u{1abd}'), ('\u{1b00}', + '\u{1b4b}'), ('\u{1b50}', '\u{1b59}'), ('\u{1b6b}', '\u{1b73}'), ('\u{1b80}', '\u{1bf3}'), + ('\u{1c00}', '\u{1c37}'), ('\u{1c40}', '\u{1c49}'), ('\u{1c4d}', '\u{1c7d}'), ('\u{1c80}', + '\u{1c88}'), ('\u{1cd0}', '\u{1cd2}'), ('\u{1cd4}', '\u{1cf6}'), ('\u{1cf8}', '\u{1cf9}'), + ('\u{1d00}', '\u{1df5}'), ('\u{1dfb}', '\u{1f15}'), ('\u{1f18}', '\u{1f1d}'), ('\u{1f20}', + '\u{1f45}'), ('\u{1f48}', '\u{1f4d}'), ('\u{1f50}', '\u{1f57}'), ('\u{1f59}', '\u{1f59}'), + ('\u{1f5b}', '\u{1f5b}'), ('\u{1f5d}', '\u{1f5d}'), ('\u{1f5f}', '\u{1f7d}'), ('\u{1f80}', + '\u{1fb4}'), ('\u{1fb6}', '\u{1fbc}'), ('\u{1fbe}', '\u{1fbe}'), ('\u{1fc2}', '\u{1fc4}'), + ('\u{1fc6}', '\u{1fcc}'), ('\u{1fd0}', '\u{1fd3}'), ('\u{1fd6}', '\u{1fdb}'), ('\u{1fe0}', + '\u{1fec}'), ('\u{1ff2}', '\u{1ff4}'), ('\u{1ff6}', '\u{1ffc}'), ('\u{203f}', '\u{2040}'), + ('\u{2054}', '\u{2054}'), ('\u{2071}', '\u{2071}'), ('\u{207f}', '\u{207f}'), ('\u{2090}', + '\u{209c}'), ('\u{20d0}', '\u{20dc}'), ('\u{20e1}', '\u{20e1}'), ('\u{20e5}', '\u{20f0}'), + ('\u{2102}', '\u{2102}'), ('\u{2107}', '\u{2107}'), ('\u{210a}', '\u{2113}'), ('\u{2115}', + '\u{2115}'), ('\u{2118}', '\u{211d}'), ('\u{2124}', '\u{2124}'), ('\u{2126}', '\u{2126}'), + ('\u{2128}', '\u{2128}'), ('\u{212a}', '\u{2139}'), ('\u{213c}', '\u{213f}'), ('\u{2145}', + '\u{2149}'), ('\u{214e}', '\u{214e}'), ('\u{2160}', '\u{2188}'), ('\u{2c00}', '\u{2c2e}'), + ('\u{2c30}', '\u{2c5e}'), ('\u{2c60}', '\u{2ce4}'), ('\u{2ceb}', '\u{2cf3}'), ('\u{2d00}', + '\u{2d25}'), ('\u{2d27}', '\u{2d27}'), ('\u{2d2d}', '\u{2d2d}'), ('\u{2d30}', '\u{2d67}'), + ('\u{2d6f}', '\u{2d6f}'), ('\u{2d7f}', '\u{2d96}'), ('\u{2da0}', '\u{2da6}'), ('\u{2da8}', + '\u{2dae}'), ('\u{2db0}', '\u{2db6}'), ('\u{2db8}', '\u{2dbe}'), ('\u{2dc0}', '\u{2dc6}'), + ('\u{2dc8}', '\u{2dce}'), ('\u{2dd0}', '\u{2dd6}'), ('\u{2dd8}', '\u{2dde}'), ('\u{2de0}', + '\u{2dff}'), ('\u{3005}', '\u{3007}'), ('\u{3021}', '\u{302f}'), ('\u{3031}', '\u{3035}'), + ('\u{3038}', '\u{303c}'), ('\u{3041}', '\u{3096}'), ('\u{3099}', '\u{309a}'), ('\u{309d}', + '\u{309f}'), ('\u{30a1}', '\u{30fa}'), ('\u{30fc}', '\u{30ff}'), ('\u{3105}', '\u{312d}'), + ('\u{3131}', '\u{318e}'), ('\u{31a0}', '\u{31ba}'), ('\u{31f0}', '\u{31ff}'), ('\u{3400}', + '\u{4db5}'), ('\u{4e00}', '\u{9fd5}'), ('\u{a000}', '\u{a48c}'), ('\u{a4d0}', '\u{a4fd}'), + ('\u{a500}', '\u{a60c}'), ('\u{a610}', '\u{a62b}'), ('\u{a640}', '\u{a66f}'), ('\u{a674}', + '\u{a67d}'), ('\u{a67f}', '\u{a6f1}'), ('\u{a717}', '\u{a71f}'), ('\u{a722}', '\u{a788}'), + ('\u{a78b}', '\u{a7ae}'), ('\u{a7b0}', '\u{a7b7}'), ('\u{a7f7}', '\u{a827}'), ('\u{a840}', + '\u{a873}'), ('\u{a880}', '\u{a8c5}'), ('\u{a8d0}', '\u{a8d9}'), ('\u{a8e0}', '\u{a8f7}'), + ('\u{a8fb}', '\u{a8fb}'), ('\u{a8fd}', '\u{a8fd}'), ('\u{a900}', '\u{a92d}'), ('\u{a930}', + '\u{a953}'), ('\u{a960}', '\u{a97c}'), ('\u{a980}', '\u{a9c0}'), ('\u{a9cf}', '\u{a9d9}'), + ('\u{a9e0}', '\u{a9fe}'), ('\u{aa00}', '\u{aa36}'), ('\u{aa40}', '\u{aa4d}'), ('\u{aa50}', + '\u{aa59}'), ('\u{aa60}', '\u{aa76}'), ('\u{aa7a}', '\u{aac2}'), ('\u{aadb}', '\u{aadd}'), + ('\u{aae0}', '\u{aaef}'), ('\u{aaf2}', '\u{aaf6}'), ('\u{ab01}', '\u{ab06}'), ('\u{ab09}', + '\u{ab0e}'), ('\u{ab11}', '\u{ab16}'), ('\u{ab20}', '\u{ab26}'), ('\u{ab28}', '\u{ab2e}'), + ('\u{ab30}', '\u{ab5a}'), ('\u{ab5c}', '\u{ab65}'), ('\u{ab70}', '\u{abea}'), ('\u{abec}', + '\u{abed}'), ('\u{abf0}', '\u{abf9}'), ('\u{ac00}', '\u{d7a3}'), ('\u{d7b0}', '\u{d7c6}'), + ('\u{d7cb}', '\u{d7fb}'), ('\u{f900}', '\u{fa6d}'), ('\u{fa70}', '\u{fad9}'), ('\u{fb00}', + '\u{fb06}'), ('\u{fb13}', '\u{fb17}'), ('\u{fb1d}', '\u{fb28}'), ('\u{fb2a}', '\u{fb36}'), + ('\u{fb38}', '\u{fb3c}'), ('\u{fb3e}', '\u{fb3e}'), ('\u{fb40}', '\u{fb41}'), ('\u{fb43}', + '\u{fb44}'), ('\u{fb46}', '\u{fbb1}'), ('\u{fbd3}', '\u{fc5d}'), ('\u{fc64}', '\u{fd3d}'), + ('\u{fd50}', '\u{fd8f}'), ('\u{fd92}', '\u{fdc7}'), ('\u{fdf0}', '\u{fdf9}'), ('\u{fe00}', + '\u{fe0f}'), ('\u{fe20}', '\u{fe2f}'), ('\u{fe33}', '\u{fe34}'), ('\u{fe4d}', '\u{fe4f}'), + ('\u{fe71}', '\u{fe71}'), ('\u{fe73}', '\u{fe73}'), ('\u{fe77}', '\u{fe77}'), ('\u{fe79}', + '\u{fe79}'), ('\u{fe7b}', '\u{fe7b}'), ('\u{fe7d}', '\u{fe7d}'), ('\u{fe7f}', '\u{fefc}'), + ('\u{ff10}', '\u{ff19}'), ('\u{ff21}', '\u{ff3a}'), ('\u{ff3f}', '\u{ff3f}'), ('\u{ff41}', + '\u{ff5a}'), ('\u{ff66}', '\u{ffbe}'), ('\u{ffc2}', '\u{ffc7}'), ('\u{ffca}', '\u{ffcf}'), + ('\u{ffd2}', '\u{ffd7}'), ('\u{ffda}', '\u{ffdc}'), ('\u{10000}', '\u{1000b}'), + ('\u{1000d}', '\u{10026}'), ('\u{10028}', '\u{1003a}'), ('\u{1003c}', '\u{1003d}'), + ('\u{1003f}', '\u{1004d}'), ('\u{10050}', '\u{1005d}'), ('\u{10080}', '\u{100fa}'), + ('\u{10140}', '\u{10174}'), ('\u{101fd}', '\u{101fd}'), ('\u{10280}', '\u{1029c}'), + ('\u{102a0}', '\u{102d0}'), ('\u{102e0}', '\u{102e0}'), ('\u{10300}', '\u{1031f}'), + ('\u{10330}', '\u{1034a}'), ('\u{10350}', '\u{1037a}'), ('\u{10380}', '\u{1039d}'), + ('\u{103a0}', '\u{103c3}'), ('\u{103c8}', '\u{103cf}'), ('\u{103d1}', '\u{103d5}'), + ('\u{10400}', '\u{1049d}'), ('\u{104a0}', '\u{104a9}'), ('\u{104b0}', '\u{104d3}'), + ('\u{104d8}', '\u{104fb}'), ('\u{10500}', '\u{10527}'), ('\u{10530}', '\u{10563}'), + ('\u{10600}', '\u{10736}'), ('\u{10740}', '\u{10755}'), ('\u{10760}', '\u{10767}'), + ('\u{10800}', '\u{10805}'), ('\u{10808}', '\u{10808}'), ('\u{1080a}', '\u{10835}'), + ('\u{10837}', '\u{10838}'), ('\u{1083c}', '\u{1083c}'), ('\u{1083f}', '\u{10855}'), + ('\u{10860}', '\u{10876}'), ('\u{10880}', '\u{1089e}'), ('\u{108e0}', '\u{108f2}'), + ('\u{108f4}', '\u{108f5}'), ('\u{10900}', '\u{10915}'), ('\u{10920}', '\u{10939}'), + ('\u{10980}', '\u{109b7}'), ('\u{109be}', '\u{109bf}'), ('\u{10a00}', '\u{10a03}'), + ('\u{10a05}', '\u{10a06}'), ('\u{10a0c}', '\u{10a13}'), ('\u{10a15}', '\u{10a17}'), + ('\u{10a19}', '\u{10a33}'), ('\u{10a38}', '\u{10a3a}'), ('\u{10a3f}', '\u{10a3f}'), + ('\u{10a60}', '\u{10a7c}'), ('\u{10a80}', '\u{10a9c}'), ('\u{10ac0}', '\u{10ac7}'), + ('\u{10ac9}', '\u{10ae6}'), ('\u{10b00}', '\u{10b35}'), ('\u{10b40}', '\u{10b55}'), + ('\u{10b60}', '\u{10b72}'), ('\u{10b80}', '\u{10b91}'), ('\u{10c00}', '\u{10c48}'), + ('\u{10c80}', '\u{10cb2}'), ('\u{10cc0}', '\u{10cf2}'), ('\u{11000}', '\u{11046}'), + ('\u{11066}', '\u{1106f}'), ('\u{1107f}', '\u{110ba}'), ('\u{110d0}', '\u{110e8}'), + ('\u{110f0}', '\u{110f9}'), ('\u{11100}', '\u{11134}'), ('\u{11136}', '\u{1113f}'), + ('\u{11150}', '\u{11173}'), ('\u{11176}', '\u{11176}'), ('\u{11180}', '\u{111c4}'), + ('\u{111ca}', '\u{111cc}'), ('\u{111d0}', '\u{111da}'), ('\u{111dc}', '\u{111dc}'), + ('\u{11200}', '\u{11211}'), ('\u{11213}', '\u{11237}'), ('\u{1123e}', '\u{1123e}'), + ('\u{11280}', '\u{11286}'), ('\u{11288}', '\u{11288}'), ('\u{1128a}', '\u{1128d}'), + ('\u{1128f}', '\u{1129d}'), ('\u{1129f}', '\u{112a8}'), ('\u{112b0}', '\u{112ea}'), + ('\u{112f0}', '\u{112f9}'), ('\u{11300}', '\u{11303}'), ('\u{11305}', '\u{1130c}'), + ('\u{1130f}', '\u{11310}'), ('\u{11313}', '\u{11328}'), ('\u{1132a}', '\u{11330}'), + ('\u{11332}', '\u{11333}'), ('\u{11335}', '\u{11339}'), ('\u{1133c}', '\u{11344}'), + ('\u{11347}', '\u{11348}'), ('\u{1134b}', '\u{1134d}'), ('\u{11350}', '\u{11350}'), + ('\u{11357}', '\u{11357}'), ('\u{1135d}', '\u{11363}'), ('\u{11366}', '\u{1136c}'), + ('\u{11370}', '\u{11374}'), ('\u{11400}', '\u{1144a}'), ('\u{11450}', '\u{11459}'), + ('\u{11480}', '\u{114c5}'), ('\u{114c7}', '\u{114c7}'), ('\u{114d0}', '\u{114d9}'), + ('\u{11580}', '\u{115b5}'), ('\u{115b8}', '\u{115c0}'), ('\u{115d8}', '\u{115dd}'), + ('\u{11600}', '\u{11640}'), ('\u{11644}', '\u{11644}'), ('\u{11650}', '\u{11659}'), + ('\u{11680}', '\u{116b7}'), ('\u{116c0}', '\u{116c9}'), ('\u{11700}', '\u{11719}'), + ('\u{1171d}', '\u{1172b}'), ('\u{11730}', '\u{11739}'), ('\u{118a0}', '\u{118e9}'), + ('\u{118ff}', '\u{118ff}'), ('\u{11ac0}', '\u{11af8}'), ('\u{11c00}', '\u{11c08}'), + ('\u{11c0a}', '\u{11c36}'), ('\u{11c38}', '\u{11c40}'), ('\u{11c50}', '\u{11c59}'), + ('\u{11c72}', '\u{11c8f}'), ('\u{11c92}', '\u{11ca7}'), ('\u{11ca9}', '\u{11cb6}'), + ('\u{12000}', '\u{12399}'), ('\u{12400}', '\u{1246e}'), ('\u{12480}', '\u{12543}'), + ('\u{13000}', '\u{1342e}'), ('\u{14400}', '\u{14646}'), ('\u{16800}', '\u{16a38}'), + ('\u{16a40}', '\u{16a5e}'), ('\u{16a60}', '\u{16a69}'), ('\u{16ad0}', '\u{16aed}'), + ('\u{16af0}', '\u{16af4}'), ('\u{16b00}', '\u{16b36}'), ('\u{16b40}', '\u{16b43}'), + ('\u{16b50}', '\u{16b59}'), ('\u{16b63}', '\u{16b77}'), ('\u{16b7d}', '\u{16b8f}'), + ('\u{16f00}', '\u{16f44}'), ('\u{16f50}', '\u{16f7e}'), ('\u{16f8f}', '\u{16f9f}'), + ('\u{16fe0}', '\u{16fe0}'), ('\u{17000}', '\u{187ec}'), ('\u{18800}', '\u{18af2}'), + ('\u{1b000}', '\u{1b001}'), ('\u{1bc00}', '\u{1bc6a}'), ('\u{1bc70}', '\u{1bc7c}'), + ('\u{1bc80}', '\u{1bc88}'), ('\u{1bc90}', '\u{1bc99}'), ('\u{1bc9d}', '\u{1bc9e}'), + ('\u{1d165}', '\u{1d169}'), ('\u{1d16d}', '\u{1d172}'), ('\u{1d17b}', '\u{1d182}'), + ('\u{1d185}', '\u{1d18b}'), ('\u{1d1aa}', '\u{1d1ad}'), ('\u{1d242}', '\u{1d244}'), + ('\u{1d400}', '\u{1d454}'), ('\u{1d456}', '\u{1d49c}'), ('\u{1d49e}', '\u{1d49f}'), + ('\u{1d4a2}', '\u{1d4a2}'), ('\u{1d4a5}', '\u{1d4a6}'), ('\u{1d4a9}', '\u{1d4ac}'), + ('\u{1d4ae}', '\u{1d4b9}'), ('\u{1d4bb}', '\u{1d4bb}'), ('\u{1d4bd}', '\u{1d4c3}'), + ('\u{1d4c5}', '\u{1d505}'), ('\u{1d507}', '\u{1d50a}'), ('\u{1d50d}', '\u{1d514}'), + ('\u{1d516}', '\u{1d51c}'), ('\u{1d51e}', '\u{1d539}'), ('\u{1d53b}', '\u{1d53e}'), + ('\u{1d540}', '\u{1d544}'), ('\u{1d546}', '\u{1d546}'), ('\u{1d54a}', '\u{1d550}'), + ('\u{1d552}', '\u{1d6a5}'), ('\u{1d6a8}', '\u{1d6c0}'), ('\u{1d6c2}', '\u{1d6da}'), + ('\u{1d6dc}', '\u{1d6fa}'), ('\u{1d6fc}', '\u{1d714}'), ('\u{1d716}', '\u{1d734}'), + ('\u{1d736}', '\u{1d74e}'), ('\u{1d750}', '\u{1d76e}'), ('\u{1d770}', '\u{1d788}'), + ('\u{1d78a}', '\u{1d7a8}'), ('\u{1d7aa}', '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7cb}'), + ('\u{1d7ce}', '\u{1d7ff}'), ('\u{1da00}', '\u{1da36}'), ('\u{1da3b}', '\u{1da6c}'), + ('\u{1da75}', '\u{1da75}'), ('\u{1da84}', '\u{1da84}'), ('\u{1da9b}', '\u{1da9f}'), + ('\u{1daa1}', '\u{1daaf}'), ('\u{1e000}', '\u{1e006}'), ('\u{1e008}', '\u{1e018}'), + ('\u{1e01b}', '\u{1e021}'), ('\u{1e023}', '\u{1e024}'), ('\u{1e026}', '\u{1e02a}'), + ('\u{1e800}', '\u{1e8c4}'), ('\u{1e8d0}', '\u{1e8d6}'), ('\u{1e900}', '\u{1e94a}'), + ('\u{1e950}', '\u{1e959}'), ('\u{1ee00}', '\u{1ee03}'), ('\u{1ee05}', '\u{1ee1f}'), + ('\u{1ee21}', '\u{1ee22}'), ('\u{1ee24}', '\u{1ee24}'), ('\u{1ee27}', '\u{1ee27}'), + ('\u{1ee29}', '\u{1ee32}'), ('\u{1ee34}', '\u{1ee37}'), ('\u{1ee39}', '\u{1ee39}'), + ('\u{1ee3b}', '\u{1ee3b}'), ('\u{1ee42}', '\u{1ee42}'), ('\u{1ee47}', '\u{1ee47}'), + ('\u{1ee49}', '\u{1ee49}'), ('\u{1ee4b}', '\u{1ee4b}'), ('\u{1ee4d}', '\u{1ee4f}'), + ('\u{1ee51}', '\u{1ee52}'), ('\u{1ee54}', '\u{1ee54}'), ('\u{1ee57}', '\u{1ee57}'), + ('\u{1ee59}', '\u{1ee59}'), ('\u{1ee5b}', '\u{1ee5b}'), ('\u{1ee5d}', '\u{1ee5d}'), + ('\u{1ee5f}', '\u{1ee5f}'), ('\u{1ee61}', '\u{1ee62}'), ('\u{1ee64}', '\u{1ee64}'), + ('\u{1ee67}', '\u{1ee6a}'), ('\u{1ee6c}', '\u{1ee72}'), ('\u{1ee74}', '\u{1ee77}'), + ('\u{1ee79}', '\u{1ee7c}'), ('\u{1ee7e}', '\u{1ee7e}'), ('\u{1ee80}', '\u{1ee89}'), + ('\u{1ee8b}', '\u{1ee9b}'), ('\u{1eea1}', '\u{1eea3}'), ('\u{1eea5}', '\u{1eea9}'), + ('\u{1eeab}', '\u{1eebb}'), ('\u{20000}', '\u{2a6d6}'), ('\u{2a700}', '\u{2b734}'), + ('\u{2b740}', '\u{2b81d}'), ('\u{2b820}', '\u{2cea1}'), ('\u{2f800}', '\u{2fa1d}'), + ('\u{e0100}', '\u{e01ef}') + ]; + + pub fn XID_Continue(c: char) -> bool { + super::bsearch_range_table(c, XID_Continue_table) + } + + pub const XID_Start_table: &'static [(char, char)] = &[ + ('\u{41}', '\u{5a}'), ('\u{61}', '\u{7a}'), ('\u{aa}', '\u{aa}'), ('\u{b5}', '\u{b5}'), + ('\u{ba}', '\u{ba}'), ('\u{c0}', '\u{d6}'), ('\u{d8}', '\u{f6}'), ('\u{f8}', '\u{2c1}'), + ('\u{2c6}', '\u{2d1}'), ('\u{2e0}', '\u{2e4}'), ('\u{2ec}', '\u{2ec}'), ('\u{2ee}', + '\u{2ee}'), ('\u{370}', '\u{374}'), ('\u{376}', '\u{377}'), ('\u{37b}', '\u{37d}'), + ('\u{37f}', '\u{37f}'), ('\u{386}', '\u{386}'), ('\u{388}', '\u{38a}'), ('\u{38c}', + '\u{38c}'), ('\u{38e}', '\u{3a1}'), ('\u{3a3}', '\u{3f5}'), ('\u{3f7}', '\u{481}'), + ('\u{48a}', '\u{52f}'), ('\u{531}', '\u{556}'), ('\u{559}', '\u{559}'), ('\u{561}', + '\u{587}'), ('\u{5d0}', '\u{5ea}'), ('\u{5f0}', '\u{5f2}'), ('\u{620}', '\u{64a}'), + ('\u{66e}', '\u{66f}'), ('\u{671}', '\u{6d3}'), ('\u{6d5}', '\u{6d5}'), ('\u{6e5}', + '\u{6e6}'), ('\u{6ee}', '\u{6ef}'), ('\u{6fa}', '\u{6fc}'), ('\u{6ff}', '\u{6ff}'), + ('\u{710}', '\u{710}'), ('\u{712}', '\u{72f}'), ('\u{74d}', '\u{7a5}'), ('\u{7b1}', + '\u{7b1}'), ('\u{7ca}', '\u{7ea}'), ('\u{7f4}', '\u{7f5}'), ('\u{7fa}', '\u{7fa}'), + ('\u{800}', '\u{815}'), ('\u{81a}', '\u{81a}'), ('\u{824}', '\u{824}'), ('\u{828}', + '\u{828}'), ('\u{840}', '\u{858}'), ('\u{8a0}', '\u{8b4}'), ('\u{8b6}', '\u{8bd}'), + ('\u{904}', '\u{939}'), ('\u{93d}', '\u{93d}'), ('\u{950}', '\u{950}'), ('\u{958}', + '\u{961}'), ('\u{971}', '\u{980}'), ('\u{985}', '\u{98c}'), ('\u{98f}', '\u{990}'), + ('\u{993}', '\u{9a8}'), ('\u{9aa}', '\u{9b0}'), ('\u{9b2}', '\u{9b2}'), ('\u{9b6}', + '\u{9b9}'), ('\u{9bd}', '\u{9bd}'), ('\u{9ce}', '\u{9ce}'), ('\u{9dc}', '\u{9dd}'), + ('\u{9df}', '\u{9e1}'), ('\u{9f0}', '\u{9f1}'), ('\u{a05}', '\u{a0a}'), ('\u{a0f}', + '\u{a10}'), ('\u{a13}', '\u{a28}'), ('\u{a2a}', '\u{a30}'), ('\u{a32}', '\u{a33}'), + ('\u{a35}', '\u{a36}'), ('\u{a38}', '\u{a39}'), ('\u{a59}', '\u{a5c}'), ('\u{a5e}', + '\u{a5e}'), ('\u{a72}', '\u{a74}'), ('\u{a85}', '\u{a8d}'), ('\u{a8f}', '\u{a91}'), + ('\u{a93}', '\u{aa8}'), ('\u{aaa}', '\u{ab0}'), ('\u{ab2}', '\u{ab3}'), ('\u{ab5}', + '\u{ab9}'), ('\u{abd}', '\u{abd}'), ('\u{ad0}', '\u{ad0}'), ('\u{ae0}', '\u{ae1}'), + ('\u{af9}', '\u{af9}'), ('\u{b05}', '\u{b0c}'), ('\u{b0f}', '\u{b10}'), ('\u{b13}', + '\u{b28}'), ('\u{b2a}', '\u{b30}'), ('\u{b32}', '\u{b33}'), ('\u{b35}', '\u{b39}'), + ('\u{b3d}', '\u{b3d}'), ('\u{b5c}', '\u{b5d}'), ('\u{b5f}', '\u{b61}'), ('\u{b71}', + '\u{b71}'), ('\u{b83}', '\u{b83}'), ('\u{b85}', '\u{b8a}'), ('\u{b8e}', '\u{b90}'), + ('\u{b92}', '\u{b95}'), ('\u{b99}', '\u{b9a}'), ('\u{b9c}', '\u{b9c}'), ('\u{b9e}', + '\u{b9f}'), ('\u{ba3}', '\u{ba4}'), ('\u{ba8}', '\u{baa}'), ('\u{bae}', '\u{bb9}'), + ('\u{bd0}', '\u{bd0}'), ('\u{c05}', '\u{c0c}'), ('\u{c0e}', '\u{c10}'), ('\u{c12}', + '\u{c28}'), ('\u{c2a}', '\u{c39}'), ('\u{c3d}', '\u{c3d}'), ('\u{c58}', '\u{c5a}'), + ('\u{c60}', '\u{c61}'), ('\u{c80}', '\u{c80}'), ('\u{c85}', '\u{c8c}'), ('\u{c8e}', + '\u{c90}'), ('\u{c92}', '\u{ca8}'), ('\u{caa}', '\u{cb3}'), ('\u{cb5}', '\u{cb9}'), + ('\u{cbd}', '\u{cbd}'), ('\u{cde}', '\u{cde}'), ('\u{ce0}', '\u{ce1}'), ('\u{cf1}', + '\u{cf2}'), ('\u{d05}', '\u{d0c}'), ('\u{d0e}', '\u{d10}'), ('\u{d12}', '\u{d3a}'), + ('\u{d3d}', '\u{d3d}'), ('\u{d4e}', '\u{d4e}'), ('\u{d54}', '\u{d56}'), ('\u{d5f}', + '\u{d61}'), ('\u{d7a}', '\u{d7f}'), ('\u{d85}', '\u{d96}'), ('\u{d9a}', '\u{db1}'), + ('\u{db3}', '\u{dbb}'), ('\u{dbd}', '\u{dbd}'), ('\u{dc0}', '\u{dc6}'), ('\u{e01}', + '\u{e30}'), ('\u{e32}', '\u{e32}'), ('\u{e40}', '\u{e46}'), ('\u{e81}', '\u{e82}'), + ('\u{e84}', '\u{e84}'), ('\u{e87}', '\u{e88}'), ('\u{e8a}', '\u{e8a}'), ('\u{e8d}', + '\u{e8d}'), ('\u{e94}', '\u{e97}'), ('\u{e99}', '\u{e9f}'), ('\u{ea1}', '\u{ea3}'), + ('\u{ea5}', '\u{ea5}'), ('\u{ea7}', '\u{ea7}'), ('\u{eaa}', '\u{eab}'), ('\u{ead}', + '\u{eb0}'), ('\u{eb2}', '\u{eb2}'), ('\u{ebd}', '\u{ebd}'), ('\u{ec0}', '\u{ec4}'), + ('\u{ec6}', '\u{ec6}'), ('\u{edc}', '\u{edf}'), ('\u{f00}', '\u{f00}'), ('\u{f40}', + '\u{f47}'), ('\u{f49}', '\u{f6c}'), ('\u{f88}', '\u{f8c}'), ('\u{1000}', '\u{102a}'), + ('\u{103f}', '\u{103f}'), ('\u{1050}', '\u{1055}'), ('\u{105a}', '\u{105d}'), ('\u{1061}', + '\u{1061}'), ('\u{1065}', '\u{1066}'), ('\u{106e}', '\u{1070}'), ('\u{1075}', '\u{1081}'), + ('\u{108e}', '\u{108e}'), ('\u{10a0}', '\u{10c5}'), ('\u{10c7}', '\u{10c7}'), ('\u{10cd}', + '\u{10cd}'), ('\u{10d0}', '\u{10fa}'), ('\u{10fc}', '\u{1248}'), ('\u{124a}', '\u{124d}'), + ('\u{1250}', '\u{1256}'), ('\u{1258}', '\u{1258}'), ('\u{125a}', '\u{125d}'), ('\u{1260}', + '\u{1288}'), ('\u{128a}', '\u{128d}'), ('\u{1290}', '\u{12b0}'), ('\u{12b2}', '\u{12b5}'), + ('\u{12b8}', '\u{12be}'), ('\u{12c0}', '\u{12c0}'), ('\u{12c2}', '\u{12c5}'), ('\u{12c8}', + '\u{12d6}'), ('\u{12d8}', '\u{1310}'), ('\u{1312}', '\u{1315}'), ('\u{1318}', '\u{135a}'), + ('\u{1380}', '\u{138f}'), ('\u{13a0}', '\u{13f5}'), ('\u{13f8}', '\u{13fd}'), ('\u{1401}', + '\u{166c}'), ('\u{166f}', '\u{167f}'), ('\u{1681}', '\u{169a}'), ('\u{16a0}', '\u{16ea}'), + ('\u{16ee}', '\u{16f8}'), ('\u{1700}', '\u{170c}'), ('\u{170e}', '\u{1711}'), ('\u{1720}', + '\u{1731}'), ('\u{1740}', '\u{1751}'), ('\u{1760}', '\u{176c}'), ('\u{176e}', '\u{1770}'), + ('\u{1780}', '\u{17b3}'), ('\u{17d7}', '\u{17d7}'), ('\u{17dc}', '\u{17dc}'), ('\u{1820}', + '\u{1877}'), ('\u{1880}', '\u{18a8}'), ('\u{18aa}', '\u{18aa}'), ('\u{18b0}', '\u{18f5}'), + ('\u{1900}', '\u{191e}'), ('\u{1950}', '\u{196d}'), ('\u{1970}', '\u{1974}'), ('\u{1980}', + '\u{19ab}'), ('\u{19b0}', '\u{19c9}'), ('\u{1a00}', '\u{1a16}'), ('\u{1a20}', '\u{1a54}'), + ('\u{1aa7}', '\u{1aa7}'), ('\u{1b05}', '\u{1b33}'), ('\u{1b45}', '\u{1b4b}'), ('\u{1b83}', + '\u{1ba0}'), ('\u{1bae}', '\u{1baf}'), ('\u{1bba}', '\u{1be5}'), ('\u{1c00}', '\u{1c23}'), + ('\u{1c4d}', '\u{1c4f}'), ('\u{1c5a}', '\u{1c7d}'), ('\u{1c80}', '\u{1c88}'), ('\u{1ce9}', + '\u{1cec}'), ('\u{1cee}', '\u{1cf1}'), ('\u{1cf5}', '\u{1cf6}'), ('\u{1d00}', '\u{1dbf}'), + ('\u{1e00}', '\u{1f15}'), ('\u{1f18}', '\u{1f1d}'), ('\u{1f20}', '\u{1f45}'), ('\u{1f48}', + '\u{1f4d}'), ('\u{1f50}', '\u{1f57}'), ('\u{1f59}', '\u{1f59}'), ('\u{1f5b}', '\u{1f5b}'), + ('\u{1f5d}', '\u{1f5d}'), ('\u{1f5f}', '\u{1f7d}'), ('\u{1f80}', '\u{1fb4}'), ('\u{1fb6}', + '\u{1fbc}'), ('\u{1fbe}', '\u{1fbe}'), ('\u{1fc2}', '\u{1fc4}'), ('\u{1fc6}', '\u{1fcc}'), + ('\u{1fd0}', '\u{1fd3}'), ('\u{1fd6}', '\u{1fdb}'), ('\u{1fe0}', '\u{1fec}'), ('\u{1ff2}', + '\u{1ff4}'), ('\u{1ff6}', '\u{1ffc}'), ('\u{2071}', '\u{2071}'), ('\u{207f}', '\u{207f}'), + ('\u{2090}', '\u{209c}'), ('\u{2102}', '\u{2102}'), ('\u{2107}', '\u{2107}'), ('\u{210a}', + '\u{2113}'), ('\u{2115}', '\u{2115}'), ('\u{2118}', '\u{211d}'), ('\u{2124}', '\u{2124}'), + ('\u{2126}', '\u{2126}'), ('\u{2128}', '\u{2128}'), ('\u{212a}', '\u{2139}'), ('\u{213c}', + '\u{213f}'), ('\u{2145}', '\u{2149}'), ('\u{214e}', '\u{214e}'), ('\u{2160}', '\u{2188}'), + ('\u{2c00}', '\u{2c2e}'), ('\u{2c30}', '\u{2c5e}'), ('\u{2c60}', '\u{2ce4}'), ('\u{2ceb}', + '\u{2cee}'), ('\u{2cf2}', '\u{2cf3}'), ('\u{2d00}', '\u{2d25}'), ('\u{2d27}', '\u{2d27}'), + ('\u{2d2d}', '\u{2d2d}'), ('\u{2d30}', '\u{2d67}'), ('\u{2d6f}', '\u{2d6f}'), ('\u{2d80}', + '\u{2d96}'), ('\u{2da0}', '\u{2da6}'), ('\u{2da8}', '\u{2dae}'), ('\u{2db0}', '\u{2db6}'), + ('\u{2db8}', '\u{2dbe}'), ('\u{2dc0}', '\u{2dc6}'), ('\u{2dc8}', '\u{2dce}'), ('\u{2dd0}', + '\u{2dd6}'), ('\u{2dd8}', '\u{2dde}'), ('\u{3005}', '\u{3007}'), ('\u{3021}', '\u{3029}'), + ('\u{3031}', '\u{3035}'), ('\u{3038}', '\u{303c}'), ('\u{3041}', '\u{3096}'), ('\u{309d}', + '\u{309f}'), ('\u{30a1}', '\u{30fa}'), ('\u{30fc}', '\u{30ff}'), ('\u{3105}', '\u{312d}'), + ('\u{3131}', '\u{318e}'), ('\u{31a0}', '\u{31ba}'), ('\u{31f0}', '\u{31ff}'), ('\u{3400}', + '\u{4db5}'), ('\u{4e00}', '\u{9fd5}'), ('\u{a000}', '\u{a48c}'), ('\u{a4d0}', '\u{a4fd}'), + ('\u{a500}', '\u{a60c}'), ('\u{a610}', '\u{a61f}'), ('\u{a62a}', '\u{a62b}'), ('\u{a640}', + '\u{a66e}'), ('\u{a67f}', '\u{a69d}'), ('\u{a6a0}', '\u{a6ef}'), ('\u{a717}', '\u{a71f}'), + ('\u{a722}', '\u{a788}'), ('\u{a78b}', '\u{a7ae}'), ('\u{a7b0}', '\u{a7b7}'), ('\u{a7f7}', + '\u{a801}'), ('\u{a803}', '\u{a805}'), ('\u{a807}', '\u{a80a}'), ('\u{a80c}', '\u{a822}'), + ('\u{a840}', '\u{a873}'), ('\u{a882}', '\u{a8b3}'), ('\u{a8f2}', '\u{a8f7}'), ('\u{a8fb}', + '\u{a8fb}'), ('\u{a8fd}', '\u{a8fd}'), ('\u{a90a}', '\u{a925}'), ('\u{a930}', '\u{a946}'), + ('\u{a960}', '\u{a97c}'), ('\u{a984}', '\u{a9b2}'), ('\u{a9cf}', '\u{a9cf}'), ('\u{a9e0}', + '\u{a9e4}'), ('\u{a9e6}', '\u{a9ef}'), ('\u{a9fa}', '\u{a9fe}'), ('\u{aa00}', '\u{aa28}'), + ('\u{aa40}', '\u{aa42}'), ('\u{aa44}', '\u{aa4b}'), ('\u{aa60}', '\u{aa76}'), ('\u{aa7a}', + '\u{aa7a}'), ('\u{aa7e}', '\u{aaaf}'), ('\u{aab1}', '\u{aab1}'), ('\u{aab5}', '\u{aab6}'), + ('\u{aab9}', '\u{aabd}'), ('\u{aac0}', '\u{aac0}'), ('\u{aac2}', '\u{aac2}'), ('\u{aadb}', + '\u{aadd}'), ('\u{aae0}', '\u{aaea}'), ('\u{aaf2}', '\u{aaf4}'), ('\u{ab01}', '\u{ab06}'), + ('\u{ab09}', '\u{ab0e}'), ('\u{ab11}', '\u{ab16}'), ('\u{ab20}', '\u{ab26}'), ('\u{ab28}', + '\u{ab2e}'), ('\u{ab30}', '\u{ab5a}'), ('\u{ab5c}', '\u{ab65}'), ('\u{ab70}', '\u{abe2}'), + ('\u{ac00}', '\u{d7a3}'), ('\u{d7b0}', '\u{d7c6}'), ('\u{d7cb}', '\u{d7fb}'), ('\u{f900}', + '\u{fa6d}'), ('\u{fa70}', '\u{fad9}'), ('\u{fb00}', '\u{fb06}'), ('\u{fb13}', '\u{fb17}'), + ('\u{fb1d}', '\u{fb1d}'), ('\u{fb1f}', '\u{fb28}'), ('\u{fb2a}', '\u{fb36}'), ('\u{fb38}', + '\u{fb3c}'), ('\u{fb3e}', '\u{fb3e}'), ('\u{fb40}', '\u{fb41}'), ('\u{fb43}', '\u{fb44}'), + ('\u{fb46}', '\u{fbb1}'), ('\u{fbd3}', '\u{fc5d}'), ('\u{fc64}', '\u{fd3d}'), ('\u{fd50}', + '\u{fd8f}'), ('\u{fd92}', '\u{fdc7}'), ('\u{fdf0}', '\u{fdf9}'), ('\u{fe71}', '\u{fe71}'), + ('\u{fe73}', '\u{fe73}'), ('\u{fe77}', '\u{fe77}'), ('\u{fe79}', '\u{fe79}'), ('\u{fe7b}', + '\u{fe7b}'), ('\u{fe7d}', '\u{fe7d}'), ('\u{fe7f}', '\u{fefc}'), ('\u{ff21}', '\u{ff3a}'), + ('\u{ff41}', '\u{ff5a}'), ('\u{ff66}', '\u{ff9d}'), ('\u{ffa0}', '\u{ffbe}'), ('\u{ffc2}', + '\u{ffc7}'), ('\u{ffca}', '\u{ffcf}'), ('\u{ffd2}', '\u{ffd7}'), ('\u{ffda}', '\u{ffdc}'), + ('\u{10000}', '\u{1000b}'), ('\u{1000d}', '\u{10026}'), ('\u{10028}', '\u{1003a}'), + ('\u{1003c}', '\u{1003d}'), ('\u{1003f}', '\u{1004d}'), ('\u{10050}', '\u{1005d}'), + ('\u{10080}', '\u{100fa}'), ('\u{10140}', '\u{10174}'), ('\u{10280}', '\u{1029c}'), + ('\u{102a0}', '\u{102d0}'), ('\u{10300}', '\u{1031f}'), ('\u{10330}', '\u{1034a}'), + ('\u{10350}', '\u{10375}'), ('\u{10380}', '\u{1039d}'), ('\u{103a0}', '\u{103c3}'), + ('\u{103c8}', '\u{103cf}'), ('\u{103d1}', '\u{103d5}'), ('\u{10400}', '\u{1049d}'), + ('\u{104b0}', '\u{104d3}'), ('\u{104d8}', '\u{104fb}'), ('\u{10500}', '\u{10527}'), + ('\u{10530}', '\u{10563}'), ('\u{10600}', '\u{10736}'), ('\u{10740}', '\u{10755}'), + ('\u{10760}', '\u{10767}'), ('\u{10800}', '\u{10805}'), ('\u{10808}', '\u{10808}'), + ('\u{1080a}', '\u{10835}'), ('\u{10837}', '\u{10838}'), ('\u{1083c}', '\u{1083c}'), + ('\u{1083f}', '\u{10855}'), ('\u{10860}', '\u{10876}'), ('\u{10880}', '\u{1089e}'), + ('\u{108e0}', '\u{108f2}'), ('\u{108f4}', '\u{108f5}'), ('\u{10900}', '\u{10915}'), + ('\u{10920}', '\u{10939}'), ('\u{10980}', '\u{109b7}'), ('\u{109be}', '\u{109bf}'), + ('\u{10a00}', '\u{10a00}'), ('\u{10a10}', '\u{10a13}'), ('\u{10a15}', '\u{10a17}'), + ('\u{10a19}', '\u{10a33}'), ('\u{10a60}', '\u{10a7c}'), ('\u{10a80}', '\u{10a9c}'), + ('\u{10ac0}', '\u{10ac7}'), ('\u{10ac9}', '\u{10ae4}'), ('\u{10b00}', '\u{10b35}'), + ('\u{10b40}', '\u{10b55}'), ('\u{10b60}', '\u{10b72}'), ('\u{10b80}', '\u{10b91}'), + ('\u{10c00}', '\u{10c48}'), ('\u{10c80}', '\u{10cb2}'), ('\u{10cc0}', '\u{10cf2}'), + ('\u{11003}', '\u{11037}'), ('\u{11083}', '\u{110af}'), ('\u{110d0}', '\u{110e8}'), + ('\u{11103}', '\u{11126}'), ('\u{11150}', '\u{11172}'), ('\u{11176}', '\u{11176}'), + ('\u{11183}', '\u{111b2}'), ('\u{111c1}', '\u{111c4}'), ('\u{111da}', '\u{111da}'), + ('\u{111dc}', '\u{111dc}'), ('\u{11200}', '\u{11211}'), ('\u{11213}', '\u{1122b}'), + ('\u{11280}', '\u{11286}'), ('\u{11288}', '\u{11288}'), ('\u{1128a}', '\u{1128d}'), + ('\u{1128f}', '\u{1129d}'), ('\u{1129f}', '\u{112a8}'), ('\u{112b0}', '\u{112de}'), + ('\u{11305}', '\u{1130c}'), ('\u{1130f}', '\u{11310}'), ('\u{11313}', '\u{11328}'), + ('\u{1132a}', '\u{11330}'), ('\u{11332}', '\u{11333}'), ('\u{11335}', '\u{11339}'), + ('\u{1133d}', '\u{1133d}'), ('\u{11350}', '\u{11350}'), ('\u{1135d}', '\u{11361}'), + ('\u{11400}', '\u{11434}'), ('\u{11447}', '\u{1144a}'), ('\u{11480}', '\u{114af}'), + ('\u{114c4}', '\u{114c5}'), ('\u{114c7}', '\u{114c7}'), ('\u{11580}', '\u{115ae}'), + ('\u{115d8}', '\u{115db}'), ('\u{11600}', '\u{1162f}'), ('\u{11644}', '\u{11644}'), + ('\u{11680}', '\u{116aa}'), ('\u{11700}', '\u{11719}'), ('\u{118a0}', '\u{118df}'), + ('\u{118ff}', '\u{118ff}'), ('\u{11ac0}', '\u{11af8}'), ('\u{11c00}', '\u{11c08}'), + ('\u{11c0a}', '\u{11c2e}'), ('\u{11c40}', '\u{11c40}'), ('\u{11c72}', '\u{11c8f}'), + ('\u{12000}', '\u{12399}'), ('\u{12400}', '\u{1246e}'), ('\u{12480}', '\u{12543}'), + ('\u{13000}', '\u{1342e}'), ('\u{14400}', '\u{14646}'), ('\u{16800}', '\u{16a38}'), + ('\u{16a40}', '\u{16a5e}'), ('\u{16ad0}', '\u{16aed}'), ('\u{16b00}', '\u{16b2f}'), + ('\u{16b40}', '\u{16b43}'), ('\u{16b63}', '\u{16b77}'), ('\u{16b7d}', '\u{16b8f}'), + ('\u{16f00}', '\u{16f44}'), ('\u{16f50}', '\u{16f50}'), ('\u{16f93}', '\u{16f9f}'), + ('\u{16fe0}', '\u{16fe0}'), ('\u{17000}', '\u{187ec}'), ('\u{18800}', '\u{18af2}'), + ('\u{1b000}', '\u{1b001}'), ('\u{1bc00}', '\u{1bc6a}'), ('\u{1bc70}', '\u{1bc7c}'), + ('\u{1bc80}', '\u{1bc88}'), ('\u{1bc90}', '\u{1bc99}'), ('\u{1d400}', '\u{1d454}'), + ('\u{1d456}', '\u{1d49c}'), ('\u{1d49e}', '\u{1d49f}'), ('\u{1d4a2}', '\u{1d4a2}'), + ('\u{1d4a5}', '\u{1d4a6}'), ('\u{1d4a9}', '\u{1d4ac}'), ('\u{1d4ae}', '\u{1d4b9}'), + ('\u{1d4bb}', '\u{1d4bb}'), ('\u{1d4bd}', '\u{1d4c3}'), ('\u{1d4c5}', '\u{1d505}'), + ('\u{1d507}', '\u{1d50a}'), ('\u{1d50d}', '\u{1d514}'), ('\u{1d516}', '\u{1d51c}'), + ('\u{1d51e}', '\u{1d539}'), ('\u{1d53b}', '\u{1d53e}'), ('\u{1d540}', '\u{1d544}'), + ('\u{1d546}', '\u{1d546}'), ('\u{1d54a}', '\u{1d550}'), ('\u{1d552}', '\u{1d6a5}'), + ('\u{1d6a8}', '\u{1d6c0}'), ('\u{1d6c2}', '\u{1d6da}'), ('\u{1d6dc}', '\u{1d6fa}'), + ('\u{1d6fc}', '\u{1d714}'), ('\u{1d716}', '\u{1d734}'), ('\u{1d736}', '\u{1d74e}'), + ('\u{1d750}', '\u{1d76e}'), ('\u{1d770}', '\u{1d788}'), ('\u{1d78a}', '\u{1d7a8}'), + ('\u{1d7aa}', '\u{1d7c2}'), ('\u{1d7c4}', '\u{1d7cb}'), ('\u{1e800}', '\u{1e8c4}'), + ('\u{1e900}', '\u{1e943}'), ('\u{1ee00}', '\u{1ee03}'), ('\u{1ee05}', '\u{1ee1f}'), + ('\u{1ee21}', '\u{1ee22}'), ('\u{1ee24}', '\u{1ee24}'), ('\u{1ee27}', '\u{1ee27}'), + ('\u{1ee29}', '\u{1ee32}'), ('\u{1ee34}', '\u{1ee37}'), ('\u{1ee39}', '\u{1ee39}'), + ('\u{1ee3b}', '\u{1ee3b}'), ('\u{1ee42}', '\u{1ee42}'), ('\u{1ee47}', '\u{1ee47}'), + ('\u{1ee49}', '\u{1ee49}'), ('\u{1ee4b}', '\u{1ee4b}'), ('\u{1ee4d}', '\u{1ee4f}'), + ('\u{1ee51}', '\u{1ee52}'), ('\u{1ee54}', '\u{1ee54}'), ('\u{1ee57}', '\u{1ee57}'), + ('\u{1ee59}', '\u{1ee59}'), ('\u{1ee5b}', '\u{1ee5b}'), ('\u{1ee5d}', '\u{1ee5d}'), + ('\u{1ee5f}', '\u{1ee5f}'), ('\u{1ee61}', '\u{1ee62}'), ('\u{1ee64}', '\u{1ee64}'), + ('\u{1ee67}', '\u{1ee6a}'), ('\u{1ee6c}', '\u{1ee72}'), ('\u{1ee74}', '\u{1ee77}'), + ('\u{1ee79}', '\u{1ee7c}'), ('\u{1ee7e}', '\u{1ee7e}'), ('\u{1ee80}', '\u{1ee89}'), + ('\u{1ee8b}', '\u{1ee9b}'), ('\u{1eea1}', '\u{1eea3}'), ('\u{1eea5}', '\u{1eea9}'), + ('\u{1eeab}', '\u{1eebb}'), ('\u{20000}', '\u{2a6d6}'), ('\u{2a700}', '\u{2b734}'), + ('\u{2b740}', '\u{2b81d}'), ('\u{2b820}', '\u{2cea1}'), ('\u{2f800}', '\u{2fa1d}') + ]; + + pub fn XID_Start(c: char) -> bool { + super::bsearch_range_table(c, XID_Start_table) + } + +} + diff -Nru cargo-0.25.0/vendor/unicode-xid-0.1.0/src/tests.rs cargo-0.26.0/vendor/unicode-xid-0.1.0/src/tests.rs --- cargo-0.25.0/vendor/unicode-xid-0.1.0/src/tests.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/unicode-xid-0.1.0/src/tests.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,113 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[cfg(feature = "bench")] +use std::iter; +#[cfg(feature = "bench")] +use test::Bencher; +#[cfg(feature = "bench")] +use std::prelude::v1::*; + +use super::UnicodeXID; + +#[cfg(feature = "bench")] +#[bench] +fn cargo_is_xid_start(b: &mut Bencher) { + let string = iter::repeat('a').take(4096).collect::<String>(); + + b.bytes = string.len() as u64; + b.iter(|| { + string.chars().all(UnicodeXID::is_xid_start) + }); +} + +#[cfg(feature = "bench")] +#[bench] +fn stdlib_is_xid_start(b: &mut Bencher) { + let string = iter::repeat('a').take(4096).collect::<String>(); + + b.bytes = string.len() as u64; + b.iter(|| { + string.chars().all(char::is_xid_start) + }); +} + +#[cfg(feature = "bench")] +#[bench] +fn cargo_xid_continue(b: &mut Bencher) { + let string = iter::repeat('a').take(4096).collect::<String>(); + + b.bytes = string.len() as u64; + b.iter(|| { + string.chars().all(UnicodeXID::is_xid_continue) + }); +} + +#[cfg(feature = "bench")] +#[bench] +fn stdlib_xid_continue(b: &mut Bencher) { + let string = iter::repeat('a').take(4096).collect::<String>(); + + b.bytes = string.len() as u64; + b.iter(|| { + string.chars().all(char::is_xid_continue) + }); +} + +#[test] +fn test_is_xid_start() { + let chars = [ + 'A', 'Z', 'a', 'z', + '\u{1000d}', '\u{10026}', + ]; + + for ch in &chars { + assert!(UnicodeXID::is_xid_start(*ch), "{}", ch); + } +} + +#[test] +fn test_is_not_xid_start() { + let chars = [ + '\x00', '\x01', + '0', '9', + ' ', '[', '<', '{', '(', + '\u{02c2}', '\u{ffff}', + ]; + + for ch in &chars { + assert!(!UnicodeXID::is_xid_start(*ch), "{}", ch); + } +} + +#[test] +fn test_is_xid_continue() { + let chars = [ + '0', '9', 'A', 'Z', 'a', 'z', '_', + '\u{1000d}', '\u{10026}', + ]; + + for ch in &chars { + assert!(UnicodeXID::is_xid_continue(*ch), "{}", ch); + } +} + +#[test] +fn test_is_not_xid_continue() { + let chars = [ + '\x00', '\x01', + ' ', '[', '<', '{', '(', + '\u{02c2}', '\u{ffff}', + ]; + + for &ch in &chars { + assert!(!UnicodeXID::is_xid_continue(ch), "{}", ch); + } +} diff -Nru cargo-0.25.0/vendor/unicode-xid-0.1.0/.travis.yml cargo-0.26.0/vendor/unicode-xid-0.1.0/.travis.yml --- cargo-0.25.0/vendor/unicode-xid-0.1.0/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/unicode-xid-0.1.0/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +language: rust +rust: 'nightly' +sudo: false +script: + - cargo build --verbose --features bench + - cargo test --verbose --features bench + - cargo bench --verbose --features bench + - cargo clean + - cargo build --verbose + - cargo test --verbose + - rustdoc --test README.md -L target/debug -L target/debug/deps + - cargo doc +after_success: | + [ $TRAVIS_BRANCH = master ] && + [ $TRAVIS_PULL_REQUEST = false ] && + echo '<meta http-equiv=refresh content=0;url=unicode_xid/index.html>' > target/doc/index.html && + pip install ghp-import --user $USER && + $HOME/.local/bin/ghp-import -n target/doc && + git push -qf https://${TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git gh-pages +env: + global: + secure: gTlge+/OQlVkV0R+RThWXeN0aknmS7iUTPBMYKJyRdLz7T2vubw3w80a2CVE87JlpV87A5cVGD+LgR+AhYrhKtvqHb1brMDd99gylBBi2DfV7YapDSwSCuFgVR+FjZfJRcXBtI8po5urUZ84V0WLzRX8SyWqWgoD3oCkSL3Wp3w= +notifications: + email: + on_success: never diff -Nru cargo-0.25.0/vendor/vcpkg-0.2.2/.cargo-checksum.json cargo-0.26.0/vendor/vcpkg-0.2.2/.cargo-checksum.json --- cargo-0.25.0/vendor/vcpkg-0.2.2/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/vcpkg-0.2.2/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"9e0a7d8bed3178a8fb112199d466eeca9ed09a14ba8ad67718179b4fd5487d0b"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/vcpkg-0.2.2/Cargo.toml cargo-0.26.0/vendor/vcpkg-0.2.2/Cargo.toml --- cargo-0.25.0/vendor/vcpkg-0.2.2/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/vcpkg-0.2.2/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,28 +0,0 @@ -# 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 believe there's an error in this file please file an -# issue against the rust-lang/cargo repository. If you're -# editing this file be aware that the upstream Cargo.toml -# will likely look very different (and much more reasonable) - -[package] -name = "vcpkg" -version = "0.2.2" -authors = ["Jim McGrath <jimmc2@gmail.com>"] -description = "A library to find native dependencies in a vcpkg tree at build\ntime in order to be used in Cargo build scripts.\n" -documentation = "https://docs.rs/vcpkg" -keywords = ["build-dependencies"] -license = "MIT/Apache-2.0" -repository = "https://github.com/mcgoo/vcpkg-rs" - -[dependencies] -[badges.travis-ci] -repository = "mcgoo/vcpkg-rs" - -[badges.appveyor] -repository = "mcgoo/vcpkg-rs" diff -Nru cargo-0.25.0/vendor/vcpkg-0.2.2/src/lib.rs cargo-0.26.0/vendor/vcpkg-0.2.2/src/lib.rs --- cargo-0.25.0/vendor/vcpkg-0.2.2/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/vcpkg-0.2.2/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,532 +0,0 @@ -//! A build dependency for Cargo libraries to find libraries in a -//! [Vcpkg](https://github.com/Microsoft/vcpkg) tree. -//! -//! Note: You must set one of `RUSTFLAGS=-Ctarget-feature=+crt-static` or -//! `VCPKGRS_DYNAMIC=1` in your environment or the vcpkg-rs helper -//! will not find any libraries. If `VCPKGRS_DYNAMIC` is set, `cargo install` will -//! generate dynamically linked binaries, in which case you will have to arrange for -//! dlls from your Vcpkg installation to be available in your path. -//! -//! The simplest possible usage for a library whose Vcpkg port name matches the -//! name of the lib and DLL that are being looked for looks like this :- -//! -//! ```rust,no_run -//! vcpkg::probe_package("libssh2").unwrap(); -//! ``` -//! -//! In practice the .lib and .dll often differ in name from the package itself, -//! in which case the library names must be specified, like this :- -//! -//! ```rust,no_run -//! vcpkg::Config::new() -//! .lib_names("zlib","zlib1") -//! .probe("zlib").unwrap(); -//! ``` -//! -//! If the search was successful all appropriate Cargo metadata will be printed -//! on stdout. -//! -//! The decision to choose static variants of libraries is driven by adding -//! `RUSTFLAGS=-Ctarget-feature=+crt-static` to the environment. This requires -//! a nightly compiler but is scheduled to be stable in rustc 1.19. -//! -//! A number of environment variables are available to globally configure which -//! libraries are selected. -//! -//! * `VCPKG_ROOT` - Set the directory to look in for a vcpkg installation. If -//! it is not set, vcpkg will use the user-wide installation if one has been -//! set up with `vcpkg integrate install` -//! -//! * `VCPKGRS_NO_FOO` - if set, vcpkg-rs will not attempt to find the -//! library named `foo`. -//! -//! * `VCPKGRS_DISABLE` - if set, vcpkg-rs will not attempt to find any libraries. -//! -//! * `VCPKGRS_DYNAMIC` - if set, vcpkg-rs will link to DLL builds of ports. -//! -//! There is a companion crate `vcpkg_cli` that allows testing of environment -//! and flag combinations. -//! -//! ```Batchfile -//! C:\src> vcpkg_cli probe -l static mysqlclient -//! Found library mysqlclient -//! Include paths: -//! C:\src\diesel_build\vcpkg-dll\installed\x64-windows-static\include -//! Library paths: -//! C:\src\diesel_build\vcpkg-dll\installed\x64-windows-static\lib -//! Cargo metadata: -//! cargo:rustc-link-search=native=C:\src\diesel_build\vcpkg-dll\installed\x64-windows-static\lib -//! cargo:rustc-link-lib=static=mysqlclient -//! ``` - -use std::ascii::AsciiExt; -use std::env; -use std::error; -use std::fs::{self, File}; -use std::fmt; -use std::io::{BufRead, BufReader}; -use std::path::{PathBuf, Path}; - -// #[derive(Clone)] -pub struct Config { - /// should the cargo metadata actually be emitted - cargo_metadata: bool, - - /// should cargo:include= metadata be emitted (defaults to false) - emit_includes: bool, - - /// libs that must be be found for probing to be considered successful - required_libs: Vec<LibNames>, - - /// should DLLs be copies to OUT_DIR? - copy_dlls: bool, -} - -#[derive(Debug)] -pub struct Library { - /// Paths for the linker to search for static or import libraries - pub link_paths: Vec<PathBuf>, - - /// Paths to search at runtme to find DLLs - pub dll_paths: Vec<PathBuf>, - - /// Paths to search for - pub include_paths: Vec<PathBuf>, - - /// cargo: metadata lines - pub cargo_metadata: Vec<String>, - - /// libraries found are static - pub is_static: bool, - - // DLLs found - pub found_dlls: Vec<PathBuf>, - - // static libs or import libs found - pub found_libs: Vec<PathBuf>, -} - -enum MSVCTarget { - X86, - X64, -} - -impl fmt::Display for MSVCTarget { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - MSVCTarget::X86 => write!(f, "x86-windows"), - MSVCTarget::X64 => write!(f, "x64-windows"), - } - } -} - -#[derive(Debug)] // need Display? -pub enum Error { - /// Aborted because of a `VCPKGRS_NO_*` environment variable. - /// - /// Contains the name of the responsible environment variable. - DisabledByEnv(String), - - /// Aborted because a required environment variable was not set. - RequiredEnvMissing(String), - - /// Only MSVC ABI is supported - NotMSVC, - - /// Can't find a vcpkg tree - VcpkgNotFound(String), - - /// Library not found in vcpkg tree - LibNotFound(String), - - #[doc(hidden)] - __Nonexhaustive, -} - -impl error::Error for Error { - fn description(&self) -> &str { - match *self { - Error::DisabledByEnv(_) => "vcpkg-rs requested to be aborted", - Error::RequiredEnvMissing(_) => "a required env setting is missing", - Error::NotMSVC => "vcpkg-rs only can only find libraries for MSVC ABI 64 bit builds", - Error::VcpkgNotFound(_) => "could not find Vcpkg tree", - Error::LibNotFound(_) => "could not find library in Vcpkg tree", - // Error::LibNotFound(_) => "could not find library in vcpkg tree", - Error::__Nonexhaustive => panic!(), - } - } - - fn cause(&self) -> Option<&error::Error> { - match *self { - // Error::Command { ref cause, .. } => Some(cause), - _ => None, - } - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { - match *self { - Error::DisabledByEnv(ref name) => write!(f, "Aborted because {} is set", name), - Error::RequiredEnvMissing(ref name) => write!(f, "Aborted because {} is not set", name), - Error::NotMSVC => { - write!(f, - "the vcpkg-rs Vcpkg build helper can only find libraries built for the MSVC ABI.") - } - Error::VcpkgNotFound(ref detail) => write!(f, "Could not find Vcpkg tree: {}", detail), - Error::LibNotFound(ref detail) => { - write!(f, "Could not find library in Vcpkg tree {}", detail) - } - Error::__Nonexhaustive => panic!(), - } - } -} - -pub fn probe_package(name: &str) -> Result<Library, Error> { - Config::new().probe(name) -} - -fn find_vcpkg_root() -> Result<PathBuf, Error> { - - // prefer the setting from the environment is there is one - if let Some(path) = env::var_os("VCPKG_ROOT") { - return Ok(PathBuf::from(path)); - } - - // see if there is a per-user vcpkg tree that has been integrated into msbuild - // using `vcpkg integrate install` - let local_app_data = try!(env::var("LOCALAPPDATA").map_err(|_| { - Error::VcpkgNotFound("Failed to read LOCALAPPDATA environment variable".to_string()) - })); // not present or can't utf8 - let vcpkg_user_targets_path = Path::new(local_app_data.as_str()) - .join("vcpkg") - .join("vcpkg.user.targets"); - - let file = try!(File::open(vcpkg_user_targets_path.clone()).map_err(|_| { - Error::VcpkgNotFound("No vcpkg.user.targets found. Set the VCPKG_ROOT environment \ - variable or run 'vcpkg integrate install'".to_string()) - })); - let file = BufReader::new(&file); - - for line in file.lines() { - let line = try!(line.map_err(|_| { - Error::VcpkgNotFound(format!("Parsing of {} failed.", - vcpkg_user_targets_path - .to_string_lossy() - .to_owned())) - })); - let mut split = line.split("Project=\""); - split.next(); // eat anything before Project=" - if let Some(found) = split.next() { - // " is illegal in a Windows pathname - if let Some(found) = found.split_terminator("\"").next() { - let mut vcpkg_root = PathBuf::from(found); - if !(vcpkg_root.pop() && vcpkg_root.pop() && vcpkg_root.pop() && vcpkg_root.pop()) { - return Err(Error::VcpkgNotFound(format!("Could not find vcpkg root above {}", - found))); - } - return Ok(vcpkg_root); - } - } - } - - Err(Error::VcpkgNotFound(format!("Project location not found parsing {}.", - vcpkg_user_targets_path.to_string_lossy().to_owned()))) -} - -fn validate_vcpkg_root(path: &PathBuf) -> Result<(), Error> { - - let mut vcpkg_root_path = path.clone(); - vcpkg_root_path.push(".vcpkg-root"); - - if vcpkg_root_path.exists() { - Ok(()) - } else { - Err(Error::VcpkgNotFound(format!("Could not find Vcpkg root at {}", - vcpkg_root_path.to_string_lossy()))) - } -} - -/// names of the libraries -struct LibNames { - lib_stem: String, - dll_stem: String, -} - -fn find_vcpkg_target(msvc_target: &MSVCTarget) -> Result<VcpkgTarget, Error> { - - let vcpkg_root = try!(find_vcpkg_root()); - try!(validate_vcpkg_root(&vcpkg_root)); - - let static_lib = env::var("CARGO_CFG_TARGET_FEATURE") - .unwrap_or(String::new()) - .contains("crt-static"); - - let mut base = vcpkg_root; - base.push("installed"); - let static_appendage = if static_lib { "-static" } else { "" }; - - let vcpkg_triple = format!("{}{}", msvc_target.to_string(), static_appendage); - base.push(vcpkg_triple); - - let lib_path = base.join("lib"); - let bin_path = base.join("bin"); - let include_path = base.join("include"); - - Ok(VcpkgTarget { - // vcpkg_triple: vcpkg_triple, - lib_path: lib_path, - bin_path: bin_path, - include_path: include_path, - is_static: static_lib, - }) -} - -/// paths and triple for the chosen target -struct VcpkgTarget { - // vcpkg_triple: String, - lib_path: PathBuf, - bin_path: PathBuf, - include_path: PathBuf, - is_static: bool, -} - -impl Config { - pub fn new() -> Config { - Config { - cargo_metadata: true, - emit_includes: false, - required_libs: Vec::new(), - copy_dlls: true, - } - } - - /// Override the name of the library to look for if it differs from the package name. - /// - /// This may be called more than once if multiple libs are required. - /// All libs must be found for the probe to succeed. `.probe()` must - /// be run with a different configuration to look for libraries under one of several names. - /// `.libname("ssleay32")` will look for ssleay32.lib and also ssleay32.dll if - /// dynamic linking is selected. - pub fn lib_name(&mut self, lib_stem: &str) -> &mut Config { - self.required_libs - .push(LibNames { - lib_stem: lib_stem.to_owned(), - dll_stem: lib_stem.to_owned(), - }); - self - } - - /// Override the name of the library to look for if it differs from the package name. - /// - /// This may be called more than once if multiple libs are required. - /// All libs must be found for the probe to succeed. `.probe()` must - /// be run with a different configuration to look for libraries under one of several names. - /// `.lib_names("libcurl_imp","curl")` will look for libcurl_imp.lib and also curl.dll if - /// dynamic linking is selected. - pub fn lib_names(&mut self, lib_stem: &str, dll_stem: &str) -> &mut Config { - self.required_libs - .push(LibNames { - lib_stem: lib_stem.to_owned(), - dll_stem: dll_stem.to_owned(), - }); - self - } - - /// Define whether metadata should be emitted for cargo allowing it to - /// automatically link the binary. Defaults to `true`. - pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config { - self.cargo_metadata = cargo_metadata; - self - } - - /// Define cargo:include= metadata should be emitted. Defaults to `false`. - pub fn emit_includes(&mut self, emit_includes: bool) -> &mut Config { - self.emit_includes = emit_includes; - self - } - - /// Should DLLs be copied to OUT_DIR? - /// Defaults to `true`. - pub fn copy_dlls(&mut self, copy_dlls: bool) -> &mut Config { - self.copy_dlls = copy_dlls; - self - } - - /// Find the library `port_name` in a Vcpkg tree. - /// - /// This will use all configuration previously set to select the - /// architecture and linkage. - pub fn probe(&mut self, port_name: &str) -> Result<Library, Error> { - - // determine the target type, bailing out if it is not some - // kind of msvc - let msvc_target = try!(msvc_target()); - - // bail out if requested to not try at all - if env::var_os("VCPKGRS_DISABLE").is_some() { - return Err(Error::DisabledByEnv("VCPKGRS_DISABLE".to_owned())); - } - - // bail out if requested to not try at all (old) - if env::var_os("NO_VCPKG").is_some() { - return Err(Error::DisabledByEnv("NO_VCPKG".to_owned())); - } - - // bail out if requested to skip this package - let abort_var_name = format!("VCPKGRS_NO_{}", envify(port_name)); - if env::var_os(&abort_var_name).is_some() { - return Err(Error::DisabledByEnv(abort_var_name)); - } - - // bail out if requested to skip this package (old) - let abort_var_name = format!("{}_NO_VCPKG", envify(port_name)); - if env::var_os(&abort_var_name).is_some() { - return Err(Error::DisabledByEnv(abort_var_name)); - } - - // if no overrides have been selected, then the Vcpkg port name - // is the the .lib name and the .dll name - if self.required_libs.is_empty() { - self.required_libs - .push(LibNames { - lib_stem: port_name.to_owned(), - dll_stem: port_name.to_owned(), - }); - } - - let vcpkg_target = try!(find_vcpkg_target(&msvc_target)); - - // require explicit opt-in before using dynamically linked - // variants, otherwise cargo install of various things will - // stop working if Vcpkg is installed. - if !vcpkg_target.is_static && !env::var_os("VCPKGRS_DYNAMIC").is_some() { - return Err(Error::RequiredEnvMissing("VCPKGRS_DYNAMIC".to_owned())); - } - - let mut lib = Library::new(vcpkg_target.is_static); - - if self.emit_includes { - lib.cargo_metadata - .push(format!("cargo:include={}", vcpkg_target.include_path.display())); - } - lib.include_paths.push(vcpkg_target.include_path); - - lib.cargo_metadata - .push(format!("cargo:rustc-link-search=native={}", - vcpkg_target - .lib_path - .to_str() - .expect("failed to convert string type"))); - lib.link_paths.push(vcpkg_target.lib_path.clone()); - if !vcpkg_target.is_static { - lib.cargo_metadata - .push(format!("cargo:rustc-link-search=native={}", - vcpkg_target - .bin_path - .to_str() - .expect("failed to convert string type"))); - // this path is dropped by recent version of cargo hence the copies to OUT_DIR below - lib.dll_paths.push(vcpkg_target.bin_path.clone()); - } - drop(port_name); - for required_lib in &self.required_libs { - if vcpkg_target.is_static { - lib.cargo_metadata - .push(format!("cargo:rustc-link-lib=static={}", required_lib.lib_stem)); - } else { - lib.cargo_metadata - .push(format!("cargo:rustc-link-lib={}", required_lib.lib_stem)); - } - - // verify that the library exists - let mut lib_location = vcpkg_target.lib_path.clone(); - lib_location.push(required_lib.lib_stem.clone()); - lib_location.set_extension("lib"); - - if !lib_location.exists() { - return Err(Error::LibNotFound(lib_location.display().to_string())); - } - lib.found_libs.push(lib_location); - - // verify that the DLL exists - if !vcpkg_target.is_static { - let mut lib_location = vcpkg_target.bin_path.clone(); - lib_location.push(required_lib.dll_stem.clone()); - lib_location.set_extension("dll"); - - if !lib_location.exists() { - return Err(Error::LibNotFound(lib_location.display().to_string())); - } - lib.found_dlls.push(lib_location); - } - } - - if self.copy_dlls { - if let Some(target_dir) = env::var_os("OUT_DIR") { - if !lib.found_dlls.is_empty() { - for file in &lib.found_dlls { - let mut dest_path = Path::new(target_dir.as_os_str()).to_path_buf(); - dest_path.push(Path::new(file.file_name().unwrap())); - try!(fs::copy(file, &dest_path).map_err(|_| { - Error::LibNotFound(format!("Can't copy file {} to {}", - file.to_string_lossy(), - dest_path.to_string_lossy())) - })); - println!("vcpkg build helper copied {} to {}", - file.to_string_lossy(), - dest_path.to_string_lossy()); - } - lib.cargo_metadata - .push(format!("cargo:rustc-link-search=native={}", - env::var("OUT_DIR").unwrap())); - // work around https://github.com/rust-lang/cargo/issues/3957 - lib.cargo_metadata - .push(format!("cargo:rustc-link-search={}", env::var("OUT_DIR").unwrap())); - } - } else { - return Err(Error::LibNotFound("Unable to get OUT_DIR".to_owned())); - } - } - - if self.cargo_metadata { - for line in &lib.cargo_metadata { - println!("{}", line); - } - } - Ok(lib) - } -} - -impl Library { - pub fn new(is_static: bool) -> Library { - Library { - link_paths: Vec::new(), - dll_paths: Vec::new(), - include_paths: Vec::new(), - cargo_metadata: Vec::new(), - is_static: is_static, - found_dlls: Vec::new(), - found_libs: Vec::new(), - } - } -} - -fn envify(name: &str) -> String { - name.chars() - .map(|c| c.to_ascii_uppercase()) - .map(|c| if c == '-' { '_' } else { c }) - .collect() -} - -fn msvc_target() -> Result<MSVCTarget, Error> { - let target = env::var("TARGET").unwrap_or(String::new()); - if !target.contains("-pc-windows-msvc") { - Err(Error::NotMSVC) - } else if target.starts_with("x86_64-") { - Ok(MSVCTarget::X64) - } else { - // everything else is x86 - Ok(MSVCTarget::X86) - } -} diff -Nru cargo-0.25.0/vendor/vcpkg-0.2.3/.cargo-checksum.json cargo-0.26.0/vendor/vcpkg-0.2.3/.cargo-checksum.json --- cargo-0.25.0/vendor/vcpkg-0.2.3/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/vcpkg-0.2.3/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"7ed0f6789c8a85ca41bbc1c9d175422116a9869bd1cf31bb08e1493ecce60380"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/vcpkg-0.2.3/Cargo.toml cargo-0.26.0/vendor/vcpkg-0.2.3/Cargo.toml --- cargo-0.25.0/vendor/vcpkg-0.2.3/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/vcpkg-0.2.3/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,33 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "vcpkg" +version = "0.2.3" +authors = ["Jim McGrath <jimmc2@gmail.com>"] +description = "A library to find native dependencies in a vcpkg tree at build\ntime in order to be used in Cargo build scripts.\n" +documentation = "https://docs.rs/vcpkg" +readme = "../README.md" +keywords = ["build-dependencies", "windows", "ffi", "win32"] +categories = ["os::windows-apis"] +license = "MIT/Apache-2.0" +repository = "https://github.com/mcgoo/vcpkg-rs" + +[dependencies] +[badges.appveyor] +branch = "master" +repository = "mcgoo/vcpkg-rs" +service = "github" + +[badges.travis-ci] +branch = "master" +repository = "mcgoo/vcpkg-rs" diff -Nru cargo-0.25.0/vendor/vcpkg-0.2.3/src/lib.rs cargo-0.26.0/vendor/vcpkg-0.2.3/src/lib.rs --- cargo-0.25.0/vendor/vcpkg-0.2.3/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/vcpkg-0.2.3/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,544 @@ +//! A build dependency for Cargo libraries to find libraries in a +//! [Vcpkg](https://github.com/Microsoft/vcpkg) tree. +//! +//! Note: You must set one of `RUSTFLAGS=-Ctarget-feature=+crt-static` or +//! `VCPKGRS_DYNAMIC=1` in your environment or the vcpkg-rs helper +//! will not find any libraries. If `VCPKGRS_DYNAMIC` is set, `cargo install` will +//! generate dynamically linked binaries, in which case you will have to arrange for +//! dlls from your Vcpkg installation to be available in your path. +//! +//! The simplest possible usage for a library whose Vcpkg port name matches the +//! name of the lib and DLL that are being looked for looks like this :- +//! +//! ```rust,no_run +//! vcpkg::probe_package("libssh2").unwrap(); +//! ``` +//! +//! In practice the .lib and .dll often differ in name from the package itself, +//! in which case the library names must be specified, like this :- +//! +//! ```rust,no_run +//! vcpkg::Config::new() +//! .lib_names("zlib","zlib1") +//! .probe("zlib").unwrap(); +//! ``` +//! +//! If the search was successful all appropriate Cargo metadata will be printed +//! on stdout. +//! +//! The decision to choose static variants of libraries is driven by adding +//! `RUSTFLAGS=-Ctarget-feature=+crt-static` to the environment. This requires +//! a nightly compiler but is scheduled to be stable in rustc 1.19. +//! +//! A number of environment variables are available to globally configure which +//! libraries are selected. +//! +//! * `VCPKG_ROOT` - Set the directory to look in for a vcpkg installation. If +//! it is not set, vcpkg will use the user-wide installation if one has been +//! set up with `vcpkg integrate install` +//! +//! * `VCPKGRS_NO_FOO` - if set, vcpkg-rs will not attempt to find the +//! library named `foo`. +//! +//! * `VCPKGRS_DISABLE` - if set, vcpkg-rs will not attempt to find any libraries. +//! +//! * `VCPKGRS_DYNAMIC` - if set, vcpkg-rs will link to DLL builds of ports. +//! +//! There is a companion crate `vcpkg_cli` that allows testing of environment +//! and flag combinations. +//! +//! ```Batchfile +//! C:\src> vcpkg_cli probe -l static mysqlclient +//! Found library mysqlclient +//! Include paths: +//! C:\src\diesel_build\vcpkg-dll\installed\x64-windows-static\include +//! Library paths: +//! C:\src\diesel_build\vcpkg-dll\installed\x64-windows-static\lib +//! Cargo metadata: +//! cargo:rustc-link-search=native=C:\src\diesel_build\vcpkg-dll\installed\x64-windows-static\lib +//! cargo:rustc-link-lib=static=mysqlclient +//! ``` + +#[allow(unused_imports)] +use std::ascii::AsciiExt; +use std::env; +use std::error; +use std::fmt; +use std::fs::{self, File}; +use std::io::{BufRead, BufReader}; +use std::path::{Path, PathBuf}; + +// #[derive(Clone)] +pub struct Config { + /// should the cargo metadata actually be emitted + cargo_metadata: bool, + + /// should cargo:include= metadata be emitted (defaults to false) + emit_includes: bool, + + /// libs that must be be found for probing to be considered successful + required_libs: Vec<LibNames>, + + /// should DLLs be copies to OUT_DIR? + copy_dlls: bool, +} + +#[derive(Debug)] +pub struct Library { + /// Paths for the linker to search for static or import libraries + pub link_paths: Vec<PathBuf>, + + /// Paths to search at runtme to find DLLs + pub dll_paths: Vec<PathBuf>, + + /// Paths to search for + pub include_paths: Vec<PathBuf>, + + /// cargo: metadata lines + pub cargo_metadata: Vec<String>, + + /// libraries found are static + pub is_static: bool, + + // DLLs found + pub found_dlls: Vec<PathBuf>, + + // static libs or import libs found + pub found_libs: Vec<PathBuf>, +} + +enum MSVCTarget { + X86, + X64, +} + +impl fmt::Display for MSVCTarget { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + MSVCTarget::X86 => write!(f, "x86-windows"), + MSVCTarget::X64 => write!(f, "x64-windows"), + } + } +} + +#[derive(Debug)] // need Display? +pub enum Error { + /// Aborted because of a `VCPKGRS_NO_*` environment variable. + /// + /// Contains the name of the responsible environment variable. + DisabledByEnv(String), + + /// Aborted because a required environment variable was not set. + RequiredEnvMissing(String), + + /// Only MSVC ABI is supported + NotMSVC, + + /// Can't find a vcpkg tree + VcpkgNotFound(String), + + /// Library not found in vcpkg tree + LibNotFound(String), + + #[doc(hidden)] __Nonexhaustive, +} + +impl error::Error for Error { + fn description(&self) -> &str { + match *self { + Error::DisabledByEnv(_) => "vcpkg-rs requested to be aborted", + Error::RequiredEnvMissing(_) => "a required env setting is missing", + Error::NotMSVC => "vcpkg-rs only can only find libraries for MSVC ABI 64 bit builds", + Error::VcpkgNotFound(_) => "could not find Vcpkg tree", + Error::LibNotFound(_) => "could not find library in Vcpkg tree", + // Error::LibNotFound(_) => "could not find library in vcpkg tree", + Error::__Nonexhaustive => panic!(), + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + // Error::Command { ref cause, .. } => Some(cause), + _ => None, + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match *self { + Error::DisabledByEnv(ref name) => write!(f, "Aborted because {} is set", name), + Error::RequiredEnvMissing(ref name) => write!(f, "Aborted because {} is not set", name), + Error::NotMSVC => write!( + f, + "the vcpkg-rs Vcpkg build helper can only find libraries built for the MSVC ABI." + ), + Error::VcpkgNotFound(ref detail) => write!(f, "Could not find Vcpkg tree: {}", detail), + Error::LibNotFound(ref detail) => { + write!(f, "Could not find library in Vcpkg tree {}", detail) + } + Error::__Nonexhaustive => panic!(), + } + } +} + +pub fn probe_package(name: &str) -> Result<Library, Error> { + Config::new().probe(name) +} + +fn find_vcpkg_root() -> Result<PathBuf, Error> { + // prefer the setting from the environment is there is one + if let Some(path) = env::var_os("VCPKG_ROOT") { + return Ok(PathBuf::from(path)); + } + + // see if there is a per-user vcpkg tree that has been integrated into msbuild + // using `vcpkg integrate install` + let local_app_data = try!(env::var("LOCALAPPDATA").map_err(|_| { + Error::VcpkgNotFound("Failed to read LOCALAPPDATA environment variable".to_string()) + })); // not present or can't utf8 + let vcpkg_user_targets_path = Path::new(local_app_data.as_str()) + .join("vcpkg") + .join("vcpkg.user.targets"); + + let file = try!(File::open(vcpkg_user_targets_path.clone()).map_err(|_| { + Error::VcpkgNotFound( + "No vcpkg.user.targets found. Set the VCPKG_ROOT environment \ + variable or run 'vcpkg integrate install'" + .to_string(), + ) + })); + let file = BufReader::new(&file); + + for line in file.lines() { + let line = try!(line.map_err(|_| { + Error::VcpkgNotFound(format!( + "Parsing of {} failed.", + vcpkg_user_targets_path.to_string_lossy().to_owned() + )) + })); + let mut split = line.split("Project=\""); + split.next(); // eat anything before Project=" + if let Some(found) = split.next() { + // " is illegal in a Windows pathname + if let Some(found) = found.split_terminator('"').next() { + let mut vcpkg_root = PathBuf::from(found); + if !(vcpkg_root.pop() && vcpkg_root.pop() && vcpkg_root.pop() && vcpkg_root.pop()) { + return Err(Error::VcpkgNotFound( + format!("Could not find vcpkg root above {}", found), + )); + } + return Ok(vcpkg_root); + } + } + } + + Err(Error::VcpkgNotFound(format!( + "Project location not found parsing {}.", + vcpkg_user_targets_path.to_string_lossy().to_owned() + ))) +} + +fn validate_vcpkg_root(path: &PathBuf) -> Result<(), Error> { + let mut vcpkg_root_path = path.clone(); + vcpkg_root_path.push(".vcpkg-root"); + + if vcpkg_root_path.exists() { + Ok(()) + } else { + Err(Error::VcpkgNotFound(format!( + "Could not find Vcpkg root at {}", + vcpkg_root_path.to_string_lossy() + ))) + } +} + +/// names of the libraries +struct LibNames { + lib_stem: String, + dll_stem: String, +} + +fn find_vcpkg_target(msvc_target: &MSVCTarget) -> Result<VcpkgTarget, Error> { + let vcpkg_root = try!(find_vcpkg_root()); + try!(validate_vcpkg_root(&vcpkg_root)); + + let static_lib = env::var("CARGO_CFG_TARGET_FEATURE") + .unwrap_or(String::new()) // rustc 1.10 + .contains("crt-static"); + + let mut base = vcpkg_root; + base.push("installed"); + let static_appendage = if static_lib { "-static" } else { "" }; + + let vcpkg_triple = format!("{}{}", msvc_target.to_string(), static_appendage); + base.push(vcpkg_triple); + + let lib_path = base.join("lib"); + let bin_path = base.join("bin"); + let include_path = base.join("include"); + + Ok(VcpkgTarget { + // vcpkg_triple: vcpkg_triple, + lib_path: lib_path, + bin_path: bin_path, + include_path: include_path, + is_static: static_lib, + }) +} + +/// paths and triple for the chosen target +struct VcpkgTarget { + // vcpkg_triple: String, + lib_path: PathBuf, + bin_path: PathBuf, + include_path: PathBuf, + is_static: bool, +} + +impl Config { + pub fn new() -> Config { + Config { + cargo_metadata: true, + emit_includes: false, + required_libs: Vec::new(), + copy_dlls: true, + } + } + + /// Override the name of the library to look for if it differs from the package name. + /// + /// This may be called more than once if multiple libs are required. + /// All libs must be found for the probe to succeed. `.probe()` must + /// be run with a different configuration to look for libraries under one of several names. + /// `.libname("ssleay32")` will look for ssleay32.lib and also ssleay32.dll if + /// dynamic linking is selected. + pub fn lib_name(&mut self, lib_stem: &str) -> &mut Config { + self.required_libs.push(LibNames { + lib_stem: lib_stem.to_owned(), + dll_stem: lib_stem.to_owned(), + }); + self + } + + /// Override the name of the library to look for if it differs from the package name. + /// + /// This may be called more than once if multiple libs are required. + /// All libs must be found for the probe to succeed. `.probe()` must + /// be run with a different configuration to look for libraries under one of several names. + /// `.lib_names("libcurl_imp","curl")` will look for libcurl_imp.lib and also curl.dll if + /// dynamic linking is selected. + pub fn lib_names(&mut self, lib_stem: &str, dll_stem: &str) -> &mut Config { + self.required_libs.push(LibNames { + lib_stem: lib_stem.to_owned(), + dll_stem: dll_stem.to_owned(), + }); + self + } + + /// Define whether metadata should be emitted for cargo allowing it to + /// automatically link the binary. Defaults to `true`. + pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config { + self.cargo_metadata = cargo_metadata; + self + } + + /// Define cargo:include= metadata should be emitted. Defaults to `false`. + pub fn emit_includes(&mut self, emit_includes: bool) -> &mut Config { + self.emit_includes = emit_includes; + self + } + + /// Should DLLs be copied to OUT_DIR? + /// Defaults to `true`. + pub fn copy_dlls(&mut self, copy_dlls: bool) -> &mut Config { + self.copy_dlls = copy_dlls; + self + } + + /// Find the library `port_name` in a Vcpkg tree. + /// + /// This will use all configuration previously set to select the + /// architecture and linkage. + pub fn probe(&mut self, port_name: &str) -> Result<Library, Error> { + // determine the target type, bailing out if it is not some + // kind of msvc + let msvc_target = try!(msvc_target()); + + // bail out if requested to not try at all + if env::var_os("VCPKGRS_DISABLE").is_some() { + return Err(Error::DisabledByEnv("VCPKGRS_DISABLE".to_owned())); + } + + // bail out if requested to not try at all (old) + if env::var_os("NO_VCPKG").is_some() { + return Err(Error::DisabledByEnv("NO_VCPKG".to_owned())); + } + + // bail out if requested to skip this package + let abort_var_name = format!("VCPKGRS_NO_{}", envify(port_name)); + if env::var_os(&abort_var_name).is_some() { + return Err(Error::DisabledByEnv(abort_var_name)); + } + + // bail out if requested to skip this package (old) + let abort_var_name = format!("{}_NO_VCPKG", envify(port_name)); + if env::var_os(&abort_var_name).is_some() { + return Err(Error::DisabledByEnv(abort_var_name)); + } + + // if no overrides have been selected, then the Vcpkg port name + // is the the .lib name and the .dll name + if self.required_libs.is_empty() { + self.required_libs.push(LibNames { + lib_stem: port_name.to_owned(), + dll_stem: port_name.to_owned(), + }); + } + + let vcpkg_target = try!(find_vcpkg_target(&msvc_target)); + + // require explicit opt-in before using dynamically linked + // variants, otherwise cargo install of various things will + // stop working if Vcpkg is installed. + if !vcpkg_target.is_static && !env::var_os("VCPKGRS_DYNAMIC").is_some() { + return Err(Error::RequiredEnvMissing("VCPKGRS_DYNAMIC".to_owned())); + } + + let mut lib = Library::new(vcpkg_target.is_static); + + if self.emit_includes { + lib.cargo_metadata.push(format!( + "cargo:include={}", + vcpkg_target.include_path.display() + )); + } + lib.include_paths.push(vcpkg_target.include_path); + + lib.cargo_metadata.push(format!( + "cargo:rustc-link-search=native={}", + vcpkg_target + .lib_path + .to_str() + .expect("failed to convert string type") + )); + lib.link_paths.push(vcpkg_target.lib_path.clone()); + if !vcpkg_target.is_static { + lib.cargo_metadata.push(format!( + "cargo:rustc-link-search=native={}", + vcpkg_target + .bin_path + .to_str() + .expect("failed to convert string type") + )); + // this path is dropped by recent version of cargo hence the copies to OUT_DIR below + lib.dll_paths.push(vcpkg_target.bin_path.clone()); + } + drop(port_name); + for required_lib in &self.required_libs { + if vcpkg_target.is_static { + lib.cargo_metadata.push(format!( + "cargo:rustc-link-lib=static={}", + required_lib.lib_stem + )); + } else { + lib.cargo_metadata + .push(format!("cargo:rustc-link-lib={}", required_lib.lib_stem)); + } + + // verify that the library exists + let mut lib_location = vcpkg_target.lib_path.clone(); + lib_location.push(format!("{}.lib", required_lib.lib_stem)); + + if !lib_location.exists() { + return Err(Error::LibNotFound(lib_location.display().to_string())); + } + lib.found_libs.push(lib_location); + + // verify that the DLL exists + if !vcpkg_target.is_static { + let mut lib_location = vcpkg_target.bin_path.clone(); + lib_location.push(format!("{}.dll", required_lib.dll_stem)); + + if !lib_location.exists() { + return Err(Error::LibNotFound(lib_location.display().to_string())); + } + lib.found_dlls.push(lib_location); + } + } + + if self.copy_dlls { + if let Some(target_dir) = env::var_os("OUT_DIR") { + if !lib.found_dlls.is_empty() { + for file in &lib.found_dlls { + let mut dest_path = Path::new(target_dir.as_os_str()).to_path_buf(); + dest_path.push(Path::new(file.file_name().unwrap())); + try!(fs::copy(file, &dest_path).map_err(|_| { + Error::LibNotFound(format!( + "Can't copy file {} to {}", + file.to_string_lossy(), + dest_path.to_string_lossy() + )) + })); + println!( + "vcpkg build helper copied {} to {}", + file.to_string_lossy(), + dest_path.to_string_lossy() + ); + } + lib.cargo_metadata.push(format!( + "cargo:rustc-link-search=native={}", + env::var("OUT_DIR").unwrap() + )); + // work around https://github.com/rust-lang/cargo/issues/3957 + lib.cargo_metadata.push(format!( + "cargo:rustc-link-search={}", + env::var("OUT_DIR").unwrap() + )); + } + } else { + return Err(Error::LibNotFound("Unable to get OUT_DIR".to_owned())); + } + } + + if self.cargo_metadata { + for line in &lib.cargo_metadata { + println!("{}", line); + } + } + Ok(lib) + } +} + +impl Library { + pub fn new(is_static: bool) -> Library { + Library { + link_paths: Vec::new(), + dll_paths: Vec::new(), + include_paths: Vec::new(), + cargo_metadata: Vec::new(), + is_static: is_static, + found_dlls: Vec::new(), + found_libs: Vec::new(), + } + } +} + +fn envify(name: &str) -> String { + name.chars() + .map(|c| c.to_ascii_uppercase()) + .map(|c| if c == '-' { '_' } else { c }) + .collect() +} + +fn msvc_target() -> Result<MSVCTarget, Error> { + let target = env::var("TARGET").unwrap_or(String::new()); + if !target.contains("-pc-windows-msvc") { + Err(Error::NotMSVC) + } else if target.starts_with("x86_64-") { + Ok(MSVCTarget::X64) + } else { + // everything else is x86 + Ok(MSVCTarget::X86) + } +} diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/appveyor.yml cargo-0.26.0/vendor/walkdir-1.0.7/appveyor.yml --- cargo-0.25.0/vendor/walkdir-1.0.7/appveyor.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,23 +0,0 @@ -environment: - matrix: - - TARGET: x86_64-pc-windows-msvc - - TARGET: i686-pc-windows-msvc - - TARGET: i686-pc-windows-gnu - -install: - - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" - - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - - SET PATH=%PATH%;C:\MinGW\bin - - rustc -V - - cargo -V - -build: false - -test_script: - - cargo build --verbose - - cargo test --verbose - -branches: - only: - - master diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/.cargo-checksum.json cargo-0.26.0/vendor/walkdir-1.0.7/.cargo-checksum.json --- cargo-0.25.0/vendor/walkdir-1.0.7/.cargo-checksum.json 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -{"files":{},"package":"bb08f9e670fab86099470b97cd2b252d6527f0b3cc1401acdb595ffc9dd288ff"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/Cargo.toml cargo-0.26.0/vendor/walkdir-1.0.7/Cargo.toml --- cargo-0.25.0/vendor/walkdir-1.0.7/Cargo.toml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -[package] -name = "walkdir" -version = "1.0.7" #:version -authors = ["Andrew Gallant <jamslam@gmail.com>"] -description = "Recursively walk a directory." -documentation = "https://docs.rs/walkdir/" -homepage = "https://github.com/BurntSushi/walkdir" -repository = "https://github.com/BurntSushi/walkdir" -readme = "README.md" -keywords = ["directory", "recursive", "walk", "iterator"] -license = "Unlicense/MIT" - -[dependencies] -same-file = "0.1.1" - -[target.'cfg(windows)'.dependencies] -kernel32-sys = "0.2" -winapi = "0.2" - -[dev-dependencies] -docopt = "0.7" -quickcheck = { version = "0.4", default-features = false } -rand = "0.3" -rustc-serialize = "0.3" diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/compare/nftw.c cargo-0.26.0/vendor/walkdir-1.0.7/compare/nftw.c --- cargo-0.25.0/vendor/walkdir-1.0.7/compare/nftw.c 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/compare/nftw.c 1970-01-01 00:00:00.000000000 +0000 @@ -1,25 +0,0 @@ -#define _XOPEN_SOURCE 500 -#include <ftw.h> -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <stdint.h> - -static int -display_info(const char *fpath, const struct stat *sb, - int tflag, struct FTW *ftwbuf) -{ - printf("%s\n", fpath); - return 0; -} - -int -main(int argc, char *argv[]) -{ - int flags = FTW_PHYS; - if (nftw((argc < 2) ? "." : argv[1], display_info, 20, flags) == -1) { - perror("nftw"); - exit(EXIT_FAILURE); - } - exit(EXIT_SUCCESS); -} diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/compare/walk.py cargo-0.26.0/vendor/walkdir-1.0.7/compare/walk.py --- cargo-0.25.0/vendor/walkdir-1.0.7/compare/walk.py 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/compare/walk.py 1970-01-01 00:00:00.000000000 +0000 @@ -1,10 +0,0 @@ -from __future__ import absolute_import, division, print_function - -import os -import sys - -for dirpath, dirnames, filenames in os.walk(sys.argv[1]): - for n in dirnames: - print(os.path.join(dirpath, n)) - for n in filenames: - print(os.path.join(dirpath, n)) diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/COPYING cargo-0.26.0/vendor/walkdir-1.0.7/COPYING --- cargo-0.25.0/vendor/walkdir-1.0.7/COPYING 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/COPYING 1970-01-01 00:00:00.000000000 +0000 @@ -1,3 +0,0 @@ -This project is dual-licensed under the Unlicense and MIT licenses. - -You may use this code under the terms of either license. diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/ctags.rust cargo-0.26.0/vendor/walkdir-1.0.7/ctags.rust --- cargo-0.25.0/vendor/walkdir-1.0.7/ctags.rust 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/ctags.rust 1970-01-01 00:00:00.000000000 +0000 @@ -1,11 +0,0 @@ ---langdef=Rust ---langmap=Rust:.rs ---regex-Rust=/^[ \t]*(#\[[^\]]\][ \t]*)*(pub[ \t]+)?(extern[ \t]+)?("[^"]+"[ \t]+)?(unsafe[ \t]+)?fn[ \t]+([a-zA-Z0-9_]+)/\6/f,functions,function definitions/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?type[ \t]+([a-zA-Z0-9_]+)/\2/T,types,type definitions/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?enum[ \t]+([a-zA-Z0-9_]+)/\2/g,enum,enumeration names/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?struct[ \t]+([a-zA-Z0-9_]+)/\2/s,structure names/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?mod[ \t]+([a-zA-Z0-9_]+)/\2/m,modules,module names/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?static[ \t]+([a-zA-Z0-9_]+)/\2/c,consts,static constants/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?trait[ \t]+([a-zA-Z0-9_]+)/\2/t,traits,traits/ ---regex-Rust=/^[ \t]*(pub[ \t]+)?impl([ \t\n]+<.*>)?[ \t]+([a-zA-Z0-9_]+)/\3/i,impls,trait implementations/ ---regex-Rust=/^[ \t]*macro_rules![ \t]+([a-zA-Z0-9_]+)/\1/d,macros,macro definitions/ diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/examples/walkdir.rs cargo-0.26.0/vendor/walkdir-1.0.7/examples/walkdir.rs --- cargo-0.25.0/vendor/walkdir-1.0.7/examples/walkdir.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/examples/walkdir.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,91 +0,0 @@ -extern crate docopt; -extern crate rustc_serialize; -extern crate walkdir; - -use std::io::{self, Write}; - -use docopt::Docopt; -use walkdir::WalkDir; - -const USAGE: &'static str = " -Usage: - walkdir [options] [<dir>] - -Options: - -h, --help - -L, --follow-links Follow symlinks. - --min-depth NUM Minimum depth. - --max-depth NUM Maximum depth. - -n, --fd-max NUM Maximum open file descriptors. [default: 32] - --tree Show output as a tree. - --sort Sort the output. - -q, --ignore-errors Ignore errors. -"; - -#[derive(Debug, RustcDecodable)] -#[allow(dead_code)] -struct Args { - arg_dir: Option<String>, - flag_follow_links: bool, - flag_min_depth: Option<usize>, - flag_max_depth: Option<usize>, - flag_fd_max: usize, - flag_tree: bool, - flag_ignore_errors: bool, - flag_sort: bool, -} - -macro_rules! wout { ($($tt:tt)*) => { {writeln!($($tt)*)}.unwrap() } } - -fn main() { - let args: Args = Docopt::new(USAGE).and_then(|d| d.decode()) - .unwrap_or_else(|e| e.exit()); - let mind = args.flag_min_depth.unwrap_or(0); - let maxd = args.flag_max_depth.unwrap_or(::std::usize::MAX); - let dir = args.arg_dir.clone().unwrap_or(".".to_owned()); - let mut walkdir = WalkDir::new(dir) - .max_open(args.flag_fd_max) - .follow_links(args.flag_follow_links) - .min_depth(mind) - .max_depth(maxd); - if args.flag_sort { - walkdir = walkdir.sort_by(|a,b| a.cmp(b)); - } - let it = walkdir.into_iter(); - let mut out = io::BufWriter::new(io::stdout()); - let mut eout = io::stderr(); - if args.flag_tree { - for dent in it { - match dent { - Err(err) => { - out.flush().unwrap(); - wout!(eout, "ERROR: {}", err); - } - Ok(dent) => { - let name = dent.file_name().to_string_lossy(); - wout!(out, "{}{}", indent(dent.depth()), name); - } - } - } - } else if args.flag_ignore_errors { - for dent in it.filter_map(|e| e.ok()) { - wout!(out, "{}", dent.path().display()); - } - } else { - for dent in it { - match dent { - Err(err) => { - out.flush().unwrap(); - wout!(eout, "ERROR: {}", err); - } - Ok(dent) => { - wout!(out, "{}", dent.path().display()); - } - } - } - } -} - -fn indent(depth: usize) -> String { - ::std::iter::repeat(' ').take(2 * depth).collect() -} diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/LICENSE-MIT cargo-0.26.0/vendor/walkdir-1.0.7/LICENSE-MIT --- cargo-0.25.0/vendor/walkdir-1.0.7/LICENSE-MIT 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Andrew Gallant - -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. diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/Makefile cargo-0.26.0/vendor/walkdir-1.0.7/Makefile --- cargo-0.25.0/vendor/walkdir-1.0.7/Makefile 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/Makefile 1970-01-01 00:00:00.000000000 +0000 @@ -1,14 +0,0 @@ -all: - echo Nothing to do... - -ctags: - ctags --recurse --options=ctags.rust --languages=Rust - -docs: - cargo doc - in-dir ./target/doc fix-perms - rscp ./target/doc/* gopher:~/www/burntsushi.net/rustdoc/ - -push: - git push origin master - git push github master diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/README.md cargo-0.26.0/vendor/walkdir-1.0.7/README.md --- cargo-0.25.0/vendor/walkdir-1.0.7/README.md 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/README.md 1970-01-01 00:00:00.000000000 +0000 @@ -1,140 +0,0 @@ -walkdir -======= -A cross platform Rust library for efficiently walking a directory recursively. -Comes with support for following symbolic links, controlling the number of -open file descriptors and efficient mechanisms for pruning the entries in the -directory tree. - -[![Linux build status](https://api.travis-ci.org/BurntSushi/walkdir.svg)](https://travis-ci.org/BurntSushi/walkdir) -[![Windows build status](https://ci.appveyor.com/api/projects/status/github/BurntSushi/walkdir?svg=true)](https://ci.appveyor.com/project/BurntSushi/walkdir) -[![](http://meritbadge.herokuapp.com/walkdir)](https://crates.io/crates/walkdir) - -Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). - -### Documentation - -[docs.rs/walkdir](https://docs.rs/walkdir/) - -### Usage - -To use this crate, add `walkdir` as a dependency to your project's -`Cargo.toml`: - -``` -[dependencies] -walkdir = "1" -``` - -### Example - -The following code recursively iterates over the directory given and prints -the path for each entry: - -```rust,no_run -use walkdir::WalkDir; - -for entry in WalkDir::new("foo") { - let entry = entry.unwrap(); - println!("{}", entry.path().display()); -} -``` - -Or, if you'd like to iterate over all entries and ignore any errors that may -arise, use `filter_map`. (e.g., This code below will silently skip directories -that the owner of the running process does not have permission to access.) - -```rust,no_run -use walkdir::WalkDir; - -for entry in WalkDir::new("foo").into_iter().filter_map(|e| e.ok()) { - println!("{}", entry.path().display()); -} -``` - -### Example: follow symbolic links - -The same code as above, except `follow_links` is enabled: - -```rust,no_run -use walkdir::WalkDir; - -for entry in WalkDir::new("foo").follow_links(true) { - let entry = entry.unwrap(); - println!("{}", entry.path().display()); -} -``` - -### Example: skip hidden files and directories efficiently on unix - -This uses the `filter_entry` iterator adapter to avoid yielding hidden files -and directories efficiently: - -```rust,no_run -use walkdir::{DirEntry, WalkDir, WalkDirIterator}; - -fn is_hidden(entry: &DirEntry) -> bool { - entry.file_name() - .to_str() - .map(|s| s.starts_with(".")) - .unwrap_or(false) -} - -let walker = WalkDir::new("foo").into_iter(); -for entry in walker.filter_entry(|e| !is_hidden(e)) { - let entry = entry.unwrap(); - println!("{}", entry.path().display()); -} -``` - -### Motivation - -`std::fs` has an unstable `walk_dir` implementation that needed some design -work. I started off on that task, but it quickly became apparent that walking -a directory recursively is quite complex and may not be a good fit for `std` -right away. - -This should at least resolve most or all of the issues reported here (and then -some): - -* https://github.com/rust-lang/rust/issues/27707 -* https://github.com/rust-lang/rust/issues/23715 - -### Performance - -The short story is that performance is comparable with `find` and glibc's -`nftw` on both a warm and cold file cache. In fact, I cannot observe any -performance difference after running `find /`, `walkdir /` and `nftw /` on my -local file system (SSD, ~3 million entries). More precisely, I am reasonably -confident that this crate makes as few system calls and close to as few -allocations as possible. - -I haven't recorded any benchmarks, but here are some things you can try with a -local checkout of `walkdir`: - -``` -# The directory you want to recursively walk: -DIR=$HOME - -# If you want to observe perf on a cold file cache, run this before *each* -# command: -sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' - -# To warm the caches -find $DIR - -# Test speed of `find` on warm cache: -time find $DIR - -# Compile and test speed of `walkdir` crate: -cargo build --release --example walkdir -time ./target/release/examples/walkdir $DIR - -# Compile and test speed of glibc's `nftw`: -gcc -O3 -o nftw ./compare/nftw.c -time ./nftw $DIR - -# For shits and giggles, test speed of Python's (2 or 3) os.walk: -time python ./compare/walk.py $DIR -``` - -On my system, the performance of `walkdir`, `find` and `nftw` is comparable. diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/session.vim cargo-0.26.0/vendor/walkdir-1.0.7/session.vim --- cargo-0.25.0/vendor/walkdir-1.0.7/session.vim 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/session.vim 1970-01-01 00:00:00.000000000 +0000 @@ -1 +0,0 @@ -au BufWritePost *.rs silent!make ctags > /dev/null 2>&1 diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/src/lib.rs cargo-0.26.0/vendor/walkdir-1.0.7/src/lib.rs --- cargo-0.25.0/vendor/walkdir-1.0.7/src/lib.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,1006 +0,0 @@ -/*! -Crate `walkdir` provides an efficient and cross platform implementation -of recursive directory traversal. Several options are exposed to control -iteration, such as whether to follow symbolic links (default off), limit the -maximum number of simultaneous open file descriptors and the ability to -efficiently skip descending into directories. - -To use this crate, add `walkdir` as a dependency to your project's -`Cargo.toml`: - -```ignore -[dependencies] -walkdir = "1" -``` - -# From the top - -The `WalkDir` type builds iterators. The `WalkDirIterator` trait provides -methods for directory iterator adapters, such as efficiently pruning entries -during traversal. The `DirEntry` type describes values yielded by the iterator. -Finally, the `Error` type is a small wrapper around `std::io::Error` with -additional information, such as if a loop was detected while following symbolic -links (not enabled by default). - -# Example - -The following code recursively iterates over the directory given and prints -the path for each entry: - -```rust,no_run -use walkdir::WalkDir; - -for entry in WalkDir::new("foo") { - let entry = entry.unwrap(); - println!("{}", entry.path().display()); -} -``` - -Or, if you'd like to iterate over all entries and ignore any errors that may -arise, use `filter_map`. (e.g., This code below will silently skip directories -that the owner of the running process does not have permission to access.) - -```rust,no_run -use walkdir::WalkDir; - -for entry in WalkDir::new("foo").into_iter().filter_map(|e| e.ok()) { - println!("{}", entry.path().display()); -} -``` - -# Example: follow symbolic links - -The same code as above, except `follow_links` is enabled: - -```rust,no_run -use walkdir::WalkDir; - -for entry in WalkDir::new("foo").follow_links(true) { - let entry = entry.unwrap(); - println!("{}", entry.path().display()); -} -``` - -# Example: skip hidden files and directories efficiently on unix - -This uses the `filter_entry` iterator adapter to avoid yielding hidden files -and directories efficiently: - -```rust,no_run -use walkdir::{DirEntry, WalkDir, WalkDirIterator}; - -fn is_hidden(entry: &DirEntry) -> bool { - entry.file_name() - .to_str() - .map(|s| s.starts_with(".")) - .unwrap_or(false) -} - -let walker = WalkDir::new("foo").into_iter(); -for entry in walker.filter_entry(|e| !is_hidden(e)) { - let entry = entry.unwrap(); - println!("{}", entry.path().display()); -} -``` - -*/ -#[cfg(windows)] extern crate kernel32; -#[cfg(windows)] extern crate winapi; -#[cfg(test)] extern crate quickcheck; -#[cfg(test)] extern crate rand; -extern crate same_file; - -use std::cmp::{Ordering, min}; -use std::error; -use std::fmt; -use std::fs::{self, FileType, ReadDir}; -use std::io; -use std::ffi::OsStr; -use std::ffi::OsString; -use std::path::{Path, PathBuf}; -use std::result; -use std::vec; - -pub use same_file::is_same_file; - -#[cfg(test)] mod tests; - -/// Like try, but for iterators that return `Option<Result<_, _>>`. -macro_rules! itry { - ($e:expr) => { - match $e { - Ok(v) => v, - Err(err) => return Some(Err(From::from(err))), - } - } -} - -/// A result type for walkdir operations. -/// -/// Note that this result type embeds the error type in this crate. This -/// is only useful if you care about the additional information provided by -/// the error (such as the path associated with the error or whether a loop -/// was dectected). If you want things to Just Work, then you can use -/// `io::Result` instead since the error type in this package will -/// automatically convert to an `io::Result` when using the `try!` macro. -pub type Result<T> = ::std::result::Result<T, Error>; - -/// A builder to create an iterator for recursively walking a directory. -/// -/// Results are returned in depth first fashion, with directories yielded -/// before their contents. The order is unspecified. Directory entries `.` -/// and `..` are always omitted. -/// -/// If an error occurs at any point during iteration, then it is returned in -/// place of its corresponding directory entry and iteration continues as -/// normal. If an error occurs while opening a directory for reading, it -/// is skipped. Iteration may be stopped at any time. When the iterator is -/// destroyed, all resources associated with it are freed. -/// -/// # Usage -/// -/// This type implements `IntoIterator` so that it may be used as the subject -/// of a `for` loop. You may need to call `into_iter` explicitly if you want -/// to use iterator adapters such as `filter_entry`. -/// -/// Idiomatic use of this type should use method chaining to set desired -/// options. For example, this only shows entries with a depth of `1`, `2` -/// or `3` (relative to `foo`): -/// -/// ```rust,no_run -/// use walkdir::WalkDir; -/// -/// for entry in WalkDir::new("foo").min_depth(1).max_depth(3) { -/// let entry = entry.unwrap(); -/// println!("{}", entry.path().display()); -/// } -/// ``` -/// -/// Note that the iterator by default includes the top-most directory. Since -/// this is the only directory yielded with depth `0`, it is easy to ignore it -/// with the `min_depth` setting: -/// -/// ```rust,no_run -/// use walkdir::WalkDir; -/// -/// for entry in WalkDir::new("foo").min_depth(1) { -/// let entry = entry.unwrap(); -/// println!("{}", entry.path().display()); -/// } -/// ``` -/// -/// This will only return descendents of the `foo` directory and not `foo` -/// itself. -/// -/// # Loops -/// -/// This iterator (like most/all recursive directory iterators) assumes that -/// no loops can be made with *hard* links on your file system. In particular, -/// this would require creating a hard link to a directory such that it creates -/// a loop. On most platforms, this operation is illegal. -/// -/// Note that when following symbolic/soft links, loops are detected and an -/// error is reported. -pub struct WalkDir { - opts: WalkDirOptions, - root: PathBuf, -} - -struct WalkDirOptions { - follow_links: bool, - max_open: usize, - min_depth: usize, - max_depth: usize, - sorter: Option<Box<FnMut(&OsString,&OsString) -> Ordering + 'static>>, -} - -impl WalkDir { - /// Create a builder for a recursive directory iterator starting at the - /// file path `root`. If `root` is a directory, then it is the first item - /// yielded by the iterator. If `root` is a file, then it is the first - /// and only item yielded by the iterator. If `root` is a symlink, then it - /// is always followed. - pub fn new<P: AsRef<Path>>(root: P) -> Self { - WalkDir { - opts: WalkDirOptions { - follow_links: false, - max_open: 10, - min_depth: 0, - max_depth: ::std::usize::MAX, - sorter: None, - }, - root: root.as_ref().to_path_buf(), - } - } - - /// Set the minimum depth of entries yielded by the iterator. - /// - /// The smallest depth is `0` and always corresponds to the path given - /// to the `new` function on this type. Its direct descendents have depth - /// `1`, and their descendents have depth `2`, and so on. - pub fn min_depth(mut self, depth: usize) -> Self { - self.opts.min_depth = depth; - if self.opts.min_depth > self.opts.max_depth { - self.opts.min_depth = self.opts.max_depth; - } - self - } - - /// Set the maximum depth of entries yield by the iterator. - /// - /// The smallest depth is `0` and always corresponds to the path given - /// to the `new` function on this type. Its direct descendents have depth - /// `1`, and their descendents have depth `2`, and so on. - /// - /// Note that this will not simply filter the entries of the iterator, but - /// it will actually avoid descending into directories when the depth is - /// exceeded. - pub fn max_depth(mut self, depth: usize) -> Self { - self.opts.max_depth = depth; - if self.opts.max_depth < self.opts.min_depth { - self.opts.max_depth = self.opts.min_depth; - } - self - } - - /// Follow symbolic links. By default, this is disabled. - /// - /// When `yes` is `true`, symbolic links are followed as if they were - /// normal directories and files. If a symbolic link is broken or is - /// involved in a loop, an error is yielded. - /// - /// When enabled, the yielded `DirEntry` values represent the target of - /// the link while the path corresponds to the link. See the `DirEntry` - /// type for more details. - pub fn follow_links(mut self, yes: bool) -> Self { - self.opts.follow_links = yes; - self - } - - /// Set the maximum number of simultaneously open file descriptors used - /// by the iterator. - /// - /// `n` must be greater than or equal to `1`. If `n` is `0`, then it is set - /// to `1` automatically. If this is not set, then it defaults to some - /// reasonably low number. - /// - /// This setting has no impact on the results yielded by the iterator - /// (even when `n` is `1`). Instead, this setting represents a trade off - /// between scarce resources (file descriptors) and memory. Namely, when - /// the maximum number of file descriptors is reached and a new directory - /// needs to be opened to continue iteration, then a previous directory - /// handle is closed and has its unyielded entries stored in memory. In - /// practice, this is a satisfying trade off because it scales with respect - /// to the *depth* of your file tree. Therefore, low values (even `1`) are - /// acceptable. - /// - /// Note that this value does not impact the number of system calls made by - /// an exhausted iterator. - pub fn max_open(mut self, mut n: usize) -> Self { - if n == 0 { - n = 1; - } - self.opts.max_open = n; - self - } - - /// Set a function for sorting directory entries. - /// - /// If a compare function is set, the resulting iterator will return all - /// paths in sorted order. The compare function will be called to compare - /// names from entries from the same directory using only the name of the - /// entry. - /// - /// ```rust,no-run - /// use std::cmp; - /// use std::ffi::OsString; - /// use walkdir::WalkDir; - /// - /// WalkDir::new("foo").sort_by(|a,b| a.cmp(b)); - /// ``` - pub fn sort_by<F>(mut self, cmp: F) -> Self - where F: FnMut(&OsString, &OsString) -> Ordering + 'static { - self.opts.sorter = Some(Box::new(cmp)); - self - } -} - -impl IntoIterator for WalkDir { - type Item = Result<DirEntry>; - type IntoIter = Iter; - - fn into_iter(self) -> Iter { - Iter { - opts: self.opts, - start: Some(self.root), - stack_list: vec![], - stack_path: vec![], - oldest_opened: 0, - depth: 0, - } - } -} - -/// A trait for recursive directory iterators. -pub trait WalkDirIterator: Iterator { - /// Skips the current directory. - /// - /// This causes the iterator to stop traversing the contents of the least - /// recently yielded directory. This means any remaining entries in that - /// directory will be skipped (including sub-directories). - /// - /// Note that the ergnomics of this method are questionable since it - /// borrows the iterator mutably. Namely, you must write out the looping - /// condition manually. For example, to skip hidden entries efficiently on - /// unix systems: - /// - /// ```rust,no_run - /// use walkdir::{DirEntry, WalkDir, WalkDirIterator}; - /// - /// fn is_hidden(entry: &DirEntry) -> bool { - /// entry.file_name() - /// .to_str() - /// .map(|s| s.starts_with(".")) - /// .unwrap_or(false) - /// } - /// - /// let mut it = WalkDir::new("foo").into_iter(); - /// loop { - /// let entry = match it.next() { - /// None => break, - /// Some(Err(err)) => panic!("ERROR: {}", err), - /// Some(Ok(entry)) => entry, - /// }; - /// if is_hidden(&entry) { - /// if entry.file_type().is_dir() { - /// it.skip_current_dir(); - /// } - /// continue; - /// } - /// println!("{}", entry.path().display()); - /// } - /// ``` - /// - /// You may find it more convenient to use the `filter_entry` iterator - /// adapter. (See its documentation for the same example functionality as - /// above.) - fn skip_current_dir(&mut self); - - /// Yields only entries which satisfy the given predicate and skips - /// descending into directories that do not satisfy the given predicate. - /// - /// The predicate is applied to all entries. If the predicate is - /// true, iteration carries on as normal. If the predicate is false, the - /// entry is ignored and if it is a directory, it is not descended into. - /// - /// This is often more convenient to use than `skip_current_dir`. For - /// example, to skip hidden files and directories efficiently on unix - /// systems: - /// - /// ```rust,no_run - /// use walkdir::{DirEntry, WalkDir, WalkDirIterator}; - /// - /// fn is_hidden(entry: &DirEntry) -> bool { - /// entry.file_name() - /// .to_str() - /// .map(|s| s.starts_with(".")) - /// .unwrap_or(false) - /// } - /// - /// for entry in WalkDir::new("foo") - /// .into_iter() - /// .filter_entry(|e| !is_hidden(e)) { - /// let entry = entry.unwrap(); - /// println!("{}", entry.path().display()); - /// } - /// ``` - /// - /// Note that the iterator will still yield errors for reading entries that - /// may not satisfy the predicate. - /// - /// Note that entries skipped with `min_depth` and `max_depth` are not - /// passed to this predicate. - fn filter_entry<P>(self, predicate: P) -> IterFilterEntry<Self, P> - where Self: Sized, P: FnMut(&DirEntry) -> bool { - IterFilterEntry { it: self, predicate: predicate } - } -} - -/// An iterator for recursively descending into a directory. -/// -/// A value with this type must be constructed with the `WalkDir` type, which -/// uses a builder pattern to set options such as min/max depth, max open file -/// descriptors and whether the iterator should follow symbolic links. -/// -/// The order of elements yielded by this iterator is unspecified. -pub struct Iter { - /// Options specified in the builder. Depths, max fds, etc. - opts: WalkDirOptions, - /// The start path. - /// - /// This is only `Some(...)` at the beginning. After the first iteration, - /// this is always `None`. - start: Option<PathBuf>, - /// A stack of open (up to max fd) or closed handles to directories. - /// An open handle is a plain `fs::ReadDir` while a closed handle is - /// a `Vec<fs::DirEntry>` corresponding to the as-of-yet consumed entries. - stack_list: Vec<DirList>, - /// A stack of file paths. - /// - /// This is *only* used when `follow_links` is enabled. In all other cases - /// this stack is empty. - stack_path: Vec<PathBuf>, - /// An index into `stack_list` that points to the oldest open directory - /// handle. If the maximum fd limit is reached and a new directory needs - /// to be read, the handle at this index is closed before the new directory - /// is opened. - oldest_opened: usize, - /// The current depth of iteration (the length of the stack at the - /// beginning of each iteration). - depth: usize, -} - -/// A sequence of unconsumed directory entries. -/// -/// This represents the opened or closed state of a directory handle. When -/// open, future entries are read by iterating over the raw `fs::ReadDir`. -/// When closed, all future entries are read into memory. Iteration then -/// proceeds over a `Vec<fs::DirEntry>`. -enum DirList { - /// An opened handle. - /// - /// This includes the depth of the handle itself. - /// - /// If there was an error with the initial `fs::read_dir` call, then it is - /// stored here. (We use an `Option<...>` to make yielding the error - /// exactly once simpler.) - Opened { depth: usize, it: result::Result<ReadDir, Option<Error>> }, - /// A closed handle. - /// - /// All remaining directory entries are read into memory. - Closed(vec::IntoIter<Result<fs::DirEntry>>), -} - -/// A directory entry. -/// -/// This is the type of value that is yielded from the iterators defined in -/// this crate. -/// -/// # Differences with `std::fs::DirEntry` -/// -/// This type mostly mirrors the type by the same name in `std::fs`. There are -/// some differences however: -/// -/// * All recursive directory iterators must inspect the entry's type. -/// Therefore, the value is stored and its access is guaranteed to be cheap and -/// successful. -/// * `path` and `file_name` return borrowed variants. -/// * If `follow_links` was enabled on the originating iterator, then all -/// operations except for `path` operate on the link target. Otherwise, all -/// operations operate on the symbolic link. -pub struct DirEntry { - /// The path as reported by the `fs::ReadDir` iterator (even if it's a - /// symbolic link). - path: PathBuf, - /// The file type. Necessary for recursive iteration, so store it. - ty: FileType, - /// Is set when this entry was created from a symbolic link and the user - /// excepts the iterator to follow symbolic links. - follow_link: bool, - /// The depth at which this entry was generated relative to the root. - depth: usize, - /// The underlying inode number (Unix only). - #[cfg(unix)] - ino: u64, -} - -impl Iterator for Iter { - type Item = Result<DirEntry>; - - fn next(&mut self) -> Option<Result<DirEntry>> { - if let Some(start) = self.start.take() { - let dent = itry!(DirEntry::from_link(0, start)); - if let Some(result) = self.handle_entry(dent) { - return Some(result); - } - } - while !self.stack_list.is_empty() { - self.depth = self.stack_list.len(); - if self.depth > self.opts.max_depth { - // If we've exceeded the max depth, pop the current dir - // so that we don't descend. - self.pop(); - continue; - } - match self.stack_list.last_mut().unwrap().next() { - None => self.pop(), - Some(Err(err)) => return Some(Err(err)), - Some(Ok(dent)) => { - let dent = itry!(DirEntry::from_entry(self.depth, &dent)); - if let Some(result) = self.handle_entry(dent) { - return Some(result); - } - } - } - } - None - } -} - -impl WalkDirIterator for Iter { - fn skip_current_dir(&mut self) { - if !self.stack_list.is_empty() { - self.stack_list.pop(); - } - if !self.stack_path.is_empty() { - self.stack_path.pop(); - } - } -} - -impl Iter { - fn handle_entry( - &mut self, - mut dent: DirEntry, - ) -> Option<Result<DirEntry>> { - if self.opts.follow_links && dent.file_type().is_symlink() { - dent = itry!(self.follow(dent)); - } - if dent.file_type().is_dir() { - self.push(&dent); - } - if self.skippable() { None } else { Some(Ok(dent)) } - } - - fn push(&mut self, dent: &DirEntry) { - // Make room for another open file descriptor if we've hit the max. - if self.stack_list.len() - self.oldest_opened == self.opts.max_open { - self.stack_list[self.oldest_opened].close(); - self.oldest_opened = self.oldest_opened.checked_add(1).unwrap(); - } - // Open a handle to reading the directory's entries. - let rd = fs::read_dir(dent.path()).map_err(|err| { - Some(Error::from_path(self.depth, dent.path().to_path_buf(), err)) - }); - let mut list = DirList::Opened { depth: self.depth, it: rd }; - if let Some(ref mut cmp) = self.opts.sorter { - let mut entries: Vec<_> = list.collect(); - entries.sort_by(|a, b| { - match (a, b) { - (&Ok(ref a), &Ok(ref b)) => { - cmp(&a.file_name(), &b.file_name()) - } - (&Err(_), &Err(_)) => Ordering::Equal, - (&Ok(_), &Err(_)) => Ordering::Greater, - (&Err(_), &Ok(_)) => Ordering::Less, - } - }); - list = DirList::Closed(entries.into_iter()); - } - self.stack_list.push(list); - if self.opts.follow_links { - self.stack_path.push(dent.path().to_path_buf()); - } - } - - fn pop(&mut self) { - self.stack_list.pop().expect("cannot pop from empty stack"); - if self.opts.follow_links { - self.stack_path.pop().expect("BUG: list/path stacks out of sync"); - } - // If everything in the stack is already closed, then there is - // room for at least one more open descriptor and it will - // always be at the top of the stack. - self.oldest_opened = min(self.oldest_opened, self.stack_list.len()); - } - - fn follow(&self, mut dent: DirEntry) -> Result<DirEntry> { - dent = try!(DirEntry::from_link(self.depth, - dent.path().to_path_buf())); - // The only way a symlink can cause a loop is if it points - // to a directory. Otherwise, it always points to a leaf - // and we can omit any loop checks. - if dent.file_type().is_dir() { - try!(self.check_loop(dent.path())); - } - Ok(dent) - } - - fn check_loop<P: AsRef<Path>>(&self, child: P) -> Result<()> { - for ancestor in self.stack_path.iter().rev() { - let same = try!(is_same_file(ancestor, &child).map_err(|err| { - Error::from_io(self.depth, err) - })); - if same { - return Err(Error { - depth: self.depth, - inner: ErrorInner::Loop { - ancestor: ancestor.to_path_buf(), - child: child.as_ref().to_path_buf(), - }, - }); - } - } - Ok(()) - } - - fn skippable(&self) -> bool { - self.depth < self.opts.min_depth || self.depth > self.opts.max_depth - } -} - -impl DirList { - fn close(&mut self) { - if let DirList::Opened { .. } = *self { - *self = DirList::Closed(self.collect::<Vec<_>>().into_iter()); - } - } -} - -impl Iterator for DirList { - type Item = Result<fs::DirEntry>; - - #[inline(always)] - fn next(&mut self) -> Option<Result<fs::DirEntry>> { - match *self { - DirList::Closed(ref mut it) => it.next(), - DirList::Opened { depth, ref mut it } => match *it { - Err(ref mut err) => err.take().map(Err), - Ok(ref mut rd) => rd.next().map(|r| r.map_err(|err| { - Error::from_io(depth + 1, err) - })), - } - } - } -} - -impl DirEntry { - /// The full path that this entry represents. - /// - /// The full path is created by joining the parents of this entry up to the - /// root initially given to `WalkDir::new` with the file name of this - /// entry. - /// - /// Note that this *always* returns the path reported by the underlying - /// directory entry, even when symbolic links are followed. To get the - /// target path, use `path_is_symbolic_link` to (cheaply) check if - /// this entry corresponds to a symbolic link, and `std::fs::read_link` to - /// resolve the target. - pub fn path(&self) -> &Path { - &self.path - } - - /// Returns `true` if and only if this entry was created from a symbolic - /// link. This is unaffected by the `follow_links` setting. - /// - /// When `true`, the value returned by the `path` method is a - /// symbolic link name. To get the full target path, you must call - /// `std::fs::read_link(entry.path())`. - pub fn path_is_symbolic_link(&self) -> bool { - self.ty.is_symlink() || self.follow_link - } - - /// Return the metadata for the file that this entry points to. - /// - /// This will follow symbolic links if and only if the `WalkDir` value - /// has `follow_links` enabled. - /// - /// # Platform behavior - /// - /// This always calls `std::fs::symlink_metadata`. - /// - /// If this entry is a symbolic link and `follow_links` is enabled, then - /// `std::fs::metadata` is called instead. - pub fn metadata(&self) -> Result<fs::Metadata> { - if self.follow_link { - fs::metadata(&self.path) - } else { - fs::symlink_metadata(&self.path) - }.map_err(|err| Error::from_entry(self, err)) - } - - /// Return the file type for the file that this entry points to. - /// - /// If this is a symbolic link and `follow_links` is `true`, then this - /// returns the type of the target. - /// - /// This never makes any system calls. - pub fn file_type(&self) -> fs::FileType { - self.ty - } - - /// Return the file name of this entry. - /// - /// If this entry has no file name (e.g., `/`), then the full path is - /// returned. - pub fn file_name(&self) -> &OsStr { - self.path.file_name().unwrap_or_else(|| self.path.as_os_str()) - } - - /// Returns the depth at which this entry was created relative to the root. - /// - /// The smallest depth is `0` and always corresponds to the path given - /// to the `new` function on `WalkDir`. Its direct descendents have depth - /// `1`, and their descendents have depth `2`, and so on. - pub fn depth(&self) -> usize { - self.depth - } - - /// Returns the underlying `d_ino` field in the contained `dirent` - /// structure. - #[cfg(unix)] - pub fn ino(&self) -> u64 { - self.ino - } - - #[cfg(not(unix))] - fn from_entry(depth: usize, ent: &fs::DirEntry) -> Result<DirEntry> { - let ty = try!(ent.file_type().map_err(|err| { - Error::from_path(depth, ent.path(), err) - })); - Ok(DirEntry { - path: ent.path(), - ty: ty, - follow_link: false, - depth: depth, - }) - } - - #[cfg(unix)] - fn from_entry(depth: usize, ent: &fs::DirEntry) -> Result<DirEntry> { - use std::os::unix::fs::DirEntryExt; - - let ty = try!(ent.file_type().map_err(|err| { - Error::from_path(depth, ent.path(), err) - })); - Ok(DirEntry { - path: ent.path(), - ty: ty, - follow_link: false, - depth: depth, - ino: ent.ino(), - }) - } - - #[cfg(not(unix))] - fn from_link(depth: usize, pb: PathBuf) -> Result<DirEntry> { - let md = try!(fs::metadata(&pb).map_err(|err| { - Error::from_path(depth, pb.clone(), err) - })); - Ok(DirEntry { - path: pb, - ty: md.file_type(), - follow_link: true, - depth: depth, - }) - } - - #[cfg(unix)] - fn from_link(depth: usize, pb: PathBuf) -> Result<DirEntry> { - use std::os::unix::fs::MetadataExt; - - let md = try!(fs::metadata(&pb).map_err(|err| { - Error::from_path(depth, pb.clone(), err) - })); - Ok(DirEntry { - path: pb, - ty: md.file_type(), - follow_link: true, - depth: depth, - ino: md.ino(), - }) - } -} - -impl Clone for DirEntry { - #[cfg(not(unix))] - fn clone(&self) -> DirEntry { - DirEntry { - path: self.path.clone(), - ty: self.ty, - follow_link: self.follow_link, - depth: self.depth, - } - } - - #[cfg(unix)] - fn clone(&self) -> DirEntry { - DirEntry { - path: self.path.clone(), - ty: self.ty, - follow_link: self.follow_link, - depth: self.depth, - ino: self.ino, - } - } -} - -impl fmt::Debug for DirEntry { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "DirEntry({:?})", self.path) - } -} - -/// A recursive directory iterator that skips entries. -/// -/// Directories that fail the predicate `P` are skipped. Namely, they are -/// never yielded and never descended into. -/// -/// Entries that are skipped with the `min_depth` and `max_depth` options are -/// not passed through this filter. -/// -/// If opening a handle to a directory resulted in an error, then it is yielded -/// and no corresponding call to the predicate is made. -/// -/// Type parameter `I` refers to the underlying iterator and `P` refers to the -/// predicate, which is usually `FnMut(&DirEntry) -> bool`. -pub struct IterFilterEntry<I, P> { - it: I, - predicate: P, -} - -impl<I, P> Iterator for IterFilterEntry<I, P> - where I: WalkDirIterator<Item=Result<DirEntry>>, - P: FnMut(&DirEntry) -> bool { - type Item = Result<DirEntry>; - - fn next(&mut self) -> Option<Result<DirEntry>> { - loop { - let dent = match self.it.next() { - None => return None, - Some(result) => itry!(result), - }; - if !(self.predicate)(&dent) { - if dent.file_type().is_dir() { - self.it.skip_current_dir(); - } - continue; - } - return Some(Ok(dent)); - } - } -} - -impl<I, P> WalkDirIterator for IterFilterEntry<I, P> - where I: WalkDirIterator<Item=Result<DirEntry>>, - P: FnMut(&DirEntry) -> bool { - fn skip_current_dir(&mut self) { - self.it.skip_current_dir(); - } -} - -/// An error produced by recursively walking a directory. -/// -/// This error type is a light wrapper around `std::io::Error`. In particular, -/// it adds the following information: -/// -/// * The depth at which the error occurred in the file tree, relative to the -/// root. -/// * The path, if any, associated with the IO error. -/// * An indication that a loop occurred when following symbolic links. In this -/// case, there is no underlying IO error. -/// -/// To maintain good ergnomics, this type has a -/// `impl From<Error> for std::io::Error` defined so that you may use an -/// `io::Result` with methods in this crate if you don't care about accessing -/// the underlying error data in a structured form. -#[derive(Debug)] -pub struct Error { - depth: usize, - inner: ErrorInner, -} - -#[derive(Debug)] -enum ErrorInner { - Io { path: Option<PathBuf>, err: io::Error }, - Loop { ancestor: PathBuf, child: PathBuf }, -} - -impl Error { - /// Returns the path associated with this error if one exists. - /// - /// For example, if an error occurred while opening a directory handle, - /// the error will include the path passed to `std::fs::read_dir`. - pub fn path(&self) -> Option<&Path> { - match self.inner { - ErrorInner::Io { path: None, .. } => None, - ErrorInner::Io { path: Some(ref path), .. } => Some(path), - ErrorInner::Loop { ref child, .. } => Some(child), - } - } - - /// Returns the path at which a cycle was detected. - /// - /// If no cycle was detected, `None` is returned. - /// - /// A cycle is detected when a directory entry is equivalent to one of - /// its ancestors. - /// - /// To get the path to the child directory entry in the cycle, use the - /// `path` method. - pub fn loop_ancestor(&self) -> Option<&Path> { - match self.inner { - ErrorInner::Loop { ref ancestor, .. } => Some(ancestor), - _ => None, - } - } - - /// Returns the depth at which this error occurred relative to the root. - /// - /// The smallest depth is `0` and always corresponds to the path given - /// to the `new` function on `WalkDir`. Its direct descendents have depth - /// `1`, and their descendents have depth `2`, and so on. - pub fn depth(&self) -> usize { - self.depth - } - - fn from_path(depth: usize, pb: PathBuf, err: io::Error) -> Self { - Error { - depth: depth, - inner: ErrorInner::Io { path: Some(pb), err: err }, - } - } - - fn from_entry(dent: &DirEntry, err: io::Error) -> Self { - Error { - depth: dent.depth, - inner: ErrorInner::Io { - path: Some(dent.path().to_path_buf()), - err: err, - }, - } - } - - fn from_io(depth: usize, err: io::Error) -> Self { - Error { - depth: depth, - inner: ErrorInner::Io { path: None, err: err }, - } - } -} - -impl error::Error for Error { - fn description(&self) -> &str { - match self.inner { - ErrorInner::Io { ref err, .. } => err.description(), - ErrorInner::Loop { .. } => "file system loop found", - } - } - - fn cause(&self) -> Option<&error::Error> { - match self.inner { - ErrorInner::Io { ref err, .. } => Some(err), - ErrorInner::Loop { .. } => None, - } - } -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.inner { - ErrorInner::Io { path: None, ref err } => { - err.fmt(f) - } - ErrorInner::Io { path: Some(ref path), ref err } => { - write!(f, "IO error for operation on {}: {}", - path.display(), err) - } - ErrorInner::Loop { ref ancestor, ref child } => { - write!(f, "File system loop found: \ - {} points to an ancestor {}", - child.display(), ancestor.display()) - } - } - } -} - -impl From<Error> for io::Error { - fn from(err: Error) -> io::Error { - match err { - Error { inner: ErrorInner::Io { err, .. }, .. } => err, - err @ Error { inner: ErrorInner::Loop { .. }, .. } => { - io::Error::new(io::ErrorKind::Other, err) - } - } - } -} diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/src/tests.rs cargo-0.26.0/vendor/walkdir-1.0.7/src/tests.rs --- cargo-0.25.0/vendor/walkdir-1.0.7/src/tests.rs 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/src/tests.rs 1970-01-01 00:00:00.000000000 +0000 @@ -1,742 +0,0 @@ -#![cfg_attr(windows, allow(dead_code, unused_imports))] - -use std::env; -use std::fs::{self, File}; -use std::io; -use std::path::{Path, PathBuf}; - -use quickcheck::{Arbitrary, Gen, QuickCheck, StdGen}; -use rand::{self, Rng}; - -use super::{DirEntry, WalkDir, WalkDirIterator, Iter, Error, ErrorInner}; - -#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] -enum Tree { - Dir(PathBuf, Vec<Tree>), - File(PathBuf), - Symlink { - src: PathBuf, - dst: PathBuf, - dir: bool, - } -} - -impl Tree { - fn from_walk_with<P, F>( - p: P, - f: F, - ) -> io::Result<Tree> - where P: AsRef<Path>, F: FnOnce(WalkDir) -> WalkDir { - let mut stack = vec![Tree::Dir(p.as_ref().to_path_buf(), vec![])]; - let it: WalkEventIter = f(WalkDir::new(p)).into(); - for ev in it { - match try!(ev) { - WalkEvent::Exit => { - let tree = stack.pop().unwrap(); - if stack.is_empty() { - return Ok(tree); - } - stack.last_mut().unwrap().children_mut().push(tree); - } - WalkEvent::Dir(dent) => { - stack.push(Tree::Dir(pb(dent.file_name()), vec![])); - } - WalkEvent::File(dent) => { - let node = if dent.file_type().is_symlink() { - let src = try!(dent.path().read_link()); - let dst = pb(dent.file_name()); - let dir = dent.path().is_dir(); - Tree::Symlink { src: src, dst: dst, dir: dir } - } else { - Tree::File(pb(dent.file_name())) - }; - stack.last_mut().unwrap().children_mut().push(node); - } - } - } - assert_eq!(stack.len(), 1); - Ok(stack.pop().unwrap()) - } - - fn name(&self) -> &Path { - match *self { - Tree::Dir(ref pb, _) => pb, - Tree::File(ref pb) => pb, - Tree::Symlink { ref dst, .. } => dst, - } - } - - fn unwrap_singleton(self) -> Tree { - match self { - Tree::File(_) | Tree::Symlink { .. } => { - panic!("cannot unwrap file or link as dir"); - } - Tree::Dir(_, mut childs) => { - assert_eq!(childs.len(), 1); - childs.pop().unwrap() - } - } - } - - fn unwrap_dir(self) -> Vec<Tree> { - match self { - Tree::File(_) | Tree::Symlink { .. } => { - panic!("cannot unwrap file as dir"); - } - Tree::Dir(_, childs) => childs, - } - } - - fn children_mut(&mut self) -> &mut Vec<Tree> { - match *self { - Tree::File(_) | Tree::Symlink { .. } => { - panic!("files do not have children"); - } - Tree::Dir(_, ref mut children) => children, - } - } - - fn create_in<P: AsRef<Path>>(&self, parent: P) -> io::Result<()> { - let parent = parent.as_ref(); - match *self { - Tree::Symlink { ref src, ref dst, dir } => { - if dir { - try!(soft_link_dir(src, parent.join(dst))); - } else { - try!(soft_link_file(src, parent.join(dst))); - } - } - Tree::File(ref p) => { try!(File::create(parent.join(p))); } - Tree::Dir(ref dir, ref children) => { - try!(fs::create_dir(parent.join(dir))); - for child in children { - try!(child.create_in(parent.join(dir))); - } - } - } - Ok(()) - } - - fn canonical(&self) -> Tree { - match *self { - Tree::Symlink { ref src, ref dst, dir } => { - Tree::Symlink { src: src.clone(), dst: dst.clone(), dir: dir } - } - Tree::File(ref p) => { - Tree::File(p.clone()) - } - Tree::Dir(ref p, ref cs) => { - let mut cs: Vec<Tree> = - cs.iter().map(|c| c.canonical()).collect(); - cs.sort(); - Tree::Dir(p.clone(), cs) - } - } - } - - fn dedup(&self) -> Tree { - match *self { - Tree::Symlink { ref src, ref dst, dir } => { - Tree::Symlink { src: src.clone(), dst: dst.clone(), dir: dir } - } - Tree::File(ref p) => { - Tree::File(p.clone()) - } - Tree::Dir(ref p, ref cs) => { - let mut nodupes: Vec<Tree> = vec![]; - for (i, c1) in cs.iter().enumerate() { - if !cs[i+1..].iter().any(|c2| c1.name() == c2.name()) - && !nodupes.iter().any(|c2| c1.name() == c2.name()) { - nodupes.push(c1.dedup()); - } - } - Tree::Dir(p.clone(), nodupes) - } - } - } - - fn gen<G: Gen>(g: &mut G, depth: usize) -> Tree { - #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] - struct NonEmptyAscii(String); - - impl Arbitrary for NonEmptyAscii { - fn arbitrary<G: Gen>(g: &mut G) -> NonEmptyAscii { - use std::char::from_u32; - let upper_bound = g.size(); - // We start with a lower bound of `4` to avoid - // generating the special file name `con` on Windows, - // because such files cannot exist... - let size = g.gen_range(4, upper_bound); - NonEmptyAscii((0..size) - .map(|_| from_u32(g.gen_range(97, 123)).unwrap()) - .collect()) - } - - fn shrink(&self) -> Box<Iterator<Item=NonEmptyAscii>> { - let mut smaller = vec![]; - for i in 1..self.0.len() { - let s: String = self.0.chars().skip(i).collect(); - smaller.push(NonEmptyAscii(s)); - } - Box::new(smaller.into_iter()) - } - } - - let name = pb(NonEmptyAscii::arbitrary(g).0); - if depth == 0 { - Tree::File(name) - } else { - let children: Vec<Tree> = - (0..g.gen_range(0, 5)) - .map(|_| Tree::gen(g, depth-1)) - .collect(); - Tree::Dir(name, children) - } - } -} - -impl Arbitrary for Tree { - fn arbitrary<G: Gen>(g: &mut G) -> Tree { - let depth = g.gen_range(0, 5); - Tree::gen(g, depth).dedup() - } - - fn shrink(&self) -> Box<Iterator<Item=Tree>> { - let trees: Box<Iterator<Item=Tree>> = match *self { - Tree::Symlink { .. } => unimplemented!(), - Tree::File(ref path) => { - let s = path.to_string_lossy().into_owned(); - Box::new(s.shrink().map(|s| Tree::File(pb(s)))) - } - Tree::Dir(ref path, ref children) => { - let s = path.to_string_lossy().into_owned(); - if children.is_empty() { - Box::new(s.shrink().map(|s| Tree::Dir(pb(s), vec![]))) - } else if children.len() == 1 { - let c = &children[0]; - Box::new(Some(c.clone()).into_iter().chain(c.shrink())) - } else { - Box::new(children - .shrink() - .map(move |cs| Tree::Dir(pb(s.clone()), cs))) - } - } - }; - Box::new(trees.map(|t| t.dedup())) - } -} - -#[derive(Debug)] -enum WalkEvent { - Dir(DirEntry), - File(DirEntry), - Exit, -} - -struct WalkEventIter { - depth: usize, - it: Iter, - next: Option<Result<DirEntry, Error>>, -} - -impl From<WalkDir> for WalkEventIter { - fn from(it: WalkDir) -> WalkEventIter { - WalkEventIter { depth: 0, it: it.into_iter(), next: None } - } -} - -impl Iterator for WalkEventIter { - type Item = io::Result<WalkEvent>; - - fn next(&mut self) -> Option<io::Result<WalkEvent>> { - let dent = self.next.take().or_else(|| self.it.next()); - let depth = match dent { - None => 0, - Some(Ok(ref dent)) => dent.depth(), - Some(Err(ref err)) => err.depth(), - }; - if depth < self.depth { - self.depth -= 1; - self.next = dent; - return Some(Ok(WalkEvent::Exit)); - } - self.depth = depth; - match dent { - None => None, - Some(Err(err)) => Some(Err(From::from(err))), - Some(Ok(dent)) => { - if dent.file_type().is_dir() { - self.depth += 1; - Some(Ok(WalkEvent::Dir(dent))) - } else { - Some(Ok(WalkEvent::File(dent))) - } - } - } - } -} - -struct TempDir(PathBuf); - -impl TempDir { - fn path<'a>(&'a self) -> &'a Path { - &self.0 - } -} - -impl Drop for TempDir { - fn drop(&mut self) { - fs::remove_dir_all(&self.0).unwrap(); - } -} - -fn tmpdir() -> TempDir { - let p = env::temp_dir(); - let mut r = rand::thread_rng(); - let ret = p.join(&format!("rust-{}", r.next_u32())); - fs::create_dir(&ret).unwrap(); - TempDir(ret) -} - -fn dir_setup_with<F>(t: &Tree, f: F) -> (TempDir, Tree) - where F: FnOnce(WalkDir) -> WalkDir { - let tmp = tmpdir(); - t.create_in(tmp.path()).unwrap(); - let got = Tree::from_walk_with(tmp.path(), f).unwrap(); - (tmp, got.unwrap_singleton().unwrap_singleton()) -} - -fn dir_setup(t: &Tree) -> (TempDir, Tree) { - dir_setup_with(t, |wd| wd) -} - -fn canon(unix: &str) -> String { - if cfg!(windows) { - unix.replace("/", "\\") - } else { - unix.to_string() - } -} - -fn pb<P: AsRef<Path>>(p: P) -> PathBuf { p.as_ref().to_path_buf() } -fn td<P: AsRef<Path>>(p: P, cs: Vec<Tree>) -> Tree { - Tree::Dir(pb(p), cs) -} -fn tf<P: AsRef<Path>>(p: P) -> Tree { - Tree::File(pb(p)) -} -fn tld<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> Tree { - Tree::Symlink { src: pb(src), dst: pb(dst), dir: true } -} -fn tlf<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> Tree { - Tree::Symlink { src: pb(src), dst: pb(dst), dir: false } -} - -#[cfg(unix)] -fn soft_link_dir<P: AsRef<Path>, Q: AsRef<Path>>( - src: P, - dst: Q, -) -> io::Result<()> { - use std::os::unix::fs::symlink; - symlink(src, dst) -} - -#[cfg(unix)] -fn soft_link_file<P: AsRef<Path>, Q: AsRef<Path>>( - src: P, - dst: Q, -) -> io::Result<()> { - soft_link_dir(src, dst) -} - -#[cfg(windows)] -fn soft_link_dir<P: AsRef<Path>, Q: AsRef<Path>>( - src: P, - dst: Q, -) -> io::Result<()> { - use std::os::windows::fs::symlink_dir; - symlink_dir(src, dst) -} - -#[cfg(windows)] -fn soft_link_file<P: AsRef<Path>, Q: AsRef<Path>>( - src: P, - dst: Q, -) -> io::Result<()> { - use std::os::windows::fs::symlink_file; - symlink_file(src, dst) -} - -macro_rules! assert_tree_eq { - ($e1:expr, $e2:expr) => { - assert_eq!($e1.canonical(), $e2.canonical()); - } -} - -#[test] -fn walk_dir_1() { - let exp = td("foo", vec![]); - let (_tmp, got) = dir_setup(&exp); - assert_tree_eq!(exp, got); -} - -#[test] -fn walk_dir_2() { - let exp = tf("foo"); - let (_tmp, got) = dir_setup(&exp); - assert_tree_eq!(exp, got); -} - -#[test] -fn walk_dir_3() { - let exp = td("foo", vec![tf("bar")]); - let (_tmp, got) = dir_setup(&exp); - assert_tree_eq!(exp, got); -} - -#[test] -fn walk_dir_4() { - let exp = td("foo", vec![tf("foo"), tf("bar"), tf("baz")]); - let (_tmp, got) = dir_setup(&exp); - assert_tree_eq!(exp, got); -} - -#[test] -fn walk_dir_5() { - let exp = td("foo", vec![td("bar", vec![])]); - let (_tmp, got) = dir_setup(&exp); - assert_tree_eq!(exp, got); -} - -#[test] -fn walk_dir_6() { - let exp = td("foo", vec![ - td("bar", vec![ - tf("baz"), td("bat", vec![]), - ]), - ]); - let (_tmp, got) = dir_setup(&exp); - assert_tree_eq!(exp, got); -} - -#[test] -fn walk_dir_7() { - let exp = td("foo", vec![ - td("bar", vec![ - tf("baz"), td("bat", vec![]), - ]), - td("a", vec![tf("b"), tf("c"), tf("d")]), - ]); - let (_tmp, got) = dir_setup(&exp); - assert_tree_eq!(exp, got); -} - -#[test] -fn walk_dir_sym_1() { - let exp = td("foo", vec![tf("bar"), tlf("bar", "baz")]); - let (_tmp, got) = dir_setup(&exp); - assert_tree_eq!(exp, got); -} - -#[test] -fn walk_dir_sym_2() { - let exp = td("foo", vec![ - td("a", vec![tf("a1"), tf("a2")]), - tld("a", "alink"), - ]); - let (_tmp, got) = dir_setup(&exp); - assert_tree_eq!(exp, got); -} - -#[test] -fn walk_dir_sym_root() { - let exp = td("foo", vec![ - td("bar", vec![tf("a"), tf("b")]), - tld("bar", "alink"), - ]); - let tmp = tmpdir(); - let tmp_path = tmp.path(); - let tmp_len = tmp_path.to_str().unwrap().len(); - exp.create_in(tmp_path).unwrap(); - - let it = WalkDir::new(tmp_path.join("foo").join("alink")).into_iter(); - let mut got = it - .map(|d| d.unwrap().path().to_str().unwrap()[tmp_len+1..].into()) - .collect::<Vec<String>>(); - got.sort(); - assert_eq!(got, vec![ - canon("foo/alink"), canon("foo/alink/a"), canon("foo/alink/b"), - ]); - - let it = WalkDir::new(tmp_path.join("foo/alink/")).into_iter(); - let mut got = it - .map(|d| d.unwrap().path().to_str().unwrap()[tmp_len+1..].into()) - .collect::<Vec<String>>(); - got.sort(); - assert_eq!(got, vec!["foo/alink/", "foo/alink/a", "foo/alink/b"]); -} - -#[test] -#[cfg(unix)] -fn walk_dir_sym_detect_no_follow_no_loop() { - let exp = td("foo", vec![ - td("a", vec![tf("a1"), tf("a2")]), - td("b", vec![tld("../a", "alink")]), - ]); - let (_tmp, got) = dir_setup(&exp); - assert_tree_eq!(exp, got); -} - -#[test] -#[cfg(unix)] -fn walk_dir_sym_follow_dir() { - let actual = td("foo", vec![ - td("a", vec![tf("a1"), tf("a2")]), - td("b", vec![tld("../a", "alink")]), - ]); - let followed = td("foo", vec![ - td("a", vec![tf("a1"), tf("a2")]), - td("b", vec![td("alink", vec![tf("a1"), tf("a2")])]), - ]); - let (_tmp, got) = dir_setup_with(&actual, |wd| wd.follow_links(true)); - assert_tree_eq!(followed, got); -} - -#[test] -#[cfg(unix)] -fn walk_dir_sym_detect_loop() { - let actual = td("foo", vec![ - td("a", vec![tlf("../b", "blink"), tf("a1"), tf("a2")]), - td("b", vec![tlf("../a", "alink")]), - ]); - let tmp = tmpdir(); - actual.create_in(tmp.path()).unwrap(); - let got = WalkDir::new(tmp.path()) - .follow_links(true) - .into_iter() - .collect::<Result<Vec<_>, _>>(); - match got { - Ok(x) => panic!("expected loop error, got no error: {:?}", x), - Err(err @ Error { inner: ErrorInner::Io { .. }, .. }) => { - panic!("expected loop error, got generic IO error: {:?}", err); - } - Err(Error { inner: ErrorInner::Loop { .. }, .. }) => {} - } -} - -#[test] -fn walk_dir_sym_infinite() { - let actual = tlf("a", "a"); - let tmp = tmpdir(); - actual.create_in(tmp.path()).unwrap(); - let got = WalkDir::new(tmp.path()) - .follow_links(true) - .into_iter() - .collect::<Result<Vec<_>, _>>(); - match got { - Ok(x) => panic!("expected IO error, got no error: {:?}", x), - Err(Error { inner: ErrorInner::Loop { .. }, .. }) => { - panic!("expected IO error, but got loop error"); - } - Err(Error { inner: ErrorInner::Io { .. }, .. }) => {} - } -} - -#[test] -fn walk_dir_min_depth_1() { - let exp = td("foo", vec![tf("bar")]); - let (_tmp, got) = dir_setup_with(&exp, |wd| wd.min_depth(1)); - assert_tree_eq!(tf("bar"), got); -} - -#[test] -fn walk_dir_min_depth_2() { - let exp = td("foo", vec![tf("bar"), tf("baz")]); - let tmp = tmpdir(); - exp.create_in(tmp.path()).unwrap(); - let got = Tree::from_walk_with(tmp.path(), |wd| wd.min_depth(2)) - .unwrap().unwrap_dir(); - assert_tree_eq!(exp, td("foo", got)); -} - -#[test] -fn walk_dir_min_depth_3() { - let exp = td("foo", vec![ - tf("bar"), - td("abc", vec![tf("xyz")]), - tf("baz"), - ]); - let tmp = tmpdir(); - exp.create_in(tmp.path()).unwrap(); - let got = Tree::from_walk_with(tmp.path(), |wd| wd.min_depth(3)) - .unwrap().unwrap_dir(); - assert_eq!(vec![tf("xyz")], got); -} - -#[test] -fn walk_dir_max_depth_1() { - let exp = td("foo", vec![tf("bar")]); - let (_tmp, got) = dir_setup_with(&exp, |wd| wd.max_depth(1)); - assert_tree_eq!(td("foo", vec![]), got); -} - -#[test] -fn walk_dir_max_depth_2() { - let exp = td("foo", vec![tf("bar"), tf("baz")]); - let (_tmp, got) = dir_setup_with(&exp, |wd| wd.max_depth(1)); - assert_tree_eq!(td("foo", vec![]), got); -} - -#[test] -fn walk_dir_max_depth_3() { - let exp = td("foo", vec![ - tf("bar"), - td("abc", vec![tf("xyz")]), - tf("baz"), - ]); - let exp_trimmed = td("foo", vec![ - tf("bar"), - td("abc", vec![]), - tf("baz"), - ]); - let (_tmp, got) = dir_setup_with(&exp, |wd| wd.max_depth(2)); - assert_tree_eq!(exp_trimmed, got); -} - -#[test] -fn walk_dir_min_max_depth() { - let exp = td("foo", vec![ - tf("bar"), - td("abc", vec![tf("xyz")]), - tf("baz"), - ]); - let tmp = tmpdir(); - exp.create_in(tmp.path()).unwrap(); - let got = Tree::from_walk_with(tmp.path(), - |wd| wd.min_depth(2).max_depth(2)) - .unwrap().unwrap_dir(); - assert_tree_eq!( - td("foo", vec![tf("bar"), td("abc", vec![]), tf("baz")]), - td("foo", got)); -} - -#[test] -fn walk_dir_skip() { - let exp = td("foo", vec![ - tf("bar"), - td("abc", vec![tf("xyz")]), - tf("baz"), - ]); - let tmp = tmpdir(); - exp.create_in(tmp.path()).unwrap(); - let mut got = vec![]; - let mut it = WalkDir::new(tmp.path()).min_depth(1).into_iter(); - loop { - let dent = match it.next().map(|x| x.unwrap()) { - None => break, - Some(dent) => dent, - }; - let name = dent.file_name().to_str().unwrap().to_owned(); - if name == "abc" { - it.skip_current_dir(); - } - got.push(name); - } - got.sort(); - assert_eq!(got, vec!["abc", "bar", "baz", "foo"]); // missing xyz! -} - -#[test] -fn walk_dir_filter() { - let exp = td("foo", vec![ - tf("bar"), - td("abc", vec![tf("fit")]), - tf("faz"), - ]); - let tmp = tmpdir(); - let tmp_path = tmp.path().to_path_buf(); - exp.create_in(tmp.path()).unwrap(); - let it = WalkDir::new(tmp.path()).min_depth(1) - .into_iter() - .filter_entry(move |d| { - let n = d.file_name().to_string_lossy().into_owned(); - !d.file_type().is_dir() - || n.starts_with("f") - || d.path() == &*tmp_path - }); - let mut got = it.map(|d| d.unwrap().file_name().to_str().unwrap().into()) - .collect::<Vec<String>>(); - got.sort(); - assert_eq!(got, vec!["bar", "faz", "foo"]); -} - -#[test] -fn qc_roundtrip() { - fn p(exp: Tree) -> bool { - let (_tmp, got) = dir_setup(&exp); - exp.canonical() == got.canonical() - } - QuickCheck::new() - .gen(StdGen::new(rand::thread_rng(), 15)) - .tests(1_000) - .max_tests(10_000) - .quickcheck(p as fn(Tree) -> bool); -} - -// Same as `qc_roundtrip`, but makes sure `follow_links` doesn't change -// the behavior of walking a directory *without* symlinks. -#[test] -fn qc_roundtrip_no_symlinks_with_follow() { - fn p(exp: Tree) -> bool { - let (_tmp, got) = dir_setup_with(&exp, |wd| wd.follow_links(true)); - exp.canonical() == got.canonical() - } - QuickCheck::new() - .gen(StdGen::new(rand::thread_rng(), 15)) - .tests(1_000) - .max_tests(10_000) - .quickcheck(p as fn(Tree) -> bool); -} - -#[test] -fn walk_dir_sort() { - let exp = td("foo", vec![ - tf("bar"), - td("abc", vec![tf("fit")]), - tf("faz"), - ]); - let tmp = tmpdir(); - let tmp_path = tmp.path(); - let tmp_len = tmp_path.to_str().unwrap().len(); - exp.create_in(tmp_path).unwrap(); - let it = WalkDir::new(tmp_path).sort_by(|a,b| a.cmp(b)).into_iter(); - let got = it.map(|d| { - let path = d.unwrap(); - let path = &path.path().to_str().unwrap()[tmp_len..]; - path.replace("\\", "/") - }).collect::<Vec<String>>(); - assert_eq!(got, - ["", "/foo", "/foo/abc", "/foo/abc/fit", "/foo/bar", "/foo/faz"]); -} - -#[test] -fn walk_dir_sort_small_fd_max() { - let exp = td("foo", vec![ - tf("bar"), - td("abc", vec![tf("fit")]), - tf("faz"), - ]); - let tmp = tmpdir(); - let tmp_path = tmp.path(); - let tmp_len = tmp_path.to_str().unwrap().len(); - exp.create_in(tmp_path).unwrap(); - let it = - WalkDir::new(tmp_path).max_open(1).sort_by(|a,b| a.cmp(b)).into_iter(); - let got = it.map(|d| { - let path = d.unwrap(); - let path = &path.path().to_str().unwrap()[tmp_len..]; - path.replace("\\", "/") - }).collect::<Vec<String>>(); - assert_eq!(got, - ["", "/foo", "/foo/abc", "/foo/abc/fit", "/foo/bar", "/foo/faz"]); -} diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/.travis.yml cargo-0.26.0/vendor/walkdir-1.0.7/.travis.yml --- cargo-0.25.0/vendor/walkdir-1.0.7/.travis.yml 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/.travis.yml 1970-01-01 00:00:00.000000000 +0000 @@ -1,13 +0,0 @@ -language: rust -rust: - - 1.10.0 - - stable - - beta - - nightly -script: - - cargo build --verbose - - cargo test --verbose - - cargo doc -branches: - only: - - master diff -Nru cargo-0.25.0/vendor/walkdir-1.0.7/UNLICENSE cargo-0.26.0/vendor/walkdir-1.0.7/UNLICENSE --- cargo-0.25.0/vendor/walkdir-1.0.7/UNLICENSE 2018-02-24 07:18:18.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-1.0.7/UNLICENSE 1970-01-01 00:00:00.000000000 +0000 @@ -1,24 +0,0 @@ -This is free and unencumbered software released into the public domain. - -Anyone is free to copy, modify, publish, use, compile, sell, or -distribute this software, either in source code form or as a compiled -binary, for any purpose, commercial or non-commercial, and by any -means. - -In jurisdictions that recognize copyright laws, the author or authors -of this software dedicate any and all copyright interest in the -software to the public domain. We make this dedication for the benefit -of the public at large and to the detriment of our heirs and -successors. We intend this dedication to be an overt act of -relinquishment in perpetuity of all present and future rights to this -software under copyright law. - -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 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. - -For more information, please refer to <http://unlicense.org/> diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/appveyor.yml cargo-0.26.0/vendor/walkdir-2.1.4/appveyor.yml --- cargo-0.25.0/vendor/walkdir-2.1.4/appveyor.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/appveyor.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,23 @@ +environment: + matrix: + - TARGET: x86_64-pc-windows-msvc + - TARGET: i686-pc-windows-msvc + - TARGET: i686-pc-windows-gnu + +install: + - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" + - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" + - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin + - SET PATH=%PATH%;C:\MinGW\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo build --verbose + - cargo test --verbose + +branches: + only: + - master diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/.cargo-checksum.json cargo-0.26.0/vendor/walkdir-2.1.4/.cargo-checksum.json --- cargo-0.25.0/vendor/walkdir-2.1.4/.cargo-checksum.json 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/.cargo-checksum.json 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +{"files":{},"package":"63636bd0eb3d00ccb8b9036381b526efac53caf112b7783b730ab3f8e44da369"} \ No newline at end of file diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/Cargo.toml cargo-0.26.0/vendor/walkdir-2.1.4/Cargo.toml --- cargo-0.25.0/vendor/walkdir-2.1.4/Cargo.toml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/Cargo.toml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,49 @@ +# 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 believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +name = "walkdir" +version = "2.1.4" +authors = ["Andrew Gallant <jamslam@gmail.com>"] +description = "Recursively walk a directory." +homepage = "https://github.com/BurntSushi/walkdir" +documentation = "https://docs.rs/walkdir/" +readme = "README.md" +keywords = ["directory", "recursive", "walk", "iterator"] +categories = ["filesystem"] +license = "Unlicense/MIT" +repository = "https://github.com/BurntSushi/walkdir" +[dependencies.same-file] +version = "1" +[dev-dependencies.docopt] +version = "0.8" + +[dev-dependencies.quickcheck] +version = "0.6" +default-features = false + +[dev-dependencies.rand] +version = "0.4" + +[dev-dependencies.serde] +version = "1" + +[dev-dependencies.serde_derive] +version = "1" +[target."cfg(windows)".dependencies.winapi] +version = "0.3" +features = ["std", "winnt"] +[badges.appveyor] +repository = "BurntSushi/walkdir" + +[badges.travis-ci] +repository = "BurntSushi/walkdir" diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/compare/nftw.c cargo-0.26.0/vendor/walkdir-2.1.4/compare/nftw.c --- cargo-0.25.0/vendor/walkdir-2.1.4/compare/nftw.c 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/compare/nftw.c 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,25 @@ +#define _XOPEN_SOURCE 500 +#include <ftw.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <stdint.h> + +static int +display_info(const char *fpath, const struct stat *sb, + int tflag, struct FTW *ftwbuf) +{ + printf("%s\n", fpath); + return 0; +} + +int +main(int argc, char *argv[]) +{ + int flags = FTW_PHYS; + if (nftw((argc < 2) ? "." : argv[1], display_info, 20, flags) == -1) { + perror("nftw"); + exit(EXIT_FAILURE); + } + exit(EXIT_SUCCESS); +} diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/compare/walk.py cargo-0.26.0/vendor/walkdir-2.1.4/compare/walk.py --- cargo-0.25.0/vendor/walkdir-2.1.4/compare/walk.py 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/compare/walk.py 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,10 @@ +from __future__ import absolute_import, division, print_function + +import os +import sys + +for dirpath, dirnames, filenames in os.walk(sys.argv[1]): + for n in dirnames: + print(os.path.join(dirpath, n)) + for n in filenames: + print(os.path.join(dirpath, n)) diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/COPYING cargo-0.26.0/vendor/walkdir-2.1.4/COPYING --- cargo-0.25.0/vendor/walkdir-2.1.4/COPYING 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/COPYING 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,3 @@ +This project is dual-licensed under the Unlicense and MIT licenses. + +You may use this code under the terms of either license. diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/ctags.rust cargo-0.26.0/vendor/walkdir-2.1.4/ctags.rust --- cargo-0.25.0/vendor/walkdir-2.1.4/ctags.rust 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/ctags.rust 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,11 @@ +--langdef=Rust +--langmap=Rust:.rs +--regex-Rust=/^[ \t]*(#\[[^\]]\][ \t]*)*(pub[ \t]+)?(extern[ \t]+)?("[^"]+"[ \t]+)?(unsafe[ \t]+)?fn[ \t]+([a-zA-Z0-9_]+)/\6/f,functions,function definitions/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?type[ \t]+([a-zA-Z0-9_]+)/\2/T,types,type definitions/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?enum[ \t]+([a-zA-Z0-9_]+)/\2/g,enum,enumeration names/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?struct[ \t]+([a-zA-Z0-9_]+)/\2/s,structure names/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?mod[ \t]+([a-zA-Z0-9_]+)/\2/m,modules,module names/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?static[ \t]+([a-zA-Z0-9_]+)/\2/c,consts,static constants/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?trait[ \t]+([a-zA-Z0-9_]+)/\2/t,traits,traits/ +--regex-Rust=/^[ \t]*(pub[ \t]+)?impl([ \t\n]+<.*>)?[ \t]+([a-zA-Z0-9_]+)/\3/i,impls,trait implementations/ +--regex-Rust=/^[ \t]*macro_rules![ \t]+([a-zA-Z0-9_]+)/\1/d,macros,macro definitions/ diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/examples/walkdir.rs cargo-0.26.0/vendor/walkdir-2.1.4/examples/walkdir.rs --- cargo-0.25.0/vendor/walkdir-2.1.4/examples/walkdir.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/examples/walkdir.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,99 @@ +extern crate docopt; +extern crate serde; +#[macro_use] +extern crate serde_derive; +extern crate walkdir; + +use std::io::{self, Write}; + +use docopt::Docopt; +use walkdir::WalkDir; + +const USAGE: &'static str = " +Usage: + walkdir [options] [<dir>] + +Options: + -h, --help + -L, --follow-links Follow symlinks. + --min-depth NUM Minimum depth. + --max-depth NUM Maximum depth. + -n, --fd-max NUM Maximum open file descriptors. [default: 32] + --tree Show output as a tree. + --sort Sort the output. + -q, --ignore-errors Ignore errors. + -d, --depth Show directory's contents before the directory itself. +"; + +#[derive(Debug, Deserialize)] +#[allow(dead_code)] +struct Args { + arg_dir: Option<String>, + flag_follow_links: bool, + flag_min_depth: Option<usize>, + flag_max_depth: Option<usize>, + flag_fd_max: usize, + flag_tree: bool, + flag_ignore_errors: bool, + flag_sort: bool, + flag_depth: bool, +} + +macro_rules! wout { ($($tt:tt)*) => { {writeln!($($tt)*)}.unwrap() } } + +fn main() { + let args: Args = Docopt::new(USAGE) + .and_then(|d| d.deserialize()) + .unwrap_or_else(|e| e.exit()); + let mind = args.flag_min_depth.unwrap_or(0); + let maxd = args.flag_max_depth.unwrap_or(::std::usize::MAX); + let dir = args.arg_dir.clone().unwrap_or(".".to_owned()); + let mut walkdir = WalkDir::new(dir) + .max_open(args.flag_fd_max) + .follow_links(args.flag_follow_links) + .min_depth(mind) + .max_depth(maxd); + if args.flag_sort { + walkdir = walkdir.sort_by(|a,b| a.file_name().cmp(b.file_name())); + } + if args.flag_depth { + walkdir = walkdir.contents_first(true) + } + let it = walkdir.into_iter(); + let mut out = io::BufWriter::new(io::stdout()); + let mut eout = io::stderr(); + if args.flag_tree { + for dent in it { + match dent { + Err(err) => { + out.flush().unwrap(); + wout!(eout, "ERROR: {}", err); + } + Ok(dent) => { + let name = dent.file_name().to_string_lossy(); + wout!(out, "{}{}", indent(dent.depth()), name); + } + } + } + } else if args.flag_ignore_errors { + for dent in it.filter_map(|e| e.ok()) { + wout!(out, "{}", dent.path().display()); + } + } else { + for dent in it { + match dent { + Err(err) => { + out.flush().unwrap(); + wout!(eout, "ERROR: {}", err); + } + Ok(dent) => { + wout!(out, "{}", dent.path().display()); + } + } + } + } +} + +fn indent(depth: usize) -> String { + ::std::iter::repeat(' ').take(2 * depth).collect() +} diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/LICENSE-MIT cargo-0.26.0/vendor/walkdir-2.1.4/LICENSE-MIT --- cargo-0.25.0/vendor/walkdir-2.1.4/LICENSE-MIT 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/LICENSE-MIT 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Andrew Gallant + +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. diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/Makefile cargo-0.26.0/vendor/walkdir-2.1.4/Makefile --- cargo-0.25.0/vendor/walkdir-2.1.4/Makefile 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/Makefile 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,14 @@ +all: + echo Nothing to do... + +ctags: + ctags --recurse --options=ctags.rust --languages=Rust + +docs: + cargo doc + in-dir ./target/doc fix-perms + rscp ./target/doc/* gopher:~/www/burntsushi.net/rustdoc/ + +push: + git push origin master + git push github master diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/README.md cargo-0.26.0/vendor/walkdir-2.1.4/README.md --- cargo-0.25.0/vendor/walkdir-2.1.4/README.md 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/README.md 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,140 @@ +walkdir +======= +A cross platform Rust library for efficiently walking a directory recursively. +Comes with support for following symbolic links, controlling the number of +open file descriptors and efficient mechanisms for pruning the entries in the +directory tree. + +[![Linux build status](https://api.travis-ci.org/BurntSushi/walkdir.svg)](https://travis-ci.org/BurntSushi/walkdir) +[![Windows build status](https://ci.appveyor.com/api/projects/status/github/BurntSushi/walkdir?svg=true)](https://ci.appveyor.com/project/BurntSushi/walkdir) +[![](http://meritbadge.herokuapp.com/walkdir)](https://crates.io/crates/walkdir) + +Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org). + +### Documentation + +[docs.rs/walkdir](https://docs.rs/walkdir/) + +### Usage + +To use this crate, add `walkdir` as a dependency to your project's +`Cargo.toml`: + +``` +[dependencies] +walkdir = "2" +``` + +### Example + +The following code recursively iterates over the directory given and prints +the path for each entry: + +```rust,no_run +use walkdir::WalkDir; + +for entry in WalkDir::new("foo") { + let entry = entry.unwrap(); + println!("{}", entry.path().display()); +} +``` + +Or, if you'd like to iterate over all entries and ignore any errors that may +arise, use `filter_map`. (e.g., This code below will silently skip directories +that the owner of the running process does not have permission to access.) + +```rust,no_run +use walkdir::WalkDir; + +for entry in WalkDir::new("foo").into_iter().filter_map(|e| e.ok()) { + println!("{}", entry.path().display()); +} +``` + +### Example: follow symbolic links + +The same code as above, except `follow_links` is enabled: + +```rust,no_run +use walkdir::WalkDir; + +for entry in WalkDir::new("foo").follow_links(true) { + let entry = entry.unwrap(); + println!("{}", entry.path().display()); +} +``` + +### Example: skip hidden files and directories efficiently on unix + +This uses the `filter_entry` iterator adapter to avoid yielding hidden files +and directories efficiently: + +```rust,no_run +use walkdir::{DirEntry, WalkDir}; + +fn is_hidden(entry: &DirEntry) -> bool { + entry.file_name() + .to_str() + .map(|s| s.starts_with(".")) + .unwrap_or(false) +} + +let walker = WalkDir::new("foo").into_iter(); +for entry in walker.filter_entry(|e| !is_hidden(e)) { + let entry = entry.unwrap(); + println!("{}", entry.path().display()); +} +``` + +### Motivation + +`std::fs` has an unstable `walk_dir` implementation that needed some design +work. I started off on that task, but it quickly became apparent that walking +a directory recursively is quite complex and may not be a good fit for `std` +right away. + +This should at least resolve most or all of the issues reported here (and then +some): + +* https://github.com/rust-lang/rust/issues/27707 +* https://github.com/rust-lang/rust/issues/23715 + +### Performance + +The short story is that performance is comparable with `find` and glibc's +`nftw` on both a warm and cold file cache. In fact, I cannot observe any +performance difference after running `find /`, `walkdir /` and `nftw /` on my +local file system (SSD, ~3 million entries). More precisely, I am reasonably +confident that this crate makes as few system calls and close to as few +allocations as possible. + +I haven't recorded any benchmarks, but here are some things you can try with a +local checkout of `walkdir`: + +``` +# The directory you want to recursively walk: +DIR=$HOME + +# If you want to observe perf on a cold file cache, run this before *each* +# command: +sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches' + +# To warm the caches +find $DIR + +# Test speed of `find` on warm cache: +time find $DIR + +# Compile and test speed of `walkdir` crate: +cargo build --release --example walkdir +time ./target/release/examples/walkdir $DIR + +# Compile and test speed of glibc's `nftw`: +gcc -O3 -o nftw ./compare/nftw.c +time ./nftw $DIR + +# For shits and giggles, test speed of Python's (2 or 3) os.walk: +time python ./compare/walk.py $DIR +``` + +On my system, the performance of `walkdir`, `find` and `nftw` is comparable. diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/session.vim cargo-0.26.0/vendor/walkdir-2.1.4/session.vim --- cargo-0.25.0/vendor/walkdir-2.1.4/session.vim 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/session.vim 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1 @@ +au BufWritePost *.rs silent!make ctags > /dev/null 2>&1 diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/src/lib.rs cargo-0.26.0/vendor/walkdir-2.1.4/src/lib.rs --- cargo-0.25.0/vendor/walkdir-2.1.4/src/lib.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/src/lib.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,1600 @@ +/*! +Crate `walkdir` provides an efficient and cross platform implementation +of recursive directory traversal. Several options are exposed to control +iteration, such as whether to follow symbolic links (default off), limit the +maximum number of simultaneous open file descriptors and the ability to +efficiently skip descending into directories. + +To use this crate, add `walkdir` as a dependency to your project's +`Cargo.toml`: + +```text +[dependencies] +walkdir = "2" +``` + +# From the top + +The [`WalkDir`] type builds iterators. The [`DirEntry`] type describes values +yielded by the iterator. Finally, the [`Error`] type is a small wrapper around +[`std::io::Error`] with additional information, such as if a loop was detected +while following symbolic links (not enabled by default). + +[`WalkDir`]: struct.WalkDir.html +[`DirEntry`]: struct.DirEntry.html +[`Error`]: struct.Error.html +[`std::io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html + +# Example + +The following code recursively iterates over the directory given and prints +the path for each entry: + +```no_run +use walkdir::WalkDir; +# use walkdir::Error; + +# fn try_main() -> Result<(), Error> { +for entry in WalkDir::new("foo") { + println!("{}", entry?.path().display()); +} +# Ok(()) +# } +``` + +Or, if you'd like to iterate over all entries and ignore any errors that +may arise, use [`filter_map`]. (e.g., This code below will silently skip +directories that the owner of the running process does not have permission to +access.) + +```no_run +use walkdir::WalkDir; + +for entry in WalkDir::new("foo").into_iter().filter_map(|e| e.ok()) { + println!("{}", entry.path().display()); +} +``` + +[`filter_map`]: https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.filter_map + +# Example: follow symbolic links + +The same code as above, except [`follow_links`] is enabled: + +```no_run +use walkdir::WalkDir; +# use walkdir::Error; + +# fn try_main() -> Result<(), Error> { +for entry in WalkDir::new("foo").follow_links(true) { + println!("{}", entry?.path().display()); +} +# Ok(()) +# } +``` + +[`follow_links`]: struct.WalkDir.html#method.follow_links + +# Example: skip hidden files and directories on unix + +This uses the [`filter_entry`] iterator adapter to avoid yielding hidden files +and directories efficiently (i.e. without recursing into hidden directories): + +```no_run +use walkdir::{DirEntry, WalkDir}; +# use walkdir::Error; + +fn is_hidden(entry: &DirEntry) -> bool { + entry.file_name() + .to_str() + .map(|s| s.starts_with(".")) + .unwrap_or(false) +} + +# fn try_main() -> Result<(), Error> { +let walker = WalkDir::new("foo").into_iter(); +for entry in walker.filter_entry(|e| !is_hidden(e)) { + println!("{}", entry?.path().display()); +} +# Ok(()) +# } +``` + +[`filter_entry`]: struct.IntoIter.html#method.filter_entry +*/ + +#![doc(html_root_url = "https://docs.rs/walkdir/2.0.0")] +#![deny(missing_docs)] + +#[cfg(test)] +extern crate quickcheck; +#[cfg(test)] +extern crate rand; +extern crate same_file; +#[cfg(windows)] +extern crate winapi; + +use std::cmp::{Ordering, min}; +use std::error; +use std::fmt; +use std::fs::{self, FileType, ReadDir}; +use std::io; +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; +use std::result; +use std::vec; + +use same_file::Handle; + +#[cfg(unix)] +pub use unix::DirEntryExt; + +#[cfg(test)] +mod tests; +#[cfg(unix)] +mod unix; + +/// Like try, but for iterators that return [`Option<Result<_, _>>`]. +/// +/// [`Option<Result<_, _>>`]: https://doc.rust-lang.org/stable/std/option/enum.Option.html +macro_rules! itry { + ($e:expr) => { + match $e { + Ok(v) => v, + Err(err) => return Some(Err(From::from(err))), + } + } +} + +/// A result type for walkdir operations. +/// +/// Note that this result type embeds the error type in this crate. This +/// is only useful if you care about the additional information provided by +/// the error (such as the path associated with the error or whether a loop +/// was dectected). If you want things to Just Work, then you can use +/// [`io::Result`] instead since the error type in this package will +/// automatically convert to an [`io::Result`] when using the [`try!`] macro. +/// +/// [`io::Result`]: https://doc.rust-lang.org/stable/std/io/type.Result.html +/// [`try!`]: https://doc.rust-lang.org/stable/std/macro.try.html +pub type Result<T> = ::std::result::Result<T, Error>; + +/// A builder to create an iterator for recursively walking a directory. +/// +/// Results are returned in depth first fashion, with directories yielded +/// before their contents. If [`contents_first`] is true, contents are yielded +/// before their directories. The order is unspecified but if [`sort_by`] is +/// given, directory entries are sorted according to this function. Directory +/// entries `.` and `..` are always omitted. +/// +/// If an error occurs at any point during iteration, then it is returned in +/// place of its corresponding directory entry and iteration continues as +/// normal. If an error occurs while opening a directory for reading, then it +/// is not descended into (but the error is still yielded by the iterator). +/// Iteration may be stopped at any time. When the iterator is destroyed, all +/// resources associated with it are freed. +/// +/// [`contents_first`]: struct.WalkDir.html#method.contents_first +/// [`sort_by`]: struct.WalkDir.html#method.sort_by +/// +/// # Usage +/// +/// This type implements [`IntoIterator`] so that it may be used as the subject +/// of a `for` loop. You may need to call [`into_iter`] explicitly if you want +/// to use iterator adapters such as [`filter_entry`]. +/// +/// Idiomatic use of this type should use method chaining to set desired +/// options. For example, this only shows entries with a depth of `1`, `2` or +/// `3` (relative to `foo`): +/// +/// ```no_run +/// use walkdir::WalkDir; +/// # use walkdir::Error; +/// +/// # fn try_main() -> Result<(), Error> { +/// for entry in WalkDir::new("foo").min_depth(1).max_depth(3) { +/// println!("{}", entry?.path().display()); +/// } +/// # Ok(()) +/// # } +/// ``` +/// +/// [`IntoIterator`]: https://doc.rust-lang.org/stable/std/iter/trait.IntoIterator.html +/// [`into_iter`]: https://doc.rust-lang.org/nightly/core/iter/trait.IntoIterator.html#tymethod.into_iter +/// [`filter_entry`]: struct.IntoIter.html#method.filter_entry +/// +/// Note that the iterator by default includes the top-most directory. Since +/// this is the only directory yielded with depth `0`, it is easy to ignore it +/// with the [`min_depth`] setting: +/// +/// ```no_run +/// use walkdir::WalkDir; +/// # use walkdir::Error; +/// +/// # fn try_main() -> Result<(), Error> { +/// for entry in WalkDir::new("foo").min_depth(1) { +/// println!("{}", entry?.path().display()); +/// } +/// # Ok(()) +/// # } +/// ``` +/// +/// [`min_depth`]: struct.WalkDir.html#method.min_depth +/// +/// This will only return descendents of the `foo` directory and not `foo` +/// itself. +/// +/// # Loops +/// +/// This iterator (like most/all recursive directory iterators) assumes that +/// no loops can be made with *hard* links on your file system. In particular, +/// this would require creating a hard link to a directory such that it creates +/// a loop. On most platforms, this operation is illegal. +/// +/// Note that when following symbolic/soft links, loops are detected and an +/// error is reported. +#[derive(Debug)] +pub struct WalkDir { + opts: WalkDirOptions, + root: PathBuf, +} + +struct WalkDirOptions { + follow_links: bool, + max_open: usize, + min_depth: usize, + max_depth: usize, + sorter: Option<Box< + FnMut(&DirEntry,&DirEntry) -> Ordering + Send + Sync + 'static + >>, + contents_first: bool, +} + +impl fmt::Debug for WalkDirOptions { + fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> { + let sorter_str = if self.sorter.is_some() { + // FnMut isn't `Debug` + "Some(...)" + } else { + "None" + }; + f.debug_struct("WalkDirOptions") + .field("follow_links", &self.follow_links) + .field("max_open", &self.max_open) + .field("min_depth", &self.min_depth) + .field("max_depth", &self.max_depth) + .field("sorter", &sorter_str) + .field("contents_first", &self.contents_first) + .finish() + } +} + +impl WalkDir { + /// Create a builder for a recursive directory iterator starting at the + /// file path `root`. If `root` is a directory, then it is the first item + /// yielded by the iterator. If `root` is a file, then it is the first + /// and only item yielded by the iterator. If `root` is a symlink, then it + /// is always followed. + pub fn new<P: AsRef<Path>>(root: P) -> Self { + WalkDir { + opts: WalkDirOptions { + follow_links: false, + max_open: 10, + min_depth: 0, + max_depth: ::std::usize::MAX, + sorter: None, + contents_first: false, + }, + root: root.as_ref().to_path_buf(), + } + } + + /// Set the minimum depth of entries yielded by the iterator. + /// + /// The smallest depth is `0` and always corresponds to the path given + /// to the `new` function on this type. Its direct descendents have depth + /// `1`, and their descendents have depth `2`, and so on. + pub fn min_depth(mut self, depth: usize) -> Self { + self.opts.min_depth = depth; + if self.opts.min_depth > self.opts.max_depth { + self.opts.min_depth = self.opts.max_depth; + } + self + } + + /// Set the maximum depth of entries yield by the iterator. + /// + /// The smallest depth is `0` and always corresponds to the path given + /// to the `new` function on this type. Its direct descendents have depth + /// `1`, and their descendents have depth `2`, and so on. + /// + /// Note that this will not simply filter the entries of the iterator, but + /// it will actually avoid descending into directories when the depth is + /// exceeded. + pub fn max_depth(mut self, depth: usize) -> Self { + self.opts.max_depth = depth; + if self.opts.max_depth < self.opts.min_depth { + self.opts.max_depth = self.opts.min_depth; + } + self + } + + /// Follow symbolic links. By default, this is disabled. + /// + /// When `yes` is `true`, symbolic links are followed as if they were + /// normal directories and files. If a symbolic link is broken or is + /// involved in a loop, an error is yielded. + /// + /// When enabled, the yielded [`DirEntry`] values represent the target of + /// the link while the path corresponds to the link. See the [`DirEntry`] + /// type for more details. + /// + /// [`DirEntry`]: struct.DirEntry.html + pub fn follow_links(mut self, yes: bool) -> Self { + self.opts.follow_links = yes; + self + } + + /// Set the maximum number of simultaneously open file descriptors used + /// by the iterator. + /// + /// `n` must be greater than or equal to `1`. If `n` is `0`, then it is set + /// to `1` automatically. If this is not set, then it defaults to some + /// reasonably low number. + /// + /// This setting has no impact on the results yielded by the iterator + /// (even when `n` is `1`). Instead, this setting represents a trade off + /// between scarce resources (file descriptors) and memory. Namely, when + /// the maximum number of file descriptors is reached and a new directory + /// needs to be opened to continue iteration, then a previous directory + /// handle is closed and has its unyielded entries stored in memory. In + /// practice, this is a satisfying trade off because it scales with respect + /// to the *depth* of your file tree. Therefore, low values (even `1`) are + /// acceptable. + /// + /// Note that this value does not impact the number of system calls made by + /// an exhausted iterator. + /// + /// # Platform behavior + /// + /// On Windows, if `follow_links` is enabled, then this limit is not + /// respected. In particular, the maximum number of file descriptors opened + /// is proportional to the depth of the directory tree traversed. + pub fn max_open(mut self, mut n: usize) -> Self { + if n == 0 { + n = 1; + } + self.opts.max_open = n; + self + } + + /// Set a function for sorting directory entries. + /// + /// If a compare function is set, the resulting iterator will return all + /// paths in sorted order. The compare function will be called to compare + /// entries from the same directory. + /// + /// ```rust,no-run + /// use std::cmp; + /// use std::ffi::OsString; + /// use walkdir::WalkDir; + /// + /// WalkDir::new("foo").sort_by(|a,b| a.file_name().cmp(b.file_name())); + /// ``` + pub fn sort_by<F>(mut self, cmp: F) -> Self + where F: FnMut(&DirEntry, &DirEntry) -> Ordering + Send + Sync + 'static + { + self.opts.sorter = Some(Box::new(cmp)); + self + } + + /// Yield a directory's contents before the directory itself. By default, + /// this is disabled. + /// + /// When `yes` is `false` (as is the default), the directory is yielded + /// before its contents are read. This is useful when, e.g. you want to + /// skip processing of some directories. + /// + /// When `yes` is `true`, the iterator yields the contents of a directory + /// before yielding the directory itself. This is useful when, e.g. you + /// want to recursively delete a directory. + /// + /// # Example + /// + /// Assume the following directory tree: + /// + /// ```text + /// foo/ + /// abc/ + /// qrs + /// tuv + /// def/ + /// ``` + /// + /// With contents_first disabled (the default), the following code visits + /// the directory tree in depth-first order: + /// + /// ```no_run + /// use walkdir::WalkDir; + /// + /// for entry in WalkDir::new("foo") { + /// let entry = entry.unwrap(); + /// println!("{}", entry.path().display()); + /// } + /// + /// // foo + /// // foo/abc + /// // foo/abc/qrs + /// // foo/abc/tuv + /// // foo/def + /// ``` + /// + /// With contents_first enabled: + /// + /// ```no_run + /// use walkdir::WalkDir; + /// + /// for entry in WalkDir::new("foo").contents_first(true) { + /// let entry = entry.unwrap(); + /// println!("{}", entry.path().display()); + /// } + /// + /// // foo/abc/qrs + /// // foo/abc/tuv + /// // foo/abc + /// // foo/def + /// // foo + /// ``` + pub fn contents_first(mut self, yes: bool) -> Self { + self.opts.contents_first = yes; + self + } +} + +impl IntoIterator for WalkDir { + type Item = Result<DirEntry>; + type IntoIter = IntoIter; + + fn into_iter(self) -> IntoIter { + IntoIter { + opts: self.opts, + start: Some(self.root), + stack_list: vec![], + stack_path: vec![], + oldest_opened: 0, + depth: 0, + deferred_dirs: vec![], + } + } +} + +/// An iterator for recursively descending into a directory. +/// +/// A value with this type must be constructed with the [`WalkDir`] type, which +/// uses a builder pattern to set options such as min/max depth, max open file +/// descriptors and whether the iterator should follow symbolic links. After +/// constructing a `WalkDir`, call [`.into_iter()`] at the end of the chain. +/// +/// The order of elements yielded by this iterator is unspecified. +/// +/// [`WalkDir`]: struct.WalkDir.html +/// [`.into_iter()`]: struct.WalkDir.html#into_iter.v +#[derive(Debug)] +pub struct IntoIter { + /// Options specified in the builder. Depths, max fds, etc. + opts: WalkDirOptions, + /// The start path. + /// + /// This is only `Some(...)` at the beginning. After the first iteration, + /// this is always `None`. + start: Option<PathBuf>, + /// A stack of open (up to max fd) or closed handles to directories. + /// An open handle is a plain [`fs::ReadDir`] while a closed handle is + /// a `Vec<fs::DirEntry>` corresponding to the as-of-yet consumed entries. + /// + /// [`fs::ReadDir`]: https://doc.rust-lang.org/stable/std/fs/struct.ReadDir.html + stack_list: Vec<DirList>, + /// A stack of file paths. + /// + /// This is *only* used when [`follow_links`] is enabled. In all other + /// cases this stack is empty. + /// + /// [`follow_links`]: struct.WalkDir.html#method.follow_links + stack_path: Vec<Ancestor>, + /// An index into `stack_list` that points to the oldest open directory + /// handle. If the maximum fd limit is reached and a new directory needs to + /// be read, the handle at this index is closed before the new directory is + /// opened. + oldest_opened: usize, + /// The current depth of iteration (the length of the stack at the + /// beginning of each iteration). + depth: usize, + /// A list of DirEntries corresponding to directories, that are + /// yielded after their contents has been fully yielded. This is only + /// used when `contents_first` is enabled. + deferred_dirs: Vec<DirEntry>, +} + +/// An ancestor is an item in the directory tree traversed by walkdir, and is +/// used to check for loops in the tree when traversing symlinks. +#[derive(Debug)] +struct Ancestor { + /// The path of this ancestor. + path: PathBuf, + /// An open file to this ancesor. This is only used on Windows where + /// opening a file handle appears to be quite expensive, so we choose to + /// cache it. This comes at the cost of not respecting the file descriptor + /// limit set by the user. + #[cfg(windows)] + handle: Handle, +} + +impl Ancestor { + /// Create a new ancestor from the given directory path. + #[cfg(windows)] + fn new(dent: &DirEntry) -> io::Result<Ancestor> { + let handle = Handle::from_path(dent.path())?; + Ok(Ancestor { + path: dent.path().to_path_buf(), + handle: handle, + }) + } + + /// Create a new ancestor from the given directory path. + #[cfg(not(windows))] + fn new(dent: &DirEntry) -> io::Result<Ancestor> { + Ok(Ancestor { path: dent.path().to_path_buf() }) + } + + /// Returns true if and only if the given open file handle corresponds to + /// the same directory as this ancestor. + #[cfg(windows)] + fn is_same(&self, child: &Handle) -> io::Result<bool> { + Ok(child == &self.handle) + } + + /// Returns true if and only if the given open file handle corresponds to + /// the same directory as this ancestor. + #[cfg(not(windows))] + fn is_same(&self, child: &Handle) -> io::Result<bool> { + Ok(child == &Handle::from_path(&self.path)?) + } +} + +/// A sequence of unconsumed directory entries. +/// +/// This represents the opened or closed state of a directory handle. When +/// open, future entries are read by iterating over the raw `fs::ReadDir`. +/// When closed, all future entries are read into memory. Iteration then +/// proceeds over a [`Vec<fs::DirEntry>`]. +/// +/// [`fs::ReadDir`]: https://doc.rust-lang.org/stable/std/fs/struct.ReadDir.html +/// [`Vec<fs::DirEntry>`]: https://doc.rust-lang.org/stable/std/vec/struct.Vec.html +#[derive(Debug)] +enum DirList { + /// An opened handle. + /// + /// This includes the depth of the handle itself. + /// + /// If there was an error with the initial [`fs::read_dir`] call, then it + /// is stored here. (We use an [`Option<...>`] to make yielding the error + /// exactly once simpler.) + /// + /// [`fs::read_dir`]: https://doc.rust-lang.org/stable/std/fs/fn.read_dir.html + /// [`Option<...>`]: https://doc.rust-lang.org/stable/std/option/enum.Option.html + Opened { depth: usize, it: result::Result<ReadDir, Option<Error>> }, + /// A closed handle. + /// + /// All remaining directory entries are read into memory. + Closed(vec::IntoIter<Result<DirEntry>>), +} + +/// A directory entry. +/// +/// This is the type of value that is yielded from the iterators defined in +/// this crate. +/// +/// On Unix systems, this type implements the [`DirEntryExt`] trait, which +/// provides efficient access to the inode number of the directory entry. +/// +/// # Differences with `std::fs::DirEntry` +/// +/// This type mostly mirrors the type by the same name in [`std::fs`]. There +/// are some differences however: +/// +/// * All recursive directory iterators must inspect the entry's type. +/// Therefore, the value is stored and its access is guaranteed to be cheap and +/// successful. +/// * [`path`] and [`file_name`] return borrowed variants. +/// * If [`follow_links`] was enabled on the originating iterator, then all +/// operations except for [`path`] operate on the link target. Otherwise, all +/// operations operate on the symbolic link. +/// +/// [`std::fs`]: https://doc.rust-lang.org/stable/std/fs/index.html +/// [`path`]: #method.path +/// [`file_name`]: #method.file_name +/// [`follow_links`]: struct.WalkDir.html#method.follow_links +/// [`DirEntryExt`]: trait.DirEntryExt.html +pub struct DirEntry { + /// The path as reported by the [`fs::ReadDir`] iterator (even if it's a + /// symbolic link). + /// + /// [`fs::ReadDir`]: https://doc.rust-lang.org/stable/std/fs/struct.ReadDir.html + path: PathBuf, + /// The file type. Necessary for recursive iteration, so store it. + ty: FileType, + /// Is set when this entry was created from a symbolic link and the user + /// excepts the iterator to follow symbolic links. + follow_link: bool, + /// The depth at which this entry was generated relative to the root. + depth: usize, + /// The underlying inode number (Unix only). + #[cfg(unix)] + ino: u64, + /// The underlying metadata (Windows only). We store this on Windows + /// because this comes for free while reading a directory. + /// + /// We use this to determine whether an entry is a directory or not, which + /// works around a bug in Rust's standard library: + /// https://github.com/rust-lang/rust/issues/46484 + #[cfg(windows)] + metadata: fs::Metadata, +} + +impl Iterator for IntoIter { + type Item = Result<DirEntry>; + /// Advances the iterator and returns the next value. + /// + /// # Errors + /// + /// If the iterator fails to retrieve the next value, this method returns + /// an error value. The error will be wrapped in an Option::Some. + fn next(&mut self) -> Option<Result<DirEntry>> { + if let Some(start) = self.start.take() { + let dent = itry!(DirEntry::from_link(0, start)); + if let Some(result) = self.handle_entry(dent) { + return Some(result); + } + } + while !self.stack_list.is_empty() { + self.depth = self.stack_list.len(); + if let Some(dentry) = self.get_deferred_dir() { + return Some(Ok(dentry)); + } + if self.depth > self.opts.max_depth { + // If we've exceeded the max depth, pop the current dir + // so that we don't descend. + self.pop(); + continue; + } + // Unwrap is safe here because we've verified above that + // `self.stack_list` is not empty + match self.stack_list.last_mut().expect("bug in walkdir").next() { + None => self.pop(), + Some(Err(err)) => return Some(Err(err)), + Some(Ok(dent)) => { + if let Some(result) = self.handle_entry(dent) { + return Some(result); + } + } + } + } + if self.opts.contents_first { + self.depth = self.stack_list.len(); + if let Some(dentry) = self.get_deferred_dir() { + return Some(Ok(dentry)); + } + } + None + } +} + +impl IntoIter { + /// Skips the current directory. + /// + /// This causes the iterator to stop traversing the contents of the least + /// recently yielded directory. This means any remaining entries in that + /// directory will be skipped (including sub-directories). + /// + /// Note that the ergonomics of this method are questionable since it + /// borrows the iterator mutably. Namely, you must write out the looping + /// condition manually. For example, to skip hidden entries efficiently on + /// unix systems: + /// + /// ```no_run + /// use walkdir::{DirEntry, WalkDir}; + /// + /// fn is_hidden(entry: &DirEntry) -> bool { + /// entry.file_name() + /// .to_str() + /// .map(|s| s.starts_with(".")) + /// .unwrap_or(false) + /// } + /// + /// let mut it = WalkDir::new("foo").into_iter(); + /// loop { + /// let entry = match it.next() { + /// None => break, + /// Some(Err(err)) => panic!("ERROR: {}", err), + /// Some(Ok(entry)) => entry, + /// }; + /// if is_hidden(&entry) { + /// if entry.file_type().is_dir() { + /// it.skip_current_dir(); + /// } + /// continue; + /// } + /// println!("{}", entry.path().display()); + /// } + /// ``` + /// + /// You may find it more convenient to use the [`filter_entry`] iterator + /// adapter. (See its documentation for the same example functionality as + /// above.) + /// + /// [`filter_entry`]: #method.filter_entry + pub fn skip_current_dir(&mut self) { + if !self.stack_list.is_empty() { + self.stack_list.pop(); + } + if !self.stack_path.is_empty() { + self.stack_path.pop(); + } + } + + /// Yields only entries which satisfy the given predicate and skips + /// descending into directories that do not satisfy the given predicate. + /// + /// The predicate is applied to all entries. If the predicate is + /// true, iteration carries on as normal. If the predicate is false, the + /// entry is ignored and if it is a directory, it is not descended into. + /// + /// This is often more convenient to use than [`skip_current_dir`]. For + /// example, to skip hidden files and directories efficiently on unix + /// systems: + /// + /// ```no_run + /// use walkdir::{DirEntry, WalkDir}; + /// # use walkdir::Error; + /// + /// fn is_hidden(entry: &DirEntry) -> bool { + /// entry.file_name() + /// .to_str() + /// .map(|s| s.starts_with(".")) + /// .unwrap_or(false) + /// } + /// + /// # fn try_main() -> Result<(), Error> { + /// for entry in WalkDir::new("foo") + /// .into_iter() + /// .filter_entry(|e| !is_hidden(e)) { + /// println!("{}", entry?.path().display()); + /// } + /// # Ok(()) + /// # } + /// ``` + /// + /// Note that the iterator will still yield errors for reading entries that + /// may not satisfy the predicate. + /// + /// Note that entries skipped with [`min_depth`] and [`max_depth`] are not + /// passed to this predicate. + /// + /// Note that if the iterator has `contents_first` enabled, then this + /// method is no different than calling the standard `Iterator::filter` + /// method (because directory entries are yielded after they've been + /// descended into). + /// + /// [`skip_current_dir`]: #method.skip_current_dir + /// [`min_depth`]: struct.WalkDir.html#method.min_depth + /// [`max_depth`]: struct.WalkDir.html#method.max_depth + pub fn filter_entry<P>(self, predicate: P) -> FilterEntry<Self, P> + where P: FnMut(&DirEntry) -> bool + { + FilterEntry { it: self, predicate: predicate } + } + + fn handle_entry( + &mut self, + mut dent: DirEntry, + ) -> Option<Result<DirEntry>> { + if self.opts.follow_links && dent.file_type().is_symlink() { + dent = itry!(self.follow(dent)); + } + let is_normal_dir = !dent.file_type().is_symlink() && dent.is_dir(); + if is_normal_dir { + itry!(self.push(&dent)); + } + if is_normal_dir && self.opts.contents_first { + self.deferred_dirs.push(dent); + None + } else if self.skippable() { + None + } else { + Some(Ok(dent)) + } + } + + fn get_deferred_dir(&mut self) -> Option<DirEntry> { + if self.opts.contents_first { + if self.depth < self.deferred_dirs.len() { + // Unwrap is safe here because we've guaranteed that + // `self.deferred_dirs.len()` can never be less than 1 + let deferred: DirEntry = self.deferred_dirs.pop() + .expect("bug in walkdir"); + if !self.skippable() { + return Some(deferred); + } + } + } + None + } + + fn push(&mut self, dent: &DirEntry) -> Result<()> { + // Make room for another open file descriptor if we've hit the max. + let free = self.stack_list + .len() + .checked_sub(self.oldest_opened).unwrap(); + if free == self.opts.max_open { + self.stack_list[self.oldest_opened].close(); + // Unwrap is safe here because self.oldest_opened is guaranteed to + // never be greater than `self.stack_list.len()`, which implies + // that the subtraction won't underflow and that adding 1 will + // never overflow. + self.oldest_opened = self.oldest_opened.checked_add(1).unwrap(); + } + // Open a handle to reading the directory's entries. + let rd = fs::read_dir(dent.path()).map_err(|err| { + Some(Error::from_path(self.depth, dent.path().to_path_buf(), err)) + }); + let mut list = DirList::Opened { depth: self.depth, it: rd }; + if let Some(ref mut cmp) = self.opts.sorter { + let mut entries: Vec<_> = list.collect(); + entries.sort_by(|a, b| { + match (a, b) { + (&Ok(ref a), &Ok(ref b)) => { + cmp(a, b) + } + (&Err(_), &Err(_)) => Ordering::Equal, + (&Ok(_), &Err(_)) => Ordering::Greater, + (&Err(_), &Ok(_)) => Ordering::Less, + } + }); + list = DirList::Closed(entries.into_iter()); + } + if self.opts.follow_links { + let ancestor = Ancestor::new(&dent).map_err(|err| { + Error::from_io(self.depth, err) + })?; + self.stack_path.push(ancestor); + } + // We push this after stack_path since creating the Ancestor can fail. + // If it fails, then we return the error and won't descend. + self.stack_list.push(list); + Ok(()) + } + + fn pop(&mut self) { + self.stack_list.pop().expect("cannot pop from empty stack"); + if self.opts.follow_links { + self.stack_path.pop().expect("BUG: list/path stacks out of sync"); + } + // If everything in the stack is already closed, then there is + // room for at least one more open descriptor and it will + // always be at the top of the stack. + self.oldest_opened = min(self.oldest_opened, self.stack_list.len()); + } + + fn follow(&self, mut dent: DirEntry) -> Result<DirEntry> { + dent = DirEntry::from_link(self.depth, dent.path().to_path_buf())?; + // The only way a symlink can cause a loop is if it points + // to a directory. Otherwise, it always points to a leaf + // and we can omit any loop checks. + if dent.is_dir() { + self.check_loop(dent.path())?; + } + Ok(dent) + } + + fn check_loop<P: AsRef<Path>>(&self, child: P) -> Result<()> { + let hchild = Handle::from_path(&child).map_err(|err| { + Error::from_io(self.depth, err) + })?; + for ancestor in self.stack_path.iter().rev() { + let is_same = ancestor.is_same(&hchild).map_err(|err| { + Error::from_io(self.depth, err) + })?; + if is_same { + return Err(Error { + depth: self.depth, + inner: ErrorInner::Loop { + ancestor: ancestor.path.to_path_buf(), + child: child.as_ref().to_path_buf(), + }, + }); + } + } + Ok(()) + } + + fn skippable(&self) -> bool { + self.depth < self.opts.min_depth || self.depth > self.opts.max_depth + } +} + +impl DirList { + fn close(&mut self) { + if let DirList::Opened { .. } = *self { + *self = DirList::Closed(self.collect::<Vec<_>>().into_iter()); + } + } +} + +impl Iterator for DirList { + type Item = Result<DirEntry>; + + #[inline(always)] + fn next(&mut self) -> Option<Result<DirEntry>> { + match *self { + DirList::Closed(ref mut it) => it.next(), + DirList::Opened { depth, ref mut it } => match *it { + Err(ref mut err) => err.take().map(Err), + Ok(ref mut rd) => rd.next().map(|r| match r { + Ok(r) => DirEntry::from_entry(depth + 1, &r), + Err(err) => Err(Error::from_io(depth + 1, err)) + }), + } + } + } +} + +impl DirEntry { + /// The full path that this entry represents. + /// + /// The full path is created by joining the parents of this entry up to the + /// root initially given to [`WalkDir::new`] with the file name of this + /// entry. + /// + /// Note that this *always* returns the path reported by the underlying + /// directory entry, even when symbolic links are followed. To get the + /// target path, use [`path_is_symlink`] to (cheaply) check if this entry + /// corresponds to a symbolic link, and [`std::fs::read_link`] to resolve + /// the target. + /// + /// [`WalkDir::new`]: struct.WalkDir.html#method.new + /// [`path_is_symlink`]: struct.DirEntry.html#method.path_is_symlink + /// [`std::fs::read_link`]: https://doc.rust-lang.org/stable/std/fs/fn.read_link.html + pub fn path(&self) -> &Path { + &self.path + } + + /// Returns `true` if and only if this entry was created from a symbolic + /// link. This is unaffected by the [`follow_links`] setting. + /// + /// When `true`, the value returned by the [`path`] method is a + /// symbolic link name. To get the full target path, you must call + /// [`std::fs::read_link(entry.path())`]. + /// + /// [`path`]: struct.DirEntry.html#method.path + /// [`follow_links`]: struct.WalkDir.html#method.follow_links + /// [`std::fs::read_link(entry.path())`]: https://doc.rust-lang.org/stable/std/fs/fn.read_link.html + pub fn path_is_symlink(&self) -> bool { + self.ty.is_symlink() || self.follow_link + } + + /// Return the metadata for the file that this entry points to. + /// + /// This will follow symbolic links if and only if the [`WalkDir`] value + /// has [`follow_links`] enabled. + /// + /// # Platform behavior + /// + /// This always calls [`std::fs::symlink_metadata`]. + /// + /// If this entry is a symbolic link and [`follow_links`] is enabled, then + /// [`std::fs::metadata`] is called instead. + /// + /// # Errors + /// + /// Similar to [`std::fs::metadata`], returns errors for path values that + /// the program does not have permissions to access or if the path does not + /// exist. + /// + /// [`WalkDir`]: struct.WalkDir.html + /// [`follow_links`]: struct.WalkDir.html#method.follow_links + /// [`std::fs::metadata`]: https://doc.rust-lang.org/std/fs/fn.metadata.html + /// [`std::fs::symlink_metadata`]: https://doc.rust-lang.org/stable/std/fs/fn.symlink_metadata.html + pub fn metadata(&self) -> Result<fs::Metadata> { + self.metadata_internal() + } + + #[cfg(windows)] + fn metadata_internal(&self) -> Result<fs::Metadata> { + if self.follow_link { + fs::metadata(&self.path) + } else { + Ok(self.metadata.clone()) + }.map_err(|err| Error::from_entry(self, err)) + } + + #[cfg(not(windows))] + fn metadata_internal(&self) -> Result<fs::Metadata> { + if self.follow_link { + fs::metadata(&self.path) + } else { + fs::symlink_metadata(&self.path) + }.map_err(|err| Error::from_entry(self, err)) + } + + /// Return the file type for the file that this entry points to. + /// + /// If this is a symbolic link and [`follow_links`] is `true`, then this + /// returns the type of the target. + /// + /// This never makes any system calls. + /// + /// [`follow_links`]: struct.WalkDir.html#method.follow_links + pub fn file_type(&self) -> fs::FileType { + self.ty + } + + /// Return the file name of this entry. + /// + /// If this entry has no file name (e.g., `/`), then the full path is + /// returned. + pub fn file_name(&self) -> &OsStr { + self.path.file_name().unwrap_or_else(|| self.path.as_os_str()) + } + + /// Returns the depth at which this entry was created relative to the root. + /// + /// The smallest depth is `0` and always corresponds to the path given + /// to the `new` function on `WalkDir`. Its direct descendents have depth + /// `1`, and their descendents have depth `2`, and so on. + pub fn depth(&self) -> usize { + self.depth + } + + /// Returns true if and only if this entry points to a directory. + /// + /// This works around a bug in Rust's standard library: + /// https://github.com/rust-lang/rust/issues/46484 + #[cfg(windows)] + fn is_dir(&self) -> bool { + use std::os::windows::fs::MetadataExt; + use winapi::um::winnt::FILE_ATTRIBUTE_DIRECTORY; + self.metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 + } + + /// Returns true if and only if this entry points to a directory. + #[cfg(not(windows))] + fn is_dir(&self) -> bool { + self.ty.is_dir() + } + + #[cfg(windows)] + fn from_entry(depth: usize, ent: &fs::DirEntry) -> Result<DirEntry> { + let path = ent.path(); + let ty = ent.file_type().map_err(|err| { + Error::from_path(depth, path.clone(), err) + })?; + let md = ent.metadata().map_err(|err| { + Error::from_path(depth, path.clone(), err) + })?; + Ok(DirEntry { + path: path, + ty: ty, + follow_link: false, + depth: depth, + metadata: md, + }) + } + + #[cfg(unix)] + fn from_entry(depth: usize, ent: &fs::DirEntry) -> Result<DirEntry> { + use std::os::unix::fs::DirEntryExt; + + let ty = ent.file_type().map_err(|err| { + Error::from_path(depth, ent.path(), err) + })?; + Ok(DirEntry { + path: ent.path(), + ty: ty, + follow_link: false, + depth: depth, + ino: ent.ino(), + }) + } + + #[cfg(not(any(unix, windows)))] + fn from_entry(depth: usize, ent: &fs::DirEntry) -> Result<DirEntry> { + use std::os::unix::fs::DirEntryExt; + + let ty = ent.file_type().map_err(|err| { + Error::from_path(depth, ent.path(), err) + })?; + Ok(DirEntry { + path: ent.path(), + ty: ty, + follow_link: false, + depth: depth, + }) + } + + #[cfg(windows)] + fn from_link(depth: usize, pb: PathBuf) -> Result<DirEntry> { + let md = fs::metadata(&pb).map_err(|err| { + Error::from_path(depth, pb.clone(), err) + })?; + Ok(DirEntry { + path: pb, + ty: md.file_type(), + follow_link: true, + depth: depth, + metadata: md, + }) + } + + #[cfg(unix)] + fn from_link(depth: usize, pb: PathBuf) -> Result<DirEntry> { + use std::os::unix::fs::MetadataExt; + + let md = fs::metadata(&pb).map_err(|err| { + Error::from_path(depth, pb.clone(), err) + })?; + Ok(DirEntry { + path: pb, + ty: md.file_type(), + follow_link: true, + depth: depth, + ino: md.ino(), + }) + } + + #[cfg(not(any(unix, windows)))] + fn from_link(depth: usize, pb: PathBuf) -> Result<DirEntry> { + use std::os::unix::fs::MetadataExt; + + let md = fs::metadata(&pb).map_err(|err| { + Error::from_path(depth, pb.clone(), err) + })?; + Ok(DirEntry { + path: pb, + ty: md.file_type(), + follow_link: true, + depth: depth, + }) + } +} + +impl Clone for DirEntry { + #[cfg(windows)] + fn clone(&self) -> DirEntry { + DirEntry { + path: self.path.clone(), + ty: self.ty, + follow_link: self.follow_link, + depth: self.depth, + metadata: self.metadata.clone(), + } + } + + #[cfg(unix)] + fn clone(&self) -> DirEntry { + DirEntry { + path: self.path.clone(), + ty: self.ty, + follow_link: self.follow_link, + depth: self.depth, + ino: self.ino, + } + } + + #[cfg(not(any(unix, windows)))] + fn clone(&self) -> DirEntry { + DirEntry { + path: self.path.clone(), + ty: self.ty, + follow_link: self.follow_link, + depth: self.depth, + ino: self.ino, + } + } +} + +impl fmt::Debug for DirEntry { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "DirEntry({:?})", self.path) + } +} + +/// A recursive directory iterator that skips entries. +/// +/// Values of this type are created by calling [`.filter_entry()`] on an +/// `IntoIter`, which is formed by calling [`.into_iter()`] on a `WalkDir`. +/// +/// Directories that fail the predicate `P` are skipped. Namely, they are +/// never yielded and never descended into. +/// +/// Entries that are skipped with the [`min_depth`] and [`max_depth`] options +/// are not passed through this filter. +/// +/// If opening a handle to a directory resulted in an error, then it is yielded +/// and no corresponding call to the predicate is made. +/// +/// Type parameter `I` refers to the underlying iterator and `P` refers to the +/// predicate, which is usually `FnMut(&DirEntry) -> bool`. +/// +/// [`.filter_entry()`]: struct.IntoIter.html#method.filter_entry +/// [`.into_iter()`]: struct.WalkDir.html#into_iter.v +/// [`min_depth`]: struct.WalkDir.html#method.min_depth +/// [`max_depth`]: struct.WalkDir.html#method.max_depth +#[derive(Debug)] +pub struct FilterEntry<I, P> { + it: I, + predicate: P, +} + +impl<P> Iterator for FilterEntry<IntoIter, P> +where P: FnMut(&DirEntry) -> bool +{ + type Item = Result<DirEntry>; + + /// Advances the iterator and returns the next value. + /// + /// # Errors + /// + /// If the iterator fails to retrieve the next value, this method returns + /// an error value. The error will be wrapped in an `Option::Some`. + fn next(&mut self) -> Option<Result<DirEntry>> { + loop { + let dent = match self.it.next() { + None => return None, + Some(result) => itry!(result), + }; + if !(self.predicate)(&dent) { + if dent.is_dir() { + self.it.skip_current_dir(); + } + continue; + } + return Some(Ok(dent)); + } + } +} + +impl<P> FilterEntry<IntoIter, P> where P: FnMut(&DirEntry) -> bool { + /// Yields only entries which satisfy the given predicate and skips + /// descending into directories that do not satisfy the given predicate. + /// + /// The predicate is applied to all entries. If the predicate is + /// true, iteration carries on as normal. If the predicate is false, the + /// entry is ignored and if it is a directory, it is not descended into. + /// + /// This is often more convenient to use than [`skip_current_dir`]. For + /// example, to skip hidden files and directories efficiently on unix + /// systems: + /// + /// ```no_run + /// use walkdir::{DirEntry, WalkDir}; + /// # use walkdir::Error; + /// + /// fn is_hidden(entry: &DirEntry) -> bool { + /// entry.file_name() + /// .to_str() + /// .map(|s| s.starts_with(".")) + /// .unwrap_or(false) + /// } + /// + /// # fn try_main() -> Result<(), Error> { + /// for entry in WalkDir::new("foo") + /// .into_iter() + /// .filter_entry(|e| !is_hidden(e)) { + /// println!("{}", entry?.path().display()); + /// } + /// # Ok(()) + /// # } + /// ``` + /// + /// Note that the iterator will still yield errors for reading entries that + /// may not satisfy the predicate. + /// + /// Note that entries skipped with [`min_depth`] and [`max_depth`] are not + /// passed to this predicate. + /// + /// Note that if the iterator has `contents_first` enabled, then this + /// method is no different than calling the standard `Iterator::filter` + /// method (because directory entries are yielded after they've been + /// descended into). + /// + /// [`skip_current_dir`]: #method.skip_current_dir + /// [`min_depth`]: struct.WalkDir.html#method.min_depth + /// [`max_depth`]: struct.WalkDir.html#method.max_depth + pub fn filter_entry(self, predicate: P) -> FilterEntry<Self, P> { + FilterEntry { it: self, predicate: predicate } + } + + /// Skips the current directory. + /// + /// This causes the iterator to stop traversing the contents of the least + /// recently yielded directory. This means any remaining entries in that + /// directory will be skipped (including sub-directories). + /// + /// Note that the ergonomics of this method are questionable since it + /// borrows the iterator mutably. Namely, you must write out the looping + /// condition manually. For example, to skip hidden entries efficiently on + /// unix systems: + /// + /// ```no_run + /// use walkdir::{DirEntry, WalkDir}; + /// + /// fn is_hidden(entry: &DirEntry) -> bool { + /// entry.file_name() + /// .to_str() + /// .map(|s| s.starts_with(".")) + /// .unwrap_or(false) + /// } + /// + /// let mut it = WalkDir::new("foo").into_iter(); + /// loop { + /// let entry = match it.next() { + /// None => break, + /// Some(Err(err)) => panic!("ERROR: {}", err), + /// Some(Ok(entry)) => entry, + /// }; + /// if is_hidden(&entry) { + /// if entry.file_type().is_dir() { + /// it.skip_current_dir(); + /// } + /// continue; + /// } + /// println!("{}", entry.path().display()); + /// } + /// ``` + /// + /// You may find it more convenient to use the [`filter_entry`] iterator + /// adapter. (See its documentation for the same example functionality as + /// above.) + /// + /// [`filter_entry`]: #method.filter_entry + pub fn skip_current_dir(&mut self) { + self.it.skip_current_dir(); + } +} + +/// An error produced by recursively walking a directory. +/// +/// This error type is a light wrapper around [`std::io::Error`]. In +/// particular, it adds the following information: +/// +/// * The depth at which the error occurred in the file tree, relative to the +/// root. +/// * The path, if any, associated with the IO error. +/// * An indication that a loop occurred when following symbolic links. In this +/// case, there is no underlying IO error. +/// +/// To maintain good ergonomics, this type has a +/// [`impl From<Error> for std::io::Error`][impl] defined which preserves the original context. +/// This allows you to use an [`io::Result`] with methods in this crate if you don't care about +/// accessing the underlying error data in a structured form. +/// +/// [`std::io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html +/// [`io::Result`]: https://doc.rust-lang.org/stable/std/io/type.Result.html +/// [impl]: struct.Error.html#impl-From%3CError%3E +#[derive(Debug)] +pub struct Error { + depth: usize, + inner: ErrorInner, +} + +#[derive(Debug)] +enum ErrorInner { + Io { path: Option<PathBuf>, err: io::Error }, + Loop { ancestor: PathBuf, child: PathBuf }, +} + +impl Error { + /// Returns the path associated with this error if one exists. + /// + /// For example, if an error occurred while opening a directory handle, + /// the error will include the path passed to [`std::fs::read_dir`]. + /// + /// [`std::fs::read_dir`]: https://doc.rust-lang.org/stable/std/fs/fn.read_dir.html + pub fn path(&self) -> Option<&Path> { + match self.inner { + ErrorInner::Io { path: None, .. } => None, + ErrorInner::Io { path: Some(ref path), .. } => Some(path), + ErrorInner::Loop { ref child, .. } => Some(child), + } + } + + /// Returns the path at which a cycle was detected. + /// + /// If no cycle was detected, [`None`] is returned. + /// + /// A cycle is detected when a directory entry is equivalent to one of + /// its ancestors. + /// + /// To get the path to the child directory entry in the cycle, use the + /// [`path`] method. + /// + /// [`None`]: https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None + /// [`path`]: struct.Error.html#path + pub fn loop_ancestor(&self) -> Option<&Path> { + match self.inner { + ErrorInner::Loop { ref ancestor, .. } => Some(ancestor), + _ => None, + } + } + + /// Returns the depth at which this error occurred relative to the root. + /// + /// The smallest depth is `0` and always corresponds to the path given to + /// the [`new`] function on [`WalkDir`]. Its direct descendents have depth + /// `1`, and their descendents have depth `2`, and so on. + /// + /// [`new`]: struct.WalkDir.html#method.new + /// [`WalkDir`]: struct.WalkDir.html + pub fn depth(&self) -> usize { + self.depth + } + + /// Inspect the original [`io::Error`] if there is one. + /// + /// [`None`] is returned if the [`Error`] doesn't correspond to an + /// [`io::Error`]. This might happen, for example, when the error was + /// produced because a cycle was found in the directory tree while + /// following symbolic links. + /// + /// This method returns a borrowed value that is bound to the lifetime of the [`Error`]. To + /// obtain an owned value, the [`into_io_error`] can be used instead. + /// + /// > This is the original [`io::Error`] and is _not_ the same as + /// > [`impl From<Error> for std::io::Error`][impl] which contains additional context about the + /// error. + /// + /// # Example + /// + /// ```rust,no-run + /// use std::io; + /// use std::path::Path; + /// + /// use walkdir::WalkDir; + /// + /// for entry in WalkDir::new("foo") { + /// match entry { + /// Ok(entry) => println!("{}", entry.path().display()), + /// Err(err) => { + /// let path = err.path().unwrap_or(Path::new("")).display(); + /// println!("failed to access entry {}", path); + /// if let Some(inner) = err.io_error() { + /// match inner.kind() { + /// io::ErrorKind::InvalidData => { + /// println!( + /// "entry contains invalid data: {}", + /// inner) + /// } + /// io::ErrorKind::PermissionDenied => { + /// println!( + /// "Missing permission to read entry: {}", + /// inner) + /// } + /// _ => { + /// println!( + /// "Unexpected error occurred: {}", + /// inner) + /// } + /// } + /// } + /// } + /// } + /// } + /// ``` + /// + /// [`None`]: https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None + /// [`io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html + /// [`From`]: https://doc.rust-lang.org/stable/std/convert/trait.From.html + /// [`Error`]: struct.Error.html + /// [`into_io_error`]: struct.Error.html#method.into_io_error + /// [impl]: struct.Error.html#impl-From%3CError%3E + pub fn io_error(&self) -> Option<&io::Error> { + match self.inner { + ErrorInner::Io { ref err, .. } => Some(err), + ErrorInner::Loop { .. } => None, + } + } + + /// Similar to [`io_error`] except consumes self to convert to the original + /// [`io::Error`] if one exists. + /// + /// [`io_error`]: struct.Error.html#method.io_error + /// [`io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html + pub fn into_io_error(self) -> Option<io::Error> { + match self.inner { + ErrorInner::Io { err, .. } => Some(err), + ErrorInner::Loop { .. } => None, + } + } + + fn from_path(depth: usize, pb: PathBuf, err: io::Error) -> Self { + Error { + depth: depth, + inner: ErrorInner::Io { path: Some(pb), err: err }, + } + } + + fn from_entry(dent: &DirEntry, err: io::Error) -> Self { + Error { + depth: dent.depth, + inner: ErrorInner::Io { + path: Some(dent.path().to_path_buf()), + err: err, + }, + } + } + + fn from_io(depth: usize, err: io::Error) -> Self { + Error { + depth: depth, + inner: ErrorInner::Io { path: None, err: err }, + } + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + match self.inner { + ErrorInner::Io { ref err, .. } => err.description(), + ErrorInner::Loop { .. } => "file system loop found", + } + } + + fn cause(&self) -> Option<&error::Error> { + match self.inner { + ErrorInner::Io { ref err, .. } => Some(err), + ErrorInner::Loop { .. } => None, + } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.inner { + ErrorInner::Io { path: None, ref err } => { + err.fmt(f) + } + ErrorInner::Io { path: Some(ref path), ref err } => { + write!(f, "IO error for operation on {}: {}", + path.display(), err) + } + ErrorInner::Loop { ref ancestor, ref child } => { + write!(f, "File system loop found: \ + {} points to an ancestor {}", + child.display(), ancestor.display()) + } + } + } +} + +impl From<Error> for io::Error { + /// Convert the [`Error`] to an [`io::Error`], preserving the original [`Error`] as the ["inner + /// error"]. Note that this also makes the display of the error include the context. + /// + /// This is different from [`into_io_error`] which returns the original [`io::Error`]. + /// + /// [`Error`]: struct.Error.html + /// [`io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html + /// ["inner error"]: https://doc.rust-lang.org/std/io/struct.Error.html#method.into_inner + /// [`into_io_error`]: struct.WalkDir.html#method.into_io_error + fn from(walk_err: Error) -> io::Error { + let kind = match walk_err { + Error { inner: ErrorInner::Io { ref err, .. }, .. } => { + err.kind() + } + Error { inner: ErrorInner::Loop { .. }, .. } => { + io::ErrorKind::Other + } + }; + io::Error::new(kind, walk_err) + } +} diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/src/tests.rs cargo-0.26.0/vendor/walkdir-2.1.4/src/tests.rs --- cargo-0.25.0/vendor/walkdir-2.1.4/src/tests.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/src/tests.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,815 @@ +#![cfg_attr(windows, allow(dead_code, unused_imports))] + +use std::cmp; +use std::env; +use std::fs::{self, File}; +use std::io; +use std::path::{Path, PathBuf}; +use std::collections::HashMap; + +use quickcheck::{Arbitrary, Gen, QuickCheck, StdGen}; +use rand::{self, Rng}; + +use super::{DirEntry, WalkDir, IntoIter, Error, ErrorInner}; + +#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] +enum Tree { + Dir(PathBuf, Vec<Tree>), + File(PathBuf), + Symlink { + src: PathBuf, + dst: PathBuf, + dir: bool, + } +} + +impl Tree { + fn from_walk_with<P, F>( + p: P, + f: F, + ) -> io::Result<Tree> + where P: AsRef<Path>, F: FnOnce(WalkDir) -> WalkDir { + let mut stack = vec![Tree::Dir(p.as_ref().to_path_buf(), vec![])]; + let it: WalkEventIter = f(WalkDir::new(p)).into(); + for ev in it { + match try!(ev) { + WalkEvent::Exit => { + let tree = stack.pop().unwrap(); + if stack.is_empty() { + return Ok(tree); + } + stack.last_mut().unwrap().children_mut().push(tree); + } + WalkEvent::Dir(dent) => { + stack.push(Tree::Dir(pb(dent.file_name()), vec![])); + } + WalkEvent::File(dent) => { + let node = if dent.file_type().is_symlink() { + let src = try!(dent.path().read_link()); + let dst = pb(dent.file_name()); + let dir = dent.path().is_dir(); + Tree::Symlink { src: src, dst: dst, dir: dir } + } else { + Tree::File(pb(dent.file_name())) + }; + stack.last_mut().unwrap().children_mut().push(node); + } + } + } + assert_eq!(stack.len(), 1); + Ok(stack.pop().unwrap()) + } + + fn from_walk_with_contents_first<P, F>( + p: P, + f: F, + ) -> io::Result<Tree> + where P: AsRef<Path>, F: FnOnce(WalkDir) -> WalkDir { + let mut contents_of_dir_at_depth = HashMap::new(); + let mut min_depth = ::std::usize::MAX; + let top_level_path = p.as_ref().to_path_buf(); + for result in f(WalkDir::new(p).contents_first(true)) { + let dentry = try!(result); + + let tree = + if dentry.file_type().is_dir() { + let any_contents = contents_of_dir_at_depth.remove( + &(dentry.depth+1)); + Tree::Dir(pb(dentry.file_name()), any_contents.unwrap_or_default()) + } else { + if dentry.file_type().is_symlink() { + let src = try!(dentry.path().read_link()); + let dst = pb(dentry.file_name()); + let dir = dentry.path().is_dir(); + Tree::Symlink { src: src, dst: dst, dir: dir } + } else { + Tree::File(pb(dentry.file_name())) + } + }; + contents_of_dir_at_depth.entry( + dentry.depth).or_insert(vec!()).push(tree); + min_depth = cmp::min(min_depth, dentry.depth); + } + Ok(Tree::Dir(top_level_path, + contents_of_dir_at_depth.remove(&min_depth) + .unwrap_or_default())) + } + + fn name(&self) -> &Path { + match *self { + Tree::Dir(ref pb, _) => pb, + Tree::File(ref pb) => pb, + Tree::Symlink { ref dst, .. } => dst, + } + } + + fn unwrap_singleton(self) -> Tree { + match self { + Tree::File(_) | Tree::Symlink { .. } => { + panic!("cannot unwrap file or link as dir"); + } + Tree::Dir(_, mut childs) => { + assert_eq!(childs.len(), 1); + childs.pop().unwrap() + } + } + } + + fn unwrap_dir(self) -> Vec<Tree> { + match self { + Tree::File(_) | Tree::Symlink { .. } => { + panic!("cannot unwrap file as dir"); + } + Tree::Dir(_, childs) => childs, + } + } + + fn children_mut(&mut self) -> &mut Vec<Tree> { + match *self { + Tree::File(_) | Tree::Symlink { .. } => { + panic!("files do not have children"); + } + Tree::Dir(_, ref mut children) => children, + } + } + + fn create_in<P: AsRef<Path>>(&self, parent: P) -> io::Result<()> { + let parent = parent.as_ref(); + match *self { + Tree::Symlink { ref src, ref dst, dir } => { + if dir { + try!(soft_link_dir(src, parent.join(dst))); + } else { + try!(soft_link_file(src, parent.join(dst))); + } + } + Tree::File(ref p) => { try!(File::create(parent.join(p))); } + Tree::Dir(ref dir, ref children) => { + try!(fs::create_dir(parent.join(dir))); + for child in children { + try!(child.create_in(parent.join(dir))); + } + } + } + Ok(()) + } + + fn canonical(&self) -> Tree { + match *self { + Tree::Symlink { ref src, ref dst, dir } => { + Tree::Symlink { src: src.clone(), dst: dst.clone(), dir: dir } + } + Tree::File(ref p) => { + Tree::File(p.clone()) + } + Tree::Dir(ref p, ref cs) => { + let mut cs: Vec<Tree> = + cs.iter().map(|c| c.canonical()).collect(); + cs.sort(); + Tree::Dir(p.clone(), cs) + } + } + } + + fn dedup(&self) -> Tree { + match *self { + Tree::Symlink { ref src, ref dst, dir } => { + Tree::Symlink { src: src.clone(), dst: dst.clone(), dir: dir } + } + Tree::File(ref p) => { + Tree::File(p.clone()) + } + Tree::Dir(ref p, ref cs) => { + let mut nodupes: Vec<Tree> = vec![]; + for (i, c1) in cs.iter().enumerate() { + if !cs[i+1..].iter().any(|c2| c1.name() == c2.name()) + && !nodupes.iter().any(|c2| c1.name() == c2.name()) { + nodupes.push(c1.dedup()); + } + } + Tree::Dir(p.clone(), nodupes) + } + } + } + + fn gen<G: Gen>(g: &mut G, depth: usize) -> Tree { + #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] + struct NonEmptyAscii(String); + + impl Arbitrary for NonEmptyAscii { + fn arbitrary<G: Gen>(g: &mut G) -> NonEmptyAscii { + use std::char::from_u32; + let upper_bound = g.size(); + // We start with a lower bound of `4` to avoid + // generating the special file name `con` on Windows, + // because such files cannot exist... + let size = g.gen_range(4, upper_bound); + NonEmptyAscii((0..size) + .map(|_| from_u32(g.gen_range(97, 123)).unwrap()) + .collect()) + } + + fn shrink(&self) -> Box<Iterator<Item=NonEmptyAscii>> { + let mut smaller = vec![]; + for i in 1..self.0.len() { + let s: String = self.0.chars().skip(i).collect(); + smaller.push(NonEmptyAscii(s)); + } + Box::new(smaller.into_iter()) + } + } + + let name = pb(NonEmptyAscii::arbitrary(g).0); + if depth == 0 { + Tree::File(name) + } else { + let children: Vec<Tree> = + (0..g.gen_range(0, 5)) + .map(|_| Tree::gen(g, depth-1)) + .collect(); + Tree::Dir(name, children) + } + } +} + +impl Arbitrary for Tree { + fn arbitrary<G: Gen>(g: &mut G) -> Tree { + let depth = g.gen_range(0, 5); + Tree::gen(g, depth).dedup() + } + + fn shrink(&self) -> Box<Iterator<Item=Tree>> { + let trees: Box<Iterator<Item=Tree>> = match *self { + Tree::Symlink { .. } => unimplemented!(), + Tree::File(ref path) => { + let s = path.to_string_lossy().into_owned(); + Box::new(s.shrink().map(|s| Tree::File(pb(s)))) + } + Tree::Dir(ref path, ref children) => { + let s = path.to_string_lossy().into_owned(); + if children.is_empty() { + Box::new(s.shrink().map(|s| Tree::Dir(pb(s), vec![]))) + } else if children.len() == 1 { + let c = &children[0]; + Box::new(Some(c.clone()).into_iter().chain(c.shrink())) + } else { + Box::new(children + .shrink() + .map(move |cs| Tree::Dir(pb(s.clone()), cs))) + } + } + }; + Box::new(trees.map(|t| t.dedup())) + } +} + +#[derive(Debug)] +enum WalkEvent { + Dir(DirEntry), + File(DirEntry), + Exit, +} + +struct WalkEventIter { + depth: usize, + it: IntoIter, + next: Option<Result<DirEntry, Error>>, +} + +impl From<WalkDir> for WalkEventIter { + fn from(it: WalkDir) -> WalkEventIter { + WalkEventIter { depth: 0, it: it.into_iter(), next: None } + } +} + +impl Iterator for WalkEventIter { + type Item = io::Result<WalkEvent>; + + fn next(&mut self) -> Option<io::Result<WalkEvent>> { + let dent = self.next.take().or_else(|| self.it.next()); + let depth = match dent { + None => 0, + Some(Ok(ref dent)) => dent.depth(), + Some(Err(ref err)) => err.depth(), + }; + if depth < self.depth { + self.depth -= 1; + self.next = dent; + return Some(Ok(WalkEvent::Exit)); + } + self.depth = depth; + match dent { + None => None, + Some(Err(err)) => Some(Err(From::from(err))), + Some(Ok(dent)) => { + if dent.file_type().is_dir() { + self.depth += 1; + Some(Ok(WalkEvent::Dir(dent))) + } else { + Some(Ok(WalkEvent::File(dent))) + } + } + } + } +} + +struct TempDir(PathBuf); + +impl TempDir { + fn path<'a>(&'a self) -> &'a Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } +} + +fn tmpdir() -> TempDir { + let p = env::temp_dir(); + let mut r = rand::thread_rng(); + let ret = p.join(&format!("rust-{}", r.next_u32())); + fs::create_dir(&ret).unwrap(); + TempDir(ret) +} + +fn dir_setup_with<F>(t: &Tree, f: F) -> (TempDir, Tree) + where F: Fn(WalkDir) -> WalkDir { + let tmp = tmpdir(); + t.create_in(tmp.path()).unwrap(); + let got = Tree::from_walk_with(tmp.path(), &f).unwrap(); + let got_cf = Tree::from_walk_with_contents_first(tmp.path(), &f).unwrap(); + assert_eq!(got, got_cf); + + (tmp, got.unwrap_singleton().unwrap_singleton()) +} + +fn dir_setup(t: &Tree) -> (TempDir, Tree) { + dir_setup_with(t, |wd| wd) +} + +fn canon(unix: &str) -> String { + if cfg!(windows) { + unix.replace("/", "\\") + } else { + unix.to_string() + } +} + +fn pb<P: AsRef<Path>>(p: P) -> PathBuf { p.as_ref().to_path_buf() } +fn td<P: AsRef<Path>>(p: P, cs: Vec<Tree>) -> Tree { + Tree::Dir(pb(p), cs) +} +fn tf<P: AsRef<Path>>(p: P) -> Tree { + Tree::File(pb(p)) +} +fn tld<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> Tree { + Tree::Symlink { src: pb(src), dst: pb(dst), dir: true } +} +fn tlf<P: AsRef<Path>, Q: AsRef<Path>>(src: P, dst: Q) -> Tree { + Tree::Symlink { src: pb(src), dst: pb(dst), dir: false } +} + +#[cfg(unix)] +fn soft_link_dir<P: AsRef<Path>, Q: AsRef<Path>>( + src: P, + dst: Q, +) -> io::Result<()> { + use std::os::unix::fs::symlink; + symlink(src, dst) +} + +#[cfg(unix)] +fn soft_link_file<P: AsRef<Path>, Q: AsRef<Path>>( + src: P, + dst: Q, +) -> io::Result<()> { + soft_link_dir(src, dst) +} + +#[cfg(windows)] +fn soft_link_dir<P: AsRef<Path>, Q: AsRef<Path>>( + src: P, + dst: Q, +) -> io::Result<()> { + use std::os::windows::fs::symlink_dir; + symlink_dir(src, dst) +} + +#[cfg(windows)] +fn soft_link_file<P: AsRef<Path>, Q: AsRef<Path>>( + src: P, + dst: Q, +) -> io::Result<()> { + use std::os::windows::fs::symlink_file; + symlink_file(src, dst) +} + +macro_rules! assert_tree_eq { + ($e1:expr, $e2:expr) => { + assert_eq!($e1.canonical(), $e2.canonical()); + } +} + +#[test] +fn walk_dir_1() { + let exp = td("foo", vec![]); + let (_tmp, got) = dir_setup(&exp); + assert_tree_eq!(exp, got); +} + +#[test] +fn walk_dir_2() { + let exp = tf("foo"); + let (_tmp, got) = dir_setup(&exp); + assert_tree_eq!(exp, got); +} + +#[test] +fn walk_dir_3() { + let exp = td("foo", vec![tf("bar")]); + let (_tmp, got) = dir_setup(&exp); + assert_tree_eq!(exp, got); +} + +#[test] +fn walk_dir_4() { + let exp = td("foo", vec![tf("foo"), tf("bar"), tf("baz")]); + let (_tmp, got) = dir_setup(&exp); + assert_tree_eq!(exp, got); +} + +#[test] +fn walk_dir_5() { + let exp = td("foo", vec![td("bar", vec![])]); + let (_tmp, got) = dir_setup(&exp); + assert_tree_eq!(exp, got); +} + +#[test] +fn walk_dir_6() { + let exp = td("foo", vec![ + td("bar", vec![ + tf("baz"), td("bat", vec![]), + ]), + ]); + let (_tmp, got) = dir_setup(&exp); + assert_tree_eq!(exp, got); +} + +#[test] +fn walk_dir_7() { + let exp = td("foo", vec![ + td("bar", vec![ + tf("baz"), td("bat", vec![]), + ]), + td("a", vec![tf("b"), tf("c"), tf("d")]), + ]); + let (_tmp, got) = dir_setup(&exp); + assert_tree_eq!(exp, got); +} + +#[test] +fn walk_dir_sym_1() { + let exp = td("foo", vec![tf("bar"), tlf("bar", "baz")]); + let (_tmp, got) = dir_setup(&exp); + assert_tree_eq!(exp, got); +} + +#[test] +fn walk_dir_sym_2() { + let exp = td("foo", vec![ + td("a", vec![tf("a1"), tf("a2")]), + tld("a", "alink"), + ]); + let (_tmp, got) = dir_setup(&exp); + assert_tree_eq!(exp, got); +} + +#[test] +fn walk_dir_sym_root() { + let exp = td("foo", vec![ + td("bar", vec![tf("a"), tf("b")]), + tld("bar", "alink"), + ]); + let tmp = tmpdir(); + let tmp_path = tmp.path(); + let tmp_len = tmp_path.to_str().unwrap().len(); + exp.create_in(tmp_path).unwrap(); + + let it = WalkDir::new(tmp_path.join("foo").join("alink")).into_iter(); + let mut got = it + .map(|d| d.unwrap().path().to_str().unwrap()[tmp_len+1..].into()) + .collect::<Vec<String>>(); + got.sort(); + assert_eq!(got, vec![ + canon("foo/alink"), canon("foo/alink/a"), canon("foo/alink/b"), + ]); + + let it = WalkDir::new(tmp_path.join("foo/alink/")).into_iter(); + let mut got = it + .map(|d| d.unwrap().path().to_str().unwrap()[tmp_len+1..].into()) + .collect::<Vec<String>>(); + got.sort(); + assert_eq!(got, vec!["foo/alink/", "foo/alink/a", "foo/alink/b"]); +} + +#[test] +#[cfg(unix)] +fn walk_dir_sym_detect_no_follow_no_loop() { + let exp = td("foo", vec![ + td("a", vec![tf("a1"), tf("a2")]), + td("b", vec![tld("../a", "alink")]), + ]); + let (_tmp, got) = dir_setup(&exp); + assert_tree_eq!(exp, got); +} + +#[test] +#[cfg(unix)] +fn walk_dir_sym_follow_dir() { + let actual = td("foo", vec![ + td("a", vec![tf("a1"), tf("a2")]), + td("b", vec![tld("../a", "alink")]), + ]); + let followed = td("foo", vec![ + td("a", vec![tf("a1"), tf("a2")]), + td("b", vec![td("alink", vec![tf("a1"), tf("a2")])]), + ]); + let (_tmp, got) = dir_setup_with(&actual, |wd| wd.follow_links(true)); + assert_tree_eq!(followed, got); +} + +#[test] +#[cfg(unix)] +fn walk_dir_sym_detect_loop() { + let actual = td("foo", vec![ + td("a", vec![tlf("../b", "blink"), tf("a1"), tf("a2")]), + td("b", vec![tlf("../a", "alink")]), + ]); + let tmp = tmpdir(); + actual.create_in(tmp.path()).unwrap(); + let got = WalkDir::new(tmp.path()) + .follow_links(true) + .into_iter() + .collect::<Result<Vec<_>, _>>(); + match got { + Ok(x) => panic!("expected loop error, got no error: {:?}", x), + Err(err @ Error { inner: ErrorInner::Io { .. }, .. }) => { + panic!("expected loop error, got generic IO error: {:?}", err); + } + Err(Error { inner: ErrorInner::Loop { .. }, .. }) => {} + } +} + +#[test] +fn walk_dir_sym_infinite() { + let actual = tlf("a", "a"); + let tmp = tmpdir(); + actual.create_in(tmp.path()).unwrap(); + let got = WalkDir::new(tmp.path()) + .follow_links(true) + .into_iter() + .collect::<Result<Vec<_>, _>>(); + match got { + Ok(x) => panic!("expected IO error, got no error: {:?}", x), + Err(Error { inner: ErrorInner::Loop { .. }, .. }) => { + panic!("expected IO error, but got loop error"); + } + Err(Error { inner: ErrorInner::Io { .. }, .. }) => {} + } +} + +#[test] +fn walk_dir_min_depth_1() { + let exp = td("foo", vec![tf("bar")]); + let (_tmp, got) = dir_setup_with(&exp, |wd| wd.min_depth(1)); + assert_tree_eq!(tf("bar"), got); +} + +#[test] +fn walk_dir_min_depth_2() { + let exp = td("foo", vec![tf("bar"), tf("baz")]); + let tmp = tmpdir(); + exp.create_in(tmp.path()).unwrap(); + let got = Tree::from_walk_with(tmp.path(), |wd| wd.min_depth(2)) + .unwrap().unwrap_dir(); + let got_cf = Tree::from_walk_with_contents_first( + tmp.path(), |wd| wd.min_depth(2)) + .unwrap().unwrap_dir(); + assert_eq!(got, got_cf); + assert_tree_eq!(exp, td("foo", got)); +} + +#[test] +fn walk_dir_min_depth_3() { + let exp = td("foo", vec![ + tf("bar"), + td("abc", vec![tf("xyz")]), + tf("baz"), + ]); + let tmp = tmpdir(); + exp.create_in(tmp.path()).unwrap(); + let got = Tree::from_walk_with(tmp.path(), |wd| wd.min_depth(3)) + .unwrap().unwrap_dir(); + assert_eq!(vec![tf("xyz")], got); + let got_cf = Tree::from_walk_with_contents_first( + tmp.path(), |wd| wd.min_depth(3)) + .unwrap().unwrap_dir(); + assert_eq!(got, got_cf); +} + +#[test] +fn walk_dir_max_depth_1() { + let exp = td("foo", vec![tf("bar")]); + let (_tmp, got) = dir_setup_with(&exp, |wd| wd.max_depth(1)); + assert_tree_eq!(td("foo", vec![]), got); +} + +#[test] +fn walk_dir_max_depth_2() { + let exp = td("foo", vec![tf("bar"), tf("baz")]); + let (_tmp, got) = dir_setup_with(&exp, |wd| wd.max_depth(1)); + assert_tree_eq!(td("foo", vec![]), got); +} + +#[test] +fn walk_dir_max_depth_3() { + let exp = td("foo", vec![ + tf("bar"), + td("abc", vec![tf("xyz")]), + tf("baz"), + ]); + let exp_trimmed = td("foo", vec![ + tf("bar"), + td("abc", vec![]), + tf("baz"), + ]); + let (_tmp, got) = dir_setup_with(&exp, |wd| wd.max_depth(2)); + assert_tree_eq!(exp_trimmed, got); +} + +#[test] +fn walk_dir_min_max_depth() { + let exp = td("foo", vec![ + tf("bar"), + td("abc", vec![tf("xyz")]), + tf("baz"), + ]); + let tmp = tmpdir(); + exp.create_in(tmp.path()).unwrap(); + let got = Tree::from_walk_with(tmp.path(), + |wd| wd.min_depth(2).max_depth(2)) + .unwrap().unwrap_dir(); + let got_cf = Tree::from_walk_with_contents_first(tmp.path(), + |wd| wd.min_depth(2).max_depth(2)) + .unwrap().unwrap_dir(); + assert_eq!(got, got_cf); + assert_tree_eq!( + td("foo", vec![tf("bar"), td("abc", vec![]), tf("baz")]), + td("foo", got)); +} + +#[test] +fn walk_dir_skip() { + let exp = td("foo", vec![ + tf("bar"), + td("abc", vec![tf("xyz")]), + tf("baz"), + ]); + let tmp = tmpdir(); + exp.create_in(tmp.path()).unwrap(); + let mut got = vec![]; + let mut it = WalkDir::new(tmp.path()).min_depth(1).into_iter(); + loop { + let dent = match it.next().map(|x| x.unwrap()) { + None => break, + Some(dent) => dent, + }; + let name = dent.file_name().to_str().unwrap().to_owned(); + if name == "abc" { + it.skip_current_dir(); + } + got.push(name); + } + got.sort(); + assert_eq!(got, vec!["abc", "bar", "baz", "foo"]); // missing xyz! +} + +#[test] +fn walk_dir_filter() { + let exp = td("foo", vec![ + tf("bar"), + td("abc", vec![tf("fit")]), + tf("faz"), + ]); + let tmp = tmpdir(); + let tmp_path = tmp.path().to_path_buf(); + exp.create_in(tmp.path()).unwrap(); + let it = WalkDir::new(tmp.path()).min_depth(1) + .into_iter() + .filter_entry(move |d| { + let n = d.file_name().to_string_lossy().into_owned(); + !d.file_type().is_dir() + || n.starts_with("f") + || d.path() == &*tmp_path + }); + let mut got = it.map(|d| d.unwrap().file_name().to_str().unwrap().into()) + .collect::<Vec<String>>(); + got.sort(); + assert_eq!(got, vec!["bar", "faz", "foo"]); +} + +#[test] +fn qc_roundtrip() { + fn p(exp: Tree) -> bool { + let (_tmp, got) = dir_setup(&exp); + exp.canonical() == got.canonical() + } + QuickCheck::new() + .gen(StdGen::new(rand::thread_rng(), 15)) + .tests(1_000) + .max_tests(10_000) + .quickcheck(p as fn(Tree) -> bool); +} + +// Same as `qc_roundtrip`, but makes sure `follow_links` doesn't change +// the behavior of walking a directory *without* symlinks. +#[test] +fn qc_roundtrip_no_symlinks_with_follow() { + fn p(exp: Tree) -> bool { + let (_tmp, got) = dir_setup_with(&exp, |wd| wd.follow_links(true)); + exp.canonical() == got.canonical() + } + QuickCheck::new() + .gen(StdGen::new(rand::thread_rng(), 15)) + .tests(1_000) + .max_tests(10_000) + .quickcheck(p as fn(Tree) -> bool); +} + +#[test] +fn walk_dir_sort() { + let exp = td("foo", vec![ + tf("bar"), + td("abc", vec![tf("fit")]), + tf("faz"), + ]); + let tmp = tmpdir(); + let tmp_path = tmp.path(); + let tmp_len = tmp_path.to_str().unwrap().len(); + exp.create_in(tmp_path).unwrap(); + let it = WalkDir::new(tmp_path) + .sort_by(|a,b| a.file_name().cmp(b.file_name())) + .into_iter(); + let got = it.map(|d| { + let path = d.unwrap(); + let path = &path.path().to_str().unwrap()[tmp_len..]; + path.replace("\\", "/") + }).collect::<Vec<String>>(); + assert_eq!( + got, + ["", "/foo", "/foo/abc", "/foo/abc/fit", "/foo/bar", "/foo/faz"]); +} + +#[test] +fn walk_dir_sort_small_fd_max() { + let exp = td("foo", vec![ + tf("bar"), + td("abc", vec![tf("fit")]), + tf("faz"), + ]); + let tmp = tmpdir(); + let tmp_path = tmp.path(); + let tmp_len = tmp_path.to_str().unwrap().len(); + exp.create_in(tmp_path).unwrap(); + let it = WalkDir::new(tmp_path) + .max_open(1) + .sort_by(|a,b| a.file_name().cmp(b.file_name())) + .into_iter(); + let got = it.map(|d| { + let path = d.unwrap(); + let path = &path.path().to_str().unwrap()[tmp_len..]; + path.replace("\\", "/") + }).collect::<Vec<String>>(); + assert_eq!( + got, + ["", "/foo", "/foo/abc", "/foo/abc/fit", "/foo/bar", "/foo/faz"]); +} + +#[test] +fn walk_dir_send_sync_traits() { + use FilterEntry; + + fn assert_send<T: Send>() {} + fn assert_sync<T: Sync>() {} + + assert_send::<WalkDir>(); + assert_sync::<WalkDir>(); + assert_send::<IntoIter>(); + assert_sync::<IntoIter>(); + assert_send::<FilterEntry<IntoIter, u8>>(); + assert_sync::<FilterEntry<IntoIter, u8>>(); +} diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/src/unix.rs cargo-0.26.0/vendor/walkdir-2.1.4/src/unix.rs --- cargo-0.25.0/vendor/walkdir-2.1.4/src/unix.rs 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/src/unix.rs 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,16 @@ +use DirEntry; + +/// Unix-specific extension methods for `walkdir::DirEntry` +pub trait DirEntryExt { + /// Returns the underlying `d_ino` field in the contained `dirent` + /// structure. + fn ino(&self) -> u64; +} + +impl DirEntryExt for DirEntry { + /// Returns the underlying `d_ino` field in the contained `dirent` + /// structure. + fn ino(&self) -> u64 { + self.ino + } +} diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/.travis.yml cargo-0.26.0/vendor/walkdir-2.1.4/.travis.yml --- cargo-0.25.0/vendor/walkdir-2.1.4/.travis.yml 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/.travis.yml 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,20 @@ +language: rust +matrix: + include: + - os: linux + rust: 1.17.0 + - os: linux + rust: stable + - os: linux + rust: beta + - os: linux + rust: nightly + - os: osx + rust: nightly +script: + - cargo build --verbose + - cargo test --verbose + - cargo doc +branches: + only: + - master diff -Nru cargo-0.25.0/vendor/walkdir-2.1.4/UNLICENSE cargo-0.26.0/vendor/walkdir-2.1.4/UNLICENSE --- cargo-0.25.0/vendor/walkdir-2.1.4/UNLICENSE 1970-01-01 00:00:00.000000000 +0000 +++ cargo-0.26.0/vendor/walkdir-2.1.4/UNLICENSE 2018-04-13 17:48:48.000000000 +0000 @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +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 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. + +For more information, please refer to <http://unlicense.org/>